[
  {
    "path": ".github/workflows/prebuilt_quickjs.yml",
    "content": "name: prebuilt_quickjs\n\non: \n  push:\n    paths: \n      - jsb_build/quickjs/quickjs-latest/quickjs.c\n      - jsb_build/quickjs/quickjs-latest/quickjs.h\n      - jsb_build/quickjs/unity_qjs.c\n      - jsb_build/quickjs/unity_ext.c\n      - jsb_build/quickjs/CMakeLists.txt\n      - jsb_build/quickjs/make_jsb_android.sh\n      - jsb_build/quickjs/make_jsb_ios.sh\n      - jsb_build/quickjs/make_jsb_macos.sh\n      - jsb_build/quickjs/make_jsb_win.sh\n      - jsb_build/quickjs/make_jsb_wsa.bat\n      - jsb_build/quickjs/make_jsb_linux.sh\n      - .github/workflows/prebuilt_quickjs.yml\n\njobs:\n  android:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - uses: lukka/get-cmake@v3.19.0\n      - name: Install android-ndk\n        run: |\n          cd ~\n          wget -O android-ndk -q https://dl.google.com/android/repository/android-ndk-r23b-linux.zip\n          sudo apt install unzip -y\n          unzip -q android-ndk\n          export ANDROID_NDK=~/android-ndk-r23b\n      - name: Build\n        run: |\n          echo $ANDROID_NDK\n          cd jsb_build/quickjs\n          chmod 744 make_jsb_android.sh\n          ./make_jsb_android.sh\n      - name: Upload\n        uses: actions/upload-artifact@v2\n        with:\n          path: ./jsb_build/prebuilt/Plugins/**/*\n          name: prebuilt_quickjs_libs\n\n  wsa:\n    runs-on: windows-latest\n    steps:\n      - uses: actions/checkout@v2\n      - name: Add MSBuild to PATH\n        uses: microsoft/setup-msbuild@v1.0.2\n      - name: Build\n        run: |\n          cd jsb_build\\quickjs\n          .\\make_jsb_wsa.bat\n      - name: Upload\n        uses: actions/upload-artifact@v2\n        with:\n          path: ./jsb_build/prebuilt/Plugins/**/*\n          name: prebuilt_quickjs_libs\n\n  windows:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - uses: lukka/get-cmake@v3.19.0\n      - name: Build\n        run: |\n          sudo apt install mingw-w64\n          cd jsb_build/quickjs\n          chmod 744 make_jsb_win.sh\n          ./make_jsb_win.sh\n      - name: Upload\n        uses: actions/upload-artifact@v2\n        with:\n          path: ./jsb_build/prebuilt/Plugins/**/*\n          name: prebuilt_quickjs_libs\n\n  linux:\n    runs-on: ubuntu-18.04\n    steps:\n      - uses: actions/checkout@v2\n      - uses: lukka/get-cmake@v3.19.0\n      - name: Build\n        run: |\n          sudo apt install g++\n          cd jsb_build/quickjs\n          chmod 744 make_jsb_linux.sh\n          ./make_jsb_linux.sh\n      - name: Upload\n        uses: actions/upload-artifact@v2\n        with:\n          path: ./jsb_build/prebuilt/Plugins/**/*\n          name: prebuilt_quickjs_libs\n\n  ios:\n    runs-on: macos-latest\n    steps:\n      - uses: actions/checkout@v2\n      - uses: lukka/get-cmake@v3.19.0\n      - name: Build\n        run: |\n          cd jsb_build/quickjs\n          sh ./make_jsb_ios.sh\n      - name: Upload\n        uses: actions/upload-artifact@v2\n        with:\n          path: ./jsb_build/prebuilt/Plugins/**/*\n          name: prebuilt_quickjs_libs\n  osx:\n    runs-on: macos-latest\n    steps:\n      - uses: actions/checkout@v2\n      - uses: lukka/get-cmake@v3.19.0\n      - name: Build\n        run: |\n          cd jsb_build/quickjs\n          sh ./make_jsb_macos.sh\n      - name: Upload\n        uses: actions/upload-artifact@v2\n        with:\n          path: ./jsb_build/prebuilt/Plugins/**/*\n          name: prebuilt_quickjs_libs\n"
  },
  {
    "path": ".github/workflows/split_upm.yml",
    "content": "name: split_upm\n\non: \n  push:\n    paths: \n      - Packages/cc.starlessnight.unity-jsb/package.json\n      - .github/workflows/upm.yml\n\njobs:\n  split-upm:\n      name: split upm branch\n      runs-on: ubuntu-latest\n      steps:\n        - uses: actions/checkout@v2\n          with: \n            fetch-depth: 0\n        - name: split upm branch\n          run: |\n            git subtree split -P \"Packages/cc.starlessnight.unity-jsb\" -b upm\n            git push -u origin upm\n            \n"
  },
  {
    "path": ".gitignore",
    "content": "/[Ll]ibrary/\n/[Tt]emp/\n/[Oo]bj/\n/[Ll]ogs/\n/[Bb]uild/\n/[Bb]uilds/\n/Assets/AssetStoreTools*\n\n# Visual Studio cache directory\n.vs/\n\n# Autogenerated VS/MD/Consulo solution and project files\n/ExportedObj/\n/.consulo/\n/*.csproj\n/*.unityproj\n/*.sln\n/*.suo\n/*.tmp\n/*.user\n/*.userprefs\n/*.pidb\n/*.booproj\n/*.svd\n/*.pdb\n/*.opendb\n/jsb_build/dotnetcore/bin/\n/jsb_build/dotnetcore/Logs/\n/jsb_build/dotnetcore/obj/\n/jsb_build/codegen/obj/\n\n# Unity3D generated meta files\n/*.pidb.meta\n/*.pdb.meta\n\n# Unity3D Generated File On Crash Reports\n/sysinfo.txt\n\n# Builds\n/*.apk\n/*.unitypackage\n\n/.idea\n\n/Assets/Generated/*\n# /Assets/Generated.meta\n!/Assets/Generated/Typings\n!/Assets/Generated/Typings.meta\n/Assets/Examples/Scripts/dist\n/Assets/Examples/Scripts/dist.meta\n/Assets/Resources\n/Assets/Resources.meta\n\n/jsb_build/out\n/jsb_build/quickjs/quickjs*/.obj\n/jsb_build/quickjs/quickjs*/repl.c\n/jsb_build/quickjs/quickjs*/host-qjsc\n/jsb_build/quickjs/quickjs*/qjsc\n/jsb_build/quickjs/quickjs*/qjs\n/jsb_build/quickjs/quickjs*/qjsbnc\n/jsb_build/quickjs/quickjs*/qjsbn\n/jsb_build/quickjs/quickjs*/qjscalc.c\n/jsb_build/quickjs/quickjs*/qjscalc\n/jsb_build/quickjs/quickjs*/repl-bn.c\n/jsb_build/quickjs/quickjs*/run-test262\n/jsb_build/quickjs/quickjs*/run-test262-bn\n/jsb_build/quickjs/quickjs*/*.a\n/jsb_build/quickjs/quickjs*/*.dll\n/jsb_build/quickjs/quickjs*/examples/*.so\n/jsb_build/quickjs/quickjs*/examples/*.exe\n/jsb_build/quickjs/quickjs*/examples/hello\n/jsb_build/quickjs/quickjs*/examples/hello_module\n/jsb_build/quickjs/quickjs*/hello.c\n/jsb_build/quickjs/quickjs*/test_fib.c\n/jsb_build/quickjs/quickjs*/examples/test_fib\n\n/jsb_build/hotfix/obj\n/jsb_build/res/unversion_*.*\n\n/node_modules\n\ndebug.log\nWSA*.pfx\n/Assets/WSA*.pfx\n/Assets/WSA*.pfx.meta\n/Scripts/dist\n/External/UIProject/*\n!/External/UIProject/plugins\njsb-modules.json\n\n**/.DS_Store"
  },
  {
    "path": ".vscode/launch.json",
    "content": "{\r\n    // Use IntelliSense to learn about possible attributes.\r\n    // Hover to view descriptions of existing attributes.\r\n    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387\r\n    \"version\": \"0.2.0\",\r\n    \"configurations\": [\r\n        {\r\n            \"name\": \"Unity Editor\",\r\n            \"type\": \"unity\",\r\n            \"path\": \"/c:/Users/julio/Documents/Projects/github.com/ialex32x/unity-jsb/Library/EditorInstance.json\",\r\n            \"request\": \"launch\"\r\n        },\r\n        {\r\n            \"name\": \"Windows Player\",\r\n            \"type\": \"unity\",\r\n            \"request\": \"launch\"\r\n        },\r\n        {\r\n            \"name\": \"OSX Player\",\r\n            \"type\": \"unity\",\r\n            \"request\": \"launch\"\r\n        },\r\n        {\r\n            \"name\": \"Linux Player\",\r\n            \"type\": \"unity\",\r\n            \"request\": \"launch\"\r\n        },\r\n        {\r\n            \"name\": \"iOS Player\",\r\n            \"type\": \"unity\",\r\n            \"request\": \"launch\"\r\n        },\r\n        {\r\n            \"name\": \"Android Player\",\r\n            \"type\": \"unity\",\r\n            \"request\": \"launch\"\r\n        },\r\n        {\r\n            \"name\": \"Xbox One Player\",\r\n            \"type\": \"unity\",\r\n            \"request\": \"launch\"\r\n        },\r\n        {\r\n            \"name\": \"PS4 Player\",\r\n            \"type\": \"unity\",\r\n            \"request\": \"launch\"\r\n        },\r\n        {\r\n            \"name\": \"SwitchPlayer\",\r\n            \"type\": \"unity\",\r\n            \"request\": \"launch\"\r\n        }, \r\n        {\r\n            \"name\": \"dotnetcore example\",\r\n            \"type\": \"coreclr\",\r\n            \"request\": \"launch\",\r\n            \"preLaunchTask\": \"build dotnetcore example\",\r\n            \"program\": \"${workspaceFolder}/jsb_build/dotnetcore/bin/Debug/example.dll\",\r\n            \"args\": [],\r\n            \"cwd\": \"${workspaceFolder}/jsb_build/dotnetcore\",\r\n            \"console\": \"internalConsole\",\r\n            \"stopAtEntry\": false\r\n        }\r\n    ]\r\n}"
  },
  {
    "path": ".vscode/settings.json",
    "content": "{\n    \"files.exclude\":\n    {\n        \"**/.DS_Store\":true,\n        \"**/.git\":true,\n        \"**/.gitignore\":false,\n        \"**/.gitmodules\":false,\n        \"**/*.booproj\":true,\n        \"**/*.pidb\":true,\n        \"**/*.suo\":true,\n        \"**/*.user\":true,\n        \"**/*.userprefs\":true,\n        \"**/*.unityproj\":true,\n        \"**/*.dll\":false,\n        \"**/*.exe\":false,\n        \"**/*.pdf\":false,\n        \"**/*.mid\":true,\n        \"**/*.midi\":true,\n        \"**/*.wav\":true,\n        \"**/*.gif\":true,\n        \"**/*.ico\":true,\n        \"**/*.jpg\":true,\n        \"**/*.jpeg\":true,\n        \"**/*.png\":true,\n        \"**/*.psd\":true,\n        \"**/*.tga\":true,\n        \"**/*.tif\":true,\n        \"**/*.tiff\":true,\n        \"**/*.3ds\":true,\n        \"**/*.3DS\":true,\n        \"**/*.fbx\":true,\n        \"**/*.FBX\":true,\n        \"**/*.lxo\":true,\n        \"**/*.LXO\":true,\n        \"**/*.ma\":true,\n        \"**/*.MA\":true,\n        \"**/*.obj\":true,\n        \"**/*.OBJ\":true,\n        \"**/*.asset\":true,\n        \"**/*.cubemap\":true,\n        \"**/*.flare\":true,\n        \"**/*.mat\":true,\n        \"**/*.meta\":true,\n        \"**/*.prefab\":true,\n        \"**/*.unity\":true,\n        \"build/\":true,\n        \"Build/\":true,\n        \"Library/\":true,\n        \"library/\":true,\n        \"obj/\":true,\n        \"Obj/\":true,\n        \"ProjectSettings/\":true,\n        \"temp/\":true,\n        \"Temp/\":true\n    }, \n    \"C_Cpp.default.defines\": [\"${default}\", \"JSB_F_WINDOWS\", \"JSB_COMPILING\"]\n}"
  },
  {
    "path": ".vscode/tasks.json",
    "content": "{\n    // See https://go.microsoft.com/fwlink/?LinkId=733558\n    // for the documentation about the tasks.json format\n    \"version\": \"2.0.0\",\n    \"tasks\": [\n        {\n            \"label\": \"build dotnetcore example\",\n            \"command\": \"dotnet\",\n            \"type\": \"shell\",\n            \"options\": {\n                \"cwd\": \"${workspaceFolder}/jsb_build/dotnetcore\"\n            },\n            \"args\": [\n                \"build\",\n                // Ask dotnet build to generate full paths for file names.\n                \"/property:GenerateFullPaths=true\",\n                // Do not generate summary otherwise it leads to duplicate errors in Problems panel\n                \"/consoleloggerparameters:NoSummary\"\n            ],\n            \"group\": \"build\",\n            \"presentation\": {\n                \"reveal\": \"silent\"\n            },\n            \"problemMatcher\": \"$msCompile\"\n        }\n    ]\n}"
  },
  {
    "path": "Assets/Examples/Data/awesome.proto",
    "content": "// awesome.proto\r\npackage awesomepackage;\r\nsyntax = \"proto3\";\r\n\r\nmessage AwesomeMessage {\r\n    string awesome_field = 1; // becomes awesomeField\r\n}\r\n"
  },
  {
    "path": "Assets/Examples/Data/awesome.proto.meta",
    "content": "fileFormatVersion: 2\nguid: 9787ccecbe2f3354d870a01e2bd1e022\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Data/test.xlsx.meta",
    "content": "fileFormatVersion: 2\nguid: 5f74b074fa120a348add4c9a1be6a7ee\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Data.meta",
    "content": "fileFormatVersion: 2\nguid: bb51247ea1a25d941863d4ec8fcf9083\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Resources/data/js_data.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!114 &11400000\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 0}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 11500000, guid: c74456a7d35a921468a4a2a23d99cee4, type: 3}\n  m_Name: js_data\n  m_EditorClassIdentifier: \n  _scriptRef:\n    sourceFile: /Users/huliangjie/Projects/github.com/ialex32x/unity-jsb/Scripts/src/my_scriptable_object.ts\n    modulePath: my_scriptable_object\n    className: MyScriptableObject\n  _properties:\n    _referencedObjects: []\n    genericValueData: 0000000676616c756531020000803f0000000676616c756532040000000573617364660000000676616c756533080000803f00000040000040400000000676616c7565356502000000180000803f0000004000004040000080400000a0400000c040\n    dataFormat: 1\n"
  },
  {
    "path": "Assets/Examples/Resources/data/js_data.asset.meta",
    "content": "fileFormatVersion: 2\nguid: e8bd9d24a9d4d8346923ac0a8da9c1a5\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 11400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Resources/data.meta",
    "content": "fileFormatVersion: 2\nguid: c297363878d8ee54bbd09387a3f359b6\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Resources/prefab/game_stage.prefab",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1 &2109509275426569018\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 7029823391080910547}\n  - component: {fileID: 4602819741932089376}\n  m_Layer: 0\n  m_Name: GameObject\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!4 &7029823391080910547\nTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 2109509275426569018}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 2.24, y: 0.32, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children: []\n  m_Father: {fileID: 4871136814211804669}\n  m_RootOrder: 3\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n--- !u!61 &4602819741932089376\nBoxCollider2D:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 2109509275426569018}\n  m_Enabled: 1\n  m_Density: 1\n  m_Material: {fileID: 0}\n  m_IsTrigger: 0\n  m_UsedByEffector: 0\n  m_UsedByComposite: 0\n  m_Offset: {x: 0, y: 0}\n  m_SpriteTilingProperty:\n    border: {x: 0, y: 0, z: 0, w: 0}\n    pivot: {x: 0, y: 0}\n    oldSize: {x: 0, y: 0}\n    newSize: {x: 0, y: 0}\n    adaptiveTilingThreshold: 0\n    drawMode: 0\n    adaptiveTiling: 0\n  m_AutoTiling: 0\n  serializedVersion: 2\n  m_Size: {x: 1, y: 2.22}\n  m_EdgeRadius: 0\n--- !u!1 &2911947737711542847\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 7509073489847283556}\n  - component: {fileID: 46605254549189738}\n  - component: {fileID: 3375243806686040490}\n  - component: {fileID: 6038123277484914262}\n  m_Layer: 0\n  m_Name: Collision\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!4 &7509073489847283556\nTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 2911947737711542847}\n  m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children: []\n  m_Father: {fileID: 4871136814211804669}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n--- !u!1839735485 &46605254549189738\nTilemap:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 2911947737711542847}\n  m_Enabled: 1\n  m_Tiles:\n  - first: {x: 0, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 0\n      m_TileSpriteIndex: 0\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 0, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 0, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 0, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 0, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 0, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 0, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 0, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 0, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  m_AnimatedTiles: {}\n  m_TileAssetArray:\n  - m_RefCount: 1\n    m_Data: {fileID: 11400000, guid: de1a7bd3b973f4b459dfd60f5ba8c149, type: 2}\n  - m_RefCount: 8\n    m_Data: {fileID: 11400000, guid: 4903021c6067ced489a594416c114bff, type: 2}\n  m_TileSpriteArray:\n  - m_RefCount: 1\n    m_Data: {fileID: 8666830670597921376, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 8\n    m_Data: {fileID: 9048098576551171047, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  m_TileMatrixArray:\n  - m_RefCount: 9\n    m_Data:\n      e00: 1\n      e01: 0\n      e02: 0\n      e03: 0\n      e10: 0\n      e11: 1\n      e12: 0\n      e13: 0\n      e20: 0\n      e21: 0\n      e22: 1\n      e23: 0\n      e30: 0\n      e31: 0\n      e32: 0\n      e33: 1\n  m_TileColorArray:\n  - m_RefCount: 9\n    m_Data: {r: 1, g: 1, b: 1, a: 1}\n  m_TileObjectToInstantiateArray: []\n  m_AnimationFrameRate: 1\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_Origin: {x: 0, y: 0, z: 0}\n  m_Size: {x: 1, y: 9, z: 1}\n  m_TileAnchor: {x: 0.5, y: 0.5, z: 0}\n  m_TileOrientation: 0\n  m_TileOrientationMatrix:\n    e00: 1\n    e01: 0\n    e02: 0\n    e03: 0\n    e10: 0\n    e11: 1\n    e12: 0\n    e13: 0\n    e20: 0\n    e21: 0\n    e22: 1\n    e23: 0\n    e30: 0\n    e31: 0\n    e32: 0\n    e33: 1\n--- !u!483693784 &3375243806686040490\nTilemapRenderer:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 2911947737711542847}\n  m_Enabled: 0\n  m_CastShadows: 0\n  m_ReceiveShadows: 0\n  m_DynamicOccludee: 1\n  m_MotionVectors: 1\n  m_LightProbeUsage: 0\n  m_ReflectionProbeUsage: 0\n  m_RayTracingMode: 0\n  m_RayTraceProcedural: 0\n  m_RenderingLayerMask: 1\n  m_RendererPriority: 0\n  m_Materials:\n  - {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0}\n  m_StaticBatchInfo:\n    firstSubMesh: 0\n    subMeshCount: 0\n  m_StaticBatchRoot: {fileID: 0}\n  m_ProbeAnchor: {fileID: 0}\n  m_LightProbeVolumeOverride: {fileID: 0}\n  m_ScaleInLightmap: 1\n  m_ReceiveGI: 1\n  m_PreserveUVs: 0\n  m_IgnoreNormalsForChartDetection: 0\n  m_ImportantGI: 0\n  m_StitchLightmapSeams: 1\n  m_SelectedEditorRenderState: 0\n  m_MinimumChartSize: 4\n  m_AutoUVMaxDistance: 0.5\n  m_AutoUVMaxAngle: 89\n  m_LightmapParameters: {fileID: 0}\n  m_SortingLayerID: 0\n  m_SortingLayer: 0\n  m_SortingOrder: 0\n  m_ChunkSize: {x: 32, y: 32, z: 32}\n  m_ChunkCullingBounds: {x: 0, y: 0, z: 0}\n  m_MaxChunkCount: 16\n  m_MaxFrameAge: 16\n  m_SortOrder: 0\n  m_Mode: 0\n  m_DetectChunkCullingBounds: 0\n  m_MaskInteraction: 0\n--- !u!19719996 &6038123277484914262\nTilemapCollider2D:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 2911947737711542847}\n  m_Enabled: 1\n  m_Density: 1\n  m_Material: {fileID: 0}\n  m_IsTrigger: 0\n  m_UsedByEffector: 0\n  m_UsedByComposite: 0\n  m_Offset: {x: -0.22, y: 0}\n  m_MaximumTileChangeCount: 1000\n  m_ExtrusionFactor: 0.00001\n--- !u!1 &3652807326340026068\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 6247703777669653908}\n  m_Layer: 0\n  m_Name: game_stage\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!4 &6247703777669653908\nTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 3652807326340026068}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children:\n  - {fileID: 4871136814211804669}\n  - {fileID: 2767091492489426270}\n  m_Father: {fileID: 0}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n--- !u!1 &3718881873203799714\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 2767091492489426270}\n  - component: {fileID: 7918431125898106511}\n  - component: {fileID: 6815848825619597188}\n  - component: {fileID: 7161838735410085109}\n  - component: {fileID: 4110258182185209090}\n  - component: {fileID: 2480755226849003214}\n  m_Layer: 0\n  m_Name: player\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!4 &2767091492489426270\nTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 3718881873203799714}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 1.127, y: 1.777, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children: []\n  m_Father: {fileID: 6247703777669653908}\n  m_RootOrder: 1\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n--- !u!212 &7918431125898106511\nSpriteRenderer:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 3718881873203799714}\n  m_Enabled: 1\n  m_CastShadows: 0\n  m_ReceiveShadows: 0\n  m_DynamicOccludee: 1\n  m_MotionVectors: 1\n  m_LightProbeUsage: 1\n  m_ReflectionProbeUsage: 1\n  m_RayTracingMode: 0\n  m_RayTraceProcedural: 0\n  m_RenderingLayerMask: 1\n  m_RendererPriority: 0\n  m_Materials:\n  - {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0}\n  m_StaticBatchInfo:\n    firstSubMesh: 0\n    subMeshCount: 0\n  m_StaticBatchRoot: {fileID: 0}\n  m_ProbeAnchor: {fileID: 0}\n  m_LightProbeVolumeOverride: {fileID: 0}\n  m_ScaleInLightmap: 1\n  m_ReceiveGI: 1\n  m_PreserveUVs: 0\n  m_IgnoreNormalsForChartDetection: 0\n  m_ImportantGI: 0\n  m_StitchLightmapSeams: 1\n  m_SelectedEditorRenderState: 0\n  m_MinimumChartSize: 4\n  m_AutoUVMaxDistance: 0.5\n  m_AutoUVMaxAngle: 89\n  m_LightmapParameters: {fileID: 0}\n  m_SortingLayerID: 0\n  m_SortingLayer: 0\n  m_SortingOrder: 1\n  m_Sprite: {fileID: 4236677631525818213, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44,\n    type: 3}\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_FlipX: 0\n  m_FlipY: 0\n  m_DrawMode: 0\n  m_Size: {x: 0.78, y: 0.58}\n  m_AdaptiveModeThreshold: 0.5\n  m_SpriteTileMode: 0\n  m_WasSpriteAssigned: 1\n  m_MaskInteraction: 0\n  m_SpriteSortPoint: 0\n--- !u!50 &6815848825619597188\nRigidbody2D:\n  serializedVersion: 4\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 3718881873203799714}\n  m_BodyType: 0\n  m_Simulated: 1\n  m_UseFullKinematicContacts: 0\n  m_UseAutoMass: 0\n  m_Mass: 1\n  m_LinearDrag: 0\n  m_AngularDrag: 0.05\n  m_GravityScale: 1\n  m_Material: {fileID: 0}\n  m_Interpolate: 0\n  m_SleepingMode: 1\n  m_CollisionDetection: 1\n  m_Constraints: 0\n--- !u!61 &7161838735410085109\nBoxCollider2D:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 3718881873203799714}\n  m_Enabled: 1\n  m_Density: 1\n  m_Material: {fileID: 0}\n  m_IsTrigger: 0\n  m_UsedByEffector: 0\n  m_UsedByComposite: 0\n  m_Offset: {x: 0, y: 0}\n  m_SpriteTilingProperty:\n    border: {x: 0, y: 0, z: 0, w: 0}\n    pivot: {x: 0.5, y: 0.5}\n    oldSize: {x: 0.78, y: 0.58}\n    newSize: {x: 0.78, y: 0.58}\n    adaptiveTilingThreshold: 0.5\n    drawMode: 0\n    adaptiveTiling: 0\n  m_AutoTiling: 0\n  serializedVersion: 2\n  m_Size: {x: 0.32, y: 0.3}\n  m_EdgeRadius: 0\n--- !u!95 &4110258182185209090\nAnimator:\n  serializedVersion: 3\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 3718881873203799714}\n  m_Enabled: 1\n  m_Avatar: {fileID: 0}\n  m_Controller: {fileID: 9100000, guid: 2f41571c8d90046448625e247abe67dc, type: 2}\n  m_CullingMode: 0\n  m_UpdateMode: 0\n  m_ApplyRootMotion: 0\n  m_LinearVelocityBlending: 0\n  m_WarningMessage: \n  m_HasTransformHierarchy: 1\n  m_AllowConstantClipSamplingOptimization: 1\n  m_KeepAnimatorControllerStateOnDisable: 0\n--- !u!114 &2480755226849003214\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 3718881873203799714}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 11500000, guid: 5d7749844623fd647859e1bd098d5a43, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  _scriptRef:\n    sourceFile: C:\\projects\\unity-jsb\\Scripts\\src\\game\\king_human_controller.ts\n    modulePath: game/king_human_controller\n    className: KingHumanController\n  _properties:\n    _referencedObjects:\n    - {fileID: 4110258182185209090}\n    genericValueData: 00000008616e696d61746f720c00000000000000096d6f7665537065656402a470fd3f0000000b6e657374656456616c7565660000005b0000000c6e6573746564537472696e67040000000568656c6c6f0000000d6e6573746564566563746f7233080000803f000000400000404000000009706f736974696f6e736507000000100000803f000000400000404000008040\n    dataFormat: 1\n--- !u!1 &4391018998062893110\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 1372304955970133991}\n  - component: {fileID: 906135534294172331}\n  - component: {fileID: 7490898619168283429}\n  - component: {fileID: 2166415763008163099}\n  m_Layer: 0\n  m_Name: Collision (1)\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!4 &1372304955970133991\nTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 4391018998062893110}\n  m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children: []\n  m_Father: {fileID: 4871136814211804669}\n  m_RootOrder: 1\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n--- !u!1839735485 &906135534294172331\nTilemap:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 4391018998062893110}\n  m_Enabled: 1\n  m_Tiles:\n  - first: {x: 0, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 1, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 2, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 3, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 4, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 5, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 6, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 7, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 8, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 9, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 10, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 11, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 12, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 13, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 0\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  m_AnimatedTiles: {}\n  m_TileAssetArray:\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 14\n    m_Data: {fileID: 11400000, guid: 2e6a9bfbab8e0c347ac12179f2a0f7a5, type: 2}\n  m_TileSpriteArray:\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 14\n    m_Data: {fileID: -2936791710745090628, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  m_TileMatrixArray:\n  - m_RefCount: 14\n    m_Data:\n      e00: 1\n      e01: 0\n      e02: 0\n      e03: 0\n      e10: 0\n      e11: 1\n      e12: 0\n      e13: 0\n      e20: 0\n      e21: 0\n      e22: 1\n      e23: 0\n      e30: 0\n      e31: 0\n      e32: 0\n      e33: 1\n  m_TileColorArray:\n  - m_RefCount: 14\n    m_Data: {r: 1, g: 1, b: 1, a: 1}\n  m_TileObjectToInstantiateArray: []\n  m_AnimationFrameRate: 1\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_Origin: {x: 0, y: 0, z: 0}\n  m_Size: {x: 14, y: 9, z: 1}\n  m_TileAnchor: {x: 0.5, y: 0.5, z: 0}\n  m_TileOrientation: 0\n  m_TileOrientationMatrix:\n    e00: 1\n    e01: 0\n    e02: 0\n    e03: 0\n    e10: 0\n    e11: 1\n    e12: 0\n    e13: 0\n    e20: 0\n    e21: 0\n    e22: 1\n    e23: 0\n    e30: 0\n    e31: 0\n    e32: 0\n    e33: 1\n--- !u!483693784 &7490898619168283429\nTilemapRenderer:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 4391018998062893110}\n  m_Enabled: 0\n  m_CastShadows: 0\n  m_ReceiveShadows: 0\n  m_DynamicOccludee: 1\n  m_MotionVectors: 1\n  m_LightProbeUsage: 0\n  m_ReflectionProbeUsage: 0\n  m_RayTracingMode: 0\n  m_RayTraceProcedural: 0\n  m_RenderingLayerMask: 1\n  m_RendererPriority: 0\n  m_Materials:\n  - {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0}\n  m_StaticBatchInfo:\n    firstSubMesh: 0\n    subMeshCount: 0\n  m_StaticBatchRoot: {fileID: 0}\n  m_ProbeAnchor: {fileID: 0}\n  m_LightProbeVolumeOverride: {fileID: 0}\n  m_ScaleInLightmap: 1\n  m_ReceiveGI: 1\n  m_PreserveUVs: 0\n  m_IgnoreNormalsForChartDetection: 0\n  m_ImportantGI: 0\n  m_StitchLightmapSeams: 1\n  m_SelectedEditorRenderState: 0\n  m_MinimumChartSize: 4\n  m_AutoUVMaxDistance: 0.5\n  m_AutoUVMaxAngle: 89\n  m_LightmapParameters: {fileID: 0}\n  m_SortingLayerID: 0\n  m_SortingLayer: 0\n  m_SortingOrder: 0\n  m_ChunkSize: {x: 32, y: 32, z: 32}\n  m_ChunkCullingBounds: {x: 0, y: 0, z: 0}\n  m_MaxChunkCount: 16\n  m_MaxFrameAge: 16\n  m_SortOrder: 0\n  m_Mode: 0\n  m_DetectChunkCullingBounds: 0\n  m_MaskInteraction: 0\n--- !u!19719996 &2166415763008163099\nTilemapCollider2D:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 4391018998062893110}\n  m_Enabled: 1\n  m_Density: 1\n  m_Material: {fileID: 0}\n  m_IsTrigger: 0\n  m_UsedByEffector: 0\n  m_UsedByComposite: 0\n  m_Offset: {x: 0, y: -0.22}\n  m_MaximumTileChangeCount: 1000\n  m_ExtrusionFactor: 0.00001\n--- !u!1 &5365635302833774329\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 3496220206110655134}\n  - component: {fileID: 1102174504189884121}\n  - component: {fileID: 2497786265729895846}\n  m_Layer: 0\n  m_Name: Tilemap\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!4 &3496220206110655134\nTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 5365635302833774329}\n  m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children: []\n  m_Father: {fileID: 4871136814211804669}\n  m_RootOrder: 2\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n--- !u!1839735485 &1102174504189884121\nTilemap:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 5365635302833774329}\n  m_Enabled: 1\n  m_Tiles:\n  - first: {x: 0, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 8\n      m_TileSpriteIndex: 9\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 1, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 7\n      m_TileSpriteIndex: 8\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 2, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 7\n      m_TileSpriteIndex: 8\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 3, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 7\n      m_TileSpriteIndex: 8\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 4, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 7\n      m_TileSpriteIndex: 8\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 5, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 7\n      m_TileSpriteIndex: 8\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 6, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 7\n      m_TileSpriteIndex: 8\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 7, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 7\n      m_TileSpriteIndex: 8\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 8, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 7\n      m_TileSpriteIndex: 8\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 9, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 7\n      m_TileSpriteIndex: 8\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 10, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 7\n      m_TileSpriteIndex: 8\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 11, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 7\n      m_TileSpriteIndex: 8\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 12, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 7\n      m_TileSpriteIndex: 8\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 13, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 7\n      m_TileSpriteIndex: 8\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 14, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 7\n      m_TileSpriteIndex: 8\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 15, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 7\n      m_TileSpriteIndex: 8\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 16, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 7\n      m_TileSpriteIndex: 8\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 17, y: 0, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 6\n      m_TileSpriteIndex: 7\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 0, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 5\n      m_TileSpriteIndex: 6\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 1, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 2, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 3, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 4, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 5, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 6, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 7, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 8, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 9, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 10, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 11, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 12, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 13, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 14, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 15, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 16, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 17, y: 1, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 3\n      m_TileSpriteIndex: 4\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 0, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 5\n      m_TileSpriteIndex: 6\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 1, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 2, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 3, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 4, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 5, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 6, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 7, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 8, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 9, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 10, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 11, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 12, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 13, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 14, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 15, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 16, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 17, y: 2, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 3\n      m_TileSpriteIndex: 4\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 0, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 5\n      m_TileSpriteIndex: 6\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 1, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 2, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 3, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 4, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 5, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 6, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 7, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 8, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 9, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 10, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 11, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 12, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 13, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 14, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 15, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 16, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 17, y: 3, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 3\n      m_TileSpriteIndex: 4\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 0, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 5\n      m_TileSpriteIndex: 6\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 1, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 2, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 3, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 4, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 5, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 6, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 7, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 8, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 9, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 10, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 11, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 12, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 13, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 14, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 15, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 16, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 17, y: 4, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 3\n      m_TileSpriteIndex: 4\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 0, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 5\n      m_TileSpriteIndex: 6\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 1, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 2, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 3, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 4, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 5, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 6, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 7, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 8, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 9, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 10, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 11, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 12, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 13, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 14, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 15, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 16, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 17, y: 5, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 3\n      m_TileSpriteIndex: 4\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 0, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 5\n      m_TileSpriteIndex: 6\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 1, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 2, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 3, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 4, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 5, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 6, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 7, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 8, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 9, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 10, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 11, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 12, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 13, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 14, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 15, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 16, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 17, y: 6, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 3\n      m_TileSpriteIndex: 4\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 0, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 5\n      m_TileSpriteIndex: 6\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 1, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 2, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 3, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 4, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 5, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 6, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 7, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 8, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 9, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 10, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 11, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 12, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 13, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 14, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 15, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 16, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 4\n      m_TileSpriteIndex: 5\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 17, y: 7, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 3\n      m_TileSpriteIndex: 4\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 0, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 2\n      m_TileSpriteIndex: 3\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 1, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 2\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 2, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 2\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 3, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 2\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 4, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 2\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 5, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 2\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 6, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 2\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 7, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 2\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 8, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 2\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 9, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 2\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 10, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 2\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 11, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 2\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 12, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 2\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 13, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 2\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 14, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 2\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 15, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 2\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 16, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 1\n      m_TileSpriteIndex: 2\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  - first: {x: 17, y: 8, z: 0}\n    second:\n      serializedVersion: 2\n      m_TileIndex: 0\n      m_TileSpriteIndex: 1\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 1\n      m_TileObjectToInstantiateIndex: 65535\n      dummyAlignment: 0\n      m_AllTileFlags: 1073741825\n  m_AnimatedTiles: {}\n  m_TileAssetArray:\n  - m_RefCount: 1\n    m_Data: {fileID: 11400000, guid: f4a4199d6aefaa543b081c23a3ce0a6a, type: 2}\n  - m_RefCount: 16\n    m_Data: {fileID: 11400000, guid: 6ad0a965971cbbe42a8b6cc2792f0e59, type: 2}\n  - m_RefCount: 1\n    m_Data: {fileID: 11400000, guid: 02ee918df97067942877970e67eb3f76, type: 2}\n  - m_RefCount: 7\n    m_Data: {fileID: 11400000, guid: 6fddaf8e8903e8b4a99c9e08b7ef4740, type: 2}\n  - m_RefCount: 112\n    m_Data: {fileID: 11400000, guid: d60c19cedbdfaf540a5224f2703d9185, type: 2}\n  - m_RefCount: 7\n    m_Data: {fileID: 11400000, guid: 4903021c6067ced489a594416c114bff, type: 2}\n  - m_RefCount: 1\n    m_Data: {fileID: 11400000, guid: 9f26bff8983bce141ae2a7232cc3110c, type: 2}\n  - m_RefCount: 16\n    m_Data: {fileID: 11400000, guid: 2e6a9bfbab8e0c347ac12179f2a0f7a5, type: 2}\n  - m_RefCount: 1\n    m_Data: {fileID: 11400000, guid: de1a7bd3b973f4b459dfd60f5ba8c149, type: 2}\n  m_TileSpriteArray:\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 1\n    m_Data: {fileID: 4239696434956193796, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 16\n    m_Data: {fileID: -9114847578740223409, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 1\n    m_Data: {fileID: -2113894134886356154, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 7\n    m_Data: {fileID: -7635356268976036439, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 112\n    m_Data: {fileID: 5550582127777731385, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 7\n    m_Data: {fileID: 9048098576551171047, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 1\n    m_Data: {fileID: -1707878253529702307, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 16\n    m_Data: {fileID: -2936791710745090628, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 1\n    m_Data: {fileID: 8666830670597921376, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  m_TileMatrixArray:\n  - m_RefCount: 162\n    m_Data:\n      e00: 1\n      e01: 0\n      e02: 0\n      e03: 0\n      e10: 0\n      e11: 1\n      e12: 0\n      e13: 0\n      e20: 0\n      e21: 0\n      e22: 1\n      e23: 0\n      e30: 0\n      e31: 0\n      e32: 0\n      e33: 1\n  m_TileColorArray:\n  - m_RefCount: 0\n    m_Data: {r: -1.0318755e+34, g: -1.0318755e+34, b: -1.0318755e+34, a: -1.0318755e+34}\n  - m_RefCount: 162\n    m_Data: {r: 1, g: 1, b: 1, a: 1}\n  m_TileObjectToInstantiateArray: []\n  m_AnimationFrameRate: 1\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_Origin: {x: -1, y: -12, z: 0}\n  m_Size: {x: 31, y: 21, z: 1}\n  m_TileAnchor: {x: 0.5, y: 0.5, z: 0}\n  m_TileOrientation: 0\n  m_TileOrientationMatrix:\n    e00: 1\n    e01: 0\n    e02: 0\n    e03: 0\n    e10: 0\n    e11: 1\n    e12: 0\n    e13: 0\n    e20: 0\n    e21: 0\n    e22: 1\n    e23: 0\n    e30: 0\n    e31: 0\n    e32: 0\n    e33: 1\n--- !u!483693784 &2497786265729895846\nTilemapRenderer:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 5365635302833774329}\n  m_Enabled: 1\n  m_CastShadows: 0\n  m_ReceiveShadows: 0\n  m_DynamicOccludee: 1\n  m_MotionVectors: 1\n  m_LightProbeUsage: 0\n  m_ReflectionProbeUsage: 0\n  m_RayTracingMode: 0\n  m_RayTraceProcedural: 0\n  m_RenderingLayerMask: 1\n  m_RendererPriority: 0\n  m_Materials:\n  - {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0}\n  m_StaticBatchInfo:\n    firstSubMesh: 0\n    subMeshCount: 0\n  m_StaticBatchRoot: {fileID: 0}\n  m_ProbeAnchor: {fileID: 0}\n  m_LightProbeVolumeOverride: {fileID: 0}\n  m_ScaleInLightmap: 1\n  m_ReceiveGI: 1\n  m_PreserveUVs: 0\n  m_IgnoreNormalsForChartDetection: 0\n  m_ImportantGI: 0\n  m_StitchLightmapSeams: 1\n  m_SelectedEditorRenderState: 0\n  m_MinimumChartSize: 4\n  m_AutoUVMaxDistance: 0.5\n  m_AutoUVMaxAngle: 89\n  m_LightmapParameters: {fileID: 0}\n  m_SortingLayerID: 0\n  m_SortingLayer: 0\n  m_SortingOrder: 0\n  m_ChunkSize: {x: 32, y: 32, z: 32}\n  m_ChunkCullingBounds: {x: 0, y: 0, z: 0}\n  m_MaxChunkCount: 16\n  m_MaxFrameAge: 16\n  m_SortOrder: 0\n  m_Mode: 0\n  m_DetectChunkCullingBounds: 0\n  m_MaskInteraction: 0\n--- !u!1 &5787739494114565399\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 4871136814211804669}\n  - component: {fileID: 435725882367536530}\n  m_Layer: 0\n  m_Name: Grid\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!4 &4871136814211804669\nTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 5787739494114565399}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children:\n  - {fileID: 7509073489847283556}\n  - {fileID: 1372304955970133991}\n  - {fileID: 3496220206110655134}\n  - {fileID: 7029823391080910547}\n  m_Father: {fileID: 6247703777669653908}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n--- !u!156049354 &435725882367536530\nGrid:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 5787739494114565399}\n  m_Enabled: 1\n  m_CellSize: {x: 0.32, y: 0.32, z: 0}\n  m_CellGap: {x: 0, y: 0, z: 0}\n  m_CellLayout: 0\n  m_CellSwizzle: 0\n"
  },
  {
    "path": "Assets/Examples/Resources/prefab/game_stage.prefab.meta",
    "content": "fileFormatVersion: 2\nguid: a427d884c5daf404b9798e510af35e25\nPrefabImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Resources/prefab/jsx_test_ui.prefab",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1 &3256278668177176484\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 5020270652044548887}\n  - component: {fileID: 1402340735853728869}\n  - component: {fileID: 4540185692050160000}\n  m_Layer: 5\n  m_Name: label\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!224 &5020270652044548887\nRectTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 3256278668177176484}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children: []\n  m_Father: {fileID: 7667242864368111302}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n  m_AnchorMin: {x: 0.5, y: 0.5}\n  m_AnchorMax: {x: 0.5, y: 0.5}\n  m_AnchoredPosition: {x: 0, y: 0}\n  m_SizeDelta: {x: 160, y: 30}\n  m_Pivot: {x: 0.5, y: 0.5}\n--- !u!222 &1402340735853728869\nCanvasRenderer:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 3256278668177176484}\n  m_CullTransparentMesh: 0\n--- !u!114 &4540185692050160000\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 3256278668177176484}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_Material: {fileID: 0}\n  m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1}\n  m_RaycastTarget: 1\n  m_OnCullStateChanged:\n    m_PersistentCalls:\n      m_Calls: []\n    m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI,\n      Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\n  m_FontData:\n    m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0}\n    m_FontSize: 14\n    m_FontStyle: 1\n    m_BestFit: 0\n    m_MinSize: 10\n    m_MaxSize: 40\n    m_Alignment: 4\n    m_AlignByGeometry: 0\n    m_RichText: 1\n    m_HorizontalOverflow: 1\n    m_VerticalOverflow: 1\n    m_LineSpacing: 1\n  m_Text: New Text\n--- !u!1 &7912323089437928816\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 7667242864368111302}\n  - component: {fileID: 3864762882740921524}\n  - component: {fileID: 6373974695743497345}\n  m_Layer: 5\n  m_Name: jsx_test_ui\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!224 &7667242864368111302\nRectTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 7912323089437928816}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children:\n  - {fileID: 5020270652044548887}\n  m_Father: {fileID: 0}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n  m_AnchorMin: {x: 0, y: 0}\n  m_AnchorMax: {x: 1, y: 1}\n  m_AnchoredPosition: {x: 0, y: 0}\n  m_SizeDelta: {x: 0, y: 0}\n  m_Pivot: {x: 0.5, y: 0.5}\n--- !u!222 &3864762882740921524\nCanvasRenderer:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 7912323089437928816}\n  m_CullTransparentMesh: 0\n--- !u!114 &6373974695743497345\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 7912323089437928816}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_Material: {fileID: 0}\n  m_Color: {r: 1, g: 1, b: 1, a: 0.392}\n  m_RaycastTarget: 1\n  m_OnCullStateChanged:\n    m_PersistentCalls:\n      m_Calls: []\n    m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI,\n      Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\n  m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0}\n  m_Type: 1\n  m_PreserveAspect: 0\n  m_FillCenter: 1\n  m_FillMethod: 4\n  m_FillAmount: 1\n  m_FillClockwise: 1\n  m_FillOrigin: 0\n  m_UseSpriteMesh: 0\n"
  },
  {
    "path": "Assets/Examples/Resources/prefab/jsx_test_ui.prefab.meta",
    "content": "fileFormatVersion: 2\nguid: e8d7522bad6844f44b855abe0e8db102\nPrefabImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Resources/prefab.meta",
    "content": "fileFormatVersion: 2\nguid: 1cf2858c45dc0384e8b87c2fde141ce5\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Resources.meta",
    "content": "fileFormatVersion: 2\nguid: b377e073e1ee3394591fa15e208f396c\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Scenes/BasicRun.unity",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!29 &1\nOcclusionCullingSettings:\n  m_ObjectHideFlags: 0\n  serializedVersion: 2\n  m_OcclusionBakeSettings:\n    smallestOccluder: 5\n    smallestHole: 0.25\n    backfaceThreshold: 100\n  m_SceneGUID: 00000000000000000000000000000000\n  m_OcclusionCullingData: {fileID: 0}\n--- !u!104 &2\nRenderSettings:\n  m_ObjectHideFlags: 0\n  serializedVersion: 9\n  m_Fog: 0\n  m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1}\n  m_FogMode: 3\n  m_FogDensity: 0.01\n  m_LinearFogStart: 0\n  m_LinearFogEnd: 300\n  m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1}\n  m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1}\n  m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1}\n  m_AmbientIntensity: 1\n  m_AmbientMode: 0\n  m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1}\n  m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0}\n  m_HaloStrength: 0.5\n  m_FlareStrength: 1\n  m_FlareFadeSpeed: 3\n  m_HaloTexture: {fileID: 0}\n  m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0}\n  m_DefaultReflectionMode: 0\n  m_DefaultReflectionResolution: 128\n  m_ReflectionBounces: 1\n  m_ReflectionIntensity: 1\n  m_CustomReflection: {fileID: 0}\n  m_Sun: {fileID: 0}\n  m_IndirectSpecularColor: {r: 0.44657826, g: 0.49641263, b: 0.57481676, a: 1}\n  m_UseRadianceAmbientProbe: 0\n--- !u!157 &3\nLightmapSettings:\n  m_ObjectHideFlags: 0\n  serializedVersion: 11\n  m_GIWorkflowMode: 1\n  m_GISettings:\n    serializedVersion: 2\n    m_BounceScale: 1\n    m_IndirectOutputScale: 1\n    m_AlbedoBoost: 1\n    m_EnvironmentLightingMode: 0\n    m_EnableBakedLightmaps: 1\n    m_EnableRealtimeLightmaps: 1\n  m_LightmapEditorSettings:\n    serializedVersion: 12\n    m_Resolution: 2\n    m_BakeResolution: 40\n    m_AtlasSize: 1024\n    m_AO: 0\n    m_AOMaxDistance: 1\n    m_CompAOExponent: 1\n    m_CompAOExponentDirect: 0\n    m_ExtractAmbientOcclusion: 0\n    m_Padding: 2\n    m_LightmapParameters: {fileID: 0}\n    m_LightmapsBakeMode: 1\n    m_TextureCompression: 1\n    m_FinalGather: 0\n    m_FinalGatherFiltering: 1\n    m_FinalGatherRayCount: 256\n    m_ReflectionCompression: 2\n    m_MixedBakeMode: 2\n    m_BakeBackend: 1\n    m_PVRSampling: 1\n    m_PVRDirectSampleCount: 32\n    m_PVRSampleCount: 512\n    m_PVRBounces: 2\n    m_PVREnvironmentSampleCount: 256\n    m_PVREnvironmentReferencePointCount: 2048\n    m_PVRFilteringMode: 1\n    m_PVRDenoiserTypeDirect: 1\n    m_PVRDenoiserTypeIndirect: 1\n    m_PVRDenoiserTypeAO: 1\n    m_PVRFilterTypeDirect: 0\n    m_PVRFilterTypeIndirect: 0\n    m_PVRFilterTypeAO: 0\n    m_PVREnvironmentMIS: 1\n    m_PVRCulling: 1\n    m_PVRFilteringGaussRadiusDirect: 1\n    m_PVRFilteringGaussRadiusIndirect: 5\n    m_PVRFilteringGaussRadiusAO: 2\n    m_PVRFilteringAtrousPositionSigmaDirect: 0.5\n    m_PVRFilteringAtrousPositionSigmaIndirect: 2\n    m_PVRFilteringAtrousPositionSigmaAO: 1\n    m_ExportTrainingData: 0\n    m_TrainingDataDestination: TrainingData\n    m_LightProbeSampleCountMultiplier: 4\n  m_LightingDataAsset: {fileID: 0}\n  m_UseShadowmask: 1\n--- !u!196 &4\nNavMeshSettings:\n  serializedVersion: 2\n  m_ObjectHideFlags: 0\n  m_BuildSettings:\n    serializedVersion: 2\n    agentTypeID: 0\n    agentRadius: 0.5\n    agentHeight: 2\n    agentSlope: 45\n    agentClimb: 0.4\n    ledgeDropHeight: 0\n    maxJumpAcrossDistance: 0\n    minRegionArea: 2\n    manualCellSize: 0\n    cellSize: 0.16666667\n    manualTileSize: 0\n    tileSize: 256\n    accuratePlacement: 0\n    debug:\n      m_Flags: 0\n  m_NavMeshData: {fileID: 0}\n--- !u!1 &617432996\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 617432998}\n  - component: {fileID: 617432997}\n  m_Layer: 0\n  m_Name: Directional Light\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!108 &617432997\nLight:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 617432996}\n  m_Enabled: 1\n  serializedVersion: 10\n  m_Type: 1\n  m_Shape: 0\n  m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1}\n  m_Intensity: 1\n  m_Range: 10\n  m_SpotAngle: 30\n  m_InnerSpotAngle: 21.80208\n  m_CookieSize: 10\n  m_Shadows:\n    m_Type: 2\n    m_Resolution: -1\n    m_CustomResolution: -1\n    m_Strength: 1\n    m_Bias: 0.05\n    m_NormalBias: 0.4\n    m_NearPlane: 0.2\n    m_CullingMatrixOverride:\n      e00: 1\n      e01: 0\n      e02: 0\n      e03: 0\n      e10: 0\n      e11: 1\n      e12: 0\n      e13: 0\n      e20: 0\n      e21: 0\n      e22: 1\n      e23: 0\n      e30: 0\n      e31: 0\n      e32: 0\n      e33: 1\n    m_UseCullingMatrixOverride: 0\n  m_Cookie: {fileID: 0}\n  m_DrawHalo: 0\n  m_Flare: {fileID: 0}\n  m_RenderMode: 0\n  m_CullingMask:\n    serializedVersion: 2\n    m_Bits: 4294967295\n  m_RenderingLayerMask: 1\n  m_Lightmapping: 4\n  m_LightShadowCasterMode: 0\n  m_AreaSize: {x: 1, y: 1}\n  m_BounceIntensity: 1\n  m_ColorTemperature: 6570\n  m_UseColorTemperature: 0\n  m_BoundingSphereOverride: {x: 0, y: 0, z: 0, w: 0}\n  m_UseBoundingSphereOverride: 0\n  m_ShadowRadius: 0\n  m_ShadowAngle: 0\n--- !u!4 &617432998\nTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 617432996}\n  m_LocalRotation: {x: 0.40821788, y: -0.23456968, z: 0.10938163, w: 0.8754261}\n  m_LocalPosition: {x: 0, y: 3, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children: []\n  m_Father: {fileID: 0}\n  m_RootOrder: 1\n  m_LocalEulerAnglesHint: {x: 50, y: -30, z: 0}\n--- !u!1 &1783206578\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 1783206582}\n  - component: {fileID: 1783206581}\n  - component: {fileID: 1783206580}\n  - component: {fileID: 1783206579}\n  m_Layer: 0\n  m_Name: Main Camera\n  m_TagString: MainCamera\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!114 &1783206579\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1783206578}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 11500000, guid: d681b6ce2f6dd914fb897251fb0375a2, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  execRuntime: 1\n--- !u!81 &1783206580\nAudioListener:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1783206578}\n  m_Enabled: 1\n--- !u!20 &1783206581\nCamera:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1783206578}\n  m_Enabled: 1\n  serializedVersion: 2\n  m_ClearFlags: 1\n  m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0}\n  m_projectionMatrixMode: 1\n  m_GateFitMode: 2\n  m_FOVAxisMode: 0\n  m_SensorSize: {x: 36, y: 24}\n  m_LensShift: {x: 0, y: 0}\n  m_FocalLength: 50\n  m_NormalizedViewPortRect:\n    serializedVersion: 2\n    x: 0\n    y: 0\n    width: 1\n    height: 1\n  near clip plane: 0.3\n  far clip plane: 1000\n  field of view: 60\n  orthographic: 0\n  orthographic size: 5\n  m_Depth: -1\n  m_CullingMask:\n    serializedVersion: 2\n    m_Bits: 4294967295\n  m_RenderingPath: -1\n  m_TargetTexture: {fileID: 0}\n  m_TargetDisplay: 0\n  m_TargetEye: 3\n  m_HDR: 1\n  m_AllowMSAA: 1\n  m_AllowDynamicResolution: 0\n  m_ForceIntoRT: 0\n  m_OcclusionCulling: 1\n  m_StereoConvergence: 10\n  m_StereoSeparation: 0.022\n--- !u!4 &1783206582\nTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1783206578}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 1, z: -10}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children: []\n  m_Father: {fileID: 0}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n"
  },
  {
    "path": "Assets/Examples/Scenes/BasicRun.unity.meta",
    "content": "fileFormatVersion: 2\nguid: 0fcf6e9a77c8854458ecac8392edf86e\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Scenes/SampleScene.unity",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!29 &1\nOcclusionCullingSettings:\n  m_ObjectHideFlags: 0\n  serializedVersion: 2\n  m_OcclusionBakeSettings:\n    smallestOccluder: 5\n    smallestHole: 0.25\n    backfaceThreshold: 100\n  m_SceneGUID: 00000000000000000000000000000000\n  m_OcclusionCullingData: {fileID: 0}\n--- !u!104 &2\nRenderSettings:\n  m_ObjectHideFlags: 0\n  serializedVersion: 9\n  m_Fog: 0\n  m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1}\n  m_FogMode: 3\n  m_FogDensity: 0.01\n  m_LinearFogStart: 0\n  m_LinearFogEnd: 300\n  m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1}\n  m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1}\n  m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1}\n  m_AmbientIntensity: 1\n  m_AmbientMode: 0\n  m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1}\n  m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0}\n  m_HaloStrength: 0.5\n  m_FlareStrength: 1\n  m_FlareFadeSpeed: 3\n  m_HaloTexture: {fileID: 0}\n  m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0}\n  m_DefaultReflectionMode: 0\n  m_DefaultReflectionResolution: 128\n  m_ReflectionBounces: 1\n  m_ReflectionIntensity: 1\n  m_CustomReflection: {fileID: 0}\n  m_Sun: {fileID: 705507994}\n  m_IndirectSpecularColor: {r: 0.44657898, g: 0.4964133, b: 0.5748178, a: 1}\n  m_UseRadianceAmbientProbe: 0\n--- !u!157 &3\nLightmapSettings:\n  m_ObjectHideFlags: 0\n  serializedVersion: 11\n  m_GIWorkflowMode: 0\n  m_GISettings:\n    serializedVersion: 2\n    m_BounceScale: 1\n    m_IndirectOutputScale: 1\n    m_AlbedoBoost: 1\n    m_EnvironmentLightingMode: 0\n    m_EnableBakedLightmaps: 1\n    m_EnableRealtimeLightmaps: 1\n  m_LightmapEditorSettings:\n    serializedVersion: 12\n    m_Resolution: 2\n    m_BakeResolution: 40\n    m_AtlasSize: 1024\n    m_AO: 0\n    m_AOMaxDistance: 1\n    m_CompAOExponent: 1\n    m_CompAOExponentDirect: 0\n    m_ExtractAmbientOcclusion: 0\n    m_Padding: 2\n    m_LightmapParameters: {fileID: 0}\n    m_LightmapsBakeMode: 1\n    m_TextureCompression: 1\n    m_FinalGather: 0\n    m_FinalGatherFiltering: 1\n    m_FinalGatherRayCount: 256\n    m_ReflectionCompression: 2\n    m_MixedBakeMode: 2\n    m_BakeBackend: 1\n    m_PVRSampling: 1\n    m_PVRDirectSampleCount: 32\n    m_PVRSampleCount: 500\n    m_PVRBounces: 2\n    m_PVREnvironmentSampleCount: 500\n    m_PVREnvironmentReferencePointCount: 2048\n    m_PVRFilteringMode: 2\n    m_PVRDenoiserTypeDirect: 0\n    m_PVRDenoiserTypeIndirect: 0\n    m_PVRDenoiserTypeAO: 0\n    m_PVRFilterTypeDirect: 0\n    m_PVRFilterTypeIndirect: 0\n    m_PVRFilterTypeAO: 0\n    m_PVREnvironmentMIS: 0\n    m_PVRCulling: 1\n    m_PVRFilteringGaussRadiusDirect: 1\n    m_PVRFilteringGaussRadiusIndirect: 5\n    m_PVRFilteringGaussRadiusAO: 2\n    m_PVRFilteringAtrousPositionSigmaDirect: 0.5\n    m_PVRFilteringAtrousPositionSigmaIndirect: 2\n    m_PVRFilteringAtrousPositionSigmaAO: 1\n    m_ShowResolutionOverlay: 1\n    m_ExportTrainingData: 0\n  m_LightingDataAsset: {fileID: 0}\n  m_UseShadowmask: 1\n--- !u!196 &4\nNavMeshSettings:\n  serializedVersion: 2\n  m_ObjectHideFlags: 0\n  m_BuildSettings:\n    serializedVersion: 2\n    agentTypeID: 0\n    agentRadius: 0.5\n    agentHeight: 2\n    agentSlope: 45\n    agentClimb: 0.4\n    ledgeDropHeight: 0\n    maxJumpAcrossDistance: 0\n    minRegionArea: 2\n    manualCellSize: 0\n    cellSize: 0.16666667\n    manualTileSize: 0\n    tileSize: 256\n    accuratePlacement: 0\n    debug:\n      m_Flags: 0\n  m_NavMeshData: {fileID: 0}\n--- !u!1 &328579302\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 328579304}\n  - component: {fileID: 328579303}\n  m_Layer: 0\n  m_Name: Sample\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!114 &328579303\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 328579302}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 11500000, guid: 08b53751862e51a46a4cfe8e661faac4, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  scrollRect: {fileID: 988056250}\n  text: {fileID: 1107551418}\n  fileLoader: 0\n  baseUrl: http://127.0.0.1:8183\n  entryFileName: game_demo\n  useReflectBind: 1\n  sourceMap: 0\n  stacktrace: 0\n--- !u!4 &328579304\nTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 328579302}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children: []\n  m_Father: {fileID: 0}\n  m_RootOrder: 4\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n--- !u!1 &561169424\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 561169425}\n  - component: {fileID: 561169427}\n  - component: {fileID: 561169426}\n  m_Layer: 5\n  m_Name: Handle\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!224 &561169425\nRectTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 561169424}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children: []\n  m_Father: {fileID: 1034749990}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n  m_AnchorMin: {x: 0, y: 0}\n  m_AnchorMax: {x: 0, y: 0}\n  m_AnchoredPosition: {x: 0, y: 0}\n  m_SizeDelta: {x: 20, y: 20}\n  m_Pivot: {x: 0.5, y: 0.5}\n--- !u!114 &561169426\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 561169424}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_Material: {fileID: 0}\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_RaycastTarget: 1\n  m_OnCullStateChanged:\n    m_PersistentCalls:\n      m_Calls: []\n    m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI,\n      Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\n  m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0}\n  m_Type: 1\n  m_PreserveAspect: 0\n  m_FillCenter: 1\n  m_FillMethod: 4\n  m_FillAmount: 1\n  m_FillClockwise: 1\n  m_FillOrigin: 0\n  m_UseSpriteMesh: 0\n--- !u!222 &561169427\nCanvasRenderer:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 561169424}\n  m_CullTransparentMesh: 0\n--- !u!1 &651251475\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 651251478}\n  - component: {fileID: 651251477}\n  - component: {fileID: 651251476}\n  m_Layer: 0\n  m_Name: EventSystem\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!114 &651251476\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 651251475}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 1077351063, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_HorizontalAxis: Horizontal\n  m_VerticalAxis: Vertical\n  m_SubmitButton: Submit\n  m_CancelButton: Cancel\n  m_InputActionsPerSecond: 10\n  m_RepeatDelay: 0.5\n  m_ForceModuleActive: 0\n--- !u!114 &651251477\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 651251475}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: -619905303, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_FirstSelected: {fileID: 0}\n  m_sendNavigationEvents: 1\n  m_DragThreshold: 10\n--- !u!4 &651251478\nTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 651251475}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children: []\n  m_Father: {fileID: 0}\n  m_RootOrder: 3\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n--- !u!1 &705507993\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 705507995}\n  - component: {fileID: 705507994}\n  m_Layer: 0\n  m_Name: Directional Light\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!108 &705507994\nLight:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 705507993}\n  m_Enabled: 1\n  serializedVersion: 9\n  m_Type: 1\n  m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1}\n  m_Intensity: 1\n  m_Range: 10\n  m_SpotAngle: 30\n  m_InnerSpotAngle: 21.80208\n  m_CookieSize: 10\n  m_Shadows:\n    m_Type: 2\n    m_Resolution: -1\n    m_CustomResolution: -1\n    m_Strength: 1\n    m_Bias: 0.05\n    m_NormalBias: 0.4\n    m_NearPlane: 0.2\n    m_CullingMatrixOverride:\n      e00: 1\n      e01: 0\n      e02: 0\n      e03: 0\n      e10: 0\n      e11: 1\n      e12: 0\n      e13: 0\n      e20: 0\n      e21: 0\n      e22: 1\n      e23: 0\n      e30: 0\n      e31: 0\n      e32: 0\n      e33: 1\n    m_UseCullingMatrixOverride: 0\n  m_Cookie: {fileID: 0}\n  m_DrawHalo: 0\n  m_Flare: {fileID: 0}\n  m_RenderMode: 0\n  m_CullingMask:\n    serializedVersion: 2\n    m_Bits: 4294967295\n  m_RenderingLayerMask: 1\n  m_Lightmapping: 1\n  m_LightShadowCasterMode: 0\n  m_AreaSize: {x: 1, y: 1}\n  m_BounceIntensity: 1\n  m_ColorTemperature: 6570\n  m_UseColorTemperature: 0\n  m_BoundingSphereOverride: {x: 0, y: 0, z: 0, w: 0}\n  m_UseBoundingSphereOverride: 0\n  m_ShadowRadius: 0\n  m_ShadowAngle: 0\n--- !u!4 &705507995\nTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 705507993}\n  m_LocalRotation: {x: 0.40821788, y: -0.23456968, z: 0.10938163, w: 0.8754261}\n  m_LocalPosition: {x: 0, y: 3, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children: []\n  m_Father: {fileID: 0}\n  m_RootOrder: 1\n  m_LocalEulerAnglesHint: {x: 50, y: -30, z: 0}\n--- !u!1 &963194225\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 963194228}\n  - component: {fileID: 963194227}\n  - component: {fileID: 963194226}\n  m_Layer: 0\n  m_Name: Main Camera\n  m_TagString: MainCamera\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!81 &963194226\nAudioListener:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 963194225}\n  m_Enabled: 1\n--- !u!20 &963194227\nCamera:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 963194225}\n  m_Enabled: 1\n  serializedVersion: 2\n  m_ClearFlags: 1\n  m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0}\n  m_projectionMatrixMode: 1\n  m_GateFitMode: 2\n  m_FOVAxisMode: 0\n  m_SensorSize: {x: 36, y: 24}\n  m_LensShift: {x: 0, y: 0}\n  m_FocalLength: 50\n  m_NormalizedViewPortRect:\n    serializedVersion: 2\n    x: 0\n    y: 0\n    width: 1\n    height: 1\n  near clip plane: 0.3\n  far clip plane: 1000\n  field of view: 60\n  orthographic: 1\n  orthographic size: 1.11\n  m_Depth: -1\n  m_CullingMask:\n    serializedVersion: 2\n    m_Bits: 4294967295\n  m_RenderingPath: -1\n  m_TargetTexture: {fileID: 0}\n  m_TargetDisplay: 0\n  m_TargetEye: 3\n  m_HDR: 0\n  m_AllowMSAA: 0\n  m_AllowDynamicResolution: 0\n  m_ForceIntoRT: 0\n  m_OcclusionCulling: 0\n  m_StereoConvergence: 10\n  m_StereoSeparation: 0.022\n--- !u!4 &963194228\nTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 963194225}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 1.542, y: 0.864, z: -10}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children: []\n  m_Father: {fileID: 0}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n--- !u!1 &988056246\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 988056247}\n  - component: {fileID: 988056250}\n  - component: {fileID: 988056249}\n  - component: {fileID: 988056248}\n  m_Layer: 5\n  m_Name: Scroll View\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!224 &988056247\nRectTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 988056246}\n  m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children:\n  - {fileID: 1175897590}\n  - {fileID: 1059422569}\n  - {fileID: 1337371029}\n  m_Father: {fileID: 1170572189}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n  m_AnchorMin: {x: 0, y: 0}\n  m_AnchorMax: {x: 0, y: 0}\n  m_AnchoredPosition: {x: 0, y: 0}\n  m_SizeDelta: {x: 600, y: 400}\n  m_Pivot: {x: 0, y: 0}\n--- !u!114 &988056248\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 988056246}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_Material: {fileID: 0}\n  m_Color: {r: 1, g: 1, b: 1, a: 0.392}\n  m_RaycastTarget: 1\n  m_OnCullStateChanged:\n    m_PersistentCalls:\n      m_Calls: []\n    m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI,\n      Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\n  m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0}\n  m_Type: 1\n  m_PreserveAspect: 0\n  m_FillCenter: 1\n  m_FillMethod: 4\n  m_FillAmount: 1\n  m_FillClockwise: 1\n  m_FillOrigin: 0\n  m_UseSpriteMesh: 0\n--- !u!222 &988056249\nCanvasRenderer:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 988056246}\n  m_CullTransparentMesh: 0\n--- !u!114 &988056250\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 988056246}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 1367256648, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_Content: {fileID: 1573113101}\n  m_Horizontal: 1\n  m_Vertical: 1\n  m_MovementType: 1\n  m_Elasticity: 0.1\n  m_Inertia: 1\n  m_DecelerationRate: 0.135\n  m_ScrollSensitivity: 1\n  m_Viewport: {fileID: 1175897590}\n  m_HorizontalScrollbar: {fileID: 1059422570}\n  m_VerticalScrollbar: {fileID: 1337371030}\n  m_HorizontalScrollbarVisibility: 2\n  m_VerticalScrollbarVisibility: 2\n  m_HorizontalScrollbarSpacing: -3\n  m_VerticalScrollbarSpacing: -3\n  m_OnValueChanged:\n    m_PersistentCalls:\n      m_Calls: []\n    m_TypeName: UnityEngine.UI.ScrollRect+ScrollRectEvent, UnityEngine.UI, Version=1.0.0.0,\n      Culture=neutral, PublicKeyToken=null\n--- !u!1 &1034749989\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 1034749990}\n  m_Layer: 5\n  m_Name: Sliding Area\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!224 &1034749990\nRectTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1034749989}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children:\n  - {fileID: 561169425}\n  m_Father: {fileID: 1059422569}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n  m_AnchorMin: {x: 0, y: 0}\n  m_AnchorMax: {x: 1, y: 1}\n  m_AnchoredPosition: {x: 0, y: 0}\n  m_SizeDelta: {x: -20, y: -20}\n  m_Pivot: {x: 0.5, y: 0.5}\n--- !u!1 &1059422568\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 1059422569}\n  - component: {fileID: 1059422572}\n  - component: {fileID: 1059422571}\n  - component: {fileID: 1059422570}\n  m_Layer: 5\n  m_Name: Scrollbar Horizontal\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!224 &1059422569\nRectTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1059422568}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children:\n  - {fileID: 1034749990}\n  m_Father: {fileID: 988056247}\n  m_RootOrder: 1\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n  m_AnchorMin: {x: 0, y: 0}\n  m_AnchorMax: {x: 0, y: 0}\n  m_AnchoredPosition: {x: 0, y: 0}\n  m_SizeDelta: {x: 0, y: 20}\n  m_Pivot: {x: 0, y: 0}\n--- !u!114 &1059422570\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1059422568}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: -2061169968, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_Navigation:\n    m_Mode: 3\n    m_SelectOnUp: {fileID: 0}\n    m_SelectOnDown: {fileID: 0}\n    m_SelectOnLeft: {fileID: 0}\n    m_SelectOnRight: {fileID: 0}\n  m_Transition: 1\n  m_Colors:\n    m_NormalColor: {r: 1, g: 1, b: 1, a: 1}\n    m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1}\n    m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1}\n    m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1}\n    m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608}\n    m_ColorMultiplier: 1\n    m_FadeDuration: 0.1\n  m_SpriteState:\n    m_HighlightedSprite: {fileID: 0}\n    m_PressedSprite: {fileID: 0}\n    m_SelectedSprite: {fileID: 0}\n    m_DisabledSprite: {fileID: 0}\n  m_AnimationTriggers:\n    m_NormalTrigger: Normal\n    m_HighlightedTrigger: Highlighted\n    m_PressedTrigger: Pressed\n    m_SelectedTrigger: Selected\n    m_DisabledTrigger: Disabled\n  m_Interactable: 1\n  m_TargetGraphic: {fileID: 561169426}\n  m_HandleRect: {fileID: 561169425}\n  m_Direction: 0\n  m_Value: 0\n  m_Size: 1\n  m_NumberOfSteps: 0\n  m_OnValueChanged:\n    m_PersistentCalls:\n      m_Calls: []\n    m_TypeName: UnityEngine.UI.Scrollbar+ScrollEvent, UnityEngine.UI, Version=1.0.0.0,\n      Culture=neutral, PublicKeyToken=null\n--- !u!114 &1059422571\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1059422568}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_Material: {fileID: 0}\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_RaycastTarget: 1\n  m_OnCullStateChanged:\n    m_PersistentCalls:\n      m_Calls: []\n    m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI,\n      Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\n  m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0}\n  m_Type: 1\n  m_PreserveAspect: 0\n  m_FillCenter: 1\n  m_FillMethod: 4\n  m_FillAmount: 1\n  m_FillClockwise: 1\n  m_FillOrigin: 0\n  m_UseSpriteMesh: 0\n--- !u!222 &1059422572\nCanvasRenderer:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1059422568}\n  m_CullTransparentMesh: 0\n--- !u!1 &1107551416\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 1107551417}\n  - component: {fileID: 1107551419}\n  - component: {fileID: 1107551418}\n  - component: {fileID: 1107551420}\n  - component: {fileID: 1107551421}\n  m_Layer: 5\n  m_Name: Text\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!224 &1107551417\nRectTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1107551416}\n  m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children: []\n  m_Father: {fileID: 1573113101}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n  m_AnchorMin: {x: 0, y: 0}\n  m_AnchorMax: {x: 0, y: 0}\n  m_AnchoredPosition: {x: 39.5, y: 0}\n  m_SizeDelta: {x: 59, y: 0}\n  m_Pivot: {x: 0.5, y: 0.5}\n--- !u!114 &1107551418\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1107551416}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_Material: {fileID: 0}\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_RaycastTarget: 0\n  m_OnCullStateChanged:\n    m_PersistentCalls:\n      m_Calls: []\n    m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI,\n      Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\n  m_FontData:\n    m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0}\n    m_FontSize: 14\n    m_FontStyle: 0\n    m_BestFit: 0\n    m_MinSize: 10\n    m_MaxSize: 40\n    m_Alignment: 0\n    m_AlignByGeometry: 0\n    m_RichText: 0\n    m_HorizontalOverflow: 1\n    m_VerticalOverflow: 1\n    m_LineSpacing: 1\n  m_Text: New Text\n--- !u!222 &1107551419\nCanvasRenderer:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1107551416}\n  m_CullTransparentMesh: 0\n--- !u!114 &1107551420\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1107551416}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 1741964061, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_HorizontalFit: 0\n  m_VerticalFit: 2\n--- !u!114 &1107551421\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1107551416}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: -900027084, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_EffectColor: {r: 0, g: 0, b: 0, a: 1}\n  m_EffectDistance: {x: 1, y: -1}\n  m_UseGraphicAlpha: 1\n--- !u!1 &1112847438\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 1112847442}\n  - component: {fileID: 1112847441}\n  - component: {fileID: 1112847440}\n  - component: {fileID: 1112847439}\n  m_Layer: 5\n  m_Name: Canvas\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!114 &1112847439\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1112847438}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 1301386320, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_IgnoreReversedGraphics: 1\n  m_BlockingObjects: 0\n  m_BlockingMask:\n    serializedVersion: 2\n    m_Bits: 4294967295\n--- !u!114 &1112847440\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1112847438}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 1980459831, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_UiScaleMode: 0\n  m_ReferencePixelsPerUnit: 100\n  m_ScaleFactor: 1\n  m_ReferenceResolution: {x: 800, y: 600}\n  m_ScreenMatchMode: 0\n  m_MatchWidthOrHeight: 0\n  m_PhysicalUnit: 3\n  m_FallbackScreenDPI: 96\n  m_DefaultSpriteDPI: 96\n  m_DynamicPixelsPerUnit: 1\n--- !u!223 &1112847441\nCanvas:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1112847438}\n  m_Enabled: 1\n  serializedVersion: 3\n  m_RenderMode: 0\n  m_Camera: {fileID: 0}\n  m_PlaneDistance: 100\n  m_PixelPerfect: 0\n  m_ReceivesEvents: 1\n  m_OverrideSorting: 0\n  m_OverridePixelPerfect: 0\n  m_SortingBucketNormalizedSize: 0\n  m_AdditionalShaderChannelsFlag: 0\n  m_SortingLayerID: 0\n  m_SortingOrder: 0\n  m_TargetDisplay: 0\n--- !u!224 &1112847442\nRectTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1112847438}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 0, y: 0, z: 0}\n  m_Children:\n  - {fileID: 1170572189}\n  m_Father: {fileID: 0}\n  m_RootOrder: 2\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n  m_AnchorMin: {x: 0, y: 0}\n  m_AnchorMax: {x: 0, y: 0}\n  m_AnchoredPosition: {x: 0, y: 0}\n  m_SizeDelta: {x: 0, y: 0}\n  m_Pivot: {x: 0, y: 0}\n--- !u!1 &1170572188\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 1170572189}\n  m_Layer: 5\n  m_Name: MiniConsole\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!224 &1170572189\nRectTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1170572188}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children:\n  - {fileID: 988056247}\n  m_Father: {fileID: 1112847442}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n  m_AnchorMin: {x: 0, y: 0}\n  m_AnchorMax: {x: 1, y: 1}\n  m_AnchoredPosition: {x: 0, y: 0}\n  m_SizeDelta: {x: 0, y: 0}\n  m_Pivot: {x: 0.5, y: 0.5}\n--- !u!1 &1175897589\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 1175897590}\n  - component: {fileID: 1175897593}\n  - component: {fileID: 1175897592}\n  - component: {fileID: 1175897591}\n  m_Layer: 5\n  m_Name: Viewport\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!224 &1175897590\nRectTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1175897589}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children:\n  - {fileID: 1573113101}\n  m_Father: {fileID: 988056247}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n  m_AnchorMin: {x: 0, y: 0}\n  m_AnchorMax: {x: 0, y: 0}\n  m_AnchoredPosition: {x: 0, y: 0}\n  m_SizeDelta: {x: 0, y: 0}\n  m_Pivot: {x: 0, y: 1}\n--- !u!114 &1175897591\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1175897589}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_Material: {fileID: 0}\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_RaycastTarget: 1\n  m_OnCullStateChanged:\n    m_PersistentCalls:\n      m_Calls: []\n    m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI,\n      Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\n  m_Sprite: {fileID: 10917, guid: 0000000000000000f000000000000000, type: 0}\n  m_Type: 1\n  m_PreserveAspect: 0\n  m_FillCenter: 1\n  m_FillMethod: 4\n  m_FillAmount: 1\n  m_FillClockwise: 1\n  m_FillOrigin: 0\n  m_UseSpriteMesh: 0\n--- !u!222 &1175897592\nCanvasRenderer:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1175897589}\n  m_CullTransparentMesh: 0\n--- !u!114 &1175897593\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1175897589}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: -1200242548, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_ShowMaskGraphic: 0\n--- !u!1 &1220345537\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 1220345538}\n  m_Layer: 5\n  m_Name: Sliding Area\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!224 &1220345538\nRectTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1220345537}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children:\n  - {fileID: 1385249363}\n  m_Father: {fileID: 1337371029}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n  m_AnchorMin: {x: 0, y: 0}\n  m_AnchorMax: {x: 1, y: 1}\n  m_AnchoredPosition: {x: 0, y: 0}\n  m_SizeDelta: {x: -20, y: -20}\n  m_Pivot: {x: 0.5, y: 0.5}\n--- !u!1 &1337371028\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 1337371029}\n  - component: {fileID: 1337371032}\n  - component: {fileID: 1337371031}\n  - component: {fileID: 1337371030}\n  m_Layer: 5\n  m_Name: Scrollbar Vertical\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!224 &1337371029\nRectTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1337371028}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children:\n  - {fileID: 1220345538}\n  m_Father: {fileID: 988056247}\n  m_RootOrder: 2\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n  m_AnchorMin: {x: 1, y: 0}\n  m_AnchorMax: {x: 1, y: 0}\n  m_AnchoredPosition: {x: 0, y: 0}\n  m_SizeDelta: {x: 20, y: 0}\n  m_Pivot: {x: 1, y: 1}\n--- !u!114 &1337371030\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1337371028}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: -2061169968, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_Navigation:\n    m_Mode: 3\n    m_SelectOnUp: {fileID: 0}\n    m_SelectOnDown: {fileID: 0}\n    m_SelectOnLeft: {fileID: 0}\n    m_SelectOnRight: {fileID: 0}\n  m_Transition: 1\n  m_Colors:\n    m_NormalColor: {r: 1, g: 1, b: 1, a: 1}\n    m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1}\n    m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1}\n    m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1}\n    m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608}\n    m_ColorMultiplier: 1\n    m_FadeDuration: 0.1\n  m_SpriteState:\n    m_HighlightedSprite: {fileID: 0}\n    m_PressedSprite: {fileID: 0}\n    m_SelectedSprite: {fileID: 0}\n    m_DisabledSprite: {fileID: 0}\n  m_AnimationTriggers:\n    m_NormalTrigger: Normal\n    m_HighlightedTrigger: Highlighted\n    m_PressedTrigger: Pressed\n    m_SelectedTrigger: Selected\n    m_DisabledTrigger: Disabled\n  m_Interactable: 1\n  m_TargetGraphic: {fileID: 1385249364}\n  m_HandleRect: {fileID: 1385249363}\n  m_Direction: 2\n  m_Value: 0\n  m_Size: 1\n  m_NumberOfSteps: 0\n  m_OnValueChanged:\n    m_PersistentCalls:\n      m_Calls: []\n    m_TypeName: UnityEngine.UI.Scrollbar+ScrollEvent, UnityEngine.UI, Version=1.0.0.0,\n      Culture=neutral, PublicKeyToken=null\n--- !u!114 &1337371031\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1337371028}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_Material: {fileID: 0}\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_RaycastTarget: 1\n  m_OnCullStateChanged:\n    m_PersistentCalls:\n      m_Calls: []\n    m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI,\n      Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\n  m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0}\n  m_Type: 1\n  m_PreserveAspect: 0\n  m_FillCenter: 1\n  m_FillMethod: 4\n  m_FillAmount: 1\n  m_FillClockwise: 1\n  m_FillOrigin: 0\n  m_UseSpriteMesh: 0\n--- !u!222 &1337371032\nCanvasRenderer:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1337371028}\n  m_CullTransparentMesh: 0\n--- !u!1 &1385249362\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 1385249363}\n  - component: {fileID: 1385249365}\n  - component: {fileID: 1385249364}\n  m_Layer: 5\n  m_Name: Handle\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!224 &1385249363\nRectTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1385249362}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children: []\n  m_Father: {fileID: 1220345538}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n  m_AnchorMin: {x: 0, y: 0}\n  m_AnchorMax: {x: 0, y: 0}\n  m_AnchoredPosition: {x: 0, y: 0}\n  m_SizeDelta: {x: 20, y: 20}\n  m_Pivot: {x: 0.5, y: 0.5}\n--- !u!114 &1385249364\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1385249362}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_Material: {fileID: 0}\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_RaycastTarget: 1\n  m_OnCullStateChanged:\n    m_PersistentCalls:\n      m_Calls: []\n    m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI,\n      Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\n  m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0}\n  m_Type: 1\n  m_PreserveAspect: 0\n  m_FillCenter: 1\n  m_FillMethod: 4\n  m_FillAmount: 1\n  m_FillClockwise: 1\n  m_FillOrigin: 0\n  m_UseSpriteMesh: 0\n--- !u!222 &1385249365\nCanvasRenderer:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1385249362}\n  m_CullTransparentMesh: 0\n--- !u!1 &1573113100\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 1573113101}\n  - component: {fileID: 1573113102}\n  - component: {fileID: 1573113103}\n  m_Layer: 5\n  m_Name: Content\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!224 &1573113101\nRectTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1573113100}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children:\n  - {fileID: 1107551417}\n  m_Father: {fileID: 1175897590}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n  m_AnchorMin: {x: 0, y: 1}\n  m_AnchorMax: {x: 1, y: 1}\n  m_AnchoredPosition: {x: 0, y: -0.0000121593475}\n  m_SizeDelta: {x: 0, y: 0}\n  m_Pivot: {x: 0, y: 1}\n--- !u!114 &1573113102\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1573113100}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 1297475563, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_Padding:\n    m_Left: 10\n    m_Right: 10\n    m_Top: 10\n    m_Bottom: 10\n  m_ChildAlignment: 0\n  m_Spacing: 0\n  m_ChildForceExpandWidth: 1\n  m_ChildForceExpandHeight: 1\n  m_ChildControlWidth: 1\n  m_ChildControlHeight: 0\n  m_ChildScaleWidth: 0\n  m_ChildScaleHeight: 0\n--- !u!114 &1573113103\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 1573113100}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 1741964061, guid: f70555f144d8491a825f0804e09c671c, type: 3}\n  m_Name: \n  m_EditorClassIdentifier: \n  m_HorizontalFit: 2\n  m_VerticalFit: 2\n"
  },
  {
    "path": "Assets/Examples/Scenes/SampleScene.unity.meta",
    "content": "fileFormatVersion: 2\nguid: 9fc0d4010bbf28b4594072e72b8655ab\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Scenes.meta",
    "content": "fileFormatVersion: 2\nguid: b16dd1c661dcc2f42b74ba7610d1605a\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/ArrayTest.cs",
    "content": "using QuickJS;\r\nusing System.Collections.Generic;\r\n\r\nnamespace Example\r\n{\r\n    [JSType]\r\n    public class ArrayTest\r\n    {\r\n        public static int[] values1 = { 0, 1, 2 };\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/Examples/Source/ArrayTest.cs.meta",
    "content": "fileFormatVersion: 2\nguid: f61959940ce0bf7459e31bcce09fbc36\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/AsyncTaskTest.cs",
    "content": "using QuickJS;\r\nusing System;\r\n\r\nnamespace Example\r\n{\r\n    [JSType]\r\n    public class AsyncTaskTest\r\n    {\r\n        public static System.Threading.Tasks.Task GetHostEntryAsync(string host)\r\n        {\r\n            return System.Net.Dns.GetHostEntryAsync(host);\r\n        }\r\n\r\n        public static async System.Threading.Tasks.Task SimpleTest(int ms)\r\n        {\r\n            await System.Threading.Tasks.Task.Delay(ms);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/Examples/Source/AsyncTaskTest.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 522abd5438a0da04dac1c103beb3a020\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/BasicRun.cs",
    "content": "using QuickJS.Native;\r\nusing System.Collections.Generic;\r\n\r\nnamespace Example\r\n{\r\n    using UnityEngine;\r\n\r\n    public class BasicRun : MonoBehaviour\r\n    {\r\n        public enum RunCase\r\n        {\r\n            None,\r\n            QuickJSCodebase,\r\n            Codegen,\r\n        }\r\n        public RunCase runCase;\r\n\r\n        unsafe void Start()\r\n        {\r\n            switch (runCase)\r\n            {\r\n                case RunCase.QuickJSCodebase:\r\n                    {\r\n                        var rt = JSApi.JSB_NewRuntime(null);\r\n                        JSMemoryUsage s;\r\n                        JSApi.JS_ComputeMemoryUsage(rt, &s);\r\n                        Debug.Log($\"test {rt}: {s.malloc_count} {s.malloc_size} {s.malloc_limit}\");\r\n                        var ctx = JSApi.JS_NewContext(rt);\r\n                        Debug.Log(\"test:\" + ctx);\r\n\r\n                        // // // JSApi.JS_AddIntrinsicOperators(ctx);\r\n                        // // var obj = JSApi.JS_NewObject(ctx);\r\n                        // // JSApi.JS_FreeValue(ctx, obj);\r\n\r\n                        JSApi.JS_FreeContext(ctx);\r\n                        JSApi.JSB_FreeRuntime(rt);\r\n                        Debug.Log(\"it's a good day\");\r\n                        GameObject.CreatePrimitive(PrimitiveType.Cube);\r\n                        break;\r\n                    }\r\n                case RunCase.Codegen:\r\n                    {\r\n#if !NET_STANDARD_2_0\r\n                        var options = new Dictionary<string, string>();\r\n                        System.Reflection.MethodInfo Call = null;\r\n                        using (var p = System.CodeDom.Compiler.CodeDomProvider.CreateProvider(\"cs\", options))\r\n                        {\r\n                            var compilerParameters = new System.CodeDom.Compiler.CompilerParameters();\r\n                            compilerParameters.GenerateInMemory = true;\r\n                            compilerParameters.OutputAssembly = \"_GeneratedAssembly\";\r\n                            compilerParameters.TreatWarningsAsErrors = false;\r\n                            compilerParameters.CompilerOptions = \"-unsafe\";\r\n                            compilerParameters.ReferencedAssemblies.Add(typeof(Debug).Assembly.Location);\r\n                            var result = p.CompileAssemblyFromSource(compilerParameters, @\"\r\n                            using UnityEngine;\r\n                            namespace _Hidden {\r\n                                public static class Foo {\r\n                                    public static unsafe void Call(ref int a0) {\r\n                                        Debug.Log(\"\"Hello \"\" + a0);\r\n                                        a0 += 1;\r\n                                    }\r\n                                }\r\n                            }\r\n                            \");\r\n                            if (result.Errors.HasErrors)\r\n                            {\r\n                                foreach (var err in result.Errors)\r\n                                {\r\n                                    Debug.LogError(err);\r\n                                }\r\n                            }\r\n                            else\r\n                            {\r\n                                Debug.Log($\"Assembly: {result.CompiledAssembly} {result.CompiledAssembly.IsDynamic}\");\r\n                                var Foo = result.CompiledAssembly.GetType(\"_Hidden.Foo\");\r\n                                Call = Foo.GetMethod(\"Call\");\r\n                            }\r\n                        }\r\n\r\n                        if (Call != null)\r\n                        {\r\n                            var v = 99;\r\n                            var ps = new object[] { v };\r\n                            Call.Invoke(null, ps);\r\n                            Debug.Log($\"Call: {ps[0]}\");\r\n                        }\r\n#else  \r\n                        Debug.LogError(\"CompilerCodeDomProvider is not supported in current settings (try to switch Api Compatibility Level to .NET 4.x in ProjectSettings->Player).\");\r\n#endif\r\n                        break;\r\n                    }\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/Examples/Source/BasicRun.cs.meta",
    "content": "fileFormatVersion: 2\nguid: d681b6ce2f6dd914fb897251fb0375a2\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/DefaultFileSystem.cs",
    "content": "using System;\r\nusing QuickJS.Utils;\r\nusing System.Net;\r\nusing System.IO;\r\nusing System.Text;\r\n\r\nnamespace Example\r\n{\r\n    /// <summary>\r\n    /// a simple demonstration of accessing remote file (sync)\r\n    /// </summary>\r\n    public class HttpFileSystem : IFileSystem\r\n    {\r\n        private string _url;\r\n\r\n        public HttpFileSystem(string baseUrl)\r\n        {\r\n            _url = baseUrl;\r\n        }\r\n\r\n        private string GetRemote(string path)\r\n        {\r\n            try\r\n            {\r\n                var uri = _url.EndsWith(\"/\") ? _url + path : $\"{_url}/{path}\";\r\n                var request = WebRequest.CreateHttp(uri);\r\n                var response = request.GetResponse() as HttpWebResponse;\r\n                if (response.StatusCode == HttpStatusCode.OK)\r\n                {\r\n                    var reader = new StreamReader(response.GetResponseStream());\r\n                    return reader.ReadToEnd();\r\n                }\r\n            }\r\n            catch (Exception)\r\n            {\r\n            }\r\n            return null;\r\n        }\r\n\r\n        public bool Exists(string path)\r\n        {\r\n            if (!path.EndsWith(\".js\") && !path.EndsWith(\".json\") && !path.EndsWith(\".jsonc\"))\r\n            {\r\n                return false;\r\n            }\r\n            var asset = GetRemote(path);\r\n            return asset != null;\r\n        }\r\n\r\n        public string GetFullPath(string path)\r\n        {\r\n            return path;\r\n        }\r\n\r\n        public byte[] ReadAllBytes(string path)\r\n        {\r\n            try\r\n            {\r\n                var asset = GetRemote(path);\r\n                return Encoding.UTF8.GetBytes(asset);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                QuickJS.Diagnostics.Logger.IO.Error(\"{0}: {1}\\n{2}\", path, exception.Message, exception.StackTrace);\r\n                return null;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/Examples/Source/DefaultFileSystem.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 1e6ea3cc9a7dd5c4cab48f36ea738b6c\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/DelegateTest.cs",
    "content": "using QuickJS;\r\nusing System;\r\n\r\nnamespace Example\r\n{\r\n    public delegate int WithByRefParametersCallback(int b, ref int a, out int v);\r\n\r\n    public delegate void WithByRefParametersCallback2(ref UnityEngine.Vector3 v);\r\n\r\n    [JSType]\r\n    public class DelegateTest\r\n    {\r\n        public WithByRefParametersCallback complexCall;\r\n        public WithByRefParametersCallback2 complexCall2;\r\n\r\n        public void TestComplexCall()\r\n        {\r\n            if (complexCall != null)\r\n            {\r\n                int b = 1;\r\n                int a = 2;\r\n                int v;\r\n                UnityEngine.Debug.Log($\"TestComplexCall (before): b={b} a={a}\");\r\n                int r = complexCall(b, ref a, out v);\r\n                UnityEngine.Debug.Log($\"TestComplexCall (after): b={b} a={a} v={v} r={r}\");\r\n            }\r\n\r\n            if (complexCall2 != null)\r\n            {\r\n                var v = new UnityEngine.Vector3(1f, 2f, 3f);\r\n                UnityEngine.Debug.Log($\"TestComplexCall2 (before): v={v}\");\r\n                complexCall2(ref v);\r\n                UnityEngine.Debug.Log($\"TestComplexCall2 (after): v={v}\");\r\n            }\r\n        }\r\n\r\n        public Action actionFieldRW;\r\n        public readonly Action actionFieldR;\r\n        public Action actionPropG { get; }\r\n        public Action actionPropS { set { } }\r\n        public Action actionPropGS { get; set; }\r\n\r\n        public static Action actionFieldRW_s;\r\n        public static readonly Action actionFieldR_s;\r\n        public static Action actionPropG_s { get; }\r\n        public static Action actionPropS_s { set { } }\r\n        public static Action actionPropGS_s { get; set; }\r\n\r\n        public class NotExportedClass\r\n        {\r\n            public string value = \"testcase: instance field access of the not-exported type\";\r\n            public static string value2 = \"testcase: static field access of the not-exported type\";\r\n\r\n            public int Add(int a, int b)\r\n            {\r\n                return a + b;\r\n            }\r\n        }\r\n\r\n        [JSType]\r\n        public class InnerTest\r\n        {\r\n            public const string hello = \"hello\";\r\n        }\r\n\r\n        public Action onAction;\r\n        public void AddAction()\r\n        {\r\n            onAction += () =>\r\n             {\r\n                 UnityEngine.Debug.Log(\"testcase: add C# Action to delegate, and invoke the delegate in script\");\r\n             };\r\n        }\r\n\r\n        public Action<string, float, int> onActionWithArgs;\r\n        public static Action<string, float, int> onStaticActionWithArgs;\r\n        public Func<int, int> onFunc;\r\n\r\n        public event Action<int> onEvent;\r\n        public static event Action<int> onStaticEvent;\r\n\r\n        public void DipatchEvent(int v)\r\n        {\r\n            onEvent?.Invoke(v);\r\n        }\r\n\r\n        public static void DipatchStaticEvent(int v)\r\n        {\r\n            onStaticEvent?.Invoke(v);\r\n        }\r\n\r\n        public static void UseDelegateInParameter(Action n)\r\n        {\r\n        }\r\n\r\n        public void CallAction()\r\n        {\r\n            onAction?.Invoke();\r\n        }\r\n\r\n        public static NotExportedClass GetNotExportedClass()\r\n        {\r\n            return new NotExportedClass();\r\n        }\r\n\r\n        public void CallActionWithArgs(string a1, float a2, int a3)\r\n        {\r\n            onActionWithArgs?.Invoke(a1, a2, a3);\r\n        }\r\n\r\n        public static void CallStaticActionWithArgs(string a1, float a2, int a3)\r\n        {\r\n            onStaticActionWithArgs?.Invoke(a1, a2, a3);\r\n        }\r\n\r\n        public int CallFunc(int a1)\r\n        {\r\n            return onFunc == null ? a1 : onFunc.Invoke(a1);\r\n        }\r\n\r\n        public static void CallHotfixTest()\r\n        {\r\n            var h1 = new HotfixTest();\r\n            UnityEngine.Debug.LogFormat(\"HotfixTest1: {0}\", h1.Foo(12));\r\n\r\n            var h2 = new HotfixTest2();\r\n            UnityEngine.Debug.LogFormat(\"HotfixTest2: {0}\", h2.Foo(12));\r\n        }\r\n\r\n        public static InnerTest[] GetArray()\r\n        {\r\n            return null;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/Examples/Source/DelegateTest.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 1b363762af3ef044ea184cb9587f6a51\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/DisposableObject.cs",
    "content": "using QuickJS;\r\nusing System;\r\n\r\nnamespace Example\r\n{\r\n    using UnityEngine;\r\n\r\n    /// <summary>\r\n    /// If the lifetime of C# object could be fully controlled by JS, it could be mark as disposable at runtime.\r\n    /// Or marking this type by SetDisposable in CustomBinding.\r\n    /// objects/types marked by disposable will be automatically disposed when it's corresponding JSValue being finalized <br/>\r\n    /// ** It's possible called after the script runtime being released when using v8-bridge as backend ** <br/>\r\n    /// <example>\r\n    ///     : in typescript/javascript\r\n    ///     <code>\r\n    ///         jsb.SetDisposable(inst, true); // mark instances up to you\r\n    ///     </code>\r\n    /// </example>\r\n    /// <example>\r\n    ///     : or in CustomBinding\r\n    ///     <code>\r\n    ///         bindingManager.AddExportedType(typeof(DisposableObject)).SetDisposable();\r\n    ///     </code>\r\n    /// </example>\r\n    /// <see href=\"https://github.com/ialex32x/unity-jsb/blob/c584aec2f2721faf0c76f0f80fc45f05ffd4cb26/Assets/Examples/Source/Editor/CustomBinding.cs\">Example in CustomBinding</see>\r\n    /// </summary>\r\n    public class DisposableObject : IDisposable\r\n    {\r\n        public DisposableObject()\r\n        {\r\n            Debug.Log(\"DisposableObject.Constructor\");\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n            Debug.Log(\"DisposableObject.Dispose\");\r\n        }\r\n\r\n        public static DisposableObject CreateDisposableObject()\r\n        {\r\n            return new DisposableObject();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/Examples/Source/DisposableObject.cs.meta",
    "content": "fileFormatVersion: 2\nguid: c680bf2428514d04fa76c725464df394\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/Editor/CustomBinding.cs",
    "content": "﻿using System.Reflection;\r\nusing System;\r\n\r\nnamespace Example.Editor\r\n{\r\n    using QuickJS.Unity;\r\n    using QuickJS.Binding;\r\n    using UnityEngine;\r\n\r\n    public class CustomBinding : AbstractBindingProcess\r\n    {\r\n        public override void OnPreExporting(BindingManager bindingManager)\r\n        {\r\n#if !UNITY_WEBGL\r\n            bindingManager.AddExportedRawTypes(typeof(QuickJS.Extra.WebSocket));\r\n            bindingManager.AddExportedRawTypes(typeof(QuickJS.Extra.XMLHttpRequest));\r\n#endif\r\n            // bindingManager.TryExportExtensionMethods(typeof(ExtensionTest));  // expose all extension methods\r\n            bindingManager.AddExtensionMethod<Transform>(ExtensionTest.ResetAll); // expose single extension method\r\n\r\n            bindingManager.AddExportedType(typeof(ParticleSystem));\r\n            bindingManager.AddExportedType(typeof(ParticleSystemRenderer))\r\n                .SetMemberBlocked(\"supportsMeshInstancing\")\r\n            ;\r\n            bindingManager.AddExportedType(typeof(ParticleSystem.MainModule));\r\n            bindingManager.AddExportedType(typeof(ParticleSystemSimulationSpace));\r\n            bindingManager.AddExportedType(typeof(System.Net.IPHostEntry)).SystemRuntime();\r\n\r\n            bindingManager.AddExportedType(typeof(System.DateTime)).SystemRuntime().EnableOperatorOverloading(false);\r\n            bindingManager.AddExportedType(typeof(System.IO.FileInfo)).SystemRuntime()\r\n                .SetMemberBlocked(\"GetAccessControl\")\r\n                .SetMemberBlocked(\"SetAccessControl\");\r\n            bindingManager.AddExportedType(typeof(System.IO.File)).SystemRuntime()\r\n                .SetMemberBlocked(\"GetAccessControl\")\r\n                .SetMemberBlocked(\"SetAccessControl\")\r\n                .OnFilter<MethodInfo>(info => info.GetParameters().Length == 4); // not available in .net standard 2.0\r\n\r\n            bindingManager.AddExportedType(typeof(TWrapper<int>));\r\n            bindingManager.AddExportedType(typeof(TWrapper<Vector3>));\r\n            bindingManager.AddExportedType(typeof(AnotherNamespace1.TSCodeGenTest.InnerClass<int>));\r\n            bindingManager.AddExportedType(typeof(AnotherNamespace1.TSCodeGenTest2<int>));\r\n            bindingManager.AddExportedType(typeof(AnotherNamespace1.TSCodeGenTest2<AnotherNamespace1.Dummy>));\r\n            bindingManager.AddExportedType(typeof(AnotherNamespace1.TSCodeGenTest2<AnotherNamespace1.Dummy.DummyInner>));\r\n            bindingManager.AddExportedType(typeof(AnotherNamespace1.Dummy));\r\n            bindingManager.AddExportedType(typeof(AnotherNamespace1.Dummy.DummyInner));\r\n            bindingManager.AddExportedType(typeof(AnotherNamespace2.TSCodeGenTest));\r\n            bindingManager.AddExportedType(typeof(DisposableObject)).SetDisposable();\r\n\r\n#if CUSTOM_DEF_FOO && UNITY_EDITOR\r\n            bindingManager.AddExportedType(typeof(FOO)).AddRequiredDefines(\"CUSTOM_DEF_FOO\", \"UNITY_EDITOR\")\r\n#if CUSTOM_DEF_PROP\r\n                .AddRequiredDefinesForMember(\"propValue\", \"CUSTOM_DEF_PROP\")                \r\n#endif\r\n#if CUSTOM_DEF_METHOD\r\n                .AddRequiredDefinesForMethod(t => t.GetMethod(\"Exclusive\", Type.EmptyTypes), \"CUSTOM_DEF_METHOD\")\r\n#endif\r\n            ;\r\n#endif\r\n#if CUSTOM_DEF_BAR\r\n            bindingManager.AddExportedType(typeof(BAR)).AddRequiredDefines(\"CUSTOM_DEF_BAR\");\r\n#endif\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/Examples/Source/Editor/CustomBinding.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 3bf7bfc4a3c24971a74412247f7a65f8\r\ntimeCreated: 1591768532"
  },
  {
    "path": "Assets/Examples/Source/Editor/ExampleScriptsHintDrawer.cs",
    "content": "﻿using System;\r\nusing System.IO;\r\nusing System.Linq;\r\n\r\nnamespace Example.Editor\r\n{\r\n    using UnityEngine;\r\n    using UnityEditor;\r\n\r\n    [CustomPropertyDrawer((typeof(ExampleScriptsHintAttribute)))]\r\n    public class ExampleScriptsHintDrawer : PropertyDrawer\r\n    {\r\n        private GUIContent _default = new GUIContent(\"example_none\");\r\n        private GUIContent[] _options = null;\r\n\r\n        private void RefreshOptions()\r\n        {\r\n            var ta = attribute as ExampleScriptsHintAttribute;\r\n            \r\n            _options = Directory.GetFiles(ta.path).Where(file => (file.Contains(\"example_\") || file.Contains(\"game_\")) && !file.EndsWith(\".meta\") && !file.EndsWith(\".map\"))\r\n                .Select((file, i) => new GUIContent(new FileInfo(file).Name.Replace(\".js\", \"\")))\r\n                .ToArray();\r\n\r\n            if (_options.Length == 0)\r\n            {\r\n                ArrayUtility.Add(ref _options, _default);\r\n            }\r\n        }\r\n\r\n        private int IndexOf(string v)\r\n        {\r\n            RefreshOptions();\r\n            for (int i = 0, count = _options.Length; i < count; i++)\r\n            {\r\n                if (_options[i].text == v)\r\n                {\r\n                    return i;\r\n                }\r\n            }\r\n            return -1;\r\n        }\r\n\r\n        public override void OnGUI(Rect pos, SerializedProperty property, GUIContent label)\r\n        {\r\n            EditorGUI.BeginDisabledGroup(EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode);\r\n            var index = IndexOf(property.stringValue);\r\n            index = EditorGUI.Popup(new Rect(pos.x, pos.y, pos.width - 22f, pos.height), label, index, _options);\r\n            if (GUI.Button(new Rect(pos.x + pos.width - 20f, pos.y, 20f, pos.height), \"R\"))\r\n            {\r\n                RefreshOptions();\r\n            }\r\n            property.stringValue = (index >= 0 ? _options[index] : _options[0]).text;\r\n            EditorGUI.EndDisabledGroup();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Assets/Examples/Source/Editor/ExampleScriptsHintDrawer.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 412b1acb25eb46bbb66ef6396e9a5550\r\ntimeCreated: 1599170451"
  },
  {
    "path": "Assets/Examples/Source/Editor/ExampleToggleHintDrawer.cs",
    "content": "﻿using System;\nusing System.IO;\nusing System.Linq;\n\nnamespace Example.Editor\n{\n    using UnityEngine;\n    using UnityEditor;\n\n    [CustomPropertyDrawer((typeof(ExampleToggleHintAttribute)))]\n    public class ExampleToggleHintDrawer : PropertyDrawer\n    {\n        public override void OnGUI(Rect pos, SerializedProperty property, GUIContent label)\n        {\n            var ta = attribute as ExampleToggleHintAttribute;\n            property.boolValue = EditorGUI.Toggle(pos, ta.text, property.boolValue);\n        }\n    }\n}"
  },
  {
    "path": "Assets/Examples/Source/Editor/ExampleToggleHintDrawer.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 13c827e03329f5a40a9ccb396e345871\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/Editor/MenuItemsBridge.cs",
    "content": "using System;\r\nusing System.IO;\r\nusing System.Linq;\r\n\r\nnamespace Example.Editor\r\n{\r\n    using UnityEngine;\r\n    using UnityEditor;\r\n\r\n    public class MenuItemsBridge\r\n    {\r\n        [MenuItem(\"My Examples/TestBuild\")]\r\n        public static void ShowMyEditorWindow()\r\n        {\r\n            UnityEditor.BuildPipeline.BuildPlayer(new string[] { \"Assets/Examples/Scenes/BasicRun.unity\" }, \"Build/macos.app\", BuildTarget.StandaloneOSX, BuildOptions.Development);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/Examples/Source/Editor/MenuItemsBridge.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 433eb8cf6c1989c48a61505275ec2008\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/Editor.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 5dc741e1a51a4d528bcabcab5ddc5385\r\ntimeCreated: 1591768735"
  },
  {
    "path": "Assets/Examples/Source/ExampleScriptsHintAttribute.cs",
    "content": "﻿using System;\r\nusing UnityEngine;\r\n\r\nnamespace Example\r\n{\r\n    public class ExampleScriptsHintAttribute : PropertyAttribute\r\n    {\r\n        public string path { get; set; }\r\n\r\n        public ExampleScriptsHintAttribute(string path)\r\n        {\r\n            this.path = path;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Assets/Examples/Source/ExampleScriptsHintAttribute.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 7ade51e3312a4d1197ad30a243403750\r\ntimeCreated: 1599170743"
  },
  {
    "path": "Assets/Examples/Source/ExampleToggleHintAttribute.cs",
    "content": "using System;\nusing UnityEngine;\n\nnamespace Example\n{\n    public class ExampleToggleHintAttribute : PropertyAttribute\n    {\n        public string text { get; set; }\n\n        public ExampleToggleHintAttribute(string text)\n        {\n            this.text = text;\n        }\n    }\n}"
  },
  {
    "path": "Assets/Examples/Source/ExampleToggleHintAttribute.cs.meta",
    "content": "fileFormatVersion: 2\nguid: a1183134372bcc040acfe81e535a403b\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/Experimental/CustomApiBridgeImpl.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace Example.Experimental\r\n{\r\n    using QuickJS;\r\n    using QuickJS.Native;\r\n    using QuickJS.Experimental;\r\n\r\n    public class CustomApiBridgeImpl : IJSApiBridge\r\n    {\r\n        public const string KeyForCSharpIdentity = \"__csharp_host_identity__\";\r\n\r\n        public JSPayloadHeader GetPayloadHeader(ScriptContext context, JSValue val)\r\n        {\r\n            JSContext ctx = context;\r\n            bool valueDuplicated = false;\r\n\r\n            if (val.IsObject())\r\n            {\r\n                var identityAtom = context.GetAtom(KeyForCSharpIdentity);\r\n                var identity = JSApi.JS_GetProperty(ctx, val, identityAtom);\r\n                if (!identity.IsNullish())\r\n                {\r\n                    val = identity;\r\n                    valueDuplicated = true;\r\n                }\r\n            }\r\n\r\n            var header = JSApi.jsb_get_payload_header(ctx, val);\r\n\r\n            if (valueDuplicated)\r\n            {\r\n                JSApi.JS_FreeValue(ctx, val);\r\n            }\r\n            return header;\r\n        }\r\n\r\n        public JSValue NewBridgeObject(ScriptContext context, object o, JSValue proto)\r\n        {\r\n            var cache = context.GetObjectCache();\r\n            var object_id = cache.AddObject(o, false);\r\n            var val = JSApi.jsb_new_bridge_object(context, proto, object_id);\r\n\r\n            if (val.IsException())\r\n            {\r\n                cache.RemoveObject(object_id);\r\n            }\r\n            else\r\n            {\r\n                if (typeof(IDictionary<string, object>).IsAssignableFrom(o.GetType()))\r\n                {\r\n                    var proxy = CreateDictionaryProxy(context, val);\r\n                    if (proxy.IsException())\r\n                    {\r\n                        JSApi.JS_FreeValue(context, proxy);\r\n                        cache.RemoveObject(object_id);\r\n                        return proxy;\r\n                    }\r\n                    val = proxy;\r\n                }\r\n                cache.AddJSValue(o, val);\r\n            }\r\n\r\n            return val;\r\n        }\r\n\r\n        private static unsafe JSValue CreateDictionaryProxy(ScriptContext _context, JSValue target)\r\n        {\r\n            var ctx = (JSContext)_context;\r\n\r\n            var createDictionaryProxy = _context.EvalSource<ScriptFunction>(@\"\r\nfunction createDictionaryProxy (targetProxy, contains, getter, setter, remover, keys) {\r\n    return new Proxy(targetProxy, {\r\n        get(target, key, receiver) {\r\n            if(key === '\" + KeyForCSharpIdentity + @\"') return target;\r\n\r\n            if(typeof key === 'string' && contains(target, key)) return getter(target, key);\r\n            var res = target[key];\r\n            return res;\r\n        },\r\n        set(target, key, value) {\r\n            if(typeof key === 'string') setter(target, key, value);\r\n            else target[key] = value;\r\n            return true;\r\n        },\r\n        has(target, key) {\r\n            return contains(target, key);\r\n        },\r\n        deleteProperty(target, key) {\r\n            remover(target, key);\r\n            return true;\r\n        },\r\n        ownKeys(target) {\r\n            return keys(target);\r\n        },\r\n        getOwnPropertyDescriptor(target, key) {\r\n            if(typeof key === 'string' && contains(target, key)) {\r\n                return {\r\n                  value: getter(target, key),\r\n                  enumerable: true,\r\n                  configurable: true\r\n                };\r\n            }\r\n            return undefined;\r\n        },\r\n    });\r\n}\r\n\r\ncreateDictionaryProxy;\r\n\", \"createDictionaryProxy\");\r\n\r\n            var contains = new Func<IDictionary<string, object>, string, bool>(\r\n                (IDictionary<string, object> dc, string key) =>\r\n                {\r\n                    return key != null && dc.ContainsKey(key);\r\n                });\r\n\r\n            var getter = new Func<IDictionary<string, object>, string, object>(\r\n                (IDictionary<string, object> dc, string key) =>\r\n                {\r\n                    return dc[key];\r\n                });\r\n\r\n            var setter = new Action<IDictionary<string, object>, string, object>(\r\n                (IDictionary<string, object> dc, string key, object value) =>\r\n                {\r\n                    dc[key] = value;\r\n                });\r\n\r\n            var remover = new Action<IDictionary<string, object>, string>(\r\n                (IDictionary<string, object> dc, string key) =>\r\n                {\r\n                    dc.Remove(key);\r\n                });\r\n\r\n            var keys = new Func<IDictionary<string, object>, object>(\r\n                (IDictionary<string, object> dc) =>\r\n                {\r\n                    var items = dc.Keys;\r\n                    var len = items.Count;\r\n                    var arr = new string[len];\r\n                    var i = 0;\r\n                    foreach (var item in items)\r\n                        arr[i++] = item;\r\n                    return arr;\r\n                });\r\n\r\n            var prs = new object[] {\r\n                target,\r\n                contains,\r\n                getter,\r\n                setter,\r\n                remover,\r\n                keys,\r\n            };\r\n\r\n            var _proxy = createDictionaryProxy.Invoke<ScriptValue>(prs);\r\n\r\n            var res = JSApi.JS_DupValue(ctx, _proxy);\r\n            _proxy.Dispose();\r\n            createDictionaryProxy.Dispose();\r\n            JSApi.JS_FreeValue(ctx, target);\r\n            return res;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/Examples/Source/Experimental/CustomApiBridgeImpl.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 34dfd204ac77ee5438fe2a077b0c2f20\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/Experimental.meta",
    "content": "fileFormatVersion: 2\nguid: a9a815ce4e4ac8449a4b3b3e2e1af2ad\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/ExtensionTest.cs",
    "content": "using QuickJS;\r\nusing System;\r\n\r\nnamespace Example\r\n{\r\n    using UnityEngine;\r\n\r\n    /// <summary>\r\n    /// demonstrates how to export extension methods\r\n    /// <see href=\"https://github.com/ialex32x/unity-jsb/blob/c584aec2f2721faf0c76f0f80fc45f05ffd4cb26/Assets/Examples/Source/Editor/CustomBinding.cs\">Example in CustomBinding</see>\r\n    /// </summary>\r\n    public static class ExtensionTest\r\n    {\r\n        public static void ResetAll(this Transform transform)\r\n        {\r\n            transform.localPosition = Vector3.zero;\r\n            transform.localRotation = Quaternion.identity;\r\n            transform.localScale = Vector3.one;\r\n        }\r\n\r\n        public static void TestWithArgs(this Transform transform, Vector3 pos, Quaternion rot, Vector3 scale)\r\n        {\r\n            transform.localPosition = pos;\r\n            transform.localRotation = rot;\r\n            transform.localScale = scale;\r\n        }\r\n\r\n        public static bool TestWithArgsAndOut(this Transform transform, Vector3 pos, Quaternion rot, Vector3 scale, out float dist)\r\n        {\r\n            transform.localPosition = pos;\r\n            transform.localRotation = rot;\r\n            transform.localScale = scale;\r\n            dist = pos.magnitude;\r\n            return true;\r\n        }\r\n\r\n        public static void TestWithScriptObject(this Transform transform, ScriptFunction function)\r\n        {\r\n            function?.Invoke();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/Examples/Source/ExtensionTest.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 9489113c94de56545b6a5784ff759b4b\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/HotfixTest.cs",
    "content": "using System;\r\nusing UnityEngine;\r\nusing QuickJS;\r\n\r\n#pragma warning disable CS0414\r\n\r\n[JSHotfix(JSHotfixFlags.Full)]\r\npublic class HotfixTest\r\n{\r\n    private int value = 12;\r\n    private static string static_value = \"<私有静态变量>\";\r\n\r\n    public HotfixTest()\r\n    {\r\n        Debug.LogFormat(\"[HOTFIX][C#] 构造函数\");\r\n    }\r\n\r\n    public int Foo(int x)\r\n    {\r\n        Debug.LogFormat(\"[HOTFIX][C#] HotfixTest.Foo({0})\", x);\r\n        return x;\r\n    }\r\n\r\n    public string Foo(string x)\r\n    {\r\n        Debug.LogFormat(\"[HOTFIX][C#] HotfixTest.Foo({0})\", x);\r\n        return x;\r\n    }\r\n\r\n    public static void SimpleStaticCall()\r\n    {\r\n        Debug.LogWarningFormat(\"[HOTFIX][C#] HotfixTest.SimpleStaticCall()\");\r\n    }\r\n\r\n    public static void AnotherStaticCall()\r\n    {\r\n        Debug.LogWarningFormat(\"[HOTFIX][C#] HotfixTest.AnotherStaticCall()\");\r\n    }\r\n}\r\n\r\n[JSHotfix]\r\n[JSType]\r\npublic class HotfixTest2\r\n{\r\n    private int value = 12;\r\n\r\n    // 暂时不支持\r\n    public void CallByRef(out int v)\r\n    {\r\n        v = 1;\r\n    }\r\n\r\n    public int Foo(int x)\r\n    {\r\n        Debug.LogFormat(\"HotfixTest2 Original Foo Method Impl Return {0}\", x);\r\n        return x;\r\n    }\r\n}\r\n\r\npublic class NotExportedClass\r\n{\r\n    private int _value;\r\n\r\n    public int value\r\n    {\r\n        get { return _value; }\r\n        set { _value = value; }\r\n    }\r\n\r\n    public void Foo()\r\n    {\r\n        Debug.Log(\"NotExportedClass.Foo\");\r\n    }\r\n}\r\n\r\n#pragma warning restore CS0414\r\n"
  },
  {
    "path": "Assets/Examples/Source/HotfixTest.cs.meta",
    "content": "fileFormatVersion: 2\nguid: ffe9915e79112534dae52315185b13de\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/InterfaceTest.cs",
    "content": "using QuickJS;\r\n\r\n/// <summary>\r\n/// demonstrates the binding of types implementing interfaces\r\n/// </summary>\r\n[JSType]\r\npublic interface MyInterface\r\n{\r\n    void Foo();\r\n}\r\n\r\n[JSType]\r\npublic class MyClass : MyInterface\r\n{\r\n    public void Foo()\r\n    {\r\n        UnityEngine.Debug.Log(\"MyClassFoo\");\r\n    }\r\n\r\n    public static MyInterface GetMyInterface()\r\n    {\r\n        return new MyClass();\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/Examples/Source/InterfaceTest.cs.meta",
    "content": "fileFormatVersion: 2\nguid: b03bc62ee8c32fc4bbc55677fe485f72\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/NamespaceAndInnerClassTest.cs",
    "content": "using QuickJS;\r\nusing System;\r\n\r\nnamespace Example.New.World\r\n{\r\n    /// <summary>\r\n    /// demonstrates nested types\r\n    /// </summary>\r\n    [JSType]\r\n    public class Galaxy\r\n    {\r\n        public static string GetName() { return nameof(Galaxy); }\r\n\r\n        [JSType]\r\n        public class Sun\r\n        {\r\n            public static string GetName() { return nameof(Sun); }\r\n        }\r\n\r\n        [JSType]\r\n        public class Earth\r\n        {\r\n            public static string GetName() { return nameof(Earth); }\r\n\r\n            public Sun GetSun() { return new Sun(); }\r\n\r\n            public Continent[] GetContinents() { return new Continent[] { new Continent(), new Continent() }; }\r\n\r\n            [JSType]\r\n            public class Ocean\r\n            {\r\n                public static string GetName() { return nameof(Ocean); }\r\n            }\r\n\r\n            [JSType]\r\n            public class Continent\r\n            {\r\n                public static string GetName() { return nameof(Continent); }\r\n            }\r\n        }\r\n    }\r\n\r\n    [JSType]\r\n    public class IncompatibleOverloadTest1\r\n    {\r\n        public void Test()\r\n        {\r\n        }\r\n    }\r\n\r\n    [JSType]\r\n    public class IncompatibleOverloadTest2 : IncompatibleOverloadTest1\r\n    {\r\n        public void Test(int a)\r\n        {\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/Examples/Source/NamespaceAndInnerClassTest.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 1c5f1f2cc156b404aaf5fcb4ce937ce4\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/NativeFileUtil.cs",
    "content": "using System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\n\r\nnamespace Example\r\n{\r\n    using System.Runtime.InteropServices;\r\n    using size_t = QuickJS.Native.size_t;\r\n\r\n    // ! ONLY FOR DEVELOPMENT !\r\n    /// <summary>\r\n    /// read content of file without io-exception of sharing violation (if you use System.IO.File)\r\n    /// </summary>\r\n    [QuickJS.JSType]\r\n    public static class NativeFileUtil\r\n    {\r\n        [DllImport(\"msvcrt.dll\", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]\r\n        private static extern IntPtr fopen(string filename, string mode);\r\n\r\n        [DllImport(\"msvcrt.dll\", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]\r\n        private static extern unsafe size_t fread(byte* buffer, size_t elemSize, size_t elemCount, IntPtr fd);\r\n\r\n        [DllImport(\"msvcrt.dll\", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]\r\n        private static extern Int32 fclose(IntPtr fd);\r\n\r\n        public static string ReadAllText(string path)\r\n        {\r\n            return System.Text.Encoding.UTF8.GetString(ReadAllBytes(path));\r\n        }\r\n\r\n        private static unsafe byte[] _ReadAllBytes(string path)\r\n        {\r\n            var fd = IntPtr.Zero;\r\n            try\r\n            {\r\n                var size = 4096;\r\n                var buffer = new byte[size];\r\n                var stream = new MemoryStream();\r\n                fd = fopen(path, \"rb\");\r\n                if (fd == IntPtr.Zero)\r\n                {\r\n                    throw new FileLoadException(\"fopen failed\", path);\r\n                }\r\n\r\n                while (true)\r\n                {\r\n                    fixed (byte* p = buffer)\r\n                    {\r\n                        var rd = fread(p, 1, size, fd);\r\n                        if (rd <= 0)\r\n                        {\r\n                            break;\r\n                        }\r\n\r\n                        stream.Write(buffer, 0, rd);\r\n                    }\r\n                }\r\n\r\n                return stream.ToArray();\r\n            }\r\n            finally\r\n            {\r\n                fclose(fd);\r\n            }\r\n        }\r\n\r\n        public static unsafe byte[] ReadAllBytes(string path)\r\n        {\r\n            try\r\n            {\r\n                return _ReadAllBytes(path);\r\n            }\r\n            catch (Exception)\r\n            {\r\n                using (var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))\r\n                {\r\n                    var bytes = new byte[stream.Length];\r\n                    stream.Read(bytes, 0, bytes.Length);\r\n                    return bytes;\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/Examples/Source/NativeFileUtil.cs.meta",
    "content": "fileFormatVersion: 2\nguid: b98eb3e8b19eada49b619353f65653c1\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/NoNamespace.cs",
    "content": "\r\n// testcase: exporting class with parent class excluded\r\n\r\npublic class NoNamespaceBase\r\n{\r\n}\r\n\r\n[QuickJS.JSType]\r\npublic class NoNamespaceClass : NoNamespaceBase\r\n{\r\n    public static void V1(UnityEngine.Vector3 v) { }\r\n    public static void V1(UnityEngine.Vector2 v) { }\r\n\r\n    public static void Moo()\r\n    {\r\n    }\r\n\r\n    public static byte[] MakeBytes()\r\n    {\r\n        return System.Text.Encoding.UTF8.GetBytes(\"sdfasdf\");\r\n    }\r\n\r\n    public static byte[] TestBytes(byte[] test)\r\n    {\r\n        return test;\r\n    }\r\n\r\n    public static void TestOut(out int x, int y, out int z)\r\n    {\r\n        x = y;\r\n        z = y;\r\n    }\r\n\r\n    public static void TestOut(out string x, int y, out string z)\r\n    {\r\n        x = y.ToString();\r\n        z = y.ToString();\r\n    }\r\n\r\n    public static void TestRefOut(ref int g, out int x, int y, out int z)\r\n    {\r\n        x = y * g;\r\n        z = y + g;\r\n        g = x + z;\r\n    }\r\n\r\n    public static int? TestNullable(int? x, int? y)\r\n    {\r\n        return (x ?? 0) + (y ?? 0);\r\n    }\r\n\r\n    public static float? TestNullable(UnityEngine.Vector2? xy)\r\n    {\r\n        return xy != null ? null : (float?)((UnityEngine.Vector2)xy).magnitude;\r\n    }\r\n\r\n    public static float? TestNullable(UnityEngine.Vector2? xy, ref float? g)\r\n    {\r\n        g = UnityEngine.Random.value;\r\n        return xy != null ? null : (float?)((UnityEngine.Vector2)xy).magnitude;\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/Examples/Source/NoNamespace.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 023d6cfb9804fc84d8c5b8eb180db2c0\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/Sample.cs",
    "content": "using System;\r\nusing QuickJS;\r\nusing QuickJS.Binding;\r\nusing QuickJS.Utils;\r\nusing QuickJS.IO;\r\nusing QuickJS.Extra;\r\nusing QuickJS.Unity;\r\n\r\nnamespace Example\r\n{\r\n    using UnityEngine;\r\n\r\n    // test\r\n    public class Sample : MonoBehaviour\r\n    {\r\n        public enum FileLoader\r\n        {\r\n            Default,\r\n            Resources,\r\n            Http,\r\n        }\r\n        public UnityEngine.UI.ScrollRect scrollRect;\r\n        public UnityEngine.UI.Text text;\r\n        public FileLoader fileLoader;\r\n        public string baseUrl = \"http://127.0.0.1:8183\";\r\n        [ExampleScriptsHint(\"Scripts/out\")]\r\n        public string entryFileName = \"example_main.js\";\r\n        [ExampleToggleHint(\"ReflectBind Mode\")]\r\n        public bool useReflectBind;\r\n        // public bool sourceMap; // temporarily removed\r\n        public bool stacktrace;\r\n\r\n        /// <summary>\r\n        /// only supported with v8-bridge\r\n        /// </summary>\r\n        public bool withDebugServer = true;\r\n        public int debugServerPort = 9229;\r\n        \r\n        /// <summary>\r\n        /// script runtime will complete the initialization process until the debugger is actually connected\r\n        /// @seealso ScriptRuntimeArgs.waitingForDebugger\r\n        /// </summary>\r\n        public bool waitingForDebugger = false;\r\n\r\n        private ScriptRuntime _rt;\r\n        private MiniConsole _mConsole;\r\n\r\n        void Awake()\r\n        {\r\n            IFileSystem fileSystem;\r\n\r\n            _mConsole = new MiniConsole(scrollRect, text, 100);\r\n            _rt = ScriptEngine.CreateRuntime();\r\n            var asyncManager = new DefaultAsyncManager();\r\n            var pathResolver = new PathResolver();\r\n            pathResolver.AddSearchPath(\"node_modules\");\r\n\r\n            if (fileLoader == FileLoader.Resources)\r\n            {\r\n                fileSystem = new ResourcesFileSystem();\r\n\r\n                // it's the relative path under Unity Resources directory space\r\n                pathResolver.AddSearchPath(\"dist\");\r\n            }\r\n            else if (fileLoader == FileLoader.Http)\r\n            {\r\n                fileSystem = new HttpFileSystem(baseUrl);\r\n            }\r\n            else\r\n            {\r\n                // the DefaultFileSystem only demonstrates the minimalistic implementation of file access, it's usually enough for development in editor.\r\n                // you should implement your own filesystem layer for the device-end runtime (based on AssetBundle or zip)\r\n                fileSystem = new DefaultFileSystem();\r\n                pathResolver.AddSearchPath(\"Scripts/out\");\r\n                // pathResolver.AddSearchPath(\"../Scripts/out\");\r\n                // _rt.AddSearchPath(\"Assets/Examples/Scripts/dist\");\r\n            }\r\n\r\n            _rt.withStacktrace = stacktrace;\r\n            // if (sourceMap)\r\n            // {\r\n            // _rt.EnableSourceMap();\r\n            // }\r\n            _rt.AddModuleResolvers();\r\n            _rt.OnInitialized += OnInitialized;\r\n            _rt.Initialize(new ScriptRuntimeArgs\r\n            {\r\n                withDebugServer = withDebugServer,\r\n                waitingForDebugger = waitingForDebugger, \r\n                debugServerPort = debugServerPort,\r\n                fileSystem = fileSystem,\r\n                pathResolver = pathResolver,\r\n                asyncManager = asyncManager,\r\n                byteBufferAllocator = new ByteBufferPooledAllocator(),\r\n                binder = DefaultBinder.GetBinder(useReflectBind),\r\n                // apiBridge = new Experimental.CustomApiBridgeImpl(),\r\n            });\r\n        }\r\n\r\n        private void OnInitialized(ScriptRuntime obj)\r\n        {\r\n            Debug.LogFormat(\"run main script: {0}\", entryFileName);\r\n            _rt.EvalMain(entryFileName);\r\n        }\r\n\r\n        void Update()\r\n        {\r\n            if (_rt != null)\r\n            {\r\n                _rt.Update((int)(Time.deltaTime * 1000f));\r\n            }\r\n        }\r\n\r\n        void OnDestroy()\r\n        {\r\n            ScriptEngine.Shutdown();\r\n            GC.Collect();\r\n            GC.WaitForPendingFinalizers();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Assets/Examples/Source/Sample.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 08b53751862e51a46a4cfe8e661faac4\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/SampleBehaviour.cs",
    "content": "using UnityEngine;\r\nusing QuickJS;\r\nusing QuickJS.Native;\r\nusing QuickJS.Binding;\r\n\r\n[JSType]\r\npublic class SampleBehaviour : MonoBehaviour\r\n{\r\n    private TypedScriptPromise<string> _p;\r\n\r\n    /// <summary>\r\n    /// Define a primitive JSCFunction in C# by yourself, this function will be exported to JS directly without any wrapping glue code. \r\n    /// !CAUTION! improper operation ref count of JSValue may crash the engine\r\n    /// </summary>\r\n    [JSCFunction(\"(a: string, b: number): void\")]\r\n    public static JSValue PrimitiveCall(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n    {\r\n        // do something you want here\r\n        return JSApi.JS_UNDEFINED;\r\n    }\r\n\r\n    public TypedScriptPromise<string> SimpleWait(ScriptContext ctx, int t)\r\n    {\r\n        if (_p != null)\r\n        {\r\n            return null;\r\n        }\r\n\r\n        _p = new TypedScriptPromise<string>(ctx);\r\n        return _p;\r\n    }\r\n\r\n    public AnyScriptPromise AnotherWait(ScriptContext ctx, int t)\r\n    {\r\n        var p = new AnyScriptPromise(ctx);\r\n        StartCoroutine(_WaitForResolve(() => p.Resolve()));\r\n        return p;\r\n    }\r\n\r\n    private System.Collections.IEnumerator _WaitForResolve(System.Action p)\r\n    {\r\n        yield return new WaitForSeconds(3f);\r\n        p();\r\n    }\r\n\r\n    void OnGUI()\r\n    {\r\n        var p = _p;\r\n        if (p == null)\r\n        {\r\n            return;\r\n        }\r\n\r\n        if (GUILayout.Button(\"Resolve\"))\r\n        {\r\n            _p = null;\r\n            p.Resolve(\"You clicked 'Resolve' (this is a string from C#)\");\r\n        }\r\n\r\n        if (GUILayout.Button(\"Reject\"))\r\n        {\r\n            _p = null;\r\n            p.Reject(\"You clicked 'Reject' (this is a string from C#)\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Assets/Examples/Source/SampleBehaviour.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 7426b3ed7f2bc134bb2ff83bc45dca21\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/TWrapper.cs",
    "content": "\r\npublic class TWrapper<T>\r\n{\r\n    private T _obj;\r\n\r\n    public TWrapper(T obj)\r\n    {\r\n        _obj = obj;\r\n    }\r\n\r\n    public T GetValue()\r\n    {\r\n        return _obj;\r\n    }\r\n\r\n    public void SetValue(T obj)\r\n    {\r\n        _obj = obj;\r\n    }\r\n\r\n    public static TWrapper<int> GetIntWrapper()\r\n    {\r\n        return null;\r\n    }\r\n}\r\n\r\nnamespace AnotherNamespace1\r\n{\r\n    public class Dummy\r\n    {\r\n        public class DummyInner\r\n        {\r\n\r\n        }\r\n    }\r\n\r\n    public class TSCodeGenTest\r\n    {\r\n        public class InnerClass<T>\r\n        {\r\n            public static TWrapper<T> GetIntWrapper()\r\n            {\r\n                return null;\r\n            }\r\n        }\r\n    }\r\n\r\n    public class TSCodeGenTest2<T>\r\n    {\r\n        public T GetValue()\r\n        {\r\n            return default(T);\r\n        }\r\n    }\r\n}\r\n\r\nnamespace AnotherNamespace2\r\n{\r\n    public class TSCodeGenTest\r\n    {\r\n        //TODO ts codegen support\r\n        public static AnotherNamespace1.TSCodeGenTest.InnerClass<int> GetInnerClass()\r\n        {\r\n            return null;\r\n        }\r\n\r\n        public static AnotherNamespace1.TSCodeGenTest2<int> GetTSCodeGenTest2()\r\n        {\r\n            return null;\r\n        }\r\n\r\n        public static AnotherNamespace1.TSCodeGenTest2<AnotherNamespace1.Dummy> GetTSCodeGenTest2Dummy()\r\n        {\r\n            return null;\r\n        }\r\n\r\n        public static AnotherNamespace1.TSCodeGenTest2<AnotherNamespace1.Dummy.DummyInner> GetTSCodeGenTest2DummyInner()\r\n        {\r\n            return null;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Assets/Examples/Source/TWrapper.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 3f0ca5850a962b44ab8e5b877c6f079a\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source/ValueTest.cs",
    "content": "using QuickJS;\r\nusing System;\r\n\r\nnamespace Example\r\n{\r\n    [JSType]\r\n    public class Jankfest\r\n    {\r\n        // the generated glue code for this function will use the given cast operation functions in ValueTest below\r\n        // it means you could extend your custom type cast operations out of jsb's assembly\r\n        public static Jankfest DoNothing(Jankfest jankfest)\r\n        {\r\n            return jankfest;\r\n        }\r\n    }\r\n\r\n    [JSType]\r\n    public class ValueTest\r\n    {\r\n        // test for external definition of type cast operation\r\n        public static QuickJS.Native.JSValue js_push_classvalue(QuickJS.Native.JSContext ctx, Jankfest o)\r\n        {\r\n            return QuickJS.Native.JSApi.JS_NewInt32(ctx, 1);\r\n        }\r\n\r\n        public static bool js_get_classvalue(QuickJS.Native.JSContext ctx, QuickJS.Native.JSValue val, out Jankfest o)\r\n        {\r\n            o = new Jankfest();\r\n            return true;\r\n        }\r\n\r\n        public static void TakeStringWithCache([JSUseStringCache] string v)\r\n        {\r\n        }\r\n\r\n        public static void TakeString(string v)\r\n        {\r\n        }\r\n\r\n        public override string ToString()\r\n        {\r\n            throw new Exception(\"the intentionally thrown error\");\r\n        }\r\n\r\n        [return: JSUseStringCache]\r\n        public static string Foo([JSUseStringCache] string v)\r\n        {\r\n            return v;\r\n        }\r\n\r\n        public static bool CheckArgs(int a, out float b, ref string c)\r\n        {\r\n            b = 1f;\r\n            return true;\r\n        }\r\n\r\n        public static bool CheckArgs(int a, out float b, ref UnityEngine.GameObject c)\r\n        {\r\n            b = 1f;\r\n            return true;\r\n        }\r\n\r\n        public static void MakeTrouble()\r\n        {\r\n            throw new InvalidOperationException();\r\n        }\r\n\r\n        public static int[] values1 = new int[6] { 0, 1, 2, 3, 5, 6 };\r\n\r\n        public static int[,] values2 = new int[2, 3] {\r\n            { 0, 1, 2 },\r\n            { 3, 4, 5 },\r\n        };\r\n    }\r\n\r\n#if CUSTOM_DEF_FOO && UNITY_EDITOR\r\n    /// <summary>\r\n    /// If the target type is defined only with specific define-symbols, you can export it with ```AddRequiredDefines```. \r\n    /// <see href=\"https://github.com/ialex32x/unity-jsb/blob/c584aec2f2721faf0c76f0f80fc45f05ffd4cb26/Assets/Examples/Source/Editor/CustomBinding.cs\">Example in CustomBinding</see>\r\n    /// </summary>\r\n    public class FOO\r\n    {\r\n#if CUSTOM_DEF_PROP\r\n        public string propValue {get; set;}\r\n#endif\r\n        \r\n        public static string value = \"FOO\";\r\n\r\n#if CUSTOM_DEF_METHOD\r\n        public static void Exclusive()\r\n        {\r\n        }\r\n#endif\r\n        public static void Exclusive(int i32)\r\n        {\r\n        }\r\n    }\r\n#endif\r\n\r\n#if CUSTOM_DEF_BAR\r\n    public class BAR\r\n    {\r\n        public static string value = \"BAR\";\r\n    }\r\n#endif\r\n}\r\n"
  },
  {
    "path": "Assets/Examples/Source/ValueTest.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 83c44042a217d3f43843670d4912b1f6\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Source.meta",
    "content": "fileFormatVersion: 2\nguid: 67423b55dbe180447a1a767634b8b99c\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Anim Controller.controller",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1102 &-7761859382232492428\nAnimatorState:\n  serializedVersion: 5\n  m_ObjectHideFlags: 1\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_Name: Hit\n  m_Speed: 1\n  m_CycleOffset: 0\n  m_Transitions: []\n  m_StateMachineBehaviours: []\n  m_Position: {x: 50, y: 50, z: 0}\n  m_IKOnFeet: 0\n  m_WriteDefaultValues: 1\n  m_Mirror: 0\n  m_SpeedParameterActive: 0\n  m_MirrorParameterActive: 0\n  m_CycleOffsetParameterActive: 0\n  m_TimeParameterActive: 0\n  m_Motion: {fileID: 7400000, guid: d83b92a5c635ae14e8ccd364a7b0afae, type: 2}\n  m_Tag: \n  m_SpeedParameter: \n  m_MirrorParameter: \n  m_CycleOffsetParameter: \n  m_TimeParameter: \n--- !u!1102 &-6652583987855233881\nAnimatorState:\n  serializedVersion: 5\n  m_ObjectHideFlags: 1\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_Name: Run\n  m_Speed: 1\n  m_CycleOffset: 0\n  m_Transitions: []\n  m_StateMachineBehaviours: []\n  m_Position: {x: 50, y: 50, z: 0}\n  m_IKOnFeet: 0\n  m_WriteDefaultValues: 1\n  m_Mirror: 0\n  m_SpeedParameterActive: 0\n  m_MirrorParameterActive: 0\n  m_CycleOffsetParameterActive: 0\n  m_TimeParameterActive: 0\n  m_Motion: {fileID: 7400000, guid: d1977fc2096a4f9419278441257c4853, type: 2}\n  m_Tag: \n  m_SpeedParameter: \n  m_MirrorParameter: \n  m_CycleOffsetParameter: \n  m_TimeParameter: \n--- !u!91 &9100000\nAnimatorController:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_Name: Anim Controller\n  serializedVersion: 5\n  m_AnimatorParameters: []\n  m_AnimatorLayers:\n  - serializedVersion: 5\n    m_Name: Base Layer\n    m_StateMachine: {fileID: 7050415367986161970}\n    m_Mask: {fileID: 0}\n    m_Motions: []\n    m_Behaviours: []\n    m_BlendingMode: 0\n    m_SyncedLayerIndex: -1\n    m_DefaultWeight: 0\n    m_IKPass: 0\n    m_SyncedLayerAffectsTiming: 0\n    m_Controller: {fileID: 9100000}\n--- !u!1102 &3860230541811862537\nAnimatorState:\n  serializedVersion: 5\n  m_ObjectHideFlags: 1\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_Name: Idle\n  m_Speed: 1\n  m_CycleOffset: 0\n  m_Transitions: []\n  m_StateMachineBehaviours: []\n  m_Position: {x: 50, y: 50, z: 0}\n  m_IKOnFeet: 0\n  m_WriteDefaultValues: 1\n  m_Mirror: 0\n  m_SpeedParameterActive: 0\n  m_MirrorParameterActive: 0\n  m_CycleOffsetParameterActive: 0\n  m_TimeParameterActive: 0\n  m_Motion: {fileID: 7400000, guid: 3f027e4cebaf17f449c707e76d35446a, type: 2}\n  m_Tag: \n  m_SpeedParameter: \n  m_MirrorParameter: \n  m_CycleOffsetParameter: \n  m_TimeParameter: \n--- !u!1102 &4474522402598323306\nAnimatorState:\n  serializedVersion: 5\n  m_ObjectHideFlags: 1\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_Name: Jump\n  m_Speed: 1\n  m_CycleOffset: 0\n  m_Transitions: []\n  m_StateMachineBehaviours: []\n  m_Position: {x: 50, y: 50, z: 0}\n  m_IKOnFeet: 0\n  m_WriteDefaultValues: 1\n  m_Mirror: 0\n  m_SpeedParameterActive: 0\n  m_MirrorParameterActive: 0\n  m_CycleOffsetParameterActive: 0\n  m_TimeParameterActive: 0\n  m_Motion: {fileID: 7400000, guid: 56ec90b8d983df04faaa9d6e0d04b02a, type: 2}\n  m_Tag: \n  m_SpeedParameter: \n  m_MirrorParameter: \n  m_CycleOffsetParameter: \n  m_TimeParameter: \n--- !u!1102 &5571350923102602129\nAnimatorState:\n  serializedVersion: 5\n  m_ObjectHideFlags: 1\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_Name: Dead\n  m_Speed: 1\n  m_CycleOffset: 0\n  m_Transitions: []\n  m_StateMachineBehaviours: []\n  m_Position: {x: 50, y: 50, z: 0}\n  m_IKOnFeet: 0\n  m_WriteDefaultValues: 1\n  m_Mirror: 0\n  m_SpeedParameterActive: 0\n  m_MirrorParameterActive: 0\n  m_CycleOffsetParameterActive: 0\n  m_TimeParameterActive: 0\n  m_Motion: {fileID: 7400000, guid: fbda551e1c3510047ae5b79a78d796b5, type: 2}\n  m_Tag: \n  m_SpeedParameter: \n  m_MirrorParameter: \n  m_CycleOffsetParameter: \n  m_TimeParameter: \n--- !u!1107 &7050415367986161970\nAnimatorStateMachine:\n  serializedVersion: 5\n  m_ObjectHideFlags: 1\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_Name: Base Layer\n  m_ChildStates:\n  - serializedVersion: 1\n    m_State: {fileID: 7107746679928369096}\n    m_Position: {x: 240, y: 350, z: 0}\n  - serializedVersion: 1\n    m_State: {fileID: 5571350923102602129}\n    m_Position: {x: 375, y: 65, z: 0}\n  - serializedVersion: 1\n    m_State: {fileID: 3860230541811862537}\n    m_Position: {x: 410, y: 130, z: 0}\n  - serializedVersion: 1\n    m_State: {fileID: -6652583987855233881}\n    m_Position: {x: 630, y: 300, z: 0}\n  - serializedVersion: 1\n    m_State: {fileID: 4474522402598323306}\n    m_Position: {x: 660, y: 360, z: 0}\n  - serializedVersion: 1\n    m_State: {fileID: -7761859382232492428}\n    m_Position: {x: 700, y: 430, z: 0}\n  - serializedVersion: 1\n    m_State: {fileID: 7362315039286852393}\n    m_Position: {x: 730, y: 490, z: 0}\n  m_ChildStateMachines: []\n  m_AnyStateTransitions: []\n  m_EntryTransitions: []\n  m_StateMachineTransitions: {}\n  m_StateMachineBehaviours: []\n  m_AnyStatePosition: {x: 50, y: 20, z: 0}\n  m_EntryPosition: {x: 100, y: 130, z: 0}\n  m_ExitPosition: {x: 800, y: 120, z: 0}\n  m_ParentStateMachinePosition: {x: 800, y: 20, z: 0}\n  m_DefaultState: {fileID: 3860230541811862537}\n--- !u!1102 &7107746679928369096\nAnimatorState:\n  serializedVersion: 5\n  m_ObjectHideFlags: 1\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_Name: Attack\n  m_Speed: 1\n  m_CycleOffset: 0\n  m_Transitions: []\n  m_StateMachineBehaviours: []\n  m_Position: {x: 50, y: 50, z: 0}\n  m_IKOnFeet: 0\n  m_WriteDefaultValues: 1\n  m_Mirror: 0\n  m_SpeedParameterActive: 0\n  m_MirrorParameterActive: 0\n  m_CycleOffsetParameterActive: 0\n  m_TimeParameterActive: 0\n  m_Motion: {fileID: 7400000, guid: 1e265735d0f0f3f4c83ce818b82591b6, type: 2}\n  m_Tag: \n  m_SpeedParameter: \n  m_MirrorParameter: \n  m_CycleOffsetParameter: \n  m_TimeParameter: \n--- !u!1102 &7362315039286852393\nAnimatorState:\n  serializedVersion: 5\n  m_ObjectHideFlags: 1\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_Name: Ground\n  m_Speed: 1\n  m_CycleOffset: 0\n  m_Transitions: []\n  m_StateMachineBehaviours: []\n  m_Position: {x: 50, y: 50, z: 0}\n  m_IKOnFeet: 0\n  m_WriteDefaultValues: 1\n  m_Mirror: 0\n  m_SpeedParameterActive: 0\n  m_MirrorParameterActive: 0\n  m_CycleOffsetParameterActive: 0\n  m_TimeParameterActive: 0\n  m_Motion: {fileID: 7400000, guid: 2b5ed9932dcd642448d07305924a64eb, type: 2}\n  m_Tag: \n  m_SpeedParameter: \n  m_MirrorParameter: \n  m_CycleOffsetParameter: \n  m_TimeParameter: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Anim Controller.controller.meta",
    "content": "fileFormatVersion: 2\nguid: 2f41571c8d90046448625e247abe67dc\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 9100000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Attack (78x58).png.meta",
    "content": "fileFormatVersion: 2\nguid: 1b39413959741ef4095987c24f563d17\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -284007684338051874\n    second: Attack (78x58)_0\n  - first:\n      213: -1349876022115668649\n    second: Attack (78x58)_1\n  - first:\n      213: 5505932642739978319\n    second: Attack (78x58)_2\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Attack (78x58)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: b04efe9c34f50004bbdc921df38631ee\n      internalID: -284007684338051874\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Attack (78x58)_1\n      rect:\n        serializedVersion: 2\n        x: 78\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 1f7d79f6cca5f474cb2be99ce644dbe5\n      internalID: -1349876022115668649\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Attack (78x58)_2\n      rect:\n        serializedVersion: 2\n        x: 156\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 5e01c2740fb7bf44a9865c953668d534\n      internalID: 5505932642739978319\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 3c96c0d7b80a97849b2f95e5f07ddfe0\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Attack.anim",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!74 &7400000\nAnimationClip:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_Name: Attack\n  serializedVersion: 6\n  m_Legacy: 0\n  m_Compressed: 0\n  m_UseHighQualityCurve: 1\n  m_RotationCurves: []\n  m_CompressedRotationCurves: []\n  m_EulerCurves: []\n  m_PositionCurves: []\n  m_ScaleCurves: []\n  m_FloatCurves: []\n  m_PPtrCurves:\n  - curve:\n    - time: 0\n      value: {fileID: -284007684338051874, guid: 1b39413959741ef4095987c24f563d17,\n        type: 3}\n    - time: 0.1\n      value: {fileID: -1349876022115668649, guid: 1b39413959741ef4095987c24f563d17,\n        type: 3}\n    - time: 0.2\n      value: {fileID: 5505932642739978319, guid: 1b39413959741ef4095987c24f563d17,\n        type: 3}\n    attribute: m_Sprite\n    path: \n    classID: 212\n    script: {fileID: 0}\n  m_SampleRate: 10\n  m_WrapMode: 0\n  m_Bounds:\n    m_Center: {x: 0, y: 0, z: 0}\n    m_Extent: {x: 0, y: 0, z: 0}\n  m_ClipBindingConstant:\n    genericBindings:\n    - serializedVersion: 2\n      path: 0\n      attribute: 0\n      script: {fileID: 0}\n      typeID: 212\n      customType: 23\n      isPPtrCurve: 1\n    pptrCurveMapping:\n    - {fileID: -284007684338051874, guid: 1b39413959741ef4095987c24f563d17, type: 3}\n    - {fileID: -1349876022115668649, guid: 1b39413959741ef4095987c24f563d17, type: 3}\n    - {fileID: 5505932642739978319, guid: 1b39413959741ef4095987c24f563d17, type: 3}\n  m_AnimationClipSettings:\n    serializedVersion: 2\n    m_AdditiveReferencePoseClip: {fileID: 0}\n    m_AdditiveReferencePoseTime: 0\n    m_StartTime: 0\n    m_StopTime: 0.3\n    m_OrientationOffsetY: 0\n    m_Level: 0\n    m_CycleOffset: 0\n    m_HasAdditiveReferencePose: 0\n    m_LoopTime: 0\n    m_LoopBlend: 0\n    m_LoopBlendOrientation: 0\n    m_LoopBlendPositionY: 0\n    m_LoopBlendPositionXZ: 0\n    m_KeepOriginalOrientation: 0\n    m_KeepOriginalPositionY: 1\n    m_KeepOriginalPositionXZ: 0\n    m_HeightFromFeet: 0\n    m_Mirror: 0\n  m_EditorCurves: []\n  m_EulerEditorCurves: []\n  m_HasGenericRootTransform: 0\n  m_HasMotionFloatCurves: 0\n  m_Events: []\n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Attack.anim.meta",
    "content": "fileFormatVersion: 2\nguid: 1e265735d0f0f3f4c83ce818b82591b6\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 7400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Dead (78x58).png.meta",
    "content": "fileFormatVersion: 2\nguid: 31e6a140e4cad81449aa72e8147922f9\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: 4689127793708524886\n    second: Dead (78x58)_0\n  - first:\n      213: 7001614322767226673\n    second: Dead (78x58)_1\n  - first:\n      213: 3236711963942979464\n    second: Dead (78x58)_2\n  - first:\n      213: -2142470299157363264\n    second: Dead (78x58)_3\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Dead (78x58)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 7f39ab31f4ea7dd4a863c97c1866e7b7\n      internalID: 4689127793708524886\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Dead (78x58)_1\n      rect:\n        serializedVersion: 2\n        x: 78\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 82d84ba38763f6e46a16dc692faa47d5\n      internalID: 7001614322767226673\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Dead (78x58)_2\n      rect:\n        serializedVersion: 2\n        x: 156\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 5a2b8caac345f5f4e9659ed5f3e64036\n      internalID: 3236711963942979464\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Dead (78x58)_3\n      rect:\n        serializedVersion: 2\n        x: 234\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 784a10af702add84aa59042c7413cff7\n      internalID: -2142470299157363264\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 30aa1961606575c4a806a323439dd702\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Dead.anim",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!74 &7400000\nAnimationClip:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_Name: Dead\n  serializedVersion: 6\n  m_Legacy: 0\n  m_Compressed: 0\n  m_UseHighQualityCurve: 1\n  m_RotationCurves: []\n  m_CompressedRotationCurves: []\n  m_EulerCurves: []\n  m_PositionCurves: []\n  m_ScaleCurves: []\n  m_FloatCurves: []\n  m_PPtrCurves:\n  - curve:\n    - time: 0\n      value: {fileID: 4689127793708524886, guid: 31e6a140e4cad81449aa72e8147922f9,\n        type: 3}\n    - time: 0.1\n      value: {fileID: 7001614322767226673, guid: 31e6a140e4cad81449aa72e8147922f9,\n        type: 3}\n    - time: 0.2\n      value: {fileID: 3236711963942979464, guid: 31e6a140e4cad81449aa72e8147922f9,\n        type: 3}\n    - time: 0.3\n      value: {fileID: -2142470299157363264, guid: 31e6a140e4cad81449aa72e8147922f9,\n        type: 3}\n    attribute: m_Sprite\n    path: \n    classID: 212\n    script: {fileID: 0}\n  m_SampleRate: 10\n  m_WrapMode: 0\n  m_Bounds:\n    m_Center: {x: 0, y: 0, z: 0}\n    m_Extent: {x: 0, y: 0, z: 0}\n  m_ClipBindingConstant:\n    genericBindings:\n    - serializedVersion: 2\n      path: 0\n      attribute: 0\n      script: {fileID: 0}\n      typeID: 212\n      customType: 23\n      isPPtrCurve: 1\n    pptrCurveMapping:\n    - {fileID: 4689127793708524886, guid: 31e6a140e4cad81449aa72e8147922f9, type: 3}\n    - {fileID: 7001614322767226673, guid: 31e6a140e4cad81449aa72e8147922f9, type: 3}\n    - {fileID: 3236711963942979464, guid: 31e6a140e4cad81449aa72e8147922f9, type: 3}\n    - {fileID: -2142470299157363264, guid: 31e6a140e4cad81449aa72e8147922f9, type: 3}\n  m_AnimationClipSettings:\n    serializedVersion: 2\n    m_AdditiveReferencePoseClip: {fileID: 0}\n    m_AdditiveReferencePoseTime: 0\n    m_StartTime: 0\n    m_StopTime: 0.4\n    m_OrientationOffsetY: 0\n    m_Level: 0\n    m_CycleOffset: 0\n    m_HasAdditiveReferencePose: 0\n    m_LoopTime: 1\n    m_LoopBlend: 0\n    m_LoopBlendOrientation: 0\n    m_LoopBlendPositionY: 0\n    m_LoopBlendPositionXZ: 0\n    m_KeepOriginalOrientation: 0\n    m_KeepOriginalPositionY: 1\n    m_KeepOriginalPositionXZ: 0\n    m_HeightFromFeet: 0\n    m_Mirror: 0\n  m_EditorCurves: []\n  m_EulerEditorCurves: []\n  m_HasGenericRootTransform: 0\n  m_HasMotionFloatCurves: 0\n  m_Events: []\n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Dead.anim.meta",
    "content": "fileFormatVersion: 2\nguid: fbda551e1c3510047ae5b79a78d796b5\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 7400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Door In (78x58).png.meta",
    "content": "fileFormatVersion: 2\nguid: 74dee9050c6a42b4d9bfeed9c35224ea\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -7119397740185149299\n    second: Door In (78x58)_0\n  - first:\n      213: 5021233943226319915\n    second: Door In (78x58)_1\n  - first:\n      213: -27342229779004594\n    second: Door In (78x58)_2\n  - first:\n      213: 1137326700241729209\n    second: Door In (78x58)_3\n  - first:\n      213: -1197886239521585513\n    second: Door In (78x58)_4\n  - first:\n      213: -2678245271350149722\n    second: Door In (78x58)_5\n  - first:\n      213: 1253004127596136218\n    second: Door In (78x58)_6\n  - first:\n      213: 7790666701104349695\n    second: Door In (78x58)_7\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Door In (78x58)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: db0f4c734c0e2b94e931df33fecf36a2\n      internalID: -7119397740185149299\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Door In (78x58)_1\n      rect:\n        serializedVersion: 2\n        x: 78\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 704bca47150cfd54fbbeb39091de3cb8\n      internalID: 5021233943226319915\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Door In (78x58)_2\n      rect:\n        serializedVersion: 2\n        x: 156\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: f3306853e863e274ca4ab49f60ed8ab8\n      internalID: -27342229779004594\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Door In (78x58)_3\n      rect:\n        serializedVersion: 2\n        x: 234\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: daa5eff467a67034c8208a8049115bbb\n      internalID: 1137326700241729209\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Door In (78x58)_4\n      rect:\n        serializedVersion: 2\n        x: 312\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: f97a1c6439e087342ae1f8a87e2c8a3a\n      internalID: -1197886239521585513\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Door In (78x58)_5\n      rect:\n        serializedVersion: 2\n        x: 390\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 32a78204cb830af4a9e9c64775718805\n      internalID: -2678245271350149722\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Door In (78x58)_6\n      rect:\n        serializedVersion: 2\n        x: 468\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 82f4f6000c7a36c44b0389f41157b80e\n      internalID: 1253004127596136218\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Door In (78x58)_7\n      rect:\n        serializedVersion: 2\n        x: 546\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 052574a6dd9f1be44942cc96633a34d1\n      internalID: 7790666701104349695\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 95abca57f0557bc459c730e1101bf129\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Door Out (78x58).png.meta",
    "content": "fileFormatVersion: 2\nguid: 6370cecc24224854b8589df233e92602\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -2040908164472487208\n    second: Door Out (78x58)_0\n  - first:\n      213: -2394759738856020318\n    second: Door Out (78x58)_1\n  - first:\n      213: 4712378661485179610\n    second: Door Out (78x58)_2\n  - first:\n      213: 4412310672111565407\n    second: Door Out (78x58)_3\n  - first:\n      213: -5231970420580665600\n    second: Door Out (78x58)_4\n  - first:\n      213: -3057481843588990713\n    second: Door Out (78x58)_5\n  - first:\n      213: 6783514942609459231\n    second: Door Out (78x58)_6\n  - first:\n      213: -78119673854300105\n    second: Door Out (78x58)_7\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Door Out (78x58)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 2205f1cbb9347044280ed87cac6ac91d\n      internalID: -2040908164472487208\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Door Out (78x58)_1\n      rect:\n        serializedVersion: 2\n        x: 78\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 08c405ffa75d4ff4fac8956745dfe219\n      internalID: -2394759738856020318\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Door Out (78x58)_2\n      rect:\n        serializedVersion: 2\n        x: 156\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: d3712fbf1f73fe74d9485f840c0edfa9\n      internalID: 4712378661485179610\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Door Out (78x58)_3\n      rect:\n        serializedVersion: 2\n        x: 234\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 61c063c5d56d6cf48b5c96b3bb490857\n      internalID: 4412310672111565407\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Door Out (78x58)_4\n      rect:\n        serializedVersion: 2\n        x: 312\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 9158016a135c5ef469474bd764610b98\n      internalID: -5231970420580665600\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Door Out (78x58)_5\n      rect:\n        serializedVersion: 2\n        x: 390\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: c88ccc6f1ef093144aba1a0ac631627b\n      internalID: -3057481843588990713\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Door Out (78x58)_6\n      rect:\n        serializedVersion: 2\n        x: 468\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 1b33adb066d7d084da37d74eaf6e4db1\n      internalID: 6783514942609459231\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Door Out (78x58)_7\n      rect:\n        serializedVersion: 2\n        x: 546\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 0ab8b58e4dc3d4144a9fdf25e5f088d5\n      internalID: -78119673854300105\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 081b06b4edf63d6409e68b4a965aabc1\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Fall (78x58).png.meta",
    "content": "fileFormatVersion: 2\nguid: 050494cd281dcfc469f7ed4ec62f2124\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: 2004566321128258969\n    second: Fall (78x58)_0\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Fall (78x58)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 275e6eb84a6e27744998fb22c55b58aa\n      internalID: 2004566321128258969\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: c47861043997b3540b4b3ea873cec46e\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Ground (78x58).png.meta",
    "content": "fileFormatVersion: 2\nguid: eb6e5618976a67248afa26d2c94004f2\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -8368525642786742431\n    second: Ground (78x58)_0\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Ground (78x58)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: f1d3ba14a2766bf428288ffbc4c3df91\n      internalID: -8368525642786742431\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 9f002885c933ac1468a52d5e90f33a69\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Ground.anim",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!74 &7400000\nAnimationClip:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_Name: Ground\n  serializedVersion: 6\n  m_Legacy: 0\n  m_Compressed: 0\n  m_UseHighQualityCurve: 1\n  m_RotationCurves: []\n  m_CompressedRotationCurves: []\n  m_EulerCurves: []\n  m_PositionCurves: []\n  m_ScaleCurves: []\n  m_FloatCurves: []\n  m_PPtrCurves:\n  - curve:\n    - time: 0\n      value: {fileID: -8368525642786742431, guid: eb6e5618976a67248afa26d2c94004f2,\n        type: 3}\n    attribute: m_Sprite\n    path: \n    classID: 212\n    script: {fileID: 0}\n  m_SampleRate: 10\n  m_WrapMode: 0\n  m_Bounds:\n    m_Center: {x: 0, y: 0, z: 0}\n    m_Extent: {x: 0, y: 0, z: 0}\n  m_ClipBindingConstant:\n    genericBindings:\n    - serializedVersion: 2\n      path: 0\n      attribute: 0\n      script: {fileID: 0}\n      typeID: 212\n      customType: 23\n      isPPtrCurve: 1\n    pptrCurveMapping:\n    - {fileID: -8368525642786742431, guid: eb6e5618976a67248afa26d2c94004f2, type: 3}\n  m_AnimationClipSettings:\n    serializedVersion: 2\n    m_AdditiveReferencePoseClip: {fileID: 0}\n    m_AdditiveReferencePoseTime: 0\n    m_StartTime: 0\n    m_StopTime: 0.1\n    m_OrientationOffsetY: 0\n    m_Level: 0\n    m_CycleOffset: 0\n    m_HasAdditiveReferencePose: 0\n    m_LoopTime: 1\n    m_LoopBlend: 0\n    m_LoopBlendOrientation: 0\n    m_LoopBlendPositionY: 0\n    m_LoopBlendPositionXZ: 0\n    m_KeepOriginalOrientation: 0\n    m_KeepOriginalPositionY: 1\n    m_KeepOriginalPositionXZ: 0\n    m_HeightFromFeet: 0\n    m_Mirror: 0\n  m_EditorCurves: []\n  m_EulerEditorCurves: []\n  m_HasGenericRootTransform: 0\n  m_HasMotionFloatCurves: 0\n  m_Events: []\n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Ground.anim.meta",
    "content": "fileFormatVersion: 2\nguid: 2b5ed9932dcd642448d07305924a64eb\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 7400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Hit (78x58).png.meta",
    "content": "fileFormatVersion: 2\nguid: 33bed1e674bb3314fabd562e83f01a8c\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -4557684136233861674\n    second: Hit (78x58)_0\n  - first:\n      213: -6048739241746539578\n    second: Hit (78x58)_1\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Hit (78x58)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 384f5a56a1d260b45a7ff8ad12e4714a\n      internalID: -4557684136233861674\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Hit (78x58)_1\n      rect:\n        serializedVersion: 2\n        x: 78\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 2d1ce16f40e076544a8ed06138ddedfa\n      internalID: -6048739241746539578\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: b25a5cdf1abf0a94d943b41580e67969\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Hit.anim",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!74 &7400000\nAnimationClip:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_Name: Hit\n  serializedVersion: 6\n  m_Legacy: 0\n  m_Compressed: 0\n  m_UseHighQualityCurve: 1\n  m_RotationCurves: []\n  m_CompressedRotationCurves: []\n  m_EulerCurves: []\n  m_PositionCurves: []\n  m_ScaleCurves: []\n  m_FloatCurves: []\n  m_PPtrCurves:\n  - curve:\n    - time: 0\n      value: {fileID: -4557684136233861674, guid: 33bed1e674bb3314fabd562e83f01a8c,\n        type: 3}\n    - time: 0.1\n      value: {fileID: -6048739241746539578, guid: 33bed1e674bb3314fabd562e83f01a8c,\n        type: 3}\n    attribute: m_Sprite\n    path: \n    classID: 212\n    script: {fileID: 0}\n  m_SampleRate: 10\n  m_WrapMode: 0\n  m_Bounds:\n    m_Center: {x: 0, y: 0, z: 0}\n    m_Extent: {x: 0, y: 0, z: 0}\n  m_ClipBindingConstant:\n    genericBindings:\n    - serializedVersion: 2\n      path: 0\n      attribute: 0\n      script: {fileID: 0}\n      typeID: 212\n      customType: 23\n      isPPtrCurve: 1\n    pptrCurveMapping:\n    - {fileID: -4557684136233861674, guid: 33bed1e674bb3314fabd562e83f01a8c, type: 3}\n    - {fileID: -6048739241746539578, guid: 33bed1e674bb3314fabd562e83f01a8c, type: 3}\n  m_AnimationClipSettings:\n    serializedVersion: 2\n    m_AdditiveReferencePoseClip: {fileID: 0}\n    m_AdditiveReferencePoseTime: 0\n    m_StartTime: 0\n    m_StopTime: 0.2\n    m_OrientationOffsetY: 0\n    m_Level: 0\n    m_CycleOffset: 0\n    m_HasAdditiveReferencePose: 0\n    m_LoopTime: 0\n    m_LoopBlend: 0\n    m_LoopBlendOrientation: 0\n    m_LoopBlendPositionY: 0\n    m_LoopBlendPositionXZ: 0\n    m_KeepOriginalOrientation: 0\n    m_KeepOriginalPositionY: 1\n    m_KeepOriginalPositionXZ: 0\n    m_HeightFromFeet: 0\n    m_Mirror: 0\n  m_EditorCurves: []\n  m_EulerEditorCurves: []\n  m_HasGenericRootTransform: 0\n  m_HasMotionFloatCurves: 0\n  m_Events: []\n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Hit.anim.meta",
    "content": "fileFormatVersion: 2\nguid: d83b92a5c635ae14e8ccd364a7b0afae\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 7400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Idle (78x58).png.meta",
    "content": "fileFormatVersion: 2\nguid: dc9e30031f07ecc40aeb0cbb3d4a9d44\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: 4236677631525818213\n    second: Idle (78x58)_0\n  - first:\n      213: 4028697958841943031\n    second: Idle (78x58)_1\n  - first:\n      213: -71890014864666246\n    second: Idle (78x58)_2\n  - first:\n      213: 1190557261751377376\n    second: Idle (78x58)_3\n  - first:\n      213: 5064041211780997922\n    second: Idle (78x58)_4\n  - first:\n      213: 8108171691728574818\n    second: Idle (78x58)_5\n  - first:\n      213: -1993345210608603527\n    second: Idle (78x58)_6\n  - first:\n      213: 4981596952429199082\n    second: Idle (78x58)_7\n  - first:\n      213: 7626191033687767977\n    second: Idle (78x58)_8\n  - first:\n      213: -5613459758552902165\n    second: Idle (78x58)_9\n  - first:\n      213: 4409867477321305065\n    second: Idle (78x58)_10\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Idle (78x58)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 3d047ff8d49023046a8d8bc86f9f20be\n      internalID: 4236677631525818213\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (78x58)_1\n      rect:\n        serializedVersion: 2\n        x: 78\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 9f4d2d1b66b08a342aab50e676146ae6\n      internalID: 4028697958841943031\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (78x58)_2\n      rect:\n        serializedVersion: 2\n        x: 156\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 9f2210f490984cc4fb5cf71cbfb737fa\n      internalID: -71890014864666246\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (78x58)_3\n      rect:\n        serializedVersion: 2\n        x: 234\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 087ffd8d821a6804ba4857fd5e597883\n      internalID: 1190557261751377376\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (78x58)_4\n      rect:\n        serializedVersion: 2\n        x: 312\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 6acdd85067d06a34ebf878d1d141117d\n      internalID: 5064041211780997922\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (78x58)_5\n      rect:\n        serializedVersion: 2\n        x: 390\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: adae0431c556a0a4aa2d8666bd8d0b0a\n      internalID: 8108171691728574818\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (78x58)_6\n      rect:\n        serializedVersion: 2\n        x: 468\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: a9f6800a3ed2c7d43862c1795f6ec5a9\n      internalID: -1993345210608603527\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (78x58)_7\n      rect:\n        serializedVersion: 2\n        x: 546\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 1784f1820a7060543bd9078908f8ce18\n      internalID: 4981596952429199082\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (78x58)_8\n      rect:\n        serializedVersion: 2\n        x: 624\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 9a94bc5a77da473479c3f44e8c3ffa83\n      internalID: 7626191033687767977\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (78x58)_9\n      rect:\n        serializedVersion: 2\n        x: 702\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 5cf56dba9bb3212438e967ed50451626\n      internalID: -5613459758552902165\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (78x58)_10\n      rect:\n        serializedVersion: 2\n        x: 780\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: d12ee99222ddd384496029589043ee46\n      internalID: 4409867477321305065\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 5d077ba7a73407144b7d9630ede1b999\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Idle.anim",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!74 &7400000\nAnimationClip:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_Name: Idle\n  serializedVersion: 6\n  m_Legacy: 0\n  m_Compressed: 0\n  m_UseHighQualityCurve: 1\n  m_RotationCurves: []\n  m_CompressedRotationCurves: []\n  m_EulerCurves: []\n  m_PositionCurves: []\n  m_ScaleCurves: []\n  m_FloatCurves: []\n  m_PPtrCurves:\n  - curve:\n    - time: 0\n      value: {fileID: 4236677631525818213, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44,\n        type: 3}\n    - time: 0.1\n      value: {fileID: 4028697958841943031, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44,\n        type: 3}\n    - time: 0.2\n      value: {fileID: -71890014864666246, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44,\n        type: 3}\n    - time: 0.3\n      value: {fileID: 1190557261751377376, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44,\n        type: 3}\n    - time: 0.4\n      value: {fileID: 5064041211780997922, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44,\n        type: 3}\n    - time: 0.5\n      value: {fileID: 8108171691728574818, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44,\n        type: 3}\n    - time: 0.6\n      value: {fileID: -1993345210608603527, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44,\n        type: 3}\n    - time: 0.7\n      value: {fileID: 4981596952429199082, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44,\n        type: 3}\n    - time: 0.8\n      value: {fileID: 7626191033687767977, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44,\n        type: 3}\n    - time: 0.9\n      value: {fileID: -5613459758552902165, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44,\n        type: 3}\n    - time: 1\n      value: {fileID: 4409867477321305065, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44,\n        type: 3}\n    attribute: m_Sprite\n    path: \n    classID: 212\n    script: {fileID: 0}\n  m_SampleRate: 10\n  m_WrapMode: 0\n  m_Bounds:\n    m_Center: {x: 0, y: 0, z: 0}\n    m_Extent: {x: 0, y: 0, z: 0}\n  m_ClipBindingConstant:\n    genericBindings:\n    - serializedVersion: 2\n      path: 0\n      attribute: 0\n      script: {fileID: 0}\n      typeID: 212\n      customType: 23\n      isPPtrCurve: 1\n    pptrCurveMapping:\n    - {fileID: 4236677631525818213, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44, type: 3}\n    - {fileID: 4028697958841943031, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44, type: 3}\n    - {fileID: -71890014864666246, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44, type: 3}\n    - {fileID: 1190557261751377376, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44, type: 3}\n    - {fileID: 5064041211780997922, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44, type: 3}\n    - {fileID: 8108171691728574818, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44, type: 3}\n    - {fileID: -1993345210608603527, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44, type: 3}\n    - {fileID: 4981596952429199082, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44, type: 3}\n    - {fileID: 7626191033687767977, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44, type: 3}\n    - {fileID: -5613459758552902165, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44, type: 3}\n    - {fileID: 4409867477321305065, guid: dc9e30031f07ecc40aeb0cbb3d4a9d44, type: 3}\n  m_AnimationClipSettings:\n    serializedVersion: 2\n    m_AdditiveReferencePoseClip: {fileID: 0}\n    m_AdditiveReferencePoseTime: 0\n    m_StartTime: 0\n    m_StopTime: 1.1\n    m_OrientationOffsetY: 0\n    m_Level: 0\n    m_CycleOffset: 0\n    m_HasAdditiveReferencePose: 0\n    m_LoopTime: 1\n    m_LoopBlend: 0\n    m_LoopBlendOrientation: 0\n    m_LoopBlendPositionY: 0\n    m_LoopBlendPositionXZ: 0\n    m_KeepOriginalOrientation: 0\n    m_KeepOriginalPositionY: 1\n    m_KeepOriginalPositionXZ: 0\n    m_HeightFromFeet: 0\n    m_Mirror: 0\n  m_EditorCurves: []\n  m_EulerEditorCurves: []\n  m_HasGenericRootTransform: 0\n  m_HasMotionFloatCurves: 0\n  m_Events: []\n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Idle.anim.meta",
    "content": "fileFormatVersion: 2\nguid: 3f027e4cebaf17f449c707e76d35446a\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 7400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Jump (78x58).png.meta",
    "content": "fileFormatVersion: 2\nguid: b74fbc8e54d1ff74998435e213301f2d\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -3294574253389157637\n    second: Jump (78x58)_0\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Jump (78x58)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 0685f136e27eb9b4eac21abdc41ef5bd\n      internalID: -3294574253389157637\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 8863fb39bcfd7624ebc89e8408569680\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Jump.anim",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!74 &7400000\nAnimationClip:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_Name: Jump\n  serializedVersion: 6\n  m_Legacy: 0\n  m_Compressed: 0\n  m_UseHighQualityCurve: 1\n  m_RotationCurves: []\n  m_CompressedRotationCurves: []\n  m_EulerCurves: []\n  m_PositionCurves: []\n  m_ScaleCurves: []\n  m_FloatCurves: []\n  m_PPtrCurves:\n  - curve:\n    - time: 0\n      value: {fileID: -3294574253389157637, guid: b74fbc8e54d1ff74998435e213301f2d,\n        type: 3}\n    attribute: m_Sprite\n    path: \n    classID: 212\n    script: {fileID: 0}\n  m_SampleRate: 10\n  m_WrapMode: 0\n  m_Bounds:\n    m_Center: {x: 0, y: 0, z: 0}\n    m_Extent: {x: 0, y: 0, z: 0}\n  m_ClipBindingConstant:\n    genericBindings:\n    - serializedVersion: 2\n      path: 0\n      attribute: 0\n      script: {fileID: 0}\n      typeID: 212\n      customType: 23\n      isPPtrCurve: 1\n    pptrCurveMapping:\n    - {fileID: -3294574253389157637, guid: b74fbc8e54d1ff74998435e213301f2d, type: 3}\n  m_AnimationClipSettings:\n    serializedVersion: 2\n    m_AdditiveReferencePoseClip: {fileID: 0}\n    m_AdditiveReferencePoseTime: 0\n    m_StartTime: 0\n    m_StopTime: 0.1\n    m_OrientationOffsetY: 0\n    m_Level: 0\n    m_CycleOffset: 0\n    m_HasAdditiveReferencePose: 0\n    m_LoopTime: 1\n    m_LoopBlend: 0\n    m_LoopBlendOrientation: 0\n    m_LoopBlendPositionY: 0\n    m_LoopBlendPositionXZ: 0\n    m_KeepOriginalOrientation: 0\n    m_KeepOriginalPositionY: 1\n    m_KeepOriginalPositionXZ: 0\n    m_HeightFromFeet: 0\n    m_Mirror: 0\n  m_EditorCurves: []\n  m_EulerEditorCurves: []\n  m_HasGenericRootTransform: 0\n  m_HasMotionFloatCurves: 0\n  m_Events: []\n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Jump.anim.meta",
    "content": "fileFormatVersion: 2\nguid: 56ec90b8d983df04faaa9d6e0d04b02a\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 7400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Run (78x58).png.meta",
    "content": "fileFormatVersion: 2\nguid: ec95ba2e5fa02994c9858c977594908b\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -7063903929861715703\n    second: Run (78x58)_0\n  - first:\n      213: 8626773255784356531\n    second: Run (78x58)_1\n  - first:\n      213: -5795003117160629848\n    second: Run (78x58)_2\n  - first:\n      213: 3561249728323253878\n    second: Run (78x58)_3\n  - first:\n      213: 3822881148397469178\n    second: Run (78x58)_4\n  - first:\n      213: 6879179259501797737\n    second: Run (78x58)_5\n  - first:\n      213: 1277852240713749110\n    second: Run (78x58)_6\n  - first:\n      213: -6436722398084169495\n    second: Run (78x58)_7\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Run (78x58)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: a4e2f3ee827562a4f980f894da6110cc\n      internalID: -7063903929861715703\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (78x58)_1\n      rect:\n        serializedVersion: 2\n        x: 78\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 711cb80878748f040aebced1adb0c421\n      internalID: 8626773255784356531\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (78x58)_2\n      rect:\n        serializedVersion: 2\n        x: 156\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 002ba4cf46ddbd04ea594def45cc0573\n      internalID: -5795003117160629848\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (78x58)_3\n      rect:\n        serializedVersion: 2\n        x: 234\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 6d85bb2139a623744ba443b8429c584b\n      internalID: 3561249728323253878\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (78x58)_4\n      rect:\n        serializedVersion: 2\n        x: 312\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: f5ed8987b5f5d364aa9a24646e449630\n      internalID: 3822881148397469178\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (78x58)_5\n      rect:\n        serializedVersion: 2\n        x: 390\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 4dc2b9c171576b74d96e37b56487bb17\n      internalID: 6879179259501797737\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (78x58)_6\n      rect:\n        serializedVersion: 2\n        x: 468\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: a29ee6aef5802504ab18554954491bf0\n      internalID: 1277852240713749110\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (78x58)_7\n      rect:\n        serializedVersion: 2\n        x: 546\n        y: 0\n        width: 78\n        height: 58\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 4066376d6655c8e47b98e82a8d3f8e71\n      internalID: -6436722398084169495\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 966854bc7fe70914a8f504a9548d7380\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Run.anim",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!74 &7400000\nAnimationClip:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_Name: Run\n  serializedVersion: 6\n  m_Legacy: 0\n  m_Compressed: 0\n  m_UseHighQualityCurve: 1\n  m_RotationCurves: []\n  m_CompressedRotationCurves: []\n  m_EulerCurves: []\n  m_PositionCurves: []\n  m_ScaleCurves: []\n  m_FloatCurves: []\n  m_PPtrCurves:\n  - curve:\n    - time: 0\n      value: {fileID: -7063903929861715703, guid: ec95ba2e5fa02994c9858c977594908b,\n        type: 3}\n    - time: 0.1\n      value: {fileID: 8626773255784356531, guid: ec95ba2e5fa02994c9858c977594908b,\n        type: 3}\n    - time: 0.2\n      value: {fileID: -5795003117160629848, guid: ec95ba2e5fa02994c9858c977594908b,\n        type: 3}\n    - time: 0.3\n      value: {fileID: 3561249728323253878, guid: ec95ba2e5fa02994c9858c977594908b,\n        type: 3}\n    - time: 0.4\n      value: {fileID: 3822881148397469178, guid: ec95ba2e5fa02994c9858c977594908b,\n        type: 3}\n    - time: 0.5\n      value: {fileID: 6879179259501797737, guid: ec95ba2e5fa02994c9858c977594908b,\n        type: 3}\n    - time: 0.6\n      value: {fileID: 1277852240713749110, guid: ec95ba2e5fa02994c9858c977594908b,\n        type: 3}\n    - time: 0.7\n      value: {fileID: -6436722398084169495, guid: ec95ba2e5fa02994c9858c977594908b,\n        type: 3}\n    attribute: m_Sprite\n    path: \n    classID: 212\n    script: {fileID: 0}\n  m_SampleRate: 10\n  m_WrapMode: 0\n  m_Bounds:\n    m_Center: {x: 0, y: 0, z: 0}\n    m_Extent: {x: 0, y: 0, z: 0}\n  m_ClipBindingConstant:\n    genericBindings:\n    - serializedVersion: 2\n      path: 0\n      attribute: 0\n      script: {fileID: 0}\n      typeID: 212\n      customType: 23\n      isPPtrCurve: 1\n    pptrCurveMapping:\n    - {fileID: -7063903929861715703, guid: ec95ba2e5fa02994c9858c977594908b, type: 3}\n    - {fileID: 8626773255784356531, guid: ec95ba2e5fa02994c9858c977594908b, type: 3}\n    - {fileID: -5795003117160629848, guid: ec95ba2e5fa02994c9858c977594908b, type: 3}\n    - {fileID: 3561249728323253878, guid: ec95ba2e5fa02994c9858c977594908b, type: 3}\n    - {fileID: 3822881148397469178, guid: ec95ba2e5fa02994c9858c977594908b, type: 3}\n    - {fileID: 6879179259501797737, guid: ec95ba2e5fa02994c9858c977594908b, type: 3}\n    - {fileID: 1277852240713749110, guid: ec95ba2e5fa02994c9858c977594908b, type: 3}\n    - {fileID: -6436722398084169495, guid: ec95ba2e5fa02994c9858c977594908b, type: 3}\n  m_AnimationClipSettings:\n    serializedVersion: 2\n    m_AdditiveReferencePoseClip: {fileID: 0}\n    m_AdditiveReferencePoseTime: 0\n    m_StartTime: 0\n    m_StopTime: 0.8\n    m_OrientationOffsetY: 0\n    m_Level: 0\n    m_CycleOffset: 0\n    m_HasAdditiveReferencePose: 0\n    m_LoopTime: 1\n    m_LoopBlend: 0\n    m_LoopBlendOrientation: 0\n    m_LoopBlendPositionY: 0\n    m_LoopBlendPositionXZ: 0\n    m_KeepOriginalOrientation: 0\n    m_KeepOriginalPositionY: 1\n    m_KeepOriginalPositionXZ: 0\n    m_HeightFromFeet: 0\n    m_Mirror: 0\n  m_EditorCurves: []\n  m_EulerEditorCurves: []\n  m_HasGenericRootTransform: 0\n  m_HasMotionFloatCurves: 0\n  m_Events: []\n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human/Run.anim.meta",
    "content": "fileFormatVersion: 2\nguid: d1977fc2096a4f9419278441257c4853\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 7400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/01-King Human.meta",
    "content": "fileFormatVersion: 2\nguid: b3f1ea61a82a56549bea9ef78dcfbdb5\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/02-King Pig/Attack (38x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: 95b0d200d451b1e44945a4b944387f4c\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -7829678037764882620\n    second: Attack (38x28)_0\n  - first:\n      213: -5602922390754421287\n    second: Attack (38x28)_1\n  - first:\n      213: -5108517543321393613\n    second: Attack (38x28)_2\n  - first:\n      213: 7624256206322610138\n    second: Attack (38x28)_3\n  - first:\n      213: -7830389831496340263\n    second: Attack (38x28)_4\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 0\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Attack (38x28)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 146582cc7aac75f4498f23cc2cede852\n      internalID: -7829678037764882620\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Attack (38x28)_1\n      rect:\n        serializedVersion: 2\n        x: 38\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 14c410d889f3aa145b8b29fadc779a72\n      internalID: -5602922390754421287\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Attack (38x28)_2\n      rect:\n        serializedVersion: 2\n        x: 76\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 2d8ea9c88a3a21946b12ef34cb21b141\n      internalID: -5108517543321393613\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Attack (38x28)_3\n      rect:\n        serializedVersion: 2\n        x: 114\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 15f8a819b077223429d9164235f2d2b4\n      internalID: 7624256206322610138\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Attack (38x28)_4\n      rect:\n        serializedVersion: 2\n        x: 152\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: c09943dca569c9e4b9e47a7838104e51\n      internalID: -7830389831496340263\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 4d9459c36ab07834a864e7073a6e3d52\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/02-King Pig/Dead (38x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: df2bc15a717a2654596d0e042a56eef0\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -3986534151507454092\n    second: Dead (38x28)_0\n  - first:\n      213: -3139996617160341511\n    second: Dead (38x28)_1\n  - first:\n      213: 1401772850646523729\n    second: Dead (38x28)_2\n  - first:\n      213: 8067800279291937271\n    second: Dead (38x28)_3\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Dead (38x28)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: e68fa876b86ce214f9442c00f7a355a5\n      internalID: -3986534151507454092\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Dead (38x28)_1\n      rect:\n        serializedVersion: 2\n        x: 38\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 61386d7407839464ab6a4b9de952ea69\n      internalID: -3139996617160341511\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Dead (38x28)_2\n      rect:\n        serializedVersion: 2\n        x: 76\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: e36bea190a3781c4ab1af042d305038a\n      internalID: 1401772850646523729\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Dead (38x28)_3\n      rect:\n        serializedVersion: 2\n        x: 114\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: e9b53ab65de5c5b4aaf77b19db4383ff\n      internalID: 8067800279291937271\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 24ff6ac5081a71542a7b658c089919ae\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/02-King Pig/Fall (38x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: 399415f2d7a1a1c499151cfd0ffddb8d\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: 6921539142100303617\n    second: Fall (38x28)_0\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Fall (38x28)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: d69883433ae0e1c44a0856b97772a949\n      internalID: 6921539142100303617\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: d192468854bc0ac419973d86eaa4e185\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/02-King Pig/Ground (38x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: fc2ebe49fffd7184181f6fb8fee53180\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: 1722116007910851073\n    second: Ground (38x28)_0\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Ground (38x28)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: a4ab84da3c15ebc49a55f6df9e67dc77\n      internalID: 1722116007910851073\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: d0638ab730467b547adfb57fa5541d2a\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/02-King Pig/Hit (38x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: 924784504e43f21428316b9a96864499\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -7982368223760686067\n    second: Hit (38x28)_0\n  - first:\n      213: -8445486696707508763\n    second: Hit (38x28)_1\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Hit (38x28)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 13e1e2daa2d146c4ca5e41b695abe716\n      internalID: -7982368223760686067\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Hit (38x28)_1\n      rect:\n        serializedVersion: 2\n        x: 38\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 9d0eb65d5df8f6748b03d83e3062bd27\n      internalID: -8445486696707508763\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 01d4b9a6e30a5504fb9433b744b29a8a\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/02-King Pig/Idle (38x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: e66ba0b41f6a56b4485591f0ea44fd76\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: 4528382388787556690\n    second: Idle (38x28)_0\n  - first:\n      213: 8412296399577003747\n    second: Idle (38x28)_1\n  - first:\n      213: -109952482578449033\n    second: Idle (38x28)_2\n  - first:\n      213: -209679512346147777\n    second: Idle (38x28)_3\n  - first:\n      213: -2607453568630673242\n    second: Idle (38x28)_4\n  - first:\n      213: -2533730466094568701\n    second: Idle (38x28)_5\n  - first:\n      213: -1521685734421727823\n    second: Idle (38x28)_6\n  - first:\n      213: -6045718703917629974\n    second: Idle (38x28)_7\n  - first:\n      213: -1104561379124751342\n    second: Idle (38x28)_8\n  - first:\n      213: 7231966715156713990\n    second: Idle (38x28)_9\n  - first:\n      213: -7253561670630318893\n    second: Idle (38x28)_10\n  - first:\n      213: -8781086628845775685\n    second: Idle (38x28)_11\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Idle (38x28)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: a77cd81da1ba292449cc756e921a1154\n      internalID: 4528382388787556690\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (38x28)_1\n      rect:\n        serializedVersion: 2\n        x: 38\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: f3f2eaba236650f47abdd6bac0bbc9fb\n      internalID: 8412296399577003747\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (38x28)_2\n      rect:\n        serializedVersion: 2\n        x: 76\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: a6287cda0d5eee54cbf65e31f71840e1\n      internalID: -109952482578449033\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (38x28)_3\n      rect:\n        serializedVersion: 2\n        x: 114\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: fbc443faa6f49dc4aa64f29739629a9a\n      internalID: -209679512346147777\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (38x28)_4\n      rect:\n        serializedVersion: 2\n        x: 152\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: c7182bbb99d7467438f3c6ffd0e631f5\n      internalID: -2607453568630673242\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (38x28)_5\n      rect:\n        serializedVersion: 2\n        x: 190\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: b629f6d73bed7b041bb90f637e4e83b4\n      internalID: -2533730466094568701\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (38x28)_6\n      rect:\n        serializedVersion: 2\n        x: 228\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 9c7e7e8163d2e5648b0133f4d2c3a6e6\n      internalID: -1521685734421727823\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (38x28)_7\n      rect:\n        serializedVersion: 2\n        x: 266\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 31b0b7c8be138aa43b59ad02e8667dee\n      internalID: -6045718703917629974\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (38x28)_8\n      rect:\n        serializedVersion: 2\n        x: 304\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: e4bbf4a616da301489e01076f8ee5ff3\n      internalID: -1104561379124751342\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (38x28)_9\n      rect:\n        serializedVersion: 2\n        x: 342\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: af2f9599f89fd644a9b1786f03e144f1\n      internalID: 7231966715156713990\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (38x28)_10\n      rect:\n        serializedVersion: 2\n        x: 380\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 41d99c321c9abbc4c847efd902ebb545\n      internalID: -7253561670630318893\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (38x28)_11\n      rect:\n        serializedVersion: 2\n        x: 418\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 4d2bacba2d352c247b3e4cce6bb7747b\n      internalID: -8781086628845775685\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 4fa95ecf0500b984b8bf72cec19dc57b\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/02-King Pig/Jump (38x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: 115c2bf0adff8624d8bcb3695edb4186\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: 8670564766382069247\n    second: Jump (38x28)_0\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Jump (38x28)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 3cd50a3f933240d4597943556a1e0ceb\n      internalID: 8670564766382069247\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 4b7fe26e029acb242893de817adb0f78\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/02-King Pig/Run (38x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: d581c7403aa1c3549a9a2e8745c68ce5\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: 6811151430340104182\n    second: Run (38x28)_0\n  - first:\n      213: -2200175214836965533\n    second: Run (38x28)_1\n  - first:\n      213: 8360943256208611768\n    second: Run (38x28)_2\n  - first:\n      213: 6079259064337885918\n    second: Run (38x28)_3\n  - first:\n      213: 572373456161430582\n    second: Run (38x28)_4\n  - first:\n      213: -5968472981034668420\n    second: Run (38x28)_5\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Run (38x28)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: ede872f5db3710443bb88bac0831185d\n      internalID: 6811151430340104182\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (38x28)_1\n      rect:\n        serializedVersion: 2\n        x: 38\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 425dcc00ae49a594f923e4c184913ffe\n      internalID: -2200175214836965533\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (38x28)_2\n      rect:\n        serializedVersion: 2\n        x: 76\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 57005f08cbc465648b70c6af9af5f9bc\n      internalID: 8360943256208611768\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (38x28)_3\n      rect:\n        serializedVersion: 2\n        x: 114\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: acd43612664fa4e4ca7ce3299753f136\n      internalID: 6079259064337885918\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (38x28)_4\n      rect:\n        serializedVersion: 2\n        x: 152\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 7d04808d185501c409faeb721fb9ae63\n      internalID: 572373456161430582\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (38x28)_5\n      rect:\n        serializedVersion: 2\n        x: 190\n        y: 0\n        width: 38\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: c663808af43e6724dbe163943f0f1d87\n      internalID: -5968472981034668420\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 0791fb93213692549aa77240df12a95e\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/02-King Pig.meta",
    "content": "fileFormatVersion: 2\nguid: 238ff009f3d2ce244bd189893c149f23\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/03-Pig/Attack (34x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: 210633ce6bc75c74c860d617e11e7e1e\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -1084714191397490296\n    second: Attack (34x28)_0\n  - first:\n      213: -3471973600961722869\n    second: Attack (34x28)_1\n  - first:\n      213: 3858816176522794952\n    second: Attack (34x28)_2\n  - first:\n      213: -1215565705406224045\n    second: Attack (34x28)_3\n  - first:\n      213: 76750241978737982\n    second: Attack (34x28)_4\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Attack (34x28)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: d14682a65ed698d4f8cb72c400a98538\n      internalID: -1084714191397490296\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Attack (34x28)_1\n      rect:\n        serializedVersion: 2\n        x: 34\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 26c38652b5aca1d4da40ce3154b2ccf4\n      internalID: -3471973600961722869\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Attack (34x28)_2\n      rect:\n        serializedVersion: 2\n        x: 68\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 821492fd04e19c04e98967dcb00daeff\n      internalID: 3858816176522794952\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Attack (34x28)_3\n      rect:\n        serializedVersion: 2\n        x: 102\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 722e8c74c0d18f547bf04f62a965025a\n      internalID: -1215565705406224045\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Attack (34x28)_4\n      rect:\n        serializedVersion: 2\n        x: 136\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 8678edb2f31991644949b9c303233408\n      internalID: 76750241978737982\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 8c12f73dc7ab9274ab1a8614f1ee610b\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/03-Pig/Dead (34x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: 1b4224f6378c0a648bb0f225af9e6fcc\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -7522094942047569111\n    second: Dead (34x28)_0\n  - first:\n      213: 425510035627860162\n    second: Dead (34x28)_1\n  - first:\n      213: 2332378773207366414\n    second: Dead (34x28)_2\n  - first:\n      213: 2076103681765718411\n    second: Dead (34x28)_3\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Dead (34x28)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: a6c2d110937d2f8449bee237b3889cd4\n      internalID: -7522094942047569111\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Dead (34x28)_1\n      rect:\n        serializedVersion: 2\n        x: 34\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 2c4129131128ab54bb6d1631a337203e\n      internalID: 425510035627860162\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Dead (34x28)_2\n      rect:\n        serializedVersion: 2\n        x: 68\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 8b2636e6c2b1be54e8d2270bae6888a9\n      internalID: 2332378773207366414\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Dead (34x28)_3\n      rect:\n        serializedVersion: 2\n        x: 102\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 288c978ba2f111741a7696ff1a3923b7\n      internalID: 2076103681765718411\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 32ab3fea98ca35d41bdb195524d583cb\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/03-Pig/Fall (34x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: 17278eb603ea89a47b3dc598ad8757af\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -977482824948291417\n    second: Fall (34x28)_0\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Fall (34x28)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 1298080b796e5264eb188c59e10a3f3d\n      internalID: -977482824948291417\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: d7e1f00d282e40345a60550d4c8659ae\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/03-Pig/Ground (34x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: d8d339f32f3e5d64cab9ff6a24468d0a\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -4482629034155238029\n    second: Ground (34x28)_0\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Ground (34x28)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: f36a6fa0f8dab6b4c84187718972fd81\n      internalID: -4482629034155238029\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: af405580bfa02fa47b5c71c2096b143f\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/03-Pig/Hit (34x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: 5a326833d7e84844293915e9a665051f\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: 1107241206036555090\n    second: Hit (34x28)_0\n  - first:\n      213: 8098470886054705025\n    second: Hit (34x28)_1\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Hit (34x28)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 93b68c4ccf2a9a14881c6fb7a819c21b\n      internalID: 1107241206036555090\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Hit (34x28)_1\n      rect:\n        serializedVersion: 2\n        x: 34\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 9b77f73b79edc1740a1c4baed794515e\n      internalID: 8098470886054705025\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 354200a67618889479169ee5e9fe5d34\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/03-Pig/Idle (34x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: e14c01bb614ce6140bad9c596f91a56b\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: 4571226829092849726\n    second: Idle (34x28)_0\n  - first:\n      213: -8949856686944730191\n    second: Idle (34x28)_1\n  - first:\n      213: 2826186669421539911\n    second: Idle (34x28)_2\n  - first:\n      213: -5531042245258228581\n    second: Idle (34x28)_3\n  - first:\n      213: 2622321733923217370\n    second: Idle (34x28)_4\n  - first:\n      213: 4508922478542092599\n    second: Idle (34x28)_5\n  - first:\n      213: 850222469992291503\n    second: Idle (34x28)_6\n  - first:\n      213: -7622230470964513380\n    second: Idle (34x28)_7\n  - first:\n      213: -4453737675818896170\n    second: Idle (34x28)_8\n  - first:\n      213: -6983562990028683331\n    second: Idle (34x28)_9\n  - first:\n      213: -1903310279220368910\n    second: Idle (34x28)_10\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Idle (34x28)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 47368cb4104822f49abc2a7f9b8d7036\n      internalID: 4571226829092849726\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (34x28)_1\n      rect:\n        serializedVersion: 2\n        x: 34\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: dfed0f5bbb5e5604fa50a4d073035115\n      internalID: -8949856686944730191\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (34x28)_2\n      rect:\n        serializedVersion: 2\n        x: 68\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 373b1c9b2e3f6d8468040cd2ed722b07\n      internalID: 2826186669421539911\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (34x28)_3\n      rect:\n        serializedVersion: 2\n        x: 102\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: d13c19f4ba55caf47bc741d97769bf24\n      internalID: -5531042245258228581\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (34x28)_4\n      rect:\n        serializedVersion: 2\n        x: 136\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 6286407dbf800964c8f4601d173a3717\n      internalID: 2622321733923217370\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (34x28)_5\n      rect:\n        serializedVersion: 2\n        x: 170\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 51155ed0ebdaeb640b5d4f7a13c2f8f1\n      internalID: 4508922478542092599\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (34x28)_6\n      rect:\n        serializedVersion: 2\n        x: 204\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: fe922cb5b644d424585e294f60a427fa\n      internalID: 850222469992291503\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (34x28)_7\n      rect:\n        serializedVersion: 2\n        x: 238\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 8d0b53182309d0b4e871310a8dab14d0\n      internalID: -7622230470964513380\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (34x28)_8\n      rect:\n        serializedVersion: 2\n        x: 272\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 3218c2a5d49a4b342bf598fcf604c284\n      internalID: -4453737675818896170\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (34x28)_9\n      rect:\n        serializedVersion: 2\n        x: 306\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: efd3cb48343b79d4eacba3717a5a7d8f\n      internalID: -6983562990028683331\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Idle (34x28)_10\n      rect:\n        serializedVersion: 2\n        x: 340\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 7b506b044bfa50f47a3367a5ee175a84\n      internalID: -1903310279220368910\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 78496ff07f6547a4ebc15f2ae3fd08a9\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/03-Pig/Jump (34x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: 146d5d1ee87dda846a2e0f8ee3a51339\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -6714613527932964215\n    second: Jump (34x28)_0\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Jump (34x28)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 86600fb7b50065b48b2bd7f5239d2ea8\n      internalID: -6714613527932964215\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: ec67ba8e4666a8b44b46a7b097423f25\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/03-Pig/Run (34x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: 5657325f0bc7e72478eb8ff5b5f5e845\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: 5287780966827553206\n    second: Run (34x28)_0\n  - first:\n      213: -8523111416270535624\n    second: Run (34x28)_1\n  - first:\n      213: 2478249536684720882\n    second: Run (34x28)_2\n  - first:\n      213: -6893775213456251399\n    second: Run (34x28)_3\n  - first:\n      213: -6883968133703189721\n    second: Run (34x28)_4\n  - first:\n      213: 8378798624735198860\n    second: Run (34x28)_5\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Run (34x28)_0\n      rect:\n        serializedVersion: 2\n        x: 0\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 96b1e5aff7c538049bc3e0c17332306a\n      internalID: 5287780966827553206\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (34x28)_1\n      rect:\n        serializedVersion: 2\n        x: 34\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: c2b5da98c036c264fa0876cb1071e4e5\n      internalID: -8523111416270535624\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (34x28)_2\n      rect:\n        serializedVersion: 2\n        x: 68\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: d3ca0cc7f66357c4f8d3b86aa50ad4e0\n      internalID: 2478249536684720882\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (34x28)_3\n      rect:\n        serializedVersion: 2\n        x: 102\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 6f63bab24136b7f43ad4c9d4133b2f0d\n      internalID: -6893775213456251399\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (34x28)_4\n      rect:\n        serializedVersion: 2\n        x: 136\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 2ff67e243275e714e9fe521f0beaac8c\n      internalID: -6883968133703189721\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Run (34x28)_5\n      rect:\n        serializedVersion: 2\n        x: 170\n        y: 0\n        width: 34\n        height: 28\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: f872adac81d73fa4ba523e848fab1375\n      internalID: 8378798624735198860\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 7b6fd64789894c242b0a220accb40b59\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/03-Pig.meta",
    "content": "fileFormatVersion: 2\nguid: 0a2f5a4cac1d8a54c8fb5d7625b9f1b7\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/04-Pig Throwing a Box/Idle (26x30).png.meta",
    "content": "fileFormatVersion: 2\nguid: 8cf98e9afa1b6aa48b01242ca7d4250e\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/04-Pig Throwing a Box/Picking Box (26x30).png.meta",
    "content": "fileFormatVersion: 2\nguid: f93dcb10cf9d2aa4b829b98aa00b5a7a\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/04-Pig Throwing a Box/Run (26x30).png.meta",
    "content": "fileFormatVersion: 2\nguid: 479ffe1ce76cfb946985ec417af3b5d9\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/04-Pig Throwing a Box/Throwing Box (26x30).png.meta",
    "content": "fileFormatVersion: 2\nguid: f0a1c00a807ef854187e6e1518d0e065\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/04-Pig Throwing a Box.meta",
    "content": "fileFormatVersion: 2\nguid: 2e9e9a707add5454a80f235cda7101af\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/05-Pig Thowing a Bomb/Idle (26x26).png.meta",
    "content": "fileFormatVersion: 2\nguid: 3673cba0ca112554d9c389e0cb807962\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/05-Pig Thowing a Bomb/Picking Bomb (26x26).png.meta",
    "content": "fileFormatVersion: 2\nguid: 0132987b75a9e2840b0e461e7efd9d1e\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/05-Pig Thowing a Bomb/Run (26x26).png.meta",
    "content": "fileFormatVersion: 2\nguid: cc8c6860c1daf344aaf2e575569a2fa9\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/05-Pig Thowing a Bomb/Throwing Boom (26x26).png.meta",
    "content": "fileFormatVersion: 2\nguid: 409088ad967251e41ab2f1f1fcfad944\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/05-Pig Thowing a Bomb.meta",
    "content": "fileFormatVersion: 2\nguid: d48671a37b1d07a48902b9442a292e8d\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/06-Pig Hide in the Box/Fall (26x20).png.meta",
    "content": "fileFormatVersion: 2\nguid: 31529d804563c6246a78885cef9a1a60\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/06-Pig Hide in the Box/Ground (26x20).png.meta",
    "content": "fileFormatVersion: 2\nguid: c241cf190e3da7e499486391b91681af\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/06-Pig Hide in the Box/Jump (26x20).png.meta",
    "content": "fileFormatVersion: 2\nguid: 22a4d4a6f85f360439b03ab0465274bc\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/06-Pig Hide in the Box/Jump Anticipation (26x20).png.meta",
    "content": "fileFormatVersion: 2\nguid: b9d0701a77e36594a82e9fdab5fdede7\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/06-Pig Hide in the Box/Looking Out (26x20).png.meta",
    "content": "fileFormatVersion: 2\nguid: 8ed7e17959c9d9a43bb91b3e7704eba6\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/06-Pig Hide in the Box.meta",
    "content": "fileFormatVersion: 2\nguid: 570f98b5200d5fc42a36fab8b9de755c\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/07-Pig With a Match/Lighting the Cannon (26x18).png.meta",
    "content": "fileFormatVersion: 2\nguid: a4110510603b7ad428a88f5d2006a56a\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/07-Pig With a Match/Lighting the Match (26x18).png.meta",
    "content": "fileFormatVersion: 2\nguid: 3d20a907ae27c134591cb4baf4a42717\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/07-Pig With a Match/Match On (26x18).png.meta",
    "content": "fileFormatVersion: 2\nguid: 9b0fc3f37ca16e541a9ffebeacf77f74\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/07-Pig With a Match.meta",
    "content": "fileFormatVersion: 2\nguid: 1613a36588163354c84b3994166ce703\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/08-Box/Box Pieces 1.png.meta",
    "content": "fileFormatVersion: 2\nguid: 2779dca38daaf9941a21d72997d57163\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/08-Box/Box Pieces 2.png.meta",
    "content": "fileFormatVersion: 2\nguid: 8602204f142c5ad4d909f66895985a9d\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/08-Box/Box Pieces 3.png.meta",
    "content": "fileFormatVersion: 2\nguid: a0ebc9ac151528f438a4491b6c0430c3\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/08-Box/Box Pieces 4.png.meta",
    "content": "fileFormatVersion: 2\nguid: b23736dfbe89b0f4782ef85ae5b0df9c\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/08-Box/Hit.png.meta",
    "content": "fileFormatVersion: 2\nguid: 1c8ef44991781c74698d5e9c2a8140aa\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/08-Box/Idle.png.meta",
    "content": "fileFormatVersion: 2\nguid: c50454672967aa342aea76a937f9ea55\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/08-Box.meta",
    "content": "fileFormatVersion: 2\nguid: 70b2b603681428c42b097bf6c9569242\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/09-Bomb/Bomb Off.png.meta",
    "content": "fileFormatVersion: 2\nguid: 50251cc45d6ec974485ce88c97d62f71\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/09-Bomb/Bomb On (52x56).png.meta",
    "content": "fileFormatVersion: 2\nguid: 65882d57dae63cb479c49ba7f793f65c\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/09-Bomb/Boooooom (52x56).png.meta",
    "content": "fileFormatVersion: 2\nguid: 317d7490385497347b59bd832c9f74ef\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/09-Bomb.meta",
    "content": "fileFormatVersion: 2\nguid: cf6873e15ee83ba43940a5d81b278893\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/10-Cannon/Cannon Ball.png.meta",
    "content": "fileFormatVersion: 2\nguid: 4fae949030c5db048b55f5407c234fe0\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/10-Cannon/Idle.png.meta",
    "content": "fileFormatVersion: 2\nguid: 4839171976f1849448163570d87b40d2\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/10-Cannon/Shoot (44x28).png.meta",
    "content": "fileFormatVersion: 2\nguid: 380421a378b15d9449732c2ebe6484ab\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/10-Cannon.meta",
    "content": "fileFormatVersion: 2\nguid: 3b9d4eb24a9ecbe438e7f4ea781cec63\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/11-Door/Closiong (46x56).png.meta",
    "content": "fileFormatVersion: 2\nguid: 8032c64faf961aa4088227af86d24ad0\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/11-Door/Idle.png.meta",
    "content": "fileFormatVersion: 2\nguid: 254afd0b68a113f469829458201c54eb\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/11-Door/Opening (46x56).png.meta",
    "content": "fileFormatVersion: 2\nguid: 955759dc879cf844094bc8852bc2f24b\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/11-Door.meta",
    "content": "fileFormatVersion: 2\nguid: cfea49ef6eb95544a9714b70f437611c\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/12-Live and Coins/Big Diamond Hit (18x14).png.meta",
    "content": "fileFormatVersion: 2\nguid: a90c5e93c2047b74c9a3fe41579a65a7\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/12-Live and Coins/Big Diamond Idle (18x14).png.meta",
    "content": "fileFormatVersion: 2\nguid: b48fc8d4a6ca84e42bc3b8d851d2d78e\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/12-Live and Coins/Big Heart Hit (18x14).png.meta",
    "content": "fileFormatVersion: 2\nguid: e4f4d73d71cdc3248987912aebc0cee0\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/12-Live and Coins/Big Heart Idle (18x14).png.meta",
    "content": "fileFormatVersion: 2\nguid: a3393c6efd8be3649ae766def4840316\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/12-Live and Coins/Live Bar.png.meta",
    "content": "fileFormatVersion: 2\nguid: d86885a3bddd8c448aba1e8c05650fd4\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/12-Live and Coins/Numbers (6x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: 46c2b87e3b74ad84dbd4c5e14f64808f\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/12-Live and Coins/Small Diamond (18x14).png.meta",
    "content": "fileFormatVersion: 2\nguid: ea824460450a4914eae51aa6963b86f1\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/12-Live and Coins/Small Heart Hit (18x14).png.meta",
    "content": "fileFormatVersion: 2\nguid: 61f82631c8de9cf43ac2a1e711bcf30f\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/12-Live and Coins/Small Heart Idle (18x14).png.meta",
    "content": "fileFormatVersion: 2\nguid: 4f5795eea8f1e9d468bda198f7118732\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/12-Live and Coins.meta",
    "content": "fileFormatVersion: 2\nguid: 6ab3d9a38ea626b4c9b51e9c3b331bae\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/!!! In (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: 1b75ab7ad1bd20f4eb1ab04a28b0e054\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -8312444205416982654\n    second: '!!! In (24x8)_0'\n  - first:\n      213: -9064495398352640142\n    second: '!!! In (24x8)_1'\n  - first:\n      213: -5965135888694036443\n    second: '!!! In (24x8)_2'\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: '!!! In (24x8)_0'\n      rect:\n        serializedVersion: 2\n        x: 12\n        y: 4\n        width: 10\n        height: 8\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 379cf651cb0cd904a8715036248ab06d\n      internalID: -8312444205416982654\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: '!!! In (24x8)_1'\n      rect:\n        serializedVersion: 2\n        x: 43\n        y: 0\n        width: 16\n        height: 15\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: f1a964145109140499cc0d4f61cf5ef5\n      internalID: -9064495398352640142\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: '!!! In (24x8)_2'\n      rect:\n        serializedVersion: 2\n        x: 78\n        y: 1\n        width: 14\n        height: 13\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 11fcaa5f4d2b3d0438d5f692114043d8\n      internalID: -5965135888694036443\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: f041830d094dcf347831460f21278c8b\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/!!! Out (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: 5efdc59a056085544b2d6388eb8a0525\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: 1830721167890027643\n    second: '!!! Out (24x8)_0'\n  - first:\n      213: -7266911070107678448\n    second: '!!! Out (24x8)_1'\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: '!!! Out (24x8)_0'\n      rect:\n        serializedVersion: 2\n        x: 9\n        y: 0\n        width: 16\n        height: 15\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: a37b527b59bcacd40973046f7cb71567\n      internalID: 1830721167890027643\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: '!!! Out (24x8)_1'\n      rect:\n        serializedVersion: 2\n        x: 46\n        y: 4\n        width: 10\n        height: 8\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: b4e794aaed3c6f940a922b5f95eb8461\n      internalID: -7266911070107678448\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 3a5283e03a2fe5b46b7dd950b4f70038\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/Attack In (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: 3ba10505a0fe01c419c3ead37b4dd9b5\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: 1187759629007415879\n    second: Attack In (24x8)_0\n  - first:\n      213: 45798349028429436\n    second: Attack In (24x8)_1\n  - first:\n      213: -3233576187388521794\n    second: Attack In (24x8)_2\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Attack In (24x8)_0\n      rect:\n        serializedVersion: 2\n        x: 2\n        y: 4\n        width: 30\n        height: 8\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: a33cfe74419f88a4788a3af2fabfc8b3\n      internalID: 1187759629007415879\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Attack In (24x8)_1\n      rect:\n        serializedVersion: 2\n        x: 34\n        y: 0\n        width: 34\n        height: 15\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 59c19db2c4225a04db79770621e8fe6d\n      internalID: 45798349028429436\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Attack In (24x8)_2\n      rect:\n        serializedVersion: 2\n        x: 69\n        y: 1\n        width: 32\n        height: 13\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: ad8647773874a9d409a262988af9900e\n      internalID: -3233576187388521794\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 0622a663ad77ad0409a824445018e08f\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/Attack Out (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: 5eaa556bbbdb03143a7901f1ef64fec9\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 1a22c785fab50da4ca56eeb43a068f2e\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/Boom In (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: b2decc89e2dec2e458bd0d422000be3b\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 4964750be0d985040a42327af0e4c8ea\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/Boom Out (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: feabc8d44f8d4ad44a1d83256a7b3349\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: cd1c7525589ea3e4690224f0a9782e06\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/Dead In (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: e607fd401585dd04f96443dfb37292ab\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 3ea27b553292b8f418f63ebb5b9723b3\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/Dead Out (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: 3a1454f144294374b89f5de9478cd8bc\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 5cb8e6ca18f59ca4db6b9e23aad5cfcf\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/Hello In (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: 8f46d1d28a733c24e8dc44bd75f25a05\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: c4f85af772257bb45ae3807a2a45c190\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/Hello Out (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: ec90c058988087a49bf68feaf8e21cef\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 997bade5263103d4c88db42c65edcc02\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/Hi In (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: c4d050242ad66e14c995c2440d8e6081\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 094f18d582a61c54eaff52eae21c4632\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/Hi Out (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: 4cbe90c1a87eed945ad4756bd0215811\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 62da60065fbb2154496c5502e762a9ea\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/Interrogation In (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: d161976930aac7243ad0718bbf2ffe85\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 4c45755f685f2eb46be1bf88110144d3\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/Interrogation Out (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: 4f574a703103f7d4fae09497f8a33886\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: bffaf95c2c5e6d8499240a1a26f474eb\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/Loser In (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: d618dc9e19a7dfe4795a6e1b534d023b\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 516834209b9b0384ba52d8f76fe53bf2\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/Loser Out (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: b908a05b0a04bd8438b2b64c7ed9b494\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: c3bda979670020c4fa7352e7b4adec45\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/No In (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: 27626cab53595d04c9c027e7e6b8b3d0\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: a2fa211b01b0e1b41bd2dd0d48cca3b4\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/No Out (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: 715c271ea10b36841a6995c691e8139d\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 5cbfd70e05d3b40459327ff661a59dcb\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/WTF In (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: e65a9e883fda5df4f9fd804e566bf07d\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 58a692a729a123e43b1b61ff06335778\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes/WTF Out (24x8).png.meta",
    "content": "fileFormatVersion: 2\nguid: 8dcc978c529ece64baa5f814627ae92f\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: a5da07331dcf5b24ba731ddceef890bd\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/13-Dialogue Boxes.meta",
    "content": "fileFormatVersion: 2\nguid: ee90a7d8eda8bdb4c80dd3be44de74bf\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Decorations (32x32).png.meta",
    "content": "fileFormatVersion: 2\nguid: e1d8d9543b88cea439659f09cc93c946\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -8605479602969983287\n    second: Decorations (32x32)_0\n  - first:\n      213: 4600129511770090565\n    second: Decorations (32x32)_1\n  - first:\n      213: -399538571583186172\n    second: Decorations (32x32)_2\n  - first:\n      213: 3406356269320503256\n    second: Decorations (32x32)_3\n  - first:\n      213: -1075017349056126811\n    second: Decorations (32x32)_4\n  - first:\n      213: -8255700023269317997\n    second: Decorations (32x32)_5\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Decorations (32x32)_0\n      rect:\n        serializedVersion: 2\n        x: 35\n        y: 71\n        width: 26\n        height: 89\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: a1b964fd4d94b624c9aca8a53bdbb179\n      internalID: -8605479602969983287\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Decorations (32x32)_1\n      rect:\n        serializedVersion: 2\n        x: 64\n        y: 153\n        width: 128\n        height: 7\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 5a2c7d6e90e4acd41a81b8e1f3d75e30\n      internalID: 4600129511770090565\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Decorations (32x32)_2\n      rect:\n        serializedVersion: 2\n        x: 64\n        y: 113\n        width: 128\n        height: 15\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 59b2120cd5ff2e84d952782b495ea7df\n      internalID: -399538571583186172\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Decorations (32x32)_3\n      rect:\n        serializedVersion: 2\n        x: 35\n        y: 39\n        width: 26\n        height: 25\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: d4c14b626719dea48bce04a42d597ab8\n      internalID: 3406356269320503256\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Decorations (32x32)_4\n      rect:\n        serializedVersion: 2\n        x: 73\n        y: 32\n        width: 55\n        height: 57\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 7f1e2322fa07187469a019422d570407\n      internalID: -1075017349056126811\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Decorations (32x32)_5\n      rect:\n        serializedVersion: 2\n        x: 137\n        y: 32\n        width: 55\n        height: 57\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: f7a2af53f4457224f907050cf48ff045\n      internalID: -8255700023269317997\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: ebc10411048c21e49a3f671e5294746d\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32).png.meta",
    "content": "fileFormatVersion: 2\nguid: c30df8d60c651bb4e91f5c99553a7117\nTextureImporter:\n  internalIDToNameTable:\n  - first:\n      213: -2113894134886356154\n    second: Terrain (32x32)_0\n  - first:\n      213: -9114847578740223409\n    second: Terrain (32x32)_1\n  - first:\n      213: 4239696434956193796\n    second: Terrain (32x32)_2\n  - first:\n      213: 8516645164251878092\n    second: Terrain (32x32)_3\n  - first:\n      213: 3709395470188729914\n    second: Terrain (32x32)_4\n  - first:\n      213: -1459069242253791122\n    second: Terrain (32x32)_5\n  - first:\n      213: 8749005635180653793\n    second: Terrain (32x32)_6\n  - first:\n      213: -2363056867471366736\n    second: Terrain (32x32)_7\n  - first:\n      213: -4332446442371571619\n    second: Terrain (32x32)_8\n  - first:\n      213: -8883423204702779729\n    second: Terrain (32x32)_9\n  - first:\n      213: 8103538333889938161\n    second: Terrain (32x32)_10\n  - first:\n      213: 9048098576551171047\n    second: Terrain (32x32)_11\n  - first:\n      213: 5550582127777731385\n    second: Terrain (32x32)_12\n  - first:\n      213: -7635356268976036439\n    second: Terrain (32x32)_13\n  - first:\n      213: 1157080223378462048\n    second: Terrain (32x32)_14\n  - first:\n      213: -6403107747435768202\n    second: Terrain (32x32)_15\n  - first:\n      213: -1544894614388092976\n    second: Terrain (32x32)_16\n  - first:\n      213: 4217461280459406555\n    second: Terrain (32x32)_17\n  - first:\n      213: -4930185675006519976\n    second: Terrain (32x32)_18\n  - first:\n      213: -4696632766430068495\n    second: Terrain (32x32)_19\n  - first:\n      213: 1243350276117333252\n    second: Terrain (32x32)_20\n  - first:\n      213: 3385679346202453554\n    second: Terrain (32x32)_21\n  - first:\n      213: 8738314733589638094\n    second: Terrain (32x32)_22\n  - first:\n      213: 8666830670597921376\n    second: Terrain (32x32)_23\n  - first:\n      213: -2936791710745090628\n    second: Terrain (32x32)_24\n  - first:\n      213: -1707878253529702307\n    second: Terrain (32x32)_25\n  - first:\n      213: -8728383186345377599\n    second: Terrain (32x32)_26\n  - first:\n      213: -8776397432039939674\n    second: Terrain (32x32)_27\n  - first:\n      213: 5097210526339842007\n    second: Terrain (32x32)_28\n  - first:\n      213: -2513879346030493484\n    second: Terrain (32x32)_29\n  - first:\n      213: -2969041350847514635\n    second: Terrain (32x32)_30\n  - first:\n      213: -1610354790490889277\n    second: Terrain (32x32)_31\n  - first:\n      213: -6560276675822979386\n    second: Terrain (32x32)_32\n  - first:\n      213: 4868307182515750219\n    second: Terrain (32x32)_33\n  - first:\n      213: 8889031353144245513\n    second: Terrain (32x32)_34\n  - first:\n      213: -12324268454884066\n    second: Terrain (32x32)_35\n  - first:\n      213: -1012594953271071554\n    second: Terrain (32x32)_36\n  - first:\n      213: -915352507628530066\n    second: Terrain (32x32)_37\n  - first:\n      213: 5504718189712137809\n    second: Terrain (32x32)_38\n  - first:\n      213: -6567338993810207375\n    second: Terrain (32x32)_39\n  - first:\n      213: -1647517347931888083\n    second: Terrain (32x32)_40\n  - first:\n      213: 299559052996832441\n    second: Terrain (32x32)_41\n  - first:\n      213: 6502491142666883771\n    second: Terrain (32x32)_42\n  - first:\n      213: 6885127967015840319\n    second: Terrain (32x32)_43\n  - first:\n      213: -8283676517091711715\n    second: Terrain (32x32)_44\n  - first:\n      213: 8576845579221683551\n    second: Terrain (32x32)_45\n  - first:\n      213: -5709979240835780729\n    second: Terrain (32x32)_46\n  - first:\n      213: -3920501327658573059\n    second: Terrain (32x32)_47\n  - first:\n      213: 6960820363678352256\n    second: Terrain (32x32)_48\n  - first:\n      213: 2361261416710784685\n    second: Terrain (32x32)_49\n  - first:\n      213: 8748934533700571379\n    second: Terrain (32x32)_50\n  - first:\n      213: -1003237281556518101\n    second: Terrain (32x32)_51\n  - first:\n      213: 2167178641356693581\n    second: Terrain (32x32)_52\n  - first:\n      213: -5688414592579563010\n    second: Terrain (32x32)_53\n  - first:\n      213: -1776422394228139669\n    second: Terrain (32x32)_54\n  - first:\n      213: 1022654863282120246\n    second: Terrain (32x32)_55\n  - first:\n      213: -996657573564455507\n    second: Terrain (32x32)_56\n  - first:\n      213: -5450112882807951249\n    second: Terrain (32x32)_57\n  - first:\n      213: 8837929274236208049\n    second: Terrain (32x32)_58\n  - first:\n      213: 8969087632853882348\n    second: Terrain (32x32)_59\n  - first:\n      213: 4478376099278307188\n    second: Terrain (32x32)_60\n  - first:\n      213: -1618197503159607877\n    second: Terrain (32x32)_61\n  - first:\n      213: -3380924289088166150\n    second: Terrain (32x32)_62\n  - first:\n      213: -8801291986591181387\n    second: Terrain (32x32)_63\n  - first:\n      213: -5645681066066357911\n    second: Terrain (32x32)_64\n  - first:\n      213: 538909327932558817\n    second: Terrain (32x32)_65\n  - first:\n      213: -4526886444840449869\n    second: Terrain (32x32)_66\n  - first:\n      213: 2913865528524152843\n    second: Terrain (32x32)_67\n  - first:\n      213: -2694742046232445392\n    second: Terrain (32x32)_68\n  - first:\n      213: -5611627923302939328\n    second: Terrain (32x32)_69\n  - first:\n      213: 6705844512150175775\n    second: Terrain (32x32)_70\n  - first:\n      213: 7756992474786954701\n    second: Terrain (32x32)_71\n  - first:\n      213: 5139404228693232197\n    second: Terrain (32x32)_72\n  - first:\n      213: -2701651782496971736\n    second: Terrain (32x32)_73\n  - first:\n      213: -6938149047964805663\n    second: Terrain (32x32)_74\n  - first:\n      213: -1548899832515325878\n    second: Terrain (32x32)_75\n  - first:\n      213: 5862921262446552523\n    second: Terrain (32x32)_76\n  - first:\n      213: 8006257600266145971\n    second: Terrain (32x32)_77\n  - first:\n      213: -3741181219524698823\n    second: Terrain (32x32)_78\n  - first:\n      213: -4524798020415664492\n    second: Terrain (32x32)_79\n  - first:\n      213: -2329063528070192035\n    second: Terrain (32x32)_80\n  - first:\n      213: -3313916609126551260\n    second: Terrain (32x32)_81\n  - first:\n      213: 4355139645102990892\n    second: Terrain (32x32)_82\n  - first:\n      213: 7276521402011691325\n    second: Terrain (32x32)_83\n  - first:\n      213: 630469584464062596\n    second: Terrain (32x32)_84\n  - first:\n      213: 3321075107539641400\n    second: Terrain (32x32)_85\n  - first:\n      213: -2560665351331762178\n    second: Terrain (32x32)_86\n  - first:\n      213: -388972771637846921\n    second: Terrain (32x32)_87\n  - first:\n      213: 6073694606739076769\n    second: Terrain (32x32)_88\n  - first:\n      213: -4537407130766249925\n    second: Terrain (32x32)_89\n  - first:\n      213: 6677824962274982429\n    second: Terrain (32x32)_90\n  - first:\n      213: -360585890479614453\n    second: Terrain (32x32)_91\n  - first:\n      213: -6808164498187367688\n    second: Terrain (32x32)_92\n  - first:\n      213: -3663827148789875764\n    second: Terrain (32x32)_93\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 0\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: 1\n    wrapV: 1\n    wrapW: -1\n  nPOTScale: 0\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 2\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 1\n  spriteTessellationDetail: -1\n  textureType: 8\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Standalone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: iPhone\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  - serializedVersion: 2\n    buildTarget: Android\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites:\n    - serializedVersion: 2\n      name: Terrain (32x32)_0\n      rect:\n        serializedVersion: 2\n        x: 32\n        y: 352\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: b3a500bfac90c404f8c1b0b0ba7fb823\n      internalID: -2113894134886356154\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_1\n      rect:\n        serializedVersion: 2\n        x: 64\n        y: 352\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: f82336e755fc6c34fa25a7499133001a\n      internalID: -9114847578740223409\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_2\n      rect:\n        serializedVersion: 2\n        x: 96\n        y: 352\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 350d2eb211e449e4bbc0c414eba373c3\n      internalID: 4239696434956193796\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_3\n      rect:\n        serializedVersion: 2\n        x: 160\n        y: 352\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: ff32e736b49328848b55b1b175c40d53\n      internalID: 8516645164251878092\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_4\n      rect:\n        serializedVersion: 2\n        x: 224\n        y: 352\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 79f7c03e1a21b934b8a69c4f8deddccf\n      internalID: 3709395470188729914\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_5\n      rect:\n        serializedVersion: 2\n        x: 256\n        y: 352\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 19308c06ed0a8dd43a4bb4ae289cb69e\n      internalID: -1459069242253791122\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_6\n      rect:\n        serializedVersion: 2\n        x: 320\n        y: 352\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 8e3c5e3cdf0b06348b29390fe2befbd0\n      internalID: 8749005635180653793\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_7\n      rect:\n        serializedVersion: 2\n        x: 352\n        y: 352\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 77fae825a389676408e717998ba640d8\n      internalID: -2363056867471366736\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_8\n      rect:\n        serializedVersion: 2\n        x: 416\n        y: 352\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: c71b122f1b5610748980b0a8689b9be3\n      internalID: -4332446442371571619\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_9\n      rect:\n        serializedVersion: 2\n        x: 448\n        y: 352\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 4a33e3d3bfe2bf84cb2c7ddaf5eb2c3e\n      internalID: -8883423204702779729\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_10\n      rect:\n        serializedVersion: 2\n        x: 512\n        y: 352\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 2354d38ecbe37f542a5e124dc1aede48\n      internalID: 8103538333889938161\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_11\n      rect:\n        serializedVersion: 2\n        x: 32\n        y: 320\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: d1a4c65fd499e2947811e681e6000cbe\n      internalID: 9048098576551171047\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_12\n      rect:\n        serializedVersion: 2\n        x: 64\n        y: 320\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 3dc2e05a416ab5145b63e833b27843f4\n      internalID: 5550582127777731385\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_13\n      rect:\n        serializedVersion: 2\n        x: 96\n        y: 320\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 68afa4bfc86e02b4bba54667cd1df1fa\n      internalID: -7635356268976036439\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_14\n      rect:\n        serializedVersion: 2\n        x: 160\n        y: 320\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: ff45d10a6824c174da6540620b41aa48\n      internalID: 1157080223378462048\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_15\n      rect:\n        serializedVersion: 2\n        x: 224\n        y: 320\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: a75b8f973989f7b429c26c5c840282bc\n      internalID: -6403107747435768202\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_16\n      rect:\n        serializedVersion: 2\n        x: 256\n        y: 320\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: de624275036ba0c4298116e426761f2b\n      internalID: -1544894614388092976\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_17\n      rect:\n        serializedVersion: 2\n        x: 320\n        y: 320\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: b3f4820e056ddfc4fa7a6915a7993971\n      internalID: 4217461280459406555\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_18\n      rect:\n        serializedVersion: 2\n        x: 352\n        y: 320\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: bd42e6b2e3d321844ab859dbe5403ee2\n      internalID: -4930185675006519976\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_19\n      rect:\n        serializedVersion: 2\n        x: 416\n        y: 320\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 86d2312d32641d448b3e5e308bcc9f3c\n      internalID: -4696632766430068495\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_20\n      rect:\n        serializedVersion: 2\n        x: 448\n        y: 320\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 96fc6d8049bc1be46a4172a4ff126375\n      internalID: 1243350276117333252\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_21\n      rect:\n        serializedVersion: 2\n        x: 512\n        y: 320\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 004439ae3d5a862489d69d44942fc23f\n      internalID: 3385679346202453554\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_22\n      rect:\n        serializedVersion: 2\n        x: 544\n        y: 320\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 003151cb7250cbc4581ff2bdd77007eb\n      internalID: 8738314733589638094\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_23\n      rect:\n        serializedVersion: 2\n        x: 32\n        y: 288\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 2d28fe80e46c041429be4d9f7592d17a\n      internalID: 8666830670597921376\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_24\n      rect:\n        serializedVersion: 2\n        x: 64\n        y: 288\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 7c8fc4fad7d67f4459e19a6552552221\n      internalID: -2936791710745090628\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_25\n      rect:\n        serializedVersion: 2\n        x: 96\n        y: 288\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: ecf39802308f6604687c2be03ca96800\n      internalID: -1707878253529702307\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_26\n      rect:\n        serializedVersion: 2\n        x: 160\n        y: 288\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: fc0c2054115a8cb43a38505bf17d8014\n      internalID: -8728383186345377599\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_27\n      rect:\n        serializedVersion: 2\n        x: 224\n        y: 256\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 2da4d1f5676e5af4b9936787e365dc60\n      internalID: -8776397432039939674\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_28\n      rect:\n        serializedVersion: 2\n        x: 256\n        y: 256\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: c93667e30c395d9439bde8018b33b58a\n      internalID: 5097210526339842007\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_29\n      rect:\n        serializedVersion: 2\n        x: 320\n        y: 256\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 4172d368fb5fdc84e8155a07fc1e023d\n      internalID: -2513879346030493484\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_30\n      rect:\n        serializedVersion: 2\n        x: 352\n        y: 256\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: c61f023cf1fb11f43807339008a6235a\n      internalID: -2969041350847514635\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_31\n      rect:\n        serializedVersion: 2\n        x: 416\n        y: 256\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 750425b644d954d4ab438ee64cf94a66\n      internalID: -1610354790490889277\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_32\n      rect:\n        serializedVersion: 2\n        x: 448\n        y: 256\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 5fbf9a0b3942a4641b17e04832478747\n      internalID: -6560276675822979386\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_33\n      rect:\n        serializedVersion: 2\n        x: 512\n        y: 256\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 56193e57b2456a448b0f333a177c177c\n      internalID: 4868307182515750219\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_34\n      rect:\n        serializedVersion: 2\n        x: 544\n        y: 256\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 17407ecd586ad654c96f42fe9de8f579\n      internalID: 8889031353144245513\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_35\n      rect:\n        serializedVersion: 2\n        x: 32\n        y: 224\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 884137cd3384fcb4eabe88f1b00f0417\n      internalID: -12324268454884066\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_36\n      rect:\n        serializedVersion: 2\n        x: 64\n        y: 224\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 411b09064baacd543a6bb0c33a34f4ba\n      internalID: -1012594953271071554\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_37\n      rect:\n        serializedVersion: 2\n        x: 96\n        y: 224\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 86af95b2f88edc947ab8ac205566089f\n      internalID: -915352507628530066\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_38\n      rect:\n        serializedVersion: 2\n        x: 160\n        y: 224\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: eee391300138def4a9ced2ed3a19bf3a\n      internalID: 5504718189712137809\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_39\n      rect:\n        serializedVersion: 2\n        x: 224\n        y: 224\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 15b84982703295b4bac4935bbbbbd8d9\n      internalID: -6567338993810207375\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_40\n      rect:\n        serializedVersion: 2\n        x: 256\n        y: 224\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 269698b49132f454bb473d99d5a96e4d\n      internalID: -1647517347931888083\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_41\n      rect:\n        serializedVersion: 2\n        x: 320\n        y: 224\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: ff8b177c143e8cb45b29b4302b77649d\n      internalID: 299559052996832441\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_42\n      rect:\n        serializedVersion: 2\n        x: 352\n        y: 224\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: c2c6d84e0128d7443bec55dd551cc68d\n      internalID: 6502491142666883771\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_43\n      rect:\n        serializedVersion: 2\n        x: 416\n        y: 224\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 507fda07370b8ab4aa37c2ebe79f4291\n      internalID: 6885127967015840319\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_44\n      rect:\n        serializedVersion: 2\n        x: 448\n        y: 224\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 1b05fb1d499ff9d48b60564907140313\n      internalID: -8283676517091711715\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_45\n      rect:\n        serializedVersion: 2\n        x: 512\n        y: 224\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 15be925d60df9d7419c4f35d86b59fb2\n      internalID: 8576845579221683551\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_46\n      rect:\n        serializedVersion: 2\n        x: 544\n        y: 224\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 34cac34eaea67c24d85f17fcb5c4ca87\n      internalID: -5709979240835780729\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_47\n      rect:\n        serializedVersion: 2\n        x: 32\n        y: 160\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 5896e6ea6aeff2543a1b281143f00740\n      internalID: -3920501327658573059\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_48\n      rect:\n        serializedVersion: 2\n        x: 64\n        y: 160\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 8d46f774a70a1c04ca6f1046cadc83a2\n      internalID: 6960820363678352256\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_49\n      rect:\n        serializedVersion: 2\n        x: 96\n        y: 160\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: d7977a1f06ed3544ab1b25e94bcb6d74\n      internalID: 2361261416710784685\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_50\n      rect:\n        serializedVersion: 2\n        x: 160\n        y: 160\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 32dd2fbabf4002644a94f3dbfeeb6d1b\n      internalID: 8748934533700571379\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_51\n      rect:\n        serializedVersion: 2\n        x: 224\n        y: 160\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 8c6a40a7a93ed8647a73ce9b4d4211a4\n      internalID: -1003237281556518101\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_52\n      rect:\n        serializedVersion: 2\n        x: 256\n        y: 160\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: b17f0331deef23049a05b45b531dee7a\n      internalID: 2167178641356693581\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_53\n      rect:\n        serializedVersion: 2\n        x: 320\n        y: 160\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: adaa4f36dad062b45a52bd87b287b1c3\n      internalID: -5688414592579563010\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_54\n      rect:\n        serializedVersion: 2\n        x: 352\n        y: 160\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: b836b2e2e7becaa4fbcb6c52c215cba2\n      internalID: -1776422394228139669\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_55\n      rect:\n        serializedVersion: 2\n        x: 416\n        y: 160\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 6228417bd24fc8649b0b6d18c8caa51d\n      internalID: 1022654863282120246\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_56\n      rect:\n        serializedVersion: 2\n        x: 448\n        y: 160\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 190b35b204988984388db56a1be6752b\n      internalID: -996657573564455507\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_57\n      rect:\n        serializedVersion: 2\n        x: 512\n        y: 160\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 2de0325f731320645a01bc6378cf0195\n      internalID: -5450112882807951249\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_58\n      rect:\n        serializedVersion: 2\n        x: 32\n        y: 128\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 0cea910aa149ce540a53ab6aac07e32f\n      internalID: 8837929274236208049\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_59\n      rect:\n        serializedVersion: 2\n        x: 64\n        y: 128\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 7f065e77ef72dae48a137ad0e626a943\n      internalID: 8969087632853882348\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_60\n      rect:\n        serializedVersion: 2\n        x: 96\n        y: 128\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 44c67b7bb0e388c4cbda7cf2b728ffe7\n      internalID: 4478376099278307188\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_61\n      rect:\n        serializedVersion: 2\n        x: 160\n        y: 128\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: d7b8f0f1f8bbfaa4dbd307a5a36c0b23\n      internalID: -1618197503159607877\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_62\n      rect:\n        serializedVersion: 2\n        x: 224\n        y: 128\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 3cb734cc435b5ab48b4c6f4509927efb\n      internalID: -3380924289088166150\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_63\n      rect:\n        serializedVersion: 2\n        x: 256\n        y: 128\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: c7e1f406834020747b08e515035c04bc\n      internalID: -8801291986591181387\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_64\n      rect:\n        serializedVersion: 2\n        x: 320\n        y: 128\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: d2a1d21f114e5ad4e937529c7c357146\n      internalID: -5645681066066357911\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_65\n      rect:\n        serializedVersion: 2\n        x: 352\n        y: 128\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 862224a77edf2cd4ca5e6b2c62a66623\n      internalID: 538909327932558817\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_66\n      rect:\n        serializedVersion: 2\n        x: 416\n        y: 128\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: e8da0619c9d48d94993851973b662a99\n      internalID: -4526886444840449869\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_67\n      rect:\n        serializedVersion: 2\n        x: 448\n        y: 128\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: aed02d754f54fdb4d9e78cde7bc34a3b\n      internalID: 2913865528524152843\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_68\n      rect:\n        serializedVersion: 2\n        x: 512\n        y: 128\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 99fb9141b41c2aa49b23638990ff0bc2\n      internalID: -2694742046232445392\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_69\n      rect:\n        serializedVersion: 2\n        x: 544\n        y: 128\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 9e3a221f93a21d541a968b636e50c333\n      internalID: -5611627923302939328\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_70\n      rect:\n        serializedVersion: 2\n        x: 32\n        y: 96\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 06152572318c3e046ab92819cf7f4d46\n      internalID: 6705844512150175775\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_71\n      rect:\n        serializedVersion: 2\n        x: 64\n        y: 96\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 693a21b0b376bd14e9a3d4f248a0e3f0\n      internalID: 7756992474786954701\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_72\n      rect:\n        serializedVersion: 2\n        x: 96\n        y: 96\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 4c0a4f5dff3284f479a2a94df6b5f1dd\n      internalID: 5139404228693232197\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_73\n      rect:\n        serializedVersion: 2\n        x: 160\n        y: 96\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: ab914785b092d0b4bb488ec0d9cb982b\n      internalID: -2701651782496971736\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_74\n      rect:\n        serializedVersion: 2\n        x: 224\n        y: 64\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 53401fbcb2169c540865546bdb0a50a3\n      internalID: -6938149047964805663\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_75\n      rect:\n        serializedVersion: 2\n        x: 256\n        y: 64\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 17ba0bbdd1d8ac4429e7aef26e4066a2\n      internalID: -1548899832515325878\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_76\n      rect:\n        serializedVersion: 2\n        x: 320\n        y: 64\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 2e86d4d136548e943a662e2aff865c18\n      internalID: 5862921262446552523\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_77\n      rect:\n        serializedVersion: 2\n        x: 352\n        y: 64\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 8081287826c72f940acf09265d760ed0\n      internalID: 8006257600266145971\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_78\n      rect:\n        serializedVersion: 2\n        x: 416\n        y: 64\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: bf82e18bccc5762448dd275f827503b8\n      internalID: -3741181219524698823\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_79\n      rect:\n        serializedVersion: 2\n        x: 448\n        y: 64\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 5fd821bed551054449273ea85cb35aaf\n      internalID: -4524798020415664492\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_80\n      rect:\n        serializedVersion: 2\n        x: 512\n        y: 64\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 08e74fee227d33343ad08b02ba14e8f8\n      internalID: -2329063528070192035\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_81\n      rect:\n        serializedVersion: 2\n        x: 544\n        y: 64\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 21952daf1db89804f9618657edfc111d\n      internalID: -3313916609126551260\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_82\n      rect:\n        serializedVersion: 2\n        x: 32\n        y: 32\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 50574118e1b6bd545b0f40c3d04fae19\n      internalID: 4355139645102990892\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_83\n      rect:\n        serializedVersion: 2\n        x: 64\n        y: 32\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: f6a7b279ff7c5a74bbe87873b31a7f02\n      internalID: 7276521402011691325\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_84\n      rect:\n        serializedVersion: 2\n        x: 96\n        y: 32\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 9c04988ca8f032546adf2397ab91aaff\n      internalID: 630469584464062596\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_85\n      rect:\n        serializedVersion: 2\n        x: 160\n        y: 32\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: e3fe5e7a7a9aa3f459cafab1c4c2694c\n      internalID: 3321075107539641400\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_86\n      rect:\n        serializedVersion: 2\n        x: 224\n        y: 32\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 824e67a9e06f0364ea4236d8d248d97a\n      internalID: -2560665351331762178\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_87\n      rect:\n        serializedVersion: 2\n        x: 256\n        y: 32\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: e5b75258f44c11044a5d45b9bfa6033c\n      internalID: -388972771637846921\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_88\n      rect:\n        serializedVersion: 2\n        x: 320\n        y: 32\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 3aea744fbec29c94b9980ca06e3c1545\n      internalID: 6073694606739076769\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_89\n      rect:\n        serializedVersion: 2\n        x: 352\n        y: 32\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 5b4e640ffb65a834eb3e38923ac1e7e8\n      internalID: -4537407130766249925\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_90\n      rect:\n        serializedVersion: 2\n        x: 416\n        y: 32\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 4a3e2f5fc5cbff14d9942f8301746b2c\n      internalID: 6677824962274982429\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_91\n      rect:\n        serializedVersion: 2\n        x: 448\n        y: 32\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: c981a80ef8015304fa362e2d14e6ccab\n      internalID: -360585890479614453\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_92\n      rect:\n        serializedVersion: 2\n        x: 512\n        y: 32\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: 86898b5a25046e648a1e9d5ae696d6d7\n      internalID: -6808164498187367688\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    - serializedVersion: 2\n      name: Terrain (32x32)_93\n      rect:\n        serializedVersion: 2\n        x: 544\n        y: 32\n        width: 32\n        height: 32\n      alignment: 0\n      pivot: {x: 0, y: 0}\n      border: {x: 0, y: 0, z: 0, w: 0}\n      outline: []\n      physicsShape: []\n      tessellationDetail: 0\n      bones: []\n      spriteID: b3162af598462144c84ad6fb224da346\n      internalID: -3663827148789875764\n      vertices: []\n      indices: \n      edges: []\n      weights: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: 888ee7c96104a804ba702121d7f0604e\n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_0.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!114 &11400000\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 0}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}\n  m_Name: Terrain (32x32)_0\n  m_EditorClassIdentifier: \n  m_Sprite: {fileID: -2113894134886356154, guid: c30df8d60c651bb4e91f5c99553a7117,\n    type: 3}\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_Transform:\n    e00: 1\n    e01: 0\n    e02: 0\n    e03: 0\n    e10: 0\n    e11: 1\n    e12: 0\n    e13: 0\n    e20: 0\n    e21: 0\n    e22: 1\n    e23: 0\n    e30: 0\n    e31: 0\n    e32: 0\n    e33: 1\n  m_InstancedGameObject: {fileID: 0}\n  m_Flags: 1\n  m_ColliderType: 1\n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_0.asset.meta",
    "content": "fileFormatVersion: 2\nguid: 02ee918df97067942877970e67eb3f76\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 11400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_1.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!114 &11400000\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 0}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}\n  m_Name: Terrain (32x32)_1\n  m_EditorClassIdentifier: \n  m_Sprite: {fileID: -9114847578740223409, guid: c30df8d60c651bb4e91f5c99553a7117,\n    type: 3}\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_Transform:\n    e00: 1\n    e01: 0\n    e02: 0\n    e03: 0\n    e10: 0\n    e11: 1\n    e12: 0\n    e13: 0\n    e20: 0\n    e21: 0\n    e22: 1\n    e23: 0\n    e30: 0\n    e31: 0\n    e32: 0\n    e33: 1\n  m_InstancedGameObject: {fileID: 0}\n  m_Flags: 1\n  m_ColliderType: 1\n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_1.asset.meta",
    "content": "fileFormatVersion: 2\nguid: 6ad0a965971cbbe42a8b6cc2792f0e59\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 11400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_11.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!114 &11400000\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 0}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}\n  m_Name: Terrain (32x32)_11\n  m_EditorClassIdentifier: \n  m_Sprite: {fileID: 9048098576551171047, guid: c30df8d60c651bb4e91f5c99553a7117,\n    type: 3}\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_Transform:\n    e00: 1\n    e01: 0\n    e02: 0\n    e03: 0\n    e10: 0\n    e11: 1\n    e12: 0\n    e13: 0\n    e20: 0\n    e21: 0\n    e22: 1\n    e23: 0\n    e30: 0\n    e31: 0\n    e32: 0\n    e33: 1\n  m_InstancedGameObject: {fileID: 0}\n  m_Flags: 1\n  m_ColliderType: 1\n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_11.asset.meta",
    "content": "fileFormatVersion: 2\nguid: 4903021c6067ced489a594416c114bff\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 11400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_12.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!114 &11400000\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 0}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}\n  m_Name: Terrain (32x32)_12\n  m_EditorClassIdentifier: \n  m_Sprite: {fileID: 5550582127777731385, guid: c30df8d60c651bb4e91f5c99553a7117,\n    type: 3}\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_Transform:\n    e00: 1\n    e01: 0\n    e02: 0\n    e03: 0\n    e10: 0\n    e11: 1\n    e12: 0\n    e13: 0\n    e20: 0\n    e21: 0\n    e22: 1\n    e23: 0\n    e30: 0\n    e31: 0\n    e32: 0\n    e33: 1\n  m_InstancedGameObject: {fileID: 0}\n  m_Flags: 1\n  m_ColliderType: 1\n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_12.asset.meta",
    "content": "fileFormatVersion: 2\nguid: d60c19cedbdfaf540a5224f2703d9185\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 11400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_13.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!114 &11400000\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 0}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}\n  m_Name: Terrain (32x32)_13\n  m_EditorClassIdentifier: \n  m_Sprite: {fileID: -7635356268976036439, guid: c30df8d60c651bb4e91f5c99553a7117,\n    type: 3}\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_Transform:\n    e00: 1\n    e01: 0\n    e02: 0\n    e03: 0\n    e10: 0\n    e11: 1\n    e12: 0\n    e13: 0\n    e20: 0\n    e21: 0\n    e22: 1\n    e23: 0\n    e30: 0\n    e31: 0\n    e32: 0\n    e33: 1\n  m_InstancedGameObject: {fileID: 0}\n  m_Flags: 1\n  m_ColliderType: 1\n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_13.asset.meta",
    "content": "fileFormatVersion: 2\nguid: 6fddaf8e8903e8b4a99c9e08b7ef4740\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 11400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_2.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!114 &11400000\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 0}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}\n  m_Name: Terrain (32x32)_2\n  m_EditorClassIdentifier: \n  m_Sprite: {fileID: 4239696434956193796, guid: c30df8d60c651bb4e91f5c99553a7117,\n    type: 3}\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_Transform:\n    e00: 1\n    e01: 0\n    e02: 0\n    e03: 0\n    e10: 0\n    e11: 1\n    e12: 0\n    e13: 0\n    e20: 0\n    e21: 0\n    e22: 1\n    e23: 0\n    e30: 0\n    e31: 0\n    e32: 0\n    e33: 1\n  m_InstancedGameObject: {fileID: 0}\n  m_Flags: 1\n  m_ColliderType: 1\n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_2.asset.meta",
    "content": "fileFormatVersion: 2\nguid: f4a4199d6aefaa543b081c23a3ce0a6a\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 11400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_23.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!114 &11400000\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 0}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}\n  m_Name: Terrain (32x32)_23\n  m_EditorClassIdentifier: \n  m_Sprite: {fileID: 8666830670597921376, guid: c30df8d60c651bb4e91f5c99553a7117,\n    type: 3}\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_Transform:\n    e00: 1\n    e01: 0\n    e02: 0\n    e03: 0\n    e10: 0\n    e11: 1\n    e12: 0\n    e13: 0\n    e20: 0\n    e21: 0\n    e22: 1\n    e23: 0\n    e30: 0\n    e31: 0\n    e32: 0\n    e33: 1\n  m_InstancedGameObject: {fileID: 0}\n  m_Flags: 1\n  m_ColliderType: 1\n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_23.asset.meta",
    "content": "fileFormatVersion: 2\nguid: de1a7bd3b973f4b459dfd60f5ba8c149\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 11400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_24.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!114 &11400000\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 0}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}\n  m_Name: Terrain (32x32)_24\n  m_EditorClassIdentifier: \n  m_Sprite: {fileID: -2936791710745090628, guid: c30df8d60c651bb4e91f5c99553a7117,\n    type: 3}\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_Transform:\n    e00: 1\n    e01: 0\n    e02: 0\n    e03: 0\n    e10: 0\n    e11: 1\n    e12: 0\n    e13: 0\n    e20: 0\n    e21: 0\n    e22: 1\n    e23: 0\n    e30: 0\n    e31: 0\n    e32: 0\n    e33: 1\n  m_InstancedGameObject: {fileID: 0}\n  m_Flags: 1\n  m_ColliderType: 1\n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_24.asset.meta",
    "content": "fileFormatVersion: 2\nguid: 2e6a9bfbab8e0c347ac12179f2a0f7a5\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 11400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_25.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!114 &11400000\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 0}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 13312, guid: 0000000000000000e000000000000000, type: 0}\n  m_Name: Terrain (32x32)_25\n  m_EditorClassIdentifier: \n  m_Sprite: {fileID: -1707878253529702307, guid: c30df8d60c651bb4e91f5c99553a7117,\n    type: 3}\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_Transform:\n    e00: 1\n    e01: 0\n    e02: 0\n    e03: 0\n    e10: 0\n    e11: 1\n    e12: 0\n    e13: 0\n    e20: 0\n    e21: 0\n    e22: 1\n    e23: 0\n    e30: 0\n    e31: 0\n    e32: 0\n    e33: 1\n  m_InstancedGameObject: {fileID: 0}\n  m_Flags: 1\n  m_ColliderType: 1\n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets/Terrain (32x32)_25.asset.meta",
    "content": "fileFormatVersion: 2\nguid: 9f26bff8983bce141ae2a7232cc3110c\nNativeFormatImporter:\n  externalObjects: {}\n  mainObjectFileID: 11400000\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/14-TileSets.meta",
    "content": "fileFormatVersion: 2\nguid: a9638703b0d4a5041b813e64a1984fcd\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/Kings and Pigs.png.meta",
    "content": "fileFormatVersion: 2\nguid: 80cfe7277384df845a0d75b8a7496809\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 10\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: -1\n    aniso: -1\n    mipBias: -100\n    wrapU: -1\n    wrapV: -1\n    wrapW: -1\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  platformSettings:\n  - serializedVersion: 2\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites/LICENSE.md",
    "content": "\n|||\n|:--|:--|\n|Author|Pixel Frog|\n|URL|https://pixelfrog-assets.itch.io/kings-and-pigs|\n|License|[![CC0](https://licensebuttons.net/p/zero/1.0/88x31.png)](http://creativecommons.org/publicdomain/zero/1.0/)|\n|||"
  },
  {
    "path": "Assets/Examples/Sprites/LICENSE.md.meta",
    "content": "fileFormatVersion: 2\nguid: 48878403b78237c418f6713df6faee20\nTextScriptImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Sprites.meta",
    "content": "fileFormatVersion: 2\nguid: 5bdb1224a3baf9e4eaf131401cf6a527\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Tiles/New Palette.prefab",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1 &2485922443281161203\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 4932602743896939386}\n  - component: {fileID: 2022612827952102804}\n  m_Layer: 31\n  m_Name: New Palette\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!4 &4932602743896939386\nTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 2485922443281161203}\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children:\n  - {fileID: 8068046143694938703}\n  m_Father: {fileID: 0}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n--- !u!156049354 &2022612827952102804\nGrid:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 2485922443281161203}\n  m_Enabled: 1\n  m_CellSize: {x: 0.32, y: 0.32, z: 0}\n  m_CellGap: {x: 0, y: 0, z: 0}\n  m_CellLayout: 0\n  m_CellSwizzle: 0\n--- !u!1 &9019164986347984336\nGameObject:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  serializedVersion: 6\n  m_Component:\n  - component: {fileID: 8068046143694938703}\n  - component: {fileID: 283772293279546334}\n  - component: {fileID: 7353399709395597127}\n  m_Layer: 31\n  m_Name: Layer1\n  m_TagString: Untagged\n  m_Icon: {fileID: 0}\n  m_NavMeshLayer: 0\n  m_StaticEditorFlags: 0\n  m_IsActive: 1\n--- !u!4 &8068046143694938703\nTransform:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 9019164986347984336}\n  m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}\n  m_LocalPosition: {x: 0, y: 0, z: 0}\n  m_LocalScale: {x: 1, y: 1, z: 1}\n  m_Children: []\n  m_Father: {fileID: 4932602743896939386}\n  m_RootOrder: 0\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\n--- !u!1839735485 &283772293279546334\nTilemap:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 9019164986347984336}\n  m_Enabled: 1\n  m_Tiles:\n  - first: {x: 2, y: -7, z: 0}\n    second:\n      m_TileIndex: 87\n      m_TileSpriteIndex: 87\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 93\n      m_ObjectToInstantiate: {fileID: 0}\n      m_TileFlags: 1\n      m_ColliderType: 1\n  - first: {x: 2, y: -5, z: 0}\n    second:\n      m_TileIndex: 85\n      m_TileSpriteIndex: 85\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 93\n      m_ObjectToInstantiate: {fileID: 0}\n      m_TileFlags: 1\n      m_ColliderType: 1\n  - first: {x: 3, y: -5, z: 0}\n    second:\n      m_TileIndex: 88\n      m_TileSpriteIndex: 88\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 93\n      m_ObjectToInstantiate: {fileID: 0}\n      m_TileFlags: 1\n      m_ColliderType: 1\n  - first: {x: 4, y: -5, z: 0}\n    second:\n      m_TileIndex: 86\n      m_TileSpriteIndex: 86\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 93\n      m_ObjectToInstantiate: {fileID: 0}\n      m_TileFlags: 1\n      m_ColliderType: 1\n  - first: {x: 2, y: -4, z: 0}\n    second:\n      m_TileIndex: 90\n      m_TileSpriteIndex: 90\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 93\n      m_ObjectToInstantiate: {fileID: 0}\n      m_TileFlags: 1\n      m_ColliderType: 1\n  - first: {x: 4, y: -4, z: 0}\n    second:\n      m_TileIndex: 89\n      m_TileSpriteIndex: 89\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 93\n      m_ObjectToInstantiate: {fileID: 0}\n      m_TileFlags: 1\n      m_ColliderType: 1\n  - first: {x: 2, y: -3, z: 0}\n    second:\n      m_TileIndex: 93\n      m_TileSpriteIndex: 93\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 93\n      m_ObjectToInstantiate: {fileID: 0}\n      m_TileFlags: 1\n      m_ColliderType: 1\n  - first: {x: 3, y: -3, z: 0}\n    second:\n      m_TileIndex: 92\n      m_TileSpriteIndex: 92\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 93\n      m_ObjectToInstantiate: {fileID: 0}\n      m_TileFlags: 1\n      m_ColliderType: 1\n  - first: {x: 4, y: -3, z: 0}\n    second:\n      m_TileIndex: 91\n      m_TileSpriteIndex: 91\n      m_TileMatrixIndex: 0\n      m_TileColorIndex: 93\n      m_ObjectToInstantiate: {fileID: 0}\n      m_TileFlags: 1\n      m_ColliderType: 1\n  m_AnimatedTiles: {}\n  m_TileAssetArray:\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 1\n    m_Data: {fileID: 11400000, guid: de1a7bd3b973f4b459dfd60f5ba8c149, type: 2}\n  - m_RefCount: 1\n    m_Data: {fileID: 11400000, guid: 9f26bff8983bce141ae2a7232cc3110c, type: 2}\n  - m_RefCount: 1\n    m_Data: {fileID: 11400000, guid: d60c19cedbdfaf540a5224f2703d9185, type: 2}\n  - m_RefCount: 1\n    m_Data: {fileID: 11400000, guid: 2e6a9bfbab8e0c347ac12179f2a0f7a5, type: 2}\n  - m_RefCount: 1\n    m_Data: {fileID: 11400000, guid: 6fddaf8e8903e8b4a99c9e08b7ef4740, type: 2}\n  - m_RefCount: 1\n    m_Data: {fileID: 11400000, guid: 4903021c6067ced489a594416c114bff, type: 2}\n  - m_RefCount: 1\n    m_Data: {fileID: 11400000, guid: f4a4199d6aefaa543b081c23a3ce0a6a, type: 2}\n  - m_RefCount: 1\n    m_Data: {fileID: 11400000, guid: 6ad0a965971cbbe42a8b6cc2792f0e59, type: 2}\n  - m_RefCount: 1\n    m_Data: {fileID: 11400000, guid: 02ee918df97067942877970e67eb3f76, type: 2}\n  m_TileSpriteArray:\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 0\n    m_Data: {fileID: 0}\n  - m_RefCount: 1\n    m_Data: {fileID: 8666830670597921376, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 1\n    m_Data: {fileID: -1707878253529702307, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 1\n    m_Data: {fileID: 5550582127777731385, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 1\n    m_Data: {fileID: -2936791710745090628, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 1\n    m_Data: {fileID: -7635356268976036439, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 1\n    m_Data: {fileID: 9048098576551171047, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 1\n    m_Data: {fileID: 4239696434956193796, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 1\n    m_Data: {fileID: -9114847578740223409, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  - m_RefCount: 1\n    m_Data: {fileID: -2113894134886356154, guid: c30df8d60c651bb4e91f5c99553a7117,\n      type: 3}\n  m_TileMatrixArray:\n  - m_RefCount: 9\n    m_Data:\n      e00: 1\n      e01: 0\n      e02: 0\n      e03: 0\n      e10: 0\n      e11: 1\n      e12: 0\n      e13: 0\n      e20: 0\n      e21: 0\n      e22: 1\n      e23: 0\n      e30: 0\n      e31: 0\n      e32: 0\n      e33: 1\n  m_TileColorArray:\n  - m_RefCount: 0\n    m_Data: {r: -1.0825261e+34, g: -1.0825261e+34, b: -1.0825261e+34, a: -1.0825261e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0828034e+34, g: -1.0828034e+34, b: -1.0828034e+34, a: -1.0828034e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.082845e+34, g: -1.082845e+34, b: -1.082845e+34, a: -1.082845e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0829282e+34, g: -1.0829282e+34, b: -1.0829282e+34, a: -1.0829282e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0823597e+34, g: -1.0823597e+34, b: -1.0823597e+34, a: -1.0823597e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0827618e+34, g: -1.0827618e+34, b: -1.0827618e+34, a: -1.0827618e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.082637e+34, g: -1.082637e+34, b: -1.082637e+34, a: -1.082637e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0828311e+34, g: -1.0828311e+34, b: -1.0828311e+34, a: -1.0828311e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0826509e+34, g: -1.0826509e+34, b: -1.0826509e+34, a: -1.0826509e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0829698e+34, g: -1.0829698e+34, b: -1.0829698e+34, a: -1.0829698e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0818744e+34, g: -1.0818744e+34, b: -1.0818744e+34, a: -1.0818744e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0819299e+34, g: -1.0819299e+34, b: -1.0819299e+34, a: -1.0819299e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0409214e+34, g: -1.0409214e+34, b: -1.0409214e+34, a: -1.0409214e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0818467e+34, g: -1.0818467e+34, b: -1.0818467e+34, a: -1.0818467e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0414344e+34, g: -1.0414344e+34, b: -1.0414344e+34, a: -1.0414344e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0824568e+34, g: -1.0824568e+34, b: -1.0824568e+34, a: -1.0824568e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0824845e+34, g: -1.0824845e+34, b: -1.0824845e+34, a: -1.0824845e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0824429e+34, g: -1.0824429e+34, b: -1.0824429e+34, a: -1.0824429e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0824706e+34, g: -1.0824706e+34, b: -1.0824706e+34, a: -1.0824706e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0824152e+34, g: -1.0824152e+34, b: -1.0824152e+34, a: -1.0824152e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0818328e+34, g: -1.0818328e+34, b: -1.0818328e+34, a: -1.0818328e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0408521e+34, g: -1.0408521e+34, b: -1.0408521e+34, a: -1.0408521e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.1031551e+34, g: -1.1031551e+34, b: -1.1031551e+34, a: -1.1031551e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0822488e+34, g: -1.0822488e+34, b: -1.0822488e+34, a: -1.0822488e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0825122e+34, g: -1.0825122e+34, b: -1.0825122e+34, a: -1.0825122e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.082942e+34, g: -1.082942e+34, b: -1.082942e+34, a: -1.082942e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0826647e+34, g: -1.0826647e+34, b: -1.0826647e+34, a: -1.0826647e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.082734e+34, g: -1.082734e+34, b: -1.082734e+34, a: -1.082734e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0826925e+34, g: -1.0826925e+34, b: -1.0826925e+34, a: -1.0826925e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0822904e+34, g: -1.0822904e+34, b: -1.0822904e+34, a: -1.0822904e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0821379e+34, g: -1.0821379e+34, b: -1.0821379e+34, a: -1.0821379e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.041781e+34, g: -1.041781e+34, b: -1.041781e+34, a: -1.041781e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0417671e+34, g: -1.0417671e+34, b: -1.0417671e+34, a: -1.0417671e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0414205e+34, g: -1.0414205e+34, b: -1.0414205e+34, a: -1.0414205e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0414067e+34, g: -1.0414067e+34, b: -1.0414067e+34, a: -1.0414067e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0829836e+34, g: -1.0829836e+34, b: -1.0829836e+34, a: -1.0829836e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.083053e+34, g: -1.083053e+34, b: -1.083053e+34, a: -1.083053e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0824983e+34, g: -1.0824983e+34, b: -1.0824983e+34, a: -1.0824983e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0828866e+34, g: -1.0828866e+34, b: -1.0828866e+34, a: -1.0828866e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0830668e+34, g: -1.0830668e+34, b: -1.0830668e+34, a: -1.0830668e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0416562e+34, g: -1.0416562e+34, b: -1.0416562e+34, a: -1.0416562e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0819992e+34, g: -1.0819992e+34, b: -1.0819992e+34, a: -1.0819992e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.1031967e+34, g: -1.1031967e+34, b: -1.1031967e+34, a: -1.1031967e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0817774e+34, g: -1.0817774e+34, b: -1.0817774e+34, a: -1.0817774e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0711232e+34, g: -1.0711232e+34, b: -1.0711232e+34, a: -1.0711232e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0827202e+34, g: -1.0827202e+34, b: -1.0827202e+34, a: -1.0827202e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0820963e+34, g: -1.0820963e+34, b: -1.0820963e+34, a: -1.0820963e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0827756e+34, g: -1.0827756e+34, b: -1.0827756e+34, a: -1.0827756e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0823874e+34, g: -1.0823874e+34, b: -1.0823874e+34, a: -1.0823874e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0819022e+34, g: -1.0819022e+34, b: -1.0819022e+34, a: -1.0819022e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0818606e+34, g: -1.0818606e+34, b: -1.0818606e+34, a: -1.0818606e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0825538e+34, g: -1.0825538e+34, b: -1.0825538e+34, a: -1.0825538e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0826231e+34, g: -1.0826231e+34, b: -1.0826231e+34, a: -1.0826231e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0828727e+34, g: -1.0828727e+34, b: -1.0828727e+34, a: -1.0828727e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0417533e+34, g: -1.0417533e+34, b: -1.0417533e+34, a: -1.0417533e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0419474e+34, g: -1.0419474e+34, b: -1.0419474e+34, a: -1.0419474e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0422524e+34, g: -1.0422524e+34, b: -1.0422524e+34, a: -1.0422524e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0421138e+34, g: -1.0421138e+34, b: -1.0421138e+34, a: -1.0421138e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0419058e+34, g: -1.0419058e+34, b: -1.0419058e+34, a: -1.0419058e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0407689e+34, g: -1.0407689e+34, b: -1.0407689e+34, a: -1.0407689e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0419751e+34, g: -1.0419751e+34, b: -1.0419751e+34, a: -1.0419751e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.1031828e+34, g: -1.1031828e+34, b: -1.1031828e+34, a: -1.1031828e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0821933e+34, g: -1.0821933e+34, b: -1.0821933e+34, a: -1.0821933e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.082027e+34, g: -1.082027e+34, b: -1.082027e+34, a: -1.082027e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0820408e+34, g: -1.0820408e+34, b: -1.0820408e+34, a: -1.0820408e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.041171e+34, g: -1.041171e+34, b: -1.041171e+34, a: -1.041171e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0411987e+34, g: -1.0411987e+34, b: -1.0411987e+34, a: -1.0411987e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0822072e+34, g: -1.0822072e+34, b: -1.0822072e+34, a: -1.0822072e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0821517e+34, g: -1.0821517e+34, b: -1.0821517e+34, a: -1.0821517e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0412957e+34, g: -1.0412957e+34, b: -1.0412957e+34, a: -1.0412957e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0415453e+34, g: -1.0415453e+34, b: -1.0415453e+34, a: -1.0415453e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.041573e+34, g: -1.041573e+34, b: -1.041573e+34, a: -1.041573e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0420029e+34, g: -1.0420029e+34, b: -1.0420029e+34, a: -1.0420029e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0413235e+34, g: -1.0413235e+34, b: -1.0413235e+34, a: -1.0413235e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0415176e+34, g: -1.0415176e+34, b: -1.0415176e+34, a: -1.0415176e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0414483e+34, g: -1.0414483e+34, b: -1.0414483e+34, a: -1.0414483e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0413512e+34, g: -1.0413512e+34, b: -1.0413512e+34, a: -1.0413512e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0413789e+34, g: -1.0413789e+34, b: -1.0413789e+34, a: -1.0413789e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.041684e+34, g: -1.041684e+34, b: -1.041684e+34, a: -1.041684e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0413096e+34, g: -1.0413096e+34, b: -1.0413096e+34, a: -1.0413096e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0415592e+34, g: -1.0415592e+34, b: -1.0415592e+34, a: -1.0415592e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0820685e+34, g: -1.0820685e+34, b: -1.0820685e+34, a: -1.0820685e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0413651e+34, g: -1.0413651e+34, b: -1.0413651e+34, a: -1.0413651e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0820547e+34, g: -1.0820547e+34, b: -1.0820547e+34, a: -1.0820547e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0422663e+34, g: -1.0422663e+34, b: -1.0422663e+34, a: -1.0422663e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0820824e+34, g: -1.0820824e+34, b: -1.0820824e+34, a: -1.0820824e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.082221e+34, g: -1.082221e+34, b: -1.082221e+34, a: -1.082221e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0825815e+34, g: -1.0825815e+34, b: -1.0825815e+34, a: -1.0825815e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0830391e+34, g: -1.0830391e+34, b: -1.0830391e+34, a: -1.0830391e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0822349e+34, g: -1.0822349e+34, b: -1.0822349e+34, a: -1.0822349e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0722601e+34, g: -1.0722601e+34, b: -1.0722601e+34, a: -1.0722601e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0474498e+34, g: -1.0474498e+34, b: -1.0474498e+34, a: -1.0474498e+34}\n  - m_RefCount: 0\n    m_Data: {r: -1.0122398e+34, g: -1.0122398e+34, b: -1.0122398e+34, a: -1.0122398e+34}\n  - m_RefCount: 9\n    m_Data: {r: 1, g: 1, b: 1, a: 1}\n  m_AnimationFrameRate: 1\n  m_Color: {r: 1, g: 1, b: 1, a: 1}\n  m_Origin: {x: 0, y: -9, z: 0}\n  m_Size: {x: 11, y: 10, z: 1}\n  m_TileAnchor: {x: 0.5, y: 0.5, z: 0}\n  m_TileOrientation: 0\n  m_TileOrientationMatrix:\n    e00: 1\n    e01: 0\n    e02: 0\n    e03: 0\n    e10: 0\n    e11: 1\n    e12: 0\n    e13: 0\n    e20: 0\n    e21: 0\n    e22: 1\n    e23: 0\n    e30: 0\n    e31: 0\n    e32: 0\n    e33: 1\n--- !u!483693784 &7353399709395597127\nTilemapRenderer:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 9019164986347984336}\n  m_Enabled: 0\n  m_CastShadows: 0\n  m_ReceiveShadows: 0\n  m_DynamicOccludee: 0\n  m_MotionVectors: 1\n  m_LightProbeUsage: 0\n  m_ReflectionProbeUsage: 0\n  m_RenderingLayerMask: 1\n  m_RendererPriority: 0\n  m_Materials:\n  - {fileID: 10754, guid: 0000000000000000f000000000000000, type: 0}\n  m_StaticBatchInfo:\n    firstSubMesh: 0\n    subMeshCount: 0\n  m_StaticBatchRoot: {fileID: 0}\n  m_ProbeAnchor: {fileID: 0}\n  m_LightProbeVolumeOverride: {fileID: 0}\n  m_ScaleInLightmap: 1\n  m_PreserveUVs: 0\n  m_IgnoreNormalsForChartDetection: 0\n  m_ImportantGI: 0\n  m_StitchLightmapSeams: 1\n  m_SelectedEditorRenderState: 0\n  m_MinimumChartSize: 4\n  m_AutoUVMaxDistance: 0.5\n  m_AutoUVMaxAngle: 89\n  m_LightmapParameters: {fileID: 0}\n  m_SortingLayerID: 0\n  m_SortingLayer: 0\n  m_SortingOrder: 0\n  m_ChunkSize: {x: 32, y: 32, z: 32}\n  m_ChunkCullingBounds: {x: 0, y: 0, z: 0}\n  m_MaxChunkCount: 16\n  m_MaxFrameAge: 16\n  m_SortOrder: 0\n  m_Mode: 0\n  m_DetectChunkCullingBounds: 0\n  m_MaskInteraction: 0\n--- !u!114 &-8087056181949013625\nMonoBehaviour:\n  m_ObjectHideFlags: 0\n  m_CorrespondingSourceObject: {fileID: 0}\n  m_PrefabInstance: {fileID: 0}\n  m_PrefabAsset: {fileID: 0}\n  m_GameObject: {fileID: 0}\n  m_Enabled: 1\n  m_EditorHideFlags: 0\n  m_Script: {fileID: 12395, guid: 0000000000000000e000000000000000, type: 0}\n  m_Name: Palette Settings\n  m_EditorClassIdentifier: \n  cellSizing: 100\n"
  },
  {
    "path": "Assets/Examples/Tiles/New Palette.prefab.meta",
    "content": "fileFormatVersion: 2\nguid: d86f8324453eed24182835f3b9e75e02\nPrefabImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples/Tiles.meta",
    "content": "fileFormatVersion: 2\nguid: 276b4cc0229778e45a0e57ead6fe4b02\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Examples.meta",
    "content": "fileFormatVersion: 2\nguid: bf815c669cc740b499dfa81392af61fb\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Generated/Typings/jsb.autogen.d.ts",
    "content": "declare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array, Object as Object1, Enum } from \"System\";\r\n    /** Script interface for ParticleSystem. Unity's powerful and versatile particle system implementation.\r\n     */\r\n    class ParticleSystem extends Component {\r\n        constructor()\r\n        SetParticles(particles: Array<any>, size: number, offset: number): void\r\n        SetParticles(particles: any, size: number, offset: number): void\r\n        SetParticles(particles: Array<any>, size: number): void\r\n        SetParticles(particles: any, size: number): void\r\n        SetParticles(particles: Array<any>): void\r\n        SetParticles(particles: any): void\r\n        GetParticles(particles: Array<any>, size: number, offset: number): number\r\n        GetParticles(particles: any, size: number, offset: number): number\r\n        GetParticles(particles: Array<any>, size: number): number\r\n        GetParticles(particles: any, size: number): number\r\n        GetParticles(particles: Array<any>): number\r\n        GetParticles(particles: any): number\r\n        SetCustomParticleData(customData: any, streamIndex: any): void\r\n        GetCustomParticleData(customData: any, streamIndex: any): number\r\n        GetPlaybackState(): any\r\n        SetPlaybackState(playbackState: any): void\r\n        GetTrails(): any\r\n        SetTrails(trailData: any): void\r\n        /** Fast-forwards the Particle System by simulating particles over the given period of time, then pauses it.\r\n         * @param t Time period in seconds to advance the ParticleSystem simulation by. If restart is true, the ParticleSystem will be reset to 0 time, and then advanced by this value. If restart is false, the ParticleSystem simulation will be advanced in time from its current state by this value.\r\n         * @param withChildren Fast-forward all child Particle Systems as well.\r\n         * @param restart Restart and start from the beginning.\r\n         * @param fixedTimeStep Only update the system at fixed intervals, based on the value in \"Fixed Time\" in the Time options.\r\n         */\r\n        Simulate(t: number, withChildren: boolean, restart: boolean, fixedTimeStep: boolean): void\r\n        /** Fast-forwards the Particle System by simulating particles over the given period of time, then pauses it.\r\n         * @param t Time period in seconds to advance the ParticleSystem simulation by. If restart is true, the ParticleSystem will be reset to 0 time, and then advanced by this value. If restart is false, the ParticleSystem simulation will be advanced in time from its current state by this value.\r\n         * @param withChildren Fast-forward all child Particle Systems as well.\r\n         * @param restart Restart and start from the beginning.\r\n         * @param fixedTimeStep Only update the system at fixed intervals, based on the value in \"Fixed Time\" in the Time options.\r\n         */\r\n        Simulate(t: number, withChildren: boolean, restart: boolean): void\r\n        /** Fast-forwards the Particle System by simulating particles over the given period of time, then pauses it.\r\n         * @param t Time period in seconds to advance the ParticleSystem simulation by. If restart is true, the ParticleSystem will be reset to 0 time, and then advanced by this value. If restart is false, the ParticleSystem simulation will be advanced in time from its current state by this value.\r\n         * @param withChildren Fast-forward all child Particle Systems as well.\r\n         * @param restart Restart and start from the beginning.\r\n         * @param fixedTimeStep Only update the system at fixed intervals, based on the value in \"Fixed Time\" in the Time options.\r\n         */\r\n        Simulate(t: number, withChildren: boolean): void\r\n        /** Fast-forwards the Particle System by simulating particles over the given period of time, then pauses it.\r\n         * @param t Time period in seconds to advance the ParticleSystem simulation by. If restart is true, the ParticleSystem will be reset to 0 time, and then advanced by this value. If restart is false, the ParticleSystem simulation will be advanced in time from its current state by this value.\r\n         * @param withChildren Fast-forward all child Particle Systems as well.\r\n         * @param restart Restart and start from the beginning.\r\n         * @param fixedTimeStep Only update the system at fixed intervals, based on the value in \"Fixed Time\" in the Time options.\r\n         */\r\n        Simulate(t: number): void\r\n        /** Starts the Particle System.\r\n         * @param withChildren Play all child Particle Systems as well.\r\n         */\r\n        Play(withChildren: boolean): void\r\n        Play(): void\r\n        /** Pauses the system so no new particles are emitted and the existing particles are not updated.\r\n         * @param withChildren Pause all child Particle Systems as well.\r\n         */\r\n        Pause(withChildren: boolean): void\r\n        Pause(): void\r\n        /** Stops playing the Particle System using the supplied stop behaviour.\r\n         * @param withChildren Stop all child Particle Systems as well.\r\n         * @param stopBehavior Stop emitting or stop emitting and clear the system.\r\n         */\r\n        Stop(withChildren: boolean, stopBehavior: any): void\r\n        /** Stops playing the Particle System using the supplied stop behaviour.\r\n         * @param withChildren Stop all child Particle Systems as well.\r\n         * @param stopBehavior Stop emitting or stop emitting and clear the system.\r\n         */\r\n        Stop(withChildren: boolean): void\r\n        Stop(): void\r\n        /** Remove all particles in the Particle System.\r\n         * @param withChildren Clear all child Particle Systems as well.\r\n         */\r\n        Clear(withChildren: boolean): void\r\n        Clear(): void\r\n        /** Does the Particle System contain any live particles, or will it produce more?\r\n         * @param withChildren Check all child Particle Systems as well.\r\n         * @returns True if the Particle System contains live particles or is still creating new particles. False if the Particle System has stopped emitting particles and all particles are dead. \r\n         */\r\n        IsAlive(withChildren: boolean): boolean\r\n        IsAlive(): boolean\r\n        Emit(emitParams: any, count: number): void\r\n        /** Emit count particles immediately.\r\n         * @param count Number of particles to emit.\r\n         */\r\n        Emit(count: number): void\r\n        TriggerSubEmitter(subEmitterIndex: number, particle: jsb.Ref<any>): void\r\n        TriggerSubEmitter(subEmitterIndex: number, particles: any): void\r\n        /** Triggers the specified sub emitter on all particles of the Particle System.\r\n         * @param subEmitterIndex Index of the sub emitter to trigger.\r\n         */\r\n        TriggerSubEmitter(subEmitterIndex: number): void\r\n        AllocateAxisOfRotationAttribute(): void\r\n        AllocateMeshIndexAttribute(): void\r\n        /** Ensures that the ParticleSystemJobs.ParticleSystemJobData.customData1|customData1 and ParticleSystemJobs.ParticleSystemJobData.customData1|customData2 particle attribute arrays are allocated.\r\n         * @param stream The custom data stream to allocate.\r\n         */\r\n        AllocateCustomDataAttribute(stream: any): void\r\n        /** Safe array size for use with ParticleSystem.GetCollisionEvents.\r\n         */\r\n        GetSafeCollisionEventSize(): number\r\n        GetCollisionEvents(go: GameObject, collisionEvents: any): number\r\n        /** Safe array size for use with ParticleSystem.GetTriggerParticles.\r\n         * @param ps Particle system.\r\n         * @param type Type of trigger to return size for.\r\n         * @returns Number of particles with this trigger event type. \r\n         */\r\n        GetSafeTriggerParticlesSize(type: any): number\r\n        GetTriggerParticles(type: any, particles: any, colliderData: jsb.Out<any>): number\r\n        GetTriggerParticles(type: any, particles: any): number\r\n        SetTriggerParticles(type: any, particles: any, offset: number, count: number): void\r\n        SetTriggerParticles(type: any, particles: any): void\r\n        static ResetPreMappedBufferMemory(): void\r\n        /** Limits the amount of graphics memory Unity reserves for efficient rendering of Particle Systems.\r\n         * @param vertexBuffersCount The maximum number of cached vertex buffers.\r\n         * @param indexBuffersCount The maximum number of cached index buffers.\r\n         */\r\n        static SetMaximumPreMappedBufferCounts(vertexBuffersCount: number, indexBuffersCount: number): void\r\n        /** Determines whether the Particle System is playing.\r\n         */\r\n        readonly isPlaying: boolean\r\n        /** Determines whether the Particle System is emitting particles. A Particle System may stop emitting when its emission module has finished, it has been paused or if the system has been stopped using ParticleSystem.Stop|Stop with the ParticleSystemStopBehavior.StopEmitting|StopEmitting flag. Resume emitting by calling ParticleSystem.Play|Play.\r\n         */\r\n        readonly isEmitting: boolean\r\n        /** Determines whether the Particle System is in the stopped state.\r\n         */\r\n        readonly isStopped: boolean\r\n        /** Determines whether the Particle System is paused.\r\n         */\r\n        readonly isPaused: boolean\r\n        /** The current number of particles (Read Only).\r\n         */\r\n        readonly particleCount: number\r\n        /** Playback position in seconds.\r\n         */\r\n        time: number\r\n        /** Override the random seed used for the Particle System emission.\r\n         */\r\n        randomSeed: number\r\n        /** Controls whether the Particle System uses an automatically-generated random number to seed the random number generator.\r\n         */\r\n        useAutoRandomSeed: boolean\r\n        /** Does this system support Procedural Simulation?\r\n         */\r\n        readonly proceduralSimulationSupported: boolean\r\n        /** Access the main Particle System settings.\r\n         */\r\n        readonly main: ParticleSystem.MainModule\r\n        /** Script interface for the EmissionModule of a Particle System.\r\n         */\r\n        readonly emission: any\r\n        /** Script interface for the ShapeModule of a Particle System. \r\n         */\r\n        readonly shape: any\r\n        /** Script interface for the VelocityOverLifetimeModule of a Particle System.\r\n         */\r\n        readonly velocityOverLifetime: any\r\n        /** Script interface for the LimitVelocityOverLifetimeModule of a Particle System. .\r\n         */\r\n        readonly limitVelocityOverLifetime: any\r\n        /** Script interface for the InheritVelocityModule of a Particle System.\r\n         */\r\n        readonly inheritVelocity: any\r\n        /** Script interface for the Particle System Lifetime By Emitter Speed module.\r\n         */\r\n        readonly lifetimeByEmitterSpeed: any\r\n        /** Script interface for the ForceOverLifetimeModule of a Particle System.\r\n         */\r\n        readonly forceOverLifetime: any\r\n        /** Script interface for the ColorOverLifetimeModule of a Particle System.\r\n         */\r\n        readonly colorOverLifetime: any\r\n        /** Script interface for the ColorByLifetimeModule of a Particle System.\r\n         */\r\n        readonly colorBySpeed: any\r\n        /** Script interface for the SizeOverLifetimeModule of a Particle System. \r\n         */\r\n        readonly sizeOverLifetime: any\r\n        /** Script interface for the SizeBySpeedModule of a Particle System.\r\n         */\r\n        readonly sizeBySpeed: any\r\n        /** Script interface for the RotationOverLifetimeModule of a Particle System.\r\n         */\r\n        readonly rotationOverLifetime: any\r\n        /** Script interface for the RotationBySpeedModule of a Particle System.\r\n         */\r\n        readonly rotationBySpeed: any\r\n        /** Script interface for the ExternalForcesModule of a Particle System.\r\n         */\r\n        readonly externalForces: any\r\n        /** Script interface for the NoiseModule of a Particle System.\r\n         */\r\n        readonly noise: any\r\n        /** Script interface for the CollisionModule of a Particle System.\r\n         */\r\n        readonly collision: any\r\n        /** Script interface for the TriggerModule of a Particle System.\r\n         */\r\n        readonly trigger: any\r\n        /** Script interface for the SubEmittersModule of a Particle System.\r\n         */\r\n        readonly subEmitters: any\r\n        /** Script interface for the TextureSheetAnimationModule of a Particle System.\r\n         */\r\n        readonly textureSheetAnimation: any\r\n        /** Script interface for the LightsModule of a Particle System.\r\n         */\r\n        readonly lights: any\r\n        /** Script interface for the TrailsModule of a Particle System.\r\n         */\r\n        readonly trails: any\r\n        /** Script interface for the CustomDataModule of a Particle System.\r\n         */\r\n        readonly customData: any\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum, Array, Object as Object1 } from \"System\";\r\n    /** Use this class to render particles on to the screen.\r\n     */\r\n    class ParticleSystemRenderer extends Renderer {\r\n        constructor()\r\n        /** Get the array of Meshes to be used as particles.\r\n         * @param meshes This array is populated with the list of Meshes being used for particle rendering.\r\n         * @returns The number of Meshes actually written to the destination array. \r\n         */\r\n        GetMeshes(meshes: Array<any>): number\r\n        /** Set an array of Meshes to use as particles when the ParticleSystemRenderer.renderMode is set to ParticleSystemRenderMode.Mesh.\r\n         * @param meshes Array of Meshes to use.\r\n         * @param size Number of elements from the Mesh array to apply.\r\n         */\r\n        SetMeshes(meshes: Array<any>, size: number): void\r\n        /** Set an array of Meshes to use as particles when the ParticleSystemRenderer.renderMode is set to ParticleSystemRenderMode.Mesh.\r\n         * @param meshes Array of Meshes to use.\r\n         * @param size Number of elements from the Mesh array to apply.\r\n         */\r\n        SetMeshes(meshes: Array<any>): void\r\n        /** Creates a snapshot of ParticleSystemRenderer and stores it in mesh.\r\n         * @param mesh A static Mesh to receive the snapshot of the particles.\r\n         * @param camera The Camera used to determine which way camera-space particles face.\r\n         * @param useTransform Specifies whether to include the rotation and scale of the Transform in the baked Mesh.\r\n         */\r\n        BakeMesh(mesh: any, camera: Camera, useTransform: boolean): void\r\n        /** Creates a snapshot of ParticleSystemRenderer and stores it in mesh.\r\n         * @param mesh A static Mesh to receive the snapshot of the particles.\r\n         * @param camera The Camera used to determine which way camera-space particles face.\r\n         * @param useTransform Specifies whether to include the rotation and scale of the Transform in the baked Mesh.\r\n         */\r\n        BakeMesh(mesh: any, useTransform: boolean): void\r\n        /** Creates a snapshot of ParticleSystem Trails and stores them in mesh.\r\n         * @param mesh A static Mesh to receive the snapshot of the particle trails.\r\n         * @param camera The Camera used to determine which way camera-space trails face.\r\n         * @param useTransform Specifies whether to include the rotation and scale of the Transform in the baked Mesh.\r\n         */\r\n        BakeTrailsMesh(mesh: any, camera: Camera, useTransform: boolean): void\r\n        /** Creates a snapshot of ParticleSystem Trails and stores them in mesh.\r\n         * @param mesh A static Mesh to receive the snapshot of the particle trails.\r\n         * @param camera The Camera used to determine which way camera-space trails face.\r\n         * @param useTransform Specifies whether to include the rotation and scale of the Transform in the baked Mesh.\r\n         */\r\n        BakeTrailsMesh(mesh: any, useTransform: boolean): void\r\n        SetActiveVertexStreams(streams: any): void\r\n        GetActiveVertexStreams(streams: any): void\r\n        /** Control the direction that particles face.\r\n         */\r\n        alignment: any\r\n        /** Specifies how the system draws particles.\r\n         */\r\n        renderMode: any\r\n        /** Specifies how to sort particles within a system.\r\n         */\r\n        sortMode: any\r\n        /** How much are the particles stretched in their direction of motion, defined as the length of the particle compared to its width.\r\n         */\r\n        lengthScale: number\r\n        /** Specifies how much particles stretch depending on their velocity.\r\n         */\r\n        velocityScale: number\r\n        /** How much do the particles stretch depending on the Camera's speed.\r\n         */\r\n        cameraVelocityScale: number\r\n        /** Specifies how much a billboard particle orients its normals towards the Camera.\r\n         */\r\n        normalDirection: number\r\n        /** Apply a shadow bias to prevent self-shadowing artifacts. The specified value is the proportion of the particle size.\r\n         */\r\n        shadowBias: number\r\n        /** Biases Particle System sorting amongst other transparencies.\r\n         */\r\n        sortingFudge: number\r\n        /** Clamp the minimum particle size.\r\n         */\r\n        minParticleSize: number\r\n        /** Clamp the maximum particle size.\r\n         */\r\n        maxParticleSize: number\r\n        /** Modify the pivot point used for rotating particles.\r\n         */\r\n        pivot: Vector3\r\n        /** Flip a percentage of the particles, along each axis.\r\n         */\r\n        flip: Vector3\r\n        /** Specifies how the Particle System Renderer interacts with SpriteMask.\r\n         */\r\n        maskInteraction: any\r\n        /** Set the Material that the TrailModule uses to attach trails to particles.\r\n         */\r\n        trailMaterial: Material\r\n        /** Enables GPU Instancing on platforms that support it.\r\n         */\r\n        enableGPUInstancing: boolean\r\n        /** Allow billboard particles to roll around their z-axis.\r\n         */\r\n        allowRoll: boolean\r\n        /** Enables freeform stretching behavior.\r\n         */\r\n        freeformStretching: boolean\r\n        /** Rotate the particles based on the direction they are stretched in. This is added on top of other particle rotation.\r\n         */\r\n        rotateWithStretchDirection: boolean\r\n        /** The Mesh that the particle uses instead of a billboarded Texture.\r\n         */\r\n        mesh: any\r\n        /** The number of Meshes the system uses for particle rendering.\r\n         */\r\n        readonly meshCount: number\r\n        /** The number of currently active custom vertex streams.\r\n         */\r\n        readonly activeVertexStreamsCount: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { ValueType, Enum } from \"System\";\r\n    namespace ParticleSystem {\r\n        class MainModule extends ValueType {\r\n            constructor()\r\n            duration: number\r\n            loop: boolean\r\n            prewarm: boolean\r\n            startDelay: any\r\n            startDelayMultiplier: number\r\n            startLifetime: any\r\n            startLifetimeMultiplier: number\r\n            startSpeed: any\r\n            startSpeedMultiplier: number\r\n            startSize3D: boolean\r\n            startSize: any\r\n            startSizeMultiplier: number\r\n            startSizeX: any\r\n            startSizeXMultiplier: number\r\n            startSizeY: any\r\n            startSizeYMultiplier: number\r\n            startSizeZ: any\r\n            startSizeZMultiplier: number\r\n            startRotation3D: boolean\r\n            startRotation: any\r\n            startRotationMultiplier: number\r\n            startRotationX: any\r\n            startRotationXMultiplier: number\r\n            startRotationY: any\r\n            startRotationYMultiplier: number\r\n            startRotationZ: any\r\n            startRotationZMultiplier: number\r\n            flipRotation: number\r\n            startColor: any\r\n            gravityModifier: any\r\n            gravityModifierMultiplier: number\r\n            simulationSpace: ParticleSystemSimulationSpace\r\n            customSimulationSpace: Transform\r\n            simulationSpeed: number\r\n            useUnscaledTime: boolean\r\n            scalingMode: any\r\n            playOnAwake: boolean\r\n            maxParticles: number\r\n            emitterVelocityMode: any\r\n            stopAction: any\r\n            ringBufferMode: any\r\n            ringBufferLoopRange: Vector2\r\n            cullingMode: any\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Enum } from \"System\";\r\n    /** The space to simulate particles in.\r\n     */\r\n    enum ParticleSystemSimulationSpace {\r\n        /** Simulate particles in local space.\r\n         */\r\n        Local = 0,\r\n        /** Simulate particles in world space.\r\n         */\r\n        World = 1,\r\n        /** Simulate particles relative to a custom transform component, defined by ParticleSystem.MainModule.customSimulationSpace.\r\n         */\r\n        Custom = 2,\r\n    }\r\n}\r\ndeclare module \"System.Net\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    class IPHostEntry extends Object {\r\n        constructor()\r\n        HostName: string\r\n        Aliases: Array<string>\r\n        AddressList: Array<any>\r\n    }\r\n}\r\ndeclare module \"System\" {\r\n    import * as jsb from \"jsb\";\r\n    class DateTime extends ValueType {\r\n        constructor(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number, calendar: any, kind: any)\r\n        constructor(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number, kind: any)\r\n        constructor(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number, calendar: any)\r\n        constructor(year: number, month: number, day: number, hour: number, minute: number, second: number, kind: any)\r\n        constructor(year: number, month: number, day: number, hour: number, minute: number, second: number, calendar: any)\r\n        constructor(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number)\r\n        constructor(year: number, month: number, day: number, hour: number, minute: number, second: number)\r\n        constructor(year: number, month: number, day: number, calendar: any)\r\n        constructor(year: number, month: number, day: number)\r\n        constructor(ticks: number, kind: any)\r\n        constructor(ticks: number)\r\n        Add(value: any): DateTime\r\n        AddDays(value: number): DateTime\r\n        AddHours(value: number): DateTime\r\n        AddMilliseconds(value: number): DateTime\r\n        AddMinutes(value: number): DateTime\r\n        AddMonths(months: number): DateTime\r\n        AddSeconds(value: number): DateTime\r\n        AddTicks(value: number): DateTime\r\n        AddYears(value: number): DateTime\r\n        CompareTo(value: Object): number\r\n        CompareTo(value: DateTime): number\r\n        Equals(value: Object): boolean\r\n        Equals(value: DateTime): boolean\r\n        IsDaylightSavingTime(): boolean\r\n        ToBinary(): number\r\n        GetHashCode(): number\r\n        Subtract(value: DateTime): any\r\n        Subtract(value: any): DateTime\r\n        ToOADate(): number\r\n        ToFileTime(): number\r\n        ToFileTimeUtc(): number\r\n        ToLocalTime(): DateTime\r\n        ToLongDateString(): string\r\n        ToLongTimeString(): string\r\n        ToShortDateString(): string\r\n        ToShortTimeString(): string\r\n        toString(format: string, provider: any): string\r\n        toString(format: string): string\r\n        toString(provider: any): string\r\n        toString(): string\r\n        ToUniversalTime(): DateTime\r\n        GetDateTimeFormats(format: string, provider: any): Array<string>\r\n        GetDateTimeFormats(provider: any): Array<string>\r\n        GetDateTimeFormats(format: string): Array<string>\r\n        GetDateTimeFormats(): Array<string>\r\n        GetTypeCode(): any\r\n        static Compare(t1: DateTime, t2: DateTime): number\r\n        static DaysInMonth(year: number, month: number): number\r\n        static Equals(t1: DateTime, t2: DateTime): boolean\r\n        static FromBinary(dateData: number): DateTime\r\n        static FromFileTime(fileTime: number): DateTime\r\n        static FromFileTimeUtc(fileTime: number): DateTime\r\n        static FromOADate(d: number): DateTime\r\n        static SpecifyKind(value: DateTime, kind: any): DateTime\r\n        static IsLeapYear(year: number): boolean\r\n        static Parse(s: string, provider: any, styles: any): DateTime\r\n        static Parse(s: string, provider: any): DateTime\r\n        static Parse(s: string): DateTime\r\n        static ParseExact(s: string, format: string, provider: any, style: any): DateTime\r\n        static ParseExact(s: string, formats: Array<string>, provider: any, style: any): DateTime\r\n        static ParseExact(s: string, format: string, provider: any): DateTime\r\n        static TryParse(s: string, provider: any, styles: any, result: jsb.Out<DateTime>): boolean\r\n        static TryParse(s: string, result: jsb.Out<DateTime>): boolean\r\n        static TryParseExact(s: string, format: string, provider: any, style: any, result: jsb.Out<DateTime>): boolean\r\n        static TryParseExact(s: string, formats: Array<string>, provider: any, style: any, result: jsb.Out<DateTime>): boolean\r\n        static op_Addition(d: DateTime, t: any): DateTime\r\n        static op_Subtraction(d: DateTime, t: any): DateTime\r\n        static op_Subtraction(d1: DateTime, d2: DateTime): any\r\n        static op_Equality(d1: DateTime, d2: DateTime): boolean\r\n        static op_Inequality(d1: DateTime, d2: DateTime): boolean\r\n        static op_LessThan(t1: DateTime, t2: DateTime): boolean\r\n        static op_LessThanOrEqual(t1: DateTime, t2: DateTime): boolean\r\n        static op_GreaterThan(t1: DateTime, t2: DateTime): boolean\r\n        static op_GreaterThanOrEqual(t1: DateTime, t2: DateTime): boolean\r\n        readonly Date: DateTime\r\n        readonly Day: number\r\n        readonly DayOfWeek: any\r\n        readonly DayOfYear: number\r\n        readonly Hour: number\r\n        readonly Kind: any\r\n        readonly Millisecond: number\r\n        readonly Minute: number\r\n        readonly Month: number\r\n        static readonly Now: DateTime\r\n        static readonly UtcNow: DateTime\r\n        readonly Second: number\r\n        readonly Ticks: number\r\n        readonly TimeOfDay: any\r\n        static readonly Today: DateTime\r\n        readonly Year: number\r\n        static readonly MinValue: DateTime\r\n        static readonly MaxValue: DateTime\r\n    }\r\n}\r\ndeclare module \"System.IO\" {\r\n    import { Object, Enum } from \"System\";\r\n    class FileInfo extends Object {\r\n        constructor(fileName: string)\r\n        OpenText(): any\r\n        CreateText(): any\r\n        AppendText(): any\r\n        CopyTo(destFileName: string, overwrite: boolean): FileInfo\r\n        CopyTo(destFileName: string): FileInfo\r\n        Create(): any\r\n        Delete(): void\r\n        Decrypt(): void\r\n        Encrypt(): void\r\n        Open(mode: any, access: any, share: any): any\r\n        Open(mode: any, access: any): any\r\n        Open(mode: any): any\r\n        OpenRead(): any\r\n        OpenWrite(): any\r\n        MoveTo(destFileName: string): void\r\n        Replace(destinationFileName: string, destinationBackupFileName: string, ignoreMetadataErrors: boolean): FileInfo\r\n        Replace(destinationFileName: string, destinationBackupFileName: string): FileInfo\r\n        toString(): string\r\n        readonly Name: string\r\n        readonly Length: number\r\n        readonly DirectoryName: string\r\n        readonly Directory: any\r\n        IsReadOnly: boolean\r\n        readonly Exists: boolean\r\n    }\r\n}\r\ndeclare module \"System.IO\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Enum, DateTime, Array } from \"System\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    abstract class File extends Object {\r\n        static AppendAllText(path: string, contents: string, encoding: any): void\r\n        static AppendAllText(path: string, contents: string): void\r\n        static AppendText(path: string): any\r\n        static Copy(sourceFileName: string, destFileName: string, overwrite: boolean): void\r\n        static Copy(sourceFileName: string, destFileName: string): void\r\n        static Create(path: string, bufferSize: number, options: any): any\r\n        static Create(path: string, bufferSize: number): any\r\n        static Create(path: string): any\r\n        static CreateText(path: string): any\r\n        static Delete(path: string): void\r\n        static Exists(path: string): boolean\r\n        static GetAttributes(path: string): any\r\n        static GetCreationTime(path: string): DateTime\r\n        static GetCreationTimeUtc(path: string): DateTime\r\n        static GetLastAccessTime(path: string): DateTime\r\n        static GetLastAccessTimeUtc(path: string): DateTime\r\n        static GetLastWriteTime(path: string): DateTime\r\n        static GetLastWriteTimeUtc(path: string): DateTime\r\n        static Move(sourceFileName: string, destFileName: string): void\r\n        static Open(path: string, mode: any, access: any): any\r\n        static Open(path: string, mode: any): any\r\n        static OpenRead(path: string): any\r\n        static OpenText(path: string): any\r\n        static OpenWrite(path: string): any\r\n        static Replace(sourceFileName: string, destinationFileName: string, destinationBackupFileName: string): void\r\n        static SetAttributes(path: string, fileAttributes: any): void\r\n        static SetCreationTime(path: string, creationTime: DateTime): void\r\n        static SetCreationTimeUtc(path: string, creationTimeUtc: DateTime): void\r\n        static SetLastAccessTime(path: string, lastAccessTime: DateTime): void\r\n        static SetLastAccessTimeUtc(path: string, lastAccessTimeUtc: DateTime): void\r\n        static SetLastWriteTime(path: string, lastWriteTime: DateTime): void\r\n        static SetLastWriteTimeUtc(path: string, lastWriteTimeUtc: DateTime): void\r\n        static ReadAllBytes(path: string): Array<jsb.byte>\r\n        static ReadAllLines(path: string, encoding: any): Array<string>\r\n        static ReadAllLines(path: string): Array<string>\r\n        static ReadAllText(path: string, encoding: any): string\r\n        static ReadAllText(path: string): string\r\n        static WriteAllBytes(path: string, bytes: Array<jsb.byte>): void\r\n        static WriteAllLines(path: string, contents: Array<string>, encoding: any): void\r\n        static WriteAllLines(path: string, contents: IEnumerable<string>, encoding: any): void\r\n        static WriteAllLines(path: string, contents: Array<string>): void\r\n        static WriteAllLines(path: string, contents: IEnumerable<string>): void\r\n        static WriteAllText(path: string, contents: string, encoding: any): void\r\n        static WriteAllText(path: string, contents: string): void\r\n        static Encrypt(path: string): void\r\n        static Decrypt(path: string): void\r\n        static ReadLines(path: string, encoding: any): IEnumerable<string>\r\n        static ReadLines(path: string): IEnumerable<string>\r\n        static AppendAllLines(path: string, contents: IEnumerable<string>, encoding: any): void\r\n        static AppendAllLines(path: string, contents: IEnumerable<string>): void\r\n    }\r\n}\r\ndeclare module \"global\" {\r\n    import { Object } from \"System\";\r\n    class TWrapper_Int32 extends Object implements TWrapper<number> {\r\n        constructor(obj: number)\r\n        GetValue(): number\r\n        SetValue(obj: number): void\r\n        static GetIntWrapper(): TWrapper<number>\r\n    }\r\n}\r\ndeclare module \"global\" {\r\n    import { Object } from \"System\";\r\n    class TWrapper<T> extends Object {\r\n    }\r\n}\r\ndeclare module \"global\" {\r\n    import { Object } from \"System\";\r\n    import { Vector3 } from \"UnityEngine\";\r\n    class TWrapper_Vector3 extends Object implements TWrapper<Vector3> {\r\n        constructor(obj: Vector3)\r\n        GetValue(): Vector3\r\n        SetValue(obj: Vector3): void\r\n        static GetIntWrapper(): TWrapper<number>\r\n    }\r\n}\r\ndeclare module \"Example\" {\r\n    import { Object } from \"System\";\r\n    class DisposableObject extends Object {\r\n        constructor()\r\n        Dispose(): void\r\n        static CreateDisposableObject(): DisposableObject\r\n    }\r\n}\r\ndeclare module \"Example\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    @jsb.RequiredDefines(\"CUSTOM_DEF_FOO\", \"UNITY_EDITOR\")\r\n    class FOO extends Object {\r\n        constructor()\r\n        static Exclusive(i32: number): void\r\n        propValue: string\r\n        static value: string\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array } from \"System\";\r\n    /** Specifies Layers to use in a Physics.Raycast.\r\n     */\r\n    class LayerMask extends ValueType {\r\n        constructor()\r\n        static op_Implicit(mask: LayerMask): number\r\n        static op_Implicit(intVal: number): LayerMask\r\n        /** Given a layer number, returns the name of the layer as defined in either a Builtin or a User Layer in the.\r\n         */\r\n        static LayerToName(layer: number): string\r\n        /** Given a layer name, returns the layer index as defined by either a Builtin or a User Layer in the.\r\n         */\r\n        static NameToLayer(layerName: string): number\r\n        /** Given a set of layer names as defined by either a Builtin or a User Layer in the, returns the equivalent layer mask for all of them.\r\n         * @param layerNames List of layer names to convert to a layer mask.\r\n         * @returns The layer mask created from the layerNames. \r\n         */\r\n        static GetMask(...layerNames: string[]): number\r\n        /** Converts a layer mask value to an integer value.\r\n         */\r\n        value: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array, Object as Object1 } from \"System\";\r\n    /** Representation of RGBA colors.\r\n     */\r\n    class Color extends ValueType {\r\n        constructor(r: number, g: number, b: number, a: number)\r\n        constructor(r: number, g: number, b: number)\r\n        $GetValue(index: number): number\r\n        $SetValue(index: number, value: number): void\r\n        /** Returns a formatted string of this color.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string, formatProvider: any): string\r\n        /** Returns a formatted string of this color.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string): string\r\n        toString(): string\r\n        GetHashCode(): number\r\n        Equals(other: Object1): boolean\r\n        Equals(other: Color): boolean\r\n        Compare(b: Color): boolean\r\n        CompareRGB(b: Color): boolean\r\n        MinAlpha(c2: Color): Color\r\n        static op_Addition(a: Color, b: Color): Color\r\n        static op_Subtraction(a: Color, b: Color): Color\r\n        static op_Multiply(a: Color, b: Color): Color\r\n        static op_Multiply(a: Color, b: number): Color\r\n        static op_Multiply(b: number, a: Color): Color\r\n        static op_Division(a: Color, b: number): Color\r\n        static op_Equality(lhs: Color, rhs: Color): boolean\r\n        static op_Inequality(lhs: Color, rhs: Color): boolean\r\n        /** Linearly interpolates between colors a and b by t.\r\n         * @param a Color a.\r\n         * @param b Color b.\r\n         * @param t Float for combining a and b.\r\n         */\r\n        static Lerp(a: Color, b: Color, t: number): Color\r\n        /** Linearly interpolates between colors a and b by t.\r\n         */\r\n        static LerpUnclamped(a: Color, b: Color, t: number): Color\r\n        static op_Implicit(c: Color): Vector4\r\n        static op_Implicit(v: Vector4): Color\r\n        /** Calculates the hue, saturation and value of an RGB input color.\r\n         * @param rgbColor An input color.\r\n         * @param H Output variable for hue.\r\n         * @param S Output variable for saturation.\r\n         * @param V Output variable for value.\r\n         */\r\n        static RGBToHSV(rgbColor: Color, H: jsb.Out<number>, S: jsb.Out<number>, V: jsb.Out<number>): void\r\n        /** Creates an RGB colour from HSV input.\r\n         * @param H Hue [0..1].\r\n         * @param S Saturation [0..1].\r\n         * @param V Brightness value [0..1].\r\n         * @param hdr Output HDR colours. If true, the returned colour will not be clamped to [0..1].\r\n         * @returns An opaque colour with HSV matching the input. \r\n         */\r\n        static HSVToRGB(H: number, S: number, V: number, hdr: boolean): Color\r\n        /** Creates an RGB colour from HSV input.\r\n         * @param H Hue [0..1].\r\n         * @param S Saturation [0..1].\r\n         * @param V Brightness value [0..1].\r\n         * @param hdr Output HDR colours. If true, the returned colour will not be clamped to [0..1].\r\n         * @returns An opaque colour with HSV matching the input. \r\n         */\r\n        static HSVToRGB(H: number, S: number, V: number): Color\r\n        // js_op_overloading: static +(a: Color, b: Color): Color\r\n        // js_op_overloading: static -(a: Color, b: Color): Color\r\n        // js_op_overloading: static *(a: Color, b: Color): Color\r\n        // js_op_overloading: static *(a: Color, b: number): Color\r\n        // js_op_overloading: static *(b: number, a: Color): Color\r\n        // js_op_overloading: static /(a: Color, b: number): Color\r\n        // js_op_overloading: static ==(lhs: Color, rhs: Color): boolean\r\n        /** Solid red. RGBA is (1, 0, 0, 1).\r\n         */\r\n        static readonly red: Color\r\n        /** Solid green. RGBA is (0, 1, 0, 1).\r\n         */\r\n        static readonly green: Color\r\n        /** Solid blue. RGBA is (0, 0, 1, 1).\r\n         */\r\n        static readonly blue: Color\r\n        /** Solid white. RGBA is (1, 1, 1, 1).\r\n         */\r\n        static readonly white: Color\r\n        /** Solid black. RGBA is (0, 0, 0, 1).\r\n         */\r\n        static readonly black: Color\r\n        /** Yellow. RGBA is (1, 0.92, 0.016, 1), but the color is nice to look at!\r\n         */\r\n        static readonly yellow: Color\r\n        /** Cyan. RGBA is (0, 1, 1, 1).\r\n         */\r\n        static readonly cyan: Color\r\n        /** Magenta. RGBA is (1, 0, 1, 1).\r\n         */\r\n        static readonly magenta: Color\r\n        /** Gray. RGBA is (0.5, 0.5, 0.5, 1).\r\n         */\r\n        static readonly gray: Color\r\n        /** English spelling for gray. RGBA is the same (0.5, 0.5, 0.5, 1).\r\n         */\r\n        static readonly grey: Color\r\n        /** Completely transparent. RGBA is (0, 0, 0, 0).\r\n         */\r\n        static readonly clear: Color\r\n        /** The grayscale value of the color. (Read Only)\r\n         */\r\n        readonly grayscale: number\r\n        /** A linear value of an sRGB color.\r\n         */\r\n        readonly linear: Color\r\n        /** A version of the color that has had the gamma curve applied.\r\n         */\r\n        readonly gamma: Color\r\n        /** Returns the maximum color component value: Max(r,g,b).\r\n         */\r\n        readonly maxColorComponent: number\r\n        /** Red component of the color.\r\n         */\r\n        r: number\r\n        /** Green component of the color.\r\n         */\r\n        g: number\r\n        /** Blue component of the color.\r\n         */\r\n        b: number\r\n        /** Alpha component of the color (0 is transparent, 1 is opaque).\r\n         */\r\n        a: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** Representation of RGBA colors in 32 bit format.\r\n     */\r\n    class Color32 extends ValueType {\r\n        constructor(r: jsb.byte, g: jsb.byte, b: jsb.byte, a: jsb.byte)\r\n        $GetValue(index: number): jsb.byte\r\n        $SetValue(index: number, value: jsb.byte): void\r\n        /** Returns a formatted string for this color.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string, formatProvider: any): string\r\n        /** Returns a formatted string for this color.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string): string\r\n        toString(): string\r\n        Compare(b: Color32): boolean\r\n        CompareRGB(b: Color32): boolean\r\n        Multiply(c2: Color32): Color32\r\n        Tint(c2: Color32): Color32\r\n        Tint(tint: number): Color32\r\n        static op_Implicit(c: Color): Color32\r\n        static op_Implicit(c: Color32): Color\r\n        /** Linearly interpolates between colors a and b by t.\r\n         */\r\n        static Lerp(a: Color32, b: Color32, t: number): Color32\r\n        /** Linearly interpolates between colors a and b by t.\r\n         */\r\n        static LerpUnclamped(a: Color32, b: Color32, t: number): Color32\r\n        /** Red component of the color.\r\n         */\r\n        r: jsb.byte\r\n        /** Green component of the color.\r\n         */\r\n        g: jsb.byte\r\n        /** Blue component of the color.\r\n         */\r\n        b: jsb.byte\r\n        /** Alpha component of the color.\r\n         */\r\n        a: jsb.byte\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array, Object as Object1 } from \"System\";\r\n    /** Representation of 2D vectors and points.\r\n     */\r\n    class Vector2 extends ValueType {\r\n        constructor(x: number, y: number)\r\n        $GetValue(index: number): number\r\n        $SetValue(index: number, value: number): void\r\n        /** Set x and y components of an existing Vector2.\r\n         */\r\n        Set(newX: number, newY: number): void\r\n        /** Multiplies every component of this vector by the same component of scale.\r\n         */\r\n        Scale(scale: Vector2): void\r\n        Normalize(): void\r\n        /** Returns a formatted string for this vector.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string, formatProvider: any): string\r\n        /** Returns a formatted string for this vector.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string): string\r\n        toString(): string\r\n        GetHashCode(): number\r\n        /** Returns true if the given vector is exactly equal to this vector.\r\n         */\r\n        Equals(other: Object1): boolean\r\n        Equals(other: Vector2): boolean\r\n        SqrMagnitude(): number\r\n        /** Linearly interpolates between vectors a and b by t.\r\n         */\r\n        static Lerp(a: Vector2, b: Vector2, t: number): Vector2\r\n        /** Linearly interpolates between vectors a and b by t.\r\n         */\r\n        static LerpUnclamped(a: Vector2, b: Vector2, t: number): Vector2\r\n        /** Moves a point current towards target.\r\n         */\r\n        static MoveTowards(current: Vector2, target: Vector2, maxDistanceDelta: number): Vector2\r\n        /** Multiplies two vectors component-wise.\r\n         */\r\n        static Scale(a: Vector2, b: Vector2): Vector2\r\n        /** Reflects a vector off the vector defined by a normal.\r\n         */\r\n        static Reflect(inDirection: Vector2, inNormal: Vector2): Vector2\r\n        /** Returns the 2D vector perpendicular to this 2D vector. The result is always rotated 90-degrees in a counter-clockwise direction for a 2D coordinate system where the positive Y axis goes up.\r\n         * @param inDirection The input direction.\r\n         * @returns The perpendicular direction. \r\n         */\r\n        static Perpendicular(inDirection: Vector2): Vector2\r\n        /** Dot Product of two vectors.\r\n         */\r\n        static Dot(lhs: Vector2, rhs: Vector2): number\r\n        /** Returns the unsigned angle in degrees between from and to.\r\n         * @param from The vector from which the angular difference is measured.\r\n         * @param to The vector to which the angular difference is measured.\r\n         */\r\n        static Angle(from: Vector2, to: Vector2): number\r\n        /** Returns the signed angle in degrees between from and to.\r\n         * @param from The vector from which the angular difference is measured.\r\n         * @param to The vector to which the angular difference is measured.\r\n         */\r\n        static SignedAngle(from: Vector2, to: Vector2): number\r\n        /** Returns the distance between a and b.\r\n         */\r\n        static Distance(a: Vector2, b: Vector2): number\r\n        /** Returns a copy of vector with its magnitude clamped to maxLength.\r\n         */\r\n        static ClampMagnitude(vector: Vector2, maxLength: number): Vector2\r\n        static SqrMagnitude(a: Vector2): number\r\n        /** Returns a vector that is made from the smallest components of two vectors.\r\n         */\r\n        static Min(lhs: Vector2, rhs: Vector2): Vector2\r\n        /** Returns a vector that is made from the largest components of two vectors.\r\n         */\r\n        static Max(lhs: Vector2, rhs: Vector2): Vector2\r\n        /** Gradually changes a vector towards a desired goal over time.\r\n         * @param current The current position.\r\n         * @param target The position we are trying to reach.\r\n         * @param currentVelocity The current velocity, this value is modified by the function every time you call it.\r\n         * @param smoothTime Approximately the time it will take to reach the target. A smaller value will reach the target faster.\r\n         * @param maxSpeed Optionally allows you to clamp the maximum speed.\r\n         * @param deltaTime The time since the last call to this function. By default Time.deltaTime.\r\n         */\r\n        static SmoothDamp(current: Vector2, target: Vector2, currentVelocity: jsb.Ref<Vector2>, smoothTime: number, maxSpeed: number, deltaTime: number): Vector2\r\n        /** Gradually changes a vector towards a desired goal over time.\r\n         * @param current The current position.\r\n         * @param target The position we are trying to reach.\r\n         * @param currentVelocity The current velocity, this value is modified by the function every time you call it.\r\n         * @param smoothTime Approximately the time it will take to reach the target. A smaller value will reach the target faster.\r\n         * @param maxSpeed Optionally allows you to clamp the maximum speed.\r\n         * @param deltaTime The time since the last call to this function. By default Time.deltaTime.\r\n         */\r\n        static SmoothDamp(current: Vector2, target: Vector2, currentVelocity: jsb.Ref<Vector2>, smoothTime: number, maxSpeed: number): Vector2\r\n        /** Gradually changes a vector towards a desired goal over time.\r\n         * @param current The current position.\r\n         * @param target The position we are trying to reach.\r\n         * @param currentVelocity The current velocity, this value is modified by the function every time you call it.\r\n         * @param smoothTime Approximately the time it will take to reach the target. A smaller value will reach the target faster.\r\n         * @param maxSpeed Optionally allows you to clamp the maximum speed.\r\n         * @param deltaTime The time since the last call to this function. By default Time.deltaTime.\r\n         */\r\n        static SmoothDamp(current: Vector2, target: Vector2, currentVelocity: jsb.Ref<Vector2>, smoothTime: number): Vector2\r\n        static op_Addition(a: Vector2, b: Vector2): Vector2\r\n        static op_Subtraction(a: Vector2, b: Vector2): Vector2\r\n        static op_Multiply(a: Vector2, b: Vector2): Vector2\r\n        static op_Multiply(a: Vector2, d: number): Vector2\r\n        static op_Multiply(d: number, a: Vector2): Vector2\r\n        static op_Division(a: Vector2, b: Vector2): Vector2\r\n        static op_Division(a: Vector2, d: number): Vector2\r\n        static op_UnaryNegation(a: Vector2): Vector2\r\n        static op_Equality(lhs: Vector2, rhs: Vector2): boolean\r\n        static op_Inequality(lhs: Vector2, rhs: Vector2): boolean\r\n        static op_Implicit(v: Vector3): Vector2\r\n        static op_Implicit(v: Vector2): Vector3\r\n        // js_op_overloading: static +(a: Vector2, b: Vector2): Vector2\r\n        // js_op_overloading: static -(a: Vector2, b: Vector2): Vector2\r\n        // js_op_overloading: static *(a: Vector2, b: Vector2): Vector2\r\n        // js_op_overloading: static /(a: Vector2, b: Vector2): Vector2\r\n        // js_op_overloading: static neg(a: Vector2): Vector2\r\n        // js_op_overloading: static *(a: Vector2, d: number): Vector2\r\n        // js_op_overloading: static *(d: number, a: Vector2): Vector2\r\n        // js_op_overloading: static /(a: Vector2, d: number): Vector2\r\n        // js_op_overloading: static ==(lhs: Vector2, rhs: Vector2): boolean\r\n        /** Returns this vector with a magnitude of 1 (Read Only).\r\n         */\r\n        readonly normalized: Vector2\r\n        /** Returns the length of this vector (Read Only).\r\n         */\r\n        readonly magnitude: number\r\n        /** Returns the squared length of this vector (Read Only).\r\n         */\r\n        readonly sqrMagnitude: number\r\n        /** Shorthand for writing Vector2(0, 0).\r\n         */\r\n        static readonly zero: Vector2\r\n        /** Shorthand for writing Vector2(1, 1).\r\n         */\r\n        static readonly one: Vector2\r\n        /** Shorthand for writing Vector2(0, 1).\r\n         */\r\n        static readonly up: Vector2\r\n        /** Shorthand for writing Vector2(0, -1).\r\n         */\r\n        static readonly down: Vector2\r\n        /** Shorthand for writing Vector2(-1, 0).\r\n         */\r\n        static readonly left: Vector2\r\n        /** Shorthand for writing Vector2(1, 0).\r\n         */\r\n        static readonly right: Vector2\r\n        /** Shorthand for writing Vector2(float.PositiveInfinity, float.PositiveInfinity).\r\n         */\r\n        static readonly positiveInfinity: Vector2\r\n        /** Shorthand for writing Vector2(float.NegativeInfinity, float.NegativeInfinity).\r\n         */\r\n        static readonly negativeInfinity: Vector2\r\n        /** X component of the vector.\r\n         */\r\n        x: number\r\n        /** Y component of the vector.\r\n         */\r\n        y: number\r\n        static readonly kEpsilon: number\r\n        static readonly kEpsilonNormalSqrt: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { ValueType, Object as Object1 } from \"System\";\r\n    /** Representation of 2D vectors and points using integers.\r\n     */\r\n    class Vector2Int extends ValueType {\r\n        constructor(x: number, y: number)\r\n        $GetValue(index: number): number\r\n        $SetValue(index: number, value: number): void\r\n        /** Set x and y components of an existing Vector2Int.\r\n         */\r\n        Set(x: number, y: number): void\r\n        /** Multiplies every component of this vector by the same component of scale.\r\n         */\r\n        Scale(scale: Vector2Int): void\r\n        /** Clamps the Vector2Int to the bounds given by min and max.\r\n         */\r\n        Clamp(min: Vector2Int, max: Vector2Int): void\r\n        /** Returns true if the objects are equal.\r\n         */\r\n        Equals(other: Object1): boolean\r\n        Equals(other: Vector2Int): boolean\r\n        GetHashCode(): number\r\n        /** Returns a formatted string for this vector.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string, formatProvider: any): string\r\n        /** Returns a formatted string for this vector.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string): string\r\n        toString(): string\r\n        /** Returns the distance between a and b.\r\n         */\r\n        static Distance(a: Vector2Int, b: Vector2Int): number\r\n        /** Returns a vector that is made from the smallest components of two vectors.\r\n         */\r\n        static Min(lhs: Vector2Int, rhs: Vector2Int): Vector2Int\r\n        /** Returns a vector that is made from the largest components of two vectors.\r\n         */\r\n        static Max(lhs: Vector2Int, rhs: Vector2Int): Vector2Int\r\n        /** Multiplies two vectors component-wise.\r\n         */\r\n        static Scale(a: Vector2Int, b: Vector2Int): Vector2Int\r\n        static op_Implicit(v: Vector2Int): Vector2\r\n        static op_Explicit(v: Vector2Int): Vector3Int\r\n        /** Converts a Vector2 to a Vector2Int by doing a Floor to each value.\r\n         */\r\n        static FloorToInt(v: Vector2): Vector2Int\r\n        /** Converts a  Vector2 to a Vector2Int by doing a Ceiling to each value.\r\n         */\r\n        static CeilToInt(v: Vector2): Vector2Int\r\n        /** Converts a  Vector2 to a Vector2Int by doing a Round to each value.\r\n         */\r\n        static RoundToInt(v: Vector2): Vector2Int\r\n        static op_UnaryNegation(v: Vector2Int): Vector2Int\r\n        static op_Addition(a: Vector2Int, b: Vector2Int): Vector2Int\r\n        static op_Subtraction(a: Vector2Int, b: Vector2Int): Vector2Int\r\n        static op_Multiply(a: Vector2Int, b: Vector2Int): Vector2Int\r\n        static op_Multiply(a: number, b: Vector2Int): Vector2Int\r\n        static op_Multiply(a: Vector2Int, b: number): Vector2Int\r\n        static op_Division(a: Vector2Int, b: number): Vector2Int\r\n        static op_Equality(lhs: Vector2Int, rhs: Vector2Int): boolean\r\n        static op_Inequality(lhs: Vector2Int, rhs: Vector2Int): boolean\r\n        // js_op_overloading: static neg(v: Vector2Int): Vector2Int\r\n        // js_op_overloading: static +(a: Vector2Int, b: Vector2Int): Vector2Int\r\n        // js_op_overloading: static -(a: Vector2Int, b: Vector2Int): Vector2Int\r\n        // js_op_overloading: static *(a: Vector2Int, b: Vector2Int): Vector2Int\r\n        // js_op_overloading: static *(a: number, b: Vector2Int): Vector2Int\r\n        // js_op_overloading: static *(a: Vector2Int, b: number): Vector2Int\r\n        // js_op_overloading: static /(a: Vector2Int, b: number): Vector2Int\r\n        // js_op_overloading: static ==(lhs: Vector2Int, rhs: Vector2Int): boolean\r\n        /** X component of the vector.\r\n         */\r\n        x: number\r\n        /** Y component of the vector.\r\n         */\r\n        y: number\r\n        /** Returns the length of this vector (Read Only).\r\n         */\r\n        readonly magnitude: number\r\n        /** Returns the squared length of this vector (Read Only).\r\n         */\r\n        readonly sqrMagnitude: number\r\n        /** Shorthand for writing Vector2Int(0, 0).\r\n         */\r\n        static readonly zero: Vector2Int\r\n        /** Shorthand for writing Vector2Int(1, 1).\r\n         */\r\n        static readonly one: Vector2Int\r\n        /** Shorthand for writing Vector2Int(0, 1).\r\n         */\r\n        static readonly up: Vector2Int\r\n        /** Shorthand for writing Vector2Int(0, -1).\r\n         */\r\n        static readonly down: Vector2Int\r\n        /** Shorthand for writing Vector2Int(-1, 0).\r\n         */\r\n        static readonly left: Vector2Int\r\n        /** Shorthand for writing Vector2Int(1, 0).\r\n         */\r\n        static readonly right: Vector2Int\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array, Object as Object1 } from \"System\";\r\n    /** Representation of 3D vectors and points.\r\n     */\r\n    class Vector3 extends ValueType {\r\n        constructor(x: number, y: number, z: number)\r\n        constructor(x: number, y: number)\r\n        $GetValue(index: number): number\r\n        $SetValue(index: number, value: number): void\r\n        /** Set x, y and z components of an existing Vector3.\r\n         */\r\n        Set(newX: number, newY: number, newZ: number): void\r\n        /** Multiplies every component of this vector by the same component of scale.\r\n         */\r\n        Scale(scale: Vector3): void\r\n        GetHashCode(): number\r\n        /** Returns true if the given vector is exactly equal to this vector.\r\n         */\r\n        Equals(other: Object1): boolean\r\n        Equals(other: Vector3): boolean\r\n        Normalize(): void\r\n        /** Returns a formatted string for this vector.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string, formatProvider: any): string\r\n        /** Returns a formatted string for this vector.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string): string\r\n        toString(): string\r\n        Compare(v2: Vector3, accuracy: number): boolean\r\n        /** Spherically interpolates between two vectors.\r\n         */\r\n        static Slerp(a: Vector3, b: Vector3, t: number): Vector3\r\n        /** Spherically interpolates between two vectors.\r\n         */\r\n        static SlerpUnclamped(a: Vector3, b: Vector3, t: number): Vector3\r\n        /** Makes vectors normalized and orthogonal to each other.\r\n         */\r\n        static OrthoNormalize(normal: jsb.Ref<Vector3>, tangent: jsb.Ref<Vector3>, binormal: jsb.Ref<Vector3>): void\r\n        /** Makes vectors normalized and orthogonal to each other.\r\n         */\r\n        static OrthoNormalize(normal: jsb.Ref<Vector3>, tangent: jsb.Ref<Vector3>): void\r\n        /** Rotates a vector current towards target.\r\n         * @param current The vector being managed.\r\n         * @param target The vector.\r\n         * @param maxRadiansDelta The maximum angle in radians allowed for this rotation.\r\n         * @param maxMagnitudeDelta The maximum allowed change in vector magnitude for this rotation.\r\n         * @returns The location that RotateTowards generates. \r\n         */\r\n        static RotateTowards(current: Vector3, target: Vector3, maxRadiansDelta: number, maxMagnitudeDelta: number): Vector3\r\n        /** Linearly interpolates between two points.\r\n         * @param a Start value, returned when t = 0.\r\n         * @param b End value, returned when t = 1.\r\n         * @param t Value used to interpolate between a and b.\r\n         * @returns Interpolated value, equals to a + (b - a) * t. \r\n         */\r\n        static Lerp(a: Vector3, b: Vector3, t: number): Vector3\r\n        /** Linearly interpolates between two vectors.\r\n         */\r\n        static LerpUnclamped(a: Vector3, b: Vector3, t: number): Vector3\r\n        /** Calculate a position between the points specified by current and target, moving no farther than the distance specified by maxDistanceDelta.\r\n         * @param current The position to move from.\r\n         * @param target The position to move towards.\r\n         * @param maxDistanceDelta Distance to move current per call.\r\n         * @returns The new position. \r\n         */\r\n        static MoveTowards(current: Vector3, target: Vector3, maxDistanceDelta: number): Vector3\r\n        /** Gradually changes a vector towards a desired goal over time.\r\n         * @param current The current position.\r\n         * @param target The position we are trying to reach.\r\n         * @param currentVelocity The current velocity, this value is modified by the function every time you call it.\r\n         * @param smoothTime Approximately the time it will take to reach the target. A smaller value will reach the target faster.\r\n         * @param maxSpeed Optionally allows you to clamp the maximum speed.\r\n         * @param deltaTime The time since the last call to this function. By default Time.deltaTime.\r\n         */\r\n        static SmoothDamp(current: Vector3, target: Vector3, currentVelocity: jsb.Ref<Vector3>, smoothTime: number, maxSpeed: number, deltaTime: number): Vector3\r\n        /** Gradually changes a vector towards a desired goal over time.\r\n         * @param current The current position.\r\n         * @param target The position we are trying to reach.\r\n         * @param currentVelocity The current velocity, this value is modified by the function every time you call it.\r\n         * @param smoothTime Approximately the time it will take to reach the target. A smaller value will reach the target faster.\r\n         * @param maxSpeed Optionally allows you to clamp the maximum speed.\r\n         * @param deltaTime The time since the last call to this function. By default Time.deltaTime.\r\n         */\r\n        static SmoothDamp(current: Vector3, target: Vector3, currentVelocity: jsb.Ref<Vector3>, smoothTime: number, maxSpeed: number): Vector3\r\n        /** Gradually changes a vector towards a desired goal over time.\r\n         * @param current The current position.\r\n         * @param target The position we are trying to reach.\r\n         * @param currentVelocity The current velocity, this value is modified by the function every time you call it.\r\n         * @param smoothTime Approximately the time it will take to reach the target. A smaller value will reach the target faster.\r\n         * @param maxSpeed Optionally allows you to clamp the maximum speed.\r\n         * @param deltaTime The time since the last call to this function. By default Time.deltaTime.\r\n         */\r\n        static SmoothDamp(current: Vector3, target: Vector3, currentVelocity: jsb.Ref<Vector3>, smoothTime: number): Vector3\r\n        /** Multiplies two vectors component-wise.\r\n         */\r\n        static Scale(a: Vector3, b: Vector3): Vector3\r\n        /** Cross Product of two vectors.\r\n         */\r\n        static Cross(lhs: Vector3, rhs: Vector3): Vector3\r\n        /** Reflects a vector off the plane defined by a normal.\r\n         */\r\n        static Reflect(inDirection: Vector3, inNormal: Vector3): Vector3\r\n        /** Makes this vector have a magnitude of 1.\r\n         */\r\n        static Normalize(value: Vector3): Vector3\r\n        /** Dot Product of two vectors.\r\n         */\r\n        static Dot(lhs: Vector3, rhs: Vector3): number\r\n        /** Projects a vector onto another vector.\r\n         */\r\n        static Project(vector: Vector3, onNormal: Vector3): Vector3\r\n        /** Projects a vector onto a plane defined by a normal orthogonal to the plane.\r\n         * @param planeNormal The direction from the vector towards the plane.\r\n         * @param vector The location of the vector above the plane.\r\n         * @returns The location of the vector on the plane. \r\n         */\r\n        static ProjectOnPlane(vector: Vector3, planeNormal: Vector3): Vector3\r\n        /** Returns the angle in degrees between from and to.\r\n         * @param from The vector from which the angular difference is measured.\r\n         * @param to The vector to which the angular difference is measured.\r\n         * @returns The angle in degrees between the two vectors. \r\n         */\r\n        static Angle(from: Vector3, to: Vector3): number\r\n        /** Returns the signed angle in degrees between from and to.\r\n         * @param from The vector from which the angular difference is measured.\r\n         * @param to The vector to which the angular difference is measured.\r\n         * @param axis A vector around which the other vectors are rotated.\r\n         */\r\n        static SignedAngle(from: Vector3, to: Vector3, axis: Vector3): number\r\n        /** Returns the distance between a and b.\r\n         */\r\n        static Distance(a: Vector3, b: Vector3): number\r\n        /** Returns a copy of vector with its magnitude clamped to maxLength.\r\n         */\r\n        static ClampMagnitude(vector: Vector3, maxLength: number): Vector3\r\n        static Magnitude(vector: Vector3): number\r\n        static SqrMagnitude(vector: Vector3): number\r\n        /** Returns a vector that is made from the smallest components of two vectors.\r\n         */\r\n        static Min(lhs: Vector3, rhs: Vector3): Vector3\r\n        /** Returns a vector that is made from the largest components of two vectors.\r\n         */\r\n        static Max(lhs: Vector3, rhs: Vector3): Vector3\r\n        static op_Addition(a: Vector3, b: Vector3): Vector3\r\n        static op_Subtraction(a: Vector3, b: Vector3): Vector3\r\n        static op_UnaryNegation(a: Vector3): Vector3\r\n        static op_Multiply(a: Vector3, d: number): Vector3\r\n        static op_Multiply(d: number, a: Vector3): Vector3\r\n        static op_Division(a: Vector3, d: number): Vector3\r\n        static op_Equality(lhs: Vector3, rhs: Vector3): boolean\r\n        static op_Inequality(lhs: Vector3, rhs: Vector3): boolean\r\n        // js_op_overloading: static +(a: Vector3, b: Vector3): Vector3\r\n        // js_op_overloading: static -(a: Vector3, b: Vector3): Vector3\r\n        // js_op_overloading: static neg(a: Vector3): Vector3\r\n        // js_op_overloading: static *(a: Vector3, d: number): Vector3\r\n        // js_op_overloading: static *(d: number, a: Vector3): Vector3\r\n        // js_op_overloading: static /(a: Vector3, d: number): Vector3\r\n        // js_op_overloading: static ==(lhs: Vector3, rhs: Vector3): boolean\r\n        /** Returns this vector with a magnitude of 1 (Read Only).\r\n         */\r\n        readonly normalized: Vector3\r\n        /** Returns the length of this vector (Read Only).\r\n         */\r\n        readonly magnitude: number\r\n        /** Returns the squared length of this vector (Read Only).\r\n         */\r\n        readonly sqrMagnitude: number\r\n        /** Shorthand for writing Vector3(0, 0, 0).\r\n         */\r\n        static readonly zero: Vector3\r\n        /** Shorthand for writing Vector3(1, 1, 1).\r\n         */\r\n        static readonly one: Vector3\r\n        /** Shorthand for writing Vector3(0, 0, 1).\r\n         */\r\n        static readonly forward: Vector3\r\n        /** Shorthand for writing Vector3(0, 0, -1).\r\n         */\r\n        static readonly back: Vector3\r\n        /** Shorthand for writing Vector3(0, 1, 0).\r\n         */\r\n        static readonly up: Vector3\r\n        /** Shorthand for writing Vector3(0, -1, 0).\r\n         */\r\n        static readonly down: Vector3\r\n        /** Shorthand for writing Vector3(-1, 0, 0).\r\n         */\r\n        static readonly left: Vector3\r\n        /** Shorthand for writing Vector3(1, 0, 0).\r\n         */\r\n        static readonly right: Vector3\r\n        /** Shorthand for writing Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity).\r\n         */\r\n        static readonly positiveInfinity: Vector3\r\n        /** Shorthand for writing Vector3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity).\r\n         */\r\n        static readonly negativeInfinity: Vector3\r\n        static readonly kEpsilon: number\r\n        static readonly kEpsilonNormalSqrt: number\r\n        /** X component of the vector.\r\n         */\r\n        x: number\r\n        /** Y component of the vector.\r\n         */\r\n        y: number\r\n        /** Z component of the vector.\r\n         */\r\n        z: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { ValueType, Object as Object1 } from \"System\";\r\n    /** Representation of 3D vectors and points using integers.\r\n     */\r\n    class Vector3Int extends ValueType {\r\n        constructor(x: number, y: number, z: number)\r\n        $GetValue(index: number): number\r\n        $SetValue(index: number, value: number): void\r\n        /** Set x, y and z components of an existing Vector3Int.\r\n         */\r\n        Set(x: number, y: number, z: number): void\r\n        /** Multiplies every component of this vector by the same component of scale.\r\n         */\r\n        Scale(scale: Vector3Int): void\r\n        /** Clamps the Vector3Int to the bounds given by min and max.\r\n         */\r\n        Clamp(min: Vector3Int, max: Vector3Int): void\r\n        /** Returns true if the objects are equal.\r\n         */\r\n        Equals(other: Object1): boolean\r\n        Equals(other: Vector3Int): boolean\r\n        GetHashCode(): number\r\n        /** Returns a formatted string for this vector.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string, formatProvider: any): string\r\n        /** Returns a formatted string for this vector.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string): string\r\n        toString(): string\r\n        /** Returns the distance between a and b.\r\n         */\r\n        static Distance(a: Vector3Int, b: Vector3Int): number\r\n        /** Returns a vector that is made from the smallest components of two vectors.\r\n         */\r\n        static Min(lhs: Vector3Int, rhs: Vector3Int): Vector3Int\r\n        /** Returns a vector that is made from the largest components of two vectors.\r\n         */\r\n        static Max(lhs: Vector3Int, rhs: Vector3Int): Vector3Int\r\n        /** Multiplies two vectors component-wise.\r\n         */\r\n        static Scale(a: Vector3Int, b: Vector3Int): Vector3Int\r\n        static op_Implicit(v: Vector3Int): Vector3\r\n        static op_Explicit(v: Vector3Int): Vector2Int\r\n        /** Converts a  Vector3 to a Vector3Int by doing a Floor to each value.\r\n         */\r\n        static FloorToInt(v: Vector3): Vector3Int\r\n        /** Converts a  Vector3 to a Vector3Int by doing a Ceiling to each value.\r\n         */\r\n        static CeilToInt(v: Vector3): Vector3Int\r\n        /** Converts a  Vector3 to a Vector3Int by doing a Round to each value.\r\n         */\r\n        static RoundToInt(v: Vector3): Vector3Int\r\n        static op_Addition(a: Vector3Int, b: Vector3Int): Vector3Int\r\n        static op_Subtraction(a: Vector3Int, b: Vector3Int): Vector3Int\r\n        static op_Multiply(a: Vector3Int, b: Vector3Int): Vector3Int\r\n        static op_Multiply(a: Vector3Int, b: number): Vector3Int\r\n        static op_Multiply(a: number, b: Vector3Int): Vector3Int\r\n        static op_UnaryNegation(a: Vector3Int): Vector3Int\r\n        static op_Division(a: Vector3Int, b: number): Vector3Int\r\n        static op_Equality(lhs: Vector3Int, rhs: Vector3Int): boolean\r\n        static op_Inequality(lhs: Vector3Int, rhs: Vector3Int): boolean\r\n        // js_op_overloading: static +(a: Vector3Int, b: Vector3Int): Vector3Int\r\n        // js_op_overloading: static -(a: Vector3Int, b: Vector3Int): Vector3Int\r\n        // js_op_overloading: static *(a: Vector3Int, b: Vector3Int): Vector3Int\r\n        // js_op_overloading: static neg(a: Vector3Int): Vector3Int\r\n        // js_op_overloading: static *(a: Vector3Int, b: number): Vector3Int\r\n        // js_op_overloading: static *(a: number, b: Vector3Int): Vector3Int\r\n        // js_op_overloading: static /(a: Vector3Int, b: number): Vector3Int\r\n        // js_op_overloading: static ==(lhs: Vector3Int, rhs: Vector3Int): boolean\r\n        /** X component of the vector.\r\n         */\r\n        x: number\r\n        /** Y component of the vector.\r\n         */\r\n        y: number\r\n        /** Z component of the vector.\r\n         */\r\n        z: number\r\n        /** Returns the length of this vector (Read Only).\r\n         */\r\n        readonly magnitude: number\r\n        /** Returns the squared length of this vector (Read Only).\r\n         */\r\n        readonly sqrMagnitude: number\r\n        /** Shorthand for writing Vector3Int(0, 0, 0).\r\n         */\r\n        static readonly zero: Vector3Int\r\n        /** Shorthand for writing Vector3Int(1, 1, 1).\r\n         */\r\n        static readonly one: Vector3Int\r\n        /** Shorthand for writing Vector3Int(0, 1, 0).\r\n         */\r\n        static readonly up: Vector3Int\r\n        /** Shorthand for writing Vector3Int(0, -1, 0).\r\n         */\r\n        static readonly down: Vector3Int\r\n        /** Shorthand for writing Vector3Int(-1, 0, 0).\r\n         */\r\n        static readonly left: Vector3Int\r\n        /** Shorthand for writing Vector3Int(1, 0, 0).\r\n         */\r\n        static readonly right: Vector3Int\r\n        /** Shorthand for writing Vector3Int(0, 0, 1).\r\n         */\r\n        static readonly forward: Vector3Int\r\n        /** Shorthand for writing Vector3Int(0, 0, -1).\r\n         */\r\n        static readonly back: Vector3Int\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { ValueType, Object as Object1 } from \"System\";\r\n    /** Representation of four-dimensional vectors.\r\n     */\r\n    class Vector4 extends ValueType {\r\n        constructor(x: number, y: number, z: number, w: number)\r\n        constructor(x: number, y: number, z: number)\r\n        constructor(x: number, y: number)\r\n        $GetValue(index: number): number\r\n        $SetValue(index: number, value: number): void\r\n        /** Set x, y, z and w components of an existing Vector4.\r\n         */\r\n        Set(newX: number, newY: number, newZ: number, newW: number): void\r\n        /** Multiplies every component of this vector by the same component of scale.\r\n         */\r\n        Scale(scale: Vector4): void\r\n        GetHashCode(): number\r\n        /** Returns true if the given vector is exactly equal to this vector.\r\n         */\r\n        Equals(other: Object1): boolean\r\n        Equals(other: Vector4): boolean\r\n        Normalize(): void\r\n        /** Returns a formatted string for this vector.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string, formatProvider: any): string\r\n        /** Returns a formatted string for this vector.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string): string\r\n        toString(): string\r\n        SqrMagnitude(): number\r\n        /** Linearly interpolates between two vectors.\r\n         */\r\n        static Lerp(a: Vector4, b: Vector4, t: number): Vector4\r\n        /** Linearly interpolates between two vectors.\r\n         */\r\n        static LerpUnclamped(a: Vector4, b: Vector4, t: number): Vector4\r\n        /** Moves a point current towards target.\r\n         */\r\n        static MoveTowards(current: Vector4, target: Vector4, maxDistanceDelta: number): Vector4\r\n        /** Multiplies two vectors component-wise.\r\n         */\r\n        static Scale(a: Vector4, b: Vector4): Vector4\r\n        static Normalize(a: Vector4): Vector4\r\n        /** Dot Product of two vectors.\r\n         */\r\n        static Dot(a: Vector4, b: Vector4): number\r\n        /** Projects a vector onto another vector.\r\n         */\r\n        static Project(a: Vector4, b: Vector4): Vector4\r\n        /** Returns the distance between a and b.\r\n         */\r\n        static Distance(a: Vector4, b: Vector4): number\r\n        static Magnitude(a: Vector4): number\r\n        /** Returns a vector that is made from the smallest components of two vectors.\r\n         */\r\n        static Min(lhs: Vector4, rhs: Vector4): Vector4\r\n        /** Returns a vector that is made from the largest components of two vectors.\r\n         */\r\n        static Max(lhs: Vector4, rhs: Vector4): Vector4\r\n        static op_Addition(a: Vector4, b: Vector4): Vector4\r\n        static op_Subtraction(a: Vector4, b: Vector4): Vector4\r\n        static op_UnaryNegation(a: Vector4): Vector4\r\n        static op_Multiply(a: Vector4, d: number): Vector4\r\n        static op_Multiply(d: number, a: Vector4): Vector4\r\n        static op_Division(a: Vector4, d: number): Vector4\r\n        static op_Equality(lhs: Vector4, rhs: Vector4): boolean\r\n        static op_Inequality(lhs: Vector4, rhs: Vector4): boolean\r\n        static op_Implicit(v: Vector3): Vector4\r\n        static op_Implicit(v: Vector4): Vector3\r\n        static op_Implicit(v: Vector2): Vector4\r\n        static SqrMagnitude(a: Vector4): number\r\n        // js_op_overloading: static +(a: Vector4, b: Vector4): Vector4\r\n        // js_op_overloading: static -(a: Vector4, b: Vector4): Vector4\r\n        // js_op_overloading: static neg(a: Vector4): Vector4\r\n        // js_op_overloading: static *(a: Vector4, d: number): Vector4\r\n        // js_op_overloading: static *(d: number, a: Vector4): Vector4\r\n        // js_op_overloading: static /(a: Vector4, d: number): Vector4\r\n        // js_op_overloading: static ==(lhs: Vector4, rhs: Vector4): boolean\r\n        /** Returns this vector with a magnitude of 1 (Read Only).\r\n         */\r\n        readonly normalized: Vector4\r\n        /** Returns the length of this vector (Read Only).\r\n         */\r\n        readonly magnitude: number\r\n        /** Returns the squared length of this vector (Read Only).\r\n         */\r\n        readonly sqrMagnitude: number\r\n        /** Shorthand for writing Vector4(0,0,0,0).\r\n         */\r\n        static readonly zero: Vector4\r\n        /** Shorthand for writing Vector4(1,1,1,1).\r\n         */\r\n        static readonly one: Vector4\r\n        /** Shorthand for writing Vector4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity).\r\n         */\r\n        static readonly positiveInfinity: Vector4\r\n        /** Shorthand for writing Vector4(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity).\r\n         */\r\n        static readonly negativeInfinity: Vector4\r\n        static readonly kEpsilon: number\r\n        /** X component of the vector.\r\n         */\r\n        x: number\r\n        /** Y component of the vector.\r\n         */\r\n        y: number\r\n        /** Z component of the vector.\r\n         */\r\n        z: number\r\n        /** W component of the vector.\r\n         */\r\n        w: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { ValueType, Object as Object1 } from \"System\";\r\n    /** A 2D Rectangle defined by X and Y position, width and height.\r\n     */\r\n    class Rect extends ValueType {\r\n        constructor(x: number, y: number, width: number, height: number)\r\n        constructor(position: Vector2, size: Vector2)\r\n        constructor(source: Rect)\r\n        /** Set components of an existing Rect.\r\n         */\r\n        Set(x: number, y: number, width: number, height: number): void\r\n        /** Returns true if the x and y components of point is a point inside this rectangle. If allowInverse is present and true, the width and height of the Rect are allowed to take negative values (ie, the min value is greater than the max), and the test will still work.\r\n         * @param point Point to test.\r\n         * @param allowInverse Does the test allow the Rect's width and height to be negative?\r\n         * @returns True if the point lies within the specified rectangle. \r\n         */\r\n        Contains(point: Vector3, allowInverse: boolean): boolean\r\n        /** Returns true if the x and y components of point is a point inside this rectangle. If allowInverse is present and true, the width and height of the Rect are allowed to take negative values (ie, the min value is greater than the max), and the test will still work.\r\n         * @param point Point to test.\r\n         * @param allowInverse Does the test allow the Rect's width and height to be negative?\r\n         * @returns True if the point lies within the specified rectangle. \r\n         */\r\n        Contains(point: Vector2): boolean\r\n        /** Returns true if the x and y components of point is a point inside this rectangle. If allowInverse is present and true, the width and height of the Rect are allowed to take negative values (ie, the min value is greater than the max), and the test will still work.\r\n         * @param point Point to test.\r\n         * @param allowInverse Does the test allow the Rect's width and height to be negative?\r\n         * @returns True if the point lies within the specified rectangle. \r\n         */\r\n        Contains(point: Vector3): boolean\r\n        /** Returns true if the other rectangle overlaps this one. If allowInverse is present and true, the widths and heights of the Rects are allowed to take negative values (ie, the min value is greater than the max), and the test will still work.\r\n         * @param other Other rectangle to test overlapping with.\r\n         * @param allowInverse Does the test allow the widths and heights of the Rects to be negative?\r\n         */\r\n        Overlaps(other: Rect, allowInverse: boolean): boolean\r\n        /** Returns true if the other rectangle overlaps this one. If allowInverse is present and true, the widths and heights of the Rects are allowed to take negative values (ie, the min value is greater than the max), and the test will still work.\r\n         * @param other Other rectangle to test overlapping with.\r\n         * @param allowInverse Does the test allow the widths and heights of the Rects to be negative?\r\n         */\r\n        Overlaps(other: Rect): boolean\r\n        GetHashCode(): number\r\n        Equals(other: Object1): boolean\r\n        Equals(other: Rect): boolean\r\n        /** Returns a formatted string for this Rect.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string, formatProvider: any): string\r\n        /** Returns a formatted string for this Rect.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string): string\r\n        toString(): string\r\n        /** Creates a rectangle from min/max coordinate values.\r\n         * @param xmin The minimum X coordinate.\r\n         * @param ymin The minimum Y coordinate.\r\n         * @param xmax The maximum X coordinate.\r\n         * @param ymax The maximum Y coordinate.\r\n         * @returns A rectangle matching the specified coordinates. \r\n         */\r\n        static MinMaxRect(xmin: number, ymin: number, xmax: number, ymax: number): Rect\r\n        /** Returns a point inside a rectangle, given normalized coordinates.\r\n         * @param rectangle Rectangle to get a point inside.\r\n         * @param normalizedRectCoordinates Normalized coordinates to get a point for.\r\n         */\r\n        static NormalizedToPoint(rectangle: Rect, normalizedRectCoordinates: Vector2): Vector2\r\n        /** Returns the normalized coordinates cooresponding the the point.\r\n         * @param rectangle Rectangle to get normalized coordinates inside.\r\n         * @param point A point inside the rectangle to get normalized coordinates for.\r\n         */\r\n        static PointToNormalized(rectangle: Rect, point: Vector2): Vector2\r\n        static op_Inequality(lhs: Rect, rhs: Rect): boolean\r\n        static op_Equality(lhs: Rect, rhs: Rect): boolean\r\n        // js_op_overloading: static ==(lhs: Rect, rhs: Rect): boolean\r\n        /** Shorthand for writing new Rect(0,0,0,0).\r\n         */\r\n        static readonly zero: Rect\r\n        /** The X coordinate of the rectangle.\r\n         */\r\n        x: number\r\n        /** The Y coordinate of the rectangle.\r\n         */\r\n        y: number\r\n        /** The X and Y position of the rectangle.\r\n         */\r\n        position: Vector2\r\n        /** The position of the center of the rectangle.\r\n         */\r\n        center: Vector2\r\n        /** The position of the minimum corner of the rectangle.\r\n         */\r\n        min: Vector2\r\n        /** The position of the maximum corner of the rectangle.\r\n         */\r\n        max: Vector2\r\n        /** The width of the rectangle, measured from the X position.\r\n         */\r\n        width: number\r\n        /** The height of the rectangle, measured from the Y position.\r\n         */\r\n        height: number\r\n        /** The width and height of the rectangle.\r\n         */\r\n        size: Vector2\r\n        /** The minimum X coordinate of the rectangle.\r\n         */\r\n        xMin: number\r\n        /** The minimum Y coordinate of the rectangle.\r\n         */\r\n        yMin: number\r\n        /** The maximum X coordinate of the rectangle.\r\n         */\r\n        xMax: number\r\n        /** The maximum Y coordinate of the rectangle.\r\n         */\r\n        yMax: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array, Object as Object1 } from \"System\";\r\n    /** Quaternions are used to represent rotations.\r\n     */\r\n    class Quaternion extends ValueType {\r\n        constructor(x: number, y: number, z: number, w: number)\r\n        $GetValue(index: number): number\r\n        $SetValue(index: number, value: number): void\r\n        /** Set x, y, z and w components of an existing Quaternion.\r\n         */\r\n        Set(newX: number, newY: number, newZ: number, newW: number): void\r\n        /** Creates a rotation with the specified forward and upwards directions.\r\n         * @param view The direction to look in.\r\n         * @param up The vector that defines in which direction up is.\r\n         */\r\n        SetLookRotation(view: Vector3, up: Vector3): void\r\n        /** Creates a rotation with the specified forward and upwards directions.\r\n         * @param view The direction to look in.\r\n         * @param up The vector that defines in which direction up is.\r\n         */\r\n        SetLookRotation(view: Vector3): void\r\n        /** Converts a rotation to angle-axis representation (angles in degrees).\r\n         */\r\n        ToAngleAxis(angle: jsb.Out<number>, axis: jsb.Out<Vector3>): void\r\n        /** Creates a rotation which rotates from fromDirection to toDirection.\r\n         */\r\n        SetFromToRotation(fromDirection: Vector3, toDirection: Vector3): void\r\n        Normalize(): void\r\n        GetHashCode(): number\r\n        Equals(other: Object1): boolean\r\n        Equals(other: Quaternion): boolean\r\n        /** Returns a formatted string of the Quaternion.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string, formatProvider: any): string\r\n        /** Returns a formatted string of the Quaternion.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string): string\r\n        toString(): string\r\n        Compare(q2: Quaternion, accuracy: number): boolean\r\n        /** Creates a rotation which rotates from fromDirection to toDirection.\r\n         */\r\n        static FromToRotation(fromDirection: Vector3, toDirection: Vector3): Quaternion\r\n        /** Returns the Inverse of rotation.\r\n         */\r\n        static Inverse(rotation: Quaternion): Quaternion\r\n        /** Spherically interpolates between quaternions a and b by ratio t. The parameter t is clamped to the range [0, 1].\r\n         * @param a Start value, returned when t = 0.\r\n         * @param b End value, returned when t = 1.\r\n         * @param t Interpolation ratio.\r\n         * @returns A quaternion spherically interpolated between quaternions a and b. \r\n         */\r\n        static Slerp(a: Quaternion, b: Quaternion, t: number): Quaternion\r\n        /** Spherically interpolates between a and b by t. The parameter t is not clamped.\r\n         */\r\n        static SlerpUnclamped(a: Quaternion, b: Quaternion, t: number): Quaternion\r\n        /** Interpolates between a and b by t and normalizes the result afterwards. The parameter t is clamped to the range [0, 1].\r\n         */\r\n        static Lerp(a: Quaternion, b: Quaternion, t: number): Quaternion\r\n        /** Interpolates between a and b by t and normalizes the result afterwards. The parameter t is not clamped.\r\n         */\r\n        static LerpUnclamped(a: Quaternion, b: Quaternion, t: number): Quaternion\r\n        /** Creates a rotation which rotates angle degrees around axis.\r\n         */\r\n        static AngleAxis(angle: number, axis: Vector3): Quaternion\r\n        /** Creates a rotation with the specified forward and upwards directions.\r\n         * @param forward The direction to look in.\r\n         * @param upwards The vector that defines in which direction up is.\r\n         */\r\n        static LookRotation(forward: Vector3, upwards: Vector3): Quaternion\r\n        /** Creates a rotation with the specified forward and upwards directions.\r\n         * @param forward The direction to look in.\r\n         * @param upwards The vector that defines in which direction up is.\r\n         */\r\n        static LookRotation(forward: Vector3): Quaternion\r\n        static op_Multiply(lhs: Quaternion, rhs: Quaternion): Quaternion\r\n        static op_Multiply(rotation: Quaternion, point: Vector3): Vector3\r\n        static op_Equality(lhs: Quaternion, rhs: Quaternion): boolean\r\n        static op_Inequality(lhs: Quaternion, rhs: Quaternion): boolean\r\n        /** The dot product between two rotations.\r\n         */\r\n        static Dot(a: Quaternion, b: Quaternion): number\r\n        /** Returns the angle in degrees between two rotations a and b.\r\n         */\r\n        static Angle(a: Quaternion, b: Quaternion): number\r\n        /** Returns a rotation that rotates z degrees around the z axis, x degrees around the x axis, and y degrees around the y axis; applied in that order.\r\n         */\r\n        static Euler(x: number, y: number, z: number): Quaternion\r\n        /** Returns a rotation that rotates z degrees around the z axis, x degrees around the x axis, and y degrees around the y axis.\r\n         */\r\n        static Euler(euler: Vector3): Quaternion\r\n        /** Rotates a rotation from towards to.\r\n         */\r\n        static RotateTowards(from: Quaternion, to: Quaternion, maxDegreesDelta: number): Quaternion\r\n        /** Converts this quaternion to one with the same orientation but with a magnitude of 1.\r\n         */\r\n        static Normalize(q: Quaternion): Quaternion\r\n        // js_op_overloading: static *(lhs: Quaternion, rhs: Quaternion): Quaternion\r\n        // js_op_overloading: static *(rotation: Quaternion, point: Vector3): Vector3\r\n        // js_op_overloading: static ==(lhs: Quaternion, rhs: Quaternion): boolean\r\n        /** The identity rotation (Read Only).\r\n         */\r\n        static readonly identity: Quaternion\r\n        /** Returns or sets the euler angle representation of the rotation.\r\n         */\r\n        eulerAngles: Vector3\r\n        /** Returns this quaternion with a magnitude of 1 (Read Only).\r\n         */\r\n        readonly normalized: Quaternion\r\n        /** X component of the Quaternion. Don't modify this directly unless you know quaternions inside out.\r\n         */\r\n        x: number\r\n        /** Y component of the Quaternion. Don't modify this directly unless you know quaternions inside out.\r\n         */\r\n        y: number\r\n        /** Z component of the Quaternion. Don't modify this directly unless you know quaternions inside out.\r\n         */\r\n        z: number\r\n        /** W component of the Quaternion. Do not directly modify quaternions.\r\n         */\r\n        w: number\r\n        static readonly kEpsilon: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array, Object as Object1 } from \"System\";\r\n    /** A standard 4x4 transformation matrix.\r\n     */\r\n    class Matrix4x4 extends ValueType {\r\n        constructor(column0: Vector4, column1: Vector4, column2: Vector4, column3: Vector4)\r\n        $GetValue(row: number, column: number): number\r\n        $GetValue(index: number): number\r\n        $SetValue(row: number, column: number, value: number): void\r\n        $SetValue(index: number, value: number): void\r\n        ValidTRS(): boolean\r\n        /** Sets this matrix to a translation, rotation and scaling matrix.\r\n         */\r\n        SetTRS(pos: Vector3, q: Quaternion, s: Vector3): void\r\n        GetHashCode(): number\r\n        Equals(other: Object1): boolean\r\n        Equals(other: Matrix4x4): boolean\r\n        /** Get a column of the matrix.\r\n         */\r\n        GetColumn(index: number): Vector4\r\n        /** Returns a row of the matrix.\r\n         */\r\n        GetRow(index: number): Vector4\r\n        /** Sets a column of the matrix.\r\n         */\r\n        SetColumn(index: number, column: Vector4): void\r\n        /** Sets a row of the matrix.\r\n         */\r\n        SetRow(index: number, row: Vector4): void\r\n        /** Transforms a position by this matrix (generic).\r\n         */\r\n        MultiplyPoint(point: Vector3): Vector3\r\n        /** Transforms a position by this matrix (fast).\r\n         */\r\n        MultiplyPoint3x4(point: Vector3): Vector3\r\n        /** Transforms a direction by this matrix.\r\n         */\r\n        MultiplyVector(vector: Vector3): Vector3\r\n        /** Returns a plane that is transformed in space.\r\n         */\r\n        TransformPlane(plane: any): any\r\n        /** Returns a formatted string for this matrix.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string, formatProvider: any): string\r\n        /** Returns a formatted string for this matrix.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string): string\r\n        toString(): string\r\n        static Determinant(m: Matrix4x4): number\r\n        /** Creates a translation, rotation and scaling matrix.\r\n         */\r\n        static TRS(pos: Vector3, q: Quaternion, s: Vector3): Matrix4x4\r\n        /** Computes the inverse of a 3D affine matrix.\r\n         * @param input Input matrix to invert.\r\n         * @param result The result of the inversion. Equal to the input matrix if the function fails.\r\n         * @returns Returns true and a valid result if the function succeeds, false and a copy of the input matrix if the function fails. \r\n         */\r\n        static Inverse3DAffine(input: Matrix4x4, result: jsb.Ref<Matrix4x4>): boolean\r\n        static Inverse(m: Matrix4x4): Matrix4x4\r\n        static Transpose(m: Matrix4x4): Matrix4x4\r\n        /** Create an orthogonal projection matrix.\r\n         * @param left Left-side x-coordinate.\r\n         * @param right Right-side x-coordinate.\r\n         * @param bottom Bottom y-coordinate.\r\n         * @param top Top y-coordinate.\r\n         * @param zNear Near depth clipping plane value.\r\n         * @param zFar Far depth clipping plane value.\r\n         * @returns The projection matrix. \r\n         */\r\n        static Ortho(left: number, right: number, bottom: number, top: number, zNear: number, zFar: number): Matrix4x4\r\n        /** Create a perspective projection matrix.\r\n         * @param fov Vertical field-of-view in degrees.\r\n         * @param aspect Aspect ratio (width divided by height).\r\n         * @param zNear Near depth clipping plane value.\r\n         * @param zFar Far depth clipping plane value.\r\n         * @returns The projection matrix. \r\n         */\r\n        static Perspective(fov: number, aspect: number, zNear: number, zFar: number): Matrix4x4\r\n        /** Create a \"look at\" matrix.\r\n         * @param from The source point.\r\n         * @param to The target point.\r\n         * @param up The vector describing the up direction (typically Vector3.up).\r\n         * @returns The resulting transformation matrix. \r\n         */\r\n        static LookAt(from: Vector3, to: Vector3, up: Vector3): Matrix4x4\r\n        /** This function returns a projection matrix with viewing frustum that has a near plane defined by the coordinates that were passed in.\r\n         * @param left The X coordinate of the left side of the near projection plane in view space.\r\n         * @param right The X coordinate of the right side of the near projection plane in view space.\r\n         * @param bottom The Y coordinate of the bottom side of the near projection plane in view space.\r\n         * @param top The Y coordinate of the top side of the near projection plane in view space.\r\n         * @param zNear Z distance to the near plane from the origin in view space.\r\n         * @param zFar Z distance to the far plane from the origin in view space.\r\n         * @param frustumPlanes Frustum planes struct that contains the view space coordinates of that define a viewing frustum.\r\n         * @returns A projection matrix with a viewing frustum defined by the plane coordinates passed in. \r\n         */\r\n        static Frustum(left: number, right: number, bottom: number, top: number, zNear: number, zFar: number): Matrix4x4\r\n        /** This function returns a projection matrix with viewing frustum that has a near plane defined by the coordinates that were passed in.\r\n         * @param left The X coordinate of the left side of the near projection plane in view space.\r\n         * @param right The X coordinate of the right side of the near projection plane in view space.\r\n         * @param bottom The Y coordinate of the bottom side of the near projection plane in view space.\r\n         * @param top The Y coordinate of the top side of the near projection plane in view space.\r\n         * @param zNear Z distance to the near plane from the origin in view space.\r\n         * @param zFar Z distance to the far plane from the origin in view space.\r\n         * @param frustumPlanes Frustum planes struct that contains the view space coordinates of that define a viewing frustum.\r\n         * @returns A projection matrix with a viewing frustum defined by the plane coordinates passed in. \r\n         */\r\n        static Frustum(fp: any): Matrix4x4\r\n        static op_Multiply(lhs: Matrix4x4, rhs: Matrix4x4): Matrix4x4\r\n        static op_Multiply(lhs: Matrix4x4, vector: Vector4): Vector4\r\n        static op_Equality(lhs: Matrix4x4, rhs: Matrix4x4): boolean\r\n        static op_Inequality(lhs: Matrix4x4, rhs: Matrix4x4): boolean\r\n        /** Creates a scaling matrix.\r\n         */\r\n        static Scale(vector: Vector3): Matrix4x4\r\n        /** Creates a translation matrix.\r\n         */\r\n        static Translate(vector: Vector3): Matrix4x4\r\n        /** Creates a rotation matrix.\r\n         */\r\n        static Rotate(q: Quaternion): Matrix4x4\r\n        // js_op_overloading: static *(lhs: Matrix4x4, rhs: Matrix4x4): Matrix4x4\r\n        // js_op_overloading: static *(lhs: Matrix4x4, vector: Vector4): Vector4\r\n        // js_op_overloading: static ==(lhs: Matrix4x4, rhs: Matrix4x4): boolean\r\n        /** Attempts to get a rotation quaternion from this matrix.\r\n         */\r\n        readonly rotation: Quaternion\r\n        /** Attempts to get a scale value from the matrix. (Read Only)\r\n         */\r\n        readonly lossyScale: Vector3\r\n        /** Checks whether this is an identity matrix. (Read Only)\r\n         */\r\n        readonly isIdentity: boolean\r\n        /** The determinant of the matrix. (Read Only)\r\n         */\r\n        readonly determinant: number\r\n        /** This property takes a projection matrix and returns the six plane coordinates that define a projection frustum.\r\n         */\r\n        readonly decomposeProjection: any\r\n        /** The inverse of this matrix. (Read Only)\r\n         */\r\n        readonly inverse: Matrix4x4\r\n        /** Returns the transpose of this matrix (Read Only).\r\n         */\r\n        readonly transpose: Matrix4x4\r\n        /** Returns a matrix with all elements set to zero (Read Only).\r\n         */\r\n        static readonly zero: Matrix4x4\r\n        /** Returns the identity matrix (Read Only).\r\n         */\r\n        static readonly identity: Matrix4x4\r\n        m00: number\r\n        m10: number\r\n        m20: number\r\n        m30: number\r\n        m01: number\r\n        m11: number\r\n        m21: number\r\n        m31: number\r\n        m02: number\r\n        m12: number\r\n        m22: number\r\n        m32: number\r\n        m03: number\r\n        m13: number\r\n        m23: number\r\n        m33: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Enum } from \"System\";\r\n    /** The various primitives that can be created using the GameObject.CreatePrimitive function.\r\n     */\r\n    enum PrimitiveType {\r\n        /** A sphere primitive.\r\n         */\r\n        Sphere = 0,\r\n        /** A capsule primitive.\r\n         */\r\n        Capsule = 1,\r\n        /** A cylinder primitive.\r\n         */\r\n        Cylinder = 2,\r\n        /** A cube primitive.\r\n         */\r\n        Cube = 3,\r\n        /** A plane primitive.\r\n         */\r\n        Plane = 4,\r\n        /** A quad primitive.\r\n         */\r\n        Quad = 5,\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object as Object1, Enum, Array } from \"System\";\r\n    /** Base class for all objects Unity can reference.\r\n     */\r\n    class Object extends Object1 {\r\n        constructor()\r\n        GetInstanceID(): number\r\n        GetHashCode(): number\r\n        Equals(other: Object1): boolean\r\n        toString(): string\r\n        static op_Implicit(exists: Object): boolean\r\n        /** Clones the object original and returns the clone.\r\n         * @param original An existing object that you want to make a copy of.\r\n         * @param position Position for the new object.\r\n         * @param rotation Orientation of the new object.\r\n         * @param parent Parent that will be assigned to the new object.\r\n         * @param instantiateInWorldSpace When you assign a parent Object, pass true to position the new object directly in world space. Pass false to set the Object’s position relative to its new parent..\r\n         * @returns The instantiated clone. \r\n         */\r\n        static Instantiate(original: Object, position: Vector3, rotation: Quaternion, parent: Transform): Object\r\n        /** Clones the object original and returns the clone.\r\n         * @param original An existing object that you want to make a copy of.\r\n         * @param position Position for the new object.\r\n         * @param rotation Orientation of the new object.\r\n         * @param parent Parent that will be assigned to the new object.\r\n         * @param instantiateInWorldSpace When you assign a parent Object, pass true to position the new object directly in world space. Pass false to set the Object’s position relative to its new parent..\r\n         * @returns The instantiated clone. \r\n         */\r\n        static Instantiate(original: Object, position: Vector3, rotation: Quaternion): Object\r\n        /** Clones the object original and returns the clone.\r\n         * @param original An existing object that you want to make a copy of.\r\n         * @param position Position for the new object.\r\n         * @param rotation Orientation of the new object.\r\n         * @param parent Parent that will be assigned to the new object.\r\n         * @param instantiateInWorldSpace When you assign a parent Object, pass true to position the new object directly in world space. Pass false to set the Object’s position relative to its new parent..\r\n         * @returns The instantiated clone. \r\n         */\r\n        static Instantiate(original: Object, parent: Transform, instantiateInWorldSpace: boolean): Object\r\n        /** Clones the object original and returns the clone.\r\n         * @param original An existing object that you want to make a copy of.\r\n         * @param position Position for the new object.\r\n         * @param rotation Orientation of the new object.\r\n         * @param parent Parent that will be assigned to the new object.\r\n         * @param instantiateInWorldSpace When you assign a parent Object, pass true to position the new object directly in world space. Pass false to set the Object’s position relative to its new parent..\r\n         * @returns The instantiated clone. \r\n         */\r\n        static Instantiate(original: Object, parent: Transform): Object\r\n        /** Clones the object original and returns the clone.\r\n         * @param original An existing object that you want to make a copy of.\r\n         * @param position Position for the new object.\r\n         * @param rotation Orientation of the new object.\r\n         * @param parent Parent that will be assigned to the new object.\r\n         * @param instantiateInWorldSpace When you assign a parent Object, pass true to position the new object directly in world space. Pass false to set the Object’s position relative to its new parent..\r\n         * @returns The instantiated clone. \r\n         */\r\n        static Instantiate(original: Object): Object\r\n        /** Removes a GameObject, component or asset.\r\n         * @param obj The object to destroy.\r\n         * @param t The optional amount of time to delay before destroying the object.\r\n         */\r\n        static Destroy(obj: Object, t: number): void\r\n        /** Removes a GameObject, component or asset.\r\n         * @param obj The object to destroy.\r\n         * @param t The optional amount of time to delay before destroying the object.\r\n         */\r\n        static Destroy(obj: Object): void\r\n        /** Destroys the object obj immediately. You are strongly recommended to use Destroy instead.\r\n         * @param obj Object to be destroyed.\r\n         * @param allowDestroyingAssets Set to true to allow assets to be destroyed.\r\n         */\r\n        static DestroyImmediate(obj: Object, allowDestroyingAssets: boolean): void\r\n        /** Destroys the object obj immediately. You are strongly recommended to use Destroy instead.\r\n         * @param obj Object to be destroyed.\r\n         * @param allowDestroyingAssets Set to true to allow assets to be destroyed.\r\n         */\r\n        static DestroyImmediate(obj: Object): void\r\n        /** Gets a list of all loaded objects of Type type.\r\n         * @param type The type of object to find.\r\n         * @param includeInactive If true, components attached to inactive GameObjects are also included.\r\n         * @returns The array of objects found matching the type specified. \r\n         */\r\n        static FindObjectsOfType(type: any, includeInactive: boolean): Array<Object>\r\n        /** Gets a list of all loaded objects of Type type.\r\n         * @param type The type of object to find.\r\n         * @param includeInactive If true, components attached to inactive GameObjects are also included.\r\n         * @returns The array of objects found matching the type specified. \r\n         */\r\n        static FindObjectsOfType(type: any): Array<Object>\r\n        /** Do not destroy the target Object when loading a new Scene.\r\n         * @param target An Object not destroyed on Scene change.\r\n         */\r\n        static DontDestroyOnLoad(target: Object): void\r\n        /** Returns the first active loaded object of Type type.\r\n         * @param type The type of object to find.\r\n         * @returns Object The first active loaded object that matches the specified type. It returns null if no Object matches the type. \r\n         */\r\n        static FindObjectOfType(type: any, includeInactive: boolean): Object\r\n        /** Returns the first active loaded object of Type type.\r\n         * @param type The type of object to find.\r\n         * @returns Object The first active loaded object that matches the specified type. It returns null if no Object matches the type. \r\n         */\r\n        static FindObjectOfType(type: any): Object\r\n        static op_Equality(x: Object, y: Object): boolean\r\n        static op_Inequality(x: Object, y: Object): boolean\r\n        /** The name of the object.\r\n         */\r\n        name: string\r\n        /** Should the object be hidden, saved with the Scene or modifiable by the user?\r\n         */\r\n        hideFlags: any\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Enum } from \"System\";\r\n    /** Key codes returned by Event.keyCode. These map directly to a physical key on the keyboard.\r\n     */\r\n    enum KeyCode {\r\n        /** Not assigned (never returned as the result of a keystroke).\r\n         */\r\n        None = 0,\r\n        /** The backspace key.\r\n         */\r\n        Backspace = 8,\r\n        /** The tab key.\r\n         */\r\n        Tab = 9,\r\n        /** The Clear key.\r\n         */\r\n        Clear = 12,\r\n        /** Return key.\r\n         */\r\n        Return = 13,\r\n        /** Pause on PC machines.\r\n         */\r\n        Pause = 19,\r\n        /** Escape key.\r\n         */\r\n        Escape = 27,\r\n        /** Space key.\r\n         */\r\n        Space = 32,\r\n        /** Exclamation mark key '!'.\r\n         */\r\n        Exclaim = 33,\r\n        /** Double quote key '\"'.\r\n         */\r\n        DoubleQuote = 34,\r\n        /** Hash key '#'.\r\n         */\r\n        Hash = 35,\r\n        /** Dollar sign key '$'.\r\n         */\r\n        Dollar = 36,\r\n        /** Percent '%' key.\r\n         */\r\n        Percent = 37,\r\n        /** Ampersand key '&'.\r\n         */\r\n        Ampersand = 38,\r\n        /** Quote key '.\r\n         */\r\n        Quote = 39,\r\n        /** Left Parenthesis key '('.\r\n         */\r\n        LeftParen = 40,\r\n        /** Right Parenthesis key ')'.\r\n         */\r\n        RightParen = 41,\r\n        /** Asterisk key '*'.\r\n         */\r\n        Asterisk = 42,\r\n        /** Plus key '+'.\r\n         */\r\n        Plus = 43,\r\n        /** Comma ',' key.\r\n         */\r\n        Comma = 44,\r\n        /** Minus '-' key.\r\n         */\r\n        Minus = 45,\r\n        /** Period '.' key.\r\n         */\r\n        Period = 46,\r\n        /** Slash '/' key.\r\n         */\r\n        Slash = 47,\r\n        /** The '0' key on the top of the alphanumeric keyboard.\r\n         */\r\n        Alpha0 = 48,\r\n        /** The '1' key on the top of the alphanumeric keyboard.\r\n         */\r\n        Alpha1 = 49,\r\n        /** The '2' key on the top of the alphanumeric keyboard.\r\n         */\r\n        Alpha2 = 50,\r\n        /** The '3' key on the top of the alphanumeric keyboard.\r\n         */\r\n        Alpha3 = 51,\r\n        /** The '4' key on the top of the alphanumeric keyboard.\r\n         */\r\n        Alpha4 = 52,\r\n        /** The '5' key on the top of the alphanumeric keyboard.\r\n         */\r\n        Alpha5 = 53,\r\n        /** The '6' key on the top of the alphanumeric keyboard.\r\n         */\r\n        Alpha6 = 54,\r\n        /** The '7' key on the top of the alphanumeric keyboard.\r\n         */\r\n        Alpha7 = 55,\r\n        /** The '8' key on the top of the alphanumeric keyboard.\r\n         */\r\n        Alpha8 = 56,\r\n        /** The '9' key on the top of the alphanumeric keyboard.\r\n         */\r\n        Alpha9 = 57,\r\n        /** Colon ':' key.\r\n         */\r\n        Colon = 58,\r\n        /** Semicolon ';' key.\r\n         */\r\n        Semicolon = 59,\r\n        /** Less than '<' key.\r\n         */\r\n        Less = 60,\r\n        /** Equals '=' key.\r\n         */\r\n        Equals = 61,\r\n        /** Greater than '>' key.\r\n         */\r\n        Greater = 62,\r\n        /** Question mark '?' key.\r\n         */\r\n        Question = 63,\r\n        /** At key '@'.\r\n         */\r\n        At = 64,\r\n        /** Left square bracket key '['.\r\n         */\r\n        LeftBracket = 91,\r\n        /** Backslash key '\\'.\r\n         */\r\n        Backslash = 92,\r\n        /** Right square bracket key ']'.\r\n         */\r\n        RightBracket = 93,\r\n        /** Caret key '^'.\r\n         */\r\n        Caret = 94,\r\n        /** Underscore '_' key.\r\n         */\r\n        Underscore = 95,\r\n        /** Back quote key '`'.\r\n         */\r\n        BackQuote = 96,\r\n        /** 'a' key.\r\n         */\r\n        A = 97,\r\n        /** 'b' key.\r\n         */\r\n        B = 98,\r\n        /** 'c' key.\r\n         */\r\n        C = 99,\r\n        /** 'd' key.\r\n         */\r\n        D = 100,\r\n        /** 'e' key.\r\n         */\r\n        E = 101,\r\n        /** 'f' key.\r\n         */\r\n        F = 102,\r\n        /** 'g' key.\r\n         */\r\n        G = 103,\r\n        /** 'h' key.\r\n         */\r\n        H = 104,\r\n        /** 'i' key.\r\n         */\r\n        I = 105,\r\n        /** 'j' key.\r\n         */\r\n        J = 106,\r\n        /** 'k' key.\r\n         */\r\n        K = 107,\r\n        /** 'l' key.\r\n         */\r\n        L = 108,\r\n        /** 'm' key.\r\n         */\r\n        M = 109,\r\n        /** 'n' key.\r\n         */\r\n        N = 110,\r\n        /** 'o' key.\r\n         */\r\n        O = 111,\r\n        /** 'p' key.\r\n         */\r\n        P = 112,\r\n        /** 'q' key.\r\n         */\r\n        Q = 113,\r\n        /** 'r' key.\r\n         */\r\n        R = 114,\r\n        /** 's' key.\r\n         */\r\n        S = 115,\r\n        /** 't' key.\r\n         */\r\n        T = 116,\r\n        /** 'u' key.\r\n         */\r\n        U = 117,\r\n        /** 'v' key.\r\n         */\r\n        V = 118,\r\n        /** 'w' key.\r\n         */\r\n        W = 119,\r\n        /** 'x' key.\r\n         */\r\n        X = 120,\r\n        /** 'y' key.\r\n         */\r\n        Y = 121,\r\n        /** 'z' key.\r\n         */\r\n        Z = 122,\r\n        /** Left curly bracket key '{'.\r\n         */\r\n        LeftCurlyBracket = 123,\r\n        /** Pipe '|' key.\r\n         */\r\n        Pipe = 124,\r\n        /** Right curly bracket key '}'.\r\n         */\r\n        RightCurlyBracket = 125,\r\n        /** Tilde '~' key.\r\n         */\r\n        Tilde = 126,\r\n        /** The forward delete key.\r\n         */\r\n        Delete = 127,\r\n        /** Numeric keypad 0.\r\n         */\r\n        Keypad0 = 256,\r\n        /** Numeric keypad 1.\r\n         */\r\n        Keypad1 = 257,\r\n        /** Numeric keypad 2.\r\n         */\r\n        Keypad2 = 258,\r\n        /** Numeric keypad 3.\r\n         */\r\n        Keypad3 = 259,\r\n        /** Numeric keypad 4.\r\n         */\r\n        Keypad4 = 260,\r\n        /** Numeric keypad 5.\r\n         */\r\n        Keypad5 = 261,\r\n        /** Numeric keypad 6.\r\n         */\r\n        Keypad6 = 262,\r\n        /** Numeric keypad 7.\r\n         */\r\n        Keypad7 = 263,\r\n        /** Numeric keypad 8.\r\n         */\r\n        Keypad8 = 264,\r\n        /** Numeric keypad 9.\r\n         */\r\n        Keypad9 = 265,\r\n        /** Numeric keypad '.'.\r\n         */\r\n        KeypadPeriod = 266,\r\n        /** Numeric keypad '/'.\r\n         */\r\n        KeypadDivide = 267,\r\n        /** Numeric keypad '*'.\r\n         */\r\n        KeypadMultiply = 268,\r\n        /** Numeric keypad '-'.\r\n         */\r\n        KeypadMinus = 269,\r\n        /** Numeric keypad '+'.\r\n         */\r\n        KeypadPlus = 270,\r\n        /** Numeric keypad Enter.\r\n         */\r\n        KeypadEnter = 271,\r\n        /** Numeric keypad '='.\r\n         */\r\n        KeypadEquals = 272,\r\n        /** Up arrow key.\r\n         */\r\n        UpArrow = 273,\r\n        /** Down arrow key.\r\n         */\r\n        DownArrow = 274,\r\n        /** Right arrow key.\r\n         */\r\n        RightArrow = 275,\r\n        /** Left arrow key.\r\n         */\r\n        LeftArrow = 276,\r\n        /** Insert key key.\r\n         */\r\n        Insert = 277,\r\n        /** Home key.\r\n         */\r\n        Home = 278,\r\n        /** End key.\r\n         */\r\n        End = 279,\r\n        /** Page up.\r\n         */\r\n        PageUp = 280,\r\n        /** Page down.\r\n         */\r\n        PageDown = 281,\r\n        /** F1 function key.\r\n         */\r\n        F1 = 282,\r\n        /** F2 function key.\r\n         */\r\n        F2 = 283,\r\n        /** F3 function key.\r\n         */\r\n        F3 = 284,\r\n        /** F4 function key.\r\n         */\r\n        F4 = 285,\r\n        /** F5 function key.\r\n         */\r\n        F5 = 286,\r\n        /** F6 function key.\r\n         */\r\n        F6 = 287,\r\n        /** F7 function key.\r\n         */\r\n        F7 = 288,\r\n        /** F8 function key.\r\n         */\r\n        F8 = 289,\r\n        /** F9 function key.\r\n         */\r\n        F9 = 290,\r\n        /** F10 function key.\r\n         */\r\n        F10 = 291,\r\n        /** F11 function key.\r\n         */\r\n        F11 = 292,\r\n        /** F12 function key.\r\n         */\r\n        F12 = 293,\r\n        /** F13 function key.\r\n         */\r\n        F13 = 294,\r\n        /** F14 function key.\r\n         */\r\n        F14 = 295,\r\n        /** F15 function key.\r\n         */\r\n        F15 = 296,\r\n        /** Numlock key.\r\n         */\r\n        Numlock = 300,\r\n        /** Capslock key.\r\n         */\r\n        CapsLock = 301,\r\n        /** Scroll lock key.\r\n         */\r\n        ScrollLock = 302,\r\n        /** Right shift key.\r\n         */\r\n        RightShift = 303,\r\n        /** Left shift key.\r\n         */\r\n        LeftShift = 304,\r\n        /** Right Control key.\r\n         */\r\n        RightControl = 305,\r\n        /** Left Control key.\r\n         */\r\n        LeftControl = 306,\r\n        /** Right Alt key.\r\n         */\r\n        RightAlt = 307,\r\n        /** Left Alt key.\r\n         */\r\n        LeftAlt = 308,\r\n        /** Right Command key.\r\n         */\r\n        RightCommand = 309,\r\n        /** Right Command key.\r\n         */\r\n        RightApple = 309,\r\n        /** Left Command key.\r\n         */\r\n        LeftCommand = 310,\r\n        /** Left Command key.\r\n         */\r\n        LeftApple = 310,\r\n        /** Left Windows key.\r\n         */\r\n        LeftWindows = 311,\r\n        /** Right Windows key.\r\n         */\r\n        RightWindows = 312,\r\n        /** Alt Gr key.\r\n         */\r\n        AltGr = 313,\r\n        /** Help key.\r\n         */\r\n        Help = 315,\r\n        /** Print key.\r\n         */\r\n        Print = 316,\r\n        /** Sys Req key.\r\n         */\r\n        SysReq = 317,\r\n        /** Break key.\r\n         */\r\n        Break = 318,\r\n        /** Menu key.\r\n         */\r\n        Menu = 319,\r\n        /** The Left (or primary) mouse button.\r\n         */\r\n        Mouse0 = 323,\r\n        /** Right mouse button (or secondary mouse button).\r\n         */\r\n        Mouse1 = 324,\r\n        /** Middle mouse button (or third button).\r\n         */\r\n        Mouse2 = 325,\r\n        /** Additional (fourth) mouse button.\r\n         */\r\n        Mouse3 = 326,\r\n        /** Additional (fifth) mouse button.\r\n         */\r\n        Mouse4 = 327,\r\n        /** Additional (or sixth) mouse button.\r\n         */\r\n        Mouse5 = 328,\r\n        /** Additional (or seventh) mouse button.\r\n         */\r\n        Mouse6 = 329,\r\n        /** Button 0 on any joystick.\r\n         */\r\n        JoystickButton0 = 330,\r\n        /** Button 1 on any joystick.\r\n         */\r\n        JoystickButton1 = 331,\r\n        /** Button 2 on any joystick.\r\n         */\r\n        JoystickButton2 = 332,\r\n        /** Button 3 on any joystick.\r\n         */\r\n        JoystickButton3 = 333,\r\n        /** Button 4 on any joystick.\r\n         */\r\n        JoystickButton4 = 334,\r\n        /** Button 5 on any joystick.\r\n         */\r\n        JoystickButton5 = 335,\r\n        /** Button 6 on any joystick.\r\n         */\r\n        JoystickButton6 = 336,\r\n        /** Button 7 on any joystick.\r\n         */\r\n        JoystickButton7 = 337,\r\n        /** Button 8 on any joystick.\r\n         */\r\n        JoystickButton8 = 338,\r\n        /** Button 9 on any joystick.\r\n         */\r\n        JoystickButton9 = 339,\r\n        /** Button 10 on any joystick.\r\n         */\r\n        JoystickButton10 = 340,\r\n        /** Button 11 on any joystick.\r\n         */\r\n        JoystickButton11 = 341,\r\n        /** Button 12 on any joystick.\r\n         */\r\n        JoystickButton12 = 342,\r\n        /** Button 13 on any joystick.\r\n         */\r\n        JoystickButton13 = 343,\r\n        /** Button 14 on any joystick.\r\n         */\r\n        JoystickButton14 = 344,\r\n        /** Button 15 on any joystick.\r\n         */\r\n        JoystickButton15 = 345,\r\n        /** Button 16 on any joystick.\r\n         */\r\n        JoystickButton16 = 346,\r\n        /** Button 17 on any joystick.\r\n         */\r\n        JoystickButton17 = 347,\r\n        /** Button 18 on any joystick.\r\n         */\r\n        JoystickButton18 = 348,\r\n        /** Button 19 on any joystick.\r\n         */\r\n        JoystickButton19 = 349,\r\n        /** Button 0 on first joystick.\r\n         */\r\n        Joystick1Button0 = 350,\r\n        /** Button 1 on first joystick.\r\n         */\r\n        Joystick1Button1 = 351,\r\n        /** Button 2 on first joystick.\r\n         */\r\n        Joystick1Button2 = 352,\r\n        /** Button 3 on first joystick.\r\n         */\r\n        Joystick1Button3 = 353,\r\n        /** Button 4 on first joystick.\r\n         */\r\n        Joystick1Button4 = 354,\r\n        /** Button 5 on first joystick.\r\n         */\r\n        Joystick1Button5 = 355,\r\n        /** Button 6 on first joystick.\r\n         */\r\n        Joystick1Button6 = 356,\r\n        /** Button 7 on first joystick.\r\n         */\r\n        Joystick1Button7 = 357,\r\n        /** Button 8 on first joystick.\r\n         */\r\n        Joystick1Button8 = 358,\r\n        /** Button 9 on first joystick.\r\n         */\r\n        Joystick1Button9 = 359,\r\n        /** Button 10 on first joystick.\r\n         */\r\n        Joystick1Button10 = 360,\r\n        /** Button 11 on first joystick.\r\n         */\r\n        Joystick1Button11 = 361,\r\n        /** Button 12 on first joystick.\r\n         */\r\n        Joystick1Button12 = 362,\r\n        /** Button 13 on first joystick.\r\n         */\r\n        Joystick1Button13 = 363,\r\n        /** Button 14 on first joystick.\r\n         */\r\n        Joystick1Button14 = 364,\r\n        /** Button 15 on first joystick.\r\n         */\r\n        Joystick1Button15 = 365,\r\n        /** Button 16 on first joystick.\r\n         */\r\n        Joystick1Button16 = 366,\r\n        /** Button 17 on first joystick.\r\n         */\r\n        Joystick1Button17 = 367,\r\n        /** Button 18 on first joystick.\r\n         */\r\n        Joystick1Button18 = 368,\r\n        /** Button 19 on first joystick.\r\n         */\r\n        Joystick1Button19 = 369,\r\n        /** Button 0 on second joystick.\r\n         */\r\n        Joystick2Button0 = 370,\r\n        /** Button 1 on second joystick.\r\n         */\r\n        Joystick2Button1 = 371,\r\n        /** Button 2 on second joystick.\r\n         */\r\n        Joystick2Button2 = 372,\r\n        /** Button 3 on second joystick.\r\n         */\r\n        Joystick2Button3 = 373,\r\n        /** Button 4 on second joystick.\r\n         */\r\n        Joystick2Button4 = 374,\r\n        /** Button 5 on second joystick.\r\n         */\r\n        Joystick2Button5 = 375,\r\n        /** Button 6 on second joystick.\r\n         */\r\n        Joystick2Button6 = 376,\r\n        /** Button 7 on second joystick.\r\n         */\r\n        Joystick2Button7 = 377,\r\n        /** Button 8 on second joystick.\r\n         */\r\n        Joystick2Button8 = 378,\r\n        /** Button 9 on second joystick.\r\n         */\r\n        Joystick2Button9 = 379,\r\n        /** Button 10 on second joystick.\r\n         */\r\n        Joystick2Button10 = 380,\r\n        /** Button 11 on second joystick.\r\n         */\r\n        Joystick2Button11 = 381,\r\n        /** Button 12 on second joystick.\r\n         */\r\n        Joystick2Button12 = 382,\r\n        /** Button 13 on second joystick.\r\n         */\r\n        Joystick2Button13 = 383,\r\n        /** Button 14 on second joystick.\r\n         */\r\n        Joystick2Button14 = 384,\r\n        /** Button 15 on second joystick.\r\n         */\r\n        Joystick2Button15 = 385,\r\n        /** Button 16 on second joystick.\r\n         */\r\n        Joystick2Button16 = 386,\r\n        /** Button 17 on second joystick.\r\n         */\r\n        Joystick2Button17 = 387,\r\n        /** Button 18 on second joystick.\r\n         */\r\n        Joystick2Button18 = 388,\r\n        /** Button 19 on second joystick.\r\n         */\r\n        Joystick2Button19 = 389,\r\n        /** Button 0 on third joystick.\r\n         */\r\n        Joystick3Button0 = 390,\r\n        /** Button 1 on third joystick.\r\n         */\r\n        Joystick3Button1 = 391,\r\n        /** Button 2 on third joystick.\r\n         */\r\n        Joystick3Button2 = 392,\r\n        /** Button 3 on third joystick.\r\n         */\r\n        Joystick3Button3 = 393,\r\n        /** Button 4 on third joystick.\r\n         */\r\n        Joystick3Button4 = 394,\r\n        /** Button 5 on third joystick.\r\n         */\r\n        Joystick3Button5 = 395,\r\n        /** Button 6 on third joystick.\r\n         */\r\n        Joystick3Button6 = 396,\r\n        /** Button 7 on third joystick.\r\n         */\r\n        Joystick3Button7 = 397,\r\n        /** Button 8 on third joystick.\r\n         */\r\n        Joystick3Button8 = 398,\r\n        /** Button 9 on third joystick.\r\n         */\r\n        Joystick3Button9 = 399,\r\n        /** Button 10 on third joystick.\r\n         */\r\n        Joystick3Button10 = 400,\r\n        /** Button 11 on third joystick.\r\n         */\r\n        Joystick3Button11 = 401,\r\n        /** Button 12 on third joystick.\r\n         */\r\n        Joystick3Button12 = 402,\r\n        /** Button 13 on third joystick.\r\n         */\r\n        Joystick3Button13 = 403,\r\n        /** Button 14 on third joystick.\r\n         */\r\n        Joystick3Button14 = 404,\r\n        /** Button 15 on third joystick.\r\n         */\r\n        Joystick3Button15 = 405,\r\n        /** Button 16 on third joystick.\r\n         */\r\n        Joystick3Button16 = 406,\r\n        /** Button 17 on third joystick.\r\n         */\r\n        Joystick3Button17 = 407,\r\n        /** Button 18 on third joystick.\r\n         */\r\n        Joystick3Button18 = 408,\r\n        /** Button 19 on third joystick.\r\n         */\r\n        Joystick3Button19 = 409,\r\n        /** Button 0 on forth joystick.\r\n         */\r\n        Joystick4Button0 = 410,\r\n        /** Button 1 on forth joystick.\r\n         */\r\n        Joystick4Button1 = 411,\r\n        /** Button 2 on forth joystick.\r\n         */\r\n        Joystick4Button2 = 412,\r\n        /** Button 3 on forth joystick.\r\n         */\r\n        Joystick4Button3 = 413,\r\n        /** Button 4 on forth joystick.\r\n         */\r\n        Joystick4Button4 = 414,\r\n        /** Button 5 on forth joystick.\r\n         */\r\n        Joystick4Button5 = 415,\r\n        /** Button 6 on forth joystick.\r\n         */\r\n        Joystick4Button6 = 416,\r\n        /** Button 7 on forth joystick.\r\n         */\r\n        Joystick4Button7 = 417,\r\n        /** Button 8 on forth joystick.\r\n         */\r\n        Joystick4Button8 = 418,\r\n        /** Button 9 on forth joystick.\r\n         */\r\n        Joystick4Button9 = 419,\r\n        /** Button 10 on forth joystick.\r\n         */\r\n        Joystick4Button10 = 420,\r\n        /** Button 11 on forth joystick.\r\n         */\r\n        Joystick4Button11 = 421,\r\n        /** Button 12 on forth joystick.\r\n         */\r\n        Joystick4Button12 = 422,\r\n        /** Button 13 on forth joystick.\r\n         */\r\n        Joystick4Button13 = 423,\r\n        /** Button 14 on forth joystick.\r\n         */\r\n        Joystick4Button14 = 424,\r\n        /** Button 15 on forth joystick.\r\n         */\r\n        Joystick4Button15 = 425,\r\n        /** Button 16 on forth joystick.\r\n         */\r\n        Joystick4Button16 = 426,\r\n        /** Button 17 on forth joystick.\r\n         */\r\n        Joystick4Button17 = 427,\r\n        /** Button 18 on forth joystick.\r\n         */\r\n        Joystick4Button18 = 428,\r\n        /** Button 19 on forth joystick.\r\n         */\r\n        Joystick4Button19 = 429,\r\n        /** Button 0 on fifth joystick.\r\n         */\r\n        Joystick5Button0 = 430,\r\n        /** Button 1 on fifth joystick.\r\n         */\r\n        Joystick5Button1 = 431,\r\n        /** Button 2 on fifth joystick.\r\n         */\r\n        Joystick5Button2 = 432,\r\n        /** Button 3 on fifth joystick.\r\n         */\r\n        Joystick5Button3 = 433,\r\n        /** Button 4 on fifth joystick.\r\n         */\r\n        Joystick5Button4 = 434,\r\n        /** Button 5 on fifth joystick.\r\n         */\r\n        Joystick5Button5 = 435,\r\n        /** Button 6 on fifth joystick.\r\n         */\r\n        Joystick5Button6 = 436,\r\n        /** Button 7 on fifth joystick.\r\n         */\r\n        Joystick5Button7 = 437,\r\n        /** Button 8 on fifth joystick.\r\n         */\r\n        Joystick5Button8 = 438,\r\n        /** Button 9 on fifth joystick.\r\n         */\r\n        Joystick5Button9 = 439,\r\n        /** Button 10 on fifth joystick.\r\n         */\r\n        Joystick5Button10 = 440,\r\n        /** Button 11 on fifth joystick.\r\n         */\r\n        Joystick5Button11 = 441,\r\n        /** Button 12 on fifth joystick.\r\n         */\r\n        Joystick5Button12 = 442,\r\n        /** Button 13 on fifth joystick.\r\n         */\r\n        Joystick5Button13 = 443,\r\n        /** Button 14 on fifth joystick.\r\n         */\r\n        Joystick5Button14 = 444,\r\n        /** Button 15 on fifth joystick.\r\n         */\r\n        Joystick5Button15 = 445,\r\n        /** Button 16 on fifth joystick.\r\n         */\r\n        Joystick5Button16 = 446,\r\n        /** Button 17 on fifth joystick.\r\n         */\r\n        Joystick5Button17 = 447,\r\n        /** Button 18 on fifth joystick.\r\n         */\r\n        Joystick5Button18 = 448,\r\n        /** Button 19 on fifth joystick.\r\n         */\r\n        Joystick5Button19 = 449,\r\n        /** Button 0 on sixth joystick.\r\n         */\r\n        Joystick6Button0 = 450,\r\n        /** Button 1 on sixth joystick.\r\n         */\r\n        Joystick6Button1 = 451,\r\n        /** Button 2 on sixth joystick.\r\n         */\r\n        Joystick6Button2 = 452,\r\n        /** Button 3 on sixth joystick.\r\n         */\r\n        Joystick6Button3 = 453,\r\n        /** Button 4 on sixth joystick.\r\n         */\r\n        Joystick6Button4 = 454,\r\n        /** Button 5 on sixth joystick.\r\n         */\r\n        Joystick6Button5 = 455,\r\n        /** Button 6 on sixth joystick.\r\n         */\r\n        Joystick6Button6 = 456,\r\n        /** Button 7 on sixth joystick.\r\n         */\r\n        Joystick6Button7 = 457,\r\n        /** Button 8 on sixth joystick.\r\n         */\r\n        Joystick6Button8 = 458,\r\n        /** Button 9 on sixth joystick.\r\n         */\r\n        Joystick6Button9 = 459,\r\n        /** Button 10 on sixth joystick.\r\n         */\r\n        Joystick6Button10 = 460,\r\n        /** Button 11 on sixth joystick.\r\n         */\r\n        Joystick6Button11 = 461,\r\n        /** Button 12 on sixth joystick.\r\n         */\r\n        Joystick6Button12 = 462,\r\n        /** Button 13 on sixth joystick.\r\n         */\r\n        Joystick6Button13 = 463,\r\n        /** Button 14 on sixth joystick.\r\n         */\r\n        Joystick6Button14 = 464,\r\n        /** Button 15 on sixth joystick.\r\n         */\r\n        Joystick6Button15 = 465,\r\n        /** Button 16 on sixth joystick.\r\n         */\r\n        Joystick6Button16 = 466,\r\n        /** Button 17 on sixth joystick.\r\n         */\r\n        Joystick6Button17 = 467,\r\n        /** Button 18 on sixth joystick.\r\n         */\r\n        Joystick6Button18 = 468,\r\n        /** Button 19 on sixth joystick.\r\n         */\r\n        Joystick6Button19 = 469,\r\n        /** Button 0 on seventh joystick.\r\n         */\r\n        Joystick7Button0 = 470,\r\n        /** Button 1 on seventh joystick.\r\n         */\r\n        Joystick7Button1 = 471,\r\n        /** Button 2 on seventh joystick.\r\n         */\r\n        Joystick7Button2 = 472,\r\n        /** Button 3 on seventh joystick.\r\n         */\r\n        Joystick7Button3 = 473,\r\n        /** Button 4 on seventh joystick.\r\n         */\r\n        Joystick7Button4 = 474,\r\n        /** Button 5 on seventh joystick.\r\n         */\r\n        Joystick7Button5 = 475,\r\n        /** Button 6 on seventh joystick.\r\n         */\r\n        Joystick7Button6 = 476,\r\n        /** Button 7 on seventh joystick.\r\n         */\r\n        Joystick7Button7 = 477,\r\n        /** Button 8 on seventh joystick.\r\n         */\r\n        Joystick7Button8 = 478,\r\n        /** Button 9 on seventh joystick.\r\n         */\r\n        Joystick7Button9 = 479,\r\n        /** Button 10 on seventh joystick.\r\n         */\r\n        Joystick7Button10 = 480,\r\n        /** Button 11 on seventh joystick.\r\n         */\r\n        Joystick7Button11 = 481,\r\n        /** Button 12 on seventh joystick.\r\n         */\r\n        Joystick7Button12 = 482,\r\n        /** Button 13 on seventh joystick.\r\n         */\r\n        Joystick7Button13 = 483,\r\n        /** Button 14 on seventh joystick.\r\n         */\r\n        Joystick7Button14 = 484,\r\n        /** Button 15 on seventh joystick.\r\n         */\r\n        Joystick7Button15 = 485,\r\n        /** Button 16 on seventh joystick.\r\n         */\r\n        Joystick7Button16 = 486,\r\n        /** Button 17 on seventh joystick.\r\n         */\r\n        Joystick7Button17 = 487,\r\n        /** Button 18 on seventh joystick.\r\n         */\r\n        Joystick7Button18 = 488,\r\n        /** Button 19 on seventh joystick.\r\n         */\r\n        Joystick7Button19 = 489,\r\n        /** Button 0 on eighth joystick.\r\n         */\r\n        Joystick8Button0 = 490,\r\n        /** Button 1 on eighth joystick.\r\n         */\r\n        Joystick8Button1 = 491,\r\n        /** Button 2 on eighth joystick.\r\n         */\r\n        Joystick8Button2 = 492,\r\n        /** Button 3 on eighth joystick.\r\n         */\r\n        Joystick8Button3 = 493,\r\n        /** Button 4 on eighth joystick.\r\n         */\r\n        Joystick8Button4 = 494,\r\n        /** Button 5 on eighth joystick.\r\n         */\r\n        Joystick8Button5 = 495,\r\n        /** Button 6 on eighth joystick.\r\n         */\r\n        Joystick8Button6 = 496,\r\n        /** Button 7 on eighth joystick.\r\n         */\r\n        Joystick8Button7 = 497,\r\n        /** Button 8 on eighth joystick.\r\n         */\r\n        Joystick8Button8 = 498,\r\n        /** Button 9 on eighth joystick.\r\n         */\r\n        Joystick8Button9 = 499,\r\n        /** Button 10 on eighth joystick.\r\n         */\r\n        Joystick8Button10 = 500,\r\n        /** Button 11 on eighth joystick.\r\n         */\r\n        Joystick8Button11 = 501,\r\n        /** Button 12 on eighth joystick.\r\n         */\r\n        Joystick8Button12 = 502,\r\n        /** Button 13 on eighth joystick.\r\n         */\r\n        Joystick8Button13 = 503,\r\n        /** Button 14 on eighth joystick.\r\n         */\r\n        Joystick8Button14 = 504,\r\n        /** Button 15 on eighth joystick.\r\n         */\r\n        Joystick8Button15 = 505,\r\n        /** Button 16 on eighth joystick.\r\n         */\r\n        Joystick8Button16 = 506,\r\n        /** Button 17 on eighth joystick.\r\n         */\r\n        Joystick8Button17 = 507,\r\n        /** Button 18 on eighth joystick.\r\n         */\r\n        Joystick8Button18 = 508,\r\n        /** Button 19 on eighth joystick.\r\n         */\r\n        Joystick8Button19 = 509,\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Enum } from \"System\";\r\n    /** Base class for Texture handling.\r\n     */\r\n    class Texture extends Object {\r\n        GetNativeTexturePtr(): any\r\n        IncrementUpdateCount(): void\r\n        /** Sets Anisotropic limits.\r\n         */\r\n        static SetGlobalAnisotropicFilteringLimits(forcedMin: number, globalMax: number): void\r\n        static SetStreamingTextureMaterialDebugProperties(): void\r\n        protected constructor()\r\n        static masterTextureLimit: number\r\n        /** How many mipmap levels are in this Texture (Read Only).\r\n         */\r\n        readonly mipmapCount: number\r\n        static anisotropicFiltering: any\r\n        /** Returns the GraphicsFormat format or color format of a Texture object.\r\n         */\r\n        readonly graphicsFormat: any\r\n        /** Width of the Texture in pixels. (Read Only)\r\n         */\r\n        width: number\r\n        /** Height of the Texture in pixels. (Read Only)\r\n         */\r\n        height: number\r\n        /** Dimensionality (type) of the Texture (Read Only).\r\n         */\r\n        dimension: any\r\n        /** Returns true if the Read/Write Enabled checkbox was checked when the Texture was imported; otherwise returns false. For a dynamic Texture created from script, always returns true. For additional information, see TextureImporter.isReadable.\r\n         */\r\n        readonly isReadable: boolean\r\n        /** Texture coordinate wrapping mode.\r\n         */\r\n        wrapMode: any\r\n        /** Texture U coordinate wrapping mode.\r\n         */\r\n        wrapModeU: any\r\n        /** Texture V coordinate wrapping mode.\r\n         */\r\n        wrapModeV: any\r\n        /** Texture W coordinate wrapping mode for Texture3D.\r\n         */\r\n        wrapModeW: any\r\n        /** Filtering mode of the Texture.\r\n         */\r\n        filterMode: any\r\n        /** Defines the anisotropic filtering level of the Texture.\r\n         */\r\n        anisoLevel: number\r\n        /** The mipmap bias of the Texture.\r\n         */\r\n        mipMapBias: number\r\n        readonly texelSize: Vector2\r\n        /** This counter is incremented when the Texture is updated.\r\n         */\r\n        readonly updateCount: number\r\n        /** The total amount of Texture memory that Unity would use if it loads all Textures at mipmap level 0.\n\nThis is a theoretical value that does not take into account any input from the streaming system or any other input, for example when you set the`Texture2D.requestedMipmapLevel` manually.\n\nTo see a Texture memory value that takes inputs into account, use `desiredTextureMemory`.\n\n`totalTextureMemory` only includes instances of Texture2D and CubeMap Textures. It does not include any other Texture types, or 2D and CubeMap Textures that Unity creates internally.\r\n         */\r\n        static readonly totalTextureMemory: number\r\n        /** The total size of the Textures, in bytes, that Unity loads if there were no other constraints. Before Unity loads any Textures, it applies the which reduces the loaded Texture resolution if the Texture sizes exceed its value. The `desiredTextureMemory` value takes into account the mipmap levels that Unity has requested or that you have set manually.\n\nFor example, if Unity does not load a Texture at full resolution because it is far away or its requested mipmap level is greater than 0,  Unity reduces the `desiredTextureMemory` value to match the total memory needed.\n\nThe `desiredTextureMemory` value can be greater than the `targetTextureMemory` value.\n                \r\n         */\r\n        static readonly desiredTextureMemory: number\r\n        /** The total amount of Texture memory that Unity allocates to the Textures in the scene after it applies the and finishes loading Textures. `targetTextureMemory`also takes mipmap streaming settings into account. This value only includes instances of Texture2D and CubeMap Textures. It does not include any other Texture types, or 2D and CubeMap Textures that Unity creates internally.\r\n         */\r\n        static readonly targetTextureMemory: number\r\n        /** The amount of memory that all Textures in the scene use.\r\n         */\r\n        static readonly currentTextureMemory: number\r\n        /** The amount of memory Unity allocates for non-streaming Textures in the scene. This only includes instances of Texture2D and CubeMap Textures. This does not include any other Texture types, or 2D and CubeMap Textures that Unity creates internally.\r\n         */\r\n        static readonly nonStreamingTextureMemory: number\r\n        /** How many times has a Texture been uploaded due to Texture mipmap streaming.\r\n         */\r\n        static readonly streamingMipmapUploadCount: number\r\n        /** Number of renderers registered with the Texture streaming system.\r\n         */\r\n        static readonly streamingRendererCount: number\r\n        /** Number of streaming Textures.\r\n         */\r\n        static readonly streamingTextureCount: number\r\n        /** The number of non-streaming Textures in the scene. This includes instances of Texture2D and CubeMap Textures. This does not include any other Texture types, or 2D and CubeMap Textures that Unity creates internally.\r\n         */\r\n        static readonly nonStreamingTextureCount: number\r\n        /** Number of streaming Textures with outstanding mipmaps to be loaded.\r\n         */\r\n        static readonly streamingTexturePendingLoadCount: number\r\n        /** Number of streaming Textures with mipmaps currently loading.\r\n         */\r\n        static readonly streamingTextureLoadingCount: number\r\n        /** Force streaming Textures to load all mipmap levels.\r\n         */\r\n        static streamingTextureForceLoadAll: boolean\r\n        /** This property forces the streaming Texture system to discard all unused mipmaps instead of caching them until the Texture is exceeded. This is useful when you profile or write tests to keep a predictable set of Textures in memory.\r\n         */\r\n        static streamingTextureDiscardUnusedMips: boolean\r\n        /** Allow Unity internals to perform Texture creation on any thread (rather than the dedicated render thread).\r\n         */\r\n        static allowThreadedTextureCreation: boolean\r\n        /** Can be used with Texture constructors that take a mip count to indicate that all mips should be generated.  The value of this field is -1.\r\n         */\r\n        static readonly GenerateAllMips: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum, Array, Object as Object1 } from \"System\";\r\n    /** Class that represents textures in C# code.\r\n     */\r\n    class Texture2D extends Texture {\r\n        constructor(width: number, height: number, format: any, mipCount: number, flags: any)\r\n        constructor(width: number, height: number, textureFormat: any, mipCount: number, linear: boolean)\r\n        constructor(width: number, height: number, textureFormat: any, mipChain: boolean, linear: boolean)\r\n        constructor(width: number, height: number, format: any, flags: any)\r\n        constructor(width: number, height: number, format: any, flags: any)\r\n        constructor(width: number, height: number, textureFormat: any, mipChain: boolean)\r\n        constructor(width: number, height: number)\r\n        /** Compress texture into DXT format.\r\n         */\r\n        Compress(highQuality: boolean): void\r\n        ClearRequestedMipmapLevel(): void\r\n        IsRequestedMipmapLevelLoaded(): boolean\r\n        ClearMinimumMipmapLevel(): void\r\n        /** Updates Unity texture to use different native texture object.\r\n         * @param nativeTex Native 2D texture object.\r\n         */\r\n        UpdateExternalTexture(nativeTex: any): void\r\n        GetRawTextureData(): Array<jsb.byte>\r\n        /** Get a block of pixel colors.\r\n         * @param x The x position of the pixel array to fetch.\r\n         * @param y The y position of the pixel array to fetch.\r\n         * @param blockWidth The width length of the pixel array to fetch.\r\n         * @param blockHeight The height length of the pixel array to fetch.\r\n         * @param miplevel The mipmap level to fetch the pixels. Defaults to zero, and is\n        optional.\r\n         * @returns The array of pixels in the texture that have been selected. \r\n         */\r\n        GetPixels(x: number, y: number, blockWidth: number, blockHeight: number, miplevel: number): Array<Color>\r\n        GetPixels(x: number, y: number, blockWidth: number, blockHeight: number): Array<Color>\r\n        /** Get the pixel colors from the texture.\r\n         * @param miplevel The mipmap level to fetch the pixels from. Defaults to zero.\r\n         * @returns The array of all pixels in the mipmap level of the texture. \r\n         */\r\n        GetPixels(miplevel: number): Array<Color>\r\n        GetPixels(): Array<Color>\r\n        /** Get a block of pixel colors in Color32 format.\r\n         */\r\n        GetPixels32(miplevel: number): Array<Color32>\r\n        GetPixels32(): Array<Color32>\r\n        /** Packs multiple Textures into a texture atlas.\r\n         * @param textures Array of textures to pack into the atlas.\r\n         * @param padding Padding in pixels between the packed textures.\r\n         * @param maximumAtlasSize Maximum size of the resulting texture.\r\n         * @param makeNoLongerReadable Should the texture be marked as no longer readable?\r\n         * @returns An array of rectangles containing the UV coordinates in the atlas for each input texture, or null if packing fails. \r\n         */\r\n        PackTextures(textures: Array<Texture2D>, padding: number, maximumAtlasSize: number, makeNoLongerReadable: boolean): Array<Rect>\r\n        PackTextures(textures: Array<Texture2D>, padding: number, maximumAtlasSize: number): Array<Rect>\r\n        PackTextures(textures: Array<Texture2D>, padding: number): Array<Rect>\r\n        SetPixel(x: number, y: number, color: Color, mipLevel: number): void\r\n        /** Sets pixel color at coordinates (x,y).\r\n         */\r\n        SetPixel(x: number, y: number, color: Color): void\r\n        /** Set a block of pixel colors.\r\n         */\r\n        SetPixels(x: number, y: number, blockWidth: number, blockHeight: number, colors: Array<Color>, miplevel: number): void\r\n        SetPixels(x: number, y: number, blockWidth: number, blockHeight: number, colors: Array<Color>): void\r\n        /** Set a block of pixel colors.\r\n         * @param colors The array of pixel colours to assign (a 2D image flattened to a 1D array).\r\n         * @param miplevel The mip level of the texture to write to.\r\n         */\r\n        SetPixels(colors: Array<Color>, miplevel: number): void\r\n        SetPixels(colors: Array<Color>): void\r\n        GetPixel(x: number, y: number, mipLevel: number): Color\r\n        /** Returns pixel color at coordinates (x, y).\r\n         */\r\n        GetPixel(x: number, y: number): Color\r\n        GetPixelBilinear(u: number, v: number, mipLevel: number): Color\r\n        /** Returns filtered pixel color at normalized coordinates (u, v).\r\n         */\r\n        GetPixelBilinear(u: number, v: number): Color\r\n        /** Fills texture pixels with raw preformatted data.\r\n         * @param data Raw data array to initialize texture pixels with.\r\n         * @param size Size of data in bytes.\r\n         */\r\n        LoadRawTextureData(data: any, size: number): void\r\n        /** Fills texture pixels with raw preformatted data.\r\n         * @param data Raw data array to initialize texture pixels with.\r\n         * @param size Size of data in bytes.\r\n         */\r\n        LoadRawTextureData(data: Array<jsb.byte>): void\r\n        /** Actually apply all previous SetPixel and SetPixels changes.\r\n         * @param updateMipmaps When set to true, mipmap levels are recalculated.\r\n         * @param makeNoLongerReadable When set to true, system memory copy of a texture is released.\r\n         */\r\n        Apply(updateMipmaps: boolean, makeNoLongerReadable: boolean): void\r\n        Apply(updateMipmaps: boolean): void\r\n        Apply(): void\r\n        /** Resizes the texture.\r\n         */\r\n        Resize(width: number, height: number, format: any, hasMipMap: boolean): boolean\r\n        Resize(width: number, height: number, format: any, hasMipMap: boolean): boolean\r\n        /** Resizes the texture.\r\n         */\r\n        Resize(width: number, height: number): boolean\r\n        /** Read pixels from screen into the saved texture data.\r\n         * @param source Rectangular region of the view to read from. Pixels are read from current render target.\r\n         * @param destX Horizontal pixel position in the texture to place the pixels that are read.\r\n         * @param destY Vertical pixel position in the texture to place the pixels that are read.\r\n         * @param recalculateMipMaps Should the texture's mipmaps be recalculated after reading?\r\n         */\r\n        ReadPixels(source: Rect, destX: number, destY: number, recalculateMipMaps: boolean): void\r\n        ReadPixels(source: Rect, destX: number, destY: number): void\r\n        /** Set a block of pixel colors.\r\n         */\r\n        SetPixels32(x: number, y: number, blockWidth: number, blockHeight: number, colors: Array<Color32>, miplevel: number): void\r\n        SetPixels32(x: number, y: number, blockWidth: number, blockHeight: number, colors: Array<Color32>): void\r\n        /** Set a block of pixel colors.\r\n         */\r\n        SetPixels32(colors: Array<Color32>, miplevel: number): void\r\n        SetPixels32(colors: Array<Color32>): void\r\n        /** Encodes the specified texture in TGA format.\r\n         * @param tex The texture to encode.\r\n         */\r\n        EncodeToTGA(): Array<jsb.byte>\r\n        /** Encodes this texture into PNG format.\r\n         * @param tex The texture to convert.\r\n         */\r\n        EncodeToPNG(): Array<jsb.byte>\r\n        /** Encodes this texture into JPG format.\r\n         * @param tex Text texture to convert.\r\n         * @param quality JPG quality to encode with, 1..100 (default 75).\r\n         */\r\n        EncodeToJPG(quality: number): Array<jsb.byte>\r\n        /** Encodes this texture into JPG format.\r\n         * @param tex Text texture to convert.\r\n         * @param quality JPG quality to encode with, 1..100 (default 75).\r\n         */\r\n        EncodeToJPG(): Array<jsb.byte>\r\n        EncodeToEXR(flags: any): Array<jsb.byte>\r\n        EncodeToEXR(): Array<jsb.byte>\r\n        /** Loads PNG/JPG (or supported format) image byte array into a texture.\r\n         * @param data The byte array containing the image data to load.\r\n         * @param markNonReadable Set to false by default, pass true to optionally mark the texture as non-readable.\r\n         * @param tex The texture to load the image into.\r\n         * @returns Returns true if the data can be loaded, false otherwise. \r\n         */\r\n        LoadImage(data: Array<jsb.byte>, markNonReadable: boolean): boolean\r\n        LoadImage(data: Array<jsb.byte>): boolean\r\n        /** Creates a Unity Texture out of an externally created native texture object.\r\n         * @param nativeTex Native 2D texture object.\r\n         * @param width Width of texture in pixels.\r\n         * @param height Height of texture in pixels.\r\n         * @param format Format of underlying texture object.\r\n         * @param mipmap Does the texture have mipmaps?\r\n         * @param linear Is texture using linear color space?\r\n         */\r\n        static CreateExternalTexture(width: number, height: number, format: any, mipChain: boolean, linear: boolean, nativeTex: any): Texture2D\r\n        static GenerateAtlas(sizes: Array<Vector2>, padding: number, atlasSize: number, results: any): boolean\r\n        /** The format of the pixel data in the texture (Read Only).\r\n         */\r\n        readonly format: any\r\n        /** Gets a small Texture with all white pixels.\r\n         */\r\n        static readonly whiteTexture: Texture2D\r\n        /** Gets a small Texture with all black pixels.\r\n         */\r\n        static readonly blackTexture: Texture2D\r\n        /** Gets a small Texture with all red pixels.\r\n         */\r\n        static readonly redTexture: Texture2D\r\n        /** Gets a small Texture with all gray pixels.\r\n         */\r\n        static readonly grayTexture: Texture2D\r\n        /** Gets a small Texture with all gray pixels.\r\n         */\r\n        static readonly linearGrayTexture: Texture2D\r\n        /** Gets a small Texture with pixels that represent surface normal vectors at a neutral position.\r\n         */\r\n        static readonly normalTexture: Texture2D\r\n        /** Returns true if the Read/Write Enabled checkbox was checked when the texture was imported; otherwise returns false. For a dynamic Texture created from script, always returns true. For additional information, see TextureImporter.isReadable.\r\n         */\r\n        readonly isReadable: boolean\r\n        /** Returns true if the VTOnly checkbox was checked when the texture was imported; otherwise returns false. For additional information, see TextureImporter.vtOnly.\r\n         */\r\n        readonly vtOnly: boolean\r\n        /** Determines whether mipmap streaming is enabled for this Texture.\r\n         */\r\n        readonly streamingMipmaps: boolean\r\n        /** Sets the relative priority for this Texture when reducing memory size to fit within the memory budget.\r\n         */\r\n        readonly streamingMipmapsPriority: number\r\n        /** The mipmap level to load.\r\n         */\r\n        requestedMipmapLevel: number\r\n        /** Restricts the mipmap streaming system to a minimum mip level for this Texture.\r\n         */\r\n        minimumMipmapLevel: number\r\n        /** The mipmap level calculated by the streaming system, which takes into account the streaming Cameras and the location of the objects containing this Texture. This is unaffected by requestedMipmapLevel or minimumMipmapLevel.\r\n         */\r\n        readonly calculatedMipmapLevel: number\r\n        /** The mipmap level that the streaming system would load before memory budgets are applied.\r\n         */\r\n        readonly desiredMipmapLevel: number\r\n        /** The mipmap level that the mipmap streaming system is in the process of loading.\r\n         */\r\n        readonly loadingMipmapLevel: number\r\n        /** The mipmap level that is currently loaded by the streaming system.\r\n         */\r\n        readonly loadedMipmapLevel: number\r\n        /** Indicates whether this texture was imported with TextureImporter.alphaIsTransparency enabled. This setting is available only in the Editor scripts. Note that changing this setting will have no effect; it must be enabled in TextureImporter instead.\r\n         */\r\n        alphaIsTransparency: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum, Array, Object as Object1 } from \"System\";\r\n    /** The material class.\r\n     */\r\n    class Material extends Object {\r\n        constructor(shader: any)\r\n        constructor(source: Material)\r\n        /** Checks if material's shader has a property of a given name.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        HasProperty(nameID: number): boolean\r\n        /** Checks if material's shader has a property of a given name.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        HasProperty(name: string): boolean\r\n        /** Enables a local shader keyword for this material.\r\n         * @param keyword The name of the local shader keyword to enable.\r\n         */\r\n        EnableKeyword(keyword: string): void\r\n        /** Disables a local shader keyword for this material.\r\n         * @param keyword The name of the local shader keyword to disable.\r\n         */\r\n        DisableKeyword(keyword: string): void\r\n        /** Checks whether a local shader keyword is enabled for this material.\r\n         * @param keyword The name of the local shader keyword to check.\r\n         * @returns Returns true if the given local shader keyword is enabled for this material. Otherwise, returns false. \r\n         */\r\n        IsKeywordEnabled(keyword: string): boolean\r\n        /** Enables or disables a Shader pass on a per-Material level.\r\n         * @param passName Shader pass name (case insensitive).\r\n         * @param enabled Flag indicating whether this Shader pass should be enabled.\r\n         */\r\n        SetShaderPassEnabled(passName: string, enabled: boolean): void\r\n        /** Checks whether a given Shader pass is enabled on this Material.\r\n         * @param passName Shader pass name (case insensitive).\r\n         * @returns True if the Shader pass is enabled. \r\n         */\r\n        GetShaderPassEnabled(passName: string): boolean\r\n        /** Returns the name of the shader pass at index pass.\r\n         */\r\n        GetPassName(pass: number): string\r\n        /** Returns the index of the pass passName.\r\n         */\r\n        FindPass(passName: string): number\r\n        /** Sets an override tag/value on the material.\r\n         * @param tag Name of the tag to set.\r\n         * @param val Name of the value to set. Empty string to clear the override flag.\r\n         */\r\n        SetOverrideTag(tag: string, val: string): void\r\n        /** Get the value of material's shader tag.\r\n         */\r\n        GetTag(tag: string, searchFallbacks: boolean, defaultValue: string): string\r\n        /** Get the value of material's shader tag.\r\n         */\r\n        GetTag(tag: string, searchFallbacks: boolean): string\r\n        /** Interpolate properties between two materials.\r\n         */\r\n        Lerp(start: Material, end: Material, t: number): void\r\n        /** Activate the given pass for rendering.\r\n         * @param pass Shader pass number to setup.\r\n         * @returns If false is returned, no rendering should be done. \r\n         */\r\n        SetPass(pass: number): boolean\r\n        /** Copy properties from other material into this material.\r\n         */\r\n        CopyPropertiesFromMaterial(mat: Material): void\r\n        ComputeCRC(): number\r\n        GetTexturePropertyNames(outNames: any): void\r\n        GetTexturePropertyNames(): Array<string>\r\n        GetTexturePropertyNameIDs(outNames: any): void\r\n        GetTexturePropertyNameIDs(): Array<number>\r\n        /** Sets a named float value.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param value Float value to set.\r\n         * @param name Property name, e.g. \"_Glossiness\".\r\n         */\r\n        SetFloat(name: string, value: number): void\r\n        /** Sets a named float value.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param value Float value to set.\r\n         * @param name Property name, e.g. \"_Glossiness\".\r\n         */\r\n        SetFloat(nameID: number, value: number): void\r\n        /** Sets a named integer value.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param value Integer value to set.\r\n         * @param name Property name, e.g. \"_SrcBlend\".\r\n         */\r\n        SetInt(name: string, value: number): void\r\n        /** Sets a named integer value.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param value Integer value to set.\r\n         * @param name Property name, e.g. \"_SrcBlend\".\r\n         */\r\n        SetInt(nameID: number, value: number): void\r\n        /** Sets a named color value.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name, e.g. \"_Color\".\r\n         * @param value Color value to set.\r\n         */\r\n        SetColor(name: string, value: Color): void\r\n        /** Sets a named color value.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name, e.g. \"_Color\".\r\n         * @param value Color value to set.\r\n         */\r\n        SetColor(nameID: number, value: Color): void\r\n        /** Sets a named vector value.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name, e.g. \"_WaveAndDistance\".\r\n         * @param value Vector value to set.\r\n         */\r\n        SetVector(name: string, value: Vector4): void\r\n        /** Sets a named vector value.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name, e.g. \"_WaveAndDistance\".\r\n         * @param value Vector value to set.\r\n         */\r\n        SetVector(nameID: number, value: Vector4): void\r\n        /** Sets a named matrix for the shader.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name, e.g. \"_CubemapRotation\".\r\n         * @param value Matrix value to set.\r\n         */\r\n        SetMatrix(name: string, value: Matrix4x4): void\r\n        /** Sets a named matrix for the shader.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name, e.g. \"_CubemapRotation\".\r\n         * @param value Matrix value to set.\r\n         */\r\n        SetMatrix(nameID: number, value: Matrix4x4): void\r\n        /** Sets a named texture.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name, e.g. \"_MainTex\".\r\n         * @param value Texture to set.\r\n         * @param element Optional parameter that specifies the type of data to set from the RenderTexture.\r\n         */\r\n        SetTexture(name: string, value: any, element: any): void\r\n        /** Sets a named texture.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name, e.g. \"_MainTex\".\r\n         * @param value Texture to set.\r\n         * @param element Optional parameter that specifies the type of data to set from the RenderTexture.\r\n         */\r\n        SetTexture(nameID: number, value: any, element: any): void\r\n        /** Sets a named texture.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name, e.g. \"_MainTex\".\r\n         * @param value Texture to set.\r\n         * @param element Optional parameter that specifies the type of data to set from the RenderTexture.\r\n         */\r\n        SetTexture(name: string, value: Texture): void\r\n        /** Sets a named texture.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name, e.g. \"_MainTex\".\r\n         * @param value Texture to set.\r\n         * @param element Optional parameter that specifies the type of data to set from the RenderTexture.\r\n         */\r\n        SetTexture(nameID: number, value: Texture): void\r\n        /** Sets a named buffer value.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name.\r\n         * @param value The ComputeBuffer or GraphicsBuffer value to set.\r\n         */\r\n        SetBuffer(name: string, value: any): void\r\n        /** Sets a named buffer value.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name.\r\n         * @param value The ComputeBuffer or GraphicsBuffer value to set.\r\n         */\r\n        SetBuffer(nameID: number, value: any): void\r\n        /** Sets a named buffer value.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name.\r\n         * @param value The ComputeBuffer or GraphicsBuffer value to set.\r\n         */\r\n        SetBuffer(name: string, value: any): void\r\n        /** Sets a named buffer value.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name.\r\n         * @param value The ComputeBuffer or GraphicsBuffer value to set.\r\n         */\r\n        SetBuffer(nameID: number, value: any): void\r\n        /** Sets a ComputeBuffer or GraphicsBuffer as a named constant buffer for the material.\r\n         * @param name The name of the constant buffer to override.\r\n         * @param value The ComputeBuffer to override the constant buffer values with, or null to remove binding.\r\n         * @param offset Offset in bytes from the beginning of the buffer to bind. Must be a multiple of SystemInfo.constantBufferOffsetAlignment, or 0 if that value is 0.\r\n         * @param size The number of bytes to bind.\r\n         * @param nameID The shader property ID of the constant buffer to override.\r\n         */\r\n        SetConstantBuffer(name: string, value: any, offset: number, size: number): void\r\n        /** Sets a ComputeBuffer or GraphicsBuffer as a named constant buffer for the material.\r\n         * @param name The name of the constant buffer to override.\r\n         * @param value The ComputeBuffer to override the constant buffer values with, or null to remove binding.\r\n         * @param offset Offset in bytes from the beginning of the buffer to bind. Must be a multiple of SystemInfo.constantBufferOffsetAlignment, or 0 if that value is 0.\r\n         * @param size The number of bytes to bind.\r\n         * @param nameID The shader property ID of the constant buffer to override.\r\n         */\r\n        SetConstantBuffer(nameID: number, value: any, offset: number, size: number): void\r\n        /** Sets a ComputeBuffer or GraphicsBuffer as a named constant buffer for the material.\r\n         * @param name The name of the constant buffer to override.\r\n         * @param value The ComputeBuffer to override the constant buffer values with, or null to remove binding.\r\n         * @param offset Offset in bytes from the beginning of the buffer to bind. Must be a multiple of SystemInfo.constantBufferOffsetAlignment, or 0 if that value is 0.\r\n         * @param size The number of bytes to bind.\r\n         * @param nameID The shader property ID of the constant buffer to override.\r\n         */\r\n        SetConstantBuffer(name: string, value: any, offset: number, size: number): void\r\n        /** Sets a ComputeBuffer or GraphicsBuffer as a named constant buffer for the material.\r\n         * @param name The name of the constant buffer to override.\r\n         * @param value The ComputeBuffer to override the constant buffer values with, or null to remove binding.\r\n         * @param offset Offset in bytes from the beginning of the buffer to bind. Must be a multiple of SystemInfo.constantBufferOffsetAlignment, or 0 if that value is 0.\r\n         * @param size The number of bytes to bind.\r\n         * @param nameID The shader property ID of the constant buffer to override.\r\n         */\r\n        SetConstantBuffer(nameID: number, value: any, offset: number, size: number): void\r\n        SetFloatArray(name: string, values: any): void\r\n        SetFloatArray(nameID: number, values: any): void\r\n        /** Sets a float array property.\r\n         * @param name Property name.\r\n         * @param nameID Property name ID. Use Shader.PropertyToID to get this ID.\r\n         * @param values Array of values to set.\r\n         */\r\n        SetFloatArray(name: string, values: Array<number>): void\r\n        /** Sets a float array property.\r\n         * @param name Property name.\r\n         * @param nameID Property name ID. Use Shader.PropertyToID to get this ID.\r\n         * @param values Array of values to set.\r\n         */\r\n        SetFloatArray(nameID: number, values: Array<number>): void\r\n        SetColorArray(name: string, values: any): void\r\n        SetColorArray(nameID: number, values: any): void\r\n        /** Sets a color array property.\r\n         * @param name Property name.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param values Array of values to set.\r\n         */\r\n        SetColorArray(name: string, values: Array<Color>): void\r\n        /** Sets a color array property.\r\n         * @param name Property name.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param values Array of values to set.\r\n         */\r\n        SetColorArray(nameID: number, values: Array<Color>): void\r\n        SetVectorArray(name: string, values: any): void\r\n        SetVectorArray(nameID: number, values: any): void\r\n        /** Sets a vector array property.\r\n         * @param name Property name.\r\n         * @param values Array of values to set.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         */\r\n        SetVectorArray(name: string, values: Array<Vector4>): void\r\n        /** Sets a vector array property.\r\n         * @param name Property name.\r\n         * @param values Array of values to set.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         */\r\n        SetVectorArray(nameID: number, values: Array<Vector4>): void\r\n        SetMatrixArray(name: string, values: any): void\r\n        SetMatrixArray(nameID: number, values: any): void\r\n        /** Sets a matrix array property.\r\n         * @param name Property name.\r\n         * @param values Array of values to set.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         */\r\n        SetMatrixArray(name: string, values: Array<Matrix4x4>): void\r\n        /** Sets a matrix array property.\r\n         * @param name Property name.\r\n         * @param values Array of values to set.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         */\r\n        SetMatrixArray(nameID: number, values: Array<Matrix4x4>): void\r\n        /** Get a named float value.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetFloat(name: string): number\r\n        /** Get a named float value.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetFloat(nameID: number): number\r\n        /** Get a named integer value.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetInt(name: string): number\r\n        /** Get a named integer value.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetInt(nameID: number): number\r\n        /** Get a named color value.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetColor(name: string): Color\r\n        /** Get a named color value.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetColor(nameID: number): Color\r\n        /** Get a named vector value.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetVector(name: string): Vector4\r\n        /** Get a named vector value.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetVector(nameID: number): Vector4\r\n        /** Get a named matrix value from the shader.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetMatrix(name: string): Matrix4x4\r\n        /** Get a named matrix value from the shader.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetMatrix(nameID: number): Matrix4x4\r\n        /** Get a named texture.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetTexture(name: string): Texture\r\n        /** Get a named texture.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetTexture(nameID: number): Texture\r\n        GetFloatArray(name: string, values: any): void\r\n        GetFloatArray(nameID: number, values: any): void\r\n        /** Get a named float array.\r\n         * @param name The name of the property.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         */\r\n        GetFloatArray(name: string): Array<number>\r\n        /** Get a named float array.\r\n         * @param name The name of the property.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         */\r\n        GetFloatArray(nameID: number): Array<number>\r\n        GetColorArray(name: string, values: any): void\r\n        GetColorArray(nameID: number, values: any): void\r\n        /** Get a named color array.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetColorArray(name: string): Array<Color>\r\n        /** Get a named color array.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetColorArray(nameID: number): Array<Color>\r\n        GetVectorArray(name: string, values: any): void\r\n        GetVectorArray(nameID: number, values: any): void\r\n        /** Get a named vector array.\r\n         * @param name The name of the property.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         */\r\n        GetVectorArray(name: string): Array<Vector4>\r\n        /** Get a named vector array.\r\n         * @param name The name of the property.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         */\r\n        GetVectorArray(nameID: number): Array<Vector4>\r\n        GetMatrixArray(name: string, values: any): void\r\n        GetMatrixArray(nameID: number, values: any): void\r\n        /** Get a named matrix array.\r\n         * @param name The name of the property.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         */\r\n        GetMatrixArray(name: string): Array<Matrix4x4>\r\n        /** Get a named matrix array.\r\n         * @param name The name of the property.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         */\r\n        GetMatrixArray(nameID: number): Array<Matrix4x4>\r\n        /** Sets the placement offset of texture propertyName.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name, for example: \"_MainTex\".\r\n         * @param value Texture placement offset.\r\n         */\r\n        SetTextureOffset(name: string, value: Vector2): void\r\n        /** Sets the placement offset of texture propertyName.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name, for example: \"_MainTex\".\r\n         * @param value Texture placement offset.\r\n         */\r\n        SetTextureOffset(nameID: number, value: Vector2): void\r\n        /** Sets the placement scale of texture propertyName.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name, e.g. \"_MainTex\".\r\n         * @param value Texture placement scale.\r\n         */\r\n        SetTextureScale(name: string, value: Vector2): void\r\n        /** Sets the placement scale of texture propertyName.\r\n         * @param nameID Property name ID, use Shader.PropertyToID to get it.\r\n         * @param name Property name, e.g. \"_MainTex\".\r\n         * @param value Texture placement scale.\r\n         */\r\n        SetTextureScale(nameID: number, value: Vector2): void\r\n        /** Gets the placement offset of texture propertyName.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetTextureOffset(name: string): Vector2\r\n        /** Gets the placement offset of texture propertyName.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetTextureOffset(nameID: number): Vector2\r\n        /** Gets the placement scale of texture propertyName.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetTextureScale(name: string): Vector2\r\n        /** Gets the placement scale of texture propertyName.\r\n         * @param nameID The name ID of the property retrieved by Shader.PropertyToID.\r\n         * @param name The name of the property.\r\n         */\r\n        GetTextureScale(nameID: number): Vector2\r\n        /** The shader used by the material.\r\n         */\r\n        shader: any\r\n        /** The main color of the Material.\r\n         */\r\n        color: Color\r\n        /** The main texture.\r\n         */\r\n        mainTexture: Texture\r\n        /** The offset of the main texture.\r\n         */\r\n        mainTextureOffset: Vector2\r\n        /** The scale of the main texture.\r\n         */\r\n        mainTextureScale: Vector2\r\n        /** Render queue of this material.\r\n         */\r\n        renderQueue: number\r\n        /** Defines how the material should interact with lightmaps and lightprobes.\r\n         */\r\n        globalIlluminationFlags: any\r\n        /** Gets and sets whether the Double Sided Global Illumination setting is enabled for this material.\r\n         */\r\n        doubleSidedGI: boolean\r\n        /** Gets and sets whether GPU instancing is enabled for this material.\r\n         */\r\n        enableInstancing: boolean\r\n        /** How many passes are in this material (Read Only).\r\n         */\r\n        readonly passCount: number\r\n        /** An array containing the names of the local shader keywords that are currently enabled for this material.\r\n         */\r\n        shaderKeywords: Array<string>\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Object as Object1 } from \"System\";\r\n    /** Provides an interface to get time information from Unity.\r\n     */\r\n    class Time extends Object1 {\r\n        constructor()\r\n        /** The time at the beginning of this frame (Read Only).\r\n         */\r\n        static readonly time: number\r\n        /** The double precision time at the beginning of this frame (Read Only). This is the time in seconds since the start of the game.\r\n         */\r\n        static readonly timeAsDouble: number\r\n        /** The time since this frame started (Read Only). This is the time in seconds since the last non-additive scene has finished loading.\r\n         */\r\n        static readonly timeSinceLevelLoad: number\r\n        /** The double precision time since this frame started (Read Only). This is the time in seconds since the last non-additive scene has finished loading.\r\n         */\r\n        static readonly timeSinceLevelLoadAsDouble: number\r\n        /** The interval in seconds from the last frame to the current one (Read Only).\r\n         */\r\n        static readonly deltaTime: number\r\n        /** The time since the last MonoBehaviour.FixedUpdate started (Read Only). This is the time in seconds since the start of the game.\r\n         */\r\n        static readonly fixedTime: number\r\n        /** The double precision time since the last MonoBehaviour.FixedUpdate started (Read Only). This is the time in seconds since the start of the game.\r\n         */\r\n        static readonly fixedTimeAsDouble: number\r\n        /** The timeScale-independent time for this frame (Read Only). This is the time in seconds since the start of the game.\r\n         */\r\n        static readonly unscaledTime: number\r\n        /** The double precision timeScale-independent time for this frame (Read Only). This is the time in seconds since the start of the game.\r\n         */\r\n        static readonly unscaledTimeAsDouble: number\r\n        /** The timeScale-independent time at the beginning of the last MonoBehaviour.FixedUpdate phase (Read Only). This is the time in seconds since the start of the game.\r\n         */\r\n        static readonly fixedUnscaledTime: number\r\n        /** The double precision timeScale-independent time at the beginning of the last MonoBehaviour.FixedUpdate (Read Only). This is the time in seconds since the start of the game.\r\n         */\r\n        static readonly fixedUnscaledTimeAsDouble: number\r\n        /** The timeScale-independent interval in seconds from the last frame to the current one (Read Only).\r\n         */\r\n        static readonly unscaledDeltaTime: number\r\n        /** The timeScale-independent interval in seconds from the last MonoBehaviour.FixedUpdate phase to the current one (Read Only).\r\n         */\r\n        static readonly fixedUnscaledDeltaTime: number\r\n        /** The interval in seconds at which physics and other fixed frame rate updates (like MonoBehaviour's MonoBehaviour.FixedUpdate) are performed.\r\n         */\r\n        static fixedDeltaTime: number\r\n        /** The maximum value of Time.deltaTime in any given frame. This is a time in seconds that limits the increase of Time.time between two frames.\r\n         */\r\n        static maximumDeltaTime: number\r\n        /** A smoothed out Time.deltaTime (Read Only).\r\n         */\r\n        static readonly smoothDeltaTime: number\r\n        /** The maximum time a frame can spend on particle updates. If the frame takes longer than this, then updates are split into multiple smaller updates.\r\n         */\r\n        static maximumParticleDeltaTime: number\r\n        /** The scale at which time passes.\r\n         */\r\n        static timeScale: number\r\n        /** The total number of frames since the start of the game (Read Only).\r\n         */\r\n        static readonly frameCount: number\r\n        static readonly renderedFrameCount: number\r\n        /** The real time in seconds since the game started (Read Only).\r\n         */\r\n        static readonly realtimeSinceStartup: number\r\n        /** The real time in seconds since the game started (Read Only). Double precision version of Time.realtimeSinceStartup. \r\n         */\r\n        static readonly realtimeSinceStartupAsDouble: number\r\n        /** Slows your application’s playback time to allow Unity to save screenshots in between frames.\r\n         */\r\n        static captureDeltaTime: number\r\n        /** The reciprocal of Time.captureDeltaTime.\r\n         */\r\n        static captureFramerate: number\r\n        /** Returns true if called inside a fixed time step callback (like MonoBehaviour's MonoBehaviour.FixedUpdate), otherwise returns false.\r\n         */\r\n        static readonly inFixedTimeStep: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Object as Object1, ValueType } from \"System\";\r\n    /** Easily generate random data for games.\r\n     */\r\n    abstract class Random extends Object1 {\r\n        /** Initializes the random number generator state with a seed.\r\n         * @param seed Seed used to initialize the random number generator.\r\n         */\r\n        static InitState(seed: number): void\r\n        /** Returns a random float within [minInclusive..maxInclusive] (range is inclusive).\r\n         */\r\n        static Range(minInclusive: number, maxInclusive: number): number\r\n        /** Return a random int within [minInclusive..maxExclusive) (Read Only).\r\n         */\r\n        static Range(minInclusive: number, maxExclusive: number): number\r\n        /** Generates a random color from HSV and alpha ranges.\r\n         * @param hueMin Minimum hue [0..1].\r\n         * @param hueMax Maximum hue [0..1].\r\n         * @param saturationMin Minimum saturation [0..1].\r\n         * @param saturationMax Maximum saturation [0..1].\r\n         * @param valueMin Minimum value [0..1].\r\n         * @param valueMax Maximum value [0..1].\r\n         * @param alphaMin Minimum alpha [0..1].\r\n         * @param alphaMax Maximum alpha [0..1].\r\n         * @returns A random color with HSV and alpha values in the (inclusive) input ranges. Values for each component are derived via linear interpolation of value. \r\n         */\r\n        static ColorHSV(hueMin: number, hueMax: number, saturationMin: number, saturationMax: number, valueMin: number, valueMax: number, alphaMin: number, alphaMax: number): Color\r\n        /** Generates a random color from HSV and alpha ranges.\r\n         * @param hueMin Minimum hue [0..1].\r\n         * @param hueMax Maximum hue [0..1].\r\n         * @param saturationMin Minimum saturation [0..1].\r\n         * @param saturationMax Maximum saturation [0..1].\r\n         * @param valueMin Minimum value [0..1].\r\n         * @param valueMax Maximum value [0..1].\r\n         * @param alphaMin Minimum alpha [0..1].\r\n         * @param alphaMax Maximum alpha [0..1].\r\n         * @returns A random color with HSV and alpha values in the (inclusive) input ranges. Values for each component are derived via linear interpolation of value. \r\n         */\r\n        static ColorHSV(hueMin: number, hueMax: number, saturationMin: number, saturationMax: number, valueMin: number, valueMax: number): Color\r\n        /** Generates a random color from HSV and alpha ranges.\r\n         * @param hueMin Minimum hue [0..1].\r\n         * @param hueMax Maximum hue [0..1].\r\n         * @param saturationMin Minimum saturation [0..1].\r\n         * @param saturationMax Maximum saturation [0..1].\r\n         * @param valueMin Minimum value [0..1].\r\n         * @param valueMax Maximum value [0..1].\r\n         * @param alphaMin Minimum alpha [0..1].\r\n         * @param alphaMax Maximum alpha [0..1].\r\n         * @returns A random color with HSV and alpha values in the (inclusive) input ranges. Values for each component are derived via linear interpolation of value. \r\n         */\r\n        static ColorHSV(hueMin: number, hueMax: number, saturationMin: number, saturationMax: number): Color\r\n        /** Generates a random color from HSV and alpha ranges.\r\n         * @param hueMin Minimum hue [0..1].\r\n         * @param hueMax Maximum hue [0..1].\r\n         * @param saturationMin Minimum saturation [0..1].\r\n         * @param saturationMax Maximum saturation [0..1].\r\n         * @param valueMin Minimum value [0..1].\r\n         * @param valueMax Maximum value [0..1].\r\n         * @param alphaMin Minimum alpha [0..1].\r\n         * @param alphaMax Maximum alpha [0..1].\r\n         * @returns A random color with HSV and alpha values in the (inclusive) input ranges. Values for each component are derived via linear interpolation of value. \r\n         */\r\n        static ColorHSV(hueMin: number, hueMax: number): Color\r\n        static ColorHSV(): Color\r\n        /** Gets or sets the full internal state of the random number generator.\r\n         */\r\n        static state: any\r\n        /** Returns a random float within [0.0..1.0] (range is inclusive) (Read Only).\r\n         */\r\n        static readonly value: number\r\n        /** Returns a random point inside or on a sphere with radius 1.0 (Read Only).\r\n         */\r\n        static readonly insideUnitSphere: Vector3\r\n        /** Returns a random point inside or on a circle with radius 1.0 (Read Only).\r\n         */\r\n        static readonly insideUnitCircle: Vector2\r\n        /** Returns a random point on the surface of a sphere with radius 1.0 (Read Only).\r\n         */\r\n        static readonly onUnitSphere: Vector3\r\n        /** Returns a random rotation (Read Only).\r\n         */\r\n        static readonly rotation: Quaternion\r\n        /** Returns a random rotation with uniform distribution (Read Only).\r\n         */\r\n        static readonly rotationUniform: Quaternion\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array, Object as Object1, Enum } from \"System\";\r\n    /** Base class for all entities in Unity Scenes.\r\n     */\r\n    class GameObject extends Object {\r\n        constructor(name: string)\r\n        constructor(name: string, ...components: any[])\r\n        constructor()\r\n        /** Returns the component of Type type if the game object has one attached, null if it doesn't.\r\n         * @param type The type of Component to retrieve.\r\n         */\r\n        GetComponent<T extends Component>(type: { new(): T }): T\r\n        /** Returns the component with name type if the game object has one attached, null if it doesn't.\r\n         * @param type The type of Component to retrieve.\r\n         */\r\n        GetComponent(type: string): Component\r\n        /** Returns the component of Type type in the GameObject or any of its children using depth first search.\r\n         * @param type The type of Component to retrieve.\r\n         * @returns A component of the matching type, if found. \r\n         */\r\n        GetComponentInChildren<T extends Component>(type: { new(): T }, includeInactive: boolean): T\r\n        /** Returns the component of Type type in the GameObject or any of its children using depth first search.\r\n         * @param type The type of Component to retrieve.\r\n         * @returns A component of the matching type, if found. \r\n         */\r\n        GetComponentInChildren<T extends Component>(type: { new(): T }): T\r\n        /** Retrieves the component of Type type in the GameObject or any of its parents.\r\n         * @param type Type of component to find.\r\n         * @returns Returns a component if a component matching the type is found. Returns null otherwise. \r\n         */\r\n        GetComponentInParent(type: any, includeInactive: boolean): Component\r\n        /** Retrieves the component of Type type in the GameObject or any of its parents.\r\n         * @param type Type of component to find.\r\n         * @returns Returns a component if a component matching the type is found. Returns null otherwise. \r\n         */\r\n        GetComponentInParent<T extends Component>(type: { new(): T }): T\r\n        GetComponents(type: any, results: any): void\r\n        /** Returns all components of Type type in the GameObject.\r\n         * @param type The type of component to retrieve.\r\n         */\r\n        GetComponents<T extends Component>(type: { new(): T }): T[]\r\n        /** Returns all components of Type type in the GameObject or any of its children.\r\n         * @param type The type of Component to retrieve.\r\n         * @param includeInactive Should Components on inactive GameObjects be included in the found set?\r\n         */\r\n        GetComponentsInChildren<T extends Component>(type: { new(): T }, includeInactive: boolean): T[]\r\n        /** Returns all components of Type type in the GameObject or any of its children.\r\n         * @param type The type of Component to retrieve.\r\n         * @param includeInactive Should Components on inactive GameObjects be included in the found set?\r\n         */\r\n        GetComponentsInChildren<T extends Component>(type: { new(): T }): T[]\r\n        /** Returns all components of Type type in the GameObject or any of its parents.\r\n         * @param type The type of Component to retrieve.\r\n         * @param includeInactive Should inactive Components be included in the found set?\r\n         */\r\n        GetComponentsInParent<T extends Component>(type: { new(): T }, includeInactive: boolean): T[]\r\n        GetComponentsInParent<T extends Component>(type: { new(): T }): T[]\r\n        /** Gets the component of the specified type, if it exists.\r\n         * @param type The type of component to retrieve.\r\n         * @param component The output argument that will contain the component or null.\r\n         * @returns Returns true if the component is found, false otherwise. \r\n         */\r\n        TryGetComponent(type: any, component: jsb.Out<Component>): boolean\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour.\r\n         * @param methodName The name of the method to call.\r\n         * @param value An optional parameter value to pass to the called method.\r\n         * @param options Should an error be raised if the method doesn't exist on the target object?\r\n         */\r\n        SendMessageUpwards(methodName: string, value: Object1, options: any): void\r\n        SendMessageUpwards(methodName: string, options: any): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour.\r\n         * @param methodName The name of the method to call.\r\n         * @param value An optional parameter value to pass to the called method.\r\n         * @param options Should an error be raised if the method doesn't exist on the target object?\r\n         */\r\n        SendMessageUpwards(methodName: string, value: Object1): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour.\r\n         * @param methodName The name of the method to call.\r\n         * @param value An optional parameter value to pass to the called method.\r\n         * @param options Should an error be raised if the method doesn't exist on the target object?\r\n         */\r\n        SendMessageUpwards(methodName: string): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object.\r\n         * @param methodName The name of the method to call.\r\n         * @param value An optional parameter value to pass to the called method.\r\n         * @param options Should an error be raised if the method doesn't exist on the target object?\r\n         */\r\n        SendMessage(methodName: string, value: Object1, options: any): void\r\n        SendMessage(methodName: string, options: any): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object.\r\n         * @param methodName The name of the method to call.\r\n         * @param value An optional parameter value to pass to the called method.\r\n         * @param options Should an error be raised if the method doesn't exist on the target object?\r\n         */\r\n        SendMessage(methodName: string, value: Object1): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object.\r\n         * @param methodName The name of the method to call.\r\n         * @param value An optional parameter value to pass to the called method.\r\n         * @param options Should an error be raised if the method doesn't exist on the target object?\r\n         */\r\n        SendMessage(methodName: string): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object or any of its children.\r\n         */\r\n        BroadcastMessage(methodName: string, parameter: Object1, options: any): void\r\n        BroadcastMessage(methodName: string, options: any): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object or any of its children.\r\n         */\r\n        BroadcastMessage(methodName: string, parameter: Object1): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object or any of its children.\r\n         */\r\n        BroadcastMessage(methodName: string): void\r\n        /** Adds a component class of type componentType to the game object. C# Users can use a generic version.\r\n         */\r\n        AddComponent<T extends Component>(type: { new(): T }): T\r\n        /** ActivatesDeactivates the GameObject, depending on the given true or false/ value.\r\n         * @param value Activate or deactivate the object, where true activates the GameObject and false deactivates the GameObject.\r\n         */\r\n        SetActive(value: boolean): void\r\n        /** Is this game object tagged with tag ?\r\n         * @param tag The tag to compare.\r\n         */\r\n        CompareTag(tag: string): boolean\r\n        /** Creates a game object with a primitive mesh renderer and appropriate collider.\r\n         * @param type The type of primitive object to create.\r\n         */\r\n        static CreatePrimitive(type: PrimitiveType): GameObject\r\n        /** Returns one active GameObject tagged tag. Returns null if no GameObject was found.\r\n         * @param tag The tag to search for.\r\n         */\r\n        static FindWithTag(tag: string): GameObject\r\n        static FindGameObjectWithTag(tag: string): GameObject\r\n        /** Returns an array of active GameObjects tagged tag. Returns empty array if no GameObject was found.\r\n         * @param tag The name of the tag to search GameObjects for.\r\n         */\r\n        static FindGameObjectsWithTag(tag: string): Array<GameObject>\r\n        /** Finds a GameObject by name and returns it.\r\n         */\r\n        static Find(name: string): GameObject\r\n        /** The Transform attached to this GameObject.\r\n         */\r\n        readonly transform: Transform\r\n        /** The layer the game object is in.\r\n         */\r\n        layer: number\r\n        /** The local active state of this GameObject. (Read Only)\r\n         */\r\n        readonly activeSelf: boolean\r\n        /** Defines whether the GameObject is active in the Scene.\r\n         */\r\n        readonly activeInHierarchy: boolean\r\n        /** Gets and sets the GameObject's StaticEditorFlags.\r\n         */\r\n        isStatic: boolean\r\n        /** The tag of this game object.\r\n         */\r\n        tag: string\r\n        /** Scene that the GameObject is part of.\r\n         */\r\n        readonly scene: any\r\n        /** Scene culling mask Unity uses to determine which scene to render the GameObject in.\r\n         */\r\n        readonly sceneCullingMask: number\r\n        readonly gameObject: GameObject\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum, Array, ValueType, Object as Object1 } from \"System\";\r\n    /** A Camera is a device through which the player views the world.\r\n     */\r\n    class Camera extends Behaviour {\r\n        constructor()\r\n        Reset(): void\r\n        ResetTransparencySortSettings(): void\r\n        ResetAspect(): void\r\n        ResetCullingMatrix(): void\r\n        /** Make the camera render with shader replacement.\r\n         */\r\n        SetReplacementShader(shader: any, replacementTag: string): void\r\n        ResetReplacementShader(): void\r\n        GetGateFittedFieldOfView(): number\r\n        GetGateFittedLensShift(): Vector2\r\n        /** Sets the Camera to render to the chosen buffers of one or more RenderTextures.\r\n         * @param colorBuffer The RenderBuffer(s) to which color information will be rendered.\r\n         * @param depthBuffer The RenderBuffer to which depth information will be rendered.\r\n         */\r\n        SetTargetBuffers(colorBuffer: any, depthBuffer: any): void\r\n        /** Sets the Camera to render to the chosen buffers of one or more RenderTextures.\r\n         * @param colorBuffer The RenderBuffer(s) to which color information will be rendered.\r\n         * @param depthBuffer The RenderBuffer to which depth information will be rendered.\r\n         */\r\n        SetTargetBuffers(colorBuffer: Array<any>, depthBuffer: any): void\r\n        ResetWorldToCameraMatrix(): void\r\n        ResetProjectionMatrix(): void\r\n        /** Calculates and returns oblique near-plane projection matrix.\r\n         * @param clipPlane Vector4 that describes a clip plane.\r\n         * @returns Oblique near-plane projection matrix. \r\n         */\r\n        CalculateObliqueMatrix(clipPlane: Vector4): Matrix4x4\r\n        WorldToScreenPoint(position: Vector3, eye: any): Vector3\r\n        /** Transforms position from world space into screen space.\r\n         * @param eye Optional argument that can be used to specify which eye transform to use. Default is Mono.\r\n         */\r\n        WorldToScreenPoint(position: Vector3): Vector3\r\n        WorldToViewportPoint(position: Vector3, eye: any): Vector3\r\n        /** Transforms position from world space into viewport space.\r\n         * @param eye Optional argument that can be used to specify which eye transform to use. Default is Mono.\r\n         */\r\n        WorldToViewportPoint(position: Vector3): Vector3\r\n        ViewportToWorldPoint(position: Vector3, eye: any): Vector3\r\n        /** Transforms position from viewport space into world space.\r\n         * @param position The 3d vector in Viewport space.\r\n         * @returns The 3d vector in World space. \r\n         */\r\n        ViewportToWorldPoint(position: Vector3): Vector3\r\n        ScreenToWorldPoint(position: Vector3, eye: any): Vector3\r\n        /** Transforms a point from screen space into world space, where world space is defined as the coordinate system at the very top of your game's hierarchy.\r\n         * @param position A screen space position (often mouse x, y), plus a z position for depth (for example, a camera clipping plane).\r\n         * @param eye By default, Camera.MonoOrStereoscopicEye.Mono. Can be set to Camera.MonoOrStereoscopicEye.Left or Camera.MonoOrStereoscopicEye.Right for use in stereoscopic rendering (e.g., for VR).\r\n         * @returns The worldspace point created by converting the screen space point at the provided distance z from the camera plane. \r\n         */\r\n        ScreenToWorldPoint(position: Vector3): Vector3\r\n        /** Transforms position from screen space into viewport space.\r\n         */\r\n        ScreenToViewportPoint(position: Vector3): Vector3\r\n        /** Transforms position from viewport space into screen space.\r\n         */\r\n        ViewportToScreenPoint(position: Vector3): Vector3\r\n        ViewportPointToRay(pos: Vector3, eye: any): Ray\r\n        /** Returns a ray going from camera through a viewport point.\r\n         * @param eye Optional argument that can be used to specify which eye transform to use. Default is Mono.\r\n         */\r\n        ViewportPointToRay(pos: Vector3): Ray\r\n        ScreenPointToRay(pos: Vector3, eye: any): Ray\r\n        /** Returns a ray going from camera through a screen point.\r\n         * @param eye Optional argument that can be used to specify which eye transform to use. Default is Mono.\r\n         */\r\n        ScreenPointToRay(pos: Vector3): Ray\r\n        CalculateFrustumCorners(viewport: Rect, z: number, eye: any, outCorners: Array<Vector3>): void\r\n        GetStereoNonJitteredProjectionMatrix(eye: any): Matrix4x4\r\n        GetStereoViewMatrix(eye: any): Matrix4x4\r\n        CopyStereoDeviceProjectionMatrixToNonJittered(eye: any): void\r\n        GetStereoProjectionMatrix(eye: any): Matrix4x4\r\n        SetStereoProjectionMatrix(eye: any, matrix: Matrix4x4): void\r\n        ResetStereoProjectionMatrices(): void\r\n        SetStereoViewMatrix(eye: any, matrix: Matrix4x4): void\r\n        ResetStereoViewMatrices(): void\r\n        RenderToCubemap(cubemap: any, faceMask: number, stereoEye: any): boolean\r\n        /** Render into a static cubemap from this camera.\r\n         * @param cubemap The cube map to render to.\r\n         * @param faceMask A bitmask which determines which of the six faces are rendered to.\r\n         * @returns False if rendering fails, else true. \r\n         */\r\n        RenderToCubemap(cubemap: any, faceMask: number): boolean\r\n        /** Render into a cubemap from this camera.\r\n         * @param faceMask A bitfield indicating which cubemap faces should be rendered into.\r\n         * @param cubemap The texture to render to.\r\n         * @returns False if rendering fails, else true. \r\n         */\r\n        RenderToCubemap(cubemap: any, faceMask: number): boolean\r\n        RenderToCubemap(cubemap: any): boolean\r\n        RenderToCubemap(cubemap: any): boolean\r\n        Render(): void\r\n        /** Render the camera with shader replacement.\r\n         */\r\n        RenderWithShader(shader: any, replacementTag: string): void\r\n        RenderDontRestore(): void\r\n        SubmitRenderRequests(renderRequests: any): void\r\n        /** Makes this camera's settings match other camera.\r\n         * @param other Copy camera settings to the other camera.\r\n         */\r\n        CopyFrom(other: Camera): void\r\n        /** Remove command buffers from execution at a specified place.\r\n         * @param evt When to execute the command buffer during rendering.\r\n         */\r\n        RemoveCommandBuffers(evt: any): void\r\n        RemoveAllCommandBuffers(): void\r\n        /** Add a command buffer to be executed at a specified place.\r\n         * @param evt When to execute the command buffer during rendering.\r\n         * @param buffer The buffer to execute.\r\n         */\r\n        AddCommandBuffer(evt: any, buffer: any): void\r\n        /** Adds a command buffer to the GPU's async compute queues and executes that command buffer when graphics processing reaches a given point.\r\n         * @param evt The point during the graphics processing at which this command buffer should commence on the GPU.\r\n         * @param buffer The buffer to execute.\r\n         * @param queueType The desired async compute queue type to execute the buffer on.\r\n         */\r\n        AddCommandBufferAsync(evt: any, buffer: any, queueType: any): void\r\n        /** Remove command buffer from execution at a specified place.\r\n         * @param evt When to execute the command buffer during rendering.\r\n         * @param buffer The buffer to execute.\r\n         */\r\n        RemoveCommandBuffer(evt: any, buffer: any): void\r\n        /** Get command buffers to be executed at a specified place.\r\n         * @param evt When to execute the command buffer during rendering.\r\n         * @returns Array of command buffers. \r\n         */\r\n        GetCommandBuffers(evt: any): Array<any>\r\n        /** Get culling parameters for a camera.\r\n         * @param cullingParameters Resultant culling parameters.\r\n         * @param stereoAware Generate single-pass stereo aware culling parameters.\r\n         * @returns Flag indicating whether culling parameters are valid. \r\n         */\r\n        TryGetCullingParameters(stereoAware: boolean, cullingParameters: jsb.Out<any>): boolean\r\n        /** Get culling parameters for a camera.\r\n         * @param cullingParameters Resultant culling parameters.\r\n         * @param stereoAware Generate single-pass stereo aware culling parameters.\r\n         * @returns Flag indicating whether culling parameters are valid. \r\n         */\r\n        TryGetCullingParameters(cullingParameters: jsb.Out<any>): boolean\r\n        static CalculateProjectionMatrixFromPhysicalProperties(output: jsb.Out<Matrix4x4>, focalLength: number, sensorSize: Vector2, lensShift: Vector2, nearClip: number, farClip: number, gateFitParameters: any): void\r\n        /** Converts focal length to field of view.\r\n         * @param focalLength Focal length in millimeters.\r\n         * @param sensorSize Sensor size in millimeters. Use the sensor height to get the vertical field of view. Use the sensor width to get the horizontal field of view.\r\n         * @returns field of view in degrees. \r\n         */\r\n        static FocalLengthToFieldOfView(focalLength: number, sensorSize: number): number\r\n        /** Converts field of view to focal length. Use either sensor height and vertical field of view or sensor width and horizontal field of view.\r\n         * @param fieldOfView field of view in degrees.\r\n         * @param sensorSize Sensor size in millimeters.\r\n         * @returns Focal length in millimeters. \r\n         */\r\n        static FieldOfViewToFocalLength(fieldOfView: number, sensorSize: number): number\r\n        /** Converts the horizontal field of view (FOV) to the vertical FOV, based on the value of the aspect ratio parameter.\r\n         * @param horizontalFOV The horizontal FOV value in degrees.\r\n         * @param aspectRatio The aspect ratio value used for the conversion\r\n         */\r\n        static HorizontalToVerticalFieldOfView(horizontalFieldOfView: number, aspectRatio: number): number\r\n        /** Converts the vertical field of view (FOV) to the horizontal FOV, based on the value of the aspect ratio parameter.\r\n         * @param verticalFieldOfView The vertical FOV value in degrees.\r\n         * @param aspectRatio The aspect ratio value used for the conversion\r\n         */\r\n        static VerticalToHorizontalFieldOfView(verticalFieldOfView: number, aspectRatio: number): number\r\n        /** Fills an array of Camera with the current cameras in the Scene, without allocating a new array.\r\n         * @param cameras An array to be filled up with cameras currently in the Scene.\r\n         */\r\n        static GetAllCameras(cameras: Array<Camera>): number\r\n        static SetupCurrent(cur: Camera): void\r\n        /** The distance of the near clipping plane from the the Camera, in world units.\r\n         */\r\n        nearClipPlane: number\r\n        /** The distance of the far clipping plane from the Camera, in world units.\r\n         */\r\n        farClipPlane: number\r\n        /** The field of view of the camera in degrees.\r\n         */\r\n        fieldOfView: number\r\n        /** The rendering path that should be used, if possible.\r\n         */\r\n        renderingPath: any\r\n        /** The rendering path that is currently being used (Read Only).\r\n         */\r\n        readonly actualRenderingPath: any\r\n        /** High dynamic range rendering.\r\n         */\r\n        allowHDR: boolean\r\n        /** MSAA rendering.\r\n         */\r\n        allowMSAA: boolean\r\n        /** Dynamic Resolution Scaling.\r\n         */\r\n        allowDynamicResolution: boolean\r\n        /** Should camera rendering be forced into a RenderTexture.\r\n         */\r\n        forceIntoRenderTexture: boolean\r\n        /** Camera's half-size when in orthographic mode.\r\n         */\r\n        orthographicSize: number\r\n        /** Is the camera orthographic (true) or perspective (false)?\r\n         */\r\n        orthographic: boolean\r\n        /** Opaque object sorting mode.\r\n         */\r\n        opaqueSortMode: any\r\n        /** Transparent object sorting mode.\r\n         */\r\n        transparencySortMode: any\r\n        /** An axis that describes the direction along which the distances of objects are measured for the purpose of sorting.\r\n         */\r\n        transparencySortAxis: Vector3\r\n        /** Camera's depth in the camera rendering order.\r\n         */\r\n        depth: number\r\n        /** The aspect ratio (width divided by height).\r\n         */\r\n        aspect: number\r\n        /** Get the world-space speed of the camera (Read Only).\r\n         */\r\n        readonly velocity: Vector3\r\n        /** This is used to render parts of the Scene selectively.\r\n         */\r\n        cullingMask: number\r\n        /** Mask to select which layers can trigger events on the camera.\r\n         */\r\n        eventMask: number\r\n        /** How to perform per-layer culling for a Camera.\r\n         */\r\n        layerCullSpherical: boolean\r\n        /** Identifies what kind of camera this is, using the CameraType enum.\r\n         */\r\n        cameraType: any\r\n        /** Sets the culling maks used to determine which objects from which Scenes to draw.\nSee EditorSceneManager.SetSceneCullingMask.\r\n         */\r\n        overrideSceneCullingMask: number\r\n        /** Per-layer culling distances.\r\n         */\r\n        layerCullDistances: Array<number>\r\n        /** Whether or not the Camera will use occlusion culling during rendering.\r\n         */\r\n        useOcclusionCulling: boolean\r\n        /** Sets a custom matrix for the camera to use for all culling queries.\r\n         */\r\n        cullingMatrix: Matrix4x4\r\n        /** The color with which the screen will be cleared.\r\n         */\r\n        backgroundColor: Color\r\n        /** How the camera clears the background.\r\n         */\r\n        clearFlags: any\r\n        /** How and if camera generates a depth texture.\r\n         */\r\n        depthTextureMode: any\r\n        /** Should the camera clear the stencil buffer after the deferred light pass?\r\n         */\r\n        clearStencilAfterLightingPass: boolean\r\n        /** Enable [UsePhysicalProperties] to use physical camera properties to compute the field of view and the frustum.\r\n         */\r\n        usePhysicalProperties: boolean\r\n        /** The size of the camera sensor, expressed in millimeters.\r\n         */\r\n        sensorSize: Vector2\r\n        /** The lens offset of the camera. The lens shift is relative to the sensor size. For example, a lens shift of 0.5 offsets the sensor by half its horizontal size.\r\n         */\r\n        lensShift: Vector2\r\n        /** The camera focal length, expressed in millimeters. To use this property, enable UsePhysicalProperties.\r\n         */\r\n        focalLength: number\r\n        /** There are two gates for a camera, the sensor gate and the resolution gate. The physical camera sensor gate is defined by the sensorSize property, the resolution gate is defined by the render target area.\r\n         */\r\n        gateFit: any\r\n        /** Where on the screen is the camera rendered in normalized coordinates.\r\n         */\r\n        rect: Rect\r\n        /** Where on the screen is the camera rendered in pixel coordinates.\r\n         */\r\n        pixelRect: Rect\r\n        /** How wide is the camera in pixels (not accounting for dynamic resolution scaling) (Read Only).\r\n         */\r\n        readonly pixelWidth: number\r\n        /** How tall is the camera in pixels (not accounting for dynamic resolution scaling) (Read Only).\r\n         */\r\n        readonly pixelHeight: number\r\n        /** How wide is the camera in pixels (accounting for dynamic resolution scaling) (Read Only).\r\n         */\r\n        readonly scaledPixelWidth: number\r\n        /** How tall is the camera in pixels (accounting for dynamic resolution scaling) (Read Only).\r\n         */\r\n        readonly scaledPixelHeight: number\r\n        /** Destination render texture.\r\n         */\r\n        targetTexture: any\r\n        /** Gets the temporary RenderTexture target for this Camera.\r\n         */\r\n        readonly activeTexture: any\r\n        /** Set the target display for this Camera.\r\n         */\r\n        targetDisplay: number\r\n        /** Matrix that transforms from camera space to world space (Read Only).\r\n         */\r\n        readonly cameraToWorldMatrix: Matrix4x4\r\n        /** Matrix that transforms from world to camera space.\r\n         */\r\n        worldToCameraMatrix: Matrix4x4\r\n        /** Set a custom projection matrix.\r\n         */\r\n        projectionMatrix: Matrix4x4\r\n        /** Get or set the raw projection matrix with no camera offset (no jittering).\r\n         */\r\n        nonJitteredProjectionMatrix: Matrix4x4\r\n        /** Should the jittered matrix be used for transparency rendering?\r\n         */\r\n        useJitteredProjectionMatrixForTransparentRendering: boolean\r\n        /** Get the view projection matrix used on the last frame.\r\n         */\r\n        readonly previousViewProjectionMatrix: Matrix4x4\r\n        /** The first enabled Camera component that is tagged \"MainCamera\" (Read Only).\r\n         */\r\n        static readonly main: Camera\r\n        /** The camera we are currently rendering with, for low-level render control only (Read Only).\r\n         */\r\n        static readonly current: Camera\r\n        /** If not null, the camera will only render the contents of the specified Scene.\r\n         */\r\n        scene: any\r\n        /** Stereoscopic rendering.\r\n         */\r\n        readonly stereoEnabled: boolean\r\n        /** The distance between the virtual eyes. Use this to query or set the current eye separation. Note that most VR devices provide this value, in which case setting the value will have no effect.\r\n         */\r\n        stereoSeparation: number\r\n        /** Distance to a point where virtual eyes converge.\r\n         */\r\n        stereoConvergence: number\r\n        /** Determines whether the stereo view matrices are suitable to allow for a single pass cull.\r\n         */\r\n        readonly areVRStereoViewMatricesWithinSingleCullTolerance: boolean\r\n        /** Defines which eye of a VR display the Camera renders into.\r\n         */\r\n        stereoTargetEye: any\r\n        /** Returns the eye that is currently rendering.\nIf called when stereo is not enabled it will return Camera.MonoOrStereoscopicEye.Mono.\n\nIf called during a camera rendering callback such as OnRenderImage it will return the currently rendering eye.\n\nIf called outside of a rendering callback and stereo is enabled, it will return the default eye which is Camera.MonoOrStereoscopicEye.Left.\r\n         */\r\n        readonly stereoActiveEye: any\r\n        /** The number of cameras in the current Scene.\r\n         */\r\n        static readonly allCamerasCount: number\r\n        /** Returns all enabled cameras in the Scene.\r\n         */\r\n        static readonly allCameras: Array<Camera>\r\n        /** Number of command buffers set up on this camera (Read Only).\r\n         */\r\n        readonly commandBufferCount: number\r\n        static onPreCull(op: \"get\"): (cam: Camera) => void\r\n        static onPreCull(op: \"add\" | \"remove\" | \"set\", fn?: (cam: Camera) => void): void\r\n        static onPreCull(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (cam: Camera) => void): (cam: Camera) => void | void\r\n        static onPreRender(op: \"get\"): (cam: Camera) => void\r\n        static onPreRender(op: \"add\" | \"remove\" | \"set\", fn?: (cam: Camera) => void): void\r\n        static onPreRender(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (cam: Camera) => void): (cam: Camera) => void | void\r\n        static onPostRender(op: \"get\"): (cam: Camera) => void\r\n        static onPostRender(op: \"add\" | \"remove\" | \"set\", fn?: (cam: Camera) => void): void\r\n        static onPostRender(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (cam: Camera) => void): (cam: Camera) => void | void\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    /** Behaviours are Components that can be enabled or disabled.\r\n     */\r\n    class Behaviour extends Component {\r\n        constructor()\r\n        /** Enabled Behaviours are Updated, disabled Behaviours are not.\r\n         */\r\n        enabled: boolean\r\n        /** Has the Behaviour had active and enabled called?\r\n         */\r\n        readonly isActiveAndEnabled: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object as Object1, Array, Enum } from \"System\";\r\n    /** Base class for everything attached to GameObjects.\r\n     */\r\n    class Component extends Object {\r\n        constructor()\r\n        /** Returns the component of Type type if the GameObject has one attached, null if it doesn't. Will also return disabled components.\r\n         * @param type The type of Component to retrieve.\r\n         */\r\n        GetComponent<T extends Component>(type: { new(): T }): T\r\n        /** Returns the component with name type if the GameObject has one attached, null if it doesn't.\r\n         */\r\n        GetComponent(type: string): Component\r\n        /** Gets the component of the specified type, if it exists.\r\n         * @param type The type of the component to retrieve.\r\n         * @param component The output argument that will contain the component or null.\r\n         * @returns Returns true if the component is found, false otherwise. \r\n         */\r\n        TryGetComponent(type: any, component: jsb.Out<Component>): boolean\r\n        GetComponentInChildren<T extends Component>(type: { new(): T }, includeInactive: boolean): T\r\n        /** Returns the component of Type type in the GameObject or any of its children using depth first search.\r\n         * @param t The type of Component to retrieve.\r\n         * @returns A component of the matching type, if found. \r\n         */\r\n        GetComponentInChildren<T extends Component>(type: { new(): T }): T\r\n        /** Returns all components of Type type in the GameObject or any of its children. Works recursively.\r\n         * @param t The type of Component to retrieve.\r\n         * @param includeInactive Should Components on inactive GameObjects be included in the found set? includeInactive decides which children of the GameObject will be searched.  The GameObject that you call GetComponentsInChildren on is always searched regardless. Default is false.\r\n         */\r\n        GetComponentsInChildren<T extends Component>(type: { new(): T }, includeInactive: boolean): T[]\r\n        GetComponentsInChildren<T extends Component>(type: { new(): T }): T[]\r\n        /** Returns the component of Type type in the GameObject or any of its parents.\r\n         * @param t The type of Component to retrieve.\r\n         * @returns A component of the matching type, if found. \r\n         */\r\n        GetComponentInParent<T extends Component>(type: { new(): T }): T\r\n        /** Returns all components of Type type in the GameObject or any of its parents.\r\n         * @param t The type of Component to retrieve.\r\n         * @param includeInactive Should inactive Components be included in the found set?\r\n         */\r\n        GetComponentsInParent<T extends Component>(type: { new(): T }, includeInactive: boolean): T[]\r\n        GetComponentsInParent<T extends Component>(type: { new(): T }): T[]\r\n        GetComponents(type: any, results: any): void\r\n        /** Returns all components of Type type in the GameObject.\r\n         * @param type The type of Component to retrieve.\r\n         */\r\n        GetComponents<T extends Component>(type: { new(): T }): T[]\r\n        /** Is this game object tagged with tag ?\r\n         * @param tag The tag to compare.\r\n         */\r\n        CompareTag(tag: string): boolean\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour.\r\n         * @param methodName Name of method to call.\r\n         * @param value Optional parameter value for the method.\r\n         * @param options Should an error be raised if the method does not exist on the target object?\r\n         */\r\n        SendMessageUpwards(methodName: string, value: Object1, options: any): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour.\r\n         * @param methodName Name of method to call.\r\n         * @param value Optional parameter value for the method.\r\n         * @param options Should an error be raised if the method does not exist on the target object?\r\n         */\r\n        SendMessageUpwards(methodName: string, value: Object1): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour.\r\n         * @param methodName Name of method to call.\r\n         * @param value Optional parameter value for the method.\r\n         * @param options Should an error be raised if the method does not exist on the target object?\r\n         */\r\n        SendMessageUpwards(methodName: string, options: any): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour.\r\n         * @param methodName Name of method to call.\r\n         * @param value Optional parameter value for the method.\r\n         * @param options Should an error be raised if the method does not exist on the target object?\r\n         */\r\n        SendMessageUpwards(methodName: string): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object.\r\n         * @param methodName Name of the method to call.\r\n         * @param value Optional parameter for the method.\r\n         * @param options Should an error be raised if the target object doesn't implement the method for the message?\r\n         */\r\n        SendMessage(methodName: string, value: Object1, options: any): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object.\r\n         * @param methodName Name of the method to call.\r\n         * @param value Optional parameter for the method.\r\n         * @param options Should an error be raised if the target object doesn't implement the method for the message?\r\n         */\r\n        SendMessage(methodName: string, value: Object1): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object.\r\n         * @param methodName Name of the method to call.\r\n         * @param value Optional parameter for the method.\r\n         * @param options Should an error be raised if the target object doesn't implement the method for the message?\r\n         */\r\n        SendMessage(methodName: string, options: any): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object.\r\n         * @param methodName Name of the method to call.\r\n         * @param value Optional parameter for the method.\r\n         * @param options Should an error be raised if the target object doesn't implement the method for the message?\r\n         */\r\n        SendMessage(methodName: string): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object or any of its children.\r\n         * @param methodName Name of the method to call.\r\n         * @param parameter Optional parameter to pass to the method (can be any value).\r\n         * @param options Should an error be raised if the method does not exist for a given target object?\r\n         */\r\n        BroadcastMessage(methodName: string, parameter: Object1, options: any): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object or any of its children.\r\n         * @param methodName Name of the method to call.\r\n         * @param parameter Optional parameter to pass to the method (can be any value).\r\n         * @param options Should an error be raised if the method does not exist for a given target object?\r\n         */\r\n        BroadcastMessage(methodName: string, parameter: Object1): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object or any of its children.\r\n         * @param methodName Name of the method to call.\r\n         * @param parameter Optional parameter to pass to the method (can be any value).\r\n         * @param options Should an error be raised if the method does not exist for a given target object?\r\n         */\r\n        BroadcastMessage(methodName: string, options: any): void\r\n        /** Calls the method named methodName on every MonoBehaviour in this game object or any of its children.\r\n         * @param methodName Name of the method to call.\r\n         * @param parameter Optional parameter to pass to the method (can be any value).\r\n         * @param options Should an error be raised if the method does not exist for a given target object?\r\n         */\r\n        BroadcastMessage(methodName: string): void\r\n        /** The Transform attached to this GameObject.\r\n         */\r\n        readonly transform: Transform\r\n        /** The game object this component is attached to. A component is always attached to a game object.\r\n         */\r\n        readonly gameObject: GameObject\r\n        /** The tag of this game object.\r\n         */\r\n        tag: string\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum, Array, Object as Object1 } from \"System\";\r\n    import { IEnumerator } from \"System.Collections\";\r\n    /** Position, rotation and scale of an object.\r\n     */\r\n    class Transform extends Component {\r\n        /** Set the parent of the transform.\r\n         * @param parent The parent Transform to use.\r\n         * @param worldPositionStays If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before.\r\n         */\r\n        SetParent(parent: Transform, worldPositionStays: boolean): void\r\n        /** Set the parent of the transform.\r\n         * @param parent The parent Transform to use.\r\n         * @param worldPositionStays If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before.\r\n         */\r\n        SetParent(p: Transform): void\r\n        /** Sets the world space position and rotation of the Transform component.\r\n         */\r\n        SetPositionAndRotation(position: Vector3, rotation: Quaternion): void\r\n        /** Moves the transform by x along the x axis, y along the y axis, and z along the z axis.\r\n         */\r\n        Translate(x: number, y: number, z: number, relativeTo: any): void\r\n        /** Moves the transform by x along the x axis, y along the y axis, and z along the z axis.\r\n         */\r\n        Translate(x: number, y: number, z: number, relativeTo: Transform): void\r\n        /** Moves the transform by x along the x axis, y along the y axis, and z along the z axis.\r\n         */\r\n        Translate(x: number, y: number, z: number): void\r\n        /** Moves the transform in the direction and distance of translation.\r\n         */\r\n        Translate(translation: Vector3, relativeTo: any): void\r\n        /** Moves the transform in the direction and distance of translation.\r\n         */\r\n        Translate(translation: Vector3, relativeTo: Transform): void\r\n        /** Moves the transform in the direction and distance of translation.\r\n         */\r\n        Translate(translation: Vector3): void\r\n        /** The implementation of this method applies a rotation of zAngle degrees around the z axis, xAngle degrees around the x axis, and yAngle degrees around the y axis (in that order).\r\n         * @param relativeTo Determines whether to rotate the GameObject either locally to the GameObject or relative to the Scene in world space.\r\n         * @param xAngle Degrees to rotate the GameObject around the X axis.\r\n         * @param yAngle Degrees to rotate the GameObject around the Y axis.\r\n         * @param zAngle Degrees to rotate the GameObject around the Z axis.\r\n         */\r\n        Rotate(xAngle: number, yAngle: number, zAngle: number, relativeTo: any): void\r\n        /** The implementation of this method applies a rotation of zAngle degrees around the z axis, xAngle degrees around the x axis, and yAngle degrees around the y axis (in that order).\r\n         * @param xAngle Degrees to rotate the GameObject around the X axis.\r\n         * @param yAngle Degrees to rotate the GameObject around the Y axis.\r\n         * @param zAngle Degrees to rotate the GameObject around the Z axis.\r\n         */\r\n        Rotate(xAngle: number, yAngle: number, zAngle: number): void\r\n        /** Rotates the object around the given axis by the number of degrees defined by the given angle.\r\n         * @param angle The degrees of rotation to apply.\r\n         * @param axis The axis to apply rotation to.\r\n         * @param relativeTo Determines whether to rotate the GameObject either locally to the GameObject or relative to the Scene in world space.\r\n         */\r\n        Rotate(axis: Vector3, angle: number, relativeTo: any): void\r\n        /** Applies a rotation of eulerAngles.z degrees around the z-axis, eulerAngles.x degrees around the x-axis, and eulerAngles.y degrees around the y-axis (in that order).\r\n         * @param eulers The rotation to apply in euler angles.\r\n         * @param relativeTo Determines whether to rotate the GameObject either locally to  the GameObject or relative to the Scene in world space.\r\n         */\r\n        Rotate(eulers: Vector3, relativeTo: any): void\r\n        /** Rotates the object around the given axis by the number of degrees defined by the given angle.\r\n         * @param axis The axis to apply rotation to.\r\n         * @param angle The degrees of rotation to apply.\r\n         */\r\n        Rotate(axis: Vector3, angle: number): void\r\n        /** Applies a rotation of eulerAngles.z degrees around the z-axis, eulerAngles.x degrees around the x-axis, and eulerAngles.y degrees around the y-axis (in that order).\r\n         * @param eulers The rotation to apply in euler angles.\r\n         */\r\n        Rotate(eulers: Vector3): void\r\n        /** Rotates the transform about axis passing through point in world coordinates by angle degrees.\r\n         */\r\n        RotateAround(point: Vector3, axis: Vector3, angle: number): void\r\n        /** Rotates the transform so the forward vector points at target's current position.\r\n         * @param target Object to point towards.\r\n         * @param worldUp Vector specifying the upward direction.\r\n         */\r\n        LookAt(target: Transform, worldUp: Vector3): void\r\n        /** Rotates the transform so the forward vector points at worldPosition.\r\n         * @param worldPosition Point to look at.\r\n         * @param worldUp Vector specifying the upward direction.\r\n         */\r\n        LookAt(worldPosition: Vector3, worldUp: Vector3): void\r\n        /** Rotates the transform so the forward vector points at target's current position.\r\n         * @param target Object to point towards.\r\n         * @param worldUp Vector specifying the upward direction.\r\n         */\r\n        LookAt(target: Transform): void\r\n        /** Rotates the transform so the forward vector points at worldPosition.\r\n         * @param worldPosition Point to look at.\r\n         * @param worldUp Vector specifying the upward direction.\r\n         */\r\n        LookAt(worldPosition: Vector3): void\r\n        /** Transforms direction x, y, z from local space to world space.\r\n         */\r\n        TransformDirection(x: number, y: number, z: number): Vector3\r\n        /** Transforms direction from local space to world space.\r\n         */\r\n        TransformDirection(direction: Vector3): Vector3\r\n        /** Transforms the direction x, y, z from world space to local space. The opposite of Transform.TransformDirection.\r\n         */\r\n        InverseTransformDirection(x: number, y: number, z: number): Vector3\r\n        /** Transforms a direction from world space to local space. The opposite of Transform.TransformDirection.\r\n         */\r\n        InverseTransformDirection(direction: Vector3): Vector3\r\n        /** Transforms vector x, y, z from local space to world space.\r\n         */\r\n        TransformVector(x: number, y: number, z: number): Vector3\r\n        /** Transforms vector from local space to world space.\r\n         */\r\n        TransformVector(vector: Vector3): Vector3\r\n        /** Transforms the vector x, y, z from world space to local space. The opposite of Transform.TransformVector.\r\n         */\r\n        InverseTransformVector(x: number, y: number, z: number): Vector3\r\n        /** Transforms a vector from world space to local space. The opposite of Transform.TransformVector.\r\n         */\r\n        InverseTransformVector(vector: Vector3): Vector3\r\n        /** Transforms the position x, y, z from local space to world space.\r\n         */\r\n        TransformPoint(x: number, y: number, z: number): Vector3\r\n        /** Transforms position from local space to world space.\r\n         */\r\n        TransformPoint(position: Vector3): Vector3\r\n        /** Transforms the position x, y, z from world space to local space. The opposite of Transform.TransformPoint.\r\n         */\r\n        InverseTransformPoint(x: number, y: number, z: number): Vector3\r\n        /** Transforms position from world space to local space.\r\n         */\r\n        InverseTransformPoint(position: Vector3): Vector3\r\n        DetachChildren(): void\r\n        SetAsFirstSibling(): void\r\n        SetAsLastSibling(): void\r\n        /** Sets the sibling index.\r\n         * @param index Index to set.\r\n         */\r\n        SetSiblingIndex(index: number): void\r\n        GetSiblingIndex(): number\r\n        /** Finds a child by n and returns it.\r\n         * @param n Name of child to be found.\r\n         * @returns The returned child transform or null if no child is found. \r\n         */\r\n        Find(n: string): Transform\r\n        /** Is this transform a child of parent?\r\n         */\r\n        IsChildOf(parent: Transform): boolean\r\n        GetEnumerator(): IEnumerator\r\n        /** Returns a transform child by index.\r\n         * @param index Index of the child transform to return. Must be smaller than Transform.childCount.\r\n         * @returns Transform child by index. \r\n         */\r\n        GetChild(index: number): Transform\r\n        ResetAll(): void\r\n        TestWithArgs(pos: Vector3, rot: Quaternion, scale: Vector3): void\r\n        TestWithArgsAndOut(pos: Vector3, rot: Quaternion, scale: Vector3, dist: jsb.Out<number>): boolean\r\n        TestWithScriptObject(function_: any): void\r\n        /*protected*/ constructor()\r\n        /** The world space position of the Transform.\r\n         */\r\n        position: Vector3\r\n        /** Position of the transform relative to the parent transform.\r\n         */\r\n        localPosition: Vector3\r\n        /** The rotation as Euler angles in degrees.\r\n         */\r\n        eulerAngles: Vector3\r\n        /** The rotation as Euler angles in degrees relative to the parent transform's rotation.\r\n         */\r\n        localEulerAngles: Vector3\r\n        /** The red axis of the transform in world space.\r\n         */\r\n        right: Vector3\r\n        /** The green axis of the transform in world space.\r\n         */\r\n        up: Vector3\r\n        /** Returns a normalized vector representing the blue axis of the transform in world space.\r\n         */\r\n        forward: Vector3\r\n        /** A Quaternion that stores the rotation of the Transform in world space.\r\n         */\r\n        rotation: Quaternion\r\n        /** The rotation of the transform relative to the transform rotation of the parent.\r\n         */\r\n        localRotation: Quaternion\r\n        /** The scale of the transform relative to the GameObjects parent.\r\n         */\r\n        localScale: Vector3\r\n        /** The parent of the transform.\r\n         */\r\n        parent: Transform\r\n        /** Matrix that transforms a point from world space into local space (Read Only).\r\n         */\r\n        readonly worldToLocalMatrix: Matrix4x4\r\n        /** Matrix that transforms a point from local space into world space (Read Only).\r\n         */\r\n        readonly localToWorldMatrix: Matrix4x4\r\n        /** Returns the topmost transform in the hierarchy.\r\n         */\r\n        readonly root: Transform\r\n        /** The number of children the parent Transform has.\r\n         */\r\n        readonly childCount: number\r\n        /** The global scale of the object (Read Only).\r\n         */\r\n        readonly lossyScale: Vector3\r\n        /** Has the transform changed since the last time the flag was set to 'false'?\r\n         */\r\n        hasChanged: boolean\r\n        /** The transform capacity of the transform's hierarchy data structure.\r\n         */\r\n        hierarchyCapacity: number\r\n        /** The number of transforms in the transform's hierarchy data structure.\r\n         */\r\n        readonly hierarchyCount: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Array, Enum } from \"System\";\r\n    /** Position, size, anchor and pivot information for a rectangle.\r\n     */\r\n    class RectTransform extends Transform {\r\n        constructor()\r\n        ForceUpdateRectTransforms(): void\r\n        /** Get the corners of the calculated rectangle in the local space of its Transform.\r\n         * @param fourCornersArray The array that corners are filled into.\r\n         */\r\n        GetLocalCorners(fourCornersArray: Array<Vector3>): void\r\n        /** Get the corners of the calculated rectangle in world space.\r\n         * @param fourCornersArray The array that corners are filled into.\r\n         */\r\n        GetWorldCorners(fourCornersArray: Array<Vector3>): void\r\n        SetInsetAndSizeFromParentEdge(edge: any, inset: number, size: number): void\r\n        SetSizeWithCurrentAnchors(axis: any, size: number): void\r\n        /** The calculated rectangle in the local space of the Transform.\r\n         */\r\n        readonly rect: Rect\r\n        /** The normalized position in the parent RectTransform that the lower left corner is anchored to.\r\n         */\r\n        anchorMin: Vector2\r\n        /** The normalized position in the parent RectTransform that the upper right corner is anchored to.\r\n         */\r\n        anchorMax: Vector2\r\n        /** The position of the pivot of this RectTransform relative to the anchor reference point.\r\n         */\r\n        anchoredPosition: Vector2\r\n        /** The size of this RectTransform relative to the distances between the anchors.\r\n         */\r\n        sizeDelta: Vector2\r\n        /** The normalized position in this RectTransform that it rotates around.\r\n         */\r\n        pivot: Vector2\r\n        /** The 3D position of the pivot of this RectTransform relative to the anchor reference point.\r\n         */\r\n        anchoredPosition3D: Vector3\r\n        /** The offset of the lower left corner of the rectangle relative to the lower left anchor.\r\n         */\r\n        offsetMin: Vector2\r\n        /** The offset of the upper right corner of the rectangle relative to the upper right anchor.\r\n         */\r\n        offsetMax: Vector2\r\n        static reapplyDrivenProperties(op: \"add\" | \"remove\", fn: (driven: RectTransform) => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Object as Object1 } from \"System\";\r\n    import { IEnumerator } from \"System.Collections\";\r\n    /** MonoBehaviour is the base class from which every Unity script derives.\r\n     */\r\n    class MonoBehaviour extends Behaviour {\r\n        constructor()\r\n        /** Is any invoke on methodName pending?\r\n         */\r\n        IsInvoking(methodName: string): boolean\r\n        IsInvoking(): boolean\r\n        /** Cancels all Invoke calls with name methodName on this behaviour.\r\n         */\r\n        CancelInvoke(methodName: string): void\r\n        CancelInvoke(): void\r\n        /** Invokes the method methodName in time seconds.\r\n         */\r\n        Invoke(methodName: string, time: number): void\r\n        /** Invokes the method methodName in time seconds, then repeatedly every repeatRate seconds.\r\n         */\r\n        InvokeRepeating(methodName: string, time: number, repeatRate: number): void\r\n        /** Starts a coroutine named methodName.\r\n         */\r\n        StartCoroutine(methodName: string, value: Object1): Coroutine\r\n        /** Starts a coroutine named methodName.\r\n         */\r\n        StartCoroutine(methodName: string): Coroutine\r\n        /** Starts a Coroutine.\r\n         */\r\n        StartCoroutine(routine: IEnumerator): Coroutine\r\n        /** Stops the first coroutine named methodName, or the coroutine stored in routine running on this behaviour.\r\n         * @param methodName Name of coroutine.\r\n         * @param routine Name of the function in code, including coroutines.\r\n         */\r\n        StopCoroutine(routine: IEnumerator): void\r\n        /** Stops the first coroutine named methodName, or the coroutine stored in routine running on this behaviour.\r\n         * @param methodName Name of coroutine.\r\n         * @param routine Name of the function in code, including coroutines.\r\n         */\r\n        StopCoroutine(routine: Coroutine): void\r\n        /** Stops the first coroutine named methodName, or the coroutine stored in routine running on this behaviour.\r\n         * @param methodName Name of coroutine.\r\n         * @param routine Name of the function in code, including coroutines.\r\n         */\r\n        StopCoroutine(methodName: string): void\r\n        StopAllCoroutines(): void\r\n        /** Logs message to the Unity Console (identical to Debug.Log).\r\n         */\r\n        static print(message: Object1): void\r\n        /** Disabling this lets you skip the GUI layout phase.\r\n         */\r\n        useGUILayout: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Object as Object1 } from \"System\";\r\n    /** A class you can derive from if you want to create objects that don't need to be attached to game objects.\r\n     */\r\n    class ScriptableObject extends Object {\r\n        constructor()\r\n        /** Creates an instance of a scriptable object.\r\n         * @param className The type of the ScriptableObject to create, as the name of the type.\r\n         * @param type The type of the ScriptableObject to create, as a System.Type instance.\r\n         * @returns The created ScriptableObject. \r\n         */\r\n        static CreateInstance<T extends ScriptableObject>(type: { new(): T }): T\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum, Array, Object as Object1, ValueType } from \"System\";\r\n    /** Represents a Sprite object for use in 2D gameplay.\r\n     */\r\n    class Sprite extends Object {\r\n        GetPhysicsShapeCount(): number\r\n        /** The number of points in the selected physics shape for the Sprite.\r\n         * @param shapeIdx The index of the physics shape to retrieve the number of points from.\r\n         * @returns The number of points in the selected physics shape for the Sprite. \r\n         */\r\n        GetPhysicsShapePointCount(shapeIdx: number): number\r\n        GetPhysicsShape(shapeIdx: number, physicsShape: any): number\r\n        OverridePhysicsShape(physicsShapes: any): void\r\n        /** Sets up new Sprite geometry.\r\n         * @param vertices Array of vertex positions in Sprite Rect space.\r\n         * @param triangles Array of sprite mesh triangle indices.\r\n         */\r\n        OverrideGeometry(vertices: Array<Vector2>, triangles: Array<number>): void\r\n        /** Returns an array of BindPoses.\r\n         * @param sprite The sprite to retrieve the bind pose from.\r\n         * @returns A list of bind poses for this sprite. There is no need to dispose the returned NativeArray. \r\n         */\r\n        GetBindPoses(): any\r\n        SetBindPoses(src: any): void\r\n        /** Returns a list of indices. This is the same as Sprite.triangle.\r\n         * @returns A read-only list of indices indicating how the triangles are formed between the vertices. The array is marked as undisposable. \r\n         */\r\n        GetIndices(): any\r\n        SetIndices(src: any): void\r\n        /** Returns a list of SpriteBone in this Sprite.\r\n         * @param sprite The sprite to get the list of SpriteBone from.\r\n         * @returns An array of SpriteBone that belongs to this Sprite. \r\n         */\r\n        GetBones(): Array<any>\r\n        /** Sets the SpriteBones for this Sprite.\r\n         */\r\n        SetBones(src: Array<any>): void\r\n        /** Checks if a specific channel exists for this Sprite.\r\n         * @returns True if the channel exists. \r\n         */\r\n        HasVertexAttribute(channel: any): boolean\r\n        /** Sets the vertex count. This resizes the internal buffer. It also preserves any configurations of VertexAttributes.\r\n         */\r\n        SetVertexCount(count: number): void\r\n        /** Returns the number of vertices in this Sprite.\r\n         */\r\n        GetVertexCount(): number\r\n        /** Create a new Sprite object.\r\n         * @param texture Texture from which to obtain the sprite graphic.\r\n         * @param rect Rectangular section of the texture to use for the sprite.\r\n         * @param pivot Sprite's pivot point relative to its graphic rectangle.\r\n         * @param pixelsPerUnit The number of pixels in the sprite that correspond to one unit in world space.\r\n         * @param extrude Amount by which the sprite mesh should be expanded outwards.\r\n         * @param meshType Controls the type of mesh generated for the sprite.\r\n         * @param border The border sizes of the sprite (X=left, Y=bottom, Z=right, W=top).\r\n         * @param generateFallbackPhysicsShape Generates a default physics shape for the sprite.\r\n         */\r\n        static Create(texture: Texture2D, rect: Rect, pivot: Vector2, pixelsPerUnit: number, extrude: number, meshType: any, border: Vector4, generateFallbackPhysicsShape: boolean): Sprite\r\n        /** Create a new Sprite object.\r\n         * @param texture Texture from which to obtain the sprite graphic.\r\n         * @param rect Rectangular section of the texture to use for the sprite.\r\n         * @param pivot Sprite's pivot point relative to its graphic rectangle.\r\n         * @param pixelsPerUnit The number of pixels in the sprite that correspond to one unit in world space.\r\n         * @param extrude Amount by which the sprite mesh should be expanded outwards.\r\n         * @param meshType Controls the type of mesh generated for the sprite.\r\n         * @param border The border sizes of the sprite (X=left, Y=bottom, Z=right, W=top).\r\n         * @param generateFallbackPhysicsShape Generates a default physics shape for the sprite.\r\n         */\r\n        static Create(texture: Texture2D, rect: Rect, pivot: Vector2, pixelsPerUnit: number, extrude: number, meshType: any, border: Vector4): Sprite\r\n        /** Create a new Sprite object.\r\n         * @param texture Texture from which to obtain the sprite graphic.\r\n         * @param rect Rectangular section of the texture to use for the sprite.\r\n         * @param pivot Sprite's pivot point relative to its graphic rectangle.\r\n         * @param pixelsPerUnit The number of pixels in the sprite that correspond to one unit in world space.\r\n         * @param extrude Amount by which the sprite mesh should be expanded outwards.\r\n         * @param meshType Controls the type of mesh generated for the sprite.\r\n         * @param border The border sizes of the sprite (X=left, Y=bottom, Z=right, W=top).\r\n         * @param generateFallbackPhysicsShape Generates a default physics shape for the sprite.\r\n         */\r\n        static Create(texture: Texture2D, rect: Rect, pivot: Vector2, pixelsPerUnit: number, extrude: number, meshType: any): Sprite\r\n        /** Create a new Sprite object.\r\n         * @param texture Texture from which to obtain the sprite graphic.\r\n         * @param rect Rectangular section of the texture to use for the sprite.\r\n         * @param pivot Sprite's pivot point relative to its graphic rectangle.\r\n         * @param pixelsPerUnit The number of pixels in the sprite that correspond to one unit in world space.\r\n         * @param extrude Amount by which the sprite mesh should be expanded outwards.\r\n         * @param meshType Controls the type of mesh generated for the sprite.\r\n         * @param border The border sizes of the sprite (X=left, Y=bottom, Z=right, W=top).\r\n         * @param generateFallbackPhysicsShape Generates a default physics shape for the sprite.\r\n         */\r\n        static Create(texture: Texture2D, rect: Rect, pivot: Vector2, pixelsPerUnit: number, extrude: number): Sprite\r\n        /** Create a new Sprite object.\r\n         * @param texture Texture from which to obtain the sprite graphic.\r\n         * @param rect Rectangular section of the texture to use for the sprite.\r\n         * @param pivot Sprite's pivot point relative to its graphic rectangle.\r\n         * @param pixelsPerUnit The number of pixels in the sprite that correspond to one unit in world space.\r\n         * @param extrude Amount by which the sprite mesh should be expanded outwards.\r\n         * @param meshType Controls the type of mesh generated for the sprite.\r\n         * @param border The border sizes of the sprite (X=left, Y=bottom, Z=right, W=top).\r\n         * @param generateFallbackPhysicsShape Generates a default physics shape for the sprite.\r\n         */\r\n        static Create(texture: Texture2D, rect: Rect, pivot: Vector2, pixelsPerUnit: number): Sprite\r\n        /** Create a new Sprite object.\r\n         * @param texture Texture from which to obtain the sprite graphic.\r\n         * @param rect Rectangular section of the texture to use for the sprite.\r\n         * @param pivot Sprite's pivot point relative to its graphic rectangle.\r\n         * @param pixelsPerUnit The number of pixels in the sprite that correspond to one unit in world space.\r\n         * @param extrude Amount by which the sprite mesh should be expanded outwards.\r\n         * @param meshType Controls the type of mesh generated for the sprite.\r\n         * @param border The border sizes of the sprite (X=left, Y=bottom, Z=right, W=top).\r\n         * @param generateFallbackPhysicsShape Generates a default physics shape for the sprite.\r\n         */\r\n        static Create(texture: Texture2D, rect: Rect, pivot: Vector2): Sprite\r\n        protected constructor()\r\n        /** Bounds of the Sprite, specified by its center and extents in world space units.\r\n         */\r\n        readonly bounds: Bounds\r\n        /** Location of the Sprite on the original Texture, specified in pixels.\r\n         */\r\n        readonly rect: Rect\r\n        /** Returns the border sizes of the sprite.\r\n         */\r\n        readonly border: Vector4\r\n        /** Get the reference to the used texture. If packed this will point to the atlas, if not packed will point to the source sprite.\r\n         */\r\n        readonly texture: Texture2D\r\n        /** The number of pixels in the sprite that correspond to one unit in world space. (Read Only)\r\n         */\r\n        readonly pixelsPerUnit: number\r\n        /** The Variant scale of texture used by the Sprite. This is useful to check when a Variant SpriteAtlas is being used by Sprites.\r\n         */\r\n        readonly spriteAtlasTextureScale: number\r\n        /** Returns the texture that contains the alpha channel from the source texture. Unity generates this texture under the hood for sprites that have alpha in the source, and need to be compressed using techniques like ETC1.\n\nReturns NULL if there is no associated alpha texture for the source sprite. This is the case if the sprite has not been setup to use ETC1 compression.\r\n         */\r\n        readonly associatedAlphaSplitTexture: Texture2D\r\n        /** Location of the Sprite's center point in the Rect on the original Texture, specified in pixels.\r\n         */\r\n        readonly pivot: Vector2\r\n        readonly isUsingPlaceholder: boolean\r\n        /** Returns true if this Sprite is packed in an atlas.\r\n         */\r\n        readonly packed: boolean\r\n        /** If Sprite is packed (see Sprite.packed), returns its SpritePackingMode.\r\n         */\r\n        readonly packingMode: any\r\n        /** If Sprite is packed (see Sprite.packed), returns its SpritePackingRotation.\r\n         */\r\n        readonly packingRotation: any\r\n        /** Get the rectangle this sprite uses on its texture. Raises an exception if this sprite is tightly packed in an atlas.\r\n         */\r\n        readonly textureRect: Rect\r\n        /** Gets the offset of the rectangle this sprite uses on its texture to the original sprite bounds. If sprite mesh type is FullRect, offset is zero.\r\n         */\r\n        readonly textureRectOffset: Vector2\r\n        /** Returns a copy of the array containing sprite mesh vertex positions.\r\n         */\r\n        readonly vertices: Array<Vector2>\r\n        /** Returns a copy of the array containing sprite mesh triangles.\r\n         */\r\n        readonly triangles: Array<number>\r\n        /** The base texture coordinates of the sprite mesh.\r\n         */\r\n        readonly uv: Array<Vector2>\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Enum } from \"System\";\r\n    /** Renders a Sprite for 2D graphics.\r\n     */\r\n    class SpriteRenderer extends Renderer {\r\n        constructor()\r\n        /** Stop using the deformable buffer to render the Sprite and use the original mesh instead.\r\n         */\r\n        DeactivateDeformableBuffer(): void\r\n        /** The Sprite to render.\r\n         */\r\n        sprite: Sprite\r\n        /** The current draw mode of the Sprite Renderer.\r\n         */\r\n        drawMode: any\r\n        /** Property to set/get the size to render when the SpriteRenderer.drawMode is set to SpriteDrawMode.Sliced.\r\n         */\r\n        size: Vector2\r\n        /** The current threshold for Sprite Renderer tiling.\r\n         */\r\n        adaptiveModeThreshold: number\r\n        /** The current tile mode of the Sprite Renderer.\r\n         */\r\n        tileMode: any\r\n        /** Rendering color for the Sprite graphic.\r\n         */\r\n        color: Color\r\n        /** Specifies how the sprite interacts with the masks.\r\n         */\r\n        maskInteraction: any\r\n        /** Flips the sprite on the X axis.\r\n         */\r\n        flipX: boolean\r\n        /** Flips the sprite on the Y axis.\r\n         */\r\n        flipY: boolean\r\n        /** Determines the position of the Sprite used for sorting the SpriteRenderer.\r\n         */\r\n        spriteSortPoint: any\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum, Array, Object as Object1, ValueType } from \"System\";\r\n    /** General functionality for all renderers.\r\n     */\r\n    class Renderer extends Component {\r\n        constructor()\r\n        HasPropertyBlock(): boolean\r\n        /** Lets you set or clear per-renderer or per-material parameter overrides.\r\n         * @param properties Property block with values you want to override.\r\n         * @param materialIndex The index of the Material you want to override the parameters of. The index ranges from 0 to Renderer.sharedMaterial.Length-1.\r\n         */\r\n        SetPropertyBlock(properties: any, materialIndex: number): void\r\n        /** Lets you set or clear per-renderer or per-material parameter overrides.\r\n         * @param properties Property block with values you want to override.\r\n         * @param materialIndex The index of the Material you want to override the parameters of. The index ranges from 0 to Renderer.sharedMaterial.Length-1.\r\n         */\r\n        SetPropertyBlock(properties: any): void\r\n        /** Get per-Renderer or per-Material property block.\r\n         * @param properties Material parameters to retrieve.\r\n         * @param materialIndex The index of the Material you want to get overridden parameters from. The index ranges from 0 to Renderer.sharedMaterials.Length-1.\r\n         */\r\n        GetPropertyBlock(properties: any, materialIndex: number): void\r\n        /** Get per-Renderer or per-Material property block.\r\n         * @param properties Material parameters to retrieve.\r\n         * @param materialIndex The index of the Material you want to get overridden parameters from. The index ranges from 0 to Renderer.sharedMaterials.Length-1.\r\n         */\r\n        GetPropertyBlock(properties: any): void\r\n        GetMaterials(m: any): void\r\n        GetSharedMaterials(m: any): void\r\n        GetClosestReflectionProbes(result: any): void\r\n        /** Schedules an update of the albedo and emissive Textures of a system that contains the Renderer.\r\n         */\r\n        UpdateGIMaterials(): void\r\n        /** The bounding volume of the renderer (Read Only).\r\n         */\r\n        readonly bounds: Bounds\r\n        /** Makes the rendered 3D object visible if enabled.\r\n         */\r\n        enabled: boolean\r\n        /** Is this renderer visible in any camera? (Read Only)\r\n         */\r\n        readonly isVisible: boolean\r\n        /** Does this object cast shadows?\r\n         */\r\n        shadowCastingMode: any\r\n        /** Does this object receive shadows?\r\n         */\r\n        receiveShadows: boolean\r\n        /** Allows turning off rendering for a specific component.\r\n         */\r\n        forceRenderingOff: boolean\r\n        /** Specifies the mode for motion vector rendering.\r\n         */\r\n        motionVectorGenerationMode: any\r\n        /** The light probe interpolation type.\r\n         */\r\n        lightProbeUsage: any\r\n        /** Should reflection probes be used for this Renderer?\r\n         */\r\n        reflectionProbeUsage: any\r\n        /** Determines which rendering layer this renderer lives on.\r\n         */\r\n        renderingLayerMask: number\r\n        /** This value sorts renderers by priority. Lower values are rendered first and higher values are rendered last.\r\n         */\r\n        rendererPriority: number\r\n        /** Describes how this renderer is updated for ray tracing.\r\n         */\r\n        rayTracingMode: any\r\n        /** Name of the Renderer's sorting layer.\r\n         */\r\n        sortingLayerName: string\r\n        /** Unique ID of the Renderer's sorting layer.\r\n         */\r\n        sortingLayerID: number\r\n        /** Renderer's order within a sorting layer.\r\n         */\r\n        sortingOrder: number\r\n        /** Controls if dynamic occlusion culling should be performed for this renderer.\r\n         */\r\n        allowOcclusionWhenDynamic: boolean\r\n        /** Has this renderer been statically batched with any other renderers?\r\n         */\r\n        readonly isPartOfStaticBatch: boolean\r\n        /** Matrix that transforms a point from world space into local space (Read Only).\r\n         */\r\n        readonly worldToLocalMatrix: Matrix4x4\r\n        /** Matrix that transforms a point from local space into world space (Read Only).\r\n         */\r\n        readonly localToWorldMatrix: Matrix4x4\r\n        /** If set, the Renderer will use the Light Probe Proxy Volume component attached to the source GameObject.\r\n         */\r\n        lightProbeProxyVolumeOverride: GameObject\r\n        /** If set, Renderer will use this Transform's position to find the light or reflection probe.\r\n         */\r\n        probeAnchor: Transform\r\n        /** The index of the baked lightmap applied to this renderer.\r\n         */\r\n        lightmapIndex: number\r\n        /** The index of the realtime lightmap applied to this renderer.\r\n         */\r\n        realtimeLightmapIndex: number\r\n        /** The UV scale & offset used for a lightmap.\r\n         */\r\n        lightmapScaleOffset: Vector4\r\n        /** The UV scale & offset used for a realtime lightmap.\r\n         */\r\n        realtimeLightmapScaleOffset: Vector4\r\n        /** Returns all the instantiated materials of this object.\r\n         */\r\n        materials: Array<Material>\r\n        /** Returns the first instantiated Material assigned to the renderer.\r\n         */\r\n        material: Material\r\n        /** The shared material of this object.\r\n         */\r\n        sharedMaterial: Material\r\n        /** All the shared materials of this object.\r\n         */\r\n        sharedMaterials: Array<Material>\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Enum } from \"System\";\r\n    import { IEnumerator } from \"System.Collections\";\r\n    /** The animation component is used to play back animations.\r\n     */\r\n    class Animation extends Behaviour {\r\n        constructor()\r\n        $GetValue(name: string): AnimationState\r\n        /** Stops an animation named name.\r\n         */\r\n        Stop(name: string): void\r\n        Stop(): void\r\n        /** Rewinds the animation named name.\r\n         */\r\n        Rewind(name: string): void\r\n        Rewind(): void\r\n        Sample(): void\r\n        /** Is the animation named name playing?\r\n         */\r\n        IsPlaying(name: string): boolean\r\n        /** Plays an animation without blending.\r\n         */\r\n        Play(animation: string, mode: any): boolean\r\n        /** Plays an animation without blending.\r\n         */\r\n        Play(mode: any): boolean\r\n        /** Plays an animation without blending.\r\n         */\r\n        Play(animation: string): boolean\r\n        /** Plays an animation without blending.\r\n         */\r\n        Play(): boolean\r\n        /** Fades the animation with name animation in over a period of time seconds and fades other animations out.\r\n         */\r\n        CrossFade(animation: string, fadeLength: number, mode: any): void\r\n        /** Fades the animation with name animation in over a period of time seconds and fades other animations out.\r\n         */\r\n        CrossFade(animation: string, fadeLength: number): void\r\n        /** Fades the animation with name animation in over a period of time seconds and fades other animations out.\r\n         */\r\n        CrossFade(animation: string): void\r\n        /** Blends the animation named animation towards targetWeight over the next time seconds.\r\n         */\r\n        Blend(animation: string, targetWeight: number, fadeLength: number): void\r\n        /** Blends the animation named animation towards targetWeight over the next time seconds.\r\n         */\r\n        Blend(animation: string, targetWeight: number): void\r\n        /** Blends the animation named animation towards targetWeight over the next time seconds.\r\n         */\r\n        Blend(animation: string): void\r\n        /** Cross fades an animation after previous animations has finished playing.\r\n         */\r\n        CrossFadeQueued(animation: string, fadeLength: number, queue: any, mode: any): AnimationState\r\n        /** Cross fades an animation after previous animations has finished playing.\r\n         */\r\n        CrossFadeQueued(animation: string, fadeLength: number, queue: any): AnimationState\r\n        /** Cross fades an animation after previous animations has finished playing.\r\n         */\r\n        CrossFadeQueued(animation: string, fadeLength: number): AnimationState\r\n        /** Cross fades an animation after previous animations has finished playing.\r\n         */\r\n        CrossFadeQueued(animation: string): AnimationState\r\n        /** Plays an animation after previous animations has finished playing.\r\n         */\r\n        PlayQueued(animation: string, queue: any, mode: any): AnimationState\r\n        /** Plays an animation after previous animations has finished playing.\r\n         */\r\n        PlayQueued(animation: string, queue: any): AnimationState\r\n        /** Plays an animation after previous animations has finished playing.\r\n         */\r\n        PlayQueued(animation: string): AnimationState\r\n        /** Adds clip to the only play between firstFrame and lastFrame. The new clip will also be added to the animation with name newName.\r\n         * @param addLoopFrame Should an extra frame be inserted at the end that matches the first frame? Turn this on if you are making a looping animation.\r\n         */\r\n        AddClip(clip: AnimationClip, newName: string, firstFrame: number, lastFrame: number, addLoopFrame: boolean): void\r\n        /** Adds clip to the only play between firstFrame and lastFrame. The new clip will also be added to the animation with name newName.\r\n         * @param addLoopFrame Should an extra frame be inserted at the end that matches the first frame? Turn this on if you are making a looping animation.\r\n         */\r\n        AddClip(clip: AnimationClip, newName: string, firstFrame: number, lastFrame: number): void\r\n        /** Adds a clip to the animation with name newName.\r\n         */\r\n        AddClip(clip: AnimationClip, newName: string): void\r\n        /** Remove clip from the animation list.\r\n         */\r\n        RemoveClip(clip: AnimationClip): void\r\n        /** Remove clip from the animation list.\r\n         */\r\n        RemoveClip(clipName: string): void\r\n        GetClipCount(): number\r\n        SyncLayer(layer: number): void\r\n        GetEnumerator(): IEnumerator\r\n        GetClip(name: string): AnimationClip\r\n        /** The default animation.\r\n         */\r\n        clip: AnimationClip\r\n        /** Should the default animation clip (the Animation.clip property) automatically start playing on startup?\r\n         */\r\n        playAutomatically: boolean\r\n        /** How should time beyond the playback range of the clip be treated?\r\n         */\r\n        wrapMode: WrapMode\r\n        /** Is an animation currently being played?\r\n         */\r\n        readonly isPlaying: boolean\r\n        /** When turned on, animations will be executed in the physics loop. This is only useful in conjunction with kinematic rigidbodies.\r\n         */\r\n        animatePhysics: boolean\r\n        /** Controls culling of this Animation component.\r\n         */\r\n        cullingType: any\r\n        /** AABB of this Animation animation component in local space.\r\n         */\r\n        localBounds: Bounds\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Array, Object as Object1 } from \"System\";\r\n    /** Stores keyframe based animations.\r\n     */\r\n    class AnimationClip extends Motion {\r\n        constructor()\r\n        /** Samples an animation at a given time for any animated properties.\r\n         * @param go The animated game object.\r\n         * @param time The time to sample an animation.\r\n         */\r\n        SampleAnimation(go: GameObject, time: number): void\r\n        /** Assigns the curve to animate a specific property.\r\n         * @param relativePath Path to the game object this curve applies to. The relativePath\n        is formatted similar to a pathname, e.g. \"rootspineleftArm\".  If relativePath\n        is empty it refers to the game object the animation clip is attached to.\r\n         * @param type The class type of the component that is animated.\r\n         * @param propertyName The name or path to the property being animated.\r\n         * @param curve The animation curve.\r\n         */\r\n        SetCurve(relativePath: string, type: any, propertyName: string, curve: AnimationCurve): void\r\n        EnsureQuaternionContinuity(): void\r\n        ClearCurves(): void\r\n        /** Adds an animation event to the clip.\r\n         * @param evt AnimationEvent to add.\r\n         */\r\n        AddEvent(evt: any): void\r\n        /** Animation length in seconds. (Read Only)\r\n         */\r\n        readonly length: number\r\n        /** Frame rate at which keyframes are sampled. (Read Only)\r\n         */\r\n        frameRate: number\r\n        /** Sets the default wrap mode used in the animation state.\r\n         */\r\n        wrapMode: WrapMode\r\n        /** AABB of this Animation Clip in local space of Animation component that it is attached too.\r\n         */\r\n        localBounds: Bounds\r\n        /** Set to true if the AnimationClip will be used with the Legacy Animation component ( instead of the Animator ).\r\n         */\r\n        legacy: boolean\r\n        /** Returns true if the animation contains curve that drives a humanoid rig.\r\n         */\r\n        readonly humanMotion: boolean\r\n        /** Returns true if the animation clip has no curves and no events.\r\n         */\r\n        readonly empty: boolean\r\n        /** Returns true if the Animation has animation on the root transform.\r\n         */\r\n        readonly hasGenericRootTransform: boolean\r\n        /** Returns true if the AnimationClip has editor curves for its root motion.\r\n         */\r\n        readonly hasMotionFloatCurves: boolean\r\n        /** Returns true if the AnimationClip has root motion curves.\r\n         */\r\n        readonly hasMotionCurves: boolean\r\n        /** Returns true if the AnimationClip has root Curves.\r\n         */\r\n        readonly hasRootCurves: boolean\r\n        /** Animation Events for this animation clip.\r\n         */\r\n        events: Array<any>\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    /** Base class for AnimationClips and BlendTrees.\r\n     */\r\n    class Motion extends Object {\r\n        protected constructor()\r\n        readonly averageDuration: number\r\n        readonly averageAngularSpeed: number\r\n        readonly averageSpeed: Vector3\r\n        readonly apparentSpeed: number\r\n        readonly isLooping: boolean\r\n        readonly legacy: boolean\r\n        readonly isHumanMotion: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum, Array, Object as Object1, ValueType } from \"System\";\r\n    /** Interface to control the Mecanim animation system.\r\n     */\r\n    class Animator extends Behaviour {\r\n        constructor()\r\n        /** Returns the value of the given float parameter.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         * @returns The value of the parameter. \r\n         */\r\n        GetFloat(name: string): number\r\n        /** Returns the value of the given float parameter.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         * @returns The value of the parameter. \r\n         */\r\n        GetFloat(id: number): number\r\n        /** Send float values to the Animator to affect transitions.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         * @param value The new parameter value.\r\n         * @param dampTime The damper total time.\r\n         * @param deltaTime The delta time to give to the damper.\r\n         */\r\n        SetFloat(name: string, value: number, dampTime: number, deltaTime: number): void\r\n        /** Send float values to the Animator to affect transitions.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         * @param value The new parameter value.\r\n         * @param dampTime The damper total time.\r\n         * @param deltaTime The delta time to give to the damper.\r\n         */\r\n        SetFloat(id: number, value: number, dampTime: number, deltaTime: number): void\r\n        /** Send float values to the Animator to affect transitions.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         * @param value The new parameter value.\r\n         * @param dampTime The damper total time.\r\n         * @param deltaTime The delta time to give to the damper.\r\n         */\r\n        SetFloat(name: string, value: number): void\r\n        /** Send float values to the Animator to affect transitions.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         * @param value The new parameter value.\r\n         * @param dampTime The damper total time.\r\n         * @param deltaTime The delta time to give to the damper.\r\n         */\r\n        SetFloat(id: number, value: number): void\r\n        /** Returns the value of the given boolean parameter.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         * @returns The value of the parameter. \r\n         */\r\n        GetBool(name: string): boolean\r\n        /** Returns the value of the given boolean parameter.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         * @returns The value of the parameter. \r\n         */\r\n        GetBool(id: number): boolean\r\n        /** Sets the value of the given boolean parameter.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         * @param value The new parameter value.\r\n         */\r\n        SetBool(name: string, value: boolean): void\r\n        /** Sets the value of the given boolean parameter.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         * @param value The new parameter value.\r\n         */\r\n        SetBool(id: number, value: boolean): void\r\n        /** Returns the value of the given integer parameter.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         * @returns The value of the parameter. \r\n         */\r\n        GetInteger(name: string): number\r\n        /** Returns the value of the given integer parameter.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         * @returns The value of the parameter. \r\n         */\r\n        GetInteger(id: number): number\r\n        /** Sets the value of the given integer parameter.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         * @param value The new parameter value.\r\n         */\r\n        SetInteger(name: string, value: number): void\r\n        /** Sets the value of the given integer parameter.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         * @param value The new parameter value.\r\n         */\r\n        SetInteger(id: number, value: number): void\r\n        /** Sets the value of the given trigger parameter.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         */\r\n        SetTrigger(name: string): void\r\n        /** Sets the value of the given trigger parameter.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         */\r\n        SetTrigger(id: number): void\r\n        /** Resets the value of the given trigger parameter.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         */\r\n        ResetTrigger(name: string): void\r\n        /** Resets the value of the given trigger parameter.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         */\r\n        ResetTrigger(id: number): void\r\n        /** Returns true if the parameter is controlled by a curve, false otherwise.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         * @returns True if the parameter is controlled by a curve, false otherwise. \r\n         */\r\n        IsParameterControlledByCurve(name: string): boolean\r\n        /** Returns true if the parameter is controlled by a curve, false otherwise.\r\n         * @param name The parameter name.\r\n         * @param id The parameter ID.\r\n         * @returns True if the parameter is controlled by a curve, false otherwise. \r\n         */\r\n        IsParameterControlledByCurve(id: number): boolean\r\n        /** Gets the position of an IK goal.\r\n         * @param goal The AvatarIKGoal that is queried.\r\n         * @returns Return the current position of this IK goal in world space. \r\n         */\r\n        GetIKPosition(goal: any): Vector3\r\n        /** Sets the position of an IK goal.\r\n         * @param goal The AvatarIKGoal that is set.\r\n         * @param goalPosition The position in world space.\r\n         */\r\n        SetIKPosition(goal: any, goalPosition: Vector3): void\r\n        /** Gets the rotation of an IK goal.\r\n         * @param goal The AvatarIKGoal that is is queried.\r\n         */\r\n        GetIKRotation(goal: any): Quaternion\r\n        /** Sets the rotation of an IK goal.\r\n         * @param goal The AvatarIKGoal that is set.\r\n         * @param goalRotation The rotation in world space.\r\n         */\r\n        SetIKRotation(goal: any, goalRotation: Quaternion): void\r\n        /** Gets the translative weight of an IK goal (0 = at the original animation before IK, 1 = at the goal).\r\n         * @param goal The AvatarIKGoal that is queried.\r\n         */\r\n        GetIKPositionWeight(goal: any): number\r\n        /** Sets the translative weight of an IK goal (0 = at the original animation before IK, 1 = at the goal).\r\n         * @param goal The AvatarIKGoal that is set.\r\n         * @param value The translative weight.\r\n         */\r\n        SetIKPositionWeight(goal: any, value: number): void\r\n        /** Gets the rotational weight of an IK goal (0 = rotation before IK, 1 = rotation at the IK goal).\r\n         * @param goal The AvatarIKGoal that is queried.\r\n         */\r\n        GetIKRotationWeight(goal: any): number\r\n        /** Sets the rotational weight of an IK goal (0 = rotation before IK, 1 = rotation at the IK goal).\r\n         * @param goal The AvatarIKGoal that is set.\r\n         * @param value The rotational weight.\r\n         */\r\n        SetIKRotationWeight(goal: any, value: number): void\r\n        /** Gets the position of an IK hint.\r\n         * @param hint The AvatarIKHint that is queried.\r\n         * @returns Return the current position of this IK hint in world space. \r\n         */\r\n        GetIKHintPosition(hint: any): Vector3\r\n        /** Sets the position of an IK hint.\r\n         * @param hint The AvatarIKHint that is set.\r\n         * @param hintPosition The position in world space.\r\n         */\r\n        SetIKHintPosition(hint: any, hintPosition: Vector3): void\r\n        /** Gets the translative weight of an IK Hint (0 = at the original animation before IK, 1 = at the hint).\r\n         * @param hint The AvatarIKHint that is queried.\r\n         * @returns Return translative weight. \r\n         */\r\n        GetIKHintPositionWeight(hint: any): number\r\n        /** Sets the translative weight of an IK hint (0 = at the original animation before IK, 1 = at the hint).\r\n         * @param hint The AvatarIKHint that is set.\r\n         * @param value The translative weight.\r\n         */\r\n        SetIKHintPositionWeight(hint: any, value: number): void\r\n        /** Sets the look at position.\r\n         * @param lookAtPosition The position to lookAt.\r\n         */\r\n        SetLookAtPosition(lookAtPosition: Vector3): void\r\n        /** Set look at weights.\r\n         * @param weight (0-1) the global weight of the LookAt, multiplier for other parameters.\r\n         * @param bodyWeight (0-1) determines how much the body is involved in the LookAt.\r\n         * @param headWeight (0-1) determines how much the head is involved in the LookAt.\r\n         * @param eyesWeight (0-1) determines how much the eyes are involved in the LookAt.\r\n         * @param clampWeight (0-1) 0.0 means the character is completely unrestrained in motion, 1.0 means he's completely clamped (look at becomes impossible), and 0.5 means he'll be able to move on half of the possible range (180 degrees).\r\n         */\r\n        SetLookAtWeight(weight: number, bodyWeight: number, headWeight: number, eyesWeight: number, clampWeight: number): void\r\n        /** Set look at weights.\r\n         * @param weight (0-1) the global weight of the LookAt, multiplier for other parameters.\r\n         * @param bodyWeight (0-1) determines how much the body is involved in the LookAt.\r\n         * @param headWeight (0-1) determines how much the head is involved in the LookAt.\r\n         * @param eyesWeight (0-1) determines how much the eyes are involved in the LookAt.\r\n         * @param clampWeight (0-1) 0.0 means the character is completely unrestrained in motion, 1.0 means he's completely clamped (look at becomes impossible), and 0.5 means he'll be able to move on half of the possible range (180 degrees).\r\n         */\r\n        SetLookAtWeight(weight: number, bodyWeight: number, headWeight: number, eyesWeight: number): void\r\n        /** Set look at weights.\r\n         * @param weight (0-1) the global weight of the LookAt, multiplier for other parameters.\r\n         * @param bodyWeight (0-1) determines how much the body is involved in the LookAt.\r\n         * @param headWeight (0-1) determines how much the head is involved in the LookAt.\r\n         * @param eyesWeight (0-1) determines how much the eyes are involved in the LookAt.\r\n         * @param clampWeight (0-1) 0.0 means the character is completely unrestrained in motion, 1.0 means he's completely clamped (look at becomes impossible), and 0.5 means he'll be able to move on half of the possible range (180 degrees).\r\n         */\r\n        SetLookAtWeight(weight: number, bodyWeight: number, headWeight: number): void\r\n        /** Set look at weights.\r\n         * @param weight (0-1) the global weight of the LookAt, multiplier for other parameters.\r\n         * @param bodyWeight (0-1) determines how much the body is involved in the LookAt.\r\n         * @param headWeight (0-1) determines how much the head is involved in the LookAt.\r\n         * @param eyesWeight (0-1) determines how much the eyes are involved in the LookAt.\r\n         * @param clampWeight (0-1) 0.0 means the character is completely unrestrained in motion, 1.0 means he's completely clamped (look at becomes impossible), and 0.5 means he'll be able to move on half of the possible range (180 degrees).\r\n         */\r\n        SetLookAtWeight(weight: number, bodyWeight: number): void\r\n        /** Set look at weights.\r\n         * @param weight (0-1) the global weight of the LookAt, multiplier for other parameters.\r\n         * @param bodyWeight (0-1) determines how much the body is involved in the LookAt.\r\n         * @param headWeight (0-1) determines how much the head is involved in the LookAt.\r\n         * @param eyesWeight (0-1) determines how much the eyes are involved in the LookAt.\r\n         * @param clampWeight (0-1) 0.0 means the character is completely unrestrained in motion, 1.0 means he's completely clamped (look at becomes impossible), and 0.5 means he'll be able to move on half of the possible range (180 degrees).\r\n         */\r\n        SetLookAtWeight(weight: number): void\r\n        /** Sets local rotation of a human bone during a IK pass.\r\n         * @param humanBoneId The human bone Id.\r\n         * @param rotation The local rotation.\r\n         */\r\n        SetBoneLocalRotation(humanBoneId: any, rotation: Quaternion): void\r\n        GetBehaviours(fullPathHash: number, layerIndex: number): Array<any>\r\n        /** Returns the layer name.\r\n         * @param layerIndex The layer index.\r\n         * @returns The layer name. \r\n         */\r\n        GetLayerName(layerIndex: number): string\r\n        /** Returns the index of the layer with the given name.\r\n         * @param layerName The layer name.\r\n         * @returns The layer index. \r\n         */\r\n        GetLayerIndex(layerName: string): number\r\n        /** Returns the weight of the layer at the specified index.\r\n         * @param layerIndex The layer index.\r\n         * @returns The layer weight. \r\n         */\r\n        GetLayerWeight(layerIndex: number): number\r\n        /** Sets the weight of the layer at the given index.\r\n         * @param layerIndex The layer index.\r\n         * @param weight The new layer weight.\r\n         */\r\n        SetLayerWeight(layerIndex: number, weight: number): void\r\n        /** Returns an AnimatorStateInfo with the information on the current state.\r\n         * @param layerIndex The layer index.\r\n         * @returns An AnimatorStateInfo with the information on the current state. \r\n         */\r\n        GetCurrentAnimatorStateInfo(layerIndex: number): any\r\n        /** Returns an AnimatorStateInfo with the information on the next state.\r\n         * @param layerIndex The layer index.\r\n         * @returns An AnimatorStateInfo with the information on the next state. \r\n         */\r\n        GetNextAnimatorStateInfo(layerIndex: number): any\r\n        /** Returns an AnimatorTransitionInfo with the informations on the current transition.\r\n         * @param layerIndex The layer's index.\r\n         * @returns An AnimatorTransitionInfo with the informations on the current transition. \r\n         */\r\n        GetAnimatorTransitionInfo(layerIndex: number): any\r\n        /** Returns the number of AnimatorClipInfo in the current state.\r\n         * @param layerIndex The layer index.\r\n         * @returns The number of AnimatorClipInfo in the current state. \r\n         */\r\n        GetCurrentAnimatorClipInfoCount(layerIndex: number): number\r\n        /** Returns the number of AnimatorClipInfo in the next state.\r\n         * @param layerIndex The layer index.\r\n         * @returns The number of AnimatorClipInfo in the next state. \r\n         */\r\n        GetNextAnimatorClipInfoCount(layerIndex: number): number\r\n        GetCurrentAnimatorClipInfo(layerIndex: number, clips: any): void\r\n        /** Returns an array of all the AnimatorClipInfo in the current state of the given layer.\r\n         * @param layerIndex The layer index.\r\n         * @returns An array of all the AnimatorClipInfo in the current state. \r\n         */\r\n        GetCurrentAnimatorClipInfo(layerIndex: number): Array<any>\r\n        GetNextAnimatorClipInfo(layerIndex: number, clips: any): void\r\n        /** Returns an array of all the AnimatorClipInfo in the next state of the given layer.\r\n         * @param layerIndex The layer index.\r\n         * @returns An array of all the AnimatorClipInfo in the next state. \r\n         */\r\n        GetNextAnimatorClipInfo(layerIndex: number): Array<any>\r\n        /** Returns true if there is a transition on the given layer, false otherwise.\r\n         * @param layerIndex The layer index.\r\n         * @returns True if there is a transition on the given layer, false otherwise. \r\n         */\r\n        IsInTransition(layerIndex: number): boolean\r\n        /** See AnimatorController.parameters.\r\n         */\r\n        GetParameter(index: number): any\r\n        MatchTarget(matchPosition: Vector3, matchRotation: Quaternion, targetBodyPart: any, weightMask: any, startNormalizedTime: number, targetNormalizedTime: number, completeMatch: boolean): void\r\n        /** Automatically adjust the GameObject position and rotation.\r\n         * @param matchPosition The position we want the body part to reach.\r\n         * @param matchRotation The rotation in which we want the body part to be.\r\n         * @param targetBodyPart The body part that is involved in the match.\r\n         * @param weightMask Structure that contains weights for matching position and rotation.\r\n         * @param startNormalizedTime Start time within the animation clip (0 - beginning of clip, 1 - end of clip).\r\n         * @param targetNormalizedTime End time within the animation clip (0 - beginning of clip, 1 - end of clip), values greater than 1 can be set to trigger a match after a certain number of loops. Ex: 2.3 means at 30% of 2nd loop.\r\n         * @param completeMatch Allows you to specify what should happen if the MatchTarget function is interrupted. A value of true causes the GameObject to immediately move to the matchPosition if interrupted. A value of false causes the GameObject to stay at its current position if interrupted.\r\n         */\r\n        MatchTarget(matchPosition: Vector3, matchRotation: Quaternion, targetBodyPart: any, weightMask: any, startNormalizedTime: number, targetNormalizedTime: number): void\r\n        MatchTarget(matchPosition: Vector3, matchRotation: Quaternion, targetBodyPart: any, weightMask: any, startNormalizedTime: number): void\r\n        /** Interrupts the automatic target matching.\r\n         */\r\n        InterruptMatchTarget(completeMatch: boolean): void\r\n        InterruptMatchTarget(): void\r\n        /** Creates a crossfade from the current state to any other state using times in seconds.\r\n         * @param stateName The name of the state.\r\n         * @param stateHashName The hash name of the state.\r\n         * @param fixedTransitionDuration The duration of the transition (in seconds).\r\n         * @param layer The layer where the crossfade occurs.\r\n         * @param fixedTimeOffset The time of the state (in seconds).\r\n         * @param normalizedTransitionTime The time of the transition (normalized).\r\n         */\r\n        CrossFadeInFixedTime(stateName: string, fixedTransitionDuration: number, layer: number, fixedTimeOffset: number, normalizedTransitionTime: number): void\r\n        /** Creates a crossfade from the current state to any other state using times in seconds.\r\n         * @param stateName The name of the state.\r\n         * @param stateHashName The hash name of the state.\r\n         * @param fixedTransitionDuration The duration of the transition (in seconds).\r\n         * @param layer The layer where the crossfade occurs.\r\n         * @param fixedTimeOffset The time of the state (in seconds).\r\n         * @param normalizedTransitionTime The time of the transition (normalized).\r\n         */\r\n        CrossFadeInFixedTime(stateHashName: number, fixedTransitionDuration: number, layer: number, fixedTimeOffset: number, normalizedTransitionTime: number): void\r\n        CrossFadeInFixedTime(stateName: string, fixedTransitionDuration: number, layer: number, fixedTimeOffset: number): void\r\n        CrossFadeInFixedTime(stateHashName: number, fixedTransitionDuration: number, layer: number, fixedTimeOffset: number): void\r\n        CrossFadeInFixedTime(stateName: string, fixedTransitionDuration: number, layer: number): void\r\n        CrossFadeInFixedTime(stateHashName: number, fixedTransitionDuration: number, layer: number): void\r\n        CrossFadeInFixedTime(stateName: string, fixedTransitionDuration: number): void\r\n        CrossFadeInFixedTime(stateHashName: number, fixedTransitionDuration: number): void\r\n        WriteDefaultValues(): void\r\n        /** Creates a crossfade from the current state to any other state using normalized times.\r\n         * @param stateName The name of the state.\r\n         * @param stateHashName The hash name of the state.\r\n         * @param normalizedTransitionDuration The duration of the transition (normalized).\r\n         * @param layer The layer where the crossfade occurs.\r\n         * @param normalizedTimeOffset The time of the state (normalized).\r\n         * @param normalizedTransitionTime The time of the transition (normalized).\r\n         */\r\n        CrossFade(stateName: string, normalizedTransitionDuration: number, layer: number, normalizedTimeOffset: number, normalizedTransitionTime: number): void\r\n        /** Creates a crossfade from the current state to any other state using normalized times.\r\n         * @param stateName The name of the state.\r\n         * @param stateHashName The hash name of the state.\r\n         * @param normalizedTransitionDuration The duration of the transition (normalized).\r\n         * @param layer The layer where the crossfade occurs.\r\n         * @param normalizedTimeOffset The time of the state (normalized).\r\n         * @param normalizedTransitionTime The time of the transition (normalized).\r\n         */\r\n        CrossFade(stateHashName: number, normalizedTransitionDuration: number, layer: number, normalizedTimeOffset: number, normalizedTransitionTime: number): void\r\n        CrossFade(stateName: string, normalizedTransitionDuration: number, layer: number, normalizedTimeOffset: number): void\r\n        CrossFade(stateHashName: number, normalizedTransitionDuration: number, layer: number, normalizedTimeOffset: number): void\r\n        CrossFade(stateName: string, normalizedTransitionDuration: number, layer: number): void\r\n        CrossFade(stateHashName: number, normalizedTransitionDuration: number, layer: number): void\r\n        CrossFade(stateName: string, normalizedTransitionDuration: number): void\r\n        CrossFade(stateHashName: number, normalizedTransitionDuration: number): void\r\n        /** Plays a state.\r\n         * @param stateName The state name.\r\n         * @param stateNameHash The state hash name. If stateNameHash is 0, it changes the current state time.\r\n         * @param layer The layer index. If layer is -1, it plays the first state with the given state name or hash.\r\n         * @param fixedTime The time offset (in seconds).\r\n         */\r\n        PlayInFixedTime(stateName: string, layer: number, fixedTime: number): void\r\n        /** Plays a state.\r\n         * @param stateName The state name.\r\n         * @param stateNameHash The state hash name. If stateNameHash is 0, it changes the current state time.\r\n         * @param layer The layer index. If layer is -1, it plays the first state with the given state name or hash.\r\n         * @param fixedTime The time offset (in seconds).\r\n         */\r\n        PlayInFixedTime(stateNameHash: number, layer: number, fixedTime: number): void\r\n        PlayInFixedTime(stateName: string, layer: number): void\r\n        PlayInFixedTime(stateNameHash: number, layer: number): void\r\n        PlayInFixedTime(stateName: string): void\r\n        PlayInFixedTime(stateNameHash: number): void\r\n        /** Plays a state.\r\n         * @param stateName The state name.\r\n         * @param stateNameHash The state hash name. If stateNameHash is 0, it changes the current state time.\r\n         * @param layer The layer index. If layer is -1, it plays the first state with the given state name or hash.\r\n         * @param normalizedTime The time offset between zero and one.\r\n         */\r\n        Play(stateName: string, layer: number, normalizedTime: number): void\r\n        /** Plays a state.\r\n         * @param stateName The state name.\r\n         * @param stateNameHash The state hash name. If stateNameHash is 0, it changes the current state time.\r\n         * @param layer The layer index. If layer is -1, it plays the first state with the given state name or hash.\r\n         * @param normalizedTime The time offset between zero and one.\r\n         */\r\n        Play(stateNameHash: number, layer: number, normalizedTime: number): void\r\n        Play(stateName: string, layer: number): void\r\n        Play(stateNameHash: number, layer: number): void\r\n        Play(stateName: string): void\r\n        Play(stateNameHash: number): void\r\n        /** Sets an AvatarTarget and a targetNormalizedTime for the current state.\r\n         * @param targetIndex The avatar body part that is queried.\r\n         * @param targetNormalizedTime The current state Time that is queried.\r\n         */\r\n        SetTarget(targetIndex: any, targetNormalizedTime: number): void\r\n        /** Returns Transform mapped to this human bone id.\r\n         * @param humanBoneId The human bone that is queried, see enum HumanBodyBones for a list of possible values.\r\n         */\r\n        GetBoneTransform(humanBoneId: any): Transform\r\n        StartPlayback(): void\r\n        StopPlayback(): void\r\n        /** Sets the animator in recording mode, and allocates a circular buffer of size frameCount.\r\n         * @param frameCount The number of frames (updates) that will be recorded. If frameCount is 0, the recording will continue until the user calls StopRecording. The maximum value for frameCount is 10000.\r\n         */\r\n        StartRecording(frameCount: number): void\r\n        StopRecording(): void\r\n        /** Returns true if the state exists in this layer, false otherwise.\r\n         * @param layerIndex The layer index.\r\n         * @param stateID The state ID.\r\n         * @returns True if the state exists in this layer, false otherwise. \r\n         */\r\n        HasState(layerIndex: number, stateID: number): boolean\r\n        /** Evaluates the animator based on deltaTime.\r\n         * @param deltaTime The time delta.\r\n         */\r\n        Update(deltaTime: number): void\r\n        Rebind(): void\r\n        ApplyBuiltinRootMotion(): void\r\n        /** Creates a dependency between animator jobs and the job represented by the supplied job handle. To add multiple job dependencies, call this method for each job that need to run before the Animator's jobs.\r\n         * @param animator The Animator instance that calls this method.\r\n         * @param jobHandle The JobHandle of the job that needs to run before animator jobs.\r\n         */\r\n        AddJobDependency(jobHandle: any): void\r\n        /** Create a TransformStreamHandle representing the new binding between the Animator and a Transform already bound to the Animator.\r\n         * @param animator The Animator instance that calls this method.\r\n         * @param transform The Transform to bind.\r\n         * @returns Returns the TransformStreamHandle that represents the new binding. \r\n         */\r\n        BindStreamTransform(transform: Transform): any\r\n        /** Create a PropertyStreamHandle representing the new binding on the Component property of a Transform already bound to the Animator.\r\n         * @param animator The Animator instance that calls this method.\r\n         * @param transform The Transform to target.\r\n         * @param type The Component type.\r\n         * @param property The property to bind.\r\n         * @param isObjectReference isObjectReference need to be set to true if the property to bind does animate an Object like SpriteRenderer.sprite.\r\n         * @returns Returns the PropertyStreamHandle that represents the new binding. \r\n         */\r\n        BindStreamProperty(transform: Transform, type: any, property: string, isObjectReference: boolean): any\r\n        /** Create a PropertyStreamHandle representing the new binding on the Component property of a Transform already bound to the Animator.\r\n         * @param animator The Animator instance that calls this method.\r\n         * @param transform The Transform to target.\r\n         * @param type The Component type.\r\n         * @param property The property to bind.\r\n         * @param isObjectReference isObjectReference need to be set to true if the property to bind does animate an Object like SpriteRenderer.sprite.\r\n         * @returns Returns the PropertyStreamHandle that represents the new binding. \r\n         */\r\n        BindStreamProperty(transform: Transform, type: any, property: string): any\r\n        /** Create a custom property in the AnimationStream to pass extra data to downstream animation jobs in your graph. Custom properties created in the AnimationStream do not exist in the scene.\r\n         * @param animator The Animator instance that calls this method.\r\n         * @param name The name of the property.\r\n         * @param type The type of property to create (float, integer or boolean).\r\n         * @returns Returns the PropertyStreamHandle that represents the new binding. \r\n         */\r\n        BindCustomStreamProperty(property: string, type: any): any\r\n        /** Create a TransformSceneHandle representing the new binding between the Animator and a Transform in the Scene.\r\n         * @param animator The Animator instance that calls this method.\r\n         * @param transform The Transform to bind.\r\n         * @returns Returns the TransformSceneHandle that represents the new binding. \r\n         */\r\n        BindSceneTransform(transform: Transform): any\r\n        /** Create a PropertySceneHandle representing the new binding on the Component property of a Transform in the Scene.\r\n         * @param animator The Animator instance that calls this method.\r\n         * @param transform The Transform to target.\r\n         * @param type The Component type.\r\n         * @param property The property to bind.\r\n         * @param isObjectReference isObjectReference need to be set to true if the property to bind does access an Object like SpriteRenderer.sprite.\r\n         * @returns Returns the PropertySceneHandle that represents the new binding. \r\n         */\r\n        BindSceneProperty(transform: Transform, type: any, property: string, isObjectReference: boolean): any\r\n        /** Create a PropertySceneHandle representing the new binding on the Component property of a Transform in the Scene.\r\n         * @param animator The Animator instance that calls this method.\r\n         * @param transform The Transform to target.\r\n         * @param type The Component type.\r\n         * @param property The property to bind.\r\n         * @param isObjectReference isObjectReference need to be set to true if the property to bind does access an Object like SpriteRenderer.sprite.\r\n         * @returns Returns the PropertySceneHandle that represents the new binding. \r\n         */\r\n        BindSceneProperty(transform: Transform, type: any, property: string): any\r\n        /** Open a new stream on the Animator.\r\n         * @param animator The Animator instance that calls this method.\r\n         * @param stream The new stream.\r\n         * @returns Returns whether or not the stream has been opened. \r\n         */\r\n        OpenAnimationStream(stream: jsb.Ref<any>): boolean\r\n        /** Close a stream that has been opened using OpenAnimationStream.\r\n         * @param animator The Animator instance that calls this method.\r\n         * @param stream The stream to close.\r\n         */\r\n        CloseAnimationStream(stream: jsb.Ref<any>): void\r\n        /** Newly created handles are always resolved lazily on the next access when the jobs are run. To avoid a cpu spike while evaluating the jobs you can manually resolve all handles from the main thread.\r\n         * @param animator The Animator instance that calls this method.\r\n         */\r\n        ResolveAllStreamHandles(): void\r\n        /** Newly created handles are always resolved lazily on the next access when the jobs are run. To avoid a cpu spike while evaluating the jobs you can manually resolve all handles from the main thread.\r\n         * @param animator The Animator instance that calls this method.\r\n         */\r\n        ResolveAllSceneHandles(): void\r\n        /** Generates an parameter id from a string.\r\n         * @param name The string to convert to Id.\r\n         */\r\n        static StringToHash(name: string): number\r\n        /** Returns true if the current rig is optimizable with AnimatorUtility.OptimizeTransformHierarchy.\r\n         */\r\n        readonly isOptimizable: boolean\r\n        /** Returns true if the current rig is humanoid, false if it is generic.\r\n         */\r\n        readonly isHuman: boolean\r\n        /** Returns true if the current rig has root motion.\r\n         */\r\n        readonly hasRootMotion: boolean\r\n        /** Returns the scale of the current Avatar for a humanoid rig, (1 by default if the rig is generic).\r\n         */\r\n        readonly humanScale: number\r\n        /** Returns whether the animator is initialized successfully.\r\n         */\r\n        readonly isInitialized: boolean\r\n        /** Gets the avatar delta position for the last evaluated frame.\r\n         */\r\n        readonly deltaPosition: Vector3\r\n        /** Gets the avatar delta rotation for the last evaluated frame.\r\n         */\r\n        readonly deltaRotation: Quaternion\r\n        /** Gets the avatar velocity  for the last evaluated frame.\r\n         */\r\n        readonly velocity: Vector3\r\n        /** Gets the avatar angular velocity for the last evaluated frame.\r\n         */\r\n        readonly angularVelocity: Vector3\r\n        /** The root position, the position of the game object.\r\n         */\r\n        rootPosition: Vector3\r\n        /** The root rotation, the rotation of the game object.\r\n         */\r\n        rootRotation: Quaternion\r\n        /** Should root motion be applied?\r\n         */\r\n        applyRootMotion: boolean\r\n        /** Specifies the update mode of the Animator.\r\n         */\r\n        updateMode: any\r\n        /** Returns true if the object has a transform hierarchy.\r\n         */\r\n        readonly hasTransformHierarchy: boolean\r\n        /** The current gravity weight based on current animations that are played.\r\n         */\r\n        readonly gravityWeight: number\r\n        /** The position of the body center of mass.\r\n         */\r\n        bodyPosition: Vector3\r\n        /** The rotation of the body center of mass.\r\n         */\r\n        bodyRotation: Quaternion\r\n        /** Automatic stabilization of feet during transition and blending.\r\n         */\r\n        stabilizeFeet: boolean\r\n        /** Returns the number of layers in the controller.\r\n         */\r\n        readonly layerCount: number\r\n        /** The AnimatorControllerParameter list used by the animator. (Read Only)\r\n         */\r\n        readonly parameters: Array<any>\r\n        /** Returns the number of parameters in the controller.\r\n         */\r\n        readonly parameterCount: number\r\n        /** Blends pivot point between body center of mass and feet pivot.\r\n         */\r\n        feetPivotActive: number\r\n        /** Gets the pivot weight.\r\n         */\r\n        readonly pivotWeight: number\r\n        /** Get the current position of the pivot.\r\n         */\r\n        readonly pivotPosition: Vector3\r\n        /** If automatic matching is active.\r\n         */\r\n        readonly isMatchingTarget: boolean\r\n        /** The playback speed of the Animator. 1 is normal playback speed.\r\n         */\r\n        speed: number\r\n        /** Returns the position of the target specified by SetTarget.\r\n         */\r\n        readonly targetPosition: Vector3\r\n        /** Returns the rotation of the target specified by SetTarget.\r\n         */\r\n        readonly targetRotation: Quaternion\r\n        /** Controls culling of this Animator component.\r\n         */\r\n        cullingMode: any\r\n        /** Sets the playback position in the recording buffer.\r\n         */\r\n        playbackTime: number\r\n        /** Start time of the first frame of the buffer relative to the frame at which StartRecording was called.\r\n         */\r\n        recorderStartTime: number\r\n        /** End time of the recorded clip relative to when StartRecording was called.\r\n         */\r\n        recorderStopTime: number\r\n        /** Gets the mode of the Animator recorder.\r\n         */\r\n        readonly recorderMode: any\r\n        /** The runtime representation of AnimatorController that controls the Animator.\r\n         */\r\n        runtimeAnimatorController: any\r\n        /** Returns true if Animator has any playables assigned to it.\r\n         */\r\n        readonly hasBoundPlayables: boolean\r\n        /** Gets/Sets the current Avatar.\r\n         */\r\n        avatar: any\r\n        /** The PlayableGraph created by the Animator.\r\n         */\r\n        readonly playableGraph: any\r\n        /** Additional layers affects the center of mass.\r\n         */\r\n        layersAffectMassCenter: boolean\r\n        /** Get left foot bottom height.\r\n         */\r\n        readonly leftFeetBottomHeight: number\r\n        /** Get right foot bottom height.\r\n         */\r\n        readonly rightFeetBottomHeight: number\r\n        logWarnings: boolean\r\n        /** Sets whether the Animator sends events of type AnimationEvent.\r\n         */\r\n        fireEvents: boolean\r\n        /** Controls the behaviour of the Animator component when a GameObject is disabled.\r\n         */\r\n        keepAnimatorControllerStateOnDisable: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Enum } from \"System\";\r\n    /** The AnimationState gives full control over animation blending.\r\n     */\r\n    class AnimationState extends TrackedReference {\r\n        constructor()\r\n        /** Adds a transform which should be animated. This allows you to reduce the number of animations you have to create.\r\n         * @param mix The transform to animate.\r\n         * @param recursive Whether to also animate all children of the specified transform.\r\n         */\r\n        AddMixingTransform(mix: Transform, recursive: boolean): void\r\n        /** Adds a transform which should be animated. This allows you to reduce the number of animations you have to create.\r\n         * @param mix The transform to animate.\r\n         * @param recursive Whether to also animate all children of the specified transform.\r\n         */\r\n        AddMixingTransform(mix: Transform): void\r\n        /** Removes a transform which should be animated.\r\n         */\r\n        RemoveMixingTransform(mix: Transform): void\r\n        /** Enables / disables the animation.\r\n         */\r\n        enabled: boolean\r\n        /** The weight of animation.\r\n         */\r\n        weight: number\r\n        /** Wrapping mode of the animation.\r\n         */\r\n        wrapMode: WrapMode\r\n        /** The current time of the animation.\r\n         */\r\n        time: number\r\n        /** The normalized time of the animation.\r\n         */\r\n        normalizedTime: number\r\n        /** The playback speed of the animation. 1 is normal playback speed.\r\n         */\r\n        speed: number\r\n        /** The normalized playback speed.\r\n         */\r\n        normalizedSpeed: number\r\n        /** The length of the animation clip in seconds.\r\n         */\r\n        readonly length: number\r\n        layer: number\r\n        /** The clip that is being played by this animation state.\r\n         */\r\n        readonly clip: AnimationClip\r\n        /** The name of the animation.\r\n         */\r\n        name: string\r\n        /** Which blend mode should be used?\r\n         */\r\n        blendMode: any\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Object as Object1 } from \"System\";\r\n    class TrackedReference extends Object1 {\r\n        Equals(o: Object1): boolean\r\n        GetHashCode(): number\r\n        static op_Equality(x: TrackedReference, y: TrackedReference): boolean\r\n        static op_Inequality(x: TrackedReference, y: TrackedReference): boolean\r\n        static op_Implicit(exists: TrackedReference): boolean\r\n        // js_op_overloading: static ==(x: TrackedReference, y: TrackedReference): boolean\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"System\" {\r\n    class Object {\r\n        constructor()\r\n        Equals(obj: Object): boolean\r\n        GetHashCode(): number\r\n        GetType(): any\r\n        toString(): string\r\n        static Equals(objA: Object, objB: Object): boolean\r\n        static ReferenceEquals(objA: Object, objB: Object): boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Enum } from \"System\";\r\n    /** Determines how time is treated outside of the keyframed range of an AnimationClip or AnimationCurve.\r\n     */\r\n    enum WrapMode {\r\n        /** Reads the default repeat mode set higher up.\r\n         */\r\n        Default = 0,\r\n        Once = 1,\r\n        Clamp = 1,\r\n        /** When time reaches the end of the animation clip, time will continue at the beginning.\r\n         */\r\n        Loop = 2,\r\n        /** When time reaches the end of the animation clip, time will ping pong back between beginning and end.\r\n         */\r\n        PingPong = 4,\r\n        /** Plays back the animation. When it reaches the end, it will keep playing the last frame and never stop playing.\r\n         */\r\n        ClampForever = 8,\r\n    }\r\n}\r\ndeclare module \"System\" {\r\n    import * as jsb from \"jsb\";\r\n    abstract class Enum extends ValueType {\r\n        Equals(obj: Object): boolean\r\n        GetHashCode(): number\r\n        toString(format: string): string\r\n        toString(): string\r\n        CompareTo(target: Object): number\r\n        HasFlag(flag: Enum): boolean\r\n        GetTypeCode(): any\r\n        static Parse(enumType: any, value: string, ignoreCase: boolean): Object\r\n        static Parse(enumType: any, value: string): Object\r\n        static GetUnderlyingType(enumType: any): any\r\n        static GetValues(enumType: any): Array<any>\r\n        static GetName(enumType: any, value: Object): string\r\n        static GetNames(enumType: any): Array<string>\r\n        static ToObject(enumType: any, value: Object): Object\r\n        static ToObject(enumType: any, value: number): Object\r\n        static ToObject(enumType: any, value: number): Object\r\n        static ToObject(enumType: any, value: number): Object\r\n        static ToObject(enumType: any, value: jsb.byte): Object\r\n        static ToObject(enumType: any, value: number): Object\r\n        static ToObject(enumType: any, value: number): Object\r\n        static ToObject(enumType: any, value: number): Object\r\n        static ToObject(enumType: any, value: number): Object\r\n        static IsDefined(enumType: any, value: Object): boolean\r\n        static Format(enumType: any, value: Object, format: string): string\r\n    }\r\n}\r\ndeclare module \"System\" {\r\n    abstract class ValueType extends Object {\r\n        Equals(obj: Object): boolean\r\n        GetHashCode(): number\r\n        toString(): string\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object as Object1, Enum, Array, Exception } from \"System\";\r\n    /** Class containing methods to ease debugging while developing a game.\r\n     */\r\n    class Debug extends Object1 {\r\n        constructor()\r\n        /** Draws a line between specified start and end points.\r\n         * @param start Point in world space where the line should start.\r\n         * @param end Point in world space where the line should end.\r\n         * @param color Color of the line.\r\n         * @param duration How long the line should be visible for.\r\n         * @param depthTest Should the line be obscured by objects closer to the camera?\r\n         */\r\n        static DrawLine(start: Vector3, end: Vector3, color: Color, duration: number, depthTest: boolean): void\r\n        /** Draws a line between specified start and end points.\r\n         * @param start Point in world space where the line should start.\r\n         * @param end Point in world space where the line should end.\r\n         * @param color Color of the line.\r\n         * @param duration How long the line should be visible for.\r\n         * @param depthTest Should the line be obscured by objects closer to the camera?\r\n         */\r\n        static DrawLine(start: Vector3, end: Vector3, color: Color, duration: number): void\r\n        /** Draws a line between specified start and end points.\r\n         * @param start Point in world space where the line should start.\r\n         * @param end Point in world space where the line should end.\r\n         * @param color Color of the line.\r\n         * @param duration How long the line should be visible for.\r\n         * @param depthTest Should the line be obscured by objects closer to the camera?\r\n         */\r\n        static DrawLine(start: Vector3, end: Vector3, color: Color): void\r\n        /** Draws a line between specified start and end points.\r\n         * @param start Point in world space where the line should start.\r\n         * @param end Point in world space where the line should end.\r\n         * @param color Color of the line.\r\n         * @param duration How long the line should be visible for.\r\n         * @param depthTest Should the line be obscured by objects closer to the camera?\r\n         */\r\n        static DrawLine(start: Vector3, end: Vector3): void\r\n        /** Draws a line from start to start + dir in world coordinates.\r\n         * @param start Point in world space where the ray should start.\r\n         * @param dir Direction and length of the ray.\r\n         * @param color Color of the drawn line.\r\n         * @param duration How long the line will be visible for (in seconds).\r\n         * @param depthTest Should the line be obscured by other objects closer to the camera?\r\n         */\r\n        static DrawRay(start: Vector3, dir: Vector3, color: Color, duration: number, depthTest: boolean): void\r\n        /** Draws a line from start to start + dir in world coordinates.\r\n         * @param start Point in world space where the ray should start.\r\n         * @param dir Direction and length of the ray.\r\n         * @param color Color of the drawn line.\r\n         * @param duration How long the line will be visible for (in seconds).\r\n         * @param depthTest Should the line be obscured by other objects closer to the camera?\r\n         */\r\n        static DrawRay(start: Vector3, dir: Vector3, color: Color, duration: number): void\r\n        /** Draws a line from start to start + dir in world coordinates.\r\n         * @param start Point in world space where the ray should start.\r\n         * @param dir Direction and length of the ray.\r\n         * @param color Color of the drawn line.\r\n         * @param duration How long the line will be visible for (in seconds).\r\n         * @param depthTest Should the line be obscured by other objects closer to the camera?\r\n         */\r\n        static DrawRay(start: Vector3, dir: Vector3, color: Color): void\r\n        /** Draws a line from start to start + dir in world coordinates.\r\n         * @param start Point in world space where the ray should start.\r\n         * @param dir Direction and length of the ray.\r\n         * @param color Color of the drawn line.\r\n         * @param duration How long the line will be visible for (in seconds).\r\n         * @param depthTest Should the line be obscured by other objects closer to the camera?\r\n         */\r\n        static DrawRay(start: Vector3, dir: Vector3): void\r\n        static Break(): void\r\n        static DebugBreak(): void\r\n        /** Logs a message to the Unity Console.\r\n         * @param message String or object to be converted to string representation for display.\r\n         * @param context Object to which the message applies.\r\n         */\r\n        static Log(message: Object1, context: Object): void\r\n        /** Logs a message to the Unity Console.\r\n         * @param message String or object to be converted to string representation for display.\r\n         * @param context Object to which the message applies.\r\n         */\r\n        static Log(message: Object1): void\r\n        /** Logs a formatted message to the Unity Console.\r\n         * @param format A composite format string.\r\n         * @param args Format arguments.\r\n         * @param context Object to which the message applies.\r\n         * @param logType Type of message e.g. warn or error etc.\r\n         * @param logOptions Option flags to treat the log message special.\r\n         */\r\n        static LogFormat(logType: any, logOptions: any, context: Object, format: string, ...args: Object1[]): void\r\n        /** Logs a formatted message to the Unity Console.\r\n         * @param format A composite format string.\r\n         * @param args Format arguments.\r\n         * @param context Object to which the message applies.\r\n         * @param logType Type of message e.g. warn or error etc.\r\n         * @param logOptions Option flags to treat the log message special.\r\n         */\r\n        static LogFormat(context: Object, format: string, ...args: Object1[]): void\r\n        /** Logs a formatted message to the Unity Console.\r\n         * @param format A composite format string.\r\n         * @param args Format arguments.\r\n         * @param context Object to which the message applies.\r\n         * @param logType Type of message e.g. warn or error etc.\r\n         * @param logOptions Option flags to treat the log message special.\r\n         */\r\n        static LogFormat(format: string, ...args: Object1[]): void\r\n        /** A variant of Debug.Log that logs an error message to the console.\r\n         * @param message String or object to be converted to string representation for display.\r\n         * @param context Object to which the message applies.\r\n         */\r\n        static LogError(message: Object1, context: Object): void\r\n        /** A variant of Debug.Log that logs an error message to the console.\r\n         * @param message String or object to be converted to string representation for display.\r\n         * @param context Object to which the message applies.\r\n         */\r\n        static LogError(message: Object1): void\r\n        /** Logs a formatted error message to the Unity console.\r\n         * @param format A composite format string.\r\n         * @param args Format arguments.\r\n         * @param context Object to which the message applies.\r\n         */\r\n        static LogErrorFormat(context: Object, format: string, ...args: Object1[]): void\r\n        /** Logs a formatted error message to the Unity console.\r\n         * @param format A composite format string.\r\n         * @param args Format arguments.\r\n         * @param context Object to which the message applies.\r\n         */\r\n        static LogErrorFormat(format: string, ...args: Object1[]): void\r\n        static ClearDeveloperConsole(): void\r\n        /** A variant of Debug.Log that logs an error message to the console.\r\n         * @param context Object to which the message applies.\r\n         * @param exception Runtime Exception.\r\n         */\r\n        static LogException(exception: Exception, context: Object): void\r\n        /** A variant of Debug.Log that logs an error message to the console.\r\n         * @param context Object to which the message applies.\r\n         * @param exception Runtime Exception.\r\n         */\r\n        static LogException(exception: Exception): void\r\n        /** A variant of Debug.Log that logs a warning message to the console.\r\n         * @param message String or object to be converted to string representation for display.\r\n         * @param context Object to which the message applies.\r\n         */\r\n        static LogWarning(message: Object1, context: Object): void\r\n        /** A variant of Debug.Log that logs a warning message to the console.\r\n         * @param message String or object to be converted to string representation for display.\r\n         * @param context Object to which the message applies.\r\n         */\r\n        static LogWarning(message: Object1): void\r\n        /** Logs a formatted warning message to the Unity Console.\r\n         * @param format A composite format string.\r\n         * @param args Format arguments.\r\n         * @param context Object to which the message applies.\r\n         */\r\n        static LogWarningFormat(context: Object, format: string, ...args: Object1[]): void\r\n        /** Logs a formatted warning message to the Unity Console.\r\n         * @param format A composite format string.\r\n         * @param args Format arguments.\r\n         * @param context Object to which the message applies.\r\n         */\r\n        static LogWarningFormat(format: string, ...args: Object1[]): void\r\n        /** Assert a condition and logs an error message to the Unity console on failure.\r\n         * @param condition Condition you expect to be true.\r\n         * @param context Object to which the message applies.\r\n         * @param message String or object to be converted to string representation for display.\r\n         */\r\n        static Assert(condition: boolean, message: Object1, context: Object): void\r\n        static Assert(condition: boolean, message: string, context: Object): void\r\n        /** Assert a condition and logs an error message to the Unity console on failure.\r\n         * @param condition Condition you expect to be true.\r\n         * @param context Object to which the message applies.\r\n         * @param message String or object to be converted to string representation for display.\r\n         */\r\n        static Assert(condition: boolean, context: Object): void\r\n        /** Assert a condition and logs an error message to the Unity console on failure.\r\n         * @param condition Condition you expect to be true.\r\n         * @param context Object to which the message applies.\r\n         * @param message String or object to be converted to string representation for display.\r\n         */\r\n        static Assert(condition: boolean, message: Object1): void\r\n        static Assert(condition: boolean, message: string): void\r\n        /** Assert a condition and logs an error message to the Unity console on failure.\r\n         * @param condition Condition you expect to be true.\r\n         * @param context Object to which the message applies.\r\n         * @param message String or object to be converted to string representation for display.\r\n         */\r\n        static Assert(condition: boolean): void\r\n        /** Assert a condition and logs a formatted error message to the Unity console on failure.\r\n         * @param condition Condition you expect to be true.\r\n         * @param format A composite format string.\r\n         * @param args Format arguments.\r\n         * @param context Object to which the message applies.\r\n         */\r\n        static AssertFormat(condition: boolean, context: Object, format: string, ...args: Object1[]): void\r\n        /** Assert a condition and logs a formatted error message to the Unity console on failure.\r\n         * @param condition Condition you expect to be true.\r\n         * @param format A composite format string.\r\n         * @param args Format arguments.\r\n         * @param context Object to which the message applies.\r\n         */\r\n        static AssertFormat(condition: boolean, format: string, ...args: Object1[]): void\r\n        /** A variant of Debug.Log that logs an assertion message to the console.\r\n         * @param message String or object to be converted to string representation for display.\r\n         * @param context Object to which the message applies.\r\n         */\r\n        static LogAssertion(message: Object1, context: Object): void\r\n        /** A variant of Debug.Log that logs an assertion message to the console.\r\n         * @param message String or object to be converted to string representation for display.\r\n         * @param context Object to which the message applies.\r\n         */\r\n        static LogAssertion(message: Object1): void\r\n        /** Logs a formatted assertion message to the Unity console.\r\n         * @param format A composite format string.\r\n         * @param args Format arguments.\r\n         * @param context Object to which the message applies.\r\n         */\r\n        static LogAssertionFormat(context: Object, format: string, ...args: Object1[]): void\r\n        /** Logs a formatted assertion message to the Unity console.\r\n         * @param format A composite format string.\r\n         * @param args Format arguments.\r\n         * @param context Object to which the message applies.\r\n         */\r\n        static LogAssertionFormat(format: string, ...args: Object1[]): void\r\n        /** Get default debug logger.\r\n         */\r\n        static readonly unityLogger: any\r\n        /** Reports whether the development console is visible. The development console cannot be made to appear using:\r\n         */\r\n        static developerConsoleVisible: boolean\r\n        /** In the Build Settings dialog there is a check box called \"Development Build\".\r\n         */\r\n        static readonly isDebugBuild: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    /** Suspends the coroutine execution for the given amount of seconds using scaled time.\r\n     */\r\n    class WaitForSeconds extends YieldInstruction {\r\n        constructor(seconds: number)\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Object as Object1 } from \"System\";\r\n    /** Base class for all yield instructions.\r\n     */\r\n    class YieldInstruction extends Object1 {\r\n        constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    /** Waits until the end of the frame after Unity has rendererd every Camera and GUI, just before displaying the frame on screen.\r\n     */\r\n    class WaitForEndOfFrame extends YieldInstruction {\r\n        constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object as Object1, Enum, Array, ValueType } from \"System\";\r\n    /** Interface into the Input system.\r\n     */\r\n    class Input extends Object1 {\r\n        constructor()\r\n        /** Returns the value of the virtual axis identified by axisName.\r\n         */\r\n        static GetAxis(axisName: string): number\r\n        /** Returns the value of the virtual axis identified by axisName with no smoothing filtering applied.\r\n         */\r\n        static GetAxisRaw(axisName: string): number\r\n        /** Returns true while the virtual button identified by buttonName is held down.\r\n         * @param buttonName The name of the button such as Jump.\r\n         * @returns True when an axis has been pressed and not released. \r\n         */\r\n        static GetButton(buttonName: string): boolean\r\n        /** Returns true during the frame the user pressed down the virtual button identified by buttonName.\r\n         */\r\n        static GetButtonDown(buttonName: string): boolean\r\n        /** Returns true the first frame the user releases the virtual button identified by buttonName.\r\n         */\r\n        static GetButtonUp(buttonName: string): boolean\r\n        /** Returns whether the given mouse button is held down.\r\n         */\r\n        static GetMouseButton(button: number): boolean\r\n        /** Returns true during the frame the user pressed the given mouse button.\r\n         */\r\n        static GetMouseButtonDown(button: number): boolean\r\n        /** Returns true during the frame the user releases the given mouse button.\r\n         */\r\n        static GetMouseButtonUp(button: number): boolean\r\n        static ResetInputAxes(): void\r\n        static GetJoystickNames(): Array<string>\r\n        /** Call Input.GetTouch to obtain a Touch struct.\r\n         * @param index The touch input on the device screen.\r\n         * @returns Touch details in the struct. \r\n         */\r\n        static GetTouch(index: number): any\r\n        /** Returns specific acceleration measurement which occurred during last frame. (Does not allocate temporary variables).\r\n         */\r\n        static GetAccelerationEvent(index: number): any\r\n        /** Returns true while the user holds down the key identified by the key KeyCode enum parameter.\r\n         */\r\n        static GetKey(key: KeyCode): boolean\r\n        /** Returns true while the user holds down the key identified by name.\r\n         */\r\n        static GetKey(name: string): boolean\r\n        /** Returns true during the frame the user releases the key identified by the key KeyCode enum parameter.\r\n         */\r\n        static GetKeyUp(key: KeyCode): boolean\r\n        /** Returns true during the frame the user releases the key identified by name.\r\n         */\r\n        static GetKeyUp(name: string): boolean\r\n        /** Returns true during the frame the user starts pressing down the key identified by the key KeyCode enum parameter.\r\n         */\r\n        static GetKeyDown(key: KeyCode): boolean\r\n        /** Returns true during the frame the user starts pressing down the key identified by name.\r\n         */\r\n        static GetKeyDown(name: string): boolean\r\n        /** Enables/Disables mouse simulation with touches. By default this option is enabled.\r\n         */\r\n        static simulateMouseWithTouches: boolean\r\n        /** Is any key or mouse button currently held down? (Read Only)\r\n         */\r\n        static readonly anyKey: boolean\r\n        /** Returns true the first frame the user hits any key or mouse button. (Read Only)\r\n         */\r\n        static readonly anyKeyDown: boolean\r\n        /** Returns the keyboard input entered this frame. (Read Only)\r\n         */\r\n        static readonly inputString: string\r\n        /** The current mouse position in pixel coordinates. (Read Only).\r\n         */\r\n        static readonly mousePosition: Vector3\r\n        /** The current mouse scroll delta. (Read Only)\r\n         */\r\n        static readonly mouseScrollDelta: Vector2\r\n        /** Controls enabling and disabling of IME input composition.\r\n         */\r\n        static imeCompositionMode: any\r\n        /** The current IME composition string being typed by the user.\r\n         */\r\n        static readonly compositionString: string\r\n        /** Does the user have an IME keyboard input source selected?\r\n         */\r\n        static readonly imeIsSelected: boolean\r\n        /** The current text input position used by IMEs to open windows.\r\n         */\r\n        static compositionCursorPos: Vector2\r\n        /** Indicates if a mouse device is detected.\r\n         */\r\n        static readonly mousePresent: boolean\r\n        /** Number of touches. Guaranteed not to change throughout the frame. (Read Only)\r\n         */\r\n        static readonly touchCount: number\r\n        /** Bool value which let's users check if touch pressure is supported.\r\n         */\r\n        static readonly touchPressureSupported: boolean\r\n        /** Returns true when Stylus Touch is supported by a device or platform.\r\n         */\r\n        static readonly stylusTouchSupported: boolean\r\n        /** Returns whether the device on which application is currently running supports touch input.\r\n         */\r\n        static readonly touchSupported: boolean\r\n        /** Property indicating whether the system handles multiple touches.\r\n         */\r\n        static multiTouchEnabled: boolean\r\n        /** Device physical orientation as reported by OS. (Read Only)\r\n         */\r\n        static readonly deviceOrientation: any\r\n        /** Last measured linear acceleration of a device in three-dimensional space. (Read Only)\r\n         */\r\n        static readonly acceleration: Vector3\r\n        /** This property controls if input sensors should be compensated for screen orientation.\r\n         */\r\n        static compensateSensors: boolean\r\n        /** Number of acceleration measurements which occurred during last frame.\r\n         */\r\n        static readonly accelerationEventCount: number\r\n        /** Should  Back button quit the application?\n\nOnly usable on Android, Windows Phone or Windows Tablets.\r\n         */\r\n        static backButtonLeavesApp: boolean\r\n        /** Property for accessing device location (handheld devices only). (Read Only)\r\n         */\r\n        static readonly location: any\r\n        /** Property for accessing compass (handheld devices only). (Read Only)\r\n         */\r\n        static readonly compass: any\r\n        /** Returns default gyroscope.\r\n         */\r\n        static readonly gyro: any\r\n        /** Returns list of objects representing status of all touches during last frame. (Read Only) (Allocates temporary variables).\r\n         */\r\n        static readonly touches: Array<any>\r\n        /** Returns list of acceleration measurements which occurred during the last frame. (Read Only) (Allocates temporary variables).\r\n         */\r\n        static readonly accelerationEvents: Array<any>\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object as Object1, Enum, Array } from \"System\";\r\n    /** Access to application run-time data.\r\n     */\r\n    class Application extends Object1 {\r\n        constructor()\r\n        static Quit(exitCode: number): void\r\n        static Quit(): void\r\n        static Unload(): void\r\n        /** Can the streamed level be loaded?\r\n         */\r\n        static CanStreamedLevelBeLoaded(levelIndex: number): boolean\r\n        /** Can the streamed level be loaded?\r\n         */\r\n        static CanStreamedLevelBeLoaded(levelName: string): boolean\r\n        /** Returns true if the given object is part of the playing world either in any kind of built Player or in Play Mode.\r\n         * @param obj The object to test.\r\n         * @returns True if the object is part of the playing world. \r\n         */\r\n        static IsPlaying(obj: Object): boolean\r\n        static GetBuildTags(): Array<string>\r\n        /** Set an array of feature tags for this build.\r\n         */\r\n        static SetBuildTags(buildTags: Array<string>): void\r\n        static HasProLicense(): boolean\r\n        static RequestAdvertisingIdentifierAsync(delegateMethod: (advertisingId: string, trackingEnabled: boolean, errorMsg: string) => void): boolean\r\n        /** Opens the URL specified, subject to the permissions and limitations of your app’s current platform and environment. This is handled in different ways depending on the nature of the URL, and with different security restrictions, depending on the runtime platform.\r\n         * @param url The URL to open.\r\n         */\r\n        static OpenURL(url: string): void\r\n        /** Get stack trace logging options. The default value is StackTraceLogType.ScriptOnly.\r\n         */\r\n        static GetStackTraceLogType(logType: any): any\r\n        /** Set stack trace logging options. The default value is StackTraceLogType.ScriptOnly.\r\n         */\r\n        static SetStackTraceLogType(logType: any, stackTraceType: any): void\r\n        /** Request authorization to use the webcam or microphone on iOS.\r\n         */\r\n        static RequestUserAuthorization(mode: any): any\r\n        /** Check if the user has authorized use of the webcam or microphone in the Web Player.\r\n         */\r\n        static HasUserAuthorization(mode: any): boolean\r\n        /** Returns true when called in any kind of built Player, or when called in the Editor in Play Mode (Read Only).\r\n         */\r\n        static readonly isPlaying: boolean\r\n        /** Whether the player currently has focus. Read-only.\r\n         */\r\n        static readonly isFocused: boolean\r\n        /** Returns a GUID for this build (Read Only).\r\n         */\r\n        static readonly buildGUID: string\r\n        /** Should the player be running when the application is in the background?\r\n         */\r\n        static runInBackground: boolean\r\n        /** Returns true when Unity is launched with the -batchmode flag from the command line (Read Only).\r\n         */\r\n        static readonly isBatchMode: boolean\r\n        /** Contains the path to the game data folder on the target device (Read Only).\r\n         */\r\n        static readonly dataPath: string\r\n        /** The path to the StreamingAssets folder (Read Only).\r\n         */\r\n        static readonly streamingAssetsPath: string\r\n        /** (Read Only) Contains the path to a persistent data directory.\r\n         */\r\n        static readonly persistentDataPath: string\r\n        /** Contains the path to a temporary data / cache directory (Read Only).\r\n         */\r\n        static readonly temporaryCachePath: string\r\n        /** The URL of the document. For WebGL, this a web URL. For Android, iOS, or Universal Windows Platform (UWP) this is a deep link URL. (Read Only)\r\n         */\r\n        static readonly absoluteURL: string\r\n        /** The version of the Unity runtime used to play the content.\r\n         */\r\n        static readonly unityVersion: string\r\n        /** Returns application version number  (Read Only).\r\n         */\r\n        static readonly version: string\r\n        /** Returns the name of the store or package that installed the application (Read Only).\r\n         */\r\n        static readonly installerName: string\r\n        /** Returns application identifier at runtime. On Apple platforms this is the 'bundleIdentifier' saved in the info.plist file, on Android it's the 'package' from the AndroidManifest.xml. \r\n         */\r\n        static readonly identifier: string\r\n        /** Returns application install mode (Read Only).\r\n         */\r\n        static readonly installMode: any\r\n        /** Returns application running in sandbox (Read Only).\r\n         */\r\n        static readonly sandboxType: any\r\n        /** Returns application product name (Read Only).\r\n         */\r\n        static readonly productName: string\r\n        /** Return application company name (Read Only).\r\n         */\r\n        static readonly companyName: string\r\n        /** A unique cloud project identifier. It is unique for every project (Read Only).\r\n         */\r\n        static readonly cloudProjectId: string\r\n        /** Instructs the game to try to render at a specified frame rate.\r\n         */\r\n        static targetFrameRate: number\r\n        /** Returns the path to the console log file, or an empty string if the current platform does not support log files.\r\n         */\r\n        static readonly consoleLogPath: string\r\n        /** Priority of background loading thread.\r\n         */\r\n        static backgroundLoadingPriority: any\r\n        /** Returns false if application is altered in any way after it was built.\r\n         */\r\n        static readonly genuine: boolean\r\n        /** Returns true if application integrity can be confirmed.\r\n         */\r\n        static readonly genuineCheckAvailable: boolean\r\n        /** Returns the platform the game is running on (Read Only).\r\n         */\r\n        static readonly platform: any\r\n        /** Is the current Runtime platform a known mobile platform.\r\n         */\r\n        static readonly isMobilePlatform: boolean\r\n        /** Is the current Runtime platform a known console platform.\r\n         */\r\n        static readonly isConsolePlatform: boolean\r\n        /** The language the user's operating system is running in.\r\n         */\r\n        static readonly systemLanguage: any\r\n        /** Returns the type of Internet reachability currently possible on the device.\r\n         */\r\n        static readonly internetReachability: any\r\n        /** Are we running inside the Unity editor? (Read Only)\r\n         */\r\n        static readonly isEditor: boolean\r\n        static lowMemory(op: \"add\" | \"remove\", fn: () => void): void\r\n        static logMessageReceived(op: \"add\" | \"remove\", fn: (condition: string, stackTrace: string, type: any) => void): void\r\n        static logMessageReceivedThreaded(op: \"add\" | \"remove\", fn: (condition: string, stackTrace: string, type: any) => void): void\r\n        static onBeforeRender(op: \"add\" | \"remove\", fn: () => void): void\r\n        static focusChanged(op: \"add\" | \"remove\", fn: (obj: boolean) => void): void\r\n        static deepLinkActivated(op: \"add\" | \"remove\", fn: (obj: string) => void): void\r\n        static wantsToQuit(op: \"add\" | \"remove\", fn: () => boolean): void\r\n        static quitting(op: \"add\" | \"remove\", fn: () => void): void\r\n        static unloading(op: \"add\" | \"remove\", fn: () => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { ValueType } from \"System\";\r\n    /** Representation of rays.\r\n     */\r\n    class Ray extends ValueType {\r\n        constructor(origin: Vector3, direction: Vector3)\r\n        /** Returns a point at distance units along the ray.\r\n         */\r\n        GetPoint(distance: number): Vector3\r\n        /** Returns a formatted string for this ray.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string, formatProvider: any): string\r\n        /** Returns a formatted string for this ray.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string): string\r\n        toString(): string\r\n        /** The origin point of the ray.\r\n         */\r\n        origin: Vector3\r\n        /** The direction of the ray.\r\n         */\r\n        direction: Vector3\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { ValueType } from \"System\";\r\n    /** Structure used to get information back from a raycast.\r\n     */\r\n    class RaycastHit extends ValueType {\r\n        constructor()\r\n        /** The Collider that was hit.\r\n         */\r\n        readonly collider: Collider\r\n        /** The impact point in world space where the ray hit the collider.\r\n         */\r\n        point: Vector3\r\n        /** The normal of the surface the ray hit.\r\n         */\r\n        normal: Vector3\r\n        /** The barycentric coordinate of the triangle we hit.\r\n         */\r\n        barycentricCoordinate: Vector3\r\n        /** The distance from the ray's origin to the impact point.\r\n         */\r\n        distance: number\r\n        /** The index of the triangle that was hit.\r\n         */\r\n        readonly triangleIndex: number\r\n        /** The uv texture coordinate at the collision location.\r\n         */\r\n        readonly textureCoord: Vector2\r\n        /** The secondary uv texture coordinate at the impact point.\r\n         */\r\n        readonly textureCoord2: Vector2\r\n        /** The Transform of the rigidbody or collider that was hit.\r\n         */\r\n        readonly transform: Transform\r\n        /** The Rigidbody of the collider that was hit. If the collider is not attached to a rigidbody then it is null.\r\n         */\r\n        readonly rigidbody: Rigidbody\r\n        /** The ArticulationBody of the collider that was hit. If the collider is not attached to an articulation body then it is null.\r\n         */\r\n        readonly articulationBody: any\r\n        /** The uv lightmap coordinate at the impact point.\r\n         */\r\n        readonly lightmapCoord: Vector2\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object as Object1, ValueType, Array, Enum } from \"System\";\r\n    /** Global physics properties and helper methods.\r\n     */\r\n    class Physics extends Object1 {\r\n        constructor()\r\n        /** Makes the collision detection system ignore all collisions between collider1 and collider2.\r\n         * @param collider1 Any collider.\r\n         * @param collider2 Another collider you want to have collider1 to start or stop ignoring collisions with.\r\n         * @param ignore Whether or not the collisions between the two colliders should be ignored or not.\r\n         */\r\n        static IgnoreCollision(collider1: Collider, collider2: Collider, ignore: boolean): void\r\n        static IgnoreCollision(collider1: Collider, collider2: Collider): void\r\n        /** Makes the collision detection system ignore all collisions between any collider in layer1 and any collider in layer2.\n\nNote that IgnoreLayerCollision will reset the trigger state of affected colliders, so you might receive OnTriggerExit and OnTriggerEnter messages in response to calling this.\r\n         */\r\n        static IgnoreLayerCollision(layer1: number, layer2: number, ignore: boolean): void\r\n        static IgnoreLayerCollision(layer1: number, layer2: number): void\r\n        /** Are collisions between layer1 and layer2 being ignored?\r\n         */\r\n        static GetIgnoreLayerCollision(layer1: number, layer2: number): boolean\r\n        /** Checks whether the collision detection system will ignore all collisionstriggers between collider1 and collider2/ or not.\r\n         * @param collider1 The first collider to compare to collider2.\r\n         * @param collider2 The second collider to compare to collider1.\r\n         * @returns Whether the collision detection system will ignore all collisionstriggers between collider1 and collider2/ or not. \r\n         */\r\n        static GetIgnoreCollision(collider1: Collider, collider2: Collider): boolean\r\n        /** Casts a ray against all colliders in the Scene and returns detailed information on what was hit.\r\n         * @param origin The starting point of the ray in world coordinates.\r\n         * @param direction The direction of the ray.\r\n         * @param hitInfo If true is returned, hitInfo will contain more information about where the closest collider was hit. (See Also: RaycastHit).\r\n         * @param maxDistance The max distance the ray should check for collisions.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a ray.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns Returns true when the ray intersects any collider, otherwise false. \r\n         */\r\n        static Raycast(origin: Vector3, direction: Vector3, hitInfo: jsb.Out<RaycastHit>, maxDistance: number, layerMask: number, queryTriggerInteraction: any): boolean\r\n        /** Casts a ray, from point origin, in direction direction, of length maxDistance, against all colliders in the Scene.\r\n         * @param origin The starting point of the ray in world coordinates.\r\n         * @param direction The direction of the ray.\r\n         * @param maxDistance The max distance the ray should check for collisions.\r\n         * @param layerMask A that is used to selectively ignore Colliders when casting a ray.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns Returns true if the ray intersects with a Collider, otherwise false. \r\n         */\r\n        static Raycast(origin: Vector3, direction: Vector3, maxDistance: number, layerMask: number, queryTriggerInteraction: any): boolean\r\n        static Raycast(origin: Vector3, direction: Vector3, hitInfo: jsb.Out<RaycastHit>, maxDistance: number, layerMask: number): boolean\r\n        /** Same as above using ray.origin and ray.direction instead of origin and direction.\r\n         * @param ray The starting point and direction of the ray.\r\n         * @param hitInfo If true is returned, hitInfo will contain more information about where the closest collider was hit. (See Also: RaycastHit).\r\n         * @param maxDistance The max distance the ray should check for collisions.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a ray.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns Returns true when the ray intersects any collider, otherwise false. \r\n         */\r\n        static Raycast(ray: Ray, hitInfo: jsb.Out<RaycastHit>, maxDistance: number, layerMask: number, queryTriggerInteraction: any): boolean\r\n        static Raycast(origin: Vector3, direction: Vector3, maxDistance: number, layerMask: number): boolean\r\n        static Raycast(origin: Vector3, direction: Vector3, hitInfo: jsb.Out<RaycastHit>, maxDistance: number): boolean\r\n        /** Same as above using ray.origin and ray.direction instead of origin and direction.\r\n         * @param ray The starting point and direction of the ray.\r\n         * @param maxDistance The max distance the ray should check for collisions.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a ray.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns Returns true when the ray intersects any collider, otherwise false. \r\n         */\r\n        static Raycast(ray: Ray, maxDistance: number, layerMask: number, queryTriggerInteraction: any): boolean\r\n        static Raycast(ray: Ray, hitInfo: jsb.Out<RaycastHit>, maxDistance: number, layerMask: number): boolean\r\n        static Raycast(origin: Vector3, direction: Vector3, maxDistance: number): boolean\r\n        static Raycast(origin: Vector3, direction: Vector3, hitInfo: jsb.Out<RaycastHit>): boolean\r\n        static Raycast(ray: Ray, maxDistance: number, layerMask: number): boolean\r\n        static Raycast(ray: Ray, hitInfo: jsb.Out<RaycastHit>, maxDistance: number): boolean\r\n        static Raycast(origin: Vector3, direction: Vector3): boolean\r\n        static Raycast(ray: Ray, maxDistance: number): boolean\r\n        static Raycast(ray: Ray, hitInfo: jsb.Out<RaycastHit>): boolean\r\n        static Raycast(ray: Ray): boolean\r\n        /** Returns true if there is any collider intersecting the line between start and end.\r\n         * @param start Start point.\r\n         * @param end End point.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a ray.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @param hitInfo If true is returned, hitInfo will contain more information about where the collider was hit. (See Also: RaycastHit).\r\n         */\r\n        static Linecast(start: Vector3, end: Vector3, hitInfo: jsb.Out<RaycastHit>, layerMask: number, queryTriggerInteraction: any): boolean\r\n        /** Returns true if there is any collider intersecting the line between start and end.\r\n         * @param start Start point.\r\n         * @param end End point.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a ray.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         */\r\n        static Linecast(start: Vector3, end: Vector3, layerMask: number, queryTriggerInteraction: any): boolean\r\n        static Linecast(start: Vector3, end: Vector3, hitInfo: jsb.Out<RaycastHit>, layerMask: number): boolean\r\n        static Linecast(start: Vector3, end: Vector3, layerMask: number): boolean\r\n        static Linecast(start: Vector3, end: Vector3, hitInfo: jsb.Out<RaycastHit>): boolean\r\n        static Linecast(start: Vector3, end: Vector3): boolean\r\n        /**\r\n         * @param point1 The center of the sphere at the start of the capsule.\r\n         * @param point2 The center of the sphere at the end of the capsule.\r\n         * @param radius The radius of the capsule.\r\n         * @param direction The direction into which to sweep the capsule.\r\n         * @param maxDistance The max length of the sweep.\r\n         * @param hitInfo If true is returned, hitInfo will contain more information about where the collider was hit. (See Also: RaycastHit).\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a capsule.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         */\r\n        static CapsuleCast(point1: Vector3, point2: Vector3, radius: number, direction: Vector3, hitInfo: jsb.Out<RaycastHit>, maxDistance: number, layerMask: number, queryTriggerInteraction: any): boolean\r\n        /** Casts a capsule against all colliders in the Scene and returns detailed information on what was hit.\r\n         * @param point1 The center of the sphere at the start of the capsule.\r\n         * @param point2 The center of the sphere at the end of the capsule.\r\n         * @param radius The radius of the capsule.\r\n         * @param direction The direction into which to sweep the capsule.\r\n         * @param maxDistance The max length of the sweep.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a capsule.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns True when the capsule sweep intersects any collider, otherwise false. \r\n         */\r\n        static CapsuleCast(point1: Vector3, point2: Vector3, radius: number, direction: Vector3, maxDistance: number, layerMask: number, queryTriggerInteraction: any): boolean\r\n        static CapsuleCast(point1: Vector3, point2: Vector3, radius: number, direction: Vector3, hitInfo: jsb.Out<RaycastHit>, maxDistance: number, layerMask: number): boolean\r\n        static CapsuleCast(point1: Vector3, point2: Vector3, radius: number, direction: Vector3, maxDistance: number, layerMask: number): boolean\r\n        static CapsuleCast(point1: Vector3, point2: Vector3, radius: number, direction: Vector3, hitInfo: jsb.Out<RaycastHit>, maxDistance: number): boolean\r\n        static CapsuleCast(point1: Vector3, point2: Vector3, radius: number, direction: Vector3, maxDistance: number): boolean\r\n        static CapsuleCast(point1: Vector3, point2: Vector3, radius: number, direction: Vector3, hitInfo: jsb.Out<RaycastHit>): boolean\r\n        static CapsuleCast(point1: Vector3, point2: Vector3, radius: number, direction: Vector3): boolean\r\n        /** Casts a sphere along a ray and returns detailed information on what was hit.\r\n         * @param origin The center of the sphere at the start of the sweep.\r\n         * @param radius The radius of the sphere.\r\n         * @param direction The direction into which to sweep the sphere.\r\n         * @param hitInfo If true is returned, hitInfo will contain more information about where the collider was hit. (See Also: RaycastHit).\r\n         * @param maxDistance The max length of the cast.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a capsule.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns True when the sphere sweep intersects any collider, otherwise false. \r\n         */\r\n        static SphereCast(origin: Vector3, radius: number, direction: Vector3, hitInfo: jsb.Out<RaycastHit>, maxDistance: number, layerMask: number, queryTriggerInteraction: any): boolean\r\n        static SphereCast(origin: Vector3, radius: number, direction: Vector3, hitInfo: jsb.Out<RaycastHit>, maxDistance: number, layerMask: number): boolean\r\n        /**\r\n         * @param ray The starting point and direction of the ray into which the sphere sweep is cast.\r\n         * @param radius The radius of the sphere.\r\n         * @param hitInfo If true is returned, hitInfo will contain more information about where the collider was hit. (See Also: RaycastHit).\r\n         * @param maxDistance The max length of the cast.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a capsule.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         */\r\n        static SphereCast(ray: Ray, radius: number, hitInfo: jsb.Out<RaycastHit>, maxDistance: number, layerMask: number, queryTriggerInteraction: any): boolean\r\n        static SphereCast(origin: Vector3, radius: number, direction: Vector3, hitInfo: jsb.Out<RaycastHit>, maxDistance: number): boolean\r\n        /** Casts a sphere along a ray and returns detailed information on what was hit.\r\n         * @param ray The starting point and direction of the ray into which the sphere sweep is cast.\r\n         * @param radius The radius of the sphere.\r\n         * @param maxDistance The max length of the cast.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a capsule.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns True when the sphere sweep intersects any collider, otherwise false. \r\n         */\r\n        static SphereCast(ray: Ray, radius: number, maxDistance: number, layerMask: number, queryTriggerInteraction: any): boolean\r\n        static SphereCast(ray: Ray, radius: number, hitInfo: jsb.Out<RaycastHit>, maxDistance: number, layerMask: number): boolean\r\n        static SphereCast(origin: Vector3, radius: number, direction: Vector3, hitInfo: jsb.Out<RaycastHit>): boolean\r\n        static SphereCast(ray: Ray, radius: number, maxDistance: number, layerMask: number): boolean\r\n        static SphereCast(ray: Ray, radius: number, hitInfo: jsb.Out<RaycastHit>, maxDistance: number): boolean\r\n        static SphereCast(ray: Ray, radius: number, maxDistance: number): boolean\r\n        static SphereCast(ray: Ray, radius: number, hitInfo: jsb.Out<RaycastHit>): boolean\r\n        static SphereCast(ray: Ray, radius: number): boolean\r\n        /** Casts the box along a ray and returns detailed information on what was hit.\r\n         * @param center Center of the box.\r\n         * @param halfExtents Half the size of the box in each dimension.\r\n         * @param direction The direction in which to cast the box.\r\n         * @param hitInfo If true is returned, hitInfo will contain more information about where the collider was hit. (See Also: RaycastHit).\r\n         * @param orientation Rotation of the box.\r\n         * @param maxDistance The max length of the cast.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a capsule.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns True, if any intersections were found. \r\n         */\r\n        static BoxCast(center: Vector3, halfExtents: Vector3, direction: Vector3, hitInfo: jsb.Out<RaycastHit>, orientation: Quaternion, maxDistance: number, layerMask: number, queryTriggerInteraction: any): boolean\r\n        /** Casts the box along a ray and returns detailed information on what was hit.\r\n         * @param center Center of the box.\r\n         * @param halfExtents Half the size of the box in each dimension.\r\n         * @param direction The direction in which to cast the box.\r\n         * @param orientation Rotation of the box.\r\n         * @param maxDistance The max length of the cast.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a capsule.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns True, if any intersections were found. \r\n         */\r\n        static BoxCast(center: Vector3, halfExtents: Vector3, direction: Vector3, orientation: Quaternion, maxDistance: number, layerMask: number, queryTriggerInteraction: any): boolean\r\n        static BoxCast(center: Vector3, halfExtents: Vector3, direction: Vector3, hitInfo: jsb.Out<RaycastHit>, orientation: Quaternion, maxDistance: number, layerMask: number): boolean\r\n        static BoxCast(center: Vector3, halfExtents: Vector3, direction: Vector3, orientation: Quaternion, maxDistance: number, layerMask: number): boolean\r\n        static BoxCast(center: Vector3, halfExtents: Vector3, direction: Vector3, hitInfo: jsb.Out<RaycastHit>, orientation: Quaternion, maxDistance: number): boolean\r\n        static BoxCast(center: Vector3, halfExtents: Vector3, direction: Vector3, orientation: Quaternion, maxDistance: number): boolean\r\n        static BoxCast(center: Vector3, halfExtents: Vector3, direction: Vector3, hitInfo: jsb.Out<RaycastHit>, orientation: Quaternion): boolean\r\n        static BoxCast(center: Vector3, halfExtents: Vector3, direction: Vector3, orientation: Quaternion): boolean\r\n        static BoxCast(center: Vector3, halfExtents: Vector3, direction: Vector3, hitInfo: jsb.Out<RaycastHit>): boolean\r\n        static BoxCast(center: Vector3, halfExtents: Vector3, direction: Vector3): boolean\r\n        /** See Also: Raycast.\r\n         * @param origin The starting point of the ray in world coordinates.\r\n         * @param direction The direction of the ray.\r\n         * @param maxDistance The max distance the rayhit is allowed to be from the start of the ray.\r\n         * @param layermask A that is used to selectively ignore colliders when casting a ray.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         */\r\n        static RaycastAll(origin: Vector3, direction: Vector3, maxDistance: number, layerMask: number, queryTriggerInteraction: any): Array<RaycastHit>\r\n        static RaycastAll(origin: Vector3, direction: Vector3, maxDistance: number, layerMask: number): Array<RaycastHit>\r\n        /** Casts a ray through the Scene and returns all hits. Note that order of the results is undefined.\r\n         * @param ray The starting point and direction of the ray.\r\n         * @param maxDistance The max distance the rayhit is allowed to be from the start of the ray.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a ray.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns An array of RaycastHit objects. Note that the order of the results is undefined. \r\n         */\r\n        static RaycastAll(ray: Ray, maxDistance: number, layerMask: number, queryTriggerInteraction: any): Array<RaycastHit>\r\n        static RaycastAll(origin: Vector3, direction: Vector3, maxDistance: number): Array<RaycastHit>\r\n        static RaycastAll(ray: Ray, maxDistance: number, layerMask: number): Array<RaycastHit>\r\n        static RaycastAll(origin: Vector3, direction: Vector3): Array<RaycastHit>\r\n        static RaycastAll(ray: Ray, maxDistance: number): Array<RaycastHit>\r\n        static RaycastAll(ray: Ray): Array<RaycastHit>\r\n        /** Cast a ray through the Scene and store the hits into the buffer.\r\n         * @param origin The starting point and direction of the ray.\r\n         * @param results The buffer to store the hits into.\r\n         * @param direction The direction of the ray.\r\n         * @param maxDistance The max distance the rayhit is allowed to be from the start of the ray.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a ray.\r\n         * @returns The amount of hits stored into the results buffer. \r\n         */\r\n        static RaycastNonAlloc(origin: Vector3, direction: Vector3, results: Array<RaycastHit>, maxDistance: number, layerMask: number, queryTriggerInteraction: any): number\r\n        /** Cast a ray through the Scene and store the hits into the buffer.\r\n         * @param ray The starting point and direction of the ray.\r\n         * @param results The buffer to store the hits into.\r\n         * @param maxDistance The max distance the rayhit is allowed to be from the start of the ray.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a ray.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns The amount of hits stored into the results buffer. \r\n         */\r\n        static RaycastNonAlloc(ray: Ray, results: Array<RaycastHit>, maxDistance: number, layerMask: number, queryTriggerInteraction: any): number\r\n        static RaycastNonAlloc(origin: Vector3, direction: Vector3, results: Array<RaycastHit>, maxDistance: number, layerMask: number): number\r\n        static RaycastNonAlloc(ray: Ray, results: Array<RaycastHit>, maxDistance: number, layerMask: number): number\r\n        static RaycastNonAlloc(origin: Vector3, direction: Vector3, results: Array<RaycastHit>, maxDistance: number): number\r\n        static RaycastNonAlloc(ray: Ray, results: Array<RaycastHit>, maxDistance: number): number\r\n        static RaycastNonAlloc(origin: Vector3, direction: Vector3, results: Array<RaycastHit>): number\r\n        static RaycastNonAlloc(ray: Ray, results: Array<RaycastHit>): number\r\n        /** Like Physics.CapsuleCast, but this function will return all hits the capsule sweep intersects.\r\n         * @param point1 The center of the sphere at the start of the capsule.\r\n         * @param point2 The center of the sphere at the end of the capsule.\r\n         * @param radius The radius of the capsule.\r\n         * @param direction The direction into which to sweep the capsule.\r\n         * @param maxDistance The max length of the sweep.\r\n         * @param layermask A that is used to selectively ignore colliders when casting a capsule.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns An array of all colliders hit in the sweep. \r\n         */\r\n        static CapsuleCastAll(point1: Vector3, point2: Vector3, radius: number, direction: Vector3, maxDistance: number, layerMask: number, queryTriggerInteraction: any): Array<RaycastHit>\r\n        static CapsuleCastAll(point1: Vector3, point2: Vector3, radius: number, direction: Vector3, maxDistance: number, layerMask: number): Array<RaycastHit>\r\n        static CapsuleCastAll(point1: Vector3, point2: Vector3, radius: number, direction: Vector3, maxDistance: number): Array<RaycastHit>\r\n        static CapsuleCastAll(point1: Vector3, point2: Vector3, radius: number, direction: Vector3): Array<RaycastHit>\r\n        /** Like Physics.SphereCast, but this function will return all hits the sphere sweep intersects.\r\n         * @param origin The center of the sphere at the start of the sweep.\r\n         * @param radius The radius of the sphere.\r\n         * @param direction The direction in which to sweep the sphere.\r\n         * @param maxDistance The max length of the sweep.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a sphere.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns An array of all colliders hit in the sweep. \r\n         */\r\n        static SphereCastAll(origin: Vector3, radius: number, direction: Vector3, maxDistance: number, layerMask: number, queryTriggerInteraction: any): Array<RaycastHit>\r\n        static SphereCastAll(origin: Vector3, radius: number, direction: Vector3, maxDistance: number, layerMask: number): Array<RaycastHit>\r\n        /** Like Physics.SphereCast, but this function will return all hits the sphere sweep intersects.\r\n         * @param ray The starting point and direction of the ray into which the sphere sweep is cast.\r\n         * @param radius The radius of the sphere.\r\n         * @param maxDistance The max length of the sweep.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a sphere.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         */\r\n        static SphereCastAll(ray: Ray, radius: number, maxDistance: number, layerMask: number, queryTriggerInteraction: any): Array<RaycastHit>\r\n        static SphereCastAll(origin: Vector3, radius: number, direction: Vector3, maxDistance: number): Array<RaycastHit>\r\n        static SphereCastAll(ray: Ray, radius: number, maxDistance: number, layerMask: number): Array<RaycastHit>\r\n        static SphereCastAll(origin: Vector3, radius: number, direction: Vector3): Array<RaycastHit>\r\n        static SphereCastAll(ray: Ray, radius: number, maxDistance: number): Array<RaycastHit>\r\n        static SphereCastAll(ray: Ray, radius: number): Array<RaycastHit>\r\n        /** Check the given capsule against the physics world and return all overlapping colliders.\r\n         * @param point0 The center of the sphere at the start of the capsule.\r\n         * @param point1 The center of the sphere at the end of the capsule.\r\n         * @param radius The radius of the capsule.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a capsule.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns Colliders touching or inside the capsule. \r\n         */\r\n        static OverlapCapsule(point0: Vector3, point1: Vector3, radius: number, layerMask: number, queryTriggerInteraction: any): Array<Collider>\r\n        static OverlapCapsule(point0: Vector3, point1: Vector3, radius: number, layerMask: number): Array<Collider>\r\n        static OverlapCapsule(point0: Vector3, point1: Vector3, radius: number): Array<Collider>\r\n        /** Computes and stores colliders touching or inside the sphere.\r\n         * @param position Center of the sphere.\r\n         * @param radius Radius of the sphere.\r\n         * @param layerMask A defines which layers of colliders to include in the query.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns Returns an array with all colliders touching or inside the sphere. \r\n         */\r\n        static OverlapSphere(position: Vector3, radius: number, layerMask: number, queryTriggerInteraction: any): Array<Collider>\r\n        static OverlapSphere(position: Vector3, radius: number, layerMask: number): Array<Collider>\r\n        static OverlapSphere(position: Vector3, radius: number): Array<Collider>\r\n        /** Simulate physics in the Scene.\r\n         * @param step The time to advance physics by.\r\n         */\r\n        static Simulate(step: number): void\r\n        static SyncTransforms(): void\r\n        /** Compute the minimal translation required to separate the given colliders apart at specified poses.\r\n         * @param colliderA The first collider.\r\n         * @param positionA Position of the first collider.\r\n         * @param rotationA Rotation of the first collider.\r\n         * @param colliderB The second collider.\r\n         * @param positionB Position of the second collider.\r\n         * @param rotationB Rotation of the second collider.\r\n         * @param direction Direction along which the translation required to separate the colliders apart is minimal.\r\n         * @param distance The distance along direction that is required to separate the colliders apart.\r\n         * @returns True, if the colliders overlap at the given poses. \r\n         */\r\n        static ComputePenetration(colliderA: Collider, positionA: Vector3, rotationA: Quaternion, colliderB: Collider, positionB: Vector3, rotationB: Quaternion, direction: jsb.Out<Vector3>, distance: jsb.Out<number>): boolean\r\n        /** Returns a point on the given collider that is closest to the specified location.\r\n         * @param point Location you want to find the closest point to.\r\n         * @param collider The collider that you find the closest point on.\r\n         * @param position The position of the collider.\r\n         * @param rotation The rotation of the collider.\r\n         * @returns The point on the collider that is closest to the specified location. \r\n         */\r\n        static ClosestPoint(point: Vector3, collider: Collider, position: Vector3, rotation: Quaternion): Vector3\r\n        /** Computes and stores colliders touching or inside the sphere into the provided buffer.\r\n         * @param position Center of the sphere.\r\n         * @param radius Radius of the sphere.\r\n         * @param results The buffer to store the results into.\r\n         * @param layerMask A defines which layers of colliders to include in the query.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns Returns the amount of colliders stored into the results buffer. \r\n         */\r\n        static OverlapSphereNonAlloc(position: Vector3, radius: number, results: Array<Collider>, layerMask: number, queryTriggerInteraction: any): number\r\n        static OverlapSphereNonAlloc(position: Vector3, radius: number, results: Array<Collider>, layerMask: number): number\r\n        static OverlapSphereNonAlloc(position: Vector3, radius: number, results: Array<Collider>): number\r\n        /** Returns true if there are any colliders overlapping the sphere defined by position and radius in world coordinates.\r\n         * @param position Center of the sphere.\r\n         * @param radius Radius of the sphere.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a capsule.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         */\r\n        static CheckSphere(position: Vector3, radius: number, layerMask: number, queryTriggerInteraction: any): boolean\r\n        static CheckSphere(position: Vector3, radius: number, layerMask: number): boolean\r\n        static CheckSphere(position: Vector3, radius: number): boolean\r\n        /** Casts a capsule against all colliders in the Scene and returns detailed information on what was hit into the buffer.\r\n         * @param point1 The center of the sphere at the start of the capsule.\r\n         * @param point2 The center of the sphere at the end of the capsule.\r\n         * @param radius The radius of the capsule.\r\n         * @param direction The direction into which to sweep the capsule.\r\n         * @param results The buffer to store the hits into.\r\n         * @param maxDistance The max length of the sweep.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a capsule.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns The amount of hits stored into the buffer. \r\n         */\r\n        static CapsuleCastNonAlloc(point1: Vector3, point2: Vector3, radius: number, direction: Vector3, results: Array<RaycastHit>, maxDistance: number, layerMask: number, queryTriggerInteraction: any): number\r\n        static CapsuleCastNonAlloc(point1: Vector3, point2: Vector3, radius: number, direction: Vector3, results: Array<RaycastHit>, maxDistance: number, layerMask: number): number\r\n        static CapsuleCastNonAlloc(point1: Vector3, point2: Vector3, radius: number, direction: Vector3, results: Array<RaycastHit>, maxDistance: number): number\r\n        static CapsuleCastNonAlloc(point1: Vector3, point2: Vector3, radius: number, direction: Vector3, results: Array<RaycastHit>): number\r\n        /** Cast sphere along the direction and store the results into buffer.\r\n         * @param origin The center of the sphere at the start of the sweep.\r\n         * @param radius The radius of the sphere.\r\n         * @param direction The direction in which to sweep the sphere.\r\n         * @param results The buffer to save the hits into.\r\n         * @param maxDistance The max length of the sweep.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a sphere.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns The amount of hits stored into the results buffer. \r\n         */\r\n        static SphereCastNonAlloc(origin: Vector3, radius: number, direction: Vector3, results: Array<RaycastHit>, maxDistance: number, layerMask: number, queryTriggerInteraction: any): number\r\n        static SphereCastNonAlloc(origin: Vector3, radius: number, direction: Vector3, results: Array<RaycastHit>, maxDistance: number, layerMask: number): number\r\n        /** Cast sphere along the direction and store the results into buffer.\r\n         * @param ray The starting point and direction of the ray into which the sphere sweep is cast.\r\n         * @param radius The radius of the sphere.\r\n         * @param results The buffer to save the results to.\r\n         * @param maxDistance The max length of the sweep.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a sphere.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns The amount of hits stored into the results buffer. \r\n         */\r\n        static SphereCastNonAlloc(ray: Ray, radius: number, results: Array<RaycastHit>, maxDistance: number, layerMask: number, queryTriggerInteraction: any): number\r\n        static SphereCastNonAlloc(origin: Vector3, radius: number, direction: Vector3, results: Array<RaycastHit>, maxDistance: number): number\r\n        static SphereCastNonAlloc(ray: Ray, radius: number, results: Array<RaycastHit>, maxDistance: number, layerMask: number): number\r\n        static SphereCastNonAlloc(origin: Vector3, radius: number, direction: Vector3, results: Array<RaycastHit>): number\r\n        static SphereCastNonAlloc(ray: Ray, radius: number, results: Array<RaycastHit>, maxDistance: number): number\r\n        static SphereCastNonAlloc(ray: Ray, radius: number, results: Array<RaycastHit>): number\r\n        /** Checks if any colliders overlap a capsule-shaped volume in world space.\r\n         * @param start The center of the sphere at the start of the capsule.\r\n         * @param end The center of the sphere at the end of the capsule.\r\n         * @param radius The radius of the capsule.\r\n         * @param layermask A that is used to selectively ignore colliders when casting a capsule.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         */\r\n        static CheckCapsule(start: Vector3, end: Vector3, radius: number, layerMask: number, queryTriggerInteraction: any): boolean\r\n        static CheckCapsule(start: Vector3, end: Vector3, radius: number, layerMask: number): boolean\r\n        static CheckCapsule(start: Vector3, end: Vector3, radius: number): boolean\r\n        /** Check whether the given box overlaps with other colliders or not.\r\n         * @param center Center of the box.\r\n         * @param halfExtents Half the size of the box in each dimension.\r\n         * @param orientation Rotation of the box.\r\n         * @param layermask A that is used to selectively ignore colliders when casting a ray.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns True, if the box overlaps with any colliders. \r\n         */\r\n        static CheckBox(center: Vector3, halfExtents: Vector3, orientation: Quaternion, layermask: number, queryTriggerInteraction: any): boolean\r\n        static CheckBox(center: Vector3, halfExtents: Vector3, orientation: Quaternion, layerMask: number): boolean\r\n        static CheckBox(center: Vector3, halfExtents: Vector3, orientation: Quaternion): boolean\r\n        static CheckBox(center: Vector3, halfExtents: Vector3): boolean\r\n        /** Find all colliders touching or inside of the given box.\r\n         * @param center Center of the box.\r\n         * @param halfExtents Half of the size of the box in each dimension.\r\n         * @param orientation Rotation of the box.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a ray.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns Colliders that overlap with the given box. \r\n         */\r\n        static OverlapBox(center: Vector3, halfExtents: Vector3, orientation: Quaternion, layerMask: number, queryTriggerInteraction: any): Array<Collider>\r\n        static OverlapBox(center: Vector3, halfExtents: Vector3, orientation: Quaternion, layerMask: number): Array<Collider>\r\n        static OverlapBox(center: Vector3, halfExtents: Vector3, orientation: Quaternion): Array<Collider>\r\n        static OverlapBox(center: Vector3, halfExtents: Vector3): Array<Collider>\r\n        /** Find all colliders touching or inside of the given box, and store them into the buffer.\r\n         * @param center Center of the box.\r\n         * @param halfExtents Half of the size of the box in each dimension.\r\n         * @param results The buffer to store the results in.\r\n         * @param orientation Rotation of the box.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a ray.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns The amount of colliders stored in results. \r\n         */\r\n        static OverlapBoxNonAlloc(center: Vector3, halfExtents: Vector3, results: Array<Collider>, orientation: Quaternion, mask: number, queryTriggerInteraction: any): number\r\n        static OverlapBoxNonAlloc(center: Vector3, halfExtents: Vector3, results: Array<Collider>, orientation: Quaternion, mask: number): number\r\n        static OverlapBoxNonAlloc(center: Vector3, halfExtents: Vector3, results: Array<Collider>, orientation: Quaternion): number\r\n        static OverlapBoxNonAlloc(center: Vector3, halfExtents: Vector3, results: Array<Collider>): number\r\n        /** Cast the box along the direction, and store hits in the provided buffer.\r\n         * @param center Center of the box.\r\n         * @param halfExtents Half the size of the box in each dimension.\r\n         * @param direction The direction in which to cast the box.\r\n         * @param results The buffer to store the results in.\r\n         * @param orientation Rotation of the box.\r\n         * @param maxDistance The max length of the cast.\r\n         * @param layermask A that is used to selectively ignore colliders when casting a capsule.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns The amount of hits stored to the results buffer. \r\n         */\r\n        static BoxCastNonAlloc(center: Vector3, halfExtents: Vector3, direction: Vector3, results: Array<RaycastHit>, orientation: Quaternion, maxDistance: number, layerMask: number, queryTriggerInteraction: any): number\r\n        static BoxCastNonAlloc(center: Vector3, halfExtents: Vector3, direction: Vector3, results: Array<RaycastHit>, orientation: Quaternion, maxDistance: number, layerMask: number): number\r\n        static BoxCastNonAlloc(center: Vector3, halfExtents: Vector3, direction: Vector3, results: Array<RaycastHit>, orientation: Quaternion, maxDistance: number): number\r\n        static BoxCastNonAlloc(center: Vector3, halfExtents: Vector3, direction: Vector3, results: Array<RaycastHit>, orientation: Quaternion): number\r\n        static BoxCastNonAlloc(center: Vector3, halfExtents: Vector3, direction: Vector3, results: Array<RaycastHit>): number\r\n        /** Like Physics.BoxCast, but returns all hits.\r\n         * @param center Center of the box.\r\n         * @param halfExtents Half the size of the box in each dimension.\r\n         * @param direction The direction in which to cast the box.\r\n         * @param orientation Rotation of the box.\r\n         * @param maxDistance The max length of the cast.\r\n         * @param layermask A that is used to selectively ignore colliders when casting a capsule.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns All colliders that were hit. \r\n         */\r\n        static BoxCastAll(center: Vector3, halfExtents: Vector3, direction: Vector3, orientation: Quaternion, maxDistance: number, layerMask: number, queryTriggerInteraction: any): Array<RaycastHit>\r\n        static BoxCastAll(center: Vector3, halfExtents: Vector3, direction: Vector3, orientation: Quaternion, maxDistance: number, layerMask: number): Array<RaycastHit>\r\n        static BoxCastAll(center: Vector3, halfExtents: Vector3, direction: Vector3, orientation: Quaternion, maxDistance: number): Array<RaycastHit>\r\n        static BoxCastAll(center: Vector3, halfExtents: Vector3, direction: Vector3, orientation: Quaternion): Array<RaycastHit>\r\n        static BoxCastAll(center: Vector3, halfExtents: Vector3, direction: Vector3): Array<RaycastHit>\r\n        /** Check the given capsule against the physics world and return all overlapping colliders in the user-provided buffer.\r\n         * @param point0 The center of the sphere at the start of the capsule.\r\n         * @param point1 The center of the sphere at the end of the capsule.\r\n         * @param radius The radius of the capsule.\r\n         * @param results The buffer to store the results into.\r\n         * @param layerMask A that is used to selectively ignore colliders when casting a capsule.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns The amount of entries written to the buffer. \r\n         */\r\n        static OverlapCapsuleNonAlloc(point0: Vector3, point1: Vector3, radius: number, results: Array<Collider>, layerMask: number, queryTriggerInteraction: any): number\r\n        static OverlapCapsuleNonAlloc(point0: Vector3, point1: Vector3, radius: number, results: Array<Collider>, layerMask: number): number\r\n        static OverlapCapsuleNonAlloc(point0: Vector3, point1: Vector3, radius: number, results: Array<Collider>): number\r\n        /** Rebuild the broadphase interest regions as well as set the world boundaries.\r\n         * @param worldBounds Boundaries of the physics world.\r\n         * @param subdivisions How many cells to create along x and z axis.\r\n         */\r\n        static RebuildBroadphaseRegions(worldBounds: Bounds, subdivisions: number): void\r\n        /** Prepares the Mesh for use with a MeshCollider.\r\n         * @param meshID The instance ID of the Mesh to bake collision data from.\r\n         * @param convex A flag to indicate whether to bake convex geometry or not.\r\n         */\r\n        static BakeMesh(meshID: number, convex: boolean): void\r\n        /** The gravity applied to all rigid bodies in the Scene.\r\n         */\r\n        static gravity: Vector3\r\n        /** The default contact offset of the newly created colliders.\r\n         */\r\n        static defaultContactOffset: number\r\n        /** The mass-normalized energy threshold, below which objects start going to sleep.\r\n         */\r\n        static sleepThreshold: number\r\n        /** Specifies whether queries (raycasts, spherecasts, overlap tests, etc.) hit Triggers by default.\r\n         */\r\n        static queriesHitTriggers: boolean\r\n        /** Whether physics queries should hit back-face triangles.\r\n         */\r\n        static queriesHitBackfaces: boolean\r\n        /** Two colliding objects with a relative velocity below this will not bounce (default 2). Must be positive.\r\n         */\r\n        static bounceThreshold: number\r\n        /** The maximum default velocity needed to move a Rigidbody's collider out of another collider's surface penetration. Must be positive.\r\n         */\r\n        static defaultMaxDepenetrationVelocity: number\r\n        /** The defaultSolverIterations determines how accurately Rigidbody joints and collision contacts are resolved. (default 6). Must be positive.\r\n         */\r\n        static defaultSolverIterations: number\r\n        /** The defaultSolverVelocityIterations affects how accurately the Rigidbody joints and collision contacts are resolved. (default 1). Must be positive.\r\n         */\r\n        static defaultSolverVelocityIterations: number\r\n        /** Default maximum angular speed of the dynamic Rigidbody, in radians (default 50).\r\n         */\r\n        static defaultMaxAngularSpeed: number\r\n        /** The PhysicsScene automatically created when Unity starts.\r\n         */\r\n        static readonly defaultPhysicsScene: any\r\n        /** Sets whether the physics should be simulated automatically or not.\r\n         */\r\n        static autoSimulation: boolean\r\n        /** Whether or not to automatically sync transform changes with the physics system whenever a Transform component changes.\r\n         */\r\n        static autoSyncTransforms: boolean\r\n        /** Determines whether the garbage collector should reuse only a single instance of a Collision type for all collision callbacks.\r\n         */\r\n        static reuseCollisionCallbacks: boolean\r\n        /** Sets the minimum separation distance for cloth inter-collision.\r\n         */\r\n        static interCollisionDistance: number\r\n        /** Sets the cloth inter-collision stiffness.\r\n         */\r\n        static interCollisionStiffness: number\r\n        static interCollisionSettingsToggle: boolean\r\n        /** Cloth Gravity setting.\nSet gravity for all cloth components.\r\n         */\r\n        static clothGravity: Vector3\r\n        /** Layer mask constant to select ignore raycast layer.\r\n         */\r\n        static readonly IgnoreRaycastLayer: number\r\n        /** Layer mask constant to select default raycast layers.\r\n         */\r\n        static readonly DefaultRaycastLayers: number\r\n        /** Layer mask constant to select all layers.\r\n         */\r\n        static readonly AllLayers: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Array } from \"System\";\r\n    /** A base class of all colliders.\r\n     */\r\n    class Collider extends Component {\r\n        constructor()\r\n        /** Returns a point on the collider that is closest to a given location.\r\n         * @param position Location you want to find the closest point to.\r\n         * @returns The point on the collider that is closest to the specified location. \r\n         */\r\n        ClosestPoint(position: Vector3): Vector3\r\n        /** Casts a Ray that ignores all Colliders except this one.\r\n         * @param ray The starting point and direction of the ray.\r\n         * @param hitInfo If true is returned, hitInfo will contain more information about where the collider was hit.\r\n         * @param maxDistance The max length of the ray.\r\n         * @returns True when the ray intersects the collider, otherwise false. \r\n         */\r\n        Raycast(ray: Ray, hitInfo: jsb.Out<RaycastHit>, maxDistance: number): boolean\r\n        /** The closest point to the bounding box of the attached collider.\r\n         */\r\n        ClosestPointOnBounds(position: Vector3): Vector3\r\n        /** Enabled Colliders will collide with other Colliders, disabled Colliders won't.\r\n         */\r\n        enabled: boolean\r\n        /** The rigidbody the collider is attached to.\r\n         */\r\n        readonly attachedRigidbody: Rigidbody\r\n        /** The articulation body the collider is attached to.\r\n         */\r\n        readonly attachedArticulationBody: any\r\n        /** Is the collider a trigger?\r\n         */\r\n        isTrigger: boolean\r\n        /** Contact offset value of this collider.\r\n         */\r\n        contactOffset: number\r\n        /** The world space bounding volume of the collider (Read Only).\r\n         */\r\n        readonly bounds: Bounds\r\n        /** The shared physic material of this collider.\r\n         */\r\n        sharedMaterial: any\r\n        /** The material used by the collider.\r\n         */\r\n        material: any\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    /** A box-shaped primitive collider.\r\n     */\r\n    class BoxCollider extends Collider {\r\n        constructor()\r\n        /** The center of the box, measured in the object's local space.\r\n         */\r\n        center: Vector3\r\n        /** The size of the box, measured in the object's local space.\r\n         */\r\n        size: Vector3\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    /** A sphere-shaped primitive collider.\r\n     */\r\n    class SphereCollider extends Collider {\r\n        constructor()\r\n        /** The center of the sphere in the object's local space.\r\n         */\r\n        center: Vector3\r\n        /** The radius of the sphere measured in the object's local space.\r\n         */\r\n        radius: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum, Array } from \"System\";\r\n    /** Control of an object's position through physics simulation.\r\n     */\r\n    class Rigidbody extends Component {\r\n        constructor()\r\n        /** Sets the mass based on the attached colliders assuming a constant density.\r\n         */\r\n        SetDensity(density: number): void\r\n        /** Moves the kinematic Rigidbody towards position.\r\n         * @param position Provides the new position for the Rigidbody object.\r\n         */\r\n        MovePosition(position: Vector3): void\r\n        /** Rotates the rigidbody to rotation.\r\n         * @param rot The new rotation for the Rigidbody.\r\n         */\r\n        MoveRotation(rot: Quaternion): void\r\n        Sleep(): void\r\n        IsSleeping(): boolean\r\n        WakeUp(): void\r\n        ResetCenterOfMass(): void\r\n        ResetInertiaTensor(): void\r\n        /** The velocity relative to the rigidbody at the point relativePoint.\r\n         */\r\n        GetRelativePointVelocity(relativePoint: Vector3): Vector3\r\n        /** The velocity of the rigidbody at the point worldPoint in global space.\r\n         */\r\n        GetPointVelocity(worldPoint: Vector3): Vector3\r\n        /** Adds a force to the Rigidbody.\r\n         * @param x Size of force along the world x-axis.\r\n         * @param y Size of force along the world y-axis.\r\n         * @param z Size of force along the world z-axis.\r\n         * @param mode Type of force to apply.\r\n         */\r\n        AddForce(x: number, y: number, z: number, mode: any): void\r\n        /** Adds a force to the Rigidbody.\r\n         * @param x Size of force along the world x-axis.\r\n         * @param y Size of force along the world y-axis.\r\n         * @param z Size of force along the world z-axis.\r\n         * @param mode Type of force to apply.\r\n         */\r\n        AddForce(x: number, y: number, z: number): void\r\n        /** Adds a force to the Rigidbody.\r\n         * @param force Force vector in world coordinates.\r\n         * @param mode Type of force to apply.\r\n         */\r\n        AddForce(force: Vector3, mode: any): void\r\n        /** Adds a force to the Rigidbody.\r\n         * @param force Force vector in world coordinates.\r\n         * @param mode Type of force to apply.\r\n         */\r\n        AddForce(force: Vector3): void\r\n        /** Adds a force to the rigidbody relative to its coordinate system.\r\n         * @param x Size of force along the local x-axis.\r\n         * @param y Size of force along the local y-axis.\r\n         * @param z Size of force along the local z-axis.\r\n         */\r\n        AddRelativeForce(x: number, y: number, z: number, mode: any): void\r\n        /** Adds a force to the rigidbody relative to its coordinate system.\r\n         * @param x Size of force along the local x-axis.\r\n         * @param y Size of force along the local y-axis.\r\n         * @param z Size of force along the local z-axis.\r\n         */\r\n        AddRelativeForce(x: number, y: number, z: number): void\r\n        /** Adds a force to the rigidbody relative to its coordinate system.\r\n         * @param force Force vector in local coordinates.\r\n         */\r\n        AddRelativeForce(force: Vector3, mode: any): void\r\n        /** Adds a force to the rigidbody relative to its coordinate system.\r\n         * @param force Force vector in local coordinates.\r\n         */\r\n        AddRelativeForce(force: Vector3): void\r\n        /** Adds a torque to the rigidbody.\r\n         * @param x Size of torque along the world x-axis.\r\n         * @param y Size of torque along the world y-axis.\r\n         * @param z Size of torque along the world z-axis.\r\n         */\r\n        AddTorque(x: number, y: number, z: number, mode: any): void\r\n        /** Adds a torque to the rigidbody.\r\n         * @param x Size of torque along the world x-axis.\r\n         * @param y Size of torque along the world y-axis.\r\n         * @param z Size of torque along the world z-axis.\r\n         */\r\n        AddTorque(x: number, y: number, z: number): void\r\n        /** Adds a torque to the rigidbody.\r\n         * @param torque Torque vector in world coordinates.\r\n         */\r\n        AddTorque(torque: Vector3, mode: any): void\r\n        /** Adds a torque to the rigidbody.\r\n         * @param torque Torque vector in world coordinates.\r\n         */\r\n        AddTorque(torque: Vector3): void\r\n        /** Adds a torque to the rigidbody relative to its coordinate system.\r\n         * @param x Size of torque along the local x-axis.\r\n         * @param y Size of torque along the local y-axis.\r\n         * @param z Size of torque along the local z-axis.\r\n         */\r\n        AddRelativeTorque(x: number, y: number, z: number, mode: any): void\r\n        /** Adds a torque to the rigidbody relative to its coordinate system.\r\n         * @param x Size of torque along the local x-axis.\r\n         * @param y Size of torque along the local y-axis.\r\n         * @param z Size of torque along the local z-axis.\r\n         */\r\n        AddRelativeTorque(x: number, y: number, z: number): void\r\n        /** Adds a torque to the rigidbody relative to its coordinate system.\r\n         * @param torque Torque vector in local coordinates.\r\n         */\r\n        AddRelativeTorque(torque: Vector3, mode: any): void\r\n        /** Adds a torque to the rigidbody relative to its coordinate system.\r\n         * @param torque Torque vector in local coordinates.\r\n         */\r\n        AddRelativeTorque(torque: Vector3): void\r\n        /** Applies force at position. As a result this will apply a torque and force on the object.\r\n         * @param force Force vector in world coordinates.\r\n         * @param position Position in world coordinates.\r\n         */\r\n        AddForceAtPosition(force: Vector3, position: Vector3, mode: any): void\r\n        /** Applies force at position. As a result this will apply a torque and force on the object.\r\n         * @param force Force vector in world coordinates.\r\n         * @param position Position in world coordinates.\r\n         */\r\n        AddForceAtPosition(force: Vector3, position: Vector3): void\r\n        /** Applies a force to a rigidbody that simulates explosion effects.\r\n         * @param explosionForce The force of the explosion (which may be modified by distance).\r\n         * @param explosionPosition The centre of the sphere within which the explosion has its effect.\r\n         * @param explosionRadius The radius of the sphere within which the explosion has its effect.\r\n         * @param upwardsModifier Adjustment to the apparent position of the explosion to make it seem to lift objects.\r\n         * @param mode The method used to apply the force to its targets.\r\n         */\r\n        AddExplosionForce(explosionForce: number, explosionPosition: Vector3, explosionRadius: number, upwardsModifier: number, mode: any): void\r\n        /** Applies a force to a rigidbody that simulates explosion effects.\r\n         * @param explosionForce The force of the explosion (which may be modified by distance).\r\n         * @param explosionPosition The centre of the sphere within which the explosion has its effect.\r\n         * @param explosionRadius The radius of the sphere within which the explosion has its effect.\r\n         * @param upwardsModifier Adjustment to the apparent position of the explosion to make it seem to lift objects.\r\n         * @param mode The method used to apply the force to its targets.\r\n         */\r\n        AddExplosionForce(explosionForce: number, explosionPosition: Vector3, explosionRadius: number, upwardsModifier: number): void\r\n        /** Applies a force to a rigidbody that simulates explosion effects.\r\n         * @param explosionForce The force of the explosion (which may be modified by distance).\r\n         * @param explosionPosition The centre of the sphere within which the explosion has its effect.\r\n         * @param explosionRadius The radius of the sphere within which the explosion has its effect.\r\n         * @param upwardsModifier Adjustment to the apparent position of the explosion to make it seem to lift objects.\r\n         * @param mode The method used to apply the force to its targets.\r\n         */\r\n        AddExplosionForce(explosionForce: number, explosionPosition: Vector3, explosionRadius: number): void\r\n        /** The closest point to the bounding box of the attached colliders.\r\n         */\r\n        ClosestPointOnBounds(position: Vector3): Vector3\r\n        /** Tests if a rigidbody would collide with anything, if it was moved through the Scene.\r\n         * @param direction The direction into which to sweep the rigidbody.\r\n         * @param hitInfo If true is returned, hitInfo will contain more information about where the collider was hit (See Also: RaycastHit).\r\n         * @param maxDistance The length of the sweep.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns True when the rigidbody sweep intersects any collider, otherwise false. \r\n         */\r\n        SweepTest(direction: Vector3, hitInfo: jsb.Out<RaycastHit>, maxDistance: number, queryTriggerInteraction: any): boolean\r\n        SweepTest(direction: Vector3, hitInfo: jsb.Out<RaycastHit>, maxDistance: number): boolean\r\n        SweepTest(direction: Vector3, hitInfo: jsb.Out<RaycastHit>): boolean\r\n        /** Like Rigidbody.SweepTest, but returns all hits.\r\n         * @param direction The direction into which to sweep the rigidbody.\r\n         * @param maxDistance The length of the sweep.\r\n         * @param queryTriggerInteraction Specifies whether this query should hit Triggers.\r\n         * @returns An array of all colliders hit in the sweep. \r\n         */\r\n        SweepTestAll(direction: Vector3, maxDistance: number, queryTriggerInteraction: any): Array<RaycastHit>\r\n        SweepTestAll(direction: Vector3, maxDistance: number): Array<RaycastHit>\r\n        SweepTestAll(direction: Vector3): Array<RaycastHit>\r\n        /** The velocity vector of the rigidbody. It represents the rate of change of Rigidbody position.\r\n         */\r\n        velocity: Vector3\r\n        /** The angular velocity vector of the rigidbody measured in radians per second.\r\n         */\r\n        angularVelocity: Vector3\r\n        /** The drag of the object.\r\n         */\r\n        drag: number\r\n        /** The angular drag of the object.\r\n         */\r\n        angularDrag: number\r\n        /** The mass of the rigidbody.\r\n         */\r\n        mass: number\r\n        /** Controls whether gravity affects this rigidbody.\r\n         */\r\n        useGravity: boolean\r\n        /** Maximum velocity of a rigidbody when moving out of penetrating state.\r\n         */\r\n        maxDepenetrationVelocity: number\r\n        /** Controls whether physics affects the rigidbody.\r\n         */\r\n        isKinematic: boolean\r\n        /** Controls whether physics will change the rotation of the object.\r\n         */\r\n        freezeRotation: boolean\r\n        /** Controls which degrees of freedom are allowed for the simulation of this Rigidbody.\r\n         */\r\n        constraints: any\r\n        /** The Rigidbody's collision detection mode.\r\n         */\r\n        collisionDetectionMode: any\r\n        /** The center of mass relative to the transform's origin.\r\n         */\r\n        centerOfMass: Vector3\r\n        /** The center of mass of the rigidbody in world space (Read Only).\r\n         */\r\n        readonly worldCenterOfMass: Vector3\r\n        /** The rotation of the inertia tensor.\r\n         */\r\n        inertiaTensorRotation: Quaternion\r\n        /** The diagonal inertia tensor of mass relative to the center of mass.\r\n         */\r\n        inertiaTensor: Vector3\r\n        /** Should collision detection be enabled? (By default always enabled).\r\n         */\r\n        detectCollisions: boolean\r\n        /** The position of the rigidbody.\r\n         */\r\n        position: Vector3\r\n        /** The rotation of the Rigidbody.\r\n         */\r\n        rotation: Quaternion\r\n        /** Interpolation allows you to smooth out the effect of running physics at a fixed frame rate.\r\n         */\r\n        interpolation: any\r\n        /** The solverIterations determines how accurately Rigidbody joints and collision contacts are resolved. Overrides Physics.defaultSolverIterations. Must be positive.\r\n         */\r\n        solverIterations: number\r\n        /** The mass-normalized energy threshold, below which objects start going to sleep.\r\n         */\r\n        sleepThreshold: number\r\n        /** The maximimum angular velocity of the rigidbody measured in radians per second. (Default 7) range { 0, infinity }.\r\n         */\r\n        maxAngularVelocity: number\r\n        /** The solverVelocityIterations affects how how accurately Rigidbody joints and collision contacts are resolved. Overrides Physics.defaultSolverVelocityIterations. Must be positive.\r\n         */\r\n        solverVelocityIterations: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object as Object1, Array, ValueType } from \"System\";\r\n    /** The Resources class allows you to find and access Objects including assets.\r\n     */\r\n    class Resources extends Object1 {\r\n        /** Returns a list of all objects of Type type.\r\n         */\r\n        static FindObjectsOfTypeAll<T extends Object>(type: { new(): T }): T[]\r\n        /** Loads an asset stored at path in a Resources folder using an optional systemTypeInstance filter.\r\n         * @param path Path to the target resource to load.\r\n         * @param systemTypeInstance Type filter for objects returned.\r\n         * @returns The requested asset returned as an Object. \r\n         */\r\n        static Load(path: string, systemTypeInstance: any): Object\r\n        /** Loads an asset stored at path in a Resources folder using an optional systemTypeInstance filter.\r\n         * @param path Path to the target resource to load.\r\n         * @param systemTypeInstance Type filter for objects returned.\r\n         * @returns The requested asset returned as an Object. \r\n         */\r\n        static Load(path: string): Object\r\n        /** Asynchronously loads an asset stored at path in a Resources folder.\r\n         * @param path Pathname of the target folder. When using the empty string (i.e., \"\"), the function will load the entire contents of the Resources folder.\r\n         * @param systemTypeInstance Type filter for objects returned.\r\n         */\r\n        static LoadAsync(path: string, type: any): any\r\n        /** Asynchronously loads an asset stored at path in a Resources folder.\r\n         * @param path Pathname of the target folder. When using the empty string (i.e., \"\"), the function will load the entire contents of the Resources folder.\r\n         */\r\n        static LoadAsync(path: string): any\r\n        /** Loads all assets in a folder or file at path in a Resources folder.\r\n         * @param path Pathname of the target folder. When using the empty string (i.e., \"\"), the function will load the entire contents of the Resources folder.\r\n         * @param systemTypeInstance Type filter for objects returned.\r\n         */\r\n        static LoadAll(path: string, systemTypeInstance: any): Array<Object>\r\n        /** Loads all assets in a folder or file at path in a Resources folder.\r\n         * @param path Pathname of the target folder. When using the empty string (i.e., \"\"), the function will load the entire contents of the Resources folder.\r\n         */\r\n        static LoadAll(path: string): Array<Object>\r\n        static GetBuiltinResource(type: any, path: string): Object\r\n        /** Unloads assetToUnload from memory.\r\n         */\r\n        static UnloadAsset(assetToUnload: Object): void\r\n        static UnloadUnusedAssets(): any\r\n        /** Translates an instance ID to an object reference.\r\n         * @param instanceID Instance ID of an Object.\r\n         * @returns Resolved reference or null if the instance ID didn't match anything. \r\n         */\r\n        static InstanceIDToObject(instanceID: number): Object\r\n        static InstanceIDToObjectList(instanceIDs: any, objects: any): void\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"QuickJS.Unity\" {\r\n    import { Object } from \"System\";\r\n    import { Object as Object1 } from \"UnityEngine\";\r\n    import { ByteBuffer } from \"QuickJS.IO\";\r\n    class JSSerializationContext extends Object {\r\n        AddReferencedObject(value: Object1): number\r\n        GetReferencedObject(index: number): Object1\r\n        Flush(byteBuffer: ByteBuffer): void\r\n        AllocByteBuffer(): ByteBuffer\r\n        Release(): void\r\n        protected constructor()\r\n        dataFormat: number\r\n    }\r\n}\r\ndeclare module \"QuickJS.Unity\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array, ValueType } from \"System\";\r\n    import { Texture } from \"UnityEngine\";\r\n    import { Prefs } from \"QuickJS.Binding\";\r\n    import { MonoScript } from \"UnityEditor\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class UnityHelper extends Object {\r\n        static GetIcon(name: string): Texture\r\n        static GenerateBindingsAndTypeDefinition(): void\r\n        static GenerateTypeDefinition(): void\r\n        static LoadPrefs(filePath: jsb.Out<string>): Prefs\r\n        static LoadPrefs(): Prefs\r\n        static GetMonoScript(type: any): MonoScript\r\n        static IsReflectBindingSupported(): boolean\r\n        static InvokeReflectBinding(): void\r\n        static IsInMemoryBindingSupported(): boolean\r\n        static InvokeInMemoryBinding(): void\r\n        static CompileScripts(): void\r\n        static ClearBindings(): void\r\n        static OpenPrefsEditor(): void\r\n        static ShowJSConsole(): void\r\n        static ShowJSModuleView(): void\r\n        static ShowScriptEditorWindowLauncher(): void\r\n        static GetPlatform(): string\r\n        static IsExplicitEditorType(type: any): boolean\r\n        static IsExplicitEditorDomain(assembly: any): boolean\r\n        static ReplacePathVars(value: string): string\r\n        static CheckAnyScriptExists(): boolean\r\n        static CompileBytecodeValidate(): boolean\r\n        static CompileBytecode(workspace: string): void\r\n        static CompileBytecode(): void\r\n        static NormalizePathString(path: string): string\r\n        static ResolveScriptRef(sourceDirBase: string, sourceFile: string, normalizedPath: jsb.Out<string>, modulePath: jsb.Out<string>, hints: any): boolean\r\n        static JSBehaviourClassNameRegex: any\r\n        static JSAssetClassNameRegex: any\r\n        static JSCustomEditorClassNameRegex: any\r\n        static JSEditorWindowClassNameRegex: any\r\n    }\r\n}\r\ndeclare module \"QuickJS.Binding\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class Prefs extends Object {\r\n        protected constructor()\r\n        readonly newline: string\r\n        static readonly PATH: string\r\n        filePath: string\r\n        logPath: string\r\n        sourceDir: string\r\n        javascriptDir: string\r\n        outDir: string\r\n        typescriptDir: string\r\n        typescriptExt: string\r\n        xmlDocDir: string\r\n        jsModulePackInfoPath: string\r\n        genTypescriptDoc: boolean\r\n        editorScripting: boolean\r\n        preferredBindingMethod: string\r\n        enableOperatorOverloading: boolean\r\n        alwaysEmitOperatorMethod: boolean\r\n        editorEntryPoint: string\r\n        assetPostProcessors: any\r\n        editorRequires: any\r\n        editorDecoratorScript: string\r\n        debugCodegen: boolean\r\n        skipDelegateWithByRefParams: boolean\r\n        verboseLog: boolean\r\n        optToString: boolean\r\n        singleTSD: boolean\r\n        alwaysCheckArgType: boolean\r\n        alwaysCheckArgc: boolean\r\n        randomizedBindingCode: boolean\r\n        typeBindingPrefix: string\r\n        ns: string\r\n        defaultJSModule: string\r\n        extraExtForTypescript: string\r\n        newLineStyle: string\r\n        tab: string\r\n        skipBinding: any\r\n        cleanupDir: any\r\n        explicitAssemblies: any\r\n        implicitAssemblies: any\r\n        typeFullNameBlacklist: any\r\n        namespaceBlacklist: any\r\n        assemblyBlacklist: any\r\n    }\r\n}\r\ndeclare module \"QuickJS.Utils\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class TSConfig extends Object {\r\n        protected constructor()\r\n        compilerOptions: TSConfig.CompilerOptions\r\n        compileOnSave: boolean\r\n        include: Array<string>\r\n        exclude: Array<string>\r\n    }\r\n}\r\ndeclare module \"QuickJS.Utils\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    namespace TSConfig {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class CompilerOptions extends Object {\r\n            protected constructor()\r\n            module_: string\r\n            target: string\r\n            sourceRoot: string\r\n            outDir: string\r\n            outFile: string\r\n            typeRoots: Array<string>\r\n            moduleResolution: string\r\n            types: Array<string>\r\n            listEmittedFiles: boolean\r\n            experimentalDecorators: boolean\r\n            noImplicitAny: boolean\r\n            allowJs: boolean\r\n            inlineSourceMap: boolean\r\n            sourceMap: boolean\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object as Object1, Array, Enum } from \"System\";\r\n    /** The GUI class is the interface for Unity's GUI with manual positioning.\r\n     */\r\n    class GUI extends Object1 {\r\n        /** Set the name of the next control.\r\n         */\r\n        static SetNextControlName(name: string): void\r\n        static GetNameOfFocusedControl(): string\r\n        /** Move keyboard focus to a named control.\r\n         * @param name Name set using SetNextControlName.\r\n         */\r\n        static FocusControl(name: string): void\r\n        /** Make a window draggable.\r\n         * @param position The part of the window that can be dragged. This is clipped to the actual window.\r\n         */\r\n        static DragWindow(position: Rect): void\r\n        static DragWindow(): void\r\n        /** Bring a specific window to front of the floating windows.\r\n         * @param windowID The identifier used when you created the window in the Window call.\r\n         */\r\n        static BringWindowToFront(windowID: number): void\r\n        /** Bring a specific window to back of the floating windows.\r\n         * @param windowID The identifier used when you created the window in the Window call.\r\n         */\r\n        static BringWindowToBack(windowID: number): void\r\n        /** Make a window become the active window.\r\n         * @param windowID The identifier used when you created the window in the Window call.\r\n         */\r\n        static FocusWindow(windowID: number): void\r\n        static UnfocusWindow(): void\r\n        /** Make a text or texture label on screen.\r\n         * @param position Rectangle on the screen to use for the label.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\r\n         */\r\n        static Label(position: Rect, text: string, style: GUIStyle): void\r\n        /** Make a text or texture label on screen.\r\n         * @param position Rectangle on the screen to use for the label.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\r\n         */\r\n        static Label(position: Rect, image: Texture, style: GUIStyle): void\r\n        /** Make a text or texture label on screen.\r\n         * @param position Rectangle on the screen to use for the label.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\r\n         */\r\n        static Label(position: Rect, content: GUIContent, style: GUIStyle): void\r\n        /** Make a text or texture label on screen.\r\n         * @param position Rectangle on the screen to use for the label.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\r\n         */\r\n        static Label(position: Rect, text: string): void\r\n        /** Make a text or texture label on screen.\r\n         * @param position Rectangle on the screen to use for the label.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\r\n         */\r\n        static Label(position: Rect, image: Texture): void\r\n        /** Make a text or texture label on screen.\r\n         * @param position Rectangle on the screen to use for the label.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\r\n         */\r\n        static Label(position: Rect, content: GUIContent): void\r\n        /** Draws a border with rounded corners within a rectangle. The texture is used to pattern the border.  Note that this method only works on shader model 2.5 and above.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param alphaBlend Whether to apply alpha blending when drawing the image (enabled by default).\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.  Pass in w/h for the desired aspect ratio.  This allows the aspect ratio of the source image to be adjusted without changing the pixel width and height.\r\n         * @param color A tint color to apply on the texture.\r\n         * @param borderWidth The width of the border. If 0, the full texture is drawn.\r\n         * @param borderWidths The width of the borders (left, top, right and bottom). If Vector4.zero, the full texture is drawn.\r\n         * @param borderRadius The radius for rounded corners. If 0, corners will not be rounded.\r\n         * @param borderRadiuses The radiuses for rounded corners (top-left, top-right, bottom-right and bottom-left). If Vector4.zero, corners will not be rounded.\r\n         */\r\n        static DrawTexture(position: Rect, image: Texture, scaleMode: ScaleMode, alphaBlend: boolean, imageAspect: number, color: Color, borderWidth: number, borderRadius: number): void\r\n        /** Draws a border with rounded corners within a rectangle. The texture is used to pattern the border.  Note that this method only works on shader model 2.5 and above.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param alphaBlend Whether to apply alpha blending when drawing the image (enabled by default).\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.  Pass in w/h for the desired aspect ratio.  This allows the aspect ratio of the source image to be adjusted without changing the pixel width and height.\r\n         * @param color A tint color to apply on the texture.\r\n         * @param borderWidth The width of the border. If 0, the full texture is drawn.\r\n         * @param borderWidths The width of the borders (left, top, right and bottom). If Vector4.zero, the full texture is drawn.\r\n         * @param borderRadius The radius for rounded corners. If 0, corners will not be rounded.\r\n         * @param borderRadiuses The radiuses for rounded corners (top-left, top-right, bottom-right and bottom-left). If Vector4.zero, corners will not be rounded.\r\n         */\r\n        static DrawTexture(position: Rect, image: Texture, scaleMode: ScaleMode, alphaBlend: boolean, imageAspect: number, color: Color, borderWidths: Vector4, borderRadius: number): void\r\n        static DrawTexture(position: Rect, image: Texture, scaleMode: ScaleMode, alphaBlend: boolean, imageAspect: number, color: Color, borderWidths: Vector4, borderRadiuses: Vector4): void\r\n        /** Draw a texture within a rectangle.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param alphaBlend Whether to apply alpha blending when drawing the image (enabled by default).\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.  Pass in w/h for the desired aspect ratio.  This allows the aspect ratio of the source image to be adjusted without changing the pixel width and height.\r\n         */\r\n        static DrawTexture(position: Rect, image: Texture, scaleMode: ScaleMode, alphaBlend: boolean, imageAspect: number): void\r\n        /** Draw a texture within a rectangle.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param alphaBlend Whether to apply alpha blending when drawing the image (enabled by default).\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.  Pass in w/h for the desired aspect ratio.  This allows the aspect ratio of the source image to be adjusted without changing the pixel width and height.\r\n         */\r\n        static DrawTexture(position: Rect, image: Texture, scaleMode: ScaleMode, alphaBlend: boolean): void\r\n        /** Draw a texture within a rectangle.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param alphaBlend Whether to apply alpha blending when drawing the image (enabled by default).\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.  Pass in w/h for the desired aspect ratio.  This allows the aspect ratio of the source image to be adjusted without changing the pixel width and height.\r\n         */\r\n        static DrawTexture(position: Rect, image: Texture, scaleMode: ScaleMode): void\r\n        /** Draw a texture within a rectangle.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param alphaBlend Whether to apply alpha blending when drawing the image (enabled by default).\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.  Pass in w/h for the desired aspect ratio.  This allows the aspect ratio of the source image to be adjusted without changing the pixel width and height.\r\n         */\r\n        static DrawTexture(position: Rect, image: Texture): void\r\n        /** Draw a texture within a rectangle with the given texture coordinates.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param texCoords How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param alphaBlend Whether to alpha blend the image on to the display (the default). If false, the picture is drawn on to the display.\r\n         */\r\n        static DrawTextureWithTexCoords(position: Rect, image: Texture, texCoords: Rect, alphaBlend: boolean): void\r\n        /** Draw a texture within a rectangle with the given texture coordinates.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param texCoords How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param alphaBlend Whether to alpha blend the image on to the display (the default). If false, the picture is drawn on to the display.\r\n         */\r\n        static DrawTextureWithTexCoords(position: Rect, image: Texture, texCoords: Rect): void\r\n        /** Create a Box on the GUI Layer.\r\n         * @param position Rectangle on the screen to use for the box.\r\n         * @param text Text to display on the box.\r\n         * @param image Texture to display on the box.\r\n         * @param content Text, image and tooltip for this box.\r\n         * @param style The style to use. If left out, the box style from the current GUISkin is used.\r\n         */\r\n        static Box(position: Rect, text: string, style: GUIStyle): void\r\n        /** Create a Box on the GUI Layer.\r\n         * @param position Rectangle on the screen to use for the box.\r\n         * @param text Text to display on the box.\r\n         * @param image Texture to display on the box.\r\n         * @param content Text, image and tooltip for this box.\r\n         * @param style The style to use. If left out, the box style from the current GUISkin is used.\r\n         */\r\n        static Box(position: Rect, image: Texture, style: GUIStyle): void\r\n        /** Create a Box on the GUI Layer.\r\n         * @param position Rectangle on the screen to use for the box.\r\n         * @param text Text to display on the box.\r\n         * @param image Texture to display on the box.\r\n         * @param content Text, image and tooltip for this box.\r\n         * @param style The style to use. If left out, the box style from the current GUISkin is used.\r\n         */\r\n        static Box(position: Rect, content: GUIContent, style: GUIStyle): void\r\n        /** Create a Box on the GUI Layer.\r\n         * @param position Rectangle on the screen to use for the box.\r\n         * @param text Text to display on the box.\r\n         * @param image Texture to display on the box.\r\n         * @param content Text, image and tooltip for this box.\r\n         * @param style The style to use. If left out, the box style from the current GUISkin is used.\r\n         */\r\n        static Box(position: Rect, text: string): void\r\n        /** Create a Box on the GUI Layer.\r\n         * @param position Rectangle on the screen to use for the box.\r\n         * @param text Text to display on the box.\r\n         * @param image Texture to display on the box.\r\n         * @param content Text, image and tooltip for this box.\r\n         * @param style The style to use. If left out, the box style from the current GUISkin is used.\r\n         */\r\n        static Box(position: Rect, image: Texture): void\r\n        /** Create a Box on the GUI Layer.\r\n         * @param position Rectangle on the screen to use for the box.\r\n         * @param text Text to display on the box.\r\n         * @param image Texture to display on the box.\r\n         * @param content Text, image and tooltip for this box.\r\n         * @param style The style to use. If left out, the box style from the current GUISkin is used.\r\n         */\r\n        static Box(position: Rect, content: GUIContent): void\r\n        /** Make a single press button. The user clicks them and something happens immediately.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns true when the users clicks the button. \r\n         */\r\n        static Button(position: Rect, text: string, style: GUIStyle): boolean\r\n        /** Make a single press button. The user clicks them and something happens immediately.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns true when the users clicks the button. \r\n         */\r\n        static Button(position: Rect, image: Texture, style: GUIStyle): boolean\r\n        /** Make a single press button. The user clicks them and something happens immediately.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns true when the users clicks the button. \r\n         */\r\n        static Button(position: Rect, content: GUIContent, style: GUIStyle): boolean\r\n        /** Make a single press button. The user clicks them and something happens immediately.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns true when the users clicks the button. \r\n         */\r\n        static Button(position: Rect, text: string): boolean\r\n        /** Make a single press button. The user clicks them and something happens immediately.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns true when the users clicks the button. \r\n         */\r\n        static Button(position: Rect, image: Texture): boolean\r\n        /** Make a single press button. The user clicks them and something happens immediately.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns true when the users clicks the button. \r\n         */\r\n        static Button(position: Rect, content: GUIContent): boolean\r\n        /** Make a button that is active as long as the user holds it down.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns True when the users clicks the button. \r\n         */\r\n        static RepeatButton(position: Rect, text: string, style: GUIStyle): boolean\r\n        /** Make a button that is active as long as the user holds it down.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns True when the users clicks the button. \r\n         */\r\n        static RepeatButton(position: Rect, image: Texture, style: GUIStyle): boolean\r\n        /** Make a button that is active as long as the user holds it down.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns True when the users clicks the button. \r\n         */\r\n        static RepeatButton(position: Rect, content: GUIContent, style: GUIStyle): boolean\r\n        /** Make a button that is active as long as the user holds it down.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns True when the users clicks the button. \r\n         */\r\n        static RepeatButton(position: Rect, text: string): boolean\r\n        /** Make a button that is active as long as the user holds it down.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns True when the users clicks the button. \r\n         */\r\n        static RepeatButton(position: Rect, image: Texture): boolean\r\n        /** Make a button that is active as long as the user holds it down.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns True when the users clicks the button. \r\n         */\r\n        static RepeatButton(position: Rect, content: GUIContent): boolean\r\n        /** Make a single-line text field where the user can edit a string.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param text Text to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textField style from the current GUISkin is used.\r\n         * @returns The edited string. \r\n         */\r\n        static TextField(position: Rect, text: string, maxLength: number, style: GUIStyle): string\r\n        /** Make a single-line text field where the user can edit a string.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param text Text to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textField style from the current GUISkin is used.\r\n         * @returns The edited string. \r\n         */\r\n        static TextField(position: Rect, text: string, maxLength: number): string\r\n        /** Make a single-line text field where the user can edit a string.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param text Text to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textField style from the current GUISkin is used.\r\n         * @returns The edited string. \r\n         */\r\n        static TextField(position: Rect, text: string, style: GUIStyle): string\r\n        /** Make a single-line text field where the user can edit a string.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param text Text to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textField style from the current GUISkin is used.\r\n         * @returns The edited string. \r\n         */\r\n        static TextField(position: Rect, text: string): string\r\n        /** Make a text field where the user can enter a password.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param password Password to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maskChar Character to mask the password with.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textField style from the current GUISkin is used.\r\n         * @returns The edited password. \r\n         */\r\n        static PasswordField(position: Rect, password: string, maskChar: string, maxLength: number, style: GUIStyle): string\r\n        /** Make a text field where the user can enter a password.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param password Password to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maskChar Character to mask the password with.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textField style from the current GUISkin is used.\r\n         * @returns The edited password. \r\n         */\r\n        static PasswordField(position: Rect, password: string, maskChar: string, maxLength: number): string\r\n        /** Make a text field where the user can enter a password.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param password Password to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maskChar Character to mask the password with.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textField style from the current GUISkin is used.\r\n         * @returns The edited password. \r\n         */\r\n        static PasswordField(position: Rect, password: string, maskChar: string, style: GUIStyle): string\r\n        /** Make a text field where the user can enter a password.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param password Password to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maskChar Character to mask the password with.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textField style from the current GUISkin is used.\r\n         * @returns The edited password. \r\n         */\r\n        static PasswordField(position: Rect, password: string, maskChar: string): string\r\n        /** Make a Multi-line text area where the user can edit a string.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param text Text to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textArea style from the current GUISkin is used.\r\n         * @returns The edited string. \r\n         */\r\n        static TextArea(position: Rect, text: string, maxLength: number, style: GUIStyle): string\r\n        /** Make a Multi-line text area where the user can edit a string.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param text Text to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textArea style from the current GUISkin is used.\r\n         * @returns The edited string. \r\n         */\r\n        static TextArea(position: Rect, text: string, maxLength: number): string\r\n        /** Make a Multi-line text area where the user can edit a string.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param text Text to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textArea style from the current GUISkin is used.\r\n         * @returns The edited string. \r\n         */\r\n        static TextArea(position: Rect, text: string, style: GUIStyle): string\r\n        /** Make a Multi-line text area where the user can edit a string.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param text Text to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textArea style from the current GUISkin is used.\r\n         * @returns The edited string. \r\n         */\r\n        static TextArea(position: Rect, text: string): string\r\n        static Toggle(position: Rect, id: number, value: boolean, content: GUIContent, style: GUIStyle): boolean\r\n        /** Make an on/off toggle button.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param value Is this button on or off?\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the toggle style from the current GUISkin is used.\r\n         * @returns The new value of the button. \r\n         */\r\n        static Toggle(position: Rect, value: boolean, text: string, style: GUIStyle): boolean\r\n        /** Make an on/off toggle button.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param value Is this button on or off?\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the toggle style from the current GUISkin is used.\r\n         * @returns The new value of the button. \r\n         */\r\n        static Toggle(position: Rect, value: boolean, image: Texture, style: GUIStyle): boolean\r\n        /** Make an on/off toggle button.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param value Is this button on or off?\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the toggle style from the current GUISkin is used.\r\n         * @returns The new value of the button. \r\n         */\r\n        static Toggle(position: Rect, value: boolean, content: GUIContent, style: GUIStyle): boolean\r\n        /** Make an on/off toggle button.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param value Is this button on or off?\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the toggle style from the current GUISkin is used.\r\n         * @returns The new value of the button. \r\n         */\r\n        static Toggle(position: Rect, value: boolean, text: string): boolean\r\n        /** Make an on/off toggle button.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param value Is this button on or off?\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the toggle style from the current GUISkin is used.\r\n         * @returns The new value of the button. \r\n         */\r\n        static Toggle(position: Rect, value: boolean, image: Texture): boolean\r\n        /** Make an on/off toggle button.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param value Is this button on or off?\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the toggle style from the current GUISkin is used.\r\n         * @returns The new value of the button. \r\n         */\r\n        static Toggle(position: Rect, value: boolean, content: GUIContent): boolean\r\n        static Toolbar(position: Rect, selected: number, contents: Array<GUIContent>, style: GUIStyle, buttonSize: any): number\r\n        /** Make a toolbar.\r\n         * @param position Rectangle on the screen to use for the toolbar.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the toolbar buttons.\r\n         * @param images An array of textures on the toolbar buttons.\r\n         * @param contents An array of text, image and tooltips for the toolbar buttons.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param buttonSize Determines how toolbar button size is calculated.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static Toolbar(position: Rect, selected: number, texts: Array<string>, style: GUIStyle): number\r\n        /** Make a toolbar.\r\n         * @param position Rectangle on the screen to use for the toolbar.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the toolbar buttons.\r\n         * @param images An array of textures on the toolbar buttons.\r\n         * @param contents An array of text, image and tooltips for the toolbar buttons.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param buttonSize Determines how toolbar button size is calculated.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static Toolbar(position: Rect, selected: number, images: Array<Texture>, style: GUIStyle): number\r\n        /** Make a toolbar.\r\n         * @param position Rectangle on the screen to use for the toolbar.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the toolbar buttons.\r\n         * @param images An array of textures on the toolbar buttons.\r\n         * @param contents An array of text, image and tooltips for the toolbar buttons.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param buttonSize Determines how toolbar button size is calculated.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static Toolbar(position: Rect, selected: number, contents: Array<GUIContent>, style: GUIStyle): number\r\n        /** Make a toolbar.\r\n         * @param position Rectangle on the screen to use for the toolbar.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the toolbar buttons.\r\n         * @param images An array of textures on the toolbar buttons.\r\n         * @param contents An array of text, image and tooltips for the toolbar buttons.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param buttonSize Determines how toolbar button size is calculated.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static Toolbar(position: Rect, selected: number, texts: Array<string>): number\r\n        /** Make a toolbar.\r\n         * @param position Rectangle on the screen to use for the toolbar.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the toolbar buttons.\r\n         * @param images An array of textures on the toolbar buttons.\r\n         * @param contents An array of text, image and tooltips for the toolbar buttons.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param buttonSize Determines how toolbar button size is calculated.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static Toolbar(position: Rect, selected: number, images: Array<Texture>): number\r\n        /** Make a toolbar.\r\n         * @param position Rectangle on the screen to use for the toolbar.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the toolbar buttons.\r\n         * @param images An array of textures on the toolbar buttons.\r\n         * @param contents An array of text, image and tooltips for the toolbar buttons.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param buttonSize Determines how toolbar button size is calculated.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static Toolbar(position: Rect, selected: number, contents: Array<GUIContent>): number\r\n        /** Make a grid of buttons.\r\n         * @param position Rectangle on the screen to use for the grid.\r\n         * @param selected The index of the selected grid button.\r\n         * @param texts An array of strings to show on the grid buttons.\r\n         * @param images An array of textures on the grid buttons.\r\n         * @param contents An array of text, image and tooltips for the grid button.\r\n         * @param xCount How many elements to fit in the horizontal direction. The controls will be scaled to fit unless the style defines a fixedWidth to use.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static SelectionGrid(position: Rect, selected: number, texts: Array<string>, xCount: number, style: GUIStyle): number\r\n        /** Make a grid of buttons.\r\n         * @param position Rectangle on the screen to use for the grid.\r\n         * @param selected The index of the selected grid button.\r\n         * @param texts An array of strings to show on the grid buttons.\r\n         * @param images An array of textures on the grid buttons.\r\n         * @param contents An array of text, image and tooltips for the grid button.\r\n         * @param xCount How many elements to fit in the horizontal direction. The controls will be scaled to fit unless the style defines a fixedWidth to use.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static SelectionGrid(position: Rect, selected: number, images: Array<Texture>, xCount: number, style: GUIStyle): number\r\n        /** Make a grid of buttons.\r\n         * @param position Rectangle on the screen to use for the grid.\r\n         * @param selected The index of the selected grid button.\r\n         * @param texts An array of strings to show on the grid buttons.\r\n         * @param images An array of textures on the grid buttons.\r\n         * @param contents An array of text, image and tooltips for the grid button.\r\n         * @param xCount How many elements to fit in the horizontal direction. The controls will be scaled to fit unless the style defines a fixedWidth to use.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static SelectionGrid(position: Rect, selected: number, contents: Array<GUIContent>, xCount: number, style: GUIStyle): number\r\n        /** Make a grid of buttons.\r\n         * @param position Rectangle on the screen to use for the grid.\r\n         * @param selected The index of the selected grid button.\r\n         * @param texts An array of strings to show on the grid buttons.\r\n         * @param images An array of textures on the grid buttons.\r\n         * @param contents An array of text, image and tooltips for the grid button.\r\n         * @param xCount How many elements to fit in the horizontal direction. The controls will be scaled to fit unless the style defines a fixedWidth to use.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static SelectionGrid(position: Rect, selected: number, texts: Array<string>, xCount: number): number\r\n        /** Make a grid of buttons.\r\n         * @param position Rectangle on the screen to use for the grid.\r\n         * @param selected The index of the selected grid button.\r\n         * @param texts An array of strings to show on the grid buttons.\r\n         * @param images An array of textures on the grid buttons.\r\n         * @param contents An array of text, image and tooltips for the grid button.\r\n         * @param xCount How many elements to fit in the horizontal direction. The controls will be scaled to fit unless the style defines a fixedWidth to use.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static SelectionGrid(position: Rect, selected: number, images: Array<Texture>, xCount: number): number\r\n        /** Make a grid of buttons.\r\n         * @param position Rectangle on the screen to use for the grid.\r\n         * @param selected The index of the selected grid button.\r\n         * @param texts An array of strings to show on the grid buttons.\r\n         * @param images An array of textures on the grid buttons.\r\n         * @param contents An array of text, image and tooltips for the grid button.\r\n         * @param xCount How many elements to fit in the horizontal direction. The controls will be scaled to fit unless the style defines a fixedWidth to use.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static SelectionGrid(position: Rect, selected: number, content: Array<GUIContent>, xCount: number): number\r\n        static HorizontalSlider(position: Rect, value: number, leftValue: number, rightValue: number, slider: GUIStyle, thumb: GUIStyle, thumbExtent: GUIStyle): number\r\n        /** A horizontal slider the user can drag to change a value between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @param slider The GUIStyle to use for displaying the dragging area. If left out, the horizontalSlider style from the current GUISkin is used.\r\n         * @param thumb The GUIStyle to use for displaying draggable thumb. If left out, the horizontalSliderThumb style from the current GUISkin is used.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static HorizontalSlider(position: Rect, value: number, leftValue: number, rightValue: number, slider: GUIStyle, thumb: GUIStyle): number\r\n        /** A horizontal slider the user can drag to change a value between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @param slider The GUIStyle to use for displaying the dragging area. If left out, the horizontalSlider style from the current GUISkin is used.\r\n         * @param thumb The GUIStyle to use for displaying draggable thumb. If left out, the horizontalSliderThumb style from the current GUISkin is used.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static HorizontalSlider(position: Rect, value: number, leftValue: number, rightValue: number): number\r\n        static VerticalSlider(position: Rect, value: number, topValue: number, bottomValue: number, slider: GUIStyle, thumb: GUIStyle, thumbExtent: GUIStyle): number\r\n        /** A vertical slider the user can drag to change a value between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param topValue The value at the top end of the slider.\r\n         * @param bottomValue The value at the bottom end of the slider.\r\n         * @param slider The GUIStyle to use for displaying the dragging area. If left out, the horizontalSlider style from the current GUISkin is used.\r\n         * @param thumb The GUIStyle to use for displaying draggable thumb. If left out, the horizontalSliderThumb style from the current GUISkin is used.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static VerticalSlider(position: Rect, value: number, topValue: number, bottomValue: number, slider: GUIStyle, thumb: GUIStyle): number\r\n        /** A vertical slider the user can drag to change a value between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param topValue The value at the top end of the slider.\r\n         * @param bottomValue The value at the bottom end of the slider.\r\n         * @param slider The GUIStyle to use for displaying the dragging area. If left out, the horizontalSlider style from the current GUISkin is used.\r\n         * @param thumb The GUIStyle to use for displaying draggable thumb. If left out, the horizontalSliderThumb style from the current GUISkin is used.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static VerticalSlider(position: Rect, value: number, topValue: number, bottomValue: number): number\r\n        static Slider(position: Rect, value: number, size: number, start: number, end: number, slider: GUIStyle, thumb: GUIStyle, horiz: boolean, id: number, thumbExtent: GUIStyle): number\r\n        /** Make a horizontal scrollbar. Scrollbars are what you use to scroll through a document. Most likely, you want to use scrollViews instead.\r\n         * @param position Rectangle on the screen to use for the scrollbar.\r\n         * @param value The position between min and max.\r\n         * @param size How much can we see?\r\n         * @param leftValue The value at the left end of the scrollbar.\r\n         * @param rightValue The value at the right end of the scrollbar.\r\n         * @param style The style to use for the scrollbar background. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @returns The modified value. This can be changed by the user by dragging the scrollbar, or clicking the arrows at the end. \r\n         */\r\n        static HorizontalScrollbar(position: Rect, value: number, size: number, leftValue: number, rightValue: number, style: GUIStyle): number\r\n        /** Make a horizontal scrollbar. Scrollbars are what you use to scroll through a document. Most likely, you want to use scrollViews instead.\r\n         * @param position Rectangle on the screen to use for the scrollbar.\r\n         * @param value The position between min and max.\r\n         * @param size How much can we see?\r\n         * @param leftValue The value at the left end of the scrollbar.\r\n         * @param rightValue The value at the right end of the scrollbar.\r\n         * @param style The style to use for the scrollbar background. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @returns The modified value. This can be changed by the user by dragging the scrollbar, or clicking the arrows at the end. \r\n         */\r\n        static HorizontalScrollbar(position: Rect, value: number, size: number, leftValue: number, rightValue: number): number\r\n        /** Make a vertical scrollbar. Scrollbars are what you use to scroll through a document. Most likely, you want to use scrollViews instead.\r\n         * @param position Rectangle on the screen to use for the scrollbar.\r\n         * @param value The position between min and max.\r\n         * @param size How much can we see?\r\n         * @param topValue The value at the top of the scrollbar.\r\n         * @param bottomValue The value at the bottom of the scrollbar.\r\n         * @param style The style to use for the scrollbar background. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @returns The modified value. This can be changed by the user by dragging the scrollbar, or clicking the arrows at the end. \r\n         */\r\n        static VerticalScrollbar(position: Rect, value: number, size: number, topValue: number, bottomValue: number, style: GUIStyle): number\r\n        /** Make a vertical scrollbar. Scrollbars are what you use to scroll through a document. Most likely, you want to use scrollViews instead.\r\n         * @param position Rectangle on the screen to use for the scrollbar.\r\n         * @param value The position between min and max.\r\n         * @param size How much can we see?\r\n         * @param topValue The value at the top of the scrollbar.\r\n         * @param bottomValue The value at the bottom of the scrollbar.\r\n         * @param style The style to use for the scrollbar background. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @returns The modified value. This can be changed by the user by dragging the scrollbar, or clicking the arrows at the end. \r\n         */\r\n        static VerticalScrollbar(position: Rect, value: number, size: number, topValue: number, bottomValue: number): number\r\n        static BeginClip(position: Rect, scrollOffset: Vector2, renderOffset: Vector2, resetOffset: boolean): void\r\n        static BeginClip(position: Rect): void\r\n        /** Begin a group. Must be matched with a call to EndGroup.\r\n         * @param position Rectangle on the screen to use for the group.\r\n         * @param text Text to display on the group.\r\n         * @param image Texture to display on the group.\r\n         * @param content Text, image and tooltip for this group. If supplied, any mouse clicks are \"captured\" by the group and not If left out, no background is rendered, and mouse clicks are passed.\r\n         * @param style The style to use for the background.\r\n         */\r\n        static BeginGroup(position: Rect, text: string, style: GUIStyle): void\r\n        /** Begin a group. Must be matched with a call to EndGroup.\r\n         * @param position Rectangle on the screen to use for the group.\r\n         * @param text Text to display on the group.\r\n         * @param image Texture to display on the group.\r\n         * @param content Text, image and tooltip for this group. If supplied, any mouse clicks are \"captured\" by the group and not If left out, no background is rendered, and mouse clicks are passed.\r\n         * @param style The style to use for the background.\r\n         */\r\n        static BeginGroup(position: Rect, image: Texture, style: GUIStyle): void\r\n        /** Begin a group. Must be matched with a call to EndGroup.\r\n         * @param position Rectangle on the screen to use for the group.\r\n         * @param text Text to display on the group.\r\n         * @param image Texture to display on the group.\r\n         * @param content Text, image and tooltip for this group. If supplied, any mouse clicks are \"captured\" by the group and not If left out, no background is rendered, and mouse clicks are passed.\r\n         * @param style The style to use for the background.\r\n         */\r\n        static BeginGroup(position: Rect, content: GUIContent, style: GUIStyle): void\r\n        /** Begin a group. Must be matched with a call to EndGroup.\r\n         * @param position Rectangle on the screen to use for the group.\r\n         * @param text Text to display on the group.\r\n         * @param image Texture to display on the group.\r\n         * @param content Text, image and tooltip for this group. If supplied, any mouse clicks are \"captured\" by the group and not If left out, no background is rendered, and mouse clicks are passed.\r\n         * @param style The style to use for the background.\r\n         */\r\n        static BeginGroup(position: Rect, text: string): void\r\n        /** Begin a group. Must be matched with a call to EndGroup.\r\n         * @param position Rectangle on the screen to use for the group.\r\n         * @param text Text to display on the group.\r\n         * @param image Texture to display on the group.\r\n         * @param content Text, image and tooltip for this group. If supplied, any mouse clicks are \"captured\" by the group and not If left out, no background is rendered, and mouse clicks are passed.\r\n         * @param style The style to use for the background.\r\n         */\r\n        static BeginGroup(position: Rect, image: Texture): void\r\n        /** Begin a group. Must be matched with a call to EndGroup.\r\n         * @param position Rectangle on the screen to use for the group.\r\n         * @param text Text to display on the group.\r\n         * @param image Texture to display on the group.\r\n         * @param content Text, image and tooltip for this group. If supplied, any mouse clicks are \"captured\" by the group and not If left out, no background is rendered, and mouse clicks are passed.\r\n         * @param style The style to use for the background.\r\n         */\r\n        static BeginGroup(position: Rect, content: GUIContent): void\r\n        /** Begin a group. Must be matched with a call to EndGroup.\r\n         * @param position Rectangle on the screen to use for the group.\r\n         * @param text Text to display on the group.\r\n         * @param image Texture to display on the group.\r\n         * @param content Text, image and tooltip for this group. If supplied, any mouse clicks are \"captured\" by the group and not If left out, no background is rendered, and mouse clicks are passed.\r\n         * @param style The style to use for the background.\r\n         */\r\n        static BeginGroup(position: Rect, style: GUIStyle): void\r\n        /** Begin a group. Must be matched with a call to EndGroup.\r\n         * @param position Rectangle on the screen to use for the group.\r\n         * @param text Text to display on the group.\r\n         * @param image Texture to display on the group.\r\n         * @param content Text, image and tooltip for this group. If supplied, any mouse clicks are \"captured\" by the group and not If left out, no background is rendered, and mouse clicks are passed.\r\n         * @param style The style to use for the background.\r\n         */\r\n        static BeginGroup(position: Rect): void\r\n        static EndGroup(): void\r\n        static EndClip(): void\r\n        /** Begin a scrolling view inside your GUI.\r\n         * @param position Rectangle on the screen to use for the ScrollView.\r\n         * @param scrollPosition The pixel distance that the view is scrolled in the X and Y directions.\r\n         * @param viewRect The rectangle used inside the scrollview.\r\n         * @param horizontalScrollbar Optional GUIStyle to use for the horizontal scrollbar. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param verticalScrollbar Optional GUIStyle to use for the vertical scrollbar. If left out, the verticalScrollbar style from the current GUISkin is used.\r\n         * @param alwaysShowHorizontal Optional parameter to always show the horizontal scrollbar. If false or left out, it is only shown when viewRect is wider than position.\r\n         * @param alwaysShowVertical Optional parameter to always show the vertical scrollbar. If false or left out, it is only shown when viewRect is taller than position.\r\n         * @returns The modified scrollPosition. Feed this back into the variable you pass in, as shown in the example. \r\n         */\r\n        static BeginScrollView(position: Rect, scrollPosition: Vector2, viewRect: Rect, alwaysShowHorizontal: boolean, alwaysShowVertical: boolean, horizontalScrollbar: GUIStyle, verticalScrollbar: GUIStyle): Vector2\r\n        /** Begin a scrolling view inside your GUI.\r\n         * @param position Rectangle on the screen to use for the ScrollView.\r\n         * @param scrollPosition The pixel distance that the view is scrolled in the X and Y directions.\r\n         * @param viewRect The rectangle used inside the scrollview.\r\n         * @param horizontalScrollbar Optional GUIStyle to use for the horizontal scrollbar. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param verticalScrollbar Optional GUIStyle to use for the vertical scrollbar. If left out, the verticalScrollbar style from the current GUISkin is used.\r\n         * @param alwaysShowHorizontal Optional parameter to always show the horizontal scrollbar. If false or left out, it is only shown when viewRect is wider than position.\r\n         * @param alwaysShowVertical Optional parameter to always show the vertical scrollbar. If false or left out, it is only shown when viewRect is taller than position.\r\n         * @returns The modified scrollPosition. Feed this back into the variable you pass in, as shown in the example. \r\n         */\r\n        static BeginScrollView(position: Rect, scrollPosition: Vector2, viewRect: Rect, alwaysShowHorizontal: boolean, alwaysShowVertical: boolean): Vector2\r\n        /** Begin a scrolling view inside your GUI.\r\n         * @param position Rectangle on the screen to use for the ScrollView.\r\n         * @param scrollPosition The pixel distance that the view is scrolled in the X and Y directions.\r\n         * @param viewRect The rectangle used inside the scrollview.\r\n         * @param horizontalScrollbar Optional GUIStyle to use for the horizontal scrollbar. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param verticalScrollbar Optional GUIStyle to use for the vertical scrollbar. If left out, the verticalScrollbar style from the current GUISkin is used.\r\n         * @param alwaysShowHorizontal Optional parameter to always show the horizontal scrollbar. If false or left out, it is only shown when viewRect is wider than position.\r\n         * @param alwaysShowVertical Optional parameter to always show the vertical scrollbar. If false or left out, it is only shown when viewRect is taller than position.\r\n         * @returns The modified scrollPosition. Feed this back into the variable you pass in, as shown in the example. \r\n         */\r\n        static BeginScrollView(position: Rect, scrollPosition: Vector2, viewRect: Rect, horizontalScrollbar: GUIStyle, verticalScrollbar: GUIStyle): Vector2\r\n        /** Begin a scrolling view inside your GUI.\r\n         * @param position Rectangle on the screen to use for the ScrollView.\r\n         * @param scrollPosition The pixel distance that the view is scrolled in the X and Y directions.\r\n         * @param viewRect The rectangle used inside the scrollview.\r\n         * @param horizontalScrollbar Optional GUIStyle to use for the horizontal scrollbar. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param verticalScrollbar Optional GUIStyle to use for the vertical scrollbar. If left out, the verticalScrollbar style from the current GUISkin is used.\r\n         * @param alwaysShowHorizontal Optional parameter to always show the horizontal scrollbar. If false or left out, it is only shown when viewRect is wider than position.\r\n         * @param alwaysShowVertical Optional parameter to always show the vertical scrollbar. If false or left out, it is only shown when viewRect is taller than position.\r\n         * @returns The modified scrollPosition. Feed this back into the variable you pass in, as shown in the example. \r\n         */\r\n        static BeginScrollView(position: Rect, scrollPosition: Vector2, viewRect: Rect): Vector2\r\n        /** Ends a scrollview started with a call to BeginScrollView.\r\n         */\r\n        static EndScrollView(handleScrollWheel: boolean): void\r\n        static EndScrollView(): void\r\n        /** Scrolls all enclosing scrollviews so they try to make position visible.\r\n         */\r\n        static ScrollTo(position: Rect): void\r\n        static ScrollTowards(position: Rect, maxDelta: number): boolean\r\n        static Window(id: number, clientRect: Rect, func: (id: number) => void, text: string, style: GUIStyle): Rect\r\n        static Window(id: number, clientRect: Rect, func: (id: number) => void, image: Texture, style: GUIStyle): Rect\r\n        static Window(id: number, clientRect: Rect, func: (id: number) => void, title: GUIContent, style: GUIStyle): Rect\r\n        static Window(id: number, clientRect: Rect, func: (id: number) => void, text: string): Rect\r\n        static Window(id: number, clientRect: Rect, func: (id: number) => void, image: Texture): Rect\r\n        static Window(id: number, clientRect: Rect, func: (id: number) => void, content: GUIContent): Rect\r\n        static ModalWindow(id: number, clientRect: Rect, func: (id: number) => void, text: string, style: GUIStyle): Rect\r\n        static ModalWindow(id: number, clientRect: Rect, func: (id: number) => void, image: Texture, style: GUIStyle): Rect\r\n        static ModalWindow(id: number, clientRect: Rect, func: (id: number) => void, content: GUIContent, style: GUIStyle): Rect\r\n        static ModalWindow(id: number, clientRect: Rect, func: (id: number) => void, text: string): Rect\r\n        static ModalWindow(id: number, clientRect: Rect, func: (id: number) => void, image: Texture): Rect\r\n        static ModalWindow(id: number, clientRect: Rect, func: (id: number) => void, content: GUIContent): Rect\r\n        protected constructor()\r\n        /** Global tinting color for the GUI.\r\n         */\r\n        static color: Color\r\n        /** Global tinting color for all background elements rendered by the GUI.\r\n         */\r\n        static backgroundColor: Color\r\n        /** Tinting color for all text rendered by the GUI.\r\n         */\r\n        static contentColor: Color\r\n        /** Returns true if any controls changed the value of the input data.\r\n         */\r\n        static changed: boolean\r\n        /** Is the GUI enabled?\r\n         */\r\n        static enabled: boolean\r\n        /** The sorting depth of the currently executing GUI behaviour.\r\n         */\r\n        static depth: number\r\n        /** The global skin to use.\r\n         */\r\n        static skin: GUISkin\r\n        /** The GUI transform matrix.\r\n         */\r\n        static matrix: Matrix4x4\r\n        /** The tooltip of the control the mouse is currently over, or which has keyboard focus. (Read Only).\r\n         */\r\n        static tooltip: string\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object as Object1, Array } from \"System\";\r\n    /** Utility class for making new GUI controls.\r\n     */\r\n    class GUIUtility extends Object1 {\r\n        /** Get a unique ID for a control, using an integer as a hint to help ensure correct matching of IDs to controls.\r\n         */\r\n        static GetControlID(hint: number, focusType: FocusType, rect: Rect): number\r\n        /** Get a unique ID for a control, using a the label content as a hint to help ensure correct matching of IDs to controls.\r\n         */\r\n        static GetControlID(contents: GUIContent, focus: FocusType, position: Rect): number\r\n        /** Get a unique ID for a control, using a the label content as a hint to help ensure correct matching of IDs to controls.\r\n         */\r\n        static GetControlID(contents: GUIContent, focus: FocusType): number\r\n        /** Get a unique ID for a control.\r\n         */\r\n        static GetControlID(focus: FocusType, position: Rect): number\r\n        /** Get a unique ID for a control, using an integer as a hint to help ensure correct matching of IDs to controls.\r\n         */\r\n        static GetControlID(hint: number, focus: FocusType): number\r\n        /** Get a unique ID for a control.\r\n         */\r\n        static GetControlID(focus: FocusType): number\r\n        /** Align a local space rectangle to the pixel grid.\r\n         * @param local The local space rectangle that needs to be processed.\r\n         * @param widthInPixels Width, in pixel units, of the axis-aligned bounding box that encompasses the aligned points.\r\n         * @param heightInPixels Height, in pixel units, of the axis-aligned bounding box that encompasses the aligned points.\r\n         * @returns The aligned rectangle in local space. \r\n         */\r\n        static AlignRectToDevice(rect: Rect, widthInPixels: jsb.Out<number>, heightInPixels: jsb.Out<number>): Rect\r\n        /** Align a local space rectangle to the pixel grid.\r\n         * @param local The local space rectangle that needs to be processed.\r\n         * @param widthInPixels Width, in pixel units, of the axis-aligned bounding box that encompasses the aligned points.\r\n         * @param heightInPixels Height, in pixel units, of the axis-aligned bounding box that encompasses the aligned points.\r\n         * @returns The aligned rectangle in local space. \r\n         */\r\n        static AlignRectToDevice(rect: Rect): Rect\r\n        /** Get a state object from a controlID.\r\n         */\r\n        static GetStateObject(t: any, controlID: number): Object1\r\n        /** Get an existing state object from a controlID.\r\n         */\r\n        static QueryStateObject(t: any, controlID: number): Object1\r\n        static ExitGUI(): void\r\n        /** Convert a point from GUI position to screen space.\r\n         */\r\n        static GUIToScreenPoint(guiPoint: Vector2): Vector2\r\n        /** Convert a rect from GUI position to screen space.\r\n         */\r\n        static GUIToScreenRect(guiRect: Rect): Rect\r\n        /** Convert a point from screen space to GUI position.\r\n         */\r\n        static ScreenToGUIPoint(screenPoint: Vector2): Vector2\r\n        /** Convert a rect from screen space to GUI position.\r\n         */\r\n        static ScreenToGUIRect(screenRect: Rect): Rect\r\n        /** Helper function to rotate the GUI around a point.\r\n         */\r\n        static RotateAroundPivot(angle: number, pivotPoint: Vector2): void\r\n        /** Helper function to scale the GUI around a point.\r\n         */\r\n        static ScaleAroundPivot(scale: Vector2, pivotPoint: Vector2): void\r\n        protected constructor()\r\n        /** A global property, which is true if a ModalWindow is being displayed, false otherwise.\r\n         */\r\n        static readonly hasModalWindow: boolean\r\n        /** Get access to the system-wide clipboard.\r\n         */\r\n        static systemCopyBuffer: string\r\n        /** The controlID of the current hot control.\r\n         */\r\n        static hotControl: number\r\n        /** The controlID of the control that has keyboard focus.\r\n         */\r\n        static keyboardControl: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object as Object1, Array, Enum } from \"System\";\r\n    /** The GUILayout class is the interface for Unity gui with automatic layout.\r\n     */\r\n    class GUILayout extends Object1 {\r\n        /** Make an auto-layout label.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static Label(image: Texture, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Make an auto-layout label.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static Label(text: string, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Make an auto-layout label.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static Label(content: GUIContent, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Make an auto-layout label.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static Label(image: Texture, ...options: GUILayoutOption[]): void\r\n        /** Make an auto-layout label.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static Label(text: string, ...options: GUILayoutOption[]): void\r\n        /** Make an auto-layout label.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static Label(content: GUIContent, ...options: GUILayoutOption[]): void\r\n        /** Make an auto-layout box.\r\n         * @param text Text to display on the box.\r\n         * @param image Texture to display on the box.\r\n         * @param content Text, image and tooltip for this box.\r\n         * @param style The style to use. If left out, the box style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static Box(image: Texture, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Make an auto-layout box.\r\n         * @param text Text to display on the box.\r\n         * @param image Texture to display on the box.\r\n         * @param content Text, image and tooltip for this box.\r\n         * @param style The style to use. If left out, the box style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static Box(text: string, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Make an auto-layout box.\r\n         * @param text Text to display on the box.\r\n         * @param image Texture to display on the box.\r\n         * @param content Text, image and tooltip for this box.\r\n         * @param style The style to use. If left out, the box style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static Box(content: GUIContent, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Make an auto-layout box.\r\n         * @param text Text to display on the box.\r\n         * @param image Texture to display on the box.\r\n         * @param content Text, image and tooltip for this box.\r\n         * @param style The style to use. If left out, the box style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static Box(image: Texture, ...options: GUILayoutOption[]): void\r\n        /** Make an auto-layout box.\r\n         * @param text Text to display on the box.\r\n         * @param image Texture to display on the box.\r\n         * @param content Text, image and tooltip for this box.\r\n         * @param style The style to use. If left out, the box style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static Box(text: string, ...options: GUILayoutOption[]): void\r\n        /** Make an auto-layout box.\r\n         * @param text Text to display on the box.\r\n         * @param image Texture to display on the box.\r\n         * @param content Text, image and tooltip for this box.\r\n         * @param style The style to use. If left out, the box style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static Box(content: GUIContent, ...options: GUILayoutOption[]): void\r\n        /** Make a single press button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns true when the users clicks the button. \r\n         */\r\n        static Button(image: Texture, style: GUIStyle, ...options: GUILayoutOption[]): boolean\r\n        /** Make a single press button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns true when the users clicks the button. \r\n         */\r\n        static Button(text: string, style: GUIStyle, ...options: GUILayoutOption[]): boolean\r\n        /** Make a single press button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns true when the users clicks the button. \r\n         */\r\n        static Button(content: GUIContent, style: GUIStyle, ...options: GUILayoutOption[]): boolean\r\n        /** Make a single press button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns true when the users clicks the button. \r\n         */\r\n        static Button(image: Texture, ...options: GUILayoutOption[]): boolean\r\n        /** Make a single press button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns true when the users clicks the button. \r\n         */\r\n        static Button(text: string, ...options: GUILayoutOption[]): boolean\r\n        /** Make a single press button.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns true when the users clicks the button. \r\n         */\r\n        static Button(content: GUIContent, ...options: GUILayoutOption[]): boolean\r\n        /** Make a repeating button. The button returns true as long as the user holds down the mouse.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns true when the holds down the mouse. \r\n         */\r\n        static RepeatButton(image: Texture, style: GUIStyle, ...options: GUILayoutOption[]): boolean\r\n        /** Make a repeating button. The button returns true as long as the user holds down the mouse.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns true when the holds down the mouse. \r\n         */\r\n        static RepeatButton(text: string, style: GUIStyle, ...options: GUILayoutOption[]): boolean\r\n        /** Make a repeating button. The button returns true as long as the user holds down the mouse.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns true when the holds down the mouse. \r\n         */\r\n        static RepeatButton(content: GUIContent, style: GUIStyle, ...options: GUILayoutOption[]): boolean\r\n        /** Make a repeating button. The button returns true as long as the user holds down the mouse.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns true when the holds down the mouse. \r\n         */\r\n        static RepeatButton(image: Texture, ...options: GUILayoutOption[]): boolean\r\n        /** Make a repeating button. The button returns true as long as the user holds down the mouse.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns true when the holds down the mouse. \r\n         */\r\n        static RepeatButton(text: string, ...options: GUILayoutOption[]): boolean\r\n        /** Make a repeating button. The button returns true as long as the user holds down the mouse.\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns true when the holds down the mouse. \r\n         */\r\n        static RepeatButton(content: GUIContent, ...options: GUILayoutOption[]): boolean\r\n        /** Make a single-line text field where the user can edit a string.\r\n         * @param text Text to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textArea style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The edited string. \r\n         */\r\n        static TextField(text: string, maxLength: number, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a single-line text field where the user can edit a string.\r\n         * @param text Text to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textArea style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The edited string. \r\n         */\r\n        static TextField(text: string, maxLength: number, ...options: GUILayoutOption[]): string\r\n        /** Make a single-line text field where the user can edit a string.\r\n         * @param text Text to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textArea style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The edited string. \r\n         */\r\n        static TextField(text: string, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a single-line text field where the user can edit a string.\r\n         * @param text Text to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textArea style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The edited string. \r\n         */\r\n        static TextField(text: string, ...options: GUILayoutOption[]): string\r\n        /** Make a text field where the user can enter a password.\r\n         * @param password Password to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maskChar Character to mask the password with.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textField style from the current GUISkin is used.\r\n         * @returns The edited password. \r\n         */\r\n        static PasswordField(password: string, maskChar: string, maxLength: number, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a text field where the user can enter a password.\r\n         * @param password Password to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maskChar Character to mask the password with.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textField style from the current GUISkin is used.\r\n         * @returns The edited password. \r\n         */\r\n        static PasswordField(password: string, maskChar: string, maxLength: number, ...options: GUILayoutOption[]): string\r\n        /** Make a text field where the user can enter a password.\r\n         * @param password Password to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maskChar Character to mask the password with.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textField style from the current GUISkin is used.\r\n         * @returns The edited password. \r\n         */\r\n        static PasswordField(password: string, maskChar: string, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a text field where the user can enter a password.\r\n         * @param password Password to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maskChar Character to mask the password with.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textField style from the current GUISkin is used.\r\n         * @returns The edited password. \r\n         */\r\n        static PasswordField(password: string, maskChar: string, ...options: GUILayoutOption[]): string\r\n        /** Make a multi-line text field where the user can edit a string.\r\n         * @param text Text to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textField style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.&amp;lt;br&amp;gt;\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The edited string. \r\n         */\r\n        static TextArea(text: string, maxLength: number, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a multi-line text field where the user can edit a string.\r\n         * @param text Text to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textField style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.&amp;lt;br&amp;gt;\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The edited string. \r\n         */\r\n        static TextArea(text: string, maxLength: number, ...options: GUILayoutOption[]): string\r\n        /** Make a multi-line text field where the user can edit a string.\r\n         * @param text Text to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textField style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.&amp;lt;br&amp;gt;\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The edited string. \r\n         */\r\n        static TextArea(text: string, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a multi-line text field where the user can edit a string.\r\n         * @param text Text to edit. The return value of this function should be assigned back to the string as shown in the example.\r\n         * @param maxLength The maximum length of the string. If left out, the user can type for ever and ever.\r\n         * @param style The style to use. If left out, the textField style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.&amp;lt;br&amp;gt;\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The edited string. \r\n         */\r\n        static TextArea(text: string, ...options: GUILayoutOption[]): string\r\n        /** Make an on/off toggle button.\r\n         * @param value Is the button on or off?\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The new value of the button. \r\n         */\r\n        static Toggle(value: boolean, image: Texture, style: GUIStyle, ...options: GUILayoutOption[]): boolean\r\n        /** Make an on/off toggle button.\r\n         * @param value Is the button on or off?\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The new value of the button. \r\n         */\r\n        static Toggle(value: boolean, text: string, style: GUIStyle, ...options: GUILayoutOption[]): boolean\r\n        /** Make an on/off toggle button.\r\n         * @param value Is the button on or off?\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The new value of the button. \r\n         */\r\n        static Toggle(value: boolean, content: GUIContent, style: GUIStyle, ...options: GUILayoutOption[]): boolean\r\n        /** Make an on/off toggle button.\r\n         * @param value Is the button on or off?\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The new value of the button. \r\n         */\r\n        static Toggle(value: boolean, image: Texture, ...options: GUILayoutOption[]): boolean\r\n        /** Make an on/off toggle button.\r\n         * @param value Is the button on or off?\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The new value of the button. \r\n         */\r\n        static Toggle(value: boolean, text: string, ...options: GUILayoutOption[]): boolean\r\n        /** Make an on/off toggle button.\r\n         * @param value Is the button on or off?\r\n         * @param text Text to display on the button.\r\n         * @param image Texture to display on the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The new value of the button. \r\n         */\r\n        static Toggle(value: boolean, content: GUIContent, ...options: GUILayoutOption[]): boolean\r\n        static Toolbar(selected: number, contents: Array<GUIContent>, enabled: Array<boolean>, style: GUIStyle, buttonSize: any, ...options: GUILayoutOption[]): number\r\n        static Toolbar(selected: number, texts: Array<string>, style: GUIStyle, buttonSize: any, ...options: GUILayoutOption[]): number\r\n        static Toolbar(selected: number, images: Array<Texture>, style: GUIStyle, buttonSize: any, ...options: GUILayoutOption[]): number\r\n        static Toolbar(selected: number, contents: Array<GUIContent>, style: GUIStyle, buttonSize: any, ...options: GUILayoutOption[]): number\r\n        static Toolbar(selected: number, contents: Array<GUIContent>, enabled: Array<boolean>, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a toolbar.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the buttons.\r\n         * @param images An array of textures on the buttons.\r\n         * @param contents An array of text, image and tooltips for the button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param buttonSize Determines how toolbar button size is calculated.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static Toolbar(selected: number, texts: Array<string>, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a toolbar.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the buttons.\r\n         * @param images An array of textures on the buttons.\r\n         * @param contents An array of text, image and tooltips for the button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param buttonSize Determines how toolbar button size is calculated.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static Toolbar(selected: number, images: Array<Texture>, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a toolbar.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the buttons.\r\n         * @param images An array of textures on the buttons.\r\n         * @param contents An array of text, image and tooltips for the button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param buttonSize Determines how toolbar button size is calculated.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static Toolbar(selected: number, contents: Array<GUIContent>, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a toolbar.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the buttons.\r\n         * @param images An array of textures on the buttons.\r\n         * @param contents An array of text, image and tooltips for the button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param buttonSize Determines how toolbar button size is calculated.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static Toolbar(selected: number, texts: Array<string>, ...options: GUILayoutOption[]): number\r\n        /** Make a toolbar.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the buttons.\r\n         * @param images An array of textures on the buttons.\r\n         * @param contents An array of text, image and tooltips for the button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param buttonSize Determines how toolbar button size is calculated.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static Toolbar(selected: number, images: Array<Texture>, ...options: GUILayoutOption[]): number\r\n        /** Make a toolbar.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the buttons.\r\n         * @param images An array of textures on the buttons.\r\n         * @param contents An array of text, image and tooltips for the button.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param buttonSize Determines how toolbar button size is calculated.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static Toolbar(selected: number, contents: Array<GUIContent>, ...options: GUILayoutOption[]): number\r\n        /** Make a Selection Grid.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the buttons.\r\n         * @param images An array of textures on the buttons.\r\n         * @param contents An array of text, image and tooltips for the button.\r\n         * @param xCount How many elements to fit in the horizontal direction. The elements will be scaled to fit unless the style defines a fixedWidth to use. The height of the control will be determined from the number of elements.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static SelectionGrid(selected: number, texts: Array<string>, xCount: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a Selection Grid.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the buttons.\r\n         * @param images An array of textures on the buttons.\r\n         * @param contents An array of text, image and tooltips for the button.\r\n         * @param xCount How many elements to fit in the horizontal direction. The elements will be scaled to fit unless the style defines a fixedWidth to use. The height of the control will be determined from the number of elements.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static SelectionGrid(selected: number, images: Array<Texture>, xCount: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a Selection Grid.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the buttons.\r\n         * @param images An array of textures on the buttons.\r\n         * @param contents An array of text, image and tooltips for the button.\r\n         * @param xCount How many elements to fit in the horizontal direction. The elements will be scaled to fit unless the style defines a fixedWidth to use. The height of the control will be determined from the number of elements.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static SelectionGrid(selected: number, contents: Array<GUIContent>, xCount: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a Selection Grid.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the buttons.\r\n         * @param images An array of textures on the buttons.\r\n         * @param contents An array of text, image and tooltips for the button.\r\n         * @param xCount How many elements to fit in the horizontal direction. The elements will be scaled to fit unless the style defines a fixedWidth to use. The height of the control will be determined from the number of elements.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static SelectionGrid(selected: number, texts: Array<string>, xCount: number, ...options: GUILayoutOption[]): number\r\n        /** Make a Selection Grid.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the buttons.\r\n         * @param images An array of textures on the buttons.\r\n         * @param contents An array of text, image and tooltips for the button.\r\n         * @param xCount How many elements to fit in the horizontal direction. The elements will be scaled to fit unless the style defines a fixedWidth to use. The height of the control will be determined from the number of elements.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static SelectionGrid(selected: number, images: Array<Texture>, xCount: number, ...options: GUILayoutOption[]): number\r\n        /** Make a Selection Grid.\r\n         * @param selected The index of the selected button.\r\n         * @param texts An array of strings to show on the buttons.\r\n         * @param images An array of textures on the buttons.\r\n         * @param contents An array of text, image and tooltips for the button.\r\n         * @param xCount How many elements to fit in the horizontal direction. The elements will be scaled to fit unless the style defines a fixedWidth to use. The height of the control will be determined from the number of elements.\r\n         * @param style The style to use. If left out, the button style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The index of the selected button. \r\n         */\r\n        static SelectionGrid(selected: number, content: Array<GUIContent>, xCount: number, ...options: GUILayoutOption[]): number\r\n        /** A horizontal slider the user can drag to change a value between a min and a max.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @param slider The GUIStyle to use for displaying the dragging area. If left out, the horizontalSlider style from the current GUISkin is used.\r\n         * @param thumb The GUIStyle to use for displaying draggable thumb. If left out, the horizontalSliderThumb style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static HorizontalSlider(value: number, leftValue: number, rightValue: number, slider: GUIStyle, thumb: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** A horizontal slider the user can drag to change a value between a min and a max.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @param slider The GUIStyle to use for displaying the dragging area. If left out, the horizontalSlider style from the current GUISkin is used.\r\n         * @param thumb The GUIStyle to use for displaying draggable thumb. If left out, the horizontalSliderThumb style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static HorizontalSlider(value: number, leftValue: number, rightValue: number, ...options: GUILayoutOption[]): number\r\n        /** A vertical slider the user can drag to change a value between a min and a max.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param topValue The value at the top end of the slider.\r\n         * @param bottomValue The value at the bottom end of the slider.\r\n         * @param slider The GUIStyle to use for displaying the dragging area. If left out, the horizontalSlider style from the current GUISkin is used.\r\n         * @param thumb The GUIStyle to use for displaying draggable thumb. If left out, the horizontalSliderThumb style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static VerticalSlider(value: number, leftValue: number, rightValue: number, slider: GUIStyle, thumb: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** A vertical slider the user can drag to change a value between a min and a max.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param topValue The value at the top end of the slider.\r\n         * @param bottomValue The value at the bottom end of the slider.\r\n         * @param slider The GUIStyle to use for displaying the dragging area. If left out, the horizontalSlider style from the current GUISkin is used.\r\n         * @param thumb The GUIStyle to use for displaying draggable thumb. If left out, the horizontalSliderThumb style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static VerticalSlider(value: number, leftValue: number, rightValue: number, ...options: GUILayoutOption[]): number\r\n        /** Make a horizontal scrollbar.\r\n         * @param value The position between min and max.\r\n         * @param size How much can we see?\r\n         * @param leftValue The value at the left end of the scrollbar.\r\n         * @param rightValue The value at the right end of the scrollbar.\r\n         * @param style The style to use for the scrollbar background. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.\r\n         * @returns The modified value. This can be changed by the user by dragging the scrollbar, or clicking the arrows at the end. \r\n         */\r\n        static HorizontalScrollbar(value: number, size: number, leftValue: number, rightValue: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a horizontal scrollbar.\r\n         * @param value The position between min and max.\r\n         * @param size How much can we see?\r\n         * @param leftValue The value at the left end of the scrollbar.\r\n         * @param rightValue The value at the right end of the scrollbar.\r\n         * @param style The style to use for the scrollbar background. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.\r\n         * @returns The modified value. This can be changed by the user by dragging the scrollbar, or clicking the arrows at the end. \r\n         */\r\n        static HorizontalScrollbar(value: number, size: number, leftValue: number, rightValue: number, ...options: GUILayoutOption[]): number\r\n        /** Make a vertical scrollbar.\r\n         * @param value The position between min and max.\r\n         * @param size How much can we see?\r\n         * @param topValue The value at the top end of the scrollbar.\r\n         * @param bottomValue The value at the bottom end of the scrollbar.\r\n         * @param style The style to use for the scrollbar background. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.\r\n         * @returns The modified value. This can be changed by the user by dragging the scrollbar, or clicking the arrows at the end. \r\n         */\r\n        static VerticalScrollbar(value: number, size: number, topValue: number, bottomValue: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a vertical scrollbar.\r\n         * @param value The position between min and max.\r\n         * @param size How much can we see?\r\n         * @param topValue The value at the top end of the scrollbar.\r\n         * @param bottomValue The value at the bottom end of the scrollbar.\r\n         * @param style The style to use for the scrollbar background. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.\r\n         * @returns The modified value. This can be changed by the user by dragging the scrollbar, or clicking the arrows at the end. \r\n         */\r\n        static VerticalScrollbar(value: number, size: number, topValue: number, bottomValue: number, ...options: GUILayoutOption[]): number\r\n        /** Insert a space in the current layout group.\r\n         */\r\n        static Space(pixels: number): void\r\n        static FlexibleSpace(): void\r\n        /** Begin a Horizontal control group.\r\n         * @param text Text to display on group.\r\n         * @param image Texture to display on group.\r\n         * @param content Text, image, and tooltip for this group.\r\n         * @param style The style to use for background image and padding values. If left out, the background is transparent.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static BeginHorizontal(text: string, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Begin a Horizontal control group.\r\n         * @param text Text to display on group.\r\n         * @param image Texture to display on group.\r\n         * @param content Text, image, and tooltip for this group.\r\n         * @param style The style to use for background image and padding values. If left out, the background is transparent.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static BeginHorizontal(image: Texture, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Begin a Horizontal control group.\r\n         * @param text Text to display on group.\r\n         * @param image Texture to display on group.\r\n         * @param content Text, image, and tooltip for this group.\r\n         * @param style The style to use for background image and padding values. If left out, the background is transparent.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static BeginHorizontal(content: GUIContent, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Begin a Horizontal control group.\r\n         * @param text Text to display on group.\r\n         * @param image Texture to display on group.\r\n         * @param content Text, image, and tooltip for this group.\r\n         * @param style The style to use for background image and padding values. If left out, the background is transparent.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static BeginHorizontal(style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Begin a Horizontal control group.\r\n         * @param text Text to display on group.\r\n         * @param image Texture to display on group.\r\n         * @param content Text, image, and tooltip for this group.\r\n         * @param style The style to use for background image and padding values. If left out, the background is transparent.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static BeginHorizontal(...options: GUILayoutOption[]): void\r\n        static EndHorizontal(): void\r\n        /** Begin a vertical control group.\r\n         * @param text Text to display on group.\r\n         * @param image Texture to display on group.\r\n         * @param content Text, image, and tooltip for this group.\r\n         * @param style The style to use for background image and padding values. If left out, the background is transparent.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static BeginVertical(text: string, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Begin a vertical control group.\r\n         * @param text Text to display on group.\r\n         * @param image Texture to display on group.\r\n         * @param content Text, image, and tooltip for this group.\r\n         * @param style The style to use for background image and padding values. If left out, the background is transparent.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static BeginVertical(image: Texture, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Begin a vertical control group.\r\n         * @param text Text to display on group.\r\n         * @param image Texture to display on group.\r\n         * @param content Text, image, and tooltip for this group.\r\n         * @param style The style to use for background image and padding values. If left out, the background is transparent.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static BeginVertical(content: GUIContent, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Begin a vertical control group.\r\n         * @param text Text to display on group.\r\n         * @param image Texture to display on group.\r\n         * @param content Text, image, and tooltip for this group.\r\n         * @param style The style to use for background image and padding values. If left out, the background is transparent.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static BeginVertical(style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Begin a vertical control group.\r\n         * @param text Text to display on group.\r\n         * @param image Texture to display on group.\r\n         * @param content Text, image, and tooltip for this group.\r\n         * @param style The style to use for background image and padding values. If left out, the background is transparent.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static BeginVertical(...options: GUILayoutOption[]): void\r\n        static EndVertical(): void\r\n        /** Begin a GUILayout block of GUI controls in a fixed screen area.\r\n         * @param text Optional text to display in the area.\r\n         * @param image Optional texture to display in the area.\r\n         * @param content Optional text, image and tooltip top display for this area.\r\n         * @param style The style to use. If left out, the empty GUIStyle (GUIStyle.none) is used, giving a transparent background.\r\n         */\r\n        static BeginArea(screenRect: Rect, text: string, style: GUIStyle): void\r\n        /** Begin a GUILayout block of GUI controls in a fixed screen area.\r\n         * @param text Optional text to display in the area.\r\n         * @param image Optional texture to display in the area.\r\n         * @param content Optional text, image and tooltip top display for this area.\r\n         * @param style The style to use. If left out, the empty GUIStyle (GUIStyle.none) is used, giving a transparent background.\r\n         */\r\n        static BeginArea(screenRect: Rect, image: Texture, style: GUIStyle): void\r\n        /** Begin a GUILayout block of GUI controls in a fixed screen area.\r\n         * @param text Optional text to display in the area.\r\n         * @param image Optional texture to display in the area.\r\n         * @param content Optional text, image and tooltip top display for this area.\r\n         * @param style The style to use. If left out, the empty GUIStyle (GUIStyle.none) is used, giving a transparent background.\r\n         */\r\n        static BeginArea(screenRect: Rect, content: GUIContent, style: GUIStyle): void\r\n        /** Begin a GUILayout block of GUI controls in a fixed screen area.\r\n         * @param text Optional text to display in the area.\r\n         * @param image Optional texture to display in the area.\r\n         * @param content Optional text, image and tooltip top display for this area.\r\n         * @param style The style to use. If left out, the empty GUIStyle (GUIStyle.none) is used, giving a transparent background.\r\n         */\r\n        static BeginArea(screenRect: Rect, text: string): void\r\n        /** Begin a GUILayout block of GUI controls in a fixed screen area.\r\n         * @param text Optional text to display in the area.\r\n         * @param image Optional texture to display in the area.\r\n         * @param content Optional text, image and tooltip top display for this area.\r\n         * @param style The style to use. If left out, the empty GUIStyle (GUIStyle.none) is used, giving a transparent background.\r\n         */\r\n        static BeginArea(screenRect: Rect, image: Texture): void\r\n        /** Begin a GUILayout block of GUI controls in a fixed screen area.\r\n         * @param text Optional text to display in the area.\r\n         * @param image Optional texture to display in the area.\r\n         * @param content Optional text, image and tooltip top display for this area.\r\n         * @param style The style to use. If left out, the empty GUIStyle (GUIStyle.none) is used, giving a transparent background.\r\n         */\r\n        static BeginArea(screenRect: Rect, content: GUIContent): void\r\n        /** Begin a GUILayout block of GUI controls in a fixed screen area.\r\n         * @param text Optional text to display in the area.\r\n         * @param image Optional texture to display in the area.\r\n         * @param content Optional text, image and tooltip top display for this area.\r\n         * @param style The style to use. If left out, the empty GUIStyle (GUIStyle.none) is used, giving a transparent background.\r\n         */\r\n        static BeginArea(screenRect: Rect, style: GUIStyle): void\r\n        /** Begin a GUILayout block of GUI controls in a fixed screen area.\r\n         * @param text Optional text to display in the area.\r\n         * @param image Optional texture to display in the area.\r\n         * @param content Optional text, image and tooltip top display for this area.\r\n         * @param style The style to use. If left out, the empty GUIStyle (GUIStyle.none) is used, giving a transparent background.\r\n         */\r\n        static BeginArea(screenRect: Rect): void\r\n        static EndArea(): void\r\n        /** Begin an automatically laid out scrollview.\r\n         * @param scrollPosition The position to use display.\r\n         * @param alwayShowHorizontal Optional parameter to always show the horizontal scrollbar. If false or left out, it is only shown when the content inside the ScrollView is wider than the scrollview itself.\r\n         * @param alwayShowVertical Optional parameter to always show the vertical scrollbar. If false or left out, it is only shown when content inside the ScrollView is taller than the scrollview itself.\r\n         * @param horizontalScrollbar Optional GUIStyle to use for the horizontal scrollbar. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param verticalScrollbar Optional GUIStyle to use for the vertical scrollbar. If left out, the verticalScrollbar style from the current GUISkin is used.\r\n         * @returns The modified scrollPosition. Feed this back into the variable you pass in, as shown in the example. \r\n         */\r\n        static BeginScrollView(scrollPosition: Vector2, alwaysShowHorizontal: boolean, alwaysShowVertical: boolean, horizontalScrollbar: GUIStyle, verticalScrollbar: GUIStyle, background: GUIStyle, ...options: GUILayoutOption[]): Vector2\r\n        /** Begin an automatically laid out scrollview.\r\n         * @param scrollPosition The position to use display.\r\n         * @param alwayShowHorizontal Optional parameter to always show the horizontal scrollbar. If false or left out, it is only shown when the content inside the ScrollView is wider than the scrollview itself.\r\n         * @param alwayShowVertical Optional parameter to always show the vertical scrollbar. If false or left out, it is only shown when content inside the ScrollView is taller than the scrollview itself.\r\n         * @param horizontalScrollbar Optional GUIStyle to use for the horizontal scrollbar. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param verticalScrollbar Optional GUIStyle to use for the vertical scrollbar. If left out, the verticalScrollbar style from the current GUISkin is used.\r\n         * @returns The modified scrollPosition. Feed this back into the variable you pass in, as shown in the example. \r\n         */\r\n        static BeginScrollView(scrollPosition: Vector2, alwaysShowHorizontal: boolean, alwaysShowVertical: boolean, horizontalScrollbar: GUIStyle, verticalScrollbar: GUIStyle, ...options: GUILayoutOption[]): Vector2\r\n        /** Begin an automatically laid out scrollview.\r\n         * @param scrollPosition The position to use display.\r\n         * @param alwayShowHorizontal Optional parameter to always show the horizontal scrollbar. If false or left out, it is only shown when the content inside the ScrollView is wider than the scrollview itself.\r\n         * @param alwayShowVertical Optional parameter to always show the vertical scrollbar. If false or left out, it is only shown when content inside the ScrollView is taller than the scrollview itself.\r\n         * @param horizontalScrollbar Optional GUIStyle to use for the horizontal scrollbar. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param verticalScrollbar Optional GUIStyle to use for the vertical scrollbar. If left out, the verticalScrollbar style from the current GUISkin is used.\r\n         * @returns The modified scrollPosition. Feed this back into the variable you pass in, as shown in the example. \r\n         */\r\n        static BeginScrollView(scrollPosition: Vector2, alwaysShowHorizontal: boolean, alwaysShowVertical: boolean, ...options: GUILayoutOption[]): Vector2\r\n        /** Begin an automatically laid out scrollview.\r\n         * @param scrollPosition The position to use display.\r\n         * @param alwayShowHorizontal Optional parameter to always show the horizontal scrollbar. If false or left out, it is only shown when the content inside the ScrollView is wider than the scrollview itself.\r\n         * @param alwayShowVertical Optional parameter to always show the vertical scrollbar. If false or left out, it is only shown when content inside the ScrollView is taller than the scrollview itself.\r\n         * @param horizontalScrollbar Optional GUIStyle to use for the horizontal scrollbar. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param verticalScrollbar Optional GUIStyle to use for the vertical scrollbar. If left out, the verticalScrollbar style from the current GUISkin is used.\r\n         * @returns The modified scrollPosition. Feed this back into the variable you pass in, as shown in the example. \r\n         */\r\n        static BeginScrollView(scrollPosition: Vector2, horizontalScrollbar: GUIStyle, verticalScrollbar: GUIStyle, ...options: GUILayoutOption[]): Vector2\r\n        /** Begin an automatically laid out scrollview.\r\n         * @param scrollPosition The position to use display.\r\n         * @param alwayShowHorizontal Optional parameter to always show the horizontal scrollbar. If false or left out, it is only shown when the content inside the ScrollView is wider than the scrollview itself.\r\n         * @param alwayShowVertical Optional parameter to always show the vertical scrollbar. If false or left out, it is only shown when content inside the ScrollView is taller than the scrollview itself.\r\n         * @param horizontalScrollbar Optional GUIStyle to use for the horizontal scrollbar. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param verticalScrollbar Optional GUIStyle to use for the vertical scrollbar. If left out, the verticalScrollbar style from the current GUISkin is used.\r\n         * @returns The modified scrollPosition. Feed this back into the variable you pass in, as shown in the example. \r\n         */\r\n        static BeginScrollView(scrollPosition: Vector2, style: GUIStyle): Vector2\r\n        /** Begin an automatically laid out scrollview.\r\n         * @param scrollPosition The position to use display.\r\n         * @param alwayShowHorizontal Optional parameter to always show the horizontal scrollbar. If false or left out, it is only shown when the content inside the ScrollView is wider than the scrollview itself.\r\n         * @param alwayShowVertical Optional parameter to always show the vertical scrollbar. If false or left out, it is only shown when content inside the ScrollView is taller than the scrollview itself.\r\n         * @param horizontalScrollbar Optional GUIStyle to use for the horizontal scrollbar. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param verticalScrollbar Optional GUIStyle to use for the vertical scrollbar. If left out, the verticalScrollbar style from the current GUISkin is used.\r\n         * @returns The modified scrollPosition. Feed this back into the variable you pass in, as shown in the example. \r\n         */\r\n        static BeginScrollView(scrollPosition: Vector2, style: GUIStyle, ...options: GUILayoutOption[]): Vector2\r\n        /** Begin an automatically laid out scrollview.\r\n         * @param scrollPosition The position to use display.\r\n         * @param alwayShowHorizontal Optional parameter to always show the horizontal scrollbar. If false or left out, it is only shown when the content inside the ScrollView is wider than the scrollview itself.\r\n         * @param alwayShowVertical Optional parameter to always show the vertical scrollbar. If false or left out, it is only shown when content inside the ScrollView is taller than the scrollview itself.\r\n         * @param horizontalScrollbar Optional GUIStyle to use for the horizontal scrollbar. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param verticalScrollbar Optional GUIStyle to use for the vertical scrollbar. If left out, the verticalScrollbar style from the current GUISkin is used.\r\n         * @returns The modified scrollPosition. Feed this back into the variable you pass in, as shown in the example. \r\n         */\r\n        static BeginScrollView(scrollPosition: Vector2, ...options: GUILayoutOption[]): Vector2\r\n        static EndScrollView(): void\r\n        static Window(id: number, screenRect: Rect, func: (id: number) => void, text: string, style: GUIStyle, ...options: GUILayoutOption[]): Rect\r\n        static Window(id: number, screenRect: Rect, func: (id: number) => void, image: Texture, style: GUIStyle, ...options: GUILayoutOption[]): Rect\r\n        static Window(id: number, screenRect: Rect, func: (id: number) => void, content: GUIContent, style: GUIStyle, ...options: GUILayoutOption[]): Rect\r\n        static Window(id: number, screenRect: Rect, func: (id: number) => void, text: string, ...options: GUILayoutOption[]): Rect\r\n        static Window(id: number, screenRect: Rect, func: (id: number) => void, image: Texture, ...options: GUILayoutOption[]): Rect\r\n        static Window(id: number, screenRect: Rect, func: (id: number) => void, content: GUIContent, ...options: GUILayoutOption[]): Rect\r\n        /** Option passed to a control to give it an absolute width.\r\n         */\r\n        static Width(width: number): GUILayoutOption\r\n        /** Option passed to a control to specify a minimum width.\n\r\n         */\r\n        static MinWidth(minWidth: number): GUILayoutOption\r\n        /** Option passed to a control to specify a maximum width.\r\n         */\r\n        static MaxWidth(maxWidth: number): GUILayoutOption\r\n        /** Option passed to a control to give it an absolute height.\r\n         */\r\n        static Height(height: number): GUILayoutOption\r\n        /** Option passed to a control to specify a minimum height.\r\n         */\r\n        static MinHeight(minHeight: number): GUILayoutOption\r\n        /** Option passed to a control to specify a maximum height.\r\n         */\r\n        static MaxHeight(maxHeight: number): GUILayoutOption\r\n        /** Option passed to a control to allow or disallow horizontal expansion.\r\n         */\r\n        static ExpandWidth(expand: boolean): GUILayoutOption\r\n        /** Option passed to a control to allow or disallow vertical expansion.\r\n         */\r\n        static ExpandHeight(expand: boolean): GUILayoutOption\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object as Object1, Array } from \"System\";\r\n    /** Utility functions for implementing and extending the GUILayout class.\r\n     */\r\n    class GUILayoutUtility extends Object1 {\r\n        /** Reserve layout space for a flexible rect.\r\n         * @param minWidth The minimum width of the area passed back.\r\n         * @param maxWidth The maximum width of the area passed back.\r\n         * @param minHeight The minimum width of the area passed back.\r\n         * @param maxHeight The maximum width of the area passed back.\r\n         * @param style An optional style. If specified, the style's padding value will be added to the sizes requested & the style's margin values will be used for spacing.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns A rectangle with size between minWidth & maxWidth on both axes. \r\n         */\r\n        static GetRect(minWidth: number, maxWidth: number, minHeight: number, maxHeight: number, style: GUIStyle): Rect\r\n        /** Reserve layout space for a flexible rect.\r\n         * @param minWidth The minimum width of the area passed back.\r\n         * @param maxWidth The maximum width of the area passed back.\r\n         * @param minHeight The minimum width of the area passed back.\r\n         * @param maxHeight The maximum width of the area passed back.\r\n         * @param style An optional style. If specified, the style's padding value will be added to the sizes requested & the style's margin values will be used for spacing.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns A rectangle with size between minWidth & maxWidth on both axes. \r\n         */\r\n        static GetRect(minWidth: number, maxWidth: number, minHeight: number, maxHeight: number, style: GUIStyle, ...options: GUILayoutOption[]): Rect\r\n        /** Reserve layout space for a flexible rect.\r\n         * @param minWidth The minimum width of the area passed back.\r\n         * @param maxWidth The maximum width of the area passed back.\r\n         * @param minHeight The minimum width of the area passed back.\r\n         * @param maxHeight The maximum width of the area passed back.\r\n         * @param style An optional style. If specified, the style's padding value will be added to the sizes requested & the style's margin values will be used for spacing.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns A rectangle with size between minWidth & maxWidth on both axes. \r\n         */\r\n        static GetRect(minWidth: number, maxWidth: number, minHeight: number, maxHeight: number): Rect\r\n        /** Reserve layout space for a flexible rect.\r\n         * @param minWidth The minimum width of the area passed back.\r\n         * @param maxWidth The maximum width of the area passed back.\r\n         * @param minHeight The minimum width of the area passed back.\r\n         * @param maxHeight The maximum width of the area passed back.\r\n         * @param style An optional style. If specified, the style's padding value will be added to the sizes requested & the style's margin values will be used for spacing.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns A rectangle with size between minWidth & maxWidth on both axes. \r\n         */\r\n        static GetRect(minWidth: number, maxWidth: number, minHeight: number, maxHeight: number, ...options: GUILayoutOption[]): Rect\r\n        /** Reserve layout space for a rectangle with a fixed content area.\r\n         * @param width The width of the area you want.\r\n         * @param height The height of the area you want.\r\n         * @param style An optional GUIStyle to layout for. If specified, the style's padding value will be added to your sizes & its margin value will be used for spacing.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The rectanlge to put your control in. \r\n         */\r\n        static GetRect(width: number, height: number, style: GUIStyle): Rect\r\n        /** Reserve layout space for a rectangle with a fixed content area.\r\n         * @param width The width of the area you want.\r\n         * @param height The height of the area you want.\r\n         * @param style An optional GUIStyle to layout for. If specified, the style's padding value will be added to your sizes & its margin value will be used for spacing.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The rectanlge to put your control in. \r\n         */\r\n        static GetRect(width: number, height: number, style: GUIStyle, ...options: GUILayoutOption[]): Rect\r\n        /** Reserve layout space for a rectangle for displaying some contents with a specific style.\r\n         * @param content The content to make room for displaying.\r\n         * @param style The GUIStyle to layout for.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns A rectangle that is large enough to contain content when rendered in style. \r\n         */\r\n        static GetRect(content: GUIContent, style: GUIStyle): Rect\r\n        /** Reserve layout space for a rectangle with a fixed content area.\r\n         * @param width The width of the area you want.\r\n         * @param height The height of the area you want.\r\n         * @param style An optional GUIStyle to layout for. If specified, the style's padding value will be added to your sizes & its margin value will be used for spacing.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The rectanlge to put your control in. \r\n         */\r\n        static GetRect(width: number, height: number): Rect\r\n        /** Reserve layout space for a rectangle for displaying some contents with a specific style.\r\n         * @param content The content to make room for displaying.\r\n         * @param style The GUIStyle to layout for.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns A rectangle that is large enough to contain content when rendered in style. \r\n         */\r\n        static GetRect(content: GUIContent, style: GUIStyle, ...options: GUILayoutOption[]): Rect\r\n        /** Reserve layout space for a rectangle with a fixed content area.\r\n         * @param width The width of the area you want.\r\n         * @param height The height of the area you want.\r\n         * @param style An optional GUIStyle to layout for. If specified, the style's padding value will be added to your sizes & its margin value will be used for spacing.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The rectanlge to put your control in. \r\n         */\r\n        static GetRect(width: number, height: number, ...options: GUILayoutOption[]): Rect\r\n        static GetLastRect(): Rect\r\n        /** Reserve layout space for a rectangle with a specific aspect ratio.\r\n         * @param aspect The aspect ratio of the element (width / height).\r\n         * @param style An optional style. If specified, the style's padding value will be added to the sizes of the returned rectangle & the style's margin values will be used for spacing.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The rect for the control. \r\n         */\r\n        static GetAspectRect(aspect: number, style: GUIStyle): Rect\r\n        /** Reserve layout space for a rectangle with a specific aspect ratio.\r\n         * @param aspect The aspect ratio of the element (width / height).\r\n         * @param style An optional style. If specified, the style's padding value will be added to the sizes of the returned rectangle & the style's margin values will be used for spacing.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The rect for the control. \r\n         */\r\n        static GetAspectRect(aspect: number, style: GUIStyle, ...options: GUILayoutOption[]): Rect\r\n        /** Reserve layout space for a rectangle with a specific aspect ratio.\r\n         * @param aspect The aspect ratio of the element (width / height).\r\n         * @param style An optional style. If specified, the style's padding value will be added to the sizes of the returned rectangle & the style's margin values will be used for spacing.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The rect for the control. \r\n         */\r\n        static GetAspectRect(aspect: number): Rect\r\n        /** Reserve layout space for a rectangle with a specific aspect ratio.\r\n         * @param aspect The aspect ratio of the element (width / height).\r\n         * @param style An optional style. If specified, the style's padding value will be added to the sizes of the returned rectangle & the style's margin values will be used for spacing.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The rect for the control. \r\n         */\r\n        static GetAspectRect(aspect: number, ...options: GUILayoutOption[]): Rect\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Object as Object1 } from \"System\";\r\n    /** Class internally used to pass layout options into GUILayout functions. You don't use these directly, but construct them with the layouting functions in the GUILayout class.\r\n     */\r\n    class GUILayoutOption extends Object1 {\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Object as Object1 } from \"System\";\r\n    /** The contents of a GUI element.\r\n     */\r\n    class GUIContent extends Object1 {\r\n        constructor(text: string, image: Texture, tooltip: string)\r\n        constructor(text: string, image: Texture)\r\n        constructor(text: string, tooltip: string)\r\n        constructor(image: Texture, tooltip: string)\r\n        constructor(text: string)\r\n        constructor(image: Texture)\r\n        constructor(src: GUIContent)\r\n        constructor()\r\n        /** The text contained.\r\n         */\r\n        text: string\r\n        /** The icon image contained.\r\n         */\r\n        image: Texture\r\n        /** The tooltip of this element.\r\n         */\r\n        tooltip: string\r\n        /** Shorthand for empty content.\r\n         */\r\n        static none: GUIContent\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Array, Object as Object1 } from \"System\";\r\n    import { IEnumerator } from \"System.Collections\";\r\n    /** Defines how GUI looks and behaves.\r\n     */\r\n    class GUISkin extends ScriptableObject {\r\n        constructor()\r\n        /** Get a named GUIStyle.\r\n         */\r\n        GetStyle(styleName: string): GUIStyle\r\n        /** Try to search for a GUIStyle. This functions returns NULL and does not give an error.\r\n         */\r\n        FindStyle(styleName: string): GUIStyle\r\n        GetEnumerator(): IEnumerator\r\n        /** The default font to use for all styles.\r\n         */\r\n        font: any\r\n        /** Style used by default for GUI.Box controls.\r\n         */\r\n        box: GUIStyle\r\n        /** Style used by default for GUI.Label controls.\r\n         */\r\n        label: GUIStyle\r\n        /** Style used by default for GUI.TextField controls.\r\n         */\r\n        textField: GUIStyle\r\n        /** Style used by default for GUI.TextArea controls.\r\n         */\r\n        textArea: GUIStyle\r\n        /** Style used by default for GUI.Button controls.\r\n         */\r\n        button: GUIStyle\r\n        /** Style used by default for GUI.Toggle controls.\r\n         */\r\n        toggle: GUIStyle\r\n        /** Style used by default for Window controls (See Also: GUI.Window).\r\n         */\r\n        window: GUIStyle\r\n        /** Style used by default for the background part of GUI.HorizontalSlider controls.\r\n         */\r\n        horizontalSlider: GUIStyle\r\n        /** Style used by default for the thumb that is dragged in GUI.HorizontalSlider controls.\r\n         */\r\n        horizontalSliderThumb: GUIStyle\r\n        /** Style used by default for the background part of GUI.VerticalSlider controls.\r\n         */\r\n        verticalSlider: GUIStyle\r\n        /** Style used by default for the thumb that is dragged in GUI.VerticalSlider controls.\r\n         */\r\n        verticalSliderThumb: GUIStyle\r\n        /** Style used by default for the background part of GUI.HorizontalScrollbar controls.\r\n         */\r\n        horizontalScrollbar: GUIStyle\r\n        /** Style used by default for the thumb that is dragged in GUI.HorizontalScrollbar controls.\r\n         */\r\n        horizontalScrollbarThumb: GUIStyle\r\n        /** Style used by default for the left button on GUI.HorizontalScrollbar controls.\r\n         */\r\n        horizontalScrollbarLeftButton: GUIStyle\r\n        /** Style used by default for the right button on GUI.HorizontalScrollbar controls.\r\n         */\r\n        horizontalScrollbarRightButton: GUIStyle\r\n        /** Style used by default for the background part of GUI.VerticalScrollbar controls.\r\n         */\r\n        verticalScrollbar: GUIStyle\r\n        /** Style used by default for the thumb that is dragged in GUI.VerticalScrollbar controls.\r\n         */\r\n        verticalScrollbarThumb: GUIStyle\r\n        /** Style used by default for the up button on GUI.VerticalScrollbar controls.\r\n         */\r\n        verticalScrollbarUpButton: GUIStyle\r\n        /** Style used by default for the down button on GUI.VerticalScrollbar controls.\r\n         */\r\n        verticalScrollbarDownButton: GUIStyle\r\n        /** Style used by default for the background of ScrollView controls (see GUI.BeginScrollView).\r\n         */\r\n        scrollView: GUIStyle\r\n        /** Array of GUI styles for specific needs.\r\n         */\r\n        customStyles: Array<GUIStyle>\r\n        /** Generic settings for how controls should behave with this skin.\r\n         */\r\n        readonly settings: any\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object as Object1, Enum, Array } from \"System\";\r\n    /** Styling information for GUI elements.\r\n     */\r\n    class GUIStyle extends Object1 {\r\n        constructor(other: GUIStyle)\r\n        constructor()\r\n        /** Draw the GUIStyle with a text string inside.\r\n         */\r\n        Draw(position: Rect, text: string, isHover: boolean, isActive: boolean, on: boolean, hasKeyboardFocus: boolean): void\r\n        /** Draw the GUIStyle with an image inside. If the image is too large to fit within the content area of the style it is scaled down.\r\n         */\r\n        Draw(position: Rect, image: Texture, isHover: boolean, isActive: boolean, on: boolean, hasKeyboardFocus: boolean): void\r\n        /** Draw the GUIStyle with text and an image inside. If the image is too large to fit within the content area of the style it is scaled down.\r\n         */\r\n        Draw(position: Rect, content: GUIContent, isHover: boolean, isActive: boolean, on: boolean, hasKeyboardFocus: boolean): void\r\n        /** Draw this GUIStyle on to the screen, internal version.\r\n         */\r\n        Draw(position: Rect, isHover: boolean, isActive: boolean, on: boolean, hasKeyboardFocus: boolean): void\r\n        Draw(position: Rect, content: GUIContent, controlID: number, on: boolean, hover: boolean): void\r\n        /** Draw the GUIStyle with text and an image inside. If the image is too large to fit within the content area of the style it is scaled down.\r\n         */\r\n        Draw(position: Rect, content: GUIContent, controlID: number, on: boolean): void\r\n        /** Draw the GUIStyle with text and an image inside. If the image is too large to fit within the content area of the style it is scaled down.\r\n         */\r\n        Draw(position: Rect, content: GUIContent, controlID: number): void\r\n        /** Draw this GUIStyle with selected content.\r\n         */\r\n        DrawCursor(position: Rect, content: GUIContent, controlID: number, character: number): void\r\n        /** Draw this GUIStyle with selected content.\r\n         */\r\n        DrawWithTextSelection(position: Rect, content: GUIContent, controlID: number, firstSelectedCharacter: number, lastSelectedCharacter: number): void\r\n        /** Get the pixel position of a given string index.\r\n         */\r\n        GetCursorPixelPosition(position: Rect, content: GUIContent, cursorStringIndex: number): Vector2\r\n        /** Get the cursor position (indexing into contents.text) when the user clicked at cursorPixelPosition.\r\n         */\r\n        GetCursorStringIndex(position: Rect, content: GUIContent, cursorPixelPosition: Vector2): number\r\n        /** Calculate the size of some content if it is rendered with this style.\r\n         */\r\n        CalcSize(content: GUIContent): Vector2\r\n        /** Calculate the size of an element formatted with this style, and a given space to content.\r\n         */\r\n        CalcScreenSize(contentSize: Vector2): Vector2\r\n        /** How tall this element will be when rendered with content and a specific width.\r\n         */\r\n        CalcHeight(content: GUIContent, width: number): number\r\n        /** Calculate the minimum and maximum widths for this style rendered with content.\r\n         */\r\n        CalcMinMaxWidth(content: GUIContent, minWidth: jsb.Out<number>, maxWidth: jsb.Out<number>): void\r\n        toString(): string\r\n        static op_Implicit(str: string): GUIStyle\r\n        /** The font to use for rendering. If null, the default font for the current GUISkin is used instead.\r\n         */\r\n        font: any\r\n        /** How image and text of the GUIContent is combined.\r\n         */\r\n        imagePosition: any\r\n        /** Text alignment.\r\n         */\r\n        alignment: TextAnchor\r\n        /** Should the text be wordwrapped?\r\n         */\r\n        wordWrap: boolean\r\n        /** What to do when the contents to be rendered is too large to fit within the area given.\r\n         */\r\n        clipping: any\r\n        /** Pixel offset to apply to the content of this GUIstyle.\r\n         */\r\n        contentOffset: Vector2\r\n        /** If non-0, any GUI elements rendered with this style will have the width specified here.\r\n         */\r\n        fixedWidth: number\r\n        /** If non-0, any GUI elements rendered with this style will have the height specified here.\r\n         */\r\n        fixedHeight: number\r\n        /** Can GUI elements of this style be stretched horizontally for better layouting?\r\n         */\r\n        stretchWidth: boolean\r\n        /** Can GUI elements of this style be stretched vertically for better layout?\r\n         */\r\n        stretchHeight: boolean\r\n        /** The font size to use (for dynamic fonts).\r\n         */\r\n        fontSize: number\r\n        /** The font style to use (for dynamic fonts).\r\n         */\r\n        fontStyle: any\r\n        /** Enable HTML-style tags for Text Formatting Markup.\r\n         */\r\n        richText: boolean\r\n        /** The name of this GUIStyle. Used for getting them based on name.\r\n         */\r\n        name: string\r\n        /** Rendering settings for when the component is displayed normally.\r\n         */\r\n        normal: any\r\n        /** Rendering settings for when the mouse is hovering over the control.\r\n         */\r\n        hover: any\r\n        /** Rendering settings for when the control is pressed down.\r\n         */\r\n        active: any\r\n        /** Rendering settings for when the control is turned on.\r\n         */\r\n        onNormal: any\r\n        /** Rendering settings for when the control is turned on and the mouse is hovering it.\r\n         */\r\n        onHover: any\r\n        /** Rendering settings for when the element is turned on and pressed down.\r\n         */\r\n        onActive: any\r\n        /** Rendering settings for when the element has keyboard focus.\r\n         */\r\n        focused: any\r\n        /** Rendering settings for when the element has keyboard and is turned on.\r\n         */\r\n        onFocused: any\r\n        /** The borders of all background images.\r\n         */\r\n        border: any\r\n        /** The margins between elements rendered in this style and any other GUI elements.\r\n         */\r\n        margin: any\r\n        /** Space from the edge of GUIStyle to the start of the contents.\r\n         */\r\n        padding: any\r\n        /** Extra space to be added to the background image.\r\n         */\r\n        overflow: any\r\n        /** The height of one line of text with this style, measured in pixels. (Read Only)\r\n         */\r\n        readonly lineHeight: number\r\n        /** Shortcut for an empty GUIStyle.\r\n         */\r\n        static readonly none: GUIStyle\r\n        readonly isHeightDependantOnWidth: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Enum } from \"System\";\r\n    /** Where the anchor of the text is placed.\r\n     */\r\n    enum TextAnchor {\r\n        /** Text is anchored in upper left corner.\r\n         */\r\n        UpperLeft = 0,\r\n        /** Text is anchored in upper side, centered horizontally.\r\n         */\r\n        UpperCenter = 1,\r\n        /** Text is anchored in upper right corner.\r\n         */\r\n        UpperRight = 2,\r\n        /** Text is anchored in left side, centered vertically.\r\n         */\r\n        MiddleLeft = 3,\r\n        /** Text is centered both horizontally and vertically.\r\n         */\r\n        MiddleCenter = 4,\r\n        /** Text is anchored in right side, centered vertically.\r\n         */\r\n        MiddleRight = 5,\r\n        /** Text is anchored in lower left corner.\r\n         */\r\n        LowerLeft = 6,\r\n        /** Text is anchored in lower side, centered horizontally.\r\n         */\r\n        LowerCenter = 7,\r\n        /** Text is anchored in lower right corner.\r\n         */\r\n        LowerRight = 8,\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Enum } from \"System\";\r\n    /** Scaling mode to draw textures with.\r\n     */\r\n    enum ScaleMode {\r\n        /** Stretches the texture to fill the complete rectangle passed in to GUI.DrawTexture.\r\n         */\r\n        StretchToFill = 0,\r\n        /** Scales the texture, maintaining aspect ratio, so it completely covers the position rectangle passed to GUI.DrawTexture. If the texture is being draw to a rectangle with a different aspect ratio than the original, the image is cropped.\r\n         */\r\n        ScaleAndCrop = 1,\r\n        /** Scales the texture, maintaining aspect ratio, so it completely fits withing the position rectangle passed to GUI.DrawTexture.\r\n         */\r\n        ScaleToFit = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Enum } from \"System\";\r\n    /** Used by GUIUtility.GetControlID to inform the IMGUI system if a given control can get keyboard focus. This allows the IMGUI system to give focus appropriately when a user presses tab for cycling between controls.\r\n     */\r\n    enum FocusType {\r\n        Native = 0,\r\n        /** This control can receive keyboard focus.\r\n         */\r\n        Keyboard = 1,\r\n        /** This control can not receive keyboard focus.\r\n         */\r\n        Passive = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum, Array } from \"System\";\r\n    /** A container for audio data.\r\n     */\r\n    class AudioClip extends Object {\r\n        LoadAudioData(): boolean\r\n        UnloadAudioData(): boolean\r\n        /** Fills an array with sample data from the clip.\r\n         */\r\n        GetData(data: Array<number>, offsetSamples: number): boolean\r\n        /** Set sample data in a clip.\r\n         */\r\n        SetData(data: Array<number>, offsetSamples: number): boolean\r\n        static Create(name: string, lengthSamples: number, channels: number, frequency: number, stream: boolean, pcmreadercallback: (data: Array<number>) => void, pcmsetpositioncallback: (id: number) => void): AudioClip\r\n        static Create(name: string, lengthSamples: number, channels: number, frequency: number, stream: boolean, pcmreadercallback: (data: Array<number>) => void): AudioClip\r\n        /** Creates a user AudioClip with a name and with the given length in samples, channels and frequency.\r\n         * @param name Name of clip.\r\n         * @param lengthSamples Number of sample frames.\r\n         * @param channels Number of channels per frame.\r\n         * @param frequency Sample frequency of clip.\r\n         * @param _3D Audio clip is played back in 3D.\r\n         * @param stream True if clip is streamed, that is if the pcmreadercallback generates data on the fly.\r\n         * @param pcmreadercallback This callback is invoked to generate a block of sample data. Non-streamed clips call this only once at creation time while streamed clips call this continuously.\r\n         * @param pcmsetpositioncallback This callback is invoked whenever the clip loops or changes playback position.\r\n         * @returns A reference to the created AudioClip. \r\n         */\r\n        static Create(name: string, lengthSamples: number, channels: number, frequency: number, stream: boolean): AudioClip\r\n        protected constructor()\r\n        /** The length of the audio clip in seconds. (Read Only)\r\n         */\r\n        readonly length: number\r\n        /** The length of the audio clip in samples. (Read Only)\r\n         */\r\n        readonly samples: number\r\n        /** The number of channels in the audio clip. (Read Only)\r\n         */\r\n        readonly channels: number\r\n        /** The sample frequency of the clip in Hertz. (Read Only)\r\n         */\r\n        readonly frequency: number\r\n        /** The load type of the clip (read-only).\r\n         */\r\n        readonly loadType: any\r\n        /** Preloads audio data of the clip when the clip asset is loaded. When this flag is off, scripts have to call AudioClip.LoadAudioData() to load the data before the clip can be played. Properties like length, channels and format are available before the audio data has been loaded.\r\n         */\r\n        readonly preloadAudioData: boolean\r\n        /** Returns true if this audio clip is ambisonic (read-only).\r\n         */\r\n        readonly ambisonic: boolean\r\n        /** Corresponding to the \"Load In Background\" flag in the inspector, when this flag is set, the loading will happen delayed without blocking the main thread.\r\n         */\r\n        readonly loadInBackground: boolean\r\n        /** Returns the current load state of the audio data associated with an AudioClip.\r\n         */\r\n        readonly loadState: any\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { ValueType } from \"System\";\r\n    /** A 2D Rectangle defined by x, y, width, height with integers.\r\n     */\r\n    class RectInt extends ValueType {\r\n        constructor(xMin: number, yMin: number, width: number, height: number)\r\n        constructor(position: Vector2Int, size: Vector2Int)\r\n        /** Sets the bounds to the min and max value of the rect.\r\n         */\r\n        SetMinMax(minPosition: Vector2Int, maxPosition: Vector2Int): void\r\n        /** Clamps the position and size of the RectInt to the given bounds.\r\n         * @param bounds Bounds to clamp the RectInt.\r\n         */\r\n        ClampToBounds(bounds: RectInt): void\r\n        /** Returns true if the given position is within the RectInt.\r\n         * @param position Position to check.\r\n         * @returns Whether the position is within the RectInt. \r\n         */\r\n        Contains(position: Vector2Int): boolean\r\n        /** RectInts overlap if each RectInt Contains a shared point.\r\n         * @param other Other rectangle to test overlapping with.\r\n         * @returns True if the other rectangle overlaps this one. \r\n         */\r\n        Overlaps(other: RectInt): boolean\r\n        /** Returns the x, y, width and height of the RectInt.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string, formatProvider: any): string\r\n        /** Returns the x, y, width and height of the RectInt.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string): string\r\n        toString(): string\r\n        /** Returns true if the given RectInt is equal to this RectInt.\r\n         */\r\n        Equals(other: RectInt): boolean\r\n        /** Left coordinate of the rectangle.\r\n         */\r\n        x: number\r\n        /** Top coordinate of the rectangle.\r\n         */\r\n        y: number\r\n        /** Center coordinate of the rectangle.\r\n         */\r\n        readonly center: Vector2\r\n        /** The lower left corner of the rectangle; which is the minimal position of the rectangle along the x- and y-axes, when it is aligned to both axes.\r\n         */\r\n        min: Vector2Int\r\n        /** The upper right corner of the rectangle; which is the maximal position of the rectangle along the x- and y-axes, when it is aligned to both axes.\r\n         */\r\n        max: Vector2Int\r\n        /** Width of the rectangle.\r\n         */\r\n        width: number\r\n        /** Height of the rectangle.\r\n         */\r\n        height: number\r\n        /** Shows the minimum X value of the RectInt.\r\n         */\r\n        xMin: number\r\n        /** Show the minimum Y value of the RectInt.\r\n         */\r\n        yMin: number\r\n        /** Shows the maximum X value of the RectInt.\r\n         */\r\n        xMax: number\r\n        /** Shows the maximum Y value of the RectInt.\r\n         */\r\n        yMax: number\r\n        /** Returns the position (x, y) of the RectInt.\r\n         */\r\n        position: Vector2Int\r\n        /** Returns the width and height of the RectInt.\r\n         */\r\n        size: Vector2Int\r\n        /** A RectInt.PositionCollection that contains all positions within the RectInt.\r\n         */\r\n        readonly allPositionsWithin: any\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Object as Object1, Array } from \"System\";\r\n    /** Represents an axis aligned bounding box.\r\n     */\r\n    class Bounds extends ValueType {\r\n        constructor(center: Vector3, size: Vector3)\r\n        GetHashCode(): number\r\n        Equals(other: Object1): boolean\r\n        Equals(other: Bounds): boolean\r\n        /** Sets the bounds to the min and max value of the box.\r\n         */\r\n        SetMinMax(min: Vector3, max: Vector3): void\r\n        /** Grows the Bounds to include the point.\r\n         */\r\n        Encapsulate(point: Vector3): void\r\n        /** Grow the bounds to encapsulate the bounds.\r\n         */\r\n        Encapsulate(bounds: Bounds): void\r\n        /** Expand the bounds by increasing its size by amount along each side.\r\n         */\r\n        Expand(amount: number): void\r\n        /** Expand the bounds by increasing its size by amount along each side.\r\n         */\r\n        Expand(amount: Vector3): void\r\n        /** Does another bounding box intersect with this bounding box?\r\n         */\r\n        Intersects(bounds: Bounds): boolean\r\n        /** Does ray intersect this bounding box?\r\n         */\r\n        IntersectRay(ray: Ray, distance: jsb.Out<number>): boolean\r\n        /** Does ray intersect this bounding box?\r\n         */\r\n        IntersectRay(ray: Ray): boolean\r\n        /** Returns a formatted string for the bounds.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string, formatProvider: any): string\r\n        /** Returns a formatted string for the bounds.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string): string\r\n        toString(): string\r\n        /** Is point contained in the bounding box?\r\n         */\r\n        Contains(point: Vector3): boolean\r\n        /** The smallest squared distance between the point and this bounding box.\r\n         */\r\n        SqrDistance(point: Vector3): number\r\n        /** The closest point on the bounding box.\r\n         * @param point Arbitrary point.\r\n         * @returns The point on the bounding box or inside the bounding box. \r\n         */\r\n        ClosestPoint(point: Vector3): Vector3\r\n        static op_Equality(lhs: Bounds, rhs: Bounds): boolean\r\n        static op_Inequality(lhs: Bounds, rhs: Bounds): boolean\r\n        // js_op_overloading: static ==(lhs: Bounds, rhs: Bounds): boolean\r\n        /** The center of the bounding box.\r\n         */\r\n        center: Vector3\r\n        /** The total size of the box. This is always twice as large as the extents.\r\n         */\r\n        size: Vector3\r\n        /** The extents of the Bounding Box. This is always half of the size of the Bounds.\r\n         */\r\n        extents: Vector3\r\n        /** The minimal point of the box. This is always equal to center-extents.\r\n         */\r\n        min: Vector3\r\n        /** The maximal point of the box. This is always equal to center+extents.\r\n         */\r\n        max: Vector3\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { ValueType, Object as Object1 } from \"System\";\r\n    /** Represents an axis aligned bounding box with all values as integers.\r\n     */\r\n    class BoundsInt extends ValueType {\r\n        constructor(xMin: number, yMin: number, zMin: number, sizeX: number, sizeY: number, sizeZ: number)\r\n        constructor(position: Vector3Int, size: Vector3Int)\r\n        /** Sets the bounds to the min and max value of the box.\r\n         */\r\n        SetMinMax(minPosition: Vector3Int, maxPosition: Vector3Int): void\r\n        /** Clamps the position and size of this bounding box to the given bounds.\r\n         * @param bounds Bounds to clamp to.\r\n         */\r\n        ClampToBounds(bounds: BoundsInt): void\r\n        /** Is point contained in the bounding box?\r\n         * @param position Point to check.\r\n         * @param inclusive Whether the max limits are included in the check.\r\n         * @returns Is point contained in the bounding box? \r\n         */\r\n        Contains(position: Vector3Int): boolean\r\n        /** Returns a formatted string for the bounds.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string, formatProvider: any): string\r\n        /** Returns a formatted string for the bounds.\r\n         * @param format A numeric format string.\r\n         * @param formatProvider An object that specifies culture-specific formatting.\r\n         */\r\n        toString(format: string): string\r\n        toString(): string\r\n        Equals(other: Object1): boolean\r\n        Equals(other: BoundsInt): boolean\r\n        GetHashCode(): number\r\n        static op_Equality(lhs: BoundsInt, rhs: BoundsInt): boolean\r\n        static op_Inequality(lhs: BoundsInt, rhs: BoundsInt): boolean\r\n        // js_op_overloading: static ==(lhs: BoundsInt, rhs: BoundsInt): boolean\r\n        /** X value of the minimal point of the box.\r\n         */\r\n        x: number\r\n        /** Y value of the minimal point of the box.\r\n         */\r\n        y: number\r\n        /** Z value of the minimal point of the box.\r\n         */\r\n        z: number\r\n        /** The center of the bounding box.\r\n         */\r\n        readonly center: Vector3\r\n        /** The minimal point of the box.\r\n         */\r\n        min: Vector3Int\r\n        /** The maximal point of the box.\r\n         */\r\n        max: Vector3Int\r\n        /** The minimal x point of the box.\r\n         */\r\n        xMin: number\r\n        /** The minimal y point of the box.\r\n         */\r\n        yMin: number\r\n        /** The minimal z point of the box.\r\n         */\r\n        zMin: number\r\n        /** The maximal x point of the box.\r\n         */\r\n        xMax: number\r\n        /** The maximal y point of the box.\r\n         */\r\n        yMax: number\r\n        /** The maximal z point of the box.\r\n         */\r\n        zMax: number\r\n        /** The position of the bounding box.\r\n         */\r\n        position: Vector3Int\r\n        /** The total size of the box.\r\n         */\r\n        size: Vector3Int\r\n        /** A BoundsInt.PositionCollection that contains all positions within the BoundsInt.\r\n         */\r\n        readonly allPositionsWithin: any\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object as Object1, Array, ValueType, Enum } from \"System\";\r\n    /** Gradient used for animating colors.\r\n     */\r\n    class Gradient extends Object1 {\r\n        constructor()\r\n        /** Calculate color at a given time.\r\n         * @param time Time of the key (0 - 1).\r\n         */\r\n        Evaluate(time: number): Color\r\n        /** Setup Gradient with an array of color keys and alpha keys.\r\n         * @param colorKeys Color keys of the gradient (maximum 8 color keys).\r\n         * @param alphaKeys Alpha keys of the gradient (maximum 8 alpha keys).\r\n         */\r\n        SetKeys(colorKeys: Array<any>, alphaKeys: Array<any>): void\r\n        Equals(o: Object1): boolean\r\n        Equals(other: Gradient): boolean\r\n        GetHashCode(): number\r\n        /** All color keys defined in the gradient.\r\n         */\r\n        colorKeys: Array<any>\r\n        /** All alpha keys defined in the gradient.\r\n         */\r\n        alphaKeys: Array<any>\r\n        /** Control how the gradient is evaluated.\r\n         */\r\n        mode: any\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object as Object1, Array, ValueType } from \"System\";\r\n    /** Store a collection of Keyframes that can be evaluated over time.\r\n     */\r\n    class AnimationCurve extends Object1 {\r\n        constructor()\r\n        constructor(...keys: any[])\r\n        $GetValue(index: number): any\r\n        /** Evaluate the curve at time.\r\n         * @param time The time within the curve you want to evaluate (the horizontal axis in the curve graph).\r\n         * @returns The value of the curve, at the point in time specified. \r\n         */\r\n        Evaluate(time: number): number\r\n        /** Add a new key to the curve.\r\n         * @param time The time at which to add the key (horizontal axis in the curve graph).\r\n         * @param value The value for the key (vertical axis in the curve graph).\r\n         * @returns The index of the added key, or -1 if the key could not be added. \r\n         */\r\n        AddKey(time: number, value: number): number\r\n        /** Add a new key to the curve.\r\n         * @param key The key to add to the curve.\r\n         * @returns The index of the added key, or -1 if the key could not be added. \r\n         */\r\n        AddKey(key: any): number\r\n        /** Removes the keyframe at index and inserts key.\r\n         * @param index The index of the key to move.\r\n         * @param key The key (with its new time) to insert.\r\n         * @returns The index of the keyframe after moving it. \r\n         */\r\n        MoveKey(index: number, key: any): number\r\n        /** Removes a key.\r\n         * @param index The index of the key to remove.\r\n         */\r\n        RemoveKey(index: number): void\r\n        /** Smooth the in and out tangents of the keyframe at index.\r\n         * @param index The index of the keyframe to be smoothed.\r\n         * @param weight The smoothing weight to apply to the keyframe's tangents.\r\n         */\r\n        SmoothTangents(index: number, weight: number): void\r\n        Equals(o: Object1): boolean\r\n        Equals(other: AnimationCurve): boolean\r\n        GetHashCode(): number\r\n        /** Creates a constant \"curve\" starting at timeStart, ending at timeEnd and with the value value.\r\n         * @param timeStart The start time for the constant curve.\r\n         * @param timeEnd The start time for the constant curve.\r\n         * @param value The value for the constant curve.\r\n         * @returns The constant curve created from the specified values. \r\n         */\r\n        static Constant(timeStart: number, timeEnd: number, value: number): AnimationCurve\r\n        /** A straight Line starting at timeStart, valueStart and ending at timeEnd, valueEnd.\r\n         * @param timeStart The start time for the linear curve.\r\n         * @param valueStart The start value for the linear curve.\r\n         * @param timeEnd The end time for the linear curve.\r\n         * @param valueEnd The end value for the linear curve.\r\n         * @returns The linear curve created from the specified values. \r\n         */\r\n        static Linear(timeStart: number, valueStart: number, timeEnd: number, valueEnd: number): AnimationCurve\r\n        /** Creates an ease-in and out curve starting at timeStart, valueStart and ending at timeEnd, valueEnd.\r\n         * @param timeStart The start time for the ease curve.\r\n         * @param valueStart The start value for the ease curve.\r\n         * @param timeEnd The end time for the ease curve.\r\n         * @param valueEnd The end value for the ease curve.\r\n         * @returns The ease-in and out curve generated from the specified values. \r\n         */\r\n        static EaseInOut(timeStart: number, valueStart: number, timeEnd: number, valueEnd: number): AnimationCurve\r\n        /** All keys defined in the animation curve.\r\n         */\r\n        keys: Array<any>\r\n        /** The number of keys in the curve. (Read Only)\r\n         */\r\n        readonly length: number\r\n        /** The behaviour of the animation before the first keyframe.\r\n         */\r\n        preWrapMode: WrapMode\r\n        /** The behaviour of the animation after the last keyframe.\r\n         */\r\n        postWrapMode: WrapMode\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Object as Object1, Enum } from \"System\";\r\n    /** A UnityGUI event.\r\n     */\r\n    class Event extends Object1 {\r\n        constructor(displayIndex: number)\r\n        constructor(other: Event)\r\n        constructor()\r\n        /** Get a filtered event type for a given control ID.\r\n         * @param controlID The ID of the control you are querying from.\r\n         */\r\n        GetTypeForControl(controlID: number): EventType\r\n        GetHashCode(): number\r\n        Equals(obj: Object1): boolean\r\n        toString(): string\r\n        Use(): void\r\n        /** Get the next queued [Event] from the event system.\r\n         * @param outEvent Next Event.\r\n         */\r\n        static PopEvent(outEvent: Event): boolean\r\n        static GetEventCount(): number\r\n        /** Create a keyboard event.\r\n         */\r\n        static KeyboardEvent(key: string): Event\r\n        readonly rawType: EventType\r\n        /** The mouse position.\r\n         */\r\n        mousePosition: Vector2\r\n        /** The relative movement of the mouse compared to last event.\r\n         */\r\n        delta: Vector2\r\n        /** The type of pointer that created this event (for example, mouse, touch screen, pen).\r\n         */\r\n        pointerType: any\r\n        /** Which mouse button was pressed.\r\n         */\r\n        button: number\r\n        /** Which modifier keys are held down.\r\n         */\r\n        modifiers: any\r\n        /** How hard stylus pressure is applied.\r\n         */\r\n        pressure: number\r\n        /** How many consecutive mouse clicks have we received.\r\n         */\r\n        clickCount: number\r\n        /** The character typed.\r\n         */\r\n        character: string\r\n        /** The raw key code for keyboard events.\r\n         */\r\n        keyCode: KeyCode\r\n        /** Index of display that the event belongs to.\r\n         */\r\n        displayIndex: number\r\n        /** The type of event.\r\n         */\r\n        type: EventType\r\n        /** The name of an ExecuteCommand or ValidateCommand Event.\r\n         */\r\n        commandName: string\r\n        /** Is Shift held down? (Read Only)\r\n         */\r\n        shift: boolean\r\n        /** Is Control key held down? (Read Only)\r\n         */\r\n        control: boolean\r\n        /** Is Alt/Option key held down? (Read Only)\r\n         */\r\n        alt: boolean\r\n        /** Is Command/Windows key held down? (Read Only)\r\n         */\r\n        command: boolean\r\n        /** Is Caps Lock on? (Read Only)\r\n         */\r\n        capsLock: boolean\r\n        /** Is the current keypress on the numeric keyboard? (Read Only)\r\n         */\r\n        numeric: boolean\r\n        /** Is the current keypress a function key? (Read Only)\r\n         */\r\n        readonly functionKey: boolean\r\n        /** The current event that's being processed right now.\r\n         */\r\n        static current: Event\r\n        /** Is this event a keyboard event? (Read Only)\r\n         */\r\n        readonly isKey: boolean\r\n        /** Is this event a mouse event? (Read Only)\r\n         */\r\n        readonly isMouse: boolean\r\n        readonly isScrollWheel: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Enum } from \"System\";\r\n    /** Types of UnityGUI input and processing events.\r\n     */\r\n    enum EventType {\r\n        /** An event that is called when the mouse is clicked.\r\n         */\r\n        MouseDown = 0,\r\n        /** An event that is called when the mouse is no longer being clicked.\r\n         */\r\n        MouseUp = 1,\r\n        MouseMove = 2,\r\n        /** An event that is called when the mouse is clicked and dragged.\r\n         */\r\n        MouseDrag = 3,\r\n        /** A keyboard key was pressed.\r\n         */\r\n        KeyDown = 4,\r\n        KeyUp = 5,\r\n        ScrollWheel = 6,\r\n        Repaint = 7,\r\n        /** A layout event.\r\n         */\r\n        Layout = 8,\r\n        /** Editor only: drag & drop operation updated.\r\n         */\r\n        DragUpdated = 9,\r\n        DragPerform = 10,\r\n        /** Event should be ignored.\r\n         */\r\n        Ignore = 11,\r\n        /** Already processed event.\r\n         */\r\n        Used = 12,\r\n        /** Validates a special command (e.g. copy & paste).\r\n         */\r\n        ValidateCommand = 13,\r\n        /** Execute a special command (eg. copy & paste).\r\n         */\r\n        ExecuteCommand = 14,\r\n        /** Editor only: drag & drop operation exited.\r\n         */\r\n        DragExited = 15,\r\n        /** User has right-clicked (or control-clicked on the mac).\r\n         */\r\n        ContextClick = 16,\r\n        /** Mouse entered a window (Editor views only).\r\n         */\r\n        MouseEnterWindow = 20,\r\n        /** Mouse left a window (Editor views only).\r\n         */\r\n        MouseLeaveWindow = 21,\r\n        /** Direct manipulation device (finger, pen) touched the screen.\r\n         */\r\n        TouchDown = 30,\r\n        /** Direct manipulation device (finger, pen) left the screen.\r\n         */\r\n        TouchUp = 31,\r\n        /** Direct manipulation device (finger, pen) moved on the screen (drag).\r\n         */\r\n        TouchMove = 32,\r\n        /** Direct manipulation device (finger, pen) moving into the window (drag).\r\n         */\r\n        TouchEnter = 33,\r\n        /** Direct manipulation device (finger, pen) moved out of the window (drag).\r\n         */\r\n        TouchLeave = 34,\r\n        /** Direct manipulation device (finger, pen) stationary event (long touch down).\r\n         */\r\n        TouchStationary = 35,\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    /** MonoBehaviour.StartCoroutine returns a Coroutine. Instances of this class are only used to reference these coroutines, and do not hold any exposed properties or functions.\r\n     */\r\n    class Coroutine extends YieldInstruction {\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"System.Collections\" {\r\n    import { Object } from \"System\";\r\n    interface IEnumerator {\r\n        MoveNext(): boolean\r\n        Reset(): void\r\n        readonly Current: Object\r\n    }\r\n}\r\ndeclare module \"System.Collections.Generic\" {\r\n    interface IEnumerable_String extends IEnumerable<string> {\r\n        GetEnumerator(): any\r\n    }\r\n}\r\ndeclare module \"System.Collections.Generic\" {\r\n    interface IEnumerable<T> {\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Rect, GUIStyle, GUILayoutOption } from \"UnityEngine\";\r\n    /** The SearchField control creates a text field for a user to input text that can be used for searching.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SearchField extends Object {\r\n        constructor()\r\n        SetFocus(): void\r\n        HasFocus(): boolean\r\n        /** This function displays a search text field with the given Rect and UI style parameters.\r\n         * @param rect Rectangle to use for the search field.\r\n         * @param text Text string to display in the search field.\r\n         * @param style The text field style.\r\n         * @param cancelButtonStyle The cancel button style used when there is text in the search field.\r\n         * @param emptyCancelButtonStyle The cancel button style used when there is no text in the search field.\r\n         * @returns The text entered in the SearchField. The original input string is returned instead if the search field text was not changed. \r\n         */\r\n        OnGUI(rect: Rect, text: string, style: GUIStyle, cancelButtonStyle: GUIStyle, emptyCancelButtonStyle: GUIStyle): string\r\n        /** This function displays the search field with the default UI style in the given Rect.\r\n         * @param rect Rectangle to use for the search field.\r\n         * @param text Text string to display in the search field.\r\n         * @returns The text entered in the search field. The original input string is returned instead if the search field text was not changed. \r\n         */\r\n        OnGUI(rect: Rect, text: string): string\r\n        /** This function displays the search field with the default UI style and uses the GUILayout class to automatically calculate the position and size of the Rect it is rendered to. Pass an optional list to specify extra layout properties.\r\n         * @param text Text string to display in the search field.\r\n         * @param options An optional list of layout options that specify extra layout properties. <br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The text entered in the search field. The original input string is returned instead if the search field text was not changed. \r\n         */\r\n        OnGUI(text: string, ...options: GUILayoutOption[]): string\r\n        /** This function displays the search field with a toolbar style in the given Rect.\r\n         * @param rect Rectangle to use for the search field.\r\n         * @param text Text string to display in the search field.\r\n         * @returns The text entered in the search field. The original input string is returned instead if the search field text was not changed. \r\n         */\r\n        OnToolbarGUI(rect: Rect, text: string): string\r\n        /** This function displays the search field with the toolbar UI style and uses the GUILayout class to automatically calculate the position and size of the Rect it is rendered to. Pass an optional list to specify extra layout properties.\r\n         * @param text Text string to display in the search field.\r\n         * @param options An optional list of layout options that specify extra layout properties. <br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The text entered in the search field. The original input string is returned instead if the search field text was not changed. \r\n         */\r\n        OnToolbarGUI(text: string, ...options: GUILayoutOption[]): string\r\n        /** This is the controlID used for the text field to obtain keyboard focus.\r\n         */\r\n        searchFieldControlID: number\r\n        /** Changes the keyboard focus to the search field when the user presses ‘Ctrl/Cmd + F’ when set to true. It is true by default.\r\n         */\r\n        autoSetFocusOnFindCommand: boolean\r\n        downOrUpArrowKeyPressed(op: \"add\" | \"remove\", fn: () => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { GUIStyle, Object as Object1 } from \"UnityEngine\";\r\n    /** Common GUIStyles used for EditorGUI controls.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class EditorStyles extends Object {\r\n        constructor()\r\n        static FromUSS(baseStyle: GUIStyle, ussStyleRuleName: string, ussInPlaceStyleOverride: string): GUIStyle\r\n        static FromUSS(ussStyleRuleName: string, ussInPlaceStyleOverride: string): GUIStyle\r\n        static ApplyUSS(style: GUIStyle, ussStyleRuleName: string, ussInPlaceStyleOverride: string): GUIStyle\r\n        /** Style used for the labelled on all EditorGUI overloads that take a prefix label.\r\n         */\r\n        static readonly label: GUIStyle\r\n        /** Style for label with small font.\r\n         */\r\n        static readonly miniLabel: GUIStyle\r\n        /** Style for label with large font.\r\n         */\r\n        static readonly largeLabel: GUIStyle\r\n        /** Style for bold label.\r\n         */\r\n        static readonly boldLabel: GUIStyle\r\n        /** Style for mini bold label.\r\n         */\r\n        static readonly miniBoldLabel: GUIStyle\r\n        /** Style for label with small font which is centered and grey.\r\n         */\r\n        static readonly centeredGreyMiniLabel: GUIStyle\r\n        /** Style for word wrapped mini label.\r\n         */\r\n        static readonly wordWrappedMiniLabel: GUIStyle\r\n        /** Style for word wrapped label.\r\n         */\r\n        static readonly wordWrappedLabel: GUIStyle\r\n        /** Style used for links.\r\n         */\r\n        static readonly linkLabel: GUIStyle\r\n        /** Style for white label.\r\n         */\r\n        static readonly whiteLabel: GUIStyle\r\n        /** Style for white mini label.\r\n         */\r\n        static readonly whiteMiniLabel: GUIStyle\r\n        /** Style for white large label.\r\n         */\r\n        static readonly whiteLargeLabel: GUIStyle\r\n        /** Style for white bold label.\r\n         */\r\n        static readonly whiteBoldLabel: GUIStyle\r\n        /** Style used for a radio button.\r\n         */\r\n        static readonly radioButton: GUIStyle\r\n        /** Style used for a standalone small button.\r\n         */\r\n        static readonly miniButton: GUIStyle\r\n        /** Style used for the leftmost button in a horizontal button group.\r\n         */\r\n        static readonly miniButtonLeft: GUIStyle\r\n        /** Style used for the middle buttons in a horizontal group.\r\n         */\r\n        static readonly miniButtonMid: GUIStyle\r\n        /** Style used for the rightmost button in a horizontal group.\r\n         */\r\n        static readonly miniButtonRight: GUIStyle\r\n        /** Style used for the drop-down controls.\r\n         */\r\n        static readonly miniPullDown: GUIStyle\r\n        /** Style used for EditorGUI.TextField.\r\n         */\r\n        static readonly textField: GUIStyle\r\n        /** Style used for EditorGUI.TextArea.\r\n         */\r\n        static readonly textArea: GUIStyle\r\n        /** Smaller text field.\r\n         */\r\n        static readonly miniTextField: GUIStyle\r\n        /** Style used for field editors for numbers.\r\n         */\r\n        static readonly numberField: GUIStyle\r\n        /** Style used for EditorGUI.Popup, EditorGUI.EnumPopup,.\r\n         */\r\n        static readonly popup: GUIStyle\r\n        /** Style used for headings for object fields.\r\n         */\r\n        static readonly objectField: GUIStyle\r\n        /** Style used for headings for the Select button in object fields.\r\n         */\r\n        static readonly objectFieldThumb: GUIStyle\r\n        /** Style used for object fields that have a thumbnail (e.g Textures). \r\n         */\r\n        static readonly objectFieldMiniThumb: GUIStyle\r\n        /** Style used for headings for Color fields.\r\n         */\r\n        static readonly colorField: GUIStyle\r\n        /** Style used for headings for Layer masks.\r\n         */\r\n        static readonly layerMaskField: GUIStyle\r\n        /** Style used for headings for EditorGUI.Toggle.\r\n         */\r\n        static readonly toggle: GUIStyle\r\n        /** Style used for headings for EditorGUI.Foldout.\r\n         */\r\n        static readonly foldout: GUIStyle\r\n        /** Style used for headings for EditorGUI.Foldout.\r\n         */\r\n        static readonly foldoutPreDrop: GUIStyle\r\n        /** Style used for headings for EditorGUILayout.BeginFoldoutHeaderGroup.\r\n         */\r\n        static readonly foldoutHeader: GUIStyle\r\n        /** Style used for icon for EditorGUILayout.BeginFoldoutHeaderGroup.\r\n         */\r\n        static readonly foldoutHeaderIcon: GUIStyle\r\n        /** Style used for headings for EditorGUILayout.BeginToggleGroup.\r\n         */\r\n        static readonly toggleGroup: GUIStyle\r\n        /** Standard font.\r\n         */\r\n        static readonly standardFont: any\r\n        /** Bold font.\r\n         */\r\n        static readonly boldFont: any\r\n        /** Mini font.\r\n         */\r\n        static readonly miniFont: any\r\n        /** Mini Bold font.\r\n         */\r\n        static readonly miniBoldFont: any\r\n        /** Toolbar background from top of windows.\r\n         */\r\n        static readonly toolbar: GUIStyle\r\n        /** Style for Button and Toggles in toolbars.\r\n         */\r\n        static readonly toolbarButton: GUIStyle\r\n        /** Toolbar Popup.\r\n         */\r\n        static readonly toolbarPopup: GUIStyle\r\n        /** Toolbar Dropdown.\r\n         */\r\n        static readonly toolbarDropDown: GUIStyle\r\n        /** Toolbar text field.\r\n         */\r\n        static readonly toolbarTextField: GUIStyle\r\n        /** Wrap content in a vertical group with this style to get the default margins used in the Inspector.\r\n         */\r\n        static readonly inspectorDefaultMargins: GUIStyle\r\n        /** Wrap content in a vertical group with this style to get full width margins in the Inspector.\r\n         */\r\n        static readonly inspectorFullWidthMargins: GUIStyle\r\n        /** Style used for background box for EditorGUI.HelpBox.\r\n         */\r\n        static readonly helpBox: GUIStyle\r\n        /** Toolbar search field.\r\n         */\r\n        static readonly toolbarSearchField: GUIStyle\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { GUIContent, Rect } from \"UnityEngine\";\r\n    /** GenericMenu lets you create custom context menus and dropdown menus.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class GenericMenu extends Object {\r\n        constructor()\r\n        AddItem(content: GUIContent, on: boolean, func: (userData: Object) => void, userData: Object): void\r\n        AddItem(content: GUIContent, on: boolean, func: () => void): void\r\n        /** Add a disabled item to the menu.\r\n         * @param content The GUIContent to display as a disabled menu item.\r\n         * @param on Specifies whether to show that the item is currently activated (i.e. a tick next to the item in the menu).\r\n         */\r\n        AddDisabledItem(content: GUIContent, on: boolean): void\r\n        /** Add a disabled item to the menu.\r\n         * @param content The GUIContent to display as a disabled menu item.\r\n         */\r\n        AddDisabledItem(content: GUIContent): void\r\n        /** Add a seperator item to the menu.\r\n         * @param path The path to the submenu, if adding a separator to a submenu. When adding a separator to the top level of a menu, use an empty string as the path.\r\n         */\r\n        AddSeparator(path: string): void\r\n        GetItemCount(): number\r\n        ShowAsContext(): void\r\n        /** Show the menu at the given screen rect.\r\n         * @param position The position at which to show the menu.\r\n         */\r\n        DropDown(position: Rect): void\r\n        /** Allow the menu to have multiple items with the same name.\r\n         */\r\n        allowDuplicateNames: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Enum indicating the type of Prefab Asset, such as Regular, Model and Variant.\r\n     */\r\n    enum PrefabAssetType {\r\n        /** The object being queried is not part of a Prefab at all.\r\n         */\r\n        NotAPrefab = 0,\r\n        /** The object being queried is part of a regular Prefab.\r\n         */\r\n        Regular = 1,\r\n        /** The object being queried is part of a Model Prefab.\r\n         */\r\n        Model = 2,\r\n        /** The object being queried is part of a Prefab Variant.\r\n         */\r\n        Variant = 3,\r\n        /** The object being queried is part of a Prefab instance, but because the asset is missing the actual type of Prefab can’t be determined.\r\n         */\r\n        MissingAsset = 4,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Enum with status about whether a Prefab instance is properly connected to its asset.\r\n     */\r\n    enum PrefabInstanceStatus {\r\n        /** The object is not part of a Prefab instance.\r\n         */\r\n        NotAPrefab = 0,\r\n        /** The Prefab instance is connected to its Prefab Asset.\r\n         */\r\n        Connected = 1,\r\n        /** The Prefab instance is not connected to its Prefab Asset.\r\n         */\r\n        Disconnected = 2,\r\n        /** The Prefab instance is missing its Prefab Asset.\r\n         */\r\n        MissingAsset = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Default mobile device orientation.\r\n     */\r\n    enum UIOrientation {\r\n        /** Portrait.\r\n         */\r\n        Portrait = 0,\r\n        /** Portrait upside down.\r\n         */\r\n        PortraitUpsideDown = 1,\r\n        /** Landscape: clockwise from Portrait.\r\n         */\r\n        LandscapeRight = 2,\r\n        /** Landscape : counter-clockwise from Portrait.\r\n         */\r\n        LandscapeLeft = 3,\r\n        /** Auto Rotation Enabled.\r\n         */\r\n        AutoRotation = 4,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** User message types.\r\n     */\r\n    enum MessageType {\r\n        /** Neutral message.\r\n         */\r\n        None = 0,\r\n        /** Info message.\r\n         */\r\n        Info = 1,\r\n        /** Warning message.\r\n         */\r\n        Warning = 2,\r\n        /** Error message.\r\n         */\r\n        Error = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Object as Object1 } from \"System\";\r\n    /** Represents  a 128-bit hash value.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class Hash128 extends ValueType {\r\n        constructor(u32_0: number, u32_1: number, u32_2: number, u32_3: number)\r\n        constructor(u64_0: number, u64_1: number)\r\n        CompareTo(rhs: Hash128): number\r\n        CompareTo(obj: Object1): number\r\n        toString(): string\r\n        /** Hash new input string and combine with the current hash value.\r\n         * @param data Input data string. Note that Unity interprets the string as UTF-8 data, even if internally in C# strings are UTF-16.\r\n         */\r\n        Append(data: string): void\r\n        /** Hash new input data and combine with the current hash value.\r\n         * @param val Input value.\r\n         */\r\n        Append(val: number): void\r\n        /** Hash new input data and combine with the current hash value.\r\n         * @param val Input value.\r\n         */\r\n        Append(val: number): void\r\n        Equals(obj: Object1): boolean\r\n        Equals(obj: Hash128): boolean\r\n        GetHashCode(): number\r\n        /** Convert a hex-encoded string into Hash128 value.\r\n         * @param hashString A hexadecimal-encoded hash string.\r\n         * @returns The 128-bit hash. \r\n         */\r\n        static Parse(hashString: string): Hash128\r\n        /** Compute a hash of input data string.\r\n         * @param data Input data string. Note that Unity interprets the string as UTF-8 data, even if internally in C# strings are UTF-16.\r\n         * @returns The 128-bit hash. \r\n         */\r\n        static Compute(data: string): Hash128\r\n        /** Compute a hash of input data.\r\n         * @param val Input value.\r\n         * @returns The 128-bit hash. \r\n         */\r\n        static Compute(val: number): Hash128\r\n        /** Compute a hash of input data.\r\n         * @param val Input value.\r\n         * @returns The 128-bit hash. \r\n         */\r\n        static Compute(val: number): Hash128\r\n        static op_Equality(hash1: Hash128, hash2: Hash128): boolean\r\n        static op_Inequality(hash1: Hash128, hash2: Hash128): boolean\r\n        static op_LessThan(x: Hash128, y: Hash128): boolean\r\n        static op_GreaterThan(x: Hash128, y: Hash128): boolean\r\n        // js_op_overloading: static ==(hash1: Hash128, hash2: Hash128): boolean\r\n        // js_op_overloading: static <(x: Hash128, y: Hash128): boolean\r\n        /** Returns true is the hash value is valid. (Read Only)\r\n         */\r\n        readonly isValid: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Asset importing options.\r\n     */\r\n    enum ImportAssetOptions {\r\n        /** Default import options.\r\n         */\r\n        Default = 0,\r\n        /** User initiated asset import.\r\n         */\r\n        ForceUpdate = 1,\r\n        /** Import all assets synchronously.\r\n         */\r\n        ForceSynchronousImport = 8,\r\n        /** When a folder is imported, import all its contents as well.\r\n         */\r\n        ImportRecursive = 256,\r\n        /** Force a full reimport but don't download the assets from the cache server.\r\n         */\r\n        DontDownloadFromCacheServer = 8192,\r\n        /** Forces asset import as uncompressed for edition facilities.\r\n         */\r\n        ForceUncompressedImport = 16384,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Object as Object1 } from \"UnityEngine\";\r\n    /** AssetPostprocessor lets you hook into the import pipeline and run scripts prior or after importing assets.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AssetPostprocessor extends Object {\r\n        /** Logs an import warning to the console.\r\n         */\r\n        LogWarning(warning: string, context: Object1): void\r\n        /** Logs an import warning to the console.\r\n         */\r\n        LogWarning(warning: string): void\r\n        /** Logs an import error message to the console.\r\n         */\r\n        LogError(warning: string, context: Object1): void\r\n        /** Logs an import error message to the console.\r\n         */\r\n        LogError(warning: string): void\r\n        GetVersion(): number\r\n        GetPostprocessOrder(): number\r\n        protected constructor()\r\n        /** The path name of the asset being imported.\r\n         */\r\n        assetPath: string\r\n        /** The import context.\r\n         */\r\n        readonly context: any\r\n        /** Reference to the asset importer.\r\n         */\r\n        readonly assetImporter: AssetImporter\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    import { Object as Object1 } from \"System\";\r\n    /** Base class from which asset importers for specific asset types derive.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AssetImporter extends Object {\r\n        constructor()\r\n        /** Set the AssetBundle name and variant.\r\n         * @param assetBundleName AssetBundle name.\r\n         * @param assetBundleVariant AssetBundle variant.\r\n         */\r\n        SetAssetBundleNameAndVariant(assetBundleName: string, assetBundleVariant: string): void\r\n        SaveAndReimport(): void\r\n        AddRemap(identifier: AssetImporter.SourceAssetIdentifier, externalObject: Object): void\r\n        RemoveRemap(identifier: AssetImporter.SourceAssetIdentifier): boolean\r\n        GetExternalObjectMap(): any\r\n        /** Checks if the AssetImporter supports remapping the given asset type.\r\n         * @param type The type of asset to check.\r\n         * @returns Returns true if the importer supports remapping the given type. Otherwise, returns false. \r\n         */\r\n        SupportsRemappedAssetType(type: any): boolean\r\n        /** Retrieves the asset importer for the asset at path.\r\n         */\r\n        static GetAtPath(path: string): AssetImporter\r\n        /** The path name of the asset for this importer. (Read Only)\r\n         */\r\n        readonly assetPath: string\r\n        /** The value is true when no meta file is provided with the imported asset.\r\n         */\r\n        readonly importSettingsMissing: boolean\r\n        readonly assetTimeStamp: number\r\n        /** Get or set any user data.\r\n         */\r\n        userData: string\r\n        /** Get or set the AssetBundle name.\r\n         */\r\n        assetBundleName: string\r\n        /** Get or set the AssetBundle variant.\r\n         */\r\n        assetBundleVariant: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Array, ValueType } from \"System\";\r\n    import { WrapMode, Object } from \"UnityEngine\";\r\n    /** Model importer lets you modify import settings from editor scripts.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ModelImporter extends AssetImporter {\r\n        constructor()\r\n        /** Creates a mask that matches the model hierarchy, and applies it to the provided ModelImporterClipAnimation.\r\n         * @param clip Clip to which the mask will be applied.\r\n         */\r\n        CreateDefaultMaskForClip(clip: ModelImporterClipAnimation): void\r\n        /** Extracts the embedded textures from a model file (such as FBX or SketchUp).\r\n         * @param folderPath The directory where the textures will be extracted.\r\n         * @returns Returns true if the textures are extracted successfully, otherwise false. \r\n         */\r\n        ExtractTextures(folderPath: string): boolean\r\n        /** Search the project for matching materials and use them instead of the internal materials.\r\n         * @param nameOption The name matching option.\r\n         * @param searchOption The search type option.\r\n         * @returns Returns true if the materials have been successfly remapped, otherwise false. \r\n         */\r\n        SearchAndRemapMaterials(nameOption: ModelImporterMaterialName, searchOption: ModelImporterMaterialSearch): boolean\r\n        /** Material naming setting.\r\n         */\r\n        materialName: ModelImporterMaterialName\r\n        /** Existing material search setting.\r\n         */\r\n        materialSearch: ModelImporterMaterialSearch\r\n        /** Material import location options.\r\n         */\r\n        materialLocation: ModelImporterMaterialLocation\r\n        /** Global scale factor for importing.\r\n         */\r\n        globalScale: number\r\n        /** Is useFileUnits supported for this asset.\r\n         */\r\n        readonly isUseFileUnitsSupported: boolean\r\n        /** Use visibility properties to enable or disable MeshRenderer components.\r\n         */\r\n        importVisibility: boolean\r\n        /** Detect file units and import as 1FileUnit=1UnityUnit, otherwise it will import as 1cm=1UnityUnit.\r\n         */\r\n        useFileUnits: boolean\r\n        /** Scaling factor used when useFileScale is set to true (Read-only).\r\n         */\r\n        readonly fileScale: number\r\n        /** Use FileScale when importing.\r\n         */\r\n        useFileScale: boolean\r\n        /** Controls import of BlendShapes.\r\n         */\r\n        importBlendShapes: boolean\r\n        /** Controls import of cameras. Basic properties like field of view, near plane distance and far plane distance can be animated.\r\n         */\r\n        importCameras: boolean\r\n        /** Controls import of lights. Note that because light are defined differently in DCC tools, some light types or properties may not be exported. Basic properties like color and intensity can be animated.\r\n         */\r\n        importLights: boolean\r\n        /** Add to imported meshes.\r\n         */\r\n        addCollider: boolean\r\n        /** Smoothing angle (in degrees) for calculating normals.\r\n         */\r\n        normalSmoothingAngle: number\r\n        /** Swap primary and secondary UV channels when importing.\r\n         */\r\n        swapUVChannels: boolean\r\n        /** Combine vertices that share the same position in space.\r\n         */\r\n        weldVertices: boolean\r\n        /** Computes the axis conversion on geometry and animation for Models defined in an axis system that differs from Unity's (left handed, Z forward, Y-up).\n\n                    When enabled, Unity transforms the geometry and animation data in order to convert the axis.\n\n                    When disabled, Unity transforms the root GameObject of the hierarchy in order to convert the axis.\r\n         */\r\n        bakeAxisConversion: boolean\r\n        /** If this is true, any quad faces that exist in the mesh data before it is imported are kept as quads instead of being split into two triangles, for the purposes of tessellation. Set this to false to disable this behavior.\r\n         */\r\n        keepQuads: boolean\r\n        /** Format of the imported mesh index buffer data.\r\n         */\r\n        indexFormat: ModelImporterIndexFormat\r\n        /** If true, always create an explicit Prefab root. Otherwise, if the model has a single root, it is reused as the Prefab root.\r\n         */\r\n        preserveHierarchy: boolean\r\n        /** Generate secondary UV set for lightmapping.\r\n         */\r\n        generateSecondaryUV: boolean\r\n        /** Threshold for angle distortion (in degrees) when generating secondary UV.\r\n         */\r\n        secondaryUVAngleDistortion: number\r\n        /** Threshold for area distortion when generating secondary UV.\r\n         */\r\n        secondaryUVAreaDistortion: number\r\n        /** Hard angle (in degrees) for generating secondary UV.\r\n         */\r\n        secondaryUVHardAngle: number\r\n        /** Method to use for handling margins when generating secondary UV.\r\n         */\r\n        secondaryUVMarginMethod: ModelImporterSecondaryUVMarginMethod\r\n        /** Margin to be left between charts when packing secondary UV.\r\n         */\r\n        secondaryUVPackMargin: number\r\n        /** The minimum lightmap resolution in texels per unit that the associated model is expected to have.\r\n         */\r\n        secondaryUVMinLightmapResolution: number\r\n        /** The minimum object scale that the associated model is expected to have.\r\n         */\r\n        secondaryUVMinObjectScale: number\r\n        /** Animation generation options.\r\n         */\r\n        generateAnimations: ModelImporterGenerateAnimations\r\n        /** Generates the list of all imported take.\r\n         */\r\n        readonly importedTakeInfos: Array<any>\r\n        /** Generates the list of all imported Transforms.\r\n         */\r\n        readonly transformPaths: Array<string>\r\n        /** Generates the list of all imported Animations.\r\n         */\r\n        readonly referencedClips: Array<string>\r\n        /** Are mesh vertices and indices accessible from script?\r\n         */\r\n        isReadable: boolean\r\n        /** Options to control the optimization of mesh data during asset import.\r\n         */\r\n        meshOptimizationFlags: MeshOptimizationFlags\r\n        /** Optimize the order of polygons in the mesh to make better use of the GPUs internal caches to improve rendering performance.\r\n         */\r\n        optimizeMeshPolygons: boolean\r\n        /** Optimize the order of vertices in the mesh to make better use of the GPUs internal caches to improve rendering performance.\r\n         */\r\n        optimizeMeshVertices: boolean\r\n        /** Skin weights import options.\r\n         */\r\n        skinWeights: ModelImporterSkinWeights\r\n        /** The maximum number of bones per vertex stored in this mesh data.\r\n         */\r\n        maxBonesPerVertex: number\r\n        /** Minimum bone weight to keep.\r\n         */\r\n        minBoneWeight: number\r\n        /** Vertex normal import options.\r\n         */\r\n        importNormals: ModelImporterNormals\r\n        /** Source of smoothing information for calculation of normals.\r\n         */\r\n        normalSmoothingSource: ModelImporterNormalSmoothingSource\r\n        /** Blend shape normal import options.\r\n         */\r\n        importBlendShapeNormals: ModelImporterNormals\r\n        /** Normal generation options for ModelImporter.\r\n         */\r\n        normalCalculationMode: ModelImporterNormalCalculationMode\r\n        /** Vertex tangent import options.\r\n         */\r\n        importTangents: ModelImporterTangents\r\n        /** Bake Inverse Kinematics (IK) when importing.\r\n         */\r\n        bakeIK: boolean\r\n        /** Is Bake Inverse Kinematics (IK) supported by this importer.\r\n         */\r\n        readonly isBakeIKSupported: boolean\r\n        /** If set to false, the importer will not resample curves when possible.\nRead more about.\n\nNotes:\n\n- Some unsupported FBX features (such as PreRotation or PostRotation on transforms) will override this setting. In these situations, animation curves will still be resampled even if the setting is disabled. For best results, avoid using PreRotation, PostRotation and GetRotationPivot.\n\n- This option was introduced in Version 5.3. Prior to this version, Unity's import behaviour was as if this option was always enabled. Therefore enabling the option gives the same behaviour as pre-5.3 animation import.\n\r\n         */\r\n        resampleCurves: boolean\r\n        /** Is import of tangents supported by this importer.\r\n         */\r\n        readonly isTangentImportSupported: boolean\r\n        /** Mesh compression setting.\r\n         */\r\n        meshCompression: ModelImporterMeshCompression\r\n        /** Import animation from file.\r\n         */\r\n        importAnimation: boolean\r\n        /** Animation optimization setting.\r\n         */\r\n        optimizeGameObjects: boolean\r\n        /** Animation optimization setting.\r\n         */\r\n        extraExposedTransformPaths: Array<string>\r\n        /** Additional properties to treat as user properties.\r\n         */\r\n        extraUserProperties: Array<string>\r\n        /** Animation compression setting.\r\n         */\r\n        animationCompression: ModelImporterAnimationCompression\r\n        /** Import animated custom properties from file.\r\n         */\r\n        importAnimatedCustomProperties: boolean\r\n        /** Import animation constraints.\r\n         */\r\n        importConstraints: boolean\r\n        /** Allowed error of animation rotation compression.\r\n         */\r\n        animationRotationError: number\r\n        /** Allowed error of animation position compression.\r\n         */\r\n        animationPositionError: number\r\n        /** Allowed error of animation scale compression.\r\n         */\r\n        animationScaleError: number\r\n        /** The default wrap mode for the generated animation clips.\r\n         */\r\n        animationWrapMode: WrapMode\r\n        /** Animator generation mode.\r\n         */\r\n        animationType: ModelImporterAnimationType\r\n        /** Controls how much oversampling is used when importing humanoid animations for retargeting.\r\n         */\r\n        humanoidOversampling: ModelImporterHumanoidOversampling\r\n        /** The path of the transform used to generation the motion of the animation.\r\n         */\r\n        motionNodeName: string\r\n        /** The Avatar generation of the imported model.\r\n         */\r\n        avatarSetup: ModelImporterAvatarSetup\r\n        /** Imports the HumanDescription from the given Avatar.\r\n         */\r\n        sourceAvatar: any\r\n        /** The human description that is used to generate an Avatar during the import process.\r\n         */\r\n        humanDescription: any\r\n        /** Animation clips to split animation into. See Also: ModelImporterClipAnimation.\r\n         */\r\n        clipAnimations: Array<ModelImporterClipAnimation>\r\n        /** Generate a list of all default animation clip based on TakeInfo.\r\n         */\r\n        readonly defaultClipAnimations: Array<ModelImporterClipAnimation>\r\n        /** When disabled, imported material albedo colors are converted to gamma space. This property should be disabled when using linear color space in Player rendering settings.\nThe default value is true.\r\n         */\r\n        useSRGBMaterialColor: boolean\r\n        /** Sorts the gameObject hierarchy by name.\r\n         */\r\n        sortHierarchyByName: boolean\r\n        /** Material creation options.\r\n         */\r\n        materialImportMode: ModelImporterMaterialImportMode\r\n        /** Generate auto mapping if no avatarSetup is provided when importing humanoid animation.\r\n         */\r\n        autoGenerateAvatarMappingIfUnspecified: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    /** Audio importer lets you modify AudioClip import settings from editor scripts.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AudioImporter extends AssetImporter {\r\n        constructor()\r\n        /** Returns whether a given build target has its sample settings currently overridden.\r\n         * @param platform The platform to query if this AudioImporter has an override for.\r\n         * @returns Returns true if the platform is currently overriden in this AudioImporter. \r\n         */\r\n        ContainsSampleSettingsOverride(platform: string): boolean\r\n        /** Return the current override settings for the given platform.\r\n         * @param platform The platform to get the override settings for.\r\n         * @returns The override sample settings for the given platform. \r\n         */\r\n        GetOverrideSampleSettings(platform: string): AudioImporterSampleSettings\r\n        /** Sets the override sample settings for the given platform.\r\n         * @param platform The platform which will have the sample settings overridden.\r\n         * @param settings The override settings for the given platform.\r\n         * @returns Returns true if the settings were successfully overriden. Some setting overrides are not possible for the given platform, in which case false is returned and the settings are not registered. \r\n         */\r\n        SetOverrideSampleSettings(platform: string, settings: AudioImporterSampleSettings): boolean\r\n        /** Clears the sample settings override for the given platform.\r\n         * @param platform The platform to clear the overrides for.\r\n         * @returns Returns true if any overrides were actually cleared. \r\n         */\r\n        ClearSampleSettingOverride(platform: string): boolean\r\n        /** The default sample settings for the AudioClip importer.\r\n         */\r\n        defaultSampleSettings: AudioImporterSampleSettings\r\n        /** Force audioclips to mono?\r\n         */\r\n        forceToMono: boolean\r\n        /** When this flag is set, the audio clip will be treated as being ambisonic.\r\n         */\r\n        ambisonic: boolean\r\n        /** Corresponding to the \"Load In Background\" flag in the AudioClip inspector, when this flag is set, the loading of the clip will happen delayed without blocking the main thread.\r\n         */\r\n        loadInBackground: boolean\r\n        /** Preloads audio data of the clip when the clip asset is loaded. When this flag is off, scripts have to call AudioClip.LoadAudioData() to load the data before the clip can be played. Properties like length, channels and format are available before the audio data has been loaded.\r\n         */\r\n        preloadAudioData: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Texture } from \"UnityEngine\";\r\n    /** VideoClipImporter lets you modify Video.VideoClip import settings from Editor scripts.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class VideoClipImporter extends AssetImporter {\r\n        constructor()\r\n        /** Returns the platform-specific import settings for the specified platform.\r\n         * @param platform Platform name.\r\n         * @returns The platform-specific import settings. Throws an exception if the platform is unknown. \r\n         */\r\n        GetTargetSettings(platform: string): VideoImporterTargetSettings\r\n        /** Sets the platform-specific import settings for the specified platform.\r\n         * @param platform Platform name.\r\n         * @param settings The new platform-specific import settings. Throws an exception if the platform is unknown.\r\n         */\r\n        SetTargetSettings(platform: string, settings: VideoImporterTargetSettings): void\r\n        /** Clear the platform-specific import settings for the specified platform, causing them to go back to the default settings.\r\n         * @param platform Platform name.\r\n         */\r\n        ClearTargetSettings(platform: string): void\r\n        PlayPreview(): void\r\n        StopPreview(): void\r\n        GetPreviewTexture(): Texture\r\n        /** Get the full name of the resize operation for the specified resize mode.\r\n         * @param mode Mode for which the width is queried.\r\n         * @returns Name for the specified resize mode. \r\n         */\r\n        GetResizeModeName(mode: VideoResizeMode): string\r\n        /** Get the resulting width of the resize operation for the specified resize mode.\r\n         * @param mode Mode for which the width is queried.\r\n         * @returns Width for the specified resize mode. \r\n         */\r\n        GetResizeWidth(mode: VideoResizeMode): number\r\n        /** Get the resulting height of the resize operation for the specified resize mode.\r\n         * @param mode Mode for which the height is queried.\r\n         * @returns Height for the specified resize mode. \r\n         */\r\n        GetResizeHeight(mode: VideoResizeMode): number\r\n        /** Number of audio channels in the specified source track.\r\n         * @param audioTrackIdx Index of the audio track to query.\r\n         * @returns Number of channels. \r\n         */\r\n        GetSourceAudioChannelCount(audioTrackIdx: number): number\r\n        /** Sample rate of the specified audio track.\r\n         * @param audioTrackIdx Index of the audio track to query.\r\n         * @returns Sample rate in Hertz. \r\n         */\r\n        GetSourceAudioSampleRate(audioTrackIdx: number): number\r\n        /** Performs a value comparison with another VideoClipImporter.\r\n         * @param rhs The importer to compare with.\r\n         * @returns Returns true if the settings for both VideoClipImporters match. Returns false otherwise. \r\n         */\r\n        Equals(rhs: VideoClipImporter): boolean\r\n        /** Size in bytes of the file before importing.\r\n         */\r\n        readonly sourceFileSize: number\r\n        /** Size in bytes of the file once imported.\r\n         */\r\n        readonly outputFileSize: number\r\n        /** Number of frames in the clip.\r\n         */\r\n        readonly frameCount: number\r\n        /** Frame rate of the clip.\r\n         */\r\n        readonly frameRate: number\r\n        /** Whether to keep the alpha from the source into the transcoded clip.\r\n         */\r\n        keepAlpha: boolean\r\n        /** True if the source file has a channel for per-pixel transparency.\r\n         */\r\n        readonly sourceHasAlpha: boolean\r\n        /** Images are deinterlaced during transcode.  This tells the importer how to interpret fields in the source, if any.\r\n         */\r\n        deinterlaceMode: VideoDeinterlaceMode\r\n        /** Apply a vertical flip during import.\r\n         */\r\n        flipVertical: boolean\r\n        /** Apply a horizontal flip during import.\r\n         */\r\n        flipHorizontal: boolean\r\n        /** Import audio tracks from source file.\r\n         */\r\n        importAudio: boolean\r\n        /** Whether the imported clip contains sRGB color data.\r\n         */\r\n        sRGBClip: boolean\r\n        /** Default values for the platform-specific import settings.\r\n         */\r\n        defaultTargetSettings: VideoImporterTargetSettings\r\n        /** Whether the preview is currently playing.\r\n         */\r\n        readonly isPlayingPreview: boolean\r\n        /** Number of audio tracks in the source file.\r\n         */\r\n        readonly sourceAudioTrackCount: number\r\n        /** Numerator of the pixel aspect ratio (num:den).\r\n         */\r\n        readonly pixelAspectRatioNumerator: number\r\n        /** Denominator of the pixel aspect ratio (num:den).\r\n         */\r\n        readonly pixelAspectRatioDenominator: number\r\n        /** Returns true if transcoding was skipped during import, false otherwise. (Read Only)\n\nWhen VideoImporterTargetSettings.enableTranscoding is set to true, the resulting transcoding operation done at import time may be quite long, up to many hours depending on source resolution and content duration. An option to skip this process is offered in the asset import progress bar. When skipped, the transcoding instead provides a non-transcoded verision of the asset. However, the importer settings stay intact so this property can be inspected to detect the incoherence with the generated artifact.\n\nRe-importing without stopping the transcode process, or with transcode turned off, causes this property to become false.\r\n         */\r\n        readonly transcodeSkipped: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum, Array, ValueType } from \"System\";\r\n    import { Vector2, Vector4 } from \"UnityEngine\";\r\n    /** Texture importer lets you modify Texture2D import settings from editor scripts.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class TextureImporter extends AssetImporter {\r\n        constructor()\r\n        /** Get platform specific texture settings.\r\n         * @param platform The platform for which settings are required (see options below).\r\n         * @param maxTextureSize Maximum texture width/height in pixels.\r\n         * @param textureFormat Format of the texture for the given platform.\r\n         * @param compressionQuality Value from 0..100, equivalent to the standard JPEG quality setting.\r\n         * @param etc1AlphaSplitEnabled Status of the ETC1 and alpha split flag.\r\n         * @returns True if the platform override was found, false if no override was found. \r\n         */\r\n        GetPlatformTextureSettings(platform: string, maxTextureSize: jsb.Out<number>, textureFormat: jsb.Out<TextureImporterFormat>, compressionQuality: jsb.Out<number>, etc1AlphaSplitEnabled: jsb.Out<boolean>): boolean\r\n        /** Get platform specific texture settings.\r\n         * @param platform The platform whose settings are required (see below).\r\n         * @param maxTextureSize Maximum texture width/height in pixels.\r\n         * @param textureFormat Format of the texture.\r\n         * @param compressionQuality Value from 0..100, equivalent to the standard JPEG quality setting.\r\n         * @returns True if the platform override was found, false if no override was found. \r\n         */\r\n        GetPlatformTextureSettings(platform: string, maxTextureSize: jsb.Out<number>, textureFormat: jsb.Out<TextureImporterFormat>, compressionQuality: jsb.Out<number>): boolean\r\n        /** Get platform specific texture settings.\r\n         * @param platform The platform whose settings are required (see below).\r\n         * @param maxTextureSize Maximum texture width/height in pixels.\r\n         * @param textureFormat Format of the texture.\r\n         * @returns True if the platform override was found, false if no override was found. \r\n         */\r\n        GetPlatformTextureSettings(platform: string, maxTextureSize: jsb.Out<number>, textureFormat: jsb.Out<TextureImporterFormat>): boolean\r\n        /** Get platform specific texture settings.\r\n         * @param platform The platform whose settings are required (see below).\r\n         * @returns A TextureImporterPlatformSettings structure containing the platform parameters. \r\n         */\r\n        GetPlatformTextureSettings(platform: string): TextureImporterPlatformSettings\r\n        GetDefaultPlatformTextureSettings(): TextureImporterPlatformSettings\r\n        /** Returns the TextureImporterFormat that would be automatically chosen for this platform.\r\n         * @returns Format chosen by the system for the provided platform, TextureImporterFormat.Automatic if the platform does not exist. \r\n         */\r\n        GetAutomaticFormat(platform: string): TextureImporterFormat\r\n        /** Set specific target platform settings.\r\n         * @param platformSettings Structure containing the platform settings.\r\n         */\r\n        SetPlatformTextureSettings(platformSettings: TextureImporterPlatformSettings): void\r\n        /** Clear specific target platform settings.\r\n         * @param platform The platform whose settings are to be cleared (see below).\r\n         */\r\n        ClearPlatformTextureSettings(platform: string): void\r\n        DoesSourceTextureHaveAlpha(): boolean\r\n        /** Read texture settings into TextureImporterSettings class.\r\n         */\r\n        ReadTextureSettings(dest: TextureImporterSettings): void\r\n        /** Set texture importers settings from TextureImporterSettings class.\r\n         */\r\n        SetTextureSettings(src: TextureImporterSettings): void\r\n        ReadTextureImportInstructions(target: BuildTarget, desiredFormat: jsb.Out<any>, colorSpace: jsb.Out<any>, compressionQuality: jsb.Out<number>): void\r\n        /** Validates ref::TextureImporterFormat:: based on a specified import type (ref::TextureImporterType::) and a specified build target (ref::BuildTarget::.).\r\n         * @param textureType The TextureImporterType that the importer uses.\r\n         * @param target The platform that the setting targets, referred to as the ref::BuilTarget::.\r\n         * @param currentFormat The TextureImporterFormat to validate.\r\n         * @returns Returns true if ref::TextureImporterFormat:: is valid and can be set. Returns false otherwise. \r\n         */\r\n        static IsPlatformTextureFormatValid(textureType: TextureImporterType, target: BuildTarget, currentFormat: TextureImporterFormat): boolean\r\n        /** Validates ref::TextureImporterFormat:: based on the type of the current format (ref::TextureImporterType::) and the default platform.\r\n         * @param currentFormat The TextureImporterType that the importer uses.\r\n         * @param textureType The TextureImporterFormat to validate.\r\n         * @returns Returns true if ref::TextureImporterFormat:: is valid and can be set. Returns false otherwise. \r\n         */\r\n        static IsDefaultPlatformTextureFormatValid(textureType: TextureImporterType, currentFormat: TextureImporterFormat): boolean\r\n        /** Maximum texture size.\r\n         */\r\n        maxTextureSize: number\r\n        /** Quality of Texture Compression in the range [0..100].\r\n         */\r\n        compressionQuality: number\r\n        /** Use crunched compression when available.\r\n         */\r\n        crunchedCompression: boolean\r\n        /** Allows alpha splitting on relevant platforms for this texture.\r\n         */\r\n        allowAlphaSplitting: boolean\r\n        /** ETC2 texture decompression fallback override on Android devices that don't support ETC2.\r\n         */\r\n        androidETC2FallbackOverride: any\r\n        /** Compression of imported texture.\r\n         */\r\n        textureCompression: TextureImporterCompression\r\n        /** Select how the alpha of the imported texture is generated.\r\n         */\r\n        alphaSource: TextureImporterAlphaSource\r\n        /** Cubemap generation mode.\r\n         */\r\n        generateCubemap: TextureImporterGenerateCubemap\r\n        /** Scaling mode for non power of two textures.\r\n         */\r\n        npotScale: TextureImporterNPOTScale\r\n        /** Set this to true if you want texture data to be readable from scripts. Set it to false to prevent scripts from reading texture data.\r\n         */\r\n        isReadable: boolean\r\n        /** Enable mipmap streaming for this texture.\r\n         */\r\n        streamingMipmaps: boolean\r\n        /** Relative priority for this texture when reducing memory size in order to hit the memory budget.\r\n         */\r\n        streamingMipmapsPriority: number\r\n        /** When enabled, this texture can solely be used in combination with a Texture Stack for Virtual Texturing. When enabled the texture is not guaranteed to be available as a Texture2D in the Player (e.g., not accessible from a script). When disabled, the Player includes the texture both as a Texture2D (e.g., accessible from script) and as a streamable texture in a Texture Stack.\r\n         */\r\n        vtOnly: boolean\r\n        /** Generate Mip Maps.\r\n         */\r\n        mipmapEnabled: boolean\r\n        /** Keeps texture borders the same when generating mipmaps.\r\n         */\r\n        borderMipmap: boolean\r\n        /** Determines whether this texture stores color data.\r\n         */\r\n        sRGBTexture: boolean\r\n        /** Enables or disables coverage-preserving alpha mipmapping.\r\n         */\r\n        mipMapsPreserveCoverage: boolean\r\n        /** Returns or assigns the alpha test reference value.\r\n         */\r\n        alphaTestReferenceValue: number\r\n        /** Mipmap filtering mode.\r\n         */\r\n        mipmapFilter: TextureImporterMipFilter\r\n        /** Fades out mip levels to a gray color.\r\n         */\r\n        fadeout: boolean\r\n        /** Mip level where texture begins to fade out.\r\n         */\r\n        mipmapFadeDistanceStart: number\r\n        /** Mip level where texture is faded out completely.\r\n         */\r\n        mipmapFadeDistanceEnd: number\r\n        /** Converts heightmaps to normal maps.\r\n         */\r\n        convertToNormalmap: boolean\r\n        /** Normal map filtering mode.\r\n         */\r\n        normalmapFilter: TextureImporterNormalFilter\r\n        /** Amount of bumpyness in the heightmap.\r\n         */\r\n        heightmapScale: number\r\n        /** Anisotropic filtering level of the texture.\r\n         */\r\n        anisoLevel: number\r\n        /** Filtering mode of the texture.\r\n         */\r\n        filterMode: any\r\n        /** Texture coordinate wrapping mode.\r\n         */\r\n        wrapMode: any\r\n        /** Texture U coordinate wrapping mode.\r\n         */\r\n        wrapModeU: any\r\n        /** Texture V coordinate wrapping mode.\r\n         */\r\n        wrapModeV: any\r\n        /** Texture W coordinate wrapping mode for Texture3D.\r\n         */\r\n        wrapModeW: any\r\n        /** Mip map bias of the texture.\r\n         */\r\n        mipMapBias: number\r\n        /** If the provided alpha channel is transparency, enable this to prefilter the color to avoid filtering artifacts.\r\n         */\r\n        alphaIsTransparency: boolean\r\n        /** Returns true if this TextureImporter is setup for Sprite packing.\r\n         */\r\n        readonly qualifiesForSpritePacking: boolean\r\n        /** Selects Single or Manual import mode for Sprite textures.\r\n         */\r\n        spriteImportMode: SpriteImportMode\r\n        /** Array representing the sections of the atlas corresponding to individual sprite graphics.\r\n         */\r\n        spritesheet: Array<SpriteMetaData>\r\n        /** Secondary textures for the imported Sprites.\r\n         */\r\n        secondarySpriteTextures: Array<any>\r\n        /** Selects the Sprite packing tag.\r\n         */\r\n        spritePackingTag: string\r\n        /** The number of pixels in the sprite that correspond to one unit in world space.\r\n         */\r\n        spritePixelsPerUnit: number\r\n        /** The point in the Sprite object's coordinate space where the graphic is located.\r\n         */\r\n        spritePivot: Vector2\r\n        /** Border sizes of the generated sprites.\r\n         */\r\n        spriteBorder: Vector4\r\n        /** Which type of texture are we dealing with here.\r\n         */\r\n        textureType: TextureImporterType\r\n        /** The shape of the imported texture.\r\n         */\r\n        textureShape: TextureImporterShape\r\n        /** Ignore the Gamma attribute in PNG files. This property does not effect other file formats.\r\n         */\r\n        ignorePngGamma: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Custom mouse cursor shapes used with EditorGUIUtility.AddCursorRect.\r\n     */\r\n    enum MouseCursor {\r\n        /** Normal pointer arrow.\r\n         */\r\n        Arrow = 0,\r\n        /** Text cursor.\r\n         */\r\n        Text = 1,\r\n        /** Vertical resize arrows.\r\n         */\r\n        ResizeVertical = 2,\r\n        /** Horizontal resize arrows.\r\n         */\r\n        ResizeHorizontal = 3,\r\n        /** Arrow with a Link badge (for assigning pointers).\r\n         */\r\n        Link = 4,\r\n        /** Arrow with small arrows for indicating sliding at number fields.\r\n         */\r\n        SlideArrow = 5,\r\n        /** Resize up-right for window edges.\r\n         */\r\n        ResizeUpRight = 6,\r\n        /** Resize up-Left for window edges.\r\n         */\r\n        ResizeUpLeft = 7,\r\n        /** Arrow with the move symbol next to it for the sceneview.\r\n         */\r\n        MoveArrow = 8,\r\n        /** Arrow with the rotate symbol next to it for the sceneview.\r\n         */\r\n        RotateArrow = 9,\r\n        /** Arrow with the scale symbol next to it for the sceneview.\r\n         */\r\n        ScaleArrow = 10,\r\n        /** Arrow with the plus symbol next to it.\r\n         */\r\n        ArrowPlus = 11,\r\n        /** Arrow with the minus symbol next to it.\r\n         */\r\n        ArrowMinus = 12,\r\n        /** Cursor with a dragging hand for pan.\r\n         */\r\n        Pan = 13,\r\n        /** Cursor with an eye for orbit.\r\n         */\r\n        Orbit = 14,\r\n        /** Cursor with a magnifying glass for zoom.\r\n         */\r\n        Zoom = 15,\r\n        /** Cursor with an eye and stylized arrow keys for FPS navigation.\r\n         */\r\n        FPS = 16,\r\n        /** The current user defined cursor.\r\n         */\r\n        CustomCursor = 17,\r\n        /** Up-Down resize arrows for window splitters.\r\n         */\r\n        SplitResizeUpDown = 18,\r\n        /** Left-Right resize arrows for window splitters.\r\n         */\r\n        SplitResizeLeftRight = 19,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Enumeration specifying the current pause state of the Editor.\n\nSee Also: PlayModeStateChange, EditorApplication.pauseStateChanged, EditorApplication.isPaused.\r\n     */\r\n    enum PauseState {\r\n        /** Occurs as soon as the Editor is paused, which may occur during either edit mode or play mode.\r\n         */\r\n        Paused = 0,\r\n        /** Occurs as soon as the Editor is unpaused, which may occur during either edit mode or play mode.\r\n         */\r\n        Unpaused = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Enumeration specifying a change in the Editor's play mode state.\n\nSee Also: PauseState, EditorApplication.playModeStateChanged, EditorApplication.isPlaying.\r\n     */\r\n    enum PlayModeStateChange {\r\n        /** Occurs during the next update of the Editor application if it is in edit mode and was previously in play mode.\r\n         */\r\n        EnteredEditMode = 0,\r\n        /** Occurs when exiting edit mode, before the Editor is in play mode.\r\n         */\r\n        ExitingEditMode = 1,\r\n        /** Occurs during the next update of the Editor application if it is in play mode and was previously in edit mode.\r\n         */\r\n        EnteredPlayMode = 2,\r\n        /** Occurs when exiting play mode, before the Editor is in edit mode.\r\n         */\r\n        ExitingPlayMode = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Export package option. Multiple options can be combined together using the | operator.\r\n     */\r\n    enum ExportPackageOptions {\r\n        /** Default mode. Will not include dependencies or subdirectories nor include Library assets unless specifically included in the asset list.\r\n         */\r\n        Default = 0,\r\n        /** The export operation will be run asynchronously and reveal the exported package file in a file browser window after the export is finished.\r\n         */\r\n        Interactive = 1,\r\n        /** Will recurse through any subdirectories listed and include all assets inside them.\r\n         */\r\n        Recurse = 2,\r\n        /** In addition to the assets paths listed, all dependent assets will be included as well.\r\n         */\r\n        IncludeDependencies = 4,\r\n        /** The exported package will include all library assets, ie. the project settings located in the Library folder of the project.\r\n         */\r\n        IncludeLibraryAssets = 8,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Options for AssetDatabase.ForceReserializeAssets.\r\n     */\r\n    enum ForceReserializeAssetsOptions {\r\n        /** Specifies that AssetDatabase.ForceReserializeAssets should load, upgrade, and save the assets at the paths passed to the function, but not their accompanying .meta files.\r\n         */\r\n        ReserializeAssets = 1,\r\n        /** Specifies that AssetDatabase.ForceReserializeAssets should load, upgrade, and save the .meta files for the assets at the paths passed to the function, but not the assets themselves.\r\n         */\r\n        ReserializeMetadata = 2,\r\n        /** Specifies that AssetDatabase.ForceReserializeAssets should load, upgrade, and save both the assets at the paths passed to the function, and also their accompanying .meta files.\r\n         */\r\n        ReserializeAssetsAndMetadata = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Options for querying the version control system status of a file.\r\n     */\r\n    enum StatusQueryOptions {\r\n        /** Force a refresh of the version control system status of the file. This is slow but accurate.\r\n         */\r\n        ForceUpdate = 0,\r\n        /** This option sets the status query to first use the latest valid version control system status of the file and query for a valid status synchronously if otherwise.\r\n         */\r\n        UseCachedIfPossible = 1,\r\n        /** This option sets the status query to first use the latest valid version control system status of the file and query for a valid status asynchronously if otherwise.\r\n         */\r\n        UseCachedAsync = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Object as Object1 } from \"UnityEngine\";\r\n    /** SerializedObject and SerializedProperty are classes for editing serialized fields on Object|Unity objects in a completely generic way. These classes automatically handle dirtying individual serialized fields so they will be processed by the Undo system and styled correctly for Prefab overrides when drawn in the Inspector.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SerializedObject extends Object {\r\n        constructor(obj: Object1, context: Object1)\r\n        constructor(objs: Array<Object1>, context: Object1)\r\n        constructor(obj: Object1)\r\n        constructor(objs: Array<Object1>)\r\n        Dispose(): void\r\n        GetIterator(): SerializedProperty\r\n        /** Find serialized property by name.\r\n         */\r\n        FindProperty(propertyPath: string): SerializedProperty\r\n        ApplyModifiedProperties(): boolean\r\n        SetIsDifferentCacheDirty(): void\r\n        Update(): void\r\n        UpdateIfRequiredOrScript(): boolean\r\n        ApplyModifiedPropertiesWithoutUndo(): boolean\r\n        /** Copies a value from a SerializedProperty to the corresponding serialized property on the serialized object.\r\n         */\r\n        CopyFromSerializedProperty(prop: SerializedProperty): void\r\n        /** Copies a changed value from a SerializedProperty to the corresponding serialized property on the serialized object.\r\n         */\r\n        CopyFromSerializedPropertyIfDifferent(prop: SerializedProperty): boolean\r\n        /** The inspected object (Read Only).\r\n         */\r\n        readonly targetObject: Object1\r\n        /** The inspected objects (Read Only).\r\n         */\r\n        readonly targetObjects: Array<Object1>\r\n        /** The context used to store and resolve ExposedReference types. This is set by the SerializedObject constructor.\r\n         */\r\n        readonly context: Object1\r\n        /** Is true when the SerializedObject has a modified property that has not been applied.\r\n         */\r\n        readonly hasModifiedProperties: boolean\r\n        /** Does the serialized object represents multiple objects due to multi-object editing? (Read Only)\r\n         */\r\n        readonly isEditingMultipleObjects: boolean\r\n        /** Defines the maximum size beyond which arrays cannot be edited when multiple objects are selected.\r\n         */\r\n        maxArraySizeForMultiEditing: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Object as Object1, Color, AnimationCurve, Vector2, Vector3, Vector4, Vector2Int, Vector3Int, Quaternion, Rect, RectInt, Bounds, BoundsInt } from \"UnityEngine\";\r\n    import { IEnumerator } from \"System.Collections\";\r\n    /** SerializedProperty and SerializedObject are classes for editing properties on objects in a completely generic way that automatically handles undo and styling UI for Prefabs.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SerializedProperty extends Object {\r\n        Copy(): SerializedProperty\r\n        /** Retrieves the SerializedProperty at a relative path to the current property.\r\n         */\r\n        FindPropertyRelative(relativePropertyPath: string): SerializedProperty\r\n        GetEnumerator(): IEnumerator\r\n        /** Returns the element at the specified index in the array.\r\n         */\r\n        GetArrayElementAtIndex(index: number): SerializedProperty\r\n        /** Move to next visible property.\r\n         */\r\n        NextVisible(enterChildren: boolean): boolean\r\n        ClearArray(): void\r\n        Dispose(): void\r\n        /** Move to next property.\r\n         */\r\n        Next(enterChildren: boolean): boolean\r\n        Reset(): void\r\n        CountRemaining(): number\r\n        CountInProperty(): number\r\n        DuplicateCommand(): boolean\r\n        DeleteCommand(): boolean\r\n        /** Retrieves the SerializedProperty that defines the end range of this property.\r\n         */\r\n        GetEndProperty(includeInvisible: boolean): SerializedProperty\r\n        GetEndProperty(): SerializedProperty\r\n        /** Insert an empty element at the specified index in the array.\r\n         */\r\n        InsertArrayElementAtIndex(index: number): void\r\n        /** Delete the element at the specified index in the array.\r\n         */\r\n        DeleteArrayElementAtIndex(index: number): void\r\n        /** Move an array element from srcIndex to dstIndex.\r\n         */\r\n        MoveArrayElement(srcIndex: number, dstIndex: number): boolean\r\n        /** Returns the element at the specified index in the fixed buffer.\r\n         */\r\n        GetFixedBufferElementAtIndex(index: number): SerializedProperty\r\n        /** See if contained serialized properties are equal.\r\n         */\r\n        static EqualContents(x: SerializedProperty, y: SerializedProperty): boolean\r\n        /** Compares the data for two SerializedProperties. This method ignores paths and SerializedObjects.\r\n         */\r\n        static DataEquals(x: SerializedProperty, y: SerializedProperty): boolean\r\n        protected constructor()\r\n        /** SerializedObject this property belongs to (Read Only).\r\n         */\r\n        readonly serializedObject: SerializedObject\r\n        /** A reference to another Object in the Scene. This reference is resolved in the context of the SerializedObject containing the SerializedProperty.\r\n         */\r\n        exposedReferenceValue: Object1\r\n        /** Does this property represent multiple different values due to multi-object editing? (Read Only)\r\n         */\r\n        readonly hasMultipleDifferentValues: boolean\r\n        /** Nice display name of the property. (Read Only)\r\n         */\r\n        readonly displayName: string\r\n        /** Name of the property. (Read Only)\r\n         */\r\n        readonly name: string\r\n        /** Type name of the property. (Read Only)\r\n         */\r\n        readonly type: string\r\n        /** Type name of the element in an array property. (Read Only)\r\n         */\r\n        readonly arrayElementType: string\r\n        /** Tooltip of the property. (Read Only)\r\n         */\r\n        readonly tooltip: string\r\n        /** Nesting depth of the property. (Read Only)\r\n         */\r\n        readonly depth: number\r\n        /** Full path of the property. (Read Only)\r\n         */\r\n        readonly propertyPath: string\r\n        /** Is this property editable? (Read Only)\r\n         */\r\n        readonly editable: boolean\r\n        readonly isAnimated: boolean\r\n        /** Is this property expanded in the inspector?\r\n         */\r\n        isExpanded: boolean\r\n        /** Does it have child properties? (Read Only)\r\n         */\r\n        readonly hasChildren: boolean\r\n        /** Does it have visible child properties? (Read Only)\r\n         */\r\n        readonly hasVisibleChildren: boolean\r\n        /** Is property part of a Prefab instance? (Read Only)\r\n         */\r\n        readonly isInstantiatedPrefab: boolean\r\n        /** Allows you to check whether a property's value is overriden (i.e. different to the Prefab it belongs to).\r\n         */\r\n        prefabOverride: boolean\r\n        /** Allows you to check whether his property is a PrefabUtility.IsDefaultOverride|default override.\n\nCertain properties on Prefab instances are default overrides.\n\nSee PrefabUtility.IsDefaultOverride for more information.\r\n         */\r\n        readonly isDefaultOverride: boolean\r\n        /** Type of this property (Read Only).\r\n         */\r\n        readonly propertyType: SerializedPropertyType\r\n        /** Value of an integer property.\r\n         */\r\n        intValue: number\r\n        /** Value of a integer property as a long.\r\n         */\r\n        longValue: number\r\n        /** Value of a boolean property.\r\n         */\r\n        boolValue: boolean\r\n        /** Value of a float property.\r\n         */\r\n        floatValue: number\r\n        /** Value of a float property as a double.\r\n         */\r\n        doubleValue: number\r\n        /** Value of a string property.\r\n         */\r\n        stringValue: string\r\n        /** Value of a color property.\r\n         */\r\n        colorValue: Color\r\n        /** Value of a animation curve property.\r\n         */\r\n        animationCurveValue: AnimationCurve\r\n        /** Value of an object reference property.\r\n         */\r\n        objectReferenceValue: Object1\r\n        managedReferenceValue: Object\r\n        /** String corresponding to the value of the managed reference object (dynamic) full type string.\r\n         */\r\n        readonly managedReferenceFullTypename: string\r\n        /** String corresponding to the value of the managed reference field full type string.\r\n         */\r\n        readonly managedReferenceFieldTypename: string\r\n        objectReferenceInstanceIDValue: number\r\n        /** Enum index of an enum property.\r\n         */\r\n        enumValueIndex: number\r\n        /** Names of enumeration of an enum property.\r\n         */\r\n        readonly enumNames: Array<string>\r\n        /** Display-friendly names of enumeration of an enum property.\r\n         */\r\n        readonly enumDisplayNames: Array<string>\r\n        /** Value of a 2D vector property.\r\n         */\r\n        vector2Value: Vector2\r\n        /** Value of a 3D vector property.\r\n         */\r\n        vector3Value: Vector3\r\n        /** Value of a 4D vector property.\r\n         */\r\n        vector4Value: Vector4\r\n        /** Value of a 2D integer vector property.\r\n         */\r\n        vector2IntValue: Vector2Int\r\n        /** Value of a 3D integer vector property.\r\n         */\r\n        vector3IntValue: Vector3Int\r\n        /** Value of a quaternion property.\r\n         */\r\n        quaternionValue: Quaternion\r\n        /** Value of a rectangle property.\r\n         */\r\n        rectValue: Rect\r\n        /** Value of a rectangle with integer values property.\r\n         */\r\n        rectIntValue: RectInt\r\n        /** Value of bounds property.\r\n         */\r\n        boundsValue: Bounds\r\n        /** Value of bounds with integer values property.\r\n         */\r\n        boundsIntValue: BoundsInt\r\n        /** Is this property an array? (Read Only)\r\n         */\r\n        readonly isArray: boolean\r\n        /** The number of elements in the array. If the SerializedObject contains multiple objects it will return the smallest number of elements. So it is always possible to iterate through the SerializedObject and only get properties found in all objects.\r\n         */\r\n        arraySize: number\r\n        /** Is this property a fixed buffer? (Read Only)\r\n         */\r\n        readonly isFixedBuffer: boolean\r\n        /** The number of elements in the fixed buffer. (Read Only)\r\n         */\r\n        readonly fixedBufferSize: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Type of a SerializedProperty.\r\n     */\r\n    enum SerializedPropertyType {\r\n        /** Integer property.\r\n         */\r\n        Integer = 0,\r\n        /** Boolean property.\r\n         */\r\n        Boolean = 1,\r\n        /** Float property.\r\n         */\r\n        Float = 2,\r\n        /** String property.\r\n         */\r\n        String = 3,\r\n        /** Color property.\r\n         */\r\n        Color = 4,\r\n        /** Reference to another object.\r\n         */\r\n        ObjectReference = 5,\r\n        /** LayerMask property.\r\n         */\r\n        LayerMask = 6,\r\n        /** Enumeration property.\r\n         */\r\n        Enum = 7,\r\n        /** 2D vector property.\r\n         */\r\n        Vector2 = 8,\r\n        /** 3D vector property.\r\n         */\r\n        Vector3 = 9,\r\n        /** 4D vector property.\r\n         */\r\n        Vector4 = 10,\r\n        /** Rectangle property.\r\n         */\r\n        Rect = 11,\r\n        /** Array size property.\r\n         */\r\n        ArraySize = 12,\r\n        /** Character property.\r\n         */\r\n        Character = 13,\r\n        /** AnimationCurve property.\r\n         */\r\n        AnimationCurve = 14,\r\n        /** Bounds property.\r\n         */\r\n        Bounds = 15,\r\n        /** Gradient property.\r\n         */\r\n        Gradient = 16,\r\n        /** Quaternion property.\r\n         */\r\n        Quaternion = 17,\r\n        /** A reference to another Object in the Scene. This is done via an ExposedReference type and resolves to a reference to an Object that exists in the context of the SerializedObject containing the SerializedProperty.\r\n         */\r\n        ExposedReference = 18,\r\n        /** Fixed buffer size property.\r\n         */\r\n        FixedBufferSize = 19,\r\n        /** 2D integer vector property.\r\n         */\r\n        Vector2Int = 20,\r\n        /** 3D integer vector property.\r\n         */\r\n        Vector3Int = 21,\r\n        /** Rectangle with Integer values property.\r\n         */\r\n        RectInt = 22,\r\n        /** Bounds with Integer values property.\r\n         */\r\n        BoundsInt = 23,\r\n        /** Managed reference property.\r\n         */\r\n        ManagedReference = 24,\r\n        Generic = -1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array } from \"System\";\r\n    /** Provide various options to control the behavior of BuildPipeline.BuildPlayer.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class BuildPlayerOptions extends ValueType {\r\n        constructor()\r\n        /** The Scenes to be included in the build. If empty, the currently open Scene will be built. Paths are relative to the project folder (AssetsMyLevelsMyScene.unity).\r\n         */\r\n        scenes: Array<string>\r\n        /** The path where the application will be built.\r\n         */\r\n        locationPathName: string\r\n        /** The path to an manifest file describing all of the asset bundles used in the build (optional).\r\n         */\r\n        assetBundleManifestPath: string\r\n        /** The BuildTargetGroup to build.\r\n         */\r\n        targetGroup: BuildTargetGroup\r\n        /** The BuildTarget to build.\r\n         */\r\n        target: BuildTarget\r\n        /** Additional BuildOptions, like whether to run the built player.\r\n         */\r\n        options: BuildOptions\r\n        /** User-specified preprocessor defines used while compiling assemblies for the player.\r\n         */\r\n        extraScriptingDefines: Array<string>\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Asset Bundle building options.\r\n     */\r\n    enum BuildAssetBundleOptions {\r\n        /** Build assetBundle without any special option.\r\n         */\r\n        None = 0,\r\n        /** Don't compress the data when creating the AssetBundle.\r\n         */\r\n        UncompressedAssetBundle = 1,\r\n        /** Includes all dependencies.\r\n         */\r\n        CollectDependencies = 2,\r\n        /** Forces inclusion of the entire asset.\r\n         */\r\n        CompleteAssets = 4,\r\n        /** Do not include type information within the AssetBundle.\r\n         */\r\n        DisableWriteTypeTree = 8,\r\n        /** Builds an asset bundle using a hash for the id of the object stored in the asset bundle.\r\n         */\r\n        DeterministicAssetBundle = 16,\r\n        /** Force rebuild the assetBundles.\r\n         */\r\n        ForceRebuildAssetBundle = 32,\r\n        /** Ignore the type tree changes when doing the incremental build check.\r\n         */\r\n        IgnoreTypeTreeChanges = 64,\r\n        /** Append the hash to the assetBundle name.\r\n         */\r\n        AppendHashToAssetBundleName = 128,\r\n        /** Use chunk-based LZ4 compression when creating the AssetBundle.\r\n         */\r\n        ChunkBasedCompression = 256,\r\n        /** Do not allow the build to succeed if any errors are reporting during it.\r\n         */\r\n        StrictMode = 512,\r\n        /** Do a dry run build.\r\n         */\r\n        DryRunBuild = 1024,\r\n        /** Disables Asset Bundle LoadAsset by file name.\r\n         */\r\n        DisableLoadAssetByFileName = 4096,\r\n        /** Disables Asset Bundle LoadAsset by file name with extension.\r\n         */\r\n        DisableLoadAssetByFileNameWithExtension = 8192,\r\n        /** Removes the Unity Version number in the Archive File & Serialized File headers during the build.\r\n         */\r\n        AssetBundleStripUnityVersion = 32768,\r\n        /** Enable asset bundle protection.\r\n         */\r\n        EnableProtection = 65536,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Target build platform.\r\n     */\r\n    enum BuildTarget {\r\n        /** Build a macOS standalone (Intel 64-bit).\r\n         */\r\n        StandaloneOSX = 2,\r\n        StandaloneOSXUniversal = 3,\r\n        /** Build a macOS Intel 32-bit standalone. (This build target is deprecated)\r\n         */\r\n        StandaloneOSXIntel = 4,\r\n        /** Build a Windows standalone.\r\n         */\r\n        StandaloneWindows = 5,\r\n        /** Build a web player. (This build target is deprecated. Building for web player will no longer be supported in future versions of Unity.)\r\n         */\r\n        WebPlayer = 6,\r\n        /** Build a streamed web player.\r\n         */\r\n        WebPlayerStreamed = 7,\r\n        /** Build an iOS player.\r\n         */\r\n        iOS = 9,\r\n        PS3 = 10,\r\n        XBOX360 = 11,\r\n        /** Build an Android .apk standalone app.\r\n         */\r\n        Android = 13,\r\n        /** Build a Linux standalone.\r\n         */\r\n        StandaloneLinux = 17,\r\n        /** Build a Windows 64-bit standalone.\r\n         */\r\n        StandaloneWindows64 = 19,\r\n        /** WebGL.\r\n         */\r\n        WebGL = 20,\r\n        /** Build an Windows Store Apps player.\r\n         */\r\n        WSAPlayer = 21,\r\n        /** Build a Linux 64-bit standalone.\r\n         */\r\n        StandaloneLinux64 = 24,\r\n        /** Build a Linux universal standalone.\r\n         */\r\n        StandaloneLinuxUniversal = 25,\r\n        WP8Player = 26,\r\n        /** Build a macOS Intel 64-bit standalone. (This build target is deprecated)\r\n         */\r\n        StandaloneOSXIntel64 = 27,\r\n        BlackBerry = 28,\r\n        Tizen = 29,\r\n        PSP2 = 30,\r\n        /** Build a PS4 Standalone.\r\n         */\r\n        PS4 = 31,\r\n        PSM = 32,\r\n        /** Build a Xbox One Standalone.\r\n         */\r\n        XboxOne = 33,\r\n        SamsungTV = 34,\r\n        /** Build to Nintendo 3DS platform.\r\n         */\r\n        N3DS = 35,\r\n        WiiU = 36,\r\n        /** Build to Apple's tvOS platform.\r\n         */\r\n        tvOS = 37,\r\n        /** Build a Nintendo Switch player.\r\n         */\r\n        Switch = 38,\r\n        Lumin = 39,\r\n        /** Build a Stadia standalone.\r\n         */\r\n        Stadia = 40,\r\n        /** Build a CloudRendering standalone.\r\n         */\r\n        CloudRendering = 41,\r\n        GameCoreScarlett = 42,\r\n        GameCoreXboxSeries = 42,\r\n        GameCoreXboxOne = 43,\r\n        /** Build to PlayStation 5 platform.\r\n         */\r\n        PS5 = 44,\r\n        NoTarget = -2,\r\n        /** OBSOLETE: Use iOS. Build an iOS player.\r\n         */\r\n        iPhone = -1,\r\n        /** OBSOLETE: Use iOS. Build an iOS player.\r\n         */\r\n        BB10 = -1,\r\n        /** OBSOLETE: Use iOS. Build an iOS player.\r\n         */\r\n        MetroPlayer = -1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Building options. Multiple options can be combined together.\r\n     */\r\n    enum BuildOptions {\r\n        /** Force full optimizations for script compilation in Development builds.\r\n         */\r\n        None = 0,\r\n        /** Force full optimizations for script compilation in Development builds.\r\n         */\r\n        CompressTextures = 0,\r\n        /** Force full optimizations for script compilation in Development builds.\r\n         */\r\n        StripDebugSymbols = 0,\r\n        /** Force full optimizations for script compilation in Development builds.\r\n         */\r\n        ForceOptimizeScriptCompilation = 0,\r\n        /** Force full optimizations for script compilation in Development builds.\r\n         */\r\n        Il2CPP = 0,\r\n        /** Build a development version of the player.\r\n         */\r\n        Development = 1,\r\n        /** Run the built player.\r\n         */\r\n        AutoRunPlayer = 4,\r\n        /** Show the built player.\r\n         */\r\n        ShowBuiltPlayer = 8,\r\n        /** Build a compressed asset bundle that contains streamed Scenes loadable with the UnityWebRequest class.\r\n         */\r\n        BuildAdditionalStreamedScenes = 16,\r\n        /** Used when building Xcode (iOS) or Eclipse (Android) projects.\r\n         */\r\n        AcceptExternalModificationsToPlayer = 32,\r\n        InstallInBuildFolder = 64,\r\n        /** Copy UnityObject.js alongside Web Player so it wouldn't have to be downloaded from internet.\r\n         */\r\n        WebPlayerOfflineDeployment = 128,\r\n        /** Start the player with a connection to the profiler in the editor.\r\n         */\r\n        ConnectWithProfiler = 256,\r\n        /** Allow script debuggers to attach to the player remotely.\r\n         */\r\n        AllowDebugging = 512,\r\n        /** Symlink runtime libraries when generating iOS Xcode project. (Faster iteration time).\r\n         */\r\n        SymlinkLibraries = 1024,\r\n        /** Don't compress the data when creating the asset bundle.\r\n         */\r\n        UncompressedAssetBundle = 2048,\r\n        /** Sets the Player to connect to the Editor.\r\n         */\r\n        ConnectToHost = 4096,\r\n        EnableInstantGame = 8192,\r\n        /** Options for building the standalone player in headless mode.\r\n         */\r\n        EnableHeadlessMode = 16384,\r\n        /** Only build the scripts in a Project.\r\n         */\r\n        BuildScriptsOnly = 32768,\r\n        /** Patch a Development app package rather than completely rebuilding it.\n\nSupported platforms:\r\n         */\r\n        PatchPackage = 65536,\r\n        /** Include assertions in the build. By default, the assertions are only included in development builds.\r\n         */\r\n        ForceEnableAssertions = 131072,\r\n        /** Use chunk-based LZ4 compression when building the Player.\r\n         */\r\n        CompressWithLz4 = 262144,\r\n        /** Use chunk-based LZ4 high-compression when building the Player.\r\n         */\r\n        CompressWithLz4HC = 524288,\r\n        ComputeCRC = 1048576,\r\n        /** Do not allow the build to succeed if any errors are reporting during it.\r\n         */\r\n        StrictMode = 2097152,\r\n        /** Build will include Assemblies for testing.\r\n         */\r\n        IncludeTestAssemblies = 4194304,\r\n        /** Will force the buildGUID to all zeros.\r\n         */\r\n        NoUniqueIdentifier = 8388608,\r\n        /** Sets the Player to wait for player connection on player start.\r\n         */\r\n        WaitForPlayerConnection = 33554432,\r\n        /** Enables code coverage. You can use this as a complimentary way of enabling code coverage on platforms that do not support command line arguments.\r\n         */\r\n        EnableCodeCoverage = 67108864,\r\n        /** Enables Deep Profiling support in the player.\r\n         */\r\n        EnableDeepProfilingSupport = 268435456,\r\n        /** Generates more information in the BuildReport.\r\n         */\r\n        DetailedBuildReport = 536870912,\r\n        /** Enable Shader Livelink support.\r\n         */\r\n        ShaderLivelinkSupport = 1073741824,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, ValueType, Enum, Array } from \"System\";\r\n    import { Component, Object as Object1, GameObject, PrimitiveType } from \"UnityEngine\";\r\n    /** Use the DefaultObject to create a new UnityEngine.Object in the editor.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class ObjectFactory extends Object {\r\n        /** Create a new instance of the given type.\r\n         * @param type The type of instance to create.\r\n         */\r\n        static CreateInstance(type: any): Object1\r\n        /** Creates a new component and adds it to the specified GameObject.\r\n         * @param gameObject The GameObject to add the new component to.\r\n         * @param type The type of component to create and add to the GameObject.\r\n         * @returns Returns the component that was created and added to the GameObject. \r\n         */\r\n        static AddComponent(gameObject: GameObject, type: any): Component\r\n        /** Creates a new GameObject.\r\n         * @param name Name of the GameObject.\r\n         * @param types The optional types to add to the GameObject when created.\r\n         * @param scene Scene where the GameObject should be created.\r\n         * @param hideFlags HideFlags to assign to the GameObject.\r\n         * @returns Returns the GameObject that was created. \r\n         */\r\n        static CreateGameObject(scene: any, hideFlags: any, name: string, ...types: any[]): GameObject\r\n        /** Creates a new GameObject.\r\n         * @param name Name of the GameObject.\r\n         * @param types The optional types to add to the GameObject when created.\r\n         * @param scene Scene where the GameObject should be created.\r\n         * @param hideFlags HideFlags to assign to the GameObject.\r\n         * @returns Returns the GameObject that was created. \r\n         */\r\n        static CreateGameObject(name: string, ...types: any[]): GameObject\r\n        /** Creates a GameObject primitive.\r\n         * @param type The type of primitive to create.\r\n         */\r\n        static CreatePrimitive(type: PrimitiveType): GameObject\r\n        static componentWasAdded(op: \"add\" | \"remove\", fn: (obj: Component) => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    /** Unity Camera Editor.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class CameraEditor extends Editor {\r\n        constructor()\r\n        OnEnable(): void\r\n        OnDisable(): void\r\n        OnDestroy(): void\r\n        OnInspectorGUI(): void\r\n        OnOverlayGUI(target: Object, sceneView: SceneView): void\r\n        OnSceneGUI(): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Camera, Vector3, Rect, Matrix4x4 } from \"UnityEngine\";\r\n    /** Utilities for cameras.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class CameraEditorUtils extends Object {\r\n        static HandleFrustum(c: Camera, cameraEditorTargetIndex: number): void\r\n        /** Draw the frustrum gizmo of a camera.\r\n         * @param camera The camera to use.\r\n         */\r\n        static DrawFrustumGizmo(camera: Camera): void\r\n        /** Calculate the frustrum corners from the sensor physical properties, without taking gate fitting into account.\nTo get the actual frustum with gate fit adjustment, use CameraEditorUtils.TryGetFrustum.\nThis method is equivalent to CameraEditorUtils.TryGetFrustum for non-physical cameras.\n\nCorners are calculated in this order: left bottom, left top, right top, right bottom.\r\n         * @param camera Camera to use.\r\n         * @param near The corners of the near plane. (A minimum size of 4 elements is required.)\r\n         * @param far The corners of the far plane. (A minimum size of 4 elements is required.)\r\n         * @param frustumAspect The aspect ratio of the frustrum.\r\n         * @returns Whether the frustrum was calculated. \r\n         */\r\n        static TryGetSensorGateFrustum(camera: Camera, near: Array<Vector3>, far: Array<Vector3>, frustumAspect: jsb.Out<number>): boolean\r\n        /** Calculate the frustrum corners.\n\nCorners are calculated in this order: left bottom, left top, right top, right bottom.\r\n         * @param camera Camera to use.\r\n         * @param near The corners of the near plane. (A minimum size of 4 elements is required.)\r\n         * @param far The corners of the far plane. (A minimum size of 4 elements is required.)\r\n         * @param frustumAspect The aspect ratio of the frustrum.\r\n         * @returns Whether the frustrum was calculated. \r\n         */\r\n        static TryGetFrustum(camera: Camera, near: Array<Vector3>, far: Array<Vector3>, frustumAspect: jsb.Out<number>): boolean\r\n        /** Check whether a viewport is valid.\r\n         * @param normalizedViewPortRect Viewport to check.\r\n         * @returns Whether the viewport is valid. \r\n         */\r\n        static IsViewportRectValidToRender(normalizedViewPortRect: Rect): boolean\r\n        /** Calculate the frustrum aspect ratio of a camera.\r\n         * @param camera Camera to use.\r\n         * @returns The frustrum aspect ratio of the provided camera. \r\n         */\r\n        static GetFrustumAspectRatio(camera: Camera): number\r\n        /** Calculate the world space position of a point in clip space.\n\nThe z component will be used to get the point at the distance z from the viewer.\r\n         * @param clipToWorld Clip to world matrix to use.\r\n         * @param viewPositionWS The viewer's position in world space.\r\n         * @param positionCS The position in clip space.\r\n         * @returns The corresponding world space position. \r\n         */\r\n        static PerspectiveClipToWorld(clipToWorld: Matrix4x4, viewPositionWS: Vector3, positionCS: Vector3): Vector3\r\n        /** Calculate the points of the frustrum plane facing the viewer at a specific distance.\n\nThe points array will be filled with the calculated points in the following order: left bottom, left top, right top and right bottom.\r\n         * @param clipToWorld Clip space to world space matrix.\r\n         * @param viewPosition View position in world space.\r\n         * @param distance Distance from the view position of the plane.\r\n         * @param points Calculated points.  (A minimum size of 4 elements is required).\r\n         */\r\n        static GetFrustumPlaneAt(clipToWorld: Matrix4x4, viewPosition: Vector3, distance: number, points: Array<Vector3>): void\r\n        /** The aspect ratio of the game view.\r\n         */\r\n        static readonly GameViewAspectRatio: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Vector3, Transform } from \"UnityEngine\";\r\n    /** Editor Transform Utility Class.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class TransformUtils extends Object {\r\n        /** Returns the rotation of a transform as it is shown in the Transform Inspector window.\r\n         * @param t Transform to get the rotation from.\r\n         * @returns Rotation as it is shown in the Transform Inspector window. \r\n         */\r\n        static GetInspectorRotation(t: Transform): Vector3\r\n        /** Sets the rotation of a transform as it would be set by the Transform Inspector window.\r\n         * @param t Transform to set the rotation on.\r\n         * @param r Rotation as it would be set by the Transform Inspector window.\r\n         */\r\n        static SetInspectorRotation(t: Transform, r: Vector3): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Utility functions for working with JSON data and engine objects.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class EditorJsonUtility extends Object {\r\n        /** Generate a JSON representation of an object.\r\n         * @param obj The object to convert to JSON form.\r\n         * @param prettyPrint If true, format the output for readability. If false, format the output for minimum size. Default is false.\r\n         * @returns The object's data in JSON format. \r\n         */\r\n        static ToJson(obj: Object, prettyPrint: boolean): string\r\n        /** Generate a JSON representation of an object.\r\n         * @param obj The object to convert to JSON form.\r\n         * @param prettyPrint If true, format the output for readability. If false, format the output for minimum size. Default is false.\r\n         * @returns The object's data in JSON format. \r\n         */\r\n        static ToJson(obj: Object): string\r\n        /** Overwrite data in an object by reading from its JSON representation.\r\n         * @param json The JSON representation of the object.\r\n         * @param objectToOverwrite The object to overwrite.\r\n         */\r\n        static FromJsonOverwrite(json: string, objectToOverwrite: Object): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { GameObject, Transform } from \"UnityEngine\";\r\n    /** GameObject utility functions.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class GameObjectUtility extends Object {\r\n        constructor()\r\n        /** Gets the StaticEditorFlags of the GameObject specified.\r\n         * @param go The GameObject whose flags you are interested in.\r\n         * @returns The static editor flags of the GameObject specified. \r\n         */\r\n        static GetStaticEditorFlags(go: GameObject): StaticEditorFlags\r\n        /** Sets the StaticEditorFlags of the specified GameObject.\r\n         * @param go The GameObject whose Static Editor Flags you want to set.\r\n         * @param flags The StaticEditorFlags to set on the GameObject.\r\n         */\r\n        static SetStaticEditorFlags(go: GameObject, flags: StaticEditorFlags): void\r\n        /** Returns true if the passed in StaticEditorFlags are set on the GameObject specified.\r\n         * @param go The GameObject to check.\r\n         * @param flags The flags you want to check.\r\n         * @returns Whether the GameObject's static flags match the flags specified. \r\n         */\r\n        static AreStaticEditorFlagsSet(go: GameObject, flags: StaticEditorFlags): boolean\r\n        /** Get the navmesh area index for the GameObject.\r\n         * @param go The GameObject to query.\r\n         * @returns NavMesh area index. \r\n         */\r\n        static GetNavMeshArea(go: GameObject): number\r\n        /** Set the navmesh area for the gameobject.\r\n         * @param go GameObject to modify.\r\n         * @param areaIndex NavMesh area index to set.\r\n         */\r\n        static SetNavMeshArea(go: GameObject, areaIndex: number): void\r\n        /** Get the navmesh area index from the area name.\r\n         * @param name NavMesh area name to query.\r\n         * @returns The NavMesh area index. If there is no NavMesh area with the requested name, the return value is -1. \r\n         */\r\n        static GetNavMeshAreaFromName(name: string): number\r\n        static GetNavMeshAreaNames(): Array<string>\r\n        /** You can use this method before instantiating a new sibling, or before parenting one GameObject to another, to ensure the new child GameObject has a unique name compared to its siblings in the hierarchy.\r\n         * @param parent Target parent for a new GameObject. Null means root level.\r\n         * @param name Requested name for a new GameObject.\r\n         * @returns Unique name for a new GameObject. \r\n         */\r\n        static GetUniqueNameForSibling(parent: Transform, name: string): string\r\n        /** You can use this method after parenting one GameObject to another to ensure the child GameObject has a unique name compared to its siblings in the hierarchy.\r\n         * @param self The GameObject whose name you want to ensure is unique.\r\n         */\r\n        static EnsureUniqueNameForSibling(self: GameObject): void\r\n        /** Sets the parent and gives the child the same layer and position.\r\n         * @param child The GameObject that should have a new parent set.\r\n         * @param parent The GameObject that the child should get as a parent and have position and layer copied from. If null, this function does nothing.\r\n         */\r\n        static SetParentAndAlign(child: GameObject, parent: GameObject): void\r\n        /** Gets the number of MonoBehaviours with a missing script for the given GameObject.\r\n         * @param go GameObject to query.\r\n         * @returns The number of MonoBehaviours with a missing script. \r\n         */\r\n        static GetMonoBehavioursWithMissingScriptCount(go: GameObject): number\r\n        /** Removes the MonoBehaviours with a missing script from the given GameObject.\r\n         * @param go The GameObject to remove MonoBehaviours with a missing script from.\r\n         * @returns The number of MonoBehaviours with a missing script that were removed. \r\n         */\r\n        static RemoveMonoBehavioursWithMissingScript(go: GameObject): number\r\n        /** Use this method if a custom scene culling mask is needed for renderers that should be shown or hidden in a Scene view when Prefab Mode in Context is active.\r\n         * @param sceneCullingMask The scene culling mask intended to be used with the custom renderer.\r\n         * @param gameObject The GameObject associated with the custom renderer.\r\n         * @returns If the GameObject is hidden for Prefab Mode in Context, a modified scene culling mask is returned. If it's not hidden, then the input scene culling mask is returned. \r\n         */\r\n        static ModifyMaskIfGameObjectIsHiddenForPrefabModeInContext(sceneCullingMask: number, gameObject: GameObject): number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Stores and accesses Unity editor preferences.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class EditorPrefs extends Object {\r\n        /** Sets the value of the preference identified by key as an integer.\r\n         * @param key Name of key to write integer to.\r\n         * @param value Value of the integer to write into the storage.\r\n         */\r\n        static SetInt(key: string, value: number): void\r\n        /** Returns the value corresponding to key in the preference file if it exists.\r\n         * @param key Name of key to read integer from.\r\n         * @param defaultValue Integer value to return if the key is not in the storage.\r\n         * @returns The value stored in the preference file. \r\n         */\r\n        static GetInt(key: string, defaultValue: number): number\r\n        /** Returns the value corresponding to key in the preference file if it exists.\r\n         * @param key Name of key to read integer from.\r\n         * @param defaultValue Integer value to return if the key is not in the storage.\r\n         * @returns The value stored in the preference file. \r\n         */\r\n        static GetInt(key: string): number\r\n        /** Sets the float value of the preference identified by key.\r\n         * @param key Name of key to write float into.\r\n         * @param value Float value to write into the storage.\r\n         */\r\n        static SetFloat(key: string, value: number): void\r\n        /** Returns the float value corresponding to key if it exists in the preference file.\r\n         * @param key Name of key to read float from.\r\n         * @param defaultValue Float value to return if the key is not in the storage.\r\n         * @returns The float value stored in the preference file or the defaultValue id the\n        requested float does not exist. \r\n         */\r\n        static GetFloat(key: string, defaultValue: number): number\r\n        /** Returns the float value corresponding to key if it exists in the preference file.\r\n         * @param key Name of key to read float from.\r\n         * @param defaultValue Float value to return if the key is not in the storage.\r\n         * @returns The float value stored in the preference file or the defaultValue id the\n        requested float does not exist. \r\n         */\r\n        static GetFloat(key: string): number\r\n        /** Sets the value of the preference identified by key. Note that EditorPrefs does not support null strings and will store an empty string instead.\r\n         */\r\n        static SetString(key: string, value: string): void\r\n        /** Returns the value corresponding to key in the preference file if it exists.\r\n         */\r\n        static GetString(key: string, defaultValue: string): string\r\n        /** Returns the value corresponding to key in the preference file if it exists.\r\n         */\r\n        static GetString(key: string): string\r\n        /** Sets the value of the preference identified by key.\r\n         */\r\n        static SetBool(key: string, value: boolean): void\r\n        /** Returns the value corresponding to key in the preference file if it exists.\r\n         */\r\n        static GetBool(key: string, defaultValue: boolean): boolean\r\n        /** Returns the value corresponding to key in the preference file if it exists.\r\n         */\r\n        static GetBool(key: string): boolean\r\n        /** Returns true if key exists in the preferences file.\r\n         * @param key Name of key to check for.\r\n         * @returns The existence or not of the key. \r\n         */\r\n        static HasKey(key: string): boolean\r\n        /** Removes key and its corresponding value from the preferences.\r\n         */\r\n        static DeleteKey(key: string): void\r\n        static DeleteAll(): void\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Enum, Array } from \"System\";\r\n    import { Color, Matrix4x4, Camera, Vector3, Quaternion, EventType, Vector2, Transform, Texture2D, Rect, GUIStyle, GUIContent, Texture, Gradient } from \"UnityEngine\";\r\n    /** Custom 3D GUI controls and drawing in the Scene view.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class Handles extends Object {\r\n        /** Draw a line going through the list of points.\r\n         */\r\n        static DrawPolyLine(...points: Vector3[]): void\r\n        /** Draws a line from p1 to p2.\r\n         * @param p1 The position of the first line's end point in world space.\r\n         * @param p2 The position of the second line's end point in world space.\r\n         * @param thickness Line thickness in UI points (zero thickness draws single-pixel line).\r\n         */\r\n        static DrawLine(p1: Vector3, p2: Vector3, thickness: number): void\r\n        /** Draws a line from p1 to p2.\r\n         * @param p1 The position of the first line's end point in world space.\r\n         * @param p2 The position of the second line's end point in world space.\r\n         * @param thickness Line thickness in UI points (zero thickness draws single-pixel line).\r\n         */\r\n        static DrawLine(p1: Vector3, p2: Vector3): void\r\n        /** Draw a list of indexed line segments.\r\n         * @param points A list of points.\r\n         * @param segmentIndices A list of pairs of indices to the start and end points of the line segments.\r\n         */\r\n        static DrawLines(points: Array<Vector3>, segmentIndices: Array<number>): void\r\n        /** Draw a list of line segments.\r\n         * @param lineSegments A list of pairs of points that represent the start and end of line segments.\r\n         */\r\n        static DrawLines(lineSegments: Array<Vector3>): void\r\n        /** Draw a dotted line from p1 to p2.\r\n         * @param p1 The start point.\r\n         * @param p2 The end point.\r\n         * @param screenSpaceSize The size in pixels for the lengths of the line segments and the gaps between them.\r\n         */\r\n        static DrawDottedLine(p1: Vector3, p2: Vector3, screenSpaceSize: number): void\r\n        /** Draw a list of indexed dotted line segments.\r\n         * @param points A list of points.\r\n         * @param segmentIndices A list of pairs of indices to the start and end points of the line segments.\r\n         * @param screenSpaceSize The size in pixels for the lengths of the line segments and the gaps between them.\r\n         */\r\n        static DrawDottedLines(points: Array<Vector3>, segmentIndices: Array<number>, screenSpaceSize: number): void\r\n        /** Draw a list of dotted line segments.\r\n         * @param lineSegments A list of pairs of points that represent the start and end of line segments.\r\n         * @param screenSpaceSize The size in pixels for the lengths of the line segments and the gaps between them.\r\n         */\r\n        static DrawDottedLines(lineSegments: Array<Vector3>, screenSpaceSize: number): void\r\n        /** Draw a wireframe box with center and size.\r\n         */\r\n        static DrawWireCube(center: Vector3, size: Vector3): void\r\n        static ShouldRenderGizmos(): boolean\r\n        static DrawGizmos(camera: Camera): void\r\n        /** Make a 3D disc that can be dragged with the mouse.\r\n         * @param id Control id of the handle.\r\n         * @param rotation The rotation of the disc.\r\n         * @param position The center of the disc.\r\n         * @param axis The axis to rotate around.\r\n         * @param size The size of the disc in world space.\r\n         * @param cutoffPlane If true, only the front-facing half of the circle is draw / draggable. This is useful when you have many overlapping rotation axes (like in the default rotate tool) to avoid clutter.\r\n         * @param snap The grid size to snap to.\r\n         * @returns The new rotation value modified by the user's interaction with the handle. If the user has not moved the handle, it will return the same value as you passed into the function. \r\n         */\r\n        static Disc(id: number, rotation: Quaternion, position: Vector3, axis: Vector3, size: number, cutoffPlane: boolean, snap: number): Quaternion\r\n        /** Make a 3D disc that can be dragged with the mouse.\r\n         * @param id Control id of the handle.\r\n         * @param rotation The rotation of the disc.\r\n         * @param position The center of the disc.\r\n         * @param axis The axis to rotate around.\r\n         * @param size The size of the disc in world space.\r\n         * @param cutoffPlane If true, only the front-facing half of the circle is draw / draggable. This is useful when you have many overlapping rotation axes (like in the default rotate tool) to avoid clutter.\r\n         * @param snap The grid size to snap to.\r\n         * @returns The new rotation value modified by the user's interaction with the handle. If the user has not moved the handle, it will return the same value as you passed into the function. \r\n         */\r\n        static Disc(rotation: Quaternion, position: Vector3, axis: Vector3, size: number, cutoffPlane: boolean, snap: number): Quaternion\r\n        /** Make an unconstrained rotation handle.\r\n         * @param id Control id of the handle.\r\n         * @param rotation Orientation of the handle.\r\n         * @param position Center of the handle in 3D space.\r\n         * @param size The size of the handle.\n\nNote: Use HandleUtility.GetHandleSize where you might want to have constant screen-sized handles.\r\n         * @returns The new rotation value modified by the user's interaction with the handle. If the user has not moved the handle, it will return the same value as you passed into the function. \r\n         */\r\n        static FreeRotateHandle(id: number, rotation: Quaternion, position: Vector3, size: number): Quaternion\r\n        /** Make an unconstrained rotation handle.\r\n         * @param id Control id of the handle.\r\n         * @param rotation Orientation of the handle.\r\n         * @param position Center of the handle in 3D space.\r\n         * @param size The size of the handle.\n\nNote: Use HandleUtility.GetHandleSize where you might want to have constant screen-sized handles.\r\n         * @returns The new rotation value modified by the user's interaction with the handle. If the user has not moved the handle, it will return the same value as you passed into the function. \r\n         */\r\n        static FreeRotateHandle(rotation: Quaternion, position: Vector3, size: number): Quaternion\r\n        static Slider(controlID: number, position: Vector3, offset: Vector3, direction: Vector3, size: number, capFunction: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void, snap: number): Vector3\r\n        static Slider(controlID: number, position: Vector3, direction: Vector3, size: number, capFunction: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void, snap: number): Vector3\r\n        static Slider(position: Vector3, direction: Vector3, size: number, capFunction: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void, snap: number): Vector3\r\n        /** Make a 3D slider that moves along one axis.\r\n         * @param position The position of the current point in the space of Handles.matrix.\r\n         * @param direction The direction axis of the slider in the space of Handles.matrix.\r\n         * @param size The size of the handle in the space of Handles.matrix. Use HandleUtility.GetHandleSize if you want a constant screen-space size.\r\n         * @param snap The snap increment. See Handles.SnapValue.\r\n         * @param capFunction The function to call for doing the actual drawing. By default it is Handles.ArrowHandleCap, but any function that has the same signature can be used.\r\n         * @returns The new value modified by the user's interaction with the handle. If the user has not moved the handle, it will return the position value passed into the function. \r\n         */\r\n        static Slider(position: Vector3, direction: Vector3): Vector3\r\n        static FreeMoveHandle(controlID: number, position: Vector3, rotation: Quaternion, size: number, snap: Vector3, capFunction: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void): Vector3\r\n        static FreeMoveHandle(position: Vector3, rotation: Quaternion, size: number, snap: Vector3, capFunction: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void): Vector3\r\n        static ScaleValueHandle(controlID: number, value: number, position: Vector3, rotation: Quaternion, size: number, capFunction: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void, snap: number): number\r\n        static ScaleValueHandle(value: number, position: Vector3, rotation: Quaternion, size: number, capFunction: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void, snap: number): number\r\n        static Button(position: Vector3, direction: Quaternion, size: number, pickSize: number, capFunction: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void): boolean\r\n        /** Draw a cube handle. Pass this into handle functions.\r\n         * @param controlID The control ID for the handle.\r\n         * @param position The position of the handle in the space of Handles.matrix.\r\n         * @param rotation The rotation of the handle in the space of Handles.matrix.\r\n         * @param size The size of the handle in the space of Handles.matrix. Use HandleUtility.GetHandleSize if you want a constant screen-space size.\r\n         * @param eventType Event type for the handle to act upon. By design it handles EventType.Layout and EventType.Repaint events.\r\n         */\r\n        static CubeHandleCap(controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType): void\r\n        /** Draw a sphere handle. Pass this into handle functions.\r\n         * @param controlID The control ID for the handle.\r\n         * @param position The position of the handle in the space of Handles.matrix.\r\n         * @param rotation The rotation of the handle in the space of Handles.matrix.\r\n         * @param eventType Event type for the handle to act upon. By design it handles EventType.Layout and EventType.Repaint events.\r\n         * @param size The size of the handle in the space of Handles.matrix. Use HandleUtility.GetHandleSize if you want a constant screen-space size.\r\n         */\r\n        static SphereHandleCap(controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType): void\r\n        /** Draw a cone handle. Pass this into handle functions.\r\n         * @param controlID The control ID for the handle.\r\n         * @param position The position of the handle in the space of Handles.matrix.\r\n         * @param rotation The rotation of the handle in the space of Handles.matrix.\r\n         * @param size The size of the handle in the space of Handles.matrix. Use HandleUtility.GetHandleSize if you want a constant screen-space size.\r\n         * @param eventType Event type for the handle to act upon. By design it handles EventType.Layout and EventType.Repaint events.\r\n         */\r\n        static ConeHandleCap(controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType): void\r\n        /** Draw a cylinder handle. Pass this into handle functions.\r\n         * @param controlID The control ID for the handle.\r\n         * @param position The position of the handle in the space of Handles.matrix.\r\n         * @param rotation The rotation of the handle in the space of Handles.matrix.\r\n         * @param size The size of the handle in the space of Handles.matrix. Use HandleUtility.GetHandleSize if you want a constant screen-space size.\r\n         * @param eventType Event type for the handle to act upon. By design it handles EventType.Layout and EventType.Repaint events.\r\n         */\r\n        static CylinderHandleCap(controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType): void\r\n        /** Draw a rectangle handle. Pass this into handle functions.\r\n         * @param controlID The control ID for the handle.\r\n         * @param position The position of the handle in the space of Handles.matrix.\r\n         * @param rotation The rotation of the handle in the space of Handles.matrix.\r\n         * @param size The size of the handle in the space of Handles.matrix. Use HandleUtility.GetHandleSize if you want a constant screen-space size.\r\n         * @param eventType Event type for the handle to act upon. By design it handles EventType.Layout and EventType.Repaint events.\r\n         */\r\n        static RectangleHandleCap(controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType): void\r\n        /** Draw a dot handle. Pass this into handle functions.\r\n         * @param controlID The control ID for the handle.\r\n         * @param position The position of the handle in the space of Handles.matrix.\r\n         * @param rotation The rotation of the handle in the space of Handles.matrix.\r\n         * @param size The size of the handle in the space of Handles.matrix. Use HandleUtility.GetHandleSize if you want a constant screen-space size.\r\n         * @param eventType Event type for the handle to act upon. By design it handles EventType.Layout and EventType.Repaint events.\r\n         */\r\n        static DotHandleCap(controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType): void\r\n        /** Draw a circle handle. Pass this into handle functions.\r\n         * @param controlID The control ID for the handle.\r\n         * @param position The position of the handle in the space of Handles.matrix.\r\n         * @param rotation The rotation of the handle in the space of Handles.matrix.\r\n         * @param size The size of the handle in the space of Handles.matrix. Use HandleUtility.GetHandleSize if you want a constant screen-space size.\r\n         * @param eventType Event type for the handle to act upon. By design it handles EventType.Layout and EventType.Repaint events.\r\n         */\r\n        static CircleHandleCap(controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType): void\r\n        /** Draw an arrow like those used by the move tool.\r\n         * @param controlID The control ID for the handle.\r\n         * @param position The position of the handle in the space of Handles.matrix.\r\n         * @param rotation The rotation of the handle in the space of Handles.matrix.\r\n         * @param size The size of the handle in the space of Handles.matrix. Use HandleUtility.GetHandleSize if you want a constant screen-space size.\r\n         * @param eventType Event type for the handle to act upon. By design it handles EventType.Layout and EventType.Repaint events.\r\n         */\r\n        static ArrowHandleCap(controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType): void\r\n        /** Draw a camera facing selection frame.\r\n         */\r\n        static DrawSelectionFrame(controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType): void\r\n        /** Make a position handle.\r\n         * @param position Center of the handle in 3D space.\r\n         * @param rotation Orientation of the handle in 3D space.\r\n         * @returns The new value modified by the user's interaction with the handle. If the user has not moved the handle, it will return the same value as you passed into the function. \r\n         */\r\n        static PositionHandle(position: Vector3, rotation: Quaternion): Vector3\r\n        /** Make a Scene view rotation handle.\r\n         * @param rotation Orientation of the handle.\r\n         * @param position Center of the handle in 3D space.\r\n         * @returns The new rotation value modified by the user's interaction with the handle. If the user has not moved the handle, it will return the same value as you passed into the function. \r\n         */\r\n        static RotationHandle(rotation: Quaternion, position: Vector3): Quaternion\r\n        /** Make a Scene view scale handle.\r\n         * @param scale Scale to modify.\r\n         * @param position The position of the handle.\r\n         * @param rotation The rotation of the handle.\r\n         * @param size Allows you to scale the size of the handle on-scren.\r\n         * @returns The new value modified by the user's interaction with the handle. If the user has not moved the handle, it will return the same value as you passed into the function. \r\n         */\r\n        static ScaleHandle(scale: Vector3, position: Vector3, rotation: Quaternion, size: number): Vector3\r\n        /** Make a Scene view radius handle.\r\n         * @param rotation Orientation of the handle.\r\n         * @param position Center of the handle in 3D space.\r\n         * @param radius Radius to modify.\r\n         * @param handlesOnly Whether to omit the circular outline of the radius and only draw the point handles.\r\n         * @returns The new value modified by the user's interaction with the handle. If the user has not moved the handle, it will return the same value as you passed into the function.\n\nNote: Use HandleUtility.GetHandleSize where you might want to have constant screen-sized handles. \r\n         */\r\n        static RadiusHandle(rotation: Quaternion, position: Vector3, radius: number, handlesOnly: boolean): number\r\n        /** Make a Scene view radius handle.\r\n         * @param rotation Orientation of the handle.\r\n         * @param position Center of the handle in 3D space.\r\n         * @param radius Radius to modify.\r\n         * @param handlesOnly Whether to omit the circular outline of the radius and only draw the point handles.\r\n         * @returns The new value modified by the user's interaction with the handle. If the user has not moved the handle, it will return the same value as you passed into the function.\n\nNote: Use HandleUtility.GetHandleSize where you might want to have constant screen-sized handles. \r\n         */\r\n        static RadiusHandle(rotation: Quaternion, position: Vector3, radius: number): number\r\n        static Slider2D(id: number, handlePos: Vector3, offset: Vector3, handleDir: Vector3, slideDir1: Vector3, slideDir2: Vector3, handleSize: number, capFunction: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void, snap: Vector2, drawHelper: boolean): Vector3\r\n        static Slider2D(id: number, handlePos: Vector3, offset: Vector3, handleDir: Vector3, slideDir1: Vector3, slideDir2: Vector3, handleSize: number, capFunction: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void, snap: Vector2): Vector3\r\n        static Slider2D(id: number, handlePos: Vector3, handleDir: Vector3, slideDir1: Vector3, slideDir2: Vector3, handleSize: number, capFunction: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void, snap: Vector2, drawHelper: boolean): Vector3\r\n        static Slider2D(handlePos: Vector3, handleDir: Vector3, slideDir1: Vector3, slideDir2: Vector3, handleSize: number, capFunction: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void, snap: Vector2, drawHelper: boolean): Vector3\r\n        static Slider2D(id: number, handlePos: Vector3, handleDir: Vector3, slideDir1: Vector3, slideDir2: Vector3, handleSize: number, capFunction: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void, snap: Vector2): Vector3\r\n        static Slider2D(handlePos: Vector3, handleDir: Vector3, slideDir1: Vector3, slideDir2: Vector3, handleSize: number, capFunction: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void, snap: number, drawHelper: boolean): Vector3\r\n        static Slider2D(handlePos: Vector3, handleDir: Vector3, slideDir1: Vector3, slideDir2: Vector3, handleSize: number, capFunction: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void, snap: Vector2): Vector3\r\n        static Slider2D(handlePos: Vector3, handleDir: Vector3, slideDir1: Vector3, slideDir2: Vector3, handleSize: number, capFunction: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void, snap: number): Vector3\r\n        /** Make a directional scale slider.\r\n         * @param scale The value the user can modify.\r\n         * @param position The position of the handle in the space of Handles.matrix.\r\n         * @param direction The direction of the handle in the space of Handles.matrix.\r\n         * @param rotation The rotation of the handle in the space of Handles.matrix.\r\n         * @param size The size of the handle in the space of Handles.matrix. Use HandleUtility.GetHandleSize if you want a constant screen-space size.\r\n         * @param snap The snap increment. See Handles.SnapValue.\r\n         * @returns The new value modified by the user's interaction with the handle. If the user has not moved the handle, it will return the same value as you passed into the function. \r\n         */\r\n        static ScaleSlider(scale: number, position: Vector3, direction: Vector3, rotation: Quaternion, size: number, snap: number): number\r\n        /** Rounds value to the closest multiple of snap if snapping is active. Note that snap can only be positive.\r\n         * @param value The value to snap.\r\n         * @param snap The increment to snap to.\r\n         * @returns If snapping is active, rounds value to the closest multiple of snap (snap can only be positive). \r\n         */\r\n        static SnapValue(value: number, snap: number): number\r\n        /** Rounds value to the closest multiple of snap if snapping is active. Note that snap can only be positive.\r\n         * @param value The value to snap.\r\n         * @param snap The increment to snap to.\r\n         * @returns If snapping is active, rounds value to the closest multiple of snap (snap can only be positive). \r\n         */\r\n        static SnapValue(value: Vector2, snap: Vector2): Vector2\r\n        /** Rounds value to the closest multiple of snap if snapping is active. Note that snap can only be positive.\r\n         * @param value The value to snap.\r\n         * @param snap The increment to snap to.\r\n         * @returns If snapping is active, rounds value to the closest multiple of snap (snap can only be positive). \r\n         */\r\n        static SnapValue(value: Vector3, snap: Vector3): Vector3\r\n        /** Rounds each Transform.position to the closest multiple of EditorSnap.move.\r\n         * @param transforms The transforms to snap.\r\n         * @param axis The axes on which to apply snapping.\r\n         */\r\n        static SnapToGrid(transforms: Array<Transform>, axis: any): void\r\n        static SelectionFrame(controlID: number, position: Vector3, rotation: Quaternion, size: number): void\r\n        /** Draw anti-aliased line specified with point array and width.\r\n         * @param lineTex The AA texture used for rendering.\r\n         * @param width The width of the line.\r\n         * @param points List of points to build the line from.\r\n         */\r\n        static DrawAAPolyLine(width: number, actualNumberOfPoints: number, ...points: Vector3[]): void\r\n        /** Draw anti-aliased line specified with point array and width.\r\n         * @param lineTex The AA texture used for rendering.\r\n         * @param width The width of the line.\r\n         * @param points List of points to build the line from.\r\n         */\r\n        static DrawAAPolyLine(lineTex: Texture2D, width: number, ...points: Vector3[]): void\r\n        /** Draw anti-aliased line specified with point array and width.\r\n         * @param lineTex The AA texture used for rendering.\r\n         * @param width The width of the line.\r\n         * @param points List of points to build the line from.\r\n         */\r\n        static DrawAAPolyLine(width: number, ...points: Vector3[]): void\r\n        /** Draw anti-aliased line specified with point array and width.\r\n         * @param lineTex The AA texture used for rendering.\r\n         * @param width The width of the line.\r\n         * @param points List of points to build the line from.\r\n         */\r\n        static DrawAAPolyLine(lineTex: Texture2D, ...points: Vector3[]): void\r\n        /** Draw anti-aliased line specified with point array and width.\r\n         * @param lineTex The AA texture used for rendering.\r\n         * @param width The width of the line.\r\n         * @param points List of points to build the line from.\r\n         */\r\n        static DrawAAPolyLine(...points: Vector3[]): void\r\n        /** Draw anti-aliased convex polygon specified with point array.\r\n         * @param points List of points describing the convex polygon.\r\n         */\r\n        static DrawAAConvexPolygon(...points: Vector3[]): void\r\n        /** Draw textured bezier line through start and end points with the given tangents.\r\n         * @param startPosition The start point of the bezier line.\r\n         * @param endPosition The end point of the bezier line.\r\n         * @param startTangent The start tangent of the bezier line.\r\n         * @param endTangent The end tangent of the bezier line.\r\n         * @param color The color to use for the bezier line.\r\n         * @param texture The texture to use for drawing the bezier line.\r\n         * @param width The width of the bezier line.\r\n         */\r\n        static DrawBezier(startPosition: Vector3, endPosition: Vector3, startTangent: Vector3, endTangent: Vector3, color: Color, texture: Texture2D, width: number): void\r\n        /** Draws the outline of a flat disc in 3D space.\r\n         * @param center The center of the disc in world space.\r\n         * @param normal The normal of the disc in world space.\r\n         * @param radius The radius of the disc in world space units.\r\n         * @param thickness Line thickness in UI points (zero thickness draws single-pixel line).\r\n         */\r\n        static DrawWireDisc(center: Vector3, normal: Vector3, radius: number, thickness: number): void\r\n        /** Draws the outline of a flat disc in 3D space.\r\n         * @param center The center of the disc in world space.\r\n         * @param normal The normal of the disc in world space.\r\n         * @param radius The radius of the disc in world space units.\r\n         * @param thickness Line thickness in UI points (zero thickness draws single-pixel line).\r\n         */\r\n        static DrawWireDisc(center: Vector3, normal: Vector3, radius: number): void\r\n        /** Draws a circular arc in 3D space.\r\n         * @param center The center of the circle in world space.\r\n         * @param normal The normal of the circle in world space.\r\n         * @param from The direction of the point on the circle circumference, relative to the center, where the arc begins.\r\n         * @param angle The angle of the arc, in degrees.\r\n         * @param radius The radius of the circle in world space units.\r\n         * @param thickness Line thickness in UI points (zero thickness draws single-pixel line).\r\n         */\r\n        static DrawWireArc(center: Vector3, normal: Vector3, from: Vector3, angle: number, radius: number, thickness: number): void\r\n        /** Draws a circular arc in 3D space.\r\n         * @param center The center of the circle in world space.\r\n         * @param normal The normal of the circle in world space.\r\n         * @param from The direction of the point on the circle circumference, relative to the center, where the arc begins.\r\n         * @param angle The angle of the arc, in degrees.\r\n         * @param radius The radius of the circle in world space units.\r\n         * @param thickness Line thickness in UI points (zero thickness draws single-pixel line).\r\n         */\r\n        static DrawWireArc(center: Vector3, normal: Vector3, from: Vector3, angle: number, radius: number): void\r\n        static DrawSolidRectangleWithOutline(rectangle: Rect, faceColor: Color, outlineColor: Color): void\r\n        /** Draw a solid outlined rectangle in 3D space.\r\n         * @param verts The 4 vertices of the rectangle in world coordinates.\r\n         * @param faceColor The color of the rectangle's face.\r\n         * @param outlineColor The outline color of the rectangle.\r\n         */\r\n        static DrawSolidRectangleWithOutline(verts: Array<Vector3>, faceColor: Color, outlineColor: Color): void\r\n        /** Draw a solid flat disc in 3D space.\r\n         * @param center The center of the dics.\r\n         * @param normal The normal of the disc.\r\n         * @param radius The radius of the dics\n\nNote: Use HandleUtility.GetHandleSize where you might want to have constant screen-sized handles.\r\n         */\r\n        static DrawSolidDisc(center: Vector3, normal: Vector3, radius: number): void\r\n        /** Draw a circular sector (pie piece) in 3D space.\r\n         * @param center The center of the circle.\r\n         * @param normal The normal of the circle.\r\n         * @param from The direction of the point on the circumference, relative to the center, where the sector begins.\r\n         * @param angle The angle of the sector, in degrees.\r\n         * @param radius The radius of the circle\n\nNote: Use HandleUtility.GetHandleSize where you might want to have constant screen-sized handles.\r\n         */\r\n        static DrawSolidArc(center: Vector3, normal: Vector3, from: Vector3, angle: number, radius: number): void\r\n        /** Make a text label positioned in 3D space.\r\n         * @param position Position in 3D space as seen from the current handle camera.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\n\nNote: Use HandleUtility.GetHandleSize where you might want to have constant screen-sized handles.\r\n         */\r\n        static Label(position: Vector3, text: string, style: GUIStyle): void\r\n        /** Make a text label positioned in 3D space.\r\n         * @param position Position in 3D space as seen from the current handle camera.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\n\nNote: Use HandleUtility.GetHandleSize where you might want to have constant screen-sized handles.\r\n         */\r\n        static Label(position: Vector3, content: GUIContent, style: GUIStyle): void\r\n        /** Make a text label positioned in 3D space.\r\n         * @param position Position in 3D space as seen from the current handle camera.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\n\nNote: Use HandleUtility.GetHandleSize where you might want to have constant screen-sized handles.\r\n         */\r\n        static Label(position: Vector3, text: string): void\r\n        /** Make a text label positioned in 3D space.\r\n         * @param position Position in 3D space as seen from the current handle camera.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\n\nNote: Use HandleUtility.GetHandleSize where you might want to have constant screen-sized handles.\r\n         */\r\n        static Label(position: Vector3, image: Texture): void\r\n        /** Make a text label positioned in 3D space.\r\n         * @param position Position in 3D space as seen from the current handle camera.\r\n         * @param text Text to display on the label.\r\n         * @param image Texture to display on the label.\r\n         * @param content Text, image and tooltip for this label.\r\n         * @param style The style to use. If left out, the label style from the current GUISkin is used.\n\nNote: Use HandleUtility.GetHandleSize where you might want to have constant screen-sized handles.\r\n         */\r\n        static Label(position: Vector3, content: GUIContent): void\r\n        static GetMainGameViewSize(): Vector2\r\n        /** Clears the camera.\r\n         * @param position Where in the Scene to clear.\r\n         * @param camera The camera to clear.\r\n         */\r\n        static ClearCamera(position: Rect, camera: Camera): void\r\n        static DrawCamera(position: Rect, camera: Camera, drawMode: DrawCameraMode, drawGizmos: boolean): void\r\n        /** Draws a camera inside a rectangle.\r\n         * @param position The area to draw the camera within in GUI coordinates.\r\n         * @param camera The camera to draw.\r\n         * @param drawMode How the camera is drawn (textured, wireframe, etc.).\r\n         */\r\n        static DrawCamera(position: Rect, camera: Camera, drawMode: DrawCameraMode): void\r\n        /** Draws a camera inside a rectangle.\r\n         * @param position The area to draw the camera within in GUI coordinates.\r\n         * @param camera The camera to draw.\r\n         * @param drawMode How the camera is drawn (textured, wireframe, etc.).\r\n         */\r\n        static DrawCamera(position: Rect, camera: Camera): void\r\n        /** Set the current camera so all Handles and Gizmos are draw with its settings.\r\n         */\r\n        static SetCamera(position: Rect, camera: Camera): void\r\n        /** Set the current camera so all Handles and Gizmos are draw with its settings.\r\n         */\r\n        static SetCamera(camera: Camera): void\r\n        static BeginGUI(): void\r\n        static EndGUI(): void\r\n        /** Retuns an array of points to representing the bezier curve.\r\n         */\r\n        static MakeBezierPoints(startPosition: Vector3, endPosition: Vector3, startTangent: Vector3, endTangent: Vector3, division: number): Array<Vector3>\r\n        /** Draws a 3D texture using Signed Distance Field rendering mode in 3D space.\r\n         * @param texture The volumetric texture to draw.\r\n         * @param stepScale The number by which to multiply the ray step size. The ray step size is the distance between 2 neighboring pixels. The default value is 1.\r\n         * @param surfaceOffset The intensity of the pixels at which the surface is rendered. When this value is positive, Unity will expand the rendered surface. When this value is negative, Unity will render empty space as a surface, and a surface as empty space. The default value is 0.\r\n         * @param customColorRamp The custom gradient that Unity uses as a color ramp. If this is not specified, Unity uses <a href=\"https:ai.googleblog.com201908turbo-improved-rainbow-colormap-for.html\">Google Turbo color ramp<a>.\r\n         */\r\n        static DrawTexture3DSDF(texture: Texture, stepScale: number, surfaceOffset: number, customColorRamp: Gradient): void\r\n        /** Draws a 3D texture using Slice rendering mode in 3D space.\r\n         * @param texture The volumetric texture to draw.\r\n         * @param slicePositions The positions of the texture sampling planes.\r\n         * @param filterMode Sets the texture filtering mode to use.\r\n         * @param useColorRamp Enables color ramp visualization.\r\n         * @param customColorRamp The custom gradient that Unity uses as a color ramp. If this is not specified, Unity uses <a href=\"https:ai.googleblog.com201908turbo-improved-rainbow-colormap-for.html\">Google Turbo color ramp<a>.\r\n         */\r\n        static DrawTexture3DSlice(texture: Texture, slicePositions: Vector3, filterMode: any, useColorRamp: boolean, customColorRamp: Gradient): void\r\n        /** Draws a 3D texture using Volume rendering mode in 3D space.\r\n         * @param texture The volumetric texture to draw.\r\n         * @param opacity The non-linear volume opacity modifier. Use this to control the opacity of the visualization. Valid values are 0-1, inclusive. A value of 1 is fully opaque and a value of 0 is fully transparent. The default value is 1.\r\n         * @param qualityModifier Sets the sample per texture pixel count. Higher values result in a higher quality render. The default value is 1.\r\n         * @param filterMode Sets the texture filtering mode to use.\r\n         * @param useColorRamp Enables color ramp visualization.\r\n         * @param customColorRamp The custom gradient that Unity uses as a color ramp. If this is not specified, Unity uses <a href=\"https:ai.googleblog.com201908turbo-improved-rainbow-colormap-for.html\">Google Turbo color ramp<a>.\r\n         */\r\n        static DrawTexture3DVolume(texture: Texture, opacity: number, qualityModifier: number, filterMode: any, useColorRamp: boolean, customColorRamp: Gradient): void\r\n        static DoPositionHandle(position: Vector3, rotation: Quaternion): Vector3\r\n        static DoRotationHandle(rotation: Quaternion, position: Vector3): Quaternion\r\n        static DoScaleHandle(scale: Vector3, position: Vector3, rotation: Quaternion, size: number): Vector3\r\n        /** Creates a transform handle.\r\n         * @param position Position of the handle.\r\n         * @param rotation Orientation of the handle.\r\n         * @param scale Scale value to modify.\r\n         * @param uniformScale Uniform scale value to modify.\r\n         */\r\n        static TransformHandle(position: jsb.Ref<Vector3>, rotation: jsb.Ref<Quaternion>, scale: jsb.Ref<Vector3>): void\r\n        static TransformHandle(position: jsb.Ref<Vector3>, rotation: Quaternion, scale: jsb.Ref<Vector3>): void\r\n        static TransformHandle(position: Vector3, rotation: jsb.Ref<Quaternion>, scale: jsb.Ref<Vector3>): void\r\n        /** Creates a transform handle.\r\n         * @param position Position of the handle.\r\n         * @param rotation Orientation of the handle.\r\n         * @param scale Scale value to modify.\r\n         * @param uniformScale Uniform scale value to modify.\r\n         */\r\n        static TransformHandle(position: jsb.Ref<Vector3>, rotation: jsb.Ref<Quaternion>, uniformScale: jsb.Ref<number>): void\r\n        static TransformHandle(position: jsb.Ref<Vector3>, rotation: Quaternion, uniformScale: jsb.Ref<number>): void\r\n        static TransformHandle(position: Vector3, rotation: jsb.Ref<Quaternion>, uniformScale: jsb.Ref<number>): void\r\n        /** Creates a transform handle.\r\n         * @param position Position of the handle.\r\n         * @param rotation Orientation of the handle.\r\n         * @param scale Scale value to modify.\r\n         * @param uniformScale Uniform scale value to modify.\r\n         */\r\n        static TransformHandle(position: jsb.Ref<Vector3>, rotation: jsb.Ref<Quaternion>): void\r\n        protected constructor()\r\n        /** Are handles lit?\r\n         */\r\n        static lighting: boolean\r\n        /** Colors of the handles.\r\n         */\r\n        static color: Color\r\n        /** zTest of the handles.\r\n         */\r\n        static zTest: any\r\n        /** Matrix for all handle operations.\r\n         */\r\n        static matrix: Matrix4x4\r\n        /** The inverse of the matrix for all handle operations.\r\n         */\r\n        static readonly inverseMatrix: Matrix4x4\r\n        /** Color to use for handles that manipulates the X coordinate of something.\r\n         */\r\n        static readonly xAxisColor: Color\r\n        /** Color to use for handles that manipulates the Y coordinate of something.\r\n         */\r\n        static readonly yAxisColor: Color\r\n        /** Color to use for handles that manipulates the Z coordinate of something.\r\n         */\r\n        static readonly zAxisColor: Color\r\n        /** Color to use for handles that represent the center of something.\r\n         */\r\n        static readonly centerColor: Color\r\n        /** Color to use for the currently active handle.\r\n         */\r\n        static readonly selectedColor: Color\r\n        /** Color to use to highlight an unselected handle currently under the mouse pointer.\r\n         */\r\n        static readonly preselectionColor: Color\r\n        /** Soft color to use for for general things.\r\n         */\r\n        static readonly secondaryColor: Color\r\n        /** Retrieves the user preference setting that controls the thickness of tool handle lines. (Read Only)\r\n         */\r\n        static readonly lineThickness: number\r\n        /** Setup viewport and stuff for a current camera.\r\n         */\r\n        currentCamera: Camera\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Material, GameObject, Camera, Vector2, Vector3, Quaternion, Ray, Rect, GUIContent, GUIStyle, Transform } from \"UnityEngine\";\r\n    /** Helper functions for Scene View style 3D GUI.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class HandleUtility extends Object {\r\n        /** Calculate distance between a point and a Bezier curve.\r\n         */\r\n        static DistancePointBezier(point: Vector3, startPosition: Vector3, endPosition: Vector3, startTangent: Vector3, endTangent: Vector3): number\r\n        /** Map a mouse drag onto a movement along a line in 3D space.\r\n         * @param src The source point of the drag.\r\n         * @param dest The destination point of the drag.\r\n         * @param srcPosition The 3D position the dragged object had at src ray.\r\n         * @param constraintDir 3D direction of constrained movement.\r\n         * @returns The distance travelled along constraintDir. \r\n         */\r\n        static CalcLineTranslation(src: Vector2, dest: Vector2, srcPosition: Vector3, constraintDir: Vector3): number\r\n        /** Returns the parameter for the projection of the point on the given line.\r\n         */\r\n        static PointOnLineParameter(point: Vector3, linePoint: Vector3, lineDirection: Vector3): number\r\n        /** Project point onto a line.\r\n         */\r\n        static ProjectPointLine(point: Vector3, lineStart: Vector3, lineEnd: Vector3): Vector3\r\n        /** Calculate distance between a point and a line.\r\n         */\r\n        static DistancePointLine(point: Vector3, lineStart: Vector3, lineEnd: Vector3): number\r\n        /** Returns the distance in pixels from the mouse pointer to a line.\r\n         */\r\n        static DistanceToLine(p1: Vector3, p2: Vector3): number\r\n        /** Returns the distance in pixels from the mouse pointer to a camera facing circle.\r\n         */\r\n        static DistanceToCircle(position: Vector3, radius: number): number\r\n        /** Returns the distance in pixels from the mouse pointer to a cone.\r\n         * @param position Position of the cone.\r\n         * @param rotation Rotation of the cone.\r\n         * @param size Size of the cone.\r\n         * @returns Distance from mouse to cone in pixels. \r\n         */\r\n        static DistanceToCone(position: Vector3, rotation: Quaternion, size: number): number\r\n        /** Returns the distance in pixels from the mouse pointer to a cube.\r\n         * @param position Position of the cube.\r\n         * @param rotation Rotation of the cube.\r\n         * @param size Size of the cube.\r\n         * @returns Distance from mouse to cube in pixels. \r\n         */\r\n        static DistanceToCube(position: Vector3, rotation: Quaternion, size: number): number\r\n        /** Returns the distance in pixels from the mouse pointer to a rectangle on screen.\r\n         */\r\n        static DistanceToRectangle(position: Vector3, rotation: Quaternion, size: number): number\r\n        /** Distance from a point p in 2d to a line defined by two points a and b.\r\n         */\r\n        static DistancePointToLine(p: Vector2, a: Vector2, b: Vector2): number\r\n        /** Distance from a point p in 2d to a line segment defined by two points a and b.\r\n         */\r\n        static DistancePointToLineSegment(p: Vector2, a: Vector2, b: Vector2): number\r\n        /** Returns the distance in pixels from the mouse pointer to a 3D disc.\r\n         */\r\n        static DistanceToDisc(center: Vector3, normal: Vector3, radius: number): number\r\n        /** Get the point on an disc (in 3D space) which is closest to the current mouse position.\r\n         */\r\n        static ClosestPointToDisc(center: Vector3, normal: Vector3, radius: number): Vector3\r\n        /** Returns the distance in pixels from the mouse pointer to a 3D section of a disc.\r\n         */\r\n        static DistanceToArc(center: Vector3, normal: Vector3, from: Vector3, angle: number, radius: number): number\r\n        /** Get the point on an arc (in 3D space) which is closest to the current mouse position.\r\n         */\r\n        static ClosestPointToArc(center: Vector3, normal: Vector3, from: Vector3, angle: number, radius: number): Vector3\r\n        /** Returns the distance in pixels from the mouse pointer to a polyline.\r\n         */\r\n        static DistanceToPolyLine(...points: Vector3[]): number\r\n        /** Get the point on a polyline (in 3D space) which is closest to the current mouse position.\r\n         */\r\n        static ClosestPointToPolyLine(...vertices: Vector3[]): Vector3\r\n        /** Record a distance measurement from a handle.\r\n         */\r\n        static AddControl(controlId: number, distance: number): void\r\n        /** Add the ID for a default control. This will be picked if nothing else is.\r\n         */\r\n        static AddDefaultControl(controlId: number): void\r\n        /** Get world space size of a manipulator handle at given position.\r\n         * @param position The position of the handle in 3d space.\r\n         * @returns A constant screen-size for the handle, based on the distance between from the supplied handle's position to the camera. \r\n         */\r\n        static GetHandleSize(position: Vector3): number\r\n        /** Convert a world space point to a 2D GUI position.\r\n         * @param world Point in world space.\r\n         */\r\n        static WorldToGUIPoint(world: Vector3): Vector2\r\n        /** Convert a world space point to a 2D GUI position.\r\n         * @param world Point in world space.\r\n         * @returns A Vector3 where the x and y values relate to the 2D GUI position. The z value is the distance in world units from the camera. \r\n         */\r\n        static WorldToGUIPointWithDepth(world: Vector3): Vector3\r\n        /** Converts a 2D GUI position to screen pixel coordinates.\r\n         */\r\n        static GUIPointToScreenPixelCoordinate(guiPoint: Vector2): Vector2\r\n        /** Convert 2D GUI position to a world space ray.\r\n         */\r\n        static GUIPointToWorldRay(position: Vector2): Ray\r\n        /** Calculate a rectangle to display a 2D GUI element near a projected point in 3D space.\r\n         * @param position The world-space position to use.\r\n         * @param content The content to make room for.\r\n         * @param style The style to use. The style's alignment.\r\n         */\r\n        static WorldPointToSizedRect(position: Vector3, content: GUIContent, style: GUIStyle): Rect\r\n        static PickRectObjects(rect: Rect, selectPrefabRootsOnly: boolean): Array<GameObject>\r\n        /** Pick GameObjects that lie within a specified screen rectangle.\r\n         * @param rect An screen rectangle specified with pixel coordinates.\r\n         */\r\n        static PickRectObjects(rect: Rect): Array<GameObject>\r\n        /** Returns the nearest vertex to a guiPoint within a maximum radius of 50 pixels.\r\n         * @param guiPoint A point in GUI space.\r\n         * @param vertex The nearest vertex position to guiPoint, or a default value if no vertex is within the minimum picking distance.\r\n         * @param objectsToSearch An array of Transform to consider when picking the nearest vertex. If null, all active objects in open scenes are considered.\r\n         * @param objectsToIgnore An array of Transform to exclude from consideration when picking nearest vertex.\r\n         * @returns Returns true if a vertex within 50 pixels of the guiPoint was found, false if no vertex found within the minimum picking radius. \r\n         */\r\n        static FindNearestVertex(guiPoint: Vector2, objectsToSearch: Array<Transform>, objectsToIgnore: Array<Transform>, vertex: jsb.Out<Vector3>): boolean\r\n        /** Returns the nearest vertex to a guiPoint within a maximum radius of 50 pixels.\r\n         * @param guiPoint A point in GUI space.\r\n         * @param vertex The nearest vertex position to guiPoint, or a default value if no vertex is within the minimum picking distance.\r\n         * @param objectsToSearch An array of Transform to consider when picking the nearest vertex. If null, all active objects in open scenes are considered.\r\n         * @param objectsToIgnore An array of Transform to exclude from consideration when picking nearest vertex.\r\n         * @returns Returns true if a vertex within 50 pixels of the guiPoint was found, false if no vertex found within the minimum picking radius. \r\n         */\r\n        static FindNearestVertex(guiPoint: Vector2, objectsToSearch: Array<Transform>, vertex: jsb.Out<Vector3>): boolean\r\n        /** Returns the nearest vertex to a guiPoint within a maximum radius of 50 pixels.\r\n         * @param guiPoint A point in GUI space.\r\n         * @param vertex The nearest vertex position to guiPoint, or a default value if no vertex is within the minimum picking distance.\r\n         * @param objectsToSearch An array of Transform to consider when picking the nearest vertex. If null, all active objects in open scenes are considered.\r\n         * @param objectsToIgnore An array of Transform to exclude from consideration when picking nearest vertex.\r\n         * @returns Returns true if a vertex within 50 pixels of the guiPoint was found, false if no vertex found within the minimum picking radius. \r\n         */\r\n        static FindNearestVertex(guiPoint: Vector2, vertex: jsb.Out<Vector3>): boolean\r\n        /** Pick game object closest to specified position.\r\n         * @param selectPrefabRoot Select Prefab.\r\n         * @param materialIndex Returns index into material array of the Renderer component that is closest to specified position.\r\n         * @param position A position in GUI coordinates. The top-left of the window is (0,0), and the bottom-right is (Screen.width, Screen.height).\r\n         * @param ignore An array of GameObjects that will not be considered when selecting the nearest GameObject.\r\n         * @param filter An array of GameObjects to be exclusively considered for selection. If null, all GameObjects in open scenes are eligible for selection.\r\n         * @returns The GameObject that is under the requested position. \r\n         */\r\n        static PickGameObject(position: Vector2, selectPrefabRoot: boolean, ignore: Array<GameObject>, filter: Array<GameObject>): GameObject\r\n        /** Pick game object closest to specified position.\r\n         * @param selectPrefabRoot Select Prefab.\r\n         * @param materialIndex Returns index into material array of the Renderer component that is closest to specified position.\r\n         * @param position A position in GUI coordinates. The top-left of the window is (0,0), and the bottom-right is (Screen.width, Screen.height).\r\n         * @param ignore An array of GameObjects that will not be considered when selecting the nearest GameObject.\r\n         * @param filter An array of GameObjects to be exclusively considered for selection. If null, all GameObjects in open scenes are eligible for selection.\r\n         * @returns The GameObject that is under the requested position. \r\n         */\r\n        static PickGameObject(position: Vector2, ignore: Array<GameObject>, materialIndex: jsb.Out<number>): GameObject\r\n        /** Pick game object closest to specified position.\r\n         * @param selectPrefabRoot Select Prefab.\r\n         * @param materialIndex Returns index into material array of the Renderer component that is closest to specified position.\r\n         * @param position A position in GUI coordinates. The top-left of the window is (0,0), and the bottom-right is (Screen.width, Screen.height).\r\n         * @param ignore An array of GameObjects that will not be considered when selecting the nearest GameObject.\r\n         * @param filter An array of GameObjects to be exclusively considered for selection. If null, all GameObjects in open scenes are eligible for selection.\r\n         * @returns The GameObject that is under the requested position. \r\n         */\r\n        static PickGameObject(position: Vector2, selectPrefabRoot: boolean, ignore: Array<GameObject>): GameObject\r\n        /** Pick game object closest to specified position.\r\n         * @param selectPrefabRoot Select Prefab.\r\n         * @param materialIndex Returns index into material array of the Renderer component that is closest to specified position.\r\n         * @param position A position in GUI coordinates. The top-left of the window is (0,0), and the bottom-right is (Screen.width, Screen.height).\r\n         * @param ignore An array of GameObjects that will not be considered when selecting the nearest GameObject.\r\n         * @param filter An array of GameObjects to be exclusively considered for selection. If null, all GameObjects in open scenes are eligible for selection.\r\n         * @returns The GameObject that is under the requested position. \r\n         */\r\n        static PickGameObject(position: Vector2, materialIndex: jsb.Out<number>): GameObject\r\n        /** Pick game object closest to specified position.\r\n         * @param selectPrefabRoot Select Prefab.\r\n         * @param materialIndex Returns index into material array of the Renderer component that is closest to specified position.\r\n         * @param position A position in GUI coordinates. The top-left of the window is (0,0), and the bottom-right is (Screen.width, Screen.height).\r\n         * @param ignore An array of GameObjects that will not be considered when selecting the nearest GameObject.\r\n         * @param filter An array of GameObjects to be exclusively considered for selection. If null, all GameObjects in open scenes are eligible for selection.\r\n         * @returns The GameObject that is under the requested position. \r\n         */\r\n        static PickGameObject(position: Vector2, selectPrefabRoot: boolean): GameObject\r\n        /** Store all camera settings.\r\n         */\r\n        static PushCamera(camera: Camera): void\r\n        /** Retrieve all camera settings.\r\n         */\r\n        static PopCamera(camera: Camera): void\r\n        /** Casts ray against the Scene and report if an object lies in its path.\r\n         * @returns A boxed RaycastHit, null if nothing hit it. \r\n         */\r\n        static RaySnap(ray: Ray): Object\r\n        /** Casts a ray against the loaded scenes and returns the nearest intersected point on a collider.\r\n         * @param guiPosition The GUI position in the SceneView. You can pass Event.current.mousePosition to this parameter in most cases.\r\n         * @param position Returns the nearest intersected point to a ray cast from the mouse position into the scene.\r\n         * @param normal Returns the normal of the nearest intersected point to a ray cast from the mouse position into the scene.\r\n         * @returns Returns true if the raycast intersected something in the scene; otherwise, false. \r\n         */\r\n        static PlaceObject(guiPosition: Vector2, position: jsb.Out<Vector3>, normal: jsb.Out<Vector3>): boolean\r\n        static Repaint(): void\r\n        protected constructor()\r\n        /** Get standard acceleration for dragging values (Read Only).\r\n         */\r\n        static readonly acceleration: number\r\n        /** Get nice mouse delta to use for dragging a float value (Read Only).\r\n         */\r\n        static readonly niceMouseDelta: number\r\n        /** Get nice mouse delta to use for zooming (Read Only).\r\n         */\r\n        static readonly niceMouseDeltaZoom: number\r\n        static nearestControl: number\r\n        static readonly handleMaterial: Material\r\n        static pickGameObjectCustomPasses(op: \"add\" | \"remove\", fn: (cam: Camera, layers: number, position: Vector2, ignore: Array<GameObject>, filter: Array<GameObject>, materialIndex: jsb.Out<number>) => GameObject): void\r\n        static placeObjectCustomPasses(op: \"add\" | \"remove\", fn: (guiPosition: Vector2, position: jsb.Out<Vector3>, normal: jsb.Out<Vector3>) => boolean): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Color, Quaternion, Camera, Vector3, Object as Object1, Transform, Bounds } from \"UnityEngine\";\r\n    import { Object, Array } from \"System\";\r\n    /** Use this class to manage SceneView settings, change the SceneView camera properties, subscribe to events, call SceneView methods, and render open scenes.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SceneView extends SearchableEditorWindow implements IHasCustomMenu {\r\n        ResetCameraSettings(): void\r\n        /** Sets a replacement shader for rendering this Scene view.\r\n         * @param shader The replacement shader.\r\n         * @param replaceString The replacement shader tag.\r\n         */\r\n        SetSceneViewShaderReplace(shader: any, replaceString: string): void\r\n        OnEnable(): void\r\n        OnDisable(): void\r\n        OnDestroy(): void\r\n        AddItemsToMenu(menu: GenericMenu): void\r\n        IsCameraDrawModeEnabled(mode: SceneView.CameraMode): boolean\r\n        FixNegativeSize(): void\r\n        /** Moves the Scene view to focus on a target.\r\n         * @param point The position in world space to frame.\r\n         * @param direction The direction that the Scene view should view the target point from.\r\n         * @param newSize The amount of camera zoom. Sets size.\r\n         * @param ortho Whether the camera focus is in orthographic mode (true) or perspective mode (false).\r\n         * @param instant Apply the movement immediately (true) or animate the transition (false).\r\n         */\r\n        LookAt(point: Vector3, direction: Quaternion, newSize: number, ortho: boolean, instant: boolean): void\r\n        /** Moves the Scene view to focus on a target.\r\n         * @param point The position in world space to frame.\r\n         * @param direction The direction that the Scene view should view the target point from.\r\n         * @param newSize The amount of camera zoom. Sets size.\r\n         * @param ortho Whether the camera focus is in orthographic mode (true) or perspective mode (false).\r\n         * @param instant Apply the movement immediately (true) or animate the transition (false).\r\n         */\r\n        LookAt(point: Vector3, direction: Quaternion, newSize: number, ortho: boolean): void\r\n        /** Moves the Scene view to focus on a target.\r\n         * @param point The position in world space to frame.\r\n         * @param direction The direction that the Scene view should view the target point from.\r\n         * @param newSize The amount of camera zoom. Sets size.\r\n         * @param ortho Whether the camera focus is in orthographic mode (true) or perspective mode (false).\r\n         * @param instant Apply the movement immediately (true) or animate the transition (false).\r\n         */\r\n        LookAt(point: Vector3, direction: Quaternion, newSize: number): void\r\n        /** Moves the Scene view to focus on a target.\r\n         * @param point The position in world space to frame.\r\n         * @param direction The direction that the Scene view should view the target point from.\r\n         * @param newSize The amount of camera zoom. Sets size.\r\n         * @param ortho Whether the camera focus is in orthographic mode (true) or perspective mode (false).\r\n         * @param instant Apply the movement immediately (true) or animate the transition (false).\r\n         */\r\n        LookAt(point: Vector3, direction: Quaternion): void\r\n        /** Moves the Scene view to focus on a target.\r\n         * @param point The position in world space to frame.\r\n         * @param direction The direction that the Scene view should view the target point from.\r\n         * @param newSize The amount of camera zoom. Sets size.\r\n         * @param ortho Whether the camera focus is in orthographic mode (true) or perspective mode (false).\r\n         * @param instant Apply the movement immediately (true) or animate the transition (false).\r\n         */\r\n        LookAt(point: Vector3): void\r\n        /** .LookAt without animating the scene movement.\r\n         * @param point The position in world space to frame.\r\n         * @param direction The direction from which the Scene view should view the point.\r\n         * @param newSize The amount of camera zoom. Sets size.\r\n         */\r\n        LookAtDirect(point: Vector3, direction: Quaternion, newSize: number): void\r\n        /** .LookAt without animating the scene movement.\r\n         * @param point The position in world space to frame.\r\n         * @param direction The direction from which the Scene view should view the point.\r\n         * @param newSize The amount of camera zoom. Sets size.\r\n         */\r\n        LookAtDirect(point: Vector3, direction: Quaternion): void\r\n        /** Moves the Scene view to frame a transform.\r\n         * @param t The transform to frame in the Scene view.\r\n         */\r\n        AlignViewToObject(t: Transform): void\r\n        AlignWithView(): void\r\n        /** Transforms all selected object to the scene pivot.\r\n         * @param target A transform to place at the scene pivot.\r\n         */\r\n        MoveToView(target: Transform): void\r\n        MoveToView(): void\r\n        FrameSelected(lockView: boolean, instant: boolean): boolean\r\n        /** Frame the object selection in the Scene view.\r\n         * @param lockView Whether the view should be locked to the selection.\r\n         * @returns Returns true if the current selection fits in the Scene view. Returns false otherwise. \r\n         */\r\n        FrameSelected(lockView: boolean): boolean\r\n        FrameSelected(): boolean\r\n        Frame(bounds: Bounds, instant: boolean): boolean\r\n        static FrameLastActiveSceneView(): boolean\r\n        static FrameLastActiveSceneViewWithLock(): boolean\r\n        static GetAllSceneCameras(): Array<Camera>\r\n        static RepaintAll(): void\r\n        /** Add a custom camera mode to the Scene view camera mode list.\r\n         * @param name The name for the new mode.\r\n         * @param section The section in which the new mode will be added. This can be an existing or new section.\r\n         * @returns A CameraMode with the provided name and section. \r\n         */\r\n        static AddCameraMode(name: string, section: string): SceneView.CameraMode\r\n        static ClearUserDefinedCameraModes(): void\r\n        /** Gets the built-in CameraMode that matches the specified DrawCameraMode.\r\n         * @param mode The DrawCameraMode to match.\r\n         * @returns Returns a built-in CameraMode. \r\n         */\r\n        static GetBuiltinCameraMode(mode: DrawCameraMode): SceneView.CameraMode\r\n        protected constructor()\r\n        /** The SceneView that was most recently in focus.\r\n         */\r\n        static readonly lastActiveSceneView: SceneView\r\n        /** The SceneView that is being drawn.\r\n         */\r\n        static readonly currentDrawingSceneView: SceneView\r\n        /** Gets the Color of selected outline.\r\n         */\r\n        static readonly selectedOutlineColor: Color\r\n        /** Sets the visibility of all Gizmos in the Scene view.\r\n         */\r\n        drawGizmos: boolean\r\n        /** Whether lighting is enabled or disabled in the Scene view.\r\n         */\r\n        sceneLighting: boolean\r\n        /** Whether the SceneView is in 2D mode.\r\n         */\r\n        in2DMode: boolean\r\n        /** Whether the Scene view camera can be rotated.\r\n         */\r\n        isRotationLocked: boolean\r\n        /** Enables or disables Scene view audio effects.\r\n         */\r\n        audioPlay: boolean\r\n        /** The current DrawCameraMode for the Scene view camera.\r\n         */\r\n        cameraMode: SceneView.CameraMode\r\n        /** Whether the albedo is black for materials with an average specular color above 0.45.\r\n         */\r\n        validateTrueMetals: boolean\r\n        /** Use SceneViewState to set the debug options for the Scene view.\r\n         */\r\n        sceneViewState: SceneView.SceneViewState\r\n        /** Gets or sets whether to enable the grid for an instance of the SceneView.\r\n         */\r\n        showGrid: boolean\r\n        /** Use CameraSettings to set the properties for the SceneView Camera.\r\n         */\r\n        cameraSettings: SceneView.CameraSettings\r\n        /** When the Scene view is in 2D mode, this property contains the last camera rotation.\r\n         */\r\n        lastSceneViewRotation: Quaternion\r\n        /** The distance from camera to pivot.\r\n         */\r\n        readonly cameraDistance: number\r\n        /** The list of all open Scene view windows.\r\n         */\r\n        static readonly sceneViews: any\r\n        /** The Camera that is rendering this SceneView.\r\n         */\r\n        readonly camera: Camera\r\n        /** The center point, or pivot, of the Scene view.\r\n         */\r\n        pivot: Vector3\r\n        /** The direction of the camera to the pivot of the SceneView.\r\n         */\r\n        rotation: Quaternion\r\n        /** The size of the Scene view measured diagonally.\r\n         */\r\n        size: number\r\n        /** Whether the Scene view camera is set to orthographic mode.\r\n         */\r\n        orthographic: boolean\r\n        onValidateCameraMode(op: \"add\" | \"remove\", fn: (arg: SceneView.CameraMode) => boolean): void\r\n        onCameraModeChanged(op: \"add\" | \"remove\", fn: (obj: SceneView.CameraMode) => void): void\r\n        gridVisibilityChanged(op: \"add\" | \"remove\", fn: (obj: boolean) => void): void\r\n        static beforeSceneGui(op: \"add\" | \"remove\", fn: (obj: SceneView) => void): void\r\n        static duringSceneGui(op: \"add\" | \"remove\", fn: (obj: SceneView) => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array, ValueType } from \"System\";\r\n    import { Object as Object1, Vector2 } from \"UnityEngine\";\r\n    /** Various utilities for mesh manipulation.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class MeshUtility extends Object {\r\n        /** Optimizes the Mesh data to improve rendering performance.\r\n         */\r\n        static Optimize(mesh: any): void\r\n        /** Change the mesh compression setting for a mesh.\r\n         * @param mesh The mesh to set the compression mode for.\r\n         * @param compression The compression mode to set.\r\n         */\r\n        static SetMeshCompression(mesh: any, compression: ModelImporterMeshCompression): void\r\n        /** Returns the mesh compression setting for a Mesh.\r\n         * @param mesh The mesh to get information on.\r\n         */\r\n        static GetMeshCompression(mesh: any): ModelImporterMeshCompression\r\n        /** Will insert per-triangle uv2 in mesh and handle vertex splitting etc.\r\n         */\r\n        static SetPerTriangleUV2(src: any, triUV: Array<Vector2>): void\r\n        /** Gets a snapshot of Mesh data for read-only access in the Unity Editor.\r\n         * @param mesh The input mesh.\r\n         * @param meshes The input meshes.\r\n         * @returns Returns a read-only snapshot of Mesh data. See Mesh.MeshDataArray and Mesh.MeshData. \r\n         */\r\n        static AcquireReadOnlyMeshData(mesh: any): any\r\n        /** Gets a snapshot of Mesh data for read-only access in the Unity Editor.\r\n         * @param mesh The input mesh.\r\n         * @param meshes The input meshes.\r\n         * @returns Returns a read-only snapshot of Mesh data. See Mesh.MeshDataArray and Mesh.MeshData. \r\n         */\r\n        static AcquireReadOnlyMeshData(meshes: Array<any>): any\r\n        static AcquireReadOnlyMeshData(meshes: any): any\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array, ValueType } from \"System\";\r\n    import { GameObject, Object as Object1, Component, Texture2D, Transform } from \"UnityEngine\";\r\n    /** Utility class for any Prefab related operations.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class PrefabUtility extends Object {\r\n        /** This function will give you the PrefabInstance object for the outermost Prefab instance the provided object is part of.\r\n         * @param instanceComponentOrGameObject An object from the Prefab instance.\r\n         * @returns The Prefab instance handle. \r\n         */\r\n        static GetPrefabInstanceHandle(instanceComponentOrGameObject: Object1): Object1\r\n        /** Extract all modifications that are applied to the Prefab instance compared to the parent Prefab.\r\n         */\r\n        static GetPropertyModifications(targetPrefab: Object1): Array<PropertyModification>\r\n        /** Assigns all modifications that are applied to the Prefab instance compared to the parent Prefab.\r\n         */\r\n        static SetPropertyModifications(targetPrefab: Object1, modifications: Array<PropertyModification>): void\r\n        /** Returns true if the given Prefab instance has any overrides.\r\n         * @param instanceRoot The root GameObject of the Prefab instance to check.\r\n         * @param includeDefaultOverrides Set to true to consider default overrides as overrides too.\r\n         * @returns Returns true if there are any overrides. \r\n         */\r\n        static HasPrefabInstanceAnyOverrides(instanceRoot: GameObject, includeDefaultOverrides: boolean): boolean\r\n        /** Instantiate an asset that is referenced by a Prefab and use it on the Prefab instance.\r\n         */\r\n        static InstantiateAttachedAsset(targetObject: Object1): Object1\r\n        /** Causes modifications made to the Prefab instance to be recorded.\r\n         * @param targetObject Object to process.\r\n         */\r\n        static RecordPrefabInstancePropertyModifications(targetObject: Object1): void\r\n        /** This function will unpack the given Prefab instance using the behaviour specified by unpackMode.\r\n         * @param instanceRoot Root GameObject of the Prefab instance.\r\n         * @param unpackMode The unpack mode to use.\r\n         * @returns Array of GameObjects representing roots of unpacked Prefab instances. \r\n         */\r\n        static UnpackPrefabInstanceAndReturnNewOutermostRoots(instanceRoot: GameObject, unpackMode: PrefabUnpackMode): Array<GameObject>\r\n        /** Loads a Prefab Asset at a given path into a given preview Scene and returns the root GameObject of the Prefab.\r\n         * @param scene The Scene to load the contents into.\r\n         * @param prefabPath The path of the Prefab Asset to load the contents of.\r\n         */\r\n        static LoadPrefabContentsIntoPreviewScene(prefabPath: string, scene: any): void\r\n        /** Is this component added to a Prefab instance as an override?\r\n         * @param component The component to check.\r\n         * @returns True if the component is an added component. \r\n         */\r\n        static IsAddedComponentOverride(component: Object1): boolean\r\n        /** Returns true if the given object is part of any kind of Prefab.\r\n         * @param componentOrGameObject The object to check. Must be a component or GameObject.\r\n         * @returns True if the object s part of a Prefab. \r\n         */\r\n        static IsPartOfAnyPrefab(componentOrGameObject: Object1): boolean\r\n        /** Returns true if the given object is part of a Prefab Asset.\r\n         * @param componentOrGameObject The object to check. Must be a component or GameObject.\r\n         * @returns True is the object is part of a Prefab Asset. \r\n         */\r\n        static IsPartOfPrefabAsset(componentOrGameObject: Object1): boolean\r\n        /** Returns true if the given object is part of a Prefab instance.\r\n         * @param componentOrGameObject The object to check. Must be a component or GameObject.\r\n         * @returns True if the object is part of a Prefab instance. \r\n         */\r\n        static IsPartOfPrefabInstance(componentOrGameObject: Object1): boolean\r\n        /** Returns true if the given object is part of a Prefab instance and not part of an asset.\r\n         * @param componentOrGameObject The object to check. Must be a component or GameObject.\r\n         * @returns True if the object is part of a Prefab instance that's not inside a Prefab Asset. \r\n         */\r\n        static IsPartOfNonAssetPrefabInstance(componentOrGameObject: Object1): boolean\r\n        /** Returns true if the given object is part of a regular Prefab instance or Prefab Asset.\r\n         * @param componentOrGameObject The object to check. Must be a component or GameObject.\r\n         * @returns True if the given object is part of a regular Prefab instance or Prefab Asset. \r\n         */\r\n        static IsPartOfRegularPrefab(componentOrGameObject: Object1): boolean\r\n        /** Returns true if the given object is part of a Model Prefab Asset or Model Prefab instance.\r\n         * @param componentOrGameObject The object to check. Must be a component or GameObject.\r\n         * @returns True if the given object is part of a Model Prefab. \r\n         */\r\n        static IsPartOfModelPrefab(componentOrGameObject: Object1): boolean\r\n        /** Returns true if the given object is part of a Prefab Variant Asset or Prefab Variant instance.\r\n         * @param componentOrGameObject The object to check. Must be a component or GameObject.\r\n         * @returns True if the given object is part of a Prefab Variant. \r\n         */\r\n        static IsPartOfVariantPrefab(componentOrGameObject: Object1): boolean\r\n        /** Is this object part of a Prefab that cannot be edited?\r\n         * @param componentOrGameObject The object to check. Must be a component or GameObject.\r\n         * @returns True if the object is part of a Prefab that cannot be edited. \r\n         */\r\n        static IsPartOfImmutablePrefab(componentOrGameObject: Object1): boolean\r\n        /** Returns true if the given object is part of an instance where the PrefabInstance object is missing but the given object has a valid corresponding object.\r\n         * @param componentOrGameObject The object to check. Must be a GameObject or component.\r\n         * @returns True if the instance is disconnected. \r\n         */\r\n        static IsDisconnectedFromPrefabAsset(componentOrGameObject: Object1): boolean\r\n        /** Returns true if the given object is part of a Prefab instance but the source asset is missing.\r\n         * @param instanceComponentOrGameObject The object to check. Must be a component or GameObject.\r\n         * @returns True if the given object is part of a Prefab instance but the source asset is missing. \r\n         */\r\n        static IsPrefabAssetMissing(instanceComponentOrGameObject: Object1): boolean\r\n        /** Returns the GameObject that is the root of the outermost Prefab instance the object is part of.\r\n         * @param componentOrGameObject The object to check. Must be a component or GameObject.\r\n         * @returns The outermost Prefab instance root. \r\n         */\r\n        static GetOutermostPrefabInstanceRoot(componentOrGameObject: Object1): GameObject\r\n        /** Return the GameObject that is the root of the nearest Prefab instance the object is part of.\r\n         * @param componentOrGameObject The object to check. Must be a component or GameObject.\r\n         * @returns The nearest Prefab instance root. \r\n         */\r\n        static GetNearestPrefabInstanceRoot(componentOrGameObject: Object1): GameObject\r\n        /** Returns true if the given modification is considered a PrefabUtility.IsDefaultOverride|default override.\r\n         * @param modification The modification for the property in question.\r\n         * @returns True if the property is a default override. \r\n         */\r\n        static IsDefaultOverride(modification: PropertyModification): boolean\r\n        /** Reverts all overrides on a Prefab instance.\r\n         * @param instanceRoot The root of the Prefab instance.\r\n         * @param action The interaction mode for this action.\r\n         */\r\n        static RevertPrefabInstance(instanceRoot: GameObject, action: InteractionMode): void\r\n        /** Applies all overrides on a Prefab instance to its Prefab Asset.\r\n         * @param instanceRoot The root of the given Prefab instance.\r\n         * @param action The interaction mode for this action.\r\n         */\r\n        static ApplyPrefabInstance(instanceRoot: GameObject, action: InteractionMode): void\r\n        /** Applies a single overridden property on a Prefab instance to the Prefab Asset at the given asset path.\r\n         * @param instanceProperty The SerializedProperty representing the property to apply.\r\n         * @param assetPath The path of the Prefab Asset to apply to.\r\n         * @param action The interaction mode for this action.\r\n         */\r\n        static ApplyPropertyOverride(instanceProperty: SerializedProperty, assetPath: string, action: InteractionMode): void\r\n        /** Revert a single property override on a Prefab instance.\r\n         * @param action The interaction mode for this action.\r\n         * @param instanceProperty The SerializedProperty representing the property to revert.\r\n         */\r\n        static RevertPropertyOverride(instanceProperty: SerializedProperty, action: InteractionMode): void\r\n        /** Applies all overridden properties on a Prefab instance component or GameObject to the Prefab Asset at the given asset path.\r\n         * @param instanceComponentOrGameObject The object on the Prefab instance to apply.\r\n         * @param assetPath The path of the Prefab Asset to apply to.\r\n         * @param action The interaction mode for this action.\r\n         */\r\n        static ApplyObjectOverride(instanceComponentOrGameObject: Object1, assetPath: string, action: InteractionMode): void\r\n        /** Reverts all overridden properties on a Prefab instance component or GameObject.\r\n         * @param action The interaction mode for this action.\r\n         * @param instanceComponentOrGameObject The object on the Prefab instance to revert.\r\n         */\r\n        static RevertObjectOverride(instanceComponentOrGameObject: Object1, action: InteractionMode): void\r\n        /** Applies the added component to the Prefab Asset at the given asset path.\r\n         * @param action The interaction mode for this action.\r\n         * @param assetPath The path of the Prefab Asset to apply to.\r\n         * @param component The added component on the Prefab instance to apply.\r\n         */\r\n        static ApplyAddedComponent(component: Component, assetPath: string, action: InteractionMode): void\r\n        /** Removes this added component on a Prefab instance.\r\n         * @param component The added component on the Prefab instance to revert.\r\n         * @param action The interaction mode for this action.\r\n         */\r\n        static RevertAddedComponent(component: Component, action: InteractionMode): void\r\n        /** Removes the component from the Prefab Asset which has the component on it.\r\n         * @param instanceGameObject The GameObject on the Prefab instance which the component has been removed from.\r\n         * @param assetComponent The component on the Prefab Asset corresponding to the removed component on the instance.\r\n         * @param action The interaction mode for this action.\r\n         */\r\n        static ApplyRemovedComponent(instanceGameObject: GameObject, assetComponent: Component, action: InteractionMode): void\r\n        /** Adds this removed component back on the Prefab instance.\r\n         * @param assetComponent The removed component on the Prefab instance to revert.\r\n         * @param action The interaction mode for this action.\r\n         * @param instanceGameObject The GameObject on the Prefab instance which the component has been removed from.\r\n         */\r\n        static RevertRemovedComponent(instanceGameObject: GameObject, assetComponent: Component, action: InteractionMode): void\r\n        /** Applies the added GameObject to the Prefab Asset at the given asset path.\r\n         * @param gameObject The added GameObject on the Prefab instance to apply.\r\n         * @param assetPath The path of the Prefab Asset to apply to.\r\n         * @param action The interaction mode for this action.\r\n         */\r\n        static ApplyAddedGameObject(gameObject: GameObject, assetPath: string, action: InteractionMode): void\r\n        /** Removes this added GameObject from a Prefab instance.\r\n         * @param action The interaction mode for this action.\r\n         * @param gameObject The added GameObject on the Prefab instance to revert.\r\n         */\r\n        static RevertAddedGameObject(gameObject: GameObject, action: InteractionMode): void\r\n        /** Returns a list of objects with information about object overrides on the Prefab instance.\r\n         * @param prefabInstance The Prefab instance to get information about.\r\n         * @param includeDefaultOverrides If true, components will also be included even if they only contain overrides that are PrefabUtility.IsDefaultOverride|default overrides. False by default.\r\n         * @returns List of objects with information about object overrides. \r\n         */\r\n        static GetObjectOverrides(prefabInstance: GameObject, includeDefaultOverrides: boolean): any\r\n        /** Returns a list of PrefabUtility.AddedComponent objects which contain information about added component overrides on the Prefab instance.\r\n         * @param prefabInstance The Prefab instance to get information about.\r\n         * @returns List of objects with information about added components. \r\n         */\r\n        static GetAddedComponents(prefabInstance: GameObject): any\r\n        /** Returns a list of objects with information about removed component overrides on the Prefab instance.\r\n         * @param prefabInstance The Prefab instance to get information about.\r\n         * @returns List of objects with information about removed components. \r\n         */\r\n        static GetRemovedComponents(prefabInstance: GameObject): any\r\n        /** Returns a list of PrefabUtility.AddedGameObject objects which contain information about added GameObjects on the Prefab instance.\r\n         * @param prefabInstance The Prefab instance to get information about.\r\n         * @returns List of objects with information about added GameObjects. \r\n         */\r\n        static GetAddedGameObjects(prefabInstance: GameObject): any\r\n        /** Is the GameObject the root of any Prefab instance?\r\n         * @param gameObject The GameObject to check.\r\n         * @returns True if the GameObject is the root GameObject of any Prefab instance. \r\n         */\r\n        static IsAnyPrefabInstanceRoot(gameObject: GameObject): boolean\r\n        /** Is the GameObject the root of a Prefab instance, excluding nested Prefabs?\r\n         * @param gameObject The GameObject to check.\r\n         * @returns True if the GameObject is an outermost Prefab instance root. \r\n         */\r\n        static IsOutermostPrefabInstanceRoot(gameObject: GameObject): boolean\r\n        /** Returns the asset path of the nearest Prefab instance root the specified object is part of.\r\n         * @param instanceComponentOrGameObject An object in the Prefab instance to get the asset path of.\r\n         * @returns The asset path. \r\n         */\r\n        static GetPrefabAssetPathOfNearestInstanceRoot(instanceComponentOrGameObject: Object1): string\r\n        /** Returns the icon for the given GameObject.\r\n         * @param gameObject The GameObject to get an icon for.\r\n         * @returns The icon for the GameObject. \r\n         */\r\n        static GetIconForGameObject(gameObject: GameObject): Texture2D\r\n        /** Use this function to save the version of an existing Prefab Asset that exists in memory back to disk.\r\n         * @param asset Any GameObject that is part of the Prefab Asset to save.\r\n         * @param savedSuccessfully The result of the save action, either successful or unsuccessful. Use this together with the console log to get more insight into the save process.\r\n         * @returns The root GameObject of the saved Prefab Asset. \r\n         */\r\n        static SavePrefabAsset(asset: GameObject, savedSuccessfully: jsb.Out<boolean>): GameObject\r\n        /** Use this function to save the version of an existing Prefab Asset that exists in memory back to disk.\r\n         * @param asset Any GameObject that is part of the Prefab Asset to save.\r\n         * @param savedSuccessfully The result of the save action, either successful or unsuccessful. Use this together with the console log to get more insight into the save process.\r\n         * @returns The root GameObject of the saved Prefab Asset. \r\n         */\r\n        static SavePrefabAsset(asset: GameObject): GameObject\r\n        /** Use this function to create a Prefab Asset at the given path from the given GameObject, including any childen in the Scene without modifying the input objects.\r\n         * @param instanceRoot The GameObject to save as a Prefab Asset.\r\n         * @param assetPath The path to save the Prefab at.\r\n         * @param success The result of the save action, either successful or unsuccessful. Use this together with the console log to get more insight into the save process.\r\n         * @returns The root GameObject of the saved Prefab Asset, if available. \r\n         */\r\n        static SaveAsPrefabAsset(instanceRoot: GameObject, assetPath: string, success: jsb.Out<boolean>): GameObject\r\n        /** Use this function to create a Prefab Asset at the given path from the given GameObject, including any childen in the Scene without modifying the input objects.\r\n         * @param instanceRoot The GameObject to save as a Prefab Asset.\r\n         * @param assetPath The path to save the Prefab at.\r\n         * @param success The result of the save action, either successful or unsuccessful. Use this together with the console log to get more insight into the save process.\r\n         * @returns The root GameObject of the saved Prefab Asset, if available. \r\n         */\r\n        static SaveAsPrefabAsset(instanceRoot: GameObject, assetPath: string): GameObject\r\n        /** Use this function to create a Prefab Asset at the given path from the given GameObject including any children in the Scene and at the same time make the given GameObject into an instance of the new Prefab.\r\n         * @param instanceRoot The GameObject to save as a Prefab and make into a Prefab instance.\r\n         * @param assetPath The path to save the Prefab at.\r\n         * @param action The interaction mode to use for this action.\r\n         * @param success The result of the save action, either successful or unsuccessful. Use this together with the console log to get more insight into the save process.\r\n         * @returns The root GameObject of the saved Prefab Asset, if available. \r\n         */\r\n        static SaveAsPrefabAssetAndConnect(instanceRoot: GameObject, assetPath: string, action: InteractionMode, success: jsb.Out<boolean>): GameObject\r\n        /** Use this function to create a Prefab Asset at the given path from the given GameObject including any children in the Scene and at the same time make the given GameObject into an instance of the new Prefab.\r\n         * @param instanceRoot The GameObject to save as a Prefab and make into a Prefab instance.\r\n         * @param assetPath The path to save the Prefab at.\r\n         * @param action The interaction mode to use for this action.\r\n         * @param success The result of the save action, either successful or unsuccessful. Use this together with the console log to get more insight into the save process.\r\n         * @returns The root GameObject of the saved Prefab Asset, if available. \r\n         */\r\n        static SaveAsPrefabAssetAndConnect(instanceRoot: GameObject, assetPath: string, action: InteractionMode): GameObject\r\n        /** Instantiates the given Prefab in a given Scene.\r\n         * @param target Prefab Asset to instantiate.\r\n         * @param destinationScene Scene to instantiate the Prefab in.\r\n         * @returns The GameObject at the root of the Prefab. \r\n         */\r\n        static InstantiatePrefab(assetComponentOrGameObject: Object1, destinationScene: any): Object1\r\n        static InstantiatePrefab(assetComponentOrGameObject: Object1, parent: Transform): Object1\r\n        /** Instantiates the given Prefab in a given Scene.\r\n         * @param target Prefab Asset to instantiate.\r\n         * @param destinationScene Scene to instantiate the Prefab in.\r\n         * @returns The GameObject at the root of the Prefab. \r\n         */\r\n        static InstantiatePrefab(assetComponentOrGameObject: Object1): Object1\r\n        /** Is this GameObject added as a child to a Prefab instance as an override?\r\n         * @param gameObject The GameObject to check.\r\n         * @returns True if the GameObject is an added GameObject. \r\n         */\r\n        static IsAddedGameObjectOverride(gameObject: GameObject): boolean\r\n        /** Unpacks a given Prefab instance so that it is replaced with the contents of the Prefab Asset while retaining all override values.\r\n         * @param instanceRoot The root of the Prefab instance to unpack.\r\n         * @param unpackMode Whether to unpack the outermost root or unpack completely.\r\n         * @param action The interaction mode to use for this action.\r\n         */\r\n        static UnpackPrefabInstance(instanceRoot: GameObject, unpackMode: PrefabUnpackMode, action: InteractionMode): void\r\n        /** Is this object part of a Prefab that cannot be applied to?\r\n         * @param gameObjectOrComponent The object to check. Must be a component or GameObject.\r\n         * @returns True if the object is part of a Prefab that cannot be applied to. \r\n         */\r\n        static IsPartOfPrefabThatCanBeAppliedTo(gameObjectOrComponent: Object1): boolean\r\n        /** Enum value with status about whether a Prefab instance is properly connected to its asset.\r\n         * @param componentOrGameObject An object that is part of a Prefab instance.\r\n         * @returns The status of the Prefab instance. \r\n         */\r\n        static GetPrefabInstanceStatus(componentOrGameObject: Object1): PrefabInstanceStatus\r\n        /** Enum value indicating the type of Prefab Asset, such as Regular Prefab, Model Prefab and Prefab Variant.\r\n         * @param componentOrGameObject An object that is part of a Prefab Asset or Prefab instance.\r\n         * @returns The type of Prefab. \r\n         */\r\n        static GetPrefabAssetType(componentOrGameObject: Object1): PrefabAssetType\r\n        /** Loads a Prefab Asset at a given path into an isolated Scene and returns the root GameObject of the Prefab.\r\n         * @param assetPath The path of the Prefab Asset to load the contents of.\r\n         * @returns The root of the loaded contents. \r\n         */\r\n        static LoadPrefabContents(assetPath: string): GameObject\r\n        /** Releases the content from a Prefab previously loaded with LoadPrefabContents from memory.\r\n         * @param contentsRoot The root of the loaded Prefab contents.\r\n         */\r\n        static UnloadPrefabContents(contentsRoot: GameObject): void\r\n        protected constructor()\r\n        static prefabInstanceUpdated(op: \"get\"): (instance: GameObject) => void\r\n        static prefabInstanceUpdated(op: \"add\" | \"remove\" | \"set\", fn?: (instance: GameObject) => void): void\r\n        static prefabInstanceUpdated(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (instance: GameObject) => void): (instance: GameObject) => void | void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Lets you do move, copy, delete operations over files or directories.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class FileUtil extends Object {\r\n        /** Deletes a file or a directory given a path.\r\n         */\r\n        static DeleteFileOrDirectory(path: string): boolean\r\n        /** Copies a file or a directory.\r\n         */\r\n        static CopyFileOrDirectory(source: string, dest: string): void\r\n        /** Copies the file or directory.\r\n         */\r\n        static CopyFileOrDirectoryFollowSymlinks(source: string, dest: string): void\r\n        /** Moves a file or a directory from a given path to another path.\r\n         */\r\n        static MoveFileOrDirectory(source: string, dest: string): void\r\n        static GetUniqueTempPathInProject(): string\r\n        static GetProjectRelativePath(path: string): string\r\n        /** Replaces a file.\r\n         */\r\n        static ReplaceFile(src: string, dst: string): void\r\n        /** Replaces a directory.\r\n         */\r\n        static ReplaceDirectory(src: string, dst: string): void\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build.Reporting\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    import { Array } from \"System\";\r\n    /** The BuildReport API gives you information about the Unity build process.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class BuildReport extends Object {\r\n        protected constructor()\r\n        /** An array of all the files output by the build process.\r\n         */\r\n        readonly files: Array<BuildFile>\r\n        /** An array of all the BuildSteps that took place during the build process.\r\n         */\r\n        readonly steps: Array<BuildStep>\r\n        /** A BuildSummary containing overall statistics and data about the build process.\r\n         */\r\n        readonly summary: BuildSummary\r\n        /** The StrippingInfo object for the build.\r\n         */\r\n        readonly strippingInfo: StrippingInfo\r\n        /** An array of all the PackedAssets generated by the build process.\r\n         */\r\n        readonly packedAssets: Array<PackedAssets>\r\n        /** An optional array of ScenesUsingAssets generated by the build process if BuildOptions.DetailedBuildReport was used during the build.\r\n         */\r\n        readonly scenesUsingAssets: Array<ScenesUsingAssets>\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Array } from \"System\";\r\n    /** Manifest for all the AssetBundles in the build.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AssetBundleManifest extends Object {\r\n        GetAllAssetBundles(): Array<string>\r\n        GetAllAssetBundlesWithVariant(): Array<string>\r\n        /** Get the hash for the given AssetBundle.\r\n         * @param assetBundleName Name of the asset bundle.\r\n         * @returns The 128-bit hash for the asset bundle. \r\n         */\r\n        GetAssetBundleHash(assetBundleName: string): Hash128\r\n        /** Get the direct dependent AssetBundles for the given AssetBundle.\r\n         * @param assetBundleName Name of the asset bundle.\r\n         * @returns Array of asset bundle names this asset bundle depends on. \r\n         */\r\n        GetDirectDependencies(assetBundleName: string): Array<string>\r\n        /** Get all the dependent AssetBundles for the given AssetBundle.\r\n         * @param assetBundleName Name of the asset bundle.\r\n         */\r\n        GetAllDependencies(assetBundleName: string): Array<string>\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { BuildReport } from \"UnityEditor.Build.Reporting\";\r\n    import { AssetBundleManifest, Hash128 } from \"UnityEngine\";\r\n    /** Lets you programmatically build players or AssetBundles which can be loaded from the web.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class BuildPipeline extends Object {\r\n        static GetBuildTargetGroup(platform: BuildTarget): BuildTargetGroup\r\n        /** Given a BuildTarget will return the well known string representation for the build target platform.\r\n         * @param targetPlatform An instance of the BuildTarget enum.\r\n         * @returns Target platform name represented by the passed in BuildTarget. \r\n         */\r\n        static GetBuildTargetName(targetPlatform: BuildTarget): string\r\n        /** SetAssetBundleEncryptKey.\r\n         */\r\n        static SetAssetBundleEncryptKey(password: string): void\r\n        /** Checks if Unity can append the build.\r\n         * @param target The BuildTarget to build.\r\n         * @param location The path where Unity builds the application.\r\n         * @returns Returns a UnityEditor.CanAppendBuild enum that indicates whether Unity can append the build. \r\n         */\r\n        static BuildCanBeAppended(target: BuildTarget, location: string): CanAppendBuild\r\n        /** Builds a player. These overloads are still supported, but will be replaced. Please use BuildPlayer (BuildPlayerOptions buildPlayerOptions)  instead.\r\n         * @param scenes The Scenes to include in the build. If empty, the build only includes the currently open Scene. Paths are relative to the project folder (AssetsMyLevelsMyScene.unity).\r\n         * @param locationPathName The path where the application will be built.\r\n         * @param target The BuildTarget to build.\r\n         * @param options Additional BuildOptions, like whether to run the built player.\r\n         * @returns An error message if an error occurred. \r\n         */\r\n        static BuildPlayer(levels: Array<EditorBuildSettingsScene>, locationPathName: string, target: BuildTarget, options: BuildOptions): BuildReport\r\n        /** Builds a player. These overloads are still supported, but will be replaced. Please use BuildPlayer (BuildPlayerOptions buildPlayerOptions)  instead.\r\n         * @param scenes The Scenes to include in the build. If empty, the build only includes the currently open Scene. Paths are relative to the project folder (AssetsMyLevelsMyScene.unity).\r\n         * @param locationPathName The path where the application will be built.\r\n         * @param target The BuildTarget to build.\r\n         * @param options Additional BuildOptions, like whether to run the built player.\r\n         * @returns An error message if an error occurred. \r\n         */\r\n        static BuildPlayer(levels: Array<string>, locationPathName: string, target: BuildTarget, options: BuildOptions): BuildReport\r\n        /** Builds a player.\r\n         * @param buildPlayerOptions Provide various options to control the behavior of BuildPipeline.BuildPlayer.\r\n         * @returns A BuildReport giving build process information. \r\n         */\r\n        static BuildPlayer(buildPlayerOptions: BuildPlayerOptions): BuildReport\r\n        /** Writes out a \"boot.config\" file that contains configuration information for the very early stages of engine startup.\r\n         * @param outputFile The location to write the file to.\r\n         * @param target The platform to target for this build.\r\n         * @param options Options for this build.\r\n         */\r\n        static WriteBootConfig(outputFile: string, target: BuildTarget, options: BuildOptions): void\r\n        /** Build AssetBundles from a building map.\r\n         * @param outputPath Output path for the AssetBundles.\r\n         * @param builds AssetBundle building map.\r\n         * @param assetBundleOptions AssetBundle building options.\r\n         * @param targetPlatform Target build platform.\r\n         * @returns The manifest listing all AssetBundles included in this build. \r\n         */\r\n        static BuildAssetBundles(outputPath: string, builds: Array<AssetBundleBuild>, assetBundleOptions: BuildAssetBundleOptions, targetPlatform: BuildTarget): AssetBundleManifest\r\n        /** Build all AssetBundles specified in the editor.\r\n         * @param outputPath Output path for the AssetBundles.\r\n         * @param assetBundleOptions AssetBundle building options.\r\n         * @param targetPlatform Chosen target build platform.\r\n         * @returns The manifest listing all AssetBundles included in this build. \r\n         */\r\n        static BuildAssetBundles(outputPath: string, assetBundleOptions: BuildAssetBundleOptions, targetPlatform: BuildTarget): AssetBundleManifest\r\n        /** Extract the crc checksum for the given AssetBundle.\r\n         */\r\n        static GetCRCForAssetBundle(targetPath: string, crc: jsb.Out<number>): boolean\r\n        /** Extract the hash for the given AssetBundle.\r\n         */\r\n        static GetHashForAssetBundle(targetPath: string, hash: jsb.Out<Hash128>): boolean\r\n        /** Returns true if the specified build target is currently available in the Editor.\r\n         * @param buildTargetGroup build target group\r\n         * @param target build target\r\n         */\r\n        static IsBuildTargetSupported(buildTargetGroup: BuildTargetGroup, target: BuildTarget): boolean\r\n        /** Returns the path of a player directory. For ex., Editor\\Data\\PlaybackEngines\\AndroidPlayer.\n\nIn some cases the player directory path can be affected by BuildOptions.Development.\r\n         * @param target Build target.\r\n         * @param options Build options.\r\n         * @param buildTargetGroup Build target group.\r\n         */\r\n        static GetPlaybackEngineDirectory(buildTargetGroup: BuildTargetGroup, target: BuildTarget, options: BuildOptions): string\r\n        /** Returns the path of a player directory. For ex., Editor\\Data\\PlaybackEngines\\AndroidPlayer.\n\nIn some cases the player directory path can be affected by BuildOptions.Development.\r\n         * @param target Build target.\r\n         * @param options Build options.\r\n         * @param buildTargetGroup Build target group.\r\n         */\r\n        static GetPlaybackEngineDirectory(target: BuildTarget, options: BuildOptions): string\r\n        /** Returns the mode currently used by players to initiate a connect to the host.\r\n         */\r\n        static GetPlayerConnectionInitiateMode(targetPlatform: BuildTarget, buildOptions: BuildOptions): PlayerConnectionInitiateMode\r\n        protected constructor()\r\n        /** Is a player currently being built?\r\n         */\r\n        static readonly isBuildingPlayer: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Object as Object1, Hash128, Texture } from \"UnityEngine\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    /** An Interface for accessing assets and performing operations on assets.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AssetDatabase extends Object {\r\n        static CanOpenForEdit(assetOrMetaFilePaths: Array<string>, outNotEditablePaths: any, statusQueryOptions: StatusQueryOptions): void\r\n        /** Query whether an Asset file can be opened for editing in version control and is not exclusively locked by another user or otherwise unavailable.\r\n         * @param assetObject Object representing the asset whose status you wish to query.\r\n         * @param assetOrMetaFilePath Path to the asset file or its .meta file on disk, relative to project folder.\r\n         * @param message Returns a reason for the asset not being available for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset is considered available for edit by the selected version control system. \r\n         */\r\n        static CanOpenForEdit(assetObject: Object1, message: jsb.Out<string>, statusOptions: StatusQueryOptions): boolean\r\n        /** Query whether an Asset file can be opened for editing in version control and is not exclusively locked by another user or otherwise unavailable.\r\n         * @param assetObject Object representing the asset whose status you wish to query.\r\n         * @param assetOrMetaFilePath Path to the asset file or its .meta file on disk, relative to project folder.\r\n         * @param message Returns a reason for the asset not being available for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset is considered available for edit by the selected version control system. \r\n         */\r\n        static CanOpenForEdit(assetOrMetaFilePath: string, message: jsb.Out<string>, statusOptions: StatusQueryOptions): boolean\r\n        /** Query whether an Asset file can be opened for editing in version control and is not exclusively locked by another user or otherwise unavailable.\r\n         * @param assetObject Object representing the asset whose status you wish to query.\r\n         * @param assetOrMetaFilePath Path to the asset file or its .meta file on disk, relative to project folder.\r\n         * @param message Returns a reason for the asset not being available for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset is considered available for edit by the selected version control system. \r\n         */\r\n        static CanOpenForEdit(assetObject: Object1, statusOptions: StatusQueryOptions): boolean\r\n        /** Query whether an Asset file can be opened for editing in version control and is not exclusively locked by another user or otherwise unavailable.\r\n         * @param assetObject Object representing the asset whose status you wish to query.\r\n         * @param assetOrMetaFilePath Path to the asset file or its .meta file on disk, relative to project folder.\r\n         * @param message Returns a reason for the asset not being available for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset is considered available for edit by the selected version control system. \r\n         */\r\n        static CanOpenForEdit(assetOrMetaFilePath: string, statusOptions: StatusQueryOptions): boolean\r\n        /** Query whether an Asset file can be opened for editing in version control and is not exclusively locked by another user or otherwise unavailable.\r\n         * @param assetObject Object representing the asset whose status you wish to query.\r\n         * @param assetOrMetaFilePath Path to the asset file or its .meta file on disk, relative to project folder.\r\n         * @param message Returns a reason for the asset not being available for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset is considered available for edit by the selected version control system. \r\n         */\r\n        static CanOpenForEdit(assetObject: Object1, message: jsb.Out<string>): boolean\r\n        /** Query whether an Asset file can be opened for editing in version control and is not exclusively locked by another user or otherwise unavailable.\r\n         * @param assetObject Object representing the asset whose status you wish to query.\r\n         * @param assetOrMetaFilePath Path to the asset file or its .meta file on disk, relative to project folder.\r\n         * @param message Returns a reason for the asset not being available for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset is considered available for edit by the selected version control system. \r\n         */\r\n        static CanOpenForEdit(assetOrMetaFilePath: string, message: jsb.Out<string>): boolean\r\n        /** Query whether an Asset file can be opened for editing in version control and is not exclusively locked by another user or otherwise unavailable.\r\n         * @param assetObject Object representing the asset whose status you wish to query.\r\n         * @param assetOrMetaFilePath Path to the asset file or its .meta file on disk, relative to project folder.\r\n         * @param message Returns a reason for the asset not being available for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset is considered available for edit by the selected version control system. \r\n         */\r\n        static CanOpenForEdit(assetObject: Object1): boolean\r\n        /** Query whether an Asset file can be opened for editing in version control and is not exclusively locked by another user or otherwise unavailable.\r\n         * @param assetObject Object representing the asset whose status you wish to query.\r\n         * @param assetOrMetaFilePath Path to the asset file or its .meta file on disk, relative to project folder.\r\n         * @param message Returns a reason for the asset not being available for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset is considered available for edit by the selected version control system. \r\n         */\r\n        static CanOpenForEdit(assetOrMetaFilePath: string): boolean\r\n        static IsOpenForEdit(assetOrMetaFilePaths: Array<string>, outNotEditablePaths: any, statusQueryOptions: StatusQueryOptions): void\r\n        /** Query whether an Asset file is open for editing in version control.\r\n         * @param assetObject Object representing the asset whose status you wish to query.\r\n         * @param assetOrMetaFilePath Path to the asset file or its .meta file on disk, relative to project folder.\r\n         * @param message Returns a reason for the asset not being open for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset is considered open for edit by the selected version control system. \r\n         */\r\n        static IsOpenForEdit(assetObject: Object1, message: jsb.Out<string>, statusOptions: StatusQueryOptions): boolean\r\n        /** Query whether an Asset file is open for editing in version control.\r\n         * @param assetObject Object representing the asset whose status you wish to query.\r\n         * @param assetOrMetaFilePath Path to the asset file or its .meta file on disk, relative to project folder.\r\n         * @param message Returns a reason for the asset not being open for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset is considered open for edit by the selected version control system. \r\n         */\r\n        static IsOpenForEdit(assetOrMetaFilePath: string, message: jsb.Out<string>, statusOptions: StatusQueryOptions): boolean\r\n        /** Query whether an Asset file is open for editing in version control.\r\n         * @param assetObject Object representing the asset whose status you wish to query.\r\n         * @param assetOrMetaFilePath Path to the asset file or its .meta file on disk, relative to project folder.\r\n         * @param message Returns a reason for the asset not being open for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset is considered open for edit by the selected version control system. \r\n         */\r\n        static IsOpenForEdit(assetObject: Object1, statusOptions: StatusQueryOptions): boolean\r\n        /** Query whether an Asset file is open for editing in version control.\r\n         * @param assetObject Object representing the asset whose status you wish to query.\r\n         * @param assetOrMetaFilePath Path to the asset file or its .meta file on disk, relative to project folder.\r\n         * @param message Returns a reason for the asset not being open for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset is considered open for edit by the selected version control system. \r\n         */\r\n        static IsOpenForEdit(assetOrMetaFilePath: string, statusOptions: StatusQueryOptions): boolean\r\n        /** Query whether an Asset file is open for editing in version control.\r\n         * @param assetObject Object representing the asset whose status you wish to query.\r\n         * @param assetOrMetaFilePath Path to the asset file or its .meta file on disk, relative to project folder.\r\n         * @param message Returns a reason for the asset not being open for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset is considered open for edit by the selected version control system. \r\n         */\r\n        static IsOpenForEdit(assetObject: Object1, message: jsb.Out<string>): boolean\r\n        /** Query whether an Asset file is open for editing in version control.\r\n         * @param assetObject Object representing the asset whose status you wish to query.\r\n         * @param assetOrMetaFilePath Path to the asset file or its .meta file on disk, relative to project folder.\r\n         * @param message Returns a reason for the asset not being open for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset is considered open for edit by the selected version control system. \r\n         */\r\n        static IsOpenForEdit(assetOrMetaFilePath: string, message: jsb.Out<string>): boolean\r\n        /** Query whether an Asset file is open for editing in version control.\r\n         * @param assetObject Object representing the asset whose status you wish to query.\r\n         * @param assetOrMetaFilePath Path to the asset file or its .meta file on disk, relative to project folder.\r\n         * @param message Returns a reason for the asset not being open for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset is considered open for edit by the selected version control system. \r\n         */\r\n        static IsOpenForEdit(assetObject: Object1): boolean\r\n        /** Query whether an Asset file is open for editing in version control.\r\n         * @param assetObject Object representing the asset whose status you wish to query.\r\n         * @param assetOrMetaFilePath Path to the asset file or its .meta file on disk, relative to project folder.\r\n         * @param message Returns a reason for the asset not being open for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset is considered open for edit by the selected version control system. \r\n         */\r\n        static IsOpenForEdit(assetOrMetaFilePath: string): boolean\r\n        static MakeEditable(paths: Array<string>, prompt: string, outNotEditablePaths: any): boolean\r\n        /** Makes a file open for editing in version control.\r\n         * @param path Specifies the path to a file relative to the project root.\r\n         * @returns true if Unity successfully made the file editable in the version control system. Otherwise, returns false. \r\n         */\r\n        static MakeEditable(path: string): boolean\r\n        /** Search the asset database using the search filter string.\r\n         * @param filter The filter string can contain search data.  See below for details about this string.\r\n         * @param searchInFolders The folders where the search will start.\r\n         * @returns Array of matching asset. Note that GUIDs will be returned. \r\n         */\r\n        static FindAssets(filter: string, searchInFolders: Array<string>): Array<string>\r\n        /** Search the asset database using the search filter string.\r\n         * @param filter The filter string can contain search data.  See below for details about this string.\r\n         * @param searchInFolders The folders where the search will start.\r\n         * @returns Array of matching asset. Note that GUIDs will be returned. \r\n         */\r\n        static FindAssets(filter: string): Array<string>\r\n        /** Is object an asset?\r\n         */\r\n        static Contains(obj: Object1): boolean\r\n        /** Is object an asset?\r\n         */\r\n        static Contains(instanceID: number): boolean\r\n        /** Creates a new folder, in the specified parent folder.\n\nThe parent folder string must start with the \"Assets\" folder, and all folders within the parent folder string must already exist. For example, when specifying \"AssetsParentFolder1Parentfolder2/\", the new folder will be created in \"ParentFolder2\" only if ParentFolder1 and ParentFolder2 already exist.\r\n         * @param parentFolder The path to the parent folder. Must start with \"Assets/\".\r\n         * @param newFolderName The name of the new folder.\r\n         * @returns The GUID of the newly created folder, if the folder was created successfully. Otherwise returns an empty string. \r\n         */\r\n        static CreateFolder(parentFolder: string, newFolderName: string): string\r\n        /** Is asset a main asset in the project window?\r\n         */\r\n        static IsMainAsset(obj: Object1): boolean\r\n        /** Is asset a main asset in the project window?\r\n         */\r\n        static IsMainAsset(instanceID: number): boolean\r\n        /** Does the asset form part of another asset?\r\n         * @param obj The asset Object to query.\r\n         * @param instanceID Instance ID of the asset Object to query.\r\n         */\r\n        static IsSubAsset(obj: Object1): boolean\r\n        /** Does the asset form part of another asset?\r\n         * @param obj The asset Object to query.\r\n         * @param instanceID Instance ID of the asset Object to query.\r\n         */\r\n        static IsSubAsset(instanceID: number): boolean\r\n        /** Determines whether the Asset is a foreign Asset.\r\n         */\r\n        static IsForeignAsset(obj: Object1): boolean\r\n        /** Determines whether the Asset is a foreign Asset.\r\n         */\r\n        static IsForeignAsset(instanceID: number): boolean\r\n        /** Determines whether the Asset is a native Asset.\r\n         */\r\n        static IsNativeAsset(obj: Object1): boolean\r\n        /** Determines whether the Asset is a native Asset.\r\n         */\r\n        static IsNativeAsset(instanceID: number): boolean\r\n        static GetCurrentCacheServerIp(): string\r\n        /** Creates a new unique path for an asset.\r\n         */\r\n        static GenerateUniqueAssetPath(path: string): string\r\n        static StartAssetEditing(): void\r\n        static StopAssetEditing(): void\r\n        static ReleaseCachedFileHandles(): void\r\n        /** Checks if an asset file can be moved from one folder to another. (Without actually moving the file).\r\n         * @param oldPath The path where the asset currently resides.\r\n         * @param newPath The path which the asset should be moved to.\r\n         * @returns An empty string if the asset can be moved, otherwise an error message. \r\n         */\r\n        static ValidateMoveAsset(oldPath: string, newPath: string): string\r\n        /** Move an asset file (or folder) from one folder to another.\r\n         * @param oldPath The path where the asset currently resides.\r\n         * @param newPath The path which the asset should be moved to.\r\n         * @returns An empty string if the asset has been successfully moved, otherwise an error message. \r\n         */\r\n        static MoveAsset(oldPath: string, newPath: string): string\r\n        /** Creates an external Asset from an object (such as a Material) by extracting it from within an imported asset (such as an FBX file).\r\n         * @param asset The sub-asset to extract.\r\n         * @param newPath The file path of the new Asset.\r\n         * @returns An empty string if Unity has successfully extracted the Asset, or an error message if not. \r\n         */\r\n        static ExtractAsset(asset: Object1, newPath: string): string\r\n        /** Rename an asset file.\r\n         * @param pathName The path where the asset currently resides.\r\n         * @param newName The new name which should be given to the asset.\r\n         * @returns An empty string, if the asset has been successfully renamed, otherwise an error message. \r\n         */\r\n        static RenameAsset(pathName: string, newName: string): string\r\n        /** Moves the specified asset  or folder to the OS trash.\r\n         * @param path Project relative path of the asset or folder to be deleted.\r\n         * @returns Returns true if the asset has been successfully removed, false if it doesn't exist or couldn't be removed. \r\n         */\r\n        static MoveAssetToTrash(path: string): boolean\r\n        static MoveAssetsToTrash(paths: Array<string>, outFailedPaths: any): boolean\r\n        /** Deletes the specified asset or folder.\r\n         * @param path Project relative path of the asset or folder to be deleted.\r\n         * @returns Returns true if the asset has been successfully removed, false if it doesn't exist or couldn't be removed. \r\n         */\r\n        static DeleteAsset(path: string): boolean\r\n        static DeleteAssets(paths: Array<string>, outFailedPaths: any): boolean\r\n        /** Import asset at path.\r\n         */\r\n        static ImportAsset(path: string, options: ImportAssetOptions): void\r\n        /** Import asset at path.\r\n         */\r\n        static ImportAsset(path: string): void\r\n        /** Duplicates the asset at path and stores it at newPath.\r\n         * @param path Filesystem path of the source asset.\r\n         * @param newPath Filesystem path of the new asset to create.\r\n         * @returns Returns true if the copy operation is successful or false if part of the process fails. \r\n         */\r\n        static CopyAsset(path: string, newPath: string): boolean\r\n        /** Writes the import settings to disk.\r\n         */\r\n        static WriteImportSettingsIfDirty(path: string): boolean\r\n        /** Given a path to a directory in the Assets folder, relative to the project folder, this method will return an array of all its subdirectories.\r\n         */\r\n        static GetSubFolders(path: string): Array<string>\r\n        /** Given a path to a folder, returns true if it exists, false otherwise.\r\n         * @param path The path to the folder.\r\n         * @returns Returns true if the folder exists. \r\n         */\r\n        static IsValidFolder(path: string): boolean\r\n        /** Creates a new asset at path.\r\n         * @param asset Object to use in creating the asset.\r\n         * @param path Filesystem path for the new asset.\r\n         */\r\n        static CreateAsset(asset: Object1, path: string): void\r\n        /** Adds objectToAdd to an existing asset at path.\r\n         * @param objectToAdd Object to add to the existing asset.\r\n         * @param path Filesystem path to the asset.\r\n         */\r\n        static AddObjectToAsset(objectToAdd: Object1, path: string): void\r\n        /** Adds objectToAdd to an existing asset identified by assetObject.\r\n         */\r\n        static AddObjectToAsset(objectToAdd: Object1, assetObject: Object1): void\r\n        /** Specifies which object in the asset file should become the main object after the next import.\r\n         * @param mainObject The object to become the main object.\r\n         * @param assetPath Path to the asset file.\r\n         */\r\n        static SetMainObject(mainObject: Object1, assetPath: string): void\r\n        /** Returns the path name relative to the project folder where the asset is stored.\r\n         * @param instanceID The instance ID of the asset.\r\n         * @param assetObject A reference to the asset.\r\n         * @returns The asset path name, or null, or an empty string if the asset does not exist. \r\n         */\r\n        static GetAssetPath(assetObject: Object1): string\r\n        /** Returns the path name relative to the project folder where the asset is stored.\r\n         * @param instanceID The instance ID of the asset.\r\n         * @param assetObject A reference to the asset.\r\n         * @returns The asset path name, or null, or an empty string if the asset does not exist. \r\n         */\r\n        static GetAssetPath(instanceID: number): string\r\n        /** Returns the path name relative to the project folder where the asset is stored.\r\n         */\r\n        static GetAssetOrScenePath(assetObject: Object1): string\r\n        /** Gets the path to the text .meta file associated with an asset.\r\n         * @param path The path to the asset.\r\n         * @returns The path to the .meta text file or empty string if the file does not exist. \r\n         */\r\n        static GetTextMetaFilePathFromAssetPath(path: string): string\r\n        /** Gets the path to the asset file associated with a text .meta file.\r\n         */\r\n        static GetAssetPathFromTextMetaFilePath(path: string): string\r\n        /** Returns the first asset object of type type at given path assetPath.\r\n         * @param assetPath Path of the asset to load.\r\n         * @param type Data type of the asset.\r\n         * @returns The asset matching the parameters. \r\n         */\r\n        static LoadAssetAtPath(assetPath: string, type: any): Object1\r\n        /** Returns the main asset object at assetPath.\n\nThe \"main\" Asset is the Asset at the root of a hierarchy (such as a Maya file which may contain multiples meshes and GameObjects).\r\n         * @param assetPath Filesystem path of the asset to load.\r\n         */\r\n        static LoadMainAssetAtPath(assetPath: string): Object1\r\n        /** Returns the type of the main asset object at assetPath.\r\n         * @param assetPath Filesystem path of the asset to load.\r\n         */\r\n        static GetMainAssetTypeAtPath(assetPath: string): any\r\n        /** Gets an object's type from an Asset path and a local file identifier.\r\n         * @param assetPath The Asset's path.\r\n         * @param localIdentifierInFile The object's local file identifier.\r\n         * @returns The object's type. \r\n         */\r\n        static GetTypeFromPathAndFileID(assetPath: string, localIdentifierInFile: number): any\r\n        /** Returns true if the main asset object at assetPath is loaded in memory.\r\n         * @param assetPath Filesystem path of the asset to load.\r\n         */\r\n        static IsMainAssetAtPathLoaded(assetPath: string): boolean\r\n        /** Returns all sub Assets at assetPath.\r\n         */\r\n        static LoadAllAssetRepresentationsAtPath(assetPath: string): Array<Object1>\r\n        /** Returns an array of all Assets at assetPath.\r\n         * @param assetPath Filesystem path to the asset.\r\n         */\r\n        static LoadAllAssetsAtPath(assetPath: string): Array<Object1>\r\n        static GetAllAssetPaths(): Array<string>\r\n        /** Import any changed assets.\r\n         */\r\n        static Refresh(options: ImportAssetOptions): void\r\n        /** Import any changed assets.\r\n         */\r\n        static Refresh(): void\r\n        /** Opens the asset with associated application.\r\n         */\r\n        static OpenAsset(instanceID: number, lineNumber: number, columnNumber: number): boolean\r\n        /** Opens the asset with associated application.\r\n         */\r\n        static OpenAsset(target: Object1, lineNumber: number, columnNumber: number): boolean\r\n        /** Opens the asset with associated application.\r\n         */\r\n        static OpenAsset(instanceID: number, lineNumber: number): boolean\r\n        /** Opens the asset with associated application.\r\n         */\r\n        static OpenAsset(target: Object1, lineNumber: number): boolean\r\n        /** Opens the asset with associated application.\r\n         */\r\n        static OpenAsset(instanceID: number): boolean\r\n        /** Opens the asset with associated application.\r\n         */\r\n        static OpenAsset(target: Object1): boolean\r\n        /** Opens the asset(s) with associated application(s).\r\n         */\r\n        static OpenAsset(objects: Array<Object1>): boolean\r\n        /** Gets the corresponding asset path for the supplied GUID, or an empty string if the GUID can't be found.\r\n         * @param guid The GUID of an asset.\r\n         * @returns Path of the asset relative to the project folder. \r\n         */\r\n        static GUIDToAssetPath(guid: string): string\r\n        /** Gets the corresponding asset path for the supplied GUID, or an empty string if the GUID can't be found.\r\n         * @param guid The GUID of an asset.\r\n         * @returns Path of the asset relative to the project folder. \r\n         */\r\n        static GUIDToAssetPath(guid: GUID): string\r\n        /** Get the GUID for the asset at path.\r\n         * @param path Filesystem path for the asset. All paths are relative to the project folder.\r\n         * @returns The GUID of the asset. An all-zero GUID denotes an invalid asset path. \r\n         */\r\n        static GUIDFromAssetPath(path: string): GUID\r\n        /** Get the GUID for the asset at path.\r\n         * @param path Filesystem path for the asset.\r\n         * @returns GUID. \r\n         */\r\n        static AssetPathToGUID(path: string): string\r\n        /** Returns the hash of all the dependencies of an asset.\r\n         * @param path Path to the asset.\r\n         * @param guid GUID of the asset.\r\n         * @returns Aggregate hash. \r\n         */\r\n        static GetAssetDependencyHash(guid: GUID): Hash128\r\n        /** Returns the hash of all the dependencies of an asset.\r\n         * @param path Path to the asset.\r\n         * @param guid GUID of the asset.\r\n         * @returns Aggregate hash. \r\n         */\r\n        static GetAssetDependencyHash(path: string): Hash128\r\n        static SaveAssets(): void\r\n        /** Writes all unsaved changes to the specified asset to disk.\r\n         * @param obj The asset object to be saved, if dirty.\r\n         * @param guid The guid of the asset to be saved, if dirty.\r\n         */\r\n        static SaveAssetIfDirty(guid: GUID): void\r\n        /** Writes all unsaved changes to the specified asset to disk.\r\n         * @param obj The asset object to be saved, if dirty.\r\n         * @param guid The guid of the asset to be saved, if dirty.\r\n         */\r\n        static SaveAssetIfDirty(obj: Object1): void\r\n        /** Retrieves an icon for the asset at the given asset path.\r\n         */\r\n        static GetCachedIcon(path: string): Texture\r\n        /** Replaces that list of labels on an asset.\r\n         */\r\n        static SetLabels(obj: Object1, labels: Array<string>): void\r\n        static GetLabels(guid: GUID): Array<string>\r\n        /** Returns all labels attached to a given asset.\r\n         */\r\n        static GetLabels(obj: Object1): Array<string>\r\n        /** Removes all labels attached to an asset.\r\n         */\r\n        static ClearLabels(obj: Object1): void\r\n        static GetAllAssetBundleNames(): Array<string>\r\n        static GetUnusedAssetBundleNames(): Array<string>\r\n        /** Remove the assetBundle name from the asset database. The forceRemove flag is used to indicate if you want to remove it even it's in use.\r\n         * @param assetBundleName The assetBundle name you want to remove.\r\n         * @param forceRemove Flag to indicate if you want to remove the assetBundle name even it's in use.\r\n         */\r\n        static RemoveAssetBundleName(assetBundleName: string, forceRemove: boolean): boolean\r\n        static RemoveUnusedAssetBundleNames(): void\r\n        /** Returns an array containing the paths of all assets marked with the specified Asset Bundle name.\r\n         */\r\n        static GetAssetPathsFromAssetBundle(assetBundleName: string): Array<string>\r\n        /** Get the Asset paths for all Assets tagged with assetBundleName and\n                named assetName.\r\n         */\r\n        static GetAssetPathsFromAssetBundleAndAssetName(assetBundleName: string, assetName: string): Array<string>\r\n        /** Returns the name of the AssetBundle that a given asset belongs to.\r\n         * @param assetPath The asset's path.\r\n         * @returns Returns the name of the AssetBundle that a given asset belongs to. See the method description for more details. \r\n         */\r\n        static GetImplicitAssetBundleName(assetPath: string): string\r\n        /** Returns the name of the AssetBundle Variant that a given asset belongs to.\r\n         * @param assetPath The asset's path.\r\n         * @returns Returns the name of the AssetBundle Variant that a given asset belongs to. See the method description for more details. \r\n         */\r\n        static GetImplicitAssetBundleVariantName(assetPath: string): string\r\n        /** Given an assetBundleName, returns the list of AssetBundles that it depends on.\r\n         * @param assetBundleName The name of the AssetBundle for which dependencies are required.\r\n         * @param recursive If false, returns only AssetBundles which are direct dependencies of the input; if true, includes all indirect dependencies of the input.\r\n         * @returns The names of all AssetBundles that the input depends on. \r\n         */\r\n        static GetAssetBundleDependencies(assetBundleName: string, recursive: boolean): Array<string>\r\n        /** Returns an array of all the assets that are dependencies of the asset at the specified pathName.\n\nNote: GetDependencies() gets the Assets that are referenced by other Assets. For example, a Scene could contain many GameObjects with a Material attached to them. In this case,  GetDependencies() will return the path to the Material Assets, but not the GameObjects as those are not Assets on your disk.\r\n         * @param pathName The path to the asset for which dependencies are required.\r\n         * @param recursive Controls whether this method recursively checks and returns all dependencies including indirect dependencies (when set to true), or whether it only returns direct dependencies (when set to false).\r\n         * @returns The paths of all assets that the input depends on. \r\n         */\r\n        static GetDependencies(pathName: string, recursive: boolean): Array<string>\r\n        /** Returns an array of the paths of assets that are dependencies of all the assets in the list of pathNames that you provide.\n\nNote: GetDependencies() gets the Assets that are referenced by other Assets. For example, a Scene could contain many GameObjects with a Material attached to them. In this case,  GetDependencies() will return the path to the Material Assets, but not the GameObjects as those are not Assets on your disk.\r\n         * @param pathNames The path to the assets for which dependencies are required.\r\n         * @param recursive Controls whether this method recursively checks and returns all dependencies including indirect dependencies (when set to true), or whether it only returns direct dependencies (when set to false).\r\n         * @returns The paths of all assets that the input depends on. \r\n         */\r\n        static GetDependencies(pathNames: Array<string>, recursive: boolean): Array<string>\r\n        /** Returns an array of all the assets that are dependencies of the asset at the specified pathName.\n\nNote: GetDependencies() gets the Assets that are referenced by other Assets. For example, a Scene could contain many GameObjects with a Material attached to them. In this case,  GetDependencies() will return the path to the Material Assets, but not the GameObjects as those are not Assets on your disk.\r\n         * @param pathName The path to the asset for which dependencies are required.\r\n         * @param recursive Controls whether this method recursively checks and returns all dependencies including indirect dependencies (when set to true), or whether it only returns direct dependencies (when set to false).\r\n         * @returns The paths of all assets that the input depends on. \r\n         */\r\n        static GetDependencies(pathName: string): Array<string>\r\n        /** Returns an array of the paths of assets that are dependencies of all the assets in the list of pathNames that you provide.\n\nNote: GetDependencies() gets the Assets that are referenced by other Assets. For example, a Scene could contain many GameObjects with a Material attached to them. In this case,  GetDependencies() will return the path to the Material Assets, but not the GameObjects as those are not Assets on your disk.\r\n         * @param pathNames The path to the assets for which dependencies are required.\r\n         * @param recursive Controls whether this method recursively checks and returns all dependencies including indirect dependencies (when set to true), or whether it only returns direct dependencies (when set to false).\r\n         * @returns The paths of all assets that the input depends on. \r\n         */\r\n        static GetDependencies(pathNames: Array<string>): Array<string>\r\n        /** Exports the assets identified by assetPathNames to a unitypackage file in fileName.\r\n         */\r\n        static ExportPackage(assetPathName: string, fileName: string, flags: ExportPackageOptions): void\r\n        /** Exports the assets identified by assetPathNames to a unitypackage file in fileName.\r\n         */\r\n        static ExportPackage(assetPathNames: Array<string>, fileName: string, flags: ExportPackageOptions): void\r\n        /** Exports the assets identified by assetPathNames to a unitypackage file in fileName.\r\n         */\r\n        static ExportPackage(assetPathName: string, fileName: string): void\r\n        /** Exports the assets identified by assetPathNames to a unitypackage file in fileName.\r\n         */\r\n        static ExportPackage(assetPathNames: Array<string>, fileName: string): void\r\n        /** Query whether an asset's metadata (.meta) file is open for edit in version control.\r\n         * @param assetObject Object representing the asset whose metadata status you wish to query.\r\n         * @param message Returns a reason for the asset metadata not being open for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset's metadata is considered open for edit by the selected version control system. \r\n         */\r\n        static IsMetaFileOpenForEdit(assetObject: Object1, message: jsb.Out<string>, statusOptions: StatusQueryOptions): boolean\r\n        /** Query whether an asset's metadata (.meta) file is open for edit in version control.\r\n         * @param assetObject Object representing the asset whose metadata status you wish to query.\r\n         * @param message Returns a reason for the asset metadata not being open for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset's metadata is considered open for edit by the selected version control system. \r\n         */\r\n        static IsMetaFileOpenForEdit(assetObject: Object1, statusOptions: StatusQueryOptions): boolean\r\n        /** Query whether an asset's metadata (.meta) file is open for edit in version control.\r\n         * @param assetObject Object representing the asset whose metadata status you wish to query.\r\n         * @param message Returns a reason for the asset metadata not being open for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset's metadata is considered open for edit by the selected version control system. \r\n         */\r\n        static IsMetaFileOpenForEdit(assetObject: Object1, message: jsb.Out<string>): boolean\r\n        /** Query whether an asset's metadata (.meta) file is open for edit in version control.\r\n         * @param assetObject Object representing the asset whose metadata status you wish to query.\r\n         * @param message Returns a reason for the asset metadata not being open for edit.\r\n         * @param statusOptions Options for how the version control system should be queried. These options can effect the speed and accuracy of the query. Default is StatusQueryOptions.UseCachedIfPossible.\r\n         * @returns True if the asset's metadata is considered open for edit by the selected version control system. \r\n         */\r\n        static IsMetaFileOpenForEdit(assetObject: Object1): boolean\r\n        static GetBuiltinExtraResource(type: any, path: string): Object1\r\n        static ForceReserializeAssets(assetPaths: IEnumerable<string>, options: ForceReserializeAssetsOptions): void\r\n        static ForceReserializeAssets(): void\r\n        /** Get the GUID and local file id from an object instance id.\r\n         * @param instanceID InstanceID of the object to retrieve information for.\r\n         * @param obj The object to retrieve GUID and File Id for.\r\n         * @param assetRef The asset reference to retrieve GUID and File Id for.\r\n         * @param guid The GUID of an asset.\r\n         * @param localId The local file identifier of this asset.\r\n         * @returns True if the guid and file id were successfully found, false if not. \r\n         */\r\n        static TryGetGUIDAndLocalFileIdentifier(obj: Object1, guid: jsb.Out<string>, localId: jsb.Out<number>): boolean\r\n        /** Get the GUID and local file id from an object instance id.\r\n         * @param instanceID InstanceID of the object to retrieve information for.\r\n         * @param obj The object to retrieve GUID and File Id for.\r\n         * @param assetRef The asset reference to retrieve GUID and File Id for.\r\n         * @param guid The GUID of an asset.\r\n         * @param localId The local file identifier of this asset.\r\n         * @returns True if the guid and file id were successfully found, false if not. \r\n         */\r\n        static TryGetGUIDAndLocalFileIdentifier(instanceID: number, guid: jsb.Out<string>, localId: jsb.Out<number>): boolean\r\n        /** Removes object from its asset (See Also: AssetDatabase.AddObjectToAsset).\r\n         */\r\n        static RemoveObjectFromAsset(objectToRemove: Object1): void\r\n        /** Imports package at packagePath into the current project.\r\n         */\r\n        static ImportPackage(packagePath: string, interactive: boolean): void\r\n        static DisallowAutoRefresh(): void\r\n        static AllowAutoRefresh(): void\r\n        /** Clears the importer override for the asset.\r\n         * @param path Asset path.\r\n         */\r\n        static ClearImporterOverride(path: string): void\r\n        static IsCacheServerEnabled(): boolean\r\n        /** Returns the type of the override importer.\r\n         * @param path Asset path.\r\n         * @returns Importer type. \r\n         */\r\n        static GetImporterOverride(path: string): any\r\n        /** Gets the importer types associated with a given Asset type.\r\n         * @param path The Asset path.\r\n         * @returns Returns an array of importer types that can handle the specified Asset. \r\n         */\r\n        static GetAvailableImporterTypes(path: string): Array<any>\r\n        /** Checks the availability of the Cache Server.\r\n         * @param ip The IP address of the Cache Server.\r\n         * @param port The Port number of the Cache Server.\r\n         * @returns Returns true when Editor can connect to the Cache Server. Returns false otherwise. \r\n         */\r\n        static CanConnectToCacheServer(ip: string, port: number): boolean\r\n        static RefreshSettings(): void\r\n        static IsConnectedToCacheServer(): boolean\r\n        static ResetCacheServerReconnectTimer(): void\r\n        static CloseCacheServerConnection(): void\r\n        static GetCacheServerAddress(): string\r\n        static GetCacheServerPort(): number\r\n        static GetCacheServerNamespacePrefix(): string\r\n        static GetCacheServerEnableDownload(): boolean\r\n        static GetCacheServerEnableUpload(): boolean\r\n        static IsDirectoryMonitoringEnabled(): boolean\r\n        /** Allows you to register a custom dependency that Assets can be dependent on. If you register a custom dependency, and specify that an Asset is dependent on it, then the Asset will get re-imported if the custom dependency changes.\r\n         * @param dependency Name of dependency. You can use any name you like, but because these names are global across all your Assets, it can be useful to use a naming convention (eg a path-based naming system) to avoid clashes with other custom dependency names.\r\n         * @param hashOfValue A Hash128 value of the dependency.\r\n         */\r\n        static RegisterCustomDependency(dependency: string, hashOfValue: Hash128): void\r\n        /** Removes custom dependencies that match the prefixFilter.\r\n         * @param prefixFilter Prefix filter for the custom dependencies to unregister.\r\n         * @returns Number of custom dependencies removed. \r\n         */\r\n        static UnregisterCustomDependencyPrefixFilter(prefixFilter: string): number\r\n        static IsAssetImportWorkerProcess(): boolean\r\n        protected constructor()\r\n        /** Changes during Refresh if anything has changed that can invalidate any artifact.\r\n         */\r\n        static readonly GlobalArtifactDependencyVersion: number\r\n        /** Changes whenever a new artifact is added to the artifact database.\r\n         */\r\n        static readonly GlobalArtifactProcessedVersion: number\r\n        static importPackageStarted(op: \"add\" | \"remove\", fn: (packageName: string) => void): void\r\n        static importPackageCompleted(op: \"add\" | \"remove\", fn: (packageName: string) => void): void\r\n        static importPackageCancelled(op: \"add\" | \"remove\", fn: (packageName: string) => void): void\r\n        static importPackageFailed(op: \"add\" | \"remove\", fn: (packageName: string, errorMessage: string) => void): void\r\n        static cacheServerConnectionChanged(op: \"add\" | \"remove\", fn: (obj: CacheServerConnectionChangedParameters) => void): void\r\n        static onImportPackageItemsCompleted(op: \"get\"): (obj: Array<string>) => void\r\n        static onImportPackageItemsCompleted(op: \"add\" | \"remove\" | \"set\", fn?: (obj: Array<string>) => void): void\r\n        static onImportPackageItemsCompleted(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (obj: Array<string>) => void): (obj: Array<string>) => void | void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array, Enum } from \"System\";\r\n    import { Object as Object1, Material } from \"UnityEngine\";\r\n    /** Utility functions to assist with working with shaders from the editor.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ShaderUtil extends Object {\r\n        /** Determines whether the specified Shader contains a valid Procedural Instancing variant.\r\n         * @param s The Shader to check.\r\n         * @returns Returns true if the Shader has a valid Procedural Instancing variant. Returns false otherwise. \r\n         */\r\n        static HasProceduralInstancing(s: any): boolean\r\n        /** Returns the number of errors and warnings generated by the Unity Shader Compiler for the given Shader.\r\n         * @param s The Shader instance to check for messages.\r\n         * @returns The number of errors and warnings generated by the Unity Shader Compiler. \r\n         */\r\n        static GetShaderMessageCount(s: any): number\r\n        /** Returns each error and warning generated by the Unity Shader Compiler for the given Shader.\r\n         * @param s The Shader instance to check for messages.\r\n         * @returns An array of ShaderMessage structs containing the generated messages. \r\n         */\r\n        static GetShaderMessages(s: any): Array<ShaderMessage>\r\n        /** Clear compile time messages for the given shader.\r\n         */\r\n        static ClearShaderMessages(s: any): void\r\n        /** Returns the number of errors and warnings generated by the Unity Shader Compiler for the given ComputeShader.\r\n         * @param s The ComputeShader instance to check for messages.\r\n         * @returns The number of errors and warnings generated by the Unity Shader Compiler. \r\n         */\r\n        static GetComputeShaderMessageCount(s: any): number\r\n        /** Returns each error and warning generated by the Unity Shader Compiler for the given ComputeShader.\r\n         * @param s The ComputeShader instance to check for messages.\r\n         * @returns An array of ShaderMessage structs containing the generated messages. \r\n         */\r\n        static GetComputeShaderMessages(s: any): Array<ShaderMessage>\r\n        /** Returns the number of errors and warnings generated by the Shader Compiler for the given RayTracingShader.\r\n         * @param s The RayTracingShader instance to check for messages.\r\n         * @returns The number of errors and warnings generated by the Shader Compiler. \r\n         */\r\n        static GetRayTracingShaderMessageCount(s: any): number\r\n        /** Returns each error and warning generated by the Shader Compiler for the given RayTracingShader.\r\n         * @param s The RayTracingShader instance to check for messages.\r\n         * @returns An array of ShaderMessage structs containing the generated messages. \r\n         */\r\n        static GetRayTracingShaderMessages(s: any): Array<ShaderMessage>\r\n        /** Returns the number of ray generation Shaders defined whitin a given RayTracingShader.\r\n         * @param s The RayTracingShader instance.\r\n         * @returns The number of ray generation Shaders defined in the RayTracingShader instance passed as argument. \r\n         */\r\n        static GetRayGenerationShaderCount(s: any): number\r\n        /** Returns the name of a user-defined ray generation Shader from within a RayTracingShader.\r\n         * @param s The RayTracingShader instance.\r\n         * @param shaderIndex The ray generation Shader index for which to retrieve the name. The ray generation Shaders defined in a RayTracingShader are sorted alphabetically by the Shader compiler.\r\n         * @returns The name of the ray generation Shader at the index passed using the \"shaderIndex\" argument. \r\n         */\r\n        static GetRayGenerationShaderName(s: any, shaderIndex: number): string\r\n        /** Returns the number of miss Shaders defined whitin a given RayTracingShader.\r\n         * @param s The RayTracingShader instance.\r\n         * @returns The number of miss Shaders defined in the RayTracingShader instance passed as argument. \r\n         */\r\n        static GetMissShaderCount(s: any): number\r\n        /** Returns the name of a user-defined miss Shader from within a RayTracingShader.\r\n         * @param s The RayTracingShader instance.\r\n         * @param shaderIndex The miss Shader index for which to retrieve the name. The miss Shaders defined in a RayTracingShader are sorted alphabetically by the Shader compiler.\r\n         * @returns The name of the miss Shader at the index passed using the \"shaderIndex\" argument. \r\n         */\r\n        static GetMissShaderName(s: any, shaderIndex: number): string\r\n        /** Returns the ray payload size of a user-defined miss Shader from within a RayTracingShader.\r\n         * @param s The RayTracingShader instance.\r\n         * @param shaderIndex The miss Shader index for which to retrieve the ray payload size.\r\n         * @returns The ray payload size in bytes. \r\n         */\r\n        static GetMissShaderRayPayloadSize(s: any, shaderIndex: number): number\r\n        /** Returns the number of callable Shaders defined whitin a given RayTracingShader.\r\n         * @param s The RayTracingShader instance.\r\n         * @returns The number of callable Shaders defined in the RayTracingShader instance passed as argument. \r\n         */\r\n        static GetCallableShaderCount(s: any): number\r\n        /** Returns the name of a user-defined callable Shader from within a RayTracingShader.\r\n         * @param s The RayTracingShader instance.\r\n         * @param shaderIndex The callable Shader index for which to retrieve the name. The callable Shaders defined in a RayTracingShader are sorted alphabetically by the Shader compiler.\r\n         * @returns The name of the callable Shader at the index passed using the \"shaderIndex\" argument. \r\n         */\r\n        static GetCallableShaderName(s: any, shaderIndex: number): string\r\n        /** Returns the parameter size of a user-defined callable Shader from within a RayTracingShader.\r\n         * @param s The RayTracingShader instance.\r\n         * @param shaderIndex The callable Shader index for which to retrieve the parameter size.\r\n         * @returns The parameter size in bytes. \r\n         */\r\n        static GetCallableShaderParamSize(s: any, shaderIndex: number): number\r\n        /** Clears all internally-cached data that was generated for the given shader, such as errors and compilation info.\r\n         */\r\n        static ClearCachedData(s: any): void\r\n        /** Creates a new Shader object from the provided source code string. You can use this method alongside the ScriptedImporter to create custom shader generation tools in the Editor.\r\n         * @param context A context object that the asset system needs to register shader dependencies properly.\r\n         * @param source A string that contains a shader written in code.\r\n         * @param compileInitialShaderVariants Set to true to compile the code contained in the source string; otherwise false.\r\n         */\r\n        static CreateShaderAsset(context: any, source: string, compileInitialShaderVariants: boolean): any\r\n        /** Creates a new Shader object from the provided source code string. You can use this method alongside the ScriptedImporter to create custom shader generation tools in the Editor.\r\n         * @param context A context object that the asset system needs to register shader dependencies properly.\r\n         * @param source A string that contains a shader written in code.\r\n         * @param compileInitialShaderVariants Set to true to compile the code contained in the source string; otherwise false.\r\n         */\r\n        static CreateShaderAsset(source: string, compileInitialShaderVariants: boolean): any\r\n        /** Creates a new Shader object from the provided source code string. You can use this method alongside the ScriptedImporter to create custom shader generation tools in the Editor.\r\n         * @param context A context object that the asset system needs to register shader dependencies properly.\r\n         * @param source A string that contains a shader written in code.\r\n         * @param compileInitialShaderVariants Set to true to compile the code contained in the source string; otherwise false.\r\n         */\r\n        static CreateShaderAsset(source: string): any\r\n        /** Replaces the existing source code in the specified shader with the source code in the supplied string.\r\n         * @param context A context object that the asset system needs to register shader dependencies properly.\r\n         * @param source A string that contains a shader written in code.\r\n         * @param compileInitialShaderVariants Set to true to compile the code contained in the source string; otherwise false.\r\n         * @param shader The Shader to update.\r\n         */\r\n        static UpdateShaderAsset(context: any, shader: any, source: string, compileInitialShaderVariants: boolean): void\r\n        /** Replaces the existing source code in the specified shader with the source code in the supplied string.\r\n         * @param context A context object that the asset system needs to register shader dependencies properly.\r\n         * @param source A string that contains a shader written in code.\r\n         * @param compileInitialShaderVariants Set to true to compile the code contained in the source string; otherwise false.\r\n         * @param shader The Shader to update.\r\n         */\r\n        static UpdateShaderAsset(shader: any, source: string, compileInitialShaderVariants: boolean): void\r\n        /** Replaces the existing source code in the specified shader with the source code in the supplied string.\r\n         * @param context A context object that the asset system needs to register shader dependencies properly.\r\n         * @param source A string that contains a shader written in code.\r\n         * @param compileInitialShaderVariants Set to true to compile the code contained in the source string; otherwise false.\r\n         * @param shader The Shader to update.\r\n         */\r\n        static UpdateShaderAsset(shader: any, source: string): void\r\n        /** Register a user created shader.\r\n         */\r\n        static RegisterShader(shader: any): void\r\n        static GetAllShaderInfo(): Array<ShaderInfo>\r\n        /** Adds shader compilation mode command in the CommandBuffer.\r\n         * @param cmd Target CommandBuffer.\r\n         * @param allow Is async Shader compilation allowed or not.\r\n         */\r\n        static SetAsyncCompilation(cmd: any, allow: boolean): void\r\n        /** Restores the previous Shader compilation mode in this CommandBuffer scope.\r\n         * @param cmd Target CommandBuffer.\r\n         */\r\n        static RestoreAsyncCompilation(cmd: any): void\r\n        /** Checks if the Shader variant for the given pass in the Material has already been compiled.\r\n         * @param material The Material to check against.\r\n         * @param pass The index of the Shader pass to check.\r\n         */\r\n        static IsPassCompiled(material: Material, pass: number): boolean\r\n        /** Request the Editor to compile the Shader Variant needed for the specific pass of the given Material.\r\n         * @param material Target Material.\r\n         * @param pass Index of the target Shader pass.\r\n         * @param forceSync Forces the script execution to wait until the compilation has finished. Optional.\r\n         */\r\n        static CompilePass(material: Material, pass: number, forceSync: boolean): void\r\n        /** Gets the platform keywords for a shader, given a shader compiler platform, build target, and optional graphics tier. These platform keywords are necessary to properly compile a shader for a given target.\r\n         * @param shaderCompilerPlatform The shader compiler platform.\r\n         * @param buildTarget The build target.\r\n         * @param tier An optional graphics tier.\r\n         * @returns Returns an array of built-in shader defines needed to compile a shader for the given target. \r\n         */\r\n        static GetShaderPlatformKeywordsForBuildTarget(shaderCompilerPlatform: any, buildTarget: BuildTarget, tier: any): Array<any>\r\n        /** Gets the platform keywords for a shader, given a shader compiler platform, build target, and optional graphics tier. These platform keywords are necessary to properly compile a shader for a given target.\r\n         * @param shaderCompilerPlatform The shader compiler platform.\r\n         * @param buildTarget The build target.\r\n         * @param tier An optional graphics tier.\r\n         * @returns Returns an array of built-in shader defines needed to compile a shader for the given target. \r\n         */\r\n        static GetShaderPlatformKeywordsForBuildTarget(shaderCompilerPlatform: any, buildTarget: BuildTarget): Array<any>\r\n        /** Get the number of properties in Shader s.\r\n         * @param s The shader to check against.\r\n         */\r\n        static GetPropertyCount(s: any): number\r\n        /** Get the name of the shader propery at index propertyIdx of Shader s.\r\n         * @param s The shader to check against.\r\n         * @param propertyIdx The property index to use.\r\n         */\r\n        static GetPropertyName(s: any, propertyIdx: number): string\r\n        /** Get the ShaderProperyType of the shader propery at index propertyIdx of Shader s.\r\n         * @param s The shader to check against.\r\n         * @param propertyIdx The property index to use.\r\n         */\r\n        static GetPropertyType(s: any, propertyIdx: number): ShaderUtil.ShaderPropertyType\r\n        /** Get the description of the shader propery at index propertyIdx of Shader s.\r\n         * @param s The shader to check against.\r\n         * @param propertyIdx The property index to use.\r\n         * @returns Returns the description of the given shader property. \r\n         */\r\n        static GetPropertyDescription(s: any, propertyIdx: number): string\r\n        /** Get Limits for a range property at index propertyIdx of Shader s.\r\n         * @param defminmax Which value to get: 0 = default, 1 = min, 2 = max.\r\n         * @param s The shader to check against.\r\n         * @param propertyIdx The property index to use.\r\n         */\r\n        static GetRangeLimits(s: any, propertyIdx: number, defminmax: number): number\r\n        /** Gets texture dimension of a shader property.\r\n         * @param s The shader to get the property from.\r\n         * @param propertyIdx The property index to use.\r\n         * @returns Texture dimension. \r\n         */\r\n        static GetTexDim(s: any, propertyIdx: number): any\r\n        /** Is the shader propery at index propertyIdx of Shader s hidden?\r\n         * @param s The shader to check against.\r\n         * @param propertyIdx The property index to use.\r\n         */\r\n        static IsShaderPropertyHidden(s: any, propertyIdx: number): boolean\r\n        /** Is the shader propery at index propertyIdx of Shader s a NonModifiableTextureProperty?\r\n         * @param s The shader to check against.\r\n         * @param propertyIdx The property index to use.\r\n         */\r\n        static IsShaderPropertyNonModifiableTexureProperty(s: any, propertyIdx: number): boolean\r\n        /** Get the shader data for a specific shader.\r\n         * @param shader The shader to get data from.\r\n         * @returns The shader data for the provided shader. \r\n         */\r\n        static GetShaderData(shader: any): ShaderData\r\n        /** Returns true if the given Shader generated any errors. Ignores warnings.\r\n         * @param shader The Shader instance to check for errors.\r\n         * @returns True if the Shader generated errors, false if there were no errors. \r\n         */\r\n        static ShaderHasError(shader: any): boolean\r\n        protected constructor()\r\n        /** Does the current hardware support render textues.\r\n         */\r\n        static readonly hardwareSupportsRectRenderTexture: boolean\r\n        /** When true, the Editor is compiling some Shaders asynchronously at the point of query.\r\n         */\r\n        static readonly anythingCompiling: boolean\r\n        /** When true, asynchronous Shader compilation is allowed at the current call site.\r\n         */\r\n        static allowAsyncCompilation: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array, Enum, ValueType } from \"System\";\r\n    import { Object as Object1, Texture2D, Texture, Renderer, Camera, Rect, GUIContent, GameObject } from \"UnityEngine\";\r\n    /** Editor utility functions.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class EditorUtility extends Object {\r\n        /** Displays the \"open file\" dialog and returns the selected path name.\r\n         */\r\n        static OpenFilePanel(title: string, directory: string, extension: string): string\r\n        /** Displays the \"open file\" dialog and returns the selected path name.\r\n         * @param title Title for dialog.\r\n         * @param directory Default directory.\r\n         * @param filters File extensions in form { \"Image files\", \"png,jpg,jpeg\", \"All files\", \"*\" }.\r\n         */\r\n        static OpenFilePanelWithFilters(title: string, directory: string, filters: Array<string>): string\r\n        static RevealInFinder(path: string): void\r\n        /** This method displays a modal dialog that lets the user opt-out of being shown the current dialog box again.\r\n         * @param title The title of the message box.\r\n         * @param message The text of the message.\r\n         * @param ok Label displayed on the OK dialog button.\r\n         * @param cancel Label displayed on the Cancel dialog button.\r\n         * @param dialogOptOutDecisionType The type of opt-out decision a user can make.\r\n         * @param dialogOptOutDecisionStorageKey The unique key setting to store the decision under.\r\n         * @returns true if the user clicks the ok button, or previously opted out. Returns false if the user cancels or closes the dialog without making a decision. \r\n         */\r\n        static DisplayDialog(title: string, message: string, ok: string, cancel: string, dialogOptOutDecisionType: DialogOptOutDecisionType, dialogOptOutDecisionStorageKey: string): boolean\r\n        /** This method displays a modal dialog that lets the user opt-out of being shown the current dialog box again.\r\n         * @param title The title of the message box.\r\n         * @param message The text of the message.\r\n         * @param ok Label displayed on the OK dialog button.\r\n         * @param cancel Label displayed on the Cancel dialog button.\r\n         * @param dialogOptOutDecisionType The type of opt-out decision a user can make.\r\n         * @param dialogOptOutDecisionStorageKey The unique key setting to store the decision under.\r\n         * @returns true if the user clicks the ok button, or previously opted out. Returns false if the user cancels or closes the dialog without making a decision. \r\n         */\r\n        static DisplayDialog(title: string, message: string, ok: string, dialogOptOutDecisionType: DialogOptOutDecisionType, dialogOptOutDecisionStorageKey: string): boolean\r\n        /** This method displays a modal dialog.\r\n         * @param title The title of the message box.\r\n         * @param message The text of the message.\r\n         * @param ok Label displayed on the OK dialog button.\r\n         * @param cancel Label displayed on the Cancel dialog button.\r\n         * @returns Returns true if the user clicks the OK button. Returns false otherwise. \r\n         */\r\n        static DisplayDialog(title: string, message: string, ok: string, cancel: string): boolean\r\n        /** This method displays a modal dialog.\r\n         * @param title The title of the message box.\r\n         * @param message The text of the message.\r\n         * @param ok Label displayed on the OK dialog button.\r\n         * @param cancel Label displayed on the Cancel dialog button.\r\n         * @returns Returns true if the user clicks the OK button. Returns false otherwise. \r\n         */\r\n        static DisplayDialog(title: string, message: string, ok: string): boolean\r\n        /** Displays a modal dialog with three buttons.\r\n         * @param title Title for dialog.\r\n         * @param message Purpose for the dialog.\r\n         * @param ok Dialog function chosen.\r\n         * @param cancel Close dialog with no operation.\r\n         * @param alt Choose alternative dialog purpose.\r\n         * @returns Returns the id of the chosen button. The ids are 0, 1 or 2 corresponding to the ok, cancel and alt buttons respectively. \r\n         */\r\n        static DisplayDialogComplex(title: string, message: string, ok: string, cancel: string, alt: string): number\r\n        /** Displays the \"open folder\" dialog and returns the selected path name.\r\n         */\r\n        static OpenFolderPanel(title: string, folder: string, defaultName: string): string\r\n        /** Displays the \"save folder\" dialog and returns the selected path name.\r\n         */\r\n        static SaveFolderPanel(title: string, folder: string, defaultName: string): string\r\n        static WarnPrefab(target: Object1, title: string, warning: string, okButton: string): boolean\r\n        /** Determines if an object is stored on disk.\r\n         */\r\n        static IsPersistent(target: Object1): boolean\r\n        /** Displays the \"save file\" dialog and returns the selected path name.\r\n         */\r\n        static SaveFilePanel(title: string, directory: string, defaultName: string, extension: string): string\r\n        /** Human-like sorting.\r\n         */\r\n        static NaturalCompare(a: string, b: string): number\r\n        /** Translates an instance ID to a reference to an object.\r\n         */\r\n        static InstanceIDToObject(instanceID: number): Object1\r\n        /** Compress a texture.\r\n         */\r\n        static CompressTexture(texture: Texture2D, format: any, quality: number): void\r\n        /** Compress a texture.\r\n         */\r\n        static CompressTexture(texture: Texture2D, format: any, quality: TextureCompressionQuality): void\r\n        /** Compress a cubemap texture.\r\n         */\r\n        static CompressCubemapTexture(texture: any, format: any, quality: number): void\r\n        /** Compress a cubemap texture.\r\n         */\r\n        static CompressCubemapTexture(texture: any, format: any, quality: TextureCompressionQuality): void\r\n        /** Marks target object as dirty.\r\n         * @param target The object to mark as dirty.\r\n         */\r\n        static SetDirty(target: Object1): void\r\n        /** Clear target's dirty flag.\r\n         */\r\n        static ClearDirty(target: Object1): void\r\n        static InvokeDiffTool(leftTitle: string, leftFile: string, rightTitle: string, rightFile: string, ancestorTitle: string, ancestorFile: string): string\r\n        /** Copy all settings of a Unity Object.\r\n         */\r\n        static CopySerialized(source: Object1, dest: Object1): void\r\n        /** Copies the serializable fields from one managed object to another.\r\n         * @param source The object to copy data from.\r\n         * @param dest The object to copy data to.\r\n         */\r\n        static CopySerializedManagedFieldsOnly(source: Object, dest: Object): void\r\n        /** Calculates and returns a list of all assets the assets listed in roots depend on.\r\n         */\r\n        static CollectDependencies(roots: Array<Object1>): Array<Object1>\r\n        /** Collect all objects in the hierarchy rooted at each of the given objects.\r\n         * @param roots Array of objects where the search will start.\r\n         * @returns Array of objects heirarchically attached to the search array. \r\n         */\r\n        static CollectDeepHierarchy(roots: Array<Object1>): Array<Object1>\r\n        static FormatBytes(bytes: number): string\r\n        /** Returns a text for a number of bytes.\r\n         */\r\n        static FormatBytes(bytes: number): string\r\n        /** Displays or updates a progress bar.\r\n         */\r\n        static DisplayProgressBar(title: string, info: string, progress: number): void\r\n        /** Displays or updates a progress bar that has a cancel button.\r\n         */\r\n        static DisplayCancelableProgressBar(title: string, info: string, progress: number): boolean\r\n        static ClearProgressBar(): void\r\n        /** Is the object enabled (0 disabled, 1 enabled, -1 has no enabled button).\r\n         */\r\n        static GetObjectEnabled(target: Object1): number\r\n        /** Set the enabled state of the object.\r\n         */\r\n        static SetObjectEnabled(target: Object1, enabled: boolean): void\r\n        /** Set the Scene View selected display mode for this Renderer.\r\n         */\r\n        static SetSelectedRenderState(renderer: Renderer, renderState: EditorSelectedRenderState): void\r\n        static OpenWithDefaultApp(fileName: string): void\r\n        /** Sets this camera to allow animation of materials in the Editor.\r\n         */\r\n        static SetCameraAnimateMaterials(camera: Camera, animate: boolean): void\r\n        /** Sets the global time for this camera to use when rendering.\r\n         */\r\n        static SetCameraAnimateMaterialsTime(camera: Camera, time: number): void\r\n        /** Updates the global shader properties to use when rendering.\r\n         * @param time Time to use. -1 to disable.\r\n         */\r\n        static UpdateGlobalShaderProperties(time: number): void\r\n        /** Returns an integer that indicates the number of times the specified object's serialized properties have changed.\r\n         * @param instanceID The object's instance ID.\r\n         * @param target The object.\r\n         */\r\n        static GetDirtyCount(instanceID: number): number\r\n        /** Returns an integer that indicates the number of times the specified object's serialized properties have changed.\r\n         * @param instanceID The object's instance ID.\r\n         * @param target The object.\r\n         */\r\n        static GetDirtyCount(target: Object1): number\r\n        /** Gets a boolean value that indicates whether the specified object has changed since the last time it was saved.\r\n         * @param instanceID The object's instance ID.\r\n         * @param target The object.\r\n         * @returns True if the object has changed; otherwise false. \r\n         */\r\n        static IsDirty(instanceID: number): boolean\r\n        /** Gets a boolean value that indicates whether the specified object has changed since the last time it was saved.\r\n         * @param instanceID The object's instance ID.\r\n         * @param target The object.\r\n         * @returns True if the object has changed; otherwise false. \r\n         */\r\n        static IsDirty(target: Object1): boolean\r\n        static FocusProjectWindow(): void\r\n        static RequestScriptReload(): void\r\n        static IsRunningUnderCPUEmulation(): boolean\r\n        static LoadWindowLayout(path: string): boolean\r\n        static SaveFilePanelInProject(title: string, defaultName: string, extension: string, message: string, path: string): string\r\n        /** Displays the \"save file\" dialog in the Assets folder of the project and returns the selected path name.\r\n         */\r\n        static SaveFilePanelInProject(title: string, defaultName: string, extension: string, message: string): string\r\n        /** Copy all settings of a Unity Object to a second Object if they differ.\r\n         */\r\n        static CopySerializedIfDifferent(source: Object1, dest: Object1): void\r\n        static UnloadUnusedAssetsImmediate(includeMonoReferencesAsRoots: boolean): void\r\n        static UnloadUnusedAssetsImmediate(): void\r\n        /** This method displays a modal dialog that lets the user opt-out of being shown the current dialog box again.\r\n         * @param dialogOptOutDecisionType The type of opt-out decision a user can make.\r\n         * @param dialogOptOutDecisionStorageKey The unique key setting to store the decision under.\r\n         * @returns true if the user previously opted out of seeing the dialog associated with dialogOptOutDecisionStorageKey. Returns false if the user did not yet opt out. \r\n         */\r\n        static GetDialogOptOutDecision(dialogOptOutDecisionType: DialogOptOutDecisionType, dialogOptOutDecisionStorageKey: string): boolean\r\n        /** This method displays a modal dialog that lets the user opt-out of being shown the current dialog box again.\r\n         * @param dialogOptOutDecisionType The type of opt-out decision a user can make.\r\n         * @param dialogOptOutDecisionStorageKey The unique key setting to store the decision under.\r\n         * @param optOutDecision The unique key setting to store the decision under.\r\n         */\r\n        static SetDialogOptOutDecision(dialogOptOutDecisionType: DialogOptOutDecisionType, dialogOptOutDecisionStorageKey: string, optOutDecision: boolean): void\r\n        /** Displays a popup menu.\r\n         */\r\n        static DisplayPopupMenu(position: Rect, menuItemPath: string, command: MenuCommand): void\r\n        static DisplayCustomMenu(position: Rect, options: Array<GUIContent>, checkEnabled: (arg: number) => boolean, selected: number, callback: (userData: Object, options: Array<string>, selected: number) => void, userData: Object, showHotkey: boolean): void\r\n        static DisplayCustomMenu(position: Rect, options: Array<GUIContent>, selected: number, callback: (userData: Object, options: Array<string>, selected: number) => void, userData: Object, showHotkey: boolean): void\r\n        static DisplayCustomMenu(position: Rect, options: Array<GUIContent>, selected: number, callback: (userData: Object, options: Array<string>, selected: number) => void, userData: Object): void\r\n        /** Creates a game object with HideFlags and specified components.\r\n         */\r\n        static CreateGameObjectWithHideFlags(name: string, flags: any, ...components: any[]): GameObject\r\n        static CompileCSharp(sources: Array<string>, references: Array<string>, defines: Array<string>, outputFile: string): Array<string>\r\n        static DisplayCustomMenuWithSeparators(position: Rect, options: Array<string>, enabled: Array<boolean>, separator: Array<boolean>, selected: Array<number>, callback: (userData: Object, options: Array<string>, selected: number) => void, userData: Object): void\r\n        /** Sets the default parent object for the active Scene.\r\n         * @param defaultParentObject The GameObject to set as the default parent object.\r\n         */\r\n        static SetDefaultParentObject(defaultParentObject: GameObject): void\r\n        /** Clears the default parent GameObject from either a specific Scene or the active Scene.\r\n         * @param scene Specify a Scene to clear the default parent object for a specific Scene. If a Scene is not specified, this method clears the default parent object for the active Scene.\r\n         */\r\n        static ClearDefaultParentObject(scene: any): void\r\n        static ClearDefaultParentObject(): void\r\n        protected constructor()\r\n        static audioMasterMute: boolean\r\n        /** True if there are any compilation error messages in the log.\r\n         */\r\n        static readonly scriptCompilationFailed: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array, Enum } from \"System\";\r\n    import { Rect, GUIStyle, GUIContent, Object as Object1, Vector2, Vector3, Vector4, Vector2Int, Vector3Int, RectInt, Bounds, BoundsInt, Color, AnimationCurve, FocusType, Texture, ScaleMode, Material, Gradient } from \"UnityEngine\";\r\n    /** These work pretty much like the normal GUI functions - and also have matching implementations in EditorGUILayout.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class EditorGUI extends Object {\r\n        /** Move keyboard focus to a named text field and begin editing of the content.\r\n         * @param name Name set using GUI.SetNextControlName.\r\n         */\r\n        static FocusTextInControl(name: string): void\r\n        /** Create a group of controls that can be disabled.\r\n         * @param disabled Boolean specifying if the controls inside the group should be disabled.\r\n         */\r\n        static BeginDisabledGroup(disabled: boolean): void\r\n        static EndDisabledGroup(): void\r\n        static BeginChangeCheck(): void\r\n        static EndChangeCheck(): boolean\r\n        /** Draws a label with a drop shadow.\r\n         * @param position Where to show the label.\r\n         * @param content Text to show\n@style style to use.\r\n         */\r\n        static DropShadowLabel(position: Rect, text: string, style: GUIStyle): void\r\n        /** Draws a label with a drop shadow.\r\n         * @param position Where to show the label.\r\n         * @param content Text to show\n@style style to use.\r\n         */\r\n        static DropShadowLabel(position: Rect, content: GUIContent, style: GUIStyle): void\r\n        /** Draws a label with a drop shadow.\r\n         * @param position Where to show the label.\r\n         * @param content Text to show\n@style style to use.\r\n         */\r\n        static DropShadowLabel(position: Rect, text: string): void\r\n        /** Draws a label with a drop shadow.\r\n         * @param position Where to show the label.\r\n         * @param content Text to show\n@style style to use.\r\n         */\r\n        static DropShadowLabel(position: Rect, content: GUIContent): void\r\n        /** Makes a toggle.\r\n         * @param position Rectangle on the screen to use for the toggle.\r\n         * @param label Optional label in front of the toggle.\r\n         * @param value The shown state of the toggle.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The selected state of the toggle. \r\n         */\r\n        static Toggle(position: Rect, label: string, value: boolean, style: GUIStyle): boolean\r\n        /** Makes a toggle.\r\n         * @param position Rectangle on the screen to use for the toggle.\r\n         * @param label Optional label in front of the toggle.\r\n         * @param value The shown state of the toggle.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The selected state of the toggle. \r\n         */\r\n        static Toggle(position: Rect, label: GUIContent, value: boolean, style: GUIStyle): boolean\r\n        /** Makes a toggle.\r\n         * @param position Rectangle on the screen to use for the toggle.\r\n         * @param label Optional label in front of the toggle.\r\n         * @param value The shown state of the toggle.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The selected state of the toggle. \r\n         */\r\n        static Toggle(position: Rect, label: string, value: boolean): boolean\r\n        /** Makes a toggle.\r\n         * @param position Rectangle on the screen to use for the toggle.\r\n         * @param label Optional label in front of the toggle.\r\n         * @param value The shown state of the toggle.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The selected state of the toggle. \r\n         */\r\n        static Toggle(position: Rect, value: boolean, style: GUIStyle): boolean\r\n        /** Makes a toggle.\r\n         * @param position Rectangle on the screen to use for the toggle.\r\n         * @param label Optional label in front of the toggle.\r\n         * @param value The shown state of the toggle.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The selected state of the toggle. \r\n         */\r\n        static Toggle(position: Rect, label: GUIContent, value: boolean): boolean\r\n        /** Makes a toggle.\r\n         * @param position Rectangle on the screen to use for the toggle.\r\n         * @param label Optional label in front of the toggle.\r\n         * @param value The shown state of the toggle.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The selected state of the toggle. \r\n         */\r\n        static Toggle(position: Rect, value: boolean): boolean\r\n        /** Makes a slider the user can drag to change a value between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param label Optional label in front of the slider.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static Slider(position: Rect, label: string, value: number, leftValue: number, rightValue: number): number\r\n        /** Makes a slider the user can drag to change a value between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param label Optional label in front of the slider.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static Slider(position: Rect, label: GUIContent, value: number, leftValue: number, rightValue: number): number\r\n        /** Makes a slider the user can drag to change a value between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param label Optional label in front of the slider.\r\n         * @param property The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         */\r\n        static Slider(position: Rect, property: SerializedProperty, leftValue: number, rightValue: number, label: string): void\r\n        /** Makes a slider the user can drag to change a value between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param label Optional label in front of the slider.\r\n         * @param property The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         */\r\n        static Slider(position: Rect, property: SerializedProperty, leftValue: number, rightValue: number, label: GUIContent): void\r\n        /** Makes a slider the user can drag to change a value between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param label Optional label in front of the slider.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static Slider(position: Rect, value: number, leftValue: number, rightValue: number): number\r\n        /** Makes a slider the user can drag to change a value between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param label Optional label in front of the slider.\r\n         * @param property The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         */\r\n        static Slider(position: Rect, property: SerializedProperty, leftValue: number, rightValue: number): void\r\n        /** Makes a slider the user can drag to change an integer value between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param label Optional label in front of the slider.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static IntSlider(position: Rect, label: string, value: number, leftValue: number, rightValue: number): number\r\n        /** Makes a slider the user can drag to change an integer value between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param label Optional label in front of the slider.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static IntSlider(position: Rect, label: GUIContent, value: number, leftValue: number, rightValue: number): number\r\n        /** Makes a slider the user can drag to change a value between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param label Optional label in front of the slider.\r\n         * @param property The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         */\r\n        static IntSlider(position: Rect, property: SerializedProperty, leftValue: number, rightValue: number, label: string): void\r\n        /** Makes a slider the user can drag to change a value between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param label Optional label in front of the slider.\r\n         * @param property The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         */\r\n        static IntSlider(position: Rect, property: SerializedProperty, leftValue: number, rightValue: number, label: GUIContent): void\r\n        /** Makes a slider the user can drag to change an integer value between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param label Optional label in front of the slider.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static IntSlider(position: Rect, value: number, leftValue: number, rightValue: number): number\r\n        /** Makes a slider the user can drag to change a value between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param label Optional label in front of the slider.\r\n         * @param property The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         */\r\n        static IntSlider(position: Rect, property: SerializedProperty, leftValue: number, rightValue: number): void\r\n        /** Makes a special slider the user can use to specify a range between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param label Optional label in front of the slider.\r\n         * @param minValue The lower value of the range the slider shows, passed by reference.\r\n         * @param maxValue The upper value at the range the slider shows, passed by reference.\r\n         * @param minLimit The limit at the left end of the slider.\r\n         * @param maxLimit The limit at the right end of the slider.\r\n         */\r\n        static MinMaxSlider(position: Rect, label: string, minValue: jsb.Ref<number>, maxValue: jsb.Ref<number>, minLimit: number, maxLimit: number): void\r\n        /** Makes a special slider the user can use to specify a range between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param label Optional label in front of the slider.\r\n         * @param minValue The lower value of the range the slider shows, passed by reference.\r\n         * @param maxValue The upper value at the range the slider shows, passed by reference.\r\n         * @param minLimit The limit at the left end of the slider.\r\n         * @param maxLimit The limit at the right end of the slider.\r\n         */\r\n        static MinMaxSlider(position: Rect, label: GUIContent, minValue: jsb.Ref<number>, maxValue: jsb.Ref<number>, minLimit: number, maxLimit: number): void\r\n        /** Makes a special slider the user can use to specify a range between a min and a max.\r\n         * @param position Rectangle on the screen to use for the slider.\r\n         * @param label Optional label in front of the slider.\r\n         * @param minValue The lower value of the range the slider shows, passed by reference.\r\n         * @param maxValue The upper value at the range the slider shows, passed by reference.\r\n         * @param minLimit The limit at the left end of the slider.\r\n         * @param maxLimit The limit at the right end of the slider.\r\n         */\r\n        static MinMaxSlider(position: Rect, minValue: jsb.Ref<number>, maxValue: jsb.Ref<number>, minLimit: number, maxLimit: number): void\r\n        /** Displays a menu with an option for every value of the enum type when clicked. An option for the value 0 with name \"Nothing\" and an option for the value ~0 (that is, all bits set) with the name \"Everything\" are always displayed at the top of the menu. The names for the values 0 and ~0 can be overriden by defining these values in the enum type.\r\n         * @param position Rectangle on the screen to use for the enum flags field.\r\n         * @param label Optional label to display in front of the enum flags field.\r\n         * @param enumValue Enum flags value (Only supports enum values for enum types with int as the underlying type).\r\n         * @param style Optional GUIStyle.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @returns The enum flags value modified by the user. This is a selection BitMask where each bit represents an Enum value index. (Note this returned value is not itself an Enum). \r\n         */\r\n        static EnumFlagsField(position: Rect, label: GUIContent, enumValue: Enum, includeObsolete: boolean, style: GUIStyle): Enum\r\n        /** Displays a menu with an option for every value of the enum type when clicked. An option for the value 0 with name \"Nothing\" and an option for the value ~0 (that is, all bits set) with the name \"Everything\" are always displayed at the top of the menu. The names for the values 0 and ~0 can be overriden by defining these values in the enum type.\r\n         * @param position Rectangle on the screen to use for the enum flags field.\r\n         * @param label Optional label to display in front of the enum flags field.\r\n         * @param enumValue Enum flags value (Only supports enum values for enum types with int as the underlying type).\r\n         * @param style Optional GUIStyle.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @returns The enum flags value modified by the user. This is a selection BitMask where each bit represents an Enum value index. (Note this returned value is not itself an Enum). \r\n         */\r\n        static EnumFlagsField(position: Rect, label: string, enumValue: Enum, style: GUIStyle): Enum\r\n        /** Displays a menu with an option for every value of the enum type when clicked. An option for the value 0 with name \"Nothing\" and an option for the value ~0 (that is, all bits set) with the name \"Everything\" are always displayed at the top of the menu. The names for the values 0 and ~0 can be overriden by defining these values in the enum type.\r\n         * @param position Rectangle on the screen to use for the enum flags field.\r\n         * @param label Optional label to display in front of the enum flags field.\r\n         * @param enumValue Enum flags value (Only supports enum values for enum types with int as the underlying type).\r\n         * @param style Optional GUIStyle.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @returns The enum flags value modified by the user. This is a selection BitMask where each bit represents an Enum value index. (Note this returned value is not itself an Enum). \r\n         */\r\n        static EnumFlagsField(position: Rect, label: GUIContent, enumValue: Enum, style: GUIStyle): Enum\r\n        /** Displays a menu with an option for every value of the enum type when clicked. An option for the value 0 with name \"Nothing\" and an option for the value ~0 (that is, all bits set) with the name \"Everything\" are always displayed at the top of the menu. The names for the values 0 and ~0 can be overriden by defining these values in the enum type.\r\n         * @param position Rectangle on the screen to use for the enum flags field.\r\n         * @param label Optional label to display in front of the enum flags field.\r\n         * @param enumValue Enum flags value (Only supports enum values for enum types with int as the underlying type).\r\n         * @param style Optional GUIStyle.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @returns The enum flags value modified by the user. This is a selection BitMask where each bit represents an Enum value index. (Note this returned value is not itself an Enum). \r\n         */\r\n        static EnumFlagsField(position: Rect, enumValue: Enum, style: GUIStyle): Enum\r\n        /** Displays a menu with an option for every value of the enum type when clicked. An option for the value 0 with name \"Nothing\" and an option for the value ~0 (that is, all bits set) with the name \"Everything\" are always displayed at the top of the menu. The names for the values 0 and ~0 can be overriden by defining these values in the enum type.\r\n         * @param position Rectangle on the screen to use for the enum flags field.\r\n         * @param label Optional label to display in front of the enum flags field.\r\n         * @param enumValue Enum flags value (Only supports enum values for enum types with int as the underlying type).\r\n         * @param style Optional GUIStyle.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @returns The enum flags value modified by the user. This is a selection BitMask where each bit represents an Enum value index. (Note this returned value is not itself an Enum). \r\n         */\r\n        static EnumFlagsField(position: Rect, label: string, enumValue: Enum): Enum\r\n        /** Displays a menu with an option for every value of the enum type when clicked. An option for the value 0 with name \"Nothing\" and an option for the value ~0 (that is, all bits set) with the name \"Everything\" are always displayed at the top of the menu. The names for the values 0 and ~0 can be overriden by defining these values in the enum type.\r\n         * @param position Rectangle on the screen to use for the enum flags field.\r\n         * @param label Optional label to display in front of the enum flags field.\r\n         * @param enumValue Enum flags value (Only supports enum values for enum types with int as the underlying type).\r\n         * @param style Optional GUIStyle.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @returns The enum flags value modified by the user. This is a selection BitMask where each bit represents an Enum value index. (Note this returned value is not itself an Enum). \r\n         */\r\n        static EnumFlagsField(position: Rect, label: GUIContent, enumValue: Enum): Enum\r\n        /** Displays a menu with an option for every value of the enum type when clicked. An option for the value 0 with name \"Nothing\" and an option for the value ~0 (that is, all bits set) with the name \"Everything\" are always displayed at the top of the menu. The names for the values 0 and ~0 can be overriden by defining these values in the enum type.\r\n         * @param position Rectangle on the screen to use for the enum flags field.\r\n         * @param label Optional label to display in front of the enum flags field.\r\n         * @param enumValue Enum flags value (Only supports enum values for enum types with int as the underlying type).\r\n         * @param style Optional GUIStyle.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @returns The enum flags value modified by the user. This is a selection BitMask where each bit represents an Enum value index. (Note this returned value is not itself an Enum). \r\n         */\r\n        static EnumFlagsField(position: Rect, enumValue: Enum): Enum\r\n        static ObjectField(position: Rect, label: string, obj: Object1, objType: any, targetBeingEdited: Object1): Object1\r\n        /** Makes an object field. You can assign objects either by drag and drop objects or by selecting an object using the Object Picker.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param obj The object the field shows.\r\n         * @param objType The type of the objects that can be assigned.\r\n         * @param allowSceneObjects Allow assigning Scene objects. See Description for more info.\r\n         * @returns The object that has been set by the user. \r\n         */\r\n        static ObjectField(position: Rect, label: string, obj: Object1, objType: any, allowSceneObjects: boolean): Object1\r\n        static ObjectField(position: Rect, label: GUIContent, obj: Object1, objType: any, targetBeingEdited: Object1): Object1\r\n        /** Makes an object field. You can assign objects either by drag and drop objects or by selecting an object using the Object Picker.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param obj The object the field shows.\r\n         * @param objType The type of the objects that can be assigned.\r\n         * @param allowSceneObjects Allow assigning Scene objects. See Description for more info.\r\n         * @returns The object that has been set by the user. \r\n         */\r\n        static ObjectField(position: Rect, label: GUIContent, obj: Object1, objType: any, allowSceneObjects: boolean): Object1\r\n        /** Makes an object field. You can assign objects either by drag and drop objects or by selecting an object using the Object Picker.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param property The object reference property the field shows.\r\n         * @param objType The type of the objects that can be assigned.\r\n         * @param label Optional label to display in front of the field. Pass GUIContent.none to hide the label.\r\n         */\r\n        static ObjectField(position: Rect, property: SerializedProperty, objType: any, label: GUIContent): void\r\n        static ObjectField(position: Rect, obj: Object1, objType: any, targetBeingEdited: Object1): Object1\r\n        /** Makes an object field. You can assign objects either by drag and drop objects or by selecting an object using the Object Picker.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param obj The object the field shows.\r\n         * @param objType The type of the objects that can be assigned.\r\n         * @param allowSceneObjects Allow assigning Scene objects. See Description for more info.\r\n         * @returns The object that has been set by the user. \r\n         */\r\n        static ObjectField(position: Rect, obj: Object1, objType: any, allowSceneObjects: boolean): Object1\r\n        /** Makes an object field. You can assign objects either by drag and drop objects or by selecting an object using the Object Picker.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param property The object reference property the field shows.\r\n         * @param objType The type of the objects that can be assigned.\r\n         * @param label Optional label to display in front of the field. Pass GUIContent.none to hide the label.\r\n         */\r\n        static ObjectField(position: Rect, property: SerializedProperty, label: GUIContent): void\r\n        /** Makes an object field. You can assign objects either by drag and drop objects or by selecting an object using the Object Picker.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param property The object reference property the field shows.\r\n         * @param objType The type of the objects that can be assigned.\r\n         * @param label Optional label to display in front of the field. Pass GUIContent.none to hide the label.\r\n         */\r\n        static ObjectField(position: Rect, property: SerializedProperty, objType: any): void\r\n        /** Makes an object field. You can assign objects either by drag and drop objects or by selecting an object using the Object Picker.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param property The object reference property the field shows.\r\n         * @param objType The type of the objects that can be assigned.\r\n         * @param label Optional label to display in front of the field. Pass GUIContent.none to hide the label.\r\n         */\r\n        static ObjectField(position: Rect, property: SerializedProperty): void\r\n        static IndentedRect(source: Rect): Rect\r\n        /** Makes an X and Y field for entering a Vector2.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector2Field(position: Rect, label: string, value: Vector2): Vector2\r\n        /** Makes an X and Y field for entering a Vector2.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector2Field(position: Rect, label: GUIContent, value: Vector2): Vector2\r\n        /** Makes an X, Y, and Z field for entering a Vector3.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector3Field(position: Rect, label: string, value: Vector3): Vector3\r\n        /** Makes an X, Y, and Z field for entering a Vector3.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector3Field(position: Rect, label: GUIContent, value: Vector3): Vector3\r\n        /** Makes an X, Y, Z, and W field for entering a Vector4.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector4Field(position: Rect, label: string, value: Vector4): Vector4\r\n        static Vector4Field(position: Rect, label: GUIContent, value: Vector4): Vector4\r\n        /** Makes an X and Y integer field for entering a Vector2Int.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector2IntField(position: Rect, label: string, value: Vector2Int): Vector2Int\r\n        /** Makes an X and Y integer field for entering a Vector2Int.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector2IntField(position: Rect, label: GUIContent, value: Vector2Int): Vector2Int\r\n        /** Makes an X, Y, and Z integer field for entering a Vector3Int.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector3IntField(position: Rect, label: string, value: Vector3Int): Vector3Int\r\n        /** Makes an X, Y, and Z integer field for entering a Vector3Int.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector3IntField(position: Rect, label: GUIContent, value: Vector3Int): Vector3Int\r\n        /** Makes an X, Y, W, and H field for entering a Rect.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static RectField(position: Rect, label: string, value: Rect): Rect\r\n        /** Makes an X, Y, W, and H field for entering a Rect.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static RectField(position: Rect, label: GUIContent, value: Rect): Rect\r\n        /** Makes an X, Y, W, and H field for entering a Rect.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static RectField(position: Rect, value: Rect): Rect\r\n        /** Makes an X, Y, W, and H field for entering a RectInt.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static RectIntField(position: Rect, label: string, value: RectInt): RectInt\r\n        /** Makes an X, Y, W, and H field for entering a RectInt.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static RectIntField(position: Rect, label: GUIContent, value: RectInt): RectInt\r\n        /** Makes an X, Y, W, and H field for entering a RectInt.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static RectIntField(position: Rect, value: RectInt): RectInt\r\n        static BoundsField(position: Rect, label: string, value: Bounds): Bounds\r\n        /** Makes Center and Extents field for entering a Bounds.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static BoundsField(position: Rect, label: GUIContent, value: Bounds): Bounds\r\n        /** Makes Center and Extents field for entering a Bounds.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static BoundsField(position: Rect, value: Bounds): Bounds\r\n        /** Makes Position and Size field for entering a BoundsInt.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static BoundsIntField(position: Rect, label: string, value: BoundsInt): BoundsInt\r\n        /** Makes Position and Size field for entering a BoundsInt.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static BoundsIntField(position: Rect, label: GUIContent, value: BoundsInt): BoundsInt\r\n        /** Makes Position and Size field for entering a BoundsInt.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display above the field.\r\n         * @param value The value to edit.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static BoundsIntField(position: Rect, value: BoundsInt): BoundsInt\r\n        /** Makes a multi-control with text fields for entering multiple floats in the same line.\r\n         * @param position Rectangle on the screen to use for the float field.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param subLabels Array with small labels to show in front of each float field. There is room for one letter per field only.\r\n         * @param values Array with the values to edit.\r\n         */\r\n        static MultiFloatField(position: Rect, label: GUIContent, subLabels: Array<GUIContent>, values: Array<number>): void\r\n        /** Makes a multi-control with text fields for entering multiple floats in the same line.\r\n         * @param position Rectangle on the screen to use for the float field.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param subLabels Array with small labels to show in front of each float field. There is room for one letter per field only.\r\n         * @param values Array with the values to edit.\r\n         */\r\n        static MultiFloatField(position: Rect, subLabels: Array<GUIContent>, values: Array<number>): void\r\n        /** Makes a multi-control with text fields for entering multiple integers in the same line.\r\n         * @param position Rectangle on the screen to use for the integer field.\r\n         * @param subLabels Array with small labels to show in front of each int field. There is room for one letter per field only.\r\n         * @param values Array with the values to edit.\r\n         */\r\n        static MultiIntField(position: Rect, subLabels: Array<GUIContent>, values: Array<number>): void\r\n        /** Makes a multi-control with several property fields in the same line.\r\n         * @param position Rectangle on the screen to use for the multi-property field.\r\n         * @param valuesIterator The SerializedProperty of the first property to make a control for.\r\n         * @param label Optional label to use. If not specified the label of the property itself is used. Use GUIContent.none to not display a label at all.\r\n         * @param subLabels Array with small labels to show in front of each float field. There is room for one letter per field only.\r\n         */\r\n        static MultiPropertyField(position: Rect, subLabels: Array<GUIContent>, valuesIterator: SerializedProperty, label: GUIContent): void\r\n        /** Makes a multi-control with several property fields in the same line.\r\n         * @param position Rectangle on the screen to use for the multi-property field.\r\n         * @param valuesIterator The SerializedProperty of the first property to make a control for.\r\n         * @param label Optional label to use. If not specified the label of the property itself is used. Use GUIContent.none to not display a label at all.\r\n         * @param subLabels Array with small labels to show in front of each float field. There is room for one letter per field only.\r\n         */\r\n        static MultiPropertyField(position: Rect, subLabels: Array<GUIContent>, valuesIterator: SerializedProperty): void\r\n        /** Makes a field for selecting a Color.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The color to edit.\r\n         * @param showEyedropper If true, the color picker should show the eyedropper control. If false, don't show it.\r\n         * @param showAlpha If true, allow the user to set an alpha value for the color. If false, hide the alpha component.\r\n         * @param hdr If true, treat the color as an HDR value. If false, treat it as a standard LDR value.\r\n         * @returns The color selected by the user. \r\n         */\r\n        static ColorField(position: Rect, label: GUIContent, value: Color, showEyedropper: boolean, showAlpha: boolean, hdr: boolean): Color\r\n        /** Makes a field for selecting a Color.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The color to edit.\r\n         * @param showEyedropper If true, the color picker should show the eyedropper control. If false, don't show it.\r\n         * @param showAlpha If true, allow the user to set an alpha value for the color. If false, hide the alpha component.\r\n         * @param hdr If true, treat the color as an HDR value. If false, treat it as a standard LDR value.\r\n         * @returns The color selected by the user. \r\n         */\r\n        static ColorField(position: Rect, label: string, value: Color): Color\r\n        /** Makes a field for selecting a Color.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The color to edit.\r\n         * @param showEyedropper If true, the color picker should show the eyedropper control. If false, don't show it.\r\n         * @param showAlpha If true, allow the user to set an alpha value for the color. If false, hide the alpha component.\r\n         * @param hdr If true, treat the color as an HDR value. If false, treat it as a standard LDR value.\r\n         * @returns The color selected by the user. \r\n         */\r\n        static ColorField(position: Rect, label: GUIContent, value: Color): Color\r\n        /** Makes a field for selecting a Color.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The color to edit.\r\n         * @param showEyedropper If true, the color picker should show the eyedropper control. If false, don't show it.\r\n         * @param showAlpha If true, allow the user to set an alpha value for the color. If false, hide the alpha component.\r\n         * @param hdr If true, treat the color as an HDR value. If false, treat it as a standard LDR value.\r\n         * @returns The color selected by the user. \r\n         */\r\n        static ColorField(position: Rect, value: Color): Color\r\n        /** Makes a field for editing an AnimationCurve.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The curve to edit.\r\n         * @param color The color to show the curve with.\r\n         * @param ranges Optional rectangle that the curve is restrained within.\r\n         * @returns The curve edited by the user. \r\n         */\r\n        static CurveField(position: Rect, label: string, value: AnimationCurve, color: Color, ranges: Rect): AnimationCurve\r\n        /** Makes a field for editing an AnimationCurve.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The curve to edit.\r\n         * @param color The color to show the curve with.\r\n         * @param ranges Optional rectangle that the curve is restrained within.\r\n         * @returns The curve edited by the user. \r\n         */\r\n        static CurveField(position: Rect, label: GUIContent, value: AnimationCurve, color: Color, ranges: Rect): AnimationCurve\r\n        /** Makes a field for editing an AnimationCurve.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param property The curve to edit.\r\n         * @param color The color to show the curve with.\r\n         * @param ranges Optional rectangle that the curve is restrained within.\r\n         * @param label Optional label to display in front of the field. Pass [[GUIContent.none] to hide the label.\r\n         */\r\n        static CurveField(position: Rect, property: SerializedProperty, color: Color, ranges: Rect, label: GUIContent): void\r\n        /** Makes a field for editing an AnimationCurve.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The curve to edit.\r\n         * @param color The color to show the curve with.\r\n         * @param ranges Optional rectangle that the curve is restrained within.\r\n         * @returns The curve edited by the user. \r\n         */\r\n        static CurveField(position: Rect, value: AnimationCurve, color: Color, ranges: Rect): AnimationCurve\r\n        /** Makes a field for editing an AnimationCurve.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param property The curve to edit.\r\n         * @param color The color to show the curve with.\r\n         * @param ranges Optional rectangle that the curve is restrained within.\r\n         * @param label Optional label to display in front of the field. Pass [[GUIContent.none] to hide the label.\r\n         */\r\n        static CurveField(position: Rect, property: SerializedProperty, color: Color, ranges: Rect): void\r\n        /** Makes a field for editing an AnimationCurve.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The curve to edit.\r\n         * @param color The color to show the curve with.\r\n         * @param ranges Optional rectangle that the curve is restrained within.\r\n         * @returns The curve edited by the user. \r\n         */\r\n        static CurveField(position: Rect, label: string, value: AnimationCurve): AnimationCurve\r\n        /** Makes a field for editing an AnimationCurve.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The curve to edit.\r\n         * @param color The color to show the curve with.\r\n         * @param ranges Optional rectangle that the curve is restrained within.\r\n         * @returns The curve edited by the user. \r\n         */\r\n        static CurveField(position: Rect, label: GUIContent, value: AnimationCurve): AnimationCurve\r\n        /** Makes a field for editing an AnimationCurve.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The curve to edit.\r\n         * @param color The color to show the curve with.\r\n         * @param ranges Optional rectangle that the curve is restrained within.\r\n         * @returns The curve edited by the user. \r\n         */\r\n        static CurveField(position: Rect, value: AnimationCurve): AnimationCurve\r\n        /** Makes an inspector-window-like titlebar.\r\n         * @param position Rectangle on the screen to use for the titlebar.\r\n         * @param foldout The foldout state shown with the arrow.\r\n         * @param targetObj The object (for example a component) that the titlebar is for.\r\n         * @param targetObjs The objects that the titlebar is for.\r\n         * @param expandable Whether this editor should display a foldout arrow in order to toggle the display of its properties.\r\n         * @returns The foldout state selected by the user. \r\n         */\r\n        static InspectorTitlebar(position: Rect, foldout: boolean, targetObj: Object1, expandable: boolean): boolean\r\n        /** Makes an inspector-window-like titlebar.\r\n         * @param position Rectangle on the screen to use for the titlebar.\r\n         * @param foldout The foldout state shown with the arrow.\r\n         * @param targetObj The object (for example a component) that the titlebar is for.\r\n         * @param targetObjs The objects that the titlebar is for.\r\n         * @param expandable Whether this editor should display a foldout arrow in order to toggle the display of its properties.\r\n         * @returns The foldout state selected by the user. \r\n         */\r\n        static InspectorTitlebar(position: Rect, foldout: boolean, targetObjs: Array<Object1>, expandable: boolean): boolean\r\n        static InspectorTitlebar(position: Rect, foldout: boolean, editor: Editor): boolean\r\n        static InspectorTitlebar(position: Rect, targetObjs: Array<Object1>): void\r\n        /** Makes a progress bar.\r\n         * @param totalPosition Rectangle on the screen to use in total for both the control.\r\n         * @param value Value that is shown.\r\n         */\r\n        static ProgressBar(position: Rect, value: number, text: string): void\r\n        /** Makes a help box with a message to the user.\r\n         * @param position Rectangle on the screen to draw the help box within.\r\n         * @param message The message text.\r\n         * @param type The type of message.\r\n         */\r\n        static HelpBox(position: Rect, message: string, type: MessageType): void\r\n        /** Makes a label in front of some control.\r\n         * @param totalPosition Rectangle on the screen to use in total for both the label and the control.\r\n         * @param id The unique ID of the control. If none specified, the ID of the following control is used.\r\n         * @param label Label to show in front of the control.\r\n         * @param style Style to use for the label.\r\n         * @returns Rectangle on the screen to use just for the control itself. \r\n         */\r\n        static PrefixLabel(totalPosition: Rect, id: number, label: GUIContent, style: GUIStyle): Rect\r\n        /** Makes a label in front of some control.\r\n         * @param totalPosition Rectangle on the screen to use in total for both the label and the control.\r\n         * @param id The unique ID of the control. If none specified, the ID of the following control is used.\r\n         * @param label Label to show in front of the control.\r\n         * @param style Style to use for the label.\r\n         * @returns Rectangle on the screen to use just for the control itself. \r\n         */\r\n        static PrefixLabel(totalPosition: Rect, label: GUIContent, style: GUIStyle): Rect\r\n        /** Makes a label in front of some control.\r\n         * @param totalPosition Rectangle on the screen to use in total for both the label and the control.\r\n         * @param id The unique ID of the control. If none specified, the ID of the following control is used.\r\n         * @param label Label to show in front of the control.\r\n         * @param style Style to use for the label.\r\n         * @returns Rectangle on the screen to use just for the control itself. \r\n         */\r\n        static PrefixLabel(totalPosition: Rect, id: number, label: GUIContent): Rect\r\n        /** Makes a label in front of some control.\r\n         * @param totalPosition Rectangle on the screen to use in total for both the label and the control.\r\n         * @param id The unique ID of the control. If none specified, the ID of the following control is used.\r\n         * @param label Label to show in front of the control.\r\n         * @param style Style to use for the label.\r\n         * @returns Rectangle on the screen to use just for the control itself. \r\n         */\r\n        static PrefixLabel(totalPosition: Rect, label: GUIContent): Rect\r\n        /** Create a Property wrapper, useful for making regular GUI controls work with SerializedProperty.\r\n         * @param totalPosition Rectangle on the screen to use for the control, including label if applicable.\r\n         * @param label Optional label in front of the slider. Use null to use the name from the SerializedProperty. Use GUIContent.none to not display a label.\r\n         * @param property The SerializedProperty to use for the control.\r\n         * @returns The actual label to use for the control. \r\n         */\r\n        static BeginProperty(totalPosition: Rect, label: GUIContent, property: SerializedProperty): GUIContent\r\n        static EndProperty(): void\r\n        /** Get the height needed for a PropertyField control.\r\n         * @param property Height of the property area.\r\n         * @param label Descriptive text or image.\r\n         * @param includeChildren Should the returned height include the height of child properties?\r\n         */\r\n        static GetPropertyHeight(property: SerializedProperty, label: GUIContent, includeChildren: boolean): number\r\n        /** Get the height needed for a PropertyField control.\r\n         * @param property Height of the property area.\r\n         * @param label Descriptive text or image.\r\n         * @param includeChildren Should the returned height include the height of child properties?\r\n         */\r\n        static GetPropertyHeight(type: SerializedPropertyType, label: GUIContent): number\r\n        /** Get the height needed for a PropertyField control.\r\n         * @param property Height of the property area.\r\n         * @param label Descriptive text or image.\r\n         * @param includeChildren Should the returned height include the height of child properties?\r\n         */\r\n        static GetPropertyHeight(property: SerializedProperty, includeChildren: boolean): number\r\n        /** Get the height needed for a PropertyField control.\r\n         * @param property Height of the property area.\r\n         * @param label Descriptive text or image.\r\n         * @param includeChildren Should the returned height include the height of child properties?\r\n         */\r\n        static GetPropertyHeight(property: SerializedProperty, label: GUIContent): number\r\n        /** Get the height needed for a PropertyField control.\r\n         * @param property Height of the property area.\r\n         * @param label Descriptive text or image.\r\n         * @param includeChildren Should the returned height include the height of child properties?\r\n         */\r\n        static GetPropertyHeight(property: SerializedProperty): number\r\n        /** Get whether a SerializedProperty's inspector GUI can be cached.\r\n         * @param property The SerializedProperty in question.\r\n         * @returns Whether the property's inspector GUI can be cached. \r\n         */\r\n        static CanCacheInspectorGUI(property: SerializedProperty): boolean\r\n        /** Makes a button that reacts to mouse down, for displaying your own dropdown content.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param focusType Whether the button should be selectable by keyboard or not.\r\n         * @param style Optional style to use.\r\n         * @returns true when the user clicks the button. \r\n         */\r\n        static DropdownButton(position: Rect, content: GUIContent, focusType: FocusType, style: GUIStyle): boolean\r\n        /** Makes a button that reacts to mouse down, for displaying your own dropdown content.\r\n         * @param position Rectangle on the screen to use for the button.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param focusType Whether the button should be selectable by keyboard or not.\r\n         * @param style Optional style to use.\r\n         * @returns true when the user clicks the button. \r\n         */\r\n        static DropdownButton(position: Rect, content: GUIContent, focusType: FocusType): boolean\r\n        /** Draws the alpha channel of a texture within a rectangle.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.\r\n         * @param mipLevel What mip-level to sample. If negative, texture will be sampled normally.\nIt sets material _Mip property.\r\n         */\r\n        static DrawTextureAlpha(position: Rect, image: Texture, scaleMode: ScaleMode, imageAspect: number, mipLevel: number): void\r\n        /** Draws the alpha channel of a texture within a rectangle.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.\r\n         * @param mipLevel What mip-level to sample. If negative, texture will be sampled normally.\nIt sets material _Mip property.\r\n         */\r\n        static DrawTextureAlpha(position: Rect, image: Texture, scaleMode: ScaleMode, imageAspect: number): void\r\n        /** Draws the alpha channel of a texture within a rectangle.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.\r\n         * @param mipLevel What mip-level to sample. If negative, texture will be sampled normally.\nIt sets material _Mip property.\r\n         */\r\n        static DrawTextureAlpha(position: Rect, image: Texture, scaleMode: ScaleMode): void\r\n        /** Draws the alpha channel of a texture within a rectangle.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.\r\n         * @param mipLevel What mip-level to sample. If negative, texture will be sampled normally.\nIt sets material _Mip property.\r\n         */\r\n        static DrawTextureAlpha(position: Rect, image: Texture): void\r\n        static DrawTextureTransparent(position: Rect, image: Texture, scaleMode: ScaleMode, imageAspect: number, mipLevel: number, colorWriteMask: any, exposure: number): void\r\n        static DrawTextureTransparent(position: Rect, image: Texture, scaleMode: ScaleMode, imageAspect: number, mipLevel: number, colorWriteMask: any): void\r\n        static DrawTextureTransparent(position: Rect, image: Texture, scaleMode: ScaleMode, imageAspect: number, mipLevel: number): void\r\n        static DrawTextureTransparent(position: Rect, image: Texture, scaleMode: ScaleMode, imageAspect: number): void\r\n        static DrawTextureTransparent(position: Rect, image: Texture, scaleMode: ScaleMode): void\r\n        static DrawTextureTransparent(position: Rect, image: Texture): void\r\n        /** Draws the texture within a rectangle.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param mat Material to be used when drawing the texture.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.\r\n         * @param mipLevel The mip-level to sample. If negative, the texture is sampled normally.\nSets material's _Mip property.\r\n         * @param colorWriteMask Specifies which color components of image will get written. Sets material's _ColorMask property.\r\n         * @param exposure Specifies the exposure for the texture. Sets material's _Exposure property.\r\n         */\r\n        static DrawPreviewTexture(position: Rect, image: Texture, mat: Material, scaleMode: ScaleMode, imageAspect: number, mipLevel: number, colorWriteMask: any, exposure: number): void\r\n        /** Draws the texture within a rectangle.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param mat Material to be used when drawing the texture.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.\r\n         * @param mipLevel The mip-level to sample. If negative, the texture is sampled normally.\nSets material's _Mip property.\r\n         * @param colorWriteMask Specifies which color components of image will get written. Sets material's _ColorMask property.\r\n         * @param exposure Specifies the exposure for the texture. Sets material's _Exposure property.\r\n         */\r\n        static DrawPreviewTexture(position: Rect, image: Texture, mat: Material, scaleMode: ScaleMode, imageAspect: number, mipLevel: number, colorWriteMask: any): void\r\n        /** Draws the texture within a rectangle.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param mat Material to be used when drawing the texture.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.\r\n         * @param mipLevel The mip-level to sample. If negative, the texture is sampled normally.\nSets material's _Mip property.\r\n         * @param colorWriteMask Specifies which color components of image will get written. Sets material's _ColorMask property.\r\n         * @param exposure Specifies the exposure for the texture. Sets material's _Exposure property.\r\n         */\r\n        static DrawPreviewTexture(position: Rect, image: Texture, mat: Material, scaleMode: ScaleMode, imageAspect: number, mipLevel: number): void\r\n        /** Draws the texture within a rectangle.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param mat Material to be used when drawing the texture.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.\r\n         * @param mipLevel The mip-level to sample. If negative, the texture is sampled normally.\nSets material's _Mip property.\r\n         * @param colorWriteMask Specifies which color components of image will get written. Sets material's _ColorMask property.\r\n         * @param exposure Specifies the exposure for the texture. Sets material's _Exposure property.\r\n         */\r\n        static DrawPreviewTexture(position: Rect, image: Texture, mat: Material, scaleMode: ScaleMode, imageAspect: number): void\r\n        /** Draws the texture within a rectangle.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param mat Material to be used when drawing the texture.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.\r\n         * @param mipLevel The mip-level to sample. If negative, the texture is sampled normally.\nSets material's _Mip property.\r\n         * @param colorWriteMask Specifies which color components of image will get written. Sets material's _ColorMask property.\r\n         * @param exposure Specifies the exposure for the texture. Sets material's _Exposure property.\r\n         */\r\n        static DrawPreviewTexture(position: Rect, image: Texture, mat: Material, scaleMode: ScaleMode): void\r\n        /** Draws the texture within a rectangle.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param mat Material to be used when drawing the texture.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.\r\n         * @param mipLevel The mip-level to sample. If negative, the texture is sampled normally.\nSets material's _Mip property.\r\n         * @param colorWriteMask Specifies which color components of image will get written. Sets material's _ColorMask property.\r\n         * @param exposure Specifies the exposure for the texture. Sets material's _Exposure property.\r\n         */\r\n        static DrawPreviewTexture(position: Rect, image: Texture, mat: Material): void\r\n        /** Draws the texture within a rectangle.\r\n         * @param position Rectangle on the screen to draw the texture within.\r\n         * @param image Texture to display.\r\n         * @param mat Material to be used when drawing the texture.\r\n         * @param scaleMode How to scale the image when the aspect ratio of it doesn't fit the aspect ratio to be drawn within.\r\n         * @param imageAspect Aspect ratio to use for the source image. If 0 (the default), the aspect ratio from the image is used.\r\n         * @param mipLevel The mip-level to sample. If negative, the texture is sampled normally.\nSets material's _Mip property.\r\n         * @param colorWriteMask Specifies which color components of image will get written. Sets material's _ColorMask property.\r\n         * @param exposure Specifies the exposure for the texture. Sets material's _Exposure property.\r\n         */\r\n        static DrawPreviewTexture(position: Rect, image: Texture): void\r\n        /** Makes a label field. (Useful for showing read-only info.)\r\n         * @param position Rectangle on the screen to use for the label field.\r\n         * @param label Label in front of the label field.\r\n         * @param label2 The label to show to the right.\r\n         * @param style Style information (color, etc) for displaying the label.\r\n         */\r\n        static LabelField(position: Rect, label: string, label2: string, style: GUIStyle): void\r\n        /** Makes a label field. (Useful for showing read-only info.)\r\n         * @param position Rectangle on the screen to use for the label field.\r\n         * @param label Label in front of the label field.\r\n         * @param label2 The label to show to the right.\r\n         * @param style Style information (color, etc) for displaying the label.\r\n         */\r\n        static LabelField(position: Rect, label: GUIContent, label2: GUIContent, style: GUIStyle): void\r\n        /** Makes a label field. (Useful for showing read-only info.)\r\n         * @param position Rectangle on the screen to use for the label field.\r\n         * @param label Label in front of the label field.\r\n         * @param label2 The label to show to the right.\r\n         * @param style Style information (color, etc) for displaying the label.\r\n         */\r\n        static LabelField(position: Rect, label: string, style: GUIStyle): void\r\n        /** Makes a label field. (Useful for showing read-only info.)\r\n         * @param position Rectangle on the screen to use for the label field.\r\n         * @param label Label in front of the label field.\r\n         * @param label2 The label to show to the right.\r\n         * @param style Style information (color, etc) for displaying the label.\r\n         */\r\n        static LabelField(position: Rect, label: GUIContent, style: GUIStyle): void\r\n        /** Makes a label field. (Useful for showing read-only info.)\r\n         * @param position Rectangle on the screen to use for the label field.\r\n         * @param label Label in front of the label field.\r\n         * @param label2 The label to show to the right.\r\n         * @param style Style information (color, etc) for displaying the label.\r\n         */\r\n        static LabelField(position: Rect, label: string, label2: string): void\r\n        /** Makes a label field. (Useful for showing read-only info.)\r\n         * @param position Rectangle on the screen to use for the label field.\r\n         * @param label Label in front of the label field.\r\n         * @param label2 The label to show to the right.\r\n         * @param style Style information (color, etc) for displaying the label.\r\n         */\r\n        static LabelField(position: Rect, label: GUIContent, label2: GUIContent): void\r\n        /** Makes a label field. (Useful for showing read-only info.)\r\n         * @param position Rectangle on the screen to use for the label field.\r\n         * @param label Label in front of the label field.\r\n         * @param label2 The label to show to the right.\r\n         * @param style Style information (color, etc) for displaying the label.\r\n         */\r\n        static LabelField(position: Rect, label: string): void\r\n        /** Makes a label field. (Useful for showing read-only info.)\r\n         * @param position Rectangle on the screen to use for the label field.\r\n         * @param label Label in front of the label field.\r\n         * @param label2 The label to show to the right.\r\n         * @param style Style information (color, etc) for displaying the label.\r\n         */\r\n        static LabelField(position: Rect, label: GUIContent): void\r\n        /** Makes a toggle field where the toggle is to the left and the label immediately to the right of it.\r\n         * @param position Rectangle on the screen to use for the toggle.\r\n         * @param label Label to display next to the toggle.\r\n         * @param value The value to edit.\r\n         * @param labelStyle Optional GUIStyle to use for the label.\r\n         * @returns The value set by the user. \r\n         */\r\n        static ToggleLeft(position: Rect, label: string, value: boolean, labelStyle: GUIStyle): boolean\r\n        /** Makes a toggle field where the toggle is to the left and the label immediately to the right of it.\r\n         * @param position Rectangle on the screen to use for the toggle.\r\n         * @param label Label to display next to the toggle.\r\n         * @param value The value to edit.\r\n         * @param labelStyle Optional GUIStyle to use for the label.\r\n         * @returns The value set by the user. \r\n         */\r\n        static ToggleLeft(position: Rect, label: GUIContent, value: boolean, labelStyle: GUIStyle): boolean\r\n        /** Makes a toggle field where the toggle is to the left and the label immediately to the right of it.\r\n         * @param position Rectangle on the screen to use for the toggle.\r\n         * @param label Label to display next to the toggle.\r\n         * @param value The value to edit.\r\n         * @param labelStyle Optional GUIStyle to use for the label.\r\n         * @returns The value set by the user. \r\n         */\r\n        static ToggleLeft(position: Rect, label: string, value: boolean): boolean\r\n        /** Makes a toggle field where the toggle is to the left and the label immediately to the right of it.\r\n         * @param position Rectangle on the screen to use for the toggle.\r\n         * @param label Label to display next to the toggle.\r\n         * @param value The value to edit.\r\n         * @param labelStyle Optional GUIStyle to use for the label.\r\n         * @returns The value set by the user. \r\n         */\r\n        static ToggleLeft(position: Rect, label: GUIContent, value: boolean): boolean\r\n        /** Makes a text field.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param label Optional label to display in front of the text field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The text entered by the user. \r\n         */\r\n        static TextField(position: Rect, label: string, text: string, style: GUIStyle): string\r\n        /** Makes a text field.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param label Optional label to display in front of the text field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The text entered by the user. \r\n         */\r\n        static TextField(position: Rect, label: GUIContent, text: string, style: GUIStyle): string\r\n        /** Makes a text field.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param label Optional label to display in front of the text field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The text entered by the user. \r\n         */\r\n        static TextField(position: Rect, text: string, style: GUIStyle): string\r\n        /** Makes a text field.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param label Optional label to display in front of the text field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The text entered by the user. \r\n         */\r\n        static TextField(position: Rect, label: string, text: string): string\r\n        /** Makes a text field.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param label Optional label to display in front of the text field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The text entered by the user. \r\n         */\r\n        static TextField(position: Rect, label: GUIContent, text: string): string\r\n        /** Makes a text field.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param label Optional label to display in front of the text field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The text entered by the user. \r\n         */\r\n        static TextField(position: Rect, text: string): string\r\n        static DelayedTextField(position: Rect, label: GUIContent, controlId: number, text: string, style: GUIStyle): string\r\n        /** Makes a delayed text field.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param text The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the text field. \r\n         */\r\n        static DelayedTextField(position: Rect, label: string, text: string, style: GUIStyle): string\r\n        /** Makes a delayed text field.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param text The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the text field. \r\n         */\r\n        static DelayedTextField(position: Rect, label: GUIContent, text: string, style: GUIStyle): string\r\n        static DelayedTextField(position: Rect, label: GUIContent, controlId: number, text: string): string\r\n        /** Makes a delayed text field.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param text The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the text field. \r\n         */\r\n        static DelayedTextField(position: Rect, text: string, style: GUIStyle): string\r\n        static DelayedTextField(position: Rect, label: string, text: string): string\r\n        static DelayedTextField(position: Rect, label: GUIContent, text: string): string\r\n        /** Makes a delayed text field.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param property The text property to edit.\r\n         * @param label Optional label to display in front of the int field. Pass GUIContent.none to hide label.\r\n         */\r\n        static DelayedTextField(position: Rect, property: SerializedProperty, label: GUIContent): void\r\n        static DelayedTextField(position: Rect, text: string): string\r\n        static DelayedTextField(position: Rect, property: SerializedProperty): void\r\n        /** Makes a text area.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The text entered by the user. \r\n         */\r\n        static TextArea(position: Rect, text: string, style: GUIStyle): string\r\n        /** Makes a text area.\r\n         * @param position Rectangle on the screen to use for the text field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The text entered by the user. \r\n         */\r\n        static TextArea(position: Rect, text: string): string\r\n        /** Makes a selectable label field. (Useful for showing read-only info that can be copy-pasted.)\r\n         * @param position Rectangle on the screen to use for the label.\r\n         * @param text The text to show.\r\n         * @param style Optional GUIStyle.\r\n         */\r\n        static SelectableLabel(position: Rect, text: string, style: GUIStyle): void\r\n        /** Makes a selectable label field. (Useful for showing read-only info that can be copy-pasted.)\r\n         * @param position Rectangle on the screen to use for the label.\r\n         * @param text The text to show.\r\n         * @param style Optional GUIStyle.\r\n         */\r\n        static SelectableLabel(position: Rect, text: string): void\r\n        /** Makes a text field where the user can enter a password.\r\n         * @param position Rectangle on the screen to use for the password field.\r\n         * @param label Optional label to display in front of the password field.\r\n         * @param password The password to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The password entered by the user. \r\n         */\r\n        static PasswordField(position: Rect, label: string, password: string, style: GUIStyle): string\r\n        /** Makes a text field where the user can enter a password.\r\n         * @param position Rectangle on the screen to use for the password field.\r\n         * @param label Optional label to display in front of the password field.\r\n         * @param password The password to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The password entered by the user. \r\n         */\r\n        static PasswordField(position: Rect, label: GUIContent, password: string, style: GUIStyle): string\r\n        /** Makes a text field where the user can enter a password.\r\n         * @param position Rectangle on the screen to use for the password field.\r\n         * @param label Optional label to display in front of the password field.\r\n         * @param password The password to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The password entered by the user. \r\n         */\r\n        static PasswordField(position: Rect, password: string, style: GUIStyle): string\r\n        /** Makes a text field where the user can enter a password.\r\n         * @param position Rectangle on the screen to use for the password field.\r\n         * @param label Optional label to display in front of the password field.\r\n         * @param password The password to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The password entered by the user. \r\n         */\r\n        static PasswordField(position: Rect, label: string, password: string): string\r\n        /** Makes a text field where the user can enter a password.\r\n         * @param position Rectangle on the screen to use for the password field.\r\n         * @param label Optional label to display in front of the password field.\r\n         * @param password The password to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The password entered by the user. \r\n         */\r\n        static PasswordField(position: Rect, label: GUIContent, password: string): string\r\n        /** Makes a text field where the user can enter a password.\r\n         * @param position Rectangle on the screen to use for the password field.\r\n         * @param label Optional label to display in front of the password field.\r\n         * @param password The password to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The password entered by the user. \r\n         */\r\n        static PasswordField(position: Rect, password: string): string\r\n        /** Makes a text field for entering floats.\r\n         * @param position Rectangle on the screen to use for the float field.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static FloatField(position: Rect, label: string, value: number, style: GUIStyle): number\r\n        /** Makes a text field for entering floats.\r\n         * @param position Rectangle on the screen to use for the float field.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static FloatField(position: Rect, label: GUIContent, value: number, style: GUIStyle): number\r\n        /** Makes a text field for entering floats.\r\n         * @param position Rectangle on the screen to use for the float field.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static FloatField(position: Rect, value: number, style: GUIStyle): number\r\n        static FloatField(position: Rect, label: string, value: number): number\r\n        static FloatField(position: Rect, label: GUIContent, value: number): number\r\n        static FloatField(position: Rect, value: number): number\r\n        /** Makes a delayed text field for entering floats.\r\n         * @param position Rectangle on the screen to use for the float field.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the float field. \r\n         */\r\n        static DelayedFloatField(position: Rect, label: string, value: number, style: GUIStyle): number\r\n        /** Makes a delayed text field for entering floats.\r\n         * @param position Rectangle on the screen to use for the float field.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the float field. \r\n         */\r\n        static DelayedFloatField(position: Rect, label: GUIContent, value: number, style: GUIStyle): number\r\n        /** Makes a delayed text field for entering floats.\r\n         * @param position Rectangle on the screen to use for the float field.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the float field. \r\n         */\r\n        static DelayedFloatField(position: Rect, value: number, style: GUIStyle): number\r\n        static DelayedFloatField(position: Rect, label: string, value: number): number\r\n        static DelayedFloatField(position: Rect, label: GUIContent, value: number): number\r\n        /** Makes a delayed text field for entering floats.\r\n         * @param position Rectangle on the screen to use for the float field.\r\n         * @param property The float property to edit.\r\n         * @param label Optional label to display in front of the float field. Pass GUIContent.none to hide label.\r\n         */\r\n        static DelayedFloatField(position: Rect, property: SerializedProperty, label: GUIContent): void\r\n        static DelayedFloatField(position: Rect, value: number): number\r\n        static DelayedFloatField(position: Rect, property: SerializedProperty): void\r\n        /** Makes a text field for entering doubles.\r\n         * @param position Rectangle on the screen to use for the double field.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static DoubleField(position: Rect, label: string, value: number, style: GUIStyle): number\r\n        /** Makes a text field for entering doubles.\r\n         * @param position Rectangle on the screen to use for the double field.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static DoubleField(position: Rect, label: GUIContent, value: number, style: GUIStyle): number\r\n        /** Makes a text field for entering doubles.\r\n         * @param position Rectangle on the screen to use for the double field.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static DoubleField(position: Rect, value: number, style: GUIStyle): number\r\n        static DoubleField(position: Rect, label: string, value: number): number\r\n        static DoubleField(position: Rect, label: GUIContent, value: number): number\r\n        static DoubleField(position: Rect, value: number): number\r\n        /** Makes a delayed text field for entering doubles.\r\n         * @param position Rectangle on the screen to use for the double field.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the double field. \r\n         */\r\n        static DelayedDoubleField(position: Rect, label: string, value: number, style: GUIStyle): number\r\n        /** Makes a delayed text field for entering doubles.\r\n         * @param position Rectangle on the screen to use for the double field.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the double field. \r\n         */\r\n        static DelayedDoubleField(position: Rect, label: GUIContent, value: number, style: GUIStyle): number\r\n        /** Makes a delayed text field for entering doubles.\r\n         * @param position Rectangle on the screen to use for the double field.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the double field. \r\n         */\r\n        static DelayedDoubleField(position: Rect, value: number, style: GUIStyle): number\r\n        static DelayedDoubleField(position: Rect, label: string, value: number): number\r\n        static DelayedDoubleField(position: Rect, label: GUIContent, value: number): number\r\n        static DelayedDoubleField(position: Rect, value: number): number\r\n        /** Makes a text field for entering integers.\r\n         * @param position Rectangle on the screen to use for the int field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static IntField(position: Rect, label: string, value: number, style: GUIStyle): number\r\n        /** Makes a text field for entering integers.\r\n         * @param position Rectangle on the screen to use for the int field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static IntField(position: Rect, label: GUIContent, value: number, style: GUIStyle): number\r\n        /** Makes a text field for entering integers.\r\n         * @param position Rectangle on the screen to use for the int field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static IntField(position: Rect, value: number, style: GUIStyle): number\r\n        /** Makes a text field for entering integers.\r\n         * @param position Rectangle on the screen to use for the int field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static IntField(position: Rect, label: string, value: number): number\r\n        /** Makes a text field for entering integers.\r\n         * @param position Rectangle on the screen to use for the int field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static IntField(position: Rect, label: GUIContent, value: number): number\r\n        /** Makes a text field for entering integers.\r\n         * @param position Rectangle on the screen to use for the int field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static IntField(position: Rect, value: number): number\r\n        /** Makes a delayed text field for entering integers.\r\n         * @param position Rectangle on the screen to use for the int field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the int field. \r\n         */\r\n        static DelayedIntField(position: Rect, label: string, value: number, style: GUIStyle): number\r\n        /** Makes a delayed text field for entering integers.\r\n         * @param position Rectangle on the screen to use for the int field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the int field. \r\n         */\r\n        static DelayedIntField(position: Rect, label: GUIContent, value: number, style: GUIStyle): number\r\n        /** Makes a delayed text field for entering integers.\r\n         * @param position Rectangle on the screen to use for the int field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the int field. \r\n         */\r\n        static DelayedIntField(position: Rect, value: number, style: GUIStyle): number\r\n        static DelayedIntField(position: Rect, label: string, value: number): number\r\n        static DelayedIntField(position: Rect, label: GUIContent, value: number): number\r\n        /** The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the int field.\r\n         * @param position Rectangle on the screen to use for the int field.\r\n         * @param property The int property to edit.\r\n         * @param label Optional label to display in front of the int field. Pass GUIContent.none to hide label.\r\n         */\r\n        static DelayedIntField(position: Rect, property: SerializedProperty, label: GUIContent): void\r\n        static DelayedIntField(position: Rect, value: number): number\r\n        static DelayedIntField(position: Rect, property: SerializedProperty): void\r\n        /** Makes a text field for entering long integers.\r\n         * @param position Rectangle on the screen to use for the long field.\r\n         * @param label Optional label to display in front of the long field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static LongField(position: Rect, label: string, value: number, style: GUIStyle): number\r\n        /** Makes a text field for entering long integers.\r\n         * @param position Rectangle on the screen to use for the long field.\r\n         * @param label Optional label to display in front of the long field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static LongField(position: Rect, label: GUIContent, value: number, style: GUIStyle): number\r\n        static LongField(position: Rect, value: number, style: GUIStyle): number\r\n        /** Makes a text field for entering long integers.\r\n         * @param position Rectangle on the screen to use for the long field.\r\n         * @param label Optional label to display in front of the long field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static LongField(position: Rect, label: string, value: number): number\r\n        /** Makes a text field for entering long integers.\r\n         * @param position Rectangle on the screen to use for the long field.\r\n         * @param label Optional label to display in front of the long field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static LongField(position: Rect, label: GUIContent, value: number): number\r\n        /** Makes a text field for entering long integers.\r\n         * @param position Rectangle on the screen to use for the long field.\r\n         * @param label Optional label to display in front of the long field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static LongField(position: Rect, value: number): number\r\n        /** Makes a generic popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedIndex The index of the option the field shows.\r\n         * @param displayedOptions An array with the options shown in the popup.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The index of the option that has been selected by the user. \r\n         */\r\n        static Popup(position: Rect, label: string, selectedIndex: number, displayedOptions: Array<string>, style: GUIStyle): number\r\n        /** Makes a generic popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedIndex The index of the option the field shows.\r\n         * @param displayedOptions An array with the options shown in the popup.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The index of the option that has been selected by the user. \r\n         */\r\n        static Popup(position: Rect, label: GUIContent, selectedIndex: number, displayedOptions: Array<GUIContent>, style: GUIStyle): number\r\n        /** Makes a generic popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedIndex The index of the option the field shows.\r\n         * @param displayedOptions An array with the options shown in the popup.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The index of the option that has been selected by the user. \r\n         */\r\n        static Popup(position: Rect, selectedIndex: number, displayedOptions: Array<string>, style: GUIStyle): number\r\n        /** Makes a generic popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedIndex The index of the option the field shows.\r\n         * @param displayedOptions An array with the options shown in the popup.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The index of the option that has been selected by the user. \r\n         */\r\n        static Popup(position: Rect, selectedIndex: number, displayedOptions: Array<GUIContent>, style: GUIStyle): number\r\n        /** Makes a generic popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedIndex The index of the option the field shows.\r\n         * @param displayedOptions An array with the options shown in the popup.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The index of the option that has been selected by the user. \r\n         */\r\n        static Popup(position: Rect, label: string, selectedIndex: number, displayedOptions: Array<string>): number\r\n        /** Makes a generic popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedIndex The index of the option the field shows.\r\n         * @param displayedOptions An array with the options shown in the popup.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The index of the option that has been selected by the user. \r\n         */\r\n        static Popup(position: Rect, label: GUIContent, selectedIndex: number, displayedOptions: Array<GUIContent>): number\r\n        /** Makes a generic popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedIndex The index of the option the field shows.\r\n         * @param displayedOptions An array with the options shown in the popup.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The index of the option that has been selected by the user. \r\n         */\r\n        static Popup(position: Rect, selectedIndex: number, displayedOptions: Array<string>): number\r\n        /** Makes a generic popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedIndex The index of the option the field shows.\r\n         * @param displayedOptions An array with the options shown in the popup.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The index of the option that has been selected by the user. \r\n         */\r\n        static Popup(position: Rect, selectedIndex: number, displayedOptions: Array<GUIContent>): number\r\n        static EnumPopup(position: Rect, label: GUIContent, selected: Enum, checkEnabled: (arg: Enum) => boolean, includeObsolete: boolean, style: GUIStyle): Enum\r\n        /** Makes an enum popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selected The enum option the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @param checkEnabled Method called for each Enum value displayed. The specified method should return true if the option can be selected, false otherwise.\r\n         * @returns The enum option that has been selected by the user. \r\n         */\r\n        static EnumPopup(position: Rect, label: string, selected: Enum, style: GUIStyle): Enum\r\n        /** Makes an enum popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selected The enum option the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @param checkEnabled Method called for each Enum value displayed. The specified method should return true if the option can be selected, false otherwise.\r\n         * @returns The enum option that has been selected by the user. \r\n         */\r\n        static EnumPopup(position: Rect, label: GUIContent, selected: Enum, style: GUIStyle): Enum\r\n        /** Makes an enum popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selected The enum option the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @param checkEnabled Method called for each Enum value displayed. The specified method should return true if the option can be selected, false otherwise.\r\n         * @returns The enum option that has been selected by the user. \r\n         */\r\n        static EnumPopup(position: Rect, selected: Enum, style: GUIStyle): Enum\r\n        /** Makes an enum popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selected The enum option the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @param checkEnabled Method called for each Enum value displayed. The specified method should return true if the option can be selected, false otherwise.\r\n         * @returns The enum option that has been selected by the user. \r\n         */\r\n        static EnumPopup(position: Rect, label: string, selected: Enum): Enum\r\n        /** Makes an enum popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selected The enum option the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @param checkEnabled Method called for each Enum value displayed. The specified method should return true if the option can be selected, false otherwise.\r\n         * @returns The enum option that has been selected by the user. \r\n         */\r\n        static EnumPopup(position: Rect, label: GUIContent, selected: Enum): Enum\r\n        /** Makes an enum popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selected The enum option the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @param checkEnabled Method called for each Enum value displayed. The specified method should return true if the option can be selected, false otherwise.\r\n         * @returns The enum option that has been selected by the user. \r\n         */\r\n        static EnumPopup(position: Rect, selected: Enum): Enum\r\n        /** Makes an integer popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedValue The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option. If optionValues a direct mapping of selectedValue to displayedOptions is assumed.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value of the option that has been selected by the user. \r\n         */\r\n        static IntPopup(position: Rect, label: GUIContent, selectedValue: number, displayedOptions: Array<GUIContent>, optionValues: Array<number>, style: GUIStyle): number\r\n        /** Makes an integer popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedValue The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option. If optionValues a direct mapping of selectedValue to displayedOptions is assumed.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value of the option that has been selected by the user. \r\n         */\r\n        static IntPopup(position: Rect, label: string, selectedValue: number, displayedOptions: Array<string>, optionValues: Array<number>, style: GUIStyle): number\r\n        /** Makes an integer popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedValue The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option. If optionValues a direct mapping of selectedValue to displayedOptions is assumed.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value of the option that has been selected by the user. \r\n         */\r\n        static IntPopup(position: Rect, selectedValue: number, displayedOptions: Array<string>, optionValues: Array<number>, style: GUIStyle): number\r\n        /** Makes an integer popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedValue The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option. If optionValues a direct mapping of selectedValue to displayedOptions is assumed.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value of the option that has been selected by the user. \r\n         */\r\n        static IntPopup(position: Rect, selectedValue: number, displayedOptions: Array<GUIContent>, optionValues: Array<number>, style: GUIStyle): number\r\n        /** Makes an integer popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedValue The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option. If optionValues a direct mapping of selectedValue to displayedOptions is assumed.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value of the option that has been selected by the user. \r\n         */\r\n        static IntPopup(position: Rect, label: GUIContent, selectedValue: number, displayedOptions: Array<GUIContent>, optionValues: Array<number>): number\r\n        /**\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param property The SerializedProperty to use for the control.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option. If optionValues a direct   mapping of selectedValue to displayedOptions is assumed.\r\n         * @param label Optional label in front of the field.\r\n         */\r\n        static IntPopup(position: Rect, property: SerializedProperty, displayedOptions: Array<GUIContent>, optionValues: Array<number>, label: GUIContent): void\r\n        /** Makes an integer popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedValue The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option. If optionValues a direct mapping of selectedValue to displayedOptions is assumed.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value of the option that has been selected by the user. \r\n         */\r\n        static IntPopup(position: Rect, label: string, selectedValue: number, displayedOptions: Array<string>, optionValues: Array<number>): number\r\n        /** Makes an integer popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedValue The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option. If optionValues a direct mapping of selectedValue to displayedOptions is assumed.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value of the option that has been selected by the user. \r\n         */\r\n        static IntPopup(position: Rect, selectedValue: number, displayedOptions: Array<string>, optionValues: Array<number>): number\r\n        /** Makes an integer popup selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedValue The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option. If optionValues a direct mapping of selectedValue to displayedOptions is assumed.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The value of the option that has been selected by the user. \r\n         */\r\n        static IntPopup(position: Rect, selectedValue: number, displayedOptions: Array<GUIContent>, optionValues: Array<number>): number\r\n        /**\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param property The SerializedProperty to use for the control.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option. If optionValues a direct   mapping of selectedValue to displayedOptions is assumed.\r\n         * @param label Optional label in front of the field.\r\n         */\r\n        static IntPopup(position: Rect, property: SerializedProperty, displayedOptions: Array<GUIContent>, optionValues: Array<number>): void\r\n        /** Makes a tag selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param tag The tag the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The tag selected by the user. \r\n         */\r\n        static TagField(position: Rect, label: string, tag: string, style: GUIStyle): string\r\n        /** Makes a tag selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param tag The tag the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The tag selected by the user. \r\n         */\r\n        static TagField(position: Rect, label: GUIContent, tag: string, style: GUIStyle): string\r\n        /** Makes a tag selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param tag The tag the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The tag selected by the user. \r\n         */\r\n        static TagField(position: Rect, tag: string, style: GUIStyle): string\r\n        /** Makes a tag selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param tag The tag the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The tag selected by the user. \r\n         */\r\n        static TagField(position: Rect, label: string, tag: string): string\r\n        /** Makes a tag selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param tag The tag the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The tag selected by the user. \r\n         */\r\n        static TagField(position: Rect, label: GUIContent, tag: string): string\r\n        /** Makes a tag selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param tag The tag the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The tag selected by the user. \r\n         */\r\n        static TagField(position: Rect, tag: string): string\r\n        /** Makes a layer selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param layer The layer shown in the field.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The layer selected by the user. \r\n         */\r\n        static LayerField(position: Rect, label: string, layer: number, style: GUIStyle): number\r\n        /** Makes a layer selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param layer The layer shown in the field.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The layer selected by the user. \r\n         */\r\n        static LayerField(position: Rect, label: GUIContent, layer: number, style: GUIStyle): number\r\n        /** Makes a layer selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param layer The layer shown in the field.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The layer selected by the user. \r\n         */\r\n        static LayerField(position: Rect, layer: number, style: GUIStyle): number\r\n        /** Makes a layer selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param layer The layer shown in the field.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The layer selected by the user. \r\n         */\r\n        static LayerField(position: Rect, label: string, layer: number): number\r\n        /** Makes a layer selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param layer The layer shown in the field.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The layer selected by the user. \r\n         */\r\n        static LayerField(position: Rect, label: GUIContent, layer: number): number\r\n        /** Makes a layer selection field.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label in front of the field.\r\n         * @param layer The layer shown in the field.\r\n         * @param style Optional GUIStyle.\r\n         * @returns The layer selected by the user. \r\n         */\r\n        static LayerField(position: Rect, layer: number): number\r\n        /** Makes a field for masks.\r\n         * @param position Rectangle on the screen to use for this control.\r\n         * @param label Label for the field.\r\n         * @param mask The current mask to display.\r\n         * @param displayedOption A string array containing the labels for each flag.\r\n         * @param style Optional GUIStyle.\r\n         * @param displayedOptions A string array containing the labels for each flag.\r\n         * @returns The value modified by the user. \r\n         */\r\n        static MaskField(position: Rect, label: GUIContent, mask: number, displayedOptions: Array<string>, style: GUIStyle): number\r\n        /** Makes a field for masks.\r\n         * @param position Rectangle on the screen to use for this control.\r\n         * @param label Label for the field.\r\n         * @param mask The current mask to display.\r\n         * @param displayedOption A string array containing the labels for each flag.\r\n         * @param style Optional GUIStyle.\r\n         * @param displayedOptions A string array containing the labels for each flag.\r\n         * @returns The value modified by the user. \r\n         */\r\n        static MaskField(position: Rect, label: string, mask: number, displayedOptions: Array<string>, style: GUIStyle): number\r\n        /** Makes a field for masks.\r\n         * @param position Rectangle on the screen to use for this control.\r\n         * @param label Label for the field.\r\n         * @param mask The current mask to display.\r\n         * @param displayedOption A string array containing the labels for each flag.\r\n         * @param style Optional GUIStyle.\r\n         * @param displayedOptions A string array containing the labels for each flag.\r\n         * @returns The value modified by the user. \r\n         */\r\n        static MaskField(position: Rect, label: GUIContent, mask: number, displayedOptions: Array<string>): number\r\n        /** Makes a field for masks.\r\n         * @param position Rectangle on the screen to use for this control.\r\n         * @param label Label for the field.\r\n         * @param mask The current mask to display.\r\n         * @param displayedOption A string array containing the labels for each flag.\r\n         * @param style Optional GUIStyle.\r\n         * @param displayedOptions A string array containing the labels for each flag.\r\n         * @returns The value modified by the user. \r\n         */\r\n        static MaskField(position: Rect, label: string, mask: number, displayedOptions: Array<string>): number\r\n        /** Makes a field for masks.\r\n         * @param position Rectangle on the screen to use for this control.\r\n         * @param label Label for the field.\r\n         * @param mask The current mask to display.\r\n         * @param displayedOption A string array containing the labels for each flag.\r\n         * @param style Optional GUIStyle.\r\n         * @param displayedOptions A string array containing the labels for each flag.\r\n         * @returns The value modified by the user. \r\n         */\r\n        static MaskField(position: Rect, mask: number, displayedOptions: Array<string>, style: GUIStyle): number\r\n        /** Makes a field for masks.\r\n         * @param position Rectangle on the screen to use for this control.\r\n         * @param label Label for the field.\r\n         * @param mask The current mask to display.\r\n         * @param displayedOption A string array containing the labels for each flag.\r\n         * @param style Optional GUIStyle.\r\n         * @param displayedOptions A string array containing the labels for each flag.\r\n         * @returns The value modified by the user. \r\n         */\r\n        static MaskField(position: Rect, mask: number, displayedOptions: Array<string>): number\r\n        /** Makes a label with a foldout arrow to the left of it.\r\n         * @param position Rectangle on the screen to use for the arrow and label.\r\n         * @param foldout The shown foldout state.\r\n         * @param content The label to show.\r\n         * @param style Optional GUIStyle.\r\n         * @param toggleOnLabelClick Should the label be a clickable part of the control?\r\n         * @returns The foldout state selected by the user. If true, you should render sub-objects. \r\n         */\r\n        static Foldout(position: Rect, foldout: boolean, content: string, toggleOnLabelClick: boolean, style: GUIStyle): boolean\r\n        /** Makes a label with a foldout arrow to the left of it.\r\n         * @param position Rectangle on the screen to use for the arrow and label.\r\n         * @param foldout The shown foldout state.\r\n         * @param content The label to show.\r\n         * @param style Optional GUIStyle.\r\n         * @param toggleOnLabelClick Should the label be a clickable part of the control?\r\n         * @returns The foldout state selected by the user. If true, you should render sub-objects. \r\n         */\r\n        static Foldout(position: Rect, foldout: boolean, content: GUIContent, toggleOnLabelClick: boolean, style: GUIStyle): boolean\r\n        /** Makes a label with a foldout arrow to the left of it.\r\n         * @param position Rectangle on the screen to use for the arrow and label.\r\n         * @param foldout The shown foldout state.\r\n         * @param content The label to show.\r\n         * @param style Optional GUIStyle.\r\n         * @param toggleOnLabelClick Should the label be a clickable part of the control?\r\n         * @returns The foldout state selected by the user. If true, you should render sub-objects. \r\n         */\r\n        static Foldout(position: Rect, foldout: boolean, content: string, style: GUIStyle): boolean\r\n        /** Makes a label with a foldout arrow to the left of it.\r\n         * @param position Rectangle on the screen to use for the arrow and label.\r\n         * @param foldout The shown foldout state.\r\n         * @param content The label to show.\r\n         * @param style Optional GUIStyle.\r\n         * @param toggleOnLabelClick Should the label be a clickable part of the control?\r\n         * @returns The foldout state selected by the user. If true, you should render sub-objects. \r\n         */\r\n        static Foldout(position: Rect, foldout: boolean, content: string, toggleOnLabelClick: boolean): boolean\r\n        /** Makes a label with a foldout arrow to the left of it.\r\n         * @param position Rectangle on the screen to use for the arrow and label.\r\n         * @param foldout The shown foldout state.\r\n         * @param content The label to show.\r\n         * @param style Optional GUIStyle.\r\n         * @param toggleOnLabelClick Should the label be a clickable part of the control?\r\n         * @returns The foldout state selected by the user. If true, you should render sub-objects. \r\n         */\r\n        static Foldout(position: Rect, foldout: boolean, content: GUIContent, style: GUIStyle): boolean\r\n        /** Makes a label with a foldout arrow to the left of it.\r\n         * @param position Rectangle on the screen to use for the arrow and label.\r\n         * @param foldout The shown foldout state.\r\n         * @param content The label to show.\r\n         * @param style Optional GUIStyle.\r\n         * @param toggleOnLabelClick Should the label be a clickable part of the control?\r\n         * @returns The foldout state selected by the user. If true, you should render sub-objects. \r\n         */\r\n        static Foldout(position: Rect, foldout: boolean, content: GUIContent, toggleOnLabelClick: boolean): boolean\r\n        /** Makes a label with a foldout arrow to the left of it.\r\n         * @param position Rectangle on the screen to use for the arrow and label.\r\n         * @param foldout The shown foldout state.\r\n         * @param content The label to show.\r\n         * @param style Optional GUIStyle.\r\n         * @param toggleOnLabelClick Should the label be a clickable part of the control?\r\n         * @returns The foldout state selected by the user. If true, you should render sub-objects. \r\n         */\r\n        static Foldout(position: Rect, foldout: boolean, content: string): boolean\r\n        /** Makes a label with a foldout arrow to the left of it.\r\n         * @param position Rectangle on the screen to use for the arrow and label.\r\n         * @param foldout The shown foldout state.\r\n         * @param content The label to show.\r\n         * @param style Optional GUIStyle.\r\n         * @param toggleOnLabelClick Should the label be a clickable part of the control?\r\n         * @returns The foldout state selected by the user. If true, you should render sub-objects. \r\n         */\r\n        static Foldout(position: Rect, foldout: boolean, content: GUIContent): boolean\r\n        /** Makes a label for some control.\r\n         * @param totalPosition Rectangle on the screen to use in total for both the label and the control.\r\n         * @param labelPosition Rectangle on the screen to use for the label.\r\n         * @param label Label to show for the control.\r\n         * @param id The unique ID of the control. If none specified, the ID of the following control is used.\r\n         * @param style Optional GUIStyle to use for the label.\r\n         */\r\n        static HandlePrefixLabel(totalPosition: Rect, labelPosition: Rect, label: GUIContent, id: number, style: GUIStyle): void\r\n        /** Makes a label for some control.\r\n         * @param totalPosition Rectangle on the screen to use in total for both the label and the control.\r\n         * @param labelPosition Rectangle on the screen to use for the label.\r\n         * @param label Label to show for the control.\r\n         * @param id The unique ID of the control. If none specified, the ID of the following control is used.\r\n         * @param style Optional GUIStyle to use for the label.\r\n         */\r\n        static HandlePrefixLabel(totalPosition: Rect, labelPosition: Rect, label: GUIContent, id: number): void\r\n        /** Makes a label for some control.\r\n         * @param totalPosition Rectangle on the screen to use in total for both the label and the control.\r\n         * @param labelPosition Rectangle on the screen to use for the label.\r\n         * @param label Label to show for the control.\r\n         * @param id The unique ID of the control. If none specified, the ID of the following control is used.\r\n         * @param style Optional GUIStyle to use for the label.\r\n         */\r\n        static HandlePrefixLabel(totalPosition: Rect, labelPosition: Rect, label: GUIContent): void\r\n        /** Use this to make a field for a SerializedProperty in the Editor.\r\n         * @param position Rectangle on the screen to use for the property field.\r\n         * @param property The SerializedProperty to make a field for.\r\n         * @param label Optional label to use. If not specified the label of the property itself is used. Use GUIContent.none to not display a label at all.\r\n         * @param includeChildren If true the property including children is drawn; otherwise only the control itself (such as only a foldout but nothing below it).\r\n         * @returns True if the property has children and is expanded and includeChildren was set to false; otherwise false. \r\n         */\r\n        static PropertyField(position: Rect, property: SerializedProperty, label: GUIContent, includeChildren: boolean): boolean\r\n        /** Use this to make a field for a SerializedProperty in the Editor.\r\n         * @param position Rectangle on the screen to use for the property field.\r\n         * @param property The SerializedProperty to make a field for.\r\n         * @param label Optional label to use. If not specified the label of the property itself is used. Use GUIContent.none to not display a label at all.\r\n         * @param includeChildren If true the property including children is drawn; otherwise only the control itself (such as only a foldout but nothing below it).\r\n         * @returns True if the property has children and is expanded and includeChildren was set to false; otherwise false. \r\n         */\r\n        static PropertyField(position: Rect, property: SerializedProperty, includeChildren: boolean): boolean\r\n        static PropertyField(position: Rect, property: SerializedProperty, label: GUIContent): boolean\r\n        static PropertyField(position: Rect, property: SerializedProperty): boolean\r\n        static BeginFoldoutHeaderGroup(position: Rect, foldout: boolean, content: string, style: GUIStyle, menuAction: (obj: Rect) => void, menuIcon: GUIStyle): boolean\r\n        static BeginFoldoutHeaderGroup(position: Rect, foldout: boolean, content: GUIContent, style: GUIStyle, menuAction: (obj: Rect) => void, menuIcon: GUIStyle): boolean\r\n        static EndFoldoutHeaderGroup(): void\r\n        /** Makes a field for editing a Gradient.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param gradient The gradient to edit.\r\n         * @param hdr Display the HDR Gradient Editor.\r\n         * @param colorSpace Display the gradient and Gradient Editor in this color space.\r\n         * @returns The gradient edited by the user. \r\n         */\r\n        static GradientField(position: Rect, label: GUIContent, gradient: Gradient, hdr: boolean, colorSpace: any): Gradient\r\n        /** Makes a field for editing a Gradient.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param gradient The gradient to edit.\r\n         * @param hdr Display the HDR Gradient Editor.\r\n         * @param colorSpace Display the gradient and Gradient Editor in this color space.\r\n         * @returns The gradient edited by the user. \r\n         */\r\n        static GradientField(position: Rect, label: GUIContent, gradient: Gradient, hdr: boolean): Gradient\r\n        /** Makes a field for editing a Gradient.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param gradient The gradient to edit.\r\n         * @param hdr Display the HDR Gradient Editor.\r\n         * @param colorSpace Display the gradient and Gradient Editor in this color space.\r\n         * @returns The gradient edited by the user. \r\n         */\r\n        static GradientField(position: Rect, label: string, gradient: Gradient): Gradient\r\n        /** Makes a field for editing a Gradient.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param gradient The gradient to edit.\r\n         * @param hdr Display the HDR Gradient Editor.\r\n         * @param colorSpace Display the gradient and Gradient Editor in this color space.\r\n         * @returns The gradient edited by the user. \r\n         */\r\n        static GradientField(position: Rect, label: GUIContent, gradient: Gradient): Gradient\r\n        /** Makes a field for editing a Gradient.\r\n         * @param position Rectangle on the screen to use for the field.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param gradient The gradient to edit.\r\n         * @param hdr Display the HDR Gradient Editor.\r\n         * @param colorSpace Display the gradient and Gradient Editor in this color space.\r\n         * @returns The gradient edited by the user. \r\n         */\r\n        static GradientField(position: Rect, gradient: Gradient): Gradient\r\n        /** Draws a filled rectangle of color at the specified position and size within the current editor window.\r\n         * @param rect The position and size of the rectangle to draw.\r\n         * @param color The color of the rectange.\r\n         */\r\n        static DrawRect(rect: Rect, color: Color): void\r\n        protected constructor()\r\n        /** Makes the following controls give the appearance of editing multiple different values.\r\n         */\r\n        static showMixedValue: boolean\r\n        /** Is the platform-dependent \"action\" modifier key held down? (Read Only)\r\n         */\r\n        static readonly actionKey: boolean\r\n        /** The indent level of the field labels.\r\n         */\r\n        static indentLevel: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { GUIUtility, Texture2D, Vector2, Event, Rect, GUIStyle, GUIContent, Texture, Object as Object1, GUISkin, Color, AnimationCurve } from \"UnityEngine\";\r\n    import { Object, Array } from \"System\";\r\n    /** Miscellaneous helper stuff for EditorGUI.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class EditorGUIUtility extends GUIUtility {\r\n        static SerializeMainMenuToString(): string\r\n        static SetMenuLocalizationTestMode(onoff: boolean): void\r\n        /** Set icons rendered as part of GUIContent to be rendered at a specific size.\r\n         */\r\n        static SetIconSize(size: Vector2): void\r\n        static SetWantsMouseJumping(wantz: number): void\r\n        /** Check if any enabled camera can render to a particular display.\r\n         * @param displayIndex Display index.\r\n         * @returns True if a camera will render to the display. \r\n         */\r\n        static IsDisplayReferencedByCameras(displayIndex: number): boolean\r\n        /** Send an input event into the game.\r\n         */\r\n        static QueueGameViewInputEvent(evt: Event): void\r\n        static GetMainWindowPosition(): Rect\r\n        /** Sets position of Unity Editor's main window.\r\n         */\r\n        static SetMainWindowPosition(position: Rect): void\r\n        /** Converts a position from point to pixel space.\r\n         * @param rect A GUI position in point space.\r\n         * @returns The same position in pixel space. \r\n         */\r\n        static PointsToPixels(rect: Rect): Rect\r\n        /** Convert a Rect from point space to pixel space.\r\n         * @param position A GUI rect measured in points.\r\n         * @returns A rect representing the same area in pixels. \r\n         */\r\n        static PointsToPixels(position: Vector2): Vector2\r\n        /** Convert a Rect from pixel space to point space.\r\n         * @param rect A GUI rect measured in pixels.\r\n         * @returns A rect representing the same area in points. \r\n         */\r\n        static PixelsToPoints(rect: Rect): Rect\r\n        /** Convert a position from pixel to point space.\r\n         * @param position A GUI position in pixel space.\r\n         * @returns A vector representing the same position in point space. \r\n         */\r\n        static PixelsToPoints(position: Vector2): Vector2\r\n        static GetFlowLayoutedRects(rect: Rect, style: GUIStyle, horizontalSpacing: number, verticalSpacing: number, items: any): any\r\n        /** Get a texture from its source filename.\r\n         */\r\n        static FindTexture(name: string): Texture2D\r\n        static TrTextContent(key: string, text: string, tooltip: string, icon: Texture): GUIContent\r\n        static TrTextContent(text: string, tooltip: string, icon: Texture): GUIContent\r\n        static TrTextContent(text: string, tooltip: string, iconName: string): GUIContent\r\n        static TrTextContent(text: string, icon: Texture): GUIContent\r\n        static TrTextContentWithIcon(text: string, tooltip: string, iconName: string): GUIContent\r\n        static TrTextContentWithIcon(text: string, tooltip: string, icon: Texture): GUIContent\r\n        static TrTextContentWithIcon(text: string, tooltip: string, messageType: MessageType): GUIContent\r\n        static TrTextContentWithIcon(text: string, icon: Texture): GUIContent\r\n        static TrTextContentWithIcon(text: string, iconName: string): GUIContent\r\n        static TrTextContentWithIcon(text: string, messageType: MessageType): GUIContent\r\n        static TrIconContent(iconName: string, tooltip: string): GUIContent\r\n        static TrIconContent(icon: Texture, tooltip: string): GUIContent\r\n        static TrTempContent(texts: Array<string>, tooltips: Array<string>): Array<GUIContent>\r\n        static TrTempContent(t: string): GUIContent\r\n        static TrTempContent(texts: Array<string>): Array<GUIContent>\r\n        /** Fetch the GUIContent from the Unity builtin resources with the given name.\r\n         * @param name Name of the desired icon.\r\n         * @param text Tooltip for hovering over the icon.\r\n         */\r\n        static IconContent(name: string, text: string): GUIContent\r\n        /** Fetch the GUIContent from the Unity builtin resources with the given name.\r\n         * @param name Name of the desired icon.\r\n         * @param text Tooltip for hovering over the icon.\r\n         */\r\n        static IconContent(name: string): GUIContent\r\n        /** Return a GUIContent object with the name and icon of an Object.\r\n         */\r\n        static ObjectContent(obj: Object1, type: any): GUIContent\r\n        /** Does a given class have per-object thumbnails?\r\n         */\r\n        static HasObjectThumbnail(objType: any): boolean\r\n        static GetIconSize(): Vector2\r\n        /** Get one of the built-in GUI skins, which can be the game view, inspector or Scene view skin as chosen by the parameter.\r\n         */\r\n        static GetBuiltinSkin(skin: EditorSkin): GUISkin\r\n        /** Load a required built-in resource.\r\n         */\r\n        static LoadRequired(path: string): Object1\r\n        /** Load a built-in resource.\r\n         */\r\n        static Load(path: string): Object1\r\n        /** Ping an object in the Scene like clicking it in an inspector.\r\n         * @param obj The object to be pinged.\r\n         */\r\n        static PingObject(obj: Object1): void\r\n        /** Ping an object in the Scene like clicking it in an inspector.\r\n         * @param obj The object to be pinged.\r\n         */\r\n        static PingObject(targetInstanceID: number): void\r\n        /** Creates an event that can be sent to another window.\r\n         * @param commandName The command to be sent.\r\n         */\r\n        static CommandEvent(commandName: string): Event\r\n        /** Draw a color swatch.\r\n         * @param position The rectangle to draw the color swatch within.\r\n         * @param color The color to draw.\r\n         */\r\n        static DrawColorSwatch(position: Rect, color: Color): void\r\n        static DrawCurveSwatch(position: Rect, curve: AnimationCurve, property: SerializedProperty, color: Color, bgColor: Color, topFillColor: Color, bottomFillColor: Color, curveRanges: Rect): void\r\n        static DrawCurveSwatch(position: Rect, curve: AnimationCurve, property: SerializedProperty, color: Color, bgColor: Color, topFillColor: Color, bottomFillColor: Color): void\r\n        /** Draw a curve swatch.\r\n         * @param position The rectangle to draw the color swatch within.\r\n         * @param curve The curve to draw.\r\n         * @param property The curve to draw as a SerializedProperty.\r\n         * @param color The color to draw the curve with.\r\n         * @param bgColor The color to draw the background with.\r\n         * @param curveRanges Optional parameter to specify the range of the curve which should be included in swatch.\r\n         */\r\n        static DrawCurveSwatch(position: Rect, curve: AnimationCurve, property: SerializedProperty, color: Color, bgColor: Color, curveRanges: Rect): void\r\n        /** Draw a curve swatch.\r\n         * @param position The rectangle to draw the color swatch within.\r\n         * @param curve The curve to draw.\r\n         * @param property The curve to draw as a SerializedProperty.\r\n         * @param color The color to draw the curve with.\r\n         * @param bgColor The color to draw the background with.\r\n         * @param curveRanges Optional parameter to specify the range of the curve which should be included in swatch.\r\n         */\r\n        static DrawCurveSwatch(position: Rect, curve: AnimationCurve, property: SerializedProperty, color: Color, bgColor: Color): void\r\n        /** Draw swatch with a filled region between two SerializedProperty curves.\r\n         */\r\n        static DrawRegionSwatch(position: Rect, property: SerializedProperty, property2: SerializedProperty, color: Color, bgColor: Color, curveRanges: Rect): void\r\n        /** Draw swatch with a filled region between two curves.\r\n         */\r\n        static DrawRegionSwatch(position: Rect, curve: AnimationCurve, curve2: AnimationCurve, color: Color, bgColor: Color, curveRanges: Rect): void\r\n        /** Add a custom mouse pointer to a control.\r\n         * @param position The rectangle the control should be shown within.\r\n         * @param mouse The mouse cursor to use.\r\n         * @param controlID ID of a target control.\r\n         */\r\n        static AddCursorRect(position: Rect, mouse: MouseCursor, controlID: number): void\r\n        /** Add a custom mouse pointer to a control.\r\n         * @param position The rectangle the control should be shown within.\r\n         * @param mouse The mouse cursor to use.\r\n         * @param controlID ID of a target control.\r\n         */\r\n        static AddCursorRect(position: Rect, mouse: MouseCursor): void\r\n        static GetObjectPickerObject(): Object1\r\n        static GetObjectPickerControlID(): number\r\n        protected constructor()\r\n        /** Get a white texture.\r\n         */\r\n        static readonly whiteTexture: Texture2D\r\n        /** The system copy buffer.\r\n         */\r\n        static systemCopyBuffer: string\r\n        /** The scale of GUI points relative to screen pixels for the current view\n\nThis value is the number of screen pixels per point of interface space. For instance, 2.0 on retina displays. Note that the value may differ from one view to the next if the views are on monitors with different UI scales.\r\n         */\r\n        static readonly pixelsPerPoint: number\r\n        /** Get the height used for a single Editor control such as a one-line EditorGUI.TextField or EditorGUI.Popup.\r\n         */\r\n        static readonly singleLineHeight: number\r\n        /** Get the height used by default for vertical spacing between controls.\r\n         */\r\n        static readonly standardVerticalSpacing: number\r\n        /** Is the user currently using the pro skin? (Read Only)\r\n         */\r\n        static readonly isProSkin: boolean\r\n        /** Is a text field currently editing text?\r\n         */\r\n        static editingTextField: boolean\r\n        /** True if a text field currently has focused and the text in it is selected.\r\n         */\r\n        static readonly textFieldHasSelection: boolean\r\n        /** Is the Editor GUI is hierarchy mode?\r\n         */\r\n        static hierarchyMode: boolean\r\n        /** Is the Editor GUI currently in wide mode?\r\n         */\r\n        static wideMode: boolean\r\n        /** The width of the GUI area for the current EditorWindow or other view.\r\n         */\r\n        static readonly currentViewWidth: number\r\n        /** The width in pixels reserved for labels of Editor GUI controls.\r\n         */\r\n        static labelWidth: number\r\n        /** The minimum width in pixels reserved for the fields of Editor GUI controls.\r\n         */\r\n        static fieldWidth: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array, Enum } from \"System\";\r\n    import { GUIStyle, GUIContent, GUILayoutOption, Object as Object1, Vector2, Vector3, Vector4, Vector2Int, Vector3Int, Rect, RectInt, Bounds, BoundsInt, Color, AnimationCurve, FocusType, Gradient } from \"UnityEngine\";\r\n    import { EditorTool } from \"UnityEditor.EditorTools\";\r\n    /** Auto laid out version of EditorGUI.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class EditorGUILayout extends Object {\r\n        /** Make a label with a foldout arrow to the left of it.\r\n         * @param foldout The shown foldout state.\r\n         * @param content The label to show.\r\n         * @param style Optional GUIStyle.\r\n         * @param toggleOnLabelClick Specifies whether clicking the label toggles the foldout state. The default value is false. Set to true to include the label in the clickable area.\r\n         * @returns The foldout state selected by the user. If true, you should render sub-objects. \r\n         */\r\n        static Foldout(foldout: boolean, content: string, toggleOnLabelClick: boolean, style: GUIStyle): boolean\r\n        /** Make a label with a foldout arrow to the left of it.\r\n         * @param foldout The shown foldout state.\r\n         * @param content The label to show.\r\n         * @param style Optional GUIStyle.\r\n         * @param toggleOnLabelClick Specifies whether clicking the label toggles the foldout state. The default value is false. Set to true to include the label in the clickable area.\r\n         * @returns The foldout state selected by the user. If true, you should render sub-objects. \r\n         */\r\n        static Foldout(foldout: boolean, content: GUIContent, toggleOnLabelClick: boolean, style: GUIStyle): boolean\r\n        /** Make a label with a foldout arrow to the left of it.\r\n         * @param foldout The shown foldout state.\r\n         * @param content The label to show.\r\n         * @param style Optional GUIStyle.\r\n         * @param toggleOnLabelClick Specifies whether clicking the label toggles the foldout state. The default value is false. Set to true to include the label in the clickable area.\r\n         * @returns The foldout state selected by the user. If true, you should render sub-objects. \r\n         */\r\n        static Foldout(foldout: boolean, content: string, style: GUIStyle): boolean\r\n        /** Make a label with a foldout arrow to the left of it.\r\n         * @param foldout The shown foldout state.\r\n         * @param content The label to show.\r\n         * @param style Optional GUIStyle.\r\n         * @param toggleOnLabelClick Specifies whether clicking the label toggles the foldout state. The default value is false. Set to true to include the label in the clickable area.\r\n         * @returns The foldout state selected by the user. If true, you should render sub-objects. \r\n         */\r\n        static Foldout(foldout: boolean, content: GUIContent, style: GUIStyle): boolean\r\n        static Foldout(foldout: boolean, content: string, toggleOnLabelClick: boolean): boolean\r\n        static Foldout(foldout: boolean, content: GUIContent, toggleOnLabelClick: boolean): boolean\r\n        /** Make a label with a foldout arrow to the left of it.\r\n         * @param foldout The shown foldout state.\r\n         * @param content The label to show.\r\n         * @param style Optional GUIStyle.\r\n         * @param toggleOnLabelClick Specifies whether clicking the label toggles the foldout state. The default value is false. Set to true to include the label in the clickable area.\r\n         * @returns The foldout state selected by the user. If true, you should render sub-objects. \r\n         */\r\n        static Foldout(foldout: boolean, content: string): boolean\r\n        /** Make a label with a foldout arrow to the left of it.\r\n         * @param foldout The shown foldout state.\r\n         * @param content The label to show.\r\n         * @param style Optional GUIStyle.\r\n         * @param toggleOnLabelClick Specifies whether clicking the label toggles the foldout state. The default value is false. Set to true to include the label in the clickable area.\r\n         * @returns The foldout state selected by the user. If true, you should render sub-objects. \r\n         */\r\n        static Foldout(foldout: boolean, content: GUIContent): boolean\r\n        /** Make a label in front of some control.\r\n         * @param label Label to show to the left of the control.\r\n         */\r\n        static PrefixLabel(label: string, followingStyle: GUIStyle, labelStyle: GUIStyle): void\r\n        /** Make a label in front of some control.\r\n         * @param label Label to show to the left of the control.\r\n         */\r\n        static PrefixLabel(label: GUIContent, followingStyle: GUIStyle, labelStyle: GUIStyle): void\r\n        /** Make a label in front of some control.\r\n         * @param label Label to show to the left of the control.\r\n         */\r\n        static PrefixLabel(label: string, followingStyle: GUIStyle): void\r\n        /** Make a label in front of some control.\r\n         * @param label Label to show to the left of the control.\r\n         */\r\n        static PrefixLabel(label: GUIContent, followingStyle: GUIStyle): void\r\n        /** Make a label in front of some control.\r\n         * @param label Label to show to the left of the control.\r\n         */\r\n        static PrefixLabel(label: string): void\r\n        /** Make a label in front of some control.\r\n         * @param label Label to show to the left of the control.\r\n         */\r\n        static PrefixLabel(label: GUIContent): void\r\n        /** Make a label field. (Useful for showing read-only info.)\r\n         * @param label Label in front of the label field.\r\n         * @param label2 The label to show to the right.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static LabelField(label: string, label2: string, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Make a label field. (Useful for showing read-only info.)\r\n         * @param label Label in front of the label field.\r\n         * @param label2 The label to show to the right.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static LabelField(label: GUIContent, label2: GUIContent, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Make a label field. (Useful for showing read-only info.)\r\n         * @param label Label in front of the label field.\r\n         * @param label2 The label to show to the right.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static LabelField(label: string, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Make a label field. (Useful for showing read-only info.)\r\n         * @param label Label in front of the label field.\r\n         * @param label2 The label to show to the right.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static LabelField(label: GUIContent, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Make a label field. (Useful for showing read-only info.)\r\n         * @param label Label in front of the label field.\r\n         * @param label2 The label to show to the right.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static LabelField(label: string, label2: string, ...options: GUILayoutOption[]): void\r\n        /** Make a label field. (Useful for showing read-only info.)\r\n         * @param label Label in front of the label field.\r\n         * @param label2 The label to show to the right.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static LabelField(label: GUIContent, label2: GUIContent, ...options: GUILayoutOption[]): void\r\n        /** Make a label field. (Useful for showing read-only info.)\r\n         * @param label Label in front of the label field.\r\n         * @param label2 The label to show to the right.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static LabelField(label: string, ...options: GUILayoutOption[]): void\r\n        /** Make a label field. (Useful for showing read-only info.)\r\n         * @param label Label in front of the label field.\r\n         * @param label2 The label to show to the right.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static LabelField(label: GUIContent, ...options: GUILayoutOption[]): void\r\n        /** Make a toggle.\r\n         * @param label Optional label in front of the toggle.\r\n         * @param value The shown state of the toggle.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout\n        properties. Any values passed in here will override settings defined by the style.<br>\n\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The selected state of the toggle. \r\n         */\r\n        static Toggle(label: string, value: boolean, style: GUIStyle, ...options: GUILayoutOption[]): boolean\r\n        /** Make a toggle.\r\n         * @param label Optional label in front of the toggle.\r\n         * @param value The shown state of the toggle.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout\n        properties. Any values passed in here will override settings defined by the style.<br>\n\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The selected state of the toggle. \r\n         */\r\n        static Toggle(label: GUIContent, value: boolean, style: GUIStyle, ...options: GUILayoutOption[]): boolean\r\n        /** Make a toggle.\r\n         * @param label Optional label in front of the toggle.\r\n         * @param value The shown state of the toggle.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout\n        properties. Any values passed in here will override settings defined by the style.<br>\n\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The selected state of the toggle. \r\n         */\r\n        static Toggle(label: string, value: boolean, ...options: GUILayoutOption[]): boolean\r\n        /** Make a toggle.\r\n         * @param label Optional label in front of the toggle.\r\n         * @param value The shown state of the toggle.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout\n        properties. Any values passed in here will override settings defined by the style.<br>\n\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The selected state of the toggle. \r\n         */\r\n        static Toggle(label: GUIContent, value: boolean, ...options: GUILayoutOption[]): boolean\r\n        /** Make a toggle.\r\n         * @param label Optional label in front of the toggle.\r\n         * @param value The shown state of the toggle.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout\n        properties. Any values passed in here will override settings defined by the style.<br>\n\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The selected state of the toggle. \r\n         */\r\n        static Toggle(value: boolean, style: GUIStyle, ...options: GUILayoutOption[]): boolean\r\n        /** Make a toggle.\r\n         * @param label Optional label in front of the toggle.\r\n         * @param value The shown state of the toggle.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout\n        properties. Any values passed in here will override settings defined by the style.<br>\n\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The selected state of the toggle. \r\n         */\r\n        static Toggle(value: boolean, ...options: GUILayoutOption[]): boolean\r\n        /** Make a toggle field where the toggle is to the left and the label immediately to the right of it.\r\n         * @param label Label to display next to the toggle.\r\n         * @param value The value to edit.\r\n         * @param labelStyle Optional GUIStyle to use for the label.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static ToggleLeft(label: string, value: boolean, labelStyle: GUIStyle, ...options: GUILayoutOption[]): boolean\r\n        /** Make a toggle field where the toggle is to the left and the label immediately to the right of it.\r\n         * @param label Label to display next to the toggle.\r\n         * @param value The value to edit.\r\n         * @param labelStyle Optional GUIStyle to use for the label.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static ToggleLeft(label: GUIContent, value: boolean, labelStyle: GUIStyle, ...options: GUILayoutOption[]): boolean\r\n        /** Make a toggle field where the toggle is to the left and the label immediately to the right of it.\r\n         * @param label Label to display next to the toggle.\r\n         * @param value The value to edit.\r\n         * @param labelStyle Optional GUIStyle to use for the label.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static ToggleLeft(label: string, value: boolean, ...options: GUILayoutOption[]): boolean\r\n        /** Make a toggle field where the toggle is to the left and the label immediately to the right of it.\r\n         * @param label Label to display next to the toggle.\r\n         * @param value The value to edit.\r\n         * @param labelStyle Optional GUIStyle to use for the label.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static ToggleLeft(label: GUIContent, value: boolean, ...options: GUILayoutOption[]): boolean\r\n        /** Make a text field.\r\n         * @param label Optional label to display in front of the text field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The text entered by the user. \r\n         */\r\n        static TextField(label: string, text: string, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a text field.\r\n         * @param label Optional label to display in front of the text field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The text entered by the user. \r\n         */\r\n        static TextField(label: GUIContent, text: string, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a text field.\r\n         * @param label Optional label to display in front of the text field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The text entered by the user. \r\n         */\r\n        static TextField(text: string, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a text field.\r\n         * @param label Optional label to display in front of the text field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The text entered by the user. \r\n         */\r\n        static TextField(label: string, text: string, ...options: GUILayoutOption[]): string\r\n        /** Make a text field.\r\n         * @param label Optional label to display in front of the text field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The text entered by the user. \r\n         */\r\n        static TextField(label: GUIContent, text: string, ...options: GUILayoutOption[]): string\r\n        /** Make a text field.\r\n         * @param label Optional label to display in front of the text field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The text entered by the user. \r\n         */\r\n        static TextField(text: string, ...options: GUILayoutOption[]): string\r\n        /** Make a delayed text field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the text field. \r\n         */\r\n        static DelayedTextField(label: string, text: string, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a delayed text field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the text field. \r\n         */\r\n        static DelayedTextField(label: GUIContent, text: string, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a delayed text field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the text field. \r\n         */\r\n        static DelayedTextField(text: string, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a delayed text field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the text field. \r\n         */\r\n        static DelayedTextField(label: string, text: string, ...options: GUILayoutOption[]): string\r\n        /** Make a delayed text field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the text field. \r\n         */\r\n        static DelayedTextField(label: GUIContent, text: string, ...options: GUILayoutOption[]): string\r\n        /** Make a delayed text field.\r\n         * @param property The text property to edit.\r\n         * @param label Optional label to display in front of the int field. Pass GUIContent.none to hide label.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static DelayedTextField(property: SerializedProperty, label: GUIContent, ...options: GUILayoutOption[]): void\r\n        /** Make a delayed text field.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the text field. \r\n         */\r\n        static DelayedTextField(text: string, ...options: GUILayoutOption[]): string\r\n        /** Make a delayed text field.\r\n         * @param property The text property to edit.\r\n         * @param label Optional label to display in front of the int field. Pass GUIContent.none to hide label.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static DelayedTextField(property: SerializedProperty, ...options: GUILayoutOption[]): void\r\n        /** Make a text area.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The text entered by the user. \r\n         */\r\n        static TextArea(text: string, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a text area.\r\n         * @param text The text to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The text entered by the user. \r\n         */\r\n        static TextArea(text: string, ...options: GUILayoutOption[]): string\r\n        /** Make a selectable label field. (Useful for showing read-only info that can be copy-pasted.)\r\n         * @param text The text to show.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static SelectableLabel(text: string, style: GUIStyle, ...options: GUILayoutOption[]): void\r\n        /** Make a selectable label field. (Useful for showing read-only info that can be copy-pasted.)\r\n         * @param text The text to show.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static SelectableLabel(text: string, ...options: GUILayoutOption[]): void\r\n        /** Make a text field where the user can enter a password.\r\n         * @param label Optional label to display in front of the password field.\r\n         * @param password The password to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The password entered by the user. \r\n         */\r\n        static PasswordField(label: string, password: string, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a text field where the user can enter a password.\r\n         * @param label Optional label to display in front of the password field.\r\n         * @param password The password to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The password entered by the user. \r\n         */\r\n        static PasswordField(label: GUIContent, password: string, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a text field where the user can enter a password.\r\n         * @param label Optional label to display in front of the password field.\r\n         * @param password The password to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The password entered by the user. \r\n         */\r\n        static PasswordField(password: string, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a text field where the user can enter a password.\r\n         * @param label Optional label to display in front of the password field.\r\n         * @param password The password to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The password entered by the user. \r\n         */\r\n        static PasswordField(label: string, password: string, ...options: GUILayoutOption[]): string\r\n        /** Make a text field where the user can enter a password.\r\n         * @param label Optional label to display in front of the password field.\r\n         * @param password The password to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The password entered by the user. \r\n         */\r\n        static PasswordField(label: GUIContent, password: string, ...options: GUILayoutOption[]): string\r\n        /** Make a text field where the user can enter a password.\r\n         * @param label Optional label to display in front of the password field.\r\n         * @param password The password to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The password entered by the user. \r\n         */\r\n        static PasswordField(password: string, ...options: GUILayoutOption[]): string\r\n        /** Make a text field for entering float values.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static FloatField(label: string, value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering float values.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static FloatField(label: GUIContent, value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering float values.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static FloatField(value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering float values.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static FloatField(label: string, value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering float values.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static FloatField(label: GUIContent, value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering float values.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static FloatField(value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering floats.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the float field. \r\n         */\r\n        static DelayedFloatField(label: string, value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering floats.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the float field. \r\n         */\r\n        static DelayedFloatField(label: GUIContent, value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering floats.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the float field. \r\n         */\r\n        static DelayedFloatField(value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering floats.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the float field. \r\n         */\r\n        static DelayedFloatField(label: string, value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering floats.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the float field. \r\n         */\r\n        static DelayedFloatField(label: GUIContent, value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering floats.\r\n         * @param property The float property to edit.\r\n         * @param label Optional label to display in front of the float field. Pass GUIContent.none to hide label.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static DelayedFloatField(property: SerializedProperty, label: GUIContent, ...options: GUILayoutOption[]): void\r\n        /** Make a delayed text field for entering floats.\r\n         * @param label Optional label to display in front of the float field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the float field. \r\n         */\r\n        static DelayedFloatField(value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering floats.\r\n         * @param property The float property to edit.\r\n         * @param label Optional label to display in front of the float field. Pass GUIContent.none to hide label.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static DelayedFloatField(property: SerializedProperty, ...options: GUILayoutOption[]): void\r\n        /** Make a text field for entering double values.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static DoubleField(label: string, value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering double values.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static DoubleField(label: GUIContent, value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering double values.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static DoubleField(value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering double values.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static DoubleField(label: string, value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering double values.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static DoubleField(label: GUIContent, value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering double values.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static DoubleField(value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering doubles.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options \n          An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\n          See Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\n          GUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\n        \r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the double field. \r\n         */\r\n        static DelayedDoubleField(label: string, value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering doubles.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options \n          An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\n          See Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\n          GUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\n        \r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the double field. \r\n         */\r\n        static DelayedDoubleField(label: GUIContent, value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering doubles.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options \n          An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\n          See Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\n          GUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\n        \r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the double field. \r\n         */\r\n        static DelayedDoubleField(value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering doubles.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options \n          An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\n          See Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\n          GUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\n        \r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the double field. \r\n         */\r\n        static DelayedDoubleField(label: string, value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering doubles.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options \n          An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\n          See Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\n          GUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\n        \r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the double field. \r\n         */\r\n        static DelayedDoubleField(label: GUIContent, value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering doubles.\r\n         * @param label Optional label to display in front of the double field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options \n          An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\n          See Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\n          GUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\n        \r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the double field. \r\n         */\r\n        static DelayedDoubleField(value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering integers.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static IntField(label: string, value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering integers.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static IntField(label: GUIContent, value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering integers.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static IntField(value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering integers.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static IntField(label: string, value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering integers.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static IntField(label: GUIContent, value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering integers.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static IntField(value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering integers.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the int field. \r\n         */\r\n        static DelayedIntField(label: string, value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering integers.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the int field. \r\n         */\r\n        static DelayedIntField(label: GUIContent, value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering integers.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the int field. \r\n         */\r\n        static DelayedIntField(value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering integers.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the int field. \r\n         */\r\n        static DelayedIntField(label: string, value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering integers.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the int field. \r\n         */\r\n        static DelayedIntField(label: GUIContent, value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering integers.\r\n         * @param property The int property to edit.\r\n         * @param label Optional label to display in front of the int field. Pass GUIContent.none to hide label.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static DelayedIntField(property: SerializedProperty, label: GUIContent, ...options: GUILayoutOption[]): void\r\n        /** Make a delayed text field for entering integers.\r\n         * @param label Optional label to display in front of the int field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. Note that the return value will not change until the user has pressed enter or focus is moved away from the int field. \r\n         */\r\n        static DelayedIntField(value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a delayed text field for entering integers.\r\n         * @param property The int property to edit.\r\n         * @param label Optional label to display in front of the int field. Pass GUIContent.none to hide label.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static DelayedIntField(property: SerializedProperty, ...options: GUILayoutOption[]): void\r\n        /** Make a text field for entering long integers.\r\n         * @param label Optional label to display in front of the long field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static LongField(label: string, value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering long integers.\r\n         * @param label Optional label to display in front of the long field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static LongField(label: GUIContent, value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering long integers.\r\n         * @param label Optional label to display in front of the long field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static LongField(value: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering long integers.\r\n         * @param label Optional label to display in front of the long field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static LongField(label: string, value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering long integers.\r\n         * @param label Optional label to display in front of the long field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static LongField(label: GUIContent, value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a text field for entering long integers.\r\n         * @param label Optional label to display in front of the long field.\r\n         * @param value The value to edit.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static LongField(value: number, ...options: GUILayoutOption[]): number\r\n        /** Make a slider the user can drag to change a value between a min and a max.\r\n         * @param label Optional label in front of the slider.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static Slider(label: string, value: number, leftValue: number, rightValue: number, ...options: GUILayoutOption[]): number\r\n        /** Make a slider the user can drag to change a value between a min and a max.\r\n         * @param label Optional label in front of the slider.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static Slider(label: GUIContent, value: number, leftValue: number, rightValue: number, ...options: GUILayoutOption[]): number\r\n        /** Make a slider the user can drag to change a value between a min and a max.\r\n         * @param label Optional label in front of the slider.\r\n         * @param property The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static Slider(property: SerializedProperty, leftValue: number, rightValue: number, label: string, ...options: GUILayoutOption[]): void\r\n        /** Make a slider the user can drag to change a value between a min and a max.\r\n         * @param label Optional label in front of the slider.\r\n         * @param property The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static Slider(property: SerializedProperty, leftValue: number, rightValue: number, label: GUIContent, ...options: GUILayoutOption[]): void\r\n        /** Make a slider the user can drag to change a value between a min and a max.\r\n         * @param label Optional label in front of the slider.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static Slider(value: number, leftValue: number, rightValue: number, ...options: GUILayoutOption[]): number\r\n        /** Make a slider the user can drag to change a value between a min and a max.\r\n         * @param label Optional label in front of the slider.\r\n         * @param property The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static Slider(property: SerializedProperty, leftValue: number, rightValue: number, ...options: GUILayoutOption[]): void\r\n        /** Make a slider the user can drag to change an integer value between a min and a max.\r\n         * @param label Optional label in front of the slider.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static IntSlider(label: string, value: number, leftValue: number, rightValue: number, ...options: GUILayoutOption[]): number\r\n        /** Make a slider the user can drag to change an integer value between a min and a max.\r\n         * @param label Optional label in front of the slider.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static IntSlider(label: GUIContent, value: number, leftValue: number, rightValue: number, ...options: GUILayoutOption[]): number\r\n        /** Make a slider the user can drag to change an integer value between a min and a max.\r\n         * @param label Optional label in front of the slider.\r\n         * @param property The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static IntSlider(property: SerializedProperty, leftValue: number, rightValue: number, label: string, ...options: GUILayoutOption[]): void\r\n        /** Make a slider the user can drag to change an integer value between a min and a max.\r\n         * @param label Optional label in front of the slider.\r\n         * @param property The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static IntSlider(property: SerializedProperty, leftValue: number, rightValue: number, label: GUIContent, ...options: GUILayoutOption[]): void\r\n        /** Make a slider the user can drag to change an integer value between a min and a max.\r\n         * @param label Optional label in front of the slider.\r\n         * @param value The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value that has been set by the user. \r\n         */\r\n        static IntSlider(value: number, leftValue: number, rightValue: number, ...options: GUILayoutOption[]): number\r\n        /** Make a slider the user can drag to change an integer value between a min and a max.\r\n         * @param label Optional label in front of the slider.\r\n         * @param property The value the slider shows. This determines the position of the draggable thumb.\r\n         * @param leftValue The value at the left end of the slider.\r\n         * @param rightValue The value at the right end of the slider.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static IntSlider(property: SerializedProperty, leftValue: number, rightValue: number, ...options: GUILayoutOption[]): void\r\n        /** Make a special slider the user can use to specify a range between a min and a max.\r\n         * @param label Optional label in front of the slider.\r\n         * @param minValue The lower value of the range the slider shows, passed by reference.\r\n         * @param maxValue The upper value at the range the slider shows, passed by reference.\r\n         * @param minLimit The limit at the left end of the slider.\r\n         * @param maxLimit The limit at the right end of the slider.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static MinMaxSlider(label: string, minValue: jsb.Ref<number>, maxValue: jsb.Ref<number>, minLimit: number, maxLimit: number, ...options: GUILayoutOption[]): void\r\n        /** Make a special slider the user can use to specify a range between a min and a max.\r\n         * @param label Optional label in front of the slider.\r\n         * @param minValue The lower value of the range the slider shows, passed by reference.\r\n         * @param maxValue The upper value at the range the slider shows, passed by reference.\r\n         * @param minLimit The limit at the left end of the slider.\r\n         * @param maxLimit The limit at the right end of the slider.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static MinMaxSlider(label: GUIContent, minValue: jsb.Ref<number>, maxValue: jsb.Ref<number>, minLimit: number, maxLimit: number, ...options: GUILayoutOption[]): void\r\n        /** Make a special slider the user can use to specify a range between a min and a max.\r\n         * @param label Optional label in front of the slider.\r\n         * @param minValue The lower value of the range the slider shows, passed by reference.\r\n         * @param maxValue The upper value at the range the slider shows, passed by reference.\r\n         * @param minLimit The limit at the left end of the slider.\r\n         * @param maxLimit The limit at the right end of the slider.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static MinMaxSlider(minValue: jsb.Ref<number>, maxValue: jsb.Ref<number>, minLimit: number, maxLimit: number, ...options: GUILayoutOption[]): void\r\n        /** Make a generic popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedIndex The index of the option the field shows.\r\n         * @param displayedOptions An array with the options shown in the popup.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The index of the option that has been selected by the user. \r\n         */\r\n        static Popup(label: string, selectedIndex: number, displayedOptions: Array<string>, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a generic popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedIndex The index of the option the field shows.\r\n         * @param displayedOptions An array with the options shown in the popup.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The index of the option that has been selected by the user. \r\n         */\r\n        static Popup(label: GUIContent, selectedIndex: number, displayedOptions: Array<GUIContent>, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a generic popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedIndex The index of the option the field shows.\r\n         * @param displayedOptions An array with the options shown in the popup.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The index of the option that has been selected by the user. \r\n         */\r\n        static Popup(selectedIndex: number, displayedOptions: Array<string>, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a generic popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedIndex The index of the option the field shows.\r\n         * @param displayedOptions An array with the options shown in the popup.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The index of the option that has been selected by the user. \r\n         */\r\n        static Popup(selectedIndex: number, displayedOptions: Array<GUIContent>, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a generic popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedIndex The index of the option the field shows.\r\n         * @param displayedOptions An array with the options shown in the popup.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The index of the option that has been selected by the user. \r\n         */\r\n        static Popup(label: string, selectedIndex: number, displayedOptions: Array<string>, ...options: GUILayoutOption[]): number\r\n        static Popup(label: GUIContent, selectedIndex: number, displayedOptions: Array<string>, ...options: GUILayoutOption[]): number\r\n        /** Make a generic popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedIndex The index of the option the field shows.\r\n         * @param displayedOptions An array with the options shown in the popup.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The index of the option that has been selected by the user. \r\n         */\r\n        static Popup(label: GUIContent, selectedIndex: number, displayedOptions: Array<GUIContent>, ...options: GUILayoutOption[]): number\r\n        /** Make a generic popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedIndex The index of the option the field shows.\r\n         * @param displayedOptions An array with the options shown in the popup.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The index of the option that has been selected by the user. \r\n         */\r\n        static Popup(selectedIndex: number, displayedOptions: Array<string>, ...options: GUILayoutOption[]): number\r\n        /** Make a generic popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedIndex The index of the option the field shows.\r\n         * @param displayedOptions An array with the options shown in the popup.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The index of the option that has been selected by the user. \r\n         */\r\n        static Popup(selectedIndex: number, displayedOptions: Array<GUIContent>, ...options: GUILayoutOption[]): number\r\n        static EnumPopup(label: GUIContent, selected: Enum, checkEnabled: (arg: Enum) => boolean, includeObsolete: boolean, style: GUIStyle, ...options: GUILayoutOption[]): Enum\r\n        static EnumPopup(label: GUIContent, selected: Enum, checkEnabled: (arg: Enum) => boolean, includeObsolete: boolean, ...options: GUILayoutOption[]): Enum\r\n        /** Make an enum popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selected The enum option the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @param checkEnabled Method called for each Enum value displayed. The specified method should return true if the option can be selected, false otherwise.\r\n         * @returns The enum option that has been selected by the user. \r\n         */\r\n        static EnumPopup(label: string, selected: Enum, style: GUIStyle, ...options: GUILayoutOption[]): Enum\r\n        /** Make an enum popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selected The enum option the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @param checkEnabled Method called for each Enum value displayed. The specified method should return true if the option can be selected, false otherwise.\r\n         * @returns The enum option that has been selected by the user. \r\n         */\r\n        static EnumPopup(label: GUIContent, selected: Enum, style: GUIStyle, ...options: GUILayoutOption[]): Enum\r\n        /** Make an enum popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selected The enum option the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @param checkEnabled Method called for each Enum value displayed. The specified method should return true if the option can be selected, false otherwise.\r\n         * @returns The enum option that has been selected by the user. \r\n         */\r\n        static EnumPopup(selected: Enum, style: GUIStyle, ...options: GUILayoutOption[]): Enum\r\n        /** Make an enum popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selected The enum option the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @param checkEnabled Method called for each Enum value displayed. The specified method should return true if the option can be selected, false otherwise.\r\n         * @returns The enum option that has been selected by the user. \r\n         */\r\n        static EnumPopup(label: string, selected: Enum, ...options: GUILayoutOption[]): Enum\r\n        /** Make an enum popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selected The enum option the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @param checkEnabled Method called for each Enum value displayed. The specified method should return true if the option can be selected, false otherwise.\r\n         * @returns The enum option that has been selected by the user. \r\n         */\r\n        static EnumPopup(label: GUIContent, selected: Enum, ...options: GUILayoutOption[]): Enum\r\n        /** Make an enum popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selected The enum option the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @param checkEnabled Method called for each Enum value displayed. The specified method should return true if the option can be selected, false otherwise.\r\n         * @returns The enum option that has been selected by the user. \r\n         */\r\n        static EnumPopup(selected: Enum, ...options: GUILayoutOption[]): Enum\r\n        /** Make an integer popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedValue The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value of the option that has been selected by the user. \r\n         */\r\n        static IntPopup(label: string, selectedValue: number, displayedOptions: Array<string>, optionValues: Array<number>, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make an integer popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedValue The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value of the option that has been selected by the user. \r\n         */\r\n        static IntPopup(label: GUIContent, selectedValue: number, displayedOptions: Array<GUIContent>, optionValues: Array<number>, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make an integer popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedValue The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value of the option that has been selected by the user. \r\n         */\r\n        static IntPopup(selectedValue: number, displayedOptions: Array<string>, optionValues: Array<number>, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make an integer popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedValue The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value of the option that has been selected by the user. \r\n         */\r\n        static IntPopup(selectedValue: number, displayedOptions: Array<GUIContent>, optionValues: Array<number>, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make an integer popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedValue The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value of the option that has been selected by the user. \r\n         */\r\n        static IntPopup(label: string, selectedValue: number, displayedOptions: Array<string>, optionValues: Array<number>, ...options: GUILayoutOption[]): number\r\n        /** Make an integer popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedValue The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value of the option that has been selected by the user. \r\n         */\r\n        static IntPopup(label: GUIContent, selectedValue: number, displayedOptions: Array<GUIContent>, optionValues: Array<number>, ...options: GUILayoutOption[]): number\r\n        /** Make an integer popup selection field.\r\n         * @param property The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option.\r\n         * @param label Optional label in front of the field.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static IntPopup(property: SerializedProperty, displayedOptions: Array<GUIContent>, optionValues: Array<number>, label: GUIContent, ...options: GUILayoutOption[]): void\r\n        /** Make an integer popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedValue The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value of the option that has been selected by the user. \r\n         */\r\n        static IntPopup(selectedValue: number, displayedOptions: Array<string>, optionValues: Array<number>, ...options: GUILayoutOption[]): number\r\n        /** Make an integer popup selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param selectedValue The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value of the option that has been selected by the user. \r\n         */\r\n        static IntPopup(selectedValue: number, displayedOptions: Array<GUIContent>, optionValues: Array<number>, ...options: GUILayoutOption[]): number\r\n        /** Make an integer popup selection field.\r\n         * @param property The value of the option the field shows.\r\n         * @param displayedOptions An array with the displayed options the user can choose from.\r\n         * @param optionValues An array with the values for each option.\r\n         * @param label Optional label in front of the field.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static IntPopup(property: SerializedProperty, displayedOptions: Array<GUIContent>, optionValues: Array<number>, ...options: GUILayoutOption[]): void\r\n        /** Make a tag selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param tag The tag the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The tag selected by the user. \r\n         */\r\n        static TagField(label: string, tag: string, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a tag selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param tag The tag the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The tag selected by the user. \r\n         */\r\n        static TagField(label: GUIContent, tag: string, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a tag selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param tag The tag the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The tag selected by the user. \r\n         */\r\n        static TagField(tag: string, style: GUIStyle, ...options: GUILayoutOption[]): string\r\n        /** Make a tag selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param tag The tag the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The tag selected by the user. \r\n         */\r\n        static TagField(label: string, tag: string, ...options: GUILayoutOption[]): string\r\n        /** Make a tag selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param tag The tag the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The tag selected by the user. \r\n         */\r\n        static TagField(label: GUIContent, tag: string, ...options: GUILayoutOption[]): string\r\n        /** Make a tag selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param tag The tag the field shows.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The tag selected by the user. \r\n         */\r\n        static TagField(tag: string, ...options: GUILayoutOption[]): string\r\n        /** Make a layer selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param layer The layer shown in the field.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The layer selected by the user. \r\n         */\r\n        static LayerField(label: string, layer: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a layer selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param layer The layer shown in the field.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The layer selected by the user. \r\n         */\r\n        static LayerField(label: GUIContent, layer: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a layer selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param layer The layer shown in the field.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The layer selected by the user. \r\n         */\r\n        static LayerField(layer: number, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a layer selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param layer The layer shown in the field.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The layer selected by the user. \r\n         */\r\n        static LayerField(label: string, layer: number, ...options: GUILayoutOption[]): number\r\n        /** Make a layer selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param layer The layer shown in the field.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The layer selected by the user. \r\n         */\r\n        static LayerField(label: GUIContent, layer: number, ...options: GUILayoutOption[]): number\r\n        /** Make a layer selection field.\r\n         * @param label Optional label in front of the field.\r\n         * @param layer The layer shown in the field.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The layer selected by the user. \r\n         */\r\n        static LayerField(layer: number, ...options: GUILayoutOption[]): number\r\n        /** Make a field for masks.\r\n         * @param label Prefix label of the field.\r\n         * @param mask The current mask to display.\r\n         * @param displayedOption A string array containing the labels for each flag.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value modified by the user. \r\n         */\r\n        static MaskField(label: GUIContent, mask: number, displayedOptions: Array<string>, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a field for masks.\r\n         * @param label Prefix label of the field.\r\n         * @param mask The current mask to display.\r\n         * @param displayedOption A string array containing the labels for each flag.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value modified by the user. \r\n         */\r\n        static MaskField(label: string, mask: number, displayedOptions: Array<string>, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a field for masks.\r\n         * @param label Prefix label of the field.\r\n         * @param mask The current mask to display.\r\n         * @param displayedOption A string array containing the labels for each flag.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value modified by the user. \r\n         */\r\n        static MaskField(label: GUIContent, mask: number, displayedOptions: Array<string>, ...options: GUILayoutOption[]): number\r\n        /** Make a field for masks.\r\n         * @param label Prefix label of the field.\r\n         * @param mask The current mask to display.\r\n         * @param displayedOption A string array containing the labels for each flag.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value modified by the user. \r\n         */\r\n        static MaskField(label: string, mask: number, displayedOptions: Array<string>, ...options: GUILayoutOption[]): number\r\n        /** Make a field for masks.\r\n         * @param label Prefix label of the field.\r\n         * @param mask The current mask to display.\r\n         * @param displayedOption A string array containing the labels for each flag.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value modified by the user. \r\n         */\r\n        static MaskField(mask: number, displayedOptions: Array<string>, style: GUIStyle, ...options: GUILayoutOption[]): number\r\n        /** Make a field for masks.\r\n         * @param label Prefix label of the field.\r\n         * @param mask The current mask to display.\r\n         * @param displayedOption A string array containing the labels for each flag.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value modified by the user. \r\n         */\r\n        static MaskField(mask: number, displayedOptions: Array<string>, ...options: GUILayoutOption[]): number\r\n        /** Displays a menu with an option for every value of the enum type when clicked.\r\n         * @param label Optional label to display in front of the enum flags field.\r\n         * @param enumValue Enum flags value.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @returns The enum flags value modified by the user. This is a selection BitMask where each bit represents an Enum value index. (Note this returned value is not itself an Enum). \r\n         */\r\n        static EnumFlagsField(label: GUIContent, enumValue: Enum, includeObsolete: boolean, style: GUIStyle, ...options: GUILayoutOption[]): Enum\r\n        /** Displays a menu with an option for every value of the enum type when clicked.\r\n         * @param label Optional label to display in front of the enum flags field.\r\n         * @param enumValue Enum flags value.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @returns The enum flags value modified by the user. This is a selection BitMask where each bit represents an Enum value index. (Note this returned value is not itself an Enum). \r\n         */\r\n        static EnumFlagsField(label: string, enumValue: Enum, style: GUIStyle, ...options: GUILayoutOption[]): Enum\r\n        /** Displays a menu with an option for every value of the enum type when clicked.\r\n         * @param label Optional label to display in front of the enum flags field.\r\n         * @param enumValue Enum flags value.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @returns The enum flags value modified by the user. This is a selection BitMask where each bit represents an Enum value index. (Note this returned value is not itself an Enum). \r\n         */\r\n        static EnumFlagsField(label: GUIContent, enumValue: Enum, style: GUIStyle, ...options: GUILayoutOption[]): Enum\r\n        /** Displays a menu with an option for every value of the enum type when clicked.\r\n         * @param label Optional label to display in front of the enum flags field.\r\n         * @param enumValue Enum flags value.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @returns The enum flags value modified by the user. This is a selection BitMask where each bit represents an Enum value index. (Note this returned value is not itself an Enum). \r\n         */\r\n        static EnumFlagsField(label: GUIContent, enumValue: Enum, includeObsolete: boolean, ...options: GUILayoutOption[]): Enum\r\n        /** Displays a menu with an option for every value of the enum type when clicked.\r\n         * @param label Optional label to display in front of the enum flags field.\r\n         * @param enumValue Enum flags value.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @returns The enum flags value modified by the user. This is a selection BitMask where each bit represents an Enum value index. (Note this returned value is not itself an Enum). \r\n         */\r\n        static EnumFlagsField(enumValue: Enum, style: GUIStyle, ...options: GUILayoutOption[]): Enum\r\n        /** Displays a menu with an option for every value of the enum type when clicked.\r\n         * @param label Optional label to display in front of the enum flags field.\r\n         * @param enumValue Enum flags value.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @returns The enum flags value modified by the user. This is a selection BitMask where each bit represents an Enum value index. (Note this returned value is not itself an Enum). \r\n         */\r\n        static EnumFlagsField(label: string, enumValue: Enum, ...options: GUILayoutOption[]): Enum\r\n        /** Displays a menu with an option for every value of the enum type when clicked.\r\n         * @param label Optional label to display in front of the enum flags field.\r\n         * @param enumValue Enum flags value.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @returns The enum flags value modified by the user. This is a selection BitMask where each bit represents an Enum value index. (Note this returned value is not itself an Enum). \r\n         */\r\n        static EnumFlagsField(label: GUIContent, enumValue: Enum, ...options: GUILayoutOption[]): Enum\r\n        /** Displays a menu with an option for every value of the enum type when clicked.\r\n         * @param label Optional label to display in front of the enum flags field.\r\n         * @param enumValue Enum flags value.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param includeObsolete Set to true to include Enum values with ObsoleteAttribute. Set to false to exclude Enum values with ObsoleteAttribute.\r\n         * @returns The enum flags value modified by the user. This is a selection BitMask where each bit represents an Enum value index. (Note this returned value is not itself an Enum). \r\n         */\r\n        static EnumFlagsField(enumValue: Enum, ...options: GUILayoutOption[]): Enum\r\n        static ObjectField(label: string, obj: Object1, objType: any, targetBeingEdited: Object1, ...options: GUILayoutOption[]): Object1\r\n        /** Make a field to receive any object type.\r\n         * @param label Optional label in front of the field.\r\n         * @param obj The object the field shows.\r\n         * @param objType The type of the objects that can be assigned.\r\n         * @param allowSceneObjects Allow assigning Scene objects. See Description for more info.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The object that has been set by the user. \r\n         */\r\n        static ObjectField(label: string, obj: Object1, objType: any, allowSceneObjects: boolean, ...options: GUILayoutOption[]): Object1\r\n        static ObjectField(label: GUIContent, obj: Object1, objType: any, targetBeingEdited: Object1, ...options: GUILayoutOption[]): Object1\r\n        /** Make a field to receive any object type.\r\n         * @param label Optional label in front of the field.\r\n         * @param obj The object the field shows.\r\n         * @param objType The type of the objects that can be assigned.\r\n         * @param allowSceneObjects Allow assigning Scene objects. See Description for more info.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The object that has been set by the user. \r\n         */\r\n        static ObjectField(label: GUIContent, obj: Object1, objType: any, allowSceneObjects: boolean, ...options: GUILayoutOption[]): Object1\r\n        static ObjectField(obj: Object1, objType: any, targetBeingEdited: Object1, ...options: GUILayoutOption[]): Object1\r\n        /** Make a field to receive any object type.\r\n         * @param label Optional label in front of the field.\r\n         * @param obj The object the field shows.\r\n         * @param objType The type of the objects that can be assigned.\r\n         * @param allowSceneObjects Allow assigning Scene objects. See Description for more info.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The object that has been set by the user. \r\n         */\r\n        static ObjectField(obj: Object1, objType: any, allowSceneObjects: boolean, ...options: GUILayoutOption[]): Object1\r\n        /** Make a field to receive any object type.\r\n         * @param property The object reference property the field shows.\r\n         * @param objType The type of the objects that can be assigned.\r\n         * @param label Optional label in front of the field. Pass GUIContent.none to hide the label.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static ObjectField(property: SerializedProperty, objType: any, label: GUIContent, ...options: GUILayoutOption[]): void\r\n        /** Make a field to receive any object type.\r\n         * @param property The object reference property the field shows.\r\n         * @param objType The type of the objects that can be assigned.\r\n         * @param label Optional label in front of the field. Pass GUIContent.none to hide the label.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static ObjectField(property: SerializedProperty, label: GUIContent, ...options: GUILayoutOption[]): void\r\n        /** Make a field to receive any object type.\r\n         * @param property The object reference property the field shows.\r\n         * @param objType The type of the objects that can be assigned.\r\n         * @param label Optional label in front of the field. Pass GUIContent.none to hide the label.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static ObjectField(property: SerializedProperty, objType: any, ...options: GUILayoutOption[]): void\r\n        /** Make a field to receive any object type.\r\n         * @param property The object reference property the field shows.\r\n         * @param objType The type of the objects that can be assigned.\r\n         * @param label Optional label in front of the field. Pass GUIContent.none to hide the label.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static ObjectField(property: SerializedProperty, ...options: GUILayoutOption[]): void\r\n        /** Make an X & Y field for entering a Vector2.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector2Field(label: string, value: Vector2, ...options: GUILayoutOption[]): Vector2\r\n        /** Make an X & Y field for entering a Vector2.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector2Field(label: GUIContent, value: Vector2, ...options: GUILayoutOption[]): Vector2\r\n        /** Make an X, Y & Z field for entering a Vector3.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout\n        properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector3Field(label: string, value: Vector3, ...options: GUILayoutOption[]): Vector3\r\n        /** Make an X, Y & Z field for entering a Vector3.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout\n        properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector3Field(label: GUIContent, value: Vector3, ...options: GUILayoutOption[]): Vector3\r\n        /** Make an X, Y, Z & W field for entering a Vector4.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector4Field(label: string, value: Vector4, ...options: GUILayoutOption[]): Vector4\r\n        static Vector4Field(label: GUIContent, value: Vector4, ...options: GUILayoutOption[]): Vector4\r\n        /** Make an X & Y integer field for entering a Vector2Int.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector2IntField(label: string, value: Vector2Int, ...options: GUILayoutOption[]): Vector2Int\r\n        /** Make an X & Y integer field for entering a Vector2Int.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector2IntField(label: GUIContent, value: Vector2Int, ...options: GUILayoutOption[]): Vector2Int\r\n        /** Make an X, Y & Z integer field for entering a Vector3Int.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector3IntField(label: string, value: Vector3Int, ...options: GUILayoutOption[]): Vector3Int\r\n        /** Make an X, Y & Z integer field for entering a Vector3Int.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static Vector3IntField(label: GUIContent, value: Vector3Int, ...options: GUILayoutOption[]): Vector3Int\r\n        /** Make an X, Y, W & H field for entering a Rect.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static RectField(label: string, value: Rect, ...options: GUILayoutOption[]): Rect\r\n        /** Make an X, Y, W & H field for entering a Rect.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static RectField(label: GUIContent, value: Rect, ...options: GUILayoutOption[]): Rect\r\n        /** Make an X, Y, W & H field for entering a Rect.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static RectField(value: Rect, ...options: GUILayoutOption[]): Rect\r\n        /** Make an X, Y, W & H field for entering a RectInt.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static RectIntField(label: string, value: RectInt, ...options: GUILayoutOption[]): RectInt\r\n        /** Make an X, Y, W & H field for entering a RectInt.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static RectIntField(label: GUIContent, value: RectInt, ...options: GUILayoutOption[]): RectInt\r\n        /** Make an X, Y, W & H field for entering a RectInt.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static RectIntField(value: RectInt, ...options: GUILayoutOption[]): RectInt\r\n        /** Make Center & Extents field for entering a Bounds.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static BoundsField(label: string, value: Bounds, ...options: GUILayoutOption[]): Bounds\r\n        /** Make Center & Extents field for entering a Bounds.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static BoundsField(label: GUIContent, value: Bounds, ...options: GUILayoutOption[]): Bounds\r\n        /** Make Center & Extents field for entering a Bounds.\r\n         * @param label Label to display above the field.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static BoundsField(value: Bounds, ...options: GUILayoutOption[]): Bounds\r\n        /** Make Position & Size field for entering a BoundsInt.\r\n         * @param label Make Position & Size field for entering a Bounds.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static BoundsIntField(label: string, value: BoundsInt, ...options: GUILayoutOption[]): BoundsInt\r\n        /** Make Position & Size field for entering a BoundsInt.\r\n         * @param label Make Position & Size field for entering a Bounds.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static BoundsIntField(label: GUIContent, value: BoundsInt, ...options: GUILayoutOption[]): BoundsInt\r\n        /** Make Position & Size field for entering a BoundsInt.\r\n         * @param label Make Position & Size field for entering a Bounds.\r\n         * @param value The value to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The value entered by the user. \r\n         */\r\n        static BoundsIntField(value: BoundsInt, ...options: GUILayoutOption[]): BoundsInt\r\n        /** Make a field for selecting a Color.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The color to edit.\r\n         * @param showEyedropper If true, the color picker should show the eyedropper control. If false, don't show it.\r\n         * @param showAlpha If true, allow the user to set an alpha value for the color. If false, hide the alpha component.\r\n         * @param hdr If true, treat the color as an HDR value. If false, treat it as a standard LDR value.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The color selected by the user. \r\n         */\r\n        static ColorField(label: GUIContent, value: Color, showEyedropper: boolean, showAlpha: boolean, hdr: boolean, ...options: GUILayoutOption[]): Color\r\n        /** Make a field for selecting a Color.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The color to edit.\r\n         * @param showEyedropper If true, the color picker should show the eyedropper control. If false, don't show it.\r\n         * @param showAlpha If true, allow the user to set an alpha value for the color. If false, hide the alpha component.\r\n         * @param hdr If true, treat the color as an HDR value. If false, treat it as a standard LDR value.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The color selected by the user. \r\n         */\r\n        static ColorField(label: string, value: Color, ...options: GUILayoutOption[]): Color\r\n        /** Make a field for selecting a Color.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The color to edit.\r\n         * @param showEyedropper If true, the color picker should show the eyedropper control. If false, don't show it.\r\n         * @param showAlpha If true, allow the user to set an alpha value for the color. If false, hide the alpha component.\r\n         * @param hdr If true, treat the color as an HDR value. If false, treat it as a standard LDR value.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The color selected by the user. \r\n         */\r\n        static ColorField(label: GUIContent, value: Color, ...options: GUILayoutOption[]): Color\r\n        /** Make a field for selecting a Color.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The color to edit.\r\n         * @param showEyedropper If true, the color picker should show the eyedropper control. If false, don't show it.\r\n         * @param showAlpha If true, allow the user to set an alpha value for the color. If false, hide the alpha component.\r\n         * @param hdr If true, treat the color as an HDR value. If false, treat it as a standard LDR value.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The color selected by the user. \r\n         */\r\n        static ColorField(value: Color, ...options: GUILayoutOption[]): Color\r\n        /** Make a field for editing an AnimationCurve.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The curve to edit.\r\n         * @param color The color to show the curve with.\r\n         * @param ranges Optional rectangle that the curve is restrained within.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The curve edited by the user. \r\n         */\r\n        static CurveField(label: string, value: AnimationCurve, color: Color, ranges: Rect, ...options: GUILayoutOption[]): AnimationCurve\r\n        /** Make a field for editing an AnimationCurve.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The curve to edit.\r\n         * @param color The color to show the curve with.\r\n         * @param ranges Optional rectangle that the curve is restrained within.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The curve edited by the user. \r\n         */\r\n        static CurveField(label: GUIContent, value: AnimationCurve, color: Color, ranges: Rect, ...options: GUILayoutOption[]): AnimationCurve\r\n        /** Make a field for editing an AnimationCurve.\r\n         * @param property The curve to edit.\r\n         * @param color The color to show the curve with.\r\n         * @param ranges Optional rectangle that the curve is restrained within.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param label Optional label to display in front of the field. Pass [[GUIContent.none] to hide the label.\r\n         */\r\n        static CurveField(property: SerializedProperty, color: Color, ranges: Rect, label: GUIContent, ...options: GUILayoutOption[]): void\r\n        /** Make a field for editing an AnimationCurve.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The curve to edit.\r\n         * @param color The color to show the curve with.\r\n         * @param ranges Optional rectangle that the curve is restrained within.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The curve edited by the user. \r\n         */\r\n        static CurveField(value: AnimationCurve, color: Color, ranges: Rect, ...options: GUILayoutOption[]): AnimationCurve\r\n        /** Make a field for editing an AnimationCurve.\r\n         * @param property The curve to edit.\r\n         * @param color The color to show the curve with.\r\n         * @param ranges Optional rectangle that the curve is restrained within.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @param label Optional label to display in front of the field. Pass [[GUIContent.none] to hide the label.\r\n         */\r\n        static CurveField(property: SerializedProperty, color: Color, ranges: Rect, ...options: GUILayoutOption[]): void\r\n        /** Make a field for editing an AnimationCurve.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The curve to edit.\r\n         * @param color The color to show the curve with.\r\n         * @param ranges Optional rectangle that the curve is restrained within.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The curve edited by the user. \r\n         */\r\n        static CurveField(label: string, value: AnimationCurve, ...options: GUILayoutOption[]): AnimationCurve\r\n        /** Make a field for editing an AnimationCurve.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The curve to edit.\r\n         * @param color The color to show the curve with.\r\n         * @param ranges Optional rectangle that the curve is restrained within.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The curve edited by the user. \r\n         */\r\n        static CurveField(label: GUIContent, value: AnimationCurve, ...options: GUILayoutOption[]): AnimationCurve\r\n        /** Make a field for editing an AnimationCurve.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The curve to edit.\r\n         * @param color The color to show the curve with.\r\n         * @param ranges Optional rectangle that the curve is restrained within.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The curve edited by the user. \r\n         */\r\n        static CurveField(value: AnimationCurve, ...options: GUILayoutOption[]): AnimationCurve\r\n        static InspectorTitlebar(foldout: boolean, targetObj: Object1, expandable: boolean): boolean\r\n        static InspectorTitlebar(foldout: boolean, targetObjs: Array<Object1>, expandable: boolean): boolean\r\n        /** Make an inspector-window-like titlebar.\r\n         * @param foldout The foldout state shown with the arrow.\r\n         * @param targetObj The object (for example a component) or objects that the titlebar is for.\r\n         * @returns The foldout state selected by the user. \r\n         */\r\n        static InspectorTitlebar(foldout: boolean, targetObj: Object1): boolean\r\n        /** Make an inspector-window-like titlebar.\r\n         * @param foldout The foldout state shown with the arrow.\r\n         * @param targetObj The object (for example a component) or objects that the titlebar is for.\r\n         * @returns The foldout state selected by the user. \r\n         */\r\n        static InspectorTitlebar(foldout: boolean, targetObjs: Array<Object1>): boolean\r\n        static InspectorTitlebar(foldout: boolean, editor: Editor): boolean\r\n        static InspectorTitlebar(targetObjs: Array<Object1>): void\r\n        /** Make a help box with a message to the user.\r\n         * @param message The message text.\r\n         * @param type The type of message.\r\n         * @param wide If true, the box will cover the whole width of the window; otherwise it will cover the controls part only.\r\n         */\r\n        static HelpBox(message: string, type: MessageType, wide: boolean): void\r\n        /** Make a help box with a message to the user.\r\n         * @param message The message text.\r\n         * @param type The type of message.\r\n         * @param wide If true, the box will cover the whole width of the window; otherwise it will cover the controls part only.\r\n         */\r\n        static HelpBox(message: string, type: MessageType): void\r\n        static HelpBox(content: GUIContent, wide: boolean): void\r\n        static Space(width: number, expand: boolean): void\r\n        static Space(width: number): void\r\n        static Space(): void\r\n        static Separator(): void\r\n        /** Begin a vertical group with a toggle to enable or disable all the controls within at once.\r\n         * @param label Label to show above the toggled controls.\r\n         * @param toggle Enabled state of the toggle group.\r\n         * @returns The enabled state selected by the user. \r\n         */\r\n        static BeginToggleGroup(label: string, toggle: boolean): boolean\r\n        /** Begin a vertical group with a toggle to enable or disable all the controls within at once.\r\n         * @param label Label to show above the toggled controls.\r\n         * @param toggle Enabled state of the toggle group.\r\n         * @returns The enabled state selected by the user. \r\n         */\r\n        static BeginToggleGroup(label: GUIContent, toggle: boolean): boolean\r\n        static EndToggleGroup(): void\r\n        /** Begin a horizontal group and get its rect back.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout\n        properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static BeginHorizontal(style: GUIStyle, ...options: GUILayoutOption[]): Rect\r\n        /** Begin a horizontal group and get its rect back.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout\n        properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static BeginHorizontal(...options: GUILayoutOption[]): Rect\r\n        static EndHorizontal(): void\r\n        /** Begin a vertical group and get its rect back.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties.\n        Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static BeginVertical(style: GUIStyle, ...options: GUILayoutOption[]): Rect\r\n        /** Begin a vertical group and get its rect back.\r\n         * @param style Optional GUIStyle.\r\n         * @param options An optional list of layout options that specify extra layout properties.\n        Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static BeginVertical(...options: GUILayoutOption[]): Rect\r\n        static EndVertical(): void\r\n        /** Begin an automatically laid out scrollview.\r\n         * @param scrollPosition The position to use display.\r\n         * @param alwayShowHorizontal Optional parameter to always show the horizontal scrollbar. If false or left out, it is only shown when the content inside the ScrollView is wider than the scrollview itself.\r\n         * @param alwayShowVertical Optional parameter to always show the vertical scrollbar. If false or left out, it is only shown when content inside the ScrollView is taller than the scrollview itself.\r\n         * @param horizontalScrollbar Optional GUIStyle to use for the horizontal scrollbar. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param verticalScrollbar Optional GUIStyle to use for the vertical scrollbar. If left out, the verticalScrollbar style from the current GUISkin is used.\r\n         * @returns The modified scrollPosition. Feed this back into the variable you pass in, as shown in the example. \r\n         */\r\n        static BeginScrollView(scrollPosition: Vector2, alwaysShowHorizontal: boolean, alwaysShowVertical: boolean, horizontalScrollbar: GUIStyle, verticalScrollbar: GUIStyle, background: GUIStyle, ...options: GUILayoutOption[]): Vector2\r\n        /** Begin an automatically laid out scrollview.\r\n         * @param scrollPosition The position to use display.\r\n         * @param alwayShowHorizontal Optional parameter to always show the horizontal scrollbar. If false or left out, it is only shown when the content inside the ScrollView is wider than the scrollview itself.\r\n         * @param alwayShowVertical Optional parameter to always show the vertical scrollbar. If false or left out, it is only shown when content inside the ScrollView is taller than the scrollview itself.\r\n         * @param horizontalScrollbar Optional GUIStyle to use for the horizontal scrollbar. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param verticalScrollbar Optional GUIStyle to use for the vertical scrollbar. If left out, the verticalScrollbar style from the current GUISkin is used.\r\n         * @returns The modified scrollPosition. Feed this back into the variable you pass in, as shown in the example. \r\n         */\r\n        static BeginScrollView(scrollPosition: Vector2, alwaysShowHorizontal: boolean, alwaysShowVertical: boolean, ...options: GUILayoutOption[]): Vector2\r\n        /** Begin an automatically laid out scrollview.\r\n         * @param scrollPosition The position to use display.\r\n         * @param alwayShowHorizontal Optional parameter to always show the horizontal scrollbar. If false or left out, it is only shown when the content inside the ScrollView is wider than the scrollview itself.\r\n         * @param alwayShowVertical Optional parameter to always show the vertical scrollbar. If false or left out, it is only shown when content inside the ScrollView is taller than the scrollview itself.\r\n         * @param horizontalScrollbar Optional GUIStyle to use for the horizontal scrollbar. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param verticalScrollbar Optional GUIStyle to use for the vertical scrollbar. If left out, the verticalScrollbar style from the current GUISkin is used.\r\n         * @returns The modified scrollPosition. Feed this back into the variable you pass in, as shown in the example. \r\n         */\r\n        static BeginScrollView(scrollPosition: Vector2, horizontalScrollbar: GUIStyle, verticalScrollbar: GUIStyle, ...options: GUILayoutOption[]): Vector2\r\n        static BeginScrollView(scrollPosition: Vector2, style: GUIStyle, ...options: GUILayoutOption[]): Vector2\r\n        /** Begin an automatically laid out scrollview.\r\n         * @param scrollPosition The position to use display.\r\n         * @param alwayShowHorizontal Optional parameter to always show the horizontal scrollbar. If false or left out, it is only shown when the content inside the ScrollView is wider than the scrollview itself.\r\n         * @param alwayShowVertical Optional parameter to always show the vertical scrollbar. If false or left out, it is only shown when content inside the ScrollView is taller than the scrollview itself.\r\n         * @param horizontalScrollbar Optional GUIStyle to use for the horizontal scrollbar. If left out, the horizontalScrollbar style from the current GUISkin is used.\r\n         * @param verticalScrollbar Optional GUIStyle to use for the vertical scrollbar. If left out, the verticalScrollbar style from the current GUISkin is used.\r\n         * @returns The modified scrollPosition. Feed this back into the variable you pass in, as shown in the example. \r\n         */\r\n        static BeginScrollView(scrollPosition: Vector2, ...options: GUILayoutOption[]): Vector2\r\n        static EndScrollView(): void\r\n        /** Make a field for SerializedProperty.\r\n         * @param property The SerializedProperty to make a field for.\r\n         * @param label Optional label to use. If not specified the label of the property itself is used. Use GUIContent.none to not display a label at all.\r\n         * @param includeChildren If true the property including children is drawn; otherwise only the control itself (such as only a foldout but nothing below it).\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns True if the property has children and is expanded and includeChildren was set to false; otherwise false. \r\n         */\r\n        static PropertyField(property: SerializedProperty, label: GUIContent, includeChildren: boolean, ...options: GUILayoutOption[]): boolean\r\n        /** Make a field for SerializedProperty.\r\n         * @param property The SerializedProperty to make a field for.\r\n         * @param label Optional label to use. If not specified the label of the property itself is used. Use GUIContent.none to not display a label at all.\r\n         * @param includeChildren If true the property including children is drawn; otherwise only the control itself (such as only a foldout but nothing below it).\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns True if the property has children and is expanded and includeChildren was set to false; otherwise false. \r\n         */\r\n        static PropertyField(property: SerializedProperty, label: GUIContent, ...options: GUILayoutOption[]): boolean\r\n        /** Make a field for SerializedProperty.\r\n         * @param property The SerializedProperty to make a field for.\r\n         * @param label Optional label to use. If not specified the label of the property itself is used. Use GUIContent.none to not display a label at all.\r\n         * @param includeChildren If true the property including children is drawn; otherwise only the control itself (such as only a foldout but nothing below it).\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns True if the property has children and is expanded and includeChildren was set to false; otherwise false. \r\n         */\r\n        static PropertyField(property: SerializedProperty, includeChildren: boolean, ...options: GUILayoutOption[]): boolean\r\n        /** Make a field for SerializedProperty.\r\n         * @param property The SerializedProperty to make a field for.\r\n         * @param label Optional label to use. If not specified the label of the property itself is used. Use GUIContent.none to not display a label at all.\r\n         * @param includeChildren If true the property including children is drawn; otherwise only the control itself (such as only a foldout but nothing below it).\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns True if the property has children and is expanded and includeChildren was set to false; otherwise false. \r\n         */\r\n        static PropertyField(property: SerializedProperty, ...options: GUILayoutOption[]): boolean\r\n        /** Get a rect for an Editor control.\r\n         * @param hasLabel Optional boolean to specify if the control has a label. Default is true.\r\n         * @param height The height in pixels of the control. Default is EditorGUIUtility.singleLineHeight.\r\n         * @param style Optional GUIStyle to use for the control.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static GetControlRect(hasLabel: boolean, height: number, style: GUIStyle, ...options: GUILayoutOption[]): Rect\r\n        /** Get a rect for an Editor control.\r\n         * @param hasLabel Optional boolean to specify if the control has a label. Default is true.\r\n         * @param height The height in pixels of the control. Default is EditorGUIUtility.singleLineHeight.\r\n         * @param style Optional GUIStyle to use for the control.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static GetControlRect(hasLabel: boolean, height: number, ...options: GUILayoutOption[]): Rect\r\n        /** Get a rect for an Editor control.\r\n         * @param hasLabel Optional boolean to specify if the control has a label. Default is true.\r\n         * @param height The height in pixels of the control. Default is EditorGUIUtility.singleLineHeight.\r\n         * @param style Optional GUIStyle to use for the control.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static GetControlRect(hasLabel: boolean, ...options: GUILayoutOption[]): Rect\r\n        /** Get a rect for an Editor control.\r\n         * @param hasLabel Optional boolean to specify if the control has a label. Default is true.\r\n         * @param height The height in pixels of the control. Default is EditorGUIUtility.singleLineHeight.\r\n         * @param style Optional GUIStyle to use for the control.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         */\r\n        static GetControlRect(...options: GUILayoutOption[]): Rect\r\n        /** Begins a group that can be be hidden/shown and the transition will be animated.\r\n         * @param value A value between 0 and 1, 0 being hidden, and 1 being fully visible.\r\n         * @returns If the group is visible or not. \r\n         */\r\n        static BeginFadeGroup(value: number): boolean\r\n        static EndFadeGroup(): void\r\n        static BeginBuildTargetSelectionGrouping(): BuildTargetGroup\r\n        static EndBuildTargetSelectionGrouping(): void\r\n        /** Make a button that reacts to mouse down, for displaying your own dropdown content.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param focusType Whether the button should be selectable by keyboard or not.\r\n         * @param style Optional style to use.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns true when the user clicks the button. \r\n         */\r\n        static DropdownButton(content: GUIContent, focusType: FocusType, style: GUIStyle, ...options: GUILayoutOption[]): boolean\r\n        /** Make a button that reacts to mouse down, for displaying your own dropdown content.\r\n         * @param content Text, image and tooltip for this button.\r\n         * @param focusType Whether the button should be selectable by keyboard or not.\r\n         * @param style Optional style to use.\r\n         * @param options An optional list of layout options that specify extra layouting properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns true when the user clicks the button. \r\n         */\r\n        static DropdownButton(content: GUIContent, focusType: FocusType, ...options: GUILayoutOption[]): boolean\r\n        static BeginFoldoutHeaderGroup(foldout: boolean, content: string, style: GUIStyle, menuAction: (obj: Rect) => void, menuIcon: GUIStyle): boolean\r\n        static BeginFoldoutHeaderGroup(foldout: boolean, content: GUIContent, style: GUIStyle, menuAction: (obj: Rect) => void, menuIcon: GUIStyle): boolean\r\n        static EndFoldoutHeaderGroup(): void\r\n        /** Make a field for editing a Gradient.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The gradient to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The gradient edited by the user. \r\n         */\r\n        static GradientField(label: GUIContent, value: Gradient, hdr: boolean, ...options: GUILayoutOption[]): Gradient\r\n        /** Make a field for editing a Gradient.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The gradient to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The gradient edited by the user. \r\n         */\r\n        static GradientField(label: string, value: Gradient, ...options: GUILayoutOption[]): Gradient\r\n        /** Make a field for editing a Gradient.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The gradient to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The gradient edited by the user. \r\n         */\r\n        static GradientField(label: GUIContent, value: Gradient, ...options: GUILayoutOption[]): Gradient\r\n        /** Make a field for editing a Gradient.\r\n         * @param label Optional label to display in front of the field.\r\n         * @param value The gradient to edit.\r\n         * @param options An optional list of layout options that specify extra layout properties. Any values passed in here will override settings defined by the style.<br>\nSee Also: GUILayout.Width, GUILayout.Height, GUILayout.MinWidth, GUILayout.MaxWidth, GUILayout.MinHeight,\nGUILayout.MaxHeight, GUILayout.ExpandWidth, GUILayout.ExpandHeight.\r\n         * @returns The gradient edited by the user. \r\n         */\r\n        static GradientField(value: Gradient, ...options: GUILayoutOption[]): Gradient\r\n        static Knob(knobSize: Vector2, value: number, minValue: number, maxValue: number, unit: string, backgroundColor: Color, activeColor: Color, showValue: boolean, ...options: GUILayoutOption[]): number\r\n        /** Makes a toolbar populated with the collection of editor tools that match the EditorToolAttribute of the target object.\r\n         * @param target The target object.\r\n         * @param content An optional prefix label.\r\n         */\r\n        static EditorToolbarForTarget(content: GUIContent, target: Object1): void\r\n        /** Makes a toolbar populated with the collection of editor tools that match the EditorToolAttribute of the target object.\r\n         * @param target The target object.\r\n         * @param content An optional prefix label.\r\n         */\r\n        static EditorToolbarForTarget(target: Object1): void\r\n        /** Makes a toolbar populated with the specified collection of editor tools.\r\n         * @param tools The collection of editor tools for the toolbar.\r\n         */\r\n        static EditorToolbar(...tools: EditorTool[]): void\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Rect } from \"UnityEngine\";\r\n    /** Main Application class.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class EditorApplication extends Object {\r\n        /** Open another project.\r\n         * @param projectPath The path of a project to open.\r\n         * @param args Arguments to pass to command line.\r\n         */\r\n        static OpenProject(projectPath: string, ...args: string[]): void\r\n        static EnterPlaymode(): void\r\n        static ExitPlaymode(): void\r\n        static Step(): void\r\n        static LockReloadAssemblies(): void\r\n        static UnlockReloadAssemblies(): void\r\n        /** Invokes the menu item in the specified path.\r\n         */\r\n        static ExecuteMenuItem(menuItemPath: string): boolean\r\n        /** Sets the path that Unity should store the current temporary project at, when the project is closed.\r\n         * @param path The path that the current temporary project should be relocated to when closing it.\r\n         */\r\n        static SetTemporaryProjectKeepPath(path: string): void\r\n        /** Exit the Unity editor application.\r\n         */\r\n        static Exit(returnValue: number): void\r\n        static QueuePlayerLoopUpdate(): void\r\n        static Beep(): void\r\n        static RepaintProjectWindow(): void\r\n        static RepaintAnimationWindow(): void\r\n        static RepaintHierarchyWindow(): void\r\n        static DirtyHierarchyWindowSorting(): void\r\n        protected constructor()\r\n        /** Is editor currently in play mode?\r\n         */\r\n        static isPlaying: boolean\r\n        /** Is editor either currently in play mode, or about to switch to it? (Read Only)\r\n         */\r\n        static readonly isPlayingOrWillChangePlaymode: boolean\r\n        /** Is editor currently paused?\r\n         */\r\n        static isPaused: boolean\r\n        /** Is editor currently compiling scripts? (Read Only)\r\n         */\r\n        static readonly isCompiling: boolean\r\n        /** True if the Editor is currently refreshing the AssetDatabase.\r\n         */\r\n        static readonly isUpdating: boolean\r\n        /** Is editor currently connected to Unity Remote 4 client app.\r\n         */\r\n        static readonly isRemoteConnected: boolean\r\n        /** Path to the Unity editor contents folder. (Read Only)\r\n         */\r\n        static readonly applicationContentsPath: string\r\n        /** Returns the path to the Unity editor application. (Read Only)\r\n         */\r\n        static readonly applicationPath: string\r\n        /** Returns true if the current project was created as a temporary project.\r\n         */\r\n        static readonly isTemporaryProject: boolean\r\n        /** The time since the editor was started. (Read Only)\r\n         */\r\n        static readonly timeSinceStartup: number\r\n        static wantsToQuit(op: \"add\" | \"remove\", fn: () => boolean): void\r\n        static quitting(op: \"add\" | \"remove\", fn: () => void): void\r\n        static hierarchyChanged(op: \"add\" | \"remove\", fn: () => void): void\r\n        static projectChanged(op: \"add\" | \"remove\", fn: () => void): void\r\n        static pauseStateChanged(op: \"add\" | \"remove\", fn: (obj: PauseState) => void): void\r\n        static playModeStateChanged(op: \"add\" | \"remove\", fn: (obj: PlayModeStateChange) => void): void\r\n        static projectWindowItemOnGUI(op: \"get\"): (guid: string, selectionRect: Rect) => void\r\n        static projectWindowItemOnGUI(op: \"add\" | \"remove\" | \"set\", fn?: (guid: string, selectionRect: Rect) => void): void\r\n        static projectWindowItemOnGUI(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (guid: string, selectionRect: Rect) => void): (guid: string, selectionRect: Rect) => void | void\r\n        static hierarchyWindowItemOnGUI(op: \"get\"): (instanceID: number, selectionRect: Rect) => void\r\n        static hierarchyWindowItemOnGUI(op: \"add\" | \"remove\" | \"set\", fn?: (instanceID: number, selectionRect: Rect) => void): void\r\n        static hierarchyWindowItemOnGUI(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (instanceID: number, selectionRect: Rect) => void): (instanceID: number, selectionRect: Rect) => void | void\r\n        static update(op: \"get\"): () => void\r\n        static update(op: \"add\" | \"remove\" | \"set\", fn?: () => void): void\r\n        static update(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => void): () => void | void\r\n        static delayCall(op: \"get\"): () => void\r\n        static delayCall(op: \"add\" | \"remove\" | \"set\", fn?: () => void): void\r\n        static delayCall(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => void): () => void | void\r\n        static searchChanged(op: \"get\"): () => void\r\n        static searchChanged(op: \"add\" | \"remove\" | \"set\", fn?: () => void): void\r\n        static searchChanged(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => void): () => void | void\r\n        static modifierKeysChanged(op: \"get\"): () => void\r\n        static modifierKeysChanged(op: \"add\" | \"remove\" | \"set\", fn?: () => void): void\r\n        static modifierKeysChanged(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => void): () => void | void\r\n        static contextualPropertyMenu(op: \"get\"): (menu: GenericMenu, property: SerializedProperty) => void\r\n        static contextualPropertyMenu(op: \"add\" | \"remove\" | \"set\", fn?: (menu: GenericMenu, property: SerializedProperty) => void): void\r\n        static contextualPropertyMenu(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (menu: GenericMenu, property: SerializedProperty) => void): (menu: GenericMenu, property: SerializedProperty) => void | void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ScriptableObject, Object, GUIContent, Texture2D, Rect, GUIStyle } from \"UnityEngine\";\r\n    import { Array, Object as Object1 } from \"System\";\r\n    /** Derive from this base class to create a custom inspector or editor for your custom object.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class Editor extends ScriptableObject {\r\n        constructor()\r\n        DrawDefaultInspector(): boolean\r\n        Repaint(): void\r\n        OnInspectorGUI(): void\r\n        CreateInspectorGUI(): any\r\n        RequiresConstantRepaint(): boolean\r\n        DrawHeader(): void\r\n        HasPreviewGUI(): boolean\r\n        GetPreviewTitle(): GUIContent\r\n        /** Override this method if you want to render a static preview.\r\n         * @param assetPath The asset to operate on.\r\n         * @param subAssets An array of all Assets at assetPath.\r\n         * @param width Width of the created texture.\r\n         * @param height Height of the created texture.\r\n         * @returns Generated texture or null. \r\n         */\r\n        RenderStaticPreview(assetPath: string, subAssets: Array<Object>, width: number, height: number): Texture2D\r\n        /** Implement to create your own custom preview for the preview area of the inspector, the headers of the primary editor, and the object selector.\r\n         * @param r Rectangle in which to draw the preview.\r\n         * @param background Background image.\r\n         */\r\n        OnPreviewGUI(r: Rect, background: GUIStyle): void\r\n        /** Implement to create your own interactive custom preview. Interactive custom previews are used in the preview area of the inspector and the object selector.\r\n         * @param r Rectangle in which to draw the preview.\r\n         * @param background Background image.\r\n         */\r\n        OnInteractivePreviewGUI(r: Rect, background: GUIStyle): void\r\n        OnPreviewSettings(): void\r\n        GetInfoString(): string\r\n        /** The first entry point for Preview Drawing.\r\n         * @param previewPosition The available area to draw the preview.\r\n         */\r\n        DrawPreview(previewArea: Rect): void\r\n        ReloadPreviewInstances(): void\r\n        UseDefaultMargins(): boolean\r\n        Initialize(targets: Array<Object>): void\r\n        MoveNextTarget(): boolean\r\n        ResetTarget(): void\r\n        /** Make a custom editor for targetObject or targetObjects with a context object.\r\n         */\r\n        static CreateEditorWithContext(targetObjects: Array<Object>, context: Object, editorType: any): Editor\r\n        static CreateEditorWithContext(targetObjects: Array<Object>, context: Object): Editor\r\n        /** Creates a cached editor using a context object.\r\n         */\r\n        static CreateCachedEditorWithContext(targetObject: Object, context: Object, editorType: any, previousEditor: jsb.Ref<Editor>): void\r\n        /** Creates a cached editor using a context object.\r\n         */\r\n        static CreateCachedEditorWithContext(targetObjects: Array<Object>, context: Object, editorType: any, previousEditor: jsb.Ref<Editor>): void\r\n        /** On return previousEditor is an editor for targetObject or targetObjects. The function either returns if the editor is already tracking the objects, or destroys the previous editor and creates a new one.\r\n         * @param obj The object the editor is tracking.\r\n         * @param editorType The requested editor type. Set to null for the default editor for the object.\r\n         * @param previousEditor The previous editor for the object. After returning from CreateCachedEditor previousEditor is an editor for the targetObject or targetObjects.\r\n         * @param objects The objects the editor is tracking.\r\n         */\r\n        static CreateCachedEditor(targetObject: Object, editorType: any, previousEditor: jsb.Ref<Editor>): void\r\n        /** On return previousEditor is an editor for targetObject or targetObjects. The function either returns if the editor is already tracking the objects, or destroys the previous editor and creates a new one.\r\n         * @param obj The object the editor is tracking.\r\n         * @param editorType The requested editor type. Set to null for the default editor for the object.\r\n         * @param previousEditor The previous editor for the object. After returning from CreateCachedEditor previousEditor is an editor for the targetObject or targetObjects.\r\n         * @param objects The objects the editor is tracking.\r\n         */\r\n        static CreateCachedEditor(targetObjects: Array<Object>, editorType: any, previousEditor: jsb.Ref<Editor>): void\r\n        /** Make a custom editor for targetObject or targetObjects.\r\n         * @param objects All objects must be of the same type.\r\n         */\r\n        static CreateEditor(targetObject: Object, editorType: any): Editor\r\n        /** Make a custom editor for targetObject or targetObjects.\r\n         * @param objects All objects must be of the same type.\r\n         */\r\n        static CreateEditor(targetObjects: Array<Object>, editorType: any): Editor\r\n        /** Make a custom editor for targetObject or targetObjects.\r\n         * @param objects All objects must be of the same type.\r\n         */\r\n        static CreateEditor(targetObject: Object): Editor\r\n        /** Make a custom editor for targetObject or targetObjects.\r\n         * @param objects All objects must be of the same type.\r\n         */\r\n        static CreateEditor(targetObjects: Array<Object>): Editor\r\n        /** Draws the inspector GUI with a foldout header for target.\r\n         * @param target The object to display the Inspector for.\r\n         * @param editor The reference to a variable of type Editor.\r\n         */\r\n        static DrawFoldoutInspector(target: Object, editor: jsb.Ref<Editor>): void\r\n        /** The object being inspected.\r\n         */\r\n        target: Object\r\n        /** An array of all the object being inspected.\r\n         */\r\n        readonly targets: Array<Object>\r\n        /** A SerializedObject representing the object or objects being inspected.\r\n         */\r\n        readonly serializedObject: SerializedObject\r\n        static finishedDefaultHeaderGUI(op: \"add\" | \"remove\", fn: (obj: Editor) => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ScriptableObject, Vector2, GUIContent, Rect, Event } from \"UnityEngine\";\r\n    import { Object } from \"System\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    /** Derive from this class to create an editor window.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class EditorWindow extends ScriptableObject {\r\n        constructor()\r\n        BeginWindows(): void\r\n        EndWindows(): void\r\n        /** Show a notification message.\r\n         * @param notification The contents of the notification message.\r\n         * @param fadeoutWait The duration the notification is displayed. Measured in seconds.\r\n         */\r\n        ShowNotification(notification: GUIContent, fadeoutWait: number): void\r\n        /** Show a notification message.\r\n         * @param notification The contents of the notification message.\r\n         * @param fadeoutWait The duration the notification is displayed. Measured in seconds.\r\n         */\r\n        ShowNotification(notification: GUIContent): void\r\n        RemoveNotification(): void\r\n        ShowTab(): void\r\n        Focus(): void\r\n        ShowUtility(): void\r\n        ShowPopup(): void\r\n        ShowModalUtility(): void\r\n        /** Shows a window with dropdown behaviour and styling.\r\n         * @param buttonRect The button from which the position of the window will be determined (see description).\r\n         * @param windowSize The initial size of the window.\r\n         */\r\n        ShowAsDropDown(buttonRect: Rect, windowSize: Vector2): void\r\n        /** Show the EditorWindow window.\r\n         * @param immediateDisplay Immediately display Show.\r\n         */\r\n        Show(immediateDisplay: boolean): void\r\n        Show(): void\r\n        ShowAuxWindow(): void\r\n        ShowModal(): void\r\n        SaveChanges(): void\r\n        Close(): void\r\n        Repaint(): void\r\n        /** Sends an Event to a window.\r\n         */\r\n        SendEvent(e: Event): boolean\r\n        GetExtraPaneTypes(): any\r\n        /** Returns the first EditorWindow of type t which is currently on the screen.\r\n         * @param t The type of the window. Must derive from EditorWindow.\r\n         * @param utility Set this to true, to create a floating utility window, false to create a normal window.\r\n         * @param title If GetWindow creates a new window, it will get this title. If this value is null, use the class name as title.\r\n         * @param focus Whether to give the window focus, if it already exists. (If GetWindow creates a new window, it will always get focus).\r\n         */\r\n        static GetWindow<T extends EditorWindow>(type: { new(): T }): T\r\n        /** Focuses the first found EditorWindow of specified type if it is open.\r\n         * @param t The type of the window. Must derive from EditorWindow.\r\n         */\r\n        static FocusWindowIfItsOpen(t: any): void\r\n        static CreateWindow<T extends EditorWindow>(type: { new(): T }, ...desiredDockNextTo: any[]): T\r\n        static CreateWindow<T extends EditorWindow>(type: { new(): T }, title: string, ...desiredDockNextTo: any[]): T\r\n        /** Retrieves the root visual element of this window hierarchy.\r\n         */\r\n        readonly rootVisualElement: any\r\n        /** Checks whether MouseMove events are received in the GUI in this Editor window.\r\n         */\r\n        wantsMouseMove: boolean\r\n        /** Checks whether MouseEnterWindow and MouseLeaveWindow events are received in the GUI in this Editor window.\r\n         */\r\n        wantsMouseEnterLeaveWindow: boolean\r\n        /** Specifies whether a layout pass is performed before all user events (for example, EventType.MouseDown or EventType, KeyDown), or is only performed before repaint events.\r\n         */\r\n        wantsLessLayoutEvents: boolean\r\n        /** Does the window automatically repaint whenever the Scene has changed?\r\n         */\r\n        autoRepaintOnSceneChange: boolean\r\n        /** Is this window maximized?\r\n         */\r\n        maximized: boolean\r\n        /** Returns true if EditorWindow is focused.\r\n         */\r\n        readonly hasFocus: boolean\r\n        /** Returns true if EditorWindow is docked.\r\n         */\r\n        readonly docked: boolean\r\n        /** The EditorWindow which currently has keyboard focus. (Read Only)\r\n         */\r\n        static readonly focusedWindow: EditorWindow\r\n        /** The EditorWindow currently under the mouse cursor. (Read Only)\r\n         */\r\n        static readonly mouseOverWindow: EditorWindow\r\n        /** When set to true in a derived class, the editor will prompt the user to save unsaved changes if the window is about to be closed.\r\n         */\r\n        readonly hasUnsavedChanges: boolean\r\n        /** The message that displays to the user if they are prompted to save\r\n         */\r\n        readonly saveChangesMessage: string\r\n        /** The minimum size of this window.\r\n         */\r\n        minSize: Vector2\r\n        /** The maximum size of this window.\r\n         */\r\n        maxSize: Vector2\r\n        /** The GUIContent used for drawing the title of EditorWindows.\r\n         */\r\n        titleContent: GUIContent\r\n        depthBufferBits: number\r\n        /** The desired position of the window in screen space.\r\n         */\r\n        position: Rect\r\n    }\r\n}\r\ndeclare module \"global\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    class HotfixTest2 extends Object {\r\n        constructor()\r\n        CallByRef(v: jsb.Out<number>): void\r\n        Foo(x: number): number\r\n    }\r\n}\r\ndeclare module \"global\" {\r\n    interface MyInterface {\r\n        Foo(): void\r\n    }\r\n}\r\ndeclare module \"global\" {\r\n    import { Object } from \"System\";\r\n    class MyClass extends Object implements MyInterface {\r\n        constructor()\r\n        Foo(): void\r\n        static GetMyInterface(): MyInterface\r\n    }\r\n}\r\ndeclare module \"global\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Vector3, Vector2 } from \"UnityEngine\";\r\n    import { Array, ValueType } from \"System\";\r\n    class NoNamespaceClass extends NoNamespaceBase {\r\n        constructor()\r\n        static V1(v: Vector3): void\r\n        static V1(v: Vector2): void\r\n        static Moo(): void\r\n        static MakeBytes(): Array<jsb.byte>\r\n        static TestBytes(test: Array<jsb.byte>): Array<jsb.byte>\r\n        static TestOut(x: jsb.Out<number>, y: number, z: jsb.Out<number>): void\r\n        static TestOut(x: jsb.Out<string>, y: number, z: jsb.Out<string>): void\r\n        static TestRefOut(g: jsb.Ref<number>, x: jsb.Out<number>, y: number, z: jsb.Out<number>): void\r\n        static TestNullable(x: jsb.Nullable<number>, y: jsb.Nullable<number>): jsb.Nullable<number>\r\n        static TestNullable(xy: jsb.Nullable<Vector2>, g: jsb.Ref<jsb.Nullable<number>>): jsb.Nullable<number>\r\n        static TestNullable(xy: jsb.Nullable<Vector2>): jsb.Nullable<number>\r\n    }\r\n}\r\ndeclare module \"global\" {\r\n    import { Object } from \"System\";\r\n    class NoNamespaceBase extends Object {\r\n        constructor()\r\n    }\r\n}\r\ndeclare module \"global\" {\r\n    import { MonoBehaviour } from \"UnityEngine\";\r\n    import { Object } from \"System\";\r\n    class SampleBehaviour extends MonoBehaviour {\r\n        constructor()\r\n        SimpleWait(t: number): Promise<string>\r\n        AnotherWait(t: number): Promise<any>\r\n        PrimitiveCall(a: string, b: number): void\r\n    }\r\n}\r\ndeclare module \"Example\" {\r\n    import { Object } from \"System\";\r\n    class AsyncTaskTest extends Object {\r\n        constructor()\r\n        static GetHostEntryAsync(host: string): any\r\n        static SimpleTest(ms: number): any\r\n    }\r\n}\r\ndeclare module \"Example\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Vector3 } from \"UnityEngine\";\r\n    class DelegateTest extends Object {\r\n        constructor()\r\n        TestComplexCall(): void\r\n        AddAction(): void\r\n        DipatchEvent(v: number): void\r\n        CallAction(): void\r\n        CallActionWithArgs(a1: string, a2: number, a3: number): void\r\n        CallFunc(a1: number): number\r\n        static DipatchStaticEvent(v: number): void\r\n        static GetNotExportedClass(): any\r\n        static CallStaticActionWithArgs(a1: string, a2: number, a3: number): void\r\n        static CallHotfixTest(): void\r\n        static GetArray(): Array<DelegateTest.InnerTest>\r\n        onEvent(op: \"add\" | \"remove\", fn: (id: number) => void): void\r\n        static onStaticEvent(op: \"add\" | \"remove\", fn: (id: number) => void): void\r\n        complexCall(op: \"get\"): (b: number, a: jsb.Ref<number>, v: jsb.Out<number>) => number\r\n        complexCall(op: \"add\" | \"remove\" | \"set\", fn?: (b: number, a: jsb.Ref<number>, v: jsb.Out<number>) => number): void\r\n        complexCall(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (b: number, a: jsb.Ref<number>, v: jsb.Out<number>) => number): (b: number, a: jsb.Ref<number>, v: jsb.Out<number>) => number | void\r\n        complexCall2(op: \"get\"): (v: jsb.Ref<Vector3>) => void\r\n        complexCall2(op: \"add\" | \"remove\" | \"set\", fn?: (v: jsb.Ref<Vector3>) => void): void\r\n        complexCall2(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (v: jsb.Ref<Vector3>) => void): (v: jsb.Ref<Vector3>) => void | void\r\n        actionFieldRW(op: \"get\"): () => void\r\n        actionFieldRW(op: \"add\" | \"remove\" | \"set\", fn?: () => void): void\r\n        actionFieldRW(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => void): () => void | void\r\n        actionFieldR(op: \"get\"): () => void\r\n        static actionFieldRW_s(op: \"get\"): () => void\r\n        static actionFieldRW_s(op: \"add\" | \"remove\" | \"set\", fn?: () => void): void\r\n        static actionFieldRW_s(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => void): () => void | void\r\n        static actionFieldR_s(op: \"get\"): () => void\r\n        onAction(op: \"get\"): () => void\r\n        onAction(op: \"add\" | \"remove\" | \"set\", fn?: () => void): void\r\n        onAction(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => void): () => void | void\r\n        onActionWithArgs(op: \"get\"): (arg1: string, arg2: number, arg3: number) => void\r\n        onActionWithArgs(op: \"add\" | \"remove\" | \"set\", fn?: (arg1: string, arg2: number, arg3: number) => void): void\r\n        onActionWithArgs(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (arg1: string, arg2: number, arg3: number) => void): (arg1: string, arg2: number, arg3: number) => void | void\r\n        static onStaticActionWithArgs(op: \"get\"): (arg1: string, arg2: number, arg3: number) => void\r\n        static onStaticActionWithArgs(op: \"add\" | \"remove\" | \"set\", fn?: (arg1: string, arg2: number, arg3: number) => void): void\r\n        static onStaticActionWithArgs(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (arg1: string, arg2: number, arg3: number) => void): (arg1: string, arg2: number, arg3: number) => void | void\r\n        onFunc(op: \"get\"): (arg: number) => number\r\n        onFunc(op: \"add\" | \"remove\" | \"set\", fn?: (arg: number) => number): void\r\n        onFunc(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (arg: number) => number): (arg: number) => number | void\r\n        actionPropG(op: \"get\"): () => void\r\n        actionPropS(op: \"set\", fn: () => void)\r\n        actionPropGS(op: \"get\"): () => void\r\n        actionPropGS(op: \"add\" | \"remove\" | \"set\", fn?: () => void): void\r\n        actionPropGS(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => void): () => void | void\r\n        static actionPropG_s(op: \"get\"): () => void\r\n        static actionPropS_s(op: \"set\", fn: () => void)\r\n        static actionPropGS_s(op: \"get\"): () => void\r\n        static actionPropGS_s(op: \"add\" | \"remove\" | \"set\", fn?: () => void): void\r\n        static actionPropGS_s(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => void): () => void | void\r\n    }\r\n}\r\ndeclare module \"Example\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    abstract class NativeFileUtil extends Object {\r\n        static ReadAllText(path: string): string\r\n        static ReadAllBytes(path: string): Array<jsb.byte>\r\n    }\r\n}\r\ndeclare module \"Example\" {\r\n    import { Object } from \"System\";\r\n    class Jankfest extends Object {\r\n        constructor()\r\n        static DoNothing(jankfest: Jankfest): Jankfest\r\n    }\r\n}\r\ndeclare module \"Example\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { GameObject } from \"UnityEngine\";\r\n    class ValueTest extends Object {\r\n        constructor()\r\n        toString(): string\r\n        static TakeStringWithCache(v: string): void\r\n        static TakeString(v: string): void\r\n        static Foo(v: string): string\r\n        static CheckArgs(a: number, b: jsb.Out<number>, c: jsb.Ref<string>): boolean\r\n        static CheckArgs(a: number, b: jsb.Out<number>, c: jsb.Ref<GameObject>): boolean\r\n        static MakeTrouble(): void\r\n        static values1: Array<number>\r\n        static values2: Array<number, 2>\r\n    }\r\n}\r\ndeclare module \"Example.New.World\" {\r\n    import { Object } from \"System\";\r\n    class Galaxy extends Object {\r\n        constructor()\r\n        static GetName(): string\r\n    }\r\n}\r\ndeclare module \"Example\" {\r\n    import { Object } from \"System\";\r\n    namespace DelegateTest {\r\n        class InnerTest extends Object {\r\n            constructor()\r\n            static readonly hello: string\r\n        }\r\n    }\r\n}\r\ndeclare module \"Example.New.World\" {\r\n    import { Object } from \"System\";\r\n    namespace Galaxy {\r\n        class Sun extends Object {\r\n            constructor()\r\n            static GetName(): string\r\n        }\r\n    }\r\n}\r\ndeclare module \"Example.New.World\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    namespace Galaxy {\r\n        class Earth extends Object {\r\n            constructor()\r\n            GetSun(): Galaxy.Sun\r\n            GetContinents(): Array<Galaxy.Earth.Continent>\r\n            static GetName(): string\r\n        }\r\n    }\r\n}\r\ndeclare module \"Example.New.World\" {\r\n    import { Object } from \"System\";\r\n    namespace Galaxy.Earth {\r\n        class Ocean extends Object {\r\n            constructor()\r\n            static GetName(): string\r\n        }\r\n    }\r\n}\r\ndeclare module \"Example.New.World\" {\r\n    import { Object } from \"System\";\r\n    namespace Galaxy.Earth {\r\n        class Continent extends Object {\r\n            constructor()\r\n            static GetName(): string\r\n        }\r\n    }\r\n}\r\ndeclare module \"System\" {\r\n    import * as jsb from \"jsb\";\r\n    class Byte extends ValueType {\r\n        CompareTo(value: Object): number\r\n        CompareTo(value: jsb.byte): number\r\n        Equals(obj: Object): boolean\r\n        Equals(obj: jsb.byte): boolean\r\n        GetHashCode(): number\r\n        toString(format: string, provider: any): string\r\n        toString(format: string): string\r\n        toString(provider: any): string\r\n        toString(): string\r\n        GetTypeCode(): any\r\n        static Parse(s: string, style: any, provider: any): jsb.byte\r\n        static Parse(s: string, style: any): jsb.byte\r\n        static Parse(s: string, provider: any): jsb.byte\r\n        static Parse(s: string): jsb.byte\r\n        static TryParse(s: string, style: any, provider: any, result: jsb.Out<jsb.byte>): boolean\r\n        static TryParse(s: string, result: jsb.Out<jsb.byte>): boolean\r\n        protected constructor()\r\n        static readonly MaxValue: jsb.byte\r\n        static readonly MinValue: jsb.byte\r\n    }\r\n}\r\ndeclare module \"System\" {\r\n    import * as jsb from \"jsb\";\r\n    class SByte extends ValueType {\r\n        CompareTo(obj: Object): number\r\n        CompareTo(value: number): number\r\n        Equals(obj: Object): boolean\r\n        Equals(obj: number): boolean\r\n        GetHashCode(): number\r\n        toString(format: string, provider: any): string\r\n        toString(provider: any): string\r\n        toString(format: string): string\r\n        toString(): string\r\n        GetTypeCode(): any\r\n        static Parse(s: string, style: any, provider: any): number\r\n        static Parse(s: string, style: any): number\r\n        static Parse(s: string, provider: any): number\r\n        static Parse(s: string): number\r\n        static TryParse(s: string, style: any, provider: any, result: jsb.Out<number>): boolean\r\n        static TryParse(s: string, result: jsb.Out<number>): boolean\r\n        protected constructor()\r\n        static readonly MaxValue: number\r\n        static readonly MinValue: number\r\n    }\r\n}\r\ndeclare module \"System\" {\r\n    import * as jsb from \"jsb\";\r\n    class Single extends ValueType {\r\n        CompareTo(value: Object): number\r\n        CompareTo(value: number): number\r\n        Equals(obj: Object): boolean\r\n        Equals(obj: number): boolean\r\n        GetHashCode(): number\r\n        toString(format: string, provider: any): string\r\n        toString(provider: any): string\r\n        toString(format: string): string\r\n        toString(): string\r\n        GetTypeCode(): any\r\n        static IsInfinity(f: number): boolean\r\n        static IsPositiveInfinity(f: number): boolean\r\n        static IsNegativeInfinity(f: number): boolean\r\n        static IsNaN(f: number): boolean\r\n        static op_Equality(left: number, right: number): boolean\r\n        static op_Inequality(left: number, right: number): boolean\r\n        static op_LessThan(left: number, right: number): boolean\r\n        static op_GreaterThan(left: number, right: number): boolean\r\n        static op_LessThanOrEqual(left: number, right: number): boolean\r\n        static op_GreaterThanOrEqual(left: number, right: number): boolean\r\n        static Parse(s: string, style: any, provider: any): number\r\n        static Parse(s: string, style: any): number\r\n        static Parse(s: string, provider: any): number\r\n        static Parse(s: string): number\r\n        static TryParse(s: string, style: any, provider: any, result: jsb.Out<number>): boolean\r\n        static TryParse(s: string, result: jsb.Out<number>): boolean\r\n        // js_op_overloading: static ==(left: number, right: number): boolean\r\n        // js_op_overloading: static <(left: number, right: number): boolean\r\n        protected constructor()\r\n        static readonly MinValue: number\r\n        static readonly Epsilon: number\r\n        static readonly MaxValue: number\r\n        static readonly PositiveInfinity: number\r\n        static readonly NegativeInfinity: number\r\n        static readonly NaN: number\r\n    }\r\n}\r\ndeclare module \"System\" {\r\n    import * as jsb from \"jsb\";\r\n    class Double extends ValueType {\r\n        CompareTo(value: Object): number\r\n        CompareTo(value: number): number\r\n        Equals(obj: Object): boolean\r\n        Equals(obj: number): boolean\r\n        GetHashCode(): number\r\n        toString(format: string, provider: any): string\r\n        toString(format: string): string\r\n        toString(provider: any): string\r\n        toString(): string\r\n        GetTypeCode(): any\r\n        static IsInfinity(d: number): boolean\r\n        static IsPositiveInfinity(d: number): boolean\r\n        static IsNegativeInfinity(d: number): boolean\r\n        static IsNaN(d: number): boolean\r\n        static op_Equality(left: number, right: number): boolean\r\n        static op_Inequality(left: number, right: number): boolean\r\n        static op_LessThan(left: number, right: number): boolean\r\n        static op_GreaterThan(left: number, right: number): boolean\r\n        static op_LessThanOrEqual(left: number, right: number): boolean\r\n        static op_GreaterThanOrEqual(left: number, right: number): boolean\r\n        static Parse(s: string, style: any, provider: any): number\r\n        static Parse(s: string, style: any): number\r\n        static Parse(s: string, provider: any): number\r\n        static Parse(s: string): number\r\n        static TryParse(s: string, style: any, provider: any, result: jsb.Out<number>): boolean\r\n        static TryParse(s: string, result: jsb.Out<number>): boolean\r\n        // js_op_overloading: static ==(left: number, right: number): boolean\r\n        // js_op_overloading: static <(left: number, right: number): boolean\r\n        protected constructor()\r\n        static readonly MinValue: number\r\n        static readonly MaxValue: number\r\n        static readonly Epsilon: number\r\n        static readonly NegativeInfinity: number\r\n        static readonly PositiveInfinity: number\r\n        static readonly NaN: number\r\n    }\r\n}\r\ndeclare module \"System\" {\r\n    import * as jsb from \"jsb\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    class String extends Object {\r\n        constructor(value: Array<string>, startIndex: number, length: number)\r\n        constructor(c: string, count: number)\r\n        constructor(value: Array<string>)\r\n        Equals(value: string, comparisonType: any): boolean\r\n        Equals(obj: Object): boolean\r\n        Equals(value: string): boolean\r\n        CopyTo(sourceIndex: number, destination: Array<string>, destinationIndex: number, count: number): void\r\n        ToCharArray(startIndex: number, length: number): Array<string>\r\n        ToCharArray(): Array<string>\r\n        GetHashCode(): number\r\n        Split(separator: Array<string>, count: number, options: any): Array<string>\r\n        Split(separator: Array<string>, count: number, options: any): Array<string>\r\n        Split(separator: Array<string>, count: number): Array<string>\r\n        Split(separator: Array<string>, options: any): Array<string>\r\n        Split(separator: Array<string>, options: any): Array<string>\r\n        Split(...separator: string[]): Array<string>\r\n        Substring(startIndex: number, length: number): string\r\n        Substring(startIndex: number): string\r\n        Trim(): string\r\n        Trim(...trimChars: string[]): string\r\n        TrimStart(...trimChars: string[]): string\r\n        TrimEnd(...trimChars: string[]): string\r\n        IsNormalized(normalizationForm: any): boolean\r\n        IsNormalized(): boolean\r\n        Normalize(normalizationForm: any): string\r\n        Normalize(): string\r\n        CompareTo(value: Object): number\r\n        CompareTo(strB: string): number\r\n        Contains(value: string): boolean\r\n        EndsWith(value: string, ignoreCase: boolean, culture: any): boolean\r\n        EndsWith(value: string, comparisonType: any): boolean\r\n        EndsWith(value: string): boolean\r\n        IndexOf(value: string, startIndex: number, count: number, comparisonType: any): number\r\n        IndexOf(value: string, startIndex: number, count: number): number\r\n        IndexOf(value: string, startIndex: number, comparisonType: any): number\r\n        IndexOf(value: string, startIndex: number, count: number): number\r\n        IndexOf(value: string, startIndex: number): number\r\n        IndexOf(value: string, startIndex: number): number\r\n        IndexOf(value: string, comparisonType: any): number\r\n        IndexOf(value: string): number\r\n        IndexOf(value: string): number\r\n        IndexOfAny(anyOf: Array<string>, startIndex: number, count: number): number\r\n        IndexOfAny(anyOf: Array<string>, startIndex: number): number\r\n        IndexOfAny(anyOf: Array<string>): number\r\n        LastIndexOf(value: string, startIndex: number, count: number, comparisonType: any): number\r\n        LastIndexOf(value: string, startIndex: number, count: number): number\r\n        LastIndexOf(value: string, startIndex: number, comparisonType: any): number\r\n        LastIndexOf(value: string, startIndex: number, count: number): number\r\n        LastIndexOf(value: string, startIndex: number): number\r\n        LastIndexOf(value: string, startIndex: number): number\r\n        LastIndexOf(value: string, comparisonType: any): number\r\n        LastIndexOf(value: string): number\r\n        LastIndexOf(value: string): number\r\n        LastIndexOfAny(anyOf: Array<string>, startIndex: number, count: number): number\r\n        LastIndexOfAny(anyOf: Array<string>, startIndex: number): number\r\n        LastIndexOfAny(anyOf: Array<string>): number\r\n        PadLeft(totalWidth: number, paddingChar: string): string\r\n        PadLeft(totalWidth: number): string\r\n        PadRight(totalWidth: number, paddingChar: string): string\r\n        PadRight(totalWidth: number): string\r\n        StartsWith(value: string, ignoreCase: boolean, culture: any): boolean\r\n        StartsWith(value: string, comparisonType: any): boolean\r\n        StartsWith(value: string): boolean\r\n        ToLower(culture: any): string\r\n        ToLower(): string\r\n        ToLowerInvariant(): string\r\n        ToUpper(culture: any): string\r\n        ToUpper(): string\r\n        ToUpperInvariant(): string\r\n        toString(provider: any): string\r\n        toString(): string\r\n        Clone(): Object\r\n        Insert(startIndex: number, value: string): string\r\n        Replace(oldChar: string, newChar: string): string\r\n        Replace(oldValue: string, newValue: string): string\r\n        Remove(startIndex: number, count: number): string\r\n        Remove(startIndex: number): string\r\n        GetTypeCode(): any\r\n        GetEnumerator(): any\r\n        ArrayListFromJson(): any\r\n        HashtableFromJson(): any\r\n        ToIntArray(): Array<number>\r\n        static Join(separator: string, value: Array<string>, startIndex: number, count: number): string\r\n        static Join(separator: string, values: IEnumerable<string>): string\r\n        static Join(separator: string, ...value: string[]): string\r\n        static Join(separator: string, ...values: Object[]): string\r\n        static Equals(a: string | Object, b: string | Object, comparisonType: any): boolean\r\n        static Equals(a: string | Object, b: string | Object): boolean\r\n        static op_Equality(a: string, b: string): boolean\r\n        static op_Inequality(a: string, b: string): boolean\r\n        static IsNullOrEmpty(value: string): boolean\r\n        static IsNullOrWhiteSpace(value: string): boolean\r\n        static Compare(strA: string, indexA: number, strB: string, indexB: number, length: number, ignoreCase: boolean, culture: any): number\r\n        static Compare(strA: string, indexA: number, strB: string, indexB: number, length: number, culture: any, options: any): number\r\n        static Compare(strA: string, indexA: number, strB: string, indexB: number, length: number, ignoreCase: boolean): number\r\n        static Compare(strA: string, indexA: number, strB: string, indexB: number, length: number, comparisonType: any): number\r\n        static Compare(strA: string, indexA: number, strB: string, indexB: number, length: number): number\r\n        static Compare(strA: string, strB: string, culture: any, options: any): number\r\n        static Compare(strA: string, strB: string, ignoreCase: boolean, culture: any): number\r\n        static Compare(strA: string, strB: string, ignoreCase: boolean): number\r\n        static Compare(strA: string, strB: string, comparisonType: any): number\r\n        static Compare(strA: string, strB: string): number\r\n        static CompareOrdinal(strA: string, indexA: number, strB: string, indexB: number, length: number): number\r\n        static CompareOrdinal(strA: string, strB: string): number\r\n        static Format(provider: any, format: string, arg0: Object, arg1: Object, arg2: Object): string\r\n        static Format(format: string, arg0: Object, arg1: Object, arg2: Object): string\r\n        static Format(provider: any, format: string, arg0: Object, arg1: Object): string\r\n        static Format(format: string, arg0: Object, arg1: Object): string\r\n        static Format(provider: any, format: string, arg0: Object): string\r\n        static Format(format: string, arg0: Object): string\r\n        static Format(provider: any, format: string, ...args: Object[]): string\r\n        static Format(format: string, ...args: Object[]): string\r\n        static Copy(str: string): string\r\n        static Concat(arg0: Object, arg1: Object, arg2: Object, arg3: Object): string\r\n        static Concat(str0: string, str1: string, str2: string, str3: string): string\r\n        static Concat(arg0: Object, arg1: Object, arg2: Object): string\r\n        static Concat(str0: string, str1: string, str2: string): string\r\n        static Concat(arg0: Object, arg1: Object): string\r\n        static Concat(str0: string, str1: string): string\r\n        static Concat(arg0: Object): string\r\n        static Concat(values: IEnumerable<string>): string\r\n        static Concat(...args: Object[]): string\r\n        static Concat(...values: string[]): string\r\n        static Intern(str: string): string\r\n        static IsInterned(str: string): string\r\n        // js_op_overloading: static ==(a: string, b: string): boolean\r\n        readonly Length: number\r\n        static readonly Empty: string\r\n    }\r\n}\r\ndeclare module \"System\" {\r\n    import * as jsb from \"jsb\";\r\n    class Int32 extends ValueType {\r\n        CompareTo(value: Object): number\r\n        CompareTo(value: number): number\r\n        Equals(obj: Object): boolean\r\n        Equals(obj: number): boolean\r\n        GetHashCode(): number\r\n        toString(format: string, provider: any): string\r\n        toString(format: string): string\r\n        toString(provider: any): string\r\n        toString(): string\r\n        GetTypeCode(): any\r\n        static Parse(s: string, style: any, provider: any): number\r\n        static Parse(s: string, style: any): number\r\n        static Parse(s: string, provider: any): number\r\n        static Parse(s: string): number\r\n        static TryParse(s: string, style: any, provider: any, result: jsb.Out<number>): boolean\r\n        static TryParse(s: string, result: jsb.Out<number>): boolean\r\n        protected constructor()\r\n        static readonly MaxValue: number\r\n        static readonly MinValue: number\r\n    }\r\n}\r\ndeclare module \"System\" {\r\n    import * as jsb from \"jsb\";\r\n    class UInt32 extends ValueType {\r\n        CompareTo(value: Object): number\r\n        CompareTo(value: number): number\r\n        Equals(obj: Object): boolean\r\n        Equals(obj: number): boolean\r\n        GetHashCode(): number\r\n        toString(format: string, provider: any): string\r\n        toString(provider: any): string\r\n        toString(format: string): string\r\n        toString(): string\r\n        GetTypeCode(): any\r\n        static Parse(s: string, style: any, provider: any): number\r\n        static Parse(s: string, style: any): number\r\n        static Parse(s: string, provider: any): number\r\n        static Parse(s: string): number\r\n        static TryParse(s: string, style: any, provider: any, result: jsb.Out<number>): boolean\r\n        static TryParse(s: string, result: jsb.Out<number>): boolean\r\n        protected constructor()\r\n        static readonly MaxValue: number\r\n        static readonly MinValue: number\r\n    }\r\n}\r\ndeclare module \"System\" {\r\n    import * as jsb from \"jsb\";\r\n    class Int16 extends ValueType {\r\n        CompareTo(value: Object): number\r\n        CompareTo(value: number): number\r\n        Equals(obj: Object): boolean\r\n        Equals(obj: number): boolean\r\n        GetHashCode(): number\r\n        toString(format: string, provider: any): string\r\n        toString(provider: any): string\r\n        toString(format: string): string\r\n        toString(): string\r\n        GetTypeCode(): any\r\n        static Parse(s: string, style: any, provider: any): number\r\n        static Parse(s: string, style: any): number\r\n        static Parse(s: string, provider: any): number\r\n        static Parse(s: string): number\r\n        static TryParse(s: string, style: any, provider: any, result: jsb.Out<number>): boolean\r\n        static TryParse(s: string, result: jsb.Out<number>): boolean\r\n        protected constructor()\r\n        static readonly MaxValue: number\r\n        static readonly MinValue: number\r\n    }\r\n}\r\ndeclare module \"System\" {\r\n    import * as jsb from \"jsb\";\r\n    class UInt16 extends ValueType {\r\n        CompareTo(value: Object): number\r\n        CompareTo(value: number): number\r\n        Equals(obj: Object): boolean\r\n        Equals(obj: number): boolean\r\n        GetHashCode(): number\r\n        toString(format: string, provider: any): string\r\n        toString(provider: any): string\r\n        toString(format: string): string\r\n        toString(): string\r\n        GetTypeCode(): any\r\n        static Parse(s: string, style: any, provider: any): number\r\n        static Parse(s: string, style: any): number\r\n        static Parse(s: string, provider: any): number\r\n        static Parse(s: string): number\r\n        static TryParse(s: string, style: any, provider: any, result: jsb.Out<number>): boolean\r\n        static TryParse(s: string, result: jsb.Out<number>): boolean\r\n        protected constructor()\r\n        static readonly MaxValue: number\r\n        static readonly MinValue: number\r\n    }\r\n}\r\ndeclare module \"System\" {\r\n    import * as jsb from \"jsb\";\r\n    import { IEnumerator } from \"System.Collections\";\r\n    abstract class Array<T, RANK = 1> extends Object {\r\n        CopyTo(array: Array<any>, index: number): void\r\n        Clone(): Object\r\n        GetLongLength(dimension: number): number\r\n        GetEnumerator(): IEnumerator\r\n        GetLength(dimension: number): number\r\n        GetLowerBound(dimension: number): number\r\n        GetValue(index1: number, index2: number, index3: number): T\r\n        GetValue(index1: number, index2: number): T\r\n        GetValue(index: number): T\r\n        GetValue(...index: number[]): T\r\n        SetValue(value: T, index1: number, index2: number, index3: number): T\r\n        SetValue(value: T, index1: number, index2: number): T\r\n        SetValue(value: T, index: number): T\r\n        SetValue(value: T, ...index: number[]): T\r\n        GetUpperBound(dimension: number): number\r\n        Initialize(): void\r\n        static BinarySearch<T>(array: Array<T>, index: number, length: number, value: Object, comparer: any): number\r\n        static BinarySearch<T>(array: Array<T>, index: number, length: number, value: Object): number\r\n        static BinarySearch<T>(array: Array<T>, value: Object, comparer: any): number\r\n        static BinarySearch<T>(array: Array<T>, value: Object): number\r\n        static IndexOf<T>(array: Array<T>, value: Object, startIndex: number, count: number): number\r\n        static IndexOf<T>(array: Array<T>, value: Object, startIndex: number): number\r\n        static IndexOf<T>(array: Array<T>, value: Object): number\r\n        static LastIndexOf<T>(array: Array<T>, value: Object, startIndex: number, count: number): number\r\n        static LastIndexOf<T>(array: Array<T>, value: Object, startIndex: number): number\r\n        static LastIndexOf<T>(array: Array<T>, value: Object): number\r\n        static Reverse<T>(array: Array<T>, index: number, length: number): void\r\n        static Reverse<T>(array: Array<T>): void\r\n        static Sort<T>(keys: Array<T>, items: Array<T>, index: number, length: number, comparer: any): void\r\n        static Sort<T>(array: Array<T>, index: number, length: number, comparer: any): void\r\n        static Sort<T>(keys: Array<T>, items: Array<T>, index: number, length: number): void\r\n        static Sort<T>(array: Array<T>, index: number, length: number): void\r\n        static Sort<T>(keys: Array<T>, items: Array<T>, comparer: any): void\r\n        static Sort<T>(array: Array<T>, comparer: any): void\r\n        static Sort<T>(keys: Array<T>, items: Array<T>): void\r\n        static Sort<T>(array: Array<T>): void\r\n        static CreateInstance<T>(elementType: any, length1: number, length2: number, length3: number): Array<T>\r\n        static CreateInstance<T>(elementType: any, length1: number, length2: number): Array<T>\r\n        static CreateInstance<T>(elementType: any, lengths: Array<number>, lowerBounds: Array<number>): Array<T>\r\n        static CreateInstance<T>(elementType: any, length: number): Array<T>\r\n        static CreateInstance<T>(elementType: any, ...lengths: number[]): Array<T>\r\n        static Clear<T>(array: Array<T>, index: number, length: number): void\r\n        static Copy<T>(sourceArray: Array<T>, sourceIndex: number, destinationArray: Array<T>, destinationIndex: number, length: number): void\r\n        static Copy<T>(sourceArray: Array<T>, destinationArray: Array<T>, length: number): void\r\n        static ConstrainedCopy<T>(sourceArray: Array<T>, sourceIndex: number, destinationArray: Array<T>, destinationIndex: number, length: number): void\r\n        readonly LongLength: number\r\n        readonly IsFixedSize: boolean\r\n        readonly IsReadOnly: boolean\r\n        readonly IsSynchronized: boolean\r\n        readonly SyncRoot: Object\r\n        readonly Length: number\r\n        readonly Rank: number\r\n    }\r\n}\r\ndeclare module \"System\" {\r\n    import * as jsb from \"jsb\";\r\n    abstract class Delegate extends Object {\r\n        DynamicInvoke(...args: Object[]): Object\r\n        Clone(): Object\r\n        Equals(obj: Object): boolean\r\n        GetHashCode(): number\r\n        GetObjectData(info: any, context: any): void\r\n        GetInvocationList(): Array<Delegate>\r\n        GetMethodInfo(): any\r\n        static Combine(a: Delegate, b: Delegate): Delegate\r\n        static Combine(...delegates: Delegate[]): Delegate\r\n        static Remove(source: Delegate, value: Delegate): Delegate\r\n        static RemoveAll(source: Delegate, value: Delegate): Delegate\r\n        static op_Equality(d1: Delegate, d2: Delegate): boolean\r\n        static op_Inequality(d1: Delegate, d2: Delegate): boolean\r\n        // js_op_overloading: static ==(d1: Delegate, d2: Delegate): boolean\r\n        readonly Method: any\r\n        readonly Target: Object\r\n    }\r\n}\r\ndeclare module \"QuickJS.IO\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    class ByteBuffer extends Object {\r\n        constructor(initialCapacity: number, maxCapacity: number, allocator: any)\r\n        constructor(data: Array<jsb.byte>, maxCapacity: number)\r\n        constructor(data: Array<jsb.byte>)\r\n        toString(): string\r\n        Release(): void\r\n        Retain(): ByteBuffer\r\n        Slice(size: number): ByteBuffer\r\n        CheckReadalbe(size: number): void\r\n        ReadBytes(dst: Array<jsb.byte>, dstOffset: number, size: number): number\r\n        ReadBytes(pointer: any, size: number): number\r\n        ReadBytes(count: number): void\r\n        ReadUByte(): jsb.byte\r\n        ReadSByte(): number\r\n        ReadBoolean(): boolean\r\n        ReadAllBytes(): Array<jsb.byte>\r\n        ReadSingle(): number\r\n        ReadDouble(): number\r\n        ReadString(): string\r\n        ReadInt16(): number\r\n        ReadUInt16(): number\r\n        ReadInt32(): number\r\n        ReadUInt32(): number\r\n        ReadInt64(): number\r\n        ReadUInt64(): number\r\n        EnsureCapacity(value: number): void\r\n        WriteByte(data: jsb.byte): void\r\n        WriteSByte(data: number): void\r\n        WriteBytes(src: Array<jsb.byte>, srcOffset: number, count: number): void\r\n        WriteBytes(memoryStream: any, size: number): void\r\n        WriteBytes(other: ByteBuffer): void\r\n        WriteBytes(byteCount: number): void\r\n        WriteBytes(data: Array<jsb.byte>): void\r\n        WriteBoolean(value: boolean): void\r\n        WriteInt16(value: number): void\r\n        WriteUInt16(value: number): void\r\n        WriteInt32(value: number): void\r\n        WriteUInt32(value: number): void\r\n        WriteInt64(value: number): void\r\n        WriteUInt64(value: number): void\r\n        WriteSingle(value: number): void\r\n        WriteDouble(value: number): void\r\n        WriteString(value: string): void\r\n        readonly data: Array<jsb.byte>\r\n        readonly capacity: number\r\n        writerIndex: number\r\n        readonly readableBytes: number\r\n        readerIndex: number\r\n        readonly maxCapacity: number\r\n        readonly isWritable: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Object as Object1 } from \"UnityEngine\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ActiveEditorTracker extends Object {\r\n        constructor()\r\n        Equals(o: Object): boolean\r\n        GetHashCode(): number\r\n        Destroy(): void\r\n        GetVisible(index: number): number\r\n        SetVisible(index: number, visible: number): void\r\n        ClearDirty(): void\r\n        RebuildIfNecessary(): void\r\n        ForceRebuild(): void\r\n        VerifyModifiedMonoBehaviours(): void\r\n        static HasCustomEditor(obj: Object1): boolean\r\n        readonly activeEditors: Array<Editor>\r\n        readonly isDirty: boolean\r\n        isLocked: boolean\r\n        inspectorMode: InspectorMode\r\n        readonly hasComponentsWhichCannotBeMultiEdited: boolean\r\n        static readonly sharedTracker: ActiveEditorTracker\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Helpers for builtin arrays.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class ArrayUtility extends Object {\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** This class has event dispatchers for assembly reload events.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class AssemblyReloadEvents extends Object {\r\n        static beforeAssemblyReload(op: \"add\" | \"remove\", fn: () => void): void\r\n        static afterAssemblyReload(op: \"add\" | \"remove\", fn: () => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Result of Asset delete operation\r\n     */\r\n    enum AssetDeleteResult {\r\n        /** Tells the internal implementation that the callback did not delete the asset. The asset will be delete by the internal implementation.\r\n         */\r\n        DidNotDelete = 0,\r\n        /** Tells Unity that the file cannot be deleted and Unity should leave it alone.\r\n         */\r\n        FailedDelete = 1,\r\n        /** Tells Unity that the asset was deleted by the callback. Unity will not try to delete the asset, but will delete the cached version and preview file.\r\n         */\r\n        DidDelete = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** AssetModificationProcessor lets you hook into saving of serialized assets and\n      scenes which are edited inside Unity.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AssetModificationProcessor extends Object {\r\n        constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Result of Asset move\r\n     */\r\n    enum AssetMoveResult {\r\n        /** Tells the internal implementation that the asset was not moved physically on disk by the script.\r\n         */\r\n        DidNotMove = 0,\r\n        /** Tells the internal implementation that the script could not move the assets.\r\n         */\r\n        FailedMove = 1,\r\n        /** Tells the internal implementation that the script moved the asset physically on disk.\r\n         */\r\n        DidMove = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Whether you can append an existing build using BuildOptions.AcceptExternalModificationsToPlayer.\r\n     */\r\n    enum CanAppendBuild {\r\n        /** The target platform does not support appending builds.\r\n         */\r\n        Unsupported = 0,\r\n        /** The target platform supports appending builds, and the build can be appended.\r\n         */\r\n        Yes = 1,\r\n        /** The target platform supports appending builds, and the build is not in a valid state.\r\n         */\r\n        No = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array } from \"System\";\r\n    /** AssetBundle building map entry.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AssetBundleBuild extends ValueType {\r\n        constructor()\r\n        /** AssetBundle name.\r\n         */\r\n        assetBundleName: string\r\n        /** AssetBundle variant.\r\n         */\r\n        assetBundleVariant: string\r\n        /** Asset names which belong to the given AssetBundle.\r\n         */\r\n        assetNames: Array<string>\r\n        /** Addressable name used to load an asset.\r\n         */\r\n        addressableNames: Array<string>\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Describes how the player connects to the Editor.\r\n     */\r\n    enum PlayerConnectionInitiateMode {\r\n        /** Player connection mode not set.\r\n         */\r\n        None = 0,\r\n        /** Player connection is initiated by the player connecting to the host, usually the host is the Editor.\r\n         */\r\n        PlayerConnectsToHost = 1,\r\n        /** Player connection is initiated by the player broadcasting its IP address, and then Editor connecting to the player.\r\n         */\r\n        PlayerListens = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    /** The default build settings window.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class BuildPlayerWindow extends EditorWindow {\r\n        constructor()\r\n        static ShowBuildPlayerWindow(): void\r\n        static GetPlaybackEngineDownloadURL(moduleName: string): string\r\n        static RegisterGetBuildPlayerOptionsHandler(func: (arg: BuildPlayerOptions) => BuildPlayerOptions): void\r\n        static RegisterBuildPlayerHandler(func: (obj: BuildPlayerOptions) => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Exception } from \"System\";\r\n    namespace BuildPlayerWindow {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class BuildMethodException extends Exception {\r\n            constructor(message: string)\r\n            constructor()\r\n        }\r\n    }\r\n}\r\ndeclare module \"System\" {\r\n    class Exception extends Object {\r\n        constructor(message: string, innerException: Exception)\r\n        constructor(message: string)\r\n        constructor()\r\n        GetBaseException(): Exception\r\n        toString(): string\r\n        GetObjectData(info: any, context: any): void\r\n        GetType(): any\r\n        readonly Message: string\r\n        readonly Data: any\r\n        readonly InnerException: Exception\r\n        readonly TargetSite: any\r\n        readonly StackTrace: string\r\n        HelpLink: string\r\n        Source: string\r\n        readonly HResult: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    namespace BuildPlayerWindow {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        abstract class DefaultBuildMethods extends Object {\r\n            static BuildPlayer(options: BuildPlayerOptions): void\r\n            static GetBuildPlayerOptions(defaultBuildPlayerOptions: BuildPlayerOptions): BuildPlayerOptions\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Build target group.\r\n     */\r\n    enum BuildTargetGroup {\r\n        /** Unknown target.\r\n         */\r\n        Unknown = 0,\r\n        /** PC, Mac & Linux standalone target.\r\n         */\r\n        Standalone = 1,\r\n        /** Mac/PC webplayer target.\r\n         */\r\n        WebPlayer = 2,\r\n        /** OBSOLETE: Use iOS. Apple iOS target.\r\n         */\r\n        iPhone = 4,\r\n        /** OBSOLETE: Use iOS. Apple iOS target.\r\n         */\r\n        iOS = 4,\r\n        PS3 = 5,\r\n        XBOX360 = 6,\r\n        /** Android target.\r\n         */\r\n        Android = 7,\r\n        /** WebGL.\r\n         */\r\n        WebGL = 13,\r\n        /** Windows Store Apps target.\r\n         */\r\n        WSA = 14,\r\n        /** Windows Store Apps target.\r\n         */\r\n        Metro = 14,\r\n        WP8 = 15,\r\n        BlackBerry = 16,\r\n        Tizen = 17,\r\n        PSP2 = 18,\r\n        /** Sony Playstation 4 target.\r\n         */\r\n        PS4 = 19,\r\n        PSM = 20,\r\n        /** Microsoft Xbox One target.\r\n         */\r\n        XboxOne = 21,\r\n        SamsungTV = 22,\r\n        /** Nintendo 3DS target.\r\n         */\r\n        N3DS = 23,\r\n        WiiU = 24,\r\n        /** Apple's tvOS target.\r\n         */\r\n        tvOS = 25,\r\n        Facebook = 26,\r\n        /** Nintendo Switch target.\r\n         */\r\n        Switch = 27,\r\n        Lumin = 28,\r\n        /** Google Stadia target.\r\n         */\r\n        Stadia = 29,\r\n        /** CloudRendering target.\r\n         */\r\n        CloudRendering = 30,\r\n        GameCoreScarlett = 31,\r\n        GameCoreXboxSeries = 31,\r\n        GameCoreXboxOne = 32,\r\n        /** Sony Playstation 5 target.\r\n         */\r\n        PS5 = 33,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    /** DefaultAsset is used for assets that do not have a specific type (yet).\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class DefaultAsset extends Object {\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Visual indication mode for Drag & Drop operation.\r\n     */\r\n    enum DragAndDropVisualMode {\r\n        /** No indication (drag should not be performed).\r\n         */\r\n        None = 0,\r\n        /** Copy dragged objects.\r\n         */\r\n        Copy = 1,\r\n        /** Link dragged objects to target.\r\n         */\r\n        Link = 2,\r\n        /** Generic drag operation.\r\n         */\r\n        Generic = 4,\r\n        /** Move dragged objects.\r\n         */\r\n        Move = 16,\r\n        /** Rejected drag operation.\r\n         */\r\n        Rejected = 32,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Object as Object1 } from \"UnityEngine\";\r\n    /** Editor drag & drop operations.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class DragAndDrop extends Object {\r\n        constructor()\r\n        static PrepareStartDrag(): void\r\n        /** Start a drag operation.\r\n         */\r\n        static StartDrag(title: string): void\r\n        /** Get data associated with current drag and drop operation.\r\n         */\r\n        static GetGenericData(type: string): Object\r\n        /** Set data associated with current drag and drop operation.\r\n         */\r\n        static SetGenericData(type: string, data: Object): void\r\n        static AcceptDrag(): void\r\n        /** References to Object|objects being dragged.\r\n         */\r\n        static objectReferences: Array<Object1>\r\n        /** The file names being dragged.\r\n         */\r\n        static paths: Array<string>\r\n        /** Get or set ID of currently active drag and drop control.\r\n         */\r\n        static activeControlID: number\r\n        /** The visual indication of the drag.\r\n         */\r\n        static visualMode: DragAndDropVisualMode\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Determines how a gizmo is drawn or picked in the Unity editor.\r\n     */\r\n    enum GizmoType {\r\n        /** The gizmo can be picked in the editor.\r\n         */\r\n        Pickable = 1,\r\n        /** Draw the gizmo if it is not selected and also no parent/ancestor is selected.\r\n         */\r\n        NotInSelectionHierarchy = 2,\r\n        /** Draw the gizmo if it is selected.\r\n         */\r\n        Selected = 4,\r\n        /** Draw the gizmo if it is active (shown in the inspector).\r\n         */\r\n        Active = 8,\r\n        /** Draw the gizmo if it is selected or it is a child/descendent of the selected.\r\n         */\r\n        InSelectionHierarchy = 16,\r\n        /** Draw the gizmo if it is not selected.\r\n         */\r\n        NonSelected = 32,\r\n        NotSelected = -127,\r\n        SelectedOrChild = -127,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    /** This class is used for entries in the Scenes list, as displayed in the window. This class contains the Scene path of a Scene and an enabled flag that indicates wether the Scene is enabled in the BuildSettings window or not.\n\nYou can use this class in combination with EditorBuildSettings.scenes to populate the list of Scenes included in the build via script. This is useful when creating custom editor scripts to automate your build pipeline.\n\nSee EditorBuildSettings.scenes for an example script.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class EditorBuildSettingsScene extends Object {\r\n        constructor(path: string, enabled: boolean)\r\n        constructor(guid: GUID, enabled: boolean)\r\n        constructor()\r\n        CompareTo(obj: Object): number\r\n        static GetActiveSceneList(scenes: Array<EditorBuildSettingsScene>): Array<string>\r\n        /** Whether this Scene is enabled in the for an example of how to use this class.\n\nSee Also: EditorBuildSettingsScene, EditorBuildSettings.scenes.\r\n         */\r\n        enabled: boolean\r\n        /** The file path of the Scene as listed in the Editor for an example of how to use this class.\n\nSee Also: EditorBuildSettingsScene, EditorBuildSettings.scenes.\r\n         */\r\n        path: string\r\n        guid: GUID\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    import { Array } from \"System\";\r\n    /** This class allows you to modify the Editor for an example of how to use this class.\n\nSee Also: EditorBuildSettingsScene, EditorBuildSettings.scenes.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class EditorBuildSettings extends Object {\r\n        /** Remove a config object reference by name.\r\n         * @param name The name in string format of the config object reference to be removed. This is the name given to the object when the reference is first created. Note: This may be different than the object name as an object can be added multiple times with different names.\r\n         * @returns Returns true if the reference was found and removed, otherwise false. \r\n         */\r\n        static RemoveConfigObject(name: string): boolean\r\n        static GetConfigObjectNames(): Array<string>\r\n        /** Store a reference to a config object by name.  The object must be an asset in the project, otherwise it will not be saved when the editor is restarted or scripts are reloaded.  To avoid name conflicts with other packages, it is recommended that names are qualified by a namespace, i.e. \"company.package.name\".\r\n         * @param name The name of the object reference in string format. This string name must be unique within your project or the overwrite parameter must be set to true.\r\n         * @param obj Object reference to be stored.  This object must be persisted and not null.\r\n         * @param overwrite Boolean parameter used to specify that you want to overwrite an entry with the same name if one already exists.\r\n         * @returns Throws an exception if the object is null, not persisted, or if there is a name conflict and the overwrite parameter is set to false. \r\n         */\r\n        static AddConfigObject(name: string, obj: Object, overwrite: boolean): void\r\n        protected constructor()\r\n        /** The list of Scenes that should be included in the build.\nThis is the same list of Scenes that is shown in the window. You can modify this list to set up which Scenes should be included in the build.\r\n         */\r\n        static scenes: Array<EditorBuildSettingsScene>\r\n        static sceneListChanged(op: \"add\" | \"remove\", fn: () => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { GUI } from \"UnityEngine\";\r\n    namespace EditorGUI {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class DisabledGroupScope extends GUI.Scope {\r\n            constructor(disabled: boolean)\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import { Object as Object1 } from \"System\";\r\n    namespace GUI {\r\n        abstract class Scope extends Object1 {\r\n            Dispose(): void\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    namespace EditorGUI {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class DisabledScope extends ValueType {\r\n            constructor(disabled: boolean)\r\n            Dispose(): void\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { GUI } from \"UnityEngine\";\r\n    namespace EditorGUI {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class ChangeCheckScope extends GUI.Scope {\r\n            constructor()\r\n            readonly changed: boolean\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { GUI } from \"UnityEngine\";\r\n    namespace EditorGUI {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class IndentLevelScope extends GUI.Scope {\r\n            constructor(increment: number)\r\n            constructor()\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { GUI, GUIContent, Rect } from \"UnityEngine\";\r\n    namespace EditorGUI {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class PropertyScope extends GUI.Scope {\r\n            constructor(totalPosition: Rect, label: GUIContent, property: SerializedProperty)\r\n            readonly content: GUIContent\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { GUI, GUIContent } from \"UnityEngine\";\r\n    namespace EditorGUILayout {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class ToggleGroupScope extends GUI.Scope {\r\n            constructor(label: string, toggle: boolean)\r\n            constructor(label: GUIContent, toggle: boolean)\r\n            readonly enabled: boolean\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { GUI, Rect, GUIStyle, GUILayoutOption } from \"UnityEngine\";\r\n    import { Array } from \"System\";\r\n    namespace EditorGUILayout {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class HorizontalScope extends GUI.Scope {\r\n            constructor(style: GUIStyle, ...options: GUILayoutOption[])\r\n            constructor(...options: GUILayoutOption[])\r\n            readonly rect: Rect\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { GUI, Rect, GUIStyle, GUILayoutOption } from \"UnityEngine\";\r\n    import { Array } from \"System\";\r\n    namespace EditorGUILayout {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class VerticalScope extends GUI.Scope {\r\n            constructor(style: GUIStyle, ...options: GUILayoutOption[])\r\n            constructor(...options: GUILayoutOption[])\r\n            readonly rect: Rect\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { GUI, Vector2, GUIStyle, GUILayoutOption } from \"UnityEngine\";\r\n    import { Array } from \"System\";\r\n    namespace EditorGUILayout {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class ScrollViewScope extends GUI.Scope {\r\n            constructor(scrollPosition: Vector2, alwaysShowHorizontal: boolean, alwaysShowVertical: boolean, horizontalScrollbar: GUIStyle, verticalScrollbar: GUIStyle, background: GUIStyle, ...options: GUILayoutOption[])\r\n            constructor(scrollPosition: Vector2, alwaysShowHorizontal: boolean, alwaysShowVertical: boolean, ...options: GUILayoutOption[])\r\n            constructor(scrollPosition: Vector2, horizontalScrollbar: GUIStyle, verticalScrollbar: GUIStyle, ...options: GUILayoutOption[])\r\n            constructor(scrollPosition: Vector2, style: GUIStyle, ...options: GUILayoutOption[])\r\n            constructor(scrollPosition: Vector2, ...options: GUILayoutOption[])\r\n            readonly scrollPosition: Vector2\r\n            handleScrollWheel: boolean\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { GUI } from \"UnityEngine\";\r\n    namespace EditorGUILayout {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class FadeGroupScope extends GUI.Scope {\r\n            constructor(value: number)\r\n            readonly visible: boolean\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Enum that selects which skin to return from EditorGUIUtility.GetBuiltinSkin.\r\n     */\r\n    enum EditorSkin {\r\n        /** The skin used for game views.\r\n         */\r\n        Game = 0,\r\n        /** The skin used for inspectors.\r\n         */\r\n        Inspector = 1,\r\n        /** The skin used for Scene views.\r\n         */\r\n        Scene = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { GUI, Vector2 } from \"UnityEngine\";\r\n    namespace EditorGUIUtility {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class IconSizeScope extends GUI.Scope {\r\n            constructor(iconSizeWithinScope: Vector2)\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Vector3 } from \"UnityEngine\";\r\n    /** SessionState is a Key-Value Store intended for storing and retrieving Editor session state that should survive assembly reloading.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SessionState extends Object {\r\n        constructor()\r\n        /** Store a Boolean value.\r\n         */\r\n        static SetBool(key: string, value: boolean): void\r\n        /** Retrieve a Boolean value.\r\n         */\r\n        static GetBool(key: string, defaultValue: boolean): boolean\r\n        /** Erase a Boolean entry in the key-value store.\r\n         */\r\n        static EraseBool(key: string): void\r\n        /** Store a Float value.\r\n         */\r\n        static SetFloat(key: string, value: number): void\r\n        /** Retrieve a Float value.\r\n         */\r\n        static GetFloat(key: string, defaultValue: number): number\r\n        /** Erase a Float entry in the key-value store.\r\n         */\r\n        static EraseFloat(key: string): void\r\n        /** Store an Integer value.\r\n         */\r\n        static SetInt(key: string, value: number): void\r\n        /** Retrieve an Integer value.\r\n         */\r\n        static GetInt(key: string, defaultValue: number): number\r\n        /** Erase an Integer entry in the key-value store.\r\n         */\r\n        static EraseInt(key: string): void\r\n        /** Store a String value.\r\n         */\r\n        static SetString(key: string, value: string): void\r\n        /** Retrieve a String value.\r\n         */\r\n        static GetString(key: string, defaultValue: string): string\r\n        /** Erase a String entry in the key-value store.\r\n         */\r\n        static EraseString(key: string): void\r\n        /** Store a Vector3.\r\n         */\r\n        static SetVector3(key: string, value: Vector3): void\r\n        /** Retrieve a Vector3.\r\n         */\r\n        static GetVector3(key: string, defaultValue: Vector3): Vector3\r\n        /** Erase a Vector3 entry in the key-value store.\r\n         */\r\n        static EraseVector3(key: string): void\r\n        /** Erase an Integer array entry in the key-value store.\r\n         */\r\n        static EraseIntArray(key: string): void\r\n        /** Store an Integer array.\r\n         */\r\n        static SetIntArray(key: string, value: Array<number>): void\r\n        /** Retrieve an Integer array.\r\n         */\r\n        static GetIntArray(key: string, defaultValue: Array<number>): Array<number>\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum SerializationMode {\r\n        Mixed = 0,\r\n        ForceBinary = 1,\r\n        ForceText = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum EditorBehaviorMode {\r\n        Mode3D = 0,\r\n        Mode2D = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Sprite Packer mode for the current project.\r\n     */\r\n    enum SpritePackerMode {\r\n        /** Doesn't pack sprites.\r\n         */\r\n        Disabled = 0,\r\n        /** Updates the sprite atlas cache when the Player or bundles builds containing Sprite with the legacy packing tag.\r\n         */\r\n        BuildTimeOnly = 1,\r\n        /** Always maintain an up-to-date sprite atlas cache for Sprite with packing tag (legacy).\r\n         */\r\n        AlwaysOn = 2,\r\n        /** Pack all the SpriteAtlas when building player/bundles.\r\n         */\r\n        BuildTimeOnlyAtlas = 3,\r\n        /** Always pack all the SpriteAtlas.\r\n         */\r\n        AlwaysOnAtlas = 4,\r\n        /** If enabled, will automatically migrate all *.spriteatlas assets to *.spriteatlasv2 assets. Old *.spriteatlas assets will be removed.\r\n         */\r\n        SpriteAtlasV2 = 5,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum LineEndingsMode {\r\n        OSNative = 0,\r\n        Unix = 1,\r\n        Windows = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Selects the Assetpipeline mode to use.\r\n     */\r\n    enum AssetPipelineMode {\r\n        /** Use this if you want to use assetpipeline version 1.\r\n         */\r\n        Version1 = 0,\r\n        /** Use this if you want to use assetpipeline version 2.\r\n         */\r\n        Version2 = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Selects the cache server configuration mode.\r\n     */\r\n    enum CacheServerMode {\r\n        /** Use this if you want to use the global cache server settings.\r\n         */\r\n        AsPreferences = 0,\r\n        /** Use this if you want to enable use of the project specific cache server settings.\r\n         */\r\n        Enabled = 1,\r\n        /** Use this if you want to disable the use of cache server for the project.\r\n         */\r\n        Disabled = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Determines the flags for the Enter Play Mode Options in the Unity Editor.\r\n     */\r\n    enum EnterPlayModeOptions {\r\n        /** This makes Unity reload the .NET Application Domain and entire Scene when entering Play Mode.\r\n         */\r\n        None = 0,\r\n        /** When Domain Reload is disabled, scripts are not reloaded when entering Play Mode. This makes it quicker to switch to Play Mode, because there's no need to destroy, create and reload the .NET Application Domain.\r\n         */\r\n        DisableDomainReload = 1,\r\n        /** When Scene Reload is disabled, Unity resets the Scene state and emulates all of the required post-processor calls when entering Play Mode, instead of reloading the whole Scene. This makes it quicker to switch to Play Mode, because there's no need to destroy, create and awaken all the Scene objects, and serialize and deserialize the Scene from disk.\r\n         */\r\n        DisableSceneReload = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    import { Array } from \"System\";\r\n    /** User settings for Unity Editor.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class EditorSettings extends Object {\r\n        protected constructor()\r\n        /** Gets or sets device ID used for Unity Remote feature.\r\n         */\r\n        static unityRemoteDevice: string\r\n        /** Gets or sets compression method used for Unity Remote screen stream.\r\n         */\r\n        static unityRemoteCompression: string\r\n        /** Gets or sets resolution used for Unity Remote screen stream.\r\n         */\r\n        static unityRemoteResolution: string\r\n        /** Gets or sets joystick source used in editor when Unity Remote is connected.\r\n         */\r\n        static unityRemoteJoystickSource: string\r\n        static serializationMode: SerializationMode\r\n        static lineEndingsForNewScripts: LineEndingsMode\r\n        static defaultBehaviorMode: EditorBehaviorMode\r\n        /** Allows you to specify a Scene to use as the for Prefabs.\r\n         */\r\n        static prefabRegularEnvironment: SceneAsset\r\n        /** Allows you to specify a Scene to use as the for UI Prefabs.\r\n         */\r\n        static prefabUIEnvironment: SceneAsset\r\n        /** Allow Auto Save in Prefab Mode for this project.\r\n         */\r\n        static prefabModeAllowAutoSave: boolean\r\n        static spritePackerMode: SpritePackerMode\r\n        /** Power of 2 value to add a boundary (padding) to Sprites packed to the Atlas (Legacy Sprite Packer).\r\n         */\r\n        static spritePackerPaddingPower: number\r\n        static etcTextureCompressorBehavior: number\r\n        static etcTextureFastCompressor: number\r\n        static etcTextureNormalCompressor: number\r\n        static etcTextureBestCompressor: number\r\n        /** Enable texture mipmap streaming system when in Edit Mode.\r\n         */\r\n        static enableTextureStreamingInEditMode: boolean\r\n        /** Enable texture mipmap streaming system when in Play Mode.\r\n         */\r\n        static enableTextureStreamingInPlayMode: boolean\r\n        /** Enable asynchronous Shader compilation in Game and Scene view.\r\n         */\r\n        static asyncShaderCompilation: boolean\r\n        /** Enables the Caching Shader Preprocessor.\r\n         */\r\n        static cachingShaderPreprocessor: boolean\r\n        /** Controls list of extensions of files that will be included in the c# .csproj projects that Unity generates.\r\n         */\r\n        static projectGenerationUserExtensions: Array<string>\r\n        /** Built-in list of extensions of files that will be included in the c# projects Unity generates.\r\n         */\r\n        static readonly projectGenerationBuiltinExtensions: Array<string>\r\n        /** Controls which root namespace gets written into the c# .csproj projects that Unity generates.\r\n         */\r\n        static projectGenerationRootNamespace: string\r\n        /** Enable the legacy fixed sample counts for baking Light Probes with Progressive Lightmapper.\r\n         */\r\n        static useLegacyProbeSampleCount: boolean\r\n        static useCloudEnlightenBake: boolean\r\n        /** Determines whether cookies should be evaluated by the Progressive Lightmapper during Global Illumination calculations.\r\n         */\r\n        static enableCookiesInLightmapper: boolean\r\n        /** Determines whether the Enter Play Mode Options are enabled in the Unity Editor or not.\r\n         */\r\n        static enterPlayModeOptionsEnabled: boolean\r\n        /** Determines the state of the Enter Play Mode Options in the Unity Editor.\r\n         */\r\n        static enterPlayModeOptions: EnterPlayModeOptions\r\n        /** Forces Unity to write references and other inline mappings on one line, to help reduce version control noise.\r\n         */\r\n        static serializeInlineMappingsOnOneLine: boolean\r\n        /** Select the assetpipeline mode.\r\n         */\r\n        static readonly assetPipelineMode: AssetPipelineMode\r\n        /** Select cache server mode\r\n         */\r\n        static cacheServerMode: CacheServerMode\r\n        /** Cache server endpoint IP address\r\n         */\r\n        static cacheServerEndpoint: string\r\n        /** Sets the namespace prefix to use for the cache server.\r\n         */\r\n        static cacheServerNamespacePrefix: string\r\n        /** Toggle whether to enable downloading from cache server.\r\n         */\r\n        static cacheServerEnableDownload: boolean\r\n        /** Toggle whether to enable uploading from cache server.\r\n         */\r\n        static cacheServerEnableUpload: boolean\r\n        /** Toggle whether to enable authentication to cache server.\r\n         */\r\n        static cacheServerEnableAuth: boolean\r\n        /** Toggle whether to enable TLS encryption to cache server.\r\n         */\r\n        static cacheServerEnableTls: boolean\r\n        /** Indicates the amount of digits to use for the numbers in a duplicated GameoObject's name.\r\n         */\r\n        static gameObjectNamingDigits: number\r\n        /** Indicates which naming scheme to use for duplicated GameObjects.\r\n         */\r\n        static gameObjectNamingScheme: EditorSettings.NamingScheme\r\n        /** Controls whether to insert a space before a number in duplicated Asset names.\r\n         */\r\n        static assetNamingUsesSpace: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace EditorSettings {\r\n        enum NamingScheme {\r\n            SpaceParenthesis = 0,\r\n            Dot = 1,\r\n            Underscore = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Type of build to generate.\r\n     */\r\n    enum PS4BuildSubtarget {\r\n        /** Build hosted on a PC, for file serving to a dev or test kit.\r\n         */\r\n        PCHosted = 0,\r\n        /** Package build for installation on either a dev or test kit.\r\n         */\r\n        Package = 1,\r\n        Iso = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum PS4HardwareTarget {\r\n        BaseOnly = 0,\r\n        NeoAndBase = 1,\r\n        ProAndBase = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Target Xbox build type.\r\n     */\r\n    enum XboxBuildSubtarget {\r\n        /** Development player.\r\n         */\r\n        Development = 0,\r\n        /** Master player (submission-proof).\r\n         */\r\n        Master = 1,\r\n        /** Debug player (for building with source code).\r\n         */\r\n        Debug = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum XboxOneDeployMethod {\r\n        Push = 0,\r\n        RunFromPC = 2,\r\n        Package = 3,\r\n        PackageStreaming = 4,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum XboxOneDeployDrive {\r\n        Default = 0,\r\n        Retail = 1,\r\n        Development = 2,\r\n        Ext1 = 3,\r\n        Ext2 = 4,\r\n        Ext3 = 5,\r\n        Ext4 = 6,\r\n        Ext5 = 7,\r\n        Ext6 = 8,\r\n        Ext7 = 9,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Compressed texture format for target build platform.\r\n     */\r\n    enum MobileTextureSubtarget {\r\n        /** Don't override texture compression.\r\n         */\r\n        Generic = 0,\r\n        /** S3 texture compression. Supported on devices with NVidia Tegra, Vivante and Intel GPUs.\r\n         */\r\n        DXT = 1,\r\n        /** PowerVR texture compression. Available on devices with PowerVR GPU.\r\n         */\r\n        PVRTC = 2,\r\n        ATC = 3,\r\n        /** ETC1 texture compression (or ETC2 for textures with alpha). ETC1 is supported by all devices. ETC2 is available on devices which support OpenGL ES 3.0; on OpenGL ES 2 devices the texture is decompressed on CPU.\r\n         */\r\n        ETC = 4,\r\n        /** ETC2 texture compression. Available on devices which support OpenGL ES 3.0; on OpenGL ES 2 devices the texture is decompressed on CPU.\r\n         */\r\n        ETC2 = 5,\r\n        /** ASTC texture compression.\r\n         */\r\n        ASTC = 6,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Build configurations for the generated Xcode project.\r\n     */\r\n    enum iOSBuildType {\r\n        /** Build configuration set to Debug for the generated Xcode project.\r\n         */\r\n        Debug = 0,\r\n        /** Build configuration set to Release for the generated Xcode project with optimization enabled.\r\n         */\r\n        Release = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    import { Enum, Array } from \"System\";\r\n    /** User build settings for the Editor\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class EditorUserBuildSettings extends Object {\r\n        /** Select a new build target to be active.\r\n         * @param target Target build platform.\r\n         * @param targetGroup Build target group.\r\n         * @returns True if the build target was successfully switched, false otherwise (for example, if license checks fail, files are missing, or if the user has cancelled the operation via the UI). \r\n         */\r\n        static SwitchActiveBuildTarget(targetGroup: BuildTargetGroup, target: BuildTarget): boolean\r\n        /** Select a new build target to be active during the next Editor update.\r\n         * @param targetGroup Target build platform.\r\n         * @param target Build target group.\r\n         * @returns True if the build target was successfully switched, false otherwise (for example, if license checks fail, files are missing, or if the user has cancelled the operation via the UI). \r\n         */\r\n        static SwitchActiveBuildTargetAsync(targetGroup: BuildTargetGroup, target: BuildTarget): boolean\r\n        /** Get the current location for the build.\r\n         */\r\n        static GetBuildLocation(target: BuildTarget): string\r\n        /** Set a new location for the build.\r\n         */\r\n        static SetBuildLocation(target: BuildTarget, location: string): void\r\n        static SetPlatformSettings(buildTargetGroup: string, buildTarget: string, name: string, value: string): void\r\n        /** Set platform specifc Editor setting.\r\n         * @param platformName The name of the platform.\r\n         * @param name The name of the setting.\r\n         * @param value Setting value.\r\n         */\r\n        static SetPlatformSettings(platformName: string, name: string, value: string): void\r\n        static GetPlatformSettings(buildTargetGroup: string, platformName: string, name: string): string\r\n        /** Returns value for platform specifc Editor setting.\r\n         * @param platformName The name of the platform.\r\n         * @param name The name of the setting.\r\n         */\r\n        static GetPlatformSettings(platformName: string, name: string): string\r\n        protected constructor()\r\n        /** The currently selected build target group.\r\n         */\r\n        static selectedBuildTargetGroup: BuildTargetGroup\r\n        /** The currently selected target for a standalone build.\r\n         */\r\n        static selectedStandaloneTarget: BuildTarget\r\n        /** PS4 Build Subtarget.\r\n         */\r\n        static ps4BuildSubtarget: PS4BuildSubtarget\r\n        /** Specifies which version of PS4 hardware to target.\r\n         */\r\n        static ps4HardwareTarget: PS4HardwareTarget\r\n        /** Are null references actively validated?\r\n         */\r\n        static explicitNullChecks: boolean\r\n        /** Are divide by zero's actively validated?\r\n         */\r\n        static explicitDivideByZeroChecks: boolean\r\n        /** Are array bounds actively validated?\r\n         */\r\n        static explicitArrayBoundsChecks: boolean\r\n        /** Build submission materials.\r\n         */\r\n        static needSubmissionMaterials: boolean\r\n        /** Build data compressed with PSArc.\r\n         */\r\n        static compressWithPsArc: boolean\r\n        /** Force installation of package, even if error.\r\n         */\r\n        static forceInstallation: boolean\r\n        /** Places the package on the outer edge of the disk.\r\n         */\r\n        static movePackageToDiscOuterEdge: boolean\r\n        /** Compress files in package.\r\n         */\r\n        static compressFilesInPackage: boolean\r\n        /** Whether the standalone player is built in headless mode.\r\n         */\r\n        static enableHeadlessMode: boolean\r\n        /** Is build script only enabled.\r\n         */\r\n        static buildScriptsOnly: boolean\r\n        /** Xbox Build subtarget.\r\n         */\r\n        static xboxBuildSubtarget: XboxBuildSubtarget\r\n        /** When building an Xbox One Streaming Install package (makepkg.exe) The layout generation code in Unity will assign each Scene and associated assets to individual chunks. Unity will mark Scene 0 as being part of the launch range, IE the set of chunks required to launch the game, you may include additional Scenes in this launch range if you desire, this specifies a range of Scenes (starting at 0) to be included in the launch set. \r\n         */\r\n        static streamingInstallLaunchRange: number\r\n        /** The currently selected Xbox One Deploy Method.\r\n         */\r\n        static xboxOneDeployMethod: XboxOneDeployMethod\r\n        /** The currently selected Xbox One Deploy Drive.\r\n         */\r\n        static xboxOneDeployDrive: XboxOneDeployDrive\r\n        static xboxOneAdditionalDebugPorts: string\r\n        /** Sets the XBox to reboot and redeploy when the deployment fails.\r\n         */\r\n        static xboxOneRebootIfDeployFailsAndRetry: boolean\r\n        /** Android platform options.\r\n         */\r\n        static androidBuildSubtarget: MobileTextureSubtarget\r\n        /** ETC2 texture decompression fallback on Android devices that don't support ETC2.\r\n         */\r\n        static androidETC2Fallback: any\r\n        static androidBuildSystem: any\r\n        static androidBuildType: any\r\n        /** Set to true to create a symbols.zip file in the same location as the .apk or .aab file.\r\n         */\r\n        static androidCreateSymbolsZip: boolean\r\n        /** Sets and gets target device type for the application to run on when building to Windows Store platform.\r\n         */\r\n        static wsaSubtarget: any\r\n        /** The build type for the Universal Windows Platform.\r\n         */\r\n        static wsaUWPBuildType: any\r\n        /** Sets and gets target UWP SDK to build Windows Store application against.\r\n         */\r\n        static wsaUWPSDK: string\r\n        static wsaMinUWPSDK: string\r\n        static wsaArchitecture: string\r\n        /** Sets and gets Visual Studio version to build Windows Store application with.\r\n         */\r\n        static wsaUWPVisualStudioVersion: string\r\n        /** Specifies the Windows DevicePortal connection address of the device to deploy and launch the UWP app on when using Build and Run.\r\n         */\r\n        static windowsDevicePortalAddress: string\r\n        /** Specifies the Windows DevicePortal username for the device to deploy and launch the UWP app on when using Build and Run.\r\n         */\r\n        static windowsDevicePortalUsername: string\r\n        /** Specifies the Windows DevicePortal password for the device to deploy and launch the UWP app on when using Build and Run.\r\n         */\r\n        static windowsDevicePortalPassword: string\r\n        /** Sets and gets the Windows device to launch the UWP app when using Build and Run.\r\n         */\r\n        static wsaBuildAndRunDeployTarget: any\r\n        /** The currently active build target.\r\n         */\r\n        static readonly activeBuildTarget: BuildTarget\r\n        /** DEFINE directives for the compiler.\r\n         */\r\n        static readonly activeScriptCompilationDefines: Array<string>\r\n        /** Enables a development build.\r\n         */\r\n        static development: boolean\r\n        /** Start the player with a connection to the profiler.\r\n         */\r\n        static connectProfiler: boolean\r\n        /** Enables Deep Profiling support in the player.\r\n         */\r\n        static buildWithDeepProfilingSupport: boolean\r\n        /** Enable source-level debuggers to connect.\r\n         */\r\n        static allowDebugging: boolean\r\n        /** Sets the Player to wait for player connection on player start.\r\n         */\r\n        static waitForPlayerConnection: boolean\r\n        /** Export Android Project for use with Android Studio/Gradle.\r\n         */\r\n        static exportAsGoogleAndroidProject: boolean\r\n        /** Set to true to build an Android App Bundle (aab file) instead of an apk. The default value is false.\r\n         */\r\n        static buildAppBundle: boolean\r\n        /** Symlink runtime libraries with an iOS Xcode project.\r\n         */\r\n        static symlinkLibraries: boolean\r\n        /** Scheme with which the project will be run in Xcode.\r\n         */\r\n        static iOSBuildConfigType: iOSBuildType\r\n        static switchCreateRomFile: boolean\r\n        static switchNVNGraphicsDebugger: boolean\r\n        static generateNintendoSwitchShaderInfo: boolean\r\n        static switchNVNShaderDebugging: boolean\r\n        static switchNVNDrawValidation_Light: boolean\r\n        static switchNVNDrawValidation_Heavy: boolean\r\n        static switchEnableHeapInspector: boolean\r\n        static switchEnableDebugPad: boolean\r\n        static switchRedirectWritesToHostMount: boolean\r\n        static switchHTCSScriptDebugging: boolean\r\n        static switchUseLegacyNvnPoolAllocator: boolean\r\n        /** Place the built player in the build folder.\r\n         */\r\n        static installInBuildFolder: boolean\r\n        /** Instructs the player to wait for managed debugger to attach before executing any script code.\r\n         */\r\n        static waitForManagedDebugger: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Behavior of semantic merge.\r\n     */\r\n    enum SemanticMergeMode {\r\n        /** Disable use of semantic merging.\r\n         */\r\n        Off = 0,\r\n        Premerge = 1,\r\n        Ask = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class EditorUserSettings extends Object {\r\n        static GetConfigValue(name: string): string\r\n        static SetConfigValue(name: string, value: string): void\r\n        protected constructor()\r\n        static AutomaticAdd: boolean\r\n        static WorkOffline: boolean\r\n        static showFailedCheckout: boolean\r\n        static overwriteFailedCheckoutAssets: boolean\r\n        static overlayIcons: boolean\r\n        static allowAsyncStatusUpdate: boolean\r\n        static semanticMergeMode: SemanticMergeMode\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** The editor selected render mode for Scene View selection.\r\n     */\r\n    enum EditorSelectedRenderState {\r\n        /** The Renderer has no selection highlight or wireframe in the Editor.\r\n         */\r\n        Hidden = 0,\r\n        /** The Renderer has wireframe but not selection highlight in the Editor.\r\n         */\r\n        Wireframe = 1,\r\n        /** The Renderer has selection highlight but no wireframe in the Editor.\r\n         */\r\n        Highlight = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** The mode of interaction, user or automated, that an API method is called with.\r\n     */\r\n    enum InteractionMode {\r\n        /** Use this setting to prevent a method from showing any dialog boxes to the user, and to prevent it recording to the undo history.\r\n         */\r\n        AutomatedAction = 0,\r\n        /** Use this setting to allow a method to show dialog boxes to the user, and to allow it to record to the undo history.\r\n         */\r\n        UserAction = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Compression Quality.\r\n     */\r\n    enum TextureCompressionQuality {\r\n        /** Fast compression.\r\n         */\r\n        Fast = 0,\r\n        /** Normal compression (default).\r\n         */\r\n        Normal = 50,\r\n        /** Best compression.\r\n         */\r\n        Best = 100,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** The type of opt-out decision a user can make.\r\n     */\r\n    enum DialogOptOutDecisionType {\r\n        /** The decision to opt out of seeing a dialog box for all time on the user's current machine.\r\n         */\r\n        ForThisMachine = 0,\r\n        /** The decision to opt out of seeing a dialog box for the duration of the current Editor session.\r\n         */\r\n        ForThisSession = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    /** SceneAsset is used to reference Scene objects in the Editor.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SceneAsset extends Object {\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array } from \"System\";\r\n    import { Object } from \"UnityEngine\";\r\n    /** Struct providing an API for stable, project-global object identifiers.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class GlobalObjectId extends ValueType {\r\n        constructor()\r\n        toString(): string\r\n        /** Check equality between two GlobalObjectIds.\r\n         */\r\n        Equals(other: GlobalObjectId): boolean\r\n        /** Converts an Object reference or InstanceID to a GlobalObjectId.\r\n         * @param targetObject The Object to be converted.\r\n         * @param instanceId The InstanceID of the Object to be converted.\r\n         * @returns The converted GlobalObjectId. If the conversion is unsuccessful, the GlobalObjectId is set to the default null ID: \"GlobalObjectId_V1-0-00000000000000000000000000000000-0-0\". \r\n         */\r\n        static GetGlobalObjectIdSlow(targetObject: Object): GlobalObjectId\r\n        /** Converts an Object reference or InstanceID to a GlobalObjectId.\r\n         * @param targetObject The Object to be converted.\r\n         * @param instanceId The InstanceID of the Object to be converted.\r\n         * @returns The converted GlobalObjectId. If the conversion is unsuccessful, the GlobalObjectId is set to the default null ID: \"GlobalObjectId_V1-0-00000000000000000000000000000000-0-0\". \r\n         */\r\n        static GetGlobalObjectIdSlow(instanceId: number): GlobalObjectId\r\n        /** Creates an array of GlobalObjectIds based on an array of Objects or InstanceIDs.\r\n         * @param objects Array of Objects to convert.\r\n         * @param outputIdentifiers Resulting array of GlobalObjectIds.\r\n         * @param instanceIds Array of InstanceIDs to convert.\r\n         */\r\n        static GetGlobalObjectIdsSlow(objects: Array<Object>, outputIdentifiers: Array<GlobalObjectId>): void\r\n        /** Creates an array of GlobalObjectIds based on an array of Objects or InstanceIDs.\r\n         * @param objects Array of Objects to convert.\r\n         * @param outputIdentifiers Resulting array of GlobalObjectIds.\r\n         * @param instanceIds Array of InstanceIDs to convert.\r\n         */\r\n        static GetGlobalObjectIdsSlow(instanceIds: Array<number>, outputIdentifiers: Array<GlobalObjectId>): void\r\n        /** Parses the string representation of a GlobalObjectId into a GlobalObjectId struct.\r\n         * @param stringValue The string representation of a GlobalObjectId.\nExample: \"GlobalObjectId_V1-2-74c253e3f16be4776bb2d88e01f77c8a-902906726-0\".\r\n         * @param id The GlobalObjectId struct for the parsed values.\r\n         * @returns Returns true if the string representation is successfully parsed. Otherwise, returns false. \r\n         */\r\n        static TryParse(stringValue: string, id: jsb.Out<GlobalObjectId>): boolean\r\n        /** Converts a GlobalObjectId to an Object reference.\r\n         * @param id The GlobalObjectId to lookup.\r\n         * @returns If the GlobalObjectId is found, this method returns the converted Object reference. Returns null if the GlobalObjectId is not found. \r\n         */\r\n        static GlobalObjectIdentifierToObjectSlow(id: GlobalObjectId): Object\r\n        /** Creates an array of Objects based on an array of GlobalObjectIds.\r\n         * @param identifiers Array of GlobalObjectIds to convert.\r\n         * @param outputObjects Resulting array of Object references.\r\n         */\r\n        static GlobalObjectIdentifiersToObjectsSlow(identifiers: Array<GlobalObjectId>, outputObjects: Array<Object>): void\r\n        /** Converts a GlobalObjectId to an InstanceID.\r\n         * @param id The GlobalObjectId to lookup.\r\n         * @returns If the GlobalObjectId is found, this method returns the converted InstanceID. Returns 0 if the GlobalObjectId is not found. \r\n         */\r\n        static GlobalObjectIdentifierToInstanceIDSlow(id: GlobalObjectId): number\r\n        /** Creates an array of InstanceIDs based on an array of GlobalObjectIds.\r\n         * @param identifiers Array of GlobalObjectIds to convert.\r\n         * @param outputInstanceIDs Resulting array of InstanceIDs.\r\n         */\r\n        static GlobalObjectIdentifiersToInstanceIDsSlow(identifiers: Array<GlobalObjectId>, outputInstanceIDs: Array<number>): void\r\n        /** The local file ID of the object.\r\n         */\r\n        readonly targetObjectId: number\r\n        /** The prefab instance id of the object.\r\n         */\r\n        readonly targetPrefabId: number\r\n        /** The GUID for the asset to which this object belongs.\r\n         */\r\n        readonly assetGUID: GUID\r\n        /** The identifier type represented as an integer.\r\n         */\r\n        readonly identifierType: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array, Object } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class GUID extends ValueType {\r\n        constructor(hexRepresentation: string)\r\n        Equals(obj: Object): boolean\r\n        Equals(obj: GUID): boolean\r\n        GetHashCode(): number\r\n        CompareTo(obj: Object): number\r\n        CompareTo(rhs: GUID): number\r\n        Empty(): boolean\r\n        toString(): string\r\n        static op_Equality(x: GUID, y: GUID): boolean\r\n        static op_Inequality(x: GUID, y: GUID): boolean\r\n        static op_LessThan(x: GUID, y: GUID): boolean\r\n        static op_GreaterThan(x: GUID, y: GUID): boolean\r\n        static TryParse(hex: string, result: jsb.Out<GUID>): boolean\r\n        static Generate(): GUID\r\n        // js_op_overloading: static ==(x: GUID, y: GUID): boolean\r\n        // js_op_overloading: static <(x: GUID, y: GUID): boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    import { Color, Matrix4x4 } from \"UnityEngine\";\r\n    namespace Handles {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class DrawingScope extends ValueType {\r\n            constructor(color: Color, matrix: Matrix4x4)\r\n            constructor(color: Color)\r\n            constructor(matrix: Matrix4x4)\r\n            Dispose(): void\r\n            readonly originalColor: Color\r\n            readonly originalMatrix: Matrix4x4\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Object as Object1 } from \"UnityEngine\";\r\n    /** Helper class to access Unity documentation.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class Help extends Object {\r\n        constructor()\r\n        /** Is there a help page for this object?\r\n         */\r\n        static HasHelpForObject(obj: Object1): boolean\r\n        /** Get the URL for this object's documentation.\r\n         * @param obj The object to retrieve documentation for.\r\n         * @returns The documentation URL for the object. Note that this could use the https: or file: schemas. \r\n         */\r\n        static GetHelpURLForObject(obj: Object1): string\r\n        /** Show help page for this object.\r\n         */\r\n        static ShowHelpForObject(obj: Object1): void\r\n        /** Show a help page.\r\n         */\r\n        static ShowHelpPage(page: string): void\r\n        /** Open url in the default web browser.\r\n         */\r\n        static BrowseURL(url: string): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum InspectorMode {\r\n        Normal = 0,\r\n        Debug = 1,\r\n        DebugInternal = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum HierarchyType {\r\n        Assets = 1,\r\n        GameObjects = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum IconDrawStyle {\r\n        NonTexture = 0,\r\n        Texture = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array, ValueType } from \"System\";\r\n    import { Object as Object1, Texture2D } from \"UnityEngine\";\r\n    import { SceneHierarchyHooks } from \"UnityEditor.SceneManagement\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class HierarchyProperty extends Object {\r\n        constructor(hierarchyType: HierarchyType, rootPath: string, forceImport: boolean)\r\n        constructor(hierarchyType: HierarchyType, forceImport: boolean)\r\n        constructor(rootPath: string, forceImport: boolean)\r\n        constructor(hierarchyType: HierarchyType)\r\n        constructor(rootPath: string)\r\n        SetCustomScenes(sceneHandles: Array<number>): void\r\n        SetSubScenes(subScenes: Array<SceneHierarchyHooks.SubSceneInfo>): void\r\n        Reset(): void\r\n        GetScene(): any\r\n        IsExpanded(expanded: Array<number>): boolean\r\n        Next(expanded: Array<number>): boolean\r\n        NextWithDepthCheck(expanded: Array<number>, minDepth: number): boolean\r\n        Previous(expanded: Array<number>): boolean\r\n        Parent(): boolean\r\n        Find(instanceID: number, expanded: Array<number>): boolean\r\n        Skip(count: number, expanded: Array<number>): boolean\r\n        CountRemaining(expanded: Array<number>): number\r\n        GetInstanceIDIfImported(): number\r\n        SetSearchFilter(searchString: string, mode: number): void\r\n        FindAllAncestors(instanceIDs: Array<number>): Array<number>\r\n        static ClearSceneObjectsFilter(): void\r\n        static FilterSingleSceneObject(instanceID: number, otherVisibilityState: boolean): void\r\n        readonly instanceID: number\r\n        readonly pptrValue: Object1\r\n        readonly name: string\r\n        readonly hasChildren: boolean\r\n        readonly depth: number\r\n        readonly ancestors: Array<number>\r\n        readonly row: number\r\n        readonly colorCode: number\r\n        readonly guid: string\r\n        alphaSorted: boolean\r\n        showSceneHeaders: boolean\r\n        readonly isSceneHeader: boolean\r\n        readonly isValid: boolean\r\n        readonly isMainRepresentation: boolean\r\n        readonly hasFullPreviewImage: boolean\r\n        readonly iconDrawStyle: IconDrawStyle\r\n        readonly isFolder: boolean\r\n        readonly dynamicDependencies: Array<GUID>\r\n        readonly icon: Texture2D\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface IHasCustomMenu {\r\n        /** Adds your custom menu items to an Editor Window.\r\n         */\r\n        AddItemsToMenu(menu: GenericMenu): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Component } from \"UnityEngine\";\r\n    /** LOD Utility Helpers.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class LODUtility extends Object {\r\n        constructor()\r\n        /** Recalculate the bounding region for the given LODGroup.\r\n         */\r\n        static CalculateLODGroupBoundingBox(group: any): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array, Enum } from \"System\";\r\n    import { Object as Object1, Vector2, Color, Vector4, Texture } from \"UnityEngine\";\r\n    /** Describes information and value of a single shader property.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class MaterialProperty extends Object {\r\n        constructor()\r\n        ReadFromMaterialPropertyBlock(block: any): void\r\n        WriteToMaterialPropertyBlock(materialblock: any, changedPropertyMask: number): void\r\n        /** Material objects being edited by this property (Read Only).\r\n         */\r\n        readonly targets: Array<Object1>\r\n        /** Type of the property (Read Only).\r\n         */\r\n        readonly type: MaterialProperty.PropType\r\n        /** Name of the property (Read Only).\r\n         */\r\n        readonly name: string\r\n        /** Display name of the property (Read Only).\r\n         */\r\n        readonly displayName: string\r\n        /** Flags that control how property is displayed (Read Only).\r\n         */\r\n        readonly flags: MaterialProperty.PropFlags\r\n        /** Texture dimension (2D, Cubemap etc.) of the property (Read Only).\r\n         */\r\n        readonly textureDimension: any\r\n        /** Min/max limits of a ranged float property (Read Only).\r\n         */\r\n        readonly rangeLimits: Vector2\r\n        /** Does this property have multiple different values? (Read Only)\r\n         */\r\n        readonly hasMixedValue: boolean\r\n        /** Color value of the property.\r\n         */\r\n        colorValue: Color\r\n        /** Vector value of the property.\r\n         */\r\n        vectorValue: Vector4\r\n        /** Float vaue of the property.\r\n         */\r\n        floatValue: number\r\n        /** Texture value of the property.\r\n         */\r\n        textureValue: Texture\r\n        textureScaleAndOffset: Vector4\r\n        applyPropertyCallback(op: \"get\"): (prop: MaterialProperty, changeMask: number, previousValue: Object) => boolean\r\n        applyPropertyCallback(op: \"add\" | \"remove\" | \"set\", fn?: (prop: MaterialProperty, changeMask: number, previousValue: Object) => boolean): void\r\n        applyPropertyCallback(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (prop: MaterialProperty, changeMask: number, previousValue: Object) => boolean): (prop: MaterialProperty, changeMask: number, previousValue: Object) => boolean | void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace MaterialProperty {\r\n        enum PropType {\r\n            Color = 0,\r\n            Vector = 1,\r\n            Float = 2,\r\n            Range = 3,\r\n            Texture = 4,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace MaterialProperty {\r\n        enum PropFlags {\r\n            None = 0,\r\n            HideInInspector = 1,\r\n            PerRendererData = 2,\r\n            NoScaleOffset = 4,\r\n            Normal = 8,\r\n            HDR = 16,\r\n            Gamma = 32,\r\n            NonModifiableTextureData = 64,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Menu class to manipulate the menu item.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class Menu extends Object {\r\n        constructor()\r\n        /** Set the check status of the given menu.\r\n         */\r\n        static SetChecked(menuPath: string, isChecked: boolean): void\r\n        /** Get the check status of the given menu.\r\n         */\r\n        static GetChecked(menuPath: string): boolean\r\n        /** Gets a menu item's enabled status.\r\n         * @param menuPath A slash-delimited path to the item's position in the menu. For example, \"Scene/Place on Surface\".\r\n         * @returns True if the menu item is enabled. False otherwise. \r\n         */\r\n        static GetEnabled(menuPath: string): boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Object as Object1 } from \"UnityEngine\";\r\n    /** Used to extract the context for a MenuItem.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class MenuCommand extends Object {\r\n        constructor(inContext: Object1, inUserData: number)\r\n        constructor(inContext: Object1)\r\n        /** Context is the object that is the target of a menu command.\r\n         */\r\n        context: Object1\r\n        /** An integer for passing custom information to a menu item.\r\n         */\r\n        userData: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { TextAsset, MonoBehaviour, ScriptableObject } from \"UnityEngine\";\r\n    import { Object } from \"System\";\r\n    /** Representation of Script assets.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class MonoScript extends TextAsset {\r\n        constructor()\r\n        GetClass(): any\r\n        /** Returns the MonoScript object containing specified MonoBehaviour.\r\n         * @param behaviour The MonoBehaviour whose MonoScript should be returned.\r\n         */\r\n        static FromMonoBehaviour(behaviour: MonoBehaviour): MonoScript\r\n        /** Returns the MonoScript object containing specified ScriptableObject.\r\n         * @param scriptableObject The ScriptableObject whose MonoScript should be returned.\r\n         */\r\n        static FromScriptableObject(scriptableObject: ScriptableObject): MonoScript\r\n    }\r\n}\r\ndeclare module \"UnityEngine\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Array } from \"System\";\r\n    /** Text file assets.\r\n     */\r\n    class TextAsset extends Object {\r\n        constructor(text: string)\r\n        constructor()\r\n        toString(): string\r\n        /** The raw bytes of the text asset. (Read Only)\r\n         */\r\n        readonly bytes: Array<jsb.byte>\r\n        /** The text contents of the .txt file as a string. (Read Only)\r\n         */\r\n        readonly text: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Object as Object1 } from \"UnityEngine\";\r\n    /** Helper class for constructing displayable names for objects.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ObjectNames extends Object {\r\n        constructor()\r\n        /** Make a displayable name for a variable.\r\n         */\r\n        static NicifyVariableName(name: string): string\r\n        /** Class name of an object.\r\n         */\r\n        static GetClassName(obj: Object1): string\r\n        /** Drag and drop title for an object.\r\n         */\r\n        static GetDragAndDropTitle(obj: Object1): string\r\n        /** Sets the name of an Object.\r\n         */\r\n        static SetNameSmart(obj: Object1, name: string): void\r\n        /** Make a unique name using the provided name as a base.\n\nIf the target name is in the provided list of existing names, a unique name is generated by appending the next available numerical increment.\r\n         * @param existingNames A list of pre-existing names.\r\n         * @param name Desired name to be used as is, or as a base.\r\n         * @returns A name not found in the list of pre-existing names. \r\n         */\r\n        static GetUniqueName(existingNames: Array<string>, name: string): string\r\n        /** Inspector title for an object.\r\n         */\r\n        static GetInspectorTitle(obj: Object1): string\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class PackageInfo extends ValueType {\r\n        constructor()\r\n        packagePath: string\r\n        jsonInfo: string\r\n        iconURL: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Scripting implementation (backend).\r\n     */\r\n    enum ScriptingImplementation {\r\n        /** The standard Mono 2.6 runtime.\r\n         */\r\n        Mono2x = 0,\r\n        /** Unity's .NET runtime.\r\n         */\r\n        IL2CPP = 1,\r\n        /** Microsoft's .NET runtime.\r\n         */\r\n        WinRTDotNET = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** C++ compiler configuration used when compiling IL2CPP generated code.\r\n     */\r\n    enum Il2CppCompilerConfiguration {\r\n        /** Debug configuration turns off all optimizations, which makes the code quicker to build but slower to run.\r\n         */\r\n        Debug = 0,\r\n        /** Release configuration enables optimizations, so the compiled code runs faster and the binary size is smaller but it takes longer to compile.\r\n         */\r\n        Release = 1,\r\n        /** Master configuration enables all possible optimizations, squeezing every bit of performance possible. For instance, on platforms that use the MSVC++ compiler, this option enables link-time code generation. Compiling code using this configuration can take significantly longer than it does using the Release configuration. Unity recommends building the shipping version of your game using the Master configuration if the increase in build time is acceptable.\r\n         */\r\n        Master = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Aspect ratio.\r\n     */\r\n    enum AspectRatio {\r\n        /** Undefined aspect ratios.\r\n         */\r\n        AspectOthers = 0,\r\n        /** 4:3 aspect ratio.\r\n         */\r\n        Aspect4by3 = 1,\r\n        /** 5:4 aspect ratio.\r\n         */\r\n        Aspect5by4 = 2,\r\n        /** 16:10 aspect ratio.\r\n         */\r\n        Aspect16by10 = 3,\r\n        /** 16:9 aspect ratio.\r\n         */\r\n        Aspect16by9 = 4,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Mac fullscreen mode.\r\n     */\r\n    enum MacFullscreenMode {\r\n        CaptureDisplay = 0,\r\n        /** Fullscreen window.\r\n         */\r\n        FullscreenWindow = 1,\r\n        /** Fullscreen window with Dock and Menu bar.\r\n         */\r\n        FullscreenWindowWithDockAndMenuBar = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Direct3D 11 fullscreen mode.\r\n     */\r\n    enum D3D11FullscreenMode {\r\n        /** Exclusive mode.\r\n         */\r\n        ExclusiveMode = 0,\r\n        /** Fullscreen window.\r\n         */\r\n        FullscreenWindow = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Enum used to specify what stereo rendering path to use.\r\n     */\r\n    enum StereoRenderingPath {\r\n        /** Multiple pass VR rendering.\r\n         */\r\n        MultiPass = 0,\r\n        /** Single pass VR rendering ( via double-wide render texture ).\r\n         */\r\n        SinglePass = 1,\r\n        /** Single pass VR rendering ( via instanced rendering ).\r\n         */\r\n        Instancing = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Managed code stripping level.\r\n     */\r\n    enum StrippingLevel {\r\n        /** Deprecated. See ManagedStrippingLevel.\r\n         */\r\n        Disabled = 0,\r\n        /** Deprecated. See ManagedStrippingLevel.\r\n         */\r\n        StripAssemblies = 1,\r\n        /** Deprecated. See ManagedStrippingLevel.\r\n         */\r\n        StripByteCode = 2,\r\n        /** Deprecated. See ManagedStrippingLevel.\r\n         */\r\n        UseMicroMSCorlib = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Script call optimization level.\r\n     */\r\n    enum ScriptCallOptimizationLevel {\r\n        /** Default setting.\r\n         */\r\n        SlowAndSafe = 0,\r\n        /** Script method call overhead decreased at the expense of limited compatibility.\r\n         */\r\n        FastButNoExceptions = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** .NET API compatibility level.\r\n     */\r\n    enum ApiCompatibilityLevel {\r\n        /** .NET 2.0.\r\n         */\r\n        NET_2_0 = 1,\r\n        /** .NET 2.0 Subset.\r\n         */\r\n        NET_2_0_Subset = 2,\r\n        /** .NET 4.6.\r\n         */\r\n        NET_4_6 = 3,\r\n        /** Web profile, formerly used only by Samsung TV.\r\n         */\r\n        NET_Web = 4,\r\n        /** Micro profile, used by Mono scripting backend on iOS, tvOS, and Android if stripping level is set to \"Use micro mscorlib\".\r\n         */\r\n        NET_Micro = 5,\r\n        /** Profile that targets the .NET Standard 2.0.\r\n         */\r\n        NET_Standard_2_0 = 6,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Defines how aggressively Unity strips unused managed (C#) code.\r\n     */\r\n    enum ManagedStrippingLevel {\r\n        /** Do not strip any code.\r\n         */\r\n        Disabled = 0,\r\n        /** Remove unreachable managed code to reduce build size and Mono/IL2CPP build times.\r\n         */\r\n        Low = 1,\r\n        /** Run UnityLinker in a less conservative mode than Low. This will further reduce code size beyond what Low can achieve. However, this additional reduction may come with tradeoffs. Possible side effects may include, having to maintain a custom link.xml file, and some reflection code paths may not behave the same.\r\n         */\r\n        Medium = 2,\r\n        /** UnityLinker will strip as much as possible. This will further reduce code size beyond what Medium can achieve. However, this additional reduction may come with tradeoffs. Possible side effects may include, managed code debugging of some methods may no longer work.  You may need to maintain a custom link.xml file, and some reflection code paths may not behave the same.\r\n         */\r\n        High = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** The behavior in case of unhandled .NET exception.\r\n     */\r\n    enum ActionOnDotNetUnhandledException {\r\n        /** Silent exit in case of unhandled .NET exception (no Crash Report generated).\r\n         */\r\n        SilentExit = 0,\r\n        /** Crash in case of unhandled .NET exception (Crash Report will be generated).\r\n         */\r\n        Crash = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Enum used to specify the graphics jobs mode to use.\r\n     */\r\n    enum GraphicsJobMode {\r\n        /** Native graphics jobs.\r\n         */\r\n        Native = 0,\r\n        /** Legacy graphics jobs.\r\n         */\r\n        Legacy = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Icon kind.\r\n     */\r\n    enum IconKind {\r\n        /** This icon is used for the main application icons.\r\n         */\r\n        Application = 0,\r\n        /** This icon is used for settings.\r\n         */\r\n        Settings = 1,\r\n        /** This icon is used for push notifications.\r\n         */\r\n        Notification = 2,\r\n        /** This icon is used for Spotlight searches. (iOS only).\r\n         */\r\n        Spotlight = 3,\r\n        /** This icon is used by the iOS App Store.\r\n         */\r\n        Store = 4,\r\n        /** This icon can be used for any purpose in an application.\r\n         */\r\n        Any = -1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Options for the shader precision model.\r\n     */\r\n    enum ShaderPrecisionModel {\r\n        /** Use the target platform defaults for sampler precision. This results in lower precision on mobile targets and full precision elsewhere.\r\n         */\r\n        PlatformDefault = 0,\r\n        /** Use full sampler precision by default and make it so you have to explicitly declare when you want to use lower precision. This sets Rendering.BuiltinShaderDefine.UNITY_UNIFIED_SHADER_PRECISION_MODEL when Unity compiles shaders.\r\n         */\r\n        Unified = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Describes the encoding of normal maps.\r\n     */\r\n    enum NormalMapEncoding {\r\n        /** Three-component normal map encoding.\r\n         */\r\n        XYZ = 0,\r\n        /** Two-component DXT5nm-style normal map encoding.\r\n         */\r\n        DXT5nm = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Texture2D, Vector2 } from \"UnityEngine\";\r\n    import { ValueType, Enum, Array } from \"System\";\r\n    /** Player Settings is where you define various parameters for the final game that you will build in Unity. Some of these values are used in the Resolution Dialog that launches when you open a standalone game.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class PlayerSettings extends Object {\r\n        /** Returns whether or not the specified aspect ratio is enabled.\r\n         */\r\n        static HasAspectRatio(aspectRatio: AspectRatio): boolean\r\n        /** Enables the specified aspect ratio.\r\n         */\r\n        static SetAspectRatio(aspectRatio: AspectRatio, enable: boolean): void\r\n        static GetPreloadedAssets(): Array<Object>\r\n        /** Assigns the assets that will be loaded at start up in the player and be kept alive until the player terminates.\r\n         */\r\n        static SetPreloadedAssets(assets: Array<Object>): void\r\n        /** Get graphics APIs to be used on a build platform.\r\n         * @param platform Platform to get APIs for.\r\n         * @returns Array of graphics APIs. \r\n         */\r\n        static GetGraphicsAPIs(platform: BuildTarget): Array<any>\r\n        /** Sets the graphics APIs used on a build platform.\r\n         * @param platform Platform to set APIs for.\r\n         * @param apis Array of graphics APIs.\r\n         */\r\n        static SetGraphicsAPIs(platform: BuildTarget, apis: Array<any>): void\r\n        /** Is a build platform using automatic graphics API choice?\r\n         * @param platform Platform to get the flag for.\r\n         * @returns Should best available graphics API be used. \r\n         */\r\n        static GetUseDefaultGraphicsAPIs(platform: BuildTarget): boolean\r\n        /** Should a build platform use automatic graphics API choice.\r\n         * @param platform Platform to set the flag for.\r\n         * @param automatic Should best available graphics API be used?\r\n         */\r\n        static SetUseDefaultGraphicsAPIs(platform: BuildTarget, automatic: boolean): void\r\n        /** Sets a value of a custom template variable.\r\n         * @param name Name of the variable.\r\n         * @param value Value of the custom template variable.\r\n         */\r\n        static SetTemplateCustomValue(name: string, value: string): void\r\n        /** Returns a value of a custom template variable.\r\n         * @param name Name of the variable.\r\n         * @returns The current value of the custom template variable. \r\n         */\r\n        static GetTemplateCustomValue(name: string): string\r\n        static GetScriptingDefineSymbolsForGroup(targetGroup: BuildTargetGroup, defines: jsb.Out<Array<string>>): void\r\n        /** Get user-specified symbols for script compilation for the given build target group.\r\n         */\r\n        static GetScriptingDefineSymbolsForGroup(targetGroup: BuildTargetGroup): string\r\n        /** Set user-specified symbols for script compilation for the given build target group.\r\n         * @param targetGroup The name of the group of devices.\r\n         * @param defines Symbols for this group can be passed as an array or as a string separated by semicolons.\r\n         */\r\n        static SetScriptingDefineSymbolsForGroup(targetGroup: BuildTargetGroup, defines: string): void\r\n        /** Set user-specified symbols for script compilation for the given build target group.\r\n         * @param targetGroup The name of the group of devices.\r\n         * @param defines Symbols for this group can be passed as an array or as a string separated by semicolons.\r\n         */\r\n        static SetScriptingDefineSymbolsForGroup(targetGroup: BuildTargetGroup, defines: Array<string>): void\r\n        /** Gets an array of additional compiler arguments set for a specific BuildTargetGroup.\r\n         * @param targetGroup The BuildTargetGroup to get the compiler arguments for.\r\n         * @returns Returns an array with the compiler arguments associated with a BuildTargetGroup. \r\n         */\r\n        static GetAdditionalCompilerArgumentsForGroup(targetGroup: BuildTargetGroup): Array<string>\r\n        /** Sets additional compiler arguments for a BuildTargetGroup.\r\n         * @param targetGroup The BuildTargetGroup to set the additional compiler arguments for.\r\n         * @param additionalCompilerArguments An array of the additional compiler arguments.\r\n         */\r\n        static SetAdditionalCompilerArgumentsForGroup(targetGroup: BuildTargetGroup, additionalCompilerArguments: Array<string>): void\r\n        /** Gets the BuildTargetPlatformGroup architecture.\r\n         */\r\n        static GetArchitecture(targetGroup: BuildTargetGroup): number\r\n        /** Sets the BuildTargetPlatformGroup architecture.\r\n         */\r\n        static SetArchitecture(targetGroup: BuildTargetGroup, architecture: number): void\r\n        /** Gets the scripting framework for a BuildTargetPlatformGroup.\r\n         */\r\n        static GetScriptingBackend(targetGroup: BuildTargetGroup): ScriptingImplementation\r\n        /** Set the application identifier for the specified platform.\r\n         */\r\n        static SetApplicationIdentifier(targetGroup: BuildTargetGroup, identifier: string): void\r\n        /** Get the application identifier for the specified platform.\r\n         */\r\n        static GetApplicationIdentifier(targetGroup: BuildTargetGroup): string\r\n        /** Sets the scripting framework for a BuildTargetPlatformGroup.\r\n         */\r\n        static SetScriptingBackend(targetGroup: BuildTargetGroup, backend: ScriptingImplementation): void\r\n        /** Returns the default ScriptingImplementation used for the given platform group.\r\n         * @param targetGroup The platform group to retrieve the scripting backend for.\r\n         * @returns A ScriptingImplementation object that describes the default scripting backend used on that platform. \r\n         */\r\n        static GetDefaultScriptingBackend(targetGroup: BuildTargetGroup): ScriptingImplementation\r\n        /** Sets compiler configuration used when compiling generated C++ code for a particular BuildTargetGroup.\r\n         * @param targetGroup Build target group.\r\n         * @param configuration Compiler configuration.\r\n         */\r\n        static SetIl2CppCompilerConfiguration(targetGroup: BuildTargetGroup, configuration: Il2CppCompilerConfiguration): void\r\n        /** Gets compiler configuration used when compiling generated C++ code for a particular BuildTargetGroup.\r\n         * @param targetGroup Build target group.\r\n         * @returns Compiler configuration. \r\n         */\r\n        static GetIl2CppCompilerConfiguration(targetGroup: BuildTargetGroup): Il2CppCompilerConfiguration\r\n        /** Does IL2CPP platform use incremental build?\r\n         */\r\n        static GetIncrementalIl2CppBuild(targetGroup: BuildTargetGroup): boolean\r\n        /** Sets incremental build flag.\r\n         */\r\n        static SetIncrementalIl2CppBuild(targetGroup: BuildTargetGroup, enabled: boolean): void\r\n        static GetAdditionalIl2CppArgs(): string\r\n        /** IL2CPP build arguments.\r\n         */\r\n        static SetAdditionalIl2CppArgs(additionalArgs: string): void\r\n        static GetWsaHolographicRemotingEnabled(): boolean\r\n        static SetWsaHolographicRemotingEnabled(enabled: boolean): void\r\n        /** Sets the managed code stripping level for specified BuildTargetGroup.\r\n         * @param BuildTargetGroup The platform build target group whose stripping level you want to set.\r\n         * @param ManagedStrippingLevel The desired managed code stripping level.\r\n         */\r\n        static SetManagedStrippingLevel(targetGroup: BuildTargetGroup, level: ManagedStrippingLevel): void\r\n        /** Returns the ManagedStrippingLevel used for the given platform group.\r\n         * @param targetGroup The target platform group whose code stripping level you want to retrieve.\r\n         * @returns The managed code stripping level set for the specified build target platform group. \r\n         */\r\n        static GetManagedStrippingLevel(targetGroup: BuildTargetGroup): ManagedStrippingLevel\r\n        /** Gets .NET API compatibility level for specified BuildTargetGroup.\r\n         */\r\n        static GetApiCompatibilityLevel(buildTargetGroup: BuildTargetGroup): ApiCompatibilityLevel\r\n        /** Sets .NET API compatibility level for specified BuildTargetGroup.\r\n         */\r\n        static SetApiCompatibilityLevel(buildTargetGroup: BuildTargetGroup, value: ApiCompatibilityLevel): void\r\n        /** Enable or disable multithreaded rendering option for mobile platform.\r\n         * @param targetGroup Mobile platform (Only iOS, tvOS and Android).\r\n         */\r\n        static SetMobileMTRendering(targetGroup: BuildTargetGroup, enable: boolean): void\r\n        /** Check if multithreaded rendering option for mobile platform is enabled.\r\n         * @param targetGroup Mobile platform (Only iOS, tvOS and Android).\r\n         * @returns Return true if multithreaded rendering option for targetGroup platform is enabled. \r\n         */\r\n        static GetMobileMTRendering(targetGroup: BuildTargetGroup): boolean\r\n        /** Get stack trace logging options.\r\n         */\r\n        static GetStackTraceLogType(logType: any): any\r\n        /** Set stack trace logging options.\nNote: calling this function will implicitly call Application.SetStackTraceLogType.\r\n         */\r\n        static SetStackTraceLogType(logType: any, stackTraceType: any): void\r\n        static GetVirtualTexturingSupportEnabled(): boolean\r\n        /** Enable virtual texturing.\r\n         * @param enabled True to enable, false to disable.\r\n         */\r\n        static SetVirtualTexturingSupportEnabled(enabled: boolean): void\r\n        static GetShaderPrecisionModel(): ShaderPrecisionModel\r\n        /** Sets the shader precision model.\r\n         * @param model The new precision model to use.\r\n         */\r\n        static SetShaderPrecisionModel(model: ShaderPrecisionModel): void\r\n        /** Returns the NormalMapEncoding used for the given platform group.\r\n         * @param targetGroup The target platform group whose normal map encoding you want to retrieve.\r\n         * @returns The NormalMapEncoding for the given platform group. \r\n         */\r\n        static GetNormalMapEncoding(platform: BuildTargetGroup): NormalMapEncoding\r\n        /** Sets the normal map encoding for the given platform.\r\n         * @param targetGroup The platform build target group whose normal map encoding you want to set.\r\n         * @param normalMapEncoding The desired normal map encoding.\r\n         */\r\n        static SetNormalMapEncoding(platform: BuildTargetGroup, encoding: NormalMapEncoding): void\r\n        /**\r\n         * @param platform Platform to get the flag for.\r\n         * @returns Should the security build be used. \r\n         */\r\n        static GetSecurityBuildForPlatform(platform: BuildTarget): boolean\r\n        /** Set the bool value to enable or disable the security build for target platform.\r\n         * @param platform The platform to use.\r\n         * @param securityBuild Should the security build be used?\r\n         */\r\n        static SetSecurityBuildForPlatform(platform: BuildTarget, securityBuild: boolean): void\r\n        /** Returns the list of available icon slots for the specified platform and  PlatformIconKind|kind.\r\n         * @param platform The full list of platforms that support this API and the supported icon kinds can be found in PlatformIconKind|icon kinds.\r\n         * @param kind Each platform supports a different set of PlatformIconKind|icon kinds. These can be found in the specific platform namespace (for example iOSPlatformIconKind.\r\n         */\r\n        static GetPlatformIcons(platform: BuildTargetGroup, kind: PlatformIconKind): Array<PlatformIcon>\r\n        /** Assign a list of icons for the specified platform and icon kind.\r\n         * @param type Each platform supports a different set of PlatformIconKind|icon kinds. These can be found in the specific platform namespace (for example iOSPlatformIconKind).\r\n         * @param platform The full list of platforms that support this API the supported  kinds can be found in PlatformIconKind|icon kinds.\r\n         * @param icons All available PlatformIcon slots must be retrieved with GetPlatformIcons.\r\n         */\r\n        static SetPlatformIcons(platform: BuildTargetGroup, kind: PlatformIconKind, icons: Array<PlatformIcon>): void\r\n        /** Retrieve all icon kinds supported by the specified platform.\r\n         */\r\n        static GetSupportedIconKindsForPlatform(platform: BuildTargetGroup): Array<PlatformIconKind>\r\n        /** Assign a list of icons for the specified platform.\r\n         */\r\n        static SetIconsForTargetGroup(platform: BuildTargetGroup, icons: Array<Texture2D>, kind: IconKind): void\r\n        /** Assign a list of icons for the specified platform.\r\n         */\r\n        static SetIconsForTargetGroup(platform: BuildTargetGroup, icons: Array<Texture2D>): void\r\n        /** Returns the list of assigned icons for the specified platform.\r\n         */\r\n        static GetIconsForTargetGroup(platform: BuildTargetGroup, kind: IconKind): Array<Texture2D>\r\n        /** Returns the list of assigned icons for the specified platform.\r\n         */\r\n        static GetIconsForTargetGroup(platform: BuildTargetGroup): Array<Texture2D>\r\n        /** Returns a list of icon sizes for the specified platform.\r\n         */\r\n        static GetIconSizesForTargetGroup(platform: BuildTargetGroup, kind: IconKind): Array<number>\r\n        /** Returns a list of icon sizes for the specified platform.\r\n         */\r\n        static GetIconSizesForTargetGroup(platform: BuildTargetGroup): Array<number>\r\n        protected constructor()\r\n        /** The name of your company.\r\n         */\r\n        static companyName: string\r\n        /** The name of your product.\r\n         */\r\n        static productName: string\r\n        static readonly productGUID: any\r\n        /** Set the rendering color space for the current project.\r\n         */\r\n        static colorSpace: any\r\n        /** Default horizontal dimension of stand-alone player window.\r\n         */\r\n        static defaultScreenWidth: number\r\n        /** Default vertical dimension of stand-alone player window.\r\n         */\r\n        static defaultScreenHeight: number\r\n        /** Default horizontal dimension of web player window.\r\n         */\r\n        static defaultWebScreenWidth: number\r\n        /** Default vertical dimension of web player window.\r\n         */\r\n        static defaultWebScreenHeight: number\r\n        static defaultIsNativeResolution: boolean\r\n        /** Enable Retina support for macOS.\r\n         */\r\n        static macRetinaSupport: boolean\r\n        /** If enabled, your game will continue to run after lost focus.\r\n         */\r\n        static runInBackground: boolean\r\n        /** Defines if fullscreen games should darken secondary displays.\r\n         */\r\n        static captureSingleScreen: boolean\r\n        /** Write a log file with debugging information.\r\n         */\r\n        static usePlayerLog: boolean\r\n        /** Use resizable window in standalone player builds.\r\n         */\r\n        static resizableWindow: boolean\r\n        /** Pre bake collision meshes on player build.\r\n         */\r\n        static bakeCollisionMeshes: boolean\r\n        /** Enable receipt validation for the Mac App Store.\r\n         */\r\n        static useMacAppStoreValidation: boolean\r\n        /** Platform agnostic setting to define fullscreen behavior. Not all platforms support all modes.\r\n         */\r\n        static fullScreenMode: any\r\n        /** Enable 360 Stereo Capture support on the current build target.\r\n         */\r\n        static enable360StereoCapture: boolean\r\n        /** Active stereo rendering path\r\n         */\r\n        static stereoRenderingPath: StereoRenderingPath\r\n        /** Enable frame timing statistics.\r\n         */\r\n        static enableFrameTimingStats: boolean\r\n        /** Switch display to HDR mode (if available).\r\n         */\r\n        static useHDRDisplay: boolean\r\n        /** The number of bits in each color channel for swap chain buffers. (Direct3D 11 and Direct3D 12 mode).\r\n         */\r\n        static D3DHDRBitDepth: any\r\n        /** On Windows, show the application in the background if Fullscreen Windowed mode is used.\r\n         */\r\n        static visibleInBackground: boolean\r\n        /** If enabled, allows the user to switch between full screen and windowed mode using OS specific keyboard short cuts.\r\n         */\r\n        static allowFullscreenSwitch: boolean\r\n        /** Restrict standalone players to a single concurrent running instance.\r\n         */\r\n        static forceSingleInstance: boolean\r\n        /** Use DXGI Flip Model Swapchain for D3D11\r\n         */\r\n        static useFlipModelSwapchain: boolean\r\n        /** Specifies whether the application requires OpenGL ES 3.1 support.\r\n         */\r\n        static openGLRequireES31: boolean\r\n        /** Specifies whether the application requires OpenGL ES 3.1 AEP support.\r\n         */\r\n        static openGLRequireES31AEP: boolean\r\n        /** Specifies whether the application requires OpenGL ES 3.2 support.\r\n         */\r\n        static openGLRequireES32: boolean\r\n        /** Virtual Reality specific splash screen.\r\n         */\r\n        static virtualRealitySplashScreen: Texture2D\r\n        /** Set to true to exact version matching for strong named assemblies.\r\n         */\r\n        static assemblyVersionValidation: boolean\r\n        /** Suppresses common C# warnings.\r\n         */\r\n        static suppressCommonWarnings: boolean\r\n        /** Allow 'unsafe' C# code code to be compiled for predefined assemblies.\r\n         */\r\n        static allowUnsafeCode: boolean\r\n        /** Set to true to make Unity use Roslyn reference assemblies when compiling scripts. Enabled by default.\r\n         */\r\n        static useReferenceAssemblies: boolean\r\n        /** Allows you to enable or disable incremental mode for garbage collection.\r\n         */\r\n        static gcIncremental: boolean\r\n        /** Password used for interacting with the Android Keystore.\r\n         */\r\n        static keystorePass: string\r\n        /** Password for the key used for signing an Android application.\r\n         */\r\n        static keyaliasPass: string\r\n        /** Enable GPU skinning on capable platforms.\r\n         */\r\n        static gpuSkinning: boolean\r\n        /** Enable graphics jobs (multi threaded rendering).\r\n         */\r\n        static graphicsJobs: boolean\r\n        /** Selects the graphics job mode to use on platforms that support both Native and Legacy graphics jobs.\r\n         */\r\n        static graphicsJobMode: GraphicsJobMode\r\n        static readonly xboxPIXTextureCapture: boolean\r\n        /** Xbox 360 Avatars.\r\n         */\r\n        static readonly xboxEnableAvatar: boolean\r\n        static readonly xboxOneResolution: number\r\n        /** Enables internal profiler.\r\n         */\r\n        static enableInternalProfiler: boolean\r\n        /** Sets the crash behavior on .NET unhandled exception.\r\n         */\r\n        static actionOnDotNetUnhandledException: ActionOnDotNetUnhandledException\r\n        /** Are ObjC uncaught exceptions logged?\r\n         */\r\n        static logObjCUncaughtExceptions: boolean\r\n        /** Enables CrashReport API.\r\n         */\r\n        static enableCrashReportAPI: boolean\r\n        /** The application identifier for the currently selected build target.\r\n         */\r\n        static applicationIdentifier: string\r\n        /** Application bundle version shared between iOS & Android platforms.\r\n         */\r\n        static bundleVersion: string\r\n        /** Returns if status bar should be hidden. Supported on iOS only; on Android, the status bar is always hidden.\r\n         */\r\n        static statusBarHidden: boolean\r\n        /** Remove unused Engine code from your build (IL2CPP-only).\r\n         */\r\n        static stripEngineCode: boolean\r\n        /** Default screen orientation for mobiles.\r\n         */\r\n        static defaultInterfaceOrientation: UIOrientation\r\n        /** Is auto-rotation to portrait supported?\r\n         */\r\n        static allowedAutorotateToPortrait: boolean\r\n        /** Is auto-rotation to portrait upside-down supported?\r\n         */\r\n        static allowedAutorotateToPortraitUpsideDown: boolean\r\n        /** Is auto-rotation to landscape right supported?\r\n         */\r\n        static allowedAutorotateToLandscapeRight: boolean\r\n        /** Is auto-rotation to landscape left supported?\r\n         */\r\n        static allowedAutorotateToLandscapeLeft: boolean\r\n        /** Let the OS autorotate the screen as the device orientation changes.\r\n         */\r\n        static useAnimatedAutorotation: boolean\r\n        /** 32-bit Display Buffer is used.\r\n         */\r\n        static use32BitDisplayBuffer: boolean\r\n        /** When enabled, preserves the alpha value in the framebuffer to support rendering over native UI on Android.\r\n         */\r\n        static preserveFramebufferAlpha: boolean\r\n        /** Should unused Mesh components be excluded from game build?\r\n         */\r\n        static stripUnusedMeshComponents: boolean\r\n        /** Enable mip stripping for all platforms.\r\n         */\r\n        static mipStripping: boolean\r\n        /** Is the advanced version being used?\r\n         */\r\n        static readonly advancedLicense: boolean\r\n        /** Additional AOT compilation options. Shared by AOT platforms.\r\n         */\r\n        static aotOptions: string\r\n        /** The default cursor for your application.\r\n         */\r\n        static defaultCursor: Texture2D\r\n        /** Default cursor's click position in pixels from the top left corner of the cursor image.\r\n         */\r\n        static cursorHotspot: Vector2\r\n        /** Accelerometer update frequency.\r\n         */\r\n        static accelerometerFrequency: number\r\n        /** Is multi-threaded rendering enabled?\r\n         */\r\n        static MTRendering: boolean\r\n        /** Stops or allows audio from other applications to play in the background while your Unity application is running.\r\n         */\r\n        static muteOtherAudioSources: boolean\r\n        /** Defines whether the BlendShape weight range in SkinnedMeshRenderers is clamped.\r\n         */\r\n        static legacyClampBlendShapeWeights: boolean\r\n        /** Enables Metal API validation in the Editor.\r\n         */\r\n        static enableMetalAPIValidation: boolean\r\n        /** Enables Graphics.SetSRGBWrite() on Vulkan renderer.\r\n         */\r\n        static vulkanEnableSetSRGBWrite: boolean\r\n        /** Set number of swapchain buffers to be used with Vulkan renderer\r\n         */\r\n        static vulkanNumSwapchainBuffers: number\r\n        /** Delays acquiring the swapchain image until after the frame is rendered.\r\n         */\r\n        static vulkanEnableLateAcquireNextImage: boolean\r\n        /** Applies the display rotation during rendering.\r\n         */\r\n        static vulkanEnablePreTransform: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Enum } from \"System\";\r\n    namespace PlayerSettings {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class Android extends Object {\r\n            constructor()\r\n            static disableDepthAndStencilBuffers: boolean\r\n            static defaultWindowWidth: number\r\n            static defaultWindowHeight: number\r\n            static minimumWindowWidth: number\r\n            static minimumWindowHeight: number\r\n            static resizableWindow: boolean\r\n            static fullscreenMode: any\r\n            static bundleVersionCode: number\r\n            static minSdkVersion: any\r\n            static targetSdkVersion: any\r\n            static preferredInstallLocation: any\r\n            static forceInternetPermission: boolean\r\n            static forceSDCardPermission: boolean\r\n            static androidTVCompatibility: boolean\r\n            static androidIsGame: boolean\r\n            static ARCoreEnabled: boolean\r\n            static chromeosInputEmulation: boolean\r\n            static targetArchitectures: any\r\n            static buildApkPerCpuArchitecture: boolean\r\n            static androidTargetDevices: AndroidTargetDevices\r\n            static splashScreenScale: any\r\n            static useCustomKeystore: boolean\r\n            static keystoreName: string\r\n            static keystorePass: string\r\n            static keyaliasName: string\r\n            static keyaliasPass: string\r\n            static readonly licenseVerification: boolean\r\n            static useAPKExpansionFiles: boolean\r\n            static showActivityIndicatorOnLoading: any\r\n            static blitType: any\r\n            static maxAspectRatio: number\r\n            static startInFullscreen: boolean\r\n            static renderOutsideSafeArea: boolean\r\n            static minifyWithR8: boolean\r\n            static minifyRelease: boolean\r\n            static minifyDebug: boolean\r\n            static optimizedFramePacing: boolean\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Enum, Array } from \"System\";\r\n    import { Texture2D } from \"UnityEngine\";\r\n    namespace PlayerSettings {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class iOS extends Object {\r\n            constructor()\r\n            static SetLaunchScreenImage(image: Texture2D, type: iOSLaunchScreenImageType): void\r\n            static SetiPhoneLaunchScreenType(type: iOSLaunchScreenType): void\r\n            static SetiPadLaunchScreenType(type: iOSLaunchScreenType): void\r\n            static applicationDisplayName: string\r\n            static buildNumber: string\r\n            static disableDepthAndStencilBuffers: boolean\r\n            static scriptCallOptimization: ScriptCallOptimizationLevel\r\n            static sdkVersion: iOSSdkVersion\r\n            static targetOSVersionString: string\r\n            static targetDevice: iOSTargetDevice\r\n            static prerenderedIcon: boolean\r\n            static requiresPersistentWiFi: boolean\r\n            static requiresFullScreen: boolean\r\n            static statusBarStyle: iOSStatusBarStyle\r\n            static deferSystemGesturesMode: any\r\n            static hideHomeButton: boolean\r\n            static appInBackgroundBehavior: iOSAppInBackgroundBehavior\r\n            static backgroundModes: iOSBackgroundMode\r\n            static forceHardShadowsOnMetal: boolean\r\n            static allowHTTPDownload: boolean\r\n            static appleDeveloperTeamID: string\r\n            static iOSManualProvisioningProfileID: string\r\n            static tvOSManualProvisioningProfileID: string\r\n            static tvOSManualProvisioningProfileType: ProvisioningProfileType\r\n            static iOSManualProvisioningProfileType: ProvisioningProfileType\r\n            static appleEnableAutomaticSigning: boolean\r\n            static cameraUsageDescription: string\r\n            static locationUsageDescription: string\r\n            static microphoneUsageDescription: string\r\n            static showActivityIndicatorOnLoading: iOSShowActivityIndicatorOnLoading\r\n            static useOnDemandResources: boolean\r\n            static iOSUrlSchemes: Array<string>\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    namespace PlayerSettings {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class Lumin extends Object {\r\n            constructor()\r\n            static iconModelFolderPath: string\r\n            static iconPortalFolderPath: string\r\n            static certificatePath: string\r\n            static signPackage: boolean\r\n            static isChannelApp: boolean\r\n            static versionCode: number\r\n            static versionName: string\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    namespace PlayerSettings {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class macOS extends Object {\r\n            constructor()\r\n            static buildNumber: string\r\n            static applicationCategoryType: string\r\n            static cameraUsageDescription: string\r\n            static microphoneUsageDescription: string\r\n            static bluetoothUsageDescription: string\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    namespace PlayerSettings {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class PS4 extends Object {\r\n            constructor()\r\n            static npTrophyPackPath: string\r\n            static npAgeRating: number\r\n            static npTitleSecret: string\r\n            static parentalLevel: number\r\n            static applicationParameter1: number\r\n            static applicationParameter2: number\r\n            static applicationParameter3: number\r\n            static applicationParameter4: number\r\n            static passcode: string\r\n            static monoEnv: string\r\n            static playerPrefsSupport: boolean\r\n            static restrictedAudioUsageRights: boolean\r\n            static useResolutionFallback: boolean\r\n            static contentID: string\r\n            static category: PlayerSettings.PS4.PS4AppCategory\r\n            static appType: number\r\n            static masterVersion: string\r\n            static appVersion: string\r\n            static remotePlayKeyAssignment: PlayerSettings.PS4.PS4RemotePlayKeyAssignment\r\n            static remotePlayKeyMappingDir: string\r\n            static playTogetherPlayerCount: number\r\n            static enterButtonAssignment: PlayerSettings.PS4.PS4EnterButtonAssignment\r\n            static paramSfxPath: string\r\n            static videoOutPixelFormat: number\r\n            static videoOutInitialWidth: number\r\n            static SdkOverride: string\r\n            static videoOutBaseModeInitialWidth: number\r\n            static videoOutReprojectionRate: number\r\n            static PronunciationXMLPath: string\r\n            static PronunciationSIGPath: string\r\n            static BackgroundImagePath: string\r\n            static StartupImagePath: string\r\n            static startupImagesFolder: string\r\n            static iconImagesFolder: string\r\n            static SaveDataImagePath: string\r\n            static BGMPath: string\r\n            static ShareFilePath: string\r\n            static ShareOverlayImagePath: string\r\n            static PrivacyGuardImagePath: string\r\n            static ExtraSceSysFile: string\r\n            static patchDayOne: boolean\r\n            static PatchPkgPath: string\r\n            static PatchLatestPkgPath: string\r\n            static PatchChangeinfoPath: string\r\n            static NPtitleDatPath: string\r\n            static pnSessions: boolean\r\n            static pnPresence: boolean\r\n            static pnFriends: boolean\r\n            static pnGameCustomData: boolean\r\n            static downloadDataSize: number\r\n            static garlicHeapSize: number\r\n            static proGarlicHeapSize: number\r\n            static reprojectionSupport: boolean\r\n            static useAudio3dBackend: boolean\r\n            static audio3dVirtualSpeakerCount: number\r\n            static scriptOptimizationLevel: number\r\n            static useLowGarlicFragmentationMode: boolean\r\n            static socialScreenEnabled: number\r\n            static attribUserManagement: boolean\r\n            static attribMoveSupport: boolean\r\n            static attrib3DSupport: boolean\r\n            static attribShareSupport: boolean\r\n            static attribExclusiveVR: boolean\r\n            static disableAutoHideSplash: boolean\r\n            static attribCpuUsage: number\r\n            static videoRecordingFeaturesUsed: boolean\r\n            static contentSearchFeaturesUsed: boolean\r\n            static attribEyeToEyeDistanceSettingVR: PlayerSettings.PS4.PlayStationVREyeToEyeDistanceSettings\r\n            static includedModules: Array<string>\r\n            static enableApplicationExit: boolean\r\n            static resetTempFolder: boolean\r\n            static playerPrefsMaxSize: number\r\n            static attribVROutputEnabled: boolean\r\n            static compatibilityPS5: boolean\r\n            static allowPS5Detection: boolean\r\n            static gpu800MHz: boolean\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings.PS4 {\r\n        enum PS4AppCategory {\r\n            Application = 0,\r\n            Patch = 1,\r\n            Remaster = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings.PS4 {\r\n        enum PS4RemotePlayKeyAssignment {\r\n            PatternA = 0,\r\n            PatternB = 1,\r\n            PatternC = 2,\r\n            PatternD = 3,\r\n            PatternE = 4,\r\n            PatternF = 5,\r\n            PatternG = 6,\r\n            PatternH = 7,\r\n            None = -1,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings.PS4 {\r\n        enum PS4EnterButtonAssignment {\r\n            CircleButton = 0,\r\n            CrossButton = 1,\r\n            SystemDefined = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings.PS4 {\r\n        enum PlayStationVREyeToEyeDistanceSettings {\r\n            PerUser = 0,\r\n            ForceDefault = 1,\r\n            DynamicModeAtRuntime = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    import { Sprite } from \"UnityEngine\";\r\n    namespace PlayerSettings {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class SplashScreenLogo extends ValueType {\r\n            constructor()\r\n            static Create(duration: number, logo: Sprite): PlayerSettings.SplashScreenLogo\r\n            static Create(duration: number): PlayerSettings.SplashScreenLogo\r\n            static Create(): PlayerSettings.SplashScreenLogo\r\n            static CreateWithUnityLogo(duration: number): PlayerSettings.SplashScreenLogo\r\n            static CreateWithUnityLogo(): PlayerSettings.SplashScreenLogo\r\n            logo: Sprite\r\n            static readonly unityLogo: Sprite\r\n            duration: number\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Sprite, Color } from \"UnityEngine\";\r\n    namespace PlayerSettings {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class SplashScreen extends Object {\r\n            constructor()\r\n            static animationMode: PlayerSettings.SplashScreen.AnimationMode\r\n            static animationBackgroundZoom: number\r\n            static animationLogoZoom: number\r\n            static background: Sprite\r\n            static backgroundPortrait: Sprite\r\n            static blurBackgroundImage: boolean\r\n            static backgroundColor: Color\r\n            static drawMode: PlayerSettings.SplashScreen.DrawMode\r\n            static logos: Array<PlayerSettings.SplashScreenLogo>\r\n            static overlayOpacity: number\r\n            static show: boolean\r\n            static showUnityLogo: boolean\r\n            static unityLogoStyle: PlayerSettings.SplashScreen.UnityLogoStyle\r\n            static showSplashAds: boolean\r\n            static adsAndroidGameId: string\r\n            static adsIosGameId: string\r\n            static showSplashAdsSlogan: boolean\r\n            static sloganHeight: number\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings.SplashScreen {\r\n        enum AnimationMode {\r\n            Static = 0,\r\n            Dolly = 1,\r\n            Custom = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings.SplashScreen {\r\n        enum DrawMode {\r\n            UnityLogoBelow = 0,\r\n            AllSequential = 1,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings.SplashScreen {\r\n        enum UnityLogoStyle {\r\n            DarkOnLight = 0,\r\n            LightOnDark = 1,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Texture2D } from \"UnityEngine\";\r\n    namespace PlayerSettings {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class Switch extends Object {\r\n            constructor()\r\n            static GetRatingAge(category: PlayerSettings.Switch.RatingCategories): number\r\n            static socketMemoryPoolSize: number\r\n            static socketAllocatorPoolSize: number\r\n            static socketConcurrencyLimit: number\r\n            static useSwitchCPUProfiler: boolean\r\n            static useSwitchGOLDLinker: boolean\r\n            static systemResourceMemory: number\r\n            static queueCommandMemory: number\r\n            static readonly defaultSwitchQueueCommandMemory: number\r\n            static readonly minimumSwitchQueueCommandMemory: number\r\n            static queueControlMemory: number\r\n            static readonly defaultSwitchQueueControlMemory: number\r\n            static readonly minimumSwitchQueueControlMemory: number\r\n            static queueComputeMemory: number\r\n            static readonly defaultSwitchQueueComputeMemory: number\r\n            static NVNShaderPoolsGranularity: number\r\n            static NVNDefaultPoolsGranularity: number\r\n            static NVNOtherPoolsGranularity: number\r\n            static NVNMaxPublicTextureIDCount: number\r\n            static NVNMaxPublicSamplerIDCount: number\r\n            static screenResolutionBehavior: PlayerSettings.Switch.ScreenResolutionBehavior\r\n            static NMETAOverride: string\r\n            static readonly NMETAOverrideFullPath: string\r\n            static applicationID: string\r\n            static nsoDependencies: string\r\n            static titleNames: Array<string>\r\n            static publisherNames: Array<string>\r\n            static icons: Array<Texture2D>\r\n            static smallIcons: Array<Texture2D>\r\n            static manualHTMLPath: string\r\n            static accessibleURLPath: string\r\n            static legalInformationPath: string\r\n            static mainThreadStackSize: number\r\n            static presenceGroupId: string\r\n            static logoHandling: PlayerSettings.Switch.LogoHandling\r\n            static releaseVersion: string\r\n            static displayVersion: string\r\n            static startupUserAccount: PlayerSettings.Switch.StartupUserAccount\r\n            static touchScreenUsage: PlayerSettings.Switch.TouchScreenUsage\r\n            static supportedLanguages: number\r\n            static logoType: PlayerSettings.Switch.LogoType\r\n            static applicationErrorCodeCategory: string\r\n            static userAccountSaveDataSize: number\r\n            static userAccountSaveDataJournalSize: number\r\n            static applicationAttribute: PlayerSettings.Switch.ApplicationAttribute\r\n            static cardSpecSize: number\r\n            static cardSpecClock: number\r\n            static ratingsMask: number\r\n            static localCommunicationIds: Array<string>\r\n            static isUnderParentalControl: boolean\r\n            static isScreenshotEnabled: boolean\r\n            static isVideoCapturingEnabled: boolean\r\n            static isRuntimeAddOnContentInstallEnabled: boolean\r\n            static isDataLossConfirmationEnabled: boolean\r\n            static isUserAccountLockEnabled: boolean\r\n            static supportedNpadStyles: PlayerSettings.Switch.SupportedNpadStyle\r\n            static ratingAgeArray: Array<number>\r\n            static nativeFsCacheSize: number\r\n            static isHoldTypeHorizontal: boolean\r\n            static supportedNpadCount: number\r\n            static socketConfigEnabled: boolean\r\n            static tcpInitialSendBufferSize: number\r\n            static tcpInitialReceiveBufferSize: number\r\n            static tcpAutoSendBufferSizeMax: number\r\n            static tcpAutoReceiveBufferSizeMax: number\r\n            static udpSendBufferSize: number\r\n            static udpReceiveBufferSize: number\r\n            static socketBufferEfficiency: number\r\n            static socketInitializeEnabled: boolean\r\n            static networkInterfaceManagerInitializeEnabled: boolean\r\n            static playerConnectionEnabled: boolean\r\n            static useNewStyleFilepaths: boolean\r\n            static switchUseMicroSleepForYield: boolean\r\n            static switchMicroSleepForYieldTime: number\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings.Switch {\r\n        enum ScreenResolutionBehavior {\r\n            Manual = 0,\r\n            OperationMode = 1,\r\n            PerformanceMode = 2,\r\n            Both = 3,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings.Switch {\r\n        enum Languages {\r\n            AmericanEnglish = 0,\r\n            BritishEnglish = 1,\r\n            Japanese = 2,\r\n            French = 3,\r\n            German = 4,\r\n            LatinAmericanSpanish = 5,\r\n            Spanish = 6,\r\n            Italian = 7,\r\n            Dutch = 8,\r\n            CanadianFrench = 9,\r\n            Portuguese = 10,\r\n            Russian = 11,\r\n            SimplifiedChinese = 12,\r\n            TraditionalChinese = 13,\r\n            Korean = 14,\r\n            BrazilianPortuguese = 15,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings.Switch {\r\n        enum StartupUserAccount {\r\n            None = 0,\r\n            Required = 1,\r\n            RequiredWithNetworkServiceAccountAvailable = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings.Switch {\r\n        enum TouchScreenUsage {\r\n            Supported = 0,\r\n            Required = 1,\r\n            None = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings.Switch {\r\n        enum LogoHandling {\r\n            Auto = 0,\r\n            Manual = 1,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings.Switch {\r\n        enum LogoType {\r\n            LicensedByNintendo = 0,\r\n            DistributedByNintendo = 1,\r\n            Nintendo = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings.Switch {\r\n        enum ApplicationAttribute {\r\n            None = 0,\r\n            Demo = 1,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings.Switch {\r\n        enum RatingCategories {\r\n            CERO = 0,\r\n            GRACGCRB = 1,\r\n            GSRMR = 2,\r\n            ESRB = 3,\r\n            ClassInd = 4,\r\n            USK = 5,\r\n            PEGI = 6,\r\n            PEGIPortugal = 7,\r\n            PEGIBBFC = 8,\r\n            Russian = 9,\r\n            ACB = 10,\r\n            OFLC = 11,\r\n            IARCGeneric = 12,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings.Switch {\r\n        enum SupportedNpadStyle {\r\n            FullKey = 2,\r\n            Handheld = 4,\r\n            JoyDual = 16,\r\n            JoyLeft = 256,\r\n            JoyRight = 65536,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    namespace PlayerSettings {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class tvOS extends Object {\r\n            constructor()\r\n            static sdkVersion: tvOSSdkVersion\r\n            static buildNumber: string\r\n            static targetOSVersionString: string\r\n            static requireExtendedGameController: boolean\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    namespace PlayerSettings {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class WebGL extends Object {\r\n            constructor()\r\n            static memorySize: number\r\n            static exceptionSupport: WebGLExceptionSupport\r\n            static dataCaching: boolean\r\n            static emscriptenArgs: string\r\n            static modulesDirectory: string\r\n            static template: string\r\n            static analyzeBuildSize: boolean\r\n            static useEmbeddedResources: boolean\r\n            static threadsSupport: boolean\r\n            static linkerTarget: WebGLLinkerTarget\r\n            static compressionFormat: WebGLCompressionFormat\r\n            static nameFilesAsHashes: boolean\r\n            static debugSymbols: boolean\r\n            static decompressionFallback: boolean\r\n            static wasmArithmeticExceptions: WebGLWasmArithmeticExceptions\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings {\r\n        enum WSAApplicationShowName {\r\n            NotSet = 0,\r\n            AllLogos = 1,\r\n            NoLogos = 2,\r\n            StandardLogoOnly = 3,\r\n            WideLogoOnly = 4,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings {\r\n        enum WSADefaultTileSize {\r\n            NotSet = 0,\r\n            Medium = 1,\r\n            Wide = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings {\r\n        enum WSAApplicationForegroundText {\r\n            Light = 1,\r\n            Dark = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings {\r\n        enum WSACapability {\r\n            EnterpriseAuthentication = 0,\r\n            InternetClient = 1,\r\n            InternetClientServer = 2,\r\n            MusicLibrary = 3,\r\n            PicturesLibrary = 4,\r\n            PrivateNetworkClientServer = 5,\r\n            RemovableStorage = 6,\r\n            SharedUserCertificates = 7,\r\n            VideosLibrary = 8,\r\n            WebCam = 9,\r\n            Proximity = 10,\r\n            Microphone = 11,\r\n            Location = 12,\r\n            HumanInterfaceDevice = 13,\r\n            AllJoyn = 14,\r\n            BlockedChatMessages = 15,\r\n            Chat = 16,\r\n            CodeGeneration = 17,\r\n            Objects3D = 18,\r\n            PhoneCall = 19,\r\n            UserAccountInformation = 20,\r\n            VoipCall = 21,\r\n            Bluetooth = 22,\r\n            SpatialPerception = 23,\r\n            InputInjectionBrokered = 24,\r\n            Appointments = 25,\r\n            BackgroundMediaPlayback = 26,\r\n            Contacts = 27,\r\n            LowLevelDevices = 28,\r\n            OfflineMapsManagement = 29,\r\n            PhoneCallHistoryPublic = 30,\r\n            PointOfService = 31,\r\n            RecordedCallsFolder = 32,\r\n            RemoteSystem = 33,\r\n            SystemManagement = 34,\r\n            UserDataTasks = 35,\r\n            UserNotificationListener = 36,\r\n            GazeInput = 37,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings {\r\n        enum WSATargetFamily {\r\n            Desktop = 0,\r\n            Mobile = 1,\r\n            Xbox = 2,\r\n            Holographic = 3,\r\n            Team = 4,\r\n            IoT = 5,\r\n            IoTHeadless = 6,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings {\r\n        enum WSAImageScale {\r\n            Target16 = 16,\r\n            Target24 = 24,\r\n            Target32 = 32,\r\n            Target48 = 48,\r\n            _80 = 80,\r\n            _100 = 100,\r\n            _125 = 125,\r\n            _140 = 140,\r\n            _150 = 150,\r\n            _180 = 180,\r\n            _200 = 200,\r\n            _240 = 240,\r\n            Target256 = 256,\r\n            _400 = 400,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings {\r\n        enum WSAImageType {\r\n            PackageLogo = 1,\r\n            SplashScreenImage = 2,\r\n            UWPSquare44x44Logo = 31,\r\n            UWPSquare71x71Logo = 32,\r\n            UWPSquare150x150Logo = 33,\r\n            UWPSquare310x310Logo = 34,\r\n            UWPWide310x150Logo = 35,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PlayerSettings {\r\n        enum WSAInputSource {\r\n            CoreWindow = 0,\r\n            IndependentInputSource = 1,\r\n            SwapChainPanel = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    namespace PlayerSettings {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class WSASupportedFileType extends ValueType {\r\n            constructor()\r\n            contentType: string\r\n            fileType: string\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array } from \"System\";\r\n    namespace PlayerSettings {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class WSAFileTypeAssociations extends ValueType {\r\n            constructor()\r\n            name: string\r\n            supportedFileTypes: Array<PlayerSettings.WSASupportedFileType>\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, DateTime, ValueType } from \"System\";\r\n    import { Color } from \"UnityEngine\";\r\n    namespace PlayerSettings {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class WSA extends Object {\r\n            constructor()\r\n            static SetCertificate(path: string, password: string): boolean\r\n            static GetVisualAssetsImage(type: PlayerSettings.WSAImageType, scale: PlayerSettings.WSAImageScale): string\r\n            static SetVisualAssetsImage(image: string, type: PlayerSettings.WSAImageType, scale: PlayerSettings.WSAImageScale): void\r\n            static SetCapability(capability: PlayerSettings.WSACapability, value: boolean): void\r\n            static GetCapability(capability: PlayerSettings.WSACapability): boolean\r\n            static SetTargetDeviceFamily(family: PlayerSettings.WSATargetFamily, value: boolean): void\r\n            static GetTargetDeviceFamily(family: PlayerSettings.WSATargetFamily): boolean\r\n            static transparentSwapchain: boolean\r\n            static packageName: string\r\n            static packageLogo: string\r\n            static readonly certificatePath: string\r\n            static readonly certificateSubject: string\r\n            static readonly certificateIssuer: string\r\n            static applicationDescription: string\r\n            static tileShortName: string\r\n            static tileShowName: PlayerSettings.WSAApplicationShowName\r\n            static mediumTileShowName: boolean\r\n            static largeTileShowName: boolean\r\n            static wideTileShowName: boolean\r\n            static defaultTileSize: PlayerSettings.WSADefaultTileSize\r\n            static tileForegroundText: PlayerSettings.WSAApplicationForegroundText\r\n            static tileBackgroundColor: Color\r\n            static inputSource: PlayerSettings.WSAInputSource\r\n            static supportStreamingInstall: boolean\r\n            static lastRequiredScene: number\r\n            static packageVersion: any\r\n            static readonly certificateNotAfter: jsb.Nullable<DateTime>\r\n            static splashScreenBackgroundColor: jsb.Nullable<Color>\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    namespace PlayerSettings.WSA {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        abstract class Declarations extends Object {\r\n            static protocolName: string\r\n            static fileTypeAssociations: PlayerSettings.WSAFileTypeAssociations\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    namespace PlayerSettings {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class XboxOne extends Object {\r\n            constructor()\r\n            static SetCapability(capability: string, value: boolean): void\r\n            static GetCapability(capability: string): boolean\r\n            static SetSupportedLanguage(language: string, enabled: boolean): void\r\n            static GetSupportedLanguage(language: string): boolean\r\n            static RemoveSocketDefinition(name: string): void\r\n            static SetSocketDefinition(name: string, port: string, protocol: number, usages: Array<number>, templateName: string, sessionRequirment: number, deviceUsages: Array<number>): void\r\n            static GetSocketDefinition(name: string, port: jsb.Out<string>, protocol: jsb.Out<number>, usages: jsb.Out<Array<number>>, templateName: jsb.Out<string>, sessionRequirment: jsb.Out<number>, deviceUsages: jsb.Out<Array<number>>): void\r\n            static RemoveAllowedProductId(id: string): void\r\n            static AddAllowedProductId(id: string): boolean\r\n            static UpdateAllowedProductId(idx: number, id: string): void\r\n            static XTitleMemory: number\r\n            static defaultLoggingLevel: XboxOneLoggingLevel\r\n            static ProductId: string\r\n            static UpdateKey: string\r\n            static ContentId: string\r\n            static TitleId: string\r\n            static SCID: string\r\n            static EnableVariableGPU: boolean\r\n            static PresentImmediateThreshold: number\r\n            static Enable7thCore: boolean\r\n            static DisableKinectGpuReservation: boolean\r\n            static EnablePIXSampling: boolean\r\n            static GameOsOverridePath: string\r\n            static PackagingOverridePath: string\r\n            static PackagingEncryption: XboxOneEncryptionLevel\r\n            static PackageUpdateGranularity: XboxOnePackageUpdateGranularity\r\n            static OverrideIdentityName: string\r\n            static OverrideIdentityPublisher: string\r\n            static AppManifestOverridePath: string\r\n            static IsContentPackage: boolean\r\n            static EnhancedXboxCompatibilityMode: boolean\r\n            static Version: string\r\n            static Description: string\r\n            static readonly SocketNames: Array<string>\r\n            static readonly AllowedProductIds: Array<string>\r\n            static PersistentLocalStorageSize: number\r\n            static EnableTypeOptimization: boolean\r\n            static monoLoggingLevel: number\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** This property allows you to specify the devices on which your Android application is allowed to run.\r\n     */\r\n    enum AndroidTargetDevices {\r\n        /** The Android build is allowed to run on all target devices.\r\n         */\r\n        AllDevices = 0,\r\n        /** The Android build is only allowed to run on Android phones, tablets, and TV devices, not on any type of Chrome OS device.\r\n         */\r\n        PhonesTabletsAndTVDevicesOnly = 1,\r\n        /** The Android build is only allowed to run on Chrome OS devices.\r\n         */\r\n        ChromeOSDevicesOnly = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Supported iOS SDK versions.\r\n     */\r\n    enum iOSSdkVersion {\r\n        /** Device SDK.\r\n         */\r\n        DeviceSDK = 988,\r\n        /** Simulator SDK.\r\n         */\r\n        SimulatorSDK = 989,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Target iOS device.\r\n     */\r\n    enum iOSTargetDevice {\r\n        /** iPhone/iPod Only.\r\n         */\r\n        iPhoneOnly = 0,\r\n        /** iPad Only.\r\n         */\r\n        iPadOnly = 1,\r\n        /** Universal : iPhone/iPod + iPad.\r\n         */\r\n        iPhoneAndiPad = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Activity Indicator on loading.\r\n     */\r\n    enum iOSShowActivityIndicatorOnLoading {\r\n        /** White Large.\r\n         */\r\n        WhiteLarge = 0,\r\n        /** White.\r\n         */\r\n        White = 1,\r\n        /** Gray.\r\n         */\r\n        Gray = 2,\r\n        /** Don't Show.\r\n         */\r\n        DontShow = -1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** iOS status bar style.\r\n     */\r\n    enum iOSStatusBarStyle {\r\n        /** Default.\r\n         */\r\n        Default = 0,\r\n        /** A light status bar, intended for use on dark backgrounds.\r\n         */\r\n        LightContent = 1,\r\n        BlackTranslucent = -1,\r\n        BlackOpaque = -1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Application behavior when entering background.\r\n     */\r\n    enum iOSAppInBackgroundBehavior {\r\n        /** Application should suspend execution when entering background.\r\n         */\r\n        Suspend = 0,\r\n        /** Application should exit when entering background.\r\n         */\r\n        Exit = 1,\r\n        /** Custom background behavior, see iOSBackgroundMode for specific background modes.\r\n         */\r\n        Custom = -1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Background modes supported by the application corresponding to project settings in Xcode.\r\n     */\r\n    enum iOSBackgroundMode {\r\n        /** No background modes supported.\r\n         */\r\n        None = 0,\r\n        /** Audio, AirPlay and Picture in Picture.\r\n         */\r\n        Audio = 1,\r\n        /** Location updates.\r\n         */\r\n        Location = 2,\r\n        /** Voice over IP.\r\n         */\r\n        VOIP = 4,\r\n        /** Newsstand downloads.\r\n         */\r\n        NewsstandContent = 8,\r\n        /** External accessory communication.\r\n         */\r\n        ExternalAccessory = 16,\r\n        /** Uses Bluetooth LE accessories.\r\n         */\r\n        BluetoothCentral = 32,\r\n        /** Acts as a Bluetooth LE accessory.\r\n         */\r\n        BluetoothPeripheral = 64,\r\n        /** Background fetch.\r\n         */\r\n        Fetch = 128,\r\n        /** Remote notifications.\r\n         */\r\n        RemoteNotification = 256,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** iOS launch screen settings.\r\n     */\r\n    enum iOSLaunchScreenImageType {\r\n        /** Portrait oriented launch screen image on the iPhone.\r\n         */\r\n        iPhonePortraitImage = 0,\r\n        /** Landscape oriented launch screen image on the iPhone.\r\n         */\r\n        iPhoneLandscapeImage = 1,\r\n        /** Launch screen image on the iPad.\r\n         */\r\n        iPadImage = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** iOS launch screen settings.\r\n     */\r\n    enum iOSLaunchScreenType {\r\n        /** Use the default launch screen (dark blue background).\r\n         */\r\n        Default = 0,\r\n        /** Use a custom launch screen image specified in the iOS Player Settings or with PlayerSettings.iOS.SetLaunchScreenImage which will be scaled across the entire screen.\r\n         */\r\n        ImageAndBackgroundRelative = 1,\r\n        /** Use a specified custom Interface Builder (.xib) file in Player Settings.\r\n         */\r\n        CustomXib = 2,\r\n        /** Generate the Xcode project without any custom launch screens.\r\n         */\r\n        None = 3,\r\n        /** Use a custom launch screen image specified in the iOS Player Settings or with PlayerSettings.iOS.SetLaunchScreenImage and use its original dimensions.\r\n         */\r\n        ImageAndBackgroundConstant = 4,\r\n        /** Use a specified custom Storyboard (.storyboard) file in Player Settings.\r\n         */\r\n        CustomStoryboard = 5,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** The type of the iOS provisioning profile if manual signing is used.\r\n     */\r\n    enum ProvisioningProfileType {\r\n        /** The provisioning profile type will be determined automatically when building the Xcode project.\r\n         */\r\n        Automatic = 0,\r\n        /** Development provisioning profiles are used to install development apps on test devices.\r\n         */\r\n        Development = 1,\r\n        /** Distribution provisioning profiles can be used when uploading the app to the App Store or for Ad Hoc and in house distribution.\r\n         */\r\n        Distribution = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** A device requirement description used for configuration of App Slicing.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class iOSDeviceRequirement extends Object {\r\n        constructor()\r\n        /** The values of the device requirement description.\r\n         */\r\n        readonly values: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Supported tvOS SDK versions.\r\n     */\r\n    enum tvOSSdkVersion {\r\n        /** Device SDK.\r\n         */\r\n        Device = 0,\r\n        /** Simulator SDK.\r\n         */\r\n        Simulator = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Options for Exception support in WebGL.\r\n     */\r\n    enum WebGLExceptionSupport {\r\n        /** Disable exception support.\r\n         */\r\n        None = 0,\r\n        /** Enable throw support.\r\n         */\r\n        ExplicitlyThrownExceptionsOnly = 1,\r\n        /** Enable exception support for all exceptions, without stack trace information.\r\n         */\r\n        FullWithoutStacktrace = 2,\r\n        /** Enable exception support for all exceptions, including stack trace information.\r\n         */\r\n        FullWithStacktrace = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** An enum containing different compression types.\r\n     */\r\n    enum WebGLCompressionFormat {\r\n        /** WebGL resources are stored using Brotli compression.\r\n         */\r\n        Brotli = 0,\r\n        /** WebGL resources are stored using Gzip compression.\r\n         */\r\n        Gzip = 1,\r\n        /** WebGL resources are uncompressed.\r\n         */\r\n        Disabled = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** The build format options available when building to WebGL.\r\n     */\r\n    enum WebGLLinkerTarget {\r\n        /** Only asm.js output will be generated. This setting has been deprecated.\r\n         */\r\n        Asm = 0,\r\n        /** Only WebAssembly output will be generated. This will require a browser with WebAssembly support to run the generated content.\r\n         */\r\n        Wasm = 1,\r\n        /** Both asm.js and WebAssembly output will be generated. The WebAssembly version of the generated content will be used if supported by the browser, otherwise, the asm.js version will be used. This setting has been deprecated.\r\n         */\r\n        Both = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** An enum containing different trapping modes for WebAssembly code.\r\n     */\r\n    enum WebGLWasmArithmeticExceptions {\r\n        /** WebAssembly code will throw an exception on things like division by zero, rounding a very large float to an int, and so forth.\r\n         */\r\n        Throw = 0,\r\n        /** This mode avoids traps by clamping floating point value to a reasonable range when performing arithmetic operations.\r\n         */\r\n        Ignore = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum XboxOneEncryptionLevel {\r\n        None = 0,\r\n        DevkitCompatible = 1,\r\n        FullEncryption = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum XboxOnePackageUpdateGranularity {\r\n        Chunk = 1,\r\n        File = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum XboxOneLoggingLevel {\r\n        ErrorsOnly = 1,\r\n        WarningsAndErrors = 2,\r\n        AllLogging = 4,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { GameObject } from \"UnityEngine\";\r\n    import { Array, ValueType } from \"System\";\r\n    /** Manages Scene Visibility in the editor.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SceneVisibilityManager extends ScriptableSingleton<SceneVisibilityManager> {\r\n        constructor()\r\n        HideAll(): void\r\n        DisableAllPicking(): void\r\n        /** Shows a GameObject, or an array of GameObjects, and its descendants.\r\n         * @param gameObject GameObject to show.\r\n         * @param gameObjects Array of GameObjects to show.\r\n         * @param includeDescendants Whether to include descendants.\r\n         */\r\n        Show(gameObject: GameObject, includeDescendants: boolean): void\r\n        /** Shows a GameObject, or an array of GameObjects, and its descendants.\r\n         * @param gameObject GameObject to show.\r\n         * @param gameObjects Array of GameObjects to show.\r\n         * @param includeDescendants Whether to include descendants.\r\n         */\r\n        Show(gameObjects: Array<GameObject>, includeDescendants: boolean): void\r\n        /** Shows all GameObjects in scene.\r\n         * @param scene Scene containing GameObjects to show.\r\n         */\r\n        Show(scene: any): void\r\n        /** Hides a GameObject, or an Array of GameObjects,  and their descendants.\r\n         * @param gameObject GameObject to hide.\r\n         * @param gameObjects Array of GameObjects to hide.\r\n         * @param includeDescendants Whether to also hide descendants.\r\n         */\r\n        Hide(gameObject: GameObject, includeDescendants: boolean): void\r\n        /** Hides a GameObject, or an Array of GameObjects,  and their descendants.\r\n         * @param gameObject GameObject to hide.\r\n         * @param gameObjects Array of GameObjects to hide.\r\n         * @param includeDescendants Whether to also hide descendants.\r\n         */\r\n        Hide(gameObjects: Array<GameObject>, includeDescendants: boolean): void\r\n        /** Hides all GameObjects in a scene.\r\n         * @param scene Scene containing GameObjects to hide.\r\n         */\r\n        Hide(scene: any): void\r\n        /** Disables picking on a GameObject, or an Array of GameObjects, and their descendants.\r\n         * @param gameObject GameObject on which to disable picking.\r\n         * @param includeDescendants Whether to include descendants.\r\n         * @param gameObjects Array of GameObjects on which to disable picking.\r\n         */\r\n        DisablePicking(gameObject: GameObject, includeDescendants: boolean): void\r\n        /** Disables picking on a GameObject, or an Array of GameObjects, and their descendants.\r\n         * @param gameObject GameObject on which to disable picking.\r\n         * @param includeDescendants Whether to include descendants.\r\n         * @param gameObjects Array of GameObjects on which to disable picking.\r\n         */\r\n        DisablePicking(gameObjects: Array<GameObject>, includeDescendants: boolean): void\r\n        /** Disables picking on all GameObjects in a Scene.\r\n         * @param scene Scene containing GameObjects on which to disable picking.\r\n         */\r\n        DisablePicking(scene: any): void\r\n        /** Enables picking on a GameObject, or an array of GameObjects, and its descendants.\r\n         * @param includeDescendants Whether to include descendants.\r\n         * @param gameObject GameObject on which to enable picking.\r\n         * @param gameObjects Array of GameObjects on which to enable picking.\r\n         */\r\n        EnablePicking(gameObject: GameObject, includeDescendants: boolean): void\r\n        /** Enables picking on a GameObject, or an array of GameObjects, and its descendants.\r\n         * @param includeDescendants Whether to include descendants.\r\n         * @param gameObject GameObject on which to enable picking.\r\n         * @param gameObjects Array of GameObjects on which to enable picking.\r\n         */\r\n        EnablePicking(gameObjects: Array<GameObject>, includeDescendants: boolean): void\r\n        /** Enables picking on all GameObjects in a Scene.\r\n         * @param scene Scene containing GameObjects on which to enable picking.\r\n         */\r\n        EnablePicking(scene: any): void\r\n        ShowAll(): void\r\n        EnableAllPicking(): void\r\n        /** Checks the hidden state of a GameObject and, optionally, its descendants.\r\n         * @param gameObject GameObject to check.\r\n         * @param includeDescendants Specify true to check the GameObject and all its descendants. Set to false to check the GameObject.\r\n         * @returns When includeDescendants is true, this method returns true when the GameObject and all its descendants are hidden. When includeDescendants is false, this method returns true when the GameObject is hidden. \r\n         */\r\n        IsHidden(gameObject: GameObject, includeDescendants: boolean): boolean\r\n        IsHidden(scene: any): boolean\r\n        /** Checks the picking state of a GameObject and, optionally, its descendants.\r\n         * @param gameObject GameObject to check.\r\n         * @param includeDescendants Specify true to check the GameObject and all its descendants. Set to false to check the GameObject.\r\n         * @returns When includeDescendants is true, this method returns true when the GameObject and all its descendants have picking disabled. When includeDescendants is false, this method returns true when the GameObject has picking disabled. \r\n         */\r\n        IsPickingDisabled(gameObject: GameObject, includeDescendants: boolean): boolean\r\n        IsPickingDisabled(scene: any): boolean\r\n        /** Checks whether root GameObjects, and all their descendants, are hidden in a Scene.\r\n         * @param scene Scene to check.\r\n         * @returns Returns true if all root GameObjects of the Scene and all their descendants are hidden. \r\n         */\r\n        AreAllDescendantsHidden(scene: any): boolean\r\n        /** Checks whether all the descendants of a GameObject are hidden.\r\n         * @param gameObject GameObject to check.\r\n         * @returns Returns true if all descendants are hidden. \r\n         */\r\n        AreAllDescendantsHidden(gameObject: GameObject): boolean\r\n        /** Checks whether all the descendants of a GameObject have picking disabled.\r\n         * @param scene Scene to check.\r\n         * @returns Returns true if all descendants have picking disabled. \r\n         */\r\n        IsPickingDisabledOnAllDescendants(scene: any): boolean\r\n        /** Checks whether root GameObjects, and all their descendants, have picking disabled in a scene.\r\n         * @param gameObject GameObject to check.\r\n         * @returns Returns true if all root GameObjects of the Scene and all their descendants have picking disabled. \r\n         */\r\n        IsPickingDisabledOnAllDescendants(gameObject: GameObject): boolean\r\n        /** Checks whether any descendants are hidden.\r\n         * @param scene Scene to check.\r\n         * @returns Returns true when at least one hidden descendant is found. \r\n         */\r\n        AreAnyDescendantsHidden(scene: any): boolean\r\n        /** Checks whether any descendants have picking disabled.\r\n         * @param scene Scene to check.\r\n         * @returns Returns true when at least one descendant with picking disabled is found. \r\n         */\r\n        IsPickingDisabledOnAnyDescendant(scene: any): boolean\r\n        /** Isolates a GameObject and its descendants.\r\n         * @param gameObject GameObject to isolate.\r\n         * @param includeDescendants Whether to include descendants.\r\n         */\r\n        Isolate(gameObject: GameObject, includeDescendants: boolean): void\r\n        /** Isolates an Array of GameObjects and their descendants.\r\n         * @param gameObjects Array of GameObjects to isolate.\r\n         * @param includeDescendants Whether to include descendants.\r\n         */\r\n        Isolate(gameObjects: Array<GameObject>, includeDescendants: boolean): void\r\n        /** Toggles the visible state of a GameObject.\r\n         * @param gameObject GameObject on which to toggle visibility.\r\n         * @param includeDescendants Whether to include descendants.\r\n         */\r\n        ToggleVisibility(gameObject: GameObject, includeDescendants: boolean): void\r\n        /** Toggles the picking ability of a GameObject.\r\n         * @param gameObject GameObject on which to toggle picking ability.\r\n         * @param includeDescendants Whether to include descendants.\r\n         */\r\n        TogglePicking(gameObject: GameObject, includeDescendants: boolean): void\r\n        /** Checks whether all the descendants are visible.\r\n         * @param gameObject GameObject to check.\r\n         * @returns Returns true if all descendants of the GameObject are visible. \r\n         */\r\n        AreAllDescendantsVisible(gameObject: GameObject): boolean\r\n        /** Checks whether all the descendants are pickable.\r\n         * @param gameObject GameObject on which to do the check.\r\n         * @returns Returns true if all descendants of the GameObject are pickable. \r\n         */\r\n        IsPickingEnabledOnAllDescendants(gameObject: GameObject): boolean\r\n        IsCurrentStageIsolated(): boolean\r\n        ExitIsolation(): void\r\n        static visibilityChanged(op: \"add\" | \"remove\", fn: () => void): void\r\n        static pickingChanged(op: \"add\" | \"remove\", fn: () => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ScriptableObject } from \"UnityEngine\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ScriptableSingleton_SceneVisibilityManager extends ScriptableObject implements ScriptableSingleton<SceneVisibilityManager> {\r\n        protected constructor()\r\n        static readonly instance: SceneVisibilityManager\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ScriptableObject } from \"UnityEngine\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ScriptableSingleton<T> extends ScriptableObject {\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Derive from this class to create an editor wizard.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ScriptableWizard extends EditorWindow {\r\n        constructor()\r\n        /** Creates a wizard.\r\n         * @param title The title shown at the top of the wizard window.\r\n         * @param klass The class implementing the wizard. It has to derive from ScriptableWizard.\r\n         * @param createButtonName The text shown on the create button.\r\n         * @param otherButtonName The text shown on the optional other button. Leave this parameter out to leave the button out.\r\n         * @returns The wizard. \r\n         */\r\n        static DisplayWizard(title: string, klass: any, createButtonName: string, otherButtonName: string): ScriptableWizard\r\n        static DisplayWizard(title: string, klass: any, createButtonName: string): ScriptableWizard\r\n        static DisplayWizard(title: string, klass: any): ScriptableWizard\r\n        /** Allows you to set the help text of the wizard.\r\n         */\r\n        helpString: string\r\n        /** Allows you to set the error text of the wizard.\r\n         */\r\n        errorString: string\r\n        /** Allows you to set the text shown on the create button of the wizard.\r\n         */\r\n        createButtonName: string\r\n        /** Allows you to set the text shown on the optional other button of the wizard. Leave this parameter out to leave the button out.\r\n         */\r\n        otherButtonName: string\r\n        /** Allows you to enable and disable the wizard create button, so that the user can not click it.\r\n         */\r\n        isValid: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** SelectionMode can be used to tweak the selection returned by Selection.GetTransforms.\r\n     */\r\n    enum SelectionMode {\r\n        /** Return the whole selection.\r\n         */\r\n        Unfiltered = 0,\r\n        /** Only return the topmost selected transform. A selected child of another selected transform will be filtered out.\r\n         */\r\n        TopLevel = 1,\r\n        /** Return the selection and all child transforms of the selection.\r\n         */\r\n        Deep = 2,\r\n        /** Excludes any Prefabs from the selection.\r\n         */\r\n        ExcludePrefab = 4,\r\n        Editable = 8,\r\n        OnlyUserModifiable = 8,\r\n        /** Only return objects that are assets in the Asset directory.\r\n         */\r\n        Assets = 16,\r\n        /** If the selection contains folders, also include all assets and subfolders within that folder in the file hierarchy.\r\n         */\r\n        DeepAssets = 32,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Transform, GameObject, Object as Object1 } from \"UnityEngine\";\r\n    /** Access to the selection in the editor.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class Selection extends Object {\r\n        constructor()\r\n        /** Returns whether an object is contained in the current selection.\r\n         */\r\n        static Contains(instanceID: number): boolean\r\n        /** Returns whether an object is contained in the current selection.\r\n         */\r\n        static Contains(obj: Object1): boolean\r\n        /** Selects an object with a context.\r\n         * @param obj Object being selected (will be equal activeObject).\r\n         * @param context Context object.\r\n         */\r\n        static SetActiveObjectWithContext(obj: Object1, context: Object1): void\r\n        /** Allows for fine grained control of the selection type using the SelectionMode bitmask.\r\n         * @param mode Options for refining the selection.\r\n         */\r\n        static GetTransforms(mode: SelectionMode): Array<Transform>\r\n        /** Returns the current selection filtered by type and mode.\r\n         * @param type Only objects of this type will be retrieved.\r\n         * @param mode Further options to refine the selection.\r\n         */\r\n        static GetFiltered(type: any, mode: SelectionMode): Array<Object1>\r\n        /** Returns the top level selection, excluding Prefabs.\r\n         */\r\n        static readonly transforms: Array<Transform>\r\n        /** Returns the active transform. (The one shown in the inspector).\r\n         */\r\n        static activeTransform: Transform\r\n        /** Returns the actual game object selection. Includes Prefabs, non-modifiable objects.\r\n         */\r\n        static readonly gameObjects: Array<GameObject>\r\n        /** Returns the active game object. (The one shown in the inspector).\r\n         */\r\n        static activeGameObject: GameObject\r\n        /** Returns the actual object selection. Includes Prefabs, non-modifiable objects.\r\n         */\r\n        static activeObject: Object1\r\n        /** Returns the current context object, as was set via SetActiveObjectWithContext.\r\n         */\r\n        static readonly activeContext: Object1\r\n        /** Returns the instanceID of the actual object selection. Includes Prefabs, non-modifiable objects.\r\n         */\r\n        static activeInstanceID: number\r\n        /** The actual unfiltered selection from the Scene.\r\n         */\r\n        static objects: Array<Object1>\r\n        /** The actual unfiltered selection from the Scene returned as instance ids instead of objects.\r\n         */\r\n        static instanceIDs: Array<number>\r\n        /** Returns the guids of the selected assets.\r\n         */\r\n        static readonly assetGUIDs: Array<string>\r\n        /** Returns the number of objects in the Selection.\r\n         */\r\n        static readonly count: number\r\n        static selectionChanged(op: \"get\"): () => void\r\n        static selectionChanged(op: \"add\" | \"remove\" | \"set\", fn?: () => void): void\r\n        static selectionChanged(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => void): () => void | void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Sets the preprocessor that Unity uses to compile this shader.\r\n     */\r\n    enum PreprocessorOverride {\r\n        /** Use the preprocessor defined in your Project's Editor Settings.\r\n         */\r\n        UseProjectSettings = 0,\r\n        /** Use the platform compilers' preprocessors.\r\n         */\r\n        ForcePlatformPreprocessor = 1,\r\n        /** Use the Caching Shader Preprocessor.\r\n         */\r\n        ForceCachingPreprocessor = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** Contains the following information about a shader:\n-If the shader has compilation errors.\n-If the shader is supported on the currently selected platform.\n-The name of the shader.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ShaderInfo extends ValueType {\r\n        constructor()\r\n        /** The name of the shader.\r\n         */\r\n        readonly name: string\r\n        /** True if the shader is supported on the currently selected platform.\r\n         */\r\n        readonly supported: boolean\r\n        /** True if the shader has compilation errors.\r\n         */\r\n        readonly hasErrors: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Enum, Object } from \"System\";\r\n    /** Contains information about messages generated by Unity's Shader Compiler.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ShaderMessage extends ValueType {\r\n        constructor(msg: string, sev: any)\r\n        /** Compares two ShaderMessage on an element-by-element basis.\r\n         * @returns True if all fields of the message are equal, otherwise false. \r\n         */\r\n        Equals(other: ShaderMessage): boolean\r\n        /** Compares two ShaderMessage on an element-by-element basis.\r\n         * @returns True if all fields of the message are equal, otherwise false. \r\n         */\r\n        Equals(obj: Object): boolean\r\n        GetHashCode(): number\r\n        static op_Equality(left: ShaderMessage, right: ShaderMessage): boolean\r\n        static op_Inequality(left: ShaderMessage, right: ShaderMessage): boolean\r\n        // js_op_overloading: static ==(left: ShaderMessage, right: ShaderMessage): boolean\r\n        /** The message returned by the Unity Shader Compiler.\r\n         */\r\n        readonly message: string\r\n        /** An (optional) detailed message returned from the Unity Shader Compiler.\r\n         */\r\n        readonly messageDetails: string\r\n        /** The source file where the shader message was found.\r\n         */\r\n        readonly file: string\r\n        /** The line of code where the shader message was found.\r\n         */\r\n        readonly line: number\r\n        /** The specific platform where the Unity Shader Compiler discovered the message.\r\n         */\r\n        readonly platform: any\r\n        /** Indicates the severity of the message returned from the Unity Shader Compiler.\r\n         */\r\n        readonly severity: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace ShaderUtil {\r\n        enum ShaderPropertyType {\r\n            Color = 0,\r\n            Vector = 1,\r\n            Float = 2,\r\n            Range = 3,\r\n            TexEnv = 4,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Object as Object1 } from \"UnityEngine\";\r\n    /** This class describes a shader.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ShaderData extends Object {\r\n        /** Get a subshader.\r\n         * @param index The index of the subshader.\r\n         * @returns The associated subshader or null if none exists. \r\n         */\r\n        GetSubshader(index: number): ShaderData.Subshader\r\n        protected constructor()\r\n        /** Returns the index of the active subshader or -1 if none is currently active.\r\n         */\r\n        readonly ActiveSubshaderIndex: number\r\n        /** The number of subshaders used by this shader.\r\n         */\r\n        readonly SubshaderCount: number\r\n        /** The shader attached to this data set.\r\n         */\r\n        readonly SourceShader: any\r\n        /** Returns the active subshader or null if none is currently active.\r\n         */\r\n        readonly ActiveSubshader: ShaderData.Subshader\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    namespace ShaderData {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class Subshader extends Object {\r\n            GetPass(passIndex: number): ShaderData.Pass\r\n            protected constructor()\r\n            readonly PassCount: number\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Enum, Array } from \"System\";\r\n    namespace ShaderData {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class Pass extends Object {\r\n            HasShaderStage(shaderType: any): boolean\r\n            CompileVariant(shaderType: any, keywords: Array<string>, shaderCompilerPlatform: any, buildTarget: BuildTarget, platformKeywords: Array<any>, tier: any): ShaderData.VariantCompileInfo\r\n            CompileVariant(shaderType: any, keywords: Array<string>, shaderCompilerPlatform: any, buildTarget: BuildTarget, tier: any): ShaderData.VariantCompileInfo\r\n            CompileVariant(shaderType: any, keywords: Array<string>, shaderCompilerPlatform: any, buildTarget: BuildTarget, platformKeywords: Array<any>): ShaderData.VariantCompileInfo\r\n            CompileVariant(shaderType: any, keywords: Array<string>, shaderCompilerPlatform: any, buildTarget: BuildTarget): ShaderData.VariantCompileInfo\r\n            PreprocessVariant(shaderType: any, keywords: Array<string>, shaderCompilerPlatform: any, buildTarget: BuildTarget, platformKeywords: Array<any>, tier: any, stripLineDirectives: boolean): ShaderData.PreprocessedVariant\r\n            PreprocessVariant(shaderType: any, keywords: Array<string>, shaderCompilerPlatform: any, buildTarget: BuildTarget, tier: any, stripLineDirectives: boolean): ShaderData.PreprocessedVariant\r\n            PreprocessVariant(shaderType: any, keywords: Array<string>, shaderCompilerPlatform: any, buildTarget: BuildTarget, platformKeywords: Array<any>, stripLineDirectives: boolean): ShaderData.PreprocessedVariant\r\n            PreprocessVariant(shaderType: any, keywords: Array<string>, shaderCompilerPlatform: any, buildTarget: BuildTarget, stripLineDirectives: boolean): ShaderData.PreprocessedVariant\r\n            protected constructor()\r\n            readonly SourceCode: string\r\n            readonly Name: string\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array } from \"System\";\r\n    namespace ShaderData {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class PreprocessedVariant extends ValueType {\r\n            constructor()\r\n            readonly Success: boolean\r\n            readonly Messages: Array<ShaderMessage>\r\n            readonly PreprocessedCode: string\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array, Enum } from \"System\";\r\n    namespace ShaderData {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class VariantCompileInfo extends ValueType {\r\n            constructor()\r\n            Success: boolean\r\n            Messages: Array<ShaderMessage>\r\n            ShaderData: Array<jsb.byte>\r\n            Attributes: Array<any>\r\n            ConstantBuffers: Array<ShaderData.ConstantBufferInfo>\r\n            TextureBindings: Array<ShaderData.TextureBindingInfo>\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array } from \"System\";\r\n    namespace ShaderData {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class ConstantBufferInfo extends ValueType {\r\n            constructor()\r\n            Name: string\r\n            Size: number\r\n            Fields: Array<ShaderData.ConstantInfo>\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Enum, Array } from \"System\";\r\n    namespace ShaderData {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class ConstantInfo extends ValueType {\r\n            constructor()\r\n            Name: string\r\n            Index: number\r\n            ConstantType: any\r\n            DataType: any\r\n            Rows: number\r\n            Columns: number\r\n            ArraySize: number\r\n            StructSize: number\r\n            StructFields: Array<ShaderData.ConstantInfo>\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Enum } from \"System\";\r\n    namespace ShaderData {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class TextureBindingInfo extends ValueType {\r\n            constructor()\r\n            Name: string\r\n            Index: number\r\n            SamplerIndex: number\r\n            Multisampled: boolean\r\n            ArraySize: number\r\n            Dim: any\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Describes which Unity systems consider the GameObject as static, and include the GameObject in their precomputations in the Unity Editor.\r\n     */\r\n    enum StaticEditorFlags {\r\n        /** Include the GameObject when precomputing lighting data.\r\n         */\r\n        ContributeGI = 1,\r\n        /** Include the GameObject when precomputing lighting data.\r\n         */\r\n        LightmapStatic = 1,\r\n        /** Mark the GameObject as a Static Occluder in the occlusion culling system.\r\n         */\r\n        OccluderStatic = 2,\r\n        /** Combine the GameObject's Mesh with other eligible Meshes, to potentially reduce runtime rendering costs.\r\n         */\r\n        BatchingStatic = 4,\r\n        /** Include the GameObject when precomputing navigation data.\r\n         */\r\n        NavigationStatic = 8,\r\n        /** Mark the GameObject as a Static Occludee in the occlusion culling system.\r\n         */\r\n        OccludeeStatic = 16,\r\n        /** Attempt to generate an Off-Mesh Link that starts from this GameObject when precomputing navigation data.\r\n         */\r\n        OffMeshLinkGeneration = 32,\r\n        /** Include this GameObject when when precomputing data for Reflection Probes whose Type property is set to Baked.\r\n         */\r\n        ReflectionProbeStatic = 64,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** StaticOcclusionCulling lets you perform static occlusion culling operations.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class StaticOcclusionCulling extends Object {\r\n        static Compute(): boolean\r\n        static GenerateInBackground(): boolean\r\n        static RemoveCacheFolder(): void\r\n        static Cancel(): void\r\n        static Clear(): void\r\n        static SetDefaultOcclusionBakeSettings(): void\r\n        /** Used to check if asynchronous generation of static occlusion culling data is still running.\r\n         */\r\n        static readonly isRunning: boolean\r\n        static smallestOccluder: number\r\n        static smallestHole: number\r\n        static backfaceThreshold: number\r\n        /** Does the Scene contain any occlusion portals that were added manually rather than automatically?\r\n         */\r\n        static readonly doesSceneHaveManualPortals: boolean\r\n        /** Returns the size in bytes that the PVS data is currently taking up in this Scene on disk.\r\n         */\r\n        static readonly umbraDataSize: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Camera } from \"UnityEngine\";\r\n    /** Used to visualize static occlusion culling at development time in Scene view.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class StaticOcclusionCullingVisualization extends Object {\r\n        /** If set to true, visualization of target volumes is enabled.\r\n         */\r\n        static showOcclusionCulling: boolean\r\n        /** If set to true, the visualization lines of the PVS volumes will show all cells rather than cells after culling.\r\n         */\r\n        static showPreVisualization: boolean\r\n        /** If set to true, visualization of view volumes is enabled.\r\n         */\r\n        static showViewVolumes: boolean\r\n        static showDynamicObjectBounds: boolean\r\n        /** If set to true, visualization of portals is enabled.\r\n         */\r\n        static showPortals: boolean\r\n        /** If set to true, visualization of portals is enabled.\r\n         */\r\n        static showVisibilityLines: boolean\r\n        /** If set to true, culling of geometry is enabled.\r\n         */\r\n        static showGeometryCulling: boolean\r\n        static readonly isPreviewOcclusionCullingCameraInPVS: boolean\r\n        static readonly previewOcclusionCamera: Camera\r\n        static readonly previewOcclucionCamera: Camera\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array, ValueType } from \"System\";\r\n    import { Object as Object1, Transform, GameObject, Component } from \"UnityEngine\";\r\n    /** Lets you register undo operations on specific objects you are about to perform changes on.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class Undo extends Object {\r\n        constructor()\r\n        /** Stores a copy of the object states on the undo stack.\r\n         * @param objectToUndo The object whose state changes need to be undone.\r\n         * @param name The name of the undo operation.\r\n         */\r\n        static RegisterCompleteObjectUndo(objectToUndo: Object1, name: string): void\r\n        /** This is equivalent to calling the first overload mutiple times, save for the fact that only one undo operation will be generated for this one.\r\n         * @param objectsToUndo An array of objects whose state changes need to be undone.\r\n         * @param name The name of the undo operation.\r\n         */\r\n        static RegisterCompleteObjectUndo(objectsToUndo: Array<Object1>, name: string): void\r\n        static SetTransformParent(transform: Transform, newParent: Transform, worldPositionStays: boolean, name: string): void\r\n        /** Sets the parent of transform to the new parent and records an undo operation.\r\n         * @param transform The Transform component whose parent is to be changed.\r\n         * @param newParent The parent Transform to be assigned.\r\n         * @param name The name of this action, to be stored in the Undo history buffer.\r\n         */\r\n        static SetTransformParent(transform: Transform, newParent: Transform, name: string): void\r\n        /** Move a GameObject from its current Scene to a new Scene.\nIt is required that the GameObject is at the root of its current Scene.\r\n         * @param go GameObject to move.\r\n         * @param scene Scene to move the GameObject into.\r\n         * @param name Name of the undo action.\r\n         */\r\n        static MoveGameObjectToScene(go: GameObject, scene: any, name: string): void\r\n        /** Register an undo operations for a newly created object.\r\n         * @param objectToUndo The object that was created.\r\n         * @param name The name of the action to undo. Think \"Undo ....\" in the main menu.\r\n         */\r\n        static RegisterCreatedObjectUndo(objectToUndo: Object1, name: string): void\r\n        /** Destroys the object and records an undo operation so that it can be recreated.\r\n         * @param objectToUndo The object that will be destroyed.\r\n         */\r\n        static DestroyObjectImmediate(objectToUndo: Object1): void\r\n        /** Adds a component to the game object and registers an undo operation for this action.\r\n         * @param gameObject The game object you want to add the component to.\r\n         * @param type The type of component you want to add.\r\n         * @returns The newly added component. \r\n         */\r\n        static AddComponent(gameObject: GameObject, type: any): Component\r\n        /** Copies the state of the importer for the given asset path.\r\n         * @param path Path of the asset importer to register for Undo.\r\n         * @param name The name of the undo operation.\r\n         */\r\n        static RegisterImporterUndo(path: string, name: string): void\r\n        /** Copy the states of a hierarchy of objects onto the undo stack.\r\n         * @param objectToUndo The object used to determine a hierarchy of objects whose state changes need to be undone.\r\n         * @param name The name of the undo operation.\r\n         */\r\n        static RegisterFullObjectHierarchyUndo(objectToUndo: Object1, name: string): void\r\n        /** Records any changes done on the object after the RecordObject function.\r\n         * @param objectToUndo The reference to the object that you will be modifying.\r\n         * @param name The title of the action to appear in the undo history (i.e. visible in the undo menu).\r\n         */\r\n        static RecordObject(objectToUndo: Object1, name: string): void\r\n        /** Records multiple undoable objects in a single call. This is the same as calling Undo.RecordObject multiple times.\r\n         */\r\n        static RecordObjects(objectsToUndo: Array<Object1>, name: string): void\r\n        /** Removes all Undo operation for the identifier object registered using Undo.RegisterCompleteObjectUndo from the undo stack.\r\n         */\r\n        static ClearUndo(identifier: Object1): void\r\n        static PerformUndo(): void\r\n        static PerformRedo(): void\r\n        static IncrementCurrentGroup(): void\r\n        static GetCurrentGroup(): number\r\n        static GetCurrentGroupName(): string\r\n        /** Set the name of the current undo group.\r\n         * @param name New name of the current undo group.\r\n         */\r\n        static SetCurrentGroupName(name: string): void\r\n        static RevertAllInCurrentGroup(): void\r\n        /** Performs all undo operations up to the group index without storing a redo operation in the process.\r\n         */\r\n        static RevertAllDownToGroup(group: number): void\r\n        /** Collapses all undo operation up to group index together into one step.\r\n         */\r\n        static CollapseUndoOperations(groupIndex: number): void\r\n        static ClearAll(): void\r\n        static FlushUndoRecordObjects(): void\r\n        static undoRedoPerformed(op: \"get\"): () => void\r\n        static undoRedoPerformed(op: \"add\" | \"remove\" | \"set\", fn?: () => void): void\r\n        static undoRedoPerformed(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => void): () => void | void\r\n        static willFlushUndoRecord(op: \"get\"): () => void\r\n        static willFlushUndoRecord(op: \"add\" | \"remove\" | \"set\", fn?: () => void): void\r\n        static willFlushUndoRecord(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => void): () => void | void\r\n        static postprocessModifications(op: \"get\"): (modifications: Array<UndoPropertyModification>) => Array<UndoPropertyModification>\r\n        static postprocessModifications(op: \"add\" | \"remove\" | \"set\", fn?: (modifications: Array<UndoPropertyModification>) => Array<UndoPropertyModification>): void\r\n        static postprocessModifications(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (modifications: Array<UndoPropertyModification>) => Array<UndoPropertyModification>): (modifications: Array<UndoPropertyModification>) => Array<UndoPropertyModification> | void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class UnityStats extends Object {\r\n        constructor()\r\n        static readonly batches: number\r\n        static readonly drawCalls: number\r\n        static readonly dynamicBatchedDrawCalls: number\r\n        static readonly staticBatchedDrawCalls: number\r\n        static readonly instancedBatchedDrawCalls: number\r\n        static readonly dynamicBatches: number\r\n        static readonly staticBatches: number\r\n        static readonly instancedBatches: number\r\n        static readonly setPassCalls: number\r\n        static readonly triangles: number\r\n        static readonly vertices: number\r\n        static readonly shadowCasters: number\r\n        static readonly renderTextureChanges: number\r\n        static readonly frameTime: number\r\n        static readonly renderTime: number\r\n        static readonly audioLevel: number\r\n        static readonly audioClippingAmount: number\r\n        static readonly audioDSPLoad: number\r\n        static readonly audioStreamLoad: number\r\n        static readonly renderTextureCount: number\r\n        static readonly renderTextureBytes: number\r\n        static readonly usedTextureMemorySize: number\r\n        static readonly usedTextureCount: number\r\n        static readonly screenRes: string\r\n        static readonly screenBytes: number\r\n        static readonly vboTotal: number\r\n        static readonly vboTotalBytes: number\r\n        static readonly vboUploads: number\r\n        static readonly vboUploadBytes: number\r\n        static readonly ibUploads: number\r\n        static readonly ibUploadBytes: number\r\n        static readonly visibleSkinnedMeshes: number\r\n        static readonly animationComponentsPlaying: number\r\n        static readonly animatorComponentsPlaying: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array, ValueType } from \"System\";\r\n    import { Object as Object1, ScriptableObject, Component, GameObject, Vector3 } from \"UnityEngine\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class Unsupported extends Object {\r\n        static CaptureScreenshotImmediate(filePath: string, x: number, y: number, width: number, height: number): void\r\n        static GetSubmenusCommands(menuPath: string): Array<string>\r\n        static GetTypeFromFullName(fullName: string): any\r\n        static GetSubmenus(menuPath: string): Array<string>\r\n        static GetSubmenusIncludingSeparators(menuPath: string): Array<string>\r\n        static PrepareObjectContextMenu(c: Object1, contextUserData: number): void\r\n        static IsDeveloperBuild(): boolean\r\n        static IsDeveloperMode(): boolean\r\n        static IsSourceBuild(checkHumanControllingUs: boolean): boolean\r\n        static IsSourceBuild(): boolean\r\n        static IsBleedingEdgeBuild(): boolean\r\n        static IsDestroyScriptableObject(target: ScriptableObject): boolean\r\n        static IsNativeCodeBuiltInReleaseMode(): boolean\r\n        static GetBaseUnityDeveloperFolder(): string\r\n        static StopPlayingImmediately(): void\r\n        static SceneTrackerFlushDirty(): void\r\n        static SetAllowCursorHide(allow: boolean): void\r\n        static SetOverrideLightingSettings(scene: any): boolean\r\n        static RestoreOverrideLightingSettings(): void\r\n        static SetRenderSettingsUseFogNoDirty(fog: boolean): void\r\n        static SetSceneViewDebugModeExposureNoDirty(exposure: number): void\r\n        static SetQualitySettingsShadowDistanceTemporarily(distance: number): void\r\n        static DeleteGameObjectSelection(): void\r\n        static CopyGameObjectsToPasteboard(): void\r\n        static PasteGameObjectsFromPasteboard(): void\r\n        static GetSerializedAssetInterfaceSingleton(className: string): Object1\r\n        static DuplicateGameObjectsUsingPasteboard(): void\r\n        static CopyComponentToPasteboard(component: Component): boolean\r\n        static PasteComponentFromPasteboard(go: GameObject): boolean\r\n        static PasteComponentValuesFromPasteboard(component: Component): boolean\r\n        static HasStateMachineTransitionDataInPasteboard(): boolean\r\n        static AreAllParametersInDestination(transition: Object1, controller: any, missingParameters: any): boolean\r\n        static DestinationHasCompatibleParameterTypes(transition: Object1, controller: any, mismatchedParameters: any): boolean\r\n        static CanPasteParametersToTransition(transition: Object1, controller: any): boolean\r\n        static CopyStateMachineTransitionParametersToPasteboard(transition: Object1, controller: any): void\r\n        static PasteToStateMachineTransitionParametersFromPasteboard(transition: Object1, controller: any, conditions: boolean, parameters: boolean): void\r\n        static CopyStateMachineDataToPasteboard(stateMachineObject: Object1, controller: any, layerIndex: number): void\r\n        static PasteToStateMachineFromPasteboard(sm: any, controller: any, layerIndex: number, position: Vector3): void\r\n        static HasStateMachineDataInPasteboard(): boolean\r\n        static SmartReset(obj: Object1): void\r\n        static ResolveSymlinks(path: string): string\r\n        static ResolveRedirectedPath(path: string): string\r\n        static SetApplicationSettingCompressAssetsOnImport(value: boolean): void\r\n        static GetApplicationSettingCompressAssetsOnImport(): boolean\r\n        static GetLocalIdentifierInFileForPersistentObject(obj: Object1): number\r\n        static IsHiddenFile(path: string): boolean\r\n        static ClearSkinCache(): void\r\n        static GetRenderSettings(): Object1\r\n        static useScriptableRenderPipeline: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array } from \"System\";\r\n    /** Unwrapping settings.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class UnwrapParam extends ValueType {\r\n        constructor()\r\n        /** Will set default values for params.\r\n         */\r\n        static SetDefaults(param: jsb.Out<UnwrapParam>): void\r\n        /** Maximum allowed angle distortion (0..1).\r\n         */\r\n        angleError: number\r\n        /** Maximum allowed area distortion (0..1).\r\n         */\r\n        areaError: number\r\n        /** This angle (in degrees) or greater between triangles will cause seam to be created.\r\n         */\r\n        hardAngle: number\r\n        /** How much uv-islands will be padded.\r\n         */\r\n        packMargin: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Vector2, Object as Object1 } from \"UnityEngine\";\r\n    /** This class holds everything you may need in regard to uv-unwrapping.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class Unwrapping extends Object {\r\n        /** Will generate per-triangle uv (3 UVs for each triangle) with provided settings.\r\n         * @param src The source mesh to generate UVs for.\r\n         * @param settings Allows you to specify custom parameters to control the unwrapping.\r\n         * @returns The list of UVs generated. \r\n         */\r\n        static GeneratePerTriangleUV(src: any, settings: UnwrapParam): Array<Vector2>\r\n        /** Will generate per-triangle uv (3 UVs for each triangle) with default settings.\r\n         * @param src The source mesh to generate UVs for.\r\n         * @returns The list of UVs generated. \r\n         */\r\n        static GeneratePerTriangleUV(src: any): Array<Vector2>\r\n        /** Will auto generate uv2 with provided settings for provided mesh, and fill them in.\r\n         */\r\n        static GenerateSecondaryUVSet(src: any, settings: UnwrapParam): void\r\n        /** Will auto generate uv2 with default settings for provided mesh, and fill them in.\r\n         */\r\n        static GenerateSecondaryUVSet(src: any): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ExternalVersionControl extends ValueType {\r\n        constructor(value: string)\r\n        toString(): string\r\n        static op_Implicit(d: ExternalVersionControl): string\r\n        static op_Implicit(d: string): ExternalVersionControl\r\n        static readonly Disabled: string\r\n        static readonly AutoDetect: string\r\n        static readonly Generic: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class VersionControlSettings extends Object {\r\n        protected constructor()\r\n        static mode: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Use these enum flags to specify which elements of a vertex to compress.\r\n     */\r\n    enum VertexChannelCompressionFlags {\r\n        /** Vertex compression disabled.\r\n         */\r\n        None = 0,\r\n        /** Position compression enabled.\r\n         */\r\n        Position = 1,\r\n        /** Position compression enabled.\r\n         */\r\n        kPosition = 1,\r\n        /** Normal compression enabled.\r\n         */\r\n        Normal = 2,\r\n        /** Normal compression enabled.\r\n         */\r\n        kNormal = 2,\r\n        /** Tangent compression enabled.\r\n         */\r\n        Tangent = 4,\r\n        /** Tangent compression enabled.\r\n         */\r\n        kColor = 4,\r\n        Color = 8,\r\n        kUV0 = 8,\r\n        TexCoord0 = 16,\r\n        kUV1 = 16,\r\n        TexCoord1 = 32,\r\n        kUV2 = 32,\r\n        TexCoord2 = 64,\r\n        kUV3 = 64,\r\n        /** Texture coordinate 3 compression enabled.\r\n         */\r\n        TexCoord3 = 128,\r\n        /** Texture coordinate 3 compression enabled.\r\n         */\r\n        kTangent = 128,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { AnimationClip } from \"UnityEngine\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AnimationClipSettings extends Object {\r\n        constructor()\r\n        additiveReferencePoseClip: AnimationClip\r\n        additiveReferencePoseTime: number\r\n        startTime: number\r\n        stopTime: number\r\n        orientationOffsetY: number\r\n        level: number\r\n        cycleOffset: number\r\n        hasAdditiveReferencePose: boolean\r\n        loopTime: boolean\r\n        loopBlend: boolean\r\n        loopBlendOrientation: boolean\r\n        loopBlendPositionY: boolean\r\n        loopBlendPositionXZ: boolean\r\n        keepOriginalOrientation: boolean\r\n        keepOriginalPositionY: boolean\r\n        keepOriginalPositionXZ: boolean\r\n        heightFromFeet: boolean\r\n        mirror: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ScriptableObject } from \"UnityEngine\";\r\n    /** AnimationMode uses AnimationModeDriver to identify the animation driver.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AnimationModeDriver extends ScriptableObject {\r\n        constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, ValueType } from \"System\";\r\n    import { Color, Object as Object1, GameObject, AnimationClip } from \"UnityEngine\";\r\n    /** AnimationMode is used by the AnimationWindow to store properties modified\n      by the AnimationClip playback.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AnimationMode extends Object {\r\n        constructor()\r\n        /** Checks whether the specified property is in Animation mode and is being animated.\r\n         * @param target The object to determine if it contained the animation.\r\n         * @param propertyPath The name of the animation to search for.\r\n         * @returns Whether the property search is found or not. \r\n         */\r\n        static IsPropertyAnimated(target: Object1, propertyPath: string): boolean\r\n        /** Stops the Animation mode and reverts any properties that were animated while in Animation mode.\r\n         * @param driver An AnimationModeDriver object must be specified if one was specified when the Animation mode was started (StartAnimationMode.)\r\n         */\r\n        static StopAnimationMode(driver: AnimationModeDriver): void\r\n        static StopAnimationMode(): void\r\n        /** Checks whether the Editor is in Animation mode.\r\n         * @param driver An AnimationModeDriver object that tests if AnimationMode has been locked specifically for this driver.\r\n         */\r\n        static InAnimationMode(driver: AnimationModeDriver): boolean\r\n        static InAnimationMode(): boolean\r\n        /** Starts the Animation mode.\r\n         * @param driver Specify an AnimationModeDriver object to lock the AnimationMode to a driver.\r\n         */\r\n        static StartAnimationMode(driver: AnimationModeDriver): void\r\n        static StartAnimationMode(): void\r\n        static BeginSampling(): void\r\n        static EndSampling(): void\r\n        /** Samples the AnimationClip for the GameObject and also records modified properties when in Animation mode.\r\n         * @param gameObject The root GameObject for the animation.\r\n         * @param clip The AnimationClip to sample.\r\n         * @param time The time at which to sample.\r\n         * @returns Returns true when the Editor is in Animation mode. Returns false otherwise. \r\n         */\r\n        static SampleAnimationClip(gameObject: GameObject, clip: AnimationClip, time: number): void\r\n        static SamplePlayableGraph(graph: any, index: number, time: number): void\r\n        /** Marks a property as currently being animated.\r\n         * @param binding Description of the animation clip curve being modified.\r\n         * @param modification Object property being modified.\r\n         * @param keepPrefabOverride Indicates whether to retain modifications when the targeted object is an instance of a Prefab.\r\n         */\r\n        static AddPropertyModification(binding: EditorCurveBinding, modification: PropertyModification, keepPrefabOverride: boolean): void\r\n        /** Marks a property defined by an EditorCurveBinding as currently being animated.\r\n         * @param gameObject The GameObject being modified.\r\n         * @param binding The binding for the property being modified.\r\n         */\r\n        static AddEditorCurveBinding(gameObject: GameObject, binding: EditorCurveBinding): void\r\n        /** The color used to show that a property is currently being animated.\r\n         */\r\n        static readonly animatedPropertyColor: Color\r\n        /** The color used to show that an animated property automatically records changes in the animation clip.\r\n         */\r\n        static readonly recordedPropertyColor: Color\r\n        /** The color used to show that an animated property has been modified.\r\n         */\r\n        static readonly candidatePropertyColor: Color\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    import { Object } from \"UnityEngine\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ObjectReferenceKeyframe extends ValueType {\r\n        constructor()\r\n        time: number\r\n        value: Object\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { AnimationCurve } from \"UnityEngine\";\r\n    /** An AnimationClipCurveData object contains all the information needed to identify a specific curve in an AnimationClip. The curve animates a specific property of a component  material attached to a game object  animated bone.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AnimationClipCurveData extends Object {\r\n        constructor(binding: EditorCurveBinding)\r\n        constructor()\r\n        /** The path of the game object / bone being animated.\r\n         */\r\n        path: string\r\n        /** The type of the component / material being animated.\r\n         */\r\n        type: any\r\n        /** The name of the property being animated.\r\n         */\r\n        propertyName: string\r\n        /** The actual animation curve.\r\n         */\r\n        curve: AnimationCurve\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { AnimationClip, GameObject, Animation, Object as Object1, AnimationCurve, Transform } from \"UnityEngine\";\r\n    /** Editor utility functions for modifying animation clips.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AnimationUtility extends Object {\r\n        constructor()\r\n        /** Retrieves an array of animation clips associated with a GameObject or component.\r\n         */\r\n        static GetAnimationClips(gameObject: GameObject): Array<AnimationClip>\r\n        /** Sets the array of animation clips to be referenced in the Animation component.\r\n         */\r\n        static SetAnimationClips(animation: Animation, clips: Array<AnimationClip>): void\r\n        /** Retrieves the animatable bindings for a specific GameObject.\r\n         */\r\n        static GetAnimatableBindings(targetObject: GameObject, root: GameObject): Array<EditorCurveBinding>\r\n        static GetEditorCurveValueType(root: GameObject, binding: EditorCurveBinding): any\r\n        static GetFloatValue(root: GameObject, binding: EditorCurveBinding, data: jsb.Out<number>): boolean\r\n        static GetObjectReferenceValue(root: GameObject, binding: EditorCurveBinding, data: jsb.Out<Object1>): boolean\r\n        /** Retrieves the animated object that the binding points to.\r\n         */\r\n        static GetAnimatedObject(root: GameObject, binding: EditorCurveBinding): Object1\r\n        static PropertyModificationToEditorCurveBinding(modification: PropertyModification, gameObject: GameObject, binding: jsb.Out<EditorCurveBinding>): any\r\n        /** Retrieves the float curve bindings in an animation clip.\r\n         */\r\n        static GetCurveBindings(clip: AnimationClip): Array<EditorCurveBinding>\r\n        /** Retrieves the object reference curve bindings stored in the animation clip.\r\n         */\r\n        static GetObjectReferenceCurveBindings(clip: AnimationClip): Array<EditorCurveBinding>\r\n        /** Retrieves the object reference curve that the binding points to.\r\n         * @returns Returns an array of keyframes. \r\n         */\r\n        static GetObjectReferenceCurve(clip: AnimationClip, binding: EditorCurveBinding): Array<ObjectReferenceKeyframe>\r\n        /** Adds, modifies, or removes an object reference curve in an animation clip.\r\n         * @param clip The animation clip to modify.\r\n         * @param binding The bindings that define the paths and the properties of each curve.\r\n         * @param keyframes Array of Object reference values over time. Setting this to null will remove the curve.\r\n         */\r\n        static SetObjectReferenceCurve(clip: AnimationClip, binding: EditorCurveBinding, keyframes: Array<ObjectReferenceKeyframe>): void\r\n        /** Adds, modifies, or removes object references curve in an animation clip.\r\n         * @param clip The animation clip to modify.\r\n         * @param bindings The bindings that define the paths and the properties of each curve.\r\n         * @param keyframes Array of Object reference arrays, one per binding.\r\n         */\r\n        static SetObjectReferenceCurves(clip: AnimationClip, bindings: Array<EditorCurveBinding>, keyframes: Array<Array<ObjectReferenceKeyframe>>): void\r\n        /** Retrieves the float curve that the binding points to.\r\n         */\r\n        static GetEditorCurve(clip: AnimationClip, binding: EditorCurveBinding): AnimationCurve\r\n        /** Adds, modifies, or removes an editor float curve in an animation clip.\r\n         * @param clip The animation clip to modify.\r\n         * @param binding The binding that defines the path and the properties of the curve.\r\n         * @param curve The curve to add. Set to null to remove the curve.\r\n         */\r\n        static SetEditorCurve(clip: AnimationClip, binding: EditorCurveBinding, curve: AnimationCurve): void\r\n        /** Adds, modifies, or removes multiple editor float curves in an animation clip.\r\n         * @param clip The animation clip to modify.\r\n         * @param binding The binding that defines the path and the properties of each curve.\r\n         * @param curves The curves to add. Setting curves in the array to null will remove these curves from the clip.\r\n         */\r\n        static SetEditorCurves(clip: AnimationClip, bindings: Array<EditorCurveBinding>, curves: Array<AnimationCurve>): void\r\n        /** Retrieves the left tangent mode of the keyframe at a specific index.\r\n         * @param curve Curve to query.\r\n         * @param index Keyframe index.\r\n         * @returns Returns the tangent mode. \r\n         */\r\n        static GetKeyLeftTangentMode(curve: AnimationCurve, index: number): AnimationUtility.TangentMode\r\n        /** Retrieves the right tangent mode of the keyframe at a specific index.\r\n         * @param curve Curve to query.\r\n         * @param index Keyframe index.\r\n         * @returns Returns the tangent mode. \r\n         */\r\n        static GetKeyRightTangentMode(curve: AnimationCurve, index: number): AnimationUtility.TangentMode\r\n        /** Retrieves the broken tangent flag for a specfic keyframe.\r\n         * @param curve Curve to query.\r\n         * @param index Keyframe index.\r\n         * @returns Broken flag at specified index. \r\n         */\r\n        static GetKeyBroken(curve: AnimationCurve, index: number): boolean\r\n        static SetKeyLeftTangentMode(curve: AnimationCurve, index: number, tangentMode: AnimationUtility.TangentMode): void\r\n        static SetKeyRightTangentMode(curve: AnimationCurve, index: number, tangentMode: AnimationUtility.TangentMode): void\r\n        /** Change the specified keyframe broken tangent flag.\r\n         * @param curve The curve to modify.\r\n         * @param index Keyframe index.\r\n         * @param broken Broken flag.\r\n         */\r\n        static SetKeyBroken(curve: AnimationCurve, index: number, broken: boolean): void\r\n        /** Retrieves all animation events associated with an animation clip.\r\n         */\r\n        static GetAnimationEvents(clip: AnimationClip): Array<any>\r\n        /** Replaces all animation events in the animation clip.\r\n         */\r\n        static SetAnimationEvents(clip: AnimationClip, events: Array<any>): void\r\n        /** Retrieves the path from the root transform to the target transform.\r\n         * @returns Returns a string representing the path in the transform hierarchy. \r\n         */\r\n        static CalculateTransformPath(targetTransform: Transform, root: Transform): string\r\n        static GetAnimationClipSettings(clip: AnimationClip): AnimationClipSettings\r\n        static SetAnimationClipSettings(clip: AnimationClip, srcClipInfo: AnimationClipSettings): void\r\n        /** Sets the additive reference pose from referenceClip at time for animation clip clip.\r\n         * @param clip The animation clip to use.\r\n         * @param referenceClip The animation clip containing the reference pose.\r\n         * @param time The time that when the reference pose occurs in referenceClip.\r\n         */\r\n        static SetAdditiveReferencePose(clip: AnimationClip, referenceClip: AnimationClip, time: number): void\r\n        static ConstrainToPolynomialCurve(curve: AnimationCurve): void\r\n        static onCurveWasModified(op: \"get\"): (clip: AnimationClip, binding: EditorCurveBinding, type: AnimationUtility.CurveModifiedType) => void\r\n        static onCurveWasModified(op: \"add\" | \"remove\" | \"set\", fn?: (clip: AnimationClip, binding: EditorCurveBinding, type: AnimationUtility.CurveModifiedType) => void): void\r\n        static onCurveWasModified(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (clip: AnimationClip, binding: EditorCurveBinding, type: AnimationUtility.CurveModifiedType) => void): (clip: AnimationClip, binding: EditorCurveBinding, type: AnimationUtility.CurveModifiedType) => void | void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace AnimationUtility {\r\n        enum CurveModifiedType {\r\n            CurveDeleted = 0,\r\n            CurveModified = 1,\r\n            ClipModified = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace AnimationUtility {\r\n        enum TangentMode {\r\n            Free = 0,\r\n            Auto = 1,\r\n            Linear = 2,\r\n            Constant = 3,\r\n            ClampedAuto = 4,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Object } from \"System\";\r\n    /** Defines how a curve is attached to an object that it controls.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class EditorCurveBinding extends ValueType {\r\n        constructor()\r\n        GetHashCode(): number\r\n        Equals(other: Object): boolean\r\n        Equals(other: EditorCurveBinding): boolean\r\n        static op_Equality(lhs: EditorCurveBinding, rhs: EditorCurveBinding): boolean\r\n        static op_Inequality(lhs: EditorCurveBinding, rhs: EditorCurveBinding): boolean\r\n        /** Creates a preconfigured binding for a float curve.\r\n         * @param inPath The transform path to the object to animate.\r\n         * @param inType The type of the object to animate.\r\n         * @param inPropertyName The name of the property to animate on the object.\r\n         */\r\n        static FloatCurve(inPath: string, inType: any, inPropertyName: string): EditorCurveBinding\r\n        /** Creates a preconfigured binding for a curve that points to an Object.\r\n         * @param inPath The transform path to the object to animate.\r\n         * @param inType The type of the object to animate.\r\n         * @param inPropertyName The name of the property to animate on the object.\r\n         */\r\n        static PPtrCurve(inPath: string, inType: any, inPropertyName: string): EditorCurveBinding\r\n        /** Creates a preconfigured binding for a curve where values should not be interpolated.\r\n         * @param inPath The transform path to the object to animate.\r\n         * @param inType The type of the object to animate.\r\n         * @param inPropertyName The name of the property to animate on the object.\r\n         */\r\n        static DiscreteCurve(inPath: string, inType: any, inPropertyName: string): EditorCurveBinding\r\n        // js_op_overloading: static ==(lhs: EditorCurveBinding, rhs: EditorCurveBinding): boolean\r\n        readonly isPPtrCurve: boolean\r\n        readonly isDiscreteCurve: boolean\r\n        /** The type of the property to be animated.\r\n         */\r\n        type: any\r\n        /** The transform path of the object that is animated.\r\n         */\r\n        path: string\r\n        /** The name of the property to be animated.\r\n         */\r\n        propertyName: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { AnimationClip } from \"UnityEngine\";\r\n    /** Use the AnimationWindow class to select and edit Animation clips.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AnimationWindow extends EditorWindow implements IHasCustomMenu {\r\n        AddItemsToMenu(menu: GenericMenu): void\r\n        protected constructor()\r\n        /** The animation clip selected in the Animation window.\r\n         */\r\n        animationClip: AnimationClip\r\n        /** This property toggles previewing in the Animation window.\r\n         */\r\n        previewing: boolean\r\n        /** True if Animation window can enable preview mode. False otherwise. (Read Only)\r\n         */\r\n        readonly canPreview: boolean\r\n        /** This property toggles recording in the Animation window.\r\n         */\r\n        recording: boolean\r\n        /** True if Animation window can enable recording mode. False otherwise. (Read Only)\r\n         */\r\n        readonly canRecord: boolean\r\n        /** This property toggles animation playback in the Animation window.\r\n         */\r\n        playing: boolean\r\n        /** The time value at which the Animation window playhead is located.\r\n         */\r\n        time: number\r\n        /** The frame number at which the Animation window playhead is located.\r\n         */\r\n        frame: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Drawing modes for Handles.DrawCamera.\r\n     */\r\n    enum DrawCameraMode {\r\n        /** Draw the camera textured with selection wireframe and no background clearing.\r\n         */\r\n        Textured = 0,\r\n        /** Draw the camera in wireframe and no background clearing.\r\n         */\r\n        Wireframe = 1,\r\n        /** Draw the camera where all objects have a wireframe overlay. and no background clearing.\r\n         */\r\n        TexturedWire = 2,\r\n        /** The camera is set to draw directional light shadow map cascades.\r\n         */\r\n        ShadowCascades = 3,\r\n        /** The camera is set to draw color coded render paths.\r\n         */\r\n        RenderPaths = 4,\r\n        /** The camera is set to display the alpha channel of the rendering.\r\n         */\r\n        AlphaChannel = 5,\r\n        /** The camera is set to display Scene overdraw, with brighter colors indicating more overdraw.\r\n         */\r\n        Overdraw = 6,\r\n        /** The camera is set to display the texture resolution, with a red tint indicating resolution that is too high, and a blue tint indicating texture sizes that could be higher.\r\n         */\r\n        Mipmaps = 7,\r\n        /** Draw diffuse color of Deferred Shading G-buffer.\r\n         */\r\n        DeferredDiffuse = 8,\r\n        /** Draw specular color of Deferred Shading G-buffer.\r\n         */\r\n        DeferredSpecular = 9,\r\n        /** Draw smoothness value of Deferred Shading G-buffer.\r\n         */\r\n        DeferredSmoothness = 10,\r\n        /** Draw world space normal of Deferred Shading G-buffer.\r\n         */\r\n        DeferredNormal = 11,\r\n        /** Draw objects with different colors for each real-time chart (UV island).\r\n         */\r\n        RealtimeCharting = 12,\r\n        /** Draw objects with different color for each GI system.\r\n         */\r\n        Systems = 13,\r\n        /** Draw objects with the real-time GI albedo component only.\r\n         */\r\n        RealtimeAlbedo = 14,\r\n        /** Draw objects with the real-time GI emission component only.\r\n         */\r\n        RealtimeEmissive = 15,\r\n        /** Draw objects with the real-time GI indirect light only.\r\n         */\r\n        RealtimeIndirect = 16,\r\n        /** Draw objects with the real-time GI directionality component only.\r\n         */\r\n        RealtimeDirectionality = 17,\r\n        /** Draw objects with the baked lightmap only.\r\n         */\r\n        BakedLightmap = 18,\r\n        /** Draw with different colors for each cluster.\r\n         */\r\n        Clustering = 19,\r\n        /** Draw lit clusters.\r\n         */\r\n        LitClustering = 20,\r\n        /** The camera is set to draw a physically based, albedo validated rendering.\r\n         */\r\n        ValidateAlbedo = 21,\r\n        /** The camera is set to draw a physically based, metal or specular validated rendering.\r\n         */\r\n        ValidateMetalSpecular = 22,\r\n        /** The camera is set to display colored ShadowMasks, coloring light gizmo with the same color.\r\n         */\r\n        ShadowMasks = 23,\r\n        /** The camera is set to show in red static lights that fall back to 'static' because more than four light volumes are overlapping.\r\n         */\r\n        LightOverlap = 24,\r\n        /** Draw objects with the baked albedo component only.\r\n         */\r\n        BakedAlbedo = 25,\r\n        /** Draw objects with the baked emission component only.\r\n         */\r\n        BakedEmissive = 26,\r\n        /** Draw objects with the baked directionality component only.\r\n         */\r\n        BakedDirectionality = 27,\r\n        /** Draw objects with baked texel validity only.\r\n         */\r\n        BakedTexelValidity = 28,\r\n        /** Draw objects with baked indices only.\r\n         */\r\n        BakedIndices = 29,\r\n        /** Draw objects with different colors for each baked chart (UV island).\r\n         */\r\n        BakedCharting = 30,\r\n        /** The camera is set to display SpriteMask and SpriteRenderer with SpriteRenderer.maskInteraction set.\r\n         */\r\n        SpriteMask = 31,\r\n        /** Draw objects with overlapping lightmap texels highlighted.\r\n         */\r\n        BakedUVOverlap = 32,\r\n        /** The camera is set to run in texture streaming debug mode.\r\n         */\r\n        TextureStreaming = 33,\r\n        /** Draw objects with visible lightmap texels highlighted.\r\n         */\r\n        BakedLightmapCulling = 34,\r\n        /** Draw Mesh Renderers and Terrains in different colors to show their StaticEditorFlags.ContributeGI  / ReceiveGI properties. With default colors:\n\nYellow means 'ContributeGI' is off.\nBlue means that 'ContributeGI' is on and the object receives GI from lightmaps. See Also: ReceiveGI.Lightmaps\nRed means that 'ContributeGI' is on, but that the object receives GI from Light Probes instead. See Also: ReceiveGI.LightProbes.\n\nAll colors can be adjusted under Preferences > Colors.\r\n         */\r\n        GIContributorsReceivers = 35,\r\n        /** A custom mode defined by the user.\r\n         */\r\n        UserDefined = -2147483648,\r\n        /** Draw objects with baked GI only. This value has been deprecated. Please use DrawCameraMode.BakedLightmap.\r\n         */\r\n        Baked = -18,\r\n        /** Draw objects with directionality for real-time GI. This value has been deprecated. Please use DrawCameraMode.RealtimeDirectionality.\r\n         */\r\n        Directionality = -17,\r\n        /** Draw objects with real-time GI only. This value has been deprecated. Please use DrawCameraMode.RealtimeIndirect.\r\n         */\r\n        Irradiance = -16,\r\n        /** Draw objects with the emission component only. This value has been deprecated. Please use DrawCameraMode.RealtimeEmissive.\r\n         */\r\n        Emissive = -15,\r\n        /** Draw objects with the albedo component only. This value has been deprecated. Please use DrawCameraMode.RealtimeAlbedo.\r\n         */\r\n        Albedo = -14,\r\n        /** Draw objects with different colors for each real-time chart (UV island).\r\n         */\r\n        Charting = -12,\r\n        /** Draw the camera like it would be drawn in-game. This uses the clear flags of the camera.\r\n         */\r\n        Normal = -1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Vector2, Rect } from \"UnityEngine\";\r\n    /** Use this class to instantiate a SceneViewCameraWindow window.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SceneViewCameraWindow extends PopupWindowContent {\r\n        constructor(sceneView: SceneView)\r\n        GetWindowSize(): Vector2\r\n        /** A callback used for drawing the GUI controls of the SceneViewCameraWindow window.\r\n         * @param rect The rectangle where the GUI controls are drawn.\r\n         */\r\n        OnGUI(rect: Rect): void\r\n        static additionalSettingsGui(op: \"add\" | \"remove\", fn: (obj: SceneView) => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Rect, Vector2 } from \"UnityEngine\";\r\n    /** Class used to implement content for a popup window.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class PopupWindowContent extends Object {\r\n        /** Callback for drawing GUI controls for the popup window.\r\n         * @param rect The rectangle to draw the GUI inside.\r\n         */\r\n        OnGUI(rect: Rect): void\r\n        GetWindowSize(): Vector2\r\n        OnOpen(): void\r\n        OnClose(): void\r\n        /** The EditorWindow that contains the popup content.\r\n         */\r\n        readonly editorWindow: EditorWindow\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Texture2D, Object as Object1 } from \"UnityEngine\";\r\n    /** Utility for fetching asset previews by instance ID of assets, See AssetPreview.GetAssetPreview. Since previews are loaded asynchronously methods are provided for requesting if all previews have been fully loaded, see AssetPreview.IsLoadingAssetPreviews. Loaded previews are stored in a cache, the size of the cache can be controlled by calling [AssetPreview.SetPreviewTextureCacheSize].\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AssetPreview extends Object {\r\n        constructor()\r\n        /** Returns a preview texture for an asset.\r\n         */\r\n        static GetAssetPreview(asset: Object1): Texture2D\r\n        /** Loading previews is asynchronous so it is useful to know if a specific asset preview is in the process of being loaded so client code e.g can repaint while waiting for the loading to finish.\r\n         * @param instanceID InstanceID of the assset that a preview has been requested for by: AssetPreview.GetAssetPreview().\r\n         */\r\n        static IsLoadingAssetPreview(instanceID: number): boolean\r\n        static IsLoadingAssetPreviews(): boolean\r\n        /** Set the asset preview cache to a size that can hold all visible previews on the screen at once.\r\n         * @param size The number of previews that can be loaded into the cache before the least used previews are being unloaded.\r\n         */\r\n        static SetPreviewTextureCacheSize(size: number): void\r\n        /** Returns the thumbnail for an object (like the ones you see in the project view).\r\n         */\r\n        static GetMiniThumbnail(obj: Object1): Texture2D\r\n        /** Returns the thumbnail for the type.\r\n         */\r\n        static GetMiniTypeThumbnail(type: any): Texture2D\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Object } from \"System\";\r\n    import { Object as Object1 } from \"UnityEngine\";\r\n    namespace AssetImporter {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class SourceAssetIdentifier extends ValueType {\r\n            constructor(type: any, name: string)\r\n            constructor(asset: Object1)\r\n            type: any\r\n            name: string\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    /** Define compute shader import settings in the Unity Editor.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ComputeShaderImporter extends AssetImporter {\r\n        constructor()\r\n        /** The preprocessor that Unity uses to compile this compute shader.\r\n         */\r\n        preprocessorOverride: PreprocessorOverride\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Use IHVImageFormatImporter to modify Texture2D import settings for Textures in IHV (Independent Hardware Vendor) formats such as .DDS and .PVR from Editor scripts.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class IHVImageFormatImporter extends AssetImporter {\r\n        constructor()\r\n        /** Is texture data readable from scripts.\r\n         */\r\n        isReadable: boolean\r\n        /** Filtering mode of the texture.\r\n         */\r\n        filterMode: any\r\n        /** Texture coordinate wrapping mode.\r\n         */\r\n        wrapMode: any\r\n        /** Texture U coordinate wrapping mode.\r\n         */\r\n        wrapModeU: any\r\n        /** Texture V coordinate wrapping mode.\r\n         */\r\n        wrapModeV: any\r\n        /** Texture W coordinate wrapping mode for Texture3D.\r\n         */\r\n        wrapModeW: any\r\n        /** Enable mipmap streaming for this texture.\r\n         */\r\n        streamingMipmaps: boolean\r\n        /** Relative priority for this texture when reducing memory size in order to hit the memory budget.\r\n         */\r\n        streamingMipmapsPriority: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Texture } from \"UnityEngine\";\r\n    import { Array } from \"System\";\r\n    /** Shader importer lets you modify shader import settings from Editor scripts.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ShaderImporter extends AssetImporter {\r\n        constructor()\r\n        GetShader(): any\r\n        /** Sets the default textures for each texture material property.\r\n         */\r\n        SetDefaultTextures(name: Array<string>, textures: Array<Texture>): void\r\n        /** Gets the default texture assigned to the shader importer for the shader property with given name.\r\n         */\r\n        GetDefaultTexture(name: string): Texture\r\n        /** Sets the non-modifiable textures for each texture material property.\r\n         */\r\n        SetNonModifiableTextures(name: Array<string>, textures: Array<Texture>): void\r\n        /** Gets the non-modifiable texture assigned to the shader importer for the shader property with given name.\r\n         */\r\n        GetNonModifiableTexture(name: string): Texture\r\n        /** The preprocessor that Unity uses to compile this shader.\r\n         */\r\n        preprocessorOverride: PreprocessorOverride\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Array, Enum } from \"System\";\r\n    import { Object, Color } from \"UnityEngine\";\r\n    /** AssetImportor for importing SpeedTree model assets.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SpeedTreeImporter extends AssetImporter {\r\n        constructor()\r\n        GenerateMaterials(): void\r\n        /** Search the project for matching materials and use them instead of the internal materials.\r\n         * @param materialFolderPath The path to search for matching materials.\r\n         * @returns Returns true if any materials have been remapped, otherwise false. \r\n         */\r\n        SearchAndRemapMaterials(materialFolderPath: string): boolean\r\n        /** Tells if the SPM file has been previously imported.\r\n         */\r\n        readonly hasImported: boolean\r\n        /** Returns the folder path where generated materials will be placed in.\r\n         */\r\n        readonly materialFolderPath: string\r\n        /** Material import location options.\r\n         */\r\n        materialLocation: SpeedTreeImporter.MaterialLocation\r\n        /** Returns true if the asset is a SpeedTree v8 asset.\r\n         */\r\n        readonly isV8: boolean\r\n        /** Returns the default SpeedTree shader for the active render pipeline (either v7 or v8 according to the asset version).\r\n         */\r\n        readonly defaultShader: any\r\n        /** Returns the default SpeedTree billboard shader for the active render pipeline, or null if the asset is a SpeedTree v8 asset.\r\n         */\r\n        readonly defaultBillboardShader: any\r\n        /** How much to scale the tree model compared to what is in the .spm file.\r\n         */\r\n        scaleFactor: number\r\n        /** Gets and sets a default main color.\r\n         */\r\n        mainColor: Color\r\n        /** Gets and sets a default Hue variation color and amount (in alpha).\r\n         */\r\n        hueVariation: Color\r\n        /** Gets and sets a default alpha test reference values.\r\n         */\r\n        alphaTestRef: number\r\n        /** Tells if there is a billboard LOD.\r\n         */\r\n        readonly hasBillboard: boolean\r\n        /** Enables smooth LOD transitions.\r\n         */\r\n        enableSmoothLODTransition: boolean\r\n        /** Indicates if the cross-fade LOD transition, applied to the last mesh LOD and the billboard, should be animated.\r\n         */\r\n        animateCrossFading: boolean\r\n        /** Proportion of the last 3D mesh LOD region width which is used for cross-fading to billboard tree.\r\n         */\r\n        billboardTransitionCrossFadeWidth: number\r\n        /** Proportion of the billboard LOD region width which is used for fading out the billboard.\r\n         */\r\n        fadeOutWidth: number\r\n        /** Gets and sets an array of floats of each LOD's screen height value.\r\n         */\r\n        LODHeights: Array<number>\r\n        /** Gets and sets an array of booleans to enable shadow casting for each LOD.\r\n         */\r\n        castShadows: Array<boolean>\r\n        /** Gets and sets an array of booleans to enable shadow receiving for each LOD.\r\n         */\r\n        receiveShadows: Array<boolean>\r\n        /** Gets and sets an array of booleans to enable Light Probe lighting for each LOD.\r\n         */\r\n        useLightProbes: Array<boolean>\r\n        reflectionProbeUsages: Array<any>\r\n        /** Gets and sets an array of booleans to enable normal mapping for each LOD.\r\n         */\r\n        enableBump: Array<boolean>\r\n        /** Gets and sets an array of booleans to enable Hue variation effect for each LOD.\r\n         */\r\n        enableHue: Array<boolean>\r\n        /** Gets and sets an array of booleans to enable Subsurface effect for each LOD (affects only SpeedTree v8 assets).\r\n         */\r\n        enableSubsurface: Array<boolean>\r\n        /** Returns the best-possible wind quality on this asset (configured in SpeedTree modeler).\r\n         */\r\n        readonly bestWindQuality: number\r\n        /** Gets and sets an array of integers of the wind qualities on each LOD. Values will be clampped by bestWindQuality internally.\r\n         */\r\n        windQualities: Array<number>\r\n        /** Gets an array of name strings for wind quality value.\r\n         */\r\n        static readonly windQualityNames: Array<string>\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace SpeedTreeImporter {\r\n        enum MaterialLocation {\r\n            External = 0,\r\n            InPrefab = 1,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Imported texture format for TextureImporter.\r\n     */\r\n    enum TextureImporterFormat {\r\n        /** TextureFormat.Alpha8 texture format.\r\n         */\r\n        Alpha8 = 1,\r\n        /** TextureFormat.ARGB4444 texture format.\r\n         */\r\n        ARGB16 = 2,\r\n        /** TextureFormat.RGB24 texture format.\r\n         */\r\n        RGB24 = 3,\r\n        /** TextureFormat.RGBA32 texture format.\r\n         */\r\n        RGBA32 = 4,\r\n        /** TextureFormat.ARGB32 texture format.\r\n         */\r\n        ARGB32 = 5,\r\n        /** TextureFormat.RGB565 texture format.\r\n         */\r\n        RGB16 = 7,\r\n        /** TextureFormat.R16 texture format.\r\n         */\r\n        R16 = 9,\r\n        /** TextureFormat.DXT1 compressed texture format.\r\n         */\r\n        DXT1 = 10,\r\n        /** TextureFormat.DXT5 compressed texture format.\r\n         */\r\n        DXT5 = 12,\r\n        /** TextureFormat.RGBA4444 texture format.\r\n         */\r\n        RGBA16 = 13,\r\n        /** TextureFormat.RHalf half-precision floating point texture format.\r\n         */\r\n        RHalf = 15,\r\n        /** TextureFormat.RGHalf half-precision floating point texture format.\r\n         */\r\n        RGHalf = 16,\r\n        /** TextureFormat.RGBAHalf half-precision floating point texture format.\r\n         */\r\n        RGBAHalf = 17,\r\n        /** TextureFormat.RFloat floating point texture format.\r\n         */\r\n        RFloat = 18,\r\n        /** TextureFormat.RGFloat floating point texture format.\r\n         */\r\n        RGFloat = 19,\r\n        /** TextureFormat.RGBAFloat floating point RGBA texture format.\r\n         */\r\n        RGBAFloat = 20,\r\n        /** TextureFormat.RGB9e5Float packed unsigned floating point texture format with shared exponent.\r\n         */\r\n        RGB9E5 = 22,\r\n        /** TextureFormat.BC6H compressed HDR texture format.\r\n         */\r\n        BC6H = 24,\r\n        /** TextureFormat.BC7 compressed texture format.\r\n         */\r\n        BC7 = 25,\r\n        /** TextureFormat.BC4 compressed texture format.\r\n         */\r\n        BC4 = 26,\r\n        /** TextureFormat.BC5 compressed texture format.\r\n         */\r\n        BC5 = 27,\r\n        /** DXT1 compressed texture format using Crunch compression for smaller storage sizes.\r\n         */\r\n        DXT1Crunched = 28,\r\n        /** DXT5 compressed texture format using Crunch compression for smaller storage sizes.\r\n         */\r\n        DXT5Crunched = 29,\r\n        /** PowerVR/iOS TextureFormat.PVRTC_RGB2 compressed texture format.\r\n         */\r\n        PVRTC_RGB2 = 30,\r\n        /** PowerVR/iOS TextureFormat.PVRTC_RGBA2 compressed texture format.\r\n         */\r\n        PVRTC_RGBA2 = 31,\r\n        /** PowerVR/iOS TextureFormat.PVRTC_RGB4 compressed texture format.\r\n         */\r\n        PVRTC_RGB4 = 32,\r\n        /** PowerVR/iOS TextureFormat.PVRTC_RGBA4 compressed texture format.\r\n         */\r\n        PVRTC_RGBA4 = 33,\r\n        /** ETC (GLES2.0) 4 bits/pixel compressed RGB texture format.\r\n         */\r\n        ETC_RGB4 = 34,\r\n        ATC_RGB4 = 35,\r\n        ATC_RGBA8 = 36,\r\n        /** ETC2EAC compressed 4 bits  pixel unsigned R texture format.\r\n         */\r\n        EAC_R = 41,\r\n        /** ETC2EAC compressed 4 bits  pixel signed R texture format.\r\n         */\r\n        EAC_R_SIGNED = 42,\r\n        /** ETC2EAC compressed 8 bits  pixel unsigned RG texture format.\r\n         */\r\n        EAC_RG = 43,\r\n        /** ETC2EAC compressed 4 bits  pixel signed RG texture format.\r\n         */\r\n        EAC_RG_SIGNED = 44,\r\n        /** ETC2 compressed 4 bits / pixel RGB texture format.\r\n         */\r\n        ETC2_RGB4 = 45,\r\n        /** ETC2 compressed 4 bits / pixel RGB + 1-bit alpha texture format.\r\n         */\r\n        ETC2_RGB4_PUNCHTHROUGH_ALPHA = 46,\r\n        /** ETC2 compressed 8 bits / pixel RGBA texture format.\r\n         */\r\n        ETC2_RGBA8 = 47,\r\n        /** ASTC compressed RGB(A) texture format, 4x4 block size.\r\n         */\r\n        ASTC_RGB_4x4 = 48,\r\n        /** ASTC compressed RGB(A) texture format, 4x4 block size.\r\n         */\r\n        ASTC_4x4 = 48,\r\n        /** ASTC compressed RGB(A) texture format, 5x5 block size.\r\n         */\r\n        ASTC_RGB_5x5 = 49,\r\n        /** ASTC compressed RGB(A) texture format, 5x5 block size.\r\n         */\r\n        ASTC_5x5 = 49,\r\n        /** ASTC compressed RGB(A) texture format, 6x6 block size.\r\n         */\r\n        ASTC_RGB_6x6 = 50,\r\n        /** ASTC compressed RGB(A) texture format, 6x6 block size.\r\n         */\r\n        ASTC_6x6 = 50,\r\n        /** ASTC compressed RGB(A) texture format, 8x8 block size.\r\n         */\r\n        ASTC_RGB_8x8 = 51,\r\n        /** ASTC compressed RGB(A) texture format, 8x8 block size.\r\n         */\r\n        ASTC_8x8 = 51,\r\n        /** ASTC compressed RGB(A) texture format, 10x10 block size.\r\n         */\r\n        ASTC_10x10 = 52,\r\n        /** ASTC compressed RGB(A) texture format, 10x10 block size.\r\n         */\r\n        ASTC_RGB_10x10 = 52,\r\n        /** ASTC compressed RGB(A) texture format, 12x12 block size.\r\n         */\r\n        ASTC_12x12 = 53,\r\n        /** ASTC compressed RGB(A) texture format, 12x12 block size.\r\n         */\r\n        ASTC_RGB_12x12 = 53,\r\n        /** ASTC compressed RGBA texture format, 4x4 block size.\r\n         */\r\n        ASTC_RGBA_4x4 = 54,\r\n        /** ASTC compressed RGBA texture format, 5x5 block size.\r\n         */\r\n        ASTC_RGBA_5x5 = 55,\r\n        /** ASTC compressed RGBA texture format, 6x6 block size.\r\n         */\r\n        ASTC_RGBA_6x6 = 56,\r\n        /** ASTC compressed RGBA texture format, 8x8 block size.\r\n         */\r\n        ASTC_RGBA_8x8 = 57,\r\n        /** ASTC compressed RGBA texture format, 10x10 block size.\r\n         */\r\n        ASTC_RGBA_10x10 = 58,\r\n        /** ASTC compressed RGBA texture format, 12x12 block size.\r\n         */\r\n        ASTC_RGBA_12x12 = 59,\r\n        /** ETC (Nintendo 3DS) 4 bits/pixel compressed RGB texture format.\r\n         */\r\n        ETC_RGB4_3DS = 60,\r\n        /** ETC (Nintendo 3DS) 8 bits/pixel compressed RGBA texture format.\r\n         */\r\n        ETC_RGBA8_3DS = 61,\r\n        /** TextureFormat.RG16 texture format.\r\n         */\r\n        RG16 = 62,\r\n        /** TextureFormat.R8 texture format.\r\n         */\r\n        R8 = 63,\r\n        /** ETC_RGB4 compressed texture format using Crunch compression for smaller storage sizes.\r\n         */\r\n        ETC_RGB4Crunched = 64,\r\n        /** ETC2_RGBA8 compressed color with alpha channel texture format using Crunch compression for smaller storage sizes.\r\n         */\r\n        ETC2_RGBA8Crunched = 65,\r\n        /** ASTC compressed RGB(A) HDR texture format, 4x4 block size.\r\n         */\r\n        ASTC_HDR_4x4 = 66,\r\n        /** ASTC compressed RGB(A) HDR texture format, 5x5 block size.\r\n         */\r\n        ASTC_HDR_5x5 = 67,\r\n        /** ASTC compressed RGB(A) HDR texture format, 6x6 block size.\r\n         */\r\n        ASTC_HDR_6x6 = 68,\r\n        /** ASTC compressed RGB(A) HDR texture format, 8x8 block size.\r\n         */\r\n        ASTC_HDR_8x8 = 69,\r\n        /** ASTC compressed RGB(A) HDR texture format, 10x10 block size.\r\n         */\r\n        ASTC_HDR_10x10 = 70,\r\n        /** ASTC compressed RGB(A) HDR texture format, 12x12 block size.\r\n         */\r\n        ASTC_HDR_12x12 = 71,\r\n        /** TextureFormat.RG32 texture format.\r\n         */\r\n        RG32 = 72,\r\n        /** TextureFormat.RGB48 texture format.\r\n         */\r\n        RGB48 = 73,\r\n        /** TextureFormat.RGBA64 texture format.\r\n         */\r\n        RGBA64 = 74,\r\n        /** Choose a compressed HDR format automatically.\r\n         */\r\n        AutomaticCompressedHDR = -7,\r\n        /** Choose an HDR format automatically.\r\n         */\r\n        AutomaticHDR = -6,\r\n        /** Choose a crunched format automatically.\r\n         */\r\n        AutomaticCrunched = -5,\r\n        /** Choose a Truecolor format automatically.\r\n         */\r\n        AutomaticTruecolor = -3,\r\n        /** Choose a 16 bit format automatically.\r\n         */\r\n        Automatic16bit = -2,\r\n        /** Choose a compressed format automatically.\r\n         */\r\n        AutomaticCompressed = -1,\r\n        /** Choose a compressed format automatically.\r\n         */\r\n        Automatic = -1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Mip map filter for TextureImporter.\r\n     */\r\n    enum TextureImporterMipFilter {\r\n        /** Box mipmap filter.\r\n         */\r\n        BoxFilter = 0,\r\n        /** Kaiser mipmap filter.\r\n         */\r\n        KaiserFilter = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Cubemap generation mode for TextureImporter.\r\n     */\r\n    enum TextureImporterGenerateCubemap {\r\n        /** Do not generate cubemap (default).\r\n         */\r\n        None = 0,\r\n        /** Generate cubemap from spheremap texture.\r\n         */\r\n        Spheremap = 1,\r\n        /** Generate cubemap from cylindrical texture.\r\n         */\r\n        Cylindrical = 2,\r\n        SimpleSpheremap = 3,\r\n        NiceSpheremap = 4,\r\n        /** Generate cubemap from vertical or horizontal cross texture.\r\n         */\r\n        FullCubemap = 5,\r\n        /** Automatically determine type of cubemap generation from the source image.\r\n         */\r\n        AutoCubemap = 6,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Scaling mode for non power of two textures in TextureImporter.\r\n     */\r\n    enum TextureImporterNPOTScale {\r\n        /** Keep non power of two textures as is.\r\n         */\r\n        None = 0,\r\n        /** Scale to nearest power of two.\r\n         */\r\n        ToNearest = 1,\r\n        /** Scale to larger power of two.\r\n         */\r\n        ToLarger = 2,\r\n        /** Scale to smaller power of two.\r\n         */\r\n        ToSmaller = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Normal map filtering mode for TextureImporter.\r\n     */\r\n    enum TextureImporterNormalFilter {\r\n        /** Standard normal map filter.\r\n         */\r\n        Standard = 0,\r\n        /** Sobel normal map filter.\r\n         */\r\n        Sobel = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Select how the alpha of the imported texture is generated.\r\n     */\r\n    enum TextureImporterAlphaSource {\r\n        /** No Alpha will be used.\r\n         */\r\n        None = 0,\r\n        /** Use Alpha from the input texture if one is provided.\r\n         */\r\n        FromInput = 1,\r\n        /** Generate Alpha from image gray scale.\r\n         */\r\n        FromGrayScale = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Selects which Color/Alpha channel TextureImporterType|Single Channel Textures uses.\r\n     */\r\n    enum TextureImporterSingleChannelComponent {\r\n        /** Use the Alpha channel.\r\n         */\r\n        Alpha = 0,\r\n        /** Use the red Color channel.\r\n         */\r\n        Red = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Select this to set basic parameters depending on the purpose of your texture.\r\n     */\r\n    enum TextureImporterType {\r\n        /** This is the most common setting used for all the textures in general.\r\n         */\r\n        Default = 0,\r\n        /** This is the most common setting used for all the textures in general.\r\n         */\r\n        Image = 0,\r\n        /** Select this to turn the color channels into a format suitable for real-time normal mapping.\r\n         */\r\n        Bump = 1,\r\n        /** Select this to turn the color channels into a format suitable for real-time normal mapping.\r\n         */\r\n        NormalMap = 1,\r\n        /** Use this if your texture is going to be used on any HUD/GUI Controls.\r\n         */\r\n        GUI = 2,\r\n        Cubemap = 3,\r\n        Reflection = 3,\r\n        /** This sets up your texture with the basic parameters used for the Cookies of your lights.\r\n         */\r\n        Cookie = 4,\r\n        Advanced = 5,\r\n        /** This sets up your texture with the parameters used by the lightmap.\r\n         */\r\n        Lightmap = 6,\r\n        /** Use this if your texture is going to be used as a cursor.\r\n         */\r\n        Cursor = 7,\r\n        /** Select this if you will be using your texture for Sprite graphics.\r\n         */\r\n        Sprite = 8,\r\n        HDRI = 9,\r\n        /** Use this for texture containing a single channel.\r\n         */\r\n        SingleChannel = 10,\r\n        /** Use this for textures that contain shadowmask data.\r\n         */\r\n        Shadowmask = 11,\r\n        /** Use this for textures that contain directional lightmap data.\r\n         */\r\n        DirectionalLightmap = 12,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Select the kind of compression you want for your texture.\r\n     */\r\n    enum TextureImporterCompression {\r\n        /** Texture will not be compressed.\r\n         */\r\n        Uncompressed = 0,\r\n        /** Texture will be compressed using a standard format depending on the platform (DXT, ASTC, ...).\r\n         */\r\n        Compressed = 1,\r\n        /** Texture will be compressed using a high quality format depending on the platform and availability (BC7, ASTC4x4, ...).\r\n         */\r\n        CompressedHQ = 2,\r\n        /** Texture will be compressed using a low quality but high performance, high compression format depending on the platform and availability (2bpp PVRTC, ASTC8x8, ...).\r\n         */\r\n        CompressedLQ = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** For Texture to be scaled down choose resize algorithm. ( Applyed only when Texture dimension is bigger than Max Size ).\r\n     */\r\n    enum TextureResizeAlgorithm {\r\n        /** Default high quality resize algorithm.\r\n         */\r\n        Mitchell = 0,\r\n        /** Might provide better result than Mitchell for some noise textures preserving more sharp details.\r\n         */\r\n        Bilinear = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** The shape of the imported texture.\r\n     */\r\n    enum TextureImporterShape {\r\n        /** Import the texture as a 2D texture (default).\r\n         */\r\n        Texture2D = 1,\r\n        /** Import the texture as a Cubemap.\r\n         */\r\n        TextureCube = 2,\r\n        /** Import the texture as a 2D Array texture.\r\n         */\r\n        Texture2DArray = 4,\r\n        /** Import the texture as a 3D texture.\r\n         */\r\n        Texture3D = 8,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Texture importer modes for Sprite import.\r\n     */\r\n    enum SpriteImportMode {\r\n        /** Graphic is not a Sprite.\r\n         */\r\n        None = 0,\r\n        /** Sprite is a single image section extracted automatically from the texture.\r\n         */\r\n        Single = 1,\r\n        /** Sprites are multiple image sections extracted from the texture.\r\n         */\r\n        Multiple = 2,\r\n        /** Sprite has it own mesh outline defined.\r\n         */\r\n        Polygon = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    import { Rect, Vector2, Vector4 } from \"UnityEngine\";\r\n    /** Editor data used in producing a Sprite.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SpriteMetaData extends ValueType {\r\n        constructor()\r\n        /** Name of the Sprite.\r\n         */\r\n        name: string\r\n        /** Bounding rectangle of the sprite's graphic within the atlas image.\r\n         */\r\n        rect: Rect\r\n        /** Edge-relative alignment of the sprite graphic.\r\n         */\r\n        alignment: number\r\n        /** The pivot point of the Sprite, relative to its bounding rectangle.\r\n         */\r\n        pivot: Vector2\r\n        /** Edge border size for a sprite (in pixels).\r\n         */\r\n        border: Vector4\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Enum } from \"System\";\r\n    import { Vector2, Vector4 } from \"UnityEngine\";\r\n    /** Stores settings of a TextureImporter.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class TextureImporterSettings extends Object {\r\n        constructor()\r\n        /** Copy parameters into another TextureImporterSettings object.\r\n         * @param target TextureImporterSettings object to copy settings to.\r\n         */\r\n        CopyTo(target: TextureImporterSettings): void\r\n        ApplyTextureType(type: TextureImporterType): void\r\n        /** Test texture importer settings for equality.\r\n         */\r\n        static Equal(a: TextureImporterSettings, b: TextureImporterSettings): boolean\r\n        /** Which type of texture are we dealing with here.\r\n         */\r\n        textureType: TextureImporterType\r\n        /** The shape of the imported texture.\r\n         */\r\n        textureShape: TextureImporterShape\r\n        /** Mipmap filtering mode.\r\n         */\r\n        mipmapFilter: TextureImporterMipFilter\r\n        /** Generate mipmaps for the texture?\r\n         */\r\n        mipmapEnabled: boolean\r\n        /** Is texture storing color data?\r\n         */\r\n        sRGBTexture: boolean\r\n        /** Fade out mip levels to gray color?\r\n         */\r\n        fadeOut: boolean\r\n        /** Enable this to avoid colors seeping out to the edge of the lower Mip levels. Used for light cookies.\r\n         */\r\n        borderMipmap: boolean\r\n        /** Enables or disables coverage-preserving alpha mipmapping.\r\n         */\r\n        mipMapsPreserveCoverage: boolean\r\n        /** Returns or assigns the alpha test reference value.\r\n         */\r\n        alphaTestReferenceValue: number\r\n        /** Mip level where texture begins to fade out to gray.\r\n         */\r\n        mipmapFadeDistanceStart: number\r\n        /** Mip level where texture is faded out to gray completely.\r\n         */\r\n        mipmapFadeDistanceEnd: number\r\n        /** Convert heightmap to normal map?\r\n         */\r\n        convertToNormalMap: boolean\r\n        /** Amount of bumpyness in the heightmap.\r\n         */\r\n        heightmapScale: number\r\n        /** Normal map filtering mode.\r\n         */\r\n        normalMapFilter: TextureImporterNormalFilter\r\n        /** Select how the alpha of the imported texture is generated.\r\n         */\r\n        alphaSource: TextureImporterAlphaSource\r\n        /** Color or Alpha component TextureImporterType|Single Channel Textures uses.\r\n         */\r\n        singleChannelComponent: TextureImporterSingleChannelComponent\r\n        /** The number of rows in the source image for a Texture2DArray or Texture3D.\r\n         */\r\n        flipbookRows: number\r\n        /** The number of columns in the source image for a Texture2DArray or Texture3D.\r\n         */\r\n        flipbookColumns: number\r\n        /** Is texture data readable from scripts.\r\n         */\r\n        readable: boolean\r\n        /** Enable mipmap streaming for this texture.\r\n         */\r\n        streamingMipmaps: boolean\r\n        /** Relative priority for this texture when reducing memory size in order to hit the memory budget.\r\n         */\r\n        streamingMipmapsPriority: number\r\n        /** Enable if the texture is purposed solely for use with a Texture Stack for Virtual Texturing.\r\n         */\r\n        vtOnly: boolean\r\n        /** Scaling mode for non power of two textures.\r\n         */\r\n        npotScale: TextureImporterNPOTScale\r\n        /** Cubemap generation mode.\r\n         */\r\n        generateCubemap: TextureImporterGenerateCubemap\r\n        /** Convolution mode.\r\n         */\r\n        cubemapConvolution: TextureImporterCubemapConvolution\r\n        seamlessCubemap: boolean\r\n        /** Filtering mode of the texture.\r\n         */\r\n        filterMode: any\r\n        /** Anisotropic filtering level of the texture.\r\n         */\r\n        aniso: number\r\n        /** Mipmap bias of the texture.\r\n         */\r\n        mipmapBias: number\r\n        /** Texture coordinate wrapping mode.\r\n         */\r\n        wrapMode: any\r\n        /** Texture U coordinate wrapping mode.\r\n         */\r\n        wrapModeU: any\r\n        /** Texture V coordinate wrapping mode.\r\n         */\r\n        wrapModeV: any\r\n        /** Texture W coordinate wrapping mode for Texture3D.\r\n         */\r\n        wrapModeW: any\r\n        /** If the provided alpha channel is transparency, enable this to dilate the color to avoid filtering artifacts on the edges.\r\n         */\r\n        alphaIsTransparency: boolean\r\n        /** Ignore the Gamma attribute in PNG files. This property does not effect other file formats.\r\n         */\r\n        ignorePngGamma: boolean\r\n        /** Sprite texture import mode.\r\n         */\r\n        spriteMode: number\r\n        /** The number of pixels in the sprite that correspond to one unit in world space.\r\n         */\r\n        spritePixelsPerUnit: number\r\n        /** The tessellation detail to be used for generating the mesh for the associated sprite if the SpriteMode is set to Single. For Multiple sprites, use the SpriteEditor to specify the value per sprite.\nValid values are in the range [0-1], with higher values generating a tighter mesh. A default of -1 will allow Unity to determine the value automatically.\r\n         */\r\n        spriteTessellationDetail: number\r\n        /** The number of blank pixels to leave between the edge of the graphic and the mesh.\r\n         */\r\n        spriteExtrude: number\r\n        /** SpriteMeshType defines the type of Mesh that TextureImporter generates for a Sprite.\r\n         */\r\n        spriteMeshType: any\r\n        /** Edge-relative alignment of the sprite graphic.\r\n         */\r\n        spriteAlignment: number\r\n        /** Pivot point of the Sprite relative to its graphic's rectangle.\r\n         */\r\n        spritePivot: Vector2\r\n        /** Border sizes of the generated sprites.\r\n         */\r\n        spriteBorder: Vector4\r\n        /** Generates a default physics shape for a Sprite if a physics shape has not been set by the user.\r\n         */\r\n        spriteGenerateFallbackPhysicsShape: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Enum } from \"System\";\r\n    /** Stores platform specifics settings of a TextureImporter.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class TextureImporterPlatformSettings extends Object {\r\n        constructor()\r\n        /** Copy parameters into another TextureImporterPlatformSettings object.\r\n         * @param target TextureImporterPlatformSettings object to copy settings to.\r\n         */\r\n        CopyTo(target: TextureImporterPlatformSettings): void\r\n        /** Name of the build target.\r\n         */\r\n        name: string\r\n        /** Set to true in order to override the Default platform parameters by those provided in the TextureImporterPlatformSettings structure.\r\n         */\r\n        overridden: boolean\r\n        /** Maximum texture size.\r\n         */\r\n        maxTextureSize: number\r\n        /** For Texture to be scaled down choose resize algorithm. ( Applyed only when Texture dimension is bigger than Max Size ).\r\n         */\r\n        resizeAlgorithm: TextureResizeAlgorithm\r\n        /** Format of imported texture.\r\n         */\r\n        format: TextureImporterFormat\r\n        /** Compression of imported texture.\r\n         */\r\n        textureCompression: TextureImporterCompression\r\n        /** Quality of texture compression in the range [0..100].\r\n         */\r\n        compressionQuality: number\r\n        /** Use crunch compression when available.\r\n         */\r\n        crunchedCompression: boolean\r\n        /** Allows Alpha splitting on the imported texture when needed (for example ETC1 compression for textures with transparency).\r\n         */\r\n        allowsAlphaSplitting: boolean\r\n        /** Override for ETC2 decompression fallback on Android devices that don't support ETC2.\r\n         */\r\n        androidETC2FallbackOverride: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Texture2D, Object as Object1 } from \"UnityEngine\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AssetStoreAsset extends Object {\r\n        constructor()\r\n        Dispose(): void\r\n        readonly Preview: Object1\r\n        readonly HasLivePreview: boolean\r\n        id: number\r\n        name: string\r\n        displayName: string\r\n        staticPreviewURL: string\r\n        dynamicPreviewURL: string\r\n        className: string\r\n        price: string\r\n        packageID: number\r\n        previewImage: Texture2D\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Color, Rect } from \"UnityEngine\";\r\n    /** Antialiased curve rendering functionality used by audio tools in the editor.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AudioCurveRendering extends Object {\r\n        constructor()\r\n        static BeginCurveFrame(r: Rect): Rect\r\n        static EndCurveFrame(): void\r\n        static DrawCurveFrame(r: Rect): Rect\r\n        static DrawCurveBackground(r: Rect): void\r\n        static DrawFilledCurve(r: Rect, eval: (x: number) => number, curveColor: Color): void\r\n        static DrawFilledCurve(r: Rect, eval: (x: number, col: jsb.Out<Color>) => number): void\r\n        static DrawMinMaxFilledCurve(r: Rect, eval: (x: number, col: jsb.Out<Color>, minValue: jsb.Out<number>, maxValue: jsb.Out<number>) => void): void\r\n        static DrawSymmetricFilledCurve(r: Rect, eval: (x: number, col: jsb.Out<Color>) => number): void\r\n        static DrawCurve(r: Rect, eval: (x: number) => number, curveColor: Color): void\r\n        static DrawGradientRect(r: Rect, c1: Color, c2: Color, blend: number, horizontal: boolean): void\r\n        static readonly kAudioOrange: Color\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class IAudioEffectPlugin extends Object {\r\n        SetFloatParameter(name: string, value: number): boolean\r\n        GetFloatParameter(name: string, value: jsb.Out<number>): boolean\r\n        GetFloatParameterInfo(name: string, minRange: jsb.Out<number>, maxRange: jsb.Out<number>, defaultValue: jsb.Out<number>): boolean\r\n        GetFloatBuffer(name: string, data: jsb.Out<Array<number>>, numsamples: number): boolean\r\n        GetSampleRate(): number\r\n        IsPluginEditableAndEnabled(): boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class IAudioEffectPluginGUI extends Object {\r\n        OnGUI(plugin: IAudioEffectPlugin): boolean\r\n        readonly Name: string\r\n        readonly Description: string\r\n        readonly Vendor: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    /** Base class for implementing sysroots and toolchains for IL2CPP\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class Sysroot extends Object {\r\n        Initialize(): boolean\r\n        GetIl2CppArguments(): IEnumerable<string>\r\n        /** Returns name of the sysroot\r\n         */\r\n        readonly Name: string\r\n        /** Returns name of the host platform\r\n         */\r\n        readonly HostPlatform: string\r\n        /** Returns name of the host architecture\r\n         */\r\n        readonly HostArch: string\r\n        /** Returns name of the target platform\r\n         */\r\n        readonly TargetPlatform: string\r\n        /** Returns name of the target architecture\r\n         */\r\n        readonly TargetArch: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    import { Camera, Vector2, Vector3 } from \"UnityEngine\";\r\n    /** Project points from world to screen space.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class CameraProjectionCache extends ValueType {\r\n        constructor(camera: Camera)\r\n        /** Transforms position from world space into screen space using the cached camera projection and viewport.\r\n         * @param worldPoint A point in world space.\r\n         * @returns The converted point in screen space. \r\n         */\r\n        WorldToScreenPoint(worldPoint: Vector3): Vector2\r\n        /** Converts a world space point to a 2D GUI position.\r\n         * @param worldPoint A point in world space.\r\n         * @returns A point in GUI space. \r\n         */\r\n        WorldToGUIPoint(worldPoint: Vector3): Vector2\r\n        /** Converts a point from GUI position to screen space relative to the cached camera viewport.\r\n         * @param guiPoint A point in GUI space to convert to screen space.\r\n         * @returns .guiPoint in screen space relative to the cached camera viewport. \r\n         */\r\n        GUIToScreenPoint(guiPoint: Vector2): Vector2\r\n        /** Converts a point from screen space to GUI position relative to the viewport at the time the CameraProjectionCache was created.\r\n         * @param screenPoint A point in screen space.\r\n         * @returns .screenPoint converted to GUI space relative to the cached camera viewport. \r\n         */\r\n        ScreenToGUIPoint(screenPoint: Vector2): Vector2\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum CommandHint {\r\n        None = 0,\r\n        Event = 1,\r\n        Menu = 2,\r\n        Shortcut = 4,\r\n        Shelf = 8,\r\n        UI = 1048576,\r\n        OnGUI = 3145728,\r\n        UIElements = 5242880,\r\n        Validate = 1073741824,\r\n        UserDefined = -2147483648,\r\n        Undefined = -1,\r\n        Any = -1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class CommandExecuteContext extends Object {\r\n        constructor()\r\n        readonly data: Object\r\n        args: Array<Object>\r\n        result: Object\r\n        hint: CommandHint\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class CommandService extends Object {\r\n        static GetCommandLabel(commandId: string): string\r\n        static RegisterCommand(id: string, label: string, handler: (context: CommandExecuteContext) => void, hint: CommandHint): void\r\n        static RegisterCommand(id: string, handler: (context: CommandExecuteContext) => void, hint: CommandHint): void\r\n        static UnregisterCommand(id: string): boolean\r\n        static Exists(id: string): boolean\r\n        static Execute(id: string, hint: CommandHint): Object\r\n        static Execute(id: string, hint: CommandHint, ...args: Object[]): Object\r\n        static Execute(id: string): Object\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class ModeService extends Object {\r\n        static ChangeModeById(modeId: string): void\r\n        static Update(): void\r\n        static HasContextMenu(menuId: string): boolean\r\n        static PopupContextMenu(menuId: string): void\r\n        static readonly modeNames: Array<string>\r\n        static readonly modeCount: number\r\n        static readonly currentId: string\r\n        static readonly currentIndex: number\r\n        static modeChanged(op: \"add\" | \"remove\", fn: (obj: ModeService.ModeChangedArgs) => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    namespace ModeService {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class ModeChangedArgs extends ValueType {\r\n            constructor()\r\n            prevIndex: number\r\n            nextIndex: number\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum GameViewSizeGroupType {\r\n        Standalone = 0,\r\n        WebPlayer = 1,\r\n        iOS = 2,\r\n        Android = 3,\r\n        PS3 = 4,\r\n        WiiU = 5,\r\n        Tizen = 6,\r\n        WP8 = 7,\r\n        N3DS = 8,\r\n        HMD = 9,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    /** The lighting data asset used by the active Scene.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class LightingDataAsset extends Object {\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Enum } from \"System\";\r\n    /** This class is now obsolete. Use LightingSettings.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class LightmapEditorSettings extends Object {\r\n        /** Determines how Unity will compress baked reflection cubemap.\r\n         */\r\n        static reflectionCubemapCompression: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    /** Configures how Unity bakes lighting and can be assigned to a LightingSettings instance or asset.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class LightmapParameters extends Object {\r\n        constructor()\r\n        /** Assignes itself to a LightingSettings instance or asset.\r\n         */\r\n        AssignToLightingSettings(lightingSettings: any): void\r\n        /** Returns the assigned LightmapParameters for the specified LightingSettings.\r\n         */\r\n        static GetLightmapParametersForLightingSettings(lightingSettings: any): LightmapParameters\r\n        /** Sets the LightmapParameters for the specified LightingSettings.\r\n         */\r\n        static SetLightmapParametersForLightingSettings(parameters: LightmapParameters, lightingSettings: any): void\r\n        /** The texel resolution per meter used for realtime lightmaps. This value is multiplied by LightingSettings.indirectResolution.\r\n         */\r\n        resolution: number\r\n        /** Controls the resolution at which Enlighten stores and can transfer input light.\r\n         */\r\n        clusterResolution: number\r\n        /** The amount of data used for realtime GI texels. Specifies how detailed view of the Scene a texel has. Small values mean more averaged out lighting.\r\n         */\r\n        irradianceBudget: number\r\n        /** The number of rays to cast for computing irradiance form factors.\r\n         */\r\n        irradianceQuality: number\r\n        /** Maximum size of gaps that can be ignored for GI (multiplier on pixel size).\r\n         */\r\n        modellingTolerance: number\r\n        /** Whether pairs of edges should be stitched together.\r\n         */\r\n        stitchEdges: boolean\r\n        /** If enabled, the object appears transparent during GlobalIllumination lighting calculations.\r\n         */\r\n        isTransparent: boolean\r\n        /** System tag is an integer identifier. It lets you force an object into a different Enlighten system even though all the other parameters are the same.\r\n         */\r\n        systemTag: number\r\n        /** The radius (in texels) of the post-processing filter that blurs baked direct lighting.\r\n         */\r\n        blurRadius: number\r\n        /** The maximum number of times to supersample a texel to reduce aliasing.\r\n         */\r\n        antiAliasingSamples: number\r\n        /** The number of rays used for lights with an area. Allows for accurate soft shadowing.\r\n         */\r\n        directLightQuality: number\r\n        /** The distance to offset the ray origin from the geometry when performing ray tracing, in modelling units. Unity applies the offset to all baked lighting: direct lighting, indirect lighting, environment lighting and ambient occlusion.\r\n         */\r\n        pushoff: number\r\n        /** BakedLightmapTag is an integer that affects the assignment to baked lightmaps. Objects with different values for bakedLightmapTag are guaranteed to not be assigned to the same lightmap even if the other baking parameters are the same.\r\n         */\r\n        bakedLightmapTag: number\r\n        /** If enabled, objects sharing the same lightmap parameters will be packed into LightmapParameters.maxLightmapCount lightmaps.\r\n         */\r\n        limitLightmapCount: boolean\r\n        /** The maximum number of lightmaps that will be created for objects sharing the same lightmap parameters. This property is ignored if LightmapParameters.limitLightmapCount is false.\r\n         */\r\n        maxLightmapCount: number\r\n        /** The number of rays to cast for computing ambient occlusion.\r\n         */\r\n        AOQuality: number\r\n        /** The maximum number of times to supersample a texel to reduce aliasing in AO.\r\n         */\r\n        AOAntiAliasingSamples: number\r\n        /** The percentage of rays shot from a ray origin that must hit front faces to be considered usable.\r\n         */\r\n        backFaceTolerance: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array, ValueType } from \"System\";\r\n    import { Object as Object1, Vector3, Behaviour } from \"UnityEngine\";\r\n    /** Allows to control the lightmapping job.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class Lightmapping extends Object {\r\n        static ClearDiskCache(): void\r\n        static BakeAsync(): boolean\r\n        static Bake(): boolean\r\n        static Cancel(): void\r\n        static ForceStop(): void\r\n        static Clear(): void\r\n        static ClearLightingDataAsset(): void\r\n        /** Calculates tetrahderons from positions using Delaunay Tetrahedralization.\r\n         * @param positions An array of Light Probe positions.\r\n         * @param outIndices An array that Unity populates with updated Light Probe indices.\r\n         * @param outPositions An array that Unity populates with updated Light Probe positions.\r\n         */\r\n        static Tetrahedralize(positions: Array<Vector3>, outIndices: jsb.Out<Array<number>>, outPositions: jsb.Out<Array<Vector3>>): void\r\n        /** Starts a synchronous bake job for the probe.\r\n         * @param probe Target probe.\r\n         * @param path The location where cubemap will be saved.\r\n         * @returns Returns true if baking was succesful. \r\n         */\r\n        static BakeReflectionProbe(probe: any, path: string): boolean\r\n        /** Get how many chunks the terrain is divided into for GI baking.\r\n         * @param terrain The terrain.\r\n         * @param numChunksX Number of chunks in terrain width.\r\n         * @param numChunksY Number of chunks in terrain length.\r\n         */\r\n        static GetTerrainGIChunks(terrain: any, numChunksX: jsb.Ref<number>, numChunksY: jsb.Ref<number>): void\r\n        /** Fetches the Lighting Settings for the current Scene. Will return false if it is null.\r\n         * @param settings See Lightmapping.lightingSettings.\r\n         * @returns Returns true if there is an object, and false if it isn't. \r\n         */\r\n        static TryGetLightingSettings(settings: jsb.Out<any>): boolean\r\n        /** Applies the settings specified in the LightingSettings object to the SceneManagement.Scene object.\r\n         * @param scene The SceneManagement.Scene object. If the Scene.isLoaded property is false, the method does not apply the settings.\r\n         * @param lightingSettings The LightingSettings object.\r\n         */\r\n        static SetLightingSettingsForScene(scene: any, lightingSettings: any): void\r\n        /** Applies the settings specified in the LightingSettings object to an array of SceneManagement.Scene objects.\r\n         * @param scenes The array of SceneManagement.Scene objects. If the Scene.isLoaded property is false on a Scene object, the method does not apply the settings to that object.\r\n         * @param lightingSettings The LightingSettings object.\r\n         */\r\n        static SetLightingSettingsForScenes(scenes: Array<any>, lightingSettings: any): void\r\n        /** Gets the LightingSettings object of a SceneManagement.Scene object.\r\n         * @param scene The SceneManagement.Scene object.\r\n         * @returns The LightingSettings object if Scene.isLoaded is true. Otherwise returns null. \r\n         */\r\n        static GetLightingSettingsForScene(scene: any): any\r\n        /** Bakes an array of Scenes.\r\n         * @param paths The path of the Scenes that should be baked.\r\n         */\r\n        static BakeMultipleScenes(paths: Array<string>): void\r\n        /** This property is now obsolete. Use LightingSettings.autoGenerate.\r\n         */\r\n        static giWorkflowMode: Lightmapping.GIWorkflowMode\r\n        /** This property is now obsolete. Use LightingSettings.realtimeGI.\r\n         */\r\n        static realtimeGI: boolean\r\n        /** This property is now obsolete. Use LightingSettings.bakedGI.\r\n         */\r\n        static bakedGI: boolean\r\n        /** Returns true when the bake job is running, false otherwise (Read Only).\r\n         */\r\n        static readonly isRunning: boolean\r\n        /** Returns the current lightmapping build progress or 0 if Lightmapping.isRunning is false.\r\n         */\r\n        static readonly buildProgress: number\r\n        /** The lighting data asset used by the active Scene.\r\n         */\r\n        static lightingDataAsset: LightingDataAsset\r\n        /** The LightingSettings that will be used for the current Scene. Will throw an exception if it is null.\r\n         */\r\n        static lightingSettings: any\r\n        /** Default LightingSettings that Unity uses for Scenes where lightingSettings is not assigned. (Read only)\r\n         */\r\n        static readonly lightingSettingsDefaults: any\r\n        static bakeStarted(op: \"add\" | \"remove\", fn: () => void): void\r\n        static lightingDataUpdated(op: \"add\" | \"remove\", fn: () => void): void\r\n        static lightingDataCleared(op: \"add\" | \"remove\", fn: () => void): void\r\n        static lightingDataAssetCleared(op: \"add\" | \"remove\", fn: () => void): void\r\n        static bakeCompleted(op: \"add\" | \"remove\", fn: () => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace Lightmapping {\r\n        enum GIWorkflowMode {\r\n            Iterative = 0,\r\n            OnDemand = 1,\r\n            Legacy = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Material, Object as Object1, Texture } from \"UnityEngine\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class EditorMaterialUtility extends Object {\r\n        constructor()\r\n        static ResetDefaultTextures(material: Material, overrideSetTextures: boolean): void\r\n        static IsBackgroundMaterial(material: Material): boolean\r\n        static SetShaderDefaults(shader: any, name: Array<string>, textures: Array<Texture>): void\r\n        static SetShaderNonModifiableDefaults(shader: any, name: Array<string>, textures: Array<Texture>): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Vector3 } from \"UnityEngine\";\r\n    /** Control the behavior of handle snapping in the editor.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class EditorSnapSettings extends Object {\r\n        static ResetSnapSettings(): void\r\n        /** Gets or sets whether grid snapping is enabled.\r\n         */\r\n        static gridSnapEnabled: boolean\r\n        /** Gets or sets the increment that translation handles snap to.\r\n         */\r\n        static move: Vector3\r\n        /** Gets or sets the increment that rotation handles snap to.\r\n         */\r\n        static rotate: number\r\n        /** Gets or sets the increment that scale handles snap to.\r\n         */\r\n        static scale: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Rect } from \"UnityEngine\";\r\n    /** Class used to display popup windows that inherit from PopupWindowContent.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class PopupWindow extends EditorWindow {\r\n        /** Show a popup with the given PopupWindowContent.\r\n         * @param activatorRect The rect of the button that opens the popup.\r\n         * @param windowContent The content to show in the popup window.\r\n         */\r\n        static Show(activatorRect: Rect, windowContent: PopupWindowContent): void\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Enum for Tools.viewTool.\r\n     */\r\n    enum ViewTool {\r\n        /** The orbit tool is selected.\r\n         */\r\n        Orbit = 0,\r\n        /** The pan tool is selected.\r\n         */\r\n        Pan = 1,\r\n        /** The zoom tool is selected.\r\n         */\r\n        Zoom = 2,\r\n        /** The FPS tool is selected.\r\n         */\r\n        FPS = 3,\r\n        /** View tool is not selected.\r\n         */\r\n        None = -1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Where is the tool handle placed.\r\n     */\r\n    enum PivotMode {\r\n        /** The tool handle is at the graphical center of the selection.\r\n         */\r\n        Center = 0,\r\n        /** The tool handle is on the pivot point of the active object.\r\n         */\r\n        Pivot = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** How is the tool handle oriented.\r\n     */\r\n    enum PivotRotation {\r\n        /** The tool handle is oriented from the active object.\r\n         */\r\n        Local = 0,\r\n        /** The tool handle is aligned along the global axes.\r\n         */\r\n        Global = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Which tool is active in the editor.\r\n     */\r\n    enum Tool {\r\n        /** The view tool is active - Use Tools.viewTool to find out which view tool we're talking about.\r\n         */\r\n        View = 0,\r\n        /** The move tool is active.\r\n         */\r\n        Move = 1,\r\n        /** The rotate tool is active.\r\n         */\r\n        Rotate = 2,\r\n        /** The scale tool is active.\r\n         */\r\n        Scale = 3,\r\n        /** The rect tool is active.\r\n         */\r\n        Rect = 4,\r\n        /** The transform tool is active.\r\n         */\r\n        Transform = 5,\r\n        /** Any tool that is not one of the built-in tools.\r\n         */\r\n        Custom = 6,\r\n        /** No tool is active. Set this to implement your own in-inspector toolbar (like the terrain editor does).\r\n         */\r\n        None = -1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ScriptableObject, Vector3, Rect, Quaternion } from \"UnityEngine\";\r\n    /** Class used to manipulate the tools used in Unity's Scene View.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class Tools extends ScriptableObject {\r\n        constructor()\r\n        /** The tool that is currently selected for the Scene View.\r\n         */\r\n        static current: Tool\r\n        /** The option that is currently active for the View tool in the Scene view.\r\n         */\r\n        static viewTool: ViewTool\r\n        /** Returns true if the active tool is a view or navigation tool.\r\n         */\r\n        static readonly viewToolActive: boolean\r\n        /** The position of the tool handle in world space.\r\n         */\r\n        static readonly handlePosition: Vector3\r\n        /** The rectangle used for the rect tool.\r\n         */\r\n        static readonly handleRect: Rect\r\n        /** The rotation of the rect tool handle in world space.\r\n         */\r\n        static readonly handleRectRotation: Quaternion\r\n        /** Are we in Center or Pivot mode.\r\n         */\r\n        static pivotMode: PivotMode\r\n        /** Is the rect handle in blueprint mode?\r\n         */\r\n        static rectBlueprintMode: boolean\r\n        /** The rotation of the tool handle in world space.\r\n         */\r\n        static handleRotation: Quaternion\r\n        /** What's the rotation of the tool handle.\r\n         */\r\n        static pivotRotation: PivotRotation\r\n        /** Hides the Tools(Move, Rotate, Resize) on the Scene view.\r\n         */\r\n        static hidden: boolean\r\n        /** Which layers are visible in the Scene view.\r\n         */\r\n        static visibleLayers: number\r\n        static lockedLayers: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Defines Cubemap convolution mode.\r\n     */\r\n    enum TextureImporterCubemapConvolution {\r\n        /** No convolution needed. This Cubemap texture represents mirror reflection or Skybox.\r\n         */\r\n        None = 0,\r\n        /** Specular convolution (aka Prefiltered Environment Map).\r\n         */\r\n        Specular = 1,\r\n        /** Diffuse convolution (aka irradiance Cubemap).\r\n         */\r\n        Diffuse = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** RGBM encoding mode for HDR textures in TextureImporter.\r\n     */\r\n    enum TextureImporterRGBMMode {\r\n        /** Do RGBM encoding when source data is HDR in TextureImporter.\r\n         */\r\n        Auto = 0,\r\n        /** Do RGBM encoding in TextureImporter.\r\n         */\r\n        On = 1,\r\n        /** Do not perform RGBM encoding in TextureImporter.\r\n         */\r\n        Off = 2,\r\n        /** Source texture is already RGBM encoded in TextureImporter.\r\n         */\r\n        Encoded = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    import { Vector2, Camera } from \"UnityEngine\";\r\n    namespace CameraEditor {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class Settings extends Object {\r\n            constructor(so: SerializedObject)\r\n            OnEnable(): void\r\n            Update(): void\r\n            ApplyModifiedProperties(): void\r\n            DrawClearFlags(): void\r\n            DrawBackgroundColor(): void\r\n            DrawCullingMask(): void\r\n            DrawProjection(): void\r\n            DrawClippingPlanes(): void\r\n            DrawNormalizedViewPort(): void\r\n            DrawDepth(): void\r\n            DrawRenderingPath(): void\r\n            DrawTargetTexture(deferred: boolean): void\r\n            DrawOcclusionCulling(): void\r\n            DrawHDR(): void\r\n            DrawMSAA(): void\r\n            DrawDynamicResolution(): void\r\n            DrawVR(): void\r\n            DrawMultiDisplay(): void\r\n            DrawTargetEye(): void\r\n            static DrawCameraWarnings(camera: Camera): void\r\n            static readonly ApertureFormatNames: IEnumerable<string>\r\n            static readonly ApertureFormatValues: any\r\n            readonly clearFlags: SerializedProperty\r\n            readonly backgroundColor: SerializedProperty\r\n            readonly normalizedViewPortRect: SerializedProperty\r\n            readonly sensorSize: SerializedProperty\r\n            readonly lensShift: SerializedProperty\r\n            readonly focalLength: SerializedProperty\r\n            readonly gateFit: SerializedProperty\r\n            readonly verticalFOV: SerializedProperty\r\n            readonly orthographic: SerializedProperty\r\n            readonly orthographicSize: SerializedProperty\r\n            readonly depth: SerializedProperty\r\n            readonly cullingMask: SerializedProperty\r\n            readonly renderingPath: SerializedProperty\r\n            readonly occlusionCulling: SerializedProperty\r\n            readonly targetTexture: SerializedProperty\r\n            readonly HDR: SerializedProperty\r\n            readonly allowMSAA: SerializedProperty\r\n            readonly allowDynamicResolution: SerializedProperty\r\n            readonly stereoConvergence: SerializedProperty\r\n            readonly stereoSeparation: SerializedProperty\r\n            readonly nearClippingPlane: SerializedProperty\r\n            readonly farClippingPlane: SerializedProperty\r\n            readonly fovAxisMode: SerializedProperty\r\n            readonly targetDisplay: SerializedProperty\r\n            readonly targetEye: SerializedProperty\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Object as Object1, GUIContent, Rect, GUIStyle } from \"UnityEngine\";\r\n    /** Base Class to derive from when creating Custom Previews.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ObjectPreview extends Object {\r\n        constructor()\r\n        /** Called when the Preview gets created with the objects being previewed.\r\n         * @param targets The objects being previewed.\r\n         */\r\n        Initialize(targets: Array<Object1>): void\r\n        MoveNextTarget(): boolean\r\n        ResetTarget(): void\r\n        HasPreviewGUI(): boolean\r\n        GetPreviewTitle(): GUIContent\r\n        /** Implement to create your own custom preview for the preview area of the inspector, primary editor headers and the object selector.\r\n         * @param r Rectangle in which to draw the preview.\r\n         * @param background Background image.\r\n         */\r\n        OnPreviewGUI(r: Rect, background: GUIStyle): void\r\n        /** Implement to create your own interactive custom preview. Interactive custom previews are used in the preview area of the inspector and the object selector.\r\n         * @param r Rectangle in which to draw the preview.\r\n         * @param background Background image.\r\n         */\r\n        OnInteractivePreviewGUI(r: Rect, background: GUIStyle): void\r\n        OnPreviewSettings(): void\r\n        GetInfoString(): string\r\n        /** This is the first entry point for Preview Drawing.\r\n         * @param previewArea The available area to draw the preview.\r\n         */\r\n        DrawPreview(previewArea: Rect): void\r\n        ReloadPreviewInstances(): void\r\n        /** The object currently being previewed.\r\n         */\r\n        readonly target: Object1\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Tells an Editor class which run-time type it's an editor for when the given RenderPipeline is activated.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class CustomEditorForRenderPipelineAttribute extends Object {\r\n        constructor(inspectedType: any, renderPipeline: any, editorForChildClasses: boolean)\r\n        constructor(inspectedType: any, renderPipeline: any)\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    /** The class used to render the Light Editor when a Light is selected in the Unity Editor.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class LightEditor extends Editor {\r\n        constructor()\r\n        OnInspectorGUI(): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Behaviour, Texture } from \"UnityEngine\";\r\n    namespace LightEditor {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class Settings extends Object {\r\n            constructor(so: SerializedObject)\r\n            OnEnable(): void\r\n            OnDestroy(): void\r\n            Update(): void\r\n            DrawLightType(): void\r\n            DrawRange(): void\r\n            DrawSpotAngle(): void\r\n            DrawInnerAndOuterSpotAngle(): void\r\n            DrawArea(): void\r\n            DrawColor(): void\r\n            DrawLightmapping(): void\r\n            DrawIntensity(): void\r\n            DrawBounceIntensity(): void\r\n            DrawCookie(): void\r\n            DrawCookieSize(): void\r\n            DrawHalo(): void\r\n            DrawFlare(): void\r\n            DrawRenderMode(): void\r\n            DrawCullingMask(): void\r\n            DrawRenderingLayerMask(): void\r\n            ApplyModifiedProperties(): void\r\n            DrawShadowsType(): void\r\n            DrawBakedShadowRadius(): void\r\n            DrawBakedShadowAngle(): void\r\n            DrawRuntimeShadow(): void\r\n            readonly lightType: SerializedProperty\r\n            readonly lightShape: SerializedProperty\r\n            readonly range: SerializedProperty\r\n            readonly spotAngle: SerializedProperty\r\n            readonly innerSpotAngle: SerializedProperty\r\n            readonly cookieSize: SerializedProperty\r\n            readonly color: SerializedProperty\r\n            readonly intensity: SerializedProperty\r\n            readonly bounceIntensity: SerializedProperty\r\n            readonly colorTemperature: SerializedProperty\r\n            readonly useColorTemperature: SerializedProperty\r\n            readonly cookieProp: SerializedProperty\r\n            readonly shadowsType: SerializedProperty\r\n            readonly shadowsStrength: SerializedProperty\r\n            readonly shadowsResolution: SerializedProperty\r\n            readonly shadowsBias: SerializedProperty\r\n            readonly shadowsNormalBias: SerializedProperty\r\n            readonly shadowsNearPlane: SerializedProperty\r\n            readonly halo: SerializedProperty\r\n            readonly flare: SerializedProperty\r\n            readonly renderMode: SerializedProperty\r\n            readonly cullingMask: SerializedProperty\r\n            readonly renderingLayerMask: SerializedProperty\r\n            readonly lightmapping: SerializedProperty\r\n            readonly areaSizeX: SerializedProperty\r\n            readonly areaSizeY: SerializedProperty\r\n            readonly bakedShadowRadiusProp: SerializedProperty\r\n            readonly bakedShadowAngleProp: SerializedProperty\r\n            readonly isRealtime: boolean\r\n            readonly isMixed: boolean\r\n            readonly isCompletelyBaked: boolean\r\n            readonly isBakedOrMixed: boolean\r\n            readonly isAreaLightType: boolean\r\n            readonly light: any\r\n            readonly cookie: Texture\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Vector4, Rect, Color, Material, Object, Renderer, Texture, GUIContent, Texture2D, GUIStyle } from \"UnityEngine\";\r\n    import { Enum, Array } from \"System\";\r\n    /** The Unity Material Editor.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class MaterialEditor extends Editor {\r\n        constructor()\r\n        /** Set the shader of the material.\r\n         * @param shader Shader to set.\r\n         * @param registerUndo Should undo be registered.\r\n         */\r\n        SetShader(newShader: any, registerUndo: boolean): void\r\n        /** Set the shader of the material.\r\n         * @param shader Shader to set.\r\n         * @param registerUndo Should undo be registered.\r\n         */\r\n        SetShader(shader: any): void\r\n        Awake(): void\r\n        OnInspectorGUI(): void\r\n        PropertiesChanged(): void\r\n        /** Draw a range slider for a range shader property.\r\n         * @param label Label for the property.\r\n         * @param prop The property to edit.\r\n         * @param position Position and size of the range slider control.\r\n         */\r\n        RangeProperty(position: Rect, prop: MaterialProperty, label: string): number\r\n        /** Draw a range slider for a range shader property.\r\n         * @param label Label for the property.\r\n         * @param prop The property to edit.\r\n         * @param position Position and size of the range slider control.\r\n         */\r\n        RangeProperty(prop: MaterialProperty, label: string): number\r\n        /** Draw a property field for a float shader property.\r\n         * @param label Label for the property.\r\n         */\r\n        FloatProperty(position: Rect, prop: MaterialProperty, label: string): number\r\n        /** Draw a property field for a float shader property.\r\n         * @param label Label for the property.\r\n         */\r\n        FloatProperty(prop: MaterialProperty, label: string): number\r\n        /** Draw a property field for a color shader property.\r\n         * @param label Label for the property.\r\n         */\r\n        ColorProperty(position: Rect, prop: MaterialProperty, label: string): Color\r\n        /** Draw a property field for a color shader property.\r\n         * @param label Label for the property.\r\n         */\r\n        ColorProperty(prop: MaterialProperty, label: string): Color\r\n        /** Draw a property field for a vector shader property.\r\n         * @param label Label for the field.\r\n         */\r\n        VectorProperty(position: Rect, prop: MaterialProperty, label: string): Vector4\r\n        /** Draw a property field for a vector shader property.\r\n         * @param label Label for the field.\r\n         */\r\n        VectorProperty(prop: MaterialProperty, label: string): Vector4\r\n        /** Draws tiling and offset properties for a texture.\r\n         * @param position Rect to draw this control in.\r\n         * @param property Property to draw.\r\n         * @param partOfTexturePropertyControl If this control should be rendered under large texture property control use 'true'. If this control should be shown seperately use 'false'.\r\n         */\r\n        TextureScaleOffsetProperty(position: Rect, property: MaterialProperty, partOfTexturePropertyControl: boolean): number\r\n        /** Draws tiling and offset properties for a texture.\r\n         * @param position Rect to draw this control in.\r\n         * @param property Property to draw.\r\n         * @param partOfTexturePropertyControl If this control should be rendered under large texture property control use 'true'. If this control should be shown seperately use 'false'.\r\n         */\r\n        TextureScaleOffsetProperty(position: Rect, property: MaterialProperty): number\r\n        TextureScaleOffsetProperty(property: MaterialProperty): void\r\n        /** Draw a property field for a texture shader property.\r\n         * @param label Label for the field.\r\n         * @param scaleOffset Draw scale / offset.\r\n         */\r\n        TextureProperty(position: Rect, prop: MaterialProperty, label: string, tooltip: string, scaleOffset: boolean): Texture\r\n        /** Draw a property field for a texture shader property.\r\n         * @param label Label for the field.\r\n         * @param scaleOffset Draw scale / offset.\r\n         */\r\n        TextureProperty(position: Rect, prop: MaterialProperty, label: string, scaleOffset: boolean): Texture\r\n        /** Draw a property field for a texture shader property.\r\n         * @param label Label for the field.\r\n         * @param scaleOffset Draw scale / offset.\r\n         */\r\n        TextureProperty(prop: MaterialProperty, label: string, scaleOffset: boolean): Texture\r\n        /** Draw a property field for a texture shader property.\r\n         * @param label Label for the field.\r\n         * @param scaleOffset Draw scale / offset.\r\n         */\r\n        TextureProperty(position: Rect, prop: MaterialProperty, label: string): Texture\r\n        /** Draw a property field for a texture shader property.\r\n         * @param label Label for the field.\r\n         * @param scaleOffset Draw scale / offset.\r\n         */\r\n        TextureProperty(prop: MaterialProperty, label: string): Texture\r\n        /** Make a help box with a message and button. Returns true, if button was pressed.\r\n         * @param messageContent The message text.\r\n         * @param buttonContent The button text.\r\n         * @returns Returns true, if button was pressed. \r\n         */\r\n        HelpBoxWithButton(messageContent: GUIContent, buttonContent: GUIContent): boolean\r\n        /** Checks if particular property has incorrect type of texture specified by the material, displays appropriate warning and suggests the user to automatically fix the problem.\r\n         * @param prop The texture property to check and display warning for, if necessary.\r\n         */\r\n        TextureCompatibilityWarning(prop: MaterialProperty): void\r\n        /** Draw a property field for a texture shader property that only takes up a single line height.\r\n         * @param position Rect that this control should be rendered in.\r\n         * @param label Label for the field.\r\n         * @returns Returns total height used by this control. \r\n         */\r\n        TexturePropertyMiniThumbnail(position: Rect, prop: MaterialProperty, label: string, tooltip: string): Texture\r\n        /** Returns the free rect below the label and before the large thumb object field. Is used for e.g. tiling and offset properties.\r\n         * @param position The total rect of the texture property.\r\n         */\r\n        GetTexturePropertyCustomArea(position: Rect): Rect\r\n        /** Calculate height needed for the property.\r\n         */\r\n        GetPropertyHeight(prop: MaterialProperty, label: string): number\r\n        /** Calculate height needed for the property.\r\n         */\r\n        GetPropertyHeight(prop: MaterialProperty): number\r\n        /** Creates a Property wrapper, useful for making regular GUI controls work with MaterialProperty.\r\n         * @param totalPosition Rectangle on the screen to use for the control, including label if applicable.\r\n         * @param prop The MaterialProperty to use for the control.\r\n         */\r\n        BeginAnimatedCheck(totalPosition: Rect, prop: MaterialProperty): void\r\n        /** Creates a Property wrapper, useful for making regular GUI controls work with MaterialProperty.\r\n         * @param totalPosition Rectangle on the screen to use for the control, including label if applicable.\r\n         * @param prop The MaterialProperty to use for the control.\r\n         */\r\n        BeginAnimatedCheck(prop: MaterialProperty): void\r\n        EndAnimatedCheck(): void\r\n        ShaderProperty(position: Rect, prop: MaterialProperty, label: string, labelIndent: number): void\r\n        ShaderProperty(position: Rect, prop: MaterialProperty, label: GUIContent, labelIndent: number): void\r\n        ShaderProperty(prop: MaterialProperty, label: string, labelIndent: number): void\r\n        ShaderProperty(prop: MaterialProperty, label: GUIContent, labelIndent: number): void\r\n        /** Handes UI for one shader property.\r\n         */\r\n        ShaderProperty(position: Rect, prop: MaterialProperty, label: string): void\r\n        ShaderProperty(position: Rect, prop: MaterialProperty, label: GUIContent): void\r\n        /** Handes UI for one shader property.\r\n         */\r\n        ShaderProperty(prop: MaterialProperty, label: string): void\r\n        ShaderProperty(prop: MaterialProperty, label: GUIContent): void\r\n        LightmapEmissionProperty(position: Rect, labelIndent: number): void\r\n        LightmapEmissionProperty(labelIndent: number): void\r\n        LightmapEmissionProperty(): void\r\n        EmissionEnabledProperty(): boolean\r\n        /** Draws the UI for setting the global illumination flag of a material.\r\n         * @param indent Level of indentation for the property.\r\n         * @param enabled True if emission is enabled for the material, false otherwise.\r\n         * @param ignoreEmissionColor True if property should always be displayed.\r\n         */\r\n        LightmapEmissionFlagsProperty(indent: number, enabled: boolean, ignoreEmissionColor: boolean): void\r\n        /** Draws the UI for setting the global illumination flag of a material.\r\n         * @param indent Level of indentation for the property.\r\n         * @param enabled True if emission is enabled for the material, false otherwise.\r\n         * @param ignoreEmissionColor True if property should always be displayed.\r\n         */\r\n        LightmapEmissionFlagsProperty(indent: number, enabled: boolean): void\r\n        /** Handles UI for one shader property ignoring any custom drawers.\r\n         */\r\n        DefaultShaderProperty(position: Rect, prop: MaterialProperty, label: string): void\r\n        /** Handles UI for one shader property ignoring any custom drawers.\r\n         */\r\n        DefaultShaderProperty(prop: MaterialProperty, label: string): void\r\n        SetDefaultGUIWidths(): void\r\n        PropertiesGUI(): boolean\r\n        /** Default rendering of shader properties.\r\n         * @param props Array of material properties.\r\n         */\r\n        PropertiesDefaultGUI(props: Array<MaterialProperty>): void\r\n        /** Call this when you change a material property. It will add an undo for the action.\r\n         * @param label Undo Label.\r\n         */\r\n        RegisterPropertyChangeUndo(label: string): void\r\n        OnPreviewSettings(): void\r\n        DefaultPreviewSettingsGUI(): void\r\n        RenderStaticPreview(assetPath: string, subAssets: Array<Object>, width: number, height: number): Texture2D\r\n        HasPreviewGUI(): boolean\r\n        RequiresConstantRepaint(): boolean\r\n        OnInteractivePreviewGUI(r: Rect, background: GUIStyle): void\r\n        /** Custom preview for Image component.\r\n         * @param r Rectangle in which to draw the preview.\r\n         * @param background Background image.\r\n         */\r\n        OnPreviewGUI(r: Rect, background: GUIStyle): void\r\n        /** Default handling of preview area for materials.\r\n         */\r\n        DefaultPreviewGUI(r: Rect, background: GUIStyle): void\r\n        OnEnable(): void\r\n        UndoRedoPerformed(): void\r\n        OnDisable(): void\r\n        /** Display UI for editing material's render queue setting.\r\n         */\r\n        RenderQueueField(r: Rect): void\r\n        RenderQueueField(): void\r\n        /** Display UI for editing material's render queue setting within the specified rect.\r\n         */\r\n        EnableInstancingField(r: Rect): void\r\n        EnableInstancingField(): boolean\r\n        IsInstancingEnabled(): boolean\r\n        DoubleSidedGIField(): boolean\r\n        /** Method for showing a texture property control with additional inlined properites.\r\n         * @param label The label used for the texture property.\r\n         * @param textureProp The texture property.\r\n         * @param extraProperty1 First optional property inlined after the texture property.\r\n         * @param extraProperty2 Second optional property inlined after the extraProperty1.\r\n         * @returns Returns the Rect used. \r\n         */\r\n        TexturePropertySingleLine(label: GUIContent, textureProp: MaterialProperty, extraProperty1: MaterialProperty, extraProperty2: MaterialProperty): Rect\r\n        /** Method for showing a texture property control with additional inlined properites.\r\n         * @param label The label used for the texture property.\r\n         * @param textureProp The texture property.\r\n         * @param extraProperty1 First optional property inlined after the texture property.\r\n         * @param extraProperty2 Second optional property inlined after the extraProperty1.\r\n         * @returns Returns the Rect used. \r\n         */\r\n        TexturePropertySingleLine(label: GUIContent, textureProp: MaterialProperty, extraProperty1: MaterialProperty): Rect\r\n        /** Method for showing a texture property control with additional inlined properites.\r\n         * @param label The label used for the texture property.\r\n         * @param textureProp The texture property.\r\n         * @param extraProperty1 First optional property inlined after the texture property.\r\n         * @param extraProperty2 Second optional property inlined after the extraProperty1.\r\n         * @returns Returns the Rect used. \r\n         */\r\n        TexturePropertySingleLine(label: GUIContent, textureProp: MaterialProperty): Rect\r\n        /** Method for showing a texture property control with a HDR color field and its color brightness float field.\r\n         * @param label The label used for the texture property.\r\n         * @param textureProp The texture property.\r\n         * @param colorProperty The color property (will be treated as a HDR color).\r\n         * @param showAlpha If false then the alpha channel information will be hidden in the GUI.\r\n         * @returns Return the Rect used. \r\n         */\r\n        TexturePropertyWithHDRColor(label: GUIContent, textureProp: MaterialProperty, colorProperty: MaterialProperty, showAlpha: boolean): Rect\r\n        /** Method for showing a compact layout of properties.\r\n         * @param label The label used for the texture property.\r\n         * @param textureProp The texture property.\r\n         * @param extraProperty1 First extra property inlined after the texture property.\r\n         * @param label2 Label for the second extra property (on a new line and indented).\r\n         * @param extraProperty2 Second property on a new line below the texture.\r\n         * @returns Returns the Rect used. \r\n         */\r\n        TexturePropertyTwoLines(label: GUIContent, textureProp: MaterialProperty, extraProperty1: MaterialProperty, label2: GUIContent, extraProperty2: MaterialProperty): Rect\r\n        /** TODO.\r\n         */\r\n        static TextureScaleOffsetProperty(position: Rect, scaleOffset: Vector4, partOfTexturePropertyControl: boolean): Vector4\r\n        /** TODO.\r\n         */\r\n        static TextureScaleOffsetProperty(position: Rect, scaleOffset: Vector4): Vector4\r\n        /** Calculate height needed for the property, ignoring custom drawers.\r\n         */\r\n        static GetDefaultPropertyHeight(prop: MaterialProperty): number\r\n        /** Returns a properly set global illlumination flag based on the passed in flag and the given color.\r\n         * @param col Emission color.\r\n         * @param flags Current global illumination flag.\r\n         * @returns The fixed up flag. \r\n         */\r\n        static FixupEmissiveFlag(col: Color, flags: any): any\r\n        /** Properly sets up the globalIllumination flag on the given Material depending on the current flag's state and the material's emission property.\r\n         * @param mat The material to be fixed up.\r\n         */\r\n        static FixupEmissiveFlag(mat: Material): void\r\n        /** Get shader property information of the passed materials.\r\n         */\r\n        static GetMaterialProperties(mats: Array<Object>): Array<MaterialProperty>\r\n        /** Get information about a single shader property.\r\n         * @param mats Selected materials.\r\n         * @param name Property name.\r\n         * @param propertyIndex Property index.\r\n         */\r\n        static GetMaterialProperty(mats: Array<Object>, name: string): MaterialProperty\r\n        /** Get information about a single shader property.\r\n         * @param mats Selected materials.\r\n         * @param name Property name.\r\n         * @param propertyIndex Property index.\r\n         */\r\n        static GetMaterialProperty(mats: Array<Object>, propertyIndex: number): MaterialProperty\r\n        static PrepareMaterialPropertiesForAnimationMode(properties: Array<MaterialProperty>, isMaterialEditable: boolean): Renderer\r\n        /** Apply initial MaterialPropertyDrawer values.\r\n         */\r\n        static ApplyMaterialPropertyDrawers(material: Material): void\r\n        /** Apply initial MaterialPropertyDrawer values.\r\n         */\r\n        static ApplyMaterialPropertyDrawers(targets: Array<Object>): void\r\n        /** Utility method for GUI layouting ShaderGUI.\r\n         * @param r Field Rect.\r\n         * @returns A sub rect of the input Rect. \r\n         */\r\n        static GetRightAlignedFieldRect(r: Rect): Rect\r\n        /** Utility method for GUI layouting ShaderGUI.\r\n         * @param r Field Rect.\r\n         * @returns A sub rect of the input Rect. \r\n         */\r\n        static GetLeftAlignedFieldRect(r: Rect): Rect\r\n        /** Utility method for GUI layouting ShaderGUI.\r\n         * @param r Field Rect.\r\n         * @returns A sub rect of the input Rect. \r\n         */\r\n        static GetFlexibleRectBetweenLabelAndField(r: Rect): Rect\r\n        /** Utility method for GUI layouting ShaderGUI. Used e.g for the rect after a left aligned Color field.\r\n         * @param r Field Rect.\r\n         * @returns A sub rect of the input Rect. \r\n         */\r\n        static GetFlexibleRectBetweenFieldAndRightEdge(r: Rect): Rect\r\n        /** Utility method for GUI layouting ShaderGUI. This is the rect after the label which can be used for multiple properties. The input rect can be fetched by calling: EditorGUILayout.GetControlRect.\r\n         * @param r Line Rect.\r\n         * @returns A sub rect of the input Rect. \r\n         */\r\n        static GetRectAfterLabelWidth(r: Rect): Rect\r\n        /** Is the current material expanded.\r\n         */\r\n        readonly isVisible: boolean\r\n        /** Returns the custom ShaderGUI implemented by the shader.\r\n         */\r\n        readonly customShaderGUI: ShaderGUI\r\n        /** Useful for indenting shader properties that need the same indent as mini texture field.\r\n         */\r\n        static readonly kMiniTextureFieldLabelIndentLevel: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Rect, GUIContent } from \"UnityEngine\";\r\n    /** Base class to derive custom material property drawers from.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class MaterialPropertyDrawer extends Object {\r\n        OnGUI(position: Rect, prop: MaterialProperty, label: GUIContent, editor: MaterialEditor): void\r\n        /** Override this method to make your own GUI for the property.\r\n         * @param position Rectangle on the screen to use for the property GUI.\r\n         * @param prop The MaterialProperty to make the custom GUI for.\r\n         * @param label The label of this property.\r\n         * @param editor Current material editor.\r\n         */\r\n        OnGUI(position: Rect, prop: MaterialProperty, label: string, editor: MaterialEditor): void\r\n        /** Override this method to specify how tall the GUI for this property is in pixels.\r\n         * @param prop The MaterialProperty to make the custom GUI for.\r\n         * @param label The label of this property.\r\n         * @param editor Current material editor.\r\n         */\r\n        GetPropertyHeight(prop: MaterialProperty, label: string, editor: MaterialEditor): number\r\n        /** Apply extra initial values to the material.\r\n         * @param prop The MaterialProperty to apply values for.\r\n         */\r\n        Apply(prop: MaterialProperty): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Camera, Color, Behaviour, Rect, GUIStyle, Texture, Texture2D, GameObject, Object as Object1, Vector3, Quaternion, Material, Transform, Matrix4x4 } from \"UnityEngine\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class PreviewRenderUtility extends Object {\r\n        constructor(renderFullScene: boolean, pixelPerfect: boolean)\r\n        constructor(renderFullScene: boolean)\r\n        constructor()\r\n        Cleanup(): void\r\n        BeginPreview(r: Rect, previewBackground: GUIStyle): void\r\n        BeginStaticPreview(r: Rect): void\r\n        GetScaleFactor(width: number, height: number): number\r\n        EndPreview(): Texture\r\n        EndAndDrawPreview(r: Rect): void\r\n        EndStaticPreview(): Texture2D\r\n        AddSingleGO(go: GameObject): void\r\n        InstantiatePrefabInScene(prefab: GameObject): GameObject\r\n        DrawMesh(mesh: any, pos: Vector3, scale: Vector3, rot: Quaternion, mat: Material, subMeshIndex: number, customProperties: any, probeAnchor: Transform, useLightProbe: boolean): void\r\n        DrawMesh(mesh: any, pos: Vector3, rot: Quaternion, mat: Material, subMeshIndex: number, customProperties: any, probeAnchor: Transform, useLightProbe: boolean): void\r\n        DrawMesh(mesh: any, m: Matrix4x4, mat: Material, subMeshIndex: number, customProperties: any, probeAnchor: Transform, useLightProbe: boolean): void\r\n        DrawMesh(mesh: any, pos: Vector3, rot: Quaternion, mat: Material, subMeshIndex: number, customProperties: any, probeAnchor: Transform): void\r\n        DrawMesh(mesh: any, pos: Vector3, rot: Quaternion, mat: Material, subMeshIndex: number, customProperties: any): void\r\n        DrawMesh(mesh: any, matrix: Matrix4x4, mat: Material, subMeshIndex: number, customProperties: any): void\r\n        DrawMesh(mesh: any, pos: Vector3, rot: Quaternion, mat: Material, subMeshIndex: number): void\r\n        DrawMesh(mesh: any, matrix: Matrix4x4, mat: Material, subMeshIndex: number): void\r\n        Render(allowScriptableRenderPipeline: boolean, updatefov: boolean): void\r\n        readonly camera: Camera\r\n        cameraFieldOfView: number\r\n        ambientColor: Color\r\n        readonly lights: Array<any>\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Rect, GUIStyle, Material, Object as Object1 } from \"UnityEngine\";\r\n    /** Abstract class to derive from for defining custom GUI for shader properties and for extending the material preview.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class ShaderGUI extends Object {\r\n        /** To define a custom shader GUI use the methods of materialEditor to render controls for the properties array.\r\n         * @param materialEditor The MaterialEditor that are calling this OnGUI (the 'owner').\r\n         * @param properties Material properties of the current selected shader.\r\n         */\r\n        OnGUI(materialEditor: MaterialEditor, properties: Array<MaterialProperty>): void\r\n        /** Override for extending the rendering of the Preview area or completly replace the preview (by not calling base.OnMaterialPreviewGUI).\r\n         * @param materialEditor The MaterialEditor that are calling this method (the 'owner').\r\n         * @param r Preview rect.\r\n         * @param background Style for the background.\r\n         */\r\n        OnMaterialPreviewGUI(materialEditor: MaterialEditor, r: Rect, background: GUIStyle): void\r\n        OnMaterialInteractivePreviewGUI(materialEditor: MaterialEditor, r: Rect, background: GUIStyle): void\r\n        /** Override for extending the functionality of the toolbar of the preview area or completly replace the toolbar by not calling base.OnMaterialPreviewSettingsGUI.\r\n         * @param materialEditor The MaterialEditor that are calling this method (the 'owner').\r\n         */\r\n        OnMaterialPreviewSettingsGUI(materialEditor: MaterialEditor): void\r\n        /** This method is called when the ShaderGUI is being closed.\r\n         */\r\n        OnClosed(material: Material): void\r\n        /** This method is called when a new shader has been selected for a Material.\r\n         * @param material The material the newShader should be assigned to.\r\n         * @param oldShader Previous shader.\r\n         * @param newShader New shader to assign to the material.\r\n         */\r\n        AssignNewShaderToMaterial(material: Material, oldShader: any, newShader: any): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum BodyPart {\r\n        Avatar = 0,\r\n        Body = 1,\r\n        Head = 2,\r\n        LeftArm = 3,\r\n        LeftFingers = 4,\r\n        RightArm = 5,\r\n        RightFingers = 6,\r\n        LeftLeg = 7,\r\n        RightLeg = 8,\r\n        Last = 9,\r\n        None = -1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum BoneState {\r\n        None = 0,\r\n        NotFound = 1,\r\n        Duplicate = 2,\r\n        InvalidHierarchy = 3,\r\n        BoneLenghtIsZero = 4,\r\n        Valid = 5,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Texture2D } from \"UnityEngine\";\r\n    /** Icon slot container.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class PlatformIcon extends Object {\r\n        /** Retrieve the texture which is currently assigned to the specified layer.\r\n         * @param layer Cannot be larger than PlatformIcon.maxLayerCount.\r\n         */\r\n        GetTexture(layer: number): Texture2D\r\n        GetTextures(): Array<Texture2D>\r\n        /** Assign a texture to the specified layer.\r\n         * @param layer Cannot be larger than PlatformIcon.maxLayerCount.\r\n         */\r\n        SetTexture(texture: Texture2D, layer: number): void\r\n        /** Assign all available icon layers.\r\n         * @param textures Must be an array of size PlatformIcon.maxLayerCount.\r\n         */\r\n        SetTextures(...textures: Texture2D[]): void\r\n        toString(): string\r\n        protected constructor()\r\n        /** The number of texture layers the icon slot currently contains.\r\n         */\r\n        layerCount: number\r\n        /** The maximum number of texture layers required by the icon slot.\r\n         */\r\n        readonly maxLayerCount: number\r\n        /** The minimum number of texture layers required by the icon slot.\r\n         */\r\n        readonly minLayerCount: number\r\n        /** The width of the icon in pixels.\r\n         */\r\n        readonly width: number\r\n        /** The height of the icon in pixels.\r\n         */\r\n        readonly height: number\r\n        /** The PlatformIconKind is specific to the target platform.\r\n         */\r\n        readonly kind: PlatformIconKind\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Icon kind wrapper.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class PlatformIconKind extends Object {\r\n        Equals(obj: Object): boolean\r\n        GetHashCode(): number\r\n        toString(): string\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    import { GameObject } from \"UnityEngine\";\r\n    namespace PrefabUtility {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class EditPrefabContentsScope extends ValueType {\r\n            constructor(assetPath: string)\r\n            Dispose(): void\r\n            readonly assetPath: string\r\n            readonly prefabContentsRoot: GameObject\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Enum used to determine how a Prefab should be unpacked.\r\n     */\r\n    enum PrefabUnpackMode {\r\n        /** Use this mode to only unpack the outermost layer of a Prefab.\r\n         */\r\n        OutermostRoot = 0,\r\n        /** Use this to strip away all Prefab information from a Prefab instance.\r\n         */\r\n        Completely = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Object as Object1 } from \"UnityEngine\";\r\n    /** Defines a single modified property.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class PropertyModification extends Object {\r\n        constructor()\r\n        /** Object that will be modified.\r\n         */\r\n        target: Object1\r\n        /** Property path of the property being modified (Matches as SerializedProperty.propertyPath).\r\n         */\r\n        propertyPath: string\r\n        /** The value being applied.\r\n         */\r\n        value: string\r\n        /** The value being applied when it is a object reference (which can not be represented as a string).\r\n         */\r\n        objectReference: Object1\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum SaveType {\r\n        Binary = 0,\r\n        Text = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, ValueType, Array } from \"System\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    /** The Progress utility class reports the progress of asynchronous tasks to Unity.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class Progress extends Object {\r\n        static Start(name: string, description: string, options: Progress.Options, parentId: number): number\r\n        static Finish(id: number, status: Progress.Status): void\r\n        /** Finishes and removes an active progress indicator.\r\n         * @param id The progress indicator's unique ID.\r\n         * @param forceSynchronous When you set this parameter to true it forces this method to remove the progress indicator synchronously.\r\n         * @returns -1 if the progress indicator is removed. Otherwise, returns the progress indicator's ID. \r\n         */\r\n        static Remove(id: number, forceSynchronous: boolean): number\r\n        /** Finishes and removes an active progress indicator.\r\n         * @param id The progress indicator's unique ID.\r\n         * @param forceSynchronous When you set this parameter to true it forces this method to remove the progress indicator synchronously.\r\n         * @returns -1 if the progress indicator is removed. Otherwise, returns the progress indicator's ID. \r\n         */\r\n        static Remove(id: number): number\r\n        /** Reports a running progress indicator's current status.\r\n         * @param id The progress indicator's unique ID.\r\n         * @param progress A new progress value between 0 and 1.\r\n         * @param description An updated description of the progress indicator. If the the progress status has not changed, or you do not set a description, this is null. To clear the current progress description, pass an empty string such as \"\".\r\n         * @param currentStep An updated current step.\r\n         * @param totalSteps An updated total number of steps, from start to finish.\r\n         */\r\n        static Report(id: number, currentStep: number, totalSteps: number, description: string): void\r\n        /** Reports a running progress indicator's current status.\r\n         * @param id The progress indicator's unique ID.\r\n         * @param progress A new progress value between 0 and 1.\r\n         * @param description An updated description of the progress indicator. If the the progress status has not changed, or you do not set a description, this is null. To clear the current progress description, pass an empty string such as \"\".\r\n         * @param currentStep An updated current step.\r\n         * @param totalSteps An updated total number of steps, from start to finish.\r\n         */\r\n        static Report(id: number, currentStep: number, totalSteps: number): void\r\n        /** Reports a running progress indicator's current status.\r\n         * @param id The progress indicator's unique ID.\r\n         * @param progress A new progress value between 0 and 1.\r\n         * @param description An updated description of the progress indicator. If the the progress status has not changed, or you do not set a description, this is null. To clear the current progress description, pass an empty string such as \"\".\r\n         * @param currentStep An updated current step.\r\n         * @param totalSteps An updated total number of steps, from start to finish.\r\n         */\r\n        static Report(id: number, progress: number, description: string): void\r\n        /** Reports a running progress indicator's current status.\r\n         * @param id The progress indicator's unique ID.\r\n         * @param progress A new progress value between 0 and 1.\r\n         * @param description An updated description of the progress indicator. If the the progress status has not changed, or you do not set a description, this is null. To clear the current progress description, pass an empty string such as \"\".\r\n         * @param currentStep An updated current step.\r\n         * @param totalSteps An updated total number of steps, from start to finish.\r\n         */\r\n        static Report(id: number, progress: number): void\r\n        /** Cancels a runnning progress indicator, and invokes the cancel callback for the associated task.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns True if the associated task is cancelled, false if it cannot be cancelled. \r\n         */\r\n        static Cancel(id: number): boolean\r\n        static RegisterCancelCallback(id: number, callback: () => boolean): void\r\n        /** Unregisters a previously registered progress cancellation callback.\r\n         * @param id The progress indicator's unique ID.\r\n         */\r\n        static UnregisterCancelCallback(id: number): void\r\n        /** Pauses a runnning progress indicator, and invokes the pause callback for its task.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns True if the task is paused, false if it cannot be paused. \r\n         */\r\n        static Pause(id: number): boolean\r\n        /** Resumes a paused progress indicator, and invokes the pause callback for the associated task.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns True if the task resumes, false if it cannot resume. \r\n         */\r\n        static Resume(id: number): boolean\r\n        static RegisterPauseCallback(id: number, callback: (arg: boolean) => boolean): void\r\n        /** Unregisters a previously registered progress pause callback.\r\n         * @param id The progress indicator's unique ID.\r\n         */\r\n        static UnregisterPauseCallback(id: number): void\r\n        static GetCount(): number\r\n        static GetCountPerStatus(): Array<number>\r\n        /** Gets a progress indicator's progress.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns The currrent progress. \r\n         */\r\n        static GetProgress(id: number): number\r\n        /** Gets the current step for a progress indicator.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns The current step. \r\n         */\r\n        static GetCurrentStep(id: number): number\r\n        /** Gets the total number of steps, from start to finish, for a progress indicator.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns The number of steps. \r\n         */\r\n        static GetTotalSteps(id: number): number\r\n        /** Gets a progress indicator's name.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns The matching progress indicator's name. \r\n         */\r\n        static GetName(id: number): string\r\n        /** Gets a progress indicator's description.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns The description, if one exists. \r\n         */\r\n        static GetDescription(id: number): string\r\n        /** Sets the progress indicator's description. To clear the description pass null.\r\n         * @param id The progress indicator's unique ID.\r\n         * @param description The progress indicator's new description.\r\n         */\r\n        static SetDescription(id: number, description: string): void\r\n        /** Gets the timestamp of when the progress indicator started.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns The progress indicator's start timestamp. \r\n         */\r\n        static GetStartDateTime(id: number): number\r\n        /** Gets the time that the progress indicator last changed, or finished.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns The timestamp of the progress indicator's last update. \r\n         */\r\n        static GetUpdateDateTime(id: number): number\r\n        /** Gets the unique ID of the progress indicator's parent, if any.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns The unique ID of the progress indicator's parent. If the progress indicator is not a child of any other progress indicators, returns -1. \r\n         */\r\n        static GetParentId(id: number): number\r\n        /** Finds a progress indicator's unique ID using its index in the set of all available progress indicators.\r\n         * @param index The valid index for a progress indicator.\r\n         * @returns The progress indicator's unique ID, or -1 if the unique ID is not available. \r\n         */\r\n        static GetId(index: number): number\r\n        /** Indicates whether you can cancel the progress indicator's associated task.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns True if you can cancel the task, false otherwise. \r\n         */\r\n        static IsCancellable(id: number): boolean\r\n        /** Indicates whether you can pause the progress indicator's task.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns True if you can pause the task, false otherwise. \r\n         */\r\n        static IsPausable(id: number): boolean\r\n        /** Gets the progress indicator's status.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns The progress indicator's current status. \r\n         */\r\n        static GetStatus(id: number): Progress.Status\r\n        /** Gets the options that you specified when you started the progress indicator.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns The progress indicator's option flags. \r\n         */\r\n        static GetOptions(id: number): Progress.Options\r\n        static SetTimeDisplayMode(id: number, displayMode: Progress.TimeDisplayMode): void\r\n        /** Sets the progress indicator's remaining time, in seconds.\r\n         * @param id The progress indicator's unique ID.\r\n         * @param seconds The progress indicator's remaining time, in seconds.\r\n         */\r\n        static SetRemainingTime(id: number, seconds: number): void\r\n        /** Sets a progress indicator's priority.\r\n         * @param id The progress indicator's unique ID.\r\n         * @param priority The priority.\r\n         */\r\n        static SetPriority(id: number, priority: number): void\r\n        static SetPriority(id: number, priority: Progress.Priority): void\r\n        /** Get a progress indicator's time display mode.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns The progress indicator's time display mode. \r\n         */\r\n        static GetTimeDisplayMode(id: number): Progress.TimeDisplayMode\r\n        /** Checks whether a progress indicator with the specified ID exists.\r\n         * @param id The unique ID to search for.\r\n         * @returns True if the progress indicator exists, false otherwise. \r\n         */\r\n        static Exists(id: number): boolean\r\n        /** Gets a progress indicator's remaining time, in seconds.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns The number of seconds remaining. \r\n         */\r\n        static GetRemainingTime(id: number): number\r\n        /** Gets a progress indicator's priority.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns The priority. \r\n         */\r\n        static GetPriority(id: number): number\r\n        /** Resets the computation of a progress indicator's remaining time.\r\n         * @param id The progress indicator's unique ID.\r\n         */\r\n        static ClearRemainingTime(id: number): void\r\n        /** Sets the label that displays a progress indicator's steps.\r\n         * @param id The progress indicator's unique ID.\r\n         * @param label The steps label.\r\n         */\r\n        static SetStepLabel(id: number, label: string): void\r\n        /** Gets the label that displays a progress indicator's steps.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns The step label. \r\n         */\r\n        static GetStepLabel(id: number): string\r\n        /** Opens the progress window for background tasks.\r\n         * @param shouldReposition To place the window in the bottom right corner of the main Editor window, pass True. To restore the last window position, pass False.\r\n         */\r\n        static ShowDetails(shouldReposition: boolean): void\r\n        static EnumerateItems(): any\r\n        /** Gets information about a progress indicator.\r\n         * @param id The progress indicator's unique ID.\r\n         * @returns The progress indicator's data structure. \r\n         */\r\n        static GetProgressById(id: number): Progress.Item\r\n        static GetRunningProgressCount(): number\r\n        /** Returns true if there is at least one running progress indicator, false otherwise.\r\n         */\r\n        static readonly running: boolean\r\n        /** Returns the global average progression of all running tasks.\r\n         */\r\n        static readonly globalProgress: number\r\n        /** Returns the maximum time remaining for all running progress indicators.\r\n         */\r\n        static readonly globalRemainingTime: any\r\n        static added(op: \"add\" | \"remove\", fn: (obj: Array<Progress.Item>) => void): void\r\n        static updated(op: \"add\" | \"remove\", fn: (obj: Array<Progress.Item>) => void): void\r\n        static removed(op: \"add\" | \"remove\", fn: (obj: Array<Progress.Item>) => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace Progress {\r\n        enum Status {\r\n            Running = 0,\r\n            Succeeded = 1,\r\n            Failed = 2,\r\n            Canceled = 3,\r\n            Paused = 4,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace Progress {\r\n        enum Options {\r\n            None = 0,\r\n            Sticky = 1,\r\n            Indefinite = 2,\r\n            Synchronous = 4,\r\n            Managed = 8,\r\n            Unmanaged = 16,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace Progress {\r\n        enum TimeDisplayMode {\r\n            NoTimeShown = 0,\r\n            ShowRunningTime = 1,\r\n            ShowRemainingTime = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace Progress {\r\n        enum Priority {\r\n            Unresponsive = 0,\r\n            Idle = 1,\r\n            Low = 2,\r\n            Normal = 6,\r\n            High = 10,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, DateTime, ValueType } from \"System\";\r\n    namespace Progress {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class Item extends Object {\r\n            Report(newCurrentStep: number, newTotalSteps: number, newDescription: string): void\r\n            Report(newCurrentStep: number, newTotalSteps: number): void\r\n            Report(newProgress: number, newDescription: string): void\r\n            Report(newProgress: number): void\r\n            Cancel(): boolean\r\n            Pause(): boolean\r\n            Resume(): boolean\r\n            Finish(finishedStatus: Progress.Status): void\r\n            Remove(): number\r\n            RegisterCancelCallback(callback: () => boolean): void\r\n            UnregisterCancelCallback(): void\r\n            RegisterPauseCallback(callback: (arg: boolean) => boolean): void\r\n            UnregisterPauseCallback(): void\r\n            SetDescription(newDescription: string): void\r\n            SetTimeDisplayMode(mode: Progress.TimeDisplayMode): void\r\n            SetRemainingTime(seconds: number): void\r\n            SetPriority(priority: number): void\r\n            SetPriority(priority: Progress.Priority): void\r\n            ClearRemainingTime(): void\r\n            SetStepLabel(label: string): void\r\n            protected constructor()\r\n            readonly name: string\r\n            readonly description: string\r\n            readonly id: number\r\n            readonly progress: number\r\n            readonly currentStep: number\r\n            readonly totalSteps: number\r\n            readonly stepLabel: string\r\n            readonly parentId: number\r\n            readonly startTime: DateTime\r\n            readonly updateTime: DateTime\r\n            readonly status: Progress.Status\r\n            readonly options: Progress.Options\r\n            readonly timeDisplayMode: Progress.TimeDisplayMode\r\n            readonly priority: number\r\n            readonly remainingTime: any\r\n            readonly finished: boolean\r\n            readonly running: boolean\r\n            readonly paused: boolean\r\n            readonly responding: boolean\r\n            readonly cancellable: boolean\r\n            readonly pausable: boolean\r\n            readonly indefinite: boolean\r\n            readonly elapsedTime: number\r\n            readonly exists: boolean\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Object as Object1, Texture2D } from \"UnityEngine\";\r\n    import { EndNameEditAction } from \"UnityEditor.ProjectWindowCallback\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ProjectWindowUtil extends Object {\r\n        constructor()\r\n        static CreateNewGUISkin(): void\r\n        static CreateAsset(asset: Object1, pathName: string): void\r\n        static CreateFolder(): void\r\n        static CreateScene(): void\r\n        static CreateAssetWithContent(filename: string, content: string, icon: Texture2D): void\r\n        static CreateScriptAssetFromTemplateFile(templatePath: string, defaultNewFileName: string): void\r\n        static ShowCreatedAsset(o: Object1): void\r\n        static StartNameEditingIfProjectWindowExists(instanceID: number, endAction: EndNameEditAction, pathName: string, icon: Texture2D, resourceFile: string): void\r\n        static GetAncestors(instanceID: number): Array<number>\r\n        static IsFolder(instanceID: number): boolean\r\n        static GetContainingFolder(path: string): string\r\n        static GetBaseFolders(folders: Array<string>): Array<string>\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SearchableEditorWindow extends EditorWindow {\r\n        constructor()\r\n        OnEnable(): void\r\n        OnDisable(): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace SearchableEditorWindow {\r\n        enum SearchMode {\r\n            All = 0,\r\n            Name = 1,\r\n            Type = 2,\r\n            Label = 3,\r\n            AssetBundleName = 4,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace SearchableEditorWindow {\r\n        enum SearchModeHierarchyWindow {\r\n            All = 0,\r\n            Name = 1,\r\n            Type = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    /** Default definition for the Lighting Explorer. Can be overridden completely or partially.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class DefaultLightingExplorerExtension extends Object implements ILightingExplorerExtension {\r\n        constructor()\r\n        GetContentTabs(): Array<LightingExplorerTab>\r\n        OnEnable(): void\r\n        OnDisable(): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Object as Object1 } from \"UnityEngine\";\r\n    /** Create custom tabs for the Lighting Explorer.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class LightingExplorerTab extends Object {\r\n        constructor(title: string, objects: () => Array<Object1>, columns: () => Array<LightingExplorerTableColumn>)\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { GUIContent, Rect } from \"UnityEngine\";\r\n    /** This is used when defining how a column should look and behave in the Lighting Explorer.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class LightingExplorerTableColumn extends Object {\r\n        constructor(type: LightingExplorerTableColumn.DataType, headerContent: GUIContent, propertyName: string, width: number, onGUIDelegate: (r: Rect, prop: SerializedProperty, dependencies: Array<SerializedProperty>) => void, compareDelegate: (lhs: SerializedProperty, rhs: SerializedProperty) => number, copyDelegate: (target: SerializedProperty, source: SerializedProperty) => void, dependencyIndices: Array<number>)\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace LightingExplorerTableColumn {\r\n        enum DataType {\r\n            Name = 0,\r\n            Checkbox = 1,\r\n            Enum = 2,\r\n            Int = 3,\r\n            Float = 4,\r\n            Color = 5,\r\n            Custom = 20,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** An attribute to mark an extension class for the Lighting Explorer. Supports one extension per render pipeline.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class LightingExplorerExtensionAttribute extends Object {\r\n        constructor(renderPipeline: any)\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Array } from \"System\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface ILightingExplorerExtension {\r\n        GetContentTabs(): Array<LightingExplorerTab>\r\n        OnEnable(): void\r\n        OnDisable(): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Base class for the Inspector that overrides the Environment section of the Lighting window.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class LightingWindowEnvironmentSection extends Object {\r\n        OnEnable(): void\r\n        OnDisable(): void\r\n        OnInspectorGUI(): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    /** Displays the Physics Debug Visualization options.\n\nThe Physics Debug Visualization is only displayed if this window is visible.\n\nSee Also: PhysicsVisualizationSettings.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class PhysicsDebugWindow extends EditorWindow {\r\n        constructor()\r\n        OnEnable(): void\r\n        OnDisable(): void\r\n        static ShowWindow(): PhysicsDebugWindow\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Object as Object1, GameObject } from \"UnityEngine\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class SceneModeUtility extends Object {\r\n        static SearchForType(type: any): void\r\n        static SearchBar(...types: any[]): any\r\n        static StaticFlagField(label: string, property: SerializedProperty, flag: number): boolean\r\n        static SetStaticFlags(targetObjects: Array<Object1>, changedFlags: number, flagValue: boolean): boolean\r\n        static GetObjects(gameObjects: Array<Object1>, includeChildren: boolean): Array<GameObject>\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Object } from \"System\";\r\n    namespace SceneView {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class CameraMode extends ValueType {\r\n            constructor()\r\n            Equals(otherObject: Object): boolean\r\n            GetHashCode(): number\r\n            toString(): string\r\n            static op_Equality(a: SceneView.CameraMode, z: SceneView.CameraMode): boolean\r\n            static op_Inequality(a: SceneView.CameraMode, z: SceneView.CameraMode): boolean\r\n            // js_op_overloading: static ==(a: SceneView.CameraMode, z: SceneView.CameraMode): boolean\r\n            drawMode: DrawCameraMode\r\n            name: string\r\n            section: string\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    namespace SceneView {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class SceneViewState extends Object {\r\n            constructor(other: SceneView.SceneViewState)\r\n            constructor()\r\n            SetAllEnabled(value: boolean): void\r\n            alwaysRefresh: boolean\r\n            readonly fogEnabled: boolean\r\n            readonly alwaysRefreshEnabled: boolean\r\n            readonly skyboxEnabled: boolean\r\n            readonly flaresEnabled: boolean\r\n            readonly imageEffectsEnabled: boolean\r\n            readonly particleSystemsEnabled: boolean\r\n            readonly visualEffectGraphsEnabled: boolean\r\n            readonly allEnabled: boolean\r\n            fxEnabled: boolean\r\n            showFog: boolean\r\n            showSkybox: boolean\r\n            showFlares: boolean\r\n            showImageEffects: boolean\r\n            showParticleSystems: boolean\r\n            showVisualEffectGraphs: boolean\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    namespace SceneView {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class CameraSettings extends Object {\r\n            constructor()\r\n            speed: number\r\n            speedNormalized: number\r\n            speedMin: number\r\n            speedMax: number\r\n            easingEnabled: boolean\r\n            easingDuration: number\r\n            accelerationEnabled: boolean\r\n            fieldOfView: number\r\n            nearClip: number\r\n            farClip: number\r\n            dynamicClip: boolean\r\n            occlusionCulling: boolean\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Rect } from \"UnityEngine\";\r\n    /** Base class to derive custom decorator drawers from.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class DecoratorDrawer extends GUIDrawer {\r\n        /** Override this method to make your own GUI for the decorator.\nSee DecoratorDrawer for an example of how to use this.\r\n         * @param position Rectangle on the screen to use for the decorator GUI.\r\n         */\r\n        OnGUI(position: Rect): void\r\n        GetHeight(): number\r\n        CanCacheInspectorGUI(): boolean\r\n        /** The PropertyAttribute for the decorator. (Read Only)\r\n         */\r\n        readonly attribute: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Base class for PropertyDrawer and DecoratorDrawer.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class GUIDrawer extends Object {\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Rect, GUIContent } from \"UnityEngine\";\r\n    /** Base class to derive custom property drawers from. Use this to create custom drawers for your own Serializable classes or for script variables with custom PropertyAttributes.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class PropertyDrawer extends GUIDrawer {\r\n        /** Override this method to make your own IMGUI based GUI for the property.\r\n         * @param position Rectangle on the screen to use for the property GUI.\r\n         * @param property The SerializedProperty to make the custom GUI for.\r\n         * @param label The label of this property.\r\n         */\r\n        OnGUI(position: Rect, property: SerializedProperty, label: GUIContent): void\r\n        /** Override this method to make your own UIElements based GUI for the property.\r\n         * @param property The SerializedProperty to make the custom GUI for.\r\n         * @returns The element containing the custom GUI. \r\n         */\r\n        CreatePropertyGUI(property: SerializedProperty): any\r\n        /** Override this method to specify how tall the GUI for this field is in pixels.\r\n         * @param property The SerializedProperty to make the custom GUI for.\r\n         * @param label The label of this property.\r\n         * @returns The height in pixels. \r\n         */\r\n        GetPropertyHeight(property: SerializedProperty, label: GUIContent): number\r\n        /** Override this method to determine whether the inspector GUI for your property can be cached.\r\n         * @param property The SerializedProperty to make the custom GUI for.\r\n         * @returns Whether the drawer's UI can be cached. \r\n         */\r\n        CanCacheInspectorGUI(property: SerializedProperty): boolean\r\n        /** The PropertyAttribute for the property. Not applicable for custom class drawers. (Read Only)\r\n         */\r\n        readonly attribute: any\r\n        /** The reflection FieldInfo for the member this property represents. (Read Only)\r\n         */\r\n        readonly fieldInfo: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Sets the scope of a SettingsProvider. The Scope determines where it appears in the UI. For example, whether it appears with the Project settings in the Settings window, or in the Preferences window, or in both windows.\r\n     */\r\n    enum SettingsScope {\r\n        /** The SettingsProvider appears only in the Preferences window.\r\n         */\r\n        User = 0,\r\n        /** The SettingsProvider appears only in the Project Settings window.\r\n         */\r\n        Project = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    /** SettingsProvider is the configuration class that specifies how a Project setting or a preference should appear in the Settings or Preferences window.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SettingsProvider extends Object {\r\n        constructor(path: string, scopes: SettingsScope, keywords: IEnumerable<string>)\r\n        /** Use this function to implement a handler for when the user clicks on the Settings in the Settings window. You can fetch a settings Asset or set up UIElements UI from this function.\r\n         * @param searchContext Search context in the search box on the Settings window.\r\n         * @param rootElement Root of the UIElements tree. If you add to this root, the SettingsProvider uses UIElements instead of calling SettingsProvider.OnGUI to build the UI. If you do not add to this VisualElement, then you must use the IMGUI to build the UI.\r\n         */\r\n        OnActivate(searchContext: string, rootElement: any): void\r\n        OnDeactivate(): void\r\n        /** Checks whether the SettingsProvider should appear when the user types something in the Settings window search box. SettingsProvider tries to match the search terms (even partially) to any of the SettingsProvider.keywords. The search is case insensitive.\r\n         * @param searchContext Search terms that the user entered in the search box on the Settings window.\r\n         * @returns True if the SettingsProvider matched the search term and if it should appear. \r\n         */\r\n        HasSearchInterest(searchContext: string): boolean\r\n        /** Use this function to draw the UI based on IMGUI. This assumes you haven't added any children to the rootElement passed to the OnActivate function.\r\n         * @param searchContext Search context for the Settings window. Used to show or hide relevant properties.\r\n         */\r\n        OnGUI(searchContext: string): void\r\n        OnTitleBarGUI(): void\r\n        OnFooterBarGUI(): void\r\n        OnInspectorUpdate(): void\r\n        Repaint(): void\r\n        /** Extract search keywords from from the serialized properties of a SerializedObject.\r\n         * @param serializedObject Object to extract properties from.\r\n         * @returns Returns the list of keywords. \r\n         */\r\n        static GetSearchKeywordsFromSerializedObject(serializedObject: SerializedObject): IEnumerable<string>\r\n        /** Extract search keywords from the serialized properties of an Asset at a specific path.\r\n         * @param path Path of the Asset on disk.\r\n         * @returns Returns the list of keywords. \r\n         */\r\n        static GetSearchKeywordsFromPath(path: string): IEnumerable<string>\r\n        /** Gets or sets the display name of the SettingsProvider as it appears in the Settings window. If not set, the Settings window uses last token of SettingsProvider.settingsPath instead.\r\n         */\r\n        label: string\r\n        /** Gets Path used to place the SettingsProvider in the tree view of the Settings window. The path should be unique among all other settings paths and should use \"/\" as its separator.\r\n         */\r\n        readonly settingsPath: string\r\n        /** Gets the Scope of the SettingsProvider. The Scope determines whether the SettingsProvider appears in the Preferences window (SettingsScope.User) or the Settings window (SettingsScope.Project).\r\n         */\r\n        readonly scope: SettingsScope\r\n        /** Gets or sets the list of keywords to compare against what the user is searching for. When the user enters values in the search box on the Settings window, SettingsProvider.HasSearchInterest tries to match those keywords to this list.\r\n         */\r\n        keywords: IEnumerable<string>\r\n        guiHandler(op: \"get\"): (obj: string) => void\r\n        guiHandler(op: \"add\" | \"remove\" | \"set\", fn?: (obj: string) => void): void\r\n        guiHandler(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (obj: string) => void): (obj: string) => void | void\r\n        titleBarGuiHandler(op: \"get\"): () => void\r\n        titleBarGuiHandler(op: \"add\" | \"remove\" | \"set\", fn?: () => void): void\r\n        titleBarGuiHandler(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => void): () => void | void\r\n        footerBarGuiHandler(op: \"get\"): () => void\r\n        footerBarGuiHandler(op: \"add\" | \"remove\" | \"set\", fn?: () => void): void\r\n        footerBarGuiHandler(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => void): () => void | void\r\n        activateHandler(op: \"get\"): (arg1: string, arg2: any) => void\r\n        activateHandler(op: \"add\" | \"remove\" | \"set\", fn?: (arg1: string, arg2: any) => void): void\r\n        activateHandler(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (arg1: string, arg2: any) => void): (arg1: string, arg2: any) => void | void\r\n        deactivateHandler(op: \"get\"): () => void\r\n        deactivateHandler(op: \"add\" | \"remove\" | \"set\", fn?: () => void): void\r\n        deactivateHandler(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => void): () => void | void\r\n        hasSearchInterestHandler(op: \"get\"): (arg: string) => boolean\r\n        hasSearchInterestHandler(op: \"add\" | \"remove\" | \"set\", fn?: (arg: string) => boolean): void\r\n        hasSearchInterestHandler(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (arg: string) => boolean): (arg: string) => boolean | void\r\n        inspectorUpdateHandler(op: \"get\"): () => void\r\n        inspectorUpdateHandler(op: \"add\" | \"remove\" | \"set\", fn?: () => void): void\r\n        inspectorUpdateHandler(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => void): () => void | void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** This class provides global APIs to interact with the Settings window.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class SettingsService extends Object {\r\n        /** Open the Project Settings window with the specified settings item already selected.\r\n         * @param settingsPath Settings paths of the item to select (for example, 'ProjectPlayer' or 'ProjectQuality').\r\n         * @returns Returns an instance to the Settings window. \r\n         */\r\n        static OpenProjectSettings(settingsPath: string): EditorWindow\r\n        /** Open the Preferences window with the specified settings item already selected.\r\n         * @param settingsPath Settings path of the item to select (for example, 'PreferencesKeys' or 'Preferences2D').\r\n         * @returns Returns an instance to the Settings window. \r\n         */\r\n        static OpenUserPreferences(settingsPath: string): EditorWindow\r\n        static NotifySettingsProviderChanged(): void\r\n        static RepaintAllSettingsWindow(): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    import { Object } from \"UnityEngine\";\r\n    import { Object as Object1 } from \"System\";\r\n    /** AssetSettingsProvider is a specialization of the SettingsProvider class that converts legacy settings to Unified Settings. Legacy settings include any settings that used the Inspector to modify themselves, such as the *.asset files under the ProjectSettings folder. Under the hood, AssetSettingsProvider creates an Editor for specific Assets and builds the UI for the Settings window by wrapping the Editor.OnInspectorGUI function.\n\nInternally we use this class to wrap our existing settings.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AssetSettingsProvider extends SettingsProvider {\r\n        constructor(settingsWindowPath: string, editorCreator: () => Editor, keywords: IEnumerable<string>)\r\n        constructor(settingsWindowPath: string, settingsGetter: () => Object)\r\n        /** Overrides SettingsProvider.OnActivate for this AssetSettingsProvider.\r\n         * @param searchContext Search context in the search box on the Settings window.\r\n         * @param rootElement Root of the UIElements tree. If you add to this root, the SettingsProvider uses UIElements instead of calling SettingsProvider.OnGUI to build the UI. If you do not add to this VisualElement, then you must use the IMGUI to build the UI.\r\n         */\r\n        OnActivate(searchContext: string, rootElement: any): void\r\n        OnDeactivate(): void\r\n        /** Overrides SettingsProvider.OnGUI for this AssetSettingsProvider.\r\n         * @param searchContext Search context for the Settings window. Used to show or hide relevant properties.\r\n         */\r\n        OnGUI(searchContext: string): void\r\n        OnTitleBarGUI(): void\r\n        OnFooterBarGUI(): void\r\n        static CreateProviderFromAssetPath(settingsWindowPath: string, assetPath: string, keywords: IEnumerable<string>): AssetSettingsProvider\r\n        static CreateProviderFromObject(settingsWindowPath: string, settingsObj: Object, keywords: IEnumerable<string>): AssetSettingsProvider\r\n        static CreateProviderFromResourcePath(settingsWindowPath: string, resourcePath: string, keywords: IEnumerable<string>): AssetSettingsProvider\r\n        /** Editor providing UI to modify the settings.\r\n         */\r\n        readonly settingsEditor: Editor\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Rect } from \"UnityEngine\";\r\n    /** Use this class to highlight elements in the editor for use in in-editor tutorials and similar.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class Highlighter extends Object {\r\n        constructor()\r\n        static Stop(): void\r\n        /** Highlights an element in the editor.\r\n         * @param windowTitle The title of the window the element is inside.\r\n         * @param text The text to identify the element with.\r\n         * @param mode Optional mode to specify how to search for the element.\r\n         * @returns true if the requested element was found; otherwise false. \r\n         */\r\n        static Highlight(windowTitle: string, text: string, mode: HighlightSearchMode): boolean\r\n        /** Highlights an element in the editor.\r\n         * @param windowTitle The title of the window the element is inside.\r\n         * @param text The text to identify the element with.\r\n         * @param mode Optional mode to specify how to search for the element.\r\n         * @returns true if the requested element was found; otherwise false. \r\n         */\r\n        static Highlight(windowTitle: string, text: string): boolean\r\n        /** Call this method to create an identifiable rect that the Highlighter can find.\r\n         * @param position The position to make highlightable.\r\n         * @param identifier The identifier text of the rect.\r\n         */\r\n        static HighlightIdentifier(position: Rect, identifier: string): void\r\n        /** The text of the current active highlight.\r\n         */\r\n        static readonly activeText: string\r\n        /** The rect in screenspace of the current active highlight.\r\n         */\r\n        static readonly activeRect: Rect\r\n        /** Is the current active highlight visible yet?\r\n         */\r\n        static readonly activeVisible: boolean\r\n        /** Is there currently an active highlight?\r\n         */\r\n        static readonly active: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Used to specify how to find a given element in the editor to highlight.\r\n     */\r\n    enum HighlightSearchMode {\r\n        /** Highlights nothing.\r\n         */\r\n        None = 0,\r\n        /** Highlights the first element found using any of the search modes.\r\n         */\r\n        Auto = 1,\r\n        /** Highlights an element with a given identifier text.\r\n         */\r\n        Identifier = 2,\r\n        /** Highlights an entire editor control using its label text as identifier.\r\n         */\r\n        PrefixLabel = 3,\r\n        /** Highlights an element containing text using the text as identifier.\r\n         */\r\n        Content = 4,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** This enumeration describes the different kind of changes that can be tracked in an ObjectChangeEventStream. Each event has a corresponding type in ObjectChangeEvents.\r\n     */\r\n    enum ObjectChangeKind {\r\n        /** Indicates an uninitialized value.\r\n         */\r\n        None = 0,\r\n        /** A change of this type indicates that an open scene has been changed (\"dirtied\") without any more specific information available. This happens for example when EditorSceneManager.MarkSceneDirty is used.\r\n         */\r\n        ChangeScene = 1,\r\n        /** A change of this type indicates that a GameObject has been created, possibly with additional objects below it in the hierarchy. This happens for example when Undo.RegisterCreatedObjectUndo is used with a GameObject.\r\n         */\r\n        CreateGameObjectHierarchy = 2,\r\n        /** A change of this type indicates that the structure of a GameObject has changed and any GameObject in the hierarchy below it might have changed. This happens for example when Undo.RegisterFullObjectHierarchyUndo is used.\r\n         */\r\n        ChangeGameObjectStructureHierarchy = 3,\r\n        /** A change of this type indicates that the structure of a GameObject has changed. This happens when a component is added to or removed from the GameObject using Undo.AddComponent or Undo.DestroyObjectImmediate.\r\n         */\r\n        ChangeGameObjectStructure = 4,\r\n        /** A change of this type indicates that the parent of a GameObject has changed. This happens when Undo.SetTransformParent or SceneManager.MoveGameObjectToScene is used.\r\n         */\r\n        ChangeGameObjectParent = 5,\r\n        /** A change of this type indicates that a property of a GameObject or Component has changed. This happens for example when Undo.RecordObject is used with an instance of a Component.\r\n         */\r\n        ChangeGameObjectOrComponentProperties = 6,\r\n        /** A change of this type indicates that a GameObject and the entire hierarchy below it has been destroyed. This happens for example when Undo.DestroyObjectImmediate is used with an GameObject.\r\n         */\r\n        DestroyGameObjectHierarchy = 7,\r\n        /** A change of this type indicates that an asset object has been created. This happens for example when Undo.RegisterCreatedObjectUndo is used with an instance of an asset (e.g. Texture).\r\n         */\r\n        CreateAssetObject = 8,\r\n        /** A change of this type indicates that an asset object has been destroyed. This happens for example when Undo.DestroyObjectImmediate is used with an instance of an asset (e.g. Texture).\r\n         */\r\n        DestroyAssetObject = 9,\r\n        /** A change of this type indicates that a property of an asset object in memory has changed. This happens for example when Undo.RecordObject is used with an instance of an asset (e.g. Texture).\r\n         */\r\n        ChangeAssetObjectProperties = 10,\r\n        /** A change of this type indicates that prefab instances in an open scene have been updated due to a change to the source prefab.\r\n         */\r\n        UpdatePrefabInstances = 11,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    /** Exposes events that allow you to track undoable changes to objects in the editor.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class ObjectChangeEvents extends Object {\r\n        static changesPublished(op: \"add\" | \"remove\", fn: (stream: jsb.Ref<ObjectChangeEventStream>) => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** A change of this type indicates that the parent of a GameObject has changed. This happens when Undo.SetTransformParent or SceneManager.MoveGameObjectToScene is used.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ChangeGameObjectParentEventArgs extends ValueType {\r\n        constructor(instanceId: number, previousScene: any, previousParentInstanceId: number, newScene: any, newParentInstanceId: number)\r\n        /** The instance ID of the GameObject whose parent changed. Note that this is not the instance ID of the Transform component.\r\n         */\r\n        readonly instanceId: number\r\n        /** The instance ID of the GameObject that was the previous parent of the target. Note that this is not the instance ID of its Transform.\r\n         */\r\n        readonly previousParentInstanceId: number\r\n        /** The instance ID of the GameObject that is the new parent of the target. Note that this is not the instance ID of its Transform.\r\n         */\r\n        readonly newParentInstanceId: number\r\n        /** The scene containing the previous parent. This is useful to detect whether a GameObject was moved to another scene.\r\n         */\r\n        readonly previousScene: any\r\n        /** The Scene containing the new parent. This is useful to detect whether a GameObject was moved to another scene or moved to the root of a scene.\r\n         */\r\n        readonly newScene: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** A change of this type indicates that an open scene has been changed (\"dirtied\") without any more specific information available. This happens for example when EditorSceneManager.MarkSceneDirty is used.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ChangeSceneEventArgs extends ValueType {\r\n        constructor(scene: any)\r\n        /** The Scene that was changed.\r\n         */\r\n        readonly scene: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** A change of this type indicates that a GameObject has been created, possibly with additional objects below it in the hierarchy. This happens for example when Undo.RegisterCreatedObjectUndo is used with a GameObject.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class CreateGameObjectHierarchyEventArgs extends ValueType {\r\n        constructor(instanceId: number, scene: any)\r\n        /** The instance ID of the GameObject that has been created.\r\n         */\r\n        readonly instanceId: number\r\n        /** The scene containing the GameObject that has been created.\r\n         */\r\n        readonly scene: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** A change of this type indicates that the structure of a GameObject has changed and any GameObject in the hierarchy below it might have changed. This happens for example when Undo.RegisterFullObjectHierarchyUndo is used.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ChangeGameObjectStructureHierarchyEventArgs extends ValueType {\r\n        constructor(instanceId: number, scene: any)\r\n        /** The instance ID of the GameObject that has been changed.\r\n         */\r\n        readonly instanceId: number\r\n        /** The scene containing the GameObject that has been changed.\r\n         */\r\n        readonly scene: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** A change of this type indicates that the structure of a GameObject has changed. This happens when a component is added to or removed from the GameObject using Undo.AddComponent or Undo.DestroyObjectImmediate.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ChangeGameObjectStructureEventArgs extends ValueType {\r\n        constructor(instanceId: number, scene: any)\r\n        /** The instance ID of the GameObject that has been changed.\r\n         */\r\n        readonly instanceId: number\r\n        /** The Scene containing the GameObject that has been changed.\r\n         */\r\n        readonly scene: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** A change of this type indicates that a property of a GameObject or Component has changed. This happens for example when Undo.RecordObject is used with an instance of a Component.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ChangeGameObjectOrComponentPropertiesEventArgs extends ValueType {\r\n        constructor(instanceId: number, scene: any)\r\n        /** The instance ID of the modified GameObject or Component.\r\n         */\r\n        readonly instanceId: number\r\n        /** The Scene that contains the GameObject associated with the change. If a Component is changed, this is the GameObject to which the component belongs.\r\n         */\r\n        readonly scene: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** A change of this type indicates that a GameObject and the entire hierarchy below it has been destroyed. This happens for example when Undo.DestroyObjectImmediate is used with an GameObject.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class DestroyGameObjectHierarchyEventArgs extends ValueType {\r\n        constructor(instanceId: number, scene: any)\r\n        /** The instance ID of the GameObject that has been destroyed.\r\n         */\r\n        readonly instanceId: number\r\n        /** The scene containing the GameObject that has been destroyed.\r\n         */\r\n        readonly scene: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** A change of this type indicates that an asset object has been created. This happens for example when Undo.RegisterCreatedObjectUndo is used with an instance of an asset (e.g. Texture).\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class CreateAssetObjectEventArgs extends ValueType {\r\n        constructor(guid: GUID, instanceId: number, scene: any)\r\n        /** The GUID of the new asset.\r\n         */\r\n        readonly guid: GUID\r\n        /** The instance ID of the modified asset.\r\n         */\r\n        readonly instanceId: number\r\n        /** The Scene that contains the new asset. This is usually an invalid scene unless the asset is explicitly associated in a scene (e.g. RenderSettings).\r\n         */\r\n        readonly scene: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** A change of this type indicates that an asset object has been destroyed. This happens for example when Undo.DestroyObjectImmediate is used with an instance of an asset (e.g. Texture).\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class DestroyAssetObjectEventArgs extends ValueType {\r\n        constructor(guid: GUID, instanceId: number, scene: any)\r\n        /** The GUID of the removed asset.\r\n         */\r\n        readonly guid: GUID\r\n        /** The instance ID of the modified asset.\r\n         */\r\n        readonly instanceId: number\r\n        /** The scene that contained the asset. This is usually an invalid scene unless the asset is explicitly associated in a scene (e.g. RenderSettings).\r\n         */\r\n        readonly scene: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** A change of this type indicates that a property of an asset object in memory has changed. This happens for example when Undo.RecordObject is used with an instance of an asset (e.g. Texture).\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ChangeAssetObjectPropertiesEventArgs extends ValueType {\r\n        constructor(guid: GUID, instanceId: number, scene: any)\r\n        /** The GUID of the changed asset.\r\n         */\r\n        readonly guid: GUID\r\n        /** The instance ID of the modified asset.\r\n         */\r\n        readonly instanceId: number\r\n        /** The Scene that contains the modified asset. This is usually an invalid scene unless the asset is explicitly associated in a scene (e.g. RenderSettings).\r\n         */\r\n        readonly scene: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array, Enum } from \"System\";\r\n    /** Represents a stream of events that describes the changes applied to objects in memory over the course of a frame.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ObjectChangeEventStream extends ValueType {\r\n        constructor()\r\n        /** Returns the type of the event at the specified index.\r\n         * @param eventIdx The index of the event whose type should be returned.\r\n         * @returns The type of the event at the specified index. \r\n         */\r\n        GetEventType(eventIdx: number): ObjectChangeKind\r\n        /** Retrieves the event data at the given index as a ChangeSceneEventArgs. Throws an exception if the event type requested does not match the event stored in the stream.\r\n         * @param eventIdx The index of the event to get the data for.\r\n         */\r\n        GetChangeSceneEvent(eventIdx: number, data: jsb.Out<ChangeSceneEventArgs>): void\r\n        /** Retrieves the event data at the given index as a CreateGameObjectHierarchyEventArgs. Throws an exception if the event type requested does not match the event stored in the stream.\r\n         * @param eventIdx The index of the event to get the data for.\r\n         * @param data The data associated with the event.\r\n         */\r\n        GetCreateGameObjectHierarchyEvent(eventIdx: number, data: jsb.Out<CreateGameObjectHierarchyEventArgs>): void\r\n        /** Retrieves the event data at the given index as a DestroyGameObjectHierarchyEventArgs. Throws an exception if the event type requested does not match the event stored in the stream.\r\n         * @param eventIdx The index of the event to get the data for.\r\n         * @param data The data associated with the event.\r\n         */\r\n        GetDestroyGameObjectHierarchyEvent(eventIdx: number, data: jsb.Out<DestroyGameObjectHierarchyEventArgs>): void\r\n        /** Retrieves the event data at the given index as a ChangeGameObjectStructureHierarchyEventArgs. Throws an exception if the event type requested does not match the event stored in the stream.\r\n         * @param eventIdx The index of the event to get the data for.\r\n         * @param data The data associated with the event.\r\n         */\r\n        GetChangeGameObjectStructureHierarchyEvent(eventIdx: number, data: jsb.Out<ChangeGameObjectStructureHierarchyEventArgs>): void\r\n        /** Retrieves the event data at the given index as a ChangeGameObjectStructureEventArgs. Throws an exception if the event type requested does not match the event stored in the stream.\r\n         * @param eventIdx The index of the event to get the data for.\r\n         * @param data The data associated with the event.\r\n         */\r\n        GetChangeGameObjectStructureEvent(eventIdx: number, data: jsb.Out<ChangeGameObjectStructureEventArgs>): void\r\n        /** Retrieves the event data at the given index as a ChangeGameObjectParentEventArgs. Throws an exception if the event type requested does not match the event stored in the stream.\r\n         * @param eventIdx The index of the event to get the data for.\r\n         * @param data The data associated with the event.\r\n         */\r\n        GetChangeGameObjectParentEvent(eventIdx: number, data: jsb.Out<ChangeGameObjectParentEventArgs>): void\r\n        /** Retrieves the event data at the given index as a ChangeAssetObjectPropertiesEventArgs. Throws an exception if the event type requested does not match the event stored in the stream.\r\n         * @param eventIdx The index of the event to get the data for.\r\n         * @param data The data associated with the event.\r\n         */\r\n        GetChangeGameObjectOrComponentPropertiesEvent(eventIdx: number, data: jsb.Out<ChangeGameObjectOrComponentPropertiesEventArgs>): void\r\n        /** Retrieves the event data at the given index as a CreateAssetObjectEventArgs. Throws an exception if the event type requested does not match the event stored in the stream.\r\n         * @param eventIdx The index of the event to get the data for.\r\n         * @param data The data associated with the event.\r\n         */\r\n        GetCreateAssetObjectEvent(eventIdx: number, data: jsb.Out<CreateAssetObjectEventArgs>): void\r\n        /** Retrieves the event data at the given index as a DestroyAssetObjectEventArgs. Throws an exception if the event type requested does not match the event stored in the stream.\r\n         * @param eventIdx The index of the event to get the data for.\r\n         * @param data The data associated with the event.\r\n         */\r\n        GetDestroyAssetObjectEvent(eventIdx: number, data: jsb.Out<DestroyAssetObjectEventArgs>): void\r\n        /** Retrieves the event data at the given index as a ChangeAssetObjectPropertiesEventArgs. Throws an exception if the event type requested does not match the event stored in the stream.\r\n         * @param eventIdx The index of the event to get the data for.\r\n         * @param data The data associated with the event.\r\n         */\r\n        GetChangeAssetObjectPropertiesEvent(eventIdx: number, data: jsb.Out<ChangeAssetObjectPropertiesEventArgs>): void\r\n        /** Retrieves the event data at the given index as a UpdatePrefabInstancesEventArgs. Throws an exception if the event type requested does not match the event stored in the stream.\r\n         * @param eventIdx The index of the event to get the data for.\r\n         * @param data The data associated with the event.\r\n         */\r\n        GetUpdatePrefabInstancesEvent(eventIdx: number, data: jsb.Out<any>): void\r\n        /** Creates a copy of this stream with the specified allocator.\r\n         * @param allocator The allocator to use to allocate the memory for the copy.\r\n         * @returns A copy of the stream that contains the same events, but in a separate memory lcoation. \r\n         */\r\n        Clone(allocator: any): ObjectChangeEventStream\r\n        Dispose(): void\r\n        /** The number of events in the stream.\r\n         */\r\n        readonly length: number\r\n        /** Indicates whether the ObjectChangeEventStream has an allocated memory buffer.\r\n         */\r\n        readonly isCreated: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Enum, Array } from \"System\";\r\n    namespace ObjectChangeEventStream {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class Builder extends ValueType {\r\n            constructor(allocator: any)\r\n            ToStream(allocator: any): ObjectChangeEventStream\r\n            Dispose(): void\r\n            PushChangeSceneEvent(data: jsb.Ref<ChangeSceneEventArgs>): void\r\n            PushCreateGameObjectHierarchyEvent(data: jsb.Ref<CreateGameObjectHierarchyEventArgs>): void\r\n            PushDestroyGameObjectHierarchyEvent(data: jsb.Ref<DestroyGameObjectHierarchyEventArgs>): void\r\n            PushChangeGameObjectStructureHierarchyEvent(data: jsb.Ref<ChangeGameObjectStructureHierarchyEventArgs>): void\r\n            PushChangeGameObjectStructureEvent(data: jsb.Ref<ChangeGameObjectStructureEventArgs>): void\r\n            PushChangeGameObjectParentEvent(data: jsb.Ref<ChangeGameObjectParentEventArgs>): void\r\n            PushChangeGameObjectOrComponentPropertiesEvent(data: jsb.Ref<ChangeGameObjectOrComponentPropertiesEventArgs>): void\r\n            PushCreateAssetObjectEvent(data: jsb.Ref<CreateAssetObjectEventArgs>): void\r\n            PushDestroyAssetObjectEvent(data: jsb.Ref<DestroyAssetObjectEventArgs>): void\r\n            PushChangeAssetObjectPropertiesEvent(data: jsb.Ref<ChangeAssetObjectPropertiesEventArgs>): void\r\n            PushUpdatePrefabInstancesEvent(data: jsb.Ref<any>): void\r\n            readonly eventCount: number\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** See Also: Undo.postprocessModifications.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class UndoPropertyModification extends ValueType {\r\n        constructor()\r\n        /** Indicates whether to retain modifications when the targeted object is an instance of a Prefab.\r\n         */\r\n        keepPrefabOverride: boolean\r\n        /** \n                  The previous value of the modified property.\n                  See Also: PropertyModification .\n                \r\n         */\r\n        previousValue: PropertyModification\r\n        /** \n                  The current value of the modified property.\n                  See Also: PropertyModification.\n                \r\n         */\r\n        currentValue: PropertyModification\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Use this class to retrieve information about the currently selected project and the current Unity ID that is logged in.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class CloudProjectSettings extends Object {\r\n        constructor()\r\n        static RefreshAccessToken(refresh: (obj: boolean) => void): void\r\n        /** The user ID of the currently logged-in Unity ID account (Read Only).\r\n         */\r\n        static readonly userId: string\r\n        /** The user name of the currently logged in Unity ID account (Read Only).\r\n         */\r\n        static readonly userName: string\r\n        static readonly accessToken: string\r\n        /** A unique cloud project identifier. It is unique for every project (Read Only).\r\n         */\r\n        static readonly projectId: string\r\n        /** The name of the project entry in the dashboard associated with this project (Read Only).\r\n         */\r\n        static readonly projectName: string\r\n        /** The ID of the organization that this project belongs to. (Read Only)\r\n         */\r\n        static readonly organizationId: string\r\n        /** The name of the organization that this project belongs to. (Read Only)\r\n         */\r\n        static readonly organizationName: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Evaluates simple math expressions; supports int  float and operators: + - *  % ^ ( ).\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ExpressionEvaluator extends Object {\r\n        constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Quaternion, Matrix4x4, Ray, Vector3 } from \"UnityEngine\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class MathUtils extends Object {\r\n        constructor()\r\n        static GetQuatLength(q: Quaternion): number\r\n        static GetQuatConjugate(q: Quaternion): Quaternion\r\n        static OrthogonalizeMatrix(m: Matrix4x4): Matrix4x4\r\n        static QuaternionNormalize(q: jsb.Ref<Quaternion>): void\r\n        static QuaternionFromMatrix(m: Matrix4x4): Quaternion\r\n        static GetQuatLog(q: Quaternion): Quaternion\r\n        static GetQuatExp(q: Quaternion): Quaternion\r\n        static GetQuatSquad(t: number, q0: Quaternion, q1: Quaternion, a0: Quaternion, a1: Quaternion): Quaternion\r\n        static GetSquadIntermediate(q0: Quaternion, q1: Quaternion, q2: Quaternion): Quaternion\r\n        static Ease(t: number, k1: number, k2: number): number\r\n        static Slerp(p: Quaternion, q: Quaternion, t: number): Quaternion\r\n        static IntersectRayTriangle(ray: Ray, v0: Vector3, v1: Vector3, v2: Vector3, bidirectional: boolean): Object\r\n        static ClosestPtSegmentRay(p1: Vector3, q1: Vector3, ray: Ray, squaredDist: jsb.Out<number>, s: jsb.Out<number>, closestRay: jsb.Out<Vector3>): Vector3\r\n        static IntersectRaySphere(ray: Ray, sphereOrigin: Vector3, sphereRadius: number, t: jsb.Ref<number>, q: jsb.Ref<Vector3>): boolean\r\n        static ClosestPtRaySphere(ray: Ray, sphereOrigin: Vector3, sphereRadius: number, t: jsb.Ref<number>, q: jsb.Ref<Vector3>): boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Options for removing assets\r\n     */\r\n    enum RemoveAssetOptions {\r\n        /** The asset should be moved to trash.\r\n         */\r\n        MoveAssetToTrash = 0,\r\n        /** Delete the asset without moving it to the trash.\r\n         */\r\n        DeleteAssets = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class CacheServerConnectionChangedParameters extends ValueType {\r\n        constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Array } from \"System\";\r\n    /** Represents an Android asset pack directory in a project.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AndroidAssetPackImporter extends AssetImporter {\r\n        constructor()\r\n        static GetAllImporters(): Array<AndroidAssetPackImporter>\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** The sample rate setting used within the AudioImporter. This defines the sample rate conversion of audio on import.\r\n     */\r\n    enum AudioSampleRateSetting {\r\n        /** Do not change the sample rate of the imported audio file. The sample rate will be preserved for the imported AudioClip.\r\n         */\r\n        PreserveSampleRate = 0,\r\n        /** Let Unity deduce the optimal sample rate for the AudioClip being imported. The audio file will be analysed and a minimal sample rate chosen while still preserving audio quality.\r\n         */\r\n        OptimizeSampleRate = 1,\r\n        /** Override the sample rate of the imported audio file with a custom value.\r\n         */\r\n        OverrideSampleRate = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Enum } from \"System\";\r\n    /** This structure contains a collection of settings used to define how an AudioClip should be imported.\n\nThis  structure is used with the AudioImporter to define how the AudioClip should be imported and treated during loading within the Scene.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AudioImporterSampleSettings extends ValueType {\r\n        constructor()\r\n        /** LoadType defines how the imported AudioClip data should be loaded.\r\n         */\r\n        loadType: any\r\n        /** Defines how the sample rate is modified (if at all) of the importer audio file.\r\n         */\r\n        sampleRateSetting: AudioSampleRateSetting\r\n        /** Target sample rate to convert to when samplerateSetting is set to OverrideSampleRate.\r\n         */\r\n        sampleRateOverride: number\r\n        /** CompressionFormat defines the compression type that the audio file is encoded to. Different compression types have different performance and audio artifact characteristics.\r\n         */\r\n        compressionFormat: any\r\n        /** Audio compression quality (0-1)\n\nAmount of compression. The value roughly corresponds to the ratio between the resulting and the source file sizes.\r\n         */\r\n        quality: number\r\n        conversionMode: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Array } from \"System\";\r\n    import { Object } from \"UnityEngine\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class MonoImporter extends AssetImporter {\r\n        constructor()\r\n        SetDefaultReferences(name: Array<string>, target: Array<Object>): void\r\n        GetScript(): MonoScript\r\n        GetDefaultReference(name: string): Object\r\n        static GetAllRuntimeMonoScripts(): Array<MonoScript>\r\n        static SetExecutionOrder(script: MonoScript, order: number): void\r\n        static GetExecutionOrder(script: MonoScript): number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Array } from \"System\";\r\n    /** Represents plugin importer.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class PluginImporter extends AssetImporter {\r\n        constructor()\r\n        ClearSettings(): void\r\n        /** Sets compatibility with Any Platform.\r\n         * @param enable Determines whether the plugin is compatible with Any Platform.\r\n         */\r\n        SetCompatibleWithAnyPlatform(enable: boolean): void\r\n        GetCompatibleWithAnyPlatform(): boolean\r\n        /** Exclude platform from compatible platforms when Any Platform is set to true.\r\n         * @param platformName Target platform.\r\n         */\r\n        SetExcludeFromAnyPlatform(platformName: string, excludedFromAny: boolean): void\r\n        /** Exclude platform from compatible platforms when Any Platform is set to true.\r\n         * @param platformName Target platform.\r\n         */\r\n        SetExcludeFromAnyPlatform(platform: BuildTarget, excludedFromAny: boolean): void\r\n        /** Is platform excluded when Any Platform set to true.\r\n         * @param platform Target platform.\r\n         */\r\n        GetExcludeFromAnyPlatform(platformName: string): boolean\r\n        /** Is platform excluded when Any Platform set to true.\r\n         * @param platform Target platform.\r\n         */\r\n        GetExcludeFromAnyPlatform(platform: BuildTarget): boolean\r\n        SetIncludeInBuildDelegate(includeInBuildDelegate: (path: string) => boolean): void\r\n        /** Exclude Editor from compatible platforms when Any Platform is set to true.\r\n         */\r\n        SetExcludeEditorFromAnyPlatform(excludedFromAny: boolean): void\r\n        GetExcludeEditorFromAnyPlatform(): boolean\r\n        /** Sets compatibility with any editor.\r\n         * @param enable Is plugin compatible with editor.\r\n         */\r\n        SetCompatibleWithEditor(enable: boolean): void\r\n        GetCompatibleWithEditor(buildTargetGroup: string, buildTarget: string): boolean\r\n        GetCompatibleWithEditor(): boolean\r\n        GetIsOverridable(): boolean\r\n        ShouldIncludeInBuild(): boolean\r\n        /** Sets compatibility with the specified platform.\r\n         * @param platform Target platform.\r\n         * @param enable Is plugin compatible with specified platform.\r\n         * @param platformName Target platform.\r\n         */\r\n        SetCompatibleWithPlatform(platform: BuildTarget, enable: boolean): void\r\n        /** Sets compatibility with the specified platform.\r\n         * @param platform Target platform.\r\n         * @param enable Is plugin compatible with specified platform.\r\n         * @param platformName Target platform.\r\n         */\r\n        SetCompatibleWithPlatform(platformName: string, enable: boolean): void\r\n        /** Is plugin compatible with specified platform.\r\n         * @param platform Target platform.\r\n         */\r\n        GetCompatibleWithPlatform(platform: BuildTarget): boolean\r\n        /** Is plugin compatible with specified platform.\r\n         * @param platform Target platform.\r\n         */\r\n        GetCompatibleWithPlatform(platformName: string): boolean\r\n        /** Sets platform specific data.\r\n         * @param platform Target platform.\r\n         * @param key Key value for data.\r\n         * @param value Data.\r\n         */\r\n        SetPlatformData(platform: BuildTarget, key: string, value: string): void\r\n        /** Sets platform specific data.\r\n         * @param platform Target platform.\r\n         * @param key Key value for data.\r\n         * @param value Data.\r\n         */\r\n        SetPlatformData(platformName: string, key: string, value: string): void\r\n        /** Get platform specific data.\r\n         * @param platform Target platform.\r\n         * @param key Key value for data.\r\n         */\r\n        GetPlatformData(platform: BuildTarget, key: string): string\r\n        /** Get platform specific data.\r\n         * @param platform Target platform.\r\n         * @param key Key value for data.\r\n         */\r\n        GetPlatformData(platformName: string, key: string): string\r\n        /** Sets editor specific data.\r\n         * @param key Key value for data.\r\n         * @param value Data.\r\n         */\r\n        SetEditorData(key: string, value: string): void\r\n        /** Returns editor specific data for specified key.\r\n         * @param key Key value for data.\r\n         */\r\n        GetEditorData(key: string): string\r\n        static GetImporters(buildTargetGroup: string, buildTarget: string): Array<PluginImporter>\r\n        static GetImporters(buildTargetGroup: BuildTargetGroup, buildTarget: BuildTarget): Array<PluginImporter>\r\n        /** Returns all plugin importers for specfied platform.\r\n         * @param platform Target platform.\r\n         * @param platformName Name of the target platform.\r\n         */\r\n        static GetImporters(platformName: string): Array<PluginImporter>\r\n        /** Returns all plugin importers for specfied platform.\r\n         * @param platform Target platform.\r\n         * @param platformName Name of the target platform.\r\n         */\r\n        static GetImporters(platform: BuildTarget): Array<PluginImporter>\r\n        static GetAllImporters(): Array<PluginImporter>\r\n        /** Allows you to specify a list of #define directives which controls whether your plug-in should be included.\r\n         */\r\n        DefineConstraints: Array<string>\r\n        /** Is a native plugin loaded during startup or on demand?\r\n         */\r\n        isPreloaded: boolean\r\n        /** Is plugin native or managed? Note: C++ libraries with CLR support are treated as native plugins, because Unity cannot load such libraries. You can still access them via P/Invoke.\r\n         */\r\n        readonly isNativePlugin: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Video codec to use when importing video clips.\r\n     */\r\n    enum VideoCodec {\r\n        /** Choose the codec that supports hardware decoding on the target platform.\r\n         */\r\n        Auto = 0,\r\n        /** Encode video with the H.264 codec.\r\n         */\r\n        H264 = 1,\r\n        /** Encode video using the vp8 codec.\r\n         */\r\n        VP8 = 2,\r\n        /** Encode video with the H.265 codec.\r\n         */\r\n        H265 = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Bit rate after the clip is transcoded.\r\n     */\r\n    enum VideoBitrateMode {\r\n        /** Low value, safe for slower internet connections or clips where visual quality is not critical.\r\n         */\r\n        Low = 0,\r\n        /** Typical bit rate supported by internet connections.\r\n         */\r\n        Medium = 1,\r\n        /** High value, possibly exceeding typical internet connection capabilities.\r\n         */\r\n        High = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Describes how the fields in the image, if any, should be interpreted.\r\n     */\r\n    enum VideoDeinterlaceMode {\r\n        /** Clip is not interlaced.\r\n         */\r\n        Off = 0,\r\n        /** First field is in the even lines.\r\n         */\r\n        Even = 1,\r\n        /** First field is in the odd lines.\r\n         */\r\n        Odd = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** How the video clip's images will be resized during transcoding.\r\n     */\r\n    enum VideoResizeMode {\r\n        /** Same width and height as the source.\r\n         */\r\n        OriginalSize = 0,\r\n        /** 3/4 width and height.\r\n         */\r\n        ThreeQuarterRes = 1,\r\n        /** Half width and height.\r\n         */\r\n        HalfRes = 2,\r\n        /** Quarter width and height.\r\n         */\r\n        QuarterRes = 3,\r\n        /** Fit source in a 1024x1024 rectangle.\r\n         */\r\n        Square1024 = 4,\r\n        /** Fit source in a 512x512 rectangle.\r\n         */\r\n        Square512 = 5,\r\n        /** Fit source in a 256x256 rectangle.\r\n         */\r\n        Square256 = 6,\r\n        /** Resulting size will be driven by VideoClipImporter.customWidth and VideoClipImporter.customHeight.\r\n         */\r\n        CustomSize = 7,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Controls the imported clip's internal resize to save space at the cost of blurrier images.\r\n     */\r\n    enum VideoSpatialQuality {\r\n        /** Scales width and height by 1/2.\r\n         */\r\n        LowSpatialQuality = 0,\r\n        /** Scales width and height by 3/4.\r\n         */\r\n        MediumSpatialQuality = 1,\r\n        /** No resize performed.\r\n         */\r\n        HighSpatialQuality = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Methods to compensate for aspect ratio discrepancies between the source resolution and the wanted encoding size.\r\n     */\r\n    enum VideoEncodeAspectRatio {\r\n        /** Perform no operation.\r\n         */\r\n        NoScaling = 0,\r\n        /** Stretch the source to fill the target resolution without preserving the aspect ratio.\r\n         */\r\n        Stretch = 5,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Importer settings that can have platform-specific values.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class VideoImporterTargetSettings extends Object {\r\n        constructor()\r\n        /** Controls whether the movie file will be transcoded during import. When transcoding is not enabled, the file will be imported in its original format.\r\n         */\r\n        enableTranscoding: boolean\r\n        /** Codec that the resulting VideoClip will use.\r\n         */\r\n        codec: VideoCodec\r\n        /** How to resize the images when going into the imported clip.\r\n         */\r\n        resizeMode: VideoResizeMode\r\n        /** How the aspect ratio discrepancies, if any, will be handled if the chosen import resolution has a different ratio than the source.\r\n         */\r\n        aspectRatio: VideoEncodeAspectRatio\r\n        /** Width of the transcoded clip when the resizeMode is set to custom.\r\n         */\r\n        customWidth: number\r\n        /** Height of the transcoded clip when the resizeMode is set to custom.\r\n         */\r\n        customHeight: number\r\n        /** Bit rate type for the transcoded clip.\r\n         */\r\n        bitrateMode: VideoBitrateMode\r\n        /** Controls an internal image resize, resulting in blurrier images but smaller image dimensions and file size.\r\n         */\r\n        spatialQuality: VideoSpatialQuality\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Options to control the optimization of mesh data during asset import.\r\n     */\r\n    enum MeshOptimizationFlags {\r\n        /** Optimize the order of polygons in the mesh to make better use of the GPUs internal caches to improve rendering performance.\r\n         */\r\n        PolygonOrder = 1,\r\n        /** Optimize the order of vertices in the mesh to make better use of the GPUs internal caches to improve rendering performance.\r\n         */\r\n        VertexOrder = 2,\r\n        /** Perform maximum optimization of the mesh data, enables all optimization options.\r\n         */\r\n        Everything = -1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** AnimationClip mask options for ModelImporterClipAnimation.\r\n     */\r\n    enum ClipAnimationMaskType {\r\n        /** A mask containing all the transform in the file will be created internally.\r\n         */\r\n        CreateFromThisModel = 0,\r\n        /** Use a mask from your project to specify which transforms animation should be imported.\r\n         */\r\n        CopyFromOther = 1,\r\n        /** No Mask. All the animation will be imported.\r\n         */\r\n        None = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    import { AnimationCurve } from \"UnityEngine\";\r\n    /** Stores a curve and its name that will be used to create additionnal curves during the import process.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ClipAnimationInfoCurve extends ValueType {\r\n        constructor()\r\n        /** The name of the animation curve.\r\n         */\r\n        name: string\r\n        /** The animation curve.\r\n         */\r\n        curve: AnimationCurve\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { WrapMode, Object as Object1 } from \"UnityEngine\";\r\n    /** Animation clips to split animation into.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ModelImporterClipAnimation extends Object {\r\n        constructor()\r\n        /** Copy the current masking settings from the clip to an AvatarMask.\r\n         * @param mask AvatarMask to which the masking values will be saved.\r\n         */\r\n        ConfigureMaskFromClip(mask: jsb.Ref<any>): void\r\n        /** Copy the mask settings from an AvatarMask to the clip configuration.\r\n         * @param mask AvatarMask from which the mask settings will be imported.\r\n         */\r\n        ConfigureClipFromMask(mask: any): void\r\n        Equals(o: Object): boolean\r\n        GetHashCode(): number\r\n        /** Take name.\r\n         */\r\n        takeName: string\r\n        /** Clip name.\r\n         */\r\n        name: string\r\n        /** First frame of the clip.\r\n         */\r\n        firstFrame: number\r\n        /** Last frame of the clip.\r\n         */\r\n        lastFrame: number\r\n        /** The wrap mode of the animation.\r\n         */\r\n        wrapMode: WrapMode\r\n        /** Is the clip a looping animation?\r\n         */\r\n        loop: boolean\r\n        /** Offset in degrees to the root rotation.\r\n         */\r\n        rotationOffset: number\r\n        /** Offset to the vertical root position.\r\n         */\r\n        heightOffset: number\r\n        /** Offset to the cycle of a looping animation, if a different time in it is desired to be the start.\r\n         */\r\n        cycleOffset: number\r\n        /** Enable to make the clip loop.\r\n         */\r\n        loopTime: boolean\r\n        /** Enable to make the motion loop seamlessly.\r\n         */\r\n        loopPose: boolean\r\n        /** Enable to make root rotation be baked into the movement of the bones. Disable to make root rotation be stored as root motion.\r\n         */\r\n        lockRootRotation: boolean\r\n        /** Enable to make vertical root motion be baked into the movement of the bones. Disable to make vertical root motion be stored as root motion.\r\n         */\r\n        lockRootHeightY: boolean\r\n        /** Enable to make horizontal root motion be baked into the movement of the bones. Disable to make horizontal root motion be stored as root motion.\r\n         */\r\n        lockRootPositionXZ: boolean\r\n        /** Keeps the vertical position as it is authored in the source file.\r\n         */\r\n        keepOriginalOrientation: boolean\r\n        /** Keeps the vertical position as it is authored in the source file.\r\n         */\r\n        keepOriginalPositionY: boolean\r\n        /** Keeps the vertical position as it is authored in the source file.\r\n         */\r\n        keepOriginalPositionXZ: boolean\r\n        /** Keeps the feet aligned with the root transform position.\r\n         */\r\n        heightFromFeet: boolean\r\n        /** Mirror left and right in this clip.\r\n         */\r\n        mirror: boolean\r\n        /** Define mask type.\r\n         */\r\n        maskType: ClipAnimationMaskType\r\n        /** The AvatarMask used to mask transforms during the import process.\r\n         */\r\n        maskSource: any\r\n        /** AnimationEvents that will be added during the import process.\r\n         */\r\n        events: Array<any>\r\n        /** Additionnal curves that will be that will be added during the import process.\r\n         */\r\n        curves: Array<ClipAnimationInfoCurve>\r\n        /** Returns true when the source AvatarMask has changed. This only happens when  ModelImporterClipAnimation.maskType is set to ClipAnimationMaskType.CopyFromOther\nTo force a reload of the mask, simply set  ModelImporterClipAnimation.maskSource to the desired AvatarMask.\r\n         */\r\n        readonly maskNeedsUpdating: boolean\r\n        /** The additive reference pose frame.\r\n         */\r\n        additiveReferencePoseFrame: number\r\n        /** Enable to defines an additive reference pose.\r\n         */\r\n        hasAdditiveReferencePose: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Material naming options for ModelImporter.\r\n     */\r\n    enum ModelImporterMaterialName {\r\n        /** Use material names in the form <textureName>.mat.\r\n         */\r\n        BasedOnTextureName = 0,\r\n        /** Use a material name of the form <materialName>.mat.\r\n         */\r\n        BasedOnMaterialName = 1,\r\n        /** Use material names in the form <modelFileName>-<materialName>.mat.\r\n         */\r\n        BasedOnModelNameAndMaterialName = 2,\r\n        /** <textureName>.mat or <modelFileName>-<materialName>.mat material name.\r\n         */\r\n        BasedOnTextureName_Or_ModelNameAndMaterialName = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Material search options for ModelImporter.\r\n     */\r\n    enum ModelImporterMaterialSearch {\r\n        /** Search in local Materials folder.\r\n         */\r\n        Local = 0,\r\n        /** Recursive-up search in Materials folders.\r\n         */\r\n        RecursiveUp = 1,\r\n        /** Search in all project.\r\n         */\r\n        Everywhere = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Material import options for ModelImporter.\r\n     */\r\n    enum ModelImporterMaterialLocation {\r\n        /** Extract the materials and textures from the model.\r\n         */\r\n        External = 0,\r\n        /** Unity imports materials as sub-assets.\r\n         */\r\n        InPrefab = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Material import options for ModelImporter.\r\n     */\r\n    enum ModelImporterMaterialImportMode {\r\n        /** The model importer does not import materials.\r\n         */\r\n        None = 0,\r\n        ImportStandard = 1,\r\n        LegacyImport = 1,\r\n        /** Enables the PreprocessMaterialDescription AssetPostprocessor on the current importer.\r\n         */\r\n        ImportViaMaterialDescription = 2,\r\n        /** Enables the PreprocessMaterialDescription AssetPostprocessor on the current importer.\r\n         */\r\n        Import = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Tangent space generation options for ModelImporter.\r\n     */\r\n    enum ModelImporterTangentSpaceMode {\r\n        /** Import normals/tangents from file.\r\n         */\r\n        Import = 0,\r\n        /** Calculate tangents.\r\n         */\r\n        Calculate = 1,\r\n        /** Strip normals/tangents.\r\n         */\r\n        None = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Normal generation options for ModelImporter.\r\n     */\r\n    enum ModelImporterNormals {\r\n        /** Import vertex normals from model file (default).\r\n         */\r\n        Import = 0,\r\n        /** Calculate vertex normals.\r\n         */\r\n        Calculate = 1,\r\n        /** Do not import vertex normals.\r\n         */\r\n        None = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Normal generation options for ModelImporter.\r\n     */\r\n    enum ModelImporterNormalCalculationMode {\r\n        /** The normals are unweighted. This option uses the legacy algorithm for handling hard edges.\r\n         */\r\n        Unweighted_Legacy = 0,\r\n        /** The normals are not weighted.\r\n         */\r\n        Unweighted = 1,\r\n        /** The normals are weighted by the face area.\r\n         */\r\n        AreaWeighted = 2,\r\n        /** The normals are weighted by the vertex angle on each face.\r\n         */\r\n        AngleWeighted = 3,\r\n        /** The normals are weighted by both the face area and the vertex angle on each face.\r\n         */\r\n        AreaAndAngleWeighted = 4,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Source of smoothing information for calculation of normals in ModelImporter.\r\n     */\r\n    enum ModelImporterNormalSmoothingSource {\r\n        /** Use smoothing groups if they are present in the Model file, otherwise use angle (default).\r\n         */\r\n        PreferSmoothingGroups = 0,\r\n        /** Use smoothing groups to determine which edges are smooth and which are hard.\r\n         */\r\n        FromSmoothingGroups = 1,\r\n        /** Use the angle between adjacent faces to determine if an edge is smooth or hard.\r\n         */\r\n        FromAngle = 2,\r\n        /** Do not create hard edges.\r\n         */\r\n        None = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Vertex tangent generation options for ModelImporter.\r\n     */\r\n    enum ModelImporterTangents {\r\n        /** Import vertex tangents from model file.\r\n         */\r\n        Import = 0,\r\n        /** Calculate tangents with legacy algorithm.\r\n         */\r\n        CalculateLegacy = 1,\r\n        /** Do not import vertex tangents.\r\n         */\r\n        None = 2,\r\n        /** Calculate tangents using MikkTSpace (default).\r\n         */\r\n        CalculateMikk = 3,\r\n        /** Calculate tangents with legacy algorithm, with splits across UV charts.\r\n         */\r\n        CalculateLegacyWithSplitTangents = 4,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Mesh compression options for ModelImporter.\r\n     */\r\n    enum ModelImporterMeshCompression {\r\n        /** No mesh compression (default).\r\n         */\r\n        Off = 0,\r\n        /** Low amount of mesh compression.\r\n         */\r\n        Low = 1,\r\n        /** Medium amount of mesh compression.\r\n         */\r\n        Medium = 2,\r\n        /** High amount of mesh compression.\r\n         */\r\n        High = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Format of the imported mesh index buffer data.\r\n     */\r\n    enum ModelImporterIndexFormat {\r\n        /** Use 16 or 32 bit index buffer depending on mesh size.\r\n         */\r\n        Auto = 0,\r\n        /** Use 16 bit index buffer.\r\n         */\r\n        UInt16 = 1,\r\n        /** Use 32 bit index buffer.\r\n         */\r\n        UInt32 = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Animation compression options for ModelImporter.\r\n     */\r\n    enum ModelImporterAnimationCompression {\r\n        /** No animation compression.\r\n         */\r\n        Off = 0,\r\n        /** Perform keyframe reduction.\r\n         */\r\n        KeyframeReduction = 1,\r\n        /** Perform keyframe reduction and compression.\r\n         */\r\n        KeyframeReductionAndCompression = 2,\r\n        /** Perform keyframe reduction and choose the best animation curve representation at runtime to reduce memory footprint (default).\r\n         */\r\n        Optimal = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Animation generation options for ModelImporter. These options relate to the legacy Animation system, they should only be used when ModelImporter.animationType==ModelImporterAnimationType.Legacy.\r\n     */\r\n    enum ModelImporterGenerateAnimations {\r\n        /** Do not generate animations.\r\n         */\r\n        None = 0,\r\n        /** Generate animations in the root objects of the animation package.\r\n         */\r\n        InOriginalRoots = 1,\r\n        /** Generate animations in the objects that animate.\r\n         */\r\n        InNodes = 2,\r\n        /** Generate animations in the transform root objects.\r\n         */\r\n        InRoot = 3,\r\n        /** Default animation import mode (All animations are stored in the root object).\r\n         */\r\n        GenerateAnimations = 4,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Animation mode for ModelImporter.\r\n     */\r\n    enum ModelImporterAnimationType {\r\n        /** Generate no animation data.\r\n         */\r\n        None = 0,\r\n        /** Generate a legacy animation type.\r\n         */\r\n        Legacy = 1,\r\n        /** Generate a generic animator.\r\n         */\r\n        Generic = 2,\r\n        /** Generate a human animator.\r\n         */\r\n        Human = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Humanoid Oversampling available multipliers.\r\n     */\r\n    enum ModelImporterHumanoidOversampling {\r\n        /** Default Humanoid Oversampling multiplier = 1 which is equivalent to no oversampling.\r\n         */\r\n        X1 = 1,\r\n        /** Humanoid Oversampling samples at 2 times the sampling rate found in the imported file.\r\n         */\r\n        X2 = 2,\r\n        /** Humanoid Oversampling samples at 4 times the sampling rate found in the imported file.\r\n         */\r\n        X4 = 4,\r\n        /** Humanoid Oversampling samples at 8 times the sampling rate found in the imported file.\r\n         */\r\n        X8 = 8,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Methods for handling margins during lightmap UV generation in ModelImporter.\r\n     */\r\n    enum ModelImporterSecondaryUVMarginMethod {\r\n        /** Specify pack margin manually.\r\n         */\r\n        Manual = 0,\r\n        /** Calculate suitable lightmap UV margins based on expected lightmap resolution and object scale.\r\n         */\r\n        Calculate = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Set the Avatar generation mode for ModelImporter.\r\n     */\r\n    enum ModelImporterAvatarSetup {\r\n        /** Disable Avatar creation for this model.\r\n         */\r\n        NoAvatar = 0,\r\n        /** Create the Avatar from this model and save it as a sub-asset.\r\n         */\r\n        CreateFromThisModel = 1,\r\n        /** Copy the Avatar from another model.\r\n         */\r\n        CopyFromOther = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Skin weights options for ModelImporter.\r\n     */\r\n    enum ModelImporterSkinWeights {\r\n        /** Import the standard number of bones per vertex (currently 4).\r\n         */\r\n        Standard = 0,\r\n        /** Import a custom number of bones per vertex.\r\n         */\r\n        Custom = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Behaviour } from \"UnityEngine\";\r\n    /** This provides an auto dispose Localization system. This can be called recursively.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class LocalizationGroup extends Object {\r\n        constructor(behaviour: Behaviour)\r\n        constructor(type: any)\r\n        constructor(obj: Object)\r\n        constructor()\r\n        Dispose(): void\r\n        /** A current group name for the localization.\r\n         */\r\n        readonly locGroupName: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Color, Vector2, GameObject, Camera } from \"UnityEngine\";\r\n    /** This class contains the settings controlling the Physics Debug Visualization.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class PhysicsVisualizationSettings extends Object {\r\n        static Reset(): void\r\n        static GetShowStaticColliders(): boolean\r\n        /** Should the Colliders without a Rigidbody component be considered by the display filter.\r\n         */\r\n        static SetShowStaticColliders(show: boolean): void\r\n        static GetShowTriggers(): boolean\r\n        /** Should the triggers be considered by the display filter.\r\n         */\r\n        static SetShowTriggers(show: boolean): void\r\n        static GetShowRigidbodies(): boolean\r\n        /** Should any Rigidbodies be considered by the display filter.\r\n         */\r\n        static SetShowRigidbodies(show: boolean): void\r\n        static GetShowKinematicBodies(): boolean\r\n        /** Should the kinematic Rigidbodies be considered by the display filter.\r\n         */\r\n        static SetShowKinematicBodies(show: boolean): void\r\n        static GetShowArticulationBodies(): boolean\r\n        /** Should Articulation Bodies be shown by the Physics Visualizer.\r\n         * @param show Value to set.\r\n         */\r\n        static SetShowArticulationBodies(show: boolean): void\r\n        static GetShowSleepingBodies(): boolean\r\n        /** Should sleeping Rigidbodies and Articulation Bodies be considered by the display filter.\r\n         */\r\n        static SetShowSleepingBodies(show: boolean): void\r\n        /** Should the given layer be considered by the display filter.\r\n         */\r\n        static GetShowCollisionLayer(layer: number): boolean\r\n        /** Should the given layer be considered by the display filter.\r\n         */\r\n        static SetShowCollisionLayer(layer: number, show: boolean): void\r\n        static GetShowCollisionLayerMask(): number\r\n        /** Should the mask representing the layers be considered by the display filter.\r\n         */\r\n        static SetShowCollisionLayerMask(mask: number): void\r\n        static GetShowBoxColliders(): boolean\r\n        /** Should BoxColliders be shown.\r\n         */\r\n        static SetShowBoxColliders(show: boolean): void\r\n        static GetShowSphereColliders(): boolean\r\n        /** Should SphereColliders be shown.\r\n         */\r\n        static SetShowSphereColliders(show: boolean): void\r\n        static GetShowCapsuleColliders(): boolean\r\n        /** Should CapsuleColliders be shown.\r\n         */\r\n        static SetShowCapsuleColliders(show: boolean): void\r\n        static GetShowMeshColliders(colliderType: PhysicsVisualizationSettings.MeshColliderType): boolean\r\n        static SetShowMeshColliders(colliderType: PhysicsVisualizationSettings.MeshColliderType, show: boolean): void\r\n        static GetShowTerrainColliders(): boolean\r\n        /** Should TerrainColliders be shown.\r\n         */\r\n        static SetShowTerrainColliders(show: boolean): void\r\n        static GetShowPhysicsSceneMask(): number\r\n        /** Should the scene mask be considered by the display filter.\r\n         */\r\n        static SetShowPhysicsSceneMask(mask: number): void\r\n        static InitDebugDraw(): void\r\n        static DeinitDebugDraw(): void\r\n        static ClearMouseHighlight(): void\r\n        static HasMouseHighlight(): boolean\r\n        /** Updates the mouse-over highlight at the given mouse position in screen space.\r\n         */\r\n        static UpdateMouseHighlight(screenPos: Vector2): void\r\n        static PickClosestGameObject(cam: Camera, layers: number, position: Vector2, ignore: Array<GameObject>, filter: Array<GameObject>, materialIndex: jsb.Out<number>): GameObject\r\n        /** Enables or disables all filtering items.\r\n         */\r\n        static SetShowForAllFilters(selected: boolean): void\r\n        /** Shows extra options used to develop and debug the physics visualization.\r\n         */\r\n        static devOptions: boolean\r\n        /** Dirty marker used for refreshing the GUI.\r\n         */\r\n        static readonly dirtyCount: number\r\n        /** Should the PhysicsDebugWindow display the collision geometry.\r\n         */\r\n        static showCollisionGeometry: boolean\r\n        /** Enables the mouse-over highlighting and mouse selection modes.\r\n         */\r\n        static enableMouseSelect: boolean\r\n        /** Controls whether the SceneView or the GameView camera is used. Not shown in the UI.\r\n         */\r\n        static useSceneCam: boolean\r\n        /** Colliders within this distance will be displayed.\r\n         */\r\n        static viewDistance: number\r\n        /** Maximum number of mesh tiles available to draw all Terrain Colliders.\r\n         */\r\n        static terrainTilesMax: number\r\n        /** Forcing the drawing of Colliders on top of any other geometry, regardless of depth.\r\n         */\r\n        static forceOverdraw: boolean\r\n        /** Color for Colliders that do not have a Rigidbody component.\r\n         */\r\n        static staticColor: Color\r\n        /** Color for Rigidbodies, primarily active ones.\r\n         */\r\n        static rigidbodyColor: Color\r\n        /** Color for kinematic Rigidbodies.\r\n         */\r\n        static kinematicColor: Color\r\n        /** Color for Articulation Bodies.\r\n         */\r\n        static articulationBodyColor: Color\r\n        /** Color for Colliders that are Triggers.\r\n         */\r\n        static triggerColor: Color\r\n        /** Color for Rigidbodies that are controlled by the physics simulator, but are not currently being simulated.\r\n         */\r\n        static sleepingBodyColor: Color\r\n        /** Alpha amount used for transparency blending.\r\n         */\r\n        static baseAlpha: number\r\n        /** Used to disinguish neighboring Colliders.\r\n         */\r\n        static colorVariance: number\r\n        static dotAlpha: number\r\n        static forceDot: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PhysicsVisualizationSettings {\r\n        enum FilterWorkflow {\r\n            HideSelectedItems = 0,\r\n            ShowSelectedItems = 1,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PhysicsVisualizationSettings {\r\n        enum MeshColliderType {\r\n            Convex = 0,\r\n            NonConvex = 1,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    import { Vector3 } from \"UnityEngine\";\r\n    /** Structure to hold camera data extracted from a SketchUp file.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SketchUpImportCamera extends ValueType {\r\n        constructor()\r\n        /** The position of the camera.\r\n         */\r\n        position: Vector3\r\n        /** The position the camera is looking at.\r\n         */\r\n        lookAt: Vector3\r\n        /** Up vector of the camera.\r\n         */\r\n        up: Vector3\r\n        /** Field of view of the camera.\r\n         */\r\n        fieldOfView: number\r\n        /** Aspect ratio of the camera.\r\n         */\r\n        aspectRatio: number\r\n        /** The orthogonal projection size of the camera. This value only make sense if SketchUpImportCamera.isPerspective is false.\r\n         */\r\n        orthoSize: number\r\n        /** The far clipping plane distance.\r\n         */\r\n        nearPlane: number\r\n        /** The near clipping plane distance.\r\n         */\r\n        farPlane: number\r\n        /** Indicate if the camera is using a perspective or orthogonal projection.\r\n         */\r\n        isPerspective: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** Structure to hold scene data extracted from a SketchUp file.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SketchUpImportScene extends ValueType {\r\n        constructor()\r\n        /** The camera data of the SketchUp scene.\r\n         */\r\n        camera: SketchUpImportCamera\r\n        /** The name of the SketchUp scene.\r\n         */\r\n        name: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Array } from \"System\";\r\n    /** Derives from AssetImporter to handle importing of SketchUp files.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SketchUpImporter extends ModelImporter {\r\n        constructor()\r\n        GetScenes(): Array<SketchUpImportScene>\r\n        GetDefaultCamera(): SketchUpImportCamera\r\n        /** Retrieves the latitude Geo Coordinate imported from the SketchUp file.\r\n         */\r\n        readonly latitude: number\r\n        /** Retrieves the longitude Geo Coordinate imported from the SketchUp file.\r\n         */\r\n        readonly longitude: number\r\n        /** Retrieves the north correction value imported from the SketchUp file.\r\n         */\r\n        readonly northCorrection: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Behaviour, Rect, GUIStyle, Texture2D, Object } from \"UnityEngine\";\r\n    import { Array } from \"System\";\r\n    /** The default Inspector class for Terrain Layer.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class TerrainLayerInspector extends Editor {\r\n        constructor()\r\n        /** Applies the custom UI for the Terrain Layer object.\r\n         * @param customUI The custom UI object.\r\n         * @param terrain The Terrain object.\r\n         */\r\n        ApplyCustomUI(customUI: ITerrainLayerCustomUI, terrain: any): void\r\n        OnInspectorGUI(): void\r\n        HasPreviewGUI(): boolean\r\n        /** Draws the default Terrain Layer preview GUI.\r\n         */\r\n        OnPreviewGUI(r: Rect, background: GUIStyle): void\r\n        /** Draws the default Terrain Layer static preview.\r\n         */\r\n        RenderStaticPreview(assetPath: string, subAssets: Array<Object>, width: number, height: number): Texture2D\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Behaviour } from \"UnityEngine\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface ITerrainLayerCustomUI {\r\n        /** Draws the custom GUI for the terrain layer.\r\n         * @param terrainLayer The TerrainLayer object.\r\n         * @param terrain The Terrain object on which the TerrainLayer object, specified by the terrainLayer parameter, is selected.\r\n         * @returns Return false to have Unity draw the default TerrainLayer inspector. Otherwise draw the custom GUI and return true. \r\n         */\r\n        OnTerrainLayerGUI(terrainLayer: any, terrain: any): boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Behaviour, Object as Object1, Texture2D } from \"UnityEngine\";\r\n    /** A set of helper functions for using terrain layers.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class TerrainLayerUtility extends Object {\r\n        /** Helper function to show the layer selection window for selecting terrain layers in inspector.\r\n         * @param terrain Terrain tile.\r\n         * @param activeTerrainLayer Currently selected terrain layer index.\r\n         * @returns Newly selected terrain layer index. \r\n         */\r\n        static ShowTerrainLayersSelectionHelper(terrain: any, activeTerrainLayer: number): number\r\n        /** This helper function shows the Terrain Layer Inspector GUI nested inside the current Inspector GUI.\r\n         * @param terrain The Terrain from which the Terrain Layer originates.\r\n         * @param terrainLayer The Terrain Layer object to show the Inspector for.\r\n         * @param terrainLayerEditor Reference to a variable of type Editor in which Unity caches the Terrain Layer Inspector object.\r\n         * @param customGUI The custom Terrain Layer GUI object.\r\n         */\r\n        static ShowTerrainLayerGUI(terrain: any, terrainLayer: any, terrainLayerEditor: jsb.Ref<Editor>, customGUI: ITerrainLayerCustomUI): void\r\n        /** Checks whether the texture is a valid TerrainLayer diffuse texture. If it detects that the texture is not valid, it displays a warning message that identifies the issue.\r\n         * @param texture The texture to validate.\r\n         */\r\n        static ValidateDiffuseTextureUI(texture: Texture2D): void\r\n        /** Checks whether the texture is correctly imported as a normal map texture.\r\n         * @param texture The texture to check.\r\n         * @returns True if texture is correctly imported, otherwise false. \r\n         */\r\n        static CheckNormalMapTextureType(texture: Texture2D): boolean\r\n        /** Checks whether the texture is a valid TerrainLayer normal map texture. If it detects that the texture is not valid, it displays a warning message that identifies the issue.\r\n         * @param texture The texture to validate.\r\n         * @param normalMapTextureType The return value from the CheckNormalMapTextureType method indicating whether the texture is imported as a normal map.\r\n         */\r\n        static ValidateNormalMapTextureUI(texture: Texture2D, normalMapTextureType: boolean): void\r\n        /** Checks whether the texture is a valid TerrainLayer mask map texture. If it detects that the texture is not valid, it displays a warning message that identifies the issue.\r\n         * @param texture The texture to validate.\r\n         */\r\n        static ValidateMaskMapTextureUI(texture: Texture2D): void\r\n        /** Displays the tiling settings UI.\r\n         * @param terrainLayer The terrain layer that contains the tiling settings to display.\r\n         * @param tileSize The tile size property to display.\r\n         * @param tileOffset The tile offset property to display.\r\n         */\r\n        static TilingSettingsUI(tileSize: SerializedProperty, tileOffset: SerializedProperty): void\r\n        /** Displays the tiling settings UI.\r\n         * @param terrainLayer The terrain layer that contains the tiling settings to display.\r\n         * @param tileSize The tile size property to display.\r\n         * @param tileOffset The tile offset property to display.\r\n         */\r\n        static TilingSettingsUI(terrainLayer: any): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Texture case constants for TrueTypeFontImporter.\r\n     */\r\n    enum FontTextureCase {\r\n        /** Import basic ASCII character set.\r\n         */\r\n        ASCII = 0,\r\n        /** Only import upper case ASCII character set.\r\n         */\r\n        ASCIIUpperCase = 1,\r\n        /** Only import lower case ASCII character set.\r\n         */\r\n        ASCIILowerCase = 2,\r\n        /** Custom set of characters.\r\n         */\r\n        CustomSet = 3,\r\n        /** Render characters into font texture at runtime as needed.\r\n         */\r\n        Dynamic = -2,\r\n        /** Import a set of Unicode characters common for latin scripts.\r\n         */\r\n        Unicode = -1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Font rendering mode constants for TrueTypeFontImporter.\r\n     */\r\n    enum FontRenderingMode {\r\n        /** Use Anti-Aliased Font rendering. When using dynamic fonts, this is the mode which is fastest in rendering font textures.\r\n         */\r\n        Smooth = 0,\r\n        /** Use Anti-Aliased Font rendering with hinting. This forces character lines to run along pixel boundaries.\r\n         */\r\n        HintedSmooth = 1,\r\n        /** Use hinted font rendering without anti-aliasing. This is the crispest font rendering option, and may be most readable for small font sizes.\r\n         */\r\n        HintedRaster = 2,\r\n        /** Use the OS default font rendering mode. This mode is only available for dynamic fonts, as static fonts are generated at build time.\r\n         */\r\n        OSDefault = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Method used for calculating a font's ascent.\r\n     */\r\n    enum AscentCalculationMode {\r\n        /** Legacy bounding box method.\r\n         */\r\n        Legacy2x = 0,\r\n        /** Ascender method.\r\n         */\r\n        FaceAscender = 1,\r\n        /** Bounding box method.\r\n         */\r\n        FaceBoundingBox = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Array } from \"System\";\r\n    import { Object } from \"UnityEngine\";\r\n    /** AssetImporter for importing Fonts.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class TrueTypeFontImporter extends AssetImporter {\r\n        constructor()\r\n        /** Create an editable copy of the font asset at path.\r\n         */\r\n        GenerateEditableFont(path: string): any\r\n        /** Font size to use for importing the characters.\r\n         */\r\n        fontSize: number\r\n        /** If this is enabled, the actual font will be embedded into the asset for Dynamic fonts.\r\n         */\r\n        includeFontData: boolean\r\n        /** Calculation mode for determining font's ascent.\r\n         */\r\n        ascentCalculationMode: AscentCalculationMode\r\n        /** A custom set of characters to be included in the Font Texture.\r\n         */\r\n        customCharacters: string\r\n        /** Spacing between character images in the generated texture in pixels. This is useful if you want to render text using a shader which samples pixels outside of the character area (like an outline shader).\r\n         */\r\n        characterSpacing: number\r\n        /** Border pixels added to character images for padding. This is useful if you want to render text using a shader which needs to render outside of the character area (like an outline shader).\r\n         */\r\n        characterPadding: number\r\n        /** Font rendering mode to use for this font.\r\n         */\r\n        fontRenderingMode: FontRenderingMode\r\n        /** Set this property to true if you want to round the internal advance width of the font to the nearest integer.\r\n         */\r\n        shouldRoundAdvanceValue: boolean\r\n        /** The internal font name of the TTF file.\r\n         */\r\n        readonly fontTTFName: string\r\n        /** Use this to adjust which characters should be imported.\r\n         */\r\n        fontTextureCase: FontTextureCase\r\n        /** References to other fonts to be used looking for fallbacks.\r\n         */\r\n        fontReferences: Array<any>\r\n        /** An array of font names, to be used when includeFontData is set to false.\r\n         */\r\n        fontNames: Array<string>\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ScriptableObject, Vector3 } from \"UnityEngine\";\r\n    import { Enum } from \"System\";\r\n    /** GridPalette stores settings for Palette assets when shown in the Palette window.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class GridPalette extends ScriptableObject {\r\n        constructor()\r\n        /** Determines the Transparency Sorting Mode of Renderers in the Palette.\r\n         */\r\n        transparencySortMode: any\r\n        /** Determines the sorting axis if the Transparency Sort Mode is set to Custom Axis.\r\n         */\r\n        transparencySortAxis: Vector3\r\n        /** Determines the sizing of cells for a Palette.\r\n         */\r\n        cellSizing: GridPalette.CellSizing\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace GridPalette {\r\n        enum CellSizing {\r\n            Automatic = 0,\r\n            Manual = 100,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Enum } from \"System\";\r\n    /** Editor API for the EditorAnalytics feature.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class EditorAnalytics extends Object {\r\n        /** This API is used for registering an Editor Analytics event. Note: This API is for internal use only and is likely change in the future. Do not use in user code.\r\n         * @param eventName Name of the event.\r\n         * @param ver Event version number.\r\n         * @param maxEventPerHour Hourly limit for this event name.\r\n         * @param maxItems Maximum number of items in this event.\r\n         * @param vendorKey Vendor key name.\r\n         */\r\n        static RegisterEventWithLimit(eventName: string, maxEventPerHour: number, maxItems: number, vendorKey: string, ver: number): any\r\n        /** This API is used for registering an Editor Analytics event. Note: This API is for internal use only and is likely change in the future. Do not use in user code.\r\n         * @param eventName Name of the event.\r\n         * @param ver Event version number.\r\n         * @param maxEventPerHour Hourly limit for this event name.\r\n         * @param maxItems Maximum number of items in this event.\r\n         * @param vendorKey Vendor key name.\r\n         */\r\n        static RegisterEventWithLimit(eventName: string, maxEventPerHour: number, maxItems: number, vendorKey: string): any\r\n        /** This API is used to send an Editor Analytics event. Note: This API is for internal use only and is likely change in the future. Do not use in user code.\r\n         * @param eventName Name of the event.\r\n         * @param parameters Additional event data.\r\n         * @param ver Event version number.\r\n         */\r\n        static SendEventWithLimit(eventName: string, parameters: Object, ver: number): any\r\n        /** This API is used to send an Editor Analytics event. Note: This API is for internal use only and is likely change in the future. Do not use in user code.\r\n         * @param eventName Name of the event.\r\n         * @param parameters Additional event data.\r\n         * @param ver Event version number.\r\n         */\r\n        static SendEventWithLimit(eventName: string, parameters: Object): any\r\n        /** Use this API to set the event end point URL. Note: This API is for internal use only and is likely change in the future. Do not use in user code.\r\n         * @param eventName Name of the event.\r\n         * @param ver Event version number.\r\n         * @param endPoint Event end point URL.\r\n         */\r\n        static SetEventWithLimitEndPoint(eventName: string, endPoint: string, ver: number): any\r\n        /** Use the API to set the event property. Note: This API is for internal use only and is likely change in the future. Do not use in user code.\r\n         * @param eventName Name of the event.\r\n         * @param ver Event version number.\r\n         * @param eventPriority Event priority.\r\n         */\r\n        static SetEventWithLimitPriority(eventName: string, eventPriority: any, ver: number): any\r\n        /** Returns true when EditorAnalytics is enabled.\r\n         */\r\n        static readonly enabled: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Provides access to Editor Analytics session information.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class EditorAnalyticsSessionInfo extends Object {\r\n        /** A random, unique GUID identifying the current Editor session.\r\n         */\r\n        static readonly id: number\r\n        /** The number of Editor sessions that have occurred since the current instance of the Unity Editor was installed.\r\n         */\r\n        static readonly sessionCount: number\r\n        /** The length of the current session, in milliseconds.\r\n         */\r\n        static readonly elapsedTime: number\r\n        /** The total time, in milliseconds, that the Editor has been in focus during the current session.\r\n         */\r\n        static readonly focusedElapsedTime: number\r\n        /** The total time, in milliseconds, that the Editor has been in playmode during the current session.\r\n         */\r\n        static readonly playbackElapsedTime: number\r\n        /** The total time, in milliseconds, that the user interacted with the Editor since the beginning of the current session.\r\n         */\r\n        static readonly activeElapsedTime: number\r\n        /** A random GUID uniquely identifying an Editor installation.\r\n         */\r\n        static readonly userId: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor.MPE\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    /** ChannelClient is a WebSocket client that connects to Unity's ChannelService, which is a WebSocket server.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ChannelClient extends Object {\r\n        IsConnected(): boolean\r\n        /** Starts an existing ChannelClient so it listens to incoming and outgoing messages.\r\n         * @param autoTick Specifies whether Unity processes (ticks) this ChannelClient's incoming and outgoing messages automatically, or the user processes (ticks) them manually, either in the main thread or a dedicated thread.\r\n         */\r\n        Start(autoTick: boolean): void\r\n        Stop(): void\r\n        Close(): void\r\n        Tick(): void\r\n        /** Sends an ASCII or binary message to the ChannelService. Depending on how the channel's handler processes the message, it may also be sent to other connections.\r\n         * @param data Data to send.\r\n         * @param connectionId The connection ID of the client sending the data.\r\n         */\r\n        Send(data: string): void\r\n        /** Sends an ASCII or binary message to the ChannelService. Depending on how the channel's handler processes the message, it may also be sent to other connections.\r\n         * @param data Data to send.\r\n         * @param connectionId The connection ID of the client sending the data.\r\n         */\r\n        Send(data: Array<jsb.byte>): void\r\n        RegisterMessageHandler(handler: (obj: string) => void): () => void\r\n        RegisterMessageHandler(handler: (obj: Array<jsb.byte>) => void): () => void\r\n        UnregisterMessageHandler(handler: (obj: string) => void): void\r\n        UnregisterMessageHandler(handler: (obj: Array<jsb.byte>) => void): void\r\n        NewRequestId(): number\r\n        GetChannelClientInfo(): ChannelClientInfo\r\n        /** Sends an ASCII or binary message to the ChannelService. Depending on how the channel's handler processes the message, it may also be sent to other connections.\r\n         * @param data Data to send.\r\n         * @param connectionId The connection ID of the client sending the data.\r\n         */\r\n        static Send(connectionId: number, data: Array<jsb.byte>): void\r\n        /** Closes the ChannelClient. This closes the WebSocket client but not the Channel in the ChannelService. Other ChannelClients can still connect on the same Channel.\r\n         * @param channelName The name of the channel to close.\r\n         */\r\n        static Close(channelName: string): void\r\n        /** Creates a new ChannelClient on a specific channel. If a client already exists, this method gets the client.\r\n         * @param channelName The name of the channel to open. This matches the last part of a WebSocket URL. For example, \"127.0.0.1:9090/<channelName>\".\r\n         * @returns Instance of the newly-created or existing ChannelClient. \r\n         */\r\n        static GetOrCreateClient(channelName: string): ChannelClient\r\n        static Shutdown(): void\r\n        /** Gets the ChannelClientInfo for a specific channel.\r\n         * @param channelName The name of the channel to get information about.\r\n         * @param clientId The ID of the channel to get information about.\r\n         * @returns A structure that describes the channel. \r\n         */\r\n        static GetChannelClientInfo(channelName: string): ChannelClientInfo\r\n        /** Gets the ChannelClientInfo for a specific channel.\r\n         * @param channelName The name of the channel to get information about.\r\n         * @param clientId The ID of the channel to get information about.\r\n         * @returns A structure that describes the channel. \r\n         */\r\n        static GetChannelClientInfo(clientId: number): ChannelClientInfo\r\n        /** Creates a unique request ID for this ChannelClient in this instance of Unity. For more information about requests, see ChannelClient.Request.\r\n         * @param clientId The ChannelClient ID to generate the request from.\r\n         * @returns The request ID. \r\n         */\r\n        static NewRequestId(clientId: number): number\r\n        static GetChannelClientList(): Array<ChannelClientInfo>\r\n        protected constructor()\r\n        /** The channel ID, which essentially a hash of the channel name. See ChannelService.ChannelNameToId.\r\n         */\r\n        readonly clientId: number\r\n        /** The name of the channel this ChannelClient is connected to. The name matches the route of the URL used to connect to Unity's ChannelService. For example, 127.0.0.1:8928/<my Channel Name>.\r\n         */\r\n        readonly channelName: string\r\n        /** Specifies whether Unity processes (ticks) this ChannelClient's incoming and outgoing messages automatically, or the user processes (ticks) them manually, either in the main thread or a dedicated thread.\r\n         */\r\n        readonly isAutoTick: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor.MPE\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array } from \"System\";\r\n    /** Scope that can be use to open a channel client on a specific channel and close the channel when the scope ends.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ChannelClientScope extends ValueType {\r\n        constructor(autoTick: boolean, channelName: string, handler: (obj: string) => void, closeClientOnExit: boolean)\r\n        constructor(autoTick: boolean, channelName: string, handler: (obj: Array<jsb.byte>) => void, closeClientOnExit: boolean)\r\n        Dispose(): void\r\n        /** Get the Chanel client of this scope.\r\n         */\r\n        readonly client: ChannelClient\r\n    }\r\n}\r\ndeclare module \"UnityEditor.MPE\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    /** The ChannelService encapsulates a WebSocket server running in Unity.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class ChannelService extends Object {\r\n        static GetOrCreateChannel(channelName: string, handler: (arg1: number, arg2: Array<jsb.byte>) => void): () => void\r\n        static RegisterMessageHandler(channelName: string, handler: (arg1: number, arg2: Array<jsb.byte>) => void): () => void\r\n        static UnregisterMessageHandler(channelName: string, handler: (arg1: number, arg2: Array<jsb.byte>) => void): void\r\n        /** Closes a specific channel and all connections to that channel.\r\n         * @param channelName The name of the channel to close.\r\n         */\r\n        static CloseChannel(channelName: string): void\r\n        /** Sends a message to all  of a specific channel's ChannelClient connections.\r\n         * @param channelId The ID of the channel to send the message to.\r\n         * @param data The message to send. It can be binary or UTF8.\r\n         */\r\n        static Broadcast(channelId: number, data: Array<jsb.byte>): void\r\n        /** Sends a message to all  of a specific channel's ChannelClient connections.\r\n         * @param channelId The ID of the channel to send the message to.\r\n         * @param data The message to send. It can be binary or UTF8.\r\n         */\r\n        static Broadcast(channelId: number, data: string): void\r\n        /** Sends a message to a specific connection. The message can be binary or UTF8.\r\n         * @param connectionId The connection ID. This matches ChannelClientInfo.channelClientId.\r\n         * @param data Data to send to the connected client.\r\n         */\r\n        static Send(connectionId: number, data: Array<jsb.byte>): void\r\n        /** Sends a message to a specific connection. The message can be binary or UTF8.\r\n         * @param connectionId The connection ID. This matches ChannelClientInfo.channelClientId.\r\n         * @param data Data to send to the connected client.\r\n         */\r\n        static Send(connectionId: number, data: string): void\r\n        static GetAddress(): string\r\n        static GetPort(): number\r\n        static Start(): void\r\n        static Stop(): void\r\n        static IsRunning(): boolean\r\n        static GetChannelList(): Array<ChannelInfo>\r\n        static GetChannelClientList(): Array<ChannelClientInfo>\r\n        /** Sends a message to all  of a specific channel's ChannelClient connections.\r\n         * @param channelId The ID of the channel to send the message to.\r\n         * @param data The binary data to send.\r\n         */\r\n        static BroadcastBinary(channelId: number, data: Array<jsb.byte>): void\r\n        /** Closes a specific channel and all connections to that channel.\r\n         * @param channelName The ChannelName.\r\n         * @returns The ChannelId. \r\n         */\r\n        static ChannelNameToId(channelName: string): number\r\n    }\r\n}\r\ndeclare module \"UnityEditor.MPE\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array } from \"System\";\r\n    /** Scope that cna be use to open a channel and that will close the channel when the scope ends.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ChannelScope extends ValueType {\r\n        constructor(channelName: string, handler: (arg1: number, arg2: Array<jsb.byte>) => void, closeChannelOnExit: boolean)\r\n        Dispose(): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.MPE\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** The Serialization type for sending a message, with arguments, using the EventService. For more information about argument serialization, see ChannelService.Broadcast and ChannelService.Emit.\r\n     */\r\n    enum EventDataSerialization {\r\n        /** Use normal JSON to send a message using the [[EventService]. The receiving handler gets JSON objects (Dictionary<string, object>, List<object>, primitive types) as arguments of his ChannelHandler.\r\n         */\r\n        StandardJson = 0,\r\n        /** Use JsonUtility.ToJson to serialize a message argument. Additional metadata is added to the message to specify which type to convert the JSON to when it is received.\r\n         */\r\n        JsonUtility = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor.MPE\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array, Exception, Enum } from \"System\";\r\n    /** The EventService is a singleton implementation of a ChannelClient that runs on all instances of Unity. It is connected to the \"events\" channel and allows a Unity instance to send JSON messages to other EventServices in external process, or other instances of Unity.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class EventService extends Object {\r\n        static Start(): void\r\n        static Close(): void\r\n        static RegisterEventHandler(eventType: string, handler: (arg1: string, arg2: Array<Object>) => void): () => void\r\n        static RegisterEventHandler(eventType: string, handler: (arg1: string, arg2: Array<Object>) => Object): () => void\r\n        static UnregisterEventHandler(eventType: string, handler: (arg1: string, arg2: Array<Object>) => Object): void\r\n        static Clear(): void\r\n        /** Sends a fire-and-forget message to all ChannelClients connected to the \"events\" route.\r\n         * @param eventType The message's type name.\r\n         * @param args The arguments sent with the message.\r\n         * @param targetId When you send the event to a specific connection, this is the connection ID. By default it is set to -1, which sends the message to all other EventServices.\r\n         * @param eventDataSerialization Specifies how to serialize the request's arguments. This can be standard JSON, or JSON annotated with JsonUtility. You can use the latter to convert the argument to a concrete Unity object that supports JsonUtility.FromJson.\r\n         */\r\n        static Emit(eventType: string, args: Object, targetId: number, eventDataSerialization: EventDataSerialization): void\r\n        /** Sends a fire-and-forget message to all ChannelClients connected to the \"events\" route.\r\n         * @param eventType The message's type name.\r\n         * @param args The arguments sent with the message.\r\n         * @param targetId When you send the event to a specific connection, this is the connection ID. By default it is set to -1, which sends the message to all other EventServices.\r\n         * @param eventDataSerialization Specifies how to serialize the request's arguments. This can be standard JSON, or JSON annotated with JsonUtility. You can use the latter to convert the argument to a concrete Unity object that supports JsonUtility.FromJson.\r\n         */\r\n        static Emit(eventType: string, args: Array<Object>, targetId: number, eventDataSerialization: EventDataSerialization): void\r\n        /** Checks whether a request is pending on a specific event. For more information about Request, see EventService.Request.\r\n         * @param eventType Event type name.\r\n         * @returns True if there is a pending request for this event. False otherwise. \r\n         */\r\n        static IsRequestPending(eventType: string): boolean\r\n        /** Checks whether there is a pending request for a specific event and, if there is, cancels it. See EventService.Request for more details on Request.\r\n         * @param eventType The event to cancel.\r\n         * @param message The error message sent to the pending request.\r\n         * @returns Returns true if a pending request was found and cancelled false otherwise. \r\n         */\r\n        static CancelRequest(eventType: string, message: string): boolean\r\n        static Request(eventType: string, promiseHandler: (arg1: Exception, arg2: Array<Object>) => void, args: Object, timeoutInMs: number, eventDataSerialization: EventDataSerialization): void\r\n        static Request(eventType: string, promiseHandler: (arg1: Exception, arg2: Array<Object>) => void, args: Array<Object>, timeoutInMs: number, eventDataSerialization: EventDataSerialization): void\r\n        /** Sends a log message to the ChannelService. Log messages are printed to the Console window.\r\n         * @param msg The message to send.\r\n         * @param logType The type of the message (i.e. Info, Warning or Error).\r\n         */\r\n        static Log(msg: string, logType: any): void\r\n        /** Sends a log message to the ChannelService. Log messages are printed to the Console window.\r\n         * @param msg The message to send.\r\n         * @param logType The type of the message (i.e. Info, Warning or Error).\r\n         */\r\n        static Log(msg: string): void\r\n        static Tick(): void\r\n        /** The EventService connected to the ChannelService's \"events\" channel.\r\n         */\r\n        static readonly isConnected: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor.MPE\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Enum that represents the events a RoleProvider can receive.\r\n     */\r\n    enum ProcessEvent {\r\n        UMP_EVENT_UNDEFINED = 0,\r\n        Undefined = 0,\r\n        UMP_EVENT_CREATE = 1,\r\n        Create = 1,\r\n        UMP_EVENT_INITIALIZE = 2,\r\n        Initialize = 2,\r\n        /** Domain reload occurs.\r\n         */\r\n        UMP_EVENT_AFTER_DOMAIN_RELOAD = 3,\r\n        /** Domain reload occurs.\r\n         */\r\n        AfterDomainReload = 3,\r\n        UMP_EVENT_SHUTDOWN = 4,\r\n        Shutdown = 4,\r\n    }\r\n}\r\ndeclare module \"UnityEditor.MPE\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** The type of the current process. It can be a Unity master instance, or a slave instance connected to the master.\r\n     */\r\n    enum ProcessLevel {\r\n        UMP_UNDEFINED = 0,\r\n        Undefined = 0,\r\n        UMP_MASTER = 1,\r\n        Master = 1,\r\n        UMP_SLAVE = 2,\r\n        Slave = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor.MPE\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Describes the state of a specifc UnityEditor process.\r\n     */\r\n    enum ProcessState {\r\n        /** The queried UnityEditor process is unknown.\r\n         */\r\n        UMP_UNKNOWN_PROCESS = 0,\r\n        /** The queried UnityEditor process is unknown.\r\n         */\r\n        UnknownProcess = 0,\r\n        /** The queried UnityEditor process ended successfully.\r\n         */\r\n        UMP_FINISHED_SUCCESSFULLY = 1,\r\n        /** The queried UnityEditor process ended successfully.\r\n         */\r\n        FinishedSuccessfully = 1,\r\n        /** The queried UnityEditor process finished with an error.\r\n         */\r\n        UMP_FINISHED_WITH_ERROR = 2,\r\n        /** The queried UnityEditor process finished with an error.\r\n         */\r\n        FinishedWithError = 2,\r\n        UMP_RUNNING = 3,\r\n        Running = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor.MPE\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Object } from \"System\";\r\n    /** A structure that contains the connection information of a Channel in ChannelService.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ChannelInfo extends ValueType {\r\n        constructor()\r\n        Equals(obj: ChannelInfo): boolean\r\n        Equals(obj: Object): boolean\r\n        GetHashCode(): number\r\n        static op_Equality(x: ChannelInfo, y: ChannelInfo): boolean\r\n        static op_Inequality(x: ChannelInfo, y: ChannelInfo): boolean\r\n        // js_op_overloading: static ==(x: ChannelInfo, y: ChannelInfo): boolean\r\n        /** The name of the channel. This matches the route of the URL that connects to the ChannelService. For example, \"127.0.0.1:9292/<channelName>\".\r\n         */\r\n        readonly name: string\r\n        /** The ID of a specific channel. Normally this is the hash of the channel name.\r\n         */\r\n        readonly id: number\r\n        static invalidChannel: ChannelInfo\r\n    }\r\n}\r\ndeclare module \"UnityEditor.MPE\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Object } from \"System\";\r\n    /** A structure that contains all of a ChannelClient's connection data.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ChannelClientInfo extends ValueType {\r\n        constructor()\r\n        Equals(obj: ChannelClientInfo): boolean\r\n        Equals(obj: Object): boolean\r\n        GetHashCode(): number\r\n        static op_Equality(x: ChannelClientInfo, y: ChannelClientInfo): boolean\r\n        static op_Inequality(x: ChannelClientInfo, y: ChannelClientInfo): boolean\r\n        // js_op_overloading: static ==(x: ChannelClientInfo, y: ChannelClientInfo): boolean\r\n        /** The ChannelClient's name (see ChannelClient.channelName. This matches the route of the URL connecting to the ChannelService. For example, \"127.0.0.1:9292/<channelName>\".\r\n         */\r\n        readonly name: string\r\n        /** The channel's channel ID (see ChannelClient.clientId).\r\n         */\r\n        readonly clientId: number\r\n        /** The ChannelClient's connection ID.\r\n         */\r\n        readonly connectionId: number\r\n        static invalidClient: ChannelClientInfo\r\n    }\r\n}\r\ndeclare module \"UnityEditor.MPE\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { PropertyModification } from \"UnityEditor\";\r\n    import { Object as Object1 } from \"UnityEngine\";\r\n    /** *This is an experimental feature.* The ProcessService allows you to start slave instance of UnityEditor, opened to the same Project as the master instance, with a specific RoleProviderAttribute.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ProcessService extends Object {\r\n        constructor()\r\n        static IsChannelServiceStarted(): boolean\r\n        /** A utility function to read command line arguments passed to the current process.\r\n         * @param paramName Specific name of a command line parameter.\r\n         * @returns The parameter value. If empty, the parameter wasn't used on the command line. \r\n         */\r\n        static ReadParameter(paramName: string): string\r\n        /** Launches a slave instance of UnityEditor on the same project as the master instance.\r\n         * @param roleName The name that corresponds to the RoleProviderAttribute of the process to start.\r\n         * @param keyValuePairs Arguments passed to the slave process.\r\n         * @returns The process ID of the slave process. A value of 0 means the slave process could not be started. \r\n         */\r\n        static LaunchSlave(roleName: string, ...keyValuePairs: string[]): number\r\n        /** Terminates a slave process.\r\n         * @param pid The process ID of the slave process to terminate.\r\n         */\r\n        static TerminateSlave(pid: number): void\r\n        /** Gets the ProcessState of a given instance of UnityEditor.\r\n         * @param pid The process ID.\r\n         * @returns The state of the queried process. \r\n         */\r\n        static GetSlaveProcessState(pid: number): ProcessState\r\n        /** Checks whether the current process has a given capability.\r\n         * @param capName The capability name.\r\n         * @returns True if the process has the capability. False otherwise. \r\n         */\r\n        static HasCapability(capName: string): boolean\r\n        static ApplyPropertyModifications(modifications: Array<PropertyModification>): void\r\n        static SerializeObject(instanceId: number): Array<jsb.byte>\r\n        static DeserializeObject(bytes: Array<jsb.byte>): Object1\r\n        /** Enables a connection to the Profiler. The standalone Profiler uses this method.\r\n         * @param dataPath Where to save profiling data. Normally this is set to Application.dataPath.\r\n         * @returns Greater than 0 if successful. \r\n         */\r\n        static EnableProfileConnection(dataPath: string): number\r\n        static DisableProfileConnection(): void\r\n        /** The ProcessLevel of the running instance of UnityEditor.\r\n         */\r\n        static readonly level: ProcessLevel\r\n        /** The role name of the running UnityEditor process. For more information about how to register handlers for a specific process role, see RoleProviderAttribute. For a UnityEditor process of ProcessLevel Master, the roleName is always empty.\r\n         */\r\n        static readonly roleName: string\r\n        static SlaveProcessExitedEvent(op: \"add\" | \"remove\", fn: (arg1: number, arg2: ProcessState) => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Purchasing\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Editor API for the Unity Services editor feature. Normally Purchasing is enabled from the Services window, but if writing your own editor extension, this API can be used.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class PurchasingSettings extends Object {\r\n        /** This Boolean field will cause the Purchasing feature in Unity to be enabled if true, or disabled if false.\r\n         */\r\n        static enabled: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Analytics\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Editor API for the Unity Services editor feature. Normally Analytics is enabled from the Services window, but if writing your own editor extension, this API can be used.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class AnalyticsSettings extends Object {\r\n        /** If set to true, this Boolean field enables the Analytics feature in Unity. It disables the feature if it is set to false.\r\n         */\r\n        static enabled: boolean\r\n        /** Set to true for testing Analytics integration only within the Editor.\r\n         */\r\n        static testMode: boolean\r\n        /** Controls whether Unity initializes Analytics immediately on startup.\r\n         */\r\n        static initializeOnStartup: boolean\r\n        /** Reports whether device stats are enabled at runtime.\r\n         */\r\n        static readonly deviceStatsEnabledInBuild: boolean\r\n        /** Set the Analytics event end point.\r\n         */\r\n        static eventUrl: string\r\n        /** Set the Analytics config end point.\r\n         */\r\n        static configUrl: string\r\n        /** Get the Analytics dashboard endpoint.\r\n         */\r\n        static dashboardUrl: string\r\n        static OnRequireInBuildHandler(op: \"add\" | \"remove\", fn: () => boolean): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Analytics\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Normally performance reporting is enabled from the Services window, but if writing your own editor extension, this API can be used.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class PerformanceReportingSettings extends Object {\r\n        /** This Boolean field causes the performance reporting feature in Unity to be enabled if true, or disabled if false.\r\n         */\r\n        static enabled: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Advertisements\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Enum } from \"System\";\r\n    /** Editor API for the Unity Services editor feature. Normally UnityAds is enabled from the Services window, but if writing your own editor extension, this API can be used.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class AdvertisementSettings extends Object {\r\n        /** Gets the game identifier specified for a runtime platform.\r\n         * @returns The platform specific game identifier. \r\n         */\r\n        static GetGameId(platform: any): string\r\n        /** Sets the game identifier for the specified platform.\r\n         */\r\n        static SetGameId(platform: any, gameId: string): void\r\n        /** Gets the game identifier specified for a runtime platform.\r\n         * @returns The platform specific game identifier. \r\n         */\r\n        static GetPlatformGameId(platformName: string): string\r\n        /** Sets the game identifier for the specified platform.\r\n         */\r\n        static SetPlatformGameId(platformName: string, gameId: string): void\r\n        /** Global boolean for enabling or disabling the advertisement feature.\r\n         */\r\n        static enabled: boolean\r\n        /** Controls if testing advertisements are used instead of production advertisements.\r\n         */\r\n        static testMode: boolean\r\n        /** Controls if the advertisement system should be initialized immediately on startup.\r\n         */\r\n        static initializeOnStartup: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Events\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { UnityEvent, UnityEventBase } from \"UnityEngine.Events\";\r\n    /** Editor tools for working with persistent UnityEvents.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class UnityEventTools extends Object {\r\n        /** Adds a persistent, call to the listener. Will be invoked with the arguments as defined by the Event and sent from the call location.\r\n         * @param unityEvent Event to modify.\r\n         * @param call Function to call.\r\n         */\r\n        static AddPersistentListener(unityEvent: UnityEvent, call: () => void): void\r\n        /** Adds a persistent, call to the listener. Will be invoked with the arguments as defined by the Event and sent from the call location.\r\n         * @param unityEvent Event to modify.\r\n         * @param call Function to call.\r\n         */\r\n        static AddPersistentListener(unityEvent: UnityEventBase): void\r\n        /** Removes the given function from the event.\r\n         * @param unityEvent Event to modify.\r\n         * @param index Index to remove (if specified).\r\n         * @param call Function to remove (if specified).\r\n         */\r\n        static RemovePersistentListener(unityEvent: UnityEventBase, index: number): void\r\n        /** Removes the given function from the event.\r\n         * @param unityEvent Event to modify.\r\n         * @param index Index to remove (if specified).\r\n         * @param call Function to remove (if specified).\r\n         */\r\n        static RemovePersistentListener(unityEvent: UnityEventBase, call: () => void): void\r\n        /** Modifies the event at the given index.\r\n         * @param unityEvent Event to modify.\r\n         * @param index Index to modify.\r\n         * @param call Function to call.\r\n         */\r\n        static RegisterPersistentListener(unityEvent: UnityEvent, index: number, call: () => void): void\r\n        /** Unregisters the given listener at the specified index.\r\n         * @param unityEvent Event to modify.\r\n         * @param index Index to unregister.\r\n         */\r\n        static UnregisterPersistentListener(unityEvent: UnityEventBase, index: number): void\r\n        /** Adds a persistent, preset call to the listener.\r\n         * @param unityEvent Event to modify.\r\n         * @param call Function to call.\r\n         */\r\n        static AddVoidPersistentListener(unityEvent: UnityEventBase, call: () => void): void\r\n        /** Modifies the event at the given index.\r\n         * @param unityEvent Event to modify.\r\n         * @param index Index to modify.\r\n         * @param call Function to call.\r\n         */\r\n        static RegisterVoidPersistentListener(unityEvent: UnityEventBase, index: number, call: () => void): void\r\n        static AddIntPersistentListener(unityEvent: UnityEventBase, call: (id: number) => void, argument: number): void\r\n        static RegisterIntPersistentListener(unityEvent: UnityEventBase, index: number, call: (id: number) => void, argument: number): void\r\n        static AddFloatPersistentListener(unityEvent: UnityEventBase, call: (arg0: number) => void, argument: number): void\r\n        static RegisterFloatPersistentListener(unityEvent: UnityEventBase, index: number, call: (arg0: number) => void, argument: number): void\r\n        static AddBoolPersistentListener(unityEvent: UnityEventBase, call: (obj: boolean) => void, argument: boolean): void\r\n        static RegisterBoolPersistentListener(unityEvent: UnityEventBase, index: number, call: (obj: boolean) => void, argument: boolean): void\r\n        static AddStringPersistentListener(unityEvent: UnityEventBase, call: (obj: string) => void, argument: string): void\r\n        static RegisterStringPersistentListener(unityEvent: UnityEventBase, index: number, call: (obj: string) => void, argument: string): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Connect\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class UnityOAuth extends Object {\r\n        static GetAuthorizationCodeAsync(clientId: string, callback: (obj: UnityOAuth.AuthCodeResponse) => void): void\r\n        static UserLoggedIn(op: \"add\" | \"remove\", fn: () => void): void\r\n        static UserLoggedOut(op: \"add\" | \"remove\", fn: () => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Connect\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Exception } from \"System\";\r\n    namespace UnityOAuth {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class AuthCodeResponse extends ValueType {\r\n            constructor()\r\n            AuthCode: string\r\n            Exception: Exception\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** A bit field that contains the different categories of object that the object selector window can display.\r\n     */\r\n    enum VisibleObjects {\r\n        /** The object selector window cannot display any objects.\r\n         */\r\n        None = 0,\r\n        /** The object selector window can only display Assets.\r\n         */\r\n        Assets = 1,\r\n        /** The object selector window can only display GameObjects.\r\n         */\r\n        Scene = 2,\r\n        /** The object selector window can display all categories.\r\n         */\r\n        All = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Object as Object1 } from \"System\";\r\n    import { GlobalObjectId } from \"UnityEditor\";\r\n    import { Object } from \"UnityEngine\";\r\n    /** A structure that contains information about an item that is about to be shown.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ObjectSelectorTargetInfo extends ValueType {\r\n        constructor(globalObjectId: GlobalObjectId, targetObject: Object, type: any)\r\n        LoadObject(): Object\r\n        /** The object's global identifier. It is always valid.\r\n         */\r\n        readonly globalObjectId: GlobalObjectId\r\n        /** If the object is already loaded in Unity, this is its instance. The instance can be null.\r\n         */\r\n        readonly targetObject: Object\r\n        /** If the object is currently loaded in Unity, this is its underlying type. The type can be null.\r\n         */\r\n        readonly type: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, ValueType, Array } from \"System\";\r\n    import { Object as Object1 } from \"UnityEngine\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    /** A search context implementation for ObjectSelector search engines. All methods that are called on an ObjectSelector search engine, and expect a SearchService.ISearchContext, receive an object of this type.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ObjectSelectorSearchContext extends Object implements ISearchContext {\r\n        constructor()\r\n        /** A unique identifier for this search context.\r\n         */\r\n        readonly guid: any\r\n        /** An enum that identifies the scope of the current search. This property is automatically set to SearchService.ObjectSelector.EngineScope.\r\n         */\r\n        readonly engineScope: SearchEngineScope\r\n        /** Identifies the currently selected object.\r\n         */\r\n        currentObject: Object1\r\n        /** When the object selector is opened from an Inspector, this property indicates which objects are currently being edited.\r\n         */\r\n        editedObjects: Array<Object1>\r\n        /** An IEnumerable of types that contains the type constraints for this search.\r\n         */\r\n        requiredTypes: any\r\n        /** An IEnumerable of strings that contains the type name constraints for this search.\r\n         */\r\n        requiredTypeNames: IEnumerable<string>\r\n        /** Indicates which categories of objects are visible in the window. For example, GameObjects, Assets, or both.\r\n         */\r\n        visibleObjects: VisibleObjects\r\n        /** IEnumerable of integers that contains the instanceIds of objects that the search can include in its results.\r\n         */\r\n        allowedInstanceIds: any\r\n        selectorConstraint(op: \"get\"): (arg1: ObjectSelectorTargetInfo, arg2: Array<Object1>, arg3: ObjectSelectorSearchContext) => boolean\r\n        selectorConstraint(op: \"add\" | \"remove\" | \"set\", fn?: (arg1: ObjectSelectorTargetInfo, arg2: Array<Object1>, arg3: ObjectSelectorSearchContext) => boolean): void\r\n        selectorConstraint(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (arg1: ObjectSelectorTargetInfo, arg2: Array<Object1>, arg3: ObjectSelectorSearchContext) => boolean): (arg1: ObjectSelectorTargetInfo, arg2: Array<Object1>, arg3: ObjectSelectorSearchContext) => boolean | void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface IObjectSelectorEngine extends ISearchEngineBase, ISelectorEngine {\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Use this API to select objects. Engines for this type of search implement the SearchService.IObjectSelectorEngine interface.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class ObjectSelector extends Object {\r\n        /** Registers an ObjectSelector search engine dynamically.\r\n         * @param engine The ObjectSelector search engine to register.\r\n         */\r\n        static RegisterEngine(engine: IObjectSelectorEngine): void\r\n        /** Unregisters a dynamically registered engine.\r\n         * @param engine The ObjectSelector search engine to unregister.\r\n         */\r\n        static UnregisterEngine(engine: IObjectSelectorEngine): void\r\n        /** A enum that indicates the search scope of ObjectSelector engines. Used by ObjectSelectorSearchContext.\r\n         */\r\n        static readonly EngineScope: SearchEngineScope\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, ValueType } from \"System\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    /** A search context implementation for Project search engines. All methods that are called on a Project search engine, and expect a SearchService.ISearchContext, receive an object of this type.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ProjectSearchContext extends Object implements ISearchContext {\r\n        constructor()\r\n        /** A unique identifier for this search context.\r\n         */\r\n        readonly guid: any\r\n        /** An enum that identifies the scope of the current search. This property is automatically set to SearchService.Project.EngineScope.\r\n         */\r\n        readonly engineScope: SearchEngineScope\r\n        /** An IEnumerable of types that contains the type constraints for this search.\r\n         */\r\n        requiredTypes: any\r\n        /** An IEnumerable of strings that contains the type name constraints for this search.\r\n         */\r\n        requiredTypeNames: IEnumerable<string>\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface IProjectSearchEngine extends ISearchEngineBase {\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Use this API to perform searches in the Project. Engines for this type of search implement the SearchService.IProjectSearchEngine interface.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class Project extends Object {\r\n        /** Registers a Project search engine dynamically.\r\n         * @param engine The Project search engine to register.\r\n         */\r\n        static RegisterEngine(engine: IProjectSearchEngine): void\r\n        /** Unregisters a dynamically registered engine.\r\n         * @param engine The Project search engine to unregister.\r\n         */\r\n        static UnregisterEngine(engine: IProjectSearchEngine): void\r\n        /** A enum that indicates the search scope for Project engines. It is used by ProjectSearchContext.\r\n         */\r\n        static readonly EngineScope: SearchEngineScope\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, ValueType } from \"System\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    import { HierarchyProperty } from \"UnityEditor\";\r\n    /** A search context implementation for Scene search engines. All methods that are called on a Scene search engine, and expect a SearchService.ISearchContext, receive an object of this type.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SceneSearchContext extends Object implements ISearchContext {\r\n        constructor()\r\n        /** A unique identifier for this search context.\r\n         */\r\n        readonly guid: any\r\n        /** An enum that identifies the scope of the current search. This property is automatically set to SearchService.Scene.EngineScope.\r\n         */\r\n        readonly engineScope: SearchEngineScope\r\n        /** An IEnumerable of types that contains the type constraints for this search.\r\n         */\r\n        requiredTypes: any\r\n        /** An IEnumerable of strings that contains the type name constraints for this search.\r\n         */\r\n        requiredTypeNames: IEnumerable<string>\r\n        /** The root HierarchyProperty on which the search is started.\r\n         */\r\n        rootProperty: HierarchyProperty\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    import { HierarchyProperty } from \"UnityEditor\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface ISceneSearchEngine extends ISearchEngineBase {\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Use this API to perform searches in the Scene. Engines for this type of search implement the SearchService.ISceneSearchEngine interface.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class Scene extends Object {\r\n        /** Registers a Scene search engine dynamically.\r\n         * @param engine The Scene search engine to register.\r\n         */\r\n        static RegisterEngine(engine: ISceneSearchEngine): void\r\n        /** Unregisters a dynamically registered engine.\r\n         * @param engine The Scene search engine to unregister.\r\n         */\r\n        static UnregisterEngine(engine: ISceneSearchEngine): void\r\n        /** A enum that indicates the search scope for Scene engines. It is used by SceneSearchContext.\r\n         */\r\n        static readonly EngineScope: SearchEngineScope\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** An enumeration that contains the available search engine scopes.\r\n     */\r\n    enum SearchEngineScope {\r\n        /** Identifies a search for Scene engines.\r\n         */\r\n        Scene = 0,\r\n        /** Identifies a search for Project engines.\r\n         */\r\n        Project = 1,\r\n        /** Identifies a search for ObjectSelector engines.\r\n         */\r\n        ObjectSelector = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Object } from \"System\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface ISearchContext {\r\n        /** A unique identifier for this search context.\r\n         */\r\n        readonly guid: any\r\n        /** An enum that identifies the current search scope.\r\n         */\r\n        readonly engineScope: SearchEngineScope\r\n        /** IEnumerable of types that contains the type constraints for this search.\r\n         */\r\n        readonly requiredTypes: any\r\n        /** An IEnumerable of strings that contains the type name constraints for this search.\r\n         */\r\n        readonly requiredTypeNames: IEnumerable<string>\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface ISearchEngineBase {\r\n        /** A function called at the beginning of a search session.\r\n         * @param context The search context.\r\n         */\r\n        BeginSession(context: ISearchContext): void\r\n        /** A function called at the end of a search session.\r\n         * @param context The search context.\r\n         */\r\n        EndSession(context: ISearchContext): void\r\n        /** A function called at the beginning of each search.\r\n         * @param context The search context.\r\n         * @param query The query string used for the search.\r\n         */\r\n        BeginSearch(context: ISearchContext, query: string): void\r\n        /** A function called at the end of a search.\r\n         * @param context The search context.\r\n         */\r\n        EndSearch(context: ISearchContext): void\r\n        /** The name displayed in the Preferences window in the Unity Editor. This name is used to store the active engine in the preferences.\r\n         */\r\n        readonly name: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface ISearchEngine<T> extends ISearchEngineBase {\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface IFilterEngine<T> extends ISearchEngineBase {\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SearchService\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface ISelectorEngine extends ISearchEngineBase {\r\n        SelectObject(context: ISearchContext, onObjectSelectorClosed: (arg1: Object, arg2: boolean) => void, onObjectSelectedUpdated: (obj: Object) => void): boolean\r\n        /** This function is called when the initial search text for the object selector window is set.\r\n         * @param context The search context.\r\n         * @param searchFilter The search filter to set on the object selector window.\r\n         */\r\n        SetSearchFilter(context: ISearchContext, searchFilter: string): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Scripting\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Representation of managed debugger in UnityEditor.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ManagedDebugger extends Object {\r\n        constructor()\r\n        static Disconnect(): void\r\n        /** Returns true if there is a managed debugger attached to the UnityEditor, or false if there is not.\r\n         */\r\n        static readonly isAttached: boolean\r\n        /** Returns true if managed debugger is enabled, or false if it is not.\r\n         */\r\n        static readonly isEnabled: boolean\r\n        static debuggerAttached(op: \"add\" | \"remove\", fn: (obj: boolean) => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.ProjectWindowCallback\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ScriptableObject } from \"UnityEngine\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class EndNameEditAction extends ScriptableObject {\r\n        OnEnable(): void\r\n        /** Unity calls this function when the user accepts an edited name, either by pressing the Enter key or by losing the keyboard input focus.\r\n         * @param instanceId The instance ID of the edited asset.\r\n         * @param pathName The path to the asset.\r\n         * @param resourceFile The resource file string argument passed to ProjectWindowUtil.StartNameEditingIfProjectWindowExists.\r\n         */\r\n        Action(instanceId: number, pathName: string, resourceFile: string): void\r\n        /** Unity calls this function when the user presses the Escape key to cancel editing a name.\r\n         * @param instanceId The instance ID of the asset that the user attempted to edit.\r\n         * @param pathName The path to the asset.\r\n         * @param resourceFile The resource file string argument passed to ProjectWindowUtil.StartNameEditingIfProjectWindowExists.\r\n         */\r\n        Cancelled(instanceId: number, pathName: string, resourceFile: string): void\r\n        CleanUp(): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Playables\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Editor extensions for all types that implement IPlayableOutput.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class PlayableOutputEditorExtensions extends Object {\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Playables\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, ValueType, Array } from \"System\";\r\n    /** Editor utility functions for the Playable graph and its nodes.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class Utility extends Object {\r\n        static GetAllGraphs(): Array<any>\r\n        static graphCreated(op: \"add\" | \"remove\", fn: (obj: any) => void): void\r\n        static destroyingGraph(op: \"add\" | \"remove\", fn: (obj: any) => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Media\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** Rational number useful for expressing fractions precisely.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class MediaRational extends ValueType {\r\n        constructor(numerator: number, denominator: number)\r\n        constructor(numerator: number)\r\n        /** Sets the numerator and denominator, performing normalization.\r\n         * @param numerator New value for the rational numerator.\r\n         * @param denominator New value for the rational denominator.\r\n         */\r\n        Set(numerator: number, denominator: number): void\r\n        static op_Explicit(r: MediaRational): number\r\n        /** The inverse of the rational number.\r\n         */\r\n        readonly inverse: MediaRational\r\n        /** Whether the rational number is valid.\r\n         */\r\n        readonly isValid: boolean\r\n        /** Whether the rational number is zero.\r\n         */\r\n        readonly isZero: boolean\r\n        /** Whether the rational number is negative.\r\n         */\r\n        readonly isNegative: boolean\r\n        /** Invalid rational value.\r\n         */\r\n        static readonly Invalid: MediaRational\r\n        /** Fraction numerator.\r\n         */\r\n        numerator: number\r\n        /** Fraction denominator.\r\n         */\r\n        denominator: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Media\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** Time representation for use with media containers.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class MediaTime extends ValueType {\r\n        constructor(count: number, rateNumerator: number, rateDenominator: number)\r\n        constructor(seconds: number)\r\n        static op_Explicit(t: MediaTime): number\r\n        /** The sample count for the time value.\r\n         */\r\n        count: number\r\n        /** The rate used for converting the count into seconds.\r\n         */\r\n        rate: MediaRational\r\n        /** Invalid time value.\r\n         */\r\n        static readonly Invalid: MediaTime\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Media\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    import { VideoBitrateMode } from \"UnityEditor\";\r\n    /** Descriptor for audio track format.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class VideoTrackAttributes extends ValueType {\r\n        constructor()\r\n        /** Frames per second.\r\n         */\r\n        frameRate: MediaRational\r\n        /** Image width in pixels.\r\n         */\r\n        width: number\r\n        /** Image height in pixels.\r\n         */\r\n        height: number\r\n        /** True if the track is to include the alpha channel found in the texture passed to AddFrame. False otherwise.\r\n         */\r\n        includeAlpha: boolean\r\n        /** VideoBitrateMode for the encoded video.\r\n         */\r\n        bitRateMode: VideoBitrateMode\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Media\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** Descriptor for audio track format.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AudioTrackAttributes extends ValueType {\r\n        constructor()\r\n        /** Audio sampling rate.\r\n         */\r\n        sampleRate: MediaRational\r\n        /** Number of channels.\r\n         */\r\n        channelCount: number\r\n        /** Dialogue language, if applicable.  Can be empty.\r\n         */\r\n        language: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Media\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array, Enum, ValueType } from \"System\";\r\n    import { Texture2D } from \"UnityEngine\";\r\n    /** Encodes images and audio samples into an audio or movie file.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class MediaEncoder extends Object {\r\n        constructor(filePath: string, videoAttrs: VideoTrackAttributes, audioAttrs: Array<AudioTrackAttributes>)\r\n        constructor(filePath: string, videoAttrs: VideoTrackAttributes, audioAttrs: AudioTrackAttributes)\r\n        constructor(filePath: string, videoAttrs: VideoTrackAttributes)\r\n        constructor(filePath: string, audioAttrs: Array<AudioTrackAttributes>)\r\n        constructor(filePath: string, audioAttrs: AudioTrackAttributes)\r\n        AddFrame(width: number, height: number, rowBytes: number, format: any, data: any, time: MediaTime): boolean\r\n        AddFrame(width: number, height: number, rowBytes: number, format: any, data: any): boolean\r\n        /** Appends a frame to the file's video track.\r\n         * @param texture Texture containing the pixels to be written into the track for the current frame.\r\n         * @param time Timestamp for the new frame.\r\n         * @returns True if the operation succeeded. False otherwise. \r\n         */\r\n        AddFrame(texture: Texture2D, time: MediaTime): boolean\r\n        /** Appends a frame to the file's video track.\r\n         * @param texture Texture containing the pixels to be written into the track for the current frame.\r\n         * @param time Timestamp for the new frame.\r\n         * @returns True if the operation succeeded. False otherwise. \r\n         */\r\n        AddFrame(texture: Texture2D): boolean\r\n        AddSamples(trackIndex: number, interleavedSamples: any): boolean\r\n        AddSamples(interleavedSamples: any): boolean\r\n        Dispose(): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.EditorTools\" {\r\n    import * as jsb from \"jsb\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface IDrawSelectedHandles {\r\n        OnDrawHandles(): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.EditorTools\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ScriptableObject, Object, GUIContent } from \"UnityEngine\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    import { EditorWindow } from \"UnityEditor\";\r\n    /** Use this class to implement custom editor tools. This is the base class from which all editor tools are inherited.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class EditorTool extends ScriptableObject {\r\n        OnActivated(): void\r\n        OnWillBeDeactivated(): void\r\n        /** Use this method to implement a custom editor tool.\r\n         * @param window The window that is displaying the custom editor tool.\r\n         */\r\n        OnToolGUI(window: EditorWindow): void\r\n        IsAvailable(): boolean\r\n        /** An array of the objects being inspected.\r\n         */\r\n        readonly targets: any\r\n        /** The object being inspected.\r\n         */\r\n        readonly target: Object\r\n        /** The icon and tooltip for this custom editor tool. If this function is not implemented, the toolbar displays the Inspector icon for the target type. If no target type is defined, the toolbar displays the Tool Mode icon.\r\n         */\r\n        readonly toolbarIcon: GUIContent\r\n    }\r\n}\r\ndeclare module \"UnityEditor.EditorTools\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ScriptableObject } from \"UnityEngine\";\r\n    import { EditorWindow, Tool } from \"UnityEditor\";\r\n    import { Object } from \"System\";\r\n    /** Use this class to implement specialized versions of the built-in transform tools. Built-in transform tools include Move, Rotate, Scale, Rect, and Transform.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class EditorToolContext extends ScriptableObject {\r\n        /** Implements any common functionality for the set of manipulation tools available for this context.\r\n         * @param window The window that is displaying the active EditorTool.\r\n         */\r\n        OnToolGUI(window: EditorWindow): void\r\n        /** Returns the matching EditorTool type for the specified Tool given the context.\r\n         * @param tool The Tool to resolve to an EditorTool type.\r\n         * @returns An EditorTool type for the requested Tool. \r\n         */\r\n        ResolveTool(tool: Tool): any\r\n    }\r\n}\r\ndeclare module \"UnityEditor.EditorTools\" {\r\n    import * as jsb from \"jsb\";\r\n    /** This class represents the default context for manipulation tools. When GameObjectToolContext is active, manipulation tools affect the transform property of GameObjects in the SceneView Selection.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class GameObjectToolContext extends EditorToolContext {\r\n        protected constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor.EditorTools\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** This class manipulates editor tools in the Scene view.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class ToolManager extends Object {\r\n        /** Sets the active EditorToolContext.\r\n         * @param context The EditorToolContext type to be set as the active tool.\r\n         */\r\n        static SetActiveContext(context: any): void\r\n        /** Sets the active EditorTool.\r\n         * @param type The EditorTool type to set as the active tool.\r\n         * @param tool The EditorTool instance to set as the active tool.\r\n         */\r\n        static SetActiveTool(type: any): void\r\n        /** Sets the active EditorTool.\r\n         * @param type The EditorTool type to set as the active tool.\r\n         * @param tool The EditorTool instance to set as the active tool.\r\n         */\r\n        static SetActiveTool(tool: EditorTool): void\r\n        static RestorePreviousTool(): void\r\n        static RestorePreviousPersistentTool(): void\r\n        /** Test if an EditorTool is currently the active tool.\r\n         * @param tool The EditorTool to compare with the active tool.\r\n         * @returns Returns true if the tool is active, false if it is not the active tool. \r\n         */\r\n        static IsActiveTool(tool: EditorTool): boolean\r\n        /** Gets the type of EditorToolContext that is currently active. The default value is GameObjectToolContext.\r\n         */\r\n        static readonly activeContextType: any\r\n        /** Gets the type of the EditorTool that is currently active.\r\n         */\r\n        static readonly activeToolType: any\r\n        static activeToolChanging(op: \"add\" | \"remove\", fn: () => void): void\r\n        static activeToolChanged(op: \"add\" | \"remove\", fn: () => void): void\r\n        static activeContextChanging(op: \"add\" | \"remove\", fn: () => void): void\r\n        static activeContextChanged(op: \"add\" | \"remove\", fn: () => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Color, Vector3, Quaternion, EventType } from \"UnityEngine\";\r\n    /** A class for a compound handle to edit an angle and a radius in the Scene view.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ArcHandle extends Object {\r\n        constructor()\r\n        /** Sets angleHandleColor, wireframeColor, and fillColor to the same value, where fillColor will have the specified alpha value. radiusHandleColor will be set to Color.clear and the radius handle will be disabled.\r\n         * @param color The color to use for the angle control handle and the fill shape.\r\n         * @param fillColorAlpha The alpha value to use for fillColor.\r\n         */\r\n        SetColorWithoutRadiusHandle(color: Color, fillColorAlpha: number): void\r\n        /** Sets angleHandleColor, radiusHandleColor, wireframeColor, and fillColor to the same value, where fillColor will have the specified alpha value.\r\n         * @param color The color to use for the angle and radius control handles and the fill shape.\r\n         * @param fillColorAlpha The alpha value to use for fillColor.\r\n         */\r\n        SetColorWithRadiusHandle(color: Color, fillColorAlpha: number): void\r\n        DrawHandle(): void\r\n        /** A Handles.CapFunction that draws a line terminated with Handles.CylinderHandleCap.\r\n         * @param controlID The control ID for the handle.\r\n         * @param position The position of the handle in the space of Handles.matrix.\r\n         * @param rotation The rotation of the handle in the space of Handles.matrix.\r\n         * @param size The size of the handle in the space of Handles.matrix. Use HandleUtility.GetHandleSize if you want a constant screen-space size.\r\n         * @param eventType Event type for the handle to act upon. By design it handles EventType.Layout and EventType.Repaint events.\r\n         */\r\n        static DefaultAngleHandleDrawFunction(controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType): void\r\n        /** A Handles.SizeFunction that returns a fixed screen-space size.\r\n         * @param position The current position of the handle in the space of Handles.matrix.\r\n         * @returns The size to use for a handle at the specified position. \r\n         */\r\n        static DefaultAngleHandleSizeFunction(position: Vector3): number\r\n        /** A Handles.SizeFunction that returns a fixed screen-space size.\r\n         * @param position The current position of the handle in the space of Handles.matrix.\r\n         * @returns The size to use for a handle at the specified position. \r\n         */\r\n        static DefaultRadiusHandleSizeFunction(position: Vector3): number\r\n        /** Returns or specifies the angle of the arc for the handle.\r\n         */\r\n        angle: number\r\n        /** Returns or specifies the radius of the arc for the handle.\r\n         */\r\n        radius: number\r\n        /** Returns or specifies the color of the angle control handle.\r\n         */\r\n        angleHandleColor: Color\r\n        /** Returns or specifies the color of the radius control handle.\r\n         */\r\n        radiusHandleColor: Color\r\n        /** Returns or specifies the color of the arc shape.\r\n         */\r\n        fillColor: Color\r\n        /** Returns or specifies the color of the curved line along the outside of the arc.\r\n         */\r\n        wireframeColor: Color\r\n        angleHandleDrawFunction(op: \"get\"): (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void\r\n        angleHandleDrawFunction(op: \"add\" | \"remove\" | \"set\", fn?: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void): void\r\n        angleHandleDrawFunction(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void): (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void | void\r\n        angleHandleSizeFunction(op: \"get\"): (position: Vector3) => number\r\n        angleHandleSizeFunction(op: \"add\" | \"remove\" | \"set\", fn?: (position: Vector3) => number): void\r\n        angleHandleSizeFunction(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (position: Vector3) => number): (position: Vector3) => number | void\r\n        radiusHandleDrawFunction(op: \"get\"): (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void\r\n        radiusHandleDrawFunction(op: \"add\" | \"remove\" | \"set\", fn?: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void): void\r\n        radiusHandleDrawFunction(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void): (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void | void\r\n        radiusHandleSizeFunction(op: \"get\"): (position: Vector3) => number\r\n        radiusHandleSizeFunction(op: \"add\" | \"remove\" | \"set\", fn?: (position: Vector3) => number): void\r\n        radiusHandleSizeFunction(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (position: Vector3) => number): (position: Vector3) => number | void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Enum } from \"System\";\r\n    import { Vector2, Color, Vector3, Quaternion, EventType } from \"UnityEngine\";\r\n    /** A class for a compound handle to edit multiaxial angular motion limits in the Scene view.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class JointAngularLimitHandle extends Object {\r\n        constructor()\r\n        DrawHandle(): void\r\n        /** Returns or specifies the minimum angular motion about the x-axis.\r\n         */\r\n        xMin: number\r\n        /** Returns or specifies the maximum angular motion about the x-axis.\r\n         */\r\n        xMax: number\r\n        /** Returns or specifies the minimum angular motion about the y-axis.\r\n         */\r\n        yMin: number\r\n        /** Returns or specifies the maximum angular motion about the y-axis.\r\n         */\r\n        yMax: number\r\n        /** Returns or specifies the minimum angular motion about the z-axis.\r\n         */\r\n        zMin: number\r\n        /** Returns or specifies the maximum angular motion about the z-axis.\r\n         */\r\n        zMax: number\r\n        /** Returns or specifies the range of valid values for angular motion about the x-axis. Defaults to [-180.0, 180.0].\r\n         */\r\n        xRange: Vector2\r\n        /** Returns or specifies the range of valid values for angular motion about the y-axis. Defaults to [-180.0, 180.0].\r\n         */\r\n        yRange: Vector2\r\n        /** Returns or specifies the range of valid values for angular motion about the z-axis. Defaults to [-180.0, 180.0].\r\n         */\r\n        zRange: Vector2\r\n        /** Returns or specifies how angular motion is limited about the x-axis. Defaults to ConfigurableJointMotion.Limited.\r\n         */\r\n        xMotion: any\r\n        /** Returns or specifies how angular motion is limited about the y-axis. Defaults to ConfigurableJointMotion.Limited.\r\n         */\r\n        yMotion: any\r\n        /** Returns or specifies how angular motion is limited about the z-axis. Defaults to ConfigurableJointMotion.Limited.\r\n         */\r\n        zMotion: any\r\n        /** Returns or specifies the color to use for the handle limiting motion around the x-axis. Defaults to Handles.xAxisColor.\r\n         */\r\n        xHandleColor: Color\r\n        /** Returns or specifies the color to use for the handle limiting motion around the y-axis. Defaults to Handles.yAxisColor.\r\n         */\r\n        yHandleColor: Color\r\n        /** Returns or specifies the color to use for the handle limiting motion around the z-axis. Defaults to Handles.zAxisColor.\r\n         */\r\n        zHandleColor: Color\r\n        /** Returns or specifies the radius of the arc for the handle. Defaults to 1.0.\r\n         */\r\n        radius: number\r\n        /** Returns or specifies the opacity to use when rendering fill shapes for the range of motion for each axis. Defaults to 0.1.\r\n         */\r\n        fillAlpha: number\r\n        /** Returns or specifies the opacity to use for the curved lines along the outside of the arcs of motion. Defaults to 1.0.\r\n         */\r\n        wireframeAlpha: number\r\n        angleHandleDrawFunction(op: \"get\"): (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void\r\n        angleHandleDrawFunction(op: \"add\" | \"remove\" | \"set\", fn?: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void): void\r\n        angleHandleDrawFunction(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void): (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void | void\r\n        angleHandleSizeFunction(op: \"get\"): (position: Vector3) => number\r\n        angleHandleSizeFunction(op: \"add\" | \"remove\" | \"set\", fn?: (position: Vector3) => number): void\r\n        angleHandleSizeFunction(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (position: Vector3) => number): (position: Vector3) => number | void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Vector3 } from \"UnityEngine\";\r\n    /** A compound handle to edit a box-shaped bounding volume in the Scene view.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class BoxBoundsHandle extends PrimitiveBoundsHandle {\r\n        constructor()\r\n        /** Returns or specifies the size of the bounding box.\r\n         */\r\n        size: Vector3\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Vector3, Color, Quaternion, EventType } from \"UnityEngine\";\r\n    /** Base class for a compound handle to edit a bounding volume in the Scene view.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class PrimitiveBoundsHandle extends Object {\r\n        /** Sets handleColor and wireframeColor to the same value.\r\n         * @param color The color to use for the control handles and the wireframe shape.\r\n         */\r\n        SetColor(color: Color): void\r\n        DrawHandle(): void\r\n        /** A Handles.SizeFunction that returns a fixed screen-space size.\r\n         * @param position The current position of the handle in the space of Handles.matrix.\r\n         * @returns The size to use for a handle at the specified position. \r\n         */\r\n        static DefaultMidpointHandleSizeFunction(position: Vector3): number\r\n        /** Returns or specifies the center of the bounding volume for the handle.\r\n         */\r\n        center: Vector3\r\n        /** Flags specifying which axes should display control handles.\r\n         */\r\n        axes: PrimitiveBoundsHandle.Axes\r\n        /** Returns or specifies the color of the control handles.\r\n         */\r\n        handleColor: Color\r\n        /** Returns or specifies the color of the wireframe shape.\r\n         */\r\n        wireframeColor: Color\r\n        midpointHandleDrawFunction(op: \"get\"): (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void\r\n        midpointHandleDrawFunction(op: \"add\" | \"remove\" | \"set\", fn?: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void): void\r\n        midpointHandleDrawFunction(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void): (controlID: number, position: Vector3, rotation: Quaternion, size: number, eventType: EventType) => void | void\r\n        midpointHandleSizeFunction(op: \"get\"): (position: Vector3) => number\r\n        midpointHandleSizeFunction(op: \"add\" | \"remove\" | \"set\", fn?: (position: Vector3) => number): void\r\n        midpointHandleSizeFunction(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (position: Vector3) => number): (position: Vector3) => number | void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    /** A compound handle to edit a capsule-shaped bounding volume in the Scene view.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class CapsuleBoundsHandle extends PrimitiveBoundsHandle {\r\n        constructor()\r\n        /** Returns or specifies the axis in the handle's space to which height maps. The radius maps to the remaining axes.\r\n         */\r\n        heightAxis: CapsuleBoundsHandle.HeightAxis\r\n        /** Returns or specifies the height of the capsule bounding volume.\r\n         */\r\n        height: number\r\n        /** Returns or specifies the radius of the capsule bounding volume.\r\n         */\r\n        radius: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace CapsuleBoundsHandle {\r\n        enum HeightAxis {\r\n            X = 0,\r\n            Y = 1,\r\n            Z = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    namespace PrimitiveBoundsHandle {\r\n        enum Axes {\r\n            None = 0,\r\n            X = 1,\r\n            Y = 2,\r\n            Z = 4,\r\n            All = 7,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    /** A compound handle to edit a sphere-shaped bounding volume in the Scene view.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SphereBoundsHandle extends PrimitiveBoundsHandle {\r\n        constructor()\r\n        /** Returns or specifies the radius of the sphere bounding volume.\r\n         */\r\n        radius: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Rect } from \"UnityEngine\";\r\n    /** The MultiColumnHeader is a general purpose class that e.g can be used with the TreeView to create multi-column tree views and list views.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class MultiColumnHeader extends Object {\r\n        constructor(state: MultiColumnHeaderState)\r\n        /** Sets multiple sorting columns and the associated sorting orders.\r\n         * @param columnIndices Column indices of the sorted columns.\r\n         * @param sortAscending Sorting order for the column indices specified.\r\n         */\r\n        SetSortingColumns(columnIndices: Array<number>, sortAscending: Array<boolean>): void\r\n        /** Sets the primary sorting column and its sorting order.\r\n         * @param columnIndex Column to sort.\r\n         * @param sortAscending Sorting order for the column specified.\r\n         */\r\n        SetSorting(columnIndex: number, sortAscending: boolean): void\r\n        /** Change sort direction for a given column.\r\n         * @param columnIndex Column index.\r\n         * @param sortAscending Direction of the sorting.\r\n         */\r\n        SetSortDirection(columnIndex: number, sortAscending: boolean): void\r\n        /** Check the sorting order state for a column.\r\n         * @param columnIndex Column index.\r\n         * @returns True if sorted ascending. \r\n         */\r\n        IsSortedAscending(columnIndex: number): boolean\r\n        /** Returns the column data for a given column index.\r\n         * @param columnIndex Column index.\r\n         * @returns Column data. \r\n         */\r\n        GetColumn(columnIndex: number): MultiColumnHeaderState.Column\r\n        /** Check if a column is currently visible in the MultiColumnHeader.\r\n         * @param columnIndex Column index.\r\n         */\r\n        IsColumnVisible(columnIndex: number): boolean\r\n        /** Convert from column index to visible column index.\r\n         * @param columnIndex Column index.\r\n         * @returns Visible column index. \r\n         */\r\n        GetVisibleColumnIndex(columnIndex: number): number\r\n        /** Calculates a cell rect for a column and row using the visibleColumnIndex and rowRect parameters.\r\n         */\r\n        GetCellRect(visibleColumnIndex: number, rowRect: Rect): Rect\r\n        /** Returns the header column Rect for a given visible column index.\r\n         * @param visibleColumnIndex Index of a visible column.\r\n         */\r\n        GetColumnRect(visibleColumnIndex: number): Rect\r\n        ResizeToFit(): void\r\n        /** Render and handle input for the MultiColumnHeader at the given rect.\r\n         * @param xScroll Horizontal scroll offset.\r\n         * @param rect Rect where the MultiColumnHeader is drawn in.\r\n         */\r\n        OnGUI(rect: Rect, xScroll: number): void\r\n        Repaint(): void\r\n        /** The index of the column that is set to be the primary sorting column. This is the column that shows the sorting arrow above the header text.\r\n         */\r\n        sortedColumnIndex: number\r\n        /** This is the state of the MultiColumnHeader.\r\n         */\r\n        state: MultiColumnHeaderState\r\n        /** Customizable height of the multi column header.\r\n         */\r\n        height: number\r\n        /** Use this property to control whether sorting is enabled for all the columns.\r\n         */\r\n        canSort: boolean\r\n        sortingChanged(op: \"add\" | \"remove\", fn: (multiColumnHeader: MultiColumnHeader) => void): void\r\n        visibleColumnsChanged(op: \"add\" | \"remove\", fn: (multiColumnHeader: MultiColumnHeader) => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    namespace MultiColumnHeader {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        abstract class DefaultGUI extends Object {\r\n            static readonly defaultHeight: number\r\n            static readonly minimumHeight: number\r\n            static readonly columnContentMargin: number\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { GUIStyle } from \"UnityEngine\";\r\n    namespace MultiColumnHeader {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        abstract class DefaultStyles extends Object {\r\n            static columnHeader: GUIStyle\r\n            static columnHeaderRightAligned: GUIStyle\r\n            static columnHeaderCenterAligned: GUIStyle\r\n            static background: GUIStyle\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    /** State used by the MultiColumnHeader.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class MultiColumnHeaderState extends Object {\r\n        constructor(columns: Array<MultiColumnHeaderState.Column>)\r\n        /** Checks if the source state can transfer its serialized data to the destination state.\r\n         * @param source State that have serialized data to be transfered to the destination state.\r\n         * @param destination Destination state.\r\n         * @returns Returns true if the source state have the same number of columns as the destination state. \r\n         */\r\n        static CanOverwriteSerializedFields(source: MultiColumnHeaderState, destination: MultiColumnHeaderState): boolean\r\n        /** Overwrites the seralized fields from the source state to the destination state.\r\n         * @param source State that have serialized data to be transfered to the destination state.\r\n         * @param destination Destination state.\r\n         */\r\n        static OverwriteSerializedFields(source: MultiColumnHeaderState, destination: MultiColumnHeaderState): void\r\n        /** This property holds the index to the primary sorted column.\r\n         */\r\n        sortedColumnIndex: number\r\n        /** This property controls the maximum number of columns returned by the sortedColumns property.\r\n         */\r\n        maximumNumberOfSortedColumns: number\r\n        /** The array of column indices for multiple column sorting.\r\n         */\r\n        sortedColumns: Array<number>\r\n        /** The array of column states used by the MultiColumnHeader class.\r\n         */\r\n        readonly columns: Array<MultiColumnHeaderState.Column>\r\n        /** This is the array of currently visible column indices.\r\n         */\r\n        visibleColumns: Array<number>\r\n        /** Returns the sum of all the widths of the visible columns in the visibleColumns array.\r\n         */\r\n        readonly widthOfAllVisibleColumns: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Enum } from \"System\";\r\n    import { GUIContent } from \"UnityEngine\";\r\n    namespace MultiColumnHeaderState {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class Column extends Object {\r\n            constructor()\r\n            width: number\r\n            sortedAscending: boolean\r\n            headerContent: GUIContent\r\n            contextMenuText: string\r\n            headerTextAlignment: any\r\n            sortingArrowAlignment: any\r\n            minWidth: number\r\n            maxWidth: number\r\n            autoResize: boolean\r\n            allowToggleVisibility: boolean\r\n            canSort: boolean\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Vector2 } from \"UnityEngine\";\r\n    /** The TreeViewState contains serializable state information for the TreeView.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class TreeViewState extends Object {\r\n        constructor()\r\n        /** Selected TreeViewItem IDs. Use of the SetSelection and IsSelected API will access this state.\r\n         */\r\n        selectedIDs: any\r\n        /** The ID for the TreeViewItem that currently is being used for multi selection and key navigation.\r\n         */\r\n        lastClickedID: number\r\n        /** This is the list of currently expanded TreeViewItem IDs.\r\n         */\r\n        expandedIDs: any\r\n        /** Search string state that can be used in the TreeView to filter the tree data when creating the TreeViewItems.\r\n         */\r\n        searchString: string\r\n        /** The current scroll values of the TreeView's scroll view.\r\n         */\r\n        scrollPos: Vector2\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Texture2D } from \"UnityEngine\";\r\n    /** The TreeViewItem is used to build the tree representation of a tree data structure.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class TreeViewItem extends Object {\r\n        constructor(id: number, depth: number, displayName: string)\r\n        constructor(id: number, depth: number)\r\n        constructor(id: number)\r\n        constructor()\r\n        /** Helper method that adds the child TreeViewItem to the children list and sets the parent property on the child.\r\n         * @param child TreeViewItem to be added to the children list.\r\n         */\r\n        AddChild(child: TreeViewItem): void\r\n        CompareTo(other: TreeViewItem): number\r\n        toString(): string\r\n        /** Unique ID for an item.\r\n         */\r\n        id: number\r\n        /** Name shown for this item when rendered.\r\n         */\r\n        displayName: string\r\n        /** The depth refers to how many ancestors this item has, and corresponds to the number of horizontal ‘indents’ this item has.\r\n         */\r\n        depth: number\r\n        /** Returns true if children has any items.\r\n         */\r\n        readonly hasChildren: boolean\r\n        /** The list of child items of this TreeViewItem.\r\n         */\r\n        children: any\r\n        /** The parent of this TreeViewItem. If it is null then it is considered the root of the TreeViewItem tree.\r\n         */\r\n        parent: TreeViewItem\r\n        /** If set, this icon will be rendered to the left of the displayName. The icon is rendered at 16x16 points by default.\r\n         */\r\n        icon: Texture2D\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Rect } from \"UnityEngine\";\r\n    /** The TreeView is an IMGUI control that lets you create tree views, list views and multi-column tables for Editor tools.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class TreeView extends Object {\r\n        Reload(): void\r\n        Repaint(): void\r\n        GetRows(): any\r\n        ExpandAll(): void\r\n        CollapseAll(): void\r\n        /** Expand or collapse all items under item with id.\r\n         * @param id TreeViewItem ID.\r\n         * @param expanded Expanded state: true expands, false collapses.\r\n         */\r\n        SetExpandedRecursive(id: number, expanded: boolean): void\r\n        /** Set a single TreeViewItem to be expanded or collapsed.\r\n         * @param id TreeViewItem ID.\r\n         * @param expanded True expands item. False collapses item.\r\n         * @returns True if item changed expanded state, false if item already had the expanded state. \r\n         */\r\n        SetExpanded(id: number, expanded: boolean): boolean\r\n        SetExpanded(ids: any): void\r\n        GetExpanded(): any\r\n        /** Returns true if the TreeViewItem with ID id is currently expanded.\r\n         * @param id TreeViewItem ID.\r\n         */\r\n        IsExpanded(id: number): boolean\r\n        GetSelection(): any\r\n        SetSelection(selectedIDs: any, options: TreeViewSelectionOptions): void\r\n        SetSelection(selectedIDs: any): void\r\n        /** Returns true if the TreeViewItem with ID id is currently selected.\r\n         * @param id TreeViewItem ID.\r\n         */\r\n        IsSelected(id: number): boolean\r\n        HasSelection(): boolean\r\n        HasFocus(): boolean\r\n        SetFocus(): void\r\n        SetFocusAndEnsureSelectedItem(): void\r\n        /** Shows the rename overlay for a TreeViewItem.\r\n         * @param item Item to rename.\r\n         * @param delay Delay in seconds until the rename overlay shows.\r\n         * @returns Returns true if renaming was started. Returns false if renaming was already active. \r\n         */\r\n        BeginRename(item: TreeViewItem, delay: number): boolean\r\n        /** Shows the rename overlay for a TreeViewItem.\r\n         * @param item Item to rename.\r\n         * @param delay Delay in seconds until the rename overlay shows.\r\n         * @returns Returns true if renaming was started. Returns false if renaming was already active. \r\n         */\r\n        BeginRename(item: TreeViewItem): boolean\r\n        EndRename(): void\r\n        /** This will reveal the item with ID id (by expanding the ancestors of that item) and will make sure it is visible in the ScrollView.\r\n         * @param id TreeViewItem ID.\r\n         */\r\n        FrameItem(id: number): void\r\n        /** This is the main GUI method of the TreeView, where the TreeViewItems are processed and drawn.\r\n         * @param rect Rect where the TreeView is rendered.\r\n         */\r\n        OnGUI(rect: Rect): void\r\n        SelectAllRows(): void\r\n        /** The state of the TreeView (expanded state, selection, scroll etc.)\r\n         */\r\n        readonly state: TreeViewState\r\n        /** Get the MultiColumnHeader of the TreeView. Can be null if the TreeView was created without a MultiColumnHeader.\r\n         */\r\n        multiColumnHeader: MultiColumnHeader\r\n        /** Returns the sum of the TreeView row heights, the MultiColumnHeader height (if used) and the border (if used).\r\n         */\r\n        readonly totalHeight: number\r\n        /** The controlID used by the TreeView to obtain keyboard control focus.\r\n         */\r\n        treeViewControlID: number\r\n        /** The current search state of the TreeView.\r\n         */\r\n        readonly hasSearch: boolean\r\n        /** Current search string of the TreeView.\r\n         */\r\n        searchString: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Rect } from \"UnityEngine\";\r\n    namespace TreeView {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        abstract class DefaultGUI extends Object {\r\n            static FoldoutLabel(rect: Rect, label: string, selected: boolean, focused: boolean): void\r\n            static Label(rect: Rect, label: string, selected: boolean, focused: boolean): void\r\n            static LabelRightAligned(rect: Rect, label: string, selected: boolean, focused: boolean): void\r\n            static BoldLabel(rect: Rect, label: string, selected: boolean, focused: boolean): void\r\n            static BoldLabelRightAligned(rect: Rect, label: string, selected: boolean, focused: boolean): void\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { GUIStyle } from \"UnityEngine\";\r\n    namespace TreeView {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        abstract class DefaultStyles extends Object {\r\n            static foldoutLabel: GUIStyle\r\n            static label: GUIStyle\r\n            static labelRightAligned: GUIStyle\r\n            static boldLabel: GUIStyle\r\n            static boldLabelRightAligned: GUIStyle\r\n            static backgroundEven: GUIStyle\r\n            static backgroundOdd: GUIStyle\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Enum used by the TreeView.SetSelection method.\r\n     */\r\n    enum TreeViewSelectionOptions {\r\n        /** If this flag is passed to TreeView.SetSelection no extra logic is be performed after setting selection.\r\n         */\r\n        None = 0,\r\n        /** If this flag is passed to TreeView.SetSelection then the TreeView will call the its TreeView.SelectionChanged method.\r\n         */\r\n        FireSelectionChanged = 1,\r\n        /** If this flag is passed to TreeView.SetSelection then the TreeView will make sure the last item in the input selection list is visible on screen.\r\n         */\r\n        RevealAndFrame = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Texture2D } from \"UnityEngine\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    /** Items that build the drop-down list.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AdvancedDropdownItem extends Object {\r\n        constructor(name: string)\r\n        /** Adds the given AdvancedDropdownItem child to the children list.\r\n         * @param child AdvancedDropdownItem to be added to the children list.\r\n         */\r\n        AddChild(child: AdvancedDropdownItem): void\r\n        CompareTo(o: Object): number\r\n        AddSeparator(): void\r\n        toString(): string\r\n        /** Name shown for this item when rendered.\r\n         */\r\n        name: string\r\n        /** If set, this icon will be rendered to the left of the item name.\r\n         */\r\n        icon: Texture2D\r\n        /** The unique identifier for an item.\r\n         */\r\n        id: number\r\n        /** True if the item is enabled.\r\n         */\r\n        enabled: boolean\r\n        /** The list of child items of this item.\r\n         */\r\n        readonly children: any\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** The state of the drop-down. This Object can be serialized.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class AdvancedDropdownState extends Object {\r\n        constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor.IMGUI.Controls\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    import { Rect } from \"UnityEngine\";\r\n    /** Inherit from this class to implement your own drop-down control.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class AdvancedDropdown extends Object {\r\n        /** Call this method to show the drop-down at the given position.\r\n         * @param rect Position of the button that triggered the drop-down.\r\n         */\r\n        Show(rect: Rect): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Exception } from \"System\";\r\n    /** An exception class that represents a failed build.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class BuildFailedException extends Exception {\r\n        constructor(message: string)\r\n        constructor(innerException: Exception)\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build\" {\r\n    import * as jsb from \"jsb\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface IOrderedCallback {\r\n        /** Returns the relative callback order for callbacks.  Callbacks with lower values are called before ones with higher values.\r\n         */\r\n        readonly callbackOrder: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build\" {\r\n    import * as jsb from \"jsb\";\r\n    import { BuildReport } from \"UnityEditor.Build.Reporting\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface IPreprocessBuildWithReport extends IOrderedCallback {\r\n        /** Implement this function to receive a callback before the build is started.\r\n         * @param report A report containing information about the build, such as its target platform and output path.\r\n         */\r\n        OnPreprocessBuild(report: BuildReport): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Array } from \"System\";\r\n    import { BuildOptions } from \"UnityEditor\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface IFilterBuildAssemblies extends IOrderedCallback {\r\n        /** Will be called after building script assemblies, but makes it possible to filter away unwanted scripts to be included.\r\n         * @param buildOptions The current build options.\r\n         * @param assemblies The list of assemblies that will be included.\r\n         * @returns Returns the filtered list of assemblies that are included in the build. \r\n         */\r\n        OnFilterAssemblies(buildOptions: BuildOptions, assemblies: Array<string>): Array<string>\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build\" {\r\n    import * as jsb from \"jsb\";\r\n    import { BuildReport } from \"UnityEditor.Build.Reporting\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface IPostprocessBuildWithReport extends IOrderedCallback {\r\n        /** Implement this function to receive a callback after the build is complete.\r\n         * @param report A BuildReport containing information about the build, such as the target platform and output path.\r\n         */\r\n        OnPostprocessBuild(report: BuildReport): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build\" {\r\n    import * as jsb from \"jsb\";\r\n    import { BuildReport } from \"UnityEditor.Build.Reporting\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface IPostBuildPlayerScriptDLLs extends IOrderedCallback {\r\n        /** Implement this interface to receive a callback just after the player scripts have been compiled.\r\n         * @param report A report containing information about the build, such as its target platform and output path.\r\n         */\r\n        OnPostBuildPlayerScriptDLLs(report: BuildReport): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    import { BuildReport } from \"UnityEditor.Build.Reporting\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface IProcessSceneWithReport extends IOrderedCallback {\r\n        /** Implement this function to receive a callback for each Scene during the build.\r\n         * @param scene The current Scene being processed.\r\n         * @param report A report containing information about the current build. When this callback is invoked for Scene loading during Editor playmode, this parameter will be null.\r\n         */\r\n        OnProcessScene(scene: any, report: BuildReport): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build\" {\r\n    import * as jsb from \"jsb\";\r\n    import { BuildTarget } from \"UnityEditor\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface IActiveBuildTargetChanged extends IOrderedCallback {\r\n        /** This function is called automatically when the active build platform has changed.\r\n         * @param previousTarget The build target before the change.\r\n         * @param newTarget The new active build target.\r\n         */\r\n        OnActiveBuildTargetChanged(previousTarget: BuildTarget, newTarget: BuildTarget): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    import { ValueType } from \"System\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface IPreprocessShaders extends IOrderedCallback {\r\n        OnProcessShader(shader: any, snippet: any, data: any): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    import { ValueType } from \"System\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface IPreprocessComputeShaders extends IOrderedCallback {\r\n        OnProcessComputeShader(shader: any, kernelName: string, data: any): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build\" {\r\n    import * as jsb from \"jsb\";\r\n    import { BuildReport } from \"UnityEditor.Build.Reporting\";\r\n    import { Object } from \"System\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface IUnityLinkerProcessor extends IOrderedCallback {\r\n        /** Generates additional link.xml files for preserving additional types and their members.\r\n         * @param report The current built report.\r\n         * @param data Information about the current run of UnityLinker.\r\n         * @returns The file path to the generated link.xml file. If the path is relative, GenerateAdditionalLinkXmlFile combines it with the working directory to make an absolute path. \r\n         */\r\n        GenerateAdditionalLinkXmlFile(report: BuildReport, data: any): string\r\n        /** Performs arbitrary logic before UnityLinker runs.\r\n         * @param report The current build report.\r\n         * @param data Information about the current run of UnityLinker.\r\n         */\r\n        OnBeforeRun(report: BuildReport, data: any): void\r\n        /** Performs arbitrary logic after UnityLinker has run.\r\n         * @param report The current build report.\r\n         * @param data Information about the current run of UnityLinker.\r\n         */\r\n        OnAfterRun(report: BuildReport, data: any): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build\" {\r\n    import * as jsb from \"jsb\";\r\n    import { BuildReport } from \"UnityEditor.Build.Reporting\";\r\n    import { Object } from \"System\";\r\n    // @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    interface IIl2CppProcessor extends IOrderedCallback {\r\n        /** Performs arbitrary logic before IL2CPP runs, which converts managed assemblies to C++ code.\r\n         * @param report The current build report.\r\n         * @param data Information about the current run of IL2CPP.\r\n         */\r\n        OnBeforeConvertRun(report: BuildReport, data: any): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build.Reporting\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** Contains information about a single file produced by the build process.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class BuildFile extends ValueType {\r\n        constructor()\r\n        toString(): string\r\n        /** The unique indentifier of the build file.\r\n         */\r\n        readonly id: number\r\n        /** The absolute path of the file produced by the build process.\r\n         */\r\n        readonly path: string\r\n        /** The role the file plays in the build output.\r\n         */\r\n        readonly role: string\r\n        /** The total size of the file, in bytes.\r\n         */\r\n        readonly size: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build.Reporting\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Describes the outcome of the build process.\r\n     */\r\n    enum BuildResult {\r\n        /** Indicates that the outcome of the build is in an unknown state.\r\n         */\r\n        Unknown = 0,\r\n        /** Indicates that the build completed successfully.\r\n         */\r\n        Succeeded = 1,\r\n        /** Indicates that the build failed.\r\n         */\r\n        Failed = 2,\r\n        /** Indicates that the build was cancelled by the user.\r\n         */\r\n        Cancelled = 3,\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build.Reporting\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array } from \"System\";\r\n    /** Contains information about a single step in the build process.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class BuildStep extends ValueType {\r\n        constructor()\r\n        toString(): string\r\n        /** The name of this build step.\r\n         */\r\n        readonly name: string\r\n        /** The total duration for this build step.\r\n         */\r\n        readonly duration: any\r\n        /** All log messages recorded during this build step, in the order of which they occurred.\r\n         */\r\n        readonly messages: Array<BuildStepMessage>\r\n        /** The nesting depth of the build step.\r\n         */\r\n        readonly depth: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build.Reporting\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Enum } from \"System\";\r\n    /** Contains information about a single log message recorded during the build process.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class BuildStepMessage extends ValueType {\r\n        constructor()\r\n        /** The LogType of the log message.\r\n         */\r\n        readonly type: any\r\n        /** The text content of the log message.\r\n         */\r\n        readonly content: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build.Reporting\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, DateTime } from \"System\";\r\n    import { GUID, BuildTarget, BuildTargetGroup, BuildOptions } from \"UnityEditor\";\r\n    /** Contains overall summary information about a build.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class BuildSummary extends ValueType {\r\n        constructor()\r\n        /** The time the build was started.\r\n         */\r\n        readonly buildStartedAt: DateTime\r\n        /** The Application.buildGUID of the build.\r\n         */\r\n        readonly guid: GUID\r\n        /** The platform that the build was created for.\r\n         */\r\n        readonly platform: BuildTarget\r\n        /** The platform group the build was created for.\r\n         */\r\n        readonly platformGroup: BuildTargetGroup\r\n        /** The BuildOptions used for the build, as passed to BuildPipeline.BuildPlayer.\r\n         */\r\n        readonly options: BuildOptions\r\n        /** The output path for the build, as provided to BuildPipeline.BuildPlayer.\r\n         */\r\n        readonly outputPath: string\r\n        /** The total size of the build output, in bytes.\r\n         */\r\n        readonly totalSize: number\r\n        /** The total time taken by the build process.\r\n         */\r\n        readonly totalTime: any\r\n        /** The time the build ended.\r\n         */\r\n        readonly buildEndedAt: DateTime\r\n        /** The total number of errors and exceptions recorded during the build process.\r\n         */\r\n        readonly totalErrors: number\r\n        /** The total number of warnings recorded during the build process.\r\n         */\r\n        readonly totalWarnings: number\r\n        /** The outcome of the build.\r\n         */\r\n        readonly result: BuildResult\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build.Reporting\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** This class provides constant values for some of the common roles used by files in the build. The role of each file in the build is available in BuildFile.role.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class CommonRoles extends Object {\r\n        /** The BuildFile.role value of a file that contains the packed content of a Scene.\r\n         */\r\n        static readonly scene: string\r\n        /** The BuildFile.role value of a file that contains asset objects which are shared between Scenes. Examples of asset objects are textures, models, and audio.\r\n         */\r\n        static readonly sharedAssets: string\r\n        /** The BuildFile.role value of the file that contains the contents of the project's \"Resources\" folder, packed into a single file.\r\n         */\r\n        static readonly resourcesFile: string\r\n        /** The BuildFile.role value of built AssetBundle files.\r\n         */\r\n        static readonly assetBundle: string\r\n        /** The BuildFile.role value of a manifest AssetBundle, which is an AssetBundle that contains information about other AssetBundles and their dependencies.\r\n         */\r\n        static readonly manifestAssetBundle: string\r\n        /** The BuildFile.role value of an AssetBundle manifest file, produced during the build process, that contains information about the bundle and its dependencies.\r\n         */\r\n        static readonly assetBundleTextManifest: string\r\n        /** The BuildFile.role value of a managed assembly, containing compiled script code.\r\n         */\r\n        static readonly managedLibrary: string\r\n        /** The BuildFile.role value of a managed library that is present in the build due to being a dependency of a CommonRoles.managedLibrary.\r\n         */\r\n        static readonly dependentManagedLibrary: string\r\n        /** The BuildFile.role value of an executable - the file that will actually be launched on the target device.\r\n         */\r\n        static readonly executable: string\r\n        /** The BuildFile.role value of a file that contains streaming resource data.\r\n         */\r\n        static readonly streamingResourceFile: string\r\n        /** The BuildFile.role value of files that have been copied into the build without modification from the StreamingAssets folder in the project.\r\n         */\r\n        static readonly streamingAsset: string\r\n        /** The BuildFile.role value of the file that contains configuration information for the very early stages of engine startup.\r\n         */\r\n        static readonly bootConfig: string\r\n        /** The BuildFile.role value of the file that contains built-in resources for the engine.\r\n         */\r\n        static readonly builtInResources: string\r\n        /** The BuildFile.role value of the file that contains Unity's built-in shaders, such as the Standard shader.\r\n         */\r\n        static readonly builtInShaders: string\r\n        /** The BuildFile.role value of the file that provides config information used in Low Integrity mode on Windows.\r\n         */\r\n        static readonly appInfo: string\r\n        /** The BuildFile.role value of files that provide the managed API for Unity.\r\n         */\r\n        static readonly managedEngineApi: string\r\n        /** The BuildFile.role value of files that make up the Mono runtime itself.\r\n         */\r\n        static readonly monoRuntime: string\r\n        /** The BuildFile.role value of files that are used as configuration data by the Mono runtime.\r\n         */\r\n        static readonly monoConfig: string\r\n        /** The BuildFile.role value of files that contain information for debuggers.\r\n         */\r\n        static readonly debugInfo: string\r\n        /** The BuildFile.role value of the file that contains global Project Settings data for the player.\r\n         */\r\n        static readonly globalGameManagers: string\r\n        /** The BuildFile.role value of the executable that is used to capture crashes from the player.\r\n         */\r\n        static readonly crashHandler: string\r\n        /** The BuildFile.role value of the main Unity runtime when it is built as a separate library.\r\n         */\r\n        static readonly engineLibrary: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build.Reporting\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Object } from \"System\";\r\n    import { GUID } from \"UnityEditor\";\r\n    /** Contains information about a single packed Asset.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class PackedAssetInfo extends ValueType {\r\n        constructor()\r\n        /** The unique identifier of the packed Asset.\r\n         */\r\n        readonly id: number\r\n        /** The type of source Asset that the build process used to generate the package Asset, such as image, Mesh or audio types.\r\n         */\r\n        readonly type: any\r\n        /** The size of the packed Asset.\r\n         */\r\n        readonly packedSize: number\r\n        /** The offset in a PackedAssets file that indicates the beginning of the packed Asset.\r\n         */\r\n        readonly offset: number\r\n        /** The Global Unique Identifier (GUID) of the source Asset that the build process used to generate the packed Asset.\r\n         */\r\n        readonly sourceAssetGUID: GUID\r\n        /** The file path to the source Asset that the build process used to generate the package Asset, relative to the Project directory.\r\n         */\r\n        readonly sourceAssetPath: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build.Reporting\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    import { Array } from \"System\";\r\n    /** An extension to the BuildReport class that tracks how Assets contribute to the size of the build.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class PackedAssets extends Object {\r\n        constructor()\r\n        /** The identifier of the BuildFile that holds the contents of the packed Asset file.\r\n         */\r\n        readonly file: number\r\n        /** The file path to the Asset package, relative to the Data folder of the build.\r\n         */\r\n        readonly shortPath: string\r\n        /** The header size of the packed Asset file.\r\n         */\r\n        readonly overhead: number\r\n        /** An array of PackedAssetInfo objects that holds information about the Assets that are included in the PackedAssets bundle, such as packed Asset size and type.\r\n         */\r\n        readonly contents: Array<PackedAssetInfo>\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build.Reporting\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Array } from \"System\";\r\n    /** Contains information about which scenes in a build have references to an Asset in the build.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ScenesUsingAsset extends ValueType {\r\n        constructor()\r\n        /** The asset path.\r\n         */\r\n        readonly assetPath: string\r\n        /** The list of scenes in the build referring to the asset, identified by a string containing the scene index in the BuildPlayerOptions.scenes list, as well as the scene path.\r\n         */\r\n        readonly scenePaths: Array<string>\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build.Reporting\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"UnityEngine\";\r\n    import { Array } from \"System\";\r\n    /** An extension to the BuildReport class that tracks which scenes in the build have references to a specific asset in the build.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class ScenesUsingAssets extends Object {\r\n        constructor()\r\n        /** An array of ScenesUsingAsset that holds information about the Assets that are included in the build.\r\n         */\r\n        readonly list: Array<ScenesUsingAsset>\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Build.Reporting\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ScriptableObject } from \"UnityEngine\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    /** The StrippingInfo object contains information about which native code modules in the engine are still present in the build, and the reasons why they are still present.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class StrippingInfo extends ScriptableObject {\r\n        constructor()\r\n        /** Returns the list of dependencies or reasons that caused the given entity to be included in the build.\r\n         * @param entityName The name of an engine module, class, or other entity present in the build.\r\n         * @returns A list of modules, classes, or other entities that caused the provided entity to be included in the build. \r\n         */\r\n        GetReasonsForIncluding(entityName: string): IEnumerable<string>\r\n        /** The native engine modules that were included in the build.\r\n         */\r\n        readonly includedModules: IEnumerable<string>\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Hardware\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class UsbDevice extends ValueType {\r\n        constructor()\r\n        toString(): string\r\n        readonly vendorId: number\r\n        readonly productId: number\r\n        readonly revision: number\r\n        readonly udid: string\r\n        readonly name: string\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Hardware\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class Usb extends Object {\r\n        constructor()\r\n        static OnDevicesChanged(devices: Array<UsbDevice>): void\r\n        static DevicesChanged(op: \"add\" | \"remove\", fn: (devices: Array<UsbDevice>) => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Hardware\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum DevDeviceState {\r\n        Disconnected = 0,\r\n        Connected = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Hardware\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    enum DevDeviceFeatures {\r\n        None = 0,\r\n        PlayerConnection = 1,\r\n        RemoteConnection = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Hardware\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class DevDevice extends ValueType {\r\n        constructor(id: string, name: string, type: string, module_: string, state: DevDeviceState, features: DevDeviceFeatures)\r\n        toString(): string\r\n        readonly isConnected: boolean\r\n        static readonly none: DevDevice\r\n        readonly id: string\r\n        readonly name: string\r\n        readonly type: string\r\n        readonly module_: string\r\n        readonly state: DevDeviceState\r\n        readonly features: DevDeviceFeatures\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Hardware\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class DevDeviceList extends Object {\r\n        constructor()\r\n        static OnChanged(): void\r\n        static FindDevice(deviceId: string, device: jsb.Out<DevDevice>): boolean\r\n        static GetDevices(): Array<DevDevice>\r\n        static Changed(op: \"add\" | \"remove\", fn: () => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SceneManagement\" {\r\n    import * as jsb from \"jsb\";\r\n    import { SceneManager } from \"UnityEngine.SceneManagement\";\r\n    import { SceneAsset } from \"UnityEditor\";\r\n    import { ValueType, Array } from \"System\";\r\n    import { Object, YieldInstruction } from \"UnityEngine\";\r\n    /** Scene management in the Editor.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class EditorSceneManager extends SceneManager {\r\n        constructor()\r\n        static IsReloading(scene: any): boolean\r\n        /** Open a Scene in the Editor.\r\n         * @param scenePath The path of the Scene. This should be relative to the Project folder; for example, \"AssetsMyScenesMyScene.unity\".\r\n         * @param mode Allows you to select how to open the specified Scene, and whether to keep existing Scenes in the Hierarchy. See SceneManagement.OpenSceneMode for more information about the options.\r\n         * @returns A reference to the opened Scene. \r\n         */\r\n        static OpenScene(scenePath: string, mode: OpenSceneMode): any\r\n        static OpenScene(scenePath: string): any\r\n        /** Create a new Scene.\r\n         * @param setup Whether the new Scene should use the default set of GameObjects.\r\n         * @param mode Whether to keep existing Scenes open.\r\n         * @returns A reference to the new Scene. \r\n         */\r\n        static NewScene(setup: NewSceneSetup, mode: NewSceneMode): any\r\n        static NewScene(setup: NewSceneSetup): any\r\n        static NewPreviewScene(): any\r\n        /** Close the Scene. If removeScene flag is true, the closed Scene will also be removed from EditorSceneManager.\r\n         * @param scene The Scene to be closed/removed.\r\n         * @param removeScene Bool flag to indicate if the Scene should be removed after closing.\r\n         * @returns Returns true if the Scene is closed/removed. \r\n         */\r\n        static CloseScene(scene: any, removeScene: boolean): boolean\r\n        /** Closes a preview Scene created by NewPreviewScene.\r\n         * @param scene The preview Scene to close.\r\n         * @returns True if the Scene was successfully closed. \r\n         */\r\n        static ClosePreviewScene(scene: any): boolean\r\n        /** Is the Scene a preview Scene?\r\n         * @param scene The Scene to check.\r\n         * @returns True if the Scene is a preview Scene. \r\n         */\r\n        static IsPreviewScene(scene: any): boolean\r\n        /** Is this object part of a preview Scene?\r\n         * @param obj The object to check.\r\n         * @returns True if this object is part of a preview Scene. \r\n         */\r\n        static IsPreviewSceneObject(obj: Object): boolean\r\n        /** Allows you to reorder the Scenes currently open in the Hierarchy window. Moves the source Scene so it comes before the destination Scene.\r\n         * @param src The Scene to move.\r\n         * @param dst The Scene which should come directly after the source Scene in the hierarchy.\r\n         */\r\n        static MoveSceneBefore(src: any, dst: any): void\r\n        /** Allows you to reorder the Scenes currently open in the Hierarchy window. Moves the source Scene so it comes after the destination Scene.\r\n         * @param src The Scene to move.\r\n         * @param dst The Scene which should come directly before the source Scene in the hierarchy.\r\n         */\r\n        static MoveSceneAfter(src: any, dst: any): void\r\n        static SaveOpenScenes(): boolean\r\n        /** Save a list of Scenes.\r\n         * @param scenes List of Scenes that should be saved.\r\n         * @returns True if the save succeeded. Otherwise false. \r\n         */\r\n        static SaveScenes(scenes: Array<any>): boolean\r\n        static SaveCurrentModifiedScenesIfUserWantsTo(): boolean\r\n        /** Asks whether the modfied input Scenes should be saved.\r\n         * @param scenes Scenes that should be saved if they are modified.\r\n         * @returns Your choice of whether to save or not save the Scenes. \r\n         */\r\n        static SaveModifiedScenesIfUserWantsTo(scenes: Array<any>): boolean\r\n        /** Shows a save dialog if an Untitled Scene exists in the current Scene manager setup.\r\n         * @param dialogContent Text shown in the save dialog.\r\n         * @returns True if the Scene is saved or if there is no Untitled Scene. \r\n         */\r\n        static EnsureUntitledSceneHasBeenSaved(dialogContent: string): boolean\r\n        /** Mark the specified Scene as modified.\r\n         * @param scene The Scene to be marked as modified.\r\n         * @returns Whether the Scene was successfully marked as dirty. \r\n         */\r\n        static MarkSceneDirty(scene: any): boolean\r\n        static MarkAllScenesDirty(): void\r\n        static GetSceneManagerSetup(): Array<SceneSetup>\r\n        /** Restore the setup of the SceneManager.\r\n         * @param value In this array, at least one Scene should be loaded, and there must be one active Scene.\r\n         */\r\n        static RestoreSceneManagerSetup(value: Array<SceneSetup>): void\r\n        /** Detects cross-Scene references in a Scene.\r\n         * @param scene Scene to check for cross-Scene references.\r\n         * @returns Was any cross-Scene references found. \r\n         */\r\n        static DetectCrossSceneReferences(scene: any): boolean\r\n        /** Return the culling mask set on the given Scene.\r\n         * @param scene The scene to get the culling mask from.\r\n         * @returns The scene's current culling mask as a bitfield. \r\n         */\r\n        static GetSceneCullingMask(scene: any): number\r\n        /** Set the culling mask on this scene to this value.\nCameras will only render objects in Scenes that have the same bits set in their culling mask.\r\n         * @param scene The scene to set the culling mask on.\r\n         * @param sceneCullingMask The value of the culling mask, stored as a bitfield.\r\n         */\r\n        static SetSceneCullingMask(scene: any, sceneCullingMask: number): void\r\n        static CalculateAvailableSceneCullingMask(): number\r\n        /** Save a Scene.\r\n         * @param scene The Scene to be saved.\r\n         * @param dstScenePath The file path to save the Scene to. If the path is empty, the current open Scene is overwritten. If it has not yet been saved at all, a save dialog is shown.\r\n         * @param saveAsCopy If set to true, the Scene is saved without changing the current Scene, and without clearing the unsaved changes marker.\r\n         * @returns True if the save succeeded, otherwise false. \r\n         */\r\n        static SaveScene(scene: any, dstScenePath: string, saveAsCopy: boolean): boolean\r\n        static SaveScene(scene: any, dstScenePath: string): boolean\r\n        static SaveScene(scene: any): boolean\r\n        /** This method allows you to load a Scene during playmode in the editor, without requiring the Scene to be included in the Scene list.\r\n         * @param path Path to Scene to load.\r\n         * @param parameters Parameters used to load the Scene SceneManagement.LoadSceneParameters.\r\n         * @returns Scene that is loading. \r\n         */\r\n        static LoadSceneInPlayMode(path: string, parameters: any): any\r\n        /** This method allows you to load a Scene during playmode in the editor, without requiring the Scene to be included in the Scene list.\r\n         * @param path Path to Scene to load.\r\n         * @param parameters Parameters to apply to loading. See SceneManagement.LoadSceneParameters.\r\n         * @returns Use the AsyncOperation to determine if the operation has completed. \r\n         */\r\n        static LoadSceneAsyncInPlayMode(path: string, parameters: any): any\r\n        /** The number of loaded Scenes.\r\n         */\r\n        static readonly loadedSceneCount: number\r\n        static readonly loadedRootSceneCount: number\r\n        /** The current amount of active preview Scenes.\r\n         */\r\n        static readonly previewSceneCount: number\r\n        /** Controls whether cross-Scene references are allowed in the Editor.\r\n         */\r\n        static preventCrossSceneReferences: boolean\r\n        /** Loads this SceneAsset when you start Play Mode.\r\n         */\r\n        static playModeStartScene: SceneAsset\r\n        /** Use SceneCullingMasks.DefaultSceneCullingMask instead.\r\n         */\r\n        static readonly DefaultSceneCullingMask: number\r\n        static activeSceneChangedInEditMode(op: \"add\" | \"remove\", fn: (arg0: any, arg1: any) => void): void\r\n        static newSceneCreated(op: \"add\" | \"remove\", fn: (scene: any, setup: NewSceneSetup, mode: NewSceneMode) => void): void\r\n        static sceneOpening(op: \"add\" | \"remove\", fn: (path: string, mode: OpenSceneMode) => void): void\r\n        static sceneOpened(op: \"add\" | \"remove\", fn: (scene: any, mode: OpenSceneMode) => void): void\r\n        static sceneClosing(op: \"add\" | \"remove\", fn: (scene: any, removingScene: boolean) => void): void\r\n        static sceneClosed(op: \"add\" | \"remove\", fn: (scene: any) => void): void\r\n        static sceneSaving(op: \"add\" | \"remove\", fn: (scene: any, path: string) => void): void\r\n        static sceneSaved(op: \"add\" | \"remove\", fn: (scene: any) => void): void\r\n        static sceneDirtied(op: \"add\" | \"remove\", fn: (scene: any) => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.SceneManagement\" {\r\n    import { Object, ValueType, Enum } from \"System\";\r\n    import { GameObject, YieldInstruction } from \"UnityEngine\";\r\n    /** Scene management at run-time.\r\n     */\r\n    class SceneManager extends Object {\r\n        constructor()\r\n        static GetActiveScene(): any\r\n        /** Set the Scene to be active.\r\n         * @param scene The Scene to be set.\r\n         * @returns Returns false if the Scene is not loaded yet. \r\n         */\r\n        static SetActiveScene(scene: any): boolean\r\n        /** Searches all Scenes loaded for a Scene that has the given asset path.\r\n         * @param scenePath Path of the Scene. Should be relative to the project folder. Like: \"AssetsMyScenesMyScene.unity\".\r\n         * @returns A reference to the Scene, if valid. If not, an invalid Scene is returned. \r\n         */\r\n        static GetSceneByPath(scenePath: string): any\r\n        /** Searches through the Scenes loaded for a Scene with the given name.\r\n         * @param name Name of Scene to find.\r\n         * @returns A reference to the Scene, if valid. If not, an invalid Scene is returned. \r\n         */\r\n        static GetSceneByName(name: string): any\r\n        /** Get a Scene struct from a build index.\r\n         * @param buildIndex Build index as shown in the Build Settings window.\r\n         * @returns A reference to the Scene, if valid. If not, an invalid Scene is returned. \r\n         */\r\n        static GetSceneByBuildIndex(buildIndex: number): any\r\n        /** Get the Scene at index in the SceneManager's list of loaded Scenes.\r\n         * @param index Index of the Scene to get. Index must be greater than or equal to 0 and less than SceneManager.sceneCount.\r\n         * @returns A reference to the Scene at the index specified. \r\n         */\r\n        static GetSceneAt(index: number): any\r\n        /** Create an empty new Scene at runtime with the given name.\r\n         * @param sceneName The name of the new Scene. It cannot be empty or null, or same as the name of the existing Scenes.\r\n         * @param parameters Various parameters used to create the Scene.\r\n         * @returns A reference to the new Scene that was created, or an invalid Scene if creation failed. \r\n         */\r\n        static CreateScene(sceneName: string, parameters: any): any\r\n        /** Create an empty new Scene at runtime with the given name.\r\n         * @param sceneName The name of the new Scene. It cannot be empty or null, or same as the name of the existing Scenes.\r\n         * @param parameters Various parameters used to create the Scene.\r\n         * @returns A reference to the new Scene that was created, or an invalid Scene if creation failed. \r\n         */\r\n        static CreateScene(sceneName: string): any\r\n        /** This will merge the source Scene into the destinationScene.\r\n         * @param sourceScene The Scene that will be merged into the destination Scene.\r\n         * @param destinationScene Existing Scene to merge the source Scene into.\r\n         */\r\n        static MergeScenes(sourceScene: any, destinationScene: any): void\r\n        /** Move a GameObject from its current Scene to a new Scene.\r\n         * @param go GameObject to move.\r\n         * @param scene Scene to move into.\r\n         */\r\n        static MoveGameObjectToScene(go: GameObject, scene: any): void\r\n        /** Loads the Scene by its name or index in Build Settings.\r\n         * @param sceneName Name or path of the Scene to load.\r\n         * @param sceneBuildIndex Index of the Scene in the Build Settings to load.\r\n         * @param mode Allows you to specify whether or not to load the Scene additively. See SceneManagement.LoadSceneMode for more information about the options.\r\n         */\r\n        static LoadScene(sceneName: string, mode: any): void\r\n        /** Loads the Scene by its name or index in Build Settings.\r\n         * @param sceneName Name or path of the Scene to load.\r\n         * @param sceneBuildIndex Index of the Scene in the Build Settings to load.\r\n         * @param parameters Various parameters used to load the Scene.\r\n         * @returns A handle to the Scene being loaded. \r\n         */\r\n        static LoadScene(sceneName: string, parameters: any): any\r\n        /** Loads the Scene by its name or index in Build Settings.\r\n         * @param sceneName Name or path of the Scene to load.\r\n         * @param sceneBuildIndex Index of the Scene in the Build Settings to load.\r\n         * @param mode Allows you to specify whether or not to load the Scene additively. See SceneManagement.LoadSceneMode for more information about the options.\r\n         */\r\n        static LoadScene(sceneBuildIndex: number, mode: any): void\r\n        /** Loads the Scene by its name or index in Build Settings.\r\n         * @param sceneName Name or path of the Scene to load.\r\n         * @param sceneBuildIndex Index of the Scene in the Build Settings to load.\r\n         * @param parameters Various parameters used to load the Scene.\r\n         * @returns A handle to the Scene being loaded. \r\n         */\r\n        static LoadScene(sceneBuildIndex: number, parameters: any): any\r\n        static LoadScene(sceneName: string): void\r\n        static LoadScene(sceneBuildIndex: number): void\r\n        /** Loads the Scene asynchronously in the background.\r\n         * @param sceneName Name or path of the Scene to load.\r\n         * @param sceneBuildIndex Index of the Scene in the Build Settings to load.\r\n         * @param mode If LoadSceneMode.Single then all current Scenes will be unloaded before loading.\r\n         * @param parameters Struct that collects the various parameters into a single place except for the name and index.\r\n         * @returns Use the AsyncOperation to determine if the operation has completed. \r\n         */\r\n        static LoadSceneAsync(sceneBuildIndex: number, mode: any): any\r\n        /** Loads the Scene asynchronously in the background.\r\n         * @param sceneName Name or path of the Scene to load.\r\n         * @param sceneBuildIndex Index of the Scene in the Build Settings to load.\r\n         * @param mode If LoadSceneMode.Single then all current Scenes will be unloaded before loading.\r\n         * @param parameters Struct that collects the various parameters into a single place except for the name and index.\r\n         * @returns Use the AsyncOperation to determine if the operation has completed. \r\n         */\r\n        static LoadSceneAsync(sceneBuildIndex: number, parameters: any): any\r\n        /** Loads the Scene asynchronously in the background.\r\n         * @param sceneName Name or path of the Scene to load.\r\n         * @param sceneBuildIndex Index of the Scene in the Build Settings to load.\r\n         * @param mode If LoadSceneMode.Single then all current Scenes will be unloaded before loading.\r\n         * @param parameters Struct that collects the various parameters into a single place except for the name and index.\r\n         * @returns Use the AsyncOperation to determine if the operation has completed. \r\n         */\r\n        static LoadSceneAsync(sceneName: string, mode: any): any\r\n        /** Loads the Scene asynchronously in the background.\r\n         * @param sceneName Name or path of the Scene to load.\r\n         * @param sceneBuildIndex Index of the Scene in the Build Settings to load.\r\n         * @param mode If LoadSceneMode.Single then all current Scenes will be unloaded before loading.\r\n         * @param parameters Struct that collects the various parameters into a single place except for the name and index.\r\n         * @returns Use the AsyncOperation to determine if the operation has completed. \r\n         */\r\n        static LoadSceneAsync(sceneName: string, parameters: any): any\r\n        static LoadSceneAsync(sceneBuildIndex: number): any\r\n        static LoadSceneAsync(sceneName: string): any\r\n        /** Destroys all GameObjects associated with the given Scene and removes the Scene from the SceneManager.\r\n         * @param sceneBuildIndex Index of the Scene in BuildSettings.\r\n         * @param sceneName Name or path of the Scene to unload.\r\n         * @param scene Scene to unload.\r\n         * @param options Scene unloading options.\r\n         * @returns Use the AsyncOperation to determine if the operation has completed. \r\n         */\r\n        static UnloadSceneAsync(sceneBuildIndex: number, options: any): any\r\n        /** Destroys all GameObjects associated with the given Scene and removes the Scene from the SceneManager.\r\n         * @param sceneBuildIndex Index of the Scene in BuildSettings.\r\n         * @param sceneName Name or path of the Scene to unload.\r\n         * @param scene Scene to unload.\r\n         * @param options Scene unloading options.\r\n         * @returns Use the AsyncOperation to determine if the operation has completed. \r\n         */\r\n        static UnloadSceneAsync(sceneName: string, options: any): any\r\n        /** Destroys all GameObjects associated with the given Scene and removes the Scene from the SceneManager.\r\n         * @param sceneBuildIndex Index of the Scene in BuildSettings.\r\n         * @param sceneName Name or path of the Scene to unload.\r\n         * @param scene Scene to unload.\r\n         * @param options Scene unloading options.\r\n         * @returns Use the AsyncOperation to determine if the operation has completed. \r\n         */\r\n        static UnloadSceneAsync(scene: any, options: any): any\r\n        /** Destroys all GameObjects associated with the given Scene and removes the Scene from the SceneManager.\r\n         * @param sceneBuildIndex Index of the Scene in BuildSettings.\r\n         * @param sceneName Name or path of the Scene to unload.\r\n         * @param scene Scene to unload.\r\n         * @param options Scene unloading options.\r\n         * @returns Use the AsyncOperation to determine if the operation has completed. \r\n         */\r\n        static UnloadSceneAsync(sceneBuildIndex: number): any\r\n        /** Destroys all GameObjects associated with the given Scene and removes the Scene from the SceneManager.\r\n         * @param sceneBuildIndex Index of the Scene in BuildSettings.\r\n         * @param sceneName Name or path of the Scene to unload.\r\n         * @param scene Scene to unload.\r\n         * @param options Scene unloading options.\r\n         * @returns Use the AsyncOperation to determine if the operation has completed. \r\n         */\r\n        static UnloadSceneAsync(sceneName: string): any\r\n        /** Destroys all GameObjects associated with the given Scene and removes the Scene from the SceneManager.\r\n         * @param sceneBuildIndex Index of the Scene in BuildSettings.\r\n         * @param sceneName Name or path of the Scene to unload.\r\n         * @param scene Scene to unload.\r\n         * @param options Scene unloading options.\r\n         * @returns Use the AsyncOperation to determine if the operation has completed. \r\n         */\r\n        static UnloadSceneAsync(scene: any): any\r\n        /** The total number of currently loaded Scenes.\r\n         */\r\n        static readonly sceneCount: number\r\n        /** Number of Scenes in Build Settings.\r\n         */\r\n        static readonly sceneCountInBuildSettings: number\r\n        static sceneLoaded(op: \"add\" | \"remove\", fn: (arg0: any, arg1: any) => void): void\r\n        static sceneUnloaded(op: \"add\" | \"remove\", fn: (arg0: any) => void): void\r\n        static activeSceneChanged(op: \"add\" | \"remove\", fn: (arg0: any, arg1: any) => void): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SceneManagement\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Masks that control what kind of Scene views and Game views Unity should render a GameObject in.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class SceneCullingMasks extends Object {\r\n        /** Specifies the default culling mask for a Scene.  Use the bits from this Scene culling mask for objects that you want to render in both in the Game view and the Scene view.\r\n         */\r\n        static readonly DefaultSceneCullingMask: number\r\n        /** The bits from this mask specify GameObjects that Unity should render in Game view.\r\n         */\r\n        static readonly GameViewObjects: number\r\n        /** The bits from this mask specify GameObjects that Unity should render in Scene views showing the main stage.\r\n         */\r\n        static readonly MainStageSceneViewObjects: number\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SceneManagement\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Used when opening a Scene in the Editor to specify how a Scene should be opened.\r\n     */\r\n    enum OpenSceneMode {\r\n        /** Closes all current open Scenes and loads a Scene.\r\n         */\r\n        Single = 0,\r\n        /** Adds a Scene to the current open Scenes and loads it.\r\n         */\r\n        Additive = 1,\r\n        /** Adds a Scene to the current open Scenes without loading it. It will show up as 'unloaded' in the Hierarchy Window.\r\n         */\r\n        AdditiveWithoutLoading = 2,\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SceneManagement\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Used when creating a new Scene in the Editor.\r\n     */\r\n    enum NewSceneMode {\r\n        /** All current open Scenes are closed and the newly created Scene are opened.\r\n         */\r\n        Single = 0,\r\n        /** The newly created Scene is added to the current open Scenes.\r\n         */\r\n        Additive = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SceneManagement\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Enum } from \"System\";\r\n    /** Used when creating a new Scene in the Editor.\r\n     */\r\n    enum NewSceneSetup {\r\n        /** No game objects are added to the new Scene.\r\n         */\r\n        EmptyScene = 0,\r\n        /** Adds default game objects to the new Scene (a light and camera).\r\n         */\r\n        DefaultGameObjects = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SceneManagement\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, ValueType, Array } from \"System\";\r\n    import { GenericMenu } from \"UnityEditor\";\r\n    import { GameObject, Transform } from \"UnityEngine\";\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class SceneHierarchyHooks extends Object {\r\n        static ReloadAllSceneHierarchies(): void\r\n        static CanSetNewParent(transform: Transform, newParent: Transform): boolean\r\n        static CanMoveTransformToScene(transform: Transform, scene: any): boolean\r\n        static addItemsToGameObjectContextMenu(op: \"add\" | \"remove\", fn: (arg1: GenericMenu, arg2: GameObject) => void): void\r\n        static addItemsToSceneHeaderContextMenu(op: \"add\" | \"remove\", fn: (arg1: GenericMenu, arg2: any) => void): void\r\n        static addItemsToSubSceneHeaderContextMenu(op: \"add\" | \"remove\", fn: (arg1: GenericMenu, arg2: SceneHierarchyHooks.SubSceneInfo) => void): void\r\n        static addItemsToCreateMenu(op: \"add\" | \"remove\", fn: (obj: GenericMenu) => void): void\r\n        static provideSubScenes(op: \"get\"): () => Array<SceneHierarchyHooks.SubSceneInfo>\r\n        static provideSubScenes(op: \"add\" | \"remove\" | \"set\", fn?: () => Array<SceneHierarchyHooks.SubSceneInfo>): void\r\n        static provideSubScenes(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: () => Array<SceneHierarchyHooks.SubSceneInfo>): () => Array<SceneHierarchyHooks.SubSceneInfo> | void\r\n        static provideSubSceneName(op: \"get\"): (arg: SceneHierarchyHooks.SubSceneInfo) => string\r\n        static provideSubSceneName(op: \"add\" | \"remove\" | \"set\", fn?: (arg: SceneHierarchyHooks.SubSceneInfo) => string): void\r\n        static provideSubSceneName(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (arg: SceneHierarchyHooks.SubSceneInfo) => string): (arg: SceneHierarchyHooks.SubSceneInfo) => string | void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SceneManagement\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    import { Transform, Color32 } from \"UnityEngine\";\r\n    import { SceneAsset } from \"UnityEditor\";\r\n    namespace SceneHierarchyHooks {\r\n        @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n        class SubSceneInfo extends ValueType {\r\n            constructor()\r\n            readonly isValid: boolean\r\n            transform: Transform\r\n            scene: any\r\n            sceneAsset: SceneAsset\r\n            sceneName: string\r\n            color: Color32\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SceneManagement\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** The setup information for a Scene in the SceneManager. This cannot be used in Play Mode. \r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class SceneSetup extends Object {\r\n        constructor()\r\n        /** Path of the Scene. Should be relative to the project folder. Like: \"AssetsMyScenesMyScene.unity\".\r\n         */\r\n        path: string\r\n        /** If the Scene is loaded.\r\n         */\r\n        isLoaded: boolean\r\n        /** If the Scene is active.\r\n         */\r\n        isActive: boolean\r\n        isSubScene: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SceneManagement\" {\r\n    import * as jsb from \"jsb\";\r\n    /** The Main Stage contains all the currently open regular Scenes and is always available.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class MainStage extends Stage {\r\n        constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SceneManagement\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ScriptableObject } from \"UnityEngine\";\r\n    /** The Stage class represents an editing context which includes a collection of Scenes.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class Stage extends ScriptableObject {\r\n        GetCombinedSceneCullingMaskForCamera(): number\r\n        /** The path of the Asset file associated with the stage, relative to the project root folder.\r\n         */\r\n        readonly assetPath: string\r\n        /** The StageHandle struct for this stage.\r\n         */\r\n        readonly stageHandle: StageHandle\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SceneManagement\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType } from \"System\";\r\n    /** The PreviewSceneStage class represents an editing context based on a single preview Scene.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class PreviewSceneStage extends Stage {\r\n        /** The preview Scene this stage controls. Stage content should be moved into this Scene.\r\n         */\r\n        readonly scene: any\r\n        /** See Stage.stageHandle.\r\n         */\r\n        readonly stageHandle: StageHandle\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SceneManagement\" {\r\n    import * as jsb from \"jsb\";\r\n    import { ValueType, Object } from \"System\";\r\n    import { GameObject } from \"UnityEngine\";\r\n    /** Struct that represents a stage handle.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class StageHandle extends ValueType {\r\n        constructor()\r\n        /** Does the stage contain the given GameObject?\r\n         * @param gameObject The GameObject to check.\r\n         * @returns True if the stage contains the given GameObject. \r\n         */\r\n        Contains(gameObject: GameObject): boolean\r\n        IsValid(): boolean\r\n        Equals(other: Object): boolean\r\n        Equals(other: StageHandle): boolean\r\n        GetHashCode(): number\r\n        static op_Equality(s1: StageHandle, s2: StageHandle): boolean\r\n        static op_Inequality(s1: StageHandle, s2: StageHandle): boolean\r\n        // js_op_overloading: static ==(s1: StageHandle, s2: StageHandle): boolean\r\n    }\r\n}\r\ndeclare module \"UnityEditor.SceneManagement\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, ValueType } from \"System\";\r\n    import { GameObject, Camera } from \"UnityEngine\";\r\n    /** Utility methods related to stages.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    abstract class StageUtility extends Object {\r\n        /** Is the given GameObject rendered by the given Camera?\r\n         * @param gameObject The GameObject to check.\r\n         * @param camera The camera to check.\r\n         * @returns True if the GameObject is rendered by the camera. \r\n         */\r\n        static IsGameObjectRenderedByCamera(gameObject: GameObject, camera: Camera): boolean\r\n        /** Specifies whether the given Camera currently renders the given GameObject and the GameObject is also part of an editable scene.\r\n         * @param gameObject The GameObject to check.\r\n         * @param camera The Camera to check.\r\n         * @returns True if the GameObject is rendered by the camera and part of an editable scene. \r\n         */\r\n        static IsGameObjectRenderedByCameraAndPartOfEditableScene(gameObject: GameObject, camera: Camera): boolean\r\n        static GetCurrentStage(): Stage\r\n        static GetMainStage(): MainStage\r\n        /** Get the Stage object that contains the input GameObject or Scene.\r\n         * @returns The Stage that contains either the GameObject or the Scene. \r\n         */\r\n        static GetStage(gameObject: GameObject): Stage\r\n        /** Get the Stage object that contains the input GameObject or Scene.\r\n         * @returns The Stage that contains either the GameObject or the Scene. \r\n         */\r\n        static GetStage(scene: any): Stage\r\n        static GetCurrentStageHandle(): StageHandle\r\n        static GetMainStageHandle(): StageHandle\r\n        /** Get the stage in which the given GameObject exists.\r\n         * @param gameObject The GameObject to find the stage of.\r\n         * @returns The stage of the GameObject. \r\n         */\r\n        static GetStageHandle(gameObject: GameObject): StageHandle\r\n        /** Get the stage in which the given Scene exists.\r\n         * @param scene The Scene to find the stage of.\r\n         * @returns The stage of the Scene. \r\n         */\r\n        static GetStageHandle(scene: any): StageHandle\r\n        static GoToMainStage(): void\r\n        static GoBackToPreviousStage(): void\r\n        /** Navigates the Editor to the specified stage.\r\n         * @param stage The stage to navigate to.\r\n         * @param setAsFirstItemAfterMainStage When set to true, the new stage replaces existing stages in the breadcrumbs, apart from the main stage.\r\n         */\r\n        static GoToStage(stage: Stage, setAsFirstItemAfterMainStage: boolean): void\r\n        /** Place the given GameObject in the current stage being edited.\r\n         * @param gameObject The GameObject to be placed in the current stage.\r\n         */\r\n        static PlaceGameObjectInCurrentStage(gameObject: GameObject): void\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Callbacks\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Add this attribute to a method to get a notification just after building the player.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class PostProcessBuildAttribute extends Object {\r\n        constructor(callbackOrder: number)\r\n        constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Callbacks\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Add this attribute to a method to get a notification just after building the Scene.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class PostProcessSceneAttribute extends Object {\r\n        constructor(callbackOrder: number, version: number)\r\n        constructor(callbackOrder: number)\r\n        constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Callbacks\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Add this attribute to a method to get a notification after scripts have been reloaded.\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class DidReloadScripts extends Object {\r\n        constructor(callbackOrder: number)\r\n        constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEditor.Callbacks\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object } from \"System\";\r\n    /** Callback attribute for opening an asset in Unity (e.g the callback is fired when double clicking an asset in the Project Browser).\r\n     */\r\n    @jsb.RequiredDefines(\"UNITY_EDITOR\")\r\n    class OnOpenAssetAttribute extends Object {\r\n        constructor(callbackOrder: number)\r\n        constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Object } from \"System\";\r\n    class AnimationTriggers extends Object {\r\n        constructor()\r\n        normalTrigger: string\r\n        highlightedTrigger: string\r\n        pressedTrigger: string\r\n        selectedTrigger: string\r\n        disabledTrigger: string\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { IEventSystemHandler, IPointerEnterHandler, ISelectHandler, IPointerExitHandler, IDeselectHandler, IPointerDownHandler, IPointerUpHandler, IMoveHandler, ISubmitHandler, IPointerClickHandler, PointerEventData, BaseEventData } from \"UnityEngine.EventSystems\";\r\n    class Button extends Selectable implements IEventSystemHandler, IPointerEnterHandler, ISelectHandler, IPointerExitHandler, IDeselectHandler, IPointerDownHandler, IPointerUpHandler, IMoveHandler, ISubmitHandler, IPointerClickHandler {\r\n        OnPointerClick(eventData: PointerEventData): void\r\n        OnSubmit(eventData: BaseEventData): void\r\n        /*protected*/ constructor()\r\n        onClick: Button.ButtonClickedEvent\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import * as jsb from \"jsb\";\r\n    import { UIBehaviour, IEventSystemHandler, IPointerEnterHandler, ISelectHandler, IPointerExitHandler, IDeselectHandler, IPointerDownHandler, IPointerUpHandler, IMoveHandler, AxisEventData, PointerEventData, BaseEventData } from \"UnityEngine.EventSystems\";\r\n    import { Array } from \"System\";\r\n    import { Animator, Vector3 } from \"UnityEngine\";\r\n    class Selectable extends UIBehaviour implements IEventSystemHandler, IPointerEnterHandler, ISelectHandler, IPointerExitHandler, IDeselectHandler, IPointerDownHandler, IPointerUpHandler, IMoveHandler {\r\n        IsInteractable(): boolean\r\n        FindSelectable(dir: Vector3): Selectable\r\n        FindSelectableOnLeft(): Selectable\r\n        FindSelectableOnRight(): Selectable\r\n        FindSelectableOnUp(): Selectable\r\n        FindSelectableOnDown(): Selectable\r\n        OnMove(eventData: AxisEventData): void\r\n        OnPointerDown(eventData: PointerEventData): void\r\n        OnPointerUp(eventData: PointerEventData): void\r\n        OnPointerEnter(eventData: PointerEventData): void\r\n        OnPointerExit(eventData: PointerEventData): void\r\n        OnSelect(eventData: BaseEventData): void\r\n        OnDeselect(eventData: BaseEventData): void\r\n        Select(): void\r\n        static AllSelectablesNoAlloc(selectables: Array<Selectable>): number\r\n        /*protected*/ constructor()\r\n        static readonly allSelectablesArray: Array<Selectable>\r\n        static readonly allSelectableCount: number\r\n        navigation: Navigation\r\n        transition: Selectable.Transition\r\n        colors: ColorBlock\r\n        spriteState: SpriteState\r\n        animationTriggers: AnimationTriggers\r\n        targetGraphic: Graphic\r\n        interactable: boolean\r\n        image: Image\r\n        readonly animator: Animator\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { MonoBehaviour } from \"UnityEngine\";\r\n    abstract class UIBehaviour extends MonoBehaviour {\r\n        IsActive(): boolean\r\n        IsDestroyed(): boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    enum CanvasUpdate {\r\n        Prelayout = 0,\r\n        Layout = 1,\r\n        PostLayout = 2,\r\n        PreRender = 3,\r\n        LatePreRender = 4,\r\n        MaxUpdateValue = 5,\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Transform } from \"UnityEngine\";\r\n    interface ICanvasElement {\r\n        Rebuild(executing: CanvasUpdate): void\r\n        LayoutComplete(): void\r\n        GraphicUpdateComplete(): void\r\n        IsDestroyed(): boolean\r\n        readonly transform: Transform\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Object } from \"System\";\r\n    class CanvasUpdateRegistry extends Object {\r\n        static RegisterCanvasElementForLayoutRebuild(element: ICanvasElement): void\r\n        static TryRegisterCanvasElementForLayoutRebuild(element: ICanvasElement): boolean\r\n        static RegisterCanvasElementForGraphicRebuild(element: ICanvasElement): void\r\n        static TryRegisterCanvasElementForGraphicRebuild(element: ICanvasElement): boolean\r\n        static UnRegisterCanvasElementForRebuild(element: ICanvasElement): void\r\n        static IsRebuildingLayout(): boolean\r\n        static IsRebuildingGraphics(): boolean\r\n        protected constructor()\r\n        static readonly instance: CanvasUpdateRegistry\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { ValueType, Object } from \"System\";\r\n    import { Color } from \"UnityEngine\";\r\n    class ColorBlock extends ValueType {\r\n        constructor()\r\n        Equals(obj: Object): boolean\r\n        Equals(other: ColorBlock): boolean\r\n        GetHashCode(): number\r\n        static op_Equality(point1: ColorBlock, point2: ColorBlock): boolean\r\n        static op_Inequality(point1: ColorBlock, point2: ColorBlock): boolean\r\n        // js_op_overloading: static ==(point1: ColorBlock, point2: ColorBlock): boolean\r\n        normalColor: Color\r\n        highlightedColor: Color\r\n        pressedColor: Color\r\n        selectedColor: Color\r\n        disabledColor: Color\r\n        colorMultiplier: number\r\n        fadeDuration: number\r\n        static defaultColorBlock: ColorBlock\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Object } from \"System\";\r\n    class ClipperRegistry extends Object {\r\n        Cull(): void\r\n        static Register(c: IClipper): void\r\n        static Unregister(c: IClipper): void\r\n        protected constructor()\r\n        static readonly instance: ClipperRegistry\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { Rect } from \"UnityEngine\";\r\n    abstract class Clipping extends Object {\r\n        static FindCullAndClipWorldRect(rectMaskParents: any, validRect: jsb.Out<boolean>): Rect\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    interface IClipper {\r\n        PerformClipping(): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { GameObject, RectTransform, Rect, Vector2 } from \"UnityEngine\";\r\n    interface IClippable {\r\n        RecalculateClipping(): void\r\n        Cull(clipRect: Rect, validRect: boolean): void\r\n        SetClipRect(value: Rect, validRect: boolean): void\r\n        SetClipSoftness(clipSoftness: Vector2): void\r\n        readonly gameObject: GameObject\r\n        readonly rectTransform: RectTransform\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Object } from \"System\";\r\n    import { GameObject } from \"UnityEngine\";\r\n    abstract class DefaultControls extends Object {\r\n        static CreatePanel(resources: DefaultControls.Resources): GameObject\r\n        static CreateButton(resources: DefaultControls.Resources): GameObject\r\n        static CreateText(resources: DefaultControls.Resources): GameObject\r\n        static CreateImage(resources: DefaultControls.Resources): GameObject\r\n        static CreateRawImage(resources: DefaultControls.Resources): GameObject\r\n        static CreateSlider(resources: DefaultControls.Resources): GameObject\r\n        static CreateScrollbar(resources: DefaultControls.Resources): GameObject\r\n        static CreateToggle(resources: DefaultControls.Resources): GameObject\r\n        static CreateInputField(resources: DefaultControls.Resources): GameObject\r\n        static CreateDropdown(resources: DefaultControls.Resources): GameObject\r\n        static CreateScrollView(resources: DefaultControls.Resources): GameObject\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { IEventSystemHandler, IPointerEnterHandler, ISelectHandler, IPointerExitHandler, IDeselectHandler, IPointerDownHandler, IPointerUpHandler, IMoveHandler, ISubmitHandler, IPointerClickHandler, ICancelHandler, PointerEventData, BaseEventData } from \"UnityEngine.EventSystems\";\r\n    import { RectTransform, Sprite } from \"UnityEngine\";\r\n    import { Object } from \"System\";\r\n    class Dropdown extends Selectable implements IEventSystemHandler, IPointerEnterHandler, ISelectHandler, IPointerExitHandler, IDeselectHandler, IPointerDownHandler, IPointerUpHandler, IMoveHandler, ISubmitHandler, IPointerClickHandler, ICancelHandler {\r\n        SetValueWithoutNotify(input: number): void\r\n        RefreshShownValue(): void\r\n        AddOptions(options: any): void\r\n        AddOptions(options: any): void\r\n        AddOptions(options: any): void\r\n        ClearOptions(): void\r\n        OnPointerClick(eventData: PointerEventData): void\r\n        OnSubmit(eventData: BaseEventData): void\r\n        OnCancel(eventData: BaseEventData): void\r\n        Show(): void\r\n        Hide(): void\r\n        /*protected*/ constructor()\r\n        template: RectTransform\r\n        captionText: Text\r\n        captionImage: Image\r\n        itemText: Text\r\n        itemImage: Image\r\n        options: any\r\n        onValueChanged: Dropdown.DropdownEvent\r\n        alphaFadeSpeed: number\r\n        value: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Object, Enum } from \"System\";\r\n    import { Object as Object1, TextAnchor } from \"UnityEngine\";\r\n    class FontData extends Object {\r\n        constructor()\r\n        static readonly defaultFontData: FontData\r\n        font: any\r\n        fontSize: number\r\n        fontStyle: any\r\n        bestFit: boolean\r\n        minSize: number\r\n        maxSize: number\r\n        alignment: TextAnchor\r\n        alignByGeometry: boolean\r\n        richText: boolean\r\n        horizontalOverflow: any\r\n        verticalOverflow: any\r\n        lineSpacing: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Object } from \"System\";\r\n    abstract class FontUpdateTracker extends Object {\r\n        static TrackText(t: Text): void\r\n        static UntrackText(t: Text): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UIBehaviour } from \"UnityEngine.EventSystems\";\r\n    import { Material, Color, Vector4, RectTransform, Behaviour, Component, Texture, Vector2, Camera, Rect } from \"UnityEngine\";\r\n    abstract class Graphic extends UIBehaviour implements ICanvasElement {\r\n        SetAllDirty(): void\r\n        SetLayoutDirty(): void\r\n        SetVerticesDirty(): void\r\n        SetMaterialDirty(): void\r\n        OnCullingChanged(): void\r\n        Rebuild(update: CanvasUpdate): void\r\n        LayoutComplete(): void\r\n        GraphicUpdateComplete(): void\r\n        SetNativeSize(): void\r\n        Raycast(sp: Vector2, eventCamera: Camera): boolean\r\n        PixelAdjustPoint(point: Vector2): Vector2\r\n        GetPixelAdjustedRect(): Rect\r\n        CrossFadeColor(targetColor: Color, duration: number, ignoreTimeScale: boolean, useAlpha: boolean, useRGB: boolean): void\r\n        CrossFadeColor(targetColor: Color, duration: number, ignoreTimeScale: boolean, useAlpha: boolean): void\r\n        CrossFadeAlpha(alpha: number, duration: number, ignoreTimeScale: boolean): void\r\n        RegisterDirtyLayoutCallback(action: () => void): void\r\n        UnregisterDirtyLayoutCallback(action: () => void): void\r\n        RegisterDirtyVerticesCallback(action: () => void): void\r\n        UnregisterDirtyVerticesCallback(action: () => void): void\r\n        RegisterDirtyMaterialCallback(action: () => void): void\r\n        UnregisterDirtyMaterialCallback(action: () => void): void\r\n        static readonly defaultGraphicMaterial: Material\r\n        color: Color\r\n        raycastTarget: boolean\r\n        raycastPadding: Vector4\r\n        readonly depth: number\r\n        readonly rectTransform: RectTransform\r\n        readonly canvas: any\r\n        readonly canvasRenderer: any\r\n        readonly defaultMaterial: Material\r\n        material: Material\r\n        readonly materialForRendering: Material\r\n        readonly mainTexture: Texture\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { BaseRaycaster, PointerEventData, RaycastResult } from \"UnityEngine.EventSystems\";\r\n    import { LayerMask, Camera } from \"UnityEngine\";\r\n    import { Object } from \"System\";\r\n    class GraphicRaycaster extends BaseRaycaster {\r\n        Raycast(eventData: PointerEventData, resultAppendList: any): void\r\n        /*protected*/ constructor()\r\n        readonly sortOrderPriority: number\r\n        readonly renderOrderPriority: number\r\n        ignoreReversedGraphics: boolean\r\n        blockingObjects: GraphicRaycaster.BlockingObjects\r\n        blockingMask: LayerMask\r\n        readonly eventCamera: Camera\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { Camera } from \"UnityEngine\";\r\n    import { Object } from \"System\";\r\n    abstract class BaseRaycaster extends UIBehaviour {\r\n        Raycast(eventData: PointerEventData, resultAppendList: any): void\r\n        toString(): string\r\n        readonly eventCamera: Camera\r\n        readonly sortOrderPriority: number\r\n        readonly renderOrderPriority: number\r\n        readonly rootRaycaster: BaseRaycaster\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Object } from \"System\";\r\n    import { Behaviour } from \"UnityEngine\";\r\n    class GraphicRegistry extends Object {\r\n        static RegisterGraphicForCanvas(c: any, graphic: Graphic): void\r\n        static RegisterRaycastGraphicForCanvas(c: any, graphic: Graphic): void\r\n        static UnregisterGraphicForCanvas(c: any, graphic: Graphic): void\r\n        static UnregisterRaycastGraphicForCanvas(c: any, graphic: Graphic): void\r\n        static GetGraphicsForCanvas(canvas: any): any\r\n        static GetRaycastableGraphicsForCanvas(canvas: any): any\r\n        protected constructor()\r\n        static readonly instance: GraphicRegistry\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    interface IMaskable {\r\n        RecalculateMasking(): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Sprite, Material, Texture, Vector2, Camera } from \"UnityEngine\";\r\n    class Image extends MaskableGraphic implements IMaterialModifier, IMaskable, ICanvasElement, ILayoutElement, IClippable {\r\n        DisableSpriteOptimizations(): void\r\n        OnBeforeSerialize(): void\r\n        OnAfterDeserialize(): void\r\n        SetNativeSize(): void\r\n        CalculateLayoutInputHorizontal(): void\r\n        CalculateLayoutInputVertical(): void\r\n        IsRaycastLocationValid(screenPoint: Vector2, eventCamera: Camera): boolean\r\n        /*protected*/ constructor()\r\n        sprite: Sprite\r\n        overrideSprite: Sprite\r\n        type: Image.Type\r\n        preserveAspect: boolean\r\n        fillCenter: boolean\r\n        fillMethod: Image.FillMethod\r\n        fillAmount: number\r\n        fillClockwise: boolean\r\n        fillOrigin: number\r\n        alphaHitTestMinimumThreshold: number\r\n        useSpriteMesh: boolean\r\n        static readonly defaultETC1GraphicMaterial: Material\r\n        readonly mainTexture: Texture\r\n        readonly hasBorder: boolean\r\n        pixelsPerUnitMultiplier: number\r\n        readonly pixelsPerUnit: number\r\n        material: Material\r\n        readonly minWidth: number\r\n        readonly preferredWidth: number\r\n        readonly flexibleWidth: number\r\n        readonly minHeight: number\r\n        readonly preferredHeight: number\r\n        readonly flexibleHeight: number\r\n        readonly layoutPriority: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Material, Rect, Vector2 } from \"UnityEngine\";\r\n    abstract class MaskableGraphic extends Graphic implements IMaterialModifier, IMaskable, ICanvasElement, IClippable {\r\n        GetModifiedMaterial(baseMaterial: Material): Material\r\n        Cull(clipRect: Rect, validRect: boolean): void\r\n        SetClipRect(clipRect: Rect, validRect: boolean): void\r\n        SetClipSoftness(clipSoftness: Vector2): void\r\n        RecalculateClipping(): void\r\n        RecalculateMasking(): void\r\n        onCullStateChanged: MaskableGraphic.CullStateChangedEvent\r\n        maskable: boolean\r\n        isMaskingGraphic: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { IDragHandler, IEndDragHandler, IEventSystemHandler, IPointerEnterHandler, IUpdateSelectedHandler, ISelectHandler, IPointerExitHandler, IDeselectHandler, IPointerDownHandler, IPointerUpHandler, IMoveHandler, ISubmitHandler, IPointerClickHandler, IBeginDragHandler, PointerEventData, BaseEventData } from \"UnityEngine.EventSystems\";\r\n    import { Color, Event } from \"UnityEngine\";\r\n    import { Object, Enum } from \"System\";\r\n    class InputField extends Selectable implements IDragHandler, IEndDragHandler, ICanvasElement, IEventSystemHandler, IPointerEnterHandler, IUpdateSelectedHandler, ISelectHandler, IPointerExitHandler, IDeselectHandler, IPointerDownHandler, IPointerUpHandler, IMoveHandler, ILayoutElement, ISubmitHandler, IPointerClickHandler, IBeginDragHandler {\r\n        SetTextWithoutNotify(input: string): void\r\n        MoveTextEnd(shift: boolean): void\r\n        MoveTextStart(shift: boolean): void\r\n        OnBeginDrag(eventData: PointerEventData): void\r\n        OnDrag(eventData: PointerEventData): void\r\n        OnEndDrag(eventData: PointerEventData): void\r\n        OnPointerDown(eventData: PointerEventData): void\r\n        ProcessEvent(e: Event): void\r\n        OnUpdateSelected(eventData: BaseEventData): void\r\n        ForceLabelUpdate(): void\r\n        Rebuild(update: CanvasUpdate): void\r\n        LayoutComplete(): void\r\n        GraphicUpdateComplete(): void\r\n        ActivateInputField(): void\r\n        OnSelect(eventData: BaseEventData): void\r\n        OnPointerClick(eventData: PointerEventData): void\r\n        DeactivateInputField(): void\r\n        OnDeselect(eventData: BaseEventData): void\r\n        OnSubmit(eventData: BaseEventData): void\r\n        CalculateLayoutInputHorizontal(): void\r\n        CalculateLayoutInputVertical(): void\r\n        /*protected*/ constructor()\r\n        shouldHideMobileInput: boolean\r\n        shouldActivateOnSelect: boolean\r\n        text: string\r\n        readonly isFocused: boolean\r\n        caretBlinkRate: number\r\n        caretWidth: number\r\n        textComponent: Text\r\n        placeholder: Graphic\r\n        caretColor: Color\r\n        customCaretColor: boolean\r\n        selectionColor: Color\r\n        onEndEdit: InputField.SubmitEvent\r\n        onValueChanged: InputField.OnChangeEvent\r\n        characterLimit: number\r\n        contentType: InputField.ContentType\r\n        lineType: InputField.LineType\r\n        inputType: InputField.InputType\r\n        readonly touchScreenKeyboard: any\r\n        keyboardType: any\r\n        characterValidation: InputField.CharacterValidation\r\n        readOnly: boolean\r\n        readonly multiLine: boolean\r\n        asteriskChar: string\r\n        readonly wasCanceled: boolean\r\n        caretPosition: number\r\n        selectionAnchorPosition: number\r\n        selectionFocusPosition: number\r\n        readonly minWidth: number\r\n        readonly preferredWidth: number\r\n        readonly flexibleWidth: number\r\n        readonly minHeight: number\r\n        readonly preferredHeight: number\r\n        readonly flexibleHeight: number\r\n        readonly layoutPriority: number\r\n        onValidateInput(op: \"get\"): (text: string, charIndex: number, addedChar: string) => string\r\n        onValidateInput(op: \"add\" | \"remove\" | \"set\", fn?: (text: string, charIndex: number, addedChar: string) => string): void\r\n        onValidateInput(op: \"add\" | \"remove\" | \"set\" | \"get\", fn?: (text: string, charIndex: number, addedChar: string) => string): (text: string, charIndex: number, addedChar: string) => string | void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UIBehaviour } from \"UnityEngine.EventSystems\";\r\n    class AspectRatioFitter extends UIBehaviour implements ILayoutController {\r\n        SetLayoutHorizontal(): void\r\n        SetLayoutVertical(): void\r\n        IsComponentValidOnObject(): boolean\r\n        IsAspectModeValid(): boolean\r\n        /*protected*/ constructor()\r\n        aspectMode: AspectRatioFitter.AspectMode\r\n        aspectRatio: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UIBehaviour } from \"UnityEngine.EventSystems\";\r\n    import { Vector2 } from \"UnityEngine\";\r\n    class CanvasScaler extends UIBehaviour {\r\n        /*protected*/ constructor()\r\n        uiScaleMode: CanvasScaler.ScaleMode\r\n        referencePixelsPerUnit: number\r\n        scaleFactor: number\r\n        referenceResolution: Vector2\r\n        screenMatchMode: CanvasScaler.ScreenMatchMode\r\n        matchWidthOrHeight: number\r\n        physicalUnit: CanvasScaler.Unit\r\n        fallbackScreenDPI: number\r\n        defaultSpriteDPI: number\r\n        dynamicPixelsPerUnit: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UIBehaviour } from \"UnityEngine.EventSystems\";\r\n    class ContentSizeFitter extends UIBehaviour implements ILayoutController {\r\n        SetLayoutHorizontal(): void\r\n        SetLayoutVertical(): void\r\n        /*protected*/ constructor()\r\n        horizontalFit: ContentSizeFitter.FitMode\r\n        verticalFit: ContentSizeFitter.FitMode\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Vector2 } from \"UnityEngine\";\r\n    class GridLayoutGroup extends LayoutGroup implements ILayoutElement, ILayoutController {\r\n        CalculateLayoutInputHorizontal(): void\r\n        CalculateLayoutInputVertical(): void\r\n        SetLayoutHorizontal(): void\r\n        SetLayoutVertical(): void\r\n        /*protected*/ constructor()\r\n        startCorner: GridLayoutGroup.Corner\r\n        startAxis: GridLayoutGroup.Axis\r\n        cellSize: Vector2\r\n        spacing: Vector2\r\n        constraint: GridLayoutGroup.Constraint\r\n        constraintCount: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UIBehaviour } from \"UnityEngine.EventSystems\";\r\n    import { Object } from \"System\";\r\n    import { TextAnchor } from \"UnityEngine\";\r\n    abstract class LayoutGroup extends UIBehaviour implements ILayoutElement, ILayoutController {\r\n        CalculateLayoutInputHorizontal(): void\r\n        CalculateLayoutInputVertical(): void\r\n        SetLayoutHorizontal(): void\r\n        SetLayoutVertical(): void\r\n        padding: any\r\n        childAlignment: TextAnchor\r\n        readonly minWidth: number\r\n        readonly preferredWidth: number\r\n        readonly flexibleWidth: number\r\n        readonly minHeight: number\r\n        readonly preferredHeight: number\r\n        readonly flexibleHeight: number\r\n        readonly layoutPriority: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    class HorizontalLayoutGroup extends HorizontalOrVerticalLayoutGroup implements ILayoutElement, ILayoutController {\r\n        CalculateLayoutInputHorizontal(): void\r\n        CalculateLayoutInputVertical(): void\r\n        SetLayoutHorizontal(): void\r\n        SetLayoutVertical(): void\r\n        /*protected*/ constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    abstract class HorizontalOrVerticalLayoutGroup extends LayoutGroup implements ILayoutElement, ILayoutController {\r\n        spacing: number\r\n        childForceExpandWidth: boolean\r\n        childForceExpandHeight: boolean\r\n        childControlWidth: boolean\r\n        childControlHeight: boolean\r\n        childScaleWidth: boolean\r\n        childScaleHeight: boolean\r\n        reverseArrangement: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    interface ILayoutElement {\r\n        CalculateLayoutInputHorizontal(): void\r\n        CalculateLayoutInputVertical(): void\r\n        readonly minWidth: number\r\n        readonly preferredWidth: number\r\n        readonly flexibleWidth: number\r\n        readonly minHeight: number\r\n        readonly preferredHeight: number\r\n        readonly flexibleHeight: number\r\n        readonly layoutPriority: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    interface ILayoutController {\r\n        SetLayoutHorizontal(): void\r\n        SetLayoutVertical(): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    interface ILayoutIgnorer {\r\n        readonly ignoreLayout: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UIBehaviour } from \"UnityEngine.EventSystems\";\r\n    class LayoutElement extends UIBehaviour implements ILayoutIgnorer, ILayoutElement {\r\n        CalculateLayoutInputHorizontal(): void\r\n        CalculateLayoutInputVertical(): void\r\n        /*protected*/ constructor()\r\n        ignoreLayout: boolean\r\n        minWidth: number\r\n        minHeight: number\r\n        preferredWidth: number\r\n        preferredHeight: number\r\n        flexibleWidth: number\r\n        flexibleHeight: number\r\n        layoutPriority: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Object } from \"System\";\r\n    import { Transform, RectTransform } from \"UnityEngine\";\r\n    class LayoutRebuilder extends Object implements ICanvasElement {\r\n        constructor()\r\n        IsDestroyed(): boolean\r\n        Rebuild(executing: CanvasUpdate): void\r\n        LayoutComplete(): void\r\n        GraphicUpdateComplete(): void\r\n        GetHashCode(): number\r\n        Equals(obj: Object): boolean\r\n        toString(): string\r\n        static ForceRebuildLayoutImmediate(layoutRoot: RectTransform): void\r\n        static MarkLayoutForRebuild(rect: RectTransform): void\r\n        readonly transform: Transform\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array } from \"System\";\r\n    import { RectTransform } from \"UnityEngine\";\r\n    abstract class LayoutUtility extends Object {\r\n        static GetMinSize(rect: RectTransform, axis: number): number\r\n        static GetPreferredSize(rect: RectTransform, axis: number): number\r\n        static GetFlexibleSize(rect: RectTransform, axis: number): number\r\n        static GetMinWidth(rect: RectTransform): number\r\n        static GetPreferredWidth(rect: RectTransform): number\r\n        static GetFlexibleWidth(rect: RectTransform): number\r\n        static GetMinHeight(rect: RectTransform): number\r\n        static GetPreferredHeight(rect: RectTransform): number\r\n        static GetFlexibleHeight(rect: RectTransform): number\r\n        static GetLayoutProperty(rect: RectTransform, property: (arg: ILayoutElement) => number, defaultValue: number, source: jsb.Out<ILayoutElement>): number\r\n        static GetLayoutProperty(rect: RectTransform, property: (arg: ILayoutElement) => number, defaultValue: number): number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    class VerticalLayoutGroup extends HorizontalOrVerticalLayoutGroup implements ILayoutElement, ILayoutController {\r\n        CalculateLayoutInputHorizontal(): void\r\n        CalculateLayoutInputVertical(): void\r\n        SetLayoutHorizontal(): void\r\n        SetLayoutVertical(): void\r\n        /*protected*/ constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UIBehaviour } from \"UnityEngine.EventSystems\";\r\n    import { RectTransform, Vector2, Camera, Material } from \"UnityEngine\";\r\n    class Mask extends UIBehaviour implements IMaterialModifier {\r\n        MaskEnabled(): boolean\r\n        IsRaycastLocationValid(sp: Vector2, eventCamera: Camera): boolean\r\n        GetModifiedMaterial(baseMaterial: Material): Material\r\n        /*protected*/ constructor()\r\n        readonly rectTransform: RectTransform\r\n        showMaskGraphic: boolean\r\n        readonly graphic: Graphic\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Object } from \"System\";\r\n    import { Component, Transform } from \"UnityEngine\";\r\n    class MaskUtilities extends Object {\r\n        constructor()\r\n        static Notify2DMaskStateChanged(mask: Component): void\r\n        static NotifyStencilStateChanged(mask: Component): void\r\n        static FindRootSortOverrideCanvas(start: Transform): Transform\r\n        static GetStencilDepth(transform: Transform, stopAfter: Transform): number\r\n        static IsDescendantOrSelf(father: Transform, child: Transform): boolean\r\n        static GetRectMaskForClippable(clippable: IClippable): RectMask2D\r\n        static GetRectMasksForClip(clipper: RectMask2D, masks: any): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Material } from \"UnityEngine\";\r\n    interface IMaterialModifier {\r\n        GetModifiedMaterial(baseMaterial: Material): Material\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { ValueType } from \"System\";\r\n    class Navigation extends ValueType {\r\n        constructor()\r\n        Equals(other: Navigation): boolean\r\n        mode: Navigation.Mode\r\n        wrapAround: boolean\r\n        selectOnUp: Selectable\r\n        selectOnDown: Selectable\r\n        selectOnLeft: Selectable\r\n        selectOnRight: Selectable\r\n        static readonly defaultNavigation: Navigation\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Texture, Rect } from \"UnityEngine\";\r\n    class RawImage extends MaskableGraphic implements IMaterialModifier, IMaskable, ICanvasElement, IClippable {\r\n        SetNativeSize(): void\r\n        /*protected*/ constructor()\r\n        readonly mainTexture: Texture\r\n        texture: Texture\r\n        uvRect: Rect\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UIBehaviour } from \"UnityEngine.EventSystems\";\r\n    import { Vector4, Vector2Int, Rect, RectTransform, Vector2, Camera } from \"UnityEngine\";\r\n    class RectMask2D extends UIBehaviour implements IClipper {\r\n        IsRaycastLocationValid(sp: Vector2, eventCamera: Camera): boolean\r\n        PerformClipping(): void\r\n        UpdateClipSoftness(): void\r\n        AddClippable(clippable: IClippable): void\r\n        RemoveClippable(clippable: IClippable): void\r\n        /*protected*/ constructor()\r\n        padding: Vector4\r\n        softness: Vector2Int\r\n        readonly canvasRect: Rect\r\n        readonly rectTransform: RectTransform\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UIBehaviour, IInitializePotentialDragHandler, IDragHandler, IEndDragHandler, IScrollHandler, IEventSystemHandler, IBeginDragHandler, PointerEventData } from \"UnityEngine.EventSystems\";\r\n    import { RectTransform, Vector2 } from \"UnityEngine\";\r\n    class ScrollRect extends UIBehaviour implements IInitializePotentialDragHandler, IDragHandler, IEndDragHandler, ICanvasElement, IScrollHandler, IEventSystemHandler, ILayoutElement, ILayoutController, IBeginDragHandler {\r\n        Rebuild(executing: CanvasUpdate): void\r\n        LayoutComplete(): void\r\n        GraphicUpdateComplete(): void\r\n        IsActive(): boolean\r\n        StopMovement(): void\r\n        OnScroll(data: PointerEventData): void\r\n        OnInitializePotentialDrag(eventData: PointerEventData): void\r\n        OnBeginDrag(eventData: PointerEventData): void\r\n        OnEndDrag(eventData: PointerEventData): void\r\n        OnDrag(eventData: PointerEventData): void\r\n        CalculateLayoutInputHorizontal(): void\r\n        CalculateLayoutInputVertical(): void\r\n        SetLayoutHorizontal(): void\r\n        SetLayoutVertical(): void\r\n        /*protected*/ constructor()\r\n        content: RectTransform\r\n        horizontal: boolean\r\n        vertical: boolean\r\n        movementType: ScrollRect.MovementType\r\n        elasticity: number\r\n        inertia: boolean\r\n        decelerationRate: number\r\n        scrollSensitivity: number\r\n        viewport: RectTransform\r\n        horizontalScrollbar: Scrollbar\r\n        verticalScrollbar: Scrollbar\r\n        horizontalScrollbarVisibility: ScrollRect.ScrollbarVisibility\r\n        verticalScrollbarVisibility: ScrollRect.ScrollbarVisibility\r\n        horizontalScrollbarSpacing: number\r\n        verticalScrollbarSpacing: number\r\n        onValueChanged: ScrollRect.ScrollRectEvent\r\n        velocity: Vector2\r\n        normalizedPosition: Vector2\r\n        horizontalNormalizedPosition: number\r\n        verticalNormalizedPosition: number\r\n        readonly minWidth: number\r\n        readonly preferredWidth: number\r\n        readonly flexibleWidth: number\r\n        readonly minHeight: number\r\n        readonly preferredHeight: number\r\n        readonly flexibleHeight: number\r\n        readonly layoutPriority: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { IInitializePotentialDragHandler, IDragHandler, IEventSystemHandler, IPointerEnterHandler, ISelectHandler, IPointerExitHandler, IDeselectHandler, IPointerDownHandler, IPointerUpHandler, IMoveHandler, IBeginDragHandler, PointerEventData, AxisEventData } from \"UnityEngine.EventSystems\";\r\n    import { RectTransform } from \"UnityEngine\";\r\n    class Scrollbar extends Selectable implements IInitializePotentialDragHandler, IDragHandler, ICanvasElement, IEventSystemHandler, IPointerEnterHandler, ISelectHandler, IPointerExitHandler, IDeselectHandler, IPointerDownHandler, IPointerUpHandler, IMoveHandler, IBeginDragHandler {\r\n        SetValueWithoutNotify(input: number): void\r\n        Rebuild(executing: CanvasUpdate): void\r\n        LayoutComplete(): void\r\n        GraphicUpdateComplete(): void\r\n        OnBeginDrag(eventData: PointerEventData): void\r\n        OnDrag(eventData: PointerEventData): void\r\n        OnPointerDown(eventData: PointerEventData): void\r\n        OnPointerUp(eventData: PointerEventData): void\r\n        OnMove(eventData: AxisEventData): void\r\n        FindSelectableOnLeft(): Selectable\r\n        FindSelectableOnRight(): Selectable\r\n        FindSelectableOnUp(): Selectable\r\n        FindSelectableOnDown(): Selectable\r\n        OnInitializePotentialDrag(eventData: PointerEventData): void\r\n        SetDirection(direction: Scrollbar.Direction, includeRectLayouts: boolean): void\r\n        /*protected*/ constructor()\r\n        handleRect: RectTransform\r\n        direction: Scrollbar.Direction\r\n        value: number\r\n        size: number\r\n        numberOfSteps: number\r\n        onValueChanged: Scrollbar.ScrollEvent\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { IInitializePotentialDragHandler, IDragHandler, IEventSystemHandler, IPointerEnterHandler, ISelectHandler, IPointerExitHandler, IDeselectHandler, IPointerDownHandler, IPointerUpHandler, IMoveHandler, PointerEventData, AxisEventData } from \"UnityEngine.EventSystems\";\r\n    import { RectTransform } from \"UnityEngine\";\r\n    class Slider extends Selectable implements IInitializePotentialDragHandler, IDragHandler, ICanvasElement, IEventSystemHandler, IPointerEnterHandler, ISelectHandler, IPointerExitHandler, IDeselectHandler, IPointerDownHandler, IPointerUpHandler, IMoveHandler {\r\n        SetValueWithoutNotify(input: number): void\r\n        Rebuild(executing: CanvasUpdate): void\r\n        LayoutComplete(): void\r\n        GraphicUpdateComplete(): void\r\n        OnPointerDown(eventData: PointerEventData): void\r\n        OnDrag(eventData: PointerEventData): void\r\n        OnMove(eventData: AxisEventData): void\r\n        FindSelectableOnLeft(): Selectable\r\n        FindSelectableOnRight(): Selectable\r\n        FindSelectableOnUp(): Selectable\r\n        FindSelectableOnDown(): Selectable\r\n        OnInitializePotentialDrag(eventData: PointerEventData): void\r\n        SetDirection(direction: Slider.Direction, includeRectLayouts: boolean): void\r\n        /*protected*/ constructor()\r\n        fillRect: RectTransform\r\n        handleRect: RectTransform\r\n        direction: Slider.Direction\r\n        minValue: number\r\n        maxValue: number\r\n        wholeNumbers: boolean\r\n        value: number\r\n        normalizedValue: number\r\n        onValueChanged: Slider.SliderEvent\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { ValueType } from \"System\";\r\n    import { Sprite } from \"UnityEngine\";\r\n    class SpriteState extends ValueType {\r\n        constructor()\r\n        Equals(other: SpriteState): boolean\r\n        highlightedSprite: Sprite\r\n        pressedSprite: Sprite\r\n        selectedSprite: Sprite\r\n        disabledSprite: Sprite\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Object, Enum } from \"System\";\r\n    import { Material } from \"UnityEngine\";\r\n    abstract class StencilMaterial extends Object {\r\n        static Add(baseMat: Material, stencilID: number, operation: any, compareFunction: any, colorWriteMask: any, readMask: number, writeMask: number): Material\r\n        static Add(baseMat: Material, stencilID: number, operation: any, compareFunction: any, colorWriteMask: any): Material\r\n        static Remove(customMat: Material): void\r\n        static ClearAll(): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Object, Enum, ValueType } from \"System\";\r\n    import { Texture, Object as Object1, TextAnchor, Vector2 } from \"UnityEngine\";\r\n    class Text extends MaskableGraphic implements IMaterialModifier, IMaskable, ICanvasElement, ILayoutElement, IClippable {\r\n        FontTextureChanged(): void\r\n        GetGenerationSettings(extents: Vector2): any\r\n        CalculateLayoutInputHorizontal(): void\r\n        CalculateLayoutInputVertical(): void\r\n        static GetTextAnchorPivot(anchor: TextAnchor): Vector2\r\n        /*protected*/ constructor()\r\n        readonly cachedTextGenerator: any\r\n        readonly cachedTextGeneratorForLayout: any\r\n        readonly mainTexture: Texture\r\n        font: any\r\n        text: string\r\n        supportRichText: boolean\r\n        resizeTextForBestFit: boolean\r\n        resizeTextMinSize: number\r\n        resizeTextMaxSize: number\r\n        alignment: TextAnchor\r\n        alignByGeometry: boolean\r\n        fontSize: number\r\n        horizontalOverflow: any\r\n        verticalOverflow: any\r\n        lineSpacing: number\r\n        fontStyle: any\r\n        readonly pixelsPerUnit: number\r\n        readonly minWidth: number\r\n        readonly preferredWidth: number\r\n        readonly flexibleWidth: number\r\n        readonly minHeight: number\r\n        readonly preferredHeight: number\r\n        readonly flexibleHeight: number\r\n        readonly layoutPriority: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { IEventSystemHandler, IPointerEnterHandler, ISelectHandler, IPointerExitHandler, IDeselectHandler, IPointerDownHandler, IPointerUpHandler, IMoveHandler, ISubmitHandler, IPointerClickHandler, PointerEventData, BaseEventData } from \"UnityEngine.EventSystems\";\r\n    class Toggle extends Selectable implements ICanvasElement, IEventSystemHandler, IPointerEnterHandler, ISelectHandler, IPointerExitHandler, IDeselectHandler, IPointerDownHandler, IPointerUpHandler, IMoveHandler, ISubmitHandler, IPointerClickHandler {\r\n        Rebuild(executing: CanvasUpdate): void\r\n        LayoutComplete(): void\r\n        GraphicUpdateComplete(): void\r\n        SetIsOnWithoutNotify(value: boolean): void\r\n        OnPointerClick(eventData: PointerEventData): void\r\n        OnSubmit(eventData: BaseEventData): void\r\n        /*protected*/ constructor()\r\n        group: ToggleGroup\r\n        isOn: boolean\r\n        toggleTransition: Toggle.ToggleTransition\r\n        graphic: Graphic\r\n        onValueChanged: Toggle.ToggleEvent\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UIBehaviour } from \"UnityEngine.EventSystems\";\r\n    import { IEnumerable } from \"System.Collections.Generic\";\r\n    class ToggleGroup extends UIBehaviour {\r\n        NotifyToggleOn(toggle: Toggle, sendCallback: boolean): void\r\n        UnregisterToggle(toggle: Toggle): void\r\n        RegisterToggle(toggle: Toggle): void\r\n        EnsureValidState(): void\r\n        AnyTogglesOn(): boolean\r\n        ActiveToggles(): any\r\n        GetFirstActiveToggle(): Toggle\r\n        SetAllTogglesOff(sendCallback: boolean): void\r\n        /*protected*/ constructor()\r\n        allowSwitchOff: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array, ValueType } from \"System\";\r\n    import { Object as Object1, Vector3, Color32, Vector4 } from \"UnityEngine\";\r\n    class VertexHelper extends Object {\r\n        constructor(m: any)\r\n        constructor()\r\n        Dispose(): void\r\n        Clear(): void\r\n        PopulateUIVertex(vertex: jsb.Ref<any>, i: number): void\r\n        SetUIVertex(vertex: any, i: number): void\r\n        FillMesh(mesh: any): void\r\n        AddVert(position: Vector3, color: Color32, uv0: Vector4, uv1: Vector4, uv2: Vector4, uv3: Vector4, normal: Vector3, tangent: Vector4): void\r\n        AddVert(position: Vector3, color: Color32, uv0: Vector4, uv1: Vector4, normal: Vector3, tangent: Vector4): void\r\n        AddVert(position: Vector3, color: Color32, uv0: Vector4): void\r\n        AddVert(v: any): void\r\n        AddTriangle(idx0: number, idx1: number, idx2: number): void\r\n        AddUIVertexQuad(verts: Array<any>): void\r\n        AddUIVertexStream(verts: any, indices: any): void\r\n        AddUIVertexTriangleStream(verts: any): void\r\n        GetUIVertexStream(stream: any): void\r\n        readonly currentVertCount: number\r\n        readonly currentIndexCount: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UIBehaviour } from \"UnityEngine.EventSystems\";\r\n    import { Object } from \"UnityEngine\";\r\n    abstract class BaseMeshEffect extends UIBehaviour implements IMeshModifier {\r\n        ModifyMesh(mesh: any): void\r\n        ModifyMesh(vh: VertexHelper): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    interface IMeshModifier {\r\n        ModifyMesh(verts: VertexHelper): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    class Outline extends Shadow implements IMeshModifier {\r\n        /*protected*/ constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Color, Vector2 } from \"UnityEngine\";\r\n    class Shadow extends BaseMeshEffect implements IMeshModifier {\r\n        /*protected*/ constructor()\r\n        effectColor: Color\r\n        effectDistance: Vector2\r\n        useGraphicAlpha: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    class PositionAsUV1 extends BaseMeshEffect implements IMeshModifier {\r\n        /*protected*/ constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { Vector2 } from \"UnityEngine\";\r\n    class AxisEventData extends BaseEventData {\r\n        constructor(eventSystem: EventSystem)\r\n        moveVector: Vector2\r\n        moveDir: MoveDirection\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { GameObject } from \"UnityEngine\";\r\n    class BaseEventData extends AbstractEventData {\r\n        constructor(eventSystem: EventSystem)\r\n        readonly currentInputModule: BaseInputModule\r\n        selectedObject: GameObject\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { Object } from \"System\";\r\n    abstract class AbstractEventData extends Object {\r\n        Reset(): void\r\n        Use(): void\r\n        readonly used: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { GameObject, Vector2, Camera } from \"UnityEngine\";\r\n    import { Object } from \"System\";\r\n    class PointerEventData extends BaseEventData {\r\n        constructor(eventSystem: EventSystem)\r\n        IsPointerMoving(): boolean\r\n        IsScrolling(): boolean\r\n        toString(): string\r\n        pointerEnter: GameObject\r\n        readonly lastPress: GameObject\r\n        rawPointerPress: GameObject\r\n        pointerDrag: GameObject\r\n        pointerClick: GameObject\r\n        pointerCurrentRaycast: RaycastResult\r\n        pointerPressRaycast: RaycastResult\r\n        eligibleForClick: boolean\r\n        pointerId: number\r\n        position: Vector2\r\n        delta: Vector2\r\n        pressPosition: Vector2\r\n        clickTime: number\r\n        clickCount: number\r\n        scrollDelta: Vector2\r\n        useDragThreshold: boolean\r\n        dragging: boolean\r\n        button: PointerEventData.InputButton\r\n        readonly enterEventCamera: Camera\r\n        readonly pressEventCamera: Camera\r\n        pointerPress: GameObject\r\n        hovered: any\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { Enum } from \"System\";\r\n    enum EventHandle {\r\n        Unused = 0,\r\n        Used = 1,\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface IEventSystemHandler {\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface IPointerEnterHandler extends IEventSystemHandler {\r\n        OnPointerEnter(eventData: PointerEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface IPointerExitHandler extends IEventSystemHandler {\r\n        OnPointerExit(eventData: PointerEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface IPointerDownHandler extends IEventSystemHandler {\r\n        OnPointerDown(eventData: PointerEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface IPointerUpHandler extends IEventSystemHandler {\r\n        OnPointerUp(eventData: PointerEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface IPointerClickHandler extends IEventSystemHandler {\r\n        OnPointerClick(eventData: PointerEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface IBeginDragHandler extends IEventSystemHandler {\r\n        OnBeginDrag(eventData: PointerEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface IInitializePotentialDragHandler extends IEventSystemHandler {\r\n        OnInitializePotentialDrag(eventData: PointerEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface IDragHandler extends IEventSystemHandler {\r\n        OnDrag(eventData: PointerEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface IEndDragHandler extends IEventSystemHandler {\r\n        OnEndDrag(eventData: PointerEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface IDropHandler extends IEventSystemHandler {\r\n        OnDrop(eventData: PointerEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface IScrollHandler extends IEventSystemHandler {\r\n        OnScroll(eventData: PointerEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface IUpdateSelectedHandler extends IEventSystemHandler {\r\n        OnUpdateSelected(eventData: BaseEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface ISelectHandler extends IEventSystemHandler {\r\n        OnSelect(eventData: BaseEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface IDeselectHandler extends IEventSystemHandler {\r\n        OnDeselect(eventData: BaseEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface IMoveHandler extends IEventSystemHandler {\r\n        OnMove(eventData: AxisEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface ISubmitHandler extends IEventSystemHandler {\r\n        OnSubmit(eventData: BaseEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    interface ICancelHandler extends IEventSystemHandler {\r\n        OnCancel(eventData: BaseEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { GameObject } from \"UnityEngine\";\r\n    import { Object } from \"System\";\r\n    class EventSystem extends UIBehaviour {\r\n        UpdateModules(): void\r\n        SetSelectedGameObject(selected: GameObject, pointer: BaseEventData): void\r\n        SetSelectedGameObject(selected: GameObject): void\r\n        RaycastAll(eventData: PointerEventData, raycastResults: any): void\r\n        IsPointerOverGameObject(pointerId: number): boolean\r\n        IsPointerOverGameObject(): boolean\r\n        toString(): string\r\n        /*protected*/ constructor()\r\n        static current: EventSystem\r\n        sendNavigationEvents: boolean\r\n        pixelDragThreshold: number\r\n        readonly currentInputModule: BaseInputModule\r\n        firstSelectedGameObject: GameObject\r\n        readonly currentSelectedGameObject: GameObject\r\n        readonly isFocused: boolean\r\n        readonly alreadySelecting: boolean\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { MonoBehaviour } from \"UnityEngine\";\r\n    import { Object } from \"System\";\r\n    class EventTrigger extends MonoBehaviour implements IInitializePotentialDragHandler, IDragHandler, IEndDragHandler, IDropHandler, IScrollHandler, IEventSystemHandler, IUpdateSelectedHandler, IPointerEnterHandler, ISelectHandler, IPointerExitHandler, IDeselectHandler, IPointerDownHandler, IMoveHandler, IPointerUpHandler, ISubmitHandler, IPointerClickHandler, ICancelHandler, IBeginDragHandler {\r\n        OnPointerEnter(eventData: PointerEventData): void\r\n        OnPointerExit(eventData: PointerEventData): void\r\n        OnDrag(eventData: PointerEventData): void\r\n        OnDrop(eventData: PointerEventData): void\r\n        OnPointerDown(eventData: PointerEventData): void\r\n        OnPointerUp(eventData: PointerEventData): void\r\n        OnPointerClick(eventData: PointerEventData): void\r\n        OnSelect(eventData: BaseEventData): void\r\n        OnDeselect(eventData: BaseEventData): void\r\n        OnScroll(eventData: PointerEventData): void\r\n        OnMove(eventData: AxisEventData): void\r\n        OnUpdateSelected(eventData: BaseEventData): void\r\n        OnInitializePotentialDrag(eventData: PointerEventData): void\r\n        OnBeginDrag(eventData: PointerEventData): void\r\n        OnEndDrag(eventData: PointerEventData): void\r\n        OnSubmit(eventData: BaseEventData): void\r\n        OnCancel(eventData: BaseEventData): void\r\n        /*protected*/ constructor()\r\n        triggers: any\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { Enum } from \"System\";\r\n    enum EventTriggerType {\r\n        PointerEnter = 0,\r\n        PointerExit = 1,\r\n        PointerDown = 2,\r\n        PointerUp = 3,\r\n        PointerClick = 4,\r\n        Drag = 5,\r\n        Drop = 6,\r\n        Scroll = 7,\r\n        UpdateSelected = 8,\r\n        Select = 9,\r\n        Deselect = 10,\r\n        Move = 11,\r\n        InitializePotentialDrag = 12,\r\n        BeginDrag = 13,\r\n        EndDrag = 14,\r\n        Submit = 15,\r\n        Cancel = 16,\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { Object } from \"System\";\r\n    abstract class ExecuteEvents extends Object {\r\n        static pointerEnterHandler(op: \"get\"): (handler: IPointerEnterHandler, eventData: BaseEventData) => void\r\n        static pointerExitHandler(op: \"get\"): (handler: IPointerExitHandler, eventData: BaseEventData) => void\r\n        static pointerDownHandler(op: \"get\"): (handler: IPointerDownHandler, eventData: BaseEventData) => void\r\n        static pointerUpHandler(op: \"get\"): (handler: IPointerUpHandler, eventData: BaseEventData) => void\r\n        static pointerClickHandler(op: \"get\"): (handler: IPointerClickHandler, eventData: BaseEventData) => void\r\n        static initializePotentialDrag(op: \"get\"): (handler: IInitializePotentialDragHandler, eventData: BaseEventData) => void\r\n        static beginDragHandler(op: \"get\"): (handler: IBeginDragHandler, eventData: BaseEventData) => void\r\n        static dragHandler(op: \"get\"): (handler: IDragHandler, eventData: BaseEventData) => void\r\n        static endDragHandler(op: \"get\"): (handler: IEndDragHandler, eventData: BaseEventData) => void\r\n        static dropHandler(op: \"get\"): (handler: IDropHandler, eventData: BaseEventData) => void\r\n        static scrollHandler(op: \"get\"): (handler: IScrollHandler, eventData: BaseEventData) => void\r\n        static updateSelectedHandler(op: \"get\"): (handler: IUpdateSelectedHandler, eventData: BaseEventData) => void\r\n        static selectHandler(op: \"get\"): (handler: ISelectHandler, eventData: BaseEventData) => void\r\n        static deselectHandler(op: \"get\"): (handler: IDeselectHandler, eventData: BaseEventData) => void\r\n        static moveHandler(op: \"get\"): (handler: IMoveHandler, eventData: BaseEventData) => void\r\n        static submitHandler(op: \"get\"): (handler: ISubmitHandler, eventData: BaseEventData) => void\r\n        static cancelHandler(op: \"get\"): (handler: ICancelHandler, eventData: BaseEventData) => void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { Enum, ValueType } from \"System\";\r\n    import { Vector2 } from \"UnityEngine\";\r\n    class BaseInput extends UIBehaviour {\r\n        constructor()\r\n        GetMouseButtonDown(button: number): boolean\r\n        GetMouseButtonUp(button: number): boolean\r\n        GetMouseButton(button: number): boolean\r\n        GetTouch(index: number): any\r\n        GetAxisRaw(axisName: string): number\r\n        GetButtonDown(buttonName: string): boolean\r\n        readonly compositionString: string\r\n        imeCompositionMode: any\r\n        compositionCursorPos: Vector2\r\n        readonly mousePresent: boolean\r\n        readonly mousePosition: Vector2\r\n        readonly mouseScrollDelta: Vector2\r\n        readonly touchSupported: boolean\r\n        readonly touchCount: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    abstract class BaseInputModule extends UIBehaviour {\r\n        Process(): void\r\n        IsPointerOverGameObject(pointerId: number): boolean\r\n        ShouldActivateModule(): boolean\r\n        DeactivateModule(): void\r\n        ActivateModule(): void\r\n        UpdateModule(): void\r\n        IsModuleSupported(): boolean\r\n        readonly input: BaseInput\r\n        inputOverride: BaseInput\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    abstract class PointerInputModule extends BaseInputModule {\r\n        IsPointerOverGameObject(pointerId: number): boolean\r\n        toString(): string\r\n        static readonly kMouseLeftId: number\r\n        static readonly kMouseRightId: number\r\n        static readonly kMouseMiddleId: number\r\n        static readonly kFakeTouchesId: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    class StandaloneInputModule extends PointerInputModule {\r\n        UpdateModule(): void\r\n        IsModuleSupported(): boolean\r\n        ShouldActivateModule(): boolean\r\n        ActivateModule(): void\r\n        DeactivateModule(): void\r\n        Process(): void\r\n        /*protected*/ constructor()\r\n        forceModuleActive: boolean\r\n        inputActionsPerSecond: number\r\n        repeatDelay: number\r\n        horizontalAxis: string\r\n        verticalAxis: string\r\n        submitButton: string\r\n        cancelButton: string\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { Enum } from \"System\";\r\n    enum MoveDirection {\r\n        Left = 0,\r\n        Up = 1,\r\n        Right = 2,\r\n        Down = 3,\r\n        None = 4,\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { ValueType } from \"System\";\r\n    import { Vector3, Vector2, GameObject } from \"UnityEngine\";\r\n    class RaycastResult extends ValueType {\r\n        constructor()\r\n        Clear(): void\r\n        toString(): string\r\n        gameObject: GameObject\r\n        readonly isValid: boolean\r\n        module_: BaseRaycaster\r\n        distance: number\r\n        index: number\r\n        depth: number\r\n        sortingLayer: number\r\n        sortingOrder: number\r\n        worldPosition: Vector3\r\n        worldNormal: Vector3\r\n        screenPosition: Vector2\r\n        displayIndex: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { Object } from \"System\";\r\n    class Physics2DRaycaster extends PhysicsRaycaster {\r\n        Raycast(eventData: PointerEventData, resultAppendList: any): void\r\n        /*protected*/ constructor()\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { Camera, LayerMask } from \"UnityEngine\";\r\n    import { Object } from \"System\";\r\n    class PhysicsRaycaster extends BaseRaycaster {\r\n        Raycast(eventData: PointerEventData, resultAppendList: any): void\r\n        /*protected*/ constructor()\r\n        readonly eventCamera: Camera\r\n        readonly depth: number\r\n        readonly finalEventMask: number\r\n        eventMask: LayerMask\r\n        maxRayIntersections: number\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UnityEvent } from \"UnityEngine.Events\";\r\n    namespace Button {\r\n        class ButtonClickedEvent extends UnityEvent {\r\n            constructor()\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.Events\" {\r\n    /** A zero argument persistent callback that can be saved with the Scene.\r\n     */\r\n    class UnityEvent extends UnityEventBase {\r\n        constructor()\r\n        /** Add a non persistent listener to the UnityEvent.\r\n         * @param call Callback function.\r\n         */\r\n        AddListener(call: () => void): void\r\n        /** Remove a non persistent listener from the UnityEvent.\r\n         * @param call Callback function.\r\n         */\r\n        RemoveListener(call: () => void): void\r\n        Invoke(): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.Events\" {\r\n    import * as jsb from \"jsb\";\r\n    import { Object, Array, Enum } from \"System\";\r\n    import { Object as Object1 } from \"UnityEngine\";\r\n    /** Abstract base class for UnityEvents.\r\n     */\r\n    abstract class UnityEventBase extends Object {\r\n        GetPersistentEventCount(): number\r\n        /** Get the target component of the listener at index index.\r\n         * @param index Index of the listener to query.\r\n         */\r\n        GetPersistentTarget(index: number): Object1\r\n        /** Get the target method name of the listener at index index.\r\n         * @param index Index of the listener to query.\r\n         */\r\n        GetPersistentMethodName(index: number): string\r\n        /** Modify the execution state of a persistent listener.\r\n         * @param index Index of the listener to query.\r\n         * @param state State to set.\r\n         */\r\n        SetPersistentListenerState(index: number, state: any): void\r\n        RemoveAllListeners(): void\r\n        toString(): string\r\n        /** Given an object, function name, and a list of argument types; find the method that matches.\r\n         * @param obj Object to search for the method.\r\n         * @param functionName Function name to search for.\r\n         * @param argumentTypes Argument types for the function.\r\n         */\r\n        static GetValidMethodInfo(obj: Object, functionName: string, argumentTypes: Array<any>): any\r\n        /** Given an object type, function name, and a list of argument types; find the method that matches.\r\n         * @param objectType Object type to search for the method.\r\n         * @param functionName Function name to search for.\r\n         * @param argumentTypes Argument types for the function.\r\n         */\r\n        static GetValidMethodInfo(objectType: any, functionName: string, argumentTypes: Array<any>): any\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import * as jsb from \"jsb\";\r\n    import { GameObject } from \"UnityEngine\";\r\n    import { Array, Object } from \"System\";\r\n    namespace DefaultControls {\r\n        interface IFactoryControls {\r\n            CreateGameObject(name: string, ...components: any[]): GameObject\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { ValueType } from \"System\";\r\n    import { Sprite } from \"UnityEngine\";\r\n    namespace DefaultControls {\r\n        class Resources extends ValueType {\r\n            constructor()\r\n            standard: Sprite\r\n            background: Sprite\r\n            inputField: Sprite\r\n            knob: Sprite\r\n            checkmark: Sprite\r\n            dropdown: Sprite\r\n            mask: Sprite\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Object } from \"System\";\r\n    import { Sprite } from \"UnityEngine\";\r\n    namespace Dropdown {\r\n        class OptionData extends Object {\r\n            constructor(text: string, image: Sprite)\r\n            constructor(text: string)\r\n            constructor(image: Sprite)\r\n            constructor()\r\n            text: string\r\n            image: Sprite\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Object } from \"System\";\r\n    namespace Dropdown {\r\n        class OptionDataList extends Object {\r\n            constructor()\r\n            options: any\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UnityEvent1, UnityEvent } from \"UnityEngine.Events\";\r\n    namespace Dropdown {\r\n        class DropdownEvent extends UnityEvent1<number> {\r\n            constructor()\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.Events\" {\r\n    class UnityEvent_Int32 extends UnityEventBase implements UnityEvent1<number> {\r\n        constructor()\r\n        AddListener(call: (id: number) => void): void\r\n        RemoveListener(call: (id: number) => void): void\r\n        Invoke(arg0: number): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.Events\" {\r\n    class UnityEvent1<T0> extends UnityEventBase {\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace GraphicRaycaster {\r\n        enum BlockingObjects {\r\n            None = 0,\r\n            TwoD = 1,\r\n            ThreeD = 2,\r\n            All = 3,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace Image {\r\n        enum Type {\r\n            Simple = 0,\r\n            Sliced = 1,\r\n            Tiled = 2,\r\n            Filled = 3,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace Image {\r\n        enum FillMethod {\r\n            Horizontal = 0,\r\n            Vertical = 1,\r\n            Radial90 = 2,\r\n            Radial180 = 3,\r\n            Radial360 = 4,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace Image {\r\n        enum OriginHorizontal {\r\n            Left = 0,\r\n            Right = 1,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace Image {\r\n        enum OriginVertical {\r\n            Bottom = 0,\r\n            Top = 1,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace Image {\r\n        enum Origin90 {\r\n            BottomLeft = 0,\r\n            TopLeft = 1,\r\n            TopRight = 2,\r\n            BottomRight = 3,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace Image {\r\n        enum Origin180 {\r\n            Bottom = 0,\r\n            Left = 1,\r\n            Top = 2,\r\n            Right = 3,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace Image {\r\n        enum Origin360 {\r\n            Bottom = 0,\r\n            Right = 1,\r\n            Top = 2,\r\n            Left = 3,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace InputField {\r\n        enum ContentType {\r\n            Standard = 0,\r\n            Autocorrected = 1,\r\n            IntegerNumber = 2,\r\n            DecimalNumber = 3,\r\n            Alphanumeric = 4,\r\n            Name = 5,\r\n            EmailAddress = 6,\r\n            Password = 7,\r\n            Pin = 8,\r\n            Custom = 9,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace InputField {\r\n        enum InputType {\r\n            Standard = 0,\r\n            AutoCorrect = 1,\r\n            Password = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace InputField {\r\n        enum CharacterValidation {\r\n            None = 0,\r\n            Integer = 1,\r\n            Decimal = 2,\r\n            Alphanumeric = 3,\r\n            Name = 4,\r\n            EmailAddress = 5,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace InputField {\r\n        enum LineType {\r\n            SingleLine = 0,\r\n            MultiLineSubmit = 1,\r\n            MultiLineNewline = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UnityEvent1, UnityEvent } from \"UnityEngine.Events\";\r\n    namespace InputField {\r\n        class SubmitEvent extends UnityEvent1<string> {\r\n            constructor()\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.Events\" {\r\n    class UnityEvent_String extends UnityEventBase implements UnityEvent1<string> {\r\n        constructor()\r\n        AddListener(call: (obj: string) => void): void\r\n        RemoveListener(call: (obj: string) => void): void\r\n        Invoke(arg0: string): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UnityEvent1, UnityEvent } from \"UnityEngine.Events\";\r\n    namespace InputField {\r\n        class OnChangeEvent extends UnityEvent1<string> {\r\n            constructor()\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace AspectRatioFitter {\r\n        enum AspectMode {\r\n            None = 0,\r\n            WidthControlsHeight = 1,\r\n            HeightControlsWidth = 2,\r\n            FitInParent = 3,\r\n            EnvelopeParent = 4,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace CanvasScaler {\r\n        enum ScaleMode {\r\n            ConstantPixelSize = 0,\r\n            ScaleWithScreenSize = 1,\r\n            ConstantPhysicalSize = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace CanvasScaler {\r\n        enum ScreenMatchMode {\r\n            MatchWidthOrHeight = 0,\r\n            Expand = 1,\r\n            Shrink = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace CanvasScaler {\r\n        enum Unit {\r\n            Centimeters = 0,\r\n            Millimeters = 1,\r\n            Inches = 2,\r\n            Points = 3,\r\n            Picas = 4,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace ContentSizeFitter {\r\n        enum FitMode {\r\n            Unconstrained = 0,\r\n            MinSize = 1,\r\n            PreferredSize = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace GridLayoutGroup {\r\n        enum Corner {\r\n            UpperLeft = 0,\r\n            UpperRight = 1,\r\n            LowerLeft = 2,\r\n            LowerRight = 3,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace GridLayoutGroup {\r\n        enum Axis {\r\n            Horizontal = 0,\r\n            Vertical = 1,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace GridLayoutGroup {\r\n        enum Constraint {\r\n            Flexible = 0,\r\n            FixedColumnCount = 1,\r\n            FixedRowCount = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UnityEvent1, UnityEvent } from \"UnityEngine.Events\";\r\n    namespace MaskableGraphic {\r\n        class CullStateChangedEvent extends UnityEvent1<boolean> {\r\n            constructor()\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.Events\" {\r\n    class UnityEvent_Boolean extends UnityEventBase implements UnityEvent1<boolean> {\r\n        constructor()\r\n        AddListener(call: (obj: boolean) => void): void\r\n        RemoveListener(call: (obj: boolean) => void): void\r\n        Invoke(arg0: boolean): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace Navigation {\r\n        enum Mode {\r\n            None = 0,\r\n            Horizontal = 1,\r\n            Vertical = 2,\r\n            Automatic = 3,\r\n            Explicit = 4,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace ScrollRect {\r\n        enum MovementType {\r\n            Unrestricted = 0,\r\n            Elastic = 1,\r\n            Clamped = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace ScrollRect {\r\n        enum ScrollbarVisibility {\r\n            Permanent = 0,\r\n            AutoHide = 1,\r\n            AutoHideAndExpandViewport = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Vector2 } from \"UnityEngine\";\r\n    import { UnityEvent1, UnityEvent } from \"UnityEngine.Events\";\r\n    namespace ScrollRect {\r\n        class ScrollRectEvent extends UnityEvent1<Vector2> {\r\n            constructor()\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.Events\" {\r\n    import { Vector2 } from \"UnityEngine\";\r\n    class UnityEvent_Vector2 extends UnityEventBase implements UnityEvent1<Vector2> {\r\n        constructor()\r\n        AddListener(call: (arg0: Vector2) => void): void\r\n        RemoveListener(call: (arg0: Vector2) => void): void\r\n        Invoke(arg0: Vector2): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace Scrollbar {\r\n        enum Direction {\r\n            LeftToRight = 0,\r\n            RightToLeft = 1,\r\n            BottomToTop = 2,\r\n            TopToBottom = 3,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UnityEvent1, UnityEvent } from \"UnityEngine.Events\";\r\n    namespace Scrollbar {\r\n        class ScrollEvent extends UnityEvent1<number> {\r\n            constructor()\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.Events\" {\r\n    class UnityEvent_Single extends UnityEventBase implements UnityEvent1<number> {\r\n        constructor()\r\n        AddListener(call: (arg0: number) => void): void\r\n        RemoveListener(call: (arg0: number) => void): void\r\n        Invoke(arg0: number): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace Selectable {\r\n        enum Transition {\r\n            None = 0,\r\n            ColorTint = 1,\r\n            SpriteSwap = 2,\r\n            Animation = 3,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace Slider {\r\n        enum Direction {\r\n            LeftToRight = 0,\r\n            RightToLeft = 1,\r\n            BottomToTop = 2,\r\n            TopToBottom = 3,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UnityEvent1, UnityEvent } from \"UnityEngine.Events\";\r\n    namespace Slider {\r\n        class SliderEvent extends UnityEvent1<number> {\r\n            constructor()\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { Enum } from \"System\";\r\n    namespace Toggle {\r\n        enum ToggleTransition {\r\n            None = 0,\r\n            Fade = 1,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.UI\" {\r\n    import { UnityEvent1, UnityEvent } from \"UnityEngine.Events\";\r\n    namespace Toggle {\r\n        class ToggleEvent extends UnityEvent1<boolean> {\r\n            constructor()\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { Enum } from \"System\";\r\n    namespace PointerEventData {\r\n        enum InputButton {\r\n            Left = 0,\r\n            Right = 1,\r\n            Middle = 2,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { Enum } from \"System\";\r\n    namespace PointerEventData {\r\n        enum FramePressState {\r\n            Pressed = 0,\r\n            Released = 1,\r\n            PressedAndReleased = 2,\r\n            NotChanged = 3,\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { UnityEvent1, UnityEvent } from \"UnityEngine.Events\";\r\n    namespace EventTrigger {\r\n        class TriggerEvent extends UnityEvent1<BaseEventData> {\r\n            constructor()\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.Events\" {\r\n    import { BaseEventData } from \"UnityEngine.EventSystems\";\r\n    class UnityEvent_BaseEventData extends UnityEventBase implements UnityEvent1<BaseEventData> {\r\n        constructor()\r\n        AddListener(call: (arg0: BaseEventData) => void): void\r\n        RemoveListener(call: (arg0: BaseEventData) => void): void\r\n        Invoke(arg0: BaseEventData): void\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { Object } from \"System\";\r\n    namespace EventTrigger {\r\n        class Entry extends Object {\r\n            constructor()\r\n            eventID: EventTriggerType\r\n            callback: EventTrigger.TriggerEvent\r\n        }\r\n    }\r\n}\r\ndeclare module \"UnityEngine.EventSystems\" {\r\n    import { Object } from \"System\";\r\n    namespace PointerInputModule {\r\n        class MouseButtonEventData extends Object {\r\n            constructor()\r\n            PressedThisFrame(): boolean\r\n            ReleasedThisFrame(): boolean\r\n            buttonState: PointerEventData.FramePressState\r\n            buttonData: PointerEventData\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/Generated/Typings/jsb.autogen.d.ts.meta",
    "content": "fileFormatVersion: 2\nguid: 3a6576832826bc54ab80a18593fb0815\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Generated/Typings.meta",
    "content": "fileFormatVersion: 2\nguid: 35f57790ebd959d489fa3c5af2ab56f0\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/Generated.meta",
    "content": "fileFormatVersion: 2\nguid: e64bc635c754fbd47991c7226fc02711\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Assets/jsb-extra/MiniConsole/MiniConsole.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Threading;\r\n\r\nnamespace QuickJS.Extra\r\n{\r\n    using UnityEngine;\r\n    using UnityEngine.UI;\r\n\r\n    public class MiniConsole : Diagnostics.ILogWriter, ILogHandler\r\n    {\r\n        private bool _loopCheck;\r\n        private int _mainThreadId;\r\n        private int _maxLines = 50;\r\n        private ILogHandler _defaultHandler;\r\n\r\n        public Text textTemplate;\r\n        public ScrollRect scrollRect;\r\n\r\n        private List<Text> _lines = new List<Text>();\r\n\r\n        public MiniConsole(ScrollRect scrollRect, Text textTemplate, int maxLines)\r\n        {\r\n            this._mainThreadId = Thread.CurrentThread.ManagedThreadId;\r\n            this._maxLines = maxLines;\r\n            this.scrollRect = scrollRect;\r\n            this.textTemplate = textTemplate;\r\n            textTemplate.gameObject.SetActive(false);\r\n\r\n            _defaultHandler = Debug.unityLogger.logHandler;\r\n            Debug.unityLogger.logHandler = this;\r\n            Diagnostics.Logger.writer = this;\r\n        }\r\n\r\n        private void NewEntry(string text, Color color)\r\n        {\r\n            if (_mainThreadId != Thread.CurrentThread.ManagedThreadId)\r\n            {\r\n                return;\r\n            }\r\n\r\n            if (scrollRect == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                if (text.Length > 503)\r\n                {\r\n                    text = text.Substring(0, 500) + \"...\";\r\n                }\r\n                if (_lines.Count > _maxLines)\r\n                {\r\n                    var textInst = _lines[0];\r\n                    _lines.RemoveAt(0);\r\n                    textInst.text = text;\r\n                    textInst.color = color;\r\n                    textInst.transform.SetSiblingIndex(textInst.transform.parent.childCount - 1);\r\n                    _lines.Add(textInst);\r\n                    LayoutRebuilder.ForceRebuildLayoutImmediate(textInst.transform.parent.GetComponent<RectTransform>());\r\n                }\r\n                else\r\n                {\r\n                    var textInst = Object.Instantiate(textTemplate);\r\n                    textInst.text = text;\r\n                    textInst.color = color;\r\n                    textInst.transform.SetParent(textTemplate.transform.parent);\r\n                    textInst.gameObject.SetActive(true);\r\n                    _lines.Add(textInst);\r\n                    LayoutRebuilder.ForceRebuildLayoutImmediate(textInst.transform.parent.GetComponent<RectTransform>());\r\n                }\r\n            }\r\n            catch (Exception)\r\n            {\r\n            }\r\n        }\r\n\r\n        private void LogError(string text)\r\n        {\r\n            if (_loopCheck)\r\n            {\r\n                return;\r\n            }\r\n\r\n            _loopCheck = true;\r\n            _defaultHandler.LogFormat(LogType.Error, null, \"{0}\", text);\r\n            NewEntry(text, Color.red);\r\n            _loopCheck = false;\r\n        }\r\n\r\n        private void LogException(Exception exception)\r\n        {\r\n            if (_loopCheck)\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                _loopCheck = true;\r\n                var text = exception.ToString();\r\n                _defaultHandler.LogFormat(LogType.Error, null, \"{0}\\nStacktrack:{1}\", text, exception.StackTrace);\r\n                if (exception.InnerException != null)\r\n                {\r\n                    _defaultHandler.LogFormat(LogType.Error, null, \"InnerException: {0}\\nStacktrack:{1}\", exception.InnerException, exception.InnerException.StackTrace);\r\n                }\r\n                NewEntry(text, Color.cyan);\r\n            }\r\n            catch (Exception)\r\n            {\r\n            }\r\n            finally\r\n            {\r\n                _loopCheck = false;\r\n            }\r\n        }\r\n\r\n        private void LogException(string text)\r\n        {\r\n            if (_loopCheck)\r\n            {\r\n                return;\r\n            }\r\n\r\n            _loopCheck = true;\r\n            _defaultHandler.LogFormat(LogType.Error, null, \"{0}\", text);\r\n            NewEntry(text, Color.cyan);\r\n            _loopCheck = false;\r\n        }\r\n\r\n        private void Log(string text)\r\n        {\r\n            if (_loopCheck)\r\n            {\r\n                return;\r\n            }\r\n\r\n            _loopCheck = true;\r\n            _defaultHandler.LogFormat(LogType.Log, null, \"{0}\", text);\r\n            NewEntry(text, Color.white);\r\n            _loopCheck = false;\r\n        }\r\n\r\n        private void LogWarning(string text)\r\n        {\r\n            if (_loopCheck)\r\n            {\r\n                return;\r\n            }\r\n\r\n            _loopCheck = true;\r\n            _defaultHandler.LogFormat(LogType.Warning, null, \"{0}\", text);\r\n            NewEntry(text, Color.yellow);\r\n            _loopCheck = false;\r\n        }\r\n\r\n        private void LogErrorFormat(string fmt, object[] args)\r\n        {\r\n            LogError(string.Format(fmt, args));\r\n        }\r\n\r\n        private void LogWarningFormat(string fmt, object[] args)\r\n        {\r\n            LogWarning(string.Format(fmt, args));\r\n        }\r\n\r\n        private void LogFormat(string fmt, object[] args)\r\n        {\r\n            Log(string.Format(fmt, args));\r\n        }\r\n\r\n        void Diagnostics.ILogWriter.Write(QuickJS.Diagnostics.ELogSeverity severity, string channel, string fmt, object[] args)\r\n        {\r\n            switch (severity)\r\n            {\r\n                case QuickJS.Diagnostics.ELogSeverity.VeryVerbose:\r\n                case QuickJS.Diagnostics.ELogSeverity.Verbose: \r\n                case QuickJS.Diagnostics.ELogSeverity.Debug: \r\n                case QuickJS.Diagnostics.ELogSeverity.Info: LogFormat(fmt, args); break;\r\n                case QuickJS.Diagnostics.ELogSeverity.Warning: LogWarningFormat(fmt, args); break;\r\n                case QuickJS.Diagnostics.ELogSeverity.Error: \r\n                case QuickJS.Diagnostics.ELogSeverity.Fatal: \r\n                default: LogErrorFormat(fmt, args); break;\r\n            }\r\n        }\r\n\r\n        void Diagnostics.ILogWriter.Write(QuickJS.Diagnostics.ELogSeverity severity, string channel, string text)\r\n        {\r\n            switch (severity)\r\n            {\r\n                case QuickJS.Diagnostics.ELogSeverity.VeryVerbose:\r\n                case QuickJS.Diagnostics.ELogSeverity.Verbose: \r\n                case QuickJS.Diagnostics.ELogSeverity.Debug: \r\n                case QuickJS.Diagnostics.ELogSeverity.Info: Log(text); break;\r\n                case QuickJS.Diagnostics.ELogSeverity.Warning: LogWarning(text); break;\r\n                case QuickJS.Diagnostics.ELogSeverity.Error: \r\n                case QuickJS.Diagnostics.ELogSeverity.Fatal: \r\n                default: LogError(text); break;\r\n            }\r\n        }\r\n\r\n        void ILogHandler.LogException(Exception exception, Object context)\r\n        {\r\n            LogException(exception);\r\n        }\r\n\r\n        void ILogHandler.LogFormat(LogType logType, Object context, string format, params object[] args)\r\n        {\r\n            switch (logType)\r\n            {\r\n                case LogType.Log: LogFormat(format, args); break;\r\n                case LogType.Warning: LogWarningFormat(format, args); break;\r\n                case LogType.Error: LogErrorFormat(format, args); break;\r\n                case LogType.Exception: LogException(string.Format(format, args)); break;\r\n                case LogType.Assert: \r\n                default: LogException(string.Format(format, args)); break;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/jsb-extra/MiniConsole/MiniConsole.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 9c0b65dd1eb97da4eb8f93bc23d475aa\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/MiniConsole.meta",
    "content": "fileFormatVersion: 2\r\nguid: 5184b47bcda33284b9202b97f80ed207\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Examples/SqliteStarter.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Net;\r\nusing System.Net.Sockets;\r\nusing System.Threading;\r\nusing System.Text;\r\n\r\nnamespace QuickJS.Extra.Sqlite\r\n{\r\n    using Native;\r\n    using UnityEngine;\r\n\r\n    public class SqliteStarter : MonoBehaviour\r\n    {\r\n        void Awake()\r\n        {\r\n            Debug.LogFormat(\"sqlite3_libversion_number: {0}\", SqliteApi.sqlite3_libversion_number());\r\n            sqlite3 db;\r\n            Debug.LogFormat(\"open: {0}\", SqliteApi.sqlite3_open(\"test.sqlite\", out db));\r\n\r\n            sqlite3_stmt stmt;\r\n            SqliteApi.sqlite3_prepare_v3(db, \"select * from test;\", out stmt);\r\n            while (SqliteApi.sqlite3_step(stmt) == ResultCode.ROW)\r\n            {\r\n                var id = SqliteApi.sqlite3_column_int(stmt, 0);\r\n                var text = SqliteApi.sqlite3_column_text(stmt, 1);\r\n                Debug.LogFormat(\"select: {0} = {1}\", id, text);\r\n            }\r\n            SqliteApi.sqlite3_finalize(stmt);\r\n\r\n            Debug.LogFormat(\"insert: {0}\", SqliteApi.sqlite3_exec(db, \"INSERT INTO \\\"main\\\".\\\"test\\\" (\\\"name\\\") VALUES (\\\"gogogogogo\\\")\"));\r\n            Debug.LogFormat(\"close: {0}\", SqliteApi.sqlite3_close(db));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Examples/SqliteStarter.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 3036777de0855f643a0f24f4f6fa6089\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Examples/sqlite_test.unity",
    "content": "%YAML 1.1\r\n%TAG !u! tag:unity3d.com,2011:\r\n--- !u!29 &1\r\nOcclusionCullingSettings:\r\n  m_ObjectHideFlags: 0\r\n  serializedVersion: 2\r\n  m_OcclusionBakeSettings:\r\n    smallestOccluder: 5\r\n    smallestHole: 0.25\r\n    backfaceThreshold: 100\r\n  m_SceneGUID: 00000000000000000000000000000000\r\n  m_OcclusionCullingData: {fileID: 0}\r\n--- !u!104 &2\r\nRenderSettings:\r\n  m_ObjectHideFlags: 0\r\n  serializedVersion: 9\r\n  m_Fog: 0\r\n  m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1}\r\n  m_FogMode: 3\r\n  m_FogDensity: 0.01\r\n  m_LinearFogStart: 0\r\n  m_LinearFogEnd: 300\r\n  m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1}\r\n  m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1}\r\n  m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1}\r\n  m_AmbientIntensity: 1\r\n  m_AmbientMode: 0\r\n  m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1}\r\n  m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0}\r\n  m_HaloStrength: 0.5\r\n  m_FlareStrength: 1\r\n  m_FlareFadeSpeed: 3\r\n  m_HaloTexture: {fileID: 0}\r\n  m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0}\r\n  m_DefaultReflectionMode: 0\r\n  m_DefaultReflectionResolution: 128\r\n  m_ReflectionBounces: 1\r\n  m_ReflectionIntensity: 1\r\n  m_CustomReflection: {fileID: 0}\r\n  m_Sun: {fileID: 0}\r\n  m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1}\r\n  m_UseRadianceAmbientProbe: 0\r\n--- !u!157 &3\r\nLightmapSettings:\r\n  m_ObjectHideFlags: 0\r\n  serializedVersion: 11\r\n  m_GIWorkflowMode: 1\r\n  m_GISettings:\r\n    serializedVersion: 2\r\n    m_BounceScale: 1\r\n    m_IndirectOutputScale: 1\r\n    m_AlbedoBoost: 1\r\n    m_EnvironmentLightingMode: 0\r\n    m_EnableBakedLightmaps: 1\r\n    m_EnableRealtimeLightmaps: 1\r\n  m_LightmapEditorSettings:\r\n    serializedVersion: 12\r\n    m_Resolution: 2\r\n    m_BakeResolution: 40\r\n    m_AtlasSize: 1024\r\n    m_AO: 0\r\n    m_AOMaxDistance: 1\r\n    m_CompAOExponent: 1\r\n    m_CompAOExponentDirect: 0\r\n    m_ExtractAmbientOcclusion: 0\r\n    m_Padding: 2\r\n    m_LightmapParameters: {fileID: 0}\r\n    m_LightmapsBakeMode: 1\r\n    m_TextureCompression: 1\r\n    m_FinalGather: 0\r\n    m_FinalGatherFiltering: 1\r\n    m_FinalGatherRayCount: 256\r\n    m_ReflectionCompression: 2\r\n    m_MixedBakeMode: 2\r\n    m_BakeBackend: 1\r\n    m_PVRSampling: 1\r\n    m_PVRDirectSampleCount: 32\r\n    m_PVRSampleCount: 512\r\n    m_PVRBounces: 2\r\n    m_PVREnvironmentSampleCount: 256\r\n    m_PVREnvironmentReferencePointCount: 2048\r\n    m_PVRFilteringMode: 1\r\n    m_PVRDenoiserTypeDirect: 1\r\n    m_PVRDenoiserTypeIndirect: 1\r\n    m_PVRDenoiserTypeAO: 1\r\n    m_PVRFilterTypeDirect: 0\r\n    m_PVRFilterTypeIndirect: 0\r\n    m_PVRFilterTypeAO: 0\r\n    m_PVREnvironmentMIS: 1\r\n    m_PVRCulling: 1\r\n    m_PVRFilteringGaussRadiusDirect: 1\r\n    m_PVRFilteringGaussRadiusIndirect: 5\r\n    m_PVRFilteringGaussRadiusAO: 2\r\n    m_PVRFilteringAtrousPositionSigmaDirect: 0.5\r\n    m_PVRFilteringAtrousPositionSigmaIndirect: 2\r\n    m_PVRFilteringAtrousPositionSigmaAO: 1\r\n    m_ShowResolutionOverlay: 1\r\n    m_ExportTrainingData: 0\r\n  m_LightingDataAsset: {fileID: 0}\r\n  m_UseShadowmask: 1\r\n--- !u!196 &4\r\nNavMeshSettings:\r\n  serializedVersion: 2\r\n  m_ObjectHideFlags: 0\r\n  m_BuildSettings:\r\n    serializedVersion: 2\r\n    agentTypeID: 0\r\n    agentRadius: 0.5\r\n    agentHeight: 2\r\n    agentSlope: 45\r\n    agentClimb: 0.4\r\n    ledgeDropHeight: 0\r\n    maxJumpAcrossDistance: 0\r\n    minRegionArea: 2\r\n    manualCellSize: 0\r\n    cellSize: 0.16666667\r\n    manualTileSize: 0\r\n    tileSize: 256\r\n    accuratePlacement: 0\r\n    debug:\r\n      m_Flags: 0\r\n  m_NavMeshData: {fileID: 0}\r\n--- !u!1 &1379752462\r\nGameObject:\r\n  m_ObjectHideFlags: 0\r\n  m_CorrespondingSourceObject: {fileID: 0}\r\n  m_PrefabInstance: {fileID: 0}\r\n  m_PrefabAsset: {fileID: 0}\r\n  serializedVersion: 6\r\n  m_Component:\r\n  - component: {fileID: 1379752466}\r\n  - component: {fileID: 1379752465}\r\n  - component: {fileID: 1379752464}\r\n  - component: {fileID: 1379752463}\r\n  m_Layer: 0\r\n  m_Name: Main Camera\r\n  m_TagString: MainCamera\r\n  m_Icon: {fileID: 0}\r\n  m_NavMeshLayer: 0\r\n  m_StaticEditorFlags: 0\r\n  m_IsActive: 1\r\n--- !u!114 &1379752463\r\nMonoBehaviour:\r\n  m_ObjectHideFlags: 0\r\n  m_CorrespondingSourceObject: {fileID: 0}\r\n  m_PrefabInstance: {fileID: 0}\r\n  m_PrefabAsset: {fileID: 0}\r\n  m_GameObject: {fileID: 1379752462}\r\n  m_Enabled: 1\r\n  m_EditorHideFlags: 0\r\n  m_Script: {fileID: 11500000, guid: 3036777de0855f643a0f24f4f6fa6089, type: 3}\r\n  m_Name: \r\n  m_EditorClassIdentifier: \r\n--- !u!81 &1379752464\r\nAudioListener:\r\n  m_ObjectHideFlags: 0\r\n  m_CorrespondingSourceObject: {fileID: 0}\r\n  m_PrefabInstance: {fileID: 0}\r\n  m_PrefabAsset: {fileID: 0}\r\n  m_GameObject: {fileID: 1379752462}\r\n  m_Enabled: 1\r\n--- !u!20 &1379752465\r\nCamera:\r\n  m_ObjectHideFlags: 0\r\n  m_CorrespondingSourceObject: {fileID: 0}\r\n  m_PrefabInstance: {fileID: 0}\r\n  m_PrefabAsset: {fileID: 0}\r\n  m_GameObject: {fileID: 1379752462}\r\n  m_Enabled: 1\r\n  serializedVersion: 2\r\n  m_ClearFlags: 1\r\n  m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0}\r\n  m_projectionMatrixMode: 1\r\n  m_GateFitMode: 2\r\n  m_FOVAxisMode: 0\r\n  m_SensorSize: {x: 36, y: 24}\r\n  m_LensShift: {x: 0, y: 0}\r\n  m_FocalLength: 50\r\n  m_NormalizedViewPortRect:\r\n    serializedVersion: 2\r\n    x: 0\r\n    y: 0\r\n    width: 1\r\n    height: 1\r\n  near clip plane: 0.3\r\n  far clip plane: 1000\r\n  field of view: 60\r\n  orthographic: 0\r\n  orthographic size: 5\r\n  m_Depth: -1\r\n  m_CullingMask:\r\n    serializedVersion: 2\r\n    m_Bits: 4294967295\r\n  m_RenderingPath: -1\r\n  m_TargetTexture: {fileID: 0}\r\n  m_TargetDisplay: 0\r\n  m_TargetEye: 3\r\n  m_HDR: 1\r\n  m_AllowMSAA: 1\r\n  m_AllowDynamicResolution: 0\r\n  m_ForceIntoRT: 0\r\n  m_OcclusionCulling: 1\r\n  m_StereoConvergence: 10\r\n  m_StereoSeparation: 0.022\r\n--- !u!4 &1379752466\r\nTransform:\r\n  m_ObjectHideFlags: 0\r\n  m_CorrespondingSourceObject: {fileID: 0}\r\n  m_PrefabInstance: {fileID: 0}\r\n  m_PrefabAsset: {fileID: 0}\r\n  m_GameObject: {fileID: 1379752462}\r\n  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}\r\n  m_LocalPosition: {x: 0, y: 1, z: -10}\r\n  m_LocalScale: {x: 1, y: 1, z: 1}\r\n  m_Children: []\r\n  m_Father: {fileID: 0}\r\n  m_RootOrder: 0\r\n  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}\r\n--- !u!1 &1526603654\r\nGameObject:\r\n  m_ObjectHideFlags: 0\r\n  m_CorrespondingSourceObject: {fileID: 0}\r\n  m_PrefabInstance: {fileID: 0}\r\n  m_PrefabAsset: {fileID: 0}\r\n  serializedVersion: 6\r\n  m_Component:\r\n  - component: {fileID: 1526603656}\r\n  - component: {fileID: 1526603655}\r\n  m_Layer: 0\r\n  m_Name: Directional Light\r\n  m_TagString: Untagged\r\n  m_Icon: {fileID: 0}\r\n  m_NavMeshLayer: 0\r\n  m_StaticEditorFlags: 0\r\n  m_IsActive: 1\r\n--- !u!108 &1526603655\r\nLight:\r\n  m_ObjectHideFlags: 0\r\n  m_CorrespondingSourceObject: {fileID: 0}\r\n  m_PrefabInstance: {fileID: 0}\r\n  m_PrefabAsset: {fileID: 0}\r\n  m_GameObject: {fileID: 1526603654}\r\n  m_Enabled: 1\r\n  serializedVersion: 9\r\n  m_Type: 1\r\n  m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1}\r\n  m_Intensity: 1\r\n  m_Range: 10\r\n  m_SpotAngle: 30\r\n  m_InnerSpotAngle: 21.80208\r\n  m_CookieSize: 10\r\n  m_Shadows:\r\n    m_Type: 2\r\n    m_Resolution: -1\r\n    m_CustomResolution: -1\r\n    m_Strength: 1\r\n    m_Bias: 0.05\r\n    m_NormalBias: 0.4\r\n    m_NearPlane: 0.2\r\n    m_CullingMatrixOverride:\r\n      e00: 1\r\n      e01: 0\r\n      e02: 0\r\n      e03: 0\r\n      e10: 0\r\n      e11: 1\r\n      e12: 0\r\n      e13: 0\r\n      e20: 0\r\n      e21: 0\r\n      e22: 1\r\n      e23: 0\r\n      e30: 0\r\n      e31: 0\r\n      e32: 0\r\n      e33: 1\r\n    m_UseCullingMatrixOverride: 0\r\n  m_Cookie: {fileID: 0}\r\n  m_DrawHalo: 0\r\n  m_Flare: {fileID: 0}\r\n  m_RenderMode: 0\r\n  m_CullingMask:\r\n    serializedVersion: 2\r\n    m_Bits: 4294967295\r\n  m_RenderingLayerMask: 1\r\n  m_Lightmapping: 4\r\n  m_LightShadowCasterMode: 0\r\n  m_AreaSize: {x: 1, y: 1}\r\n  m_BounceIntensity: 1\r\n  m_ColorTemperature: 6570\r\n  m_UseColorTemperature: 0\r\n  m_BoundingSphereOverride: {x: 0, y: 0, z: 0, w: 0}\r\n  m_UseBoundingSphereOverride: 0\r\n  m_ShadowRadius: 0\r\n  m_ShadowAngle: 0\r\n--- !u!4 &1526603656\r\nTransform:\r\n  m_ObjectHideFlags: 0\r\n  m_CorrespondingSourceObject: {fileID: 0}\r\n  m_PrefabInstance: {fileID: 0}\r\n  m_PrefabAsset: {fileID: 0}\r\n  m_GameObject: {fileID: 1526603654}\r\n  m_LocalRotation: {x: 0.40821788, y: -0.23456968, z: 0.10938163, w: 0.8754261}\r\n  m_LocalPosition: {x: 0, y: 3, z: 0}\r\n  m_LocalScale: {x: 1, y: 1, z: 1}\r\n  m_Children: []\r\n  m_Father: {fileID: 0}\r\n  m_RootOrder: 1\r\n  m_LocalEulerAnglesHint: {x: 50, y: -30, z: 0}\r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Examples/sqlite_test.unity.meta",
    "content": "fileFormatVersion: 2\r\nguid: 40298fe628d95c64ba20e61218a29813\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Examples.meta",
    "content": "fileFormatVersion: 2\r\nguid: db363a727a212f94396e8fc1dc749cc7\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Plugins/x64/sqlite3.dll.meta",
    "content": "fileFormatVersion: 2\r\nguid: cdcc4227744ec9142bf3c8ce91ff66eb\r\nPluginImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  iconMap: {}\r\n  executionOrder: {}\r\n  defineConstraints: []\r\n  isPreloaded: 0\r\n  isOverridable: 0\r\n  isExplicitlyReferenced: 0\r\n  validateReferences: 1\r\n  platformData:\r\n  - first:\r\n      '': Any\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        Exclude Android: 1\r\n        Exclude Editor: 0\r\n        Exclude Linux: 0\r\n        Exclude Linux64: 0\r\n        Exclude LinuxUniversal: 0\r\n        Exclude OSXUniversal: 0\r\n        Exclude WebGL: 1\r\n        Exclude Win: 0\r\n        Exclude Win64: 0\r\n        Exclude iOS: 1\r\n  - first:\r\n      Android: Android\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: ARMv7\r\n  - first:\r\n      Any: \r\n    second:\r\n      enabled: 0\r\n      settings: {}\r\n  - first:\r\n      Editor: Editor\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86_64\r\n        DefaultValueInitialized: true\r\n        OS: AnyOS\r\n  - first:\r\n      Facebook: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Facebook: Win64\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Linux\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: Linux64\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86_64\r\n  - first:\r\n      Standalone: LinuxUniversal\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86_64\r\n  - first:\r\n      Standalone: OSXUniversal\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86_64\r\n  - first:\r\n      Standalone: Win\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: Win64\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      iPhone: iOS\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        AddToEmbeddedBinaries: false\r\n        CompileFlags: \r\n        FrameworkDependencies: \r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Plugins/x64.meta",
    "content": "fileFormatVersion: 2\r\nguid: 1a68065b742a72740872d228560e5e47\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Plugins.meta",
    "content": "fileFormatVersion: 2\r\nguid: b9a9a5d70e0ff2048b3ca1377f869d1f\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native/ResultCode.cs",
    "content": "using System;\r\nusing System.Text;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Extra.Sqlite.Native\r\n{\r\n    /*\r\n    ** CAPI3REF: Result Codes\r\n    ** KEYWORDS: {result code definitions}\r\n    **\r\n    ** Many SQLite functions return an integer result code from the set shown\r\n    ** here in order to indicate success or failure.\r\n    **\r\n    ** New error codes may be added in future versions of SQLite.\r\n    **\r\n    ** See also: [extended result code definitions]\r\n    */\r\n    public enum ResultCode : int\r\n    {\r\n        OK = 0,   /* Successful result */\r\n        /* beginning-of-error-codes */\r\n        ERROR = 1,   /* Generic error */\r\n        INTERNAL = 2,   /* Internal logic error in SQLite */\r\n        PERM = 3,   /* Access permission denied */\r\n        ABORT = 4,   /* Callback routine requested an abort */\r\n        BUSY = 5,   /* The database file is locked */\r\n        LOCKED = 6,   /* A table in the database is locked */\r\n        NOMEM = 7,   /* A malloc() failed */\r\n        READONLY = 8,   /* Attempt to write a readonly database */\r\n        INTERRUPT = 9,   /* Operation terminated by sqlite3_interrupt()*/\r\n        IOERR = 10,   /* Some kind of disk I/O error occurred */\r\n        CORRUPT = 11,   /* The database disk image is malformed */\r\n        NOTFOUND = 12,   /* Unknown opcode in sqlite3_file_control() */\r\n        FULL = 13,   /* Insertion failed because database is full */\r\n        CANTOPEN = 14,   /* Unable to open the database file */\r\n        PROTOCOL = 15,   /* Database lock protocol error */\r\n        EMPTY = 16,   /* Internal use only */\r\n        SCHEMA = 17,   /* The database schema changed */\r\n        TOOBIG = 18,   /* String or BLOB exceeds size limit */\r\n        CONSTRAINT = 19,   /* Abort due to constraint violation */\r\n        MISMATCH = 20,   /* Data type mismatch */\r\n        MISUSE = 21,   /* Library used incorrectly */\r\n        NOLFS = 22,   /* Uses OS features not supported on host */\r\n        AUTH = 23,   /* Authorization denied */\r\n        FORMAT = 24,   /* Not used */\r\n        RANGE = 25,   /* 2nd parameter to sqlite3_bind out of range */\r\n        NOTADB = 26,   /* File opened that is not a database file */\r\n        NOTICE = 27,   /* Notifications from sqlite3_log() */\r\n        WARNING = 28,   /* Warnings from sqlite3_log() */\r\n        ROW = 100,  /* sqlite3_step() has another row ready */\r\n        DONE = 101,  /* sqlite3_step() has finished executing */\r\n        /* end-of-error-codes */\r\n\r\n        /*\r\n        ** CAPI3REF: Extended Result Codes\r\n        ** KEYWORDS: {extended result code definitions}\r\n        **\r\n        ** In its default configuration, SQLite API routines return one of 30 integer\r\n        ** [result codes].  However, experience has shown that many of\r\n        ** these result codes are too coarse-grained.  They do not provide as\r\n        ** much information about problems as programmers might like.  In an effort to\r\n        ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]\r\n        ** and later) include\r\n        ** support for additional result codes that provide more detailed information\r\n        ** about errors. These [extended result codes] are enabled or disabled\r\n        ** on a per database connection basis using the\r\n        ** [sqlite3_extended_result_codes()] API.  Or, the extended code for\r\n        ** the most recent error can be obtained using\r\n        ** [sqlite3_extended_errcode()].\r\n        */\r\n        ERROR_MISSING_COLLSEQ = (ERROR | (1 << 8)),\r\n        ERROR_RETRY = (ERROR | (2 << 8)),\r\n        ERROR_SNAPSHOT = (ERROR | (3 << 8)),\r\n        IOERR_READ = (IOERR | (1 << 8)),\r\n        IOERR_SHORT_READ = (IOERR | (2 << 8)),\r\n        IOERR_WRITE = (IOERR | (3 << 8)),\r\n        IOERR_FSYNC = (IOERR | (4 << 8)),\r\n        IOERR_DIR_FSYNC = (IOERR | (5 << 8)),\r\n        IOERR_TRUNCATE = (IOERR | (6 << 8)),\r\n        IOERR_FSTAT = (IOERR | (7 << 8)),\r\n        IOERR_UNLOCK = (IOERR | (8 << 8)),\r\n        IOERR_RDLOCK = (IOERR | (9 << 8)),\r\n        IOERR_DELETE = (IOERR | (10 << 8)),\r\n        IOERR_BLOCKED = (IOERR | (11 << 8)),\r\n        IOERR_NOMEM = (IOERR | (12 << 8)),\r\n        IOERR_ACCESS = (IOERR | (13 << 8)),\r\n        IOERR_CHECKRESERVEDLOCK = (IOERR | (14 << 8)),\r\n        IOERR_LOCK = (IOERR | (15 << 8)),\r\n        IOERR_CLOSE = (IOERR | (16 << 8)),\r\n        IOERR_DIR_CLOSE = (IOERR | (17 << 8)),\r\n        IOERR_SHMOPEN = (IOERR | (18 << 8)),\r\n        IOERR_SHMSIZE = (IOERR | (19 << 8)),\r\n        IOERR_SHMLOCK = (IOERR | (20 << 8)),\r\n        IOERR_SHMMAP = (IOERR | (21 << 8)),\r\n        IOERR_SEEK = (IOERR | (22 << 8)),\r\n        IOERR_DELETE_NOENT = (IOERR | (23 << 8)),\r\n        IOERR_MMAP = (IOERR | (24 << 8)),\r\n        IOERR_GETTEMPPATH = (IOERR | (25 << 8)),\r\n        IOERR_CONVPATH = (IOERR | (26 << 8)),\r\n        IOERR_VNODE = (IOERR | (27 << 8)),\r\n        IOERR_AUTH = (IOERR | (28 << 8)),\r\n        IOERR_BEGIN_ATOMIC = (IOERR | (29 << 8)),\r\n        IOERR_COMMIT_ATOMIC = (IOERR | (30 << 8)),\r\n        IOERR_ROLLBACK_ATOMIC = (IOERR | (31 << 8)),\r\n        IOERR_DATA = (IOERR | (32 << 8)),\r\n        LOCKED_SHAREDCACHE = (LOCKED | (1 << 8)),\r\n        LOCKED_VTAB = (LOCKED | (2 << 8)),\r\n        BUSY_RECOVERY = (BUSY | (1 << 8)),\r\n        BUSY_SNAPSHOT = (BUSY | (2 << 8)),\r\n        BUSY_TIMEOUT = (BUSY | (3 << 8)),\r\n        CANTOPEN_NOTEMPDIR = (CANTOPEN | (1 << 8)),\r\n        CANTOPEN_ISDIR = (CANTOPEN | (2 << 8)),\r\n        CANTOPEN_FULLPATH = (CANTOPEN | (3 << 8)),\r\n        CANTOPEN_CONVPATH = (CANTOPEN | (4 << 8)),\r\n        CANTOPEN_DIRTYWAL = (CANTOPEN | (5 << 8)) /* Not Used */,\r\n        CANTOPEN_SYMLINK = (CANTOPEN | (6 << 8)),\r\n        CORRUPT_VTAB = (CORRUPT | (1 << 8)),\r\n        CORRUPT_SEQUENCE = (CORRUPT | (2 << 8)),\r\n        CORRUPT_INDEX = (CORRUPT | (3 << 8)),\r\n        READONLY_RECOVERY = (READONLY | (1 << 8)),\r\n        READONLY_CANTLOCK = (READONLY | (2 << 8)),\r\n        READONLY_ROLLBACK = (READONLY | (3 << 8)),\r\n        READONLY_DBMOVED = (READONLY | (4 << 8)),\r\n        READONLY_CANTINIT = (READONLY | (5 << 8)),\r\n        READONLY_DIRECTORY = (READONLY | (6 << 8)),\r\n        ABORT_ROLLBACK = (ABORT | (2 << 8)),\r\n        CONSTRAINT_CHECK = (CONSTRAINT | (1 << 8)),\r\n        CONSTRAINT_COMMITHOOK = (CONSTRAINT | (2 << 8)),\r\n        CONSTRAINT_FOREIGNKEY = (CONSTRAINT | (3 << 8)),\r\n        CONSTRAINT_FUNCTION = (CONSTRAINT | (4 << 8)),\r\n        CONSTRAINT_NOTNULL = (CONSTRAINT | (5 << 8)),\r\n        CONSTRAINT_PRIMARYKEY = (CONSTRAINT | (6 << 8)),\r\n        CONSTRAINT_TRIGGER = (CONSTRAINT | (7 << 8)),\r\n        CONSTRAINT_UNIQUE = (CONSTRAINT | (8 << 8)),\r\n        CONSTRAINT_VTAB = (CONSTRAINT | (9 << 8)),\r\n        CONSTRAINT_ROWID = (CONSTRAINT | (10 << 8)),\r\n        CONSTRAINT_PINNED = (CONSTRAINT | (11 << 8)),\r\n        NOTICE_RECOVER_WAL = (NOTICE | (1 << 8)),\r\n        NOTICE_RECOVER_ROLLBACK = (NOTICE | (2 << 8)),\r\n        WARNING_AUTOINDEX = (WARNING | (1 << 8)),\r\n        AUTH_USER = (AUTH | (1 << 8)),\r\n        OK_LOAD_PERMANENTLY = (OK | (1 << 8)),\r\n        OK_SYMLINK = (OK | (2 << 8)),\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native/ResultCode.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 83e4f7120f125c64e99be8d6b576d4b0\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native/SqliteApi.cs",
    "content": "using System;\r\nusing System.Text;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Extra.Sqlite.Native\r\n{\r\n    using sqlite3_int64 = System.Int64;\r\n    using sqlite3_uint64 = System.UInt64;\r\n\r\n    public class SqliteApi\r\n    {\r\n#if UNITY_IPHONE && !UNITY_EDITOR\r\n\t    const string SQLITE3DLL = \"__Internal\";\r\n#else\r\n        const string SQLITE3DLL = \"sqlite3\";\r\n#endif\r\n        /*\r\n        ** CAPI3REF: Flags For File Open Operations\r\n        **\r\n        ** These bit values are intended for use in the\r\n        ** 3rd parameter to the [sqlite3_open_v2()] interface and\r\n        ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.\r\n        */\r\n        [Flags]\r\n        public enum OpenFlags : int\r\n        {\r\n            READONLY = 0x00000001,  /* Ok for sqlite3_open_v2() */\r\n            READWRITE = 0x00000002,  /* Ok for sqlite3_open_v2() */\r\n            CREATE = 0x00000004,  /* Ok for sqlite3_open_v2() */\r\n            DELETEONCLOSE = 0x00000008,  /* VFS only */\r\n            EXCLUSIVE = 0x00000010,  /* VFS only */\r\n            AUTOPROXY = 0x00000020,  /* VFS only */\r\n            URI = 0x00000040,  /* Ok for sqlite3_open_v2() */\r\n            MEMORY = 0x00000080,  /* Ok for sqlite3_open_v2() */\r\n            MAIN_DB = 0x00000100,  /* VFS only */\r\n            TEMP_DB = 0x00000200,  /* VFS only */\r\n            TRANSIENT_DB = 0x00000400,  /* VFS only */\r\n            MAIN_JOURNAL = 0x00000800,  /* VFS only */\r\n            TEMP_JOURNAL = 0x00001000,  /* VFS only */\r\n            SUBJOURNAL = 0x00002000,  /* VFS only */\r\n            MASTER_JOURNAL = 0x00004000,  /* VFS only */\r\n            NOMUTEX = 0x00008000,  /* Ok for sqlite3_open_v2() */\r\n            FULLMUTEX = 0x00010000,  /* Ok for sqlite3_open_v2() */\r\n            SHAREDCACHE = 0x00020000,  /* Ok for sqlite3_open_v2() */\r\n            PRIVATECACHE = 0x00040000,  /* Ok for sqlite3_open_v2() */\r\n            WAL = 0x00080000,  /* VFS only */\r\n            NOFOLLOW = 0x01000000,  /* Ok for sqlite3_open_v2() */\r\n        }\r\n\r\n        public enum PrepFlags : uint\r\n        {\r\n            ZERO = 0,\r\n\r\n            PERSISTENT = 0x01,\r\n            NORMALIZE = 0x02,\r\n            NO_VTAB = 0x04,\r\n        }\r\n\r\n        public enum DataTypes : int\r\n        {\r\n            INTEGER = 1,\r\n            FLOAT = 2,\r\n            BLOB = 4,\r\n            NULL = 5,\r\n            TEXT = 3,\r\n        }\r\n\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n        public unsafe delegate void SqliteActionCallback(IntPtr ptr);\r\n\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n        public unsafe delegate int SqliteExecCallback(IntPtr ptr, int col_count, IntPtr pp1, IntPtr pp2);\r\n\r\n        public static ResultCode sqlite3_open(\r\n            string filename,   /* Database filename (UTF-8) */\r\n            out sqlite3 ppDb      /* OUT: SQLite db handle */\r\n        )\r\n        {\r\n            return sqlite3_open_v2(filename, out ppDb, OpenFlags.READWRITE | OpenFlags.CREATE, null);\r\n        }\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe ResultCode sqlite3_open_v2(\r\n            string filename,   /* Database filename (UTF-8) */\r\n            out sqlite3 ppDb,     /* OUT: SQLite db handle */\r\n            OpenFlags flags,   /* Flags */\r\n            string zVfs        /* Name of VFS module to use */\r\n        );\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern ResultCode sqlite3_close(sqlite3 db);\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern ResultCode sqlite3_close_v2(sqlite3 db);\r\n\r\n        #region error\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int sqlite3_errcode(sqlite3 db);\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int sqlite3_extended_errcode(sqlite3 db);\r\n        #endregion \r\n\r\n        #region vfs\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe sqlite3_vfs* sqlite3_vfs_find(IntPtr zVfsName);\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe int sqlite3_vfs_register(sqlite3_vfs* vfs, int makeDflt);\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe int sqlite3_vfs_unregister(sqlite3_vfs* vfs);\r\n        #endregion \r\n\r\n        #region memory management\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern IntPtr sqlite3_malloc(int size);\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern IntPtr sqlite3_realloc(IntPtr ptr, int size);\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern sqlite3_uint64 sqlite3_msize(IntPtr ptr);\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern void sqlite3_free(IntPtr ptr);\r\n        #endregion\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int sqlite3_libversion_number();\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe ResultCode sqlite3_exec(\r\n            sqlite3 db,                                  /* An open database */\r\n            byte* sql,                           /* SQL to be evaluated */\r\n            IntPtr callback,  /* Callback function */\r\n            IntPtr p1,                                    /* 1st argument to callback */\r\n            byte** errmsg                              /* Error msg written here */\r\n        );\r\n\r\n        public static unsafe ResultCode sqlite3_exec(sqlite3 db, string zSql)\r\n        {\r\n            var bytes = GetNullTerminatedBytes(zSql);\r\n            fixed (byte* ptr = bytes)\r\n            {\r\n                return sqlite3_exec(db, ptr, IntPtr.Zero, IntPtr.Zero, (byte**)0);\r\n            }\r\n        }\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe ResultCode sqlite3_prepare_v3(\r\n            sqlite3 db,            /* Database handle */\r\n            byte* zSql,       /* SQL statement, UTF-8 encoded */\r\n            int nByte,              /* Maximum length of zSql in bytes. */\r\n            PrepFlags prepFlags, /* Zero or more SQLITE_PREPARE_ flags */\r\n            out sqlite3_stmt ppStmt,  /* OUT: Statement handle */\r\n            out IntPtr pzTail     /* OUT: Pointer to unused portion of zSql */\r\n        );\r\n\r\n        public static unsafe ResultCode sqlite3_prepare_v3(sqlite3 db, string zSql, PrepFlags prepFlags, out sqlite3_stmt ppStmt)\r\n        {\r\n            IntPtr pzTail;\r\n            var bytes = Encoding.UTF8.GetBytes(zSql);\r\n            fixed (byte* ptr = bytes)\r\n            {\r\n                return sqlite3_prepare_v3(db, ptr, bytes.Length, prepFlags, out ppStmt, out pzTail);\r\n            }\r\n        }\r\n\r\n        public static unsafe ResultCode sqlite3_prepare_v3(sqlite3 db, string zSql, out sqlite3_stmt ppStmt)\r\n        {\r\n            IntPtr pzTail;\r\n            var bytes = Encoding.UTF8.GetBytes(zSql);\r\n            fixed (byte* ptr = bytes)\r\n            {\r\n                return sqlite3_prepare_v3(db, ptr, bytes.Length, PrepFlags.ZERO, out ppStmt, out pzTail);\r\n            }\r\n        }\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern ResultCode sqlite3_step(sqlite3_stmt pStmt);\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern ResultCode sqlite3_finalize(sqlite3_stmt pStmt);\r\n\r\n        #region sqlite3 bind\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern ResultCode sqlite3_clear_bindings(sqlite3_stmt pStmt);\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern ResultCode sqlite3_reset(sqlite3_stmt pStmt);\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe ResultCode sqlite3_bind_blob(sqlite3_stmt pStmt, int index, byte* ptr, int n, /*void(*)(void*)*/IntPtr xDel);\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe ResultCode sqlite3_bind_blob64(sqlite3_stmt pStmt, int index, byte* ptr, sqlite3_uint64 n, /*void(*)(void*)*/IntPtr xDel);\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern ResultCode sqlite3_bind_double(sqlite3_stmt pStmt, int index, double value);\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern ResultCode sqlite3_bind_int(sqlite3_stmt pStmt, int index, int value);\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern ResultCode sqlite3_bind_int64(sqlite3_stmt pStmt, int index, sqlite3_int64 value);\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern ResultCode sqlite3_bind_null(sqlite3_stmt pStmt, int index);\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe ResultCode sqlite3_bind_text(sqlite3_stmt pStmt, int index, byte* pText, int nByte, IntPtr xDel);\r\n\r\n        public static unsafe ResultCode sqlite3_bind_text(sqlite3_stmt pStmt, int index, string text)\r\n        {\r\n            var bytes = Encoding.UTF8.GetBytes(text);\r\n            fixed (byte* ptr = bytes)\r\n            {\r\n                return sqlite3_bind_text(pStmt, index, ptr, bytes.Length, IntPtr.Zero);\r\n            }\r\n        }\r\n\r\n        // ResultCode sqlite3_bind_text16(sqlite3_stmt pStmt, int index, const void*, int, void(*)(void*));\r\n        // ResultCode sqlite3_bind_text64(sqlite3_stmt pStmt, int index, const char*, sqlite3_uint64, void(*)(void*), unsigned char encoding);\r\n        // ResultCode sqlite3_bind_value(sqlite3_stmt pStmt, int index, const sqlite3_value*);\r\n        // ResultCode sqlite3_bind_pointer(sqlite3_stmt pStmt, int index, void*, const char*,void(*)(void*));\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern ResultCode sqlite3_bind_zeroblob(sqlite3_stmt pStmt, int index, int n);\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern ResultCode sqlite3_bind_zeroblob64(sqlite3_stmt pStmt, int index, sqlite3_uint64 n);\r\n\r\n        #endregion\r\n\r\n        #region sqlite3 column\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern IntPtr sqlite3_column_blob(sqlite3_stmt pStmt, int iCol);\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern double sqlite3_column_double(sqlite3_stmt pStmt, int iCol);\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int sqlite3_column_int(sqlite3_stmt pStmt, int iCol);\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern sqlite3_int64 sqlite3_column_int64(sqlite3_stmt pStmt, int iCol);\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = \"sqlite3_column_text\")]\r\n        private static extern unsafe IntPtr _sqlite3_column_text(sqlite3_stmt pStmt, int iCol);\r\n\r\n        public static string sqlite3_column_text(sqlite3_stmt pStmt, int iCol)\r\n        {\r\n            var nByte = sqlite3_column_bytes(pStmt, iCol);\r\n            if (nByte < 0)\r\n            {\r\n                return null;\r\n            }\r\n            if (nByte == 0)\r\n            {\r\n                return string.Empty;\r\n            }\r\n            var ptr = _sqlite3_column_text(pStmt, iCol);\r\n            return GetString(ptr, nByte);\r\n        }\r\n\r\n        // const void* sqlite3_column_text16(sqlite3_stmt *, int iCol);\r\n        // sqlite3_value* sqlite3_column_value(sqlite3_stmt*, int iCol);\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int sqlite3_column_bytes(sqlite3_stmt pStmt, int iCol);\r\n        // int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern DataTypes sqlite3_column_type(sqlite3_stmt pStmt, int iCol);\r\n\r\n        [DllImport(SQLITE3DLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int sqlite3_column_count(sqlite3_stmt pStmt);\r\n\r\n        #endregion\r\n\r\n        #region helpers\r\n\r\n        public static byte[] GetNullTerminatedBytes(string str)\r\n        {\r\n            if (str == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var len = str.Length;\r\n            if (len > 0 && str[len - 1] == 0)\r\n            {\r\n                return Encoding.UTF8.GetBytes(str);\r\n            }\r\n\r\n            var count = Encoding.UTF8.GetByteCount(str);\r\n            var bytes = new byte[count + 1];\r\n            Encoding.UTF8.GetBytes(str, 0, len, bytes, 0);\r\n\r\n            return bytes;\r\n        }\r\n\r\n        public static unsafe string GetString(IntPtr ptr, int len)\r\n        {\r\n            var str = Marshal.PtrToStringAnsi(ptr, len);\r\n            if (str == null)\r\n            {\r\n                // var pointer = (byte*)(void*)ptr;\r\n                // return Encoding.UTF8.GetString(pointer, len);\r\n\r\n                var buffer = new byte[len];\r\n                Marshal.Copy(ptr, buffer, 0, len);\r\n                return Encoding.UTF8.GetString(buffer);\r\n            }\r\n\r\n            return str;\r\n        }\r\n        #endregion \r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native/SqliteApi.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 5285a2ece98ea784b835e0043380024b\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native/size_t.cs",
    "content": "using System;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Extra.Sqlite.Native\r\n{\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public unsafe struct size_t\r\n    {\r\n        private void* _value;\r\n\r\n        public size_t(int value)\r\n        {\r\n            _value = (void*) (uint) value;\r\n        }\r\n\r\n        public size_t(uint value)\r\n        {\r\n            _value = (void*) value;\r\n        }\r\n\r\n        public size_t(ulong value)\r\n        {\r\n            _value = (void*) value;\r\n        }\r\n\r\n        public size_t(UIntPtr value)\r\n        {\r\n            _value = (void*) value;\r\n        }\r\n\r\n        public static implicit operator size_t(int value)\r\n        {\r\n            return new size_t(value);\r\n        }\r\n\r\n        public static implicit operator size_t(uint value)\r\n        {\r\n            return new size_t(value);\r\n        }\r\n\r\n        public static implicit operator size_t(ulong value)\r\n        {\r\n            return new size_t(value);\r\n        }\r\n\r\n        public static implicit operator size_t(UIntPtr value)\r\n        {\r\n            return new size_t(value);\r\n        }\r\n\r\n        public static implicit operator int(size_t value)\r\n        {\r\n            return (int) value._value;\r\n        }\r\n\r\n        public static implicit operator uint(size_t value)\r\n        {\r\n            return (uint) value._value;\r\n        }\r\n\r\n        public static implicit operator ulong(size_t value)\r\n        {\r\n            return (ulong) value._value;\r\n        }\r\n        \r\n        public static implicit operator UIntPtr(size_t value)\r\n        {\r\n            return new UIntPtr(value._value);\r\n        }\r\n\r\n        public override string ToString()\r\n        {\r\n            return ((ulong)this).ToString();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native/size_t.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 33b56bae7a39fe546a1ae2e8aa0f0b4e\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native/sqlite3.cs",
    "content": "using System;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Extra.Sqlite.Native\r\n{\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public unsafe struct sqlite3\r\n    {\r\n        private void* _value;\r\n\r\n        public override string ToString()\r\n        {\r\n            return ((ulong)_value).ToString();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native/sqlite3.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: b013c8b698d77774ea70047750c3477e\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native/sqlite3_file.cs",
    "content": "using System;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Extra.Sqlite.Native\r\n{\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public unsafe struct sqlite3_file\r\n    {\r\n        private sqlite3_io_methods *pMethods;\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native/sqlite3_file.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 819dfd589b465ea4db27640c51736135\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native/sqlite3_io_methods.cs",
    "content": "using System;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Extra.Sqlite.Native\r\n{\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public unsafe struct sqlite3_io_methods\r\n    {\r\n        int iVersion;\r\n        IntPtr xClose; // int (*xClose)(sqlite3_file*);\r\n        IntPtr xRead; // int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);\r\n        IntPtr xWrite; // int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);\r\n        IntPtr xTruncate; // int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);\r\n        IntPtr xSync; // int (*xSync)(sqlite3_file*, int flags);\r\n        IntPtr xFileSize; // int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);\r\n        IntPtr xLock; // int (*xLock)(sqlite3_file*, int);\r\n        IntPtr xUnlock; // int (*xUnlock)(sqlite3_file*, int);\r\n        IntPtr xCheckReservedLock; // int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);\r\n        IntPtr xFileControl; // int (*xFileControl)(sqlite3_file*, int op, void *pArg);\r\n        IntPtr xSectorSize; // int (*xSectorSize)(sqlite3_file*);\r\n        IntPtr xDeviceCharacteristics; // int (*xDeviceCharacteristics)(sqlite3_file*);\r\n        IntPtr xShmMap; // int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);\r\n        IntPtr xShmLock; // int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);\r\n        IntPtr xShmBarrier; // void (*xShmBarrier)(sqlite3_file*);\r\n        IntPtr xShmUnmap; // int (*xShmUnmap)(sqlite3_file*, int deleteFlag);\r\n        IntPtr xFetch; // int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);\r\n        IntPtr xUnfetch; // int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native/sqlite3_io_methods.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 383f3a69ce69c7842b3747ca7b181390\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native/sqlite3_stmt.cs",
    "content": "using System;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Extra.Sqlite.Native\r\n{\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public unsafe struct sqlite3_stmt\r\n    {\r\n        private void* _value;\r\n\r\n        public override string ToString()\r\n        {\r\n            return ((ulong)_value).ToString();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native/sqlite3_stmt.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: a76803fa1aa069447a9ac23961a222ed\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native/sqlite3_vfs.cs",
    "content": "using System;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Extra.Sqlite.Native\r\n{\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public unsafe delegate int xOpenDelegate(sqlite3_vfs* vfs, IntPtr zName, sqlite3_file* file, int flags, ref int pOutFlags);\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public unsafe delegate int xDeleteDelegate(sqlite3_vfs* vfs, IntPtr zName, int syncDir);\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public unsafe delegate int xAccessDelegate(sqlite3_vfs* vfs, IntPtr zName, int flags, ref int pResOut);\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public unsafe delegate int xFullPathnameDelegate(sqlite3_vfs* vfs, IntPtr zName, int nOut, IntPtr zOut);\r\n\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public unsafe struct sqlite3_vfs\r\n    {\r\n        public int iVersion; /* Structure version number (currently 3) */\r\n        public int szOsFile; /* Size of subclassed sqlite3_file */\r\n        public int mxPathname; /* Maximum file pathname length */\r\n        public IntPtr pNext; /* Next registered VFS */\r\n        public IntPtr zName; /* Name of this virtual file system */\r\n        public IntPtr pAppData; /* Pointer to application-specific data */\r\n        public IntPtr xOpen; // int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, int flags, int *pOutFlags);\r\n        public IntPtr xDelete; // int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);\r\n        public IntPtr xAccess; // int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);\r\n        public IntPtr xFullPathname; // int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);\r\n\r\n        public IntPtr xDlOpen; // void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);\r\n        public IntPtr xDlError; // void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);\r\n        public IntPtr xDlSym; // void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);\r\n        public IntPtr xDlClose; // void (*xDlClose)(sqlite3_vfs*, void*);\r\n\r\n        public IntPtr xRandomness; // int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);\r\n        public IntPtr xSleep; // int (*xSleep)(sqlite3_vfs*, int microseconds);\r\n        public IntPtr xCurrentTime; // int (*xCurrentTime)(sqlite3_vfs*, double*);\r\n        public IntPtr xGetLastError; // int (*xGetLastError)(sqlite3_vfs*, int, char *);\r\n        public IntPtr xCurrentTimeInt64; // int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);\r\n        public IntPtr xSetSystemCall; // int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);\r\n        public IntPtr xGetSystemCall; // sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);\r\n        public IntPtr xNextSystemCall; // const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native/sqlite3_vfs.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 988bda8919cb6534ebe846a0b684172a\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/Native.meta",
    "content": "fileFormatVersion: 2\r\nguid: 6e919dc886a25e1449479608201ac193\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/SqliteConnection.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Extra.Sqlite\r\n{\r\n    using Native;\r\n\r\n    public unsafe class SqliteConnection\r\n    {\r\n        private sqlite3 _db;\r\n\r\n        public void Open()\r\n        {\r\n            SqliteApi.sqlite3_open(\"test.sqlite\", out _db);\r\n        }\r\n\r\n        public void Close()\r\n        {\r\n            SqliteApi.sqlite3_close(_db);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/SqliteConnection.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: df326d1fbe6e63e4fa852a289d3d751e\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/SqliteFileSystem.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Extra.Sqlite\r\n{\r\n    using Native;\r\n\r\n    public unsafe struct VFSFile\r\n    {\r\n\r\n    }\r\n\r\n    public unsafe class VFS : IDisposable\r\n    {\r\n        private static VFS _instance;\r\n\r\n        private IntPtr _name;\r\n        private sqlite3_vfs* _vfs;\r\n\r\n        public static VFS GetInstance()\r\n        {\r\n            if (_instance == null)\r\n            {\r\n                _instance = new VFS();\r\n            }\r\n            return _instance;\r\n        }\r\n\r\n        private VFS()\r\n        {\r\n            var name = QuickJS.Utils.TextUtils.GetNullTerminatedBytes(\"unity\");\r\n            _name = Marshal.AllocHGlobal(name.Length);\r\n            Marshal.Copy(name, 0, _name, name.Length);\r\n\r\n            _vfs = (sqlite3_vfs*)Marshal.AllocHGlobal(Marshal.SizeOf<sqlite3_vfs>());\r\n            _vfs->iVersion = 3;\r\n            _vfs->szOsFile = Marshal.SizeOf<VFSFile>();\r\n            _vfs->mxPathname = 260 * 4;\r\n            _vfs->pNext = IntPtr.Zero;\r\n            _vfs->zName = _name;\r\n            _vfs->pAppData = IntPtr.Zero;\r\n            // _vfs->xOpen = ;\r\n            // _vfs->xDelete = ;\r\n            // _vfs->xAccess = ;\r\n            // _vfs->xFullPathname = ;\r\n            // _vfs->xDlOpen = ;\r\n            // _vfs->xDlError = ;\r\n            // _vfs->xDlSym = ;\r\n            // _vfs->xDlClose = ;\r\n            // _vfs->xRandomness = ;\r\n            // _vfs->xSleep = ;\r\n            // _vfs->xCurrentTime = ;\r\n            SqliteApi.sqlite3_vfs_register(_vfs, 1);\r\n        }\r\n\r\n        ~VFS()\r\n        {\r\n            Dispose(false);\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n            Dispose(true);\r\n            GC.SuppressFinalize(this);\r\n        }\r\n\r\n        protected void Dispose(bool disposing)\r\n        {\r\n            if (_vfs != (sqlite3_vfs*)0)\r\n            {\r\n                SqliteApi.sqlite3_vfs_unregister(_vfs);\r\n                Marshal.FreeHGlobal((IntPtr)_vfs);\r\n                Marshal.FreeHGlobal(_name);\r\n                _name = IntPtr.Zero;\r\n                _vfs = (sqlite3_vfs*)0;\r\n            }\r\n        }\r\n    }\r\n\r\n    public unsafe class VFSRegister\r\n    {\r\n        // private Dictionary<string, VFS> _all = new Dictionary<string, VFS>();\r\n\r\n        [MonoPInvokeCallbackAttribute(typeof(xOpenDelegate))]\r\n        // int xOpenDelegate(sqlite3_vfs* vfs, IntPtr zName, sqlite3_file* file, int flags, ref int pOutFlags);\r\n        public static ResultCode Open(sqlite3_vfs* vfs, IntPtr zName, sqlite3_file* file, int flags, ref int pOutFlags)\r\n        {\r\n            return ResultCode.OK;\r\n        }\r\n\r\n        [MonoPInvokeCallbackAttribute(typeof(xDeleteDelegate))]\r\n        // int xDeleteDelegate(sqlite3_vfs* vfs, IntPtr zName, int syncDir);\r\n        public static ResultCode xDelete(sqlite3_vfs* vfs, IntPtr zName, int syncDir)\r\n        {\r\n            return ResultCode.OK;\r\n        }\r\n\r\n        [MonoPInvokeCallbackAttribute(typeof(xAccessDelegate))]\r\n        // int xAccessDelegate(sqlite3_vfs* vfs, IntPtr zName, int flags, ref int pResOut);\r\n        public static ResultCode xAccess(sqlite3_vfs* vfs, IntPtr zName, int flags, ref int pResOut)\r\n        {\r\n            return ResultCode.OK;\r\n        }\r\n\r\n        [MonoPInvokeCallbackAttribute(typeof(xFullPathnameDelegate))]\r\n        // int xFullPathnameDelegate(sqlite3_vfs* vfs, IntPtr zName, int nOut, IntPtr zOut);\r\n        public static ResultCode xFullPathname(sqlite3_vfs* vfs, IntPtr zName, int nOut, IntPtr zOut)\r\n        {\r\n            return ResultCode.OK;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source/SqliteFileSystem.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: f9898bed62f4ad14ca3bc74dcce06a64\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3/Source.meta",
    "content": "fileFormatVersion: 2\r\nguid: 6a9b4b02139a66242a5f4389ad0bc6f7\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/SQLite3.meta",
    "content": "fileFormatVersion: 2\r\nguid: 78b5ba75b99b39e4b91deb7d376b1fc8\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins/Android/libs/arm64-v8a/libwebsockets.so.meta",
    "content": "fileFormatVersion: 2\r\nguid: cad7d6836dc391a4a8176d63b9bf3bdb\r\nPluginImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  iconMap: {}\r\n  executionOrder: {}\r\n  defineConstraints: []\r\n  isPreloaded: 0\r\n  isOverridable: 0\r\n  isExplicitlyReferenced: 0\r\n  validateReferences: 1\r\n  platformData:\r\n  - first:\r\n      '': Any\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        Exclude Android: 0\r\n        Exclude Editor: 1\r\n        Exclude Linux: 1\r\n        Exclude Linux64: 1\r\n        Exclude LinuxUniversal: 1\r\n        Exclude OSXUniversal: 1\r\n        Exclude WebGL: 1\r\n        Exclude Win: 1\r\n        Exclude Win64: 1\r\n        Exclude iOS: 1\r\n  - first:\r\n      Android: Android\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: ARM64\r\n  - first:\r\n      Any: \r\n    second:\r\n      enabled: 0\r\n      settings: {}\r\n  - first:\r\n      Editor: Editor\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n        DefaultValueInitialized: true\r\n        OS: AnyOS\r\n  - first:\r\n      Facebook: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Facebook: Win64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Linux\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: x86\r\n  - first:\r\n      Standalone: Linux64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: x86_64\r\n  - first:\r\n      Standalone: LinuxUniversal\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: OSXUniversal\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Win64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      iPhone: iOS\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        AddToEmbeddedBinaries: false\r\n        CompileFlags: \r\n        FrameworkDependencies: \r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins/Android/libs/arm64-v8a.meta",
    "content": "fileFormatVersion: 2\r\nguid: 164305af7ae298240ba1da78d13cb718\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins/Android/libs/armeabi-v7a/libwebsockets.so.meta",
    "content": "fileFormatVersion: 2\r\nguid: d487889369bf0794caa4850dd211f7be\r\nPluginImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  iconMap: {}\r\n  executionOrder: {}\r\n  defineConstraints: []\r\n  isPreloaded: 0\r\n  isOverridable: 0\r\n  isExplicitlyReferenced: 0\r\n  validateReferences: 1\r\n  platformData:\r\n  - first:\r\n      '': Any\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        Exclude Android: 0\r\n        Exclude Editor: 1\r\n        Exclude Linux: 1\r\n        Exclude Linux64: 1\r\n        Exclude LinuxUniversal: 1\r\n        Exclude OSXUniversal: 1\r\n        Exclude WebGL: 1\r\n        Exclude Win: 1\r\n        Exclude Win64: 1\r\n        Exclude iOS: 1\r\n  - first:\r\n      Android: Android\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: ARMv7\r\n  - first:\r\n      Any: \r\n    second:\r\n      enabled: 0\r\n      settings: {}\r\n  - first:\r\n      Editor: Editor\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n        DefaultValueInitialized: true\r\n        OS: AnyOS\r\n  - first:\r\n      Facebook: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Facebook: Win64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Linux\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: x86\r\n  - first:\r\n      Standalone: Linux64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: x86_64\r\n  - first:\r\n      Standalone: LinuxUniversal\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: OSXUniversal\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Win64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      iPhone: iOS\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        AddToEmbeddedBinaries: false\r\n        CompileFlags: \r\n        FrameworkDependencies: \r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins/Android/libs/armeabi-v7a.meta",
    "content": "fileFormatVersion: 2\r\nguid: 130cbeb3781f7f54ea12bfaad40f1f90\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins/Android/libs/x86/libwebsockets.so.meta",
    "content": "fileFormatVersion: 2\r\nguid: 28ffb3a2c90d8f84bafb1b6cbb6203ae\r\nPluginImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  iconMap: {}\r\n  executionOrder: {}\r\n  defineConstraints: []\r\n  isPreloaded: 0\r\n  isOverridable: 0\r\n  isExplicitlyReferenced: 0\r\n  validateReferences: 1\r\n  platformData:\r\n  - first:\r\n      '': Any\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        Exclude Android: 0\r\n        Exclude Editor: 1\r\n        Exclude Linux: 1\r\n        Exclude Linux64: 1\r\n        Exclude LinuxUniversal: 1\r\n        Exclude OSXUniversal: 1\r\n        Exclude WebGL: 1\r\n        Exclude Win: 1\r\n        Exclude Win64: 1\r\n        Exclude iOS: 1\r\n  - first:\r\n      Android: Android\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86\r\n  - first:\r\n      Any: \r\n    second:\r\n      enabled: 0\r\n      settings: {}\r\n  - first:\r\n      Editor: Editor\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n        DefaultValueInitialized: true\r\n        OS: AnyOS\r\n  - first:\r\n      Facebook: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Facebook: Win64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Linux\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: x86\r\n  - first:\r\n      Standalone: Linux64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: x86_64\r\n  - first:\r\n      Standalone: LinuxUniversal\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: OSXUniversal\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Win64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      iPhone: iOS\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        AddToEmbeddedBinaries: false\r\n        CompileFlags: \r\n        FrameworkDependencies: \r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins/Android/libs/x86.meta",
    "content": "fileFormatVersion: 2\r\nguid: 9d64214b4f8d6514bae4fceac572993b\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins/Android/libs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 0ab73159c796c3c41a8dc9a77d1d39ce\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins/Android.meta",
    "content": "fileFormatVersion: 2\r\nguid: 9fdead7d5c94a2841b321a7e9cccfae4\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins/websockets.bundle/Contents/MacOS/websockets.meta",
    "content": "fileFormatVersion: 2\r\nguid: c54549681bd1340a1882225784f71996\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins/websockets.bundle/Contents/MacOS.meta",
    "content": "fileFormatVersion: 2\r\nguid: 1899e23ab1db0421a9731e84edb8d36b\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins/websockets.bundle/Contents.meta",
    "content": "fileFormatVersion: 2\r\nguid: 65681db52712e41f78b407e7d74cbf00\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins/websockets.bundle.meta",
    "content": "fileFormatVersion: 2\r\nguid: 37c5f4f5918e24506959ce6e819bc060\r\nfolderAsset: yes\r\nPluginImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  iconMap: {}\r\n  executionOrder: {}\r\n  defineConstraints: []\r\n  isPreloaded: 0\r\n  isOverridable: 0\r\n  isExplicitlyReferenced: 0\r\n  validateReferences: 1\r\n  platformData:\r\n  - first:\r\n      Any: \r\n    second:\r\n      enabled: 0\r\n      settings: {}\r\n  - first:\r\n      Editor: Editor\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        DefaultValueInitialized: true\r\n  - first:\r\n      Standalone: OSXUniversal\r\n    second:\r\n      enabled: 1\r\n      settings: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins/x64/websockets.dll.meta",
    "content": "fileFormatVersion: 2\r\nguid: f9e2a31f68623a945a04eded6adc721c\r\nPluginImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  iconMap: {}\r\n  executionOrder: {}\r\n  defineConstraints: []\r\n  isPreloaded: 0\r\n  isOverridable: 0\r\n  isExplicitlyReferenced: 0\r\n  validateReferences: 1\r\n  platformData:\r\n  - first:\r\n      '': Any\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        Exclude Android: 1\r\n        Exclude Editor: 0\r\n        Exclude Linux: 0\r\n        Exclude Linux64: 0\r\n        Exclude LinuxUniversal: 0\r\n        Exclude OSXUniversal: 0\r\n        Exclude WebGL: 1\r\n        Exclude Win: 0\r\n        Exclude Win64: 0\r\n        Exclude iOS: 1\r\n  - first:\r\n      Android: Android\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: ARMv7\r\n  - first:\r\n      Any: \r\n    second:\r\n      enabled: 0\r\n      settings: {}\r\n  - first:\r\n      Editor: Editor\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86_64\r\n        DefaultValueInitialized: true\r\n        OS: AnyOS\r\n  - first:\r\n      Facebook: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Facebook: Win64\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Linux\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: Linux64\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86_64\r\n  - first:\r\n      Standalone: LinuxUniversal\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86_64\r\n  - first:\r\n      Standalone: OSXUniversal\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86_64\r\n  - first:\r\n      Standalone: Win\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: Win64\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      iPhone: iOS\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        AddToEmbeddedBinaries: false\r\n        CompileFlags: \r\n        FrameworkDependencies: \r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins/x64.meta",
    "content": "fileFormatVersion: 2\r\nguid: 84b8fc574a7ac86468330f9d9081ce87\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins/x86/websockets.dll.meta",
    "content": "fileFormatVersion: 2\r\nguid: c3085fd0a4103e74fb12091d97d82a8a\r\nPluginImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  iconMap: {}\r\n  executionOrder: {}\r\n  defineConstraints: []\r\n  isPreloaded: 0\r\n  isOverridable: 0\r\n  isExplicitlyReferenced: 0\r\n  validateReferences: 1\r\n  platformData:\r\n  - first:\r\n      '': Any\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        Exclude Android: 1\r\n        Exclude Editor: 0\r\n        Exclude Linux: 0\r\n        Exclude Linux64: 0\r\n        Exclude LinuxUniversal: 0\r\n        Exclude OSXUniversal: 0\r\n        Exclude WebGL: 1\r\n        Exclude Win: 0\r\n        Exclude Win64: 0\r\n        Exclude iOS: 1\r\n  - first:\r\n      Android: Android\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: ARMv7\r\n  - first:\r\n      Any: \r\n    second:\r\n      enabled: 0\r\n      settings: {}\r\n  - first:\r\n      Editor: Editor\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86\r\n        DefaultValueInitialized: true\r\n        OS: AnyOS\r\n  - first:\r\n      Facebook: Win\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Facebook: Win64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: Linux\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86\r\n  - first:\r\n      Standalone: Linux64\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: LinuxUniversal\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: OSXUniversal\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86\r\n  - first:\r\n      Standalone: Win\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Win64\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      iPhone: iOS\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        AddToEmbeddedBinaries: false\r\n        CompileFlags: \r\n        FrameworkDependencies: \r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins/x86.meta",
    "content": "fileFormatVersion: 2\r\nguid: e184dd1bdcb84a541b2f94f04ebe87de\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Plugins.meta",
    "content": "fileFormatVersion: 2\r\nguid: d2e28b3996a3dc748b0b9627cd24c867\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/Native/WSApi.cs",
    "content": "#if !UNITY_WEBGL \r\nusing System;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Extra.WebSockets\r\n{\r\n    using size_t = QuickJS.Native.size_t;\r\n\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public delegate int lws_callback_function(lws wsi, lws_callback_reasons reason, IntPtr user, IntPtr @in, size_t len);\r\n\r\n    public class WSApi\r\n    {\r\n#if UNITY_IPHONE && !UNITY_EDITOR\r\n\t    const string WSDLL = \"__Internal\";\r\n#else\r\n        const string WSDLL = \"websockets\";\r\n#endif\r\n        [DllImport(WSDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe lws_context ulws_create(byte* name, size_t len, IntPtr callback, size_t rx_buffer_size, size_t tx_packet_size);\r\n\r\n        public static lws_context ulws_create(string name, lws_callback_function callback, size_t rx_buffer_size, size_t tx_packet_size)\r\n        {\r\n            var fn = Marshal.GetFunctionPointerForDelegate(callback);\r\n            var bytes = QuickJS.Utils.TextUtils.GetNullTerminatedBytes(name);\r\n            unsafe\r\n            {\r\n                fixed (byte* pointer = bytes)\r\n                {\r\n                    return ulws_create(pointer, bytes.Length - 1, fn, rx_buffer_size, tx_packet_size);\r\n                }\r\n            }\r\n        }\r\n\r\n        [DllImport(WSDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe lws ulws_connect(lws_context context, byte* protocol_names, ulws_ssl_type ssl_type, byte* host, byte* address, byte* path, int port);\r\n\r\n        [DllImport(WSDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int ulws_pre();\r\n\r\n        public static readonly int LWS_PRE = ulws_pre();\r\n\r\n        [DllImport(WSDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe int lws_write(lws wsi, byte* buf, size_t len, lws_write_protocol wp);\r\n\r\n        [DllImport(WSDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern lws_context lws_get_context(lws wsi);\r\n\r\n        [DllImport(WSDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern void ulws_destroy(lws_context context);\r\n\r\n        [DllImport(WSDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int lws_service(lws_context context, int timeout_ms);\r\n\r\n        [DllImport(WSDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int lws_is_first_fragment(lws wsi);\r\n\r\n        [DllImport(WSDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int lws_frame_is_binary(lws wsi);\r\n\r\n        [DllImport(WSDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int lws_callback_on_writable(lws wsi);\r\n\r\n        [DllImport(WSDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int lws_is_final_fragment(lws wsi);\r\n\r\n        [DllImport(WSDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe void lws_close_reason(lws wsi, lws_close_status status, byte* buf, size_t len);\r\n\r\n        public static void lws_close_reason(lws wsi, lws_close_status status, string buf)\r\n        {\r\n            var bytes = QuickJS.Utils.TextUtils.GetNullTerminatedBytes(buf);\r\n            unsafe\r\n            {\r\n                fixed (byte* pointer = bytes)\r\n                {\r\n                    lws_close_reason(wsi, status, pointer, bytes.Length - 1);\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/Native/WSApi.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 69c0b09531d03a44e980802b9e06a49d\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/Native/lws.cs",
    "content": "#if !UNITY_WEBGL\r\nusing System;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Extra.WebSockets\r\n{\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public unsafe struct lws\r\n    {\r\n        public static readonly lws Null = new lws();\r\n        \r\n        public void* _value;\r\n\r\n        public bool IsValid()\r\n        {\r\n            return _value != (void*)0;\r\n        }\r\n\r\n        public override int GetHashCode()\r\n        {\r\n            return (int) _value;\r\n        }\r\n\r\n        public bool Equals(lws other)\r\n        {\r\n            return this == other;\r\n        }\r\n\r\n        public override bool Equals(object obj)\r\n        {\r\n            if (obj is lws)\r\n            {\r\n                var other = (lws)obj;\r\n                return this == other;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public override string ToString()\r\n        {\r\n            return string.Format(\"lws:{0:X}\", (ulong) _value);\r\n        }\r\n\r\n        public static bool operator ==(lws a, lws b)\r\n        {\r\n            return a._value == b._value;\r\n        }\r\n\r\n        public static bool operator !=(lws a, lws b)\r\n        {\r\n            return !(a == b);\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/Native/lws.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 4d3cd1f8bf98ff14ab1998069834b778\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/Native/lws_callback_reasons.cs",
    "content": "#if !UNITY_WEBGL \r\nusing System;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Extra.WebSockets\r\n{\r\n    /*\r\n     * NOTE: These public enums are part of the abi.  If you want to add one,\r\n     * add it at where specified so existing users are unaffected.\r\n     */\r\n    /** enum lws_callback_reasons - reason you're getting a protocol callback */\r\n    public enum lws_callback_reasons\r\n    {\r\n\r\n        /* ---------------------------------------------------------------------\r\n         * ----- Callbacks related to wsi and protocol binding lifecycle -----\r\n         */\r\n\r\n        LWS_CALLBACK_PROTOCOL_INIT = 27,\r\n        /**< One-time call per protocol, per-vhost using it, so it can\r\n         * do initial setup / allocations etc */\r\n\r\n        LWS_CALLBACK_PROTOCOL_DESTROY = 28,\r\n        /**< One-time call per protocol, per-vhost using it, indicating\r\n         * this protocol won't get used at all after this callback, the\r\n         * vhost is getting destroyed.  Take the opportunity to\r\n         * deallocate everything that was allocated by the protocol. */\r\n\r\n        LWS_CALLBACK_WSI_CREATE = 29,\r\n        /**< outermost (earliest) wsi create notification to protocols[0] */\r\n\r\n        LWS_CALLBACK_WSI_DESTROY = 30,\r\n        /**< outermost (latest) wsi destroy notification to protocols[0] */\r\n\r\n        LWS_CALLBACK_HTTP_BIND_PROTOCOL = 49,\r\n        /**< By default, all HTTP handling is done in protocols[0].\r\n         * However you can bind different protocols (by name) to\r\n         * different parts of the URL space using callback mounts.  This\r\n         * callback occurs in the new protocol when a wsi is bound\r\n         * to that protocol.  Any protocol allocation related to the\r\n         * http transaction processing should be created then.\r\n         * These specific callbacks are necessary because with HTTP/1.1,\r\n         * a single connection may perform at series of different\r\n         * transactions at different URLs, thus the lifetime of the\r\n         * protocol bind is just for one transaction, not connection. */\r\n\r\n        LWS_CALLBACK_HTTP_DROP_PROTOCOL = 50,\r\n        /**< This is called when a transaction is unbound from a protocol.\r\n         * It indicates the connection completed its transaction and may\r\n         * do something different now.  Any protocol allocation related\r\n         * to the http transaction processing should be destroyed. */\r\n\r\n        /* ---------------------------------------------------------------------\r\n         * ----- Callbacks related to Server TLS -----\r\n         */\r\n\r\n        LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS = 21,\r\n        /**< if configured for\r\n         * including OpenSSL support, this callback allows your user code\r\n         * to perform extra SSL_CTX_load_verify_locations() or similar\r\n         * calls to direct OpenSSL where to find certificates the client\r\n         * can use to confirm the remote server identity.  user is the\r\n         * OpenSSL SSL_CTX* */\r\n\r\n        LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS = 22,\r\n        /**< if configured for\r\n         * including OpenSSL support, this callback allows your user code\r\n         * to load extra certificates into the server which allow it to\r\n         * verify the validity of certificates returned by clients.  user\r\n         * is the server's OpenSSL SSL_CTX* and in is the lws_vhost */\r\n\r\n        LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION = 23,\r\n        /**< if the libwebsockets vhost was created with the option\r\n         * LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this\r\n         * callback is generated during OpenSSL verification of the cert\r\n         * sent from the client.  It is sent to protocol[0] callback as\r\n         * no protocol has been negotiated on the connection yet.\r\n         * Notice that the libwebsockets context and wsi are both NULL\r\n         * during this callback.  See\r\n         *  http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html\r\n         * to understand more detail about the OpenSSL callback that\r\n         * generates this libwebsockets callback and the meanings of the\r\n         * arguments passed.  In this callback, user is the x509_ctx,\r\n         * in is the ssl pointer and len is preverify_ok\r\n         * Notice that this callback maintains libwebsocket return\r\n         * conventions, return 0 to mean the cert is OK or 1 to fail it.\r\n         * This also means that if you don't handle this callback then\r\n         * the default callback action of returning 0 allows the client\r\n         * certificates. */\r\n\r\n        LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY = 37,\r\n        /**< if configured for including OpenSSL support but no private key\r\n         * file has been specified (ssl_private_key_filepath is NULL), this is\r\n         * called to allow the user to set the private key directly via\r\n         * libopenssl and perform further operations if required; this might be\r\n         * useful in situations where the private key is not directly accessible\r\n         * by the OS, for example if it is stored on a smartcard.\r\n         * user is the server's OpenSSL SSL_CTX* */\r\n\r\n        LWS_CALLBACK_SSL_INFO = 67,\r\n        /**< SSL connections only.  An event you registered an\r\n         * interest in at the vhost has occurred on a connection\r\n         * using the vhost.  in is a pointer to a\r\n         * struct lws_ssl_info containing information about the\r\n         * event*/\r\n\r\n        /* ---------------------------------------------------------------------\r\n         * ----- Callbacks related to Client TLS -----\r\n         */\r\n\r\n        LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION = 58,\r\n        /**< Similar to LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION\r\n         * this callback is called during OpenSSL verification of the cert\r\n         * sent from the server to the client. It is sent to protocol[0]\r\n         * callback as no protocol has been negotiated on the connection yet.\r\n         * Notice that the wsi is set because lws_client_connect_via_info was\r\n         * successful.\r\n         *\r\n         * See http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html\r\n         * to understand more detail about the OpenSSL callback that\r\n         * generates this libwebsockets callback and the meanings of the\r\n         * arguments passed. In this callback, user is the x509_ctx,\r\n         * in is the ssl pointer and len is preverify_ok.\r\n         *\r\n         * THIS IS NOT RECOMMENDED BUT if a cert validation error shall be\r\n         * overruled and cert shall be accepted as ok,\r\n         * X509_STORE_CTX_set_error((X509_STORE_CTX*)user, X509_V_OK); must be\r\n         * called and return value must be 0 to mean the cert is OK;\r\n         * returning 1 will fail the cert in any case.\r\n         *\r\n         * This also means that if you don't handle this callback then\r\n         * the default callback action of returning 0 will not accept the\r\n         * certificate in case of a validation error decided by the SSL lib.\r\n         *\r\n         * This is expected and secure behaviour when validating certificates.\r\n         *\r\n         * Note: LCCSCF_ALLOW_SELFSIGNED and\r\n         * LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK still work without this\r\n         * callback being implemented.\r\n         */\r\n\r\n        /* ---------------------------------------------------------------------\r\n         * ----- Callbacks related to HTTP Server  -----\r\n         */\r\n\r\n        LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED = 19,\r\n        /**< A new client has been accepted by the ws server.  This\r\n         * callback allows setting any relevant property to it. Because this\r\n         * happens immediately after the instantiation of a new client,\r\n         * there's no websocket protocol selected yet so this callback is\r\n         * issued only to protocol 0. Only wsi is defined, pointing to the\r\n         * new client, and the return value is ignored. */\r\n\r\n        LWS_CALLBACK_HTTP = 12,\r\n        /**< an http request has come from a client that is not\r\n         * asking to upgrade the connection to a websocket\r\n         * one.  This is a chance to serve http content,\r\n         * for example, to send a script to the client\r\n         * which will then open the websockets connection.\r\n         * in points to the URI path requested and\r\n         * lws_serve_http_file() makes it very\r\n         * simple to send back a file to the client.\r\n         * Normally after sending the file you are done\r\n         * with the http connection, since the rest of the\r\n         * activity will come by websockets from the script\r\n         * that was delivered by http, so you will want to\r\n         * return 1; to close and free up the connection. */\r\n\r\n        LWS_CALLBACK_HTTP_BODY = 13,\r\n        /**< the next len bytes data from the http\r\n         * request body HTTP connection is now available in in. */\r\n\r\n        LWS_CALLBACK_HTTP_BODY_COMPLETION = 14,\r\n        /**< the expected amount of http request body has been delivered */\r\n\r\n        LWS_CALLBACK_HTTP_FILE_COMPLETION = 15,\r\n        /**< a file requested to be sent down http link has completed. */\r\n\r\n        LWS_CALLBACK_HTTP_WRITEABLE = 16,\r\n        /**< you can write more down the http protocol link now. */\r\n\r\n        LWS_CALLBACK_CLOSED_HTTP = 5,\r\n        /**< when a HTTP (non-websocket) session ends */\r\n\r\n        LWS_CALLBACK_FILTER_HTTP_CONNECTION = 18,\r\n        /**< called when the request has\r\n         * been received and parsed from the client, but the response is\r\n         * not sent yet.  Return non-zero to disallow the connection.\r\n         * user is a pointer to the connection user space allocation,\r\n         * in is the URI, eg, \"/\"\r\n         * In your handler you can use the public APIs\r\n         * lws_hdr_total_length() / lws_hdr_copy() to access all of the\r\n         * headers using the header enums lws_token_indexes from\r\n         * libwebsockets.h to check for and read the supported header\r\n         * presence and content before deciding to allow the http\r\n         * connection to proceed or to kill the connection. */\r\n\r\n        LWS_CALLBACK_ADD_HEADERS = 53,\r\n        /**< This gives your user code a chance to add headers to a server\r\n         * transaction bound to your protocol.  `in` points to a\r\n         * `struct lws_process_html_args` describing a buffer and length\r\n         * you can add headers into using the normal lws apis.\r\n         *\r\n         * (see LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER to add headers to\r\n         * a client transaction)\r\n         *\r\n         * Only `args->p` and `args->len` are valid, and `args->p` should\r\n         * be moved on by the amount of bytes written, if any.  Eg\r\n         *\r\n         * \tcase LWS_CALLBACK_ADD_HEADERS:\r\n         *\r\n         *          struct lws_process_html_args *args =\r\n         *          \t\t(struct lws_process_html_args *)in;\r\n         *\r\n         *\t    if (lws_add_http_header_by_name(wsi,\r\n         *\t\t\t(unsigned char *)\"set-cookie:\",\r\n         *\t\t\t(unsigned char *)cookie, cookie_len,\r\n         *\t\t\t(unsigned char **)&args->p,\r\n         *\t\t\t(unsigned char *)args->p + args->max_len))\r\n         *\t\treturn 1;\r\n         *\r\n         *          break;\r\n         */\r\n\r\n        LWS_CALLBACK_CHECK_ACCESS_RIGHTS = 51,\r\n        /**< This gives the user code a chance to forbid an http access.\r\n         * `in` points to a `struct lws_process_html_args`, which\r\n         * describes the URL, and a bit mask describing the type of\r\n         * authentication required.  If the callback returns nonzero,\r\n         * the transaction ends with HTTP_STATUS_UNAUTHORIZED. */\r\n\r\n        LWS_CALLBACK_PROCESS_HTML = 52,\r\n        /**< This gives your user code a chance to mangle outgoing\r\n         * HTML.  `in` points to a `struct lws_process_html_args`\r\n         * which describes the buffer containing outgoing HTML.\r\n         * The buffer may grow up to `.max_len` (currently +128\r\n         * bytes per buffer).\r\n         */\r\n\r\n        /* ---------------------------------------------------------------------\r\n         * ----- Callbacks related to HTTP Client  -----\r\n         */\r\n\r\n        LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP = 44,\r\n        /**< The HTTP client connection has succeeded, and is now\r\n         * connected to the server */\r\n\r\n        LWS_CALLBACK_CLOSED_CLIENT_HTTP = 45,\r\n        /**< The HTTP client connection is closing */\r\n\r\n        LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ = 48,\r\n        /**< This is generated by lws_http_client_read() used to drain\r\n         * incoming data.  In the case the incoming data was chunked, it will\r\n         * be split into multiple smaller callbacks for each chunk block,\r\n         * removing the chunk headers. If not chunked, it will appear all in\r\n         * one callback. */\r\n\r\n        LWS_CALLBACK_RECEIVE_CLIENT_HTTP = 46,\r\n        /**< This simply indicates data was received on the HTTP client\r\n         * connection.  It does NOT drain or provide the data.\r\n         * This exists to neatly allow a proxying type situation,\r\n         * where this incoming data will go out on another connection.\r\n         * If the outgoing connection stalls, we should stall processing\r\n         * the incoming data.  So a handler for this in that case should\r\n         * simply set a flag to indicate there is incoming data ready\r\n         * and ask for a writeable callback on the outgoing connection.\r\n         * In the writable callback he can check the flag and then get\r\n         * and drain the waiting incoming data using lws_http_client_read().\r\n         * This will use callbacks to LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ\r\n         * to get and drain the incoming data, where it should be sent\r\n         * back out on the outgoing connection. */\r\n        LWS_CALLBACK_COMPLETED_CLIENT_HTTP = 47,\r\n        /**< The client transaction completed... at the moment this\r\n         * is the same as closing since transaction pipelining on\r\n         * client side is not yet supported.  */\r\n\r\n        LWS_CALLBACK_CLIENT_HTTP_WRITEABLE = 57,\r\n        /**< when doing an HTTP type client connection, you can call\r\n         * lws_client_http_body_pending(wsi, 1) from\r\n         * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER to get these callbacks\r\n         * sending the HTTP headers.\r\n         *\r\n         * From this callback, when you have sent everything, you should let\r\n         * lws know by calling lws_client_http_body_pending(wsi, 0)\r\n         */\r\n\r\n        /* ---------------------------------------------------------------------\r\n         * ----- Callbacks related to Websocket Server -----\r\n         */\r\n\r\n        LWS_CALLBACK_ESTABLISHED = 0,\r\n        /**< (VH) after the server completes a handshake with an incoming\r\n         * client.  If you built the library with ssl support, in is a\r\n         * pointer to the ssl struct associated with the connection or NULL.\r\n         *\r\n         * b0 of len is set if the connection was made using ws-over-h2\r\n         */\r\n\r\n        LWS_CALLBACK_CLOSED = 4,\r\n        /**< when the websocket session ends */\r\n\r\n        LWS_CALLBACK_SERVER_WRITEABLE = 11,\r\n        /**< See LWS_CALLBACK_CLIENT_WRITEABLE */\r\n\r\n        LWS_CALLBACK_RECEIVE = 6,\r\n        /**< data has appeared for this server endpoint from a\r\n         * remote client, it can be found at *in and is\r\n         * len bytes long */\r\n\r\n        LWS_CALLBACK_RECEIVE_PONG = 7,\r\n        /**< servers receive PONG packets with this callback reason */\r\n\r\n        LWS_CALLBACK_WS_PEER_INITIATED_CLOSE = 38,\r\n        /**< The peer has sent an unsolicited Close WS packet.  in and\r\n         * len are the optional close code (first 2 bytes, network\r\n         * order) and the optional additional information which is not\r\n         * defined in the standard, and may be a string or non human-readable\r\n         * data.\r\n         * If you return 0 lws will echo the close and then close the\r\n         * connection.  If you return nonzero lws will just close the\r\n         * connection. */\r\n\r\n        LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION = 20,\r\n        /**< called when the handshake has\r\n         * been received and parsed from the client, but the response is\r\n         * not sent yet.  Return non-zero to disallow the connection.\r\n         * user is a pointer to the connection user space allocation,\r\n         * in is the requested protocol name\r\n         * In your handler you can use the public APIs\r\n         * lws_hdr_total_length() / lws_hdr_copy() to access all of the\r\n         * headers using the header enums lws_token_indexes from\r\n         * libwebsockets.h to check for and read the supported header\r\n         * presence and content before deciding to allow the handshake\r\n         * to proceed or to kill the connection. */\r\n\r\n        LWS_CALLBACK_CONFIRM_EXTENSION_OKAY = 25,\r\n        /**< When the server handshake code\r\n         * sees that it does support a requested extension, before\r\n         * accepting the extension by additing to the list sent back to\r\n         * the client it gives this callback just to check that it's okay\r\n         * to use that extension.  It calls back to the requested protocol\r\n         * and with in being the extension name, len is 0 and user is\r\n         * valid.  Note though at this time the ESTABLISHED callback hasn't\r\n         * happened yet so if you initialize user content there, user\r\n         * content during this callback might not be useful for anything. */\r\n\r\n        /* ---------------------------------------------------------------------\r\n         * ----- Callbacks related to Websocket Client -----\r\n         */\r\n\r\n        LWS_CALLBACK_CLIENT_CONNECTION_ERROR = 1,\r\n        /**< the request client connection has been unable to complete a\r\n         * handshake with the remote server.  If in is non-NULL, you can\r\n         * find an error string of length len where it points to\r\n         *\r\n         * Diagnostic strings that may be returned include\r\n         *\r\n         *     \t\"getaddrinfo (ipv6) failed\"\r\n         *     \t\"unknown address family\"\r\n         *     \t\"getaddrinfo (ipv4) failed\"\r\n         *     \t\"set socket opts failed\"\r\n         *     \t\"insert wsi failed\"\r\n         *     \t\"lws_ssl_client_connect1 failed\"\r\n         *     \t\"lws_ssl_client_connect2 failed\"\r\n         *     \t\"Peer hung up\"\r\n         *     \t\"read failed\"\r\n         *     \t\"HS: URI missing\"\r\n         *     \t\"HS: Redirect code but no Location\"\r\n         *     \t\"HS: URI did not parse\"\r\n         *     \t\"HS: Redirect failed\"\r\n         *     \t\"HS: Server did not return 200\"\r\n         *     \t\"HS: OOM\"\r\n         *     \t\"HS: disallowed by client filter\"\r\n         *     \t\"HS: disallowed at ESTABLISHED\"\r\n         *     \t\"HS: ACCEPT missing\"\r\n         *     \t\"HS: ws upgrade response not 101\"\r\n         *     \t\"HS: UPGRADE missing\"\r\n         *     \t\"HS: Upgrade to something other than websocket\"\r\n         *     \t\"HS: CONNECTION missing\"\r\n         *     \t\"HS: UPGRADE malformed\"\r\n         *     \t\"HS: PROTOCOL malformed\"\r\n         *     \t\"HS: Cannot match protocol\"\r\n         *     \t\"HS: EXT: list too big\"\r\n         *     \t\"HS: EXT: failed setting defaults\"\r\n         *     \t\"HS: EXT: failed parsing defaults\"\r\n         *     \t\"HS: EXT: failed parsing options\"\r\n         *     \t\"HS: EXT: Rejects server options\"\r\n         *     \t\"HS: EXT: unknown ext\"\r\n         *     \t\"HS: Accept hash wrong\"\r\n         *     \t\"HS: Rejected by filter cb\"\r\n         *     \t\"HS: OOM\"\r\n         *     \t\"HS: SO_SNDBUF failed\"\r\n         *     \t\"HS: Rejected at CLIENT_ESTABLISHED\"\r\n         */\r\n\r\n        LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH = 2,\r\n        /**< this is the last chance for the client user code to examine the\r\n         * http headers and decide to reject the connection.  If the\r\n         * content in the headers is interesting to the\r\n         * client (url, etc) it needs to copy it out at\r\n         * this point since it will be destroyed before\r\n         * the CLIENT_ESTABLISHED call */\r\n\r\n        LWS_CALLBACK_CLIENT_ESTABLISHED = 3,\r\n        /**< after your client connection completed the websocket upgrade\r\n         * handshake with the remote server */\r\n\r\n        LWS_CALLBACK_CLIENT_CLOSED = 75,\r\n        /**< when a client websocket session ends */\r\n\r\n        LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER = 24,\r\n        /**< this callback happens\r\n         * when a client handshake is being compiled.  user is NULL,\r\n         * in is a char **, it's pointing to a char * which holds the\r\n         * next location in the header buffer where you can add\r\n         * headers, and len is the remaining space in the header buffer,\r\n         * which is typically some hundreds of bytes.  So, to add a canned\r\n         * cookie, your handler code might look similar to:\r\n         *\r\n         *\tchar **p = (char **)in;\r\n         *\r\n         *\tif (len < 100)\r\n         *\t\treturn 1;\r\n         *\r\n         *\t*p += sprintf(*p, \"Cookie: a=b\\x0d\\x0a\");\r\n         *\r\n         *\treturn 0;\r\n         *\r\n         * Notice if you add anything, you just have to take care about\r\n         * the CRLF on the line you added.  Obviously this callback is\r\n         * optional, if you don't handle it everything is fine.\r\n         *\r\n         * Notice the callback is coming to protocols[0] all the time,\r\n         * because there is no specific protocol negotiated yet.\r\n         *\r\n         * See LWS_CALLBACK_ADD_HEADERS for adding headers to server\r\n         * transactions.\r\n         */\r\n\r\n        LWS_CALLBACK_CLIENT_RECEIVE = 8,\r\n        /**< data has appeared from the server for the client connection, it\r\n         * can be found at *in and is len bytes long */\r\n\r\n        LWS_CALLBACK_CLIENT_RECEIVE_PONG = 9,\r\n        /**< clients receive PONG packets with this callback reason */\r\n\r\n        LWS_CALLBACK_CLIENT_WRITEABLE = 10,\r\n        /**<  If you call lws_callback_on_writable() on a connection, you will\r\n         * get one of these callbacks coming when the connection socket\r\n         * is able to accept another write packet without blocking.\r\n         * If it already was able to take another packet without blocking,\r\n         * you'll get this callback at the next call to the service loop\r\n         * function.  Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE\r\n         * and servers get LWS_CALLBACK_SERVER_WRITEABLE. */\r\n\r\n        LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED = 26,\r\n        /**< When a ws client\r\n         * connection is being prepared to start a handshake to a server,\r\n         * each supported extension is checked with protocols[0] callback\r\n         * with this reason, giving the user code a chance to suppress the\r\n         * claim to support that extension by returning non-zero.  If\r\n         * unhandled, by default 0 will be returned and the extension\r\n         * support included in the header to the server.  Notice this\r\n         * callback comes to protocols[0]. */\r\n\r\n        LWS_CALLBACK_WS_EXT_DEFAULTS = 39,\r\n        /**< Gives client connections an opportunity to adjust negotiated\r\n         * extension defaults.  `user` is the extension name that was\r\n         * negotiated (eg, \"permessage-deflate\").  `in` points to a\r\n         * buffer and `len` is the buffer size.  The user callback can\r\n         * set the buffer to a string describing options the extension\r\n         * should parse.  Or just ignore for defaults. */\r\n\r\n\r\n        LWS_CALLBACK_FILTER_NETWORK_CONNECTION = 17,\r\n        /**< called when a client connects to\r\n         * the server at network level; the connection is accepted but then\r\n         * passed to this callback to decide whether to hang up immediately\r\n         * or not, based on the client IP.  in contains the connection\r\n         * socket's descriptor. Since the client connection information is\r\n         * not available yet, wsi still pointing to the main server socket.\r\n         * Return non-zero to terminate the connection before sending or\r\n         * receiving anything. Because this happens immediately after the\r\n         * network connection from the client, there's no websocket protocol\r\n         * selected yet so this callback is issued only to protocol 0. */\r\n\r\n        /* ---------------------------------------------------------------------\r\n         * ----- Callbacks related to external poll loop integration  -----\r\n         */\r\n\r\n        LWS_CALLBACK_GET_THREAD_ID = 31,\r\n        /**< lws can accept callback when writable requests from other\r\n         * threads, if you implement this callback and return an opaque\r\n         * current thread ID integer. */\r\n\r\n        /* external poll() management support */\r\n        LWS_CALLBACK_ADD_POLL_FD = 32,\r\n        /**< lws normally deals with its poll() or other event loop\r\n         * internally, but in the case you are integrating with another\r\n         * server you will need to have lws sockets share a\r\n         * polling array with the other server.  This and the other\r\n         * POLL_FD related callbacks let you put your specialized\r\n         * poll array interface code in the callback for protocol 0, the\r\n         * first protocol you support, usually the HTTP protocol in the\r\n         * serving case.\r\n         * This callback happens when a socket needs to be\r\n         * added to the polling loop: in points to a struct\r\n         * lws_pollargs; the fd member of the struct is the file\r\n         * descriptor, and events contains the active events\r\n         *\r\n         * If you are using the internal lws polling / event loop\r\n         * you can just ignore these callbacks. */\r\n\r\n        LWS_CALLBACK_DEL_POLL_FD = 33,\r\n        /**< This callback happens when a socket descriptor\r\n         * needs to be removed from an external polling array.  in is\r\n         * again the struct lws_pollargs containing the fd member\r\n         * to be removed.  If you are using the internal polling\r\n         * loop, you can just ignore it. */\r\n\r\n        LWS_CALLBACK_CHANGE_MODE_POLL_FD = 34,\r\n        /**< This callback happens when lws wants to modify the events for\r\n         * a connection.\r\n         * in is the struct lws_pollargs with the fd to change.\r\n         * The new event mask is in events member and the old mask is in\r\n         * the prev_events member.\r\n         * If you are using the internal polling loop, you can just ignore\r\n         * it. */\r\n\r\n        LWS_CALLBACK_LOCK_POLL = 35,\r\n        /**< These allow the external poll changes driven\r\n         * by lws to participate in an external thread locking\r\n         * scheme around the changes, so the whole thing is threadsafe.\r\n         * These are called around three activities in the library,\r\n         *\t- inserting a new wsi in the wsi / fd table (len=1)\r\n         *\t- deleting a wsi from the wsi / fd table (len=1)\r\n         *\t- changing a wsi's POLLIN/OUT state (len=0)\r\n         * Locking and unlocking external synchronization objects when\r\n         * len == 1 allows external threads to be synchronized against\r\n         * wsi lifecycle changes if it acquires the same lock for the\r\n         * duration of wsi dereference from the other thread context. */\r\n\r\n        LWS_CALLBACK_UNLOCK_POLL = 36,\r\n        /**< See LWS_CALLBACK_LOCK_POLL, ignore if using lws internal poll */\r\n\r\n        /* ---------------------------------------------------------------------\r\n         * ----- Callbacks related to CGI serving -----\r\n         */\r\n\r\n        LWS_CALLBACK_CGI = 40,\r\n        /**< CGI: CGI IO events on stdin / out / err are sent here on\r\n         * protocols[0].  The provided `lws_callback_http_dummy()`\r\n         * handles this and the callback should be directed there if\r\n         * you use CGI. */\r\n\r\n        LWS_CALLBACK_CGI_TERMINATED = 41,\r\n        /**< CGI: The related CGI process ended, this is called before\r\n         * the wsi is closed.  Used to, eg, terminate chunking.\r\n         * The provided `lws_callback_http_dummy()`\r\n         * handles this and the callback should be directed there if\r\n         * you use CGI.  The child PID that terminated is in len. */\r\n\r\n        LWS_CALLBACK_CGI_STDIN_DATA = 42,\r\n        /**< CGI: Data is, to be sent to the CGI process stdin, eg from\r\n         * a POST body.  The provided `lws_callback_http_dummy()`\r\n         * handles this and the callback should be directed there if\r\n         * you use CGI. */\r\n\r\n        LWS_CALLBACK_CGI_STDIN_COMPLETED = 43,\r\n        /**< CGI: no more stdin is coming.  The provided\r\n         * `lws_callback_http_dummy()` handles this and the callback\r\n         * should be directed there if you use CGI. */\r\n\r\n        LWS_CALLBACK_CGI_PROCESS_ATTACH = 70,\r\n        /**< CGI: Sent when the CGI process is spawned for the wsi.  The\r\n         * len parameter is the PID of the child process */\r\n\r\n        /* ---------------------------------------------------------------------\r\n         * ----- Callbacks related to Generic Sessions -----\r\n         */\r\n\r\n        LWS_CALLBACK_SESSION_INFO = 54,\r\n        /**< This is only generated by user code using generic sessions.\r\n         * It's used to get a `struct lws_session_info` filled in by\r\n         * generic sessions with information about the logged-in user.\r\n         * See the messageboard sample for an example of how to use. */\r\n\r\n        LWS_CALLBACK_GS_EVENT = 55,\r\n        /**< Indicates an event happened to the Generic Sessions session.\r\n         * `in` contains a `struct lws_gs_event_args` describing the event. */\r\n\r\n        LWS_CALLBACK_HTTP_PMO = 56,\r\n        /**< per-mount options for this connection, called before\r\n         * the normal LWS_CALLBACK_HTTP when the mount has per-mount\r\n         * options.\r\n         */\r\n\r\n        /* ---------------------------------------------------------------------\r\n         * ----- Callbacks related to RAW sockets -----\r\n         */\r\n\r\n        LWS_CALLBACK_RAW_RX = 59,\r\n        /**< RAW mode connection RX */\r\n\r\n        LWS_CALLBACK_RAW_CLOSE = 60,\r\n        /**< RAW mode connection is closing */\r\n\r\n        LWS_CALLBACK_RAW_WRITEABLE = 61,\r\n        /**< RAW mode connection may be written */\r\n\r\n        LWS_CALLBACK_RAW_ADOPT = 62,\r\n        /**< RAW mode connection was adopted (equivalent to 'wsi created') */\r\n\r\n        /* ---------------------------------------------------------------------\r\n         * ----- Callbacks related to RAW file handles -----\r\n         */\r\n\r\n        LWS_CALLBACK_RAW_ADOPT_FILE = 63,\r\n        /**< RAW mode file was adopted (equivalent to 'wsi created') */\r\n\r\n        LWS_CALLBACK_RAW_RX_FILE = 64,\r\n        /**< This is the indication the RAW mode file has something to read.\r\n         *   This doesn't actually do the read of the file and len is always\r\n         *   0... your code should do the read having been informed there is\r\n         *   something to read now. */\r\n\r\n        LWS_CALLBACK_RAW_WRITEABLE_FILE = 65,\r\n        /**< RAW mode file is writeable */\r\n\r\n        LWS_CALLBACK_RAW_CLOSE_FILE = 66,\r\n        /**< RAW mode wsi that adopted a file is closing */\r\n\r\n        /* ---------------------------------------------------------------------\r\n         * ----- Callbacks related to generic wsi events -----\r\n         */\r\n\r\n        LWS_CALLBACK_TIMER = 73,\r\n        /**< When the time elapsed after a call to\r\n         * lws_set_timer_usecs(wsi, usecs) is up, the wsi will get one of\r\n         * these callbacks.  The deadline can be continuously extended into the\r\n         * future by later calls to lws_set_timer_usecs() before the deadline\r\n         * expires, or cancelled by lws_set_timer_usecs(wsi, -1);\r\n         * See the note on lws_set_timer_usecs() about which event loops are\r\n         * supported. */\r\n\r\n        LWS_CALLBACK_EVENT_WAIT_CANCELLED = 71,\r\n        /**< This is sent to every protocol of every vhost in response\r\n         * to lws_cancel_service() or lws_cancel_service_pt().  This\r\n         * callback is serialized in the lws event loop normally, even\r\n         * if the lws_cancel_service[_pt]() call was from a different\r\n         * thread. */\r\n\r\n        LWS_CALLBACK_CHILD_CLOSING = 69,\r\n        /**< Sent to parent to notify them a child is closing / being\r\n         * destroyed.  in is the child wsi.\r\n         */\r\n\r\n        LWS_CALLBACK_CHILD_WRITE_VIA_PARENT = 68,\r\n        /**< Child has been marked with parent_carries_io attribute, so\r\n         * lws_write directs the to this callback at the parent,\r\n         * in is a struct lws_write_passthru containing the args\r\n         * the lws_write() was called with.\r\n         */\r\n\r\n        /* ---------------------------------------------------------------------\r\n         * ----- Callbacks related to TLS certificate management -----\r\n         */\r\n\r\n        LWS_CALLBACK_VHOST_CERT_AGING = 72,\r\n        /**< When a vhost TLS cert has its expiry checked, this callback\r\n         * is broadcast to every protocol of every vhost in case the\r\n         * protocol wants to take some action with this information.\r\n         * \\p in is a pointer to a struct lws_acme_cert_aging_args,\r\n         * and \\p len is the number of days left before it expires, as\r\n         * a (ssize_t).  In the struct lws_acme_cert_aging_args, vh\r\n         * points to the vhost the cert aging information applies to,\r\n         * and element_overrides[] is an optional way to update information\r\n         * from the pvos... NULL in an index means use the information from\r\n         * from the pvo for the cert renewal, non-NULL in the array index\r\n         * means use that pointer instead for the index. */\r\n\r\n        LWS_CALLBACK_VHOST_CERT_UPDATE = 74,\r\n        /**< When a vhost TLS cert is being updated, progress is\r\n         * reported to the vhost in question here, including completion\r\n         * and failure.  in points to optional JSON, and len represents the\r\n         * connection state using enum lws_cert_update_state */\r\n\r\n\r\n        /****** add new things just above ---^ ******/\r\n\r\n        LWS_CALLBACK_USER = 1000,\r\n        /*  user code can use any including above without fear of clashes */\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/Native/lws_callback_reasons.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 7c27b17d74c39764e9c320635880e75c\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/Native/lws_close_status.cs",
    "content": "﻿#if !UNITY_WEBGL \r\nnamespace QuickJS.Extra.WebSockets\r\n{\r\n    /*\r\n     * NOTE: These public enums are part of the abi.  If you want to add one,\r\n     * add it at where specified so existing users are unaffected.\r\n     */\r\n    /** enum lws_close_status - RFC6455 close status codes */\r\n    public enum lws_close_status\r\n    {\r\n        LWS_CLOSE_STATUS_NOSTATUS = 0,\r\n        LWS_CLOSE_STATUS_NORMAL = 1000,\r\n\r\n        /**< 1000 indicates a normal closure, meaning that the purpose for\r\n      which the connection was established has been fulfilled. */\r\n        LWS_CLOSE_STATUS_GOINGAWAY = 1001,\r\n\r\n        /**< 1001 indicates that an endpoint is \"going away\", such as a server\r\n      going down or a browser having navigated away from a page. */\r\n        LWS_CLOSE_STATUS_PROTOCOL_ERR = 1002,\r\n\r\n        /**< 1002 indicates that an endpoint is terminating the connection due\r\n      to a protocol error. */\r\n        LWS_CLOSE_STATUS_UNACCEPTABLE_OPCODE = 1003,\r\n\r\n        /**< 1003 indicates that an endpoint is terminating the connection\r\n      because it has received a type of data it cannot accept (e.g., an\r\n      endpoint that understands only text data MAY send this if it\r\n      receives a binary message). */\r\n        LWS_CLOSE_STATUS_RESERVED = 1004,\r\n\r\n        /**< Reserved.  The specific meaning might be defined in the future. */\r\n        LWS_CLOSE_STATUS_NO_STATUS = 1005,\r\n\r\n        /**< 1005 is a reserved value and MUST NOT be set as a status code in a\r\n      Close control frame by an endpoint.  It is designated for use in\r\n      applications expecting a status code to indicate that no status\r\n      code was actually present. */\r\n        LWS_CLOSE_STATUS_ABNORMAL_CLOSE = 1006,\r\n\r\n        /**< 1006 is a reserved value and MUST NOT be set as a status code in a\r\n      Close control frame by an endpoint.  It is designated for use in\r\n      applications expecting a status code to indicate that the\r\n      connection was closed abnormally, e.g., without sending or\r\n      receiving a Close control frame. */\r\n        LWS_CLOSE_STATUS_INVALID_PAYLOAD = 1007,\r\n\r\n        /**< 1007 indicates that an endpoint is terminating the connection\r\n      because it has received data within a message that was not\r\n      consistent with the type of the message (e.g., non-UTF-8 [RFC3629]\r\n      data within a text message). */\r\n        LWS_CLOSE_STATUS_POLICY_VIOLATION = 1008,\r\n\r\n        /**< 1008 indicates that an endpoint is terminating the connection\r\n      because it has received a message that violates its policy.  This\r\n      is a generic status code that can be returned when there is no\r\n      other more suitable status code (e.g., 1003 or 1009) or if there\r\n      is a need to hide specific details about the policy. */\r\n        LWS_CLOSE_STATUS_MESSAGE_TOO_LARGE = 1009,\r\n\r\n        /**< 1009 indicates that an endpoint is terminating the connection\r\n      because it has received a message that is too big for it to\r\n      process. */\r\n        LWS_CLOSE_STATUS_EXTENSION_REQUIRED = 1010,\r\n\r\n        /**< 1010 indicates that an endpoint (client) is terminating the\r\n      connection because it has expected the server to negotiate one or\r\n      more extension, but the server didn't return them in the response\r\n      message of the WebSocket handshake.  The list of extensions that\r\n      are needed SHOULD appear in the /reason/ part of the Close frame.\r\n      Note that this status code is not used by the server, because it\r\n      can fail the WebSocket handshake instead */\r\n        LWS_CLOSE_STATUS_UNEXPECTED_CONDITION = 1011,\r\n\r\n        /**< 1011 indicates that a server is terminating the connection because\r\n      it encountered an unexpected condition that prevented it from\r\n      fulfilling the request. */\r\n        LWS_CLOSE_STATUS_TLS_FAILURE = 1015,\r\n\r\n        /**< 1015 is a reserved value and MUST NOT be set as a status code in a\r\n      Close control frame by an endpoint.  It is designated for use in\r\n      applications expecting a status code to indicate that the\r\n      connection was closed due to a failure to perform a TLS handshake\r\n      (e.g., the server certificate can't be verified). */\r\n        LWS_CLOSE_STATUS_CLIENT_TRANSACTION_DONE = 2000,\r\n\r\n        /****** add new things just above ---^ ******/\r\n\r\n        LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY = 9999,\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/Native/lws_close_status.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: c6506c4d2bd543998e3ff7e0684e5115\r\ntimeCreated: 1592480247"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/Native/lws_context.cs",
    "content": "#if !UNITY_WEBGL \r\nusing System;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Extra.WebSockets\r\n{\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public unsafe struct lws_context\r\n    {\r\n        public static readonly lws_context Null = new lws_context();\r\n\r\n        public void* _value;\r\n\r\n        public bool IsValid()\r\n        {\r\n            return _value != (void*)0;\r\n        }\r\n        \r\n        public override int GetHashCode()\r\n        {\r\n            return (int) _value;\r\n        }\r\n\r\n        public bool Equals(lws_context other)\r\n        {\r\n            return this == other;\r\n        }\r\n\r\n        public override bool Equals(object obj)\r\n        {\r\n            if (obj is lws_context)\r\n            {\r\n                var other = (lws_context)obj;\r\n                return this == other;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public override string ToString()\r\n        {\r\n            return string.Format(\"lws_context:{0:X}\", (ulong) _value);\r\n        }\r\n\r\n        public static bool operator ==(lws_context a, lws_context b)\r\n        {\r\n            return a._value == b._value;\r\n        }\r\n\r\n        public static bool operator !=(lws_context a, lws_context b)\r\n        {\r\n            return !(a == b);\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/Native/lws_context.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 1a5a23344189e4044acb637d33fae55c\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/Native/lws_write_protocol.cs",
    "content": "#if !UNITY_WEBGL \r\nnamespace QuickJS.Extra.WebSockets\r\n{\r\n    /*\r\n    * NOTE: These public enums are part of the abi.  If you want to add one,\r\n    * add it at where specified so existing users are unaffected.\r\n    */\r\n    public enum lws_write_protocol\r\n    {\r\n        LWS_WRITE_TEXT = 0,\r\n        /**< Send a ws TEXT message,the pointer must have LWS_PRE valid\r\n         * memory behind it.  The receiver expects only valid utf-8 in the\r\n         * payload */\r\n        LWS_WRITE_BINARY = 1,\r\n        /**< Send a ws BINARY message, the pointer must have LWS_PRE valid\r\n         * memory behind it.  Any sequence of bytes is valid */\r\n        LWS_WRITE_CONTINUATION = 2,\r\n        /**< Continue a previous ws message, the pointer must have LWS_PRE valid\r\n         * memory behind it */\r\n        LWS_WRITE_HTTP = 3,\r\n        /**< Send HTTP content */\r\n\r\n        /* LWS_WRITE_CLOSE is handled by lws_close_reason() */\r\n        LWS_WRITE_PING = 5,\r\n        LWS_WRITE_PONG = 6,\r\n\r\n        /* Same as write_http but we know this write ends the transaction */\r\n        LWS_WRITE_HTTP_FINAL = 7,\r\n\r\n        /* HTTP2 */\r\n\r\n        LWS_WRITE_HTTP_HEADERS = 8,\r\n        /**< Send http headers (http2 encodes this payload and LWS_WRITE_HTTP\r\n         * payload differently, http 1.x links also handle this correctly. so\r\n         * to be compatible with both in the future,header response part should\r\n         * be sent using this regardless of http version expected)\r\n         */\r\n        LWS_WRITE_HTTP_HEADERS_CONTINUATION = 9,\r\n        /**< Continuation of http/2 headers\r\n         */\r\n\r\n        /****** add new things just above ---^ ******/\r\n\r\n        /* flags */\r\n\r\n        LWS_WRITE_NO_FIN = 0x40,\r\n        /**< This part of the message is not the end of the message */\r\n\r\n        LWS_WRITE_H2_STREAM_END = 0x80,\r\n        /**< Flag indicates this packet should go out with STREAM_END if h2\r\n         * STREAM_END is allowed on DATA or HEADERS.\r\n         */\r\n\r\n        LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80\r\n        /* client packet payload goes out on wire unmunged\r\n         * only useful for security tests since normal servers cannot\r\n         * decode the content if used */\r\n    };\r\n}\r\n#endif"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/Native/lws_write_protocol.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 449d09bec1c452d4a8422e755b7c1815\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/Native/ulws_ssl_type.cs",
    "content": "#if !UNITY_WEBGL \r\nnamespace QuickJS.Extra.WebSockets\r\n{\r\n    public enum ulws_ssl_type\r\n    {\r\n        ULWS_DEFAULT = 0,\r\n        ULWS_USE_SSL = 1,\r\n        ULWS_USE_SSL_ALLOW_SELFSIGNED = 2,\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/Native/ulws_ssl_type.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 9c0a62248d842a0429cb702ec08d0de6\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/Native.meta",
    "content": "fileFormatVersion: 2\r\nguid: 52e8b22d5c5aa914a83e81133c656694\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/WebSocket.cs",
    "content": "#if !UNITY_WEBGL\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Net;\r\nusing System.Net.Sockets;\r\nusing System.Threading;\r\nusing System.Text;\r\n\r\nnamespace QuickJS.Extra\r\n{\r\n    using QuickJS;\r\n    using QuickJS.IO;\r\n    using QuickJS.Errors;\r\n    using QuickJS.Native;\r\n    using QuickJS.Binding;\r\n    using QuickJS.Extra.WebSockets;\r\n\r\n    /*\r\n    constructor:\r\n        new WebSocket(url, [protocol]);\r\n            url: 要连接的URL\r\n            protocol: 一个协议字符串或者一个包含协议字符串的数组。\r\n    property:\r\n        x binaryType \r\n        bufferedAmount\r\n        x protocol\r\n        url\r\n        readyState\r\n            0 (WebSocket.CONNECTING)\r\n                正在链接中\r\n            1 (WebSocket.OPEN)\r\n                已经链接并且可以通讯\r\n            2 (WebSocket.CLOSING)\r\n                连接正在关闭\r\n            3 (WebSocket.CLOSED)\r\n                连接已关闭或者没有链接成功 \r\n        onopen(event)\r\n        onmessage(event)\r\n        onerror(event)\r\n        onclose(event)\r\n    event:\r\n        x 'message'\r\n    method: \r\n        send\r\n        close\r\n        x addEventListener('message', func)\r\n    */\r\n    //TODO: 用 dotnet WebSocket 代替 lws\r\n    public class WebSocket : Values, IDisposable, Utils.IObjectCollectionEntry\r\n    {\r\n        private enum ReadyState\r\n        {\r\n            CONNECTING = 0,\r\n            OPEN = 1,\r\n            CLOSING = 2,\r\n            CLOSED = 3,\r\n\r\n            _CONSTRUCTED = -1,\r\n            _DNS = -2,\r\n        }\r\n        private struct Packet\r\n        {\r\n            public bool is_binary;\r\n            public ByteBuffer buffer;\r\n\r\n            public Packet(bool is_binary, ByteBuffer buffer)\r\n            {\r\n                this.is_binary = is_binary;\r\n                this.buffer = buffer;\r\n            }\r\n\r\n            public void Release()\r\n            {\r\n                if (buffer != null)\r\n                {\r\n                    buffer.Release();\r\n                    buffer = null;\r\n                }\r\n            }\r\n        }\r\n\r\n        private static ReaderWriterLockSlim _rwlock = new ReaderWriterLockSlim();\r\n        private static List<WebSocket> _websockets = new List<WebSocket>();\r\n\r\n        private static WebSocket GetWebSocket(lws_context context)\r\n        {\r\n            try\r\n            {\r\n                _rwlock.EnterReadLock();\r\n                var count = _websockets.Count;\r\n                for (var i = 0; i < count; i++)\r\n                {\r\n                    var websocket = _websockets[i];\r\n                    if (websocket._context == context)\r\n                    {\r\n                        return websocket;\r\n                    }\r\n                }\r\n                return null;\r\n            }\r\n            finally\r\n            {\r\n                _rwlock.ExitReadLock();\r\n            }\r\n        }\r\n\r\n        private Utils.ObjectCollection.Handle _handle;\r\n        private lws _wsi;\r\n        private lws_context _context;\r\n        private ReadyState _readyState;\r\n        private int _bufferedAmount;\r\n        private bool _is_closing;\r\n        private bool _is_servicing;\r\n        private bool _is_polling;\r\n        private bool _is_context_destroying;\r\n        private bool _is_context_destroyed;\r\n        private Queue<Packet> _pending = new Queue<Packet>();\r\n\r\n        private ByteBuffer _buffer;\r\n\r\n        private JSValue _jsThis; // dangeous reference holder (no ref count)\r\n        private JSContext _jsContext; // dangeous reference holder\r\n\r\n        private string _url;\r\n        private string _protocol;\r\n        private string[] _protocols;\r\n\r\n        [MonoPInvokeCallback(typeof(lws_callback_function))]\r\n        public static int _callback(lws wsi, lws_callback_reasons reason, IntPtr user, IntPtr @in, size_t len)\r\n        {\r\n            var context = WSApi.lws_get_context(wsi);\r\n            var websocket = GetWebSocket(context);\r\n            if (websocket == null)\r\n            {\r\n                return -1;\r\n            }\r\n\r\n            switch (reason)\r\n            {\r\n                case lws_callback_reasons.LWS_CALLBACK_CHANGE_MODE_POLL_FD:\r\n                    {\r\n                        return 0;\r\n                    }\r\n                case lws_callback_reasons.LWS_CALLBACK_CLIENT_RECEIVE:\r\n                    {\r\n                        websocket._is_servicing = true;\r\n                        return websocket.OnReceive(@in, len);\r\n                    }\r\n                case lws_callback_reasons.LWS_CALLBACK_CLIENT_WRITEABLE:\r\n                    {\r\n                        websocket._is_servicing = true;\r\n                        if (websocket._is_closing)\r\n                        {\r\n                            WSApi.lws_close_reason(wsi, lws_close_status.LWS_CLOSE_STATUS_NORMAL, \"\");\r\n                            return -1;\r\n                        }\r\n                        websocket.OnWrite();\r\n                        return 0;\r\n                    }\r\n                case lws_callback_reasons.LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS:\r\n                    {\r\n                        return 0;\r\n                    }\r\n                case lws_callback_reasons.LWS_CALLBACK_CLIENT_ESTABLISHED:\r\n                    {\r\n                        websocket._is_servicing = true;\r\n                        websocket._wsi = wsi;\r\n                        websocket.OnConnect(); // _on_connect(websocket, lws_get_protocol(wsi)->name);\r\n                        return 0;\r\n                    }\r\n                case lws_callback_reasons.LWS_CALLBACK_CLIENT_CONNECTION_ERROR:\r\n                    {\r\n                        websocket._is_servicing = true;\r\n                        websocket.OnError(@in, len);\r\n                        websocket.Destroy();\r\n                        return -1;\r\n                    }\r\n                case lws_callback_reasons.LWS_CALLBACK_WS_PEER_INITIATED_CLOSE:\r\n                    {\r\n                        websocket._is_servicing = true;\r\n                        websocket.OnCloseRequest(@in, len);\r\n                        return 0;\r\n                    }\r\n                case lws_callback_reasons.LWS_CALLBACK_CLIENT_CLOSED:\r\n                    {\r\n                        websocket.SetClose(); // _duk_lws_close(websocket);\r\n                        websocket.Destroy();\r\n                        websocket.OnClose();\r\n                        return 0;\r\n                    }\r\n                default:\r\n                    {\r\n                        return 0;\r\n                    }\r\n            }\r\n        }\r\n\r\n        private static unsafe bool TryParseReason(IntPtr @in, size_t len, out int code, out string reason)\r\n        {\r\n            if (len < 2)\r\n            {\r\n                code = 0;\r\n                reason = null;\r\n                return false;\r\n            }\r\n            byte* ptr = (byte*)@in;\r\n            code = ptr[0] << 8 | ptr[1];\r\n            try\r\n            {\r\n                reason = Encoding.UTF8.GetString(&ptr[2], len - 2);\r\n            }\r\n            catch (Exception)\r\n            {\r\n                reason = null;\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n        private void SetReadyState(ReadyState readyState)\r\n        {\r\n            _readyState = readyState;\r\n        }\r\n\r\n        private void SetClose()\r\n        {\r\n            if (_wsi.IsValid())\r\n            {\r\n                _is_closing = true;\r\n                SetReadyState(ReadyState.CLOSING);\r\n                WSApi.lws_callback_on_writable(_wsi);\r\n                _wsi = lws.Null;\r\n            }\r\n            else\r\n            {\r\n                SetReadyState(ReadyState.CLOSED);\r\n            }\r\n        }\r\n\r\n        #region IObjectCollectionEntry implementation\r\n        public void OnCollectionReleased()\r\n        {\r\n            Destroy();\r\n        }\r\n        #endregion\r\n\r\n        // _duk_lws_destroy\r\n        private void Destroy()\r\n        {\r\n            if (_is_context_destroyed)\r\n            {\r\n                return;\r\n            }\r\n\r\n            if (_is_polling)\r\n            {\r\n                _is_context_destroying = true;\r\n                return;\r\n            }\r\n\r\n            SetReadyState(ReadyState.CLOSED);\r\n            _is_context_destroyed = true;\r\n            if (_context.IsValid())\r\n            {\r\n                // WSApi.ulws_destroy(_context);\r\n                _context = lws_context.Null;\r\n            }\r\n\r\n            while (_pending.Count > 0)\r\n            {\r\n                var packet = _pending.Dequeue();\r\n                packet.Release();\r\n            }\r\n            _bufferedAmount = 0;\r\n\r\n            if (_buffer != null)\r\n            {\r\n                _buffer.Release();\r\n                _buffer = null;\r\n            }\r\n            var runtime = ScriptEngine.GetRuntime(_jsContext);\r\n            if (runtime != null)\r\n            {\r\n                runtime.OnUpdate -= Update;\r\n                runtime.RemoveManagedObject(_handle);\r\n                var cache = runtime.GetObjectCache();\r\n                cache.RemoveObject(JSApi.JSB_FreePayload(_jsContext, _jsThis));\r\n            }\r\n\r\n            _jsContext = JSContext.Null;\r\n            _jsThis = JSApi.JS_UNDEFINED;\r\n            _rwlock.EnterWriteLock();\r\n            _websockets.Remove(this);\r\n            _rwlock.ExitWriteLock();\r\n        }\r\n\r\n        private void OnWrite()\r\n        {\r\n            if (_pending.Count > 0)\r\n            {\r\n                var packet = _pending.Dequeue();\r\n                var protocol = packet.is_binary ? lws_write_protocol.LWS_WRITE_BINARY : lws_write_protocol.LWS_WRITE_TEXT;\r\n                var len = packet.buffer.writerIndex - WSApi.LWS_PRE;\r\n\r\n                unsafe\r\n                {\r\n                    fixed (byte* buf = packet.buffer.data)\r\n                    {\r\n                        WSApi.lws_write(_wsi, &buf[WSApi.LWS_PRE], len, protocol);\r\n                    }\r\n                }\r\n\r\n                _bufferedAmount -= len;\r\n                packet.Release();\r\n                if (_pending.Count > 0)\r\n                {\r\n                    WSApi.lws_callback_on_writable(_wsi);\r\n                }\r\n            }\r\n        }\r\n\r\n        private void Update()\r\n        {\r\n            switch (_readyState)\r\n            {\r\n                case ReadyState.OPEN:\r\n                case ReadyState.CLOSING:\r\n                case ReadyState.CONNECTING:\r\n                    if (!_context.IsValid())\r\n                    {\r\n                        return;\r\n                    }\r\n\r\n                    _is_polling = true;\r\n                    do\r\n                    {\r\n                        _is_servicing = false;\r\n                        WSApi.lws_service(_context, 0);\r\n                    } while (_is_servicing);\r\n                    _is_polling = false;\r\n                    break;\r\n                case ReadyState._CONSTRUCTED:\r\n                    Connect();\r\n                    break;\r\n            }\r\n\r\n            if (_is_context_destroying)\r\n            {\r\n                Destroy();\r\n            }\r\n        }\r\n\r\n        private void OnClose()\r\n        {\r\n            SetReadyState(ReadyState.CLOSED);\r\n            CallScript(\"onclose\", JSApi.JS_UNDEFINED);\r\n        }\r\n\r\n        // 已建立连接\r\n        private void OnConnect()\r\n        {\r\n            SetReadyState(ReadyState.OPEN);\r\n            CallScript(\"onopen\", JSApi.JS_UNDEFINED);\r\n        }\r\n\r\n        private void OnError(IntPtr @in, size_t len)\r\n        {\r\n            var val = JSApi.JS_UNDEFINED;\r\n            if (len > 0)\r\n            {\r\n                unsafe\r\n                {\r\n                    byte* ptr = (byte*)@in;\r\n                    if (ptr[len] == 0)\r\n                    {\r\n                        val = JSApi.JS_NewString(_jsContext, ptr);\r\n                        if (val.IsException())\r\n                        {\r\n                            _jsContext.print_exception();\r\n                            val = JSApi.JS_UNDEFINED;\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n            else\r\n            {\r\n                val = _jsContext.NewString(\"connection timeout\");\r\n                if (val.IsException())\r\n                {\r\n                    _jsContext.print_exception();\r\n                    val = JSApi.JS_UNDEFINED;\r\n                }\r\n            }\r\n            CallScript(\"onerror\", val);\r\n            JSApi.JS_FreeValue(_jsContext, val);\r\n        }\r\n\r\n        private void OnError(Exception exception)\r\n        {\r\n            var val = _jsContext.NewString(exception.ToString());\r\n            if (val.IsException())\r\n            {\r\n                _jsContext.print_exception();\r\n                val = JSApi.JS_UNDEFINED;\r\n            }\r\n            CallScript(\"onerror\", val);\r\n            JSApi.JS_FreeValue(_jsContext, val);\r\n\r\n        }\r\n\r\n        private void OnCloseRequest(IntPtr @in, size_t len)\r\n        {\r\n            int code;\r\n            string reason;\r\n            if (TryParseReason(@in, len, out code, out reason))\r\n            {\r\n                var val = JSApi.JS_NewInt32(_jsContext, code);\r\n                CallScript(\"oncloserequest\", val);\r\n                JSApi.JS_FreeValue(_jsContext, val);\r\n            }\r\n        }\r\n\r\n        // return -1 if error\r\n        private int OnReceive(IntPtr @in, size_t len)\r\n        {\r\n            if (WSApi.lws_is_first_fragment(_wsi) == 1)\r\n            {\r\n                _buffer.writerIndex = 0;\r\n            }\r\n            _buffer.WriteBytes(@in, len);\r\n\r\n            if (WSApi.lws_is_final_fragment(_wsi) == 1)\r\n            {\r\n                var is_binary = WSApi.lws_frame_is_binary(_wsi) == 1;\r\n                if (is_binary)\r\n                {\r\n                    unsafe\r\n                    {\r\n                        fixed (byte* ptr = _buffer.data)\r\n                        {\r\n                            var val = JSApi.JS_NewArrayBufferCopy(_jsContext, ptr, _buffer.writerIndex);\r\n                            CallScript(\"onmessage\", val);\r\n                            JSApi.JS_FreeValue(_jsContext, val);\r\n                        }\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    unsafe\r\n                    {\r\n                        _buffer.WriteByte(0); // make it null terminated\r\n                        fixed (byte* ptr = _buffer.data)\r\n                        {\r\n                            var val = JSApi.JS_NewString(_jsContext, ptr);\r\n                            CallScript(\"onmessage\", val);\r\n                            JSApi.JS_FreeValue(_jsContext, val);\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            return 0;\r\n        }\r\n\r\n        private unsafe void CallScript(string eventName, JSValue eventArg)\r\n        {\r\n            if (eventArg.IsException())\r\n            {\r\n                _jsContext.print_exception();\r\n                return;\r\n            }\r\n            var scriptContext = ScriptEngine.GetContext(_jsContext);\r\n            if (scriptContext != null)\r\n            {\r\n                var eventFunc = JSApi.JS_GetProperty(_jsContext, _jsThis, scriptContext.GetAtom(eventName));\r\n                if (JSApi.JS_IsFunction(_jsContext, eventFunc) != 1)\r\n                {\r\n                    if (eventFunc.IsException())\r\n                    {\r\n                        _jsContext.print_exception();\r\n                    }\r\n                    else\r\n                    {\r\n                        JSApi.JS_FreeValue(_jsContext, eventFunc);\r\n                    }\r\n                    return;\r\n                }\r\n                var args = stackalloc JSValue[1];\r\n                args[0] = eventArg;\r\n                var rval = JSApi.JS_Call(_jsContext, eventFunc, _jsThis, 1, args);\r\n                if (rval.IsException())\r\n                {\r\n                    _jsContext.print_exception();\r\n                }\r\n                else\r\n                {\r\n                    JSApi.JS_FreeValue(_jsContext, rval);\r\n                }\r\n                JSApi.JS_FreeValue(_jsContext, eventFunc);\r\n            }\r\n        }\r\n\r\n        // buffer: buffer for recv\r\n        private WebSocket(ByteBuffer buffer, string url, List<string> protocols)\r\n        {\r\n            _url = url;\r\n            _buffer = buffer;\r\n            _protocols = protocols != null ? protocols.ToArray() : new string[] { \"\" };\r\n\r\n            _rwlock.EnterWriteLock();\r\n            _websockets.Add(this);\r\n            _rwlock.ExitWriteLock();\r\n\r\n            do\r\n            {\r\n                if (_protocols != null && _protocols.Length > 0)\r\n                {\r\n                    _context = WSApi.ulws_create(_protocols[0], _callback, 1024 * 4, 1024 * 4);\r\n                    if (_context.IsValid())\r\n                    {\r\n                        SetReadyState(ReadyState._CONSTRUCTED);\r\n                        break;\r\n                    }\r\n                }\r\n                SetReadyState(ReadyState.CLOSED);\r\n            } while (false);\r\n        }\r\n\r\n        private void _Transfer(JSContext ctx, JSValue value)\r\n        {\r\n            _jsContext = ctx;\r\n            _jsThis = value;\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            var runtime = context.GetRuntime();\r\n\r\n            runtime.OnUpdate += Update;\r\n            runtime.AddManagedObject(this, out _handle);\r\n            JSApi.JS_SetProperty(ctx, value, context.GetAtom(\"onopen\"), JSApi.JS_NULL);\r\n            JSApi.JS_SetProperty(ctx, value, context.GetAtom(\"onclose\"), JSApi.JS_NULL);\r\n            JSApi.JS_SetProperty(ctx, value, context.GetAtom(\"onerror\"), JSApi.JS_NULL);\r\n            JSApi.JS_SetProperty(ctx, value, context.GetAtom(\"onmessage\"), JSApi.JS_NULL);\r\n            JSApi.JS_SetProperty(ctx, value, context.GetAtom(\"url\"), ctx.NewString(_url));\r\n        }\r\n\r\n        private async void Connect()\r\n        {\r\n            if (_readyState != ReadyState._CONSTRUCTED)\r\n            {\r\n                return;\r\n            }\r\n            SetReadyState(ReadyState._DNS);\r\n            var uri = new Uri(_url);\r\n            var ssl_type = uri.Scheme == \"ws\" ? ulws_ssl_type.ULWS_DEFAULT : ulws_ssl_type.ULWS_USE_SSL_ALLOW_SELFSIGNED;\r\n            var protocol_names = QuickJS.Utils.TextUtils.GetNullTerminatedBytes(string.Join(\",\", _protocols));\r\n            var path = QuickJS.Utils.TextUtils.GetNullTerminatedBytes(uri.AbsolutePath);\r\n            var host = QuickJS.Utils.TextUtils.GetNullTerminatedBytes(uri.DnsSafeHost);\r\n            var port = uri.Port;\r\n            switch (uri.HostNameType)\r\n            {\r\n                case UriHostNameType.IPv4:\r\n                case UriHostNameType.IPv6:\r\n                    {\r\n                        var address = QuickJS.Utils.TextUtils.GetNullTerminatedBytes(uri.DnsSafeHost);\r\n                        SetReadyState(ReadyState.CONNECTING);\r\n                        unsafe\r\n                        {\r\n                            fixed (byte* protocol_names_ptr = protocol_names)\r\n                            fixed (byte* host_ptr = host)\r\n                            fixed (byte* address_ptr = address)\r\n                            fixed (byte* path_ptr = path)\r\n                            {\r\n                                WSApi.ulws_connect(_context, protocol_names_ptr, ssl_type, host_ptr, address_ptr, path_ptr, port);\r\n                            }\r\n                        }\r\n                    }\r\n                    break;\r\n                default:\r\n                    {\r\n                        var entry = await Dns.GetHostEntryAsync(uri.DnsSafeHost);\r\n                        if (_readyState != ReadyState._DNS)\r\n                        {\r\n                            // already closed\r\n                            return;\r\n                        }\r\n                        SetReadyState(ReadyState.CONNECTING);\r\n                        try\r\n                        {\r\n                            var ipAddress = Select(entry.AddressList);\r\n                            var address = QuickJS.Utils.TextUtils.GetNullTerminatedBytes(ipAddress.ToString());\r\n                            unsafe\r\n                            {\r\n                                fixed (byte* protocol_names_ptr = protocol_names)\r\n                                fixed (byte* host_ptr = host)\r\n                                fixed (byte* address_ptr = address)\r\n                                fixed (byte* path_ptr = path)\r\n                                {\r\n                                    WSApi.ulws_connect(_context, protocol_names_ptr, ssl_type, host_ptr, address_ptr, path_ptr, port);\r\n                                }\r\n                            }\r\n                        }\r\n                        catch (Exception exception)\r\n                        {\r\n                            // UnityEngine.Debug.LogErrorFormat(\"{0}\", exception);\r\n                            SetReadyState(ReadyState.CLOSED);\r\n                            OnError(exception);\r\n                        }\r\n                    }\r\n                    break;\r\n            }\r\n        }\r\n\r\n        private IPAddress Select(IPAddress[] list)\r\n        {\r\n            for (int i = 0, len = list.Length; i < len; i++)\r\n            {\r\n                var ipAddress = list[i];\r\n                if (ipAddress.AddressFamily == AddressFamily.InterNetwork || i == len - 1)\r\n                {\r\n                    return ipAddress;\r\n                }\r\n            }\r\n            throw new ArgumentOutOfRangeException(\"no IPAddress available\");\r\n        }\r\n\r\n        // = OnJSFinalize\r\n        public void Dispose()\r\n        {\r\n            Destroy();\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunctionMagic))]\r\n        private static JSValue _js_constructor(JSContext ctx, JSValue new_target, int argc, JSValue[] argv, int magic)\r\n        {\r\n            try\r\n            {\r\n                if (argc < 1 || !argv[0].IsString())\r\n                {\r\n                    throw new ParameterException(\"url\", typeof(string), 0);\r\n                }\r\n                var protocols = new List<string>();\r\n                if (argc > 1)\r\n                {\r\n                    if (argv[1].IsString())\r\n                    {\r\n                        protocols.Add(JSApi.GetString(ctx, argv[1]));\r\n                    }\r\n                    else if (JSApi.JS_IsArray(ctx, argv[1]) == 1)\r\n                    {\r\n                        var length_prop = JSApi.JS_GetProperty(ctx, argv[1], JSApi.JS_ATOM_length);\r\n                        int length;\r\n                        if (JSApi.JS_ToInt32(ctx, out length, length_prop) >= 0)\r\n                        {\r\n                            for (uint i = 0; i < length; i++)\r\n                            {\r\n                                var element = JSApi.JS_GetPropertyUint32(ctx, argv[1], i);\r\n                                var protocol_element = JSApi.GetString(ctx, element);\r\n                                if (protocol_element != null)\r\n                                {\r\n                                    protocols.Add(protocol_element);\r\n                                }\r\n                                JSApi.JS_FreeValue(ctx, element);\r\n                            }\r\n                        }\r\n                        JSApi.JS_FreeValue(ctx, length_prop);\r\n                    }\r\n                    else\r\n                    {\r\n                        throw new ParameterException(\"protocol\", typeof(string), 1);\r\n                    }\r\n                }\r\n                var url = JSApi.GetString(ctx, argv[0]);\r\n                var buffer = ScriptEngine.AllocByteBuffer(ctx, 2048);\r\n                var o = new WebSocket(buffer, url, protocols);\r\n                var val = NewBridgeClassObject(ctx, new_target, o, magic, true);\r\n                o._Transfer(ctx, val);\r\n                return val;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        private static JSValue _js_close(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            try\r\n            {\r\n                WebSocket self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                self.SetClose();\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue _js_bufferedAmount(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                WebSocket self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                return JSApi.JS_NewInt32(ctx, self._bufferedAmount);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue _js_readyState(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                WebSocket self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                return JSApi.JS_NewInt32(ctx, (int)(self._readyState >= 0 ? self._readyState : ReadyState.CONNECTING));\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        private static JSValue _js_send(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            try\r\n            {\r\n                WebSocket self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                if (argc == 0)\r\n                {\r\n                    throw new ParameterException(\"data\", typeof(string), 0);\r\n                }\r\n                if (!self._wsi.IsValid() || !self._context.IsValid())\r\n                {\r\n                    return ctx.ThrowInternalError(\"websocket closed\");\r\n                }\r\n\r\n                if (argv[0].IsString())\r\n                {\r\n                    // send text data\r\n                    size_t psize;\r\n                    var pointer = JSApi.JS_ToCStringLen(ctx, out psize, argv[0]);\r\n                    if (pointer != IntPtr.Zero && psize > 0)\r\n                    {\r\n                        var buffer = ScriptEngine.AllocByteBuffer(ctx, psize + WSApi.LWS_PRE);\r\n                        if (buffer != null)\r\n                        {\r\n                            buffer.WriteBytes(WSApi.LWS_PRE);\r\n                            buffer.WriteBytes(pointer, psize);\r\n                            self._pending.Enqueue(new Packet(false, buffer));\r\n                            self._bufferedAmount += psize;\r\n                            WSApi.lws_callback_on_writable(self._wsi);\r\n                        }\r\n                        else\r\n                        {\r\n                            JSApi.JS_FreeCString(ctx, pointer);\r\n                            return ctx.ThrowInternalError(\"buf alloc failed\");\r\n                        }\r\n                    }\r\n                    JSApi.JS_FreeCString(ctx, pointer);\r\n                }\r\n                else\r\n                {\r\n                    size_t psize;\r\n                    var pointer = JSApi.JS_GetArrayBuffer(ctx, out psize, argv[0]);\r\n                    if (pointer != IntPtr.Zero)\r\n                    {\r\n                        var buffer = ScriptEngine.AllocByteBuffer(ctx, psize + WSApi.LWS_PRE);\r\n                        if (buffer != null)\r\n                        {\r\n                            buffer.WriteBytes(WSApi.LWS_PRE);\r\n                            buffer.WriteBytes(pointer, psize);\r\n                            self._pending.Enqueue(new Packet(false, buffer));\r\n                            self._bufferedAmount += psize;\r\n                            WSApi.lws_callback_on_writable(self._wsi);\r\n                        }\r\n                        else\r\n                        {\r\n                            return ctx.ThrowInternalError(\"buf alloc failed\");\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        var asBuffer = JSApi.JS_GetProperty(ctx, argv[0], ScriptEngine.GetContext(ctx).GetAtom(\"buffer\"));\r\n                        if (asBuffer.IsObject())\r\n                        {\r\n                            pointer = JSApi.JS_GetArrayBuffer(ctx, out psize, asBuffer);\r\n                            JSApi.JS_FreeValue(ctx, asBuffer);\r\n                            if (pointer != IntPtr.Zero)\r\n                            {\r\n                                var buffer = ScriptEngine.AllocByteBuffer(ctx, psize + WSApi.LWS_PRE);\r\n                                if (buffer != null)\r\n                                {\r\n                                    buffer.WriteBytes(WSApi.LWS_PRE);\r\n                                    buffer.WriteBytes(pointer, psize);\r\n                                    self._pending.Enqueue(new Packet(false, buffer));\r\n                                    self._bufferedAmount += psize;\r\n                                    WSApi.lws_callback_on_writable(self._wsi);\r\n                                    return JSApi.JS_UNDEFINED;\r\n                                }\r\n                                else\r\n                                {\r\n                                    return ctx.ThrowInternalError(\"buf alloc failed\");\r\n                                }\r\n                            }\r\n                        }\r\n                        else\r\n                        {\r\n                            JSApi.JS_FreeValue(ctx, asBuffer);\r\n                        }\r\n                        return ctx.ThrowInternalError(\"unknown buf type\");\r\n                    }\r\n                }\r\n\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        public static void Bind(TypeRegister register, string name)\r\n        {\r\n            var cls = register.CreateGlobalClass(name, typeof(WebSocket), _js_constructor);\r\n            cls.AddMethod(false, \"close\", _js_close);\r\n            cls.AddMethod(false, \"send\", _js_send);\r\n            cls.AddProperty(false, \"readyState\", _js_readyState, null);\r\n            cls.AddProperty(false, \"bufferedAmount\", _js_bufferedAmount, null);\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source/WebSocket.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 6432db3d564692b4dbcf363cad70f09c\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket/Source.meta",
    "content": "fileFormatVersion: 2\r\nguid: 5ca75ba3e09e4524db8cadd75d2642c2\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/Websocket.meta",
    "content": "fileFormatVersion: 2\r\nguid: ed009e2313685404faa9740231986dc1\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/XMLHttpRequest/XMLHttpRequest.cs",
    "content": "using System;\r\nusing System.IO;\r\nusing System.Text;\r\nusing System.Net;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\nusing System.Threading;\r\nusing System.Threading.Tasks;\r\nusing QuickJS.Utils;\r\n\r\nnamespace QuickJS.Extra\r\n{\r\n    using UnityEngine;\r\n    using QuickJS;\r\n    using QuickJS.Errors;\r\n    using QuickJS.IO;\r\n    using QuickJS.Native;\r\n    using QuickJS.Binding;\r\n\r\n    public class XMLHttpRequest : Values, IDisposable, Utils.IObjectCollectionEntry\r\n    {\r\n        private class ResponseArgs\r\n        {\r\n            public XMLHttpRequest request;\r\n            public string error;\r\n        }\r\n\r\n        private enum ReadyState\r\n        {\r\n            /// <summary>\r\n            /// 代理被创建，但尚未调用 open() 方法。\r\n            /// </summary>\r\n            UNSENT = 0,\r\n            /// <summary>\r\n            /// open() 方法已经被调用。\r\n            /// </summary>\r\n            OPENED = 1,\r\n            /// <summary>\r\n            /// send() 方法已经被调用，并且头部和状态已经可获得。 \r\n            /// </summary>\r\n            HEADERS_RECEIVED = 2,\r\n            /// <summary>\r\n            /// 下载中； responseText 属性已经包含部分数据。\r\n            /// </summary>\r\n            LOADING = 3,\r\n            /// <summary>\r\n            /// 下载操作已完成。\r\n            /// </summary>\r\n            DONE = 4,\r\n        }\r\n\r\n        private Utils.ObjectCollection.Handle _handle;\r\n        private JSValue _jsThis; // dangeous reference holder (no ref count)\r\n        private JSContext _jsContext; // dangeous reference holder\r\n\r\n        private JSValue _onerror;\r\n        private JSValue _onreadystatechange;\r\n\r\n        private ReadyState _state;\r\n        private bool _bAsync;\r\n        private string _method;\r\n        private int _timeout;\r\n        private string _requestUriString;\r\n        private HttpStatusCode _code;\r\n        private string _reseponseText;\r\n\r\n        private void _Transfer(JSContext ctx, JSValue value)\r\n        {\r\n            _jsContext = ctx;\r\n            _jsThis = value;\r\n            _onreadystatechange = JSApi.JS_UNDEFINED;\r\n            _onerror = JSApi.JS_UNDEFINED;\r\n\r\n            var runtime = ScriptEngine.GetRuntime(ctx);\r\n            runtime.AddManagedObject(this, out _handle);\r\n        }\r\n\r\n        #region IObjectCollectionEntry implementation\r\n        public void OnCollectionReleased()\r\n        {\r\n            Destroy();\r\n        }\r\n        #endregion\r\n\r\n        private void Destroy()\r\n        {\r\n            if (_jsThis.IsUndefined())\r\n            {\r\n                return;\r\n            }\r\n            var runtime = ScriptEngine.GetRuntime(_jsContext);\r\n            if (runtime == null)\r\n            {\r\n                return;\r\n            }\r\n            var jsThis = _jsThis;\r\n            _jsThis = JSApi.JS_UNDEFINED;\r\n            var cache = runtime.GetObjectCache();\r\n            cache.RemoveObject(JSApi.JSB_FreePayload(_jsContext, jsThis));\r\n            _state = ReadyState.UNSENT;\r\n            _code = 0;\r\n            runtime.RemoveManagedObject(_handle);\r\n            JSApi.JS_FreeValue(_jsContext, _onreadystatechange);\r\n            _onreadystatechange = JSApi.JS_UNDEFINED;\r\n\r\n            JSApi.JS_FreeValue(_jsContext, _onerror);\r\n            _onerror = JSApi.JS_UNDEFINED;\r\n\r\n            _jsContext = JSContext.Null;\r\n        }\r\n\r\n        // = OnJSFinalize\r\n        public void Dispose()\r\n        {\r\n            Destroy();\r\n        }\r\n\r\n        private void OnReadyStateChange()\r\n        {\r\n            if (!_jsContext.IsValid() || JSApi.JS_IsFunction(_jsContext, _onreadystatechange) != 1)\r\n            {\r\n                return;\r\n            }\r\n            var ret = JSApi.JS_Call(_jsContext, _onreadystatechange, JSApi.JS_UNDEFINED);\r\n            JSApi.JS_FreeValue(_jsContext, ret);\r\n        }\r\n\r\n        private unsafe void OnError(string error)\r\n        {\r\n            if (!_jsContext.IsValid() || JSApi.JS_IsFunction(_jsContext, _onerror) != 1)\r\n            {\r\n                return;\r\n            }\r\n            var argv = stackalloc[] { Values.js_push_primitive(_jsContext, error) };\r\n            var ret = JSApi.JS_Call(_jsContext, _onerror, JSApi.JS_UNDEFINED, 1, argv);\r\n            if (ret.IsException())\r\n            {\r\n                var ex = _jsContext.GetExceptionString();\r\n                Diagnostics.Logger.Default.Error(ex);\r\n            }\r\n            else\r\n            {\r\n                JSApi.JS_FreeValue(_jsContext, ret);\r\n            }\r\n            JSApi.JS_FreeValue(_jsContext, argv[0]);\r\n        }\r\n\r\n        private void Open(string requestUriString, string method, bool bAsync)\r\n        {\r\n            if (_state != ReadyState.UNSENT)\r\n            {\r\n                throw new InvalidOperationException();\r\n            }\r\n            _bAsync = bAsync;\r\n            _method = method;\r\n            _requestUriString = requestUriString;\r\n            _state = ReadyState.OPENED;\r\n            OnReadyStateChange();\r\n        }\r\n\r\n        private void Send()\r\n        {\r\n            if (_state != ReadyState.OPENED)\r\n            {\r\n                throw new InvalidOperationException();\r\n            }\r\n            _state = ReadyState.LOADING;\r\n            OnReadyStateChange();\r\n            if (_state != ReadyState.LOADING)\r\n            {\r\n                return;\r\n            }\r\n\r\n            if (_bAsync)\r\n            {\r\n                //TODO: 替换做法\r\n                new Thread(_SendAsync).Start();\r\n            }\r\n            else\r\n            {\r\n                _SendAsync();\r\n            }\r\n        }\r\n\r\n        //TODO: 处理线程安全问题\r\n        private void _SendAsync()\r\n        {\r\n            string error = null;\r\n            HttpWebRequest request = null;\r\n            try\r\n            {\r\n                var uri = new Uri(_requestUriString);\r\n                request = WebRequest.CreateHttp(uri);\r\n                request.Method = _method;\r\n                request.Timeout = _timeout;\r\n\r\n                var rsp = request.GetResponse();\r\n                if (_state != ReadyState.LOADING)\r\n                {\r\n                    return;\r\n                }\r\n\r\n                var reader = new StreamReader(rsp.GetResponseStream());\r\n                _reseponseText = reader.ReadToEnd();\r\n                if (_state != ReadyState.LOADING)\r\n                {\r\n                    return;\r\n                }\r\n                _code = ((HttpWebResponse)rsp).StatusCode;\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                if (_state != ReadyState.LOADING)\r\n                {\r\n                    return;\r\n                }\r\n                error = ex.ToString();\r\n            }\r\n            finally\r\n            {\r\n                try { request?.Abort(); } catch (Exception) { }\r\n            }\r\n\r\n            var runtime = ScriptEngine.GetRuntime(_jsContext);\r\n            runtime?.EnqueueAction(OnResponseCallback, new ResponseArgs()\r\n            {\r\n                request = this,\r\n                error = error,\r\n            });\r\n        }\r\n\r\n        private static void OnResponseCallback(ScriptRuntime runtime, object cbArgs, JSValue cbValue)\r\n        {\r\n            if (!runtime.isValid || !runtime.isRunning)\r\n            {\r\n                return;\r\n            }\r\n            var args = cbArgs as ResponseArgs;\r\n            if (!args.request._jsThis.IsUndefined() && args.request._state != ReadyState.UNSENT)\r\n            {\r\n                args.request._state = ReadyState.DONE;\r\n                if (args.error != null)\r\n                {\r\n                    args.request.OnError(args.error);\r\n                }\r\n                else\r\n                {\r\n                    args.request.OnReadyStateChange();\r\n                }\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunctionMagic))]\r\n        private static JSValue js_constructor(JSContext ctx, JSValue new_target, int argc, JSValue[] argv, int magic)\r\n        {\r\n            var o = new XMLHttpRequest();\r\n            var val = NewBridgeClassObject(ctx, new_target, o, magic, true);\r\n            o._Transfer(ctx, val);\r\n            return val;\r\n        }\r\n\r\n        // xhr.open(method: string, url: string, async: boolean = true);\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        private static JSValue js_open(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            try\r\n            {\r\n                XMLHttpRequest self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                if (argc < 2)\r\n                {\r\n                    throw new InvalidDataException();\r\n                }\r\n                if (!argv[0].IsString() || !argv[0].IsString())\r\n                {\r\n                    throw new InvalidDataException();\r\n                }\r\n                var method = JSApi.GetString(ctx, argv[0]);\r\n                var uri = JSApi.GetString(ctx, argv[1]);\r\n                self.Open(uri, method, true);\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        // xhr.timeout = 2000; # unsigned long, milliseconds\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue js_get_timeout(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                XMLHttpRequest self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n\r\n                if (self._state != ReadyState.OPENED)\r\n                {\r\n                    throw new InvalidOperationException();\r\n                }\r\n\r\n                return JSApi.JS_NewInt32(ctx, self._timeout);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSSetterCFunction))]\r\n        private static JSValue js_set_timeout(JSContext ctx, JSValue this_obj, JSValue val)\r\n        {\r\n            try\r\n            {\r\n                XMLHttpRequest self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                if (!val.IsNumber())\r\n                {\r\n                    throw new InvalidDataException();\r\n                }\r\n\r\n                if (self._state != ReadyState.OPENED)\r\n                {\r\n                    throw new InvalidOperationException();\r\n                }\r\n                int timeout;\r\n                JSApi.JS_ToInt32(ctx, out timeout, val);\r\n                self._timeout = timeout;\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        // xhr.send(data?: FormData); \r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        private static JSValue js_send(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            try\r\n            {\r\n                XMLHttpRequest self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                self.Send();\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        // xhr.onreadystatechange = function () { ... };\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue js_get_onreadystatechange(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                XMLHttpRequest self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                return JSApi.JS_DupValue(ctx, self._onreadystatechange);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSSetterCFunction))]\r\n        private static JSValue js_set_onreadystatechange(JSContext ctx, JSValue this_obj, JSValue val)\r\n        {\r\n            try\r\n            {\r\n                XMLHttpRequest self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                JSApi.JS_FreeValue(ctx, self._onreadystatechange);\r\n                self._onreadystatechange = JSApi.JS_DupValue(ctx, val);\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue js_get_onerror(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                XMLHttpRequest self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                return JSApi.JS_DupValue(ctx, self._onerror);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSSetterCFunction))]\r\n        private static JSValue js_set_onerror(JSContext ctx, JSValue this_obj, JSValue val)\r\n        {\r\n            try\r\n            {\r\n                XMLHttpRequest self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                JSApi.JS_FreeValue(ctx, self._onerror);\r\n                self._onerror = JSApi.JS_DupValue(ctx, val);\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        // xhr.readyState\r\n        // 0 \tUNSENT \t代理被创建，但尚未调用 open() 方法。\r\n        // 1 \tOPENED \topen() 方法已经被调用。\r\n        // 2 \tHEADERS_RECEIVED \tsend() 方法已经被调用，并且头部和状态已经可获得。\r\n        // 3 \tLOADING \t下载中； responseText 属性已经包含部分数据。\r\n        // 4 \tDONE \t下载操作已完成。\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue js_get_readyState(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                XMLHttpRequest self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                return JSApi.JS_NewInt32(ctx, (int)self._state);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        // xhr.status \r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue js_get_status(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                XMLHttpRequest self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                return JSApi.JSB_NewInt64(ctx, (int)self._code);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        // xhr.responseText\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue js_get_responseText(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                XMLHttpRequest self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n\r\n                return ctx.NewString(self._reseponseText);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        public static void Bind(TypeRegister register, string name)\r\n        {\r\n            var cls = register.CreateGlobalClass(name, typeof(XMLHttpRequest), js_constructor);\r\n            cls.AddMethod(false, \"open\", js_open, 2);\r\n            cls.AddMethod(false, \"send\", js_send, 0);\r\n            cls.AddProperty(false, \"readyState\", js_get_readyState, null);\r\n            cls.AddProperty(false, \"status\", js_get_status, null);\r\n            cls.AddProperty(false, \"responseText\", js_get_responseText, null);\r\n            cls.AddProperty(false, \"timeout\", js_get_timeout, js_set_timeout);\r\n            cls.AddProperty(false, \"onreadystatechange\", js_get_onreadystatechange, js_set_onreadystatechange);\r\n            cls.AddProperty(false, \"onerror\", js_get_onerror, js_set_onerror);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Assets/jsb-extra/XMLHttpRequest/XMLHttpRequest.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 73774620fb8990645854d50ce6d18f23\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra/XMLHttpRequest.meta",
    "content": "fileFormatVersion: 2\r\nguid: a7ca25d10921a7a4bbb7ee4acfb0a4b3\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Assets/jsb-extra.meta",
    "content": "fileFormatVersion: 2\nguid: 1b9f8699e9eaae540bd0d0b605065dc3\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Directory.Build.props",
    "content": "<Project>\r\n    <PropertyGroup Condition=\"$(SolutionName) == 'unity-jsb'\">\r\n        <GenerateDocumentationFile>true</GenerateDocumentationFile>\r\n        <!-- The rest is omitted for clarity. -->\r\n        <!-- warning CS1591: Missing XML comment for publicly visible type or member -->\r\n        <NoWarn>1591,1570</NoWarn>\r\n        <DocumentationFile>Assets\\Generated\\Docs\\$(MSBuildProjectName).xml</DocumentationFile>\r\n    </PropertyGroup>\r\n</Project>"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2019 huliangjie\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "NOTE.md",
    "content": "\n| Symbol | Domain | Description |\n| --- | --- | ---\n| JSB_COMPATIBLE | C# | compatible with .net4.0\n| JSB_UNITYLESS  | C# | for using in dotnetcore, without accessing any feature of Unity3D.\n| JSB_WITH_UIELEMENTS | C# | with UI Toolkit binding.\n| JSB_WITH_V8_BACKEND | C# | with v8 backend\n| JSB_NO_BIGNUM | C# | without bignum support\n| JSB_DEBUG | C# | debug mode\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/AssemblyIcon.png.meta",
    "content": "fileFormatVersion: 2\nguid: 3874d8bc9c32962428262bb5554ed656\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/ClassIcon.png.meta",
    "content": "fileFormatVersion: 2\nguid: f7e330bb379c0584985c5ade63e8daec\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/Collapsed.png.meta",
    "content": "fileFormatVersion: 2\nguid: c27461f83e960f346a66c575232b0390\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/CollapsedItemIcon.png.meta",
    "content": "fileFormatVersion: 2\nguid: 9182766c77f82334081cfefa4c7ee60d\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/DelegateIcon.png.meta",
    "content": "fileFormatVersion: 2\nguid: afafd8c8952a8ad4fb842e3128ba7226\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/EditorWindowIcon.png.meta",
    "content": "fileFormatVersion: 2\nguid: 57c927357403c422fbbbb8d3528d69a0\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  vTOnly: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  flipbookRows: 1\n  flipbookColumns: 1\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  ignorePngGamma: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/EnumIcon.png.meta",
    "content": "fileFormatVersion: 2\nguid: b11d4b9cf43cffa40aebf569af85d27f\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/ExpandedItemIcon.png.meta",
    "content": "fileFormatVersion: 2\nguid: c8a3de0b80626a745a5ddcfa3f57490f\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/Folder.png.meta",
    "content": "fileFormatVersion: 2\nguid: 2594f0011264b5e44a222f19d0139c1c\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/FolderOpened.png.meta",
    "content": "fileFormatVersion: 2\nguid: 639a67f6f1deddd479925ff00c106793\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/Hierarchy.png.meta",
    "content": "fileFormatVersion: 2\nguid: 52065068dcbf0574f95caeef5b426e77\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/InspectorIcon.png.meta",
    "content": "fileFormatVersion: 2\nguid: 4c10af89029da406086f65993249eab7\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  vTOnly: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  flipbookRows: 1\n  flipbookColumns: 1\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  ignorePngGamma: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/InterfaceIcon.png.meta",
    "content": "fileFormatVersion: 2\nguid: 0ab1cfbcbf8577541a354e856f637a9f\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/JsScript.png.meta",
    "content": "fileFormatVersion: 2\nguid: 34cd15c8b09bd40449647a6e9017701b\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/MonoBehaviourIcon.png.meta",
    "content": "fileFormatVersion: 2\nguid: e4a26913bd0554c2092267f890467b7d\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  vTOnly: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  flipbookRows: 1\n  flipbookColumns: 1\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  ignorePngGamma: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/NamespaceIcon.png.meta",
    "content": "fileFormatVersion: 2\nguid: cf37377101985a24abee018ddcd774d0\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/Refresh.png.meta",
    "content": "fileFormatVersion: 2\nguid: f9d50e9112f6a2e489d4d57572fbfdc4\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/ScriptableObjectIcon.png.meta",
    "content": "fileFormatVersion: 2\nguid: 44123f576f3dc435c80a8a1c82855863\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  vTOnly: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  flipbookRows: 1\n  flipbookColumns: 1\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  ignorePngGamma: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons/StructIcon.png.meta",
    "content": "fileFormatVersion: 2\nguid: 95b2ea36c06b2714593bfc6e3ef71a77\nTextureImporter:\n  internalIDToNameTable: []\n  externalObjects: {}\n  serializedVersion: 11\n  mipmaps:\n    mipMapMode: 0\n    enableMipMap: 1\n    sRGBTexture: 1\n    linearTexture: 0\n    fadeOut: 0\n    borderMipMap: 0\n    mipMapsPreserveCoverage: 0\n    alphaTestReferenceValue: 0.5\n    mipMapFadeDistanceStart: 1\n    mipMapFadeDistanceEnd: 3\n  bumpmap:\n    convertToNormalMap: 0\n    externalNormalMap: 0\n    heightScale: 0.25\n    normalMapFilter: 0\n  isReadable: 0\n  streamingMipmaps: 0\n  streamingMipmapsPriority: 0\n  grayScaleToAlpha: 0\n  generateCubemap: 6\n  cubemapConvolution: 0\n  seamlessCubemap: 0\n  textureFormat: 1\n  maxTextureSize: 2048\n  textureSettings:\n    serializedVersion: 2\n    filterMode: 1\n    aniso: 1\n    mipBias: 0\n    wrapU: 0\n    wrapV: 0\n    wrapW: 0\n  nPOTScale: 1\n  lightmap: 0\n  compressionQuality: 50\n  spriteMode: 0\n  spriteExtrude: 1\n  spriteMeshType: 1\n  alignment: 0\n  spritePivot: {x: 0.5, y: 0.5}\n  spritePixelsToUnits: 100\n  spriteBorder: {x: 0, y: 0, z: 0, w: 0}\n  spriteGenerateFallbackPhysicsShape: 1\n  alphaUsage: 1\n  alphaIsTransparency: 0\n  spriteTessellationDetail: -1\n  textureType: 0\n  textureShape: 1\n  singleChannelComponent: 0\n  maxTextureSizeSet: 0\n  compressionQualitySet: 0\n  textureFormatSet: 0\n  applyGammaDecoding: 0\n  platformSettings:\n  - serializedVersion: 3\n    buildTarget: DefaultTexturePlatform\n    maxTextureSize: 2048\n    resizeAlgorithm: 0\n    textureFormat: -1\n    textureCompression: 1\n    compressionQuality: 50\n    crunchedCompression: 0\n    allowsAlphaSplitting: 0\n    overridden: 0\n    androidETC2FallbackOverride: 0\n    forceMaximumCompressionQuality_BC6H_BC7: 0\n  spriteSheet:\n    serializedVersion: 2\n    sprites: []\n    outline: []\n    physicsShape: []\n    bones: []\n    spriteID: \n    internalID: 0\n    vertices: []\n    indices: \n    edges: []\n    weights: []\n    secondaryTextures: []\n  spritePackingTag: \n  pSDRemoveMatte: 0\n  pSDShowRemoveMatteOption: 0\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor/Icons.meta",
    "content": "fileFormatVersion: 2\nguid: 3a51ac8df77003347b84d1702e29a00a\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Editor.meta",
    "content": "fileFormatVersion: 2\nguid: c81c1b16c0a44c245bc9f941a34bc57a\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/LICENSE.md",
    "content": "MIT License\r\n\r\nCopyright (c) 2019 huliangjie\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/LICENSE.md.meta",
    "content": "fileFormatVersion: 2\nguid: 837392458ab81e945a443e906bfc78c7\nTextScriptImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/Android/libs/arm64-v8a/libquickjs.so.meta",
    "content": "fileFormatVersion: 2\r\nguid: 3154da33c9ecf1b47b2c6d571c9dbe56\r\nPluginImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  iconMap: {}\r\n  executionOrder: {}\r\n  defineConstraints: []\r\n  isPreloaded: 0\r\n  isOverridable: 0\r\n  isExplicitlyReferenced: 0\r\n  validateReferences: 1\r\n  platformData:\r\n  - first:\r\n      '': Any\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        Exclude Android: 0\r\n        Exclude Editor: 1\r\n        Exclude Linux: 1\r\n        Exclude Linux64: 1\r\n        Exclude LinuxUniversal: 1\r\n        Exclude OSXUniversal: 1\r\n        Exclude WebGL: 1\r\n        Exclude Win: 1\r\n        Exclude Win64: 1\r\n        Exclude iOS: 1\r\n  - first:\r\n      Android: Android\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: ARM64\r\n  - first:\r\n      Any: \r\n    second:\r\n      enabled: 0\r\n      settings: {}\r\n  - first:\r\n      Editor: Editor\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n        DefaultValueInitialized: true\r\n        OS: AnyOS\r\n  - first:\r\n      Facebook: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Facebook: Win64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Linux\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: x86\r\n  - first:\r\n      Standalone: Linux64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: x86_64\r\n  - first:\r\n      Standalone: LinuxUniversal\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: OSXUniversal\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Win64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      iPhone: iOS\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        AddToEmbeddedBinaries: false\r\n        CompileFlags: \r\n        FrameworkDependencies: \r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/Android/libs/arm64-v8a.meta",
    "content": "fileFormatVersion: 2\r\nguid: b7e351671f36cbd4dad73b272cbd224b\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/Android/libs/armeabi-v7a/libquickjs.so.meta",
    "content": "fileFormatVersion: 2\r\nguid: ee25b3c6ff4d4ba47af20723d8482117\r\nPluginImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  iconMap: {}\r\n  executionOrder: {}\r\n  defineConstraints: []\r\n  isPreloaded: 0\r\n  isOverridable: 0\r\n  isExplicitlyReferenced: 0\r\n  validateReferences: 1\r\n  platformData:\r\n  - first:\r\n      '': Any\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        Exclude Android: 0\r\n        Exclude Editor: 1\r\n        Exclude Linux: 1\r\n        Exclude Linux64: 1\r\n        Exclude LinuxUniversal: 1\r\n        Exclude OSXUniversal: 1\r\n        Exclude WebGL: 1\r\n        Exclude Win: 1\r\n        Exclude Win64: 1\r\n        Exclude iOS: 1\r\n  - first:\r\n      Android: Android\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: ARMv7\r\n  - first:\r\n      Any: \r\n    second:\r\n      enabled: 0\r\n      settings: {}\r\n  - first:\r\n      Editor: Editor\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n        DefaultValueInitialized: true\r\n        OS: AnyOS\r\n  - first:\r\n      Facebook: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Facebook: Win64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Linux\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: x86\r\n  - first:\r\n      Standalone: Linux64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: x86_64\r\n  - first:\r\n      Standalone: LinuxUniversal\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: OSXUniversal\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Win64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      iPhone: iOS\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        AddToEmbeddedBinaries: false\r\n        CompileFlags: \r\n        FrameworkDependencies: \r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/Android/libs/armeabi-v7a.meta",
    "content": "fileFormatVersion: 2\r\nguid: f85ed01d5cb13914ab960b60cad49632\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/Android/libs/x86/libquickjs.so.meta",
    "content": "fileFormatVersion: 2\r\nguid: 1ca1d4ddaea49034caa9af339a14f56d\r\nPluginImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  iconMap: {}\r\n  executionOrder: {}\r\n  defineConstraints: []\r\n  isPreloaded: 0\r\n  isOverridable: 0\r\n  isExplicitlyReferenced: 0\r\n  validateReferences: 1\r\n  platformData:\r\n  - first:\r\n      '': Any\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        Exclude Android: 0\r\n        Exclude Editor: 1\r\n        Exclude Linux: 1\r\n        Exclude Linux64: 1\r\n        Exclude LinuxUniversal: 1\r\n        Exclude OSXUniversal: 1\r\n        Exclude WebGL: 1\r\n        Exclude Win: 1\r\n        Exclude Win64: 1\r\n        Exclude iOS: 1\r\n  - first:\r\n      Android: Android\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86\r\n  - first:\r\n      Any: \r\n    second:\r\n      enabled: 0\r\n      settings: {}\r\n  - first:\r\n      Editor: Editor\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n        DefaultValueInitialized: true\r\n        OS: AnyOS\r\n  - first:\r\n      Facebook: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Facebook: Win64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Linux\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: x86\r\n  - first:\r\n      Standalone: Linux64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: x86_64\r\n  - first:\r\n      Standalone: LinuxUniversal\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: OSXUniversal\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Win64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      iPhone: iOS\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        AddToEmbeddedBinaries: false\r\n        CompileFlags: \r\n        FrameworkDependencies: \r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/Android/libs/x86.meta",
    "content": "fileFormatVersion: 2\r\nguid: 058169f66259125469ca809ad39e73e9\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/Android/libs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 99501539c9b4f6d4d8a99280ce0f7424\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/Android.meta",
    "content": "fileFormatVersion: 2\r\nguid: 129f70be3a3e5114c8e0210ad43a893a\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WSA/ARM/quickjs.dll.meta",
    "content": "fileFormatVersion: 2\nguid: 7e3fafadeba1bac40b4d3a149ba0fee0\nPluginImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  iconMap: {}\n  executionOrder: {}\n  defineConstraints: []\n  isPreloaded: 0\n  isOverridable: 1\n  isExplicitlyReferenced: 0\n  validateReferences: 1\n  platformData:\n  - first:\n      : Any\n    second:\n      enabled: 0\n      settings:\n        Exclude Editor: 1\n        Exclude Linux64: 1\n        Exclude OSXUniversal: 1\n        Exclude WebGL: 1\n        Exclude Win: 1\n        Exclude Win64: 1\n        Exclude WindowsStoreApps: 0\n  - first:\n      Any: \n    second:\n      enabled: 0\n      settings: {}\n  - first:\n      Editor: Editor\n    second:\n      enabled: 0\n      settings:\n        CPU: AnyCPU\n        DefaultValueInitialized: true\n        OS: AnyOS\n  - first:\n      Standalone: Linux64\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      Standalone: OSXUniversal\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      Standalone: Win\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      Standalone: Win64\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      WebGL: WebGL\n    second:\n      enabled: 0\n      settings: {}\n  - first:\n      Windows Store Apps: WindowsStoreApps\n    second:\n      enabled: 1\n      settings:\n        CPU: ARM\n        DontProcess: false\n        PlaceholderPath: \n        SDK: AnySDK\n        ScriptingBackend: AnyScriptingBackend\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WSA/ARM.meta",
    "content": "fileFormatVersion: 2\nguid: 509feaf236f876b40af3fe6059ddbca7\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WSA/ARM64/quickjs.dll.meta",
    "content": "fileFormatVersion: 2\nguid: 9b82627973f81354ba9e97649aa465b4\nPluginImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  iconMap: {}\n  executionOrder: {}\n  defineConstraints: []\n  isPreloaded: 0\n  isOverridable: 1\n  isExplicitlyReferenced: 0\n  validateReferences: 1\n  platformData:\n  - first:\n      : Any\n    second:\n      enabled: 0\n      settings:\n        Exclude Editor: 1\n        Exclude Linux64: 1\n        Exclude OSXUniversal: 1\n        Exclude WebGL: 1\n        Exclude Win: 1\n        Exclude Win64: 1\n        Exclude WindowsStoreApps: 0\n  - first:\n      Any: \n    second:\n      enabled: 0\n      settings: {}\n  - first:\n      Editor: Editor\n    second:\n      enabled: 0\n      settings:\n        CPU: AnyCPU\n        DefaultValueInitialized: true\n        OS: AnyOS\n  - first:\n      Standalone: Linux64\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      Standalone: OSXUniversal\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      Standalone: Win\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      Standalone: Win64\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      WebGL: WebGL\n    second:\n      enabled: 0\n      settings: {}\n  - first:\n      Windows Store Apps: WindowsStoreApps\n    second:\n      enabled: 1\n      settings:\n        CPU: ARM64\n        DontProcess: false\n        PlaceholderPath: \n        SDK: AnySDK\n        ScriptingBackend: AnyScriptingBackend\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WSA/ARM64.meta",
    "content": "fileFormatVersion: 2\nguid: 71c55f7802fa8fc4aa8b4b9d8dc9302d\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WSA/x64/quickjs.dll.meta",
    "content": "fileFormatVersion: 2\nguid: f1e5bc811dac7db4d8f9a85c7c7b81e9\nPluginImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  iconMap: {}\n  executionOrder: {}\n  defineConstraints: []\n  isPreloaded: 0\n  isOverridable: 1\n  isExplicitlyReferenced: 0\n  validateReferences: 1\n  platformData:\n  - first:\n      : Any\n    second:\n      enabled: 0\n      settings:\n        Exclude Editor: 1\n        Exclude Linux64: 1\n        Exclude OSXUniversal: 1\n        Exclude WebGL: 1\n        Exclude Win: 1\n        Exclude Win64: 1\n        Exclude WindowsStoreApps: 0\n  - first:\n      Any: \n    second:\n      enabled: 0\n      settings: {}\n  - first:\n      Editor: Editor\n    second:\n      enabled: 0\n      settings:\n        CPU: AnyCPU\n        DefaultValueInitialized: true\n        OS: AnyOS\n  - first:\n      Standalone: Linux64\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      Standalone: OSXUniversal\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      Standalone: Win\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      Standalone: Win64\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      WebGL: WebGL\n    second:\n      enabled: 0\n      settings: {}\n  - first:\n      Windows Store Apps: WindowsStoreApps\n    second:\n      enabled: 1\n      settings:\n        CPU: X64\n        DontProcess: false\n        PlaceholderPath: \n        SDK: AnySDK\n        ScriptingBackend: AnyScriptingBackend\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WSA/x64.meta",
    "content": "fileFormatVersion: 2\nguid: 7de76f74eab3cc944a4529eb06ba5a30\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WSA/x86/quickjs.dll.meta",
    "content": "fileFormatVersion: 2\nguid: b2fcc9f91959f6441bf52e7325cff903\nPluginImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  iconMap: {}\n  executionOrder: {}\n  defineConstraints: []\n  isPreloaded: 0\n  isOverridable: 1\n  isExplicitlyReferenced: 0\n  validateReferences: 1\n  platformData:\n  - first:\n      : Any\n    second:\n      enabled: 0\n      settings:\n        Exclude Editor: 1\n        Exclude Linux64: 1\n        Exclude OSXUniversal: 1\n        Exclude WebGL: 1\n        Exclude Win: 1\n        Exclude Win64: 1\n        Exclude WindowsStoreApps: 0\n  - first:\n      Any: \n    second:\n      enabled: 0\n      settings: {}\n  - first:\n      Editor: Editor\n    second:\n      enabled: 0\n      settings:\n        CPU: AnyCPU\n        DefaultValueInitialized: true\n        OS: AnyOS\n  - first:\n      Standalone: Linux64\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      Standalone: OSXUniversal\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      Standalone: Win\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      Standalone: Win64\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      WebGL: WebGL\n    second:\n      enabled: 0\n      settings: {}\n  - first:\n      Windows Store Apps: WindowsStoreApps\n    second:\n      enabled: 1\n      settings:\n        CPU: X86\n        DontProcess: false\n        PlaceholderPath: \n        SDK: AnySDK\n        ScriptingBackend: AnyScriptingBackend\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WSA/x86.meta",
    "content": "fileFormatVersion: 2\nguid: 70ad126ef0df6ad4799a818d83d68a0d\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WSA.meta",
    "content": "fileFormatVersion: 2\nguid: cc36fb3496ac3f348814a7a8294727e3\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WebGL/.source/jsbplugin.ts",
    "content": "/**\r\n * Build with the following command:\r\n * npx -p typescript tsc\r\n *\r\n * BEWARE: Using some syntaxes will make Emscripten fail while building\r\n * Such known syntaxes: Object spread (...), BigInt literals\r\n * The output is targeted for es5 as Emscripten only understands that syntax\r\n */\r\n\r\ntype PluginType = JSApiExternals & {\r\n  $unityJsbState: typeof unityJsbState;\r\n  $unityJsbState__postset?: string;\r\n}\r\n\r\nconst UnityJSBPlugin: PluginType = {\r\n  $unityJsbState__postset: 'unityJsbState.atoms = unityJsbState.createAtoms();\\n',\r\n  $unityJsbState: {\r\n    createObjectReferences: function (): ObjectReferences {\r\n      const getTag = function (object): Tags {\r\n        if (object === undefined) return Tags.JS_TAG_UNDEFINED;\r\n        if (object === null) return Tags.JS_TAG_NULL;\r\n        if (typeof object === 'number') return Tags.JS_TAG_FLOAT64;\r\n        if (typeof object === 'boolean') return Tags.JS_TAG_BOOL;\r\n        if (typeof object === 'symbol') return Tags.JS_TAG_SYMBOL;\r\n        if (typeof object === 'string') return Tags.JS_TAG_STRING;\r\n        if (typeof object === 'bigint') return Tags.JS_TAG_BIG_INT;\r\n        if (object instanceof Error) return Tags.JS_TAG_EXCEPTION;\r\n        return Tags.JS_TAG_OBJECT;\r\n      };\r\n\r\n      const record: ObjectReferences['record'] = {};\r\n\r\n      const map = new Map<any, number>();\r\n\r\n      const payloadMap: ObjectReferences['payloadMap'] = new Map();\r\n\r\n      const res: ObjectReferences = {\r\n        record,\r\n        lastId: 0,\r\n\r\n        allocate(object) {\r\n          const ptr = _malloc(Sizes.JSValue) as JSValue;\r\n          const id = res.push(object, ptr);\r\n          return [ptr as JSValue, id];\r\n        },\r\n        batchAllocate(objects) {\r\n          const size = Sizes.JSValue;\r\n          const len = objects.length;\r\n          const arr = _malloc(size * len) as PointerArray<JSValue>;\r\n          const ids = Array(len);\r\n\r\n          for (let index = 0; index < len; index++) {\r\n            const object = objects[index];\r\n            const id = res.push(object, arr + (index * size) as JSValue);\r\n            ids[index] = id;\r\n          }\r\n\r\n          return [arr, ids];\r\n        },\r\n        batchGet(ptrs, count) {\r\n          const size = Sizes.JSValue;\r\n\r\n          const arr = new Array(count);\r\n          for (let index = 0; index < count; index++) {\r\n            const object = res.get(ptrs + index * size as JSValue);\r\n            arr[index] = object;\r\n          }\r\n\r\n          return arr;\r\n        },\r\n        push(object, ptr) {\r\n          if (typeof object === 'undefined') {\r\n            res.duplicateId(0, ptr);\r\n            return;\r\n          }\r\n\r\n          if (typeof object === 'number') {\r\n            if (typeof ptr === 'number') {\r\n              HEAPF64[ptr >> 3] = object;\r\n              unityJsbState.HEAP64()[(ptr >> 3) + 1] = BigInt(Tags.JS_TAG_FLOAT64);\r\n            }\r\n\r\n            return;\r\n          }\r\n\r\n          if (typeof object === 'boolean') {\r\n            if (typeof ptr === 'number') {\r\n              HEAP32[ptr >> 2] = object ? 1 : 0;\r\n              HEAP32[(ptr >> 2) + 1] = 0;\r\n              unityJsbState.HEAP64()[(ptr >> 3) + 1] = BigInt(Tags.JS_TAG_BOOL);\r\n            }\r\n\r\n            return;\r\n          }\r\n\r\n          const foundId = map.get(object);\r\n\r\n          if (foundId > 0) {\r\n            res.duplicateId(foundId, ptr);\r\n            return foundId;\r\n          }\r\n\r\n          const id = ++res.lastId;\r\n\r\n          record[id] = {\r\n            id,\r\n            refCount: 0,\r\n            value: object,\r\n            tag: getTag(object),\r\n          };\r\n\r\n          map.set(object, id);\r\n\r\n          res.duplicateId(id, ptr);\r\n\r\n          return id;\r\n        },\r\n        get(val) {\r\n          const tag = Number(unityJsbState.HEAP64()[(val >> 3) + 1]);\r\n\r\n          if (tag === Tags.JS_TAG_INT) {\r\n            return HEAP32[val >> 2];\r\n          }\r\n          else if (tag === Tags.JS_TAG_BOOL) {\r\n            return !!HEAP32[val >> 2];\r\n          }\r\n          else if (tag === Tags.JS_TAG_FLOAT64) {\r\n            return HEAPF64[val >> 3];\r\n          }\r\n          else {\r\n            const id = HEAP32[val >> 2];\r\n            if (id === 0) return undefined;\r\n            const ho = record[id];\r\n            return ho.value;\r\n          }\r\n        },\r\n        getRecord(val) {\r\n          const tag = Number(unityJsbState.HEAP64()[(val >> 3) + 1]);\r\n\r\n          if (tag === Tags.JS_TAG_INT) {\r\n            const value = HEAP32[val >> 2];\r\n            return {\r\n              id: -1,\r\n              refCount: 0,\r\n              value,\r\n              tag,\r\n            };\r\n          }\r\n          else if (tag === Tags.JS_TAG_BOOL) {\r\n            const boolValue = !!HEAP32[val >> 2];\r\n            return {\r\n              id: -1,\r\n              refCount: 0,\r\n              value: boolValue,\r\n              tag,\r\n            };\r\n          }\r\n          else if (tag === Tags.JS_TAG_FLOAT64) {\r\n            const value = HEAPF64[val >> 3];\r\n            return {\r\n              id: -1,\r\n              refCount: 0,\r\n              value,\r\n              tag,\r\n            };\r\n          }\r\n          else {\r\n            const id = HEAP32[val >> 2];\r\n            if (id === 0) return {\r\n              id: 0,\r\n              refCount: 0,\r\n              value: undefined,\r\n              tag: Tags.JS_TAG_UNDEFINED,\r\n              type: BridgeObjectType.None,\r\n              payload: -1,\r\n            };\r\n            const ho = record[id];\r\n            return ho;\r\n          }\r\n        },\r\n        duplicate(obj, ptr) {\r\n          const tag = Number(unityJsbState.HEAP64()[(obj >> 3) + 1]);\r\n\r\n          if (tag === Tags.JS_TAG_FLOAT64) {\r\n            if (typeof ptr === 'number') {\r\n              const val = HEAPF64[(obj >> 3)];\r\n              HEAPF64[ptr >> 3] = val;\r\n              unityJsbState.HEAP64()[(ptr >> 3) + 1] = BigInt(tag);\r\n            }\r\n            return;\r\n          }\r\n          else if (tag === Tags.JS_TAG_INT) {\r\n            if (typeof ptr === 'number') {\r\n              const val = HEAP32[(obj >> 2)];\r\n              HEAP32[(ptr >> 2)] = val;\r\n              HEAP32[(ptr >> 2) + 1] = 0;\r\n              unityJsbState.HEAP64()[(ptr >> 3) + 1] = BigInt(tag);\r\n            }\r\n            return;\r\n          }\r\n          else if (tag === Tags.JS_TAG_BOOL) {\r\n            if (typeof ptr === 'number') {\r\n              const valBool = !!HEAP32[(obj >> 2)];\r\n              HEAP32[(ptr >> 2)] = valBool ? 1 : 0;\r\n              HEAP32[(ptr >> 2) + 1] = 0;\r\n              unityJsbState.HEAP64()[(ptr >> 3) + 1] = BigInt(tag);\r\n            }\r\n            return;\r\n          }\r\n\r\n          const id = HEAP32[obj >> 2];\r\n          res.duplicateId(id, ptr);\r\n        },\r\n        duplicateId(id, ptr) {\r\n          if (id === 0) {\r\n            if (typeof ptr === 'number') {\r\n              HEAP32[ptr >> 2] = 0;\r\n              HEAP32[(ptr >> 2) + 1] = 0;\r\n              unityJsbState.HEAP64()[(ptr >> 3) + 1] = BigInt(Tags.JS_TAG_UNDEFINED);\r\n            }\r\n            return;\r\n          }\r\n\r\n          const ho = record[id];\r\n\r\n          ho.refCount += 1;\r\n\r\n          if (typeof ptr === 'number') {\r\n            HEAP32[ptr >> 2] = id;\r\n            HEAP32[(ptr >> 2) + 1] = 0;\r\n            unityJsbState.HEAP64()[(ptr >> 3) + 1] = BigInt(ho.tag);\r\n          }\r\n        },\r\n        pop(obj) {\r\n          const tag = Number(unityJsbState.HEAP64()[(obj >> 3) + 1]);\r\n\r\n          if (tag === Tags.JS_TAG_FLOAT64\r\n            || tag === Tags.JS_TAG_INT\r\n            || tag === Tags.JS_TAG_BOOL) return;\r\n\r\n          const id = HEAP32[obj >> 2];\r\n          res.popId(id);\r\n        },\r\n        popId(id) {\r\n          if (!id) return;\r\n          const ho = record[id];\r\n          ho.refCount -= 1;\r\n          console.assert(ho.refCount >= 0);\r\n        },\r\n        deleteRecord(id) {\r\n          const rec = record[id];\r\n          delete record[id];\r\n          res.clearPayload(rec.value);\r\n          map.delete(rec.value);\r\n        },\r\n        payloadMap,\r\n        setPayload(obj, type, payload) {\r\n          payloadMap.set(obj, {\r\n            type,\r\n            payload,\r\n          });\r\n        },\r\n        getPayload(obj) {\r\n          const res = payloadMap.get(obj);\r\n\r\n          if (res) return res;\r\n          else {\r\n            return {\r\n              type: BridgeObjectType.None,\r\n              payload: 0,\r\n            };\r\n          }\r\n        },\r\n        clearPayload(obj) {\r\n          payloadMap.delete(obj);\r\n        },\r\n      };\r\n\r\n      return res;\r\n    },\r\n    createAtoms(): AtomReferences {\r\n      const record: AtomReferences['record'] = {};\r\n      const map = new Map<string, AtomReference>();\r\n\r\n      const res: AtomReferences = {\r\n        record,\r\n        lastId: 0,\r\n        get(ref) {\r\n          if (ref === 0) return undefined;\r\n          return record[ref].value;\r\n        },\r\n        push(str) {\r\n          if (str === undefined) return 0;\r\n          const mapped = map.get(str);\r\n          let id;\r\n\r\n          if (!mapped) {\r\n            id = ++res.lastId;\r\n            const item = record[id] = {\r\n              id,\r\n              value: str,\r\n              refCount: 1,\r\n            };\r\n            map.set(str, item);\r\n          } else {\r\n            id = mapped.id;\r\n            mapped.refCount++;\r\n          }\r\n\r\n          return id;\r\n        },\r\n        pushId(id) {\r\n          if (id === 0) return;\r\n\r\n          const recorded = record[id];\r\n          console.assert(!!recorded);\r\n          if (!recorded) return 0;\r\n          recorded.refCount++;\r\n\r\n          return id;\r\n        },\r\n        pop(id) {\r\n          if (id === 0) return;\r\n\r\n          const recorded = record[id];\r\n          console.assert(!!recorded);\r\n          if (!recorded) return;\r\n\r\n          recorded.refCount--;\r\n          console.assert(recorded.refCount >= 0);\r\n\r\n          if (recorded.refCount == 0) {\r\n            map.delete(recorded.value);\r\n            delete record[id];\r\n          }\r\n        },\r\n      };\r\n\r\n      return res;\r\n    },\r\n    stringify: function (ptr: number | Pointer<number>, bufferLength?: number) { return (typeof UTF8ToString !== 'undefined' ? UTF8ToString : Pointer_stringify)(ptr, bufferLength); },\r\n    bufferify: function (arg: string) {\r\n      const bufferSize = lengthBytesUTF8(arg) + 1;\r\n      const buffer = _malloc(bufferSize);\r\n      stringToUTF8(arg, buffer, bufferSize);\r\n      return [buffer, bufferSize];\r\n    },\r\n\r\n    dynCall: function () { return (typeof Runtime !== 'undefined' ? Runtime.dynCall : dynCall).apply(typeof Runtime !== 'undefined' ? Runtime : undefined, arguments); },\r\n    runtimes: {},\r\n    contexts: {},\r\n    lastRuntimeId: 1,\r\n    lastContextId: 1,\r\n    getRuntime: function (rt) {\r\n      const rtId = rt;\r\n      return unityJsbState.runtimes[rtId];\r\n    },\r\n    getContext: function (ctx) {\r\n      const ctxId = ctx;\r\n      return unityJsbState.contexts[ctxId];\r\n    },\r\n    HEAP64: function () {\r\n      return new BigInt64Array(HEAPF64.buffer);\r\n    },\r\n    HEAPU64: function () {\r\n      return new BigUint64Array(HEAPF64.buffer);\r\n    },\r\n  },\r\n\r\n  JSB_Init() {\r\n    return Constants.CS_JSB_VERSION;\r\n  },\r\n\r\n  JSB_NewRuntime(finalizer) {\r\n    // TODO: understand what to do with finalizer\r\n\r\n    const id = unityJsbState.lastRuntimeId++;\r\n    const refs = unityJsbState.createObjectReferences();\r\n\r\n    unityJsbState.runtimes[id] = {\r\n      id,\r\n      contexts: {},\r\n      refs,\r\n      isDestroyed: false,\r\n      garbageCollect() {\r\n        const lastId = refs.lastId;\r\n        const record = refs.record;\r\n\r\n        let aliveItemCount = 0;\r\n\r\n        for (let index = 0; index <= lastId; index++) {\r\n          const element = record[index];\r\n\r\n          if (element) {\r\n            if (element.refCount <= 0) {\r\n              refs.deleteRecord(index);\r\n            }\r\n            else {\r\n              aliveItemCount++;\r\n            }\r\n          }\r\n        }\r\n\r\n        return aliveItemCount;\r\n      },\r\n    };\r\n\r\n    return id;\r\n  },\r\n\r\n  JSB_GetRuntimeOpaque(rtId) {\r\n    return unityJsbState.getRuntime(rtId).opaque;\r\n  },\r\n\r\n  JSB_SetRuntimeOpaque(rtId, opaque) {\r\n    unityJsbState.getRuntime(rtId).opaque = opaque;\r\n  },\r\n\r\n  JS_GetContextOpaque(ctx) {\r\n    return unityJsbState.getContext(ctx).opaque;\r\n  },\r\n\r\n  JS_SetContextOpaque(ctx, opaque) {\r\n    unityJsbState.getContext(ctx).opaque = opaque;\r\n  },\r\n\r\n  JSB_FreeRuntime(rtId) {\r\n    const runtime = unityJsbState.getRuntime(rtId);\r\n    const ctxIds = Object.keys(runtime.contexts);\r\n\r\n    for (let index = 0; index < ctxIds.length; index++) {\r\n      const ctxId = ctxIds[index];\r\n      const context = runtime.contexts[ctxId];\r\n      context.free();\r\n    }\r\n\r\n    const aliveItemCount = runtime.garbageCollect();\r\n\r\n    runtime.isDestroyed = true;\r\n    delete unityJsbState.runtimes[runtime.id];\r\n\r\n    return aliveItemCount === 0;\r\n  },\r\n\r\n  JS_GetRuntime(ctxId) {\r\n    const context = unityJsbState.getContext(ctxId);\r\n    return context.runtimeId;\r\n  },\r\n\r\n  JS_NewContext(rtId) {\r\n    const id = unityJsbState.lastContextId++;\r\n    const runtime = unityJsbState.getRuntime(rtId);\r\n\r\n    const iframe = document.createElement('iframe');\r\n    iframe.name = 'unity-jsb-context-' + id;\r\n    iframe.style.display = 'none';\r\n    document.head.appendChild(iframe);\r\n\r\n    const contentWindow = iframe.contentWindow! as typeof window;\r\n    const fetch = contentWindow.fetch.bind(contentWindow);\r\n    const URL = contentWindow.URL;\r\n    const XMLHttpRequest = contentWindow.XMLHttpRequest;\r\n    const XMLHttpRequestUpload = contentWindow.XMLHttpRequestUpload;\r\n    const WebSocket = contentWindow.WebSocket;\r\n\r\n    let baseTag: HTMLBaseElement = null;\r\n\r\n\r\n    // #region Promise monkey patch\r\n\r\n    // This patches the Promise so that microtasks are not run after the context is destroyed\r\n\r\n    const Promise = contentWindow.Promise;\r\n    const originalThen = Promise.prototype.then;\r\n    const originalCatch = Promise.prototype.catch;\r\n    const originalFinally = Promise.prototype.finally;\r\n\r\n    Promise.prototype.then = function promiseThenPatch(onFulfilled, onRejected) {\r\n      return originalThen.call(\r\n        this,\r\n        !onFulfilled ? undefined : function onFulfilledPatch() { if (!context.isDestroyed) return onFulfilled.apply(this, arguments); },\r\n        !onRejected ? undefined : function onRejectedPatch() { if (!context.isDestroyed) return onRejected.apply(this, arguments); },\r\n      );\r\n    };\r\n\r\n    Promise.prototype.catch = function promiseCatchPatch(onRejected) {\r\n      return originalCatch.call(\r\n        this,\r\n        !onRejected ? undefined : function onRejectedPatch() { if (!context.isDestroyed) return onRejected.apply(this, arguments); },\r\n      );\r\n    };\r\n\r\n    if (originalFinally) {\r\n      Promise.prototype.finally = function promiseFinallyPatch(onFinally) {\r\n        return originalFinally.call(\r\n          this,\r\n          !onFinally ? undefined : function onFinallyPatch() { if (!context.isDestroyed) return onFinally.apply(this, arguments); },\r\n        );\r\n      };\r\n    }\r\n\r\n    // #endregion\r\n\r\n\r\n    const extraGlobals: any = {\r\n      location: undefined,\r\n      document: undefined,\r\n      addEventListener: undefined,\r\n      btoa: window.btoa?.bind(window),\r\n      atob: window.atob?.bind(window),\r\n      $$webglWindow: window,\r\n      WebSocket,\r\n      fetch,\r\n      URL,\r\n      XMLHttpRequest,\r\n      XMLHttpRequestUpload,\r\n      Promise,\r\n    };\r\n\r\n    const globals: typeof window = new Proxy(extraGlobals, {\r\n      get(target, p, receiver) {\r\n        if (p in target) return target[p];\r\n        const res = window[p];\r\n        return res;\r\n      },\r\n      set(target, p, val, receiver) {\r\n        target[p] = val;\r\n        return true;\r\n      },\r\n      has(target, key) {\r\n        return (key in window) || (key in target);\r\n      },\r\n    }) as any;\r\n\r\n    extraGlobals.globalThis =\r\n      extraGlobals.global =\r\n      extraGlobals.window =\r\n      extraGlobals.parent =\r\n      extraGlobals.self =\r\n      extraGlobals.this =\r\n      globals;\r\n\r\n    const evaluate = function (code: string, filename?: string) {\r\n      const sourceMap = !filename ? '' : '\\n//# sourceURL=unity-jsb:///' + filename;\r\n\r\n      return (function (evalCode) {\r\n        //@ts-ignore\r\n        with (globals) {\r\n          return eval(evalCode);\r\n        }\r\n      }).call(globals, code + sourceMap);\r\n    };\r\n\r\n\r\n    const context: PluginContext = {\r\n      id,\r\n      runtime,\r\n      runtimeId: rtId,\r\n      window,\r\n      globalObject: globals,\r\n      evaluate,\r\n      iframe,\r\n      contentWindow,\r\n      isDestroyed: false,\r\n\r\n      free() {\r\n        if (iframe.parentNode) iframe.parentNode.removeChild(iframe);\r\n\r\n        context.isDestroyed = true;\r\n        delete runtime.contexts[context.id];\r\n        delete unityJsbState.contexts[context.id];\r\n      },\r\n\r\n      setBaseUrl(url: string) {\r\n        if (!baseTag) {\r\n          baseTag = document.createElement('base');\r\n        }\r\n\r\n        baseTag.setAttribute('href', url);\r\n\r\n        if (baseTag.parentNode && !url) {\r\n          baseTag.parentNode.removeChild(baseTag);\r\n        }\r\n        else if (!baseTag.parentNode && url) {\r\n          iframe.contentWindow.document.head.appendChild(baseTag);\r\n        }\r\n      },\r\n    };\r\n\r\n    runtime.contexts[id] = context;\r\n    unityJsbState.contexts[id] = context;\r\n    return id;\r\n  },\r\n\r\n  JS_FreeContext(ctxId) {\r\n    const context = unityJsbState.getContext(ctxId);\r\n    context.free();\r\n  },\r\n\r\n  JS_SetBaseUrl(ctxId, url) {\r\n    const context = unityJsbState.getContext(ctxId);\r\n    const urlStr = unityJsbState.stringify(url);\r\n\r\n    context.setBaseUrl(urlStr);\r\n  },\r\n\r\n  JS_GetGlobalObject(returnValue, ctxId) {\r\n    const context = unityJsbState.getContext(ctxId);\r\n\r\n    if (!context.globalObjectId) {\r\n      context.runtime.refs.push(context.globalObject, returnValue);\r\n    }\r\n    else {\r\n      context.runtime.refs.duplicateId(context.globalObjectId, returnValue);\r\n    }\r\n  },\r\n\r\n  JS_Eval(ptr, ctx, input, input_len, filename, eval_flags) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    try {\r\n      const code = unityJsbState.stringify(input, input_len);\r\n      const filenameStr = unityJsbState.stringify(filename);\r\n\r\n      const res = context.evaluate(code, filenameStr);\r\n\r\n      context.runtime.refs.push(res, ptr);\r\n    } catch (err) {\r\n      context.lastException = err;\r\n      context.runtime.refs.push(err, ptr);\r\n      console.error(err);\r\n    }\r\n  },\r\n\r\n  JS_IsInstanceOf(ctxId, val, obj) {\r\n    const context = unityJsbState.getContext(ctxId);\r\n    const valVal = context.runtime.refs.get(val);\r\n    const ctorVal = context.runtime.refs.get(obj);\r\n    return !!(valVal instanceof ctorVal);\r\n  },\r\n\r\n  JS_GetException(ptr, ctx) {\r\n    const context = unityJsbState.getContext(ctx);\r\n\r\n    context.runtime.refs.push(context.lastException, ptr);\r\n  },\r\n\r\n  JSB_FreeValue(ctx, v) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    context.runtime.refs.pop(v);\r\n  },\r\n\r\n  JSB_FreeValueRT(rt, v) {\r\n    const runtime = unityJsbState.getRuntime(rt);\r\n    runtime.refs.pop(v);\r\n  },\r\n\r\n  JSB_FreePayload(ret, ctx, val) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val);\r\n\r\n    const payload = context.runtime.refs.getPayload(obj);\r\n    HEAP32[ret >> 2] = payload.type;\r\n    HEAP32[(ret >> 2) + 1] = payload.payload;\r\n\r\n    context.runtime.refs.clearPayload(obj);\r\n  },\r\n\r\n  JSB_DupValue(ptr, ctx, v) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    context.runtime.refs.duplicate(v, ptr);\r\n  },\r\n\r\n  JS_RunGC(rt) {\r\n    const runtime = unityJsbState.getRuntime(rt);\r\n\r\n    runtime.garbageCollect();\r\n  },\r\n\r\n  JS_ComputeMemoryUsage(rt, s) {\r\n    // TODO: https://blog.unity.com/technology/unity-webgl-memory-the-unity-heap\r\n  },\r\n\r\n  JS_GetPropertyUint32(ptr, ctxId, val, index) {\r\n    const context = unityJsbState.getContext(ctxId);\r\n    const obj = context.runtime.refs.get(val);\r\n    const res = obj[index];\r\n\r\n    context.runtime.refs.push(res, ptr);\r\n  },\r\n\r\n  JS_GetPropertyInternal(ptr, ctxId, val, prop, receiver, throwRefError) {\r\n    const context = unityJsbState.getContext(ctxId);\r\n    const valObj = context.runtime.refs.get(val);\r\n    const propStr = unityJsbState.atoms.get(prop);\r\n    const res = valObj[propStr];\r\n\r\n    context.runtime.refs.push(res, ptr);\r\n  },\r\n\r\n  JS_GetPropertyStr(ptr, ctxId, val, prop) {\r\n    const context = unityJsbState.getContext(ctxId);\r\n    const valObj = context.runtime.refs.get(val);\r\n    const propStr = unityJsbState.stringify(prop);\r\n    const res = valObj[propStr];\r\n\r\n    context.runtime.refs.push(res, ptr);\r\n  },\r\n\r\n  JS_Invoke(ptr, ctx, this_obj, prop, argc, argv) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const propVal = unityJsbState.atoms.get(prop);\r\n    const thisVal = context.runtime.refs.get(this_obj);\r\n    const func = thisVal[propVal];\r\n\r\n    const args = context.runtime.refs.batchGet(argv, argc);\r\n\r\n    let res;\r\n    try {\r\n      res = func.apply(thisVal, args);\r\n    }\r\n    catch (err) {\r\n      context.lastException = err;\r\n      res = err;\r\n    }\r\n\r\n    context.runtime.refs.push(res, ptr);\r\n  },\r\n\r\n  JS_Call(ptr, ctx, func_obj, this_obj, argc, argv) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const func = context.runtime.refs.get(func_obj);\r\n    const thisVal = context.runtime.refs.get(this_obj);\r\n\r\n    const args = context.runtime.refs.batchGet(argv, argc);\r\n\r\n    let res;\r\n    try {\r\n      res = func.apply(thisVal, args);\r\n    }\r\n    catch (err) {\r\n      context.lastException = err;\r\n      res = err;\r\n    }\r\n\r\n    context.runtime.refs.push(res, ptr);\r\n  },\r\n\r\n  JS_CallConstructor(ptr, ctx, func_obj, argc, argv) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const func = context.runtime.refs.get(func_obj);\r\n\r\n    const args = context.runtime.refs.batchGet(argv, argc);\r\n\r\n    let res;\r\n    try {\r\n      res = Reflect.construct(func, args);\r\n    }\r\n    catch (err) {\r\n      context.lastException = err;\r\n      res = err;\r\n    }\r\n\r\n    context.runtime.refs.push(res, ptr);\r\n  },\r\n\r\n  JS_SetConstructor(ctx, ctor, proto) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const ctorVal = context.runtime.refs.get(ctor);\r\n    const protoVal = context.runtime.refs.get(proto);\r\n    ctorVal.prototype = protoVal;\r\n    protoVal.constructor = ctorVal;\r\n\r\n    var ctorPayload = context.runtime.refs.getPayload(ctorVal);\r\n    if (ctorPayload.type === BridgeObjectType.TypeRef) {\r\n      context.runtime.refs.setPayload(protoVal, ctorPayload.type, ctorPayload.payload);\r\n    }\r\n  },\r\n\r\n  JS_SetPrototype(ctx, obj, proto) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const objVal = context.runtime.refs.get(obj);\r\n    const protoVal = context.runtime.refs.get(proto);\r\n    Reflect.setPrototypeOf(objVal, protoVal);\r\n\r\n    return true;\r\n  },\r\n\r\n  JS_DefineProperty(ctx, this_obj, prop, val, getter, setter, flags) {\r\n    const context = unityJsbState.getContext(ctx);\r\n\r\n    const thisVal = context.runtime.refs.get(this_obj);\r\n    const getterVal = context.runtime.refs.get(getter);\r\n    const setterVal = context.runtime.refs.get(setter);\r\n    const valVal = context.runtime.refs.get(val);\r\n    const propVal = unityJsbState.atoms.get(prop);\r\n\r\n    const configurable = !!(flags & JSPropFlags.JS_PROP_CONFIGURABLE);\r\n    const hasConfigurable = configurable || !!(flags & JSPropFlags.JS_PROP_HAS_CONFIGURABLE);\r\n    const enumerable = !!(flags & JSPropFlags.JS_PROP_ENUMERABLE);\r\n    const hasEnumerable = enumerable || !!(flags & JSPropFlags.JS_PROP_HAS_ENUMERABLE);\r\n    const writable = !!(flags & JSPropFlags.JS_PROP_WRITABLE);\r\n    const hasWritable = writable || !!(flags & JSPropFlags.JS_PROP_HAS_WRITABLE);\r\n\r\n    const shouldThrow = !!(flags & JSPropFlags.JS_PROP_THROW) || !!(flags & JSPropFlags.JS_PROP_THROW_STRICT);\r\n\r\n\r\n    try {\r\n      const opts: PropertyDescriptor = {\r\n        get: getterVal,\r\n        set: setterVal,\r\n      };\r\n\r\n      if (!getter && !setter) {\r\n        opts.value = valVal;\r\n      }\r\n\r\n      if (hasConfigurable) opts.configurable = configurable;\r\n      if (hasEnumerable) opts.enumerable = enumerable;\r\n      if (!getter && !setter && hasWritable) opts.writable = writable;\r\n\r\n      Object.defineProperty(thisVal, propVal, opts);\r\n\r\n      return true;\r\n    } catch (err) {\r\n      context.lastException = err;\r\n      if (shouldThrow) {\r\n        console.error(err);\r\n        return -1;\r\n      }\r\n    }\r\n\r\n    return false;\r\n  },\r\n\r\n  JS_DefinePropertyValue(ctx, this_obj, prop, val, flags) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const runtime = context.runtime;\r\n\r\n    const thisVal = runtime.refs.get(this_obj);\r\n    const valVal = runtime.refs.get(val);\r\n    const propVal = unityJsbState.atoms.get(prop);\r\n\r\n    const configurable = !!(flags & JSPropFlags.JS_PROP_CONFIGURABLE);\r\n    const hasConfigurable = configurable || !!(flags & JSPropFlags.JS_PROP_HAS_CONFIGURABLE);\r\n    const enumerable = !!(flags & JSPropFlags.JS_PROP_ENUMERABLE);\r\n    const hasEnumerable = enumerable || !!(flags & JSPropFlags.JS_PROP_HAS_ENUMERABLE);\r\n    const writable = !!(flags & JSPropFlags.JS_PROP_WRITABLE);\r\n    const hasWritable = writable || !!(flags & JSPropFlags.JS_PROP_HAS_WRITABLE);\r\n\r\n    const shouldThrow = !!(flags & JSPropFlags.JS_PROP_THROW) || !!(flags & JSPropFlags.JS_PROP_THROW_STRICT);\r\n\r\n    // SetProperty frees the value automatically\r\n    runtime.refs.pop(val);\r\n\r\n    try {\r\n      const opts: PropertyDescriptor = {\r\n        value: valVal,\r\n      };\r\n\r\n      if (hasConfigurable) opts.configurable = configurable;\r\n      if (hasEnumerable) opts.enumerable = enumerable;\r\n      if (hasWritable) opts.writable = writable;\r\n\r\n      Object.defineProperty(thisVal, propVal, opts);\r\n      return true;\r\n    }\r\n    catch (err) {\r\n      context.lastException = err;\r\n      if (shouldThrow) {\r\n        console.error(err);\r\n        return -1;\r\n      }\r\n    }\r\n\r\n    return false;\r\n  },\r\n\r\n  JS_HasProperty(ctx, this_obj, prop) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const thisVal = context.runtime.refs.get(this_obj);\r\n    const propVal = unityJsbState.atoms.get(prop);\r\n\r\n    const res = Reflect.has(thisVal, propVal);\r\n\r\n    return !!res;\r\n  },\r\n\r\n  JS_SetPropertyInternal(ctx, this_obj, prop, val, flags) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const runtime = context.runtime;\r\n\r\n    const thisVal = runtime.refs.get(this_obj);\r\n    const valVal = runtime.refs.get(val);\r\n    const propVal = unityJsbState.atoms.get(prop);\r\n\r\n    // SetProperty frees the value automatically\r\n    runtime.refs.pop(val);\r\n\r\n    const shouldThrow = !!(flags & JSPropFlags.JS_PROP_THROW) || !!(flags & JSPropFlags.JS_PROP_THROW_STRICT);\r\n\r\n    try {\r\n      thisVal[propVal] = valVal;\r\n      return true;\r\n    } catch (err) {\r\n      context.lastException = err;\r\n      if (shouldThrow) {\r\n        console.error(err);\r\n        return -1;\r\n      }\r\n    }\r\n\r\n    return false;\r\n  },\r\n\r\n  JS_SetPropertyUint32(ctx, this_obj, idx, val) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const runtime = context.runtime;\r\n\r\n    const thisVal = context.runtime.refs.get(this_obj);\r\n    const valVal = context.runtime.refs.get(val);\r\n    const propVal = idx;\r\n\r\n    // SetProperty frees the value automatically\r\n    runtime.refs.pop(val);\r\n\r\n    try {\r\n      thisVal[propVal] = valVal;\r\n      return true;\r\n    } catch (err) {\r\n      context.lastException = err;\r\n    }\r\n\r\n    return false;\r\n  },\r\n\r\n  jsb_get_payload_header(ret, ctx, val) {\r\n\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val);\r\n\r\n    const rec = context.runtime.refs.getPayload(obj);\r\n\r\n    HEAP32[ret >> 2] = rec.type;\r\n    HEAP32[(ret >> 2) + 1] = rec.payload;\r\n  },\r\n\r\n  JS_ToCStringLen2(ctx, len, val, cesu8) {\r\n    const context = unityJsbState.getContext(ctx);\r\n\r\n    const str = context.runtime.refs.get(val);\r\n\r\n\r\n    if (typeof str === 'undefined') {\r\n      HEAP32[(len >> 2)] = 0;\r\n      return 0 as IntPtr;\r\n    }\r\n\r\n    const [buffer, length] = unityJsbState.bufferify(str);\r\n    HEAP32[(len >> 2)] = length - 1;\r\n    return buffer as IntPtr;\r\n  },\r\n\r\n  JS_FreeCString(ctx, ptr) {\r\n    _free(ptr);\r\n  },\r\n\r\n  JS_GetArrayBuffer(ctx, psize, obj) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const value = context.runtime.refs.get(obj);\r\n\r\n    if (value instanceof ArrayBuffer) {\r\n      HEAP32[psize >> 2] = value.byteLength;\r\n\r\n      return value as any;\r\n    }\r\n\r\n    return 0 as IntPtr;\r\n  },\r\n\r\n  // #region Atoms\r\n\r\n  JS_NewAtomLen(ctx, str, len) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const val = unityJsbState.stringify(str, len);\r\n\r\n    return unityJsbState.atoms.push(val);\r\n  },\r\n\r\n  JS_AtomToString(ptr, ctx, atom) {\r\n    const context = unityJsbState.getContext(ctx);\r\n\r\n    const str = unityJsbState.atoms.get(atom);\r\n\r\n    context.runtime.refs.push(str, ptr);\r\n  },\r\n\r\n  JS_FreeAtom(ctx, v) {\r\n    unityJsbState.atoms.pop(v);\r\n  },\r\n\r\n  JS_DupAtom(ctx, v) {\r\n    return unityJsbState.atoms.pushId(v);\r\n  },\r\n\r\n  JSB_ATOM_constructor() {\r\n    return unityJsbState.atoms.push('constructor');\r\n  },\r\n\r\n  JSB_ATOM_Error() {\r\n    return unityJsbState.atoms.push('Error');\r\n  },\r\n\r\n  JSB_ATOM_fileName() {\r\n    return unityJsbState.atoms.push('fileName');\r\n  },\r\n\r\n  JSB_ATOM_Function() {\r\n    return unityJsbState.atoms.push('Function');\r\n  },\r\n\r\n  JSB_ATOM_length() {\r\n    return unityJsbState.atoms.push('length');\r\n  },\r\n\r\n  JSB_ATOM_lineNumber() {\r\n    return unityJsbState.atoms.push('lineNumber');\r\n  },\r\n\r\n  JSB_ATOM_message() {\r\n    return unityJsbState.atoms.push('message');\r\n  },\r\n\r\n  JSB_ATOM_name() {\r\n    return unityJsbState.atoms.push('name');\r\n  },\r\n\r\n  JSB_ATOM_Number() {\r\n    return unityJsbState.atoms.push('Number');\r\n  },\r\n\r\n  JSB_ATOM_prototype() {\r\n    return unityJsbState.atoms.push('prototype');\r\n  },\r\n\r\n  JSB_ATOM_Proxy() {\r\n    return unityJsbState.atoms.push('Proxy');\r\n  },\r\n\r\n  JSB_ATOM_stack() {\r\n    return unityJsbState.atoms.push('stack');\r\n  },\r\n\r\n  JSB_ATOM_String() {\r\n    return unityJsbState.atoms.push('String');\r\n  },\r\n\r\n  JSB_ATOM_Object() {\r\n    return unityJsbState.atoms.push('Object');\r\n  },\r\n\r\n  JSB_ATOM_Operators() {\r\n    return unityJsbState.atoms.push('Operators');\r\n  },\r\n\r\n  JSB_ATOM_Symbol_operatorSet() {\r\n    return unityJsbState.atoms.push('operatorSet');\r\n  },\r\n\r\n  // #endregion\r\n\r\n  // #region Is\r\n\r\n  JS_IsArray(ctx, val) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const valVal = context.runtime.refs.get(val);\r\n    const res = Array.isArray(valVal);\r\n    return !!res;\r\n  },\r\n\r\n  JS_IsConstructor(ctx, val) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val);\r\n    const res = !!obj.prototype && !!obj.prototype.constructor.name;\r\n    return !!res;\r\n  },\r\n\r\n  JS_IsError(ctx, val) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const valVal = context.runtime.refs.get(val);\r\n    const res = valVal instanceof Error;\r\n    return !!res;\r\n  },\r\n\r\n  JS_IsFunction(ctx, val) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const valVal = context.runtime.refs.get(val);\r\n    const res = typeof valVal === 'function';\r\n    return !!res;\r\n  },\r\n\r\n  // #endregion\r\n\r\n  JS_ParseJSON(ptr, ctx, buf, buf_len, filename) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const str = unityJsbState.stringify(buf as any, buf_len);\r\n    const res = JSON.parse(str);\r\n    context.runtime.refs.push(res, ptr);\r\n  },\r\n\r\n  JS_JSONStringify(ptr, ctx, obj, replacer, space) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const objVal = context.runtime.refs.get(obj);\r\n    const rpVal = context.runtime.refs.get(replacer);\r\n    const spVal = context.runtime.refs.get(space);\r\n\r\n    const res = JSON.stringify(objVal, rpVal, spVal);\r\n    context.runtime.refs.push(res, ptr);\r\n  },\r\n\r\n  // #region New\r\n\r\n  JS_NewArray(ptr, ctx) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const res = [];\r\n    context.runtime.refs.push(res, ptr);\r\n  },\r\n\r\n  JS_NewArrayBufferCopy(ptr, ctx, buf, len) {\r\n    const context = unityJsbState.getContext(ctx);\r\n\r\n    const nptr = _malloc(len);\r\n    const res = new Uint8Array(HEAPU8.buffer, nptr, len);\r\n    const existing = new Uint8Array(HEAPU8.buffer, buf, len);\r\n    res.set(existing);\r\n\r\n    context.runtime.refs.push(res, ptr);\r\n  },\r\n\r\n  JSB_NewFloat64(ptr, ctx, d) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    context.runtime.refs.push(d, ptr);\r\n  },\r\n\r\n  JSB_NewInt64(ptr, ctx, d) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    context.runtime.refs.push(d, ptr);\r\n  },\r\n\r\n  JS_NewObject(ptr, ctx) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const res = {};\r\n    context.runtime.refs.push(res, ptr);\r\n  },\r\n\r\n  JS_NewString(ptr, ctx, str) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const res = unityJsbState.stringify(str);\r\n    context.runtime.refs.push(res, ptr);\r\n  },\r\n\r\n  JS_NewStringLen(ptr, ctx, str, len) {\r\n    const context = unityJsbState.getContext(ctx);\r\n\r\n    const val = unityJsbState.stringify(str as any, len);\r\n\r\n    context.runtime.refs.push(val, ptr);\r\n  },\r\n\r\n  JSB_NewEmptyString(ptr, ctx) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const res = \"\";\r\n    context.runtime.refs.push(res, ptr);\r\n  },\r\n\r\n  // #endregion\r\n\r\n  // #region Bridge\r\n\r\n  JSB_NewCFunction(ret, ctx, func, atom, length, cproto, magic) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const refs = context.runtime.refs;\r\n\r\n    const name = unityJsbState.atoms.get(atom) || 'jscFunction';\r\n\r\n    function jscFunction() {\r\n      const args = arguments;\r\n\r\n      const thisObj = this === window ? context.globalObject : this;\r\n      const [thisPtr, thisId] = refs.allocate(thisObj);\r\n      const ret = _malloc(Sizes.JSValue) as JSValue;\r\n\r\n      if (cproto === JSCFunctionEnum.JS_CFUNC_generic) {\r\n        const argc = args.length;\r\n        const [argv, argIds] = refs.batchAllocate(Array.from(args));\r\n        unityJsbState.dynCall<typeof JSApiDelegates.JSCFunction>('viiiii', func, [ret, ctx, thisPtr, argc, argv]);\r\n        argIds.forEach(refs.popId);\r\n        _free(argv);\r\n      }\r\n      else if (cproto === JSCFunctionEnum.JS_CFUNC_setter) {\r\n        const [val, valId] = refs.allocate(args[0]);\r\n        unityJsbState.dynCall<typeof JSApiDelegates.JSSetterCFunction>('viiii', func, [ret, ctx, thisPtr, val]);\r\n        refs.popId(valId);\r\n        _free(val);\r\n      }\r\n      else if (cproto === JSCFunctionEnum.JS_CFUNC_getter) {\r\n        unityJsbState.dynCall<typeof JSApiDelegates.JSGetterCFunction>('viii', func, [ret, ctx, thisPtr]);\r\n      }\r\n      else {\r\n        throw new Error(`Unknown type of function specified: name=${name} type=${cproto}`);\r\n      }\r\n      refs.popId(thisId);\r\n      _free(thisPtr);\r\n\r\n      const returnValue = refs.get(ret);\r\n      refs.pop(ret);\r\n      _free(ret);\r\n      return returnValue;\r\n    }\r\n\r\n    jscFunction['$$csharpFunctionName'] = name;\r\n    refs.push(jscFunction, ret);\r\n  },\r\n\r\n  JSB_NewCFunctionMagic(ret, ctx, func, atom, length, cproto, magic) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const refs = context.runtime.refs;\r\n\r\n    const name = unityJsbState.atoms.get(atom) || 'jscFunctionMagic';\r\n\r\n    function jscFunctionMagic() {\r\n      const args = arguments;\r\n\r\n      const thisObj = this === window ? context.globalObject : this;\r\n      const [thisPtr, thisId] = refs.allocate(thisObj);\r\n      const ret = _malloc(Sizes.JSValue) as JSValue;\r\n\r\n      if (cproto === JSCFunctionEnum.JS_CFUNC_generic_magic) {\r\n        const argc = args.length;\r\n        const [argv, argIds] = refs.batchAllocate(Array.from(args));\r\n        unityJsbState.dynCall<typeof JSApiDelegates.JSCFunctionMagic>('viiiiii', func, [ret, ctx, thisPtr, argc, argv, magic]);\r\n        argIds.forEach(refs.popId);\r\n        _free(argv);\r\n      }\r\n      else if (cproto === JSCFunctionEnum.JS_CFUNC_constructor_magic) {\r\n        const argc = args.length;\r\n        const [argv, argIds] = refs.batchAllocate(Array.from(args));\r\n        unityJsbState.dynCall<typeof JSApiDelegates.JSCFunctionMagic>('viiiiii', func, [ret, ctx, thisPtr, argc, argv, magic]);\r\n        argIds.forEach(refs.popId);\r\n        _free(argv);\r\n      }\r\n      else if (cproto === JSCFunctionEnum.JS_CFUNC_setter_magic) {\r\n        const [val, valId] = refs.allocate(args[0]);\r\n        unityJsbState.dynCall<typeof JSApiDelegates.JSSetterCFunctionMagic>('viiiii', func, [ret, ctx, thisPtr, val, magic]);\r\n        refs.popId(valId);\r\n        _free(val);\r\n      }\r\n      else if (cproto === JSCFunctionEnum.JS_CFUNC_getter_magic) {\r\n        unityJsbState.dynCall<typeof JSApiDelegates.JSGetterCFunctionMagic>('viiii', func, [ret, ctx, thisPtr, magic]);\r\n      }\r\n      else {\r\n        throw new Error(`Unknown type of function specified: name=${name} type=${cproto}`);\r\n      }\r\n      refs.popId(thisId);\r\n      _free(thisPtr);\r\n\r\n      const returnValue = refs.get(ret);\r\n      refs.pop(ret);\r\n      _free(ret);\r\n      return returnValue;\r\n    };\r\n    jscFunctionMagic['$$csharpFunctionName'] = name;\r\n    refs.push(jscFunctionMagic, ret);\r\n\r\n    if (cproto === JSCFunctionEnum.JS_CFUNC_constructor_magic) {\r\n      refs.setPayload(jscFunctionMagic, BridgeObjectType.TypeRef, magic);\r\n    }\r\n  },\r\n\r\n  jsb_new_bridge_object(ret, ctx, proto, object_id) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const protoVal = context.runtime.refs.get(proto);\r\n    const res = Object.create(protoVal);\r\n    context.runtime.refs.push(res, ret);\r\n    context.runtime.refs.setPayload(res, BridgeObjectType.ObjectRef, object_id);\r\n  },\r\n\r\n  jsb_new_bridge_value(ret, ctx, proto, size) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const protoVal = context.runtime.refs.get(proto);\r\n    const res = Object.create(protoVal) as BridgeStruct;\r\n    res.$$values = new Array(size).fill(0);\r\n    context.runtime.refs.push(res, ret);\r\n  },\r\n\r\n  JSB_NewBridgeClassObject(ret, ctx, new_target, object_id) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const res = context.runtime.refs.get(new_target);\r\n\r\n    context.runtime.refs.push(res, ret);\r\n    context.runtime.refs.setPayload(res, BridgeObjectType.ObjectRef, object_id);\r\n  },\r\n\r\n  JSB_NewBridgeClassValue(ret, ctx, new_target, size) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const res = context.runtime.refs.get(new_target) as BridgeStruct;\r\n    res.$$values = new Array(size).fill(0);\r\n    context.runtime.refs.push(res, ret);\r\n  },\r\n\r\n  JSB_GetBridgeClassID() {\r\n    // TODO: I have no idea\r\n    return 0;\r\n  },\r\n\r\n  jsb_construct_bridge_object(ret, ctx, ctor, object_id) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const ctorVal = context.runtime.refs.get(ctor);\r\n    const res = Reflect.construct(ctorVal, []);\r\n    context.runtime.refs.push(res, ret);\r\n    context.runtime.refs.setPayload(res, BridgeObjectType.ObjectRef, object_id);\r\n  },\r\n\r\n  jsb_crossbind_constructor(ret, ctx, new_target) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const target = context.runtime.refs.get(new_target);\r\n    // TODO: I have no idea\r\n    const res = function () {\r\n      return new target();\r\n    };\r\n    context.runtime.refs.push(res, ret);\r\n  },\r\n\r\n  // #endregion\r\n\r\n  // #region Errors\r\n\r\n  JSB_ThrowError(ret, ctx, buf, buf_len) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const str = unityJsbState.stringify(buf as any, buf_len);\r\n    const err = new Error(str);\r\n    console.error(err);\r\n    context.runtime.refs.push(err, ret);\r\n    // TODO: throw?\r\n  },\r\n\r\n  JSB_ThrowTypeError(ret, ctx, msg) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const str = 'Type Error';\r\n    const err = new Error(str);\r\n    console.error(err);\r\n    context.runtime.refs.push(err, ret);\r\n    // TODO: throw?\r\n  },\r\n\r\n  JSB_ThrowRangeError(ret, ctx, msg) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const str = 'Range Error';\r\n    const err = new Error(str);\r\n    console.error(err);\r\n    context.runtime.refs.push(err, ret);\r\n    // TODO: throw?\r\n  },\r\n\r\n  JSB_ThrowInternalError(ret, ctx, msg) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const str = 'Internal Error';\r\n    const err = new Error(str);\r\n    console.error(err);\r\n    context.runtime.refs.push(err, ret);\r\n    // TODO: throw?\r\n  },\r\n\r\n  JSB_ThrowReferenceError(ret, ctx, msg) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const str = 'Reference Error';\r\n    const err = new Error(str);\r\n    console.error(err);\r\n    context.runtime.refs.push(err, ret);\r\n    // TODO: throw?\r\n  },\r\n\r\n  // #endregion\r\n\r\n  // #region Low level Set\r\n\r\n  js_strndup(ctx, s, n) {\r\n    const buffer = _malloc(n + 1);\r\n    _memcpy(buffer, s, n);\r\n    HEAPU8[buffer + n] = 0;\r\n    return buffer as IntPtr;\r\n  },\r\n\r\n  jsb_set_floats(ctx, val, n, v0) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = n / Sizes.Single;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    for (let index = 0; index < count; index++) {\r\n      const val = HEAPF32[(v0 >> 2) + index];\r\n      obj.$$values[index] = val;\r\n    }\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_set_bytes(ctx, val, n, v0) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = n / Sizes.Single;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    for (let index = 0; index < count; index++) {\r\n      const val = HEAP32[(v0 >> 2) + index];\r\n      obj.$$values[index] = val;\r\n    }\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_set_byte_4(ctx, val, v0, v1, v2, v3) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = 4;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    obj.$$values[0] = HEAP32[(v0 >> 2)];\r\n    obj.$$values[1] = HEAP32[(v1 >> 2)];\r\n    obj.$$values[2] = HEAP32[(v2 >> 2)];\r\n    obj.$$values[3] = HEAP32[(v3 >> 2)];\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_set_float_2(ctx, val, v0, v1) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = 2;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    obj.$$values[0] = HEAPF32[(v0 >> 2)];\r\n    obj.$$values[1] = HEAPF32[(v1 >> 2)];\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_set_float_3(ctx, val, v0, v1, v2) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = 3;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    obj.$$values[0] = HEAPF32[(v0 >> 2)];\r\n    obj.$$values[1] = HEAPF32[(v1 >> 2)];\r\n    obj.$$values[2] = HEAPF32[(v2 >> 2)];\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_set_float_4(ctx, val, v0, v1, v2, v3) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = 4;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    obj.$$values[0] = HEAPF32[(v0 >> 2)];\r\n    obj.$$values[1] = HEAPF32[(v1 >> 2)];\r\n    obj.$$values[2] = HEAPF32[(v2 >> 2)];\r\n    obj.$$values[3] = HEAPF32[(v3 >> 2)];\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_set_int_1(ctx, val, v0) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = 1;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    obj.$$values[0] = HEAP32[(v0 >> 2)];\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_set_int_2(ctx, val, v0, v1) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = 2;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    obj.$$values[0] = HEAP32[(v0 >> 2)];\r\n    obj.$$values[1] = HEAP32[(v1 >> 2)];\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_set_int_3(ctx, val, v0, v1, v2) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = 3;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    obj.$$values[0] = HEAP32[(v0 >> 2)];\r\n    obj.$$values[1] = HEAP32[(v1 >> 2)];\r\n    obj.$$values[2] = HEAP32[(v2 >> 2)];\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_set_int_4(ctx, val, v0, v1, v2, v3) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = 4;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    obj.$$values[0] = HEAP32[(v0 >> 2)];\r\n    obj.$$values[1] = HEAP32[(v1 >> 2)];\r\n    obj.$$values[2] = HEAP32[(v2 >> 2)];\r\n    obj.$$values[3] = HEAP32[(v3 >> 2)];\r\n\r\n    return true;\r\n  },\r\n\r\n  // #endregion\r\n\r\n  // #region Low Level Get\r\n\r\n  jsb_get_bytes(ctx, val, n, v0) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = n / Sizes.Single;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    for (let index = 0; index < count; index++) {\r\n      const val = obj.$$values[index];\r\n      HEAP32[(v0 >> 2) + index] = val;\r\n    }\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_get_floats(ctx, val, n, v0) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = n / Sizes.Single;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    for (let index = 0; index < count; index++) {\r\n      const val = obj.$$values[index];\r\n      HEAPF32[(v0 >> 2) + index] = val;\r\n    }\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_get_byte_4(ctx, val, v0, v1, v2, v3) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = 4;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    HEAP32[(v0 >> 2)] = obj.$$values[0];\r\n    HEAP32[(v1 >> 2)] = obj.$$values[1];\r\n    HEAP32[(v2 >> 2)] = obj.$$values[2];\r\n    HEAP32[(v3 >> 2)] = obj.$$values[3];\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_get_float_2(ctx, val, v0, v1) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = 2;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    HEAPF32[(v0 >> 2)] = obj.$$values[0];\r\n    HEAPF32[(v1 >> 2)] = obj.$$values[1];\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_get_float_3(ctx, val, v0, v1, v2) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = 3;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    HEAPF32[(v0 >> 2)] = obj.$$values[0];\r\n    HEAPF32[(v1 >> 2)] = obj.$$values[1];\r\n    HEAPF32[(v2 >> 2)] = obj.$$values[2];\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_get_float_4(ctx, val, v0, v1, v2, v3) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = 4;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    HEAPF32[(v0 >> 2)] = obj.$$values[0];\r\n    HEAPF32[(v1 >> 2)] = obj.$$values[1];\r\n    HEAPF32[(v2 >> 2)] = obj.$$values[2];\r\n    HEAPF32[(v3 >> 2)] = obj.$$values[3];\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_get_int_1(ctx, val, v0) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = 1;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    HEAP32[(v0 >> 2)] = obj.$$values[0];\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_get_int_2(ctx, val, v0, v1) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = 2;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    HEAP32[(v0 >> 2)] = obj.$$values[0];\r\n    HEAP32[(v1 >> 2)] = obj.$$values[1];\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_get_int_3(ctx, val, v0, v1, v2) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = 3;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    HEAP32[(v0 >> 2)] = obj.$$values[0];\r\n    HEAP32[(v1 >> 2)] = obj.$$values[1];\r\n    HEAP32[(v2 >> 2)] = obj.$$values[2];\r\n\r\n    return true;\r\n  },\r\n\r\n  jsb_get_int_4(ctx, val, v0, v1, v2, v3) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const obj = context.runtime.refs.get(val) as BridgeStruct;\r\n\r\n    const count = 4;\r\n    if (!Array.isArray(obj.$$values) || count >= obj.$$values.length) return false;\r\n\r\n    HEAP32[(v0 >> 2)] = obj.$$values[0];\r\n    HEAP32[(v1 >> 2)] = obj.$$values[1];\r\n    HEAP32[(v2 >> 2)] = obj.$$values[2];\r\n    HEAP32[(v3 >> 2)] = obj.$$values[3];\r\n\r\n    return true;\r\n  },\r\n\r\n  // #endregion\r\n\r\n  // #region To\r\n\r\n  JS_ToFloat64(ctx, pres, val) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const value = context.runtime.refs.get(val);\r\n\r\n    if (typeof value === 'number' || typeof value === 'bigint') {\r\n      HEAPF64[pres >> 3] = Number(value);\r\n      return false;\r\n    }\r\n    return -1;\r\n  },\r\n\r\n\r\n  JS_ToInt32(ctx, pres, val) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const value = context.runtime.refs.get(val);\r\n\r\n    if (typeof value === 'number' || typeof value === 'bigint') {\r\n      HEAP32[pres >> 2] = Number(value);\r\n      return false;\r\n    }\r\n\r\n    return -1;\r\n  },\r\n\r\n  JS_ToInt64(ctx, pres, val) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const value = context.runtime.refs.get(val);\r\n    if (typeof value === 'number' || typeof value === 'bigint') {\r\n      unityJsbState.HEAP64()[pres >> 3] = BigInt(value);\r\n      return false;\r\n    }\r\n    return -1;\r\n  },\r\n\r\n  JS_ToBigInt64(ctx, pres, val) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const value = context.runtime.refs.get(val);\r\n    if (typeof value === 'number' || typeof value === 'bigint') {\r\n      unityJsbState.HEAP64()[pres >> 3] = BigInt(value);\r\n      return false;\r\n    }\r\n    return -1;\r\n  },\r\n\r\n  JS_ToIndex(ctx, pres, val) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const value = context.runtime.refs.get(val);\r\n    if (typeof value === 'number' || typeof value === 'bigint') {\r\n      unityJsbState.HEAPU64()[pres >> 3] = BigInt(value);\r\n      return false;\r\n    }\r\n    return -1;\r\n  },\r\n\r\n  JSB_ToUint32(ctx, pres, val) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const value = context.runtime.refs.get(val);\r\n\r\n    if (typeof value === 'number' || typeof value === 'bigint') {\r\n      HEAPU32[pres >> 2] = Number(value);\r\n      return false;\r\n    }\r\n    return -1;\r\n  },\r\n\r\n  JS_ToBool(ctx, val) {\r\n    const context = unityJsbState.getContext(ctx);\r\n    const objVal = context.runtime.refs.get(val);\r\n    return !!objVal;\r\n  },\r\n\r\n  // #endregion\r\n\r\n  // #region Bytecode\r\n\r\n  JS_ReadObject(ptr, ctx, buf, buf_len, flags) {\r\n    console.warn('Bytecode is not supported in WebGL Backend');\r\n  },\r\n\r\n  JS_WriteObject(ctx, psize, obj, flags) {\r\n    console.warn('Bytecode is not supported in WebGL Backend');\r\n    return 0 as IntPtr;\r\n  },\r\n\r\n  JS_EvalFunction(ptr, ctx, fun_obj) {\r\n    console.warn('Bytecode is not supported in WebGL Backend');\r\n  },\r\n\r\n  js_free(ctx, ptr) {\r\n    // TODO: Not sure what this is but seems related to Bytecode\r\n  },\r\n\r\n  // #endregion\r\n\r\n  // #region Misc features\r\n\r\n  JS_NewPromiseCapability(ret, ctx, resolving_funcs) {\r\n    // TODO\r\n    return 0;\r\n  },\r\n\r\n  JS_SetHostPromiseRejectionTracker(rt, cb, opaque) {\r\n    // TODO:\r\n  },\r\n\r\n  JS_SetInterruptHandler(rt, cb, opaque) {\r\n    // TODO:\r\n  },\r\n\r\n  JS_SetModuleLoaderFunc(rt, module_normalize, module_loader, opaque) {\r\n    // TODO:\r\n  },\r\n\r\n  JS_GetImportMeta(ret, ctx, m) {\r\n    // TODO:\r\n    return 0;\r\n  },\r\n\r\n  JS_ResolveModule(ctx, obj) {\r\n    // TODO:\r\n    return 0;\r\n  },\r\n\r\n  JS_AddIntrinsicOperators(ctx) {\r\n    console.warn('Operator overloading is not supported in WebGL Backend');\r\n  },\r\n\r\n  JS_ExecutePendingJob(rt, pctx) {\r\n    // Automatically handled by browsers\r\n    return false;\r\n  },\r\n\r\n  JS_IsJobPending(rt, pctx) {\r\n    // Automatically handled by browsers\r\n    return false;\r\n  },\r\n\r\n  // #endregion\r\n\r\n};\r\n\r\nautoAddDeps(UnityJSBPlugin, '$unityJsbState');\r\nmergeInto(LibraryManager.library, UnityJSBPlugin);\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WebGL/.source/tsconfig.json",
    "content": "{\r\n  \"compilerOptions\": {\r\n    \"target\": \"es5\",\r\n    \"lib\": [\r\n      \"dom\",\r\n      \"dom.iterable\",\r\n      \"esnext\"\r\n    ],\r\n    \"types\": [],\r\n    \"typeRoots\": [\r\n      \"typings\"\r\n    ],\r\n    \"baseUrl\": \"./\",\r\n    \"pretty\": true,\r\n    \"allowJs\": true,\r\n    \"skipLibCheck\": true,\r\n    \"forceConsistentCasingInFileNames\": true,\r\n    \"module\": \"none\",\r\n    \"allowUmdGlobalAccess\": true,\r\n    \"moduleResolution\": \"node\",\r\n    \"outDir\": \"..\",\r\n    \"outFile\": \"../jsbplugin.jslib\",\r\n    \"noImplicitAny\": false,\r\n    \"strict\": false,\r\n    \"noUnusedLocals\": false,\r\n    \"noUnusedParameters\": false,\r\n    \"removeComments\": false,\r\n    \"noImplicitUseStrict\": true,\r\n    \"noUncheckedIndexedAccess\": false,\r\n    \"suppressExcessPropertyErrors\": true,\r\n    \"suppressImplicitAnyIndexErrors\": true,\r\n    \"noPropertyAccessFromIndexSignature\": false,\r\n    \"strictNullChecks\": false\r\n  },\r\n  \"files\": [\r\n    \"jsbplugin.ts\",\r\n    \"typings/environment.d.ts\",\r\n    \"typings/jsapi.d.ts\",\r\n    \"typings/plugin.d.ts\"\r\n  ],\r\n  \"include\": [\r\n    \"typings/*.d.ts\",\r\n  ]\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WebGL/.source/typings/environment.d.ts",
    "content": "export { };\r\n\r\ndeclare global {\r\n\r\n  const UTF8ToString: (ptr: number, maxBytesToRead?: number) => string;\r\n  const stringToUTF8: (str: string, outPtr: number, maxBytesToRead?: number) => void;\r\n\r\n  const Pointer_stringify: (val: any) => string;\r\n  const lengthBytesUTF8: (val: any) => number;\r\n\r\n  const dynCall: <T = void>(\r\n    signature: T extends void ? string : string,\r\n    ptr: number | Pointer<any>,\r\n    args: T extends void ? (number | Pointer<any>)[] : Parameters<T>\r\n  ) => void;\r\n  const Runtime: any;\r\n  const LibraryManager: any;\r\n  const autoAddDeps: any;\r\n  const mergeInto: any;\r\n\r\n\r\n\r\n  function print(str: string): void;\r\n  function printErr(str: string): void;\r\n  const arguments: string[];\r\n  const environment: Emscripten.EnvironmentType;\r\n  const preInit: Array<{ (): void }>;\r\n  const preRun: Array<{ (): void }>;\r\n  const postRun: Array<{ (): void }>;\r\n  const onAbort: { (what: any): void };\r\n  const onRuntimeInitialized: { (): void };\r\n  const preinitializedWebGLContext: WebGLRenderingContext;\r\n  const noInitialRun: boolean;\r\n  const noExitRuntime: boolean;\r\n  const logReadFiles: boolean;\r\n  const filePackagePrefixURL: string;\r\n  const wasmBinary: ArrayBuffer;\r\n\r\n  function destroy(object: object): void;\r\n  function getPreloadedPackage(remotePackageName: string, remotePackageSize: number): ArrayBuffer;\r\n  function instantiateWasm(\r\n    imports: Emscripten.WebAssemblyImports,\r\n    successCallback: (module: WebAssembly.Module) => void,\r\n  ): Emscripten.WebAssemblyExports;\r\n  function locateFile(url: string, scriptDirectory: string): string;\r\n  function onCustomMessage(event: MessageEvent): void;\r\n\r\n  // USE_TYPED_ARRAYS == 1\r\n  const HEAP: Int32Array;\r\n  const IHEAP: Int32Array;\r\n  const FHEAP: Float64Array;\r\n\r\n  // USE_TYPED_ARRAYS == 2\r\n  const HEAP8: Int8Array;\r\n  const HEAP16: Int16Array;\r\n  const HEAP32: Int32Array;\r\n  const HEAPU8: Uint8Array;\r\n  const HEAPU16: Uint16Array;\r\n  const HEAPU32: Uint32Array;\r\n  const HEAPF32: Float32Array;\r\n  const HEAPF64: Float64Array;\r\n\r\n  const TOTAL_STACK: number;\r\n  const TOTAL_MEMORY: number;\r\n  const FAST_MEMORY: number;\r\n\r\n  function addOnPreRun(cb: () => any): void;\r\n  function addOnInit(cb: () => any): void;\r\n  function addOnPreMain(cb: () => any): void;\r\n  function addOnExit(cb: () => any): void;\r\n  function addOnPostRun(cb: () => any): void;\r\n\r\n  const preloadedImages: any;\r\n  const preloadedAudios: any;\r\n\r\n  function _malloc(size: number): number;\r\n  function _memcpy(target: number, src: number, size: number): void;\r\n  function _free(ptr: number): void;\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WebGL/.source/typings/jsapi.d.ts",
    "content": "export { };\r\n\r\ndeclare global {\r\n  // export type Pointer<T> = number & {\r\n  //   type?: T;\r\n  //   __pointer: true;\r\n  // };\r\n\r\n  export type Pointer<T> = number & {\r\n    type?: T;\r\n    __pointer: true;\r\n  };\r\n\r\n  export type PointerArray<T> = number & {\r\n    type?: T;\r\n    __pointerArray: true;\r\n  };\r\n\r\n  export type Out<T> = number & {\r\n    type?: T;\r\n    __out: true;\r\n  };\r\n\r\n  export type Boolish = boolean | -1;\r\n\r\n  export type int = number;\r\n  export type Byte = number;\r\n  export type Int64 = number;\r\n  export type UInt32 = number;\r\n\r\n  export type IntPtr = Pointer<'IntPtr'>;\r\n  export type JSPayloadHeader = Pointer<'JSPayloadHeader'>;\r\n  export type JSValue = Pointer<'JSValue'>;\r\n  export type JSValueConst = JSValue;\r\n  export type JSAtom = UInt32;\r\n  export type JSContext = UInt32;\r\n  export type JSRuntime = UInt32;\r\n  export type JSModuleDef = UInt32;\r\n  export type JSClassID = UInt32;\r\n  export type JSMemoryUsage = Pointer<'JSMemoryUsage'>;\r\n  export type size_t = number;\r\n\r\n  export declare interface JSApiExternals {\r\n    static JS_SetModuleLoaderFunc(rt: JSRuntime, module_normalize: IntPtr, module_loader: IntPtr, opaque: IntPtr): void;\r\n    static JS_GetImportMeta(returnValue: JSValue, ctx: JSContext, m: JSModuleDef);\r\n    static JSB_GetBridgeClassID(): JSClassID;\r\n    static jsb_construct_bridge_object(returnValue: JSValue, ctx: JSContext, proto: JSValue, object_id: number);\r\n    static jsb_new_bridge_object(returnValue: JSValue, ctx: JSContext, proto: JSValue, object_id: number);\r\n    static JSB_NewBridgeClassObject(returnValue: JSValue, ctx: JSContext, new_target: JSValue, object_id: number);\r\n    static jsb_new_bridge_value(returnValue: JSValue, ctx: JSContext, proto: JSValue, size: UInt32);\r\n    static JSB_NewBridgeClassValue(returnValue: JSValue, ctx: JSContext, new_target: JSValue, size: number);\r\n    static JSB_FreePayload(returnValue: JSPayloadHeader, ctx: JSContext, val: JSValue);\r\n    static jsb_get_payload_header(returnValue: JSPayloadHeader, ctx: JSContext, val: JSValue);\r\n    static JSB_NewRuntime(class_finalizer: IntPtr): JSRuntime;\r\n    static JSB_GetRuntimeOpaque(rt: JSRuntime): IntPtr;\r\n    static JSB_SetRuntimeOpaque(rt: JSRuntime, opaque: IntPtr): void;\r\n    static JSB_FreeRuntime(rt: JSRuntime): Boolish;\r\n    static JS_GetRuntime(ctx: JSContext): JSRuntime;\r\n    static JS_NewContext(rt: JSRuntime): JSContext;\r\n    static JS_FreeContext(ctx: JSContext): void;\r\n    static JS_GetGlobalObject(returnValue: JSValue, ctx: JSContext);\r\n    static JS_IsInstanceOf(ctx: JSContext, val: JSValue, obj: JSValue): Boolish;\r\n    static JS_NewPromiseCapability(returnValue: JSValue, ctx: JSContext, resolving_funcs: Pointer<JSValue>);\r\n    static JS_SetHostPromiseRejectionTracker(rt: JSRuntime, cb: IntPtr, opaque: IntPtr): void;\r\n    static JS_GetPropertyUint32(returnValue: JSValue, ctx: JSContext, this_obj: JSValue, idx: UInt32);\r\n    static JS_GetPropertyInternal(returnValue: JSValue, ctx: JSContext, obj: JSValue, prop: JSAtom, receiver: JSValue, throw_ref_error: number);\r\n    static JS_GetPropertyStr(returnValue: JSValue, ctx: JSContext, this_obj: JSValue, prop: Pointer<string>);\r\n    static JS_DefineProperty(ctx: JSContext, this_obj: JSValue, prop: JSAtom, val: JSValue, getter: JSValue, setter: JSValue, flags: JSPropFlags): Boolish;\r\n    static JS_DefinePropertyValue(ctx: JSContext, this_obj: JSValue, prop: JSAtom, val: JSValue, flags: JSPropFlags): Boolish;\r\n    static JS_GetException(returnValue: JSValue, ctx: JSContext);\r\n    static JS_IsError(ctx: JSContext, val: JSValue): Boolish;\r\n    static JSB_ThrowError(returnValue: JSValue, ctx: JSContext, buf: Pointer<Byte>, buf_len: size_t);\r\n    static JSB_ThrowTypeError(returnValue: JSValue, ctx: JSContext, msg: Pointer<Byte>);\r\n    static JSB_ThrowInternalError(returnValue: JSValue, ctx: JSContext, msg: Pointer<Byte>);\r\n    static JSB_ThrowRangeError(returnValue: JSValue, ctx: JSContext, msg: Pointer<Byte>);\r\n    static JSB_ThrowReferenceError(returnValue: JSValue, ctx: JSContext, msg: Pointer<Byte>);\r\n    static JSB_NewEmptyString(returnValue: JSValue, ctx: JSContext);\r\n    static JS_NewString(returnValue: JSValue, ctx: JSContext, str: Pointer<Byte>);\r\n    static JS_NewStringLen(returnValue: JSValue, ctx: JSContext, buf: Pointer<Byte>, buf_len: size_t);\r\n    static JSB_NewInt64(returnValue: JSValue, ctx: JSContext, val: Int64);\r\n    static JSB_NewFloat64(returnValue: JSValue, ctx: JSContext, d: number);\r\n    static JS_NewAtomLen(ctx: JSContext, str: Pointer<Byte>, len: size_t): JSAtom;\r\n    static JS_DupAtom(ctx: JSContext, v: JSAtom): JSAtom;\r\n    static JS_FreeAtom(ctx: JSContext, v: JSAtom): void;\r\n    static JS_AtomToString(returnValue: JSValue, ctx: JSContext, atom: JSAtom);\r\n    static jsb_crossbind_constructor(returnValue: JSValue, ctx: JSContext, new_target: JSValue);\r\n    static JS_NewObject(returnValue: JSValue, ctx: JSContext);\r\n    static JS_IsFunction(ctx: JSContext, val: JSValue): Boolish;\r\n    static JS_IsConstructor(ctx: JSContext, val: JSValue): Boolish;\r\n    static JS_NewArray(returnValue: JSValue, ctx: JSContext);\r\n    static JS_IsArray(ctx: JSContext, val: JSValue): Boolish;\r\n    static JS_GetContextOpaque(ctx: JSContext): IntPtr;\r\n    static JS_SetContextOpaque(ctx: JSContext, opaque: IntPtr): void;\r\n    static JSB_NewCFunctionMagic(returnValue: JSValue, ctx: JSContext, func: IntPtr, atom: JSAtom, length: number, cproto: JSCFunctionEnum, magic: number);\r\n    static JSB_NewCFunction(returnValue: JSValue, ctx: JSContext, func: IntPtr, atom: JSAtom, length: number, cproto: JSCFunctionEnum, magic: number);\r\n    static JS_SetConstructor(ctx: JSContext, func_obj: JSValue, proto: JSValue): void;\r\n    static JS_SetPropertyInternal(ctx: JSContext, this_obj: JSValue, prop: JSAtom, val: JSValue, flags: number): Boolish;\r\n    static JS_SetPropertyUint32(ctx: JSContext, this_obj: JSValue, idx: UInt32, val: JSValue): Boolish;\r\n    static JS_HasProperty(ctx: JSContext, this_obj: JSValue, prop: JSAtom): Boolish;\r\n    static JS_ParseJSON(returnValue: JSValue, ctx: JSContext, buf: Pointer<Byte>, buf_len: size_t, filename: Pointer<Byte>);\r\n    static JS_JSONStringify(returnValue: JSValue, ctx: JSContext, obj: JSValue, replacer: JSValue, space0: JSValue);\r\n    static JS_CallConstructor(returnValue: JSValue, ctx: JSContext, func_obj: JSValue, argc: number, argv: PointerArray<JSValue>);\r\n    static JS_Call(returnValue: JSValue, ctx: JSContext, func_obj: JSValue, this_obj: JSValue, argc: number, argv: PointerArray<JSValue>);\r\n    static JS_Invoke(returnValue: JSValue, ctx: JSContext, this_val: JSValue, atom: JSAtom, argc: number, argv: PointerArray<JSValue>);\r\n    static JS_SetPrototype(ctx: JSContext, obj: JSValue, proto_val: JSValue): Boolish;\r\n    static JS_RunGC(rt: JSRuntime): void;\r\n    static JS_ToBool(ctx: JSContext, val: JSValue): Boolish;\r\n    static js_free(ctx: JSContext, ptr: IntPtr): void;\r\n    static JS_ReadObject(returnValue: JSValue, ctx: JSContext, buf: Pointer<Byte>, buf_len: size_t, flags: number);\r\n    static JS_Eval(returnValue: JSValue, ctx: JSContext, input: Pointer<Byte>, input_len: size_t, filename: Pointer<Byte>, eval_flags: JSEvalFlags);\r\n    static JS_EvalFunction(returnValue: JSValue, ctx: JSContext, fun_obj: JSValue);\r\n    static JS_ResolveModule(ctx: JSContext, obj: JSValue): number;\r\n    static JSB_DupValue(returnValue: JSValue, ctx: JSContext, v: JSValue);\r\n    static JSB_FreeValue(ctx: JSContext, v: JSValue): void;\r\n    static JSB_FreeValueRT(rt: JSRuntime, v: JSValue): void;\r\n    static JS_AddIntrinsicOperators(ctx: JSContext): void;\r\n    static JSB_ATOM_Proxy(): JSAtom;\r\n    static JSB_ATOM_constructor(): JSAtom;\r\n    static JSB_ATOM_Number(): JSAtom;\r\n    static JSB_ATOM_Object(): JSAtom;\r\n    static JSB_ATOM_String(): JSAtom;\r\n    static JSB_ATOM_Function(): JSAtom;\r\n    static JSB_ATOM_Error(): JSAtom;\r\n    static JSB_ATOM_Operators(): JSAtom;\r\n    static JSB_ATOM_Symbol_operatorSet(): JSAtom;\r\n    static JSB_ATOM_name(): JSAtom;\r\n    static JSB_ATOM_message(): JSAtom;\r\n    static JSB_ATOM_fileName(): JSAtom;\r\n    static JSB_ATOM_lineNumber(): JSAtom;\r\n    static JSB_ATOM_length(): JSAtom;\r\n    static JSB_ATOM_stack(): JSAtom;\r\n    static JSB_ATOM_prototype(): JSAtom;\r\n    static JSB_Init(): number;\r\n    static JS_FreeCString(ctx: JSContext, ptr: IntPtr): void;\r\n    static js_strndup(ctx: JSContext, s: Pointer<Byte>, n: size_t): IntPtr;\r\n    static JS_NewArrayBufferCopy(returnValue: JSValue, ctx: JSContext, buf: Pointer<Byte>, len: size_t);\r\n    static JS_ComputeMemoryUsage(rt: JSRuntime, s: Pointer<JSMemoryUsage>): void;\r\n    static JS_SetInterruptHandler(rt: JSRuntime, cb: IntPtr, opaque: IntPtr): void;\r\n\r\n    static JS_IsJobPending(rt: JSRuntime, pctx: Out<JSContext>): Boolish;\r\n    static JS_ExecutePendingJob(rt: JSRuntime, pctx: Out<JSContext>): Boolish;\r\n    static JS_ToInt32(ctx: JSContext, pres: Out<number>, val: JSValue): Boolish;\r\n    static JS_ToInt64(ctx: JSContext, pres: Out<number>, val: JSValue): Boolish;\r\n    static JS_ToBigInt64(ctx: JSContext, pres: Out<number>, val: JSValue): Boolish;\r\n    static JS_ToIndex(ctx: JSContext, plen: Out<number>, val: JSValue): Boolish;\r\n    static JS_ToFloat64(ctx: JSContext, pres: Out<number>, val: JSValue): Boolish;\r\n    static JSB_ToUint32(ctx: JSContext, pres: Out<number>, val: JSValue): Boolish;\r\n    static JS_WriteObject(ctx: JSContext, psize: Out<number>, obj: JSValue, flags: number): IntPtr;\r\n    static JS_ToCStringLen2(ctx: JSContext, len: Out<number>, val: JSValue, cesu8: boolean): IntPtr;\r\n    static JS_GetArrayBuffer(ctx: JSContext, psize: Out<size_t>, obj: JSValue): IntPtr;\r\n\r\n    static jsb_get_float_2(ctx: JSContext, val: JSValue, v0: Out<number>, v1: Out<number>): Boolish;\r\n    static jsb_get_float_3(ctx: JSContext, val: JSValue, v0: Out<number>, v1: Out<number>, v2: Out<number>): Boolish;\r\n    static jsb_get_float_4(ctx: JSContext, val: JSValue, v0: Out<number>, v1: Out<number>, v2: Out<number>, v3: Out<number>): Boolish;\r\n    static jsb_get_int_1(ctx: JSContext, val: JSValue, v0: Out<number>): Boolish;\r\n    static jsb_get_int_2(ctx: JSContext, val: JSValue, v0: Out<number>, v1: Out<number>): Boolish;\r\n    static jsb_get_int_3(ctx: JSContext, val: JSValue, v0: Out<number>, v1: Out<number>, v2: Out<number>): Boolish;\r\n    static jsb_get_int_4(ctx: JSContext, val: JSValue, v0: Out<number>, v1: Out<number>, v2: Out<number>, v3: Out<number>): Boolish;\r\n    static jsb_get_byte_4(ctx: JSContext, val: JSValue, v0: Out<number>, v1: Out<number>, v2: Out<number>, v3: Out<number>): Boolish;\r\n    static jsb_get_floats(ctx: JSContext, val: JSValue, n: number, v0: Pointer<number>): Boolish;\r\n    static jsb_get_bytes(ctx: JSContext, val: JSValue, n: number, v0: Pointer<Byte>): Boolish;\r\n\r\n    static jsb_set_floats(ctx: JSContext, val: JSValue, n: number, v0: Pointer<number>): Boolish;\r\n    static jsb_set_float_2(ctx: JSContext, val: JSValue, v0: number, v1: number): Boolish;\r\n    static jsb_set_float_3(ctx: JSContext, val: JSValue, v0: number, v1: number, v2: number): Boolish;\r\n    static jsb_set_float_4(ctx: JSContext, val: JSValue, v0: number, v1: number, v2: number, v3: number): Boolish;\r\n    static jsb_set_int_1(ctx: JSContext, val: JSValue, v0: number): Boolish;\r\n    static jsb_set_int_2(ctx: JSContext, val: JSValue, v0: number, v1: number): Boolish;\r\n    static jsb_set_int_3(ctx: JSContext, val: JSValue, v0: number, v1: number, v2: number): Boolish;\r\n    static jsb_set_int_4(ctx: JSContext, val: JSValue, v0: number, v1: number, v2: number, v3: number): Boolish;\r\n    static jsb_set_byte_4(ctx: JSContext, val: JSValue, v0: Byte, v1: Byte, v2: Byte, v3: Byte): Boolish;\r\n    static jsb_set_bytes(ctx: JSContext, val: JSValue, n: number, v0: Pointer<Byte>): Boolish;\r\n\r\n    static JS_SetBaseUrl(ctx: JSContext, url: Pointer<string>): void;\r\n  }\r\n\r\n  export declare class JSApiDelegates {\r\n    static JSInterruptHandler(rt: JSRuntime, opaque: IntPtr): int;\r\n    static JSHostPromiseRejectionTracker(ctx: JSContext, promise: JSValueConst, reason: JSValueConst, is_handled: bool, opaque: IntPtr): void;\r\n    static JSModuleNormalizeFunc(ctx: JSContext, module_base_name: Pointer<string>, module_name: Pointer<string>, opaque: IntPtr): IntPtr;\r\n    static JSModuleLoaderFunc(ctx: JSContext, module_name: Pointer<string>, opaque: IntPtr): JSModuleDef;\r\n    static JSGCObjectFinalizer(rt: JSRuntime, header: JSPayloadHeader): void;\r\n    static JSCFunction(returnValue: JSValue, ctx: JSContext, this_obj: JSValueConst, argc: int, argv: PointerArray<JSValueConst>);\r\n    static JSCFunctionMagic(returnValue: JSValue, ctx: JSContext, this_obj: JSValueConst, argc: int, argv: PointerArray<JSValueConst>, magic: int);\r\n    static JSSetterCFunction(returnValue: JSValue, ctx: JSContext, this_val: JSValueConst, val: JSValueConst);\r\n    static JSSetterCFunctionMagic(returnValue: JSValue, ctx: JSContext, this_val: JSValueConst, val: JSValueConst, magic: int);\r\n    static JSGetterCFunction(returnValue: JSValue, ctx: JSContext, this_val: JSValueConst);\r\n    static JSGetterCFunctionMagic(returnValue: JSValue, ctx: JSContext, this_val: JSValueConst, magic: int);\r\n    static JSLogCFunction(level: number, line: Pointer<string>): void;\r\n    static JSWaitingForDebuggerCFunction(ctx: JSContext): void;\r\n  }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WebGL/.source/typings/plugin.d.ts",
    "content": "export { };\r\n\r\ndeclare global {\r\n  var unityJsbState: PluginState;\r\n\r\n  export declare type PluginState = {\r\n    stringify: ((ptr: number | Pointer<string>, bufferLength?: number) => string);\r\n    bufferify: ((str: string) => [number, number]);\r\n    dynCall: typeof dynCall;\r\n    runtimes: Record<string, PluginRuntime | undefined>;\r\n    contexts: Record<string, PluginContext | undefined>;\r\n    lastRuntimeId: number;\r\n    lastContextId: number;\r\n    atoms?: AtomReferences;\r\n    createObjectReferences: () => ObjectReferences;\r\n    createAtoms: () => AtomReferences;\r\n\r\n    getRuntime: (ctx: JSRuntime) => PluginRuntime;\r\n    getContext: (ctx: JSContext) => PluginContext;\r\n\r\n    HEAP64: () => BigInt64Array;\r\n    HEAPU64: () => BigUint64Array;\r\n  }\r\n\r\n  export declare type PluginRuntime = {\r\n    id: number;\r\n    opaque?: any;\r\n    contexts: Record<string, PluginContext | undefined>;\r\n    refs: ObjectReferences;\r\n    isDestroyed: boolean;\r\n    garbageCollect(): number;\r\n  };\r\n\r\n  export declare type PluginContext = {\r\n    id: number;\r\n    opaque?: any;\r\n    runtime: PluginRuntime;\r\n    runtimeId: number;\r\n    isDestroyed: boolean;\r\n\r\n    window: Window;\r\n    iframe: HTMLIFrameElement;\r\n    contentWindow: Window;\r\n\r\n    globalObject: Window;\r\n    globalObjectId?: number;\r\n\r\n    evaluate: ((script: string, filename?: string) => any);\r\n    lastException?: Error;\r\n\r\n    free(): void;\r\n    setBaseUrl(url: string): void;\r\n  };\r\n\r\n  export declare type AtomReferences = {\r\n    record: Record<number, AtomReference>;\r\n    get: ((ref: JSAtom) => string);\r\n    lastId: number;\r\n    push: ((str: string) => JSAtom);\r\n    pushId: ((id: JSAtom) => JSAtom);\r\n    pop: ((ref: JSAtom) => void);\r\n  };\r\n\r\n  export declare type AtomReference = {\r\n    id: number;\r\n    value: string;\r\n    refCount: number;\r\n  }\r\n\r\n  export declare type ObjectReferences = {\r\n    deleteRecord: (id: number) => void;\r\n    record: Record<number, ObjectReference>;\r\n    get: ((ref: JSValue) => any);\r\n    getRecord: ((ref: JSValue) => ObjectReference);\r\n    push: ((obj: any, ptr: JSValue) => number | undefined);\r\n    duplicate: ((obj: JSValue, ptr: JSValue) => void);\r\n    duplicateId: ((id: number, ptr: JSValue) => void);\r\n    pop: ((obj: JSValue) => void);\r\n    popId: ((id: number | undefined) => void);\r\n    allocate: ((obj: any) => [JSValue, number | undefined]);\r\n    batchAllocate: ((objs: any[]) => [PointerArray<JSValue>, (number | undefined)[]]);\r\n    batchGet: ((arr: PointerArray<JSValue>, count: number) => any[]);\r\n    lastId: number;\r\n    setPayload: ((obj: any, type: BridgeObjectType, payload: number) => void);\r\n    getPayload: ((obj: any) => ObjectReferencePayload);\r\n    clearPayload: ((obj: any) => void);\r\n    payloadMap: Map<any, ObjectReferencePayload>;\r\n  };\r\n\r\n  export declare type ObjectReference = {\r\n    id: number;\r\n    refCount: number;\r\n    tag: Tags;\r\n    value: any;\r\n  };\r\n\r\n  export declare type ObjectReferencePayload = {\r\n    type: BridgeObjectType;\r\n    payload: number;\r\n  };\r\n\r\n  export declare type BridgeStruct = {\r\n    $$values: number[];\r\n  };\r\n\r\n  const enum JSPropFlags {\r\n    /* flags for object properties */\r\n    JS_PROP_CONFIGURABLE = (1 << 0),\r\n    JS_PROP_WRITABLE = (1 << 1),\r\n    JS_PROP_ENUMERABLE = (1 << 2),\r\n    JS_PROP_C_W_E = (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE | JS_PROP_ENUMERABLE),\r\n    JS_PROP_LENGTH = (1 << 3) /* used internally in Arrays */,\r\n    JS_PROP_TMASK = (3 << 4) /* mask for NORMAL, GETSET, VARREF, AUTOINIT */,\r\n    JS_PROP_NORMAL = (0 << 4),\r\n    JS_PROP_GETSET = (1 << 4),\r\n    JS_PROP_VARREF = (2 << 4) /* used internally */,\r\n    JS_PROP_AUTOINIT = (3 << 4) /* used internally */,\r\n\r\n    /* flags for JS_DefineProperty */\r\n    JS_PROP_HAS_SHIFT = 8,\r\n    JS_PROP_HAS_CONFIGURABLE = (1 << 8),\r\n    JS_PROP_HAS_WRITABLE = (1 << 9),\r\n    JS_PROP_HAS_ENUMERABLE = (1 << 10),\r\n    JS_PROP_HAS_GET = (1 << 11),\r\n    JS_PROP_HAS_SET = (1 << 12),\r\n    JS_PROP_HAS_VALUE = (1 << 13),\r\n\r\n    /* throw an exception if false would be returned\r\n       (JS_DefineProperty/JS_SetProperty) */\r\n    JS_PROP_THROW = (1 << 14),\r\n\r\n    /* throw an exception if false would be returned in strict mode\r\n       (JS_SetProperty) */\r\n    JS_PROP_THROW_STRICT = (1 << 15),\r\n\r\n    JS_PROP_NO_ADD = (1 << 16) /* internal use */,\r\n    JS_PROP_NO_EXOTIC = (1 << 17) /* internal use */,\r\n\r\n    // custom values\r\n    CONST_VALUE = JS_PROP_HAS_VALUE | JS_PROP_ENUMERABLE,\r\n    DEFAULT = JS_PROP_CONFIGURABLE | JS_PROP_ENUMERABLE,\r\n    NONE = 0,\r\n  }\r\n\r\n  const enum Tags {\r\n    JS_TAG_FIRST = -11, /* first negative tag */\r\n    JS_TAG_BIG_DECIMAL = -11,\r\n    JS_TAG_BIG_INT = -10,\r\n    JS_TAG_BIG_FLOAT = -9,\r\n    JS_TAG_SYMBOL = -8,\r\n    JS_TAG_STRING = -7,\r\n    JS_TAG_MODULE = -3, /* used internally */\r\n    JS_TAG_FUNCTION_BYTECODE = -2, /* used internally */\r\n    JS_TAG_OBJECT = -1,\r\n    JS_TAG_INT = 0,\r\n    JS_TAG_BOOL = 1,\r\n    JS_TAG_NULL = 2,\r\n    JS_TAG_UNDEFINED = 3,\r\n    JS_TAG_EXCEPTION = 6,\r\n    JS_TAG_FLOAT64 = 7,\r\n  }\r\n\r\n  const enum Constants {\r\n    VERSION = 0x010704,\r\n    CS_JSB_VERSION = 0xa,\r\n\r\n    JS_WRITE_OBJ_BYTECODE = 1 << 0, /* allow function/module */\r\n    JS_WRITE_OBJ_BSWAP = 1 << 1, /* byte swapped output */\r\n    JS_WRITE_OBJ_SAB = 1 << 2, /* allow SharedArrayBuffer */\r\n    JS_WRITE_OBJ_REFERENCE = 1 << 3, /* allow object references to encode arbitrary object graph */\r\n    JS_READ_OBJ_BYTECODE = 1 << 0, /* allow function/module */\r\n    JS_READ_OBJ_ROM_DATA = 1 << 1, /* avoid duplicating 'buf' data */\r\n    JS_READ_OBJ_SAB = 1 << 2, /* allow SharedArrayBuffer */\r\n    JS_READ_OBJ_REFERENCE = 1 << 3, /* allow object references */\r\n  }\r\n\r\n  const enum JSEvalFlags {\r\n    JS_EVAL_TYPE_GLOBAL = (0 << 0) /* global code (default) */,\r\n    JS_EVAL_TYPE_MODULE = (1 << 0) /* module code */,\r\n    JS_EVAL_TYPE_DIRECT = (2 << 0) /* direct call (internal use) */,\r\n    JS_EVAL_TYPE_INDIRECT = (3 << 0) /* indirect call (internal use) */,\r\n    JS_EVAL_TYPE_MASK = (3 << 0),\r\n\r\n    JS_EVAL_FLAG_STRICT = (1 << 3) /* force 'strict' mode */,\r\n    JS_EVAL_FLAG_STRIP = (1 << 4) /* force 'strip' mode */,\r\n\r\n    /* compile but do not run. The result is an object with a\r\n       JS_TAG_FUNCTION_BYTECODE or JS_TAG_MODULE tag. It can be executed\r\n       with JS_EvalFunction(). */\r\n    JS_EVAL_FLAG_COMPILE_ONLY = (1 << 5),\r\n\r\n    /* don't include the stack frames before this eval in the Error() backtraces */\r\n    JS_EVAL_FLAG_BACKTRACE_BARRIER = (1 << 6),\r\n  }\r\n\r\n\r\n  const enum BridgeObjectType {\r\n    None = 0,\r\n    TypeRef = 1,\r\n    ObjectRef = 2,\r\n    ValueType = 3,\r\n  }\r\n\r\n  const enum JSCFunctionEnum {\r\n    /* XXX: should rename for namespace isolation */\r\n    JS_CFUNC_generic = 0,\r\n    JS_CFUNC_generic_magic = 1,\r\n    JS_CFUNC_constructor = 2, // unused in jsb\r\n    JS_CFUNC_constructor_magic = 3,\r\n    JS_CFUNC_constructor_or_func = 4, // unused in jsb\r\n    JS_CFUNC_constructor_or_func_magic = 5, // unused in jsb\r\n    JS_CFUNC_f_f = 6, // unused in jsb\r\n    JS_CFUNC_f_f_f = 7, // unused in jsb\r\n    JS_CFUNC_getter = 8,\r\n    JS_CFUNC_setter = 9,\r\n    JS_CFUNC_getter_magic = 10,\r\n    JS_CFUNC_setter_magic = 11,\r\n    JS_CFUNC_iterator_next = 12, // unused in jsb\r\n  }\r\n\r\n\r\n  const enum Sizes {\r\n    JSPayloadHeader = 8,\r\n    JSValueUnion = 8,\r\n    JSValue = 16,\r\n    JSAtom = 4,\r\n    Single = 4,\r\n    Double = 8,\r\n  }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WebGL/jsbplugin.jslib",
    "content": "/**\r\n * Build with the following command:\r\n * npx -p typescript tsc\r\n *\r\n * BEWARE: Using some syntaxes will make Emscripten fail while building\r\n * Such known syntaxes: Object spread (...), BigInt literals\r\n * The output is targeted for es5 as Emscripten only understands that syntax\r\n */\r\nvar UnityJSBPlugin = {\r\n    $unityJsbState__postset: 'unityJsbState.atoms = unityJsbState.createAtoms();\\n',\r\n    $unityJsbState: {\r\n        createObjectReferences: function () {\r\n            var getTag = function (object) {\r\n                if (object === undefined)\r\n                    return 3 /* Tags.JS_TAG_UNDEFINED */;\r\n                if (object === null)\r\n                    return 2 /* Tags.JS_TAG_NULL */;\r\n                if (typeof object === 'number')\r\n                    return 7 /* Tags.JS_TAG_FLOAT64 */;\r\n                if (typeof object === 'boolean')\r\n                    return 1 /* Tags.JS_TAG_BOOL */;\r\n                if (typeof object === 'symbol')\r\n                    return -8 /* Tags.JS_TAG_SYMBOL */;\r\n                if (typeof object === 'string')\r\n                    return -7 /* Tags.JS_TAG_STRING */;\r\n                if (typeof object === 'bigint')\r\n                    return -10 /* Tags.JS_TAG_BIG_INT */;\r\n                if (object instanceof Error)\r\n                    return 6 /* Tags.JS_TAG_EXCEPTION */;\r\n                return -1 /* Tags.JS_TAG_OBJECT */;\r\n            };\r\n            var record = {};\r\n            var map = new Map();\r\n            var payloadMap = new Map();\r\n            var res = {\r\n                record: record,\r\n                lastId: 0,\r\n                allocate: function (object) {\r\n                    var ptr = _malloc(16 /* Sizes.JSValue */);\r\n                    var id = res.push(object, ptr);\r\n                    return [ptr, id];\r\n                },\r\n                batchAllocate: function (objects) {\r\n                    var size = 16 /* Sizes.JSValue */;\r\n                    var len = objects.length;\r\n                    var arr = _malloc(size * len);\r\n                    var ids = Array(len);\r\n                    for (var index = 0; index < len; index++) {\r\n                        var object = objects[index];\r\n                        var id = res.push(object, arr + (index * size));\r\n                        ids[index] = id;\r\n                    }\r\n                    return [arr, ids];\r\n                },\r\n                batchGet: function (ptrs, count) {\r\n                    var size = 16 /* Sizes.JSValue */;\r\n                    var arr = new Array(count);\r\n                    for (var index = 0; index < count; index++) {\r\n                        var object = res.get(ptrs + index * size);\r\n                        arr[index] = object;\r\n                    }\r\n                    return arr;\r\n                },\r\n                push: function (object, ptr) {\r\n                    if (typeof object === 'undefined') {\r\n                        res.duplicateId(0, ptr);\r\n                        return;\r\n                    }\r\n                    if (typeof object === 'number') {\r\n                        if (typeof ptr === 'number') {\r\n                            HEAPF64[ptr >> 3] = object;\r\n                            unityJsbState.HEAP64()[(ptr >> 3) + 1] = BigInt(7 /* Tags.JS_TAG_FLOAT64 */);\r\n                        }\r\n                        return;\r\n                    }\r\n                    if (typeof object === 'boolean') {\r\n                        if (typeof ptr === 'number') {\r\n                            HEAP32[ptr >> 2] = object ? 1 : 0;\r\n                            HEAP32[(ptr >> 2) + 1] = 0;\r\n                            unityJsbState.HEAP64()[(ptr >> 3) + 1] = BigInt(1 /* Tags.JS_TAG_BOOL */);\r\n                        }\r\n                        return;\r\n                    }\r\n                    var foundId = map.get(object);\r\n                    if (foundId > 0) {\r\n                        res.duplicateId(foundId, ptr);\r\n                        return foundId;\r\n                    }\r\n                    var id = ++res.lastId;\r\n                    record[id] = {\r\n                        id: id,\r\n                        refCount: 0,\r\n                        value: object,\r\n                        tag: getTag(object),\r\n                    };\r\n                    map.set(object, id);\r\n                    res.duplicateId(id, ptr);\r\n                    return id;\r\n                },\r\n                get: function (val) {\r\n                    var tag = Number(unityJsbState.HEAP64()[(val >> 3) + 1]);\r\n                    if (tag === 0 /* Tags.JS_TAG_INT */) {\r\n                        return HEAP32[val >> 2];\r\n                    }\r\n                    else if (tag === 1 /* Tags.JS_TAG_BOOL */) {\r\n                        return !!HEAP32[val >> 2];\r\n                    }\r\n                    else if (tag === 7 /* Tags.JS_TAG_FLOAT64 */) {\r\n                        return HEAPF64[val >> 3];\r\n                    }\r\n                    else {\r\n                        var id = HEAP32[val >> 2];\r\n                        if (id === 0)\r\n                            return undefined;\r\n                        var ho = record[id];\r\n                        return ho.value;\r\n                    }\r\n                },\r\n                getRecord: function (val) {\r\n                    var tag = Number(unityJsbState.HEAP64()[(val >> 3) + 1]);\r\n                    if (tag === 0 /* Tags.JS_TAG_INT */) {\r\n                        var value = HEAP32[val >> 2];\r\n                        return {\r\n                            id: -1,\r\n                            refCount: 0,\r\n                            value: value,\r\n                            tag: tag,\r\n                        };\r\n                    }\r\n                    else if (tag === 1 /* Tags.JS_TAG_BOOL */) {\r\n                        var boolValue = !!HEAP32[val >> 2];\r\n                        return {\r\n                            id: -1,\r\n                            refCount: 0,\r\n                            value: boolValue,\r\n                            tag: tag,\r\n                        };\r\n                    }\r\n                    else if (tag === 7 /* Tags.JS_TAG_FLOAT64 */) {\r\n                        var value = HEAPF64[val >> 3];\r\n                        return {\r\n                            id: -1,\r\n                            refCount: 0,\r\n                            value: value,\r\n                            tag: tag,\r\n                        };\r\n                    }\r\n                    else {\r\n                        var id = HEAP32[val >> 2];\r\n                        if (id === 0)\r\n                            return {\r\n                                id: 0,\r\n                                refCount: 0,\r\n                                value: undefined,\r\n                                tag: 3 /* Tags.JS_TAG_UNDEFINED */,\r\n                                type: 0 /* BridgeObjectType.None */,\r\n                                payload: -1,\r\n                            };\r\n                        var ho = record[id];\r\n                        return ho;\r\n                    }\r\n                },\r\n                duplicate: function (obj, ptr) {\r\n                    var tag = Number(unityJsbState.HEAP64()[(obj >> 3) + 1]);\r\n                    if (tag === 7 /* Tags.JS_TAG_FLOAT64 */) {\r\n                        if (typeof ptr === 'number') {\r\n                            var val = HEAPF64[(obj >> 3)];\r\n                            HEAPF64[ptr >> 3] = val;\r\n                            unityJsbState.HEAP64()[(ptr >> 3) + 1] = BigInt(tag);\r\n                        }\r\n                        return;\r\n                    }\r\n                    else if (tag === 0 /* Tags.JS_TAG_INT */) {\r\n                        if (typeof ptr === 'number') {\r\n                            var val = HEAP32[(obj >> 2)];\r\n                            HEAP32[(ptr >> 2)] = val;\r\n                            HEAP32[(ptr >> 2) + 1] = 0;\r\n                            unityJsbState.HEAP64()[(ptr >> 3) + 1] = BigInt(tag);\r\n                        }\r\n                        return;\r\n                    }\r\n                    else if (tag === 1 /* Tags.JS_TAG_BOOL */) {\r\n                        if (typeof ptr === 'number') {\r\n                            var valBool = !!HEAP32[(obj >> 2)];\r\n                            HEAP32[(ptr >> 2)] = valBool ? 1 : 0;\r\n                            HEAP32[(ptr >> 2) + 1] = 0;\r\n                            unityJsbState.HEAP64()[(ptr >> 3) + 1] = BigInt(tag);\r\n                        }\r\n                        return;\r\n                    }\r\n                    var id = HEAP32[obj >> 2];\r\n                    res.duplicateId(id, ptr);\r\n                },\r\n                duplicateId: function (id, ptr) {\r\n                    if (id === 0) {\r\n                        if (typeof ptr === 'number') {\r\n                            HEAP32[ptr >> 2] = 0;\r\n                            HEAP32[(ptr >> 2) + 1] = 0;\r\n                            unityJsbState.HEAP64()[(ptr >> 3) + 1] = BigInt(3 /* Tags.JS_TAG_UNDEFINED */);\r\n                        }\r\n                        return;\r\n                    }\r\n                    var ho = record[id];\r\n                    ho.refCount += 1;\r\n                    if (typeof ptr === 'number') {\r\n                        HEAP32[ptr >> 2] = id;\r\n                        HEAP32[(ptr >> 2) + 1] = 0;\r\n                        unityJsbState.HEAP64()[(ptr >> 3) + 1] = BigInt(ho.tag);\r\n                    }\r\n                },\r\n                pop: function (obj) {\r\n                    var tag = Number(unityJsbState.HEAP64()[(obj >> 3) + 1]);\r\n                    if (tag === 7 /* Tags.JS_TAG_FLOAT64 */\r\n                        || tag === 0 /* Tags.JS_TAG_INT */\r\n                        || tag === 1 /* Tags.JS_TAG_BOOL */)\r\n                        return;\r\n                    var id = HEAP32[obj >> 2];\r\n                    res.popId(id);\r\n                },\r\n                popId: function (id) {\r\n                    if (!id)\r\n                        return;\r\n                    var ho = record[id];\r\n                    ho.refCount -= 1;\r\n                    console.assert(ho.refCount >= 0);\r\n                },\r\n                deleteRecord: function (id) {\r\n                    var rec = record[id];\r\n                    delete record[id];\r\n                    res.clearPayload(rec.value);\r\n                    map.delete(rec.value);\r\n                },\r\n                payloadMap: payloadMap,\r\n                setPayload: function (obj, type, payload) {\r\n                    payloadMap.set(obj, {\r\n                        type: type,\r\n                        payload: payload,\r\n                    });\r\n                },\r\n                getPayload: function (obj) {\r\n                    var res = payloadMap.get(obj);\r\n                    if (res)\r\n                        return res;\r\n                    else {\r\n                        return {\r\n                            type: 0 /* BridgeObjectType.None */,\r\n                            payload: 0,\r\n                        };\r\n                    }\r\n                },\r\n                clearPayload: function (obj) {\r\n                    payloadMap.delete(obj);\r\n                },\r\n            };\r\n            return res;\r\n        },\r\n        createAtoms: function () {\r\n            var record = {};\r\n            var map = new Map();\r\n            var res = {\r\n                record: record,\r\n                lastId: 0,\r\n                get: function (ref) {\r\n                    if (ref === 0)\r\n                        return undefined;\r\n                    return record[ref].value;\r\n                },\r\n                push: function (str) {\r\n                    if (str === undefined)\r\n                        return 0;\r\n                    var mapped = map.get(str);\r\n                    var id;\r\n                    if (!mapped) {\r\n                        id = ++res.lastId;\r\n                        var item = record[id] = {\r\n                            id: id,\r\n                            value: str,\r\n                            refCount: 1,\r\n                        };\r\n                        map.set(str, item);\r\n                    }\r\n                    else {\r\n                        id = mapped.id;\r\n                        mapped.refCount++;\r\n                    }\r\n                    return id;\r\n                },\r\n                pushId: function (id) {\r\n                    if (id === 0)\r\n                        return;\r\n                    var recorded = record[id];\r\n                    console.assert(!!recorded);\r\n                    if (!recorded)\r\n                        return 0;\r\n                    recorded.refCount++;\r\n                    return id;\r\n                },\r\n                pop: function (id) {\r\n                    if (id === 0)\r\n                        return;\r\n                    var recorded = record[id];\r\n                    console.assert(!!recorded);\r\n                    if (!recorded)\r\n                        return;\r\n                    recorded.refCount--;\r\n                    console.assert(recorded.refCount >= 0);\r\n                    if (recorded.refCount == 0) {\r\n                        map.delete(recorded.value);\r\n                        delete record[id];\r\n                    }\r\n                },\r\n            };\r\n            return res;\r\n        },\r\n        stringify: function (ptr, bufferLength) { return (typeof UTF8ToString !== 'undefined' ? UTF8ToString : Pointer_stringify)(ptr, bufferLength); },\r\n        bufferify: function (arg) {\r\n            var bufferSize = lengthBytesUTF8(arg) + 1;\r\n            var buffer = _malloc(bufferSize);\r\n            stringToUTF8(arg, buffer, bufferSize);\r\n            return [buffer, bufferSize];\r\n        },\r\n        dynCall: function () { return (typeof Runtime !== 'undefined' ? Runtime.dynCall : dynCall).apply(typeof Runtime !== 'undefined' ? Runtime : undefined, arguments); },\r\n        runtimes: {},\r\n        contexts: {},\r\n        lastRuntimeId: 1,\r\n        lastContextId: 1,\r\n        getRuntime: function (rt) {\r\n            var rtId = rt;\r\n            return unityJsbState.runtimes[rtId];\r\n        },\r\n        getContext: function (ctx) {\r\n            var ctxId = ctx;\r\n            return unityJsbState.contexts[ctxId];\r\n        },\r\n        HEAP64: function () {\r\n            return new BigInt64Array(HEAPF64.buffer);\r\n        },\r\n        HEAPU64: function () {\r\n            return new BigUint64Array(HEAPF64.buffer);\r\n        },\r\n    },\r\n    JSB_Init: function () {\r\n        return 10 /* Constants.CS_JSB_VERSION */;\r\n    },\r\n    JSB_NewRuntime: function (finalizer) {\r\n        // TODO: understand what to do with finalizer\r\n        var id = unityJsbState.lastRuntimeId++;\r\n        var refs = unityJsbState.createObjectReferences();\r\n        unityJsbState.runtimes[id] = {\r\n            id: id,\r\n            contexts: {},\r\n            refs: refs,\r\n            isDestroyed: false,\r\n            garbageCollect: function () {\r\n                var lastId = refs.lastId;\r\n                var record = refs.record;\r\n                var aliveItemCount = 0;\r\n                for (var index = 0; index <= lastId; index++) {\r\n                    var element = record[index];\r\n                    if (element) {\r\n                        if (element.refCount <= 0) {\r\n                            refs.deleteRecord(index);\r\n                        }\r\n                        else {\r\n                            aliveItemCount++;\r\n                        }\r\n                    }\r\n                }\r\n                return aliveItemCount;\r\n            },\r\n        };\r\n        return id;\r\n    },\r\n    JSB_GetRuntimeOpaque: function (rtId) {\r\n        return unityJsbState.getRuntime(rtId).opaque;\r\n    },\r\n    JSB_SetRuntimeOpaque: function (rtId, opaque) {\r\n        unityJsbState.getRuntime(rtId).opaque = opaque;\r\n    },\r\n    JS_GetContextOpaque: function (ctx) {\r\n        return unityJsbState.getContext(ctx).opaque;\r\n    },\r\n    JS_SetContextOpaque: function (ctx, opaque) {\r\n        unityJsbState.getContext(ctx).opaque = opaque;\r\n    },\r\n    JSB_FreeRuntime: function (rtId) {\r\n        var runtime = unityJsbState.getRuntime(rtId);\r\n        var ctxIds = Object.keys(runtime.contexts);\r\n        for (var index = 0; index < ctxIds.length; index++) {\r\n            var ctxId = ctxIds[index];\r\n            var context = runtime.contexts[ctxId];\r\n            context.free();\r\n        }\r\n        var aliveItemCount = runtime.garbageCollect();\r\n        runtime.isDestroyed = true;\r\n        delete unityJsbState.runtimes[runtime.id];\r\n        return aliveItemCount === 0;\r\n    },\r\n    JS_GetRuntime: function (ctxId) {\r\n        var context = unityJsbState.getContext(ctxId);\r\n        return context.runtimeId;\r\n    },\r\n    JS_NewContext: function (rtId) {\r\n        var _a, _b;\r\n        var id = unityJsbState.lastContextId++;\r\n        var runtime = unityJsbState.getRuntime(rtId);\r\n        var iframe = document.createElement('iframe');\r\n        iframe.name = 'unity-jsb-context-' + id;\r\n        iframe.style.display = 'none';\r\n        document.head.appendChild(iframe);\r\n        var contentWindow = iframe.contentWindow;\r\n        var fetch = contentWindow.fetch.bind(contentWindow);\r\n        var URL = contentWindow.URL;\r\n        var XMLHttpRequest = contentWindow.XMLHttpRequest;\r\n        var XMLHttpRequestUpload = contentWindow.XMLHttpRequestUpload;\r\n        var WebSocket = contentWindow.WebSocket;\r\n        var baseTag = null;\r\n        // #region Promise monkey patch\r\n        // This patches the Promise so that microtasks are not run after the context is destroyed\r\n        var Promise = contentWindow.Promise;\r\n        var originalThen = Promise.prototype.then;\r\n        var originalCatch = Promise.prototype.catch;\r\n        var originalFinally = Promise.prototype.finally;\r\n        Promise.prototype.then = function promiseThenPatch(onFulfilled, onRejected) {\r\n            return originalThen.call(this, !onFulfilled ? undefined : function onFulfilledPatch() { if (!context.isDestroyed)\r\n                return onFulfilled.apply(this, arguments); }, !onRejected ? undefined : function onRejectedPatch() { if (!context.isDestroyed)\r\n                return onRejected.apply(this, arguments); });\r\n        };\r\n        Promise.prototype.catch = function promiseCatchPatch(onRejected) {\r\n            return originalCatch.call(this, !onRejected ? undefined : function onRejectedPatch() { if (!context.isDestroyed)\r\n                return onRejected.apply(this, arguments); });\r\n        };\r\n        if (originalFinally) {\r\n            Promise.prototype.finally = function promiseFinallyPatch(onFinally) {\r\n                return originalFinally.call(this, !onFinally ? undefined : function onFinallyPatch() { if (!context.isDestroyed)\r\n                    return onFinally.apply(this, arguments); });\r\n            };\r\n        }\r\n        // #endregion\r\n        var extraGlobals = {\r\n            location: undefined,\r\n            document: undefined,\r\n            addEventListener: undefined,\r\n            btoa: (_a = window.btoa) === null || _a === void 0 ? void 0 : _a.bind(window),\r\n            atob: (_b = window.atob) === null || _b === void 0 ? void 0 : _b.bind(window),\r\n            $$webglWindow: window,\r\n            WebSocket: WebSocket,\r\n            fetch: fetch,\r\n            URL: URL,\r\n            XMLHttpRequest: XMLHttpRequest,\r\n            XMLHttpRequestUpload: XMLHttpRequestUpload,\r\n            Promise: Promise,\r\n        };\r\n        var globals = new Proxy(extraGlobals, {\r\n            get: function (target, p, receiver) {\r\n                if (p in target)\r\n                    return target[p];\r\n                var res = window[p];\r\n                return res;\r\n            },\r\n            set: function (target, p, val, receiver) {\r\n                target[p] = val;\r\n                return true;\r\n            },\r\n            has: function (target, key) {\r\n                return (key in window) || (key in target);\r\n            },\r\n        });\r\n        extraGlobals.globalThis =\r\n            extraGlobals.global =\r\n                extraGlobals.window =\r\n                    extraGlobals.parent =\r\n                        extraGlobals.self =\r\n                            extraGlobals.this =\r\n                                globals;\r\n        var evaluate = function (code, filename) {\r\n            var sourceMap = !filename ? '' : '\\n//# sourceURL=unity-jsb:///' + filename;\r\n            return (function (evalCode) {\r\n                //@ts-ignore\r\n                with (globals) {\r\n                    return eval(evalCode);\r\n                }\r\n            }).call(globals, code + sourceMap);\r\n        };\r\n        var context = {\r\n            id: id,\r\n            runtime: runtime,\r\n            runtimeId: rtId,\r\n            window: window,\r\n            globalObject: globals,\r\n            evaluate: evaluate,\r\n            iframe: iframe,\r\n            contentWindow: contentWindow,\r\n            isDestroyed: false,\r\n            free: function () {\r\n                if (iframe.parentNode)\r\n                    iframe.parentNode.removeChild(iframe);\r\n                context.isDestroyed = true;\r\n                delete runtime.contexts[context.id];\r\n                delete unityJsbState.contexts[context.id];\r\n            },\r\n            setBaseUrl: function (url) {\r\n                if (!baseTag) {\r\n                    baseTag = document.createElement('base');\r\n                }\r\n                baseTag.setAttribute('href', url);\r\n                if (baseTag.parentNode && !url) {\r\n                    baseTag.parentNode.removeChild(baseTag);\r\n                }\r\n                else if (!baseTag.parentNode && url) {\r\n                    iframe.contentWindow.document.head.appendChild(baseTag);\r\n                }\r\n            },\r\n        };\r\n        runtime.contexts[id] = context;\r\n        unityJsbState.contexts[id] = context;\r\n        return id;\r\n    },\r\n    JS_FreeContext: function (ctxId) {\r\n        var context = unityJsbState.getContext(ctxId);\r\n        context.free();\r\n    },\r\n    JS_SetBaseUrl: function (ctxId, url) {\r\n        var context = unityJsbState.getContext(ctxId);\r\n        var urlStr = unityJsbState.stringify(url);\r\n        context.setBaseUrl(urlStr);\r\n    },\r\n    JS_GetGlobalObject: function (returnValue, ctxId) {\r\n        var context = unityJsbState.getContext(ctxId);\r\n        if (!context.globalObjectId) {\r\n            context.runtime.refs.push(context.globalObject, returnValue);\r\n        }\r\n        else {\r\n            context.runtime.refs.duplicateId(context.globalObjectId, returnValue);\r\n        }\r\n    },\r\n    JS_Eval: function (ptr, ctx, input, input_len, filename, eval_flags) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        try {\r\n            var code = unityJsbState.stringify(input, input_len);\r\n            var filenameStr = unityJsbState.stringify(filename);\r\n            var res = context.evaluate(code, filenameStr);\r\n            context.runtime.refs.push(res, ptr);\r\n        }\r\n        catch (err) {\r\n            context.lastException = err;\r\n            context.runtime.refs.push(err, ptr);\r\n            console.error(err);\r\n        }\r\n    },\r\n    JS_IsInstanceOf: function (ctxId, val, obj) {\r\n        var context = unityJsbState.getContext(ctxId);\r\n        var valVal = context.runtime.refs.get(val);\r\n        var ctorVal = context.runtime.refs.get(obj);\r\n        return !!(valVal instanceof ctorVal);\r\n    },\r\n    JS_GetException: function (ptr, ctx) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        context.runtime.refs.push(context.lastException, ptr);\r\n    },\r\n    JSB_FreeValue: function (ctx, v) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        context.runtime.refs.pop(v);\r\n    },\r\n    JSB_FreeValueRT: function (rt, v) {\r\n        var runtime = unityJsbState.getRuntime(rt);\r\n        runtime.refs.pop(v);\r\n    },\r\n    JSB_FreePayload: function (ret, ctx, val) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var payload = context.runtime.refs.getPayload(obj);\r\n        HEAP32[ret >> 2] = payload.type;\r\n        HEAP32[(ret >> 2) + 1] = payload.payload;\r\n        context.runtime.refs.clearPayload(obj);\r\n    },\r\n    JSB_DupValue: function (ptr, ctx, v) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        context.runtime.refs.duplicate(v, ptr);\r\n    },\r\n    JS_RunGC: function (rt) {\r\n        var runtime = unityJsbState.getRuntime(rt);\r\n        runtime.garbageCollect();\r\n    },\r\n    JS_ComputeMemoryUsage: function (rt, s) {\r\n        // TODO: https://blog.unity.com/technology/unity-webgl-memory-the-unity-heap\r\n    },\r\n    JS_GetPropertyUint32: function (ptr, ctxId, val, index) {\r\n        var context = unityJsbState.getContext(ctxId);\r\n        var obj = context.runtime.refs.get(val);\r\n        var res = obj[index];\r\n        context.runtime.refs.push(res, ptr);\r\n    },\r\n    JS_GetPropertyInternal: function (ptr, ctxId, val, prop, receiver, throwRefError) {\r\n        var context = unityJsbState.getContext(ctxId);\r\n        var valObj = context.runtime.refs.get(val);\r\n        var propStr = unityJsbState.atoms.get(prop);\r\n        var res = valObj[propStr];\r\n        context.runtime.refs.push(res, ptr);\r\n    },\r\n    JS_GetPropertyStr: function (ptr, ctxId, val, prop) {\r\n        var context = unityJsbState.getContext(ctxId);\r\n        var valObj = context.runtime.refs.get(val);\r\n        var propStr = unityJsbState.stringify(prop);\r\n        var res = valObj[propStr];\r\n        context.runtime.refs.push(res, ptr);\r\n    },\r\n    JS_Invoke: function (ptr, ctx, this_obj, prop, argc, argv) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var propVal = unityJsbState.atoms.get(prop);\r\n        var thisVal = context.runtime.refs.get(this_obj);\r\n        var func = thisVal[propVal];\r\n        var args = context.runtime.refs.batchGet(argv, argc);\r\n        var res;\r\n        try {\r\n            res = func.apply(thisVal, args);\r\n        }\r\n        catch (err) {\r\n            context.lastException = err;\r\n            res = err;\r\n        }\r\n        context.runtime.refs.push(res, ptr);\r\n    },\r\n    JS_Call: function (ptr, ctx, func_obj, this_obj, argc, argv) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var func = context.runtime.refs.get(func_obj);\r\n        var thisVal = context.runtime.refs.get(this_obj);\r\n        var args = context.runtime.refs.batchGet(argv, argc);\r\n        var res;\r\n        try {\r\n            res = func.apply(thisVal, args);\r\n        }\r\n        catch (err) {\r\n            context.lastException = err;\r\n            res = err;\r\n        }\r\n        context.runtime.refs.push(res, ptr);\r\n    },\r\n    JS_CallConstructor: function (ptr, ctx, func_obj, argc, argv) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var func = context.runtime.refs.get(func_obj);\r\n        var args = context.runtime.refs.batchGet(argv, argc);\r\n        var res;\r\n        try {\r\n            res = Reflect.construct(func, args);\r\n        }\r\n        catch (err) {\r\n            context.lastException = err;\r\n            res = err;\r\n        }\r\n        context.runtime.refs.push(res, ptr);\r\n    },\r\n    JS_SetConstructor: function (ctx, ctor, proto) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var ctorVal = context.runtime.refs.get(ctor);\r\n        var protoVal = context.runtime.refs.get(proto);\r\n        ctorVal.prototype = protoVal;\r\n        protoVal.constructor = ctorVal;\r\n        var ctorPayload = context.runtime.refs.getPayload(ctorVal);\r\n        if (ctorPayload.type === 1 /* BridgeObjectType.TypeRef */) {\r\n            context.runtime.refs.setPayload(protoVal, ctorPayload.type, ctorPayload.payload);\r\n        }\r\n    },\r\n    JS_SetPrototype: function (ctx, obj, proto) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var objVal = context.runtime.refs.get(obj);\r\n        var protoVal = context.runtime.refs.get(proto);\r\n        Reflect.setPrototypeOf(objVal, protoVal);\r\n        return true;\r\n    },\r\n    JS_DefineProperty: function (ctx, this_obj, prop, val, getter, setter, flags) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var thisVal = context.runtime.refs.get(this_obj);\r\n        var getterVal = context.runtime.refs.get(getter);\r\n        var setterVal = context.runtime.refs.get(setter);\r\n        var valVal = context.runtime.refs.get(val);\r\n        var propVal = unityJsbState.atoms.get(prop);\r\n        var configurable = !!(flags & 1 /* JSPropFlags.JS_PROP_CONFIGURABLE */);\r\n        var hasConfigurable = configurable || !!(flags & 256 /* JSPropFlags.JS_PROP_HAS_CONFIGURABLE */);\r\n        var enumerable = !!(flags & 4 /* JSPropFlags.JS_PROP_ENUMERABLE */);\r\n        var hasEnumerable = enumerable || !!(flags & 1024 /* JSPropFlags.JS_PROP_HAS_ENUMERABLE */);\r\n        var writable = !!(flags & 2 /* JSPropFlags.JS_PROP_WRITABLE */);\r\n        var hasWritable = writable || !!(flags & 512 /* JSPropFlags.JS_PROP_HAS_WRITABLE */);\r\n        var shouldThrow = !!(flags & 16384 /* JSPropFlags.JS_PROP_THROW */) || !!(flags & 32768 /* JSPropFlags.JS_PROP_THROW_STRICT */);\r\n        try {\r\n            var opts = {\r\n                get: getterVal,\r\n                set: setterVal,\r\n            };\r\n            if (!getter && !setter) {\r\n                opts.value = valVal;\r\n            }\r\n            if (hasConfigurable)\r\n                opts.configurable = configurable;\r\n            if (hasEnumerable)\r\n                opts.enumerable = enumerable;\r\n            if (!getter && !setter && hasWritable)\r\n                opts.writable = writable;\r\n            Object.defineProperty(thisVal, propVal, opts);\r\n            return true;\r\n        }\r\n        catch (err) {\r\n            context.lastException = err;\r\n            if (shouldThrow) {\r\n                console.error(err);\r\n                return -1;\r\n            }\r\n        }\r\n        return false;\r\n    },\r\n    JS_DefinePropertyValue: function (ctx, this_obj, prop, val, flags) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var runtime = context.runtime;\r\n        var thisVal = runtime.refs.get(this_obj);\r\n        var valVal = runtime.refs.get(val);\r\n        var propVal = unityJsbState.atoms.get(prop);\r\n        var configurable = !!(flags & 1 /* JSPropFlags.JS_PROP_CONFIGURABLE */);\r\n        var hasConfigurable = configurable || !!(flags & 256 /* JSPropFlags.JS_PROP_HAS_CONFIGURABLE */);\r\n        var enumerable = !!(flags & 4 /* JSPropFlags.JS_PROP_ENUMERABLE */);\r\n        var hasEnumerable = enumerable || !!(flags & 1024 /* JSPropFlags.JS_PROP_HAS_ENUMERABLE */);\r\n        var writable = !!(flags & 2 /* JSPropFlags.JS_PROP_WRITABLE */);\r\n        var hasWritable = writable || !!(flags & 512 /* JSPropFlags.JS_PROP_HAS_WRITABLE */);\r\n        var shouldThrow = !!(flags & 16384 /* JSPropFlags.JS_PROP_THROW */) || !!(flags & 32768 /* JSPropFlags.JS_PROP_THROW_STRICT */);\r\n        // SetProperty frees the value automatically\r\n        runtime.refs.pop(val);\r\n        try {\r\n            var opts = {\r\n                value: valVal,\r\n            };\r\n            if (hasConfigurable)\r\n                opts.configurable = configurable;\r\n            if (hasEnumerable)\r\n                opts.enumerable = enumerable;\r\n            if (hasWritable)\r\n                opts.writable = writable;\r\n            Object.defineProperty(thisVal, propVal, opts);\r\n            return true;\r\n        }\r\n        catch (err) {\r\n            context.lastException = err;\r\n            if (shouldThrow) {\r\n                console.error(err);\r\n                return -1;\r\n            }\r\n        }\r\n        return false;\r\n    },\r\n    JS_HasProperty: function (ctx, this_obj, prop) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var thisVal = context.runtime.refs.get(this_obj);\r\n        var propVal = unityJsbState.atoms.get(prop);\r\n        var res = Reflect.has(thisVal, propVal);\r\n        return !!res;\r\n    },\r\n    JS_SetPropertyInternal: function (ctx, this_obj, prop, val, flags) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var runtime = context.runtime;\r\n        var thisVal = runtime.refs.get(this_obj);\r\n        var valVal = runtime.refs.get(val);\r\n        var propVal = unityJsbState.atoms.get(prop);\r\n        // SetProperty frees the value automatically\r\n        runtime.refs.pop(val);\r\n        var shouldThrow = !!(flags & 16384 /* JSPropFlags.JS_PROP_THROW */) || !!(flags & 32768 /* JSPropFlags.JS_PROP_THROW_STRICT */);\r\n        try {\r\n            thisVal[propVal] = valVal;\r\n            return true;\r\n        }\r\n        catch (err) {\r\n            context.lastException = err;\r\n            if (shouldThrow) {\r\n                console.error(err);\r\n                return -1;\r\n            }\r\n        }\r\n        return false;\r\n    },\r\n    JS_SetPropertyUint32: function (ctx, this_obj, idx, val) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var runtime = context.runtime;\r\n        var thisVal = context.runtime.refs.get(this_obj);\r\n        var valVal = context.runtime.refs.get(val);\r\n        var propVal = idx;\r\n        // SetProperty frees the value automatically\r\n        runtime.refs.pop(val);\r\n        try {\r\n            thisVal[propVal] = valVal;\r\n            return true;\r\n        }\r\n        catch (err) {\r\n            context.lastException = err;\r\n        }\r\n        return false;\r\n    },\r\n    jsb_get_payload_header: function (ret, ctx, val) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var rec = context.runtime.refs.getPayload(obj);\r\n        HEAP32[ret >> 2] = rec.type;\r\n        HEAP32[(ret >> 2) + 1] = rec.payload;\r\n    },\r\n    JS_ToCStringLen2: function (ctx, len, val, cesu8) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var str = context.runtime.refs.get(val);\r\n        if (typeof str === 'undefined') {\r\n            HEAP32[(len >> 2)] = 0;\r\n            return 0;\r\n        }\r\n        var _a = unityJsbState.bufferify(str), buffer = _a[0], length = _a[1];\r\n        HEAP32[(len >> 2)] = length - 1;\r\n        return buffer;\r\n    },\r\n    JS_FreeCString: function (ctx, ptr) {\r\n        _free(ptr);\r\n    },\r\n    JS_GetArrayBuffer: function (ctx, psize, obj) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var value = context.runtime.refs.get(obj);\r\n        if (value instanceof ArrayBuffer) {\r\n            HEAP32[psize >> 2] = value.byteLength;\r\n            return value;\r\n        }\r\n        return 0;\r\n    },\r\n    // #region Atoms\r\n    JS_NewAtomLen: function (ctx, str, len) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var val = unityJsbState.stringify(str, len);\r\n        return unityJsbState.atoms.push(val);\r\n    },\r\n    JS_AtomToString: function (ptr, ctx, atom) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var str = unityJsbState.atoms.get(atom);\r\n        context.runtime.refs.push(str, ptr);\r\n    },\r\n    JS_FreeAtom: function (ctx, v) {\r\n        unityJsbState.atoms.pop(v);\r\n    },\r\n    JS_DupAtom: function (ctx, v) {\r\n        return unityJsbState.atoms.pushId(v);\r\n    },\r\n    JSB_ATOM_constructor: function () {\r\n        return unityJsbState.atoms.push('constructor');\r\n    },\r\n    JSB_ATOM_Error: function () {\r\n        return unityJsbState.atoms.push('Error');\r\n    },\r\n    JSB_ATOM_fileName: function () {\r\n        return unityJsbState.atoms.push('fileName');\r\n    },\r\n    JSB_ATOM_Function: function () {\r\n        return unityJsbState.atoms.push('Function');\r\n    },\r\n    JSB_ATOM_length: function () {\r\n        return unityJsbState.atoms.push('length');\r\n    },\r\n    JSB_ATOM_lineNumber: function () {\r\n        return unityJsbState.atoms.push('lineNumber');\r\n    },\r\n    JSB_ATOM_message: function () {\r\n        return unityJsbState.atoms.push('message');\r\n    },\r\n    JSB_ATOM_name: function () {\r\n        return unityJsbState.atoms.push('name');\r\n    },\r\n    JSB_ATOM_Number: function () {\r\n        return unityJsbState.atoms.push('Number');\r\n    },\r\n    JSB_ATOM_prototype: function () {\r\n        return unityJsbState.atoms.push('prototype');\r\n    },\r\n    JSB_ATOM_Proxy: function () {\r\n        return unityJsbState.atoms.push('Proxy');\r\n    },\r\n    JSB_ATOM_stack: function () {\r\n        return unityJsbState.atoms.push('stack');\r\n    },\r\n    JSB_ATOM_String: function () {\r\n        return unityJsbState.atoms.push('String');\r\n    },\r\n    JSB_ATOM_Object: function () {\r\n        return unityJsbState.atoms.push('Object');\r\n    },\r\n    JSB_ATOM_Operators: function () {\r\n        return unityJsbState.atoms.push('Operators');\r\n    },\r\n    JSB_ATOM_Symbol_operatorSet: function () {\r\n        return unityJsbState.atoms.push('operatorSet');\r\n    },\r\n    // #endregion\r\n    // #region Is\r\n    JS_IsArray: function (ctx, val) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var valVal = context.runtime.refs.get(val);\r\n        var res = Array.isArray(valVal);\r\n        return !!res;\r\n    },\r\n    JS_IsConstructor: function (ctx, val) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var res = !!obj.prototype && !!obj.prototype.constructor.name;\r\n        return !!res;\r\n    },\r\n    JS_IsError: function (ctx, val) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var valVal = context.runtime.refs.get(val);\r\n        var res = valVal instanceof Error;\r\n        return !!res;\r\n    },\r\n    JS_IsFunction: function (ctx, val) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var valVal = context.runtime.refs.get(val);\r\n        var res = typeof valVal === 'function';\r\n        return !!res;\r\n    },\r\n    // #endregion\r\n    JS_ParseJSON: function (ptr, ctx, buf, buf_len, filename) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var str = unityJsbState.stringify(buf, buf_len);\r\n        var res = JSON.parse(str);\r\n        context.runtime.refs.push(res, ptr);\r\n    },\r\n    JS_JSONStringify: function (ptr, ctx, obj, replacer, space) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var objVal = context.runtime.refs.get(obj);\r\n        var rpVal = context.runtime.refs.get(replacer);\r\n        var spVal = context.runtime.refs.get(space);\r\n        var res = JSON.stringify(objVal, rpVal, spVal);\r\n        context.runtime.refs.push(res, ptr);\r\n    },\r\n    // #region New\r\n    JS_NewArray: function (ptr, ctx) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var res = [];\r\n        context.runtime.refs.push(res, ptr);\r\n    },\r\n    JS_NewArrayBufferCopy: function (ptr, ctx, buf, len) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var nptr = _malloc(len);\r\n        var res = new Uint8Array(HEAPU8.buffer, nptr, len);\r\n        var existing = new Uint8Array(HEAPU8.buffer, buf, len);\r\n        res.set(existing);\r\n        context.runtime.refs.push(res, ptr);\r\n    },\r\n    JSB_NewFloat64: function (ptr, ctx, d) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        context.runtime.refs.push(d, ptr);\r\n    },\r\n    JSB_NewInt64: function (ptr, ctx, d) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        context.runtime.refs.push(d, ptr);\r\n    },\r\n    JS_NewObject: function (ptr, ctx) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var res = {};\r\n        context.runtime.refs.push(res, ptr);\r\n    },\r\n    JS_NewString: function (ptr, ctx, str) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var res = unityJsbState.stringify(str);\r\n        context.runtime.refs.push(res, ptr);\r\n    },\r\n    JS_NewStringLen: function (ptr, ctx, str, len) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var val = unityJsbState.stringify(str, len);\r\n        context.runtime.refs.push(val, ptr);\r\n    },\r\n    JSB_NewEmptyString: function (ptr, ctx) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var res = \"\";\r\n        context.runtime.refs.push(res, ptr);\r\n    },\r\n    // #endregion\r\n    // #region Bridge\r\n    JSB_NewCFunction: function (ret, ctx, func, atom, length, cproto, magic) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var refs = context.runtime.refs;\r\n        var name = unityJsbState.atoms.get(atom) || 'jscFunction';\r\n        function jscFunction() {\r\n            var args = arguments;\r\n            var thisObj = this === window ? context.globalObject : this;\r\n            var _a = refs.allocate(thisObj), thisPtr = _a[0], thisId = _a[1];\r\n            var ret = _malloc(16 /* Sizes.JSValue */);\r\n            if (cproto === 0 /* JSCFunctionEnum.JS_CFUNC_generic */) {\r\n                var argc = args.length;\r\n                var _b = refs.batchAllocate(Array.from(args)), argv = _b[0], argIds = _b[1];\r\n                unityJsbState.dynCall('viiiii', func, [ret, ctx, thisPtr, argc, argv]);\r\n                argIds.forEach(refs.popId);\r\n                _free(argv);\r\n            }\r\n            else if (cproto === 9 /* JSCFunctionEnum.JS_CFUNC_setter */) {\r\n                var _c = refs.allocate(args[0]), val = _c[0], valId = _c[1];\r\n                unityJsbState.dynCall('viiii', func, [ret, ctx, thisPtr, val]);\r\n                refs.popId(valId);\r\n                _free(val);\r\n            }\r\n            else if (cproto === 8 /* JSCFunctionEnum.JS_CFUNC_getter */) {\r\n                unityJsbState.dynCall('viii', func, [ret, ctx, thisPtr]);\r\n            }\r\n            else {\r\n                throw new Error(\"Unknown type of function specified: name=\".concat(name, \" type=\").concat(cproto));\r\n            }\r\n            refs.popId(thisId);\r\n            _free(thisPtr);\r\n            var returnValue = refs.get(ret);\r\n            refs.pop(ret);\r\n            _free(ret);\r\n            return returnValue;\r\n        }\r\n        jscFunction['$$csharpFunctionName'] = name;\r\n        refs.push(jscFunction, ret);\r\n    },\r\n    JSB_NewCFunctionMagic: function (ret, ctx, func, atom, length, cproto, magic) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var refs = context.runtime.refs;\r\n        var name = unityJsbState.atoms.get(atom) || 'jscFunctionMagic';\r\n        function jscFunctionMagic() {\r\n            var args = arguments;\r\n            var thisObj = this === window ? context.globalObject : this;\r\n            var _a = refs.allocate(thisObj), thisPtr = _a[0], thisId = _a[1];\r\n            var ret = _malloc(16 /* Sizes.JSValue */);\r\n            if (cproto === 1 /* JSCFunctionEnum.JS_CFUNC_generic_magic */) {\r\n                var argc = args.length;\r\n                var _b = refs.batchAllocate(Array.from(args)), argv = _b[0], argIds = _b[1];\r\n                unityJsbState.dynCall('viiiiii', func, [ret, ctx, thisPtr, argc, argv, magic]);\r\n                argIds.forEach(refs.popId);\r\n                _free(argv);\r\n            }\r\n            else if (cproto === 3 /* JSCFunctionEnum.JS_CFUNC_constructor_magic */) {\r\n                var argc = args.length;\r\n                var _c = refs.batchAllocate(Array.from(args)), argv = _c[0], argIds = _c[1];\r\n                unityJsbState.dynCall('viiiiii', func, [ret, ctx, thisPtr, argc, argv, magic]);\r\n                argIds.forEach(refs.popId);\r\n                _free(argv);\r\n            }\r\n            else if (cproto === 11 /* JSCFunctionEnum.JS_CFUNC_setter_magic */) {\r\n                var _d = refs.allocate(args[0]), val = _d[0], valId = _d[1];\r\n                unityJsbState.dynCall('viiiii', func, [ret, ctx, thisPtr, val, magic]);\r\n                refs.popId(valId);\r\n                _free(val);\r\n            }\r\n            else if (cproto === 10 /* JSCFunctionEnum.JS_CFUNC_getter_magic */) {\r\n                unityJsbState.dynCall('viiii', func, [ret, ctx, thisPtr, magic]);\r\n            }\r\n            else {\r\n                throw new Error(\"Unknown type of function specified: name=\".concat(name, \" type=\").concat(cproto));\r\n            }\r\n            refs.popId(thisId);\r\n            _free(thisPtr);\r\n            var returnValue = refs.get(ret);\r\n            refs.pop(ret);\r\n            _free(ret);\r\n            return returnValue;\r\n        }\r\n        ;\r\n        jscFunctionMagic['$$csharpFunctionName'] = name;\r\n        refs.push(jscFunctionMagic, ret);\r\n        if (cproto === 3 /* JSCFunctionEnum.JS_CFUNC_constructor_magic */) {\r\n            refs.setPayload(jscFunctionMagic, 1 /* BridgeObjectType.TypeRef */, magic);\r\n        }\r\n    },\r\n    jsb_new_bridge_object: function (ret, ctx, proto, object_id) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var protoVal = context.runtime.refs.get(proto);\r\n        var res = Object.create(protoVal);\r\n        context.runtime.refs.push(res, ret);\r\n        context.runtime.refs.setPayload(res, 2 /* BridgeObjectType.ObjectRef */, object_id);\r\n    },\r\n    jsb_new_bridge_value: function (ret, ctx, proto, size) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var protoVal = context.runtime.refs.get(proto);\r\n        var res = Object.create(protoVal);\r\n        res.$$values = new Array(size).fill(0);\r\n        context.runtime.refs.push(res, ret);\r\n    },\r\n    JSB_NewBridgeClassObject: function (ret, ctx, new_target, object_id) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var res = context.runtime.refs.get(new_target);\r\n        context.runtime.refs.push(res, ret);\r\n        context.runtime.refs.setPayload(res, 2 /* BridgeObjectType.ObjectRef */, object_id);\r\n    },\r\n    JSB_NewBridgeClassValue: function (ret, ctx, new_target, size) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var res = context.runtime.refs.get(new_target);\r\n        res.$$values = new Array(size).fill(0);\r\n        context.runtime.refs.push(res, ret);\r\n    },\r\n    JSB_GetBridgeClassID: function () {\r\n        // TODO: I have no idea\r\n        return 0;\r\n    },\r\n    jsb_construct_bridge_object: function (ret, ctx, ctor, object_id) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var ctorVal = context.runtime.refs.get(ctor);\r\n        var res = Reflect.construct(ctorVal, []);\r\n        context.runtime.refs.push(res, ret);\r\n        context.runtime.refs.setPayload(res, 2 /* BridgeObjectType.ObjectRef */, object_id);\r\n    },\r\n    jsb_crossbind_constructor: function (ret, ctx, new_target) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var target = context.runtime.refs.get(new_target);\r\n        // TODO: I have no idea\r\n        var res = function () {\r\n            return new target();\r\n        };\r\n        context.runtime.refs.push(res, ret);\r\n    },\r\n    // #endregion\r\n    // #region Errors\r\n    JSB_ThrowError: function (ret, ctx, buf, buf_len) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var str = unityJsbState.stringify(buf, buf_len);\r\n        var err = new Error(str);\r\n        console.error(err);\r\n        context.runtime.refs.push(err, ret);\r\n        // TODO: throw?\r\n    },\r\n    JSB_ThrowTypeError: function (ret, ctx, msg) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var str = 'Type Error';\r\n        var err = new Error(str);\r\n        console.error(err);\r\n        context.runtime.refs.push(err, ret);\r\n        // TODO: throw?\r\n    },\r\n    JSB_ThrowRangeError: function (ret, ctx, msg) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var str = 'Range Error';\r\n        var err = new Error(str);\r\n        console.error(err);\r\n        context.runtime.refs.push(err, ret);\r\n        // TODO: throw?\r\n    },\r\n    JSB_ThrowInternalError: function (ret, ctx, msg) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var str = 'Internal Error';\r\n        var err = new Error(str);\r\n        console.error(err);\r\n        context.runtime.refs.push(err, ret);\r\n        // TODO: throw?\r\n    },\r\n    JSB_ThrowReferenceError: function (ret, ctx, msg) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var str = 'Reference Error';\r\n        var err = new Error(str);\r\n        console.error(err);\r\n        context.runtime.refs.push(err, ret);\r\n        // TODO: throw?\r\n    },\r\n    // #endregion\r\n    // #region Low level Set\r\n    js_strndup: function (ctx, s, n) {\r\n        var buffer = _malloc(n + 1);\r\n        _memcpy(buffer, s, n);\r\n        HEAPU8[buffer + n] = 0;\r\n        return buffer;\r\n    },\r\n    jsb_set_floats: function (ctx, val, n, v0) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = n / 4 /* Sizes.Single */;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        for (var index = 0; index < count; index++) {\r\n            var val_1 = HEAPF32[(v0 >> 2) + index];\r\n            obj.$$values[index] = val_1;\r\n        }\r\n        return true;\r\n    },\r\n    jsb_set_bytes: function (ctx, val, n, v0) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = n / 4 /* Sizes.Single */;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        for (var index = 0; index < count; index++) {\r\n            var val_2 = HEAP32[(v0 >> 2) + index];\r\n            obj.$$values[index] = val_2;\r\n        }\r\n        return true;\r\n    },\r\n    jsb_set_byte_4: function (ctx, val, v0, v1, v2, v3) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = 4;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        obj.$$values[0] = HEAP32[(v0 >> 2)];\r\n        obj.$$values[1] = HEAP32[(v1 >> 2)];\r\n        obj.$$values[2] = HEAP32[(v2 >> 2)];\r\n        obj.$$values[3] = HEAP32[(v3 >> 2)];\r\n        return true;\r\n    },\r\n    jsb_set_float_2: function (ctx, val, v0, v1) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = 2;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        obj.$$values[0] = HEAPF32[(v0 >> 2)];\r\n        obj.$$values[1] = HEAPF32[(v1 >> 2)];\r\n        return true;\r\n    },\r\n    jsb_set_float_3: function (ctx, val, v0, v1, v2) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = 3;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        obj.$$values[0] = HEAPF32[(v0 >> 2)];\r\n        obj.$$values[1] = HEAPF32[(v1 >> 2)];\r\n        obj.$$values[2] = HEAPF32[(v2 >> 2)];\r\n        return true;\r\n    },\r\n    jsb_set_float_4: function (ctx, val, v0, v1, v2, v3) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = 4;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        obj.$$values[0] = HEAPF32[(v0 >> 2)];\r\n        obj.$$values[1] = HEAPF32[(v1 >> 2)];\r\n        obj.$$values[2] = HEAPF32[(v2 >> 2)];\r\n        obj.$$values[3] = HEAPF32[(v3 >> 2)];\r\n        return true;\r\n    },\r\n    jsb_set_int_1: function (ctx, val, v0) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = 1;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        obj.$$values[0] = HEAP32[(v0 >> 2)];\r\n        return true;\r\n    },\r\n    jsb_set_int_2: function (ctx, val, v0, v1) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = 2;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        obj.$$values[0] = HEAP32[(v0 >> 2)];\r\n        obj.$$values[1] = HEAP32[(v1 >> 2)];\r\n        return true;\r\n    },\r\n    jsb_set_int_3: function (ctx, val, v0, v1, v2) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = 3;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        obj.$$values[0] = HEAP32[(v0 >> 2)];\r\n        obj.$$values[1] = HEAP32[(v1 >> 2)];\r\n        obj.$$values[2] = HEAP32[(v2 >> 2)];\r\n        return true;\r\n    },\r\n    jsb_set_int_4: function (ctx, val, v0, v1, v2, v3) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = 4;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        obj.$$values[0] = HEAP32[(v0 >> 2)];\r\n        obj.$$values[1] = HEAP32[(v1 >> 2)];\r\n        obj.$$values[2] = HEAP32[(v2 >> 2)];\r\n        obj.$$values[3] = HEAP32[(v3 >> 2)];\r\n        return true;\r\n    },\r\n    // #endregion\r\n    // #region Low Level Get\r\n    jsb_get_bytes: function (ctx, val, n, v0) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = n / 4 /* Sizes.Single */;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        for (var index = 0; index < count; index++) {\r\n            var val_3 = obj.$$values[index];\r\n            HEAP32[(v0 >> 2) + index] = val_3;\r\n        }\r\n        return true;\r\n    },\r\n    jsb_get_floats: function (ctx, val, n, v0) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = n / 4 /* Sizes.Single */;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        for (var index = 0; index < count; index++) {\r\n            var val_4 = obj.$$values[index];\r\n            HEAPF32[(v0 >> 2) + index] = val_4;\r\n        }\r\n        return true;\r\n    },\r\n    jsb_get_byte_4: function (ctx, val, v0, v1, v2, v3) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = 4;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        HEAP32[(v0 >> 2)] = obj.$$values[0];\r\n        HEAP32[(v1 >> 2)] = obj.$$values[1];\r\n        HEAP32[(v2 >> 2)] = obj.$$values[2];\r\n        HEAP32[(v3 >> 2)] = obj.$$values[3];\r\n        return true;\r\n    },\r\n    jsb_get_float_2: function (ctx, val, v0, v1) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = 2;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        HEAPF32[(v0 >> 2)] = obj.$$values[0];\r\n        HEAPF32[(v1 >> 2)] = obj.$$values[1];\r\n        return true;\r\n    },\r\n    jsb_get_float_3: function (ctx, val, v0, v1, v2) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = 3;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        HEAPF32[(v0 >> 2)] = obj.$$values[0];\r\n        HEAPF32[(v1 >> 2)] = obj.$$values[1];\r\n        HEAPF32[(v2 >> 2)] = obj.$$values[2];\r\n        return true;\r\n    },\r\n    jsb_get_float_4: function (ctx, val, v0, v1, v2, v3) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = 4;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        HEAPF32[(v0 >> 2)] = obj.$$values[0];\r\n        HEAPF32[(v1 >> 2)] = obj.$$values[1];\r\n        HEAPF32[(v2 >> 2)] = obj.$$values[2];\r\n        HEAPF32[(v3 >> 2)] = obj.$$values[3];\r\n        return true;\r\n    },\r\n    jsb_get_int_1: function (ctx, val, v0) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = 1;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        HEAP32[(v0 >> 2)] = obj.$$values[0];\r\n        return true;\r\n    },\r\n    jsb_get_int_2: function (ctx, val, v0, v1) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = 2;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        HEAP32[(v0 >> 2)] = obj.$$values[0];\r\n        HEAP32[(v1 >> 2)] = obj.$$values[1];\r\n        return true;\r\n    },\r\n    jsb_get_int_3: function (ctx, val, v0, v1, v2) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = 3;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        HEAP32[(v0 >> 2)] = obj.$$values[0];\r\n        HEAP32[(v1 >> 2)] = obj.$$values[1];\r\n        HEAP32[(v2 >> 2)] = obj.$$values[2];\r\n        return true;\r\n    },\r\n    jsb_get_int_4: function (ctx, val, v0, v1, v2, v3) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var obj = context.runtime.refs.get(val);\r\n        var count = 4;\r\n        if (!Array.isArray(obj.$$values) || count >= obj.$$values.length)\r\n            return false;\r\n        HEAP32[(v0 >> 2)] = obj.$$values[0];\r\n        HEAP32[(v1 >> 2)] = obj.$$values[1];\r\n        HEAP32[(v2 >> 2)] = obj.$$values[2];\r\n        HEAP32[(v3 >> 2)] = obj.$$values[3];\r\n        return true;\r\n    },\r\n    // #endregion\r\n    // #region To\r\n    JS_ToFloat64: function (ctx, pres, val) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var value = context.runtime.refs.get(val);\r\n        if (typeof value === 'number' || typeof value === 'bigint') {\r\n            HEAPF64[pres >> 3] = Number(value);\r\n            return false;\r\n        }\r\n        return -1;\r\n    },\r\n    JS_ToInt32: function (ctx, pres, val) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var value = context.runtime.refs.get(val);\r\n        if (typeof value === 'number' || typeof value === 'bigint') {\r\n            HEAP32[pres >> 2] = Number(value);\r\n            return false;\r\n        }\r\n        return -1;\r\n    },\r\n    JS_ToInt64: function (ctx, pres, val) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var value = context.runtime.refs.get(val);\r\n        if (typeof value === 'number' || typeof value === 'bigint') {\r\n            unityJsbState.HEAP64()[pres >> 3] = BigInt(value);\r\n            return false;\r\n        }\r\n        return -1;\r\n    },\r\n    JS_ToBigInt64: function (ctx, pres, val) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var value = context.runtime.refs.get(val);\r\n        if (typeof value === 'number' || typeof value === 'bigint') {\r\n            unityJsbState.HEAP64()[pres >> 3] = BigInt(value);\r\n            return false;\r\n        }\r\n        return -1;\r\n    },\r\n    JS_ToIndex: function (ctx, pres, val) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var value = context.runtime.refs.get(val);\r\n        if (typeof value === 'number' || typeof value === 'bigint') {\r\n            unityJsbState.HEAPU64()[pres >> 3] = BigInt(value);\r\n            return false;\r\n        }\r\n        return -1;\r\n    },\r\n    JSB_ToUint32: function (ctx, pres, val) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var value = context.runtime.refs.get(val);\r\n        if (typeof value === 'number' || typeof value === 'bigint') {\r\n            HEAPU32[pres >> 2] = Number(value);\r\n            return false;\r\n        }\r\n        return -1;\r\n    },\r\n    JS_ToBool: function (ctx, val) {\r\n        var context = unityJsbState.getContext(ctx);\r\n        var objVal = context.runtime.refs.get(val);\r\n        return !!objVal;\r\n    },\r\n    // #endregion\r\n    // #region Bytecode\r\n    JS_ReadObject: function (ptr, ctx, buf, buf_len, flags) {\r\n        console.warn('Bytecode is not supported in WebGL Backend');\r\n    },\r\n    JS_WriteObject: function (ctx, psize, obj, flags) {\r\n        console.warn('Bytecode is not supported in WebGL Backend');\r\n        return 0;\r\n    },\r\n    JS_EvalFunction: function (ptr, ctx, fun_obj) {\r\n        console.warn('Bytecode is not supported in WebGL Backend');\r\n    },\r\n    js_free: function (ctx, ptr) {\r\n        // TODO: Not sure what this is but seems related to Bytecode\r\n    },\r\n    // #endregion\r\n    // #region Misc features\r\n    JS_NewPromiseCapability: function (ret, ctx, resolving_funcs) {\r\n        // TODO\r\n        return 0;\r\n    },\r\n    JS_SetHostPromiseRejectionTracker: function (rt, cb, opaque) {\r\n        // TODO:\r\n    },\r\n    JS_SetInterruptHandler: function (rt, cb, opaque) {\r\n        // TODO:\r\n    },\r\n    JS_SetModuleLoaderFunc: function (rt, module_normalize, module_loader, opaque) {\r\n        // TODO:\r\n    },\r\n    JS_GetImportMeta: function (ret, ctx, m) {\r\n        // TODO:\r\n        return 0;\r\n    },\r\n    JS_ResolveModule: function (ctx, obj) {\r\n        // TODO:\r\n        return 0;\r\n    },\r\n    JS_AddIntrinsicOperators: function (ctx) {\r\n        console.warn('Operator overloading is not supported in WebGL Backend');\r\n    },\r\n    JS_ExecutePendingJob: function (rt, pctx) {\r\n        // Automatically handled by browsers\r\n        return false;\r\n    },\r\n    JS_IsJobPending: function (rt, pctx) {\r\n        // Automatically handled by browsers\r\n        return false;\r\n    },\r\n    // #endregion\r\n};\r\nautoAddDeps(UnityJSBPlugin, '$unityJsbState');\r\nmergeInto(LibraryManager.library, UnityJSBPlugin);\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WebGL/jsbplugin.jslib.meta",
    "content": "fileFormatVersion: 2\nguid: 02906906a6f163f47adcf793967e7728\nPluginImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  iconMap: {}\n  executionOrder: {}\n  defineConstraints: []\n  isPreloaded: 0\n  isOverridable: 1\n  isExplicitlyReferenced: 0\n  validateReferences: 1\n  platformData:\n  - first:\n      Any: \n    second:\n      enabled: 0\n      settings: {}\n  - first:\n      Editor: Editor\n    second:\n      enabled: 0\n      settings:\n        DefaultValueInitialized: true\n  - first:\n      WebGL: WebGL\n    second:\n      enabled: 1\n      settings: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/WebGL.meta",
    "content": "fileFormatVersion: 2\r\nguid: fed91097b671a28479f32a8dbba88bc3\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/iOS/libquickjs.a.meta",
    "content": "fileFormatVersion: 2\r\nguid: 6323c4b8646655d45bb80886eac8a94f\r\nPluginImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  iconMap: {}\r\n  executionOrder: {}\r\n  defineConstraints: []\r\n  isPreloaded: 0\r\n  isOverridable: 0\r\n  isExplicitlyReferenced: 0\r\n  validateReferences: 1\r\n  platformData:\r\n  - first:\r\n      '': Any\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        Exclude Android: 1\r\n        Exclude Editor: 1\r\n        Exclude Linux: 1\r\n        Exclude Linux64: 1\r\n        Exclude LinuxUniversal: 1\r\n        Exclude OSXUniversal: 1\r\n        Exclude Win: 1\r\n        Exclude Win64: 1\r\n        Exclude iOS: 0\r\n  - first:\r\n      Android: Android\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: ARMv7\r\n  - first:\r\n      Any: \r\n    second:\r\n      enabled: 0\r\n      settings: {}\r\n  - first:\r\n      Editor: Editor\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n        DefaultValueInitialized: true\r\n        OS: AnyOS\r\n  - first:\r\n      Facebook: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Facebook: Win64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Linux\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: x86\r\n  - first:\r\n      Standalone: Linux64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: x86_64\r\n  - first:\r\n      Standalone: LinuxUniversal\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: OSXUniversal\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Win64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      iPhone: iOS\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        AddToEmbeddedBinaries: false\r\n        CompileFlags: \r\n        FrameworkDependencies: \r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/iOS.meta",
    "content": "fileFormatVersion: 2\r\nguid: 6effe97f20f8f0943bdc52afb9e6d13c\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/quickjs.bundle/Contents/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>BuildMachineOSBuild</key>\n\t<string>20G314</string>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>English</string>\n\t<key>CFBundleExecutable</key>\n\t<string>quickjs</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleLongVersionString</key>\n\t<string></string>\n\t<key>CFBundlePackageType</key>\n\t<string>APPL</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleSupportedPlatforms</key>\n\t<array>\n\t\t<string>MacOSX</string>\n\t</array>\n\t<key>CSResourcesFileMapped</key>\n\t<true/>\n\t<key>DTCompiler</key>\n\t<string>com.apple.compilers.llvm.clang.1_0</string>\n\t<key>DTPlatformBuild</key>\n\t<string>13A1030d</string>\n\t<key>DTPlatformName</key>\n\t<string>macosx</string>\n\t<key>DTPlatformVersion</key>\n\t<string>12.0</string>\n\t<key>DTSDKBuild</key>\n\t<string>21A344</string>\n\t<key>DTSDKName</key>\n\t<string>macosx12.0</string>\n\t<key>DTXcode</key>\n\t<string>1310</string>\n\t<key>DTXcodeBuild</key>\n\t<string>13A1030d</string>\n\t<key>LSMinimumSystemVersion</key>\n\t<string>10.13</string>\n\t<key>NSHumanReadableCopyright</key>\n\t<string></string>\n</dict>\n</plist>\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/quickjs.bundle/Contents/Info.plist.meta",
    "content": "fileFormatVersion: 2\nguid: 60759bbfed45e4157b0172fed9657329\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/quickjs.bundle/Contents/MacOS/quickjs.meta",
    "content": "fileFormatVersion: 2\r\nguid: a6d2476cce0a14da9b56985677b3b805\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/quickjs.bundle/Contents/MacOS.meta",
    "content": "fileFormatVersion: 2\r\nguid: 15bda948bdeb74263aaf195506c344d6\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/quickjs.bundle/Contents.meta",
    "content": "fileFormatVersion: 2\r\nguid: 8dbbb3dca1dae47a7a0fa3c984fae70a\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/quickjs.bundle.meta",
    "content": "fileFormatVersion: 2\nguid: 8b67da05d6f104dbfb76bdb250790e8b\nfolderAsset: yes\nPluginImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  iconMap: {}\n  executionOrder: {}\n  defineConstraints: []\n  isPreloaded: 0\n  isOverridable: 0\n  isExplicitlyReferenced: 0\n  validateReferences: 1\n  platformData:\n  - first:\n      : Any\n    second:\n      enabled: 0\n      settings:\n        Exclude Android: 1\n        Exclude Editor: 0\n        Exclude Linux64: 1\n        Exclude OSXUniversal: 0\n        Exclude Win: 1\n        Exclude Win64: 1\n        Exclude iOS: 1\n  - first:\n      Android: Android\n    second:\n      enabled: 0\n      settings:\n        CPU: ARMv7\n  - first:\n      Any: \n    second:\n      enabled: 0\n      settings: {}\n  - first:\n      Editor: Editor\n    second:\n      enabled: 1\n      settings:\n        CPU: AnyCPU\n        DefaultValueInitialized: true\n        OS: AnyOS\n  - first:\n      Standalone: Linux64\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      Standalone: OSXUniversal\n    second:\n      enabled: 1\n      settings:\n        CPU: AnyCPU\n  - first:\n      Standalone: Win\n    second:\n      enabled: 0\n      settings:\n        CPU: x86\n  - first:\n      Standalone: Win64\n    second:\n      enabled: 0\n      settings:\n        CPU: x86_64\n  - first:\n      iPhone: iOS\n    second:\n      enabled: 0\n      settings:\n        AddToEmbeddedBinaries: false\n        CPU: AnyCPU\n        CompileFlags: \n        FrameworkDependencies: \n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/x64/libquickjs.so.meta",
    "content": "fileFormatVersion: 2\nguid: 33906c8e6e8a1bd4d8385dce93455477\nPluginImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  iconMap: {}\n  executionOrder: {}\n  defineConstraints: []\n  isPreloaded: 0\n  isOverridable: 0\n  isExplicitlyReferenced: 0\n  validateReferences: 1\n  platformData:\n  - first:\n      Any: \n    second:\n      enabled: 1\n      settings: {}\n  - first:\n      Editor: Editor\n    second:\n      enabled: 0\n      settings:\n        CPU: x86_64\n        DefaultValueInitialized: true\n  - first:\n      Standalone: Linux64\n    second:\n      enabled: 1\n      settings:\n        CPU: x86_64\n  - first:\n      Standalone: OSXUniversal\n    second:\n      enabled: 0\n      settings:\n        CPU: x86_64\n  - first:\n      Standalone: Win\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      Standalone: Win64\n    second:\n      enabled: 1\n      settings:\n        CPU: AnyCPU\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/x64/quickjs.dll.meta",
    "content": "fileFormatVersion: 2\r\nguid: f0c77bb9ef06d824b9f3f00613903257\r\nPluginImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  iconMap: {}\r\n  executionOrder: {}\r\n  defineConstraints: []\r\n  isPreloaded: 0\r\n  isOverridable: 0\r\n  isExplicitlyReferenced: 0\r\n  validateReferences: 1\r\n  platformData:\r\n  - first:\r\n      '': Any\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        Exclude Android: 1\r\n        Exclude Editor: 0\r\n        Exclude Linux: 0\r\n        Exclude Linux64: 0\r\n        Exclude LinuxUniversal: 0\r\n        Exclude OSXUniversal: 0\r\n        Exclude WebGL: 1\r\n        Exclude Win: 0\r\n        Exclude Win64: 0\r\n        Exclude iOS: 1\r\n  - first:\r\n      Android: Android\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: ARMv7\r\n  - first:\r\n      Any: \r\n    second:\r\n      enabled: 0\r\n      settings: {}\r\n  - first:\r\n      Editor: Editor\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86_64\r\n        DefaultValueInitialized: true\r\n        OS: Windows\r\n  - first:\r\n      Facebook: Win\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Facebook: Win64\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Linux\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: Linux64\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86_64\r\n  - first:\r\n      Standalone: LinuxUniversal\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86_64\r\n  - first:\r\n      Standalone: OSXUniversal\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86_64\r\n  - first:\r\n      Standalone: Win\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: Win64\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      iPhone: iOS\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        AddToEmbeddedBinaries: false\r\n        CompileFlags: \r\n        FrameworkDependencies: \r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/x64/v8-bridge.dll.meta",
    "content": "fileFormatVersion: 2\nguid: 76136c59d66e7e94882f6f68917f0436\nPluginImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  iconMap: {}\n  executionOrder: {}\n  defineConstraints: []\n  isPreloaded: 0\n  isOverridable: 1\n  isExplicitlyReferenced: 0\n  validateReferences: 1\n  platformData:\n  - first:\n      Any: \n    second:\n      enabled: 1\n      settings: {}\n  - first:\n      Editor: Editor\n    second:\n      enabled: 0\n      settings:\n        CPU: x86_64\n        DefaultValueInitialized: true\n  - first:\n      Standalone: Linux64\n    second:\n      enabled: 1\n      settings:\n        CPU: x86_64\n  - first:\n      Standalone: OSXUniversal\n    second:\n      enabled: 0\n      settings:\n        CPU: x86_64\n  - first:\n      Standalone: Win\n    second:\n      enabled: 0\n      settings:\n        CPU: None\n  - first:\n      Standalone: Win64\n    second:\n      enabled: 1\n      settings:\n        CPU: AnyCPU\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/x64.meta",
    "content": "fileFormatVersion: 2\r\nguid: 883cb8e537b9efc44af939b9797f0552\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/x86/quickjs.dll.meta",
    "content": "fileFormatVersion: 2\r\nguid: c322dc8e8419f764fa73aef1753cd629\r\nPluginImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  iconMap: {}\r\n  executionOrder: {}\r\n  defineConstraints: []\r\n  isPreloaded: 0\r\n  isOverridable: 0\r\n  isExplicitlyReferenced: 0\r\n  validateReferences: 1\r\n  platformData:\r\n  - first:\r\n      '': Any\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        Exclude Android: 1\r\n        Exclude Editor: 0\r\n        Exclude Linux: 0\r\n        Exclude Linux64: 0\r\n        Exclude LinuxUniversal: 0\r\n        Exclude OSXUniversal: 0\r\n        Exclude WebGL: 1\r\n        Exclude Win: 0\r\n        Exclude Win64: 0\r\n        Exclude iOS: 1\r\n  - first:\r\n      Android: Android\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: ARMv7\r\n  - first:\r\n      Any: \r\n    second:\r\n      enabled: 0\r\n      settings: {}\r\n  - first:\r\n      Editor: Editor\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86\r\n        DefaultValueInitialized: true\r\n        OS: Windows\r\n  - first:\r\n      Facebook: Win\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Facebook: Win64\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: Linux\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86\r\n  - first:\r\n      Standalone: Linux64\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      Standalone: LinuxUniversal\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86\r\n  - first:\r\n      Standalone: OSXUniversal\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: x86\r\n  - first:\r\n      Standalone: Win\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: AnyCPU\r\n  - first:\r\n      Standalone: Win64\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        CPU: None\r\n  - first:\r\n      iPhone: iOS\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        AddToEmbeddedBinaries: false\r\n        CompileFlags: \r\n        FrameworkDependencies: \r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins/x86.meta",
    "content": "fileFormatVersion: 2\r\nguid: 86a72fb2929d46d42848ab1c2e51fff7\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Plugins.meta",
    "content": "fileFormatVersion: 2\r\nguid: 0fcd72595b06d104d846f77cb5f03853\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Resources/plover.js.txt",
    "content": "var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n};\r\ndefine(\"plover/events/dispatcher\", [\"require\", \"exports\"], function (require, exports) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.EventDispatcher = exports.Dispatcher = exports.Handler = void 0;\r\n    class Handler {\r\n        constructor(caller, fn, once) {\r\n            this.caller = caller;\r\n            this.fn = fn;\r\n            this.once = !!once;\r\n        }\r\n        invoke(arg0, arg1, arg2) {\r\n            if (this.fn) {\r\n                this.fn.call(this.caller, arg0, arg1, arg2);\r\n            }\r\n        }\r\n    }\r\n    exports.Handler = Handler;\r\n    /**\r\n     * 简单的事件分发器实现\r\n     * 此实现功能与 DuktapeJS.Dispatcher 基本一致,\r\n     * 但 DuktapeJS.Dispatcher 不保证事件响应顺序, 但效率更高 (因为复用了中途移除的索引)\r\n     */\r\n    class Dispatcher {\r\n        constructor() {\r\n            this._handlers = [];\r\n        }\r\n        on(caller, fn) {\r\n            let handler = new Handler(caller, fn);\r\n            this._handlers.push(handler);\r\n            return handler;\r\n        }\r\n        once(caller, fn) {\r\n            let handler = new Handler(caller, fn, true);\r\n            this._handlers.push(handler);\r\n            return handler;\r\n        }\r\n        off(caller, fn) {\r\n            let size = this._handlers.length;\r\n            if (typeof fn === \"undefined\") {\r\n                let found = false;\r\n                for (let i = 0; i < size;) {\r\n                    let item = this._handlers[i];\r\n                    if (item.caller == caller) {\r\n                        found = true;\r\n                        item.fn = null;\r\n                        item.caller = null;\r\n                        this._handlers.splice(i, 1);\r\n                        size--;\r\n                    }\r\n                    else {\r\n                        i++;\r\n                    }\r\n                }\r\n                return found;\r\n            }\r\n            for (let i = 0; i < size; i++) {\r\n                let item = this._handlers[i];\r\n                if (item.caller == caller && item.fn == fn) {\r\n                    item.fn = null;\r\n                    item.caller = null;\r\n                    this._handlers.splice(i, 1);\r\n                    return true;\r\n                }\r\n            }\r\n            return false;\r\n        }\r\n        /**\r\n         * 移除所有处理器\r\n         */\r\n        clear() {\r\n            this._handlers.splice(0);\r\n        }\r\n        dispatch(arg0, arg1, arg2) {\r\n            let size = this._handlers.length;\r\n            if (size == 0) {\r\n                return;\r\n            }\r\n            if (size == 1) {\r\n                let item = this._handlers[0];\r\n                if (item.once) {\r\n                    this._handlers.splice(0, 1);\r\n                }\r\n                item.invoke(arg0, arg1, arg2);\r\n                return;\r\n            }\r\n            if (size == 2) {\r\n                let item0 = this._handlers[0];\r\n                let item1 = this._handlers[1];\r\n                if (item0.once) {\r\n                    if (item1.once) {\r\n                        this._handlers.splice(0, 2);\r\n                    }\r\n                    else {\r\n                        this._handlers.splice(0, 1);\r\n                    }\r\n                }\r\n                else {\r\n                    if (item1.once) {\r\n                        this._handlers.splice(1, 1);\r\n                    }\r\n                }\r\n                item0.invoke(arg0, arg1, arg2);\r\n                item1.invoke(arg0, arg1, arg2);\r\n                return;\r\n            }\r\n            let copy = new Array(...this._handlers);\r\n            for (let i = 0; i < size; i++) {\r\n                let item = copy[i];\r\n                if (item.once) {\r\n                    let found = this._handlers.indexOf(item);\r\n                    if (found >= 0) {\r\n                        this._handlers.splice(found, 1);\r\n                    }\r\n                }\r\n                copy[i].invoke(arg0, arg1, arg2);\r\n            }\r\n        }\r\n    }\r\n    exports.Dispatcher = Dispatcher;\r\n    /**\r\n     * 按事件名派发\r\n     */\r\n    class EventDispatcher {\r\n        constructor() {\r\n            this._dispatcher = {};\r\n        }\r\n        on(evt, caller, fn) {\r\n            let dispatcher = this._dispatcher[evt];\r\n            if (typeof dispatcher === \"undefined\") {\r\n                dispatcher = this._dispatcher[evt] = new Dispatcher();\r\n            }\r\n            dispatcher.on(caller, fn);\r\n        }\r\n        once(evt, caller, fn) {\r\n            let dispatcher = this._dispatcher[evt];\r\n            if (typeof dispatcher === \"undefined\") {\r\n                dispatcher = this._dispatcher[evt] = new Dispatcher();\r\n            }\r\n            dispatcher.once(caller, fn);\r\n        }\r\n        off(evt, caller, fn) {\r\n            let dispatcher = this._dispatcher[evt];\r\n            if (typeof dispatcher !== \"undefined\") {\r\n                dispatcher.off(caller, fn);\r\n            }\r\n        }\r\n        clear() {\r\n            for (let evt in this._dispatcher) {\r\n                let dispatcher = this._dispatcher[evt];\r\n                if (dispatcher instanceof Dispatcher) {\r\n                    dispatcher.clear();\r\n                }\r\n            }\r\n        }\r\n        /**\r\n         * 派发指定事件\r\n         */\r\n        dispatch(evt, arg0, arg1, arg2) {\r\n            let dispatcher = this._dispatcher[evt];\r\n            if (typeof dispatcher !== \"undefined\") {\r\n                dispatcher.dispatch(arg0, arg1, arg2);\r\n            }\r\n        }\r\n    }\r\n    exports.EventDispatcher = EventDispatcher;\r\n});\r\n/*\r\nhttps://github.com/marijnz/unity-autocomplete-search-field\r\n*/\r\ndefine(\"plover/editor/auto_completion_field\", [\"require\", \"exports\", \"UnityEditor\", \"UnityEditor.IMGUI.Controls\", \"UnityEngine\", \"plover/events/dispatcher\"], function (require, exports, UnityEditor_1, UnityEditor_IMGUI_Controls_1, UnityEngine_1, dispatcher_1) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.AutoCompletionField = void 0;\r\n    let Styles = {\r\n        resultHeight: 20,\r\n        resultsBorderWidth: 2,\r\n        resultsMargin: 15,\r\n        resultsLabelOffset: 2,\r\n        entryEven: UnityEngine_1.GUIStyle.op_Implicit(\"CN EntryBackEven\"),\r\n        entryOdd: UnityEngine_1.GUIStyle.op_Implicit(\"CN EntryBackOdd\"),\r\n        labelStyle: new UnityEngine_1.GUIStyle(UnityEditor_1.EditorStyles.label),\r\n        resultsBorderStyle: UnityEngine_1.GUIStyle.op_Implicit(\"hostview\"),\r\n    };\r\n    Styles.labelStyle.alignment = UnityEngine_1.TextAnchor.MiddleLeft;\r\n    Styles.labelStyle.richText = true;\r\n    class AutoCompletionField extends dispatcher_1.EventDispatcher {\r\n        constructor() {\r\n            super();\r\n            this.searchString = \"\";\r\n            this.maxResults = 15;\r\n            this.results = [];\r\n            this.selectedIndex = -1;\r\n            this.previousMousePosition = UnityEngine_1.Vector2.zero;\r\n            this.selectedIndexByMouse = false;\r\n            this.showResults = false;\r\n        }\r\n        addResult(result) {\r\n            this.results.push(result);\r\n        }\r\n        clearResults() {\r\n            this.results.splice(0);\r\n        }\r\n        onToolbarGUI() {\r\n            this.draw(true);\r\n        }\r\n        onGUI() {\r\n            this.draw(false);\r\n        }\r\n        draw(asToolbar) {\r\n            let rect = UnityEngine_1.GUILayoutUtility.GetRect(1, 1, 18, 18, UnityEngine_1.GUILayout.ExpandWidth(true));\r\n            UnityEngine_1.GUILayout.BeginHorizontal();\r\n            this.doSearchField(rect, asToolbar);\r\n            UnityEngine_1.GUILayout.EndHorizontal();\r\n            rect.y += 18;\r\n            this.doResults(rect);\r\n        }\r\n        doSearchField(rect, asToolbar) {\r\n            if (this.searchField == null) {\r\n                this.searchField = new UnityEditor_IMGUI_Controls_1.SearchField();\r\n                this.searchField.downOrUpArrowKeyPressed(\"add\", this.onDownOrUpArrowKeyPressed.bind(this));\r\n            }\r\n            var result = asToolbar\r\n                ? this.searchField.OnToolbarGUI(rect, this.searchString)\r\n                : this.searchField.OnGUI(rect, this.searchString);\r\n            if (typeof result === \"string\") {\r\n                if (result != this.searchString) {\r\n                    this.dispatch(\"change\", result);\r\n                    this.selectedIndex = -1;\r\n                    this.showResults = true;\r\n                }\r\n                this.searchString = result;\r\n                if (this.hasSearchbarFocused()) {\r\n                    this.repaintFocusedWindow();\r\n                }\r\n            }\r\n        }\r\n        onDownOrUpArrowKeyPressed() {\r\n            let current = UnityEngine_1.Event.current;\r\n            if (current.keyCode == UnityEngine_1.KeyCode.UpArrow) {\r\n                current.Use();\r\n                this.selectedIndex--;\r\n                this.selectedIndexByMouse = false;\r\n            }\r\n            else {\r\n                current.Use();\r\n                this.selectedIndex++;\r\n                this.selectedIndexByMouse = false;\r\n            }\r\n            if (this.selectedIndex >= this.results.length)\r\n                this.selectedIndex = this.results.length - 1;\r\n            else if (this.selectedIndex < 0)\r\n                this.selectedIndex = -1;\r\n        }\r\n        doResults(rect) {\r\n            if (this.results.length <= 0 || !this.showResults)\r\n                return;\r\n            var current = UnityEngine_1.Event.current;\r\n            rect.height = Styles.resultHeight * Math.min(this.maxResults, this.results.length);\r\n            rect.x = Styles.resultsMargin;\r\n            rect.width -= Styles.resultsMargin * 2;\r\n            var elementRect = new UnityEngine_1.Rect(rect);\r\n            rect.height += Styles.resultsBorderWidth;\r\n            UnityEngine_1.GUI.Label(rect, \"\", Styles.resultsBorderStyle);\r\n            var mouseIsInResultsRect = rect.Contains(current.mousePosition);\r\n            if (mouseIsInResultsRect) {\r\n                this.repaintFocusedWindow();\r\n            }\r\n            var movedMouseInRect = UnityEngine_1.Vector2.op_Inequality(this.previousMousePosition, current.mousePosition);\r\n            elementRect.x += Styles.resultsBorderWidth;\r\n            elementRect.width -= Styles.resultsBorderWidth * 2;\r\n            elementRect.height = Styles.resultHeight;\r\n            var didJustSelectIndex = false;\r\n            for (var i = 0; i < this.results.length && i < this.maxResults; i++) {\r\n                if (current.type == UnityEngine_1.EventType.Repaint) {\r\n                    var style = i % 2 == 0 ? Styles.entryOdd : Styles.entryEven;\r\n                    style.Draw(elementRect, false, false, i == this.selectedIndex, false);\r\n                    var labelRect = new UnityEngine_1.Rect(elementRect);\r\n                    labelRect.x += Styles.resultsLabelOffset;\r\n                    UnityEngine_1.GUI.Label(labelRect, this.results[i], Styles.labelStyle);\r\n                }\r\n                if (elementRect.Contains(current.mousePosition)) {\r\n                    if (movedMouseInRect) {\r\n                        this.selectedIndex = i;\r\n                        this.selectedIndexByMouse = true;\r\n                        didJustSelectIndex = true;\r\n                    }\r\n                    if (current.type == UnityEngine_1.EventType.MouseDown) {\r\n                        this.onConfirm(this.results[i]);\r\n                    }\r\n                }\r\n                elementRect.y += Styles.resultHeight;\r\n            }\r\n            if (current.type == UnityEngine_1.EventType.Repaint && !didJustSelectIndex && !mouseIsInResultsRect && this.selectedIndexByMouse) {\r\n                this.selectedIndex = -1;\r\n            }\r\n            if ((UnityEngine_1.GUIUtility.hotControl != this.searchField.searchFieldControlID && UnityEngine_1.GUIUtility.hotControl > 0)\r\n                || (current.rawType == UnityEngine_1.EventType.MouseDown && !mouseIsInResultsRect)) {\r\n                this.showResults = false;\r\n            }\r\n            if (current.type == UnityEngine_1.EventType.KeyUp && current.keyCode == UnityEngine_1.KeyCode.Return && this.selectedIndex >= 0) {\r\n                this.onConfirm(this.results[this.selectedIndex]);\r\n            }\r\n            if (current.type == UnityEngine_1.EventType.Repaint) {\r\n                this.previousMousePosition = current.mousePosition;\r\n            }\r\n        }\r\n        onConfirm(result) {\r\n            this.searchString = result;\r\n            this.dispatch(\"confirm\", result);\r\n            this.dispatch(\"change\", result);\r\n            this.repaintFocusedWindow();\r\n            UnityEngine_1.GUIUtility.keyboardControl = 0; // To avoid Unity sometimes not updating the search field text\r\n        }\r\n        hasSearchbarFocused() {\r\n            return UnityEngine_1.GUIUtility.keyboardControl == this.searchField.searchFieldControlID;\r\n        }\r\n        repaintFocusedWindow() {\r\n            if (UnityEditor_1.EditorWindow.focusedWindow != null) {\r\n                UnityEditor_1.EditorWindow.focusedWindow.Repaint();\r\n            }\r\n        }\r\n    }\r\n    exports.AutoCompletionField = AutoCompletionField;\r\n});\r\ndefine(\"plover/runtime/serialize\", [\"require\", \"exports\", \"UnityEngine\"], function (require, exports, UnityEngine_2) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.RegisterSerializer = exports.GetSerializer = exports.GetLatestSerializer = exports.SerializedTypeID = void 0;\r\n    var SerializedTypeID;\r\n    (function (SerializedTypeID) {\r\n        SerializedTypeID[SerializedTypeID[\"Null\"] = 0] = \"Null\";\r\n        SerializedTypeID[SerializedTypeID[\"UserDefinedMin\"] = 1] = \"UserDefinedMin\";\r\n        SerializedTypeID[SerializedTypeID[\"UserDefinedMax\"] = 100] = \"UserDefinedMax\";\r\n        SerializedTypeID[SerializedTypeID[\"Array\"] = 101] = \"Array\";\r\n        SerializedTypeID[SerializedTypeID[\"Object\"] = 102] = \"Object\";\r\n    })(SerializedTypeID = exports.SerializedTypeID || (exports.SerializedTypeID = {}));\r\n    let _PrimitiveSerializerImpls = [];\r\n    let _LatestSerializer;\r\n    function GetLatestSerializer() {\r\n        return _LatestSerializer;\r\n    }\r\n    exports.GetLatestSerializer = GetLatestSerializer;\r\n    function GetSerializer(dataFormat) {\r\n        return _PrimitiveSerializerImpls[dataFormat];\r\n    }\r\n    exports.GetSerializer = GetSerializer;\r\n    function RegisterSerializer(dataFormat, description, types, bSetAsLatest) {\r\n        let impl = {\r\n            dataFormat: dataFormat,\r\n            description: description,\r\n            types: types,\r\n            typeids: [],\r\n        };\r\n        for (let typename in types) {\r\n            let type = types[typename];\r\n            console.assert(type.typeid >= SerializedTypeID.UserDefinedMin && type.typeid <= SerializedTypeID.UserDefinedMax, \"typeid must be greater than 0 and less than 100\");\r\n            impl.typeids[type.typeid] = type;\r\n        }\r\n        _PrimitiveSerializerImpls[dataFormat] = impl;\r\n        if (!!bSetAsLatest) {\r\n            _LatestSerializer = impl;\r\n        }\r\n    }\r\n    exports.RegisterSerializer = RegisterSerializer;\r\n    RegisterSerializer(1, \"v1: without size check\", {\r\n        \"bool\": {\r\n            typeid: 1,\r\n            defaultValue: false,\r\n            serialize(context, buffer, value) {\r\n                buffer.WriteBoolean(!!value);\r\n            },\r\n            deserilize(context, buffer) {\r\n                return buffer.ReadBoolean();\r\n            }\r\n        },\r\n        \"float\": {\r\n            typeid: 2,\r\n            defaultValue: 0,\r\n            serialize(context, buffer, value) {\r\n                if (typeof value === \"number\") {\r\n                    buffer.WriteSingle(value);\r\n                }\r\n                else {\r\n                    buffer.WriteSingle(0);\r\n                }\r\n            },\r\n            deserilize(context, buffer) {\r\n                return buffer.ReadSingle();\r\n            }\r\n        },\r\n        \"double\": {\r\n            typeid: 3,\r\n            defaultValue: 0,\r\n            serialize(context, buffer, value) {\r\n                if (typeof value === \"number\") {\r\n                    buffer.WriteDouble(value);\r\n                }\r\n                else {\r\n                    buffer.WriteDouble(0);\r\n                }\r\n            },\r\n            deserilize(context, buffer) {\r\n                return buffer.ReadDouble();\r\n            }\r\n        },\r\n        \"string\": {\r\n            typeid: 4,\r\n            defaultValue: null,\r\n            serialize(context, buffer, value) {\r\n                if (typeof value === \"string\") {\r\n                    buffer.WriteString(value);\r\n                }\r\n                else {\r\n                    buffer.WriteString(null);\r\n                }\r\n            },\r\n            deserilize(context, buffer) {\r\n                return buffer.ReadString();\r\n            }\r\n        },\r\n        \"int\": {\r\n            typeid: 5,\r\n            defaultValue: 0,\r\n            serialize(context, buffer, value) {\r\n                if (typeof value === \"number\") {\r\n                    buffer.WriteInt32(value);\r\n                }\r\n                else {\r\n                    buffer.WriteInt32(0);\r\n                }\r\n            },\r\n            deserilize(context, buffer) {\r\n                return buffer.ReadInt32();\r\n            }\r\n        },\r\n        \"uint\": {\r\n            typeid: 6,\r\n            defaultValue: 0,\r\n            serialize(context, buffer, value) {\r\n                if (typeof value === \"number\") {\r\n                    buffer.WriteUInt32(value);\r\n                }\r\n                else {\r\n                    buffer.WriteUInt32(0);\r\n                }\r\n            },\r\n            deserilize(context, buffer) {\r\n                return buffer.ReadUInt32();\r\n            }\r\n        },\r\n        \"Vector2\": {\r\n            typeid: 7,\r\n            defaultValue: () => UnityEngine_2.Vector2.zero,\r\n            serialize(context, buffer, value) {\r\n                if (value instanceof UnityEngine_2.Vector2) {\r\n                    buffer.WriteSingle(value.x);\r\n                    buffer.WriteSingle(value.y);\r\n                }\r\n                else {\r\n                    buffer.WriteSingle(0);\r\n                    buffer.WriteSingle(0);\r\n                }\r\n            },\r\n            deserilize(context, buffer) {\r\n                return new UnityEngine_2.Vector2(buffer.ReadSingle(), buffer.ReadSingle());\r\n            }\r\n        },\r\n        \"Vector3\": {\r\n            typeid: 8,\r\n            defaultValue: () => UnityEngine_2.Vector3.zero,\r\n            serialize(context, buffer, value) {\r\n                if (value instanceof UnityEngine_2.Vector3) {\r\n                    buffer.WriteSingle(value.x);\r\n                    buffer.WriteSingle(value.y);\r\n                    buffer.WriteSingle(value.z);\r\n                }\r\n                else {\r\n                    buffer.WriteSingle(0);\r\n                    buffer.WriteSingle(0);\r\n                    buffer.WriteSingle(0);\r\n                }\r\n            },\r\n            deserilize(context, buffer) {\r\n                return new UnityEngine_2.Vector3(buffer.ReadSingle(), buffer.ReadSingle(), buffer.ReadSingle());\r\n            }\r\n        },\r\n        \"Vector4\": {\r\n            typeid: 9,\r\n            defaultValue: () => UnityEngine_2.Vector4.zero,\r\n            serialize(context, buffer, value) {\r\n                if (value instanceof UnityEngine_2.Vector4) {\r\n                    buffer.WriteSingle(value.x);\r\n                    buffer.WriteSingle(value.y);\r\n                    buffer.WriteSingle(value.z);\r\n                    buffer.WriteSingle(value.w);\r\n                }\r\n                else {\r\n                    buffer.WriteSingle(0);\r\n                    buffer.WriteSingle(0);\r\n                    buffer.WriteSingle(0);\r\n                    buffer.WriteSingle(0);\r\n                }\r\n            },\r\n            deserilize(context, buffer) {\r\n                return new UnityEngine_2.Vector4(buffer.ReadSingle(), buffer.ReadSingle(), buffer.ReadSingle(), buffer.ReadSingle());\r\n            }\r\n        },\r\n        \"Rect\": {\r\n            typeid: 10,\r\n            defaultValue: () => UnityEngine_2.Rect.zero,\r\n            serialize(context, buffer, value) {\r\n                if (value instanceof UnityEngine_2.Rect) {\r\n                    buffer.WriteSingle(value.x);\r\n                    buffer.WriteSingle(value.y);\r\n                    buffer.WriteSingle(value.width);\r\n                    buffer.WriteSingle(value.height);\r\n                }\r\n                else {\r\n                    buffer.WriteSingle(0);\r\n                    buffer.WriteSingle(0);\r\n                    buffer.WriteSingle(0);\r\n                    buffer.WriteSingle(0);\r\n                }\r\n            },\r\n            deserilize(context, buffer) {\r\n                return new UnityEngine_2.Rect(buffer.ReadSingle(), buffer.ReadSingle(), buffer.ReadSingle(), buffer.ReadSingle());\r\n            }\r\n        },\r\n        \"Quaternion\": {\r\n            typeid: 11,\r\n            defaultValue: () => UnityEngine_2.Quaternion.identity,\r\n            serialize(context, buffer, value) {\r\n                if (value instanceof UnityEngine_2.Quaternion) {\r\n                    buffer.WriteSingle(value.x);\r\n                    buffer.WriteSingle(value.y);\r\n                    buffer.WriteSingle(value.z);\r\n                    buffer.WriteSingle(value.w);\r\n                }\r\n                else {\r\n                    buffer.WriteSingle(0);\r\n                    buffer.WriteSingle(0);\r\n                    buffer.WriteSingle(0);\r\n                    buffer.WriteSingle(1);\r\n                }\r\n            },\r\n            deserilize(context, buffer) {\r\n                return new UnityEngine_2.Quaternion(buffer.ReadSingle(), buffer.ReadSingle(), buffer.ReadSingle(), buffer.ReadSingle());\r\n            }\r\n        },\r\n        \"object\": {\r\n            typeid: 12,\r\n            defaultValue: null,\r\n            serialize(context, buffer, value) {\r\n                if (value instanceof UnityEngine_2.Object) {\r\n                    let index = context.ps.AddReferencedObject(value);\r\n                    buffer.WriteInt32(index);\r\n                }\r\n                else {\r\n                    if (!!value) {\r\n                        console.error(\"only types inheriting UnityEngine.Object is unsupported\", value);\r\n                    }\r\n                    buffer.WriteInt32(-1);\r\n                }\r\n            },\r\n            deserilize(context, buffer) {\r\n                let index = buffer.ReadInt32();\r\n                return context.ps.GetReferencedObject(index);\r\n            }\r\n        },\r\n        // js Uint8ArrayBuffer\r\n        \"Uint8ArrayBuffer\": {\r\n            typeid: 13,\r\n            defaultValue: null,\r\n            serialize(context, buffer, value) {\r\n                if (value instanceof Uint8Array) {\r\n                    let length = value.byteLength;\r\n                    buffer.WriteInt32(length);\r\n                    for (let i = 0; i < length; ++i) {\r\n                        buffer.WriteByte(value[i]);\r\n                    }\r\n                }\r\n                else {\r\n                    buffer.WriteInt32(-1);\r\n                }\r\n            },\r\n            deserilize(context, buffer) {\r\n                let length = buffer.ReadInt32();\r\n                if (length < 0) {\r\n                    return null;\r\n                }\r\n                else {\r\n                    let items = new Uint8Array(length);\r\n                    for (let i = 0; i < length; ++i) {\r\n                        items[i] = buffer.ReadUByte();\r\n                    }\r\n                    return items;\r\n                }\r\n            }\r\n        },\r\n        \"json\": {\r\n            typeid: 14,\r\n            defaultValue: null,\r\n            serialize(context, buffer, value) {\r\n                if (typeof value === \"object\") {\r\n                    let json = JSON.stringify(value);\r\n                    buffer.WriteString(json);\r\n                }\r\n                else {\r\n                    buffer.WriteString(null);\r\n                }\r\n            },\r\n            deserilize(context, buffer) {\r\n                let json = buffer.ReadString();\r\n                if (typeof json === \"string\") {\r\n                    return JSON.parse(json);\r\n                }\r\n                return null;\r\n            }\r\n        },\r\n    }, true);\r\n});\r\ndefine(\"plover/runtime/class_decorators\", [\"require\", \"exports\", \"UnityEngine\", \"plover/runtime/serialize\"], function (require, exports, UnityEngine_3, serialize_1) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.SerializationUtil = exports.ScriptFunction = exports.ScriptProperty = exports.ScriptObject = exports.ScriptString = exports.ScriptNumber = exports.ScriptInteger = exports.ScriptType = exports.ScriptAsset = exports.ScriptSerializable = void 0;\r\n    let Symbol_PropertiesTouched = Symbol.for(\"PropertiesTouched\");\r\n    let Symbol_MemberFuncs = Symbol.for(\"MemberFuncs\");\r\n    let Symbol_SerializedFields = Symbol.for(\"SerializedFields\");\r\n    function ScriptSerializable(meta) {\r\n        return ScriptType(meta);\r\n    }\r\n    exports.ScriptSerializable = ScriptSerializable;\r\n    function ScriptAsset(meta) {\r\n        return ScriptType(meta);\r\n    }\r\n    exports.ScriptAsset = ScriptAsset;\r\n    // expose this script class type to JSBehaviour, so you can put it on a prefab gameObject\r\n    function ScriptType(meta) {\r\n        return function (target) {\r\n            let OnBeforeSerialize = target.prototype[\"OnBeforeSerialize\"];\r\n            target.prototype[\"OnBeforeSerialize\"] = function (ps) {\r\n                this[Symbol_PropertiesTouched] = false;\r\n                if (typeof OnBeforeSerialize === \"function\") {\r\n                    OnBeforeSerialize.call(this, ps);\r\n                }\r\n                if (!this[Symbol_PropertiesTouched]) {\r\n                    SerializationUtil.serialize(this, ps);\r\n                }\r\n            };\r\n            let OnAfterDeserialize = target.prototype[\"OnAfterDeserialize\"];\r\n            target.prototype[\"OnAfterDeserialize\"] = function (ps, buffer) {\r\n                this[Symbol_PropertiesTouched] = false;\r\n                if (typeof OnAfterDeserialize === \"function\") {\r\n                    OnAfterDeserialize.call(this, ps, buffer);\r\n                }\r\n                if (!this[Symbol_PropertiesTouched]) {\r\n                    SerializationUtil.deserialize(this, ps, buffer);\r\n                }\r\n            };\r\n            return target;\r\n        };\r\n    }\r\n    exports.ScriptType = ScriptType;\r\n    function ScriptInteger(meta) {\r\n        let meta_t = meta;\r\n        if (typeof meta_t === \"undefined\") {\r\n            meta_t = { type: \"int\" };\r\n        }\r\n        else {\r\n            meta_t.type = \"int\";\r\n        }\r\n        return ScriptProperty(meta_t);\r\n    }\r\n    exports.ScriptInteger = ScriptInteger;\r\n    function ScriptNumber(meta) {\r\n        let meta_t = meta;\r\n        if (typeof meta_t === \"undefined\") {\r\n            meta_t = { type: \"float\" };\r\n        }\r\n        else {\r\n            meta_t.type = \"float\";\r\n        }\r\n        return ScriptProperty(meta_t);\r\n    }\r\n    exports.ScriptNumber = ScriptNumber;\r\n    function ScriptString(meta) {\r\n        let meta_t = meta;\r\n        if (typeof meta_t === \"undefined\") {\r\n            meta_t = { type: \"string\" };\r\n        }\r\n        else {\r\n            meta_t.type = \"string\";\r\n        }\r\n        return ScriptProperty(meta_t);\r\n    }\r\n    exports.ScriptString = ScriptString;\r\n    function ScriptObject(meta) {\r\n        let meta_t = meta;\r\n        if (typeof meta_t === \"undefined\") {\r\n            meta_t = { type: \"object\" };\r\n        }\r\n        else {\r\n            meta_t.type = \"object\";\r\n        }\r\n        return ScriptProperty(meta_t);\r\n    }\r\n    exports.ScriptObject = ScriptObject;\r\n    function ScriptProperty(meta) {\r\n        return function (target, propertyKey) {\r\n            let slots = target[Symbol_SerializedFields];\r\n            if (typeof slots === \"undefined\") {\r\n                slots = target[Symbol_SerializedFields] = {};\r\n            }\r\n            let slot = slots[propertyKey] = meta || { type: \"object\" };\r\n            slot.propertyKey = propertyKey;\r\n            if (typeof slot.serializable !== \"boolean\") {\r\n                slot.serializable = true;\r\n            }\r\n            if (typeof slot.editable !== \"boolean\") {\r\n                slot.editable = true;\r\n            }\r\n            if (typeof slot.visible !== \"boolean\") {\r\n                slot.visible = true;\r\n            }\r\n            if (typeof slot.name !== \"string\") {\r\n                slot.name = propertyKey;\r\n            }\r\n        };\r\n    }\r\n    exports.ScriptProperty = ScriptProperty;\r\n    function ScriptFunction(meta) {\r\n        return function (target, propertyKey) {\r\n            let funcMap = target[Symbol_MemberFuncs];\r\n            if (typeof funcMap === \"undefined\") {\r\n                funcMap = target[Symbol_MemberFuncs] = {};\r\n            }\r\n            funcMap[propertyKey] = propertyKey;\r\n        };\r\n    }\r\n    exports.ScriptFunction = ScriptFunction;\r\n    class SerializationUtil {\r\n        static forEach(target, cb) {\r\n            let slots = target[Symbol_SerializedFields];\r\n            if (typeof slots !== \"undefined\") {\r\n                for (let propertyKey in slots) {\r\n                    cb(slots, propertyKey);\r\n                }\r\n            }\r\n        }\r\n        // 当不需要默认行为时, 调用此函数将序列化状态标记为已完成, 以便跳过默认的 serialize/deserialize 行为\r\n        static markAsReady(target) {\r\n            target[Symbol_PropertiesTouched] = true;\r\n        }\r\n        static serialize(target, ps) {\r\n            SerializationUtil.markAsReady(target);\r\n            let impl = serialize_1.GetLatestSerializer();\r\n            console.assert(typeof ps === \"object\");\r\n            if (typeof impl === \"object\") {\r\n                ps.dataFormat = impl.dataFormat;\r\n                let slots = target[Symbol_SerializedFields];\r\n                if (typeof slots !== \"undefined\") {\r\n                    let buffer = SerializationUtil._serializeObject({ impl: impl, ps: ps }, target, slots);\r\n                    ps.Flush(buffer);\r\n                }\r\n            }\r\n        }\r\n        static _serializeValue(context, slot, value, buffer) {\r\n            let slotType = slot.type;\r\n            let isArray = value instanceof Array;\r\n            if (typeof value === \"object\") {\r\n                if (value instanceof UnityEngine_3.Object) {\r\n                    slotType = \"object\";\r\n                }\r\n            }\r\n            if (typeof slotType === \"string\") {\r\n                // primitive serializer impl\r\n                let s = context.impl.types[slotType];\r\n                if (typeof s === \"object\") {\r\n                    if (isArray) {\r\n                        let section = SerializationUtil._serializePrimitiveArray(context, s, value);\r\n                        buffer.WriteByte(serialize_1.SerializedTypeID.Array);\r\n                        buffer.WriteByte(s.typeid);\r\n                        buffer.WriteInt32(section.readableBytes);\r\n                        buffer.WriteBytes(section);\r\n                    }\r\n                    else {\r\n                        buffer.WriteByte(s.typeid);\r\n                        s.serialize(context, buffer, value);\r\n                    }\r\n                }\r\n                else {\r\n                    console.error(\"no serializer impl for\", slotType);\r\n                }\r\n            }\r\n            else {\r\n                // typeof slot.type === \"function\" (a constructor)\r\n                // nested value\r\n                let fieldSlots = slotType.prototype[Symbol_SerializedFields];\r\n                if (typeof fieldSlots !== \"undefined\") {\r\n                    if (isArray) {\r\n                        let section = SerializationUtil._serializeObjectArray(context, fieldSlots, value);\r\n                        buffer.WriteByte(serialize_1.SerializedTypeID.Array);\r\n                        buffer.WriteByte(serialize_1.SerializedTypeID.Object);\r\n                        buffer.WriteInt32(section.readableBytes);\r\n                        buffer.WriteBytes(section);\r\n                    }\r\n                    else {\r\n                        let section = SerializationUtil._serializeObject(context, value, fieldSlots);\r\n                        buffer.WriteByte(serialize_1.SerializedTypeID.Object);\r\n                        buffer.WriteInt32(section.readableBytes);\r\n                        buffer.WriteBytes(section);\r\n                    }\r\n                }\r\n                else {\r\n                    console.error(\"no serialization info on field\", slot.name);\r\n                }\r\n            }\r\n        }\r\n        static _serializeObjectArray(context, slots, value) {\r\n            let length = value.length;\r\n            let buffer = context.ps.AllocByteBuffer();\r\n            for (let i = 0; i < length; ++i) {\r\n                let section = SerializationUtil._serializeObject(context, value[i], slots);\r\n                buffer.WriteInt32(section.readableBytes);\r\n                buffer.WriteBytes(section);\r\n            }\r\n            return buffer;\r\n        }\r\n        static _serializePrimitiveArray(context, s, value) {\r\n            let length = value.length;\r\n            let buffer = context.ps.AllocByteBuffer();\r\n            for (let i = 0; i < length; ++i) {\r\n                s.serialize(context, buffer, value[i]);\r\n            }\r\n            return buffer;\r\n        }\r\n        static _serializeObject(context, target, slots) {\r\n            let buffer = context.ps.AllocByteBuffer();\r\n            for (let propertyKey in slots) {\r\n                let slot = slots[propertyKey];\r\n                if (slot.serializable) {\r\n                    let value = target && target[propertyKey];\r\n                    // skip undefined and null value\r\n                    if (value == null) {\r\n                        continue;\r\n                    }\r\n                    buffer.WriteString(slot.name);\r\n                    SerializationUtil._serializeValue(context, slot, value, buffer);\r\n                }\r\n            }\r\n            return buffer;\r\n        }\r\n        static deserialize(target, ps, buffer) {\r\n            SerializationUtil.markAsReady(target);\r\n            let slots = target[Symbol_SerializedFields];\r\n            if (typeof slots !== \"undefined\") {\r\n                let dataFormat = ps.dataFormat || 0;\r\n                let impl = serialize_1.GetSerializer(dataFormat);\r\n                if (typeof impl === \"object\") {\r\n                    SerializationUtil._deserializeObjectInternal({ impl: impl, ps: ps }, target, slots, buffer);\r\n                }\r\n                else {\r\n                    if (buffer.readableBytes > 0 && ps.dataFormat >= 0) {\r\n                        console.error(\"no serializer for dataFormat\", dataFormat);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        static _deserializeObject(context, slot, buffer) {\r\n            if (typeof slot.type === \"function\") {\r\n                let fieldValue = Object.create(slot.type);\r\n                let fieldSlots = slot.type.prototype[Symbol_SerializedFields];\r\n                SerializationUtil._deserializeObjectInternal(context, fieldValue, fieldSlots, buffer);\r\n                return fieldValue;\r\n            }\r\n            else {\r\n                console.error(\"expecting object but got primitive\", slot.type);\r\n            }\r\n        }\r\n        static _deserializeObjectArray(context, slot, buffer) {\r\n            let items = [];\r\n            while (buffer.readableBytes > 0) {\r\n                let size = buffer.ReadInt32();\r\n                let section = buffer.Slice(size);\r\n                let value = SerializationUtil._deserializeObject(context, slot, section);\r\n                items.push(value);\r\n            }\r\n            return items;\r\n        }\r\n        static _deserializePrimitiveArray(context, s, buffer) {\r\n            let items = [];\r\n            while (buffer.readableBytes > 0) {\r\n                let value = s.deserilize(context, buffer);\r\n                items.push(value);\r\n            }\r\n            return items;\r\n        }\r\n        static _deserializeObjectInternal(context, target, slots, buffer) {\r\n            let slotByName = {};\r\n            for (let propertyKey in slots) {\r\n                let slot = slots[propertyKey];\r\n                if (slot.serializable) {\r\n                    slotByName[slot.name] = slot;\r\n                    if (typeof slot.type === \"string\") {\r\n                        let defaultValue = context.impl.types[slot.type].defaultValue;\r\n                        if (typeof defaultValue === \"function\") {\r\n                            defaultValue = defaultValue();\r\n                        }\r\n                        target[slot.propertyKey] = defaultValue;\r\n                    }\r\n                    else {\r\n                        target[slot.propertyKey] = null;\r\n                    }\r\n                }\r\n            }\r\n            while (buffer.readableBytes > 0) {\r\n                let name = buffer.ReadString();\r\n                let typeid = buffer.ReadUByte();\r\n                let slot = slotByName[name];\r\n                // should always read the buffer since the serialized field may be removed from script\r\n                let s = context.impl.typeids[typeid];\r\n                if (typeof s === \"object\") {\r\n                    let slot_value = s.deserilize(context, buffer);\r\n                    if (slot) {\r\n                        if (typeof slot.type === \"string\") {\r\n                            console.assert(typeid == context.impl.types[slot.type].typeid, \"slot type mismatch\");\r\n                        }\r\n                        else {\r\n                            if (typeof slot_value === \"object\") {\r\n                                console.assert(slot_value instanceof slot.type, \"slot type mismatch\");\r\n                            }\r\n                        }\r\n                        target[slot.propertyKey] = slot_value;\r\n                    }\r\n                    else {\r\n                        console.warn(\"failed to read slot\", name);\r\n                    }\r\n                }\r\n                else {\r\n                    switch (typeid) {\r\n                        case serialize_1.SerializedTypeID.Object: {\r\n                            let size = buffer.ReadInt32();\r\n                            let section = buffer.Slice(size);\r\n                            target[slot.propertyKey] = SerializationUtil._deserializeObject(context, slot, section);\r\n                            break;\r\n                        }\r\n                        case serialize_1.SerializedTypeID.Array: {\r\n                            let elementTypeID = buffer.ReadUByte();\r\n                            let size = buffer.ReadInt32();\r\n                            let section = buffer.Slice(size);\r\n                            let s = context.impl.typeids[elementTypeID];\r\n                            if (typeof s === \"undefined\") {\r\n                                target[slot.propertyKey] = SerializationUtil._deserializeObjectArray(context, slot, section);\r\n                            }\r\n                            else {\r\n                                target[slot.propertyKey] = SerializationUtil._deserializePrimitiveArray(context, s, section);\r\n                            }\r\n                            break;\r\n                        }\r\n                        case serialize_1.SerializedTypeID.Null: break;\r\n                        default: {\r\n                            console.error(`no serializer for serialized field ${name} with typeid ${typeid}`);\r\n                            break;\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n    exports.SerializationUtil = SerializationUtil;\r\n});\r\ndefine(\"plover/editor/drawer\", [\"require\", \"exports\", \"UnityEditor\", \"UnityEngine\"], function (require, exports, UnityEditor_2, UnityEngine_4) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.DefaultPropertyDrawers = void 0;\r\n    exports.DefaultPropertyDrawers = {\r\n        \"bool\": {\r\n            draw(rawValue, prop, label, editablePE) {\r\n                let oldValue = !!rawValue;\r\n                if (editablePE) {\r\n                    let newValue = UnityEditor_2.EditorGUILayout.Toggle(label, oldValue);\r\n                    return newValue;\r\n                }\r\n                else {\r\n                    UnityEditor_2.EditorGUI.BeginDisabledGroup(true);\r\n                    UnityEditor_2.EditorGUILayout.Toggle(label, oldValue);\r\n                    UnityEditor_2.EditorGUI.EndDisabledGroup();\r\n                }\r\n            },\r\n        },\r\n        \"int\": {\r\n            draw(rawValue, prop, label, editablePE) {\r\n                let oldValue = rawValue || 0;\r\n                if (editablePE) {\r\n                    let newValue = UnityEditor_2.EditorGUILayout.IntField(label, oldValue);\r\n                    return newValue;\r\n                }\r\n                else {\r\n                    UnityEditor_2.EditorGUI.BeginDisabledGroup(true);\r\n                    UnityEditor_2.EditorGUILayout.IntField(label, oldValue);\r\n                    UnityEditor_2.EditorGUI.EndDisabledGroup();\r\n                }\r\n            },\r\n        },\r\n        \"float\": {\r\n            draw(rawValue, prop, label, editablePE) {\r\n                let oldValue = rawValue || 0;\r\n                if (editablePE) {\r\n                    let newValue = UnityEditor_2.EditorGUILayout.FloatField(label, oldValue);\r\n                    return newValue;\r\n                }\r\n                else {\r\n                    UnityEditor_2.EditorGUI.BeginDisabledGroup(true);\r\n                    UnityEditor_2.EditorGUILayout.FloatField(label, oldValue);\r\n                    UnityEditor_2.EditorGUI.EndDisabledGroup();\r\n                }\r\n            },\r\n        },\r\n        \"double\": {\r\n            draw(rawValue, prop, label, editablePE) {\r\n                let oldValue = rawValue || 0;\r\n                if (editablePE) {\r\n                    let newValue = UnityEditor_2.EditorGUILayout.FloatField(label, oldValue);\r\n                    return newValue;\r\n                }\r\n                else {\r\n                    UnityEditor_2.EditorGUI.BeginDisabledGroup(true);\r\n                    UnityEditor_2.EditorGUILayout.FloatField(label, oldValue);\r\n                    UnityEditor_2.EditorGUI.EndDisabledGroup();\r\n                }\r\n            },\r\n        },\r\n        \"string\": {\r\n            draw(rawValue, prop, label, editablePE) {\r\n                let oldValue = rawValue || \"\";\r\n                if (editablePE) {\r\n                    let newValue = UnityEditor_2.EditorGUILayout.TextField(label, oldValue);\r\n                    return newValue;\r\n                }\r\n                else {\r\n                    UnityEditor_2.EditorGUI.BeginDisabledGroup(true);\r\n                    UnityEditor_2.EditorGUILayout.TextField(label, oldValue);\r\n                    UnityEditor_2.EditorGUI.EndDisabledGroup();\r\n                }\r\n            },\r\n        },\r\n        \"object\": {\r\n            draw(rawValue, prop, label, editablePE) {\r\n                let oldValue = rawValue instanceof UnityEngine_4.Object || null;\r\n                if (editablePE) {\r\n                    let allowSceneObjects = prop.extra && prop.extra.allowSceneObjects;\r\n                    let newValue = UnityEditor_2.EditorGUILayout.ObjectField(label, oldValue, prop.extra && prop.extra.type || Object, typeof allowSceneObjects === \"boolean\" ? allowSceneObjects : true);\r\n                    return newValue;\r\n                }\r\n                else {\r\n                    UnityEditor_2.EditorGUI.BeginDisabledGroup(true);\r\n                    UnityEditor_2.EditorGUILayout.ObjectField(label, oldValue, Object, false);\r\n                    UnityEditor_2.EditorGUI.EndDisabledGroup();\r\n                }\r\n            },\r\n        },\r\n        \"Vector2\": {\r\n            draw(rawValue, prop, label, editablePE) {\r\n                let oldValue = rawValue || UnityEngine_4.Vector2.zero;\r\n                if (editablePE) {\r\n                    let newValue = UnityEditor_2.EditorGUILayout.Vector2Field(label, oldValue);\r\n                    return newValue;\r\n                }\r\n                else {\r\n                    UnityEditor_2.EditorGUI.BeginDisabledGroup(true);\r\n                    UnityEditor_2.EditorGUILayout.Vector2Field(label, oldValue);\r\n                    UnityEditor_2.EditorGUI.EndDisabledGroup();\r\n                }\r\n            },\r\n        },\r\n        \"Vector3\": {\r\n            draw(rawValue, prop, label, editablePE) {\r\n                let oldValue = rawValue || UnityEngine_4.Vector3.zero;\r\n                if (editablePE) {\r\n                    let newValue = UnityEditor_2.EditorGUILayout.Vector3Field(label, oldValue);\r\n                    return newValue;\r\n                }\r\n                else {\r\n                    UnityEditor_2.EditorGUI.BeginDisabledGroup(true);\r\n                    UnityEditor_2.EditorGUILayout.Vector3Field(label, oldValue);\r\n                    UnityEditor_2.EditorGUI.EndDisabledGroup();\r\n                }\r\n            },\r\n        },\r\n        \"Vector4\": {\r\n            draw(rawValue, prop, label, editablePE) {\r\n                let oldValue = rawValue || UnityEngine_4.Vector4.zero;\r\n                if (editablePE) {\r\n                    let newValue = UnityEditor_2.EditorGUILayout.Vector4Field(label, oldValue);\r\n                    return newValue;\r\n                }\r\n                else {\r\n                    UnityEditor_2.EditorGUI.BeginDisabledGroup(true);\r\n                    UnityEditor_2.EditorGUILayout.Vector4Field(label, oldValue);\r\n                    UnityEditor_2.EditorGUI.EndDisabledGroup();\r\n                }\r\n            },\r\n        },\r\n        \"Quaternion\": {\r\n            draw(rawValue, prop, label, editablePE) {\r\n                let oldValue = rawValue || UnityEngine_4.Quaternion.identity;\r\n                if (editablePE) {\r\n                    let newValue = UnityEditor_2.EditorGUILayout.Vector4Field(label, oldValue);\r\n                    return newValue;\r\n                }\r\n                else {\r\n                    UnityEditor_2.EditorGUI.BeginDisabledGroup(true);\r\n                    UnityEditor_2.EditorGUILayout.Vector4Field(label, oldValue);\r\n                    UnityEditor_2.EditorGUI.EndDisabledGroup();\r\n                }\r\n            },\r\n        },\r\n    };\r\n});\r\ndefine(\"plover/editor/editor_decorators\", [\"require\", \"exports\", \"UnityEditor\", \"UnityEngine\", \"plover/runtime/class_decorators\", \"plover/editor/drawer\"], function (require, exports, UnityEditor_3, UnityEngine_5, class_decorators_1, drawer_1) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.EditorUtil = exports.DefaultEditor = exports.ScriptEditorWindow = exports.ScriptEditor = void 0;\r\n    let Symbol_CustomEditor = Symbol.for(\"CustomEditor\");\r\n    function ScriptEditor(forType) {\r\n        return function (editorType) {\r\n            forType.prototype[Symbol_CustomEditor] = editorType;\r\n            return editorType;\r\n        };\r\n    }\r\n    exports.ScriptEditor = ScriptEditor;\r\n    function ScriptEditorWindow(meta) {\r\n        return class_decorators_1.ScriptType(meta);\r\n    }\r\n    exports.ScriptEditorWindow = ScriptEditorWindow;\r\n    class DefaultEditor extends UnityEditor_3.Editor {\r\n        OnPropertyPreChanging(target, name) {\r\n            UnityEditor_3.Undo.RecordObject(target, \"Change \" + name);\r\n        }\r\n        OnPropertyChanging(target, property, propertyKey, newValue) {\r\n            this.OnPropertyPreChanging(target, propertyKey);\r\n            property[propertyKey] = newValue;\r\n            UnityEditor_3.EditorUtility.SetDirty(target);\r\n        }\r\n        OnArrayPropertyChanging(target, property, propertyKey, index, newValue) {\r\n            this.OnPropertyPreChanging(target, propertyKey);\r\n            property[index] = newValue;\r\n            UnityEditor_3.EditorUtility.SetDirty(target);\r\n        }\r\n        OnInspectorGUI() {\r\n            EditorUtil.draw(this, this.target);\r\n        }\r\n    }\r\n    exports.DefaultEditor = DefaultEditor;\r\n    class EditorUtil {\r\n        static getCustomEditor(forType) {\r\n            return forType[Symbol_CustomEditor] || DefaultEditor;\r\n        }\r\n        /**\r\n         * 默认编辑器绘制行为\r\n         */\r\n        static draw(editor, target) {\r\n            class_decorators_1.SerializationUtil.forEach(target, (slots, propertyKey) => {\r\n                let slot = slots[propertyKey];\r\n                if (slot.visible) {\r\n                    let label = slot.label || propertyKey;\r\n                    let editablePE = slot.editable && (!slot.editorOnly || !UnityEditor_3.EditorApplication.isPlaying);\r\n                    if (typeof slot.type === \"string\") {\r\n                        let d = drawer_1.DefaultPropertyDrawers[slot.type];\r\n                        if (typeof d !== \"undefined\") {\r\n                            let propertyKey = slot.propertyKey;\r\n                            let oldValue = target[propertyKey];\r\n                            if (oldValue instanceof Array) {\r\n                                let length = oldValue.length;\r\n                                for (let i = 0; i < length; i++) {\r\n                                    let newValue = d.draw(oldValue[i], slot, label, editablePE);\r\n                                    if (editablePE && oldValue[i] != newValue) {\r\n                                        editor.OnArrayPropertyChanging(target, oldValue, propertyKey, i, newValue);\r\n                                    }\r\n                                }\r\n                                if (editablePE) {\r\n                                    if (UnityEngine_5.GUILayout.Button(\"Add Element\")) {\r\n                                        oldValue.push(null);\r\n                                        UnityEditor_3.EditorUtility.SetDirty(target);\r\n                                    }\r\n                                }\r\n                            }\r\n                            else {\r\n                                let newValue = d.draw(oldValue, slot, label, editablePE);\r\n                                if (editablePE && oldValue != newValue) {\r\n                                    editor.OnPropertyChanging(target, target, propertyKey, newValue);\r\n                                }\r\n                            }\r\n                            return true;\r\n                        }\r\n                        else {\r\n                            UnityEditor_3.EditorGUILayout.LabelField(label);\r\n                            UnityEditor_3.EditorGUILayout.HelpBox(\"no draw operation for this type\", UnityEditor_3.MessageType.Warning);\r\n                        }\r\n                    }\r\n                    else {\r\n                        UnityEditor_3.EditorGUILayout.LabelField(label);\r\n                        UnityEditor_3.EditorGUILayout.HelpBox(\"unsupported type\", UnityEditor_3.MessageType.Warning);\r\n                    }\r\n                }\r\n            });\r\n        }\r\n    }\r\n    exports.EditorUtil = EditorUtil;\r\n});\r\ndefine(\"plover/editor/file_watcher\", [\"require\", \"exports\", \"plover/events/dispatcher\"], function (require, exports, dispatcher_2) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.FileWatcher = exports.EFileState = void 0;\r\n    var EFileState;\r\n    (function (EFileState) {\r\n        EFileState[EFileState[\"CHANGE\"] = 1] = \"CHANGE\";\r\n        EFileState[EFileState[\"NEW\"] = 2] = \"NEW\";\r\n        EFileState[EFileState[\"DELETE\"] = 3] = \"DELETE\";\r\n    })(EFileState = exports.EFileState || (exports.EFileState = {}));\r\n    class FileWatcher {\r\n        constructor(path, filter) {\r\n            this._dispatcher = new dispatcher_2.EventDispatcher();\r\n            this._disposed = false;\r\n            this._pending = false;\r\n            this._cache = {};\r\n            this._fsw = new FSWatcher(path, filter);\r\n            this._fsw.oncreate = this.oncreate.bind(this);\r\n            this._fsw.onchange = this.onchange.bind(this);\r\n            this._fsw.ondelete = this.ondelete.bind(this);\r\n            this._fsw.includeSubdirectories = true;\r\n            this._fsw.enableRaisingEvents = true;\r\n        }\r\n        get includeSubdirectories() {\r\n            return this._fsw.includeSubdirectories;\r\n        }\r\n        set includeSubdirectories(v) {\r\n            this._fsw.includeSubdirectories = v;\r\n        }\r\n        get enableRaisingEvents() {\r\n            return this._fsw.enableRaisingEvents;\r\n        }\r\n        set enableRaisingEvents(v) {\r\n            this._fsw.enableRaisingEvents = v;\r\n        }\r\n        dispose() {\r\n            if (this._disposed) {\r\n                return;\r\n            }\r\n            this._disposed = true;\r\n            this._fsw.dispose();\r\n            this._fsw = null;\r\n        }\r\n        on(name, caller, fn) {\r\n            this._dispatcher.on(name, caller, fn);\r\n        }\r\n        off(name, caller, fn) {\r\n            this._dispatcher.off(name, caller, fn);\r\n        }\r\n        oncreate(name, fullPath) {\r\n            this.setCacheState(name, fullPath, EFileState.NEW);\r\n        }\r\n        onchange(name, fullPath) {\r\n            this.setCacheState(name, fullPath, EFileState.CHANGE);\r\n        }\r\n        ondelete(name, fullPath) {\r\n            this.setCacheState(name, fullPath, EFileState.DELETE);\r\n        }\r\n        setCacheState(name, fullPath, state) {\r\n            if (this._disposed) {\r\n                return;\r\n            }\r\n            this._cache[name] = {\r\n                name: name,\r\n                fullPath: fullPath,\r\n                state: state,\r\n            };\r\n            if (!this._pending) {\r\n                this._pending = true;\r\n                setTimeout(() => this.dispatchEvents(), 500);\r\n            }\r\n        }\r\n        dispatchEvents() {\r\n            if (this._disposed) {\r\n                return;\r\n            }\r\n            this._pending = false;\r\n            let map = this._cache;\r\n            this._cache = {};\r\n            for (let name in map) {\r\n                let state = map[name];\r\n                this._dispatcher.dispatch(name, state);\r\n                this._dispatcher.dispatch(FileWatcher.ANY, state);\r\n            }\r\n            this._dispatcher.dispatch(FileWatcher.CHANGED, map);\r\n        }\r\n    }\r\n    exports.FileWatcher = FileWatcher;\r\n    FileWatcher.ANY = \"* ANY\";\r\n    FileWatcher.CHANGED = \"* CHANGED\";\r\n});\r\ndefine(\"plover/editor/js_console\", [\"require\", \"exports\", \"UnityEditor\", \"UnityEngine\", \"plover/editor/auto_completion_field\"], function (require, exports, UnityEditor_4, UnityEngine_6, auto_completion_field_1) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.JSConsole = exports.fillAutoCompletion = void 0;\r\n    function fillAutoCompletion(scope, pattern) {\r\n        let result = [];\r\n        if (typeof pattern !== \"string\") {\r\n            return result;\r\n        }\r\n        let head = '';\r\n        pattern.replace(/\\\\W*([\\\\w\\\\.]+)$/, (a, b, c) => {\r\n            head = pattern.substr(0, c + a.length - b.length);\r\n            pattern = b;\r\n            return b;\r\n        });\r\n        let index = pattern.lastIndexOf('.');\r\n        let left = '';\r\n        if (index >= 0) {\r\n            left = pattern.substr(0, index + 1);\r\n            try {\r\n                scope = eval(pattern.substr(0, index));\r\n            }\r\n            catch (e) {\r\n                scope = null;\r\n            }\r\n            pattern = pattern.substr(index + 1);\r\n        }\r\n        for (let k in scope) {\r\n            if (k.indexOf(pattern) == 0) {\r\n                result.push(head + left + k);\r\n            }\r\n        }\r\n        return result;\r\n    }\r\n    exports.fillAutoCompletion = fillAutoCompletion;\r\n    class JSConsole extends UnityEditor_4.EditorWindow {\r\n        constructor() {\r\n            super(...arguments);\r\n            this._searchField = new auto_completion_field_1.AutoCompletionField();\r\n            this._history = [];\r\n        }\r\n        Awake() {\r\n            this._searchField.on(\"change\", this, this.onSearchChange);\r\n            this._searchField.on(\"confirm\", this, this.onSearchConfirm);\r\n        }\r\n        onSearchChange(s) {\r\n            this._searchField.clearResults();\r\n            fillAutoCompletion(globalThis, s).forEach(element => {\r\n                if (element != s) {\r\n                    this._searchField.addResult(element);\r\n                }\r\n            });\r\n        }\r\n        onSearchConfirm(s) {\r\n            console.log(\"confirm:\", s);\r\n        }\r\n        OnEnable() {\r\n            this.titleContent = new UnityEngine_6.GUIContent(\"Javascript Console\");\r\n        }\r\n        OnGUI() {\r\n            let evt = UnityEngine_6.Event.current;\r\n            this._searchField.onGUI();\r\n            if (evt.type == UnityEngine_6.EventType.KeyUp) {\r\n                switch (evt.keyCode) {\r\n                    case UnityEngine_6.KeyCode.Return: {\r\n                        let code = this._searchField.searchString;\r\n                        if (code != null && code.length > 0) {\r\n                            try {\r\n                                let rval = eval(code);\r\n                                console.log(JSON.stringify(rval));\r\n                            }\r\n                            catch (e) {\r\n                                console.error(e);\r\n                            }\r\n                            // this._history.push(code);\r\n                        }\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n            // GUI.Box(new Rect(0, 50, 300, 100), this._history.join(\"\\n\"));\r\n        }\r\n    }\r\n    exports.JSConsole = JSConsole;\r\n});\r\ndefine(\"plover/text/string_utils\", [\"require\", \"exports\", \"jsb\"], function (require, exports, jsb) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.StringUtil = exports.Contextual = exports.TEXT = exports.DefaultMatcher = void 0;\r\n    exports.DefaultMatcher = /\\$\\{([^\\{^\\}]+)\\}/g;\r\n    let _stringCache = new Set();\r\n    function TEXT(s) {\r\n        if (!_stringCache.has(s)) {\r\n            _stringCache.add(s);\r\n            jsb.AddCacheString(s);\r\n        }\r\n        return s;\r\n    }\r\n    exports.TEXT = TEXT;\r\n    /**\r\n     * 按一个上下文对象替换字符串中相应的关键字匹配串\r\n     */\r\n    class Contextual {\r\n        constructor(re = exports.DefaultMatcher) {\r\n            this.re = re;\r\n        }\r\n        /**\r\n         * 绑定一个上下文对象 （通常是一个map）\r\n         */\r\n        bind(context) {\r\n            this.context = context;\r\n            return this;\r\n        }\r\n        /**\r\n         * 替换字符串匹配串 (可以传入上下文，否则使用绑定的)\r\n         * context 可以是一个支持嵌套数据的map, 也可以是一个处理函数.\r\n         * 当使用处理函数时, 参数为取值key字符串.\r\n         */\r\n        replace(text, context) {\r\n            return text.replace(this.re, substring => {\r\n                let variable = substring.substring(2, substring.length - 1);\r\n                let ctx = context || this.context;\r\n                if (typeof ctx == \"function\") {\r\n                    return ctx(variable);\r\n                }\r\n                else {\r\n                    let elements = variable.split(\".\");\r\n                    for (let i = 0; i < elements.length; i++) {\r\n                        let element = elements[i];\r\n                        ctx = ctx[element];\r\n                    }\r\n                    return ctx;\r\n                }\r\n            });\r\n        }\r\n        /**\r\n         * let data = {\r\n         *     name: \"test\",\r\n         *     company: {\r\n         *         name: \"unity\",\r\n         *     },\r\n         * }\r\n         * let x = Contextual.replace(\"hello, mm: ${name} ${company.name}\", data)\r\n         * console.log(x);\r\n         */\r\n        static replace(text, context, re = exports.DefaultMatcher) {\r\n            return new Contextual(re).replace(text, context);\r\n        }\r\n    }\r\n    exports.Contextual = Contextual;\r\n    class StringUtil {\r\n        /**\r\n         * 替换字符串中的字串\r\n         * @param oldString 原字符串\r\n         * @param matchString 匹配字串\r\n         * @param replaceString 替换字串\r\n         * @returns 替换后的字符串\r\n         */\r\n        static replaceAll(oldString, matchString, replaceString) {\r\n            return oldString.replace(new RegExp(matchString, \"g\"), replaceString);\r\n        }\r\n        static contains(str, match) {\r\n            return str.search(new RegExp(match, \"i\")) > 0;\r\n        }\r\n        /**\r\n         * 数字 => 前缀0固定长度字符串\r\n         */\r\n        static prefix(num, length) {\r\n            let n = num.toString();\r\n            let p = length - n.length;\r\n            if (p <= 0) {\r\n                return n;\r\n            }\r\n            return Array(p + 1).join('0') + n;\r\n        }\r\n        /**\r\n         * 转换为固定小数和整数部分长度的字符串\r\n         */\r\n        static prefix2(num, length1, length2) {\r\n            let p = num.toString().split(\".\");\r\n            if (p.length == 1) {\r\n                return StringUtil.prefix(p[0], length1) + \".\" + StringUtil.prefix(0, length2);\r\n            }\r\n            return StringUtil.prefix(p[0], length1) + \".\" + StringUtil.prefix(p[1].substring(0, length2), length2);\r\n        }\r\n        /**\r\n         * 简单字符串表示的时长 (mm:ss.mmm)\r\n         */\r\n        static time(deltaTime) {\r\n            let nmsec = deltaTime % 999;\r\n            let fsec = Math.floor(deltaTime / 1000);\r\n            let nsec = fsec % 60;\r\n            let fmin = Math.floor(fsec / 60);\r\n            let text = fmin < 10 ? \"0\" + fmin : fmin.toString();\r\n            text += nsec < 10 ? \":0\" + nsec : \":\" + nsec;\r\n            text += nmsec < 10 ? \".00\" + nmsec : (nmsec < 100 ? \".0\" + nmsec : \".\" + nmsec);\r\n            return text;\r\n        }\r\n    }\r\n    exports.StringUtil = StringUtil;\r\n});\r\ndefine(\"plover/editor/base/menu_builder\", [\"require\", \"exports\", \"UnityEditor\", \"UnityEngine\"], function (require, exports, UnityEditor_5, UnityEngine_7) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.MenuBuilder = exports.MenuDisabledAction = exports.MenuAction = exports.MenuSeparator = exports.MenuAbstractItem = void 0;\r\n    class MenuAbstractItem {\r\n        constructor(name) {\r\n            this._name = name;\r\n        }\r\n        get name() { return this._name; }\r\n    }\r\n    exports.MenuAbstractItem = MenuAbstractItem;\r\n    class MenuSeparator extends MenuAbstractItem {\r\n        build(menu) {\r\n            menu.AddSeparator(this.name);\r\n        }\r\n    }\r\n    exports.MenuSeparator = MenuSeparator;\r\n    class MenuAction extends MenuAbstractItem {\r\n        constructor(name, action) {\r\n            super(name);\r\n            this._action = action;\r\n        }\r\n        get action() { return this._action; }\r\n        build(menu) {\r\n            let content = new UnityEngine_7.GUIContent(this.name);\r\n            menu.AddItem(content, false, () => this._action());\r\n        }\r\n    }\r\n    exports.MenuAction = MenuAction;\r\n    class MenuDisabledAction extends MenuAbstractItem {\r\n        constructor(name) {\r\n            super(name);\r\n        }\r\n        build(menu) {\r\n            let content = new UnityEngine_7.GUIContent(this.name);\r\n            menu.AddDisabledItem(content, false);\r\n        }\r\n    }\r\n    exports.MenuDisabledAction = MenuDisabledAction;\r\n    class MenuBuilder {\r\n        constructor() {\r\n            this._items = [];\r\n        }\r\n        addAction(name, action, isDisabled = false) {\r\n            if (isDisabled) {\r\n                return this.addDisabledAction(name);\r\n            }\r\n            this._items.push(new MenuAction(name, action));\r\n        }\r\n        addDisabledAction(name) {\r\n            this._items.push(new MenuDisabledAction(name));\r\n        }\r\n        addSeperator() {\r\n            this._items.push(new MenuSeparator(\"\"));\r\n        }\r\n        build() {\r\n            let count = this._items.length;\r\n            if (count > 0) {\r\n                let menu = new UnityEditor_5.GenericMenu();\r\n                for (let i = 0; i < count; i++) {\r\n                    let item = this._items[i];\r\n                    item.build(menu);\r\n                }\r\n                return menu;\r\n            }\r\n            return null;\r\n        }\r\n    }\r\n    exports.MenuBuilder = MenuBuilder;\r\n});\r\ndefine(\"plover/editor/base/splitview\", [\"require\", \"exports\", \"UnityEditor\", \"UnityEngine\"], function (require, exports, UnityEditor_6, UnityEngine_8) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.HSplitView = void 0;\r\n    class HSplitView {\r\n        constructor() {\r\n            this.init = false; // 是否初始化\r\n            this.splitPivot = 0;\r\n            this.resize = false;\r\n            this.cursorChangeRect = UnityEngine_8.Rect.zero;\r\n            this.cursorHintRect = UnityEngine_8.Rect.zero;\r\n            this.cursorHintSize = 2;\r\n            this.cursorSize = 6;\r\n            this.cursorHintColor = new UnityEngine_8.Color(0, 0, 0, 0.25);\r\n        }\r\n        draw(window, startY, fullWidth, fullHeight) {\r\n            if (!this.init) {\r\n                this.init = true;\r\n                this.splitPivot = Math.min(Math.max(fullWidth * .25, 10), fullWidth - 10);\r\n                this.cursorChangeRect.Set(this.splitPivot - 2, startY, this.cursorSize, fullHeight);\r\n                this.cursorHintRect.Set(this.splitPivot - 2, startY, this.cursorHintSize, fullHeight);\r\n            }\r\n            else {\r\n                this.cursorChangeRect.height = fullHeight;\r\n                this.cursorHintRect.height = fullHeight;\r\n            }\r\n            UnityEditor_6.EditorGUI.DrawRect(this.cursorHintRect, this.cursorHintColor);\r\n            UnityEditor_6.EditorGUIUtility.AddCursorRect(this.cursorChangeRect, UnityEditor_6.MouseCursor.ResizeHorizontal);\r\n            if (UnityEngine_8.Event.current.type == UnityEngine_8.EventType.MouseDown && this.cursorChangeRect.Contains(UnityEngine_8.Event.current.mousePosition)) {\r\n                this.resize = true;\r\n            }\r\n            if (this.resize) {\r\n                let y = this.cursorChangeRect.y;\r\n                let h = this.cursorChangeRect.height;\r\n                this.splitPivot = Math.min(Math.max(UnityEngine_8.Event.current.mousePosition.x, 10), fullWidth - 10);\r\n                this.cursorChangeRect.Set(this.splitPivot - 2, y, this.cursorSize, h);\r\n                this.cursorHintRect.Set(this.splitPivot - 2, y, this.cursorHintSize, h);\r\n                window.Repaint();\r\n            }\r\n            if (UnityEngine_8.Event.current.type == UnityEngine_8.EventType.MouseUp) {\r\n                this.resize = false;\r\n            }\r\n        }\r\n    }\r\n    exports.HSplitView = HSplitView;\r\n});\r\ndefine(\"plover/editor/base/treeview\", [\"require\", \"exports\", \"UnityEditor\", \"UnityEngine\", \"plover/events/dispatcher\", \"plover/editor/base/treenode\"], function (require, exports, UnityEditor_7, UnityEngine_9, dispatcher_3, treenode_1) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.UTreeView = void 0;\r\n    class UTreeView {\r\n        constructor(handler) {\r\n            this.SKIP_RETURN = 0;\r\n            this._eventUsed = false;\r\n            this._skipReturn = 0;\r\n            this._indentSize = 16;\r\n            this._rowRect = UnityEngine_9.Rect.zero;\r\n            this._indentRect = UnityEngine_9.Rect.zero;\r\n            this._tempRect = UnityEngine_9.Rect.zero;\r\n            this._editing = false;\r\n            this._deferredMenuPopup = false;\r\n            this._selectionColor = new UnityEngine_9.Color(44 / 255, 93 / 255, 135 / 255);\r\n            this._rowColor = new UnityEngine_9.Color(0.5, 0.5, 0.5, 0.1);\r\n            this._focusColor = new UnityEngine_9.Color(58 / 255, 121 / 255, 187 / 255);\r\n            this._debug_touchChild = 0;\r\n            this._debug_drawChild = 0;\r\n            this._searchString = \"\";\r\n            this._handler = handler;\r\n            this._root = new treenode_1.UTreeNode(this, null, true, \"/\");\r\n            this._root.isEditable = false;\r\n            this._root.isSearchable = false;\r\n            this._root.expanded = true;\r\n        }\r\n        get selected() { return this._selected; }\r\n        set selected(value) {\r\n            var _a;\r\n            if (this._selected != value) {\r\n                (_a = this._selected) === null || _a === void 0 ? void 0 : _a.endEdit();\r\n                this._editing = false;\r\n                this._skipReturn = 0;\r\n                this._selected = value;\r\n            }\r\n        }\r\n        get searchString() { return this._searchString; }\r\n        set searchString(value) { this.search(value); }\r\n        get root() {\r\n            return this._root;\r\n        }\r\n        get handler() { return this._handler; }\r\n        set handler(value) { this._handler = value; }\r\n        on(evt, caller, fn) {\r\n            if (!this._events) {\r\n                this._events = new dispatcher_3.EventDispatcher();\r\n            }\r\n            this._events.on(evt, caller, fn);\r\n        }\r\n        off(evt, caller, fn) {\r\n            if (this._events) {\r\n                this._events.off(evt, caller, fn);\r\n            }\r\n        }\r\n        dispatch(name, arg0, arg1, arg2) {\r\n            if (!this._events) {\r\n                this._events = new dispatcher_3.EventDispatcher();\r\n            }\r\n            this._events.dispatch(name, arg0, arg1, arg2);\r\n        }\r\n        allocFolderHierarchy(path, data) {\r\n            return this._getFolderHierarchy(path, data);\r\n        }\r\n        getFolderHierarchy(path) {\r\n            return this._getFolderHierarchy(path, null);\r\n        }\r\n        _getFolderHierarchy(path, data) {\r\n            if (path.startsWith(\"/\")) {\r\n                path = path.substring(1);\r\n            }\r\n            let node = this._root;\r\n            if (path.length > 0) {\r\n                let hierarchy = path.split(\"/\");\r\n                for (let i = 0; i < hierarchy.length; i++) {\r\n                    node = node.getFolderByName(hierarchy[i], true, data);\r\n                }\r\n            }\r\n            return node;\r\n        }\r\n        removeAll() {\r\n            this._root.removeAll();\r\n            this.selected = null;\r\n        }\r\n        deleteNode(node) {\r\n            if (node && this._selected == node && node.parent) {\r\n                this._selected = this.findNextNode(node) || this.findPreviousNode(node);\r\n                return node.parent.removeChild(node);\r\n            }\r\n            return false;\r\n        }\r\n        search(p) {\r\n            if (p == null) {\r\n                p = \"\";\r\n            }\r\n            if (this._searchString != p) {\r\n                this._searchString = p;\r\n                this._search(this._root);\r\n            }\r\n        }\r\n        _search(node) {\r\n            node.match(this._searchString);\r\n            for (let i = 0, count = node.childCount; i < count; i++) {\r\n                this._search(node.getChildByIndex(i));\r\n            }\r\n        }\r\n        expandAll() { this._root.expandAll(); }\r\n        collapseAll() { this._root.collapseAll(); }\r\n        draw(offsetX, offsetY, width, height) {\r\n            var _a;\r\n            let repaint = false;\r\n            let cEvent = UnityEngine_9.Event.current;\r\n            if (this._deferredMenuPopup) {\r\n                this._deferredMenuPopup = false;\r\n                if (this._selected) {\r\n                    this._selected.drawMenu(this, cEvent.mousePosition, this._handler);\r\n                    repaint = true;\r\n                }\r\n            }\r\n            this._debug_touchChild = 0;\r\n            this._debug_drawChild = 0;\r\n            this._eventUsed = false;\r\n            this._height = 0;\r\n            this._drawY = 0;\r\n            this._rowIndex = 0;\r\n            if (this._searchString == null || this._searchString.length == 0) {\r\n                this.calcRowHeight(this._root);\r\n                this.setControlRect(cEvent);\r\n                this.drawRow(this._root, 0, offsetY, height);\r\n            }\r\n            else {\r\n                this.calcSearchResultsHeight(this._root);\r\n                this.setControlRect(cEvent);\r\n                this.drawSearchResults(this._root, 0, offsetY, height);\r\n            }\r\n            if (this._controlID == UnityEngine_9.GUIUtility.keyboardControl) {\r\n                this._tempRect.Set(0, 0, 1, height);\r\n                UnityEditor_7.EditorGUI.DrawRect(this._tempRect, this._focusColor);\r\n            }\r\n            if (cEvent.isKey) {\r\n                let eventType = cEvent.type;\r\n                if (this._editing) {\r\n                    switch (eventType) {\r\n                        case UnityEngine_9.EventType.KeyUp:\r\n                            {\r\n                                let keyCode = cEvent.keyCode;\r\n                                if (keyCode == UnityEngine_9.KeyCode.Return) {\r\n                                    if (this._skipReturn > 0) {\r\n                                        this._skipReturn--;\r\n                                        this.useEvent();\r\n                                    }\r\n                                    else {\r\n                                        UnityEngine_9.GUI.FocusControl(null);\r\n                                        UnityEngine_9.GUIUtility.keyboardControl = this._controlID;\r\n                                        (_a = this._selected) === null || _a === void 0 ? void 0 : _a.endEdit();\r\n                                        this._editing = false;\r\n                                        this._skipReturn = 0;\r\n                                        this.useEvent();\r\n                                    }\r\n                                }\r\n                            }\r\n                            break;\r\n                    }\r\n                }\r\n                else {\r\n                    if (this._selected && this._controlEventType == UnityEngine_9.EventType.KeyUp && this._controlID == UnityEngine_9.GUIUtility.keyboardControl) {\r\n                        // console.log(GUIUtility.keyboardControl, this._controlID);\r\n                        let keyCode = cEvent.keyCode;\r\n                        if (keyCode == UnityEngine_9.KeyCode.Return) {\r\n                            if (this._selected.isEditable) {\r\n                                this._editing = true;\r\n                                this._skipReturn = this.SKIP_RETURN;\r\n                                this.useEvent();\r\n                            }\r\n                        }\r\n                        else {\r\n                            if (keyCode == UnityEngine_9.KeyCode.UpArrow) {\r\n                                if (this._selected.parent) {\r\n                                    let sibling = this.findPreviousNode(this._selected);\r\n                                    if (sibling) {\r\n                                        this._selected = sibling;\r\n                                        this._selected.expandUp();\r\n                                        this.useEvent();\r\n                                    }\r\n                                }\r\n                            }\r\n                            else if (keyCode == UnityEngine_9.KeyCode.DownArrow) {\r\n                                let sibling = this.findNextNode(this._selected);\r\n                                if (sibling) {\r\n                                    this._selected = sibling;\r\n                                    this._selected.expandUp();\r\n                                    this.useEvent();\r\n                                }\r\n                            }\r\n                            else if (keyCode == UnityEngine_9.KeyCode.LeftArrow) {\r\n                                if (this._selected.expanded && this._selected.isFolder) {\r\n                                    this._selected.expanded = false;\r\n                                    this._selected.expandUp();\r\n                                }\r\n                                else if (this._selected.parent) {\r\n                                    this._selected = this._selected.parent;\r\n                                    this._selected.expandUp();\r\n                                }\r\n                                this.useEvent();\r\n                            }\r\n                            else if (keyCode == UnityEngine_9.KeyCode.RightArrow) {\r\n                                this._selected.expanded = true;\r\n                                this._selected.expandUp();\r\n                                this.useEvent();\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n            else {\r\n                if (!this._editing && this._controlEventType == UnityEngine_9.EventType.MouseUp) {\r\n                    this._tempRect.Set(0, 0, width, height);\r\n                    if (this._tempRect.Contains(this._controlMousePos)) {\r\n                        UnityEngine_9.GUIUtility.keyboardControl = this._controlID;\r\n                        repaint = true;\r\n                    }\r\n                }\r\n            }\r\n            return this._deferredMenuPopup || repaint;\r\n        }\r\n        calcRowHeight(node) {\r\n            this._height += node.calcRowHeight();\r\n            if (node.expanded) {\r\n                for (let i = 0, count = node.childCount; i < count; i++) {\r\n                    this.calcRowHeight(node.getChildByIndex(i));\r\n                }\r\n            }\r\n        }\r\n        calcSearchResultsHeight(node) {\r\n            if (node.isMatch) {\r\n                this._height += node.calcRowHeight();\r\n            }\r\n            for (let i = 0, count = node.childCount; i < count; i++) {\r\n                this.calcRowHeight(node.getChildByIndex(i));\r\n            }\r\n        }\r\n        setControlRect(cEvent) {\r\n            this._controlRect = UnityEditor_7.EditorGUILayout.GetControlRect(false, this._height, UnityEngine_9.GUILayout.MinWidth(160));\r\n            this._controlID = UnityEngine_9.GUIUtility.GetControlID(UnityEngine_9.FocusType.Keyboard, this._controlRect);\r\n            this._controlEventType = cEvent.GetTypeForControl(this._controlID);\r\n            if (this._controlEventType == UnityEngine_9.EventType.MouseUp) {\r\n                this._controlMousePos = cEvent.mousePosition;\r\n            }\r\n        }\r\n        useEvent() {\r\n            this._eventUsed = true;\r\n            UnityEngine_9.GUI.changed = true;\r\n            UnityEngine_9.Event.current.Use();\r\n        }\r\n        drawSearchResults(node, depth, offsetY, height) {\r\n            let drawY = this._drawY;\r\n            if (node.isMatch) {\r\n                this._drawY += node.height;\r\n                ++this._rowIndex;\r\n                ++this._debug_touchChild;\r\n                if ((this._drawY - offsetY) > 0 && (drawY - offsetY) < height) {\r\n                    let rowIndent = 0;\r\n                    let baseX = 14;\r\n                    let bSelected = this._selected == node;\r\n                    ++this._debug_drawChild;\r\n                    this._rowRect.Set(this._controlRect.x, this._controlRect.y + drawY, this._controlRect.width, node.height);\r\n                    this._indentRect.Set(this._controlRect.x + baseX + rowIndent, this._rowRect.y, this._controlRect.width - rowIndent, node.height);\r\n                    if (bSelected) {\r\n                        UnityEditor_7.EditorGUI.DrawRect(this._rowRect, this._selectionColor);\r\n                    }\r\n                    else if (this._rowIndex % 2) {\r\n                        UnityEditor_7.EditorGUI.DrawRect(this._rowRect, this._rowColor);\r\n                    }\r\n                    node.draw(this._indentRect, bSelected, bSelected && this._editing, this._indentSize);\r\n                    if (this._controlEventType == UnityEngine_9.EventType.MouseUp) {\r\n                        if (this._rowRect.Contains(this._controlMousePos)) {\r\n                            if (UnityEngine_9.Event.current.button == 1) {\r\n                                if (this._selected == node) {\r\n                                    node.drawMenu(this, this._controlMousePos, this._handler);\r\n                                    this.useEvent();\r\n                                }\r\n                                else {\r\n                                    this.selected = node;\r\n                                    if (!this._editing) {\r\n                                        this._deferredMenuPopup = true;\r\n                                    }\r\n                                    this.useEvent();\r\n                                }\r\n                            }\r\n                            else if (UnityEngine_9.Event.current.button == 0) {\r\n                                if (node.isFolder && node._foldoutRect.Contains(this._controlMousePos)) {\r\n                                    node.expanded = !node.expanded;\r\n                                }\r\n                                else {\r\n                                    this.selected = node;\r\n                                }\r\n                                this.useEvent();\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n            for (let i = 0, count = node.childCount; i < count; i++) {\r\n                this.drawSearchResults(node.getChildByIndex(i), depth + 1, offsetY, height);\r\n            }\r\n        }\r\n        drawRow(node, depth, offsetY, height) {\r\n            let drawY = this._drawY;\r\n            this._drawY += node.height;\r\n            ++this._rowIndex;\r\n            ++this._debug_touchChild;\r\n            if ((this._drawY - offsetY) > 0 && (drawY - offsetY) < height) {\r\n                let rowIndent = this._indentSize * depth;\r\n                let baseX = 14;\r\n                let bSelected = this._selected == node;\r\n                ++this._debug_drawChild;\r\n                this._rowRect.Set(this._controlRect.x, this._controlRect.y + drawY, this._controlRect.width, node.height);\r\n                this._indentRect.Set(this._controlRect.x + baseX + rowIndent, this._rowRect.y, this._controlRect.width - rowIndent, node.height);\r\n                if (bSelected) {\r\n                    UnityEditor_7.EditorGUI.DrawRect(this._rowRect, this._selectionColor);\r\n                }\r\n                else if (this._rowIndex % 2) {\r\n                    UnityEditor_7.EditorGUI.DrawRect(this._rowRect, this._rowColor);\r\n                }\r\n                node.draw(this._indentRect, bSelected, bSelected && this._editing, this._indentSize);\r\n                if (this._controlEventType == UnityEngine_9.EventType.MouseUp) {\r\n                    if (this._rowRect.Contains(this._controlMousePos)) {\r\n                        if (UnityEngine_9.Event.current.button == 1) {\r\n                            if (this._selected == node) {\r\n                                node.drawMenu(this, this._controlMousePos, this._handler);\r\n                                this.useEvent();\r\n                            }\r\n                            else {\r\n                                this.selected = node;\r\n                                if (!this._editing) {\r\n                                    this._deferredMenuPopup = true;\r\n                                }\r\n                                this.useEvent();\r\n                            }\r\n                        }\r\n                        else if (UnityEngine_9.Event.current.button == 0) {\r\n                            if (node.isFolder && node._foldoutRect.Contains(this._controlMousePos)) {\r\n                                node.expanded = !node.expanded;\r\n                            }\r\n                            else {\r\n                                this.selected = node;\r\n                            }\r\n                            this.useEvent();\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n            else {\r\n                node.visible = false;\r\n            }\r\n            if (node.expanded) {\r\n                for (let i = 0, count = node.childCount; i < count; i++) {\r\n                    this.drawRow(node.getChildByIndex(i), depth + 1, offsetY, height);\r\n                    // if (this._drawLine && i == count - 1) {\r\n                    //     this._point.Set(child._lineStart.x, node._lineStart.y, 0);\r\n                    //     // Handles.DrawDottedLine(this._point, child._lineStartIn, 1);\r\n                    //     Handles.color = Color.gray;\r\n                    //     Handles.DrawLine(this._point, child._lineStartIn);\r\n                    // }\r\n                }\r\n            }\r\n        }\r\n        findPreviousNode(node) {\r\n            let sibling = node.parent.findLastSibling(node);\r\n            while (sibling && sibling.expanded && sibling.childCount > 0) {\r\n                sibling = sibling.getLastChild();\r\n            }\r\n            return sibling || node.parent;\r\n        }\r\n        findNextNode(node) {\r\n            if (node.expanded && node.childCount > 0) {\r\n                return node.getFirstChild();\r\n            }\r\n            while (node.parent) {\r\n                let sibling = node.parent.findNextSibling(node);\r\n                if (sibling) {\r\n                    return sibling;\r\n                }\r\n                node = node.parent;\r\n            }\r\n            return null;\r\n        }\r\n    }\r\n    exports.UTreeView = UTreeView;\r\n    UTreeView.CONTEXT_MENU = \"CONTEXT_MENU\";\r\n});\r\ndefine(\"plover/editor/base/treenode\", [\"require\", \"exports\", \"QuickJS.Unity\", \"UnityEditor\", \"UnityEngine\", \"plover/events/dispatcher\", \"plover/editor/base/menu_builder\", \"plover/editor/base/treeview\"], function (require, exports, QuickJS_Unity_1, UnityEditor_8, UnityEngine_10, dispatcher_4, menu_builder_1, treeview_1) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.UTreeNode = exports.BuiltinIcons = void 0;\r\n    class BuiltinIcons {\r\n        static getIcon(name) {\r\n            let icon = BuiltinIcons._cache[name];\r\n            if (typeof icon === \"undefined\") {\r\n                icon = BuiltinIcons._cache[name] = QuickJS_Unity_1.UnityHelper.GetIcon(name);\r\n            }\r\n            return icon;\r\n        }\r\n    }\r\n    exports.BuiltinIcons = BuiltinIcons;\r\n    BuiltinIcons._cache = {};\r\n    class UTreeNode {\r\n        constructor(tree, parent, isFolder, name) {\r\n            this._children = null;\r\n            this._expanded = true;\r\n            this._name = \"noname\";\r\n            this.isSearchable = true;\r\n            this.isEditable = true;\r\n            // _lineStart = Vector3.zero;\r\n            // _lineStartIn = Vector3.zero;\r\n            // protected _lineEnd = Vector3.zero;\r\n            this._foldoutRect = UnityEngine_10.Rect.zero;\r\n            this._bFocusTextField = false;\r\n            this._bVisible = true;\r\n            this._height = 0;\r\n            this._bMatch = true;\r\n            this._name = name;\r\n            this._tree = tree;\r\n            this._parent = parent;\r\n            this._children = isFolder ? [] : null;\r\n        }\r\n        get isMatch() { return this._bMatch; }\r\n        get height() { return this._height; }\r\n        /**\r\n         * 当前层级是否展开\r\n         */\r\n        get expanded() { return this._expanded; }\r\n        set expanded(value) {\r\n            if (this._expanded != value) {\r\n                this._expanded = value;\r\n            }\r\n        }\r\n        get isFolder() { return !!this._children; }\r\n        get visible() { return this._bVisible; }\r\n        set visible(value) {\r\n            if (this._bVisible != value) {\r\n                this._bVisible = value;\r\n            }\r\n        }\r\n        get parent() { return this._parent; }\r\n        get isRoot() { return this._parent == null; }\r\n        get name() { return this._name; }\r\n        set name(value) {\r\n            if (this._name != value) {\r\n                let oldName = this._name;\r\n                this._name = value;\r\n                this._tree.handler.onTreeNodeNameChanged(this, oldName);\r\n            }\r\n        }\r\n        get fullPath() {\r\n            let path = this._name;\r\n            let node = this._parent;\r\n            while (node && !node.isRoot) {\r\n                if (node._name && node._name.length > 0) {\r\n                    path = node._name + \"/\" + path;\r\n                }\r\n                node = node._parent;\r\n            }\r\n            return path;\r\n        }\r\n        get treeView() { return this._tree; }\r\n        get childCount() { return this._children ? this._children.length : 0; }\r\n        on(evt, caller, fn) {\r\n            if (!this._events) {\r\n                this._events = new dispatcher_4.EventDispatcher();\r\n            }\r\n            this._events.on(evt, caller, fn);\r\n        }\r\n        off(evt, caller, fn) {\r\n            if (this._events) {\r\n                this._events.off(evt, caller, fn);\r\n            }\r\n        }\r\n        dispatch(name, arg0, arg1, arg2) {\r\n            if (!this._events) {\r\n                this._events = new dispatcher_4.EventDispatcher();\r\n            }\r\n            this._events.dispatch(name, arg0, arg1, arg2);\r\n        }\r\n        match(p) {\r\n            if (p == null || p.length == 0) {\r\n                return this._bMatch = true;\r\n            }\r\n            return this._bMatch = this.isSearchable && this._name.indexOf(p) >= 0;\r\n        }\r\n        getRelativePath(top) {\r\n            let path = this._name;\r\n            let node = this._parent;\r\n            while (node && node != top) {\r\n                path = node._name + \"/\" + path;\r\n                node = node._parent;\r\n            }\r\n            return path;\r\n        }\r\n        expandAll() {\r\n            this._setExpandAll(true);\r\n        }\r\n        collapseAll() {\r\n            this._setExpandAll(false);\r\n        }\r\n        _setExpandAll(state) {\r\n            this._expanded = state;\r\n            if (this._children) {\r\n                for (let i = 0, count = this._children.length; i < count; i++) {\r\n                    this._children[i]._setExpandAll(state);\r\n                }\r\n            }\r\n        }\r\n        expandUp() {\r\n            let node = this._parent;\r\n            while (node) {\r\n                node.expanded = true;\r\n                node = node.parent;\r\n            }\r\n        }\r\n        /**\r\n         * 获取指定节点的在当前层级中的下一个相邻节点\r\n         */\r\n        findNextSibling(node) {\r\n            if (this._children) {\r\n                let index = this._children.indexOf(node);\r\n                if (index >= 0 && index < this._children.length - 1) {\r\n                    return this._children[index + 1];\r\n                }\r\n            }\r\n            return null;\r\n        }\r\n        /**\r\n         * 获取指定节点的在当前层级中的上一个相邻节点\r\n         */\r\n        findLastSibling(node) {\r\n            if (this._children) {\r\n                let index = this._children.indexOf(node);\r\n                if (index > 0) {\r\n                    return this._children[index - 1];\r\n                }\r\n            }\r\n            return null;\r\n        }\r\n        forEachChild(fn) {\r\n            if (this._children) {\r\n                for (let i = 0, count = this._children.length; i < count; i++) {\r\n                    fn(this._children[i]);\r\n                }\r\n            }\r\n        }\r\n        /**\r\n         * 获取当前层级下的子节点\r\n         * @param index 索引 或者 命名\r\n         * @param autoNew 不存在时是否创建 (仅通过命名获取时有效)\r\n         * @returns 子节点\r\n         */\r\n        getFolderByName(name, isAutoCreate, data) {\r\n            if (this._children) {\r\n                for (let i = 0, size = this._children.length; i < size; i++) {\r\n                    let child = this._children[i];\r\n                    if (child.isFolder && child.name == name) {\r\n                        return child;\r\n                    }\r\n                }\r\n                if (isAutoCreate) {\r\n                    let child = this._addChild(name, true, data);\r\n                    return child;\r\n                }\r\n            }\r\n            return null;\r\n        }\r\n        getLeafByName(name, isAutoCreate, data) {\r\n            if (this._children) {\r\n                for (let i = 0, size = this._children.length; i < size; i++) {\r\n                    let child = this._children[i];\r\n                    if (!child.isFolder && child.name == name) {\r\n                        return child;\r\n                    }\r\n                }\r\n                if (isAutoCreate) {\r\n                    let child = this._addChild(name, false, data);\r\n                    return child;\r\n                }\r\n            }\r\n            return null;\r\n        }\r\n        getChildByIndex(index) {\r\n            return this._children[index];\r\n        }\r\n        /**\r\n         * 当前层级最后一个子节点\r\n         */\r\n        getLastChild() {\r\n            return this._children && this._children.length > 0 ? this._children[this._children.length - 1] : null;\r\n        }\r\n        /**\r\n         * 当前层级第一个子节点\r\n         */\r\n        getFirstChild() {\r\n            return this._children && this._children.length > 0 ? this._children[0] : null;\r\n        }\r\n        addFolderChild(name) {\r\n            return this.getFolderByName(name, true, null);\r\n        }\r\n        addLeafChild(name) {\r\n            return this.getLeafByName(name, true, null);\r\n        }\r\n        allocLeafChild(name, data) {\r\n            return this.getLeafByName(name, true, data);\r\n        }\r\n        /**\r\n         * 在当前层级添加一个子节点\r\n         */\r\n        _addChild(name, isFolder, data) {\r\n            if (this._children) {\r\n                let node = new UTreeNode(this._tree, this, isFolder, name);\r\n                this._children.push(node);\r\n                node._expanded = true;\r\n                node.data = data;\r\n                this._tree.handler.onTreeNodeCreated(node);\r\n                return node;\r\n            }\r\n            return null;\r\n        }\r\n        /**\r\n         * 将一个子节点从当前层级中移除\r\n         */\r\n        removeChild(node) {\r\n            if (this._children) {\r\n                let index = this._children.indexOf(node);\r\n                if (index >= 0) {\r\n                    this._children.splice(index, 1);\r\n                    return true;\r\n                }\r\n            }\r\n            return false;\r\n        }\r\n        removeAll() {\r\n            if (this._children) {\r\n                this._children.splice(0);\r\n            }\r\n        }\r\n        calcRowHeight() {\r\n            this._height = UnityEditor_8.EditorGUIUtility.singleLineHeight;\r\n            return this._height;\r\n        }\r\n        drawMenu(treeView, pos, handler) {\r\n            let builder = new menu_builder_1.MenuBuilder();\r\n            handler.onTreeNodeContextMenu(this, builder);\r\n            treeView.dispatch(treeview_1.UTreeView.CONTEXT_MENU, builder, this);\r\n            let menu = builder.build();\r\n            if (menu) {\r\n                menu.ShowAsContext();\r\n            }\r\n        }\r\n        draw(rect, bSelected, bEditing, indentSize) {\r\n            // let lineY = rect.y + rect.height * 0.5;\r\n            // this._lineStartIn.Set(rect.x - indentSize * 1.5, lineY, 0);\r\n            // this._lineStart.Set(rect.x - indentSize * 1.5, rect.y + rect.height, 0);\r\n            this._bVisible = true;\r\n            if (this._children && this._children.length > 0) {\r\n                this._foldoutRect.Set(rect.x - 14, rect.y, 12, rect.height);\r\n                /*this._expanded =*/ UnityEditor_8.EditorGUI.Foldout(this._foldoutRect, this._expanded, UnityEngine_10.GUIContent.none);\r\n                // this._lineEnd.Set(rect.x - indentSize, lineY, 0);\r\n                let image = this._expanded ? BuiltinIcons.getIcon(\"FolderOpened\") : BuiltinIcons.getIcon(\"Folder\");\r\n                if (!this._label) {\r\n                    this._label = new UnityEngine_10.GUIContent(this._name, image);\r\n                }\r\n                else {\r\n                    this._label.image = image;\r\n                }\r\n            }\r\n            else {\r\n                // this._lineEnd.Set(rect.x - 4, lineY, 0);\r\n                if (!this._label) {\r\n                    this._label = new UnityEngine_10.GUIContent(this._name, BuiltinIcons.getIcon(\"JsScript\"));\r\n                }\r\n            }\r\n            // Handles.color = Color.gray;\r\n            // Handles.DrawLine(this._lineStartIn, this._lineEnd);\r\n            if (bEditing) {\r\n                let text;\r\n                if (this._bFocusTextField) {\r\n                    UnityEngine_10.GUI.SetNextControlName(\"TreeViewNode.Editing\");\r\n                    this._label.text = UnityEditor_8.EditorGUI.TextField(rect, this._label.text);\r\n                }\r\n                else {\r\n                    UnityEngine_10.GUI.SetNextControlName(\"TreeViewNode.Editing\");\r\n                    this._label.text = UnityEditor_8.EditorGUI.TextField(rect, this._label.text);\r\n                    UnityEngine_10.GUI.FocusControl(\"TreeViewNode.Editing\");\r\n                }\r\n            }\r\n            else {\r\n                this._bFocusTextField = false;\r\n                UnityEditor_8.EditorGUI.LabelField(rect, this._label, bSelected ? UnityEditor_8.EditorStyles.whiteLabel : UnityEditor_8.EditorStyles.label);\r\n            }\r\n        }\r\n        endEdit() {\r\n            if (this._label.text != this._name) {\r\n                this._tree.handler.onTreeNodeNameEditEnded(this, this._label.text);\r\n            }\r\n        }\r\n    }\r\n    exports.UTreeNode = UTreeNode;\r\n});\r\ndefine(\"plover/editor/base/breadcrumb\", [\"require\", \"exports\", \"UnityEditor\", \"UnityEngine\", \"jsb\", \"plover/events/dispatcher\"], function (require, exports, UnityEditor_9, UnityEngine_11, jsb, dispatcher_5) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.Breadcrumb = void 0;\r\n    class Breadcrumb extends dispatcher_5.EventDispatcher {\r\n        constructor() {\r\n            super();\r\n            this._cache = [];\r\n            this._color = new UnityEngine_11.Color(1, 1, 1, 0);\r\n            this._sv = UnityEngine_11.Vector2.zero;\r\n            jsb.AddCacheString(\">\");\r\n            this._height = UnityEditor_9.EditorGUIUtility.singleLineHeight + 14;\r\n            this._heightOptionSV = UnityEngine_11.GUILayout.Height(this._height);\r\n            this._heightOptionHB = UnityEngine_11.GUILayout.Height(this._height - 6);\r\n        }\r\n        get height() { return this._height; }\r\n        draw(node) {\r\n            if (!node || !node.parent) {\r\n                return;\r\n            }\r\n            let count = 0;\r\n            while (node.parent) {\r\n                this._cache[count++] = node;\r\n                node = node.parent;\r\n            }\r\n            this._sv = UnityEditor_9.EditorGUILayout.BeginScrollView(this._sv, this._heightOptionSV);\r\n            UnityEngine_11.GUILayout.BeginHorizontal(this._heightOptionHB);\r\n            let color = UnityEngine_11.GUI.backgroundColor;\r\n            UnityEngine_11.GUI.backgroundColor = this._color;\r\n            for (let i = count - 1; i >= 0; --i) {\r\n                let item = this._cache[i];\r\n                if (UnityEngine_11.GUILayout.Button(item.name, UnityEngine_11.GUILayout.ExpandWidth(false))) {\r\n                    this.dispatch(Breadcrumb.CLICKED, item, false);\r\n                }\r\n                if (i != 0) {\r\n                    // GUILayout.Label(\">\", GUILayout.ExpandWidth(false));\r\n                    if (UnityEngine_11.GUILayout.Button(\">\", UnityEngine_11.GUILayout.ExpandWidth(false))) {\r\n                        this.dispatch(Breadcrumb.CLICKED, item, true);\r\n                    }\r\n                    // let rect = EditorGUILayout.GetControlRect(GUILayout.Width(10));\r\n                    // EditorGUI.DrawRect(rect, Color.yellow);\r\n                }\r\n                this._cache[i] = null;\r\n            }\r\n            UnityEngine_11.GUI.backgroundColor = color;\r\n            UnityEngine_11.GUILayout.EndHorizontal();\r\n            UnityEditor_9.EditorGUILayout.EndScrollView();\r\n        }\r\n    }\r\n    exports.Breadcrumb = Breadcrumb;\r\n    Breadcrumb.CLICKED = \"CLICKED\";\r\n});\r\ndefine(\"plover/editor/base/editor_window_base\", [\"require\", \"exports\", \"UnityEditor\", \"UnityEngine\", \"plover/editor/base/menu_builder\", \"plover/editor/base/splitview\", \"plover/editor/base/treenode\", \"plover/editor/base/treeview\", \"jsb\", \"plover/text/string_utils\", \"plover/editor/base/breadcrumb\"], function (require, exports, UnityEditor_10, UnityEngine_12, menu_builder_2, splitview_1, treenode_2, treeview_2, jsb, string_utils_1, breadcrumb_1) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.EditorWindowBase = void 0;\r\n    class EditorWindowBase extends UnityEditor_10.EditorWindow {\r\n        constructor() {\r\n            super(...arguments);\r\n            this._treeViewScroll = UnityEngine_12.Vector2.zero;\r\n            this._toolbarRect = UnityEngine_12.Rect.zero;\r\n            this._leftRect = UnityEngine_12.Rect.zero;\r\n            this._rightRect = UnityEngine_12.Rect.zero;\r\n            // protected _topSplitLine = Rect.zero;\r\n            this._searchLabel = new UnityEngine_12.GUIContent(\"Search\");\r\n            this._tempRect = UnityEngine_12.Rect.zero;\r\n            this._contents = {};\r\n            this.toobarHeight = 24;\r\n        }\r\n        onTreeNodeNameEditEnded(node, newName) {\r\n            if (node.isRoot || !node.data) {\r\n                return;\r\n            }\r\n            node.name = newName;\r\n        }\r\n        onTreeNodeNameChanged(node, oldName) {\r\n            if (node.isRoot || !node.data) {\r\n                return;\r\n            }\r\n        }\r\n        onTreeNodeCreated(node) {\r\n            if (node.data) {\r\n                return;\r\n            }\r\n        }\r\n        onTreeNodeContextMenu(node, builder) {\r\n            if (!node.isRoot) {\r\n            }\r\n        }\r\n        buildBreadcrumbMenu(top, node, builder) {\r\n            node.forEachChild(child => {\r\n                let relativePath = child.getRelativePath(top);\r\n                builder.addAction(relativePath, () => {\r\n                    this._treeView.selected = child;\r\n                });\r\n                this.buildBreadcrumbMenu(top, child, builder);\r\n            });\r\n        }\r\n        onClickBreadcrumb(node, isContext) {\r\n            if (isContext) {\r\n                let builder = new menu_builder_2.MenuBuilder();\r\n                this.buildBreadcrumbMenu(node, node, builder);\r\n                let menu = builder.build();\r\n                if (menu) {\r\n                    menu.ShowAsContext();\r\n                }\r\n            }\r\n            else {\r\n                this._treeView.selected = node;\r\n            }\r\n        }\r\n        Awake() {\r\n            jsb.AddCacheString(\"\");\r\n            this._hSplitView = new splitview_1.HSplitView();\r\n            this._treeView = new treeview_2.UTreeView(this);\r\n            this._breadcrumb = new breadcrumb_1.Breadcrumb();\r\n            this._breadcrumb.on(breadcrumb_1.Breadcrumb.CLICKED, this, this.onClickBreadcrumb);\r\n        }\r\n        drawLeftTreeView(width, height) {\r\n            this._treeView.searchString = UnityEditor_10.EditorGUILayout.TextField(this._treeView.searchString);\r\n            this._treeViewScroll = UnityEditor_10.EditorGUILayout.BeginScrollView(this._treeViewScroll);\r\n            if (this._treeView.draw(this._treeViewScroll.x, this._treeViewScroll.y, width, height)) {\r\n                this.Repaint();\r\n            }\r\n            UnityEditor_10.EditorGUILayout.EndScrollView();\r\n        }\r\n        drawConfigView(data, node) { }\r\n        drawFolderView(data, node) { }\r\n        TRect(x, y, w, h) {\r\n            this._tempRect.Set(x, y, w, h);\r\n            return this._tempRect;\r\n        }\r\n        TContent(name, icon, tooltip, text) {\r\n            let content = this._contents[name];\r\n            if (typeof content === \"undefined\") {\r\n                if (typeof text !== \"string\") {\r\n                    text = name;\r\n                }\r\n                if (typeof tooltip === \"string\") {\r\n                    content = new UnityEngine_12.GUIContent(text, treenode_2.BuiltinIcons.getIcon(icon), tooltip);\r\n                }\r\n                else {\r\n                    content = new UnityEngine_12.GUIContent(text, treenode_2.BuiltinIcons.getIcon(icon));\r\n                }\r\n                this._contents[name] = content;\r\n            }\r\n            return content;\r\n        }\r\n        OnGUI() {\r\n            this._event = UnityEngine_12.Event.current;\r\n            let padding = 8;\r\n            let windowStartY = this.toobarHeight + padding * 0.5;\r\n            let windowWidth = this.position.width;\r\n            let windowHeight = this.position.height - windowStartY;\r\n            this._toolbarRect.Set(padding * 0.5, padding * 0.5, windowWidth - padding, this.toobarHeight);\r\n            UnityEngine_12.GUILayout.BeginArea(this._toolbarRect);\r\n            UnityEngine_12.GUILayout.BeginHorizontal();\r\n            this.drawToolBar();\r\n            UnityEngine_12.GUILayout.EndHorizontal();\r\n            UnityEngine_12.GUILayout.EndArea();\r\n            this._tempRect.Set(0, windowStartY, windowWidth, 1);\r\n            UnityEditor_10.EditorGUI.DrawRect(this._tempRect, this._hSplitView.cursorHintColor);\r\n            this._hSplitView.draw(this, windowStartY, windowWidth, windowHeight);\r\n            this._leftRect.Set(0, windowStartY, this._hSplitView.cursorChangeRect.x, windowHeight);\r\n            UnityEngine_12.GUILayout.BeginArea(this._leftRect);\r\n            this.drawLeftTreeView(this._leftRect.width, this._leftRect.height);\r\n            UnityEngine_12.GUILayout.EndArea();\r\n            this._rightRect.Set(this._leftRect.width + this._hSplitView.cursorChangeRect.width + padding, windowStartY + padding, windowWidth - this._hSplitView.cursorChangeRect.xMax - padding * 2, windowHeight - padding * 2 - windowStartY);\r\n            UnityEngine_12.GUILayout.BeginArea(this._rightRect);\r\n            let selected = this._treeView.selected;\r\n            if (selected && selected.data) {\r\n                this._breadcrumb.draw(selected);\r\n                this._tempRect.Set(0, this._breadcrumb.height - 6, this._rightRect.width, 1);\r\n                UnityEditor_10.EditorGUI.DrawRect(this._tempRect, this._hSplitView.cursorHintColor);\r\n                if (selected.isFolder) {\r\n                    this.drawFolderView(selected.data, selected);\r\n                }\r\n                else {\r\n                    this.drawConfigView(selected.data, selected);\r\n                }\r\n            }\r\n            else {\r\n                UnityEditor_10.EditorGUILayout.HelpBox(string_utils_1.TEXT(\"Nothing Selected\"), UnityEditor_10.MessageType.Warning);\r\n            }\r\n            UnityEngine_12.GUILayout.EndArea();\r\n        }\r\n    }\r\n    exports.EditorWindowBase = EditorWindowBase;\r\n});\r\ndefine(\"plover/editor/js_reload\", [\"require\", \"exports\", \"plover/editor/file_watcher\", \"jsb\", \"jsb.editor\"], function (require, exports, file_watcher_1, jsb_1, jsb_editor_1) {\r\n    \"use strict\";\r\n    var _a, _b, _c;\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.reload = void 0;\r\n    let FileWatcherSymbol = Symbol.for(\"GlobalFileWatcher\");\r\n    if (typeof globalThis[FileWatcherSymbol] !== \"undefined\") {\r\n        globalThis[FileWatcherSymbol].dispose();\r\n        delete globalThis[FileWatcherSymbol];\r\n    }\r\n    function reload(mod) {\r\n        if (typeof mod === \"object\") {\r\n            let dirtylist = [];\r\n            collect_reload_deps(mod, dirtylist);\r\n            do_reload(dirtylist);\r\n        }\r\n    }\r\n    exports.reload = reload;\r\n    function do_reload(dirtylist) {\r\n        if (dirtylist.length > 0) {\r\n            jsb_1.ModuleManager.BeginReload();\r\n            for (let i = 0; i < dirtylist.length; i++) {\r\n                let mod = dirtylist[i];\r\n                console.warn(\"reloading\", mod.id);\r\n                jsb_1.ModuleManager.MarkReload(mod.id);\r\n            }\r\n            jsb_1.ModuleManager.EndReload();\r\n        }\r\n    }\r\n    function collect_reload_deps(mod, dirtylist) {\r\n        if (dirtylist.indexOf(mod) < 0) {\r\n            dirtylist.push(mod);\r\n            let parent = mod.parent;\r\n            if (typeof parent === \"object\") {\r\n                collect_reload_deps(parent, dirtylist);\r\n                parent = parent.parent;\r\n            }\r\n        }\r\n    }\r\n    let outDir = ((_b = (_a = jsb_editor_1.EditorRuntime === null || jsb_editor_1.EditorRuntime === void 0 ? void 0 : jsb_editor_1.EditorRuntime.tsconfig) === null || _a === void 0 ? void 0 : _a.compilerOptions) === null || _b === void 0 ? void 0 : _b.outDir) || ((_c = jsb_editor_1.EditorRuntime === null || jsb_editor_1.EditorRuntime === void 0 ? void 0 : jsb_editor_1.EditorRuntime.prefs) === null || _c === void 0 ? void 0 : _c.javascriptDir);\r\n    if (typeof outDir === \"string\" && outDir.length > 0) {\r\n        try {\r\n            let fw = new file_watcher_1.FileWatcher(outDir, \"*.js\");\r\n            fw.on(file_watcher_1.FileWatcher.CHANGED, this, function (filestates) {\r\n                let cache = require.main[\"cache\"];\r\n                let dirtylist = [];\r\n                for (let name in filestates) {\r\n                    let filestate = filestates[name];\r\n                    // console.log(\"file changed:\", filestate.name, filestate.fullPath, filestate.state);\r\n                    if (filestate.state != file_watcher_1.EFileState.CHANGE) {\r\n                        continue;\r\n                    }\r\n                    for (let moduleId in cache) {\r\n                        let mod = cache[moduleId];\r\n                        // console.warn(mod.filename, mod.filename == filestate.fullPath)\r\n                        if (mod.filename == filestate.fullPath) {\r\n                            collect_reload_deps(mod, dirtylist);\r\n                            break;\r\n                        }\r\n                    }\r\n                }\r\n                do_reload(dirtylist);\r\n            });\r\n            globalThis[FileWatcherSymbol] = fw;\r\n            console.log(\"watching\", outDir);\r\n        }\r\n        catch (error) {\r\n            console.error(error);\r\n        }\r\n    }\r\n    else {\r\n        console.warn(\"can not read compilerOptions.outDir from EditorRuntime\");\r\n    }\r\n});\r\ndefine(\"plover/editor/js_module_view\", [\"require\", \"exports\", \"UnityEditor\", \"UnityEngine\", \"plover/text/string_utils\", \"plover/editor/base/editor_window_base\", \"plover/editor/js_reload\"], function (require, exports, UnityEditor_11, UnityEngine_13, string_utils_2, editor_window_base_1, js_reload_1) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.JSModuleView = void 0;\r\n    class JSModuleView extends editor_window_base_1.EditorWindowBase {\r\n        Awake() {\r\n            super.Awake();\r\n            if (!this._touch) {\r\n                this.updateModules();\r\n            }\r\n            this.toobarHeight = 26;\r\n        }\r\n        OnEnable() {\r\n            this.titleContent = new UnityEngine_13.GUIContent(\"JS Modules\");\r\n        }\r\n        drawFolderView(data, node) {\r\n            if (!data) {\r\n                return;\r\n            }\r\n            let mod = data;\r\n            UnityEditor_11.EditorGUILayout.Toggle(string_utils_2.TEXT(\"Main\"), mod == require.main);\r\n            UnityEditor_11.EditorGUILayout.BeginHorizontal();\r\n            UnityEditor_11.EditorGUILayout.TextField(string_utils_2.TEXT(\"Module ID\"), mod.id);\r\n            let doReload = false;\r\n            if (mod[\"resolvername\"] != \"source\") {\r\n                UnityEditor_11.EditorGUI.BeginDisabledGroup(true);\r\n                doReload = UnityEngine_13.GUILayout.Button(string_utils_2.TEXT(\"Reload\"));\r\n                UnityEditor_11.EditorGUI.EndDisabledGroup();\r\n            }\r\n            else {\r\n                doReload = UnityEngine_13.GUILayout.Button(string_utils_2.TEXT(\"Reload\"));\r\n            }\r\n            UnityEditor_11.EditorGUILayout.EndHorizontal();\r\n            UnityEditor_11.EditorGUILayout.TextField(string_utils_2.TEXT(\"File Name\"), mod.filename);\r\n            if (typeof mod.parent === \"object\") {\r\n                UnityEditor_11.EditorGUILayout.TextField(string_utils_2.TEXT(\"Parent\"), mod.parent.id);\r\n            }\r\n            else {\r\n                UnityEditor_11.EditorGUILayout.TextField(string_utils_2.TEXT(\"Parent\"), string_utils_2.TEXT(\"TOP LEVEL\"));\r\n            }\r\n            if (doReload) {\r\n                js_reload_1.reload(mod);\r\n            }\r\n        }\r\n        drawToolBar() {\r\n            if (UnityEngine_13.GUILayout.Button(this.TContent(\"Expand All\", \"Hierarchy\", \"Expand All\"), UnityEditor_11.EditorStyles.toolbarButton, UnityEngine_13.GUILayout.Width(128), UnityEngine_13.GUILayout.Height(this.toobarHeight))) {\r\n                this._treeView.expandAll();\r\n            }\r\n            if (UnityEngine_13.GUILayout.Button(this.TContent(\"Collapse All\", \"Collapsed\", \"Collapse All\"), UnityEditor_11.EditorStyles.toolbarButton, UnityEngine_13.GUILayout.Width(128), UnityEngine_13.GUILayout.Height(this.toobarHeight))) {\r\n                this._treeView.collapseAll();\r\n            }\r\n            if (UnityEngine_13.GUILayout.Button(this.TContent(\"Refresh\", \"Refresh\", \"Refresh\"), UnityEditor_11.EditorStyles.toolbarButton, UnityEngine_13.GUILayout.Width(128), UnityEngine_13.GUILayout.Height(this.toobarHeight))) {\r\n                this.updateModules();\r\n            }\r\n        }\r\n        updateModules() {\r\n            this._treeView.removeAll();\r\n            let cache = require.main[\"cache\"];\r\n            if (typeof cache === \"undefined\") {\r\n                return;\r\n            }\r\n            this._touch = {};\r\n            Object.keys(cache).forEach(name => {\r\n                let mod = cache[name];\r\n                this.addModule(mod, this._treeView.root);\r\n            });\r\n        }\r\n        getSimplifiedName(id) {\r\n            let index = id.lastIndexOf('/');\r\n            return index >= 0 ? id.substring(index + 1) : id;\r\n        }\r\n        addModule(mod, treeNode) {\r\n            if (typeof this._touch[mod.id] !== \"undefined\") {\r\n                // skip infinite loop\r\n                return;\r\n            }\r\n            let childNode = treeNode.addFolderChild(this.getSimplifiedName(mod.id));\r\n            this._touch[mod.id] = true;\r\n            childNode.data = mod;\r\n            childNode.isEditable = false;\r\n            if (typeof mod.children !== \"undefined\") {\r\n                for (let i = 0; i < mod.children.length; i++) {\r\n                    let child = mod.children[i];\r\n                    this.addModule(child, childNode);\r\n                }\r\n            }\r\n        }\r\n    }\r\n    exports.JSModuleView = JSModuleView;\r\n});\r\ndefine(\"plover/editor/base/content_cache\", [\"require\", \"exports\", \"UnityEngine\"], function (require, exports, UnityEngine_14) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.EdCache = void 0;\r\n    class EdCache {\r\n        static T(title, tooltip = null, image = null) {\r\n            let item = EdCache.cache[title];\r\n            if (typeof item === \"undefined\") {\r\n                item = EdCache.cache[title] = tooltip == null ? new UnityEngine_14.GUIContent(title, image) : new UnityEngine_14.GUIContent(title, image, tooltip);\r\n            }\r\n            return item;\r\n        }\r\n    }\r\n    exports.EdCache = EdCache;\r\n    EdCache.cache = {};\r\n});\r\ndefine(\"plover/events/data_binding\", [\"require\", \"exports\"], function (require, exports) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.DataBinding = exports.Subscribers = exports.Subscriber = void 0;\r\n    class Subscriber {\r\n        constructor(model, key) {\r\n            this._model = model;\r\n            this._key = key;\r\n            this._model.addSubscriber(this);\r\n        }\r\n        get value() {\r\n            return this._model[this._key];\r\n        }\r\n        set value(newValue) {\r\n            this._source = true;\r\n            this._model[this._key] = newValue;\r\n            this._source = false;\r\n        }\r\n        update(value) {\r\n        }\r\n        notify(value) {\r\n            if (!this._source) {\r\n                this.update(value);\r\n            }\r\n        }\r\n        unsubscribe() {\r\n            if (this._model) {\r\n                this._model.removeSubscriber(this);\r\n                this._model = undefined;\r\n            }\r\n        }\r\n    }\r\n    exports.Subscriber = Subscriber;\r\n    class Subscribers {\r\n        notify(valueProxy) {\r\n            if (this._subs) {\r\n                const copy = this._subs.slice();\r\n                for (let i = 0, len = copy.length; i < len; i++) {\r\n                    copy[i].notify(valueProxy);\r\n                }\r\n            }\r\n        }\r\n        addSub(sub) {\r\n            if (!this._subs) {\r\n                this._subs = [];\r\n            }\r\n            this._subs.push(sub);\r\n        }\r\n        removeSub(sub) {\r\n            if (this._subs && this._subs.length) {\r\n                const index = this._subs.indexOf(sub);\r\n                if (index >= 0) {\r\n                    this._subs.splice(index, 1);\r\n                }\r\n            }\r\n        }\r\n        // 废弃当前值, 将监听者转移给新值\r\n        transfer(newValue) {\r\n            newValue._subs = this._subs;\r\n            this._subs = undefined;\r\n        }\r\n    }\r\n    exports.Subscribers = Subscribers;\r\n    const SubscribersKey = Symbol.for(\"subscribers\");\r\n    class DataBinding {\r\n        constructor() {\r\n            Object.defineProperty(this, SubscribersKey, { value: new Subscribers(), enumerable: false });\r\n        }\r\n        addSubscriber(sub) {\r\n            this[SubscribersKey].addSub(sub);\r\n        }\r\n        removeSubscriber(sub) {\r\n            this[SubscribersKey].removeSub(sub);\r\n        }\r\n        static bind(data) {\r\n            let model = new DataBinding();\r\n            let subscribers = model[SubscribersKey];\r\n            for (let key in data) {\r\n                if (key.startsWith(\"$\") || key.startsWith(\"_$\")) {\r\n                    continue;\r\n                }\r\n                let value = data[key];\r\n                let valueProxy = value;\r\n                if (typeof value === \"object\") {\r\n                    valueProxy = DataBinding.bind(value);\r\n                }\r\n                Object.defineProperty(model, key, {\r\n                    enumerable: true,\r\n                    get() {\r\n                        return valueProxy;\r\n                    },\r\n                    set(newValue) {\r\n                        if (newValue !== value) {\r\n                            let oldValue = value;\r\n                            if (typeof newValue === \"object\") {\r\n                                valueProxy = DataBinding.bind(newValue);\r\n                                oldValue[SubscribersKey].transfer(valueProxy[SubscribersKey]);\r\n                                // Model.transfer(<Model><any>oldValue, <Model><any>valueProxy);\r\n                            }\r\n                            else {\r\n                                valueProxy = newValue;\r\n                            }\r\n                            subscribers.notify(valueProxy);\r\n                        }\r\n                    },\r\n                });\r\n            }\r\n            return model;\r\n        }\r\n        static subscribe(SubscriberType, modelObject, path, ...args) {\r\n            let model = modelObject;\r\n            let keys = path.split(\".\");\r\n            let key = path;\r\n            for (let i = 0, len = keys.length - 1; i < len; i++) {\r\n                key = keys[i];\r\n                model = model[key];\r\n            }\r\n            let sub = new SubscriberType(model, key, ...args);\r\n            return sub;\r\n        }\r\n    }\r\n    exports.DataBinding = DataBinding;\r\n});\r\n/*!\r\n * Vue.js v2.6.14\r\n * (c) 2014-2021 Evan You\r\n * Released under the MIT License.\r\n */\r\ndefine(\"plover/jsx/vue\", [\"require\", \"exports\"], function (require, exports) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.ViewModel = void 0;\r\n    /**\r\n     * Perform no operation.\r\n     * Stubbing args to make Flow happy without leaving useless transpiled code\r\n     * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/).\r\n     */\r\n    function noop(a, b, c) { }\r\n    function warn(m, v) { }\r\n    // can we use __proto__?\r\n    var hasProto = '__proto__' in {};\r\n    /**\r\n     * Augment a target Object or Array by intercepting\r\n     * the prototype chain using __proto__\r\n     */\r\n    function protoAugment(target, src) {\r\n        /* eslint-disable no-proto */\r\n        target.__proto__ = src;\r\n        /* eslint-enable no-proto */\r\n    }\r\n    /**\r\n     * Augment a target Object or Array by defining\r\n     * hidden properties.\r\n     */\r\n    /* istanbul ignore next */\r\n    function copyAugment(target, src, keys) {\r\n        for (var i = 0, l = keys.length; i < l; i++) {\r\n            var key = keys[i];\r\n            def(target, key, src[key]);\r\n        }\r\n    }\r\n    /**\r\n     * Define a property.\r\n     */\r\n    function def(obj, key, val, enumerable) {\r\n        Object.defineProperty(obj, key, {\r\n            value: val,\r\n            enumerable: !!enumerable,\r\n            writable: true,\r\n            configurable: true\r\n        });\r\n    }\r\n    /*\r\n     * not type checking this file because flow doesn't play well with\r\n     * dynamically accessing methods on Array prototype\r\n     */\r\n    var arrayProto = Array.prototype;\r\n    var arrayMethods = Object.create(arrayProto);\r\n    var methodsToPatch = [\r\n        'push',\r\n        'pop',\r\n        'shift',\r\n        'unshift',\r\n        'splice',\r\n        'sort',\r\n        'reverse'\r\n    ];\r\n    /**\r\n     * Intercept mutating methods and emit events\r\n     */\r\n    methodsToPatch.forEach(function (method) {\r\n        // cache original method\r\n        var original = arrayProto[method];\r\n        def(arrayMethods, method, function mutator() {\r\n            var args = [], len = arguments.length;\r\n            while (len--)\r\n                args[len] = arguments[len];\r\n            var result = original.apply(this, args);\r\n            var ob = this.__ob__;\r\n            var inserted;\r\n            switch (method) {\r\n                case 'push':\r\n                case 'unshift':\r\n                    inserted = args;\r\n                    break;\r\n                case 'splice':\r\n                    inserted = args.slice(2);\r\n                    break;\r\n            }\r\n            if (inserted) {\r\n                ob.observeArray(inserted);\r\n            }\r\n            // notify change\r\n            ob.dep.notify();\r\n            return result;\r\n        });\r\n    });\r\n    /*  */\r\n    var arrayKeys = Object.getOwnPropertyNames(arrayMethods);\r\n    /**\r\n     * Remove an item from an array.\r\n     */\r\n    function remove(arr, item) {\r\n        if (arr.length) {\r\n            var index = arr.indexOf(item);\r\n            if (index > -1) {\r\n                return arr.splice(index, 1);\r\n            }\r\n        }\r\n    }\r\n    /*  */\r\n    var uid = 0;\r\n    /**\r\n     * A dep is an observable that can have multiple\r\n     * directives subscribing to it.\r\n     */\r\n    function Dep() {\r\n        this.id = uid++;\r\n        this.subs = [];\r\n    }\r\n    ;\r\n    Dep.prototype.addSub = function addSub(sub) {\r\n        this.subs.push(sub);\r\n    };\r\n    Dep.prototype.removeSub = function removeSub(sub) {\r\n        remove(this.subs, sub);\r\n    };\r\n    Dep.prototype.depend = function depend() {\r\n        if (Dep.target) {\r\n            Dep.target.addDep(this);\r\n        }\r\n    };\r\n    Dep.prototype.notify = function notify() {\r\n        // stabilize the subscriber list first\r\n        var subs = this.subs.slice();\r\n        for (var i = 0, l = subs.length; i < l; i++) {\r\n            subs[i].update();\r\n        }\r\n    };\r\n    // The current target watcher being evaluated.\r\n    // This is globally unique because only one watcher\r\n    // can be evaluated at a time.\r\n    Dep.target = null;\r\n    var targetStack = [];\r\n    function pushTarget(target) {\r\n        targetStack.push(target);\r\n        Dep.target = target;\r\n    }\r\n    function popTarget() {\r\n        targetStack.pop();\r\n        Dep.target = targetStack[targetStack.length - 1];\r\n    }\r\n    /**\r\n     * Collect dependencies on array elements when the array is touched, since\r\n     * we cannot intercept array element access like property getters.\r\n     */\r\n    function dependArray(value) {\r\n        for (var e = (void 0), i = 0, l = value.length; i < l; i++) {\r\n            e = value[i];\r\n            e && e.__ob__ && e.__ob__.dep.depend();\r\n            if (Array.isArray(e)) {\r\n                dependArray(e);\r\n            }\r\n        }\r\n    }\r\n    /**\r\n     * Define a reactive property on an Object.\r\n     */\r\n    function defineReactive$$1(obj, key, val, customSetter, shallow) {\r\n        var dep = new Dep();\r\n        var property = Object.getOwnPropertyDescriptor(obj, key);\r\n        if (property && property.configurable === false) {\r\n            return;\r\n        }\r\n        // cater for pre-defined getter/setters\r\n        var getter = property && property.get;\r\n        var setter = property && property.set;\r\n        if ((!getter || setter) && arguments.length === 2) {\r\n            val = obj[key];\r\n        }\r\n        var childOb = !shallow && observe(val);\r\n        Object.defineProperty(obj, key, {\r\n            enumerable: true,\r\n            configurable: true,\r\n            get: function reactiveGetter() {\r\n                var value = getter ? getter.call(obj) : val;\r\n                if (Dep.target) {\r\n                    dep.depend();\r\n                    if (childOb) {\r\n                        childOb.dep.depend();\r\n                        if (Array.isArray(value)) {\r\n                            dependArray(value);\r\n                        }\r\n                    }\r\n                }\r\n                return value;\r\n            },\r\n            set: function reactiveSetter(newVal) {\r\n                var value = getter ? getter.call(obj) : val;\r\n                /* eslint-disable no-self-compare */\r\n                if (newVal === value || (newVal !== newVal && value !== value)) {\r\n                    return;\r\n                }\r\n                /* eslint-enable no-self-compare */\r\n                if (customSetter) {\r\n                    customSetter();\r\n                }\r\n                // #7981: for accessor properties without setter\r\n                if (getter && !setter) {\r\n                    return;\r\n                }\r\n                if (setter) {\r\n                    setter.call(obj, newVal);\r\n                }\r\n                else {\r\n                    val = newVal;\r\n                }\r\n                childOb = !shallow && observe(newVal);\r\n                dep.notify();\r\n            }\r\n        });\r\n    }\r\n    /**\r\n     * Check whether an object has the property.\r\n     */\r\n    var hasOwnProperty = Object.prototype.hasOwnProperty;\r\n    function hasOwn(obj, key) {\r\n        return hasOwnProperty.call(obj, key);\r\n    }\r\n    /**\r\n     * Quick object check - this is primarily used to tell\r\n     * Objects from primitive values when we know the value\r\n     * is a JSON-compliant type.\r\n     */\r\n    function isObject(obj) {\r\n        return obj !== null && typeof obj === 'object';\r\n    }\r\n    /**\r\n     * In some cases we may want to disable observation inside a component's\r\n     * update computation.\r\n     */\r\n    var shouldObserve = true;\r\n    function toggleObserving(value) {\r\n        shouldObserve = value;\r\n    }\r\n    /**\r\n     * Get the raw type string of a value, e.g., [object Object].\r\n     */\r\n    var _toString = Object.prototype.toString;\r\n    function toRawType(value) {\r\n        return _toString.call(value).slice(8, -1);\r\n    }\r\n    /**\r\n     * Strict object type check. Only returns true\r\n     * for plain JavaScript objects.\r\n     */\r\n    function isPlainObject(obj) {\r\n        return _toString.call(obj) === '[object Object]';\r\n    }\r\n    function isRegExp(v) {\r\n        return _toString.call(v) === '[object RegExp]';\r\n    }\r\n    /**\r\n     * Attempt to create an observer instance for a value,\r\n     * returns the new observer if successfully observed,\r\n     * or the existing observer if the value already has one.\r\n     */\r\n    function observe(value, asRootData) {\r\n        if (!isObject(value)) {\r\n            return;\r\n        }\r\n        var ob;\r\n        if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {\r\n            ob = value.__ob__;\r\n        }\r\n        else if (shouldObserve &&\r\n            (Array.isArray(value) || isPlainObject(value)) &&\r\n            Object.isExtensible(value) &&\r\n            !value._isVue) {\r\n            ob = new Observer(value);\r\n        }\r\n        if (asRootData && ob) {\r\n            ob.vmCount++;\r\n        }\r\n        return ob;\r\n    }\r\n    /* istanbul ignore next */\r\n    function isNative(Ctor) {\r\n        return typeof Ctor === 'function' && /native code/.test(Ctor.toString());\r\n    }\r\n    var _Set;\r\n    /* istanbul ignore if */ // $flow-disable-line\r\n    if (typeof Set !== 'undefined' && isNative(Set)) {\r\n        // use native Set when available.\r\n        _Set = Set;\r\n    }\r\n    else {\r\n        // a non-standard Set polyfill that only works with primitive keys.\r\n        _Set = /*@__PURE__*/ (function () {\r\n            function Set() {\r\n                this.set = Object.create(null);\r\n            }\r\n            Set.prototype.has = function has(key) {\r\n                return this.set[key] === true;\r\n            };\r\n            Set.prototype.add = function add(key) {\r\n                this.set[key] = true;\r\n            };\r\n            Set.prototype.clear = function clear() {\r\n                this.set = Object.create(null);\r\n            };\r\n            return Set;\r\n        }());\r\n    }\r\n    /*  */\r\n    /**\r\n     * unicode letters used for parsing html tags, component names and property paths.\r\n     * using https://www.w3.org/TR/html53/semantics-scripting.html#potentialcustomelementname\r\n     * skipping \\u10000-\\uEFFFF due to it freezing up PhantomJS\r\n     */\r\n    var unicodeRegExp = /a-zA-Z\\u00B7\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u203F-\\u2040\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD/;\r\n    /**\r\n     * Parse simple path.\r\n     */\r\n    var bailRE = new RegExp((\"[^\" + (unicodeRegExp.source) + \".$_\\\\d]\"));\r\n    function parsePath(path) {\r\n        if (bailRE.test(path)) {\r\n            return;\r\n        }\r\n        var segments = path.split('.');\r\n        return function (obj) {\r\n            for (var i = 0; i < segments.length; i++) {\r\n                if (!obj) {\r\n                    return;\r\n                }\r\n                obj = obj[segments[i]];\r\n            }\r\n            return obj;\r\n        };\r\n    }\r\n    /*  */\r\n    var seenObjects = new _Set();\r\n    /**\r\n     * Recursively traverse an object to evoke all converted\r\n     * getters, so that every nested property inside the object\r\n     * is collected as a \"deep\" dependency.\r\n     */\r\n    function traverse(val) {\r\n        _traverse(val, seenObjects);\r\n        seenObjects.clear();\r\n    }\r\n    function _traverse(val, seen) {\r\n        var i, keys;\r\n        var isA = Array.isArray(val);\r\n        if ((!isA && !isObject(val)) || Object.isFrozen(val) /* || val instanceof VNode */) {\r\n            return;\r\n        }\r\n        if (val.__ob__) {\r\n            var depId = val.__ob__.dep.id;\r\n            if (seen.has(depId)) {\r\n                return;\r\n            }\r\n            seen.add(depId);\r\n        }\r\n        if (isA) {\r\n            i = val.length;\r\n            while (i--) {\r\n                _traverse(val[i], seen);\r\n            }\r\n        }\r\n        else {\r\n            keys = Object.keys(val);\r\n            i = keys.length;\r\n            while (i--) {\r\n                _traverse(val[keys[i]], seen);\r\n            }\r\n        }\r\n    }\r\n    /*  */\r\n    function handleError(err, vm, info) {\r\n        // Deactivate deps tracking while processing error handler to avoid possible infinite rendering.\r\n        // See: https://github.com/vuejs/vuex/issues/1505\r\n        pushTarget();\r\n        try {\r\n            if (vm) {\r\n                var cur = vm;\r\n                while ((cur = cur.$parent)) {\r\n                    var hooks = cur.$options.errorCaptured;\r\n                    if (hooks) {\r\n                        for (var i = 0; i < hooks.length; i++) {\r\n                            try {\r\n                                var capture = hooks[i].call(cur, err, vm, info) === false;\r\n                                if (capture) {\r\n                                    return;\r\n                                }\r\n                            }\r\n                            catch (e) {\r\n                                globalHandleError(e, cur, 'errorCaptured hook');\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n            globalHandleError(err, vm, info);\r\n        }\r\n        finally {\r\n            popTarget();\r\n        }\r\n    }\r\n    function isDef(v) {\r\n        return v !== undefined && v !== null;\r\n    }\r\n    function isPromise(val) {\r\n        return (isDef(val) &&\r\n            typeof val.then === 'function' &&\r\n            typeof val.catch === 'function');\r\n    }\r\n    function invokeWithErrorHandling(handler, context, args, vm, info) {\r\n        var res;\r\n        try {\r\n            res = args ? handler.apply(context, args) : handler.call(context);\r\n            if (res && !res._isVue && isPromise(res) && !res._handled) {\r\n                res.catch(function (e) { return handleError(e, vm, info + \" (Promise/async)\"); });\r\n                // issue #9511\r\n                // avoid catch triggering multiple times when nested calls\r\n                res._handled = true;\r\n            }\r\n        }\r\n        catch (e) {\r\n            handleError(e, vm, info);\r\n        }\r\n        return res;\r\n    }\r\n    function globalHandleError(err, vm, info) {\r\n        // if (config.errorHandler) {\r\n        //     try {\r\n        //         return config.errorHandler.call(null, err, vm, info)\r\n        //     } catch (e) {\r\n        //         // if the user intentionally throws the original error in the handler,\r\n        //         // do not log it twice\r\n        //         if (e !== err) {\r\n        //             logError(e, null, 'config.errorHandler');\r\n        //         }\r\n        //     }\r\n        // }\r\n        logError(err, vm, info);\r\n    }\r\n    function logError(err, vm, info) {\r\n        {\r\n            warn((\"Error in \" + info + \": \\\"\" + (err.toString()) + \"\\\"\"), vm);\r\n        }\r\n        /* istanbul ignore else */\r\n        if (typeof console !== 'undefined') {\r\n            console.error(err);\r\n        }\r\n        else {\r\n            throw err;\r\n        }\r\n    }\r\n    /**\r\n     * Push a watcher into the watcher queue.\r\n     * Jobs with duplicate IDs will be skipped unless it's\r\n     * pushed when the queue is being flushed.\r\n     */\r\n    function queueWatcher(watcher) {\r\n        var id = watcher.id;\r\n        if (has[id] == null) {\r\n            has[id] = true;\r\n            if (!flushing) {\r\n                queue.push(watcher);\r\n            }\r\n            else {\r\n                // if already flushing, splice the watcher based on its id\r\n                // if already past its id, it will be run next immediately.\r\n                var i = queue.length - 1;\r\n                while (i > index && queue[i].id > watcher.id) {\r\n                    i--;\r\n                }\r\n                queue.splice(i + 1, 0, watcher);\r\n            }\r\n            // queue the flush\r\n            if (!waiting) {\r\n                waiting = true;\r\n                // if (!config.async) {\r\n                //     flushSchedulerQueue();\r\n                //     return\r\n                // }\r\n                nextTick(flushSchedulerQueue);\r\n            }\r\n        }\r\n    }\r\n    var callbacks = [];\r\n    var pending = false;\r\n    function flushCallbacks() {\r\n        pending = false;\r\n        var copies = callbacks.slice(0);\r\n        callbacks.length = 0;\r\n        for (var i = 0; i < copies.length; i++) {\r\n            copies[i]();\r\n        }\r\n    }\r\n    // Here we have async deferring wrappers using microtasks.\r\n    // In 2.5 we used (macro) tasks (in combination with microtasks).\r\n    // However, it has subtle problems when state is changed right before repaint\r\n    // (e.g. #6813, out-in transitions).\r\n    // Also, using (macro) tasks in event handler would cause some weird behaviors\r\n    // that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).\r\n    // So we now use microtasks everywhere, again.\r\n    // A major drawback of this tradeoff is that there are some scenarios\r\n    // where microtasks have too high a priority and fire in between supposedly\r\n    // sequential events (e.g. #4521, #6690, which have workarounds)\r\n    // or even between bubbling of the same event (#6566).\r\n    var timerFunc;\r\n    var p = Promise.resolve();\r\n    timerFunc = function () {\r\n        p.then(flushCallbacks);\r\n    };\r\n    function nextTick(cb, ctx) {\r\n        var _resolve;\r\n        callbacks.push(function () {\r\n            if (cb) {\r\n                try {\r\n                    cb.call(ctx);\r\n                }\r\n                catch (e) {\r\n                    handleError(e, ctx, 'nextTick');\r\n                }\r\n            }\r\n            else if (_resolve) {\r\n                _resolve(ctx);\r\n            }\r\n        });\r\n        if (!pending) {\r\n            pending = true;\r\n            timerFunc();\r\n        }\r\n        // $flow-disable-line\r\n        if (!cb && typeof Promise !== 'undefined') {\r\n            return new Promise(function (resolve) {\r\n                _resolve = resolve;\r\n            });\r\n        }\r\n    }\r\n    /*  */\r\n    var MAX_UPDATE_COUNT = 100;\r\n    var queue = [];\r\n    var activatedChildren = [];\r\n    var has = {};\r\n    var circular = {};\r\n    var waiting = false;\r\n    var flushing = false;\r\n    var index = 0;\r\n    /**\r\n     * Reset the scheduler's state.\r\n     */\r\n    function resetSchedulerState() {\r\n        index = queue.length = activatedChildren.length = 0;\r\n        has = {};\r\n        {\r\n            circular = {};\r\n        }\r\n        waiting = flushing = false;\r\n    }\r\n    // Async edge case #6566 requires saving the timestamp when event listeners are\r\n    // attached. However, calling performance.now() has a perf overhead especially\r\n    // if the page has thousands of event listeners. Instead, we take a timestamp\r\n    // every time the scheduler flushes and use that for all event listeners\r\n    // attached during that flush.\r\n    var currentFlushTimestamp = 0;\r\n    // Async edge case fix requires storing an event listener's attach timestamp.\r\n    var getNow = Date.now;\r\n    /**\r\n     * Flush both queues and run the watchers.\r\n     */\r\n    function flushSchedulerQueue() {\r\n        currentFlushTimestamp = getNow();\r\n        flushing = true;\r\n        var watcher, id;\r\n        // Sort queue before flush.\r\n        // This ensures that:\r\n        // 1. Components are updated from parent to child. (because parent is always\r\n        //    created before the child)\r\n        // 2. A component's user watchers are run before its render watcher (because\r\n        //    user watchers are created before the render watcher)\r\n        // 3. If a component is destroyed during a parent component's watcher run,\r\n        //    its watchers can be skipped.\r\n        queue.sort(function (a, b) { return a.id - b.id; });\r\n        // do not cache length because more watchers might be pushed\r\n        // as we run existing watchers\r\n        for (index = 0; index < queue.length; index++) {\r\n            watcher = queue[index];\r\n            if (watcher.before) {\r\n                watcher.before();\r\n            }\r\n            id = watcher.id;\r\n            has[id] = null;\r\n            watcher.run();\r\n            // in dev build, check and stop circular updates.\r\n            if (has[id] != null) {\r\n                circular[id] = (circular[id] || 0) + 1;\r\n                if (circular[id] > MAX_UPDATE_COUNT) {\r\n                    warn('You may have an infinite update loop ' + (watcher.user\r\n                        ? (\"in watcher with expression \\\"\" + (watcher.expression) + \"\\\"\")\r\n                        : \"in a component render function.\"), watcher.vm);\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n        // keep copies of post queues before resetting state\r\n        var activatedQueue = activatedChildren.slice();\r\n        var updatedQueue = queue.slice();\r\n        resetSchedulerState();\r\n        // call component updated and activated hooks\r\n        callActivatedHooks(activatedQueue);\r\n        callUpdatedHooks(updatedQueue);\r\n        // // devtool hook\r\n        // /* istanbul ignore if */\r\n        // if (devtools && config.devtools) {\r\n        //     devtools.emit('flush');\r\n        // }\r\n    }\r\n    function callActivatedHooks(queue) {\r\n        for (var i = 0; i < queue.length; i++) {\r\n            queue[i]._inactive = true;\r\n            // activateChildComponent(queue[i], true /* true */);\r\n        }\r\n    }\r\n    function callHook(vm, hook) {\r\n        // #7573 disable dep collection when invoking lifecycle hooks\r\n        pushTarget();\r\n        var handlers = vm.$options[hook];\r\n        var info = hook + \" hook\";\r\n        if (handlers) {\r\n            for (var i = 0, j = handlers.length; i < j; i++) {\r\n                invokeWithErrorHandling(handlers[i], vm, null, vm, info);\r\n            }\r\n        }\r\n        if (vm._hasHookEvent) {\r\n            vm.$emit('hook:' + hook);\r\n        }\r\n        popTarget();\r\n    }\r\n    function callUpdatedHooks(queue) {\r\n        var i = queue.length;\r\n        while (i--) {\r\n            var watcher = queue[i];\r\n            var vm = watcher.vm;\r\n            if (vm._watcher === watcher && vm._isMounted && !vm._isDestroyed) {\r\n                callHook(vm, 'updated');\r\n            }\r\n        }\r\n    }\r\n    /*  */\r\n    var uid$2 = 0;\r\n    /**\r\n     * A watcher parses an expression, collects dependencies,\r\n     * and fires callback when the expression value changes.\r\n     * This is used for both the $watch() api and directives.\r\n     */\r\n    function Watcher(vm, expOrFn, cb, options, isRenderWatcher) {\r\n        this.vm = vm;\r\n        if (isRenderWatcher) {\r\n            vm._watcher = this;\r\n        }\r\n        vm._watchers.push(this);\r\n        // options\r\n        if (options) {\r\n            this.deep = !!options.deep;\r\n            this.user = !!options.user;\r\n            this.lazy = !!options.lazy;\r\n            this.sync = !!options.sync;\r\n            this.before = options.before;\r\n        }\r\n        else {\r\n            this.deep = this.user = this.lazy = this.sync = false;\r\n        }\r\n        this.cb = cb;\r\n        this.id = ++uid$2; // uid for batching\r\n        this.active = true;\r\n        this.dirty = this.lazy; // for lazy watchers\r\n        this.deps = [];\r\n        this.newDeps = [];\r\n        this.depIds = new _Set();\r\n        this.newDepIds = new _Set();\r\n        this.expression = expOrFn.toString();\r\n        // parse expression for getter\r\n        if (typeof expOrFn === 'function') {\r\n            this.getter = expOrFn;\r\n        }\r\n        else {\r\n            this.getter = parsePath(expOrFn);\r\n            if (!this.getter) {\r\n                this.getter = noop;\r\n                warn(\"Failed watching path: \\\"\" + expOrFn + \"\\\" \" +\r\n                    'Watcher only accepts simple dot-delimited paths. ' +\r\n                    'For full control, use a function instead.', vm);\r\n            }\r\n        }\r\n        this.value = this.lazy\r\n            ? undefined\r\n            : this.get();\r\n    }\r\n    ;\r\n    /**\r\n     * Evaluate the getter, and re-collect dependencies.\r\n     */\r\n    Watcher.prototype.get = function get() {\r\n        pushTarget(this);\r\n        var value;\r\n        var vm = this.vm;\r\n        try {\r\n            value = this.getter.call(vm, vm);\r\n        }\r\n        catch (e) {\r\n            if (this.user) {\r\n                handleError(e, vm, (\"getter for watcher \\\"\" + (this.expression) + \"\\\"\"));\r\n            }\r\n            else {\r\n                throw e;\r\n            }\r\n        }\r\n        finally {\r\n            // \"touch\" every property so they are all tracked as\r\n            // dependencies for deep watching\r\n            if (this.deep) {\r\n                traverse(value);\r\n            }\r\n            popTarget();\r\n            this.cleanupDeps();\r\n        }\r\n        return value;\r\n    };\r\n    /**\r\n     * Add a dependency to this directive.\r\n     */\r\n    Watcher.prototype.addDep = function addDep(dep) {\r\n        var id = dep.id;\r\n        if (!this.newDepIds.has(id)) {\r\n            this.newDepIds.add(id);\r\n            this.newDeps.push(dep);\r\n            if (!this.depIds.has(id)) {\r\n                dep.addSub(this);\r\n            }\r\n        }\r\n    };\r\n    /**\r\n     * Clean up for dependency collection.\r\n     */\r\n    Watcher.prototype.cleanupDeps = function cleanupDeps() {\r\n        var i = this.deps.length;\r\n        while (i--) {\r\n            var dep = this.deps[i];\r\n            if (!this.newDepIds.has(dep.id)) {\r\n                dep.removeSub(this);\r\n            }\r\n        }\r\n        var tmp = this.depIds;\r\n        this.depIds = this.newDepIds;\r\n        this.newDepIds = tmp;\r\n        this.newDepIds.clear();\r\n        tmp = this.deps;\r\n        this.deps = this.newDeps;\r\n        this.newDeps = tmp;\r\n        this.newDeps.length = 0;\r\n    };\r\n    /**\r\n     * Subscriber interface.\r\n     * Will be called when a dependency changes.\r\n     */\r\n    Watcher.prototype.update = function update() {\r\n        /* istanbul ignore else */\r\n        if (this.lazy) {\r\n            this.dirty = true;\r\n        }\r\n        else if (this.sync) {\r\n            this.run();\r\n        }\r\n        else {\r\n            queueWatcher(this);\r\n        }\r\n    };\r\n    /**\r\n     * Scheduler job interface.\r\n     * Will be called by the scheduler.\r\n     */\r\n    Watcher.prototype.run = function run() {\r\n        if (this.active) {\r\n            var value = this.get();\r\n            if (value !== this.value ||\r\n                // Deep watchers and watchers on Object/Arrays should fire even\r\n                // when the value is the same, because the value may\r\n                // have mutated.\r\n                isObject(value) ||\r\n                this.deep) {\r\n                // set new value\r\n                var oldValue = this.value;\r\n                this.value = value;\r\n                if (this.user) {\r\n                    var info = \"callback for watcher \\\"\" + (this.expression) + \"\\\"\";\r\n                    invokeWithErrorHandling(this.cb, this.vm, [value, oldValue], this.vm, info);\r\n                }\r\n                else {\r\n                    this.cb.call(this.vm, value, oldValue);\r\n                }\r\n            }\r\n        }\r\n    };\r\n    /**\r\n     * Evaluate the value of the watcher.\r\n     * This only gets called for lazy watchers.\r\n     */\r\n    Watcher.prototype.evaluate = function evaluate() {\r\n        this.value = this.get();\r\n        this.dirty = false;\r\n    };\r\n    /**\r\n     * Depend on all deps collected by this watcher.\r\n     */\r\n    Watcher.prototype.depend = function depend() {\r\n        var i = this.deps.length;\r\n        while (i--) {\r\n            this.deps[i].depend();\r\n        }\r\n    };\r\n    /**\r\n     * Remove self from all dependencies' subscriber list.\r\n     */\r\n    Watcher.prototype.teardown = function teardown() {\r\n        if (this.active) {\r\n            // remove self from vm's watcher list\r\n            // this is a somewhat expensive operation so we skip it\r\n            // if the vm is being destroyed.\r\n            if (!this.vm._isBeingDestroyed) {\r\n                remove(this.vm._watchers, this);\r\n            }\r\n            var i = this.deps.length;\r\n            while (i--) {\r\n                this.deps[i].removeSub(this);\r\n            }\r\n            this.active = false;\r\n        }\r\n    };\r\n    /**\r\n     * Observer class that is attached to each observed\r\n     * object. Once attached, the observer converts the target\r\n     * object's property keys into getter/setters that\r\n     * collect dependencies and dispatch updates.\r\n     */\r\n    var Observer = function Observer(value) {\r\n        this.value = value;\r\n        this.dep = new Dep();\r\n        this.vmCount = 0;\r\n        def(value, '__ob__', this);\r\n        if (Array.isArray(value)) {\r\n            if (hasProto) {\r\n                protoAugment(value, arrayMethods);\r\n            }\r\n            else {\r\n                copyAugment(value, arrayMethods, arrayKeys);\r\n            }\r\n            this.observeArray(value);\r\n        }\r\n        else {\r\n            this.walk(value);\r\n        }\r\n    };\r\n    /**\r\n     * Walk through all properties and convert them into\r\n     * getter/setters. This method should only be called when\r\n     * value type is Object.\r\n     */\r\n    Observer.prototype.walk = function walk(obj) {\r\n        var keys = Object.keys(obj);\r\n        for (var i = 0; i < keys.length; i++) {\r\n            defineReactive$$1(obj, keys[i]);\r\n        }\r\n    };\r\n    /**\r\n     * Observe a list of Array items.\r\n     */\r\n    Observer.prototype.observeArray = function observeArray(items) {\r\n        for (var i = 0, l = items.length; i < l; i++) {\r\n            observe(items[i]);\r\n        }\r\n    };\r\n    var validDivisionCharRE = /[\\w).+\\-_$\\]]/;\r\n    function parseFilters(exp) {\r\n        var inSingle = false;\r\n        var inDouble = false;\r\n        var inTemplateString = false;\r\n        var inRegex = false;\r\n        var curly = 0;\r\n        var square = 0;\r\n        var paren = 0;\r\n        var lastFilterIndex = 0;\r\n        var c, prev, i, expression, filters;\r\n        for (i = 0; i < exp.length; i++) {\r\n            prev = c;\r\n            c = exp.charCodeAt(i);\r\n            if (inSingle) {\r\n                if (c === 0x27 && prev !== 0x5C) {\r\n                    inSingle = false;\r\n                }\r\n            }\r\n            else if (inDouble) {\r\n                if (c === 0x22 && prev !== 0x5C) {\r\n                    inDouble = false;\r\n                }\r\n            }\r\n            else if (inTemplateString) {\r\n                if (c === 0x60 && prev !== 0x5C) {\r\n                    inTemplateString = false;\r\n                }\r\n            }\r\n            else if (inRegex) {\r\n                if (c === 0x2f && prev !== 0x5C) {\r\n                    inRegex = false;\r\n                }\r\n            }\r\n            else if (c === 0x7C && // pipe\r\n                exp.charCodeAt(i + 1) !== 0x7C &&\r\n                exp.charCodeAt(i - 1) !== 0x7C &&\r\n                !curly && !square && !paren) {\r\n                if (expression === undefined) {\r\n                    // first filter, end of expression\r\n                    lastFilterIndex = i + 1;\r\n                    expression = exp.slice(0, i).trim();\r\n                }\r\n                else {\r\n                    pushFilter();\r\n                }\r\n            }\r\n            else {\r\n                switch (c) {\r\n                    case 0x22:\r\n                        inDouble = true;\r\n                        break; // \"\r\n                    case 0x27:\r\n                        inSingle = true;\r\n                        break; // '\r\n                    case 0x60:\r\n                        inTemplateString = true;\r\n                        break; // `\r\n                    case 0x28:\r\n                        paren++;\r\n                        break; // (\r\n                    case 0x29:\r\n                        paren--;\r\n                        break; // )\r\n                    case 0x5B:\r\n                        square++;\r\n                        break; // [\r\n                    case 0x5D:\r\n                        square--;\r\n                        break; // ]\r\n                    case 0x7B:\r\n                        curly++;\r\n                        break; // {\r\n                    case 0x7D:\r\n                        curly--;\r\n                        break; // }\r\n                }\r\n                if (c === 0x2f) { // /\r\n                    var j = i - 1;\r\n                    var p = (void 0);\r\n                    // find first non-whitespace prev char\r\n                    for (; j >= 0; j--) {\r\n                        p = exp.charAt(j);\r\n                        if (p !== ' ') {\r\n                            break;\r\n                        }\r\n                    }\r\n                    if (!p || !validDivisionCharRE.test(p)) {\r\n                        inRegex = true;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        if (expression === undefined) {\r\n            expression = exp.slice(0, i).trim();\r\n        }\r\n        else if (lastFilterIndex !== 0) {\r\n            pushFilter();\r\n        }\r\n        function pushFilter() {\r\n            (filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim());\r\n            lastFilterIndex = i + 1;\r\n        }\r\n        if (filters) {\r\n            for (i = 0; i < filters.length; i++) {\r\n                expression = wrapFilter(expression, filters[i]);\r\n            }\r\n        }\r\n        return expression;\r\n    }\r\n    function wrapFilter(exp, filter) {\r\n        var i = filter.indexOf('(');\r\n        if (i < 0) {\r\n            // _f: resolveFilter\r\n            return (\"_f(\\\"\" + filter + \"\\\")(\" + exp + \")\");\r\n        }\r\n        else {\r\n            var name = filter.slice(0, i);\r\n            var args = filter.slice(i + 1);\r\n            return (\"_f(\\\"\" + name + \"\\\")(\" + exp + (args !== ')' ? ',' + args : args));\r\n        }\r\n    }\r\n    var defaultTagRE = /\\{\\{((?:.|\\r?\\n)+?)\\}\\}/g;\r\n    var regexEscapeRE = /[-.*+?^${}()|[\\]\\/\\\\]/g;\r\n    /**\r\n     * Create a cached version of a pure function.\r\n     */\r\n    function cached(fn) {\r\n        var cache = Object.create(null);\r\n        return (function cachedFn(str) {\r\n            var hit = cache[str];\r\n            return hit || (cache[str] = fn(str));\r\n        });\r\n    }\r\n    var buildRegex = cached(function (delimiters) {\r\n        var open = delimiters[0].replace(regexEscapeRE, '\\\\$&');\r\n        var close = delimiters[1].replace(regexEscapeRE, '\\\\$&');\r\n        return new RegExp(open + '((?:.|\\\\n)+?)' + close, 'g');\r\n    });\r\n    function parseText(text, delimiters) {\r\n        var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE;\r\n        if (!tagRE.test(text)) {\r\n            console.error(tagRE, text);\r\n            return;\r\n        }\r\n        var tokens = [];\r\n        var rawTokens = [];\r\n        var lastIndex = tagRE.lastIndex = 0;\r\n        var match, index, tokenValue;\r\n        while ((match = tagRE.exec(text))) {\r\n            index = match.index;\r\n            // push text token\r\n            if (index > lastIndex) {\r\n                rawTokens.push(tokenValue = text.slice(lastIndex, index));\r\n                tokens.push(JSON.stringify(tokenValue));\r\n            }\r\n            // tag token\r\n            var exp = parseFilters(match[1].trim());\r\n            tokens.push((\"_s(\" + exp + \")\"));\r\n            rawTokens.push({ '@binding': exp });\r\n            lastIndex = index + match[0].length;\r\n        }\r\n        if (lastIndex < text.length) {\r\n            rawTokens.push(tokenValue = text.slice(lastIndex));\r\n            tokens.push(JSON.stringify(tokenValue));\r\n        }\r\n        return {\r\n            expression: tokens.join('+'),\r\n            tokens: rawTokens\r\n        };\r\n    }\r\n    class ViewModel {\r\n        static create(data) {\r\n            let vm = new ViewModel(data);\r\n            return vm;\r\n        }\r\n        constructor(data) {\r\n            Object.defineProperty(this, \"_watchers\", {\r\n                value: [],\r\n                enumerable: false,\r\n                writable: true,\r\n                configurable: false,\r\n            });\r\n            Object.defineProperty(this, \"_isVue\", {\r\n                value: true,\r\n                enumerable: false,\r\n                writable: false,\r\n                configurable: false,\r\n            });\r\n            let keys = Object.keys(data);\r\n            let i = keys.length;\r\n            while (i--) {\r\n                let key = keys[i];\r\n                Object.defineProperty(this, key, {\r\n                    enumerable: true,\r\n                    configurable: true,\r\n                    get: function () {\r\n                        return data[key];\r\n                    },\r\n                    set: function (val) {\r\n                        data[key] = val;\r\n                    },\r\n                });\r\n            }\r\n            observe(data, true);\r\n        }\r\n        static $toString(v) {\r\n            return new String(v);\r\n        }\r\n        // 临时代码\r\n        static flush() {\r\n            flushSchedulerQueue();\r\n        }\r\n        static expression(vm, expression, cb) {\r\n            if (vm instanceof ViewModel) {\r\n                let exp = parseText(expression, null);\r\n                let fn = function () { return eval(\"(function (_s) { return \" + exp.expression + \"; })\").call(this, ViewModel.$toString); };\r\n                return new Watcher(vm, fn, cb);\r\n            }\r\n        }\r\n        static field(vm, path, cb) {\r\n            if (vm instanceof ViewModel) {\r\n                return new Watcher(vm, path, cb);\r\n            }\r\n        }\r\n    }\r\n    exports.ViewModel = ViewModel;\r\n});\r\ndefine(\"plover/jsx/element\", [\"require\", \"exports\", \"UnityEngine.UI\", \"plover/jsx/vue\"], function (require, exports, UnityEngine_UI_1, vue_1) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.JSXText = exports.JSXWidget = exports.JSXCompoundNode = exports.registerElement = exports.createElement = exports.element = exports.findUIComponent = exports.JSXNode = void 0;\r\n    let elementActivators = {};\r\n    class JSXNode {\r\n        get parent() { return this._parent; }\r\n        set parent(value) {\r\n            if (this._parent != value) {\r\n                this._parent = value;\r\n                this.onParentSet();\r\n            }\r\n        }\r\n        get widget() {\r\n            let p = this._parent;\r\n            while (p) {\r\n                if (p instanceof JSXWidget) {\r\n                    return p;\r\n                }\r\n                p = p._parent;\r\n            }\r\n        }\r\n    }\r\n    exports.JSXNode = JSXNode;\r\n    function findUIComponent(transform, name, type) {\r\n        let n = transform.childCount;\r\n        for (let i = 0; i < n; i++) {\r\n            let child = transform.GetChild(i);\r\n            if (child.name == name) {\r\n                let com = child.GetComponent(type);\r\n                if (com) {\r\n                    return com;\r\n                }\r\n            }\r\n            let com = findUIComponent(child, name, type);\r\n            if (com) {\r\n                return com;\r\n            }\r\n        }\r\n    }\r\n    exports.findUIComponent = findUIComponent;\r\n    function element(name) {\r\n        return function (target) {\r\n            registerElement(name, target);\r\n        };\r\n    }\r\n    exports.element = element;\r\n    function createElement(name, attributes, ...children) {\r\n        let act = elementActivators[name];\r\n        if (typeof act !== \"undefined\") {\r\n            let element = new act();\r\n            element.init(attributes, ...children);\r\n            return element;\r\n        }\r\n    }\r\n    exports.createElement = createElement;\r\n    function registerElement(name, activator) {\r\n        elementActivators[name] = activator;\r\n    }\r\n    exports.registerElement = registerElement;\r\n    class JSXCompoundNode extends JSXNode {\r\n        init(attributes, ...children) {\r\n            this._children = children;\r\n            for (let i = 0; i < this._children.length; i++) {\r\n                let child = this._children[i];\r\n                child.parent = this;\r\n            }\r\n        }\r\n        evaluate() {\r\n            for (let i = 0; i < this._children.length; i++) {\r\n                let child = this._children[i];\r\n                child.evaluate();\r\n            }\r\n        }\r\n        destroy() {\r\n            for (let i = 0; i < this._children.length; i++) {\r\n                let child = this._children[i];\r\n                child.destroy();\r\n            }\r\n        }\r\n    }\r\n    exports.JSXCompoundNode = JSXCompoundNode;\r\n    // export interface IWidgetInstance {\r\n    //     readonly gameObject: GameObject;\r\n    //     readonly data: any;\r\n    // }\r\n    let JSXWidget = class JSXWidget extends JSXCompoundNode {\r\n        get instance() { return this._instance; }\r\n        get data() { return this._instance.data; }\r\n        init(attributes, ...children) {\r\n            this._instance = attributes.class;\r\n            super.init(attributes, ...children);\r\n        }\r\n        onParentSet() {\r\n        }\r\n    };\r\n    JSXWidget = __decorate([\r\n        element(\"widget\")\r\n    ], JSXWidget);\r\n    exports.JSXWidget = JSXWidget;\r\n    let JSXText = class JSXText extends JSXNode {\r\n        init(attributes, ...children) {\r\n            if (attributes) {\r\n                this._name = attributes.name;\r\n                this._text = attributes.text;\r\n            }\r\n        }\r\n        onParentSet() {\r\n            this._component = findUIComponent(this.widget.instance.transform, this._name, UnityEngine_UI_1.Text);\r\n            this._watcher = vue_1.ViewModel.expression(this.widget.data, this._text, this.onValueChanged.bind(this));\r\n        }\r\n        onValueChanged(value) {\r\n            this._component.text = value;\r\n        }\r\n        evaluate() {\r\n            if (this._watcher) {\r\n                this._watcher.evaluate();\r\n            }\r\n        }\r\n        destroy() {\r\n            if (this._watcher) {\r\n                this._watcher.teardown();\r\n                this._watcher = null;\r\n            }\r\n        }\r\n    };\r\n    JSXText = __decorate([\r\n        element(\"text\")\r\n    ], JSXText);\r\n    exports.JSXText = JSXText;\r\n});\r\ndefine(\"plover/jsx/bridge\", [\"require\", \"exports\", \"UnityEngine\", \"plover/runtime/class_decorators\"], function (require, exports, UnityEngine_15, class_decorators_2) {\r\n    \"use strict\";\r\n    Object.defineProperty(exports, \"__esModule\", { value: true });\r\n    exports.JSXWidgetBridge = void 0;\r\n    let JSXWidgetBridge = class JSXWidgetBridge extends UnityEngine_15.MonoBehaviour {\r\n        get data() { return null; }\r\n        OnDestroy() {\r\n            if (this._widget) {\r\n                this._widget.destroy();\r\n            }\r\n        }\r\n    };\r\n    JSXWidgetBridge = __decorate([\r\n        class_decorators_2.ScriptType()\r\n    ], JSXWidgetBridge);\r\n    exports.JSXWidgetBridge = JSXWidgetBridge;\r\n});\r\n// // not implemented yet, it's imagination for fun\r\n// console.log(\"test jsx\");\r\n// let userWidget = <widget>\r\n//     <label name=\"test\" bind=\"expression {test.value}\" />\r\n//     <list name=\"list_test\" bind=\"mydata.mylist\" entry-class=\"SomeType\" />\r\n//     <button name=\"button_test\" bind=\"mydata.myaction\" onclick=\"this.onclick\" />\r\n// </widget>\r\n//# sourceMappingURL=plover.js.map"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Resources/plover.js.txt.meta",
    "content": "fileFormatVersion: 2\nguid: 2cff5ac341500d94781fc0e6402e4adc\nTextScriptImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Resources.meta",
    "content": "fileFormatVersion: 2\nguid: ba9945c54e1383241a1589d598219e45\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Attributes.cs",
    "content": "using System;\r\n\r\nnamespace QuickJS\r\n{\r\n    [Flags]\r\n    public enum JSHotfixFlags\r\n    {\r\n        Default = 0, // 替换\r\n        Before = 1,  // 前置执行\r\n        After = 2,   // 后置执行\r\n\r\n        Full = Before | After,\r\n    }\r\n\r\n    [AttributeUsage(AttributeTargets.Class,\r\n                    AllowMultiple = false,\r\n                    Inherited = false)]\r\n    public class JSHotfixAttribute : Attribute\r\n    {\r\n        public JSHotfixFlags flags { get; set; }\r\n\r\n        public JSHotfixAttribute()\r\n        {\r\n        }\r\n\r\n        public JSHotfixAttribute(JSHotfixFlags flags)\r\n        {\r\n            this.flags = flags;\r\n        }\r\n    }\r\n\r\n    // 指定类型生成绑定代码\r\n    [AttributeUsage(AttributeTargets.Class\r\n                  | AttributeTargets.Struct\r\n                  | AttributeTargets.Enum\r\n                  | AttributeTargets.Interface,\r\n                    AllowMultiple = false,\r\n                    Inherited = false)]\r\n    public class JSTypeAttribute : Attribute\r\n    {\r\n    }\r\n\r\n    // 不产生包装, 直接导出 (签名必须符合 JSCFunction)\r\n    // 这种方式导出的方法不支持重载, 需要在方法内部自行处理变参\r\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]\r\n    public class JSCFunctionAttribute : Attribute\r\n    {\r\n        // 是否静态\r\n        public bool isStatic { get; set; }\r\n\r\n        // [可选] d.ts 对应输出信息\r\n        public string[] difinitions { get; set; }\r\n\r\n        public JSCFunctionAttribute()\r\n        {\r\n        }\r\n\r\n        public JSCFunctionAttribute(bool isStatic, params string[] difinitions)\r\n        {\r\n            this.isStatic = isStatic;\r\n            this.difinitions = difinitions;\r\n        }\r\n\r\n        public JSCFunctionAttribute(params string[] difinitions)\r\n        {\r\n            this.difinitions = difinitions;\r\n        }\r\n    }\r\n\r\n    [AttributeUsage(AttributeTargets.Class |\r\n                    AttributeTargets.Struct |\r\n                    AttributeTargets.Interface |\r\n                    AttributeTargets.Field |\r\n                    AttributeTargets.Method |\r\n                    AttributeTargets.Event |\r\n                    AttributeTargets.Constructor |\r\n                    AttributeTargets.Property,\r\n                    AllowMultiple = false,\r\n                    Inherited = false)]\r\n    public class JSOmitAttribute : Attribute\r\n    {\r\n    }\r\n\r\n    // JS绑定代码\r\n    [AttributeUsage(AttributeTargets.Class,\r\n                    AllowMultiple = false,\r\n                    Inherited = false)]\r\n    public class JSBindingAttribute : Attribute\r\n    {\r\n    }\r\n\r\n    // // 强制转换为 JS Array\r\n    // [AttributeUsage(AttributeTargets.Parameter\r\n    //               | AttributeTargets.ReturnValue,\r\n    //                 AllowMultiple = false)]\r\n    // public class JSArrayAttribute : Attribute\r\n    // {\r\n    // }\r\n\r\n    // // 在JS中指定名称\r\n    // [AttributeUsage(AttributeTargets.Class\r\n    //               | AttributeTargets.Struct\r\n    //               | AttributeTargets.Enum\r\n    //               | AttributeTargets.Field\r\n    //               | AttributeTargets.Method\r\n    //               | AttributeTargets.Property,\r\n    //                 AllowMultiple = false)]\r\n    // public class JSNamingAttribute : Attribute\r\n    // {\r\n    //     public string name { get; set; }\r\n    //     public JSNamingAttribute(string name)\r\n    //     {\r\n    //         this.name = name;\r\n    //     }\r\n    // }\r\n\r\n    // // 用于标记 struct 非静态方法, 表明该方法调用将修改 struct 自身 (在 js 中产生一次 rebind)\r\n    // [AttributeUsage(AttributeTargets.Method,\r\n    //                 AllowMultiple = false)]\r\n    // public class JSMutableAttribute : Attribute\r\n    // {\r\n    // }\r\n\r\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]\r\n    public class JSDelegateAttribute : Attribute\r\n    {\r\n        public Type target { get; set; }\r\n\r\n        public JSDelegateAttribute(Type target)\r\n        {\r\n            this.target = target;\r\n        }\r\n    }\r\n\r\n    [AttributeUsage(AttributeTargets.Class\r\n                  | AttributeTargets.Struct\r\n                  | AttributeTargets.Enum\r\n                  | AttributeTargets.Field\r\n                  | AttributeTargets.Method\r\n                  | AttributeTargets.Property\r\n                  | AttributeTargets.Constructor,\r\n                    AllowMultiple = false)]\r\n    public class JSDocAttribute : Attribute\r\n    {\r\n        public string[] lines { get; set; }\r\n\r\n        public JSDocAttribute(string text)\r\n        {\r\n            this.lines = new string[] { text };\r\n        }\r\n\r\n        public JSDocAttribute(params string[] lines)\r\n        {\r\n            this.lines = lines;\r\n        }\r\n    }\r\n\r\n    /// <summary>\r\n    /// NOT_IMPLEMENTED\r\n    /// </summary>\r\n    [AttributeUsage(AttributeTargets.Parameter\r\n                  | AttributeTargets.ReturnValue,\r\n                    AllowMultiple = false)]\r\n    public class JSUseStringCacheAttribute : Attribute\r\n    {\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Attributes.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 75ecefcb47671264a8e8810a78309fde\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ClassBind.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using Native;\r\n\r\n    public delegate ClassDecl ClassBind(TypeRegister register);\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ClassBind.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 9f65852ea23cfff49879635006ac4cf2\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ClassDecl.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\nusing QuickJS.Native;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public struct OperatorDef\r\n    {\r\n        public string op;\r\n        public JSValue value;\r\n\r\n        public OperatorDef(string op, JSValue value)\r\n        {\r\n            this.op = op;\r\n            this.value = value;\r\n        }\r\n    }\r\n\r\n    public struct CrossOperatorDef\r\n    {\r\n        public Type type;\r\n        public List<OperatorDef> operators;\r\n\r\n        public CrossOperatorDef(Type type)\r\n        {\r\n            this.type = type;\r\n            this.operators = new List<OperatorDef>();\r\n        }\r\n    }\r\n\r\n    public struct ClassDecl\r\n    {\r\n        private TypeRegister _register;\r\n        private ScriptContext _context;\r\n        private JSValue _ctor;\r\n        private JSValue _proto;\r\n        private Type _type;\r\n\r\n        public ClassDecl(TypeRegister register, JSValue ctorVal, JSValue protoVal, Type type)\r\n        {\r\n            _type = type;\r\n            _register = register;\r\n            _context = _register.GetContext();\r\n            _ctor = JSApi.JS_DupValue(_context, ctorVal);\r\n            _proto = JSApi.JS_DupValue(_context, protoVal);\r\n        }\r\n\r\n        /// <summary>\r\n        /// obtain the raw JS constructor.\r\n        /// NOTE: the return value is already duplicated\r\n        /// </summary>\r\n        public JSValue GetConstructor()\r\n        {\r\n            return JSApi.JS_DupValue(_context, _ctor);\r\n        }\r\n\r\n        public void Close()\r\n        {\r\n            if (_context != null)\r\n            {\r\n                var ctx = (JSContext)_context;\r\n\r\n                JSApi.JS_FreeValue(ctx, _ctor);\r\n                JSApi.JS_FreeValue(ctx, _proto);\r\n                _ctor = JSApi.JS_UNDEFINED;\r\n                _proto = JSApi.JS_UNDEFINED;\r\n                _context = null;\r\n            }\r\n        }\r\n\r\n        public void AddSelfOperator(string op, IDynamicMethod func)\r\n        {\r\n            _register.RegisterOperator(_type, op, func);\r\n        }\r\n\r\n        public void AddLeftOperator(string op, IDynamicMethod func, Type type)\r\n        {\r\n            _register.RegisterOperator(_type, op, func, true, type);\r\n        }\r\n\r\n        public void AddRightOperator(string op, IDynamicMethod func, Type type)\r\n        {\r\n            _register.RegisterOperator(_type, op, func, false, type);\r\n        }\r\n\r\n        public void AddSelfOperator(string op, JSCFunction func, int length)\r\n        {\r\n            _register.RegisterOperator(_type, op, func, length);\r\n        }\r\n\r\n        public void AddLeftOperator(string op, JSCFunction func, int length, Type type)\r\n        {\r\n            _register.RegisterOperator(_type, op, func, length, true, type);\r\n        }\r\n\r\n        public void AddRightOperator(string op, JSCFunction func, int length, Type type)\r\n        {\r\n            _register.RegisterOperator(_type, op, func, length, false, type);\r\n        }\r\n\r\n        public void AddFunction(string name, JSCFunctionMagic func, int length, int magic)\r\n        {\r\n            AddMethod(true, name, func, length, magic);\r\n        }\r\n\r\n        public void AddMethod(bool bStatic, string name, JSCFunctionMagic func, int length, int magic)\r\n        {\r\n            var nameAtom = _register.GetAtom(name);\r\n            var funcVal = JSApi.JSB_NewCFunctionMagic(_context, func, nameAtom, length, magic);\r\n            JSApi.JS_DefinePropertyValue(_context, bStatic ? _ctor : _proto, nameAtom, funcVal);\r\n        }\r\n\r\n        public void AddFunction(string name, JSCFunction func)\r\n        {\r\n            AddMethod(true, name, func);\r\n        }\r\n\r\n        public void AddMethod(bool bStatic, string name, JSCFunction func)\r\n        {\r\n            var nameAtom = _register.GetAtom(name);\r\n            var funcVal = JSApi.JSB_NewCFunction(_context, func, nameAtom, 0);\r\n            JSApi.JS_DefinePropertyValue(_context, bStatic ? _ctor : _proto, nameAtom, funcVal);\r\n        }\r\n\r\n        public void AddFunction(string name, JSCFunction func, int length)\r\n        {\r\n            AddMethod(true, name, func, length);\r\n        }\r\n\r\n        public void AddMethod(bool bStatic, string name, JSCFunction func, int length)\r\n        {\r\n            var nameAtom = _register.GetAtom(name);\r\n            var funcVal = JSApi.JSB_NewCFunction(_context, func, nameAtom, length);\r\n            JSApi.JS_DefinePropertyValue(_context, bStatic ? _ctor : _proto, nameAtom, funcVal);\r\n        }\r\n\r\n        public void AddStaticEvent(string name, JSCFunction adder, JSCFunction remover)\r\n        {\r\n            var nameAtom = _register.GetAtom(name);\r\n            var op = JSApi.JS_NewObject(_context);\r\n            var adderFunc = JSApi.JSB_NewCFunction(_context, adder, _register.GetAtom(\"on\"), 1);\r\n            JSApi.JS_SetProperty(_context, op, _register.GetAtom(\"on\"), adderFunc);\r\n            var removerFunc = JSApi.JSB_NewCFunction(_context, remover, _register.GetAtom(\"off\"), 1);\r\n            JSApi.JS_SetProperty(_context, op, _register.GetAtom(\"off\"), removerFunc);\r\n            JSApi.JS_SetProperty(_context, _ctor, nameAtom, op);\r\n        }\r\n\r\n        public void AddRawMethod(bool bStatic, string name, JSCFunction method)\r\n        {\r\n            var nameAtom = _register.GetAtom(name);\r\n            var db = _register.GetTypeDB();\r\n            var funcVal = db.NewDynamicMethod(nameAtom, method);\r\n            JSApi.JS_DefinePropertyValue(_context, bStatic ? _ctor : _proto, nameAtom, funcVal);\r\n        }\r\n\r\n        public void AddMethod(bool bStatic, string name, IDynamicMethod method)\r\n        {\r\n            var nameAtom = _register.GetAtom(name);\r\n            var db = _register.GetTypeDB();\r\n            var funcVal = db.NewDynamicMethod(nameAtom, method);\r\n            JSApi.JS_DefinePropertyValue(_context, bStatic ? _ctor : _proto, nameAtom, funcVal);\r\n        }\r\n\r\n        public void AddField(bool bStatic, string name, JSGetterCFunction getter, JSSetterCFunction setter)\r\n        {\r\n            AddProperty(bStatic, name, getter, setter);\r\n        }\r\n\r\n        public void AddField(bool bStatic, string name, IDynamicField field)\r\n        {\r\n            AddProperty(bStatic, name, field);\r\n        }\r\n\r\n        public void AddProperty(bool bStatic, string name, JSGetterCFunction getter, JSSetterCFunction setter)\r\n        {\r\n            var ctx = (JSContext)_context;\r\n            var nameAtom = _register.GetAtom(name);\r\n            var getterVal = JSApi.JSB_NewGetter(ctx, getter, nameAtom);\r\n            var setterVal = JSApi.JSB_NewSetter(ctx, setter, nameAtom);\r\n            var rs = JSApi.JS_DefineProperty(ctx, bStatic ? _ctor : _proto, nameAtom, getterVal, setterVal);\r\n\r\n            if (rs != 1)\r\n            {\r\n                Diagnostics.Logger.Default.Error(\"define property failed: {0}\", ctx.GetExceptionString());\r\n            }\r\n            JSApi.JS_FreeValue(ctx, getterVal);\r\n            JSApi.JS_FreeValue(ctx, setterVal);\r\n        }\r\n\r\n        public void AddProperty(bool bStatic, string name, IDynamicField field)\r\n        {\r\n            var ctx = (JSContext)_context;\r\n            var nameAtom = _register.GetAtom(name);\r\n            var db = _register.GetTypeDB();\r\n            var getterVal = JSApi.JS_UNDEFINED;\r\n            var setterVal = JSApi.JS_UNDEFINED;\r\n\r\n            db.NewDynamicFieldAccess(nameAtom, field, out getterVal, out setterVal);\r\n            var rs = JSApi.JS_DefineProperty(ctx, bStatic ? _ctor : _proto, nameAtom, getterVal, setterVal);\r\n            if (rs != 1)\r\n            {\r\n                Diagnostics.Logger.Default.Error(\"define property failed: {0}\", ctx.GetExceptionString());\r\n            }\r\n            JSApi.JS_FreeValue(ctx, getterVal);\r\n            JSApi.JS_FreeValue(ctx, setterVal);\r\n        }\r\n\r\n        public void AddValue(string name, JSValue v)\r\n        {\r\n            var nameAtom = _register.GetAtom(name);\r\n            JSApi.JS_DefinePropertyValue(_context, _ctor, nameAtom, v);\r\n        }\r\n\r\n        #region Registration for const values\r\n        public void AddConstValue(string name, bool v)\r\n        {\r\n            var val = JSApi.JS_NewBool(_context, v);\r\n            var nameAtom = _register.GetAtom(name);\r\n            JSApi.JS_DefineConstPropertyValue(_context, _ctor, nameAtom, val);\r\n        }\r\n\r\n        public void AddConstValue(string name, char v)\r\n        {\r\n            var val = JSApi.JS_NewInt32(_context, v);\r\n            var nameAtom = _register.GetAtom(name);\r\n            JSApi.JS_DefineConstPropertyValue(_context, _ctor, nameAtom, val);\r\n        }\r\n\r\n        public void AddConstValue(string name, byte v)\r\n        {\r\n            var val = JSApi.JS_NewInt32(_context, v);\r\n            var nameAtom = _register.GetAtom(name);\r\n            JSApi.JS_DefineConstPropertyValue(_context, _ctor, nameAtom, val);\r\n        }\r\n\r\n        public void AddConstValue(string name, sbyte v)\r\n        {\r\n            var val = JSApi.JS_NewInt32(_context, v);\r\n            var nameAtom = _register.GetAtom(name);\r\n            JSApi.JS_DefineConstPropertyValue(_context, _ctor, nameAtom, val);\r\n        }\r\n\r\n        public void AddConstValue(string name, short v)\r\n        {\r\n            var val = JSApi.JS_NewInt32(_context, v);\r\n            var nameAtom = _register.GetAtom(name);\r\n            JSApi.JS_DefineConstPropertyValue(_context, _ctor, nameAtom, val);\r\n        }\r\n\r\n        public void AddConstValue(string name, ushort v)\r\n        {\r\n            var val = JSApi.JS_NewInt32(_context, v);\r\n            var nameAtom = _register.GetAtom(name);\r\n            JSApi.JS_DefineConstPropertyValue(_context, _ctor, nameAtom, val);\r\n        }\r\n\r\n        public void AddConstValue(string name, int v)\r\n        {\r\n            var val = JSApi.JS_NewInt32(_context, v);\r\n            var nameAtom = _register.GetAtom(name);\r\n            JSApi.JS_DefineConstPropertyValue(_context, _ctor, nameAtom, val);\r\n        }\r\n\r\n        public void AddConstValue(string name, uint v)\r\n        {\r\n            var val = JSApi.JS_NewUint32(_context, v);\r\n            var nameAtom = _register.GetAtom(name);\r\n            JSApi.JS_DefineConstPropertyValue(_context, _ctor, nameAtom, val);\r\n        }\r\n\r\n        public void AddConstValue(string name, double v)\r\n        {\r\n            var val = JSApi.JS_NewFloat64(_context, v);\r\n            var nameAtom = _register.GetAtom(name);\r\n            JSApi.JS_DefineConstPropertyValue(_context, _ctor, nameAtom, val);\r\n        }\r\n\r\n        public void AddConstValue(string name, float v)\r\n        {\r\n            var val = JSApi.JS_NewFloat64(_context, v);\r\n            var nameAtom = _register.GetAtom(name);\r\n            JSApi.JS_DefineConstPropertyValue(_context, _ctor, nameAtom, val);\r\n        }\r\n\r\n        public void AddConstValue(string name, string v)\r\n        {\r\n            var val = JSNative.NewString(_context, v);\r\n            var nameAtom = _register.GetAtom(name);\r\n            JSApi.JS_DefineConstPropertyValue(_context, _ctor, nameAtom, val);\r\n        }\r\n        #endregion\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ClassDecl.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: c1c658a9dab4416fb8ea4a103a8451cf\r\ntimeCreated: 1591010003"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/CommonFix.cs",
    "content": "using System;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using QuickJS.Native;\r\n    using QuickJS.Errors;\r\n\r\n    public static class CommonFix\r\n    {\r\n        [MonoPInvokeCallbackAttribute(typeof(QuickJS.Native.JSCFunctionMagic))]\r\n        public static JSValue CrossBindConstructor(JSContext ctx, JSValue new_target, int argc, JSValue[] argv, int magic)\r\n        {\r\n            try\r\n            {\r\n                if (argc == 0)\r\n                {\r\n                    return JSApi.jsb_crossbind_constructor(ctx, new_target);\r\n                }\r\n                throw new NoSuitableMethodException(\"constructor\", argc);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/CommonFix.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: a4af49a4e4417644aa684bcbd664e65f\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/DefaultBinder.cs",
    "content": "using System;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public delegate void BindAction(ScriptRuntime runtime);\r\n\r\n    public static class DefaultBinder\r\n    {\r\n        /// <summary>\r\n        /// determine which type binding mode to use (between staticbind and reflectbind)\r\n        /// </summary>\r\n        public static BindAction GetBinder(bool useReflectBind)\r\n        {\r\n            return useReflectBind && IsReflectBindingSupported() ? (BindAction)ReflectBind : StaticBind;\r\n        }\r\n\r\n        public static BindAction GetBinder(string bindingMethod)\r\n        {\r\n            switch (bindingMethod.ToLower().Replace(\" \", \"\").Replace(\"-\", \"\"))\r\n            {\r\n                case \"reflectbind\": return ReflectBind;\r\n                case \"inmemorybind\": return InMemoryBind;\r\n                default: return StaticBind;\r\n            }\r\n        }\r\n\r\n        public static bool IsStaticBinding(BindAction bindAction)\r\n        {\r\n            return bindAction == StaticBind;\r\n        }\r\n\r\n        public static BindAction StaticBind = (runtime) =>\r\n        {\r\n            var assemblies = AppDomain.CurrentDomain.GetAssemblies();\r\n            var typeName = $\"{Values.NamespaceOfStaticBinder}.{Values.ClassNameOfStaticBinder}\";\r\n            Type type = null;\r\n            for (var i = assemblies.Length - 1; i >= 0; --i)\r\n            {\r\n                var assembly = assemblies[i];\r\n                if (!assembly.IsDynamic)\r\n                {\r\n                    type = assembly.GetType(typeName);\r\n                    if (type != null)\r\n                    {\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n            _StaticBindInternal(runtime, type);\r\n        };\r\n\r\n        public static void _StaticBindInternal(ScriptRuntime runtime, Type type)\r\n        {\r\n            var bindAll = type?.GetMethod(Values.MethodNameOfStaticBinder, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);\r\n            if (bindAll == null)\r\n            {\r\n                Diagnostics.Logger.Binding.Error(\"generate binding code before run, or turn on ReflectBind\");\r\n                return;\r\n            }\r\n\r\n            var codeGenVersionField = type.GetField(\"CodeGenVersion\");\r\n            if (codeGenVersionField == null || !codeGenVersionField.IsStatic || !codeGenVersionField.IsLiteral || codeGenVersionField.FieldType != typeof(uint))\r\n            {\r\n                Diagnostics.Logger.Binding.Error(\"binding code version mismatch\");\r\n                return;\r\n            }\r\n\r\n            var codeGenVersion = (uint)codeGenVersionField.GetValue(null);\r\n            if (codeGenVersion != ScriptEngine.VERSION)\r\n            {\r\n                Diagnostics.Logger.Binding.Warning(\"CodeGenVersion: {0} != {1}\", codeGenVersion, ScriptEngine.VERSION);\r\n            }\r\n\r\n            bindAll.Invoke(null, new object[] { runtime });\r\n        }\r\n\r\n        public static bool IsReflectBindingSupported()\r\n        {\r\n            try\r\n            {\r\n                var UnityHelper = Binding.Values.FindType(\"QuickJS.Unity.UnityHelper\");\r\n                if (UnityHelper != null)\r\n                {\r\n                    var IsReflectBindingSupported = UnityHelper.GetMethod(\"IsReflectBindingSupported\");\r\n                    if (IsReflectBindingSupported != null && (bool)IsReflectBindingSupported.Invoke(null, null))\r\n                    {\r\n                        var InvokeReflectBinding = UnityHelper.GetMethod(\"InvokeReflectBinding\");\r\n                        return InvokeReflectBinding != null;\r\n                    }\r\n                }\r\n                return false;\r\n            }\r\n            catch (Exception)\r\n            {\r\n                return false;\r\n            }\r\n        }\r\n\r\n        public static void ReflectBind(ScriptRuntime runtime)\r\n        {\r\n            try\r\n            {\r\n                var typeName = \"QuickJS.Unity.UnityHelper\";\r\n                var methodName = \"InvokeReflectBinding\";\r\n                var UnityHelper = Binding.Values.FindType(typeName);\r\n                if (UnityHelper != null)\r\n                {\r\n                    var IsReflectBindingSupported = UnityHelper.GetMethod(\"IsReflectBindingSupported\");\r\n                    if (IsReflectBindingSupported != null && (bool)IsReflectBindingSupported.Invoke(null, null))\r\n                    {\r\n                        var InvokeReflectBinding = UnityHelper.GetMethod(methodName);\r\n                        if (InvokeReflectBinding != null)\r\n                        {\r\n                            InvokeReflectBinding.Invoke(null, new object[] { runtime });\r\n                            return;\r\n                        }\r\n                    }\r\n                }\r\n                throw new Exception($\"failed to invoke {typeName}.{methodName}\");\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                Diagnostics.Logger.Binding.Exception(\"fallback to StaticBind mode\", exception);\r\n                StaticBind(runtime);\r\n            }\r\n        }\r\n\r\n        public static void InMemoryBind(ScriptRuntime runtime)\r\n        {\r\n            try\r\n            {\r\n                var typeName = \"QuickJS.Unity.UnityHelper\";\r\n                var methodName = \"InvokeInMemoryBinding\";\r\n                var UnityHelper = Binding.Values.FindType(typeName);\r\n                if (UnityHelper != null)\r\n                {\r\n                    var IsInMemoryBindingSupported = UnityHelper.GetMethod(\"IsInMemoryBindingSupported\");\r\n                    if (IsInMemoryBindingSupported != null && (bool)IsInMemoryBindingSupported.Invoke(null, null))\r\n                    {\r\n                        var InvokeInMemoryBinding = UnityHelper.GetMethod(methodName);\r\n                        if (InvokeInMemoryBinding != null)\r\n                        {\r\n                            InvokeInMemoryBinding.Invoke(null, new object[] { runtime });\r\n                            return;\r\n                        }\r\n                    }\r\n                }\r\n                throw new Exception($\"failed to invoke {typeName}.{methodName}\");\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                Diagnostics.Logger.Binding.Exception(\"fallback to ReflectBind mode\", exception);\r\n                ReflectBind(runtime);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/DefaultBinder.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: d71c3c9391c8989449649ef8e04d4d16\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/DynamicDelegateOp.cs",
    "content": "using System;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using QuickJS.Native;\r\n    using QuickJS.Errors;\r\n\r\n    // 委托 add/remove/set/get 操作包装函数\r\n    public class DynamicFieldDelegateOp : IDynamicMethod\r\n    {\r\n        private string _varName;\r\n        private DynamicType _type;\r\n        private FieldInfo _fieldInfo;\r\n\r\n        public DynamicFieldDelegateOp(DynamicType type, FieldInfo fieldInfo, string varName)\r\n        {\r\n            _type = type;\r\n            _fieldInfo = fieldInfo;\r\n            _varName = string.IsNullOrEmpty(varName) ? _fieldInfo.Name : varName;\r\n        }\r\n\r\n        public JSValue Invoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (!_fieldInfo.IsPublic && !_type.privateAccess)\r\n            {\r\n                throw new InaccessibleMemberException(_fieldInfo.Name);\r\n            }\r\n\r\n            object self = null;\r\n            if (!_fieldInfo.IsStatic)\r\n            {\r\n                Values.js_get_cached_object(ctx, this_obj, out self);\r\n                if (!_type.CheckThis(self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n            }\r\n\r\n            try\r\n            {\r\n                var op = Values.js_parse_event_op(ctx, argv[0]);\r\n                var delegateType = _fieldInfo.FieldType;\r\n\r\n                switch (op)\r\n                {\r\n                    case Values.EVT_OP_ADD:\r\n                        {\r\n                            Delegate value;\r\n                            if (!Values.js_get_delegate(ctx, argv[1], delegateType, out value))\r\n                            {\r\n                                throw new ParameterException(_type.type, _varName, delegateType, 1);\r\n                            }\r\n                            var fValue = (Delegate)_fieldInfo.GetValue(self);\r\n                            _fieldInfo.SetValue(self, Delegate.Combine(fValue, value));\r\n                            return JSApi.JS_UNDEFINED;\r\n                        }\r\n                    case Values.EVT_OP_REMOVE:\r\n                        {\r\n                            Delegate value;\r\n                            if (!Values.js_get_delegate(ctx, argv[1], delegateType, out value))\r\n                            {\r\n                                throw new ParameterException(_type.type, _varName, delegateType, 1);\r\n                            }\r\n                            var fValue = (Delegate)_fieldInfo.GetValue(self);\r\n                            _fieldInfo.SetValue(self, Delegate.Remove(fValue, value));\r\n                            return JSApi.JS_UNDEFINED;\r\n                        }\r\n                    case Values.EVT_OP_SET:\r\n                        {\r\n                            Delegate value;\r\n                            if (!Values.js_get_delegate(ctx, argv[1], delegateType, out value))\r\n                            {\r\n                                throw new ParameterException(_type.type, _varName, delegateType, 1);\r\n                            }\r\n                            _fieldInfo.SetValue(self, value);\r\n                            return JSApi.JS_UNDEFINED;\r\n                        }\r\n                    case Values.EVT_OP_GET:\r\n                        {\r\n                            var ret = (Delegate)_fieldInfo.GetValue(self);\r\n                            return Values.js_push_delegate(ctx, ret);\r\n                        }\r\n                    default: throw new JSException(\"invalid event op\");\r\n                }\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n    }\r\n\r\n    public class DynamicPropertyDelegateOp : IDynamicMethod\r\n    {\r\n        private string _varName;\r\n        private DynamicType _type;\r\n        private PropertyInfo _propertyInfo;\r\n\r\n        public DynamicPropertyDelegateOp(DynamicType type, PropertyInfo propertyInfo, string varName)\r\n        {\r\n            _type = type;\r\n            _propertyInfo = propertyInfo;\r\n            _varName = string.IsNullOrEmpty(varName) ? _propertyInfo.Name : varName;\r\n        }\r\n\r\n        public JSValue Invoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            try\r\n            {\r\n                var op = Values.js_parse_event_op(ctx, argv[0]);\r\n                var delegateType = _propertyInfo.PropertyType;\r\n                var propInfoGetMethod = _propertyInfo.GetGetMethod(true);\r\n                var propInfoSetMethod = _propertyInfo.GetSetMethod(true);\r\n\r\n                switch (op)\r\n                {\r\n                    case Values.EVT_OP_ADD:\r\n                        {\r\n                            if (propInfoGetMethod == null || propInfoSetMethod == null)\r\n                            {\r\n                                throw new InaccessibleMemberException(_propertyInfo.Name);\r\n                            }\r\n\r\n                            if ((!propInfoGetMethod.IsPublic || !propInfoSetMethod.IsPublic) && !_type.privateAccess)\r\n                            {\r\n                                throw new InaccessibleMemberException(_propertyInfo.Name);\r\n                            }\r\n\r\n                            object self = null;\r\n                            if (!propInfoGetMethod.IsStatic)\r\n                            {\r\n                                Values.js_get_cached_object(ctx, this_obj, out self);\r\n                                if (!_type.CheckThis(self))\r\n                                {\r\n                                    throw new ThisBoundException();\r\n                                }\r\n                            }\r\n\r\n                            Delegate value;\r\n                            if (!Values.js_get_delegate(ctx, argv[1], delegateType, out value))\r\n                            {\r\n                                throw new ParameterException(_type.type, _varName, delegateType, 1);\r\n                            }\r\n                            var fValue = (Delegate)_propertyInfo.GetValue(self, null);\r\n                            _propertyInfo.SetValue(self, Delegate.Combine(fValue, value), null);\r\n                            return JSApi.JS_UNDEFINED;\r\n                        }\r\n                    case Values.EVT_OP_REMOVE:\r\n                        {\r\n                            if (propInfoGetMethod == null || propInfoSetMethod == null)\r\n                            {\r\n                                throw new InaccessibleMemberException(_propertyInfo.Name);\r\n                            }\r\n\r\n                            if ((!propInfoGetMethod.IsPublic || !propInfoSetMethod.IsPublic) && !_type.privateAccess)\r\n                            {\r\n                                throw new InaccessibleMemberException(_propertyInfo.Name);\r\n                            }\r\n\r\n                            object self = null;\r\n                            if (!propInfoGetMethod.IsStatic)\r\n                            {\r\n                                Values.js_get_cached_object(ctx, this_obj, out self);\r\n                                if (!_type.CheckThis(self))\r\n                                {\r\n                                    throw new ThisBoundException();\r\n                                }\r\n                            }\r\n\r\n                            Delegate value;\r\n                            if (!Values.js_get_delegate(ctx, argv[1], delegateType, out value))\r\n                            {\r\n                                throw new ParameterException(_type.type, _varName, delegateType, 1);\r\n                            }\r\n                            var fValue = (Delegate)_propertyInfo.GetValue(self, null);\r\n                            _propertyInfo.SetValue(self, Delegate.Remove(fValue, value), null);\r\n                            return JSApi.JS_UNDEFINED;\r\n                        }\r\n                    case Values.EVT_OP_SET:\r\n                        {\r\n                            if (propInfoSetMethod == null)\r\n                            {\r\n                                throw new InaccessibleMemberException(_propertyInfo.Name);\r\n                            }\r\n\r\n                            if (!propInfoSetMethod.IsPublic && !_type.privateAccess)\r\n                            {\r\n                                throw new InaccessibleMemberException(_propertyInfo.Name);\r\n                            }\r\n\r\n                            object self = null;\r\n                            if (!propInfoSetMethod.IsStatic)\r\n                            {\r\n                                Values.js_get_cached_object(ctx, this_obj, out self);\r\n                                if (!_type.CheckThis(self))\r\n                                {\r\n                                    throw new ThisBoundException();\r\n                                }\r\n                            }\r\n\r\n                            Delegate value;\r\n                            if (!Values.js_get_delegate(ctx, argv[1], delegateType, out value))\r\n                            {\r\n                                throw new ParameterException(_type.type, _varName, delegateType, 1);\r\n                            }\r\n                            _propertyInfo.SetValue(self, value, null);\r\n                            return JSApi.JS_UNDEFINED;\r\n                        }\r\n                    case Values.EVT_OP_GET:\r\n                        {\r\n                            if (propInfoGetMethod == null)\r\n                            {\r\n                                throw new InaccessibleMemberException(_propertyInfo.Name);\r\n                            }\r\n\r\n                            if (!propInfoGetMethod.IsPublic && !_type.privateAccess)\r\n                            {\r\n                                throw new InaccessibleMemberException(_propertyInfo.Name);\r\n                            }\r\n\r\n                            object self = null;\r\n                            if (!propInfoGetMethod.IsStatic)\r\n                            {\r\n                                Values.js_get_cached_object(ctx, this_obj, out self);\r\n                                if (!_type.CheckThis(self))\r\n                                {\r\n                                    throw new ThisBoundException();\r\n                                }\r\n                            }\r\n\r\n                            var ret = (Delegate)_propertyInfo.GetValue(self, null);\r\n                            return Values.js_push_delegate(ctx, ret);\r\n                        }\r\n                    default: throw new JSException(\"invalid event op\");\r\n                }\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n    }\r\n\r\n    public class DynamicEventDelegateOp : IDynamicMethod\r\n    {\r\n        private string _varName;\r\n        private DynamicType _type;\r\n        private EventInfo _eventInfo;\r\n\r\n        public DynamicEventDelegateOp(DynamicType type, EventInfo eventInfo, string varName)\r\n        {\r\n            _type = type;\r\n            _eventInfo = eventInfo;\r\n            _varName = string.IsNullOrEmpty(varName) ? _eventInfo.Name : varName;\r\n        }\r\n\r\n        public JSValue Invoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            try\r\n            {\r\n                var op = Values.js_parse_event_op(ctx, argv[0]);\r\n                var delegateType = _eventInfo.EventHandlerType;\r\n\r\n                switch (op)\r\n                {\r\n                    case Values.EVT_OP_ADD:\r\n                        {\r\n                            var eventInfoAddMethod = _eventInfo.GetAddMethod(true);\r\n                            if (eventInfoAddMethod == null)\r\n                            {\r\n                                throw new InaccessibleMemberException(_eventInfo.Name);\r\n                            }\r\n\r\n                            if (!eventInfoAddMethod.IsPublic && !_type.privateAccess)\r\n                            {\r\n                                throw new InaccessibleMemberException(_eventInfo.Name);\r\n                            }\r\n\r\n                            object self = null;\r\n                            if (!eventInfoAddMethod.IsStatic)\r\n                            {\r\n                                Values.js_get_cached_object(ctx, this_obj, out self);\r\n                                if (!_type.CheckThis(self))\r\n                                {\r\n                                    throw new ThisBoundException();\r\n                                }\r\n                            }\r\n\r\n                            Delegate value;\r\n                            if (!Values.js_get_delegate(ctx, argv[1], delegateType, out value))\r\n                            {\r\n                                throw new ParameterException(_type.type, _varName, delegateType, 1);\r\n                            }\r\n                            _eventInfo.AddEventHandler(self, value);\r\n                            return JSApi.JS_UNDEFINED;\r\n                        }\r\n                    case Values.EVT_OP_REMOVE:\r\n                        {\r\n                            var eventInfoRemoveMethod = _eventInfo.GetRemoveMethod(true);\r\n                            if (eventInfoRemoveMethod == null)\r\n                            {\r\n                                throw new InaccessibleMemberException(_eventInfo.Name);\r\n                            }\r\n\r\n                            if (!eventInfoRemoveMethod.IsPublic && !_type.privateAccess)\r\n                            {\r\n                                throw new InaccessibleMemberException(_eventInfo.Name);\r\n                            }\r\n\r\n                            object self = null;\r\n                            if (!eventInfoRemoveMethod.IsStatic)\r\n                            {\r\n                                Values.js_get_cached_object(ctx, this_obj, out self);\r\n                                if (!_type.CheckThis(self))\r\n                                {\r\n                                    throw new ThisBoundException();\r\n                                }\r\n                            }\r\n\r\n                            Delegate value;\r\n                            if (!Values.js_get_delegate(ctx, argv[1], delegateType, out value))\r\n                            {\r\n                                throw new ParameterException(_type.type, _varName, delegateType, 1);\r\n                            }\r\n                            _eventInfo.RemoveEventHandler(self, value);\r\n                            return JSApi.JS_UNDEFINED;\r\n                        }\r\n                    default: throw new JSException(\"invalid event op\");\r\n                }\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/DynamicDelegateOp.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 626bb6b9006a64844b9ff6f8ac1c7241\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/DynamicField.cs",
    "content": "using System;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using QuickJS.Native;\r\n    using QuickJS.Errors;\r\n\r\n    public interface IDynamicField\r\n    {\r\n        JSValue GetValue(JSContext ctx, JSValue this_val);\r\n        JSValue SetValue(JSContext ctx, JSValue this_val, JSValue val);\r\n    }\r\n\r\n    public class DynamicField : IDynamicField\r\n    {\r\n        private DynamicType _type;\r\n        private FieldInfo _fieldInfo;\r\n\r\n        public DynamicField(DynamicType type, FieldInfo fieldInfo)\r\n        {\r\n            _type = type;\r\n            _fieldInfo = fieldInfo;\r\n        }\r\n\r\n        public JSValue GetValue(JSContext ctx, JSValue this_obj)\r\n        {\r\n            if (!_fieldInfo.IsPublic && !_type.privateAccess)\r\n            {\r\n                throw new InaccessibleMemberException(_fieldInfo.Name);\r\n            }\r\n            object self = null;\r\n            if (!_fieldInfo.IsStatic)\r\n            {\r\n                if (!Values.js_get_var(ctx, this_obj, _type.type, out self) || !_type.CheckThis(self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n            }\r\n            \r\n            var rval = _fieldInfo.GetValue(self);\r\n            return Values.js_push_var(ctx, rval);\r\n        }\r\n\r\n        public JSValue SetValue(JSContext ctx, JSValue this_obj, JSValue val)\r\n        {\r\n            if (!_fieldInfo.IsPublic && !_type.privateAccess)\r\n            {\r\n                throw new InaccessibleMemberException(_fieldInfo.Name);\r\n            }\r\n            object self = null;\r\n            if (!_fieldInfo.IsStatic)\r\n            {\r\n                if (!Values.js_get_var(ctx, this_obj, _type.type, out self) || !_type.CheckThis(self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n            }\r\n            object t_val = null;\r\n            if (!Values.js_get_var(ctx, val, _fieldInfo.FieldType, out t_val))\r\n            {\r\n                throw new InvalidCastException();\r\n            }\r\n            _fieldInfo.SetValue(self, t_val);\r\n            \r\n            if (_type.type.IsValueType && !_fieldInfo.IsStatic)\r\n            {\r\n                Values.js_rebind_var(ctx, this_obj, _type.type, self);\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n    }\r\n\r\n    public class DynamicProperty : IDynamicField\r\n    {\r\n        private DynamicType _type;\r\n        private PropertyInfo _propertyInfo;\r\n\r\n        public DynamicProperty(DynamicType type, PropertyInfo propertyInfo)\r\n        {\r\n            _type = type;\r\n            _propertyInfo = propertyInfo;\r\n        }\r\n\r\n        public JSValue GetValue(JSContext ctx, JSValue this_obj)\r\n        {\r\n            var propInfoGetMethod = _propertyInfo.GetGetMethod(true);\r\n            if (propInfoGetMethod == null)\r\n            {\r\n                throw new NullReferenceException(\"property getter is null\");\r\n            }\r\n            if (!propInfoGetMethod.IsPublic && !_type.privateAccess)\r\n            {\r\n                throw new InaccessibleMemberException(_propertyInfo.Name);\r\n            }\r\n            object self = null;\r\n            if (!propInfoGetMethod.IsStatic)\r\n            {\r\n                if (!Values.js_get_var(ctx, this_obj, _type.type, out self) || !_type.CheckThis(self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n            }\r\n\r\n            var rval = _propertyInfo.GetValue(self, null);\r\n            return Values.js_push_var(ctx, rval);\r\n        }\r\n\r\n        public JSValue SetValue(JSContext ctx, JSValue this_obj, JSValue val)\r\n        {\r\n            var propInfoSetMethod = _propertyInfo.GetSetMethod(true);\r\n            if (propInfoSetMethod == null)\r\n            {\r\n                throw new NullReferenceException(\"property setter is null\");\r\n            }\r\n            if (!propInfoSetMethod.IsPublic && !_type.privateAccess)\r\n            {\r\n                throw new InaccessibleMemberException(_propertyInfo.Name);\r\n            }\r\n            object self = null;\r\n            if (!propInfoSetMethod.IsStatic)\r\n            {\r\n                if (!Values.js_get_var(ctx, this_obj, _type.type, out self) || !_type.CheckThis(self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n            }\r\n            object t_val = null;\r\n            if (!Values.js_get_var(ctx, val, _propertyInfo.PropertyType, out t_val))\r\n            {\r\n                throw new InvalidCastException();\r\n            }\r\n            _propertyInfo.SetValue(self, t_val, null);\r\n            if (_type.type.IsValueType && !propInfoSetMethod.IsStatic)\r\n            {\r\n                Values.js_rebind_var(ctx, this_obj, _type.type, self);\r\n            }\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/DynamicField.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: fdd878e7d27be9e43b3b511c3c5f3325\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/DynamicMethod.cs",
    "content": "using System;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using QuickJS.Native;\r\n    using QuickJS.Errors;\r\n\r\n    public interface IDynamicMethod\r\n    {\r\n        JSValue Invoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv);\r\n    }\r\n\r\n    public abstract class DynamicMethodBase : IDynamicMethod\r\n    {\r\n        public abstract int GetParameterCount();\r\n\r\n        public abstract bool CheckArgs(JSContext ctx, int argc, JSValue[] argv);\r\n\r\n        public abstract JSValue Invoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv);\r\n    }\r\n\r\n    /// <summary>\r\n    /// primitive JSCFunction\r\n    /// </summary>\r\n    public class DynamicPrimitiveMethod : DynamicMethodBase\r\n    {\r\n        private MethodBase _methodInfo;\r\n\r\n        public DynamicPrimitiveMethod(DynamicType type, MethodBase methodInfo)\r\n        {\r\n            _methodInfo = methodInfo;\r\n        }\r\n\r\n        public override bool CheckArgs(JSContext ctx, int argc, JSValue[] argv)\r\n        {\r\n            //TODO: args check \r\n            return true;\r\n        }\r\n\r\n        public override int GetParameterCount()\r\n        {\r\n            return 0;\r\n        }\r\n\r\n        public override JSValue Invoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            var rval = _methodInfo.Invoke(null, new object[] { ctx, this_obj, argc, argv });\r\n            return (JSValue)rval;\r\n        }\r\n    }\r\n\r\n    public static class DynamicMethodFactory\r\n    {\r\n        public static DynamicMethodBase CreateMethod(DynamicType type, MethodInfo methodInfo, bool asExtensionAnyway)\r\n        {\r\n            if (Values.IsVarargParameter(methodInfo.GetParameters()))\r\n            {\r\n                return new DynamicVariadicMethod(type, methodInfo, asExtensionAnyway);\r\n            }\r\n            return new DynamicMethod(type, methodInfo, asExtensionAnyway);\r\n        }\r\n    }\r\n\r\n    public class DynamicMethod : DynamicMethodBase\r\n    {\r\n        private DynamicType _type;\r\n        private bool _isExtension;\r\n        private MethodInfo _methodInfo;\r\n\r\n        private ParameterInfo[] _inputParameters;\r\n        private int requiredArgCount;\r\n        private ParameterInfo[] _methodParameters;\r\n\r\n        public DynamicMethod(DynamicType type, MethodInfo methodInfo, bool asExtensionAnyway)\r\n        {\r\n            _type = type;\r\n            _isExtension = asExtensionAnyway;\r\n            _methodInfo = methodInfo;\r\n            _methodParameters = _methodInfo.GetParameters();\r\n\r\n            var paramStartIndex = _isExtension ? 1 : 0;\r\n            var argIndex = 0;\r\n            for (var i = paramStartIndex; i < _methodParameters.Length; i++)\r\n            {\r\n                var p = _methodParameters[i];\r\n                if (!Values.IsContextualType(p.ParameterType))\r\n                {\r\n                    argIndex++;\r\n                }\r\n\r\n                if (!p.IsOptional)\r\n                {\r\n                    requiredArgCount++;\r\n                }\r\n            }\r\n            _inputParameters = new ParameterInfo[argIndex];\r\n            argIndex = 0;\r\n            for (var i = paramStartIndex; i < _methodParameters.Length; i++)\r\n            {\r\n                var p = _methodParameters[i];\r\n                if (!Values.IsContextualType(p.ParameterType))\r\n                {\r\n                    _inputParameters[argIndex++] = p;\r\n                }\r\n            }\r\n        }\r\n\r\n        public override int GetParameterCount()\r\n        {\r\n            return _inputParameters.Length;\r\n        }\r\n\r\n        public override bool CheckArgs(JSContext ctx, int argc, JSValue[] argv)\r\n        {\r\n            if (!(argc <= _inputParameters.Length && argc >= requiredArgCount))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            return Values.js_match_parameters(ctx, argv, _inputParameters);\r\n        }\r\n\r\n        public override JSValue Invoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (!_methodInfo.IsPublic && !_type.privateAccess)\r\n            {\r\n                return ctx.ThrowInternalError(\"method is inaccessible due to its protection level\");\r\n            }\r\n            object self = null;\r\n            if (_isExtension || !_methodInfo.IsStatic)\r\n            {\r\n                if (!Values.js_get_var(ctx, this_obj, _type.type, out self) || !_type.CheckThis(self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n            }\r\n            var nArgs = _methodParameters.Length;\r\n            var requiredArgNum = nArgs;\r\n            var args = new object[nArgs];\r\n            var argvIndex = 0;\r\n            var paramIndex = 0;\r\n            var bBackValues = false;\r\n\r\n            if (_isExtension)\r\n            {\r\n                args[paramIndex++] = self;\r\n                --requiredArgNum;\r\n            }\r\n            for (; paramIndex < nArgs; paramIndex++)\r\n            {\r\n                var parameterInfo = _methodParameters[paramIndex];\r\n                var pType = parameterInfo.ParameterType;\r\n                if (Values.IsContextualType(pType))\r\n                {\r\n                    args[paramIndex] = Values.GetContext(ctx, pType);\r\n                }\r\n                else\r\n                {\r\n                    if (pType.IsByRef)\r\n                    {\r\n                        bBackValues = true;\r\n                        if (!parameterInfo.IsOut)\r\n                        {\r\n                            JSValue realArgValue;\r\n                            if (!Values.js_read_wrap(ctx, argv[argvIndex], out realArgValue))\r\n                            {\r\n                                return realArgValue;\r\n                            }\r\n                            if (!Values.js_get_var(ctx, realArgValue, pType.GetElementType(), out args[paramIndex]))\r\n                            {\r\n                                JSApi.JS_FreeValue(ctx, realArgValue);\r\n                                return ctx.ThrowInternalError($\"failed to cast val byref #{argvIndex}\");\r\n                            }\r\n                            JSApi.JS_FreeValue(ctx, realArgValue);\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        if (argvIndex >= argv.Length)\r\n                        {\r\n                            args[paramIndex] = null;\r\n                        }\r\n                        else if (!Values.js_get_var(ctx, argv[argvIndex], pType, out args[paramIndex]))\r\n                        {\r\n                            return ctx.ThrowInternalError($\"failed to cast val #{argvIndex}\");\r\n                        }\r\n                    }\r\n                    argvIndex++;\r\n                }\r\n            }\r\n\r\n            var ret = _methodInfo.Invoke(_isExtension ? null : self, args);\r\n\r\n            if (bBackValues)\r\n            {\r\n                argvIndex = 0;\r\n                for (var i = 0; i < nArgs; i++)\r\n                {\r\n                    var parameterInfo = _methodParameters[i];\r\n                    var pType = parameterInfo.ParameterType;\r\n                    if (!Values.IsContextualType(pType))\r\n                    {\r\n                        if (pType.IsByRef)\r\n                        {\r\n                            var backValue = Values.js_push_var(ctx, args[i]);\r\n                            var valueAtom = ScriptEngine.GetContext(ctx).GetAtom(\"value\");\r\n                            JSApi.JS_SetProperty(ctx, argv[argvIndex], valueAtom, backValue);\r\n                        }\r\n\r\n                        argvIndex++;\r\n                    }\r\n                }\r\n            }\r\n\r\n            if (_type.type.IsValueType && !_methodInfo.IsStatic)\r\n            {\r\n                Values.js_rebind_var(ctx, this_obj, _type.type, self);\r\n            }\r\n\r\n            if (_methodInfo.ReturnType != typeof(void))\r\n            {\r\n                return Values.js_push_var(ctx, ret);\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n    }\r\n\r\n    public class DynamicVariadicMethod : DynamicMethodBase\r\n    {\r\n        private DynamicType _type;\r\n        private bool _isExtension;\r\n        private MethodInfo _methodInfo;\r\n\r\n        private ParameterInfo[] _inputParameters;\r\n        private ParameterInfo[] _methodParameters;\r\n\r\n        public DynamicVariadicMethod(DynamicType type, MethodInfo methodInfo, bool asExtensionAnyway)\r\n        {\r\n            _type = type;\r\n            _isExtension = asExtensionAnyway;\r\n            _methodInfo = methodInfo;\r\n            _methodParameters = _methodInfo.GetParameters();\r\n            // _isVarargMethod = Values.IsVarargParameter(_methodParameters);\r\n\r\n            var paramStartIndex = _isExtension ? 1 : 0;\r\n            var argIndex = 0;\r\n            for (var i = paramStartIndex; i < _methodParameters.Length; i++)\r\n            {\r\n                var p = _methodParameters[i];\r\n                if (!Values.IsContextualType(p.ParameterType))\r\n                {\r\n                    argIndex++;\r\n                }\r\n            }\r\n            _inputParameters = new ParameterInfo[argIndex];\r\n            argIndex = 0;\r\n            for (var i = paramStartIndex; i < _methodParameters.Length; i++)\r\n            {\r\n                var p = _methodParameters[i];\r\n                if (!Values.IsContextualType(p.ParameterType))\r\n                {\r\n                    _inputParameters[argIndex++] = p;\r\n                }\r\n            }\r\n        }\r\n\r\n        public override int GetParameterCount()\r\n        {\r\n            return _inputParameters.Length;\r\n        }\r\n\r\n        public override bool CheckArgs(JSContext ctx, int argc, JSValue[] argv)\r\n        {\r\n            if (_inputParameters.Length - 1 > argc)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            return Values.js_match_parameters_vararg(ctx, argc, argv, _inputParameters);\r\n        }\r\n\r\n        public override JSValue Invoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (!_methodInfo.IsPublic && !_type.privateAccess)\r\n            {\r\n                return ctx.ThrowInternalError(\"method is inaccessible due to its protection level\");\r\n            }\r\n            object self = null;\r\n            if (_isExtension || !_methodInfo.IsStatic)\r\n            {\r\n                if (!Values.js_get_var(ctx, this_obj, _type.type, out self) || !_type.CheckThis(self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n            }\r\n            var nArgs = _methodParameters.Length;\r\n            var requiredArgNum = nArgs;\r\n            var args = new object[nArgs];\r\n            var argvIndex = 0;\r\n            var paramIndex = 0;\r\n            var bBackValues = false;\r\n\r\n            if (_isExtension)\r\n            {\r\n                args[paramIndex++] = self;\r\n                --requiredArgNum;\r\n            }\r\n            for (; paramIndex < nArgs; paramIndex++)\r\n            {\r\n                var parameterInfo = _methodParameters[paramIndex];\r\n                var pType = parameterInfo.ParameterType;\r\n                if (Values.IsContextualType(pType))\r\n                {\r\n                    args[paramIndex] = Values.GetContext(ctx, pType);\r\n                }\r\n                else\r\n                {\r\n                    if (/*_isVarargMethod && */paramIndex == nArgs - 1)\r\n                    {\r\n                        var varArgLength = argc - requiredArgNum + 1;\r\n                        var varArgType = pType.GetElementType();\r\n                        var varArgArray = Array.CreateInstance(varArgType, varArgLength);\r\n                        for (var varArgIndex = 0; varArgIndex < varArgLength; varArgIndex++)\r\n                        {\r\n                            object varArgElement = null;\r\n                            if (!Values.js_get_var(ctx, argv[argvIndex++], varArgType, out varArgElement))\r\n                            {\r\n                                return ctx.ThrowInternalError($\"failed to cast val vararg #{varArgIndex}\");\r\n                            }\r\n                            varArgArray.SetValue(varArgElement, varArgIndex);\r\n                        }\r\n                        args[paramIndex] = varArgArray;\r\n                    }\r\n                    else\r\n                    {\r\n                        if (pType.IsByRef)\r\n                        {\r\n                            bBackValues = true;\r\n                            if (!parameterInfo.IsOut)\r\n                            {\r\n                                JSValue realArgValue;\r\n                                if (!Values.js_read_wrap(ctx, argv[argvIndex], out realArgValue))\r\n                                {\r\n                                    return realArgValue;\r\n                                }\r\n                                if (!Values.js_get_var(ctx, realArgValue, pType.GetElementType(), out args[paramIndex]))\r\n                                {\r\n                                    JSApi.JS_FreeValue(ctx, realArgValue);\r\n                                    return ctx.ThrowInternalError($\"failed to cast val byref #{argvIndex}\");\r\n                                }\r\n                                JSApi.JS_FreeValue(ctx, realArgValue);\r\n                            }\r\n                        }\r\n                        else\r\n                        {\r\n                            if (!Values.js_get_var(ctx, argv[argvIndex], pType, out args[paramIndex]))\r\n                            {\r\n                                return ctx.ThrowInternalError($\"failed to cast val #{argvIndex}\");\r\n                            }\r\n                        }\r\n                        argvIndex++;\r\n                    }\r\n                }\r\n            }\r\n\r\n            var ret = _methodInfo.Invoke(_isExtension ? null : self, args);\r\n\r\n            if (bBackValues)\r\n            {\r\n                argvIndex = 0;\r\n                for (var i = 0; i < nArgs; i++)\r\n                {\r\n                    var parameterInfo = _methodParameters[i];\r\n                    var pType = parameterInfo.ParameterType;\r\n                    if (!Values.IsContextualType(pType))\r\n                    {\r\n                        if (/*_isVarargMethod && */i == nArgs - 1)\r\n                        {\r\n                        }\r\n                        else\r\n                        {\r\n                            if (pType.IsByRef)\r\n                            {\r\n                                var backValue = Values.js_push_var(ctx, args[i]);\r\n                                var valueAtom = ScriptEngine.GetContext(ctx).GetAtom(\"value\");\r\n                                JSApi.JS_SetProperty(ctx, argv[argvIndex], valueAtom, backValue);\r\n                            }\r\n\r\n                            argvIndex++;\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            if (_type.type.IsValueType && !_methodInfo.IsStatic)\r\n            {\r\n                Values.js_rebind_var(ctx, this_obj, _type.type, self);\r\n            }\r\n\r\n            if (_methodInfo.ReturnType != typeof(void))\r\n            {\r\n                return Values.js_push_var(ctx, ret);\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n    }\r\n\r\n    public class DynamicDelegateMethod : IDynamicMethod\r\n    {\r\n        private Delegate _delegate;\r\n\r\n        public DynamicDelegateMethod(Delegate d)\r\n        {\r\n            _delegate = d;\r\n        }\r\n\r\n        public JSValue Invoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            var self = _delegate.Target;\r\n            var methodInfo = _delegate.Method;\r\n            var parameters = methodInfo.GetParameters();\r\n            var nArgs = Math.Min(argc, parameters.Length);\r\n            var args = new object[nArgs];\r\n            for (var i = 0; i < nArgs; i++)\r\n            {\r\n                if (!Values.js_get_var(ctx, argv[i], parameters[i].ParameterType, out args[i]))\r\n                {\r\n                    return ctx.ThrowInternalError(\"failed to cast val\");\r\n                }\r\n            }\r\n            var ret = methodInfo.Invoke(self, args);\r\n\r\n            if (methodInfo.ReturnType != typeof(void))\r\n            {\r\n                return Values.js_push_var(ctx, ret);\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n    }\r\n\r\n    public class DynamicCrossBindConstructor : DynamicMethodBase\r\n    {\r\n        public DynamicCrossBindConstructor()\r\n        {\r\n        }\r\n\r\n        public override int GetParameterCount()\r\n        {\r\n            return 0;\r\n        }\r\n\r\n        public override bool CheckArgs(JSContext ctx, int argc, JSValue[] argv)\r\n        {\r\n            return true;\r\n        }\r\n\r\n        public override JSValue Invoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            return JSApi.jsb_crossbind_constructor(ctx, this_obj);\r\n        }\r\n    }\r\n\r\n    public class DynamicDefaultConstructor : DynamicMethodBase\r\n    {\r\n        private DynamicType _type;\r\n\r\n        public DynamicDefaultConstructor(DynamicType type)\r\n        {\r\n            _type = type;\r\n        }\r\n\r\n        public override int GetParameterCount()\r\n        {\r\n            return 0;\r\n        }\r\n\r\n        public override bool CheckArgs(JSContext ctx, int argc, JSValue[] argv)\r\n        {\r\n            return true;\r\n        }\r\n\r\n        public override JSValue Invoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            var inst = Activator.CreateInstance(_type.type);\r\n            var val = Values.NewBridgeClassObject(ctx, this_obj, inst, _type.id, false);\r\n            return val;\r\n        }\r\n    }\r\n\r\n    public class DynamicConstructor : DynamicMethodBase\r\n    {\r\n        private DynamicType _type;\r\n        private ConstructorInfo _ctor;\r\n        private ParameterInfo[] _parameters;\r\n        private int requiredArgCount;\r\n        private bool _disposable;\r\n\r\n        public DynamicConstructor(DynamicType type, ConstructorInfo ctor)\r\n        : this(type, ctor, false)\r\n        {\r\n        }\r\n\r\n        public DynamicConstructor(DynamicType type, ConstructorInfo ctor, bool disposable)\r\n        {\r\n            _type = type;\r\n            _ctor = ctor;\r\n            _parameters = _ctor.GetParameters();\r\n            _disposable = disposable;\r\n\r\n            for (int i = 0; i < _parameters.Length; i++)\r\n            {\r\n                if (!_parameters[i].IsOptional)\r\n                {\r\n                    requiredArgCount++;\r\n                }\r\n            }\r\n        }\r\n\r\n        public override int GetParameterCount()\r\n        {\r\n            return _parameters.Length;\r\n        }\r\n\r\n        public override bool CheckArgs(JSContext ctx, int argc, JSValue[] argv)\r\n        {\r\n            if (!(argc <= _parameters.Length && argc >= requiredArgCount))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            return Values.js_match_parameters(ctx, argv, _parameters);\r\n        }\r\n\r\n        public override JSValue Invoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (!_ctor.IsPublic && !_type.privateAccess)\r\n            {\r\n                return ctx.ThrowInternalError(\"constructor is inaccessible due to its protection level\");\r\n            }\r\n\r\n            var nArgs = _parameters.Length;\r\n            var args = new object[_parameters.Length];\r\n            for (var i = 0; i < nArgs; i++)\r\n            {\r\n                var param = _parameters[i];\r\n\r\n                if (i >= argc)\r\n                {\r\n                    if (param.IsOptional)\r\n                    {\r\n                        args[i] = param.DefaultValue;\r\n                    }\r\n                    else\r\n                    {\r\n                        return ctx.ThrowInternalError(\"enough arguments were not specified for constructor\");\r\n                    }\r\n                }\r\n                else if (!Values.js_get_var(ctx, argv[i], param.ParameterType, out args[i]))\r\n                {\r\n                    return ctx.ThrowInternalError(\"failed to cast val\");\r\n                }\r\n            }\r\n\r\n            var inst = _ctor.Invoke(args);\r\n            var val = Values.js_new_var(ctx, this_obj, _type.type, inst, _type.id, _disposable);\r\n            return val;\r\n        }\r\n    }\r\n\r\n    public class DynamicMethodInvoke : IDynamicMethod\r\n    {\r\n        private JSCFunction _method;\r\n\r\n        public DynamicMethodInvoke(JSCFunction method)\r\n        {\r\n            _method = method;\r\n        }\r\n\r\n        public JSValue Invoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            return _method.Invoke(ctx, this_obj, argc, argv);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/DynamicMethod.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 757716eff76bb9e49bf965ae3022bf0d\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/DynamicMethods.cs",
    "content": "using System.Collections.Generic;\r\nusing QuickJS.Native;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    // 存在重载的函数调用\r\n    public class DynamicMethods : IDynamicMethod\r\n    {\r\n        private DynamicType _type;\r\n        private string _methodName;\r\n        private List<DynamicMethodBase> _overloads;\r\n\r\n        public DynamicMethods(DynamicType type, string methodName, int initCapacity)\r\n        {\r\n            _type = type;\r\n            _methodName = methodName;\r\n            _overloads = new List<DynamicMethodBase>(initCapacity);\r\n        }\r\n\r\n        public void Add(DynamicMethodBase method)\r\n        {\r\n            var count = _overloads.Count;\r\n            for (var i = 0; i < count; i++)\r\n            {\r\n                var overload = _overloads[i];\r\n                if (method.GetParameterCount() > overload.GetParameterCount())\r\n                {\r\n                    _overloads.Insert(i, method);\r\n                    return;\r\n                }\r\n            }\r\n            _overloads.Add(method);\r\n        }\r\n\r\n        public JSValue Invoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            var count = _overloads.Count;\r\n\r\n            for (var i = 0; i < count; i++)\r\n            {\r\n                var method = _overloads[i];\r\n                \r\n                if (method.CheckArgs(ctx, argc, argv))\r\n                {\r\n                    return method.Invoke(ctx, this_obj, argc, argv);\r\n                }\r\n            }\r\n\r\n            return ctx.ThrowInternalError($\"no overload method matched for {_type.type.Name}.{_methodName} [{count}]\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/DynamicMethods.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 1afef451f394bf14095670c79175f87f\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/DynamicType.cs",
    "content": "using System;\r\nusing System.Reflection;\r\nusing System.Collections.Generic;\r\nusing QuickJS.Native;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public class DynamicType\r\n    {\r\n        public const BindingFlags BaseFlags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static;\r\n        public const BindingFlags PublicFlags = BaseFlags | BindingFlags.Public;\r\n        public const BindingFlags PrivateFlags = BaseFlags | BindingFlags.NonPublic;\r\n        public const BindingFlags DefaultFlags = BaseFlags | BindingFlags.Public | BindingFlags.NonPublic;\r\n\r\n        private Type _type;\r\n        private int _type_id;\r\n        private bool _privateAccess;\r\n\r\n        public int id => _type_id;\r\n\r\n        public string name => _type.Name;\r\n\r\n        public Type type => _type;\r\n\r\n        public bool privateAccess => _privateAccess;\r\n\r\n        public DynamicType(Type type, bool privateAccess)\r\n        {\r\n            _type = type;\r\n            _type_id = -1;\r\n            _privateAccess = privateAccess;\r\n        }\r\n\r\n        public void OpenPrivateAccess()\r\n        {\r\n            if (!_privateAccess)\r\n            {\r\n                _privateAccess = true;\r\n            }\r\n        }\r\n\r\n        public bool CheckThis(object self)\r\n        {\r\n            if (self == null)\r\n            {\r\n                return false;\r\n            }\r\n            var type = self.GetType();\r\n            return type == _type || type.IsSubclassOf(_type);\r\n        }\r\n\r\n        private void AddMethods(ref ClassDecl cls, bool bStatic, Dictionary<string, List<MethodInfo>> map)\r\n        {\r\n            foreach (var kv in map)\r\n            {\r\n                var methodInfos = kv.Value;\r\n                var methodName = kv.Key;\r\n                var count = methodInfos.Count;\r\n                var dynamicMethod = default(IDynamicMethod);\r\n                if (count == 1)\r\n                {\r\n                    dynamicMethod = DynamicMethodFactory.CreateMethod(this, methodInfos[0], false);\r\n                }\r\n                else\r\n                {\r\n                    var overloads = new DynamicMethods(this, methodName, count);\r\n                    for (var i = 0; i < count; i++)\r\n                    {\r\n                        var methodInfo = methodInfos[i];\r\n                        DynamicMethodBase overload;\r\n                        overload = DynamicMethodFactory.CreateMethod(this, methodInfos[i], false);\r\n                        overloads.Add(overload);\r\n                    }\r\n                    dynamicMethod = overloads;\r\n                }\r\n                cls.AddMethod(bStatic, methodName, dynamicMethod);\r\n            }\r\n        }\r\n\r\n        private void CollectMethod(ref ClassDecl cls, MethodInfo[] methodInfos, Dictionary<string, List<MethodInfo>> instMap, Dictionary<string, List<MethodInfo>> staticMap)\r\n        {\r\n            for (int i = 0, count = methodInfos.Length; i < count; i++)\r\n            {\r\n                var methodInfo = methodInfos[i];\r\n                var name = methodInfo.Name;\r\n\r\n                if (methodInfo.IsSpecialName)\r\n                {\r\n                    var enableOperatorOverloading = false;\r\n\r\n                    //TODO: 反射方式的运算符重载注册\r\n                    if (name.StartsWith(\"op_\"))\r\n                    {\r\n                        switch (name)\r\n                        {\r\n                            case \"op_Addition\":\r\n                            case \"op_Subtraction\":\r\n                            case \"op_Equality\":\r\n                            case \"op_Multiply\":\r\n                            case \"op_Division\":\r\n                            case \"op_UnaryNegation\":\r\n                                //TODO: add operators\r\n                                // var op = new DynamicMethod(this, methodInfo);\r\n                                // cls.AddSelfOperator()\r\n                                // cls.AddLeftOperator()\r\n                                // cls.AddRightOperator()\r\n                                break;\r\n                        }\r\n                    }\r\n\r\n                    if (enableOperatorOverloading)\r\n                    {\r\n                        continue;\r\n                    }\r\n                }\r\n\r\n                var map = methodInfo.IsStatic ? staticMap : instMap;\r\n                List<MethodInfo> list;\r\n                if (!map.TryGetValue(name, out list))\r\n                {\r\n                    list = map[name] = new List<MethodInfo>();\r\n                }\r\n                list.Add(methodInfo);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// 通过反射枚举所有成员并注册绑定\r\n        /// (此方法用于运行时在脚本中使用静态绑定的类型, 需提前保证类型未被剔除).\r\n        /// (此方法仅用于用户运行时, 不适用于 RefectBind)\r\n        /// </summary>\r\n        public ClassDecl Bind(TypeRegister register, bool crossbind = false)\r\n        {\r\n            ClassDecl cls;\r\n            var db = register.GetTypeDB();\r\n            var ctx = (JSContext)register.GetContext();\r\n            var flags = DefaultFlags;\r\n            var proto = db.FindPrototypeOf(_type, out _type_id);\r\n\r\n            if (proto.IsNullish())\r\n            {\r\n                _type_id = db.AddType(_type, JSApi.JS_UNDEFINED);\r\n\r\n                var dynamicConstructor = default(IDynamicMethod);\r\n\r\n                if (crossbind)\r\n                {\r\n                    dynamicConstructor = new DynamicCrossBindConstructor();\r\n                }\r\n                else\r\n                {\r\n                    var constructors = _type.GetConstructors(flags);\r\n                    if (constructors.Length > 0)\r\n                    {\r\n                        var count = constructors.Length;\r\n                        if (count == 1)\r\n                        {\r\n                            dynamicConstructor = new DynamicConstructor(this, constructors[0]);\r\n                        }\r\n                        else\r\n                        {\r\n                            var overloads = new DynamicMethods(this, \"constructor\", count);\r\n                            for (var i = 0; i < count; i++)\r\n                            {\r\n                                var overload = new DynamicConstructor(this, constructors[i]);\r\n                                overloads.Add(overload);\r\n                            }\r\n                            dynamicConstructor = overloads;\r\n                        }\r\n                    }\r\n                }\r\n\r\n                cls = register.CreateClass(_type.Name, _type, dynamicConstructor);\r\n            }\r\n            else\r\n            {\r\n                cls = register.CreateClassWithPrototype(_type, proto);\r\n            }\r\n\r\n            #region BindMethods(register, flags);\r\n            var instMap = new Dictionary<string, List<MethodInfo>>();\r\n            var staticMap = new Dictionary<string, List<MethodInfo>>();\r\n            CollectMethod(ref cls, _type.GetMethods(flags), instMap, staticMap);\r\n            AddMethods(ref cls, true, staticMap);\r\n            AddMethods(ref cls, false, instMap);\r\n            #endregion\r\n\r\n            #region BindFields(register, flags);\r\n            var fieldInfos = _type.GetFields(flags);\r\n            for (int i = 0, count = fieldInfos.Length; i < count; i++)\r\n            {\r\n                var fieldInfo = fieldInfos[i];\r\n                if (!fieldInfo.Name.StartsWith(\"_JSFIX_\")) // skip hotfix slots\r\n                {\r\n                    var dynamicField = new DynamicField(this, fieldInfo);\r\n                    cls.AddField(fieldInfo.IsStatic, fieldInfo.Name, dynamicField);\r\n                }\r\n            }\r\n            #endregion\r\n\r\n            #region BindProperties(register, flags);\r\n            var propertyInfos = _type.GetProperties(flags);\r\n            for (int i = 0, count = propertyInfos.Length; i < count; i++)\r\n            {\r\n                //TODO fix indexed accessor\r\n                var propertyInfo = propertyInfos[i];\r\n                var anyMethod = propertyInfo.GetGetMethod(true) ?? propertyInfo.GetSetMethod(true);\r\n                var dynamicProperty = new DynamicProperty(this, propertyInfo);\r\n                cls.AddField(anyMethod.IsStatic, propertyInfo.Name, dynamicProperty);\r\n            }\r\n            #endregion\r\n\r\n            return cls;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/DynamicType.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 4611ff31f84124c419aaa75eb80be95f\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/AbstractBindingProcess.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public abstract class AbstractBindingProcess : IBindingProcess\r\n    {\r\n        public virtual void OnInitialize(BindingManager bindingManager)\r\n        {\r\n        }\r\n\r\n        public virtual void OnPreCollectAssemblies(BindingManager bindingManager)\r\n        {\r\n        }\r\n\r\n        public virtual void OnPostCollectAssemblies(BindingManager bindingManager)\r\n        {\r\n        }\r\n\r\n        public virtual void OnPreExporting(BindingManager bindingManager)\r\n        {\r\n        }\r\n\r\n        public virtual void OnPostExporting(BindingManager bindingManager)\r\n        {\r\n        }\r\n\r\n        public virtual void OnPreCollectTypes(BindingManager bindingManager)\r\n        {\r\n        }\r\n\r\n        public virtual void OnPostCollectTypes(BindingManager bindingManager)\r\n        {\r\n        }\r\n\r\n        public virtual bool OnExportingType(BindingManager bindingManager, Type type)\r\n        {\r\n            return false;\r\n        }\r\n\r\n        public virtual void OnPreGenerateType(BindingManager bindingManager, TypeBindingInfo bindingInfo)\r\n        {\r\n        }\r\n\r\n        public virtual void OnPostGenerateType(BindingManager bindingManager, TypeBindingInfo bindingInfo)\r\n        {\r\n        }\r\n\r\n        public virtual void OnPreGenerateDelegate(BindingManager bindingManager, DelegateBridgeBindingInfo bindingInfo)\r\n        {\r\n        }\r\n\r\n        public virtual void OnPostGenerateDelegate(BindingManager bindingManager, DelegateBridgeBindingInfo bindingInfo)\r\n        {\r\n        }\r\n\r\n        public virtual void OnCleanup(BindingManager bindingManager)\r\n        {\r\n        }\r\n        \r\n        public virtual int Priority { get; set; }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/AbstractBindingProcess.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 3db6422e84c9d834f898a2b8b822e0b9\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingCallback/DefaultCodeGenCallback.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\nusing System.Linq;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public class DefaultCodeGenCallback : ICodeGenCallback\r\n    {\r\n        private BindingManager _bindingManager;\r\n\r\n        public void OnCodeGenBegin(BindingManager bindingManager)\r\n        {\r\n            _bindingManager = bindingManager;\r\n        }\r\n\r\n        public void OnCodeGenEnd()\r\n        {\r\n\r\n        }\r\n\r\n        public bool OnTypeGenerating(TypeBindingInfo typeBindingInfo, int current, int total)\r\n        {\r\n#if JSB_UNITYLESS\r\n            return false;\r\n#else\r\n            return UnityEditor.EditorUtility.DisplayCancelableProgressBar(\r\n                \"Generating\",\r\n                $\"{current}/{total}: {typeBindingInfo.FullName}\",\r\n                (float)current / total);\r\n#endif\r\n        }\r\n\r\n        public void OnGenerateFinish()\r\n        {\r\n#if !JSB_UNITYLESS\r\n            UnityEditor.EditorUtility.ClearProgressBar();\r\n#endif\r\n        }\r\n\r\n        public void OnSourceCodeEmitted(CodeGenerator cg, string codeOutDir, string codeName, SourceCodeType type, TextGenerator textGenerator)\r\n        {\r\n            if (!Directory.Exists(codeOutDir))\r\n            {\r\n                Directory.CreateDirectory(codeOutDir);\r\n            }\r\n\r\n            var extension = \"\";\r\n            switch (type)\r\n            {\r\n                case SourceCodeType.CSharp: extension = \".cs\"; break;\r\n                case SourceCodeType.TSD: extension = \".d.ts\" + _bindingManager.prefs.extraExtForTypescript; break;\r\n            }\r\n\r\n            var slices = textGenerator.SubmitAll();\r\n            var sliceCount = slices.Length;\r\n            if (sliceCount == 1)\r\n            {\r\n                var csPath = Path.Combine(codeOutDir, codeName + extension);\r\n                cg.WriteAllText(csPath, slices[0]);\r\n                _bindingManager.AddOutputFile(codeOutDir, csPath);\r\n            }\r\n            else\r\n            {\r\n                for (int sliceIndex = 0; sliceIndex < sliceCount; ++sliceIndex)\r\n                {\r\n                    var csPath = Path.Combine(codeOutDir, $\"{codeName}.part{sliceIndex}{extension}\");\r\n                    cg.WriteAllText(csPath, slices[sliceIndex]);\r\n                    _bindingManager.AddOutputFile(codeOutDir, csPath);\r\n                }\r\n            }\r\n        }\r\n\r\n        public void OnGenerateBindingList(CodeGenerator cg, IEnumerable<IGrouping<string, TypeBindingInfo>> modules, ICollection<RawTypeBindingInfo> rawTypes)\r\n        {\r\n            cg.GenerateBindingList(Values.NamespaceOfStaticBinder, Values.ClassNameOfStaticBinder, modules, true, rawTypes);\r\n        }\r\n    }\r\n}\r\n#endif "
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingCallback/DefaultCodeGenCallback.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 2abbf3f5f59520b4aa1f7fe09b245d9f\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingCallback/IBindingCallback.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    /// <summary>\r\n    /// the BindingManager will invoke a specific method at the specific stage of the binding process\r\n    /// </summary>\r\n    public interface IBindingCallback\r\n    {\r\n        void OnBindingBegin(BindingManager bindingManager);\r\n        void OnBindingEnd();\r\n\r\n        void BindRawTypes(ICollection<RawTypeBindingInfo> rawTypes);\r\n        void BeginStaticModule(string moduleName, int capacity);\r\n        void AddTypeReference(string moduleName, TypeBindingInfo typeBindingInfo);\r\n        void EndStaticModule(string moduleName);\r\n\r\n        void AddDelegate(DelegateBridgeBindingInfo bindingInfo);\r\n    }\r\n}\r\n\r\n#endif "
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingCallback/IBindingCallback.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: f9346a1b409cfbb49b1d425096ce334b\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingCallback/ICodeGenCallback.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\nusing System.Linq;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public enum SourceCodeType\r\n    {\r\n        CSharp, \r\n        TSD, \r\n    }\r\n\r\n    public interface ICodeGenCallback\r\n    {\r\n        void OnCodeGenBegin(BindingManager bindingManager);\r\n        \r\n        void OnCodeGenEnd();\r\n\r\n        // return true to cancel the binding process\r\n        bool OnTypeGenerating(TypeBindingInfo typeBindingInfo, int current, int total);\r\n\r\n        void OnGenerateFinish();\r\n\r\n        void OnSourceCodeEmitted(CodeGenerator cg, string csOutDir, string csName, SourceCodeType type, TextGenerator textGenerator);\r\n\r\n        void OnGenerateBindingList(CodeGenerator cg, IEnumerable<IGrouping<string, TypeBindingInfo>> modules, ICollection<RawTypeBindingInfo> rawTypes);\r\n    }\r\n}\r\n\r\n#endif "
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingCallback/ICodeGenCallback.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 243d60ec4d2b75d46afe43135034ebc8\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingCallback/InMemoryCompilationBindingCallback.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\nusing System.Linq;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    /// <summary>\r\n    /// [experimental] do StaticBind but in the memory with the CodeDomProvider for csharp. \r\n    /// </summary>\r\n    public class InMemoryCompilationBindingCallback : IBindingCallback, ICodeGenCallback\r\n    {\r\n        private ScriptRuntime _runtime;\r\n        private BindingManager _bindingManager;\r\n\r\n        private string _namespace = Values.NamespaceOfStaticBinder;\r\n        private string _className;\r\n        private HashSet<Assembly> _referencedAssemblies = new HashSet<Assembly>();\r\n        private List<Assembly> _generatedAssemblies = new List<Assembly>();\r\n        private string _compilerOptions;\r\n\r\n        public static List<string> GetDefinedSymbols()\r\n        {\r\n            var defines = new List<string>();\r\n\r\n#if UNITY_EDITOR // #define directive to call Unity Editor scripts from your game code.\r\n            defines.Add(\"UNITY_EDITOR\");\r\n#endif\r\n#if UNITY_EDITOR_WIN // #define directive for Editor code on Windows.\r\n            defines.Add(\"UNITY_EDITOR_WIN\");\r\n#endif\r\n#if UNITY_EDITOR_OSX // #define directive for Editor code on Mac OS X.\r\n            defines.Add(\"UNITY_EDITOR_OSX\");\r\n#endif\r\n#if UNITY_EDITOR_LINUX // #define directive for Editor code on Linux.\r\n            defines.Add(\"UNITY_EDITOR_LINUX\");\r\n#endif\r\n#if UNITY_STANDALONE_OSX // #define directive to compile or execute code specifically for Mac OS X (including Universal, PPC and Intel architectures).\r\n            defines.Add(\"UNITY_STANDALONE_OSX\");\r\n#endif\r\n#if UNITY_STANDALONE_WIN // #define directive for compiling/executing code specifically for Windows standalone applications.\r\n            defines.Add(\"UNITY_STANDALONE_WIN\");\r\n#endif\r\n#if UNITY_STANDALONE_LINUX // #define directive for compiling/executing code specifically for Linux standalone applications.\r\n            defines.Add(\"UNITY_STANDALONE_LINUX\");\r\n#endif\r\n#if UNITY_STANDALONE // #define directive for compiling/executing code for any standalone platform (Mac OS X, Windows or Linux).\r\n            defines.Add(\"UNITY_STANDALONE\");\r\n#endif\r\n#if UNITY_WII // #define directive for compiling/executing code for the Wii console.\r\n            defines.Add(\"UNITY_WII\");\r\n#endif\r\n#if UNITY_IOS // #define directive for compiling/executing code for the iOS platform.\r\n            defines.Add(\"UNITY_IOS\");\r\n#endif\r\n#if UNITY_IPHONE // \tDeprecated. Use UNITY_IOS instead.\r\n            defines.Add(\"UNITY_IPHONE\");\r\n#endif\r\n#if UNITY_ANDROID // #define directive for the Android platform.\r\n            defines.Add(\"UNITY_ANDROID\");\r\n#endif\r\n#if UNITY_PS4 // #define directive for running PlayStation 4 code.\r\n            defines.Add(\"UNITY_PS4\");\r\n#endif\r\n#if UNITY_XBOXONE // #define directive for executing Xbox One code.\r\n            defines.Add(\"UNITY_XBOXONE\");\r\n#endif\r\n#if UNITY_LUMIN // #define directive for the Magic Leap OS platform. You can also use PLATFORM_LUMIN.\r\n            defines.Add(\"UNITY_LUMIN\");\r\n#endif\r\n#if UNITY_TIZEN // #define directive for the Tizen platform.\r\n            defines.Add(\"UNITY_TIZEN\");\r\n#endif\r\n#if UNITY_TVOS // #define directive for the Apple TV platform.\r\n            defines.Add(\"UNITY_TVOS\");\r\n#endif\r\n#if UNITY_WSA // #define directive for Universal Windows Platform\r\n            defines.Add(\"UNITY_WSA\");\r\n#endif\r\n#if UNITY_WSA_10_0 // #define directive for Universal Windows Platform. Additionally WINDOWS_UWP is defined when compiling C# files against .NET Core.\r\n            defines.Add(\"UNITY_WSA_10_0\");\r\n#endif\r\n#if UNITY_WINRT // \tSame as UNITY_WSA.\r\n            defines.Add(\"UNITY_WINRT\");\r\n#endif\r\n#if UNITY_WINRT_10_0 // \tEquivalent to UNITY_WSA_10_0\r\n            defines.Add(\"UNITY_WINRT_10_0\");\r\n#endif\r\n#if UNITY_WEBGL // #define directive for WebGL\r\n            defines.Add(\"UNITY_WEBGL\");\r\n#endif\r\n#if UNITY_FACEBOOK // #define directive for the Facebook platform (WebGL or Windows standalone).\r\n            defines.Add(\"UNITY_FACEBOOK\");\r\n#endif\r\n#if UNITY_ANALYTICS // #define directive for calling Unity Analytics\r\n            defines.Add(\"UNITY_ANALYTICS\");\r\n#endif\r\n#if UNITY_ASSERTIONS // #define directive for assertions control process.\r\n            defines.Add(\"UNITY_ASSERTIONS\");\r\n#endif\r\n#if UNITY_64 // #define directive for 64-bit platforms.\r\n            defines.Add(\"UNITY_64\");\r\n#endif\r\n#if UNITY_SERVER\r\n            defines.Add(\"UNITY_SERVER\");\r\n#endif\r\n            return defines;\r\n        }\r\n\r\n#if !JSB_UNITYLESS && UNITY_EDITOR\r\n        public static UnityEditor.BuildTargetGroup GetBuildTargetGroup()\r\n        {\r\n            var buildTarget = UnityEditor.EditorUserBuildSettings.activeBuildTarget;\r\n            switch (buildTarget)\r\n            {\r\n                case UnityEditor.BuildTarget.Android: return UnityEditor.BuildTargetGroup.Android;\r\n                case UnityEditor.BuildTarget.iOS: return UnityEditor.BuildTargetGroup.iOS;\r\n                case UnityEditor.BuildTarget.WSAPlayer: return UnityEditor.BuildTargetGroup.WSA;\r\n#if !UNITY_2019_2_OR_NEWER\r\n                case UnityEditor.BuildTarget.StandaloneLinux:\r\n                case UnityEditor.BuildTarget.StandaloneLinuxUniversal: \r\n#endif\r\n                case UnityEditor.BuildTarget.StandaloneLinux64:\r\n                case UnityEditor.BuildTarget.StandaloneOSX:\r\n                case UnityEditor.BuildTarget.StandaloneWindows:\r\n                case UnityEditor.BuildTarget.StandaloneWindows64: return UnityEditor.BuildTargetGroup.Standalone;\r\n                case UnityEditor.BuildTarget.Switch: return UnityEditor.BuildTargetGroup.Switch;\r\n                case UnityEditor.BuildTarget.PS4: return UnityEditor.BuildTargetGroup.PS4;\r\n                case UnityEditor.BuildTarget.XboxOne: return UnityEditor.BuildTargetGroup.XboxOne;\r\n            }\r\n            throw new NotImplementedException();\r\n        }\r\n#endif\r\n\r\n        public InMemoryCompilationBindingCallback(ScriptRuntime runtime)\r\n        {\r\n            _runtime = runtime;\r\n            _className = \"_GeneratedClass_\" + Guid.NewGuid().ToString().Replace(\"-\", \"\");\r\n            var symbolList = new List<string>();\r\n            var defines = \"\";\r\n            var compilerOptions = \"-unsafe\";\r\n\r\n#if !JSB_UNITYLESS\r\n            symbolList.AddRange(GetDefinedSymbols());\r\n#endif\r\n\r\n            defines += string.Join(\";\", symbolList);\r\n\r\n#if !JSB_UNITYLESS && UNITY_EDITOR\r\n            var customDefinedSymbols = UnityEditor.PlayerSettings.GetScriptingDefineSymbolsForGroup(GetBuildTargetGroup());\r\n            if (!string.IsNullOrEmpty(customDefinedSymbols))\r\n            {\r\n                defines += \";\" + customDefinedSymbols;\r\n            }\r\n#endif\r\n            if (!string.IsNullOrEmpty(defines))\r\n            {\r\n                compilerOptions += \" -defines:\" + defines;\r\n            }\r\n            _compilerOptions = compilerOptions;\r\n        }\r\n\r\n        public void OnBindingBegin(BindingManager bindingManager)\r\n        {\r\n            _bindingManager = bindingManager;\r\n            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())\r\n            {\r\n                if (!assembly.IsDynamic && !string.IsNullOrEmpty(assembly.Location))\r\n                {\r\n                    _referencedAssemblies.Add(assembly);\r\n                }\r\n            }\r\n        }\r\n\r\n        public void OnBindingEnd()\r\n        {\r\n        }\r\n\r\n        public void BeginStaticModule(string moduleName, int capacity)\r\n        {\r\n        }\r\n\r\n        public void AddTypeReference(string moduleName, TypeBindingInfo typeBindingInfo)\r\n        {\r\n        }\r\n\r\n        public void EndStaticModule(string moduleName)\r\n        {\r\n        }\r\n\r\n        public void AddDelegate(DelegateBridgeBindingInfo bindingInfo)\r\n        {\r\n        }\r\n\r\n        public void OnCodeGenBegin(BindingManager bindingManager)\r\n        {\r\n        }\r\n\r\n        public void OnCodeGenEnd()\r\n        {\r\n        }\r\n\r\n        public void BindRawTypes(ICollection<RawTypeBindingInfo> rawTypes)\r\n        {\r\n        }\r\n\r\n        public bool OnTypeGenerating(TypeBindingInfo typeBindingInfo, int current, int total)\r\n        {\r\n            return false;\r\n        }\r\n\r\n        public void OnGenerateFinish()\r\n        {\r\n        }\r\n\r\n        //TODO [IMPROVMENT] delay the compilation util using the type at runtime\r\n        public void OnSourceCodeEmitted(CodeGenerator cg, string codeOutDir, string codeName, SourceCodeType type, TextGenerator textGenerator)\r\n        {\r\n            if (type == SourceCodeType.CSharp)\r\n            {\r\n                if (codeName == CodeGenerator.NameOfBindingList)\r\n                {\r\n                    var list = new List<Assembly>(_generatedAssemblies);\r\n                    list.AddRange(_referencedAssemblies);\r\n                    var assembly = CompileSource(textGenerator.Submit(), codeName, list);\r\n                    var Class = assembly.GetType(_namespace + \".\" + _className);\r\n                    var BindAll = Class?.GetMethod(Values.MethodNameOfStaticBinder);\r\n\r\n                    BindAll.Invoke(null, new object[] { _runtime });\r\n                }\r\n                else\r\n                {\r\n                    _generatedAssemblies.Add(CompileSource(textGenerator.Submit(), codeName, _referencedAssemblies));\r\n                }\r\n            }\r\n        }\r\n\r\n        public void OnGenerateBindingList(CodeGenerator cg, IEnumerable<IGrouping<string, TypeBindingInfo>> modules, ICollection<RawTypeBindingInfo> rawTypes)\r\n        {\r\n            cg.GenerateBindingList(_namespace, _className, modules, false, rawTypes);\r\n        }\r\n\r\n        private Assembly CompileSource(string source, string assemblyName, IEnumerable<Assembly> referencedAssemblies)\r\n        {\r\n            var compiledAssembly = CodeGenUtils.Compile(source, referencedAssemblies, _compilerOptions, _bindingManager.GetBindingLogger());\r\n            if (compiledAssembly == null)\r\n            {\r\n                throw new InvalidOperationException($\"failed to compile {assemblyName} in memory\");\r\n            }\r\n            return compiledAssembly;\r\n        }\r\n    }\r\n}\r\n\r\n#endif "
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingCallback/InMemoryCompilationBindingCallback.cs.meta",
    "content": "fileFormatVersion: 2\nguid: a471925b48dd85d488c14e96e8a44506\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingCallback/ReflectBindingCallback.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\nusing QuickJS.Native;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    /// <summary>\r\n    /// the BindingCallback implementation of ReflectBind mode, no source will be actually emitted in ReflectBind mode.\r\n    /// Dynamic types bridges will be generated at the runtime for all types, methods and delegates.\r\n    /// </summary>\r\n    public class ReflectBindingCallback : IBindingCallback\r\n    {\r\n        /// <summary>\r\n        /// With this lazy typedb the delegates implementations will be dynamically generated util the first time use\r\n        /// </summary>\r\n        protected class LazyTypeDB : Utils.ITypeDB\r\n        {\r\n            private BindingManager _bindingManager;\r\n            private Utils.ITypeDB _backend;\r\n\r\n            public LazyTypeDB(BindingManager bindingManager, Utils.ITypeDB backend)\r\n            {\r\n                _bindingManager = bindingManager;\r\n                _backend = backend;\r\n            }\r\n\r\n            public int Count => _backend.Count;\r\n\r\n            public void AddDelegate(Type type, MethodInfo method)\r\n            {\r\n                _backend.AddDelegate(type, method);\r\n            }\r\n\r\n            public int AddType(Type type, JSValue proto)\r\n            {\r\n                return _backend.AddType(type, proto);\r\n            }\r\n\r\n            public void AddTypeBinder(Type type, ClassBind binder)\r\n            {\r\n                _backend.AddTypeBinder(type, binder);\r\n            }\r\n\r\n            public DynamicType CreateFreeDynamicType(Type type)\r\n            {\r\n                return _backend.CreateFreeDynamicType(type);\r\n            }\r\n\r\n            public void Destroy()\r\n            {\r\n                _backend.Destroy();\r\n            }\r\n\r\n            public JSValue FindChainedPrototypeOf(Type cType, out int type_id)\r\n            {\r\n                return _backend.FindChainedPrototypeOf(cType, out type_id);\r\n            }\r\n\r\n            public JSValue FindChainedPrototypeOf(Type cType)\r\n            {\r\n                return _backend.FindChainedPrototypeOf(cType);\r\n            }\r\n\r\n            public JSValue FindChainedPrototypeOf(Type cType, out Type pType)\r\n            {\r\n                return _backend.FindChainedPrototypeOf(cType, out pType);\r\n            }\r\n\r\n            public JSValue FindPrototypeOf(Type type)\r\n            {\r\n                return _backend.FindPrototypeOf(type);\r\n            }\r\n\r\n            public JSValue FindPrototypeOf(Type type, out int type_id)\r\n            {\r\n                return _backend.FindPrototypeOf(type, out type_id);\r\n            }\r\n\r\n            public JSValue GetConstructorOf(Type type)\r\n            {\r\n                return _backend.GetConstructorOf(type);\r\n            }\r\n\r\n            public MethodInfo GetDelegateFunc(Type delegateType)\r\n            {\r\n                var func = _backend.GetDelegateFunc(delegateType);\r\n                if (func == null)\r\n                {\r\n                    var invoke = delegateType.GetMethod(\"Invoke\");\r\n                    var returnType = invoke.ReturnType;\r\n                    var parameters = invoke.GetParameters();\r\n                    var method = _bindingManager.GetReflectedDelegateMethod(returnType, parameters);\r\n\r\n                    _backend.AddDelegate(delegateType, method);\r\n                    return method;\r\n                }\r\n                return func;\r\n            }\r\n\r\n            public IDynamicField GetDynamicField(int index)\r\n            {\r\n                return _backend.GetDynamicField(index);\r\n            }\r\n\r\n            public IDynamicMethod GetDynamicMethod(int index)\r\n            {\r\n                return _backend.GetDynamicMethod(index);\r\n            }\r\n\r\n            public DynamicType GetDynamicType(Type type, bool privateAccess)\r\n            {\r\n                return _backend.GetDynamicType(type, privateAccess);\r\n            }\r\n\r\n            public JSValue GetPrototypeOf(Type type)\r\n            {\r\n                return _backend.GetPrototypeOf(type);\r\n            }\r\n\r\n            public Type GetType(int index)\r\n            {\r\n                return _backend.GetType(index);\r\n            }\r\n\r\n            public int GetTypeID(Type type)\r\n            {\r\n                return _backend.GetTypeID(type);\r\n            }\r\n\r\n            public bool IsConstructorEquals(Type type, JSValue ctor)\r\n            {\r\n                return _backend.IsConstructorEquals(type, ctor);\r\n            }\r\n\r\n            public JSValue NewDynamicConstructor(JSAtom name, IDynamicMethod method)\r\n            {\r\n                return _backend.NewDynamicConstructor(name, method);\r\n            }\r\n\r\n            public JSValue NewDynamicDelegate(JSAtom name, Delegate d)\r\n            {\r\n                return _backend.NewDynamicDelegate(name, d);\r\n            }\r\n\r\n            public void NewDynamicFieldAccess(JSAtom name, IDynamicField field, out JSValue getter, out JSValue setter)\r\n            {\r\n                _backend.NewDynamicFieldAccess(name, field, out getter, out setter);\r\n            }\r\n\r\n            public JSValue NewDynamicMethod(JSAtom name, JSCFunction method)\r\n            {\r\n                return _backend.NewDynamicMethod(name, method);\r\n            }\r\n\r\n            public JSValue NewDynamicMethod(JSAtom name, IDynamicMethod method)\r\n            {\r\n                return _backend.NewDynamicMethod(name, method);\r\n            }\r\n\r\n            public bool TryGetPrototypeOf(Type type, out JSValue proto)\r\n            {\r\n                return _backend.TryGetPrototypeOf(type, out proto);\r\n            }\r\n        }\r\n\r\n        private ScriptRuntime _runtime;\r\n        private BindingManager _bindingManager;\r\n        private Module.ProxyModuleRegister _moduleReg;\r\n        private List<Type> _preloadTypes = new List<Type>();\r\n\r\n        public ReflectBindingCallback(ScriptRuntime runtime)\r\n        {\r\n            _runtime = runtime;\r\n\r\n            ReflectBindValueOp.Register<string>(Binding.Values.js_push_primitive, Binding.Values.js_get_primitive);\r\n            ReflectBindValueOp.Register<bool>(Binding.Values.js_push_primitive, Binding.Values.js_get_primitive);\r\n            ReflectBindValueOp.Register<char>(Binding.Values.js_push_primitive, Binding.Values.js_get_primitive);\r\n            ReflectBindValueOp.Register<byte>(Binding.Values.js_push_primitive, Binding.Values.js_get_primitive);\r\n            ReflectBindValueOp.Register<sbyte>(Binding.Values.js_push_primitive, Binding.Values.js_get_primitive);\r\n            ReflectBindValueOp.Register<double>(Binding.Values.js_push_primitive, Binding.Values.js_get_primitive);\r\n            ReflectBindValueOp.Register<float>(Binding.Values.js_push_primitive, Binding.Values.js_get_primitive);\r\n            ReflectBindValueOp.Register<short>(Binding.Values.js_push_primitive, Binding.Values.js_get_primitive);\r\n            ReflectBindValueOp.Register<ushort>(Binding.Values.js_push_primitive, Binding.Values.js_get_primitive);\r\n            ReflectBindValueOp.Register<int>(Binding.Values.js_push_primitive, Binding.Values.js_get_primitive);\r\n            ReflectBindValueOp.Register<uint>(Binding.Values.js_push_primitive, Binding.Values.js_get_primitive);\r\n            ReflectBindValueOp.Register<long>(Binding.Values.js_push_primitive, Binding.Values.js_get_primitive);\r\n            ReflectBindValueOp.Register<ulong>(Binding.Values.js_push_primitive, Binding.Values.js_get_primitive);\r\n            ReflectBindValueOp.Register<DateTime>(Binding.Values.js_push_structvalue, Binding.Values.js_get_structvalue);\r\n\r\n#if !JSB_UNITYLESS\r\n            ReflectBindValueOp.Register<UnityEngine.Vector2>(Binding.Values.js_push_structvalue, Binding.Values.js_get_structvalue);\r\n            ReflectBindValueOp.Register<UnityEngine.Vector2Int>(Binding.Values.js_push_structvalue, Binding.Values.js_get_structvalue);\r\n            ReflectBindValueOp.Register<UnityEngine.Vector3>(Binding.Values.js_push_structvalue, Binding.Values.js_get_structvalue);\r\n            ReflectBindValueOp.Register<UnityEngine.Vector3Int>(Binding.Values.js_push_structvalue, Binding.Values.js_get_structvalue);\r\n            ReflectBindValueOp.Register<UnityEngine.Vector4>(Binding.Values.js_push_structvalue, Binding.Values.js_get_structvalue);\r\n            ReflectBindValueOp.Register<UnityEngine.Rect>(Binding.Values.js_push_structvalue, Binding.Values.js_get_structvalue);\r\n            ReflectBindValueOp.Register<UnityEngine.Quaternion>(Binding.Values.js_push_structvalue, Binding.Values.js_get_structvalue);\r\n            ReflectBindValueOp.Register<UnityEngine.LayerMask>(Binding.Values.js_push_structvalue, Binding.Values.js_get_structvalue);\r\n            ReflectBindValueOp.Register<UnityEngine.Ray>(Binding.Values.js_push_structvalue, Binding.Values.js_get_structvalue);\r\n            ReflectBindValueOp.Register<UnityEngine.Color>(Binding.Values.js_push_structvalue, Binding.Values.js_get_structvalue);\r\n            ReflectBindValueOp.Register<UnityEngine.Color32>(Binding.Values.js_push_structvalue, Binding.Values.js_get_structvalue);\r\n            ReflectBindValueOp.Register<UnityEngine.Matrix4x4>(Binding.Values.js_push_structvalue, Binding.Values.js_get_structvalue);\r\n#endif\r\n\r\n            if (!CodeGenUtils.IsCodeEmitSupported())\r\n            {\r\n                Diagnostics.Logger.Default.Warning(CodeGenUtils.CodeEmitWarning);\r\n            }\r\n        }\r\n\r\n        public void OnBindingBegin(BindingManager bindingManager)\r\n        {\r\n            _bindingManager = bindingManager;\r\n            _runtime.ReplaceTypeDB(new LazyTypeDB(_bindingManager, _runtime.GetTypeDB()));\r\n        }\r\n\r\n        public void OnBindingEnd()\r\n        {\r\n            // GeneratePreloadTypes\r\n            var register = _runtime.GetMainContext().CreateTypeRegister();\r\n            for (int i = 0, count = _preloadTypes.Count; i < count; ++i)\r\n            {\r\n                var type = _preloadTypes[i];\r\n                register.FindPrototypeOf(type);\r\n            }\r\n            register.Finish();\r\n        }\r\n\r\n        public void BindRawTypes(ICollection<RawTypeBindingInfo> rawTypes)\r\n        {\r\n            if (rawTypes.Count == 0)\r\n            {\r\n                return;\r\n            }\r\n\r\n            var register = _runtime.GetMainContext().CreateTypeRegister();\r\n            var parameters = new object[] { register, null };\r\n            foreach (var type in rawTypes)\r\n            {\r\n                try\r\n                {\r\n                    parameters[1] = type.jsName;\r\n                    if (!register.IsGlobalRegistered(type.jsName))\r\n                    {\r\n                        type.method.Invoke(null, parameters);\r\n                    }\r\n                }\r\n                catch (Exception exception)\r\n                {\r\n                    _bindingManager.Error(exception);\r\n                }\r\n            }\r\n            register.Finish();\r\n        }\r\n\r\n        public void BeginStaticModule(string moduleName, int capacity)\r\n        {\r\n            _moduleReg = _runtime.AddStaticModuleProxy(moduleName);\r\n        }\r\n\r\n        public void AddTypeReference(string moduleName, TypeBindingInfo typeBindingInfo)\r\n        {\r\n            var moduleRegistrationPathSlice = CodeGenUtils.GetModuleRegistrationPathSlice(typeBindingInfo.tsTypeNaming);\r\n\r\n            _runtime.AddTypeReference(_moduleReg, typeBindingInfo.type, register => typeBindingInfo.DoReflectBind(register, _moduleReg), moduleRegistrationPathSlice);\r\n            if (typeBindingInfo.preload)\r\n            {\r\n                _preloadTypes.Add(typeBindingInfo.type);\r\n            }\r\n        }\r\n\r\n        public void EndStaticModule(string moduleName)\r\n        {\r\n        }\r\n\r\n        public void AddDelegate(DelegateBridgeBindingInfo bindingInfo)\r\n        {\r\n            // unnecessary to generate delegate binding at the bind-generating phase\r\n        }\r\n    }\r\n}\r\n\r\n#endif "
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingCallback/ReflectBindingCallback.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: e948b86d09571e646bed10cd726044a7\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingCallback.meta",
    "content": "fileFormatVersion: 2\nguid: 2a9c4f9fb98435b4e97232c33374902b\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/DelegateBindingInfo.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\n\nnamespace QuickJS.Binding\n{\n    public class DelegateBindingInfo\n    {\n        public string name = null; // 绑定代码名\n        public string regName = null; // js 注册名\n        public string csName = null; // cs 代码名\n\n        public Type declaringType;\n        public Type delegateType;\n        public bool readable; // 可读\n        public bool writable; // 可写\n        public bool isStatic; // 静态\n\n        public bool isField;\n        public MemberInfo fieldOrPropertyInfo;\n\n        public DelegateBindingInfo(TypeBindingInfo typeBindingInfo, FieldInfo fieldInfo)\n        {\n            this.declaringType = typeBindingInfo.type;\n            this.delegateType = fieldInfo.FieldType;\n            this.readable = true;\n            this.writable = !fieldInfo.IsInitOnly;\n            this.isStatic = fieldInfo.IsStatic;\n            this.csName = fieldInfo.Name;\n            this.isField = true;\n            this.fieldOrPropertyInfo = fieldInfo;\n\n            do\n            {\n                if (this.isStatic)\n                {\n                    this.name = \"BindStaticDelegate_\" + fieldInfo.Name;\n                }\n                else\n                {\n                    this.name = \"BindDelegate_\" + fieldInfo.Name;\n                }\n            } while (false);\n\n            this.regName = typeBindingInfo.bindingManager.GetNamingAttribute(typeBindingInfo.transform, fieldInfo);\n        }\n\n        public DelegateBindingInfo(TypeBindingInfo typeBindingInfo, PropertyInfo propertyInfo)\n        {\n            this.declaringType = typeBindingInfo.type;\n            this.delegateType = propertyInfo.PropertyType;\n            var propInfoGetMethod = propertyInfo.GetGetMethod(true);\n            var propInfoSetMethod = propertyInfo.GetSetMethod(true);\n            this.readable = propInfoGetMethod != null && propInfoGetMethod.IsPublic;\n            this.writable = propInfoSetMethod != null && propInfoSetMethod.IsPublic;\n            this.isStatic = (propInfoGetMethod ?? propInfoSetMethod).IsStatic;\n            this.csName = propertyInfo.Name;\n            this.isField = false;\n            this.fieldOrPropertyInfo = propertyInfo;\n\n            if (this.isStatic)\n            {\n                this.name = \"BindStaticDelegate_\" + propertyInfo.Name;\n            }\n            else\n            {\n                this.name = \"BindDelegate_\" + propertyInfo.Name;\n            }\n\n            this.regName = typeBindingInfo.bindingManager.GetNamingAttribute(typeBindingInfo.transform, propertyInfo);\n        }\n    }\n}\n\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/DelegateBindingInfo.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 4839b4aca0f3d4643837ab4cffc8ac94\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/EventBindingInfo.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\n\nnamespace QuickJS.Binding\n{\n    public class EventBindingInfo\n    {\n        public string name = null; // 绑定代码名\n        public string regName = null; // js 注册名\n\n        public Type declaringType;\n        public EventInfo eventInfo;\n\n        public bool isStatic\n        {\n            get { return eventInfo.GetAddMethod().IsStatic; }\n        }\n\n        public EventBindingInfo(TypeBindingInfo typeBindingInfo, EventInfo eventInfo)\n        {\n            this.declaringType = typeBindingInfo.type;\n            this.eventInfo = eventInfo;\n\n            if (this.isStatic)\n            {\n                this.name = \"BindStaticEvent_\" + eventInfo.Name;\n            }\n            else\n            {\n                this.name = \"BindEvent_\" + eventInfo.Name;\n            }\n\n            this.regName = typeBindingInfo.bindingManager.GetNamingAttribute(typeBindingInfo.transform, eventInfo);\n        }\n    }\n}\n\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/EventBindingInfo.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 397948c0245c74f33a60c106290543b8\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/FieldBindingInfo.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\n\nnamespace QuickJS.Binding\n{\n    public class FieldBindingInfo\n    {\n        public string getterName = null; // 绑定代码名\n        public string setterName = null;\n        public string regName = null; // js 注册名\n\n        public FieldInfo fieldInfo;\n\n        public string constantValue;\n\n        public bool isStatic => fieldInfo.IsStatic;\n\n        public Type fieldType => fieldInfo.FieldType;\n\n        public FieldBindingInfo(TypeBindingInfo typeBindingInfo, FieldInfo fieldInfo)\n        {\n            do\n            {\n                if (fieldInfo.IsLiteral)\n                {\n                    try\n                    {\n                        var cv = fieldInfo.GetRawConstantValue();\n                        var cvType = cv.GetType();\n                        if (cvType == typeof(string))\n                        {\n                            constantValue = $\"\\\"{cv}\\\"\";\n                            break;\n                        }\n\n                        if (cvType == typeof(int)\n                            || cvType == typeof(uint)\n                            || cvType == typeof(byte)\n                            || cvType == typeof(sbyte)\n                            || cvType == typeof(short)\n                            || cvType == typeof(ushort)\n                            || cvType == typeof(bool))\n                        {\n                            constantValue = $\"{cv}\";\n                            break;\n                        }\n\n                        if (cvType == typeof(float))\n                        {\n                            var fcv = (float)cv;\n                            if (!float.IsInfinity(fcv)\n                                && !float.IsNaN(fcv))\n                            {\n                                constantValue = $\"{cv}\";\n                                break;\n                            }\n                        }\n\n                        // if (cvType.IsPrimitive && cvType.IsValueType)\n                        // {\n                        //     constantValue = $\"{cv}\";\n                        //     break;\n                        // }\n                    }\n                    catch (Exception)\n                    {\n                    }\n                }\n\n                if (fieldInfo.IsStatic)\n                {\n                    this.getterName = \"BindStaticRead_\" + fieldInfo.Name;\n                    if (!fieldInfo.IsInitOnly && !fieldInfo.IsLiteral)\n                    {\n                        this.setterName = \"BindStaticWrite_\" + fieldInfo.Name;\n                    }\n                }\n                else\n                {\n                    this.getterName = \"BindRead_\" + fieldInfo.Name;\n                    if (!fieldInfo.IsInitOnly && !fieldInfo.IsLiteral)\n                    {\n                        this.setterName = \"BindWrite_\" + fieldInfo.Name;\n                    }\n                }\n            } while (false);\n\n            this.regName = typeBindingInfo.bindingManager.GetNamingAttribute(typeBindingInfo.transform, fieldInfo);\n            this.fieldInfo = fieldInfo;\n        }\n    }\n}\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/FieldBindingInfo.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: abce51a09f23441a7a5c35d977caf981\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/MethodBaseBindingInfo.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\nusing System.Linq;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public abstract class MethodBaseBindingInfo<T>\r\n        where T : MethodBase\r\n    {\r\n        public string csBindName { get; set; } // 绑定代码名\r\n        public string jsName { get; set; } // 导出名\r\n\r\n        private int _count = 0;\r\n        private int _extensionCount = 0;\r\n\r\n        // 按照参数数逆序排序所有变体\r\n        // 有相同参数数量要求的方法记录在同一个 Variant 中 (变参方法按最少参数数计算, 不计变参参数数)\r\n        public SortedDictionary<int, MethodBaseVariant<T>> variants = new SortedDictionary<int, MethodBaseVariant<T>>(new MethodVariantComparer());\r\n\r\n        // 标记为 JSCFunction, 不生成包装代码, 直接注册给JS\r\n        // 必须为静态函数, 且函数签名完全匹配 JSCFunction\r\n        public MethodBase _cfunc;\r\n\r\n        /// <summary>\r\n        /// number of variants\r\n        /// </summary>\r\n        public int count => _count;\r\n\r\n        /// <summary>\r\n        /// number of extension methods in all variants\r\n        /// </summary>\r\n        public int extensionCount => _extensionCount;\r\n\r\n        public bool Add(T method, bool isExtension)\r\n        {\r\n            if (method.IsDefined(typeof(JSCFunctionAttribute), false))\r\n            {\r\n                if (!method.IsStatic || _cfunc != null)\r\n                {\r\n                    return false;\r\n                }\r\n                this._cfunc = method;\r\n                return true;\r\n            }\r\n\r\n            var parameters = method.GetParameters();\r\n            var nargs = BindingManager.GetTSParameterCount(parameters);\r\n            var isVararg = Binding.Values.IsVarargParameter(parameters);\r\n            MethodBaseVariant<T> variant;\r\n            if (isVararg)\r\n            {\r\n                --nargs;\r\n            }\r\n\r\n            if (isExtension)\r\n            {\r\n                --nargs;\r\n                ++_extensionCount;\r\n            }\r\n\r\n            if (!this.variants.TryGetValue(nargs, out variant))\r\n            {\r\n                variant = new MethodBaseVariant<T>(nargs);\r\n                this.variants.Add(nargs, variant);\r\n            }\r\n\r\n            if (variant.Add(method, isVararg, isExtension))\r\n            {\r\n                _count++;\r\n            }\r\n            return true;\r\n        }\r\n    }\r\n\r\n    public class MethodBindingInfo : MethodBaseBindingInfo<MethodInfo>\r\n    {\r\n        public MethodBindingInfo(BindingManager bindingManager, bool bStatic, string csName, string jsName)\r\n        {\r\n            this.csBindName = bindingManager.GetBindName(bStatic, csName);\r\n            this.jsName = jsName;\r\n        }\r\n    }\r\n\r\n    public class OperatorBindingInfo : MethodBaseBindingInfo<MethodInfo>\r\n    {\r\n        public int length; // 参数数\r\n        public string csName; // CS原始方法名 (op_xxx)\r\n        public string cs_op; // 绑定代码中的运算符\r\n        public MethodInfo methodInfo;\r\n        public bool isExtension;\r\n\r\n        // regName: js 中的重载运算符\r\n        public OperatorBindingInfo(BindingManager bindingManager, MethodInfo methodInfo, bool isExtension, bool bStatic, string csName, string jsName, string cs_op, int length)\r\n        {\r\n            this.methodInfo = methodInfo;\r\n            this.isExtension = isExtension;\r\n            this.length = length;\r\n            this.csName = csName;\r\n            this.jsName = jsName;\r\n            this.cs_op = cs_op;\r\n            this.csBindName = bindingManager.GetBindName(bStatic, csName + \"_qjs\");\r\n            if (methodInfo.DeclaringType.GetMethods().Count(m => m.IsSpecialName && m.Name.StartsWith(\"op_\") && m.Name == methodInfo.Name) > 1)\r\n            {\r\n                this.csBindName += \"_m\";\r\n            }\r\n\r\n            this.Add(methodInfo, isExtension); //NOTE: 旧代码, 待更替\r\n        }\r\n    }\r\n\r\n    public class ConstructorBindingInfo : MethodBaseBindingInfo<ConstructorInfo>\r\n    {\r\n        public Type decalringType;\r\n\r\n        // public 构造是否可用\r\n        public bool available\r\n        {\r\n            get\r\n            {\r\n                if (decalringType.IsGenericTypeDefinition)\r\n                {\r\n                    return false;\r\n                }\r\n                \r\n                if (decalringType.IsValueType && !decalringType.IsPrimitive && !decalringType.IsAbstract)\r\n                {\r\n                    return true; // default constructor for struct\r\n                }\r\n\r\n                return variants.Count > 0;\r\n            }\r\n        }\r\n\r\n        public ConstructorBindingInfo(BindingManager bindingManager, Type decalringType)\r\n        {\r\n            this.decalringType = decalringType;\r\n            this.csBindName = bindingManager.GetConstructorBindName();\r\n            this.jsName = \"constructor\";\r\n        }\r\n    }\r\n\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/MethodBaseBindingInfo.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 58ef2ae2782604a45a2691b7aa6f395d\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/MethodBaseVariant.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    // 所有具有相同参数数量的方法变体 (最少参数的情况下)\r\n    public class MethodBaseVariant<T>\r\n        where T : MethodBase\r\n    {\r\n        public class MethodBind\r\n        {\r\n            public T method;\r\n            public bool isExtension;\r\n\r\n            public MethodBind(T method, bool isExtension)\r\n            {\r\n                this.method = method;\r\n                this.isExtension = isExtension;\r\n            }\r\n\r\n            public bool CheckMethodEquality(ParameterInfo[] a, int aIndex, ParameterInfo[] b, int bIndex)\r\n            {\r\n                var aLen = a.Length - aIndex;\r\n                var bLen = b.Length - bIndex;\r\n                if (aLen != bLen)\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                while (aIndex < a.Length && bIndex < b.Length)\r\n                {\r\n                    var aInfo = a[aIndex++];\r\n                    var bInfo = b[bIndex++];\r\n                    if (aInfo.ParameterType != bInfo.ParameterType || aInfo.IsOut != bInfo.IsOut)\r\n                    {\r\n                        return false;\r\n                    }\r\n                }\r\n\r\n                return true;\r\n            }\r\n\r\n            public bool CheckMethodEquality(T method, bool isExtension)\r\n            {\r\n                return CheckMethodEquality(\r\n                    this.method.GetParameters(), this.isExtension ? 1 : 0,\r\n                    method.GetParameters(), isExtension ? 1 : 0\r\n                );\r\n            }\r\n        }\r\n\r\n        public int argc; // 最少参数数要求\r\n        public List<MethodBind> plainMethods = new List<MethodBind>();\r\n        public List<MethodBind> varargMethods = new List<MethodBind>();\r\n\r\n        // 是否包含变参方法\r\n        public bool isVararg\r\n        {\r\n            get { return varargMethods.Count > 0; }\r\n        }\r\n\r\n        public int count\r\n        {\r\n            get { return plainMethods.Count + varargMethods.Count; }\r\n        }\r\n\r\n        public MethodBaseVariant(int argc)\r\n        {\r\n            this.argc = argc;\r\n        }\r\n\r\n        public bool Add(T methodInfo, bool isVararg, bool isExtension)\r\n        {\r\n            //TODO: method 按照参数的具体程度排序以提高 match_type 的有效命中率\r\n            if (isVararg)\r\n            {\r\n                foreach (var entry in this.varargMethods)\r\n                {\r\n                    if (entry.CheckMethodEquality(methodInfo, isExtension))\r\n                    {\r\n                        return false;\r\n                    }\r\n                }\r\n                this.varargMethods.Add(new MethodBind(methodInfo, isExtension));\r\n            }\r\n            else\r\n            {\r\n                foreach (var entry in this.plainMethods)\r\n                {\r\n                    if (entry.CheckMethodEquality(methodInfo, isExtension))\r\n                    {\r\n                        return false;\r\n                    }\r\n                }\r\n                this.plainMethods.Add(new MethodBind(methodInfo, isExtension));\r\n            }\r\n            return true;\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/MethodBaseVariant.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 7a974f534fe7e4a779a7243eefd50283\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/MethodVariantComparer.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public class MethodVariantComparer : IComparer<int>\r\n    {\r\n        public int Compare(int a, int b)\r\n        {\r\n            return a < b ? 1 : (a == b ? 0 : -1);\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/MethodVariantComparer.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: ac456e24d33e94615931e328b437d71a\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/PropertyBindingInfo.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\n\nnamespace QuickJS.Binding\n{\n    public struct PropertyBindingPair\n    {\n        public string getterName; // 绑定代码名\n        public string setterName;\n\n        public bool IsValid()\n        {\n            return this.getterName != null || this.setterName != null;\n        }\n    }\n\n    public class PropertyBindingInfo\n    {\n        public PropertyBindingPair staticPair;\n\n        public PropertyBindingPair instancePair;\n\n        // public string getterName; // 绑定代码名\n        // public string setterName;\n        public string regName; // js 注册名\n        public PropertyInfo propertyInfo;\n\n        public readonly MethodInfo getMethod;\n\n        public readonly MethodInfo setMethod;\n\n        public bool isStatic => staticPair.IsValid();\n\n        public Type propertyType => propertyInfo.PropertyType;\n\n        public PropertyBindingInfo(TypeBindingInfo typeBindingInfo, PropertyInfo propertyInfo)\n        {\n            this.propertyInfo = propertyInfo;\n            this.getMethod = propertyInfo.GetGetMethod(true);\n            this.setMethod = propertyInfo.GetSetMethod(true);\n            if (propertyInfo.CanRead && getMethod != null && getMethod.IsPublic)\n            {\n                if (getMethod.IsStatic)\n                {\n                    staticPair.getterName = \"BindStaticRead_\" + propertyInfo.Name;\n                }\n                else\n                {\n                    instancePair.getterName = \"BindRead_\" + propertyInfo.Name;\n                }\n            }\n\n            if (propertyInfo.CanWrite && setMethod != null && setMethod.IsPublic)\n            {\n                if (setMethod.IsStatic)\n                {\n                    staticPair.setterName = \"BindStaticWrite_\" + propertyInfo.Name;\n                }\n                else\n                {\n                    instancePair.setterName = \"BindWrite_\" + propertyInfo.Name;\n                }\n            }\n\n            this.regName = typeBindingInfo.bindingManager.GetNamingAttribute(typeBindingInfo.transform, propertyInfo);\n        }\n    }\n\n}\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/PropertyBindingInfo.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 39f946f4ed9bd4017b73e7c617bd07d4\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/RawTypeBindingInfo.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.Collections.Generic;\nusing System.Reflection;\n\nnamespace QuickJS.Binding\n{\n    public class RawTypeBindingInfo\n    {\n        public readonly Type type;\n        public readonly string jsName;\n        public readonly MethodInfo method;\n\n        public RawTypeBindingInfo(Type type, MethodInfo method)\n        {\n            this.type = type;\n            this.jsName = type.Name;\n            this.method = method;\n        }\n    }\n}\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/RawTypeBindingInfo.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 030f7e69ba6fb42f98d58e7ce4fbb6c7\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/TSModuleBindingInfo.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public class TSModuleBindingInfo\r\n    {\r\n        private HashSet<string> _moduleAccessNames = new HashSet<string>();\r\n\r\n        public bool Contains(string name)\r\n        {\r\n            return _moduleAccessNames.Contains(name);\r\n        }\r\n\r\n        public void Add(string moduleEntry)\r\n        {\r\n            _moduleAccessNames.Add(moduleEntry);\r\n        }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/TSModuleBindingInfo.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: e79d5feef148fc34ba20f55ce0227179\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/TypeBindingFlags.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    [Flags]\r\n    public enum TypeBindingFlags\r\n    {\r\n        None = 0,\r\n        BindingCode = 1,  // 生成绑定代码\r\n        TypeDefinition = 2, // 生成 d.ts 声明\r\n        BuildTargetPlatformOnly = 4, \r\n\r\n        Default = BindingCode | TypeDefinition | BuildTargetPlatformOnly,\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/TypeBindingFlags.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 9fd04f053ee0848069007e174cfd506c\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/TypeBindingInfo.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public class TypeBindingInfo\r\n    {\r\n        public readonly BindingManager bindingManager;\r\n        public readonly Type type;\r\n\r\n        /// <summary>\r\n        /// 类型转换信息 (此处必不为空)\r\n        /// </summary>\r\n        public readonly TypeTransform transform;\r\n\r\n        public bool preload => operators.Count != 0;\r\n\r\n        public TypeBindingFlags bindingFlags => transform.bindingFlags;\r\n\r\n        public bool isAbstract => type.IsAbstract;\r\n\r\n        /// <summary>\r\n        /// 是否可以在脚本中继承此类型\r\n        /// </summary>\r\n        public bool crossbind => transform.crossbind;\r\n\r\n        /// <summary>\r\n        /// 是否完全由 JS 托管 (JS对象释放时, CS对象即释放)\r\n        /// </summary>\r\n        public bool disposable => transform.disposable;\r\n\r\n        /// <summary>\r\n        /// 是否生成绑定代码\r\n        /// </summary>\r\n        public bool genBindingCode => (bindingFlags & TypeBindingFlags.BindingCode) != 0;\r\n\r\n        // 父类类型\r\n        public Type super => type.BaseType;\r\n\r\n        public Type[] interfaces => type.GetInterfaces();\r\n\r\n        public Type[] directInterfaces => (from interfaceType in type.GetInterfaces() where CodeGenUtils.IsDirectlyImplements(type, interfaceType) select interfaceType).ToArray();\r\n\r\n        /// <summary>\r\n        /// 跳过此类型的导出\r\n        /// </summary>\r\n        public bool omit => _omit;\r\n\r\n        /// <summary>\r\n        /// 等价于 type.Assembly\r\n        /// </summary>\r\n        public Assembly Assembly => type.Assembly;\r\n\r\n        /// <summary>\r\n        /// 等价于 type.FullName\r\n        /// </summary>\r\n        public string FullName => type.FullName;\r\n\r\n        /// <summary>\r\n        /// 等价于 type.IsEnum\r\n        /// </summary>\r\n        public bool IsEnum => type.IsEnum;\r\n\r\n        private string _csBindingName;\r\n\r\n        /// <summary>\r\n        /// 绑定代码名\r\n        /// </summary>\r\n        public string csBindingName => _csBindingName;\r\n\r\n        public List<OperatorBindingInfo> operators = new List<OperatorBindingInfo>();\r\n\r\n        public Dictionary<string, MethodBindingInfo> methods = new Dictionary<string, MethodBindingInfo>();\r\n        public Dictionary<string, MethodBindingInfo> staticMethods = new Dictionary<string, MethodBindingInfo>();\r\n\r\n        public Dictionary<string, PropertyBindingInfo> properties = new Dictionary<string, PropertyBindingInfo>();\r\n        public Dictionary<string, FieldBindingInfo> fields = new Dictionary<string, FieldBindingInfo>();\r\n        public Dictionary<string, EventBindingInfo> events = new Dictionary<string, EventBindingInfo>();\r\n        public Dictionary<string, DelegateBindingInfo> delegates = new Dictionary<string, DelegateBindingInfo>();\r\n        public ConstructorBindingInfo constructors;\r\n\r\n        private ITSTypeNaming _tsTypeNaming;\r\n\r\n        /// <summary>\r\n        /// names for the typescript codegen\r\n        /// </summary>\r\n        public ITSTypeNaming tsTypeNaming => _tsTypeNaming;\r\n\r\n        private bool _omit;\r\n\r\n        public TypeBindingInfo(BindingManager bindingManager, Type type, TypeTransform typeTransform)\r\n        {\r\n            this.bindingManager = bindingManager;\r\n            this.type = type;\r\n            this.transform = typeTransform;\r\n            this._omit = type.IsDefined(typeof(JSOmitAttribute), false);\r\n        }\r\n\r\n        public void Initialize()\r\n        {\r\n            _tsTypeNaming = bindingManager.GetTSTypeNaming(type, true);\r\n            _csBindingName = bindingManager.prefs.typeBindingPrefix + CodeGenUtils.GetFileName(type);\r\n            CodeGenUtils.Assert(CodeGenUtils.IsValidTypeDeclarationName(_csBindingName), \"invalid binding name\");\r\n        }\r\n\r\n        public HashSet<string> GetRequiredDefines(MemberInfo memberInfo)\r\n        {\r\n            var setForMember = transform.GetRequiredDefinesOfMember(memberInfo.Name);\r\n            var declaringType = bindingManager.TransformType(memberInfo.DeclaringType);\r\n            var setForDeclaringType = declaringType?.requiredDefines;\r\n            if (setForMember != null)\r\n            {\r\n                if (setForDeclaringType != null)\r\n                {\r\n                    var set = new HashSet<string>(setForMember);\r\n                    set.UnionWith(setForDeclaringType);\r\n                    return set;\r\n                }\r\n                return setForMember;\r\n            }\r\n            return null;\r\n        }\r\n\r\n        public void AddEvent(EventInfo eventInfo)\r\n        {\r\n            try\r\n            {\r\n                bindingManager.CollectDelegate(eventInfo.EventHandlerType);\r\n                events.Add(eventInfo.Name, new EventBindingInfo(this, eventInfo));\r\n                bindingManager.Info(\"[AddEvent] {0}.{1}\", type, eventInfo.Name);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                bindingManager.Error(\"AddEvent failed {0} @ {1}: {2}\", eventInfo, type, exception.Message);\r\n            }\r\n        }\r\n\r\n        public void AddField(FieldInfo fieldInfo)\r\n        {\r\n            try\r\n            {\r\n                bindingManager.CollectDelegate(fieldInfo.FieldType);\r\n                if (fieldInfo.FieldType.BaseType == typeof(MulticastDelegate))\r\n                {\r\n                    delegates.Add(fieldInfo.Name, new DelegateBindingInfo(this, fieldInfo));\r\n                    bindingManager.Info(\"[AddField] As Delegate: {0}.{1}\", type, fieldInfo.Name);\r\n                }\r\n                else\r\n                {\r\n                    fields.Add(fieldInfo.Name, new FieldBindingInfo(this, fieldInfo));\r\n                    bindingManager.Info(\"[AddField] {0}.{1}\", type, fieldInfo.Name);\r\n                }\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                bindingManager.Error(\"AddField failed {0} @ {1}: {2}\", fieldInfo, type, exception.Message);\r\n            }\r\n        }\r\n\r\n        public void AddProperty(PropertyInfo propInfo)\r\n        {\r\n            try\r\n            {\r\n                bindingManager.CollectDelegate(propInfo.PropertyType);\r\n                if (propInfo.PropertyType.BaseType == typeof(MulticastDelegate))\r\n                {\r\n                    delegates.Add(propInfo.Name, new DelegateBindingInfo(this, propInfo));\r\n                    bindingManager.Info(\"[AddProperty] As Delegate: {0}.{1}\", type, propInfo.Name);\r\n                }\r\n                else\r\n                {\r\n                    properties.Add(propInfo.Name, new PropertyBindingInfo(this, propInfo));\r\n                    bindingManager.Info(\"[AddProperty] {0}.{1}\", type, propInfo.Name);\r\n                }\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                bindingManager.Error(\"AddProperty failed {0} @ {1}: {2}\", propInfo, type, exception.Message);\r\n            }\r\n        }\r\n\r\n        public bool IsSupportedOperators(MethodInfo methodInfo)\r\n        {\r\n            if (methodInfo.IsSpecialName && methodInfo.Name.StartsWith(\"op_\"))\r\n            {\r\n                // do not support overloaded operators at present\r\n                // if (methodInfo.DeclaringType.GetMethods().Count(m => m.IsSpecialName && m.Name.StartsWith(\"op_\") && m.Name == methodInfo.Name) == 1)\r\n                // {\r\n                //     return true;\r\n                // }\r\n                return true;\r\n            }\r\n            return false;\r\n        }\r\n\r\n        public bool IsOperatorOverloadingEnabled(MethodInfo methodInfo)\r\n        {\r\n            return Native.JSApi.IsOperatorOverloadingSupported && bindingManager.prefs.enableOperatorOverloading && transform.enableOperatorOverloading && IsSupportedOperators(methodInfo);\r\n        }\r\n\r\n        public void AddMethod(MethodInfo methodInfo, bool asExtensionAnyway)\r\n        {\r\n            if (this.transform.IsBlocked(methodInfo))\r\n            {\r\n                bindingManager.Info(\"skip blocked method: {0}\", methodInfo.Name);\r\n                return;\r\n            }\r\n\r\n            if (Values.register_type_caster(methodInfo))\r\n            {\r\n                bindingManager.Info(\"collected as type caster method: {0}.{1}\", methodInfo.DeclaringType.FullName, methodInfo.Name);\r\n                return;\r\n            }\r\n\r\n            // if (type.IsConstructedGenericType)\r\n            // {\r\n            //     var gTransform = bindingManager.GetTypeTransform(type.GetGenericTypeDefinition());\r\n            //     if (gTransform != null && gTransform.IsBlocked(methodInfo.??))\r\n            //     {\r\n            //         bindingManager.Info(\"skip blocked method in generic definition: {0}\", methodInfo.Name);\r\n            //         return;\r\n            //     }\r\n            // }\r\n\r\n            var isExtension = asExtensionAnyway || BindingManager.IsExtensionMethod(methodInfo);\r\n            var isStatic = methodInfo.IsStatic && !isExtension;\r\n\r\n            if (isStatic && type.IsGenericTypeDefinition)\r\n            {\r\n                bindingManager.Info(\"skip static method in generic type definition: {0}\", methodInfo.Name);\r\n                return;\r\n            }\r\n\r\n            var methodCSName = methodInfo.Name;\r\n            var methodJSName = this.bindingManager.GetNamingAttribute(this.transform, methodInfo);\r\n\r\n            if (IsOperatorOverloadingEnabled(methodInfo))\r\n            {\r\n                var parameters = methodInfo.GetParameters();\r\n                var declaringType = methodInfo.DeclaringType;\r\n                OperatorBindingInfo operatorBindingInfo = null;\r\n                switch (methodCSName)\r\n                {\r\n                    case \"op_LessThan\":\r\n                        if (parameters.Length == 2)\r\n                        {\r\n                            if (parameters[0].ParameterType == declaringType && parameters[1].ParameterType == declaringType)\r\n                            {\r\n                                operatorBindingInfo = new OperatorBindingInfo(bindingManager, methodInfo, isExtension, isStatic, methodCSName, \"<\", \"<\", 2);\r\n                            }\r\n                        }\r\n                        break;\r\n                    case \"op_Addition\":\r\n                        if (parameters.Length == 2)\r\n                        {\r\n                            if (parameters[0].ParameterType == declaringType && parameters[1].ParameterType == declaringType)\r\n                            {\r\n                                operatorBindingInfo = new OperatorBindingInfo(bindingManager, methodInfo, isExtension, isStatic, methodCSName, \"+\", \"+\", 2);\r\n                            }\r\n                        }\r\n                        break;\r\n                    case \"op_Subtraction\":\r\n                        if (parameters.Length == 2)\r\n                        {\r\n                            if (parameters[0].ParameterType == declaringType && parameters[1].ParameterType == declaringType)\r\n                            {\r\n                                operatorBindingInfo = new OperatorBindingInfo(bindingManager, methodInfo, isExtension, isStatic, methodCSName, \"-\", \"-\", 2);\r\n                            }\r\n                        }\r\n                        break;\r\n                    case \"op_Equality\":\r\n                        if (parameters.Length == 2)\r\n                        {\r\n                            if (parameters[0].ParameterType == declaringType && parameters[1].ParameterType == declaringType)\r\n                            {\r\n                                operatorBindingInfo = new OperatorBindingInfo(bindingManager, methodInfo, isExtension, isStatic, methodCSName, \"==\", \"==\", 2);\r\n                            }\r\n                        }\r\n                        break;\r\n                    case \"op_Multiply\":\r\n                        if (parameters.Length == 2)\r\n                        {\r\n                            var op0 = bindingManager.GetExportedType(parameters[0].ParameterType);\r\n                            var op1 = bindingManager.GetExportedType(parameters[1].ParameterType);\r\n                            if (op0 != null && op1 != null)\r\n                            {\r\n                                var bindingName = methodCSName + \"_\" + op0.csBindingName + \"_\" + op1.csBindingName;\r\n                                operatorBindingInfo = new OperatorBindingInfo(bindingManager, methodInfo, isExtension, isStatic, bindingName, \"*\", \"*\", 2);\r\n                            }\r\n                        }\r\n                        break;\r\n                    case \"op_Division\":\r\n                        if (parameters.Length == 2)\r\n                        {\r\n                            var op0 = bindingManager.GetExportedType(parameters[0].ParameterType);\r\n                            var op1 = bindingManager.GetExportedType(parameters[1].ParameterType);\r\n                            if (op0 != null && op1 != null)\r\n                            {\r\n                                var bindingName = methodCSName + \"_\" + op0.csBindingName + \"_\" + op1.csBindingName;\r\n                                operatorBindingInfo = new OperatorBindingInfo(bindingManager, methodInfo, isExtension, isStatic, bindingName, \"/\", \"/\", 2);\r\n                            }\r\n                        }\r\n                        break;\r\n                    case \"op_UnaryNegation\":\r\n                        {\r\n                            operatorBindingInfo = new OperatorBindingInfo(bindingManager, methodInfo, isExtension, isStatic, methodCSName, \"neg\", \"-\", 1);\r\n                        }\r\n                        break;\r\n                }\r\n\r\n                if (operatorBindingInfo != null)\r\n                {\r\n                    operators.Add(operatorBindingInfo);\r\n                    CollectDelegate(methodInfo);\r\n                    bindingManager.Info(\"[AddOperator] {0}.{1}\", type, methodInfo);\r\n                    if (!bindingManager.prefs.alwaysEmitOperatorMethod)\r\n                    {\r\n                        return;\r\n                    }\r\n                }\r\n\r\n                // fallback to normal method binding\r\n            }\r\n\r\n            var group = isStatic ? staticMethods : methods;\r\n            MethodBindingInfo methodBindingInfo;\r\n            if (!group.TryGetValue(methodJSName, out methodBindingInfo))\r\n            {\r\n                methodBindingInfo = new MethodBindingInfo(bindingManager, isStatic, methodCSName, methodJSName);\r\n                group.Add(methodJSName, methodBindingInfo);\r\n            }\r\n\r\n            if (!methodBindingInfo.Add(methodInfo, isExtension))\r\n            {\r\n                bindingManager.Info(\"fail to add method: {0}\", methodInfo.Name);\r\n                return;\r\n            }\r\n\r\n            CollectDelegate(methodInfo);\r\n            bindingManager.Info(\"[AddMethod] {0}.{1}\", type, methodInfo);\r\n        }\r\n\r\n        public void AddMethod(Native.JSCFunction func)\r\n        {\r\n            var group = staticMethods;\r\n            MethodBindingInfo methodBindingInfo;\r\n            var methodCSName = func.Method.Name;\r\n            var methodJSName = this.bindingManager.GetNamingAttribute(this.transform, func.Method);\r\n            if (!group.TryGetValue(methodJSName, out methodBindingInfo))\r\n            {\r\n                methodBindingInfo = new MethodBindingInfo(bindingManager, true, methodCSName, methodJSName);\r\n                group.Add(methodJSName, methodBindingInfo);\r\n            }\r\n\r\n            methodBindingInfo._cfunc = func.Method;\r\n        }\r\n\r\n        private void CollectDelegate(MethodBase method)\r\n        {\r\n            var parameters = method.GetParameters();\r\n            for (var i = 0; i < parameters.Length; i++)\r\n            {\r\n                bindingManager.CollectDelegate(parameters[i].ParameterType);\r\n            }\r\n        }\r\n\r\n        public void AddConstructor(ConstructorInfo constructorInfo)\r\n        {\r\n            if (!constructors.Add(constructorInfo, false))\r\n            {\r\n                bindingManager.Info(\"add constructor failed: {0}\", constructorInfo.Name);\r\n                return;\r\n            }\r\n            CollectDelegate(constructorInfo);\r\n            this.bindingManager.Info(\"[AddConstructor] {0}.{1}\", type, constructorInfo);\r\n        }\r\n\r\n        // 收集所有 字段,属性,方法\r\n        public void Collect()\r\n        {\r\n            this.constructors = new ConstructorBindingInfo(bindingManager, type);\r\n\r\n            var bindingFlags = Binding.DynamicType.PublicFlags;\r\n            var fields = type.GetFields(bindingFlags);\r\n            foreach (var field in fields)\r\n            {\r\n                if (field.IsSpecialName || field.Name.StartsWith(\"_JSFIX_\"))\r\n                {\r\n                    bindingManager.Info(\"skip special field: {0}\", field.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (field.IsStatic && type.IsGenericTypeDefinition)\r\n                {\r\n                    bindingManager.Info(\"skip static field in generic type definition: {0}\", field.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (field.FieldType.IsPointer)\r\n                {\r\n                    bindingManager.Info(\"skip pointer field: {0}\", field.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (field.IsDefined(typeof(JSOmitAttribute), false))\r\n                {\r\n                    bindingManager.Info(\"skip omitted field: {0}\", field.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (bindingManager.prefs.excludeObsoleteItems && field.IsDefined(typeof(ObsoleteAttribute), false))\r\n                {\r\n                    bindingManager.Info(\"skip obsolete field: {0}\", field.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (field.IsDefined(typeof(System.Runtime.CompilerServices.FixedBufferAttribute), false))\r\n                {\r\n                    bindingManager.Info(\"skip unsupported field (FixedBuffer): {0}\", field.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (transform.IsMemberBlocked(field.Name))\r\n                {\r\n                    bindingManager.Info(\"skip blocked field: {0}\", field.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (transform.Filter(field))\r\n                {\r\n                    bindingManager.Info(\"skip filtered field: {0}\", field.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (field.FieldType.BaseType == typeof(MulticastDelegate))\r\n                {\r\n                    if (!bindingManager.IsSupportedAsDelegate(field.FieldType))\r\n                    {\r\n                        bindingManager.Info(\"skip unsupported delegate field: {0}\", field.Name);\r\n                        continue;\r\n                    }\r\n                }\r\n\r\n                AddField(field);\r\n            }\r\n\r\n            var events = type.GetEvents(bindingFlags);\r\n            foreach (var evt in events)\r\n            {\r\n                if (evt.IsSpecialName)\r\n                {\r\n                    bindingManager.Info(\"skip special event: {0}\", evt.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (evt.EventHandlerType.IsPointer)\r\n                {\r\n                    bindingManager.Info(\"skip pointer event: {0}\", evt.Name);\r\n                    continue;\r\n                }\r\n\r\n                if ((evt.GetAddMethod(true)?.IsStatic == true || evt.GetRemoveMethod(true)?.IsStatic == true) && type.IsGenericTypeDefinition)\r\n                {\r\n                    bindingManager.Info(\"skip static event in generic type definition: {0}\", evt.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (bindingManager.prefs.excludeObsoleteItems && evt.IsDefined(typeof(ObsoleteAttribute), false))\r\n                {\r\n                    bindingManager.Info(\"skip obsolete event: {0}\", evt.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (evt.IsDefined(typeof(JSOmitAttribute), false))\r\n                {\r\n                    bindingManager.Info(\"skip omitted event: {0}\", evt.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (transform.IsMemberBlocked(evt.Name))\r\n                {\r\n                    bindingManager.Info(\"skip blocked event: {0}\", evt.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (transform.Filter(evt))\r\n                {\r\n                    bindingManager.Info(\"skip filtered event: {0}\", evt.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (!bindingManager.IsSupportedAsDelegate(evt.EventHandlerType))\r\n                {\r\n                    bindingManager.Info(\"skip unsupported delegate event: {0}\", evt.Name);\r\n                    continue;\r\n                }\r\n\r\n                AddEvent(evt);\r\n            }\r\n\r\n            var properties = type.GetProperties(bindingFlags);\r\n            foreach (var property in properties)\r\n            {\r\n                if (property.IsSpecialName)\r\n                {\r\n                    bindingManager.Info(\"skip special property: {0}\", property.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (property.PropertyType.IsPointer)\r\n                {\r\n                    bindingManager.Info(\"skip pointer property: {0}\", property.Name);\r\n                    continue;\r\n                }\r\n\r\n                var propInfoGetMethod = property.GetGetMethod(true);\r\n                var propInfoSetMethod = property.GetSetMethod(true);\r\n\r\n                if ((propInfoGetMethod?.IsStatic == true || propInfoSetMethod?.IsStatic == true) && type.IsGenericTypeDefinition)\r\n                {\r\n                    bindingManager.Info(\"skip static property in generic type definition: {0}\", property.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (property.IsDefined(typeof(JSOmitAttribute), false))\r\n                {\r\n                    bindingManager.Info(\"skip omitted property: {0}\", property.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (bindingManager.prefs.excludeObsoleteItems && property.IsDefined(typeof(ObsoleteAttribute), false))\r\n                {\r\n                    bindingManager.Info(\"skip obsolete property: {0}\", property.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (transform.IsMemberBlocked(property.Name))\r\n                {\r\n                    bindingManager.Info(\"skip blocked property: {0}\", property.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (transform.Filter(property))\r\n                {\r\n                    bindingManager.Info(\"skip filtered property: {0}\", property.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (property.PropertyType.BaseType == typeof(MulticastDelegate))\r\n                {\r\n                    if (!bindingManager.IsSupportedAsDelegate(property.PropertyType))\r\n                    {\r\n                        bindingManager.Info(\"skip unsupported delegate property: {0}\", property.Name);\r\n                        continue;\r\n                    }\r\n                }\r\n\r\n                //NOTE: special name for Indexer\r\n                if (property.Name == \"Item\")\r\n                {\r\n                    if (property.CanRead && propInfoGetMethod != null && propInfoGetMethod.IsPublic)\r\n                    {\r\n                        if (BindingManager.IsUnsupported(propInfoGetMethod))\r\n                        {\r\n                            bindingManager.Info(\"skip unsupported get-method: {0}\", propInfoGetMethod);\r\n                            continue;\r\n                        }\r\n\r\n                        AddMethod(propInfoGetMethod, false);\r\n                    }\r\n\r\n                    if (property.CanWrite && propInfoSetMethod != null && propInfoSetMethod.IsPublic)\r\n                    {\r\n                        if (BindingManager.IsUnsupported(propInfoSetMethod))\r\n                        {\r\n                            bindingManager.Info(\"skip unsupported set-method: {0}\", propInfoSetMethod);\r\n                            continue;\r\n                        }\r\n\r\n                        AddMethod(propInfoSetMethod, false);\r\n                    }\r\n\r\n                    // bindingManager.Info(\"skip indexer property: {0}\", property.Name);\r\n                    continue;\r\n                }\r\n\r\n                AddProperty(property);\r\n            }\r\n\r\n            if (!type.IsAbstract)\r\n            {\r\n                var constructors = type.GetConstructors();\r\n                foreach (var constructor in constructors)\r\n                {\r\n                    if (constructor.IsDefined(typeof(JSOmitAttribute), false))\r\n                    {\r\n                        bindingManager.Info(\"skip omitted constructor: {0}\", constructor);\r\n                        continue;\r\n                    }\r\n\r\n                    if (bindingManager.prefs.excludeObsoleteItems && constructor.IsDefined(typeof(ObsoleteAttribute), false))\r\n                    {\r\n                        bindingManager.Info(\"skip obsolete constructor: {0}\", constructor);\r\n                        continue;\r\n                    }\r\n\r\n                    if (BindingManager.ContainsPointer(constructor))\r\n                    {\r\n                        bindingManager.Info(\"skip pointer-param constructor: {0}\", constructor);\r\n                        continue;\r\n                    }\r\n\r\n                    if (BindingManager.ContainsByRefParameters(constructor))\r\n                    {\r\n                        bindingManager.Info(\"skip byref-param constructor: {0}\", constructor);\r\n                        continue;\r\n                    }\r\n\r\n                    if (transform.Filter(constructor))\r\n                    {\r\n                        bindingManager.Info(\"skip filtered constructor: {0}\", constructor.Name);\r\n                        continue;\r\n                    }\r\n\r\n                    if (transform.IsBlocked(constructor))\r\n                    {\r\n                        bindingManager.Info(\"skip blocked constructor: {0}\", constructor.Name);\r\n                        continue;\r\n                    }\r\n\r\n                    if (!bindingManager.IsSupportedMethod(typeof(void), constructor))\r\n                    {\r\n                        bindingManager.Info(\"skip unsupported constructor: {0}\", constructor.Name);\r\n                        continue;\r\n                    }\r\n\r\n                    AddConstructor(constructor);\r\n                }\r\n            }\r\n\r\n            CollectMethods(type.GetMethods(bindingFlags), false);\r\n            CollectMethods(transform.extensionMethods, true);\r\n            CollectMethods(transform.staticMethods, false);\r\n        }\r\n\r\n        private void CollectMethods(IEnumerable<Native.JSCFunction> funcs, bool asExtensionAnyway)\r\n        {\r\n            if (funcs == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            foreach (var func in funcs)\r\n            {\r\n                AddMethod(func);\r\n            }\r\n        }\r\n\r\n        private void CollectMethods(IEnumerable<MethodInfo> methods, bool asExtensionAnyway)\r\n        {\r\n            if (methods == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            foreach (var method in methods)\r\n            {\r\n                if (method.IsSpecialName)\r\n                {\r\n                    if (!IsSupportedOperators(method))\r\n                    {\r\n                        bindingManager.Info(\"skip special method: {0}\", method);\r\n                        continue;\r\n                    }\r\n                }\r\n\r\n                if (method.IsDefined(typeof(JSOmitAttribute), false))\r\n                {\r\n                    bindingManager.Info(\"skip omitted method: {0}\", method);\r\n                    continue;\r\n                }\r\n\r\n                if (bindingManager.prefs.excludeObsoleteItems && method.IsDefined(typeof(ObsoleteAttribute), false))\r\n                {\r\n                    bindingManager.Info(\"skip obsolete method: {0}\", method);\r\n                    continue;\r\n                }\r\n\r\n                if (transform.IsMemberBlocked(method.Name))\r\n                {\r\n                    bindingManager.Info(\"skip blocked method: {0}\", method.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (transform.Filter(method))\r\n                {\r\n                    bindingManager.Info(\"skip filtered method: {0}\", method.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (!bindingManager.IsSupportedMethod(method.ReturnType, method))\r\n                {\r\n                    bindingManager.Info(\"skip unsupported method: {0}\", method.Name);\r\n                    continue;\r\n                }\r\n\r\n                if (asExtensionAnyway || BindingManager.IsExtensionMethod(method))\r\n                {\r\n                    var targetType = method.GetParameters()[0].ParameterType;\r\n                    var targetInfo = bindingManager.GetExportedType(targetType);\r\n                    if (targetInfo != null)\r\n                    {\r\n                        targetInfo.AddMethod(method, true);\r\n                        continue;\r\n                    }\r\n                }\r\n\r\n                AddMethod(method, false);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// 按照 TypeBindingInfo 的记录, 进行动态类型的成员绑定.\r\n        /// </summary>\r\n        public Binding.ClassDecl DoReflectBind(Binding.TypeRegister register, Module.ProxyModuleRegister proxyModuleRegister)\r\n        {\r\n            var typeDB = register.GetTypeDB();\r\n            var dynamicType = typeDB.CreateFreeDynamicType(type);\r\n\r\n            Binding.ClassDecl cls;\r\n\r\n            if (transform.csConstructorOverride != null)\r\n            {\r\n                cls = register.CreateClass(type.Name, type, transform.csConstructorOverride);\r\n            }\r\n            else\r\n            {\r\n                var dynamicConstructor = default(Binding.IDynamicMethod);\r\n\r\n                if (crossbind)\r\n                {\r\n                    dynamicConstructor = new Binding.DynamicCrossBindConstructor();\r\n                }\r\n                else\r\n                {\r\n                    if (constructors.count > 0)\r\n                    {\r\n                        var dynamicCtorGroup = new Binding.DynamicMethods(dynamicType, \"constructor\", 1);\r\n                        foreach (var variant in constructors.variants)\r\n                        {\r\n                            foreach (var methodBind in variant.Value.plainMethods)\r\n                            {\r\n                                var dynamicCtor = new Binding.DynamicConstructor(dynamicType, methodBind.method, this.disposable);\r\n\r\n                                dynamicCtorGroup.Add(dynamicCtor);\r\n                            }\r\n                        }\r\n                        dynamicConstructor = dynamicCtorGroup;\r\n                    }\r\n                    else\r\n                    {\r\n                        // struct 默认无参构造\r\n                        dynamicConstructor = new Binding.DynamicDefaultConstructor(dynamicType);\r\n                    }\r\n                }\r\n                cls = register.CreateClass(type.Name, type, dynamicConstructor);\r\n            }\r\n\r\n            foreach (var pair in staticMethods)\r\n            {\r\n                var methodBindingInfo = pair.Value;\r\n                var methodJSName = methodBindingInfo.jsName;\r\n                var jscOverride = transform.GetCSMethodOverrideBinding(methodJSName);\r\n\r\n                if (jscOverride != null)\r\n                {\r\n                    cls.AddMethod(true, methodJSName, jscOverride);\r\n                }\r\n                else if (methodBindingInfo._cfunc != null)\r\n                {\r\n                    var dynamicMethod = new Binding.DynamicPrimitiveMethod(dynamicType, methodBindingInfo._cfunc);\r\n                    cls.AddMethod(true, methodJSName, dynamicMethod);\r\n                }\r\n                else\r\n                {\r\n                    var methodGroup = new Binding.DynamicMethods(dynamicType, methodJSName, 0);\r\n\r\n                    foreach (var variantKV in methodBindingInfo.variants)\r\n                    {\r\n                        var expectedArgCount = variantKV.Key;\r\n                        var variant = variantKV.Value;\r\n\r\n                        foreach (var mb in variant.plainMethods)\r\n                        {\r\n                            var dynamicMethod = Binding.DynamicMethodFactory.CreateMethod(dynamicType, mb.method, mb.isExtension);\r\n                            methodGroup.Add(dynamicMethod);\r\n                        }\r\n\r\n                        foreach (var mb in variant.varargMethods)\r\n                        {\r\n                            var dynamicMethod = Binding.DynamicMethodFactory.CreateMethod(dynamicType, mb.method, mb.isExtension);\r\n                            methodGroup.Add(dynamicMethod);\r\n                        }\r\n                    }\r\n\r\n                    cls.AddMethod(true, methodJSName, methodGroup);\r\n                }\r\n            }\r\n\r\n            foreach (var pair in methods)\r\n            {\r\n                var methodBindingInfo = pair.Value;\r\n                var methodJSName = methodBindingInfo.jsName;\r\n                var jscOverride = transform.GetCSMethodOverrideBinding(methodJSName);\r\n\r\n                if (jscOverride != null)\r\n                {\r\n                    cls.AddMethod(false, methodJSName, jscOverride);\r\n                }\r\n                else\r\n                {\r\n                    var methodGroup = new Binding.DynamicMethods(dynamicType, methodJSName, 0);\r\n\r\n                    foreach (var variantKV in methodBindingInfo.variants)\r\n                    {\r\n                        var expectedArgCount = variantKV.Key;\r\n                        var variant = variantKV.Value;\r\n\r\n                        foreach (var mb in variant.plainMethods)\r\n                        {\r\n                            var dynamicMethod = Binding.DynamicMethodFactory.CreateMethod(dynamicType, mb.method, mb.isExtension);\r\n                            methodGroup.Add(dynamicMethod);\r\n                        }\r\n\r\n                        foreach (var mb in variant.varargMethods)\r\n                        {\r\n                            var dynamicMethod = Binding.DynamicMethodFactory.CreateMethod(dynamicType, mb.method, mb.isExtension);\r\n                            methodGroup.Add(dynamicMethod);\r\n                        }\r\n                    }\r\n\r\n                    cls.AddMethod(false, methodJSName, methodGroup);\r\n                }\r\n            }\r\n\r\n            foreach (var pair in properties)\r\n            {\r\n                var propertyBindingInfo = pair.Value;\r\n                var isStatic = propertyBindingInfo.isStatic;\r\n                var tsPropertyVar = BindingManager.GetTSVariable(propertyBindingInfo.regName);\r\n                var dynamicProperty = new Binding.DynamicProperty(dynamicType, propertyBindingInfo.propertyInfo);\r\n\r\n                cls.AddField(isStatic, propertyBindingInfo.regName, dynamicProperty);\r\n            }\r\n\r\n            foreach (var pair in fields)\r\n            {\r\n                var fieldBindingInfo = pair.Value;\r\n                var isStatic = fieldBindingInfo.isStatic;\r\n                var tsPropertyVar = BindingManager.GetTSVariable(fieldBindingInfo.regName);\r\n                var dynamicField = new Binding.DynamicField(dynamicType, fieldBindingInfo.fieldInfo);\r\n\r\n                cls.AddField(isStatic, fieldBindingInfo.regName, dynamicField);\r\n            }\r\n\r\n            // 注册事件\r\n            foreach (var pair in events)\r\n            {\r\n                var eventBindingInfo = pair.Value;\r\n                var tsDelegateVar = BindingManager.GetTSVariable(eventBindingInfo.regName);\r\n                var dynamicMethod = new Binding.DynamicEventDelegateOp(dynamicType, eventBindingInfo.eventInfo, tsDelegateVar);\r\n\r\n                cls.AddMethod(eventBindingInfo.isStatic, tsDelegateVar, dynamicMethod);\r\n            }\r\n\r\n            // 注册委托\r\n            foreach (var pair in delegates)\r\n            {\r\n                var delegateBindingInfo = pair.Value;\r\n                var tsDelegateVar = BindingManager.GetTSVariable(delegateBindingInfo.regName);\r\n                Binding.IDynamicMethod dynamicMethod = null;\r\n\r\n                if (delegateBindingInfo.isField)\r\n                {\r\n                    dynamicMethod = new Binding.DynamicFieldDelegateOp(dynamicType, (FieldInfo)delegateBindingInfo.fieldOrPropertyInfo, tsDelegateVar);\r\n                }\r\n                else\r\n                {\r\n                    dynamicMethod = new Binding.DynamicPropertyDelegateOp(dynamicType, (PropertyInfo)delegateBindingInfo.fieldOrPropertyInfo, tsDelegateVar);\r\n                }\r\n\r\n                cls.AddMethod(delegateBindingInfo.isStatic, tsDelegateVar, dynamicMethod);\r\n            }\r\n\r\n            // 注册运算符\r\n            if (Native.JSApi.JS_ATOM_Operators.IsValid)\r\n            {\r\n                if (operators.Count > 0)\r\n                {\r\n                    //TODO: 目前运算符必须在同一个 TypeRegister 实例中注册\r\n                    // proxyModuleRegister.MarkAsCritical();\r\n                }\r\n\r\n                foreach (var operatorBindingInfo in operators)\r\n                {\r\n                    var dynamicMethod = Binding.DynamicMethodFactory.CreateMethod(dynamicType, operatorBindingInfo.methodInfo, operatorBindingInfo.isExtension);\r\n                    var regName = operatorBindingInfo.jsName;\r\n                    var parameters = operatorBindingInfo.methodInfo.GetParameters();\r\n                    var declaringType = operatorBindingInfo.methodInfo.DeclaringType;\r\n\r\n                    do\r\n                    {\r\n                        if (parameters.Length == 2)\r\n                        {\r\n                            if (parameters[0].ParameterType != declaringType)\r\n                            {\r\n                                var leftType = parameters[0].ParameterType;\r\n                                cls.AddLeftOperator(regName, dynamicMethod, leftType);\r\n                                break;\r\n                            }\r\n                            else if (parameters[1].ParameterType != declaringType)\r\n                            {\r\n                                var rightType = parameters[1].ParameterType;\r\n                                cls.AddRightOperator(regName, dynamicMethod, rightType);\r\n                                break;\r\n                            }\r\n                        }\r\n\r\n                        cls.AddSelfOperator(regName, dynamicMethod);\r\n                    } while (false);\r\n                }\r\n            }\r\n\r\n            return cls;\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/TypeBindingInfo.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: aba63f24a2cdf4c438dc46858454514a\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/TypeNaming/LegacyTSTypeNaming.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.Collections.Generic;\n\nnamespace QuickJS.Binding\n{\n    public class LegacyTSTypeNaming : ITSTypeNaming\n    {\n        public override void Initialize(BindingManager bindingManager, Type type)\n        {\n            this.moduleName = type.Namespace ?? \"\";\n            var tsNaming = bindingManager.GetTypeTransform(type)?.GetTSNaming();\n\n            if (tsNaming == null)\n            {\n                genericDefinition = \"\";\n\n                // remove the suffix primitive array types\n                tsNaming = type.IsArray ? type.Name.Substring(0, type.Name.Length - 2) : type.Name;\n                var gArgIndex = tsNaming.IndexOf('`');\n                if (gArgIndex >= 0)\n                {\n                    tsNaming = tsNaming.Substring(0, gArgIndex);\n                }\n\n                // flattening constructed generic type\n                if (type.IsGenericType && !type.IsGenericTypeDefinition)\n                {\n                    foreach (var gp in type.GetGenericArguments())\n                    {\n                        tsNaming += \"_\" + gp.Name;\n                    }\n                }\n            }\n            else\n            {\n                var gArgIndex = tsNaming.IndexOf('<');\n                if (gArgIndex >= 0)\n                {\n                    genericDefinition = tsNaming.Substring(gArgIndex);\n                    tsNaming = tsNaming.Substring(0, gArgIndex);\n                }\n                else\n                {\n                    genericDefinition = \"\";\n                }\n            }\n\n            var headingPath = new List<string>();\n\n            // 处理内部类层级\n            var declaringType = type.DeclaringType;\n            while (declaringType != null)\n            {\n                headingPath.Insert(0, StripCSharpGenericDefinition(declaringType.Name));\n                declaringType = declaringType.DeclaringType;\n            }\n            headingPath.Add(tsNaming);\n            classPath = headingPath.ToArray();\n        }\n    }\n}\n\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/TypeNaming/LegacyTSTypeNaming.cs.meta",
    "content": "fileFormatVersion: 2\nguid: df27d0d1d04cb5146b23b38170b84bdd\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/TypeNaming/SingularTSTypeNaming.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.Collections.Generic;\n\nnamespace QuickJS.Binding\n{\n    public class SingularTSTypeNaming : ITSTypeNaming\n    {\n        public override void Initialize(BindingManager bindingManager, Type type)\n        {\n            this.moduleName = bindingManager.prefs.singularModuleName;\n            var tsNaming = bindingManager.GetTypeTransform(type)?.GetTSNaming();\n\n            if (tsNaming == null)\n            {\n                genericDefinition = \"\";\n\n                // remove the suffix primitive array types\n                tsNaming = type.IsArray ? type.Name.Substring(0, type.Name.Length - 2) : type.Name;\n                var gArgIndex = tsNaming.IndexOf('`');\n                if (gArgIndex >= 0)\n                {\n                    tsNaming = tsNaming.Substring(0, gArgIndex);\n                }\n\n                // flattening constructed generic type\n                if (type.IsGenericType && !type.IsGenericTypeDefinition)\n                {\n                    foreach (var gp in type.GetGenericArguments())\n                    {\n                        tsNaming += \"_\" + gp.Name;\n                    }\n                }\n            }\n            else\n            {\n                var gArgIndex = tsNaming.IndexOf('<');\n                if (gArgIndex >= 0)\n                {\n                    genericDefinition = tsNaming.Substring(gArgIndex);\n                    tsNaming = tsNaming.Substring(0, gArgIndex);\n                }\n                else\n                {\n                    genericDefinition = \"\";\n                }\n            }\n\n            var headingPath = new List<string>();\n\n            // extract the nested class hierarchy\n            var declaringType = type.DeclaringType;\n            var lastType = type;\n            while (declaringType != null)\n            {\n                headingPath.Insert(0, StripCSharpGenericDefinition(declaringType.Name));\n                lastType = declaringType;\n                declaringType = declaringType.DeclaringType;\n            }\n\n            if (lastType.Namespace != null)\n            {\n                headingPath.InsertRange(0, lastType.Namespace.Split('.'));\n            }\n\n            headingPath.Add(tsNaming);\n            classPath = headingPath.ToArray();\n        }\n    }\n}\n\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/TypeNaming/SingularTSTypeNaming.cs.meta",
    "content": "fileFormatVersion: 2\nguid: b6527b8548499bb45983da4f097b5f41\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/TypeNaming/TSTypeNaming.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.Collections.Generic;\n\nnamespace QuickJS.Binding\n{\n    public abstract class ITSTypeNaming\n    {\n        /// <summary>\n        /// js module name <br/>\n        /// NOTE: in legacy mode, it will be empty if the corresponding csharp type is not in namespace\n        /// </summary>\n        public string moduleName { get; protected set; }\n\n        /// <summary>\n        /// full path of class apart from the generic arguments of generic type definition\n        /// </summary>\n        public string[] classPath { get; protected set; }\n\n        /// <summary>\n        /// (optional) only for renamed types\n        /// </summary>\n        public string genericDefinition { get; protected set; }\n\n        /// <summary>\n        /// e.g NS1 from NS1.OUT1.THIS\n        /// </summary>\n        public string moduleEntry => classPath[0];\n\n        public string className => classPath[classPath.Length - 1];\n\n        /// <summary>\n        /// joined the class path without the type name (the last element)\n        /// e.g NS1.OUT1 from NS1.OUT1.THIS\n        /// </summary>\n        public string ns => classPath.Length == 1 ? string.Empty : CodeGenUtils.Join(\".\", classPath, 0, classPath.Length - 1);\n\n        /// <summary>\n        /// full name without generic part\n        /// </summary>\n        public string GetFullName(string alias = null)\n        {\n            if (alias == null)\n            {\n                return CodeGenUtils.Join(\".\", CodeGenUtils.Join(\".\", classPath, 0, classPath.Length), genericDefinition);\n            }\n            return CodeGenUtils.Join(\".\", CodeGenUtils.Join(\".\", alias, CodeGenUtils.Join(\".\", classPath, 1, classPath.Length - 1)), genericDefinition);\n        }\n\n        protected string StripCSharpGenericDefinition(string typeName)\n        {\n            var gArgIndex = typeName.IndexOf('`');\n            return gArgIndex < 0 ? typeName : typeName.Substring(0, gArgIndex);\n        }\n\n        public abstract void Initialize(BindingManager bindingManager, Type type);\n    }\n}\n\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/TypeNaming/TSTypeNaming.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 67b2c3a0b905fa94cbd5f3d1f036379a\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo/TypeNaming.meta",
    "content": "fileFormatVersion: 2\nguid: 8a43c2a7efae64c4e99a42ce939ebfe2\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingInfo.meta",
    "content": "fileFormatVersion: 2\nguid: 44cecc170cc417e438d6bde43046bd44\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingLogger.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public interface IBindingLogger\r\n    {\r\n        void Log(string message);\r\n        void LogWarning(string message);\r\n        void LogError(string message);\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingLogger.cs.meta",
    "content": "fileFormatVersion: 2\nguid: bb6156e4abe14644d94d70cccdfcfbe4\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingManager.cs",
    "content": "﻿#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Text.RegularExpressions;\n\nnamespace QuickJS.Binding\n{\n    public partial class BindingManager\n    {\n        public struct Args\n        {\n            public ICodeGenCallback codeGenCallback;\n            public IBindingCallback bindingCallback;\n            public IBindingLogger bindingLogger;\n            public Utils.IJsonConverter jsonConverter;\n            public IBindingUtils utils;\n            public bool useLogWriter;\n        }\n\n        public static Native.JSCFunctionMagic DefaultPrivateConstructor = JSNative.class_private_ctor;\n\n        public DateTime dateTime;\n        public Prefs prefs;\n\n        private Utils.IJsonConverter _jsonConv;\n        private IBindingUtils _utils;\n        private TextGenerator _logWriter;\n\n        private List<string> _implicitAssemblies = new List<string>(); // 默认导出所有类型\n        private List<string> _explicitAssemblies = new List<string>(); // 仅导出指定需要导出的类型\n\n        private HashSet<Type> _typeBlacklist;\n        // any member method/field/property/event which references a type in this hashset will not eventually exported\n        private HashSet<Type> _unsupportedRelevantTypes;\n        private HashSet<Type> _unsupportedDelegates;\n        private HashSet<string> _namespaceBlacklist;\n        private HashSet<string> _typeFullNameBlacklist;\n        private HashSet<string> _assemblyBlacklist;  // 禁止导出的 assembly\n        private Dictionary<Type, TypeBindingInfo> _exportedTypes = new Dictionary<Type, TypeBindingInfo>();\n        private Dictionary<Type, ITSTypeNaming> _tsTypeNamings = new Dictionary<Type, ITSTypeNaming>();\n        private Dictionary<string, TSModuleBindingInfo> _exportedModules = new Dictionary<string, TSModuleBindingInfo>();\n        private List<TypeBindingInfo> _collectedTypes = new List<TypeBindingInfo>(); // 已经完成导出的类型 \n        private Dictionary<Type, RawTypeBindingInfo> _collectedRawTypes = new Dictionary<Type, RawTypeBindingInfo>(); // 已经完成导出的类型 \n        private Dictionary<Type, DelegateBridgeBindingInfo> _exportedDelegates = new Dictionary<Type, DelegateBridgeBindingInfo>();\n        private Dictionary<Type, Type> _redirectDelegates = new Dictionary<Type, Type>();\n\n        private HashSet<Type> _hotfixTypes = new HashSet<Type>();\n        private List<HotfixDelegateBindingInfo> _exportedHotfixDelegates = new List<HotfixDelegateBindingInfo>();\n        // 类型修改\n        private Dictionary<Type, TypeTransform> _typesTarnsform = new Dictionary<Type, TypeTransform>();\n        private Dictionary<string, List<string>> _outputFiles = new Dictionary<string, List<string>>();\n        private List<string> _removedFiles = new List<string>();\n\n        private Dictionary<Type, List<string>> _tsTypeNameMap = new Dictionary<Type, List<string>>();\n        private Dictionary<Type, string> _csTypeNameMap = new Dictionary<Type, string>();\n        private Dictionary<Type, string> _csTypePusherMap = new Dictionary<Type, string>();\n        private Dictionary<string, string> _csTypeNameMapS = new Dictionary<string, string>();\n        private static HashSet<string> _tsKeywords = new HashSet<string>();\n        private static HashSet<string> _csKeywords = new HashSet<string>();\n\n        private Dictionary<int, List<MethodInfo>> _reflectedDelegateTemplates = new Dictionary<int, List<MethodInfo>>();\n\n        // 自定义的处理流程\n        private List<Type> _allBindingProcessTypes = new List<Type>();\n        private List<IBindingProcess> _enabledBindingProcess = new List<IBindingProcess>();\n\n        private ICodeGenCallback _codegenCallback;\n        private IBindingCallback _bindingCallback;\n        private IBindingLogger _bindingLogger;\n\n        // ruleName: text => text\n        private Dictionary<string, Func<string, string>> _nameRules = new Dictionary<string, Func<string, string>>();\n        // text => text\n        private Dictionary<string, string> _globalNameRules = new Dictionary<string, string>();\n\n        public Utils.IJsonConverter json => _jsonConv;\n\n        static BindingManager()\n        {\n            AddTSKeywords(\n                // \"type\",\n                \"return\", \"function\", \"interface\", \"class\", \"let\", \"break\", \"as\", \"any\", \"switch\", \"case\", \"if\", \"enum\",\n                \"throw\", \"else\", \"var\", \"number\", \"string\", \"get\", \"module\", \"instanceof\", \"typeof\", \"public\", \"private\",\n                \"while\", \"void\", \"null\", \"super\", \"this\", \"new\", \"in\", \"await\", \"async\", \"extends\", \"static\",\n                \"package\", \"implements\", \"interface\", \"continue\", \"yield\", \"const\", \"export\", \"finally\", \"for\"\n            );\n            AddCSKeywords(\n                \"default\", \"return\", \"class\", \"struct\", \"break\", \"continue\", \"var\", \"if\", \"else\", \"for\", \"nameof\",\n                \"typeof\", \"while\", \"new\", \"in\", \"static\", \"catch\", \"public\", \"case\"\n            );\n        }\n\n        public BindingManager(Prefs prefs, Args args)\n        {\n            this.prefs = prefs;\n            this.dateTime = DateTime.Now;\n            var tab = prefs.tab;\n            var newline = prefs.newline;\n\n            _jsonConv = args.jsonConverter ?? new Utils.DefaultJsonConverter();\n            _utils = args.utils ?? new DefaultBindingUtils();\n            _bindingLogger = args.bindingLogger;\n            _codegenCallback = args.codeGenCallback;\n            _bindingCallback = args.bindingCallback;\n            _namespaceBlacklist = new HashSet<string>(prefs.namespaceBlacklist);\n            _typeFullNameBlacklist = new HashSet<string>(prefs.typeFullNameBlacklist);\n            _assemblyBlacklist = new HashSet<string>(prefs.assemblyBlacklist);\n            _typeBlacklist = new HashSet<Type>();\n            _unsupportedRelevantTypes = new HashSet<Type>();\n            _unsupportedDelegates = new HashSet<Type>();\n            _logWriter = args.useLogWriter ? new TextGenerator(newline, tab) : null;\n\n            if (prefs.optToString)\n            {\n                AddGlobalNameRule(\"ToString\", \"toString\");\n            }\n\n            CollectRefectedDelegateTemplates(typeof(ReflectBindDelegateGen));\n            AddNameRule(\"js\", t => char.ToLower(t[0]) + t.Substring(1));\n\n            TransformType(typeof(string))\n                .AddTSMethodDeclaration(\"static Equals(a: string | Object, b: string | Object, comparisonType: any): boolean\", \"Equals\", typeof(string), typeof(string), typeof(StringComparison))\n                .AddTSMethodDeclaration(\"static Equals(a: string | Object, b: string | Object): boolean\", \"Equals\", typeof(string), typeof(string))\n                .SetMemberBlocked(\"ContainsInvarianCulture\")\n            ;\n\n            // editor 使用的 .net 与 player 所用存在差异, 这里屏蔽不存在的成员\n            TransformType(typeof(double))\n                .SetMemberBlocked(\"IsFinite\")\n            ;\n            TransformType(typeof(float))\n                .SetMemberBlocked(\"IsFinite\")\n            ;\n            TransformType(typeof(string))\n                .SetMemberBlocked(\"Chars\")\n            ;\n\n            TransformType(typeof(Enum))\n                .AddTSMethodDeclaration(\"static GetValues<T>(enumType: any): Array<T>\", \"GetValue\", typeof(Type))\n            ;\n\n            // TransformType(typeof(Dictionary<,>))\n            // ;\n\n            TransformType(typeof(Array))\n                .Rename(\"Array<T, RANK = 1>\")\n\n                .SetMethodBlocked(\"GetValue\", typeof(long), typeof(long), typeof(long))\n                .SetMethodBlocked(\"GetValue\", typeof(long), typeof(long))\n                .SetMethodBlocked(\"GetValue\", typeof(long))\n                .SetMethodBlocked(\"GetValue\", typeof(long[]))\n                .SetMethodBlocked(\"SetValue\", typeof(object), typeof(long), typeof(long), typeof(long))\n                .SetMethodBlocked(\"SetValue\", typeof(object), typeof(long), typeof(long))\n                .SetMethodBlocked(\"SetValue\", typeof(object), typeof(long))\n                .SetMethodBlocked(\"SetValue\", typeof(object), typeof(long[]))\n                .SetMethodBlocked(\"CopyTo\", typeof(Array), typeof(long))\n                .SetMethodBlocked(\"Copy\", typeof(Array), typeof(long), typeof(Array), typeof(long), typeof(long))\n                .SetMethodBlocked(\"Copy\", typeof(Array), typeof(Array), typeof(long))\n                .SetMethodBlocked(\"CreateInstance\", typeof(Type), typeof(long[]))\n\n                .AddTSMethodDeclaration(\"GetValue(index1: number, index2: number, index3: number): T\", \"GetValue\", typeof(int), typeof(int), typeof(int))\n                .AddTSMethodDeclaration(\"GetValue(index1: number, index2: number): T\", \"GetValue\", typeof(int), typeof(int))\n                .AddTSMethodDeclaration(\"GetValue(index: number): T\", \"GetValue\", typeof(int))\n                .AddTSMethodDeclaration(\"GetValue(...index: number[]): T\", \"GetValue\", typeof(int[]))\n\n                .AddTSMethodDeclaration(\"SetValue(value: T, index1: number, index2: number, index3: number): T\", \"SetValue\", typeof(object), typeof(int), typeof(int), typeof(int))\n                .AddTSMethodDeclaration(\"SetValue(value: T, index1: number, index2: number): T\", \"SetValue\", typeof(object), typeof(int), typeof(int))\n                .AddTSMethodDeclaration(\"SetValue(value: T, index: number): T\", \"SetValue\", typeof(object), typeof(int))\n                .AddTSMethodDeclaration(\"SetValue(value: T, ...index: number[]): T\", \"SetValue\", typeof(object), typeof(int[]))\n\n                .AddTSMethodDeclaration(\"static BinarySearch<T>(array: Array<T>, index: number, length: number, value: Object, comparer: any): number\", \"BinarySearch\", typeof(Array), typeof(int), typeof(int), typeof(object), typeof(System.Collections.IComparer))\n                .AddTSMethodDeclaration(\"static BinarySearch<T>(array: Array<T>, index: number, length: number, value: Object): number\", \"BinarySearch\", typeof(Array), typeof(int), typeof(int), typeof(object))\n                .AddTSMethodDeclaration(\"static BinarySearch<T>(array: Array<T>, value: Object, comparer: any): number\", \"BinarySearch\", typeof(Array), typeof(object), typeof(System.Collections.IComparer))\n                .AddTSMethodDeclaration(\"static BinarySearch<T>(array: Array<T>, value: Object): number\", \"BinarySearch\", typeof(Array), typeof(object))\n                .AddTSMethodDeclaration(\"static IndexOf<T>(array: Array<T>, value: Object, startIndex: number, count: number): number\", \"IndexOf\", typeof(Array), typeof(object), typeof(int), typeof(int))\n                .AddTSMethodDeclaration(\"static IndexOf<T>(array: Array<T>, value: Object, startIndex: number): number\", \"IndexOf\", typeof(Array), typeof(object), typeof(int))\n                .AddTSMethodDeclaration(\"static IndexOf<T>(array: Array<T>, value: Object): number\", \"IndexOf\", typeof(Array), typeof(object))\n                .AddTSMethodDeclaration(\"static LastIndexOf<T>(array: Array<T>, value: Object, startIndex: number, count: number): number\", \"LastIndexOf\", typeof(Array), typeof(object), typeof(int), typeof(int))\n                .AddTSMethodDeclaration(\"static LastIndexOf<T>(array: Array<T>, value: Object, startIndex: number): number\", \"LastIndexOf\", typeof(Array), typeof(object), typeof(int))\n                .AddTSMethodDeclaration(\"static LastIndexOf<T>(array: Array<T>, value: Object): number\", \"LastIndexOf\", typeof(Array), typeof(object))\n                .AddTSMethodDeclaration(\"static Reverse<T>(array: Array<T>, index: number, length: number): void\", \"Reverse\", typeof(Array), typeof(int), typeof(int))\n                .AddTSMethodDeclaration(\"static Reverse<T>(array: Array<T>): void\", \"Reverse\", typeof(Array))\n                .AddTSMethodDeclaration(\"static Sort<T>(keys: Array<T>, items: Array<T>, index: number, length: number, comparer: any): void\", \"Sort\", typeof(Array), typeof(Array), typeof(int), typeof(int), typeof(System.Collections.IComparer))\n                .AddTSMethodDeclaration(\"static Sort<T>(array: Array<T>, index: number, length: number, comparer: any): void\", \"Sort\", typeof(Array), typeof(int), typeof(int), typeof(System.Collections.IComparer))\n                .AddTSMethodDeclaration(\"static Sort<T>(keys: Array<T>, items: Array<T>, index: number, length: number): void\", \"Sort\", typeof(Array), typeof(Array), typeof(int), typeof(int))\n                .AddTSMethodDeclaration(\"static Sort<T>(array: Array<T>, index: number, length: number): void\", \"Sort\", typeof(Array), typeof(int), typeof(int))\n                .AddTSMethodDeclaration(\"static Sort<T>(keys: Array<T>, items: Array<T>, comparer: any): void\", \"Sort\", typeof(Array), typeof(Array), typeof(System.Collections.IComparer))\n                .AddTSMethodDeclaration(\"static Sort<T>(array: Array<T>, comparer: any): void\", \"Sort\", typeof(Array), typeof(System.Collections.IComparer))\n                .AddTSMethodDeclaration(\"static Sort<T>(keys: Array<T>, items: Array<T>): void\", \"Sort\", typeof(Array), typeof(Array))\n                .AddTSMethodDeclaration(\"static Sort<T>(array: Array<T>): void\", \"Sort\", typeof(Array))\n                .AddTSMethodDeclaration(\"static CreateInstance<T>(elementType: any, length1: number, length2: number, length3: number): Array<T>\", \"CreateInstance\", typeof(Type), typeof(int), typeof(int), typeof(int))\n                .AddTSMethodDeclaration(\"static CreateInstance<T>(elementType: any, length1: number, length2: number): Array<T>\", \"CreateInstance\", typeof(Type), typeof(int), typeof(int))\n                .AddTSMethodDeclaration(\"static CreateInstance<T>(elementType: any, lengths: Array<number>, lowerBounds: Array<number>): Array<T>\", \"CreateInstance\", typeof(Type), typeof(int[]), typeof(int[]))\n                .AddTSMethodDeclaration(\"static CreateInstance<T>(elementType: any, length: number): Array<T>\", \"CreateInstance\", typeof(Type), typeof(int))\n                .AddTSMethodDeclaration(\"static CreateInstance<T>(elementType: any, ...lengths: number[]): Array<T>\", \"CreateInstance\", typeof(Type), typeof(int[]))\n                .AddTSMethodDeclaration(\"static Clear<T>(array: Array<T>, index: number, length: number): void\", \"Clear\", typeof(Array), typeof(int), typeof(int))\n                .AddTSMethodDeclaration(\"static Copy<T>(sourceArray: Array<T>, sourceIndex: number, destinationArray: Array<T>, destinationIndex: number, length: number): void\", \"Copy\", typeof(Array), typeof(int), typeof(Array), typeof(int), typeof(int))\n                .AddTSMethodDeclaration(\"static Copy<T>(sourceArray: Array<T>, destinationArray: Array<T>, length: number): void\", \"Copy\", typeof(Array), typeof(Array), typeof(int))\n                .AddTSMethodDeclaration(\"static ConstrainedCopy<T>(sourceArray: Array<T>, sourceIndex: number, destinationArray: Array<T>, destinationIndex: number, length: number): void\", \"ConstrainedCopy\", typeof(Array), typeof(int), typeof(Array), typeof(int), typeof(int))\n            ;\n\n            AddTSTypeNameMap(typeof(sbyte), \"number\");\n            AddTSTypeNameMap(typeof(byte), $\"{GetDefaultTypePrefix()}byte\");\n            AddTSTypeNameMap(typeof(int), \"number\");\n            AddTSTypeNameMap(typeof(uint), \"number\");\n            AddTSTypeNameMap(typeof(short), \"number\");\n            AddTSTypeNameMap(typeof(ushort), \"number\");\n            AddTSTypeNameMap(typeof(long), \"number\");\n            AddTSTypeNameMap(typeof(ulong), \"number\");\n            AddTSTypeNameMap(typeof(float), \"number\");\n            AddTSTypeNameMap(typeof(double), \"number\");\n            AddTSTypeNameMap(typeof(bool), \"boolean\");\n            AddTSTypeNameMap(typeof(string), \"string\");\n            AddTSTypeNameMap(typeof(char), \"string\");\n            AddTSTypeNameMap(typeof(void), \"void\");\n\n            AddUnsupportedRelevantType(typeof(System.Int32).Assembly.GetType(\"System.Span`1\"));\n            AddUnsupportedRelevantType(typeof(System.Int32).Assembly.GetType(\"System.ReadOnlySpan`1\"));\n\n            TransformType(typeof(QuickJS.IO.ByteBuffer))\n                .SetMemberBlocked(\"_SetPosition\")\n                .SetMethodBlocked(\"ReadAllBytes\", typeof(IntPtr))\n                .SetMethodBlocked(\"WriteBytes\", typeof(IntPtr), typeof(int));\n\n            AddCSTypeNameMap(typeof(sbyte), \"sbyte\");\n            AddCSTypeNameMap(typeof(byte), \"byte\");\n            AddCSTypeNameMap(typeof(int), \"int\");\n            AddCSTypeNameMap(typeof(uint), \"uint\");\n            AddCSTypeNameMap(typeof(short), \"short\");\n            AddCSTypeNameMap(typeof(ushort), \"ushort\");\n            AddCSTypeNameMap(typeof(long), \"long\");\n            AddCSTypeNameMap(typeof(ulong), \"ulong\");\n            AddCSTypeNameMap(typeof(float), \"float\");\n            AddCSTypeNameMap(typeof(double), \"double\");\n            AddCSTypeNameMap(typeof(bool), \"bool\");\n            AddCSTypeNameMap(typeof(string), \"string\");\n            AddCSTypeNameMap(typeof(char), \"char\");\n            AddCSTypeNameMap(typeof(System.Object), \"object\");\n            AddCSTypeNameMap(typeof(void), \"void\");\n            AddCSTypeNameMap(typeof(QuickJS.Native.JSValue), \"JSValue\");\n            AddCSTypeNameMap(typeof(QuickJS.Native.JSContext), \"JSContext\");\n\n            Initialize();\n        }\n\n        public IBindingLogger GetBindingLogger()\n        {\n            return _bindingLogger;\n        }\n\n        public void AddGlobalNameRule(string name, string mapping)\n        {\n            if (!string.IsNullOrEmpty(name))\n            {\n                _globalNameRules[name] = mapping;\n            }\n        }\n\n        public void AddNameRule(string name, Func<string, string> fn)\n        {\n            if (!string.IsNullOrEmpty(name))\n            {\n                _nameRules[name] = fn;\n            }\n        }\n\n        public string ApplyNameRule(string name, string text)\n        {\n            if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(name))\n            {\n                Func<string, string> tfn;\n                if (_nameRules.TryGetValue(name, out tfn))\n                {\n                    return tfn(text);\n                }\n            }\n\n            string mapping;\n            if (_globalNameRules.TryGetValue(text, out mapping))\n            {\n                return mapping;\n            }\n\n            return text;\n        }\n\n        public void SetTypeBlocked(Type type)\n        {\n            _typeBlacklist.Add(type);\n        }\n\n        public List<Type> GetBindingProcessTypes()\n        {\n            return _allBindingProcessTypes;\n        }\n\n        public bool GetTSMethodDeclaration(MethodBase method, out string code)\n        {\n            var transform = GetTypeTransform(method.DeclaringType);\n            if (transform != null)\n            {\n                return transform.GetTSMethodDeclaration(method, out code);\n            }\n            code = null;\n            return false;\n        }\n\n        public TypeTransform GetTypeTransform(Type type)\n        {\n            TypeTransform transform;\n            return _typesTarnsform.TryGetValue(type, out transform) ? transform : null;\n        }\n\n        public TypeTransform TransformType(Type type)\n        {\n            TypeTransform transform;\n            if (!_typesTarnsform.TryGetValue(type, out transform))\n            {\n                _typesTarnsform[type] = transform = new TypeTransform(type);\n                if (_utils.IsExplicitEditorType(type))\n                {\n                    transform.EditorRuntime();\n                }\n            }\n            return transform;\n        }\n\n        private static bool _FindFilterBindingProcess(Type type, object l)\n        {\n            return type == typeof(IBindingProcess);\n        }\n\n        private void Initialize()\n        {\n            var assemblies = AppDomain.CurrentDomain.GetAssemblies();\n            for (var i = 0; i < assemblies.Length; i++)\n            {\n                var assembly = assemblies[i];\n                if (!assembly.IsDynamic && IsAssemblyReferencedTo(assembly, typeof(IBindingProcess).Assembly))\n                {\n                    CollectBindingProcess(assembly);\n                }\n            }\n        }\n\n        private void CollectBindingProcess(Assembly assembly)\n        {\n            var types = assembly.GetExportedTypes();\n            for (int i = 0, size = types.Length; i < size; i++)\n            {\n                var type = types[i];\n                if (type.IsAbstract)\n                {\n                    continue;\n                }\n                try\n                {\n                    var interfaces = type.FindInterfaces(_FindFilterBindingProcess, null);\n                    if (interfaces != null && interfaces.Length > 0)\n                    {\n                        _allBindingProcessTypes.Add(type);\n\n                        if (prefs.skipBinding.Contains(type.FullName))\n                        {\n                            _bindingLogger?.Log($\"skip binding process: {type}\");\n                        }\n                        else\n                        {\n                            var ctor = type.GetConstructor(Type.EmptyTypes);\n                            var inst = ctor.Invoke(null) as IBindingProcess;\n\n                            inst.OnInitialize(this);\n                            _enabledBindingProcess.Add(inst);\n                            _enabledBindingProcess.Sort((p1, p2) => p1.Priority.CompareTo(p2.Priority));\n                            _bindingLogger?.Log($\"add binding process: {type}\");\n                        }\n                    }\n                }\n                catch (Exception exception)\n                {\n                    _bindingLogger?.LogWarning($\"failed to add binding process: {type}\\n{exception}\");\n                }\n            }\n        }\n\n        /// <summary>\n        /// TS: 添加保留字, CS中相关变量名等会自动重命名注册到js中\n        /// </summary>\n        public static void AddTSKeywords(params string[] keywords)\n        {\n            foreach (var keyword in keywords)\n            {\n                _tsKeywords.Add(keyword);\n            }\n        }\n\n        public static void AddCSKeywords(params string[] keywords)\n        {\n            foreach (var keyword in keywords)\n            {\n                _csKeywords.Add(keyword);\n            }\n        }\n\n        /// <summary>\n        /// 指定类型在 ts 声明中的映射名 (可以指定多项)\n        /// </summary>\n        public void AddTSTypeNameMap(Type type, params string[] names)\n        {\n            List<string> list;\n            if (!_tsTypeNameMap.TryGetValue(type, out list))\n            {\n                _tsTypeNameMap[type] = list = new List<string>();\n            }\n            list.AddRange(names);\n        }\n\n        public bool GetTSTypeNameMap(Type type, out List<string> list)\n        {\n            return _tsTypeNameMap.TryGetValue(type, out list);\n        }\n\n        /// <summary>\n        /// CS, 添加类型名称映射, 用于简化导出时的常用类型名\n        /// </summary>\n        public void AddCSTypeNameMap(Type type, string name)\n        {\n            _csTypeNameMap[type] = name;\n            _csTypeNameMapS[type.FullName] = name;\n            _csTypeNameMapS[GetCSNamespace(type) + type.Name] = name;\n        }\n\n        public void AddCSTypePusherMap(Type type, string name)\n        {\n            _csTypePusherMap[type] = name;\n        }\n\n        public void AddHotfixType(Type type)\n        {\n            if (!_hotfixTypes.Contains(type))\n            {\n                _hotfixTypes.Add(type);\n            }\n        }\n\n        public void AddUnsupportedRelevantType(Type type)\n        {\n            if (type != null) \n            {\n                _unsupportedRelevantTypes.Add(type);\n            }\n        }\n\n        public RawTypeBindingInfo GetExportedRawType(Type type)\n        {\n            RawTypeBindingInfo rawTypeBindingInfo;\n            return _collectedRawTypes.TryGetValue(type, out rawTypeBindingInfo) ? rawTypeBindingInfo : null;\n        }\n\n        public TypeTransform AddExportedRawTypes(Type type)\n        {\n            var typeTransform = TransformType(type);\n            if (!_collectedRawTypes.ContainsKey(type))\n            {\n                var method = type.GetMethod(\"Bind\", BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);\n                do\n                {\n                    if (method == null)\n                    {\n                        Error(\"no Bind() on raw type: {0}\", type.FullName);\n                        break;\n                    }\n\n                    if (method.ReturnType != typeof(void))\n                    {\n                        Error(\"incorrect return type of Bind() on raw type: {0}\", type.FullName);\n                        break;\n                    }\n\n                    var parameters = method.GetParameters();\n                    if (parameters.Length != 2\n                    || parameters[0].ParameterType != typeof(TypeRegister)\n                    || parameters[1].ParameterType != typeof(string))\n                    {\n                        Error(\"incorrect parameter type of Bind() on raw type: {0}\", type.FullName);\n                        break;\n                    }\n\n                    _collectedRawTypes.Add(type, new RawTypeBindingInfo(type, method));\n                } while (false);\n            }\n            return typeTransform;\n        }\n\n        /// <summary>\n        /// Add the type to the typelist for binding. (do it before Collect())\n        /// </summary>\n        /// <param name=\"importBaseType\">whether to process the base type or not</param>\n        public TypeTransform AddExportedType(Type type, bool importBaseType = false)\n        {\n            var typeTransform = TransformType(type);\n            if (!_exportedTypes.ContainsKey(type))\n            {\n                var typeBindingInfo = new TypeBindingInfo(this, type, typeTransform);\n                _exportedTypes.Add(type, typeBindingInfo);\n                Info($\"AddExportedType: {type} Assembly: {type.Assembly} Location: {type.Assembly.Location}\");\n\n                var baseType = type.BaseType;\n                if (baseType != null && !IsExportingBlocked(baseType))\n                {\n                    // 检查具体化泛型基类 (如果基类泛型定义在显式导出清单中, 那么导出此具体化类)\n                    // Debug.LogFormat(\"{0} IsConstructedGenericType:{1} {2} {3}\", type, type.IsConstructedGenericType, type.IsGenericType, importBaseType);\n                    if (IsConstructedGenericType(baseType)) // if (baseType.IsConstructedGenericType)\n                    {\n                        if (IsExportingExplicit(baseType.GetGenericTypeDefinition()))\n                        {\n                            AddExportedType(baseType);\n                        }\n                    }\n\n                    if (importBaseType)\n                    {\n                        AddExportedType(baseType, importBaseType);\n                    }\n                }\n\n                // 尝试以 typescript interface 形式导出泛型定义\n                if (IsConstructedGenericType(type))// if (type.IsConstructedGenericType)\n                {\n                    AddExportedType(type.GetGenericTypeDefinition(), false);\n                }\n            }\n            return typeTransform;\n        }\n\n        public static bool IsCompoundedType(Type[] types)\n        {\n            for (int i = 0, size = types.Length; i < size; ++i)\n            {\n                var type = types[i];\n                if (type.IsArray)\n                {\n                    return true;\n                }\n            }\n\n            return false;\n        }\n\n        public static bool IsConstructedGenericType(Type type)\n        {\n            return type.IsGenericType && !type.IsGenericTypeDefinition;\n        }\n\n        public TSModuleBindingInfo GetExportedTSModule(string name)\n        {\n            TSModuleBindingInfo module;\n            if (!_exportedModules.TryGetValue(name, out module))\n            {\n                module = _exportedModules[name] = new TSModuleBindingInfo();\n            }\n            return module;\n        }\n\n        public DelegateBridgeBindingInfo GetDelegateBindingInfo(Type type)\n        {\n            if (type != null)\n            {\n                Type target;\n                if (_redirectDelegates.TryGetValue(type, out target))\n                {\n                    type = target;\n                }\n                DelegateBridgeBindingInfo delegateBindingInfo;\n                if (_exportedDelegates.TryGetValue(type, out delegateBindingInfo))\n                {\n                    return delegateBindingInfo;\n                }\n            }\n            return null;\n        }\n\n        public void CollectHotfix(Type type)\n        {\n            if (type == null)\n            {\n                return;\n            }\n            var transform = GetTypeTransform(type);\n            var methodInfos = type.GetMethods(Binding.DynamicType.DefaultFlags);\n            var hotfix = transform?.GetHotfix();\n            var hotfixBefore = hotfix != null && (hotfix.flags & JSHotfixFlags.Before) != 0;\n            var hotfixAfter = hotfix != null && (hotfix.flags & JSHotfixFlags.After) != 0;\n            foreach (var methodInfo in methodInfos)\n            {\n                CollectHotfix(type, methodInfo, methodInfo.ReturnType);\n                if (hotfixBefore | hotfixAfter)\n                {\n                    CollectHotfix(type, methodInfo, typeof(void));\n                }\n            }\n\n            var constructorInfos = type.GetConstructors(Binding.DynamicType.DefaultFlags);\n            foreach (var constructorInfo in constructorInfos)\n            {\n                CollectHotfix(type, constructorInfo, typeof(void));\n            }\n        }\n\n        private bool CollectHotfix(Type declaringType, MethodBase methodBase, Type returnType)\n        {\n            if (methodBase.IsGenericMethodDefinition)\n            {\n                return false;\n            }\n\n            if (declaringType.IsValueType)\n            {\n                return false;\n            }\n\n            if (methodBase.Name == \".cctor\")\n            {\n                return false;\n            }\n\n            var parameters = methodBase.GetParameters();\n\n            for (var i = 0; i < parameters.Length; i++)\n            {\n                var parameter = parameters[i];\n\n                // 暂不支持\n                if (parameter.IsOut || parameter.ParameterType.IsPointer || parameter.IsDefined(typeof(ParamArrayAttribute), false))\n                {\n                    return false;\n                }\n            }\n\n            for (var i = 0; i < _exportedHotfixDelegates.Count; i++)\n            {\n                var regDelegateBinding = _exportedHotfixDelegates[i];\n                if (regDelegateBinding.Equals(declaringType, methodBase.IsStatic, returnType, parameters))\n                {\n                    return true;\n                }\n            }\n\n            var newDelegateBinding = new HotfixDelegateBindingInfo(declaringType, methodBase.IsStatic, returnType, parameters);\n            _exportedHotfixDelegates.Add(newDelegateBinding);\n            for (var i = 0; i < parameters.Length; i++)\n            {\n                CollectDelegate(parameters[i].ParameterType);\n            }\n            return true;\n        }\n\n        public void CollectTypeRequiredDefines(HashSet<string> defs, Type type)\n        {\n            if (type == null || type == typeof(void))\n            {\n                return;\n            }\n\n            var requiredDefines = TransformType(type).requiredDefines;\n            if (requiredDefines != null)\n            {\n                defs.UnionWith(requiredDefines);\n            }\n\n            // check outter class for nested class\n            CollectTypeRequiredDefines(defs, type.DeclaringType);\n        }\n\n        public void CollectTypeRequiredDefines(HashSet<string> defs, ParameterInfo[] parameters)\n        {\n            for (int i = 0, count = parameters.Length; i < count; i++)\n            {\n                var parameter = parameters[i];\n                CollectTypeRequiredDefines(defs, parameter.ParameterType);\n            }\n        }\n\n        public bool IsSupportedMethod(Type returnType, MethodBase methodBase)\n        {\n            if (methodBase.IsGenericMethod)\n            {\n                return false;\n            }\n\n            // var returnType = methodInfo.ReturnType;\n            var parameters = methodBase.GetParameters();\n\n            if (returnType.IsPointer || returnType.FullName == null || returnType.IsGenericTypeDefinition || _unsupportedRelevantTypes.Contains(returnType))\n            {\n                return false;\n            }\n\n            if (returnType.IsGenericType)\n            {\n                //TODO temporarily skip types like NativeArray<XXX> with _unsupportedRelevantTypes\n                if (_unsupportedRelevantTypes.Contains(returnType.GetGenericTypeDefinition()))\n                {\n                    return false;\n                }\n            }\n\n            for (int i = 0, count = parameters.Length; i < count; ++i)\n            {\n                var parameterType = parameters[i].ParameterType;\n                if (parameterType.IsPointer || parameterType.FullName == null || parameterType.IsGenericTypeDefinition || parameterType.IsGenericParameter || _unsupportedRelevantTypes.Contains(parameterType))\n                {\n                    return false;\n                }\n                if (prefs.skipDelegateWithByRefParams && parameterType.IsByRef)\n                {\n                    return false;\n                }\n                if (parameterType.IsGenericType)\n                {\n                    //TODO temporarily skip types like NativeArray<XXX> with _unsupportedRelevantTypes\n                    if (_unsupportedRelevantTypes.Contains(parameterType.GetGenericTypeDefinition()))\n                    {\n                        return false;\n                    }\n                }\n                if (parameterType.DeclaringType != null)\n                {\n                    //TODO nested type in a generic class (even in a constructed generic type) not supported for now\n                    if (parameterType.DeclaringType.IsGenericType)\n                    {\n                        return false;\n                    }\n                }\n            }\n            return true;\n        }\n\n        public bool IsSupportedAsDelegate(Type delegateType)\n        {\n            if (_unsupportedDelegates.Contains(delegateType))\n            {\n                return false;\n            }\n\n            var invoke = delegateType.GetMethod(\"Invoke\");\n            var returnType = invoke.ReturnType;\n            var parameters = invoke.GetParameters();\n\n            if (returnType.IsPointer || returnType.IsGenericTypeDefinition || _unsupportedRelevantTypes.Contains(returnType))\n            {\n                _unsupportedDelegates.Add(delegateType);\n                return false;\n            }\n\n            if (returnType.IsGenericType)\n            {\n                //TODO temporarily skip types like NativeArray<XXX> with _unsupportedRelevantTypes\n                if (_unsupportedRelevantTypes.Contains(returnType.GetGenericTypeDefinition()))\n                {\n                    _unsupportedDelegates.Add(delegateType);\n                    return false;\n                }\n            }\n\n            for (int i = 0, count = parameters.Length; i < count; ++i)\n            {\n                var parameterType = parameters[i].ParameterType;\n                if (parameterType.IsPointer || parameterType.IsGenericTypeDefinition || parameterType.IsGenericParameter || _unsupportedRelevantTypes.Contains(parameterType))\n                {\n                    _unsupportedDelegates.Add(delegateType);\n                    return false;\n                }\n                if (prefs.skipDelegateWithByRefParams && parameterType.IsByRef)\n                {\n                    _unsupportedDelegates.Add(delegateType);\n                    return false;\n                }\n                if (parameterType.IsGenericType)\n                {\n                    //TODO temporarily skip types like NativeArray<XXX> with _unsupportedRelevantTypes\n                    if (_unsupportedRelevantTypes.Contains(parameterType.GetGenericTypeDefinition()))\n                    {\n                        _unsupportedDelegates.Add(delegateType);\n                        return false;\n                    }\n                }\n                if (parameterType.DeclaringType != null)\n                {\n                    //TODO nested type in a generic class (even in a constructed generic type) not supported for now\n                    if (parameterType.DeclaringType.IsGenericType)\n                    {\n                        _unsupportedDelegates.Add(delegateType);\n                        return false;\n                    }\n                }\n            }\n            return true;\n        }\n\n        // 收集所有 delegate 类型\n        // delegateType: 委托本身的类型\n        // explicitThis: 委托的首个参数作为 显式 this 传递\n        public void CollectDelegate(Type delegateType)\n        {\n            if (delegateType == null || delegateType.BaseType != typeof(MulticastDelegate) || _exportedDelegates.ContainsKey(delegateType))\n            {\n                return;\n            }\n\n            if (!IsSupportedAsDelegate(delegateType))\n            {\n                return;\n            }\n\n            var invoke = delegateType.GetMethod(\"Invoke\");\n            var returnType = invoke.ReturnType;\n            var parameters = invoke.GetParameters();\n            var requiredDefines = new HashSet<string>();\n\n            CollectTypeRequiredDefines(requiredDefines, delegateType);\n            CollectTypeRequiredDefines(requiredDefines, returnType);\n            CollectTypeRequiredDefines(requiredDefines, parameters);\n            var defs = string.Join(\" && \", from def in requiredDefines select def);\n\n            // 是否存在等价 delegate\n            foreach (var kv in _exportedDelegates)\n            {\n                var regDelegateType = kv.Key;\n                var regDelegateBinding = kv.Value;\n                if (regDelegateBinding.Equals(returnType, parameters, defs))\n                {\n                    Info(\"skip delegate: {0} && {1} required defines: {2}\", regDelegateBinding, delegateType, defs);\n                    regDelegateBinding.types.Add(delegateType);\n                    _redirectDelegates[delegateType] = regDelegateType;\n                    return;\n                }\n            }\n            var delegateBindingInfo = new DelegateBridgeBindingInfo(returnType, parameters, defs);\n            delegateBindingInfo.types.Add(delegateType);\n            _exportedDelegates.Add(delegateType, delegateBindingInfo);\n            Info(\"add delegate: {0} required defines: {1}\", delegateType, defs);\n            for (var i = 0; i < parameters.Length; i++)\n            {\n                CollectDelegate(parameters[i].ParameterType);\n            }\n        }\n\n        public void CollectRefectedDelegateTemplates(Type type)\n        {\n            var methods = type.GetMethods();\n            for (int i = 0, length = methods.Length; i < length; ++i)\n            {\n                AddReflectedDelegateTemplate(methods[i]);\n            }\n        }\n\n        public bool AddReflectedDelegateTemplate(MethodInfo methodInfo)\n        {\n            var parameters = methodInfo.GetParameters();\n\n            if (parameters.Length > 0 && parameters[0].ParameterType == typeof(ScriptDelegate))\n            {\n                List<MethodInfo> list;\n                var argc = parameters.Length - 1;\n                if (!_reflectedDelegateTemplates.TryGetValue(argc, out list))\n                {\n                    _reflectedDelegateTemplates[argc] = list = new List<MethodInfo>();\n                }\n                list.Add(methodInfo);\n                return true;\n            }\n            return false;\n        }\n\n        public static bool IsDelegateMethodSuitable(MethodInfo methodTemplate, int startIndex, ParameterInfo[] parameters, Type returnType)\n        {\n            if (methodTemplate.ReturnType != returnType && methodTemplate.ReturnType == typeof(void))\n            {\n                return false;\n            }\n            var templateParameters = methodTemplate.GetParameters();\n            var templateLength = templateParameters.Length - startIndex;\n            var targetLength = parameters.Length;\n            if (templateLength != targetLength)\n            {\n                return false;\n            }\n\n            for (var i = 0; i < targetLength; ++i)\n            {\n                var templateInfo = templateParameters[i + startIndex];\n                var targetInfo = parameters[i];\n                if (templateInfo.IsOut != targetInfo.IsOut || templateInfo.ParameterType.IsByRef != targetInfo.ParameterType.IsByRef)\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n\n        public MethodInfo GenerateReflectedDelegateMethod(List<MethodInfo> templates, Type returnType, ParameterInfo[] parameters)\n        {\n            for (int i = 0, count = templates.Count; i < count; ++i)\n            {\n                var template = templates[i];\n                if (IsDelegateMethodSuitable(template, 1, parameters, returnType))\n                {\n                    if (!template.IsGenericMethodDefinition)\n                    {\n                        return template;\n                    }\n\n                    var parametersTypes = from p in parameters select p.ParameterType;\n                    return template.MakeGenericMethod(\n                        returnType != typeof(void)\n                        ? AppendEnumerable(parametersTypes, returnType)\n                        : parametersTypes.ToArray());\n                }\n            }\n\n            // dynamically emit method\n            var emittedMethod = _EmitDelegateMethod(returnType, parameters);\n            if (emittedMethod != null)\n            {\n                templates.Add(emittedMethod);\n                return emittedMethod;\n            }\n\n            return null;\n        }\n\n        private void AddAssemblies(HashSet<Assembly> assemblies, IEnumerable<Type> types)\n        {\n            foreach (var t in types)\n            {\n                AddAssemblies(assemblies, t);\n            }\n        }\n\n        private void AddAssemblies(HashSet<Assembly> assemblies, Type type)\n        {\n            if (type != null && assemblies.Add(type.Assembly))\n            {\n                // UnityEngine.Debug.LogFormat(\"ref assembly {0}\", type.Assembly.Location);\n                AddAssemblies(assemblies, type.BaseType);\n            }\n        }\n\n        private ulong _emitSeq = 0;\n        public MethodInfo _EmitDelegateMethod(Type returnType, ParameterInfo[] parameters)\n        {\n            try\n            {\n                if (!CodeGenUtils.IsCodeEmitSupported())\n                {\n                    return null;\n                }\n                var cg = new CodeGenerator(this, TypeBindingFlags.Default);\n                var ns = \"_Generated\" + (_emitSeq++);\n                var className = CodeGenerator.NameOfDelegates;\n                var assemblies = new HashSet<Assembly>();\n\n                AddAssemblies(assemblies, returnType);\n                AddAssemblies(assemblies, from p in parameters select p.ParameterType);\n                assemblies.Add(typeof(Values).Assembly);\n                assemblies.Add(typeof(Native.JSApi).Assembly);\n                assemblies.Add(typeof(Exception).Assembly);\n                assemblies.Add(typeof(System.Object).Assembly);\n                using (new CSNamespaceCodeGen(cg, ns))\n                {\n                    cg.cs.AppendLine(\"public static class \" + className);\n                    cg.cs.AppendLine(\"{\");\n                    cg.cs.AddTabLevel();\n                    using (new DelegateCodeGen(cg, \"_Generated\", returnType, parameters))\n                    {\n                    }\n                    cg.cs.DecTabLevel();\n                    cg.cs.AppendLine(\"}\");\n                }\n\n                var source = cg.cs.Submit();\n                var compiledAssembly = CodeGenUtils.Compile(source, assemblies, \"-unsafe\", _bindingLogger);\n                if (compiledAssembly.ExportedTypes.Count() == 1)\n                {\n                    var resultType = compiledAssembly.ExportedTypes.First();\n                    if (resultType.Namespace == ns)\n                    {\n                        return resultType.GetMethod(\"_Generated\");\n                    }\n                    Error(\"not expected type\");\n                }\n                else\n                {\n                    Error(\"no exported type in compiled assembly\");\n                }\n            }\n            catch (Exception exception)\n            {\n                Error(exception);\n            }\n\n            return null;\n        }\n\n        public MethodInfo GetReflectedDelegateMethod(Type returnType, ParameterInfo[] parameters)\n        {\n            // skip unsupported types\n            if (Binding.Values.IsVarargParameter(parameters))\n            {\n                return null;\n            }\n\n            List<MethodInfo> templates = null;\n            var argc = parameters.Length;\n            if (!_reflectedDelegateTemplates.TryGetValue(argc, out templates))\n            {\n                _reflectedDelegateTemplates[argc] = templates = new List<MethodInfo>();\n            }\n            return GenerateReflectedDelegateMethod(templates, returnType, parameters);\n        }\n\n        public static T[] AppendEnumerable<T>(IEnumerable<T> e, T item)\n        {\n#if JSB_COMPATIBLE\n            var list = e.ToList();\n            list.Add(item);\n            return list.ToArray();\n#else\n            return e.Append(item).ToArray();\n#endif\n        }\n\n        public bool IsExported(Type type)\n        {\n            return _exportedTypes.ContainsKey(type);\n        }\n\n        public string GetDefaultTypePrefix()\n        {\n            return \"jsb.\";\n        }\n\n        public string GetNewOperation(Type forType)\n        {\n            MethodInfo methodInfo;\n            if (Values._JSNewMap.TryGetValue(forType, out methodInfo))\n            {\n                return GetCSTypeFullName(methodInfo);\n            }\n            return \"Values.NewBridgeClassObject\";\n        }\n\n        public string GetRebindOperation(Type forType)\n        {\n            MethodInfo methodInfo;\n            if (Values._JSRebindMap.TryGetValue(forType, out methodInfo))\n            {\n                return GetCSTypeFullName(methodInfo);\n            }\n            return \"Values.js_rebind_this\";\n        }\n\n        public string GetCSNamespace(Type type)\n        {\n            return string.IsNullOrEmpty(type.Namespace) ? \"\" : (type.Namespace + \".\");\n        }\n\n        public string GetScriptObjectGetter(Type type, string ctx, string index, string varname)\n        {\n            var getter = GetScriptObjectPropertyGetter(type);\n            return $\"{getter}({ctx}, {index}, out {varname})\";\n        }\n\n        private string GetScriptObjectPropertyGetter(Type type)\n        {\n            MethodInfo methodInfo;\n            if (type != typeof(object) && Values._JSCastMap.TryGetValue(type, out methodInfo))\n            {\n                return GetCSTypeFullName(methodInfo);\n            }\n\n            if (type.IsByRef)\n            {\n                return GetScriptObjectPropertyGetter(type.GetElementType());\n            }\n\n            if (type.IsArray)\n            {\n                if (type.GetArrayRank() == 1)\n                {\n                    var elementType = type.GetElementType();\n                    if (!elementType.IsArray)\n                    {\n                        return GetScriptObjectPropertyGetter(elementType);\n                    }\n                }\n                return \"Values.js_get_classvalue\";\n            }\n\n            if (type.IsValueType)\n            {\n                if (type.IsPrimitive)\n                {\n                    return \"Values.js_get_primitive\";\n                }\n                if (type.IsEnum)\n                {\n                    return \"Values.js_get_enumvalue\";\n                }\n                if (type.IsGenericType)\n                {\n                    if (type.GetGenericTypeDefinition() == typeof(Nullable<>))\n                    {\n                        var gArgs = type.GetGenericArguments();\n                        if (gArgs[0].IsValueType && gArgs[0].IsPrimitive)\n                        {\n                            return \"Values.js_get_primitive\";\n                        }\n                    }\n                }\n                return \"Values.js_get_structvalue\";\n            }\n\n            if (type == typeof(string))\n            {\n                return \"Values.js_get_primitive\";\n            }\n\n            if (type == typeof(object))\n            {\n                return \"Values.js_get_var\";\n            }\n\n            if (type.BaseType == typeof(MulticastDelegate))\n            {\n                return \"Values.js_get_delegate\";\n            }\n\n            return \"Values.js_get_classvalue\";\n        }\n\n        public string GetScriptObjectPusher(Type type, string ctx, string value)\n        {\n            string op;\n            if (type.IsEnum)\n            {\n                var eType = type.GetEnumUnderlyingType();\n                var eTypeName = this.GetCSTypeFullName(eType);\n                return $\"{this.GetScriptObjectPusher(eType, out op)}(ctx, ({eTypeName}){value})\";\n            }\n            return $\"{this.GetScriptObjectPusher(type, out op)}(ctx, {op}{value})\";\n        }\n\n        public string GetScriptObjectPusher(Type type, out string op)\n        {\n            MethodInfo methodInfo;\n            if (Values._CSCastMap.TryGetValue(type, out methodInfo))\n            {\n                op = \"\";\n                return GetCSTypeFullName(methodInfo);\n            }\n\n            if (type.IsByRef)\n            {\n                return GetScriptObjectPusher(type.GetElementType(), out op);\n            }\n\n            op = \"\";\n            string pusher;\n            if (_csTypePusherMap.TryGetValue(type, out pusher))\n            {\n                return pusher;\n            }\n\n            if (type == typeof(Delegate) || type.BaseType == typeof(MulticastDelegate))\n            {\n                return \"Values.js_push_delegate\";\n            }\n\n            if (type.IsValueType)\n            {\n                if (type.IsPrimitive)\n                {\n                    return \"Values.js_push_primitive\";\n                }\n\n                if (type.IsEnum)\n                {\n                    return \"Values.js_push_enumvalue\";\n                }\n\n                if (type.IsGenericType)\n                {\n                    if (type.GetGenericTypeDefinition() == typeof(Nullable<>))\n                    {\n                        var gArgs = type.GetGenericArguments();\n\n                        if (gArgs[0].IsValueType && gArgs[0].IsPrimitive)\n                        {\n                            return \"Values.js_push_primitive\";\n                        }\n                    }\n                }\n\n                // op = \"ref \";\n                return \"Values.js_push_structvalue\";\n            }\n\n            if (type == typeof(string))\n            {\n                return \"Values.js_push_primitive\";\n            }\n\n            if (type == typeof(object))\n            {\n                return \"Values.js_push_var\";\n            }\n\n            return \"Values.js_push_classvalue\";\n        }\n\n        public static string GetCSVariable(string name)\n        {\n            return _csKeywords.Contains(name) ? \"@\" + name : name;\n        }\n\n        public static string GetTSVariable(string name)\n        {\n            return _tsKeywords.Contains(name) ? name + \"_\" : name;\n        }\n\n        /// <summary>\n        /// 获取父类的 TypeBindingInfo (沿继承链上溯直到存在导出), 不存在时返回 null\n        /// </summary>\n        public TypeBindingInfo GetSuperTypeBindingInfo(TypeBindingInfo typeBindingInfo)\n        {\n            var super = typeBindingInfo.super;\n            while (super != null)\n            {\n                var superBindingInfo = GetExportedType(super);\n                if (superBindingInfo != null)\n                {\n                    return superBindingInfo;\n                }\n\n                super = super.BaseType;\n            }\n\n            return null;\n        }\n\n        // 生成参数对应的字符串形式参数列表 (csharp)\n        public string GetCSArglistDecl(ParameterInfo[] parameters)\n        {\n            var size = parameters.Length;\n            var arglist = \"\";\n            if (size == 0)\n            {\n                return arglist;\n            }\n            for (var i = 0; i < size; i++)\n            {\n                var parameter = parameters[i];\n                var typename = GetCSTypeFullName(parameter.ParameterType);\n                if (parameter.IsOut && parameter.ParameterType.IsByRef)\n                {\n                    arglist += \"out \";\n                }\n                else if (parameter.ParameterType.IsByRef)\n                {\n                    arglist += \"ref \";\n                }\n                arglist += typename;\n                arglist += \" \";\n                arglist += parameter.Name;\n                if (i != size - 1)\n                {\n                    arglist += \", \";\n                }\n            }\n            return arglist;\n        }\n\n        public string GetCSTypeFullName(Delegate @delegate)\n        {\n            return GetCSTypeFullName(@delegate.GetMethodInfo());\n        }\n\n        public string GetCSTypeFullName(MethodInfo methodInfo)\n        {\n            return $\"{this.GetCSTypeFullName(methodInfo.DeclaringType)}.{methodInfo.Name}\";\n        }\n\n        // 获取 type 在 绑定代码 中对应类型名\n        public string GetCSTypeFullName(Type type)\n        {\n            return GetCSTypeFullName(type, true);\n        }\n\n        public string GetCSTypeFullName(Type type, bool shortName)\n        {\n            // Debug.LogFormat(\"{0} Array {1} ByRef {2} GetElementType {3}\", type, type.IsArray, type.IsByRef, type.GetElementType());\n            if (type.IsGenericType)\n            {\n                var @namespace = string.Empty;\n                var classname = type.Name.Substring(0, type.Name.Length - 2);\n                if (type.IsNested)\n                {\n                    var indexOf = type.FullName.IndexOf(\"+\");\n                    @namespace = type.FullName.Substring(0, indexOf) + \".\";\n                }\n                else\n                {\n                    @namespace = GetCSNamespace(type);\n                }\n                var purename = @namespace + classname;\n                var gargs = type.GetGenericArguments();\n                purename += \"<\";\n                for (var i = 0; i < gargs.Length; i++)\n                {\n                    var garg = gargs[i];\n                    purename += GetCSTypeFullName(garg, shortName);\n                    if (i != gargs.Length - 1)\n                    {\n                        purename += \", \";\n                    }\n                }\n                purename += \">\";\n                return purename;\n            }\n\n            if (type.IsArray)\n            {\n                var rank = type.GetArrayRank();\n                var element = GetCSTypeFullName(type.GetElementType(), shortName);\n\n                if (rank == 1)\n                {\n                    return element + \"[]\";\n                }\n                return element + \"[\" + StringRepeat(\",\", rank - 1) + \"]\";\n            }\n\n            if (type.IsByRef)\n            {\n                return GetCSTypeFullName(type.GetElementType(), shortName);\n            }\n            string name;\n            if (shortName)\n            {\n                if (_csTypeNameMap.TryGetValue(type, out name))\n                {\n                    return name;\n                }\n            }\n            if (type.IsGenericParameter)\n            {\n                return type.Name;\n            }\n            var fullname = type.FullName.Replace('+', '.');\n            if (fullname.Contains(\"`\"))\n            {\n                fullname = new Regex(@\"`\\d\", RegexOptions.None).Replace(fullname, \"\");\n                fullname = fullname.Replace(\"[\", \"<\");\n                fullname = fullname.Replace(\"]\", \">\");\n            }\n            if (_csTypeNameMapS.TryGetValue(fullname, out name))\n            {\n                return name;\n            }\n            return fullname;\n        }\n\n        public static string StringRepeat(string s, int repeat)\n        {\n            var sb = new System.Text.StringBuilder(s.Length * repeat);\n            for (var i = 0; i < repeat; i++)\n            {\n                sb.Append(s);\n            }\n            return sb.ToString();\n        }\n\n        public string GetConstructorBindName()\n        {\n            if (prefs.randomizedBindingCode)\n            {\n                return 'a' + Guid.NewGuid().ToString().Replace(\"-\", \"\");\n            }\n            return \"BindConstructor\";\n        }\n\n        public string GetBindName(bool bStatic, string csName)\n        {\n            if (prefs.randomizedBindingCode)\n            {\n                return 'Z' + Guid.NewGuid().ToString().Replace(\"-\", \"\");\n            }\n            return (bStatic ? \"BindStatic_\" : \"Bind_\") + csName;\n        }\n\n        public ITSTypeNaming GetTSTypeNaming(Type type, bool noBindingRequired = false)\n        {\n            ITSTypeNaming value = null;\n            if (!_tsTypeNamings.TryGetValue(type, out value))\n            {\n                if (noBindingRequired || GetExportedType(type) != null)\n                {\n                    switch (prefs.GetModuleStyle())\n                    {\n                        case ETSModuleStyle.Singular:\n                            value = new SingularTSTypeNaming();\n                            break;\n                        default:\n                            value = new LegacyTSTypeNaming();\n                            break;\n                    }\n                    value.Initialize(this, type);\n                    _tsTypeNamings[type] = value;\n\n                    var tsModule = GetExportedTSModule(value.moduleName);\n                    tsModule.Add(value.moduleEntry);\n                }\n            }\n\n            return value;\n        }\n\n        public string GetNamingAttribute(TypeTransform transform, MethodInfo info)\n        {\n            if (info.IsSpecialName)\n            {\n                switch (info.Name)\n                {\n                    case \"get_Item\": return \"$GetValue\";\n                    case \"set_Item\": return \"$SetValue\";\n                }\n            }\n\n            return ApplyNameRule(transform.GetNameRule(info), transform.GetNameAlias(info));\n        }\n\n        public string GetNamingAttribute(TypeTransform transform, MemberInfo info)\n        {\n            return ApplyNameRule(transform.GetNameRule(info), transform.GetNameAlias(info));\n        }\n\n        public TypeBindingInfo GetExportedType(Type type)\n        {\n            TypeBindingInfo typeBindingInfo;\n            if (type != null && _exportedTypes.TryGetValue(type, out typeBindingInfo))\n            {\n                return typeBindingInfo;\n            }\n            return null;\n        }\n\n        // 是否在黑名单中屏蔽, 或者已知无需导出的类型\n        public bool IsExportingBlocked(Type type)\n        {\n            if (_typeBlacklist.Contains(type))\n            {\n                return true;\n            }\n\n            if (type.IsGenericType)\n            {\n                if (type.IsConstructedGenericType)\n                {\n                    if (_typeBlacklist.Contains(type.GetGenericTypeDefinition()))\n                    {\n                        return true;\n                    }\n                    if (IsCompoundedType(type.GetGenericArguments()))\n                    {\n                        return true;\n                    }\n                }\n                else\n                {\n                    return true;\n                }\n            }\n\n            if (type.IsDefined(typeof(JSBindingAttribute), false))\n            {\n                return true;\n            }\n\n            if (prefs.excludeObsoleteItems && type.IsDefined(typeof(ObsoleteAttribute), false))\n            {\n                return true;\n            }\n\n            if (type.BaseType == typeof(Attribute))\n            {\n                return true;\n            }\n\n            if (type.BaseType == typeof(MulticastDelegate))\n            {\n                return true;\n            }\n\n            if (type.IsPointer)\n            {\n                return true;\n            }\n\n            //TODO support for unsafe types?\n            if (type.IsDefined(typeof(System.Runtime.CompilerServices.UnsafeValueTypeAttribute), false))\n            {\n                return true;\n            }\n\n            var encloser = type.DeclaringType;\n            if (encloser != null && IsExportingBlocked(encloser))\n            {\n                return true;\n            }\n\n            if (_namespaceBlacklist.Contains(type.Namespace) || _typeFullNameBlacklist.Contains(type.FullName))\n            {\n                return true;\n            }\n\n            // extremely strong impact on performance \n            // for (int i = 0, size = prefs.typePrefixBlacklist.Count; i < size; i++)\n            // {\n            //     if (type.FullName.StartsWith(prefs.typePrefixBlacklist[i]))\n            //     {\n            //         UnityEngine.Debug.LogFormat(\"<01> skip in-blacklist type: {0} NS: {1} Assembly: {2}\", type.FullName, type.Namespace, type.Assembly.FullName);\n            //         return true;\n            //     }\n            // }\n\n            return false;\n        }\n\n        // 是否显式要求导出\n        public bool IsExportingExplicit(Type type)\n        {\n            if (type.IsDefined(typeof(JSTypeAttribute), false))\n            {\n                return true;\n            }\n            return false;\n        }\n\n        private void OnPreCollectAssemblies()\n        {\n            for (int i = 0, size = _enabledBindingProcess.Count; i < size; i++)\n            {\n                var bp = _enabledBindingProcess[i];\n                try\n                {\n                    bp.OnPreCollectAssemblies(this);\n                }\n                catch (Exception exception)\n                {\n                    this.Error($\"process failed [{bp}][OnPreCollect]: {exception}\");\n                }\n            }\n        }\n\n        private void OnPostCollectAssemblies()\n        {\n            for (int i = 0, size = _enabledBindingProcess.Count; i < size; i++)\n            {\n                var bp = _enabledBindingProcess[i];\n                try\n                {\n                    bp.OnPostCollectAssemblies(this);\n                }\n                catch (Exception exception)\n                {\n                    this.Error($\"process failed [{bp}][OnPostCollect]: {exception}\");\n                }\n            }\n        }\n\n        private void OnPostExporting()\n        {\n            for (int i = 0, size = _enabledBindingProcess.Count; i < size; i++)\n            {\n                var bp = _enabledBindingProcess[i];\n                try\n                {\n                    bp.OnPostExporting(this);\n                }\n                catch (Exception exception)\n                {\n                    this.Error($\"process failed [{bp}][OnPostExporting]: {exception}\");\n                }\n            }\n        }\n\n        private void OnPreExporting()\n        {\n            for (int i = 0, size = _enabledBindingProcess.Count; i < size; i++)\n            {\n                var bp = _enabledBindingProcess[i];\n                try\n                {\n                    bp.OnPreExporting(this);\n                }\n                catch (Exception exception)\n                {\n                    this.Error($\"process failed [{bp}][OnPreExporting]: {exception}\");\n                }\n            }\n        }\n\n        private void OnPreCollectTypes()\n        {\n            for (int i = 0, size = _enabledBindingProcess.Count; i < size; i++)\n            {\n                var bp = _enabledBindingProcess[i];\n                try\n                {\n                    bp.OnPreCollectTypes(this);\n                }\n                catch (Exception exception)\n                {\n                    this.Error($\"process failed [{bp}][OnPreCollect]: {exception}\");\n                }\n            }\n        }\n\n        public TypeBindingInfo GetExportedTypeRecursively(Type type)\n        {\n            TypeBindingInfo typeBindingInfo;\n            if (type != null)\n            {\n                if (_exportedTypes.TryGetValue(type, out typeBindingInfo))\n                {\n                    return typeBindingInfo;\n                }\n                return GetExportedTypeRecursively(type.BaseType);\n            }\n            return null;\n        }\n\n        private void OnPostCollectTypes()\n        {\n            for (int i = 0, size = _enabledBindingProcess.Count; i < size; i++)\n            {\n                var bp = _enabledBindingProcess[i];\n                try\n                {\n                    bp.OnPostCollectTypes(this);\n                }\n                catch (Exception exception)\n                {\n                    this.Error($\"process failed [{bp}][OnPostCollect]: {exception}\");\n                }\n            }\n\n\n            for (int i = 0, size = _collectedTypes.Count; i < size; i++)\n            {\n                var collectedType = _collectedTypes[i];\n                CollectIncompatibleMethods(collectedType);\n            }\n        }\n\n        private void CollectIncompatibleMethods(TypeBindingInfo typeBindingInfo)\n        {\n            foreach (var method in typeBindingInfo.methods)\n            {\n                var interfaces = typeBindingInfo.type.GetInterfaces();\n                foreach (var interfaceType in interfaces)\n                {\n                    var interfaceTypeBindingInfo = GetExportedTypeRecursively(interfaceType);\n                    MergeIncompatibleMethods(method.Value, interfaceTypeBindingInfo);\n                }\n\n                var baseType = typeBindingInfo.super;\n                while (baseType != null)\n                {\n                    var baseTypeBindingInfo = GetExportedTypeRecursively(baseType);\n                    if (!MergeIncompatibleMethods(method.Value, baseTypeBindingInfo))\n                    {\n                        break;\n                    }\n                    baseType = baseTypeBindingInfo.super;\n                }\n            }\n        }\n\n        private bool MergeIncompatibleMethods(MethodBindingInfo target, TypeBindingInfo source)\n        {\n            if (source == null)\n            {\n                return false;\n            }\n            MethodBindingInfo sourceMethod;\n            if (source.methods.TryGetValue(target.jsName, out sourceMethod))\n            {\n                foreach (var kv in sourceMethod.variants)\n                {\n                    foreach (var i in kv.Value.plainMethods)\n                    {\n                        target.Add(i.method, i.isExtension);\n                    }\n\n                    foreach (var i in kv.Value.varargMethods)\n                    {\n                        target.Add(i.method, i.isExtension);\n                    }\n                }\n            }\n            return true;\n        }\n\n        private void OnPreGenerateType(TypeBindingInfo bindingInfo)\n        {\n            for (int i = 0, size = _enabledBindingProcess.Count; i < size; i++)\n            {\n                var bp = _enabledBindingProcess[i];\n                try\n                {\n                    bp.OnPreGenerateType(this, bindingInfo);\n                }\n                catch (Exception exception)\n                {\n                    this.Error($\"process failed [{bp}][OnPreGenerateType]: {exception}\");\n                }\n            }\n        }\n\n        private void OnPostGenerateType(TypeBindingInfo bindingInfo)\n        {\n            for (int i = 0, size = _enabledBindingProcess.Count; i < size; i++)\n            {\n                var bp = _enabledBindingProcess[i];\n                try\n                {\n                    bp.OnPostGenerateType(this, bindingInfo);\n                }\n                catch (Exception exception)\n                {\n                    this.Error($\"process failed [{bp}][OnPostGenerateType]: {exception}\");\n                }\n            }\n        }\n\n        public void OnPreGenerateDelegate(DelegateBridgeBindingInfo bindingInfo)\n        {\n            for (int i = 0, size = _enabledBindingProcess.Count; i < size; i++)\n            {\n                var bp = _enabledBindingProcess[i];\n                try\n                {\n                    bp.OnPreGenerateDelegate(this, bindingInfo);\n                }\n                catch (Exception exception)\n                {\n                    this.Error($\"process failed [{bp}][OnPreGenerateDelegate]: {exception}\");\n                }\n            }\n        }\n\n        public void OnPostGenerateDelegate(DelegateBridgeBindingInfo bindingInfo)\n        {\n            for (int i = 0, size = _enabledBindingProcess.Count; i < size; i++)\n            {\n                var bp = _enabledBindingProcess[i];\n                try\n                {\n                    bp.OnPostGenerateDelegate(this, bindingInfo);\n                }\n                catch (Exception exception)\n                {\n                    this.Error($\"process failed [{bp}][OnPostGenerateDelegate]: {exception}\");\n                }\n            }\n        }\n\n        private void OnCleanup()\n        {\n            for (int i = 0, size = _enabledBindingProcess.Count; i < size; i++)\n            {\n                var bp = _enabledBindingProcess[i];\n                try\n                {\n                    bp.OnCleanup(this);\n                }\n                catch (Exception exception)\n                {\n                    this.Error($\"process failed [{bp}][OnCleanup]: {exception}\");\n                }\n            }\n        }\n\n        public void Collect()\n        {\n            // 收集直接类型, 加入 exportedTypes\n            OnPreCollectAssemblies();\n            AddAssemblies(false, prefs.explicitAssemblies.ToArray());\n            AddAssemblies(true, prefs.implicitAssemblies.ToArray());\n            var assemblies = AppDomain.CurrentDomain.GetAssemblies();\n            for (var i = 0; i < assemblies.Length; i++)\n            {\n                var assembly = assemblies[i];\n                if (!assembly.IsDynamic && !IsAssemblyBlocked(assembly))\n                {\n                    AddAssemblies(false, assembly.FullName);\n                }\n            }\n            OnPostCollectAssemblies();\n\n            OnPreExporting();\n            ExportAssemblies(_explicitAssemblies, false);\n            ExportAssemblies(_implicitAssemblies, true);\n            ExportBuiltins();\n            OnPostExporting();\n\n            Info(\"collecting members\");\n            _logWriter?.AddTabLevel();\n            OnPreCollectTypes();\n            foreach (var type in _hotfixTypes)\n            {\n                CollectHotfix(type);\n            }\n\n            foreach (var typeBindingInfoKV in _exportedTypes)\n            {\n                _CollectType(typeBindingInfoKV.Value.type);\n            }\n\n            OnPostCollectTypes();\n            _logWriter?.DecTabLevel();\n        }\n\n        private void _CollectType(Type type)\n        {\n            if (type == null)\n            {\n                return;\n            }\n            var typeBindingInfo = GetExportedType(type);\n\n            _CollectType(type.DeclaringType);\n\n            if (typeBindingInfo == null || _collectedTypes.Contains(typeBindingInfo))\n            {\n                return;\n            }\n\n            typeBindingInfo.Initialize();\n            _collectedTypes.Add(typeBindingInfo);\n            Info(\"type: {0}\", type);\n            _logWriter?.AddTabLevel();\n            typeBindingInfo.Collect();\n            _logWriter?.DecTabLevel();\n        }\n\n        public void AddTypeFullNameBlacklist(string fullName)\n        {\n            _typeFullNameBlacklist.Add(fullName);\n        }\n\n        public bool IsNamespaceInBlacklist(string ns)\n        {\n            return _namespaceBlacklist.Contains(ns);\n        }\n\n        public bool RemoveNamespaceBlacklist(string ns)\n        {\n            return _namespaceBlacklist.Remove(ns);\n        }\n\n        public void AddNamespaceBlacklist(string ns)\n        {\n            _namespaceBlacklist.Add(ns);\n        }\n\n        public void AddAssemblyBlacklist(string simplifiedAssembly)\n        {\n            _assemblyBlacklist.Add(simplifiedAssembly);\n        }\n\n        public void RemoveAssemblyBlacklist(string simplifiedAssembly)\n        {\n            _assemblyBlacklist.Remove(simplifiedAssembly);\n        }\n\n        public bool InAssemblyBlacklist(string simplifiedAssembly)\n        {\n            return _assemblyBlacklist.Contains(simplifiedAssembly);\n        }\n\n        public bool IsAssemblyReferencedTo(Assembly assembly, Assembly target)\n        {\n            if (assembly == target)\n            {\n                return true;\n            }\n\n            var refs = assembly.GetReferencedAssemblies();\n            for (int i = 0, count = refs.Length; i < count; i++)\n            {\n                var @ref = refs[i];\n                if (AssemblyName.ReferenceMatchesDefinition(@ref, target.GetName()))\n                {\n                    return true;\n                }\n            }\n\n            return false;\n        }\n\n        public bool IsAssemblyBlocked(Assembly assembly)\n        {\n            try\n            {\n                if (string.IsNullOrEmpty(assembly.Location))\n                {\n                    return false;\n                }\n                var fileInfo = new FileInfo(assembly.Location);\n                if (fileInfo.DirectoryName.EndsWith(\"/Editor/Data/Managed\"))\n                {\n                    return true;\n                }\n                if (fileInfo.Name.StartsWith(\"UnityEditor\"))\n                {\n                    return true;\n                }\n            }\n            catch (Exception ex)\n            {\n                _bindingLogger?.LogError($\"{assembly} {assembly.Location} {ex}\");\n                return false;\n            }\n\n            var refs = assembly.GetReferencedAssemblies();\n            for (int i = 0, count = refs.Length; i < count; i++)\n            {\n                var @ref = refs[i];\n                if (@ref.Name == \"UnityEditor\")\n                {\n                    return true;\n                }\n            }\n\n            return _assemblyBlacklist.Contains(GetSimplifiedAssemblyName(assembly));\n        }\n\n        public string GetSimplifiedAssemblyName(Assembly assembly)\n        {\n            var comma = assembly.FullName.IndexOf(',');\n            var name = comma >= 0 ? assembly.FullName.Substring(0, comma) : assembly.FullName;\n            return name;\n        }\n\n        public void AddAssemblies(bool implicitExport, params string[] assemblyNames)\n        {\n            if (implicitExport)\n            {\n                for (var i = 0; i < assemblyNames.Length; i++)\n                {\n                    var assemblyName = assemblyNames[i];\n                    if (!_implicitAssemblies.Contains(assemblyName) && !_explicitAssemblies.Contains(assemblyName))\n                    {\n                        _implicitAssemblies.Add(assemblyName);\n                    }\n                }\n            }\n            else\n            {\n                for (var i = 0; i < assemblyNames.Length; i++)\n                {\n                    var assemblyName = assemblyNames[i];\n                    if (!_implicitAssemblies.Contains(assemblyName) && !_explicitAssemblies.Contains(assemblyName))\n                    {\n                        _explicitAssemblies.Add(assemblyName);\n                    }\n                }\n            }\n        }\n\n        public void RemoveAssemblies(params string[] assemblyNames)\n        {\n            foreach (var name in assemblyNames)\n            {\n                _implicitAssemblies.Remove(name);\n                _explicitAssemblies.Remove(name);\n            }\n        }\n\n        /// <summary>\n        /// 导出一些必要的基本类型\n        /// </summary>\n        private void ExportBuiltins()\n        {\n            AddExportedType(typeof(byte)).SystemRuntime();\n            AddExportedType(typeof(sbyte)).SystemRuntime();\n            AddExportedType(typeof(float)).SystemRuntime();\n            AddExportedType(typeof(double)).SystemRuntime();\n            AddExportedType(typeof(string)).SystemRuntime()\n                .SetMemberBlocked(\"ContainsInvariantCultureIgnoreCase\");\n            AddExportedType(typeof(int)).SystemRuntime();\n            AddExportedType(typeof(uint)).SystemRuntime();\n            AddExportedType(typeof(short)).SystemRuntime();\n            AddExportedType(typeof(ushort)).SystemRuntime();\n            AddExportedType(typeof(object)).SystemRuntime();\n            AddExportedType(typeof(Array)).SystemRuntime();\n            AddExportedType(typeof(Delegate)).SystemRuntime()\n                .SetMemberBlocked(\"CreateDelegate\")\n            ;\n\n            AddExportedType(typeof(System.Enum)).SystemRuntime();\n            AddExportedType(typeof(QuickJS.IO.ByteBuffer));\n        }\n\n        // implicitExport: 默认进行导出(黑名单例外), 否则根据导出标记或手工添加\n        private void ExportAssemblies(List<string> assemblyNames, bool implicitExport)\n        {\n            foreach (var assemblyName in assemblyNames)\n            {\n                Info(\"assembly: {0}\", assemblyName);\n                _logWriter?.AddTabLevel();\n                ExportTypesInAssembly(TryGetAssembly(assemblyName), implicitExport);\n                _logWriter?.DecTabLevel();\n            }\n        }\n\n        public static Assembly TryGetAssembly(string name)\n        {\n            try { return Assembly.Load(name); } catch (Exception) { }\n            return null;\n        }\n\n        public void ExportTypesInAssembly(Assembly assembly, bool implicitExport, Action<TypeTransform> iterator = null)\n        {\n            try\n            {\n                if (assembly == null || assembly.IsDynamic)\n                {\n                    return;\n                }\n                var types = assembly.GetExportedTypes();\n\n                Info(\"info: {0}\", assembly);\n                Info(\"location: {0}\", assembly.Location);\n                Info(\"types: {0}\", types.Length);\n                _logWriter?.AddTabLevel();\n                foreach (var type in types)\n                {\n                    if (Attribute.IsDefined(type, typeof(JSHotfixAttribute)))\n                    {\n                        var hotfixTag = Attribute.GetCustomAttribute(type, typeof(JSHotfixAttribute)) as JSHotfixAttribute;\n                        if (hotfixTag != null)\n                        {\n                            TransformType(type).SetHotfix(hotfixTag);\n                            AddHotfixType(type);\n                        }\n                    }\n\n                    if (IsExportingBlocked(type))\n                    {\n                        Info(\"blocked: {0}\", type.FullName);\n                        continue;\n                    }\n\n                    if (implicitExport)\n                    {\n                        Info(\"export (implicit): {0}\", type.FullName);\n                        var transform = this.AddExportedType(type, true);\n                        iterator?.Invoke(transform);\n                        continue;\n                    }\n\n                    if (IsExportingExplicit(type))\n                    {\n                        Info(\"export (explicit): {0}\", type.FullName);\n                        var transform = this.AddExportedType(type, true);\n                        iterator?.Invoke(transform);\n                        continue;\n                    }\n\n                    TryCollectMethods(type);\n                    Info(\"skip: {0}\", type.FullName);\n                }\n                _logWriter?.DecTabLevel();\n            }\n            catch (Exception exception)\n            {\n                Error(exception.ToString());\n            }\n        }\n\n        /// <summary>\n        /// collect extension methods and value operation methods (the type itself will not be exported)\n        /// </summary>\n        public void TryCollectMethods(Type type)\n        {\n            var methods = type.GetMethods(QuickJS.Binding.DynamicType.PublicFlags);\n            var methodCount = methods.Length;\n            for (var methodIndex = 0; methodIndex < methodCount; methodIndex++)\n            {\n                var method = methods[methodIndex];\n                if (TryCollectExtensionMethod(type, method) || TryCollectValueOperator(type, method))\n                {\n                }\n            }\n        }\n\n        public bool TryCollectExtensionMethod(Type type, MethodInfo method)\n        {\n            if (IsExtensionMethod(method))\n            {\n                var parameters = method.GetParameters();\n                var declType = parameters[0].ParameterType;\n                TransformType(declType).AddExtensionMethod(method);\n                return true;\n            }\n            return false;\n        }\n\n        public bool TryCollectValueOperator(Type type, MethodInfo method)\n        {\n            if (type != typeof(Values) && Values.register_type_caster(method))\n            {\n                return true;\n            }\n\n            return false;\n        }\n\n        /// <summary>\n        /// remove unused files in 'Generated' directory\n        /// </summary>\n        public void Cleanup()\n        {\n            Info(\"cleanup\");\n            _logWriter?.AddTabLevel();\n            Cleanup(_outputFiles, file =>\n            {\n                _removedFiles.Add(file);\n                Info(\"remove unused file {0}\", file);\n            });\n            OnCleanup();\n            _logWriter?.DecTabLevel();\n        }\n\n        public static void Cleanup(Dictionary<string, List<string>> excludedFilesKV, Action<string> ondelete)\n        {\n            foreach (var kv in excludedFilesKV)\n            {\n                var outDir = kv.Key;\n                var excludedFiles = kv.Value;\n                if (Directory.Exists(outDir))\n                {\n                    foreach (var file in Directory.GetFiles(outDir))\n                    {\n                        var nfile = file;\n                        if (file.EndsWith(\".meta\"))\n                        {\n                            nfile = file.Substring(0, file.Length - 5);\n                        }\n                        // UnityEngine.Debug.LogFormat(\"checking file {0}\", nfile);\n                        if (excludedFiles == null || !excludedFiles.Contains(nfile))\n                        {\n                            File.Delete(file);\n                            if (ondelete != null)\n                            {\n                                ondelete(file);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        public void AddOutputFile(string outDir, string filename)\n        {\n            List<string> list;\n            if (!_outputFiles.TryGetValue(outDir, out list))\n            {\n                list = _outputFiles[outDir] = new List<string>();\n            }\n            list.Add(filename);\n        }\n\n        public void Generate(TypeBindingFlags typeBindingFlags)\n        {\n            var cg = new CodeGenerator(this, typeBindingFlags);\n            var csOutDir = _utils.ReplacePathVars(prefs.outDir);\n            var tsOutDir = _utils.ReplacePathVars(prefs.typescriptDir);\n            var cancel = false;\n            var current = 0;\n            var total = _exportedTypes.Count;\n\n            cg.Begin();\n            _codegenCallback?.OnCodeGenBegin(this);\n            _bindingCallback?.OnBindingBegin(this);\n            foreach (var typeKV in _exportedTypes)\n            {\n                var typeBindingInfo = typeKV.Value;\n                try\n                {\n                    current++;\n                    cancel = _codegenCallback != null ? _codegenCallback.OnTypeGenerating(typeBindingInfo, current, total) : false;\n                    if (cancel)\n                    {\n                        Warn(\"operation canceled\");\n                        break;\n                    }\n\n                    if (!typeBindingInfo.omit)\n                    {\n                        cg.Clear();\n                        OnPreGenerateType(typeBindingInfo);\n                        cg.Generate(typeBindingInfo);\n                        OnPostGenerateType(typeBindingInfo);\n\n                        if (_codegenCallback != null)\n                        {\n                            _WriteCSharp(cg, csOutDir, typeBindingInfo.csBindingName);\n                        }\n                    }\n                }\n                catch (Exception exception)\n                {\n                    Error($\"generate failed {typeBindingInfo.type.FullName}: {exception.Message}\\n{exception.StackTrace}\");\n                }\n            }\n\n            if (!cancel)\n            {\n                try\n                {\n                    var exportedDelegatesArray = new DelegateBridgeBindingInfo[this._exportedDelegates.Count];\n                    this._exportedDelegates.Values.CopyTo(exportedDelegatesArray, 0);\n\n                    if (_bindingCallback != null)\n                    {\n                        for (var i = 0; i < exportedDelegatesArray.Length; i++)\n                        {\n                            var delegateBindingInfo = exportedDelegatesArray[i];\n                            // var nargs = delegateBindingInfo.parameters.Length;\n\n                            _bindingCallback.AddDelegate(delegateBindingInfo);\n                        }\n                    }\n\n                    if (_codegenCallback != null)\n                    {\n                        cg.Clear();\n                        cg.Generate(exportedDelegatesArray, _exportedHotfixDelegates);\n                        _WriteCSharp(cg, csOutDir, CodeGenerator.NameOfDelegates);\n                    }\n                }\n                catch (Exception exception)\n                {\n                    Error($\"generate delegates failed: {exception.Message}\");\n                }\n            }\n\n            if (!cancel)\n            {\n                try\n                {\n                    var modules = from t in _collectedTypes\n                                  where t.genBindingCode\n                                  group t by t.tsTypeNaming.moduleName;\n\n                    // for reflect binding\n                    if (_bindingCallback != null)\n                    {\n                        _bindingCallback.BindRawTypes(_collectedRawTypes.Values);\n                        foreach (var module in modules)\n                        {\n                            var count = module.Count();\n\n                            if (count > 0)\n                            {\n                                var moduleName = string.IsNullOrEmpty(module.Key) ? this.prefs.defaultJSModule : module.Key;\n                                _bindingCallback.BeginStaticModule(moduleName, count);\n                                foreach (var type in module)\n                                {\n                                    _bindingCallback.AddTypeReference(moduleName, type);\n                                }\n                                _bindingCallback.EndStaticModule(moduleName);\n                            }\n                        }\n                    }\n\n                    if (_codegenCallback != null)\n                    {\n                        cg.Clear();\n                        _codegenCallback.OnGenerateBindingList(cg, modules, _collectedRawTypes.Values);\n                        _WriteCSharp(cg, csOutDir, CodeGenerator.NameOfBindingList);\n                    }\n                }\n                catch (Exception exception)\n                {\n                    Error($\"generate delegates failed: {exception.Message}\");\n                }\n            }\n            cg.End();\n\n            if (!cancel)\n            {\n                try\n                {\n                    cg.Clear();\n                    _WriteTSD(cg, tsOutDir, \"jsb.autogen\");\n                }\n                catch (Exception exception)\n                {\n                    Error($\"generate delegates failed: {exception.Message}\");\n                }\n            }\n\n            _bindingCallback?.OnBindingEnd();\n            _codegenCallback?.OnCodeGenEnd();\n\n            try\n            {\n                var logText = _logWriter?.Submit();\n                if (!string.IsNullOrEmpty(logText) && !string.IsNullOrEmpty(prefs.logPath))\n                {\n                    var logPath = prefs.logPath;\n                    var logDir = Path.GetDirectoryName(logPath);\n                    if (!Directory.Exists(logDir))\n                    {\n                        Directory.CreateDirectory(logDir);\n                    }\n                    File.WriteAllText(logPath, logText);\n                }\n            }\n            catch (Exception)\n            {\n            }\n\n            _codegenCallback?.OnGenerateFinish();\n        }\n\n        private void _WriteTSD(CodeGenerator cg, string tsOutDir, string tsName)\n        {\n            try\n            {\n                if (cg.tsDeclare.enabled && !cg.tsDeclare.isEmpty)\n                {\n                    _codegenCallback?.OnSourceCodeEmitted(cg, tsOutDir, tsName, SourceCodeType.TSD, cg.tsDeclare);\n                }\n            }\n            catch (Exception exception)\n            {\n                this.Error(\"write typescript declaration file failed [{0}]: {1}\", tsName, exception.Message);\n            }\n        }\n\n        private void _WriteCSharp(CodeGenerator cg, string csOutDir, string csName)\n        {\n            try\n            {\n                if (cg.cs.enabled && !cg.cs.isEmpty)\n                {\n                    _codegenCallback?.OnSourceCodeEmitted(cg, csOutDir, csName, SourceCodeType.CSharp, cg.cs);\n                }\n            }\n            catch (Exception exception)\n            {\n                this.Error(\"write csharp file failed [{0}]: {1}\", csName, exception.Message);\n            }\n        }\n\n        public void Report()\n        {\n            var now = DateTime.Now;\n            var ts = now.Subtract(dateTime);\n            _bindingLogger?.Log(string.Format(\"generated {0} type(s), {1} delegate(s), {2} deletion(s) in {3:0.##} seconds.\",\n                _exportedTypes.Count,\n                _exportedDelegates.Count,\n                _removedFiles.Count,\n                ts.TotalSeconds));\n        }\n    }\n}\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingManager.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 35fe53e5b44fff64b9081ca2aa5fce40\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingManager_Log.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public partial class BindingManager\r\n    {\r\n        public void Info(string message)\r\n        {\r\n            _logWriter?.AppendLine(message);\r\n        }\r\n\r\n        public void Info(string fmt, object arg1)\r\n        {\r\n            _logWriter?.AppendLine(fmt, arg1);\r\n        }\r\n\r\n        public void Info(string fmt, object arg1, string arg2)\r\n        {\r\n            _logWriter?.AppendLine(fmt, arg1, arg2);\r\n        }\r\n\r\n        public void Info(string fmt, params object[] args)\r\n        {\r\n            _logWriter?.AppendLine(fmt, args);\r\n        }\r\n\r\n        public void Error(Exception exception)\r\n        {\r\n            var str = string.Format(\"{0}\\n{1}\", exception.Message, exception.StackTrace);\r\n            if (exception.InnerException != null)\r\n            {\r\n                str += string.Format(\"=== Inner Exception ===\\n{0}\\n{1}\", exception.InnerException.Message, exception.InnerException.StackTrace);\r\n            }\r\n            Error(str);\r\n        }\r\n\r\n        public void Error(string message)\r\n        {\r\n            _bindingLogger?.LogError(message);\r\n            _logWriter?.AppendLine(message);\r\n        }\r\n\r\n        public void Error(string fmt, object arg1)\r\n        {\r\n            _bindingLogger?.LogError(string.Format(fmt, arg1));\r\n            _logWriter?.AppendLine(fmt, arg1);\r\n        }\r\n\r\n        public void Error(string fmt, object arg1, string arg2)\r\n        {\r\n            _bindingLogger?.LogError(string.Format(fmt, arg1, arg2));\r\n            _logWriter?.AppendLine(fmt, arg1, arg2);\r\n        }\r\n\r\n        public void Error(string fmt, params object[] args)\r\n        {\r\n            _bindingLogger?.LogError(string.Format(fmt, args));\r\n            _logWriter?.AppendLine(fmt, args);\r\n        }\r\n\r\n        public void Warn(string message)\r\n        {\r\n            _bindingLogger?.LogWarning(message);\r\n            _logWriter?.AppendLine(message);\r\n        }\r\n\r\n        public void Warn(string fmt, object arg1)\r\n        {\r\n            _bindingLogger?.LogWarning(string.Format(fmt, arg1));\r\n            _logWriter?.AppendLine(fmt, arg1);\r\n        }\r\n\r\n        public void Warn(string fmt, object arg1, string arg2)\r\n        {\r\n            _bindingLogger?.LogWarning(string.Format(fmt, arg1, arg2));\r\n            _logWriter?.AppendLine(fmt, arg1, arg2);\r\n        }\r\n\r\n        public void Warn(string fmt, params object[] args)\r\n        {\r\n            _bindingLogger?.LogWarning(string.Format(fmt, args));\r\n            _logWriter?.AppendLine(fmt, args);\r\n        }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingManager_Log.cs.meta",
    "content": "fileFormatVersion: 2\nguid: faa27c60156b27f4ca464fcbd1b5a0eb\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingManager_helper.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public partial class BindingManager\r\n    {\r\n        public static void UnitylessReflectBind(ScriptRuntime runtime)\r\n        {\r\n            var bm = new BindingManager(new Prefs(), new BindingManager.Args\r\n            {\r\n                bindingCallback = new ReflectBindingCallback(runtime),\r\n            });\r\n            bm.Collect();\r\n            bm.Generate(TypeBindingFlags.None);\r\n            bm.Report();\r\n        }\r\n\r\n        public static int GetTSParameterCount(ParameterInfo[] parameters)\r\n        {\r\n            var len = parameters.Length;\r\n            var argc = len;\r\n            for (var i = 0; i < len; i++)\r\n            {\r\n                var parameterType = parameters[i].ParameterType;\r\n                if (Binding.Values.IsContextualType(parameterType))\r\n                {\r\n                    argc--;\r\n                }\r\n            }\r\n            return argc;\r\n        }\r\n\r\n        public static bool IsExtensionMethod(MethodBase method)\r\n        {\r\n            return method.IsStatic && method.IsDefined(typeof(System.Runtime.CompilerServices.ExtensionAttribute), false);\r\n        }\r\n\r\n        public static bool ContainsGenericParameters(MethodBase method)\r\n        {\r\n            var parameters = method.GetParameters();\r\n            for (int i = 0, size = parameters.Length; i < size; i++)\r\n            {\r\n                var parameterType = parameters[i].ParameterType;\r\n                if (parameterType.IsGenericTypeDefinition || parameterType.IsGenericParameter)\r\n                {\r\n                    return true;\r\n                }\r\n            }\r\n            return false;\r\n        }\r\n\r\n        // 是否包含指针参数\r\n        public static bool ContainsPointer(MethodInfo method)\r\n        {\r\n            if (method.ReturnType.IsPointer)\r\n            {\r\n                return true;\r\n            }\r\n            return ContainsPointer((MethodBase)method);\r\n        }\r\n\r\n        public static bool ContainsPointer(MethodBase method)\r\n        {\r\n            var parameters = method.GetParameters();\r\n            for (int i = 0, size = parameters.Length; i < size; i++)\r\n            {\r\n                var parameterType = parameters[i].ParameterType;\r\n                if (parameterType.IsPointer)\r\n                {\r\n                    return true;\r\n                }\r\n            }\r\n            return false;\r\n        }\r\n\r\n        public static bool ContainsUnsupportedParameter(MethodInfo method)\r\n        {\r\n            if (method.ReturnType.IsPointer || method.ReturnType.FullName == null)\r\n            {\r\n                return true;\r\n            }\r\n            return ContainsUnsupportedParameter((MethodBase)method);\r\n        }\r\n\r\n        public static bool ContainsUnsupportedParameter(MethodBase method)\r\n        {\r\n            var parameters = method.GetParameters();\r\n            for (int i = 0, size = parameters.Length; i < size; i++)\r\n            {\r\n                var parameterType = parameters[i].ParameterType;\r\n                if (parameterType.IsPointer || parameterType.FullName == null)\r\n                {\r\n                    return true;\r\n                }\r\n            }\r\n            return false;\r\n        }\r\n\r\n        // 是否包含按引用传参 (ref/out)\r\n        public static bool ContainsByRefParameters(ParameterInfo[] parameters)\r\n        {\r\n            for (int i = 0, size = parameters.Length; i < size; i++)\r\n            {\r\n                var parameterType = parameters[i].ParameterType;\r\n                if (parameterType.IsByRef)\r\n                {\r\n                    return true;\r\n                }\r\n            }\r\n            return false;\r\n        }\r\n\r\n        public static bool ContainsByRefParameters(MethodBase method)\r\n        {\r\n            return ContainsByRefParameters(method.GetParameters());\r\n        }\r\n\r\n        public static bool IsGenericMethod(MethodBase method)\r\n        {\r\n            return method.GetGenericArguments().Length > 0;\r\n        }\r\n\r\n        public static bool IsUnsupported(MethodBase method)\r\n        {\r\n            return ContainsUnsupportedParameter(method) || IsGenericMethod(method);\r\n        }\r\n\r\n        public static bool IsUnsupported(MethodInfo method)\r\n        {\r\n            return ContainsUnsupportedParameter(method) || IsGenericMethod(method);\r\n        }\r\n\r\n        #region Helper for Extension Methods \r\n        \r\n        public TypeTransform AddExtensionMethod<T>(Action<T> method, string tsDecl = null)\r\n        {\r\n            return AddExtensionMethod(method.Method, tsDecl);\r\n        }\r\n\r\n        public TypeTransform AddExtensionMethod<T1, T2>(Action<T1, T2> method, string tsDecl = null)\r\n        {\r\n            return AddExtensionMethod(method.Method, tsDecl);\r\n        }\r\n\r\n        public TypeTransform AddExtensionMethod<T1, T2, T3>(Action<T1, T2, T3> method, string tsDecl = null)\r\n        {\r\n            return AddExtensionMethod(method.Method, tsDecl);\r\n        }\r\n\r\n        public TypeTransform AddExtensionMethod<TResult>(Func<TResult> method, string tsDecl = null)\r\n        {\r\n            return AddExtensionMethod(method.Method, tsDecl);\r\n        }\r\n\r\n        public TypeTransform AddExtensionMethod<T1, TResult>(Func<T1, TResult> method, string tsDecl = null)\r\n        {\r\n            return AddExtensionMethod(method.Method, tsDecl);\r\n        }\r\n\r\n        public TypeTransform AddExtensionMethod<T1, T2, TResult>(Func<T1, T2, TResult> method, string tsDecl = null)\r\n        {\r\n            return AddExtensionMethod(method.Method, tsDecl);\r\n        }\r\n\r\n        public TypeTransform AddExtensionMethod<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult> method, string tsDecl = null)\r\n        {\r\n            return AddExtensionMethod(method.Method, tsDecl);\r\n        }\r\n\r\n        public TypeTransform AddExtensionMethod(MethodInfo method, string tsDecl = null)\r\n        {\r\n            if (!IsExtensionMethod(method))\r\n            {\r\n                throw new InvalidCastException(\"Not an extension method: \" + method.ToString());\r\n            }\r\n\r\n            var parameters = method.GetParameters();\r\n            var parameterType = parameters[0].ParameterType;\r\n            return TransformType(parameterType).AddExtensionMethod(method, tsDecl);\r\n        }\r\n\r\n        #endregion\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/BindingManager_helper.cs.meta",
    "content": "fileFormatVersion: 2\nguid: ef0f581514c9f9e44956d3c0a868a13a\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.Linq;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing System.IO;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public class CSDebugCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n\r\n        public CSDebugCodeGen(CodeGenerator cg)\r\n        {\r\n            this.cg = cg;\r\n            if (cg.bindingManager.prefs.debugCodegen)\r\n            {\r\n                this.cg.cs.AppendLine(\"/*\");\r\n            }\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n            if (cg.bindingManager.prefs.debugCodegen)\r\n            {\r\n                this.cg.cs.AppendLine(\"*/\");\r\n            }\r\n        }\r\n    }\r\n\r\n    public class CSTopLevelCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n\r\n        public CSTopLevelCodeGen(CodeGenerator cg, TypeBindingInfo typeBindingInfo)\r\n        {\r\n            this.cg = cg;\r\n            this.AppendCommonHead();\r\n            // this.cg.typescript.AppendLine(\"// {0} {1}\", Environment.UserName, this.cg.bindingManager.dateTime);\r\n        }\r\n\r\n        public CSTopLevelCodeGen(CodeGenerator cg, string name)\r\n        {\r\n            this.cg = cg;\r\n            this.AppendCommonHead();\r\n            this.cg.cs.AppendLine(\"// Special: {0}\", name);\r\n        }\r\n\r\n        private void AppendCommonHead()\r\n        {\r\n#if !JSB_UNITYLESS\r\n            this.cg.cs.AppendLine(\"// Unity: {0}\", UnityEngine.Application.unityVersion);\r\n#endif\r\n            this.cg.cs.AppendLine(\"using System;\");\r\n            this.cg.cs.AppendLine(\"using System.Collections.Generic;\");\r\n            this.cg.cs.AppendLine();\r\n        }\r\n\r\n        private void AppendCommonTail()\r\n        {\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n            AppendCommonTail();\r\n        }\r\n    }\r\n\r\n    public class CSNamespaceCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n        protected string csNamespace;\r\n\r\n        public CSNamespaceCodeGen(CodeGenerator cg, string csNamespace, params string[] csUsings)\r\n        {\r\n            this.cg = cg;\r\n            this.csNamespace = csNamespace;\r\n\r\n            if (!string.IsNullOrEmpty(csNamespace))\r\n            {\r\n                this.cg.cs.AppendLine(\"namespace {0} {{\", csNamespace);\r\n                this.cg.cs.AddTabLevel();\r\n            }\r\n\r\n            this.cg.cs.AppendLine(\"using QuickJS.Errors;\");\r\n            this.cg.cs.AppendLine(\"using JSValue = QuickJS.Native.JSValue;\");\r\n            this.cg.cs.AppendLine(\"using JSApi = QuickJS.Native.JSApi;\");\r\n            this.cg.cs.AppendLine(\"using JSNative = QuickJS.JSNative;\");\r\n            this.cg.cs.AppendLine(\"using JSContext = QuickJS.Native.JSContext;\");\r\n            this.cg.cs.AppendLine(\"using Values = QuickJS.Binding.Values;\");\r\n            this.cg.cs.AppendLine(\"using ScriptEngine = QuickJS.ScriptEngine;\");\r\n            this.cg.cs.AppendLine(\"using JSBindingAttribute = QuickJS.JSBindingAttribute;\");\r\n            this.cg.cs.AppendLine(\"using MonoPInvokeCallbackAttribute = QuickJS.MonoPInvokeCallbackAttribute;\");\r\n            foreach (var @using in csUsings)\r\n            {\r\n                this.cg.cs.AppendLine(\"using {0};\", @using);\r\n            }\r\n            // this.cg.cs.AppendLine(\"using QuickJS;\");\r\n            // this.cg.cs.AppendLine(\"using QuickJS.Binding;\");\r\n            // this.cg.cs.AppendLine(\"using QuickJS.Native;\");\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n            if (!string.IsNullOrEmpty(csNamespace))\r\n            {\r\n                this.cg.cs.DecTabLevel();\r\n                this.cg.cs.AppendLine(\"}\");\r\n            }\r\n        }\r\n    }\r\n\r\n    public class TSNamespaceCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n        protected string tsNamespace;\r\n\r\n        public TSNamespaceCodeGen(CodeGenerator cg, string tsNamespace)\r\n        {\r\n            this.cg = cg;\r\n            this.tsNamespace = tsNamespace;\r\n\r\n            if (!string.IsNullOrEmpty(tsNamespace))\r\n            {\r\n                this.cg.tsDeclare.AppendLine($\"namespace {this.tsNamespace} {{\");\r\n                this.cg.tsDeclare.AddTabLevel();\r\n            }\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n            if (!string.IsNullOrEmpty(tsNamespace))\r\n            {\r\n                this.cg.tsDeclare.DecTabLevel();\r\n                this.cg.tsDeclare.AppendLine(\"}\");\r\n            }\r\n        }\r\n    }\r\n\r\n    public class RegFuncCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n\r\n        public RegFuncCodeGen(CodeGenerator cg)\r\n        {\r\n            this.cg = cg;\r\n            this.cg.cs.AppendLine(\"public static {0} Bind({1} register)\", \r\n                this.cg.bindingManager.GetCSTypeFullName(typeof(ClassDecl)),\r\n                this.cg.bindingManager.GetCSTypeFullName(typeof(TypeRegister)));\r\n            this.cg.cs.AppendLine(\"{\");\r\n            this.cg.cs.AddTabLevel();\r\n        }\r\n\r\n        public virtual void Dispose()\r\n        {\r\n            this.cg.cs.DecTabLevel();\r\n            this.cg.cs.AppendLine(\"}\");\r\n        }\r\n    }\r\n\r\n    public class RuntimeRegFuncCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n\r\n        public RuntimeRegFuncCodeGen(CodeGenerator cg)\r\n        {\r\n            this.cg = cg;\r\n            this.cg.cs.AppendLine(\"public static void Bind({0} runtime)\", \r\n                this.cg.bindingManager.GetCSTypeFullName(typeof(ScriptRuntime)));\r\n            this.cg.cs.AppendLine(\"{\");\r\n            this.cg.cs.AddTabLevel();\r\n        }\r\n\r\n        public virtual void Dispose()\r\n        {\r\n            this.cg.cs.DecTabLevel();\r\n            this.cg.cs.AppendLine(\"}\");\r\n        }\r\n    }\r\n\r\n    public class TypeCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n        protected TypeBindingInfo typeBindingInfo;\r\n\r\n        public TypeCodeGen(CodeGenerator cg, TypeBindingInfo typeBindingInfo)\r\n        {\r\n            this.cg = cg;\r\n            this.typeBindingInfo = typeBindingInfo;\r\n            this.cg.cs.AppendLine(\"// Assembly: {0}\", typeBindingInfo.Assembly.GetName());\r\n            this.cg.cs.AppendLine(\"// Location: {0}\", typeBindingInfo.Assembly.Location);\r\n            this.cg.cs.AppendLine(\"// Type: {0}\", typeBindingInfo.FullName);\r\n            this.cg.cs.AppendLine(\"[{0}]\", nameof(JSBindingAttribute));\r\n            // this.cg.cs.AppendLine(\"[UnityEngine.Scripting.Preserve]\");\r\n            this.cg.cs.AppendLine(\"public class {0}\", typeBindingInfo.csBindingName);\r\n            this.cg.cs.AppendLine(\"{\");\r\n            this.cg.cs.AddTabLevel();\r\n        }\r\n\r\n        public string GetTypeName(Type type)\r\n        {\r\n            return type.FullName.Replace(\".\", \"_\");\r\n        }\r\n\r\n        public virtual void Dispose()\r\n        {\r\n            this.cg.cs.DecTabLevel();\r\n            this.cg.cs.AppendLine(\"}\");\r\n        }\r\n    }\r\n\r\n    public class PreservedCodeGen : IDisposable\r\n    {\r\n        public PreservedCodeGen(CodeGenerator cg)\r\n        {\r\n            cg.cs.AppendLine(\"[UnityEngine.Scripting.Preserve]\");\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n        }\r\n    }\r\n\r\n    public class PInvokeGuardCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n\r\n        public PInvokeGuardCodeGen(CodeGenerator cg, Type target)\r\n        {\r\n            this.cg = cg;\r\n            this.cg.cs.AppendLine(\"[MonoPInvokeCallbackAttribute(typeof({0}))]\", target.FullName);\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n        }\r\n    }\r\n\r\n    public class BindingGetterFuncDeclareCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n\r\n        public BindingGetterFuncDeclareCodeGen(CodeGenerator cg, string name)\r\n        {\r\n            this.cg = cg;\r\n            this.cg.cs.AppendLine(\"public static JSValue {0}(JSContext ctx, JSValue this_obj)\", name);\r\n            this.cg.cs.AppendLine(\"{\");\r\n            this.cg.cs.AddTabLevel();\r\n        }\r\n\r\n        public virtual void Dispose()\r\n        {\r\n            this.cg.cs.DecTabLevel();\r\n            this.cg.cs.AppendLine(\"}\");\r\n        }\r\n    }\r\n\r\n    public class BindingSetterFuncDeclareCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n\r\n        public BindingSetterFuncDeclareCodeGen(CodeGenerator cg, string name)\r\n        {\r\n            this.cg = cg;\r\n            this.cg.cs.AppendLine(\"public static JSValue {0}(JSContext ctx, JSValue this_obj, JSValue arg_val)\", name);\r\n            this.cg.cs.AppendLine(\"{\");\r\n            this.cg.cs.AddTabLevel();\r\n        }\r\n\r\n        public virtual void Dispose()\r\n        {\r\n            this.cg.cs.DecTabLevel();\r\n            this.cg.cs.AppendLine(\"}\");\r\n        }\r\n    }\r\n\r\n    // 方法绑定\r\n    public class BindingFuncDeclareCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n\r\n        public BindingFuncDeclareCodeGen(CodeGenerator cg, Type func_decl, string name)\r\n        {\r\n            this.cg = cg;\r\n            var invoke = func_decl.GetMethod(\"Invoke\");\r\n            this.cg.cs.Append(\"public static JSValue {0}(\", name);\r\n            var parameters = invoke.GetParameters();\r\n            for (int i = 0, len = parameters.Length; i < len; ++i)\r\n            {\r\n                var p = parameters[i];\r\n                if (i != len - 1)\r\n                {\r\n                    this.cg.cs.AppendL(\"{0} {1}, \", cg.bindingManager.GetCSTypeFullName(p.ParameterType), p.Name);\r\n                }\r\n                else\r\n                {\r\n                    this.cg.cs.AppendL(\"{0} {1}\", cg.bindingManager.GetCSTypeFullName(p.ParameterType), p.Name);\r\n                }\r\n            }\r\n            this.cg.cs.AppendLineL(\")\");\r\n            // this.cg.cs.AppendLine(\"public static JSValue {0}(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\", name);\r\n            this.cg.cs.AppendLine(\"{\");\r\n            this.cg.cs.AddTabLevel();\r\n        }\r\n\r\n        public virtual void Dispose()\r\n        {\r\n            this.cg.cs.DecTabLevel();\r\n            this.cg.cs.AppendLine(\"}\");\r\n        }\r\n    }\r\n\r\n    // 构造方法绑定\r\n    public class BindingConstructorDeclareCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n\r\n        public BindingConstructorDeclareCodeGen(CodeGenerator cg, string name)\r\n        {\r\n            this.cg = cg;\r\n            this.cg.cs.AppendLine(\"public static JSValue {0}(JSContext ctx, JSValue new_target, int argc, JSValue[] argv, int magic)\", name);\r\n            this.cg.cs.AppendLine(\"{\");\r\n            this.cg.cs.AddTabLevel();\r\n        }\r\n\r\n        public virtual void Dispose()\r\n        {\r\n            this.cg.cs.DecTabLevel();\r\n            this.cg.cs.AppendLine(\"}\");\r\n        }\r\n    }\r\n\r\n    public class TryCatchGuradCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n        public TryCatchGuradCodeGen(CodeGenerator cg)\r\n        {\r\n            this.cg = cg;\r\n            this.cg.cs.AppendLine(\"try\");\r\n            this.cg.cs.AppendLine(\"{\");\r\n            this.cg.cs.AddTabLevel();\r\n        }\r\n\r\n        private string GetVarName(Type type)\r\n        {\r\n            var name = type.Name;\r\n            if (char.IsLower(name[0]))\r\n            {\r\n                return name + \"_\";\r\n            }\r\n            return char.ToLower(name[0]) + name.Substring(1);\r\n        }\r\n\r\n        private void AddCatchClause(Type exceptionType)\r\n        {\r\n            var varName = GetVarName(exceptionType);\r\n            this.cg.cs.AppendLine(\"catch ({0} {1})\", exceptionType.Name, varName);\r\n            this.cg.cs.AppendLine(\"{\");\r\n            this.cg.cs.AddTabLevel();\r\n            {\r\n                this.cg.cs.AppendLine(\"return JSNative.ThrowException(ctx, {0});\", varName);\r\n            }\r\n            this.cg.cs.DecTabLevel();\r\n            this.cg.cs.AppendLine(\"}\");\r\n        }\r\n\r\n        public virtual void Dispose()\r\n        {\r\n            this.cg.cs.DecTabLevel();\r\n            this.cg.cs.AppendLine(\"}\");\r\n            this.AddCatchClause(typeof(Exception));\r\n        }\r\n    }\r\n\r\n    public class CSEditorOnlyCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n        protected string requiredDefines;\r\n\r\n        public CSEditorOnlyCodeGen(CodeGenerator cg, IEnumerable<string> requiredDefines)\r\n        : this(cg, (string)(requiredDefines != null ? string.Join(\" && \", from def in requiredDefines select def) : null))\r\n        {\r\n        }\r\n\r\n        public CSEditorOnlyCodeGen(CodeGenerator cg, string requiredDefines)\r\n        {\r\n            this.cg = cg;\r\n            this.requiredDefines = requiredDefines;\r\n            if (!string.IsNullOrEmpty(requiredDefines))\r\n            {\r\n                cg.cs.AppendLineL(\"#if {0}\", requiredDefines);\r\n            }\r\n        }\r\n\r\n        public CSEditorOnlyCodeGen(CodeGenerator cg, bool isEditorRuntime = true)\r\n        : this(cg, isEditorRuntime ? \"UNITY_EDITOR\" : null)\r\n        {\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n            if (!string.IsNullOrEmpty(requiredDefines))\r\n            {\r\n                cg.cs.AppendLineL(\"#endif\");\r\n            }\r\n        }\r\n    }\r\n\r\n    public class CSTypeRegisterScopeCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n        protected string name;\r\n\r\n        public CSTypeRegisterScopeCodeGen(CodeGenerator cg, string name, string contextName)\r\n        {\r\n            this.cg = cg;\r\n            this.name = name;\r\n            this.cg.cs.AppendLine(\"{\");\r\n            this.cg.cs.AddTabLevel();\r\n            this.cg.cs.AppendLine(\"var {0} = {1}.CreateTypeRegister();\", name, contextName);\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n            this.cg.cs.AppendLine(\"{0}.Finish();\", name);\r\n            this.cg.cs.DecTabLevel();\r\n            this.cg.cs.AppendLine(\"}\");\r\n        }\r\n    }\r\n\r\n    public class CSPlatformCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n        protected TypeBindingFlags bf;\r\n        protected string predef;\r\n\r\n        public CSPlatformCodeGen(CodeGenerator cg, TypeBindingFlags bf)\r\n        {\r\n            this.cg = cg;\r\n            this.bf = bf;\r\n            this.predef = string.Empty;\r\n\r\n#if !JSB_UNITYLESS\r\n            if ((this.bf & TypeBindingFlags.BuildTargetPlatformOnly) != 0)\r\n            {\r\n                var buildTarget = UnityEditor.EditorUserBuildSettings.activeBuildTarget;\r\n                switch (buildTarget)\r\n                {\r\n                    case UnityEditor.BuildTarget.Android:\r\n                        predef = \"UNITY_ANDROID\";\r\n                        break;\r\n                    case UnityEditor.BuildTarget.iOS:\r\n                        predef = \"UNITY_IOS\";\r\n                        break;\r\n                    case UnityEditor.BuildTarget.WSAPlayer:\r\n                        predef = \"UNITY_WSA\"; // not supported\r\n                        break;\r\n                    case UnityEditor.BuildTarget.StandaloneWindows:\r\n                    case UnityEditor.BuildTarget.StandaloneWindows64:\r\n                        predef = \"UNITY_STANDALONE_WIN\";\r\n                        break;\r\n                    case UnityEditor.BuildTarget.StandaloneOSX:\r\n                        predef = \"UNITY_STANDALONE_OSX\";\r\n                        break;\r\n                    case UnityEditor.BuildTarget.StandaloneLinux64:\r\n                        predef = \"UNITY_STANDALONE_LINUX\";\r\n                        break;\r\n                    default:\r\n                        predef = string.Format(\"false // {0} is not supported\", buildTarget);\r\n                        break;\r\n                }\r\n            }\r\n#endif\r\n\r\n            if (!string.IsNullOrEmpty(this.predef))\r\n            {\r\n                cg.cs.AppendLineL(\"#if {0}\", this.predef);\r\n            }\r\n        }\r\n\r\n\r\n        public void Dispose()\r\n        {\r\n            if (!string.IsNullOrEmpty(predef))\r\n            {\r\n                cg.cs.AppendLineL(\"#endif\");\r\n            }\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 64721f4fe659d7c459237a7bdac240ef\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_Class.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing System.Reflection;\r\nusing QuickJS.Native;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public class ClassCodeGen : TypeCodeGen\r\n    {\r\n        private string _tsClassName;\r\n\r\n        public ClassCodeGen(CodeGenerator cg, TypeBindingInfo typeBindingInfo)\r\n        : base(cg, typeBindingInfo)\r\n        {\r\n            this.cg.AppendJSDoc(this.typeBindingInfo.type);\r\n            var transform = this.typeBindingInfo.transform;\r\n            var superBindingInfo = this.cg.bindingManager.GetSuperTypeBindingInfo(this.typeBindingInfo);\r\n            var super = superBindingInfo != null ? this.cg.currentTSModule.GetTSTypeFullName(superBindingInfo.type) : \"\";\r\n            var interfaces = this.cg.currentTSModule.GetTSInterfaceNames(this.typeBindingInfo.type);\r\n            var implements = \"\";\r\n            var jsClassType = \"\";\r\n\r\n            _tsClassName = CodeGenUtils.GetTSClassName(typeBindingInfo);\r\n            if (typeBindingInfo.type.IsInterface)\r\n            {\r\n                jsClassType = \"interface\";\r\n\r\n                if (interfaces.Length == 0)\r\n                {\r\n                    if (super.Length != 0)\r\n                    {\r\n                        implements += $\" extends {super}\";\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    implements += $\" extends {interfaces}\";\r\n\r\n                    if (super.Length != 0)\r\n                    {\r\n                        implements += $\", {super}\";\r\n                    }\r\n                }\r\n            }\r\n            else\r\n            {\r\n                jsClassType = typeBindingInfo.isAbstract ? \"abstract class\" : \"class\";\r\n\r\n                if (super.Length != 0)\r\n                {\r\n                    implements += $\" extends {super}\";\r\n                }\r\n\r\n                if (interfaces.Length != 0)\r\n                {\r\n                    implements += $\" implements {interfaces}\";\r\n                }\r\n            }\r\n\r\n            var requiredDefinesOfType = typeBindingInfo.transform.requiredDefines;\r\n            if (requiredDefinesOfType != null)\r\n            {\r\n                var defs = string.Join(\", \", from def in requiredDefinesOfType select $\"\\\"{def}\\\"\");\r\n                if (jsClassType == \"interface\")\r\n                {\r\n                    this.cg.tsDeclare.AppendLine($\"// @{this.cg.bindingManager.GetDefaultTypePrefix()}RequiredDefines({defs})\");\r\n                }\r\n                else\r\n                {\r\n                    this.cg.tsDeclare.AppendLine($\"@{this.cg.bindingManager.GetDefaultTypePrefix()}RequiredDefines({defs})\");\r\n                }\r\n            }\r\n\r\n            this.cg.tsDeclare.AppendLine($\"{jsClassType} {_tsClassName}{implements} {{\");\r\n            this.cg.tsDeclare.AddTabLevel();\r\n\r\n            // 生成函数体\r\n            // 构造函数\r\n            if (this.typeBindingInfo.constructors.available)\r\n            {\r\n                if (this.typeBindingInfo.transform.csConstructorOverride == null)\r\n                {\r\n                    using (new PInvokeGuardCodeGen(cg, typeof(Native.JSCFunctionMagic)))\r\n                    {\r\n                        using (new BindingConstructorDeclareCodeGen(cg, this.typeBindingInfo.constructors.csBindName))\r\n                        {\r\n                            using (new TryCatchGuradCodeGen(cg))\r\n                            {\r\n                                using (new ConstructorCodeGen(cg, this.typeBindingInfo))\r\n                                {\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n\r\n                using (new TSConstructorCodeGen(cg, this.typeBindingInfo, this.typeBindingInfo.constructors))\r\n                {\r\n                }\r\n            }\r\n\r\n            // 非静态成员方法\r\n            foreach (var kv in this.typeBindingInfo.methods)\r\n            {\r\n                var methodBindingInfo = kv.Value;\r\n\r\n                //TODO skip cs/tsd codegen in CSMethodCodeGen/TSMethodCodeGen/ClassMethodBindEntry for extension methods of interfaces\r\n\r\n                if (!this.typeBindingInfo.type.IsInterface || (methodBindingInfo.count > 0 && methodBindingInfo.extensionCount != methodBindingInfo.count))\r\n                {\r\n                    var jscOverride = transform.GetCSMethodOverrideBinding(methodBindingInfo.jsName);\r\n                    if (jscOverride == null)\r\n                    {\r\n                        //TODO add requiredDefines support\r\n                        using (new PInvokeGuardCodeGen(cg, typeof(QuickJS.Native.JSCFunction)))\r\n                        {\r\n                            using (new BindingFuncDeclareCodeGen(cg, typeof(QuickJS.Native.JSCFunction), methodBindingInfo.csBindName))\r\n                            {\r\n                                using (new TryCatchGuradCodeGen(cg))\r\n                                {\r\n                                    using (new CSMethodCodeGen(cg, this.typeBindingInfo, methodBindingInfo))\r\n                                    {\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n\r\n                    if (this.cg.tsDeclare.enabled)\r\n                    {\r\n                        using (new TSMethodCodeGen<MethodInfo>(cg, this.typeBindingInfo, methodBindingInfo))\r\n                        {\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            // generates extension methods of directly implemented interfaces for classes\r\n            foreach (var interfaceType in typeBindingInfo.directInterfaces)\r\n            {\r\n                var type = typeBindingInfo.bindingManager.GetExportedType(interfaceType);\r\n                if (type != null)\r\n                {\r\n                    foreach (var interfaceMethod in type.methods)\r\n                    {\r\n                        var methodBindingInfo = interfaceMethod.Value;\r\n                        if (methodBindingInfo.extensionCount > 0)\r\n                        {\r\n                            using (new PInvokeGuardCodeGen(cg, typeof(QuickJS.Native.JSCFunction)))\r\n                            {\r\n                                using (new BindingFuncDeclareCodeGen(cg, typeof(QuickJS.Native.JSCFunction), methodBindingInfo.csBindName))\r\n                                {\r\n                                    using (new TryCatchGuradCodeGen(cg))\r\n                                    {\r\n                                        using (new CSMethodCodeGen(cg, this.typeBindingInfo, methodBindingInfo))\r\n                                        {\r\n                                        }\r\n                                    }\r\n                                }\r\n                            }\r\n\r\n                            if (this.cg.tsDeclare.enabled)\r\n                            {\r\n                                using (new TSMethodCodeGen<MethodInfo>(cg, this.typeBindingInfo, methodBindingInfo))\r\n                                {\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            //TODO: C# 抽象类可以不提供方法实现, d.ts 需要补充声明\r\n            // if (this.bindingInfo.type.IsAbstract && !this.bindingInfo.type.IsInterface)\r\n            // {\r\n            // }\r\n            // 静态成员方法\r\n            if (!typeBindingInfo.type.IsGenericTypeDefinition)\r\n            {\r\n                foreach (var kv in this.typeBindingInfo.staticMethods)\r\n                {\r\n                    var methodBindingInfo = kv.Value;\r\n                    if (methodBindingInfo._cfunc != null)\r\n                    {\r\n                        continue;\r\n                    }\r\n\r\n                    var jscOverride = transform.GetCSMethodOverrideBinding(methodBindingInfo.jsName);\r\n                    if (jscOverride == null)\r\n                    {\r\n                        //TODO add requiredDefines support\r\n                        using (new PInvokeGuardCodeGen(cg, typeof(QuickJS.Native.JSCFunction)))\r\n                        {\r\n                            using (new BindingFuncDeclareCodeGen(cg, typeof(QuickJS.Native.JSCFunction), methodBindingInfo.csBindName))\r\n                            {\r\n                                using (new TryCatchGuradCodeGen(cg))\r\n                                {\r\n                                    using (new CSMethodCodeGen(cg, this.typeBindingInfo, methodBindingInfo))\r\n                                    {\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n\r\n                    if (this.cg.tsDeclare.enabled)\r\n                    {\r\n                        using (new TSMethodCodeGen<MethodInfo>(cg, typeBindingInfo, methodBindingInfo))\r\n                        {\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            if (!typeBindingInfo.type.IsGenericTypeDefinition)\r\n            {\r\n                foreach (var operatorBindingInfo in this.typeBindingInfo.operators)\r\n                {\r\n                    using (new PInvokeGuardCodeGen(cg, typeof(QuickJS.Native.JSCFunction)))\r\n                    {\r\n                        using (new BindingFuncDeclareCodeGen(cg, typeof(QuickJS.Native.JSCFunction), operatorBindingInfo.csBindName))\r\n                        {\r\n                            using (new TryCatchGuradCodeGen(cg))\r\n                            {\r\n                                using (new OperatorCodeGen(cg, this.typeBindingInfo, operatorBindingInfo))\r\n                                {\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n\r\n                    using (new TSOperatorCodeGen(cg, typeBindingInfo, operatorBindingInfo))\r\n                    {\r\n                    }\r\n                }\r\n            }\r\n\r\n            // 所有附加方法\r\n            transform.ForEachAdditionalTSMethodDeclaration(decl => this.cg.tsDeclare.AppendLine(decl));\r\n\r\n            // 所有属性\r\n            foreach (var kv in this.typeBindingInfo.properties)\r\n            {\r\n                var propertyBindingInfo = kv.Value;\r\n\r\n                // 静态\r\n                if (propertyBindingInfo.isStatic)\r\n                {\r\n                    // 可读属性\r\n                    if (propertyBindingInfo.staticPair.getterName != null)\r\n                    {\r\n                        using (new CSEditorOnlyCodeGen(cg, typeBindingInfo.GetRequiredDefines(propertyBindingInfo.propertyInfo)))\r\n                        {\r\n                            using (new PInvokeGuardCodeGen(cg, typeof(JSGetterCFunction)))\r\n                            {\r\n                                using (new BindingGetterFuncDeclareCodeGen(cg, propertyBindingInfo.staticPair.getterName))\r\n                                {\r\n                                    using (new TryCatchGuradCodeGen(cg))\r\n                                    {\r\n                                        using (new PropertyGetterCodeGen(cg, propertyBindingInfo))\r\n                                        {\r\n                                        }\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n\r\n                    // 可写属性\r\n                    if (propertyBindingInfo.staticPair.setterName != null)\r\n                    {\r\n                        using (new CSEditorOnlyCodeGen(cg, typeBindingInfo.GetRequiredDefines(propertyBindingInfo.propertyInfo)))\r\n                        {\r\n                            using (new PInvokeGuardCodeGen(cg, typeof(JSSetterCFunction)))\r\n                            {\r\n                                using (new BindingSetterFuncDeclareCodeGen(cg, propertyBindingInfo.staticPair.setterName))\r\n                                {\r\n                                    using (new TryCatchGuradCodeGen(cg))\r\n                                    {\r\n                                        using (new PropertySetterCodeGen(cg, propertyBindingInfo))\r\n                                        {\r\n                                        }\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n                else // if (propertyBindingInfo.instancePair.IsValid())\r\n                {\r\n                    // 非静态\r\n                    // 可读属性\r\n                    if (propertyBindingInfo.instancePair.getterName != null)\r\n                    {\r\n                        using (new CSEditorOnlyCodeGen(cg, typeBindingInfo.GetRequiredDefines(propertyBindingInfo.propertyInfo)))\r\n                        {\r\n                            using (new PInvokeGuardCodeGen(cg, typeof(JSGetterCFunction)))\r\n                            {\r\n                                using (new BindingGetterFuncDeclareCodeGen(cg, propertyBindingInfo.instancePair.getterName))\r\n                                {\r\n                                    using (new TryCatchGuradCodeGen(cg))\r\n                                    {\r\n                                        using (new PropertyGetterCodeGen(cg, propertyBindingInfo))\r\n                                        {\r\n                                        }\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                    // 可写属性\r\n                    if (propertyBindingInfo.instancePair.setterName != null)\r\n                    {\r\n                        using (new CSEditorOnlyCodeGen(cg, typeBindingInfo.GetRequiredDefines(propertyBindingInfo.propertyInfo)))\r\n                        {\r\n                            using (new PInvokeGuardCodeGen(cg, typeof(JSSetterCFunction)))\r\n                            {\r\n                                using (new BindingSetterFuncDeclareCodeGen(cg, propertyBindingInfo.instancePair.setterName))\r\n                                {\r\n                                    using (new TryCatchGuradCodeGen(cg))\r\n                                    {\r\n                                        using (new PropertySetterCodeGen(cg, propertyBindingInfo))\r\n                                        {\r\n                                        }\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            // 所有字段\r\n            foreach (var kv in this.typeBindingInfo.fields)\r\n            {\r\n                var fieldBindingInfo = kv.Value;\r\n\r\n                // 可读\r\n                if (fieldBindingInfo.getterName != null)\r\n                {\r\n                    using (new CSEditorOnlyCodeGen(cg, typeBindingInfo.GetRequiredDefines(fieldBindingInfo.fieldInfo)))\r\n                    {\r\n                        using (new PInvokeGuardCodeGen(cg, typeof(JSGetterCFunction)))\r\n                        {\r\n                            using (new BindingGetterFuncDeclareCodeGen(cg, fieldBindingInfo.getterName))\r\n                            {\r\n                                using (new TryCatchGuradCodeGen(cg))\r\n                                {\r\n                                    using (new FieldGetterCodeGen(cg, fieldBindingInfo))\r\n                                    {\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n\r\n                // 可写 \r\n                if (fieldBindingInfo.setterName != null)\r\n                {\r\n                    using (new CSEditorOnlyCodeGen(cg, typeBindingInfo.GetRequiredDefines(fieldBindingInfo.fieldInfo)))\r\n                    {\r\n                        using (new PInvokeGuardCodeGen(cg, typeof(JSSetterCFunction)))\r\n                        {\r\n                            using (new BindingSetterFuncDeclareCodeGen(cg, fieldBindingInfo.setterName))\r\n                            {\r\n                                using (new TryCatchGuradCodeGen(cg))\r\n                                {\r\n                                    using (new FieldSetterCodeGen(cg, fieldBindingInfo))\r\n                                    {\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            // 所有事件\r\n            foreach (var kv in this.typeBindingInfo.events)\r\n            {\r\n                var eventBindingInfo = kv.Value;\r\n                using (new PInvokeGuardCodeGen(cg, typeof(QuickJS.Native.JSCFunction)))\r\n                {\r\n                    using (new BindingFuncDeclareCodeGen(cg, typeof(QuickJS.Native.JSCFunction), eventBindingInfo.name))\r\n                    {\r\n                        using (new TryCatchGuradCodeGen(cg))\r\n                        {\r\n                            using (new EventOperationCodeGen(cg, eventBindingInfo))\r\n                            {\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            // 所有委托 (Field/Property)\r\n            foreach (var kv in this.typeBindingInfo.delegates)\r\n            {\r\n                var delegateBindingInfo = kv.Value;\r\n                using (new PInvokeGuardCodeGen(cg, typeof(QuickJS.Native.JSCFunction)))\r\n                {\r\n                    using (new BindingFuncDeclareCodeGen(cg, typeof(QuickJS.Native.JSCFunction), delegateBindingInfo.name))\r\n                    {\r\n                        using (new TryCatchGuradCodeGen(cg))\r\n                        {\r\n                            using (new DelegateOperationCodeGen(cg, delegateBindingInfo))\r\n                            {\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        public override void Dispose()\r\n        {\r\n            using (new RegFuncCodeGen(cg))\r\n            {\r\n                var transform = typeBindingInfo.transform;\r\n                var constructor = typeBindingInfo.constructors.available ? typeBindingInfo.constructors.csBindName : cg.bindingManager.GetCSTypeFullName(BindingManager.DefaultPrivateConstructor);\r\n\r\n                if (!typeBindingInfo.constructors.available && !typeBindingInfo.type.IsAbstract)\r\n                {\r\n#if !JSB_UNITYLESS\r\n                    if (typeBindingInfo.type.IsSubclassOf(typeof(UnityEngine.Component)))\r\n                    {\r\n                        // 因为 ts 泛型约束需要 new() 形式, 所以在定义中产生一个 public 定义\r\n                        // 例如: GetComponent<T extends Component>(type: { new(): T }): T\r\n                        cg.tsDeclare.AppendLine(\"/*protected*/ constructor()\");\r\n                    }\r\n                    else\r\n#endif\r\n                    {\r\n                        if (!typeBindingInfo.type.IsGenericTypeDefinition)\r\n                        {\r\n                            cg.tsDeclare.AppendLine(\"protected constructor()\");\r\n                        }\r\n                    }\r\n                }\r\n\r\n                var constructor_jscOverride = typeBindingInfo.transform.csConstructorOverride;\r\n                if (constructor_jscOverride != null)\r\n                {\r\n                    constructor = this.cg.bindingManager.GetCSTypeFullName(constructor_jscOverride.Method);\r\n                }\r\n\r\n                cg.cs.AppendLine(\"var cls = register.CreateClass(\\\"{0}\\\", typeof({1}), {2});\",\r\n                    _tsClassName,\r\n                    this.cg.bindingManager.GetCSTypeFullName(typeBindingInfo.type),\r\n                    constructor);\r\n\r\n                // 运算符\r\n                foreach (var operatorBindingInfo in typeBindingInfo.operators)\r\n                {\r\n                    var regName = operatorBindingInfo.jsName;\r\n                    var funcName = operatorBindingInfo.csBindName;\r\n                    var parameters = operatorBindingInfo.methodInfo.GetParameters();\r\n                    var declaringType = operatorBindingInfo.methodInfo.DeclaringType;\r\n\r\n                    do\r\n                    {\r\n                        if (parameters.Length == 2)\r\n                        {\r\n                            if (parameters[0].ParameterType != declaringType)\r\n                            {\r\n                                var leftType = typeBindingInfo.bindingManager.GetCSTypeFullName(parameters[0].ParameterType);\r\n                                cg.cs.AppendLine(\"cls.AddLeftOperator(\\\"{0}\\\", {1}, {2}, typeof({3}));\", regName, funcName, operatorBindingInfo.length, leftType);\r\n                                break;\r\n                            }\r\n                            else if (parameters[1].ParameterType != declaringType)\r\n                            {\r\n                                var rightType = typeBindingInfo.bindingManager.GetCSTypeFullName(parameters[1].ParameterType);\r\n                                cg.cs.AppendLine(\"cls.AddRightOperator(\\\"{0}\\\", {1}, {2}, typeof({3}));\", regName, funcName, operatorBindingInfo.length, rightType);\r\n                                break;\r\n                            }\r\n                        }\r\n\r\n                        cg.cs.AppendLine(\"cls.AddSelfOperator(\\\"{0}\\\", {1}, {2});\", regName, funcName, operatorBindingInfo.length);\r\n                    } while (false);\r\n                }\r\n\r\n                // 非静态方法\r\n                foreach (var kv in typeBindingInfo.methods)\r\n                {\r\n                    var regName = kv.Value.jsName;\r\n                    var funcName = kv.Value.csBindName;\r\n                    var jscOverride = typeBindingInfo.transform.GetCSMethodOverrideBinding(regName);\r\n                    if (jscOverride != null)\r\n                    {\r\n                        funcName = this.cg.bindingManager.GetCSTypeFullName(jscOverride.Method);\r\n                    }\r\n\r\n                    cg.cs.AppendLine(\"cls.AddMethod(false, \\\"{0}\\\", {1});\", regName, funcName);\r\n                }\r\n\r\n                // 静态方法\r\n                foreach (var kv in typeBindingInfo.staticMethods)\r\n                {\r\n                    var methodBindingInfo = kv.Value;\r\n                    var regName = methodBindingInfo.jsName;\r\n\r\n                    if (methodBindingInfo._cfunc != null)\r\n                    {\r\n                        var attr = (JSCFunctionAttribute)Attribute.GetCustomAttribute(methodBindingInfo._cfunc, typeof(JSCFunctionAttribute));\r\n                        var methodDeclType = this.cg.bindingManager.GetCSTypeFullName(methodBindingInfo._cfunc.DeclaringType);\r\n                        cg.cs.AppendLine(\"cls.AddRawMethod({0}, \\\"{1}\\\", {2}.{3});\", CodeGenUtils.ToExpression(attr.isStatic), regName, methodDeclType, methodBindingInfo._cfunc.Name);\r\n                        if (attr.difinitions != null)\r\n                        {\r\n                            foreach (var defEntry in attr.difinitions)\r\n                            {\r\n                                var prefix = attr.isStatic ? \"static \" : \"\";\r\n\r\n                                // 附带的签名没有带命名时, 自动加上\r\n                                if (defEntry.StartsWith(\"(\") || defEntry.StartsWith(\"<\"))\r\n                                {\r\n                                    this.cg.tsDeclare.AppendLine($\"{prefix}{regName}{defEntry}\");\r\n                                }\r\n                                else\r\n                                {\r\n                                    this.cg.tsDeclare.AppendLine($\"{prefix}{defEntry}\");\r\n                                }\r\n                            }\r\n                        }\r\n                        else\r\n                        {\r\n                            this.cg.tsDeclare.AppendLine(\"(...uncertain: any[]): any /* uncertain */\");\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        var funcName = methodBindingInfo.csBindName;\r\n                        var jscOverride = typeBindingInfo.transform.GetCSMethodOverrideBinding(regName);\r\n                        if (jscOverride != null)\r\n                        {\r\n                            funcName = this.cg.bindingManager.GetCSTypeFullName(jscOverride.Method);\r\n                        }\r\n\r\n                        cg.cs.AppendLine(\"cls.AddMethod(true, \\\"{0}\\\", {1});\", regName, funcName);\r\n                    }\r\n                }\r\n\r\n                // 属性\r\n                foreach (var kv in typeBindingInfo.properties)\r\n                {\r\n                    var propertyBindingInfo = kv.Value;\r\n                    if (propertyBindingInfo.staticPair.IsValid())\r\n                    {\r\n                        var tsPropertyVar = BindingManager.GetTSVariable(propertyBindingInfo.regName);\r\n                        using (new CSEditorOnlyCodeGen(cg, typeBindingInfo.GetRequiredDefines(propertyBindingInfo.propertyInfo)))\r\n                        {\r\n                            cg.cs.AppendLine(\"cls.AddProperty(true, \\\"{0}\\\", {1}, {2});\",\r\n                                tsPropertyVar,\r\n                                propertyBindingInfo.staticPair.getterName != null ? propertyBindingInfo.staticPair.getterName : \"null\",\r\n                                propertyBindingInfo.staticPair.setterName != null ? propertyBindingInfo.staticPair.setterName : \"null\");\r\n                        }\r\n                        var tsPropertyPrefix = \"static \";\r\n                        if (propertyBindingInfo.staticPair.setterName == null)\r\n                        {\r\n                            tsPropertyPrefix += \"readonly \";\r\n                        }\r\n                        var tsPropertyType = this.cg.currentTSModule.GetTSTypeFullName(propertyBindingInfo.propertyType);\r\n                        cg.AppendJSDoc(propertyBindingInfo.propertyInfo);\r\n                        cg.tsDeclare.AppendLine($\"{tsPropertyPrefix}{tsPropertyVar}: {tsPropertyType}\");\r\n                    }\r\n\r\n                    if (propertyBindingInfo.instancePair.IsValid())\r\n                    {\r\n                        var tsPropertyVar = BindingManager.GetTSVariable(propertyBindingInfo.regName);\r\n                        using (new CSEditorOnlyCodeGen(cg, typeBindingInfo.GetRequiredDefines(propertyBindingInfo.propertyInfo)))\r\n                        {\r\n                            cg.cs.AppendLine(\"cls.AddProperty(false, \\\"{0}\\\", {1}, {2});\",\r\n                                tsPropertyVar,\r\n                                propertyBindingInfo.instancePair.getterName != null ? propertyBindingInfo.instancePair.getterName : \"null\",\r\n                                propertyBindingInfo.instancePair.setterName != null ? propertyBindingInfo.instancePair.setterName : \"null\");\r\n                        }\r\n                        var tsPropertyPrefix = \"\";\r\n                        if (propertyBindingInfo.instancePair.setterName == null)\r\n                        {\r\n                            tsPropertyPrefix += \"readonly \";\r\n                        }\r\n                        var tsPropertyType = this.cg.currentTSModule.GetTSTypeFullName(propertyBindingInfo.propertyType);\r\n                        cg.AppendJSDoc(propertyBindingInfo.propertyInfo);\r\n                        cg.tsDeclare.AppendLine($\"{tsPropertyPrefix}{tsPropertyVar}: {tsPropertyType}\");\r\n                    }\r\n                }\r\n\r\n                foreach (var kv in typeBindingInfo.fields)\r\n                {\r\n                    var fieldBindingInfo = kv.Value;\r\n                    var bStatic = fieldBindingInfo.isStatic;\r\n                    var tsFieldVar = BindingManager.GetTSVariable(fieldBindingInfo.regName);\r\n                    using (new CSEditorOnlyCodeGen(cg, typeBindingInfo.GetRequiredDefines(fieldBindingInfo.fieldInfo)))\r\n                    {\r\n                        if (fieldBindingInfo.constantValue != null)\r\n                        {\r\n                            var cv = fieldBindingInfo.constantValue;\r\n                            cg.cs.AppendLine($\"cls.AddConstValue(\\\"{tsFieldVar}\\\", {cv});\");\r\n                        }\r\n                        else\r\n                        {\r\n                            cg.cs.AppendLine(\"cls.AddField({0}, \\\"{1}\\\", {2}, {3});\",\r\n                                CodeGenUtils.ToExpression(bStatic),\r\n                                tsFieldVar,\r\n                                fieldBindingInfo.getterName != null ? fieldBindingInfo.getterName : \"null\",\r\n                                fieldBindingInfo.setterName != null ? fieldBindingInfo.setterName : \"null\");\r\n                        }\r\n                    }\r\n                    var tsFieldPrefix = bStatic ? \"static \" : \"\";\r\n                    if (fieldBindingInfo.setterName == null)\r\n                    {\r\n                        tsFieldPrefix += \"readonly \";\r\n                    }\r\n                    var tsFieldType = this.cg.currentTSModule.GetTSTypeFullName(fieldBindingInfo.fieldType);\r\n                    cg.AppendJSDoc(fieldBindingInfo.fieldInfo);\r\n                    cg.tsDeclare.AppendLine($\"{tsFieldPrefix}{tsFieldVar}: {tsFieldType}\");\r\n                }\r\n\r\n                foreach (var kv in typeBindingInfo.events)\r\n                {\r\n                    var eventBindingInfo = kv.Value;\r\n                    var bStatic = eventBindingInfo.isStatic;\r\n                    var tsFieldVar = BindingManager.GetTSVariable(eventBindingInfo.regName);\r\n                    var tsFieldType = this.cg.currentTSModule.GetTSTypeFullName(eventBindingInfo.eventInfo.EventHandlerType);\r\n                    var tsFieldPrefix = \"\";\r\n                    if (bStatic)\r\n                    {\r\n                        tsFieldPrefix += \"static \";\r\n                        cg.cs.AppendLine($\"cls.AddMethod(true, \\\"{tsFieldVar}\\\", {eventBindingInfo.name});\");\r\n                    }\r\n                    else\r\n                    {\r\n                        cg.cs.AppendLine($\"cls.AddMethod(false, \\\"{tsFieldVar}\\\", {eventBindingInfo.name});\");\r\n                    }\r\n                    cg.tsDeclare.AppendLine($\"{tsFieldPrefix}{tsFieldVar}(op: \\\"add\\\" | \\\"remove\\\", fn: {tsFieldType}): void\");\r\n                }\r\n\r\n                foreach (var kv in typeBindingInfo.delegates)\r\n                {\r\n                    var delegateBindingInfo = kv.Value;\r\n                    var bStatic = delegateBindingInfo.isStatic;\r\n                    var tsFieldVar = BindingManager.GetTSVariable(delegateBindingInfo.regName);\r\n                    var tsFieldType = this.cg.currentTSModule.GetTSTypeFullName(delegateBindingInfo.delegateType);\r\n                    var tsFieldPrefix = \"\";\r\n                    if (bStatic)\r\n                    {\r\n                        tsFieldPrefix += \"static \";\r\n                        cg.cs.AppendLine($\"cls.AddMethod(true, \\\"{tsFieldVar}\\\", {delegateBindingInfo.name});\");\r\n                    }\r\n                    else\r\n                    {\r\n                        cg.cs.AppendLine($\"cls.AddMethod(false, \\\"{tsFieldVar}\\\", {delegateBindingInfo.name});\");\r\n                    }\r\n\r\n                    if (delegateBindingInfo.readable)\r\n                    {\r\n                        if (delegateBindingInfo.writable)\r\n                        {\r\n                            cg.tsDeclare.AppendLine($\"{tsFieldPrefix}{tsFieldVar}(op: \\\"get\\\"): {tsFieldType}\");\r\n                            cg.tsDeclare.AppendLine($\"{tsFieldPrefix}{tsFieldVar}(op: \\\"add\\\" | \\\"remove\\\" | \\\"set\\\", fn?: {tsFieldType}): void\");\r\n                            cg.tsDeclare.AppendLine($\"{tsFieldPrefix}{tsFieldVar}(op: \\\"add\\\" | \\\"remove\\\" | \\\"set\\\" | \\\"get\\\", fn?: {tsFieldType}): {tsFieldType} | void\");\r\n                        }\r\n                        else\r\n                        {\r\n                            cg.tsDeclare.AppendLine($\"{tsFieldPrefix}{tsFieldVar}(op: \\\"get\\\"): {tsFieldType}\");\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        cg.tsDeclare.AppendLine($\"{tsFieldPrefix}{tsFieldVar}(op: \\\"set\\\", fn: {tsFieldType})\");\r\n                    }\r\n                }\r\n\r\n                cg.cs.AppendLine(\"return cls;\");\r\n            }\r\n            base.Dispose();\r\n\r\n            this.cg.tsDeclare.DecTabLevel();\r\n            this.cg.tsDeclare.AppendLine(\"}\");\r\n        }\r\n    }\r\n}\r\n\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_Class.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: ff17c5a88714df94a97294725ccea4da\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_DelegateHotfix.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.IO;\nusing System.Reflection;\n\nnamespace QuickJS.Binding\n{\n    public class HotfixDelegateCodeGen : IDisposable\n    {\n        protected CodeGenerator cg;\n\n        private string GetSignature(HotfixDelegateBindingInfo delegateBindingInfo, int index, string arglist, out string sig)\n        {\n            sig = \"_HotfixDelegate\" + index;\n            var str = \"public delegate \";\n            str += this.cg.bindingManager.GetCSTypeFullName(delegateBindingInfo.returnType) + \" \";\n            str += sig + \"(\";\n            str += arglist;\n            str += \");\";\n            return str;\n        }\n\n        public string GetCSArglistDecl(Type self, bool isStatic, string selfName, ParameterInfo[] parameters)\n        {\n            var arglist = this.cg.bindingManager.GetCSArglistDecl(parameters);\n            var firstArgType = isStatic ? \"Type\" : \"object\";\n            var firstArg = firstArgType + \" \" + selfName;\n\n            return string.IsNullOrEmpty(arglist) ? firstArg : firstArg + \", \" + arglist;\n        }\n\n        public HotfixDelegateCodeGen(CodeGenerator cg, HotfixDelegateBindingInfo delegateBindingInfo, int index)\n        {\n            this.cg = cg;\n\n            var self_name = \"_hotfix_this\";\n            var nargs = delegateBindingInfo.parameters.Length;\n            var retName = CodeGenUtils.GetUniqueName(delegateBindingInfo.parameters, \"ret\");\n            var firstArgument = typeof(ScriptDelegate) + \" fn\";\n            var returnTypeName = this.cg.bindingManager.GetCSTypeFullName(delegateBindingInfo.returnType);\n            var delegateName = CodeGenerator.NameOfHotfixDelegates + index;\n            var arglist = GetCSArglistDecl(delegateBindingInfo.thisType, delegateBindingInfo.isStatic, self_name, delegateBindingInfo.parameters);\n            string sig;\n            var delegateSig = GetSignature(delegateBindingInfo, index, arglist, out sig);\n\n            this.cg.cs.AppendLine(delegateSig);\n            this.cg.cs.AppendLine(\"[UnityEngine.Scripting.Preserve]\");\n            this.cg.cs.AppendLine(\"[{0}(typeof({1}))]\",\n                this.cg.bindingManager.GetCSTypeFullName(typeof(JSDelegateAttribute)),\n                sig);\n            this.cg.bindingManager.Info(\"emitting delegate decl: {0}\", sig);\n            if (!string.IsNullOrEmpty(arglist))\n            {\n                arglist = \", \" + arglist;\n            }\n            this.cg.cs.AppendLine($\"public static unsafe {returnTypeName} {delegateName}({firstArgument}{arglist})\");\n            this.cg.cs.AppendLine(\"{\");\n            this.cg.cs.AddTabLevel();\n            this.cg.cs.AppendLine(\"var ctx = fn.ctx;\");\n\n            if (nargs > 0)\n            {\n                this.cg.cs.AppendLine(\"var argv = stackalloc JSValue[{0}];\", nargs);\n                for (var i = 0; i < nargs; i++)\n                {\n                    var parameter = delegateBindingInfo.parameters[i];\n                    var pusher = this.cg.AppendValuePusher(parameter.ParameterType, parameter.Name);\n                    this.cg.cs.AppendLine(\"argv[{0}] = {1};\", i, pusher);\n                    this.cg.cs.AppendLine(\"if (argv[{0}].IsException())\", i);\n                    using (this.cg.cs.CodeBlockScope())\n                    {\n                        for (var j = 0; j < i; j++)\n                        {\n                            this.cg.cs.AppendLine(\"JSApi.JS_FreeValue(ctx, argv[{0}]);\", j);\n                        }\n\n                        this.cg.cs.AppendLine(\"throw new Exception(ctx.GetExceptionString());\");\n                    }\n                }\n                this.cg.cs.AppendLine(\"var this_obj = hotfix_push_classvalue(ctx, {0});\", self_name);\n                this.cg.cs.AppendLine(\"var rval = fn.Invoke(ctx, this_obj, {0}, argv);\", nargs);\n                this.cg.cs.AppendLine(\"JSApi.JS_FreeValue(ctx, this_obj);\");\n            }\n            else\n            {\n                this.cg.cs.AppendLine(\"var this_obj = hotfix_push_classvalue(ctx, {0});\", self_name);\n                this.cg.cs.AppendLine(\"var rval = fn.Invoke(ctx, this_obj);\");\n                this.cg.cs.AppendLine(\"JSApi.JS_FreeValue(ctx, this_obj);\");\n            }\n\n            if (delegateBindingInfo.returnType != typeof(void))\n            {\n                this.cg.cs.AppendLine($\"{this.cg.bindingManager.GetCSTypeFullName(delegateBindingInfo.returnType)} {retName};\");\n                var getter = this.cg.bindingManager.GetScriptObjectGetter(delegateBindingInfo.returnType, \"ctx\", \"rval\", retName);\n                this.cg.cs.AppendLine(\"var succ = {0};\", getter);\n\n                FreeArgs(nargs);\n                CheckReturnValue();\n\n                this.cg.cs.AppendLine(\"if (succ)\");\n                using (this.cg.cs.CodeBlockScope())\n                {\n                    this.cg.cs.AppendLine($\"return {retName};\");\n                }\n                this.cg.cs.AppendLine(\"else\");\n                using (this.cg.cs.CodeBlockScope())\n                {\n                    this.cg.cs.AppendLine($\"throw new Exception(\\\"js exception caught\\\");\");\n                }\n            }\n            else\n            {\n                FreeArgs(nargs);\n                CheckReturnValue();\n            }\n        }\n\n        private void CheckReturnValue()\n        {\n            this.cg.cs.AppendLine(\"if (rval.IsException())\");\n            using (this.cg.cs.CodeBlockScope())\n            {\n                this.cg.cs.AppendLine(\"throw new Exception(ctx.GetExceptionString());\");\n            }\n            this.cg.cs.AppendLine(\"JSApi.JS_FreeValue(ctx, rval);\");\n        }\n\n        private void FreeArgs(int nargs)\n        {\n            for (var i = 0; i < nargs; i++)\n            {\n                this.cg.cs.AppendLine(\"JSApi.JS_FreeValue(ctx, argv[{0}]);\", i);\n                // this.cg.cs.AppendLine(\"argv[{0}] = JSApi.JS_UNDEFINED;\", i);\n            }\n        }\n\n        public void Dispose()\n        {\n            this.cg.cs.DecTabLevel();\n            this.cg.cs.AppendLine(\"}\");\n        }\n    }\n}\n\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_DelegateHotfix.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 3682fe278e84fc34587bc6416d957f5d\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_DelegateInvoke.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public class DelegateCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n\r\n        protected string delegateName;\r\n        protected Type returnType;\r\n        protected ParameterInfo[] parameters;\r\n        protected HashSet<Type> delegateTypeRefs;\r\n\r\n        private ParameterInfo[] GetInputParameters(ParameterInfo[] parameters)\r\n        {\r\n            // return parameters.Where(p => !p.IsOut).ToArray();\r\n            return parameters;\r\n        }\r\n\r\n        public DelegateCodeGen(CodeGenerator cg, DelegateBridgeBindingInfo delegateBindingInfo, int index)\r\n        {\r\n            this.cg = cg;\r\n            this.delegateName = CodeGenerator.NameOfDelegates + index;\r\n            this.returnType = delegateBindingInfo.returnType;\r\n            this.parameters = delegateBindingInfo.parameters;\r\n            this.delegateTypeRefs = delegateBindingInfo.types;\r\n            _Emit();\r\n        }\r\n\r\n        public DelegateCodeGen(CodeGenerator cg, string delegateName, Type returnType, ParameterInfo[] parameters)\r\n        {\r\n            this.cg = cg;\r\n            this.delegateName = delegateName;\r\n            this.returnType = returnType;\r\n            this.parameters = parameters;\r\n            this.delegateTypeRefs = null;\r\n            _Emit();\r\n        }\r\n\r\n        protected void _Emit()\r\n        {\r\n            var inputParameters = GetInputParameters(parameters);\r\n            var nargs = inputParameters.Length;\r\n            var retName = CodeGenUtils.GetUniqueName(parameters, \"ret\");\r\n            var firstArgument = typeof(ScriptDelegate) + \" fn\";\r\n            var returnTypeName = this.cg.bindingManager.GetCSTypeFullName(returnType);\r\n            var arglist = this.cg.bindingManager.GetCSArglistDecl(parameters);\r\n\r\n            if (delegateTypeRefs != null)\r\n            {\r\n                foreach (var target in delegateTypeRefs)\r\n                {\r\n                    this.cg.cs.AppendLine(\"[{0}(typeof({1}))]\",\r\n                        this.cg.bindingManager.GetCSTypeFullName(typeof(JSDelegateAttribute)),\r\n                        this.cg.bindingManager.GetCSTypeFullName(target));\r\n                    this.cg.bindingManager.Info(\"emitting delegate decl: {0}\", target);\r\n                }\r\n            }\r\n            if (!string.IsNullOrEmpty(arglist))\r\n            {\r\n                arglist = \", \" + arglist;\r\n            }\r\n            this.cg.cs.AppendLine($\"public static unsafe {returnTypeName} {delegateName}({firstArgument}{arglist})\");\r\n            this.cg.cs.AppendLine(\"{\");\r\n            this.cg.cs.AddTabLevel();\r\n            this.cg.cs.AppendLine(\"var ctx = fn.ctx;\");\r\n\r\n            if (nargs > 0)\r\n            {\r\n                var getContext = false;\r\n                this.cg.cs.AppendLine(\"var argv = stackalloc JSValue[{0}];\", nargs);\r\n                for (var i = 0; i < nargs; i++)\r\n                {\r\n                    var parameter = inputParameters[i];\r\n                    if (parameter.ParameterType.IsByRef)\r\n                    {\r\n                        if (parameter.IsOut)\r\n                        {\r\n                            var pusher = \"JSApi.JS_NewObject(ctx)\";\r\n                            this.cg.cs.AppendLine(\"argv[{0}] = {1};\", i, pusher);\r\n                            CheckParameterException(i);\r\n                        }\r\n                        else\r\n                        {\r\n                            var pusher = \"JSApi.JS_NewObject(ctx)\";\r\n                            var value_pusher = this.cg.AppendValuePusher(parameter.ParameterType, parameter.Name);\r\n                            this.cg.cs.AppendLine(\"argv[{0}] = {1};\", i, pusher);\r\n                            CheckParameterException(i);\r\n                            if (!getContext)\r\n                            {\r\n                                getContext = true;\r\n                                cg.cs.AppendLine(\"var context = ScriptEngine.GetContext(ctx);\");\r\n                            }\r\n                            cg.cs.AppendLine(\"JSApi.JS_SetProperty(ctx, argv[{0}], context.GetAtom(\\\"value\\\"), {1});\", i, value_pusher);\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        var pusher = this.cg.AppendValuePusher(parameter.ParameterType, parameter.Name);\r\n                        this.cg.cs.AppendLine(\"argv[{0}] = {1};\", i, pusher);\r\n                        CheckParameterException(i);\r\n                    }\r\n                }\r\n                this.cg.cs.AppendLine(\"var rval = fn.Invoke(ctx, {0}, argv);\", nargs);\r\n            }\r\n            else\r\n            {\r\n                this.cg.cs.AppendLine(\"var rval = fn.Invoke(ctx);\");\r\n            }\r\n\r\n            CheckReturnValue(nargs);\r\n            _WriteBackParameters(nargs, inputParameters);\r\n\r\n            if (returnType != typeof(void))\r\n            {\r\n                this.cg.cs.AppendLine($\"{this.cg.bindingManager.GetCSTypeFullName(returnType)} {retName};\");\r\n                var getter = this.cg.bindingManager.GetScriptObjectGetter(returnType, \"ctx\", \"rval\", retName);\r\n\r\n                this.cg.cs.AppendLine(\"var succ = {0};\", getter);\r\n                FreeRVal();\r\n                FreeArgs(nargs);\r\n\r\n                this.cg.cs.AppendLine(\"if (succ)\");\r\n                this.cg.cs.AppendLine(\"{\");\r\n                this.cg.cs.AddTabLevel();\r\n                this.cg.cs.AppendLine($\"return {retName};\");\r\n                this.cg.cs.DecTabLevel();\r\n                this.cg.cs.AppendLine(\"}\");\r\n                this.cg.cs.AppendLine(\"else\");\r\n                this.cg.cs.AppendLine(\"{\");\r\n                this.cg.cs.AddTabLevel();\r\n                this.cg.cs.AppendLine($\"throw new System.Exception(\\\"js exception caught\\\");\");\r\n                this.cg.cs.DecTabLevel();\r\n                this.cg.cs.AppendLine(\"}\");\r\n            }\r\n            else\r\n            {\r\n                FreeRVal();\r\n                FreeArgs(nargs);\r\n            }\r\n        }\r\n\r\n        protected void CheckParameterException(int argIndex)\r\n        {\r\n            this.cg.cs.AppendLine(\"if (argv[{0}].IsException())\", argIndex);\r\n            this.cg.cs.AppendLine(\"{\");\r\n            this.cg.cs.AddTabLevel();\r\n            for (var j = 0; j < argIndex; j++)\r\n            {\r\n                this.cg.cs.AppendLine(\"JSApi.JS_FreeValue(ctx, argv[{0}]);\", j);\r\n            }\r\n\r\n            this.cg.cs.AppendLine(\"throw new System.Exception(ctx.GetExceptionString());\");\r\n            this.cg.cs.DecTabLevel();\r\n            this.cg.cs.AppendLine(\"}\");\r\n        }\r\n\r\n        // 回填 ref/out 参数\r\n        protected void _WriteBackParameters(int nargs, ParameterInfo[] parameters)\r\n        {\r\n            for (int pIndex = 0, pCount = parameters.Length; pIndex < pCount; pIndex++)\r\n            {\r\n                var parameter = parameters[pIndex];\r\n                var pType = parameter.ParameterType;\r\n\r\n                if (!pType.IsByRef || Binding.Values.IsContextualType(pType))\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                var refValVar = $\"refVal{pIndex}\";\r\n                this.cg.cs.AppendLine(\"var {0} = Values.js_read_wrap(ctx, argv[{1}]);\", refValVar, pIndex);\r\n\r\n                this.cg.cs.AppendLine(\"if ({0}.IsException())\", refValVar);\r\n                using (this.cg.cs.CodeBlockScope())\r\n                {\r\n                    FreeRVal();\r\n                    FreeArgs(nargs);\r\n                    this.cg.cs.AppendLine(\"throw new System.Exception(ctx.GetExceptionString());\");\r\n                }\r\n\r\n                var getter = this.cg.bindingManager.GetScriptObjectGetter(pType, \"ctx\", refValVar, parameter.Name);\r\n                this.cg.cs.AppendLine(\"if (!{0})\", getter);\r\n                using (this.cg.cs.CodeBlockScope())\r\n                {\r\n                    var argTypeStr = this.cg.bindingManager.GetCSTypeFullName(parameter.ParameterType);\r\n\r\n                    FreeRVal();\r\n                    FreeArgs(nargs);\r\n                    this.cg.cs.AppendLine(\"JSApi.JS_FreeValue(ctx, {0});\", refValVar);\r\n                    this.cg.WriteParameterException(CodeGenerator.NameOfDelegates, delegateName, argTypeStr, pIndex);\r\n                }\r\n                this.cg.cs.AppendLine(\"JSApi.JS_FreeValue(ctx, {0});\", refValVar);\r\n            }\r\n        }\r\n\r\n        private void CheckReturnValue(int nargs)\r\n        {\r\n            this.cg.cs.AppendLine(\"if (rval.IsException())\");\r\n            this.cg.cs.AppendLine(\"{\");\r\n            this.cg.cs.AddTabLevel();\r\n            FreeArgs(nargs);\r\n            this.cg.cs.AppendLine(\"throw new System.Exception(ctx.GetExceptionString());\");\r\n            this.cg.cs.DecTabLevel();\r\n            this.cg.cs.AppendLine(\"}\");\r\n        }\r\n\r\n        private void FreeRVal()\r\n        {\r\n            this.cg.cs.AppendLine(\"JSApi.JS_FreeValue(ctx, rval);\");\r\n        }\r\n\r\n        private void FreeArgs(int nargs)\r\n        {\r\n            for (var i = 0; i < nargs; i++)\r\n            {\r\n                this.cg.cs.AppendLine(\"JSApi.JS_FreeValue(ctx, argv[{0}]);\", i);\r\n                // this.cg.cs.AppendLine(\"argv[{0}] = JSApi.JS_UNDEFINED;\", i);\r\n            }\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n            this.cg.cs.DecTabLevel();\r\n            this.cg.cs.AppendLine(\"}\");\r\n        }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_DelegateInvoke.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: cc2fb77ac8feede4db4ee4b57c262a5f\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_DelegateOperation.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.IO;\nusing System.Reflection;\n\nnamespace QuickJS.Binding\n{\n    public class DelegateOperationCodeGen : IDisposable\n    {\n        protected CodeGenerator cg;\n        protected DelegateBindingInfo bindingInfo;\n\n        public DelegateOperationCodeGen(CodeGenerator cg, DelegateBindingInfo bindingInfo)\n        {\n            this.cg = cg;\n            this.bindingInfo = bindingInfo;\n\n            this.cg.cs.AppendLine(\"var op = Values.js_parse_event_op(ctx, argv[0]);\");\n            var caller = this.cg.AppendGetThisCS(bindingInfo);\n            var eventTypeName = this.cg.bindingManager.GetCSTypeFullName(bindingInfo.delegateType);\n\n            this.cg.cs.AppendLine(\"switch(op)\");\n            using (this.cg.cs.CodeBlockScope())\n            {\n                if (this.bindingInfo.writable)\n                {\n                    if (this.bindingInfo.readable)\n                    {\n                        this.cg.cs.AppendLine(\"case Values.EVT_OP_ADD:\");\n                        using (this.cg.cs.CodeBlockScope())\n                        {\n                            this.cg.cs.AppendLine(\"{0} value;\", eventTypeName);\n                            var getter = this.cg.bindingManager.GetScriptObjectGetter(bindingInfo.delegateType, \"ctx\", \"argv[1]\", \"value\");\n                            this.cg.cs.AppendLine(\"if (!{0})\", getter);\n                            using (this.cg.cs.CodeBlockScope())\n                            {\n                                this.cg.WriteParameterException(bindingInfo.declaringType, bindingInfo.csName, eventTypeName, 1);\n                            }\n                            this.cg.cs.AppendLine(\"{0}.{1} += value;\", caller, bindingInfo.csName);\n                            this.cg.cs.AppendLine(\"return JSApi.JS_UNDEFINED;\");\n                        }\n                        this.cg.cs.AppendLine(\"case Values.EVT_OP_REMOVE:\");\n                        using (this.cg.cs.CodeBlockScope())\n                        {\n                            this.cg.cs.AppendLine(\"{0} value;\", eventTypeName);\n                            var getter = this.cg.bindingManager.GetScriptObjectGetter(bindingInfo.delegateType, \"ctx\", \"argv[1]\", \"value\");\n                            this.cg.cs.AppendLine(\"if (!{0})\", getter);\n                            using (this.cg.cs.CodeBlockScope())\n                            {\n                                this.cg.WriteParameterException(bindingInfo.declaringType, bindingInfo.csName, eventTypeName, 1);\n                            }\n                            this.cg.cs.AppendLine(\"{0}.{1} -= value;\", caller, bindingInfo.csName);\n                            this.cg.cs.AppendLine(\"return JSApi.JS_UNDEFINED;\");\n                        }\n                    }\n                    this.cg.cs.AppendLine(\"case Values.EVT_OP_SET:\");\n                    using (this.cg.cs.CodeBlockScope())\n                    {\n                        this.cg.cs.AppendLine(\"{0} value;\", eventTypeName);\n                        var getter = this.cg.bindingManager.GetScriptObjectGetter(bindingInfo.delegateType, \"ctx\", \"argv[1]\", \"value\");\n                        this.cg.cs.AppendLine(\"if (!{0})\", getter);\n                        using (this.cg.cs.CodeBlockScope())\n                        {\n                            this.cg.WriteParameterException(bindingInfo.declaringType, bindingInfo.csName, eventTypeName, 1);\n                        }\n                        this.cg.cs.AppendLine(\"{0}.{1} = value;\", caller, bindingInfo.csName);\n                        this.cg.cs.AppendLine(\"return JSApi.JS_UNDEFINED;\");\n                    }\n                }\n                if (this.bindingInfo.readable)\n                {\n                    this.cg.cs.AppendLine(\"case Values.EVT_OP_GET:\");\n                    using (this.cg.cs.CodeBlockScope())\n                    {\n                        this.cg.cs.AppendLine(\"var ret = {0}.{1};\", caller, bindingInfo.csName);\n                        var pusher = this.cg.AppendValuePusher(bindingInfo.delegateType, \"ret\");\n                        this.cg.cs.AppendLine(\"return {0};\", pusher);\n                    }\n                }\n                this.cg.cs.AppendLine(\"default: throw new JSException(\\\"invalid event op\\\");\");\n            }\n        }\n\n        public virtual void Dispose()\n        {\n        }\n    }\n}\n\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_DelegateOperation.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: e9067139ac30e59468ccfc8599edaa2c\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_DelegateWrapper.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing System.IO;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public class DelegateWrapperCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n\r\n        public DelegateWrapperCodeGen(CodeGenerator cg)\r\n        {\r\n            this.cg = cg;\r\n            this.cg.cs.AppendLine(\"[{0}]\", typeof(JSBindingAttribute).Name);\r\n            // this.cg.cs.AppendLine(\"[UnityEngine.Scripting.Preserve]\");\r\n            this.cg.cs.AppendLine(\"public class {0} : {1}\", CodeGenerator.NameOfDelegates, typeof(Binding.Values).Name);\r\n            this.cg.cs.AppendLine(\"{\");\r\n            this.cg.cs.AddTabLevel();\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n            using (new RuntimeRegFuncCodeGen(cg))\r\n            {\r\n                this.cg.cs.AppendLine(\"var type = typeof({0});\", CodeGenerator.NameOfDelegates);\r\n                this.cg.cs.AppendLine(\"var typeDB = runtime.GetTypeDB();\");\r\n                this.cg.cs.AppendLine(\"var methods = type.GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);\");\r\n                this.cg.cs.AppendLine(\"for (int i = 0, size = methods.Length; i < size; i++)\");\r\n                using (this.cg.cs.CodeBlockScope())\r\n                {\r\n                    this.cg.cs.AppendLine(\"var method = methods[i];\");\r\n                    this.cg.cs.AppendLine(\"var attributes = method.GetCustomAttributes(typeof(JSDelegateAttribute), false);\");\r\n                    this.cg.cs.AppendLine(\"var attributesLength = attributes.Length;\");\r\n                    this.cg.cs.AppendLine(\"if (attributesLength > 0)\");\r\n                    using (this.cg.cs.CodeBlockScope())\r\n                    {\r\n                        this.cg.cs.AppendLine(\"for (var a = 0; a < attributesLength; a++)\");\r\n                        using (this.cg.cs.CodeBlockScope())\r\n                        {\r\n                            this.cg.cs.AppendLine(\"var attribute = attributes[a] as JSDelegateAttribute;\");\r\n                            this.cg.cs.AppendLine(\"typeDB.AddDelegate(attribute.target, method);\");\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            this.cg.cs.DecTabLevel();\r\n            this.cg.cs.AppendLine(\"}\");\r\n        }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_DelegateWrapper.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 9777db33d2236884a9acdb2f29dd7db0\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_Enum.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing System.IO;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public class EnumCodeGen : TypeCodeGen\r\n    {\r\n        private string _tsClassName;\r\n\r\n        public EnumCodeGen(CodeGenerator cg, TypeBindingInfo type)\r\n        : base(cg, type)\r\n        {\r\n            _tsClassName = CodeGenUtils.GetTSClassName(typeBindingInfo);\r\n\r\n            this.cg.AppendJSDoc(type.type);\r\n            this.cg.tsDeclare.AppendLine(\"enum {0} {{\", _tsClassName);\r\n            this.cg.tsDeclare.AddTabLevel();\r\n        }\r\n\r\n        public override void Dispose()\r\n        {\r\n            using (new RegFuncCodeGen(cg))\r\n            {\r\n                this.cg.cs.AppendLine(\"var cls = register.CreateEnum(\\\"{0}\\\", typeof({1}));\",\r\n                    _tsClassName,\r\n                    this.cg.bindingManager.GetCSTypeFullName(typeBindingInfo.type));\r\n                var values = new Dictionary<string, object>();\r\n                foreach (var name in Enum.GetNames(typeBindingInfo.type))\r\n                {\r\n                    if (!typeBindingInfo.transform.Filter(name))\r\n                    {\r\n                        values[name] = Enum.Parse(typeBindingInfo.type, name);\r\n                    }\r\n                }\r\n                foreach (var kv in values)\r\n                {\r\n                    var name = kv.Key;\r\n                    var value = kv.Value;\r\n                    var pvalue = Convert.ToInt32(value);\r\n                    this.cg.cs.AppendLine($\"cls.AddConstValue(\\\"{name}\\\", {pvalue});\");\r\n                    this.cg.AppendEnumJSDoc(typeBindingInfo.type, value);\r\n                    this.cg.tsDeclare.AppendLine($\"{name} = {pvalue},\");\r\n                }\r\n                this.cg.cs.AppendLine(\"return cls;\");\r\n            }\r\n            base.Dispose();\r\n            this.cg.tsDeclare.DecTabLevel();\r\n            this.cg.tsDeclare.AppendLine(\"}\");\r\n        }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_Enum.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 1f73f8604ea67c24ba833a09112b0129\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_Event.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.IO;\nusing System.Reflection;\n\nnamespace QuickJS.Binding\n{\n    public class EventOperationCodeGen : IDisposable\n    {\n        protected CodeGenerator cg;\n        protected EventBindingInfo bindingInfo;\n\n        public EventOperationCodeGen(CodeGenerator cg, EventBindingInfo bindingInfo)\n        {\n            this.cg = cg;\n            this.bindingInfo = bindingInfo;\n\n            var eventInfo = this.bindingInfo.eventInfo;\n            var declaringType = eventInfo.DeclaringType;\n\n            this.cg.cs.AppendLine(\"var op = Values.js_parse_event_op(ctx, argv[0]);\");\n            var caller = this.cg.AppendGetThisCS(bindingInfo);\n            var eventTypeName = this.cg.bindingManager.GetCSTypeFullName(eventInfo.EventHandlerType);\n            this.cg.cs.AppendLine(\"{0} value;\", eventTypeName);\n            this.cg.cs.AppendLine(\"switch(op)\");\n            using (this.cg.cs.CodeBlockScope())\n            {\n                this.cg.cs.AppendLine(\"case Values.EVT_OP_ADD:\");\n                using (this.cg.cs.IndentBlockScope())\n                {\n                    var getter = this.cg.bindingManager.GetScriptObjectGetter(eventInfo.EventHandlerType, \"ctx\", \"argv[1]\", \"value\");\n                    this.cg.cs.AppendLine(\"if (!{0})\", getter);\n                    using (this.cg.cs.CodeBlockScope())\n                    {\n                        this.cg.WriteParameterException(declaringType, eventInfo.Name, eventTypeName, 1);\n                    }\n                    this.cg.cs.AppendLine(\"{0}.{1} += value;\", caller, BindingManager.GetCSVariable(eventInfo.Name));\n                    this.cg.cs.AppendLine(\"break;\");\n                }\n                this.cg.cs.AppendLine(\"case Values.EVT_OP_REMOVE:\");\n                using (this.cg.cs.IndentBlockScope())\n                {\n                    var getter = this.cg.bindingManager.GetScriptObjectGetter(eventInfo.EventHandlerType, \"ctx\", \"argv[1]\", \"value\");\n                    this.cg.cs.AppendLine(\"if (!{0})\", getter);\n                    using (this.cg.cs.CodeBlockScope())\n                    {\n                        this.cg.WriteParameterException(declaringType, eventInfo.Name, eventTypeName, 1);\n                    }\n                    this.cg.cs.AppendLine(\"{0}.{1} -= value;\", caller, BindingManager.GetCSVariable(eventInfo.Name));\n                    this.cg.cs.AppendLine(\"break;\");\n                }\n                this.cg.cs.AppendLine(\"default: throw new JSException(\\\"invalid event op\\\");\");\n            }\n            if (declaringType.IsValueType && !eventInfo.GetAddMethod().IsStatic)\n            {\n                // 非静态结构体属性修改, 尝试替换实例\n                var js_rebind_this = this.cg.bindingManager.GetRebindOperation(bindingInfo.declaringType);\n                this.cg.cs.AppendLine($\"{js_rebind_this}(ctx, this_obj, ref {caller});\");\n            }\n            this.cg.cs.AppendLine(\"return JSApi.JS_UNDEFINED;\");\n        }\n\n        public virtual void Dispose()\n        {\n        }\n    }\n}\n\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_Event.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 5684fc9a5670ec54f8976ee1ff09640f\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_Field.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.IO;\nusing System.Reflection;\n\nnamespace QuickJS.Binding\n{\n    public class FieldGetterCodeGen : IDisposable\n    {\n        protected CodeGenerator cg;\n        protected FieldBindingInfo bindingInfo;\n\n        public FieldGetterCodeGen(CodeGenerator cg, FieldBindingInfo bindingInfo)\n        {\n            this.cg = cg;\n            this.bindingInfo = bindingInfo;\n\n            var caller = this.cg.AppendGetThisCS(bindingInfo);\n\n            this.cg.cs.AppendLine(\"var ret = {0}.{1};\", caller, BindingManager.GetCSVariable(bindingInfo.fieldInfo.Name));\n            var pusher = this.cg.AppendValuePusher(bindingInfo.fieldType, \"ret\");\n            this.cg.cs.AppendLine(\"return {0};\", pusher);\n        }\n\n        public virtual void Dispose()\n        {\n        }\n    }\n\n    public class FieldSetterCodeGen : IDisposable\n    {\n        protected CodeGenerator cg;\n        protected FieldBindingInfo bindingInfo;\n\n        public FieldSetterCodeGen(CodeGenerator cg, FieldBindingInfo bindingInfo)\n        {\n            this.cg = cg;\n            this.bindingInfo = bindingInfo;\n\n            var caller = this.cg.AppendGetThisCS(bindingInfo);\n            var fieldInfo = bindingInfo.fieldInfo;\n            var declaringType = fieldInfo.DeclaringType;\n            var fieldTypeName = this.cg.bindingManager.GetCSTypeFullName(fieldInfo.FieldType);\n            this.cg.cs.AppendLine(\"{0} value;\", fieldTypeName);\n            var getter = this.cg.bindingManager.GetScriptObjectGetter(fieldInfo.FieldType, \"ctx\", \"arg_val\", \"value\");\n            this.cg.cs.AppendLine(\"if (!{0})\", getter);\n            using (this.cg.cs.CodeBlockScope())\n            {\n                this.cg.WriteParameterException(declaringType, fieldInfo.Name, fieldTypeName, 0);\n            }\n            this.cg.cs.AppendLine(\"{0}.{1} = value;\", caller, BindingManager.GetCSVariable(fieldInfo.Name));\n            if (declaringType.IsValueType && !fieldInfo.IsStatic)\n            {\n                // 非静态结构体字段修改, 尝试替换实例\n                var js_rebind_this = this.cg.bindingManager.GetRebindOperation(declaringType);\n                this.cg.cs.AppendLine($\"{js_rebind_this}(ctx, this_obj, ref {caller});\");\n            }\n            this.cg.cs.AppendLine(\"return JSApi.JS_UNDEFINED;\");\n        }\n\n        public virtual void Dispose()\n        {\n        }\n    }\n}\n\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_Field.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: f5be9d52ad420b54fa791dca9c427d8d\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_Method.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public abstract class MethodBaseCodeGen<T> : IDisposable\r\n    where T : MethodBase\r\n    {\r\n        protected CodeGenerator cg;\r\n\r\n        // 方法参数数比较, 用于列表排序\r\n        public static int MethodComparer(T a, T b)\r\n        {\r\n            var va = a.GetParameters().Length;\r\n            var vb = b.GetParameters().Length;\r\n            return va > vb ? 1 : ((va == vb) ? 0 : -1);\r\n        }\r\n\r\n        public MethodBaseCodeGen(CodeGenerator cg)\r\n        {\r\n            this.cg = cg;\r\n        }\r\n\r\n        protected virtual void OnBegin()\r\n        {\r\n        }\r\n\r\n        public virtual void Dispose()\r\n        {\r\n        }\r\n\r\n        protected virtual IEnumerable<string> GetRequiredDefines(MethodBase methodBase)\r\n        {\r\n            return null;\r\n        }\r\n\r\n        public string GetParamArrayMatchType(T method)\r\n        {\r\n            var parameters = method.GetParameters();\r\n            var parameter = parameters[parameters.Length - 1];\r\n            var typename = this.cg.bindingManager.GetCSTypeFullName(parameter.ParameterType.GetElementType());\r\n            return $\"typeof({typename})\";\r\n        }\r\n\r\n        // 生成定参部分 type 列表 (首参前也会补\",\")\r\n        public string GetFixedMatchTypes(T method, bool isVararg, bool isExtension)\r\n        {\r\n            var snippet = \"\";\r\n            var parameters = method.GetParameters();\r\n            var pIndex = isExtension ? 1 : 0;\r\n            var length = isVararg ? parameters.Length - 1 : parameters.Length;\r\n            var argIndex = 0;\r\n\r\n            for (; pIndex < length; pIndex++)\r\n            {\r\n                var parameter = parameters[pIndex];\r\n                var typename = this.cg.bindingManager.GetCSTypeFullName(parameter.ParameterType);\r\n\r\n                if (parameter.ParameterType.IsByRef)\r\n                {\r\n                    snippet += $\"Values.js_match_type_hint(ctx, argv[{argIndex}], typeof({typename}))\";\r\n                }\r\n                else\r\n                {\r\n                    snippet += $\"Values.js_match_type(ctx, argv[{argIndex}], typeof({typename}))\";\r\n                }\r\n\r\n                if (pIndex != length - 1)\r\n                {\r\n                    snippet += \" && \";\r\n                }\r\n\r\n                argIndex++;\r\n            }\r\n\r\n            return snippet;\r\n        }\r\n\r\n        public string Concat(List<string> args, string sp = \", \")\r\n        {\r\n            var len = args.Count;\r\n            var res = \"\";\r\n            for (var i = 0; i < len; i++)\r\n            {\r\n                res += args[i];\r\n                if (i != len - 1)\r\n                {\r\n                    res += sp;\r\n                }\r\n            }\r\n\r\n            return res;\r\n        }\r\n\r\n        // hasParams: 是否包含变参 (最后一个参数将按数组处理)\r\n        public List<string> AppendGetParameters(bool hasParams, string nargs, MethodBase methodBase, ParameterInfo[] parameters)\r\n        {\r\n            var arglist = new List<string>();\r\n            var assignIndex = 0;\r\n            for (var i = 0; i < parameters.Length; i++)\r\n            {\r\n                var argitem = \"\";\r\n                var parameter = parameters[i];\r\n                if (parameter.ParameterType.IsByRef)\r\n                {\r\n                    if (parameter.IsOut)\r\n                    {\r\n                        argitem += \"out \";\r\n                    }\r\n                    else if (parameter.IsIn)\r\n                    {\r\n                        argitem += \"in \";\r\n                    }\r\n                    else\r\n                    {\r\n                        argitem += \"ref \";\r\n                    }\r\n                }\r\n                argitem += \"arg\" + i;\r\n                arglist.Add(argitem);\r\n                if (hasParams && i == parameters.Length - 1)\r\n                {\r\n                    // 处理数组\r\n                    var argType = this.cg.bindingManager.GetCSTypeFullName(parameter.ParameterType);\r\n                    var argElementType = this.cg.bindingManager.GetCSTypeFullName(parameter.ParameterType.GetElementType());\r\n                    var argElementIndex = i == 0 ? nargs : nargs + \" - \" + i;\r\n                    this.cg.cs.AppendLine($\"{argType} arg{i} = null;\");\r\n                    this.cg.cs.AppendLine($\"if ({argElementIndex} > 0)\");\r\n                    using (this.cg.cs.CodeBlockScope())\r\n                    {\r\n                        this.cg.cs.AppendLine($\"arg{i} = new {argElementType}[{argElementIndex}];\");\r\n                        this.cg.cs.AppendLine($\"for (var i = {i}; i < {nargs}; i++)\");\r\n                        using (this.cg.cs.CodeBlockScope())\r\n                        {\r\n                            var argElementOffset = i == 0 ? \"\" : \" - \" + i;\r\n                            var argName = $\"arg{i}[i{argElementOffset}]\";\r\n                            var argGetter = this.cg.bindingManager.GetScriptObjectGetter(parameter.ParameterType.GetElementType(), \"ctx\", \"argv[i]\", argName);\r\n                            this.cg.cs.AppendLine(\"{0};\", argGetter);\r\n                        }\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    if (this.cg.WriteParameterGetter(parameter, assignIndex, $\"arg{i}\", methodBase))\r\n                    {\r\n                        assignIndex++;\r\n                    }\r\n                }\r\n            }\r\n            return arglist;\r\n        }\r\n\r\n        protected virtual void InvokeVoidReturn()\r\n        {\r\n            cg.cs.AppendLine(\"return JSApi.JS_UNDEFINED;\");\r\n        }\r\n\r\n        // 输出所有变体绑定\r\n        protected void WriteCSAllVariants(TypeBindingInfo typeBindingInfo, MethodBaseBindingInfo<T> methodBindingInfo) // SortedDictionary<int, MethodBaseVariant<T>> variants)\r\n        {\r\n            var transform = typeBindingInfo.transform;\r\n            var variants = methodBindingInfo.variants;\r\n            var prefs = cg.bindingManager.prefs;\r\n\r\n            if (prefs.alwaysCheckArgc || /*hasOverrides*/ methodBindingInfo.count > 1)\r\n            {\r\n                // 需要处理重载\r\n                GenMethodVariants(methodBindingInfo, variants);\r\n            }\r\n            else\r\n            {\r\n                // 没有重载的情况 (variants.Count == 1)\r\n                foreach (var variantKV in variants)\r\n                {\r\n                    var args = variantKV.Key;\r\n                    var variant = variantKV.Value;\r\n                    var argc = cg.AppendGetArgCount(variant.isVararg);\r\n\r\n                    if (variant.isVararg)\r\n                    {\r\n                        var method = variant.varargMethods[0];\r\n\r\n                        using (new CSEditorOnlyCodeGen(cg, GetRequiredDefines(method.method)))\r\n                        {\r\n                            WriteCSBindingMethodBody(methodBindingInfo, method.method, argc, true, method.isExtension);\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        var method = variant.plainMethods[0];\r\n\r\n                        using (new CSEditorOnlyCodeGen(cg, GetRequiredDefines(method.method)))\r\n                        {\r\n                            WriteCSBindingMethodBody(methodBindingInfo, method.method, argc, false, method.isExtension);\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        protected void WriteTSAllVariants(TypeBindingInfo typeBindingInfo, MethodBaseBindingInfo<T> bindingInfo)\r\n        {\r\n            var variants = bindingInfo.variants;\r\n            //NOTE: 如果产生了无法在 typescript 中声明的方法, 则作标记, 并输出一条万能声明 \r\n            //      [key: string]: any\r\n            foreach (var variantKV in variants)\r\n            {\r\n                foreach (var method in variantKV.Value.plainMethods)\r\n                {\r\n                    WriteTSDeclaration(typeBindingInfo, method.method, bindingInfo, method.isExtension);\r\n                }\r\n\r\n                foreach (var method in variantKV.Value.varargMethods)\r\n                {\r\n                    WriteTSDeclaration(typeBindingInfo, method.method, bindingInfo, method.isExtension);\r\n                }\r\n            }\r\n        }\r\n\r\n        // 写入返回类型声明\r\n        protected virtual void WriteTSReturn(T method, List<ParameterInfo> returnParameters)\r\n        {\r\n            var returnType = GetReturnType(method);\r\n            var outParametersCount = returnParameters.Count;\r\n            if (returnType != null && returnType != typeof(void))\r\n            {\r\n                if (outParametersCount != 0)\r\n                {\r\n                    this.cg.tsDeclare.AppendL(\": { \");\r\n\r\n                    var returnTypeTS = this.cg.currentTSModule.GetTSTypeFullName(returnType);\r\n                    var returnVarName = BindingManager.GetTSVariable(\"return\");\r\n                    this.cg.tsDeclare.AppendL($\"\\\"{returnVarName}\\\": {returnTypeTS}\");\r\n\r\n                    for (var i = 0; i < outParametersCount; i++)\r\n                    {\r\n                        var rp = returnParameters[i];\r\n                        var name = BindingManager.GetTSVariable(rp.Name);\r\n                        var ts = this.cg.currentTSModule.GetTSTypeFullName(rp.ParameterType);\r\n                        if (i != outParametersCount - 1)\r\n                        {\r\n                            this.cg.tsDeclare.AppendL($\", \\\"{name}\\\": {ts}\");\r\n                        }\r\n                        else\r\n                        {\r\n                            this.cg.tsDeclare.AppendL($\", \\\"{name}\\\": {ts}\");\r\n                        }\r\n                    }\r\n                    this.cg.tsDeclare.AppendL(\" }\");\r\n                    this.cg.tsDeclare.AppendLine();\r\n                }\r\n                else\r\n                {\r\n                    var returnTypeTS = this.cg.currentTSModule.GetTSTypeFullName(returnType);\r\n                    this.cg.tsDeclare.AppendL($\": {returnTypeTS}\");\r\n                    this.cg.tsDeclare.AppendLine();\r\n                }\r\n            }\r\n            else\r\n            {\r\n                if (outParametersCount != 0)\r\n                {\r\n                    this.cg.tsDeclare.AppendL(\": { \");\r\n                    for (var i = 0; i < outParametersCount; i++)\r\n                    {\r\n                        var rp = returnParameters[i];\r\n                        var name = rp.Name;\r\n                        var ts = this.cg.currentTSModule.GetTSTypeFullName(rp.ParameterType);\r\n                        if (i != outParametersCount - 1)\r\n                        {\r\n                            this.cg.tsDeclare.AppendL($\"\\\"{name}\\\": {ts}, \");\r\n                        }\r\n                        else\r\n                        {\r\n                            this.cg.tsDeclare.AppendL($\"\\\"{name}\\\": {ts}\");\r\n                        }\r\n                    }\r\n                    this.cg.tsDeclare.AppendL(\" }\");\r\n                    this.cg.tsDeclare.AppendLine();\r\n                }\r\n                else\r\n                {\r\n                    if (method.IsConstructor)\r\n                    {\r\n                        this.cg.tsDeclare.AppendLine();\r\n                    }\r\n                    else\r\n                    {\r\n                        this.cg.tsDeclare.AppendL(\": void\");\r\n                        this.cg.tsDeclare.AppendLine();\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        protected void GenMethodVariants(MethodBaseBindingInfo<T> methodBindingInfo, SortedDictionary<int, MethodBaseVariant<T>> variants)\r\n        {\r\n            var argc = cg.AppendGetArgCount(true);\r\n            using (cg.cs.DoWhileBlockScope(methodBindingInfo.count > 1))\r\n            {\r\n                foreach (var variantKV in variants)\r\n                {\r\n                    var expectedArgCount = variantKV.Key;\r\n                    var variant = variantKV.Value;\r\n                    var gecheck = expectedArgCount > 0 && variant.isVararg; // 最后一组分支且存在变参时才需要判断 >= \r\n\r\n                    if (gecheck)\r\n                    {\r\n                        cg.cs.AppendLine(\"if (argc >= {0})\", expectedArgCount);\r\n                        cg.cs.AppendLine(\"{\");\r\n                        cg.cs.AddTabLevel();\r\n                    }\r\n\r\n                    // 处理定参\r\n                    if (variant.plainMethods.Count > 0)\r\n                    {\r\n                        cg.cs.AppendLine(\"if (argc == {0})\", expectedArgCount);\r\n                        using (cg.cs.CodeBlockScope())\r\n                        {\r\n                            var prefs = cg.bindingManager.prefs;\r\n                            if (prefs.alwaysCheckArgType || (variant.plainMethods.Count + variant.varargMethods.Count) > 1)\r\n                            {\r\n                                foreach (var method in variant.plainMethods)\r\n                                {\r\n                                    using (new CSEditorOnlyCodeGen(cg, GetRequiredDefines(method.method)))\r\n                                    {\r\n                                        var fixedMatchers = GetFixedMatchTypes(method.method, false, method.isExtension);\r\n                                        if (fixedMatchers.Length != 0)\r\n                                        {\r\n                                            cg.cs.AppendLine($\"if ({fixedMatchers})\");\r\n                                            using (cg.cs.CodeBlockScope())\r\n                                            {\r\n                                                this.WriteCSBindingMethodBody(methodBindingInfo, method.method, argc, false, method.isExtension);\r\n                                            }\r\n                                        }\r\n                                        else\r\n                                        {\r\n                                            this.WriteCSBindingMethodBody(methodBindingInfo, method.method, argc, false, method.isExtension);\r\n                                        }\r\n                                    }\r\n                                }\r\n\r\n                                // if (methodBindingInfo.count > 1 && expectedArgCount != 0)\r\n                                // {\r\n                                //     cg.cs.AppendLine(\"break;\");\r\n                                // }\r\n                            }\r\n                            else\r\n                            {\r\n                                // 只有一个定参方法时, 不再判定类型匹配\r\n                                var method = variant.plainMethods[0];\r\n                                using (new CSEditorOnlyCodeGen(cg, GetRequiredDefines(method.method)))\r\n                                {\r\n                                    this.WriteCSBindingMethodBody(methodBindingInfo, method.method, argc, false, method.isExtension);\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n\r\n                    // 处理变参\r\n                    if (variant.varargMethods.Count > 0)\r\n                    {\r\n                        foreach (var method in variant.varargMethods)\r\n                        {\r\n                            using (new CSEditorOnlyCodeGen(cg, GetRequiredDefines(method.method)))\r\n                            {\r\n                                var fixedMatchers = GetFixedMatchTypes(method.method, true, method.isExtension);\r\n                                var variantMatchers = GetParamArrayMatchType(method.method);\r\n\r\n                                if (fixedMatchers.Length > 0)\r\n                                {\r\n                                    cg.cs.AppendLine($\"if ({fixedMatchers} && Values.js_match_param_types(ctx, {expectedArgCount}, argv, {variantMatchers}))\");\r\n                                }\r\n                                else\r\n                                {\r\n                                    cg.cs.AppendLine($\"if (Values.js_match_param_types(ctx, {expectedArgCount}, argv, {variantMatchers}))\");\r\n                                }\r\n\r\n                                using (cg.cs.CodeBlockScope())\r\n                                {\r\n                                    this.WriteCSBindingMethodBody(methodBindingInfo, method.method, argc, true, method.isExtension);\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n\r\n                    if (gecheck)\r\n                    {\r\n                        cg.cs.DecTabLevel();\r\n                        cg.cs.AppendLine(\"}\");\r\n                    }\r\n                }\r\n            }\r\n\r\n            cg.cs.AppendLine($\"throw new NoSuitableMethodException(\\\"{methodBindingInfo.jsName}\\\", {argc});\");\r\n        }\r\n\r\n        protected List<ParameterInfo> WriteTSDeclaration(TypeBindingInfo typeBindingInfo, T method, MethodBaseBindingInfo<T> bindingInfo, bool isExtension)\r\n        {\r\n            var refParameters = new List<ParameterInfo>();\r\n            string tsMethodDeclaration;\r\n            this.cg.AppendJSDoc(method);\r\n\r\n            if (typeBindingInfo.transform.GetTSMethodDeclaration(method, out tsMethodDeclaration)\r\n             || this.cg.bindingManager.GetTSMethodDeclaration(method, out tsMethodDeclaration))\r\n            {\r\n                this.cg.tsDeclare.AppendLine(tsMethodDeclaration);\r\n                return refParameters;\r\n            }\r\n\r\n            var tsMethodRename = bindingInfo.jsName;\r\n            var isRaw = method.IsDefined(typeof(JSCFunctionAttribute), false);\r\n            //TODO: 需要处理参数类型归并问题, 因为如果类型没有导入 ts 中, 可能会在声明中出现相同参数列表的定义\r\n            //      在 MethodVariant 中创建每个方法对应的TS类型名参数列表, 完全相同的不再输出\r\n            var prefix = \"\";\r\n            // if (method.Name.StartsWith(\"op_\"))\r\n            if (bindingInfo is OperatorBindingInfo)\r\n            {\r\n                prefix += \"// js_op_overloading: \";\r\n            }\r\n\r\n            if (method.IsStatic && !isExtension)\r\n            {\r\n                prefix += \"static \";\r\n            }\r\n\r\n            this.cg.tsDeclare.Append($\"{prefix}{tsMethodRename}(\");\r\n\r\n            if (this.cg.bindingManager.prefs.verboseLog)\r\n            {\r\n                this.cg.bindingManager.Info($\"WriteTSDeclaration: {method.Name} <isExtension: {isExtension}> => {tsMethodRename} {this.cg.tsDeclare.enabled}\");\r\n            }\r\n\r\n            if (isRaw)\r\n            {\r\n                this.cg.tsDeclare.AppendL(\"...uncertain: any[]): any /* uncertain */\");\r\n                this.cg.tsDeclare.AppendLine();\r\n            }\r\n            else\r\n            {\r\n                var parameters = method.GetParameters();\r\n                if (isExtension)\r\n                {\r\n                    CodeGenUtils.RemoveAt(ref parameters, 0);\r\n                }\r\n\r\n                for (int i = 0, len = parameters.Length; i < len;)\r\n                {\r\n                    var parameter = parameters[i];\r\n                    var parameterType = parameter.ParameterType;\r\n                    if (Binding.Values.IsContextualType(parameterType))\r\n                    {\r\n                        // 剔除 JSContext, JSRuntime\r\n                        CodeGenUtils.RemoveAt(ref parameters, i);\r\n                        len--;\r\n                    }\r\n                    // else if (parameter.IsOut)\r\n                    // {\r\n                    //     ArrayUtility.RemoveAt(ref parameters, i);\r\n                    //     len--;\r\n                    //     refParameters.Add(parameter);\r\n                    // }\r\n                    else\r\n                    {\r\n                        // if (parameterType.IsByRef)\r\n                        // {\r\n                        //     refParameters.Add(parameter);\r\n                        // }\r\n                        i++;\r\n                    }\r\n                }\r\n\r\n                for (int i = 0, len = parameters.Length; i < len; i++)\r\n                {\r\n                    var parameter = parameters[i];\r\n                    var parameter_prefix = \"\";\r\n                    var parameterType = parameter.ParameterType;\r\n\r\n                    if (parameter.IsDefined(typeof(ParamArrayAttribute), false) && i == parameters.Length - 1)\r\n                    {\r\n                        var elementType = parameterType.GetElementType();\r\n                        var elementTS = this.cg.currentTSModule.GetTSTypeFullName(elementType);\r\n                        var parameterVarName = BindingManager.GetTSVariable(parameter.Name);\r\n                        this.cg.tsDeclare.AppendL($\"{parameter_prefix}...{parameterVarName}: {elementTS}[]\");\r\n                    }\r\n                    else\r\n                    {\r\n                        var parameterTS = this.cg.currentTSModule.GetTSTypeFullName(parameter);\r\n                        var parameterVarName = BindingManager.GetTSVariable(parameter.Name);\r\n                        this.cg.tsDeclare.AppendL($\"{parameter_prefix}{parameterVarName}: {parameterTS}\");\r\n                    }\r\n\r\n                    if (i != parameters.Length - 1)\r\n                    {\r\n                        this.cg.tsDeclare.AppendL(\", \");\r\n                    }\r\n                }\r\n                this.cg.tsDeclare.AppendL($\")\");\r\n                WriteTSReturn(method, refParameters);\r\n            }\r\n\r\n            return refParameters;\r\n        }\r\n\r\n        // 获取返回值类型\r\n        protected abstract Type GetReturnType(T method);\r\n\r\n        // 获取方法调用\r\n        protected abstract string GetInvokeBinding(string caller, T method, bool hasParams, bool isExtension, string nargs, ParameterInfo[] parameters);\r\n\r\n        protected virtual void BeginInvokeBinding() { }\r\n\r\n        protected virtual void EndInvokeBinding() { }\r\n\r\n        protected virtual void OnBeforeExceptionReturn() { }\r\n\r\n        protected void SplitParamters(ParameterInfo[] parameters, int index, List<ParameterInfo> out_params)\r\n        {\r\n            for (int i = index, len = parameters.Length; i < len; i++)\r\n            {\r\n                var p = parameters[i];\r\n\r\n                if (p.IsOut || p.ParameterType.IsByRef)\r\n                {\r\n                    out_params.Add(p);\r\n                }\r\n            }\r\n        }\r\n\r\n        private void WriteRebindThis(MethodBase method, Type callerType, string caller)\r\n        {\r\n            if (!method.IsStatic && method.DeclaringType.IsValueType) // struct 非静态方法 检查 Mutable 属性\r\n            {\r\n                if (!string.IsNullOrEmpty(caller))\r\n                {\r\n                    var js_rebind_this = this.cg.bindingManager.GetRebindOperation(callerType);\r\n                    cg.cs.AppendLine($\"{js_rebind_this}(ctx, this_obj, ref {caller});\");\r\n                }\r\n            }\r\n        }\r\n\r\n        // 写入绑定代码\r\n        protected void WriteCSBindingMethodBody(MethodBaseBindingInfo<T> bindingInfo, T method, string argc, bool isVararg, bool isExtension)\r\n        {\r\n            if (this.cg.bindingManager.prefs.verboseLog)\r\n            {\r\n                cg.bindingManager.Info($\"WriteCSMethodBinding: {method.Name} {isExtension}\");\r\n            }\r\n\r\n            var parameters = method.GetParameters();\r\n            Type callerType;\r\n            var caller = this.cg.AppendGetThisCS(method, isExtension, out callerType);\r\n            var returnType = GetReturnType(method);\r\n\r\n            if (returnType == null || returnType == typeof(void))\r\n            {\r\n                // 方法本身没有返回值\r\n                this.BeginInvokeBinding();\r\n                cg.cs.AppendLine($\"{this.GetInvokeBinding(caller, method, isVararg, isExtension, argc, parameters)};\");\r\n                this.EndInvokeBinding();\r\n\r\n                _WriteBackParameters(isExtension, parameters);\r\n                WriteRebindThis(method, callerType, caller);\r\n                InvokeVoidReturn();\r\n            }\r\n            else\r\n            {\r\n                var retVar = \"ret\"; // cs return value var name\r\n                this.BeginInvokeBinding();\r\n                cg.cs.AppendLine($\"var {retVar} = {this.GetInvokeBinding(caller, method, isVararg, isExtension, argc, parameters)};\");\r\n                this.EndInvokeBinding();\r\n\r\n                var retPusher = cg.AppendMethodReturnValuePusher(method, returnType, retVar);\r\n\r\n                _WriteBackParameters(isExtension, parameters);\r\n                cg.cs.AppendLine(\"return {0};\", retPusher);\r\n            }\r\n        }\r\n\r\n        // 回填 ref/out 参数\r\n        // 扩展方法参数索引需要偏移\r\n        protected void _WriteBackParameters(bool isExtension, ParameterInfo[] parameters)\r\n        {\r\n            var pIndex = isExtension ? 1 : 0;\r\n            var oIndex = 0;\r\n            var pBase = pIndex;\r\n            var getContext = false;\r\n            for (; pIndex < parameters.Length; pIndex++)\r\n            {\r\n                var parameter = parameters[pIndex];\r\n                var pType = parameter.ParameterType;\r\n\r\n                if (!pType.IsByRef || Binding.Values.IsContextualType(pType))\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                var baseIndex = pIndex - pBase;\r\n                var pusher = cg.AppendValuePusher(parameter.ParameterType, $\"arg{baseIndex}\");\r\n\r\n                cg.cs.AppendLine(\"var out{0} = {1};\", oIndex, pusher);\r\n                cg.cs.AppendLine(\"if (JSApi.JS_IsException(out{0}))\", oIndex);\r\n                using (cg.cs.CodeBlockScope())\r\n                {\r\n                    // for (var j = 0; j < oIndex; j++)\r\n                    // {\r\n                    //     cg.cs.AppendLine(\"JSApi.JS_FreeValue(ctx, out{0});\", j);\r\n                    // }\r\n                    OnBeforeExceptionReturn();\r\n                    cg.cs.AppendLine(\"return out{0};\", oIndex);\r\n                }\r\n\r\n                if (!getContext)\r\n                {\r\n                    cg.cs.AppendLine(\"var context = ScriptEngine.GetContext(ctx);\");\r\n                    getContext = true;\r\n                }\r\n\r\n                cg.cs.AppendLine(\"JSApi.JS_SetProperty(ctx, argv[{0}], context.GetAtom(\\\"value\\\"), out{1});\", baseIndex, oIndex);\r\n                oIndex++;\r\n            }\r\n        }\r\n    }\r\n\r\n    public class ConstructorCodeGen : MethodBaseCodeGen<ConstructorInfo>\r\n    {\r\n        private TypeBindingInfo typeBindingInfo;\r\n        private ConstructorBindingInfo methodBindingInfo;\r\n\r\n        private bool disposable => typeBindingInfo.disposable;\r\n\r\n        protected override Type GetReturnType(ConstructorInfo method)\r\n        {\r\n            return null;\r\n        }\r\n\r\n        // 写入默认构造函数 (struct 无参构造)\r\n        private void WriteDefaultConstructorBinding()\r\n        {\r\n            var decalringTypeName = this.cg.bindingManager.GetCSTypeFullName(this.methodBindingInfo.decalringType);\r\n            var castOperation = this.cg.bindingManager.GetNewOperation(this.methodBindingInfo.decalringType);\r\n            this.cg.cs.AppendLine(\"var o = new {0}();\", decalringTypeName);\r\n            this.cg.cs.AppendLine(\"var val = {0}(ctx, new_target, o, magic, {1});\", castOperation, CodeGenUtils.ToExpression(this.disposable));\r\n            this.cg.cs.AppendLine(\"return val;\");\r\n\r\n            this.cg.tsDeclare.AppendLine($\"{this.methodBindingInfo.jsName}()\");\r\n        }\r\n\r\n        protected override string GetInvokeBinding(string caller, ConstructorInfo method, bool hasParams, bool isExtension, string nargs, ParameterInfo[] parameters)\r\n        {\r\n            var arglist = Concat(AppendGetParameters(hasParams, nargs, method, parameters));\r\n            var decalringTypeName = this.cg.bindingManager.GetCSTypeFullName(this.methodBindingInfo.decalringType);\r\n            // // 方法本身有返回值\r\n            // var transform = cg.bindingManager.GetTypeTransform(method.DeclaringType);\r\n            // if (transform == null || !transform.OnBinding(BindingPoints.METHOD_BINDING_BEFORE_INVOKE, method, cg, arglist))\r\n            // {\r\n            // }\r\n            return $\"var o = new {decalringTypeName}({arglist})\";\r\n        }\r\n\r\n        protected override void EndInvokeBinding()\r\n        {\r\n            var castOperation = this.cg.bindingManager.GetNewOperation(this.methodBindingInfo.decalringType);\r\n            this.cg.cs.AppendLine(\"var val = {0}(ctx, new_target, o, magic, {1});\", castOperation, CodeGenUtils.ToExpression(this.disposable));\r\n        }\r\n\r\n        protected override void InvokeVoidReturn()\r\n        {\r\n            this.cg.cs.AppendLine(\"return val;\");\r\n        }\r\n\r\n        protected override void OnBeforeExceptionReturn()\r\n        {\r\n            this.cg.cs.AppendLine(\"JSApi.JS_FreeValue(ctx, val);\");\r\n        }\r\n\r\n        public ConstructorCodeGen(CodeGenerator cg, TypeBindingInfo typeBindingInfo)\r\n        : base(cg)\r\n        {\r\n            this.typeBindingInfo = typeBindingInfo;\r\n            this.methodBindingInfo = typeBindingInfo.constructors;\r\n            if (this.methodBindingInfo.count > 0)\r\n            {\r\n\r\n                WriteCSAllVariants(this.typeBindingInfo, this.methodBindingInfo);\r\n                // WriteTSAllVariants(typeBindingInfo, this.methodBindingInfo);\r\n            }\r\n            else\r\n            {\r\n                WriteDefaultConstructorBinding();\r\n            }\r\n        }\r\n    }\r\n\r\n    // 生成成员方法绑定代码\r\n    public class CSMethodCodeGen : MethodBaseCodeGen<MethodInfo>\r\n    {\r\n        protected TypeBindingInfo typeBindingInfo;\r\n        protected MethodBindingInfo methodBindingInfo;\r\n\r\n        public CSMethodCodeGen(CodeGenerator cg, TypeBindingInfo typeBindingInfo, MethodBindingInfo methodBindingInfo)\r\n        : base(cg)\r\n        {\r\n            this.typeBindingInfo = typeBindingInfo;\r\n            this.methodBindingInfo = methodBindingInfo;\r\n            WriteCSAllVariants(this.typeBindingInfo, this.methodBindingInfo);\r\n        }\r\n\r\n        protected override IEnumerable<string> GetRequiredDefines(MethodBase methodBase)\r\n        {\r\n            return typeBindingInfo.transform.GetRequiredDefinesOfMethod(methodBase);\r\n        }\r\n\r\n        protected override Type GetReturnType(MethodInfo method)\r\n        {\r\n            return method.ReturnType;\r\n        }\r\n\r\n        private string WriteSetterBinding(string caller, MethodBase method, ParameterInfo[] parameters)\r\n        {\r\n            var last = parameters.Length - 1;\r\n            var arglist_t = \"\";\r\n            var assignIndex = 0;\r\n            for (var i = 0; i < last; i++)\r\n            {\r\n                var argname = $\"arg{i}\";\r\n                if (this.cg.WriteParameterGetter(parameters[i], assignIndex, argname, method))\r\n                {\r\n                    assignIndex++;\r\n                }\r\n                arglist_t += argname;\r\n                if (i != last - 1)\r\n                {\r\n                    arglist_t += \", \";\r\n                }\r\n            }\r\n            var argname_last = $\"arg{last}\";\r\n            this.cg.WriteParameterGetter(parameters[last], assignIndex, argname_last, method);\r\n            return $\"{caller}[{arglist_t}] = {argname_last}\"; // setter\r\n        }\r\n\r\n        private string WriteGetterBinding(string caller, MethodBase method, ParameterInfo[] parameters)\r\n        {\r\n            var last = parameters.Length;\r\n            var arglist_t = \"\";\r\n            var assignIndex = 0;\r\n            for (var i = 0; i < last; i++)\r\n            {\r\n                var argname = $\"arg{i}\";\r\n                if (this.cg.WriteParameterGetter(parameters[i], assignIndex, argname, method))\r\n                {\r\n                    assignIndex++;\r\n                }\r\n                arglist_t += argname;\r\n                if (i != last - 1)\r\n                {\r\n                    arglist_t += \", \";\r\n                }\r\n            }\r\n            return $\"{caller}[{arglist_t}]\"; // getter\r\n        }\r\n\r\n        protected override string GetInvokeBinding(string caller, MethodInfo method, bool hasParams, bool isExtension, string nargs, ParameterInfo[] parameters)\r\n        {\r\n            if (method.IsSpecialName) // if (bindingInfo.isIndexer)\r\n            {\r\n                if (method.Name == \"set_Item\") // if (method.ReturnType == typeof(void))\r\n                {\r\n                    return WriteSetterBinding(caller, method, parameters); // setter\r\n                }\r\n                else if (method.Name == \"get_Item\")\r\n                {\r\n                    return WriteGetterBinding(caller, method, parameters);\r\n                }\r\n            }\r\n\r\n            var paramsToGet = isExtension ? parameters.Skip(1).ToArray() : parameters;\r\n            var arglist = AppendGetParameters(hasParams, nargs, method, paramsToGet);\r\n            var arglistSig = Concat(arglist);\r\n            // var transform = cg.bindingManager.GetTypeTransform(method.DeclaringType);\r\n            // // 在生成调用前插入代码 \r\n            // if (transform == null || !transform.OnBinding(BindingPoints.METHOD_BINDING_BEFORE_INVOKE, method, cg))\r\n            // {\r\n            // }\r\n\r\n            // 扩展方法调用实际静态类方法\r\n            if (isExtension)\r\n            {\r\n                var methodDeclType = this.cg.bindingManager.GetCSTypeFullName(method.DeclaringType);\r\n                if (arglistSig.Length > 0)\r\n                {\r\n                    arglistSig = \", \" + arglistSig;\r\n                }\r\n\r\n                return $\"{methodDeclType}.{method.Name}({caller}{arglistSig})\";\r\n            }\r\n\r\n            // 处理运算符方式调用\r\n            if (method.IsSpecialName)\r\n            {\r\n                switch (method.Name)\r\n                {\r\n                    case \"op_Addition\":\r\n                        return $\"{arglist[0]} + {arglist[1]}\";\r\n                    case \"op_Subtraction\":\r\n                        return $\"{arglist[0]} - {arglist[1]}\";\r\n                    case \"op_Modulus\":\r\n                        return $\"{arglist[0]} % {arglist[1]}\";\r\n                    case \"op_Equality\":\r\n                        return $\"{arglist[0]} == {arglist[1]}\";\r\n                    case \"op_Inequality\":\r\n                        return $\"{arglist[0]} != {arglist[1]}\";\r\n                    case \"op_LessThan\":\r\n                        return $\"{arglist[0]} < {arglist[1]}\";\r\n                    case \"op_LessThanOrEqual\":\r\n                        return $\"{arglist[0]} <= {arglist[1]}\";\r\n                    case \"op_GreaterThan\":\r\n                        return $\"{arglist[0]} > {arglist[1]}\";\r\n                    case \"op_GreaterThanOrEqual\":\r\n                        return $\"{arglist[0]} >= {arglist[1]}\";\r\n                    case \"op_Division\":\r\n                        return $\"{arglist[0]} / {arglist[1]}\";\r\n                    case \"op_Multiply\":\r\n                        return $\"{arglist[0]} * {arglist[1]}\";\r\n                    case \"op_UnaryNegation\":\r\n                        return $\"-{arglist[0]}\";\r\n                    case \"op_Explicit\":\r\n                    case \"op_Implicit\":\r\n                        var implicitTypeName = this.cg.bindingManager.GetCSTypeFullName(GetReturnType(method));\r\n                        return $\"({implicitTypeName}){arglist[0]}\";\r\n                    case \"op_BitwiseAnd\":\r\n                        return $\"{arglist[0]} & {arglist[1]}\";\r\n                    case \"op_BitwiseOr\":\r\n                        return $\"{arglist[0]} | {arglist[1]}\";\r\n                }\r\n            }\r\n\r\n            // 普通成员调用\r\n            return $\"{caller}.{method.Name}({arglistSig})\";\r\n        }\r\n    }\r\n\r\n    public class TSConstructorCodeGen : MethodBaseCodeGen<ConstructorInfo>\r\n    {\r\n        protected MethodBaseBindingInfo<ConstructorInfo> bindingInfo;\r\n\r\n        protected override Type GetReturnType(ConstructorInfo method)\r\n        {\r\n            return null;\r\n        }\r\n\r\n        protected override string GetInvokeBinding(string caller, ConstructorInfo method, bool hasParams, bool isExtension, string nargs, ParameterInfo[] parameters)\r\n        {\r\n            return null;\r\n        }\r\n\r\n        public TSConstructorCodeGen(CodeGenerator cg, TypeBindingInfo typeBindingInfo, MethodBaseBindingInfo<ConstructorInfo> bindingInfo)\r\n            : base(cg)\r\n        {\r\n            this.bindingInfo = bindingInfo;\r\n            WriteTSAllVariants(typeBindingInfo, this.bindingInfo);\r\n        }\r\n    }\r\n\r\n    public class TSMethodCodeGen<T> : MethodBaseCodeGen<T>\r\n        where T : MethodInfo\r\n    {\r\n        protected MethodBaseBindingInfo<T> bindingInfo;\r\n\r\n        protected override Type GetReturnType(T method)\r\n        {\r\n            return method.ReturnType;\r\n        }\r\n\r\n        protected override string GetInvokeBinding(string caller, T method, bool hasParams, bool isExtension, string nargs, ParameterInfo[] parameters)\r\n        {\r\n            return null;\r\n        }\r\n\r\n        public TSMethodCodeGen(CodeGenerator cg, TypeBindingInfo typeBindingInfo, MethodBaseBindingInfo<T> bindingInfo)\r\n            : base(cg)\r\n        {\r\n            this.bindingInfo = bindingInfo;\r\n            WriteTSAllVariants(typeBindingInfo, this.bindingInfo);\r\n        }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_Method.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 3430939f47b05c34d89895dbcc46bb27\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_Operator.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    // 生成成员方法绑定代码\r\n    public class OperatorCodeGen : MethodBaseCodeGen<MethodInfo>\r\n    {\r\n        protected TypeBindingInfo typeBindingInfo;\r\n        protected OperatorBindingInfo operatorBindingInfo;\r\n\r\n        protected override Type GetReturnType(MethodInfo method)\r\n        {\r\n            return method.ReturnType;\r\n        }\r\n\r\n        private string OpArgsConcat(List<string> args, string sp = \", \")\r\n        {\r\n            if (args.Count == 1)\r\n            {\r\n                return sp + args[0];\r\n            }\r\n            var len = args.Count;\r\n            var res = \"\";\r\n            for (var i = 0; i < len; i++)\r\n            {\r\n                res += args[i];\r\n                if (i != len - 1)\r\n                {\r\n                    res += sp;\r\n                }\r\n            }\r\n\r\n            return res;\r\n        }\r\n\r\n        protected override string GetInvokeBinding(string caller, MethodInfo method, bool hasParams, bool isExtension, string nargs, ParameterInfo[] parameters)\r\n        {\r\n            var arglist = OpArgsConcat(AppendGetParameters(hasParams, nargs, method, parameters), \" \" + operatorBindingInfo.cs_op + \" \");\r\n            // var transform = cg.bindingManager.GetTypeTransform(method.DeclaringType);\r\n            // if (transform == null || !transform.OnBinding(BindingPoints.METHOD_BINDING_BEFORE_INVOKE, method, cg))\r\n            // {\r\n            // }\r\n\r\n            return arglist;\r\n        }\r\n\r\n        public OperatorCodeGen(CodeGenerator cg, TypeBindingInfo typeBindingInfo, OperatorBindingInfo bindingInfo)\r\n            : base(cg)\r\n        {\r\n            this.typeBindingInfo = typeBindingInfo;\r\n            this.operatorBindingInfo = bindingInfo;\r\n            WriteCSAllVariants(this.typeBindingInfo, this.operatorBindingInfo);\r\n            // WriteTSAllVariants(this.bindingInfo);\r\n        }\r\n    }\r\n\r\n    public class TSOperatorCodeGen : MethodBaseCodeGen<MethodInfo>\r\n    {\r\n        protected OperatorBindingInfo bindingInfo;\r\n\r\n        protected override Type GetReturnType(MethodInfo method)\r\n        {\r\n            return method.ReturnType;\r\n        }\r\n\r\n        protected override string GetInvokeBinding(string caller, MethodInfo method, bool hasParams, bool isExtension, string nargs, ParameterInfo[] parameters)\r\n        {\r\n            return null;\r\n        }\r\n\r\n        public TSOperatorCodeGen(CodeGenerator cg, TypeBindingInfo typeBindingInfo, OperatorBindingInfo bindingInfo)\r\n            : base(cg)\r\n        {\r\n            this.bindingInfo = bindingInfo;\r\n            WriteTSAllVariants(typeBindingInfo, this.bindingInfo);\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_Operator.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: f588afad6badbfc43a2ede6b28758f07\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_PlainClass.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing System.IO;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public class PlainClassCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n\r\n        public PlainClassCodeGen(CodeGenerator cg, string name, bool isPartial)\r\n        {\r\n            this.cg = cg;\r\n            if (isPartial)\r\n            {\r\n                this.cg.cs.AppendLine(\"public partial class {0}\", name);\r\n            }\r\n            else\r\n            {\r\n                this.cg.cs.AppendLine(\"public class {0}\", name);\r\n            }\r\n            this.cg.cs.AppendLine(\"{\");\r\n            this.cg.cs.AddTabLevel();\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n            this.cg.cs.DecTabLevel();\r\n            this.cg.cs.AppendLine(\"}\");\r\n        }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_PlainClass.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: da4a004307c395a4f9767d92483529a6\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_PlainMethod.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing System.IO;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public class PlainMethodCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n\r\n        public PlainMethodCodeGen(CodeGenerator cg, string sig)\r\n        {\r\n            this.cg = cg;\r\n            this.cg.cs.AppendLine(sig);\r\n            this.cg.cs.AppendLine(\"{\");\r\n            this.cg.cs.AddTabLevel();\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n            this.cg.cs.DecTabLevel();\r\n            this.cg.cs.AppendLine(\"}\");\r\n        }\r\n\r\n        public void AddStatement(string fmt, params object[] args)\r\n        {\r\n            this.cg.cs.AppendLine(fmt, args);\r\n        }\r\n\r\n        public void AddModuleEntry(string moduleName, string runtimeVarName, string moduleVarName, TypeBindingInfo typeBindingInfo)\r\n        {\r\n            var csType = this.cg.bindingManager.GetCSTypeFullName(typeBindingInfo.type);\r\n            var csNamespace = this.cg.bindingManager.prefs.ns;\r\n            var csBindingName = typeBindingInfo.csBindingName;\r\n            var moduleRegistrationPathSlice = CodeGenUtils.GetModuleRegistrationPathSlice(typeBindingInfo.tsTypeNaming);\r\n            var jsNamespace = CodeGenUtils.JoinExpression(\", \", moduleRegistrationPathSlice);\r\n            \r\n            AddStatement($\"{runtimeVarName}.AddTypeReference({moduleVarName}, typeof({csType}), {csNamespace}.{csBindingName}.Bind, {jsNamespace});\");\r\n        }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_PlainMethod.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 8ac2ba9dc9657f74b9f5b19a6140c668\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_Property.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.IO;\nusing System.Reflection;\n\nnamespace QuickJS.Binding\n{\n    public class PropertyGetterCodeGen : IDisposable\n    {\n        protected CodeGenerator cg;\n        protected PropertyBindingInfo bindingInfo;\n\n        public PropertyGetterCodeGen(CodeGenerator cg, PropertyBindingInfo bindingInfo)\n        {\n            this.cg = cg;\n            this.bindingInfo = bindingInfo;\n\n            Type callerType;\n            var caller = this.cg.AppendGetThisCS(bindingInfo.getMethod, false, out callerType);\n\n            this.cg.cs.AppendLine(\"var ret = {0}.{1};\", caller, BindingManager.GetCSVariable(bindingInfo.propertyInfo.Name));\n            var pusher = this.cg.AppendValuePusher(bindingInfo.propertyType, \"ret\");\n            this.cg.cs.AppendLine(\"return {0};\", pusher);\n        }\n\n        public virtual void Dispose()\n        {\n        }\n    }\n\n    public class PropertySetterCodeGen : IDisposable\n    {\n        protected CodeGenerator cg;\n        protected PropertyBindingInfo bindingInfo;\n\n        public PropertySetterCodeGen(CodeGenerator cg, PropertyBindingInfo propertyBindingInfo)\n        {\n            this.cg = cg;\n            this.bindingInfo = propertyBindingInfo;\n\n            var propertyInfo = this.bindingInfo.propertyInfo;\n            var declaringType = propertyInfo.DeclaringType;\n            Type callerType;\n            var caller = this.cg.AppendGetThisCS(propertyBindingInfo.setMethod, false, out callerType);\n            var propertyType = this.cg.bindingManager.GetCSTypeFullName(propertyInfo.PropertyType);\n\n            this.cg.cs.AppendLine(\"{0} value;\", propertyType);\n            var getter = this.cg.bindingManager.GetScriptObjectGetter(propertyInfo.PropertyType, \"ctx\", \"arg_val\", \"value\");\n            this.cg.cs.AppendLine(\"if (!{0})\", getter);\n            using (this.cg.cs.CodeBlockScope())\n            {\n                this.cg.WriteParameterException(declaringType, propertyInfo.Name, propertyType, 0);\n            }\n            this.cg.cs.AppendLine(\"{0}.{1} = value;\", caller, BindingManager.GetCSVariable(propertyInfo.Name));\n            if (declaringType.IsValueType && !propertyBindingInfo.setMethod.IsStatic)\n            {\n                // 非静态结构体属性修改, 尝试替换实例\n                var js_rebind_this = this.cg.bindingManager.GetRebindOperation(callerType);\n                this.cg.cs.AppendLine($\"{js_rebind_this}(ctx, this_obj, ref {caller});\");\n            }\n            this.cg.cs.AppendLine(\"return JSApi.JS_UNDEFINED;\");\n        }\n\n        public virtual void Dispose()\n        {\n        }\n    }\n}\n\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenHelper_Property.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 46a271593497aa74bb2de85024b04db7\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenUtils.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.Linq;\r\nusing System.Collections.Generic;\r\nusing System.Diagnostics;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public static class CodeGenUtils\r\n    {\r\n        public const string CodeEmitWarning = \"Codegen for delegate binding with ref/out parameters will not work properly, because CodeDomProvider is not supported with current dotnet api compatibility settings. Please consider switching to .NET 4.6 in player settings.\";\r\n\r\n        public static bool IsCodeEmitSupported()\r\n        {\r\n#if JSB_UNITYLESS\r\n#if NETCOREAPP\r\n            return false;\r\n#else\r\n            return true;\r\n#endif\r\n#else\r\n            var apiCompatibilityLevel = UnityEditor.PlayerSettings.GetApiCompatibilityLevel(UnityEditor.BuildTargetGroup.Standalone);\r\n            return apiCompatibilityLevel == UnityEditor.ApiCompatibilityLevel.NET_4_6;\r\n#endif\r\n        }\r\n\r\n        /// <summary>\r\n        /// Compiles C# source into assembly, usually used for dynamically generating delegate function with ref/out parameters at runtime.\r\n        /// NOTE: It will directly return null if CodeDom is not supported without throwing any exception.\r\n        /// </summary>\r\n        public static Assembly Compile(string source, IEnumerable<Assembly> referencedAssemblies, string compilerOptions, IBindingLogger logger)\r\n        {\r\n#if !(NETCOREAPP || NET_STANDARD_2_0 || NET_STANDARD_2_1 || NET_STANDARD)\r\n            using (var codeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider(\"cs\"))\r\n            {\r\n                var compilerParameters = new System.CodeDom.Compiler.CompilerParameters();\r\n                compilerParameters.GenerateInMemory = true;\r\n                compilerParameters.TreatWarningsAsErrors = false;\r\n                compilerParameters.CompilerOptions = compilerOptions;\r\n                // compilerParameters.TempFiles = new System.CodeDom.Compiler.TempFileCollection(\"Temp\", false);\r\n                compilerParameters.OutputAssembly = \"Temp/_Generated_\" + Guid.NewGuid().ToString() + \".dll\";\r\n                compilerParameters.ReferencedAssemblies.AddRange((from a in referencedAssemblies select a.Location).ToArray());\r\n                var result = codeDomProvider.CompileAssemblyFromSource(compilerParameters, source);\r\n\r\n                if (result.Errors.HasErrors)\r\n                {\r\n                    if (logger != null)\r\n                    {\r\n                        logger.LogError($\"failed to compile source [{result.Errors.Count} errors]\\nSource: {source}\");\r\n                        foreach (var err in result.Errors)\r\n                        {\r\n                            logger.LogError(err.ToString());\r\n                        }\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    return result.CompiledAssembly;\r\n                }\r\n            }\r\n#endif\r\n            return null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Check if the type directly implements the given interface\r\n        /// </summary>\r\n        public static bool IsDirectlyImplements(Type type, Type interfaceType)\r\n        {\r\n            return type.BaseType != null && interfaceType.IsAssignableFrom(type) && !interfaceType.IsAssignableFrom(type.BaseType);\r\n        }\r\n\r\n        public static void RemoveAt<T>(ref T[] array, int index)\r\n        {\r\n#if JSB_UNITYLESS\r\n            for (var i = index; i < array.Length - 1; i++)\r\n            {\r\n                array[i] = array[i + 1];\r\n            }\r\n            Array.Resize(ref array, array.Length - 1);\r\n#else\r\n            UnityEditor.ArrayUtility.RemoveAt(ref array, index);\r\n#endif\r\n        }\r\n\r\n        public static string ToExpression(bool v)\r\n        {\r\n            return v ? \"true\" : \"false\";\r\n        }\r\n\r\n        /// <summary>\r\n        /// remove part of generic definition from TS naming result\r\n        /// </summary>\r\n        public static string StripGenericDeclaration(string name)\r\n        {\r\n            var index = name.IndexOf(\"<\");\r\n            return index < 0 ? name : name.Substring(0, index);\r\n        }\r\n\r\n        /// <summary>\r\n        /// remove part of generic definition from CSharp type name\r\n        /// </summary>\r\n        public static string StripGenericDefinition(string name)\r\n        {\r\n            var index = name.IndexOf(\"`\");\r\n            return index < 0 ? name : name.Substring(0, index);\r\n        }\r\n\r\n        public static string[] Strip(string[] values, string additional)\r\n        {\r\n            var list = new List<string>(values.Length + 1);\r\n            list.AddRange(values);\r\n            list.Add(additional);\r\n            return Strip(list.ToArray());\r\n        }\r\n\r\n        /// <summary>\r\n        /// return an array copy without empty elements\r\n        /// </summary>\r\n        public static string[] Strip(params string[] values)\r\n        {\r\n            return (from value in values where !string.IsNullOrEmpty(value) select value).ToArray();\r\n        }\r\n\r\n        public static string Join(string sp, string left, string right)\r\n        {\r\n            if (right.Length > 0)\r\n            {\r\n                return left.Length > 0 ? left + sp + right : right;\r\n            }\r\n            return left;\r\n        }\r\n\r\n        public static string Join(string sp, string[] values, int offset, int count)\r\n        {\r\n            var r = \"\";\r\n            for (int i = 0; i < count; ++i)\r\n            {\r\n                var value = values[i + offset];\r\n                if (value.Length != 0)\r\n                {\r\n                    r += i != count - 1 ? value + sp : value;\r\n                }\r\n            }\r\n            return r;\r\n        }\r\n\r\n        public static string Join(string sp, params string[] values)\r\n        {\r\n            return string.Join(sp, Strip(values));\r\n        }\r\n\r\n        // 将类型名转换成简单字符串 (比如用于文件名)\r\n        public static string GetFileName(Type type)\r\n        {\r\n            string typeName = \"\";\r\n            if (type.IsGenericType)\r\n            {\r\n                typeName += type.Name.Substring(0, type.Name.IndexOf('`'));\r\n                foreach (var gp in type.GetGenericArguments())\r\n                {\r\n                    typeName += \"_\" + gp.Name;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                typeName = type.IsArray ? type.Name + \"_array\" : type.Name;\r\n            }\r\n\r\n            if (type.DeclaringType != null)\r\n            {\r\n                return GetFileName(type.DeclaringType) + \"_\" + typeName;\r\n            }\r\n\r\n            if (string.IsNullOrEmpty(type.Namespace))\r\n            {\r\n                return typeName;\r\n            }\r\n\r\n            return type.Namespace.Replace(\".\", \"_\") + \"_\" + typeName;\r\n        }\r\n\r\n        public static bool IsValidTypeDeclarationName(string name)\r\n        {\r\n            return !(\r\n                name.Contains(\".\") ||\r\n                name.Contains(\"<\") ||\r\n                name.Contains(\">\") ||\r\n                name.Contains(\"`\") ||\r\n                name.Contains(\"+\") ||\r\n                name.Contains(\" \") ||\r\n                name.Contains(\",\") ||\r\n                name.Contains(\"=\")\r\n            );\r\n        }\r\n\r\n        /// <summary>\r\n        /// concat strings as: \"value1\", \"value2\", \"value3\"\r\n        /// </summary>\r\n        public static string JoinExpression(string sp, params string[] values)\r\n        {\r\n            return string.Join(sp, from value in values select $\"\\\"{value}\\\"\");\r\n        }\r\n\r\n        // 保证生成一个以 prefix 为前缀, 与参数列表中所有参数名不同的名字\r\n        public static string GetUniqueName(ParameterInfo[] parameters, string prefix)\r\n        {\r\n            return GetUniqueName(parameters, prefix, 0);\r\n        }\r\n\r\n        public static string GetUniqueName(ParameterInfo[] parameters, string prefix, int index)\r\n        {\r\n            var size = parameters.Length;\r\n            var name = prefix + index;\r\n            for (var i = 0; i < size; i++)\r\n            {\r\n                var parameter = parameters[i];\r\n                if (parameter.Name == prefix)\r\n                {\r\n                    return GetUniqueName(parameters, prefix, index + 1);\r\n                }\r\n            }\r\n            return name;\r\n        }\r\n\r\n        /// <summary>\r\n        /// e.g [\"TypeA\", \"TypeB\", \"ThisType\"]\r\n        /// </summary>\r\n        public static string[] GetModuleRegistrationPathSlice(ITSTypeNaming tSTypeNaming)\r\n        {\r\n            return tSTypeNaming.classPath;\r\n        }\r\n\r\n        public static string GetTSClassName(TypeBindingInfo typeBindingInfo)\r\n        {\r\n            var tsTypeNaming = typeBindingInfo.tsTypeNaming;\r\n            var type = typeBindingInfo.type;\r\n            if (type.IsGenericType)\r\n            {\r\n                if (type.IsGenericTypeDefinition)\r\n                {\r\n                    var args = string.Join(\", \", from arg in type.GetGenericArguments() select arg.Name);\r\n                    return string.Format(\"{0}<{1}>\", tsTypeNaming.className, args);\r\n                }\r\n            }\r\n\r\n            return Join(\"\", tsTypeNaming.className, tsTypeNaming.genericDefinition);\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public static void Assert(bool condition, string msg)\r\n        {\r\n#if UNITY_EDITOR\r\n            UnityEngine.Debug.Assert(condition, msg);\r\n#endif\r\n        }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenUtils.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 6ea048735b4a68c48a366a773c8fdb76\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenerator.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.Linq;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Reflection;\nusing System.IO;\n\nnamespace QuickJS.Binding\n{\n    using QuickJS.Binding;\n\n    public partial class CodeGenerator\n    {\n        public const string NameOfDelegates = \"_QuickJSDelegates\";\n        public const string NameOfHotfixDelegates = \"_QuickJSHotfixDelegates\";\n        public const string NameOfBindingList = \"_QuickJSBindings\";\n        public const string NamespaceOfScriptTypes = \"QuickJS\";\n        public const string NamespaceOfInternalScriptTypes = \"QuickJS.Internal\";\n        public const string NameOfBuffer = \"ArrayBuffer\";\n\n        private TSModuleCodeGen _currentTSModule = null;\n\n        public TSModuleCodeGen currentTSModule => _currentTSModule;\n        public BindingManager bindingManager;\n        public TextGenerator cs;\n        public TextGenerator tsDeclare;\n        public JSBindResult bindResult;\n        public TypeBindingFlags typeBindingFlags;\n\n        public bool withCodegen => cs.enabled || tsDeclare.enabled;\n\n        public CodeGenerator(BindingManager bindingManager, TypeBindingFlags typeBindingFlags)\n        {\n            this.typeBindingFlags = typeBindingFlags;\n            this.bindingManager = bindingManager;\n            var tab = this.bindingManager.prefs.tab;\n            var newline = this.bindingManager.prefs.newline;\n\n            bindResult = new JSBindResult();\n            cs = new TextGenerator(newline, tab);\n            tsDeclare = new TextGenerator(newline, tab, bindingManager.prefs.tsdSizeThreshold);\n        }\n\n        public void Clear()\n        {\n            cs.Clear();\n            // if (!bindingManager.prefs.singleTSD)\n            // {\n            //     tsDeclare.Clear();\n            // }\n        }\n\n        public void GenRegistrationCodeForTypeCaster(MethodInfo methodInfo, int indexOfRegardingType)\n        {\n            var declaringType = methodInfo.DeclaringType;\n            if (declaringType != typeof(Values))\n            {\n                var ps = methodInfo.GetParameters();\n                var pattern = bindingManager.GetCSTypeFullName(ps[indexOfRegardingType].ParameterType, true);\n                cs.AppendLine(\"Values.register_type_caster<{0}>({1});\", pattern, bindingManager.GetCSTypeFullName(methodInfo));\n            }\n        }\n\n        public void GenerateBindingList(string @namespace, string className, IEnumerable<IGrouping<string, TypeBindingInfo>> modules, bool writeModules, ICollection<RawTypeBindingInfo> rawTypes)\n        {\n            this.cs.enabled = (typeBindingFlags & TypeBindingFlags.BindingCode) != 0;\n            this.tsDeclare.enabled = (typeBindingFlags & TypeBindingFlags.TypeDefinition) != 0;\n\n            if (!withCodegen)\n            {\n                return;\n            }\n\n            using (new CSDebugCodeGen(this))\n            {\n                using (new CSPlatformCodeGen(this, TypeBindingFlags.Default))\n                {\n                    using (new CSTopLevelCodeGen(this, CodeGenerator.NameOfBindingList)) // just comments\n                    {\n                        using (new CSNamespaceCodeGen(this, @namespace, \"ScriptRuntime = QuickJS.ScriptRuntime\"))\n                        {\n                            using (new PreservedCodeGen(this))\n                            {\n                                using (new PlainClassCodeGen(this, className, false))\n                                {\n                                    this.cs.AppendLine(\"public const uint CodeGenVersion = {0};\", ScriptEngine.VERSION);\n                                    this.cs.AppendLine(\"public const string Vendor = \\\"{0}\\\";\", this.bindingManager.prefs.vendor);\n\n                                    var runtimeVarName = \"runtime\";\n                                    using (var method = new PlainMethodCodeGen(this, $\"private static void {Values.MethodNameOfStaticBinder}(ScriptRuntime {runtimeVarName})\"))\n                                    {\n                                        foreach (var kv in Values._JSCastMap)\n                                        {\n                                            GenRegistrationCodeForTypeCaster(kv.Value, 2);\n                                        }\n\n                                        foreach (var kv in Values._JSRebindMap)\n                                        {\n                                            GenRegistrationCodeForTypeCaster(kv.Value, 2);\n                                        }\n\n                                        foreach (var kv in Values._CSCastMap)\n                                        {\n                                            GenRegistrationCodeForTypeCaster(kv.Value, 1);\n                                        }\n\n                                        foreach (var kv in Values._JSNewMap)\n                                        {\n                                            GenRegistrationCodeForTypeCaster(kv.Value, 2);\n                                        }\n\n                                        var preloadTypes = new List<Type>();\n                                        foreach (var module in modules)\n                                        {\n                                            if (module.Count() > 0)\n                                            {\n                                                var moduleName = string.IsNullOrEmpty(module.Key) ? this.bindingManager.prefs.defaultJSModule : module.Key;\n                                                var moduleVarName = \"module\";\n                                                this.cs.AppendLine($\"{runtimeVarName}.AddStaticModuleProxy(\\\"{moduleName}\\\", ({runtimeVarName}, {moduleVarName}) => \");\n                                                this.bindResult.modules.Add(moduleName);\n\n                                                using (this.cs.TailCallCodeBlockScope())\n                                                {\n                                                    var editorTypesMap = new Dictionary<string, List<TypeBindingInfo>>();\n                                                    foreach (var type in module)\n                                                    {\n                                                        if (type.preload)\n                                                        {\n                                                            preloadTypes.Add(type.type);\n                                                        }\n                                                        var requiredDefinesOfType = type.transform.requiredDefines;\n                                                        if (requiredDefinesOfType != null)\n                                                        {\n                                                            var defs = string.Join(\" && \", from def in requiredDefinesOfType select def);\n                                                            List<TypeBindingInfo> list;\n                                                            if (!editorTypesMap.TryGetValue(defs, out list))\n                                                            {\n                                                                editorTypesMap[defs] = list = new List<TypeBindingInfo>();\n                                                            }\n                                                            list.Add(type);\n                                                        }\n                                                        else\n                                                        {\n                                                            method.AddModuleEntry(moduleName, runtimeVarName, moduleVarName, type);\n                                                        }\n                                                    }\n\n                                                    foreach (var editorTypes in editorTypesMap)\n                                                    {\n                                                        using (new CSEditorOnlyCodeGen(this, editorTypes.Key))\n                                                        {\n                                                            foreach (var type in editorTypes.Value)\n                                                            {\n                                                                method.AddModuleEntry(moduleName, runtimeVarName, moduleVarName, type);\n                                                            }\n                                                        }\n                                                    }\n                                                }\n                                            }\n                                        }\n                                        method.AddStatement(\"{0}.{1}.Bind({2});\", this.bindingManager.prefs.ns, CodeGenerator.NameOfDelegates, runtimeVarName);\n                                        var registerVarName = \"register\";\n                                        using (new CSTypeRegisterScopeCodeGen(this, registerVarName, $\"{runtimeVarName}.GetMainContext()\"))\n                                        {\n                                            // GeneratePreloadTypes\n                                            if (preloadTypes.Count != 0)\n                                            {\n                                                this.cs.AppendLine(\"// preload types begin\");\n                                                foreach (var preloadType in preloadTypes)\n                                                {\n                                                    this.cs.AppendLine(\"{0}.FindPrototypeOf(typeof({1}));\", registerVarName, this.bindingManager.GetCSTypeFullName(preloadType));\n                                                }\n                                                this.cs.AppendLine(\"// preload types end\");\n                                            }\n\n                                            // GenerateRawTypes\n                                            foreach (var rawTypeBindingInfo in rawTypes)\n                                            {\n                                                var transform = bindingManager.TransformType(rawTypeBindingInfo.type);\n                                                using (new CSEditorOnlyCodeGen(this, transform.requiredDefines))\n                                                {\n                                                    var typename = this.bindingManager.GetCSTypeFullName(rawTypeBindingInfo.type);\n                                                    var jsname = rawTypeBindingInfo.jsName;\n                                                    this.cs.AppendLine(\"if (!{0}.IsGlobalRegistered(\\\"{1}\\\"))\", registerVarName, jsname);\n                                                    this.cs.AppendLine(\"{\");\n                                                    this.cs.AddTabLevel();\n                                                    this.cs.AppendLine(\"{0}.Bind({1}, \\\"{2}\\\");\", rawTypeBindingInfo.type.FullName, registerVarName, jsname);\n                                                    this.cs.DecTabLevel();\n                                                    this.cs.AppendLine(\"}\");\n                                                }\n                                            }\n                                        }\n                                    } // func: BindAll\n                                } // class \n                            } // preserved\n                        } // cs-namespace\n                    } // toplevel\n                } // platform\n            } // debug\n\n            this.bindResult.comment = \"this file was generated by CodeGenerator\";\n            if (writeModules && !string.IsNullOrEmpty(this.bindingManager.prefs.jsModulePackInfoPath))\n            {\n                WriteJSON(this.bindingManager.prefs.jsModulePackInfoPath, this.bindResult);\n            }\n        }\n\n        // 生成委托绑定\n        public void Generate(DelegateBridgeBindingInfo[] delegateBindingInfos, List<HotfixDelegateBindingInfo> exportedHotfixDelegates)\n        {\n            this.cs.enabled = (typeBindingFlags & TypeBindingFlags.BindingCode) != 0;\n            this.tsDeclare.enabled = (typeBindingFlags & TypeBindingFlags.TypeDefinition) != 0;\n\n            if (!withCodegen)\n            {\n                return;\n            }\n\n            using (new CSDebugCodeGen(this))\n            {\n                using (new CSPlatformCodeGen(this, TypeBindingFlags.Default))\n                {\n                    using (new CSTopLevelCodeGen(this, CodeGenerator.NameOfDelegates))\n                    {\n                        using (new CSNamespaceCodeGen(this, this.bindingManager.prefs.ns, \"JSDelegateAttribute = QuickJS.JSDelegateAttribute\"))\n                        {\n                            using (new PreservedCodeGen(this))\n                            {\n                                using (new DelegateWrapperCodeGen(this))\n                                {\n                                    for (var i = 0; i < exportedHotfixDelegates.Count; i++)\n                                    {\n                                        var hotfixDelegateBindingInfo = exportedHotfixDelegates[i];\n\n                                        using (new HotfixDelegateCodeGen(this, hotfixDelegateBindingInfo, i))\n                                        {\n                                        }\n                                    }\n\n                                    for (var i = 0; i < delegateBindingInfos.Length; i++)\n                                    {\n                                        var delegateBindingInfo = delegateBindingInfos[i];\n                                        // var nargs = delegateBindingInfo.parameters.Length;\n\n                                        this.bindingManager.OnPreGenerateDelegate(delegateBindingInfo);\n                                        using (new CSEditorOnlyCodeGen(this, delegateBindingInfo.requiredDefines))\n                                        {\n                                            using (new DelegateCodeGen(this, delegateBindingInfo, i))\n                                            {\n                                            }\n                                        }\n                                        this.bindingManager.OnPostGenerateDelegate(delegateBindingInfo);\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        public void Begin()\n        {\n        }\n\n        public void End()\n        {\n        }\n\n        // 生成类型绑定\n        public void Generate(TypeBindingInfo typeBindingInfo)\n        {\n            this.cs.enabled = (typeBindingInfo.bindingFlags & TypeBindingFlags.BindingCode) != 0 && (typeBindingFlags & TypeBindingFlags.BindingCode) != 0;\n            this.tsDeclare.enabled = (typeBindingInfo.bindingFlags & TypeBindingFlags.TypeDefinition) != 0 && (typeBindingFlags & TypeBindingFlags.TypeDefinition) != 0;\n\n            if (!withCodegen)\n            {\n                return;\n            }\n\n            using (new CSDebugCodeGen(this))\n            {\n                using (new CSEditorOnlyCodeGen(this, typeBindingInfo.transform.requiredDefines))\n                {\n                    using (new CSPlatformCodeGen(this, TypeBindingFlags.Default))\n                    {\n                        using (new CSTopLevelCodeGen(this, typeBindingInfo))\n                        {\n                            using (new CSNamespaceCodeGen(this, this.bindingManager.prefs.ns))\n                            {\n                                GenerateInternal(typeBindingInfo);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        private void GenerateInternal(TypeBindingInfo typeBindingInfo)\n        {\n            using (var tsMod = new TSModuleCodeGen(this, typeBindingInfo))\n            {\n                _currentTSModule = tsMod;\n                using (new TSNamespaceCodeGen(this, typeBindingInfo.tsTypeNaming.ns))\n                {\n                    if (typeBindingInfo.IsEnum)\n                    {\n                        using (new EnumCodeGen(this, typeBindingInfo))\n                        {\n                        }\n                    }\n                    else\n                    {\n                        using (new ClassCodeGen(this, typeBindingInfo))\n                        {\n                        }\n                    }\n                }\n                _currentTSModule = null;\n            }\n        }\n\n        public void WriteAllText(string path, string contents)\n        {\n            File.WriteAllText(path, contents);\n            this.bindingManager.Info($\"output file: {path} ({contents.Length})\");\n        }\n\n        private void WriteJSON<T>(string path, T obj)\n        {\n            try\n            {\n                var contents = bindingManager.json.Serialize(obj, true);\n                File.WriteAllText(path, contents);\n                this.bindingManager.Info($\"output file: {path} ({contents.Length})\");\n            }\n            catch (Exception exception)\n            {\n                this.bindingManager.Error(\"write json failed [{0}]: {1}\\n{2}\", typeof(T), path, exception.Message);\n            }\n        }\n\n        private void CopyFile(string srcPath, string dir, string filename)\n        {\n            if (!Directory.Exists(dir))\n            {\n                Directory.CreateDirectory(dir);\n            }\n            File.Copy(srcPath, Path.Combine(dir, filename));\n        }\n\n        // 对参数进行取值, 如果此参数无需取值, 则返回 false\n        // methodBase: (optional) 提供辅助异常信息\n        public bool WriteParameterGetter(ParameterInfo parameter, int index, string argname, MethodBase methodBase)\n        {\n            // 非 out 参数才需要取值\n            var argAssign = !parameter.IsOut || !parameter.ParameterType.IsByRef;\n            return WriteParameterGetter(parameter, index, true, argname, argAssign, methodBase);\n        }\n\n        public bool WriteParameterGetter(ParameterInfo parameter, int index, bool argDecl, string argname, bool argAssign, MethodBase methodBase)\n        {\n            var ptype = parameter.ParameterType;\n            var argTypeStr = this.bindingManager.GetCSTypeFullName(parameter.ParameterType);\n\n            if (argDecl)\n            {\n                this.cs.AppendLine($\"{argTypeStr} {argname};\");\n            }\n\n            if (argAssign)\n            {\n                if (ptype == typeof(Native.JSContext))\n                {\n                    this.cs.AppendLine(\"{0} = ctx;\", argname);\n                    return false;\n                }\n\n                if (ptype == typeof(ScriptContext))\n                {\n                    this.cs.AppendLine(\"{0} = {1}.GetContext(ctx);\", argname, nameof(ScriptEngine));\n                    return false;\n                }\n\n                if (ptype == typeof(Native.JSRuntime))\n                {\n                    this.cs.AppendLine(\"{0} = JSApi.JS_GetRuntime(ctx);\", argname);\n                    return false;\n                }\n\n                if (ptype == typeof(ScriptRuntime))\n                {\n                    this.cs.AppendLine(\"{0} = {1}.GetRuntime(ctx);\", argname, nameof(ScriptEngine));\n                    return false;\n                }\n\n                var isRefWrapper = parameter.ParameterType.IsByRef && !parameter.IsOut;\n\n                // process ref parameter get\n                string getVal;\n                string refValVar = null;\n                if (isRefWrapper)\n                {\n                    refValVar = $\"refVal{index}\";\n                    this.cs.AppendLine(\"var {0} = Values.js_read_wrap(ctx, argv[{1}]);\", refValVar, index);\n                    getVal = refValVar;\n\n                    this.cs.AppendLine(\"if ({0}.IsException())\", refValVar);\n                    using (this.cs.CodeBlockScope())\n                    {\n                        this.cs.AppendLine(\"return {0};\", refValVar);\n                    }\n                }\n                else\n                {\n                    getVal = $\"argv[{index}]\";\n                }\n                var getter = this.bindingManager.GetScriptObjectGetter(ptype, \"ctx\", getVal, argname);\n                this.cs.AppendLine(\"if (!{0})\", getter);\n                using (this.cs.CodeBlockScope())\n                {\n                    if (isRefWrapper)\n                    {\n                        this.cs.AppendLine(\"JSApi.JS_FreeValue(ctx, {0});\", refValVar);\n                    }\n                    this.WriteParameterException(methodBase, argTypeStr, index);\n                }\n                if (isRefWrapper)\n                {\n                    this.cs.AppendLine(\"JSApi.JS_FreeValue(ctx, {0});\", refValVar);\n                }\n                return true;\n            }\n\n            return true;\n        }\n\n        // type: csharp 方法本身返回值的类型\n        // value: csharp 方法本身的返回值名字\n        public string AppendValuePusher(Type type, string value)\n        {\n            // if (type.IsEnum)\n            // {\n            //     var eType = type.GetEnumUnderlyingType();\n            //     var eTypeName = this.bindingManager.GetCSTypeFullName(eType);\n            //     return $\"{this.bindingManager.GetScriptObjectPusher(eType)}(ctx, ({eTypeName}){value})\";\n            // }\n            // return $\"{this.bindingManager.GetScriptObjectPusher(type)}(ctx, {value})\";\n            return this.bindingManager.GetScriptObjectPusher(type, \"ctx\", value);\n        }\n\n        public string AppendMethodReturnValuePusher(MethodBase method, Type returnType, string value)\n        {\n            // var transform = bindingManager.GetTypeTransform(method.DeclaringType);\n            // if (transform != null)\n            // {\n            //     var mrp = transform.GetMethodReturnPusher(method);\n            //     if (mrp != null)\n            //     {\n            //         return $\"{mrp}(ctx, {value})\";\n            //     }\n            // }\n            // if (returnType.IsEnum)\n            // {\n            //     var eType = returnType.GetEnumUnderlyingType();\n            //     var eTypeName = this.bindingManager.GetCSTypeFullName(eType);\n            //     return $\"{this.bindingManager.GetScriptObjectPusher(eType)}(ctx, ({eTypeName}){value})\";\n            // }\n            // return $\"{this.bindingManager.GetScriptObjectPusher(returnType)}(ctx, {value})\";\n            return this.bindingManager.GetScriptObjectPusher(returnType, \"ctx\", value);\n        }\n\n        public string AppendGetThisCS(FieldBindingInfo bindingInfo)\n        {\n            return AppendGetThisCS(bindingInfo.isStatic, bindingInfo.fieldInfo.DeclaringType);\n        }\n\n        public string AppendGetThisCS(DelegateBindingInfo bindingInfo)\n        {\n            return AppendGetThisCS(bindingInfo.isStatic, bindingInfo.declaringType);\n        }\n\n        public string AppendGetThisCS(EventBindingInfo bindingInfo)\n        {\n            var isStatic = bindingInfo.isStatic;\n            var declaringType = bindingInfo.declaringType;\n            var caller = \"\";\n            if (isStatic)\n            {\n                caller = this.bindingManager.GetCSTypeFullName(declaringType, false);\n            }\n            else\n            {\n                caller = \"self\";\n                this.cs.AppendLine($\"{this.bindingManager.GetCSTypeFullName(declaringType)} {caller};\");\n                var getter = this.bindingManager.GetScriptObjectGetter(declaringType, \"ctx\", \"this_obj\", caller);\n                this.cs.AppendLine(\"{0};\", getter);\n            }\n            return caller;\n        }\n\n        public string AppendGetThisCS(MethodBase method, bool asExtensionAnyway, out Type thisType)\n        {\n            if (method.IsConstructor)\n            {\n                thisType = null;\n                return null;\n            }\n\n            if (asExtensionAnyway)\n            {\n                var parameters = method.GetParameters();\n                thisType = parameters[0].ParameterType;\n                return AppendGetThisCS(false, parameters[0].ParameterType);\n            }\n\n            thisType = method.DeclaringType;\n            return AppendGetThisCS(method.IsStatic, method.DeclaringType);\n        }\n\n        public string AppendGetThisCS(bool isStatic, Type declaringType)\n        {\n            var caller = \"\";\n            if (isStatic)\n            {\n                caller = this.bindingManager.GetCSTypeFullName(declaringType, false);\n            }\n            else\n            {\n                caller = \"self\";\n                if (this.cs.enabled)\n                {\n                    this.cs.AppendLine($\"{this.bindingManager.GetCSTypeFullName(declaringType)} {caller};\");\n                    var getter = this.bindingManager.GetScriptObjectGetter(declaringType, \"ctx\", \"this_obj\", caller);\n                    this.cs.AppendLine(\"if (!{0})\", getter);\n                    using (this.cs.CodeBlockScope())\n                    {\n                        this.cs.AppendLine(\"throw new ThisBoundException();\");\n                    }\n                }\n            }\n            return caller;\n        }\n\n        public string AppendGetArgCount(bool isVararg)\n        {\n            if (isVararg)\n            {\n                var varName = \"argc\";\n                return varName;\n            }\n            return null;\n        }\n\n        public void AppendJSDoc(Type type)\n        {\n            if (bindingManager.prefs.genTypescriptDoc && this.tsDeclare.enabled)\n            {\n                var doc = this.GetDocBody(type);\n                if (doc != null)\n                {\n                    AppendJSDoc(doc);\n                    return;\n                }\n\n                var jsdoc = Attribute.GetCustomAttribute(type, typeof(JSDocAttribute), false) as JSDocAttribute;\n                if (jsdoc != null)\n                {\n                    AppendJSDoc(jsdoc.lines);\n                }\n            }\n        }\n\n        public void AppendJSDoc(PropertyInfo propertyInfo)\n        {\n            if (bindingManager.prefs.genTypescriptDoc && this.tsDeclare.enabled)\n            {\n                var doc = this.GetDocBody(propertyInfo);\n                if (doc != null)\n                {\n                    AppendJSDoc(doc);\n                    return;\n                }\n\n                var jsdoc = Attribute.GetCustomAttribute(propertyInfo, typeof(JSDocAttribute), false) as JSDocAttribute;\n                if (jsdoc != null)\n                {\n                    AppendJSDoc(jsdoc.lines);\n                }\n            }\n        }\n\n        public void AppendJSDoc(FieldInfo fieldInfo)\n        {\n            if (bindingManager.prefs.genTypescriptDoc && this.tsDeclare.enabled)\n            {\n                var doc = this.GetDocBody(fieldInfo);\n                if (doc != null)\n                {\n                    AppendJSDoc(doc);\n                    return;\n                }\n\n                var jsdoc = Attribute.GetCustomAttribute(fieldInfo, typeof(JSDocAttribute), false) as JSDocAttribute;\n                if (jsdoc != null)\n                {\n                    AppendJSDoc(jsdoc.lines);\n                }\n            }\n        }\n\n        public void AppendEnumJSDoc(Type type, object value)\n        {\n            if (bindingManager.prefs.genTypescriptDoc && this.tsDeclare.enabled)\n            {\n                var resolver = this.GetResolver(type.Assembly);\n                var doc = resolver.GetFieldDocBody(type.FullName + \".\" + Enum.GetName(type, value));\n                if (doc != null)\n                {\n                    AppendJSDoc(doc);\n                    return;\n                }\n            }\n        }\n\n        public void AppendJSDoc<T>(T methodInfo)\n        where T : MethodBase\n        {\n            if (bindingManager.prefs.genTypescriptDoc && this.tsDeclare.enabled)\n            {\n                var doc = this.GetDocBody(methodInfo);\n                if (doc != null)\n                {\n                    AppendJSDoc(doc);\n                    return;\n                }\n\n                var jsdoc = Attribute.GetCustomAttribute(methodInfo, typeof(JSDocAttribute), false) as JSDocAttribute;\n                if (jsdoc != null)\n                {\n                    AppendJSDoc(jsdoc.lines);\n                }\n            }\n        }\n\n        public void AppendJSDoc(DocResolver.DocBody body)\n        {\n            if (body.summary != null && body.summary.Length > 1)\n            {\n                this.tsDeclare.AppendLine(\"/**\");\n                foreach (var line in body.summary)\n                {\n                    this.tsDeclare.AppendLine(\" * {0}\", line.Replace('\\r', ' '));\n                }\n            }\n            else\n            {\n                if (body.summary == null || body.summary.Length == 0 || string.IsNullOrEmpty(body.summary[0]))\n                {\n                    if (body.parameters.Count == 0 && string.IsNullOrEmpty(body.returns))\n                    {\n                        return;\n                    }\n\n                    this.tsDeclare.AppendLine(\"/**\");\n                }\n                else\n                {\n                    this.tsDeclare.AppendLine(\"/** {0}\", body.summary[0]);\n                }\n            }\n\n            if (body.parameters != null)\n            {\n                foreach (var kv in body.parameters)\n                {\n                    var pname = kv.Key;\n                    var ptext = kv.Value;\n                    this.tsDeclare.AppendLine($\" * @param {pname} {ptext}\");\n                }\n            }\n\n            if (!string.IsNullOrEmpty(body.returns))\n            {\n                this.tsDeclare.AppendLine($\" * @returns {body.returns}\");\n            }\n\n            this.tsDeclare.AppendLine(\" */\");\n        }\n\n        public void AppendJSDoc(string[] lines)\n        {\n            if (lines != null && lines.Length > 0)\n            {\n                if (lines.Length > 1)\n                {\n                    this.tsDeclare.AppendLine(\"/**\");\n                    foreach (var line in lines)\n                    {\n                        this.tsDeclare.AppendLine(\" * {0}\", line.Replace('\\r', ' '));\n                    }\n                }\n                else\n                {\n                    this.tsDeclare.AppendLine(\"/** {0}\", lines[0]);\n                }\n                this.tsDeclare.AppendLine(\" */\");\n            }\n        }\n\n        public void WriteParameterException(MethodBase methodBase, Type argType, int argIndex)\n        {\n            WriteParameterException(methodBase.DeclaringType, methodBase.Name, argType, argIndex);\n        }\n\n        public void WriteParameterException(MethodBase methodBase, string argTypeStr, int argIndex)\n        {\n            if (methodBase != null)\n            {\n                WriteParameterException(methodBase.DeclaringType, methodBase.Name, argTypeStr, argIndex);\n            }\n            else\n            {\n                WriteParameterException(\"?\", \"?\", argTypeStr, argIndex);\n            }\n        }\n\n        public void WriteParameterException(Type argType, int argIndex)\n        {\n            var argTypeStr = this.bindingManager.GetCSTypeFullName(argType);\n            WriteParameterException(argTypeStr, argIndex);\n        }\n\n        public void WriteParameterException(string argTypeStr, int argIndex)\n        {\n            this.cs.AppendLine(\"throw new ParameterException(typeof({0}), {1});\", argTypeStr, argIndex);\n        }\n\n        public void WriteParameterException(Type caller, string method, Type argType, int argIndex)\n        {\n            var callerStr = this.bindingManager.GetCSTypeFullName(caller);\n            var argTypeStr = this.bindingManager.GetCSTypeFullName(argType);\n            WriteParameterException(callerStr, method, argTypeStr, argIndex);\n        }\n\n        public void WriteParameterException(Type caller, string method, string argTypeStr, int argIndex)\n        {\n            var callerStr = this.bindingManager.GetCSTypeFullName(caller);\n            WriteParameterException(callerStr, method, argTypeStr, argIndex);\n        }\n\n        public void WriteParameterException(string callerStr, string method, string argTypeStr, int argIndex)\n        {\n            this.cs.AppendLine(\"throw new ParameterException(typeof({0}), \\\"{1}\\\", typeof({2}), {3});\", callerStr, method, argTypeStr, argIndex);\n        }\n    }\n}\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenerator.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: f027cd41976eb314f947ae8e49d7c264\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenerator_Doc.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing System.Reflection;\r\nusing System.IO;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public partial class CodeGenerator\r\n    {\r\n        private Dictionary<Assembly, DocResolver> _resolvers = new Dictionary<Assembly, DocResolver>();\r\n\r\n        public DocResolver GetResolver(Assembly assembly)\r\n        {\r\n            DocResolver resolver;\r\n            if (!_resolvers.TryGetValue(assembly, out resolver))\r\n            {\r\n                resolver = _resolvers[assembly] = new DocResolver();\r\n                if (!LoadXmlDocFrom(resolver, assembly.Location))\r\n                {\r\n                    var fi = new FileInfo(assembly.Location);\r\n                    LoadXmlDocFrom(resolver, Path.Combine(bindingManager.prefs.xmlDocDir, fi.Name));\r\n                }\r\n            }\r\n            return resolver;\r\n        }\r\n\r\n        public bool LoadXmlDocFrom(DocResolver resolver, string location)\r\n        {\r\n            try\r\n            {\r\n                var ext = Path.GetExtension(location);\r\n                var xmlFilePath = location.Substring(0, location.Length - ext.Length) + \".xml\";\r\n\r\n                return resolver.ParseXml(xmlFilePath);\r\n            }\r\n            catch (Exception)\r\n            {\r\n                return false;\r\n            }\r\n        }\r\n\r\n        public DocResolver.DocBody GetDocBody(Type type)\r\n        {\r\n            return GetResolver(type.Assembly).GetDocBody(type);\r\n        }\r\n\r\n        public DocResolver.DocBody GetDocBody<T>(T methodBase)\r\n        where T : MethodBase\r\n        {\r\n            return GetResolver(methodBase.DeclaringType.Assembly).GetDocBody(methodBase);\r\n        }\r\n\r\n        public DocResolver.DocBody GetDocBody(FieldInfo fieldInfo)\r\n        {\r\n            return GetResolver(fieldInfo.DeclaringType.Assembly).GetDocBody(fieldInfo);\r\n        }\r\n\r\n        public DocResolver.DocBody GetDocBody(PropertyInfo propertyInfo)\r\n        {\r\n            return GetResolver(propertyInfo.DeclaringType.Assembly).GetDocBody(propertyInfo);\r\n        }\r\n\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/CodeGenerator_Doc.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 94d186772749d07438f9ad85fd80178a\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/TSModuleCodeGen.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.Linq;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public class TSModuleCodeGen : IDisposable\r\n    {\r\n        protected CodeGenerator cg;\r\n        protected TypeBindingInfo typeBindingInfo;\r\n\r\n        protected static HashSet<Type> _noImportTypes = new HashSet<Type>(new Type[]\r\n        {\r\n            typeof(void),\r\n            typeof(string),\r\n            typeof(Delegate),\r\n        });\r\n\r\n        /// <summary>\r\n        /// current module name\r\n        /// </summary>\r\n        protected readonly string moduleName;\r\n\r\n        protected TSModuleBindingInfo moduleBindingInfo;\r\n\r\n        public class ModuleInfo\r\n        {\r\n            /// <summary>\r\n            /// a name map for all referenced types from other modules <br/>\r\n            /// entry-name => alias-name \r\n            /// </summary>\r\n            public Dictionary<string, string> alias = new Dictionary<string, string>();\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// all referenced modules <br/>\r\n        /// module-name => module-info\r\n        /// </summary>\r\n        protected Dictionary<string, ModuleInfo> _modules = new Dictionary<string, ModuleInfo>();\r\n\r\n        /// <summary>\r\n        /// records of unique local names for all referenced types from other modules\r\n        /// </summary>\r\n        protected HashSet<string> _uniqueNames = new HashSet<string>();\r\n\r\n        public TSModuleCodeGen(CodeGenerator cg, TypeBindingInfo typeBindingInfo)\r\n        {\r\n            this.cg = cg;\r\n            this.typeBindingInfo = typeBindingInfo;\r\n            this.moduleName = typeBindingInfo.tsTypeNaming.moduleName;\r\n            this.moduleBindingInfo = cg.bindingManager.GetExportedTSModule(this.moduleName);\r\n\r\n            this.cg.tsDeclare.BeginPart();\r\n            this.cg.tsDeclare.AppendLine($\"declare module \\\"{GetModuleName(this.moduleName)}\\\" {{\");\r\n            this.cg.tsDeclare.AddTabLevel();\r\n\r\n            CollectImports();\r\n            WriteImports();\r\n        }\r\n\r\n        private string GetModuleName(string rawModuleName)\r\n        {\r\n            return string.IsNullOrEmpty(rawModuleName) ? cg.bindingManager.prefs.defaultJSModule : rawModuleName;\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n            this.cg.tsDeclare.DecTabLevel();\r\n            this.cg.tsDeclare.AppendLine(\"}\");\r\n            this.cg.tsDeclare.EndPart();\r\n        }\r\n\r\n        private void CollectImports()\r\n        {\r\n            if (typeBindingInfo.super != typeof(Enum))\r\n            {\r\n                AddModuleAlias(typeBindingInfo.super);\r\n            }\r\n\r\n            foreach (var @interface in typeBindingInfo.interfaces)\r\n            {\r\n                AddModuleAlias(@interface);\r\n            }\r\n\r\n            foreach (var entry in typeBindingInfo.fields)\r\n            {\r\n                AddModuleAlias(entry.Value.fieldType);\r\n            }\r\n\r\n            foreach (var entry in typeBindingInfo.properties)\r\n            {\r\n                AddModuleAlias(entry.Value.propertyType);\r\n            }\r\n\r\n            foreach (var entry in typeBindingInfo.events)\r\n            {\r\n                AddModuleAlias(entry.Value.eventInfo.EventHandlerType);\r\n            }\r\n\r\n            // process all type references in delegates\r\n            foreach (var @delegate in typeBindingInfo.delegates)\r\n            {\r\n                AddModuleAlias(@delegate.Value.delegateType);\r\n            }\r\n\r\n            // process all type references in constructors\r\n            foreach (var entryVariant in typeBindingInfo.constructors.variants)\r\n            {\r\n                foreach (var method in entryVariant.Value.plainMethods)\r\n                {\r\n                    foreach (var p in method.method.GetParameters())\r\n                    {\r\n                        AddModuleAlias(p);\r\n                    }\r\n                }\r\n\r\n                foreach (var method in entryVariant.Value.varargMethods)\r\n                {\r\n                    foreach (var p in method.method.GetParameters())\r\n                    {\r\n                        AddModuleAlias(p);\r\n                    }\r\n                }\r\n            }\r\n\r\n            // process all type references in methods\r\n            var methods = typeBindingInfo.staticMethods.Select(s => s.Value)\r\n                .Concat(typeBindingInfo.methods.Select(s => s.Value));\r\n\r\n            foreach (var entry in methods)\r\n            {\r\n                foreach (var entryVariant in entry.variants)\r\n                {\r\n                    foreach (var method in entryVariant.Value.plainMethods)\r\n                    {\r\n                        AddModuleAlias(method.method.ReturnType);\r\n                        foreach (var p in method.method.GetParameters())\r\n                        {\r\n                            AddModuleAlias(p);\r\n                        }\r\n                    }\r\n\r\n                    foreach (var method in entryVariant.Value.varargMethods)\r\n                    {\r\n                        AddModuleAlias(method.method.ReturnType);\r\n                        foreach (var p in method.method.GetParameters())\r\n                        {\r\n                            AddModuleAlias(p);\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        private void WriteImports()\r\n        {\r\n            // always import jsb for simplicity (ref, out, Nullable<>, byte)\r\n            this.cg.tsDeclare.AppendLine($\"import * as jsb from \\\"jsb\\\";\");\r\n\r\n            foreach (var me in _modules)\r\n            {\r\n                var moduleName = me.Key;\r\n                var moduleInfo = me.Value;\r\n                var count = moduleInfo.alias.Count;\r\n\r\n                if (count > 0)\r\n                {\r\n                    var index = 0;\r\n\r\n                    this.cg.tsDeclare.Append($\"import {{ \");\r\n                    foreach (var pair in moduleInfo.alias)\r\n                    {\r\n                        var entry = pair.Key;\r\n                        var alias = pair.Value;\r\n\r\n                        if (entry != alias)\r\n                        {\r\n                            this.cg.tsDeclare.AppendL($\"{entry} as {alias}\");\r\n                        }\r\n                        else\r\n                        {\r\n                            this.cg.tsDeclare.AppendL($\"{entry}\");\r\n                        }\r\n\r\n                        if (index != count - 1)\r\n                        {\r\n                            this.cg.tsDeclare.AppendL(\", \");\r\n                        }\r\n                        ++index;\r\n                    }\r\n                    this.cg.tsDeclare.AppendL($\" }} from \\\"{GetModuleName(moduleName)}\\\";\");\r\n                    this.cg.tsDeclare.AppendLine();\r\n                }\r\n            }\r\n        }\r\n\r\n        private void AddModuleAlias(ParameterInfo p)\r\n        {\r\n            AddModuleAlias(p.IsDefined(typeof(ParamArrayAttribute)) ? p.ParameterType.GetElementType() : p.ParameterType);\r\n        }\r\n\r\n        //TODO hardcoded, refactor it later\r\n        private string GetCSharpArray()\r\n        {\r\n            var prefs = typeBindingInfo.bindingManager.prefs;\r\n            if (prefs.GetModuleStyle() == ETSModuleStyle.Singular)\r\n            {\r\n                return \"System.Array\";\r\n            }\r\n            return \"Array\";\r\n        }\r\n\r\n        private void AddBuiltinModuleAlias(string topLevel, string typeName)\r\n        {\r\n            var prefs = typeBindingInfo.bindingManager.prefs;\r\n            if (prefs.GetModuleStyle() == ETSModuleStyle.Singular)\r\n            {\r\n                AddModuleAlias(prefs.singularModuleName, topLevel);\r\n            }\r\n            else\r\n            {\r\n                AddModuleAlias(topLevel, typeName);\r\n            }\r\n        }\r\n\r\n        private void AddModuleAlias(Type originalType)\r\n        {\r\n            if (originalType == null || originalType.IsPrimitive || _noImportTypes.Contains(originalType))\r\n            {\r\n                return;\r\n            }\r\n\r\n            if (originalType == typeof(Enum))\r\n            {\r\n                AddBuiltinModuleAlias(\"System\", \"Enum\");\r\n                return;\r\n            }\r\n\r\n            if (originalType.IsArray)\r\n            {\r\n                AddBuiltinModuleAlias(\"System\", \"Array\");\r\n                AddModuleAlias(originalType.GetElementType());\r\n                return;\r\n            }\r\n\r\n            if (originalType.IsByRef)\r\n            {\r\n                AddModuleAlias(originalType.GetElementType());\r\n                return;\r\n            }\r\n\r\n            if (originalType.IsGenericType && !originalType.IsGenericTypeDefinition)\r\n            {\r\n                foreach (var g in originalType.GetGenericArguments())\r\n                {\r\n                    AddModuleAlias(g);\r\n                }\r\n\r\n                AddModuleAlias(originalType.GetGenericTypeDefinition());\r\n                return;\r\n            }\r\n\r\n            var tsTypeNaming = cg.bindingManager.GetTSTypeNaming(originalType);\r\n            if (tsTypeNaming != null)\r\n            {\r\n                // 避免引入自身\r\n                if (tsTypeNaming.moduleName != this.typeBindingInfo.tsTypeNaming.moduleName)\r\n                {\r\n                    AddModuleAlias(tsTypeNaming.moduleName, tsTypeNaming.moduleEntry);\r\n                }\r\n            }\r\n            else\r\n            {\r\n                var delegateBindingInfo = this.cg.bindingManager.GetDelegateBindingInfo(originalType);\r\n\r\n                if (delegateBindingInfo != null)\r\n                {\r\n                    AddModuleAlias(delegateBindingInfo.returnType);\r\n                    foreach (var p in delegateBindingInfo.parameters)\r\n                    {\r\n                        AddModuleAlias(p.ParameterType);\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    var exported = this.cg.bindingManager.GetExportedTypeRecursively(originalType);\r\n                    if (exported != null && exported.type != originalType)\r\n                    {\r\n                        AddModuleAlias(exported.type);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        private void AddModuleAlias(string moduleName, string moduleEntry)\r\n        {\r\n            // 手工添加的模块访问需要过滤掉本模块自身 \r\n            // 例如: AddModuleAlias(\"System\", \"Array\")\r\n            if (moduleName == this.moduleName)\r\n            {\r\n                return;\r\n            }\r\n\r\n            ModuleInfo reg;\r\n            if (!_modules.TryGetValue(moduleName, out reg))\r\n            {\r\n                reg = _modules[moduleName] = new ModuleInfo();\r\n            }\r\n\r\n            if (!reg.alias.ContainsKey(moduleEntry))\r\n            {\r\n                var uniqueName = GetUniqueAccess(moduleEntry);\r\n                reg.alias.Add(moduleEntry, uniqueName);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Generate a unique name for referencing in the current module. \r\n        /// The given name will be renamed with a number suffix if a type with the same name exists or it's already been generated before.\r\n        /// </summary>\r\n        private string GetUniqueAccess(string uname, int index = 0)\r\n        {\r\n            var rename = index == 0 ? uname : uname + index;\r\n\r\n            if (this.moduleBindingInfo.Contains(rename) || _uniqueNames.Contains(rename))\r\n            {\r\n                return GetUniqueAccess(uname, index + 1);\r\n            }\r\n\r\n            _uniqueNames.Add(rename);\r\n            return rename;\r\n        }\r\n\r\n        public string GetAlias(ITSTypeNaming tsTypeNaming)\r\n        {\r\n            // var tsTypeNaming = this.cg.bindingManager.GetTSTypeNaming(type);\r\n            ModuleInfo moduleInfo;\r\n            if (_modules.TryGetValue(tsTypeNaming.moduleName, out moduleInfo))\r\n            {\r\n                string alias;\r\n                if (moduleInfo.alias.TryGetValue(tsTypeNaming.moduleEntry, out alias))\r\n                {\r\n                    return alias;\r\n                }\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        // 获取 type 在 typescript 中对应类型名\r\n        public string GetTSTypeFullName(Type type)\r\n        {\r\n            return GetTSTypeFullName(type, false);\r\n        }\r\n\r\n        public string GetTSTypeFullName(ParameterInfo p)\r\n        {\r\n            return GetTSTypeFullName(p.ParameterType, p.IsOut);\r\n        }\r\n\r\n        public string GetTSTypeFullName(Type type, bool isOut)\r\n        {\r\n            if (type == null || type == typeof(void))\r\n            {\r\n                return \"void\";\r\n            }\r\n\r\n            if (type.IsByRef)\r\n            {\r\n                if (isOut)\r\n                {\r\n                    return $\"{this.cg.bindingManager.GetDefaultTypePrefix()}Out<{GetTSTypeFullName(type.GetElementType())}>\";\r\n                }\r\n                return $\"{this.cg.bindingManager.GetDefaultTypePrefix()}Ref<{GetTSTypeFullName(type.GetElementType())}>\";\r\n                // return GetTSTypeFullName(type.GetElementType());\r\n            }\r\n\r\n            List<string> names;\r\n            if (this.cg.bindingManager.GetTSTypeNameMap(type, out names))\r\n            {\r\n                return names.Count > 1 ? $\"({String.Join(\" | \", names)})\" : names[0];\r\n            }\r\n\r\n            if (type == typeof(Array))\r\n            {\r\n                return GetCSharpArray() + \"<any>\";\r\n            }\r\n\r\n            if (type == typeof(ScriptPromise))\r\n            {\r\n                return \"Promise<void>\";\r\n            }\r\n\r\n            if (type.IsSubclassOf(typeof(ScriptPromise)))\r\n            {\r\n                if (type.IsGenericType)\r\n                {\r\n                    var gt = type.GetGenericArguments()[0];\r\n                    return \"Promise<\" + GetTSTypeFullName(gt) + \">\";\r\n                }\r\n                return \"Promise<any>\";\r\n            }\r\n\r\n            if (type.IsArray)\r\n            {\r\n                var elementType = type.GetElementType();\r\n                var tsFullName = GetTSTypeFullName(elementType);\r\n                var rank = type.GetArrayRank();\r\n\r\n                if (rank == 1)\r\n                {\r\n                    return GetCSharpArray() + \"<\" + tsFullName + \">\";\r\n                }\r\n                return GetCSharpArray() + \"<\" + tsFullName + \", \" + rank + \">\";\r\n            }\r\n\r\n            var info = this.cg.bindingManager.GetExportedType(type);\r\n            if (info != null)\r\n            {\r\n                var tsTypeNaming = info.tsTypeNaming;\r\n                var localAlias = GetAlias(tsTypeNaming);\r\n\r\n                if (type.IsGenericType)\r\n                {\r\n                    if (type.IsGenericTypeDefinition)\r\n                    {\r\n                        var joinedArgs = string.Join(\", \", from arg in type.GetGenericArguments() select arg.Name);\r\n                        var typeName = tsTypeNaming.GetFullName(localAlias);\r\n                        return $\"{typeName}<{joinedArgs}>\";\r\n                    }\r\n                    else\r\n                    {\r\n                        var gType = type.GetGenericTypeDefinition();\r\n                        var gTypeInfo = this.cg.bindingManager.GetExportedType(gType);\r\n                        if (gTypeInfo != null)\r\n                        {\r\n                            var tArgs = type.GetGenericArguments();\r\n                            var tArgCount = tArgs.Length;\r\n                            var templateArgs = new string[tArgCount];\r\n                            var typeName = gTypeInfo.tsTypeNaming.GetFullName(localAlias);\r\n\r\n                            for (int i = 0; i < tArgCount; i++)\r\n                            {\r\n                                templateArgs[i] = GetTSTypeFullName(tArgs[i]);\r\n                            }\r\n\r\n                            var joinedArgs = CodeGenUtils.Join(\", \", templateArgs);\r\n                            return $\"{typeName}<{joinedArgs}>\";\r\n                        }\r\n                    }\r\n                }\r\n\r\n                return tsTypeNaming.GetFullName(localAlias);\r\n            }\r\n\r\n            if (type.BaseType == typeof(MulticastDelegate))\r\n            {\r\n                var delegateBindingInfo = this.cg.bindingManager.GetDelegateBindingInfo(type);\r\n                if (delegateBindingInfo != null)\r\n                {\r\n                    var ret = GetTSTypeFullName(delegateBindingInfo.returnType);\r\n                    var v_arglist = GetTSArglistTypes(delegateBindingInfo.parameters);\r\n                    return $\"({v_arglist}) => {ret}\";\r\n                }\r\n            }\r\n\r\n            if (type.IsGenericType)\r\n            {\r\n                if (type.GetGenericTypeDefinition() == typeof(Nullable<>))\r\n                {\r\n                    var gArgs = type.GetGenericArguments();\r\n                    var gArgsTS = GetTSTypeFullName(gArgs[0]);\r\n                    return $\"{this.cg.bindingManager.GetDefaultTypePrefix()}Nullable<{gArgsTS}>\";\r\n                }\r\n            }\r\n            else\r\n            {\r\n                if (type.IsGenericParameter)\r\n                {\r\n                    return type.Name;\r\n                }\r\n            }\r\n\r\n            return \"any\";\r\n        }\r\n\r\n        // 生成参数对应的字符串形式参数列表定义 (typescript)\r\n        public string GetTSArglistTypes(ParameterInfo[] parameters)\r\n        {\r\n            var size = parameters.Length;\r\n            var arglist = \"\";\r\n            if (size == 0)\r\n            {\r\n                return arglist;\r\n            }\r\n            for (var i = 0; i < size; i++)\r\n            {\r\n                var parameter = parameters[i];\r\n                var typename = GetTSTypeFullName(parameter);\r\n                arglist += BindingManager.GetTSVariable(parameter.Name) + \": \";\r\n                arglist += typename;\r\n                if (i != size - 1)\r\n                {\r\n                    arglist += \", \";\r\n                }\r\n            }\r\n            return arglist;\r\n        }\r\n\r\n        // 获取实现的接口的ts声明\r\n        public string GetTSInterfaceNames(Type type)\r\n        {\r\n            var interfaces = type.GetInterfaces();\r\n            var str = \"\";\r\n\r\n            foreach (var @interface in interfaces)\r\n            {\r\n                var interfaceBindingInfo = this.cg.bindingManager.GetExportedType(@interface);\r\n                if (interfaceBindingInfo != null)\r\n                {\r\n                    // Debug.Log($\"{type.Name} implements {@interface.Name}\");\r\n                    str = CodeGenUtils.Join(\", \", str, GetTSTypeFullName(interfaceBindingInfo.type));\r\n                }\r\n            }\r\n\r\n            return str;\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/TSModuleCodeGen.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: ccd29405372243b42b9138515a824c03\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/TSModuleStyle.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public enum ETSModuleStyle\r\n    {\r\n        Legacy, \r\n        Singular, \r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen/TSModuleStyle.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 814265c184c5a4641b3873d9a6ee3fd7\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Codegen.meta",
    "content": "fileFormatVersion: 2\nguid: 99b17e5da711b1240a94fc58846cd122\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/DefaultBindingLogger.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nnamespace QuickJS.Binding\r\n{\r\n    public class DefaultBindingLogger : IBindingLogger\r\n    {\r\n        public DefaultBindingLogger() { }\r\n\r\n        public void Log(string message) => Diagnostics.Logger.Binding.Info(message);\r\n\r\n        public void LogWarning(string message) => Diagnostics.Logger.Binding.Warning(message);\r\n\r\n        public void LogError(string message) => Diagnostics.Logger.Binding.Error(message);\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/DefaultBindingLogger.cs.meta",
    "content": "fileFormatVersion: 2\nguid: eb374b25558bd674a8d7a3e5a64ed879\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/DelegateBridgeBindingInfo.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Text.RegularExpressions;\n\nnamespace QuickJS.Binding\n{\n    public class DelegateBridgeBindingInfo\n    {\n        // set of delegate types\n        public HashSet<Type> types = new HashSet<Type>();\n\n        public Type returnType;\n        public ParameterInfo[] parameters;\n        public string requiredDefines;\n\n        public DelegateBridgeBindingInfo(Type returnType, ParameterInfo[] parameters, string requiredDefines)\n        {\n            this.returnType = returnType;\n            this.parameters = parameters;\n            this.requiredDefines = requiredDefines;\n        }\n\n        public bool Equals(Type returnType, ParameterInfo[] parameters, string requiredDefines)\n        {\n            if (this.requiredDefines != requiredDefines)\n            {\n                return false;\n            }\n            \n            if (returnType != this.returnType || parameters.Length != this.parameters.Length)\n            {\n                return false;\n            }\n\n            for (var i = 0; i < parameters.Length; i++)\n            {\n                if (parameters[i].ParameterType != this.parameters[i].ParameterType)\n                {\n                    return false;\n                }\n\n                if (parameters[i].IsOut != this.parameters[i].IsOut)\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n    }\n}\n\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/DelegateBridgeBindingInfo.cs.meta",
    "content": "fileFormatVersion: 2\nguid: cf644ab671044694ca0297a49596cb74\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/DocResolver.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Text;\r\nusing System.Reflection;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using System.Xml;\r\n\r\n    public class DocResolver\r\n    {\r\n        public class DocBody\r\n        {\r\n            public string name;\r\n            public string[] summary;\r\n            public Dictionary<string, string> parameters = new Dictionary<string, string>();\r\n            public string returns;\r\n        }\r\n\r\n        private StringBuilder _sb = new StringBuilder();\r\n        private Dictionary<string, DocBody> _tdocs = new Dictionary<string, DocBody>();\r\n        private Dictionary<string, DocBody> _pdocs = new Dictionary<string, DocBody>();\r\n        private Dictionary<string, DocBody> _fdocs = new Dictionary<string, DocBody>();\r\n        private Dictionary<string, DocBody> _mdocs = new Dictionary<string, DocBody>();\r\n\r\n        public DocBody GetFieldDocBody(string path)\r\n        {\r\n            DocBody body;\r\n            _fdocs.TryGetValue(path, out body);\r\n            return body;\r\n        }\r\n\r\n        public DocBody GetDocBody(Type type)\r\n        {\r\n            if (type.IsGenericType || type.IsGenericTypeDefinition || !type.IsPublic)\r\n            {\r\n                return null;\r\n            }\r\n            var xName = type.FullName;\r\n            DocBody body;\r\n            _tdocs.TryGetValue(xName, out body);\r\n            return body;\r\n        }\r\n\r\n        public DocBody GetDocBody<T>(T methodBase)\r\n        where T : MethodBase\r\n        {\r\n            if (methodBase.IsGenericMethod || !methodBase.IsPublic || methodBase.ContainsGenericParameters)\r\n            {\r\n                return null;\r\n            }\r\n            var declType = methodBase.DeclaringType;\r\n            _sb.Clear();\r\n            _sb.Append(declType.FullName);\r\n            _sb.Append('.');\r\n            _sb.Append(methodBase.Name);\r\n            _sb.Append('(');\r\n            if (!ExtractMethodParamters(methodBase, _sb))\r\n            {\r\n                return null;\r\n            }\r\n            _sb.Append(')');\r\n            var xName = _sb.ToString();\r\n            DocBody body;\r\n            _mdocs.TryGetValue(xName, out body);\r\n            return body;\r\n        }\r\n\r\n        public DocBody GetDocBody(FieldInfo fieldInfo)\r\n        {\r\n            if (!fieldInfo.IsPublic)\r\n            {\r\n                return null;\r\n            }\r\n            var declType = fieldInfo.DeclaringType;\r\n            var xName = declType.FullName + \".\" + fieldInfo.Name;\r\n            DocBody body;\r\n            _fdocs.TryGetValue(xName, out body);\r\n            return body;\r\n        }\r\n\r\n        public DocBody GetDocBody(PropertyInfo propertyInfo)\r\n        {\r\n            var getMethod = propertyInfo.GetGetMethod(true);\r\n            if (getMethod == null || !getMethod.IsPublic)\r\n            {\r\n                return null;\r\n            }\r\n            var declType = propertyInfo.DeclaringType;\r\n            var xName = declType.FullName + \".\" + propertyInfo.Name;\r\n            DocBody body;\r\n            _pdocs.TryGetValue(xName, out body);\r\n            return body;\r\n        }\r\n\r\n        private bool ExtractMethodParamters<T>(T methodBase, StringBuilder sb)\r\n        where T : MethodBase\r\n        {\r\n            var parameters = methodBase.GetParameters();\r\n            for (int i = 0, size = parameters.Length; i < size; i++)\r\n            {\r\n                var type = parameters[i].ParameterType;\r\n                if (type.IsGenericType)\r\n                {\r\n                    return false;\r\n                }\r\n                sb.Append(type.FullName);\r\n                if (i != size - 1)\r\n                {\r\n                    sb.Append(',');\r\n                }\r\n            }\r\n            return true;\r\n        }\r\n\r\n        private void ParseXmlMember(XmlReader reader, DocBody body, string elementName)\r\n        {\r\n            while (reader.Read())\r\n            {\r\n                var type = reader.NodeType;\r\n\r\n                if (type == XmlNodeType.EndElement && reader.Name == elementName)\r\n                {\r\n                    break;\r\n                }\r\n\r\n                if (type == XmlNodeType.Element && reader.Name == \"summary\")\r\n                {\r\n                    body.summary = ReadTextBlock(reader, body, \"summary\");\r\n                }\r\n\r\n                if (type == XmlNodeType.Element && reader.Name == \"param\")\r\n                {\r\n                    var pname = reader.GetAttribute(\"name\");\r\n                    var ptext = ReadSingleTextBlock(reader, body, \"param\");\r\n                    if (!string.IsNullOrEmpty(ptext))\r\n                    {\r\n                        body.parameters[pname] = ptext;\r\n                    }\r\n                }\r\n\r\n                if (type == XmlNodeType.Element && reader.Name == \"returns\")\r\n                {\r\n                    body.returns = ReadSingleTextBlock(reader, body, \"returns\");\r\n                }\r\n            }\r\n        }\r\n\r\n        private string[] ReadTextBlock(XmlReader reader, DocBody body, string elementName)\r\n        {\r\n            var lines = new List<string>();\r\n\r\n            if (!reader.IsEmptyElement)\r\n            {\r\n                while (reader.Read())\r\n                {\r\n                    var type = reader.NodeType;\r\n                    if (type == XmlNodeType.EndElement && reader.Name == elementName)\r\n                    {\r\n                        break;\r\n                    }\r\n\r\n                    if (type == XmlNodeType.Element && reader.Name == \"para\")\r\n                    {\r\n                        lines.Add(ReadElementContentAsString(reader, body, \"para\"));\r\n                    }\r\n                    else if (type == XmlNodeType.Text || type == XmlNodeType.CDATA)\r\n                    {\r\n                        foreach (var line in reader.Value.Split('\\n'))\r\n                        {\r\n                            var trim = line.Trim();\r\n                            if (trim.Length > 0)\r\n                            {\r\n                                lines.Add(trim);\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            return lines.ToArray();\r\n        }\r\n\r\n        private string ReadElementContentAsString(XmlReader reader, DocBody body, string elementName)\r\n        {\r\n            var text = string.Empty;\r\n            while (reader.Read())\r\n            {\r\n                var type = reader.NodeType;\r\n                if (type == XmlNodeType.EndElement && reader.Name == elementName)\r\n                {\r\n                    break;\r\n                }\r\n                if (type == XmlNodeType.Text)\r\n                {\r\n                    text = reader.Value;\r\n                }\r\n            }\r\n            return text;\r\n        }\r\n\r\n        private string ReadSingleTextBlock(XmlReader reader, DocBody body, string elementName)\r\n        {\r\n            _sb.Clear();\r\n            if (!reader.IsEmptyElement)\r\n            {\r\n                while (reader.Read())\r\n                {\r\n                    var type = reader.NodeType;\r\n                    if (type == XmlNodeType.EndElement && reader.Name == elementName)\r\n                    {\r\n                        break;\r\n                    }\r\n                    if (type == XmlNodeType.Element && reader.Name == \"para\")\r\n                    {\r\n                        _sb.Append(ReadElementContentAsString(reader, body, \"para\"));\r\n                        _sb.Append(' ');\r\n                    }\r\n                    if (type == XmlNodeType.Text)\r\n                    {\r\n                        _sb.Append(reader.Value);\r\n                    }\r\n                }\r\n            }\r\n            return _sb.ToString();\r\n        }\r\n\r\n        public bool ParseXml(string filename)\r\n        {\r\n            if (!File.Exists(filename))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            // Debug.LogFormat(\"read doc: {0}\", filename);\r\n            using (var fs = File.OpenRead(filename))\r\n            {\r\n                using (var reader = XmlReader.Create(fs))\r\n                {\r\n                    while (reader.Read())\r\n                    {\r\n                        var type = reader.NodeType;\r\n                        if (type == XmlNodeType.Element && reader.Name == \"member\")\r\n                        {\r\n                            var body = new DocBody();\r\n                            var name = reader.GetAttribute(\"name\");\r\n                            if (name.Length > 2)\r\n                            {\r\n                                var subname = name.Substring(2);\r\n                                body.name = subname;\r\n                                switch (name[0])\r\n                                {\r\n                                    case 'F': _fdocs[subname] = body; break;\r\n                                    case 'P': _pdocs[subname] = body; break;\r\n                                    case 'M': _mdocs[subname] = body; break;\r\n                                    case 'T': _tdocs[subname] = body; break;\r\n                                }\r\n                            }\r\n                            ParseXmlMember(reader, body, \"member\");\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            return true;\r\n        }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/DocResolver.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 5b3992bd6a31d204e8265148a767724e\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/HotfixDelegateBindingInfo.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\nusing System.Text.RegularExpressions;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public class HotfixDelegateBindingInfo\r\n    {\r\n        public Type returnType;\r\n        public bool isStatic; // 委托针对的是静态函数\r\n        public Type thisType;\r\n        public ParameterInfo[] parameters;\r\n\r\n        public HotfixDelegateBindingInfo(Type thisType, bool isStatic, Type returnType, ParameterInfo[] parameters)\r\n        {\r\n            this.isStatic = isStatic;\r\n            this.thisType = thisType;\r\n            this.returnType = returnType;\r\n            this.parameters = parameters;\r\n        }\r\n\r\n        public bool Equals(Type thisType, bool isStatic, Type returnType, ParameterInfo[] parameters)\r\n        {\r\n            if (thisType != this.thisType)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (isStatic != this.isStatic)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (returnType != this.returnType || parameters.Length != this.parameters.Length)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            for (var i = 0; i < parameters.Length; i++)\r\n            {\r\n                if (parameters[i].ParameterType != this.parameters[i].ParameterType)\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                if (parameters[i].IsOut != this.parameters[i].IsOut)\r\n                {\r\n                    return false;\r\n                }\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/HotfixDelegateBindingInfo.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 46bf60e8adf5916479e97d5a44d2d0f6\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/IBindingProcess.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    // 继承该接口(或 AbstractBindingProcess)的类将在导出过程中执行指定方法, 可以在特定阶段进行特定操作\r\n    public interface IBindingProcess\r\n    {\r\n        // 初始化阶段回调, 可以调用 AddTSMethodDeclaration, AddTSKeywords 等进行定制\r\n        void OnInitialize(BindingManager bindingManager);\r\n\r\n        // 收集 Assembly 阶段, 可在该阶段 AddAssemblies/RemoveAssemblies\r\n        void OnPreCollectAssemblies(BindingManager bindingManager);\r\n\r\n        //\r\n        void OnPostCollectAssemblies(BindingManager bindingManager);\r\n        \r\n        void OnPreExporting(BindingManager bindingManager);\r\n        \r\n        void OnPostExporting(BindingManager bindingManager);\r\n\r\n        // 收集类型阶段开始, 可在该阶段 AddExportedType 增加导出类型\r\n        void OnPreCollectTypes(BindingManager bindingManager);\r\n\r\n        //\r\n        void OnPostCollectTypes(BindingManager bindingManager);\r\n\r\n        // 是否要导出指定类型\r\n        bool OnExportingType(BindingManager bindingManager, Type type);\r\n\r\n        // 生成指定类型绑定代码前\r\n        void OnPreGenerateType(BindingManager bindingManager, TypeBindingInfo bindingInfo);\r\n        \r\n        // 生成指定类型绑定代码后\r\n        void OnPostGenerateType(BindingManager bindingManager, TypeBindingInfo bindingInfo);\r\n        \r\n        // 生成指定Delegate类型的绑定代码前\r\n        void OnPreGenerateDelegate(BindingManager bindingManager, DelegateBridgeBindingInfo bindingInfo);\r\n\r\n        // 生成指定Delegate类型的绑定代码后\r\n        void OnPostGenerateDelegate(BindingManager bindingManager, DelegateBridgeBindingInfo bindingInfo);\r\n        \r\n        // 完成默认清理行为后 \r\n        void OnCleanup(BindingManager bindingManager);\r\n        \r\n        int Priority { get; set; }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/IBindingProcess.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 8a28348773a19f34f9de2f4a405e8e82\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/IBindingUtils.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public interface IBindingUtils\r\n    {\r\n        string ReplacePathVars(string value);\r\n\r\n        bool IsExplicitEditorType(Type type);\r\n    }\r\n\r\n    public class DefaultBindingUtils : IBindingUtils\r\n    {\r\n        public string ReplacePathVars(string value)\r\n        {\r\n            value = value.Replace(\"${platform}\", \"unityless\");\r\n            return value;\r\n        }\r\n\r\n        public bool IsExplicitEditorType(Type type)\r\n        {\r\n            return false;\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/IBindingUtils.cs.meta",
    "content": "fileFormatVersion: 2\nguid: e52109913a02dd5459f62c370fa46ca5\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/JSBindResult.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    /// <summary>\r\n    /// some useful information collected in the binding process\r\n    /// </summary>\r\n    public class JSBindResult\r\n    {\r\n        public string comment;\r\n\r\n        /// <summary>\r\n        /// a list of all js modules corresponding to exported csharp types. \r\n        /// (useful for configuring webpack's externals)\r\n        /// </summary>\r\n        public List<string> modules = new List<string>();\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/JSBindResult.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 486ac6c4cde13ca49ba27f86d61be6e4\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Prefs.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.Collections.Generic;\n\nnamespace QuickJS.Binding\n{\n    /// <summary>\n    /// [EDITOR_ONLY] configuration for BindingManager\n    /// you can use a json file at './js-bridge.json' without modifying the source file 'Prefs.cs'\n    /// </summary>\n    public class Prefs\n    {\n        /// <summary>\n        /// location of this configuration\n        /// </summary>\n        public const string PATH = \"js-bridge.json\";\n\n        /// <summary>\n        /// the actual location of this configuration (valid only if loaded from disk)\n        /// </summary>\n        [NonSerialized]\n        public string filePath;\n\n        #region Configurable Fields\n\n        /// <summary>\n        /// the log file generated by the binding process\n        /// </summary>\n        public string logPath = \"Logs/js-bridge.log\";\n\n        /// <summary>\n        /// JSBehaviourScriptRef will parse 'modulePath' from 'JSBehaviourScriptRef.sourceFile' with this 'sourceDir'\n        /// </summary>\n        public string sourceDir = \"Scripts/src\";\n\n        /// <summary>\n        /// [optional] read this property as javascript dir for js_reload (https://github.com/ialex32x/plover)\n        /// !! this property is read only when tsconfig.json can not be located at the project root path or compilerOptions.outDir is not configured\n        /// </summary>\n        public string javascriptDir = \"\"; // Scripts/out\n\n        /// <summary>\n        /// the output directory for generating static binding code\n        /// </summary>\n        public string outDir = \"Assets/Generated/${platform}\";\n\n        /// <summary>\n        /// the location of the corresponding d.ts of the generated binding code\n        /// </summary>\n        public string typescriptDir = \"Assets/Generated/Typings\";\n\n        /// <summary>\n        /// used for editor scripting to find out all unity classes implemented in typescript\n        /// </summary>\n        public string typescriptExt = \".ts\";\n\n        /// <summary>\n        /// location of XmlDoc generated from Assembly-CSharp.dll \n        /// </summary>\n        public string xmlDocDir = \"Assets/Generated/Docs\";\n\n        /// <summary>\n        /// output as a const field in generated code\n        /// </summary>\n        public string vendor = \"\";\n\n        /// <summary>\n        /// all related modules information generated in the binding process will be written into this file. \n        /// it's useful to mark these modules as external when using webpack for packaging.\n        /// </summary>\n        public string jsModulePackInfoPath = \"jsb-modules.json\";\n\n        /// <summary>\n        /// whether to generate doc comments in d.ts or not\n        /// </summary>\n        public bool genTypescriptDoc = true;\n\n        /// <summary>\n        /// enable editor scripting feature\n        /// </summary>\n        public bool editorScripting = true;\n\n        /// <summary>\n        /// [EDITOR_ONLY] preferred to bind types by reflection in editor without generating any binding code (useful for development stage in editor)\n        /// (\"Reflect Bind\", \"In-Memory Bind\", \"Static Bind\")\n        /// </summary>\n        public string preferredBindingMethod = \"Reflect Bind\";\n\n        /// <summary>\n        /// generate binding code for operator overloading support in QuickJS (not fully supported). \n        /// operators will be generated as ordinary method (op_XXX) if disabled\n        /// </summary>\n        public bool enableOperatorOverloading = true;\n\n        /// <summary>\n        /// emit binding code for operator methods even if operator overlaoding enabled\n        /// </summary>\n        public bool alwaysEmitOperatorMethod = true;\n\n        /// <summary>\n        /// [EXPERIMENTAL][UNFINISHED] \n        /// csharp array => js array / csharp dictionary => js map \n        /// (with Proxy)\n        /// </summary>\n        public bool enableTypeProxy = false;\n\n        /// <summary>\n        /// all obsolete types/members will not be exported if set true\n        /// </summary>\n        public bool excludeObsoleteItems = true;\n\n        /// <summary>\n        /// optional entry point for editor scripting\n        /// </summary>\n        public string editorEntryPoint = \"\";\n\n        /// <summary>\n        /// Asset Postprocessor(s) implemented in scripts\n        /// </summary>\n        public List<string> assetPostProcessors = new List<string>(new string[]\n        {\n            // \"editor/asset_postprocessor\",\n        });\n\n        public List<string> editorRequires = new List<string>(new string[]\n        {\n            \"plover/editor/js_reload\",\n        });\n\n        public string editorDecoratorScript = \"plover/editor/editor_decorators\";\n\n        /// <summary>\n        /// generate totally commented staticbind code for more conveniently debugging the codegen process itself\n        /// </summary>\n        public bool debugCodegen = false;\n\n        /// <summary>\n        /// omit all delegates with ByRef parameter\n        /// </summary>\n        public bool skipDelegateWithByRefParams = false;\n\n        /// <summary>\n        /// output more details to the log file\n        /// </summary>\n        public bool verboseLog = true;\n\n        /// <summary>\n        /// automatically rename ToString() into toString()\n        /// </summary>\n        public bool optToString = true;\n\n        /// <summary>\n        /// the d.ts will be split into parts with this file length threshold \n        /// </summary>\n        public int tsdSizeThreshold = 512 * 1024;\n\n        /// <summary>\n        /// enable parameter type checking for methods (even if no overloading exists)\n        /// </summary>\n        public bool alwaysCheckArgType = false;\n\n        /// <summary>\n        /// enable checking the number of parameters even if not overloading exists\n        /// </summary>\n        public bool alwaysCheckArgc = true;\n\n        /// <summary>\n        /// [EXPERIMENTAL, UNFINISHED] generate obfuscated binding code\n        /// </summary>\n        public bool randomizedBindingCode = false;\n\n        /// <summary>\n        /// prefix of the type of generated binding code\n        /// </summary>\n        public string typeBindingPrefix = \"QuickJS_\";\n\n        /// <summary>\n        /// C# namespace for the generated glue code\n        /// </summary>\n        public string ns = \"jsb\";\n\n        /// <summary>\n        /// module name for the C# global types\n        /// </summary>\n        public string defaultJSModule = \"global\";\n\n        /// <summary>\n        /// Determines which module will the types be exported. <br/>\n        ///     legacy(default): export types into dispersed modules (depends on it's namespace and outer class) <br/>\n        ///     singular(experimental): export types into a single module  <br/>\n        /// NOT_IMPLEMENTED\n        /// </summary>\n        public string moduleStyle = \"legacy\";\n\n        public string singularModuleName = \"interop\";\n\n        /// <summary>\n        /// the optional suffix for the generated d.ts file\n        /// </summary>\n        public string extraExtForTypescript = \"\";\n\n        /// <summary>\n        /// the new-line style for codegen (cr, lf, crlf). \n        /// it will depend on the operating system if not assigned.\n        /// </summary>\n        public string newLineStyle = \"\";\n\n        /// <summary>\n        /// the indent block for codegen\n        /// </summary>\n        public string tab = \"    \";\n\n        /// <summary>\n        /// a list of BindingProcess not to run (type.FullName)\n        /// </summary>\n        public List<string> skipBinding = new List<string>(new string[]\n        {\n            // \"jsb.Editor.UnityEditorBinding\",\n        });\n\n        /// <summary>\n        /// the directories will be cleaned up after code generation (only unused files will be deleted)\n        /// </summary>\n        public List<string> cleanupDir = new List<string>(new string[]\n        {\n            \"Assets/Generated\",\n        });\n\n        /// <summary>\n        /// all the types in the listed assemblies will not be exported automatically\n        /// </summary>\n        public List<string> explicitAssemblies = new List<string>(new string[]\n        {\n            // \"Assembly-CSharp-firstpass\",\n            \"Assembly-CSharp\",\n        });\n\n        /// <summary>\n        /// all the types in the listed assemblies will be exported automatically (except the manually blocked types in BindingManager)\n        /// </summary>\n        public List<string> implicitAssemblies = new List<string>(new string[]\n        {\n            // \"UnityEngine\",\n            // \"UnityEngine.CoreModule\",\n            // \"UnityEngine.UIModule\",\n            // \"UnityEngine.TextRenderingModule\",\n            // \"UnityEngine.TextRenderingModule\",\n            // \"UnityEngine.UnityWebRequestWWWModule\",\n            // \"UnityEngine.Physics2DModule\",\n            // \"UnityEngine.AnimationModule\",\n            // \"UnityEngine.TextRenderingModule\",\n            // \"UnityEngine.IMGUIModule\",\n            // \"UnityEngine.UnityWebRequestModule\",\n            // \"UnityEngine.PhysicsModule\",\n            // \"UnityEngine.UI\",\n        });\n\n        public List<string> typeFullNameBlacklist = new List<string>(new string[]\n        {\n            \"System.SpanExtensions\",\n            \"UnityEditor.MaterialEditorExtensions\",\n            \"UnityEditor.AppleMobileArchitecture\",\n            \"UnityEngine.AndroidJavaException\",\n            \"UnityEngine.AndroidJavaProxy\",\n            \"UnityEngine.AndroidJavaObject\",\n            \"UnityEngine.AndroidJavaClass\",\n            \"UnityEngine.AndroidJNIHelper\",\n            \"UnityEngine.AndroidJNI\",\n            \"UnityEngine.AndroidActivityIndicatorStyle\",\n            \"UnityEngine.Android.AndroidDevice\",\n            \"UnityEngine.Android.Permission\",\n            \"UnityEngine.AndroidInput\",\n            \"UnityEditor.AndroidETC2Fallback\",\n            \"UnityEditor.AndroidBuildSystem\",\n            \"UnityEditor.AndroidBuildType\",\n            \"UnityEditor.AndroidMinification\",\n            \"UnityEditor.AndroidArchitecture\",\n            \"UnityEditor.AndroidSdkVersions\",\n            \"UnityEditor.AndroidPreferredInstallLocation\",\n            \"UnityEditor.AndroidShowActivityIndicatorOnLoading\",\n            \"UnityEditor.AndroidGamepadSupportLevel\",\n            \"UnityEditor.AndroidSplashScreenScale\",\n            \"UnityEditor.AndroidBlitType\",\n            \"UnityEditor.AndroidETC2FallbackOverride\",\n            \"UnityEditor.Android.IPostGenerateGradleAndroidProject\",\n            \"UnityEditor.WSASubtarget\",\n            \"UnityEditor.WSASDK\",\n            \"UnityEditor.WSAUWPBuildType\",\n            \"UnityEditor.WSABuildAndRunDeployTarget\",\n            \"UnityEditor.WSABuildType\",\n            \"UnityEditor.HumanTemplate\",\n            \"UnityEditor.TakeInfo\",\n            \"UnityEditor.L10n\",\n            \"UnityEditor.Build.Reporting\",\n            \"UnityEditor.TypeCache\",\n            \"UnityEditor.SceneManagement.ObjectOverride\",\n            \"UnityEditor.SceneManagement.PrefabOverride\",\n            \"UnityEditor.SceneManagement.AddedGameObject\",\n            \"UnityEditor.SceneManagement.AddedComponent\",\n            \"UnityEditor.SceneManagement.RemovedComponent\",\n        });\n\n        public List<string> namespaceBlacklist = new List<string>(new string[]\n        {\n            \"TreeEditor\",\n            \"UnityEditor.U2D\",\n            \"UnityEditor.Rendering\",\n            \"UnityEditor.AssetImporters\",\n            \"UnityEditor.Audio\",\n            \"UnityEditor.Build.Player\",\n            \"Unity.CodeEditor\",\n            \"UnityEditor.Sprites\",\n            \"UnityEditor.Experimental\",\n            \"UnityEngine.Assertions\",\n            \"UnityEngine.Experimental.AI\",\n            \"UnityEngine.Experimental.Animations\",\n            \"UnityEngine.Experimental.AssetBundlePatching\",\n            \"UnityEngine.Experimental.Audio\",\n            \"UnityEngine.Experimental.Networking.PlayerConnection\",\n            \"UnityEngine.Experimental.GlobalIllumination\",\n            \"UnityEngine.Experimental.Playables\",\n            \"UnityEngine.Experimental.Rendering\",\n            \"UnityEngine.Experimental.TerrainAPI\",\n            \"UnityEngine.Experimental.XR\",\n            \"UnityEngine.Experimental.Video\",\n            \"UnityEditor.Experimental.U2D\",\n            \"UnityEngine.Jobs\",\n            \"Unity.Jobs\",\n            \"Unity.Profiling\",\n            \"Unity.Profiling.LowLevel\",\n            \"Unity.Jobs.LowLevel.Unsafe\",\n            \"Unity.Collections.LowLevel.Unsafe\",\n            \"UnityEngine.Apple.ReplayKit\",\n            \"UnityEditor.VisualStudioIntegration\",\n            \"UnityEditor.Profiling.Memory.Experimental\",\n            \"UnityEditor.Profiling\",\n            \"UnityEditor.UIElements\",\n            \"UnityEditor.Animations\",\n            \"UnityEditor.Experimental.AssetImporters\",\n            \"UnityEditor.Experimental.SceneManagement\",\n            \"UnityEngineInternal\",\n            \"UnityEditorInternal\",\n            \"UnityEditorInternal.VersionControl\",\n            \"JetBrains.Annotations\",\n            \"Unity.IO.LowLevel.Unsafe\",\n            \"Unity.Collections\",\n            \"UnityEditor.UnityLinker\",\n            \"UnityEditor.Il2Cpp\",\n            \"UnityEditor.Experimental.Rendering\",\n            \"UnityEditor.Experimental.GraphView\",\n            \"UnityEditor.Experimental.Licensing\",\n            \"UnityEditor.Experimental.TerrainAPI\",\n            \"UnityEditor.XR\",\n            \"UnityEditor.XR.Daydream\",\n            \"UnityEditorInternal.Profiling.Memory.Experimental\",\n            \"UnityEditorInternal.Profiling.Memory.Experimental.FileFormat\",\n            \"UnityEditor.Build.Content\",\n            \"UnityEditor.AnimatedValues\",\n            \"UnityEditor.AI\",\n            \"UnityEditor.Macros\",\n            \"UnityEditor.Experimental.Networking.PlayerConnection\",\n            \"UnityEditor.Compilation\",\n            \"UnityEditor.Networking.PlayerConnection\",\n            \"UnityEditor.VersionControl\",\n            \"UnityEditor.Localization.Editor\",\n            \"UnityEditor.CrashReporting\",\n            \"UnityEditor.ShaderProfiler\",\n            \"UnityEditor.MemoryProfiler\",\n            \"UnityEditor.ShortcutManagement\",\n            \"UnityEditorInternal.VR\",\n            \"UnityEditor.Presets\",\n            \"UnityEditor.PackageManager\",\n            \"UnityEditor.PackageManager.UI\",\n            \"UnityEditor.PackageManager.Requests\",\n            \"SyntaxTree.VisualStudio.Unity.Messaging\",\n        });\n\n        public List<string> assemblyBlacklist = new List<string>(new string[]\n        {\n            \"ExCSS.Unity\",\n            \"Unity.Cecil\",\n            \"Unity.Cecil.Mdb\",\n            \"Unity.Cecil.Pdb\",\n            \"Unity.Cecil.Rocks\",\n            \"Unity.CecilTools\",\n        });\n\n        #endregion\n\n        #region Runtime Methods\n\n        public string newline\n        {\n            get\n            {\n                if (newLineStyle == null)\n                {\n                    return Environment.NewLine;\n                }\n\n                switch (newLineStyle.ToLower())\n                {\n                    case \"cr\": return \"\\r\";\n                    case \"lf\": return \"\\n\";\n                    case \"crlf\": return \"\\r\\n\";\n                    case \"\":\n                    case \"auto\": return Environment.NewLine;\n                    default: return newLineStyle;\n                }\n            }\n        }\n\n        public ETSModuleStyle GetModuleStyle()\n        {\n            switch(moduleStyle)\n            {\n                case \"singular\": return ETSModuleStyle.Singular;\n                default: return ETSModuleStyle.Legacy;\n            }\n        }\n\n        #endregion\n    }\n}\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/Prefs.cs.meta",
    "content": "fileFormatVersion: 2\nguid: e0674056373aa7849a207d7cc6513d9d\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/ReflectBindDelegateGen.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\nusing System.Text.RegularExpressions;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using QuickJS.Native;\r\n\r\n    /// <summary>\r\n    /// Provide function templates which will be used as delegate's script bridge in ReflectBind mode. \r\n    /// no need to list all the possibilities, the missing call will be dynamically generated by CSharpCodeDom at runtime.\r\n    /// </summary>\r\n    public unsafe static class ReflectBindDelegateGen\r\n    {\r\n        public static void ActionCall(ScriptDelegate fn)\r\n        {\r\n            if (!fn.isValid)\r\n            {\r\n                return;\r\n            }\r\n            var ctx = fn.ctx;\r\n            var rval = fn.Invoke(ctx);\r\n            if (rval.IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            JSApi.JS_FreeValue(ctx, rval);\r\n        }\r\n\r\n        public static void ActionCall<T1>(ScriptDelegate fn, T1 a1)\r\n        {\r\n            if (!fn.isValid)\r\n            {\r\n                return;\r\n            }\r\n            var ctx = fn.ctx;\r\n            var argv = stackalloc JSValue[1];\r\n            argv[0] = ReflectBindValueOp.js_push_tvar<T1>(ctx, a1);\r\n            if (argv[0].IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            var rval = fn.Invoke(ctx, 1, argv);\r\n            JSApi.JS_FreeValue(ctx, argv[0]);\r\n            if (rval.IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            JSApi.JS_FreeValue(ctx, rval);\r\n        }\r\n\r\n        public static void ActionCall<T1, T2>(ScriptDelegate fn, T1 a1, T2 a2)\r\n        {\r\n            if (!fn.isValid)\r\n            {\r\n                return;\r\n            }\r\n            var ctx = fn.ctx;\r\n            var argv = stackalloc JSValue[2];\r\n            argv[0] = ReflectBindValueOp.js_push_tvar<T1>(ctx, a1);\r\n            if (argv[0].IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            argv[1] = ReflectBindValueOp.js_push_tvar<T2>(ctx, a2);\r\n            if (argv[1].IsException())\r\n            {\r\n                JSApi.JS_FreeValue(ctx, argv[0]);\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            var rval = fn.Invoke(ctx, 2, argv);\r\n            JSApi.JS_FreeValue(ctx, argv[0]);\r\n            JSApi.JS_FreeValue(ctx, argv[1]);\r\n            if (rval.IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            JSApi.JS_FreeValue(ctx, rval);\r\n        }\r\n\r\n        public static void ActionCall<T1, T2, T3>(ScriptDelegate fn, T1 a1, T2 a2, T3 a3)\r\n        {\r\n            if (!fn.isValid)\r\n            {\r\n                return;\r\n            }\r\n            var ctx = fn.ctx;\r\n            var argv = stackalloc JSValue[3];\r\n            argv[0] = ReflectBindValueOp.js_push_tvar<T1>(ctx, a1);\r\n            if (argv[0].IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            argv[1] = ReflectBindValueOp.js_push_tvar<T2>(ctx, a2);\r\n            if (argv[1].IsException())\r\n            {\r\n                JSApi.JS_FreeValue(ctx, argv[0]);\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            argv[2] = ReflectBindValueOp.js_push_tvar<T3>(ctx, a3);\r\n            if (argv[2].IsException())\r\n            {\r\n                JSApi.JS_FreeValue(ctx, argv[0]);\r\n                JSApi.JS_FreeValue(ctx, argv[1]);\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            var rval = fn.Invoke(ctx, 3, argv);\r\n            JSApi.JS_FreeValue(ctx, argv[0]);\r\n            JSApi.JS_FreeValue(ctx, argv[1]);\r\n            JSApi.JS_FreeValue(ctx, argv[2]);\r\n            if (rval.IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            JSApi.JS_FreeValue(ctx, rval);\r\n        }\r\n\r\n        public static void ActionCall<T1, T2, T3, T4>(ScriptDelegate fn, T1 a1, T2 a2, T3 a3, T4 a4)\r\n        {\r\n            if (!fn.isValid)\r\n            {\r\n                return;\r\n            }\r\n            var ctx = fn.ctx;\r\n            var argv = stackalloc JSValue[4];\r\n            argv[0] = ReflectBindValueOp.js_push_tvar<T1>(ctx, a1);\r\n            if (argv[0].IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            argv[1] = ReflectBindValueOp.js_push_tvar<T2>(ctx, a2);\r\n            if (argv[1].IsException())\r\n            {\r\n                JSApi.JS_FreeValue(ctx, argv[0]);\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            argv[2] = ReflectBindValueOp.js_push_tvar<T3>(ctx, a3);\r\n            if (argv[2].IsException())\r\n            {\r\n                JSApi.JS_FreeValue(ctx, argv[0]);\r\n                JSApi.JS_FreeValue(ctx, argv[1]);\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            argv[3] = ReflectBindValueOp.js_push_tvar<T4>(ctx, a4);\r\n            if (argv[3].IsException())\r\n            {\r\n                JSApi.JS_FreeValue(ctx, argv[0]);\r\n                JSApi.JS_FreeValue(ctx, argv[1]);\r\n                JSApi.JS_FreeValue(ctx, argv[2]);\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            var rval = fn.Invoke(ctx, 4, argv);\r\n            JSApi.JS_FreeValue(ctx, argv[0]);\r\n            JSApi.JS_FreeValue(ctx, argv[1]);\r\n            JSApi.JS_FreeValue(ctx, argv[2]);\r\n            JSApi.JS_FreeValue(ctx, argv[3]);\r\n            if (rval.IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            JSApi.JS_FreeValue(ctx, rval);\r\n        }\r\n\r\n        public static void ActionCall<T1, T2, T3, T4, T5>(ScriptDelegate fn, T1 a1, T2 a2, T3 a3, T4 a4, T5 a5)\r\n        {\r\n            if (!fn.isValid)\r\n            {\r\n                return;\r\n            }\r\n            var ctx = fn.ctx;\r\n            var argv = stackalloc JSValue[5];\r\n            argv[0] = ReflectBindValueOp.js_push_tvar<T1>(ctx, a1);\r\n            if (argv[0].IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            argv[1] = ReflectBindValueOp.js_push_tvar<T2>(ctx, a2);\r\n            if (argv[1].IsException())\r\n            {\r\n                JSApi.JS_FreeValue(ctx, argv[0]);\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            argv[2] = ReflectBindValueOp.js_push_tvar<T3>(ctx, a3);\r\n            if (argv[2].IsException())\r\n            {\r\n                JSApi.JS_FreeValue(ctx, argv[0]);\r\n                JSApi.JS_FreeValue(ctx, argv[1]);\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            argv[3] = ReflectBindValueOp.js_push_tvar<T4>(ctx, a4);\r\n            if (argv[3].IsException())\r\n            {\r\n                JSApi.JS_FreeValue(ctx, argv[0]);\r\n                JSApi.JS_FreeValue(ctx, argv[1]);\r\n                JSApi.JS_FreeValue(ctx, argv[2]);\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            argv[4] = ReflectBindValueOp.js_push_tvar<T5>(ctx, a5);\r\n            if (argv[4].IsException())\r\n            {\r\n                JSApi.JS_FreeValue(ctx, argv[0]);\r\n                JSApi.JS_FreeValue(ctx, argv[1]);\r\n                JSApi.JS_FreeValue(ctx, argv[2]);\r\n                JSApi.JS_FreeValue(ctx, argv[3]);\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            var rval = fn.Invoke(ctx, 5, argv);\r\n            JSApi.JS_FreeValue(ctx, argv[0]);\r\n            JSApi.JS_FreeValue(ctx, argv[1]);\r\n            JSApi.JS_FreeValue(ctx, argv[2]);\r\n            JSApi.JS_FreeValue(ctx, argv[3]);\r\n            JSApi.JS_FreeValue(ctx, argv[4]);\r\n            if (rval.IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            JSApi.JS_FreeValue(ctx, rval);\r\n        }\r\n\r\n        public static RT FuncCall<RT>(ScriptDelegate fn)\r\n        {\r\n            if (!fn.isValid)\r\n            {\r\n                return default(RT);\r\n            }\r\n            var ctx = fn.ctx;\r\n            var rval = fn.Invoke(ctx);\r\n            if (rval.IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            RT ret0;\r\n            var succ = ReflectBindValueOp.js_get_tvar<RT>(ctx, rval, out ret0);\r\n            JSApi.JS_FreeValue(ctx, rval);\r\n            if (succ)\r\n            {\r\n                return ret0;\r\n            }\r\n            else\r\n            {\r\n                throw new Exception(\"js exception caught\");\r\n            }\r\n        }\r\n\r\n        public static RT FuncCall<T1, RT>(ScriptDelegate fn, T1 a1)\r\n        {\r\n            if (!fn.isValid)\r\n            {\r\n                return default(RT);\r\n            }\r\n            var ctx = fn.ctx;\r\n            var argv = stackalloc JSValue[1];\r\n            argv[0] = ReflectBindValueOp.js_push_tvar<T1>(ctx, a1);\r\n            if (argv[0].IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            var rval = fn.Invoke(ctx, 1, argv);\r\n            if (rval.IsException())\r\n            {\r\n                JSApi.JS_FreeValue(ctx, argv[0]);\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            RT ret0;\r\n            var succ = ReflectBindValueOp.js_get_tvar<RT>(ctx, rval, out ret0);\r\n            JSApi.JS_FreeValue(ctx, rval);\r\n            JSApi.JS_FreeValue(ctx, argv[0]);\r\n            if (succ)\r\n            {\r\n                return ret0;\r\n            }\r\n            else\r\n            {\r\n                throw new Exception(\"js exception caught\");\r\n            }\r\n        }\r\n\r\n        public static RT FuncCall<T1, T2, RT>(ScriptDelegate fn, T1 a1, T2 a2)\r\n        {\r\n            if (!fn.isValid)\r\n            {\r\n                return default(RT);\r\n            }\r\n            var ctx = fn.ctx;\r\n            var argv = stackalloc JSValue[2];\r\n            argv[0] = ReflectBindValueOp.js_push_tvar<T1>(ctx, a1);\r\n            if (argv[0].IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            argv[1] = ReflectBindValueOp.js_push_tvar<T2>(ctx, a2);\r\n            if (argv[1].IsException())\r\n            {\r\n                JSApi.JS_FreeValue(ctx, argv[0]);\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            var rval = fn.Invoke(ctx, 2, argv);\r\n            JSApi.JS_FreeValue(ctx, argv[0]);\r\n            JSApi.JS_FreeValue(ctx, argv[1]);\r\n            if (rval.IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            RT ret0;\r\n            var succ = ReflectBindValueOp.js_get_tvar<RT>(ctx, rval, out ret0);\r\n            JSApi.JS_FreeValue(ctx, rval);\r\n            if (succ)\r\n            {\r\n                return ret0;\r\n            }\r\n            else\r\n            {\r\n                throw new Exception(\"js exception caught\");\r\n            }\r\n        }\r\n\r\n        public static RT FuncCall<T1, T2, T3, RT>(ScriptDelegate fn, T1 a1, T2 a2, T3 a3)\r\n        {\r\n            if (!fn.isValid)\r\n            {\r\n                return default(RT);\r\n            }\r\n            var ctx = fn.ctx;\r\n            var argv = stackalloc JSValue[3];\r\n            argv[0] = ReflectBindValueOp.js_push_tvar<T1>(ctx, a1);\r\n            if (argv[0].IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            argv[1] = ReflectBindValueOp.js_push_tvar<T2>(ctx, a2);\r\n            if (argv[1].IsException())\r\n            {\r\n                JSApi.JS_FreeValue(ctx, argv[0]);\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            argv[2] = ReflectBindValueOp.js_push_tvar<T3>(ctx, a3);\r\n            if (argv[2].IsException())\r\n            {\r\n                JSApi.JS_FreeValue(ctx, argv[0]);\r\n                JSApi.JS_FreeValue(ctx, argv[1]);\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            var rval = fn.Invoke(ctx, 3, argv);\r\n            JSApi.JS_FreeValue(ctx, argv[0]);\r\n            JSApi.JS_FreeValue(ctx, argv[1]);\r\n            JSApi.JS_FreeValue(ctx, argv[2]);\r\n            if (rval.IsException())\r\n            {\r\n                throw new Exception(ctx.GetExceptionString());\r\n            }\r\n            RT ret0;\r\n            var succ = ReflectBindValueOp.js_get_tvar<RT>(ctx, rval, out ret0);\r\n            JSApi.JS_FreeValue(ctx, rval);\r\n            if (succ)\r\n            {\r\n                return ret0;\r\n            }\r\n            else\r\n            {\r\n                throw new Exception(\"js exception caught\");\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/ReflectBindDelegateGen.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 9bf303659c245004d80227cc60d1ef42\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/ReflectBindValueOp.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\nusing System.Text.RegularExpressions;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using QuickJS.Native;\r\n\r\n    public delegate JSValue ReflectBindValuePusher<T>(JSContext ctx, T o);\r\n    public delegate bool ReflectBindValueGetter<T>(JSContext ctx, JSValue val, out T o);\r\n\r\n    public static class ReflectBindValueConvert<T>\r\n    {\r\n        public static ReflectBindValuePusher<T> push;\r\n        public static ReflectBindValueGetter<T> get;\r\n    }\r\n\r\n    public class ReflectBindValueOp\r\n    {\r\n        private static HashSet<Type> _registeredTypes = new HashSet<Type>();\r\n\r\n        public static void Register<T>(ReflectBindValuePusher<T> push, ReflectBindValueGetter<T> get)\r\n        {\r\n            if (_registeredTypes.Add(typeof(T)))\r\n            {\r\n                ReflectBindValueConvert<T>.push = push;\r\n                ReflectBindValueConvert<T>.get = get;\r\n            }\r\n        }\r\n\r\n        public static bool js_get_tvar<T>(JSContext ctx, JSValue val, out T o)\r\n        {\r\n            if (_registeredTypes.Contains(typeof(T)))\r\n            {\r\n                return ReflectBindValueConvert<T>.get(ctx, val, out o);\r\n            }\r\n\r\n            object ft = null;\r\n            if (Binding.Values.js_get_var(ctx, val, typeof(T), out ft))\r\n            {\r\n                if (ft == null)\r\n                {\r\n                    o = default(T);\r\n                    return true;\r\n                }\r\n\r\n                if (typeof(T).IsInstanceOfType(ft))\r\n                {\r\n                    o = (T)ft;\r\n                    return true;\r\n                }\r\n            }\r\n            o = default(T);\r\n            return false;\r\n        }\r\n\r\n        public static JSValue js_push_tvar<T>(JSContext ctx, T o)\r\n        {\r\n            if (_registeredTypes.Contains(typeof(T)))\r\n            {\r\n                return ReflectBindValueConvert<T>.push(ctx, o);\r\n            }\r\n\r\n            return Binding.Values.js_push_var(ctx, o);\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/ReflectBindValueOp.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 08ec2b0787d5aa64693d0849d6f56358\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/TextGenerator.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing System.Linq;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public class TextGenerator\r\n    {\r\n        public class IndentBlock : IDisposable\r\n        {\r\n            private TextGenerator _generator;\r\n\r\n            public IndentBlock(TextGenerator generator)\r\n            {\r\n                _generator = generator;\r\n                _generator.AddTabLevel();\r\n            }\r\n\r\n            public void Dispose()\r\n            {\r\n                _generator.DecTabLevel();\r\n            }\r\n        }\r\n\r\n        public class DoWhileBlock : IDisposable\r\n        {\r\n            private bool _valid;\r\n            private TextGenerator _generator;\r\n\r\n            public DoWhileBlock(TextGenerator generator, bool valid)\r\n            {\r\n                _valid = valid;\r\n                _generator = generator;\r\n                if (_valid)\r\n                {\r\n                    _generator.AppendLine(\"do\");\r\n                    _generator.AppendLine(\"{\");\r\n                    _generator.AddTabLevel();\r\n                }\r\n            }\r\n\r\n            public void Dispose()\r\n            {\r\n                if (_valid)\r\n                {\r\n                    _generator.DecTabLevel();\r\n                    _generator.AppendLine(\"} while(false);\");\r\n                }\r\n            }\r\n        }\r\n\r\n        public class CodeBlock : IDisposable\r\n        {\r\n            private string _tail;\r\n            private TextGenerator _generator;\r\n\r\n            public CodeBlock(TextGenerator generator, string tail)\r\n            {\r\n                _tail = tail;\r\n                _generator = generator;\r\n                _generator.AppendLine(\"{\");\r\n                _generator.AddTabLevel();\r\n            }\r\n\r\n            public void Dispose()\r\n            {\r\n                _generator.DecTabLevel();\r\n                _generator.AppendLine(\"}\" + _tail);\r\n            }\r\n        }\r\n\r\n        public bool enabled = true;\r\n        public readonly string newline;\r\n        private string tab;\r\n        private int tabLevel;\r\n\r\n        private StringBuilder sb => parts[partIndex];\r\n\r\n        private int partThreshold = 0;\r\n\r\n        private int partIndex = 0;\r\n\r\n        private List<StringBuilder> parts = new List<StringBuilder>();\r\n\r\n        private List<string> partResults = new List<string>();\r\n\r\n        public bool isEmpty { get { return partResults.Count == 0 && (from part in parts where part.Length > 0 select part.Length).Sum() == 0; } }\r\n\r\n        public string tabString\r\n        {\r\n            get\r\n            {\r\n                var s = \"\";\r\n                for (var i = 0; i < tabLevel; i++)\r\n                {\r\n                    s += tab;\r\n                }\r\n                return s;\r\n            }\r\n        }\r\n\r\n        public TextGenerator(string newline, string tab, int partThreshold = 0)\r\n        {\r\n            this.newline = newline;\r\n            this.tab = tab;\r\n            this.tabLevel = 0;\r\n            this.partIndex = 0;\r\n            this.partThreshold = partThreshold;\r\n            this.parts.Add(new StringBuilder());\r\n        }\r\n\r\n        public string Submit()\r\n        {\r\n            var text = sb.ToString();\r\n            return text;\r\n        }\r\n\r\n        public string[] SubmitAll()\r\n        {\r\n            var list = new List<string>();\r\n            list.AddRange(from part in parts where part.Length > 0 select part.ToString());\r\n            list.AddRange(partResults);\r\n            return list.ToArray();\r\n        }\r\n\r\n        public void BeginPart()\r\n        {\r\n            if (partThreshold > 0)\r\n            {\r\n                partIndex++;\r\n                while (partIndex >= parts.Count)\r\n                {\r\n                    parts.Add(new StringBuilder());\r\n                }\r\n            }\r\n        }\r\n\r\n        public void EndPart()\r\n        {\r\n            if (partThreshold > 0)\r\n            {\r\n                if (partIndex == 0)\r\n                {\r\n                    throw new InvalidOperationException();\r\n                }\r\n\r\n                if (sb.Length > partThreshold)\r\n                {\r\n                    partResults.Add(sb.ToString());\r\n                    sb.Clear();\r\n                }\r\n\r\n                --partIndex;\r\n            }\r\n        }\r\n\r\n        #region Code Text\r\n        public CodeBlock CodeBlockScope()\r\n        {\r\n            return new CodeBlock(this, string.Empty);\r\n        }\r\n\r\n        public CodeBlock TailCallCodeBlockScope()\r\n        {\r\n            return new CodeBlock(this, \");\");\r\n        }\r\n\r\n        public DoWhileBlock DoWhileBlockScope(bool valid = true)\r\n        {\r\n            return new DoWhileBlock(this, valid);\r\n        }\r\n\r\n        public IndentBlock IndentBlockScope()\r\n        {\r\n            return new IndentBlock(this);\r\n        }\r\n\r\n        public void BeginBlock()\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n            AppendLine(\"{\");\r\n            tabLevel++;\r\n        }\r\n\r\n        public void EndBlock()\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n            tabLevel--;\r\n            AppendLine(\"}\");\r\n        }\r\n\r\n        public void AddTabLevel()\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n            tabLevel++;\r\n        }\r\n\r\n        public void DecTabLevel()\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n            tabLevel--;\r\n        }\r\n\r\n        public void AppendTab()\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n            for (var i = 0; i < tabLevel; i++)\r\n            {\r\n                sb.Append(tab);\r\n            }\r\n        }\r\n\r\n        public void AppendLines(params string[] lines)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            foreach (var line in lines)\r\n            {\r\n                AppendLine(line);\r\n            }\r\n        }\r\n\r\n        public void AppendLine()\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n            sb.Append(newline);\r\n        }\r\n\r\n        public void AppendLine(string text)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n            AppendTab();\r\n            sb.Append(text);\r\n            sb.Append(newline);\r\n        }\r\n\r\n        public void AppendLine(string text, object arg1)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n            AppendTab();\r\n            sb.AppendFormat(text, arg1);\r\n            sb.Append(newline);\r\n        }\r\n\r\n        public void AppendLine(string text, object arg1, object arg2)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n            AppendTab();\r\n            sb.AppendFormat(text, arg1, arg2);\r\n            sb.Append(newline);\r\n        }\r\n\r\n        public void AppendLine(string text, object arg1, object arg2, object arg3)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            AppendTab();\r\n            sb.AppendFormat(text, arg1, arg2, arg3);\r\n            sb.Append(newline);\r\n        }\r\n\r\n        public void AppendLine(string text, params object[] args)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            AppendTab();\r\n            sb.AppendFormat(text, args);\r\n            sb.Append(newline);\r\n        }\r\n\r\n        public void AppendLineL(string text)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            sb.Append(text);\r\n            sb.Append(newline);\r\n        }\r\n\r\n        public void AppendLineL(string text, object arg1)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            sb.AppendFormat(text, arg1);\r\n            sb.Append(newline);\r\n        }\r\n\r\n        public void AppendLineL(string text, object arg1, object arg2)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            sb.AppendFormat(text, arg1, arg2);\r\n            sb.Append(newline);\r\n        }\r\n\r\n        public void AppendLineL(string text, object arg1, object arg2, object arg3)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            sb.AppendFormat(text, arg1, arg2, arg3);\r\n            sb.Append(newline);\r\n        }\r\n\r\n        public void AppendLineL(string text, params object[] args)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            sb.AppendFormat(text, args);\r\n            sb.Append(newline);\r\n        }\r\n\r\n        public void Append(string text)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            AppendTab();\r\n            sb.Append(text);\r\n        }\r\n\r\n        public void Append(string text, object arg1)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            AppendTab();\r\n            sb.AppendFormat(text, arg1);\r\n        }\r\n\r\n        public void Append(string text, object arg1, object arg2)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            AppendTab();\r\n            sb.AppendFormat(text, arg1, arg2);\r\n        }\r\n\r\n        public void Append(string text, object arg1, object arg2, object arg3)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            AppendTab();\r\n            sb.AppendFormat(text, arg1, arg2, arg3);\r\n        }\r\n\r\n        public void Append(string text, params object[] args)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            AppendTab();\r\n            sb.AppendFormat(text, args);\r\n        }\r\n\r\n        public void AppendL(string text)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            sb.Append(text);\r\n        }\r\n\r\n        public void AppendL(string text, object arg1)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            sb.AppendFormat(text, arg1);\r\n        }\r\n\r\n        public void AppendL(string text, object arg1, object arg2)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            sb.AppendFormat(text, arg1, arg2);\r\n        }\r\n\r\n        public void AppendL(string text, object arg1, object arg2, object arg3)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            sb.AppendFormat(text, arg1, arg2, arg3);\r\n        }\r\n\r\n        public void AppendL(string text, params object[] args)\r\n        {\r\n            if (!enabled)\r\n            {\r\n                return;\r\n            }\r\n\r\n            sb.AppendFormat(text, args);\r\n        }\r\n\r\n        public void Clear()\r\n        {\r\n            tabLevel = 0;\r\n            sb.Clear();\r\n        }\r\n        #endregion\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/TextGenerator.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 6111077e25feaa348b73e240a8ef6609\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/TypeTransform.cs",
    "content": "#if UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\nusing System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Text.RegularExpressions;\nusing System.Linq;\n\nnamespace QuickJS.Binding\n{\n    public class BindingPoints\n    {\n        public const string METHOD_BINDING_FULL = \"METHOD_BINDING_FULL\";\n        public const string METHOD_BINDING_BEFORE_INVOKE = \"METHOD_BINDING_BEFORE_INVOKE\";\n    }\n\n    public class TypeTransform\n    {\n        private Type _type;\n        private JSHotfixAttribute _hotfix;\n        private string _tsNaming;\n        private bool _enableOperatorOverloading = true;\n        private bool _disposable;\n        private Native.JSCFunctionMagic _csConstructorOverride = null;\n\n        public bool crossbind => _csConstructorOverride != null;\n\n        public bool disposable => _disposable;\n\n        public TypeBindingFlags bindingFlags = TypeBindingFlags.Default;\n\n        /// <summary>\n        /// required defines of this type\n        /// </summary>\n        public HashSet<string> requiredDefines;\n\n        private Dictionary<string, HashSet<string>> _requiredDefinesOfMember;\n\n        //TODO requiredDefines of type.method \n        private Dictionary<MethodBase, HashSet<string>> _requiredDefinesOfMethod;\n\n        /// <summary>\n        /// additional extension methods not directly belonging to this type\n        /// </summary>\n        public HashSet<MethodInfo> extensionMethods;\n\n        /// <summary>\n        /// additional static JS raw method for this type\n        /// </summary>\n        public HashSet<Native.JSCFunction> staticMethods;\n\n        /// <summary>\n        /// all memebers not to expose to JS by name\n        /// </summary>\n        private HashSet<string> _memberBlacklist;\n\n        // 强制不导出的方法\n        private HashSet<MethodBase> _methodBlacklist = new HashSet<MethodBase>();\n\n        // 针对特定方法的 ts 声明优化\n        private Dictionary<MethodBase, string> _tsMethodDeclarations = new Dictionary<MethodBase, string>();\n        private Dictionary<string, Native.JSCFunction> _csMethodOverride = new Dictionary<string, Native.JSCFunction>();\n\n        private List<string> _tsAdditionalMethodDeclarations;\n\n        private Dictionary<Type, Delegate> _filters = new Dictionary<Type, Delegate>();\n\n        private Dictionary<MemberInfo, string> _memberNameRules = new Dictionary<MemberInfo, string>();\n\n        private Dictionary<MemberInfo, string> _memberNameAlias = new Dictionary<MemberInfo, string>();\n\n        public bool enableOperatorOverloading => _enableOperatorOverloading;\n\n        public Type type => _type;\n\n        public Native.JSCFunctionMagic csConstructorOverride => _csConstructorOverride;\n\n        public TypeTransform(Type type)\n        {\n            _type = type;\n            if (_type.IsGenericTypeDefinition)\n            {\n                bindingFlags = TypeBindingFlags.Default & ~TypeBindingFlags.BindingCode;\n            }\n        }\n\n        public TypeTransform EnableOperatorOverloading(bool value)\n        {\n            _enableOperatorOverloading = value;\n            return this;\n        }\n\n        /// <summary>\n        /// let the lifetime of this type totally managed by JS.\n        /// it means the underlying C# object will be automatically disposed after JS object's releasing.\n        /// NOTE: it's only valid for the objects created by JS ('new XXX()' in JS).\n        /// </summary>\n        public TypeTransform SetDisposable()\n        {\n            _disposable = true;\n            return this;\n        }\n\n        /// <summary>\n        /// the generated static binding code for this type will be guarded by UNITY_EDITOR\n        /// </summary>\n        public TypeTransform EditorRuntime()\n        {\n            return AddRequiredDefines(\"UNITY_EDITOR\");\n        }\n\n        /// <summary>\n        /// let this type binding only available with specified C# DefineConstants\n        /// </summary>\n        public TypeTransform AddRequiredDefines(params string[] defines)\n        {\n            if (requiredDefines == null)\n            {\n                requiredDefines = new HashSet<string>();\n            }\n\n            for (int i = 0, len = defines.Length; i < len; i++)\n            {\n                requiredDefines.Add(defines[i]);\n            }\n            return this;\n        }\n\n        /// <summary>\n        /// this type will not guarded by unity target platform define constants (UNITY_ANDROID, UNITY_IOS etc.)\n        /// it's only used for generating static binding code.\n        /// </summary>\n        public TypeTransform SystemRuntime()\n        {\n            bindingFlags &= ~TypeBindingFlags.BuildTargetPlatformOnly;\n            return this;\n        }\n\n        public HashSet<string> GetRequiredDefinesOfMember(string memberName)\n        {\n            if (_requiredDefinesOfMember != null)\n            {\n                HashSet<string> requiredDefines;\n                if (_requiredDefinesOfMember.TryGetValue(memberName, out requiredDefines))\n                {\n                    return requiredDefines;\n                }\n            }\n            return null;\n        }\n\n        public TypeTransform AddRequiredDefinesForMember(string memberName, params string[] requiredDefines)\n        {\n            if (_requiredDefinesOfMember == null)\n            {\n                _requiredDefinesOfMember = new Dictionary<string, HashSet<string>>();\n            }\n            HashSet<string> oldValues;\n            if (_requiredDefinesOfMember.TryGetValue(memberName, out oldValues))\n            {\n                oldValues.UnionWith(requiredDefines);\n            }\n            else\n            {\n                _requiredDefinesOfMember[memberName] = new HashSet<string>(requiredDefines);\n            }\n            return this;\n        }\n\n        public HashSet<string> GetRequiredDefinesOfMethod(MethodBase methodBase)\n        {\n            if (_requiredDefinesOfMethod != null)\n            {\n                HashSet<string> requiredDefines;\n                if (_requiredDefinesOfMethod.TryGetValue(methodBase, out requiredDefines))\n                {\n                    return requiredDefines;\n                }\n            }\n            return null;\n        }\n\n        public TypeTransform AddRequiredDefinesForMethod(MethodBase methodBase, params string[] requiredDefines)\n        {\n            if (_requiredDefinesOfMethod == null)\n            {\n                _requiredDefinesOfMethod = new Dictionary<MethodBase, HashSet<string>>();\n            }\n            HashSet<string> oldValues;\n            if (_requiredDefinesOfMethod.TryGetValue(methodBase, out oldValues))\n            {\n                oldValues.UnionWith(requiredDefines);\n            }\n            else\n            {\n                _requiredDefinesOfMethod[methodBase] = new HashSet<string>(requiredDefines);\n            }\n            return this;\n        }\n\n        public TypeTransform AddRequiredDefinesForMethod(Func<Type, MethodBase> getter, params string[] requiredDefines)\n        {\n            var methodBase = getter(_type);\n            if (methodBase != null)\n            {\n                return AddRequiredDefinesForMethod(methodBase, requiredDefines);\n            }\n            return this;\n        }\n\n        /// <summary>\n        /// filter out the member if the callback returns true.\n        /// </summary>\n        public TypeTransform OnFilter<T>(Func<T, bool> callback)\n        {\n            _filters[typeof(T)] = callback;\n            return this;\n        }\n\n        public bool Filter<T>(T info)\n        {\n            Delegate d;\n            if (!_filters.TryGetValue(typeof(T), out d))\n            {\n                return false;\n            }\n            var t = (Func<T, bool>)d;\n            return t(info);\n        }\n\n        public string GetNameAlias(MemberInfo info)\n        {\n            string alias;\n            return _memberNameAlias.TryGetValue(info, out alias) ? alias : info.Name;\n        }\n\n        public string GetNameRule(MemberInfo info)\n        {\n            string rule;\n            return _memberNameRules.TryGetValue(info, out rule) ? rule : null;\n        }\n\n        public void SetNameRule(Func<MemberInfo, string> callback)\n        {\n            foreach (var m in _type.GetMembers())\n            {\n                var r = callback(m);\n                if (r != null)\n                {\n                    _memberNameRules[m] = r;\n                }\n            }\n        }\n\n        #region Extension Method Management\n        public TypeTransform AddExtensionMethod<T>(Action<T> method, string tsDecl = null)\n        {\n            return AddExtensionMethod(method.Method, tsDecl);\n        }\n\n        public TypeTransform AddExtensionMethod<T1, T2>(Action<T1, T2> method, string tsDecl = null)\n        {\n            return AddExtensionMethod(method.Method, tsDecl);\n        }\n\n        public TypeTransform AddExtensionMethod<T1, T2, T3>(Action<T1, T2, T3> method, string tsDecl = null)\n        {\n            return AddExtensionMethod(method.Method, tsDecl);\n        }\n\n        public TypeTransform AddExtensionMethod<TResult>(Func<TResult> method, string tsDecl = null)\n        {\n            return AddExtensionMethod(method.Method, tsDecl);\n        }\n\n        public TypeTransform AddExtensionMethod<T1, TResult>(Func<T1, TResult> method, string tsDecl = null)\n        {\n            return AddExtensionMethod(method.Method, tsDecl);\n        }\n\n        public TypeTransform AddExtensionMethod<T1, T2, TResult>(Func<T1, T2, TResult> method, string tsDecl = null)\n        {\n            return AddExtensionMethod(method.Method, tsDecl);\n        }\n\n        public TypeTransform AddExtensionMethod(MethodInfo method, string tsDecl = null)\n        {\n            if (extensionMethods == null)\n            {\n                extensionMethods = new HashSet<MethodInfo>();\n            }\n\n            if (!extensionMethods.Contains(method) && !Filter(method))\n            {\n                extensionMethods.Add(method);\n                AddTSMethodDeclaration(method, tsDecl);\n            }\n\n            return this;\n        }\n        #endregion\n\n        public TypeTransform AddStaticMethod(Native.JSCFunction method, string tsDecl = null)\n        {\n            if (staticMethods == null)\n            {\n                staticMethods = new HashSet<Native.JSCFunction>();\n            }\n\n            if (staticMethods.Add(method))\n            {\n                AddTSMethodDeclaration(method.Method, tsDecl);\n            }\n\n            return this;\n        }\n\n\n        public JSHotfixAttribute GetHotfix()\n        {\n            return _hotfix;\n        }\n\n        public void SetHotfix(JSHotfixAttribute attr)\n        {\n            _hotfix = attr;\n        }\n\n        public void ForEachAdditionalTSMethodDeclaration(Action<string> fn)\n        {\n            if (_tsAdditionalMethodDeclarations != null)\n            {\n                foreach (var decl in _tsAdditionalMethodDeclarations)\n                {\n                    fn(decl);\n                }\n            }\n        }\n\n        public string GetTSNaming()\n        {\n            return _tsNaming;\n        }\n\n        /// <summary>\n        /// Override the type name in typescript.\n        /// The type hierarchy from CSharp will be used as the type path in typescript.\n        /// </summary>\n        public TypeTransform Rename(string name)\n        {\n            CodeGenUtils.Assert(!name.Contains('.') && !name.Contains('+'), \"hierarchy overwritting is not allowed\");\n            _tsNaming = name;\n            return this;\n        }\n\n        public TypeTransform AddTSMethodDeclaration(string spec)\n        {\n            if (_tsAdditionalMethodDeclarations == null)\n            {\n                _tsAdditionalMethodDeclarations = new List<string>();\n            }\n            _tsAdditionalMethodDeclarations.Add(spec);\n            return this;\n        }\n\n        public TypeTransform AddTSMethodDeclaration(params string[] specs)\n        {\n            if (_tsAdditionalMethodDeclarations == null)\n            {\n                _tsAdditionalMethodDeclarations = new List<string>();\n            }\n            _tsAdditionalMethodDeclarations.AddRange(specs);\n            return this;\n        }\n\n        public bool IsMemberBlocked(string memeberName)\n        {\n            return _memberBlacklist != null && _memberBlacklist.Contains(memeberName);\n        }\n\n        /// <summary>\n        /// mark any member as blocked with specific name. \n        /// </summary>\n        /// <param name=\"memberName\">the name of member you want to block</param>\n        public TypeTransform SetMemberBlocked(string memberName)\n        {\n            if (_memberBlacklist == null)\n            {\n                _memberBlacklist = new HashSet<string>();\n            }\n            _memberBlacklist.Add(memberName);\n            return this;\n        }\n\n        // 指定的方法是否被屏蔽\n        public bool IsBlocked(MethodBase method)\n        {\n            return _methodBlacklist.Contains(method);\n        }\n\n        public bool IsBlocked(int token)\n        {\n            return _methodBlacklist.Any(i => i.MetadataToken == token);\n        }\n\n        /// <summary>\n        /// block all of the constructors \n        /// </summary>\n        public TypeTransform SetAllConstructorsBlocked()\n        {\n            foreach (var ctor in _type.GetConstructors())\n            {\n                _methodBlacklist.Add(ctor);\n            }\n\n            return this;\n        }\n\n        /// <summary>\n        /// block the constructors with specific parameters\n        /// </summary>\n        public TypeTransform SetConstructorBlocked(params Type[] parameters)\n        {\n            var method = _type.GetConstructor(parameters);\n            if (method != null)\n            {\n                _methodBlacklist.Add(method);\n            }\n            return this;\n        }\n\n        /// <summary>\n        /// 屏蔽指定名字与签名的方法\n        /// </summary>\n        public TypeTransform SetMethodBlocked(string name, params Type[] parameters)\n        {\n            var method = _type.GetMethod(name, parameters);\n            if (method != null)\n            {\n                _methodBlacklist.Add(method);\n            }\n            return this;\n        }\n\n        /// <summary>\n        /// specify the method name in JS instead of it's C# name\n        /// </summary>\n        public TypeTransform SetMethodJSName(string jsName, string name, params Type[] parameters)\n        {\n            var method = _type.GetMethod(name, parameters);\n            if (method != null)\n            {\n                _memberNameAlias[method] = jsName;\n            }\n\n            return this;\n        }\n\n        // TS: 为指定类型的匹配方法添加声明映射 (仅用于优化代码提示体验)\n        public TypeTransform AddTSMethodDeclaration(string spec, string name, params Type[] parameters)\n        {\n            var method = _type.GetMethod(name, parameters);\n            if (method != null)\n            {\n                _tsMethodDeclarations[method] = spec;\n            }\n            return this;\n        }\n\n        public TypeTransform AddTSMethodDeclaration(MethodBase method, string spec)\n        {\n            if (method != null && spec != null)\n            {\n                _tsMethodDeclarations[method] = spec;\n            }\n            return this;\n        }\n\n        public bool GetTSMethodDeclaration(MethodBase method, out string code)\n        {\n            return _tsMethodDeclarations.TryGetValue(method, out code);\n        }\n\n        public TypeTransform WriteCrossBindingConstructor(params Type[] parameters)\n        {\n            _csConstructorOverride = CommonFix.CrossBindConstructor;\n            return this;\n        }\n\n        public TypeTransform WriteCSMethodOverrideBinding(string methodName, Native.JSCFunction writer)\n        {\n            _csMethodOverride[methodName] = writer;\n            return this;\n        }\n\n        public Native.JSCFunction GetCSMethodOverrideBinding(string methodName)\n        {\n            return _csMethodOverride.TryGetValue(methodName, out var func) ? func : null;\n        }\n    }\n}\n\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/TypeTransform.cs.meta",
    "content": "fileFormatVersion: 2\nguid: add2d696e44797549b3a17e243a1900b\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/jsb.editor.binding.asmdef",
    "content": "{\n    \"name\": \"jsb.editor.binding\",\n    \"rootNamespace\": \"\",\n    \"references\": [\n        \"GUID:118b4ca3a1852354bac065cf952c1e85\",\n        \"GUID:595d45be140461240b6b4358dc45f2c0\",\n        \"GUID:ac4126d60783f3d4a98aee6be9a997aa\"\n    ],\n    \"includePlatforms\": [],\n    \"excludePlatforms\": [],\n    \"allowUnsafeCode\": true,\n    \"overrideReferences\": false,\n    \"precompiledReferences\": [],\n    \"autoReferenced\": true,\n    \"defineConstraints\": [],\n    \"versionDefines\": [],\n    \"noEngineReferences\": false\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor/jsb.editor.binding.asmdef.meta",
    "content": "fileFormatVersion: 2\nguid: eda0539582471264796e5affb41fe082\nAssemblyDefinitionImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Editor.meta",
    "content": "fileFormatVersion: 2\nguid: 51a232a4c4ed9d043929ca9c501f6a30\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/OperatorDecl.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\nusing QuickJS.Native;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    public class OperatorDecl\r\n    {\r\n        private Type type;\r\n        private List<OperatorDef> self;\r\n        private List<CrossOperatorDef> left;\r\n        private List<CrossOperatorDef> right;\r\n\r\n        public OperatorDecl(Type type)\r\n        {\r\n            this.type = type;\r\n            self = new List<OperatorDef>();\r\n            left = new List<CrossOperatorDef>();\r\n            right = new List<CrossOperatorDef>();\r\n        }\r\n\r\n        public void AddOperator(string op, JSValue value)\r\n        {\r\n            self.Add(new OperatorDef(op, value));\r\n        }\r\n\r\n        public void AddCrossOperator(string op, JSValue value, bool bLeft, Type sideType)\r\n        {\r\n            var list = bLeft ? left : right;\r\n            var count = list.Count;\r\n            for (var i = 0; i < count; i++)\r\n            {\r\n                if (list[i].type == sideType)\r\n                {\r\n                    list[i].operators.Add(new OperatorDef(op, value));\r\n                    return;\r\n                }\r\n            }\r\n            var newCrossDef = new CrossOperatorDef(sideType);\r\n            newCrossDef.operators.Add(new OperatorDef(op, value));\r\n            list.Add(newCrossDef);\r\n        }\r\n\r\n        ///<summary>\r\n        /// 实际定义运算符重载 (请保证 create 本身有效)\r\n        ///</summary>\r\n        public unsafe void Register(TypeRegister register, JSContext ctx, JSValue create)\r\n        {\r\n            var proto = register.FindChainedPrototypeOf(type);\r\n            var leftCount = left.Count;\r\n            var rightCount = right.Count;\r\n            var argv = new JSValue[leftCount + rightCount + 1];\r\n\r\n            argv[0] = JSApi.JS_NewObject(ctx);\r\n            for (int i = 0, len = self.Count; i < len; i++)\r\n            {\r\n                var def = self[i];\r\n                // var funcVal = JSApi.JS_NewCFunction(ctx, def.func, def.op, def.length);\r\n                JSApi.JS_DefinePropertyValue(ctx, argv[0], register.GetAtom(def.op), def.value);\r\n                // UnityEngine.Debug.LogFormat(\"{0} operator {1}\", type, def.op);\r\n            }\r\n\r\n            for (int i = 0, len = leftCount; i < len; i++)\r\n            {\r\n                var cross = left[i];\r\n                var sideCtor = register.GetConstructor(cross.type);\r\n                var operator_ = JSApi.JS_NewObject(ctx);\r\n                var side = \"left\";\r\n                JSApi.JS_SetProperty(ctx, operator_, register.GetAtom(side), sideCtor);\r\n                for (int opIndex = 0, opCount = cross.operators.Count; opIndex < opCount; opIndex++)\r\n                {\r\n                    var def = cross.operators[opIndex];\r\n                    // var funcVal = JSApi.JS_NewCFunction(ctx, def.func, def.op, def.length);\r\n                    JSApi.JS_DefinePropertyValue(ctx, operator_, register.GetAtom(def.op), def.value);\r\n                    argv[i + 1] = operator_;\r\n                    // UnityEngine.Debug.LogFormat(\"{0} {1} operator {2} {3} ({4})\", type, side, def.op, cross.type, sideCtor);\r\n                }\r\n            }\r\n\r\n            for (int i = 0, len = rightCount; i < len; i++)\r\n            {\r\n                var cross = right[i];\r\n                var sideCtor = register.GetConstructor(cross.type);\r\n                var operator_ = JSApi.JS_NewObject(ctx);\r\n                var side = \"right\";\r\n                JSApi.JS_SetProperty(ctx, operator_, register.GetAtom(side), sideCtor);\r\n                for (int opIndex = 0, opCount = cross.operators.Count; opIndex < opCount; opIndex++)\r\n                {\r\n                    var def = cross.operators[opIndex];\r\n                    // var funcVal = JSApi.JS_NewCFunction(ctx, def.func, def.op, def.length);\r\n                    JSApi.JS_DefinePropertyValue(ctx, operator_, register.GetAtom(def.op), def.value);\r\n                    argv[i + 1 + leftCount] = operator_;\r\n                    // UnityEngine.Debug.LogFormat(\"{0} {1} operator {2} {3} ({4})\", type, side, def.op, cross.type, sideCtor);\r\n                }\r\n            }\r\n\r\n            fixed (JSValue* ptr = argv)\r\n            {\r\n                var rval = JSApi.JS_Call(ctx, create, JSApi.JS_UNDEFINED, argv.Length, ptr);\r\n                if (rval.IsException())\r\n                {\r\n                    ctx.print_exception(string.Format(\"[{0} operators failed]\", type));\r\n                }\r\n                else\r\n                {\r\n                    JSApi.JS_DefinePropertyValue(ctx, proto, JSApi.JS_ATOM_Symbol_operatorSet, rval);\r\n                }\r\n            }\r\n\r\n            for (int i = 0, len = argv.Length; i < len; i++)\r\n            {\r\n                JSApi.JS_FreeValue(ctx, argv[i]);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/OperatorDecl.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 7fca01a6fda646108fac38e7ceb1adad\r\ntimeCreated: 1591936629"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/TypeRegister.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\nusing QuickJS.Native;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using Utils;\r\n\r\n    public class TypeRegister\r\n    {\r\n        private ScriptContext _context;\r\n        private ITypeDB _db;\r\n        private int _refCount;\r\n\r\n        // 注册过程中产生的 atom, 完成后自动释放 \r\n        private AtomCache _atoms;\r\n        private List<Type> _pendingTypes = new List<Type>();\r\n        private List<ClassDecl> _pendingClasses = new List<ClassDecl>();\r\n        \r\n        private List<OperatorDecl> _operatorDecls = new List<OperatorDecl>();\r\n        private Dictionary<Type, int> _operatorDeclIndex = new Dictionary<Type, int>();\r\n\r\n        public static implicit operator JSContext(TypeRegister register)\r\n        {\r\n            return register._context;\r\n        }\r\n\r\n        public ScriptRuntime GetRuntime()\r\n        {\r\n            return _context.GetRuntime();\r\n        }\r\n\r\n        public ScriptContext GetContext()\r\n        {\r\n            return _context;\r\n        }\r\n\r\n        public JSAtom GetAtom(string name)\r\n        {\r\n            return _atoms.GetAtom(name);\r\n        }\r\n\r\n        public TypeRegister(ScriptContext context)\r\n        {\r\n            _context = context;\r\n            _refCount = 1;\r\n            _atoms = new AtomCache(_context);\r\n            _db = context.GetTypeDB();\r\n        }\r\n\r\n        public void AddRef()\r\n        {\r\n            _refCount++;\r\n        }\r\n\r\n        public ITypeDB GetTypeDB()\r\n        {\r\n            return _db;\r\n        }\r\n\r\n        // 覆盖现有定义\r\n        public ClassDecl CreateClassWithPrototype(Type type, JSValue protoVal)\r\n        {\r\n            JSContext ctx = _context;\r\n            var ctorVal = JSApi.JS_GetProperty(_context, protoVal, JSApi.JS_ATOM_constructor);\r\n            var decl = new ClassDecl(this, ctorVal, protoVal, type);\r\n            JSApi.JS_FreeValue(ctx, ctorVal);\r\n            _pendingClasses.Add(decl);\r\n            return decl;\r\n        }\r\n\r\n        public ClassDecl CreateEnum(string typename, Type type)\r\n        {\r\n            return CreateClass(JSApi.JS_UNDEFINED, typename, type, JSNative.class_private_ctor);\r\n        }\r\n\r\n        public ClassDecl CreateClass(string typename, Type type, JSCFunctionMagic ctorFunc)\r\n        {\r\n            return CreateClass(JSApi.JS_UNDEFINED, typename, type, ctorFunc);\r\n        }\r\n\r\n        public ClassDecl CreateGlobalClass(string typename, Type type, JSCFunctionMagic ctorFunc)\r\n        {\r\n            var globalObject = _context.GetGlobalObject();\r\n            var decl = CreateClass(globalObject, typename, type, ctorFunc);\r\n            JSApi.JS_FreeValue(_context, globalObject);\r\n            return decl;\r\n        }\r\n\r\n        public bool IsGlobalRegistered(string typename)\r\n        {\r\n            JSContext ctx = _context;\r\n            var globalObject = _context.GetGlobalObject();\r\n            var prop = JSApi.JS_GetProperty(ctx, globalObject, GetAtom(typename));\r\n            var retVal = !prop.IsNullish();\r\n            JSApi.JS_FreeValue(_context, prop);\r\n            JSApi.JS_FreeValue(_context, globalObject);\r\n            return retVal;\r\n        }\r\n\r\n        /// <summary>\r\n        /// 在指定的对象上创建类型\r\n        /// </summary>\r\n        public ClassDecl CreateClass(JSValue nsValue, string typename, Type type, JSCFunctionMagic ctorFunc)\r\n        {\r\n            var nameAtom = GetAtom(typename);\r\n            JSContext ctx = _context;\r\n            var protoVal = JSApi.JS_NewObject(ctx);\r\n            var type_id = RegisterType(type, protoVal);\r\n            var ctorVal = JSApi.JSB_NewConstructor(ctx, ctorFunc, nameAtom, type_id);\r\n            var decl = new ClassDecl(this, ctorVal, protoVal, type);\r\n            JSApi.JS_SetConstructor(ctx, ctorVal, protoVal);\r\n            JSApi.JSB_SetBridgeType(ctx, ctorVal, GetAtom(Values.KeyForCSharpTypeID), type_id);\r\n            JSApi.JSB_SetBridgeType(ctx, protoVal, GetAtom(Values.KeyForCSharpTypeID), type_id);\r\n            if (!nsValue.IsNullish())\r\n            {\r\n                JSApi.JS_DefinePropertyValue(ctx, nsValue, nameAtom, ctorVal);\r\n            }\r\n            else\r\n            {\r\n                JSApi.JS_FreeValue(ctx, ctorVal);\r\n            }\r\n            // Debug.LogFormat(\"define class {0}: {1}\", type, protoVal);\r\n            JSApi.JS_FreeValue(ctx, protoVal);\r\n            _pendingClasses.Add(decl);\r\n            return decl;\r\n        }\r\n\r\n        public ClassDecl CreateClass(string typename)\r\n        {\r\n            return CreateClass(JSApi.JS_UNDEFINED, typename);\r\n        }\r\n\r\n        public ClassDecl CreateClass(JSValue nsValue, string typename)\r\n        {\r\n            var nameAtom = GetAtom(typename);\r\n            JSContext ctx = _context;\r\n            var protoVal = JSApi.JS_NewObject(ctx);\r\n            var ctorVal = JSApi.JSB_NewConstructor(ctx, JSNative.class_private_ctor, nameAtom, 0);\r\n            var decl = new ClassDecl(this, ctorVal, protoVal, null);\r\n            JSApi.JS_SetConstructor(ctx, ctorVal, protoVal);\r\n            if (!nsValue.IsNullish())\r\n            {\r\n                JSApi.JS_DefinePropertyValue(ctx, nsValue, nameAtom, ctorVal);\r\n            }\r\n            else\r\n            {\r\n                JSApi.JS_FreeValue(ctx, ctorVal);\r\n            }\r\n            // Debug.LogFormat(\"define class {0}: {1}\", type, protoVal);\r\n            JSApi.JS_FreeValue(ctx, protoVal);\r\n            _pendingClasses.Add(decl);\r\n            return decl;\r\n        }\r\n\r\n        public ClassDecl CreateClass(string typename, Type type, IDynamicMethod dynamicMethod)\r\n        {\r\n            return CreateClass(JSApi.JS_UNDEFINED, typename, type, dynamicMethod);\r\n        }\r\n\r\n        public ClassDecl CreateClass(JSValue nsValue, string typename, Type type, IDynamicMethod dynamicMethod)\r\n        {\r\n            var nameAtom = GetAtom(typename);\r\n            JSContext ctx = _context;\r\n            var protoVal = JSApi.JS_NewObject(ctx);\r\n            var type_id = RegisterType(type, protoVal);\r\n            var ctorVal = _db.NewDynamicConstructor(nameAtom, dynamicMethod);\r\n            var decl = new ClassDecl(this, ctorVal, protoVal, type);\r\n            JSApi.JS_SetConstructor(ctx, ctorVal, protoVal);\r\n            JSApi.JSB_SetBridgeType(ctx, ctorVal, GetAtom(Values.KeyForCSharpTypeID), type_id);\r\n            JSApi.JSB_SetBridgeType(ctx, protoVal, GetAtom(Values.KeyForCSharpTypeID), type_id);\r\n            if (!nsValue.IsNullish())\r\n            {\r\n                JSApi.JS_DefinePropertyValue(ctx, nsValue, nameAtom, ctorVal);\r\n            }\r\n            else\r\n            {\r\n                JSApi.JS_FreeValue(ctx, ctorVal);\r\n            }\r\n            // Debug.LogFormat(\"define class {0}: {1}\", type, protoVal);\r\n            JSApi.JS_FreeValue(ctx, protoVal);\r\n            _pendingClasses.Add(decl);\r\n            return decl;\r\n        }\r\n\r\n        // return type id, 不可重复注册\r\n        public int RegisterType(Type type, JSValue proto)\r\n        {\r\n            _pendingTypes.Add(type);\r\n            return _db.AddType(type, proto);\r\n        }\r\n\r\n        private void SubmitOperators()\r\n        {\r\n            // 提交运算符重载\r\n            var ctx = (JSContext)_context;\r\n            var operatorCreate = _context.GetOperatorCreate();\r\n\r\n            if (!operatorCreate.IsUndefined())\r\n            {\r\n                var count = _operatorDecls.Count;\r\n                for (var i = 0; i < count; i++)\r\n                {\r\n                    _operatorDecls[i].Register(this, ctx, operatorCreate);\r\n                }\r\n            }\r\n\r\n            JSApi.JS_FreeValue(ctx, operatorCreate);\r\n            _operatorDeclIndex.Clear();\r\n            _operatorDecls.Clear();\r\n        }\r\n\r\n        private OperatorDecl GetOperatorDecl(Type type, out int index)\r\n        {\r\n            if (_operatorDeclIndex.TryGetValue(type, out index))\r\n            {\r\n                return _operatorDecls[index];\r\n            }\r\n            var decl = new OperatorDecl(type);\r\n            index = _operatorDecls.Count;\r\n            _operatorDeclIndex[type] = index;\r\n            _operatorDecls.Add(decl);\r\n            return decl;\r\n        }\r\n        \r\n        public void RegisterOperator(Type type, string op, JSCFunction func, int length)\r\n        {\r\n            RegisterOperator(type, op, JSApi.JSB_NewCFunction(_context, func, GetAtom(op), length));\r\n        }\r\n\r\n        public void RegisterOperator(Type type, string op, IDynamicMethod func)\r\n        {\r\n            RegisterOperator(type, op, _db.NewDynamicMethod(GetAtom(op), func));\r\n        }\r\n\r\n        public void RegisterOperator(Type type, string op, JSCFunction func, int length, bool left, Type sideType)\r\n        {\r\n            RegisterOperator(type, op, JSApi.JSB_NewCFunction(_context, func, GetAtom(op), length), left, sideType);\r\n        }\r\n\r\n        public void RegisterOperator(Type type, string op, IDynamicMethod func, bool left, Type sideType)\r\n        {\r\n            RegisterOperator(type, op, _db.NewDynamicMethod(GetAtom(op), func), left, sideType);\r\n        }\r\n\r\n        // self operator for type\r\n        public void RegisterOperator(Type type, string op, JSValue value)\r\n        {\r\n            int index;\r\n            var decl = GetOperatorDecl(type, out index);\r\n            decl.AddOperator(op, value);\r\n        }\r\n\r\n        // left/right operator for type\r\n        public void RegisterOperator(Type type, string op, JSValue value, bool left, Type sideType)\r\n        {\r\n            if (sideType == typeof(string) || sideType == typeof(void) || (sideType.IsValueType && (sideType.IsPrimitive || sideType.IsEnum)))\r\n            {\r\n                int index;\r\n                var decl = GetOperatorDecl(type, out index);\r\n                decl.AddCrossOperator(op, value, left, sideType);\r\n            }\r\n            else\r\n            {\r\n                int index1, index2;\r\n                var decl1 = GetOperatorDecl(type, out index1);\r\n                var decl2 = GetOperatorDecl(sideType, out index2);\r\n                if (index2 > index1)\r\n                {\r\n                    decl2.AddCrossOperator(op, value, !left, type);\r\n                }\r\n                else\r\n                {\r\n                    decl1.AddCrossOperator(op, value, left, sideType);\r\n                }\r\n            }\r\n        }\r\n\r\n        // 返回值已经过 DupValue\r\n        public JSValue GetConstructor(Type type)\r\n        {\r\n            if (type == typeof(JSFunction))\r\n            {\r\n                return _context.GetFunctionConstructor();\r\n            }\r\n\r\n            if (type == typeof(string) || type == typeof(char))\r\n            {\r\n                return _context.GetStringConstructor();\r\n            }\r\n\r\n            if (type.IsValueType && (type.IsPrimitive || type.IsEnum))\r\n            {\r\n                return _context.GetNumberConstructor();\r\n            }\r\n\r\n            var val = _db.FindChainedPrototypeOf(type);\r\n            return JSApi.JS_GetProperty(_context, val, JSApi.JS_ATOM_constructor);\r\n        }\r\n\r\n        public JSValue FindChainedPrototypeOf(Type type)\r\n        {\r\n            return _db.FindChainedPrototypeOf(type);\r\n        }\r\n\r\n        public JSValue FindPrototypeOf(Type type)\r\n        {\r\n            return _db.FindPrototypeOf(type);\r\n        }\r\n\r\n        public void Finish()\r\n        {\r\n            _refCount--;\r\n\r\n            if (_refCount == 0)\r\n            {\r\n                _context.ReleaseTypeRegister(this);\r\n                SubmitOperators();\r\n                _atoms.Clear();\r\n                var ctx = (JSContext)_context;\r\n\r\n                for (int i = 0, count = _pendingTypes.Count; i < count; i++)\r\n                {\r\n                    var type = _pendingTypes[i];\r\n                    var proto = _db.GetPrototypeOf(type);\r\n                    if (!proto.IsNullish())\r\n                    {\r\n                        var baseType = type.BaseType;\r\n                        var parentProto = _db.FindChainedPrototypeOf(baseType);\r\n                        if (!parentProto.IsNullish())\r\n                        {\r\n                            JSApi.JS_SetPrototype(ctx, proto, parentProto);\r\n                        }\r\n                    }\r\n                }\r\n\r\n                for (int i = 0, count = _pendingClasses.Count; i < count; i++)\r\n                {\r\n                    var clazz = _pendingClasses[i];\r\n                    clazz.Close();\r\n                }\r\n\r\n                _pendingClasses.Clear();\r\n                _pendingTypes.Clear();\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/TypeRegister.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: b06f06ed2a4347a28bad3427ffbb2278\r\ntimeCreated: 1590991493"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Bounds.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using UnityEngine;\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static unsafe JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, Bounds o, int type_id, bool disposable)\r\n        {\r\n            var val = JSApi.JSB_NewBridgeClassValue(ctx, new_target, sizeof(float) * 6);\r\n            if (!JSApi.JS_IsException(val))\r\n            {\r\n                js_rebind_this(ctx, val, ref o);\r\n            }\r\n            return val;\r\n        }\r\n\r\n        public static unsafe bool js_rebind_this(JSContext ctx, JSValue this_obj, ref Bounds o)\r\n        {\r\n            var data = stackalloc float[6];\r\n            var center = o.center;\r\n            var size = o.size;\r\n            \r\n            JSApi.MemoryCopy(&center.x, data, sizeof(float) * 3, sizeof(float) * 3);\r\n            JSApi.MemoryCopy(&size.x, data + 3, sizeof(float) * 3, sizeof(float) * 3);\r\n            return JSApi.jsb_set_floats(ctx, this_obj, 6, data) == 1;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, Bounds o)\r\n        {\r\n            var proto = FindPrototypeOf<Bounds>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(float) * 6);\r\n            js_rebind_this(ctx, val, ref o);\r\n            return val;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, Bounds? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            var proto = FindPrototypeOf<Bounds>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(float) * 6);\r\n            var v = (Bounds)o;\r\n            js_rebind_this(ctx, val, ref v);\r\n            return val;\r\n        }\r\n\r\n        public static unsafe bool js_get_structvalue(JSContext ctx, JSValue val, out Bounds o)\r\n        {\r\n            var data = stackalloc float[6];\r\n            var ret = JSApi.jsb_get_floats(ctx, val, 6, data);\r\n            o = new Bounds(new Vector3(data[0], data[1], data[2]), new Vector3(data[3], data[4], data[5]));\r\n            return ret != 0;\r\n        }\r\n\r\n        public static unsafe bool js_get_structvalue(JSContext ctx, JSValue val, out Bounds? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            var data = stackalloc float[6];\r\n            var ret = JSApi.jsb_get_floats(ctx, val, 6, data);\r\n            o = new Bounds(new Vector3(data[0], data[1], data[2]), new Vector3(data[3], data[4], data[5]));\r\n            return ret != 0;\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Bounds.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: a5c7e1e4ef201e248a1a5d67efb46fa9\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_BoundsInt.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using UnityEngine;\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static unsafe JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, BoundsInt o, int type_id, bool disposable)\r\n        {\r\n            var val = JSApi.JSB_NewBridgeClassValue(ctx, new_target, sizeof(int) * 6);\r\n            if (!JSApi.JS_IsException(val))\r\n            {\r\n                js_rebind_this(ctx, val, ref o);\r\n            }\r\n            return val;\r\n        }\r\n\r\n        public static unsafe bool js_rebind_this(JSContext ctx, JSValue this_obj, ref BoundsInt o)\r\n        {\r\n            var data = stackalloc int[6];\r\n            var position = o.position;\r\n            var size = o.size;\r\n            data[0] = position.x;\r\n            data[1] = position.y;\r\n            data[2] = position.z;\r\n            data[3] = size.x;\r\n            data[4] = size.y;\r\n            data[5] = size.z;\r\n            return JSApi.jsb_set_bytes(ctx, this_obj, sizeof(int) * 6, (byte*)data) == 1;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, BoundsInt o)\r\n        {\r\n            var proto = FindPrototypeOf<BoundsInt>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(int) * 6);\r\n            js_rebind_this(ctx, val, ref o);\r\n            return val;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, BoundsInt? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            var proto = FindPrototypeOf<BoundsInt>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(int) * 6);\r\n            var v = (BoundsInt)o;\r\n            js_rebind_this(ctx, val, ref v);\r\n            return val;\r\n        }\r\n\r\n        public static unsafe bool js_get_structvalue(JSContext ctx, JSValue val, out BoundsInt o)\r\n        {\r\n            var data = stackalloc int[6];\r\n            var ret = JSApi.jsb_get_bytes(ctx, val, sizeof(int) * 6, (byte*)data);\r\n            o = new BoundsInt(new Vector3Int(data[0], data[1], data[2]), new Vector3Int(data[3], data[4], data[5]));\r\n            return ret != 0;\r\n        }\r\n\r\n        public static unsafe bool js_get_structvalue(JSContext ctx, JSValue val, out BoundsInt? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            var data = stackalloc int[6];\r\n            var ret = JSApi.jsb_get_bytes(ctx, val, sizeof(int) * 6, (byte*)data);\r\n            o = new BoundsInt(new Vector3Int(data[0], data[1], data[2]), new Vector3Int(data[3], data[4], data[5]));\r\n            return ret != 0;\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_BoundsInt.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 9fb597c76c37c4a40b015e83603b2e6f\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Color.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using UnityEngine;\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, Color o, int type_id, bool disposable)\r\n        {\r\n            var val = JSApi.JSB_NewBridgeClassValue(ctx, new_target, sizeof(float) * 4);\r\n            if (!JSApi.JS_IsException(val))\r\n            {\r\n                JSApi.jsb_set_float_4(ctx, val, o.r, o.g, o.b, o.a);\r\n            }\r\n            return val;\r\n        }\r\n\r\n        public static bool js_rebind_this(JSContext ctx, JSValue this_obj, ref Color o)\r\n        {\r\n            return JSApi.jsb_set_float_4(ctx, this_obj, o.r, o.g, o.b, o.a) == 1;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, Color o)\r\n        {\r\n            var proto = FindPrototypeOf<Color>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(float) * 4);\r\n            JSApi.jsb_set_float_4(ctx, val, o.r, o.g, o.b, o.a);\r\n            return val;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Color o)\r\n        {\r\n            float r, g, b, a;\r\n            var ret = JSApi.jsb_get_float_4(ctx, val, out r, out g, out b, out a);\r\n            if (ret != 0)\r\n            {\r\n                o = new Color(r, g, b, a);\r\n                return true;\r\n            }\r\n\r\n            float[] batch;\r\n            if (js_get_primitive(ctx, val, out batch))\r\n            {\r\n                var len = batch.Length;\r\n                switch (len)\r\n                {\r\n                    case 4: o = new Color(batch[0], batch[1], batch[2], batch[3]); return true;\r\n                    case 3: o = new Color(batch[0], batch[1], batch[2]); return true;\r\n                    case 2: o = new Color(batch[0], batch[1], 1.0f); return true;\r\n                    case 1: o = new Color(batch[0], 1.0f, 1.0f); return true;\r\n                    default: o = new Color(); return true;\r\n                }\r\n            }\r\n            o = new Color(); \r\n            return false;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Color? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n\r\n            Color v;\r\n            var rval = js_get_structvalue(ctx, val, out v);\r\n            o = v;\r\n            return rval;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Color[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new Color[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    Color e;\r\n                    if (js_get_structvalue(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n\r\n            return js_get_classvalue<Color[]>(ctx, val, out o);\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Color.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: f8fe6072236ac034db9b80c4248add3d\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Color32.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using UnityEngine;\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, Color32 o, int type_id, bool disposable)\r\n        {\r\n            var val = JSApi.JSB_NewBridgeClassValue(ctx, new_target, sizeof(byte) * 4);\r\n            if (!JSApi.JS_IsException(val))\r\n            {\r\n                JSApi.jsb_set_byte_4(ctx, val, o.r, o.g, o.b, o.a);\r\n            }\r\n            return val;\r\n        }\r\n\r\n        public static bool js_rebind_this(JSContext ctx, JSValue this_obj, ref Color32 o)\r\n        {\r\n            return JSApi.jsb_set_byte_4(ctx, this_obj, o.r, o.g, o.b, o.a) == 1;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, Color32 o)\r\n        {\r\n            var proto = FindPrototypeOf<Color32>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(byte) * 4);\r\n            JSApi.jsb_set_byte_4(ctx, val, o.r, o.g, o.b, o.a);\r\n            return val;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Color32 o)\r\n        {\r\n            byte r, g, b, a;\r\n            var ret = JSApi.jsb_get_byte_4(ctx, val, out r, out g, out b, out a);\r\n            o = new Color32((byte)r, (byte)g, (byte)b, (byte)a);\r\n            return ret != 0;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Color32? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            byte r, g, b, a;\r\n            var ret = JSApi.jsb_get_byte_4(ctx, val, out r, out g, out b, out a);\r\n            o = new Color32((byte)r, (byte)g, (byte)b, (byte)a);\r\n            return ret != 0;\r\n        }\r\n        \r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Color32[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new Color32[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    Color32 e;\r\n                    if (js_get_structvalue(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            \r\n            return js_get_classvalue<Color32[]>(ctx, val, out o);\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Color32.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 3fe12a0adc003614081c1c3ef9779ca8\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_DateTime.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static unsafe JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, DateTime o, int type_id, bool disposable)\r\n        {\r\n            var val = JSApi.JSB_NewBridgeClassValue(ctx, new_target, sizeof(long));\r\n            if (!JSApi.JS_IsException(val))\r\n            {\r\n                JSApi.jsb_set_bytes(ctx, val, o.Ticks);\r\n            }\r\n            return val;\r\n        }\r\n\r\n        public static unsafe bool js_rebind_this(JSContext ctx, JSValue this_obj, ref DateTime o)\r\n        {\r\n            return JSApi.jsb_set_bytes(ctx, this_obj, o.Ticks) == 1;\r\n        }\r\n\r\n        public static unsafe JSValue js_push_structvalue(JSContext ctx, DateTime o)\r\n        {\r\n            var proto = FindPrototypeOf<DateTime>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(long));\r\n            JSApi.jsb_set_bytes(ctx, val, o.Ticks);\r\n            return val;\r\n        }\r\n\r\n        public static unsafe bool js_get_structvalue(JSContext ctx, JSValue val, out DateTime o)\r\n        {\r\n            long p;\r\n            var ret = JSApi.jsb_get_bytes(ctx, val, out p);\r\n            o = new DateTime(p);\r\n            return ret != 0;\r\n        }\r\n\r\n        public static unsafe bool js_get_structvalue(JSContext ctx, JSValue val, out DateTime? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            long p;\r\n            var ret = JSApi.jsb_get_bytes(ctx, val, out p);\r\n            o = new DateTime(p);\r\n            return ret != 0;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_DateTime.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: f8f5bf509c045d245bd68658e146be53\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_LayerMask.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using UnityEngine;\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, LayerMask o, int type_id, bool disposable)\r\n        {\r\n            var val = JSApi.JSB_NewBridgeClassValue(ctx, new_target, sizeof(int) * 1);\r\n            if (!JSApi.JS_IsException(val))\r\n            {\r\n                JSApi.jsb_set_int_1(ctx, val, o.value);\r\n            }\r\n            return val;\r\n        }\r\n\r\n        public static bool js_rebind_this(JSContext ctx, JSValue this_obj, ref LayerMask o)\r\n        {\r\n            return JSApi.jsb_set_int_1(ctx, this_obj, o.value) == 1;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, LayerMask o)\r\n        {\r\n            var proto = FindPrototypeOf<LayerMask>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(int) * 1);\r\n            JSApi.jsb_set_int_1(ctx, val, o.value);\r\n            return val;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, LayerMask? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            var proto = FindPrototypeOf<LayerMask>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(int) * 1);\r\n            JSApi.jsb_set_int_1(ctx, val, ((LayerMask)o).value);\r\n            return val;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out LayerMask o)\r\n        {\r\n            int pres;\r\n            if (JSApi.jsb_get_int_1(ctx, val, out pres) == 0)\r\n            {\r\n                if (JSApi.JS_ToInt32(ctx, out pres, val) < 0)\r\n                {\r\n                    o = (LayerMask)0;\r\n                    return false;\r\n                }\r\n            }\r\n            o = (LayerMask)pres;\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out LayerMask? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            int pres;\r\n            if (JSApi.jsb_get_int_1(ctx, val, out pres) == 0)\r\n            {\r\n                if (JSApi.JS_ToInt32(ctx, out pres, val) < 0)\r\n                {\r\n                    o = (LayerMask)0;\r\n                    return false;\r\n                }\r\n            }\r\n            o = (LayerMask)pres;\r\n            return true;\r\n        }\r\n\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_LayerMask.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 735a83464cc90234f9bc371a16b5847d\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Matrix4x4.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using UnityEngine;\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static unsafe JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, Matrix4x4 o, int type_id, bool disposable)\r\n        {\r\n            var val = JSApi.JSB_NewBridgeClassValue(ctx, new_target, sizeof(float) * 4 * 4);\r\n            if (!JSApi.JS_IsException(val))\r\n            {\r\n                js_rebind_this(ctx, val, ref o);\r\n            }\r\n            return val;\r\n        }\r\n\r\n        public static unsafe bool js_rebind_this(JSContext ctx, JSValue this_obj, ref Matrix4x4 o)\r\n        {\r\n            var _matrix_floats_buffer = stackalloc float[16];\r\n\r\n            _matrix_floats_buffer[0] = o.m00;\r\n            _matrix_floats_buffer[1] = o.m10;\r\n            _matrix_floats_buffer[2] = o.m20;\r\n            _matrix_floats_buffer[3] = o.m30;\r\n\r\n            _matrix_floats_buffer[4] = o.m01;\r\n            _matrix_floats_buffer[5] = o.m11;\r\n            _matrix_floats_buffer[6] = o.m21;\r\n            _matrix_floats_buffer[7] = o.m31;\r\n\r\n            _matrix_floats_buffer[8] = o.m02;\r\n            _matrix_floats_buffer[9] = o.m12;\r\n            _matrix_floats_buffer[10] = o.m22;\r\n            _matrix_floats_buffer[11] = o.m32;\r\n\r\n            _matrix_floats_buffer[12] = o.m03;\r\n            _matrix_floats_buffer[13] = o.m13;\r\n            _matrix_floats_buffer[14] = o.m23;\r\n            _matrix_floats_buffer[15] = o.m33;\r\n\r\n            return JSApi.jsb_set_floats(ctx, this_obj, 4 * 4, _matrix_floats_buffer) == 1;\r\n        }\r\n\r\n        public static unsafe JSValue js_push_structvalue(JSContext ctx, Matrix4x4 o)\r\n        {\r\n            var proto = FindPrototypeOf<Matrix4x4>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(float) * 4 * 4);\r\n\r\n            js_rebind_this(ctx, val, ref o);\r\n            return val;\r\n        }\r\n\r\n        public static unsafe bool js_get_structvalue(JSContext ctx, JSValue val, out Matrix4x4 o)\r\n        {\r\n            var _matrix_floats_buffer = stackalloc float[16];\r\n            var ret = JSApi.jsb_get_floats(ctx, val, 16, _matrix_floats_buffer);\r\n            var c0 = new Vector4(_matrix_floats_buffer[0], _matrix_floats_buffer[1], _matrix_floats_buffer[2], _matrix_floats_buffer[3]);\r\n            var c1 = new Vector4(_matrix_floats_buffer[4], _matrix_floats_buffer[5], _matrix_floats_buffer[6], _matrix_floats_buffer[7]);\r\n            var c2 = new Vector4(_matrix_floats_buffer[8], _matrix_floats_buffer[8], _matrix_floats_buffer[10], _matrix_floats_buffer[11]);\r\n            var c3 = new Vector4(_matrix_floats_buffer[12], _matrix_floats_buffer[13], _matrix_floats_buffer[14], _matrix_floats_buffer[15]);\r\n            o = new Matrix4x4(c0, c1, c2, c3);\r\n            return ret != 0;\r\n        }\r\n\r\n        public static unsafe bool js_get_structvalue(JSContext ctx, JSValue val, out Matrix4x4? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            var _matrix_floats_buffer = stackalloc float[16];\r\n            var ret = JSApi.jsb_get_floats(ctx, val, 16, _matrix_floats_buffer);\r\n            var c0 = new Vector4(_matrix_floats_buffer[0], _matrix_floats_buffer[1], _matrix_floats_buffer[2], _matrix_floats_buffer[3]);\r\n            var c1 = new Vector4(_matrix_floats_buffer[4], _matrix_floats_buffer[5], _matrix_floats_buffer[6], _matrix_floats_buffer[7]);\r\n            var c2 = new Vector4(_matrix_floats_buffer[8], _matrix_floats_buffer[8], _matrix_floats_buffer[10], _matrix_floats_buffer[11]);\r\n            var c3 = new Vector4(_matrix_floats_buffer[12], _matrix_floats_buffer[13], _matrix_floats_buffer[14], _matrix_floats_buffer[15]);\r\n            o = new Matrix4x4(c0, c1, c2, c3);\r\n            return ret != 0;\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Matrix4x4.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: b4fb7ea333903cb40a21e2b38f9bed62\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Preserve.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using UnityEngine;\r\n    using Native;\r\n\r\n    [UnityEngine.Scripting.Preserve]\r\n    public partial class Values\r\n    {\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Preserve.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 6976f80e0bd861a43a4609eb549b59e2\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Quaternion.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using UnityEngine;\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, Quaternion o, int type_id, bool disposable)\r\n        {\r\n            var val = JSApi.JSB_NewBridgeClassValue(ctx, new_target, sizeof(float) * 4);\r\n            if (!JSApi.JS_IsException(val))\r\n            {\r\n                JSApi.jsb_set_float_4(ctx, val, o.x, o.y, o.z, o.w);\r\n            }\r\n            return val;\r\n        }\r\n\r\n        public static bool js_rebind_this(JSContext ctx, JSValue this_obj, ref Quaternion o)\r\n        {\r\n            return JSApi.jsb_set_float_4(ctx, this_obj, o.x, o.y, o.z, o.w) == 1;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Quaternion o)\r\n        {\r\n            float x, y, z, w;\r\n            var ret = JSApi.jsb_get_float_4(ctx, val, out x, out y, out z, out w);\r\n            o = new Quaternion(x, y, z, w);\r\n            return ret != 0;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Quaternion? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            float x, y, z, w;\r\n            var ret = JSApi.jsb_get_float_4(ctx, val, out x, out y, out z, out w);\r\n            o = new Quaternion(x, y, z, w);\r\n            return ret != 0;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, Quaternion o)\r\n        {\r\n            var proto = FindPrototypeOf<Quaternion>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(float) * 4);\r\n            JSApi.jsb_set_float_4(ctx, val, o.x, o.y, o.z, o.w);\r\n            return val;\r\n        }\r\n\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Quaternion.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 8dac0802d186d9445b809e36ba6822f7\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Ray.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using UnityEngine;\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, Ray o, int type_id, bool disposable)\r\n        {\r\n            var val = JSApi.JSB_NewBridgeClassValue(ctx, new_target, sizeof(float) * 6);\r\n            if (!JSApi.JS_IsException(val))\r\n            {\r\n                js_rebind_this(ctx, val, ref o);\r\n            }\r\n            return val;\r\n        }\r\n\r\n        public static unsafe bool js_rebind_this(JSContext ctx, JSValue this_obj, ref Ray o)\r\n        {\r\n            var buffer = stackalloc float[6];\r\n            var origin = o.origin;\r\n            var direction = o.direction;\r\n            buffer[0] = origin.x;\r\n            buffer[1] = origin.y;\r\n            buffer[2] = origin.z;\r\n            buffer[3] = direction.x;\r\n            buffer[4] = direction.y;\r\n            buffer[5] = direction.z;\r\n            return JSApi.jsb_set_floats(ctx, this_obj, 6, buffer) == 1;\r\n        }\r\n\r\n        public static unsafe bool js_get_structvalue(JSContext ctx, JSValue val, out Ray o)\r\n        {\r\n            var buffer = stackalloc float[6];\r\n            var ret = JSApi.jsb_get_floats(ctx, val, 6, buffer);\r\n            o = new Ray(new Vector3(buffer[0], buffer[1], buffer[2]), \r\n                new Vector3(buffer[3], buffer[4], buffer[5]));\r\n            return ret != 0;\r\n        }\r\n\r\n        public static unsafe JSValue js_push_structvalue(JSContext ctx, Ray o)\r\n        {\r\n            var proto = FindPrototypeOf<Ray>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(float) * 6);\r\n            var buffer = stackalloc float[6];\r\n            var origin = o.origin;\r\n            var direction = o.direction;\r\n            buffer[0] = origin.x;\r\n            buffer[1] = origin.y;\r\n            buffer[2] = origin.z;\r\n            buffer[3] = direction.x;\r\n            buffer[4] = direction.y;\r\n            buffer[5] = direction.z;\r\n            JSApi.jsb_set_floats(ctx, val, 6, buffer);\r\n            return val;\r\n        }\r\n\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Ray.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 6673d31143d79ab408251cf607a63f2d\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Rect.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using UnityEngine;\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, Rect o, int type_id, bool disposable)\r\n        {\r\n            var val = JSApi.JSB_NewBridgeClassValue(ctx, new_target, sizeof(float) * 4);\r\n            if (!JSApi.JS_IsException(val))\r\n            {\r\n                JSApi.jsb_set_float_4(ctx, val, o.x, o.y, o.width, o.height);\r\n            }\r\n            return val;\r\n        }\r\n\r\n        public static bool js_rebind_this(JSContext ctx, JSValue this_obj, ref Rect o)\r\n        {\r\n            return JSApi.jsb_set_float_4(ctx, this_obj, o.x, o.y, o.width, o.height) == 1;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, Rect o)\r\n        {\r\n            var proto = FindPrototypeOf<Rect>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(float) * 4);\r\n            JSApi.jsb_set_float_4(ctx, val, o.x, o.y, o.width, o.height);\r\n            return val;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, Rect? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            var proto = FindPrototypeOf<Rect>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(float) * 4);\r\n            var v = (Rect)o;\r\n            JSApi.jsb_set_float_4(ctx, val, v.x, v.y, v.width, v.height);\r\n            return val;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Rect o)\r\n        {\r\n            float x, y, z, w;\r\n            var ret = JSApi.jsb_get_float_4(ctx, val, out x, out y, out z, out w);\r\n            o = new Rect(x, y, z, w);\r\n            return ret != 0;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Rect? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            float x, y, z, w;\r\n            var ret = JSApi.jsb_get_float_4(ctx, val, out x, out y, out z, out w);\r\n            o = new Rect(x, y, z, w);\r\n            return ret != 0;\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Rect.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 3f18d133f0b50a84ea5a716fd3e12cd4\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Vector2.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using UnityEngine;\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, Vector2 o, int type_id, bool disposable)\r\n        {\r\n            var val = JSApi.JSB_NewBridgeClassValue(ctx, new_target, sizeof(float) * 2);\r\n            if (!JSApi.JS_IsException(val))\r\n            {\r\n                JSApi.jsb_set_float_2(ctx, val, o.x, o.y);\r\n            }\r\n            return val;\r\n        }\r\n\r\n        public static bool js_rebind_this(JSContext ctx, JSValue this_obj, ref Vector2 o)\r\n        {\r\n            return JSApi.jsb_set_float_2(ctx, this_obj, o.x, o.y) == 1;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, Vector2 o)\r\n        {\r\n            var proto = FindPrototypeOf<Vector2>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(float) * 2);\r\n            JSApi.jsb_set_float_2(ctx, val, o.x, o.y);\r\n            return val;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Vector2 o)\r\n        {\r\n            float x, y;\r\n            var ret = JSApi.jsb_get_float_2(ctx, val, out x, out y);\r\n            o = new Vector2(x, y);\r\n            return ret != 0;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Vector2? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            float x, y;\r\n            var ret = JSApi.jsb_get_float_2(ctx, val, out x, out y);\r\n            o = new Vector2(x, y);\r\n            return ret != 0;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Vector2[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new Vector2[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    Vector2 e;\r\n                    if (js_get_structvalue(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            \r\n            return js_get_classvalue<Vector2[]>(ctx, val, out o);\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Vector2.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: c348cebd3a730004a848e4866c1a0842\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Vector2Int.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using UnityEngine;\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, Vector2Int o, int type_id, bool disposable)\r\n        {\r\n            var val = JSApi.JSB_NewBridgeClassValue(ctx, new_target, sizeof(int) * 2);\r\n            if (!JSApi.JS_IsException(val))\r\n            {\r\n                JSApi.jsb_set_int_2(ctx, val, o.x, o.y);\r\n            }\r\n            return val;\r\n        }\r\n\r\n        public static bool js_rebind_this(JSContext ctx, JSValue this_obj, ref Vector2Int o)\r\n        {\r\n            return JSApi.jsb_set_int_2(ctx, this_obj, o.x, o.y) == 1;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, Vector2Int o)\r\n        {\r\n            var proto = FindPrototypeOf<Vector2Int>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(int) * 2);\r\n            JSApi.jsb_set_int_2(ctx, val, o.x, o.y);\r\n            return val;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Vector2Int o)\r\n        {\r\n            int x, y;\r\n            var ret = JSApi.jsb_get_int_2(ctx, val, out x, out y);\r\n            o = new Vector2Int(x, y);\r\n            return ret != 0;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Vector2Int? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            int x, y;\r\n            var ret = JSApi.jsb_get_int_2(ctx, val, out x, out y);\r\n            o = new Vector2Int(x, y);\r\n            return ret != 0;\r\n        }\r\n\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Vector2Int.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 43d2b1773da9e104daffc4a6f6cf4656\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Vector3.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using UnityEngine;\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, Vector3 o, int type_id, bool disposable)\r\n        {\r\n            var val = JSApi.JSB_NewBridgeClassValue(ctx, new_target, sizeof(float) * 3);\r\n            if (!JSApi.JS_IsException(val))\r\n            {\r\n                JSApi.jsb_set_float_3(ctx, val, o.x, o.y, o.z);\r\n            }\r\n            return val;\r\n        }\r\n\r\n        public static bool js_rebind_this(JSContext ctx, JSValue this_obj, ref Vector3 o)\r\n        {\r\n            return JSApi.jsb_set_float_3(ctx, this_obj, o.x, o.y, o.z) == 1;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, Vector3 o)\r\n        {\r\n            var proto = FindPrototypeOf<Vector3>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(float) * 3);\r\n            JSApi.jsb_set_float_3(ctx, val, o.x, o.y, o.z);\r\n            return val;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Vector3 o)\r\n        {\r\n            float x, y, z;\r\n            var ret = JSApi.jsb_get_float_3(ctx, val, out x, out y, out z);\r\n            o = new Vector3(x, y, z);\r\n            return ret != 0;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Vector3? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            float x, y, z;\r\n            var ret = JSApi.jsb_get_float_3(ctx, val, out x, out y, out z);\r\n            o = new Vector3(x, y, z);\r\n            return ret != 0;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Vector3[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new Vector3[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    Vector3 e;\r\n                    if (js_get_structvalue(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            \r\n            return js_get_classvalue<Vector3[]>(ctx, val, out o);\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Vector3.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: dcee99b194f31de46806e2f66c83be4f\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Vector3Int.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using UnityEngine;\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, Vector3Int o, int type_id, bool disposable)\r\n        {\r\n            var val = JSApi.JSB_NewBridgeClassValue(ctx, new_target, sizeof(int) * 3);\r\n            if (!JSApi.JS_IsException(val))\r\n            {\r\n                JSApi.jsb_set_int_3(ctx, val, o.x, o.y, o.z);\r\n            }\r\n            return val;\r\n        }\r\n\r\n        public static bool js_rebind_this(JSContext ctx, JSValue this_obj, ref Vector3Int o)\r\n        {\r\n            return JSApi.jsb_set_int_3(ctx, this_obj, o.x, o.y, o.z) == 1;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, Vector3Int o)\r\n        {\r\n            var proto = FindPrototypeOf<Vector2Int>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(int) * 3);\r\n            JSApi.jsb_set_int_3(ctx, val, o.x, o.y, o.z);\r\n            return val;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Vector3Int o)\r\n        {\r\n            int x, y, z;\r\n            var ret = JSApi.jsb_get_int_3(ctx, val, out x, out y, out z);\r\n            o = new Vector3Int(x, y, z);\r\n            return ret != 0;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Vector3Int? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            int x, y, z;\r\n            var ret = JSApi.jsb_get_int_3(ctx, val, out x, out y, out z);\r\n            o = new Vector3Int(x, y, z);\r\n            return ret != 0;\r\n        }\r\n\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Vector3Int.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 0e543a07a9631bc4891201abe723a6a1\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Vector4.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using UnityEngine;\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, Vector4 o, int type_id, bool disposable)\r\n        {\r\n            var val = JSApi.JSB_NewBridgeClassValue(ctx, new_target, sizeof(float) * 4);\r\n            if (!JSApi.JS_IsException(val))\r\n            {\r\n                JSApi.jsb_set_float_4(ctx, val, o.x, o.y, o.z, o.w);\r\n            }\r\n            return val;\r\n        }\r\n\r\n        public static bool js_rebind_this(JSContext ctx, JSValue this_obj, ref Vector4 o)\r\n        {\r\n            return JSApi.jsb_set_float_4(ctx, this_obj, o.x, o.y, o.z, o.w) == 1;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, Vector4 o)\r\n        {\r\n            var proto = FindPrototypeOf<Vector4>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(float) * 4);\r\n            JSApi.jsb_set_float_4(ctx, val, o.x, o.y, o.z, o.w);\r\n            return val;\r\n        }\r\n\r\n        public static JSValue js_push_structvalue(JSContext ctx, Vector4? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            var proto = FindPrototypeOf<Vector4>(ctx);\r\n            JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(float) * 4);\r\n            var v = (Vector4)o;\r\n            JSApi.jsb_set_float_4(ctx, val, v.x, v.y, v.z, v.w);\r\n            return val;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Vector4 o)\r\n        {\r\n            float x, y, z, w;\r\n            var ret = JSApi.jsb_get_float_4(ctx, val, out x, out y, out z, out w);\r\n            o = new Vector4(x, y, z, w);\r\n            return ret != 0;\r\n        }\r\n\r\n        public static bool js_get_structvalue(JSContext ctx, JSValue val, out Vector4? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            float x, y, z, w;\r\n            var ret = JSApi.jsb_get_float_4(ctx, val, out x, out y, out z, out w);\r\n            o = new Vector4(x, y, z, w);\r\n            return ret != 0;\r\n        }\r\n\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Vector4.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 4871cd66988501f4b9923135cc5e3103\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes.meta",
    "content": "fileFormatVersion: 2\r\nguid: 7dd87eb7cf254554ba702ab0c2aef153\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values.cs",
    "content": "﻿using System;\r\nusing System.Reflection;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public const string KeyForCSharpTypeID = \"__csharp_type_id__\";\r\n        public const string NamespaceOfStaticBinder = \"jsb.gen\";\r\n        public const string ClassNameOfStaticBinder = \"StaticBinder\";\r\n        public const string MethodNameOfStaticBinder = \"BindAll\";\r\n\r\n        static Values()\r\n        {\r\n            init_cast_map();\r\n        }\r\n\r\n        public static bool IsVarargParameter(ParameterInfo[] parameters)\r\n        {\r\n            return parameters.Length > 0 && parameters[parameters.Length - 1].IsDefined(typeof(ParamArrayAttribute), false);\r\n        }\r\n\r\n        /// <summary>\r\n        /// globally find a type with FullName\r\n        /// </summary>\r\n        public static Type FindType(string type_name)\r\n        {\r\n            Type type = null; //Assembly.GetExecutingAssembly().GetType(type_name);\r\n            var assemblies = AppDomain.CurrentDomain.GetAssemblies();\r\n            for (int i = 0, count = assemblies.Length; i < count; i++)\r\n            {\r\n                var assembly = assemblies[i];\r\n                if (!assembly.IsDynamic)\r\n                {\r\n                    type = assembly.GetType(type_name);\r\n                    if (type != null)\r\n                    {\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n            return type;\r\n        }\r\n\r\n        public static bool IsContextualType(Type pType)\r\n        {\r\n            return pType == typeof(JSContext) || pType == typeof(JSRuntime)\r\n                || pType == typeof(ScriptContext) || pType == typeof(ScriptRuntime);\r\n        }\r\n\r\n        /// <summary>\r\n        /// explicitly push as JSArray\r\n        /// </summary>\r\n        public static unsafe JSValue PushArray(JSContext ctx, object o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n\r\n            if (!(o is Array))\r\n            {\r\n                return ctx.ThrowException(new InvalidCastException($\"fail to cast type to Array\"));\r\n            }\r\n\r\n            var arr = (Array)o;\r\n            var length = arr.Length;\r\n            var rval = JSApi.JS_NewArray(ctx);\r\n            try\r\n            {\r\n                for (var i = 0; i < length; i++)\r\n                {\r\n                    var obj = arr.GetValue(i);\r\n                    var elem = Values.js_push_var(ctx, obj);\r\n                    JSApi.JS_SetPropertyUint32(ctx, rval, (uint)i, elem);\r\n                }\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                JSApi.JS_FreeValue(ctx, rval);\r\n                return ctx.ThrowException(exception);\r\n            }\r\n            return rval;\r\n        }\r\n\r\n        public static object GetContext(JSContext ctx, Type type)\r\n        {\r\n            if (type == typeof(JSContext))\r\n            {\r\n                return ctx;\r\n            }\r\n\r\n            if (type == typeof(JSRuntime))\r\n            {\r\n                return JSApi.JS_GetRuntime(ctx);\r\n            }\r\n\r\n            if (type == typeof(ScriptContext))\r\n            {\r\n                return ScriptEngine.GetContext(ctx);\r\n            }\r\n\r\n            if (type == typeof(ScriptRuntime))\r\n            {\r\n                return ScriptEngine.GetRuntime(ctx);\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        public static JSValue FindPrototypeOf<T>(JSContext ctx)\r\n        {\r\n            int type_id;\r\n            var types = ScriptEngine.GetTypeDB(ctx);\r\n            return types.FindChainedPrototypeOf(typeof(T), out type_id);\r\n        }\r\n\r\n        public static JSValue FindPrototypeOf(JSContext ctx, Type type)\r\n        {\r\n            int type_id;\r\n            var types = ScriptEngine.GetTypeDB(ctx);\r\n            return types.FindChainedPrototypeOf(type, out type_id);\r\n        }\r\n\r\n        protected static bool WriteScriptError(JSContext ctx)\r\n        {\r\n            Diagnostics.Logger.Default.Error(ctx.GetExceptionString());\r\n            return false;\r\n        }\r\n\r\n        public static bool GetObjectFallthrough<T>(JSContext ctx, JSValue val, out T o)\r\n        where T : class\r\n        {\r\n            object o_t;\r\n            if (GetObjectFallthrough(ctx, val, out o_t))\r\n            {\r\n                o = o_t as T;\r\n                if (o_t != null && o == null)\r\n                {\r\n                    // throw new InvalidCastException(string.Format(\"{0} type mismatch {1}\", o_t.GetType(), typeof(T)));\r\n                    return false;\r\n                }\r\n                return true;\r\n            }\r\n\r\n            o = default(T);\r\n            return false;\r\n        }\r\n\r\n        public static bool GetObjectFallthrough(JSContext ctx, JSValue val, out object o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n\r\n            if (val.IsString())\r\n            {\r\n                string t;\r\n                var r = js_get_primitive(ctx, val, out t);\r\n                o = t;\r\n                return r;\r\n            }\r\n\r\n            if (val.IsBoolean())\r\n            {\r\n                bool t;\r\n                var r = js_get_primitive(ctx, val, out t);\r\n                o = t;\r\n                return r;\r\n            }\r\n\r\n            if (val.IsNumber())\r\n            {\r\n                double t;\r\n                var r = js_get_primitive(ctx, val, out t);\r\n                o = t;\r\n                return r;\r\n            }\r\n\r\n            return js_get_cached_object(ctx, val, out o);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: f51ee4719ca24aaab51b7a850c5da88e\r\ntimeCreated: 1591424204"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_delegate.cs",
    "content": "using System;\r\nusing System.Runtime.CompilerServices;\r\nusing QuickJS.Native;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    /// <summary>\r\n    /// raw methods for handling delegates/events\r\n    /// </summary>\r\n    public partial class Values\r\n    {\r\n        public const int EVT_OP_NONE = 0;\r\n        public const int EVT_OP_ADD = 1;\r\n        public const int EVT_OP_REMOVE = 2;\r\n        public const int EVT_OP_SET = 3; // only for delegate\r\n        public const int EVT_OP_GET = 4; // only for delegate\r\n\r\n        public static int js_parse_event_op(JSContext ctx, JSValue val)\r\n        {\r\n            var str = JSApi.GetString(ctx, val);\r\n            switch (str)\r\n            {\r\n                case \"add\": case \"on\": return EVT_OP_ADD;\r\n                case \"remove\": case \"off\": return EVT_OP_REMOVE;\r\n                case \"set\": return EVT_OP_SET;\r\n                case \"get\": return EVT_OP_GET;\r\n                default: return EVT_OP_NONE;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// push the corresponding js value if o is a ScriptDelegate, \r\n        /// otherwise push it as a C# Object directly.\r\n        /// </summary>\r\n        public static JSValue js_push_delegate(JSContext ctx, Delegate o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n\r\n            var dDelegate = o.Target as ScriptDelegate;\r\n            if (dDelegate != null)\r\n            {\r\n                return JSApi.JS_DupValue(ctx, dDelegate);\r\n            }\r\n\r\n            // fallback\r\n            return js_push_object(ctx, (object)o);\r\n        }\r\n\r\n        public static bool js_get_delegate<T>(JSContext ctx, JSValue val, out T[] o)\r\n        where T : class\r\n        {\r\n            if (JSApi.JS_IsArray(ctx, val) == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    throw new Exception(ctx.GetExceptionString());\r\n                }\r\n                uint length;\r\n                JSApi.JSB_ToUint32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new T[length];\r\n                for (uint i = 0; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    T e;\r\n                    js_get_delegate(ctx, eVal, out e);\r\n                    o[i] = e;\r\n                    JSApi.JS_FreeValue(ctx, eVal);\r\n                }\r\n                return true;\r\n            }\r\n            js_get_classvalue<T[]>(ctx, val, out o);\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_delegate<T>(JSContext ctx, JSValue val, out T o)\r\n        where T : class\r\n        {\r\n            Delegate d;\r\n            var ret = js_get_delegate(ctx, val, typeof(T), out d);\r\n            o = ret ? d as T : null;\r\n            return ret;\r\n        }\r\n\r\n        /// <summary>\r\n        /// 从 JSValue 反推 Delegate. 不约束委托类型 (因此也不会自动创建委托, 不存在已有映射时, 将失败)\r\n        /// </summary>\r\n        public static bool js_get_delegate_unsafe(JSContext ctx, JSValue val, out Delegate o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n\r\n            if (JSApi.JS_IsFunction(ctx, val) == 1)\r\n            {\r\n                ScriptDelegate fn;\r\n                var cache = ScriptEngine.GetObjectCache(ctx);\r\n\r\n                if (cache.TryGetDelegate(val, out fn))\r\n                {\r\n                    o = fn.Any();\r\n                    return o != null;\r\n                }\r\n                else\r\n                {\r\n                    o = null;\r\n                    return false;\r\n                }\r\n            }\r\n\r\n            // 检查 val 是否是一个委托对象 wrapped object\r\n            if (JSApi.JS_IsObject(val))\r\n            {\r\n                return js_get_classvalue<Delegate>(ctx, val, out o);\r\n            }\r\n\r\n            o = null;\r\n            return false;\r\n        }\r\n\r\n        /// <summary>\r\n        /// 从 JSValue 反推 Delegate, JSValue 可能是一个 js function, cs delegate (js object) <br/>\r\n        /// 注意: 会自动创建 ScriptDelegate 映射\r\n        /// </summary>\r\n        public static bool js_get_delegate(JSContext ctx, JSValue val, Type delegateType, out Delegate o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n\r\n            // 检查 val 是否是一个委托对象 wrapped object\r\n            if (JSApi.JS_IsObject(val))\r\n            {\r\n                if (js_get_classvalue<Delegate>(ctx, val, out o))\r\n                {\r\n                    return o == null || o.GetType() == delegateType;\r\n                }\r\n                if (JSApi.JS_IsFunction(ctx, val) == 1)\r\n                {\r\n                    ScriptDelegate fn;\r\n                    var cache = ScriptEngine.GetObjectCache(ctx);\r\n\r\n                    if (cache.TryGetDelegate(val, out fn))\r\n                    {\r\n                        // 已经存在映射关系, 找出符合预期类型的委托\r\n                        o = fn.Match(delegateType);\r\n                        if (o == null)\r\n                        {\r\n                            // 存在 JSValue => Delegate 的多重映射\r\n                            var types = ScriptEngine.GetTypeDB(ctx);\r\n                            var func = types.GetDelegateFunc(delegateType);\r\n                            o = Delegate.CreateDelegate(delegateType, fn, func, false);\r\n                            if (o != null)\r\n                            {\r\n                                fn.Add(o);\r\n                            }\r\n                        }\r\n                        return o != null;\r\n                    }\r\n                    else\r\n                    {\r\n                        // 建立新的映射关系\r\n                        var context = ScriptEngine.GetContext(ctx);\r\n                        var types = context.GetTypeDB();\r\n                        var func = types.GetDelegateFunc(delegateType);\r\n\r\n                        if (func == null)\r\n                        {\r\n                            o = null;\r\n                            return false;\r\n                        }\r\n\r\n                        fn = new ScriptDelegate(context, val);\r\n                        o = Delegate.CreateDelegate(delegateType, fn, func, false);\r\n                        if (o != null)\r\n                        {\r\n                            fn.Add(o);\r\n                        }\r\n\r\n                        return o != null;\r\n                    }\r\n                }\r\n            }\r\n\r\n            o = null;\r\n            return false;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_delegate.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 547c9de1eb82f614ebbc4618f1c9e797\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_get.cs",
    "content": "using System;\r\nusing System.Runtime.InteropServices;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using Native;\r\n    using QuickJS.Utils;\r\n\r\n    // 处理常规值, class, struct\r\n    public partial class Values\r\n    {\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out JSValue o)\r\n        {\r\n            o = val;\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out IntPtr o)\r\n        {\r\n            object o_t;\r\n            var ret = js_get_cached_object(ctx, val, out o_t);\r\n            o = (IntPtr)o_t;\r\n            return ret;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out IntPtr? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            object o_t;\r\n            var ret = js_get_cached_object(ctx, val, out o_t);\r\n            o = (IntPtr)o_t;\r\n            return ret;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out IntPtr[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new IntPtr[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    IntPtr e;\r\n                    if (js_get_primitive(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            return js_get_classvalue<IntPtr[]>(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out bool o)\r\n        {\r\n#if JSB_STRICT\r\n            if (!val.IsBoolean())\r\n            {\r\n                o = false;\r\n                return false;\r\n            }\r\n#endif\r\n            var r = JSApi.JS_ToBool(ctx, val);\r\n            o = r != 0;\r\n            return r >= 0;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out bool? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n#if JSB_STRICT\r\n            if (!val.IsBoolean())\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n#endif\r\n            var r = JSApi.JS_ToBool(ctx, val);\r\n            o = r != 0;\r\n            return r >= 0;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out bool[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new bool[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    bool e;\r\n                    if (js_get_primitive(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            return js_get_classvalue<bool[]>(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out sbyte o)\r\n        {\r\n            int pres;\r\n            JSApi.JS_ToInt32(ctx, out pres, val);\r\n            o = (sbyte)pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out sbyte? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            int pres;\r\n            JSApi.JS_ToInt32(ctx, out pres, val);\r\n            o = (sbyte)pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out sbyte[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new sbyte[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    sbyte e;\r\n                    if (js_get_primitive(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            return js_get_classvalue<sbyte[]>(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out byte o)\r\n        {\r\n            int pres;\r\n            JSApi.JS_ToInt32(ctx, out pres, val);\r\n            o = (byte)pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out byte? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            int pres;\r\n            JSApi.JS_ToInt32(ctx, out pres, val);\r\n            o = (byte)pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out byte[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new byte[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    byte e;\r\n                    if (js_get_primitive(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n\r\n            // check ArrayBuffer \r\n            size_t psize;\r\n            var pbuf = JSApi.JS_GetArrayBuffer(ctx, out psize, val);\r\n\r\n            if (pbuf != IntPtr.Zero)\r\n            {\r\n                o = new byte[psize];\r\n                Marshal.Copy(pbuf, o, 0, psize);\r\n                return true;\r\n            }\r\n\r\n            // check TypedArray\r\n            var asBuffer = JSApi.JS_GetProperty(ctx, val, ScriptEngine.GetContext(ctx).GetAtom(\"buffer\"));\r\n            if (asBuffer.IsObject())\r\n            {\r\n                pbuf = JSApi.JS_GetArrayBuffer(ctx, out psize, asBuffer);\r\n                JSApi.JS_FreeValue(ctx, asBuffer);\r\n\r\n                if (pbuf != IntPtr.Zero)\r\n                {\r\n                    o = new byte[psize];\r\n                    Marshal.Copy(pbuf, o, 0, psize);\r\n                    return true;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                JSApi.JS_FreeValue(ctx, asBuffer);\r\n            }\r\n\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            return js_get_classvalue<byte[]>(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out char o)\r\n        {\r\n            int pres;\r\n            JSApi.JS_ToInt32(ctx, out pres, val);\r\n            o = (char)pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out char? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            int pres;\r\n            JSApi.JS_ToInt32(ctx, out pres, val);\r\n            o = (char)pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out char[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new char[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    char e;\r\n                    if (js_get_primitive(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            return js_get_classvalue<char[]>(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out string o)\r\n        {\r\n            //TODO: make the stringcache behaviour configurable?\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            var cache = context.GetStringCache();\r\n            if (cache.TryGetValue(val, out o))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            o = JSApi.GetString(ctx, val); // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out string[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new string[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    string e;\r\n                    if (js_get_primitive(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            return js_get_classvalue<string[]>(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out short o)\r\n        {\r\n            int pres;\r\n            JSApi.JS_ToInt32(ctx, out pres, val);\r\n            o = (short)pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out short? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            int pres;\r\n            JSApi.JS_ToInt32(ctx, out pres, val);\r\n            o = (short)pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out short[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new short[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    short e;\r\n                    if (js_get_primitive(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            return js_get_classvalue<short[]>(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out ushort o)\r\n        {\r\n            int pres;\r\n            JSApi.JS_ToInt32(ctx, out pres, val);\r\n            o = (ushort)pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out ushort? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            int pres;\r\n            JSApi.JS_ToInt32(ctx, out pres, val);\r\n            o = (ushort)pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out ushort[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new ushort[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    ushort e;\r\n                    if (js_get_primitive(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            return js_get_classvalue<ushort[]>(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out int o)\r\n        {\r\n            int pres;\r\n            JSApi.JS_ToInt32(ctx, out pres, val);\r\n            o = pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out int? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            int pres;\r\n            JSApi.JS_ToInt32(ctx, out pres, val);\r\n            o = pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out int[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new int[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    int e;\r\n                    if (js_get_primitive(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            return js_get_classvalue<int[]>(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out uint o)\r\n        {\r\n            uint pres;\r\n            JSApi.JSB_ToUint32(ctx, out pres, val);\r\n            o = pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out uint? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            uint pres;\r\n            JSApi.JSB_ToUint32(ctx, out pres, val);\r\n            o = pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out uint[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new uint[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    uint e;\r\n                    if (js_get_primitive(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            return js_get_classvalue<uint[]>(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out long o)\r\n        {\r\n            long pres;\r\n            JSApi.JS_ToInt64(ctx, out pres, val);\r\n            o = pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out long? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            long pres;\r\n            JSApi.JS_ToInt64(ctx, out pres, val);\r\n            o = pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out long[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new long[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    long e;\r\n                    if (js_get_primitive(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            return js_get_classvalue<long[]>(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out ulong o)\r\n        {\r\n            ulong pres;\r\n            JSApi.JS_ToIndex(ctx, out pres, val);\r\n            o = pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out ulong? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            ulong pres;\r\n            JSApi.JS_ToIndex(ctx, out pres, val);\r\n            o = pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out ulong[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new ulong[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    ulong e;\r\n                    if (js_get_primitive(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            return js_get_classvalue<ulong[]>(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out float o)\r\n        {\r\n#if JSB_STRICT\r\n            if (!val.IsNumber())\r\n            {\r\n                o = 0f;\r\n                return false;\r\n            }\r\n#endif\r\n            double pres;\r\n            var res = JSApi.JS_ToFloat64(ctx, out pres, val);\r\n            o = (float)pres; // no check\r\n            return res == 0;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out float? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n#if JSB_STRICT\r\n            if (!val.IsNumber())\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n#endif\r\n            double pres;\r\n            var res = JSApi.JS_ToFloat64(ctx, out pres, val);\r\n            o = (float)pres; // no check\r\n            return res == 0;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out float[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new float[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    float e;\r\n                    if (js_get_primitive(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            return js_get_classvalue<float[]>(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out double o)\r\n        {\r\n            double pres;\r\n            JSApi.JS_ToFloat64(ctx, out pres, val);\r\n            o = pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out double? o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            double pres;\r\n            JSApi.JS_ToFloat64(ctx, out pres, val);\r\n            o = pres; // no check\r\n            return true;\r\n        }\r\n\r\n        public static bool js_get_primitive(JSContext ctx, JSValue val, out double[] o)\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new double[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    double e;\r\n                    if (js_get_primitive(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            return js_get_classvalue<double[]>(ctx, val, out o);\r\n        }\r\n\r\n        // fallthrough\r\n        public static bool js_get_structvalue<T>(JSContext ctx, JSValue val, out T o)\r\n        where T : struct\r\n        {\r\n            object o_t;\r\n            var ret = js_get_cached_object(ctx, val, out o_t);\r\n            o = (T)o_t;\r\n            return ret;\r\n        }\r\n\r\n        public static bool js_get_structvalue<T>(JSContext ctx, JSValue val, out T? o)\r\n        where T : struct\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n            object o_t;\r\n            var ret = js_get_cached_object(ctx, val, out o_t);\r\n            o = (T)o_t;\r\n            return ret;\r\n        }\r\n\r\n        public static bool js_get_structvalue<T>(JSContext ctx, JSValue val, out T[] o)\r\n        where T : struct\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new T[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    T e;\r\n                    if (js_get_structvalue(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            return js_get_classvalue<T[]>(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_structvalue<T>(JSContext ctx, JSValue val, out T?[] o)\r\n        where T : struct\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new T?[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    T? e;\r\n                    if (js_get_structvalue(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n            return js_get_classvalue<T?[]>(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_classvalue(JSContext ctx, JSValue jsValue, out Type o)\r\n        {\r\n            if (JSApi.JS_IsString(jsValue))\r\n            {\r\n                var name = JSApi.GetString(ctx, jsValue);\r\n                o = TypeDB.GetType(name);\r\n                return o != null;\r\n            }\r\n            else\r\n            {\r\n                var context = ScriptEngine.GetContext(ctx);\r\n                var type_id = JSApi.JSB_GetBridgeType(ctx, jsValue, context.GetAtom(Values.KeyForCSharpTypeID));\r\n                if (type_id >= 0)\r\n                {\r\n                    var types = context.GetTypeDB();\r\n                    o = types.GetType(type_id);\r\n                    // Debug.Log($\"get type from exported registry {o}:{typeid}\");\r\n                    return o != null;\r\n                }\r\n                else\r\n                {\r\n                    var header = JSApi.jsb_get_payload_header(ctx, jsValue);\r\n                    switch (header.type_id)\r\n                    {\r\n                        case BridgeObjectType.TypeRef:\r\n                            {\r\n                                var types = context.GetTypeDB();\r\n                                o = types.GetType(header.value);\r\n                                // Debug.Log($\"get type from exported registry {o}:{typeid}\");\r\n                                return o != null;\r\n                            }\r\n                        case BridgeObjectType.ObjectRef:\r\n                            {\r\n                                var cache = context.GetObjectCache();\r\n                                object obj;\r\n                                cache.TryGetObject(header.value, out obj);\r\n                                o = obj.GetType();\r\n                                return o != null;\r\n                            }\r\n                    }\r\n                }\r\n            }\r\n\r\n            o = null;\r\n            return false;\r\n        }\r\n\r\n        public static bool js_get_classvalue(JSContext ctx, JSValue val, out Delegate o)\r\n        {\r\n            return js_get_delegate_unsafe(ctx, val, out o);\r\n        }\r\n\r\n        /// <summary>\r\n        /// be equivalent to js_get_cached_object, but will cast as expecting type T.\r\n        /// </summary>\r\n        public static bool js_get_classvalue<T>(JSContext ctx, JSValue val, out T o)\r\n        where T : class\r\n        {\r\n            object o_t;\r\n            if (js_get_cached_object(ctx, val, out o_t))\r\n            {\r\n                o = o_t as T;\r\n                if (o_t != null && o == null)\r\n                {\r\n                    // throw new InvalidCastException(string.Format(\"{0} type mismatch {1}\", o_t.GetType(), typeof(T)));\r\n                    return false;\r\n                }\r\n                return true;\r\n            }\r\n\r\n            o = default(T);\r\n            return false;\r\n        }\r\n\r\n        /// <summary>\r\n        /// It's not allowed to dereference a JSValue back into ScriptPromise.\r\n        /// </summary>\r\n        public static bool js_get_classvalue(JSContext ctx, JSValue val, out ScriptPromise o)\r\n        {\r\n            o = null;\r\n            return false;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value wrapper instance for the given JSValue.\r\n        /// NOTE: It'll return an existing instance if it's in the map of ScriptValue's cache.\r\n        /// </summary>\r\n        public static bool js_get_classvalue(JSContext ctx, JSValue val, out ScriptValue o)\r\n        {\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            var cache = context.GetObjectCache();\r\n\r\n            if (cache.TryGetScriptValue(val, out o))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            o = new ScriptValue(context, val);\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a function wrapper instance for the given JSValue.\r\n        /// NOTE: It'll always return a new instance.\r\n        /// </summary>\r\n        public static bool js_get_classvalue(JSContext ctx, JSValue val, out ScriptFunction o)\r\n        {\r\n            if (JSApi.JS_IsFunction(ctx, val) != 0)\r\n            {\r\n                var context = ScriptEngine.GetContext(ctx);\r\n                if (context != null)\r\n                {\r\n                    o = new ScriptFunction(context, val);\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            o = null;\r\n            return false;\r\n        }\r\n\r\n        public static bool js_get_classvalue(JSContext ctx, JSValue val, out QuickJS.IO.ByteBuffer o)\r\n        {\r\n            object obj;\r\n            if (js_get_cached_object(ctx, val, out obj))\r\n            {\r\n                if (obj is QuickJS.IO.ByteBuffer)\r\n                {\r\n                    o = (QuickJS.IO.ByteBuffer)obj;\r\n                    return true;\r\n                }\r\n            }\r\n            size_t psize;\r\n            var pointer = JSApi.JS_GetArrayBuffer(ctx, out psize, val);\r\n            if (pointer != IntPtr.Zero)\r\n            {\r\n                var runtime = ScriptEngine.GetRuntime(ctx);\r\n                var allocator = runtime.GetByteBufferAllocator();\r\n                if (allocator != null)\r\n                {\r\n                    var length = (int)psize;\r\n\r\n                    o = allocator.Alloc(length);\r\n                    runtime.AutoRelease(o);\r\n                    o.WriteBytes(pointer, length);\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            var asBuffer = JSApi.JS_GetProperty(ctx, val, ScriptEngine.GetContext(ctx).GetAtom(\"buffer\"));\r\n            if (asBuffer.IsObject())\r\n            {\r\n                pointer = JSApi.JS_GetArrayBuffer(ctx, out psize, asBuffer);\r\n                JSApi.JS_FreeValue(ctx, asBuffer);\r\n\r\n                if (pointer != IntPtr.Zero)\r\n                {\r\n                    var runtime = ScriptEngine.GetRuntime(ctx);\r\n                    var allocator = runtime.GetByteBufferAllocator();\r\n                    if (allocator != null)\r\n                    {\r\n                        var length = (int)psize;\r\n\r\n                        o = allocator.Alloc(length);\r\n                        runtime.AutoRelease(o);\r\n                        o.WriteBytes(pointer, length);\r\n                        return true;\r\n                    }\r\n                }\r\n            }\r\n            else\r\n            {\r\n                JSApi.JS_FreeValue(ctx, asBuffer);\r\n            }\r\n\r\n            o = null;\r\n            return false;\r\n        }\r\n\r\n        public static bool js_set_cached_object_disposable(JSContext ctx, JSValue val, bool disposable)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                return true;\r\n            }\r\n\r\n            var header = JSApi.jsb_get_payload_header(ctx, val);\r\n            switch (header.type_id)\r\n            {\r\n                case BridgeObjectType.ObjectRef:\r\n                    return ScriptEngine.GetObjectCache(ctx).SetObjectDisposable(header.value, disposable);\r\n                case BridgeObjectType.TypeRef:\r\n                case BridgeObjectType.ValueType:\r\n                    return false;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public static bool js_get_cached_object(JSContext ctx, JSValue val, out object o)\r\n        {\r\n            if (val.IsNullish())\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            var header = context.GetPayloadHeader(val);\r\n            \r\n            switch (header.type_id)\r\n            {\r\n                case BridgeObjectType.ObjectRef:\r\n                    return ScriptEngine.GetObjectCache(ctx).TryGetObject(header.value, out o);\r\n                case BridgeObjectType.TypeRef:\r\n                    o = ScriptEngine.GetTypeDB(ctx).GetType(header.value);\r\n                    return o != null;\r\n                case BridgeObjectType.ValueType:\r\n                    o = null;\r\n                    return false;\r\n            }\r\n\r\n            o = null;\r\n            return false;\r\n        }\r\n\r\n        /// <summary>\r\n        /// try to translate a JSArray to a C# Array, otherwise fallback to break down a wrapped object\r\n        /// </summary>\r\n        public static bool js_get_classvalue<T>(JSContext ctx, JSValue val, out T[] o)\r\n        where T : class\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new T[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    T e;\r\n                    if (js_get_classvalue(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n\r\n            // fallback to get_object\r\n            return js_get_classvalue<T[]>(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_enumvalue<T>(JSContext ctx, JSValue val, out T o)\r\n        where T : Enum\r\n        {\r\n            int v;\r\n            var ret = js_get_primitive(ctx, val, out v);\r\n            o = (T)Enum.ToObject(typeof(T), v);\r\n            return ret;\r\n        }\r\n\r\n        public static bool js_get_enumvalue(JSContext ctx, JSValue val, Type type, out object o)\r\n        {\r\n            int v;\r\n            var ret = js_get_primitive(ctx, val, out v);\r\n            o = Enum.ToObject(type, v);\r\n            return ret;\r\n        }\r\n\r\n        public static bool js_get_enumvalue<T>(JSContext ctx, JSValue val, out T[] o)\r\n        where T : Enum\r\n        {\r\n            var isArray = JSApi.JS_IsArray(ctx, val);\r\n            if (isArray == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                o = new T[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    T e;\r\n                    if (js_get_enumvalue(ctx, eVal, out e))\r\n                    {\r\n                        o[i] = e;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n\r\n            if (isArray == -1)\r\n            {\r\n                o = null;\r\n                return false;\r\n            }\r\n\r\n            return js_get_classvalue<T[]>(ctx, val, out o);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_get.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 69aa4c110fe255347b0ab9e9e1f00797\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_get_var.cs",
    "content": "using System;\r\nusing System.Reflection;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using Native;\r\n\r\n    // collect all built-in js-cs conversion helper methods\r\n    public partial class Values\r\n    {\r\n        // cast js value to csharp value \r\n        // TypeCastGet ~ get/rebind: bool js_get_*(JSContext ctx, JSValue val, out T o);\r\n        public static Dictionary<Type, MethodInfo> _JSCastMap = new Dictionary<Type, MethodInfo>();\r\n\r\n        // replace the js value reference with another csharp value (for struct)\r\n        public static Dictionary<Type, MethodInfo> _JSRebindMap = new Dictionary<Type, MethodInfo>();\r\n\r\n        // cast csharp value to js value\r\n        // TypeCastPush ~ push: JSValue js_push_primitive(JSContext ctx, T o)\r\n        public static Dictionary<Type, MethodInfo> _CSCastMap = new Dictionary<Type, MethodInfo>();\r\n\r\n        // construct a js value with given csharp value\r\n        // TypeCastNew ~ new: JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, T o, int type_id, bool disposable)\r\n        public static Dictionary<Type, MethodInfo> _JSNewMap = new Dictionary<Type, MethodInfo>();\r\n\r\n        public delegate bool TypeCastGet<T>(JSContext ctx, JSValue val, out T o);\r\n\r\n        public delegate bool TypeCastRebind<T>(JSContext ctx, JSValue new_target, ref T o);\r\n\r\n        public delegate JSValue TypeCastPush<T>(JSContext ctx, T o);\r\n\r\n        public delegate JSValue TypeCastNew<T>(JSContext ctx, JSValue new_target, T o, int type_id, bool disposable);\r\n\r\n        private static void init_cast_map()\r\n        {\r\n            var methods = typeof(Values).GetMethods();\r\n            for (int i = 0, len = methods.Length; i < len; ++i)\r\n            {\r\n                register_type_caster(methods[i]);\r\n            }\r\n        }\r\n\r\n        public static bool register_type_caster<T>(TypeCastGet<T> fn)\r\n        {\r\n            return register_type_caster(fn.Method);\r\n        }\r\n\r\n        public static bool register_type_caster<T>(TypeCastRebind<T> fn)\r\n        {\r\n            return register_type_caster(fn.Method);\r\n        }\r\n\r\n        public static bool register_type_caster<T>(TypeCastPush<T> fn)\r\n        {\r\n            return register_type_caster(fn.Method);\r\n        }\r\n\r\n        public static bool register_type_caster<T>(TypeCastNew<T> fn)\r\n        {\r\n            return register_type_caster(fn.Method);\r\n        }\r\n\r\n        public static bool register_type_caster(MethodInfo method)\r\n        {\r\n            if (!method.IsGenericMethodDefinition && method.IsStatic && method.IsPublic)\r\n            {\r\n                var parameters = method.GetParameters();\r\n\r\n                if (parameters.Length < 2 || parameters[0].ParameterType != typeof(JSContext))\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                if (parameters.Length == 5)\r\n                {\r\n                    if (parameters[1].ParameterType == typeof(JSValue))\r\n                    {\r\n                        // JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, T o, int type_id, bool disposable)\r\n                        if (method.Name == \"NewBridgeClassObject\")\r\n                        {\r\n                            var type = parameters[2].ParameterType;\r\n                            _JSNewMap[type] = method;\r\n                            return true;\r\n                        }\r\n                    }\r\n                }\r\n                else if (parameters.Length == 3)\r\n                {\r\n                    // should only collect the method name with the expected signature, \r\n                    // bool js_get_*(JSContext ctx, JSValue val, out T o);\r\n                    if (parameters[2].ParameterType.IsByRef && parameters[1].ParameterType == typeof(JSValue))\r\n                    {\r\n                        var type = parameters[2].ParameterType.GetElementType();\r\n                        switch (method.Name)\r\n                        {\r\n                            case \"js_rebind_this\":\r\n                                _JSRebindMap[type] = method;\r\n                                return true;\r\n                            case \"js_get_primitive\":\r\n                            case \"js_get_structvalue\":\r\n                            case \"js_get_classvalue\":\r\n                                _JSCastMap[type] = method;\r\n                                return true;\r\n                        }\r\n                    }\r\n                }\r\n                else if (parameters.Length == 2)\r\n                {\r\n                    // JSValue js_push_primitive(JSContext ctx, T o)\r\n                    if (method.Name.StartsWith(\"js_push_\"))\r\n                    {\r\n                        var type = parameters[1].ParameterType;\r\n\r\n                        _CSCastMap[type] = method;\r\n                        return true;\r\n                    }\r\n                }\r\n            }\r\n            return false;\r\n        }\r\n\r\n        public static bool js_rebind_var(JSContext ctx, JSValue this_obj, Type type, object o)\r\n        {\r\n            MethodInfo method;\r\n            if (_JSRebindMap.TryGetValue(type, out method))\r\n            {\r\n                var parameters = new object[3] { ctx, this_obj, o };\r\n                return (bool)method.Invoke(o, parameters);\r\n            }\r\n            return false;\r\n        }\r\n\r\n        /// <summary>\r\n        /// convert csharp object `o` to jsvalue with o.GetType()\r\n        /// NOTE: auto conversion to JS Array is deliberately ignored to avoid unnecessary gc alloc. \r\n        ///       jsb.ToArray() is available to use to convert a C# Array to JS Array. \r\n        /// Type conversions will be processed by _CSCastMap. \r\n        /// ScriptValue is processed in Values_push_class.cs => public static JSValue js_push_classvalue(JSContext ctx, ScriptValue o)\r\n        /// JSValue is processed in Values_push_primitive.cs => public static JSValue js_push_primitive(JSContext ctx, JSValue o)\r\n        /// </summary>\r\n        public static JSValue js_push_var(JSContext ctx, object o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n\r\n            var type = o.GetType();\r\n\r\n            if (type.IsEnum)\r\n            {\r\n                return js_push_primitive(ctx, Convert.ToInt32(o));\r\n            }\r\n\r\n            MethodInfo cast;\r\n            do\r\n            {\r\n                if (_CSCastMap.TryGetValue(type, out cast))\r\n                {\r\n                    var parameters = new object[2] { ctx, o };\r\n                    var rval = (JSValue)cast.Invoke(null, parameters);\r\n                    return rval;\r\n                }\r\n                type = type.BaseType;\r\n            } while (type != null);\r\n\r\n            //NOTE: 2. fallthrough, push as object\r\n            return js_push_classvalue(ctx, o);\r\n        }\r\n\r\n        public static JSValue js_new_var(JSContext ctx, JSValue new_target, Type type, object o, int type_id, bool disposable)\r\n        {\r\n            // most of NewBridgeClassObject are overrided for struct-type, no need to traverse their BaseType\r\n            // all class-type can be directly tackled as 'object'\r\n            MethodInfo cast;\r\n            if (_JSNewMap.TryGetValue(type, out cast))\r\n            {\r\n                var parameters = new object[5] { ctx, new_target, o, type_id, disposable };\r\n                var rval = (JSValue)cast.Invoke(null, parameters);\r\n                return rval;\r\n            }\r\n\r\n            return NewBridgeClassObject(ctx, new_target, o, type_id, disposable);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts js value to C# object without giving C# type information.\r\n        /// It will try to convert by the type of the js value.\r\n        /// </summary>\r\n        public static bool js_get_var(JSContext ctx, JSValue val, out object o)\r\n        {\r\n            return GetObjectFallthrough(ctx, val, out o);\r\n        }\r\n\r\n        public static bool js_get_var(JSContext ctx, JSValue val, out object[] o)\r\n        {\r\n            if (JSApi.JS_IsArray(ctx, val) == 1)\r\n            {\r\n                var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                if (JSApi.JS_IsException(lengthVal))\r\n                {\r\n                    o = null;\r\n                    return WriteScriptError(ctx);\r\n                }\r\n\r\n                int length;\r\n                JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                JSApi.JS_FreeValue(ctx, lengthVal);\r\n                var array = new object[length];\r\n                for (var i = 0U; i < length; i++)\r\n                {\r\n                    var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                    object e;\r\n                    if (js_get_var(ctx, eVal, out e))\r\n                    {\r\n                        array.SetValue(e, i);\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                    }\r\n                    else\r\n                    {\r\n                        o = null;\r\n                        JSApi.JS_FreeValue(ctx, eVal);\r\n                        return false;\r\n                    }\r\n                }\r\n                o = array;\r\n                return true;\r\n            }\r\n\r\n            return GetObjectFallthrough(ctx, val, out o);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts a js value to C# object with the given type.\r\n        /// NOTE: js_get_primitive/structvalue/classvalue() are perfered to use when object type is known at compile-time.\r\n        /// This method is primarily used when compile-time inference isn't possible.\r\n        /// </summary>\r\n        /// <param name=\"val\">Source js value to convert</param>\r\n        /// <param name=\"type\">Expected type of object o</param>\r\n        /// <param name=\"o\">target object converted from js value</param>\r\n        public static bool js_get_var(JSContext ctx, JSValue val, Type type, out object o)\r\n        {\r\n            if (val.IsNullish() || type == typeof(void))\r\n            {\r\n                o = null;\r\n                return true;\r\n            }\r\n\r\n            if (type.BaseType == typeof(MulticastDelegate))\r\n            {\r\n                Delegate d;\r\n                var rs = js_get_delegate(ctx, val, type, out d);\r\n                o = d;\r\n                return rs;\r\n            }\r\n\r\n            var lookupType = type;\r\n            MethodInfo cast;\r\n            while (lookupType != null && lookupType != typeof(object))\r\n            {\r\n                if (_JSCastMap.TryGetValue(lookupType, out cast))\r\n                {\r\n                    var parameters = new object[3] { ctx, val, null };\r\n                    var rval = (bool)cast.Invoke(null, parameters);\r\n                    o = parameters[2];\r\n                    return rval;\r\n                }\r\n                lookupType = lookupType.BaseType;\r\n            }\r\n\r\n            if (type.IsArray)\r\n            {\r\n                if (type.GetArrayRank() == 1 && JSApi.JS_IsArray(ctx, val) == 1)\r\n                {\r\n                    var lengthVal = JSApi.JS_GetProperty(ctx, val, JSApi.JS_ATOM_length);\r\n                    if (JSApi.JS_IsException(lengthVal))\r\n                    {\r\n                        o = null;\r\n                        return WriteScriptError(ctx);\r\n                    }\r\n\r\n                    var elementType = type.GetElementType();\r\n                    int length;\r\n                    JSApi.JS_ToInt32(ctx, out length, lengthVal);\r\n                    JSApi.JS_FreeValue(ctx, lengthVal);\r\n                    var array = Array.CreateInstance(elementType, length);\r\n                    for (var i = 0U; i < length; i++)\r\n                    {\r\n                        var eVal = JSApi.JS_GetPropertyUint32(ctx, val, i);\r\n                        object e;\r\n                        if (js_get_var(ctx, eVal, elementType, out e))\r\n                        {\r\n                            array.SetValue(e, i);\r\n                            JSApi.JS_FreeValue(ctx, eVal);\r\n                        }\r\n                        else\r\n                        {\r\n                            o = null;\r\n                            JSApi.JS_FreeValue(ctx, eVal);\r\n                            return false;\r\n                        }\r\n                    }\r\n                    o = array;\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            if (type.IsEnum)\r\n            {\r\n                return js_get_enumvalue(ctx, val, type, out o);\r\n            }\r\n\r\n            if (val.IsString())\r\n            {\r\n                if (type.IsAssignableFrom(typeof(string)))\r\n                {\r\n                    string t;\r\n                    var r = js_get_primitive(ctx, val, out t);\r\n                    o = t;\r\n                    return r;\r\n                }\r\n                o = null;\r\n                return false;\r\n            }\r\n\r\n            if (val.IsBoolean())\r\n            {\r\n                if (type.IsAssignableFrom(typeof(bool)))\r\n                {\r\n                    bool t;\r\n                    var r = js_get_primitive(ctx, val, out t);\r\n                    o = t;\r\n                    return r;\r\n                }\r\n                o = null;\r\n                return false;\r\n            }\r\n\r\n            if (val.IsNumber())\r\n            {\r\n                if (type.IsAssignableFrom(typeof(double)))\r\n                {\r\n                    double t;\r\n                    var r = js_get_primitive(ctx, val, out t);\r\n                    o = t;\r\n                    return r;\r\n                }\r\n                o = null;\r\n                return false;\r\n            }\r\n\r\n            if (js_get_cached_object(ctx, val, out o))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            if (type == typeof(object))\r\n            {\r\n                var targetType = typeof(object);\r\n\r\n                // Detect value type and convert to it\r\n                var header = JSApi.jsb_get_payload_header(ctx, val);\r\n\r\n                if (header.type_id != BridgeObjectType.None)\r\n                {\r\n                    var context = ScriptEngine.GetContext(ctx);\r\n                    var type_id = JSApi.JSB_GetBridgeType(ctx, val, context.GetAtom(Values.KeyForCSharpTypeID));\r\n                    if (type_id > 0)\r\n                    {\r\n                        var types = context.GetTypeDB();\r\n                        var t = types.GetType(type_id);\r\n\r\n                        if (t != null)\r\n                        {\r\n                            targetType = t;\r\n                        }\r\n                    }\r\n                }\r\n\r\n                if (_JSCastMap.TryGetValue(targetType, out cast))\r\n                {\r\n                    var parameters = new object[3] { ctx, val, null };\r\n                    var rval = (bool)cast.Invoke(null, parameters);\r\n                    o = parameters[2];\r\n                    return rval;\r\n                }\r\n            }\r\n\r\n            o = null;\r\n            return false;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_get_var.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 5d66930a5ac19c845816c1d65e85574e\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_hotfix.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Runtime.CompilerServices;\n\nnamespace QuickJS.Binding\n{\n    using Native;\n\n    // [experimental][NOT_IMPLEMENTED] caster for hotfix\n    public partial class Values\n    {\n        public static JSValue hotfix_push_classvalue(JSContext ctx, Type type)\n        {\n            if (type == null)\n            {\n                return JSApi.JS_NULL;\n            }\n\n            var runtime = ScriptEngine.GetRuntime(ctx);\n            var db = runtime.GetTypeDB();\n\n            return db.GetConstructorOf(type);\n        }\n\n        // 用于热更 C# 代码中传入的 this\n        public static JSValue hotfix_push_classvalue(JSContext ctx, object this_obj)\n        {\n            if (this_obj == null)\n            {\n                return JSApi.JS_NULL;\n            }\n\n            return js_push_object(ctx, this_obj);\n        }\n    }\n}\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_hotfix.cs.meta",
    "content": "fileFormatVersion: 2\nguid: c29ecf8b91d3542bb8f5cd0718c2bcf4\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_inject.cs",
    "content": "﻿#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using UnityEngine;\r\n    using Native;\r\n    using Unity;\r\n\r\n    public partial class Values\r\n    {\r\n        // inject GameObject.AddComponent(Type);\r\n        public static JSValue _js_game_object_add_component(JSContext ctx, JSValue ctor, GameObject gameObject, Type type)\r\n        {\r\n            if (type == typeof(MonoBehaviour))\r\n            {\r\n#if UNITY_EDITOR\r\n                // JSBehaviour.Awake should not be executed in editor mode (not playing)\r\n                return JSBehaviour.SetScriptInstance(gameObject, ctx, ctor, UnityEditor.EditorApplication.isPlaying);\r\n#else\r\n                return JSBehaviour.SetScriptInstance(gameObject, ctx, ctor, true);\r\n#endif                \r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        public static JSValue _js_game_object_get_component(JSContext ctx, JSValue ctor, Component component, Type type)\r\n        {\r\n            return _js_game_object_get_component(ctx, ctor, component.gameObject, type);\r\n        }\r\n\r\n        public static JSValue _js_game_object_get_component(JSContext ctx, JSValue ctor, GameObject gameObject, Type type)\r\n        {\r\n            if (JSApi.JS_IsConstructor(ctx, ctor) == 1)\r\n            {\r\n                var header = JSApi.jsb_get_payload_header(ctx, ctor);\r\n                if (header.type_id == BridgeObjectType.None) // it's a plain js value\r\n                {\r\n                    if (type == typeof(MonoBehaviour))\r\n                    {\r\n                        var bridge = _get_component(gameObject, ctor);\r\n                        if (bridge != null)\r\n                        {\r\n                            return bridge.CloneValue();\r\n                        }\r\n\r\n                        return JSApi.JS_NULL; // or return an empty array?\r\n                    }\r\n                }\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        private static JSBehaviour _get_component(GameObject gameObject, JSValue ctor)\r\n        {\r\n            if (gameObject == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var allBridges = gameObject.GetComponents<JSBehaviour>();\r\n            for (int i = 0, size = allBridges.Length; i < size; i++)\r\n            {\r\n                var bridge = allBridges[i];\r\n                if (bridge.IsInstanceOf(ctor) == 1)\r\n                {\r\n                    return bridge;\r\n                }\r\n            }\r\n            return null;\r\n        }\r\n\r\n        private static JSBehaviour _get_component(Transform transform, JSValue ctor)\r\n        {\r\n            if (transform == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var allBridges = transform.GetComponents<JSBehaviour>();\r\n            for (int i = 0, size = allBridges.Length; i < size; i++)\r\n            {\r\n                var bridge = allBridges[i];\r\n                if (bridge.IsInstanceOf(ctor) == 1)\r\n                {\r\n                    return bridge;\r\n                }\r\n            }\r\n            return null;\r\n        }\r\n\r\n        private static JSBehaviour _get_component_in_children(Transform transform, JSValue ctor, bool includeInactive)\r\n        {\r\n            if (transform == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            if (includeInactive || transform.gameObject.activeInHierarchy)\r\n            {\r\n                var bridge = _get_component(transform, ctor);\r\n                if (bridge != null)\r\n                {\r\n                    return bridge;\r\n                }\r\n            }\r\n\r\n            var count = transform.childCount;\r\n            for (var i = 0; i < count; i++)\r\n            {\r\n                var child = _get_component_in_children(transform.GetChild(i), ctor, includeInactive);\r\n                if (child != null)\r\n                {\r\n                    return child;\r\n                }\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        private static JSBehaviour _get_component_in_parent(Transform transform, JSValue ctor, bool includeInactive)\r\n        {\r\n            if (transform == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            if (includeInactive || transform.gameObject.activeInHierarchy)\r\n            {\r\n                var bridge = _get_component(transform, ctor);\r\n                if (bridge != null)\r\n                {\r\n                    return bridge;\r\n                }\r\n            }\r\n\r\n            if (transform.parent != null)\r\n            {\r\n                var parent = _get_component_in_parent(transform.parent, ctor, includeInactive);\r\n                if (parent != null)\r\n                {\r\n                    return parent;\r\n                }\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        public static JSValue _js_game_object_get_component_in_children(JSContext ctx, JSValue ctor, Component component, Type type, bool includeInactive)\r\n        {\r\n            return _js_game_object_get_component_in_children(ctx, ctor, component.gameObject, type, includeInactive);\r\n        }\r\n\r\n        public static JSValue _js_game_object_get_component_in_children(JSContext ctx, JSValue ctor, GameObject gameObject, Type type, bool includeInactive)\r\n        {\r\n            if (JSApi.JS_IsConstructor(ctx, ctor) == 1)\r\n            {\r\n                var header = JSApi.jsb_get_payload_header(ctx, ctor);\r\n                if (header.type_id == BridgeObjectType.None) // it's a plain js value\r\n                {\r\n                    if (type == typeof(MonoBehaviour))\r\n                    {\r\n                        var bridge = _get_component_in_children(gameObject.transform, ctor, includeInactive);\r\n                        if (bridge != null)\r\n                        {\r\n                            return bridge.CloneValue();\r\n                        }\r\n\r\n                        return JSApi.JS_NULL; // or return an empty array?\r\n                    }\r\n                }\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        public static JSValue _js_game_object_get_component_in_parent(JSContext ctx, JSValue ctor, Component component, Type type, bool includeInactive)\r\n        {\r\n            return _js_game_object_get_component_in_parent(ctx, ctor, component.gameObject, type, includeInactive);\r\n        }\r\n\r\n        public static JSValue _js_game_object_get_component_in_parent(JSContext ctx, JSValue ctor, GameObject gameObject, Type type, bool includeInactive)\r\n        {\r\n            if (JSApi.JS_IsConstructor(ctx, ctor) == 1)\r\n            {\r\n                var header = JSApi.jsb_get_payload_header(ctx, ctor);\r\n                if (header.type_id == BridgeObjectType.None) // it's a plain js value\r\n                {\r\n                    if (type == typeof(MonoBehaviour))\r\n                    {\r\n                        var bridge = _get_component_in_parent(gameObject.transform, ctor, includeInactive);\r\n                        if (bridge != null)\r\n                        {\r\n                            return bridge.CloneValue();\r\n                        }\r\n\r\n                        return JSApi.JS_NULL; // or return an empty array?\r\n                    }\r\n                }\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        public static JSValue _js_game_object_get_components(JSContext ctx, JSValue ctor, Component component, Type type)\r\n        {\r\n            return _js_game_object_get_components(ctx, ctor, component.gameObject, type);\r\n        }\r\n\r\n        public static JSValue _js_game_object_get_components(JSContext ctx, JSValue ctor, GameObject gameObject, Type type)\r\n        {\r\n            if (JSApi.JS_IsConstructor(ctx, ctor) == 1)\r\n            {\r\n                var header = JSApi.jsb_get_payload_header(ctx, ctor);\r\n                if (header.type_id == BridgeObjectType.None) // it's a plain js value\r\n                {\r\n                    if (type == typeof(MonoBehaviour))\r\n                    {\r\n                        var array = JSApi.JS_NewArray(ctx);\r\n                        var length = 0;\r\n                        var allBridges = gameObject.GetComponents<JSBehaviour>();\r\n                        for (int i = 0, size = allBridges.Length; i < size; i++)\r\n                        {\r\n                            var bridge = allBridges[i];\r\n                            var instanceOf = bridge.IsInstanceOf(ctor);\r\n                            if (instanceOf == 1)\r\n                            {\r\n                                JSApi.JS_SetPropertyUint32(ctx, array, (uint)length, bridge.CloneValue());\r\n                                length++;\r\n                            }\r\n\r\n                            if (instanceOf == -1)\r\n                            {\r\n                                ctx.print_exception();\r\n                            }\r\n                        }\r\n\r\n                        return array; // or return an empty array?\r\n                    }\r\n                }\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        public static JSValue _js_game_object_get_components(JSContext ctx, JSValue ctor, Component component, Type type, List<Component> results)\r\n        {\r\n            return _js_game_object_get_components(ctx, ctor, component.gameObject, type, results);\r\n        }\r\n\r\n        public static JSValue _js_game_object_get_components(JSContext ctx, JSValue ctor, GameObject gameObject, Type type, List<Component> results)\r\n        {\r\n            if (JSApi.JS_IsConstructor(ctx, ctor) == 1)\r\n            {\r\n                var header = JSApi.jsb_get_payload_header(ctx, ctor);\r\n                if (header.type_id == BridgeObjectType.None) // it's a plain js value\r\n                {\r\n                    if (type == typeof(MonoBehaviour))\r\n                    {\r\n                        var allBridges = gameObject.GetComponents<JSBehaviour>();\r\n                        for (int i = 0, size = allBridges.Length; i < size; i++)\r\n                        {\r\n                            var bridge = allBridges[i];\r\n                            var instanceOf = bridge.IsInstanceOf(ctor);\r\n                            if (instanceOf == 1)\r\n                            {\r\n                                results.Add(bridge);\r\n                            }\r\n\r\n                            if (instanceOf == -1)\r\n                            {\r\n                                ctx.print_exception();\r\n                            }\r\n                        }\r\n\r\n                        return JSApi.JS_NULL;\r\n                    }\r\n                }\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        public static JSValue _js_game_object_get_components_in_children(JSContext ctx, JSValue ctor, Component component, Type type, bool includeInactive)\r\n        {\r\n            return _js_game_object_get_components_in_children(ctx, ctor, component.gameObject, type, includeInactive);\r\n        }\r\n\r\n        public static JSValue _js_game_object_get_components_in_children(JSContext ctx, JSValue ctor, GameObject gameObject, Type type, bool includeInactive)\r\n        {\r\n            if (JSApi.JS_IsConstructor(ctx, ctor) == 1)\r\n            {\r\n                var header = JSApi.jsb_get_payload_header(ctx, ctor);\r\n                if (header.type_id == BridgeObjectType.None) // it's a plain js value\r\n                {\r\n                    if (type == typeof(MonoBehaviour))\r\n                    {\r\n                        var array = JSApi.JS_NewArray(ctx);\r\n                        var length = 0;\r\n                        var allBridges = gameObject.GetComponentsInChildren<JSBehaviour>(includeInactive);\r\n                        for (int i = 0, size = allBridges.Length; i < size; i++)\r\n                        {\r\n                            var bridge = allBridges[i];\r\n                            var instanceOf = bridge.IsInstanceOf(ctor);\r\n                            if (instanceOf == 1)\r\n                            {\r\n                                JSApi.JS_SetPropertyUint32(ctx, array, (uint)length, bridge.CloneValue());\r\n                                length++;\r\n                            }\r\n\r\n                            if (instanceOf == -1)\r\n                            {\r\n                                ctx.print_exception();\r\n                            }\r\n                        }\r\n\r\n                        return array; // or return an empty array?\r\n                    }\r\n                }\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        public static JSValue _js_game_object_get_components_in_parent(JSContext ctx, JSValue ctor, Component component, Type type, bool includeInactive)\r\n        {\r\n            return _js_game_object_get_components_in_parent(ctx, ctor, component.gameObject, type, includeInactive);\r\n        }\r\n\r\n        public static JSValue _js_game_object_get_components_in_parent(JSContext ctx, JSValue ctor, GameObject gameObject, Type type, bool includeInactive)\r\n        {\r\n            if (JSApi.JS_IsConstructor(ctx, ctor) == 1)\r\n            {\r\n                var header = JSApi.jsb_get_payload_header(ctx, ctor);\r\n                if (header.type_id == BridgeObjectType.None) // it's a plain js value\r\n                {\r\n                    if (type == typeof(MonoBehaviour))\r\n                    {\r\n                        var array = JSApi.JS_NewArray(ctx);\r\n                        var length = 0;\r\n                        var allBridges = gameObject.GetComponentsInParent<JSBehaviour>(includeInactive);\r\n                        for (int i = 0, size = allBridges.Length; i < size; i++)\r\n                        {\r\n                            var bridge = allBridges[i];\r\n                            var instanceOf = bridge.IsInstanceOf(ctor);\r\n                            if (instanceOf == 1)\r\n                            {\r\n                                JSApi.JS_SetPropertyUint32(ctx, array, (uint)length, bridge.CloneValue());\r\n                                length++;\r\n                            }\r\n\r\n                            if (instanceOf == -1)\r\n                            {\r\n                                ctx.print_exception();\r\n                            }\r\n                        }\r\n\r\n                        return array; // or return an empty array?\r\n                    }\r\n                }\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_inject.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 77e32cc4d3414afb91705af7fa949dd7\r\ntimeCreated: 1591852994"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_match.cs",
    "content": "using System;\r\nusing System.Reflection;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using Native;\r\n\r\n    // 处理类型匹配\r\n    public partial class Values\r\n    {\r\n        public static bool js_read_wrap(JSContext ctx, JSValue jsValue, out JSValue realValue)\r\n        {\r\n            if (jsValue.IsNullish())\r\n            {\r\n                realValue = jsValue;\r\n                return true;\r\n            }\r\n\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            realValue = JSApi.JS_GetProperty(ctx, jsValue, context.GetAtom(\"value\"));\r\n            return !realValue.IsException();\r\n        }\r\n\r\n        public static JSValue js_read_wrap(JSContext ctx, JSValue jsValue)\r\n        {\r\n            if (jsValue.IsNullish())\r\n            {\r\n                return jsValue;\r\n            }\r\n\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            return JSApi.JS_GetProperty(ctx, jsValue, context.GetAtom(\"value\"));\r\n        }\r\n\r\n        // guess real type in Ref<T> / Out<T>\r\n        public static bool js_match_type_hint(JSContext ctx, JSValue jsValue, Type type)\r\n        {\r\n            if (jsValue.IsNullish())\r\n            {\r\n                return false;\r\n            }\r\n\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            var jsHintType = JSApi.JS_GetProperty(ctx, jsValue, context.GetAtom(\"type\"));\r\n            if (jsHintType.IsNullish())\r\n            {\r\n                return true;\r\n            }\r\n\r\n            var rs = js_match_type(ctx, jsHintType, type);\r\n            JSApi.JS_FreeValue(ctx, jsHintType);\r\n            return rs;\r\n        }\r\n\r\n        public static bool js_match_type(JSContext ctx, JSValue jsValue, Type type)\r\n        {\r\n            if (type == null)\r\n            {\r\n                return true;\r\n            }\r\n            if (type == typeof(object))\r\n            {\r\n                return true;\r\n            }\r\n            if (type == typeof(Type)) \r\n            {\r\n                Type otype;\r\n                // just check if the value is a type without comparing since what expected is a type of Type itself\r\n                return js_get_classvalue(ctx, jsValue, out otype); \r\n            }\r\n\r\n            if (JSApi.JS_IsObject(jsValue))\r\n            {\r\n                if (type == typeof(ScriptFunction) || type.BaseType == typeof(MulticastDelegate))\r\n                {\r\n                    return JSApi.JS_IsFunction(ctx, jsValue) == 1;\r\n                }\r\n\r\n                var context = ScriptEngine.GetContext(ctx);\r\n                var type_id = JSApi.JSB_GetBridgeType(ctx, jsValue, context.GetAtom(Values.KeyForCSharpTypeID));\r\n                if (type_id > 0)\r\n                {\r\n                    var types = context.GetTypeDB();\r\n                    var o = types.GetType(type_id);\r\n                    // UnityEngine.Debug.Log($\"get type from exported registry {o}:{type_id} expected:{type}\");\r\n                    return o != null && (o == type || type.IsAssignableFrom(o));\r\n                }\r\n\r\n                var header = JSApi.jsb_get_payload_header(ctx, jsValue);\r\n                switch (header.type_id)\r\n                {\r\n                    case BridgeObjectType.ObjectRef:\r\n                        {\r\n                            var cache = ScriptEngine.GetObjectCache(ctx);\r\n                            return cache.MatchObjectType(header.value, type);\r\n                        }\r\n                    case BridgeObjectType.TypeRef:\r\n                        {\r\n                            return type == typeof(Type);\r\n                        }\r\n                    case BridgeObjectType.ValueType:\r\n                        {\r\n                            break;\r\n                        }\r\n                    default: // plain js object?\r\n                        {\r\n                            if (type.IsValueType)\r\n                            {\r\n                                if (type.IsPrimitive || type.IsEnum)\r\n                                {\r\n                                    return context.CheckNumberType(jsValue);\r\n                                }\r\n                            }\r\n                            else if (type == typeof(string))\r\n                            {\r\n                                return context.CheckStringType(jsValue);\r\n                            }\r\n\r\n                            break;\r\n                        }\r\n                }\r\n\r\n                if (type.IsArray)\r\n                {\r\n                    return JSApi.JS_IsArray(ctx, jsValue) == 1;\r\n                }\r\n\r\n                return typeof(ScriptValue).IsAssignableFrom(type);\r\n            }\r\n\r\n            if (jsValue.IsNullish())\r\n            {\r\n                return !type.IsValueType && !type.IsPrimitive;\r\n            }\r\n\r\n            if (jsValue.IsBoolean())\r\n            {\r\n                return type == typeof(bool);\r\n            }\r\n\r\n            if (jsValue.IsString())\r\n            {\r\n                return type == typeof(string);\r\n            }\r\n\r\n            if (jsValue.IsNumber())\r\n            {\r\n                if (type.IsEnum || type.IsPrimitive)\r\n                {\r\n                    return true;\r\n                }\r\n\r\n                return false;\r\n            }\r\n\r\n            if (type == typeof(byte[]))\r\n            {\r\n                size_t psize;\r\n                var ptr = JSApi.JS_GetArrayBuffer(ctx, out psize, jsValue);\r\n                if (ptr != IntPtr.Zero)\r\n                {\r\n                    return true;\r\n                }\r\n\r\n                var asBuffer = JSApi.JS_GetProperty(ctx, jsValue, ScriptEngine.GetContext(ctx).GetAtom(\"buffer\"));\r\n                if (asBuffer.IsObject())\r\n                {\r\n                    ptr = JSApi.JS_GetArrayBuffer(ctx, out psize, asBuffer);\r\n                    JSApi.JS_FreeValue(ctx, asBuffer);\r\n                    return ptr != IntPtr.Zero;\r\n                }\r\n                else\r\n                {\r\n                    JSApi.JS_FreeValue(ctx, asBuffer);\r\n                }\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        // 检查变参参数\r\n        // offset: 从偏移处开始为变参\r\n        public static bool js_match_param_types(JSContext ctx, int offset, JSValue[] argv, Type type)\r\n        {\r\n            var nargs = argv.Length;\r\n            for (var i = offset; i < nargs; i++)\r\n            {\r\n                if (!js_match_type(ctx, argv[i], type))\r\n                {\r\n                    return false;\r\n                }\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n        public static bool js_match_types(JSContext ctx, JSValue[] argv, Type t0)\r\n        {\r\n            return js_match_type(ctx, argv[0], t0);\r\n        }\r\n\r\n        public static bool js_match_types(JSContext ctx, JSValue[] argv, Type t0, Type t1)\r\n        {\r\n            return js_match_type(ctx, argv[0], t0) && js_match_type(ctx, argv[1], t1);\r\n        }\r\n\r\n        public static bool js_match_types(JSContext ctx, JSValue[] argv, Type t0, Type t1, Type t2)\r\n        {\r\n            return js_match_type(ctx, argv[0], t0) && js_match_type(ctx, argv[1], t1) && js_match_type(ctx, argv[2], t2);\r\n        }\r\n\r\n        public static bool js_match_types(JSContext ctx, JSValue[] argv, Type t0, Type t1, Type t2, Type t3)\r\n        {\r\n            return js_match_type(ctx, argv[0], t0) && js_match_type(ctx, argv[1], t1) && js_match_type(ctx, argv[2], t2) && js_match_type(ctx, argv[3], t3);\r\n        }\r\n\r\n        public static bool js_match_types(JSContext ctx, JSValue[] argv, Type t0, Type t1, Type t2, Type t3, Type t4)\r\n        {\r\n            return js_match_type(ctx, argv[0], t0) && js_match_type(ctx, argv[1], t1) && js_match_type(ctx, argv[2], t2) && js_match_type(ctx, argv[3], t3) && js_match_type(ctx, argv[4], t4);\r\n        }\r\n\r\n        public static bool js_match_types(JSContext ctx, JSValue[] argv, Type t0, Type t1, Type t2, Type t3, Type t4, Type t5)\r\n        {\r\n            return js_match_type(ctx, argv[0], t0) && js_match_type(ctx, argv[1], t1) && js_match_type(ctx, argv[2], t2) && js_match_type(ctx, argv[3], t3) && js_match_type(ctx, argv[4], t4) && js_match_type(ctx, argv[5], t5);\r\n        }\r\n\r\n        public static bool js_match_types(JSContext ctx, JSValue[] argv, Type t0, Type t1, Type t2, Type t3, Type t4, Type t5, Type t6)\r\n        {\r\n            return js_match_type(ctx, argv[0], t0) && js_match_type(ctx, argv[1], t1) && js_match_type(ctx, argv[2], t2) && js_match_type(ctx, argv[3], t3) && js_match_type(ctx, argv[4], t4) && js_match_type(ctx, argv[5], t5) && js_match_type(ctx, argv[6], t6);\r\n        }\r\n\r\n        public static bool js_match_types(JSContext ctx, JSValue[] argv, params Type[] types)\r\n        {\r\n            for (int i = 0, size = types.Length; i < size; i++)\r\n            {\r\n                if (!js_match_type(ctx, argv[i], types[i]))\r\n                {\r\n                    return false;\r\n                }\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n        public static bool js_match_parameters(JSContext ctx, JSValue[] argv, ParameterInfo[] parameterInfos)\r\n        {\r\n            for (int i = 0, size = parameterInfos.Length; i < size; i++)\r\n            {\r\n                var parameterInfo = parameterInfos[i];\r\n                var pType = parameterInfo.ParameterType;\r\n\r\n                if (i >= argv.Length)\r\n                {\r\n                    if (!parameterInfo.IsOptional)\r\n                    {\r\n                        return false;\r\n                    }\r\n                    continue;\r\n                }\r\n\r\n                if (pType.IsByRef)\r\n                {\r\n                    if (!js_match_type_hint(ctx, argv[i], pType.GetElementType()))\r\n                    {\r\n                        return false;\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    if (!js_match_type(ctx, argv[i], pType))\r\n                    {\r\n                        return false;\r\n                    }\r\n                }\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n        public static bool js_match_parameters_vararg(JSContext ctx, int argc, JSValue[] argv, ParameterInfo[] parameterInfos)\r\n        {\r\n            var size = parameterInfos.Length - 1;\r\n            if (argc < size)\r\n            {\r\n                return false;\r\n            }\r\n            for (var i = 0; i < size; i++)\r\n            {\r\n                var parameterInfo = parameterInfos[i];\r\n                var pType = parameterInfo.ParameterType;\r\n                if (pType.IsByRef)\r\n                {\r\n                    if (!js_match_type_hint(ctx, argv[i], pType.GetElementType()))\r\n                    {\r\n                        return false;\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    if (!js_match_type(ctx, argv[i], pType))\r\n                    {\r\n                        return false;\r\n                    }\r\n                }\r\n            }\r\n\r\n            var varArgType = parameterInfos[size].ParameterType.GetElementType();\r\n            for (var i = size; i < argc; i++)\r\n            {\r\n                if (!js_match_type(ctx, argv[i], varArgType))\r\n                {\r\n                    return false;\r\n                }\r\n            }\r\n\r\n            return true;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_match.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 7100c99a7a7a734459de4906f1463314\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_new.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using Native;\r\n\r\n    // 处理特殊操作, 关联本地对象等\r\n    public partial class Values\r\n    {\r\n        /// <summary>\r\n        /// 用于对由 js 构造产生的 c# 对象产生一个 js 包装对象 \r\n        /// 注意: 此函数签名发生变化时, 用于优化的所有重载匹配函数需要统一变化\r\n        /// </summary>\r\n        /// <param name=\"ctx\">JS 环境</param>\r\n        /// <param name=\"new_target\">构造</param>\r\n        /// <param name=\"o\">CS 对象</param>\r\n        /// <param name=\"type_id\">类型索引</param>\r\n        /// <param name=\"disposable\">是否生命周期完全由JS托管, 映射对象释放时, CS对象将被Dispose(如果是IDisposable)</param>\r\n        /// <returns>映射对象</returns>\r\n        public static JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, object o, int type_id, bool disposable)\r\n        {\r\n            var cache = ScriptEngine.GetObjectCache(ctx);\r\n            var object_id = cache.AddObject(o, disposable);\r\n            var val = JSApi.JSB_NewBridgeClassObject(ctx, new_target, object_id);\r\n            if (JSApi.JS_IsException(val))\r\n            {\r\n                cache.RemoveObject(object_id);\r\n            }\r\n            else\r\n            {\r\n                cache.AddJSValue(o, val);\r\n            }\r\n\r\n            return val;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_new.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 60d358ea17bad514dae97368de0f9f10\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_push_class.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n#if !JSB_UNITYLESS\r\n        // variant push\r\n        // explicitly call UnityEngine.Object.operator == \r\n        public static JSValue js_push_classvalue(JSContext ctx, UnityEngine.Object o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n\r\n            return js_push_object(ctx, (object)o);\r\n        }\r\n#endif\r\n\r\n        public static JSValue js_push_classvalue(JSContext ctx, ScriptValue o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            return JSApi.JS_DupValue(ctx, o);\r\n        }\r\n\r\n        public static unsafe JSValue js_push_classvalue(JSContext ctx, Array o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n\r\n            return js_push_object(ctx, (object)o);\r\n        }\r\n\r\n        public static JSValue js_push_classvalue(JSContext ctx, ScriptPromise promise)\r\n        {\r\n            if (promise == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            return JSApi.JS_DupValue(ctx, promise);\r\n        }\r\n\r\n        public static JSValue js_push_classvalue(JSContext ctx, Type o)\r\n        {\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            var types = context.GetTypeDB();\r\n            var jsVal = types.GetPrototypeOf(o);\r\n            return JSApi.JS_DupValue(ctx, jsVal);\r\n        }\r\n\r\n        public static JSValue js_push_classvalue(JSContext ctx, object o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n\r\n            return js_push_object(ctx, o);\r\n        }\r\n\r\n        // push 一个对象实例 \r\n        public static JSValue js_push_object(JSContext ctx, object o)\r\n        {\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            return context.NewBridgeObjectBind(o);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_push_class.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 68bcc9fe98905df44aff6498cb80fe56\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_push_primitive.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static JSValue js_push_primitive(JSContext ctx, JSValue o)\r\n        {\r\n            return JSApi.JS_DupValue(ctx, o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, IntPtr o)\r\n        {\r\n            return js_push_classvalue(ctx, o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, IntPtr? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            return js_push_classvalue(ctx, (IntPtr)o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, bool o)\r\n        {\r\n            return JSApi.JS_NewBool(ctx, o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, bool? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            return JSApi.JS_NewBool(ctx, (bool)o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, sbyte o)\r\n        {\r\n            return JSApi.JS_NewInt32(ctx, o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, sbyte? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            return JSApi.JS_NewInt32(ctx, (sbyte)o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, byte o)\r\n        {\r\n            return JSApi.JS_NewInt32(ctx, o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, byte? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            return JSApi.JS_NewInt32(ctx, (byte)o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, char o)\r\n        {\r\n            return JSApi.JS_NewInt32(ctx, o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, char? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            return JSApi.JS_NewInt32(ctx, (char)o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, short o)\r\n        {\r\n            return JSApi.JS_NewInt32(ctx, o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, short? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            return JSApi.JS_NewInt32(ctx, (short)o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, ushort o)\r\n        {\r\n            return JSApi.JS_NewInt32(ctx, o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, ushort? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            return JSApi.JS_NewInt32(ctx, (ushort)o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, int o)\r\n        {\r\n            return JSApi.JS_NewInt32(ctx, o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, int? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            return JSApi.JS_NewInt32(ctx, (int)o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, uint o)\r\n        {\r\n            return JSApi.JS_NewUint32(ctx, o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, uint? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            return JSApi.JS_NewUint32(ctx, (uint)o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, long o)\r\n        {\r\n            return JSApi.JSB_NewInt64(ctx, o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, long? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            return JSApi.JSB_NewInt64(ctx, (long)o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, ulong o)\r\n        {\r\n            return JSApi.JSB_NewInt64(ctx, (long)o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, ulong? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            return JSApi.JSB_NewInt64(ctx, (long)o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, float o)\r\n        {\r\n            return JSApi.JS_NewFloat64(ctx, o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, float? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            return JSApi.JS_NewFloat64(ctx, (float)o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, double o)\r\n        {\r\n            return JSApi.JS_NewFloat64(ctx, o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, double? o)\r\n        {\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            return JSApi.JS_NewFloat64(ctx, (double)o);\r\n        }\r\n\r\n        public static JSValue js_push_primitive(JSContext ctx, string o)\r\n        {\r\n            //TODO: make the stringcache behaviour configurable?\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            var cache = context.GetStringCache();\r\n            JSValue jsValue;\r\n            if (cache.TryGetValue(o, out jsValue))\r\n            {\r\n                return JSApi.JS_DupValue(ctx, jsValue);\r\n            }\r\n\r\n            return ctx.NewString(o);\r\n        }\r\n\r\n        public static JSValue js_push_enumvalue<T>(JSContext ctx, T o)\r\n        where T : Enum\r\n        {\r\n            return js_push_primitive(ctx, Convert.ToInt32(o));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_push_primitive.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 6db4a4cd79840e24392d52877b578cbf\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_push_struct.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        public static JSValue js_push_structvalue<T>(JSContext ctx, T o)\r\n            where T : struct\r\n        {\r\n            return js_push_classvalue(ctx, o);\r\n        }\r\n\r\n        public static JSValue js_push_structvalue<T>(JSContext ctx, T? o)\r\n            where T : struct\r\n        {\r\n            return js_push_classvalue(ctx, o);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_push_struct.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: abff6870301f4ff4789bba5ccb0f750e\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_replace.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Binding\r\n{\r\n    using Native;\r\n\r\n    public partial class Values\r\n    {\r\n        /// <summary>\r\n        /// It's the default behaviour for value rebinding, write an overloaded version of this function for a specific type if it's different from the default.\r\n        /// </summary>\r\n        public static bool js_rebind_this<T>(JSContext ctx, JSValue this_obj, ref T o)\r\n        // where T : struct\r\n        {\r\n            var header = JSApi.jsb_get_payload_header(ctx, this_obj);\r\n            switch (header.type_id)\r\n            {\r\n                case BridgeObjectType.ObjectRef:\r\n                    return ScriptEngine.GetObjectCache(ctx).ReplaceObject(header.value, o);\r\n            }\r\n            return false;\r\n        }\r\n\r\n        // fallback\r\n        public static bool js_rebind_this(JSContext ctx, JSValue this_obj, ref object o)\r\n        {\r\n            var header = JSApi.jsb_get_payload_header(ctx, this_obj);\r\n            switch (header.type_id)\r\n            {\r\n                case BridgeObjectType.ObjectRef:\r\n                    return ScriptEngine.GetObjectCache(ctx).ReplaceObject(header.value, o);\r\n            }\r\n            return false;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding/Values_replace.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: c0f8c515627e250478aa46e6abbd6068\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Binding.meta",
    "content": "fileFormatVersion: 2\r\nguid: dc2a5e8fc34a3ab4f826be5607726d34\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Buffer/ByteBuffer.cs",
    "content": "using System;\nusing System.Net;\n\nnamespace QuickJS.IO\n{\n    // 容量会自动扩展 (翻倍)\n    // 所有操作都不是线程安全的\n    public class ByteBuffer : Utils.IReferenceObject\n    {\n        private IByteBufferAllocator _allocator;\n\n        private int _refCount = 0;\n        private byte[] _data;\n\n        private int _writePosition;  // 写入操作当前位置\n        private int _readPosition;  // 当前观察位置 （网络数据写入时会用到）\n        private int _maxCapacity;\n\n        // 内部数据\n        public byte[] data { get { return _data; } }\n\n        public int capacity { get { return _data.Length; } }\n\n        public int writerIndex\n        {\n            get { return _writePosition; }\n            set\n            {\n                if (_writePosition != value)\n                {\n                    if (value < 0 || value > _maxCapacity)\n                    {\n                        throw new IndexOutOfRangeException();\n                    }\n                    EnsureCapacity(value);\n                    _writePosition = value;\n                }\n            }\n        }\n\n        // 剩余可以读取的字节数量\n        public int readableBytes { get { return _writePosition - _readPosition; } }\n\n        public int readerIndex\n        {\n            get { return _readPosition; }\n            set\n            {\n                if (_readPosition != value)\n                {\n                    if (value < 0 || value > _writePosition)\n                    {\n                        throw new IndexOutOfRangeException();\n                    }\n                    _readPosition = value;\n                }\n            }\n        }\n\n        public int maxCapacity { get { return _maxCapacity; } }\n\n        public bool isWritable\n        {\n            get { return _writePosition < _maxCapacity; }\n        }\n\n        public override string ToString()\n        {\n            return string.Format(\"<ByteBuffer offset: {0} remain: {1} #{2}>\", readerIndex, readableBytes, _data.Length);\n        }\n\n        public ByteBuffer(byte[] data) : this(data, int.MaxValue)\n        {\n        }\n\n        public ByteBuffer(byte[] data, int maxCapacity)\n        {\n            _data = data;\n            _writePosition = _data != null ? _data.Length : 0;\n            _maxCapacity = maxCapacity > _writePosition ? maxCapacity : _writePosition;\n            _readPosition = 0;\n            _allocator = null;\n        }\n\n        public ByteBuffer(int initialCapacity, int maxCapacity, IByteBufferAllocator allocator)\n        {\n            _data = new byte[initialCapacity];\n            _maxCapacity = maxCapacity > initialCapacity ? maxCapacity : initialCapacity;\n            _writePosition = 0;\n            _readPosition = 0;\n            _allocator = allocator;\n        }\n\n        public void Release()\n        {\n            --_refCount;\n            if (_refCount == 0)\n            {\n                _writePosition = 0;\n                _readPosition = 0;\n                if (_allocator != null)\n                {\n                    // Debug.LogFormat(\"<< ByteBuffer released {0}\", GetHashCode());\n                    _allocator.Recycle(this);\n                }\n            }\n        }\n\n        public ByteBuffer Retain()\n        {\n            //         #if DEBUG\n            // if (_refCount == 0)\n            // {\n            //     if (_allocator != null)\n            //     {\n            //         var stackTrace = new System.Diagnostics.StackTrace(true);\n            //         string debugInfo = \"\";\n            //         for (var i = 0; i < stackTrace.FrameCount; i++)\n            //         {\n            //             var stackFrame = stackTrace.GetFrame(i);\n            //             debugInfo += string.Format(\"[{0}] Method: {1}\\n\", i, stackFrame.GetMethod());\n            //             debugInfo += string.Format(\"[{0}] Line Number: {1}\\n\", i, stackFrame.GetFileLineNumber());\n            //         }\n            //         _stacktrace = debugInfo;\n            //     }\n            //     // Debug.LogFormat(\">> ByteBuffer allocated {0}\", GetHashCode());\n            // }\n            //         #endif\n            ++_refCount;\n            return this;\n        }\n\n        public ByteBuffer Slice(int size)\n        {\n            CheckReadalbe(size);\n            var slice = new ByteBuffer(data, data.Length).Retain();\n            slice._writePosition = this._readPosition + size;\n            slice._readPosition = this._readPosition;\n            this._readPosition += size;\n            return slice;\n        }\n\n        #region reader operations\n\n        public void CheckReadalbe(int size)\n        {\n            if (readableBytes < size)\n            {\n                throw new IndexOutOfRangeException(string.Format(\"readableBytes {0} size {1}\", readableBytes, size));\n            }\n        }\n\n        // 跳过指定的字节数量\n        public void ReadBytes(int count)\n        {\n            CheckReadalbe(count);\n            _readPosition += count;\n        }\n\n        public byte ReadUByte()\n        {\n            CheckReadalbe(sizeof(byte));\n            var v = _data[_readPosition];\n            _readPosition += sizeof(byte);\n            return v;\n        }\n\n        public sbyte ReadSByte()\n        {\n            CheckReadalbe(sizeof(sbyte));\n            var v = _data[_readPosition];\n            _readPosition += sizeof(sbyte);\n            return (sbyte)v;\n        }\n\n        public int ReadBytes(byte[] dst, int dstOffset, int size)\n        {\n            // CheckReadalbe(1);\n            if (size > readableBytes)\n            {\n                size = readableBytes;\n            }\n\n            if (size > 0)\n            {\n                Buffer.BlockCopy(_data, _readPosition, dst, dstOffset, size);\n                _readPosition += size;\n            }\n\n            return size;\n        }\n\n        // dangerous: read bytes to destination pointer\n        public int ReadBytes(IntPtr pointer, int size)\n        {\n            // CheckReadalbe(1);\n            if (size > readableBytes)\n            {\n                size = readableBytes;\n            }\n\n            if (size > 0)\n            {\n                System.Runtime.InteropServices.Marshal.Copy(_data, _readPosition, pointer, size);\n                _readPosition += size;\n            }\n\n            return size;\n        }\n\n        public bool ReadBoolean()\n        {\n            CheckReadalbe(sizeof(bool));\n            var v = BitConverter.ToBoolean(_data, _readPosition);\n            _readPosition += sizeof(bool);\n            return v;\n        }\n\n        // 读取所有可读取的字节并返回\n        public byte[] ReadAllBytes()\n        {\n            if (readableBytes == 0)\n            {\n                return null;\n            }\n            var bytes = new byte[readableBytes];\n            Buffer.BlockCopy(_data, _readPosition, bytes, 0, readableBytes);\n            _readPosition += readableBytes;\n            return bytes;\n        }\n\n        // dangerous: read all bytes to destination pointer\n        public int ReadAllBytes(IntPtr pointer)\n        {\n            var size = readableBytes;\n            if (size == 0)\n            {\n                return size;\n            }\n            System.Runtime.InteropServices.Marshal.Copy(_data, _readPosition, pointer, size);\n            _readPosition += size;\n            return size;\n        }\n\n        public float ReadSingle()\n        {\n            CheckReadalbe(sizeof(float));\n            var v = BitConverter.ToSingle(_data, _readPosition);\n            _readPosition += sizeof(float);\n            return v;\n        }\n\n        public double ReadDouble()\n        {\n            CheckReadalbe(sizeof(double));\n            var v = BitConverter.ToDouble(_data, _readPosition);\n            _readPosition += sizeof(double);\n            return v;\n        }\n\n        public string ReadString()\n        {\n            var length = ReadInt32();\n            if (length == 0)\n            {\n                return string.Empty;\n            }\n\n            var bytes = new byte[length];\n            ReadBytes(bytes, 0, length);\n            return System.Text.Encoding.UTF8.GetString(bytes);\n        }\n\n        public short ReadInt16()\n        {\n            CheckReadalbe(sizeof(short));\n            var v = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(_data, _readPosition));\n            _readPosition += sizeof(short);\n            return v;\n        }\n\n        public ushort ReadUInt16()\n        {\n            CheckReadalbe(sizeof(ushort));\n            var v = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(_data, _readPosition));\n            _readPosition += sizeof(ushort);\n            return v;\n        }\n\n        public int ReadInt32()\n        {\n            CheckReadalbe(sizeof(int));\n            var v = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(_data, _readPosition));\n            _readPosition += sizeof(int);\n            return v;\n        }\n\n        public uint ReadUInt32()\n        {\n            CheckReadalbe(sizeof(uint));\n            var v = (uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(_data, _readPosition));\n            _readPosition += sizeof(uint);\n            return v;\n        }\n\n        public long ReadInt64()\n        {\n            CheckReadalbe(sizeof(long));\n            var v = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt64(_data, _readPosition));\n            _readPosition += sizeof(long);\n            return v;\n        }\n\n        public ulong ReadUInt64()\n        {\n            CheckReadalbe(sizeof(ulong));\n            var v = (ulong)System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt64(_data, _readPosition));\n            _readPosition += sizeof(long);\n            return v;\n        }\n\n        #endregion\n\n        #region writer operations\n\n        // 确保容量达到value值，不够时自动扩容 (*2)\n        public void EnsureCapacity(int value)\n        {\n            var capacity = _data.Length;\n            if (value > capacity)\n            {\n                var newCapacity = value;\n                if (newCapacity < 256)\n                {\n                    newCapacity = 256;\n                }\n                if (newCapacity < capacity * 2)\n                {\n                    newCapacity = capacity * 2;\n                }\n                if (newCapacity > _maxCapacity)\n                {\n                    throw new IndexOutOfRangeException();\n                }\n                Array.Resize(ref _data, newCapacity);\n            }\n        }\n\n        public void WriteByte(byte data)\n        {\n            EnsureCapacity(_writePosition + sizeof(byte));\n            _data[_writePosition] = (byte)data;\n            _writePosition += sizeof(byte);\n        }\n\n        public void WriteSByte(sbyte data)\n        {\n            EnsureCapacity(_writePosition + sizeof(byte));\n            _data[_writePosition] = (byte)data;\n            _writePosition += sizeof(byte);\n        }\n\n        public void _SetPosition(int size)\n        {\n            EnsureCapacity(_writePosition + size);\n            _writePosition += size;\n        }\n\n        public void WriteBytes(System.IO.MemoryStream memoryStream, int size)\n        {\n            if (size > 0)\n            {\n                EnsureCapacity(_writePosition + size);\n                memoryStream.Read(_data, _writePosition, size);\n                _writePosition += size;\n            }\n        }\n\n        public void WriteBytes(IntPtr pointer, int size)\n        {\n            if (size > 0)\n            {\n                EnsureCapacity(_writePosition + size);\n                System.Runtime.InteropServices.Marshal.Copy(pointer, _data, _writePosition, size);\n                _writePosition += size;\n            }\n        }\n\n        // 将 other 中所有可读取的字节写入当前 buffer 中\n        public void WriteBytes(ByteBuffer other)\n        {\n            if (other == null || other.readableBytes == 0)\n            {\n                return;\n            }\n            else\n            {\n                EnsureCapacity(_writePosition + other.readableBytes);\n                Buffer.BlockCopy(other._data, other.readerIndex, _data, _writePosition, other.readableBytes);\n                _writePosition += other.readableBytes;\n            }\n        }\n\n        // 写入位置后移指定字节数 (内容不确定)\n        public void WriteBytes(int byteCount)\n        {\n            EnsureCapacity(_writePosition + byteCount);\n            _writePosition += byteCount;\n        }\n\n        public void WriteBytes(byte[] data)\n        {\n            EnsureCapacity(_writePosition + data.Length);\n            Buffer.BlockCopy(data, 0, _data, _writePosition, data.Length);\n            _writePosition += data.Length;\n        }\n\n        public void WriteBytes(byte[] src, int srcOffset, int count)\n        {\n            EnsureCapacity(_writePosition + count);\n            Buffer.BlockCopy(src, srcOffset, _data, _writePosition, count);\n            _writePosition += count;\n        }\n\n        public void WriteBoolean(bool value)\n        {\n            WriteBytes(BitConverter.GetBytes(value));\n        }\n\n        public void WriteInt16(short value)\n        {\n            WriteBytes(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(value)));\n        }\n\n        public void WriteUInt16(ushort value)\n        {\n            WriteBytes(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)value)));\n        }\n\n        public void WriteInt32(int value)\n        {\n            WriteBytes(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(value)));\n        }\n\n        public void WriteUInt32(uint value)\n        {\n            WriteBytes(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((int)value)));\n        }\n\n        public void WriteInt64(long value)\n        {\n            var data = BitConverter.GetBytes(System.Net.IPAddress.HostToNetworkOrder(value));\n            WriteBytes(data);\n        }\n\n        public void WriteUInt64(ulong value)\n        {\n            var data = BitConverter.GetBytes(System.Net.IPAddress.HostToNetworkOrder((long)value));\n            WriteBytes(data);\n        }\n\n        public void WriteSingle(float value)\n        {\n            WriteBytes(BitConverter.GetBytes(value));\n        }\n\n        public void WriteDouble(double value)\n        {\n            WriteBytes(BitConverter.GetBytes(value));\n        }\n\n        public void WriteString(string value)\n        {\n            if (string.IsNullOrEmpty(value))\n            {\n                WriteInt32(0);\n            }\n            else\n            {\n                var bytes = System.Text.Encoding.UTF8.GetBytes(value);\n                WriteInt32(bytes.Length);\n                WriteBytes(bytes);\n            }\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Buffer/ByteBuffer.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 319b2c195f98df342bbedf99e2d0d6a5\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Buffer/ByteBufferPooledAllocator.cs",
    "content": "﻿using System.Collections.Generic;\r\n\r\nnamespace QuickJS.IO\r\n{\r\n    // 简易的 ByteBuffer 池分配器, 非线程安全\r\n    public class ByteBufferPooledAllocator : IByteBufferAllocator\r\n    {\r\n        private int _maxCapacity;\r\n        private List<ByteBuffer> __freelist;\r\n\r\n        public ByteBufferPooledAllocator()\r\n        : this(24, 512, int.MaxValue)\r\n        {\r\n        }\r\n\r\n        // 预分配缓冲池\r\n        public ByteBufferPooledAllocator(int prealloc, int initialCapacity, int maxCapacity)\r\n        {\r\n            _maxCapacity = maxCapacity;\r\n            __freelist = new List<ByteBuffer>(prealloc);\r\n            while (prealloc-- > 0)\r\n            {\r\n                __freelist.Add(new ByteBuffer(initialCapacity, maxCapacity, this));\r\n            }\r\n        }\r\n\r\n        // 返回一个由对象池分配的 ByteBuffer 对象, 大小至少为 size\r\n        public ByteBuffer Alloc(int size)\r\n        {\r\n            var count = __freelist.Count;\r\n            if (count > 0)\r\n            {\r\n                var free = __freelist[count - 1];\r\n                __freelist.RemoveAt(count - 1);\r\n                free.Retain();\r\n                return free;\r\n            }\r\n            return new ByteBuffer(size, _maxCapacity, this).Retain();\r\n        }\r\n\r\n        public void Recycle(ByteBuffer byteBuffer)\r\n        {\r\n            __freelist.Add(byteBuffer);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Buffer/ByteBufferPooledAllocator.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: a4f6708b3be9e194ab95d82f561656c3\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Buffer/ByteBufferReader.cs",
    "content": "﻿using System;\r\nusing System.IO;\r\n\r\nnamespace QuickJS.IO\r\n{\r\n    public class ByteBufferReader : System.IO.Stream\r\n    {\r\n        private ByteBuffer _byteBuffer;\r\n\r\n        public ByteBufferReader(ByteBuffer byteBuffer)\r\n        {\r\n            _byteBuffer = byteBuffer;\r\n        }\r\n\r\n        public override bool CanWrite\r\n        {\r\n            get { return _byteBuffer.isWritable; }\r\n        }\r\n\r\n        public override bool CanSeek\r\n        {\r\n            get { return true; }\r\n        }\r\n\r\n        public override bool CanRead\r\n        {\r\n            get { return true; }\r\n        }\r\n\r\n        public override long Position\r\n        {\r\n            get { return _byteBuffer.readerIndex; }\r\n            set { _byteBuffer.readerIndex = (int)value; }\r\n        }\r\n        public override long Length { get { return _byteBuffer.readableBytes; } }\r\n\r\n        public override void Flush() { }\r\n\r\n        public override int Read(byte[] buffer, int offset, int count)\r\n        {\r\n            return _byteBuffer.ReadBytes(buffer, offset, count);\r\n        }\r\n        public override int ReadByte()\r\n        {\r\n            return _byteBuffer.ReadUByte();\r\n        }\r\n        public override long Seek(long offset, SeekOrigin loc)\r\n        {\r\n            switch (loc)\r\n            {\r\n                case SeekOrigin.Begin: _byteBuffer.readerIndex = (int)offset; return _byteBuffer.readerIndex;\r\n                case SeekOrigin.Current: _byteBuffer.readerIndex += (int)offset; return _byteBuffer.readerIndex;\r\n                default: _byteBuffer.readerIndex -= (int)offset; return _byteBuffer.readerIndex;\r\n            }\r\n        }\r\n\r\n        public override void SetLength(long value)\r\n        {\r\n            throw new NotSupportedException();\r\n        }\r\n\r\n        public override void Write(byte[] buffer, int offset, int count)\r\n        {\r\n            throw new NotSupportedException();\r\n        }\r\n\r\n        // public override void WriteByte(byte value);\r\n        protected override void Dispose(bool disposing)\r\n        {\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Buffer/ByteBufferReader.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: b90a0ad245b807142a4f2423c91d63da\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Buffer/ByteBufferThreadedPooledAllocator.cs",
    "content": "﻿using System.Collections.Generic;\r\nusing System.Threading;\r\n\r\nnamespace QuickJS.IO\r\n{\r\n    // 简易的 ByteBuffer 池分配器\r\n    // 仅保证分配与回收的线程安全, 不保证数据读写的线程安全\r\n    public class ByteBufferThreadedPooledAllocator : IByteBufferAllocator\r\n    {\r\n        private int _maxCapacity;\r\n        private List<ByteBuffer> __freelist;\r\n\r\n        public ByteBufferThreadedPooledAllocator()\r\n        : this(2, 1024, int.MaxValue)\r\n        {\r\n        }\r\n\r\n        // 预分配缓冲池\r\n        public ByteBufferThreadedPooledAllocator(int prealloc, int initialCapacity, int maxCapacity)\r\n        {\r\n            _maxCapacity = maxCapacity;\r\n            __freelist = new List<ByteBuffer>(prealloc);\r\n            while (prealloc-- > 0)\r\n            {\r\n                __freelist.Add(new ByteBuffer(initialCapacity, maxCapacity, this));\r\n            }\r\n        }\r\n\r\n        // 返回一个由对象池分配的 ByteBuffer 对象, 大小至少为 size\r\n        public ByteBuffer Alloc(int size)\r\n        {\r\n            lock (this)\r\n            {\r\n                var count = __freelist.Count;\r\n                if (count > 0)\r\n                {\r\n                    var free = __freelist[count - 1];\r\n                    __freelist.RemoveAt(count - 1);\r\n                    free.Retain();\r\n                    return free;\r\n                }\r\n                return new ByteBuffer(size, _maxCapacity, this).Retain();\r\n            }\r\n        }\r\n\r\n        public void Recycle(ByteBuffer byteBuffer)\r\n        {\r\n            lock (this)\r\n            {\r\n                __freelist.Add(byteBuffer);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Buffer/ByteBufferThreadedPooledAllocator.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: dabf9d2354f8df040b1ab77d99e12b73\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Buffer/ByteBufferUnpooledAllocator.cs",
    "content": "﻿using System.Collections.Generic;\r\n\r\nnamespace QuickJS.IO\r\n{\r\n    public class ByteBufferUnpooledAllocator : IByteBufferAllocator\r\n    {\r\n        // 返回一个 ByteBuffer 对象, 大小至少为 size\r\n        public ByteBuffer Alloc(int size)\r\n        {\r\n            return new ByteBuffer(size, int.MaxValue, null);\r\n        }\r\n\r\n        public void Recycle(ByteBuffer byteBuffer)\r\n        {\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Buffer/ByteBufferUnpooledAllocator.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: a085ebc559675474b80da2b45e1dc2f2\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Buffer/ByteBufferWriter.cs",
    "content": "﻿using System;\r\nusing System.IO;\r\n\r\nnamespace QuickJS.IO\r\n{\r\n    public class ByteBufferWriter : Stream\r\n    {\r\n        private ByteBuffer _byteBuffer;\r\n\r\n        public ByteBufferWriter(ByteBuffer byteBuffer)\r\n        {\r\n            _byteBuffer = byteBuffer;\r\n        }\r\n\r\n        public override bool CanWrite { get { return true; } }\r\n\r\n        public override bool CanSeek { get { return true; } }\r\n\r\n        public override bool CanRead { get { return false; } }\r\n\r\n        public override long Position\r\n        {\r\n            get { return _byteBuffer.writerIndex; }\r\n            set { _byteBuffer.writerIndex = (int)value; }\r\n        }\r\n        public override long Length { get { return _byteBuffer.writerIndex; } }\r\n\r\n        public override void Flush() { }\r\n\r\n        public override int Read(byte[] buffer, int offset, int count)\r\n        {\r\n            throw new NotSupportedException();\r\n        }\r\n\r\n        public override int ReadByte()\r\n        {\r\n            throw new NotSupportedException();\r\n        }\r\n\r\n        public override long Seek(long offset, System.IO.SeekOrigin loc)\r\n        {\r\n            switch (loc)\r\n            {\r\n                case SeekOrigin.Begin: _byteBuffer.writerIndex = (int)offset; return _byteBuffer.writerIndex;\r\n                case SeekOrigin.Current: _byteBuffer.writerIndex += (int)offset; return _byteBuffer.writerIndex;\r\n                default: _byteBuffer.writerIndex -= (int)offset; return _byteBuffer.writerIndex;\r\n            }\r\n        }\r\n\r\n        public override void SetLength(long value)\r\n        {\r\n            throw new NotSupportedException();\r\n        }\r\n\r\n        public override void Write(byte[] src, int srcOffset, int count)\r\n        {\r\n            _byteBuffer.WriteBytes(src, srcOffset, count);\r\n        }\r\n\r\n        public override void WriteByte(byte value)\r\n        {\r\n            _byteBuffer.WriteByte(value);\r\n        }\r\n\r\n        protected override void Dispose(bool disposing)\r\n        {\r\n        }\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Buffer/ByteBufferWriter.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 5406917ba77f5644ba93400cfc3b47a3\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Buffer/IByteBufferAllocator.cs",
    "content": "using System.Collections.Generic;\r\n\r\nnamespace QuickJS.IO\r\n{\r\n    public interface IByteBufferAllocator\r\n    {\r\n        // 返回一个由对象池分配的 ByteBuffer 对象, 初始容量至少为 size\r\n        ByteBuffer Alloc(int size);\r\n\r\n        void Recycle(ByteBuffer byteBuffer);\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Buffer/IByteBufferAllocator.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 52b9246acce027b4581080d9c4cdbbda\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Buffer.meta",
    "content": "fileFormatVersion: 2\r\nguid: e05f9d2828de09d4f8429d7faed4da4b\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Diagnostics/Assert.cs",
    "content": "using System.Diagnostics;\r\n\r\nnamespace QuickJS.Diagnostics\r\n{\r\n    public static class Assert\r\n    {\r\n        /// <summary>\r\n        /// 发布期断言, 在定义为 JSB_RELEASE 时仅报错, 不暂停, 否则等价于 Debug 断言 \r\n        /// </summary>\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        [Conditional(\"JSB_RELEASE\")]\r\n        public static void Never(string message = \"\")\r\n        {\r\n            var stackTrace = new StackTrace(1, true);\r\n            var text = \"[ASSERT_FAILED][NEVER] \";\r\n\r\n            if (!string.IsNullOrEmpty(message))\r\n            {\r\n                text += message + \"\\n\";\r\n            }\r\n            text += stackTrace.ToString();\r\n\r\n#if JSB_DEBUG\r\n            Logger.Default.Fatal(text);\r\n#else \r\n            Logger.Default.Error(text);\r\n#endif\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        [Conditional(\"JSB_RELEASE\")]\r\n        public static void Never(string fmt, params object[] args)\r\n        {\r\n            Never(string.Format(fmt, args));\r\n        }\r\n\r\n        /// <summary>\r\n        /// 发布期断言, 在定义为 JSB_RELEASE 时仅报错, 不暂停, 否则等价于 Debug 断言 \r\n        /// </summary>\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        [Conditional(\"JSB_RELEASE\")]\r\n        public static void Release(bool condition, string message = \"\")\r\n        {\r\n            if (condition)\r\n            {\r\n                return;\r\n            }\r\n            var stackTrace = new StackTrace(1, true);\r\n            var text = \"[ASSERT_FAILED][RELEASE] \";\r\n\r\n            if (!string.IsNullOrEmpty(message))\r\n            {\r\n                text += message + \"\\n\";\r\n            }\r\n            text += stackTrace.ToString();\r\n\r\n#if JSB_DEBUG\r\n            Logger.Default.Fatal(text);\r\n#else \r\n            Logger.Default.Error(text);\r\n#endif\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        [Conditional(\"JSB_RELEASE\")]\r\n        public static void Release(bool condition, string fmt, params object[] args)\r\n        {\r\n            if (condition)\r\n            {\r\n                return;\r\n            }\r\n            Release(false, string.Format(fmt, args));\r\n        }\r\n\r\n        /// <summary>\r\n        /// 调试期断言, 触发时将暂停编辑器运行\r\n        /// </summary>\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public static void Debug(bool condition, string message = \"\")\r\n        {\r\n            if (condition)\r\n            {\r\n                return;\r\n            }\r\n            var stackTrace = new StackTrace(1, true);\r\n            var text = \"[ASSERT_FAILED][DEBUG] \";\r\n\r\n            if (!string.IsNullOrEmpty(message))\r\n            {\r\n                text += message + \"\\n\";\r\n            }\r\n            text += stackTrace.ToString();\r\n\r\n            Logger.Default.Fatal(text);\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public static void Debug(bool condition, string fmt, params object[] args)\r\n        {\r\n            if (condition)\r\n            {\r\n                return;\r\n            }\r\n            Debug(false, string.Format(fmt, args));\r\n        }\r\n\r\n        public static bool Ensure(bool condition, string message = \"\")\r\n        {\r\n            if (condition)\r\n            {\r\n                return true;\r\n            }\r\n\r\n#if JSB_DEBUG\r\n            var stackTrace = new StackTrace(1, true);\r\n            var text = \"[ASSERT_FAILED] \";\r\n\r\n            if (!string.IsNullOrEmpty(message))\r\n            {\r\n                text += message + \"\\n\";\r\n            }\r\n            text += stackTrace.ToString();\r\n\r\n            Logger.Default.Fatal(text);\r\n#endif\r\n            return false;\r\n        }\r\n\r\n        public static bool Ensure(bool condition, string fmt, params object[] args)\r\n        {\r\n            if (condition)\r\n            {\r\n                return true;\r\n            }\r\n            return Ensure(false, string.Format(fmt, args));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Diagnostics/Assert.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 2e68fdd03c139e34182f91f63e794ed0\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Diagnostics/LogChannel.cs",
    "content": "using System;\r\nusing System.Diagnostics;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Diagnostics\r\n{\r\n    public sealed class LogChannel\r\n    {\r\n        private bool _enabled = true;\r\n        private string _name = string.Empty;\r\n\r\n        public bool enabled { get => _enabled; set => _enabled = value; }\r\n\r\n        public string name => _name;\r\n\r\n        public LogChannel()\r\n        {\r\n            _name = \"Default\";\r\n        }\r\n\r\n        public LogChannel(string name)\r\n        {\r\n            _name = string.IsNullOrEmpty(name) ? \"Default\" : name;\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public void VeryVerbose(string text)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(ELogSeverity.VeryVerbose, _name, text);\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public void VeryVerbose(object obj)\r\n        {\r\n            if (!_enabled || obj == null) return;\r\n            Logger.Write(ELogSeverity.VeryVerbose, _name, obj.ToString());\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public void VeryVerbose(string fmt, params object[] args)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(ELogSeverity.VeryVerbose, _name, fmt, args);\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public void Verbose(string text)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(ELogSeverity.Verbose, _name, text);\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public void Verbose(object obj)\r\n        {\r\n            if (!_enabled || obj == null) return;\r\n            Logger.Write(ELogSeverity.Verbose, _name, obj.ToString());\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public void Verbose(string fmt, params object[] args)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(ELogSeverity.Verbose, _name, fmt, args);\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public void Debug(string text)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(ELogSeverity.Debug, _name, text);\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public void Debug(object obj)\r\n        {\r\n            if (!_enabled || obj == null) return;\r\n            Logger.Write(ELogSeverity.Debug, _name, obj.ToString());\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public void Debug(string fmt, params object[] args)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(ELogSeverity.Debug, _name, fmt, args);\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public void Info(string text)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(ELogSeverity.Info, _name, text);\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public void Info(object obj)\r\n        {\r\n            if (!_enabled || obj == null) return;\r\n            Logger.Write(ELogSeverity.Info, _name, obj.ToString());\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public void Info(string fmt, params object[] args)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(ELogSeverity.Info, _name, fmt, args);\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public void Warning(string text)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(ELogSeverity.Warning, _name, text);\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public void Warning(object obj)\r\n        {\r\n            if (!_enabled || obj == null) return;\r\n            Logger.Write(ELogSeverity.Warning, _name, obj.ToString());\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        public void Warning(string fmt, params object[] args)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(ELogSeverity.Warning, _name, fmt, args);\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        [Conditional(\"JSB_RELEASE\")]\r\n        public void Error(string text)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(ELogSeverity.Error, _name, text);\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        [Conditional(\"JSB_RELEASE\")]\r\n        public void Error(object obj)\r\n        {\r\n            if (!_enabled || obj == null) return;\r\n            Logger.Write(ELogSeverity.Error, _name, obj.ToString());\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        [Conditional(\"JSB_RELEASE\")]\r\n        public void Error(string fmt, params object[] args)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(ELogSeverity.Error, _name, fmt, args);\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        [Conditional(\"JSB_RELEASE\")]\r\n        public void Fatal(string text)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(ELogSeverity.Fatal, _name, text);\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        [Conditional(\"JSB_RELEASE\")]\r\n        public void Fatal(object obj)\r\n        {\r\n            if (!_enabled || obj == null) return;\r\n            Logger.Write(ELogSeverity.Fatal, _name, obj.ToString());\r\n        }\r\n\r\n        [Conditional(\"JSB_DEBUG\")]\r\n        [Conditional(\"JSB_RELEASE\")]\r\n        public void Fatal(string fmt, params object[] args)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(ELogSeverity.Fatal, _name, fmt, args);\r\n        }\r\n\r\n        public void Write(ELogSeverity severity, object obj)\r\n        {\r\n            if (!_enabled || obj == null) return;\r\n            Logger.Write(severity, _name, obj.ToString());\r\n        }\r\n\r\n        public void Write(ELogSeverity severity, string fmt, params object[] args)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(severity, _name, fmt, args);\r\n        }\r\n\r\n        public void Exception(Exception exception)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(ELogSeverity.Error, _name, exception.ToString());\r\n        }\r\n\r\n        public void Exception(string description, Exception exception)\r\n        {\r\n            if (!_enabled) return;\r\n            Logger.Write(ELogSeverity.Error, _name, \"{0}\\n{1}\", description, exception);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Diagnostics/LogChannel.cs.meta",
    "content": "fileFormatVersion: 2\nguid: e9ff53e37ea7ea44faea6a79973ea253\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Diagnostics/LogSeverity.cs",
    "content": "using System;\n\nnamespace QuickJS.Diagnostics\n{\n    [Flags]\n    public enum ELogSeverity\n    {\n        VeryVerbose = 1,\n        Verbose = 2,\n        Debug = 4,\n        Info = 8,\n        Warning = 16,\n        Error = 32,\n        Fatal = 64,\n        Assert = 128, \n\n        All = VeryVerbose | Verbose | Debug | Info | Warning | Error | Fatal | Assert,\n    }\n}\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Diagnostics/LogSeverity.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 3fbee40b52bd64d0d97cc50ec20ccd2f\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Diagnostics/LogWriter.cs",
    "content": "using System;\n\nnamespace QuickJS.Diagnostics\n{\n    public interface ILogWriter\n    {\n        void Write(ELogSeverity severity, string channel, string text);\n        void Write(ELogSeverity severity, string channel, string fmt, object[] args);\n    }\n\n    public class DefaultLogWriter : ILogWriter\n    {\n        public void Write(ELogSeverity severity, string channel, string text)\n        {\n            var content = string.Format(\"[{0}] {1}\", channel, text);\n\n#if JSB_UNITYLESS\n            switch (severity)\n            {\n                case ELogSeverity.VeryVerbose: System.Console.WriteLine(\"[VERY ] \" + content); break;\n                case ELogSeverity.Verbose:     System.Console.WriteLine(\"[VERB ] \" + content); break;\n                case ELogSeverity.Debug:       System.Console.WriteLine(\"[DEBUG] \" + content); break;\n                case ELogSeverity.Info:        System.Console.WriteLine(\"[INFO ] \" + content); break;\n                case ELogSeverity.Warning:     System.Console.WriteLine(\"[WARN ] \" + content); break;\n                case ELogSeverity.Fatal:       System.Console.WriteLine(\"[FATAL] \" + content); break;\n                case ELogSeverity.Error:\n                default:                       System.Console.WriteLine(\"[ERROR  ] \" + content); break;\n            }\n#else\n            switch (severity)\n            {\n                case ELogSeverity.VeryVerbose:\n                case ELogSeverity.Verbose:\n                case ELogSeverity.Debug:\n                case ELogSeverity.Info: UnityEngine.Debug.Log(content); break;\n                case ELogSeverity.Warning: UnityEngine.Debug.LogWarning(content); break;\n                case ELogSeverity.Fatal: UnityEngine.Debug.LogError(content); UnityEngine.Debug.Break(); break;\n                case ELogSeverity.Error:\n                default: UnityEngine.Debug.LogError(content); break;\n            }\n#endif\n        }\n\n        public void Write(ELogSeverity severity, string channel, string fmt, object[] args)\n        {\n            Write(severity, channel, string.Format(fmt, args));\n        }\n    }\n}\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Diagnostics/LogWriter.cs.meta",
    "content": "fileFormatVersion: 2\nguid: cbacb2a6e24021e499c639fde3239e79\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Diagnostics/Logger.cs",
    "content": "using System;\r\nusing System.Diagnostics;\r\nusing System.Collections.Generic;\r\nusing System.Threading;\r\n\r\nnamespace QuickJS.Diagnostics\r\n{\r\n    public static class Logger\r\n    {\r\n        public static LogChannel Default => GetChannel(\"Default\");\r\n        public static LogChannel Binding => GetChannel(\"Binding\");\r\n        public static LogChannel IO => GetChannel(\"IO\");\r\n        public static LogChannel Scripting => GetChannel(\"Scripting\");\r\n\r\n        private static ReaderWriterLockSlim _channelsLock = new ReaderWriterLockSlim();\r\n        private static ELogSeverity _severity = ELogSeverity.All;\r\n        private static Dictionary<string, LogChannel> _channels = new Dictionary<string, LogChannel>();\r\n        private static ILogWriter _writer = new DefaultLogWriter();\r\n\r\n        public static ILogWriter writer { get => _writer; set => _writer = value; }\r\n\r\n        public static bool GetSeverityEnabled(ELogSeverity severity) => (_severity | severity) != 0;\r\n\r\n        public static void SetSeverityEnabled(ELogSeverity severity, bool state) => _severity = state ? _severity | severity : _severity & ~severity;\r\n\r\n        public static LogChannel GetChannel<T>()\r\n        {\r\n            return GetChannel(typeof(T).Name);\r\n        }\r\n\r\n        public static LogChannel[] GetAllChannels()\r\n        {\r\n            _channelsLock.EnterReadLock();\r\n            var buff = new LogChannel[_channels.Count];\r\n            _channels.Values.CopyTo(buff, 0);\r\n            _channelsLock.ExitReadLock();\r\n            return buff;\r\n        }\r\n\r\n        public static LogChannel GetChannel(string name)\r\n        {\r\n            if (string.IsNullOrEmpty(name)) return Default;\r\n            try\r\n            {\r\n                _channelsLock.EnterUpgradeableReadLock();\r\n                if (_channels.TryGetValue(name, out var channel))\r\n                {\r\n                    return channel;\r\n                }\r\n\r\n                channel = new LogChannel(name);\r\n                _channelsLock.EnterWriteLock();\r\n                _channels.Add(name, channel);\r\n                _channelsLock.ExitWriteLock();\r\n                return channel;\r\n            }\r\n            finally\r\n            {\r\n                _channelsLock.ExitUpgradeableReadLock();\r\n            }\r\n        }\r\n\r\n        public static void Write(ELogSeverity severity, string channel, string text)\r\n        {\r\n            if ((severity & _severity) == 0) return;\r\n            var target = _writer;\r\n            target?.Write(severity, channel, text);\r\n        }\r\n\r\n        public static void Write(ELogSeverity severity, string channel, string fmt, params object[] args)\r\n        {\r\n            if ((severity & _severity) == 0) return;\r\n            var target = _writer;\r\n            target?.Write(severity, channel, fmt, args);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Diagnostics/Logger.cs.meta",
    "content": "fileFormatVersion: 2\nguid: c3ea255186136d34e8169a40bb6b4605\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Diagnostics.meta",
    "content": "fileFormatVersion: 2\nguid: cb957218180041948ac3e9a573f8f650\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Errors/InaccessibleMemberException.cs",
    "content": "using System;\n\nnamespace QuickJS.Errors\n{\n    public class InaccessibleMemberException : Exception\n    {\n        private string _memberName;\n\n        public string name { get { return _memberName; } }\n\n        public InaccessibleMemberException(string memberName)\n        : base(\"inaccessible due to its protection level\")\n        {\n            _memberName = memberName;\n        }\n\n        public override string ToString()\n        {\n            if (string.IsNullOrEmpty(_memberName))\n            {\n                return base.ToString();\n            }\n            return string.Format(\"{0}: {1}\", Message, _memberName);\n        }\n    }\n}\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Errors/InaccessibleMemberException.cs.meta",
    "content": "fileFormatVersion: 2\nguid: eca8d02101a58cc43bd305d481dd3fcb\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Errors/JSException.cs",
    "content": "using System;\n\nnamespace QuickJS.Errors\n{\n    public class JSException : Exception\n    {\n        private string _fileName;\n\n        public JSException(string message, string fileName)\n        : base(message)\n        {\n            _fileName = fileName;\n        }\n\n        public JSException(string message)\n        : base(message)\n        {\n        }\n\n        public override string ToString()\n        {\n            var baseStr = base.ToString();\n            return string.IsNullOrEmpty(_fileName) \n                ? baseStr\n                : $\"{baseStr} ({_fileName})\";\n        }\n    }\n}\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Errors/JSException.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 88c8f9390aa758d4c940649f2ba3b244\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Errors/NoSuitableMethodException.cs",
    "content": "using System;\n\nnamespace QuickJS.Errors\n{\n    public class NoSuitableMethodException : Exception\n    {\n        private int _argc;\n        private string _methodName;\n\n        public int argc { get { return _argc; } }\n\n        public string name { get { return _methodName; } }\n\n        public NoSuitableMethodException(string methodName, int argc)\n        : base(\"no suitable method to call\")\n        {\n            _argc = argc;\n            _methodName = methodName;\n        }\n\n        public override string ToString()\n        {\n            return string.Format(\"{0}: {1} [{2}]\", Message, _methodName, _argc);\n        }\n    }\n}\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Errors/NoSuitableMethodException.cs.meta",
    "content": "fileFormatVersion: 2\nguid: bb892e4afcac6154cab1fc07203ee7ff\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Errors/ParameterException.cs",
    "content": "using System;\n\nnamespace QuickJS.Errors\n{\n    public class ParameterException : Exception\n    {\n        /// <summary>\n        /// 调用类型\n        /// </summary>\n        public Type thisType { get; set; }\n\n        /// <summary>\n        /// 调用的方法名\n        /// </summary>\n        public string methodName { get; set; }\n\n        /// <summary>\n        /// 期望参数类型\n        /// </summary>\n        public Type pType { get; set; }\n\n        /// <summary>\n        /// 参数位置\n        /// </summary>\n        public int pIndex { get; set; }\n\n        public ParameterException(string message, Type pType, int pIndex)\n        : base(message)\n        {\n            this.pType = pType;\n            this.pIndex = pIndex;\n        }\n\n        public ParameterException(Type pType, int pIndex)\n        : base(\"parameter error\")\n        {\n            this.pType = pType;\n            this.pIndex = pIndex;\n        }\n\n        public ParameterException(Type caller, string method, Type pType, int pIndex)\n        : base(\"parameter error\")\n        {\n            this.thisType = caller;\n            this.methodName = method;\n            this.pType = pType;\n            this.pIndex = pIndex;\n        }\n\n        public override string ToString()\n        {\n            var callInfo = \"\";\n            if (thisType != null)\n            {\n                callInfo += thisType.Name;\n                if (methodName != null)\n                {\n                    callInfo += \".\" + methodName;\n                }\n                callInfo += \" \";\n            }\n\n            return string.Format(\"{0} [{1}expect {2} at {3}]\", Message, callInfo, pType, pIndex);\n        }\n    }\n}\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Errors/ParameterException.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 1489dc915770d9e4682c7124dffca8c8\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Errors/PropertySetterException.cs",
    "content": "﻿using System;\n\nnamespace QuickJS.Errors\n{\n    public class PropertySetterException : Exception\n    {\n    }\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Errors/PropertySetterException.cs.meta",
    "content": "﻿fileFormatVersion: 2\nguid: 0c3d23107f944b5eb0ce18b59b80ec37\ntimeCreated: 1591615325"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Errors/ThisBoundException.cs",
    "content": "using System;\n\nnamespace QuickJS.Errors\n{\n    public class ThisBoundException : Exception\n    {\n    }\n}\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Errors/ThisBoundException.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 30cd9564669426741a9a62d9c705267f\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Errors/UnexpectedException.cs",
    "content": "using System;\n\nnamespace QuickJS.Errors\n{\n    public class UnexpectedException : Exception\n    {\n        private string _text;\n\n        public UnexpectedException(string text, string message)\n        : base(message)\n        {\n            _text = text;\n        }\n\n        public override string ToString()\n        {\n            return string.Format(\"{0}: {1}\", Message, _text);\n        }\n    }\n}\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Errors/UnexpectedException.cs.meta",
    "content": "fileFormatVersion: 2\nguid: dc6573ce787ff5f4eb03cd9338770c98\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Errors.meta",
    "content": "fileFormatVersion: 2\nguid: 5208edcd72cea3a479da0def64c88471\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Experimental/IJSApiBridge.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Experimental\r\n{\r\n    using QuickJS.Native;\r\n\r\n    /// <summary>\r\n    /// TODO\r\n    /// NOTE: should never throw any C# exception\r\n    /// </summary>\r\n    public interface IJSApiBridge\r\n    {\r\n        JSPayloadHeader GetPayloadHeader(ScriptContext context, JSValue val);\r\n\r\n        JSValue NewBridgeObject(ScriptContext context, object o, JSValue proto);\r\n    }\r\n\r\n    public class DefaultJSApiBridgeImpl : IJSApiBridge\r\n    {\r\n        public JSPayloadHeader GetPayloadHeader(ScriptContext context, JSValue val)\r\n        {\r\n            return JSApi.jsb_get_payload_header(context, val);\r\n        }\r\n\r\n        public JSValue NewBridgeObject(ScriptContext context, object o, JSValue proto)\r\n        {\r\n            var cache = context.GetObjectCache();\r\n            var object_id = cache.AddObject(o, false);\r\n            var val = JSApi.jsb_new_bridge_object(context, proto, object_id);\r\n\r\n            if (val.IsException())\r\n            {\r\n                cache.RemoveObject(object_id);\r\n            }\r\n            else\r\n            {\r\n                cache.AddJSValue(o, val);\r\n            }\r\n            return val;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Experimental/IJSApiBridge.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 7feeda07bc0f8d34e920317871428955\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Experimental.meta",
    "content": "fileFormatVersion: 2\nguid: 9b21e85e64c76424187807436da80d46\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/GCObject.cs",
    "content": "using System;\nusing QuickJS.Native;\n\nnamespace QuickJS\n{\n    public abstract class GCObject\n    {\n        private ScriptContext _context;\n\n        public JSContext ctx => _context;\n\n        public GCObject(ScriptContext context)\n        {\n            _context = context;\n        }\n\n        ~GCObject()\n        {\n            Dispose(false);\n        }\n\n        // should only be invoked on the script runtime thread\n        public void Dispose()\n        {\n            Dispose(true);\n            GC.SuppressFinalize(this);\n        }\n\n        // should only be invoked on the script runtime thread or C# gc thread (from C# finalizer)\n        private void Dispose(bool bManaged)\n        {\n            var context = _context;\n            if (context != null)\n            {\n                _context = null;\n                OnDisposing(context);\n            }\n        }\n\n        public static implicit operator JSContext(GCObject value)\n        {\n            return value != null ? value._context : JSContext.Null;\n        }\n\n        public ScriptContext GetContext()\n        {\n            return _context;\n        }\n\n        protected abstract void OnDisposing(ScriptContext context);\n    }\n}\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/GCObject.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 7db87b8dbffde4003a92f81cbea38975\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/JSFunction.cs",
    "content": "using System;\r\n\r\nnamespace QuickJS\r\n{\r\n    // Dummy Type for Function (js)\r\n    public class JSFunction {}\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/JSFunction.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 0414ea1ef9870644a9948a55eb3dac9e\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/JSNative.cs",
    "content": "using System;\r\n\r\nnamespace QuickJS\r\n{\r\n    using Native;\r\n    using JSValueConst = Native.JSValue;\r\n    using JS_BOOL = Int32;\r\n\r\n    /// <summary>\r\n    /// A thin layer wrapping the raw JSApi which depends on some methods from jsb.core module.\r\n    /// the JSApi will be isolated from jsb.core module later.\r\n    /// </summary>\r\n    public static class JSNative\r\n    {\r\n        [MonoPInvokeCallback(typeof(JSCFunctionMagic))]\r\n        public static JSValue class_private_ctor(JSContext ctx, JSValue new_target, int argc, JSValue[] argv, int magic)\r\n        {\r\n            return ctx.ThrowInternalError(\"cant call constructor on this type\");\r\n        }\r\n\r\n        public static bool CheckFuncProperty(this JSValue self, ScriptContext context, string name)\r\n        {\r\n            if (context == null)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            var ctx = (JSContext)context;\r\n            var prop = JSApi.JS_GetProperty(ctx, self, context.GetAtom(name));\r\n            var res = JSApi.JS_IsFunction(context, prop) == 1;\r\n            \r\n            JSApi.JS_FreeValue(ctx, prop);\r\n            return res;\r\n        }\r\n\r\n        public static void print_exception(this JSContext ctx, string title = \"\")\r\n        {\r\n            var ex = JSApi.JS_GetException(ctx);\r\n\r\n            try\r\n            {\r\n                var err_fileName = JSApi.JS_GetProperty(ctx, ex, JSApi.JS_ATOM_fileName);\r\n                var err_lineNumber = JSApi.JS_GetProperty(ctx, ex, JSApi.JS_ATOM_lineNumber);\r\n                var err_message = JSApi.JS_GetProperty(ctx, ex, JSApi.JS_ATOM_message);\r\n                var err_stack = JSApi.JS_GetProperty(ctx, ex, JSApi.JS_ATOM_stack);\r\n\r\n                try\r\n                {\r\n                    var fileName = err_fileName.IsNullish() ? \"native\" : JSApi.GetString(ctx, err_fileName);\r\n                    var lineNumber = err_lineNumber.IsNullish() ? null : JSApi.GetString(ctx, err_lineNumber);\r\n                    var message = JSApi.GetString(ctx, err_message);\r\n                    var stack = JSApi.GetString(ctx, err_stack);\r\n\r\n                    if (string.IsNullOrEmpty(lineNumber))\r\n                    {\r\n                        if (string.IsNullOrEmpty(stack))\r\n                        {\r\n                            Diagnostics.Logger.Default.Error(\"[{0}] {1} {2}\",\r\n                                fileName, title, message);\r\n                        }\r\n                        else\r\n                        {\r\n                            Diagnostics.Logger.Default.Error(\"[{0}] {1} {2}\\nJavascript stack:\\n{3}\",\r\n                                fileName, title, message, stack);\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        if (string.IsNullOrEmpty(stack))\r\n                        {\r\n                            Diagnostics.Logger.Default.Error(\"[{0}:{1}] {2} {3}\",\r\n                            fileName, lineNumber, title, message);\r\n                        }\r\n                        else\r\n                        {\r\n                            Diagnostics.Logger.Default.Error(\"[{0}:{1}] {2} {3}\\nJavascript stack:\\n{4}\",\r\n                                fileName, lineNumber, title, message, stack);\r\n                        }\r\n                    }\r\n                }\r\n                finally\r\n                {\r\n                    JSApi.JS_FreeValue(ctx, err_fileName);\r\n                    JSApi.JS_FreeValue(ctx, err_lineNumber);\r\n                    JSApi.JS_FreeValue(ctx, err_message);\r\n                    JSApi.JS_FreeValue(ctx, err_stack);\r\n                }\r\n            }\r\n            finally\r\n            {\r\n                JSApi.JS_FreeValue(ctx, ex);\r\n            }\r\n        }\r\n\r\n        public static unsafe JSValue NewString(this JSContext ctx, string str)\r\n        {\r\n            if (str == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n\r\n            if (str.Length == 0)\r\n            {\r\n                return JSApi.JSB_NewEmptyString(ctx);\r\n            }\r\n\r\n            var bytes = Utils.TextUtils.GetBytes(str);\r\n            fixed (byte* buf = bytes)\r\n            {\r\n                return JSApi.JS_NewStringLen(ctx, buf, bytes.Length);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get a cstring allocated on the heap (will not be automatically collected by GC)\r\n        /// </summary>\r\n        public static unsafe IntPtr NewCString(this JSContext ctx, string str)\r\n        {\r\n            var bytes = Utils.TextUtils.GetNullTerminatedBytes(str);\r\n            fixed (byte* ptr = bytes)\r\n            {\r\n                return JSApi.js_strndup(ctx, ptr, bytes.Length - 1);\r\n            }\r\n        }\r\n\r\n        public static unsafe JSValue ThrowException(this JSContext ctx, Exception exception)\r\n        {\r\n            return ThrowInternalError(ctx, exception.ToString());\r\n        }\r\n\r\n        public static unsafe JSValue ThrowTypeError(this JSContext ctx, string message)\r\n        {\r\n            var bytes = Utils.TextUtils.GetNullTerminatedBytes(message);\r\n            fixed (byte* msg = bytes)\r\n            {\r\n                return JSApi.JSB_ThrowTypeError(ctx, msg);\r\n            }\r\n        }\r\n\r\n        public static unsafe JSValue ThrowInternalError(this JSContext ctx, string message)\r\n        {\r\n            if (string.IsNullOrEmpty(message))\r\n            {\r\n                return JSApi.JSB_ThrowInternalError(ctx, (byte*)0);\r\n            }\r\n\r\n            var bytes = Utils.TextUtils.GetBytes(message);\r\n            fixed (byte* buf = bytes)\r\n            {\r\n                return JSApi.JSB_ThrowError(ctx, buf, bytes.Length);\r\n            }\r\n        }\r\n\r\n        public static unsafe JSValue ThrowRangeError(this JSContext ctx, string message)\r\n        {\r\n            var bytes = Utils.TextUtils.GetNullTerminatedBytes(message);\r\n            fixed (byte* msg = bytes)\r\n            {\r\n                return JSApi.JSB_ThrowRangeError(ctx, msg);\r\n            }\r\n        }\r\n\r\n        public static unsafe JSValue ThrowReferenceError(this JSContext ctx, string message)\r\n        {\r\n            var bytes = Utils.TextUtils.GetNullTerminatedBytes(message);\r\n            fixed (byte* msg = bytes)\r\n            {\r\n                return JSApi.JSB_ThrowReferenceError(ctx, msg);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSHostPromiseRejectionTracker))]\r\n        public static void PromiseRejectionTracker(JSContext ctx, JSValueConst promise, JSValueConst reason, JS_BOOL is_handled, IntPtr opaque)\r\n        {\r\n            if (is_handled != 1)\r\n            {\r\n                var reasonStr = JSApi.GetString(ctx, reason);\r\n                var is_error = JSApi.JS_IsError(ctx, reason);\r\n\r\n                do\r\n                {\r\n                    if (is_error == 1)\r\n                    {\r\n                        var val = JSApi.JS_GetPropertyStr(ctx, reason, \"stack\");\r\n                        if (!JSApi.JS_IsUndefined(val))\r\n                        {\r\n                            var stack = JSApi.GetString(ctx, val);\r\n                            JSApi.JS_FreeValue(ctx, val);\r\n                            Diagnostics.Logger.Default.Error(\"Unhandled promise rejection: {0}\\n{1}\", reasonStr, stack);\r\n                            return;\r\n                        }\r\n                        JSApi.JS_FreeValue(ctx, val);\r\n                    }\r\n                    Diagnostics.Logger.Default.Error(\"Unhandled promise rejection: {0}\", reasonStr);\r\n                } while (false);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/JSNative.cs.meta",
    "content": "fileFormatVersion: 2\nguid: aaab0feecda516a4892e9928426c6973\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/JSWorker.cs",
    "content": "using System;\r\nusing System.Threading;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS\r\n{\r\n    using QuickJS.IO;\r\n    using QuickJS.Utils;\r\n    using QuickJS.Native;\r\n    using QuickJS.Binding;\r\n    using QuickJS.Errors;\r\n\r\n    public class JSWorker : Values, IDisposable, IObjectCollectionEntry\r\n    {\r\n        private class JSWorkerArgs\r\n        {\r\n            // for worker only \r\n            public JSWorker worker;\r\n            public IO.ByteBuffer buffer;\r\n        }\r\n\r\n        private JSValue _self; // 在 main thread 中的 worker 自身\r\n\r\n        private Thread _thread;\r\n        private ScriptRuntime _parentRuntime;\r\n        private ObjectCollection.Handle _handle;\r\n        private ScriptRuntime _runtime;\r\n        private Queue<IO.ByteBuffer> _inbox = new Queue<ByteBuffer>();\r\n\r\n        private JSWorker()\r\n        {\r\n        }\r\n\r\n#if JSB_DEBUG\r\n        ~JSWorker()\r\n        {\r\n            if (_inbox.Count != 0)\r\n            {\r\n                Diagnostics.Logger.Default.Error(\"worker: not cleaned up\");\r\n            }\r\n        }\r\n#endif\r\n\r\n        private void Cleanup()\r\n        {\r\n            lock (_inbox)\r\n            {\r\n                while (_inbox.Count != 0)\r\n                {\r\n                    var buf = _inbox.Dequeue();\r\n                    if (buf == null)\r\n                    {\r\n                        break;\r\n                    }\r\n                    buf.Release();\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// should only be called by js object finalizer in main thread\r\n        /// </summary>\r\n        public void Dispose()\r\n        {\r\n            Cleanup();\r\n        }\r\n\r\n        #region IObjectCollectionEntry implementation\r\n        public void OnCollectionReleased()\r\n        {\r\n            // callback from main thread\r\n            if (!_self.IsUndefined())\r\n            {\r\n                _parentRuntime.FreeValue(_self);\r\n                _self = JSApi.JS_UNDEFINED;\r\n            }\r\n            _runtime.Shutdown();\r\n        }\r\n        #endregion\r\n\r\n        private void Start(JSContext ctx, JSValue value, string scriptPath)\r\n        {\r\n            var parent = ScriptEngine.GetRuntime(ctx);\r\n            var runtime = parent.CreateWorker();\r\n\r\n            if (runtime == null)\r\n            {\r\n                throw new NullReferenceException();\r\n            }\r\n\r\n            _self = JSApi.JS_DupValue(ctx, value);\r\n            _parentRuntime = parent;\r\n            _parentRuntime.AddManagedObject(this, out _handle);\r\n            _runtime = runtime;\r\n            RegisterGlobalObjects();\r\n            _runtime.EvalMain(scriptPath);\r\n            _thread = new Thread(new ThreadStart(Run));\r\n            _thread.Priority = ThreadPriority.Lowest;\r\n            _thread.IsBackground = true;\r\n            _thread.Start();\r\n        }\r\n\r\n        private void RegisterGlobalObjects()\r\n        {\r\n            var context = _runtime.GetMainContext();\r\n            var db = context.GetTypeDB();\r\n            var globalObject = context.GetGlobalObject();\r\n            {\r\n                var propName = context.GetAtom(\"postMessage\");\r\n                var postMessage = db.NewDynamicMethod(propName, _js_self_postMessage);\r\n                JSApi.JS_DefinePropertyValue(context, globalObject, propName, postMessage);\r\n            }\r\n            {\r\n                var propName = context.GetAtom(\"onmessage\");\r\n                JSApi.JS_DefinePropertyValue(context, globalObject, propName, JSApi.JS_NULL);\r\n            }\r\n            JSApi.JS_FreeValue(context, globalObject);\r\n        }\r\n\r\n        private void Run()\r\n        {\r\n            var tick = Environment.TickCount;\r\n            var list = new List<IO.ByteBuffer>();\r\n            var context = _runtime.GetMainContext();\r\n\r\n            while (_runtime.isRunning)\r\n            {\r\n                lock (_inbox)\r\n                {\r\n                    list.AddRange(_inbox);\r\n                    _inbox.Clear();\r\n                }\r\n\r\n                if (list.Count == 0)\r\n                {\r\n                    Thread.Yield();\r\n                }\r\n                else\r\n                {\r\n                    JSContext ctx = context;\r\n                    var globalObject = context.GetGlobalObject();\r\n                    var onmessage = JSApi.JS_GetPropertyStr(context, globalObject, \"onmessage\");\r\n                    var callable = JSApi.JS_IsFunction(ctx, onmessage) == 1;\r\n\r\n                    for (int i = 0, count = list.Count; i < count; i++)\r\n                    {\r\n                        var byteBuffer = list[i];\r\n\r\n                        if (callable)\r\n                        {\r\n                            unsafe\r\n                            {\r\n                                JSValue data;\r\n                                fixed (byte* buf = byteBuffer.data)\r\n                                {\r\n                                    data = JSApi.JSB_Deserialize(ctx, buf, byteBuffer.readableBytes);\r\n                                }\r\n\r\n                                do\r\n                                {\r\n                                    if (!data.IsException())\r\n                                    {\r\n                                        var evt = JSApi.JS_NewObject(ctx);\r\n                                        if (!evt.IsException())\r\n                                        {\r\n                                            JSApi.JS_SetProperty(ctx, evt, context.GetAtom(\"data\"), data);\r\n                                            var argv = stackalloc JSValue[1] { evt };\r\n                                            var rval = JSApi.JS_Call(ctx, onmessage, globalObject, 1, argv);\r\n                                            JSApi.JS_FreeValue(ctx, rval);\r\n                                            JSApi.JS_FreeValue(ctx, evt);\r\n                                            break;\r\n                                        }\r\n                                        else\r\n                                        {\r\n                                            JSApi.JS_FreeValue(ctx, data);\r\n                                        }\r\n                                    }\r\n\r\n                                    var exceptionString = ctx.GetExceptionString();\r\n                                    Diagnostics.Logger.Default.Error(exceptionString);\r\n                                } while (false);\r\n                            }\r\n                        }\r\n                        byteBuffer.Release();\r\n                    }\r\n                    JSApi.JS_FreeValue(ctx, onmessage);\r\n                    JSApi.JS_FreeValue(ctx, globalObject);\r\n                    list.Clear();\r\n                }\r\n\r\n                var now = Environment.TickCount;\r\n                if (now < tick)\r\n                {\r\n                    _runtime.Update((now - int.MinValue) + (int.MaxValue - tick));\r\n                }\r\n                else\r\n                {\r\n                    _runtime.Update(now - tick);\r\n                }\r\n                tick = now;\r\n            }\r\n\r\n            _runtime.Destroy();\r\n        }\r\n\r\n        /// <summary>\r\n        /// master 处理 worker 发送的消息 (在master线程回调)\r\n        /// </summary>\r\n        private static unsafe void _MasterOnMessage(ScriptRuntime runtime, object cbArgs, JSValue cbValue)\r\n        {\r\n            var args = (JSWorkerArgs)cbArgs;\r\n            var buffer = args.buffer;\r\n\r\n            try\r\n            {\r\n                var worker = args.worker;\r\n                if (worker._runtime.isRunning && worker._parentRuntime.isRunning)\r\n                {\r\n                    var context = runtime.GetMainContext();\r\n                    var ctx = (JSContext)context;\r\n                    var onmessage = JSApi.JS_GetProperty(ctx, worker._self, context.GetAtom(\"onmessage\"));\r\n                    if (onmessage.IsException())\r\n                    {\r\n                        var exceptionString = ctx.GetExceptionString();\r\n                        Diagnostics.Logger.Default.Error(exceptionString);\r\n                    }\r\n                    else\r\n                    {\r\n                        if (JSApi.JS_IsFunction(ctx, onmessage) == 1)\r\n                        {\r\n                            // read object => jsvalue\r\n                            JSValue data;\r\n                            fixed (byte* buf = buffer.data)\r\n                            {\r\n                                data = JSApi.JSB_Deserialize(ctx, buf, buffer.readableBytes);\r\n                            }\r\n\r\n                            do\r\n                            {\r\n                                if (!data.IsException())\r\n                                {\r\n                                    var evt = JSApi.JS_NewObject(ctx);\r\n                                    if (!evt.IsException())\r\n                                    {\r\n                                        JSApi.JS_SetProperty(ctx, evt, context.GetAtom(\"data\"), data);\r\n                                        var argv = stackalloc JSValue[1] { evt };\r\n                                        var rval = JSApi.JS_Call(ctx, onmessage, worker._self, 1, argv);\r\n                                        JSApi.JS_FreeValue(ctx, rval);\r\n                                        JSApi.JS_FreeValue(ctx, evt);\r\n                                        break;\r\n                                    }\r\n                                    else\r\n                                    {\r\n                                        JSApi.JS_FreeValue(ctx, data);\r\n                                    }\r\n                                }\r\n\r\n                                var exceptionString = ctx.GetExceptionString();\r\n                                Diagnostics.Logger.Default.Error(exceptionString);\r\n                            } while (false);\r\n                        }\r\n                        else\r\n                        {\r\n                            // not function\r\n                        }\r\n                        JSApi.JS_FreeValue(ctx, onmessage);\r\n                    }\r\n                }\r\n            }\r\n            finally\r\n            {\r\n                buffer.Release();\r\n            }\r\n        }\r\n\r\n        private JSValue _js_self_postMessage(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            try\r\n            {\r\n                // ctx is woker runtime\r\n                if (!_runtime.isRunning)\r\n                {\r\n                    return ctx.ThrowInternalError(\"worker is not running\");\r\n                }\r\n\r\n                if (argc < 1)\r\n                {\r\n                    return ctx.ThrowInternalError(\"invalid parameter\");\r\n                }\r\n\r\n                size_t psize;\r\n                var dataStore = JSApi.JSB_Serialize(ctx, out psize, argv[0]);\r\n                if (dataStore == IntPtr.Zero)\r\n                {\r\n                    return ctx.ThrowInternalError(\"fail to write object\");\r\n                }\r\n\r\n                var buffer = ScriptEngine.AllocSharedByteBuffer(psize);\r\n                buffer.WriteBytes(dataStore, psize);\r\n                JSApi.js_free(ctx, dataStore);\r\n\r\n                var succ = this._parentRuntime.EnqueueAction(_MasterOnMessage, new JSWorkerArgs { worker = this, buffer = buffer });\r\n                if (!succ)\r\n                {\r\n                    buffer.Release();\r\n                }\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunctionMagic))]\r\n        private static JSValue _js_worker_ctor(JSContext ctx, JSValue new_target, int argc, JSValue[] argv, int magic)\r\n        {\r\n            if (argc < 1 || !argv[0].IsString())\r\n            {\r\n                return ctx.ThrowInternalError(\"invalid parameter\");\r\n            }\r\n\r\n            var scriptPath = JSApi.GetString(ctx, argv[0]);\r\n            var worker = new JSWorker();\r\n            var val = NewBridgeClassObject(ctx, new_target, worker, magic, true);\r\n            try\r\n            {\r\n                if (val.IsObject())\r\n                {\r\n                    worker.Start(ctx, val, scriptPath);\r\n                }\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                JSApi.JS_FreeValue(ctx, val);\r\n                return ctx.ThrowException(e);\r\n            }\r\n            return val;\r\n        }\r\n\r\n        // main thread post message to worker\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        private static JSValue _js_worker_postMessage(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            try\r\n            {\r\n                JSWorker self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n\r\n                if (argc < 1)\r\n                {\r\n                    return ctx.ThrowInternalError(\"invalid parameter\");\r\n                }\r\n\r\n                if (!self._runtime.isRunning)\r\n                {\r\n                    return ctx.ThrowInternalError(\"worker is not running\");\r\n                }\r\n\r\n                size_t psize;\r\n                var dataStore = JSApi.JSB_Serialize(ctx, out psize, argv[0]);\r\n                if (dataStore == IntPtr.Zero)\r\n                {\r\n                    return ctx.ThrowInternalError(\"fail to write object\");\r\n                }\r\n\r\n                var buffer = ScriptEngine.AllocSharedByteBuffer(psize);\r\n                buffer.WriteBytes(dataStore, psize);\r\n                JSApi.js_free(ctx, dataStore);\r\n\r\n                lock (self._inbox)\r\n                {\r\n                    if (self._runtime.isRunning)\r\n                    {\r\n                        self._inbox.Enqueue(buffer);\r\n                    }\r\n                    else\r\n                    {\r\n                        buffer.Release();\r\n                    }\r\n                }\r\n\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        private static JSValue _js_worker_terminate(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            try\r\n            {\r\n                JSWorker self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n\r\n                self._runtime.Shutdown();\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        public static void Bind(TypeRegister register)\r\n        {\r\n            var cls = register.CreateGlobalClass(\"Worker\", typeof(JSWorker), _js_worker_ctor);\r\n            cls.AddMethod(false, \"postMessage\", _js_worker_postMessage, 1);\r\n            cls.AddMethod(false, \"terminate\", _js_worker_terminate);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/JSWorker.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: ce144bdce2a7ab849a23c1d9173d8580\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/AMDModuleRegister.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Module\r\n{\r\n    using Native;\r\n    using Binding;\r\n\r\n    /// <summary>\r\n    /// a minimalistic implementation of AMD modules\r\n    /// </summary>\r\n    public class AMDModuleRegister : IModuleRegister\r\n    {\r\n        private JSContext _ctx;\r\n        private string[] _deps;\r\n        private JSValue _loader;\r\n\r\n        public bool isReloadSupported => false;\r\n\r\n        public AMDModuleRegister(JSContext ctx, string[] deps, JSValue loader)\r\n        {\r\n            _ctx = ctx;\r\n            _deps = deps;\r\n            _loader = JSApi.JS_DupValue(ctx, loader);\r\n        }\r\n\r\n        public void Unload()\r\n        {\r\n            if (_ctx.IsValid())\r\n            {\r\n                if (!_loader.IsUndefined())\r\n                {\r\n                    JSApi.JS_FreeValue(_ctx, _loader);\r\n                    _loader = JSApi.JS_UNDEFINED;\r\n                }\r\n\r\n                _ctx = JSContext.Null;\r\n            }\r\n        }\r\n\r\n        public unsafe JSValue Load(ScriptContext context, string resolved_id, JSValue module_obj, JSValue exports_obj)\r\n        {\r\n            var ctx = (JSContext)context;\r\n\r\n            try\r\n            {\r\n                var len = _deps.Length;\r\n                var values = stackalloc JSValue[len];\r\n                var require_obj = context._CreateRequireFunction(resolved_id, module_obj);\r\n                var filename_obj = JSApi.JS_GetProperty(ctx, module_obj, context.GetAtom(\"filename\"));\r\n                var dirname_obj = JSApi.JS_NULL;\r\n                var require_argv = stackalloc JSValue[5] { JSApi.JS_DupValue(ctx, exports_obj), JSApi.JS_DupValue(ctx, require_obj), JSApi.JS_DupValue(ctx, module_obj), filename_obj, dirname_obj, };\r\n                var rval = JSApi.JS_UNDEFINED;\r\n\r\n                for (var i = 0; i < len; ++i)\r\n                {\r\n                    var dep_id = _deps[i];\r\n                    switch (dep_id)\r\n                    {\r\n                        case \"require\": values[i] = JSApi.JS_DupValue(ctx, require_obj); break;\r\n                        case \"exports\": values[i] = JSApi.JS_DupValue(ctx, exports_obj); break;\r\n                        default:\r\n                            var dep_exports = context.GetRuntime().ResolveModule(context, \"\", dep_id, false);\r\n                            if (dep_exports.IsException())\r\n                            {\r\n                                rval = dep_exports;\r\n                            }\r\n                            else\r\n                            {\r\n                                values[i] = dep_exports;\r\n                            }\r\n                            break;\r\n                    }\r\n\r\n                    if (!rval.IsUndefined())\r\n                    {\r\n                        break;\r\n                    }\r\n                }\r\n\r\n\r\n                // call loader if all dependencies are successfully evaludated\r\n                if (rval.IsUndefined())\r\n                {\r\n                    rval = JSApi.JS_Call(ctx, _loader, JSApi.JS_UNDEFINED, len, values);\r\n\r\n                    if (!rval.IsException())\r\n                    {\r\n                        // drop the return value of 'define' call (the 'define' should returns 'undefined')\r\n                        JSApi.JS_FreeValue(ctx, rval);\r\n                        rval = JSApi.JS_GetProperty(ctx, module_obj, context.GetAtom(\"exports\"));\r\n                    }\r\n                }\r\n\r\n                JSApi.JS_FreeValue(ctx, require_obj);\r\n                for (var i = 0; i < len; ++i)\r\n                {\r\n                    JSApi.JS_FreeValue(ctx, values[i]);\r\n                }\r\n                for (var i = 0; i < 5; ++i)\r\n                {\r\n                    JSApi.JS_FreeValue(ctx, require_argv[i]);\r\n                }\r\n\r\n                return rval;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                // unexpected exception (should never happen)\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/AMDModuleRegister.cs.meta",
    "content": "fileFormatVersion: 2\nguid: ff65db2d857f97c4b8a1b9d11085ecce\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/FuncModuleRegister.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Module\r\n{\r\n    using Native;\r\n    using Binding;\r\n\r\n    // 一个绑定函数代表一个类型注册为一个模块\r\n    public class FuncModuleRegister : IModuleRegister\r\n    {\r\n        private ClassBind _bind;\r\n\r\n        public bool isReloadSupported => true;\r\n\r\n        public FuncModuleRegister(ClassBind bind)\r\n        {\r\n            _bind = bind;\r\n        }\r\n\r\n        public void Unload()\r\n        {\r\n        }\r\n\r\n        public JSValue Load(ScriptContext context, string resolved_id, JSValue module_obj, JSValue exports_obj)\r\n        {\r\n            var register = context.CreateTypeRegister();\r\n            var clazz = _bind(register);\r\n            var rval = clazz.GetConstructor();\r\n            var ctx = (JSContext)context;\r\n            JSApi.JS_SetProperty(ctx, module_obj, register.GetAtom(\"exports\"), JSApi.JS_DupValue(ctx, rval));\r\n            register.Finish();\r\n            return rval;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/FuncModuleRegister.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 46d7094be0276d94c954c269f82bc187\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/IModuleRegister.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Module\r\n{\r\n    using Native;\r\n    using Binding;\r\n\r\n    public interface IModuleRegister\r\n    {\r\n        bool isReloadSupported { get; }\r\n\r\n        /// <summary>\r\n        /// setup module members and return the final exports object (usually equals to exports_obj, but with an additional reference counting)\r\n        /// </summary>\r\n        JSValue Load(ScriptContext context, string resolved_id, JSValue module_obj, JSValue exports_obj);\r\n        void Unload();\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/IModuleRegister.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 3270ff43a301fc34e84e653ee8d8f969\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/IModuleResolver.cs",
    "content": "using System;\r\n\r\nnamespace QuickJS.Module\r\n{\r\n    using Native;\r\n    using Utils;\r\n\r\n    public interface IModuleResolver\r\n    {\r\n        bool ResolveModule(IFileSystem fileSystem, IPathResolver pathResolver, string parent_module_id, string module_id, out string resolved_id);\r\n        bool ContainsModule(IFileSystem fileSystem, IPathResolver pathResolver, string resolved_id);\r\n        JSValue LoadModule(ScriptContext context, string parent_module_id, string resolved_id, bool set_as_main);\r\n        \r\n        /// <summary>\r\n        /// reload the specified module, return false if this module can not be resolved by this resolver, otherwise return true even if fail to load the module\r\n        /// (this method will not consume the refcount of module_obj)\r\n        /// </summary>\r\n        bool ReloadModule(ScriptContext context, string resolved_id, JSValue module_obj, out JSValue exports_obj);\r\n\r\n        void Release();\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/IModuleResolver.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: abece41b99a341847aa678b421fe7bbb\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/JsonModuleResolver.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Module\r\n{\r\n    using Utils;\r\n    using Native;\r\n\r\n    public class JsonModuleResolver : PathBasedModuleResolver\r\n    {\r\n        public JsonModuleResolver()\r\n        {\r\n        }\r\n\r\n        public override void Release()\r\n        {\r\n        }\r\n\r\n        protected override bool OnValidating(string module_id)\r\n        {\r\n            // 必须指明后缀\r\n            return module_id.EndsWith(\".json\") || module_id.EndsWith(\".jsonc\");\r\n        }\r\n\r\n        protected override bool OnResolvingFile(IFileSystem fileSystem, IPathResolver pathResolver, string fileName, out string searchPath, out string resolvedFileName)\r\n        {\r\n            if (pathResolver.ResolvePath(fileSystem, fileName, out searchPath, out resolvedFileName))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public override bool ReloadModule(ScriptContext context, string resolved_id, JSValue module_obj, out JSValue exports_obj)\r\n        {\r\n            exports_obj = LoadModule(context, null, resolved_id, false);\r\n            if (exports_obj.IsException())\r\n            {\r\n                JSNative.print_exception(context);\r\n                exports_obj = JSApi.JS_UNDEFINED;\r\n                return false;\r\n            }\r\n            \r\n            return true;\r\n        }\r\n\r\n        public override unsafe JSValue LoadModule(ScriptContext context, string parent_module_id, string resolved_id, bool set_as_main)\r\n        {\r\n            var fileSystem = context.GetRuntime().GetFileSystem();\r\n            var resolved_id_bytes = Utils.TextUtils.GetNullTerminatedBytes(resolved_id);\r\n            // var dirname = PathUtils.GetDirectoryName(resolved_id);\r\n            var source = fileSystem.ReadAllBytes(resolved_id);\r\n            var ctx = (JSContext)context;\r\n\r\n            if (source == null)\r\n            {\r\n                return ctx.ThrowInternalError(\"require module load failed\");\r\n            }\r\n\r\n            var input_bytes = TextUtils.GetNullTerminatedBytes(source);\r\n            var input_bom = TextUtils.GetBomSize(source);\r\n\r\n            fixed (byte* input_ptr = &input_bytes[input_bom])\r\n            fixed (byte* filename_ptr = resolved_id_bytes)\r\n            {\r\n                var rval = JSApi.JS_ParseJSON(ctx, input_ptr, input_bytes.Length - 1 - input_bom, filename_ptr);\r\n                if (rval.IsException())\r\n                {\r\n                    return rval;\r\n                }\r\n\r\n                var module_obj = context._new_commonjs_resolver_module(resolved_id, \"json\", rval, true, set_as_main);\r\n                JSApi.JS_FreeValue(ctx, module_obj);\r\n\r\n                return rval;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/JsonModuleResolver.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 7886f6919cd45fb48bf2fda052022fd1\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/PathBasedModuleResolver.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Module\r\n{\r\n    using Utils;\r\n    using Native;\r\n\r\n    public abstract class PathBasedModuleResolver : IModuleResolver\r\n    {\r\n        public PathBasedModuleResolver()\r\n        {\r\n        }\r\n\r\n        public abstract void Release();\r\n\r\n        // 验证模块名可接受\r\n        protected abstract bool OnValidating(string module_id);\r\n\r\n        protected abstract bool OnResolvingFile(IFileSystem fileSystem, IPathResolver pathResolver, string fileName, out string searchPath, out string resolvedFileName);\r\n\r\n        public bool ContainsModule(IFileSystem fileSystem, IPathResolver pathResolver, string resolved_id)\r\n        {\r\n            return OnValidating( resolved_id) && fileSystem.Exists(resolved_id);\r\n        }\r\n\r\n        public bool ResolveModule(IFileSystem fileSystem, IPathResolver pathResolver, string parent_module_id, string module_id, out string resolved_id)\r\n        {\r\n            if (OnValidating(module_id))\r\n            {\r\n                var resolving = module_id;\r\n\r\n                // 将相对目录展开\r\n                if (module_id.StartsWith(\"./\") || module_id.StartsWith(\"../\") || module_id.Contains(\"/./\") ||\r\n                    module_id.Contains(\"/../\"))\r\n                {\r\n                    // 显式相对路径直接从 parent 模块路径拼接\r\n                    var parent_path = PathUtils.GetDirectoryName(parent_module_id);\r\n                    try\r\n                    {\r\n                        resolving = PathUtils.ExtractPath(PathUtils.Combine(parent_path, module_id), '/');\r\n                    }\r\n                    catch\r\n                    {\r\n                        // 不能提升到源代码目录外面\r\n                        throw new Exception(string.Format(\"invalid module path (out of sourceRoot): {0}\", module_id));\r\n                    }\r\n                }\r\n\r\n                string searchPath;\r\n                if (OnResolvingFile(fileSystem, pathResolver, resolving, out searchPath, out resolved_id))\r\n                {\r\n                    return true;\r\n                }\r\n            }\r\n            \r\n            resolved_id = null;\r\n            return false;\r\n        }\r\n\r\n        public abstract JSValue LoadModule(ScriptContext context, string parent_module_id, string resolved_id, bool set_as_main);\r\n        \r\n        public abstract bool ReloadModule(ScriptContext context, string resolved_id, JSValue module_obj, out JSValue exports_obj);\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/PathBasedModuleResolver.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: c59e06e939ab8a24fa0e12a4a2552878\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/ProxyModuleRegister.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Module\r\n{\r\n    using Native;\r\n    using Binding;\r\n\r\n    public class ProxyModuleRegister : IModuleRegister\r\n    {\r\n        // Key: FullName in module\r\n        // Value: Type\r\n        private Dictionary<string, Type> _typeTree; // root space\r\n        private HashSet<string> _intermediatePath;\r\n\r\n        public bool isReloadSupported => false;\r\n\r\n        public ProxyModuleRegister()\r\n        {\r\n            _typeTree = new Dictionary<string, Type>();\r\n            _intermediatePath = new HashSet<string>();\r\n        }\r\n\r\n        public void Unload()\r\n        {\r\n        }\r\n\r\n        public void Add(Type type, string[] ns)\r\n        {\r\n            for (int i = 0, length = ns.Length; i < length; ++i)\r\n            {\r\n                var intermediate = string.Join(\".\", ns, 0, i + 1);\r\n                if (i != length - 1)\r\n                {\r\n                    _intermediatePath.Add(intermediate);\r\n                }\r\n                else\r\n                {\r\n                    _typeTree[intermediate] = type;\r\n                }\r\n            }\r\n        }\r\n\r\n        private JSValue LoadType(ScriptContext context, string typePath)\r\n        {\r\n            Type type;\r\n            if (_typeTree.TryGetValue(typePath, out type))\r\n            {\r\n                return context.GetTypeDB().GetConstructorOf(type);\r\n            }\r\n            if (_intermediatePath.Contains(typePath))\r\n            {\r\n                return JSApi.JS_NewObject(context);\r\n            }\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        private static JSValue js_load_type(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc != 2 || !argv[0].IsString() || !argv[1].IsString())\r\n            {\r\n                return ctx.ThrowInternalError(\"string expected\");\r\n            }\r\n\r\n            var module_id = JSApi.GetString(ctx, argv[0]);\r\n            var type_path = JSApi.GetString(ctx, argv[1]);\r\n\r\n            if (module_id == null || type_path == null)\r\n            {\r\n                return ctx.ThrowInternalError(\"get invalid string\");\r\n            }\r\n\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            var runtime = context.GetRuntime();\r\n            var proxy = runtime.FindModuleResolver<StaticModuleResolver>()?.GetModuleRegister<ProxyModuleRegister>(module_id);\r\n            return proxy != null ? proxy.LoadType(context, type_path) : JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        // the given exports object is ignored, type loader uses a Proxy object as new exports\r\n        public unsafe JSValue Load(ScriptContext context, string resolved_id, JSValue module_obj, JSValue exports_obj)\r\n        {\r\n            var ctx = (JSContext)context;\r\n            var sourceString = @\"(function (module_id, load_type) {\r\n                let new_proxy;\r\n                new_proxy = function (t, last) {\r\n                    if (typeof t === 'undefined') {\r\n                        throw new Error(`type '${last}' does not exist`);\r\n                    }\r\n                    return new Proxy(t, {\r\n                        set: function (target, p, value) {\r\n                            if (typeof p !== 'string') {\r\n                                throw new Error(`symbol is not acceptable`);\r\n                            }\r\n                            if (typeof target[p] !== 'undefined') {\r\n                                target[p] = value;\r\n                                return true;\r\n                            }\r\n                            let type_path = typeof last === 'string' ? last + '.' + p : p;\r\n                            throw new Error(`'${type_path}' is not writable`);\r\n                        }, \r\n                        get: function (target, p) {\r\n                            let o = target[p];\r\n                            if (typeof o === 'undefined' && typeof p === 'string') {\r\n                                let type_path = typeof last === 'string' ? last + '.' + p : p;\r\n                                o = target[p] = new_proxy(load_type(module_id, type_path), type_path)\r\n                            }\r\n                            return o;\r\n                        }\r\n                    })\r\n                };\r\n                return new_proxy({}); \r\n            })\";\r\n            var proxyGen = ScriptRuntime.EvalSource(ctx, sourceString, \"eval\", false);\r\n            var argv = stackalloc JSValue[2]\r\n            {\r\n                ctx.NewString(resolved_id),\r\n                JSApi.JSB_NewCFunction(ctx, js_load_type, context.GetAtom(\"$LoadType\"), 2),\r\n            };\r\n            var retVal = JSApi.JS_Call(ctx, proxyGen, JSApi.JS_UNDEFINED, 2, argv);\r\n            JSApi.JS_FreeValue(ctx, proxyGen);\r\n            JSApi.JS_FreeValue(ctx, argv[0]);\r\n            JSApi.JS_FreeValue(ctx, argv[1]);\r\n            JSApi.JS_SetProperty(ctx, module_obj, context.GetAtom(\"exports\"), JSApi.JS_DupValue(ctx, retVal));\r\n            return retVal;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/ProxyModuleRegister.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 8519b16fd8c1dc04393acb0056e89f77\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/RawModuleRegister.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Module\r\n{\r\n    using Native;\r\n    using Binding;\r\n\r\n    public delegate JSValue RawModuleBind(ScriptContext context);\r\n\r\n    /// <summary>\r\n    /// 返回值注册为模块对象\r\n    /// </summary>\r\n    public class RawModuleRegister : IModuleRegister\r\n    {\r\n        private RawModuleBind _bind;\r\n\r\n        public bool isReloadSupported => true;\r\n\r\n        public RawModuleRegister(RawModuleBind bind)\r\n        {\r\n            _bind = bind;\r\n        }\r\n\r\n        public void Unload()\r\n        {\r\n        }\r\n\r\n        public JSValue Load(ScriptContext context, string resolved_id, JSValue module_obj, JSValue exports_obj)\r\n        {\r\n            var v = _bind(context);\r\n            var ctx = (JSContext)context;\r\n            var key_atom = context.GetAtom(\"exports\");\r\n            JSApi.JS_SetProperty(ctx, module_obj, key_atom, JSApi.JS_DupValue(ctx, v));\r\n            return v;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/RawModuleRegister.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 3834be6a4c924194ba286238b2d28ad6\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/SourceModuleResolver.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Module\r\n{\r\n    using Utils;\r\n    using Native;\r\n\r\n    public class SourceModuleResolver : PathBasedModuleResolver\r\n    {\r\n        private const string LoadModuleEmptySourceError = \"failed to load module with empty source\";\r\n        private const string LoadModuleTypeError = \"es6 module can not be loaded by require\";\r\n\r\n        [Serializable]\r\n        public class PackageConfig\r\n        {\r\n            public string main;\r\n        }\r\n\r\n        // a json converter for package.json parsing\r\n        private IJsonConverter _jsonConv;\r\n\r\n        public SourceModuleResolver(IJsonConverter jsonConv)\r\n        {\r\n            _jsonConv = jsonConv;\r\n        }\r\n\r\n        public override void Release()\r\n        {\r\n        }\r\n\r\n        protected override bool OnValidating(string module_id)\r\n        {\r\n            // 接受无后缀路径\r\n            return true;\r\n        }\r\n\r\n        protected override bool OnResolvingFile(IFileSystem fileSystem, IPathResolver pathResolver, string fileName, out string searchPath, out string resolvedFileName)\r\n        {\r\n            if (pathResolver.ResolvePath(fileSystem, fileName, out searchPath, out resolvedFileName))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            // try resolve bytecode file\r\n            if (pathResolver.ResolvePath(fileSystem, fileName + \".js.bytes\", out searchPath, out resolvedFileName))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            if (pathResolver.ResolvePath(fileSystem, fileName + \".js\", out searchPath, out resolvedFileName))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            if (pathResolver.ResolvePath(fileSystem, PathUtils.Combine(fileName, \"index.js\"), out searchPath, out resolvedFileName))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            if (_jsonConv != null && pathResolver.ResolvePath(fileSystem, PathUtils.Combine(fileName, \"package.json\"), out searchPath, out resolvedFileName))\r\n            {\r\n                var packageDataBytes = fileSystem.ReadAllBytes(resolvedFileName);\r\n                if (packageDataBytes != null)\r\n                {\r\n                    var packageData = System.Text.Encoding.UTF8.GetString(packageDataBytes);\r\n                    var packageConfig = _jsonConv.Deserialize(packageData, typeof(PackageConfig)) as PackageConfig;\r\n                    if (packageConfig != null && !string.IsNullOrEmpty(packageConfig.main))\r\n                    {\r\n                        var main = PathUtils.Combine(searchPath, fileName, packageConfig.main);\r\n                        if (!main.EndsWith(\".js\"))\r\n                        {\r\n                            main += \".js\";\r\n                        }\r\n                        main = PathUtils.ExtractPath(main, '/');\r\n                        if (fileSystem.Exists(main))\r\n                        {\r\n                            resolvedFileName = main;\r\n                            return true;\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            resolvedFileName = null;\r\n            return false;\r\n        }\r\n\r\n        public override bool ReloadModule(ScriptContext context, string resolved_id, JSValue module_obj, out JSValue exports_obj)\r\n        {\r\n            exports_obj = _ReloadModule(context, resolved_id, JSApi.JS_DupValue(context, module_obj));\r\n            if (exports_obj.IsException())\r\n            {\r\n                JSNative.print_exception(context);\r\n                exports_obj = JSApi.JS_UNDEFINED;\r\n                return false;\r\n            }\r\n            \r\n            return true;\r\n        }\r\n\r\n        private JSValue _ReloadModule(ScriptContext context, string resolved_id, JSValue module_obj)\r\n        {\r\n            var fileSystem = context.GetRuntime().GetFileSystem();\r\n            var source = fileSystem.ReadAllBytes(resolved_id);\r\n            var ctx = (JSContext)context;\r\n\r\n            if (source == null)\r\n            {\r\n                return ctx.ThrowInternalError(LoadModuleEmptySourceError);\r\n            }\r\n\r\n            var tagValue = ScriptRuntime.TryReadByteCodeTagValue(source);\r\n\r\n            if (tagValue == ScriptRuntime.BYTECODE_ES6_MODULE_TAG)\r\n            {\r\n                return ctx.ThrowInternalError(LoadModuleTypeError);\r\n            }\r\n\r\n            var filename = fileSystem.GetFullPath(resolved_id) ?? resolved_id;\r\n            JSApi.JS_SetProperty(ctx, module_obj, context.GetAtom(\"loaded\"), JSApi.JS_NewBool(ctx, false));\r\n            return context.LoadModuleFromSource(source, resolved_id, filename, module_obj);\r\n        }\r\n\r\n        public override JSValue LoadModule(ScriptContext context, string parent_module_id, string resolved_id, bool set_as_main)\r\n        {\r\n            var fileSystem = context.GetRuntime().GetFileSystem();\r\n            var source = fileSystem.ReadAllBytes(resolved_id);\r\n            var ctx = (JSContext)context;\r\n\r\n            if (source == null)\r\n            {\r\n                return ctx.ThrowInternalError(LoadModuleEmptySourceError);\r\n            }\r\n\r\n            var tagValue = ScriptRuntime.TryReadByteCodeTagValue(source);\r\n\r\n            if (tagValue == ScriptRuntime.BYTECODE_ES6_MODULE_TAG)\r\n            {\r\n                return ctx.ThrowInternalError(LoadModuleTypeError);\r\n            }\r\n\r\n            var exports_obj = JSApi.JS_UNDEFINED;\r\n            var module_obj = JSApi.JS_UNDEFINED;\r\n            if (context.TryGetModuleForReloading(resolved_id, out module_obj))\r\n            {\r\n                if (ReloadModule(context, resolved_id, module_obj, out exports_obj))\r\n                {\r\n                    JSApi.JS_FreeValue(ctx, module_obj);\r\n                    return exports_obj;\r\n                }\r\n                JSApi.JS_FreeValue(ctx, module_obj);\r\n            }\r\n\r\n            var filename = fileSystem.GetFullPath(resolved_id) ?? resolved_id;\r\n            exports_obj = JSApi.JS_NewObject(ctx); \r\n            module_obj = context._new_commonjs_script_module(parent_module_id, resolved_id, filename, exports_obj, false, set_as_main);\r\n            JSApi.JS_FreeValue(ctx, exports_obj);\r\n            return context.LoadModuleFromSource(source, resolved_id, filename, module_obj);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/SourceModuleResolver.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 29eb51435bb9b0847820cb55a52b5168\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/StaticModuleResolver.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Module\r\n{\r\n    using Utils;\r\n    using Native;\r\n    using Binding;\r\n\r\n    public class StaticModuleResolver : IModuleResolver\r\n    {\r\n        private Dictionary<string, IModuleRegister> _modRegisters = new Dictionary<string, IModuleRegister>();\r\n\r\n        public void Release()\r\n        {\r\n            var count = _modRegisters.Count;\r\n            if (count > 0)\r\n            {\r\n                var values = new IModuleRegister[count];\r\n                _modRegisters.Values.CopyTo(values, 0);\r\n                _modRegisters.Clear();\r\n                for (var i = 0; i < count; ++i)\r\n                {\r\n                    values[i].Unload();\r\n                }\r\n            }\r\n        }\r\n\r\n        public StaticModuleResolver AddStaticModule(string module_id, ClassBind bind)\r\n        {\r\n            return AddStaticModule(module_id, new FuncModuleRegister(bind));\r\n        }\r\n\r\n        public StaticModuleResolver AddStaticModule(string module_id, RawModuleBind bind)\r\n        {\r\n            return AddStaticModule(module_id, new RawModuleRegister(bind));\r\n        }\r\n\r\n        public StaticModuleResolver AddStaticModule(string module_id, IModuleRegister moduleRegister)\r\n        {\r\n            IModuleRegister oldRegister;\r\n            if (_modRegisters.TryGetValue(module_id, out oldRegister))\r\n            {\r\n                oldRegister.Unload();\r\n            }\r\n            _modRegisters[module_id] = moduleRegister;\r\n            return this;\r\n        }\r\n\r\n        public bool ContainsModule(IFileSystem fileSystem, IPathResolver pathResolver, string resolved_id)\r\n        {\r\n            return _modRegisters.ContainsKey(resolved_id);\r\n        }\r\n\r\n        public bool ResolveModule(IFileSystem fileSystem, IPathResolver pathResolver, string parent_module_id, string module_id, out string resolved_id)\r\n        {\r\n            if (_modRegisters.ContainsKey(module_id))\r\n            {\r\n                resolved_id = module_id;\r\n                return true;\r\n            }\r\n            resolved_id = null;\r\n            return false;\r\n        }\r\n\r\n        public bool ReloadModule(ScriptContext context, string resolved_id, JSValue module_obj, out JSValue exports_obj)\r\n        {\r\n            exports_obj = JSApi.JS_UNDEFINED;\r\n            IModuleRegister moduleRegister;\r\n            if (_modRegisters.TryGetValue(resolved_id, out moduleRegister) && moduleRegister.isReloadSupported)\r\n            {\r\n                var ctx = (JSContext)context;\r\n                var old_exports_obj = JSApi.JS_GetProperty(ctx, module_obj, context.GetAtom(\"exports\"));\r\n\r\n                exports_obj = moduleRegister.Load(context, resolved_id, module_obj, old_exports_obj);\r\n\r\n                JSApi.JS_FreeValue(ctx, old_exports_obj);\r\n                JSApi.JS_SetProperty(ctx, module_obj, context.GetAtom(\"loaded\"), JSApi.JS_NewBool(ctx, true));\r\n                return true;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public JSValue LoadModule(ScriptContext context, string parent_module_id, string resolved_id, bool set_as_main)\r\n        {\r\n            IModuleRegister moduleRegister;\r\n            var ctx = (JSContext)context;\r\n            if (_modRegisters.TryGetValue(resolved_id, out moduleRegister))\r\n            {\r\n                var exports_obj = JSApi.JS_NewObject(ctx);\r\n                var module_obj = context._new_commonjs_resolver_module(resolved_id, \"static\", exports_obj, false, set_as_main);\r\n\r\n                var rval = moduleRegister.Load(context, resolved_id, module_obj, exports_obj);\r\n\r\n                JSApi.JS_SetProperty(ctx, module_obj, context.GetAtom(\"loaded\"), JSApi.JS_NewBool(ctx, true));\r\n                JSApi.JS_FreeValue(ctx, exports_obj);\r\n                JSApi.JS_FreeValue(ctx, module_obj);\r\n                return rval;\r\n            }\r\n\r\n            return ctx.ThrowInternalError(\"invalid static module loader\");\r\n        }\r\n\r\n        public T GetModuleRegister<T>(string module_id) where T : class, IModuleRegister\r\n        {\r\n            IModuleRegister moduleRegister;\r\n            if (_modRegisters.TryGetValue(module_id, out moduleRegister))\r\n            {\r\n                return moduleRegister as T;\r\n            }\r\n            return default(T);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/StaticModuleResolver.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: b3583447d1a8df8489f8fdd8704ad596\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/ValueModuleRegister.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Module\r\n{\r\n    using Native;\r\n    using Binding;\r\n\r\n    public class ValueModuleRegister : IModuleRegister\r\n    {\r\n        private ScriptRuntime _runtime;\r\n        private JSValue _rawValue;\r\n\r\n        public bool isReloadSupported => false;\r\n\r\n        public ValueModuleRegister(ScriptRuntime runtime, JSValue bind)\r\n        {\r\n            _runtime = runtime;\r\n            _rawValue = JSApi.JS_DupValue(_runtime.GetMainContext(), bind);\r\n        }\r\n\r\n        public void Unload()\r\n        {\r\n            if (!_rawValue.IsUndefined())\r\n            {\r\n                var rawValue = _rawValue;\r\n                _rawValue = JSApi.JS_UNDEFINED;\r\n                _runtime.FreeValue(rawValue);\r\n            }\r\n        }\r\n\r\n        public JSValue Load(ScriptContext context, string resolved_id, JSValue module_obj, JSValue exports_obj)\r\n        {\r\n            var ctx = (JSContext)context;\r\n            var key_atom = context.GetAtom(\"exports\");\r\n            JSApi.JS_SetProperty(ctx, module_obj, key_atom, JSApi.JS_DupValue(ctx, _rawValue));\r\n            return JSApi.JS_DupValue(ctx, _rawValue);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module/ValueModuleRegister.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 21d438d328efcf54486954d1b318344c\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Module.meta",
    "content": "fileFormatVersion: 2\r\nguid: 367e9f5481ad13049a26ce404ca87e25\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSApi+Helpers.cs",
    "content": "﻿using System;\r\nusing System.Runtime.InteropServices;\r\nusing System.Text;\r\n\r\nnamespace QuickJS.Native\r\n{\r\n    public partial class JSApi\r\n    {\r\n        /// <summary>\r\n        /// it's equivalent to JS_Call with a single element argv\r\n        /// </summary>\r\n        public static unsafe JSValue Call(JSContext ctx, JSValue func_obj, JSValue this_obj, JSValue arg0)\r\n        {\r\n            var argv = stackalloc[] { arg0 };\r\n            return JS_Call(ctx, func_obj, this_obj, 1, argv);\r\n        }\r\n\r\n        public static string GetString(JSContext ctx, JSAtom atom)\r\n        {\r\n            var strValue = JSApi.JS_AtomToString(ctx, atom);\r\n            var str = strValue.IsString() ? GetString(ctx, strValue) : null;\r\n            JSApi.JS_FreeValue(ctx, strValue);\r\n            return str;\r\n        }\r\n\r\n        public static string GetString(JSContext ctx, JSValue val)\r\n        {\r\n            size_t len;\r\n            var pstr = JSApi.JS_ToCStringLen(ctx, out len, val);\r\n            if (pstr == IntPtr.Zero)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            try\r\n            {\r\n                return JSApi.GetString(ctx, pstr, len);\r\n            }\r\n            finally\r\n            {\r\n                JSApi.JS_FreeCString(ctx, pstr);\r\n            }\r\n        }\r\n\r\n        public static string GetNonNullString(JSContext ctx, JSValue val)\r\n        {\r\n            size_t len;\r\n            var pstr = JSApi.JS_ToCStringLen(ctx, out len, val);\r\n            if (pstr == IntPtr.Zero)\r\n            {\r\n                return string.Empty;\r\n            }\r\n\r\n            try\r\n            {\r\n                return JSApi.GetString(ctx, pstr, len) ?? string.Empty;\r\n            }\r\n            finally\r\n            {\r\n                JSApi.JS_FreeCString(ctx, pstr);\r\n            }\r\n        }\r\n\r\n        public static unsafe void MemoryCopy(void* source, void* destination, long destinationSizeInBytes, long sourceBytesToCopy)\r\n        {\r\n#if JSB_COMPATIBLE\r\n            if (sourceBytesToCopy > destinationSizeInBytes)\r\n            {\r\n                throw new ArgumentOutOfRangeException();\r\n            }\r\n\r\n            var pSource = (byte*)source;\r\n            var pDestination = (byte*)destination;\r\n\r\n            for (int i = 0; i < sourceBytesToCopy; ++i)\r\n            {\r\n                pDestination[i] = pSource[i];\r\n            }\r\n#else\r\n            Buffer.MemoryCopy(source, destination, destinationSizeInBytes, sourceBytesToCopy);\r\n#endif\r\n        }\r\n\r\n        public static unsafe string GetString(JSContext ctx, IntPtr ptr, int len)\r\n        {\r\n            if (len > 0)\r\n            {\r\n                var str = Marshal.PtrToStringAnsi(ptr, len);\r\n                if (str == null)\r\n                {\r\n#if JSB_COMPATIBLE\r\n                    var buffer = new byte[len];\r\n                    Marshal.Copy(ptr, buffer, 0, len);\r\n                    return Encoding.UTF8.GetString(buffer);\r\n#else\r\n                    var pointer = (byte*)(void*)ptr;\r\n                    return Encoding.UTF8.GetString(pointer, len);\r\n#endif\r\n                }\r\n\r\n                return str;\r\n            }\r\n\r\n            return null;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSApi+Helpers.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 677c4d1d6320403293356314508feb78\r\ntimeCreated: 1590734190"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSApi+QuickJS.cs",
    "content": "#if !JSB_WITH_V8_BACKEND\r\nusing System;\r\nusing System.Runtime.InteropServices;\r\nusing System.Text;\r\n\r\nnamespace QuickJS.Native\r\n{\r\n    public partial class JSApi\r\n    {\r\n        #region module\r\n        /* module_normalize = NULL is allowed and invokes the default module filename normalizer */\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern void JS_SetModuleLoaderFunc(JSRuntime rt, IntPtr module_normalize, IntPtr module_loader, IntPtr opaque);\r\n\r\n        public static void JS_SetModuleLoaderFunc(JSRuntime rt, JSModuleNormalizeFunc module_normalize, JSModuleLoaderFunc module_loader, IntPtr opaque)\r\n        {\r\n#if JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n            GCHandle.Alloc(module_normalize);\r\n            GCHandle.Alloc(module_loader);\r\n#endif\r\n            JS_SetModuleLoaderFunc(rt,\r\n                module_normalize != null ? Marshal.GetFunctionPointerForDelegate(module_normalize) : IntPtr.Zero,\r\n                module_loader != null ? Marshal.GetFunctionPointerForDelegate(module_loader) : IntPtr.Zero, opaque);\r\n        }\r\n\r\n        /* return the import.meta object of a module */\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue JS_GetImportMeta(JSContext ctx, JSModuleDef m);\r\n        #endregion\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSApi+QuickJS.cs.meta",
    "content": "fileFormatVersion: 2\nguid: a32f4708473abab45ad8ab69d9c1850d\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSApi+StructValue.cs",
    "content": "using System;\r\nusing System.Runtime.InteropServices;\r\nusing System.Text;\r\n\r\nnamespace QuickJS.Native\r\n{\r\n    using int32_t = Int32;\r\n    using uint32_t = UInt32;\r\n    using JS_BOOL = Int32;\r\n\r\n    public partial class JSApi\r\n    {\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSClassID JSB_GetBridgeClassID();\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue jsb_construct_bridge_object(JSContext ctx, JSValue proto, int32_t object_id);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue jsb_new_bridge_object(JSContext ctx, JSValue proto, int object_id);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue JSB_NewBridgeClassObject(JSContext ctx, JSValue new_target, int object_id);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue jsb_new_bridge_value(JSContext ctx, JSValue proto, uint32_t size);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue JSB_NewBridgeClassValue(JSContext ctx, JSValue new_target, int32_t size);\r\n\r\n        public static bool JSB_SetBridgeType(JSContext ctx, JSValue obj, JSAtom key, int32_t type)\r\n        {\r\n            if (obj.tag == JS_TAG_OBJECT)\r\n            {\r\n                JS_DefinePropertyValue(ctx, obj, key, JS_NewInt32(ctx, type));\r\n                return true;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public static int32_t JSB_GetBridgeType(JSContext ctx, JSValue obj, JSAtom key)\r\n        {\r\n            if (obj.tag == JS_TAG_OBJECT)\r\n            {\r\n                var val = JS_GetProperty(ctx, obj, key);\r\n                int32_t pres;\r\n                if (JS_ToInt32(ctx, out pres, val) == 0)\r\n                {\r\n                    JS_FreeValue(ctx, val);\r\n                    return pres;\r\n                }\r\n                JS_FreeValue(ctx, val);\r\n            }\r\n\r\n            return -1;\r\n        }\r\n\r\n        // !!!\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSPayloadHeader JSB_FreePayload(JSContext ctx, JSValue val);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSPayloadHeader jsb_get_payload_header(JSContext ctx, JSValue val);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JS_BOOL jsb_get_floats(JSContext ctx, JSValue val, int n, float* v0);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JS_BOOL jsb_set_floats(JSContext ctx, JSValue val, int n, float* v0);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL jsb_get_float_2(JSContext ctx, JSValue val, out float v0, out float v1);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL jsb_set_float_2(JSContext ctx, JSValue val, float v0, float v1);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL jsb_get_float_3(JSContext ctx, JSValue val, out float v0, out float v1, out float v2);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL jsb_set_float_3(JSContext ctx, JSValue val, float v0, float v1, float v2);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL jsb_get_float_4(JSContext ctx, JSValue val, out float v0, out float v1, out float v2, out float v3);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL jsb_set_float_4(JSContext ctx, JSValue val, float v0, float v1, float v2, float v3);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL jsb_get_int_1(JSContext ctx, JSValue val, out int v0);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL jsb_set_int_1(JSContext ctx, JSValue val, int v0);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL jsb_get_int_2(JSContext ctx, JSValue val, out int v0, out int v1);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL jsb_set_int_2(JSContext ctx, JSValue val, int v0, int v1);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL jsb_get_int_3(JSContext ctx, JSValue val, out int v0, out int v1, out int v2);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL jsb_set_int_3(JSContext ctx, JSValue val, int v0, int v1, int v2);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL jsb_get_int_4(JSContext ctx, JSValue val, out int v0, out int v1, out int v2, out int v3);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL jsb_set_int_4(JSContext ctx, JSValue val, int v0, int v1, int v2, int v3);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL jsb_get_byte_4(JSContext ctx, JSValue val, out byte v0, out byte v1, out byte v2, out byte v3);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL jsb_set_byte_4(JSContext ctx, JSValue val, byte v0, byte v1, byte v2, byte v3);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JS_BOOL jsb_get_bytes(JSContext ctx, JSValue val, int n, byte* v0);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JS_BOOL jsb_set_bytes(JSContext ctx, JSValue val, int n, byte* v0);\r\n\r\n        public static unsafe JS_BOOL jsb_get_bytes(JSContext ctx, JSValue val, out long v0)\r\n        {\r\n            long v;\r\n            var ret = jsb_get_bytes(ctx, val, sizeof(long), (byte*)&v);\r\n            v0 = v;\r\n            return ret;\r\n        }\r\n\r\n        public static unsafe JS_BOOL jsb_set_bytes(JSContext ctx, JSValue val, long v0)\r\n        {\r\n            long* p = &v0;\r\n            return JSApi.jsb_set_bytes(ctx, val, sizeof(long), (byte*)p);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSApi+StructValue.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 87f70c640fe2a2346b39e2e1506081e6\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSApi.cs",
    "content": "using System;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\n// Default Marshaling for Strings\r\n// https://docs.microsoft.com/en-us/dotnet/framework/interop/default-marshaling-for-strings\r\n\r\n// Marshaling a Delegate as a Callback Method\r\n// https://docs.microsoft.com/en-us/dotnet/framework/interop/marshaling-a-delegate-as-a-callback-method\r\n\r\nnamespace QuickJS.Native\r\n{\r\n    using JSValueConst = JSValue;\r\n    using JS_BOOL = Int32;\r\n    using int32_t = Int32;\r\n    using uint32_t = UInt32;\r\n    using int64_t = Int64;\r\n    using uint64_t = UInt64;\r\n\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public delegate int JSInterruptHandler(JSRuntime rt, IntPtr opaque);\r\n\r\n    /* is_handled = TRUE means that the rejection is handled */\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public delegate void JSHostPromiseRejectionTracker(JSContext ctx, JSValueConst promise, JSValueConst reason, JS_BOOL is_handled, IntPtr opaque);\r\n\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public unsafe delegate IntPtr JSModuleNormalizeFunc(JSContext ctx, [MarshalAs(UnmanagedType.LPStr)] string module_base_name, [MarshalAs(UnmanagedType.LPStr)] string module_name, IntPtr opaque);\r\n\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public delegate JSModuleDef JSModuleLoaderFunc(JSContext ctx, [MarshalAs(UnmanagedType.LPStr)] string module_name, IntPtr opaque);\r\n\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public delegate void JSGCObjectFinalizer(JSRuntime rt, JSPayloadHeader header);\r\n\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public delegate JSValue JSCFunction(JSContext ctx, JSValueConst this_obj, int argc, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] JSValueConst[] argv);\r\n\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public delegate JSValue JSCFunctionMagic(JSContext ctx, JSValueConst this_obj, int argc, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] JSValueConst[] argv, int magic);\r\n\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public delegate JSValue JSSetterCFunction(JSContext ctx, JSValueConst this_val, JSValueConst val);\r\n\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public delegate JSValue JSSetterCFunctionMagic(JSContext ctx, JSValueConst this_val, JSValueConst val, int magic);\r\n\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public delegate JSValue JSGetterCFunction(JSContext ctx, JSValueConst this_val);\r\n\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public delegate JSValue JSGetterCFunctionMagic(JSContext ctx, JSValueConst this_val, int magic);\r\n\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public delegate void JSLogCFunction(int level, [MarshalAs(UnmanagedType.LPStr)] string line);\r\n\r\n#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n#endif\r\n    public delegate void JSWaitingForDebuggerCFunction(JSContext ctx);\r\n\r\n    public partial class JSApi\r\n    {\r\n        public const int VERSION = 0x010704;\r\n        public const int CS_JSB_VERSION = 0xa; // expected dll version\r\n        public static readonly int SO_JSB_VERSION; // actual dll version\r\n\r\n#if JSB_NO_BIGNUM || ((UNITY_WSA || UNITY_WEBGL) && !UNITY_EDITOR) || JSB_WITH_V8_BACKEND\r\n        public const bool IsOperatorOverloadingSupported = false;\r\n#else\r\n        public const bool IsOperatorOverloadingSupported = true;\r\n#endif\r\n\r\n#if (UNITY_IPHONE || UNITY_WEBGL) && !UNITY_EDITOR\r\n\t    public const string JSBDLL = \"__Internal\";\r\n#else\r\n#if JSB_WITH_V8_BACKEND\r\n        public const string JSBDLL = \"v8-bridge\";\r\n#else\r\n        public const string JSBDLL = \"quickjs\";\r\n#endif\r\n#endif\r\n\r\n        public const int JS_TAG_FIRST = -11; /* first negative tag */\r\n        public const int JS_TAG_BIG_DECIMAL = -11;\r\n        public const int JS_TAG_BIG_INT = -10;\r\n        public const int JS_TAG_BIG_FLOAT = -9;\r\n        public const int JS_TAG_SYMBOL = -8;\r\n        public const int JS_TAG_STRING = -7;\r\n        public const int JS_TAG_MODULE = -3; /* used internally */\r\n        public const int JS_TAG_FUNCTION_BYTECODE = -2; /* used internally */\r\n        public const int JS_TAG_OBJECT = -1;\r\n\r\n        public const int JS_TAG_INT = 0;\r\n        public const int JS_TAG_BOOL = 1;\r\n        public const int JS_TAG_NULL = 2;\r\n        public const int JS_TAG_UNDEFINED = 3;\r\n        public const int JS_TAG_EXCEPTION = 6;\r\n        public const int JS_TAG_FLOAT64 = 7;\r\n\r\n        // #define JS_WRITE_OBJ_BYTECODE (1 << 0) /* allow function/module */\r\n        public const int JS_WRITE_OBJ_BYTECODE = 1 << 0; /* allow function/module */\r\n        public const int JS_WRITE_OBJ_BSWAP = 1 << 1; /* byte swapped output */\r\n        public const int JS_WRITE_OBJ_SAB = 1 << 2; /* allow SharedArrayBuffer */\r\n        public const int JS_WRITE_OBJ_REFERENCE = 1 << 3; /* allow object references to\r\n                                                             encode arbitrary object\r\n                                                             graph */\r\n        public const int JS_READ_OBJ_BYTECODE = 1 << 0; /* allow function/module */\r\n        public const int JS_READ_OBJ_ROM_DATA = 1 << 1; /* avoid duplicating 'buf' data */\r\n        public const int JS_READ_OBJ_SAB = 1 << 2; /* allow SharedArrayBuffer */\r\n        public const int JS_READ_OBJ_REFERENCE = 1 << 3; /* allow object references */\r\n\r\n        public static readonly JSValue[] EmptyValues = new JSValue[0];\r\n\r\n        private static JSValue JS_MKVAL(long tag, int val)\r\n        {\r\n            return new JSValue() { u = new JSValueUnion() { int32 = val }, tag = tag };\r\n        }\r\n\r\n        public static readonly JSValue JS_NULL = JS_MKVAL(JS_TAG_NULL, 0);\r\n        public static readonly JSValue JS_UNDEFINED = JS_MKVAL(JS_TAG_UNDEFINED, 0);\r\n        public static readonly JSValue JS_FALSE = JS_MKVAL(JS_TAG_BOOL, 0);\r\n        public static readonly JSValue JS_TRUE = JS_MKVAL(JS_TAG_BOOL, 1);\r\n\r\n        static JSApi()\r\n        {\r\n            SO_JSB_VERSION = JSB_Init();\r\n        }\r\n\r\n        public static bool IsValid()\r\n        {\r\n            return CS_JSB_VERSION == SO_JSB_VERSION;\r\n        }\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern JSRuntime JSB_NewRuntime(IntPtr class_finalizer);\r\n\r\n        public static JSRuntime JSB_NewRuntime(JSGCObjectFinalizer class_finalizer)\r\n        {\r\n            if (class_finalizer != null)\r\n            {\r\n#if JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n                GCHandle.Alloc(class_finalizer);\r\n#endif\r\n                var fn = Marshal.GetFunctionPointerForDelegate(class_finalizer);\r\n                return JSB_NewRuntime(fn);\r\n            }\r\n            return JSB_NewRuntime(IntPtr.Zero);\r\n        }\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern IntPtr JSB_GetRuntimeOpaque(JSRuntime rt);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern void JSB_SetRuntimeOpaque(JSRuntime rt, IntPtr opaque);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int JSB_FreeRuntime(JSRuntime rt);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSRuntime JS_GetRuntime(JSContext ctx);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSContext JS_NewContext(JSRuntime rt);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern void JS_FreeContext(JSContext ctx);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue JS_GetGlobalObject(JSContext ctx);\r\n\r\n        /// <summary>\r\n        /// return TRUE, FALSE or (-1) in case of exception\r\n        /// </summary>\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int JS_IsInstanceOf(JSContext ctx, JSValueConst val, JSValueConst obj);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JSValue JS_NewPromiseCapability(JSContext ctx, JSValue* resolving_funcs);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern void JS_SetHostPromiseRejectionTracker(JSRuntime rt, IntPtr cb, IntPtr opaque);\r\n\r\n        public static void JS_SetHostPromiseRejectionTracker(JSRuntime rt, JSHostPromiseRejectionTracker cb, IntPtr opaque)\r\n        {\r\n#if JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n            GCHandle.Alloc(cb);\r\n#endif\r\n            var fn = Marshal.GetFunctionPointerForDelegate(cb);\r\n            JS_SetHostPromiseRejectionTracker(rt, fn, opaque);\r\n        }\r\n\r\n        public static unsafe JSValue JS_NewPromiseCapability(JSContext ctx, JSValue[] resolving_funcs)\r\n        {\r\n            fixed (JSValue* ptr = resolving_funcs)\r\n            {\r\n                return JS_NewPromiseCapability(ctx, ptr);\r\n            }\r\n        }\r\n\r\n        public static unsafe JSValue JS_NewPromiseCapability(JSContext ctx, out JSValue on_resolve, out JSValue on_reject)\r\n        {\r\n            var resolving_funcs = stackalloc[] { JS_UNDEFINED, JS_UNDEFINED };\r\n            var promise = JS_NewPromiseCapability(ctx, resolving_funcs);\r\n            on_resolve = resolving_funcs[0];\r\n            on_reject = resolving_funcs[1];\r\n            return promise;\r\n        }\r\n\r\n        #region property\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue JS_GetPropertyUint32(JSContext ctx, JSValueConst this_obj, uint32_t idx);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue JS_GetPropertyInternal(JSContext ctx, JSValueConst obj, JSAtom prop,\r\n            JSValueConst receiver, JS_BOOL throw_ref_error);\r\n\r\n        // 增引用, 需要 FreeValue\r\n        public static JSValue JS_GetProperty(JSContext ctx, JSValueConst this_obj, JSAtom prop)\r\n        {\r\n            return JS_GetPropertyInternal(ctx, this_obj, prop, this_obj, 0);\r\n        }\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue JS_GetPropertyStr(JSContext ctx, JSValueConst this_obj,\r\n            [MarshalAs(UnmanagedType.LPStr)] string prop);\r\n\r\n        ///<summary>\r\n        /// 不会减引用, getter/setter 需要自己 FreeValue\r\n        ///</summary>\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern int JS_DefineProperty(JSContext ctx, JSValueConst this_obj, JSAtom prop, JSValueConst val, JSValueConst getter, JSValueConst setter, JSPropFlags flags);\r\n\r\n        public static int JS_DefineProperty(JSContext ctx, JSValueConst this_obj, JSAtom prop, JSValueConst getter, JSValueConst setter)\r\n        {\r\n            var flags = JSPropFlags.JS_PROP_CONFIGURABLE | JSPropFlags.JS_PROP_ENUMERABLE;\r\n            if (!getter.IsUndefined())\r\n            {\r\n                flags |= JSPropFlags.JS_PROP_HAS_GET;\r\n            }\r\n            if (!setter.IsUndefined())\r\n            {\r\n                flags |= JSPropFlags.JS_PROP_HAS_SET;\r\n                flags |= JSPropFlags.JS_PROP_WRITABLE;\r\n            }\r\n            return JS_DefineProperty(ctx, this_obj, prop, JS_UNDEFINED, getter, setter, flags);\r\n        }\r\n\r\n        // flags |=  JS_PROP_HAS_VALUE | JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_WRITABLE | JS_PROP_HAS_ENUMERABLE;\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern int JS_DefinePropertyValue(JSContext ctx, JSValueConst this_obj, JSAtom prop, JSValue val, JSPropFlags flags);\r\n\r\n        public static int JS_DefinePropertyValue(JSContext ctx, JSValueConst this_obj, JSAtom prop, JSValue val)\r\n        {\r\n            return JS_DefinePropertyValue(ctx, this_obj, prop, val, JSPropFlags.JS_PROP_C_W_E);\r\n        }\r\n\r\n        public static int JS_DefineConstPropertyValue(JSContext ctx, JSValueConst this_obj, JSAtom prop, JSValue val)\r\n        {\r\n            return JS_DefinePropertyValue(ctx, this_obj, prop, val, JSPropFlags.NONE);\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region error handling\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue JS_GetException(JSContext ctx);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL JS_IsError(JSContext ctx, JSValueConst val);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JSValue JSB_ThrowError(JSContext ctx, byte* buf, size_t buf_len);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JSValue JSB_ThrowTypeError(JSContext ctx, byte* msg);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JSValue JSB_ThrowInternalError(JSContext ctx, byte* msg);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JSValue JSB_ThrowRangeError(JSContext ctx, byte* msg);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JSValue JSB_ThrowReferenceError(JSContext ctx, byte* msg);\r\n\r\n        #endregion\r\n\r\n        #region new values\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue JSB_NewEmptyString(JSContext ctx);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JSValue JS_NewString(JSContext ctx, byte* str);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JSValue JS_NewStringLen(JSContext ctx, byte* buf, size_t buf_len);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue JSB_NewInt64(JSContext ctx, int64_t val);\r\n\r\n        public static JSValue JS_NewBool(JSContext ctx, bool val)\r\n        {\r\n            return val ? JS_TRUE : JS_FALSE;\r\n        }\r\n\r\n        public static JSValue JS_NewInt32(JSContext ctx, int val)\r\n        {\r\n            return JS_MKVAL(JS_TAG_INT, val);\r\n        }\r\n\r\n        public static JSValue __JS_NewFloat64(JSContext ctx, double d)\r\n        {\r\n            JSValue v = new JSValue();\r\n            v.tag = JS_TAG_FLOAT64;\r\n            v.u.float64 = d;\r\n            return v;\r\n        }\r\n\r\n        public static JSValue JS_NewUint32(JSContext ctx, uint32_t val)\r\n        {\r\n            JSValue v;\r\n            if (val <= 0x7fffffff)\r\n            {\r\n                v = JS_NewInt32(ctx, (int)val);\r\n            }\r\n            else\r\n            {\r\n                v = __JS_NewFloat64(ctx, val);\r\n            }\r\n\r\n            return v;\r\n        }\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = \"JSB_NewFloat64\")]\r\n        public static extern JSValue JS_NewFloat64(JSContext ctx, double d);\r\n\r\n        #endregion\r\n\r\n        #region atom support\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JSAtom JS_NewAtomLen(JSContext ctx, byte* str, size_t len);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JS_DupAtom(JSContext ctx, JSAtom v);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern void JS_FreeAtom(JSContext ctx, JSAtom v);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue JS_AtomToString(JSContext ctx, JSAtom atom);\r\n\r\n        #endregion\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue jsb_crossbind_constructor(JSContext ctx, JSValue new_target);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue JS_NewObject(JSContext ctx);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL JS_IsFunction(JSContext ctx, JSValueConst val);\r\n\r\n        /// <summary>\r\n        /// return 1:true 0:false \r\n        /// </summary>\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL JS_IsConstructor(JSContext ctx, JSValueConst val);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue JS_NewArray(JSContext ctx);\r\n\r\n        /// <summary>\r\n        /// return -1 if exception (proxy case) or TRUE/FALSE\r\n        /// </summary>\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int JS_IsArray(JSContext ctx, JSValueConst val);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern IntPtr JS_GetContextOpaque(JSContext ctx);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern void JS_SetContextOpaque(JSContext ctx, IntPtr opaque);\r\n\r\n        // 通过 Atom 命名创建函数\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern JSValue JSB_NewCFunctionMagic(JSContext ctx, IntPtr func, JSAtom atom, int length, JSCFunctionEnum cproto, int magic);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern JSValue JSB_NewCFunction(JSContext ctx, IntPtr func, JSAtom atom, int length, JSCFunctionEnum cproto, int magic);\r\n\r\n        public static JSValue JSB_NewGetter(JSContext ctx, JSGetterCFunctionMagic func, JSAtom atom, int magic)\r\n        {\r\n#if JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n            GCHandle.Alloc(func);\r\n#endif\r\n            var fn = Marshal.GetFunctionPointerForDelegate(func);\r\n            return JSB_NewCFunctionMagic(ctx, fn, atom, 0, JSCFunctionEnum.JS_CFUNC_getter_magic, magic);\r\n        }\r\n\r\n        public static JSValue JSB_NewSetter(JSContext ctx, JSSetterCFunctionMagic func, JSAtom atom, int magic)\r\n        {\r\n#if JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n            GCHandle.Alloc(func);\r\n#endif\r\n            var fn = Marshal.GetFunctionPointerForDelegate(func);\r\n            return JSB_NewCFunctionMagic(ctx, fn, atom, 1, JSCFunctionEnum.JS_CFUNC_setter_magic, magic);\r\n        }\r\n\r\n        public static JSValue JSB_NewConstructor(JSContext ctx, JSCFunctionMagic func, JSAtom atom, int magic)\r\n        {\r\n#if JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n            GCHandle.Alloc(func);\r\n#endif\r\n            var fn = Marshal.GetFunctionPointerForDelegate(func);\r\n            return JSB_NewCFunctionMagic(ctx, fn, atom, 0, JSCFunctionEnum.JS_CFUNC_constructor_magic, magic);\r\n        }\r\n\r\n        public static JSValue JSB_NewCFunctionMagic(JSContext ctx, JSCFunctionMagic func, JSAtom atom, int length, int magic)\r\n        {\r\n#if JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n            GCHandle.Alloc(func);\r\n#endif\r\n            var fn = Marshal.GetFunctionPointerForDelegate(func);\r\n            return JSB_NewCFunctionMagic(ctx, fn, atom, length, JSCFunctionEnum.JS_CFUNC_generic_magic, magic);\r\n        }\r\n\r\n        public static JSValue JSB_NewGetter(JSContext ctx, JSGetterCFunction func, JSAtom atom)\r\n        {\r\n            if (func == null)\r\n            {\r\n                return JS_UNDEFINED;\r\n            }\r\n#if JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n            GCHandle.Alloc(func);\r\n#endif\r\n            var fn = Marshal.GetFunctionPointerForDelegate(func);\r\n            return JSB_NewCFunction(ctx, fn, atom, 0, JSCFunctionEnum.JS_CFUNC_getter, 0);\r\n        }\r\n\r\n        public static JSValue JSB_NewSetter(JSContext ctx, JSSetterCFunction func, JSAtom atom)\r\n        {\r\n            if (func == null)\r\n            {\r\n                return JS_UNDEFINED;\r\n            }\r\n#if JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n            GCHandle.Alloc(func);\r\n#endif\r\n            var fn = Marshal.GetFunctionPointerForDelegate(func);\r\n            return JSB_NewCFunction(ctx, fn, atom, 1, JSCFunctionEnum.JS_CFUNC_setter, 0);\r\n        }\r\n\r\n        public static JSValue JSB_NewCFunction(JSContext ctx, JSCFunction func, JSAtom atom, int length)\r\n        {\r\n#if JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n            GCHandle.Alloc(func);\r\n#endif\r\n            var fn = Marshal.GetFunctionPointerForDelegate(func);\r\n            return JSB_NewCFunction(ctx, fn, atom, length, JSCFunctionEnum.JS_CFUNC_generic, 0);\r\n        }\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern void JS_SetConstructor(JSContext ctx, JSValueConst func_obj, JSValueConst proto);\r\n\r\n        /* return -1 in case of exception or TRUE or FALSE. Warning: 'val' is\r\n           freed by the function. 'flags' is a bitmask of JS_PROP_NO_ADD,\r\n           JS_PROP_THROW or JS_PROP_THROW_STRICT. If JS_PROP_NO_ADD is set,\r\n           the new property is not added and an error is raised. */\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int JS_SetPropertyInternal(JSContext ctx, JSValueConst this_obj, JSAtom prop, JSValue val, int flags);\r\n\r\n        public static int JS_SetProperty(JSContext ctx, JSValueConst this_obj, JSAtom prop, JSValue val)\r\n        {\r\n            return JS_SetPropertyInternal(ctx, this_obj, prop, val, (int)JSPropFlags.JS_PROP_THROW);\r\n        }\r\n\r\n        public static bool IsDebugMode()\r\n        {\r\n#if JSB_DEBUG\r\n            return true;\r\n#else\r\n            return false;\r\n#endif\r\n        }\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int JS_SetPropertyUint32(JSContext ctx, JSValueConst this_obj, uint32_t idx, JSValue val);\r\n\r\n        // [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]\r\n        // public static extern int JS_SetPropertyStr(JSContext ctx, [In] JSValueConst this_obj, [MarshalAs(UnmanagedType.LPStr)] string prop, JSValue val);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int JS_HasProperty(JSContext ctx, JSValueConst this_obj, JSAtom prop);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JSValue JS_ParseJSON(JSContext ctx, byte* buf, size_t buf_len, byte* filename);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue JS_JSONStringify(JSContext ctx, JSValueConst obj, JSValueConst replacer, JSValueConst space0);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern unsafe JSValue JS_CallConstructor(JSContext ctx, JSValueConst func_obj, int argc, JSValueConst* argv);\r\n\r\n        public static unsafe JSValue JS_CallConstructor(JSContext ctx, JSValueConst func_obj)\r\n        {\r\n            return JS_CallConstructor(ctx, func_obj, 0, (JSValueConst*)0);\r\n        }\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JSValue JS_Call(JSContext ctx, JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst* argv);\r\n\r\n        // [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        // public static extern JSValue JS_Call(JSContext ctx, JSValueConst func_obj, JSValueConst this_obj, int argc, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] JSValueConst[] argv);\r\n\r\n        public static unsafe JSValue JS_Call(JSContext ctx, JSValueConst func_obj, JSValueConst this_obj)\r\n        {\r\n            return JS_Call(ctx, func_obj, this_obj, 0, (JSValueConst*)0);\r\n        }\r\n\r\n        public static unsafe JSValue JS_Call(JSContext ctx, JSValueConst func_obj)\r\n        {\r\n            return JS_Call(ctx, func_obj, JS_UNDEFINED, 0, (JSValueConst*)0);\r\n        }\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JSValue JS_Invoke(JSContext ctx, JSValueConst this_val, JSAtom atom, int argc, JSValueConst* argv);\r\n\r\n        public static unsafe JSValue JS_Invoke(JSContext ctx, JSValueConst this_val, JSAtom atom)\r\n        {\r\n            return JS_Invoke(ctx, this_val, atom, 0, (JSValueConst*)0);\r\n        }\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int JS_SetPrototype(JSContext ctx, JSValueConst obj, JSValueConst proto_val);\r\n\r\n        // 2020-04-12: 返回值不需要 FreeValue\r\n        // 2020-07-05: 返回值需要 FreeValue\r\n        // [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        // public static extern JSValueConst JS_GetPrototype(JSContext ctx, JSValueConst val);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern void JS_RunGC(JSRuntime rt);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int JS_ExecutePendingJob(JSRuntime rt, out JSContext pctx);\r\n\r\n#if JSB_WITH_V8_BACKEND\r\n        //TODO unity-jsb: [IMPORTANT] implement it in v8-bridge later\r\n        public static int JS_IsJobPending(JSRuntime rt, out JSContext pctx) { return 0; }\r\n#else\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int JS_IsJobPending(JSRuntime rt, out JSContext pctx);\r\n#endif\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int JS_ToBool(JSContext ctx, JSValueConst val);\r\n\r\n        /// <summary>\r\n        /// 返回 &lt; 0 表示失败, 0 表示成功\r\n        /// </summary>\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int JS_ToInt32(JSContext ctx, out int pres, JSValue val);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int JS_ToInt64(JSContext ctx, out int64_t pres, JSValueConst val);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int JS_ToBigInt64(JSContext ctx, out int64_t pres, JSValueConst val);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int JS_ToIndex(JSContext ctx, out uint64_t plen, JSValueConst val);\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int JS_ToFloat64(JSContext ctx, out double pres, JSValueConst val);\r\n\r\n        /* return 0 for success, otherwise -1 in case of exception */\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JS_BOOL JSB_ToUint32(JSContext ctx, out uint32_t pres, JSValueConst val);\r\n\r\n        /* free raw memory directly allocated by jsruntime */\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern void js_free(JSContext ctx, IntPtr ptr);\r\n\r\n        //TODO [v8_integrating] get rid of using ReadObject/WriteObject for better compatibility between different backends\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern IntPtr JS_WriteObject(JSContext ctx, out size_t psize, JSValueConst obj, int flags);\r\n\r\n        //TODO [v8_integrating] get rid of using ReadObject/WriteObject for better compatibility between different backends\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern unsafe JSValue JS_ReadObject(JSContext ctx, byte* buf, size_t buf_len, int flags);\r\n\r\n        public static unsafe JSValue JS_ReadByteCode(JSContext ctx, byte* buf, size_t buf_len)\r\n        {\r\n            return JS_ReadObject(ctx, buf, buf_len, JS_READ_OBJ_BYTECODE);\r\n        }\r\n\r\n        public static unsafe IntPtr JS_WriteByteCode(JSContext ctx, out size_t psize, JSValueConst obj)\r\n        {\r\n            return JS_WriteObject(ctx, out psize, obj, JS_WRITE_OBJ_BYTECODE);\r\n        }\r\n\r\n        public static unsafe JSValue JSB_Deserialize(JSContext ctx, byte* buf, size_t buf_len)\r\n        {\r\n            return JS_ReadObject(ctx, buf, buf_len, JS_READ_OBJ_REFERENCE);\r\n        }\r\n\r\n        public static unsafe IntPtr JSB_Serialize(JSContext ctx, out size_t psize, JSValueConst obj)\r\n        {\r\n            return JS_WriteObject(ctx, out psize, obj, JS_WRITE_OBJ_REFERENCE);\r\n        }\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern unsafe JSValue JS_Eval(JSContext ctx, byte* input, size_t input_len, byte* filename, JSEvalFlags eval_flags);\r\n\r\n        //TODO [v8_integrating] this api is only for the es module which will be removed later\r\n        public static unsafe JSValue JS_EvalModule(JSContext ctx, byte* input, size_t input_len, byte* filename)\r\n        {\r\n            return JS_Eval(ctx, input, input_len, filename, JSEvalFlags.JS_EVAL_TYPE_MODULE | JSEvalFlags.JS_EVAL_FLAG_STRICT);\r\n        }\r\n\r\n        //TODO [v8_integrating] this api is only for the es module which will be removed later \r\n        public static unsafe JSValue JS_CompileModule(JSContext ctx, byte* input, size_t input_len, byte* filename)\r\n        {\r\n            return JS_Eval(ctx, input, input_len, filename, JSEvalFlags.JS_EVAL_TYPE_MODULE | JSEvalFlags.JS_EVAL_FLAG_STRICT | JSEvalFlags.JS_EVAL_FLAG_COMPILE_ONLY);\r\n        }\r\n\r\n        public static unsafe JSValue JS_EvalSource(JSContext ctx, byte* input, size_t input_len, byte* filename)\r\n        {\r\n            return JS_Eval(ctx, input, input_len, filename, JSEvalFlags.JS_EVAL_TYPE_GLOBAL | JSEvalFlags.JS_EVAL_FLAG_STRICT);\r\n        }\r\n\r\n        public static unsafe JSValue JS_CompileSource(JSContext ctx, byte* input, size_t input_len, byte* filename)\r\n        {\r\n            return JS_Eval(ctx, input, input_len, filename, JSEvalFlags.JS_EVAL_TYPE_GLOBAL | JSEvalFlags.JS_EVAL_FLAG_STRICT | JSEvalFlags.JS_EVAL_FLAG_COMPILE_ONLY);\r\n        }\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSValue JS_EvalFunction(JSContext ctx, JSValue fun_obj);\r\n\r\n        /* load the dependencies of the module 'obj'. Useful when JS_ReadObject()\r\n           returns a module. */\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern int JS_ResolveModule(JSContext ctx, JSValueConst obj);\r\n\r\n        public static bool JS_IsNumber(JSValueConst v)\r\n        {\r\n            var tag = v.tag;\r\n            return tag == JS_TAG_INT || tag == JS_TAG_FLOAT64;\r\n        }\r\n\r\n        public static bool JS_IsBool(JSValueConst v)\r\n        {\r\n            return v.tag == JS_TAG_BOOL;\r\n        }\r\n\r\n        public static bool JS_IsNull(JSValueConst v)\r\n        {\r\n            return v.tag == JS_TAG_NULL;\r\n        }\r\n\r\n        public static bool JS_IsUndefined(JSValueConst v)\r\n        {\r\n            return v.tag == JS_TAG_UNDEFINED;\r\n        }\r\n\r\n        public static bool JS_IsException(JSValueConst v)\r\n        {\r\n            return (v.tag == JS_TAG_EXCEPTION);\r\n        }\r\n\r\n        public static bool JS_IsString(JSValueConst v)\r\n        {\r\n            return v.tag == JS_TAG_STRING;\r\n        }\r\n\r\n        public static bool JS_IsObject(JSValueConst v)\r\n        {\r\n            return v.tag == JS_TAG_OBJECT;\r\n        }\r\n\r\n        #region ref counting\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = \"JSB_DupValue\")]\r\n        public static extern JSValue JS_DupValue(JSContext ctx, JSValueConst v);\r\n\r\n        /// <summary>\r\n        /// dereference a JSValue (must be called in the script thread only)\r\n        /// </summary>\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = \"JSB_FreeValue\")]\r\n        public static extern void JS_FreeValue(JSContext ctx, JSValue v);\r\n\r\n        /// <summary>\r\n        /// dereference the JSValues (must be called in the script thread only)\r\n        /// </summary>\r\n        public static void JS_FreeValue(JSContext ctx, JSValue[] v)\r\n        {\r\n            for (int i = 0, len = v.Length; i < len; i++)\r\n            {\r\n                JS_FreeValue(ctx, v[i]);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// dereference the JSValues (must be called in the script thread only)\r\n        /// </summary>\r\n        public static unsafe void JS_FreeValue(JSContext ctx, int count, JSValue* vs)\r\n        {\r\n            for (int i = 0, len = count; i < len; i++)\r\n            {\r\n                JS_FreeValue(ctx, vs[i]);\r\n            }\r\n        }\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern void JSB_FreeValueRT(JSRuntime rt, JSValue v);\r\n\r\n        #endregion\r\n\r\n        #region unity base\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JSB_ATOM_Proxy();\r\n\r\n        public static readonly JSAtom JS_ATOM_Proxy = JSB_ATOM_Proxy();\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JSB_ATOM_constructor();\r\n\r\n        public static readonly JSAtom JS_ATOM_constructor = JSB_ATOM_constructor();\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JSB_ATOM_Number();\r\n\r\n        public static readonly JSAtom JS_ATOM_Number = JSB_ATOM_Number();\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JSB_ATOM_Object();\r\n\r\n        public static readonly JSAtom JS_ATOM_Object = JSB_ATOM_Object();\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JSB_ATOM_String();\r\n\r\n        public static readonly JSAtom JS_ATOM_String = JSB_ATOM_String();\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JSB_ATOM_Function();\r\n\r\n        public static readonly JSAtom JS_ATOM_Function = JSB_ATOM_Function();\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JSB_ATOM_Error();\r\n\r\n        public static readonly JSAtom JS_ATOM_Error = JSB_ATOM_Error();\r\n\r\n#if JSB_NO_BIGNUM || ((UNITY_WSA || UNITY_WEBGL) && !UNITY_EDITOR)\r\n        public static void JS_AddIntrinsicOperators(JSContext ctx) {}\r\n        public static readonly JSAtom JS_ATOM_Operators;\r\n        public static readonly JSAtom JS_ATOM_Symbol_operatorSet;\r\n#else \r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern void JS_AddIntrinsicOperators(JSContext ctx);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JSB_ATOM_Operators();\r\n\r\n        public static readonly JSAtom JS_ATOM_Operators = JSB_ATOM_Operators();\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JSB_ATOM_Symbol_operatorSet();\r\n\r\n        // only available CONFIG_BIGNUM\r\n        public static readonly JSAtom JS_ATOM_Symbol_operatorSet = JSB_ATOM_Symbol_operatorSet();\r\n#endif\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JSB_ATOM_name();\r\n\r\n        public static readonly JSAtom JS_ATOM_name = JSB_ATOM_name();\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JSB_ATOM_message();\r\n\r\n        public static readonly JSAtom JS_ATOM_message = JSB_ATOM_message();\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JSB_ATOM_fileName();\r\n\r\n        public static readonly JSAtom JS_ATOM_fileName = JSB_ATOM_fileName();\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JSB_ATOM_lineNumber();\r\n\r\n        public static readonly JSAtom JS_ATOM_lineNumber = JSB_ATOM_lineNumber();\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JSB_ATOM_length();\r\n\r\n        public static readonly JSAtom JS_ATOM_length = JSB_ATOM_length();\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JSB_ATOM_stack();\r\n\r\n        public static readonly JSAtom JS_ATOM_stack = JSB_ATOM_stack();\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern JSAtom JSB_ATOM_prototype();\r\n\r\n        public static readonly JSAtom JS_ATOM_prototype = JSB_ATOM_prototype();\r\n\r\n        /// <summary>\r\n        /// init the native library, return the version tag of it\r\n        /// </summary>\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern int JSB_Init();\r\n\r\n        // [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        // private static extern JSClassID JSB_NewClass(JSRuntime rt, JSClassID class_id, [MarshalAs(UnmanagedType.LPStr)] string class_name, IntPtr finalizer);\r\n\r\n        //         public static JSClassID JS_NewClass(JSRuntime rt, JSClassFinalizer class_finalizer)\r\n        //         {\r\n        // #if JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n        //             GCHandle.Alloc(class_finalizer);\r\n        // #endif\r\n        //             var fn_ptr = Marshal.GetFunctionPointerForDelegate(class_finalizer);\r\n        //             return JSApi.JSB_NewClass(rt, JSApi.JSB_GetBridgeClassID(), \"CSharpClass\", fn_ptr);\r\n        //         }\r\n\r\n        #endregion\r\n\r\n        #region string\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern IntPtr JS_ToCStringLen2(JSContext ctx, out size_t len, [In] JSValue val, [MarshalAs(UnmanagedType.Bool)] bool cesu8);\r\n\r\n        public static IntPtr JS_ToCStringLen(JSContext ctx, out size_t len, JSValue val)\r\n        {\r\n            return JS_ToCStringLen2(ctx, out len, val, false);\r\n        }\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern void JS_FreeCString(JSContext ctx, IntPtr ptr);\r\n\r\n        #endregion\r\n\r\n        #region critical\r\n\r\n        /* return < 0, 0 or > 0 */\r\n        // [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        // public static extern int js_string_compare(JSContext ctx, /*const JSString*/ IntPtr p1, /*const JSString*/ IntPtr p2);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe IntPtr js_strndup(JSContext ctx, byte* s, size_t n);\r\n\r\n        #endregion\r\n\r\n        #region array buffer\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern IntPtr JS_GetArrayBuffer(JSContext ctx, out size_t psize, JSValueConst obj);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JSValue JS_NewArrayBufferCopy(JSContext ctx, byte* buf, size_t len);\r\n\r\n        #endregion\r\n\r\n        #region diagnostics\r\n\r\n#if JSB_WITH_V8_BACKEND\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe void JS_OpenDebugger(JSContext ctx, int port);\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JS_BOOL JS_IsDebuggerConnected(JSContext ctx);\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe JS_BOOL JS_IsDebuggerOpen(JSContext ctx);\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe void JS_CloseDebugger(JSContext ctx);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern unsafe void JS_SetLogFunc(JSContext ctx, IntPtr func);\r\n        public static void JS_SetLogFunc(JSContext ctx, JSLogCFunction cb)\r\n        {\r\n#if JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n            GCHandle.Alloc(cb);\r\n#endif\r\n            var fn = Marshal.GetFunctionPointerForDelegate(cb);\r\n            JS_SetLogFunc(ctx, fn);\r\n        }\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern unsafe void JS_SetWaitingForDebuggerFunc(JSContext ctx, IntPtr func);\r\n        public static void JS_SetWaitingForDebuggerFunc(JSContext ctx, JSWaitingForDebuggerCFunction cb)\r\n        {\r\n            if (cb != null)\r\n            {\r\n#if JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n                GCHandle.Alloc(cb);\r\n#endif\r\n                var fn = Marshal.GetFunctionPointerForDelegate(cb);\r\n                JS_SetWaitingForDebuggerFunc(ctx, fn);\r\n            }\r\n            else\r\n            {\r\n                JS_SetWaitingForDebuggerFunc(ctx, IntPtr.Zero);\r\n            }\r\n        }\r\n#else \r\n        public static void JS_OpenDebugger(JSContext ctx, int port) { }\r\n        public static JS_BOOL JS_IsDebuggerConnected(JSContext ctx) { return 0; }\r\n        public static JS_BOOL JS_IsDebuggerOpen(JSContext ctx) { return 0; }\r\n        public static void JS_CloseDebugger(JSContext ctx) { }\r\n        public static void JS_SetLogFunc(JSContext ctx, JSLogCFunction cb) { }\r\n        public static void JS_SetWaitingForDebuggerFunc(JSContext ctx, JSWaitingForDebuggerCFunction cb) { }\r\n#endif // end JSB_WITH_V8_BACKEND\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        public static extern unsafe void JS_ComputeMemoryUsage(JSRuntime rt, JSMemoryUsage* s);\r\n\r\n        [DllImport(JSBDLL, CallingConvention = CallingConvention.Cdecl)]\r\n        private static extern unsafe void JS_SetInterruptHandler(JSRuntime rt, IntPtr cb, IntPtr opaque);\r\n\r\n        public static void JS_SetInterruptHandler(JSRuntime rt, JSInterruptHandler cb, IntPtr opaque)\r\n        {\r\n#if JSB_UNITYLESS || (UNITY_WSA && !UNITY_EDITOR)\r\n            GCHandle.Alloc(cb);\r\n#endif\r\n            var fn = Marshal.GetFunctionPointerForDelegate(cb);\r\n            JS_SetInterruptHandler(rt, fn, opaque);\r\n        }\r\n        #endregion\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSApi.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: c02aeb4da3ff9974a977814921e36deb\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSAtom.cs",
    "content": "﻿using System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Native\r\n{\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public struct JSAtom\r\n    {\r\n        public static readonly JSAtom Null;\r\n        \r\n        private int _value;\r\n\r\n        public bool IsValid => _value != 0;\r\n\r\n        /// <inheritdoc/>\r\n        public override int GetHashCode()\r\n        {\r\n            return _value.GetHashCode();\r\n        }\r\n\r\n        /// <inheritdoc/>\r\n        public override string ToString()\r\n        {\r\n            return _value.ToString();\r\n        }\r\n\r\n        /// <inheritdoc/>\r\n        public override bool Equals(object obj)\r\n        {\r\n            if (obj is JSAtom)\r\n            {\r\n                return ((JSAtom) obj)._value == _value;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public static bool operator ==(JSAtom a, JSAtom b)\r\n        {\r\n            return a._value == b._value;\r\n        }\r\n\r\n        public static bool operator !=(JSAtom a, JSAtom b)\r\n        {\r\n            return !(a == b);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSAtom.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: d49bc85e6eb74433a5690dd7d1e24b85\r\ntimeCreated: 1590740142"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSCFunctionEnum.cs",
    "content": "﻿namespace QuickJS.Native\r\n{\r\n    internal enum JSCFunctionEnum\r\n    {\r\n        /* XXX: should rename for namespace isolation */\r\n        JS_CFUNC_generic,\r\n        JS_CFUNC_generic_magic,\r\n        JS_CFUNC_constructor, // unused in jsb\r\n        JS_CFUNC_constructor_magic,\r\n        JS_CFUNC_constructor_or_func, // unused in jsb\r\n        JS_CFUNC_constructor_or_func_magic, // unused in jsb\r\n        JS_CFUNC_f_f, // unused in jsb\r\n        JS_CFUNC_f_f_f, // unused in jsb\r\n        JS_CFUNC_getter,\r\n        JS_CFUNC_setter,\r\n        JS_CFUNC_getter_magic,\r\n        JS_CFUNC_setter_magic,\r\n        JS_CFUNC_iterator_next, // unused in jsb\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSCFunctionEnum.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 83c6f0376dcf4d118286c0f9066f7c49\r\ntimeCreated: 1590732945"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSClassID.cs",
    "content": "﻿using System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Native\r\n{\r\n    /// <summary>\r\n    /// JSClassID is identical to uint32\r\n    /// </summary>\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public struct JSClassID\r\n    {\r\n        private uint _value;\r\n\r\n        public static implicit operator JSClassID(uint value)\r\n        {\r\n            return new JSClassID {_value = value};\r\n        }\r\n\r\n        public static implicit operator uint(JSClassID value)\r\n        {\r\n            return value._value;\r\n        }\r\n\r\n        public override int GetHashCode()\r\n        {\r\n            return _value.GetHashCode();\r\n        }\r\n\r\n        public override string ToString()\r\n        {\r\n            return _value.ToString();\r\n        }\r\n\r\n        public override bool Equals(object obj)\r\n        {\r\n            if (obj is JSClassID)\r\n            {\r\n                return ((JSClassID) obj)._value == _value;\r\n            }\r\n\r\n            return false;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSClassID.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 74f857510b654d48a16adab5b0f34555\r\ntimeCreated: 1590740331"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSContext.cs",
    "content": "﻿using System;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Native\r\n{\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public struct JSContext\r\n    {\r\n        public static readonly JSContext Null;\r\n\r\n        private unsafe void* _ptr;\r\n\r\n        public unsafe bool IsValid()\r\n        {\r\n            return _ptr != (void*)0;\r\n        }\r\n\r\n        public unsafe bool IsContext(JSContext c)\r\n        {\r\n            return _ptr == c._ptr;\r\n        }\r\n\r\n        /// <summary>\r\n        /// useful if you need a string from JS Exception and want to rethrow it as a C# Exception\r\n        /// </summary>\r\n        public string GetExceptionString()\r\n        {\r\n            var ex = JSApi.JS_GetException(this);\r\n            var err_fileName = JSApi.JS_GetProperty(this, ex, JSApi.JS_ATOM_fileName);\r\n            var err_lineNumber = JSApi.JS_GetProperty(this, ex, JSApi.JS_ATOM_lineNumber);\r\n            var err_message = JSApi.JS_GetProperty(this, ex, JSApi.JS_ATOM_message);\r\n            var err_stack = JSApi.JS_GetProperty(this, ex, JSApi.JS_ATOM_stack);\r\n\r\n            try\r\n            {\r\n                var fileName = JSApi.GetString(this, err_fileName);\r\n                var lineNumber = JSApi.GetString(this, err_lineNumber);\r\n                var message = JSApi.GetString(this, err_message);\r\n                var stack = JSApi.GetString(this, err_stack);\r\n                var exceptionString = string.Format(\"[JS] {0}:{1} {2}\\n{3}\", fileName, lineNumber, message, stack);\r\n\r\n                return exceptionString;\r\n            }\r\n            finally\r\n            {\r\n\r\n                JSApi.JS_FreeValue(this, err_fileName);\r\n                JSApi.JS_FreeValue(this, err_lineNumber);\r\n                JSApi.JS_FreeValue(this, err_message);\r\n                JSApi.JS_FreeValue(this, err_stack);\r\n                JSApi.JS_FreeValue(this, ex);\r\n            }\r\n        }\r\n\r\n        public override unsafe int GetHashCode()\r\n        {\r\n            return (int)_ptr;\r\n        }\r\n\r\n        public override unsafe bool Equals(object obj)\r\n        {\r\n            if (obj is JSContext)\r\n            {\r\n                var t = (JSContext)obj;\r\n                return t._ptr == _ptr;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public static unsafe bool operator ==(JSContext a, JSContext b)\r\n        {\r\n            return a._ptr == b._ptr;\r\n        }\r\n\r\n        public static bool operator !=(JSContext a, JSContext b)\r\n        {\r\n            return !(a == b);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSContext.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 2e23ec6ddc3c4e7c85da5a63fd939e00\r\ntimeCreated: 1590736213"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSEvalFlags.cs",
    "content": "﻿using System;\r\n\r\nnamespace QuickJS.Native\r\n{\r\n    [Flags]\r\n    internal enum JSEvalFlags\r\n    {\r\n        /* JS_Eval() flags */\r\n        JS_EVAL_TYPE_GLOBAL = (0 << 0) /* global code (default) */,\r\n        JS_EVAL_TYPE_MODULE = (1 << 0) /* module code */,\r\n        JS_EVAL_TYPE_DIRECT = (2 << 0) /* direct call (internal use) */,\r\n        JS_EVAL_TYPE_INDIRECT = (3 << 0) /* indirect call (internal use) */,\r\n        JS_EVAL_TYPE_MASK = (3 << 0),\r\n\r\n        JS_EVAL_FLAG_STRICT = (1 << 3) /* force 'strict' mode */,\r\n        JS_EVAL_FLAG_STRIP = (1 << 4) /* force 'strip' mode */,\r\n\r\n        /* compile but do not run. The result is an object with a\r\n           JS_TAG_FUNCTION_BYTECODE or JS_TAG_MODULE tag. It can be executed\r\n           with JS_EvalFunction(). */\r\n        JS_EVAL_FLAG_COMPILE_ONLY = (1 << 5),\r\n\r\n        /* don't include the stack frames before this eval in the Error() backtraces */\r\n        JS_EVAL_FLAG_BACKTRACE_BARRIER = (1 << 6),\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSEvalFlags.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 9b302db1caee4cb0b874864b5bed9304\r\ntimeCreated: 1590743896"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSGPNFlags.cs",
    "content": "using System;\r\n\r\nnamespace QuickJS.Native\r\n{\r\n    // #define JS_GPN_STRING_MASK  (1 << 0)\r\n    // #define JS_GPN_SYMBOL_MASK  (1 << 1)\r\n    // #define JS_GPN_PRIVATE_MASK (1 << 2)\r\n    // /* only include the enumerable properties */\r\n    // #define JS_GPN_ENUM_ONLY    (1 << 4)\r\n    // /* set theJSPropertyEnum.is_enumerable field */\r\n    // #define JS_GPN_SET_ENUM     (1 << 5)\r\n\r\n    [Flags]\r\n    internal enum JSGPNFlags : int\r\n    {\r\n        JS_GPN_STRING_MASK = (1 << 0),\r\n        JS_GPN_SYMBOL_MASK = (1 << 1),\r\n        JS_GPN_PRIVATE_MASK = (1 << 2),\r\n        JS_GPN_ENUM_ONLY = (1 << 4),\r\n        JS_GPN_SET_ENUM = (1 << 5),\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSGPNFlags.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 97db2551bff42ec46aba33f4177370a6\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSMemoryUsage.cs",
    "content": "using System;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Native\r\n{\r\n    using int64_t = Int64;\r\n\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public struct JSMemoryUsage\r\n    {\r\n        public int64_t malloc_size, malloc_limit, memory_used_size;\r\n        public int64_t malloc_count;\r\n        public int64_t memory_used_count;\r\n        public int64_t atom_count, atom_size;\r\n        public int64_t str_count, str_size;\r\n        public int64_t obj_count, obj_size;\r\n        public int64_t prop_count, prop_size;\r\n        public int64_t shape_count, shape_size;\r\n        public int64_t js_func_count, js_func_size, js_func_code_size;\r\n        public int64_t js_func_pc2line_count, js_func_pc2line_size;\r\n        public int64_t c_func_count, array_count;\r\n        public int64_t fast_array_count, fast_array_elements;\r\n        public int64_t binary_object_count, binary_object_size;\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSMemoryUsage.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: e6d49084ba8d4434ebe3e68c970266c7\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSModuleDef.cs",
    "content": "﻿using System;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Native\r\n{\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public struct JSModuleDef\r\n    {\r\n        private unsafe void* _value;\r\n        \r\n        public static readonly JSModuleDef Null;\r\n\r\n        public unsafe JSModuleDef(IntPtr ptr)\r\n        {\r\n            _value = ptr.ToPointer();\r\n        }\r\n        \r\n        /// <inheritdoc/>\r\n        public override unsafe int GetHashCode()\r\n        {\r\n            return (int) _value;\r\n        }\r\n\r\n        public override unsafe bool Equals(object obj)\r\n        {\r\n            if (obj is JSModuleDef)\r\n            {\r\n                return ((JSModuleDef) obj)._value == _value;\r\n            }\r\n\r\n            return false;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSModuleDef.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 2017b932c99f4d9d948b4f689ba79b70\r\ntimeCreated: 1590742780"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSPropFlags.cs",
    "content": "﻿using System;\r\n\r\nnamespace QuickJS.Native\r\n{\r\n    //TODO [v8-integrating] not to expose this enum out of JSApi module\r\n    [Flags]\r\n    internal enum JSPropFlags\r\n    {\r\n        /* flags for object properties */\r\n        JS_PROP_CONFIGURABLE = (1 << 0),\r\n        JS_PROP_WRITABLE = (1 << 1),\r\n        JS_PROP_ENUMERABLE = (1 << 2),\r\n        JS_PROP_C_W_E = (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE | JS_PROP_ENUMERABLE),\r\n        JS_PROP_LENGTH = (1 << 3) /* used internally in Arrays */,\r\n        JS_PROP_TMASK = (3 << 4) /* mask for NORMAL, GETSET, VARREF, AUTOINIT */,\r\n        JS_PROP_NORMAL = (0 << 4),\r\n        JS_PROP_GETSET = (1 << 4),\r\n        JS_PROP_VARREF = (2 << 4) /* used internally */,\r\n        JS_PROP_AUTOINIT = (3 << 4) /* used internally */,\r\n\r\n        /* flags for JS_DefineProperty */\r\n        JS_PROP_HAS_SHIFT = 8,\r\n        JS_PROP_HAS_CONFIGURABLE = (1 << 8),\r\n        JS_PROP_HAS_WRITABLE = (1 << 9),\r\n        JS_PROP_HAS_ENUMERABLE = (1 << 10),\r\n        JS_PROP_HAS_GET = (1 << 11),\r\n        JS_PROP_HAS_SET = (1 << 12),\r\n        JS_PROP_HAS_VALUE = (1 << 13),\r\n\r\n        /* throw an exception if false would be returned\r\n           (JS_DefineProperty/JS_SetProperty) */\r\n        JS_PROP_THROW = (1 << 14),\r\n\r\n        /* throw an exception if false would be returned in strict mode\r\n           (JS_SetProperty) */\r\n        JS_PROP_THROW_STRICT = (1 << 15),\r\n\r\n        JS_PROP_NO_ADD = (1 << 16) /* internal use */,\r\n        JS_PROP_NO_EXOTIC = (1 << 17) /* internal use */,\r\n        \r\n        // custom values\r\n        CONST_VALUE = JS_PROP_HAS_VALUE | JS_PROP_ENUMERABLE, \r\n        DEFAULT = JS_PROP_CONFIGURABLE | JS_PROP_ENUMERABLE, \r\n        NONE = 0, \r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSPropFlags.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 7857dbad4a004920b18d75aff51035dc\r\ntimeCreated: 1590732988"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSPropertyEnum.cs",
    "content": "using System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Native\r\n{\r\n    using JS_BOOL = System.Int32;\r\n\r\n    /*\r\n        typedef struct JSPropertyEnum {\r\n            JS_BOOL is_enumerable;\r\n            JSAtom atom;\r\n        } JSPropertyEnum;\r\n    */\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public struct JSPropertyEnum\r\n    {\r\n        public JS_BOOL is_enumerable;\r\n        public JSAtom atom;\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSPropertyEnum.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: afd064b77cd6e0e41a14d9fcdd061d29\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSRuntime.cs",
    "content": "﻿using System;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Native\r\n{\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public struct JSRuntime\r\n    {\r\n        private unsafe void* _ptr;\r\n\r\n        public static readonly JSRuntime Null;\r\n\r\n        public unsafe bool IsValid()\r\n        {\r\n            return _ptr != (void*) 0;\r\n        }\r\n\r\n        public override unsafe int GetHashCode()\r\n        {\r\n            return (int)_ptr;\r\n        }\r\n\r\n        public override unsafe bool Equals(object obj)\r\n        {\r\n            if (obj is JSRuntime)\r\n            {\r\n                var t = (JSRuntime)obj;\r\n                return t._ptr == _ptr;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public override unsafe string ToString()\r\n        {\r\n            return string.Format(\"JSRuntime:{0}\", (IntPtr)_ptr);\r\n        }\r\n\r\n        public static unsafe bool operator ==(JSRuntime a, JSRuntime b)\r\n        {\r\n            return a._ptr == b._ptr;\r\n        }\r\n\r\n        public static unsafe bool operator !=(JSRuntime a, JSRuntime b)\r\n        {\r\n            return a._ptr != b._ptr;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSRuntime.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 1e8afad12a4440c1a2ddbe7d93dfb2bf\r\ntimeCreated: 1590736351"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSValue.cs",
    "content": "﻿using System;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Native\r\n{\r\n    [StructLayout(LayoutKind.Explicit)]\r\n    public struct JSValueUnion\r\n    {\r\n        [FieldOffset(0)] public int int32;\r\n\r\n        [FieldOffset(0)] public double float64;\r\n\r\n        [FieldOffset(0)] public IntPtr ptr;\r\n    }\r\n\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public struct JSValue\r\n    {\r\n        public JSValueUnion u; // IntPtr\r\n        public long tag;\r\n\r\n        public bool IsFunctionByteCode()\r\n        {\r\n            return tag == JSApi.JS_TAG_FUNCTION_BYTECODE;\r\n        }\r\n\r\n        public bool IsException()\r\n        {\r\n            // return JSApi.JS_IsException(this);\r\n            return tag == JSApi.JS_TAG_EXCEPTION;\r\n        }\r\n\r\n        public bool IsModule()\r\n        {\r\n            return tag == JSApi.JS_TAG_MODULE;\r\n        }\r\n\r\n        public bool IsNullish()\r\n        {\r\n            // return JSApi.JS_IsNull(this) || JSApi.JS_IsUndefined(this);\r\n            return tag == JSApi.JS_TAG_NULL || tag == JSApi.JS_TAG_UNDEFINED;\r\n        }\r\n\r\n        public bool IsNull()\r\n        {\r\n            return tag == JSApi.JS_TAG_NULL;\r\n        }\r\n\r\n        public bool IsUndefined()\r\n        {\r\n            return tag == JSApi.JS_TAG_UNDEFINED;\r\n        }\r\n\r\n        public bool IsBoolean()\r\n        {\r\n            return tag == JSApi.JS_TAG_BOOL;\r\n        }\r\n\r\n        public bool IsString()\r\n        {\r\n            return tag == JSApi.JS_TAG_STRING;\r\n        }\r\n\r\n        public bool IsSymbol()\r\n        {\r\n            return tag == JSApi.JS_TAG_SYMBOL;\r\n        }\r\n\r\n        public bool IsNumber()\r\n        {\r\n            // return JSApi.JS_IsNumber(this);\r\n            return tag == JSApi.JS_TAG_INT || tag == JSApi.JS_TAG_FLOAT64;\r\n        }\r\n\r\n        public bool IsObject()\r\n        {\r\n            // return JSApi.JS_IsObject(this);\r\n            return tag == JSApi.JS_TAG_OBJECT;\r\n        }\r\n\r\n        public override int GetHashCode()\r\n        {\r\n            return u.int32 << 2 | (int)tag;\r\n        }\r\n\r\n        public bool Equals(JSValue other)\r\n        {\r\n            return this == other;\r\n        }\r\n\r\n        public override bool Equals(object obj)\r\n        {\r\n            if (obj is JSValue)\r\n            {\r\n                var other = (JSValue)obj;\r\n                return this == other;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public override string ToString()\r\n        {\r\n            if (tag >= 0)\r\n            {\r\n                switch (tag)\r\n                {\r\n                    case JSApi.JS_TAG_FLOAT64: return u.float64.ToString();\r\n                    case JSApi.JS_TAG_NULL: return \"null\";\r\n                    case JSApi.JS_TAG_UNDEFINED: return \"undefined\";\r\n                    case JSApi.JS_TAG_EXCEPTION: return \"exception\";\r\n                    default: return string.Format(\"Value:{0:X}\", (ulong)u.ptr);\r\n                }\r\n            }\r\n\r\n            switch (tag)\r\n            {\r\n                case JSApi.JS_TAG_SYMBOL: return string.Format(\"Symbol:{0:X}\", (ulong)u.ptr);\r\n                case JSApi.JS_TAG_STRING: return string.Format(\"String:{0:X}\", (ulong)u.ptr);\r\n                default: return string.Format(\"Reference:{0:X}\", (ulong)u.ptr);\r\n            }\r\n        }\r\n\r\n        public static bool operator ==(JSValue a, JSValue b)\r\n        {\r\n            if (b.tag == a.tag)\r\n            {\r\n                if (a.tag >= 0)\r\n                {\r\n                    return a.tag == JSApi.JS_TAG_FLOAT64 ? a.u.float64 == b.u.float64 : a.u.int32 == b.u.int32;\r\n                }\r\n\r\n                // 注意: 引用类型的 JSValue 的基于指针地址判断, 没有经过 js_*_compare 的真实比较语义, 但通常情况下这足够了\r\n                return a.u.ptr == b.u.ptr;\r\n            }\r\n            return false;\r\n        }\r\n\r\n        public static bool operator !=(JSValue a, JSValue b)\r\n        {\r\n            return !(a == b);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/JSValue.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: e75a304b6b2945ccb519a7675aa3bb8a\r\ntimeCreated: 1590732833"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/jsb.native.asmdef",
    "content": "{\n    \"name\": \"jsb.native\",\n    \"rootNamespace\": \"\",\n    \"references\": [\n        \"GUID:595d45be140461240b6b4358dc45f2c0\"\n    ],\n    \"includePlatforms\": [],\n    \"excludePlatforms\": [],\n    \"allowUnsafeCode\": true,\n    \"overrideReferences\": false,\n    \"precompiledReferences\": [],\n    \"autoReferenced\": true,\n    \"defineConstraints\": [],\n    \"versionDefines\": [],\n    \"noEngineReferences\": true\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/jsb.native.asmdef.meta",
    "content": "fileFormatVersion: 2\nguid: ac4126d60783f3d4a98aee6be9a997aa\nAssemblyDefinitionImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/size_t.cs",
    "content": "﻿using System;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Native\r\n{\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public unsafe struct size_t\r\n    {\r\n        private void* _value;\r\n\r\n        public size_t(int value)\r\n        {\r\n            _value = (void*) (uint) value;\r\n        }\r\n\r\n        public size_t(uint value)\r\n        {\r\n            _value = (void*) value;\r\n        }\r\n\r\n        public size_t(ulong value)\r\n        {\r\n            _value = (void*) value;\r\n        }\r\n\r\n        public size_t(UIntPtr value)\r\n        {\r\n            _value = (void*) value;\r\n        }\r\n\r\n        public static implicit operator size_t(int value)\r\n        {\r\n            return new size_t(value);\r\n        }\r\n\r\n        public static implicit operator size_t(uint value)\r\n        {\r\n            return new size_t(value);\r\n        }\r\n\r\n        public static implicit operator size_t(ulong value)\r\n        {\r\n            return new size_t(value);\r\n        }\r\n\r\n        public static implicit operator size_t(UIntPtr value)\r\n        {\r\n            return new size_t(value);\r\n        }\r\n\r\n        public static implicit operator int(size_t value)\r\n        {\r\n            return (int) value._value;\r\n        }\r\n\r\n        public static implicit operator uint(size_t value)\r\n        {\r\n            return (uint) value._value;\r\n        }\r\n\r\n        public static implicit operator ulong(size_t value)\r\n        {\r\n            return (ulong) value._value;\r\n        }\r\n        \r\n        public static implicit operator UIntPtr(size_t value)\r\n        {\r\n            return new UIntPtr(value._value);\r\n        }\r\n\r\n        public override string ToString()\r\n        {\r\n            return ((ulong)this).ToString();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native/size_t.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 45734c6ab9ae40739192c736d870f99a\r\ntimeCreated: 1590733522"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Native.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 102a3fc29d4f44e7a16433a590211212\r\ntimeCreated: 1590732721"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptContext.cs",
    "content": "﻿using System;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\nusing System.Text;\r\nusing System.Text.RegularExpressions;\r\n\r\nnamespace QuickJS\r\n{\r\n    using QuickJS.Binding;\r\n    using QuickJS.Native;\r\n    using QuickJS.Utils;\r\n    using QuickJS.Errors;\r\n\r\n    public partial class ScriptContext\r\n    {\r\n        public event Action<ScriptContext, string> OnScriptReloading;\r\n        public event Action<ScriptContext, string> OnScriptReloaded;\r\n\r\n        private ScriptRuntime _runtime;\r\n        private Experimental.IJSApiBridge _apiBridge;\r\n        private int _contextId;\r\n        private JSContext _ctx;\r\n        private AtomCache _atoms;\r\n        private JSStringCache _stringCache;\r\n\r\n        private JSValue _moduleCache; // commonjs module cache\r\n\r\n        /// globally defined require function object, its only used in source evaluated from scratch (not module) (e.g dofile/eval)\r\n        private JSValue _require;\r\n        private JSValue _mainModule;\r\n        private bool _isValid;\r\n        private Regex _stRegex;\r\n\r\n        private JSValue _globalObject;\r\n        private JSValue _operatorCreate;\r\n        private JSValue _proxyConstructor;\r\n        private JSValue _objectConstructor;\r\n        private JSValue _numberConstructor;\r\n        private JSValue _stringConstructor;\r\n        private JSValue _functionConstructor;\r\n\r\n        private bool _isReloading;\r\n        private List<string> _waitForReloadModules;\r\n        private List<string> _moduleIdList;\r\n\r\n        private TypeRegister _currentTypeRegister;\r\n\r\n        // id = context slot index + 1\r\n        public int id { get { return _contextId; } }\r\n\r\n        [MonoPInvokeCallback(typeof(JSLogCFunction))]\r\n        private static void _JSLog(int level, string line)\r\n        {\r\n#if !JSB_UNITYLESS\r\n            UnityEngine.Debug.LogFormat(\"[RAW] {0}\", line);\r\n#endif\r\n        }\r\n\r\n        public ScriptContext(ScriptRuntime runtime, int contextId, Experimental.IJSApiBridge apiBridge, bool withDebugServer, int debugServerPort)\r\n        {\r\n            _isValid = true;\r\n            _runtime = runtime;\r\n            _apiBridge = apiBridge ?? new Experimental.DefaultJSApiBridgeImpl();\r\n            _contextId = contextId;\r\n            _ctx = JSApi.JS_NewContext(_runtime);\r\n            //TODO will be removed later\r\n            JSApi.JS_SetLogFunc(_ctx, _JSLog);\r\n            if (withDebugServer && debugServerPort > 0)\r\n            {\r\n                JSApi.JS_OpenDebugger(_ctx, debugServerPort);\r\n                Diagnostics.Logger.Default.Info(\"[EXPERIMENTAL] Debugger is now available with this URL (Windows x64 only): devtools://devtools/bundled/inspector.html?v8only=true&ws=127.0.0.1:{0}/1\", debugServerPort);\r\n            }\r\n            JSApi.JS_SetContextOpaque(_ctx, (IntPtr)_contextId);\r\n            JSApi.JS_AddIntrinsicOperators(_ctx);\r\n            _atoms = new AtomCache(_ctx);\r\n            _moduleIdList = new List<string>();\r\n            _stringCache = new JSStringCache(_ctx);\r\n            _mainModule = JSApi.JS_NewObject(_ctx);\r\n            _moduleCache = JSApi.JS_NewObject(_ctx);\r\n            JSApi.JS_SetProperty(_ctx, _mainModule, GetAtom(\"cache\"), JSApi.JS_DupValue(_ctx, _moduleCache));\r\n            _globalObject = JSApi.JS_GetGlobalObject(_ctx);\r\n            _objectConstructor = JSApi.JS_GetProperty(_ctx, _globalObject, JSApi.JS_ATOM_Object);\r\n            _numberConstructor = JSApi.JS_GetProperty(_ctx, _globalObject, JSApi.JS_ATOM_Number);\r\n            _proxyConstructor = JSApi.JS_GetProperty(_ctx, _globalObject, JSApi.JS_ATOM_Proxy);\r\n            _stringConstructor = JSApi.JS_GetProperty(_ctx, _globalObject, JSApi.JS_ATOM_String);\r\n            _functionConstructor = JSApi.JS_GetProperty(_ctx, _globalObject, JSApi.JS_ATOM_Function);\r\n            _operatorCreate = JSApi.JS_UNDEFINED;\r\n\r\n            if (JSApi.IsOperatorOverloadingSupported && JSApi.JS_ATOM_Operators.IsValid)\r\n            {\r\n                var operators = JSApi.JS_GetProperty(_ctx, _globalObject, JSApi.JS_ATOM_Operators);\r\n                if (!operators.IsNullish())\r\n                {\r\n                    if (operators.IsException())\r\n                    {\r\n                        _ctx.print_exception();\r\n                    }\r\n                    else\r\n                    {\r\n                        var create = JSApi.JS_GetProperty(_ctx, operators, GetAtom(\"create\"));\r\n                        JSApi.JS_FreeValue(_ctx, operators);\r\n                        if (create.IsException())\r\n                        {\r\n                            _ctx.print_exception();\r\n                        }\r\n                        else\r\n                        {\r\n                            if (JSApi.JS_IsFunction(_ctx, create) == 1)\r\n                            {\r\n                                _operatorCreate = create;\r\n\r\n                                // Function.prototype[Symbol.operatorSet] = Operators.create();\r\n                                CreateDefaultOperators(_functionConstructor);\r\n                            }\r\n                            else\r\n                            {\r\n                                JSApi.JS_FreeValue(_ctx, create);\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        public void ReleaseTypeRegister(TypeRegister register)\r\n        {\r\n            _currentTypeRegister = null;\r\n        }\r\n\r\n        public TypeRegister CreateTypeRegister()\r\n        {\r\n            if (_currentTypeRegister == null)\r\n            {\r\n                _currentTypeRegister = new TypeRegister(this);\r\n            }\r\n            else\r\n            {\r\n                _currentTypeRegister.AddRef();\r\n            }\r\n\r\n            return _currentTypeRegister;\r\n        }\r\n\r\n        private unsafe void CreateDefaultOperators(JSValue constructor)\r\n        {\r\n            if (!_operatorCreate.IsNullish())\r\n            {\r\n                var rval = JSApi.JS_Call(_ctx, _operatorCreate);\r\n                if (rval.IsException())\r\n                {\r\n                    Diagnostics.Logger.Default.Error(_ctx.GetExceptionString());\r\n                }\r\n                else\r\n                {\r\n                    JSApi.JS_DefinePropertyValue(_ctx, constructor, JSApi.JS_ATOM_Symbol_operatorSet, rval);\r\n                }\r\n            }\r\n        }\r\n\r\n        public bool IsValid()\r\n        {\r\n            lock (this)\r\n            {\r\n                return _isValid;\r\n            }\r\n        }\r\n\r\n        public IAsyncManager GetAsyncManager()\r\n        {\r\n            return _isValid ? _runtime.GetAsyncManager() : null;\r\n        }\r\n\r\n        public ITimerManager GetTimerManager()\r\n        {\r\n            return _runtime.GetTimerManager();\r\n        }\r\n\r\n        public ITypeDB GetTypeDB()\r\n        {\r\n            return _runtime.GetTypeDB();\r\n        }\r\n\r\n        public ObjectCache GetObjectCache()\r\n        {\r\n            return _runtime.GetObjectCache();\r\n        }\r\n\r\n        public ScriptRuntime GetRuntime()\r\n        {\r\n            return _runtime;\r\n        }\r\n\r\n        public bool IsContext(JSContext ctx)\r\n        {\r\n            return ctx == _ctx;\r\n        }\r\n\r\n        //NOTE: 返回值不需要释放, context 销毁时会自动释放所管理的 Atom\r\n        public JSAtom GetAtom(string name)\r\n        {\r\n            return _atoms.GetAtom(name);\r\n        }\r\n\r\n        public JSStringCache GetStringCache()\r\n        {\r\n            return _stringCache;\r\n        }\r\n\r\n        public void Destroy()\r\n        {\r\n            lock (this)\r\n            {\r\n                if (!_isValid)\r\n                {\r\n                    return;\r\n                }\r\n                _isValid = false;\r\n            }\r\n\r\n            _runtime.RemoveContext(this);\r\n            _stringCache.Destroy();\r\n            _atoms.Clear();\r\n\r\n            JSApi.JS_FreeValue(_ctx, _proxyConstructor);\r\n            JSApi.JS_FreeValue(_ctx, _objectConstructor);\r\n            JSApi.JS_FreeValue(_ctx, _numberConstructor);\r\n            JSApi.JS_FreeValue(_ctx, _stringConstructor);\r\n            JSApi.JS_FreeValue(_ctx, _functionConstructor);\r\n            JSApi.JS_FreeValue(_ctx, _globalObject);\r\n            JSApi.JS_FreeValue(_ctx, _operatorCreate);\r\n\r\n            JSApi.JS_FreeValue(_ctx, _moduleCache);\r\n            JSApi.JS_FreeValue(_ctx, _mainModule);\r\n            JSApi.JS_FreeValue(_ctx, _require);\r\n            JSApi.JS_FreeContext(_ctx);\r\n            var id = _contextId;\r\n            _contextId = -1;\r\n            _ctx = JSContext.Null;\r\n        }\r\n\r\n        public void FreeValue(JSValue value)\r\n        {\r\n            _runtime.FreeValue(value);\r\n        }\r\n\r\n        public void FreeValues(JSValue[] values)\r\n        {\r\n            _runtime.FreeValues(values);\r\n        }\r\n\r\n        public unsafe void FreeValues(int argc, JSValue* values)\r\n        {\r\n            _runtime.FreeValues(argc, values);\r\n        }\r\n\r\n        ///<summary>\r\n        /// 获取全局对象 (增加引用计数)\r\n        ///</summary>\r\n        public JSValue GetGlobalObject()\r\n        {\r\n            return JSApi.JS_DupValue(_ctx, _globalObject);\r\n        }\r\n\r\n        ///<summary>\r\n        /// 获取 string.constructor (增加引用计数)\r\n        ///</summary>\r\n        public JSValue GetStringConstructor()\r\n        {\r\n            return JSApi.JS_DupValue(_ctx, _stringConstructor);\r\n        }\r\n\r\n        public JSValue GetFunctionConstructor()\r\n        {\r\n            return JSApi.JS_DupValue(_ctx, _functionConstructor);\r\n        }\r\n\r\n        ///<summary>\r\n        /// 获取 number.constructor (增加引用计数)\r\n        ///</summary>\r\n        public JSValue GetNumberConstructor()\r\n        {\r\n            return JSApi.JS_DupValue(_ctx, _numberConstructor);\r\n        }\r\n\r\n        public JSValue GetObjectConstructor()\r\n        {\r\n            return JSApi.JS_DupValue(_ctx, _objectConstructor);\r\n        }\r\n\r\n        public JSValue GetProxyConstructor()\r\n        {\r\n            return JSApi.JS_DupValue(_ctx, _proxyConstructor);\r\n        }\r\n\r\n        public bool CheckNumberType(JSValue jsValue)\r\n        {\r\n            //TODO: 是否成立? 否则需要使用 jsapi equals\r\n            if (jsValue == _numberConstructor)\r\n            {\r\n                return true;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public bool CheckStringType(JSValue jsValue)\r\n        {\r\n            //TODO: 是否成立? 否则需要使用 jsapi equals\r\n            if (jsValue == _stringConstructor)\r\n            {\r\n                return true;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        ///<summary>\r\n        /// 获取 operator.create (增加引用计数)\r\n        ///</summary>\r\n        public JSValue GetOperatorCreate()\r\n        {\r\n            return JSApi.JS_DupValue(_ctx, _operatorCreate);\r\n        }\r\n\r\n        //TODO: 改为消耗 exports_obj 计数\r\n        // for special resolver (json/static) use\r\n        // no specified parent module assignment\r\n        public JSValue _new_commonjs_resolver_module(string module_id, string resolvername, JSValue exports_obj, bool loaded, bool set_as_main)\r\n        {\r\n            return _new_commonjs_module_entry(null, module_id, module_id, resolvername, exports_obj, loaded, set_as_main);\r\n        }\r\n\r\n        //TODO: 改为消耗 exports_obj 计数\r\n        // for source script use\r\n        public JSValue _new_commonjs_script_module(string parent_module_id, string module_id, string filename, JSValue exports_obj, bool loaded, bool set_as_main)\r\n        {\r\n            return _new_commonjs_module_entry(parent_module_id, module_id, filename, \"source\", exports_obj, loaded, set_as_main);\r\n        }\r\n\r\n        //TODO: 改为消耗 exports_obj 计数\r\n        //NOTE: 返回值需要调用者 free\r\n        public JSValue _new_commonjs_module_entry(string parent_module_id, string module_id, string filename, string resolvername, JSValue exports_obj, bool loaded, bool set_as_main)\r\n        {\r\n            var module_obj = set_as_main ? JSApi.JS_DupValue(_ctx, _mainModule) : JSApi.JS_NewObject(_ctx);\r\n            var module_id_atom = GetAtom(module_id);\r\n            var module_id_obj = JSApi.JS_AtomToString(_ctx, module_id_atom);\r\n            var filename_atom = GetAtom(filename);\r\n            var resolvername_atom = GetAtom(resolvername);\r\n\r\n            if (!_moduleIdList.Contains(module_id))\r\n            {\r\n                _moduleIdList.Add(module_id);\r\n            }\r\n            JSApi.JS_SetProperty(_ctx, _moduleCache, module_id_atom, JSApi.JS_DupValue(_ctx, module_obj));\r\n            JSApi.JS_SetProperty(_ctx, module_obj, GetAtom(\"id\"), JSApi.JS_DupValue(_ctx, module_id_obj));\r\n            JSApi.JS_SetProperty(_ctx, module_obj, GetAtom(\"filename\"), JSApi.JS_AtomToString(_ctx, filename_atom));\r\n            JSApi.JS_SetProperty(_ctx, module_obj, GetAtom(\"cache\"), JSApi.JS_DupValue(_ctx, _moduleCache));\r\n            JSApi.JS_SetProperty(_ctx, module_obj, GetAtom(\"loaded\"), JSApi.JS_NewBool(_ctx, loaded));\r\n            JSApi.JS_SetProperty(_ctx, module_obj, GetAtom(\"exports\"), JSApi.JS_DupValue(_ctx, exports_obj));\r\n            JSApi.JS_SetProperty(_ctx, module_obj, GetAtom(\"resolvername\"), JSApi.JS_AtomToString(_ctx, resolvername_atom));\r\n            JSApi.JS_SetProperty(_ctx, module_obj, GetAtom(\"children\"), JSApi.JS_NewArray(_ctx));\r\n            JSApi.JS_FreeValue(_ctx, module_id_obj);\r\n\r\n            // set parent/children here\r\n            if (!string.IsNullOrEmpty(parent_module_id))\r\n            {\r\n                JSValue parent_mod_obj;\r\n                if (LoadModuleCache(parent_module_id, out parent_mod_obj))\r\n                {\r\n                    var children_obj = JSApi.JS_GetProperty(_ctx, parent_mod_obj, GetAtom(\"children\"));\r\n                    if (JSApi.JS_IsArray(_ctx, children_obj) == 1)\r\n                    {\r\n                        var lengthVal = JSApi.JS_GetProperty(_ctx, children_obj, JSApi.JS_ATOM_length);\r\n                        if (lengthVal.IsNumber())\r\n                        {\r\n                            int length;\r\n                            if (JSApi.JS_ToInt32(_ctx, out length, lengthVal) == 0 && length >= 0)\r\n                            {\r\n                                JSApi.JS_SetPropertyUint32(_ctx, children_obj, (uint)length, JSApi.JS_DupValue(_ctx, module_obj));\r\n                            }\r\n                        }\r\n                        JSApi.JS_FreeValue(_ctx, lengthVal);\r\n                    }\r\n                    JSApi.JS_FreeValue(_ctx, children_obj);\r\n                    JSApi.JS_SetProperty(_ctx, module_obj, GetAtom(\"parent\"), parent_mod_obj);\r\n                }\r\n            }\r\n\r\n            return module_obj;\r\n        }\r\n\r\n#if !JSB_UNITYLESS\r\n        public unsafe bool TrySetScriptRef(ref Unity.JSScriptRef scriptRef, JSValue ctor)\r\n        {\r\n            string[] scriptRefValue = null;\r\n            var sourceString = @\"(function (cache, ctor) {\r\n                for (let mod_id in cache) {\r\n                    let mod_obj = cache[mod_id];\r\n                    let exports = mod_obj['exports'];\r\n                    if (typeof exports === 'object') {\r\n                        for (let member_id in exports) {\r\n                            let member_obj = exports[member_id];\r\n                            if (typeof member_obj === 'function' && member_obj == ctor) {\r\n                                return [mod_id, member_id];\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n                return null;\r\n            })\";\r\n            var scriptRefFinder = ScriptRuntime.EvalSource(_ctx, sourceString, \"eval\", false);\r\n            if (scriptRefFinder.IsException())\r\n            {\r\n                _ctx.print_exception();\r\n                return false;\r\n            }\r\n            var argv = stackalloc JSValue[2]\r\n            {\r\n                JSApi.JS_DupValue(_ctx, _moduleCache),\r\n                JSApi.JS_DupValue(_ctx, ctor),\r\n            };\r\n            var retVal = JSApi.JS_Call(_ctx, scriptRefFinder, JSApi.JS_UNDEFINED, 2, argv);\r\n            JSApi.JS_FreeValue(_ctx, scriptRefFinder);\r\n            JSApi.JS_FreeValue(_ctx, argv[0]);\r\n            JSApi.JS_FreeValue(_ctx, argv[1]);\r\n            if (retVal.IsException())\r\n            {\r\n                _ctx.print_exception();\r\n                return false;\r\n            }\r\n            if (Values.js_get_primitive(_ctx, retVal, out scriptRefValue) && scriptRefValue != null && scriptRefValue.Length >= 2)\r\n            {\r\n                if (!string.IsNullOrEmpty(scriptRefValue[1]))\r\n                {\r\n                    JSApi.JS_FreeValue(_ctx, retVal);\r\n                    scriptRef.modulePath = scriptRefValue[0];\r\n                    scriptRef.className = scriptRefValue[1];\r\n                    return true;\r\n                }\r\n            }\r\n            JSApi.JS_FreeValue(_ctx, retVal);\r\n            return false;\r\n        }\r\n#endif\r\n\r\n        public bool LoadModuleCacheExports(string module_id, string key, out JSValue value)\r\n        {\r\n            JSValue mod_obj;\r\n\r\n            value = JSApi.JS_UNDEFINED;\r\n            if (LoadModuleCache(module_id, out mod_obj))\r\n            {\r\n                var exports = JSApi.JS_GetProperty(_ctx, mod_obj, GetAtom(\"exports\"));\r\n\r\n                if (exports.IsObject())\r\n                {\r\n                    value = JSApi.JS_GetProperty(_ctx, exports, GetAtom(key));\r\n                }\r\n\r\n                JSApi.JS_FreeValue(_ctx, exports);\r\n                JSApi.JS_FreeValue(_ctx, mod_obj);\r\n            }\r\n\r\n            return !value.IsUndefined();\r\n        }\r\n\r\n        public bool LoadModuleCache(string module_id, out JSValue value)\r\n        {\r\n            var prop = GetAtom(module_id);\r\n            var mod = JSApi.JS_GetProperty(_ctx, _moduleCache, prop);\r\n            if (mod.IsObject())\r\n            {\r\n                value = mod;\r\n                return true;\r\n            }\r\n            value = JSApi.JS_UNDEFINED;\r\n            JSApi.JS_FreeValue(_ctx, mod);\r\n            return false;\r\n        }\r\n\r\n        public void BeginModuleReload()\r\n        {\r\n            if (!_isReloading)\r\n            {\r\n                _isReloading = true;\r\n                _waitForReloadModules = new List<string>();\r\n            }\r\n        }\r\n\r\n        public void MarkModuleReload(string module_id)\r\n        {\r\n            if (_isReloading && !_waitForReloadModules.Contains(module_id))\r\n            {\r\n                _waitForReloadModules.Add(module_id);\r\n            }\r\n        }\r\n\r\n        public void EndModuleReload()\r\n        {\r\n            if (!_isReloading)\r\n            {\r\n                return;\r\n            }\r\n\r\n            while (_waitForReloadModules.Count > 0)\r\n            {\r\n                var module_id = _waitForReloadModules[0];\r\n\r\n                if (!_runtime.ReloadModule(this, module_id))\r\n                {\r\n                    _waitForReloadModules.Remove(module_id);\r\n                }\r\n            }\r\n\r\n            _isReloading = false;\r\n            _waitForReloadModules = null;\r\n        }\r\n\r\n        public void RaiseScriptReloadingEvent_throw(string resolved_id)\r\n        {\r\n            OnScriptReloading?.Invoke(this, resolved_id);\r\n        }\r\n\r\n        public void RaiseScriptReloadedEvent_throw(string resolved_id)\r\n        {\r\n            OnScriptReloaded?.Invoke(this, resolved_id);\r\n        }\r\n\r\n#if !JSB_UNITYLESS\r\n        public bool CheckModuleId(Unity.JSScriptRef scriptRef, string resolved_id)\r\n        {\r\n            return _runtime.ResolveModuleId(this, \"\", scriptRef.modulePath) == resolved_id;\r\n        }\r\n#endif\r\n\r\n        public bool TryGetModuleForReloading(string resolved_id, out JSValue module_obj)\r\n        {\r\n            if (_waitForReloadModules != null && _waitForReloadModules.Contains(resolved_id))\r\n            {\r\n                _waitForReloadModules.Remove(resolved_id);\r\n                if (LoadModuleCache(resolved_id, out module_obj))\r\n                {\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            module_obj = JSApi.JS_UNDEFINED;\r\n            return false;\r\n        }\r\n\r\n        // require(id);\r\n        [MonoPInvokeCallback(typeof(JSCFunctionMagic))]\r\n        public static unsafe JSValue module_require(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv, int magic)\r\n        {\r\n            if (argc < 1)\r\n            {\r\n                return ctx.ThrowInternalError(\"require module id\");\r\n            }\r\n\r\n            if (!argv[0].IsString())\r\n            {\r\n                return ctx.ThrowInternalError(\"require module id (string)\");\r\n            }\r\n\r\n#if JSB_WITH_ACTIVEFUNCTION\r\n            // callee is the function <'require'> of current module\r\n            var callee = JSApi.JS_GetActiveFunction(ctx);\r\n\r\n            if (JSApi.JS_IsFunction(ctx, callee) != 1)\r\n            {\r\n                return ctx.ThrowInternalError(\"require != function\");\r\n            }\r\n\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            var runtime = context.GetRuntime();\r\n            var parent_module_id_val = JSApi.JS_GetProperty(ctx, callee, context.GetAtom(\"moduleId\"));\r\n            var parent_module_id = JSApi.GetString(ctx, parent_module_id_val);\r\n            JSApi.JS_FreeValue(ctx, parent_module_id_val);\r\n\r\n            try\r\n            {\r\n                var module_id = JSApi.GetString(ctx, argv[0]);\r\n                return runtime.ResolveModule(context, parent_module_id, module_id, false);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n#else \r\n            try\r\n            {\r\n                var context = ScriptEngine.GetContext(ctx);\r\n                var list = context._moduleIdList;\r\n                string parent_module_id = null;\r\n                if (magic >= 0 && magic < list.Count)\r\n                {\r\n                    parent_module_id = list[magic];\r\n                }\r\n                var runtime = context.GetRuntime();\r\n                var module_id = JSApi.GetString(ctx, argv[0]);\r\n                return runtime.ResolveModule(context, parent_module_id, module_id, false);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n#endif\r\n        }\r\n\r\n        public JSValue _CreateRequireFunction(string resolved_id, JSValue module_obj)\r\n        {\r\n            var require_obj = JSApi.JSB_NewCFunctionMagic(_ctx, module_require, GetAtom(\"require\"), 1, _moduleIdList.IndexOf(resolved_id));\r\n\r\n            JSApi.JS_SetProperty(_ctx, require_obj, GetAtom(\"moduleId\"), JSApi.JS_GetProperty(_ctx, module_obj, GetAtom(\"id\")));\r\n            JSApi.JS_SetProperty(_ctx, require_obj, GetAtom(\"main\"), JSApi.JS_DupValue(_ctx, _mainModule));\r\n            JSApi.JS_SetProperty(_ctx, require_obj, GetAtom(\"cache\"), JSApi.JS_DupValue(_ctx, _moduleCache));\r\n            return require_obj;\r\n        }\r\n\r\n        // this method will consume the module_obj refcount \r\n        public unsafe JSValue LoadModuleFromSource(byte[] source, string resolved_id, string filename, JSValue module_obj)\r\n        {\r\n            object unused;\r\n            return LoadModuleFromSource(source, resolved_id, filename, module_obj, null, out unused);\r\n        }\r\n\r\n        //TODO remove parameter: filename\r\n        public unsafe JSValue LoadModuleFromSource(byte[] source, string resolved_id, string filename, JSValue module_obj, Type expectedReturnType, out object expectedReturnValue)\r\n        {\r\n            var context = this;\r\n            var ctx = _ctx;\r\n            var dirname = PathUtils.GetDirectoryName(resolved_id);\r\n            var resolved_id_bytes = Utils.TextUtils.GetNullTerminatedBytes(resolved_id);\r\n            var filename_obj = JSApi.JS_GetProperty(ctx, module_obj, context.GetAtom(\"filename\"));\r\n            var module_id_atom = context.GetAtom(resolved_id);\r\n            var dirname_atom = context.GetAtom(dirname);\r\n            var require_obj = JSApi.JSB_NewCFunctionMagic(ctx, module_require, context.GetAtom(\"require\"), 1, _moduleIdList.IndexOf(resolved_id));\r\n            var main_mod_obj = JSApi.JS_DupValue(ctx, _mainModule);\r\n            var dirname_obj = JSApi.JS_AtomToString(ctx, dirname_atom);\r\n            var exports_obj = JSApi.JS_GetProperty(ctx, module_obj, context.GetAtom(\"exports\"));\r\n\r\n            expectedReturnValue = null;\r\n            JSApi.JS_SetProperty(ctx, require_obj, context.GetAtom(\"moduleId\"), JSApi.JS_AtomToString(ctx, module_id_atom));\r\n            JSApi.JS_SetProperty(ctx, require_obj, context.GetAtom(\"main\"), main_mod_obj);\r\n            JSApi.JS_SetProperty(ctx, require_obj, context.GetAtom(\"cache\"), JSApi.JS_DupValue(ctx, _moduleCache));\r\n\r\n            const int RequireArgNum = 5;\r\n            var require_argv = stackalloc JSValue[RequireArgNum] { exports_obj, require_obj, module_obj, filename_obj, dirname_obj, };\r\n\r\n            var tagValue = ScriptRuntime.TryReadByteCodeTagValue(source);\r\n            if (tagValue == ScriptRuntime.BYTECODE_COMMONJS_MODULE_TAG)\r\n            {\r\n                // bytecode\r\n                fixed (byte* intput_ptr = source)\r\n                {\r\n                    var bytecodeFunc = JSApi.JS_ReadByteCode(ctx, intput_ptr + sizeof(uint), source.Length - sizeof(uint));\r\n\r\n                    if (bytecodeFunc.IsFunctionByteCode())\r\n                    {\r\n                        var func_val = JSApi.JS_EvalFunction(ctx, bytecodeFunc); // it's CallFree (bytecodeFunc)\r\n                        if (JSApi.JS_IsFunction(ctx, func_val) != 1)\r\n                        {\r\n                            JSApi.JS_FreeValue(ctx, func_val);\r\n                            JSApi.JS_FreeValue(ctx, RequireArgNum, require_argv);\r\n                            return ctx.ThrowInternalError(\"failed to require bytecode module\");\r\n                        }\r\n\r\n                        var rval = JSApi.JS_Call(ctx, func_val, JSApi.JS_UNDEFINED, RequireArgNum, require_argv);\r\n                        JSApi.JS_FreeValue(ctx, func_val);\r\n                        if (rval.IsException())\r\n                        {\r\n                            JSApi.JS_FreeValue(ctx, RequireArgNum, require_argv);\r\n                            return rval;\r\n                        }\r\n\r\n                        // success\r\n                        if (expectedReturnType != null)\r\n                        {\r\n                            Values.js_get_var(_ctx, rval, expectedReturnType, out expectedReturnValue);\r\n                        }\r\n                        else\r\n                        {\r\n                            expectedReturnValue = null;\r\n                        }\r\n                        JSApi.JS_FreeValue(ctx, rval);\r\n                    }\r\n                    else\r\n                    {\r\n                        JSApi.JS_FreeValue(ctx, bytecodeFunc);\r\n                        JSApi.JS_FreeValue(ctx, RequireArgNum, require_argv);\r\n                        return ctx.ThrowInternalError(\"failed to require bytecode module\");\r\n                    }\r\n                }\r\n            }\r\n            else\r\n            {\r\n                // source\r\n                var input_bytes = TextUtils.GetShebangNullTerminatedCommonJSBytes(source);\r\n                fixed (byte* input_ptr = input_bytes)\r\n                fixed (byte* resolved_id_ptr = resolved_id_bytes)\r\n                {\r\n                    var input_len = (size_t)(input_bytes.Length - 1);\r\n#if JSB_WITH_V8_BACKEND\r\n                    JSValue func_val;\r\n                    var filename_bytes = TextUtils.GetNullTerminatedBytes(filename.Replace('/', '\\\\')); // normalize for v8 debug protocol\r\n                    fixed (byte* filename_ptr = filename_bytes)\r\n                    {\r\n                        func_val = JSApi.JS_EvalSource(ctx, input_ptr, input_len, filename_ptr);\r\n                    }\r\n#else\r\n                    var func_val = JSApi.JS_EvalSource(ctx, input_ptr, input_len, resolved_id_ptr);\r\n#endif\r\n\r\n                    if (func_val.IsException())\r\n                    {\r\n                        JSApi.JS_FreeValue(ctx, RequireArgNum, require_argv);\r\n                        return func_val;\r\n                    }\r\n\r\n                    if (JSApi.JS_IsFunction(ctx, func_val) == 1)\r\n                    {\r\n                        var rval = JSApi.JS_Call(ctx, func_val, JSApi.JS_UNDEFINED, RequireArgNum, require_argv);\r\n                        if (rval.IsException())\r\n                        {\r\n                            JSApi.JS_FreeValue(ctx, func_val);\r\n                            JSApi.JS_FreeValue(ctx, RequireArgNum, require_argv);\r\n                            return rval;\r\n                        }\r\n\r\n                        // success\r\n                        if (expectedReturnType != null)\r\n                        {\r\n                            Values.js_get_var(_ctx, rval, expectedReturnType, out expectedReturnValue);\r\n                        }\r\n                        else\r\n                        {\r\n                            expectedReturnValue = null;\r\n                        }\r\n                        JSApi.JS_FreeValue(ctx, rval);\r\n                    }\r\n\r\n                    JSApi.JS_FreeValue(ctx, func_val);\r\n                }\r\n            }\r\n\r\n            JSApi.JS_SetProperty(ctx, module_obj, context.GetAtom(\"loaded\"), JSApi.JS_NewBool(ctx, true));\r\n            var exports_ = JSApi.JS_GetProperty(ctx, module_obj, context.GetAtom(\"exports\"));\r\n            JSApi.JS_FreeValue(ctx, RequireArgNum, require_argv);\r\n            return exports_;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add a function to globalThis (will overwrite anything with a same name if already existed)\r\n        /// </summary>\r\n        public void AddGlobalFunction(string name, JSCFunction func, int length)\r\n        {\r\n            var nameAtom = GetAtom(name);\r\n            var cfun = JSApi.JSB_NewCFunction(_ctx, func, nameAtom, length);\r\n            JSApi.JS_DefinePropertyValue(_ctx, _globalObject, nameAtom, cfun);\r\n        }\r\n\r\n        public void AddFunction(JSValue thisObject, string name, JSCFunction func, int length)\r\n        {\r\n            var nameAtom = GetAtom(name);\r\n            var cfun = JSApi.JSB_NewCFunction(_ctx, func, nameAtom, length);\r\n            JSApi.JS_DefinePropertyValue(_ctx, thisObject, nameAtom, cfun);\r\n        }\r\n\r\n        public static ClassDecl Bind(TypeRegister register)\r\n        {\r\n            var ns_jsb = register.CreateClass(\"JSBObject\");\r\n\r\n            ns_jsb.AddFunction(\"DoFile\", _DoFile, 1);\r\n            ns_jsb.AddFunction(\"AddSearchPath\", _AddSearchPath, 1);\r\n            ns_jsb.AddFunction(\"Yield\", yield_func, 1);\r\n            ns_jsb.AddFunction(\"ToArray\", to_js_array, 1);\r\n            ns_jsb.AddFunction(\"ToArrayBuffer\", to_js_array_buffer, 1);\r\n            ns_jsb.AddFunction(\"ToBytes\", to_cs_bytes, 1);\r\n            ns_jsb.AddFunction(\"ToFunction\", to_js_function, 1);\r\n            ns_jsb.AddFunction(\"ToDelegate\", to_cs_delegate, 1);\r\n            ns_jsb.AddFunction(\"Import\", js_import_type, 2);\r\n            ns_jsb.AddFunction(\"GC\", _gc, 0);\r\n            ns_jsb.AddFunction(\"SetDisposable\", _set_disposable, 2);\r\n            ns_jsb.AddFunction(\"AddCacheString\", _add_cache_string, 1);\r\n            ns_jsb.AddFunction(\"RemoveCacheString\", _remove_cache_string, 1);\r\n            ns_jsb.AddFunction(\"Sleep\", _sleep, 1);\r\n            ns_jsb.AddFunction(\"AddModule\", _add_module, 2);\r\n            ns_jsb.AddFunction(\"Now\", _now, 0);\r\n            ns_jsb.AddFunction(\"IsStaticBinding\", _IsStaticBinding, 0);\r\n            ns_jsb.AddConstValue(\"isOperatorOverloadingSupported\", JSApi.IsOperatorOverloadingSupported);\r\n            ns_jsb.AddConstValue(\"engine\", JSApi.JSBDLL);\r\n            ns_jsb.AddConstValue(\"version\", JSApi.SO_JSB_VERSION);\r\n            ns_jsb.AddConstValue(\"pluginVersion\", JSApi.VERSION);\r\n            {\r\n                var ns_hotfix = register.CreateClass(\"JSBHotfix\");\r\n                ns_hotfix.AddFunction(\"replace_single\", hotfix_replace_single, 2);\r\n                ns_hotfix.AddFunction(\"before_single\", hotfix_before_single, 2);\r\n                // ns_hotfix.AddFunction(\"replace\", hotfix_replace, 2);\r\n                // ns_hotfix.AddFunction(\"before\", hotfix_before);\r\n                // ns_hotfix.AddFunction(\"after\", hotfix_after);\r\n\r\n                ns_jsb.AddValue(\"hotfix\", ns_hotfix.GetConstructor());\r\n            }\r\n            {\r\n                var ns_ModuleManager = register.CreateClass(\"ModuleManager\");\r\n                ns_ModuleManager.AddFunction(\"BeginReload\", ModuleManager_BeginReload, 0);\r\n                ns_ModuleManager.AddFunction(\"MarkReload\", ModuleManager_MarkReload, 1);\r\n                ns_ModuleManager.AddFunction(\"EndReload\", ModuleManager_EndReload, 0);\r\n\r\n                ns_jsb.AddValue(\"ModuleManager\", ns_ModuleManager.GetConstructor());\r\n            }\r\n            {\r\n                var ns_ArrayUtils = register.CreateClass(\"ArrayUtils\");\r\n                ns_ArrayUtils.AddFunction(\"GetLength\", ArrayLike_GetLength, 1);\r\n                ns_ArrayUtils.AddFunction(\"GetValue\", ArrayLike_GetValue, 2);\r\n                ns_ArrayUtils.AddFunction(\"RemoveAt\", ArrayLike_RemoveAt, 2);\r\n                ns_ArrayUtils.AddFunction(\"Insert\", ArrayLike_Insert, 3);\r\n                ns_ArrayUtils.AddFunction(\"SetValue\", ArrayLike_SetValue, 3);\r\n\r\n                ns_jsb.AddValue(\"ArrayUtils\", ns_ArrayUtils.GetConstructor());\r\n            }\r\n            return ns_jsb;\r\n        }\r\n\r\n        public void EvalSource(string source, string fileName)\r\n        {\r\n            var bytes = System.Text.Encoding.UTF8.GetBytes(source);\r\n            EvalSource(bytes, fileName, typeof(void));\r\n        }\r\n\r\n        public T EvalSource<T>(string source, string fileName)\r\n        {\r\n            var bytes = System.Text.Encoding.UTF8.GetBytes(source);\r\n            return (T)EvalSource(bytes, fileName, typeof(T));\r\n        }\r\n\r\n        public void EvalSource(byte[] source, string fileName)\r\n        {\r\n            EvalSource(source, fileName, typeof(void));\r\n        }\r\n\r\n        public T EvalSource<T>(byte[] source, string fileName)\r\n        {\r\n            return (T)EvalSource(source, fileName, typeof(T));\r\n        }\r\n\r\n        public object EvalSource(byte[] source, string fileName, Type returnType)\r\n        {\r\n            var jsValue = ScriptRuntime.EvalSource(_ctx, source, fileName, false);\r\n            if (JSApi.JS_IsException(jsValue))\r\n            {\r\n                var ex = _ctx.GetExceptionString();\r\n                JSApi.JS_FreeValue(_ctx, jsValue);\r\n                throw new JSException(ex, fileName);\r\n            }\r\n            object retObject;\r\n            Values.js_get_var(_ctx, jsValue, returnType, out retObject);\r\n            JSApi.JS_FreeValue(_ctx, jsValue);\r\n            return retObject;\r\n        }\r\n\r\n        public void RegisterBuiltins()\r\n        {\r\n            var ctx = (JSContext)this;\r\n            var global_object = this.GetGlobalObject();\r\n            {\r\n                _require = JSApi.JSB_NewCFunctionMagic(ctx, module_require, GetAtom(\"require\"), 1, -1);\r\n                JSApi.JS_SetProperty(ctx, _require, GetAtom(\"moduleId\"), ctx.NewString(\"\"));\r\n                JSApi.JS_SetProperty(ctx, _require, GetAtom(\"cache\"), JSApi.JS_DupValue(ctx, _moduleCache));\r\n                JSApi.JS_SetProperty(ctx, global_object, GetAtom(\"require\"), JSApi.JS_DupValue(ctx, _require));\r\n                JSApi.JS_SetProperty(ctx, global_object, GetAtom(\"define\"), JSApi.JSB_NewCFunction(ctx, ScriptRuntime.module_define, GetAtom(\"define\"), 3));\r\n\r\n                JSApi.JS_SetProperty(ctx, global_object, GetAtom(\"print\"), JSApi.JSB_NewCFunctionMagic(ctx, _print, GetAtom(\"print\"), 1, 0));\r\n                var console = JSApi.JS_NewObject(ctx);\r\n                {\r\n                    JSApi.JS_SetProperty(ctx, console, GetAtom(\"log\"), JSApi.JSB_NewCFunctionMagic(ctx, _print, GetAtom(\"log\"), 1, (int)Diagnostics.ELogSeverity.Info));\r\n                    JSApi.JS_SetProperty(ctx, console, GetAtom(\"info\"), JSApi.JSB_NewCFunctionMagic(ctx, _print, GetAtom(\"info\"), 1, (int)Diagnostics.ELogSeverity.Info));\r\n                    JSApi.JS_SetProperty(ctx, console, GetAtom(\"debug\"), JSApi.JSB_NewCFunctionMagic(ctx, _print, GetAtom(\"debug\"), 1, (int)Diagnostics.ELogSeverity.Debug));\r\n                    JSApi.JS_SetProperty(ctx, console, GetAtom(\"warn\"), JSApi.JSB_NewCFunctionMagic(ctx, _print, GetAtom(\"warn\"), 1, (int)Diagnostics.ELogSeverity.Warning));\r\n                    JSApi.JS_SetProperty(ctx, console, GetAtom(\"error\"), JSApi.JSB_NewCFunctionMagic(ctx, _print, GetAtom(\"error\"), 1, (int)Diagnostics.ELogSeverity.Error));\r\n                    JSApi.JS_SetProperty(ctx, console, GetAtom(\"assert\"), JSApi.JSB_NewCFunctionMagic(ctx, _print, GetAtom(\"assert\"), 1, (int)Diagnostics.ELogSeverity.Assert));\r\n                    JSApi.JS_SetProperty(ctx, console, GetAtom(\"trace\"), JSApi.JSB_NewCFunctionMagic(ctx, _print, GetAtom(\"trace\"), 0, -1));\r\n                }\r\n                JSApi.JS_SetProperty(ctx, global_object, GetAtom(\"console\"), console);\r\n            }\r\n            JSApi.JS_FreeValue(ctx, global_object);\r\n        }\r\n\r\n        private string js_source_position(JSContext ctx, string funcName, string fileName, int lineNumber)\r\n        {\r\n            return $\"{funcName} ({fileName}:{lineNumber})\";\r\n        }\r\n\r\n        public void AppendStacktrace(StringBuilder sb)\r\n        {\r\n            var ctx = _ctx;\r\n            var globalObject = JSApi.JS_GetGlobalObject(ctx);\r\n            var errorConstructor = JSApi.JS_GetProperty(ctx, globalObject, JSApi.JS_ATOM_Error);\r\n            var errorObject = JSApi.JS_CallConstructor(ctx, errorConstructor);\r\n            var stackValue = JSApi.JS_GetProperty(ctx, errorObject, JSApi.JS_ATOM_stack);\r\n            var stack = JSApi.GetString(ctx, stackValue);\r\n\r\n            if (!string.IsNullOrEmpty(stack))\r\n            {\r\n                var errlines = stack.Split('\\n');\r\n                if (_stRegex == null)\r\n                {\r\n                    _stRegex = new Regex(@\"^\\s+at\\s(.+)\\s\\((.+\\.js):(\\d+)\\)(.*)$\", RegexOptions.Compiled);\r\n                }\r\n                for (var i = 0; i < errlines.Length; i++)\r\n                {\r\n                    var line = errlines[i];\r\n                    if (i == 0 && line == \"Error\")\r\n                    {\r\n                        continue;\r\n                    }\r\n                    var matches = _stRegex.Matches(line);\r\n                    if (matches.Count == 1)\r\n                    {\r\n                        var match = matches[0];\r\n                        if (match.Groups.Count >= 4)\r\n                        {\r\n                            var funcName = match.Groups[1].Value;\r\n                            var fileName = match.Groups[2].Value;\r\n                            var lineNumber = 0;\r\n                            int.TryParse(match.Groups[3].Value, out lineNumber);\r\n                            var extra = match.Groups.Count >= 5 ? match.Groups[4].Value : \"\";\r\n                            var sroucePosition = (_runtime.OnSourceMap ?? js_source_position)(ctx, funcName, fileName, lineNumber);\r\n                            sb.AppendLine($\"    at {sroucePosition}{extra}\");\r\n                            continue;\r\n                        }\r\n                    }\r\n                    sb.AppendLine(line);\r\n                }\r\n            }\r\n\r\n            JSApi.JS_FreeValue(ctx, stackValue);\r\n            JSApi.JS_FreeValue(ctx, errorObject);\r\n            JSApi.JS_FreeValue(ctx, errorConstructor);\r\n            JSApi.JS_FreeValue(ctx, globalObject);\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// 用于对 c# 对象产生 js 包装对象 (不负责自动 Dispose)\r\n        /// </summary>\r\n        /// <param name=\"ctx\">JS 环境</param>\r\n        /// <param name=\"o\">CS 对象</param>\r\n        /// <returns>映射对象</returns>\r\n        public JSValue NewBridgeObjectBind(object o)\r\n        {\r\n            var cache = _runtime.GetObjectCache();\r\n            JSValue heapptr;\r\n            if (cache.TryGetJSValue(o, out heapptr))\r\n            {\r\n                return JSApi.JS_DupValue(_ctx, heapptr);\r\n            }\r\n\r\n            var type = o.GetType();\r\n            var db = this.GetTypeDB();\r\n            var proto = db.GetPrototypeOf(type.BaseType == typeof(MulticastDelegate) ? typeof(Delegate) : type);\r\n\r\n            if (proto.IsNullish())\r\n            {\r\n                db.GetDynamicType(type, false);\r\n                proto = db.GetPrototypeOf(type);\r\n                if (proto.IsNullish())\r\n                {\r\n                    return _ctx.ThrowInternalError(string.Format(\"no prototype found for {0}\", type));\r\n                }\r\n            }\r\n\r\n            return _apiBridge.NewBridgeObject(this, o, proto);\r\n        }\r\n\r\n        public JSPayloadHeader GetPayloadHeader(JSValue val)\r\n        {\r\n            return _apiBridge.GetPayloadHeader(this, val);\r\n        }\r\n\r\n        public static implicit operator JSContext(ScriptContext sc)\r\n        {\r\n            return sc != null ? sc._ctx : JSContext.Null;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptContext.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 4e64ad60dcc74cc1a5cc73512e794ae0\r\ntimeCreated: 1590741631"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptContext_funcs.cs",
    "content": "using System;\r\nusing System.Reflection;\r\nusing System.Text;\r\nusing QuickJS.Binding;\r\nusing QuickJS.Native;\r\nusing QuickJS.Utils;\r\n\r\nnamespace QuickJS\r\n{\r\n    public partial class ScriptContext\r\n    {\r\n        #region Builtins\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        private static JSValue _sleep(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            int pres = 0;\r\n            if (argc > 0)\r\n            {\r\n                if (JSApi.JS_ToInt32(ctx, out pres, argv[0]) != 0)\r\n                {\r\n                    return ctx.ThrowInternalError(\"invalid parameter: milliseconds\");\r\n                }\r\n            }\r\n            if (pres > 0)\r\n            {\r\n                System.Threading.Thread.Sleep(pres);\r\n            }\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        private static JSValue _add_module(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc >= 2 && argv[0].IsString() && !argv[1].IsNullish())\r\n            {\r\n                var runtime = ScriptEngine.GetRuntime(ctx);\r\n                var name = JSApi.GetString(ctx, argv[0]);\r\n                runtime.AddStaticModule(name, argv[1]);\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        private static JSValue _IsStaticBinding(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            var runtime = ScriptEngine.GetRuntime(ctx);\r\n            return JSApi.JS_NewBool(ctx, runtime.isStaticBinding);\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        private static JSValue _add_cache_string(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc > 0 && argv[0].IsString())\r\n            {\r\n                var context = ScriptEngine.GetContext(ctx);\r\n                var cache = context.GetStringCache();\r\n                string stringValue;\r\n                if (cache.GetValue(argv[0], out stringValue))\r\n                {\r\n                    return JSApi.JS_DupValue(ctx, argv[0]);\r\n                }\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        private static JSValue _remove_cache_string(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc > 0 && argv[0].IsString())\r\n            {\r\n                var context = ScriptEngine.GetContext(ctx);\r\n                var cache = context.GetStringCache();\r\n                string stringValue;\r\n                if (cache.TryGetValue(argv[0], out stringValue))\r\n                {\r\n                    cache.RemoveValue(stringValue);\r\n                    return JSApi.JS_TRUE;\r\n                }\r\n            }\r\n\r\n            return JSApi.JS_FALSE;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        private static JSValue _gc(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            // var runtime = ScriptEngine.GetRuntime(ctx);\r\n            // runtime.EnqueueAction(new JSAction() { callback = _RunGC });\r\n            var rt = JSApi.JS_GetRuntime(ctx);\r\n            JSApi.JS_RunGC(rt);\r\n            GC.Collect();\r\n            GC.WaitForPendingFinalizers();\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        private static JSValue _now(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            var timerManager = ScriptEngine.GetTimerManager(ctx);\r\n            if (timerManager == null)\r\n            {\r\n                return ctx.ThrowInternalError(\"no timer manager\");\r\n            }\r\n            return JSApi.JS_NewInt32(ctx, timerManager.now);\r\n        }\r\n\r\n        // private static void _RunGC(ScriptRuntime rt, JSAction value)\r\n        // {\r\n        //     JSApi.JS_RunGC(rt);\r\n        //     GC.Collect();\r\n        //     GC.WaitForPendingFinalizers();\r\n        // }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunctionMagic))]\r\n        private static JSValue _print(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv, int magic)\r\n        {\r\n            if (argc == 0 && magic >= 0)\r\n            {\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n\r\n            var runtime = ScriptEngine.GetRuntime(ctx);\r\n            if (runtime == null || !runtime.isValid)\r\n            {\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n\r\n            int i = 0;\r\n            if (magic == (int)Diagnostics.ELogSeverity.Assert)\r\n            {\r\n                if (JSApi.JS_ToBool(ctx, argv[0]) == 1)\r\n                {\r\n                    return JSApi.JS_UNDEFINED;\r\n                }\r\n\r\n                i = 1;\r\n            }\r\n\r\n            var sb = new StringBuilder();\r\n            size_t str_len;\r\n            if (magic == (int)Diagnostics.ELogSeverity.Assert)\r\n            {\r\n                sb.Append(\"Assertion failed: \");\r\n            }\r\n\r\n            for (; i < argc; i++)\r\n            {\r\n                var pstr = JSApi.JS_ToCStringLen(ctx, out str_len, argv[i]);\r\n                if (pstr != IntPtr.Zero)\r\n                {\r\n                    var str = JSApi.GetString(ctx, pstr, str_len);\r\n                    if (str != null)\r\n                    {\r\n                        sb.Append(str);\r\n                    }\r\n\r\n                    JSApi.JS_FreeCString(ctx, pstr);\r\n                    if (i != argc - 1)\r\n                    {\r\n                        sb.Append(' ');\r\n                    }\r\n                }\r\n            }\r\n\r\n            var severity = magic == -1 ? Diagnostics.ELogSeverity.Info : (Diagnostics.ELogSeverity)magic;\r\n            if (severity > Diagnostics.ELogSeverity.Warning || runtime.withStacktrace)\r\n            {\r\n                sb.AppendLine();\r\n                runtime.GetContext(ctx).AppendStacktrace(sb);\r\n            }\r\n\r\n            try\r\n            {\r\n                Diagnostics.Logger.Scripting.Write(severity, sb.ToString());\r\n            }\r\n            catch (Exception)\r\n            {\r\n                // Debug.LogErrorFormat(\"Logger Exception: {0}\\n{1}\", exception, exception.StackTrace);\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        #endregion\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue _DoFile(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc < 1 || !argv[0].IsString())\r\n            {\r\n                return ctx.ThrowInternalError(\"path expected\");\r\n            }\r\n            var path = JSApi.GetString(ctx, argv[0]);\r\n            if (string.IsNullOrEmpty(path))\r\n            {\r\n                return ctx.ThrowInternalError(\"invalid path\");\r\n            }\r\n\r\n            //TODO: use runtime.EvalFile instead\r\n\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            var runtime = context.GetRuntime();\r\n            var fileSystem = runtime.GetFileSystem();\r\n            var resolvedPath = runtime.ResolveFilePath(\"\", path);\r\n            if (resolvedPath == null)\r\n            {\r\n                return ctx.ThrowInternalError(\"file not found:\" + path);\r\n            }\r\n            var source = fileSystem.ReadAllBytes(resolvedPath);\r\n            return ScriptRuntime.EvalSource(ctx, source, resolvedPath, true);\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue _AddSearchPath(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc < 1 || !argv[0].IsString())\r\n            {\r\n                return ctx.ThrowInternalError(\"path expected\");\r\n            }\r\n            var path = JSApi.GetString(ctx, argv[0]);\r\n            if (string.IsNullOrEmpty(path))\r\n            {\r\n                return ctx.ThrowInternalError(\"invalid path\");\r\n            }\r\n\r\n            var runtime = ScriptEngine.GetRuntime(ctx);\r\n            runtime.AddSearchPath(path);\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        // 尝试将传入的委托转换为 js function\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static unsafe JSValue to_js_function(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc >= 1)\r\n            {\r\n                var make_dynamic = argc >= 2 && JSApi.JS_ToBool(ctx, argv[1]) == 1;\r\n\r\n                if (JSApi.JS_IsFunction(ctx, argv[0]) == 1)\r\n                {\r\n                    return JSApi.JS_DupValue(ctx, argv[0]);\r\n                }\r\n\r\n                if (JSApi.JS_IsObject(argv[0]))\r\n                {\r\n                    Delegate o;\r\n                    if (Values.js_get_delegate_unsafe(ctx, argv[0], out o))\r\n                    {\r\n                        if (o != null)\r\n                        {\r\n                            var sd = o.Target as ScriptDelegate;\r\n                            if (sd != null)\r\n                            {\r\n                                return JSApi.JS_DupValue(ctx, sd);\r\n                            }\r\n\r\n                            // 尝试将传入的委托转换为 js function\r\n                            // c# delegate 通过 dynamic method wrapper 产生一个 jsvalue \r\n                            // 谨慎: 无法再从 function 还原此委托, 两者不会建立关联 (构成强引用循环)\r\n                            // 谨慎: NewDynamicDelegate 会产生一个与 Runtime 相同生命周期的对象, 该对象将持有 Delegate 对象引用\r\n                            if (make_dynamic)\r\n                            {\r\n                                var context = ScriptEngine.GetContext(ctx);\r\n                                var types = context.GetTypeDB();\r\n                                var name = context.GetAtom(o.Method.Name);\r\n\r\n                                return types.NewDynamicDelegate(name, o);\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        // 尝试将传入的 function 转换为 cs delegate\r\n        // 暂时只转换 ScriptDelegate\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static unsafe JSValue to_cs_delegate(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc == 2)\r\n            {\r\n                var type_name = JSApi.GetString(ctx, argv[1]);\r\n                var type = Values.FindType(type_name);\r\n                if (type != null)\r\n                {\r\n                    Delegate d;\r\n                    if (Values.js_get_delegate(ctx, argv[0], type, out d))\r\n                    {\r\n                        return Values.js_push_object(ctx, d);\r\n                    }\r\n                }\r\n            }\r\n\r\n            return ctx.ThrowInternalError(\"invalid parameters\");\r\n        }\r\n\r\n        // arraybuffer => c# array<byte>\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static unsafe JSValue to_cs_bytes(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc < 1)\r\n            {\r\n                return ctx.ThrowInternalError(\"byte[] expected\");\r\n            }\r\n\r\n            byte[] o;\r\n            if (!Values.js_get_primitive(ctx, argv[0], out o))\r\n            {\r\n                return ctx.ThrowInternalError(\"byte[] expected\");\r\n            }\r\n\r\n            return Values.js_push_classvalue(ctx, o);\r\n        }\r\n\r\n        // c# array<byte> => js arraybuffer\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static unsafe JSValue to_js_array_buffer(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc < 1)\r\n            {\r\n                return ctx.ThrowInternalError(\"byte[] expected\");\r\n            }\r\n\r\n            byte[] o;\r\n            if (!Values.js_get_classvalue(ctx, argv[0], out o))\r\n            {\r\n                return ctx.ThrowInternalError(\"byte[] expected\");\r\n            }\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            fixed (byte* mem_ptr = o)\r\n            {\r\n                return JSApi.JS_NewArrayBufferCopy(ctx, mem_ptr, o.Length);\r\n            }\r\n        }\r\n\r\n        // c# array => js array\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue to_js_array(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc < 1)\r\n            {\r\n                return ctx.ThrowInternalError(\"array expected\");\r\n            }\r\n            if (JSApi.JS_IsArray(ctx, argv[0]) == 1)\r\n            {\r\n                return JSApi.JS_DupValue(ctx, argv[0]);\r\n            }\r\n\r\n            Array o;\r\n            if (!Values.js_get_classvalue<Array>(ctx, argv[0], out o))\r\n            {\r\n                return ctx.ThrowInternalError(\"array expected\");\r\n            }\r\n            if (o == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n            var len = o.Length;\r\n            var rval = JSApi.JS_NewArray(ctx);\r\n            try\r\n            {\r\n                for (var i = 0; i < len; i++)\r\n                {\r\n                    var obj = o.GetValue(i);\r\n                    var elem = Values.js_push_var(ctx, obj);\r\n                    if (elem.IsException())\r\n                    {\r\n                        JSApi.JS_FreeValue(ctx, rval);\r\n                        return elem;\r\n                    }\r\n                    JSApi.JS_SetPropertyUint32(ctx, rval, (uint)i, elem);\r\n                }\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                JSApi.JS_FreeValue(ctx, rval);\r\n                return ctx.ThrowException(exception);\r\n            }\r\n            return rval;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue yield_func(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc < 1)\r\n            {\r\n                return ctx.ThrowInternalError(\"type YieldInstruction or Task expected\");\r\n            }\r\n            object awaitObject;\r\n            if (Values.js_get_cached_object(ctx, argv[0], out awaitObject))\r\n            {\r\n                var context = ScriptEngine.GetContext(ctx);\r\n                var co = context.GetAsyncManager();\r\n                if (co != null)\r\n                {\r\n                    return co.Yield(context, awaitObject);\r\n                }\r\n\r\n                return ctx.ThrowInternalError(\"no async manager\");\r\n                // return context.Yield(awaitObject);\r\n            }\r\n\r\n            return ctx.ThrowInternalError(\"type YieldInstruction or Task expected\");\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue _set_disposable(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc != 2 || !argv[0].IsObject() || !argv[1].IsBoolean())\r\n            {\r\n                return ctx.ThrowInternalError(\"invalid args\");\r\n            }\r\n\r\n            bool disposable;\r\n            if (Values.js_get_primitive(ctx, argv[1], out disposable) && Values.js_set_cached_object_disposable(ctx, argv[0], disposable))\r\n            {\r\n                return JSApi.JS_TRUE;\r\n            }\r\n\r\n            return JSApi.JS_FALSE;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue js_import_type(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc < 1 || !argv[0].IsString())\r\n            {\r\n                return ctx.ThrowInternalError(\"type_name expected\");\r\n            }\r\n\r\n            var type_name = JSApi.GetString(ctx, argv[0]);\r\n            var type = Values.FindType(type_name);\r\n\r\n            if (type == null)\r\n            {\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n\r\n            var privateAccess = false;\r\n            if (argc > 1 && argv[1].IsBoolean())\r\n            {\r\n                if (JSApi.JS_ToBool(ctx, argv[1]) == 1)\r\n                {\r\n                    privateAccess = true;\r\n                }\r\n            }\r\n\r\n            var runtime = ScriptEngine.GetRuntime(ctx);\r\n            var db = runtime.GetTypeDB();\r\n            var proto = db.GetPrototypeOf(type);\r\n\r\n            db.GetDynamicType(type, privateAccess);\r\n            // get proto again after dynamic type alloc if proto is undefined\r\n            if (proto.IsNullish())\r\n            {\r\n                proto = db.GetPrototypeOf(type);\r\n            }\r\n\r\n            return JSApi.JS_GetProperty(ctx, proto, JSApi.JS_ATOM_constructor);\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue ModuleManager_BeginReload(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            if (context != null)\r\n            {\r\n                context.BeginModuleReload();\r\n            }\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue ModuleManager_MarkReload(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc < 1 || !argv[0].IsString())\r\n            {\r\n                return ctx.ThrowInternalError(\"resolved module_id expected\");\r\n            }\r\n\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            if (context != null)\r\n            {\r\n                var module_id = JSApi.GetString(ctx, argv[0]);\r\n                if (!string.IsNullOrEmpty(module_id))\r\n                {\r\n                    context.MarkModuleReload(module_id);\r\n                    return JSApi.JS_TRUE;\r\n                }\r\n            }\r\n            return JSApi.JS_FALSE;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue ModuleManager_EndReload(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            if (context != null)\r\n            {\r\n                context.EndModuleReload();\r\n            }\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        // EXPERIMENTAL\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue ArrayLike_GetLength(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc < 1 || !argv[0].IsObject())\r\n            {\r\n                return ctx.ThrowInternalError(\"unknown type\");\r\n            }\r\n\r\n            object o;\r\n            if (Values.js_get_cached_object(ctx, argv[0], out o) && o != null)\r\n            {\r\n                if (o is Array array)\r\n                {\r\n                    return JSApi.JS_NewInt32(ctx, array.Length);\r\n                }\r\n            }\r\n            return ctx.ThrowInternalError(\"unknown type\");\r\n        }\r\n\r\n        // EXPERIMENTAL\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue ArrayLike_GetValue(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc < 2 || !argv[0].IsObject() || !argv[1].IsNumber())\r\n            {\r\n                return ctx.ThrowInternalError(\"unknown type\");\r\n            }\r\n\r\n            int index;\r\n            if (!Values.js_get_primitive(ctx, argv[1], out index))\r\n            {\r\n                return ctx.ThrowInternalError(\"unknown type\");\r\n            }\r\n\r\n            object o;\r\n            if (Values.js_get_cached_object(ctx, argv[0], out o) && o != null)\r\n            {\r\n                if (o is Array array)\r\n                {\r\n                    return Values.js_push_var(ctx, array.GetValue(index));\r\n                }\r\n            }\r\n            return ctx.ThrowInternalError(\"unknown type\");\r\n        }\r\n\r\n        // EXPERIMENTAL\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue ArrayLike_SetValue(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc < 3 || !argv[0].IsObject() || !argv[1].IsNumber())\r\n            {\r\n                return ctx.ThrowInternalError(\"unknown type\");\r\n            }\r\n\r\n            int index;\r\n            if (!Values.js_get_primitive(ctx, argv[1], out index))\r\n            {\r\n                return ctx.ThrowInternalError(\"unknown type\");\r\n            }\r\n\r\n            object o;\r\n            if (Values.js_get_cached_object(ctx, argv[0], out o) && o != null)\r\n            {\r\n                if (o is Array array)\r\n                {\r\n                    if (index >= array.Length)\r\n                    {\r\n                        _ArrayResize(ref array, index + 1);\r\n                        Values.js_rebind_this(ctx, argv[0], ref array);\r\n                    }\r\n                    object value;\r\n                    if (Values.js_get_var(ctx, argv[2], o.GetType().GetElementType(), out value))\r\n                    {\r\n                        array.SetValue(value, index);\r\n                        return JSApi.JS_UNDEFINED;\r\n                    }\r\n                }\r\n            }\r\n            return ctx.ThrowInternalError(\"unknown type\");\r\n        }\r\n\r\n        private static void _ArrayResize(ref Array array, int newSize)\r\n        {\r\n            var sourceArray = array;\r\n            if (sourceArray.Length != newSize)\r\n            {\r\n                var destinationArray = Array.CreateInstance(array.GetType().GetElementType(), newSize);\r\n                Array.Copy((Array)sourceArray, 0, (Array)destinationArray, 0, sourceArray.Length > newSize ? newSize : sourceArray.Length);\r\n                array = destinationArray;\r\n            }\r\n        }\r\n\r\n        // EXPERIMENTAL\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue ArrayLike_RemoveAt(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc < 2 || !argv[0].IsObject() || !argv[1].IsNumber())\r\n            {\r\n                return ctx.ThrowInternalError(\"unknown type\");\r\n            }\r\n\r\n            int index;\r\n            if (!Values.js_get_primitive(ctx, argv[1], out index))\r\n            {\r\n                return ctx.ThrowInternalError(\"unknown type\");\r\n            }\r\n\r\n            object o;\r\n            if (Values.js_get_cached_object(ctx, argv[0], out o) && o != null)\r\n            {\r\n                if (o is Array array)\r\n                {\r\n                    var len = array.Length;\r\n                    for (var i = index; i < len - 1; ++i)\r\n                    {\r\n                        array.SetValue(array.GetValue(i + 1), i);\r\n                    }\r\n                    _ArrayResize(ref array, len - 1);\r\n                    Values.js_rebind_this(ctx, argv[0], ref array);\r\n                    return JSApi.JS_UNDEFINED;\r\n                }\r\n            }\r\n            return ctx.ThrowInternalError(\"unknown type\");\r\n        }\r\n\r\n        // EXPERIMENTAL\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue ArrayLike_Insert(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc < 3 || !argv[0].IsObject() || !argv[1].IsNumber())\r\n            {\r\n                return ctx.ThrowInternalError(\"unknown type\");\r\n            }\r\n\r\n            int index;\r\n            if (!Values.js_get_primitive(ctx, argv[1], out index))\r\n            {\r\n                return ctx.ThrowInternalError(\"unknown type\");\r\n            }\r\n\r\n            object o;\r\n            if (Values.js_get_cached_object(ctx, argv[0], out o) && o != null)\r\n            {\r\n                if (o is Array array)\r\n                {\r\n                    if (index >= array.Length)\r\n                    {\r\n                        _ArrayResize(ref array, index + 1);\r\n                        Values.js_rebind_this(ctx, argv[0], ref array);\r\n                    }\r\n                    object value;\r\n                    if (Values.js_get_var(ctx, argv[2], o.GetType().GetElementType(), out value))\r\n                    {\r\n                        var len = array.Length;\r\n                        for (var i = index; i < len - 1; ++i)\r\n                        {\r\n                            array.SetValue(array.GetValue(i), i + 1);\r\n                        }\r\n                        array.SetValue(value, index);\r\n                        return JSApi.JS_UNDEFINED;\r\n                    }\r\n                }\r\n            }\r\n            return ctx.ThrowInternalError(\"unknown type\");\r\n        }\r\n\r\n        //TODO: 临时代码\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue hotfix_replace_single(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc < 3)\r\n            {\r\n                return ctx.ThrowInternalError(\"type_name, func_name, func expected\");\r\n            }\r\n            if (!argv[0].IsString() || !argv[1].IsString() || JSApi.JS_IsFunction(ctx, argv[2]) != 1)\r\n            {\r\n                return ctx.ThrowInternalError(\"type_name, func_name expected\");\r\n            }\r\n\r\n            var type_name = JSApi.GetString(ctx, argv[0]);\r\n            var field_name = JSApi.GetString(ctx, argv[1]);\r\n            var type = Assembly.GetExecutingAssembly().GetType(type_name);\r\n            if (type == null)\r\n            {\r\n                return ctx.ThrowInternalError(\"no such type\");\r\n            }\r\n\r\n            var runtime = ScriptEngine.GetRuntime(ctx);\r\n            var db = runtime.GetTypeDB();\r\n            var hotfixBaseName = field_name != \".ctor\" ? \"_JSFIX_R_\" + field_name + \"_\" : \"_JSFIX_RC_ctor_\";\r\n            var hotfixSlot = 0;\r\n\r\n            do\r\n            {\r\n                var hotfixName = hotfixBaseName + hotfixSlot;\r\n                var field = type.GetField(hotfixName);\r\n                if (field == null)\r\n                {\r\n                    if (hotfixSlot == 0)\r\n                    {\r\n                        return ctx.ThrowInternalError(\"invalid hotfix point\");\r\n                    }\r\n                    break;\r\n                }\r\n                Delegate d;\r\n                if (Values.js_get_delegate(ctx, argv[2], field.FieldType, out d))\r\n                {\r\n                    field.SetValue(null, d);\r\n                }\r\n                ++hotfixSlot;\r\n            } while (true);\r\n\r\n            db.GetDynamicType(type, true);\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        //TODO: 临时代码\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue hotfix_before_single(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc < 3)\r\n            {\r\n                return ctx.ThrowInternalError(\"type_name, func_name, func expected\");\r\n            }\r\n            if (!argv[0].IsString() || !argv[1].IsString() || JSApi.JS_IsFunction(ctx, argv[2]) != 1)\r\n            {\r\n                return ctx.ThrowInternalError(\"type_name, func_name expected\");\r\n            }\r\n\r\n            var type_name = JSApi.GetString(ctx, argv[0]);\r\n            var field_name = JSApi.GetString(ctx, argv[1]);\r\n            var type = Assembly.GetExecutingAssembly().GetType(type_name);\r\n            if (type == null)\r\n            {\r\n                return ctx.ThrowInternalError(\"no such type\");\r\n            }\r\n\r\n            var runtime = ScriptEngine.GetRuntime(ctx);\r\n            var db = runtime.GetTypeDB();\r\n            var hotfixBaseName = field_name != \".ctor\" ? \"_JSFIX_B_\" + field_name + \"_\" : \"_JSFIX_BC_ctor_\";\r\n            var hotfixSlot = 0;\r\n\r\n            do\r\n            {\r\n                var hotfixName = hotfixBaseName + hotfixSlot;\r\n                var field = type.GetField(hotfixName);\r\n                if (field == null)\r\n                {\r\n                    if (hotfixSlot == 0)\r\n                    {\r\n                        return ctx.ThrowInternalError(\"invalid hotfix point\");\r\n                    }\r\n                    break;\r\n                }\r\n                Delegate d;\r\n                if (Values.js_get_delegate(ctx, argv[2], field.FieldType, out d))\r\n                {\r\n                    field.SetValue(null, d);\r\n                }\r\n                ++hotfixSlot;\r\n            } while (true);\r\n\r\n            db.GetDynamicType(type, true);\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptContext_funcs.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 7c241eb8fcac13346b417c3c6c550af9\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptDelegate.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Threading;\r\nusing QuickJS.Native;\r\n\r\nnamespace QuickJS\r\n{\r\n    // 刻意与 ScriptValue 隔离\r\n    public class ScriptDelegate : GCObject, Utils.IWeakMapEntry\r\n    {\r\n        protected /*readonly*/ JSValue _jsValue;\r\n\r\n        // 一个 JSValue (function) 可能会被用于映射多个委托对象\r\n        private List<WeakReference<Delegate>> _matches = new List<WeakReference<Delegate>>();\r\n\r\n        public bool isValid => ctx != JSContext.Null;\r\n\r\n        internal ScriptDelegate(ScriptContext context, JSValue jsValue)\r\n        : base(context)\r\n        {\r\n            _jsValue = JSApi.JS_DupValue(context, jsValue);\r\n            // ScriptDelegate 拥有 js 对象的强引用, 此 js 对象无法释放 cache 中的 object, 所以这里用弱引用注册\r\n            // 会出现的问题是, 如果 c# 没有对 ScriptDelegate 的强引用, 那么反复 get_delegate 会重复创建 ScriptDelegate\r\n            context.GetObjectCache().AddDelegate(_jsValue, this);\r\n#if JSB_DEBUG\r\n            Diagnostics.Logger.Default.Debug(\"Alloc DelegateValue {0}\", _jsValue);\r\n#endif\r\n        }\r\n\r\n        public static implicit operator JSValue(ScriptDelegate value)\r\n        {\r\n            return value._jsValue;\r\n        }\r\n\r\n        // should only be invoked on the script runtime thread or C# gc thread (from C# finalizer)\r\n        protected override void OnDisposing(ScriptContext context)\r\n        {\r\n            var jsValue = _jsValue;\r\n            _jsValue = JSApi.JS_UNDEFINED;\r\n\r\n#if JSB_DEBUG\r\n            Diagnostics.Logger.Default.Debug(\"FreeDelegationValue {0}\", jsValue);\r\n#endif\r\n            context.GetRuntime().FreeDelegationValue(jsValue);\r\n        }\r\n\r\n        public override int GetHashCode()\r\n        {\r\n            return _jsValue.GetHashCode();\r\n        }\r\n\r\n        public override bool Equals(object obj)\r\n        {\r\n            if (obj is ScriptDelegate)\r\n            {\r\n                var other = (ScriptDelegate)obj;\r\n                return other._jsValue == _jsValue;\r\n            }\r\n\r\n            if (obj is JSValue)\r\n            {\r\n                var other = (JSValue)obj;\r\n                return other == _jsValue;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public Delegate Any()\r\n        {\r\n            Delegate d;\r\n            for (int i = 0, count = _matches.Count; i < count; ++i)\r\n            {\r\n                var item = _matches[i];\r\n                if (item.TryGetTarget(out d))\r\n                {\r\n                    return d;\r\n                }\r\n            }\r\n            return null;\r\n        }\r\n\r\n        public Delegate Match(Type delegateType)\r\n        {\r\n            Delegate d;\r\n            for (int i = 0, count = _matches.Count; i < count; i++)\r\n            {\r\n                var item = _matches[i];\r\n                if (item.TryGetTarget(out d) && d.GetType() == delegateType)\r\n                {\r\n                    return d;\r\n                }\r\n            }\r\n            return null;\r\n        }\r\n\r\n        public void Add(Delegate d)\r\n        {\r\n            if (d == null)\r\n            {\r\n                throw new ArgumentNullException();\r\n            }\r\n            _matches.Add(new WeakReference<Delegate>(d));\r\n        }\r\n\r\n        public unsafe JSValue Invoke(JSContext ctx)\r\n        {\r\n            JSValue rval = JSApi.JS_Call(ctx, _jsValue, JSApi.JS_UNDEFINED, 0, (JSValue*)0);\r\n            return rval;\r\n        }\r\n\r\n        public unsafe JSValue Invoke(JSContext ctx, int argc, JSValue[] argv)\r\n        {\r\n            fixed (JSValue* ptr = argv)\r\n            {\r\n                JSValue rval = JSApi.JS_Call(ctx, _jsValue, JSApi.JS_UNDEFINED, argc, ptr);\r\n                return rval;\r\n            }\r\n        }\r\n\r\n        public unsafe JSValue Invoke(JSContext ctx, int argc, JSValue* argv)\r\n        {\r\n            JSValue rval = JSApi.JS_Call(ctx, _jsValue, JSApi.JS_UNDEFINED, argc, argv);\r\n            return rval;\r\n        }\r\n\r\n        public unsafe JSValue Invoke(JSContext ctx, JSValue this_obj)\r\n        {\r\n            JSValue rval = JSApi.JS_Call(ctx, _jsValue, this_obj, 0, (JSValue*)0);\r\n            return rval;\r\n        }\r\n\r\n        public unsafe JSValue Invoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            fixed (JSValue* ptr = argv)\r\n            {\r\n                JSValue rval = JSApi.JS_Call(ctx, _jsValue, this_obj, argc, ptr);\r\n                return rval;\r\n            }\r\n        }\r\n\r\n        public unsafe JSValue Invoke(JSContext ctx, JSValue this_obj, int argc, JSValue* argv)\r\n        {\r\n            JSValue rval = JSApi.JS_Call(ctx, _jsValue, this_obj, argc, argv);\r\n            return rval;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptDelegate.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 0fc2d84d072f7fd4eb51e438e06a6f90\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptEngine.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Threading;\r\nusing QuickJS.Native;\r\nusing QuickJS.Utils;\r\n\r\nnamespace QuickJS\r\n{\r\n    public class ScriptEngine\r\n    {\r\n        private class ScriptRuntimeRef\r\n        {\r\n            public int next;\r\n            public ScriptRuntime target;\r\n            public bool isEditorRuntime;\r\n        }\r\n\r\n        public const uint VERSION = 0x723 + 170;\r\n\r\n        private static int _freeSlot = -1;\r\n        private static List<ScriptRuntimeRef> _runtimeRefs = new List<ScriptRuntimeRef>();\r\n        private static ReaderWriterLockSlim _rwlock = new ReaderWriterLockSlim();\r\n\r\n        private static IO.ByteBufferThreadedPooledAllocator _sharedAllocator;\r\n\r\n        /// <summary>\r\n        /// a new runtime is created, this event would always be raised on the script runtime thread.\r\n        /// NOTE: due to it's impossible to create a worker in worker thread for now.\r\n        /// </summary>\r\n        public static event Action<ScriptRuntime> RuntimeCreated;\r\n        public static event Action<ScriptRuntime> RuntimeInitialized;\r\n\r\n        static ScriptEngine()\r\n        {\r\n            _sharedAllocator = new IO.ByteBufferThreadedPooledAllocator();\r\n        }\r\n\r\n        // unstable interface\r\n        public static int ForEachRuntime(Action<ScriptRuntime> visitor)\r\n        {\r\n            var count = 0;\r\n            try\r\n            {\r\n                _rwlock.EnterReadLock();\r\n                for (int i = 0, len = _runtimeRefs.Count; i < len; ++i)\r\n                {\r\n                    var slot = _runtimeRefs[i];\r\n                    if (slot.target != null && slot.target.isValid)\r\n                    {\r\n                        count++;\r\n                        visitor(slot.target);\r\n                    }\r\n                }\r\n            }\r\n            finally\r\n            {\r\n                _rwlock.ExitReadLock();\r\n            }\r\n            return count;\r\n        }\r\n\r\n        public static ObjectCache GetObjectCache(JSRuntime rt)\r\n        {\r\n            return GetRuntime(rt)?.GetObjectCache();\r\n        }\r\n\r\n        public static ObjectCache GetObjectCache(JSContext ctx)\r\n        {\r\n            return GetRuntime(ctx)?.GetObjectCache();\r\n        }\r\n\r\n        public static ITypeDB GetTypeDB(JSContext ctx)\r\n        {\r\n            return GetRuntime(ctx)?.GetTypeDB();\r\n        }\r\n\r\n        public static ITimerManager GetTimerManager(JSContext ctx)\r\n        {\r\n            return GetRuntime(ctx)?.GetTimerManager();\r\n        }\r\n\r\n        // 可跨越运行时分配 (但内容非线程安全)\r\n        public static IO.ByteBuffer AllocSharedByteBuffer(int size)\r\n        {\r\n            return _sharedAllocator.Alloc(size);\r\n        }\r\n\r\n        /// <summary>\r\n        /// 分配一个在指定 JSContext 下使用的 Buffer\r\n        /// </summary>\r\n        public static IO.ByteBuffer AllocByteBuffer(JSContext ctx, int size)\r\n        {\r\n            return GetRuntime(ctx)?.GetByteBufferAllocator()?.Alloc(size);\r\n        }\r\n\r\n        public static bool IsEditorRuntime(ScriptRuntime runtime)\r\n        {\r\n            var result = false;\r\n            _rwlock.EnterWriteLock();\r\n            var len = _runtimeRefs.Count;\r\n            \r\n            for (int i = 0; i < len; ++i)\r\n            {\r\n                var runtimeRef = _runtimeRefs[i];\r\n                if (runtimeRef.target == runtime)\r\n                {\r\n                    result = true;\r\n                    break;\r\n                }\r\n            }\r\n            _rwlock.ExitWriteLock();\r\n            return result;\r\n        }\r\n\r\n        /// <summary>\r\n        /// (内部使用) 获取第一个有效的前台运行时 (不包括编辑器运行时)\r\n        /// </summary>\r\n        public static ScriptRuntime GetRuntime(bool isEditorRuntime)\r\n        {\r\n            ScriptRuntime target = null;\r\n            _rwlock.EnterWriteLock();\r\n            var len = _runtimeRefs.Count;\r\n            \r\n            for (int i = 0; i < len; ++i)\r\n            {\r\n                var runtimeRef = _runtimeRefs[i];\r\n                if (runtimeRef.isEditorRuntime == isEditorRuntime)\r\n                {\r\n                    var runtime = runtimeRef.target;\r\n                    if (runtime != null && !runtime.isWorker && runtime.isRunning && runtime.isValid)\r\n                    {\r\n                        target = runtime;\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n            _rwlock.ExitWriteLock();\r\n            return target;\r\n        }\r\n\r\n        /// <summary>\r\n        /// (内部使用) 获取第一个有效的前台运行时\r\n        /// </summary>\r\n        public static ScriptRuntime GetRuntime()\r\n        {\r\n            ScriptRuntime target = null;\r\n            _rwlock.EnterWriteLock();\r\n            var len = _runtimeRefs.Count;\r\n            \r\n            for (int i = 0; i < len; ++i)\r\n            {\r\n                var runtimeRef = _runtimeRefs[i];\r\n                var runtime = runtimeRef.target;\r\n\r\n                if (runtime != null && !runtime.isWorker && runtime.isRunning && runtime.isValid)\r\n                {\r\n                    target = runtime;\r\n                    break;\r\n                }\r\n            }\r\n            _rwlock.ExitWriteLock();\r\n            return target;\r\n        }\r\n\r\n        public static ScriptRuntime GetRuntime(JSContext ctx)\r\n        {\r\n            return ctx.IsValid() ? GetRuntime(JSApi.JS_GetRuntime(ctx)) : null;\r\n        }\r\n\r\n        public static ScriptRuntime GetRuntime(JSRuntime rt)\r\n        {\r\n            ScriptRuntime runtime = null;\r\n\r\n            if (rt.IsValid())\r\n            {\r\n                var id = (int)JSApi.JSB_GetRuntimeOpaque(rt);\r\n                if (id > 0)\r\n                {\r\n                    var index = id - 1;\r\n                    _rwlock.EnterReadLock();\r\n                    var slot = _runtimeRefs[index];\r\n                    runtime = slot.target;\r\n                    _rwlock.ExitReadLock();\r\n                }\r\n            }\r\n\r\n            return runtime;\r\n        }\r\n\r\n        /// <summary>\r\n        /// (内部使用) 获取第一个有效的前台运行时的 MainContext\r\n        /// </summary>\r\n        public static ScriptContext GetContext()\r\n        {\r\n            var context = GetRuntime();\r\n\r\n            if (context != null && context.isValid)\r\n            {\r\n                return context.GetMainContext();\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        public static ScriptContext GetContext(JSContext ctx)\r\n        {\r\n            if (ctx.IsValid())\r\n            {\r\n                var rt = JSApi.JS_GetRuntime(ctx);\r\n                return GetRuntime(rt)?.GetContext(ctx);\r\n            }\r\n            return null;\r\n        }\r\n\r\n        public static ScriptRuntime CreateRuntime()\r\n        {\r\n            return CreateRuntime(false);\r\n        }\r\n\r\n        public static ScriptRuntime CreateRuntime(bool isEditorRuntime)\r\n        {\r\n            if (!JSApi.IsValid())\r\n            {\r\n                throw new InvalidOperationException(\"quickjs library is not matched, you need to rebuild it for current platform\");\r\n            }\r\n\r\n            _rwlock.EnterWriteLock();\r\n            ScriptRuntimeRef freeEntry;\r\n            int slotIndex;\r\n            if (_freeSlot < 0)\r\n            {\r\n                freeEntry = new ScriptRuntimeRef();\r\n                slotIndex = _runtimeRefs.Count;\r\n                _runtimeRefs.Add(freeEntry);\r\n                freeEntry.next = -1;\r\n            }\r\n            else\r\n            {\r\n                slotIndex = _freeSlot;\r\n                freeEntry = _runtimeRefs[slotIndex];\r\n                _freeSlot = freeEntry.next;\r\n                freeEntry.next = -1;\r\n            }\r\n\r\n            var runtime = new ScriptRuntime(slotIndex + 1);\r\n            freeEntry.target = runtime;\r\n            freeEntry.isEditorRuntime = isEditorRuntime;\r\n            runtime.OnAfterDestroy += OnRuntimeAfterDestroy;\r\n            runtime.OnInitialized += OnRuntimeInitialized;\r\n            _rwlock.ExitWriteLock();\r\n            RuntimeCreated?.Invoke(runtime);\r\n            \r\n            return runtime;\r\n        }\r\n\r\n        /// <summary>\r\n        /// 关闭所有运行时 (不包括编辑器运行时)\r\n        /// </summary>\r\n        public static void Shutdown()\r\n        {\r\n            _rwlock.EnterWriteLock();\r\n            var len = _runtimeRefs.Count;\r\n            var copylist = new List<ScriptRuntime>(len);\r\n            for (int i = 0; i < len; ++i)\r\n            {\r\n                var runtimeRef = _runtimeRefs[i];\r\n                if (!runtimeRef.isEditorRuntime)\r\n                {\r\n                    var runtime = runtimeRef.target;\r\n                    if (runtime != null)\r\n                    {\r\n                        copylist.Add(runtime);\r\n                    }\r\n                }\r\n            }\r\n            _rwlock.ExitWriteLock();\r\n\r\n            for (int i = 0, count = copylist.Count; i < count; ++i)\r\n            {\r\n                var runtime = copylist[i];\r\n                runtime.Shutdown();\r\n            }\r\n        }\r\n\r\n        private static void OnRuntimeInitialized(ScriptRuntime runtime)\r\n        {\r\n            runtime.OnInitialized -= OnRuntimeInitialized;\r\n            RuntimeInitialized?.Invoke(runtime);\r\n        }\r\n\r\n        private static void OnRuntimeAfterDestroy(int runtimeId)\r\n        {\r\n            if (runtimeId <= 0)\r\n            {\r\n                return;\r\n            }\r\n            _rwlock.EnterWriteLock();\r\n            var index = runtimeId - 1;\r\n            var freeEntry = _runtimeRefs[index];\r\n            freeEntry.next = _freeSlot;\r\n            freeEntry.target = null;\r\n            _freeSlot = index;\r\n            _rwlock.ExitWriteLock();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptEngine.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 7513d785eb5d4dfa8d5baca5349cbb9a\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptFunction.cs",
    "content": "﻿using System;\r\n\r\nnamespace QuickJS\r\n{\r\n    using QuickJS.Native;\r\n    using QuickJS.Errors;\r\n\r\n    public class ScriptFunction : GCObject, Utils.IInvokable\r\n    {\r\n        private JSValue _fnValue;\r\n        private JSValue _thisValue;\r\n        private JSValue[] _args;\r\n\r\n        public ScriptFunction(ScriptContext context, JSValue fnValue)\r\n            : base(context)\r\n        {\r\n            _fnValue = JSApi.JS_DupValue(context, fnValue);\r\n            _thisValue = JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        public ScriptFunction(ScriptContext context, JSValue fnValue, JSValue thisValue)\r\n            : base(context)\r\n        {\r\n            _fnValue = JSApi.JS_DupValue(context, fnValue);\r\n            _thisValue = JSApi.JS_DupValue(context, thisValue);\r\n        }\r\n\r\n        public ScriptFunction(ScriptContext context, JSValue fnValue, JSValue thisValue, JSValue[] args)\r\n            : base(context)\r\n        {\r\n            var ctx = (JSContext)context;\r\n            _fnValue = JSApi.JS_DupValue(context, fnValue);\r\n            _thisValue = JSApi.JS_DupValue(context, thisValue);\r\n            _args = args;\r\n            for (int i = 0, count = _args.Length; i < count; i++)\r\n            {\r\n                JSApi.JS_DupValue(ctx, _args[i]);\r\n            }\r\n        }\r\n\r\n        public void SetBound(JSValue thisValue)\r\n        {\r\n            var ctx = (JSContext)this;\r\n            JSApi.JS_FreeValue(ctx, _thisValue);\r\n            _thisValue = JSApi.JS_DupValue(ctx, thisValue);\r\n        }\r\n\r\n        public unsafe void SetArguments(int offset, int size, JSValue[] values)\r\n        {\r\n            fixed (JSValue* ptr = values)\r\n            {\r\n                SetArguments(offset, size, ptr);\r\n            }\r\n        }\r\n\r\n        public unsafe void SetArguments(int offset, int size, JSValue* values)\r\n        {\r\n            var ctx = (JSContext)this;\r\n            \r\n            if (_args != null)\r\n            {\r\n                JSApi.JS_FreeValue(ctx, _args);\r\n            }\r\n\r\n            if (size > 0)\r\n            {\r\n                _args = new JSValue[size];\r\n                for (var i = 0; i < size; ++i)\r\n                {\r\n                    _args[i] = JSApi.JS_DupValue(ctx, values[offset + i]);\r\n                }\r\n            }\r\n            else\r\n            {\r\n                _args = null;\r\n            }\r\n        }\r\n\r\n        public static implicit operator JSValue(ScriptFunction value)\r\n        {\r\n            return value != null ? value._fnValue : JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        protected override void OnDisposing(ScriptContext context)\r\n        {\r\n            var fnValue = _fnValue;\r\n            var thisValue = _thisValue;\r\n            var args = _args;\r\n\r\n            _fnValue = JSApi.JS_UNDEFINED;\r\n            _thisValue = JSApi.JS_UNDEFINED;\r\n            _args = null;\r\n\r\n            context.FreeValue(fnValue);\r\n            context.FreeValue(thisValue);\r\n            context.FreeValues(args);\r\n        }\r\n\r\n        public unsafe void Invoke()\r\n        {\r\n            Invoke(typeof(void));\r\n        }\r\n\r\n        public unsafe T Invoke<T>()\r\n        {\r\n            return (T)Invoke(typeof(T));\r\n        }\r\n\r\n        private unsafe object Invoke(Type resultType)\r\n        {\r\n            var ctx = (JSContext)this;\r\n            if (ctx == JSContext.Null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var argc = _args == null ? 0 : _args.Length;\r\n            fixed (JSValue* ptr = _args)\r\n            {\r\n                var rVal = JSApi.JS_Call(ctx, _fnValue, _thisValue, argc, ptr);\r\n                if (JSApi.JS_IsException(rVal))\r\n                {\r\n                    var ex = ctx.GetExceptionString();\r\n                    throw new JSException(ex);\r\n                }\r\n\r\n                object resultObject = null;\r\n                Binding.Values.js_get_var(ctx, rVal, resultType, out resultObject);\r\n                JSApi.JS_FreeValue(ctx, rVal);\r\n                return resultObject;\r\n            }\r\n        }\r\n\r\n        public void Invoke(object arg1)\r\n        {\r\n            Invoke(typeof(void), arg1);\r\n        }\r\n\r\n        public T Invoke<T>(object arg1)\r\n        {\r\n            return (T)Invoke(typeof(T), arg1);\r\n        }\r\n\r\n        public unsafe object Invoke(Type resultType, object arg1)\r\n        {\r\n            var ctx = (JSContext)this;\r\n            if (ctx == JSContext.Null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var val = Binding.Values.js_push_var(ctx, arg1);\r\n            var args = stackalloc[] { val };\r\n            var rVal = _Invoke(ctx, 1, args);\r\n            if (JSApi.JS_IsException(rVal))\r\n            {\r\n                var ex = ctx.GetExceptionString();\r\n                JSApi.JS_FreeValue(ctx, val);\r\n                throw new JSException(ex);\r\n            }\r\n            object rObj = null;\r\n            Binding.Values.js_get_var(ctx, rVal, resultType, out rObj);\r\n            JSApi.JS_FreeValue(ctx, rVal);\r\n            JSApi.JS_FreeValue(ctx, val);\r\n            return rObj;\r\n        }\r\n\r\n        public void Invoke(params object[] parameters)\r\n        {\r\n            Invoke(typeof(void), parameters);\r\n        }\r\n\r\n        public T Invoke<T>(params object[] parameters)\r\n        {\r\n            return (T)Invoke(typeof(T), parameters);\r\n        }\r\n\r\n        public unsafe object Invoke(Type resultType, params object[] parameters)\r\n        {\r\n            var ctx = (JSContext)this;\r\n            if (ctx == JSContext.Null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var count = parameters.Length;\r\n            var args = stackalloc JSValue[count];\r\n            for (var i = 0; i < count; i++)\r\n            {\r\n                args[i] = Binding.Values.js_push_var(ctx, parameters[i]);\r\n            }\r\n            var rVal = _Invoke(ctx, count, args);\r\n            if (JSApi.JS_IsException(rVal))\r\n            {\r\n                var ex = ctx.GetExceptionString();\r\n                JSApi.JS_FreeValue(ctx, count, args);\r\n                throw new JSException(ex);\r\n            }\r\n            object rObj = null;\r\n            Binding.Values.js_get_var(ctx, rVal, resultType, out rObj);\r\n            JSApi.JS_FreeValue(ctx, rVal);\r\n            JSApi.JS_FreeValue(ctx, count, args);\r\n            return rObj;\r\n        }\r\n\r\n        // unsafe primitive call, will not change ref count of jsvalue in argv\r\n        public unsafe JSValue _Invoke(JSContext ctx, int argc, JSValue* argv)\r\n        {\r\n            var rVal = JSApi.JS_Call(ctx, _fnValue, _thisValue, argc, argv);\r\n            return rVal;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptFunction.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 8bc9418121374f0eaaeb370d463cd751\r\ntimeCreated: 1591161906"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptPromise.cs",
    "content": "using System;\r\n\r\nnamespace QuickJS\r\n{\r\n    using QuickJS.Native;\r\n    using QuickJS.Errors;\r\n    \r\n    public abstract class ScriptPromise : GCObject, Utils.IObjectCollectionEntry\r\n    {\r\n        private Utils.ObjectCollection.Handle _handle;\r\n\r\n        private JSValue _promise;\r\n        private JSValue _on_resolve;\r\n        private JSValue _on_reject;\r\n\r\n        public JSValue promiseValue => _promise;\r\n        public JSValue onResolveValue => _on_resolve;\r\n        public JSValue onRejectValue => _on_reject;\r\n\r\n        internal ScriptPromise(JSContext ctx)\r\n        : this(ScriptEngine.GetContext(ctx))\r\n        {\r\n        }\r\n\r\n        internal ScriptPromise(ScriptContext context)\r\n        : base(context)\r\n        {\r\n            _promise = JSApi.JS_NewPromiseCapability(context, out _on_resolve, out _on_reject);\r\n            context.GetRuntime().AddManagedObject(this, out _handle);\r\n            // context.GetObjectCache().AddScriptPromise(_promise, this);\r\n        }\r\n\r\n        protected override void OnDisposing(ScriptContext context)\r\n        {\r\n            var on_resolve = _on_resolve;\r\n            var on_reject = _on_reject;\r\n            var promise = _promise;\r\n\r\n            _on_resolve = JSApi.JS_UNDEFINED;\r\n            _on_reject = JSApi.JS_UNDEFINED;\r\n            _promise = JSApi.JS_UNDEFINED;\r\n            var runtime = context.GetRuntime();\r\n            runtime.FreeValue(promise);\r\n            runtime.FreeValue(on_resolve);\r\n            runtime.FreeValue(on_reject);\r\n            runtime.FreeManagedObject(_handle);\r\n            // context.GetRuntime().FreeScriptPromise(promise, on_resolve, on_reject);\r\n        }\r\n\r\n        public static implicit operator JSValue(ScriptPromise value)\r\n        {\r\n            return value != null ? value._promise : JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        #region IObjectCollectionEntry implementation\r\n        public void OnCollectionReleased()\r\n        {\r\n            Dispose();\r\n        }\r\n        #endregion\r\n\r\n        public void Reject(object value = null)\r\n        {\r\n            Invoke(_on_reject, value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// 完成此 Promise\r\n        /// </summary>\r\n        /// <param name=\"index\">0 表示成功, 1 表示失败</param>\r\n        /// <param name=\"value\">传参给回调</param>\r\n        protected unsafe void Invoke(JSValue callback, object value)\r\n        {\r\n            var ctx = (JSContext)this;\r\n            if (ctx == JSContext.Null)\r\n            {\r\n                throw new NullReferenceException(\"already released\");\r\n            }\r\n            \r\n            if (JSApi.JS_IsFunction(ctx, callback) != 1)\r\n            {\r\n                Dispose();\r\n                return;\r\n            }\r\n\r\n            var backVal = Binding.Values.js_push_var(ctx, value);\r\n            if (backVal.IsException())\r\n            {\r\n                var ex = ctx.GetExceptionString();\r\n                Dispose();\r\n                throw new JSException(ex);\r\n            }\r\n\r\n            var argv = stackalloc[] { backVal };\r\n            var rval = JSApi.JS_Call(ctx, callback, JSApi.JS_UNDEFINED, 1, argv);\r\n            JSApi.JS_FreeValue(ctx, backVal);\r\n            if (rval.IsException())\r\n            {\r\n                var ex = ctx.GetExceptionString();\r\n                Dispose();\r\n                throw new JSException(ex);\r\n            }\r\n\r\n            JSApi.JS_FreeValue(ctx, rval);\r\n            Dispose();\r\n\r\n            var runtime = ScriptEngine.GetRuntime(ctx);\r\n            if (runtime != null)\r\n            {\r\n                runtime.ExecutePendingJob();\r\n            }\r\n        }\r\n    }\r\n\r\n    public class TypedScriptPromise<TResult> : ScriptPromise\r\n    {\r\n        public TypedScriptPromise(ScriptContext context)\r\n        : base(context)\r\n        {\r\n        }\r\n\r\n        public void Resolve(TResult value)\r\n        {\r\n            Invoke(onResolveValue, value);\r\n        }\r\n    }\r\n\r\n    public class AnyScriptPromise : ScriptPromise\r\n    {\r\n        public AnyScriptPromise(ScriptContext context)\r\n        : base(context)\r\n        {\r\n        }\r\n\r\n        public void Resolve(object value = null)\r\n        {\r\n            Invoke(onResolveValue, value);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptPromise.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: ec58548b20c3d4445a47b4633d1c391a\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptRuntime+Module.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.IO;\r\nusing System.Text;\r\nusing QuickJS.Native;\r\nusing System.Threading;\r\n\r\nnamespace QuickJS\r\n{\r\n    using Utils;\r\n\r\n    public partial class ScriptRuntime\r\n    {\r\n        public const uint BYTECODE_COMMONJS_MODULE_TAG = ScriptEngine.VERSION << 8 | 0x23;\r\n        public const uint BYTECODE_ES6_MODULE_TAG = ScriptEngine.VERSION << 8 | 0xfe;\r\n\r\n        public static uint TryReadByteCodeTagValue(byte[] bytes)\r\n        {\r\n            if (bytes != null && bytes.Length > sizeof(uint))\r\n            {\r\n                return TextUtils.ToHostByteOrder(BitConverter.ToUInt32(bytes, 0));\r\n            }\r\n            return 0;\r\n        }\r\n\r\n        /// <summary>\r\n        /// the 'define' function for minimalistic AMD module support\r\n        /// </summary>\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static unsafe JSValue module_define(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc != 3 || !argv[0].IsString() || JSApi.JS_IsArray(ctx, argv[1]) != 1 || JSApi.JS_IsFunction(ctx, argv[2]) != 1)\r\n            {\r\n                return ctx.ThrowInternalError(\"unsupported 'define' invocation\");\r\n            }\r\n\r\n            string[] deps;\r\n            if (!Binding.Values.js_get_primitive(ctx, argv[1], out deps))\r\n            {\r\n                return ctx.ThrowInternalError(\"unsupported 'define' invocation\");\r\n            }\r\n            var module_id = JSApi.GetString(ctx, argv[0]);\r\n            if (string.IsNullOrEmpty(module_id))\r\n            {\r\n                return ctx.ThrowInternalError(\"unsupported 'define' invocation\");\r\n            }\r\n\r\n            var runtime = ScriptEngine.GetRuntime(ctx);\r\n            var staticModuleResolver = runtime.FindModuleResolver<Module.StaticModuleResolver>();\r\n            if (staticModuleResolver != null)\r\n            {\r\n                var amd = new Module.AMDModuleRegister(ctx, deps, argv[2]);\r\n                staticModuleResolver.AddStaticModule(module_id, amd);\r\n            }\r\n            else\r\n            {\r\n                return ctx.ThrowInternalError(\"no static module resolver\");\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        public static unsafe JSValue EvalSource(JSContext ctx, string source, string fileName, bool bModule)\r\n        {\r\n            return EvalSource(ctx, Utils.TextUtils.GetNullTerminatedBytes(source), fileName, bModule);\r\n        }\r\n\r\n        public static unsafe JSValue EvalSource(JSContext ctx, byte[] source, string fileName, bool bModule)\r\n        {\r\n            if (source == null || source.Length == 0)\r\n            {\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n\r\n            var tagValue = TryReadByteCodeTagValue(source);\r\n\r\n            if (tagValue == BYTECODE_ES6_MODULE_TAG)\r\n            {\r\n                return ctx.ThrowInternalError(\"eval does not support es6 module bytecode\");\r\n            }\r\n\r\n            if (tagValue == BYTECODE_COMMONJS_MODULE_TAG)\r\n            {\r\n                fixed (byte* intput_ptr = source)\r\n                {\r\n                    var bytecodeFunc = JSApi.JS_ReadByteCode(ctx, intput_ptr + sizeof(uint), source.Length - sizeof(uint));\r\n\r\n                    if (bytecodeFunc.IsFunctionByteCode())\r\n                    {\r\n                        var func_val = JSApi.JS_EvalFunction(ctx, bytecodeFunc); // it's CallFree (bytecodeFunc)\r\n                        if (JSApi.JS_IsFunction(ctx, func_val) != 1)\r\n                        {\r\n                            JSApi.JS_FreeValue(ctx, func_val);\r\n                            return ctx.ThrowInternalError(\"failed to eval bytecode module\");\r\n                        }\r\n\r\n                        var rval = JSApi.JS_Call(ctx, func_val, JSApi.JS_UNDEFINED);\r\n                        JSApi.JS_FreeValue(ctx, func_val);\r\n                        return rval;\r\n                    }\r\n\r\n                    JSApi.JS_FreeValue(ctx, bytecodeFunc);\r\n                    return ctx.ThrowInternalError(\"failed to eval bytecode module\");\r\n                }\r\n            }\r\n\r\n            var input_bytes = Utils.TextUtils.GetNullTerminatedBytes(source);\r\n            var fn_bytes = Utils.TextUtils.GetNullTerminatedBytes(fileName);\r\n\r\n            fixed (byte* input_ptr = input_bytes)\r\n            fixed (byte* fn_ptr = fn_bytes)\r\n            {\r\n                var input_len = (size_t)(input_bytes.Length - 1);\r\n\r\n                if (bModule)\r\n                {\r\n                    return JSApi.JS_EvalModule(ctx, input_ptr, input_len, fn_ptr);\r\n                }\r\n                return JSApi.JS_EvalSource(ctx, input_ptr, input_len, fn_ptr);\r\n\r\n            }\r\n        }\r\n\r\n#if !JSB_WITH_V8_BACKEND\r\n        [MonoPInvokeCallback(typeof(JSModuleNormalizeFunc))]\r\n        public static IntPtr module_normalize(JSContext ctx, string module_base_name, string module_name, IntPtr opaque)\r\n        {\r\n            try\r\n            {\r\n                var runtime = ScriptEngine.GetRuntime(ctx);\r\n                var resolve_to = runtime.ResolveFilePath(module_base_name, module_name);\r\n                return ctx.NewCString(resolve_to);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                ctx.ThrowInternalError(exception.Message);\r\n                return IntPtr.Zero;\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSModuleLoaderFunc))]\r\n        public static unsafe JSModuleDef module_loader(JSContext ctx, string module_name, IntPtr opaque)\r\n        {\r\n            // Debug.LogFormat(\"module_loader: {0}\", module_name);\r\n            var runtime = ScriptEngine.GetRuntime(ctx);\r\n            var fileSystem = runtime._fileSystem;\r\n            if (!fileSystem.Exists(module_name))\r\n            {\r\n                ctx.ThrowReferenceError(\"module not found\");\r\n                return JSModuleDef.Null;\r\n            }\r\n\r\n            var source = fileSystem.ReadAllBytes(module_name);\r\n            var tagValue = TryReadByteCodeTagValue(source);\r\n\r\n            if (tagValue == BYTECODE_COMMONJS_MODULE_TAG)\r\n            {\r\n                ctx.ThrowReferenceError(\"commonjs module can not be loaded by import\");\r\n                return JSModuleDef.Null;\r\n            }\r\n\r\n            if (tagValue == BYTECODE_ES6_MODULE_TAG)\r\n            {\r\n                // bytecode\r\n                fixed (byte* intput_ptr = source)\r\n                {\r\n                    var modObj = JSApi.JS_ReadByteCode(ctx, intput_ptr + sizeof(uint), source.Length - sizeof(uint));\r\n                    if (!modObj.IsModule())\r\n                    {\r\n                        JSApi.JS_FreeValue(ctx, modObj);\r\n                        ctx.ThrowReferenceError(\"unsupported module object\");\r\n                        return JSModuleDef.Null;\r\n                    }\r\n\r\n                    if (JSApi.JS_ResolveModule(ctx, modObj) < 0)\r\n                    {\r\n                        // fail\r\n                        JSApi.JS_FreeValue(ctx, modObj);\r\n                        ctx.ThrowReferenceError(\"module resolve failed\");\r\n                        return JSModuleDef.Null;\r\n                    }\r\n\r\n                    return _NewModuleDef(ctx, modObj, module_name);\r\n                }\r\n            }\r\n\r\n            // source \r\n            var input_bytes = TextUtils.GetNullTerminatedBytes(source);\r\n            var fn_bytes = TextUtils.GetNullTerminatedBytes(module_name);\r\n\r\n            fixed (byte* input_ptr = input_bytes)\r\n            fixed (byte* fn_ptr = fn_bytes)\r\n            {\r\n                var input_len = (size_t)(input_bytes.Length - 1);\r\n                var func_val = JSApi.JS_CompileModule(ctx, input_ptr, input_len, fn_ptr);\r\n\r\n                if (JSApi.JS_IsException(func_val))\r\n                {\r\n                    ctx.print_exception();\r\n                    ctx.ThrowReferenceError(\"module error\");\r\n                    return JSModuleDef.Null;\r\n                }\r\n\r\n                if (func_val.IsNullish())\r\n                {\r\n                    ctx.ThrowReferenceError(\"module is null\");\r\n                    return JSModuleDef.Null;\r\n                }\r\n\r\n                return _NewModuleDef(ctx, func_val, module_name);\r\n            }\r\n        }\r\n\r\n        private static JSModuleDef _NewModuleDef(JSContext ctx, JSValue func_val, string module_name)\r\n        {\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            var mod = new JSModuleDef(func_val.u.ptr);\r\n            var meta = JSApi.JS_GetImportMeta(ctx, mod);\r\n            JSApi.JS_DefinePropertyValue(ctx, meta, context.GetAtom(\"url\"), ctx.NewString($\"file://{module_name}\"));\r\n            JSApi.JS_DefinePropertyValue(ctx, meta, context.GetAtom(\"main\"), JSApi.JS_NewBool(ctx, false));\r\n            JSApi.JS_FreeValue(ctx, meta);\r\n            return mod;\r\n        }\r\n#endif\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptRuntime+Module.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: f1086ef1b9848b3489114f20a863776f\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptRuntime.cs",
    "content": "﻿using System;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\nusing System.Threading.Tasks;\r\nusing System.IO;\r\nusing System.Threading;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS\r\n{\r\n    using Native;\r\n    using Binding;\r\n    using Utils;\r\n    using Module;\r\n\r\n    public partial class ScriptRuntime\r\n    {\r\n        private class ScriptContextRef\r\n        {\r\n            public int next;\r\n            public ScriptContext target;\r\n        }\r\n\r\n        public event Action<ScriptRuntime> OnInitializing;\r\n        public event Action<ScriptRuntime> OnInitialized;\r\n        public event Action<ScriptRuntime> OnMainModuleLoaded;\r\n\r\n        /// <summary>\r\n        /// this event will be raised after debugger connected if debug server is used, otherwise it will be raised immediately after OnInitialized\r\n        /// </summary>\r\n        public event Action<ScriptRuntime> OnDebuggerConnected;\r\n        public event Action<int> OnAfterDestroy;\r\n        public event Action OnUpdate;\r\n        public event Action<ScriptContext, string> OnScriptReloading;\r\n        public event Action<ScriptContext, string> OnScriptReloaded;\r\n        public Func<JSContext, string, string, int, string> OnSourceMap;\r\n\r\n        private JSRuntime _rt;\r\n        private int _runtimeId;\r\n        private bool _withStacktrace;\r\n        private int _freeContextSlot = -1;\r\n\r\n        // reserved feature, there is only one context for a script runtime so far.\r\n        private List<ScriptContextRef> _contextRefs = new List<ScriptContextRef>();\r\n        private ScriptContext _mainContext;\r\n\r\n        private Queue<JSAction> _pendingActions = new Queue<JSAction>();\r\n        private List<JSAction> _delayedActions = new List<JSAction>();\r\n        private List<JSAction> _executingActions = new List<JSAction>();\r\n\r\n        private int _mainThreadId;\r\n\r\n        private IFileSystem _fileSystem;\r\n        private IPathResolver _pathResolver;\r\n        private List<IModuleResolver> _moduleResolvers = new List<IModuleResolver>();\r\n        private ObjectCache _objectCache;\r\n        private ObjectCollection _objectCollection;\r\n        private ITypeDB _typeDB;\r\n        private ITimerManager _timerManager;\r\n        private IO.IByteBufferAllocator _byteBufferAllocator;\r\n        private Utils.AutoReleasePool _autorelease;\r\n        private IAsyncManager _asyncManager;\r\n\r\n        private bool _isValid; // destroy 调用后立即 = false\r\n        private bool _isRunning;\r\n        private bool _isInitialized;\r\n        private bool _isWorker;\r\n        private bool _isStaticBinding;\r\n\r\n        public bool withStacktrace\r\n        {\r\n            get { return _withStacktrace; }\r\n            set { _withStacktrace = value; }\r\n        }\r\n\r\n        public bool isInitialized { get { return _isInitialized; } }\r\n\r\n        public bool isWorker { get { return _isWorker; } }\r\n\r\n        public int id { get { return _runtimeId; } }\r\n\r\n        public bool isRunning { get { return _isRunning; } }\r\n\r\n        public bool isValid { get { return _isValid; } }\r\n\r\n        public bool isStaticBinding { get { return _isStaticBinding; } }\r\n\r\n        public ScriptRuntime(int runtimeId)\r\n        {\r\n            _runtimeId = runtimeId;\r\n            _isWorker = false;\r\n            _mainThreadId = Thread.CurrentThread.ManagedThreadId;\r\n        }\r\n\r\n        public IAsyncManager GetAsyncManager()\r\n        {\r\n            return _asyncManager;\r\n        }\r\n\r\n        public IFileSystem GetFileSystem()\r\n        {\r\n            return _fileSystem;\r\n        }\r\n\r\n        public IPathResolver GetPathResolver()\r\n        {\r\n            return _pathResolver;\r\n        }\r\n\r\n        public void AddSearchPath(string path)\r\n        {\r\n            _pathResolver.AddSearchPath(path);\r\n        }\r\n\r\n        public void AddTypeReference(ProxyModuleRegister proxy, Type type, ClassBind bind, params string[] ns)\r\n        {\r\n            proxy.Add(type, ns);\r\n            _typeDB.AddTypeBinder(type, bind);\r\n        }\r\n\r\n        // 添加默认 resolver\r\n        public void AddModuleResolvers()\r\n        {\r\n            AddModuleResolver(new StaticModuleResolver());\r\n            AddModuleResolver(new JsonModuleResolver());\r\n            AddModuleResolver(new SourceModuleResolver(new Utils.DefaultJsonConverter()));\r\n        }\r\n\r\n        public T AddModuleResolver<T>(T moduleResolver)\r\n        where T : IModuleResolver\r\n        {\r\n            _moduleResolvers.Add(moduleResolver);\r\n            return moduleResolver;\r\n        }\r\n\r\n        public T FindModuleResolver<T>()\r\n        {\r\n            for (int i = 0, count = _moduleResolvers.Count; i < count; i++)\r\n            {\r\n                var resolver = _moduleResolvers[i];\r\n                if (resolver is T)\r\n                {\r\n                    return (T)resolver;\r\n                }\r\n            }\r\n            return default(T);\r\n        }\r\n\r\n        public string ResolveFilePath(string parent_module_id, string module_id)\r\n        {\r\n            string resolved_id;\r\n            for (int i = 0, count = _moduleResolvers.Count; i < count; i++)\r\n            {\r\n                var resolver = _moduleResolvers[i];\r\n                if (resolver.ResolveModule(_fileSystem, _pathResolver, parent_module_id, module_id, out resolved_id))\r\n                {\r\n                    return resolved_id;\r\n                }\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        public string ResolveModuleId(ScriptContext context, string parent_module_id, string module_id)\r\n        {\r\n            if (module_id != null)\r\n            {\r\n                for (int i = 0, count = _moduleResolvers.Count; i < count; i++)\r\n                {\r\n                    var resolver = _moduleResolvers[i];\r\n                    string resolved_id;\r\n                    if (resolver.ResolveModule(_fileSystem, _pathResolver, parent_module_id, module_id, out resolved_id))\r\n                    {\r\n                        return resolved_id;\r\n                    }\r\n                }\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        public void ResolveModule(string module_id)\r\n        {\r\n            ResolveModule(module_id, false);\r\n        }\r\n\r\n        public void ResolveModule(string module_id, bool set_as_main)\r\n        {\r\n            if (!string.IsNullOrEmpty(module_id))\r\n            {\r\n                var rval = ResolveModule(_mainContext, \"\", module_id, set_as_main);\r\n                if (rval.IsException())\r\n                {\r\n                    JSNative.print_exception(_mainContext, \"failed to load module: \" + module_id);\r\n                }\r\n                else\r\n                {\r\n                    JSApi.JSB_FreeValueRT(_rt, rval);\r\n                }\r\n            }\r\n        }\r\n\r\n        public JSValue ResolveModule(ScriptContext context, string parent_module_id, string module_id, bool set_as_main)\r\n        {\r\n            var ctx = (JSContext)context;\r\n            for (int i = 0, count = _moduleResolvers.Count; i < count; i++)\r\n            {\r\n                var resolver = _moduleResolvers[i];\r\n                string resolved_id;\r\n                if (resolver.ResolveModule(_fileSystem, _pathResolver, parent_module_id, module_id, out resolved_id))\r\n                {\r\n                    // 如果目标模块在 reloading 列表中, 直接进入重载逻辑\r\n                    JSValue exports_obj;\r\n                    if (TryGetModuleForReloading(context, resolver, resolved_id, out exports_obj))\r\n                    {\r\n                        return exports_obj;\r\n                    }\r\n\r\n                    // 如果已经在模块缓存中, 直接返回\r\n                    JSValue module_obj;\r\n                    if (context.LoadModuleCache(resolved_id, out module_obj))\r\n                    {\r\n                        exports_obj = JSApi.JS_GetProperty(ctx, module_obj, context.GetAtom(\"exports\"));\r\n                        JSApi.JS_FreeValue(ctx, module_obj);\r\n                        return exports_obj;\r\n                    }\r\n\r\n                    // 载入新模块\r\n                    return resolver.LoadModule(context, parent_module_id, resolved_id, set_as_main);\r\n                }\r\n            }\r\n\r\n            return ctx.ThrowInternalError($\"module can not be resolved ({module_id})\");\r\n        }\r\n\r\n        public bool ReloadModule(ScriptContext context, string resolved_id)\r\n        {\r\n            JSContext ctx = context;\r\n            for (int i = 0, count = _moduleResolvers.Count; i < count; i++)\r\n            {\r\n                var resolver = _moduleResolvers[i];\r\n                JSValue exports_obj;\r\n                if (resolver.ContainsModule(_fileSystem, _pathResolver, resolved_id) && TryGetModuleForReloading(context, resolver, resolved_id, out exports_obj))\r\n                {\r\n                    JSApi.JS_FreeValue(ctx, exports_obj);\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        private bool TryGetModuleForReloading(ScriptContext context, IModuleResolver resolver, string resolved_id, out JSValue exports_obj)\r\n        {\r\n            JSValue module_obj;\r\n            if (context.TryGetModuleForReloading(resolved_id, out module_obj))\r\n            {\r\n                RaiseScriptReloadingEvent_nothrow(context, resolved_id);\r\n                if (resolver.ReloadModule(context, resolved_id, module_obj, out exports_obj))\r\n                {\r\n                    RaiseScriptReloadedEvent_nothrow(context, resolved_id);\r\n                    JSApi.JS_FreeValue(context, module_obj);\r\n                    return true;\r\n                }\r\n\r\n                JSApi.JS_FreeValue(context, module_obj);\r\n            }\r\n\r\n            exports_obj = JSApi.JS_UNDEFINED;\r\n            return false;\r\n        }\r\n\r\n        private void RaiseScriptReloadingEvent_nothrow(ScriptContext context, string resolved_id)\r\n        {\r\n            try\r\n            {\r\n                OnScriptReloading?.Invoke(context, resolved_id);\r\n                context.RaiseScriptReloadingEvent_throw(resolved_id);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                Diagnostics.Logger.Default.Exception(exception);\r\n            }\r\n        }\r\n\r\n        private void RaiseScriptReloadedEvent_nothrow(ScriptContext context, string resolved_id)\r\n        {\r\n            try\r\n            {\r\n                OnScriptReloaded?.Invoke(context, resolved_id);\r\n                context.RaiseScriptReloadedEvent_throw(resolved_id);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                Diagnostics.Logger.Default.Exception(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSWaitingForDebuggerCFunction))]\r\n        private static void _RunIfWaitingForDebugger(JSContext ctx)\r\n        {\r\n            var runtime = ScriptEngine.GetRuntime(ctx);\r\n            if (runtime != null)\r\n            {\r\n                // wait only once\r\n                JSApi.JS_SetWaitingForDebuggerFunc(ctx, null);\r\n                runtime.RaiseDebuggerConnectedEvent();\r\n            }\r\n        }\r\n\r\n        // 通用析构函数\r\n        [MonoPInvokeCallback(typeof(JSGCObjectFinalizer))]\r\n        public static void class_finalizer(JSRuntime rt, JSPayloadHeader header)\r\n        {\r\n            if (header.type_id == BridgeObjectType.ObjectRef)\r\n            {\r\n                var objectCache = ScriptEngine.GetObjectCache(rt);\r\n                if (objectCache != null)\r\n                {\r\n                    try\r\n                    {\r\n                        objectCache.RemoveObject(header.value);\r\n                    }\r\n                    catch (Exception exception)\r\n                    {\r\n                        Diagnostics.Logger.Default.Exception(exception);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        public void Initialize(ScriptRuntimeArgs args)\r\n        {\r\n            var fileSystem = args.fileSystem;\r\n            if (fileSystem == null)\r\n            {\r\n                throw new NullReferenceException(nameof(fileSystem));\r\n            }\r\n\r\n#if !JSB_WITH_V8_BACKEND\r\n            args.withDebugServer = false;\r\n#endif\r\n            args.asyncManager.Initialize(_mainThreadId);\r\n\r\n            _isValid = true;\r\n            _isRunning = true;\r\n            _isStaticBinding = DefaultBinder.IsStaticBinding(args.binder);\r\n#if JSB_DEBUG\r\n            Diagnostics.Logger.Default.Info(\"initializing script runtime: {0}\", _runtimeId);\r\n#endif\r\n            _rt = JSApi.JSB_NewRuntime(class_finalizer);\r\n            JSApi.JS_SetHostPromiseRejectionTracker(_rt, JSNative.PromiseRejectionTracker, IntPtr.Zero);\r\n#if UNITY_EDITOR\r\n            JSApi.JS_SetInterruptHandler(_rt, _InterruptHandler, IntPtr.Zero);\r\n#else\r\n            if (isWorker)\r\n            {\r\n                JSApi.JS_SetInterruptHandler(_rt, _InterruptHandler, IntPtr.Zero);\r\n            }\r\n#endif\r\n            JSApi.JSB_SetRuntimeOpaque(_rt, (IntPtr)_runtimeId);\r\n#if !JSB_WITH_V8_BACKEND\r\n            JSApi.JS_SetModuleLoaderFunc(_rt, module_normalize, module_loader, IntPtr.Zero);\r\n#endif\r\n            CreateContext(args.apiBridge, args.withDebugServer, args.debugServerPort);\r\n            _pathResolver = args.pathResolver;\r\n            _asyncManager = args.asyncManager;\r\n            _byteBufferAllocator = args.byteBufferAllocator;\r\n            _autorelease = new Utils.AutoReleasePool();\r\n            _fileSystem = fileSystem;\r\n            _objectCache = new ObjectCache(args.initialObjectCacheSize);\r\n            _objectCollection = new ObjectCollection(args.initialObjectCollectionSize);\r\n            _timerManager = args.timerManager ?? new DefaultTimerManager();\r\n            _typeDB = new TypeDB(this, _mainContext);\r\n#if !JSB_UNITYLESS\r\n            _typeDB.AddType(typeof(Unity.JSBehaviour), JSApi.JS_UNDEFINED);\r\n            _typeDB.AddType(typeof(Unity.JSScriptableObject), JSApi.JS_UNDEFINED);\r\n#endif\r\n#if !JSB_UNITYLESS && UNITY_EDITOR\r\n            _typeDB.AddType(Values.FindType(\"QuickJS.Unity.JSEditorWindow\"), JSApi.JS_UNDEFINED);\r\n            _typeDB.AddType(Values.FindType(\"QuickJS.Unity.JSBehaviourInspector\"), JSApi.JS_UNDEFINED);\r\n#endif\r\n\r\n            // await Task.Run(() => runner.OnBind(this, register));\r\n            try\r\n            {\r\n                args.binder?.Invoke(this);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                Diagnostics.Logger.Default.Exception(exception);\r\n            }\r\n\r\n            var register = _mainContext.CreateTypeRegister();\r\n            if (!_isWorker)\r\n            {\r\n                JSWorker.Bind(register);\r\n            }\r\n            _timerManager.Bind(register);\r\n            register.Finish();\r\n\r\n            AddStaticModule(\"jsb\", ScriptContext.Bind);\r\n            // FindModuleResolver<StaticModuleResolver>().Warmup(_mainContext);\r\n\r\n#if !JSB_UNITYLESS\r\n            //TODO may be changed in the future\r\n            var plover = UnityEngine.Resources.Load<UnityEngine.TextAsset>(\"plover.js\");\r\n            if (plover != null)\r\n            {\r\n                _mainContext.EvalSource(plover.text, \"plover.js\");\r\n            }\r\n            else\r\n            {\r\n                Diagnostics.Logger.Default.Error(\"failed to load plover.js from Resources\");\r\n            }\r\n#endif\r\n\r\n            if (!args.withDebugServer || !args.waitingForDebugger || args.debugServerPort <= 0 || JSApi.JS_IsDebuggerConnected(_mainContext) == 1)\r\n            {\r\n                RaiseDebuggerConnectedEvent();\r\n            }\r\n            else\r\n            {\r\n                Diagnostics.Logger.Default.Debug(\"[EXPERIMENTAL] Waiting for debugger...\");\r\n                JSApi.JS_SetWaitingForDebuggerFunc((JSContext)_mainContext, _RunIfWaitingForDebugger);\r\n            }\r\n        }\r\n\r\n        private void RaiseDebuggerConnectedEvent()\r\n        {\r\n            if (!_isInitialized)\r\n            {\r\n                _isInitialized = true;\r\n                OnInitializing?.Invoke(this);\r\n                OnInitialized?.Invoke(this);\r\n            }\r\n            OnDebuggerConnected?.Invoke(this);\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSInterruptHandler))]\r\n        private static unsafe int _InterruptHandler(JSRuntime rt, IntPtr opaque)\r\n        {\r\n            var runtime = ScriptEngine.GetRuntime(rt);\r\n            return runtime != null && runtime._isRunning ? 0 : 1;\r\n        }\r\n\r\n        public void AddStaticModule(string module_id, ClassBind bind)\r\n        {\r\n            FindModuleResolver<StaticModuleResolver>().AddStaticModule(module_id, bind);\r\n        }\r\n\r\n        public void AddStaticModule(string module_id, RawModuleBind bind)\r\n        {\r\n            FindModuleResolver<StaticModuleResolver>().AddStaticModule(module_id, bind);\r\n        }\r\n\r\n        public void AddStaticModule(string module_id, JSValue rawValue)\r\n        {\r\n            FindModuleResolver<StaticModuleResolver>().AddStaticModule(module_id, new ValueModuleRegister(this, rawValue));\r\n        }\r\n\r\n        public void AddStaticModule(string module_id, IModuleRegister register)\r\n        {\r\n            FindModuleResolver<StaticModuleResolver>().AddStaticModule(module_id, register);\r\n        }\r\n\r\n        // 用于静态绑定代码注册绑定模块\r\n        public ProxyModuleRegister AddStaticModuleProxy(string module_id, Action<ScriptRuntime, ProxyModuleRegister> proxyReg = null)\r\n        {\r\n            var proxy = new ProxyModuleRegister();\r\n            FindModuleResolver<StaticModuleResolver>().AddStaticModule(module_id, proxy);\r\n            proxyReg?.Invoke(this, proxy);\r\n            return proxy;\r\n        }\r\n\r\n        public ScriptRuntime CreateWorker()\r\n        {\r\n            if (isWorker)\r\n            {\r\n                throw new Exception(\"cannot create a worker inside a worker\");\r\n            }\r\n\r\n            var runtime = ScriptEngine.CreateRuntime();\r\n\r\n            runtime._isWorker = true;\r\n            runtime.Initialize(new ScriptRuntimeArgs()\r\n            {\r\n                fileSystem = _fileSystem,\r\n                pathResolver = _pathResolver,\r\n                asyncManager = _asyncManager,\r\n                byteBufferAllocator = new IO.ByteBufferPooledAllocator(),\r\n            });\r\n            return runtime;\r\n        }\r\n\r\n        public void AutoRelease(Utils.IReferenceObject referenceObject)\r\n        {\r\n            _autorelease.AutoRelease(referenceObject);\r\n        }\r\n\r\n        public IO.IByteBufferAllocator GetByteBufferAllocator()\r\n        {\r\n            return _byteBufferAllocator;\r\n        }\r\n\r\n        public ITimerManager GetTimerManager()\r\n        {\r\n            return _timerManager;\r\n        }\r\n\r\n        public ITypeDB GetTypeDB()\r\n        {\r\n            return _typeDB;\r\n        }\r\n\r\n        public void ReplaceTypeDB(ITypeDB newTypeDB)\r\n        {\r\n            _typeDB = newTypeDB;\r\n        }\r\n\r\n        public Utils.ObjectCache GetObjectCache()\r\n        {\r\n            return _objectCache;\r\n        }\r\n\r\n        public void AddManagedObject(IObjectCollectionEntry entry, out ObjectCollection.Handle handle)\r\n        {\r\n            _objectCollection.AddObject(entry, out handle);\r\n        }\r\n\r\n        public bool RemoveManagedObject(in ObjectCollection.Handle handle)\r\n        {\r\n#if JSB_DEBUG\r\n            if (!IsMainThread())\r\n            {\r\n                Diagnostics.Logger.Default.Error(\"RemoveManagedObject is only allowed to be invoked in script runtime thread\");\r\n            }\r\n#endif\r\n            return _objectCollection.RemoveObject(handle);\r\n        }\r\n\r\n        private ScriptContext CreateContext(Experimental.IJSApiBridge apiBridge, bool withDebugServer, int debugServerPort)\r\n        {\r\n            ScriptContextRef freeEntry;\r\n            int slotIndex;\r\n            if (_freeContextSlot < 0)\r\n            {\r\n                freeEntry = new ScriptContextRef();\r\n                slotIndex = _contextRefs.Count;\r\n                _contextRefs.Add(freeEntry);\r\n                freeEntry.next = -1;\r\n            }\r\n            else\r\n            {\r\n                slotIndex = _freeContextSlot;\r\n                freeEntry = _contextRefs[slotIndex];\r\n                _freeContextSlot = freeEntry.next;\r\n                freeEntry.next = -1;\r\n            }\r\n\r\n            var context = new ScriptContext(this, slotIndex + 1, apiBridge, withDebugServer, debugServerPort);\r\n\r\n            freeEntry.target = context;\r\n            if (_mainContext == null)\r\n            {\r\n                _mainContext = context;\r\n            }\r\n\r\n            context.RegisterBuiltins();\r\n            return context;\r\n        }\r\n\r\n        /// <summary>\r\n        /// (internal use only)\r\n        /// </summary>\r\n        public void RemoveContext(ScriptContext context)\r\n        {\r\n            var id = context.id;\r\n            if (id > 0)\r\n            {\r\n                var index = id - 1;\r\n                var entry = _contextRefs[index];\r\n                entry.next = _freeContextSlot;\r\n                entry.target = null;\r\n                _freeContextSlot = index;\r\n            }\r\n        }\r\n\r\n        public ScriptContext GetMainContext()\r\n        {\r\n            return _mainContext;\r\n        }\r\n\r\n        public ScriptContext GetContext(JSContext ctx)\r\n        {\r\n            ScriptContext context = null;\r\n            var id = (int)JSApi.JS_GetContextOpaque(ctx);\r\n            if (id > 0)\r\n            {\r\n                var index = id - 1;\r\n                if (index < _contextRefs.Count)\r\n                {\r\n                    context = _contextRefs[index].target;\r\n                }\r\n            }\r\n            return context;\r\n        }\r\n\r\n        private static void _FreeValueAction(ScriptRuntime rt, object cbArgs, JSValue cbValue)\r\n        {\r\n            JSApi.JSB_FreeValueRT(rt, cbValue);\r\n        }\r\n\r\n        private static void _FreeValueAndDelegationAction(ScriptRuntime rt, object cbArgs, JSValue cbValue)\r\n        {\r\n            var cache = rt.GetObjectCache();\r\n            cache.RemoveDelegate(cbValue);\r\n            JSApi.JSB_FreeValueRT(rt, cbValue);\r\n        }\r\n\r\n        private static void _FreeManagedObjectAction(ScriptRuntime rt, object cbArgs, JSValue cbValue)\r\n        {\r\n            var handle = (ObjectCollection.Handle)cbArgs;\r\n            rt.RemoveManagedObject(handle);\r\n        }\r\n\r\n        private static void _FreeValueAndScriptValueAction(ScriptRuntime rt, object cbArgs, JSValue cbValue)\r\n        {\r\n            var cache = rt.GetObjectCache();\r\n            cache.RemoveScriptValue(cbValue);\r\n            JSApi.JSB_FreeValueRT(rt, cbValue);\r\n        }\r\n\r\n        // private static void _FreeValueAndScriptPromiseAction(ScriptRuntime rt, object cbArgs, JSValue cbValue)\r\n        // {\r\n        //     var cache = rt.GetObjectCache();\r\n        //     cache.RemoveScriptPromise(cbValue);\r\n        //     JSApi.JSB_FreeValueRT(rt, cbValue);\r\n        // }\r\n\r\n        // 可在 GC 线程直接调用此方法\r\n        public bool FreeDelegationValue(JSValue value)\r\n        {\r\n            if (!EnqueuePendingAction(new JSAction { value = value, callback = _FreeValueAndDelegationAction }))\r\n            {\r\n                return false;\r\n            }\r\n            return true;\r\n        }\r\n\r\n        // 可在 GC 线程直接调用此方法\r\n        public void FreeScriptValue(JSValue value)\r\n        {\r\n            EnqueuePendingAction(new JSAction { value = value, callback = _FreeValueAndScriptValueAction });\r\n        }\r\n\r\n        public void FreeManagedObject(ObjectCollection.Handle handle)\r\n        {\r\n            EnqueuePendingAction(new JSAction { args = handle, callback = _FreeManagedObjectAction });\r\n        }\r\n\r\n        // // 可在 GC 线程直接调用此方法\r\n        // public unsafe void FreeScriptPromise(JSValue promise, JSValue onResolve, JSValue onReject)\r\n        // {\r\n        //     if (_runtimeId < 0)\r\n        //     {\r\n        //         Diagnostics.Logger.Default.Error(\"fatal error: enqueue pending action after the runtime shutdown\");\r\n        //         return;\r\n        //     }\r\n\r\n        //     if (IsMainThread())\r\n        //     {\r\n        //         _FreeValueAndScriptPromiseAction(this, null, promise);\r\n        //         _FreeValueAction(this, null, onResolve);\r\n        //         _FreeValueAction(this, null, onReject);\r\n        //         return;\r\n        //     }\r\n\r\n        //     lock (_pendingActions)\r\n        //     {\r\n        //         _pendingActions.Enqueue(new JSAction { value = promise, callback = _FreeValueAndScriptPromiseAction });\r\n        //         _pendingActions.Enqueue(new JSAction { value = onResolve, callback = _FreeValueAction });\r\n        //         _pendingActions.Enqueue(new JSAction { value = onReject, callback = _FreeValueAction });\r\n        //     }\r\n        // }\r\n\r\n        // 可在 GC 线程直接调用此方法\r\n        public void FreeValues(JSValue[] values)\r\n        {\r\n            if (values == null || values.Length == 0)\r\n            {\r\n                return;\r\n            }\r\n\r\n            if (_runtimeId < 0)\r\n            {\r\n                Diagnostics.Logger.Default.Error(\"fatal error: enqueue pending action after the runtime shutdown\");\r\n                return;\r\n            }\r\n\r\n            if (IsMainThread())\r\n            {\r\n                for (int i = 0, len = values.Length; i < len; i++)\r\n                {\r\n                    _FreeValueAction(this, null, values[i]);\r\n                }\r\n                return;\r\n            }\r\n\r\n            lock (_pendingActions)\r\n            {\r\n                for (int i = 0, count = values.Length; i < count; ++i)\r\n                {\r\n                    _pendingActions.Enqueue(new JSAction { value = values[i], callback = _FreeValueAction });\r\n                }\r\n            }\r\n        }\r\n\r\n        // 可在 GC 线程直接调用此方法\r\n        public void FreeValue(JSValue value)\r\n        {\r\n            EnqueuePendingAction(new JSAction { value = value, callback = _FreeValueAction });\r\n        }\r\n\r\n        // 可在 GC 线程直接调用此方法\r\n        public unsafe void FreeValues(int count, JSValue* values)\r\n        {\r\n            if (count == 0 || values == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            if (_runtimeId < 0)\r\n            {\r\n                Diagnostics.Logger.Default.Error(\"fatal error: enqueue pending action after the runtime shutdown\");\r\n                return;\r\n            }\r\n\r\n            if (IsMainThread())\r\n            {\r\n                for (int i = 0; i < count; i++)\r\n                {\r\n                    _FreeValueAction(this, null, values[i]);\r\n                }\r\n                return;\r\n            }\r\n\r\n            lock (_pendingActions)\r\n            {\r\n                for (var i = 0; i < count; ++i)\r\n                {\r\n                    _pendingActions.Enqueue(new JSAction { value = values[i], callback = _FreeValueAction });\r\n                }\r\n            }\r\n        }\r\n\r\n        public bool EnqueueAction(JSActionCallback callback, object args, bool isDelayedUntilActive = false)\r\n        {\r\n            return EnqueuePendingAction(new JSAction { callback = callback, args = args, isDelayedUntilActive = isDelayedUntilActive });\r\n        }\r\n\r\n        private bool EnqueuePendingAction(JSAction action)\r\n        {\r\n            if (_runtimeId < 0)\r\n            {\r\n                Diagnostics.Logger.Default.Error(\"fatal error: enqueue pending action after the runtime shutdown\");\r\n                return false;\r\n            }\r\n\r\n            if (!action.isDelayedUntilActive && IsMainThread())\r\n            {\r\n                action.callback(this, action.args, action.value);\r\n                return true;\r\n            }\r\n\r\n            lock (_pendingActions) { _pendingActions.Enqueue(action); }\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// try to eval the main module\r\n        /// </summary>\r\n        public void EvalMain(string fileName)\r\n        {\r\n            ResolveModule(fileName, true);\r\n            OnMainModuleLoaded?.Invoke(this);\r\n        }\r\n\r\n        public void EvalFile(string fileName)\r\n        {\r\n            EvalFile(fileName, typeof(void));\r\n        }\r\n\r\n        public T EvalFile<T>(string fileName)\r\n        {\r\n            return (T)EvalFile(fileName, typeof(T));\r\n        }\r\n\r\n        public object EvalFile(string fileName, Type returnType)\r\n        {\r\n            var resolvedPath = ResolveFilePath(\"\", fileName);\r\n            if (resolvedPath != null)\r\n            {\r\n                var source = _fileSystem.ReadAllBytes(resolvedPath);\r\n                return _mainContext.EvalSource(source, resolvedPath, returnType);\r\n            }\r\n            else\r\n            {\r\n                throw new Exception(\"can not resolve file path\");\r\n            }\r\n        }\r\n\r\n        public bool IsMainThread()\r\n        {\r\n            return _mainThreadId == Thread.CurrentThread.ManagedThreadId;\r\n        }\r\n\r\n        // main loop\r\n        public void Update(int ms)\r\n        {\r\n            if (!_isValid || !_isRunning)\r\n            {\r\n                return;\r\n            }\r\n\r\n#if UNITY_EDITOR\r\n            if (UnityEditor.EditorApplication.isCompiling)\r\n            {\r\n                ScriptEngine.Shutdown();\r\n                Diagnostics.Logger.Default.Warning(\"assembly reloading, shutdown script engine immediately\");\r\n                return;\r\n            }\r\n#endif\r\n\r\n#if UNITY_EDITOR\r\n            var isApplicationActive = UnityEditorInternal.InternalEditorUtility.isApplicationActive;\r\n#else\r\n            var isApplicationActive = true;\r\n#endif\r\n            ExecutePendingActions(isApplicationActive);\r\n\r\n            OnUpdate?.Invoke(); //TODO: optimize\r\n            ExecutePendingJob();\r\n\r\n            // poll here;\r\n            _timerManager.Update(ms);\r\n            _autorelease.Drain();\r\n        }\r\n\r\n        public void ExecutePendingJob()\r\n        {\r\n            JSContext ctx;\r\n            while (true)\r\n            {\r\n                var err = JSApi.JS_ExecutePendingJob(_rt, out ctx);\r\n\r\n                if (err >= 0)\r\n                {\r\n                    var hasPending = JSApi.JS_IsJobPending(_rt, out ctx);\r\n\r\n                    if (hasPending == 0)\r\n                    {\r\n                        break;\r\n                    }\r\n                }\r\n\r\n                if (err < 0)\r\n                {\r\n                    ctx.print_exception();\r\n                }\r\n            }\r\n        }\r\n\r\n        private void ExecutePendingActions(bool isApplicationActive)\r\n        {\r\n            lock (_pendingActions)\r\n            {\r\n                while (_pendingActions.Count != 0)\r\n                {\r\n                    var action = _pendingActions.Dequeue();\r\n\r\n                    if (!isApplicationActive && action.isDelayedUntilActive)\r\n                    {\r\n                        _delayedActions.Add(action);\r\n                    }\r\n                    else\r\n                    {\r\n                        _executingActions.Add(action);\r\n                    }\r\n                }\r\n            }\r\n\r\n            {\r\n                var count = _executingActions.Count;\r\n                if (count > 0)\r\n                {\r\n                    for (int i = 0; i < count; ++i)\r\n                    {\r\n                        var action = _executingActions[i];\r\n                        try { action.callback(this, action.args, action.value); }\r\n                        catch (Exception exception)\r\n                        {\r\n                            Diagnostics.Logger.Default.Exception(exception);\r\n                        }\r\n                    }\r\n                    _executingActions.Clear();\r\n                }\r\n            }\r\n\r\n            if (isApplicationActive)\r\n            {\r\n                var count = _delayedActions.Count;\r\n                if (count != 0)\r\n                {\r\n                    for (int i = 0; i < count; ++i)\r\n                    {\r\n                        var action = _delayedActions[i];\r\n\r\n                        try { action.callback(this, action.args, action.value); }\r\n                        catch (Exception exception)\r\n                        {\r\n                            Diagnostics.Logger.Default.Exception(exception);\r\n                        }\r\n                    }\r\n                    _delayedActions.Clear();\r\n                }\r\n            }\r\n        }\r\n\r\n        ~ScriptRuntime()\r\n        {\r\n#if JSB_DEBUG\r\n            if (_isValid)\r\n            {\r\n                Diagnostics.Logger.Default.Fatal(\"should never happen, ensure the script runtime is explicitly closed\");\r\n            }\r\n#endif\r\n            Destroy();\r\n        }\r\n\r\n        public void Shutdown()\r\n        {\r\n            if (IsMainThread())\r\n            {\r\n                Destroy();\r\n            }\r\n            else\r\n            {\r\n                _isRunning = false;\r\n            }\r\n        }\r\n\r\n        public void Destroy()\r\n        {\r\n            if (!_isValid)\r\n            {\r\n                return;\r\n            }\r\n#if JSB_DEBUG\r\n            Diagnostics.Logger.Default.Info(\"destroying script runtime: {0}\", _runtimeId);\r\n#endif\r\n            _isValid = false;\r\n            try\r\n            {\r\n                for (int i = 0, count = _moduleResolvers.Count; i < count; i++)\r\n                {\r\n                    var resolver = _moduleResolvers[i];\r\n                    resolver.Release();\r\n                }\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                Diagnostics.Logger.Default.Exception(e);\r\n            }\r\n\r\n            _isInitialized = false;\r\n            _isRunning = false;\r\n            _objectCollection.Clear();\r\n            _timerManager.Destroy();\r\n            _typeDB.Destroy();\r\n\r\n            // execute all pending actions (enqueued in gc thread) before ObjectCahce disposing\r\n            GC.Collect();\r\n            GC.WaitForPendingFinalizers();\r\n            ExecutePendingActions(true);\r\n\r\n#if !JSB_WITH_V8_BACKEND\r\n            //TODO unity-jsb: jsvalue's gc finalizer can't be certainly invoked when the jsvalue hasn't any reference, leave cache.Destroy not called for now.\r\n            _objectCache.Destroy();\r\n#endif\r\n            GC.Collect();\r\n            GC.WaitForPendingFinalizers();\r\n            ExecutePendingActions(true);\r\n\r\n            for (int i = 0, count = _contextRefs.Count; i < count; i++)\r\n            {\r\n                var contextRef = _contextRefs[i];\r\n                contextRef.target.Destroy();\r\n            }\r\n\r\n            _contextRefs.Clear();\r\n            _mainContext = null;\r\n\r\n            if (_asyncManager != null)\r\n            {\r\n                _asyncManager.Destroy();\r\n                _asyncManager = null;\r\n            }\r\n\r\n            lock (_pendingActions)\r\n            {\r\n                if (_pendingActions.Count != 0)\r\n                {\r\n                    Diagnostics.Logger.Default.Error(\"unexpected pending actions\");\r\n                }\r\n            }\r\n\r\n            if (_delayedActions.Count != 0)\r\n            {\r\n                Diagnostics.Logger.Default.Error(\"unexpected delayed actions\");\r\n            }\r\n\r\n            if (JSApi.JSB_FreeRuntime(_rt) == 0)\r\n            {\r\n                Diagnostics.Logger.Default.Error(\"gc object leaks\");\r\n            }\r\n\r\n#if JSB_WITH_V8_BACKEND\r\n            //TODO unity-jsb: jsvalue's gc finalizer can't be certainly invoked when the jsvalue hasn't any reference, we just do not calling cache.Destroy normally for now.\r\n            _objectCache.Destroy();\r\n#endif\r\n            var id = _runtimeId;\r\n            _runtimeId = -1;\r\n            _rt = JSRuntime.Null;\r\n\r\n            try\r\n            {\r\n                OnAfterDestroy?.Invoke(id);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                Diagnostics.Logger.Default.Exception(e);\r\n            }\r\n        }\r\n\r\n        public static implicit operator JSRuntime(ScriptRuntime se)\r\n        {\r\n            return se._rt;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptRuntime.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 53e1f200ad7eb544481ae0241581b5fc\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptRuntimeArgs.cs",
    "content": "using System;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\nusing System.Threading.Tasks;\r\nusing System.IO;\r\nusing System.Threading;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS\r\n{\r\n    using Native;\r\n    using Binding;\r\n    using Utils;\r\n    using Module;\r\n\r\n    public struct ScriptRuntimeArgs\r\n    {\r\n        /// <summary>\r\n        /// [v8-bridge] open debug server automatically after JSContext created\r\n        /// </summary>\r\n        public bool withDebugServer;\r\n\r\n        /// <summary>\r\n        /// the ScriptRuntime will complete the initialization process until the debugger is actually connected.\r\n        /// if very early breakpoints are required to be set, 'debugger' should be added to the script to hit before these breakpoints.\r\n        /// </summary>\r\n        public bool waitingForDebugger;\r\n\r\n        /// <summary>\r\n        /// [v8-bridge] the port to listen of the debug server\r\n        /// </summary>\r\n        public int debugServerPort;\r\n\r\n        public IFileSystem fileSystem;\r\n        \r\n        public IPathResolver pathResolver;\r\n\r\n        public IAsyncManager asyncManager;\r\n\r\n        /// <summary>\r\n        /// TimerManager used by the script runtime. \r\n        /// DefaultTimerManager will be used if this field is null.\r\n        /// </summary>\r\n        public ITimerManager timerManager;\r\n\r\n        /// <summary>\r\n        /// The allocator of ByteBuffer. ByteBuffer is only used in unity-jsb C# code, not for quickjs itself.\r\n        /// It's usually used for exchanging data between JS and C#.\r\n        /// </summary>\r\n        public IO.IByteBufferAllocator byteBufferAllocator;\r\n\r\n        public Experimental.IJSApiBridge apiBridge;\r\n\r\n        /// <summary>\r\n        /// specify the binding method (usually via DefaultBinder.GetBinder(...)).\r\n        /// NOTE: reflectbind is only supported in editor.\r\n        /// </summary>\r\n        public BindAction binder;\r\n\r\n        \r\n        public uint initialObjectCollectionSize;\r\n\r\n        public uint initialObjectCacheSize;\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptRuntimeArgs.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 298ef2cf6ab3c5641aadbf5d2c856faa\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptValue.cs",
    "content": "\r\nnamespace QuickJS\r\n{\r\n    using QuickJS.Native;\r\n    using QuickJS.Errors;\r\n    \r\n    /// <summary>\r\n    /// ScriptValue holds a strong reference of js value, so it relies on C# object finalizer (or the runtime managed object cache) to release.\r\n    /// Directly creating a ScriptValue instance outside is not allowed, use js_get_classvalue(ctx, val, out scriptValue) if you want to get a ScriptValue instance from a JSValue.\r\n    /// </summary>\r\n    public sealed class ScriptValue : GCObject, Utils.IWeakMapEntry\r\n    {\r\n        private /*readonly*/ JSValue _jsValue;\r\n\r\n        internal ScriptValue(ScriptContext context, JSValue jsValue)\r\n        : base(context)\r\n        {\r\n            _jsValue = jsValue;\r\n            JSApi.JS_DupValue(context, jsValue);\r\n            context.GetObjectCache().AddScriptValue(_jsValue, this);\r\n        }\r\n\r\n        public static implicit operator JSValue(ScriptValue value)\r\n        {\r\n            return value._jsValue;\r\n        }\r\n\r\n        protected override void OnDisposing(ScriptContext context)\r\n        {\r\n            var jsValue = _jsValue;\r\n            _jsValue = JSApi.JS_UNDEFINED;\r\n            context.GetRuntime().FreeScriptValue(jsValue);\r\n        }\r\n\r\n        public override int GetHashCode()\r\n        {\r\n            return _jsValue.GetHashCode();\r\n        }\r\n\r\n        public override bool Equals(object obj)\r\n        {\r\n            if (obj is ScriptValue)\r\n            {\r\n                var other = (ScriptValue)obj;\r\n                return other._jsValue == _jsValue;\r\n            }\r\n\r\n            if (obj is JSValue)\r\n            {\r\n                var other = (JSValue)obj;\r\n                return other == _jsValue;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public T GetProperty<T>(string key)\r\n        {\r\n            var ctx = (JSContext)this;\r\n            var propVal = JSApi.JS_GetPropertyStr(ctx, _jsValue, key);\r\n            if (propVal.IsException())\r\n            {\r\n                var ex = ctx.GetExceptionString();\r\n                throw new JSException(ex);\r\n            }\r\n\r\n            object o;\r\n            if (Binding.Values.js_get_var(ctx, propVal, typeof(T), out o))\r\n            {\r\n                JSApi.JS_FreeValue(ctx, propVal);\r\n                return (T)o;\r\n            }\r\n            JSApi.JS_FreeValue(ctx, propVal);\r\n            throw new JSException(\"invalid cast\");\r\n        }\r\n\r\n        public void SetProperty(string key, object value)\r\n        {\r\n            var context = GetContext();\r\n            var key_atom = context.GetAtom(key);\r\n            var ctx = (JSContext)context;\r\n            var jsValue = Binding.Values.js_push_var(ctx, value);\r\n            JSApi.JS_SetProperty(ctx, _jsValue, key_atom, jsValue);\r\n        }\r\n\r\n        public override string ToString()\r\n        {\r\n            var context = GetContext();\r\n            if (context == null)\r\n            {\r\n                return null;\r\n            }\r\n            return JSApi.GetString(context, _jsValue);\r\n        }\r\n\r\n        public string JSONStringify()\r\n        {\r\n            var ctx = (JSContext)this;\r\n            if (ctx == JSContext.Null)\r\n            {\r\n                return null;\r\n            }\r\n            var rval = JSApi.JS_JSONStringify(ctx, _jsValue, JSApi.JS_UNDEFINED, JSApi.JS_UNDEFINED);\r\n            var str = JSApi.GetString(ctx, rval);\r\n            JSApi.JS_FreeValue(ctx, rval);\r\n            return str;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/ScriptValue.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 43a3c1a050cde434d8bf9c11471eaa45\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Shared/JSPayloadHeader.cs",
    "content": "﻿using System;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS\r\n{\r\n    using int32_t = Int32;\r\n\r\n    public enum BridgeObjectType : int32_t\r\n    {\r\n        None = 0,\r\n        TypeRef = 1,\r\n        ObjectRef = 2,\r\n        ValueType = 3,\r\n    }\r\n\r\n    [StructLayout(LayoutKind.Sequential)]\r\n    public struct JSPayloadHeader\r\n    {\r\n        public BridgeObjectType type_id;\r\n        public int32_t value;\r\n\r\n        public override int GetHashCode()\r\n        {\r\n            return ((int32_t)type_id & 0x3) & (value << 2);\r\n        }\r\n\r\n        public override bool Equals(object obj)\r\n        {\r\n            if (obj is JSPayloadHeader)\r\n            {\r\n                var t = (JSPayloadHeader)obj;\r\n                return t.type_id == type_id && t.value == value;\r\n            }\r\n\r\n            return false;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Shared/JSPayloadHeader.cs.meta",
    "content": "fileFormatVersion: 2\nguid: fc1ef3bf50f7faf42bf7cfccf1737797\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Shared/NativeAttributes.cs",
    "content": "using System;\r\nnamespace QuickJS\r\n{\r\n#pragma warning disable 414\r\n    [AttributeUsage(AttributeTargets.Method)]\r\n    public class MonoPInvokeCallbackAttribute : Attribute\r\n    {\r\n        private Type type;\r\n        public MonoPInvokeCallbackAttribute(Type t)\r\n        {\r\n            type = t;\r\n        }\r\n    }\r\n#pragma warning restore 414\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Shared/NativeAttributes.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 2bcd8bb9083672048a249da579f404b4\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Shared/jsb.shared.asmdef",
    "content": "{\n    \"name\": \"jsb.shared\",\n    \"rootNamespace\": \"\",\n    \"references\": [],\n    \"includePlatforms\": [],\n    \"excludePlatforms\": [],\n    \"allowUnsafeCode\": true,\n    \"overrideReferences\": false,\n    \"precompiledReferences\": [],\n    \"autoReferenced\": true,\n    \"defineConstraints\": [],\n    \"versionDefines\": [],\n    \"noEngineReferences\": true\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Shared/jsb.shared.asmdef.meta",
    "content": "fileFormatVersion: 2\nguid: 595d45be140461240b6b4358dc45f2c0\nAssemblyDefinitionImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Shared.meta",
    "content": "fileFormatVersion: 2\nguid: 7ea835cae170967439b04bd9f740f54f\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Callbacks/ApplicationCallback.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using Native;\r\n    using UnityEngine;\r\n    using UnityEngine.Serialization;\r\n\r\n    // it's an example how to receive more MonoBehaviour callbacks without modifying JSBehaviour class.\r\n    public class JSApplicationCallback : MonoBehaviour\r\n    {\r\n        void OnApplicationFocus(bool hasFocus)\r\n        {\r\n            JSBehaviour.Dispatch(gameObject, \"OnApplicationFocus\", hasFocus);\r\n        }\r\n\r\n        void OnApplicationPause(bool pauseStatus)\r\n        {\r\n            JSBehaviour.Dispatch(gameObject, \"OnApplicationPause\", pauseStatus);\r\n        }\r\n\r\n        //TODO fixme, script order\r\n        void OnApplicationQuit()\r\n        {\r\n            JSBehaviour.Dispatch(gameObject, \"OnApplicationQuit\");\r\n        }\r\n    }\r\n}\r\n#endif // if !JSB_UNITYLESS\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Callbacks/ApplicationCallback.cs.meta",
    "content": "fileFormatVersion: 2\nguid: af9079c36cea7ec40b351e2d1d839db2\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Callbacks/BecameVisibleCallback.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using Native;\r\n    using UnityEngine;\r\n    using UnityEngine.Serialization;\r\n\r\n    // it's an example how to receive more MonoBehaviour callbacks without modifying JSBehaviour class.\r\n    public class JSBecameVisibleCallback : MonoBehaviour\r\n    {\r\n        void OnBecameVisible()\r\n        {\r\n            JSBehaviour.Dispatch(gameObject, \"OnBecameVisible\");\r\n        }\r\n\r\n        void OnBecameInvisible()\r\n        {\r\n            JSBehaviour.Dispatch(gameObject, \"OnBecameInvisible\");\r\n        }\r\n    }\r\n}\r\n#endif // if !JSB_UNITYLESS\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Callbacks/BecameVisibleCallback.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 6962bdad98ed190458e1b6535f716efe\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Callbacks/CollisionCallback.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using Native;\r\n    using UnityEngine;\r\n    using UnityEngine.Serialization;\r\n\r\n    // it's an example how to receive more MonoBehaviour callbacks without modifying JSBehaviour class.\r\n    public class JSCollisionCallback : MonoBehaviour\r\n    {\r\n        void OnCollisionEnter(Collision other)\r\n        {\r\n            JSBehaviour.Dispatch(gameObject, \"OnCollisionEnter\", other);\r\n        }\r\n\r\n        void OnCollisionExit(Collision other)\r\n        {\r\n            JSBehaviour.Dispatch(gameObject, \"OnCollisionExit\", other);\r\n        }\r\n\r\n        void OnCollisionStay(Collision other)\r\n        {\r\n            JSBehaviour.Dispatch(gameObject, \"OnCollisionStay\", other);\r\n        }\r\n    }\r\n}\r\n#endif // if !JSB_UNITYLESS\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Callbacks/CollisionCallback.cs.meta",
    "content": "fileFormatVersion: 2\nguid: d299c7c1179632f4bb5fbdac9200a1eb\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Callbacks.meta",
    "content": "fileFormatVersion: 2\nguid: 64513695e0d694f4a97ce98212a57c58\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/ComponentFix.cs",
    "content": "#if !JSB_UNITYLESS\nusing System;\n\nnamespace QuickJS.Unity\n{\n    using Native;\n    using Binding;\n    using Errors;\n\n    public static class ComponentFix\n    {\n        [MonoPInvokeCallbackAttribute(typeof(JSCFunction))]\n        public static JSValue Bind_GetComponent(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\n        {\n            try\n            {\n                do\n                {\n                    if (argc == 1)\n                    {\n                        if (Values.js_match_type(ctx, argv[0], typeof(System.Type)))\n                        {\n                            UnityEngine.Component self;\n                            if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                            {\n                                throw new ThisBoundException();\n                            }\n                            System.Type arg0;\n                            if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                            {\n                                throw new ParameterException(typeof(UnityEngine.Component), \"GetComponent\", typeof(System.Type), 0);\n                            }\n                            var inject = Values._js_game_object_get_component(ctx, argv[0], self, arg0);\n                            if (!inject.IsUndefined())\n                            {\n                                return inject;\n                            }\n                            var ret = self.GetComponent(arg0);\n                            return Values.js_push_classvalue(ctx, ret);\n                        }\n                        if (Values.js_match_type(ctx, argv[0], typeof(string)))\n                        {\n                            UnityEngine.Component self;\n                            if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                            {\n                                throw new ThisBoundException();\n                            }\n                            string arg0;\n                            if (!Values.js_get_primitive(ctx, argv[0], out arg0))\n                            {\n                                throw new ParameterException(typeof(UnityEngine.Component), \"GetComponent\", typeof(string), 0);\n                            }\n                            var ret = self.GetComponent(arg0);\n                            return Values.js_push_classvalue(ctx, ret);\n                        }\n                    }\n                } while (false);\n                throw new NoSuitableMethodException(\"GetComponent\", argc);\n            }\n            catch (Exception exception)\n            {\n                return ctx.ThrowException(exception);\n            }\n        }\n        [MonoPInvokeCallbackAttribute(typeof(JSCFunction))]\n        public static JSValue Bind_GetComponentInChildren(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\n        {\n            try\n            {\n                do\n                {\n                    if (argc == 2)\n                    {\n                        UnityEngine.Component self;\n                        if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                        {\n                            throw new ThisBoundException();\n                        }\n                        System.Type arg0;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.Component), \"GetComponentInChildren\", typeof(System.Type), 0);\n                        }\n                        bool arg1;\n                        if (!Values.js_get_primitive(ctx, argv[1], out arg1))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.Component), \"GetComponentInChildren\", typeof(bool), 1);\n                        }\n                        var inject = Values._js_game_object_get_component_in_children(ctx, argv[0], self, arg0, arg1);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = self.GetComponentInChildren(arg0, arg1);\n                        return Values.js_push_classvalue(ctx, ret);\n                    }\n                    if (argc == 1)\n                    {\n                        UnityEngine.Component self;\n                        if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                        {\n                            throw new ThisBoundException();\n                        }\n                        System.Type arg0;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.Component), \"GetComponentInChildren\", typeof(System.Type), 0);\n                        }\n                        var inject = Values._js_game_object_get_component_in_children(ctx, argv[0], self, arg0, false);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = self.GetComponentInChildren(arg0);\n                        return Values.js_push_classvalue(ctx, ret);\n                    }\n                } while (false);\n                throw new NoSuitableMethodException(\"GetComponentInChildren\", argc);\n            }\n            catch (Exception exception)\n            {\n                return ctx.ThrowException(exception);\n            }\n        }\n        [MonoPInvokeCallbackAttribute(typeof(JSCFunction))]\n        public static JSValue Bind_GetComponentsInChildren(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\n        {\n            try\n            {\n                do\n                {\n                    if (argc == 2)\n                    {\n                        UnityEngine.Component self;\n                        if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                        {\n                            throw new ThisBoundException();\n                        }\n                        System.Type arg0;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.Component), \"GetComponentsInChildren\", typeof(System.Type), 0);\n                        }\n                        bool arg1;\n                        if (!Values.js_get_primitive(ctx, argv[1], out arg1))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.Component), \"GetComponentsInChildren\", typeof(bool), 1);\n                        }\n                        var inject = Values._js_game_object_get_components_in_children(ctx, argv[0], self, arg0, arg1);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = self.GetComponentsInChildren(arg0, arg1);\n                        return Values.PushArray(ctx, ret);\n                    }\n                    if (argc == 1)\n                    {\n                        UnityEngine.Component self;\n                        if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                        {\n                            throw new ThisBoundException();\n                        }\n                        System.Type arg0;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.Component), \"GetComponentsInChildren\", typeof(System.Type), 0);\n                        }\n                        var inject = Values._js_game_object_get_components_in_children(ctx, argv[0], self, arg0, false);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = self.GetComponentsInChildren(arg0);\n                        return Values.PushArray(ctx, ret);\n                    }\n                } while (false);\n                throw new NoSuitableMethodException(\"GetComponentsInChildren\", argc);\n            }\n            catch (Exception exception)\n            {\n                return ctx.ThrowException(exception);\n            }\n        }\n        [MonoPInvokeCallbackAttribute(typeof(JSCFunction))]\n        public static JSValue Bind_GetComponentInParent(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\n        {\n            try\n            {\n                if (argc == 1)\n                {\n                    UnityEngine.Component self;\n                    if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                    {\n                        throw new ThisBoundException();\n                    }\n                    System.Type arg0;\n                    if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                    {\n                        throw new ParameterException(typeof(UnityEngine.Component), \"GetComponentInParent\", typeof(System.Type), 0);\n                    }\n                    var inject = Values._js_game_object_get_component_in_parent(ctx, argv[0], self, arg0, false);\n                    if (!inject.IsUndefined())\n                    {\n                        return inject;\n                    }\n                    var ret = self.GetComponentInParent(arg0);\n                    return Values.js_push_classvalue(ctx, ret);\n                }\n                throw new NoSuitableMethodException(\"GetComponentInParent\", argc);\n            }\n            catch (Exception exception)\n            {\n                return ctx.ThrowException(exception);\n            }\n        }\n        [MonoPInvokeCallbackAttribute(typeof(JSCFunction))]\n        public static JSValue Bind_GetComponentsInParent(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\n        {\n            try\n            {\n                do\n                {\n                    if (argc == 2)\n                    {\n                        UnityEngine.Component self;\n                        if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                        {\n                            throw new ThisBoundException();\n                        }\n                        System.Type arg0;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.Component), \"GetComponentsInParent\", typeof(System.Type), 0);\n                        }\n                        bool arg1;\n                        if (!Values.js_get_primitive(ctx, argv[1], out arg1))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.Component), \"GetComponentsInParent\", typeof(bool), 1);\n                        }\n                        var inject = Values._js_game_object_get_components_in_parent(ctx, argv[0], self, arg0, arg1);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = self.GetComponentsInParent(arg0, arg1);\n                        return Values.PushArray(ctx, ret);\n                    }\n                    if (argc == 1)\n                    {\n                        UnityEngine.Component self;\n                        if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                        {\n                            throw new ThisBoundException();\n                        }\n                        System.Type arg0;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.Component), \"GetComponentsInParent\", typeof(System.Type), 0);\n                        }\n                        var inject = Values._js_game_object_get_components_in_parent(ctx, argv[0], self, arg0, false);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = self.GetComponentsInParent(arg0);\n                        return Values.PushArray(ctx, ret);\n                    }\n                } while (false);\n                throw new NoSuitableMethodException(\"GetComponentsInParent\", argc);\n            }\n            catch (Exception exception)\n            {\n                return ctx.ThrowException(exception);\n            }\n        }\n        [MonoPInvokeCallbackAttribute(typeof(JSCFunction))]\n        public static JSValue Bind_GetComponents(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\n        {\n            try\n            {\n                do\n                {\n                    if (argc == 2)\n                    {\n                        UnityEngine.Component self;\n                        if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                        {\n                            throw new ThisBoundException();\n                        }\n                        System.Type arg0;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.Component), \"GetComponents\", typeof(System.Type), 0);\n                        }\n                        System.Collections.Generic.List<UnityEngine.Component> arg1;\n                        if (!Values.js_get_classvalue(ctx, argv[1], out arg1))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.Component), \"GetComponents\", typeof(System.Collections.Generic.List<UnityEngine.Component>), 1);\n                        }\n                        var inject = Values._js_game_object_get_components(ctx, argv[0], self, arg0, arg1);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        self.GetComponents(arg0, arg1);\n                        return JSApi.JS_UNDEFINED;\n                    }\n                    if (argc == 1)\n                    {\n                        UnityEngine.Component self;\n                        if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                        {\n                            throw new ThisBoundException();\n                        }\n                        System.Type arg0;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.Component), \"GetComponents\", typeof(System.Type), 0);\n                        }\n                        var inject = Values._js_game_object_get_components(ctx, argv[0], self, arg0);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = self.GetComponents(arg0);\n                        return Values.PushArray(ctx, ret);\n                    }\n                } while (false);\n                throw new NoSuitableMethodException(\"GetComponents\", argc);\n            }\n            catch (Exception exception)\n            {\n                return ctx.ThrowException(exception);\n            }\n        }\n    }\n}\n#endif // !JSB_UNITYLESS"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/ComponentFix.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 3a3d7819a05d0584e8ca675d09d7afac\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/BaseEditorWindow.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.IO;\r\nusing System.Text;\r\nusing System.Reflection;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using UnityEngine;\r\n    using UnityEditor;\r\n\r\n    public class BaseEditorWindow : EditorWindow\r\n    {\r\n        protected static GUIStyle _blockStyle = new GUIStyle();\r\n        protected List<Action> _defers = new List<Action>();\r\n\r\n        private static Dictionary<string, GUIContent> _textContents = new Dictionary<string, GUIContent>();\r\n\r\n        protected virtual void OnEnable()\r\n        {\r\n        }\r\n\r\n        protected virtual void OnDisable()\r\n        {\r\n        }\r\n\r\n        protected virtual void OnPaint()\r\n        {\r\n        }\r\n\r\n        protected void Update()\r\n        {\r\n            OnUpdate();\r\n        }\r\n\r\n        protected virtual void OnUpdate()\r\n        {\r\n        }\r\n\r\n        private void OnGUI()\r\n        {\r\n            OnPaint();\r\n            ExecuteDefers();\r\n        }\r\n\r\n        public static GUIContent GetCachedTextContent(string text)\r\n        {\r\n            if (_textContents.TryGetValue(text, out var content))\r\n            {\r\n                return content;\r\n            }\r\n            _textContents[text] = new GUIContent(text);\r\n            return content;\r\n        }\r\n\r\n        public static Texture2D MakeTex(int width, int height, Color fillColor)\r\n        {\r\n            var pixels = new Color[width * height];\r\n            for (var x = 0; x < width; ++x)\r\n            {\r\n                for (var y = 0; y < height; ++y)\r\n                {\r\n                    var point = x + y * width;\r\n                    pixels[point] = fillColor;\r\n                }\r\n            }\r\n            var result = new Texture2D(width, height);\r\n            result.SetPixels(pixels);\r\n            result.Apply();\r\n            return result;\r\n        }\r\n\r\n        public static void BorderLine(Rect rect)\r\n        {\r\n            Handles.color = Color.black;\r\n            Handles.DrawLine(new Vector3(rect.xMin, rect.yMin + rect.height * 0.5f), new Vector3(rect.xMax, rect.yMin + rect.height * 0.5f));\r\n            Handles.color = Color.gray;\r\n            Handles.DrawLine(new Vector3(rect.xMin + 1f, rect.yMin + rect.height * 0.5f + 1f), new Vector3(rect.xMax, rect.yMin + rect.height * 0.5f + 1f));\r\n        }\r\n\r\n        public static void BorderLine(float x1, float y1, float x2, float y2)\r\n        {\r\n            Handles.color = Color.black;\r\n            Handles.DrawLine(new Vector3(x1, y1), new Vector3(x2, y2));\r\n            Handles.color = Color.gray;\r\n            Handles.DrawLine(new Vector3(x1 + 1f, y1 + 1f), new Vector3(x2, y2));\r\n        }\r\n\r\n        public static void Block(string title, Action contentDrawer, Action[] utilities, Action tailUtility)\r\n        {\r\n            var li = new Action[utilities.Length + 1];\r\n            for (var i = 0; i < utilities.Length; i++)\r\n            {\r\n                li[i] = utilities[i];\r\n            }\r\n            li[utilities.Length] = tailUtility;\r\n            Block(title, Color.clear, contentDrawer, li);\r\n        }\r\n\r\n        public static void Block(string title, Action contentDrawer, params Action[] utilities)\r\n        {\r\n            Block(title, Color.clear, contentDrawer, utilities);\r\n        }\r\n\r\n        public static void Block(string title, Color titleColor, Action contentDrawer, params Action[] utilities)\r\n        {\r\n            EditorGUILayout.BeginHorizontal();\r\n            GUILayout.Space(10f);\r\n            if (_blockStyle == null)\r\n            {\r\n                _blockStyle = new GUIStyle();\r\n                _blockStyle.normal.background = MakeTex(100, 100, new Color32(56, 56, 56, 0));\r\n            }\r\n            EditorGUILayout.BeginVertical(_blockStyle);\r\n            EditorGUILayout.BeginHorizontal();\r\n            var guiColor = GUI.color;\r\n            if (titleColor != Color.clear)\r\n            {\r\n                GUI.color = titleColor;\r\n            }\r\n            GUILayout.Label(title, GUILayout.ExpandWidth(false));\r\n            GUI.color = guiColor;\r\n            var rectBegin = EditorGUILayout.GetControlRect(true, GUILayout.ExpandWidth(true));\r\n            var handlesColor = Handles.color;\r\n            BorderLine(rectBegin);\r\n            Handles.color = handlesColor;\r\n            for (var i = 0; i < utilities.Length; i++)\r\n            {\r\n                utilities[i]();\r\n            }\r\n            EditorGUILayout.EndHorizontal();\r\n            GUILayout.Space(4f);\r\n            EditorGUILayout.BeginHorizontal();\r\n            GUILayout.Space(10f);\r\n            EditorGUILayout.BeginVertical();\r\n            contentDrawer();\r\n            EditorGUILayout.EndVertical();\r\n            GUILayout.Space(4f);\r\n            EditorGUILayout.EndHorizontal();\r\n            GUILayout.Space(10f);\r\n            var rectEnd = EditorGUILayout.GetControlRect(true, GUILayout.Height(1f));\r\n            BorderLine(rectEnd);\r\n            BorderLine(rectEnd.xMin, rectBegin.yMax, rectEnd.xMin, rectEnd.yMax);\r\n            BorderLine(rectEnd.xMax, (rectBegin.yMin + rectBegin.yMax) * 0.5f, rectEnd.xMax, rectEnd.yMax);\r\n            Handles.color = handlesColor;\r\n            GUILayout.Space(2f);\r\n            EditorGUILayout.EndVertical();\r\n            EditorGUILayout.EndHorizontal();\r\n        }\r\n\r\n        protected void Defer(Action action)\r\n        {\r\n            _defers.Add(action);\r\n        }\r\n\r\n        protected void ExecuteDefers()\r\n        {\r\n            var size = _defers.Count;\r\n            if (size > 0)\r\n            {\r\n                var list = new Action[size];\r\n                _defers.CopyTo(list, 0);\r\n                _defers.Clear();\r\n                for (var i = 0; i < size; i++)\r\n                {\r\n                    list[i]();\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/BaseEditorWindow.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 666a8ccf93b43fa4d9c66e1ae0798faf\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/CustomBindings/UnityBinding.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Reflection;\r\n\r\nnamespace jsb.Editor\r\n{\r\n    using QuickJS.Unity;\r\n    using QuickJS.Binding;\r\n    using UnityEngine;\r\n\r\n    /// <summary>\r\n    /// the most essential types for scripting.\r\n    /// you could define your own BindingProcess anywhere in your project's 'Assets' editor directory, \r\n    /// add more types to export and transform even the types already added here.\r\n    /// </summary>\r\n    public class UnityBinding : AbstractBindingProcess\r\n    {\r\n        public bool IsAvailable(MethodInfo methodInfo)\r\n        {\r\n            return methodInfo != null && methodInfo.IsPublic;\r\n        }\r\n\r\n        public override void OnPreCollectAssemblies(BindingManager bindingManager)\r\n        {\r\n            HackGetComponents(bindingManager.TransformType(typeof(GameObject)));\r\n            HackGetComponents(bindingManager.TransformType(typeof(Component)));\r\n\r\n            bindingManager.TransformType(typeof(MonoBehaviour))\r\n                .WriteCrossBindingConstructor();\r\n\r\n            bindingManager.TransformType(typeof(ScriptableObject))\r\n                .WriteCrossBindingConstructor()\r\n                .SetMethodBlocked(\"CreateInstance\", typeof(string))\r\n                // .SetMethodBlocked(\"CreateInstance\", typeof(Type)) \r\n                .AddTSMethodDeclaration(\"static CreateInstance<T extends ScriptableObject>(type: { new(): T }): T\", \"CreateInstance\", typeof(Type))\r\n                .WriteCSMethodOverrideBinding(\"CreateInstance\", ScriptableObjectFix.BindStatic_CreateInstance)\r\n            ;\r\n\r\n            // var buildTarget = EditorUserBuildSettings.activeBuildTarget;\r\n            // if (buildTarget != BuildTarget.iOS)\r\n            // {\r\n            //     bindingManager.AddTypePrefixBlacklist(\"UnityEngine.Apple\");\r\n            // }\r\n            // if (buildTarget != BuildTarget.Android)\r\n            // {\r\n            //     bindingManager.AddTypePrefixBlacklist(\"UnityEngine.Android\");\r\n            // }\r\n            // bindingManager.AddTypePrefixBlacklist(\"SyntaxTree.\");\r\n\r\n            // fix d.ts, some C# classes use explicit implemented interface method\r\n            bindingManager.SetTypeBlocked(typeof(UnityEngine.ILogHandler));\r\n            bindingManager.SetTypeBlocked(typeof(UnityEngine.ISerializationCallbackReceiver));\r\n            bindingManager.SetTypeBlocked(typeof(UnityEngine.Playables.ScriptPlayable<>));\r\n            bindingManager.SetTypeBlocked(typeof(AOT.MonoPInvokeCallbackAttribute));\r\n            bindingManager.AddUnsupportedRelevantType(typeof(Unity.Collections.NativeArray<>));\r\n\r\n            // SetTypeBlocked(typeof(RendererExtensions));\r\n            bindingManager.TransformType(typeof(UnityEngine.Events.UnityEvent<>))\r\n                .Rename(\"UnityEvent1\");\r\n\r\n            bindingManager.TransformType(typeof(UnityEngine.Events.UnityEvent<,>))\r\n                .Rename(\"UnityEvent2\");\r\n\r\n            bindingManager.TransformType(typeof(UnityEngine.Events.UnityEvent<,,>))\r\n                .Rename(\"UnityEvent3\");\r\n\r\n            bindingManager.TransformType(typeof(UnityEngine.Events.UnityEvent<,,,>))\r\n                .Rename(\"UnityEvent4\");\r\n\r\n            bindingManager.TransformType(typeof(UnityEngine.Texture))\r\n                .SetMemberBlocked(\"imageContentsHash\");\r\n            bindingManager.TransformType(typeof(UnityEngine.Texture2D))\r\n                .AddRequiredDefinesForMember(\"alphaIsTransparency\", \"UNITY_EDITOR\");\r\n            bindingManager.TransformType(typeof(UnityEngine.Input))\r\n                .SetMemberBlocked(\"IsJoystickPreconfigured\"); // specific platform available only\r\n            bindingManager.TransformType(typeof(UnityEngine.MonoBehaviour))\r\n                .SetMemberBlocked(\"runInEditMode\"); // editor only\r\n            bindingManager.TransformType(typeof(UnityEngine.QualitySettings))\r\n                .SetMemberBlocked(\"streamingMipmapsRenderersPerFrame\");\r\n        }\r\n\r\n        public override void OnPreExporting(BindingManager bindingManager)\r\n        {\r\n            bindingManager.AddExportedType(typeof(LayerMask));\r\n            bindingManager.AddExportedType(typeof(Color));\r\n            bindingManager.AddExportedType(typeof(Color32));\r\n            bindingManager.AddExportedType(typeof(Vector2));\r\n            bindingManager.AddExportedType(typeof(Vector2Int));\r\n            bindingManager.AddExportedType(typeof(Vector3));\r\n            bindingManager.AddExportedType(typeof(Vector3Int));\r\n            bindingManager.AddExportedType(typeof(Vector4));\r\n            bindingManager.AddExportedType(typeof(Rect));\r\n            bindingManager.AddExportedType(typeof(Quaternion));\r\n            bindingManager.AddExportedType(typeof(Matrix4x4));\r\n            bindingManager.AddExportedType(typeof(PrimitiveType));\r\n\r\n            bindingManager.AddExportedType(typeof(UnityEngine.Object))\r\n                .EnableOperatorOverloading(false)\r\n                ;\r\n            bindingManager.AddExportedType(typeof(KeyCode));\r\n            bindingManager.AddExportedType(typeof(Texture));\r\n            bindingManager.AddExportedType(typeof(Texture2D));\r\n            bindingManager.AddExportedType(typeof(Material));\r\n            bindingManager.AddExportedType(typeof(Time));\r\n            bindingManager.AddExportedType(typeof(Random));\r\n            bindingManager.AddExportedType(typeof(GameObject), true);\r\n            bindingManager.AddExportedType(typeof(Camera), true);\r\n            bindingManager.AddExportedType(typeof(Transform), true);\r\n            bindingManager.AddExportedType(typeof(RectTransform), true);\r\n            bindingManager.AddExportedType(typeof(MonoBehaviour), true);\r\n            bindingManager.AddExportedType(typeof(ScriptableObject), true);\r\n            bindingManager.AddExportedType(typeof(Sprite), true);\r\n            bindingManager.AddExportedType(typeof(SpriteRenderer), true);\r\n            bindingManager.AddExportedType(typeof(Animation), true);\r\n            bindingManager.AddExportedType(typeof(AnimationClip), true);\r\n            bindingManager.AddExportedType(typeof(Animator), true);\r\n            bindingManager.AddExportedType(typeof(AnimationState), true);\r\n            bindingManager.AddExportedType(typeof(WrapMode), true);\r\n            bindingManager.AddExportedType(typeof(Debug));\r\n            bindingManager.AddExportedType(typeof(WaitForSeconds), true);\r\n            bindingManager.AddExportedType(typeof(WaitForEndOfFrame), true);\r\n            bindingManager.AddExportedType(typeof(Input));\r\n            bindingManager.AddExportedType(typeof(Application));\r\n\r\n            bindingManager.AddExportedType(typeof(Ray));\r\n            bindingManager.AddExportedType(typeof(RaycastHit));\r\n            bindingManager.AddExportedType(typeof(Physics));\r\n            bindingManager.AddExportedType(typeof(Collider));\r\n            bindingManager.AddExportedType(typeof(BoxCollider));\r\n            bindingManager.AddExportedType(typeof(SphereCollider));\r\n            bindingManager.AddExportedType(typeof(Rigidbody));\r\n\r\n            bindingManager.AddExportedType(typeof(Resources))\r\n                .SetAllConstructorsBlocked()\r\n                // .SetMethodBlocked(\"FindObjectsOfTypeAll\", typeof(Type)) \r\n                .AddTSMethodDeclaration(\"static FindObjectsOfTypeAll<T extends Object>(type: { new(): T }): T[]\", \"FindObjectsOfTypeAll\", typeof(Type))\r\n                .WriteCSMethodOverrideBinding(\"FindObjectsOfTypeAll\", ResourcesFix.BindStatic_FindObjectsOfTypeAll)\r\n            ;\r\n            bindingManager.AddExportedType(typeof(QuickJS.Unity.JSSerializationContext)).SetAllConstructorsBlocked();\r\n\r\n#if JSB_WITH_UIELEMENTS\r\n            //TODO [experimental, not_implemented] ui elements support\r\n            bindingManager.SetTypeBlocked(typeof(UnityEngine.UIElements.IUxmlFactory));\r\n            bindingManager.SetTypeBlocked(typeof(UnityEngine.UIElements.IMouseEvent));\r\n            bindingManager.SetTypeBlocked(typeof(UnityEngine.UIElements.ITransform));\r\n            bindingManager.SetTypeBlocked(typeof(UnityEngine.UIElements.IVisualElementScheduler));\r\n            bindingManager.SetTypeBlocked(typeof(UnityEngine.UIElements.IResolvedStyle));\r\n            bindingManager.SetTypeBlocked(typeof(UnityEngine.UIElements.IExperimentalFeatures));\r\n            bindingManager.SetTypeBlocked(typeof(UnityEngine.UIElements.Experimental.ITransitionAnimations));\r\n            bindingManager.SetTypeBlocked(typeof(UnityEngine.UIElements.Experimental.IValueAnimation));\r\n            \r\n            bindingManager.TransformType(typeof(UnityEngine.UIElements.VisualElement.UxmlTraits)).Rename(\"UxmlTraits0\");\r\n            bindingManager.TransformType(typeof(UnityEngine.UIElements.EventBase<>)).Rename(\"EventBase1\");\r\n            bindingManager.TransformType(typeof(UnityEngine.UIElements.UxmlFactory<>)).Rename(\"UxmlFactory1\");\r\n            bindingManager.TransformType(typeof(UnityEngine.UIElements.UxmlFactory<,>)).Rename(\"UxmlFactory2\");\r\n            bindingManager.ExportTypesInAssembly(typeof(UnityEngine.UIElements.Label).Assembly, true);\r\n#endif\r\n        }\r\n\r\n        private static TypeTransform HackGetComponents(TypeTransform typeTransform)\r\n        {\r\n            if (typeTransform.type == typeof(GameObject))\r\n            {\r\n                typeTransform.AddTSMethodDeclaration($\"AddComponent<T extends Component>(type: {{ new(): T }}): T\",\r\n                     \"AddComponent\", typeof(Type));\r\n\r\n                typeTransform.WriteCSMethodOverrideBinding(\"AddComponent\", GameObjectFix.Bind_AddComponent);\r\n\r\n                typeTransform.WriteCSMethodOverrideBinding(\"GetComponent\", GameObjectFix.Bind_GetComponent);\r\n                typeTransform.WriteCSMethodOverrideBinding(\"GetComponentInChildren\", GameObjectFix.Bind_GetComponentInChildren);\r\n                typeTransform.WriteCSMethodOverrideBinding(\"GetComponentInParent\", GameObjectFix.Bind_GetComponentInParent);\r\n                typeTransform.WriteCSMethodOverrideBinding(\"GetComponentsInChildren\", GameObjectFix.Bind_GetComponentsInChildren);\r\n                typeTransform.WriteCSMethodOverrideBinding(\"GetComponentsInParent\", GameObjectFix.Bind_GetComponentsInParent);\r\n                typeTransform.WriteCSMethodOverrideBinding(\"GetComponents\", GameObjectFix.Bind_GetComponents);\r\n            }\r\n            else\r\n            {\r\n                typeTransform.WriteCSMethodOverrideBinding(\"GetComponent\", ComponentFix.Bind_GetComponent);\r\n                typeTransform.WriteCSMethodOverrideBinding(\"GetComponentInChildren\", ComponentFix.Bind_GetComponentInChildren);\r\n                typeTransform.WriteCSMethodOverrideBinding(\"GetComponentInParent\", ComponentFix.Bind_GetComponentInParent);\r\n                typeTransform.WriteCSMethodOverrideBinding(\"GetComponentsInChildren\", ComponentFix.Bind_GetComponentsInChildren);\r\n                typeTransform.WriteCSMethodOverrideBinding(\"GetComponentsInParent\", ComponentFix.Bind_GetComponentsInParent);\r\n                typeTransform.WriteCSMethodOverrideBinding(\"GetComponents\", ComponentFix.Bind_GetComponents);\r\n            }\r\n\r\n            typeTransform.AddTSMethodDeclaration($\"GetComponent<T extends Component>(type: {{ new(): T }}): T\",\r\n                    \"GetComponent\", typeof(Type))\r\n                .AddTSMethodDeclaration($\"GetComponentInChildren<T extends Component>(type: {{ new(): T }}, includeInactive: boolean): T\",\r\n                    \"GetComponentInChildren\", typeof(Type), typeof(bool))\r\n                .AddTSMethodDeclaration($\"GetComponentInChildren<T extends Component>(type: {{ new(): T }}): T\",\r\n                    \"GetComponentInChildren\", typeof(Type))\r\n                .AddTSMethodDeclaration($\"GetComponentInParent<T extends Component>(type: {{ new(): T }}): T\",\r\n                    \"GetComponentInParent\", typeof(Type))\r\n                .AddTSMethodDeclaration($\"GetComponents<T extends Component>(type: {{ new(): T }}): T[]\",\r\n                    \"GetComponents\", typeof(Type))\r\n                .AddTSMethodDeclaration($\"GetComponentsInChildren<T extends Component>(type: {{ new(): T }}, includeInactive: boolean): T[]\",\r\n                    \"GetComponentsInChildren\", typeof(Type), typeof(bool))\r\n                .AddTSMethodDeclaration($\"GetComponentsInChildren<T extends Component>(type: {{ new(): T }}): T[]\",\r\n                    \"GetComponentsInChildren\", typeof(Type))\r\n                .AddTSMethodDeclaration($\"GetComponentsInParent<T extends Component>(type: {{ new(): T }}, includeInactive: boolean): T[]\",\r\n                    \"GetComponentsInParent\", typeof(Type), typeof(bool))\r\n                .AddTSMethodDeclaration($\"GetComponentsInParent<T extends Component>(type: {{ new(): T }}): T[]\",\r\n                    \"GetComponentsInParent\", typeof(Type))\r\n                ;\r\n            return typeTransform;\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/CustomBindings/UnityBinding.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: b04afd0268214ec4ab688d493f3165b8\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/CustomBindings/UnityEditorBinding.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Reflection;\r\n\r\nnamespace jsb.Editor\r\n{\r\n    using QuickJS.Native;\r\n    using QuickJS.Binding;\r\n    using QuickJS.Unity;\r\n    using UnityEngine;\r\n    using UnityEditor;\r\n    using UnityEditor.IMGUI.Controls;\r\n\r\n    public class UnityEditorBinding : AbstractBindingProcess\r\n    {\r\n        public bool IsAvailable(MethodInfo methodInfo)\r\n        {\r\n            return methodInfo != null && methodInfo.IsPublic;\r\n        }\r\n\r\n        public override void OnPreExporting(BindingManager bindingManager)\r\n        {\r\n#if !UNITY_WEBGL\r\n            bindingManager.AddExportedRawTypes(typeof(QuickJS.Utils.FSWatcher)).EditorRuntime();\r\n#endif\r\n            // bindingManager.AddTypePrefixBlacklist(\"Unity.\");\r\n            // bindingManager.AddTypePrefixBlacklist(\"TreeEditor.\");\r\n            bindingManager.AddTypeFullNameBlacklist(\"UnityEditor.UpdatePrefabInstancesEventArgs\");\r\n            bindingManager.AddExportedType(typeof(QuickJS.Unity.UnityHelper)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(QuickJS.Binding.Prefs)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(QuickJS.Utils.TSConfig)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(QuickJS.Utils.TSConfig.CompilerOptions)).EditorRuntime().SetAllConstructorsBlocked();\r\n            \r\n            bindingManager.AddExportedType(typeof(GUI)).SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(GUIUtility)).SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(GUILayout)).SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(GUILayoutUtility)).SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(GUILayoutOption));\r\n            bindingManager.AddExportedType(typeof(GUIContent));\r\n            bindingManager.AddExportedType(typeof(GUISkin));\r\n            bindingManager.AddExportedType(typeof(GUIStyle));\r\n            bindingManager.AddExportedType(typeof(TextAnchor));\r\n            bindingManager.AddExportedType(typeof(ScaleMode));\r\n            bindingManager.AddExportedType(typeof(FocusType));\r\n            bindingManager.AddExportedType(typeof(AudioClip));\r\n            bindingManager.AddExportedType(typeof(RectInt));\r\n            bindingManager.AddExportedType(typeof(Bounds));\r\n            bindingManager.AddExportedType(typeof(BoundsInt));\r\n            bindingManager.AddExportedType(typeof(Gradient));\r\n            bindingManager.AddExportedType(typeof(AnimationCurve));\r\n            bindingManager.AddExportedType(typeof(Event));\r\n            bindingManager.AddExportedType(typeof(EventType)).OnFilter<string>(i => char.IsLower(i[0]));\r\n            bindingManager.AddExportedType(typeof(Coroutine));\r\n            bindingManager.AddExportedType(typeof(System.Collections.IEnumerator));\r\n            bindingManager.AddExportedType(typeof(System.Collections.Generic.IEnumerable<string>));\r\n\r\n            bindingManager.AddExportedType(typeof(SearchField)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(EditorStyles)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(GenericMenu)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(PrefabAssetType)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(PrefabInstanceStatus)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(UIOrientation)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(MessageType)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(Hash128)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(ImportAssetOptions)).EditorRuntime();\r\n            #if !UNITY_2019_3_OR_NEWER\r\n            bindingManager.AddExportedType(typeof(ScriptingRuntimeVersion)).EditorRuntime();\r\n            #endif\r\n            bindingManager.AddExportedType(typeof(AssetPostprocessor)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(AssetImporter)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(ModelImporter)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(AudioImporter)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(VideoClipImporter)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(TextureImporter)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(MouseCursor)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(PauseState)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(PlayModeStateChange)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(ExportPackageOptions)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(ForceReserializeAssetsOptions)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(StatusQueryOptions)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(SerializedObject)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(SerializedProperty)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(SerializedPropertyType)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(BuildPlayerOptions)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(BuildAssetBundleOptions)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(BuildTarget)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(BuildOptions)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(ObjectFactory)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(CameraEditor)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(CameraEditorUtils)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(TransformUtils)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(EditorJsonUtility)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(GameObjectUtility)).EditorRuntime();\r\n            bindingManager.AddExportedType(typeof(EditorPrefs)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(Handles)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(HandleUtility)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(SceneView)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(MeshUtility)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(PrefabUtility)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(FileUtil)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(UnityEditor.Build.Reporting.BuildReport)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(AssetBundleManifest)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(BuildPipeline)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(AssetDatabase)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(ShaderUtil)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(EditorUtility)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(EditorGUI)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(EditorGUIUtility)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(EditorGUILayout)).EditorRuntime().SetAllConstructorsBlocked()\r\n                // note: it's easy to confuse a bunch of overloads in typescript (you need to add '<any>' before every argument or 'ts-ignore' when the ts compiler can't guess the correct candidate)\r\n                // note: so you'd prefer to rename some of them it another totally different name like this: .SetMethodJSName(\"Popup_sis\", \"Popup\", typeof(string), typeof(int), typeof(string[]), typeof(GUILayoutOption[]))\r\n                // .SetMethodJSName(\"Popup_sis\", \"Popup\", typeof(string), typeof(int), typeof(string[]), typeof(GUILayoutOption[]))\r\n            ;\r\n            bindingManager.AddExportedType(typeof(EditorApplication)).EditorRuntime().SetAllConstructorsBlocked();\r\n            bindingManager.AddExportedType(typeof(Editor)).EditorRuntime()\r\n                .WriteCrossBindingConstructor();\r\n            bindingManager.AddExportedType(typeof(EditorWindow)).EditorRuntime()\r\n                .SetMemberBlocked(\"CreateWindow\")\r\n                .SetMemberBlocked(\"GetWindowWithRect\")\r\n                .SetMethodBlocked(\"GetWindow\", typeof(Type), typeof(bool), typeof(string), typeof(bool))\r\n                .SetMethodBlocked(\"GetWindow\", typeof(Type), typeof(bool), typeof(string))\r\n                .SetMethodBlocked(\"GetWindow\", typeof(Type), typeof(bool))\r\n                //TODO add overloading members of GetWindow (already implemented)\r\n                .AddTSMethodDeclaration(\"static GetWindow<T extends EditorWindow>(type: { new(): T }): T\", \"GetWindow\", typeof(Type))\r\n                //TODO desiredDockNextTo\r\n                //.add equivalent memeber function in typescript for desiredDockNextTo\r\n                .WriteCrossBindingConstructor()\r\n                .WriteCSMethodOverrideBinding(\"GetWindow\", EditorWindowFix.BindStatic_GetWindow)\r\n                .AddStaticMethod(EditorWindowFix.CreateWindow)\r\n            ;\r\n            bindingManager.AddTypeFullNameBlacklist(\"UnityEditor.ProfilerWindow\");\r\n            bindingManager.AddTypeFullNameBlacklist(\"UnityEditor.MaterialEditor\");\r\n            bindingManager.AddTypeFullNameBlacklist(\"UnityEditor.ShaderUtil\");\r\n        }\r\n        \r\n        public override void OnPostExporting(BindingManager bindingManager)\r\n        {\r\n            bindingManager.ExportTypesInAssembly(typeof(Editor).Assembly, true, transform => transform.EditorRuntime());\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/CustomBindings/UnityEditorBinding.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 8fdb1efddb7f11a42934fcc318602ffc\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/CustomBindings/UnityUIBinding.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Reflection;\r\n\r\nnamespace jsb.Editor\r\n{\r\n    using QuickJS.Native;\r\n    using QuickJS.Unity;\r\n    using QuickJS.Binding;\r\n    using UnityEngine;\r\n    using UnityEditor;\r\n    using UnityEditor.IMGUI.Controls;\r\n\r\n    public class UnityUIBinding : AbstractBindingProcess\r\n    {\r\n        public bool IsAvailable(MethodInfo methodInfo)\r\n        {\r\n            return methodInfo != null && methodInfo.IsPublic;\r\n        }\r\n\r\n        public override void OnPreCollectAssemblies(BindingManager bindingManager)\r\n        {\r\n            bindingManager.SetTypeBlocked(typeof(UnityEngine.UI.ILayoutGroup));\r\n            bindingManager.SetTypeBlocked(typeof(UnityEngine.UI.ILayoutSelfController));\r\n            bindingManager.SetTypeBlocked(typeof(UnityEngine.UI.GraphicRebuildTracker));\r\n            bindingManager.TransformType(typeof(UnityEngine.UI.DefaultControls))\r\n                .SetMemberBlocked(\"factory\");\r\n            ;\r\n            bindingManager.TransformType(typeof(UnityEngine.UI.PositionAsUV1))\r\n                .SetMemberBlocked(\"ModifyMesh\");\r\n            bindingManager.TransformType(typeof(UnityEngine.UI.Shadow))\r\n                .SetMemberBlocked(\"ModifyMesh\");\r\n            bindingManager.TransformType(typeof(UnityEngine.UI.Outline))\r\n                .SetMemberBlocked(\"ModifyMesh\");\r\n            bindingManager.TransformType(typeof(UnityEngine.UI.Graphic))\r\n                .SetMemberBlocked(\"OnRebuildRequested\");\r\n            bindingManager.TransformType(typeof(UnityEngine.UI.Text))\r\n                .SetMemberBlocked(\"OnRebuildRequested\");\r\n        }\r\n\r\n        public override void OnPreExporting(BindingManager bindingManager)\r\n        {\r\n        }\r\n        \r\n        public override void OnPostExporting(BindingManager bindingManager)\r\n        {\r\n            bindingManager.ExportTypesInAssembly(typeof(UnityEngine.UI.Text).Assembly, true);\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/CustomBindings/UnityUIBinding.cs.meta",
    "content": "fileFormatVersion: 2\nguid: f24feeabf2369dc40928bc73f4676413\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/CustomBindings.meta",
    "content": "fileFormatVersion: 2\r\nguid: 3da17c6d4b07a81489fd383109d2442d\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/EditorRuntime.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using UnityEngine;\r\n    using UnityEditor;\r\n    using QuickJS.Utils;\r\n    using QuickJS.IO;\r\n    using QuickJS;\r\n    using QuickJS.Binding;\r\n    using QuickJS.Native;\r\n\r\n    [InitializeOnLoad]\r\n    public class EditorRuntime\r\n    {\r\n        private enum RunMode\r\n        {\r\n            Editor,\r\n            Playing,\r\n            None,\r\n        }\r\n#pragma warning disable 0649\r\n        private static EditorRuntime _instance;\r\n#pragma warning restore 0649\r\n        private ScriptRuntime _runtime;\r\n        private RunMode _runMode;\r\n        private int _tick;\r\n        private Prefs _prefs;\r\n        private TSConfig _tsConfig;\r\n        private float _changedFileInterval;\r\n        private HashSet<string> _changedFileQueue;\r\n\r\n        static EditorRuntime()\r\n        {\r\n            PrefsLoader.prefsChanged += OnPrefsChanged;\r\n            OnPrefsChanged(PrefsLoader.CurrentPrefs);\r\n        }\r\n\r\n        private static void OnPrefsChanged(Prefs prefs)\r\n        {\r\n            if (_instance != null)\r\n            {\r\n                if (!prefs.editorScripting)\r\n                {\r\n                    _instance.OnEditorQuitting();\r\n                    _instance = null;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                if (prefs.editorScripting)\r\n                {\r\n                    _instance = new EditorRuntime(prefs);\r\n                }\r\n            }\r\n        }\r\n\r\n        public static Prefs GetPrefs()\r\n        {\r\n            return _instance?._prefs;\r\n        }\r\n\r\n        public static TSConfig GetTSConfig()\r\n        {\r\n            return _instance?._tsConfig;\r\n        }\r\n\r\n        public static EditorRuntime GetInstance()\r\n        {\r\n            return _instance;\r\n        }\r\n\r\n        public EditorRuntime(Prefs prefs)\r\n        {\r\n            _prefs = prefs;\r\n            _runMode = RunMode.None;\r\n            _changedFileQueue = new HashSet<string>();\r\n            ScriptEngine.RuntimeCreated += OnScriptRuntimeCreated;\r\n            EditorApplication.delayCall += OnEditorInit;\r\n            EditorApplication.playModeStateChanged += OnPlayModeStateChanged;\r\n        }\r\n\r\n        ~EditorRuntime()\r\n        {\r\n        }\r\n\r\n        private void OnEditorQuitting()\r\n        {\r\n            if (_runtime == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            var runtime = _runtime;\r\n            _runtime = null;\r\n            _runMode = RunMode.None;\r\n            JSScriptFinder.GetInstance().ModuleSourceChanged -= OnModuleSourceChanged;\r\n            EditorApplication.delayCall -= OnEditorInit;\r\n            EditorApplication.update -= OnEditorUpdate;\r\n            AssemblyReloadEvents.beforeAssemblyReload -= OnBeforeAssemblyReload;\r\n            EditorApplication.quitting -= OnEditorQuitting;\r\n            runtime.Shutdown();\r\n        }\r\n\r\n        public bool Reload()\r\n        {\r\n            if (EditorApplication.isCompiling)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            OnEditorQuitting();\r\n            OnEditorInit();\r\n            return true;\r\n        }\r\n\r\n        private void OnEditorInit()\r\n        {\r\n            if (_runMode == RunMode.Playing)\r\n            {\r\n                return;\r\n            }\r\n\r\n            if (_runtime == null)\r\n            {\r\n                EditorApplication.update += OnEditorUpdate;\r\n                AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload;\r\n                EditorApplication.quitting += OnEditorQuitting;\r\n\r\n                var pathResolver = new PathResolver();\r\n                var fileSystem = new DefaultFileSystem();\r\n                var asyncManager = new DefaultAsyncManager();\r\n\r\n                _tick = Environment.TickCount;\r\n                _runtime = ScriptEngine.CreateRuntime(true);\r\n                _runtime.AddModuleResolvers();\r\n                _runtime.Initialize(new ScriptRuntimeArgs\r\n                {\r\n                    fileSystem = fileSystem,\r\n                    pathResolver = pathResolver,\r\n                    asyncManager = asyncManager,\r\n                    byteBufferAllocator = new ByteBufferPooledAllocator(),\r\n                    binder = DefaultBinder.GetBinder(_prefs.preferredBindingMethod),\r\n                });\r\n            }\r\n        }\r\n\r\n        private void OnScriptRuntimeCreated(ScriptRuntime runtime)\r\n        {\r\n            runtime.OnInitializing += OnScriptRuntimeInitializing;\r\n            runtime.OnMainModuleLoaded += OnScriptRuntimeMainModuleLoaded;\r\n        }\r\n\r\n        public static TSConfig LoadTSConfig(string workspace = null)\r\n        {\r\n            var tsconfigPath = string.IsNullOrEmpty(workspace) ? \"tsconfig.json\" : Path.Combine(workspace, \"tsconfig.json\");\r\n            if (File.Exists(tsconfigPath))\r\n            {\r\n                var text = Utils.TextUtils.NormalizeJson(File.ReadAllText(tsconfigPath));\r\n                var tsconfig = JsonUtility.FromJson<TSConfig>(text);\r\n                return tsconfig;\r\n            }\r\n\r\n            Debug.LogWarning(\"no tsconfig.json found\");\r\n            return null;\r\n        }\r\n\r\n        private void OnScriptRuntimeMainModuleLoaded(ScriptRuntime runtime)\r\n        {\r\n        }\r\n\r\n        private void OnScriptRuntimeInitializing(ScriptRuntime runtime)\r\n        {\r\n            _tsConfig = LoadTSConfig();\r\n\r\n            if (_tsConfig != null && !string.IsNullOrEmpty(_tsConfig.compilerOptions.outDir))\r\n            {\r\n                runtime.AddSearchPath(_tsConfig.compilerOptions.outDir);\r\n            }\r\n            runtime.AddStaticModule(\"jsb.editor\", Bind);\r\n            JSScriptFinder.GetInstance().ModuleSourceChanged += OnModuleSourceChanged;\r\n\r\n            if (!string.IsNullOrEmpty(_prefs.editorEntryPoint))\r\n            {\r\n                runtime.ResolveModule(_prefs.editorEntryPoint);\r\n            }\r\n\r\n            foreach (var module in _prefs.editorRequires)\r\n            {\r\n                runtime.ResolveModule(module);\r\n            }\r\n\r\n            // in order to evaluate the decorator (the registration of CustomEditor), we need to load these modules before actually using\r\n            var editorScripts = new List<JSScriptClassPathHint>();\r\n            JSScriptFinder.GetInstance().Search(JSScriptClassType.CustomEditor, editorScripts);\r\n            foreach (var editorScript in editorScripts)\r\n            {\r\n                runtime.ResolveModule(editorScript.modulePath);\r\n            }\r\n        }\r\n\r\n        public static ClassDecl Bind(TypeRegister register)\r\n        {\r\n            var ns_jsb = register.CreateClass(\"JSBEditorModule\");\r\n\r\n            {\r\n                var ns_editorRuntime = register.CreateClass(\"JSEditorRuntimeClass\");\r\n                ns_editorRuntime.AddProperty(true, \"prefs\", JS_GetPrefs, null);\r\n                ns_editorRuntime.AddProperty(true, \"tsconfig\", JS_GetTSConfig, null);\r\n                ns_jsb.AddValue(\"EditorRuntime\", ns_editorRuntime.GetConstructor());\r\n            }\r\n            return ns_jsb;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue JS_GetPrefs(JSContext ctx, JSValue this_val)\r\n        {\r\n            return Values.js_push_classvalue(ctx, GetPrefs());\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue JS_GetTSConfig(JSContext ctx, JSValue this_val)\r\n        {\r\n            return Values.js_push_classvalue(ctx, GetTSConfig());\r\n        }\r\n\r\n        private void OnModuleSourceChanged(string modulePath, JSScriptClassType classTypes)\r\n        {\r\n            // the already loaded CustomEditor scripts could be reloaded automatically by file-watcher\r\n            // but if it's freshly added, resolve it here\r\n            if ((classTypes & JSScriptClassType.CustomEditor) != 0)\r\n            {\r\n                var runtime = ScriptEngine.GetRuntime();\r\n                if (runtime != null && !EditorApplication.isCompiling)\r\n                {\r\n                    runtime.ResolveModule(modulePath);\r\n                }\r\n            }\r\n        }\r\n\r\n        private void OnPlayModeStateChanged(PlayModeStateChange mode)\r\n        {\r\n            switch (mode)\r\n            {\r\n                case PlayModeStateChange.EnteredEditMode: _runMode = RunMode.Editor; EditorApplication.delayCall += OnEditorInit; break;\r\n                case PlayModeStateChange.ExitingEditMode: OnEditorQuitting(); break;\r\n                case PlayModeStateChange.EnteredPlayMode: _runMode = RunMode.Playing; break;\r\n            }\r\n        }\r\n\r\n        private void OnBeforeAssemblyReload()\r\n        {\r\n            OnEditorQuitting();\r\n        }\r\n\r\n        private void OnEditorUpdate()\r\n        {\r\n            if (_runtime != null)\r\n            {\r\n                if (EditorApplication.isCompiling)\r\n                {\r\n                    OnEditorQuitting();\r\n                    return;\r\n                }\r\n\r\n                var tick = Environment.TickCount;\r\n                if (tick < _tick)\r\n                {\r\n                    _runtime.Update((tick - int.MinValue) + (int.MaxValue - _tick));\r\n                }\r\n                else\r\n                {\r\n                    _runtime.Update(tick - _tick);\r\n                }\r\n                _tick = tick;\r\n            }\r\n        }\r\n\r\n        public static void Eval(string code)\r\n        {\r\n            var runtime = ScriptEngine.GetRuntime();\r\n            if (runtime != null && !EditorApplication.isCompiling)\r\n            {\r\n                runtime.GetMainContext().EvalSource(code, \"eval\");\r\n                return;\r\n            }\r\n\r\n            Debug.LogError(\"no running ScriptRuntime\");\r\n        }\r\n\r\n        public static void ShowWindow(string module, string typename)\r\n        {\r\n            Eval($\"require('UnityEditor').EditorWindow.GetWindow(require('{module}').{typename}).Show()\");\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/EditorRuntime.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 624bf9490fcf6e24aa6c8cde17602b3b\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/JSAssetPostprocessor.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using Binding;\r\n    using Native;\r\n    using UnityEngine;\r\n    using UnityEditor;\r\n\r\n    public class JSAssetPostprocessor : AssetPostprocessor\r\n    {\r\n        private void OnPostprocessTexture(Texture2D texture)\r\n        {\r\n            CallJavascript(this, \"OnPostprocessTexture\", texture);\r\n        }\r\n\r\n        private void OnPostprocessModel(GameObject model)\r\n        {\r\n            CallJavascript(this, \"OnPostprocessModel\", model);\r\n        }\r\n\r\n        private void OnPostprocessAudio(AudioClip audioClip)\r\n        {\r\n            CallJavascript(this, \"OnPostprocessAudio\", audioClip);\r\n        }\r\n\r\n        private void OnPostprocessMaterial(Material material)\r\n        {\r\n            CallJavascript(this, \"OnPostprocessMaterial\", material);\r\n        }\r\n\r\n        private void OnPostProcessSprites(Texture2D texture, Sprite[] sprites)\r\n        {\r\n            CallJavascript(this, \"OnPostProcessSprites\", texture, sprites);\r\n        }\r\n\r\n        static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)\r\n        {\r\n            CallJavascript(null, \"OnPostprocessAllAssets\", importedAssets, deletedAssets, movedAssets, movedFromAssetPaths);\r\n        }\r\n\r\n        private static void CallJavascript(AssetPostprocessor proc, string funcName, params object[] args)\r\n        {\r\n            var prefs = EditorRuntime.GetPrefs();\r\n            if (prefs != null && prefs.assetPostProcessors != null)\r\n            {\r\n                foreach (var postprocessor in prefs.assetPostProcessors)\r\n                {\r\n                    CallJavascript(postprocessor, proc, funcName, args);\r\n                }\r\n            }\r\n        }\r\n\r\n        private static void CallJavascript(string module_id, AssetPostprocessor proc, string funcName, params object[] args)\r\n        {\r\n            var runtime = ScriptEngine.GetRuntime();\r\n            if (runtime != null && runtime.isValid && !EditorApplication.isCompiling)\r\n            {\r\n                runtime.ResolveModule(module_id);\r\n\r\n                var context = runtime.GetMainContext();\r\n                var ctx = (JSContext)context;\r\n                JSValue func;\r\n\r\n                if (context.LoadModuleCacheExports(module_id, funcName, out func))\r\n                {\r\n                    var globalThis = context.GetGlobalObject();\r\n\r\n                    if (JSApi.JS_IsFunction(ctx, func) == 1)\r\n                    {\r\n                        var arglist = new List<JSValue>();\r\n                        do\r\n                        {\r\n                            if (proc != null)\r\n                            {\r\n                                var val = Values.js_push_var(ctx, proc);\r\n                                if (val.IsException())\r\n                                {\r\n                                    ctx.print_exception();\r\n                                    break;\r\n                                }\r\n                                arglist.Add(val);\r\n                            }\r\n\r\n                            var err = false;\r\n                            for (var i = 0; i < args.Length; i++)\r\n                            {\r\n                                var val = Values.js_push_var(ctx, args[i]);\r\n                                if (val.IsException())\r\n                                {\r\n                                    ctx.print_exception();\r\n                                    err = true;\r\n                                    break;\r\n                                }\r\n                                arglist.Add(val);\r\n                            }\r\n\r\n                            if (err)\r\n                            {\r\n                                break;\r\n                            }\r\n\r\n                            var argv = arglist.ToArray();\r\n                            JSValue rval = JSApi.JS_UNDEFINED;\r\n                            unsafe\r\n                            {\r\n                                fixed (JSValue* pArgs = argv)\r\n                                {\r\n                                    rval = JSApi.JS_Call(ctx, func, globalThis, argv.Length, pArgs);\r\n                                }\r\n                            }\r\n\r\n                            if (rval.IsException())\r\n                            {\r\n                                ctx.print_exception();\r\n                            }\r\n                            else\r\n                            {\r\n                                JSApi.JS_FreeValue(ctx, rval);\r\n                            }\r\n                        } while (false);\r\n\r\n                        for (var i = 0; i < arglist.Count; i++)\r\n                        {\r\n                            JSApi.JS_FreeValue(ctx, arglist[i]);\r\n                        }\r\n                    }\r\n\r\n                    JSApi.JS_FreeValue(ctx, globalThis);\r\n                    JSApi.JS_FreeValue(ctx, func);\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/JSAssetPostprocessor.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 80d6ff795de7fef48a922288249e1616\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/JSBehaviourFullInspector.cs",
    "content": "﻿#if !JSB_UNITYLESS\n\nnamespace QuickJS.Unity\n{\n    using UnityEditor;\n\n    [CustomEditor(typeof(JSBehaviourFull))]\n    public class JSBehaviourFullInspector : JSBehaviourInspector\n    {\n    }\n}\n\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/JSBehaviourFullInspector.cs.meta",
    "content": "fileFormatVersion: 2\nguid: e19e97cf5f4c95749aa634d2d97a1fe5\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/JSBehaviourInspector.cs",
    "content": "﻿#if !JSB_UNITYLESS\nusing System;\n\nnamespace QuickJS.Unity\n{\n    using UnityEditor;\n\n    [CustomEditor(typeof(JSBehaviour))]\n    public class JSBehaviourInspector : JSInspectorBase<JSBehaviour>\n    {\n        protected override JSScriptClassType GetScriptClassType()\n        {\n            return JSScriptClassType.MonoBehaviour;\n        }\n\n        protected override void DrawSourceView()\n        {\n            base.DrawSourceView();\n\n            var target_t = GetTarget();\n            var updatableOld = target_t is JSBehaviourFull;\n            var updatableNew = EditorGUILayout.Toggle(\"Updatable\", updatableOld);\n\n            if (updatableNew != updatableOld)\n            {\n                this.ReleaseJSValues();\n                target_t.ReleaseScriptInstance();\n\n                var type = updatableNew ? typeof(JSBehaviourFull) : typeof(JSBehaviour);\n                var monoScript = UnityHelper.GetMonoScript(type);\n                var prop = serializedObject.FindProperty(\"m_Script\");\n                serializedObject.Update();\n                prop.objectReferenceValue = monoScript;\n\n                // this editor instance (and _target) reference will be invalid after this call, \n                // do not access anything relating to the old references\n                serializedObject.ApplyModifiedProperties();\n            }\n        }\n    }\n}\n\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/JSBehaviourInspector.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 56ce79cbfb2f9ba45bf27a8f8f95a243\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/JSInspectorBase.cs",
    "content": "﻿#if !JSB_UNITYLESS\nusing System;\nusing System.IO;\nusing System.Collections.Generic;\n\nnamespace QuickJS.Unity\n{\n    using UnityEditor;\n    using UnityEngine;\n    using Native;\n\n    public abstract class JSInspectorBase<T> : Editor, Utils.IObjectCollectionEntry\n    where T : Object, IScriptEditorSupport\n    {\n        private T _target;\n        private Utils.ObjectCollection.Handle _handle;\n        private JSScriptRef _scriptRef;\n\n        [NonSerialized]\n        private JSScriptRef _lastScriptRefOfTarget;\n\n        private string[] _tabViews = new string[] { \"Editor\", \"Source\", \"Primitive\" };\n        private int _selectedTabViewIndex = 0;\n\n        /// <summary>\n        /// indicates the current acutal state of this Editor instance\n        /// </summary>\n        private bool _enabled;\n\n        /// <summary>\n        /// the script runtime is not ready when the Editor is enabled, \n        /// try to mark and delay the call of OnEnable in scripts\n        /// </summary>\n        private bool _enabledPending;\n\n        private JSContext _ctx = JSContext.Null;\n        private JSValue _this_obj = JSApi.JS_UNDEFINED;\n\n        private bool _onDestroyValid;\n        private JSValue _onDestroyFunc = JSApi.JS_UNDEFINED;\n\n        private bool _onEnableValid;\n        private JSValue _onEnableFunc = JSApi.JS_UNDEFINED;\n\n        private bool _onDisableValid;\n        private JSValue _onDisableFunc = JSApi.JS_UNDEFINED;\n\n        private bool _onInspectorGUIValid;\n        private JSValue _onInspectorGUIFunc = JSApi.JS_UNDEFINED;\n\n        private bool _onBeforeScriptReloadValid;\n        private JSValue _onBeforeScriptReloadFunc = JSApi.JS_UNDEFINED;\n\n        private bool _onAfterScriptReloadValid;\n        private JSValue _onAfterScriptReloadFunc = JSApi.JS_UNDEFINED;\n\n        protected T GetTarget()\n        {\n            if (_target == null)\n            {\n                _target = target as T;\n            }\n            return _target;\n        }\n\n        void Awake()\n        {\n        }\n\n        protected abstract JSScriptClassType GetScriptClassType();\n\n        private void OnScriptReloading(ScriptContext context, string resolved_id)\n        {\n            if (context.CheckModuleId(_scriptRef, resolved_id))\n            {\n                if (_onBeforeScriptReloadValid)\n                {\n                    JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onBeforeScriptReloadFunc);\n                }\n            }\n        }\n\n        private void OnScriptReloaded(ScriptContext context, string resolved_id)\n        {\n            if (context.CheckModuleId(_scriptRef, resolved_id))\n            {\n                if (!_this_obj.IsNullish())\n                {\n                    JSValue newClass;\n                    if (context.LoadModuleCacheExports(resolved_id, _scriptRef.className, out newClass))\n                    {\n                        var prototype = JSApi.JS_GetProperty(context, newClass, context.GetAtom(\"prototype\"));\n\n                        if (prototype.IsObject())\n                        {\n                            OnUnbindingJSMembers();\n                            JSApi.JS_SetPrototype(context, _this_obj, prototype);\n                            OnBindingJSMembers(context);\n\n                            if (_onAfterScriptReloadValid)\n                            {\n                                JSScriptableObject._CallJSFunc(context, _this_obj, _onAfterScriptReloadFunc);\n                            }\n                        }\n\n                        JSApi.JS_FreeValue(context, prototype);\n                        JSApi.JS_FreeValue(context, newClass);\n                    }\n                }\n            }\n\n            var scriptRefOfTarget = GetTarget().scriptRef;\n            if (!_lastScriptRefOfTarget.IsSameScript(scriptRefOfTarget) && context.CheckModuleId(scriptRefOfTarget, resolved_id))\n            {\n                // trigger editor script reloading after the target being changed\n                if (_enabled)\n                {\n                    OnEnable();\n                }\n            }\n        }\n\n        #region IObjectCollectionEntry implementation\n        public void OnCollectionReleased()\n        {\n            Release();\n        }\n        #endregion\n\n        protected void ReleaseJSValues()\n        {\n            var runtime = ScriptEngine.GetRuntime(_ctx);\n            if (!_this_obj.IsNullish())\n            {\n                OnUnbindingJSMembers();\n                runtime.GetObjectCache()?.RemoveObject(JSApi.JSB_FreePayload(_ctx, _this_obj));\n                JSApi.JS_FreeValue(_ctx, _this_obj);\n                _this_obj = JSApi.JS_UNDEFINED;\n            }\n\n            var context = runtime?.GetContext(_ctx);\n            _ctx = JSContext.Null;\n\n            if (context != null)\n            {\n                runtime.RemoveManagedObject(_handle);\n                context.OnScriptReloading -= OnScriptReloading;\n                context.OnScriptReloaded -= OnScriptReloaded;\n            }\n        }\n\n        void Release()\n        {\n            if (!GetTarget().isStandaloneScript)\n            {\n                GetTarget().ReleaseScriptInstance();\n                _lastScriptRefOfTarget.Reset();\n            }\n            ReleaseJSValues();\n        }\n\n        protected void CreateScriptInstance(JSContext ctx, JSValue this_obj, JSValue ctor)\n        {\n            var runtime = ScriptEngine.GetRuntime(ctx);\n            var context = runtime?.GetContext(ctx);\n            if (context == null || !context.IsValid())\n            {\n                return;\n            }\n\n            runtime.AddManagedObject(this, out _handle);\n            context.OnScriptReloading += OnScriptReloading;\n            context.OnScriptReloaded += OnScriptReloaded;\n            _ctx = ctx;\n            _this_obj = JSApi.JS_DupValue(ctx, this_obj);\n\n            if (!_this_obj.IsNullish())\n            {\n                OnBindingJSMembers(context);\n\n                var awakeFunc = JSApi.JS_GetProperty(ctx, this_obj, context.GetAtom(\"Awake\"));\n\n                JSScriptableObject._CallJSFunc(_ctx, _this_obj, awakeFunc);\n                JSApi.JS_FreeValue(_ctx, awakeFunc);\n            }\n        }\n\n        private void OnBindingJSMembers(ScriptContext context)\n        {\n            var ctx = (JSContext)context;\n\n            _onDestroyFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnDestroy\"));\n            _onDestroyValid = JSApi.JS_IsFunction(ctx, _onDestroyFunc) == 1;\n\n            _onEnableFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnEnable\"));\n            _onEnableValid = JSApi.JS_IsFunction(ctx, _onEnableFunc) == 1;\n\n            _onDisableFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnDisable\"));\n            _onDisableValid = JSApi.JS_IsFunction(ctx, _onDisableFunc) == 1;\n\n            _onInspectorGUIFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnInspectorGUI\"));\n            _onInspectorGUIValid = JSApi.JS_IsFunction(ctx, _onInspectorGUIFunc) == 1;\n\n            _onBeforeScriptReloadFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnBeforeScriptReload\"));\n            _onBeforeScriptReloadValid = JSApi.JS_IsFunction(ctx, _onBeforeScriptReloadFunc) == 1;\n\n            _onAfterScriptReloadFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnAfterScriptReload\"));\n            _onAfterScriptReloadValid = JSApi.JS_IsFunction(ctx, _onAfterScriptReloadFunc) == 1;\n        }\n\n        private void OnUnbindingJSMembers()\n        {\n            JSApi.JS_FreeValue(_ctx, _onDestroyFunc);\n            _onDestroyFunc = JSApi.JS_UNDEFINED;\n            _onDestroyValid = false;\n\n            JSApi.JS_FreeValue(_ctx, _onEnableFunc);\n            _onEnableFunc = JSApi.JS_UNDEFINED;\n            _onEnableValid = false;\n\n            JSApi.JS_FreeValue(_ctx, _onDisableFunc);\n            _onDisableFunc = JSApi.JS_UNDEFINED;\n            _onDisableValid = false;\n\n            JSApi.JS_FreeValue(_ctx, _onInspectorGUIFunc);\n            _onInspectorGUIFunc = JSApi.JS_UNDEFINED;\n            _onInspectorGUIValid = false;\n\n            JSApi.JS_FreeValue(_ctx, _onBeforeScriptReloadFunc);\n            _onBeforeScriptReloadFunc = JSApi.JS_UNDEFINED;\n            _onBeforeScriptReloadValid = false;\n\n            JSApi.JS_FreeValue(_ctx, _onAfterScriptReloadFunc);\n            _onAfterScriptReloadFunc = JSApi.JS_UNDEFINED;\n            _onAfterScriptReloadValid = false;\n        }\n\n        protected void CreateScriptInstance()\n        {\n            ReleaseJSValues();\n\n            var target_t = GetTarget();\n            var ctx = target_t.ctx;\n            if (!ctx.IsValid())\n            {\n                return;\n            }\n\n            var prefs = EditorRuntime.GetPrefs();\n            var runtime = ScriptEngine.GetRuntime(ctx);\n            if (prefs == null || runtime == null || !runtime.isRunning)\n            {\n                return;\n            }\n\n            var editorClass = JSApi.JS_UNDEFINED;\n            var context = runtime.GetMainContext();\n            var decorator_module = prefs.editorDecoratorScript;\n            var scriptFunc = context.EvalSource<ScriptFunction>($\"require('{decorator_module}').EditorUtil.getCustomEditor\", \"eval\");\n            if (scriptFunc != null)\n            {\n                unsafe\n                {\n                    var safeRelease = new Utils.SafeRelease(context, target_t.CloneValue());\n                    if (safeRelease[0].IsObject())\n                    {\n                        var args = stackalloc JSValue[] { safeRelease[0] };\n                        editorClass = scriptFunc._Invoke(context, 1, args);\n                    }\n                    safeRelease.Release();\n                }\n                scriptFunc.Dispose();\n            }\n            else\n            {\n                Debug.LogError($\"failed to get EditorUtil.getCustomEditor in {decorator_module}\");\n            }\n\n            if (JSApi.JS_IsConstructor(ctx, editorClass) == 1)\n            {\n                var objectCache = runtime.GetObjectCache();\n                var object_id = objectCache.AddObject(this, false);\n                var editorInstance = JSApi.jsb_construct_bridge_object(ctx, editorClass, object_id);\n                if (editorInstance.IsException())\n                {\n                    ctx.print_exception();\n                    objectCache.RemoveObject(object_id);\n                }\n                else\n                {\n                    _lastScriptRefOfTarget = target_t.scriptRef;\n                    objectCache.AddJSValue(this, editorInstance);\n                    context.TrySetScriptRef(ref _scriptRef, editorClass);\n                    CreateScriptInstance(ctx, editorInstance, editorClass);\n                    JSApi.JS_FreeValue(ctx, editorInstance);\n                }\n            }\n\n            JSApi.JS_FreeValue(ctx, editorClass);\n        }\n\n        void OnEnable()\n        {\n            _enabled = true;\n            _enabledPending = true;\n            ReleaseJSValues();\n        }\n\n        private void EnableScriptInstance()\n        {\n            if (!_enabledPending || !_enabled)\n            {\n                return;\n            }\n\n            // 当前编辑器为附加模式执行时, 等待目标脚本建立连接\n            // 否则由编辑器管理目标生命周期\n\n            if (GetTarget().isStandaloneScript)\n            {\n                if (GetTarget().isScriptInstanced)\n                {\n                    this.OnEnableScriptInstance();\n                }\n            }\n            else\n            {\n                if (GetTarget().CreateScriptInstance())\n                {\n                    this.OnEnableScriptInstance();\n                }\n            }\n        }\n\n        private void OnEnableScriptInstance()\n        {\n            _enabledPending = false;\n            this.CreateScriptInstance();\n\n            if (_onEnableValid)\n            {\n                JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onEnableFunc);\n            }\n        }\n\n        void OnDisable()\n        {\n            _enabledPending = false;\n            _enabled = false;\n\n            if (_onDisableValid)\n            {\n                JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onDisableFunc);\n            }\n\n            Release();\n        }\n\n        void OnDestroy()\n        {\n            if (_onDestroyValid)\n            {\n                JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onDestroyFunc);\n            }\n\n            _enabledPending = false;\n            Release();\n        }\n\n        private void OnSelectedScript(JSScriptClassPathHint classPath)\n        {\n            var target_t = GetTarget();\n\n            if (_enabled && target_t != null && !classPath.IsReferenced(target_t.scriptRef))\n            {\n                var scriptRef = target_t.scriptRef;\n\n                scriptRef.sourceFile = classPath.sourceFile;\n                if (scriptRef.modulePath != classPath.modulePath || scriptRef.className != classPath.className)\n                {\n                    scriptRef.modulePath = classPath.modulePath;\n                    scriptRef.className = classPath.className;\n\n                    Undo.RecordObject(target_t, \"Change Script Reference\");\n                    target_t.scriptRef = scriptRef;\n                    this.ReleaseJSValues();\n                    target_t.ReleaseScriptInstance();\n                    target_t.CreateScriptInstance();\n\n                    // 重新绑定当前编辑器脚本实例\n                    this.CreateScriptInstance();\n                }\n                else\n                {\n                    Undo.RecordObject(target_t, \"Update Script Source\");\n                    target_t.scriptRef = scriptRef;\n                }\n\n                EditorUtility.SetDirty(target_t);\n            }\n        }\n\n        protected virtual void DrawSourceView()\n        {\n            BaseEditorWindow.Block(\"Target Script\", () =>\n            {\n                var target_t = GetTarget();\n                EditorGUILayout.BeginHorizontal();\n                EditorGUILayout.TextField(\"Source File\", target_t.scriptRef.sourceFile);\n                var sourceFileRect = GUILayoutUtility.GetLastRect();\n\n                if (GUILayout.Button(\"F\", GUILayout.Width(20f)))\n                {\n                    sourceFileRect.y += 10f;\n                    if (JSScriptSearchWindow.Show(sourceFileRect, string.Empty, GetScriptClassType(), OnSelectedScript))\n                    {\n                        GUIUtility.ExitGUI();\n                    }\n                }\n\n                EditorGUILayout.EndHorizontal();\n\n                if (!string.IsNullOrEmpty(target_t.scriptRef.sourceFile))\n                {\n                    var sourceFileExists = File.Exists(target_t.scriptRef.sourceFile);\n\n                    if (!sourceFileExists)\n                    {\n                        EditorGUILayout.HelpBox(\"Source file is missing\", MessageType.Warning);\n                    }\n                }\n                else\n                {\n                    if (EditorApplication.isPlaying)\n                    {\n                        EditorGUILayout.HelpBox(\"Script instance without relevant script reference info?\", MessageType.Warning);\n                    }\n                }\n\n                EditorGUILayout.LabelField(\"Module Path\", target_t.scriptRef.modulePath);\n                EditorGUILayout.LabelField(\"Class Name\", target_t.scriptRef.className);\n            });\n\n            BaseEditorWindow.Block(\"Editor Script\", () =>\n            {\n                EditorGUILayout.LabelField(\"Module Path\", _scriptRef.modulePath);\n                EditorGUILayout.LabelField(\"Class Name\", _scriptRef.className);\n            });\n        }\n\n        private void DrawPrimitiveView()\n        {\n            var ps = GetTarget().properties;\n            if (ps == null || ps.IsEmpty)\n            {\n                EditorGUILayout.HelpBox(\"Empty Properties View\", MessageType.Info);\n                return;\n            }\n\n            EditorGUI.BeginDisabledGroup(true);\n            EditorGUILayout.IntField(\"Data Format\", ps.dataFormat);\n            EditorGUILayout.IntField(\"Blob\", ps.GenericCount);\n            EditorGUILayout.IntField(\"Referenced Objects\", ps.ReferencedObjectCount);\n            EditorGUI.EndDisabledGroup();\n        }\n\n        private void DrawScriptingView()\n        {\n            var target_t = GetTarget();\n\n            if (target_t.isScriptInstanced)\n            {\n                if (target_t.IsValid())\n                {\n                    if (_onInspectorGUIValid)\n                    {\n                        JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onInspectorGUIFunc);\n                    }\n                    else\n                    {\n                        EditorGUILayout.HelpBox(\"No inspector available for this script type\", MessageType.Info);\n                    }\n                }\n                else\n                {\n                    if (!target_t.scriptRef.IsEmpty())\n                    {\n                        EditorGUILayout.HelpBox(\"Invalid script reference\", MessageType.Warning);\n                    }\n                    DrawSourceView();\n                }\n            }\n            else\n            {\n                EditorGUILayout.HelpBox(\"Waiting for script instancing...\", MessageType.Warning);\n                OnWaitingForScriptInstancing();\n            }\n        }\n\n        protected virtual void OnWaitingForScriptInstancing()\n        {\n        }\n\n        public override void OnInspectorGUI()\n        {\n            if (EditorApplication.isCompiling || (!EditorApplication.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode))\n            {\n                Release();\n                EditorGUILayout.HelpBox(\"Temporarily unavailable in the script compilation process\", MessageType.Warning);\n                return;\n            }\n\n            if (_enabledPending)\n            {\n                EnableScriptInstance();\n            }\n\n            _selectedTabViewIndex = GUILayout.Toolbar(_selectedTabViewIndex, _tabViews);\n            switch (_selectedTabViewIndex)\n            {\n                case 0: DrawScriptingView(); break;\n                case 1: DrawSourceView(); break;\n                default: DrawPrimitiveView(); break;\n            }\n        }\n    }\n}\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/JSInspectorBase.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 43d172ac0ae6ce64392ab5e901a6aeee\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/JSScriptClassPathHint.cs",
    "content": "﻿#if !JSB_UNITYLESS\nnamespace QuickJS.Unity\n{\n    [System.Flags]\n    public enum JSScriptClassType\n    {\n        None = 0,\n        MonoBehaviour = 1,\n\n        /// <summary>\n        /// UnityEditor.Editor\n        /// </summary>\n        CustomEditor = 2,\n\n        ScriptableObject = 4,\n        EditorWindow = 8,\n    }\n\n    public struct JSScriptClassPathHint\n    {\n        public readonly string sourceFile;\n        public readonly string modulePath;\n        public readonly string className;\n        public readonly string classPath;\n        public readonly JSScriptClassType classType;\n\n        public JSScriptClassPathHint(string sourceFile, string modulePath, string className, JSScriptClassType classType)\n        {\n            this.sourceFile = sourceFile;\n            this.modulePath = modulePath;\n            this.className = className;\n            this.classPath = JSScriptRef.ToClassPath(modulePath, className);\n            this.classType = classType;\n        }\n\n        public bool IsReferenced(JSScriptRef scriptRef)\n        {\n            return scriptRef.modulePath == modulePath && scriptRef.className == className;\n        }\n\n        public string ToClassPath()\n        {\n            return classPath;\n        }\n    }\n}\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/JSScriptClassPathHint.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 2f85e8f11c134957badab8e5e5587495\r\ntimeCreated: 1619156725"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/JSScriptFinder.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    /// <summary>\r\n    /// ScriptFinder is a utility editor service to collect the unity scripts (MonoBehaviour/Editor etc.) implemented by typescripts \r\n    /// </summary>\r\n    public class JSScriptFinder\r\n    {\r\n        private static JSScriptFinder _finder;\r\n\r\n        private FileSystemWatcher _fsw;\r\n        private string _baseDir;\r\n        private string _fileExt;\r\n        private bool _isRefreshing;\r\n        private float _delay;\r\n\r\n        // classPath => JSScriptClassPathHint\r\n        private Dictionary<string, JSScriptClassPathHint> _scriptClassPaths = new Dictionary<string, JSScriptClassPathHint>();\r\n        private Dictionary<string, List<string>> _fullPathToClassPath = new Dictionary<string, List<string>>();\r\n\r\n        private bool _cachedChangesDirty = false;\r\n        // fullPath => WatcherChangeType\r\n        private Dictionary<string, WatcherChangeTypes> _cachedChanges = new Dictionary<string, WatcherChangeTypes>();\r\n\r\n        public event Action<string, JSScriptClassType> ModuleSourceChanged;\r\n        public event Action ScriptClassPathsUpdated;\r\n\r\n        public static JSScriptFinder GetInstance()\r\n        {\r\n            if (_finder == null)\r\n            {\r\n                var prefs = PrefsLoader.CurrentPrefs;\r\n                var baseDir = prefs.sourceDir;\r\n\r\n                _finder = new JSScriptFinder(baseDir, prefs.typescriptExt);\r\n                _finder.Start(); //TODO: need optimization, make the full collecting process async, and wait it finished \r\n            }\r\n\r\n            return _finder;\r\n        }\r\n\r\n        public JSScriptFinder(string baseDir, string fileExt)\r\n        {\r\n            _baseDir = baseDir;\r\n            _fileExt = fileExt;\r\n        }\r\n\r\n        private void OnChanged(object sender, FileSystemEventArgs e)\r\n        {\r\n            lock (_cachedChanges)\r\n            {\r\n                var fullPath = Path.GetFullPath(e.FullPath);\r\n                _cachedChanges[fullPath] = WatcherChangeTypes.Changed;\r\n                _cachedChangesDirty = true;\r\n                // UnityEngine.Debug.Log($\"changed {fullPath}\");\r\n            }\r\n        }\r\n\r\n        private void OnCreated(object sender, FileSystemEventArgs e)\r\n        {\r\n            lock (_cachedChanges)\r\n            {\r\n                var fullPath = Path.GetFullPath(e.FullPath);\r\n                _cachedChanges[fullPath] = WatcherChangeTypes.Created;\r\n                _cachedChangesDirty = true;\r\n                // UnityEngine.Debug.Log($\"created {fullPath}\");\r\n            }\r\n        }\r\n\r\n        private void OnDeleted(object sender, FileSystemEventArgs e)\r\n        {\r\n            lock (_cachedChanges)\r\n            {\r\n                var fullPath = Path.GetFullPath(e.FullPath);\r\n                _cachedChanges[fullPath] = WatcherChangeTypes.Deleted;\r\n                _cachedChangesDirty = true;\r\n                // UnityEngine.Debug.Log($\"deleted {fullPath}\");\r\n            }\r\n        }\r\n\r\n        public void RefreshAll()\r\n        {\r\n            _isRefreshing = true;\r\n            _scriptClassPaths.Clear();\r\n            SearchDirectory(_baseDir);\r\n            _isRefreshing = false;\r\n            ScriptClassPathsUpdated?.Invoke();\r\n        }\r\n\r\n        private void SearchDirectory(string dir)\r\n        {\r\n            foreach (var subDir in Directory.GetDirectories(dir))\r\n            {\r\n                SearchDirectory(subDir);\r\n            }\r\n\r\n            foreach (var file in Directory.GetFiles(dir))\r\n            {\r\n                ParseFile(file.Replace('\\\\', '/'));\r\n            }\r\n        }\r\n\r\n        private void ParseFile(string filePath)\r\n        {\r\n            if (!filePath.EndsWith(_fileExt))\r\n            {\r\n                return;\r\n            }\r\n\r\n            var results = new List<JSScriptClassPathHint>();\r\n            string normalizedPath;\r\n            string modulePath;\r\n            if (UnityHelper.ResolveScriptRef(_baseDir, filePath, out normalizedPath, out modulePath, results))\r\n            {\r\n                List<string> list;\r\n                normalizedPath = normalizedPath.ToLower();\r\n                if (_fullPathToClassPath.TryGetValue(normalizedPath, out list))\r\n                {\r\n                    foreach (var item in list)\r\n                    {\r\n                        _scriptClassPaths.Remove(item);\r\n                    }\r\n                    list.Clear();\r\n                }\r\n                else\r\n                {\r\n                    list = _fullPathToClassPath[normalizedPath] = new List<string>();\r\n                }\r\n\r\n                var classTypes = JSScriptClassType.None;\r\n                foreach (var result in results)\r\n                {\r\n                    var classPath = result.ToClassPath();\r\n\r\n                    list.Add(classPath);\r\n                    _scriptClassPaths[classPath] = result;\r\n                    classTypes |= result.classType;\r\n                }\r\n\r\n                ModuleSourceChanged?.Invoke(modulePath, classTypes);\r\n            }\r\n        }\r\n\r\n        public bool Search(JSScriptClassType classType, List<JSScriptClassPathHint> results)\r\n        {\r\n            return Search(null, classType, results);\r\n        }\r\n\r\n        public bool Search(string pattern, JSScriptClassType classType, List<JSScriptClassPathHint> results)\r\n        {\r\n            foreach (var pair in _scriptClassPaths)\r\n            {\r\n                //TODO: need optimization\r\n                if ((pair.Value.classType & classType) != 0 && (string.IsNullOrEmpty(pattern) || pair.Key.Contains(pattern)))\r\n                {\r\n                    results.Add(pair.Value);\r\n                }\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n        public void Start()\r\n        {\r\n            if (_fsw != null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            UnityEditor.EditorApplication.update += OnUpdate;\r\n        }\r\n\r\n        private void OnUpdate()\r\n        {\r\n            if (_isRefreshing || !UnityHelper.IsApplicationActive())\r\n            {\r\n                return;\r\n            }\r\n\r\n            _delay += UnityEngine.Time.realtimeSinceStartup;\r\n            if (_delay < 1.0f)\r\n            {\r\n                return;\r\n            }\r\n\r\n            _delay = 0f;\r\n            if (_fsw == null)\r\n            {\r\n                if (Directory.Exists(_baseDir))\r\n                {\r\n                    _fsw = new FileSystemWatcher(_baseDir, $\"*{_fileExt}\");\r\n                    _fsw.IncludeSubdirectories = true;\r\n                    _fsw.Changed += OnChanged;\r\n                    _fsw.Created += OnCreated;\r\n                    _fsw.Deleted += OnDeleted;\r\n                    _fsw.EnableRaisingEvents = true;\r\n                    RefreshAll();\r\n                }\r\n                return;\r\n            }\r\n\r\n            lock (_cachedChanges)\r\n            {\r\n                if (_cachedChangesDirty)\r\n                {\r\n                    foreach (var pair in _cachedChanges)\r\n                    {\r\n                        var fullPath = pair.Key;\r\n                        var changeType = pair.Value;\r\n\r\n                        if (changeType == WatcherChangeTypes.Deleted)\r\n                        {\r\n                            List<string> classPathList;\r\n                            var lowerCasedFullPath = fullPath.ToLower();\r\n                            if (_fullPathToClassPath.TryGetValue(lowerCasedFullPath, out classPathList))\r\n                            {\r\n                                _fullPathToClassPath.Remove(lowerCasedFullPath);\r\n                                foreach (var item in classPathList)\r\n                                {\r\n                                    _scriptClassPaths.Remove(item);\r\n                                }\r\n                            }\r\n                        }\r\n                        else\r\n                        {\r\n                            ParseFile(fullPath);\r\n                        }\r\n                    }\r\n                    _cachedChanges.Clear();\r\n                    _cachedChangesDirty = false;\r\n                    ScriptClassPathsUpdated?.Invoke();\r\n                }\r\n            }\r\n        }\r\n\r\n        public void Stop()\r\n        {\r\n            UnityEditor.EditorApplication.update -= OnUpdate;\r\n\r\n            if (_fsw != null)\r\n            {\r\n                _fsw.Dispose();\r\n                _fsw = null;\r\n            }\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/JSScriptFinder.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 6b6b93d0397822b44aa94815efb3343d\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/JSScriptSearchWindow.cs",
    "content": "﻿#if !JSB_UNITYLESS\nusing System;\nusing System.Collections.Generic;\n\nnamespace QuickJS.Unity\n{\n    using UnityEditor;\n    using UnityEditor.IMGUI.Controls;\n    using UnityEngine;\n\n    public class JSScriptSearchWindow : EditorWindow\n    {\n        private bool _parepared;\n        private Action<JSScriptClassPathHint> _selectCallback;\n        \n        private bool _showSearchResults;\n        private int _selectedSearchResultIndex;\n        private int _maxSearchResults = 30;\n        private string _searchString = \"string.Empty\";\n\n        private JSScriptClassType _searchType;\n\n        private List<JSScriptClassPathHint> _searchResults = new List<JSScriptClassPathHint>();\n        private SearchField _searchField;\n\n        private Vector2 _searchScrollViewState;\n\n        private float Styles_resultHeight = 20;\n        private float Styles_resultsBorderWidth = 2;\n        // private float Styles_resultsMargin = 15;\n        // private float Styles_resultsLabelOffset = 2;\n\n        private GUIStyle Styles_entryEven;\n        private GUIStyle Styles_entryOdd;\n        private GUIStyle Styles_labelStyle;\n        // private GUIStyle Styles_resultsBorderStyle;\n\n        private GUIContent s_TextImage = new GUIContent();\n        \n        private GUIContent TempContent(string t, Texture i = null)\n        {\n            s_TextImage.text = t;\n            s_TextImage.image = i;\n            return s_TextImage;\n        }\n\n        private void OnEnable()\n        {\n            _parepared = false;\n        }\n\n        private void OnPrepareGUI()\n        {\n            Styles_entryEven = new GUIStyle(\"CN EntryBackEven\");\n            Styles_entryOdd = new GUIStyle(\"CN EntryBackOdd\");\n            Styles_labelStyle = new GUIStyle(EditorStyles.label);\n            // Styles_resultsBorderStyle = new GUIStyle(\"hostview\");\n\n            Styles_labelStyle.alignment = TextAnchor.MiddleLeft;\n            Styles_labelStyle.richText = true;\n        }\n\n        void OnGUI()\n        {\n            if (!_parepared)\n            {\n                _parepared = true;\n                OnPrepareGUI();\n            }\n\n            DrawSearchField();\n            Repaint();\n        }\n        \n        private static void CloseAllOpenWindows<T>()\n        {\n            foreach (var obj in Resources.FindObjectsOfTypeAll(typeof(T)))\n            {\n                try\n                {\n                    ((EditorWindow)obj).Close();\n                }\n                catch\n                {\n                    Object.DestroyImmediate(obj);\n                }\n            }\n        }\n\n        public static bool Show(Rect rect, string searchString, JSScriptClassType searchType, Action<JSScriptClassPathHint> selectCallback)\n        {\n            CloseAllOpenWindows<JSScriptSearchWindow>();\n            var window = ScriptableObject.CreateInstance<JSScriptSearchWindow>();\n            window._searchString = searchString;\n            window._selectCallback = selectCallback;\n            window._searchType = searchType;\n            window.Init(rect);\n            return true;\n        }\n\n        private void Init(Rect rect)\n        {\n            var screenRect = GUIUtility.GUIToScreenRect(rect);\n            \n            ShowAsDropDown(screenRect, CalculateWindowSize(rect));\n            \n            _searchResults.Clear();\n            JSScriptFinder.GetInstance().Search(_searchString, _searchType, _searchResults);\n        }\n        \n        private Vector2 CalculateWindowSize(Rect buttonRect)\n        {\n            var vector = new Vector2(200f, _maxSearchResults * Styles_resultHeight);\n            vector.x += Styles_resultsBorderWidth * 2f;\n            vector.y += Styles_resultHeight;\n            vector.y = Mathf.Clamp(vector.y, base.minSize.y, base.maxSize.y);\n            if (vector.x < buttonRect.width)\n            {\n                vector.x = buttonRect.width;\n            }\n            if (vector.x < minSize.x)\n            {\n                vector.x = minSize.x;\n            }\n            if (vector.y < minSize.y)\n            {\n                vector.y = minSize.y;\n            }\n            return new Vector2(vector.x, vector.y);\n        }\n\n        private void DrawSearchField()\n        {\n            var rect = GUILayoutUtility.GetRect(1, 1, 18, 18, GUILayout.ExpandWidth(true));\n            if (_searchField == null)\n            {\n                _searchField = new SearchField();\n                _searchField.downOrUpArrowKeyPressed += OnDownOrUpArrowKeyPressed;\n            }\n\n            var result = _searchField.OnGUI(rect, _searchString);\n            if (result != _searchString)\n            {\n                _searchString = result;\n                _searchResults.Clear();\n                JSScriptFinder.GetInstance().Search(_searchString, _searchType, _searchResults);\n            }\n\n            rect.y += 18;\n            DrawSearchResults(rect);\n        }\n\n        private void DrawSearchResults(Rect rect)\n        {\n            if (this._searchResults.Count <= 0)\n            {\n                return;\n            }\n\n            _searchScrollViewState = GUILayout.BeginScrollView(_searchScrollViewState);\n            var current = Event.current;\n            var mouseIsInResultsRect = rect.Contains(current.mousePosition);\n            var lastSelectedSearchResultIndex = _selectedSearchResultIndex;\n\n            for (var i = 0; i < this._searchResults.Count; i++)\n            {\n                var elementContent = TempContent(_searchResults[i].ToClassPath());\n                var elementRect = GUILayoutUtility.GetRect(elementContent, Styles_labelStyle);\n\n                elementRect.width = rect.width;\n                if (current.type == EventType.Repaint)\n                {\n                    var style = i % 2 == 0 ? Styles_entryOdd : Styles_entryEven;\n                    style.Draw(elementRect, false, false, i == _selectedSearchResultIndex, false);\n                    GUI.Label(elementRect, this._searchResults[i].ToClassPath(), Styles_labelStyle);\n                }\n                \n                if (elementRect.Contains(current.mousePosition))\n                {\n                    _selectedSearchResultIndex = i;\n                    \n                    if (current.type == EventType.MouseDown)\n                    {\n                        this.OnConfirmSearchResult(this._searchResults[i]);\n                    }\n                }\n            }\n            GUI.EndScrollView();\n            \n            if (current.type == EventType.KeyUp && current.keyCode == KeyCode.Return && _selectedSearchResultIndex >= 0)\n            {\n                this.OnConfirmSearchResult(this._searchResults[_selectedSearchResultIndex]);\n            }\n        }\n\n        private void OnConfirmSearchResult(JSScriptClassPathHint result)\n        {\n            try\n            {\n                _selectCallback?.Invoke(result);\n            }\n            catch (Exception exception)\n            {\n                Debug.LogError(exception);\n            }\n            Close();\n            GUIUtility.ExitGUI();\n            Event.current.Use();\n        }\n\n        private void OnDownOrUpArrowKeyPressed()\n        {\n            //TODO: keyboard operations\n        }\n    }\n}\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/JSScriptSearchWindow.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 7918b934f03640d0986a2f9658f54caa\r\ntimeCreated: 1619152826"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/JSScriptableObjectInspector.cs",
    "content": "﻿#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.IO;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using UnityEditor;\r\n    using UnityEditor.IMGUI.Controls;\r\n    using UnityEngine;\r\n    using Native;\r\n\r\n    [CustomEditor(typeof(JSScriptableObject))]\r\n    public class JSScriptableObjectInspector : JSInspectorBase<JSScriptableObject>\r\n    {\r\n        protected override JSScriptClassType GetScriptClassType()\r\n        {\r\n            return JSScriptClassType.ScriptableObject;\r\n        }\r\n\r\n        protected override void OnWaitingForScriptInstancing()\r\n        {\r\n            var target_t = GetTarget();\r\n\r\n            if (target_t.enabled)\r\n            {\r\n                target_t.CreateScriptInstance();\r\n            }\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/JSScriptableObjectInspector.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 3479d842276b7594ba8030a3090bf4b4\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/PrefsEditor.cs",
    "content": "﻿#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.IO;\r\nusing System.Text;\r\nusing System.Reflection;\r\nusing System.Runtime.CompilerServices;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using UnityEngine;\r\n    using UnityEditor;\r\n    using UnityEditor.IMGUI.Controls;\r\n    using QuickJS.Binding;\r\n\r\n    // 配置编辑器\r\n    public class PrefsEditor : BaseEditorWindow\r\n    {\r\n        internal abstract class TreeViewNode<T> : SimpleTreeView.INode\r\n        {\r\n            protected bool _expanded = true;\r\n\r\n            protected T _value;\r\n            protected GUIContent _content;\r\n            private bool _isSizeCached;\r\n            private Vector2 _contentSize;\r\n            protected List<SimpleTreeView.INode> _children = new List<SimpleTreeView.INode>();\r\n\r\n            public T value => _value;\r\n\r\n            public GUIContent content => _content;\r\n\r\n            public int childCount => _children.Count;\r\n\r\n            public bool isExpanded\r\n            {\r\n                get { return _expanded; }\r\n                set { _expanded = value; }\r\n            }\r\n\r\n            public bool CollapseAll()\r\n            {\r\n                var change = false;\r\n                if (_expanded)\r\n                {\r\n                    _expanded = false;\r\n                    change = true;\r\n                }\r\n\r\n                foreach (var child in _children)\r\n                {\r\n                    if (child.CollapseAll())\r\n                    {\r\n                        change = true;\r\n                    }\r\n                }\r\n                return change;\r\n            }\r\n\r\n            public bool ExpandAll()\r\n            {\r\n                var change = false;\r\n                if (!_expanded)\r\n                {\r\n                    _expanded = true; change = true;\r\n                }\r\n\r\n                foreach (var child in _children)\r\n                {\r\n                    if (child.ExpandAll())\r\n                    {\r\n                        change = true;\r\n                    }\r\n                }\r\n                return change;\r\n            }\r\n\r\n            public void ShowContextMenu(SimpleTreeView.State state)\r\n            {\r\n                var menu = new GenericMenu();\r\n                menu.AddItem(new GUIContent(\"Expand All\"), false, () => state.ExpandAll());\r\n                menu.AddItem(new GUIContent(\"Collapse All\"), false, () => state.CollapseAll());\r\n                menu.ShowAsContext();\r\n            }\r\n\r\n            public void AddChild(SimpleTreeView.INode node)\r\n            {\r\n                _children.Add(node);\r\n            }\r\n\r\n            public Vector2 CalcSize(GUIStyle style)\r\n            {\r\n                if (!_isSizeCached)\r\n                {\r\n                    _isSizeCached = true;\r\n                    _contentSize = style.CalcSize(content);\r\n                }\r\n                return _contentSize;\r\n            }\r\n\r\n            public void Prepass(SimpleTreeView.State state)\r\n            {\r\n                state.AddSpace(this);\r\n                if (_expanded)\r\n                {\r\n                    state.PushGroup();\r\n                    for (int i = 0, count = _children.Count; i < count; ++i)\r\n                    {\r\n                        _children[i].Prepass(state);\r\n                    }\r\n                    state.PopGroup();\r\n                }\r\n            }\r\n\r\n            public bool Render(SimpleTreeView.State state)\r\n            {\r\n                if (state.Render(this))\r\n                {\r\n                    if (_expanded)\r\n                    {\r\n                        state.PushGroup();\r\n                        for (int i = 0, count = _children.Count; i < count; ++i)\r\n                        {\r\n                            if (!_children[i].Render(state))\r\n                            {\r\n                                return false;\r\n                            }\r\n                        }\r\n                        state.PopGroup();\r\n                    }\r\n                    return true;\r\n                }\r\n                return false;\r\n            }\r\n        }\r\n\r\n        internal class Type_TreeViewNode : TreeViewNode<Type>\r\n        {\r\n            private GUIContent _fullNameContent;\r\n\r\n            public GUIContent FullName => _fullNameContent;\r\n\r\n            public Type_TreeViewNode(Type type)\r\n            {\r\n                var icon = GetIcon(type);\r\n\r\n                _value = type;\r\n                _content = new GUIContent(type.Name, icon);\r\n                _fullNameContent = new GUIContent(type.FullName, icon);\r\n            }\r\n\r\n            public static Texture GetIcon(Type type)\r\n            {\r\n                if (type.IsEnum)\r\n                {\r\n                    return UnityHelper.GetIcon(\"EnumIcon\");\r\n                }\r\n\r\n                if (type.IsValueType)\r\n                {\r\n                    return UnityHelper.GetIcon(\"StructIcon\");\r\n                }\r\n\r\n                return UnityHelper.GetIcon(\"ClassIcon\");\r\n            }\r\n\r\n            public bool MatchString(string pattern)\r\n            {\r\n                return _value.FullName.IndexOf(pattern, StringComparison.OrdinalIgnoreCase) >= 0;\r\n            }\r\n\r\n            public override string ToString()\r\n            {\r\n                return _value.Name;\r\n            }\r\n        }\r\n\r\n        internal class Namespace_TreeViewNode : TreeViewNode<string>\r\n        {\r\n            public Namespace_TreeViewNode(string ns)\r\n            {\r\n                _value = ns;\r\n                _content = new GUIContent(ns, UnityHelper.GetIcon(\"NamespaceIcon\"));\r\n            }\r\n\r\n            public override string ToString()\r\n            {\r\n                return _value;\r\n            }\r\n        }\r\n\r\n        internal class Assembly_TreeViewNode : TreeViewNode<Assembly>\r\n        {\r\n            private Dictionary<string, Namespace_TreeViewNode> _allNamespaces = new Dictionary<string, Namespace_TreeViewNode>();\r\n\r\n            public Namespace_TreeViewNode GetNamespace_TreeViewNode(string ns)\r\n            {\r\n                var name = string.IsNullOrEmpty(ns) ? \"-\" : ns;\r\n                Namespace_TreeViewNode node;\r\n                if (!_allNamespaces.TryGetValue(name, out node))\r\n                {\r\n                    _allNamespaces[name] = node = new Namespace_TreeViewNode(name);\r\n                    AddChild(node);\r\n                }\r\n                return node;\r\n            }\r\n\r\n            public Assembly_TreeViewNode(Assembly assembly)\r\n            {\r\n                _value = assembly;\r\n                _content = new GUIContent(assembly.GetName().Name, UnityHelper.GetIcon(\"AssemblyIcon\"));\r\n            }\r\n\r\n            public override string ToString()\r\n            {\r\n                return _value.GetName().Name;\r\n            }\r\n        }\r\n\r\n        internal interface IView\r\n        {\r\n            void Draw(PrefsEditor context);\r\n        }\r\n\r\n        internal class NoneView : IView\r\n        {\r\n            public void Draw(PrefsEditor context)\r\n            {\r\n                EditorGUILayout.HelpBox(\"Nothing\", MessageType.Warning);\r\n            }\r\n        }\r\n\r\n        internal class NamespaceInfoView : IView\r\n        {\r\n            public string _namespace;\r\n\r\n            public void Show(string ns)\r\n            {\r\n                _namespace = ns;\r\n            }\r\n\r\n            public void Draw(PrefsEditor context)\r\n            {\r\n                if (_namespace == \"-\")\r\n                {\r\n                    EditorGUILayout.HelpBox(\"It's not a real namespace (types without namespace)\", MessageType.Info);\r\n                }\r\n                else\r\n                {\r\n                    EditorGUILayout.LabelField(\"Namespace\", _namespace);\r\n                    var blocked = context._bindingManager.IsNamespaceInBlacklist(_namespace);\r\n                    var blocked_t = EditorGUILayout.Toggle(\"Blacklisted\", blocked);\r\n                    if (blocked_t != blocked)\r\n                    {\r\n                        if (blocked_t)\r\n                        {\r\n                            context._bindingManager.AddNamespaceBlacklist(_namespace);\r\n                            context._prefs.namespaceBlacklist.Add(_namespace);\r\n                        }\r\n                        else\r\n                        {\r\n                            context._bindingManager.RemoveNamespaceBlacklist(_namespace);\r\n                            context._prefs.namespaceBlacklist.Remove(_namespace);\r\n                        }\r\n                        context.MarkAsDirty();\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        internal class TypeInfoView : IView\r\n        {\r\n            private Type _type;\r\n\r\n            public void Show(Type type)\r\n            {\r\n                _type = type;\r\n            }\r\n\r\n            public void Draw(PrefsEditor context)\r\n            {\r\n                if (_type == null)\r\n                {\r\n                    EditorGUILayout.HelpBox(\"No type is seleted\", MessageType.Warning);\r\n                    return;\r\n                }\r\n\r\n                if (DrawTypeBindingInfo(context._bindingManager.GetExportedType(_type)))\r\n                {\r\n                    return;\r\n                }\r\n\r\n                if (DrawRawTypeBindingInfo(context._bindingManager.GetExportedRawType(_type)))\r\n                {\r\n                    return;\r\n                }\r\n\r\n                EditorGUILayout.HelpBox(_type.Name + \" will not be exported to the script runtime\", MessageType.Warning);\r\n            }\r\n\r\n            private bool DrawRawTypeBindingInfo(RawTypeBindingInfo rawTypeBindingInfo)\r\n            {\r\n                if (rawTypeBindingInfo == null)\r\n                {\r\n                    return false;\r\n                }\r\n                EditorGUI.BeginDisabledGroup(true);\r\n                EditorGUILayout.TextField(\"Raw Binding\", rawTypeBindingInfo.jsName);\r\n                EditorGUI.EndDisabledGroup();\r\n                return true;\r\n            }\r\n\r\n            private bool DrawTypeBindingInfo(TypeBindingInfo typeBindingInfo)\r\n            {\r\n                if (typeBindingInfo == null)\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                EditorGUI.BeginDisabledGroup(true);\r\n                EditorGUILayout.Toggle(\"Managed\", typeBindingInfo.disposable);\r\n                EditorGUILayout.TextField(\"Binding\", typeBindingInfo.csBindingName ?? string.Empty);\r\n\r\n                var tsTypeNaming = typeBindingInfo.tsTypeNaming;\r\n                EditorGUILayout.TextField(\"JS Module\", tsTypeNaming.moduleName);\r\n                EditorGUILayout.TextField(\"JS Namespace\", tsTypeNaming.ns);\r\n                EditorGUILayout.TextField(\"JS ClassName\", CodeGenUtils.GetTSClassName(typeBindingInfo));\r\n\r\n                var requiredDefines = typeBindingInfo.transform.requiredDefines;\r\n                if (requiredDefines != null && requiredDefines.Count > 0)\r\n                {\r\n                    EditorGUILayout.LabelField(\"Required Defines\");\r\n                    foreach (var def in requiredDefines)\r\n                    {\r\n                        EditorGUILayout.TextField(def);\r\n                    }\r\n                }\r\n                EditorGUI.EndDisabledGroup();\r\n                return true;\r\n            }\r\n        }\r\n\r\n        internal class AssemblyInfoView : IView\r\n        {\r\n            private Assembly _assembly;\r\n\r\n            public void Show(Assembly assembly)\r\n            {\r\n                _assembly = assembly;\r\n            }\r\n\r\n            public void Draw(PrefsEditor context)\r\n            {\r\n                if (_assembly == null)\r\n                {\r\n                    EditorGUILayout.HelpBox(\"No assembly is seleted\", MessageType.Warning);\r\n                    return;\r\n                }\r\n\r\n                var name = context._bindingManager.GetSimplifiedAssemblyName(_assembly);\r\n                var blocked = context._bindingManager.InAssemblyBlacklist(name);\r\n\r\n                EditorGUILayout.LabelField(\"Assembly\", _assembly.FullName);\r\n                EditorGUILayout.LabelField(\"Location\", _assembly.Location);\r\n                var blocked_t = EditorGUILayout.Toggle(\"Blacklisted\", blocked);\r\n                if (blocked_t != blocked)\r\n                {\r\n                    if (blocked_t)\r\n                    {\r\n                        context._bindingManager.AddAssemblyBlacklist(name);\r\n                        context._prefs.assemblyBlacklist.Add(name);\r\n                    }\r\n                    else\r\n                    {\r\n                        context._bindingManager.RemoveAssemblyBlacklist(name);\r\n                        context._prefs.assemblyBlacklist.Remove(name);\r\n                    }\r\n                    context.MarkAsDirty();\r\n                }\r\n            }\r\n        }\r\n\r\n        private Prefs _prefs;\r\n        private bool _dirty;\r\n        private BindingManager _bindingManager;\r\n\r\n        private int _selectedTabViewIndex;\r\n\r\n        [NonSerialized]\r\n        private GUIContent[] _tabViewNames = new GUIContent[] { };\r\n        private Action[] _tabViewDrawers = new Action[] { };\r\n        private string[] _newlineValues = new string[] { \"cr\", \"lf\", \"crlf\", \"\" };\r\n        private string[] _newlineNames = new string[] { \"UNIX\", \"MacOS\", \"Windows\", \"Auto\" };\r\n        private string[] _moduleStyleValues = new string[] { \"legacy\", \"singular\" };\r\n        private string[] _moduleStyleNames = new string[] { \"Legacy (Default)\", \"Singular (Experimental)\" };\r\n        private int _selectedBindingMethod;\r\n        private string[] _bindingMethodValues = new string[] { \"Reflect Bind\", \"Static Bind\", \"In-Memory Bind\" };\r\n        private string[] _bindingMethodDescriptions = new string[] { \"Reflect Bind\", \"Static Bind\", \"In-Memory Bind (experimental)\" };\r\n\r\n        private GUIStyle _footStyle;\r\n        private SearchField _searchField;\r\n        private string _lastSearchString = string.Empty;\r\n\r\n        private System.Collections.IEnumerator _typeTreeConstruct;\r\n        private int _typeTreeConstructWalk;\r\n        private int _typeTreeConstructAll;\r\n\r\n        private List<Type_TreeViewNode> _typeNodes = new List<Type_TreeViewNode>();\r\n\r\n        private SimpleTreeView _treeView = new SimpleTreeView();\r\n        private SimpleListView<Type_TreeViewNode> _listView = new SimpleListView<Type_TreeViewNode>();\r\n        private SimpleSplitView _splitView = new SimpleSplitView();\r\n        private List<IView> _allViews = new List<IView>();\r\n        private IView _activeView;\r\n\r\n        private List<string> _repeatStringCache = new List<string>(new string[] { \"\" });\r\n        [NonSerialized]\r\n        private Vector2 _scrollPosition_TypeCastRegistry;\r\n        [NonSerialized]\r\n        private Vector2 _scrollPosition_Codegen;\r\n        [NonSerialized]\r\n        private Rect _typesViewRect;\r\n\r\n        public void AddTabView(string name, Action action)\r\n        {\r\n            ArrayUtility.Add(ref _tabViewNames, new GUIContent(name));\r\n            ArrayUtility.Add(ref _tabViewDrawers, action);\r\n        }\r\n\r\n        private Type_TreeViewNode ConstructTypeNode<T>(TreeViewNode<T> parent, Dictionary<Type, Type_TreeViewNode> cache, Type type)\r\n        {\r\n            Type_TreeViewNode self;\r\n            if (!cache.TryGetValue(type, out self))\r\n            {\r\n                self = new Type_TreeViewNode(type);\r\n                cache[type] = self;\r\n                _typeNodes.Add(self);\r\n                if (type.DeclaringType != null)\r\n                {\r\n                    var declaringType = ConstructTypeNode(parent, cache, type.DeclaringType);\r\n                    declaringType.AddChild(self);\r\n                }\r\n                else\r\n                {\r\n                    parent.AddChild(self);\r\n                }\r\n            }\r\n\r\n            return self;\r\n        }\r\n\r\n        private System.Collections.IEnumerator ConstructAssemblyNode(Assembly assembly, Type[] types)\r\n        {\r\n            if (types.Length == 0)\r\n            {\r\n                yield break;\r\n            }\r\n            _typeTreeConstructAll += types.Length;\r\n            var node = new Assembly_TreeViewNode(assembly);\r\n\r\n            Array.Sort<Type>(types, (a, b) => string.Compare(a.FullName, b.FullName, true));\r\n            var cache = new Dictionary<Type, Type_TreeViewNode>();\r\n            foreach (var type in types)\r\n            {\r\n                _typeTreeConstructWalk++;\r\n                if (type.IsGenericTypeDefinition)\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                var ns = node.GetNamespace_TreeViewNode(type.Namespace);\r\n                ConstructTypeNode(ns, cache, type);\r\n                yield return null;\r\n            }\r\n\r\n            if (node.childCount > 0)\r\n            {\r\n                _treeView.Add(node);\r\n            }\r\n\r\n            yield break;\r\n        }\r\n\r\n        protected override void OnEnable()\r\n        {\r\n            base.OnEnable();\r\n\r\n            var args = new BindingManager.Args()\r\n            {\r\n                utils = new UnityBindingUtils(),\r\n            };\r\n\r\n            _prefs = PrefsLoader.CurrentPrefs;\r\n            _dirty = string.IsNullOrEmpty(_prefs.filePath);\r\n            _selectedBindingMethod = Array.IndexOf(_bindingMethodValues, _prefs.preferredBindingMethod);\r\n            _bindingManager = new BindingManager(_prefs, args);\r\n            _bindingManager.Collect();\r\n            _bindingManager.Generate(TypeBindingFlags.None);\r\n            _bindingManager.Report();\r\n\r\n            AddTabView(\"Types\", DrawView_Types);\r\n            AddTabView(\"Codegen\", DrawView_Codegen);\r\n            AddTabView(\"Type Cast Registry\", DrawView_TypeCastRegistry);\r\n            AddTabView(\"Scripting\", DrawView_Scripting);\r\n            OnDirtyStateChanged();\r\n        }\r\n\r\n        public void MarkAsDirty()\r\n        {\r\n            if (!_dirty)\r\n            {\r\n                _dirty = true;\r\n                OnDirtyStateChanged();\r\n                // EditorApplication.delayCall += Save;\r\n            }\r\n        }\r\n\r\n        public void Save()\r\n        {\r\n            if (_dirty)\r\n            {\r\n                _dirty = false;\r\n                OnDirtyStateChanged();\r\n                try\r\n                {\r\n                    var isNewFile = !File.Exists(Prefs.PATH);\r\n                    var json = JsonUtility.ToJson(_prefs, true);\r\n                    System.IO.File.WriteAllText(Prefs.PATH, json);\r\n                    _prefs.filePath = Prefs.PATH;\r\n                    Debug.LogFormat(\"saved {0}\", Prefs.PATH);\r\n                }\r\n                catch (Exception exception)\r\n                {\r\n                    Debug.LogWarning(exception);\r\n                }\r\n            }\r\n        }\r\n\r\n        private void OnDirtyStateChanged()\r\n        {\r\n            titleContent = new GUIContent(\"JS Bridge Prefs\" + (_dirty ? \" *\" : \"\"));\r\n        }\r\n\r\n        private void OnDrawItem(Rect rect, Type type)\r\n        {\r\n            GUI.Label(rect, type.FullName);\r\n        }\r\n\r\n        private void DrawView_Scripting()\r\n        {\r\n            Block(\"Basic\", () =>\r\n            {\r\n                EditorGUI.BeginChangeCheck();\r\n                _prefs.editorScripting = EditorGUILayout.Toggle(\"Editor Scripting\", _prefs.editorScripting);\r\n                var selectedBindingMethod_t = EditorGUILayout.Popup(\"Binding Method\", _selectedBindingMethod, _bindingMethodDescriptions);\r\n                if (_selectedBindingMethod != selectedBindingMethod_t)\r\n                {\r\n                    _selectedBindingMethod = selectedBindingMethod_t;\r\n                    _prefs.preferredBindingMethod = _bindingMethodValues[Mathf.Clamp(_selectedBindingMethod, 0, _bindingMethodValues.Length - 1)];\r\n                }\r\n                if (!CodeGenUtils.IsCodeEmitSupported() && _prefs.preferredBindingMethod == _bindingMethodValues[0])\r\n                {\r\n                    EditorGUILayout.HelpBox(CodeGenUtils.CodeEmitWarning, MessageType.Warning);\r\n                }\r\n                _prefs.typescriptExt = EditorGUILayout.TextField(\"Typescript Ext\", _prefs.typescriptExt);\r\n                _prefs.sourceDir = EditorGUILayout.TextField(\"Source Dir\", _prefs.sourceDir);\r\n\r\n                if (EditorGUI.EndChangeCheck())\r\n                {\r\n                    MarkAsDirty();\r\n                }\r\n            });\r\n\r\n            Block(\"Editor Scripts\", () =>\r\n            {\r\n                EditorGUI.BeginChangeCheck();\r\n                _prefs.editorEntryPoint = EditorGUILayout.TextField(\"Entry Point\", _prefs.editorEntryPoint);\r\n                _prefs.editorDecoratorScript = EditorGUILayout.TextField(\"Decorator Definition\", _prefs.editorDecoratorScript);\r\n\r\n                if (EditorGUI.EndChangeCheck())\r\n                {\r\n                    MarkAsDirty();\r\n                }\r\n            });\r\n\r\n            Block(\"Preloaded Modules\", () =>\r\n            {\r\n                if (_prefs.editorRequires == null)\r\n                {\r\n                    _prefs.editorRequires = new List<string>();\r\n                }\r\n\r\n                var count = _prefs.editorRequires.Count;\r\n                for (var i = 0; i < count;)\r\n                {\r\n                    EditorGUILayout.BeginHorizontal();\r\n                    var do_delete = GUILayout.Button(\"X\", GUILayout.Width(22f));\r\n                    var mod_old = _prefs.editorRequires[i] ?? string.Empty;\r\n                    var mod_new = EditorGUILayout.TextField(mod_old);\r\n                    EditorGUILayout.EndHorizontal();\r\n\r\n                    if (do_delete)\r\n                    {\r\n                        --count;\r\n                        continue;\r\n                    }\r\n\r\n                    if (mod_new != mod_old)\r\n                    {\r\n                        _prefs.editorRequires[i] = mod_new;\r\n                        MarkAsDirty();\r\n                    }\r\n                    ++i;\r\n                }\r\n            }, () =>\r\n            {\r\n                if (GUILayout.Button(\"+\", GUILayout.Width(22f)))\r\n                {\r\n                    _prefs.editorRequires.Add(\"\");\r\n                    MarkAsDirty();\r\n                }\r\n            });\r\n\r\n            Block(\"AssetPost Processors\", () =>\r\n            {\r\n                if (_prefs.assetPostProcessors == null)\r\n                {\r\n                    _prefs.assetPostProcessors = new List<string>();\r\n                }\r\n\r\n                foreach (var assetPostProcessor in _prefs.assetPostProcessors)\r\n                {\r\n                    EditorGUILayout.TextField(assetPostProcessor);\r\n                }\r\n            }, () =>\r\n            {\r\n                if (GUILayout.Button(\"+\", GUILayout.Width(22f)))\r\n                {\r\n                    _prefs.assetPostProcessors.Add(\"\");\r\n                    MarkAsDirty();\r\n                }\r\n            });\r\n        }\r\n\r\n        private string RepeatString(string v, int repeat)\r\n        {\r\n            while (_repeatStringCache.Count < repeat + 1)\r\n            {\r\n                _repeatStringCache.Add(_repeatStringCache[_repeatStringCache.Count - 1] + v);\r\n            }\r\n            return _repeatStringCache[repeat];\r\n        }\r\n\r\n        private string Popup(string label, string value, string[] names, string[] values)\r\n        {\r\n            var newlineIndex = Array.IndexOf(values, value);\r\n            var newlineIndex_t = EditorGUILayout.Popup(label, newlineIndex, names);\r\n            if (newlineIndex_t != newlineIndex && newlineIndex_t >= 0)\r\n            {\r\n                return values[newlineIndex_t];\r\n            }\r\n            return value;\r\n        }\r\n\r\n        private void DrawView_TypeCastRegistry()\r\n        {\r\n            //TODO jsb.editor/prefs: draw it as a tree\r\n            using (var scope = new EditorGUILayout.ScrollViewScope(_scrollPosition_TypeCastRegistry))\r\n            {\r\n                _scrollPosition_TypeCastRegistry = scope.scrollPosition;\r\n                Block(\"js_get: \" + Values._JSCastMap.Count, () =>\r\n                {\r\n                    foreach (var kv in Values._JSCastMap)\r\n                    {\r\n                        EditorGUILayout.TextField(string.Format(\"{0}: {1}\", _bindingManager.GetCSTypeFullName(kv.Value), _bindingManager.GetCSTypeFullName(kv.Key)));\r\n                    }\r\n                });\r\n\r\n                Block(\"js_rebind: \" + Values._JSRebindMap.Count, () =>\r\n                {\r\n                    foreach (var kv in Values._JSRebindMap)\r\n                    {\r\n                        EditorGUILayout.TextField(string.Format(\"{0}: {1}\", _bindingManager.GetCSTypeFullName(kv.Value), _bindingManager.GetCSTypeFullName(kv.Key)));\r\n                    }\r\n                });\r\n\r\n                Block(\"js_push: \" + Values._CSCastMap.Count, () =>\r\n                {\r\n                    foreach (var kv in Values._CSCastMap)\r\n                    {\r\n                        EditorGUILayout.TextField(string.Format(\"{0}: {1}\", _bindingManager.GetCSTypeFullName(kv.Value), _bindingManager.GetCSTypeFullName(kv.Key)));\r\n                    }\r\n                });\r\n\r\n                Block(\"js_new: \" + Values._JSNewMap.Count, () =>\r\n                {\r\n                    foreach (var kv in Values._JSNewMap)\r\n                    {\r\n                        EditorGUILayout.TextField(string.Format(\"{0}: {1}\", _bindingManager.GetCSTypeFullName(kv.Value), _bindingManager.GetCSTypeFullName(kv.Key)));\r\n                    }\r\n                });\r\n            }\r\n        }\r\n\r\n        private void DrawView_Codegen()\r\n        {\r\n            using (var scope = new EditorGUILayout.ScrollViewScope(_scrollPosition_Codegen))\r\n            {\r\n                EditorGUI.BeginChangeCheck();\r\n                _scrollPosition_Codegen = scope.scrollPosition;\r\n                Block(\"Binding Options\", () =>\r\n                {\r\n                    _prefs.optToString = EditorGUILayout.Toggle(\"Auto ToString\", _prefs.optToString);\r\n                    _prefs.enableOperatorOverloading = EditorGUILayout.Toggle(\"Operator Overloading\", _prefs.enableOperatorOverloading);\r\n                    _prefs.alwaysEmitOperatorMethod = EditorGUILayout.Toggle(\"Always Emit Operators\", _prefs.alwaysEmitOperatorMethod);\r\n                    _prefs.excludeObsoleteItems = EditorGUILayout.Toggle(\"Exclude Obsoleted\", _prefs.excludeObsoleteItems);\r\n                    _prefs.skipDelegateWithByRefParams = EditorGUILayout.Toggle(\"Omit ref param Delegates\", _prefs.skipDelegateWithByRefParams);\r\n                    _prefs.alwaysCheckArgType = EditorGUILayout.Toggle(\"Always check arg type\", _prefs.alwaysCheckArgType);\r\n                    _prefs.alwaysCheckArgc = EditorGUILayout.Toggle(\"Always check argc\", _prefs.alwaysCheckArgc);\r\n                    _prefs.typeBindingPrefix = EditorGUILayout.TextField(\"C# Binding Prefix\", _prefs.typeBindingPrefix);\r\n                    _prefs.ns = EditorGUILayout.TextField(\"C# Binding Namespace\", _prefs.ns);\r\n                    _prefs.outDir = EditorGUILayout.TextField(\"Output Dir\", _prefs.outDir);\r\n                    _prefs.genTypescriptDoc = EditorGUILayout.Toggle(\"Gen d.ts\", _prefs.genTypescriptDoc);\r\n                    _prefs.xmlDocDir = EditorGUILayout.TextField(\"XmlDoc Dir\", _prefs.xmlDocDir);\r\n                    _prefs.typescriptDir = EditorGUILayout.TextField(\"d.ts Output Dir\", _prefs.typescriptDir);\r\n                    _prefs.jsModulePackInfoPath = EditorGUILayout.TextField(\"JS Module List\", _prefs.jsModulePackInfoPath);\r\n                });\r\n\r\n                Block(\"Code Style\", () =>\r\n                {\r\n                    _prefs.tsdSizeThreshold = EditorGUILayout.IntField(\"TSD Slice Size\", _prefs.tsdSizeThreshold);\r\n                    _prefs.tab = RepeatString(\" \", EditorGUILayout.IntSlider(\"Tab Size\", _prefs.tab.Length, 0, 8));\r\n                    _prefs.newLineStyle = Popup(\"Newline Style\", _prefs.newLineStyle, _newlineNames, _newlineValues);\r\n                    _prefs.moduleStyle = Popup(\"Module Style\", _prefs.moduleStyle, _moduleStyleNames, _moduleStyleValues);\r\n                    var moduleStyle = _prefs.GetModuleStyle();\r\n                    EditorGUI.BeginDisabledGroup(moduleStyle != ETSModuleStyle.Legacy);\r\n                    _prefs.defaultJSModule = EditorGUILayout.TextField(\"Default Module\", _prefs.defaultJSModule);\r\n                    EditorGUI.EndDisabledGroup();\r\n                    EditorGUI.BeginDisabledGroup(moduleStyle != ETSModuleStyle.Singular);\r\n                    _prefs.singularModuleName = EditorGUILayout.TextField(\"Singular Module\", _prefs.singularModuleName);\r\n                    EditorGUI.EndDisabledGroup();\r\n                });\r\n\r\n                Block(\"Advanced (Experimental)\", () =>\r\n                {\r\n                    _prefs.randomizedBindingCode = EditorGUILayout.Toggle(\"Obfuscate\", _prefs.randomizedBindingCode);\r\n                });\r\n\r\n                Block(\"Custom Binding Process\", () =>\r\n                {\r\n                    var list = _bindingManager.GetBindingProcessTypes();\r\n                    for (int i = 0, count = list.Count; i < count; ++i)\r\n                    {\r\n                        var process = list[i];\r\n                        var name = process.FullName;\r\n                        var enabled = !_prefs.skipBinding.Contains(name);\r\n                        var state = EditorGUILayout.ToggleLeft(name, enabled);\r\n                        if (state != enabled)\r\n                        {\r\n                            if (state)\r\n                            {\r\n                                _prefs.skipBinding.Remove(name);\r\n                            }\r\n                            else\r\n                            {\r\n                                _prefs.skipBinding.Add(name);\r\n                            }\r\n                            MarkAsDirty();\r\n                        } // end if: enabled\r\n                    } // end for: list\r\n                }); // end block: custom binding process\r\n\r\n                Block(\"Diagnostics\", () =>\r\n                {\r\n                    _prefs.debugCodegen = EditorGUILayout.Toggle(\"Debug Codegen\", _prefs.debugCodegen);\r\n                    _prefs.verboseLog = EditorGUILayout.Toggle(\"Verbose Log\", _prefs.verboseLog);\r\n                    _prefs.logPath = EditorGUILayout.TextField(\"Log\", _prefs.logPath);\r\n                });\r\n\r\n                if (EditorGUI.EndChangeCheck())\r\n                {\r\n                    MarkAsDirty();\r\n                }\r\n            }\r\n        }\r\n\r\n        private void DrawView_Types()\r\n        {\r\n            var y = 90f;\r\n            _typesViewRect.Set(0f, y, position.width, position.height - y);\r\n            var repaint = _splitView.Draw(_typesViewRect);\r\n\r\n            _typesViewRect.Set(0f, y, _splitView.cursorChangeRect.x, position.height - y);\r\n            GUILayout.BeginArea(_typesViewRect);\r\n            DrawView_Types_Left();\r\n            GUILayout.EndArea();\r\n\r\n            _typesViewRect.Set(_splitView.cursorChangeRect.xMax, y, position.width - _splitView.cursorChangeRect.x, position.height - y);\r\n            GUILayout.BeginArea(_typesViewRect);\r\n            DrawView_Types_Right();\r\n            GUILayout.EndArea();\r\n\r\n            if (repaint)\r\n            {\r\n                Repaint();\r\n            }\r\n        }\r\n\r\n        private void DrawView_Types_Right()\r\n        {\r\n            _activeView?.Draw(this);\r\n        }\r\n\r\n        private System.Collections.IEnumerator ConstructTypeTree()\r\n        {\r\n            var assemblyList = AppDomain.CurrentDomain.GetAssemblies();\r\n            Array.Sort<Assembly>(assemblyList, (a, b) => string.Compare(a.FullName, b.FullName, true));\r\n            List<Tuple<Assembly, Type[]>> aTypes = new List<Tuple<Assembly, Type[]>>(assemblyList.Length);\r\n            foreach (var assembly in assemblyList)\r\n            {\r\n                if (!assembly.IsDynamic)\r\n                {\r\n                    var types = assembly.GetExportedTypes();\r\n                    aTypes.Add(new Tuple<Assembly, Type[]>(assembly, types));\r\n                    _typeTreeConstructAll += types.Length;\r\n                }\r\n            }\r\n\r\n            for (int i = 0, count = aTypes.Count; i < count; i++)\r\n            {\r\n                var tuple = aTypes[i];\r\n                var e = ConstructAssemblyNode(tuple.Item1, tuple.Item2);\r\n                while (e.MoveNext())\r\n                {\r\n                    yield return null;\r\n                }\r\n\r\n                _treeView.Invalidate();\r\n            }\r\n            _typeTreeConstruct = null;\r\n        }\r\n\r\n        private void DrawView_Types_Left()\r\n        {\r\n            if (_searchField == null)\r\n            {\r\n                if (_typeTreeConstruct == null)\r\n                {\r\n                    _typeTreeConstruct = ConstructTypeTree();\r\n                }\r\n                _treeView.OnSelectItem = OnSelectTreeViewItem;\r\n                _listView.OnDrawItem = (rect, index, node) => GUI.Label(rect, node.FullName, EditorStyles.label);\r\n                _listView.OnSelectItem = OnSelectListViewItem;\r\n                _searchField = new SearchField();\r\n                _searchField.autoSetFocusOnFindCommand = true;\r\n            }\r\n\r\n            var searchFieldRect = EditorGUILayout.GetControlRect();\r\n            var searchString = _searchField.OnGUI(searchFieldRect, _lastSearchString);\r\n            if (_lastSearchString != searchString)\r\n            {\r\n                _lastSearchString = searchString;\r\n                _listView.Clear();\r\n                if (!string.IsNullOrEmpty(_lastSearchString))\r\n                {\r\n                    foreach (var t in _typeNodes)\r\n                    {\r\n                        if (t.MatchString(_lastSearchString))\r\n                        {\r\n                            _listView.Add(t);\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            if (_footStyle == null)\r\n            {\r\n                _footStyle = new GUIStyle(EditorStyles.miniLabel);\r\n                _footStyle.alignment = TextAnchor.MiddleRight;\r\n            }\r\n\r\n            var typesViewRect = EditorGUILayout.GetControlRect(GUILayout.ExpandHeight(true));\r\n            var pendingHint = string.Empty;\r\n\r\n            if (_typeTreeConstruct != null)\r\n            {\r\n                pendingHint = $\"(Loading... {ToPercent((float)_typeTreeConstructWalk / _typeTreeConstructAll)}%) \";\r\n                Repaint();\r\n            }\r\n\r\n            if (string.IsNullOrEmpty(_lastSearchString))\r\n            {\r\n                if (_treeView.Draw(typesViewRect))\r\n                {\r\n                    Repaint();\r\n                }\r\n                GUILayout.Label($\"{pendingHint}{_typeNodes.Count} Types\", _footStyle);\r\n            }\r\n            else\r\n            {\r\n                _listView.Draw(typesViewRect);\r\n                GUILayout.Label($\"{pendingHint}{_listView.Count} Types\", _footStyle);\r\n            }\r\n        }\r\n\r\n        private static int ToPercent(float p)\r\n        {\r\n            return Mathf.FloorToInt(p * 100f);\r\n        }\r\n\r\n        private T SetActiveView<T>()\r\n        where T : IView, new()\r\n        {\r\n            Repaint();\r\n\r\n            foreach (var view in _allViews)\r\n            {\r\n                if (view.GetType() == typeof(T))\r\n                {\r\n                    _activeView = view;\r\n                    return (T)view;\r\n                }\r\n            }\r\n\r\n            var newView = new T();\r\n            _allViews.Add(newView);\r\n            _activeView = newView;\r\n\r\n            return newView;\r\n        }\r\n\r\n        private void OnSelectTreeViewItem(SimpleTreeView.INode item, HashSet<SimpleTreeView.INode> selection)\r\n        {\r\n            if (item is Assembly_TreeViewNode)\r\n            {\r\n                Defer(() => SetActiveView<AssemblyInfoView>().Show((item as Assembly_TreeViewNode).value));\r\n            }\r\n            else if (item is Type_TreeViewNode)\r\n            {\r\n                Defer(() => SetActiveView<TypeInfoView>().Show((item as Type_TreeViewNode).value));\r\n            }\r\n            else if (item is Namespace_TreeViewNode)\r\n            {\r\n                Defer(() => SetActiveView<NamespaceInfoView>().Show((item as Namespace_TreeViewNode).value));\r\n            }\r\n            else\r\n            {\r\n                Defer(() => SetActiveView<NoneView>());\r\n            }\r\n            Repaint();\r\n        }\r\n\r\n        private void OnSelectListViewItem(Type_TreeViewNode item, HashSet<Type_TreeViewNode> selection)\r\n        {\r\n            _treeView.Select(item);\r\n            Defer(() => SetActiveView<TypeInfoView>().Show(item.value));\r\n            Repaint();\r\n        }\r\n\r\n        protected override void OnUpdate()\r\n        {\r\n            var cycle = 5;\r\n            while (_typeTreeConstruct != null && --cycle > 0)\r\n            {\r\n                _typeTreeConstruct.MoveNext();\r\n            }\r\n        }\r\n\r\n        protected override void OnPaint()\r\n        {\r\n            EditorGUILayout.BeginHorizontal();\r\n            EditorGUI.BeginDisabledGroup(!_dirty);\r\n            if (GUILayout.Button(\"Save\", EditorStyles.miniButton, GUILayout.Width(46f)))\r\n            {\r\n                Save();\r\n            }\r\n            EditorGUI.EndDisabledGroup();\r\n            EditorGUILayout.EndHorizontal();\r\n            var fileType = string.IsNullOrEmpty(_prefs.filePath) ? \"in memory\" : \"from file\";\r\n            EditorGUILayout.HelpBox($\"(experimental) Editor for {Prefs.PATH} ({fileType})\", MessageType.Warning);\r\n\r\n            _selectedTabViewIndex = GUILayout.Toolbar(_selectedTabViewIndex, _tabViewNames);\r\n            _tabViewDrawers[_selectedTabViewIndex]();\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/PrefsEditor.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 5f02c64b59b6a0d4ab946e82c9673fb0\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/PrefsLoader.cs",
    "content": "#if !JSB_UNITYLESS\nusing System;\nusing System.IO;\n\nnamespace QuickJS.Unity\n{\n    using UnityEngine;\n    using UnityEditor;\n    using QuickJS.Binding;\n\n    public class PrefsLoader\n    {\n        private static PrefsLoader _loader;\n\n        public static Action<Prefs> prefsChanged;\n\n        private FileSystemWatcher _prefsWatcher;\n        private float _changedFileInterval;\n        private int _changedEvent;\n\n        private Prefs _prefs;\n\n        public static Prefs CurrentPrefs { get { return GetInstance()._prefs; } }\n\n        public static PrefsLoader GetInstance()\n        {\n            if (_loader == null)\n            {\n                _loader = new PrefsLoader();\n                _loader.Initialize();\n            }\n            return _loader;\n        }\n\n        private PrefsLoader()\n        {\n        }\n\n        private static Prefs LoadPrefs()\n        {\n            string filePath;\n            return LoadPrefs(out filePath);\n        }\n\n        private static Prefs LoadPrefs(out string filePath)\n        {\n            if (File.Exists(Prefs.PATH))\n            {\n                try\n                {\n                    var json = Utils.TextUtils.NormalizeJson(File.ReadAllText(Prefs.PATH));\n                    Debug.Log($\"load prefs({Prefs.PATH}): {json}\");\n                    var prefs = JsonUtility.FromJson<Prefs>(json);\n                    filePath = Prefs.PATH;\n                    prefs.filePath = filePath;\n                    if (string.IsNullOrEmpty(prefs.typescriptDir))\n                    {\n                        prefs.typescriptDir = prefs.outDir;\n                    }\n                    return prefs;\n                }\n                catch (Exception exception)\n                {\n                    Debug.LogWarning(exception);\n                }\n            }\n            Debug.Log($\"load prefs in memory\");\n            var defaultPrefs = new Prefs();\n            filePath = Prefs.PATH;\n            return defaultPrefs;\n        }\n\n        private void Initialize()\n        {\n            _prefs = LoadPrefs();\n            _prefsWatcher = new FileSystemWatcher(\".\", Prefs.PATH);\n            _prefsWatcher.Changed += OnFileChanged;\n            _prefsWatcher.Created += OnFileChanged;\n            _prefsWatcher.Deleted += OnFileChanged;\n            _prefsWatcher.EnableRaisingEvents = true;\n            EditorApplication.update += OnPrefsSync;\n        }\n\n        private void OnPrefsSync()\n        {\n            if (!UnityHelper.IsApplicationActive())\n            {\n                return;\n            }\n\n            _changedFileInterval += Time.realtimeSinceStartup;\n            if (_changedFileInterval < 3f)\n            {\n                return;\n            }\n\n            _changedFileInterval = 0f;\n            if (System.Threading.Interlocked.Exchange(ref _changedEvent, 0) > 0)\n            {\n                _prefs = LoadPrefs();\n                try\n                {\n                    prefsChanged?.Invoke(_prefs);\n                }\n                catch (Exception exception)\n                {\n                    Debug.LogErrorFormat(\"OnPrefsChanged: {0}\\n{1}\", exception.Message, exception.StackTrace);\n                }\n            }\n        }\n\n        private void OnFileChanged(object sender, FileSystemEventArgs e)\n        {\n            var changedFile = e.FullPath;\n            var fullPath1 = Path.GetFullPath(changedFile);\n            var fullPath2 = Path.GetFullPath(Prefs.PATH);\n\n            if (string.Compare(fullPath1, fullPath2, true) == 0)\n            {\n                System.Threading.Interlocked.Exchange(ref _changedEvent, 1);\n            }\n        }\n    }\n}\n#endif // !JSB_UNITYLESS"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/PrefsLoader.cs.meta",
    "content": "fileFormatVersion: 2\nguid: d94e1e1811cd345da8876261d6cbd08b\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/ScriptEditorWindowLauncher.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using UnityEngine;\r\n    using UnityEditor;\r\n\r\n    /// <summary>\r\n    /// ScriptEditorWindowLauncher is an experimental unfinished feature. \r\n    /// it could be used to open editor windows implemented in typescript, \r\n    /// we need this because there is no open api in Unity to dynamically create menu item at the moment.\r\n    /// </summary>\r\n    public class ScriptEditorWindowLauncher : BaseEditorWindow, IHasCustomMenu\r\n    {\r\n        [Serializable]\r\n        public enum ListMode\r\n        {\r\n            Icons,\r\n            List,\r\n        }\r\n        private const JSScriptClassType classTypes =\r\n            JSScriptClassType.EditorWindow |\r\n            JSScriptClassType.CustomEditor |\r\n            JSScriptClassType.MonoBehaviour |\r\n            JSScriptClassType.ScriptableObject;\r\n\r\n        private GUIContent _scriptIcon;\r\n        private GUIContent _InspectorIcon;\r\n        private GUIContent _EditorWindowIcon;\r\n        private GUIContent _ScriptableObjectIcon;\r\n        private GUIContent _MonoBehaviourIcon;\r\n        private Vector2 _scriptListViewScrollPosition;\r\n        private List<JSScriptClassPathHint> _scriptClassPaths;\r\n        private GUIStyle _footStyle;\r\n\r\n        [SerializeField]\r\n        private ListMode _listMode;\r\n\r\n        void Awake()\r\n        {\r\n            _scriptIcon = new GUIContent(UnityHelper.LoadPackageAsset<Texture>(\"Editor/Icons/JsScript.png\"));\r\n            _InspectorIcon = new GUIContent(UnityHelper.LoadPackageAsset<Texture>(\"Editor/Icons/InspectorIcon.png\"));\r\n            _EditorWindowIcon = new GUIContent(UnityHelper.LoadPackageAsset<Texture>(\"Editor/Icons/EditorWindowIcon.png\"));\r\n            _ScriptableObjectIcon = new GUIContent(UnityHelper.LoadPackageAsset<Texture>(\"Editor/Icons/ScriptableObjectIcon.png\"));\r\n            _MonoBehaviourIcon = new GUIContent(UnityHelper.LoadPackageAsset<Texture>(\"Editor/Icons/MonoBehaviourIcon.png\"));\r\n            Reset();\r\n        }\r\n\r\n        void OnDestroy()\r\n        {\r\n            JSScriptFinder.GetInstance().ScriptClassPathsUpdated -= OnScriptClassPathsUpdated;\r\n        }\r\n\r\n        protected override void OnEnable()\r\n        {\r\n            base.OnEnable();\r\n            titleContent = new GUIContent(\"Launchpad\", _scriptIcon.image);\r\n        }\r\n\r\n        private void OnScriptClassPathsUpdated()\r\n        {\r\n            _scriptClassPaths.Clear();\r\n            JSScriptFinder.GetInstance().Search(classTypes, _scriptClassPaths);\r\n        }\r\n\r\n        private GUIContent GetIcon(JSScriptClassType type)\r\n        {\r\n            switch (type)\r\n            {\r\n                case JSScriptClassType.CustomEditor: return _InspectorIcon;\r\n                case JSScriptClassType.MonoBehaviour: return _MonoBehaviourIcon;\r\n                case JSScriptClassType.EditorWindow: return _EditorWindowIcon;\r\n                case JSScriptClassType.ScriptableObject: return _ScriptableObjectIcon;\r\n                default: return _scriptIcon;\r\n            }\r\n        }\r\n\r\n        private void DrawScriptItemAsIcon(Rect rect, JSScriptClassPathHint classPath)\r\n        {\r\n            var labelHeight = Math.Min(EditorStyles.label.lineHeight, rect.height);\r\n            var padding = 4f;\r\n            var buttonSize = rect.height - labelHeight - padding;\r\n\r\n            if (buttonSize > 8f)\r\n            {\r\n                var buttonRect = new Rect(rect.x + (rect.width - buttonSize) * .5f, rect.y, buttonSize, buttonSize);\r\n\r\n                if (classPath.classType != JSScriptClassType.EditorWindow || !PrefsLoader.CurrentPrefs.editorScripting)\r\n                {\r\n                    GUI.DrawTexture(buttonRect, GetIcon(classPath.classType).image);\r\n                }\r\n                else\r\n                {\r\n                    if (GUI.Button(buttonRect, GetIcon(classPath.classType)))\r\n                    {\r\n                        EditorRuntime.ShowWindow(classPath.modulePath, classPath.className);\r\n                    }\r\n                }\r\n\r\n                var labelRect = new Rect(rect.x, rect.yMax - labelHeight, rect.width, labelHeight);\r\n                EditorGUI.LabelField(labelRect, classPath.className, EditorStyles.centeredGreyMiniLabel);\r\n            }\r\n            else\r\n            {\r\n                if (GUI.Button(rect, classPath.className))\r\n                {\r\n                    EditorRuntime.ShowWindow(classPath.modulePath, classPath.className);\r\n                }\r\n            }\r\n        }\r\n\r\n        private void DrawScriptItemAsListEntry(Rect rect, JSScriptClassPathHint classPath)\r\n        {\r\n            var texRect = new Rect(rect.x, rect.y, EditorGUIUtility.singleLineHeight, EditorGUIUtility.singleLineHeight);\r\n            GUI.DrawTexture(texRect, GetIcon(classPath.classType).image);\r\n            if (classPath.classType == JSScriptClassType.EditorWindow)\r\n            {\r\n                var buttonRect = new Rect(rect.xMax - 52f, rect.y, 52f, rect.height);\r\n                var labelRect = new Rect(texRect.xMax + 4f, rect.y, rect.width - texRect.xMax - 4f - buttonRect.width, EditorGUIUtility.singleLineHeight);\r\n                GUI.Label(labelRect, classPath.className);\r\n                if (GUI.Button(buttonRect, \"Show\"))\r\n                {\r\n                    EditorRuntime.ShowWindow(classPath.modulePath, classPath.className);\r\n                }\r\n            }\r\n            else\r\n            {\r\n                var labelRect = new Rect(texRect.xMax + 4f, rect.y, rect.width - texRect.xMax - 4f, EditorGUIUtility.singleLineHeight);\r\n                GUI.Label(labelRect, classPath.className);\r\n            }\r\n        }\r\n\r\n        private void Reset()\r\n        {\r\n            JSScriptFinder.GetInstance().ScriptClassPathsUpdated -= OnScriptClassPathsUpdated;\r\n            JSScriptFinder.GetInstance().ScriptClassPathsUpdated += OnScriptClassPathsUpdated;\r\n            _scriptClassPaths = new List<JSScriptClassPathHint>();\r\n            OnScriptClassPathsUpdated();\r\n        }\r\n\r\n        public void AddItemsToMenu(GenericMenu menu)\r\n        {\r\n            menu.AddItem(new GUIContent(\"Show as Icons\"), _listMode == ListMode.Icons, () => _listMode = ListMode.Icons);\r\n            menu.AddItem(new GUIContent(\"Show as List\"), _listMode == ListMode.List, () => _listMode = ListMode.List);\r\n        }\r\n\r\n        private void DrawScriptListView()\r\n        {\r\n            _scriptListViewScrollPosition = EditorGUILayout.BeginScrollView(_scriptListViewScrollPosition);\r\n            var size = _scriptClassPaths.Count;\r\n            GUILayout.Space(6f);\r\n            if (_listMode == ListMode.Icons)\r\n            {\r\n                var itemSize = new Vector2(120f, 80f);\r\n                var rowRect = EditorGUILayout.GetControlRect(GUILayout.Height(itemSize.y));\r\n                var rows = 0;\r\n                var itemRect = new Rect(rowRect.x, rowRect.y, itemSize.x, itemSize.y);\r\n                for (var i = 0; i < size; i++)\r\n                {\r\n                    var item = _scriptClassPaths[i];\r\n\r\n                    DrawScriptItemAsIcon(itemRect, item);\r\n                    itemRect.x += itemSize.x;\r\n                    if (i != size - 1 && itemRect.xMax > position.width)\r\n                    {\r\n                        itemRect.x = rowRect.x;\r\n                        itemRect.y += itemSize.y;\r\n                        ++rows;\r\n                    }\r\n                }\r\n                EditorGUILayout.GetControlRect(GUILayout.Height(rows * itemSize.y));\r\n            }\r\n            else\r\n            {\r\n                for (var i = 0; i < size; i++)\r\n                {\r\n                    var item = _scriptClassPaths[i];\r\n                    var itemRect = EditorGUILayout.GetControlRect();\r\n                    if (i % 2 == 0)\r\n                    {\r\n                        EditorGUI.DrawRect(itemRect, UnityHelper.RowColor);\r\n                    }\r\n                    DrawScriptItemAsListEntry(itemRect, item);\r\n                }\r\n            }\r\n            EditorGUILayout.EndScrollView();\r\n\r\n            if (_footStyle == null)\r\n            {\r\n                _footStyle = new GUIStyle(EditorStyles.miniLabel);\r\n                _footStyle.alignment = TextAnchor.MiddleRight;\r\n            }\r\n            if (size > 1)\r\n            {\r\n                if (PrefsLoader.CurrentPrefs.editorScripting)\r\n                {\r\n                    GUILayout.Label(size + \" Scripts | EditorScripting: enabled\", _footStyle);\r\n                }\r\n                else\r\n                {\r\n                    GUILayout.Label(size + \" Scripts | EditorScripting: disabled\", _footStyle);\r\n                }\r\n            }\r\n        }\r\n\r\n        protected override void OnPaint()\r\n        {\r\n            if (_scriptClassPaths == null)\r\n            {\r\n                Reset();\r\n            }\r\n\r\n            // _selectedTabViewIndex = GUILayout.Toolbar(_selectedTabViewIndex, _tabViews);\r\n            // GUILayout.Space(12f);\r\n            DrawScriptListView();\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/ScriptEditorWindowLauncher.cs.meta",
    "content": "fileFormatVersion: 2\nguid: eddfb1a522315a94683ede96d3b9b9af\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/ScriptEngineStatsWindow.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Linq;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using UnityEngine;\r\n    using UnityEditor;\r\n    using System.Threading;\r\n\r\n    public class ScriptEngineStatsWindow : BaseEditorWindow, IHasCustomMenu\r\n    {\r\n        private static readonly string[] _backends = { \"quickjs\", \"v8-bridge\" };\r\n        private static GUIContent GUIContent_Stats_Operator = new GUIContent(\"Operator\", \"Is operator overloading supported?\");\r\n\r\n        private int _categoryIndex;\r\n        private string[] _categoryLabels;\r\n        private Action<Snapshot>[] _categoryDrawers;\r\n\r\n        private class Snapshot\r\n        {\r\n            public int id;\r\n            public bool alive;\r\n\r\n            public Native.JSMemoryUsage memoryUsage;\r\n            public bool isStaticBinding;\r\n            public int exportedTypes;\r\n            public int managedObjectCount;\r\n            public int managedObjectCap;\r\n            public bool fetchManagedObjectRefs;\r\n            public int selectedManagedObjectIndex;\r\n            // public List<WeakReference<object>> managedObjectRefs = new List<WeakReference<object>>();\r\n            public SimpleListView<WeakReference<object>> managedObjectRefs = new SimpleListView<WeakReference<object>>();\r\n            public int jsObjectCount;\r\n            public int delegateCount;\r\n            public int scriptValueCount;\r\n            // public int scriptPromiseCount;\r\n            public int stringCount;\r\n            public int timeNow;\r\n            public List<Utils.TimerInfo> activeTimers = new List<Utils.TimerInfo>();\r\n        }\r\n\r\n        private Vector2 _sv;\r\n        private int _alive;\r\n\r\n        [SerializeField]\r\n        private bool _fetchManagedObjectRefs = false;\r\n\r\n        [SerializeField]\r\n        private bool _autoCap = true;\r\n\r\n        private float _time;\r\n\r\n        [SerializeField]\r\n        private float _timeCap = 5f;\r\n        private List<Snapshot> _snapshots = new List<Snapshot>();\r\n        private string[] _snapshotNames = new string[] { };\r\n        private int _selectedSnapshotIndex;\r\n\r\n        [MenuItem(\"JS Bridge/Stats Viewer\", false, 5000)]\r\n        static void OpenThis()\r\n        {\r\n            GetWindow<ScriptEngineStatsWindow>().Show();\r\n        }\r\n\r\n        protected override void OnEnable()\r\n        {\r\n            base.OnEnable();\r\n            _categoryLabels = new string[] { \"Statistics\", \"Managed Objects\", \"Timers\" };\r\n            _categoryDrawers = new Action<Snapshot>[] { OnStatisticsGUI, OnManagedObjectsGUI, OnTimersGUI };\r\n            _categoryIndex = Math.Min(_categoryIndex, _categoryLabels.Length - 1);\r\n\r\n            titleContent = new GUIContent(\"ScriptEngine Stats\");\r\n            _time = Time.realtimeSinceStartup;\r\n            CaptureAll();\r\n        }\r\n\r\n        protected override void OnDisable()\r\n        {\r\n            base.OnDisable();\r\n        }\r\n\r\n        string ToSizeText(long size)\r\n        {\r\n            if (size > 1024 * 1024 * 2)\r\n            {\r\n                return string.Format(\"{0:.0} MB\", (float)size / 1024f / 1024f);\r\n            }\r\n            else if (size > 1024 * 2)\r\n            {\r\n                return string.Format(\"{0:.0} KB\", (float)size / 1024f);\r\n            }\r\n            return string.Format(\"{0} B\", (int)size);\r\n        }\r\n\r\n        string ToCountText(long size)\r\n        {\r\n            return size.ToString();\r\n        }\r\n\r\n        private void GarbadgeCollect()\r\n        {\r\n            GC.Collect();\r\n            GC.WaitForPendingFinalizers();\r\n        }\r\n\r\n        public void AddItemsToMenu(GenericMenu menu)\r\n        {\r\n            menu.AddItem(new GUIContent(\"JS Launcher\"), false, () => GetWindow<ScriptEditorWindowLauncher>().Show());\r\n            menu.AddItem(new GUIContent(\"Prefs\"), false, () => GetWindow<PrefsEditor>().Show());\r\n            menu.AddSeparator(\"\");\r\n            menu.AddItem(new GUIContent(\"Capture\"), false, () => CaptureAll());\r\n            menu.AddItem(new GUIContent(\"GC (mono)\"), false, () => GarbadgeCollect());\r\n            menu.AddItem(new GUIContent(\"Reload EditorScripting\"), false, () => EditorRuntime.GetInstance()?.Reload());\r\n#if UNITY_2019_4_OR_NEWER\r\n            menu.AddItem(new GUIContent(\"Reload CSharp\"), false, () => UnityEditor.Compilation.CompilationPipeline.RequestScriptCompilation());\r\n#endif\r\n        }\r\n\r\n        private Snapshot GetSnapshot(int id)\r\n        {\r\n            for (int i = 0, count = _snapshots.Count; i < count; i++)\r\n            {\r\n                var snapshot = _snapshots[i];\r\n                if (snapshot.id == id)\r\n                {\r\n                    return snapshot;\r\n                }\r\n            }\r\n            var inst = new Snapshot();\r\n            inst.id = id;\r\n            ArrayUtility.Add(ref _snapshotNames, id.ToString());\r\n            _snapshots.Add(inst);\r\n            return inst;\r\n        }\r\n\r\n        private void Capture(ScriptRuntime runtime)\r\n        {\r\n            if (!runtime.isValid)\r\n            {\r\n                return;\r\n            }\r\n\r\n            var snapshot = GetSnapshot(runtime.id);\r\n            snapshot.alive = true;\r\n            snapshot.fetchManagedObjectRefs = _fetchManagedObjectRefs;\r\n            runtime.EnqueueAction(OnSnapshotRequest, snapshot);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Callback runs on the script runtime thread\r\n        /// </summary>\r\n        private static void OnSnapshotRequest(ScriptRuntime runtime, object cbArgs, Native.JSValue cbValue)\r\n        {\r\n            if (!runtime.isValid || !runtime.isRunning)\r\n            {\r\n                return;\r\n            }\r\n\r\n            var snapshot = (Snapshot)cbArgs;\r\n            lock (snapshot)\r\n            {\r\n                unsafe\r\n                {\r\n                    fixed (Native.JSMemoryUsage* ptr = &snapshot.memoryUsage)\r\n                    {\r\n                        Native.JSApi.JS_ComputeMemoryUsage(runtime, ptr);\r\n                    }\r\n                }\r\n\r\n                var typeDB = runtime.GetTypeDB();\r\n                snapshot.exportedTypes = typeDB.Count;\r\n                snapshot.isStaticBinding = runtime.isStaticBinding;\r\n\r\n                var objectCache = runtime.GetObjectCache();\r\n                var stringCache = runtime.GetMainContext().GetStringCache();\r\n\r\n                snapshot.managedObjectCount = objectCache.GetManagedObjectCount();\r\n                snapshot.managedObjectCap = objectCache.GetManagedObjectCap();\r\n                snapshot.managedObjectRefs.Clear();\r\n                if (snapshot.fetchManagedObjectRefs)\r\n                {\r\n                    objectCache.ForEachManagedObject(obj =>\r\n                    {\r\n                        snapshot.managedObjectRefs.Add(new WeakReference<object>(obj));\r\n                    });\r\n                }\r\n                snapshot.selectedManagedObjectIndex = Math.Min(snapshot.selectedManagedObjectIndex, snapshot.managedObjectRefs.Count - 1);\r\n                snapshot.jsObjectCount = objectCache.GetJSObjectCount();\r\n                snapshot.delegateCount = objectCache.GetDelegateCount();\r\n                snapshot.scriptValueCount = objectCache.GetScriptValueCount();\r\n                // snapshot.scriptPromiseCount = objectCache.GetScriptPromiseCount();\r\n                snapshot.stringCount = stringCache.GetStringCount();\r\n\r\n                var timerManager = runtime.GetTimerManager();\r\n                snapshot.activeTimers.Clear();\r\n                snapshot.timeNow = timerManager.now;\r\n                foreach (var info in timerManager)\r\n                {\r\n                    snapshot.activeTimers.Add(info);\r\n                }\r\n            }\r\n        }\r\n\r\n        private string GetDescription(object obj)\r\n        {\r\n            try\r\n            {\r\n                return obj.ToString();\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                return \"[Error] \" + e.Message;\r\n            }\r\n        }\r\n\r\n        private void OnStatisticsGUI(Snapshot snapshot)\r\n        {\r\n            EditorGUILayout.BeginVertical();\r\n            Block(\"Misc.\", () =>\r\n            {\r\n                EditorGUILayout.Toggle(\"Static Bind\", snapshot.isStaticBinding);\r\n                EditorGUILayout.IntField(\"Exported Types\", snapshot.exportedTypes);\r\n                EditorGUILayout.TextField(\"ManagedObject\", snapshot.managedObjectCount + \"/\" + snapshot.managedObjectCap);\r\n                EditorGUILayout.IntField(\"JSObject\", snapshot.jsObjectCount);\r\n                EditorGUILayout.IntField(\"Delegate Mapping\", snapshot.delegateCount);\r\n                EditorGUILayout.IntField(\"Value Mapping\", snapshot.scriptValueCount);\r\n                // EditorGUILayout.IntField(\"ScriptPromise Mapping\", snapshot.scriptPromiseCount);\r\n                EditorGUILayout.IntField(\"Cached String\", snapshot.stringCount);\r\n            });\r\n            Block(\"Timers\", () =>\r\n            {\r\n                EditorGUILayout.IntField(\"Active Timer\", snapshot.activeTimers.Count);\r\n                EditorGUILayout.IntField(\"Now\", snapshot.timeNow);\r\n            });\r\n            Block(\"JSMemoryUsage\", () =>\r\n            {\r\n                EditorGUILayout.TextField(\"malloc_size\", ToSizeText(snapshot.memoryUsage.malloc_size));\r\n                EditorGUILayout.TextField(\"malloc_limit\", ToCountText(snapshot.memoryUsage.malloc_limit));\r\n                EditorGUILayout.TextField(\"memory_used_size\", ToSizeText(snapshot.memoryUsage.memory_used_size));\r\n                EditorGUILayout.TextField(\"malloc_count\", ToCountText(snapshot.memoryUsage.malloc_count));\r\n                EditorGUILayout.TextField(\"memory_used_count\", ToCountText(snapshot.memoryUsage.memory_used_count));\r\n                EditorGUILayout.TextField(\"atom_count\", ToCountText(snapshot.memoryUsage.atom_count));\r\n                EditorGUILayout.TextField(\"atom_size\", ToSizeText(snapshot.memoryUsage.atom_size));\r\n                EditorGUILayout.TextField(\"str_count\", ToCountText(snapshot.memoryUsage.str_count));\r\n                EditorGUILayout.TextField(\"str_size\", ToSizeText(snapshot.memoryUsage.str_size));\r\n                EditorGUILayout.TextField(\"obj_count\", ToCountText(snapshot.memoryUsage.obj_count));\r\n                EditorGUILayout.TextField(\"obj_size\", ToSizeText(snapshot.memoryUsage.obj_size));\r\n                EditorGUILayout.TextField(\"prop_count\", ToCountText(snapshot.memoryUsage.prop_count));\r\n                EditorGUILayout.TextField(\"prop_size\", ToSizeText(snapshot.memoryUsage.prop_size));\r\n                EditorGUILayout.TextField(\"shape_count\", ToCountText(snapshot.memoryUsage.shape_count));\r\n                EditorGUILayout.TextField(\"shape_size\", ToSizeText(snapshot.memoryUsage.shape_size));\r\n                EditorGUILayout.TextField(\"js_func_count\", ToCountText(snapshot.memoryUsage.js_func_count));\r\n                EditorGUILayout.TextField(\"js_func_size\", ToSizeText(snapshot.memoryUsage.js_func_size));\r\n                EditorGUILayout.TextField(\"js_func_code_size\", ToSizeText(snapshot.memoryUsage.js_func_code_size));\r\n                EditorGUILayout.TextField(\"js_func_pc2line_count\", ToCountText(snapshot.memoryUsage.js_func_pc2line_count));\r\n                EditorGUILayout.TextField(\"js_func_pc2line_size\", ToSizeText(snapshot.memoryUsage.js_func_pc2line_size));\r\n                EditorGUILayout.TextField(\"c_func_count\", ToCountText(snapshot.memoryUsage.c_func_count));\r\n                EditorGUILayout.TextField(\"array_count\", ToCountText(snapshot.memoryUsage.array_count));\r\n                EditorGUILayout.TextField(\"fast_array_count\", ToCountText(snapshot.memoryUsage.fast_array_count));\r\n                EditorGUILayout.TextField(\"fast_array_elements\", ToCountText(snapshot.memoryUsage.fast_array_elements));\r\n                EditorGUILayout.TextField(\"binary_object_count\", ToCountText(snapshot.memoryUsage.binary_object_count));\r\n                EditorGUILayout.TextField(\"binary_object_size\", ToSizeText(snapshot.memoryUsage.binary_object_size));\r\n            });\r\n            EditorGUILayout.EndVertical();\r\n        }\r\n\r\n        private void OnDrawManagedObjectEntry(Rect rect, int index, WeakReference<object> objRef)\r\n        {\r\n            if (objRef.TryGetTarget(out var item))\r\n            {\r\n                EditorGUI.LabelField(rect, GetDescription(item));\r\n            }\r\n            else\r\n            {\r\n                EditorGUI.LabelField(rect, \"Empty Slot\");\r\n            }\r\n        }\r\n\r\n        private void OnManagedObjectsGUI(Snapshot snapshot)\r\n        {\r\n            EditorGUILayout.BeginHorizontal();\r\n            EditorGUILayout.BeginVertical(GUILayout.Width(100f));\r\n            var rect = EditorGUILayout.GetControlRect(GUILayout.ExpandHeight(true));\r\n            if (snapshot.fetchManagedObjectRefs)\r\n            {\r\n\r\n                snapshot.managedObjectRefs.OnDrawItem = OnDrawManagedObjectEntry;\r\n                snapshot.managedObjectRefs.Draw(rect);\r\n            }\r\n            EditorGUILayout.EndVertical();\r\n            EditorGUILayout.BeginVertical();\r\n\r\n            var first = snapshot.managedObjectRefs.selection.FirstOrDefault();\r\n            if (first != null && first.TryGetTarget(out var obj))\r\n            {\r\n                InspectObject(obj);\r\n            }\r\n            EditorGUILayout.EndVertical();\r\n            EditorGUILayout.EndHorizontal();\r\n        }\r\n\r\n        //TODO unfinished_feature: inspect internal details of object\r\n        private void InspectObject(object selected)\r\n        {\r\n            if (selected == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            var type = selected.GetType();\r\n            EditorGUILayout.LabelField(\"Type\", type.Name);\r\n            EditorGUILayout.Toggle(\"Primitive\", type.IsPrimitive);\r\n            EditorGUILayout.Toggle(\"Pointer\", type.IsPointer);\r\n            if (type.IsPointer)\r\n            {\r\n                return;\r\n            }\r\n            if (type.IsArray)\r\n            {\r\n                var array = selected as Array;\r\n                if (array.Rank == 1)\r\n                {\r\n                    var len = array.GetLength(0);\r\n                    EditorGUILayout.IntField(\"Length\", len);\r\n                    for (var i = 0; i < len; ++i)\r\n                    {\r\n                        InspectObject(array.GetValue(i));\r\n                    }\r\n                }\r\n                return;\r\n            }\r\n\r\n            if (type == typeof(string))\r\n            {\r\n                EditorGUILayout.LabelField(\"String\", selected as string);\r\n                return;\r\n            }\r\n\r\n            if (type == typeof(GUIContent))\r\n            {\r\n                EditorGUILayout.LabelField(GetCachedTextContent(\"GUIContent\"), selected as GUIContent);\r\n                return;\r\n            }\r\n\r\n            var fields = type.GetFields(Binding.DynamicType.DefaultFlags);\r\n            for (var i = 0; i < fields.Length; i++)\r\n            {\r\n                var field = fields[i];\r\n                var fieldValue = field.GetValue(field.IsStatic ? null : selected);\r\n                EditorGUILayout.LabelField(field.Name, GetDescription(fieldValue));\r\n            }\r\n        }\r\n\r\n        private void OnTimersGUI(Snapshot snapshot)\r\n        {\r\n            EditorGUILayout.BeginVertical();\r\n            EditorGUILayout.IntField(\"Now\", snapshot.timeNow);\r\n\r\n            var count = snapshot.activeTimers.Count;\r\n            if (count > 0)\r\n            {\r\n                EditorGUILayout.BeginHorizontal();\r\n                EditorGUILayout.LabelField(\"ID\");\r\n                EditorGUILayout.LabelField(\"Delay\");\r\n                EditorGUILayout.LabelField(\"Deadline\");\r\n                EditorGUILayout.EndHorizontal();\r\n                for (var i = 0; i < count; i++)\r\n                {\r\n                    var t = snapshot.activeTimers[i];\r\n                    EditorGUILayout.BeginHorizontal();\r\n                    EditorGUILayout.TextField(t.id.ToString());\r\n                    EditorGUILayout.IntField(t.delay);\r\n                    EditorGUILayout.IntField(t.deadline);\r\n                    EditorGUILayout.EndHorizontal();\r\n                }\r\n            }\r\n            EditorGUILayout.EndVertical();\r\n        }\r\n\r\n        private void InspectSnapshot(Snapshot snapshot)\r\n        {\r\n            lock (snapshot)\r\n            {\r\n                if (!snapshot.alive)\r\n                {\r\n                    EditorGUILayout.HelpBox(\"This runtime isn't alive.\", MessageType.Info);\r\n                    return;\r\n                }\r\n\r\n                _categoryIndex = GUILayout.Toolbar(_categoryIndex, _categoryLabels);\r\n                _categoryDrawers[_categoryIndex](snapshot);\r\n            }\r\n        }\r\n\r\n        protected override void OnUpdate()\r\n        {\r\n            if (_autoCap)\r\n            {\r\n                var rt = Time.realtimeSinceStartup;\r\n\r\n                if (rt - _time > _timeCap)\r\n                {\r\n                    _time = rt;\r\n                    CaptureAll();\r\n                }\r\n            }\r\n        }\r\n\r\n        private void CaptureAll()\r\n        {\r\n            for (int i = 0, count = _snapshots.Count; i < count; i++)\r\n            {\r\n                var snapshot = _snapshots[i];\r\n                snapshot.alive = false;\r\n            }\r\n            _alive = ScriptEngine.ForEachRuntime(runtime => Capture(runtime));\r\n\r\n            for (int i = 0, count = _snapshots.Count; i < count; i++)\r\n            {\r\n                var snapshot = _snapshots[i];\r\n                if (snapshot.alive)\r\n                {\r\n                    _snapshotNames[i] = snapshot.id.ToString();\r\n                }\r\n                else\r\n                {\r\n                    _snapshotNames[i] = snapshot.id.ToString() + \" (dead)\";\r\n                }\r\n            }\r\n            Repaint();\r\n        }\r\n\r\n        protected override void OnPaint()\r\n        {\r\n            _alive = ScriptEngine.ForEachRuntime(runtime => { });\r\n\r\n            using (var scrollViewScope = new EditorGUILayout.ScrollViewScope(_sv))\r\n            {\r\n                _sv = scrollViewScope.scrollPosition;\r\n\r\n                Block(\"Control\", () =>\r\n                {\r\n                    EditorGUI.BeginDisabledGroup(EditorApplication.isCompiling);\r\n                    EditorGUILayout.BeginHorizontal();\r\n                    EditorGUILayout.LabelField(\"Engine\");\r\n                    var selectedBackend = Array.IndexOf(_backends, Native.JSApi.JSBDLL);\r\n                    var selectedBackendNew = GUILayout.Toolbar(selectedBackend, _backends);\r\n                    if (selectedBackendNew != selectedBackend)\r\n                    {\r\n                        if (EditorUtility.DisplayDialog(\"Switching backend\", \"Are you sure to switch to \" + _backends[selectedBackendNew] + \"?\", \"Confirm\", \"Cancel\"))\r\n                        {\r\n                            UnityHelper.SetDefineSymbol(\"JSB_WITH_V8_BACKEND\", _backends[selectedBackendNew] != \"quickjs\");\r\n                        }\r\n                    }\r\n                    EditorGUILayout.EndHorizontal();\r\n                    if (_backends[selectedBackendNew] != \"quickjs\")\r\n                    {\r\n                        EditorGUILayout.HelpBox(\"v8-bridge is still in experimental stage, the stability and the performance are unsure.\", MessageType.Warning);\r\n                    }\r\n                    EditorGUI.EndDisabledGroup();\r\n\r\n                    var old_isDebugMode = Native.JSApi.IsDebugMode();\r\n                    var new_isDebugMode = EditorGUILayout.Toggle(\"IsDebugMode\", old_isDebugMode);\r\n                    if (new_isDebugMode != old_isDebugMode)\r\n                    {\r\n                        if (EditorUtility.DisplayDialog(\"Setting debug symbol\", \"Are you sure to \" + (new_isDebugMode ? \"set\" : \"unset\") + \" debug mode?\", \"Confirm\", \"Cancel\"))\r\n                        {\r\n                            UnityHelper.SetDefineSymbol(\"JSB_DEBUG\", new_isDebugMode);\r\n                        }\r\n                    }\r\n                    EditorGUI.BeginDisabledGroup(true);\r\n                    EditorGUILayout.IntField(\"Dll Version\", Native.JSApi.SO_JSB_VERSION);\r\n                    if (Native.JSApi.CS_JSB_VERSION != Native.JSApi.SO_JSB_VERSION)\r\n                    {\r\n                        EditorGUILayout.HelpBox(\"The version of imported dll doesn't equal to \" + Native.JSApi.CS_JSB_VERSION, MessageType.Warning);\r\n                    }\r\n                    EditorGUILayout.Toggle(GUIContent_Stats_Operator, Native.JSApi.IsOperatorOverloadingSupported);\r\n                    EditorGUI.EndDisabledGroup();\r\n\r\n                    _fetchManagedObjectRefs = EditorGUILayout.Toggle(\"Show Refs\", _fetchManagedObjectRefs);\r\n                    _autoCap = EditorGUILayout.Toggle(\"Auto Refresh\", _autoCap);\r\n                    EditorGUI.BeginDisabledGroup(!_autoCap);\r\n                    _timeCap = EditorGUILayout.Slider(\"Interval\", _timeCap, 1f, 30f);\r\n                    EditorGUI.EndDisabledGroup();\r\n\r\n                    _selectedSnapshotIndex = EditorGUILayout.Popup(\"Snapshot\", _selectedSnapshotIndex, _snapshotNames);\r\n                });\r\n\r\n                if (_alive == 0)\r\n                {\r\n                    EditorGUILayout.HelpBox(\"No Running Runtime\", MessageType.Info);\r\n                    return;\r\n                }\r\n\r\n                if (_selectedSnapshotIndex >= 0 && _selectedSnapshotIndex < _snapshots.Count)\r\n                {\r\n                    InspectSnapshot(_snapshots[_selectedSnapshotIndex]);\r\n                }\r\n            }\r\n        } // end OnPaint()\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/ScriptEngineStatsWindow.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 4281011bc9bc4444f96b29365e6c00f5\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/SimpleListView.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using UnityEngine;\r\n    using UnityEditor;\r\n\r\n    public class SimpleListView<T>\r\n    {\r\n        private Vector2 _scollPosition;\r\n        private Rect _viewRect;\r\n        private Rect _itemRect;\r\n        private List<T> _items;\r\n        private HashSet<T> _selection = new HashSet<T>();\r\n        private float _itemHeight;\r\n\r\n        public Action<Rect, int, T> OnDrawItem;\r\n        public Action<T, HashSet<T>> OnSelectItem;\r\n\r\n        public HashSet<T> selection => _selection;\r\n\r\n        public SimpleListView()\r\n        {\r\n            _itemHeight = EditorGUIUtility.singleLineHeight;\r\n            _items = new List<T>();\r\n        }\r\n\r\n        public int Count => _items.Count;\r\n\r\n        public void Clear()\r\n        {\r\n            _items.Clear();\r\n            _viewRect = new Rect(0f, 0f, 0f, 0f);\r\n        }\r\n\r\n        public void AddRange(System.Collections.Generic.IEnumerable<T> items)\r\n        {\r\n            _items.AddRange(items);\r\n            _viewRect.height = _itemHeight * _items.Count;\r\n        }\r\n\r\n        public void Add(T item)\r\n        {\r\n            _items.Add(item);\r\n            _viewRect.height = _itemHeight * _items.Count;\r\n        }\r\n\r\n        public void Draw(Rect rect)\r\n        {\r\n            _viewRect.width = rect.width - 16f;\r\n            _scollPosition = GUI.BeginScrollView(rect, _scollPosition, _viewRect);\r\n            var fromIndex = Mathf.Max(Mathf.FloorToInt(_scollPosition.y / _itemHeight), 0);\r\n            var toIndex = Mathf.Min(fromIndex + Mathf.CeilToInt(rect.height / _itemHeight), _items.Count - 1);\r\n            for (var i = fromIndex; i <= toIndex; ++i)\r\n            {\r\n                _itemRect.Set(0f, i * _itemHeight, rect.width, _itemHeight);\r\n\r\n                var currentItem = _items[i];\r\n                var isSelected = _selection.Contains(currentItem);\r\n\r\n                if (!isSelected && Event.current.type == EventType.MouseUp)\r\n                {\r\n                    if (_itemRect.Contains(Event.current.mousePosition))\r\n                    {\r\n                        _selection.Clear();\r\n                        _selection.Add(currentItem);\r\n                        OnSelectItem?.Invoke(currentItem, _selection);\r\n                        isSelected = true;\r\n                    }\r\n                }\r\n\r\n                if (isSelected)\r\n                {\r\n                    EditorGUI.DrawRect(_itemRect, UnityHelper.SelectRowColor);\r\n                }\r\n                else\r\n                {\r\n                    if (i % 2 == 0)\r\n                    {\r\n                        EditorGUI.DrawRect(_itemRect, UnityHelper.RowColor);\r\n                    }\r\n                }\r\n                OnDrawItem?.Invoke(_itemRect, i, currentItem);\r\n            }\r\n            GUI.EndScrollView();\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/SimpleListView.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 9dba33ffeddeae841bf2938c9bcf9024\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/SimpleSplitView.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using UnityEngine;\r\n    using UnityEditor;\r\n\r\n    public class SimpleSplitView\r\n    {\r\n        public bool init = false; // 是否初始化\r\n        public float splitPivot = 0f;\r\n        public bool resizing = false;\r\n        public Rect cursorChangeRect;\r\n        public Rect cursorHintRect;\r\n\r\n        public float cursorHintSize = 2f;\r\n        public float cursorSize = 6f;\r\n        public Color cursorHintColor = new Color(0f, 0f, 0f, 0.35f);\r\n\r\n        public bool Draw(Rect rect)\r\n        {\r\n            var startY = rect.y;\r\n            var layout = Event.current.type == EventType.Repaint;\r\n\r\n            if (!this.init && layout)\r\n            {\r\n                this.init = true;\r\n                this.splitPivot = Mathf.Max(Mathf.Min(rect.width * .25f, rect.width - 10f), 10f);\r\n            }\r\n\r\n            if (!this.resizing)\r\n            {\r\n                this.cursorChangeRect.Set(this.splitPivot - 2f, startY, this.cursorSize, rect.height);\r\n                this.cursorHintRect.Set(this.splitPivot - 2f, startY, this.cursorHintSize, rect.height);\r\n            }\r\n\r\n            EditorGUI.DrawRect(this.cursorHintRect, this.cursorHintColor);\r\n            EditorGUIUtility.AddCursorRect(this.cursorChangeRect, MouseCursor.ResizeHorizontal);\r\n\r\n            if (Event.current.type == EventType.MouseDown && this.cursorChangeRect.Contains(Event.current.mousePosition))\r\n            {\r\n                this.resizing = true;\r\n            }\r\n\r\n            if (this.resizing && layout)\r\n            {\r\n                var y = this.cursorChangeRect.y;\r\n                var h = this.cursorChangeRect.height;\r\n                this.splitPivot = Mathf.Min(Mathf.Max(Event.current.mousePosition.x, 10), rect.width - 10);\r\n                this.cursorChangeRect.Set(this.splitPivot - 2, y, this.cursorSize, h);\r\n                this.cursorHintRect.Set(this.splitPivot - 2, y, this.cursorHintSize, h);\r\n            }\r\n\r\n            if (Event.current.type == EventType.MouseUp)\r\n            {\r\n                this.resizing = false;\r\n            }\r\n\r\n            return this.resizing;\r\n        }\r\n\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/SimpleSplitView.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 713e0cd4cf9039348a24135792042c66\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/SimpleTreeView.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using UnityEngine;\r\n    using UnityEditor;\r\n\r\n    internal class SimpleTreeView\r\n    {\r\n        public interface INode\r\n        {\r\n            GUIContent content { get; }\r\n            bool isExpanded { get; set; }\r\n            int childCount { get; }\r\n\r\n            void AddChild(INode node);\r\n            void Prepass(State state);\r\n            bool Render(State state);\r\n            Vector2 CalcSize(GUIStyle style);\r\n\r\n            bool CollapseAll();\r\n            bool ExpandAll();\r\n\r\n            void ShowContextMenu(State state);\r\n        }\r\n\r\n        public class State\r\n        {\r\n            private SimpleTreeView _treeView;\r\n            private float _indentWidth = 16f;\r\n            private float _itemHeight = EditorGUIUtility.singleLineHeight;\r\n\r\n            private int _index;\r\n            private int _indent;\r\n            private float _leftPadding = 4f;\r\n            private Vector2 _position;\r\n            protected Vector2 _scrollPosition;\r\n            private float _maxWidth;\r\n            private Rect _drawRect;\r\n            private Rect _viewRect;\r\n            private Rect _itemRect;\r\n            private Rect _itemFullRect;\r\n            private GUIStyle _itemStyle;\r\n\r\n            private float _lastClickTime;\r\n\r\n            private Color _rowColor = new Color(0.5f, 0.5f, 0.5f, 0.1f);\r\n            private Color _selectColor = new Color(44f / 255f, 93f / 255f, 135f / 255f);\r\n\r\n            private int _fromIndex;\r\n            private int _toIndex;\r\n            private int _itemCount;\r\n            private bool _repaint;\r\n            private bool _isRendering;\r\n\r\n            private HashSet<INode> _selection = new HashSet<INode>();\r\n\r\n            private Func<INode, bool> _itemValidator = null;\r\n\r\n            public bool repaint => _repaint;\r\n\r\n            public State(SimpleTreeView treeView)\r\n            {\r\n                _treeView = treeView;\r\n                _itemStyle = EditorStyles.label;\r\n            }\r\n\r\n            public void BeginPrepass()\r\n            {\r\n                _indent = 0;\r\n                _itemCount = 0;\r\n                _viewRect.Set(0f, 0f, 0f, 0f);\r\n            }\r\n\r\n            public void AddSpace(INode node)\r\n            {\r\n                var itemWidth = node.CalcSize(_itemStyle).x;\r\n                _viewRect.height += _itemHeight;\r\n                var width = _indent * _indentWidth + itemWidth;\r\n                _viewRect.width = Mathf.Max(width, _viewRect.width);\r\n                _itemCount++;\r\n            }\r\n\r\n            public void EndPrepass()\r\n            {\r\n                var yMax = _viewRect.height - _drawRect.height;\r\n                if (_scrollPosition.y > yMax)\r\n                {\r\n                    _scrollPosition.y = yMax;\r\n                }\r\n            }\r\n\r\n            public void Begin(Func<INode, bool> itemValidator)\r\n            {\r\n                _index = 0;\r\n                _indent = 0;\r\n                _isRendering = false;\r\n                _itemValidator = itemValidator;\r\n            }\r\n\r\n            public void End()\r\n            {\r\n            }\r\n\r\n            public void BeginView(Rect rect)\r\n            {\r\n                Begin(null);\r\n                _repaint = false;\r\n                _isRendering = true;\r\n                _drawRect = rect;\r\n                _maxWidth = Mathf.Max(_drawRect.width, _viewRect.width);\r\n                _scrollPosition = GUI.BeginScrollView(_drawRect, _scrollPosition, _viewRect);\r\n                _fromIndex = Mathf.Max(Mathf.FloorToInt(_scrollPosition.y / _itemHeight) - 1, 0);\r\n                _toIndex = Mathf.Min(_fromIndex + Mathf.CeilToInt(_drawRect.height / _itemHeight) + 1, _itemCount - 1);\r\n            }\r\n\r\n            public void EndView()\r\n            {\r\n                End();\r\n                GUI.EndScrollView();\r\n            }\r\n\r\n            public void PushGroup()\r\n            {\r\n                ++_indent;\r\n            }\r\n\r\n            public void PopGroup()\r\n            {\r\n                --_indent;\r\n            }\r\n\r\n            private bool CheckDoubleClick()\r\n            {\r\n                var rt = Time.realtimeSinceStartup;\r\n                var dt = rt - _lastClickTime;\r\n                if (dt < 0.2f)\r\n                {\r\n                    _lastClickTime = 0f;\r\n                    return true;\r\n                }\r\n                _lastClickTime = rt;\r\n                return false;\r\n            }\r\n\r\n            public bool Render(INode node)\r\n            {\r\n                if (_itemValidator != null && !_itemValidator(node))\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                var index = _index++;\r\n\r\n                if (!_isRendering)\r\n                {\r\n                    return true;\r\n                }\r\n\r\n                if (index >= _fromIndex && index <= _toIndex)\r\n                {\r\n                    var isSelected = _selection.Contains(node);\r\n                    var isExpandable = node.childCount > 0;\r\n\r\n                    if (isSelected)\r\n                    {\r\n                        _itemRect.Set(0, index * _itemHeight, _maxWidth, _itemHeight);\r\n                        EditorGUI.DrawRect(_itemRect, _selectColor);\r\n                    }\r\n                    else\r\n                    {\r\n                        if (index % 2 == 0)\r\n                        {\r\n                            _itemRect.Set(0, index * _itemHeight, _maxWidth, _itemHeight);\r\n                            EditorGUI.DrawRect(_itemRect, _rowColor);\r\n                        }\r\n                    }\r\n\r\n                    var x = _indent * _indentWidth + _leftPadding;\r\n                    var eventUsed = false;\r\n\r\n                    if (isExpandable)\r\n                    {\r\n                        _itemRect.Set(x, index * _itemHeight, _itemHeight, _itemHeight);\r\n\r\n                        var isExpanded = node.isExpanded;\r\n                        GUI.DrawTexture(_itemRect, isExpanded ? UnityHelper.GetIcon(\"ExpandedItemIcon\") : UnityHelper.GetIcon(\"CollapsedItemIcon\"), ScaleMode.ScaleToFit);\r\n                        if (!eventUsed && Event.current.type == EventType.MouseUp)\r\n                        {\r\n                            if (_itemRect.Contains(Event.current.mousePosition))\r\n                            {\r\n                                if (Event.current.button == 1)\r\n                                {\r\n                                    node.ShowContextMenu(this);\r\n                                    eventUsed = true;\r\n                                }\r\n                                else\r\n                                {\r\n                                    node.isExpanded = !isExpanded;\r\n                                    _treeView.Invalidate();\r\n                                    _repaint = true;\r\n                                    eventUsed = true;\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n\r\n                    _itemRect.Set(x + _itemHeight, index * _itemHeight, _maxWidth - x, _itemHeight);\r\n                    EditorGUI.LabelField(_itemRect, node.content, _itemStyle);\r\n\r\n                    if (!eventUsed && Event.current.type == EventType.MouseUp)\r\n                    {\r\n                        _itemRect.x = 0f;\r\n                        if (_itemRect.Contains(Event.current.mousePosition))\r\n                        {\r\n                            if (Event.current.button == 1)\r\n                            {\r\n                                node.ShowContextMenu(this);\r\n                                eventUsed = true;\r\n                            }\r\n                            else\r\n                            {\r\n                                if (CheckDoubleClick())\r\n                                {\r\n                                    node.isExpanded = !node.isExpanded;\r\n                                    _treeView.Invalidate();\r\n                                    _repaint = true;\r\n                                    eventUsed = true;\r\n                                }\r\n                                else\r\n                                {\r\n                                    if (!isSelected)\r\n                                    {\r\n                                        _selection.Clear();\r\n                                        _selection.Add(node);\r\n                                        _treeView.OnSelectItem?.Invoke(node, _selection);\r\n                                        _repaint = true;\r\n                                        eventUsed = true;\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                } // end if visible\r\n                return true;\r\n            }\r\n\r\n            public void Select(INode node, bool doRaiseEvent)\r\n            {\r\n                _selection.Clear();\r\n                _selection.Add(node);\r\n                if (doRaiseEvent)\r\n                {\r\n                    _treeView.OnSelectItem?.Invoke(node, _selection);\r\n                }\r\n            }\r\n\r\n            public void SelectCurrent(INode node, bool doRaiseEvent)\r\n            {\r\n                _scrollPosition.y = Mathf.Min(_index * _itemHeight, _viewRect.height - _drawRect.height);\r\n                Select(node, doRaiseEvent);\r\n            }\r\n\r\n            public void CollapseAll()\r\n            {\r\n                var change = false;\r\n                foreach (var child in _treeView._children)\r\n                {\r\n                    if (child.CollapseAll())\r\n                    {\r\n                        change = true;\r\n                    }\r\n                }\r\n\r\n                if (change)\r\n                {\r\n                    _treeView.Invalidate();\r\n                }\r\n            }\r\n\r\n            public void ExpandAll()\r\n            {\r\n                var change = false;\r\n                foreach (var child in _treeView._children)\r\n                {\r\n                    if (child.ExpandAll())\r\n                    {\r\n                        change = true;\r\n                    }\r\n                }\r\n\r\n                if (change)\r\n                {\r\n                    _treeView.Invalidate();\r\n                }\r\n            }\r\n        }\r\n\r\n        public Action<INode, HashSet<INode>> OnSelectItem;\r\n\r\n        private State _state;\r\n        private List<INode> _children = new List<INode>();\r\n\r\n        public void Add(INode node)\r\n        {\r\n            if (node != null)\r\n            {\r\n                _children.Add(node);\r\n            }\r\n        }\r\n\r\n        public void Invalidate()\r\n        {\r\n            if (_state == null)\r\n            {\r\n                _state = new State(this);\r\n            }\r\n            _state.BeginPrepass();\r\n            for (int i = 0, count = _children.Count; i < count; ++i)\r\n            {\r\n                var child = _children[i];\r\n                child.Prepass(_state);\r\n            }\r\n            _state.EndPrepass();\r\n        }\r\n\r\n        public void Select(INode node, bool doScrollTo = true, bool doRaiseEvent = false)\r\n        {\r\n            if (_state == null)\r\n            {\r\n                _state = new State(this);\r\n            }\r\n\r\n            if (!doScrollTo)\r\n            {\r\n                _state.Select(node, doRaiseEvent);\r\n                return;\r\n            }\r\n\r\n            _state.Begin(it =>\r\n            {\r\n                if (it == node)\r\n                {\r\n                    _state.SelectCurrent(node, doRaiseEvent);\r\n                    return false;\r\n                }\r\n                return true;\r\n            });\r\n\r\n            for (int i = 0, count = _children.Count; i < count; ++i)\r\n            {\r\n                var child = _children[i];\r\n                if (!child.Render(_state))\r\n                {\r\n                    break;\r\n                }\r\n            }\r\n            _state.End();\r\n        }\r\n\r\n        public bool Draw(Rect rect)\r\n        {\r\n            if (_state == null)\r\n            {\r\n                _state = new State(this);\r\n            }\r\n            _state.BeginView(rect);\r\n            for (int i = 0, count = _children.Count; i < count; ++i)\r\n            {\r\n                var child = _children[i];\r\n                if (!child.Render(_state))\r\n                {\r\n                    break;\r\n                }\r\n            }\r\n            _state.EndView();\r\n\r\n            return _state.repaint;\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/SimpleTreeView.cs.meta",
    "content": "fileFormatVersion: 2\nguid: bc1f08674fa18f8428f05556b44352b9\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/TypescriptPostProcessor.cs",
    "content": "#if !JSB_UNITYLESS\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    // public class TypeScriptPostProcessor : AssetPostprocessor\r\n    // {\r\n    //     private static bool IsScriptSourceFile(string filename)\r\n    //     {\r\n    //         return filename.EndsWith(\".ts\") || filename.EndsWith(\".js\") || filename.EndsWith(\".js.txt\");\r\n    //     }\r\n\r\n    //     private static bool CheckAssets(string outDir, string[] assetPaths)\r\n    //     {\r\n    //         foreach (var assetPath in assetPaths)\r\n    //         {\r\n    //             if (outDir == null || !assetPath.StartsWith(outDir, StringComparison.OrdinalIgnoreCase)) // skip output files\r\n    //             {\r\n    //                 if (IsScriptSourceFile(assetPath))\r\n    //                 {\r\n    //                     // Debug.Log(assetPath);\r\n    //                     return true;\r\n    //                 }\r\n    //             }\r\n    //         }\r\n    //         return false;\r\n    //     }\r\n\r\n    //     private static void OnPostprocessAllAssets(\r\n    //         string[] importedAssets,\r\n    //         string[] deletedAssets,\r\n    //         string[] movedAssets,\r\n    //         string[] movedFromAssetPaths)\r\n    //     {\r\n    //         // if (EditorApplication.isPlaying || EditorApplication.isPaused)\r\n    //         // {\r\n    //         //     return;\r\n    //         // }\r\n    //         // if (!File.Exists(\"tsconfig.json\"))\r\n    //         // {\r\n    //         //     // no typescript context\r\n    //         //     return;\r\n    //         // }\r\n    //         // string outDir = null;\r\n    //         // try\r\n    //         // {\r\n    //         //     var text = NormalizeJson(File.ReadAllText(\"tsconfig.json\"));\r\n    //         //     var tsconfig = JsonUtility.FromJson<TSConfig>(text);\r\n    //         //     outDir = tsconfig.compilerOptions.outDir;\r\n    //         // }\r\n    //         // catch (Exception exception) { Debug.LogWarning(exception); }\r\n    //         // if (CheckAssets(outDir, importedAssets) ||\r\n    //         //     CheckAssets(outDir, deletedAssets) ||\r\n    //         //     CheckAssets(outDir, movedAssets) ||\r\n    //         //     CheckAssets(outDir, movedFromAssetPaths))\r\n    //         // {\r\n    //         //     UnityHelper.CompileScripts();\r\n    //         // }\r\n    //     }\r\n    // }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/TypescriptPostProcessor.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 0e76ab41d4b3cd444a1305b4b13ea7d9\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/UnityBindingUtils.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    public class UnityBindingUtils : Binding.IBindingUtils\r\n    {\r\n        public string ReplacePathVars(string value)\r\n        {\r\n            return Unity.UnityHelper.ReplacePathVars(value);\r\n        }\r\n\r\n        public bool IsExplicitEditorType(Type type)\r\n        {\r\n            return Unity.UnityHelper.IsExplicitEditorType(type);\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/UnityBindingUtils.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 687b23b93fb78b5429ad5cfb965c731b\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/UnityHelper.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Text.RegularExpressions;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using UnityEngine;\r\n    using UnityEditor;\r\n    using System.Reflection;\r\n    using QuickJS.Binding;\r\n\r\n    [InitializeOnLoad]\r\n    public static class UnityHelper\r\n    {\r\n        public static Color RowColor = new Color(0.5f, 0.5f, 0.5f, 0.1f);\r\n        public static Color SelectRowColor = new Color(44f / 255f, 93f / 255f, 135f / 255f);\r\n\r\n        private static Dictionary<string, Texture> _iconCache = new Dictionary<string, Texture>();\r\n\r\n        public static Texture GetIcon(string name)\r\n        {\r\n            Texture icon;\r\n            if (!_iconCache.TryGetValue(name, out icon))\r\n            {\r\n                icon = _iconCache[name] = LoadPackageAsset<Texture>($\"Editor/Icons/{name}.png\");\r\n            }\r\n            return icon;\r\n        }\r\n\r\n        public static bool IsApplicationActive()\r\n        {\r\n            return UnityEditorInternal.InternalEditorUtility.isApplicationActive && !EditorApplication.isCompiling;\r\n        }\r\n\r\n        #region All Menu Items\r\n        [MenuItem(\"JS Bridge/Generate Bindings And Type Definition\")]\r\n        public static void GenerateBindingsAndTypeDefinition()\r\n        {\r\n            var bm = new BindingManager(PrefsLoader.CurrentPrefs, new BindingManager.Args\r\n            {\r\n                codeGenCallback = new DefaultCodeGenCallback(),\r\n                bindingLogger = new DefaultBindingLogger(),\r\n                useLogWriter = true,\r\n                utils = new UnityBindingUtils(),\r\n            });\r\n            bm.Collect();\r\n            bm.Generate(TypeBindingFlags.Default);\r\n            bm.Cleanup();\r\n            bm.Report();\r\n            AssetDatabase.Refresh();\r\n        }\r\n\r\n        [MenuItem(\"JS Bridge/Generate Type Definition\")]\r\n        public static void GenerateTypeDefinition()\r\n        {\r\n            var bm = new BindingManager(PrefsLoader.CurrentPrefs, new BindingManager.Args\r\n            {\r\n                codeGenCallback = new DefaultCodeGenCallback(),\r\n                bindingLogger = new DefaultBindingLogger(),\r\n                useLogWriter = true,\r\n                utils = new UnityBindingUtils(),\r\n            });\r\n            bm.Collect();\r\n            bm.Generate(TypeBindingFlags.TypeDefinition);\r\n            bm.Cleanup();\r\n            bm.Report();\r\n            AssetDatabase.Refresh();\r\n        }\r\n\r\n        public static T LoadPackageAsset<T>(string assetPath)\r\n        where T : Object\r\n        {\r\n            try\r\n            {\r\n                var path = AssetDatabase.GetAssetPath(GetMonoScript(typeof(JSBehaviour)));\r\n                if (path != null)\r\n                {\r\n                    var evaluatedPath = Path.Combine(Path.GetDirectoryName(path), \"../../\", assetPath).Replace(\"\\\\\", \"/\");\r\n                    var extractedPath = Utils.PathUtils.ExtractPath(evaluatedPath, '/');\r\n                    if (File.Exists(extractedPath))\r\n                    {\r\n                        return LoadAssetAtPath<T>(extractedPath); // for upm-shipping style\r\n                    }\r\n                }\r\n            }\r\n            catch (Exception)\r\n            {\r\n            }\r\n\r\n            return LoadAssetAtPath<T>(\"Assets/jsb/\" + assetPath) // for old-school style\r\n               ?? LoadAssetAtPath<T>(\"Packages/cc.starlessnight.unity-jsb/\" + assetPath) // for upm-dev style\r\n            ;\r\n        }\r\n\r\n        public static T LoadAssetAtPath<T>(string assetPath)\r\n        where T : Object\r\n        {\r\n            return AssetDatabase.LoadAssetAtPath(assetPath, typeof(T)) as T;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get MonoScript by type\r\n        /// </summary>\r\n        public static MonoScript GetMonoScript(Type type)\r\n        {\r\n            var name = type.Name;\r\n            var assetGuids = AssetDatabase.FindAssets($\"t:Script {name}\");\r\n            foreach (var assetGuid in assetGuids)\r\n            {\r\n                var assetPath = AssetDatabase.GUIDToAssetPath(assetGuid);\r\n                var asset = AssetDatabase.LoadAssetAtPath<MonoScript>(assetPath);\r\n                if (asset && asset.GetClass() == type)\r\n                {\r\n                    return asset;\r\n                }\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        public static void SetDefineSymbol(string defineItem, bool isAdding)\r\n        {\r\n            var buildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup;\r\n            var defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup).Split(';').ToList();\r\n            if (isAdding)\r\n            {\r\n                if (!defines.Contains(defineItem))\r\n                {\r\n                    defines.Add(defineItem);\r\n                    PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, string.Join(\";\", defines));\r\n                }\r\n            }\r\n            else\r\n            {\r\n                if (defines.Remove(defineItem))\r\n                {\r\n                    PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, string.Join(\";\", defines));\r\n                }\r\n            }\r\n        }\r\n\r\n        public static bool IsReflectBindingSupported()\r\n        {\r\n            return PrefsLoader.CurrentPrefs.preferredBindingMethod == \"Reflect Bind\";\r\n        }\r\n\r\n        public static void Time(string name, Action action)\r\n        {\r\n            var stopWatch = new System.Diagnostics.Stopwatch();\r\n            stopWatch.Start();\r\n            try\r\n            {\r\n                action();\r\n                stopWatch.Stop();\r\n                Debug.LogFormat(\"Finished executing {0} in {1}ms\", name, stopWatch.ElapsedMilliseconds);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                stopWatch.Stop();\r\n                Debug.LogFormat(\"Finished executing {0} in {1}ms with error: {2}\\nStackTrace: {3}\", name, stopWatch.ElapsedMilliseconds, exception.Message, exception.StackTrace);\r\n                throw;\r\n            }\r\n        }\r\n\r\n        public static void InvokeReflectBinding(ScriptRuntime runtime)\r\n        {\r\n            Time(\"InvokeReflectBinding\", () =>\r\n            {\r\n                var bm = new BindingManager(PrefsLoader.CurrentPrefs, new BindingManager.Args\r\n                {\r\n                    bindingCallback = new ReflectBindingCallback(runtime),\r\n                    utils = new UnityBindingUtils(),\r\n                    bindingLogger = new DefaultBindingLogger(),\r\n                });\r\n                bm.Collect();\r\n                bm.Generate(TypeBindingFlags.None);\r\n                bm.Report();\r\n            });\r\n        }\r\n\r\n        public static bool IsInMemoryBindingSupported()\r\n        {\r\n            return PrefsLoader.CurrentPrefs.preferredBindingMethod == \"In-Memory Bind\";\r\n        }\r\n\r\n        public static void InvokeInMemoryBinding(ScriptRuntime runtime)\r\n        {\r\n            Time(\"InvokeInMemoryBinding\", () =>\r\n            {\r\n                var callback = new InMemoryCompilationBindingCallback(runtime);\r\n                var bm = new BindingManager(PrefsLoader.CurrentPrefs, new BindingManager.Args\r\n                {\r\n                    bindingCallback = callback,\r\n                    codeGenCallback = callback,\r\n                    utils = new UnityBindingUtils(),\r\n                });\r\n                bm.Collect();\r\n                bm.Generate(TypeBindingFlags.BindingCode | TypeBindingFlags.BuildTargetPlatformOnly);\r\n                bm.Report();\r\n            });\r\n        }\r\n\r\n        // [MenuItem(\"JS Bridge/Compile TypeScript\")]\r\n        public static void CompileScripts()\r\n        {\r\n            Debug.Log(\"compiling typescript source...\");\r\n            EditorApplication.delayCall += () =>\r\n            {\r\n                EditorApplication.delayCall += () =>\r\n                {\r\n#if UNITY_EDITOR_WIN\r\n                    string command = \"tsc.cmd\";\r\n#else\r\n                    string command = \"tsc\";\r\n#endif\r\n                    var exitCode = UnityShellHelper.Run(command, \"\", 30);\r\n                    Debug.Log($\"{command}: {exitCode}\");\r\n                };\r\n            };\r\n        }\r\n\r\n        [MenuItem(\"JS Bridge/Clear\")]\r\n        public static void ClearBindings()\r\n        {\r\n            var prefs = PrefsLoader.CurrentPrefs;\r\n            var kv = new Dictionary<string, List<string>>();\r\n\r\n            if (prefs.cleanupDir != null)\r\n            {\r\n                prefs.cleanupDir.ForEach(dir => kv[ReplacePathVars(dir)] = null);\r\n            }\r\n            kv[ReplacePathVars(prefs.outDir)] = null;\r\n            kv[ReplacePathVars(prefs.typescriptDir)] = null;\r\n            BindingManager.Cleanup(kv, null);\r\n            AssetDatabase.Refresh();\r\n        }\r\n\r\n        [MenuItem(\"JS Bridge/Prefs ...\", false, 5001)]\r\n        public static void OpenPrefsEditor()\r\n        {\r\n            EditorWindow.GetWindow<PrefsEditor>().Show();\r\n        }\r\n\r\n        [MenuItem(\"JS Bridge/Javascript Console\", false, 5003)]\r\n        public static void ShowJSConsole()\r\n        {\r\n            QuickJS.Unity.EditorRuntime.ShowWindow(\"plover/editor/js_console\", \"JSConsole\");\r\n        }\r\n\r\n        [MenuItem(\"JS Bridge/Javascript Module View\", false, 5004)]\r\n        public static void ShowJSModuleView()\r\n        {\r\n            QuickJS.Unity.EditorRuntime.ShowWindow(\"plover/editor/js_module_view\", \"JSModuleView\");\r\n        }\r\n\r\n        [MenuItem(\"JS Bridge/Script Editor Window Launcher\", false, 5005)]\r\n        public static void ShowScriptEditorWindowLauncher()\r\n        {\r\n            EditorWindow.GetWindow<ScriptEditorWindowLauncher>().Show();\r\n        }\r\n\r\n        public static string GetPlatform()\r\n        {\r\n            var buildTarget = EditorUserBuildSettings.activeBuildTarget;\r\n            switch (buildTarget)\r\n            {\r\n                case BuildTarget.Android: return \"Android\";\r\n                case BuildTarget.iOS: return \"iOS\";\r\n                case BuildTarget.WSAPlayer: return \"WSA\";\r\n                case BuildTarget.StandaloneWindows:\r\n                case BuildTarget.StandaloneWindows64: return \"Windows\";\r\n                case BuildTarget.StandaloneOSX: return \"OSX\";\r\n#if !UNITY_2019_2_OR_NEWER\r\n                case BuildTarget.StandaloneLinux:\r\n                case BuildTarget.StandaloneLinuxUniversal:\r\n#endif\r\n                case BuildTarget.StandaloneLinux64: return \"Linux\";\r\n                case BuildTarget.Switch: return \"Switch\";\r\n                case BuildTarget.PS4: return \"PS4\";\r\n                case BuildTarget.XboxOne: return \"XboxOne\";\r\n                default: return buildTarget.ToString();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// 可以明确表明该 Type 属于 Editor 运行时\r\n        /// </summary>\r\n        public static bool IsExplicitEditorType(Type type)\r\n        {\r\n            if (type.Namespace != null && type.Namespace.StartsWith(\"UnityEditor\"))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            return IsExplicitEditorDomain(type.Assembly);\r\n        }\r\n\r\n        /// <summary>\r\n        /// 可以明确表明该 Assembly 包含的类型属于 Editor 运行时\r\n        /// </summary>\r\n        public static bool IsExplicitEditorDomain(Assembly assembly)\r\n        {\r\n            if (assembly == typeof(Editor).Assembly)\r\n            {\r\n                return true;\r\n            }\r\n\r\n            var location = assembly.Location.Replace('\\\\', '/');\r\n            var assetsPath = new FileInfo(Application.dataPath);\r\n            var fullAssetsPath = assetsPath.FullName.Replace('\\\\', '/');\r\n\r\n            if (location.StartsWith(fullAssetsPath, StringComparison.OrdinalIgnoreCase))\r\n            {\r\n                var substr = location.Substring(fullAssetsPath.Length).ToLower();\r\n                if (substr.Contains(\"/editor/\"))\r\n                {\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public static string ReplacePathVars(string value)\r\n        {\r\n            var platform = GetPlatform();\r\n            value = value.Replace(\"${platform}\", platform);\r\n            return value;\r\n        }\r\n\r\n        public static void CompileBytecode(IList<string> assetPaths) => CompileBytecode(null, assetPaths);\r\n\r\n        /// <summary>\r\n        /// Compile scripts into bytecode\r\n        /// </summary>\r\n        /// <param name=\"workspace\">the container directory of tsconfig.json</param>\r\n        /// <param name=\"assetPaths\">path list of all scripts, all scripts will be recursively compiled if a given path is directory</param>\r\n        public static void CompileBytecode(string workspace, IList<string> assetPaths)\r\n        {\r\n            // nothing to compile\r\n            if (assetPaths.Count == 0)\r\n            {\r\n                return;\r\n            }\r\n            \r\n            var commonJSModule = false;\r\n            var tsconfigPath = string.IsNullOrEmpty(workspace) ? \"tsconfig.json\" : Path.Combine(workspace, \"tsconfig.json\");\r\n            if (File.Exists(tsconfigPath))\r\n            {\r\n                var text = Utils.TextUtils.NormalizeJson(File.ReadAllText(tsconfigPath));\r\n                var tsconfig = JsonUtility.FromJson<Utils.TSConfig>(text);\r\n                var module = tsconfig.compilerOptions.module;\r\n                if (module == \"commonjs\")\r\n                {\r\n                    commonJSModule = true;\r\n                    Debug.LogFormat(\"read tsconfig.json: compile as commonjs module mode\");\r\n                }\r\n            }\r\n            else\r\n            {\r\n                Debug.LogFormat(\"no tsconfig.json found, compile as ES6 module mode\");\r\n            }\r\n\r\n            using (var compiler = new UnityJSScriptCompiler())\r\n            {\r\n                foreach (var assetPath in assetPaths)\r\n                {\r\n                    CompileBytecode(compiler, assetPath, commonJSModule);\r\n                }\r\n            }\r\n        }\r\n\r\n        private static void CompileBytecode(UnityJSScriptCompiler compiler, string assetPath, bool commonJSModule)\r\n        {\r\n            if (Directory.Exists(assetPath))\r\n            {\r\n                foreach (var subDir in Directory.GetDirectories(assetPath))\r\n                {\r\n                    CompileBytecode(compiler, subDir, commonJSModule);\r\n                }\r\n\r\n                foreach (var subFile in Directory.GetFiles(assetPath))\r\n                {\r\n                    CompileBytecode(compiler, subFile, commonJSModule);\r\n                }\r\n            }\r\n            else\r\n            {\r\n                if (!string.IsNullOrEmpty(assetPath) && assetPath.EndsWith(\".js\"))\r\n                {\r\n                    var outPath = assetPath + \".bytes\";\r\n                    var bytes = File.ReadAllBytes(assetPath);\r\n                    var bytecode = compiler.Compile(assetPath, bytes, commonJSModule);\r\n                    if (bytecode != null)\r\n                    {\r\n                        File.WriteAllBytes(outPath, bytecode);\r\n                        Debug.LogFormat(\"compile {0}({1}) => {2}({3})\", assetPath, bytes.Length, outPath, bytecode.Length);\r\n                    }\r\n                    else\r\n                    {\r\n                        Debug.LogErrorFormat(\"compilation failed: {0}\", assetPath);\r\n                        if (File.Exists(outPath))\r\n                        {\r\n                            File.Delete(outPath);\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        #endregion\r\n\r\n        // https://regex101.com/r/426q4x/1\r\n        public static Regex JSBehaviourClassNameRegex = new Regex(@\"@ScriptType\\s*\\([\\s\\w\\{\\})]*\\)[\\n\\s]*export\\s+class\\s+(\\w+)\\s+extends\", RegexOptions.Multiline | RegexOptions.Compiled);\r\n        public static Regex JSAssetClassNameRegex = new Regex(@\"@ScriptAsset\\s*\\([\\s\\w\\{\\})]*\\)[\\n\\s]*export\\s+class\\s+(\\w+)\\s+extends\", RegexOptions.Multiline | RegexOptions.Compiled);\r\n        public static Regex JSCustomEditorClassNameRegex = new Regex(@\"^\\s*@ScriptEditor\\s*\\([\\s\\w\\{\\})]*\\)[\\n\\s]*export\\s+class\\s+(\\w+)\\s+extends\", RegexOptions.Multiline | RegexOptions.Compiled);\r\n        public static Regex JSEditorWindowClassNameRegex = new Regex(@\"^\\s*@ScriptEditorWindow\\s*\\([\\s\\w\\{\\})]*\\)[\\n\\s]*export\\s+class\\s+(\\w+)\\s+extends\", RegexOptions.Multiline | RegexOptions.Compiled);\r\n\r\n        public static string NormalizePathString(string path)\r\n        {\r\n            return path.Replace('\\\\', '/');\r\n        }\r\n\r\n        // sourceFile: 需要传入 FullPath\r\n        public static bool ResolveScriptRef(string sourceDirBase, string sourceFile, out string normalizedPath, out string modulePath, List<JSScriptClassPathHint> hints)\r\n        {\r\n            if (!Path.IsPathRooted(sourceFile))\r\n            {\r\n                sourceFile = Path.GetFullPath(sourceFile);\r\n            }\r\n\r\n            normalizedPath = sourceFile;\r\n            if (!sourceFile.EndsWith(\".ts\") && !sourceFile.EndsWith(\".tsx\"))\r\n            {\r\n                // invalid \r\n                modulePath = null;\r\n                return false;\r\n            }\r\n\r\n            var sourceExt = Path.GetExtension(sourceFile);\r\n\r\n            if (File.Exists(sourceFile))\r\n            {\r\n                var sourceDir = string.IsNullOrEmpty(sourceDirBase) ? \".\" : sourceDirBase;\r\n                if (Path.IsPathRooted(sourceDir))\r\n                {\r\n                    // not implemented\r\n                }\r\n                else\r\n                {\r\n                    var appRoot = Path.GetPathRoot(Application.dataPath);\r\n                    var sourceRoot = Path.GetPathRoot(sourceFile).Replace('\\\\', '/');\r\n\r\n                    if (appRoot == sourceRoot)\r\n                    {\r\n                        var sourcePathNorm = sourceFile.Replace('\\\\', '/');\r\n                        var appPathNorm = Path.Combine(Directory.GetParent(Application.dataPath).FullName, sourceDir).Replace('\\\\', '/');\r\n\r\n                        if (sourcePathNorm.ToLower().StartsWith(appPathNorm.ToLower()))\r\n                        {\r\n                            var sourceSubPathNorm = sourcePathNorm[0] == '/' ? sourcePathNorm.Substring(appPathNorm.Length + 1) : sourcePathNorm.Substring(appPathNorm.Length);\r\n                            var offset = sourceSubPathNorm[0] == '/' ? 1 : 0;\r\n\r\n                            modulePath = sourceSubPathNorm.Substring(offset, sourceSubPathNorm.Length - sourceExt.Length - offset);\r\n                            GetJSScriptClasses(sourceFile, modulePath, hints);\r\n                            return true;\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        // invalid\r\n                    }\r\n                }\r\n            }\r\n\r\n            modulePath = null;\r\n            return false;\r\n        }\r\n\r\n        private static void GetJSScriptClasses(string sourceFile, string modulePath, List<JSScriptClassPathHint> hints)\r\n        {\r\n            //TODO: need optimization?\r\n            var text = File.ReadAllText(sourceFile);\r\n\r\n            foreach (Match m in JSBehaviourClassNameRegex.Matches(text))\r\n            {\r\n                hints.Add(new JSScriptClassPathHint(sourceFile, modulePath, m.Groups[1].Value, JSScriptClassType.MonoBehaviour));\r\n            }\r\n\r\n            foreach (Match m in JSAssetClassNameRegex.Matches(text))\r\n            {\r\n                hints.Add(new JSScriptClassPathHint(sourceFile, modulePath, m.Groups[1].Value, JSScriptClassType.ScriptableObject));\r\n            }\r\n\r\n            foreach (Match m in JSCustomEditorClassNameRegex.Matches(text))\r\n            {\r\n                hints.Add(new JSScriptClassPathHint(sourceFile, modulePath, m.Groups[1].Value, JSScriptClassType.CustomEditor));\r\n            }\r\n\r\n            foreach (Match m in JSEditorWindowClassNameRegex.Matches(text))\r\n            {\r\n                hints.Add(new JSScriptClassPathHint(sourceFile, modulePath, m.Groups[1].Value, JSScriptClassType.EditorWindow));\r\n            }\r\n        }\r\n\r\n        static UnityHelper()\r\n        {\r\n            // EditorApplication.playModeStateChanged += OnPlayModeStateChanged;\r\n        }\r\n\r\n        // private static void OnPlayModeStateChanged(PlayModeStateChange playModeStateChange)\r\n        // {\r\n        //     if (playModeStateChange == PlayModeStateChange.EnteredEditMode)\r\n        //     {\r\n        //         EditorApplication.delayCall += () => ScriptEngine.Shutdown();\r\n        //     }\r\n        // }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/UnityHelper.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: a2bdcad3496b55147b4d1665e163a907\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/UnityJSScriptCompiler.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.IO;\r\nusing System.Text;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using Native;\r\n\r\n    /// utility helps to compile js source into bytecode\r\n    public class UnityJSScriptCompiler : IDisposable\r\n    {\r\n        private JSRuntime _rt;\r\n        private JSContext _ctx;\r\n\r\n        public UnityJSScriptCompiler()\r\n        {\r\n            _rt = JSApi.JSB_NewRuntime(ScriptRuntime.class_finalizer);\r\n            _ctx = JSApi.JS_NewContext(_rt);\r\n            JSApi.JS_AddIntrinsicOperators(_ctx);\r\n        }\r\n\r\n        ~UnityJSScriptCompiler()\r\n        {\r\n            Dispose(false);\r\n        }\r\n\r\n        public unsafe byte[] Compile(string filename, byte[] input_bytes, bool commonJSModule)\r\n        {\r\n            byte[] outputBytes = null;\r\n            try\r\n            {\r\n                byte[] fn_bytes = null;\r\n                if (commonJSModule)\r\n                {\r\n                    input_bytes = Utils.TextUtils.GetShebangNullTerminatedCommonJSBytes(input_bytes);\r\n                }\r\n\r\n                fn_bytes = Utils.TextUtils.GetNullTerminatedBytes(filename);\r\n                fixed (byte* input_ptr = input_bytes)\r\n                fixed (byte* fn_ptr = fn_bytes)\r\n                {\r\n                    var input_len = (size_t)(input_bytes.Length - 1);\r\n                    JSValue rval;\r\n                    if (commonJSModule)\r\n                    {\r\n                        rval = JSApi.JS_CompileSource(_ctx, input_ptr, input_len, fn_ptr);\r\n                    }\r\n                    else\r\n                    {\r\n                        rval = JSApi.JS_CompileModule(_ctx, input_ptr, input_len, fn_ptr);\r\n                    }\r\n\r\n                    if (JSApi.JS_IsException(rval))\r\n                    {\r\n                        JSNative.print_exception(_ctx, \"[ScriptCompiler]\");\r\n                    }\r\n                    else\r\n                    {\r\n                        size_t psize;\r\n                        var byteCode = JSApi.JS_WriteByteCode(_ctx, out psize, rval);\r\n                        JSApi.JS_FreeValue(_ctx, rval);\r\n                        if (byteCode != IntPtr.Zero)\r\n                        {\r\n                            var tagSize = sizeof(uint);\r\n                            uint tagValue = commonJSModule ? ScriptRuntime.BYTECODE_COMMONJS_MODULE_TAG : ScriptRuntime.BYTECODE_ES6_MODULE_TAG;\r\n\r\n                            outputBytes = new byte[psize + tagSize];\r\n                            Buffer.BlockCopy(BitConverter.GetBytes(Utils.TextUtils.ToNetworkByteOrder(tagValue)), 0, outputBytes, 0, tagSize);\r\n                            Marshal.Copy(byteCode, outputBytes, tagSize, psize);\r\n                        }\r\n                        JSApi.js_free(_ctx, byteCode);\r\n                    }\r\n                }\r\n                return outputBytes;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                Diagnostics.Logger.Default.Exception(exception);\r\n                return null;\r\n            }\r\n        }\r\n\r\n        public virtual void Dispose(bool bManaged)\r\n        {\r\n            if (_ctx.IsValid())\r\n            {\r\n                JSApi.JS_FreeContext(_ctx);\r\n                _ctx = JSContext.Null;\r\n            }\r\n\r\n            if (_rt.IsValid())\r\n            {\r\n                JSApi.JSB_FreeRuntime(_rt);\r\n                _rt = JSRuntime.Null;\r\n            }\r\n        }\r\n\r\n        public void Dispose()\r\n        {\r\n            Dispose(true);\r\n            GC.SuppressFinalize(this);\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/UnityJSScriptCompiler.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 415f0d456dbbcbb4b9f993cc27d84df8\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/UnityShellHelper.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Diagnostics;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing System.Text;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    public static class UnityShellHelper\r\n    {\r\n        public static int Run(string command, string arguments, int maxIdleTime)\r\n        {\r\n            return Run(command, arguments, null, maxIdleTime);\r\n        }\r\n\r\n        private static int Run(string command, string arguments, DirectoryInfo workingDirectory, int maxIdleTime)\r\n        {\r\n            var output = new StringBuilder();\r\n            using (var process = new Process())\r\n            {\r\n                process.StartInfo = new ProcessStartInfo()\r\n                {\r\n                    FileName = command,\r\n                    Arguments = arguments,\r\n                    WorkingDirectory = workingDirectory?.FullName ?? new DirectoryInfo(\".\").FullName,\r\n                    RedirectStandardInput = true,\r\n                    RedirectStandardOutput = true,\r\n                    RedirectStandardError = true,\r\n                    CreateNoWindow = true,\r\n                    UseShellExecute = false\r\n                };\r\n                // Prepare data received handlers\r\n                process.OutputDataReceived += (sender, e) =>\r\n                {\r\n                    if (!string.IsNullOrEmpty(e.Data))\r\n                    {\r\n                        output.AppendLine(e.Data);\r\n                        UnityEngine.Debug.Log(e.Data);\r\n                    }\r\n                };\r\n                process.ErrorDataReceived += (sender, e) =>\r\n                {\r\n                    if (!string.IsNullOrEmpty(e.Data))\r\n                    {\r\n                        UnityEngine.Debug.LogError(e.Data);\r\n                    }\r\n                };\r\n                process.Start();\r\n                process.BeginOutputReadLine();\r\n                process.BeginErrorReadLine();\r\n                return WaitForProcess(process, output, maxIdleTime);\r\n            }\r\n        }\r\n\r\n        private static int WaitForProcess(Process process, StringBuilder output, int maxIdleTime)\r\n        {\r\n            while (true)\r\n            {\r\n                var len = output.Length;\r\n                if (process.WaitForExit(maxIdleTime * 1000))\r\n                {\r\n                    // WaitForExit with a timeout will not wait for async event handling operations to finish.\r\n                    // To ensure that async event handling has been completed, call WaitForExit that takes no parameters.\r\n                    // See remarks: https://msdn.microsoft.com/en-us/library/ty0d8k56(v=vs.110)\r\n                    process.WaitForExit();\r\n\r\n                    return process.ExitCode;\r\n                }\r\n                if (output.Length != len)\r\n                {\r\n                    continue;\r\n                }\r\n                // idle for too long with no output? -> kill\r\n                // nb: testing the process threads WaitState doesn't work on OSX\r\n                UnityEngine.Debug.LogError(\"Idle process detected. See console for more details.\");\r\n                process.Kill();\r\n                return -1;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/UnityShellHelper.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 4379e5600ae38c54ba8a035d9dfca5e7\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/jsb.editor.unity.asmdef",
    "content": "{\n    \"name\": \"jsb.editor.unity\",\n    \"rootNamespace\": \"\",\n    \"references\": [\n        \"GUID:118b4ca3a1852354bac065cf952c1e85\",\n        \"GUID:eda0539582471264796e5affb41fe082\",\n        \"GUID:ac4126d60783f3d4a98aee6be9a997aa\",\n        \"GUID:595d45be140461240b6b4358dc45f2c0\"\n    ],\n    \"includePlatforms\": [],\n    \"excludePlatforms\": [],\n    \"allowUnsafeCode\": true,\n    \"overrideReferences\": false,\n    \"precompiledReferences\": [],\n    \"autoReferenced\": true,\n    \"defineConstraints\": [\n        \"UNITY_EDITOR || JSB_RUNTIME_REFLECT_BINDING\"\n    ],\n    \"versionDefines\": [],\n    \"noEngineReferences\": false\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/jsb.editor.unity.asmdef.meta",
    "content": "fileFormatVersion: 2\nguid: 2746379d15af6e84cbeb433df77dd384\nAssemblyDefinitionImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor.meta",
    "content": "fileFormatVersion: 2\r\nguid: eca8a806d86464b4c9c0939da061e24c\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/EditorWindowFix.cs",
    "content": "#if !JSB_UNITYLESS\n#if UNITY_EDITOR\nusing System;\nusing System.Reflection;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace QuickJS.Unity\n{\n    using Native;\n    using Errors;\n    using Binding;\n    using UnityEngine;\n    using UnityEditor;\n\n    public static class EditorWindowFix\n    {\n        [MonoPInvokeCallbackAttribute(typeof(JSCFunction))]\n        public static JSValue BindStatic_GetWindow(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\n        {\n            try\n            {\n                //TODO: 需要补充 GetWindow 其余重载匹配\n                if (argc == 1)\n                {\n                    System.Type arg_editorType;\n                    if (!Values.js_get_classvalue(ctx, argv[0], out arg_editorType))\n                    {\n                        throw new ParameterException(typeof(UnityEditor.EditorWindow), \"GetWindow\", typeof(System.Type), 0);\n                    }\n                    var inject = js_get_window(ctx, argv[0], arg_editorType, false, null, true);\n                    if (!inject.IsUndefined())\n                    {\n                        return inject;\n                    }\n                    var ret = UnityEditor.EditorWindow.GetWindow(arg_editorType);\n                    return Values.js_push_classvalue(ctx, ret);\n                }\n                else if (argc == 2)\n                {\n                    if (Values.js_match_type(ctx, argv[0], typeof(Type)) && Values.js_match_type(ctx, argv[1], typeof(bool)))\n                    {\n                        System.Type arg_editorType;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg_editorType))\n                        {\n                            throw new ParameterException(typeof(UnityEditor.EditorWindow), \"GetWindow\", typeof(System.Type), 0);\n                        }\n                        bool arg_utility;\n                        if (!Values.js_get_primitive(ctx, argv[1], out arg_utility))\n                        {\n                            throw new ParameterException(typeof(UnityEditor.EditorWindow), \"GetWindow\", typeof(bool), 1);\n                        }\n                        var inject = js_get_window(ctx, argv[0], arg_editorType, arg_utility, null, true);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = UnityEditor.EditorWindow.GetWindow(arg_editorType);\n                        return Values.js_push_classvalue(ctx, ret);\n                    }\n                }\n                else if (argc == 3)\n                {\n                    if (Values.js_match_type(ctx, argv[0], typeof(Type)) && Values.js_match_type(ctx, argv[1], typeof(bool)) && Values.js_match_type(ctx, argv[2], typeof(string)))\n                    {\n                        System.Type arg_editorType;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg_editorType))\n                        {\n                            throw new ParameterException(typeof(UnityEditor.EditorWindow), \"GetWindow\", typeof(System.Type), 0);\n                        }\n                        bool arg_utility;\n                        if (!Values.js_get_primitive(ctx, argv[1], out arg_utility))\n                        {\n                            throw new ParameterException(typeof(UnityEditor.EditorWindow), \"GetWindow\", typeof(bool), 1);\n                        }\n                        string arg_title;\n                        if (!Values.js_get_primitive(ctx, argv[2], out arg_title))\n                        {\n                            throw new ParameterException(typeof(UnityEditor.EditorWindow), \"GetWindow\", typeof(string), 2);\n                        }\n                        var inject = js_get_window(ctx, argv[0], arg_editorType, arg_utility, arg_title, true);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = UnityEditor.EditorWindow.GetWindow(arg_editorType);\n                        return Values.js_push_classvalue(ctx, ret);\n                    }\n                }\n                else if (argc == 4)\n                {\n                    if (Values.js_match_type(ctx, argv[0], typeof(Type)) && Values.js_match_type(ctx, argv[1], typeof(bool)) && Values.js_match_type(ctx, argv[2], typeof(string)) && Values.js_match_type(ctx, argv[3], typeof(bool)))\n                    {\n                        System.Type arg_editorType;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg_editorType))\n                        {\n                            throw new ParameterException(typeof(UnityEditor.EditorWindow), \"GetWindow\", typeof(System.Type), 0);\n                        }\n                        bool arg_utility;\n                        if (!Values.js_get_primitive(ctx, argv[1], out arg_utility))\n                        {\n                            throw new ParameterException(typeof(UnityEditor.EditorWindow), \"GetWindow\", typeof(bool), 1);\n                        }\n                        string arg_title;\n                        if (!Values.js_get_primitive(ctx, argv[2], out arg_title))\n                        {\n                            throw new ParameterException(typeof(UnityEditor.EditorWindow), \"GetWindow\", typeof(string), 2);\n                        }\n                        bool arg_focus;\n                        if (!Values.js_get_primitive(ctx, argv[3], out arg_focus))\n                        {\n                            throw new ParameterException(typeof(UnityEditor.EditorWindow), \"GetWindow\", typeof(bool), 3);\n                        }\n                        var inject = js_get_window(ctx, argv[0], arg_editorType, arg_utility, arg_title, arg_focus);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = UnityEditor.EditorWindow.GetWindow(arg_editorType);\n                        return Values.js_push_classvalue(ctx, ret);\n                    }\n                }\n                throw new NoSuitableMethodException(\"GetWindow\", argc);\n            }\n            catch (Exception exception)\n            {\n                return ctx.ThrowException(exception);\n            }\n        }\n\n        // as extended method\n        // public static T CreateWindow<T>(string title, params Type[] desiredDockNextTo) where T : EditorWindow\n        // public static T CreateWindow<T>(params Type[] desiredDockNextTo) where T : EditorWindow\n        [JSCFunction(true,\n            \"<T extends EditorWindow>(type: { new(): T }, ...desiredDockNextTo: any[]): T\",\n            \"<T extends EditorWindow>(type: { new(): T }, title: string, ...desiredDockNextTo: any[]): T\")]\n        public static JSValue CreateWindow(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\n        {\n            if (argc == 0 || JSApi.JS_IsConstructor(ctx, argv[0]) != 1)\n            {\n                throw new ParameterException(\"type\", typeof(Type), 0);\n            }\n\n            if (argc > 1)\n            {\n                var firstAsTitle = argv[1].IsString() || argv[1].IsNullish();\n                var title = firstAsTitle ? JSApi.GetString(ctx, argv[1]) : null;\n                var firstArgIndex = firstAsTitle ? 2 : 1;\n\n                return _new_js_editor_window(ctx, argv[0], false, title, argv, firstArgIndex);\n            }\n\n            return _new_js_editor_window(ctx, argv[0], false, null, null, 0);\n        }\n\n        //TODO fix type checking\n        private static bool __type_equals(EditorWindow editorWindow, JSContext ctx, JSValue value)\n        {\n            var jsEditorWindow = editorWindow as JSEditorWindow;\n            if (jsEditorWindow != null)\n            {\n                if (jsEditorWindow.IsInstanceOf(value) == 1)\n                {\n                    return true;\n                }\n            }\n\n            Type type;\n            if (Values.js_get_classvalue(ctx, value, out type))\n            {\n                var editorWindowType = editorWindow.GetType();\n                if (editorWindowType == type || editorWindowType.IsSubclassOf(type))\n                {\n                    return true;\n                }\n            }\n\n            return false;\n        }\n\n        private static bool __dock(EditorWindow val, JSContext ctx, JSValue[] desiredDockNextTo)\n        {\n            if (desiredDockNextTo == null || desiredDockNextTo.Length == 0)\n            {\n                return false;\n            }\n\n            try\n            {\n                var ContainerWindow = typeof(EditorWindow).Assembly.GetType(\"UnityEditor.ContainerWindow\");\n                var ContainerWindow_windows = ContainerWindow.GetProperty(\"windows\", BindingFlags.Public | BindingFlags.Static);\n                var ContainerWindow_rootView = ContainerWindow.GetProperty(\"rootView\", BindingFlags.Public | BindingFlags.Instance);\n\n                var View = typeof(EditorWindow).Assembly.GetType(\"UnityEditor.View\");\n                var View_allChildren = View.GetProperty(\"allChildren\", BindingFlags.Public | BindingFlags.Instance);\n                var DockArea = typeof(EditorWindow).Assembly.GetType(\"UnityEditor.DockArea\");\n                var DockArea_Panes = DockArea.GetField(\"m_Panes\", BindingFlags.NonPublic | BindingFlags.Instance);\n                var DockArea_AddTab = DockArea.GetMethod(\"AddTab\", new Type[] { typeof(EditorWindow), typeof(bool) });\n\n                // foreach (var desired in desiredDockNextTo)\n                for (var dIndex = 0; dIndex < desiredDockNextTo.Length; dIndex++)\n                {\n                    var desired = desiredDockNextTo[dIndex];\n                    // ContainerWindow[]\n                    var windows = (Array)ContainerWindow_windows.GetMethod.Invoke(null, null);\n                    for (var wIndex = 0; wIndex < windows.Length; wIndex++)\n                    {\n                        var containerWindow = windows.GetValue(wIndex);\n                        var rootView = ContainerWindow_rootView.GetMethod.Invoke(containerWindow, null);\n                        // View[]\n                        var allChildren = (Array)View_allChildren.GetMethod.Invoke(rootView, null);\n                        for (var vIndex = 0; vIndex < allChildren.Length; vIndex++)\n                        {\n                            var view = allChildren.GetValue(vIndex);\n                            var dockArea = view; //  as DockArea\n\n                            // DockArea.m_Panes: internal List<EditorWindow> \n                            if (!((UnityEngine.Object)dockArea == null) && DockArea.IsInstanceOfType(dockArea))\n                            {\n                                if ((DockArea_Panes.GetValue(dockArea) as List<EditorWindow>).Any((EditorWindow pane) => __type_equals(pane, ctx, desired)))\n                                {\n                                    DockArea_AddTab.Invoke(dockArea, new object[] { val, true }); // dockArea.AddTab(val);\n                                    return true;\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n            catch (Exception exception)\n            {\n                Debug.LogError(exception);\n            }\n\n            return false;\n        }\n\n        // inject: GetWindow(Type)\n        public static JSValue js_get_window(JSContext ctx, JSValue ctor, Type type, bool utility, string title, bool focus)\n        {\n            if (JSApi.JS_IsConstructor(ctx, ctor) == 1)\n            {\n                var header = JSApi.jsb_get_payload_header(ctx, ctor);\n                if (header.type_id == BridgeObjectType.None) // it's a plain js value\n                {\n                    if (type == typeof(EditorWindow))\n                    {\n                        var bridgeValue = _js_get_window_clone(ctx, ctor, utility, title, focus);\n                        if (!bridgeValue.IsUndefined())\n                        {\n                            return bridgeValue;\n                        }\n\n                        return JSApi.JS_NULL; // or return an empty array?\n                    }\n                }\n            }\n\n            return JSApi.JS_UNDEFINED;\n        }\n\n        private static JSValue _js_get_window_clone(JSContext ctx, JSValue ctor, bool utility, string title, bool focus)\n        {\n            var t = typeof(JSEditorWindow);\n            var array = Resources.FindObjectsOfTypeAll(t);\n            var editorWindow = _get_js_editor_window(array, ctor);\n            if (!editorWindow)\n            {\n                return _new_js_editor_window(ctx, ctor, utility, title, null, 0);\n            }\n            else if (focus)\n            {\n                editorWindow.Show();\n                editorWindow.Focus();\n            }\n\n            return editorWindow.CloneValue();\n        }\n\n        private static JSValue _new_js_editor_window(JSContext ctx, JSValue ctor, bool utility, string title, JSValue[] desiredDockNextTo, int desiredDockNextToOffset)\n        {\n            var editorWindow = ScriptableObject.CreateInstance<JSEditorWindow>();\n            var val = editorWindow.SetScriptInstance(ctx, ctor, true);\n\n            if (val.IsUndefined())\n            {\n                editorWindow.ReleaseScriptInstance();\n                Object.DestroyImmediate(editorWindow);\n                return ctx.ThrowInternalError(\"failed to bind script\");\n            }\n\n            if (title != null)\n            {\n                editorWindow.titleContent = new GUIContent(title);\n            }\n\n            __dock(editorWindow, ctx, desiredDockNextTo);\n            if (utility)\n            {\n                editorWindow.ShowUtility();\n            }\n            else\n            {\n                editorWindow.Show();\n            }\n\n            return val;\n        }\n\n        private static JSEditorWindow _get_js_editor_window(Object[] array, JSValue ctor)\n        {\n            for (int i = 0, len = array.Length; i < len; i++)\n            {\n                var ew = (JSEditorWindow)array[i];\n                if (ew.IsInstanceOf(ctor) == 1)\n                {\n                    return ew;\n                }\n            }\n            return null;\n        }\n    }\n}\n#endif\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/EditorWindowFix.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 75488ab2780cee646867983c07e2f785\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/GameObjectFix.cs",
    "content": "#if !JSB_UNITYLESS\nusing System;\n\nnamespace QuickJS.Unity\n{\n    using Native;\n    using Errors;\n    using Binding;\n\n    public static class GameObjectFix\n    {\n        [MonoPInvokeCallbackAttribute(typeof(JSCFunction))]\n        public static JSValue Bind_AddComponent(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\n        {\n            try\n            {\n                if (argc == 1)\n                {\n                    UnityEngine.GameObject self;\n                    if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                    {\n                        throw new ThisBoundException();\n                    }\n                    System.Type arg0;\n                    if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                    {\n                        throw new ParameterException(typeof(UnityEngine.GameObject), \"AddComponent\", typeof(System.Type), 0);\n                    }\n                    var inject = Values._js_game_object_add_component(ctx, argv[0], self, arg0);\n                    if (!inject.IsUndefined())\n                    {\n                        return inject;\n                    }\n                    var ret = self.AddComponent(arg0);\n                    return Values.js_push_classvalue(ctx, ret);\n                }\n                throw new NoSuitableMethodException(\"AddComponent\", argc);\n            }\n            catch (Exception exception)\n            {\n                return ctx.ThrowException(exception);\n            }\n        }\n\n        [MonoPInvokeCallbackAttribute(typeof(JSCFunction))]\n        public static JSValue Bind_GetComponent(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\n        {\n            try\n            {\n                do\n                {\n                    if (argc == 1)\n                    {\n                        if (Values.js_match_type(ctx, argv[0], typeof(System.Type)))\n                        {\n                            UnityEngine.GameObject self;\n                            if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                            {\n                                throw new ThisBoundException();\n                            }\n                            System.Type arg0;\n                            if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                            {\n                                throw new ParameterException(typeof(UnityEngine.GameObject), \"GetComponent\", typeof(System.Type), 0);\n                            }\n                            var inject = Values._js_game_object_get_component(ctx, argv[0], self, arg0);\n                            if (!inject.IsUndefined())\n                            {\n                                return inject;\n                            }\n                            var ret = self.GetComponent(arg0);\n                            return Values.js_push_classvalue(ctx, ret);\n                        }\n                        if (Values.js_match_type(ctx, argv[0], typeof(string)))\n                        {\n                            UnityEngine.GameObject self;\n                            if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                            {\n                                throw new ThisBoundException();\n                            }\n                            string arg0;\n                            if (!Values.js_get_primitive(ctx, argv[0], out arg0))\n                            {\n                                throw new ParameterException(typeof(UnityEngine.GameObject), \"GetComponent\", typeof(string), 0);\n                            }\n                            var ret = self.GetComponent(arg0);\n                            return Values.js_push_classvalue(ctx, ret);\n                        }\n                    }\n                } while (false);\n                throw new NoSuitableMethodException(\"GetComponent\", argc);\n            }\n            catch (Exception exception)\n            {\n                return ctx.ThrowException(exception);\n            }\n        }\n\n        [MonoPInvokeCallbackAttribute(typeof(JSCFunction))]\n        public static JSValue Bind_GetComponentInChildren(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\n        {\n            try\n            {\n                do\n                {\n                    if (argc == 2)\n                    {\n                        UnityEngine.GameObject self;\n                        if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                        {\n                            throw new ThisBoundException();\n                        }\n                        System.Type arg0;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.GameObject), \"GetComponentInChildren\", typeof(System.Type), 0);\n                        }\n                        bool arg1;\n                        if (!Values.js_get_primitive(ctx, argv[1], out arg1))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.GameObject), \"GetComponentInChildren\", typeof(bool), 1);\n                        }\n                        var inject = Values._js_game_object_get_component_in_children(ctx, argv[0], self, arg0, arg1);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = self.GetComponentInChildren(arg0, arg1);\n                        return Values.js_push_classvalue(ctx, ret);\n                    }\n                    if (argc == 1)\n                    {\n                        UnityEngine.GameObject self;\n                        if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                        {\n                            throw new ThisBoundException();\n                        }\n                        System.Type arg0;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.GameObject), \"GetComponentInChildren\", typeof(System.Type), 0);\n                        }\n                        var inject = Values._js_game_object_get_component_in_children(ctx, argv[0], self, arg0, false);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = self.GetComponentInChildren(arg0);\n                        return Values.js_push_classvalue(ctx, ret);\n                    }\n                } while (false);\n                throw new NoSuitableMethodException(\"GetComponentInChildren\", argc);\n            }\n            catch (Exception exception)\n            {\n                return ctx.ThrowException(exception);\n            }\n        }\n\n        [MonoPInvokeCallbackAttribute(typeof(JSCFunction))]\n        public static JSValue Bind_GetComponentInParent(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\n        {\n            try\n            {\n                if (argc == 1)\n                {\n                    UnityEngine.GameObject self;\n                    if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                    {\n                        throw new ThisBoundException();\n                    }\n                    System.Type arg0;\n                    if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                    {\n                        throw new ParameterException(typeof(UnityEngine.GameObject), \"GetComponentInParent\", typeof(System.Type), 0);\n                    }\n                    var inject = Values._js_game_object_get_component_in_parent(ctx, argv[0], self, arg0, false);\n                    if (!inject.IsUndefined())\n                    {\n                        return inject;\n                    }\n                    var ret = self.GetComponentInParent(arg0);\n                    return Values.js_push_classvalue(ctx, ret);\n                }\n                throw new NoSuitableMethodException(\"GetComponentInParent\", argc);\n            }\n            catch (Exception exception)\n            {\n                return ctx.ThrowException(exception);\n            }\n        }\n\n        [MonoPInvokeCallbackAttribute(typeof(JSCFunction))]\n        public static JSValue Bind_GetComponents(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\n        {\n            try\n            {\n                do\n                {\n                    if (argc == 2)\n                    {\n                        UnityEngine.GameObject self;\n                        if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                        {\n                            throw new ThisBoundException();\n                        }\n                        System.Type arg0;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.GameObject), \"GetComponents\", typeof(System.Type), 0);\n                        }\n                        System.Collections.Generic.List<UnityEngine.Component> arg1;\n                        if (!Values.js_get_classvalue(ctx, argv[1], out arg1))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.GameObject), \"GetComponents\", typeof(System.Collections.Generic.List<UnityEngine.Component>), 1);\n                        }\n                        var inject = Values._js_game_object_get_components(ctx, argv[0], self, arg0, arg1);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        self.GetComponents(arg0, arg1);\n                        return JSApi.JS_UNDEFINED;\n                    }\n                    if (argc == 1)\n                    {\n                        UnityEngine.GameObject self;\n                        if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                        {\n                            throw new ThisBoundException();\n                        }\n                        System.Type arg0;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.GameObject), \"GetComponents\", typeof(System.Type), 0);\n                        }\n                        var inject = Values._js_game_object_get_components(ctx, argv[0], self, arg0);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = self.GetComponents(arg0);\n                        return Values.PushArray(ctx, ret);\n                    }\n                } while (false);\n                throw new NoSuitableMethodException(\"GetComponents\", argc);\n            }\n            catch (Exception exception)\n            {\n                return ctx.ThrowException(exception);\n            }\n        }\n\n        [MonoPInvokeCallbackAttribute(typeof(JSCFunction))]\n        public static JSValue Bind_GetComponentsInChildren(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\n        {\n            try\n            {\n                do\n                {\n                    if (argc == 2)\n                    {\n                        UnityEngine.GameObject self;\n                        if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                        {\n                            throw new ThisBoundException();\n                        }\n                        System.Type arg0;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.GameObject), \"GetComponentsInChildren\", typeof(System.Type), 0);\n                        }\n                        bool arg1;\n                        if (!Values.js_get_primitive(ctx, argv[1], out arg1))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.GameObject), \"GetComponentsInChildren\", typeof(bool), 1);\n                        }\n                        var inject = Values._js_game_object_get_components_in_children(ctx, argv[0], self, arg0, arg1);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = self.GetComponentsInChildren(arg0, arg1);\n                        return Values.PushArray(ctx, ret);\n                    }\n                    if (argc == 1)\n                    {\n                        UnityEngine.GameObject self;\n                        if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                        {\n                            throw new ThisBoundException();\n                        }\n                        System.Type arg0;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.GameObject), \"GetComponentsInChildren\", typeof(System.Type), 0);\n                        }\n                        var inject = Values._js_game_object_get_components_in_children(ctx, argv[0], self, arg0, false);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = self.GetComponentsInChildren(arg0);\n                        return Values.PushArray(ctx, ret);\n                    }\n                } while (false);\n                throw new NoSuitableMethodException(\"GetComponentsInChildren\", argc);\n            }\n            catch (Exception exception)\n            {\n                return ctx.ThrowException(exception);\n            }\n        }\n\n        [MonoPInvokeCallbackAttribute(typeof(JSCFunction))]\n        public static JSValue Bind_GetComponentsInParent(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\n        {\n            try\n            {\n                do\n                {\n                    if (argc == 2)\n                    {\n                        UnityEngine.GameObject self;\n                        if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                        {\n                            throw new ThisBoundException();\n                        }\n                        System.Type arg0;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.GameObject), \"GetComponentsInParent\", typeof(System.Type), 0);\n                        }\n                        bool arg1;\n                        if (!Values.js_get_primitive(ctx, argv[1], out arg1))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.GameObject), \"GetComponentsInParent\", typeof(bool), 1);\n                        }\n                        var inject = Values._js_game_object_get_components_in_parent(ctx, argv[0], self, arg0, arg1);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = self.GetComponentsInParent(arg0, arg1);\n                        return Values.PushArray(ctx, ret);\n                    }\n                    if (argc == 1)\n                    {\n                        UnityEngine.GameObject self;\n                        if (!Values.js_get_classvalue(ctx, this_obj, out self))\n                        {\n                            throw new ThisBoundException();\n                        }\n                        System.Type arg0;\n                        if (!Values.js_get_classvalue(ctx, argv[0], out arg0))\n                        {\n                            throw new ParameterException(typeof(UnityEngine.GameObject), \"GetComponentsInParent\", typeof(System.Type), 0);\n                        }\n                        var inject = Values._js_game_object_get_components_in_parent(ctx, argv[0], self, arg0, false);\n                        if (!inject.IsUndefined())\n                        {\n                            return inject;\n                        }\n                        var ret = self.GetComponentsInParent(arg0);\n                        return Values.PushArray(ctx, ret);\n                    }\n                } while (false);\n                throw new NoSuitableMethodException(\"GetComponentsInParent\", argc);\n            }\n            catch (Exception exception)\n            {\n                return ctx.ThrowException(exception);\n            }\n        }\n    }\n}\n#endif // !JSB_UNITYLESS"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/GameObjectFix.cs.meta",
    "content": "fileFormatVersion: 2\nguid: f7b186cd0be52224f84af7900e3dc03b\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Hotfix/Editor/HotfixUtil.cs",
    "content": "﻿#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing Mono.Cecil;\r\nusing Mono.Cecil.Cil;\r\n\r\nnamespace QuickJS.Unity.Experimental.Hotfix\r\n{\r\n    using UnityEditor;\r\n    using UnityEngine;\r\n\r\n    //TODO: 热更功能临时代码\r\n    public class HotfixUtil\r\n    {\r\n        private const string TypeNameForInjectFlag = \"_jsb_injected_flag_\";\r\n\r\n        [MenuItem(\"JS Bridge/Hotfix\")]\r\n        public static void RunHotfix()\r\n        {\r\n            Run();\r\n        }\r\n\r\n        private static bool IsHotfixTarget(TypeDefinition td)\r\n        {\r\n            foreach (var attr in td.CustomAttributes)\r\n            {\r\n                if (attr.AttributeType.FullName == typeof(QuickJS.JSHotfixAttribute).FullName)\r\n                {\r\n                    return true;\r\n                }\r\n            }\r\n            return false;\r\n        }\r\n\r\n        public static bool Collect(AssemblyDefinition a, List<TypeDefinition> delegateTypes)\r\n        {\r\n            foreach (var type in a.MainModule.Types)\r\n            {\r\n                if (type.Name == TypeNameForInjectFlag)\r\n                {\r\n                    return false;\r\n                }\r\n                if (type.FullName == \"jsb._QuickJSDelegates\")\r\n                {\r\n                    foreach (var nested in type.NestedTypes)\r\n                    {\r\n                        if (nested.BaseType.FullName == \"System.MulticastDelegate\")\r\n                        {\r\n                            delegateTypes.Add(nested);\r\n                            // Debug.LogFormat(\"Nest: {0} based {1} in {2}\", nested.FullName, nested.BaseType.FullName, type.FullName);\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n            return true;\r\n        }\r\n\r\n        public static bool IsParameterMatched(ParameterDefinition p1, ParameterDefinition p2)\r\n        {\r\n            return p1.ParameterType == p2.ParameterType && p1.IsOut == p2.IsOut;\r\n        }\r\n\r\n        // 方法定义是否与 hotfix 委托定义匹配\r\n        public static bool IsDelegateMatched(MethodDefinition m, TypeReference returnType, TypeDefinition d)\r\n        {\r\n            var invoke = d.Methods.First(dm => dm.Name == \"Invoke\");\r\n            var argc = invoke.Parameters.Count;\r\n            if (argc != m.Parameters.Count + 1)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (invoke.ReturnType != returnType)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (invoke.Parameters[0].IsOut)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (m.IsStatic)\r\n            {\r\n                if (invoke.Parameters[0].ParameterType.FullName != \"System.Type\")\r\n                {\r\n                    return false;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                if (invoke.Parameters[0].ParameterType.FullName != \"System.Object\")\r\n                {\r\n                    return false;\r\n                }\r\n            }\r\n\r\n            for (var i = 1; i < argc; i++)\r\n            {\r\n                var p1 = invoke.Parameters[i];\r\n                var p2 = m.Parameters[i - 1];\r\n\r\n                if (!IsParameterMatched(p1, p2))\r\n                {\r\n                    return false;\r\n                }\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n        // 从 Delegate 定义池中找一个匹配的\r\n        public static TypeDefinition GetDelegate(MethodDefinition m, TypeReference returnType, List<TypeDefinition> list)\r\n        {\r\n            if (m.Name != \".cctor\")\r\n            {\r\n                for (var i = 0; i < list.Count; i++)\r\n                {\r\n                    var item = list[i];\r\n                    if (IsDelegateMatched(m, returnType, item))\r\n                    {\r\n                        return item;\r\n                    }\r\n                }\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        public static string GetMethodString(MethodDefinition method)\r\n        {\r\n            var sb = \"\";\r\n            sb += $\"{method.ReturnType} \";\r\n            sb += $\"{method.DeclaringType.FullName}.\";\r\n            sb += $\"{method.Name}(\";\r\n            for (var i = 0; i < method.Parameters.Count; i++)\r\n            {\r\n                var p = method.Parameters[i];\r\n                sb += $\"{p.ParameterType} {p.Name}\";\r\n                if (i != method.Parameters.Count - 1)\r\n                {\r\n                    sb += \", \";\r\n                }\r\n            }\r\n            sb += \");\";\r\n\r\n            return sb;\r\n        }\r\n\r\n        private static OpCode[] ldarg_i_table = new OpCode[] { OpCodes.Ldarg_0, OpCodes.Ldarg_1, OpCodes.Ldarg_2, OpCodes.Ldarg_3 };\r\n\r\n        private static Instruction FindPatchPoint(MethodBody body)\r\n        {\r\n            var instructions = body.Instructions;\r\n            return instructions.Count > 0 ? instructions[0] : null;\r\n        }\r\n\r\n        private static string GetHotfixFieldName_r(MethodDefinition method, HashSet<string> set)\r\n        {\r\n            var plainName = method.IsConstructor ? \"_JSFIX_RC_\" + method.Name.Replace(\".\", \"\") : \"_JSFIX_R_\" + method.Name;\r\n            var index = 0;\r\n            var serialName = plainName + \"_\" + index;\r\n\r\n            while (set.Contains(serialName))\r\n            {\r\n                serialName = plainName + \"_\" + ++index;\r\n            }\r\n\r\n            set.Add(serialName);\r\n            return serialName;\r\n        }\r\n\r\n        private static string GetHotfixFieldName_b(MethodDefinition method, HashSet<string> set)\r\n        {\r\n            var plainName = method.IsConstructor ? \"_JSFIX_BC_\" + method.Name.Replace(\".\", \"\") : \"_JSFIX_B_\" + method.Name;\r\n            var index = 0;\r\n            var serialName = plainName + \"_\" + index;\r\n\r\n            while (set.Contains(serialName))\r\n            {\r\n                serialName = plainName + \"_\" + ++index;\r\n            }\r\n\r\n            return serialName;\r\n        }\r\n\r\n        public static void Run()\r\n        {\r\n            var testAssembly = Binding.BindingManager.TryGetAssembly(\"Assembly-CSharp\");\r\n            if (testAssembly == null)\r\n            {\r\n                return;\r\n            }\r\n            var assemblyFilePath = testAssembly.Location;\r\n            var a = AssemblyDefinition.ReadAssembly(assemblyFilePath);\r\n            var delegateTypes = new List<TypeDefinition>();\r\n            var modified = false;\r\n\r\n            if (!Collect(a, delegateTypes))\r\n            {\r\n                Debug.LogError(\"dirty dll\");\r\n                return;\r\n            }\r\n\r\n            foreach (var type in a.MainModule.Types)\r\n            {\r\n                //TODO: 改为通过列表而不是 Attribute 判断\r\n                if (!IsHotfixTarget(type))\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                var sb = $\"{type.FullName}\\n\";\r\n                var hotfixRegs = new HashSet<string>();\r\n                foreach (var method in type.Methods)\r\n                {\r\n                    var delegateType_r = GetDelegate(method, method.ReturnType, delegateTypes);\r\n                    var delegateType_b = GetDelegate(method, a.MainModule.TypeSystem.Void, delegateTypes);\r\n                    if (delegateType_r == null)\r\n                    {\r\n                        continue;\r\n                    }\r\n                    var hotfixFieldName_r = GetHotfixFieldName_r(method, hotfixRegs);\r\n                    var signatureLit = GetMethodString(method);\r\n\r\n                    var point = FindPatchPoint(method.Body);\r\n                    if (point == null)\r\n                    {\r\n                        Debug.LogWarningFormat(\"no patch point in {0}\", signatureLit);\r\n                        continue;\r\n                    }\r\n\r\n                    modified = true;\r\n                    var argCount = method.IsStatic ? method.Parameters.Count : method.Parameters.Count + 1;\r\n                    var proc = method.Body.GetILProcessor();\r\n                    var boolVar = new VariableDefinition(a.MainModule.TypeSystem.Boolean);\r\n                    method.Body.Variables.Add(boolVar);\r\n\r\n                    if (delegateType_b != null)\r\n                    {\r\n                        var hotfixFieldName_b = GetHotfixFieldName_b(method, hotfixRegs);\r\n                        var delegateField_b = new FieldDefinition(hotfixFieldName_b, FieldAttributes.Public | FieldAttributes.Static, delegateType_b);\r\n                        var localPoint = point;\r\n\r\n                        type.Fields.Add(delegateField_b);\r\n                        proc.InsertBefore(localPoint, point = proc.Create(OpCodes.Ldsfld, delegateField_b));\r\n                        proc.InsertBefore(localPoint, proc.Create(OpCodes.Ldnull));\r\n                        proc.InsertBefore(localPoint, proc.Create(OpCodes.Cgt_Un));\r\n                        proc.InsertBefore(localPoint, proc.Create(OpCodes.Stloc, boolVar));\r\n                        proc.InsertBefore(localPoint, proc.Create(OpCodes.Ldloc, boolVar));\r\n                        proc.InsertBefore(localPoint, proc.Create(OpCodes.Brfalse_S, localPoint)); // jump to original instructions\r\n                        proc.InsertBefore(localPoint, proc.Create(OpCodes.Ldsfld, delegateField_b));\r\n\r\n                        if (method.IsStatic)\r\n                        {\r\n                            var refGetTypeFromHandle = a.MainModule.ImportReference(typeof(Type).GetMethod(\"GetTypeFromHandle\"));\r\n                            proc.InsertBefore(localPoint, proc.Create(OpCodes.Ldtoken, type));\r\n                            proc.InsertBefore(localPoint, proc.Create(OpCodes.Call, refGetTypeFromHandle));\r\n                        }\r\n\r\n                        for (var argIndex = 0; argIndex < argCount; argIndex++)\r\n                        {\r\n                            var ldarg_i = argIndex;\r\n                            if (ldarg_i < ldarg_i_table.Length)\r\n                            {\r\n                                proc.InsertBefore(localPoint, proc.Create(ldarg_i_table[ldarg_i]));\r\n                            }\r\n                            else if (ldarg_i <= byte.MaxValue)\r\n                            {\r\n                                proc.InsertBefore(localPoint, proc.Create(OpCodes.Ldarg_S, (byte)ldarg_i));\r\n                            }\r\n                            else\r\n                            {\r\n                                proc.InsertBefore(localPoint, proc.Create(OpCodes.Ldarg, ldarg_i));\r\n                            }\r\n                        }\r\n                        var invoke_b = delegateType_b.Methods.First(dm => dm.Name == \"Invoke\");\r\n                        proc.InsertBefore(localPoint, proc.Create(OpCodes.Callvirt, invoke_b));\r\n                    }\r\n\r\n                    if (delegateType_r != null)\r\n                    {\r\n                        var delegateField_r = new FieldDefinition(hotfixFieldName_r, FieldAttributes.Public | FieldAttributes.Static, delegateType_r);\r\n                        var localPoint = point;\r\n\r\n                        type.Fields.Add(delegateField_r);\r\n                        proc.InsertBefore(localPoint, point = proc.Create(OpCodes.Ldsfld, delegateField_r));\r\n                        proc.InsertBefore(localPoint, proc.Create(OpCodes.Ldnull));\r\n                        proc.InsertBefore(localPoint, proc.Create(OpCodes.Cgt_Un));\r\n                        proc.InsertBefore(localPoint, proc.Create(OpCodes.Stloc, boolVar));\r\n                        proc.InsertBefore(localPoint, proc.Create(OpCodes.Ldloc, boolVar));\r\n                        proc.InsertBefore(localPoint, proc.Create(OpCodes.Brfalse_S, localPoint)); // jump to original instructions\r\n                        proc.InsertBefore(localPoint, proc.Create(OpCodes.Ldsfld, delegateField_r));\r\n\r\n                        if (method.IsStatic)\r\n                        {\r\n                            var refGetTypeFromHandle = a.MainModule.ImportReference(typeof(Type).GetMethod(\"GetTypeFromHandle\"));\r\n                            proc.InsertBefore(localPoint, proc.Create(OpCodes.Ldtoken, type));\r\n                            proc.InsertBefore(localPoint, proc.Create(OpCodes.Call, refGetTypeFromHandle));\r\n                        }\r\n\r\n                        for (var argIndex = 0; argIndex < argCount; argIndex++)\r\n                        {\r\n                            var ldarg_i = argIndex;\r\n                            if (ldarg_i < ldarg_i_table.Length)\r\n                            {\r\n                                proc.InsertBefore(localPoint, proc.Create(ldarg_i_table[ldarg_i]));\r\n                            }\r\n                            else if (ldarg_i <= byte.MaxValue)\r\n                            {\r\n                                proc.InsertBefore(localPoint, proc.Create(OpCodes.Ldarg_S, (byte)ldarg_i));\r\n                            }\r\n                            else\r\n                            {\r\n                                proc.InsertBefore(localPoint, proc.Create(OpCodes.Ldarg, ldarg_i));\r\n                            }\r\n                        }\r\n                        var invoke_r = delegateType_r.Methods.First(dm => dm.Name == \"Invoke\");\r\n                        proc.InsertBefore(localPoint, proc.Create(OpCodes.Callvirt, invoke_r));\r\n                        proc.InsertBefore(localPoint, proc.Create(OpCodes.Ret));\r\n                    }\r\n\r\n                    sb += hotfixFieldName_r + \" > \" + signatureLit;\r\n                    sb += \"\\n\";\r\n                }\r\n                Debug.LogFormat(\"{0}\", sb);\r\n            }\r\n\r\n            if (modified)\r\n            {\r\n                a.MainModule.Types.Add(new TypeDefinition(\"QuickJS\", TypeNameForInjectFlag, Mono.Cecil.TypeAttributes.Class, a.MainModule.TypeSystem.Object));\r\n                a.Write(assemblyFilePath);\r\n                // a.Write(\"temp.dll\");\r\n                Debug.LogFormat(\"write: {0}\", assemblyFilePath);\r\n            }\r\n            else\r\n            {\r\n                Debug.LogWarningFormat(\"no change\");\r\n            }\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Hotfix/Editor/HotfixUtil.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: b0e8d91143bed454c90fd461485b2089\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Hotfix/Editor/Plugins/Unity.Cecil.Mdb.dll.meta",
    "content": "fileFormatVersion: 2\r\nguid: 226114ec6853e9b4694b3f0a48aa41fc\r\nPluginImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  iconMap: {}\r\n  executionOrder: {}\r\n  defineConstraints: []\r\n  isPreloaded: 0\r\n  isOverridable: 0\r\n  isExplicitlyReferenced: 0\r\n  validateReferences: 1\r\n  platformData:\r\n  - first:\r\n      Any: \r\n    second:\r\n      enabled: 0\r\n      settings: {}\r\n  - first:\r\n      Editor: Editor\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        DefaultValueInitialized: true\r\n  - first:\r\n      Windows Store Apps: WindowsStoreApps\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Hotfix/Editor/Plugins/Unity.Cecil.Pdb.dll.meta",
    "content": "fileFormatVersion: 2\r\nguid: 5b0af44536dc7564384347c55b64e4c9\r\nPluginImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  iconMap: {}\r\n  executionOrder: {}\r\n  defineConstraints: []\r\n  isPreloaded: 0\r\n  isOverridable: 0\r\n  isExplicitlyReferenced: 0\r\n  validateReferences: 1\r\n  platformData:\r\n  - first:\r\n      Any: \r\n    second:\r\n      enabled: 0\r\n      settings: {}\r\n  - first:\r\n      Editor: Editor\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        DefaultValueInitialized: true\r\n  - first:\r\n      Windows Store Apps: WindowsStoreApps\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Hotfix/Editor/Plugins/Unity.Cecil.dll.meta",
    "content": "fileFormatVersion: 2\r\nguid: cf55851fa2120e0489592be4bbd7f3a8\r\nPluginImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  iconMap: {}\r\n  executionOrder: {}\r\n  defineConstraints: []\r\n  isPreloaded: 0\r\n  isOverridable: 0\r\n  isExplicitlyReferenced: 0\r\n  validateReferences: 1\r\n  platformData:\r\n  - first:\r\n      Any: \r\n    second:\r\n      enabled: 0\r\n      settings: {}\r\n  - first:\r\n      Editor: Editor\r\n    second:\r\n      enabled: 1\r\n      settings:\r\n        DefaultValueInitialized: true\r\n  - first:\r\n      Windows Store Apps: WindowsStoreApps\r\n    second:\r\n      enabled: 0\r\n      settings:\r\n        CPU: AnyCPU\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Hotfix/Editor/Plugins.meta",
    "content": "fileFormatVersion: 2\r\nguid: 3aa64c11d48fd4d4f9adb05011b4df0a\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Hotfix/Editor/jsb.editor.hotfix.asmdef",
    "content": "{\n    \"name\": \"jsb.editor.hotfix\",\n    \"rootNamespace\": \"\",\n    \"references\": [\n        \"GUID:118b4ca3a1852354bac065cf952c1e85\",\n        \"GUID:eda0539582471264796e5affb41fe082\",\n        \"GUID:2746379d15af6e84cbeb433df77dd384\",\n        \"GUID:ac4126d60783f3d4a98aee6be9a997aa\",\n        \"GUID:595d45be140461240b6b4358dc45f2c0\"\n    ],\n    \"includePlatforms\": [\n        \"Editor\"\n    ],\n    \"excludePlatforms\": [],\n    \"allowUnsafeCode\": true,\n    \"overrideReferences\": false,\n    \"precompiledReferences\": [],\n    \"autoReferenced\": true,\n    \"defineConstraints\": [],\n    \"versionDefines\": [],\n    \"noEngineReferences\": false\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Hotfix/Editor/jsb.editor.hotfix.asmdef.meta",
    "content": "fileFormatVersion: 2\nguid: a6213e1ed98b428479613d08aa859f3f\nAssemblyDefinitionImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Hotfix/Editor.meta",
    "content": "fileFormatVersion: 2\r\nguid: ca0ac49d09e11c2409aa809968ff7c93\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/Hotfix.meta",
    "content": "fileFormatVersion: 2\nguid: 94626bff5ed00354ba545a33f52cf384\nfolderAsset: yes\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/JSBehaviour.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using Native;\r\n    using UnityEngine;\r\n    using UnityEngine.Serialization;\r\n\r\n    public class JSBehaviour : MonoBehaviour, ISerializationCallbackReceiver, IScriptEditorSupport, IScriptInstancedObject, Utils.IObjectCollectionEntry\r\n    {\r\n        // 在编辑器运行时下与 js 脚本建立链接关系\r\n        [SerializeField]\r\n        [FormerlySerializedAs(\"scriptRef\")]\r\n        private JSScriptRef _scriptRef;\r\n\r\n        public JSScriptRef scriptRef { get { return _scriptRef; } set { _scriptRef = value; } }\r\n\r\n        [SerializeField]\r\n        private JSScriptProperties _properties;\r\n\r\n        // internal use only\r\n        public JSScriptProperties properties => _properties;\r\n\r\n        // unsafe, internal use only\r\n        public JSContext ctx => _ctx;\r\n\r\n        private bool _isScriptInstanced = false;\r\n\r\n        public bool isScriptInstanced => _isScriptInstanced;\r\n\r\n#if UNITY_EDITOR\r\n        // self controlled script instance lifetime \r\n        private bool _isStandaloneScript = false;\r\n        public bool isStandaloneScript => _isStandaloneScript;\r\n#else\r\n        public bool isStandaloneScript => true;\r\n#endif\r\n\r\n        protected JSContext _ctx = JSContext.Null;\r\n        private Utils.ObjectCollection.Handle _handle;\r\n\r\n        protected JSValue _this_obj = JSApi.JS_UNDEFINED;\r\n\r\n        private bool _startValid;\r\n        private JSValue _startFunc = JSApi.JS_UNDEFINED;\r\n\r\n        private bool _resetValid;\r\n        private JSValue _resetFunc = JSApi.JS_UNDEFINED;\r\n\r\n        private bool _onEnableValid;\r\n        private JSValue _onEnableFunc = JSApi.JS_UNDEFINED;\r\n\r\n        private bool _onDisableValid;\r\n        private JSValue _onDisableFunc = JSApi.JS_UNDEFINED;\r\n\r\n        private bool _onDestroyValid;\r\n        private JSValue _onDestroyFunc = JSApi.JS_UNDEFINED;\r\n\r\n        private bool _awakeValid;\r\n        private JSValue _awakeFunc = JSApi.JS_UNDEFINED;\r\n\r\n        private bool _onBeforeSerializeValid;\r\n        private JSValue _onBeforeSerializeFunc = JSApi.JS_UNDEFINED;\r\n\r\n        private bool _onAfterDeserializeValid;\r\n        private JSValue _onAfterDeserializeFunc = JSApi.JS_UNDEFINED;\r\n\r\n        private bool _onBeforeScriptReloadValid;\r\n        private JSValue _onBeforeScriptReloadFunc = JSApi.JS_UNDEFINED;\r\n\r\n        private bool _onAfterScriptReloadValid;\r\n        private JSValue _onAfterScriptReloadFunc = JSApi.JS_UNDEFINED;\r\n\r\n#if UNITY_EDITOR\r\n        private bool _onDrawGizmosValid;\r\n        private JSValue _onDrawGizmosFunc = JSApi.JS_UNDEFINED;\r\n#endif\r\n\r\n        public bool IsValid()\r\n        {\r\n            return _ctx.IsValid() && !_this_obj.IsNullish();\r\n        }\r\n\r\n        public int IsInstanceOf(JSValue ctor)\r\n        {\r\n            if (!IsValid())\r\n            {\r\n                return 0;\r\n            }\r\n            return JSApi.JS_IsInstanceOf(_ctx, _this_obj, ctor);\r\n        }\r\n\r\n        public JSValue CloneValue()\r\n        {\r\n            if (!IsValid())\r\n            {\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            return JSApi.JS_DupValue(_ctx, _this_obj);\r\n        }\r\n\r\n        public JSValue GetProperty(string key)\r\n        {\r\n            if (!IsValid())\r\n            {\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n\r\n            return JSApi.JS_GetPropertyStr(_ctx, _this_obj, key);\r\n        }\r\n\r\n        public static bool IsUpdatable(ScriptContext context, JSValue prototype)\r\n        {\r\n            return prototype.CheckFuncProperty(context, \"Update\")\r\n                || prototype.CheckFuncProperty(context, \"LateUpdate\")\r\n                || prototype.CheckFuncProperty(context, \"FixedUpdate\");\r\n        }\r\n\r\n        // 在 gameObject 上创建一个新的脚本组件实例\r\n        // ctor: js class\r\n        public static JSValue SetScriptInstance(GameObject gameObject, JSContext ctx, JSValue ctor, bool execAwake)\r\n        {\r\n            if (JSApi.JS_IsConstructor(ctx, ctor) == 1)\r\n            {\r\n                var header = JSApi.jsb_get_payload_header(ctx, ctor);\r\n                if (header.type_id == BridgeObjectType.None) // it's a plain js value\r\n                {\r\n                    var fullCap = false;\r\n                    var prototype = JSApi.JS_GetProperty(ctx, ctor, JSApi.JS_ATOM_prototype);\r\n                    var context = ScriptEngine.GetContext(ctx);\r\n                    if (!prototype.IsException())\r\n                    {\r\n                        if (context != null)\r\n                        {\r\n                            fullCap = IsUpdatable(context, prototype);\r\n                        }\r\n                    }\r\n                    JSApi.JS_FreeValue(ctx, prototype);\r\n                    var bridge = fullCap ? gameObject.AddComponent<JSBehaviourFull>() : gameObject.AddComponent<JSBehaviour>();\r\n#if UNITY_EDITOR\r\n                    context.TrySetScriptRef(ref bridge._scriptRef, ctor);\r\n#endif\r\n                    return bridge.SetScriptInstance(ctx, ctor, execAwake);\r\n                }\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        public void SetUnresolvedScriptInstance()\r\n        {\r\n            _isScriptInstanced = true;\r\n        }\r\n\r\n        public void ReleaseScriptInstance()\r\n        {\r\n            _isScriptInstanced = false;\r\n            ReleaseJSValues();\r\n        }\r\n\r\n        // 在当前 JSBehaviour 实例上创建一个脚本实例并与之绑定\r\n        public JSValue SetScriptInstance(JSContext ctx, JSValue ctor, bool execAwake)\r\n        {\r\n            if (JSApi.JS_IsConstructor(ctx, ctor) == 1)\r\n            {\r\n                var header = JSApi.jsb_get_payload_header(ctx, ctor);\r\n                if (header.type_id == BridgeObjectType.None) // it's a plain js value\r\n                {\r\n                    var objectCache = ScriptEngine.GetObjectCache(ctx);\r\n\r\n                    // 旧的绑定值释放？\r\n                    OnUnbindingObject(ctx, _this_obj);\r\n                    var object_id = objectCache.AddObject(this, false);\r\n                    var val = JSApi.jsb_construct_bridge_object(ctx, ctor, object_id);\r\n                    if (val.IsException())\r\n                    {\r\n                        objectCache.RemoveObject(object_id);\r\n                        SetUnresolvedScriptInstance();\r\n                    }\r\n                    else\r\n                    {\r\n                        objectCache.AddJSValue(this, val);\r\n                        this._SetScriptInstance(ctx, val, execAwake);\r\n                    }\r\n\r\n                    return val;\r\n                }\r\n            }\r\n\r\n            SetUnresolvedScriptInstance();\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        private void _SetScriptInstance(JSContext ctx, JSValue this_obj, bool execAwake)\r\n        {\r\n            var runtime = ScriptEngine.GetRuntime(ctx);\r\n            var context = runtime?.GetContext(ctx);\r\n            if (context == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            ReleaseJSValues();\r\n            _ctx = ctx;\r\n            runtime.AddManagedObject(this, out _handle);\r\n#if UNITY_EDITOR\r\n            context.OnScriptReloading += OnScriptReloading;\r\n            context.OnScriptReloaded += OnScriptReloaded;\r\n#endif\r\n\r\n            _isScriptInstanced = true;\r\n            _this_obj = JSApi.JS_DupValue(ctx, this_obj);\r\n\r\n            if (!_this_obj.IsNullish())\r\n            {\r\n                this.OnBindingJSFuncs(context);\r\n                this._OnScriptingAfterDeserialize();\r\n                if (execAwake)\r\n                {\r\n                    JSScriptableObject._CallJSFunc(context, _this_obj, _awakeFunc);\r\n                    if (enabled && _onEnableValid)\r\n                    {\r\n                        JSScriptableObject._CallJSFunc(context, _this_obj, _onEnableFunc);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        protected virtual void OnBindingJSFuncs(ScriptContext context)\r\n        {\r\n            _onBeforeSerializeFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnBeforeSerialize\"));\r\n            _onBeforeSerializeValid = JSApi.JS_IsFunction(ctx, _onBeforeSerializeFunc) == 1;\r\n\r\n            _onAfterDeserializeFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnAfterDeserialize\"));\r\n            _onAfterDeserializeValid = JSApi.JS_IsFunction(ctx, _onAfterDeserializeFunc) == 1;\r\n\r\n            _onBeforeScriptReloadFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnBeforeScriptReload\"));\r\n            _onBeforeScriptReloadValid = JSApi.JS_IsFunction(ctx, _onBeforeScriptReloadFunc) == 1;\r\n\r\n            _onAfterScriptReloadFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnAfterScriptReload\"));\r\n            _onAfterScriptReloadValid = JSApi.JS_IsFunction(ctx, _onAfterScriptReloadFunc) == 1;\r\n\r\n            _startFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"Start\"));\r\n            _startValid = JSApi.JS_IsFunction(ctx, _startFunc) == 1;\r\n\r\n            _resetFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"Reset\"));\r\n            _resetValid = JSApi.JS_IsFunction(ctx, _resetFunc) == 1;\r\n\r\n            _onEnableFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnEnable\"));\r\n            _onEnableValid = JSApi.JS_IsFunction(ctx, _onEnableFunc) == 1;\r\n\r\n            _onDisableFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnDisable\"));\r\n            _onDisableValid = JSApi.JS_IsFunction(ctx, _onDisableFunc) == 1;\r\n\r\n#if UNITY_EDITOR\r\n            _onDrawGizmosFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnDrawGizmos\"));\r\n            _onDrawGizmosValid = JSApi.JS_IsFunction(ctx, _onDrawGizmosFunc) == 1;\r\n#endif\r\n\r\n            _onDestroyFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnDestroy\"));\r\n            _onDestroyValid = JSApi.JS_IsFunction(ctx, _onDestroyFunc) == 1;\r\n\r\n            _awakeFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"Awake\"));\r\n            _awakeValid = JSApi.JS_IsFunction(ctx, _awakeFunc) == 1;\r\n\r\n            if (Application.isPlaying)\r\n            {\r\n                if (JSApi.JS_HasProperty(ctx, _this_obj, context.GetAtom(\"OnBecameVisible\")) == 1\r\n                || JSApi.JS_HasProperty(ctx, _this_obj, context.GetAtom(\"OnBecameInvisible\")) == 1)\r\n                {\r\n                    SetupMonoBehaviourCallback(typeof(JSBecameVisibleCallback));\r\n                }\r\n\r\n                if (JSApi.JS_HasProperty(ctx, _this_obj, context.GetAtom(\"OnCollisionEnter\")) == 1\r\n                || JSApi.JS_HasProperty(ctx, _this_obj, context.GetAtom(\"OnCollisionExit\")) == 1\r\n                || JSApi.JS_HasProperty(ctx, _this_obj, context.GetAtom(\"OnCollisionStay\")) == 1)\r\n                {\r\n                    SetupMonoBehaviourCallback(typeof(JSCollisionCallback));\r\n                }\r\n\r\n                if (JSApi.JS_HasProperty(ctx, _this_obj, context.GetAtom(\"OnApplicationFocus\")) == 1\r\n                || JSApi.JS_HasProperty(ctx, _this_obj, context.GetAtom(\"OnApplicationPause\")) == 1\r\n                || JSApi.JS_HasProperty(ctx, _this_obj, context.GetAtom(\"OnApplicationQuit\")) == 1)\r\n                {\r\n                    SetupMonoBehaviourCallback(typeof(JSApplicationCallback));\r\n                }\r\n            }\r\n        }\r\n\r\n        public void SetupMonoBehaviourCallback(Type type)\r\n        {\r\n            if (type != null && type.IsSubclassOf(typeof(MonoBehaviour)))\r\n            {\r\n                var go = gameObject;\r\n                if (go && !go.GetComponent(type))\r\n                {\r\n                    go.AddComponent(type);\r\n                }\r\n            }\r\n        }\r\n\r\n        protected virtual void OnUnbindingJSFuncs()\r\n        {\r\n            JSApi.JS_FreeValue(_ctx, _startFunc);\r\n            _startFunc = JSApi.JS_UNDEFINED;\r\n            _startValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _resetFunc);\r\n            _resetFunc = JSApi.JS_UNDEFINED;\r\n            _resetValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onEnableFunc);\r\n            _onEnableFunc = JSApi.JS_UNDEFINED;\r\n            _onEnableValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onDisableFunc);\r\n            _onDisableFunc = JSApi.JS_UNDEFINED;\r\n            _onDisableValid = false;\r\n\r\n#if UNITY_EDITOR\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onDrawGizmosFunc);\r\n            _onDrawGizmosFunc = JSApi.JS_UNDEFINED;\r\n            _onDrawGizmosValid = false;\r\n#endif\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onDestroyFunc);\r\n            _onDestroyFunc = JSApi.JS_UNDEFINED;\r\n            _onDestroyValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _awakeFunc);\r\n            _awakeFunc = JSApi.JS_UNDEFINED;\r\n            _awakeValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onBeforeSerializeFunc);\r\n            _onBeforeSerializeFunc = JSApi.JS_UNDEFINED;\r\n            _onBeforeSerializeValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onAfterDeserializeFunc);\r\n            _onAfterDeserializeFunc = JSApi.JS_UNDEFINED;\r\n            _onAfterDeserializeValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onBeforeScriptReloadFunc);\r\n            _onBeforeScriptReloadFunc = JSApi.JS_UNDEFINED;\r\n            _onBeforeScriptReloadValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onAfterScriptReloadFunc);\r\n            _onAfterScriptReloadFunc = JSApi.JS_UNDEFINED;\r\n            _onAfterScriptReloadValid = false;\r\n        }\r\n\r\n        public static void Dispatch(GameObject gameObject, string funcName)\r\n        {\r\n            if (gameObject)\r\n            {\r\n                foreach (var comp in gameObject.GetComponents<JSBehaviour>())\r\n                {\r\n                    comp._Dispatch(funcName);\r\n                }\r\n            }\r\n        }\r\n\r\n        public static void Dispatch(GameObject gameObject, string funcName, bool p1)\r\n        {\r\n            if (gameObject)\r\n            {\r\n                foreach (var comp in gameObject.GetComponents<JSBehaviour>())\r\n                {\r\n                    comp._Dispatch(funcName, p1);\r\n                }\r\n            }\r\n        }\r\n\r\n        public static void Dispatch(GameObject gameObject, string funcName, object p1)\r\n        {\r\n            if (gameObject)\r\n            {\r\n                foreach (var comp in gameObject.GetComponents<JSBehaviour>())\r\n                {\r\n                    comp._Dispatch(funcName, p1);\r\n                }\r\n            }\r\n        }\r\n\r\n        public void _Dispatch(string funcName)\r\n        {\r\n            if (!_this_obj.IsNullish())\r\n            {\r\n                var context = ScriptEngine.GetContext(_ctx);\r\n                var atom = context.GetAtom(funcName);\r\n                if (JSApi.JS_HasProperty(_ctx, _this_obj, atom) == 1)\r\n                {\r\n                    var rval = JSApi.JS_Invoke(_ctx, _this_obj, atom);\r\n                    if (rval.IsException())\r\n                    {\r\n                        _ctx.print_exception();\r\n                    }\r\n                    else\r\n                    {\r\n                        JSApi.JS_FreeValue(_ctx, rval);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        public unsafe void _Dispatch(string funcName, bool p1)\r\n        {\r\n            if (!_this_obj.IsNullish())\r\n            {\r\n                var context = ScriptEngine.GetContext(_ctx);\r\n                var atom = context.GetAtom(funcName);\r\n                if (JSApi.JS_HasProperty(_ctx, _this_obj, atom) == 1)\r\n                {\r\n                    var argv = stackalloc[] { Binding.Values.js_push_primitive(_ctx, p1) };\r\n                    var rval = JSApi.JS_Invoke(_ctx, _this_obj, atom, 1, argv);\r\n                    if (rval.IsException())\r\n                    {\r\n                        _ctx.print_exception();\r\n                    }\r\n                    else\r\n                    {\r\n                        JSApi.JS_FreeValue(_ctx, rval);\r\n                    }\r\n                    JSApi.JS_FreeValue(_ctx, argv[0]);\r\n                }\r\n            }\r\n        }\r\n\r\n        public unsafe void _Dispatch(string funcName, object p1)\r\n        {\r\n            if (!_this_obj.IsNullish())\r\n            {\r\n                var context = ScriptEngine.GetContext(_ctx);\r\n                var atom = context.GetAtom(funcName);\r\n                if (JSApi.JS_HasProperty(_ctx, _this_obj, atom) == 1)\r\n                {\r\n                    var argv = stackalloc[] { Binding.Values.js_push_var(_ctx, p1) };\r\n                    var rval = JSApi.JS_Invoke(_ctx, _this_obj, atom, 1, argv);\r\n                    if (rval.IsException())\r\n                    {\r\n                        _ctx.print_exception();\r\n                    }\r\n                    else\r\n                    {\r\n                        JSApi.JS_FreeValue(_ctx, rval);\r\n                    }\r\n                    JSApi.JS_FreeValue(_ctx, argv[0]);\r\n                }\r\n            }\r\n        }\r\n\r\n        #region IObjectCollectionEntry implementation\r\n        public void OnCollectionReleased()\r\n        {\r\n            // it's dangerous, more protection are required during the process of context-destroying\r\n            if (enabled)\r\n            {\r\n                OnDisable();\r\n            }\r\n            OnDestroy();\r\n        }\r\n        #endregion\r\n\r\n#if UNITY_EDITOR\r\n        private void OnScriptReloading(ScriptContext context, string resolved_id)\r\n        {\r\n            if (context.CheckModuleId(_scriptRef, resolved_id))\r\n            {\r\n                if (_onBeforeScriptReloadValid)\r\n                {\r\n                    JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onBeforeScriptReloadFunc);\r\n                }\r\n            }\r\n        }\r\n\r\n        private void OnScriptReloaded(ScriptContext context, string resolved_id)\r\n        {\r\n            if (context.CheckModuleId(_scriptRef, resolved_id))\r\n            {\r\n                if (!_this_obj.IsNullish())\r\n                {\r\n                    JSValue newClass;\r\n                    if (context.LoadModuleCacheExports(resolved_id, _scriptRef.className, out newClass))\r\n                    {\r\n                        var prototype = JSApi.JS_GetProperty(context, newClass, context.GetAtom(\"prototype\"));\r\n\r\n                        if (prototype.IsObject())\r\n                        {\r\n                            OnUnbindingJSFuncs();\r\n                            JSApi.JS_SetPrototype(context, _this_obj, prototype);\r\n                            OnBindingJSFuncs(context);\r\n\r\n                            if (_onAfterScriptReloadValid)\r\n                            {\r\n                                JSScriptableObject._CallJSFunc(context, _this_obj, _onAfterScriptReloadFunc);\r\n                            }\r\n                        }\r\n\r\n                        JSApi.JS_FreeValue(context, prototype);\r\n                        JSApi.JS_FreeValue(context, newClass);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n#endif\r\n\r\n        void OnUnbindingObject(JSContext ctx, JSValue this_obj)\r\n        {\r\n            var payload = JSApi.JSB_FreePayload(ctx, this_obj);\r\n            ScriptEngine.GetObjectCache(ctx)?.RemoveObject(payload);\r\n        }\r\n\r\n        public void ReleaseJSValues()\r\n        {\r\n            if (!_this_obj.IsNullish())\r\n            {\r\n                OnUnbindingObject(_ctx, _this_obj);\r\n                OnUnbindingJSFuncs();\r\n                JSApi.JS_FreeValue(_ctx, _this_obj);\r\n                _this_obj = JSApi.JS_UNDEFINED;\r\n            }\r\n\r\n            _isScriptInstanced = false;\r\n            var runtime = ScriptEngine.GetRuntime(_ctx);\r\n            var context = runtime?.GetContext(_ctx);\r\n            _ctx = JSContext.Null;\r\n\r\n            if (context != null)\r\n            {\r\n                runtime.RemoveManagedObject(_handle);\r\n#if UNITY_EDITOR\r\n                context.OnScriptReloading -= OnScriptReloading;\r\n                context.OnScriptReloaded -= OnScriptReloaded;\r\n#endif\r\n            }\r\n        }\r\n\r\n        void Awake()\r\n        {\r\n#if UNITY_EDITOR\r\n            _isStandaloneScript = true;\r\n#endif\r\n            CreateScriptInstance();\r\n            // _OnScriptingAfterDeserialize();\r\n\r\n            if (_awakeValid)\r\n            {\r\n                JSScriptableObject._CallJSFunc(_ctx, _this_obj, _awakeFunc);\r\n            }\r\n        }\r\n\r\n        void Start()\r\n        {\r\n            if (_startValid)\r\n            {\r\n                JSScriptableObject._CallJSFunc(_ctx, _this_obj, _startFunc);\r\n            }\r\n        }\r\n\r\n        public void Reset()\r\n        {\r\n            if (_resetValid)\r\n            {\r\n                JSScriptableObject._CallJSFunc(_ctx, _this_obj, _resetFunc);\r\n            }\r\n        }\r\n\r\n        void OnEnable()\r\n        {\r\n            if (_onEnableValid)\r\n            {\r\n                JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onEnableFunc);\r\n            }\r\n        }\r\n\r\n        void OnDisable()\r\n        {\r\n            if (_onDisableValid)\r\n            {\r\n                JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onDisableFunc);\r\n            }\r\n\r\n#if UNITY_EDITOR\r\n            if (UnityEditor.EditorApplication.isCompiling)\r\n            {\r\n                ReleaseJSValues();\r\n            }\r\n#endif\r\n        }\r\n\r\n#if UNITY_EDITOR\r\n        void OnDrawGizmos()\r\n        {\r\n            if (_onDrawGizmosValid)\r\n            {\r\n                JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onDrawGizmosFunc);\r\n            }\r\n        }\r\n#endif\r\n\r\n        void OnDestroy()\r\n        {\r\n            if (_onDestroyValid)\r\n            {\r\n                JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onDestroyFunc);\r\n            }\r\n            ReleaseJSValues();\r\n        }\r\n\r\n        public void OnBeforeSerialize()\r\n        {\r\n            if (_onBeforeSerializeValid)\r\n            {\r\n                JSScriptableObject.ExecOnBeforeSerialize(ref _properties, _ctx, _this_obj, _onBeforeSerializeFunc);\r\n            }\r\n        }\r\n\r\n        public void OnAfterDeserialize()\r\n        {\r\n            _OnScriptingAfterDeserialize();\r\n        }\r\n\r\n        public void _OnScriptingAfterDeserialize()\r\n        {\r\n            if (_onAfterDeserializeValid)\r\n            {\r\n                JSScriptableObject.ExecOnAfterDeserialize(ref _properties, _ctx, _this_obj, _onAfterDeserializeFunc);\r\n            }\r\n        }\r\n\r\n        // 通过 scriptRef 还原脚本绑定关系\r\n        public bool CreateScriptInstance()\r\n        {\r\n            if (!_isScriptInstanced)\r\n            {\r\n                if (!string.IsNullOrEmpty(_scriptRef.modulePath) && !string.IsNullOrEmpty(_scriptRef.className))\r\n                {\r\n                    var runtime = ScriptEngine.GetRuntime();\r\n                    if (runtime != null && runtime.isInitialized)\r\n                    {\r\n                        var context = runtime.GetMainContext();\r\n                        if (context != null)\r\n                        {\r\n                            var ctx = (JSContext)context;\r\n                            var snippet = $\"require('{_scriptRef.modulePath}')['{_scriptRef.className}']\";\r\n                            var bytes = System.Text.Encoding.UTF8.GetBytes(snippet);\r\n                            var typeValue = ScriptRuntime.EvalSource(ctx, bytes, _scriptRef.sourceFile, false);\r\n                            if (JSApi.JS_IsException(typeValue))\r\n                            {\r\n                                var ex = ctx.GetExceptionString();\r\n                                Debug.LogError(ex);\r\n                                SetUnresolvedScriptInstance();\r\n                            }\r\n                            else\r\n                            {\r\n                                var instValue = SetScriptInstance(ctx, typeValue, false);\r\n                                JSApi.JS_FreeValue(ctx, instValue);\r\n                                JSApi.JS_FreeValue(ctx, typeValue);\r\n                            }\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        Debug.LogError(\"script runtime not ready\");\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    SetUnresolvedScriptInstance();\r\n                }\r\n            }\r\n\r\n            return _isScriptInstanced;\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/JSBehaviour.cs.meta",
    "content": "fileFormatVersion: 2\nguid: e8f8ea57c07f0ad4fa78fb459ef8f2d5\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/JSBehaviourFull.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using Native;\r\n    using UnityEngine;\r\n    using UnityEngine.Serialization;\r\n\r\n    public class JSBehaviourFull : JSBehaviour\r\n    {\r\n        private bool _updateValid;\r\n        private JSValue _updateFunc = JSApi.JS_UNDEFINED;\r\n\r\n        private bool _lateUpdateValid;\r\n        private JSValue _lateUpdateFunc = JSApi.JS_UNDEFINED;\r\n\r\n        private bool _fixedUpdateValid;\r\n        private JSValue _fixedUpdateFunc = JSApi.JS_UNDEFINED;\r\n\r\n        protected override void OnBindingJSFuncs(ScriptContext context)\r\n        {\r\n            base.OnBindingJSFuncs(context);\r\n\r\n            var ctx = (JSContext)context;\r\n\r\n            _updateFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"Update\"));\r\n            _updateValid = JSApi.JS_IsFunction(ctx, _updateFunc) == 1;\r\n\r\n            _lateUpdateFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"LateUpdate\"));\r\n            _lateUpdateValid = JSApi.JS_IsFunction(ctx, _lateUpdateFunc) == 1;\r\n\r\n            _fixedUpdateFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"FixedUpdate\"));\r\n            _fixedUpdateValid = JSApi.JS_IsFunction(ctx, _fixedUpdateFunc) == 1;\r\n        }\r\n\r\n        protected override void OnUnbindingJSFuncs()\r\n        {\r\n            base.OnUnbindingJSFuncs();\r\n\r\n            JSApi.JS_FreeValue(_ctx, _updateFunc);\r\n            _updateFunc = JSApi.JS_UNDEFINED;\r\n            _updateValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _lateUpdateFunc);\r\n            _lateUpdateFunc = JSApi.JS_UNDEFINED;\r\n            _lateUpdateValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _fixedUpdateFunc);\r\n            _fixedUpdateFunc = JSApi.JS_UNDEFINED;\r\n            _fixedUpdateValid = false;\r\n        }\r\n\r\n        void Update()\r\n        {\r\n            if (_updateValid)\r\n            {\r\n                var rval = JSApi.JS_Call(_ctx, _updateFunc, _this_obj);\r\n                if (rval.IsException())\r\n                {\r\n                    _ctx.print_exception();\r\n                }\r\n                else\r\n                {\r\n                    JSApi.JS_FreeValue(_ctx, rval);\r\n                }\r\n            }\r\n        }\r\n\r\n        void LateUpdate()\r\n        {\r\n            if (_lateUpdateValid)\r\n            {\r\n                var rval = JSApi.JS_Call(_ctx, _lateUpdateFunc, _this_obj);\r\n                if (rval.IsException())\r\n                {\r\n                    _ctx.print_exception();\r\n                }\r\n                else\r\n                {\r\n                    JSApi.JS_FreeValue(_ctx, rval);\r\n                }\r\n            }\r\n        }\r\n\r\n        void FixedUpdate()\r\n        {\r\n            if (_fixedUpdateValid)\r\n            {\r\n                var rval = JSApi.JS_Call(_ctx, _fixedUpdateFunc, _this_obj);\r\n                if (rval.IsException())\r\n                {\r\n                    _ctx.print_exception();\r\n                }\r\n                else\r\n                {\r\n                    JSApi.JS_FreeValue(_ctx, rval);\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/JSBehaviourFull.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 5d7749844623fd647859e1bd098d5a43\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/JSEditorWindow.cs",
    "content": "#if !JSB_UNITYLESS\r\n#if UNITY_EDITOR\r\nusing System;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using Native;\r\n    using UnityEngine;\r\n    using UnityEditor;\r\n\r\n    /// <summary>\r\n    /// 脚本实现编辑器窗口的基础类. \r\n    /// 此实现刻意放在非 Editor 目录下, 以便在非编辑器脚本中也可以使用, 实际仍然只在编辑器环境下可用.\r\n    /// </summary>\r\n    public class JSEditorWindow : EditorWindow, IHasCustomMenu, IScriptInstancedObject, ISerializationCallbackReceiver, Utils.IObjectCollectionEntry\r\n    {\r\n        private Utils.ObjectCollection.Handle _handle;\r\n\r\n        [NonSerialized]\r\n        private bool _isScriptInstanced;\r\n\r\n        [NonSerialized]\r\n        private bool _isWaitingRuntime = false;\r\n\r\n        [NonSerialized]\r\n        private bool _checkInstanceOnce = true;\r\n\r\n        [SerializeField]\r\n        private JSScriptRef _scriptRef;\r\n\r\n        [SerializeField]\r\n        private JSScriptProperties _properties;\r\n\r\n        // internal use only\r\n        public JSScriptProperties properties => _properties;\r\n\r\n        [NonSerialized]\r\n        private JSContext _ctx;\r\n\r\n        private JSValue _this_obj = JSApi.JS_UNDEFINED;\r\n\r\n        [NonSerialized]\r\n        private bool _updateValid;\r\n        private JSValue _updateFunc = JSApi.JS_UNDEFINED;\r\n\r\n        [NonSerialized]\r\n        private bool _onEnableValid;\r\n        private JSValue _onEnableFunc = JSApi.JS_UNDEFINED;\r\n\r\n        [NonSerialized]\r\n        private bool _onDisableValid;\r\n        private JSValue _onDisableFunc = JSApi.JS_UNDEFINED;\r\n\r\n        [NonSerialized]\r\n        private bool _onDestroyValid;\r\n        private JSValue _onDestroyFunc = JSApi.JS_UNDEFINED;\r\n\r\n        [NonSerialized]\r\n        private bool _onGUIValid;\r\n        private JSValue _onGUIFunc = JSApi.JS_UNDEFINED;\r\n\r\n#if JSB_WITH_UIELEMENTS\r\n        [NonSerialized]\r\n        private bool _createGUIValid;\r\n        private JSValue _createGUIFunc = JSApi.JS_UNDEFINED;\r\n#endif\r\n\r\n        [NonSerialized]\r\n        private bool _addItemsToMenuValid;\r\n        private JSValue _addItemsToMenuFunc = JSApi.JS_UNDEFINED;\r\n\r\n        [NonSerialized]\r\n        private bool _onBeforeScriptReloadValid;\r\n        private JSValue _onBeforeScriptReloadFunc = JSApi.JS_UNDEFINED;\r\n\r\n        [NonSerialized]\r\n        private bool _onAfterScriptReloadValid;\r\n        private JSValue _onAfterScriptReloadFunc = JSApi.JS_UNDEFINED;\r\n\r\n        [NonSerialized]\r\n        private bool _onBeforeSerializeValid;\r\n        private JSValue _onBeforeSerializeFunc = JSApi.JS_UNDEFINED;\r\n\r\n        [NonSerialized]\r\n        private bool _onAfterDeserializeValid;\r\n        private JSValue _onAfterDeserializeFunc = JSApi.JS_UNDEFINED;\r\n\r\n        public int IsInstanceOf(JSValue ctor)\r\n        {\r\n            if (!_isScriptInstanced)\r\n            {\r\n                return 0;\r\n            }\r\n            return JSApi.JS_IsInstanceOf(_ctx, _this_obj, ctor);\r\n        }\r\n\r\n        public JSValue CloneValue()\r\n        {\r\n            if (!_isScriptInstanced)\r\n            {\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            return JSApi.JS_DupValue(_ctx, _this_obj);\r\n        }\r\n\r\n        public JSValue SetScriptInstance(JSContext ctx, JSValue ctor, bool execAwake)\r\n        {\r\n            if (JSApi.JS_IsConstructor(ctx, ctor) == 1)\r\n            {\r\n                var header = JSApi.jsb_get_payload_header(ctx, ctor);\r\n                if (header.type_id == BridgeObjectType.None) // it's a plain js value\r\n                {\r\n                    var cache = ScriptEngine.GetObjectCache(ctx);\r\n\r\n                    // 旧的绑定值释放？\r\n                    OnUnbindingObject(ctx, _this_obj);\r\n                    var object_id = cache.AddObject(this, false);\r\n                    var val = JSApi.jsb_construct_bridge_object(ctx, ctor, object_id);\r\n                    if (val.IsException())\r\n                    {\r\n                        cache.RemoveObject(object_id);\r\n                        SetUnresolvedScriptInstance();\r\n                    }\r\n                    else\r\n                    {\r\n                        cache.AddJSValue(this, val);\r\n                        this._SetScriptInstance(ctx, val, ctor, execAwake);\r\n                        // JSApi.JSB_SetBridgeType(ctx, val, type_id);\r\n                    }\r\n\r\n                    return val;\r\n                }\r\n            }\r\n\r\n            SetUnresolvedScriptInstance();\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        public void ReleaseScriptInstance()\r\n        {\r\n            _isScriptInstanced = false;\r\n            ReleaseJSValues();\r\n        }\r\n\r\n        private void SetUnresolvedScriptInstance()\r\n        {\r\n            _isScriptInstanced = true;\r\n        }\r\n\r\n        public bool CreateScriptInstance()\r\n        {\r\n            if (!_isScriptInstanced)\r\n            {\r\n                if (!string.IsNullOrEmpty(_scriptRef.modulePath) && !string.IsNullOrEmpty(_scriptRef.className))\r\n                {\r\n                    var runtime = ScriptEngine.GetRuntime();\r\n                    if (runtime != null && runtime.isValid && runtime.isInitialized)\r\n                    {\r\n                        var context = runtime.GetMainContext();\r\n                        if (context != null)\r\n                        {\r\n                            var ctx = (JSContext)context;\r\n                            var snippet = $\"require('{_scriptRef.modulePath}')['{_scriptRef.className}']\";\r\n                            var bytes = System.Text.Encoding.UTF8.GetBytes(snippet);\r\n                            var typeValue = ScriptRuntime.EvalSource(ctx, bytes, _scriptRef.sourceFile ?? _scriptRef.modulePath, false);\r\n                            if (typeValue.IsException())\r\n                            {\r\n                                ctx.print_exception();\r\n                                SetUnresolvedScriptInstance();\r\n                            }\r\n                            else\r\n                            {\r\n                                var instValue = SetScriptInstance(ctx, typeValue, false);\r\n                                JSApi.JS_FreeValue(ctx, instValue);\r\n                                JSApi.JS_FreeValue(ctx, typeValue);\r\n                            }\r\n                        }\r\n                        else\r\n                        {\r\n                            SetUnresolvedScriptInstance();\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        if (!_isWaitingRuntime)\r\n                        {\r\n                            _isWaitingRuntime = true;\r\n                            ScriptEngine.RuntimeInitialized += OnRuntimeInitialized;\r\n                        }\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    SetUnresolvedScriptInstance();\r\n                }\r\n            }\r\n\r\n            return _isScriptInstanced;\r\n        }\r\n\r\n        private void OnRuntimeInitialized(ScriptRuntime runtime)\r\n        {\r\n            if (_isWaitingRuntime)\r\n            {\r\n                _isWaitingRuntime = false;\r\n                ScriptEngine.RuntimeInitialized -= OnRuntimeInitialized;\r\n                CreateScriptInstance();\r\n            }\r\n        }\r\n\r\n        private void _SetScriptInstance(JSContext ctx, JSValue this_obj, JSValue ctor, bool execAwake)\r\n        {\r\n            var context = ScriptEngine.GetContext(ctx);\r\n            if (context == null || !context.IsValid())\r\n            {\r\n                return;\r\n            }\r\n\r\n            ReleaseJSValues();\r\n            context.TrySetScriptRef(ref _scriptRef, ctor);\r\n            var runtime = context.GetRuntime();\r\n            runtime.AddManagedObject(this, out _handle);\r\n#if UNITY_EDITOR\r\n            context.OnScriptReloading += OnScriptReloading;\r\n            context.OnScriptReloaded += OnScriptReloaded;\r\n#endif\r\n            _ctx = ctx;\r\n            _isScriptInstanced = true;\r\n            _this_obj = JSApi.JS_DupValue(ctx, this_obj);\r\n\r\n            if (!_this_obj.IsNullish())\r\n            {\r\n                OnBindingJSFuncs(context);\r\n\r\n                if (execAwake)\r\n                {\r\n                    var awake_obj = JSApi.JS_GetProperty(ctx, this_obj, context.GetAtom(\"Awake\"));\r\n                    JSScriptableObject._CallJSFunc(_ctx, _this_obj, awake_obj);\r\n                    JSApi.JS_FreeValue(_ctx, awake_obj);\r\n\r\n                }\r\n\r\n                this._OnScriptingAfterDeserialize();\r\n                if (_onEnableValid)\r\n                {\r\n                    JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onEnableFunc);\r\n                }\r\n            }\r\n        }\r\n\r\n        private void OnBindingJSFuncs(ScriptContext context)\r\n        {\r\n            var ctx = (JSContext)context;\r\n\r\n            _updateFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"Update\"));\r\n            _updateValid = JSApi.JS_IsFunction(ctx, _updateFunc) == 1;\r\n\r\n            _onEnableFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnEnable\"));\r\n            _onEnableValid = JSApi.JS_IsFunction(ctx, _onEnableFunc) == 1;\r\n\r\n            _onDisableFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnDisable\"));\r\n            _onDisableValid = JSApi.JS_IsFunction(ctx, _onDisableFunc) == 1;\r\n\r\n            _onDestroyFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnDestroy\"));\r\n            _onDestroyValid = JSApi.JS_IsFunction(ctx, _onDestroyFunc) == 1;\r\n\r\n            _onGUIFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnGUI\"));\r\n            _onGUIValid = JSApi.JS_IsFunction(ctx, _onGUIFunc) == 1;\r\n\r\n#if JSB_WITH_UIELEMENTS\r\n            _createGUIFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"CreateGUI\"));\r\n            _createGUIValid = JSApi.JS_IsFunction(ctx, _createGUIFunc) == 1;\r\n#endif\r\n\r\n            _addItemsToMenuFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"AddItemsToMenu\"));\r\n            _addItemsToMenuValid = JSApi.JS_IsFunction(ctx, _addItemsToMenuFunc) == 1;\r\n\r\n            _onBeforeScriptReloadFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnBeforeScriptReload\"));\r\n            _onBeforeScriptReloadValid = JSApi.JS_IsFunction(ctx, _onBeforeScriptReloadFunc) == 1;\r\n\r\n            _onAfterScriptReloadFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnAfterScriptReload\"));\r\n            _onAfterScriptReloadValid = JSApi.JS_IsFunction(ctx, _onAfterScriptReloadFunc) == 1;\r\n\r\n            _onBeforeSerializeFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnBeforeSerialize\"));\r\n            _onBeforeSerializeValid = JSApi.JS_IsFunction(ctx, _onBeforeSerializeFunc) == 1;\r\n\r\n            _onAfterDeserializeFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnAfterDeserialize\"));\r\n            _onAfterDeserializeValid = JSApi.JS_IsFunction(ctx, _onAfterDeserializeFunc) == 1;\r\n        }\r\n\r\n        private void OnUnbindingJSFuncs()\r\n        {\r\n            JSApi.JS_FreeValue(_ctx, _updateFunc);\r\n            _updateFunc = JSApi.JS_UNDEFINED;\r\n            _updateValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onEnableFunc);\r\n            _onEnableFunc = JSApi.JS_UNDEFINED;\r\n            _onEnableValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onDisableFunc);\r\n            _onDisableFunc = JSApi.JS_UNDEFINED;\r\n            _onDisableValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onDestroyFunc);\r\n            _onDestroyFunc = JSApi.JS_UNDEFINED;\r\n            _onDestroyValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onGUIFunc);\r\n            _onGUIFunc = JSApi.JS_UNDEFINED;\r\n            _onGUIValid = false;\r\n\r\n#if JSB_WITH_UIELEMENTS\r\n            JSApi.JS_FreeValue(_ctx, _createGUIFunc);\r\n            _createGUIFunc = JSApi.JS_UNDEFINED;\r\n            _createGUIValid = false;\r\n#endif\r\n\r\n            JSApi.JS_FreeValue(_ctx, _addItemsToMenuFunc);\r\n            _addItemsToMenuFunc = JSApi.JS_UNDEFINED;\r\n            _addItemsToMenuValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onBeforeScriptReloadFunc);\r\n            _onBeforeScriptReloadFunc = JSApi.JS_UNDEFINED;\r\n            _onBeforeScriptReloadValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onAfterScriptReloadFunc);\r\n            _onAfterScriptReloadFunc = JSApi.JS_UNDEFINED;\r\n            _onAfterScriptReloadValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onBeforeSerializeFunc);\r\n            _onBeforeSerializeFunc = JSApi.JS_UNDEFINED;\r\n            _onBeforeSerializeValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onAfterDeserializeFunc);\r\n            _onAfterDeserializeFunc = JSApi.JS_UNDEFINED;\r\n            _onAfterDeserializeValid = false;\r\n        }\r\n\r\n#if UNITY_EDITOR\r\n        private void OnScriptReloading(ScriptContext context, string resolved_id)\r\n        {\r\n            if (context.CheckModuleId(_scriptRef, resolved_id))\r\n            {\r\n                if (_onBeforeScriptReloadValid)\r\n                {\r\n                    JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onBeforeScriptReloadFunc);\r\n                }\r\n            }\r\n        }\r\n\r\n        private void OnScriptReloaded(ScriptContext context, string resolved_id)\r\n        {\r\n            if (context.CheckModuleId(_scriptRef, resolved_id))\r\n            {\r\n                JSValue newClass;\r\n                if (context.LoadModuleCacheExports(resolved_id, _scriptRef.className, out newClass))\r\n                {\r\n                    var prototype = JSApi.JS_GetProperty(context, newClass, context.GetAtom(\"prototype\"));\r\n\r\n                    if (prototype.IsObject() && _this_obj.IsObject())\r\n                    {\r\n                        OnUnbindingJSFuncs();\r\n                        JSApi.JS_SetPrototype(context, _this_obj, prototype);\r\n                        OnBindingJSFuncs(context);\r\n\r\n                        if (_onAfterScriptReloadValid)\r\n                        {\r\n                            JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onAfterScriptReloadFunc);\r\n                        }\r\n                    }\r\n\r\n                    JSApi.JS_FreeValue(context, prototype);\r\n                    JSApi.JS_FreeValue(context, newClass);\r\n                }\r\n            }\r\n        }\r\n#endif\r\n\r\n        #region IObjectCollectionEntry implementation\r\n        public void OnCollectionReleased()\r\n        {\r\n            OnBeforeSerialize();\r\n            ReleaseJSValues();\r\n        }\r\n        #endregion\r\n\r\n        void OnUnbindingObject(JSContext ctx, JSValue this_obj)\r\n        {\r\n            var payload = JSApi.JSB_FreePayload(ctx, this_obj);\r\n            ScriptEngine.GetObjectCache(ctx)?.RemoveObject(payload);\r\n        }\r\n\r\n        void ReleaseJSValues(bool noClose = false)\r\n        {\r\n            _isScriptInstanced = false;\r\n            if (_isWaitingRuntime)\r\n            {\r\n                _isWaitingRuntime = false;\r\n                ScriptEngine.RuntimeInitialized -= OnRuntimeInitialized;\r\n            }\r\n\r\n            if (!_this_obj.IsNullish())\r\n            {\r\n                OnUnbindingObject(_ctx, _this_obj);\r\n                OnUnbindingJSFuncs();\r\n                JSApi.JS_FreeValue(_ctx, _this_obj);\r\n                _this_obj = JSApi.JS_UNDEFINED;\r\n            }\r\n\r\n            var context = ScriptEngine.GetContext(_ctx);\r\n            _ctx = JSContext.Null;\r\n            if (context != null)\r\n            {\r\n                var runtime = context.GetRuntime();\r\n                if (runtime != null)\r\n                {\r\n                    runtime.RemoveManagedObject(_handle);\r\n                }\r\n#if UNITY_EDITOR\r\n                context.OnScriptReloading -= OnScriptReloading;\r\n                context.OnScriptReloaded -= OnScriptReloaded;\r\n#endif\r\n            }\r\n\r\n            try\r\n            {\r\n                if (!noClose && _scriptRef.IsEmpty())\r\n                {\r\n                    Close();\r\n                }\r\n            }\r\n            catch (Exception) { }\r\n        }\r\n\r\n        void Update()\r\n        {\r\n            if (_updateValid && _ctx.IsValid())\r\n            {\r\n                JSScriptableObject._CallJSFunc(_ctx, _this_obj, _updateFunc);\r\n            }\r\n            else\r\n            {\r\n                // there is no callback available to restore the script reference after getting back to edit mode.\r\n                // it seems that checking is the only way.\r\n\r\n                if (_checkInstanceOnce && !Application.isPlaying)\r\n                {\r\n                    _checkInstanceOnce = false;\r\n                    CreateScriptInstance();\r\n                }\r\n            }\r\n        }\r\n\r\n        void OnEnable()\r\n        {\r\n            CreateScriptInstance();\r\n\r\n            // if (_onEnableValid)\r\n            // {\r\n            //     JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onEnableFunc);\r\n            // }\r\n        }\r\n\r\n        void OnDisable()\r\n        {\r\n            if (_onDisableValid)\r\n            {\r\n                JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onDisableFunc);\r\n            }\r\n        }\r\n\r\n        void OnDestroy()\r\n        {\r\n            if (_onDestroyValid)\r\n            {\r\n                JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onDestroyFunc);\r\n            }\r\n            ReleaseJSValues(true);\r\n        }\r\n\r\n#if JSB_WITH_UIELEMENTS\r\n        void CreateGUI()\r\n        {\r\n            if (EditorApplication.isCompiling)\r\n            {\r\n                ReleaseJSValues();\r\n                return;\r\n            }\r\n\r\n            if (_createGUIValid && _isScriptInstanced && _ctx.IsValid())\r\n            {\r\n                JSScriptableObject._CallJSFunc(_ctx, _this_obj, _createGUIFunc);\r\n            }\r\n        }\r\n#endif\r\n\r\n        void OnGUI()\r\n        {\r\n            if (EditorApplication.isCompiling)\r\n            {\r\n                ReleaseJSValues();\r\n                return;\r\n            }\r\n\r\n            if (_onGUIValid && _isScriptInstanced && _ctx.IsValid())\r\n            {\r\n                JSScriptableObject._CallJSFunc(_ctx, _this_obj, _onGUIFunc);\r\n            }\r\n            else\r\n            {\r\n                var promptMessage = @\"script callback not ready:\r\n    1. runtime unavailable\r\n    2. script instance not ready\r\n    3. callback of OnGUI not provided in target script\";\r\n                EditorGUILayout.HelpBox(promptMessage, MessageType.Warning);\r\n            }\r\n        }\r\n\r\n        public unsafe void AddItemsToMenu(GenericMenu menu)\r\n        {\r\n            if (_addItemsToMenuValid)\r\n            {\r\n                var argv = stackalloc JSValue[] { Binding.Values.js_push_classvalue(_ctx, menu) };\r\n                var rval = JSApi.JS_Call(_ctx, _addItemsToMenuFunc, _this_obj, 1, argv);\r\n\r\n                JSApi.JS_FreeValue(_ctx, argv[0]);\r\n                if (rval.IsException())\r\n                {\r\n                    _ctx.print_exception();\r\n                }\r\n                else\r\n                {\r\n                    JSApi.JS_FreeValue(_ctx, rval);\r\n                }\r\n            }\r\n        }\r\n\r\n        public void OnBeforeSerialize()\r\n        {\r\n            if (_onBeforeSerializeValid)\r\n            {\r\n                JSScriptableObject.ExecOnBeforeSerialize(ref _properties, _ctx, _this_obj, _onBeforeSerializeFunc);\r\n            }\r\n\r\n            if (UnityEditor.EditorApplication.isCompiling)\r\n            {\r\n                ReleaseJSValues();\r\n            }\r\n        }\r\n\r\n        public void _OnScriptingAfterDeserialize()\r\n        {\r\n            if (_onAfterDeserializeValid)\r\n            {\r\n                JSScriptableObject.ExecOnAfterDeserialize(ref _properties, _ctx, _this_obj, _onAfterDeserializeFunc);\r\n            }\r\n        }\r\n\r\n        public void OnAfterDeserialize()\r\n        {\r\n            if (_isScriptInstanced)\r\n            {\r\n                _OnScriptingAfterDeserialize();\r\n            }\r\n            else\r\n            {\r\n                CreateScriptInstance();\r\n            }\r\n        }\r\n    }\r\n}\r\n#endif\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/JSEditorWindow.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 6e20916374902fa4380b6f21d2af62a2\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/JSScriptProperties.cs",
    "content": "#if !JSB_UNITYLESS\nusing System;\nusing System.Collections.Generic;\n\nnamespace QuickJS.Unity\n{\n    using UnityEngine;\n\n    [Serializable]\n    public class JSScriptProperties\n    {\n        [SerializeField]\n        private List<Object> _referencedObjects;\n\n        [SerializeField]\n        public byte[] genericValueData;\n\n        [SerializeField]\n        public int dataFormat = -1;\n\n        public bool IsEmpty\n        {\n            get { return GenericCount == 0; }\n        }\n\n        public int ReferencedObjectCount => _referencedObjects != null ? _referencedObjects.Count : 0;\n\n        public int GenericCount => genericValueData != null ? genericValueData.Length : 0;\n\n        public int AddReferencedObject(Object value)\n        {\n            if (_referencedObjects == null)\n            {\n                _referencedObjects = new List<Object>();\n                _referencedObjects.Add(value);\n                return 0;\n            }\n            var count = _referencedObjects.Count;\n            for (var i = 0; i < count; ++i)\n            {\n                var item = _referencedObjects[i];\n                if (item == value)\n                {\n                    return i;\n                }\n            }\n            _referencedObjects.Add(value);\n            return count;\n        }\n\n        public Object GetReferencedObject(int index)\n        {\n            if (_referencedObjects != null && index >= 0 && index < _referencedObjects.Count)\n            {\n                return _referencedObjects[index];\n            }\n            return null;\n        }\n\n        public void SetGenericValue(IO.ByteBuffer buffer)\n        {\n            if (buffer != null && buffer.readableBytes > 0)\n            {\n                if (genericValueData == null)\n                {\n                    genericValueData = new byte[buffer.readableBytes];\n                    buffer.ReadBytes(genericValueData, 0, buffer.readableBytes);\n                }\n                else\n                {\n                    if (genericValueData.Length != buffer.readableBytes)\n                    {\n                        Array.Resize(ref genericValueData, buffer.readableBytes);\n                    }\n                    buffer.ReadBytes(genericValueData, 0, buffer.readableBytes);\n                }\n            }\n            else\n            {\n                genericValueData = null;\n            }\n        }\n\n        public void Clear()\n        {\n            _referencedObjects?.Clear();\n        }\n    }\n}\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/JSScriptProperties.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 52448f6ae6da2354889ad0d6628e5856\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/JSScriptRef.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using Native;\r\n    using UnityEngine;\r\n\r\n    /// <summary>\r\n    /// indicates a script class\r\n    /// (case-sensitive)\r\n    /// </summary>\r\n    [Serializable]\r\n    public struct JSScriptRef\r\n    {\r\n        /// <summary>\r\n        /// sourceFile will be broken down into modulePath and className by the editor, \r\n        /// but not necessary for instantiating the script class instance\r\n        /// </summary>\r\n        public string sourceFile;\r\n\r\n        /// <summary>\r\n        /// the actual script loaded, it's parsed from sourceFile and be resolved by ScriptRuntime.pathResolver. \r\n        /// </summary>\r\n        public string modulePath;\r\n\r\n        /// <summary>\r\n        /// it specifies the exported target class used for bridging of Unity's facilities\r\n        /// </summary>\r\n        public string className;\r\n\r\n        public void Reset()\r\n        {\r\n            sourceFile = null;\r\n            modulePath = null;\r\n            className = null;\r\n        }\r\n\r\n        public bool IsEmpty()\r\n        {\r\n            return string.IsNullOrEmpty(modulePath) && string.IsNullOrEmpty(className);\r\n        }\r\n\r\n        public bool IsSameScript(JSScriptRef other)\r\n        {\r\n            return modulePath == other.modulePath && className == other.className;\r\n        }\r\n\r\n        public static string ToClassPath(string modulePath, string className)\r\n        {\r\n            if (string.IsNullOrEmpty(modulePath))\r\n            {\r\n                return className ?? string.Empty;\r\n            }\r\n\r\n            return string.IsNullOrEmpty(className) ? string.Empty : $\"{modulePath.Replace('/', '.')}.{className}\";\r\n        }\r\n\r\n        public string ToClassPath()\r\n        {\r\n            return ToClassPath(modulePath, className);\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/JSScriptRef.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 8399b86686bcf604e85be1be014eb933\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/JSScriptableObject.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using Native;\r\n    using UnityEngine;\r\n    using UnityEngine.Serialization;\r\n\r\n    // 实际 ScriptableObject.OnAfterDeserialize/OnEnable 可能早于 Runtime 初始化\r\n    // 脚本回调与 C# 版本不完全一致\r\n\r\n    [CreateAssetMenu(fileName = \"js_data\", menuName = \"JSScriptableObject Asset\", order = 100)]\r\n    public class JSScriptableObject : ScriptableObject, ISerializationCallbackReceiver, IScriptEditorSupport, IScriptInstancedObject, Utils.IObjectCollectionEntry\r\n    {\r\n        // 在编辑器运行时下与 js 脚本建立链接关系\r\n        [SerializeField]\r\n        [FormerlySerializedAs(\"scriptRef\")]\r\n        private JSScriptRef _scriptRef;\r\n\r\n        [SerializeField]\r\n        private JSScriptProperties _properties;\r\n\r\n        // internal use only\r\n        public JSScriptProperties properties => _properties;\r\n\r\n        [NonSerialized]\r\n        private bool _enabled;\r\n\r\n        [NonSerialized]\r\n        private bool _isScriptInstanced = false;\r\n\r\n        [NonSerialized]\r\n        private bool _isWaitingRuntime = false;\r\n\r\n        private JSContext _ctx = JSContext.Null;\r\n        private Utils.ObjectCollection.Handle _handle;\r\n        private JSValue _this_obj = JSApi.JS_UNDEFINED;\r\n\r\n        [NonSerialized]\r\n        private bool _resetValid;\r\n        private JSValue _resetFunc = JSApi.JS_UNDEFINED;\r\n\r\n        [NonSerialized]\r\n        private bool _onBeforeSerializeValid;\r\n        private JSValue _onBeforeSerializeFunc = JSApi.JS_UNDEFINED;\r\n\r\n        [NonSerialized]\r\n        private bool _onAfterDeserializeValid;\r\n        private JSValue _onAfterDeserializeFunc = JSApi.JS_UNDEFINED;\r\n\r\n        [NonSerialized]\r\n        private bool _onBeforeScriptReloadValid;\r\n        private JSValue _onBeforeScriptReloadFunc = JSApi.JS_UNDEFINED;\r\n\r\n        [NonSerialized]\r\n        private bool _onAfterScriptReloadValid;\r\n        private JSValue _onAfterScriptReloadFunc = JSApi.JS_UNDEFINED;\r\n\r\n        public bool enabled => _enabled;\r\n\r\n        public bool isScriptInstanced => _isScriptInstanced;\r\n\r\n        // self controlled script instance lifetime \r\n        public bool isStandaloneScript => true;\r\n\r\n        JSScriptRef IScriptEditorSupport.scriptRef { get { return _scriptRef; } set { _scriptRef = value; } }\r\n\r\n        public JSContext ctx => _ctx;\r\n\r\n        public bool IsValid()\r\n        {\r\n            return _ctx.IsValid() && !_this_obj.IsNullish();\r\n        }\r\n\r\n        public int IsInstanceOf(JSValue ctor)\r\n        {\r\n            if (!IsValid())\r\n            {\r\n                return 0;\r\n            }\r\n            return JSApi.JS_IsInstanceOf(_ctx, _this_obj, ctor);\r\n        }\r\n\r\n        public JSValue CloneValue()\r\n        {\r\n            if (!IsValid())\r\n            {\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            return JSApi.JS_DupValue(_ctx, _this_obj);\r\n        }\r\n\r\n        public static void _CallJSFunc(JSContext ctx, JSValue this_obj, JSValue func_obj)\r\n        {\r\n            if (!this_obj.IsNullish() && JSApi.JS_IsFunction(ctx, func_obj) == 1)\r\n            {\r\n                var rval = JSApi.JS_Call(ctx, func_obj, this_obj);\r\n                if (rval.IsException())\r\n                {\r\n                    ctx.print_exception();\r\n                }\r\n                else\r\n                {\r\n                    JSApi.JS_FreeValue(ctx, rval);\r\n                }\r\n            }\r\n        }\r\n\r\n        private void OnBindingJSFuncs(ScriptContext context)\r\n        {\r\n            var ctx = (JSContext)context;\r\n\r\n            _onBeforeSerializeFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnBeforeSerialize\"));\r\n            _onBeforeSerializeValid = JSApi.JS_IsFunction(ctx, _onBeforeSerializeFunc) == 1;\r\n\r\n            _onAfterDeserializeFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnAfterDeserialize\"));\r\n            _onAfterDeserializeValid = JSApi.JS_IsFunction(ctx, _onAfterDeserializeFunc) == 1;\r\n\r\n            _onBeforeScriptReloadFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnBeforeScriptReload\"));\r\n            _onBeforeScriptReloadValid = JSApi.JS_IsFunction(ctx, _onBeforeScriptReloadFunc) == 1;\r\n\r\n            _onAfterScriptReloadFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"OnAfterScriptReload\"));\r\n            _onAfterScriptReloadValid = JSApi.JS_IsFunction(ctx, _onAfterScriptReloadFunc) == 1;\r\n\r\n            _resetFunc = JSApi.JS_GetProperty(ctx, _this_obj, context.GetAtom(\"Reset\"));\r\n            _resetValid = JSApi.JS_IsFunction(ctx, _resetFunc) == 1;\r\n        }\r\n\r\n        private void OnUnbindingJSFuncs()\r\n        {\r\n            JSApi.JS_FreeValue(_ctx, _onBeforeSerializeFunc);\r\n            _onBeforeSerializeFunc = JSApi.JS_UNDEFINED;\r\n            _onBeforeSerializeValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onAfterDeserializeFunc);\r\n            _onAfterDeserializeFunc = JSApi.JS_UNDEFINED;\r\n            _onAfterDeserializeValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onBeforeScriptReloadFunc);\r\n            _onBeforeScriptReloadFunc = JSApi.JS_UNDEFINED;\r\n            _onBeforeScriptReloadValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _onAfterScriptReloadFunc);\r\n            _onAfterScriptReloadFunc = JSApi.JS_UNDEFINED;\r\n            _onAfterScriptReloadValid = false;\r\n\r\n            JSApi.JS_FreeValue(_ctx, _resetFunc);\r\n            _resetFunc = JSApi.JS_UNDEFINED;\r\n            _resetValid = false;\r\n        }\r\n\r\n        void OnUnbindingObject(JSContext ctx, JSValue this_obj)\r\n        {\r\n            var payload = JSApi.JSB_FreePayload(ctx, this_obj);\r\n            ScriptEngine.GetObjectCache(ctx)?.RemoveObject(payload);\r\n        }\r\n\r\n        public void ReleaseJSValues()\r\n        {\r\n            if (!_this_obj.IsNullish())\r\n            {\r\n                OnUnbindingObject(_ctx, _this_obj);\r\n                OnUnbindingJSFuncs();\r\n                JSApi.JS_FreeValue(_ctx, _this_obj);\r\n                _this_obj = JSApi.JS_UNDEFINED;\r\n            }\r\n\r\n            var runtime = ScriptEngine.GetRuntime(_ctx);\r\n            var context = runtime?.GetContext(_ctx);\r\n            _isScriptInstanced = false;\r\n            if (_isWaitingRuntime)\r\n            {\r\n                _isWaitingRuntime = false;\r\n                ScriptEngine.RuntimeInitialized -= OnRuntimeInitialized;\r\n            }\r\n            _ctx = JSContext.Null;\r\n\r\n            if (context != null)\r\n            {\r\n                runtime.RemoveManagedObject(_handle);\r\n#if UNITY_EDITOR\r\n                context.OnScriptReloading -= OnScriptReloading;\r\n                context.OnScriptReloaded -= OnScriptReloaded;\r\n#endif\r\n            }\r\n        }\r\n\r\n#if UNITY_EDITOR\r\n        private void OnScriptReloading(ScriptContext context, string resolved_id)\r\n        {\r\n            if (context.CheckModuleId(_scriptRef, resolved_id))\r\n            {\r\n                if (_onBeforeScriptReloadValid)\r\n                {\r\n                    var rval = JSApi.JS_Call(_ctx, _onBeforeScriptReloadFunc, _this_obj);\r\n                    if (rval.IsException())\r\n                    {\r\n                        _ctx.print_exception();\r\n                    }\r\n                    else\r\n                    {\r\n                        JSApi.JS_FreeValue(_ctx, rval);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        private void OnScriptReloaded(ScriptContext context, string resolved_id)\r\n        {\r\n            if (context.CheckModuleId(_scriptRef, resolved_id))\r\n            {\r\n                if (!_this_obj.IsNullish())\r\n                {\r\n                    JSValue newClass;\r\n                    if (context.LoadModuleCacheExports(resolved_id, _scriptRef.className, out newClass))\r\n                    {\r\n                        var prototype = JSApi.JS_GetProperty(context, newClass, context.GetAtom(\"prototype\"));\r\n\r\n                        if (prototype.IsObject())\r\n                        {\r\n                            OnUnbindingJSFuncs();\r\n                            JSApi.JS_SetPrototype(context, _this_obj, prototype);\r\n                            OnBindingJSFuncs(context);\r\n\r\n                            if (_onAfterScriptReloadValid)\r\n                            {\r\n                                var rval = JSApi.JS_Call(_ctx, _onAfterScriptReloadFunc, _this_obj);\r\n                                if (rval.IsException())\r\n                                {\r\n                                    _ctx.print_exception();\r\n                                }\r\n                                else\r\n                                {\r\n                                    JSApi.JS_FreeValue(_ctx, rval);\r\n                                }\r\n                            }\r\n                        }\r\n\r\n                        JSApi.JS_FreeValue(context, prototype);\r\n                        JSApi.JS_FreeValue(context, newClass);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n#endif\r\n\r\n        #region IObjectCollectionEntry implementation\r\n        public void OnCollectionReleased()\r\n        {\r\n            ReleaseJSValues();\r\n        }\r\n        #endregion\r\n\r\n        // 通过 scriptRef 还原脚本绑定关系\r\n        public bool CreateScriptInstance()\r\n        {\r\n            if (!_isScriptInstanced)\r\n            {\r\n                if (!string.IsNullOrEmpty(_scriptRef.modulePath) && !string.IsNullOrEmpty(_scriptRef.className))\r\n                {\r\n                    var runtime = ScriptEngine.GetRuntime();\r\n                    if (runtime != null && runtime.isInitialized && runtime.isValid)\r\n                    {\r\n                        var context = runtime.GetMainContext();\r\n                        if (context != null)\r\n                        {\r\n                            var ctx = (JSContext)context;\r\n                            var snippet = $\"require('{_scriptRef.modulePath}')['{_scriptRef.className}']\";\r\n                            var bytes = System.Text.Encoding.UTF8.GetBytes(snippet);\r\n                            var typeValue = ScriptRuntime.EvalSource(ctx, bytes, _scriptRef.sourceFile, false);\r\n                            if (typeValue.IsException())\r\n                            {\r\n                                ctx.print_exception();\r\n                                SetUnresolvedScriptInstance();\r\n                            }\r\n                            else\r\n                            {\r\n                                var instValue = SetScriptInstance(ctx, typeValue, false);\r\n                                JSApi.JS_FreeValue(ctx, instValue);\r\n                                JSApi.JS_FreeValue(ctx, typeValue);\r\n                            }\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        if (!_isWaitingRuntime)\r\n                        {\r\n                            _isWaitingRuntime = true;\r\n                            ScriptEngine.RuntimeInitialized += OnRuntimeInitialized;\r\n                        }\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    SetUnresolvedScriptInstance();\r\n                }\r\n            }\r\n\r\n            return _isScriptInstanced;\r\n        }\r\n\r\n        private void OnRuntimeInitialized(ScriptRuntime runtime)\r\n        {\r\n            if (_isWaitingRuntime)\r\n            {\r\n                _isWaitingRuntime = false;\r\n                ScriptEngine.RuntimeInitialized -= OnRuntimeInitialized;\r\n                CreateScriptInstance();\r\n            }\r\n        }\r\n\r\n        // 在当前 JSBehaviour 实例上创建一个脚本实例并与之绑定\r\n        public JSValue SetScriptInstance(JSContext ctx, JSValue ctor, bool execAwake)\r\n        {\r\n            if (JSApi.JS_IsConstructor(ctx, ctor) == 1)\r\n            {\r\n                var header = JSApi.jsb_get_payload_header(ctx, ctor);\r\n                if (header.type_id == BridgeObjectType.None) // it's a plain js value\r\n                {\r\n                    var cache = ScriptEngine.GetObjectCache(ctx);\r\n\r\n                    // 旧的绑定值释放？\r\n                    OnUnbindingObject(ctx, _this_obj);\r\n                    var object_id = cache.AddObject(this, false);\r\n                    var val = JSApi.jsb_construct_bridge_object(ctx, ctor, object_id);\r\n                    if (val.IsException())\r\n                    {\r\n                        cache.RemoveObject(object_id);\r\n                        SetUnresolvedScriptInstance();\r\n                    }\r\n                    else\r\n                    {\r\n                        cache.AddJSValue(this, val);\r\n                        this._SetScriptInstance(ctx, val, execAwake);\r\n                    }\r\n\r\n                    return val;\r\n                }\r\n            }\r\n\r\n            SetUnresolvedScriptInstance();\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        private void _SetScriptInstance(JSContext ctx, JSValue this_obj, bool execAwake)\r\n        {\r\n            var runtime = ScriptEngine.GetRuntime(ctx);\r\n            var context = runtime?.GetContext(ctx);\r\n            if (context == null || !context.IsValid())\r\n            {\r\n                return;\r\n            }\r\n\r\n            ReleaseJSValues();\r\n\r\n            runtime.AddManagedObject(this, out _handle);\r\n#if UNITY_EDITOR\r\n            context.OnScriptReloading += OnScriptReloading;\r\n            context.OnScriptReloaded += OnScriptReloaded;\r\n#endif\r\n\r\n            _ctx = ctx;\r\n            _isScriptInstanced = true;\r\n            _this_obj = JSApi.JS_DupValue(ctx, this_obj);\r\n\r\n            if (!_this_obj.IsNullish())\r\n            {\r\n                OnBindingJSFuncs(context);\r\n                this._OnScriptingAfterDeserialize();\r\n            }\r\n        }\r\n\r\n        private void SetUnresolvedScriptInstance()\r\n        {\r\n            _isScriptInstanced = true;\r\n        }\r\n\r\n        public void ReleaseScriptInstance()\r\n        {\r\n            _isScriptInstanced = false;\r\n            ReleaseJSValues();\r\n        }\r\n\r\n        public void Reset()\r\n        {\r\n            if (_resetValid)\r\n            {\r\n                var rval = JSApi.JS_Call(_ctx, _resetFunc, _this_obj);\r\n                if (rval.IsException())\r\n                {\r\n                    _ctx.print_exception();\r\n                }\r\n                else\r\n                {\r\n                    JSApi.JS_FreeValue(_ctx, rval);\r\n                }\r\n            }\r\n        }\r\n\r\n        public void OnBeforeSerialize()\r\n        {\r\n            if (_onBeforeSerializeValid)\r\n            {\r\n                ExecOnBeforeSerialize(ref _properties, _ctx, _this_obj, _onBeforeSerializeFunc);\r\n            }\r\n        }\r\n\r\n        void Awake()\r\n        {\r\n            //NOTE: only Awake will be called if using Scriptable.CreateInstance\r\n            //      only OnAfterDeserialize will be called if deserializing from asset\r\n        }\r\n\r\n        public void OnAfterDeserialize()\r\n        {\r\n            if (_isScriptInstanced)\r\n            {\r\n                _OnScriptingAfterDeserialize();\r\n            }\r\n            else\r\n            {\r\n                CreateScriptInstance();\r\n            }\r\n        }\r\n\r\n        public void _OnScriptingAfterDeserialize()\r\n        {\r\n            if (_onAfterDeserializeValid)\r\n            {\r\n                ExecOnAfterDeserialize(ref _properties, _ctx, _this_obj, _onAfterDeserializeFunc);\r\n            }\r\n        }\r\n\r\n        public static void ExecOnAfterDeserialize(ref JSScriptProperties properties, JSContext ctx, JSValue this_obj, JSValue onAfterDeserializeFunc)\r\n        {\r\n            if (properties == null)\r\n            {\r\n                properties = new JSScriptProperties();\r\n            }\r\n\r\n            var buffer = new IO.ByteBuffer(properties.genericValueData);\r\n            var context = new JSSerializationContext(properties);\r\n\r\n            unsafe\r\n            {\r\n                var argv = stackalloc[] { Binding.Values.js_push_classvalue(ctx, context), Binding.Values.js_push_classvalue(ctx, buffer) };\r\n                var rval = JSApi.JS_Call(ctx, onAfterDeserializeFunc, this_obj, 2, argv);\r\n                JSApi.JS_FreeValue(ctx, argv[0]);\r\n                JSApi.JS_FreeValue(ctx, argv[1]);\r\n                if (rval.IsException())\r\n                {\r\n                    ctx.print_exception();\r\n                }\r\n                else\r\n                {\r\n                    JSApi.JS_FreeValue(ctx, rval);\r\n                }\r\n            }\r\n            context.Release();\r\n        }\r\n\r\n        public static void ExecOnBeforeSerialize(ref JSScriptProperties properties, JSContext ctx, JSValue this_obj, JSValue onBeforeSerializeFunc)\r\n        {\r\n            if (properties == null)\r\n            {\r\n                properties = new JSScriptProperties();\r\n            }\r\n            else\r\n            {\r\n                properties.Clear();\r\n            }\r\n\r\n            var context = new JSSerializationContext(properties);\r\n\r\n            unsafe\r\n            {\r\n                var argv = stackalloc[] { Binding.Values.js_push_classvalue(ctx, context) };\r\n                var rval = JSApi.JS_Call(ctx, onBeforeSerializeFunc, this_obj, 1, argv);\r\n                JSApi.JS_FreeValue(ctx, argv[0]);\r\n                JSApi.JS_FreeValue(ctx, argv[1]);\r\n                if (rval.IsException())\r\n                {\r\n                    ctx.print_exception();\r\n                }\r\n                else\r\n                {\r\n                    JSApi.JS_FreeValue(ctx, rval);\r\n                }\r\n            }\r\n            context.Release();\r\n        }\r\n\r\n        void OnEnable()\r\n        {\r\n            _enabled = true;\r\n            CreateScriptInstance();\r\n        }\r\n\r\n        void OnDisable()\r\n        {\r\n            _enabled = false;\r\n            ReleaseJSValues();\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/JSScriptableObject.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: c74456a7d35a921468a4a2a23d99cee4\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/JSSerializationContext.cs",
    "content": "#if !JSB_UNITYLESS\nusing System;\n\nnamespace QuickJS.Unity\n{\n    using UnityEngine;\n\n    public class JSSerializationContext\n    {\n        private JSScriptProperties _properties;\n        private Utils.AutoReleasePool _bufferPool = new Utils.AutoReleasePool();\n\n        public int dataFormat\n        {\n            get { return _properties.dataFormat; }\n            set { _properties.dataFormat = value; }\n        }\n\n        public JSSerializationContext(JSScriptProperties properties)\n        {\n            _properties = properties;\n        }\n\n        public int AddReferencedObject(Object value)\n        {\n            return _properties.AddReferencedObject(value);\n        }\n\n        public Object GetReferencedObject(int index)\n        {\n            return _properties.GetReferencedObject(index);\n        }\n\n        /// <summary>\n        /// flush the data of byteBuffer into JSProperties.genericValueData\n        /// </summary>\n        public void Flush(IO.ByteBuffer byteBuffer)\n        {\n            _properties.SetGenericValue(byteBuffer);\n        }\n\n        /// <summary>\n        /// allocate a new ByteBuffer from ScriptRuntime, it will autoreleased after serialization\n        /// </summary>\n        public IO.ByteBuffer AllocByteBuffer(ScriptRuntime runtime)\n        {\n            if (_bufferPool == null)\n            {\n                throw new ObjectDisposedException(this.GetType().Name);\n            }\n            var buffer = runtime.GetByteBufferAllocator().Alloc(64);\n            _bufferPool.AutoRelease(buffer);\n            return buffer;\n        }\n\n        public void Release()\n        {\n            _properties = null;\n            _bufferPool.Drain();\n            _bufferPool = null;\n        }\n    }\n}\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/JSSerializationContext.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 9ff1e3ea29e1e4a2da5153cb3d029e38\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/ObjectFix.cs",
    "content": "#if !JSB_UNITYLESS\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    public static class ObjectFix\r\n    {\r\n    }\r\n}\r\n\r\n#endif // !JSB_UNITYLESS"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/ObjectFix.cs.meta",
    "content": "fileFormatVersion: 2\nguid: f6155f7aace8ddc4f94a7606c3f9e61a\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/ResourcesFix.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using Native;\r\n    using Errors;\r\n    using Binding;\r\n    using UnityEngine;\r\n\r\n    public static class ResourcesFix\r\n    {\r\n        [MonoPInvokeCallbackAttribute(typeof(JSCFunction))]\r\n        public static JSValue BindStatic_FindObjectsOfTypeAll(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            try\r\n            {\r\n                if (argc == 1)\r\n                {\r\n                    System.Type arg_type;\r\n                    if (!Values.js_get_classvalue(ctx, argv[0], out arg_type))\r\n                    {\r\n                        throw new ParameterException(typeof(Resources), \"FindObjectsOfTypeAll\", typeof(System.Type), 0);\r\n                    }\r\n                    var inject = js_find_objects_of_type_all(ctx, argv[0], arg_type);\r\n                    if (!inject.IsUndefined())\r\n                    {\r\n                        return inject;\r\n                    }\r\n                    var ret = Resources.FindObjectsOfTypeAll(arg_type);\r\n                    return Values.PushArray(ctx, ret);\r\n                }\r\n\r\n                throw new NotImplementedException();\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        public static JSValue js_find_objects_of_type_all(JSContext ctx, JSValue ctor, Type type)\r\n        {\r\n            if (JSApi.JS_IsConstructor(ctx, ctor) == 1)\r\n            {\r\n                var header = JSApi.jsb_get_payload_header(ctx, ctor);\r\n\r\n                if (header.type_id == BridgeObjectType.None) // it's a plain js value\r\n                {\r\n                    var typeDB = ScriptEngine.GetTypeDB(ctx);\r\n                    if (!typeDB.IsConstructorEquals(type, ctor))\r\n                    {\r\n                        var objects = Resources.FindObjectsOfTypeAll(type);\r\n                        var len = objects.Length;\r\n                        var array = JSApi.JS_NewArray(ctx);\r\n                        var arrayLength = 0;\r\n\r\n                        for (var i = 0; i < len; ++i)\r\n                        {\r\n                            var obj = objects[i];\r\n\r\n                            if (typeof(IScriptInstancedObject).IsAssignableFrom(obj.GetType()))\r\n                            {\r\n                                var si = (IScriptInstancedObject)obj;\r\n                                if (si.IsInstanceOf(ctor) == 1)\r\n                                {\r\n                                    JSApi.JS_SetPropertyUint32(ctx, array, (uint)arrayLength, si.CloneValue());\r\n                                    arrayLength++;\r\n                                }\r\n                                continue;\r\n                            }\r\n                        }\r\n\r\n                        return array;\r\n                    }\r\n                }\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n    }\r\n}\r\n\r\n#endif // !JSB_UNITYLESS"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/ResourcesFix.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 4770a7341bc885d40b39fc6503fe01a6\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/ScriptEditorSupport.cs",
    "content": "#if !JSB_UNITYLESS\n\nnamespace QuickJS.Unity\n{\n    using Native;\n\n    public interface IScriptEditorSupport : IScriptInstancedObject\n    {\n        bool isStandaloneScript { get; }\n\n        bool isScriptInstanced { get; }\n\n        JSScriptRef scriptRef { get; set; }\n\n        JSContext ctx { get; }\n\n        JSScriptProperties properties { get; }\n\n        bool IsValid();\n\n        bool CreateScriptInstance();\n    }\n}\n\n#endif\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/ScriptEditorSupport.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 478a5f29c4c1cea4390bb5f0667f12cb\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/ScriptInstancedObject.cs",
    "content": "#if !JSB_UNITYLESS\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using Native;\r\n\r\n    public interface IScriptInstancedObject\r\n    {\r\n        int IsInstanceOf(JSValue ctor);\r\n        JSValue CloneValue();\r\n        JSValue SetScriptInstance(JSContext ctx, JSValue ctor, bool execAwake);\r\n        void ReleaseScriptInstance();\r\n    }\r\n}\r\n\r\n#endif // JSB_UNITYLESS\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/ScriptInstancedObject.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 3b467906077fb574dad9d6134addf58b\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/ScriptableObjectFix.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using Native;\r\n    using Binding;\r\n    using Errors;\r\n    using UnityEngine;\r\n\r\n    public static class ScriptableObjectFix\r\n    {\r\n        [MonoPInvokeCallbackAttribute(typeof(JSCFunction))]\r\n        public static JSValue BindStatic_CreateInstance(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            try\r\n            {\r\n                if (argc == 1)\r\n                {\r\n                    System.Type arg_type;\r\n                    if (!Values.js_get_classvalue(ctx, argv[0], out arg_type))\r\n                    {\r\n                        throw new ParameterException(typeof(ScriptableObject), \"CreateInstance\", typeof(System.Type), 0);\r\n                    }\r\n                    var inject = js_create_instance(ctx, argv[0], arg_type);\r\n                    if (!inject.IsUndefined())\r\n                    {\r\n                        return inject;\r\n                    }\r\n                    var ret = ScriptableObject.CreateInstance(arg_type);\r\n                    return Values.js_push_classvalue(ctx, ret);\r\n                }\r\n\r\n                throw new NotImplementedException();\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        public static JSValue js_create_instance(JSContext ctx, JSValue ctor, Type type)\r\n        {\r\n            if (JSApi.JS_IsConstructor(ctx, ctor) == 1)\r\n            {\r\n                var header = JSApi.jsb_get_payload_header(ctx, ctor);\r\n                if (header.type_id == BridgeObjectType.None) // it's a plain js value\r\n                {\r\n                    var typeDB = ScriptEngine.GetTypeDB(ctx);\r\n                    if (!typeDB.IsConstructorEquals(type, ctor))\r\n                    {\r\n                        Type bridgeType = null;\r\n                        if (type == typeof(ScriptableObject))\r\n                        {\r\n                            bridgeType = typeof(JSScriptableObject);\r\n                        }\r\n                        else if (type == typeof(MonoBehaviour))\r\n                        {\r\n                            bridgeType = typeof(JSBehaviourFull);\r\n                        }\r\n#if UNITY_EDITOR\r\n                        else if (type == typeof(UnityEditor.EditorWindow))\r\n                        {\r\n                            bridgeType = typeof(JSEditorWindow);\r\n                        }\r\n#endif // !UNITY_EDITOR\r\n\r\n                        if (bridgeType != null)\r\n                        {\r\n                            var scriptableObject = (IScriptInstancedObject)ScriptableObject.CreateInstance(bridgeType);\r\n                            var bridgeValue = scriptableObject.SetScriptInstance(ctx, ctor, false);\r\n\r\n                            if (!bridgeValue.IsUndefined())\r\n                            {\r\n                                return bridgeValue;\r\n                            }\r\n\r\n                            scriptableObject.ReleaseScriptInstance();\r\n                            Object.DestroyImmediate((Object)scriptableObject);\r\n                            return JSApi.JS_NULL;\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            // fallthrough\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n    }\r\n}\r\n\r\n#endif // !JSB_UNITYLESS"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/ScriptableObjectFix.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 97a26f8a71e75c1409bbfc5525cf9d69\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/UnityCoroutineContext.cs",
    "content": "#if !JSB_UNITYLESS\r\nusing System.Collections;\r\n\r\nnamespace QuickJS.Unity\r\n{\r\n    using QuickJS.Native;\r\n    using QuickJS.Utils;\r\n    using UnityEngine;\r\n\r\n    public class UnityCoroutineContext : MonoBehaviour\r\n    {\r\n        internal void RunTask(object awaitObject, ScriptContext context, SafeRelease safeRelease)\r\n        {\r\n            if (awaitObject is IEnumerator)\r\n            {\r\n                StartCoroutine(_Pending(awaitObject as IEnumerator, context, safeRelease));\r\n            }\r\n            else\r\n            {\r\n                StartCoroutine(_Pending(awaitObject as YieldInstruction, context, safeRelease));\r\n            }\r\n        }\r\n\r\n        private IEnumerator _Pending(YieldInstruction instruction, ScriptContext context, SafeRelease safeRelease)\r\n        {\r\n            yield return instruction;\r\n\r\n            if (!context.IsValid())\r\n            {\r\n                yield break;\r\n            }\r\n\r\n            if (!safeRelease.isValid)\r\n            {\r\n                Diagnostics.Logger.Default.Error(\"pormise func has already been released\");\r\n                yield break;\r\n            }\r\n\r\n            var ctx = (JSContext)context;\r\n            var backVal = Binding.Values.js_push_classvalue(ctx, instruction);\r\n            if (backVal.IsException())\r\n            {\r\n                ctx.print_exception();\r\n                safeRelease.Release();\r\n                yield break;\r\n            }\r\n\r\n            var rval = JSApi.Call(ctx, safeRelease[0], JSApi.JS_UNDEFINED, backVal);\r\n            JSApi.JS_FreeValue(ctx, backVal);\r\n            if (rval.IsException())\r\n            {\r\n                ctx.print_exception();\r\n                safeRelease.Release();\r\n                yield break;\r\n            }\r\n\r\n            JSApi.JS_FreeValue(ctx, rval);\r\n            safeRelease.Release();\r\n\r\n            context.GetRuntime().ExecutePendingJob();\r\n        }\r\n\r\n        private IEnumerator _Pending(IEnumerator enumerator, ScriptContext context, SafeRelease safeRelease)\r\n        {\r\n            while (enumerator.MoveNext())\r\n            {\r\n                var current = enumerator.Current;\r\n\r\n                if (current is YieldInstruction)\r\n                {\r\n                    yield return current;\r\n                }\r\n\r\n                yield return null;\r\n            }\r\n\r\n            if (!context.IsValid())\r\n            {\r\n                yield break;\r\n            }\r\n\r\n            if (!safeRelease.isValid)\r\n            {\r\n                Diagnostics.Logger.Default.Error(\"pormise func has already been released\");\r\n                yield break;\r\n            }\r\n\r\n            var ctx = (JSContext)context;\r\n            var backVal = Binding.Values.js_push_var(ctx, enumerator.Current);\r\n            if (backVal.IsException())\r\n            {\r\n                ctx.print_exception();\r\n                safeRelease.Release();\r\n                yield break;\r\n            }\r\n\r\n            var rval = JSApi.Call(ctx, safeRelease[0], JSApi.JS_UNDEFINED, backVal);\r\n            JSApi.JS_FreeValue(ctx, backVal);\r\n            if (rval.IsException())\r\n            {\r\n                ctx.print_exception();\r\n                safeRelease.Release();\r\n                yield break;\r\n            }\r\n\r\n            JSApi.JS_FreeValue(ctx, rval);\r\n            safeRelease.Release();\r\n\r\n            context.GetRuntime().ExecutePendingJob();\r\n        }\r\n    }\r\n}\r\n\r\n#endif // !JSB_UNITYLESS"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity/UnityCoroutineContext.cs.meta",
    "content": "fileFormatVersion: 2\nguid: f27026bc3190b8d44a5f07351b7d641e\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Unity.meta",
    "content": "fileFormatVersion: 2\r\nguid: 044d3429d1ce7e94fbb9d3ae59dfa4b3\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/AtomCache.cs",
    "content": "using System.Collections.Generic;\r\nusing QuickJS.Native;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    /// <summary>\r\n    /// a cache for JSAtom (preventing repeatedly gc alloc of string => bytes convertion)\r\n    /// </summary>\r\n    public class AtomCache\r\n    {\r\n        private JSContext _ctx;\r\n        private Dictionary<string, JSAtom> _atoms = new Dictionary<string, JSAtom>();\r\n\r\n        public AtomCache(JSContext ctx)\r\n        {\r\n            _ctx = ctx;\r\n        }\r\n\r\n        public unsafe JSAtom GetAtom(string name)\r\n        {\r\n            JSAtom atom;\r\n            if (!_atoms.TryGetValue(name, out atom))\r\n            {\r\n                var bytes = TextUtils.GetNullTerminatedBytes(name);\r\n                fixed (byte* ptr = bytes)\r\n                {\r\n                    atom = JSApi.JS_NewAtomLen(_ctx, ptr, bytes.Length - 1);\r\n                }\r\n\r\n                _atoms[name] = atom;\r\n            }\r\n\r\n            return atom;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Clear the atom cache. It's safe to clear the cache for memory shrinking, the atom will be re-cached at next GetAtom() call.\r\n        /// </summary>\r\n        public void Clear()\r\n        {\r\n            foreach (var kv in _atoms)\r\n            {\r\n                var atom = kv.Value;\r\n                JSApi.JS_FreeAtom(_ctx, atom);\r\n            }\r\n\r\n            _atoms.Clear();\r\n        }\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/AtomCache.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: dddf3cebbe67d9b42b319908e53b0a0a\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/AutoReleasePool.cs",
    "content": "using System.Collections.Generic;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    public class AutoReleasePool\r\n    {\r\n        private List<IReferenceObject> _autoreleases = new List<IReferenceObject>();\r\n\r\n        public void AutoRelease(IReferenceObject b)\r\n        {\r\n            _autoreleases.Add(b);\r\n        }\r\n\r\n        public void Drain()\r\n        {\r\n            var size = _autoreleases.Count;\r\n            if (size > 0)\r\n            {\r\n                for (var i = 0; i < size; ++i)\r\n                {\r\n                    var b = _autoreleases[i];\r\n                    b.Release();\r\n                }\r\n                _autoreleases.Clear();\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/AutoReleasePool.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: dc46929a5ca30ae42b9d5d31f14dea8d\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/DefaultAsyncManager.cs",
    "content": "﻿using System;\r\nusing System.IO;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\nusing System.Threading;\r\nusing System.Threading.Tasks;\r\nusing System.Net;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    using Native;\r\n    using Utils;\r\n\r\n    public class DefaultAsyncManager : IAsyncManager\r\n    {\r\n        private class JSTaskCompletionArgs\r\n        {\r\n            public System.Threading.Tasks.Task task;\r\n            public SafeRelease safeRelease;\r\n\r\n            public JSTaskCompletionArgs(System.Threading.Tasks.Task task, SafeRelease safeRelease)\r\n            {\r\n                this.task = task;\r\n                this.safeRelease = safeRelease;\r\n            }\r\n        }\r\n\r\n        private int _mainThreadId;\r\n\r\n#if !JSB_UNITYLESS\r\n        private Unity.UnityCoroutineContext _mb = null;\r\n#endif\r\n\r\n        public DefaultAsyncManager()\r\n        {\r\n\r\n        }\r\n\r\n        public void Initialize(int mainThreadId)\r\n        {\r\n            _mainThreadId = mainThreadId;\r\n        }\r\n\r\n        public void Destroy()\r\n        {\r\n#if !JSB_UNITYLESS\r\n            if (_mb != null)\r\n            {\r\n                UnityEngine.Object.DestroyImmediate(_mb.gameObject);\r\n                _mb = null;\r\n            }\r\n#endif\r\n        }\r\n\r\n        // return promise\r\n        public unsafe JSValue Yield(ScriptContext context, object awaitObject)\r\n        {\r\n            var ctx = (JSContext)context;\r\n\r\n            if (awaitObject is System.Threading.Tasks.Task)\r\n            {\r\n                var resolving_funcs = stackalloc[] { JSApi.JS_UNDEFINED, JSApi.JS_UNDEFINED };\r\n                var promise = JSApi.JS_NewPromiseCapability(ctx, resolving_funcs);\r\n                var safeRelease = new SafeRelease(context).Append(2, resolving_funcs);\r\n                var task = awaitObject as System.Threading.Tasks.Task;\r\n                var runtime = context.GetRuntime();\r\n\r\n#if JSB_COMPATIBLE\r\n                task.ContinueWith(antecedent => runtime.EnqueueAction(_OnTaskCompleted, new JSTaskCompletionArgs(task, safeRelease)));\r\n#else\r\n                task.GetAwaiter().OnCompleted(() =>\r\n                {\r\n                    runtime.EnqueueAction(_OnTaskCompleted, new JSTaskCompletionArgs(task, safeRelease));\r\n                });\r\n#endif\r\n                return promise;\r\n            }\r\n#if !JSB_UNITYLESS\r\n            else\r\n            {\r\n                if (_mainThreadId != Thread.CurrentThread.ManagedThreadId)\r\n                {\r\n                    return ctx.ThrowInternalError(\"not supported on background thread\");\r\n                }\r\n\r\n                if (_mb == null)\r\n                {\r\n                    var container = new UnityEngine.GameObject(\"JSRuntimeContainer\");\r\n                    container.hideFlags = UnityEngine.HideFlags.HideInHierarchy;\r\n                    UnityEngine.Object.DontDestroyOnLoad(container);\r\n                    _mb = container.AddComponent<Unity.UnityCoroutineContext>();\r\n                }\r\n\r\n                var resolving_funcs = stackalloc[] { JSApi.JS_UNDEFINED, JSApi.JS_UNDEFINED };\r\n                var promise = JSApi.JS_NewPromiseCapability(ctx, resolving_funcs);\r\n                var safeRelease = new SafeRelease(context).Append(2, resolving_funcs);\r\n\r\n                _mb.RunTask(awaitObject, context, safeRelease);\r\n                return promise;\r\n            }\r\n#else \r\n            return ctx.ThrowInternalError(\"not supported await object\");\r\n#endif // !JSB_UNITYLESS\r\n        }\r\n\r\n        private static unsafe void _OnTaskCompleted(ScriptRuntime runtime, object cbArgs, JSValue cbValue)\r\n        {\r\n            if (!runtime.isValid || !runtime.isRunning)\r\n            {\r\n                return;\r\n            }\r\n            var context = runtime.GetMainContext();\r\n            var args = (JSTaskCompletionArgs)cbArgs;\r\n            var task = args.task;\r\n            var safeRelease = args.safeRelease;\r\n\r\n            if (!safeRelease.isValid)\r\n            {\r\n                Diagnostics.Logger.Default.Error(\"pormise func has already been released\");\r\n                return;\r\n            }\r\n\r\n            object result = null;\r\n            var taskType = task.GetType();\r\n\r\n            if (taskType.IsGenericType && taskType.GetGenericTypeDefinition() == typeof(Task<>))\r\n            {\r\n                try\r\n                {\r\n                    result = taskType.GetProperty(\"Result\").GetValue(task, null);\r\n                }\r\n                catch (Exception exception)\r\n                {\r\n                    Diagnostics.Logger.Default.Exception(exception);\r\n                }\r\n            }\r\n\r\n            var ctx = (JSContext)context;\r\n            var backVal = Binding.Values.js_push_var(ctx, result);\r\n            if (backVal.IsException())\r\n            {\r\n                ctx.print_exception();\r\n                safeRelease.Release();\r\n                return;\r\n            }\r\n\r\n            var argv = stackalloc[] { backVal };\r\n            var rval = JSApi.JS_Call(ctx, safeRelease[0], JSApi.JS_UNDEFINED, 1, argv);\r\n            JSApi.JS_FreeValue(ctx, backVal);\r\n            if (rval.IsException())\r\n            {\r\n                ctx.print_exception();\r\n                safeRelease.Release();\r\n                return;\r\n            }\r\n\r\n            JSApi.JS_FreeValue(ctx, rval);\r\n            safeRelease.Release();\r\n\r\n            context.GetRuntime().ExecutePendingJob();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/DefaultAsyncManager.cs.meta",
    "content": "fileFormatVersion: 2\nguid: df95e5eb9134d434297715531a967773\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/DefaultJsonConverter.cs",
    "content": "using System;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    public class DefaultJsonConverter : IJsonConverter\r\n    {\r\n        public object Deserialize(string json, Type type)\r\n        {\r\n            // If inside Unity, use Unity's JSON utility even if JSB_UNITYLESS is defined\r\n#if JSB_UNITYLESS && !UNITY_2019_1_OR_NEWER\r\n#if JSB_COMPATIBLE\r\n            throw new NotImplementedException();\r\n#else\r\n            return System.Text.Json.JsonSerializer.Deserialize(json, type);\r\n#endif\r\n#else\r\n            return UnityEngine.JsonUtility.FromJson(json, type);\r\n#endif\r\n        }\r\n\r\n        public string Serialize(object obj, bool prettyPrint)\r\n        {\r\n#if JSB_UNITYLESS && !UNITY_2019_1_OR_NEWER\r\n#if JSB_COMPATIBLE\r\n            throw new NotImplementedException();\r\n#else\r\n            return System.Text.Json.JsonSerializer.Serialize(obj);\r\n#endif\r\n#else\r\n            return UnityEngine.JsonUtility.ToJson(obj, true);\r\n#endif\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/DefaultJsonConverter.cs.meta",
    "content": "fileFormatVersion: 2\nguid: ba8a063fd23dd9348a9f4fcf9aa04a16\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/DefaultTimerManager.cs",
    "content": "﻿using System;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\nusing QuickJS.Binding;\r\nusing QuickJS.Native;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    public readonly struct TimerInfo\r\n    {\r\n        public readonly uint id;\r\n        public readonly int delay;\r\n        public readonly int deadline;\r\n        public readonly bool once;\r\n\r\n        public TimerInfo(uint id, int delay, int deadline, bool once)\r\n        {\r\n            this.id = id;\r\n            this.delay = delay;\r\n            this.deadline = deadline;\r\n            this.once = once;\r\n        }\r\n    }\r\n\r\n    public class DefaultTimerManager : ITimerManager\r\n    {\r\n        private uint _idgen;\r\n        private TimerManager _manager = new TimerManager();\r\n        private Dictionary<uint, SIndex> _timers = new Dictionary<uint, SIndex>();\r\n\r\n        public DefaultTimerManager()\r\n        {\r\n        }\r\n\r\n        public int now => (int)_manager.now;\r\n\r\n        public void Update(int milliseconds)\r\n        {\r\n            _manager.Update((uint)milliseconds);\r\n        }\r\n\r\n        public void Destroy()\r\n        {\r\n            _manager.Clear();\r\n            _timers.Clear();\r\n        }\r\n\r\n        public uint SetTimeout(ScriptFunction fn, int ms)\r\n        {\r\n            var id = ++_idgen;\r\n            var index = SIndex.None;\r\n            _manager.SetTimer(ref index, fn, (uint)ms, false);\r\n            _timers.Add(id, index);\r\n            return id;\r\n        }\r\n\r\n        public uint SetInterval(ScriptFunction fn, int ms)\r\n        {\r\n            var id = ++_idgen;\r\n            var index = SIndex.None;\r\n            _manager.SetTimer(ref index, fn, (uint)ms, true);\r\n            _timers.Add(id, index);\r\n            return id;\r\n        }\r\n\r\n        public bool ClearTimer(uint id)\r\n        {\r\n            if (_timers.TryGetValue(id, out var index))\r\n            {\r\n                _timers.Remove(id);\r\n                _manager.ClearTimer(index);\r\n                return true;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue js_clear_timer(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc >= 1)\r\n            {\r\n                uint pres;\r\n                if (JSApi.JSB_ToUint32(ctx, out pres, argv[0]) >= 0)\r\n                {\r\n                    var tm = ScriptEngine.GetTimerManager(ctx);\r\n                    if (tm != null)\r\n                    {\r\n                        tm.ClearTimer(pres);\r\n                    }\r\n                }\r\n            }\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static unsafe JSValue js_set_immediate(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc >= 1)\r\n            {\r\n                var timerManager = ScriptEngine.GetTimerManager(ctx);\r\n                if (timerManager == null)\r\n                {\r\n                    return ctx.ThrowTypeError(\"no bound TimerManager\");\r\n                }\r\n\r\n                ScriptFunction func;\r\n                if (!Values.js_get_classvalue(ctx, argv[0], out func) || func == null)\r\n                {\r\n                    return ctx.ThrowTypeError(\"the first arg is not a function\");\r\n                }\r\n\r\n                func.SetBound(this_obj);\r\n                func.SetArguments(1, argc - 1, argv);\r\n                var timer = timerManager.SetInterval(func, 0);\r\n                return JSApi.JS_NewUint32(ctx, timer);\r\n            }\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue js_set_interval(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc >= 1)\r\n            {\r\n                int pres = 0;\r\n                if (argc >= 2)\r\n                {\r\n                    if (JSApi.JS_ToInt32(ctx, out pres, argv[1]) < 0)\r\n                    {\r\n                        return ctx.ThrowTypeError(\"the given interval is not a number\");\r\n                    }\r\n                }\r\n\r\n                var timerManager = ScriptEngine.GetTimerManager(ctx);\r\n                if (timerManager == null)\r\n                {\r\n                    return ctx.ThrowTypeError(\"no bound TimerManager\");\r\n                }\r\n\r\n                ScriptFunction func;\r\n                if (!Values.js_get_classvalue(ctx, argv[0], out func) || func == null)\r\n                {\r\n                    return ctx.ThrowTypeError(\"the first arg is not a function\");\r\n                }\r\n\r\n                func.SetBound(this_obj);\r\n                func.SetArguments(2, argc - 2, argv);\r\n                var timer = timerManager.SetInterval(func, pres);\r\n                return JSApi.JS_NewUint32(ctx, timer);\r\n            }\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        public static JSValue js_set_timeout(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            if (argc >= 1)\r\n            {\r\n                int pres = 0;\r\n                if (argc >= 2)\r\n                {\r\n                    if (JSApi.JS_ToInt32(ctx, out pres, argv[1]) < 0)\r\n                    {\r\n                        return ctx.ThrowTypeError(\"the given interval is not a number\");\r\n                    }\r\n                }\r\n\r\n                var timerManager = ScriptEngine.GetTimerManager(ctx);\r\n                if (timerManager == null)\r\n                {\r\n                    return ctx.ThrowTypeError(\"no bound TimerManager\");\r\n                }\r\n\r\n                ScriptFunction func;\r\n                if (!Values.js_get_classvalue(ctx, argv[0], out func) || func == null)\r\n                {\r\n                    return ctx.ThrowTypeError(\"the first arg is not a function\");\r\n                }\r\n\r\n                func.SetBound(this_obj);\r\n                func.SetArguments(2, argc - 2, argv);\r\n                var timer = timerManager.SetTimeout(func, pres);\r\n                return JSApi.JS_NewUint32(ctx, timer);\r\n            }\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        public void Bind(TypeRegister register)\r\n        {\r\n            var context = register.GetContext();\r\n\r\n            context.AddGlobalFunction(\"setImmediate\", js_set_immediate, 2);\r\n            context.AddGlobalFunction(\"setInterval\", js_set_interval, 3);\r\n            context.AddGlobalFunction(\"setTimeout\", js_set_timeout, 3);\r\n            context.AddGlobalFunction(\"clearImmediate\", js_clear_timer, 1);\r\n            context.AddGlobalFunction(\"clearInterval\", js_clear_timer, 1);\r\n            context.AddGlobalFunction(\"clearTimeout\", js_clear_timer, 1);\r\n        }\r\n\r\n        #region Enumeration Support\r\n        IEnumerator<TimerInfo> IEnumerable<TimerInfo>.GetEnumerator() => (IEnumerator<TimerInfo>)this.GetEnumerator();\r\n        IEnumerator IEnumerable.GetEnumerator() => (IEnumerator)this.GetEnumerator();\r\n        public Enumerator GetEnumerator() => new Enumerator(this);\r\n        public struct Enumerator : IEnumerator<TimerInfo>, IDisposable, IEnumerator\r\n        {\r\n            private DefaultTimerManager _self;\r\n            private Dictionary<uint, SIndex>.Enumerator _e;\r\n\r\n            public Enumerator(DefaultTimerManager self)\r\n            {\r\n                _self = self;\r\n                _e = self._timers.GetEnumerator();\r\n            }\r\n\r\n            public TimerInfo Current\r\n            {\r\n                get\r\n                {\r\n                    var pair = _e.Current;\r\n                    var data = _self._manager.GetTimerInfo(pair.Value);\r\n                    return new TimerInfo(pair.Key, data.delay, data.deadline, data.once);\r\n                }\r\n            }\r\n\r\n            public void Reset()\r\n            {\r\n                _e = _self._timers.GetEnumerator();\r\n            }\r\n\r\n            public bool MoveNext()\r\n            {\r\n                return _e.MoveNext();\r\n            }\r\n\r\n            public void Dispose() => _e.Dispose();\r\n\r\n            void IDisposable.Dispose() => _e.Dispose();\r\n\r\n            object IEnumerator.Current\r\n            {\r\n                get\r\n                {\r\n                    var pair = _e.Current;\r\n                    var data = _self._manager.GetTimerInfo(pair.Value);\r\n                    return (object)new TimerInfo(pair.Key, data.delay, data.deadline, data.once);\r\n                }\r\n            }\r\n        }\r\n\r\n        #endregion\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/DefaultTimerManager.cs.meta",
    "content": "fileFormatVersion: 2\nguid: c561430cf869f44129a1ba9d983192ac\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/EqualityComparer.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    public class EqualityComparer : IEqualityComparer<object>\r\n    {\r\n        public static readonly EqualityComparer Default = new EqualityComparer();\r\n\r\n        public new bool Equals(object x, object y)\r\n        {\r\n            return ReferenceEquals(x, y);\r\n        }\r\n\r\n        public int GetHashCode(object obj)\r\n        {\r\n            return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/EqualityComparer.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: a1d3a8df6a7f546439a924ff7b2a3e7c\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/FSWatcher.cs",
    "content": "using System;\r\nusing System.IO;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    using QuickJS;\r\n    using QuickJS.Errors;\r\n    using QuickJS.Native;\r\n    using QuickJS.Binding;\r\n\r\n    public class FSWatcher : Values, IDisposable, IObjectCollectionEntry\r\n    {\r\n        private FileSystemWatcher _fsw;\r\n        private bool _isDelayedUntilActive = true;\r\n\r\n        private FSWatcher(string path, string filter)\r\n        {\r\n            try\r\n            {\r\n                _fsw = new FileSystemWatcher(path ?? \".\", filter ?? \"*.*\");\r\n                _fsw.Changed += OnChanged;\r\n                _fsw.Created += OnCreated;\r\n                _fsw.Deleted += OnDeleted;\r\n                _fsw.EnableRaisingEvents = true;\r\n            }\r\n            catch (Exception)\r\n            {\r\n                // failed to watch, it usually caused by watching not-exsited folder/file\r\n            }\r\n        }\r\n\r\n        private void OnChanged(object sender, FileSystemEventArgs e)\r\n        {\r\n            _runtime.EnqueueAction(_JSActionCallback, e, _isDelayedUntilActive);\r\n        }\r\n\r\n        private void OnCreated(object sender, FileSystemEventArgs e)\r\n        {\r\n            _runtime.EnqueueAction(_JSActionCallback, e, _isDelayedUntilActive);\r\n        }\r\n\r\n        private void OnDeleted(object sender, FileSystemEventArgs e)\r\n        {\r\n            _runtime.EnqueueAction(_JSActionCallback, e, _isDelayedUntilActive);\r\n        }\r\n\r\n        private void _DisposeWatcher()\r\n        {\r\n            if (_fsw != null)\r\n            {\r\n                _fsw.Dispose();\r\n                _fsw = null;\r\n            }\r\n        }\r\n\r\n        private static string GetFullPath(string filePath)\r\n        {\r\n#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX\r\n            return new FileInfo(filePath).FullName;\r\n#else\r\n            return filePath;\r\n#endif\r\n        }\r\n\r\n        private void _JSActionCallback(ScriptRuntime runtime, object cbArgs, JSValue cbValue)\r\n        {\r\n            // check if the runtime or this FSWatcher has already been destroyed\r\n            if (!runtime.isValid || !runtime.isRunning || _runtime == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            var e = (FileSystemEventArgs)cbArgs;\r\n            switch (e.ChangeType)\r\n            {\r\n                case WatcherChangeTypes.Changed:\r\n                    Call(_onchange, e.Name, GetFullPath(e.FullPath));\r\n                    break;\r\n                case WatcherChangeTypes.Created:\r\n                    Call(_oncreate, e.Name, GetFullPath(e.FullPath));\r\n                    break;\r\n                case WatcherChangeTypes.Deleted:\r\n                    Call(_ondelete, e.Name, GetFullPath(e.FullPath));\r\n                    break;\r\n            }\r\n        }\r\n\r\n        private unsafe void Call(JSValue func, string name, string fullPath)\r\n        {\r\n            if (JSApi.JS_IsFunction(_jsContext, func) != 1)\r\n            {\r\n                return;\r\n            }\r\n\r\n            var argv = stackalloc JSValue[2]\r\n            {\r\n                _jsContext.NewString(name),\r\n                _jsContext.NewString(fullPath),\r\n            };\r\n            var ret = JSApi.JS_Call(_jsContext, func, JSApi.JS_UNDEFINED, 2, argv);\r\n            JSApi.JS_FreeValue(_jsContext, argv[0]);\r\n            JSApi.JS_FreeValue(_jsContext, argv[1]);\r\n            if (ret.IsException())\r\n            {\r\n                Diagnostics.Logger.Default.Error(\"exception thrown in FSWatcher.Call: {0} Path: {1}\", name, fullPath);\r\n            }\r\n            else\r\n            {\r\n                JSApi.JS_FreeValue(_jsContext, ret);\r\n            }\r\n        }\r\n\r\n        #region JS Bridging\r\n        private JSContext _jsContext; // dangeous reference holder\r\n        private ScriptRuntime _runtime;\r\n\r\n        private JSValue _oncreate;\r\n        private JSValue _ondelete;\r\n        private JSValue _onchange;\r\n\r\n        private ObjectCollection.Handle _handle;\r\n\r\n        #region IObjectCollectionEntry implementation\r\n        public void OnCollectionReleased()\r\n        {\r\n            Dispose();\r\n        }\r\n        #endregion\r\n\r\n        // = OnJSFinalize\r\n        public void Dispose()\r\n        {\r\n            if (_runtime == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            var runtime = _runtime;\r\n            _runtime = null;\r\n            _DisposeWatcher();\r\n            var cache = runtime.GetObjectCache();\r\n            if (cache.TryGetJSValue(this, out var this_obj))\r\n            {\r\n                cache.RemoveObject(JSApi.JSB_FreePayload(_jsContext, this_obj));\r\n            }\r\n            runtime.RemoveManagedObject(_handle);\r\n            JSApi.JS_FreeValue(_jsContext, _oncreate);\r\n            _oncreate = JSApi.JS_UNDEFINED;\r\n            JSApi.JS_FreeValue(_jsContext, _ondelete);\r\n            _ondelete = JSApi.JS_UNDEFINED;\r\n            JSApi.JS_FreeValue(_jsContext, _onchange);\r\n            _onchange = JSApi.JS_UNDEFINED;\r\n            _jsContext = JSContext.Null;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunctionMagic))]\r\n        private static JSValue js_constructor(JSContext ctx, JSValue new_target, int argc, JSValue[] argv, int magic)\r\n        {\r\n            string path = null;\r\n            string filter = null;\r\n            if (argc > 0)\r\n            {\r\n                js_get_primitive(ctx, argv[0], out path);\r\n            }\r\n            if (argc > 1)\r\n            {\r\n                js_get_primitive(ctx, argv[1], out filter);\r\n            }\r\n            var o = new FSWatcher(path, filter);\r\n            var val = NewBridgeClassObject(ctx, new_target, o, magic, true);\r\n            o._jsContext = ctx;\r\n            o._runtime = ScriptEngine.GetRuntime(ctx);\r\n            o._runtime.AddManagedObject(o, out o._handle);\r\n            return val;\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSCFunction))]\r\n        private static JSValue js_dispose(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n\r\n                self._DisposeWatcher();\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue js_get_onchange(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                return JSApi.JS_DupValue(ctx, self._onchange);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSSetterCFunction))]\r\n        private static JSValue js_set_onchange(JSContext ctx, JSValue this_obj, JSValue val)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                JSApi.JS_FreeValue(ctx, self._onchange);\r\n                self._onchange = JSApi.JS_DupValue(ctx, val);\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue js_get_oncreate(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                return JSApi.JS_DupValue(ctx, self._oncreate);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSSetterCFunction))]\r\n        private static JSValue js_set_oncreate(JSContext ctx, JSValue this_obj, JSValue val)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                JSApi.JS_FreeValue(ctx, self._oncreate);\r\n                self._oncreate = JSApi.JS_DupValue(ctx, val);\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue js_get_ondelete(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                return JSApi.JS_DupValue(ctx, self._ondelete);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSSetterCFunction))]\r\n        private static JSValue js_set_ondelete(JSContext ctx, JSValue this_obj, JSValue val)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                JSApi.JS_FreeValue(ctx, self._ondelete);\r\n                self._ondelete = JSApi.JS_DupValue(ctx, val);\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue js_get_path(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                if (self._fsw == null)\r\n                {\r\n                    throw new InvalidOperationException();\r\n                }\r\n\r\n                return ctx.NewString(self._fsw.Path);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSSetterCFunction))]\r\n        private static JSValue js_set_path(JSContext ctx, JSValue this_obj, JSValue val)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                if (self._fsw == null)\r\n                {\r\n                    throw new InvalidOperationException();\r\n                }\r\n                if (!val.IsString())\r\n                {\r\n                    throw new InvalidDataException();\r\n                }\r\n\r\n                self._fsw.Path = JSApi.GetString(ctx, val);\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue js_get_filter(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                if (self._fsw == null)\r\n                {\r\n                    throw new InvalidOperationException();\r\n                }\r\n\r\n                return ctx.NewString(self._fsw.Filter);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSSetterCFunction))]\r\n        private static JSValue js_set_filter(JSContext ctx, JSValue this_obj, JSValue val)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                if (self._fsw == null)\r\n                {\r\n                    throw new InvalidOperationException();\r\n                }\r\n                if (!val.IsString())\r\n                {\r\n                    throw new InvalidDataException();\r\n                }\r\n\r\n                self._fsw.Filter = JSApi.GetString(ctx, val);\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue js_get_isValid(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n\r\n                return self._fsw != null ? JSApi.JS_TRUE : JSApi.JS_FALSE;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue js_get_includeSubdirectories(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                if (self._fsw == null)\r\n                {\r\n                    throw new InvalidOperationException();\r\n                }\r\n\r\n                return JSApi.JS_NewBool(ctx, self._fsw.IncludeSubdirectories);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSSetterCFunction))]\r\n        private static JSValue js_set_includeSubdirectories(JSContext ctx, JSValue this_obj, JSValue val)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                if (self._fsw == null)\r\n                {\r\n                    throw new InvalidOperationException();\r\n                }\r\n                if (!val.IsBoolean())\r\n                {\r\n                    throw new InvalidDataException();\r\n                }\r\n\r\n                self._fsw.IncludeSubdirectories = JSApi.JS_ToBool(ctx, val) == 1;\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue js_get_enableRaisingEvents(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                if (self._fsw == null)\r\n                {\r\n                    throw new InvalidOperationException();\r\n                }\r\n\r\n                return JSApi.JS_NewBool(ctx, self._fsw.EnableRaisingEvents);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSSetterCFunction))]\r\n        private static JSValue js_set_enableRaisingEvents(JSContext ctx, JSValue this_obj, JSValue val)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                if (self._fsw == null)\r\n                {\r\n                    throw new InvalidOperationException();\r\n                }\r\n                if (!val.IsBoolean())\r\n                {\r\n                    throw new InvalidDataException();\r\n                }\r\n\r\n                self._fsw.EnableRaisingEvents = JSApi.JS_ToBool(ctx, val) == 1;\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunction))]\r\n        private static JSValue js_get_isDelayedUntilActive(JSContext ctx, JSValue this_obj)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                if (self._fsw == null)\r\n                {\r\n                    throw new InvalidOperationException();\r\n                }\r\n\r\n                return JSApi.JS_NewBool(ctx, self._isDelayedUntilActive);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        [MonoPInvokeCallback(typeof(JSSetterCFunction))]\r\n        private static JSValue js_set_isDelayedUntilActive(JSContext ctx, JSValue this_obj, JSValue val)\r\n        {\r\n            try\r\n            {\r\n                FSWatcher self;\r\n                if (!js_get_classvalue(ctx, this_obj, out self))\r\n                {\r\n                    throw new ThisBoundException();\r\n                }\r\n                if (self._fsw == null)\r\n                {\r\n                    throw new InvalidOperationException();\r\n                }\r\n                if (!val.IsBoolean())\r\n                {\r\n                    throw new InvalidDataException();\r\n                }\r\n\r\n                self._isDelayedUntilActive = JSApi.JS_ToBool(ctx, val) == 1;\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                return ctx.ThrowException(exception);\r\n            }\r\n        }\r\n\r\n        #endregion\r\n\r\n        public static void Bind(TypeRegister register, string name)\r\n        {\r\n            var cls = register.CreateGlobalClass(name, typeof(FSWatcher), js_constructor);\r\n            cls.AddProperty(false, \"path\", js_get_path, js_set_path);\r\n            cls.AddProperty(false, \"filter\", js_get_filter, js_set_filter);\r\n            cls.AddProperty(false, \"isValid\", js_get_isValid, null);\r\n            cls.AddProperty(false, \"enableRaisingEvents\", js_get_enableRaisingEvents, js_set_enableRaisingEvents);\r\n            cls.AddProperty(false, \"includeSubdirectories\", js_get_includeSubdirectories, js_set_includeSubdirectories);\r\n            cls.AddProperty(false, \"isDelayedUntilActive\", js_get_isDelayedUntilActive, js_set_isDelayedUntilActive);\r\n            cls.AddProperty(false, \"oncreate\", js_get_oncreate, js_set_oncreate);\r\n            cls.AddProperty(false, \"ondelete\", js_get_ondelete, js_set_ondelete);\r\n            cls.AddProperty(false, \"onchange\", js_get_onchange, js_set_onchange);\r\n            cls.AddMethod(false, \"dispose\", js_dispose, 0);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/FSWatcher.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: a7f485b0eddea9f43bb6bea1f7dfcf48\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/IAsyncManager.cs",
    "content": "﻿using System;\r\nusing System.IO;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\nusing System.Threading.Tasks;\r\nusing System.Net;\r\nusing QuickJS.Native;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    public interface IAsyncManager\r\n    {\r\n        void Initialize(int mainThreadId);\r\n\r\n        JSValue Yield(ScriptContext context, object awaitObject);\r\n\r\n        void Destroy();\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/IAsyncManager.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 4776caf1b0685fd49a3320707409afc9\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/IFileSystem.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    public interface IFileSystem\r\n    {\r\n        /// <summary>\r\n        /// to check if the file is existed (do not throw exception)\r\n        /// </summary>\r\n        bool Exists(string path);\r\n\r\n        /// <summary>\r\n        /// the fullpath of the given path (do not throw exception)\r\n        /// </summary>\r\n        string GetFullPath(string path);\r\n\r\n        /// <summary>\r\n        /// the content of file, return null if any error occurs (do not throw exception)\r\n        /// </summary>\r\n        byte[] ReadAllBytes(string path);\r\n    }\r\n\r\n    public class CompoundedFileSystem : IFileSystem\r\n    {\r\n        private List<IFileSystem> _fileSystems = new List<IFileSystem>();\r\n\r\n        public bool Exists(string path)\r\n        {\r\n            for (int i = 0, count = _fileSystems.Count; i < count; ++i)\r\n            {\r\n                var fs = _fileSystems[i];\r\n                if (fs.Exists(path))\r\n                {\r\n                    return true;\r\n                }\r\n            }\r\n            return false;\r\n        }\r\n\r\n        public string GetFullPath(string path)\r\n        {\r\n            for (int i = 0, count = _fileSystems.Count; i < count; ++i)\r\n            {\r\n                var fs = _fileSystems[i];\r\n                var fp = fs.GetFullPath(path);\r\n                if (!string.IsNullOrEmpty(fp))\r\n                {\r\n                    return fp;\r\n                }\r\n            }\r\n            return null;\r\n        }\r\n\r\n        public byte[] ReadAllBytes(string path)\r\n        {\r\n            for (int i = 0, count = _fileSystems.Count; i < count; ++i)\r\n            {\r\n                var fs = _fileSystems[i];\r\n                var fp = fs.ReadAllBytes(path);\r\n                if (fp != null)\r\n                {\r\n                    return fp;\r\n                }\r\n            }\r\n            return null;\r\n        }\r\n    }\r\n\r\n    public class DefaultFileSystem : IFileSystem\r\n    {\r\n        public DefaultFileSystem()\r\n        {\r\n        }\r\n\r\n        public bool Exists(string path)\r\n        {\r\n            return System.IO.File.Exists(path);\r\n        }\r\n\r\n        public string GetFullPath(string path)\r\n        {\r\n            try\r\n            {\r\n                return System.IO.Path.GetFullPath(path);\r\n            }\r\n            catch (Exception)\r\n            {\r\n                return null;\r\n            }\r\n        }\r\n\r\n        public byte[] ReadAllBytes(string path)\r\n        {\r\n            try\r\n            {\r\n                return System.IO.File.ReadAllBytes(path);\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                Diagnostics.Logger.IO.Exception(path, exception);\r\n                return null;\r\n            }\r\n        }\r\n    }\r\n\r\n#if !JSB_UNITYLESS\r\n    public class ResourcesFileSystem : IFileSystem\r\n    {\r\n        public ResourcesFileSystem()\r\n        {\r\n        }\r\n\r\n        public bool Exists(string path)\r\n        {\r\n            var asset = UnityEngine.Resources.Load<UnityEngine.TextAsset>(path);\r\n            return asset != null;\r\n        }\r\n\r\n        public string GetFullPath(string path)\r\n        {\r\n            return path;\r\n        }\r\n\r\n        public byte[] ReadAllBytes(string path)\r\n        {\r\n            try\r\n            {\r\n                var asset = UnityEngine.Resources.Load<UnityEngine.TextAsset>(path);\r\n                return asset.bytes;\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                Diagnostics.Logger.IO.Exception(path, exception);\r\n                return null;\r\n            }\r\n        }\r\n    }\r\n#endif\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/IFileSystem.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: b423c292f3f6e4542b34f251afb65db3\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/IJsonConverter.cs",
    "content": "using System;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    public interface IJsonConverter\r\n    {\r\n        string Serialize(object obj, bool prettyPrint);\r\n        object Deserialize(string json, Type type);\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/IJsonConverter.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 172815072d7e7f242abcf36a1f34023b\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/IPathResolver.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    public interface IPathResolver\r\n    {\r\n        void AddSearchPath(string path);\r\n        bool ResolvePath(IFileSystem fileSystem, string fileName, out string searchPath, out string resolvedPath);\r\n    }\r\n\r\n    public class PathResolver : IPathResolver\r\n    {\r\n        private List<string> _searchPaths = new List<string>();\r\n\r\n        public PathResolver()\r\n        {\r\n        }\r\n\r\n        public void AddSearchPath(string path)\r\n        {\r\n            if (!_searchPaths.Contains(path))\r\n            {\r\n                _searchPaths.Add(path);\r\n            }\r\n        }\r\n\r\n        public bool ResolvePath(IFileSystem fileSystem, string fileName, out string searchPath, out string resolvedPath)\r\n        {\r\n            if (fileSystem.Exists(fileName))\r\n            {\r\n                resolvedPath = fileName;\r\n                searchPath = \"\";\r\n                return true;\r\n            }\r\n\r\n            if (!fileName.StartsWith(\"/\"))\r\n            {\r\n                for (int i = 0, count = _searchPaths.Count; i < count; i++)\r\n                {\r\n                    var path = _searchPaths[i];\r\n                    var vpath = PathUtils.Combine(path, fileName);\r\n                    if (fileSystem.Exists(vpath))\r\n                    {\r\n                        searchPath = path;\r\n                        resolvedPath = vpath;\r\n                        return true;\r\n                    }\r\n                }\r\n            }\r\n\r\n            searchPath = null;\r\n            resolvedPath = null;\r\n            return false;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/IPathResolver.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 36ee0371f4afa82479d9510c64243f06\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/IReferenceObject.cs",
    "content": "using System.Collections.Generic;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    public interface IReferenceObject\r\n    {\r\n        void Release();\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/IReferenceObject.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: f1fbe03f43528a04fb8c2f05bfcef925\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/ITimerManager.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing QuickJS.Binding;\nusing QuickJS.Native;\n\nnamespace QuickJS.Utils\n{\n    public interface ITimerManager : IEnumerable<TimerInfo>\n    {\n        #region Timer Management\n        uint SetTimeout(ScriptFunction fn, int ms);\n        uint SetInterval(ScriptFunction fn, int ms);\n        bool ClearTimer(uint id);\n        #endregion\n\n        void Bind(TypeRegister typeRegister);\n\n        int now { get; }\n\n        void Update(int milliseconds);\n        void Destroy();\n    }\n}\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/ITimerManager.cs.meta",
    "content": "fileFormatVersion: 2\nguid: c3f1e988ecb3449fbbe982eecf876baf\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/Invokable.cs",
    "content": "using System;\n\nnamespace QuickJS.Utils\n{\n    public interface IInvokable : IDisposable\n    {\n        void Invoke();\n    }\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/Invokable.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 49865a00fe2edbc4eaadd76d1706434c\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/JSAction.cs",
    "content": "﻿using QuickJS.Native;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    public delegate void JSActionCallback(ScriptRuntime runtime, object cbArgs, JSValue cbValue);\r\n\r\n    public struct JSAction\r\n    {\r\n        public JSActionCallback callback;\r\n        public JSValue value;\r\n        public object args; \r\n        public bool isDelayedUntilActive;\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/JSAction.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: cf0653804b1344f3a155f6b567b91e8b\r\ntimeCreated: 1591427254"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/JSStringCache.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    using Native;\r\n\r\n    public class JSStringCache\r\n    {\r\n        const uint kInitialStringCacheSize = 64;\r\n\r\n        private struct Slot\r\n        {\r\n            public int next;\r\n            public JSValue jsValue;\r\n            public string stringValue;\r\n        }\r\n\r\n        private bool _disposed;\r\n\r\n        // js string => slot id\r\n        private Dictionary<JSValue, int> _jsvMap = new Dictionary<JSValue, int>();\r\n        // c# string => slot id\r\n        private Dictionary<string, int> _strMap = new Dictionary<string, int>();\r\n\r\n        private int _freeIndex = -1;\r\n        private int _allocated = 0;\r\n        private Slot[] _slots = new Slot[kInitialStringCacheSize];\r\n\r\n        private JSContext _ctx;\r\n\r\n        public JSStringCache(JSContext ctx)\r\n        {\r\n            _ctx = ctx;\r\n        }\r\n\r\n        public void Destroy()\r\n        {\r\n            if (_disposed)\r\n            {\r\n                return;\r\n            }\r\n            _disposed = true;\r\n            Clear();\r\n        }\r\n\r\n        public int GetStringCount()\r\n        {\r\n            return _strMap.Count;\r\n        }\r\n\r\n        public void Clear()\r\n        {\r\n            if (_jsvMap.Count > 0)\r\n            {\r\n                _jsvMap.Clear();\r\n                foreach (var kv in _strMap)\r\n                {\r\n                    var slotIndex = kv.Value;\r\n                    ref var slot = ref _slots[slotIndex];\r\n                    JSApi.JS_FreeValue(_ctx, slot.jsValue);\r\n                    slot.jsValue = JSApi.JS_UNDEFINED;\r\n                    slot.stringValue = null;\r\n                }\r\n                _strMap.Clear();\r\n                _freeIndex = -1;\r\n                _allocated = 0;\r\n            }\r\n        }\r\n\r\n        public void RemoveValue(string o)\r\n        {\r\n            if (_disposed || o == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            int slotIndex;\r\n            if (_strMap.TryGetValue(o, out slotIndex))\r\n            {\r\n                ref var slot = ref _slots[slotIndex];\r\n                _strMap.Remove(o);\r\n                _jsvMap.Remove(slot.jsValue);\r\n                JSApi.JS_FreeValue(_ctx, slot.jsValue);\r\n                slot.jsValue = JSApi.JS_UNDEFINED;\r\n                slot.stringValue = null;\r\n                slot.next = _freeIndex;\r\n                _freeIndex = slotIndex;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// the returned jsValue is not reference added, DupValue call is required if jsValue used/stored out of the cache\r\n        /// </summary>\r\n        public bool AddValue(string stringValue, out JSValue jsValue)\r\n        {\r\n            if (_disposed || stringValue == null)\r\n            {\r\n                jsValue = JSApi.JS_UNDEFINED;\r\n                return false;\r\n            }\r\n\r\n            jsValue = _ctx.NewString(stringValue);\r\n            if (jsValue.IsString())\r\n            {\r\n                return _AddPair(jsValue, stringValue) >= 0;\r\n            }\r\n            JSApi.JS_FreeValue(_ctx, jsValue);\r\n            jsValue = JSApi.JS_UNDEFINED;\r\n            return false;\r\n        }\r\n\r\n        public bool AddValue(JSValue jsValue, out string stringValue)\r\n        {\r\n            if (_disposed || !jsValue.IsString())\r\n            {\r\n                stringValue = null;\r\n                return false;\r\n            }\r\n\r\n            stringValue = JSApi.GetNonNullString(_ctx, jsValue);\r\n            if (stringValue != null)\r\n            {\r\n                return _AddPair(JSApi.JS_DupValue(_ctx, jsValue), stringValue) >= 0;\r\n            }\r\n            return false;\r\n        }\r\n\r\n        private int _AddPair(JSValue jsValue, string stringValue)\r\n        {\r\n            int findSlotIndex;\r\n            if (_strMap.TryGetValue(stringValue, out findSlotIndex))\r\n            {\r\n#if JSB_DEBUG\r\n                ref var slot = ref _slots[findSlotIndex];\r\n                Diagnostics.Assert.Debug(slot.jsValue == jsValue, \"corrupted string cache: {0} != {1} => {2}\", slot.jsValue, jsValue, slot.stringValue);\r\n#endif\r\n                return findSlotIndex;\r\n            }\r\n\r\n            if (_freeIndex < 0)\r\n            {\r\n                var oldSize = _slots.Length;\r\n                var id = _allocated++;\r\n                if (id >= oldSize)\r\n                {\r\n                    Array.Resize(ref _slots, oldSize < 8192 ? oldSize * 2 : oldSize + 1024);\r\n                }\r\n                ref var slot = ref _slots[id];\r\n                slot.next = -1;\r\n                slot.stringValue = stringValue;\r\n                slot.jsValue = jsValue;\r\n                _strMap[stringValue] = id;\r\n                _jsvMap[jsValue] = id;\r\n                return id;\r\n            }\r\n            else\r\n            {\r\n                var id = _freeIndex;\r\n                ref var slot = ref _slots[id];\r\n                _freeIndex = slot.next;\r\n                slot.next = -1;\r\n                slot.stringValue = stringValue;\r\n                slot.jsValue = jsValue;\r\n                _strMap[stringValue] = id;\r\n                _jsvMap[jsValue] = id;\r\n                return id;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// get corresponding jsValue of stringValue (only if cached before with AddValue/GetValue)\r\n        /// </summary>\r\n        public bool TryGetValue(string stringValue, out JSValue jsValue)\r\n        {\r\n            if (!_disposed && stringValue != null)\r\n            {\r\n                int slotIndex;\r\n                if (_strMap.TryGetValue(stringValue, out slotIndex))\r\n                {\r\n                    ref readonly var slot = ref _slots[slotIndex];\r\n                    jsValue = slot.jsValue;\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            jsValue = JSApi.JS_UNDEFINED;\r\n            return false;\r\n        }\r\n\r\n        /// <summary>\r\n        /// get corresponding jsValue of stringValue (cache it if not exist)\r\n        /// </summary>\r\n        public bool GetValue(string stringValue, out JSValue jsValue)\r\n        {\r\n            if (!_disposed && stringValue != null)\r\n            {\r\n                int slotIndex;\r\n                if (_strMap.TryGetValue(stringValue, out slotIndex))\r\n                {\r\n                    ref readonly var slot = ref _slots[slotIndex];\r\n                    jsValue = slot.jsValue;\r\n                    return true;\r\n                }\r\n\r\n                return AddValue(stringValue, out jsValue);\r\n            }\r\n\r\n            jsValue = JSApi.JS_UNDEFINED;\r\n            return false;\r\n        }\r\n\r\n        public bool TryGetValue(JSValue jsValue, out string stringValue)\r\n        {\r\n            if (!_disposed && jsValue.IsString())\r\n            {\r\n                int slotIndex;\r\n                if (_jsvMap.TryGetValue(jsValue, out slotIndex))\r\n                {\r\n                    ref readonly var slot = ref _slots[slotIndex];\r\n                    stringValue = slot.stringValue;\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            stringValue = null;\r\n            return false;\r\n        }\r\n\r\n        public bool GetValue(JSValue jsValue, out string stringValue)\r\n        {\r\n            if (!_disposed && jsValue.IsString())\r\n            {\r\n                int slotIndex;\r\n                if (_jsvMap.TryGetValue(jsValue, out slotIndex))\r\n                {\r\n                    ref readonly var slot = ref _slots[slotIndex];\r\n                    stringValue = slot.stringValue;\r\n                    return true;\r\n                }\r\n\r\n                return AddValue(jsValue, out stringValue);\r\n            }\r\n\r\n            stringValue = null;\r\n            return false;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/JSStringCache.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 6ec553df9bbd3af4a88e62e0cd12728a\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/JSWeakMap.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    using Native;\r\n\r\n    public interface IWeakMapEntry\r\n    {\r\n        void Dispose();\r\n    }\r\n\r\n    public class JSWeakMap<T>\r\n    where T : class, IWeakMapEntry\r\n    {\r\n        // weak reference table for script values (dangerous, no ref count)\r\n        private Dictionary<JSValue, WeakReference> _map = new Dictionary<JSValue, WeakReference>();\r\n\r\n        /// <summary>\r\n        /// [FOR_DEBUG_ONLY] \r\n        /// </summary>\r\n        public int Count\r\n        {\r\n            get\r\n            {\r\n#if JSB_DEBUG\r\n                var active = 0;\r\n                foreach (var kv in _map)\r\n                {\r\n                    if (kv.Value.IsAlive)\r\n                    {\r\n                        ++active;\r\n                    }\r\n                }\r\n#if !JSB_UNITYLESS\r\n                Diagnostics.Assert.Debug(active == _map.Count, string.Format(\"unbalanced WeakMap<{0}> {1} != {2}\", typeof(T).Name, active, _map.Count));\r\n#endif\r\n#endif\r\n                return _map.Count;\r\n            }\r\n        }\r\n\r\n        public void Clear()\r\n        {\r\n            var valueMapSize = _map.Count;\r\n            var values = new WeakReference[valueMapSize];\r\n            _map.Values.CopyTo(values, 0);\r\n            _map.Clear();\r\n#if JSB_DEBUG \r\n            Diagnostics.Logger.Default.Debug(\"WeakMap<{0}>.Clear: {1}\", typeof(T).Name, valueMapSize);\r\n#endif\r\n            for (var i = 0; i < valueMapSize; i++)\r\n            {\r\n                var d = values[i].Target as T;\r\n                if (d != null)\r\n                {\r\n#if JSB_DEBUG \r\n                    Diagnostics.Logger.Default.Debug(\"    {0}: {1}\", i, d);\r\n#endif\r\n                    d.Dispose();\r\n                }\r\n#if JSB_DEBUG \r\n                else\r\n                {\r\n                    Diagnostics.Logger.Default.Debug(\"    {0}: {1}\", i, \"null\");\r\n                }\r\n#endif\r\n            }\r\n        }\r\n\r\n        public void Add(JSValue jso, T o)\r\n        {\r\n            T old;\r\n            if (TryGetValue(jso, out old))\r\n            {\r\n                old.Dispose();\r\n            }\r\n            _map[jso] = new WeakReference(o);\r\n        }\r\n\r\n        public bool TryGetValue(JSValue jso, out T o)\r\n        {\r\n            WeakReference weakRef;\r\n            if (_map.TryGetValue(jso, out weakRef))\r\n            {\r\n                o = weakRef.Target as T;\r\n                return o != null;\r\n            }\r\n            o = default(T);\r\n            return false;\r\n        }\r\n\r\n        public bool Remove(JSValue jso)\r\n        {\r\n            WeakReference weakRef;\r\n            var r = false;\r\n            if (_map.TryGetValue(jso, out weakRef))\r\n            {\r\n                r = true;\r\n                _map.Remove(jso);\r\n#if JSB_DEBUG\r\n                Diagnostics.Logger.Default.Debug(\"WeakMap<{0}>.Remove: {1} = {2}\", typeof(T).Name, jso, weakRef.Target);\r\n#endif\r\n            }\r\n            return r;\r\n        }\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/JSWeakMap.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: c0e5dc10f33c23d4ea08b3ce60cff228\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/ObjectCache.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    using Native;\r\n\r\n    public class ObjectCache\r\n    {\r\n        private struct ObjectSlot\r\n        {\r\n            public int next;\r\n            public object target;\r\n            public bool disposable;\r\n        }\r\n\r\n        private bool _disposed;\r\n\r\n        private int _freeIndex = -1;\r\n        private int _activeMapSlotCount = 0;\r\n\r\n        // it holds any two way binding object (with JS finalizer calling)\r\n        // id => host object\r\n        private ObjectSlot[] _objectSlots;\r\n        private int _slotAllocated = 0;\r\n\r\n        // host object => jsvalue heapptr (dangerous, no ref count)\r\n        private Dictionary<object, JSValue> _rmap = new Dictionary<object, JSValue>(EqualityComparer.Default);\r\n\r\n        private JSWeakMap<ScriptValue> _scriptValueMap = new JSWeakMap<ScriptValue>();\r\n\r\n        // 刻意与 ScriptValue 隔离\r\n        private JSWeakMap<ScriptDelegate> _delegateMap = new JSWeakMap<ScriptDelegate>();\r\n\r\n        // private JSWeakMap<ScriptPromise> _promiseMap = new JSWeakMap<ScriptPromise>();\r\n\r\n        public ObjectCache(uint initialSize)\r\n        {\r\n            _objectSlots = new ObjectSlot[initialSize > 256 ? initialSize : 256];\r\n        }\r\n\r\n        public void ForEachManagedObject(Action<object> callback)\r\n        {\r\n            for (int i = 0, count = _slotAllocated; i < count; ++i)\r\n            {\r\n                ref readonly var item = ref _objectSlots[i];\r\n                if (item.next == -1)\r\n                {\r\n                    callback(item.target);\r\n                }\r\n            }\r\n        }\r\n\r\n        public int GetManagedObjectCount()\r\n        {\r\n            return _activeMapSlotCount;\r\n        }\r\n\r\n        public int GetManagedObjectCap()\r\n        {\r\n            return _slotAllocated;\r\n        }\r\n\r\n        public int GetJSObjectCount()\r\n        {\r\n            return _rmap.Count;\r\n        }\r\n\r\n        public int GetDelegateCount()\r\n        {\r\n            return _delegateMap.Count;\r\n        }\r\n\r\n        public int GetScriptValueCount()\r\n        {\r\n            return _scriptValueMap.Count;\r\n        }\r\n\r\n        // public int GetScriptPromiseCount()\r\n        // {\r\n        //     return _promiseMap.Count;\r\n        // }\r\n\r\n        public void Destroy()\r\n        {\r\n            if (_disposed)\r\n            {\r\n                return;\r\n            }\r\n#if JSB_DEBUG\r\n            Diagnostics.Logger.Default.Debug(\"_activeMapSlotCount {0}\", _activeMapSlotCount);\r\n            foreach (var entry in _objectSlots)\r\n            {\r\n                Diagnostics.Assert.Debug(entry.target == null, \"Entry {0}\", entry.target);\r\n            }\r\n            foreach (var entry in _rmap)\r\n            {\r\n                Diagnostics.Logger.Default.Debug(\"REntry {0} = {1}\", entry.Key, entry.Value);\r\n            }\r\n#endif\r\n            _disposed = true;\r\n            _freeIndex = -1;\r\n            _activeMapSlotCount = 0;\r\n            _slotAllocated = 0;\r\n            _rmap.Clear();\r\n            _delegateMap.Clear();\r\n            _scriptValueMap.Clear();\r\n            // _promiseMap.Clear();\r\n        }\r\n\r\n        /// <summary>\r\n        /// 建立 object to jsvalue 的映射. \r\n        /// 外部必须自己保证 object 存在的情况下对应的 js value 不会被释放.\r\n        /// </summary>\r\n        public void AddJSValue(object o, JSValue heapptr)\r\n        {\r\n            if (_disposed)\r\n            {\r\n                return;\r\n            }\r\n            if (o != null)\r\n            {\r\n#if JSB_DEBUG\r\n                JSValue oldPtr;\r\n                if (TryGetJSValue(o, out oldPtr))\r\n                {\r\n                    Diagnostics.Logger.Default.Fatal(\"exists object => js value mapping {0}: {1} => {2}\", o, oldPtr, heapptr);\r\n                }\r\n#endif\r\n                _rmap[o] = heapptr;\r\n            }\r\n        }\r\n\r\n        // object `o` must be valid as key\r\n        public bool TryGetJSValue(object o, out JSValue heapptr)\r\n        {\r\n            return _rmap.TryGetValue(o, out heapptr);\r\n        }\r\n\r\n        /// <summary>\r\n        /// register a strong reference of object in ObjectCache\r\n        /// </summary>\r\n        public int AddObject(object o, bool disposable)\r\n        {\r\n            if (_disposed)\r\n            {\r\n                Diagnostics.Logger.Default.Debug(\"calling AddObject after being disposed: {0}\", o);\r\n                return -1;\r\n            }\r\n            Diagnostics.Assert.Debug(o != null);\r\n            ++_activeMapSlotCount;\r\n            if (_freeIndex < 0)\r\n            {\r\n                var oldSize = _objectSlots.Length;\r\n                var id = _slotAllocated++;\r\n                if (id >= oldSize)\r\n                {\r\n                    Array.Resize(ref _objectSlots, oldSize <= 8192 ? oldSize * 2 : oldSize + 1024);\r\n                }\r\n                ref var freeEntryRef = ref _objectSlots[id];\r\n                freeEntryRef.next = -1;\r\n                freeEntryRef.target = o;\r\n                freeEntryRef.disposable = disposable;\r\n                return id;\r\n            }\r\n            else\r\n            {\r\n                var id = _freeIndex;\r\n                ref var freeEntryRef = ref _objectSlots[id];\r\n                _freeIndex = freeEntryRef.next;\r\n                freeEntryRef.next = -1;\r\n                freeEntryRef.target = o;\r\n                freeEntryRef.disposable = disposable;\r\n                return id;\r\n            }\r\n        }\r\n\r\n        public bool SetObjectDisposable(int id, bool disposable)\r\n        {\r\n            if (id >= 0 && id < _slotAllocated)\r\n            {\r\n                ref var entryRef = ref _objectSlots[id];\r\n                if (entryRef.next == -1)\r\n                {\r\n                    entryRef.disposable = disposable;\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public bool TryGetObject(int id, out object o)\r\n        {\r\n            if (id >= 0 && id < _slotAllocated)\r\n            {\r\n                ref readonly var entryRef = ref _objectSlots[id];\r\n                if (entryRef.next == -1)\r\n                {\r\n                    o = entryRef.target;\r\n                    return true;\r\n                }\r\n            }\r\n            o = null;\r\n            return false;\r\n        }\r\n\r\n        public bool RemoveObject(in JSPayloadHeader payload)\r\n        {\r\n            return payload.type_id == BridgeObjectType.ObjectRef ? RemoveObject(payload.value) : false;\r\n        }\r\n\r\n        public bool RemoveObject(int id)\r\n        {\r\n            object o;\r\n            return RemoveObject(id, out o);\r\n        }\r\n\r\n        public bool RemoveObject(int id, out object o)\r\n        {\r\n            if (TryGetObject(id, out o))\r\n            {\r\n                ref var entryRef = ref _objectSlots[id];\r\n                var disposable = entryRef.disposable;\r\n                entryRef.next = _freeIndex;\r\n                entryRef.target = null;\r\n                _freeIndex = id;\r\n                --_activeMapSlotCount;\r\n                _rmap.Remove(o);\r\n                if (disposable)\r\n                {\r\n                    var jsf = o as IDisposable;\r\n                    if (jsf != null)\r\n                    {\r\n                        jsf.Dispose();\r\n                    }\r\n                }\r\n                return true;\r\n            }\r\n            return false;\r\n        }\r\n\r\n        // 覆盖已有记录, 无记录返回 false\r\n        public bool ReplaceObject(int id, object o)\r\n        {\r\n            object oldValue;\r\n            if (TryGetObject(id, out oldValue))\r\n            {\r\n                ref var entryRef = ref _objectSlots[id];\r\n                entryRef.target = o;\r\n                JSValue heapptr;\r\n                if (oldValue != null && _rmap.TryGetValue(oldValue, out heapptr))\r\n                {\r\n                    _rmap.Remove(oldValue);\r\n                    _rmap[o] = heapptr;\r\n                }\r\n                return true;\r\n            }\r\n            return false;\r\n        }\r\n\r\n        public bool TryGetTypedWeakObject<T>(int id, out T o)\r\n        where T : class\r\n        {\r\n            object obj;\r\n            if (TryGetObject(id, out obj))\r\n            {\r\n                var w = obj as WeakReference;\r\n                o = w != null ? w.Target as T : null;\r\n                return true;\r\n            }\r\n            o = null;\r\n            return false;\r\n        }\r\n\r\n        public bool TryGetTypedObject<T>(int id, out T o)\r\n        where T : class\r\n        {\r\n            object obj;\r\n            if (TryGetObject(id, out obj))\r\n            {\r\n                o = obj as T;\r\n                return true;\r\n            }\r\n            o = null;\r\n            return false;\r\n        }\r\n\r\n        public bool MatchObjectType(int id, Type type)\r\n        {\r\n            object o;\r\n            if (TryGetObject(id, out o))\r\n            {\r\n                if (o != null)\r\n                {\r\n                    var otype = o.GetType();\r\n                    return otype == type || otype.IsSubclassOf(type) || type.IsAssignableFrom(otype);\r\n                }\r\n                return true;\r\n            }\r\n            return false;\r\n        }\r\n\r\n        #region delegate mapping \r\n\r\n        /// <summary>\r\n        /// register a weak reference of ScriptDelegate in ObjectCache\r\n        /// </summary>\r\n        public bool AddDelegate(JSValue jso, ScriptDelegate o)\r\n        {\r\n            if (_disposed)\r\n            {\r\n                Diagnostics.Logger.Default.Debug(\"calling AddDelegate after disposed: {0}\", o);\r\n                return false;\r\n            }\r\n            _delegateMap.Add(jso, o);\r\n            return true;\r\n        }\r\n\r\n        public bool TryGetDelegate(JSValue jso, out ScriptDelegate o)\r\n        {\r\n            return _delegateMap.TryGetValue(jso, out o);\r\n        }\r\n\r\n        public bool RemoveDelegate(JSValue jso)\r\n        {\r\n            if (_disposed)\r\n            {\r\n                Diagnostics.Logger.Default.Debug(\"calling RemoveDelegate after disposed: {0}\", jso);\r\n                return false;\r\n            }\r\n            return _delegateMap.Remove(jso);\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region script value mapping \r\n\r\n        /// <summary>\r\n        /// register a weak reference of ScriptValue in ObjectCache\r\n        /// </summary>\r\n        public void AddScriptValue(JSValue jso, ScriptValue o)\r\n        {\r\n            if (_disposed)\r\n            {\r\n                return;\r\n            }\r\n            _scriptValueMap.Add(jso, o);\r\n        }\r\n\r\n        public bool TryGetScriptValue(JSValue jso, out ScriptValue o)\r\n        {\r\n            ScriptValue value;\r\n            if (_scriptValueMap.TryGetValue(jso, out value))\r\n            {\r\n                o = value;\r\n                return true;\r\n            }\r\n            o = null;\r\n            return false;\r\n        }\r\n\r\n        public bool RemoveScriptValue(JSValue jso)\r\n        {\r\n            if (_disposed)\r\n            {\r\n                return false;\r\n            }\r\n            return _scriptValueMap.Remove(jso);\r\n        }\r\n\r\n        #endregion\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/ObjectCache.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 1f420fcce48ede24abd185ce3e619647\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/ObjectCollection.cs",
    "content": "using System;\nusing System.Collections.Generic;\n\nnamespace QuickJS.Utils\n{\n    public interface IObjectCollectionEntry\n    {\n        void OnCollectionReleased();\n    }\n\n    /// <summary>\n    /// A collection of entries who need to be notified at the stage of releasing script runtime.\n    /// </summary>\n    public class ObjectCollection\n    {\n        public struct Handle\n        {\n            public int id;\n            public int tag;\n        }\n\n        private struct ObjectEntry\n        {\n            public int next;\n            public int tag;\n            public WeakReference<IObjectCollectionEntry> target;\n        }\n\n        private bool _isClearing = false;\n        private int _freeIndex = -1;\n        private int _activeCount = 0;\n        private int _allocatedCount = 0;\n        private ObjectEntry[] _entries;\n\n        public int count => _activeCount;\n\n        public ObjectCollection(uint initialSize)\n        {\n            _entries = new ObjectEntry[initialSize > 32 ? initialSize : 32];\n        }\n\n        public void Clear()\n        {\n            if (_activeCount <= 0)\n            {\n                return;\n            }\n\n            try\n            {\n                _isClearing = true;\n                var count = _allocatedCount;\n                for (int i = 0; i < count; ++i)\n                {\n                    ref var entry = ref _entries[i];\n                    IObjectCollectionEntry target;\n                    WeakReference<IObjectCollectionEntry> reference = entry.target;\n                    if (reference.TryGetTarget(out target))\n                    {\n                        // entry should be purged OnCollectionReleased with RemoveObject\n                        target.OnCollectionReleased();\n                        Diagnostics.Logger.Default.Debug(\"releasing collection entry: {0}\", target);\n                        Diagnostics.Assert.Debug(!reference.TryGetTarget(out var _1) || _1 == null);\n                        Diagnostics.Assert.Debug(_allocatedCount == count);\n                    }\n                    else if (entry.next == -1)\n                    {\n                        Diagnostics.Logger.Default.Warning(\"null collection entry\");\n                    }\n                } // end for count\n                Diagnostics.Assert.Debug(_activeCount == 0, \"invalid object collection state during the phase of destroying runtime: {0}\", _activeCount);\n            }\n            finally\n            {\n                _isClearing = false;\n            }\n        }\n\n        public void AddObject(IObjectCollectionEntry o, out Handle handle)\n        {\n            if (o != null)\n            {\n                Diagnostics.Assert.Debug(!_isClearing);\n                ++_activeCount;\n                if (_freeIndex < 0)\n                {\n                    var id = _allocatedCount++;\n                    var oldSize = _entries.Length;\n                    if (id >= oldSize)\n                    {\n                        Array.Resize(ref _entries, oldSize <= 1024 ? oldSize * 2 : oldSize + 128);\n                    }\n                    ref var freeEntry = ref _entries[id];\n                    ++freeEntry.tag;\n                    freeEntry.next = -1;\n                    if (freeEntry.target == null)\n                    {\n                        freeEntry.target = new WeakReference<IObjectCollectionEntry>(o);\n                    }\n                    else\n                    {\n                        freeEntry.target.SetTarget(o);\n                    }\n                    handle = new Handle() { id = id, tag = freeEntry.tag };\n                }\n                else\n                {\n                    var id = _freeIndex;\n                    ref var freeEntry = ref _entries[id];\n                    _freeIndex = freeEntry.next;\n                    ++freeEntry.tag;\n                    freeEntry.next = -1;\n                    freeEntry.target.SetTarget(o);\n                    handle = new Handle() { id = id, tag = freeEntry.tag };\n                }\n            }\n            else\n            {\n                handle = new Handle();\n            }\n        }\n\n        public bool IsHandleValid(in Handle handle)\n        {\n            var id = handle.id;\n            if (id >= 0 && id < _allocatedCount)\n            {\n                ref readonly var entry = ref _entries[id];\n                if (entry.next == -1 && entry.tag == handle.tag)\n                {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        public bool TryGetObject(in Handle handle, out IObjectCollectionEntry o)\n        {\n            var id = handle.id;\n            if (id >= 0 && id < _allocatedCount)\n            {\n                ref readonly var entry = ref _entries[id];\n                if (entry.next == -1 && entry.tag == handle.tag)\n                {\n                    return entry.target.TryGetTarget(out o);\n                }\n            }\n            o = null;\n            return false;\n        }\n\n        public bool RemoveObject(in Handle handle)\n        {\n            IObjectCollectionEntry o;\n            return RemoveObject(handle, out o);\n        }\n\n        public bool RemoveObject(in Handle handle, out IObjectCollectionEntry o)\n        {\n            if (TryGetObject(handle, out o))\n            {\n                ref var entry = ref _entries[handle.id];\n                entry.next = _freeIndex;\n                entry.target.SetTarget(null);\n                ++entry.tag;\n                _freeIndex = handle.id;\n                --_activeCount;\n                return true;\n            }\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/ObjectCollection.cs.meta",
    "content": "fileFormatVersion: 2\nguid: c5e84006c94604e6a9f44defbeb2e0a8\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/PathUtils.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    public static class PathUtils\r\n    {\r\n        public static string GetDirectoryName(string path)\r\n        {\r\n            return string.IsNullOrEmpty(path) ? path : System.IO.Path.GetDirectoryName(path).Replace('\\\\', '/');\r\n        }\r\n\r\n        public static string Combine(string path1, string path2)\r\n        {\r\n            return System.IO.Path.Combine(path1, path2).Replace('\\\\', '/');\r\n        }\r\n\r\n        public static string Combine(string path1, string path2, string path3)\r\n        {\r\n            return System.IO.Path.Combine(path1, path2, path3).Replace('\\\\', '/');\r\n        }\r\n\r\n        public static string Combine(params string[] paths)\r\n        {\r\n            return System.IO.Path.Combine(paths).Replace('\\\\', '/');\r\n        }\r\n\r\n        /// 展开路径中的 ./..\r\n        public static string ExtractPath(string path, char sp)\r\n        {\r\n            var prefix = string.Empty;\r\n            var pathRoot = System.IO.Path.GetPathRoot(path);\r\n            if (pathRoot != string.Empty)\r\n            {\r\n                prefix = path.Substring(0, pathRoot.Length);\r\n                path = path.Substring(pathRoot.Length);\r\n            }\r\n\r\n            var items = path.Split(sp);\r\n            if (items.Length < 2)\r\n            {\r\n                return prefix + path;\r\n            }\r\n\r\n            var array = new List<string>(items.Length);\r\n            for (var i = 0; i < items.Length; i++)\r\n            {\r\n                var item = items[i];\r\n                switch (item)\r\n                {\r\n                    case \".\": break;\r\n                    case \"..\":\r\n                    {\r\n                        if (array.Count > 0 && array[array.Count - 1] != \"..\")\r\n                        {\r\n                            array.RemoveAt(array.Count - 1);\r\n                        }\r\n                        else\r\n                        {\r\n                            array.Add(item); \r\n                        }\r\n\r\n                        break;\r\n                    }\r\n                    default:\r\n                    {\r\n                        array.Add(item);\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n\r\n            return prefix + Combine(array.ToArray());\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/PathUtils.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 4be6b2807f345334e96667201f5ca24e\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/SList.cs",
    "content": "using System;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\nusing System.Reflection;\r\nusing System.Text;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    using QuickJS.Diagnostics;\r\n\r\n    /// <summary>\r\n    /// Stable Index\r\n    /// </summary>\r\n    public readonly struct SIndex : IEquatable<SIndex>\r\n    {\r\n        public static readonly SIndex None = default;\r\n\r\n        public readonly int index;\r\n        public readonly int revision;\r\n\r\n        public SIndex(int index, int revision)\r\n        {\r\n            this.index = index;\r\n            this.revision = revision;\r\n        }\r\n\r\n        public bool Equals(in SIndex other) => this == other;\r\n\r\n        public bool Equals(SIndex other) => this == other;\r\n\r\n        public override bool Equals(object obj) => obj is SIndex other && this == other;\r\n\r\n        public override int GetHashCode() => index ^ revision;\r\n\r\n        public override string ToString() => index.ToString();\r\n\r\n        public static bool operator ==(SIndex a, SIndex b) => a.index == b.index && a.revision == b.revision;\r\n\r\n        public static bool operator !=(SIndex a, SIndex b) => a.index != b.index || a.revision != b.revision;\r\n    }\r\n\r\n    public interface SListAccess\r\n    {\r\n        void Lock();\r\n        void Unlock();\r\n        bool IsValidIndex(in SIndex index);\r\n        bool UnsafeSetValue(in SIndex index);\r\n        bool RemoveAt(in SIndex index);\r\n        void Clear();\r\n    }\r\n\r\n    /// <summary>\r\n    /// Stable Indexed Array List.\r\n    /// * 可以使用稳定索引快速访问元素, 元素在列表中的稳定索引不会发生变化.\r\n    /// * 可以使用稳定索引快速删除元素.\r\n    /// * 元素移除后索引位置会由下一个被添加的元素复用\r\n    /// * 可以使用 foreach 顺序迭代此列表, 没有额外的查找开销. (即 GetEnumerator)\r\n    /// * 可以使用稳定索引安全地访问, 如果该稳定索引已失效, 则抛出异常.\r\n    /// * 可以使用 Lock 阻止所有修改操作 (Unload 解锁)\r\n    /// * 此列表的使用稳定索引(SIndex)的效率较高, 随机直接索引(int)访问的效率较差.\r\n    /// </summary>\r\n    public class SList<T> : SListAccess, IEnumerable<T>\r\n    {\r\n        private struct Slot\r\n        {\r\n            // 空闲状态下指向下一个空闲栏位, 否则指向下一个有效栏位\r\n            public int next;\r\n            // 空闲状态下无效, 在有效栏位时代表前一个有效栏位\r\n            public int previous;\r\n            // 记录覆盖次数\r\n            public int revision;\r\n            // 单独记录有效性, 增加 revision 溢出时的可靠性\r\n            public bool isValid;\r\n            public T value;\r\n\r\n            public override string ToString()\r\n            {\r\n                return $\"valid: {isValid} rev: {revision} prev: {previous} next: {next} value: {value}\";\r\n            }\r\n        }\r\n\r\n        private int _lock;\r\n        private int _freeIndex;\r\n        private int _usedSize;\r\n        private Slot[] _slots;\r\n\r\n        private int _firstIndex;\r\n        private int _lastIndex;\r\n        private int _version;\r\n\r\n        public int Count => _usedSize;\r\n\r\n        public int Capacity => _slots.Length;\r\n\r\n        public bool isLocked => _lock > 0;\r\n\r\n        public SIndex firstIndex => _firstIndex >= 0 ? new SIndex(_firstIndex, _slots[_firstIndex].revision) : SIndex.None;\r\n        \r\n        public SIndex lastIndex => _lastIndex >= 0 ? new SIndex(_lastIndex, _slots[_lastIndex].revision) : SIndex.None;\r\n        \r\n        public T this[in SIndex index]\r\n        {\r\n            get\r\n            {\r\n                if (index.index >= 0 && index.index < this._slots.Length)\r\n                {\r\n                    ref var slot = ref _slots[index.index];\r\n\r\n                    if (slot.revision == index.revision)\r\n                    {\r\n                        return slot.value;\r\n                    }\r\n                    throw new IndexOutOfRangeException(\"accessing with expired index\");\r\n                }\r\n\r\n                throw new IndexOutOfRangeException();\r\n            }\r\n\r\n            set\r\n            {\r\n                if (!UnsafeSetValue(index, value))\r\n                {\r\n                    throw new IndexOutOfRangeException();\r\n                }\r\n            }\r\n        }\r\n\r\n        public T this[int index]\r\n        {\r\n            get\r\n            {\r\n                if (index >= 0 && index < this._usedSize)\r\n                {\r\n                    var current = _firstIndex;\r\n                    while (current >= 0)\r\n                    {\r\n                        ref var slot = ref this._slots[current];\r\n                        Assert.Debug(slot.isValid);\r\n                        if (index-- == 0)\r\n                        {\r\n                            return slot.value;\r\n                        }\r\n                        current = slot.next;\r\n                    }\r\n                }\r\n\r\n                throw new ArgumentOutOfRangeException(nameof(index));\r\n            }\r\n            set\r\n            {\r\n                if (index >= 0 && index < this._usedSize)\r\n                {\r\n                    var current = _firstIndex;\r\n                    while (current >= 0)\r\n                    {\r\n                        ref var slot = ref this._slots[current];\r\n                        Assert.Debug(slot.isValid);\r\n                        if (index-- == 0)\r\n                        {\r\n                            slot.value = value;\r\n                            return;\r\n                        }\r\n                        current = slot.next;\r\n                    }\r\n                }\r\n\r\n                throw new ArgumentOutOfRangeException(nameof(index));\r\n            }\r\n        }\r\n\r\n        IEnumerator<T> IEnumerable<T>.GetEnumerator() => (IEnumerator<T>)this.GetEnumerator();\r\n\r\n        IEnumerator IEnumerable.GetEnumerator() => (IEnumerator)this.GetEnumerator();\r\n\r\n        public SList<T>.Enumerator GetEnumerator() => new SList<T>.Enumerator(this);\r\n\r\n        public SList<T>.UnsafeEnumerator GetUnsafeEnumerator() => new SList<T>.UnsafeEnumerator(this);\r\n\r\n        public SList<T>.StableIndexEnumerator GetStableIndexEnumerator() => new SList<T>.StableIndexEnumerator(this);\r\n\r\n        public SList()\r\n        : this(8)\r\n        {\r\n        }\r\n\r\n        public SList(int initialCapacity)\r\n        {\r\n            _lock = 0;\r\n            _freeIndex = -1;\r\n            _firstIndex = -1;\r\n            _lastIndex = -1;\r\n            _slots = new Slot[0];\r\n            GrowIfNeeded(initialCapacity);\r\n        }\r\n\r\n        public override string ToString()\r\n        {\r\n            var sb = new StringBuilder();\r\n            var current = this._firstIndex;\r\n\r\n            sb.Append('[');\r\n            while (current >= 0)\r\n            {\r\n                ref var slot = ref this._slots[current];\r\n                sb.Append(slot.value);\r\n                if (current != _lastIndex)\r\n                {\r\n                    sb.Append(\", \");\r\n                }\r\n                current = slot.next;\r\n            }\r\n            sb.Append(']');\r\n            return sb.ToString();\r\n        }\r\n\r\n        public string ToDebugString()\r\n        {\r\n            var sb = new StringBuilder();\r\n\r\n            sb.AppendLine(\"[\");\r\n            sb.AppendLine($\"\\tfirst: {_firstIndex}\");\r\n            sb.AppendLine($\"\\tlast: {_lastIndex}\");\r\n            sb.AppendLine($\"\\tfree: {_freeIndex}\");\r\n            sb.AppendLine($\"\\tused: {_usedSize}\");\r\n            sb.AppendLine($\"\\tlock: {_lock}\");\r\n            for (int i = 0, count = _slots.Length; i < count; i++)\r\n            {\r\n                ref var slot = ref this._slots[i];\r\n                if (i != count)\r\n                {\r\n                    sb.AppendLine($\"\\t{i} = {slot}, \");\r\n                }\r\n                else\r\n                {\r\n                    sb.AppendLine($\"\\t{i} = {slot}\");\r\n                }\r\n            }\r\n            sb.AppendLine(\"]\");\r\n            return sb.ToString();\r\n        }\r\n\r\n        public T[] ToArray()\r\n        {\r\n            var array = new T[_usedSize];\r\n            var fillIndex = 0;\r\n            var current = this._firstIndex;\r\n\r\n            while (current >= 0)\r\n            {\r\n                ref var slot = ref this._slots[current];\r\n                Assert.Debug(slot.isValid);\r\n                array[fillIndex++] = slot.value;\r\n                current = slot.next;\r\n            }\r\n\r\n            Assert.Debug(fillIndex == _usedSize);\r\n            return array;\r\n        }\r\n\r\n        private void GrowIfNeeded(int newCount)\r\n        {\r\n            var newSize = this._usedSize + newCount;\r\n            var oldSize = this._slots.Length;\r\n            if (newSize > oldSize)\r\n            {\r\n                newSize = Math.Max(Math.Max(oldSize * 2, 4), newSize);\r\n\r\n                Array.Resize(ref this._slots, newSize);\r\n                for (var i = oldSize; i < newSize; ++i)\r\n                {\r\n                    ref var slot = ref this._slots[i];\r\n                    slot.next = _freeIndex;\r\n                    this._freeIndex = i;\r\n                }\r\n            }\r\n        }\r\n\r\n        public void Lock()\r\n        {\r\n            ++_lock;\r\n        }\r\n\r\n        public void Unlock()\r\n        {\r\n            --_lock;\r\n            Assert.Debug(_lock >= 0);\r\n        }\r\n\r\n        public bool IsValidIndex(in SIndex index)\r\n        {\r\n            if (index.index >= 0 && index.index < this._slots.Length)\r\n            {\r\n                ref var slot = ref _slots[index.index];\r\n\r\n                if (slot.isValid && slot.revision == index.revision)\r\n                {\r\n                    return true;\r\n                }\r\n            }\r\n            return false;\r\n        }\r\n\r\n        public bool TryGetValue(in SIndex index, out T value)\r\n        {\r\n            if (index.index >= 0 && index.index < this._slots.Length)\r\n            {\r\n                ref var slot = ref _slots[index.index];\r\n\r\n                if (slot.isValid && slot.revision == index.revision)\r\n                {\r\n                    value = slot.value;\r\n                    return true;\r\n                }\r\n            }\r\n            value = default;\r\n            return false;\r\n        }\r\n\r\n        public ref T UnsafeGetValueByRef(SIndex index)\r\n        {\r\n            if (index.index >= 0 && index.index < this._slots.Length)\r\n            {\r\n                ref var slot = ref _slots[index.index];\r\n\r\n                if (slot.revision == index.revision)\r\n                {\r\n                    return ref slot.value;\r\n                }\r\n\r\n                throw new IndexOutOfRangeException(\"accessing with expired index\");\r\n            }\r\n\r\n            throw new KeyNotFoundException(\"accessing with invalid index\");\r\n        }\r\n\r\n        public T UnsafeGetValue(in SIndex index)\r\n        {\r\n            if (index.index >= 0 && index.index < this._slots.Length)\r\n            {\r\n                ref var slot = ref _slots[index.index];\r\n\r\n                if (slot.isValid && slot.revision == index.revision)\r\n                {\r\n                    return slot.value;\r\n                }\r\n            }\r\n            return default;\r\n        }\r\n\r\n        public bool UnsafeSetValue(in SIndex index)\r\n        {\r\n            return UnsafeSetValue(index, default);\r\n        }\r\n\r\n        public bool UnsafeSetValue(in SIndex index, T value)\r\n        {\r\n            if (index.index >= 0 && index.index < this._slots.Length)\r\n            {\r\n                ref var slot = ref _slots[index.index];\r\n\r\n                if (slot.isValid && slot.revision == index.revision)\r\n                {\r\n                    slot.value = value;\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public SIndex UnsafeIndexAt(int index, out T value)\r\n        {\r\n            Assert.Debug(index >= 0 && index < _usedSize);\r\n\r\n            var current = _firstIndex;\r\n            while (current >= 0)\r\n            {\r\n                ref var slot = ref this._slots[current];\r\n                Assert.Debug(slot.isValid);\r\n                if (index-- == 0)\r\n                {\r\n                    value = slot.value;\r\n                    return new(current, slot.revision);\r\n                }\r\n                current = slot.next;\r\n            }\r\n\r\n            value = default;\r\n            return SIndex.None;\r\n        }\r\n\r\n        public SIndex UnsafeAdd(T value)\r\n        {\r\n            GrowIfNeeded(1);\r\n            Assert.Debug(_freeIndex != -1);\r\n\r\n            var index = _freeIndex;\r\n            ref var slot = ref _slots[index];\r\n\r\n            // safer to skip SIndex.None\r\n            slot.revision = slot.revision == -1 ? 1 : slot.revision + 1;\r\n            slot.value = value;\r\n            slot.isValid = true;\r\n            _freeIndex = slot.next;\r\n            slot.next = -1;\r\n            slot.previous = _lastIndex;\r\n            ++_usedSize;\r\n            if (_lastIndex >= 0)\r\n            {\r\n                ref var lastSlot = ref _slots[_lastIndex];\r\n                lastSlot.next = index;\r\n            }\r\n            if (_firstIndex < 0)\r\n            {\r\n                _firstIndex = index;\r\n            }\r\n            _lastIndex = index;\r\n            ++_version;\r\n            return new SIndex(index, slot.revision);\r\n        }\r\n\r\n        public SIndex Add(T value)\r\n        {\r\n            Assert.Debug(_lock == 0);\r\n            return UnsafeAdd(value);\r\n        }\r\n\r\n        public void Insert(in SIndex index, T value)\r\n        {\r\n            Assert.Debug(_lock == 0);\r\n            if (index.index < 0 || index.index >= _slots.Length)\r\n            {\r\n                throw new IndexOutOfRangeException();\r\n            }\r\n\r\n            ref var slot = ref this._slots[index.index];\r\n            if (!slot.isValid || slot.revision != index.revision)\r\n            {\r\n                throw new IndexOutOfRangeException(\"accessing with expired index\");\r\n            }\r\n\r\n            var newIndex = _freeIndex;\r\n            ref var newSlot = ref _slots[newIndex];\r\n\r\n            newSlot.revision = newSlot.revision == -1 ? 1 : newSlot.revision + 1;\r\n            newSlot.value = value;\r\n            newSlot.isValid = true;\r\n            _freeIndex = newSlot.next;\r\n            newSlot.next = index.index;\r\n            newSlot.previous = slot.previous;\r\n            slot.previous = newIndex;\r\n            if (newSlot.previous >= 0)\r\n            {\r\n                ref var previousSlot = ref _slots[newSlot.previous];\r\n                previousSlot.next = newIndex;\r\n            }\r\n            ++_usedSize;\r\n            if (_firstIndex == index.index)\r\n            {\r\n                _firstIndex = newIndex;\r\n            }\r\n            ++_version;\r\n        }\r\n\r\n        public void Insert(int index, T value)\r\n        {\r\n            Assert.Debug(index >= 0 && index <= _usedSize);\r\n            if (_usedSize == index)\r\n            {\r\n                Add(value);\r\n                return;\r\n            }\r\n\r\n            Assert.Debug(_lock == 0);\r\n            GrowIfNeeded(1);\r\n            Assert.Debug(_freeIndex != -1);\r\n\r\n            var current = _firstIndex;\r\n            while (current >= 0)\r\n            {\r\n                ref var slot = ref this._slots[current];\r\n                Assert.Debug(slot.isValid);\r\n                if (index-- == 0)\r\n                {\r\n                    var newIndex = _freeIndex;\r\n                    ref var newSlot = ref _slots[newIndex];\r\n\r\n                    newSlot.revision = newSlot.revision == -1 ? 1 : newSlot.revision + 1;\r\n                    newSlot.value = value;\r\n                    newSlot.isValid = true;\r\n                    _freeIndex = newSlot.next;\r\n                    newSlot.next = current;\r\n                    newSlot.previous = slot.previous;\r\n                    slot.previous = newIndex;\r\n                    if (newSlot.previous >= 0)\r\n                    {\r\n                        ref var previousSlot = ref _slots[newSlot.previous];\r\n                        previousSlot.next = newIndex;\r\n                    }\r\n                    ++_usedSize;\r\n                    if (_firstIndex == current)\r\n                    {\r\n                        _firstIndex = newIndex;\r\n                    }\r\n                    ++_version;\r\n                    break;\r\n                }\r\n                current = slot.next;\r\n            }\r\n            ++_version;\r\n        }\r\n\r\n        public bool Remove(T item)\r\n        {\r\n            return RemoveAt(StableIndexOf(item));\r\n        }\r\n\r\n        public bool RemoveAt(int index)\r\n        {\r\n            if (index >= 0 && index < _usedSize)\r\n            {\r\n                var current = _firstIndex;\r\n                while (current >= 0)\r\n                {\r\n                    ref var slot = ref this._slots[current];\r\n                    Assert.Debug(slot.isValid);\r\n                    if (index-- == 0)\r\n                    {\r\n                        return RemoveAt(new SIndex(current, slot.revision));\r\n                    }\r\n                    current = slot.next;\r\n                }\r\n                Assert.Never();\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        // 按绝对位置删除\r\n        public bool UnsafeRemoveSlotAt(int index)\r\n        {\r\n            if (index >= 0 && index < _slots.Length)\r\n            {\r\n                ref var slot = ref _slots[index];\r\n                return RemoveAt(new SIndex(index, slot.revision));\r\n            }\r\n            return false;\r\n        }\r\n\r\n        public bool RemoveAt(in SIndex index)\r\n        {\r\n            return TryRemoveAt(index, out var value);\r\n        }\r\n\r\n        public bool TryRemoveAt(int index, out T value)\r\n        {\r\n            if (index >= 0 && index < this._usedSize)\r\n            {\r\n                var current = _firstIndex;\r\n                while (current >= 0)\r\n                {\r\n                    ref var slot = ref this._slots[current];\r\n                    Assert.Debug(slot.isValid);\r\n                    if (index-- == 0)\r\n                    {\r\n                        return TryRemoveAt(new SIndex(current, slot.revision), out value);\r\n                    }\r\n                    current = slot.next;\r\n                }\r\n            }\r\n\r\n            value = default;\r\n            return false;\r\n        }\r\n\r\n        public bool TryRemoveAt(in SIndex index, out T value)\r\n        {\r\n            if (index.index >= 0 && index.index < this._slots.Length)\r\n            {\r\n                ref var slot = ref _slots[index.index];\r\n\r\n                if (slot.isValid && slot.revision == index.revision)\r\n                {\r\n                    Assert.Debug(_lock == 0);\r\n\r\n                    var next = slot.next;\r\n                    var previous = slot.previous;\r\n\r\n                    value = slot.value;\r\n                    slot.value = default;\r\n                    slot.next = _freeIndex;\r\n                    slot.isValid = false;\r\n                    _freeIndex = index.index;\r\n                    --_usedSize;\r\n                    ++_version;\r\n\r\n                    if (next >= 0)\r\n                    {\r\n                        ref var nextSlot = ref _slots[next];\r\n                        nextSlot.previous = previous;\r\n                    }\r\n                    if (previous >= 0)\r\n                    {\r\n                        ref var previousSlot = ref _slots[previous];\r\n                        previousSlot.next = next;\r\n                    }\r\n                    if (_firstIndex == index.index)\r\n                    {\r\n                        _firstIndex = next;\r\n                    }\r\n                    if (_lastIndex == index.index)\r\n                    {\r\n                        _lastIndex = previous;\r\n                    }\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            value = default;\r\n            return false;\r\n        }\r\n\r\n        public void Clear()\r\n        {\r\n            if (_usedSize > 0)\r\n            {\r\n                Assert.Debug(_lock == 0);\r\n                Assert.Debug(_firstIndex >= 0);\r\n\r\n                while (_firstIndex >= 0)\r\n                {\r\n                    var index = _firstIndex;\r\n                    ref var slot = ref this._slots[index];\r\n\r\n                    Assert.Debug(slot.isValid);\r\n                    _firstIndex = slot.next;\r\n                    slot.next = _freeIndex;\r\n                    slot.value = default;\r\n                    slot.isValid = false;\r\n                    // ++slot.revision;\r\n                    _freeIndex = index;\r\n                }\r\n                Assert.Debug(_firstIndex == -1);\r\n                _lastIndex = -1;\r\n                _usedSize = 0;\r\n                ++_version;\r\n            }\r\n        }\r\n\r\n        public bool Contains(T item)\r\n        {\r\n            return IndexOf(item) >= 0;\r\n        }\r\n\r\n        public int IndexOf(T item)\r\n        {\r\n            if ((object)item == null)\r\n            {\r\n                var current = _firstIndex;\r\n                while (current >= 0)\r\n                {\r\n                    ref var slot = ref this._slots[current];\r\n                    Assert.Debug(slot.isValid);\r\n                    if ((object)slot.value == null)\r\n                    {\r\n                        return current;\r\n                    }\r\n                    current = slot.next;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                EqualityComparer<T> equalityComparer = EqualityComparer<T>.Default;\r\n                var current = _firstIndex;\r\n                while (current >= 0)\r\n                {\r\n                    ref var slot = ref this._slots[current];\r\n                    Assert.Debug(slot.isValid);\r\n                    if (equalityComparer.Equals(slot.value, item))\r\n                    {\r\n                        return current;\r\n                    }\r\n                    current = slot.next;\r\n                }\r\n            }\r\n\r\n            return -1;\r\n        }\r\n\r\n        public int LastIndexOf(T item)\r\n        {\r\n            if ((object)item == null)\r\n            {\r\n                var current = _lastIndex;\r\n                while (current >= 0)\r\n                {\r\n                    ref var slot = ref this._slots[current];\r\n                    Assert.Debug(slot.isValid);\r\n                    if ((object)slot.value == null)\r\n                    {\r\n                        return current;\r\n                    }\r\n                    current = slot.previous;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                EqualityComparer<T> equalityComparer = EqualityComparer<T>.Default;\r\n                var current = _lastIndex;\r\n                while (current >= 0)\r\n                {\r\n                    ref var slot = ref this._slots[current];\r\n                    Assert.Debug(slot.isValid);\r\n                    if (equalityComparer.Equals(slot.value, item))\r\n                    {\r\n                        return current;\r\n                    }\r\n                    current = slot.previous;\r\n                }\r\n            }\r\n\r\n            return -1;\r\n        }\r\n\r\n        public SIndex StableIndexOf(T item)\r\n        {\r\n            var index = IndexOf(item);\r\n            if (index >= 0)\r\n            {\r\n                ref var slot = ref this._slots[index];\r\n                return new SIndex(index, slot.revision);\r\n            }\r\n\r\n            return SIndex.None;\r\n        }\r\n\r\n        public SIndex LastStableIndexOf(T item)\r\n        {\r\n            var index = LastIndexOf(item);\r\n            if (index >= 0)\r\n            {\r\n                ref var slot = ref this._slots[index];\r\n                return new SIndex(index, slot.revision);\r\n            }\r\n\r\n            return SIndex.None;\r\n        }\r\n\r\n        public SIndex Find(Func<T, bool> pred)\r\n        {\r\n            var current = this._firstIndex;\r\n\r\n            while (current >= 0)\r\n            {\r\n                ref var slot = ref this._slots[current];\r\n                Assert.Debug(slot.isValid);\r\n                if (pred(slot.value))\r\n                {\r\n                    return new SIndex(current, slot.revision);\r\n                }\r\n                current = slot.next;\r\n            }\r\n\r\n            return default;\r\n        }\r\n\r\n        public R Sum<R>(Func<T, R, R> fn)\r\n        {\r\n            var current = this._firstIndex;\r\n            var result = default(R);\r\n\r\n            while (current >= 0)\r\n            {\r\n                ref var slot = ref this._slots[current];\r\n                Assert.Debug(slot.isValid);\r\n                result = fn(slot.value, result);\r\n                current = slot.next;\r\n            }\r\n\r\n            return result;\r\n        }\r\n\r\n        public struct Enumerator : IEnumerator<T>, IDisposable, IEnumerator\r\n        {\r\n            private SList<T> _list;\r\n            private int _current;\r\n            private int _next;\r\n            private int _version;\r\n\r\n            public Enumerator(SList<T> pool)\r\n            {\r\n                this._list = pool;\r\n                this._current = -1;\r\n                this._next = pool._firstIndex;\r\n                this._version = pool._version;\r\n            }\r\n\r\n            private void VerifyState()\r\n            {\r\n                if (this._list == null)\r\n                {\r\n                    throw new ObjectDisposedException(this.GetType().FullName);\r\n                }\r\n                if (this._version != this._list._version)\r\n                {\r\n                    throw new InvalidOperationException(\"Collection was modified; enumeration operation may not execute.\");\r\n                }\r\n            }\r\n\r\n            public T Current\r\n            {\r\n                get\r\n                {\r\n                    VerifyState();\r\n                    return this._list._slots[_current].value;\r\n                }\r\n            }\r\n\r\n            public bool MoveNext()\r\n            {\r\n                VerifyState();\r\n\r\n                this._current = this._next;\r\n                if (this._current < 0)\r\n                {\r\n                    return false;\r\n                }\r\n                this._next = this._list._slots[this._current].next;\r\n                return true;\r\n            }\r\n\r\n            public void Reset()\r\n            {\r\n                this._current = -1;\r\n                this._next = this._list._firstIndex;\r\n            }\r\n\r\n            public void Dispose() => this._list = null;\r\n\r\n            void IDisposable.Dispose() => this._list = null;\r\n\r\n            object IEnumerator.Current\r\n            {\r\n                get\r\n                {\r\n                    VerifyState();\r\n                    ref var slot = ref this._list._slots[_current];\r\n                    Assert.Debug(slot.isValid);\r\n                    return (object)slot.value;\r\n                }\r\n            }\r\n        }\r\n\r\n        public struct UnsafeEnumerator : IEnumerator<T>, IDisposable, IEnumerator\r\n        {\r\n            private SList<T> _list;\r\n            private int _current;\r\n            private int _next;\r\n\r\n            public UnsafeEnumerator(SList<T> pool)\r\n            {\r\n                this._list = pool;\r\n                this._current = -1;\r\n                this._next = pool._firstIndex;\r\n            }\r\n\r\n            public SIndex Index\r\n            {\r\n                get\r\n                {\r\n                    ref var slot = ref this._list._slots[_current];\r\n                    return new(_current, slot.revision);\r\n                }\r\n            }\r\n\r\n            public T Current\r\n            {\r\n                get\r\n                {\r\n                    ref var slot = ref this._list._slots[_current];\r\n                    Assert.Debug(slot.isValid);\r\n                    return slot.value;\r\n                }\r\n            }\r\n\r\n            public bool MoveNext()\r\n            {\r\n                this._current = this._next;\r\n                if (this._current < 0)\r\n                {\r\n                    return false;\r\n                }\r\n                this._next = this._list._slots[this._current].next;\r\n                return true;\r\n            }\r\n\r\n            public void Remove()\r\n            {\r\n                this._list.UnsafeRemoveSlotAt(_current);\r\n                this._current = -1;\r\n            }\r\n\r\n            public void Reset()\r\n            {\r\n                this._current = -1;\r\n                this._next = this._list._firstIndex;\r\n            }\r\n\r\n            public void Dispose() => this._list = null;\r\n\r\n            void IDisposable.Dispose() => this._list = null;\r\n\r\n            object IEnumerator.Current => (object)this._list._slots[_current].value;\r\n        }\r\n\r\n        public struct StableIndexEnumerator : IEnumerator<SIndex>, IDisposable, IEnumerator\r\n        {\r\n            private SList<T> _list;\r\n            private int _current;\r\n            private int _next;\r\n            private int _version;\r\n\r\n            public StableIndexEnumerator(SList<T> pool)\r\n            {\r\n                this._list = pool;\r\n                this._current = -1;\r\n                this._next = pool._firstIndex;\r\n                this._version = pool._version;\r\n            }\r\n\r\n            private void VerifyState()\r\n            {\r\n                if (this._list == null)\r\n                {\r\n                    throw new ObjectDisposedException(this.GetType().FullName);\r\n                }\r\n                if (this._version != this._list._version)\r\n                {\r\n                    throw new InvalidOperationException(\"Collection was modified; enumeration operation may not execute.\");\r\n                }\r\n            }\r\n\r\n            public SIndex Current\r\n            {\r\n                get\r\n                {\r\n                    VerifyState();\r\n                    ref var slot = ref this._list._slots[_current];\r\n                    Assert.Debug(slot.isValid);\r\n                    return new SIndex(_current, slot.revision);\r\n                }\r\n            }\r\n\r\n            public T Value => this._list[this.Current];\r\n\r\n            public bool MoveNext()\r\n            {\r\n                VerifyState();\r\n\r\n                this._current = this._next;\r\n                if (this._current < 0)\r\n                {\r\n                    return false;\r\n                }\r\n                this._next = this._list._slots[this._current].next;\r\n                return true;\r\n            }\r\n\r\n            public void Reset()\r\n            {\r\n                this._current = -1;\r\n                this._next = this._list._firstIndex;\r\n            }\r\n\r\n            public void Dispose() => this._list = null;\r\n\r\n            void IDisposable.Dispose() => this._list = null;\r\n\r\n            object IEnumerator.Current\r\n            {\r\n                get\r\n                {\r\n                    VerifyState();\r\n                    ref var slot = ref this._list._slots[_current];\r\n                    Assert.Debug(slot.isValid);\r\n                    return (object)new SIndex(_current, slot.revision);\r\n                }\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/SList.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 254fa75c4f555304e8c8e46cdb63e9bb\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/SafeRelease.cs",
    "content": "﻿using System.Collections.Generic;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    using Native;\r\n\r\n    public class SafeRelease : IObjectCollectionEntry\r\n    {\r\n        private ScriptContext _context;\r\n        private List<JSValue> _values = new List<JSValue>();\r\n        private ObjectCollection.Handle _handle;\r\n\r\n        public JSValue this[int index]\r\n        {\r\n            get { return _values[index]; }\r\n        }\r\n\r\n        public bool isValid => _context != null;\r\n\r\n        public SafeRelease(ScriptContext context)\r\n        {\r\n            _context = context;\r\n            _context.GetRuntime().AddManagedObject(this, out _handle);\r\n        }\r\n\r\n        public SafeRelease(ScriptContext context, JSValue value)\r\n        {\r\n            _context = context;\r\n            _values.Add(value);\r\n            _context.GetRuntime().AddManagedObject(this, out _handle);\r\n        }\r\n\r\n        public SafeRelease(ScriptContext context, JSValue value1, JSValue value2)\r\n        {\r\n            _context = context;\r\n            _values.Add(value1);\r\n            _values.Add(value2);\r\n            _context.GetRuntime().AddManagedObject(this, out _handle);\r\n        }\r\n\r\n        #region IObjectCollectionEntry implementation\r\n        public void OnCollectionReleased()\r\n        {\r\n            Release();\r\n        }\r\n        #endregion\r\n\r\n        public JSValue[] ToArray()\r\n        {\r\n            return _values.ToArray();\r\n        }\r\n\r\n        public unsafe SafeRelease Append(int len, JSValue* values)\r\n        {\r\n            for (int i = 0; i < len; i++)\r\n            {\r\n                _values.Add(values[i]);\r\n            }\r\n\r\n            return this;\r\n        }\r\n\r\n        public SafeRelease Append(params JSValue[] values)\r\n        {\r\n            for (int i = 0, size = values.Length; i < size; i++)\r\n            {\r\n                _values.Add(values[i]);\r\n            }\r\n\r\n            return this;\r\n        }\r\n\r\n        public void Release()\r\n        {\r\n            if (_context != null)\r\n            {\r\n                var context = _context;\r\n                _context = null;\r\n                var runtime = context.GetRuntime();\r\n                if (runtime != null)\r\n                {\r\n                    runtime.RemoveManagedObject(_handle);\r\n                }\r\n                var len = _values.Count;\r\n                for (var i = 0; i < len; i++)\r\n                {\r\n                    JSApi.JS_FreeValue(context, _values[i]);\r\n                }\r\n\r\n                _values.Clear();\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/SafeRelease.cs.meta",
    "content": "﻿fileFormatVersion: 2\r\nguid: 1b9e95deb8924e9c842ce08e568f4ac5\r\ntimeCreated: 1591765709"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/TSConfig.cs",
    "content": "using System;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    [Serializable]\r\n    public class TSConfig\r\n    {\r\n        [Serializable]\r\n        public class CompilerOptions\r\n        {\r\n            public string module;\r\n            public string target;\r\n            public string sourceRoot;\r\n            public string outDir;\r\n            public string outFile;\r\n            public string[] typeRoots;\r\n            public string moduleResolution;\r\n            public string[] types;\r\n            public bool listEmittedFiles;\r\n            public bool experimentalDecorators;\r\n            public bool noImplicitAny;\r\n            public bool allowJs;\r\n            public bool inlineSourceMap;\r\n            public bool sourceMap;\r\n        }\r\n        public CompilerOptions compilerOptions;\r\n        public bool compileOnSave;\r\n        public string[] include;\r\n        public string[] exclude;\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/TSConfig.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 82a8176ebd66e724a9234c45b18adb65\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/TextUtils.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.InteropServices;\r\nusing System.Text;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    public static class TextUtils\r\n    {\r\n        private static readonly byte[] _header;\r\n        private static readonly byte[] _footer;\r\n\r\n        static TextUtils()\r\n        {\r\n            _header = Encoding.UTF8.GetBytes(\"(function(exports,require,module,__filename,__dirname){\");\r\n            _footer = Encoding.UTF8.GetBytes(\"\\n})\");\r\n        }\r\n\r\n        public static uint ToHostByteOrder(uint x)\r\n        {\r\n            return (uint)System.Net.IPAddress.NetworkToHostOrder((int)x);\r\n        }\r\n\r\n        public static uint ToNetworkByteOrder(uint x)\r\n        {\r\n            return (uint)System.Net.IPAddress.HostToNetworkOrder((int)x);\r\n        }\r\n\r\n        /// <summary>\r\n        /// 剔除行注释\r\n        /// </summary>\r\n        public static string NormalizeJson(string json)\r\n        {\r\n            if (json == null)\r\n            {\r\n                return json;\r\n            }\r\n            \r\n            var outstr = new StringBuilder();\r\n            var state = 0;\r\n            for (int i = 0; i < json.Length; i++)\r\n            {\r\n                if (state == 0)\r\n                {\r\n                    if (json[i] == '/')\r\n                    {\r\n                        // try to skip url scheme\r\n                        if (i == 0 || json[i - 1] != ':')\r\n                        {\r\n                            state = 1;\r\n                            continue;\r\n                        }\r\n                    }\r\n                }\r\n                else if (state == 1)\r\n                {\r\n                    if (json[i] == '/')\r\n                    {\r\n                        state = 2;\r\n                        continue;\r\n                    }\r\n                    state = 0;\r\n                    outstr.Append('/');\r\n                }\r\n                else if (state == 2)\r\n                {\r\n                    if (json[i] != '\\n')\r\n                    {\r\n                        continue;\r\n                    }\r\n                    state = 0;\r\n                }\r\n                outstr.Append(json[i]);\r\n            }\r\n            return outstr.ToString();\r\n        }\r\n\r\n        public static byte[] GetBytes(string str)\r\n        {\r\n            return Encoding.UTF8.GetBytes(str);\r\n        }\r\n\r\n        public static byte[] GetNullTerminatedBytes(string str)\r\n        {\r\n            if (str == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var len = str.Length;\r\n            if (len > 0 && str[len - 1] == 0)\r\n            {\r\n                return Encoding.UTF8.GetBytes(str);\r\n            }\r\n\r\n            var count = Encoding.UTF8.GetByteCount(str);\r\n            var bytes = new byte[count + 1];\r\n            Encoding.UTF8.GetBytes(str, 0, len, bytes, 0);\r\n\r\n            return bytes;\r\n        }\r\n\r\n        /// <summary>\r\n        /// 在首尾添加内容产生一个可供 require 的 module def\r\n        /// </summary>\r\n        public static byte[] GetShebangNullTerminatedCommonJSBytes(byte[] str)\r\n        {\r\n            return GetShebangNullTerminatedCommonJSBytes(str, _header, _footer);\r\n        }\r\n\r\n        public static byte[] GetShebangNullTerminatedCommonJSBytes(byte[] str, byte[] header, byte[] footer)\r\n        {\r\n            if (str == null)\r\n            {\r\n                return str;\r\n            }\r\n            var count = str.Length;\r\n\r\n            if (str[count - 1] == 0)\r\n            {\r\n                count--;\r\n            }\r\n\r\n            var header_size = header.Length;\r\n            var footer_size = footer.Length;\r\n            var bom_size = 0;\r\n            if (count >= 3)\r\n            {\r\n                // utf8 with bom\r\n                if (str[0] == 239 && str[1] == 187 && str[2] == 191)\r\n                {\r\n                    bom_size = 3;\r\n                }\r\n            }\r\n\r\n            var bytes = new byte[header_size + count + footer_size + 1 - bom_size];\r\n            Array.Copy(header, 0, bytes, 0, header_size);\r\n            Array.Copy(str, bom_size, bytes, header_size, count - bom_size);\r\n\r\n            if (count >= 2)\r\n            {\r\n                // skip shebang line (replace #! => //)\r\n                if (str[0] == 35 && str[1] == 33)\r\n                {\r\n                    bytes[header_size] = 47;\r\n                    bytes[header_size + 1] = 47;\r\n                }\r\n                else\r\n                {\r\n                    if (bom_size > 0)\r\n                    {\r\n                        if (count > bom_size + 1)\r\n                        {\r\n                            if (str[bom_size] == 35 && str[bom_size + 1] == 33)\r\n                            {\r\n                                bytes[header_size] = 47;\r\n                                bytes[header_size + 1] = 47;\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            Array.Copy(footer, 0, bytes, header_size + count - bom_size, footer_size);\r\n            return bytes;\r\n        }\r\n\r\n        /// <summary>\r\n        /// 保证内容存在 \\0 结尾, 返回值可能是源内容本身\r\n        /// </summary>\r\n        public static byte[] GetNullTerminatedBytes(byte[] str)\r\n        {\r\n            if (str == null)\r\n            {\r\n                return str;\r\n            }\r\n\r\n            var count = str.Length;\r\n            if (str[count - 1] == 0)\r\n            {\r\n                return str;\r\n            }\r\n            var bytes = new byte[count + 1];\r\n            Array.Copy(str, 0, bytes, 0, count);\r\n            return bytes;\r\n        }\r\n\r\n        public static int GetBomSize(byte[] str)\r\n        {\r\n            if (str == null)\r\n            {\r\n                return 0;\r\n            }\r\n\r\n            var count = str.Length;\r\n            if (count > 3)\r\n            {\r\n                if (str[0] == 239 && str[1] == 187 && str[2] == 191)\r\n                {\r\n                    return 3;\r\n                }\r\n            }\r\n            return 0;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/TextUtils.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: e0ebfdfd5707cd844b8979f87c9bc093\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/TimerManager.cs",
    "content": "using System;\nusing System.Threading;\nusing System.Diagnostics;\nusing System.Collections.Generic;\n\nnamespace QuickJS.Utils\n{\n    using MillisecondType = UInt64;\n\n    public readonly struct TimerHandle\n    {\n        private readonly TimerManager _timerManager;\n        private readonly SIndex _index;\n\n        public SIndex index => _index;\n\n        public bool isValid => _timerManager != null && _timerManager.IsValidTimer(this);\n\n        public TimerHandle(TimerManager timerManager, in SIndex index)\n        {\n            _timerManager = timerManager;\n            _index = index;\n        }\n\n        public void Invalidate() => _timerManager?.ClearTimer(_index);\n    }\n\n    public readonly struct InternalTimerInfo\n    {\n        public readonly SIndex index;\n        public readonly int delay;\n        public readonly int deadline;\n        public readonly bool once;\n\n        public InternalTimerInfo(in SIndex index, int delay, int deadline, bool once)\n        {\n            this.index = index;\n            this.delay = delay;\n            this.deadline = deadline;\n            this.once = once;\n        }\n    }\n\n    public class TimerManager\n    {\n        private struct InternalTimerData\n        {\n            public SIndex id;\n            public IInvokable action;\n            public MillisecondType rate;\n            public MillisecondType expires;\n            public bool loop;\n\n            public override string ToString() => $\"{nameof(InternalTimerData)}({id}: {rate} {loop})\";\n        }\n\n        private class WheelSlot\n        {\n            private readonly List<SIndex> _timerIndices = new();\n\n            public void Append(in SIndex timerIndex) => _timerIndices.Add(timerIndex);\n\n            public void Move(List<SIndex> cache)\n            {\n                cache.AddRange(_timerIndices);\n                _timerIndices.Clear();\n            }\n\n            public void Move(SList<SIndex> cache)\n            {\n                for (int i = 0, n = _timerIndices.Count; i < n; ++i)\n                {\n                    cache.Add(_timerIndices[i]);\n                }\n                _timerIndices.Clear();\n            }\n\n            public void Clear() => _timerIndices.Clear();\n        }\n\n        private class Wheel\n        {\n            private readonly uint _depth;\n            private readonly MillisecondType _interval;\n            private readonly MillisecondType _range;\n            private readonly WheelSlot[] _slots;\n            private uint _index;\n\n            public MillisecondType range => _range;\n\n            public Wheel(uint depth, MillisecondType interval, uint slots)\n            {\n                _depth = depth;\n                _index = 0;\n                _interval = interval;\n                _range = _interval * slots;\n                _slots = new WheelSlot[slots];\n                for (var i = 0; i < slots; i++)\n                {\n                    _slots[i] = new WheelSlot();\n                }\n            }\n\n            public void Add(MillisecondType delay, in SIndex timerIndex)\n            {\n                var offset = delay >= _interval ? (delay / _interval) - 1 : delay / _interval;\n                // var offset = _depth == 0 ? Math.Max(0, (delay / _interval) - 1) : delay / _interval;\n                // Diagnostics.Logger.Default.Warning(\"time wheel {0} insert delay:{1} index:{2} offset:{3}/{4}\", this, delay, _index, offset, _slots.Length);\n                var index = (uint)((_index + offset) % (MillisecondType)_slots.Length);\n                _slots[index].Append(timerIndex);\n                //UnityEngine.Debug.Assert(index > _index, \"timer slot index\");\n                //UnityEngine.Debug.LogWarning($\"[wheel#{_depth}:{_index}<range:{_range} _interval:{_interval}>] add timer#{timer.id} delay:{delay} to index: {index} offset: {offset}\");\n            }\n\n            /// <summary>\n            /// 返回 true 表示完成一轮循环\n            /// </summary>\n            public void Next(List<SIndex> activeIndices) => _slots[_index++].Move(activeIndices);\n            \n            public void Next(SList<SIndex> activeIndices) => _slots[_index++].Move(activeIndices);\n\n            public bool Round()\n            {\n                if (_index == _slots.Length)\n                {\n                    _index = 0;\n                    return true;\n                }\n                return false;\n            }\n\n            public void Clear()\n            {\n                _index = 0;\n                for (int i = 0, count = _slots.Length; i < count; ++i)\n                {\n                    _slots[i].Clear();\n                }\n            }\n            \n            public override string ToString() => $\"Wheel({_depth} index:{_index} range:{_range} interval:{_interval})\";\n        }\n\n        private readonly int _mainThreadId;\n        private readonly SList<InternalTimerData> _usedTimers = new();\n        private readonly SList<SIndex> _activatedTimers = new();\n        private readonly List<SIndex> _movingTimers = new();\n        private readonly Wheel[] _wheels;\n        private readonly uint _jiffies;\n        private uint _timeSlice;\n        private MillisecondType _elapsed;\n        \n        public MillisecondType now => _elapsed;\n\n        public TimerManager(uint jiffies = 10, uint slots = 20, uint depth = 12)\n        {\n            _mainThreadId = Thread.CurrentThread.ManagedThreadId;\n            _jiffies = jiffies;\n            _wheels = new Wheel[depth];\n            for (uint i = 0; i < depth; i++)\n            {\n                uint interval = 1;\n                for (var j = 0; j < i; j++)\n                {\n                    interval *= slots;\n                }\n                _wheels[i] = new Wheel(i, jiffies * interval, slots);\n            }\n        }\n\n        public InternalTimerInfo GetTimerInfo(in SIndex index)\n        {\n            if (_usedTimers.TryGetValue(index, out var data))\n            {\n                return new InternalTimerInfo(index, (int)data.rate, (int)data.expires, !data.loop);\n            }\n            return new InternalTimerInfo();\n        }\n\n        public void SetTimer(IInvokable fn, MillisecondType rate, bool isLoop = false, MillisecondType firstDelay = default)\n        {\n            SIndex index = default;\n            SetTimer(ref index, fn, rate, isLoop, firstDelay);\n        }\n\n        public void SetTimer(ref TimerHandle handle, IInvokable fn, MillisecondType rate, bool isLoop = false, MillisecondType firstDelay = default)\n        {\n            var index = handle.index;\n            SetTimer(ref index, fn, rate, isLoop, firstDelay);\n            handle = new TimerHandle(this, index);\n        }\n\n        public void SetTimer(ref SIndex timerIndex, IInvokable fn, MillisecondType rate, bool isLoop = false, MillisecondType firstDelay = default)\n        {\n            CheckInternalState();\n\n            _usedTimers.RemoveAt(timerIndex);\n            var index = _usedTimers.Add(default);\n            ref var timer = ref _usedTimers.UnsafeGetValueByRef(index);\n            var delay = firstDelay > 0 ? firstDelay : rate;\n            timer.rate = rate;\n            timer.expires = delay + _elapsed;\n            timer.action = fn;\n            timer.id = index;\n            timer.loop = isLoop;\n\n            if (delay == 0)\n            {\n                Diagnostics.Logger.Default.Warning(\"timer with no delay will initially be processed after a single tick\");\n            }\n            RearrangeTimer(timer.id, delay);\n            // Diagnostics.Logger.Default.Debug($\"[TimerManager] Add timer {timer}\");\n            timerIndex = index;\n        }\n\n        public bool IsValidTimer(in TimerHandle handle) => _usedTimers.IsValidIndex(handle.index);\n\n        public bool ClearTimer(in SIndex timerIndex)\n        {\n            CheckInternalState();\n            if (_usedTimers.RemoveAt(timerIndex))\n            {\n                return true;\n            }\n\n            return false;\n        }\n\n        public void Clear()\n        {\n            CheckInternalState();\n            _timeSlice = default;\n            _elapsed = default;\n            _activatedTimers.Clear();\n            _movingTimers.Clear();\n            for (int wheelIndex = 0, wheelCount = _wheels.Length; wheelIndex < wheelCount; ++wheelIndex)\n            {\n                _wheels[wheelIndex].Clear();\n            }\n            _usedTimers.Clear();\n        }\n\n        public void Tick() => Update(_jiffies);\n\n        public void Update(uint ms)\n        {\n            _timeSlice += ms;\n            while (_timeSlice >= _jiffies)\n            {\n                _timeSlice -= _jiffies;\n                _elapsed += _jiffies;\n                _wheels[0].Next(_activatedTimers);\n                for (int wheelIndex = 0, wheelCount = _wheels.Length; wheelIndex < wheelCount; ++wheelIndex)\n                {\n                    if (_wheels[wheelIndex].Round())\n                    {\n                        if (wheelIndex != wheelCount - 1)\n                        {\n                            _wheels[wheelIndex + 1].Next(_movingTimers);\n                            for (int i = 0, count2 = _movingTimers.Count; i < count2; ++i)\n                            {\n                                if (!_usedTimers.IsValidIndex(_movingTimers[i]))\n                                {\n                                    continue;\n                                }\n                                ref var timer = ref _usedTimers.UnsafeGetValueByRef(_movingTimers[i]);\n                                if (timer.expires > _elapsed)\n                                {\n                                    RearrangeTimer(timer.id, timer.expires - _elapsed);\n                                }\n                                else\n                                {\n                                    _activatedTimers.Add(timer.id);\n                                }\n                            }\n                            _movingTimers.Clear();\n                        }\n                    }\n                    else\n                    {\n                        break;\n                    }\n                }\n            }\n\n            InvokeTimers();\n        }\n\n        public override string ToString()\n        {\n            var sb = new System.Text.StringBuilder();\n            foreach (var w in _wheels)\n            {\n                sb.AppendFormat(\"{0}, \", w);\n            }\n            return sb.ToString();\n        }\n\n        [Conditional(\"JSB_DEBUG\")]\n        private void CheckInternalState()\n        {\n            if (_mainThreadId != Thread.CurrentThread.ManagedThreadId)\n            {\n                throw new Exception(\"TimerManager is only available in main thread\");\n            }\n        }\n\n        private void RearrangeTimer(in SIndex timerId, MillisecondType delay)\n        {\n            var wheelCount = _wheels.Length;\n            for (var i = 0; i < wheelCount; i++)\n            {\n                var wheel = _wheels[i];\n                if (delay < wheel.range)\n                {\n                    wheel.Add(delay, timerId);\n                    return;\n                }\n            }\n\n            Diagnostics.Logger.Default.Error(\"out of time range {0}\", delay);\n            _wheels[wheelCount - 1].Add(delay, timerId);\n        }\n\n        private void InvokeTimers()\n        {\n            do\n            {\n                var index = _activatedTimers.firstIndex;\n                if (!_activatedTimers.TryRemoveAt(index, out var pendingTimerIndex))\n                {\n                    return;\n                }\n                if (!_usedTimers.IsValidIndex(pendingTimerIndex))\n                {\n                    continue;\n                }\n\n                ref var timer = ref _usedTimers.UnsafeGetValueByRef(pendingTimerIndex);\n                // Diagnostics.Logger.Default.Debug(\"timer active {0}\", timer);\n                timer.action.Invoke();\n                if (pendingTimerIndex == timer.id)\n                {\n                    if (timer.loop)\n                    {\n                        // 确认该 timer 仍然有效 (没有在回调中 Remove), 刷新下一次触发时间\n                        timer.expires = timer.rate + _elapsed;\n                        RearrangeTimer(timer.id, timer.rate);\n                    }\n                    else\n                    {\n                        ClearTimer(pendingTimerIndex);\n                    }\n                }\n            } while (true);\n        }\n    }\n}\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/TimerManager.cs.meta",
    "content": "fileFormatVersion: 2\nguid: 96c9edf741aeb2649a66212cfa8ac5af\nMonoImporter:\n  externalObjects: {}\n  serializedVersion: 2\n  defaultReferences: []\n  executionOrder: 0\n  icon: {instanceID: 0}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/TypeDB.cs",
    "content": "using System;\r\nusing System.Collections.Generic;\r\nusing QuickJS.Native;\r\nusing QuickJS.Binding;\r\nusing System.Reflection;\r\n\r\nnamespace QuickJS.Utils\r\n{\r\n    public interface ITypeDB\r\n    {\r\n        int Count { get; }\r\n        DynamicType GetDynamicType(Type type, bool privateAccess);\r\n        DynamicType CreateFreeDynamicType(Type type);\r\n        // bool ContainsDelegate(Type type);\r\n        void AddDelegate(Type type, MethodInfo method);\r\n        MethodInfo GetDelegateFunc(Type delegateType);\r\n        int AddType(Type type, JSValue proto);\r\n        void AddTypeBinder(Type type, ClassBind binder);\r\n        Type GetType(int index);\r\n        int GetTypeID(Type type);\r\n        JSValue FindChainedPrototypeOf(Type cType, out int type_id);\r\n        JSValue FindChainedPrototypeOf(Type cType);\r\n        JSValue FindChainedPrototypeOf(Type cType, out Type pType);\r\n        bool TryGetPrototypeOf(Type type, out JSValue proto);\r\n\r\n        /// <summary>\r\n        /// Get the prototype of type.\r\n        /// NOTE: the returned value is not duplicated. (this behaviour will be changed in the future for better consistency)\r\n        /// </summary>\r\n        JSValue GetPrototypeOf(Type type);\r\n        JSValue FindPrototypeOf(Type type);\r\n        JSValue FindPrototypeOf(Type type, out int type_id);\r\n\r\n        /// <summary>\r\n        /// Get the js contructor value of type (you need to free the returned value by yourself)\r\n        /// </summary>\r\n        JSValue GetConstructorOf(Type type);\r\n        bool IsConstructorEquals(Type type, JSValue ctor);\r\n        void Destroy();\r\n        JSValue NewDynamicMethod(JSAtom name, JSCFunction method);\r\n        JSValue NewDynamicDelegate(JSAtom name, Delegate d);\r\n        JSValue NewDynamicMethod(JSAtom name, IDynamicMethod method);\r\n        JSValue NewDynamicConstructor(JSAtom name, IDynamicMethod method);\r\n        void NewDynamicFieldAccess(JSAtom name, IDynamicField field, out JSValue getter, out JSValue setter);\r\n        IDynamicMethod GetDynamicMethod(int index);\r\n        IDynamicField GetDynamicField(int index);\r\n    }\r\n\r\n    public class TypeDB : ITypeDB\r\n    {\r\n        private ScriptRuntime _runtime;\r\n        private ScriptContext _context;\r\n        private Dictionary<Type, MethodInfo> _delegates = new Dictionary<Type, MethodInfo>(); // 委托对应的 js 绑定函数\r\n        private Dictionary<Type, int> _typeIndex = new Dictionary<Type, int>();\r\n        private Dictionary<Type, DynamicType> _dynamicTypes = new Dictionary<Type, DynamicType>();\r\n        private List<Type> _types = new List<Type>(); // 可用 索引 反查 Type\r\n        private Dictionary<Type, JSValue> _prototypes = new Dictionary<Type, JSValue>();\r\n        private List<IDynamicMethod> _dynamicMethods = new List<IDynamicMethod>();\r\n        private List<IDynamicField> _dynamicFields = new List<IDynamicField>();\r\n\r\n        private Dictionary<Type, ClassBind> _typeBinders = new Dictionary<Type, ClassBind>();\r\n\r\n        public int Count\r\n        {\r\n            get { return _types.Count; }\r\n        }\r\n\r\n        public TypeDB(ScriptRuntime runtime, ScriptContext context)\r\n        {\r\n            _runtime = runtime;\r\n            _context = context;\r\n        }\r\n\r\n        public void AddTypeBinder(Type type, ClassBind binder)\r\n        {\r\n            _typeBinders[type] = binder;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Create dynamic binding for a type, it's used for accessing types which not exported in CustomBinding.\r\n        /// Be careful when using this feature, the type and it's members may be stripped by Unity.\r\n        /// \r\n        /// NOTE: it's usually used by *Hotfix* to replace a statically exported type with it's correspondingly dynamic version, \r\n        ///       and possible to access it's private members at runtime.\r\n        /// \r\n        /// NOTE: it will break the rules defined in CustomBinding.\r\n        /// </summary>\r\n        public DynamicType GetDynamicType(Type type, bool privateAccess)\r\n        {\r\n            DynamicType dynamicType;\r\n            if (_dynamicTypes.TryGetValue(type, out dynamicType))\r\n            {\r\n                if (privateAccess)\r\n                {\r\n                    dynamicType.OpenPrivateAccess();\r\n                }\r\n                return dynamicType;\r\n            }\r\n\r\n            var register = _context.CreateTypeRegister();\r\n\r\n            dynamicType = new DynamicType(type, privateAccess);\r\n            dynamicType.Bind(register);\r\n            _dynamicTypes[type] = dynamicType;\r\n\r\n            if (type.BaseType != null)\r\n            {\r\n                JSValue basePrototype;\r\n                if (!TryGetPrototypeOf(type.BaseType, out basePrototype))\r\n                {\r\n                    // the prototype chain will be setup in register.Finish()\r\n                    GetDynamicType(type.BaseType, privateAccess);\r\n                }\r\n            }\r\n\r\n            register.Finish();\r\n            return dynamicType;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Create a dynamic type without binding (it will be done outside).\r\n        /// \r\n        /// NOTE: this method is only used by TypeBindingInfo.DoReflectBind(), \r\n        ///       the members of the type and it's inheritance are manipulated by BindingManager.\r\n        /// </summary>\r\n        public DynamicType CreateFreeDynamicType(Type type)\r\n        {\r\n            DynamicType dynamicType;\r\n            if (_dynamicTypes.TryGetValue(type, out dynamicType))\r\n            {\r\n                return dynamicType;\r\n            }\r\n\r\n            dynamicType = new DynamicType(type, false);\r\n            _dynamicTypes[type] = dynamicType;\r\n            return dynamicType;\r\n        }\r\n\r\n        // public bool ContainsDelegate(Type type)\r\n        // {\r\n        //     return _delegates.ContainsKey(type);\r\n        // }\r\n\r\n        public void AddDelegate(Type type, MethodInfo method)\r\n        {\r\n            _delegates[type] = method;\r\n        }\r\n\r\n        public MethodInfo GetDelegateFunc(Type delegateType)\r\n        {\r\n            MethodInfo method;\r\n            if (_delegates.TryGetValue(delegateType, out method))\r\n            {\r\n                return method;\r\n            }\r\n            return null;\r\n        }\r\n\r\n        // 注册新类型, 会增加 proto 的引用计数\r\n        public int AddType(Type type, JSValue proto)\r\n        {\r\n            JSValue old_proto;\r\n            if (_prototypes.TryGetValue(type, out old_proto))\r\n            {\r\n                JSApi.JS_FreeValue(_context, old_proto);\r\n                _prototypes[type] = JSApi.JS_DupValue(_context, proto);\r\n                return _typeIndex[type];\r\n            }\r\n\r\n            _prototypes[type] = JSApi.JS_DupValue(_context, proto);\r\n            _types.Add(type);\r\n            var index = _types.Count;\r\n            _typeIndex[type] = index;\r\n            return index;\r\n        }\r\n\r\n        public Type GetType(int index)\r\n        {\r\n            return index >= 1 && index <= _types.Count ? _types[index - 1] : null;\r\n        }\r\n\r\n        public int GetTypeID(Type type)\r\n        {\r\n            int index;\r\n            if (_typeIndex.TryGetValue(type, out index))\r\n            {\r\n                return index;\r\n            }\r\n\r\n            return -1;\r\n        }\r\n\r\n        // 将 type 的 prototype 压栈 （未导出则向父类追溯）\r\n        // without reference-count added\r\n        public JSValue FindChainedPrototypeOf(Type cType, out int type_id)\r\n        {\r\n            if (cType == null)\r\n            {\r\n                type_id = -1;\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n\r\n            JSValue proto;\r\n            if (TryGetPrototypeOf(cType, out proto))\r\n            {\r\n                type_id = GetTypeID(cType);\r\n                return proto;\r\n            }\r\n\r\n            return FindChainedPrototypeOf(cType.BaseType, out type_id);\r\n        }\r\n\r\n        public JSValue FindChainedPrototypeOf(Type cType)\r\n        {\r\n            if (cType == null)\r\n            {\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n\r\n            if (cType == typeof(Enum))\r\n            {\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n\r\n            JSValue proto;\r\n            if (TryGetPrototypeOf(cType, out proto))\r\n            {\r\n                return proto;\r\n            }\r\n\r\n            return FindChainedPrototypeOf(cType.BaseType);\r\n        }\r\n\r\n        public JSValue FindChainedPrototypeOf(Type cType, out Type pType)\r\n        {\r\n            if (cType == null)\r\n            {\r\n                pType = null;\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n\r\n            if (cType == typeof(Enum))\r\n            {\r\n                pType = null;\r\n                return JSApi.JS_UNDEFINED;\r\n            }\r\n\r\n            JSValue proto;\r\n            if (TryGetPrototypeOf(cType, out proto))\r\n            {\r\n                pType = cType;\r\n                return proto;\r\n            }\r\n\r\n            return FindChainedPrototypeOf(cType.BaseType, out pType);\r\n        }\r\n\r\n        public bool TryGetPrototypeOf(Type type, out JSValue proto)\r\n        {\r\n            if (_prototypes.TryGetValue(type, out proto))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            ClassBind binder;\r\n            if (_typeBinders.TryGetValue(type, out binder))\r\n            {\r\n                var typeRegister = _context.CreateTypeRegister();\r\n                binder(typeRegister);\r\n                typeRegister.Finish();\r\n\r\n                if (_prototypes.TryGetValue(type, out proto))\r\n                {\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            proto = JSApi.JS_UNDEFINED;\r\n            return false;\r\n        }\r\n\r\n        public JSValue GetPrototypeOf(Type type)\r\n        {\r\n            JSValue proto;\r\n            if (TryGetPrototypeOf(type, out proto))\r\n            {\r\n                return proto;\r\n            }\r\n\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        public JSValue FindPrototypeOf(Type type)\r\n        {\r\n            int type_id;\r\n            return FindPrototypeOf(type, out type_id);\r\n        }\r\n\r\n        public JSValue FindPrototypeOf(Type type, out int type_id)\r\n        {\r\n            JSValue proto;\r\n            if (TryGetPrototypeOf(type, out proto))\r\n            {\r\n                type_id = GetTypeID(type);\r\n                return proto;\r\n            }\r\n\r\n            type_id = -1;\r\n            return JSApi.JS_UNDEFINED;\r\n        }\r\n\r\n        public JSValue GetConstructorOf(Type type)\r\n        {\r\n            var proto = GetPrototypeOf(type);\r\n            if (proto.IsUndefined())\r\n            {\r\n                return proto;\r\n            }\r\n            return JSApi.JS_GetProperty(_context, proto, JSApi.JS_ATOM_constructor);\r\n        }\r\n\r\n        public bool IsConstructorEquals(Type type, JSValue ctor)\r\n        {\r\n            var proto = GetPrototypeOf(type);\r\n            var type_ctor = JSApi.JS_GetProperty(_context, proto, JSApi.JS_ATOM_constructor);\r\n            var result = type_ctor == ctor;\r\n            JSApi.JS_FreeValue(_context, type_ctor);\r\n            return result;\r\n        }\r\n\r\n        public void Destroy()\r\n        {\r\n            var ctx = (JSContext)_context;\r\n            foreach (var kv in _prototypes)\r\n            {\r\n                var jsValue = kv.Value;\r\n                JSApi.JS_FreeValue(ctx, jsValue);\r\n            }\r\n\r\n            _prototypes.Clear();\r\n        }\r\n\r\n        public static Type GetType(string name)\r\n        {\r\n            if (string.IsNullOrEmpty(name))\r\n            {\r\n                return null;\r\n            }\r\n            var type = Assembly.GetExecutingAssembly().GetType(name);\r\n            return type;\r\n        }\r\n\r\n        public JSValue NewDynamicMethod(JSAtom name, JSCFunction method)\r\n        {\r\n            return NewDynamicMethod(name, new DynamicMethodInvoke(method));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Create a delegate wrapper object.\r\n        /// NOTE: the method registry will hold a reference of the given delegate, this usually causes leaks.\r\n        /// </summary>\r\n        public JSValue NewDynamicDelegate(JSAtom name, Delegate d)\r\n        {\r\n            if (d == null)\r\n            {\r\n                return JSApi.JS_NULL;\r\n            }\r\n\r\n            var method = new DynamicDelegateMethod(d);\r\n            var magic = _dynamicMethods.Count;\r\n            var funValue = JSApi.JSB_NewCFunctionMagic(_context, _DynamicMethodInvoke, name, 0, magic);\r\n            _dynamicMethods.Add(method);\r\n#if JSB_DEBUG\r\n            Diagnostics.Logger.Default.Debug(\"NewDynamicDelegate {0} {1} = {2}\", name, d, funValue);\r\n#endif\r\n            return funValue;\r\n        }\r\n\r\n        public JSValue NewDynamicMethod(JSAtom name, IDynamicMethod method)\r\n        {\r\n            if (method == null)\r\n            {\r\n                var funValue = JSApi.JSB_NewCFunctionMagic(_context, JSNative.class_private_ctor, name, 0, 0);\r\n                return funValue;\r\n            }\r\n            else\r\n            {\r\n                var magic = _dynamicMethods.Count;\r\n                var funValue = JSApi.JSB_NewCFunctionMagic(_context, _DynamicMethodInvoke, name, 0, magic);\r\n                _dynamicMethods.Add(method);\r\n                return funValue;\r\n            }\r\n        }\r\n\r\n        public JSValue NewDynamicConstructor(JSAtom name, IDynamicMethod method)\r\n        {\r\n            if (method == null)\r\n            {\r\n                var funValue = JSApi.JSB_NewConstructor(_context, JSNative.class_private_ctor, name, 0);\r\n                return funValue;\r\n            }\r\n            else\r\n            {\r\n                var magic = _dynamicMethods.Count;\r\n                var funValue = JSApi.JSB_NewConstructor(_context, _DynamicMethodInvoke, name, magic);\r\n                _dynamicMethods.Add(method);\r\n                return funValue;\r\n            }\r\n        }\r\n\r\n        public void NewDynamicFieldAccess(JSAtom name, IDynamicField field, out JSValue getter, out JSValue setter)\r\n        {\r\n            var magic = _dynamicFields.Count;\r\n            getter = JSApi.JSB_NewGetter(_context, _DynamicFieldGetter, name, magic);\r\n            setter = JSApi.JSB_NewSetter(_context, _DynamicFieldSetter, name, magic);\r\n            _dynamicFields.Add(field);\r\n        }\r\n\r\n        public IDynamicMethod GetDynamicMethod(int index)\r\n        {\r\n            return index >= 0 && index < _dynamicMethods.Count ? _dynamicMethods[index] : null;\r\n        }\r\n\r\n        public IDynamicField GetDynamicField(int index)\r\n        {\r\n            return index >= 0 && index < _dynamicFields.Count ? _dynamicFields[index] : null;\r\n        }\r\n\r\n        // 用于中转动态注册的反射调用\r\n        [MonoPInvokeCallback(typeof(JSCFunctionMagic))]\r\n        public static JSValue _DynamicOperatorInvoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv, int magic)\r\n        {\r\n            throw new NotImplementedException();\r\n        }\r\n\r\n        // 用于中转动态注册的反射调用\r\n        [MonoPInvokeCallback(typeof(JSCFunctionMagic))]\r\n        public static JSValue _DynamicMethodInvoke(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv, int magic)\r\n        {\r\n            var typeDB = ScriptEngine.GetTypeDB(ctx);\r\n\r\n            if (typeDB == null)\r\n            {\r\n                return ctx.ThrowInternalError(\"type db is null\");\r\n            }\r\n\r\n            var method = typeDB.GetDynamicMethod(magic);\r\n            if (method != null)\r\n            {\r\n                try\r\n                {\r\n                    return method.Invoke(ctx, this_obj, argc, argv);\r\n                }\r\n                catch (Exception exception)\r\n                {\r\n                    return ctx.ThrowException(exception);\r\n                }\r\n            }\r\n\r\n            return ctx.ThrowInternalError(\"dynamic method not found\");\r\n        }\r\n\r\n        // 用于中转动态注册的反射调用\r\n        [MonoPInvokeCallback(typeof(JSGetterCFunctionMagic))]\r\n        public static JSValue _DynamicFieldGetter(JSContext ctx, JSValue this_obj, int magic)\r\n        {\r\n            var typeDB = ScriptEngine.GetTypeDB(ctx);\r\n\r\n            if (typeDB == null)\r\n            {\r\n                return ctx.ThrowInternalError(\"type db is null\");\r\n            }\r\n\r\n            var field = typeDB.GetDynamicField(magic);\r\n            if (field != null)\r\n            {\r\n                try\r\n                {\r\n                    return field.GetValue(ctx, this_obj);\r\n                }\r\n                catch (Exception exception)\r\n                {\r\n                    return ctx.ThrowException(exception);\r\n                }\r\n            }\r\n\r\n            return ctx.ThrowInternalError(\"dynamic field not found\");\r\n        }\r\n\r\n        // 用于中转动态注册的反射调用\r\n        [MonoPInvokeCallback(typeof(JSSetterCFunctionMagic))]\r\n        public static JSValue _DynamicFieldSetter(JSContext ctx, JSValue this_obj, JSValue val, int magic)\r\n        {\r\n            var typeDB = ScriptEngine.GetTypeDB(ctx);\r\n\r\n            if (typeDB == null)\r\n            {\r\n                return ctx.ThrowInternalError(\"type db is null\");\r\n            }\r\n\r\n            var field = typeDB.GetDynamicField(magic);\r\n            if (field != null)\r\n            {\r\n                try\r\n                {\r\n                    return field.SetValue(ctx, this_obj, val);\r\n                }\r\n                catch (Exception exception)\r\n                {\r\n                    return ctx.ThrowException(exception);\r\n                }\r\n            }\r\n\r\n            return ctx.ThrowInternalError(\"dynamic field not found\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils/TypeDB.cs.meta",
    "content": "fileFormatVersion: 2\r\nguid: 56fe39ed05ffbc347ba31e4135d6d46f\r\nMonoImporter:\r\n  externalObjects: {}\r\n  serializedVersion: 2\r\n  defaultReferences: []\r\n  executionOrder: 0\r\n  icon: {instanceID: 0}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/Utils.meta",
    "content": "fileFormatVersion: 2\r\nguid: 7350183ab52168f47b9c3f2d3f67030a\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/jsb.core.asmdef",
    "content": "{\n    \"name\": \"jsb.core\",\n    \"rootNamespace\": \"\",\n    \"references\": [\n        \"GUID:595d45be140461240b6b4358dc45f2c0\",\n        \"GUID:ac4126d60783f3d4a98aee6be9a997aa\"\n    ],\n    \"includePlatforms\": [],\n    \"excludePlatforms\": [],\n    \"allowUnsafeCode\": true,\n    \"overrideReferences\": false,\n    \"precompiledReferences\": [],\n    \"autoReferenced\": true,\n    \"defineConstraints\": [],\n    \"versionDefines\": [],\n    \"noEngineReferences\": false\n}"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source/jsb.core.asmdef.meta",
    "content": "fileFormatVersion: 2\nguid: 118b4ca3a1852354bac065cf952c1e85\nAssemblyDefinitionImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Source.meta",
    "content": "fileFormatVersion: 2\r\nguid: 376be4fcda6ee7841945549b8c5b64be\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Typings/fswatcher.d.ts",
    "content": "\r\ndeclare class FSWatcher {\r\n    constructor(path?: string, filter?: string);\r\n\r\n    path: string;\r\n    filter: string;\r\n    enableRaisingEvents: boolean;\r\n    includeSubdirectories: boolean;\r\n\r\n    /**\r\n     * all file change events will be delayed until the application become active. \r\n     * default: true\r\n     */\r\n    isDelayedUntilActive: boolean; \r\n\r\n    oncreate: (name: string, fullPath: string) => void;\r\n    ondelete: (name: string, fullPath: string) => void;\r\n    onchange: (name: string, fullPath: string) => void;\r\n\r\n    dispose(): void;\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Typings/fswatcher.d.ts.meta",
    "content": "fileFormatVersion: 2\r\nguid: fafb41fe21afbad43a85efe005e4bc12\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Typings/jsb.d.ts",
    "content": "\r\n/**\r\n * alternative to console.log\r\n */\r\ndeclare function print(...args: any[]): void;\r\n\r\n/**\r\n * [EXPERIMENTAL]\r\n * 向 master runtime 发送消息 (目前 data 通过 JS_WriteObject/ReadObject 进行传输)\r\n * !!! 注意: 目前还没有提供跨越 runtime 的托管对象传递, 请不要传递.net托管对象. \r\n */\r\ndeclare function postMessage(data: any): void;\r\n\r\n/**\r\n * [EXPERIMENTAL]\r\n */\r\ndeclare function jsx(type: string, attributes: any, content?: any): any;\r\n\r\n/**\r\n * this module is only available with `editorScripting`\r\n */\r\ndeclare module \"jsb.editor\" {\r\n    import { Prefs } from \"QuickJS.Binding\";\r\n    import { TSConfig } from \"QuickJS.Utils\";\r\n\r\n    class EditorRuntime {\r\n        /**\r\n         * the prefs loaded by EditorRuntime \r\n         */\r\n        static readonly prefs: Prefs;\r\n\r\n        /**\r\n         * the tsconfig.json parsed by EditorRuntime\r\n         */\r\n        static readonly tsconfig: TSConfig;\r\n    }\r\n}\r\n\r\ndeclare module \"jsb\" {\r\n    import { Delegate as SystemDelegate, Array as CSharpArray } from \"System\";\r\n\r\n    type byte = number;\r\n    type Nullable<T> = T;\r\n\r\n    /**\r\n    * 封装 C# ref 传参约定\r\n    */\r\n    interface Ref<T = any> {\r\n        type?: { new(): T } | Function\r\n        value?: T\r\n    }\r\n\r\n    /**\r\n    * 封装 C# out 传参约定\r\n    */\r\n    interface Out<T = any> {\r\n        type?: { new(): T } | Function\r\n        value?: T\r\n    }\r\n\r\n    /**\r\n     * [NOT_IMPLEMENTED]\r\n     */\r\n    interface RuntimeInfo {\r\n        /**\r\n         * 运行时唯一ID\r\n         */\r\n        id: number;\r\n\r\n        /**\r\n         * 是否是工作者线程\r\n         */\r\n        isWorker: boolean;\r\n\r\n        /**\r\n         * 是否是编辑器运行时\r\n         */\r\n        isEditor: boolean;\r\n    }\r\n\r\n    /**\r\n     * duck type\r\n     */\r\n    interface Task<T> { }\r\n\r\n    /**\r\n     * 标记一个类型仅在特定编译选项下存在 (该修饰器并不存在实际定义, 仅用于标记, 不要在代码中使用)\r\n     */\r\n    function RequiredDefines(...targets: string[]);\r\n\r\n    /**\r\n     * [EXPERIMENTAL]\r\n     * [NOT_IMPLEMENTED]\r\n     * 替换C#代码执行 (未完成此功能)\r\n     */\r\n    namespace hotfix {\r\n        /**\r\n         * 替换 C# 方法 (此方法为测试方法, 最终将移除)\r\n         */\r\n        function replace_single(type: string, func_name: string, func: Function): void\r\n        /**\r\n         * 在 C# 方法前插入执行 (此方法为测试方法, 最终将移除)\r\n         */\r\n        function before_single(type: string, func_name: string, func: Function): void\r\n\r\n        /**\r\n         * 在 C# 方法执行前插入执行 (未完成此功能)\r\n         */\r\n        function before(type: string, func_name: string, func: Function): void\r\n\r\n        /**\r\n         * 在 C# 方法执行后插入执行 (未完成此功能)\r\n         */\r\n        function after(type: string, func_name: string, func: Function): void\r\n    }\r\n\r\n    /**\r\n     * [NOT_IMPLEMENTED]\r\n     */\r\n    class Runtime {\r\n        /**\r\n         * [NotImplemented][未实现] 获取所有 ScriptRuntime 信息\r\n         */\r\n        static get runtimes(): RuntimeInfo[];\r\n\r\n        /**\r\n         * [NotImplemented][未实现] 从其他 ScriptRuntime 接收消息\r\n         */\r\n        static get onmessage(): (id: number, data: any) => void;\r\n        static set onmessage(cb: (id: number, data: any) => void);\r\n\r\n        /**\r\n         * [NotImplemented][未实现] 向指定 ScriptRuntime 发送消息\r\n         */\r\n        static postMessage(id: number, data: any): void;\r\n    }\r\n\r\n    class ModuleManager {\r\n        static BeginReload();\r\n\r\n        /**\r\n         * 将此模块标记为等待重载\r\n         */\r\n        static MarkReload(moduleId: string);\r\n\r\n        static EndReload();\r\n    }\r\n\r\n    class ArrayUtils {\r\n        static GetLength(cs: CSharpArray<any>): number;\r\n        static GetValue(cs: CSharpArray<any>, index: number): any;\r\n        static RemoveAt(cs: CSharpArray<any>, index: number): void;\r\n        static Insert(cs: CSharpArray<any>, value: any, index: number): void;\r\n        static SetValue(cs: CSharpArray<any>, value: any, index: number): void;\r\n    }\r\n\r\n    /**\r\n     * Eval code snippet read from file.\r\n     */\r\n    function DoFile(filename: string): void;\r\n\r\n    /**\r\n     * Requests a garbadge collection call.\r\n     */\r\n    function GC(): void\r\n\r\n    /**\r\n     * 标记对象是否由JS管理销毁 (自动调用 Dispose)\r\n     * @param o CS对象实例\r\n     * @param disposable 是否托管\r\n     * @returns 是否设置成功\r\n     */\r\n    function SetDisposable(o: any, disposable: boolean): boolean;\r\n\r\n    /**\r\n     * The current tick (in milliseconds) of the scheduler used by setInterval and setTimeout.\r\n     * NOTE: It starts from 0.\r\n     */\r\n    function Now(): number\r\n\r\n    /**\r\n     * Is running with StaticBind mode\r\n     */\r\n    function IsStaticBinding(): boolean;\r\n\r\n    let isOperatorOverloadingSupported: boolean;\r\n\r\n    /**\r\n     * Indicates what backend engine is being used\r\n     */\r\n    let engine: string;\r\n\r\n    /**\r\n     * Represents the version of jsb dll (the value of JSApi.SO_JSB_VERSION)\r\n     */\r\n    let version: number;\r\n\r\n    /**\r\n     * The version of this plugin itself (in hex)\r\n     */\r\n    let pluginVersion: number;\r\n\r\n    /**\r\n     * Calls Thread.Sleep()\r\n     */\r\n    function Sleep(millisecondsTimeout?: number): void\r\n\r\n    /**\r\n     * Cache a string (It's helpful to avoid unnecessary gc alloc when frequently used in interop)\r\n     */\r\n    function AddCacheString(str: string): string;\r\n\r\n    /**\r\n     * Remove a string from string cache.\r\n     */\r\n    function RemoveCacheString(str: string): boolean;\r\n\r\n    /**\r\n     * \r\n     */\r\n    function AddSearchPath(path: string): void\r\n\r\n    /**\r\n     * [UNDOCUMENTED]\r\n     */\r\n    function AddModule(module_id: string, e: any): void;\r\n\r\n    // @ts-ignore\r\n    // function Yield(instruction: UnityEngine.YieldInstruction): Promise<UnityEngine.YieldInstruction>;\r\n    // function Yield(enumerator: SystemCollections.IEnumerator): Promise<SystemObject>;\r\n    function Yield<T>(task: Task<T>): Promise<T>;\r\n\r\n    /**\r\n     * 将 C# 委托强制转换为 JS Function\r\n     * @summary 如果传入的已经是 Function, 将直接返回\r\n     * @summary 如果传入的是一个 C# 委托对象, 将通过 dynamic method wrapper 产生一个 JS Function \r\n     * @summary 谨慎: 无法再从 function 还原此委托, 两者不会建立关联 (会构成强引用循环) \r\n     * @summary 谨慎: NewDynamicDelegate 会产生一个与 Runtime 相同生命周期的对象, 该对象将持有 Delegate 对象引用 \r\n     * @param makeDynamic 是否创建委托的JS函数包装 (NewDynamicDelegate) [默认 false]\r\n     */\r\n    function ToFunction(o: SystemDelegate | Function, makeDynamic?: boolean): Function;\r\n\r\n    /**\r\n     * [EXPERIMENTAL]\r\n     */\r\n    function ToDelegate(o: SystemDelegate | Function, typeName: string): SystemDelegate;\r\n\r\n    /**\r\n     * [NOT_DETERMINED]\r\n     */\r\n    // function ToJSArray(o: any): Array;\r\n\r\n    /**\r\n     * Converts C# Array into JS Array\r\n     */\r\n    function ToArray<T>(o: CSharpArray<T>): Array<T>;\r\n\r\n    /**\r\n     * Converts C# Array<byte> into JS ArrayBuffer\r\n     */\r\n    function ToArrayBuffer(o: CSharpArray<byte> | number[]): ArrayBuffer;\r\n\r\n    /**\r\n     * Converts JS ArrayBuffer or Unit8Array into C# Array<byte>\r\n     */\r\n    function ToBytes(o: ArrayBuffer | Uint8Array): CSharpArray<byte>;\r\n\r\n    /**\r\n     * Dynamically import a C# type\r\n     * @param type FullName of a C# type\r\n     * @param privateAccess Whether the private members are allowed to access in JS\r\n     */\r\n    function Import(type: string, privateAccess?: boolean): FunctionConstructor;\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Typings/jsb.d.ts.meta",
    "content": "fileFormatVersion: 2\r\nguid: 42b907f7ca05f6a4c88e7c6df8535202\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Typings/plover.d.ts",
    "content": "/// <reference types=\"node\" />\r\ndeclare module \"plover/events/dispatcher\" {\r\n    export class Handler {\r\n        caller: any;\r\n        fn: Function;\r\n        once: boolean;\r\n        constructor(caller: any, fn: Function, once?: boolean);\r\n        invoke(arg0?: any, arg1?: any, arg2?: any): void;\r\n    }\r\n    /**\r\n     * 简单的事件分发器实现\r\n     * 此实现功能与 DuktapeJS.Dispatcher 基本一致,\r\n     * 但 DuktapeJS.Dispatcher 不保证事件响应顺序, 但效率更高 (因为复用了中途移除的索引)\r\n     */\r\n    export class Dispatcher {\r\n        private _handlers;\r\n        on(caller: any, fn: Function): Handler;\r\n        once(caller: any, fn: Function): Handler;\r\n        off(caller: any, fn: Function): boolean;\r\n        /**\r\n         * 移除所有处理器\r\n         */\r\n        clear(): void;\r\n        dispatch(arg0?: any, arg1?: any, arg2?: any): void;\r\n    }\r\n    /**\r\n     * 按事件名派发\r\n     */\r\n    export class EventDispatcher {\r\n        private _dispatcher;\r\n        on(evt: string, caller: any, fn?: Function): void;\r\n        once(evt: string, caller: any, fn?: Function): void;\r\n        off(evt: string, caller: any, fn?: Function): void;\r\n        clear(): void;\r\n        /**\r\n         * 派发指定事件\r\n         */\r\n        dispatch(evt: string, arg0?: any, arg1?: any, arg2?: any): void;\r\n    }\r\n}\r\ndeclare module \"plover/editor/auto_completion_field\" {\r\n    import { EventDispatcher } from \"plover/events/dispatcher\";\r\n    export class AutoCompletionField extends EventDispatcher {\r\n        searchString: string;\r\n        maxResults: number;\r\n        private results;\r\n        private selectedIndex;\r\n        private searchField;\r\n        private previousMousePosition;\r\n        private selectedIndexByMouse;\r\n        private showResults;\r\n        constructor();\r\n        addResult(result: string): void;\r\n        clearResults(): void;\r\n        onToolbarGUI(): void;\r\n        onGUI(): void;\r\n        private draw;\r\n        private doSearchField;\r\n        private onDownOrUpArrowKeyPressed;\r\n        private doResults;\r\n        private onConfirm;\r\n        private hasSearchbarFocused;\r\n        private repaintFocusedWindow;\r\n    }\r\n}\r\ndeclare module \"plover/runtime/serialize\" {\r\n    import { ByteBuffer } from \"QuickJS.IO\";\r\n    import { JSSerializationContext } from \"QuickJS.Unity\";\r\n    export interface IPrimitiveSerializer {\r\n        typeid: number;\r\n        defaultValue: any;\r\n        serialize(context: SerializationContext, buffer: ByteBuffer, value: any): void;\r\n        deserilize(context: SerializationContext, buffer: ByteBuffer): any;\r\n    }\r\n    export interface PrimitiveSerializerImpl {\r\n        dataFormat: number;\r\n        description: string;\r\n        types: {\r\n            [key: string]: IPrimitiveSerializer;\r\n        };\r\n        typeids: IPrimitiveSerializer[];\r\n    }\r\n    export interface SerializationContext {\r\n        impl: PrimitiveSerializerImpl;\r\n        ps: JSSerializationContext;\r\n    }\r\n    export enum SerializedTypeID {\r\n        Null = 0,\r\n        UserDefinedMin = 1,\r\n        UserDefinedMax = 100,\r\n        Array = 101,\r\n        Object = 102\r\n    }\r\n    export function GetLatestSerializer(): PrimitiveSerializerImpl;\r\n    export function GetSerializer(dataFormat: number): PrimitiveSerializerImpl;\r\n    export function RegisterSerializer(dataFormat: number, description: string, types: {\r\n        [key: string]: IPrimitiveSerializer;\r\n    }, bSetAsLatest?: boolean): void;\r\n}\r\ndeclare module \"plover/runtime/class_decorators\" {\r\n    import { ByteBuffer } from \"QuickJS.IO\";\r\n    import { JSSerializationContext } from \"QuickJS.Unity\";\r\n    export interface FunctionMetaInfo {\r\n    }\r\n    export interface ClassMetaInfo {\r\n    }\r\n    export type PropertyTypeID = \"bool\" | \"float\" | \"double\" | \"string\" | \"object\" | \"int\" | \"uint\" | \"Uint8ArrayBuffer\" | \"Vector2\" | \"Vector3\" | \"Vector4\" | \"Rect\" | \"Quaternion\" | \"json\" | Function;\r\n    export type PropertyLayout = \"plain\" | \"array\";\r\n    export interface WeakPropertyMetaInfo {\r\n        /**\r\n         * slot name in property table\r\n         */\r\n        name?: string;\r\n        propertyKey?: string;\r\n        /**\r\n         * (默认编辑器行为中) 是否可见\r\n         */\r\n        visible?: boolean;\r\n        /**\r\n         * (默认编辑器行为中) 是否可以编辑\r\n         */\r\n        editable?: boolean;\r\n        /**\r\n         * 是否仅编辑器状态可编辑\r\n         */\r\n        editorOnly?: boolean;\r\n        /**\r\n         * 是否序列化\r\n         */\r\n        serializable?: boolean;\r\n        label?: string;\r\n        tooltip?: string;\r\n        extra?: any;\r\n        /**\r\n         * UGUI, 自动绑定界面组件\r\n         */\r\n        bind?: {\r\n            name?: string;\r\n            widget?: Function;\r\n        };\r\n    }\r\n    export interface PropertyMetaInfo extends WeakPropertyMetaInfo {\r\n        type: PropertyTypeID;\r\n        layout?: PropertyLayout;\r\n    }\r\n    export function ScriptSerializable(meta?: any): (target: any) => any;\r\n    export function ScriptAsset(meta?: any): (target: any) => any;\r\n    export function ScriptType(meta?: ClassMetaInfo): (target: any) => any;\r\n    export function ScriptInteger(meta?: WeakPropertyMetaInfo): (target: any, propertyKey: string) => void;\r\n    export function ScriptNumber(meta?: WeakPropertyMetaInfo): (target: any, propertyKey: string) => void;\r\n    export function ScriptString(meta?: WeakPropertyMetaInfo): (target: any, propertyKey: string) => void;\r\n    export function ScriptObject(meta?: WeakPropertyMetaInfo): (target: any, propertyKey: string) => void;\r\n    export function ScriptProperty(meta?: PropertyMetaInfo): (target: any, propertyKey: string) => void;\r\n    export function ScriptFunction(meta?: any): (target: any, propertyKey: string) => void;\r\n    export class SerializationUtil {\r\n        static forEach(target: any, cb: (slots: {\r\n            [key: string]: PropertyMetaInfo;\r\n        }, propertyKey: string) => void): void;\r\n        static markAsReady(target: any): void;\r\n        static serialize(target: any, ps: JSSerializationContext): void;\r\n        private static _serializeValue;\r\n        private static _serializeObjectArray;\r\n        private static _serializePrimitiveArray;\r\n        private static _serializeObject;\r\n        static deserialize(target: any, ps: JSSerializationContext, buffer: ByteBuffer): void;\r\n        private static _deserializeObject;\r\n        private static _deserializeObjectArray;\r\n        private static _deserializePrimitiveArray;\r\n        private static _deserializeObjectInternal;\r\n    }\r\n}\r\ndeclare module \"plover/editor/drawer\" {\r\n    import { PropertyMetaInfo } from \"plover/runtime/class_decorators\";\r\n    interface IPropertyDrawer {\r\n        draw(value: any, prop: PropertyMetaInfo, label: string, editablePE: boolean): any;\r\n    }\r\n    export let DefaultPropertyDrawers: {\r\n        [key: string]: IPropertyDrawer;\r\n    };\r\n}\r\ndeclare module \"plover/editor/editor_decorators\" {\r\n    import { Editor } from \"UnityEditor\";\r\n    import { ClassMetaInfo } from \"plover/runtime/class_decorators\";\r\n    export interface EditorWindowMetaInfo extends ClassMetaInfo {\r\n    }\r\n    export function ScriptEditor(forType: any): (editorType: any) => any;\r\n    export function ScriptEditorWindow(meta?: EditorWindowMetaInfo): (target: any) => any;\r\n    export interface IEditorScriptingSupport {\r\n        OnPropertyChanging(target: any, property: any, propertyKey: string, newValue: any): void;\r\n        OnArrayPropertyChanging(target: any, property: any, propertyKey: string, index: number, newValue: any): void;\r\n    }\r\n    export class DefaultEditor extends Editor implements IEditorScriptingSupport {\r\n        OnPropertyPreChanging(target: any, name: string): void;\r\n        OnPropertyChanging(target: any, property: any, propertyKey: string, newValue: any): void;\r\n        OnArrayPropertyChanging(target: any, property: any, propertyKey: string, index: number, newValue: any): void;\r\n        OnInspectorGUI(): void;\r\n    }\r\n    export class EditorUtil {\r\n        static getCustomEditor(forType: any): any;\r\n        /**\r\n         * 默认编辑器绘制行为\r\n         */\r\n        static draw(editor: IEditorScriptingSupport, target: any): void;\r\n    }\r\n}\r\ndeclare module \"plover/editor/file_watcher\" {\r\n    export enum EFileState {\r\n        CHANGE = 1,\r\n        NEW = 2,\r\n        DELETE = 3\r\n    }\r\n    export interface FileState {\r\n        name: string;\r\n        fullPath: string;\r\n        state: EFileState;\r\n    }\r\n    export interface IFileStateMap {\r\n        [name: string]: FileState;\r\n    }\r\n    export class FileWatcher {\r\n        static readonly ANY = \"* ANY\";\r\n        static readonly CHANGED = \"* CHANGED\";\r\n        private _fsw;\r\n        private _dispatcher;\r\n        private _disposed;\r\n        private _pending;\r\n        private _cache;\r\n        get includeSubdirectories(): boolean;\r\n        set includeSubdirectories(v: boolean);\r\n        get enableRaisingEvents(): boolean;\r\n        set enableRaisingEvents(v: boolean);\r\n        constructor(path: string, filter: string);\r\n        dispose(): void;\r\n        on(name: string, caller: any, fn: Function): void;\r\n        off(name: string, caller: any, fn: Function): void;\r\n        private oncreate;\r\n        private onchange;\r\n        private ondelete;\r\n        private setCacheState;\r\n        private dispatchEvents;\r\n    }\r\n}\r\ndeclare module \"plover/editor/js_console\" {\r\n    import { EditorWindow } from \"UnityEditor\";\r\n    export function fillAutoCompletion(scope: any, pattern: string): Array<string>;\r\n    export class JSConsole extends EditorWindow {\r\n        private _searchField;\r\n        private _history;\r\n        Awake(): void;\r\n        private onSearchChange;\r\n        private onSearchConfirm;\r\n        OnEnable(): void;\r\n        OnGUI(): void;\r\n    }\r\n}\r\ndeclare module \"plover/text/string_utils\" {\r\n    export let DefaultMatcher: RegExp;\r\n    export function TEXT(s: string): string;\r\n    /**\r\n     * 按一个上下文对象替换字符串中相应的关键字匹配串\r\n     */\r\n    export class Contextual {\r\n        private re;\r\n        private context;\r\n        constructor(re?: RegExp);\r\n        /**\r\n         * 绑定一个上下文对象 （通常是一个map）\r\n         */\r\n        bind(context: any): this;\r\n        /**\r\n         * 替换字符串匹配串 (可以传入上下文，否则使用绑定的)\r\n         * context 可以是一个支持嵌套数据的map, 也可以是一个处理函数.\r\n         * 当使用处理函数时, 参数为取值key字符串.\r\n         */\r\n        replace(text: string, context?: any): string;\r\n        /**\r\n         * let data = {\r\n         *     name: \"test\",\r\n         *     company: {\r\n         *         name: \"unity\",\r\n         *     },\r\n         * }\r\n         * let x = Contextual.replace(\"hello, mm: ${name} ${company.name}\", data)\r\n         * console.log(x);\r\n         */\r\n        static replace(text: string, context: any, re?: RegExp): string;\r\n    }\r\n    export class StringUtil {\r\n        /**\r\n         * 替换字符串中的字串\r\n         * @param oldString 原字符串\r\n         * @param matchString 匹配字串\r\n         * @param replaceString 替换字串\r\n         * @returns 替换后的字符串\r\n         */\r\n        static replaceAll(oldString: string, matchString: string, replaceString: string): string;\r\n        static contains(str: string, match: string): boolean;\r\n        /**\r\n         * 数字 => 前缀0固定长度字符串\r\n         */\r\n        static prefix(num: number | string, length: number): string;\r\n        /**\r\n         * 转换为固定小数和整数部分长度的字符串\r\n         */\r\n        static prefix2(num: number, length1: number, length2: number): string;\r\n        /**\r\n         * 简单字符串表示的时长 (mm:ss.mmm)\r\n         */\r\n        static time(deltaTime: number): string;\r\n    }\r\n}\r\ndeclare module \"plover/editor/base/menu_builder\" {\r\n    import { GenericMenu } from \"UnityEditor\";\r\n    export interface IMenuItem {\r\n        name: string;\r\n        build(menu: GenericMenu): any;\r\n    }\r\n    export abstract class MenuAbstractItem implements IMenuItem {\r\n        private _name;\r\n        get name(): string;\r\n        constructor(name: string);\r\n        abstract build(menu: GenericMenu): any;\r\n    }\r\n    export class MenuSeparator extends MenuAbstractItem {\r\n        build(menu: GenericMenu): void;\r\n    }\r\n    export class MenuAction extends MenuAbstractItem {\r\n        private _action;\r\n        get action(): Function;\r\n        constructor(name: string, action: Function);\r\n        build(menu: GenericMenu): void;\r\n    }\r\n    export class MenuDisabledAction extends MenuAbstractItem {\r\n        constructor(name: string);\r\n        build(menu: GenericMenu): void;\r\n    }\r\n    export class MenuBuilder {\r\n        private _items;\r\n        addAction(name: string, action: Function, isDisabled?: boolean): void;\r\n        addDisabledAction(name: string): void;\r\n        addSeperator(): void;\r\n        build(): GenericMenu;\r\n    }\r\n}\r\ndeclare module \"plover/editor/base/splitview\" {\r\n    import { EditorWindow } from \"UnityEditor\";\r\n    import { Color, Rect } from \"UnityEngine\";\r\n    export class HSplitView {\r\n        init: boolean;\r\n        splitPivot: number;\r\n        resize: boolean;\r\n        cursorChangeRect: Rect;\r\n        cursorHintRect: Rect;\r\n        cursorHintSize: number;\r\n        cursorSize: number;\r\n        cursorHintColor: Color;\r\n        draw(window: EditorWindow, startY: number, fullWidth: number, fullHeight: number): void;\r\n    }\r\n}\r\ndeclare module \"plover/editor/base/treeview\" {\r\n    import { ITreeNodeEventHandler, UTreeNode } from \"plover/editor/base/treenode\";\r\n    export class UTreeView {\r\n        static readonly CONTEXT_MENU = \"CONTEXT_MENU\";\r\n        readonly SKIP_RETURN = 0;\r\n        private _handler;\r\n        private _events;\r\n        private _eventUsed;\r\n        private _skipReturn;\r\n        private _root;\r\n        private _height;\r\n        private _drawY;\r\n        private _rowIndex;\r\n        private _indentSize;\r\n        private _controlRect;\r\n        private _controlID;\r\n        private _controlEventType;\r\n        private _controlMousePos;\r\n        private _rowRect;\r\n        private _indentRect;\r\n        private _tempRect;\r\n        private _selected;\r\n        private _editing;\r\n        private _deferredMenuPopup;\r\n        private _searchString;\r\n        private _selectionColor;\r\n        private _rowColor;\r\n        private _focusColor;\r\n        private _debug_touchChild;\r\n        private _debug_drawChild;\r\n        get selected(): UTreeNode;\r\n        set selected(value: UTreeNode);\r\n        get searchString(): string;\r\n        set searchString(value: string);\r\n        get root(): UTreeNode;\r\n        get handler(): ITreeNodeEventHandler;\r\n        set handler(value: ITreeNodeEventHandler);\r\n        constructor(handler: ITreeNodeEventHandler);\r\n        on(evt: string, caller: any, fn?: Function): void;\r\n        off(evt: string, caller: any, fn?: Function): void;\r\n        dispatch(name: string, arg0?: any, arg1?: any, arg2?: any): void;\r\n        allocFolderHierarchy(path: string, data: any): UTreeNode;\r\n        getFolderHierarchy(path: string): UTreeNode;\r\n        private _getFolderHierarchy;\r\n        removeAll(): void;\r\n        deleteNode(node: UTreeNode): boolean;\r\n        search(p: string): void;\r\n        private _search;\r\n        expandAll(): void;\r\n        collapseAll(): void;\r\n        draw(offsetX: number, offsetY: number, width: number, height: number): boolean;\r\n        private calcRowHeight;\r\n        private calcSearchResultsHeight;\r\n        private setControlRect;\r\n        private useEvent;\r\n        private drawSearchResults;\r\n        private drawRow;\r\n        findPreviousNode(node: UTreeNode): UTreeNode;\r\n        findNextNode(node: UTreeNode): UTreeNode;\r\n    }\r\n}\r\ndeclare module \"plover/editor/base/treenode\" {\r\n    import { GUIContent, Rect, Texture, Vector2 } from \"UnityEngine\";\r\n    import { EventDispatcher } from \"plover/events/dispatcher\";\r\n    import { MenuBuilder } from \"plover/editor/base/menu_builder\";\r\n    import { UTreeView } from \"plover/editor/base/treeview\";\r\n    export interface ITreeNodeEventHandler {\r\n        onTreeNodeContextMenu(node: UTreeNode, builder: MenuBuilder): any;\r\n        onTreeNodeCreated(node: UTreeNode): any;\r\n        onTreeNodeNameEditEnded(node: UTreeNode, newName: string): any;\r\n        onTreeNodeNameChanged(node: UTreeNode, oldName: string): any;\r\n    }\r\n    export class BuiltinIcons {\r\n        private static _cache;\r\n        static getIcon(name: string): Texture;\r\n    }\r\n    export class UTreeNode {\r\n        protected _tree: UTreeView;\r\n        protected _parent: UTreeNode;\r\n        protected _children: Array<UTreeNode>;\r\n        protected _expanded: boolean;\r\n        protected _name: string;\r\n        protected _events: EventDispatcher;\r\n        data: any;\r\n        isSearchable: boolean;\r\n        isEditable: boolean;\r\n        _foldoutRect: Rect;\r\n        protected _label: GUIContent;\r\n        protected _folderClose: Texture;\r\n        protected _folderOpen: Texture;\r\n        private _bFocusTextField;\r\n        private _bVisible;\r\n        private _height;\r\n        private _bMatch;\r\n        get isMatch(): boolean;\r\n        get height(): number;\r\n        /**\r\n         * 当前层级是否展开\r\n         */\r\n        get expanded(): boolean;\r\n        set expanded(value: boolean);\r\n        get isFolder(): boolean;\r\n        get visible(): boolean;\r\n        set visible(value: boolean);\r\n        get parent(): UTreeNode;\r\n        get isRoot(): boolean;\r\n        get name(): string;\r\n        set name(value: string);\r\n        get fullPath(): string;\r\n        get treeView(): UTreeView;\r\n        constructor(tree: UTreeView, parent: UTreeNode, isFolder: boolean, name: string);\r\n        get childCount(): number;\r\n        on(evt: string, caller: any, fn?: Function): void;\r\n        off(evt: string, caller: any, fn?: Function): void;\r\n        dispatch(name: string, arg0?: any, arg1?: any, arg2?: any): void;\r\n        match(p: string): boolean;\r\n        getRelativePath(top: UTreeNode): string;\r\n        expandAll(): void;\r\n        collapseAll(): void;\r\n        private _setExpandAll;\r\n        expandUp(): void;\r\n        /**\r\n         * 获取指定节点的在当前层级中的下一个相邻节点\r\n         */\r\n        findNextSibling(node: UTreeNode): UTreeNode;\r\n        /**\r\n         * 获取指定节点的在当前层级中的上一个相邻节点\r\n         */\r\n        findLastSibling(node: UTreeNode): UTreeNode;\r\n        forEachChild(fn: (child: UTreeNode) => void): void;\r\n        /**\r\n         * 获取当前层级下的子节点\r\n         * @param index 索引 或者 命名\r\n         * @param autoNew 不存在时是否创建 (仅通过命名获取时有效)\r\n         * @returns 子节点\r\n         */\r\n        getFolderByName(name: string, isAutoCreate: boolean, data: any): UTreeNode;\r\n        getLeafByName(name: string, isAutoCreate: boolean, data: any): UTreeNode;\r\n        getChildByIndex(index: number): UTreeNode;\r\n        /**\r\n         * 当前层级最后一个子节点\r\n         */\r\n        getLastChild(): UTreeNode;\r\n        /**\r\n         * 当前层级第一个子节点\r\n         */\r\n        getFirstChild(): UTreeNode;\r\n        addFolderChild(name: string): UTreeNode;\r\n        addLeafChild(name: string): UTreeNode;\r\n        allocLeafChild(name: string, data: any): UTreeNode;\r\n        /**\r\n         * 在当前层级添加一个子节点\r\n         */\r\n        private _addChild;\r\n        /**\r\n         * 将一个子节点从当前层级中移除\r\n         */\r\n        removeChild(node: UTreeNode): boolean;\r\n        removeAll(): void;\r\n        calcRowHeight(): number;\r\n        drawMenu(treeView: UTreeView, pos: Vector2, handler: ITreeNodeEventHandler): void;\r\n        draw(rect: Rect, bSelected: boolean, bEditing: boolean, indentSize: number): void;\r\n        endEdit(): void;\r\n    }\r\n}\r\ndeclare module \"plover/editor/base/breadcrumb\" {\r\n    import { UTreeNode } from \"plover/editor/base/treenode\";\r\n    import { EventDispatcher } from \"plover/events/dispatcher\";\r\n    export class Breadcrumb extends EventDispatcher {\r\n        static readonly CLICKED = \"CLICKED\";\r\n        private _height;\r\n        private _heightOptionSV;\r\n        private _heightOptionHB;\r\n        private _cache;\r\n        private _color;\r\n        private _sv;\r\n        get height(): number;\r\n        constructor();\r\n        draw(node: UTreeNode): void;\r\n    }\r\n}\r\ndeclare module \"plover/editor/base/editor_window_base\" {\r\n    import { EditorWindow } from \"UnityEditor\";\r\n    import { Event, GUIContent, Rect, Vector2 } from \"UnityEngine\";\r\n    import { MenuBuilder } from \"plover/editor/base/menu_builder\";\r\n    import { HSplitView } from \"plover/editor/base/splitview\";\r\n    import { ITreeNodeEventHandler, UTreeNode } from \"plover/editor/base/treenode\";\r\n    import { UTreeView } from \"plover/editor/base/treeview\";\r\n    import { Breadcrumb } from \"plover/editor/base/breadcrumb\";\r\n    export abstract class EditorWindowBase extends EditorWindow implements ITreeNodeEventHandler {\r\n        protected _treeView: UTreeView;\r\n        protected _breadcrumb: Breadcrumb;\r\n        protected _treeViewScroll: Vector2;\r\n        protected _hSplitView: HSplitView;\r\n        protected _toolbarRect: Rect;\r\n        protected _leftRect: Rect;\r\n        protected _rightRect: Rect;\r\n        protected _searchLabel: GUIContent;\r\n        protected _tempRect: Rect;\r\n        protected _event: Event;\r\n        protected _contents: {\r\n            [key: string]: GUIContent;\r\n        };\r\n        toobarHeight: number;\r\n        onTreeNodeNameEditEnded(node: UTreeNode, newName: string): void;\r\n        onTreeNodeNameChanged(node: UTreeNode, oldName: string): void;\r\n        onTreeNodeCreated(node: UTreeNode): void;\r\n        onTreeNodeContextMenu(node: UTreeNode, builder: MenuBuilder): void;\r\n        buildBreadcrumbMenu(top: UTreeNode, node: UTreeNode, builder: MenuBuilder): void;\r\n        onClickBreadcrumb(node: UTreeNode, isContext: boolean): void;\r\n        Awake(): void;\r\n        private drawLeftTreeView;\r\n        protected drawConfigView(data: any, node: UTreeNode): void;\r\n        protected drawFolderView(data: any, node: UTreeNode): void;\r\n        protected abstract drawToolBar(): any;\r\n        protected TRect(x: number, y: number, w: number, h: number): Rect;\r\n        protected TContent(name: string, icon: string, tooltip?: string, text?: string): GUIContent;\r\n        OnGUI(): void;\r\n    }\r\n}\r\ndeclare module \"plover/editor/js_reload\" {\r\n    export function reload(mod: NodeModule): void;\r\n}\r\ndeclare module \"plover/editor/js_module_view\" {\r\n    import { EditorWindowBase } from \"plover/editor/base/editor_window_base\";\r\n    import { UTreeNode } from \"plover/editor/base/treenode\";\r\n    export class JSModuleView extends EditorWindowBase {\r\n        private _touch;\r\n        Awake(): void;\r\n        OnEnable(): void;\r\n        protected drawFolderView(data: any, node: UTreeNode): void;\r\n        protected drawToolBar(): void;\r\n        private updateModules;\r\n        private getSimplifiedName;\r\n        private addModule;\r\n    }\r\n}\r\ndeclare module \"plover/editor/base/content_cache\" {\r\n    import { GUIContent, Texture } from \"UnityEngine\";\r\n    export class EdCache {\r\n        static cache: {\r\n            [key: string]: GUIContent;\r\n        };\r\n        static T(title: string, tooltip?: string, image?: Texture): GUIContent;\r\n    }\r\n}\r\ndeclare module \"plover/events/data_binding\" {\r\n    export abstract class Subscriber {\r\n        private _model;\r\n        private _key;\r\n        private _source;\r\n        constructor(model: DataBinding, key: string);\r\n        get value(): any;\r\n        set value(newValue: any);\r\n        protected update(value: any): void;\r\n        notify(value: any): void;\r\n        unsubscribe(): void;\r\n    }\r\n    export class Subscribers {\r\n        private _subs;\r\n        notify(valueProxy: any): void;\r\n        addSub(sub: Subscriber): void;\r\n        removeSub(sub: Subscriber): void;\r\n        transfer(newValue: Subscribers): void;\r\n    }\r\n    export class DataBinding {\r\n        private constructor();\r\n        addSubscriber(sub: Subscriber): void;\r\n        removeSubscriber(sub: Subscriber): void;\r\n        static bind<T>(data: T): T;\r\n        static subscribe<T extends Subscriber>(SubscriberType: {\r\n            new (model: DataBinding, key: string, ...args: any[]): T;\r\n        }, modelObject: any, path: string, ...args: any[]): T;\r\n    }\r\n}\r\ndeclare module \"plover/jsx/vue\" {\r\n    export interface IViewModelWatcher {\r\n        readonly value: string;\r\n        readonly dirty: boolean;\r\n        readonly expression: string;\r\n        readonly id: number;\r\n        cb: (value: any, oldValue: any) => void;\r\n        evaluate: () => void;\r\n        teardown: () => void;\r\n    }\r\n    export class ViewModel {\r\n        static create<T>(data: T): T;\r\n        constructor(data: any);\r\n        static $toString(v: any): String;\r\n        static flush(): void;\r\n        static expression(vm: any, expression: string, cb?: (value: any, oldValue: any) => void): IViewModelWatcher;\r\n        static field(vm: any, path: string, cb?: (value: any, oldValue: any) => void): IViewModelWatcher;\r\n    }\r\n}\r\ndeclare module \"plover/jsx/element\" {\r\n    import { Component, Transform } from \"UnityEngine\";\r\n    import { JSXWidgetBridge } from \"plover/jsx/bridge\";\r\n    export interface Activator<T = JSXNode> {\r\n        new (): T;\r\n    }\r\n    export abstract class JSXNode {\r\n        private _parent;\r\n        get parent(): JSXNode;\r\n        set parent(value: JSXNode);\r\n        get widget(): JSXWidget;\r\n        protected abstract onParentSet(): any;\r\n        abstract init(attributes: any, ...children: Array<JSXNode>): any;\r\n        abstract evaluate(): any;\r\n        abstract destroy(): any;\r\n    }\r\n    export function findUIComponent<T extends Component>(transform: Transform, name: string, type: {\r\n        new (): T;\r\n    }): T;\r\n    export function element(name: string): (target: any) => void;\r\n    export function createElement(name: string, attributes: any, ...children: Array<JSXNode>): JSXNode;\r\n    export function registerElement(name: string, activator: Activator): void;\r\n    export abstract class JSXCompoundNode extends JSXNode {\r\n        private _children;\r\n        init(attributes: any, ...children: Array<JSXNode>): void;\r\n        evaluate(): void;\r\n        destroy(): void;\r\n    }\r\n    export class JSXWidget extends JSXCompoundNode {\r\n        private _instance;\r\n        get instance(): JSXWidgetBridge;\r\n        get data(): any;\r\n        init(attributes: any, ...children: Array<JSXNode>): void;\r\n        protected onParentSet(): void;\r\n    }\r\n    export class JSXText extends JSXNode {\r\n        private _name;\r\n        private _text;\r\n        private _component;\r\n        private _watcher;\r\n        init(attributes: any, ...children: Array<JSXNode>): void;\r\n        protected onParentSet(): void;\r\n        private onValueChanged;\r\n        evaluate(): void;\r\n        destroy(): void;\r\n    }\r\n}\r\ndeclare module \"plover/jsx/bridge\" {\r\n    import { MonoBehaviour } from \"UnityEngine\";\r\n    import * as JSX from \"plover/jsx/element\";\r\n    export abstract class JSXWidgetBridge extends MonoBehaviour {\r\n        protected _widget: JSX.JSXWidget;\r\n        get data(): any;\r\n        OnDestroy(): void;\r\n    }\r\n}\r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Typings/plover.d.ts.meta",
    "content": "fileFormatVersion: 2\nguid: e203c7bf420d8cd47be8723a020189a6\nDefaultImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/Typings.meta",
    "content": "fileFormatVersion: 2\r\nguid: 808ddf5069ff3534880f27cc5c1c0906\r\nfolderAsset: yes\r\nDefaultImporter:\r\n  externalObjects: {}\r\n  userData: \r\n  assetBundleName: \r\n  assetBundleVariant: \r\n"
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/package.json",
    "content": "{\r\n    \"name\": \"cc.starlessnight.unity-jsb\",\r\n    \"version\": \"1.7.4\",\r\n    \"description\": \" It brings Javascript runtime capability to Unity3D by integrating QuickJS. It's highly integrated with Unity3D, and possible to implement MonoBehaviour/ScriptableObject/Editor/EditorWindow in typescript.\",\r\n    \"displayName\": \"unity-jsb\",\r\n    \"unity\": \"2018.4\",\r\n    \r\n    \"author\": {\r\n        \"name\": \"ialex32x\", \r\n        \"email\": \"lin_032@hotmail.com\"\r\n    },\r\n    \"keywords\": [\r\n        \"typescript\", \r\n        \"javascript\", \r\n        \"quickjs\"\r\n    ],\r\n\r\n    \"repository\": {\r\n      \"url\": \"https://github.com/ialex32x/unity-jsb.git\",\r\n      \"type\": \"git\"\r\n    }\r\n  }\r\n  "
  },
  {
    "path": "Packages/cc.starlessnight.unity-jsb/package.json.meta",
    "content": "fileFormatVersion: 2\nguid: 26054c1ac760b1043a549b3753c09425\nPackageManifestImporter:\n  externalObjects: {}\n  userData: \n  assetBundleName: \n  assetBundleVariant: \n"
  },
  {
    "path": "Packages/manifest.json",
    "content": "{\n  \"dependencies\": {\n    \"com.unity.ads\": \"2.0.8\",\n    \"com.unity.analytics\": \"3.3.2\",\n    \"com.unity.collab-proxy\": \"1.2.16\",\n    \"com.unity.package-manager-ui\": \"2.1.2\",\n    \"com.unity.purchasing\": \"2.0.6\",\n    \"com.unity.textmeshpro\": \"2.0.1\",\n    \"com.unity.timeline\": \"1.0.0\",\n    \"com.unity.modules.ai\": \"1.0.0\",\n    \"com.unity.modules.animation\": \"1.0.0\",\n    \"com.unity.modules.assetbundle\": \"1.0.0\",\n    \"com.unity.modules.audio\": \"1.0.0\",\n    \"com.unity.modules.cloth\": \"1.0.0\",\n    \"com.unity.modules.director\": \"1.0.0\",\n    \"com.unity.modules.imageconversion\": \"1.0.0\",\n    \"com.unity.modules.imgui\": \"1.0.0\",\n    \"com.unity.modules.jsonserialize\": \"1.0.0\",\n    \"com.unity.modules.particlesystem\": \"1.0.0\",\n    \"com.unity.modules.physics\": \"1.0.0\",\n    \"com.unity.modules.physics2d\": \"1.0.0\",\n    \"com.unity.modules.screencapture\": \"1.0.0\",\n    \"com.unity.modules.terrain\": \"1.0.0\",\n    \"com.unity.modules.terrainphysics\": \"1.0.0\",\n    \"com.unity.modules.tilemap\": \"1.0.0\",\n    \"com.unity.modules.ui\": \"1.0.0\",\n    \"com.unity.modules.uielements\": \"1.0.0\",\n    \"com.unity.modules.umbra\": \"1.0.0\",\n    \"com.unity.modules.unityanalytics\": \"1.0.0\",\n    \"com.unity.modules.unitywebrequest\": \"1.0.0\",\n    \"com.unity.modules.unitywebrequestassetbundle\": \"1.0.0\",\n    \"com.unity.modules.unitywebrequestaudio\": \"1.0.0\",\n    \"com.unity.modules.unitywebrequesttexture\": \"1.0.0\",\n    \"com.unity.modules.unitywebrequestwww\": \"1.0.0\",\n    \"com.unity.modules.vehicles\": \"1.0.0\",\n    \"com.unity.modules.video\": \"1.0.0\",\n    \"com.unity.modules.vr\": \"1.0.0\",\n    \"com.unity.modules.wind\": \"1.0.0\",\n    \"com.unity.modules.xr\": \"1.0.0\"\n  }\n}\n"
  },
  {
    "path": "ProjectSettings/AudioManager.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!11 &1\nAudioManager:\n  m_ObjectHideFlags: 0\n  serializedVersion: 2\n  m_Volume: 1\n  Rolloff Scale: 1\n  Doppler Factor: 1\n  Default Speaker Mode: 2\n  m_SampleRate: 0\n  m_DSPBufferSize: 1024\n  m_VirtualVoiceCount: 512\n  m_RealVoiceCount: 32\n  m_SpatializerPlugin: \n  m_AmbisonicDecoderPlugin: \n  m_DisableAudio: 0\n  m_VirtualizeEffects: 1\n  m_RequestedDSPBufferSize: 1024\n"
  },
  {
    "path": "ProjectSettings/ClusterInputManager.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!236 &1\nClusterInputManager:\n  m_ObjectHideFlags: 0\n  m_Inputs: []\n"
  },
  {
    "path": "ProjectSettings/DynamicsManager.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!55 &1\nPhysicsManager:\n  m_ObjectHideFlags: 0\n  serializedVersion: 11\n  m_Gravity: {x: 0, y: -9.81, z: 0}\n  m_DefaultMaterial: {fileID: 0}\n  m_BounceThreshold: 2\n  m_SleepThreshold: 0.005\n  m_DefaultContactOffset: 0.01\n  m_DefaultSolverIterations: 6\n  m_DefaultSolverVelocityIterations: 1\n  m_QueriesHitBackfaces: 0\n  m_QueriesHitTriggers: 1\n  m_EnableAdaptiveForce: 0\n  m_ClothInterCollisionDistance: 0\n  m_ClothInterCollisionStiffness: 0\n  m_ContactsGeneration: 1\n  m_LayerCollisionMatrix: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\n  m_AutoSimulation: 1\n  m_AutoSyncTransforms: 0\n  m_ReuseCollisionCallbacks: 1\n  m_ClothInterCollisionSettingsToggle: 0\n  m_ContactPairsMode: 0\n  m_BroadphaseType: 0\n  m_WorldBounds:\n    m_Center: {x: 0, y: 0, z: 0}\n    m_Extent: {x: 250, y: 250, z: 250}\n  m_WorldSubdivisions: 8\n  m_FrictionType: 0\n  m_EnableEnhancedDeterminism: 0\n  m_EnableUnifiedHeightmaps: 1\n  m_DefaultMaxAngluarSpeed: 7\n"
  },
  {
    "path": "ProjectSettings/EditorBuildSettings.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1045 &1\nEditorBuildSettings:\n  m_ObjectHideFlags: 0\n  serializedVersion: 2\n  m_Scenes:\n  - enabled: 1\n    path: Assets/Examples/Scenes/SampleScene.unity\n    guid: 9fc0d4010bbf28b4594072e72b8655ab\n  m_configObjects: {}\n"
  },
  {
    "path": "ProjectSettings/EditorSettings.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!159 &1\nEditorSettings:\n  m_ObjectHideFlags: 0\n  serializedVersion: 7\n  m_ExternalVersionControlSupport: Visible Meta Files\n  m_SerializationMode: 2\n  m_LineEndingsForNewScripts: 2\n  m_DefaultBehaviorMode: 0\n  m_PrefabRegularEnvironment: {fileID: 0}\n  m_PrefabUIEnvironment: {fileID: 0}\n  m_SpritePackerMode: 4\n  m_SpritePackerPaddingPower: 1\n  m_EtcTextureCompressorBehavior: 1\n  m_EtcTextureFastCompressor: 1\n  m_EtcTextureNormalCompressor: 2\n  m_EtcTextureBestCompressor: 4\n  m_ProjectGenerationIncludedExtensions: txt;xml;fnt;cd;asmdef;rsp\n  m_ProjectGenerationRootNamespace: \n  m_CollabEditorSettings:\n    inProgressEnabled: 1\n  m_EnableTextureStreamingInEditMode: 1\n  m_EnableTextureStreamingInPlayMode: 1\n  m_AsyncShaderCompilation: 1\n"
  },
  {
    "path": "ProjectSettings/GraphicsSettings.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!30 &1\nGraphicsSettings:\n  m_ObjectHideFlags: 0\n  serializedVersion: 12\n  m_Deferred:\n    m_Mode: 1\n    m_Shader: {fileID: 69, guid: 0000000000000000f000000000000000, type: 0}\n  m_DeferredReflections:\n    m_Mode: 1\n    m_Shader: {fileID: 74, guid: 0000000000000000f000000000000000, type: 0}\n  m_ScreenSpaceShadows:\n    m_Mode: 1\n    m_Shader: {fileID: 64, guid: 0000000000000000f000000000000000, type: 0}\n  m_LegacyDeferred:\n    m_Mode: 1\n    m_Shader: {fileID: 63, guid: 0000000000000000f000000000000000, type: 0}\n  m_DepthNormals:\n    m_Mode: 1\n    m_Shader: {fileID: 62, guid: 0000000000000000f000000000000000, type: 0}\n  m_MotionVectors:\n    m_Mode: 1\n    m_Shader: {fileID: 75, guid: 0000000000000000f000000000000000, type: 0}\n  m_LightHalo:\n    m_Mode: 1\n    m_Shader: {fileID: 105, guid: 0000000000000000f000000000000000, type: 0}\n  m_LensFlare:\n    m_Mode: 1\n    m_Shader: {fileID: 102, guid: 0000000000000000f000000000000000, type: 0}\n  m_AlwaysIncludedShaders:\n  - {fileID: 7, guid: 0000000000000000f000000000000000, type: 0}\n  - {fileID: 15104, guid: 0000000000000000f000000000000000, type: 0}\n  - {fileID: 15105, guid: 0000000000000000f000000000000000, type: 0}\n  - {fileID: 15106, guid: 0000000000000000f000000000000000, type: 0}\n  - {fileID: 10753, guid: 0000000000000000f000000000000000, type: 0}\n  - {fileID: 10770, guid: 0000000000000000f000000000000000, type: 0}\n  m_PreloadedShaders: []\n  m_SpritesDefaultMaterial: {fileID: 10754, guid: 0000000000000000f000000000000000,\n    type: 0}\n  m_CustomRenderPipeline: {fileID: 0}\n  m_TransparencySortMode: 0\n  m_TransparencySortAxis: {x: 0, y: 0, z: 1}\n  m_DefaultRenderingPath: 1\n  m_DefaultMobileRenderingPath: 1\n  m_TierSettings: []\n  m_LightmapStripping: 0\n  m_FogStripping: 0\n  m_InstancingStripping: 0\n  m_LightmapKeepPlain: 1\n  m_LightmapKeepDirCombined: 1\n  m_LightmapKeepDynamicPlain: 1\n  m_LightmapKeepDynamicDirCombined: 1\n  m_LightmapKeepShadowMask: 1\n  m_LightmapKeepSubtractive: 1\n  m_FogKeepLinear: 1\n  m_FogKeepExp: 1\n  m_FogKeepExp2: 1\n  m_AlbedoSwatchInfos: []\n  m_LightsUseLinearIntensity: 0\n  m_LightsUseColorTemperature: 0\n"
  },
  {
    "path": "ProjectSettings/InputManager.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!13 &1\nInputManager:\n  m_ObjectHideFlags: 0\n  serializedVersion: 2\n  m_Axes:\n  - serializedVersion: 3\n    m_Name: Horizontal\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: left\n    positiveButton: right\n    altNegativeButton: a\n    altPositiveButton: d\n    gravity: 3\n    dead: 0.001\n    sensitivity: 3\n    snap: 1\n    invert: 0\n    type: 0\n    axis: 0\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Vertical\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: down\n    positiveButton: up\n    altNegativeButton: s\n    altPositiveButton: w\n    gravity: 3\n    dead: 0.001\n    sensitivity: 3\n    snap: 1\n    invert: 0\n    type: 0\n    axis: 0\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Fire1\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: \n    positiveButton: left ctrl\n    altNegativeButton: \n    altPositiveButton: mouse 0\n    gravity: 1000\n    dead: 0.001\n    sensitivity: 1000\n    snap: 0\n    invert: 0\n    type: 0\n    axis: 0\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Fire2\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: \n    positiveButton: left alt\n    altNegativeButton: \n    altPositiveButton: mouse 1\n    gravity: 1000\n    dead: 0.001\n    sensitivity: 1000\n    snap: 0\n    invert: 0\n    type: 0\n    axis: 0\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Fire3\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: \n    positiveButton: left shift\n    altNegativeButton: \n    altPositiveButton: mouse 2\n    gravity: 1000\n    dead: 0.001\n    sensitivity: 1000\n    snap: 0\n    invert: 0\n    type: 0\n    axis: 0\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Jump\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: \n    positiveButton: space\n    altNegativeButton: \n    altPositiveButton: \n    gravity: 1000\n    dead: 0.001\n    sensitivity: 1000\n    snap: 0\n    invert: 0\n    type: 0\n    axis: 0\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Mouse X\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: \n    positiveButton: \n    altNegativeButton: \n    altPositiveButton: \n    gravity: 0\n    dead: 0\n    sensitivity: 0.1\n    snap: 0\n    invert: 0\n    type: 1\n    axis: 0\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Mouse Y\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: \n    positiveButton: \n    altNegativeButton: \n    altPositiveButton: \n    gravity: 0\n    dead: 0\n    sensitivity: 0.1\n    snap: 0\n    invert: 0\n    type: 1\n    axis: 1\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Mouse ScrollWheel\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: \n    positiveButton: \n    altNegativeButton: \n    altPositiveButton: \n    gravity: 0\n    dead: 0\n    sensitivity: 0.1\n    snap: 0\n    invert: 0\n    type: 1\n    axis: 2\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Horizontal\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: \n    positiveButton: \n    altNegativeButton: \n    altPositiveButton: \n    gravity: 0\n    dead: 0.19\n    sensitivity: 1\n    snap: 0\n    invert: 0\n    type: 2\n    axis: 0\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Vertical\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: \n    positiveButton: \n    altNegativeButton: \n    altPositiveButton: \n    gravity: 0\n    dead: 0.19\n    sensitivity: 1\n    snap: 0\n    invert: 1\n    type: 2\n    axis: 1\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Fire1\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: \n    positiveButton: joystick button 0\n    altNegativeButton: \n    altPositiveButton: \n    gravity: 1000\n    dead: 0.001\n    sensitivity: 1000\n    snap: 0\n    invert: 0\n    type: 0\n    axis: 0\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Fire2\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: \n    positiveButton: joystick button 1\n    altNegativeButton: \n    altPositiveButton: \n    gravity: 1000\n    dead: 0.001\n    sensitivity: 1000\n    snap: 0\n    invert: 0\n    type: 0\n    axis: 0\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Fire3\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: \n    positiveButton: joystick button 2\n    altNegativeButton: \n    altPositiveButton: \n    gravity: 1000\n    dead: 0.001\n    sensitivity: 1000\n    snap: 0\n    invert: 0\n    type: 0\n    axis: 0\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Jump\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: \n    positiveButton: joystick button 3\n    altNegativeButton: \n    altPositiveButton: \n    gravity: 1000\n    dead: 0.001\n    sensitivity: 1000\n    snap: 0\n    invert: 0\n    type: 0\n    axis: 0\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Submit\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: \n    positiveButton: return\n    altNegativeButton: \n    altPositiveButton: joystick button 0\n    gravity: 1000\n    dead: 0.001\n    sensitivity: 1000\n    snap: 0\n    invert: 0\n    type: 0\n    axis: 0\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Submit\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: \n    positiveButton: enter\n    altNegativeButton: \n    altPositiveButton: space\n    gravity: 1000\n    dead: 0.001\n    sensitivity: 1000\n    snap: 0\n    invert: 0\n    type: 0\n    axis: 0\n    joyNum: 0\n  - serializedVersion: 3\n    m_Name: Cancel\n    descriptiveName: \n    descriptiveNegativeName: \n    negativeButton: \n    positiveButton: escape\n    altNegativeButton: \n    altPositiveButton: joystick button 1\n    gravity: 1000\n    dead: 0.001\n    sensitivity: 1000\n    snap: 0\n    invert: 0\n    type: 0\n    axis: 0\n    joyNum: 0\n"
  },
  {
    "path": "ProjectSettings/NavMeshAreas.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!126 &1\nNavMeshProjectSettings:\n  m_ObjectHideFlags: 0\n  serializedVersion: 2\n  areas:\n  - name: Walkable\n    cost: 1\n  - name: Not Walkable\n    cost: 1\n  - name: Jump\n    cost: 2\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  - name: \n    cost: 1\n  m_LastAgentTypeID: -887442657\n  m_Settings:\n  - serializedVersion: 2\n    agentTypeID: 0\n    agentRadius: 0.5\n    agentHeight: 2\n    agentSlope: 45\n    agentClimb: 0.75\n    ledgeDropHeight: 0\n    maxJumpAcrossDistance: 0\n    minRegionArea: 2\n    manualCellSize: 0\n    cellSize: 0.16666667\n    manualTileSize: 0\n    tileSize: 256\n    accuratePlacement: 0\n    debug:\n      m_Flags: 0\n  m_SettingNames:\n  - Humanoid\n"
  },
  {
    "path": "ProjectSettings/Physics2DSettings.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!19 &1\nPhysics2DSettings:\n  m_ObjectHideFlags: 0\n  serializedVersion: 4\n  m_Gravity: {x: 0, y: -9.81}\n  m_DefaultMaterial: {fileID: 0}\n  m_VelocityIterations: 8\n  m_PositionIterations: 3\n  m_VelocityThreshold: 1\n  m_MaxLinearCorrection: 0.2\n  m_MaxAngularCorrection: 8\n  m_MaxTranslationSpeed: 100\n  m_MaxRotationSpeed: 360\n  m_BaumgarteScale: 0.2\n  m_BaumgarteTimeOfImpactScale: 0.75\n  m_TimeToSleep: 0.5\n  m_LinearSleepTolerance: 0.01\n  m_AngularSleepTolerance: 2\n  m_DefaultContactOffset: 0.01\n  m_JobOptions:\n    serializedVersion: 2\n    useMultithreading: 0\n    useConsistencySorting: 0\n    m_InterpolationPosesPerJob: 100\n    m_NewContactsPerJob: 30\n    m_CollideContactsPerJob: 100\n    m_ClearFlagsPerJob: 200\n    m_ClearBodyForcesPerJob: 200\n    m_SyncDiscreteFixturesPerJob: 50\n    m_SyncContinuousFixturesPerJob: 50\n    m_FindNearestContactsPerJob: 100\n    m_UpdateTriggerContactsPerJob: 100\n    m_IslandSolverCostThreshold: 100\n    m_IslandSolverBodyCostScale: 1\n    m_IslandSolverContactCostScale: 10\n    m_IslandSolverJointCostScale: 10\n    m_IslandSolverBodiesPerJob: 50\n    m_IslandSolverContactsPerJob: 50\n  m_AutoSimulation: 1\n  m_QueriesHitTriggers: 1\n  m_QueriesStartInColliders: 1\n  m_CallbacksOnDisable: 1\n  m_ReuseCollisionCallbacks: 1\n  m_AutoSyncTransforms: 0\n  m_AlwaysShowColliders: 0\n  m_ShowColliderSleep: 1\n  m_ShowColliderContacts: 0\n  m_ShowColliderAABB: 0\n  m_ContactArrowScale: 0.2\n  m_ColliderAwakeColor: {r: 0.5686275, g: 0.95686275, b: 0.54509807, a: 0.7529412}\n  m_ColliderAsleepColor: {r: 0.5686275, g: 0.95686275, b: 0.54509807, a: 0.36078432}\n  m_ColliderContactColor: {r: 1, g: 0, b: 1, a: 0.6862745}\n  m_ColliderAABBColor: {r: 1, g: 1, b: 0, a: 0.2509804}\n  m_LayerCollisionMatrix: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\n"
  },
  {
    "path": "ProjectSettings/PresetManager.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1386491679 &1\nPresetManager:\n  m_ObjectHideFlags: 0\n  m_DefaultList: []\n"
  },
  {
    "path": "ProjectSettings/ProjectSettings.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!129 &1\nPlayerSettings:\n  m_ObjectHideFlags: 0\n  serializedVersion: 16\n  productGUID: 9fa792e7cc331954cb61febcd8472968\n  AndroidProfiler: 0\n  AndroidFilterTouchesWhenObscured: 0\n  AndroidEnableSustainedPerformanceMode: 0\n  defaultScreenOrientation: 4\n  targetDevice: 2\n  useOnDemandResources: 0\n  accelerometerFrequency: 60\n  companyName: ialex32x\n  productName: unity-jsb\n  defaultCursor: {fileID: 0}\n  cursorHotspot: {x: 0, y: 0}\n  m_SplashScreenBackgroundColor: {r: 0.13725491, g: 0.12156863, b: 0.1254902, a: 1}\n  m_ShowUnitySplashScreen: 1\n  m_ShowUnitySplashLogo: 1\n  m_SplashScreenOverlayOpacity: 1\n  m_SplashScreenAnimation: 1\n  m_SplashScreenLogoStyle: 1\n  m_SplashScreenDrawMode: 0\n  m_SplashScreenBackgroundAnimationZoom: 1\n  m_SplashScreenLogoAnimationZoom: 1\n  m_SplashScreenBackgroundLandscapeAspect: 1\n  m_SplashScreenBackgroundPortraitAspect: 1\n  m_SplashScreenBackgroundLandscapeUvs:\n    serializedVersion: 2\n    x: 0\n    y: 0\n    width: 1\n    height: 1\n  m_SplashScreenBackgroundPortraitUvs:\n    serializedVersion: 2\n    x: 0\n    y: 0\n    width: 1\n    height: 1\n  m_SplashScreenLogos: []\n  m_VirtualRealitySplashScreen: {fileID: 0}\n  m_HolographicTrackingLossScreen: {fileID: 0}\n  defaultScreenWidth: 1024\n  defaultScreenHeight: 768\n  defaultScreenWidthWeb: 960\n  defaultScreenHeightWeb: 600\n  m_StereoRenderingPath: 0\n  m_ActiveColorSpace: 0\n  m_MTRendering: 1\n  m_StackTraceTypes: 010000000100000001000000010000000100000001000000\n  iosShowActivityIndicatorOnLoading: -1\n  androidShowActivityIndicatorOnLoading: -1\n  iosAppInBackgroundBehavior: 0\n  displayResolutionDialog: 0\n  iosAllowHTTPDownload: 1\n  allowedAutorotateToPortrait: 1\n  allowedAutorotateToPortraitUpsideDown: 1\n  allowedAutorotateToLandscapeRight: 1\n  allowedAutorotateToLandscapeLeft: 1\n  useOSAutorotation: 1\n  use32BitDisplayBuffer: 1\n  preserveFramebufferAlpha: 0\n  disableDepthAndStencilBuffers: 0\n  androidStartInFullscreen: 1\n  androidRenderOutsideSafeArea: 1\n  androidBlitType: 0\n  defaultIsNativeResolution: 1\n  macRetinaSupport: 1\n  runInBackground: 1\n  captureSingleScreen: 0\n  muteOtherAudioSources: 0\n  Prepare IOS For Recording: 0\n  Force IOS Speakers When Recording: 0\n  deferSystemGesturesMode: 0\n  hideHomeButton: 0\n  submitAnalytics: 1\n  usePlayerLog: 1\n  bakeCollisionMeshes: 0\n  forceSingleInstance: 0\n  useFlipModelSwapchain: 1\n  resizableWindow: 0\n  useMacAppStoreValidation: 0\n  macAppStoreCategory: public.app-category.games\n  gpuSkinning: 1\n  graphicsJobs: 0\n  xboxPIXTextureCapture: 0\n  xboxEnableAvatar: 0\n  xboxEnableKinect: 0\n  xboxEnableKinectAutoTracking: 0\n  xboxEnableFitness: 0\n  visibleInBackground: 1\n  allowFullscreenSwitch: 1\n  graphicsJobMode: 0\n  fullscreenMode: 1\n  xboxSpeechDB: 0\n  xboxEnableHeadOrientation: 0\n  xboxEnableGuest: 0\n  xboxEnablePIXSampling: 0\n  metalFramebufferOnly: 0\n  xboxOneResolution: 0\n  xboxOneSResolution: 0\n  xboxOneXResolution: 3\n  xboxOneMonoLoggingLevel: 0\n  xboxOneLoggingLevel: 1\n  xboxOneDisableEsram: 0\n  xboxOnePresentImmediateThreshold: 0\n  switchQueueCommandMemory: 0\n  switchQueueControlMemory: 16384\n  switchQueueComputeMemory: 262144\n  switchNVNShaderPoolsGranularity: 33554432\n  switchNVNDefaultPoolsGranularity: 16777216\n  switchNVNOtherPoolsGranularity: 16777216\n  vulkanEnableSetSRGBWrite: 0\n  m_SupportedAspectRatios:\n    4:3: 1\n    5:4: 1\n    16:10: 1\n    16:9: 1\n    Others: 1\n  bundleVersion: 0.1\n  preloadedAssets: []\n  metroInputSource: 0\n  wsaTransparentSwapchain: 0\n  m_HolographicPauseOnTrackingLoss: 1\n  xboxOneDisableKinectGpuReservation: 1\n  xboxOneEnable7thCore: 1\n  vrSettings:\n    cardboard:\n      depthFormat: 0\n      enableTransitionView: 0\n    daydream:\n      depthFormat: 0\n      useSustainedPerformanceMode: 0\n      enableVideoLayer: 0\n      useProtectedVideoMemory: 0\n      minimumSupportedHeadTracking: 0\n      maximumSupportedHeadTracking: 1\n    hololens:\n      depthFormat: 1\n      depthBufferSharingEnabled: 1\n    lumin:\n      depthFormat: 0\n      frameTiming: 2\n      enableGLCache: 0\n      glCacheMaxBlobSize: 524288\n      glCacheMaxFileSize: 8388608\n    oculus:\n      sharedDepthBuffer: 1\n      dashSupport: 1\n    enable360StereoCapture: 0\n  isWsaHolographicRemotingEnabled: 0\n  protectGraphicsMemory: 0\n  enableFrameTimingStats: 0\n  useHDRDisplay: 0\n  m_ColorGamuts: 00000000\n  targetPixelDensity: 30\n  resolutionScalingMode: 0\n  androidSupportedAspectRatio: 1\n  androidMaxAspectRatio: 2.1\n  applicationIdentifier:\n    Android: com.ialex32x.jsb\n  buildNumber: {}\n  AndroidBundleVersionCode: 1\n  AndroidMinSdkVersion: 16\n  AndroidTargetSdkVersion: 0\n  AndroidPreferredInstallLocation: 1\n  aotOptions: \n  stripEngineCode: 1\n  iPhoneStrippingLevel: 0\n  iPhoneScriptCallOptimization: 0\n  ForceInternetPermission: 0\n  ForceSDCardPermission: 0\n  CreateWallpaper: 0\n  APKExpansionFiles: 0\n  keepLoadedShadersAlive: 0\n  StripUnusedMeshComponents: 1\n  VertexChannelCompressionMask: 4054\n  iPhoneSdkVersion: 988\n  iOSTargetOSVersionString: 9.0\n  tvOSSdkVersion: 0\n  tvOSRequireExtendedGameController: 0\n  tvOSTargetOSVersionString: 9.0\n  uIPrerenderedIcon: 0\n  uIRequiresPersistentWiFi: 0\n  uIRequiresFullScreen: 1\n  uIStatusBarHidden: 1\n  uIExitOnSuspend: 0\n  uIStatusBarStyle: 0\n  iPhoneSplashScreen: {fileID: 0}\n  iPhoneHighResSplashScreen: {fileID: 0}\n  iPhoneTallHighResSplashScreen: {fileID: 0}\n  iPhone47inSplashScreen: {fileID: 0}\n  iPhone55inPortraitSplashScreen: {fileID: 0}\n  iPhone55inLandscapeSplashScreen: {fileID: 0}\n  iPhone58inPortraitSplashScreen: {fileID: 0}\n  iPhone58inLandscapeSplashScreen: {fileID: 0}\n  iPadPortraitSplashScreen: {fileID: 0}\n  iPadHighResPortraitSplashScreen: {fileID: 0}\n  iPadLandscapeSplashScreen: {fileID: 0}\n  iPadHighResLandscapeSplashScreen: {fileID: 0}\n  iPhone65inPortraitSplashScreen: {fileID: 0}\n  iPhone65inLandscapeSplashScreen: {fileID: 0}\n  iPhone61inPortraitSplashScreen: {fileID: 0}\n  iPhone61inLandscapeSplashScreen: {fileID: 0}\n  appleTVSplashScreen: {fileID: 0}\n  appleTVSplashScreen2x: {fileID: 0}\n  tvOSSmallIconLayers: []\n  tvOSSmallIconLayers2x: []\n  tvOSLargeIconLayers: []\n  tvOSLargeIconLayers2x: []\n  tvOSTopShelfImageLayers: []\n  tvOSTopShelfImageLayers2x: []\n  tvOSTopShelfImageWideLayers: []\n  tvOSTopShelfImageWideLayers2x: []\n  iOSLaunchScreenType: 0\n  iOSLaunchScreenPortrait: {fileID: 0}\n  iOSLaunchScreenLandscape: {fileID: 0}\n  iOSLaunchScreenBackgroundColor:\n    serializedVersion: 2\n    rgba: 0\n  iOSLaunchScreenFillPct: 100\n  iOSLaunchScreenSize: 100\n  iOSLaunchScreenCustomXibPath: \n  iOSLaunchScreeniPadType: 0\n  iOSLaunchScreeniPadImage: {fileID: 0}\n  iOSLaunchScreeniPadBackgroundColor:\n    serializedVersion: 2\n    rgba: 0\n  iOSLaunchScreeniPadFillPct: 100\n  iOSLaunchScreeniPadSize: 100\n  iOSLaunchScreeniPadCustomXibPath: \n  iOSUseLaunchScreenStoryboard: 0\n  iOSLaunchScreenCustomStoryboardPath: \n  iOSDeviceRequirements: []\n  iOSURLSchemes: []\n  iOSBackgroundModes: 0\n  iOSMetalForceHardShadows: 0\n  metalEditorSupport: 1\n  metalAPIValidation: 1\n  iOSRenderExtraFrameOnPause: 0\n  appleDeveloperTeamID: \n  iOSManualSigningProvisioningProfileID: \n  tvOSManualSigningProvisioningProfileID: \n  iOSManualSigningProvisioningProfileType: 0\n  tvOSManualSigningProvisioningProfileType: 0\n  appleEnableAutomaticSigning: 0\n  iOSRequireARKit: 0\n  iOSAutomaticallyDetectAndAddCapabilities: 1\n  appleEnableProMotion: 0\n  clonedFromGUID: c0afd0d1d80e3634a9dac47e8a0426ea\n  templatePackageId: com.unity.template.3d@2.3.3\n  templateDefaultScene: Assets/Scenes/SampleScene.unity\n  AndroidTargetArchitectures: 1\n  AndroidSplashScreenScale: 0\n  androidSplashScreen: {fileID: 0}\n  AndroidKeystoreName: '{inproject}: '\n  AndroidKeyaliasName: \n  AndroidBuildApkPerCpuArchitecture: 0\n  AndroidTVCompatibility: 0\n  AndroidIsGame: 1\n  AndroidEnableTango: 0\n  androidEnableBanner: 1\n  androidUseLowAccuracyLocation: 0\n  androidUseCustomKeystore: 0\n  m_AndroidBanners:\n  - width: 320\n    height: 180\n    banner: {fileID: 0}\n  androidGamepadSupportLevel: 0\n  resolutionDialogBanner: {fileID: 0}\n  m_BuildTargetIcons: []\n  m_BuildTargetPlatformIcons:\n  - m_BuildTarget: Android\n    m_Icons:\n    - m_Textures: []\n      m_Width: 432\n      m_Height: 432\n      m_Kind: 2\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 324\n      m_Height: 324\n      m_Kind: 2\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 216\n      m_Height: 216\n      m_Kind: 2\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 162\n      m_Height: 162\n      m_Kind: 2\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 108\n      m_Height: 108\n      m_Kind: 2\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 81\n      m_Height: 81\n      m_Kind: 2\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 192\n      m_Height: 192\n      m_Kind: 0\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 144\n      m_Height: 144\n      m_Kind: 0\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 96\n      m_Height: 96\n      m_Kind: 0\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 72\n      m_Height: 72\n      m_Kind: 0\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 48\n      m_Height: 48\n      m_Kind: 0\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 36\n      m_Height: 36\n      m_Kind: 0\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 192\n      m_Height: 192\n      m_Kind: 1\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 144\n      m_Height: 144\n      m_Kind: 1\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 96\n      m_Height: 96\n      m_Kind: 1\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 72\n      m_Height: 72\n      m_Kind: 1\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 48\n      m_Height: 48\n      m_Kind: 1\n      m_SubKind: \n    - m_Textures: []\n      m_Width: 36\n      m_Height: 36\n      m_Kind: 1\n      m_SubKind: \n  m_BuildTargetBatching:\n  - m_BuildTarget: Standalone\n    m_StaticBatching: 1\n    m_DynamicBatching: 0\n  - m_BuildTarget: tvOS\n    m_StaticBatching: 1\n    m_DynamicBatching: 0\n  - m_BuildTarget: Android\n    m_StaticBatching: 1\n    m_DynamicBatching: 0\n  - m_BuildTarget: iPhone\n    m_StaticBatching: 1\n    m_DynamicBatching: 0\n  - m_BuildTarget: WebGL\n    m_StaticBatching: 0\n    m_DynamicBatching: 0\n  m_BuildTargetGraphicsAPIs:\n  - m_BuildTarget: AndroidPlayer\n    m_APIs: 150000000b000000\n    m_Automatic: 0\n  - m_BuildTarget: iOSSupport\n    m_APIs: 10000000\n    m_Automatic: 1\n  - m_BuildTarget: AppleTVSupport\n    m_APIs: 10000000\n    m_Automatic: 0\n  - m_BuildTarget: WebGLSupport\n    m_APIs: 0b000000\n    m_Automatic: 1\n  m_BuildTargetVRSettings:\n  - m_BuildTarget: Standalone\n    m_Enabled: 0\n    m_Devices:\n    - Oculus\n    - OpenVR\n  m_BuildTargetEnableVuforiaSettings: []\n  openGLRequireES31: 0\n  openGLRequireES31AEP: 0\n  openGLRequireES32: 0\n  m_TemplateCustomTags: {}\n  mobileMTRendering:\n    Android: 1\n    iPhone: 1\n    tvOS: 1\n  m_BuildTargetGroupLightmapEncodingQuality: []\n  m_BuildTargetGroupLightmapSettings: []\n  playModeTestRunnerEnabled: 0\n  runPlayModeTestAsEditModeTest: 0\n  actionOnDotNetUnhandledException: 1\n  enableInternalProfiler: 0\n  logObjCUncaughtExceptions: 1\n  enableCrashReportAPI: 0\n  cameraUsageDescription: \n  locationUsageDescription: \n  microphoneUsageDescription: \n  switchNetLibKey: \n  switchSocketMemoryPoolSize: 6144\n  switchSocketAllocatorPoolSize: 128\n  switchSocketConcurrencyLimit: 14\n  switchScreenResolutionBehavior: 2\n  switchUseCPUProfiler: 0\n  switchApplicationID: 0x01004b9000490000\n  switchNSODependencies: \n  switchTitleNames_0: \n  switchTitleNames_1: \n  switchTitleNames_2: \n  switchTitleNames_3: \n  switchTitleNames_4: \n  switchTitleNames_5: \n  switchTitleNames_6: \n  switchTitleNames_7: \n  switchTitleNames_8: \n  switchTitleNames_9: \n  switchTitleNames_10: \n  switchTitleNames_11: \n  switchTitleNames_12: \n  switchTitleNames_13: \n  switchTitleNames_14: \n  switchPublisherNames_0: \n  switchPublisherNames_1: \n  switchPublisherNames_2: \n  switchPublisherNames_3: \n  switchPublisherNames_4: \n  switchPublisherNames_5: \n  switchPublisherNames_6: \n  switchPublisherNames_7: \n  switchPublisherNames_8: \n  switchPublisherNames_9: \n  switchPublisherNames_10: \n  switchPublisherNames_11: \n  switchPublisherNames_12: \n  switchPublisherNames_13: \n  switchPublisherNames_14: \n  switchIcons_0: {fileID: 0}\n  switchIcons_1: {fileID: 0}\n  switchIcons_2: {fileID: 0}\n  switchIcons_3: {fileID: 0}\n  switchIcons_4: {fileID: 0}\n  switchIcons_5: {fileID: 0}\n  switchIcons_6: {fileID: 0}\n  switchIcons_7: {fileID: 0}\n  switchIcons_8: {fileID: 0}\n  switchIcons_9: {fileID: 0}\n  switchIcons_10: {fileID: 0}\n  switchIcons_11: {fileID: 0}\n  switchIcons_12: {fileID: 0}\n  switchIcons_13: {fileID: 0}\n  switchIcons_14: {fileID: 0}\n  switchSmallIcons_0: {fileID: 0}\n  switchSmallIcons_1: {fileID: 0}\n  switchSmallIcons_2: {fileID: 0}\n  switchSmallIcons_3: {fileID: 0}\n  switchSmallIcons_4: {fileID: 0}\n  switchSmallIcons_5: {fileID: 0}\n  switchSmallIcons_6: {fileID: 0}\n  switchSmallIcons_7: {fileID: 0}\n  switchSmallIcons_8: {fileID: 0}\n  switchSmallIcons_9: {fileID: 0}\n  switchSmallIcons_10: {fileID: 0}\n  switchSmallIcons_11: {fileID: 0}\n  switchSmallIcons_12: {fileID: 0}\n  switchSmallIcons_13: {fileID: 0}\n  switchSmallIcons_14: {fileID: 0}\n  switchManualHTML: \n  switchAccessibleURLs: \n  switchLegalInformation: \n  switchMainThreadStackSize: 1048576\n  switchPresenceGroupId: \n  switchLogoHandling: 0\n  switchReleaseVersion: 0\n  switchDisplayVersion: 1.0.0\n  switchStartupUserAccount: 0\n  switchTouchScreenUsage: 0\n  switchSupportedLanguagesMask: 0\n  switchLogoType: 0\n  switchApplicationErrorCodeCategory: \n  switchUserAccountSaveDataSize: 0\n  switchUserAccountSaveDataJournalSize: 0\n  switchApplicationAttribute: 0\n  switchCardSpecSize: -1\n  switchCardSpecClock: -1\n  switchRatingsMask: 0\n  switchRatingsInt_0: 0\n  switchRatingsInt_1: 0\n  switchRatingsInt_2: 0\n  switchRatingsInt_3: 0\n  switchRatingsInt_4: 0\n  switchRatingsInt_5: 0\n  switchRatingsInt_6: 0\n  switchRatingsInt_7: 0\n  switchRatingsInt_8: 0\n  switchRatingsInt_9: 0\n  switchRatingsInt_10: 0\n  switchRatingsInt_11: 0\n  switchLocalCommunicationIds_0: \n  switchLocalCommunicationIds_1: \n  switchLocalCommunicationIds_2: \n  switchLocalCommunicationIds_3: \n  switchLocalCommunicationIds_4: \n  switchLocalCommunicationIds_5: \n  switchLocalCommunicationIds_6: \n  switchLocalCommunicationIds_7: \n  switchParentalControl: 0\n  switchAllowsScreenshot: 1\n  switchAllowsVideoCapturing: 1\n  switchAllowsRuntimeAddOnContentInstall: 0\n  switchDataLossConfirmation: 0\n  switchUserAccountLockEnabled: 0\n  switchSystemResourceMemory: 16777216\n  switchSupportedNpadStyles: 3\n  switchNativeFsCacheSize: 32\n  switchIsHoldTypeHorizontal: 0\n  switchSupportedNpadCount: 8\n  switchSocketConfigEnabled: 0\n  switchTcpInitialSendBufferSize: 32\n  switchTcpInitialReceiveBufferSize: 64\n  switchTcpAutoSendBufferSizeMax: 256\n  switchTcpAutoReceiveBufferSizeMax: 256\n  switchUdpSendBufferSize: 9\n  switchUdpReceiveBufferSize: 42\n  switchSocketBufferEfficiency: 4\n  switchSocketInitializeEnabled: 1\n  switchNetworkInterfaceManagerInitializeEnabled: 1\n  switchPlayerConnectionEnabled: 1\n  ps4NPAgeRating: 12\n  ps4NPTitleSecret: \n  ps4NPTrophyPackPath: \n  ps4ParentalLevel: 11\n  ps4ContentID: ED1633-NPXX51362_00-0000000000000000\n  ps4Category: 0\n  ps4MasterVersion: 01.00\n  ps4AppVersion: 01.00\n  ps4AppType: 0\n  ps4ParamSfxPath: \n  ps4VideoOutPixelFormat: 0\n  ps4VideoOutInitialWidth: 1920\n  ps4VideoOutBaseModeInitialWidth: 1920\n  ps4VideoOutReprojectionRate: 60\n  ps4PronunciationXMLPath: \n  ps4PronunciationSIGPath: \n  ps4BackgroundImagePath: \n  ps4StartupImagePath: \n  ps4StartupImagesFolder: \n  ps4IconImagesFolder: \n  ps4SaveDataImagePath: \n  ps4SdkOverride: \n  ps4BGMPath: \n  ps4ShareFilePath: \n  ps4ShareOverlayImagePath: \n  ps4PrivacyGuardImagePath: \n  ps4NPtitleDatPath: \n  ps4RemotePlayKeyAssignment: -1\n  ps4RemotePlayKeyMappingDir: \n  ps4PlayTogetherPlayerCount: 0\n  ps4EnterButtonAssignment: 1\n  ps4ApplicationParam1: 0\n  ps4ApplicationParam2: 0\n  ps4ApplicationParam3: 0\n  ps4ApplicationParam4: 0\n  ps4DownloadDataSize: 0\n  ps4GarlicHeapSize: 2048\n  ps4ProGarlicHeapSize: 2560\n  playerPrefsMaxSize: 32768\n  ps4Passcode: frAQBc8Wsa1xVPfvJcrgRYwTiizs2trQ\n  ps4pnSessions: 1\n  ps4pnPresence: 1\n  ps4pnFriends: 1\n  ps4pnGameCustomData: 1\n  playerPrefsSupport: 0\n  enableApplicationExit: 0\n  resetTempFolder: 1\n  restrictedAudioUsageRights: 0\n  ps4UseResolutionFallback: 0\n  ps4ReprojectionSupport: 0\n  ps4UseAudio3dBackend: 0\n  ps4SocialScreenEnabled: 0\n  ps4ScriptOptimizationLevel: 0\n  ps4Audio3dVirtualSpeakerCount: 14\n  ps4attribCpuUsage: 0\n  ps4PatchPkgPath: \n  ps4PatchLatestPkgPath: \n  ps4PatchChangeinfoPath: \n  ps4PatchDayOne: 0\n  ps4attribUserManagement: 0\n  ps4attribMoveSupport: 0\n  ps4attrib3DSupport: 0\n  ps4attribShareSupport: 0\n  ps4attribExclusiveVR: 0\n  ps4disableAutoHideSplash: 0\n  ps4videoRecordingFeaturesUsed: 0\n  ps4contentSearchFeaturesUsed: 0\n  ps4attribEyeToEyeDistanceSettingVR: 0\n  ps4IncludedModules: []\n  monoEnv: \n  splashScreenBackgroundSourceLandscape: {fileID: 0}\n  splashScreenBackgroundSourcePortrait: {fileID: 0}\n  spritePackerPolicy: \n  webGLMemorySize: 16\n  webGLExceptionSupport: 1\n  webGLNameFilesAsHashes: 0\n  webGLDataCaching: 1\n  webGLDebugSymbols: 0\n  webGLEmscriptenArgs: \n  webGLModulesDirectory: \n  webGLTemplate: APPLICATION:Default\n  webGLAnalyzeBuildSize: 0\n  webGLUseEmbeddedResources: 0\n  webGLCompressionFormat: 1\n  webGLLinkerTarget: 1\n  webGLThreadsSupport: 0\n  webGLWasmStreaming: 0\n  scriptingDefineSymbols: {}\n  platformArchitecture: {}\n  scriptingBackend: {}\n  il2cppCompilerConfiguration: {}\n  managedStrippingLevel: {}\n  incrementalIl2cppBuild: {}\n  allowUnsafeCode: 1\n  additionalIl2CppArgs: \n  scriptingRuntimeVersion: 1\n  gcIncremental: 0\n  gcWBarrierValidation: 0\n  apiCompatibilityLevelPerPlatform: {}\n  m_RenderingPath: 1\n  m_MobileRenderingPath: 1\n  metroPackageName: Template_3D\n  metroPackageVersion: \n  metroCertificatePath: \n  metroCertificatePassword: \n  metroCertificateSubject: \n  metroCertificateIssuer: \n  metroCertificateNotAfter: 0000000000000000\n  metroApplicationDescription: Template_3D\n  wsaImages: {}\n  metroTileShortName: \n  metroTileShowName: 0\n  metroMediumTileShowName: 0\n  metroLargeTileShowName: 0\n  metroWideTileShowName: 0\n  metroSupportStreamingInstall: 0\n  metroLastRequiredScene: 0\n  metroDefaultTileSize: 1\n  metroTileForegroundText: 2\n  metroTileBackgroundColor: {r: 0.13333334, g: 0.17254902, b: 0.21568628, a: 0}\n  metroSplashScreenBackgroundColor: {r: 0.12941177, g: 0.17254902, b: 0.21568628,\n    a: 1}\n  metroSplashScreenUseBackgroundColor: 0\n  platformCapabilities: {}\n  metroTargetDeviceFamilies: {}\n  metroFTAName: \n  metroFTAFileTypes: []\n  metroProtocolName: \n  XboxOneProductId: \n  XboxOneUpdateKey: \n  XboxOneSandboxId: \n  XboxOneContentId: \n  XboxOneTitleId: \n  XboxOneSCId: \n  XboxOneGameOsOverridePath: \n  XboxOnePackagingOverridePath: \n  XboxOneAppManifestOverridePath: \n  XboxOneVersion: 1.0.0.0\n  XboxOnePackageEncryption: 0\n  XboxOnePackageUpdateGranularity: 2\n  XboxOneDescription: \n  XboxOneLanguage:\n  - enus\n  XboxOneCapability: []\n  XboxOneGameRating: {}\n  XboxOneIsContentPackage: 0\n  XboxOneEnableGPUVariability: 1\n  XboxOneSockets: {}\n  XboxOneSplashScreen: {fileID: 0}\n  XboxOneAllowedProductIds: []\n  XboxOnePersistentLocalStorageSize: 0\n  XboxOneXTitleMemory: 8\n  xboxOneScriptCompiler: 1\n  XboxOneOverrideIdentityName: \n  vrEditorSettings:\n    daydream:\n      daydreamIconForeground: {fileID: 0}\n      daydreamIconBackground: {fileID: 0}\n  cloudServicesEnabled:\n    UNet: 1\n  luminIcon:\n    m_Name: \n    m_ModelFolderPath: \n    m_PortalFolderPath: \n  luminCert:\n    m_CertPath: \n    m_SignPackage: 1\n  luminIsChannelApp: 0\n  luminVersion:\n    m_VersionCode: 1\n    m_VersionName: \n  facebookSdkVersion: 7.9.4\n  facebookAppId: \n  facebookCookies: 1\n  facebookLogging: 1\n  facebookStatus: 1\n  facebookXfbml: 0\n  facebookFrictionlessRequests: 1\n  apiCompatibilityLevel: 6\n  cloudProjectId: \n  framebufferDepthMemorylessMode: 0\n  projectName: \n  organizationId: \n  cloudEnabled: 0\n  enableNativePlatformBackendsForNewInputSystem: 0\n  disableOldInputManagerSupport: 0\n  legacyClampBlendShapeWeights: 0\n"
  },
  {
    "path": "ProjectSettings/ProjectVersion.txt",
    "content": "m_EditorVersion: 2019.1.9f1\nm_EditorVersionWithRevision: 2019.1.9f1 (d5f1b37da199)\n"
  },
  {
    "path": "ProjectSettings/QualitySettings.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!47 &1\nQualitySettings:\n  m_ObjectHideFlags: 0\n  serializedVersion: 5\n  m_CurrentQuality: 5\n  m_QualitySettings:\n  - serializedVersion: 2\n    name: Very Low\n    pixelLightCount: 0\n    shadows: 0\n    shadowResolution: 0\n    shadowProjection: 1\n    shadowCascades: 1\n    shadowDistance: 15\n    shadowNearPlaneOffset: 3\n    shadowCascade2Split: 0.33333334\n    shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667}\n    shadowmaskMode: 0\n    blendWeights: 1\n    textureQuality: 1\n    anisotropicTextures: 0\n    antiAliasing: 0\n    softParticles: 0\n    softVegetation: 0\n    realtimeReflectionProbes: 0\n    billboardsFaceCameraPosition: 0\n    vSyncCount: 0\n    lodBias: 0.3\n    maximumLODLevel: 0\n    streamingMipmapsActive: 0\n    streamingMipmapsAddAllCameras: 1\n    streamingMipmapsMemoryBudget: 512\n    streamingMipmapsRenderersPerFrame: 512\n    streamingMipmapsMaxLevelReduction: 2\n    streamingMipmapsMaxFileIORequests: 1024\n    particleRaycastBudget: 4\n    asyncUploadTimeSlice: 2\n    asyncUploadBufferSize: 16\n    asyncUploadPersistentBuffer: 1\n    resolutionScalingFixedDPIFactor: 1\n    excludedTargetPlatforms: []\n  - serializedVersion: 2\n    name: Low\n    pixelLightCount: 0\n    shadows: 0\n    shadowResolution: 0\n    shadowProjection: 1\n    shadowCascades: 1\n    shadowDistance: 20\n    shadowNearPlaneOffset: 3\n    shadowCascade2Split: 0.33333334\n    shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667}\n    shadowmaskMode: 0\n    blendWeights: 2\n    textureQuality: 0\n    anisotropicTextures: 0\n    antiAliasing: 0\n    softParticles: 0\n    softVegetation: 0\n    realtimeReflectionProbes: 0\n    billboardsFaceCameraPosition: 0\n    vSyncCount: 0\n    lodBias: 0.4\n    maximumLODLevel: 0\n    streamingMipmapsActive: 0\n    streamingMipmapsAddAllCameras: 1\n    streamingMipmapsMemoryBudget: 512\n    streamingMipmapsRenderersPerFrame: 512\n    streamingMipmapsMaxLevelReduction: 2\n    streamingMipmapsMaxFileIORequests: 1024\n    particleRaycastBudget: 16\n    asyncUploadTimeSlice: 2\n    asyncUploadBufferSize: 16\n    asyncUploadPersistentBuffer: 1\n    resolutionScalingFixedDPIFactor: 1\n    excludedTargetPlatforms: []\n  - serializedVersion: 2\n    name: Medium\n    pixelLightCount: 1\n    shadows: 1\n    shadowResolution: 0\n    shadowProjection: 1\n    shadowCascades: 1\n    shadowDistance: 20\n    shadowNearPlaneOffset: 3\n    shadowCascade2Split: 0.33333334\n    shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667}\n    shadowmaskMode: 0\n    blendWeights: 2\n    textureQuality: 0\n    anisotropicTextures: 1\n    antiAliasing: 0\n    softParticles: 0\n    softVegetation: 0\n    realtimeReflectionProbes: 0\n    billboardsFaceCameraPosition: 0\n    vSyncCount: 1\n    lodBias: 0.7\n    maximumLODLevel: 0\n    streamingMipmapsActive: 0\n    streamingMipmapsAddAllCameras: 1\n    streamingMipmapsMemoryBudget: 512\n    streamingMipmapsRenderersPerFrame: 512\n    streamingMipmapsMaxLevelReduction: 2\n    streamingMipmapsMaxFileIORequests: 1024\n    particleRaycastBudget: 64\n    asyncUploadTimeSlice: 2\n    asyncUploadBufferSize: 16\n    asyncUploadPersistentBuffer: 1\n    resolutionScalingFixedDPIFactor: 1\n    excludedTargetPlatforms: []\n  - serializedVersion: 2\n    name: High\n    pixelLightCount: 2\n    shadows: 2\n    shadowResolution: 1\n    shadowProjection: 1\n    shadowCascades: 2\n    shadowDistance: 40\n    shadowNearPlaneOffset: 3\n    shadowCascade2Split: 0.33333334\n    shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667}\n    shadowmaskMode: 1\n    blendWeights: 2\n    textureQuality: 0\n    anisotropicTextures: 1\n    antiAliasing: 0\n    softParticles: 0\n    softVegetation: 1\n    realtimeReflectionProbes: 1\n    billboardsFaceCameraPosition: 1\n    vSyncCount: 1\n    lodBias: 1\n    maximumLODLevel: 0\n    streamingMipmapsActive: 0\n    streamingMipmapsAddAllCameras: 1\n    streamingMipmapsMemoryBudget: 512\n    streamingMipmapsRenderersPerFrame: 512\n    streamingMipmapsMaxLevelReduction: 2\n    streamingMipmapsMaxFileIORequests: 1024\n    particleRaycastBudget: 256\n    asyncUploadTimeSlice: 2\n    asyncUploadBufferSize: 16\n    asyncUploadPersistentBuffer: 1\n    resolutionScalingFixedDPIFactor: 1\n    excludedTargetPlatforms: []\n  - serializedVersion: 2\n    name: Very High\n    pixelLightCount: 3\n    shadows: 2\n    shadowResolution: 2\n    shadowProjection: 1\n    shadowCascades: 2\n    shadowDistance: 70\n    shadowNearPlaneOffset: 3\n    shadowCascade2Split: 0.33333334\n    shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667}\n    shadowmaskMode: 1\n    blendWeights: 4\n    textureQuality: 0\n    anisotropicTextures: 2\n    antiAliasing: 2\n    softParticles: 1\n    softVegetation: 1\n    realtimeReflectionProbes: 1\n    billboardsFaceCameraPosition: 1\n    vSyncCount: 1\n    lodBias: 1.5\n    maximumLODLevel: 0\n    streamingMipmapsActive: 0\n    streamingMipmapsAddAllCameras: 1\n    streamingMipmapsMemoryBudget: 512\n    streamingMipmapsRenderersPerFrame: 512\n    streamingMipmapsMaxLevelReduction: 2\n    streamingMipmapsMaxFileIORequests: 1024\n    particleRaycastBudget: 1024\n    asyncUploadTimeSlice: 2\n    asyncUploadBufferSize: 16\n    asyncUploadPersistentBuffer: 1\n    resolutionScalingFixedDPIFactor: 1\n    excludedTargetPlatforms: []\n  - serializedVersion: 2\n    name: Ultra\n    pixelLightCount: 4\n    shadows: 2\n    shadowResolution: 2\n    shadowProjection: 1\n    shadowCascades: 4\n    shadowDistance: 150\n    shadowNearPlaneOffset: 3\n    shadowCascade2Split: 0.33333334\n    shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667}\n    shadowmaskMode: 1\n    blendWeights: 4\n    textureQuality: 0\n    anisotropicTextures: 2\n    antiAliasing: 2\n    softParticles: 1\n    softVegetation: 1\n    realtimeReflectionProbes: 1\n    billboardsFaceCameraPosition: 1\n    vSyncCount: 1\n    lodBias: 2\n    maximumLODLevel: 0\n    streamingMipmapsActive: 0\n    streamingMipmapsAddAllCameras: 1\n    streamingMipmapsMemoryBudget: 512\n    streamingMipmapsRenderersPerFrame: 512\n    streamingMipmapsMaxLevelReduction: 2\n    streamingMipmapsMaxFileIORequests: 1024\n    particleRaycastBudget: 4096\n    asyncUploadTimeSlice: 2\n    asyncUploadBufferSize: 16\n    asyncUploadPersistentBuffer: 1\n    resolutionScalingFixedDPIFactor: 1\n    excludedTargetPlatforms: []\n  m_PerPlatformDefaultQuality:\n    Android: 2\n    Lumin: 5\n    Nintendo 3DS: 5\n    Nintendo Switch: 5\n    PS4: 5\n    PSP2: 2\n    Standalone: 5\n    WebGL: 3\n    Windows Store Apps: 5\n    XboxOne: 5\n    iPhone: 2\n    tvOS: 2\n"
  },
  {
    "path": "ProjectSettings/TagManager.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!78 &1\nTagManager:\n  serializedVersion: 2\n  tags: []\n  layers:\n  - Default\n  - TransparentFX\n  - Ignore Raycast\n  - \n  - Water\n  - UI\n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  - \n  m_SortingLayers:\n  - name: Default\n    uniqueID: 0\n    locked: 0\n"
  },
  {
    "path": "ProjectSettings/TimeManager.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!5 &1\nTimeManager:\n  m_ObjectHideFlags: 0\n  Fixed Timestep: 0.02\n  Maximum Allowed Timestep: 0.33333334\n  m_TimeScale: 1\n  Maximum Particle Timestep: 0.03\n"
  },
  {
    "path": "ProjectSettings/UnityConnectSettings.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!310 &1\nUnityConnectSettings:\n  m_ObjectHideFlags: 0\n  serializedVersion: 1\n  m_Enabled: 1\n  m_TestMode: 0\n  m_EventOldUrl: https://api.uca.cloud.unity3d.com/v1/events\n  m_EventUrl: https://cdp.cloud.unity3d.com/v1/events\n  m_ConfigUrl: https://config.uca.cloud.unity3d.com\n  m_TestInitMode: 0\n  CrashReportingSettings:\n    m_EventUrl: https://perf-events.cloud.unity3d.com\n    m_Enabled: 0\n    m_LogBufferSize: 10\n    m_CaptureEditorExceptions: 1\n  UnityPurchasingSettings:\n    m_Enabled: 0\n    m_TestMode: 0\n  UnityAnalyticsSettings:\n    m_Enabled: 0\n    m_TestMode: 0\n    m_InitializeOnStartup: 1\n  UnityAdsSettings:\n    m_Enabled: 0\n    m_InitializeOnStartup: 1\n    m_TestMode: 0\n    m_IosGameId: \n    m_AndroidGameId: \n    m_GameIds: {}\n    m_GameId: \n  PerformanceReportingSettings:\n    m_Enabled: 0\n"
  },
  {
    "path": "ProjectSettings/VFXManager.asset",
    "content": "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!937362698 &1\nVFXManager:\n  m_ObjectHideFlags: 0\n  m_IndirectShader: {fileID: 0}\n  m_CopyBufferShader: {fileID: 0}\n  m_SortShader: {fileID: 0}\n  m_RenderPipeSettingsPath: \n  m_FixedTimeStep: 0.016666668\n  m_MaxDeltaTime: 0.05\n"
  },
  {
    "path": "ProjectSettings/XRSettings.asset",
    "content": "{\n    \"m_SettingKeys\": [\n        \"VR Device Disabled\",\n        \"VR Device User Alert\"\n    ],\n    \"m_SettingValues\": [\n        \"False\",\n        \"False\"\n    ]\n}"
  },
  {
    "path": "README.md",
    "content": "# unity-jsb\r\n\r\n[![openupm](https://img.shields.io/npm/v/cc.starlessnight.unity-jsb?label=openupm&registry_uri=https://package.openupm.com)](https://openupm.com/packages/cc.starlessnight.unity-jsb/)\r\n\r\nIt brings Javascript runtime capability to Unity3D by integrating [QuickJS](https://bellard.org/quickjs/).\r\n\r\n**Typescript is the scripting language used in unity-jsb, the definition files (d.ts) of exported C# types could be generated with one-click simplicity.**\r\n\r\n> **v8 is experimentally supported as an alternative backend (only on Windows x64 for now)**\r\n> [Debugger is supported when using v8 backend.](#debugger)\r\n\r\n> QuickJS is a small and embeddable Javascript engine. It supports the ES2020 specification including modules, asynchronous generators, proxies and BigInt. \r\n\r\n# Features\r\n* Unity3D coroutines and C# tasks support in JS async function\r\n* Operator overloading for Vector2/Vector3 etc. (only supported with QuickJS)\r\n* [Javascript hotload](#hotload) (development stage only)\r\n* Highly integrated with Unity3D\r\n    * JS implemented `MonoBehaviour` (also available on `Prefab`)\r\n    * JS implemented `EditorWindow`\r\n    * JS implemented `CustomEditor` (Inspector)\r\n    * JS implemented `ScriptableObject`\r\n    * JS implemented `AssetPostProcessor`\r\n* JS/C# interaction without glue code (development stage only)\r\n* Generates glue code for better performance\r\n    * [PLANNED] Generates glue code with `Roslyn` source generator (for Unity2021.3+ only)\r\n* [UNFINISHED] JS Worker\r\n* [UNFINISHED] Hotfix on C#\r\n* [UNFINISHED] `UIElement` support\r\n\r\n> Supports .NET4.0/dotnetcore3.1/Unity2020.3+ (Windows/macOS/iOS/Android)  x86/x64/arm64\r\n> Only tested on macOS with Unity2020.3(INTEL)\r\n\r\n# Samples\r\n\r\n## Extends MonoBehaviour \r\n\r\n```ts\r\n// the namespace will be mapped into module in javascript\r\n// it's not always necessary to write type-imports manually, intellisense could finish it automatically and properly in VSCode\r\nimport { MonoBehaviour, WaitForSeconds, Object, GameObject } from \"UnityEngine\";\r\n\r\nclass MyClass extends MonoBehaviour {\r\n    protected _tick = 0;\r\n\r\n    Awake() {\r\n        console.log(\"MyClass.Awake\", this._tick++);\r\n    }\r\n\r\n    async OnEnable() {\r\n        console.log(\"MyClass.OnEnable\", this._tick++);\r\n        await jsb.Yield(new WaitForSeconds(1));\r\n        console.log(\"MyClass.OnEnable (delayed)\", this._tick++);\r\n    }\r\n\r\n    OnDisable() {\r\n        console.log(\"MyClass.OnDisable\", this._tick++);\r\n    }\r\n\r\n    OnDestroy() {\r\n        console.log(\"MyClass.OnDestroy\", this._tick++);\r\n    }\r\n\r\n    async test() {\r\n        console.log(\"MyClass.test (will be destroied after 5 secs.\", this.transform);\r\n        await jsb.Yield(new WaitForSeconds(5));\r\n        Object.Destroy(this.gameObject);\r\n    }\r\n}\r\n\r\n// with @ScriptType decorator, this class will be recognized by Unity Editor\r\n@ScriptType()\r\nexport class MySubClass extends MyClass {\r\n\r\n    // make this field be serialized automatically\r\n    @ScriptInteger()\r\n    year = 2021;\r\n\r\n    @ScriptInteger()\r\n    month = 5;\r\n\r\n    @ScriptString()\r\n    theName = \"Bob\";\r\n\r\n    Awake() {\r\n        super.Awake();\r\n        console.log(\"MySubClass.Awake\", this._tick++);\r\n    }\r\n\r\n    play() {\r\n        console.log(\"MySubClass.play\");\r\n    }\r\n}\r\n\r\nlet gameObject = new GameObject();\r\nlet comp = gameObject.AddComponent(MySubClass);\r\n\r\ncomp.play();\r\n\r\nlet comp_bySuperClass = gameObject.GetComponent(MyClass);\r\ncomp_bySuperClass.test();\r\n```\r\n\r\n## Extends EditorWindow\r\n\r\n```ts\r\nimport { EditorWindow } from \"UnityEditor\";\r\nimport { GUILayout, GUIContent } from \"UnityEngine\";\r\n\r\n// with @ScriptEditorWindow decorator, the type will be listed in script launchpad window (Menu: JS Bridge -> Script Editor Window Launcher)\r\n@ScriptEditorWindow()\r\nexport class MyEditorWindow extends EditorWindow {\r\n    Awake() {\r\n        console.log(\"MyEditorWindow.Awake\");\r\n    }\r\n\r\n    OnEnable() {\r\n        this.titleContent = new GUIContent(\"Blablabla\");\r\n    }\r\n\r\n    OnGUI() {\r\n        if (GUILayout.Button(\"I am Javascript\")) {\r\n            console.log(\"Thanks\");\r\n        }\r\n    }\r\n}\r\n```\r\n\r\n## Hotload\r\nScript hot-load is supported, you can run the game, edit scripts without stopping playing to see the change affects immediately. The class instance including member variables in scripts (MonoBehaviour/EditorWindow) will be retained, only the type of class itself will be replaced on the fly to the new version.\r\n\r\n![Code Hotload](jsb_build/res/hotload.gif)\r\n\r\n## Editor Scripting\r\nSupports editor scripting:\r\n* Editor\r\n* EditorWindow\r\n* ScriptableObject\r\n* AssetPostProcessor\r\n\r\n> Here is an example of EditorWindow totally implemented in typescript. *Only imgui is supported for now.*\r\n\r\n![JS Module Viewer](jsb_build/res/js_module_viewer.png)\r\n\r\n## Async Functions\r\n* await Unity3D coroutines\r\n* await C# Tasks\r\n\r\n> NOTE: In current version, a C# task returning nothing should use `System.Threading.Tasks.Task` as return type explicitly instead of `void`, then `jsb.Yield` can understand that it's a async task.\r\n\r\n```ts\r\nimport { WaitForSeconds } from \"UnityEngine\";\r\nimport { IPHostEntry } from \"System.Net\";\r\nimport { AsyncTaskTest } from \"Example\";\r\nimport * as jsb from \"jsb\";\r\n\r\nasync function testAsyncFunc () {\r\n    console.log(\"you can await any Unity YieldInstructions\");\r\n    await jsb.Yield(new WaitForSeconds(1.2));\r\n    await jsb.Yield(null);\r\n\r\n    console.log(\"setTimeout support\")\r\n    await new Promise(resolve => {\r\n        setTimeout(() => resolve(), 1000);    \r\n    });\r\n\r\n    // System.Threading.Tasks.Task<System.Net.IPHostEntry>\r\n    let result = <IPHostEntry> await jsb.Yield(Example.AsyncTaskTest.GetHostEntryAsync(\"www.baidu.com\"));\r\n    console.log(\"host entry:\", result.HostName);\r\n}\r\n\r\ntestAsyncFunc();\r\n```\r\n\r\n## Operator overloading\r\n```Vector3 * Vector3``` or ```Vector3 * float``` is all right, but be caution that there is no value type in Javascript, Vector3 is by-ref in Javascript.\r\n> NOTE: Operator overloading is only supported by quickjs.\r\n\r\n```ts\r\n{\r\n    let vec1 = new Vector3(1, 2, 3);\r\n    let vec2 = new Vector3(9, 8, 7);\r\n    \r\n    // @ts-ignore\r\n    let vec3 = vec1 + vec2; \r\n    let vec4 = vec1 + vec2;\r\n    console.log(vec3);\r\n    console.log(vec3 / 3);\r\n    console.log(vec3 == vec4);\r\n}\r\n{\r\n    let vec1 = new Vector2(1, 2);\r\n    let vec2 = new Vector2(9, 8);\r\n    let vec3 = vec1 + vec2;\r\n    console.log(vec3);\r\n}\r\n```\r\n\r\n## Modules\r\n\r\n```ts\r\n// Supports commonjs modules (require)\r\n\r\nrequire(\"./test\");\r\n\r\n// commonjs modules cache access\r\nObject.keys(require.cache).forEach(key => console.log(key));\r\n```\r\n\r\n## WebSocket \r\n\r\n```ts\r\nlet ws = new WebSocket(\"ws://127.0.0.1:8080/websocket\", \"default\");\r\n\r\nconsole.log(\"websocket connecting:\", ws.url);\r\n\r\nws.onopen = function () {\r\n    console.log(\"[ws.onopen]\", ws.readyState);\r\n    let count = 0;\r\n    setInterval(function () {\r\n        ws.send(\"websocket message test\" + count++);\r\n    }, 1000);\r\n};\r\nws.onclose = function () {\r\n    console.log(\"[ws.onclose]\", ws.readyState);\r\n};\r\nws.onerror = function (err) {\r\n    console.log(\"[ws.onerror]\", err);\r\n};\r\nws.onmessage = function (msg) {\r\n    console.log(\"[ws.recv]\", msg);\r\n};\r\n```\r\n\r\n## XMLHttpRequest\r\n\r\n```ts\r\nlet xhr = new XMLHttpRequest();\r\nxhr.open(\"GET\", \"http://127.0.0.1:8080/windows/checksum.txt\");\r\nxhr.timeout = 1000;\r\nxhr.onreadystatechange = function () {\r\n    console.log(\"readyState:\", xhr.readyState);\r\n    if (xhr.readyState !== 4) {\r\n        return;\r\n    }\r\n    console.log(\"status:\", xhr.status);\r\n    if (xhr.status == 200) {\r\n        console.log(\"responseText:\", xhr.responseText);\r\n    }\r\n}\r\nxhr.send();\r\n```\r\n\r\n## Worker\r\n> This feature is UNFINISHED, all C# types are not exported into Worker runtime at present.\r\n\r\n```ts\r\n/// master.js\r\n\r\nlet worker = new Worker(\"worker\");\r\n\r\nworker.onmessage = function (data) { \r\n    console.log(\"master receive message from worker\", data);\r\n}\r\n\r\n// setTimeout(function () { worker.terminate(); }, 5000);\r\n\r\n/// worker.js \r\n\r\nsetInterval(function () {\r\n    postMessage(\"message form worker\");\r\n}, 3000)\r\n\r\nonmessage = function (data) {\r\n    console.log(\"worker get message from master:\", data);\r\n}\r\n\r\n```\r\n\r\n## Hotfix\r\n> You can replace a tagged C# member method by a script function at runtime. This feature is UNFINISHED.\r\n\r\n```ts\r\n\r\n// replace method in C# class\r\njsb.hotfix.replace_single(\"HotfixTest\", \"Foo\", function (x: number) {\r\n    // CAUTION: private memebers will be accessible in scripts after hotfix\r\n    // if the replaced method is instance method, 'this' refers to C# object instance\r\n    // otherwise, 'this' refers to the type itself (JS Constructor)\r\n    console.log(\"replace C# method body by js function\", this.value); \r\n    return x;\r\n});\r\n\r\n// insert code snippet before method in C# class\r\njsb.hotfix.before_single(\"HotfixTest\", \"AnotherCall\", function () {\r\n    print(\"this will be executed before C# code\");\r\n});\r\n\r\n\r\n```\r\n\r\n### Unity API Docs included in d.ts\r\n![unity_ts_docs](jsb_build/res/unity_ts_docs.png)\r\n\r\n### Strong-typed\r\n![ts_code_complete](jsb_build/res/ts_code_complete.png)\r\n\r\n# How to get the minimalistic jsb package\r\n\r\nYou could add jsb as a UPM package with this URL: [https://github.com/ialex32x/unity-jsb.git#upm](https://github.com/ialex32x/unity-jsb.git#upm). \r\n> ! Samples are not included in UPM package.\r\n\r\n# How to get the sample project\r\n\r\nYou could clone this repository as a complete sample project.\r\n\r\n## Clone \r\n```\r\ngit clone https://github.com/ialex32x/unity-jsb --depth=1\r\n```\r\n## Restore node_modules\r\n```\r\nnpm install\r\n\r\n```\r\n## Re-compile ts source files (only if modified)\r\n```sh\r\ntsc \r\n# or compile and watch\r\n# tsc --watch \r\n```\r\n\r\n## Generate d.ts\r\nOpen project with Unity3D, run menu command ```JS Bridge/Generate Type Definition```\r\n> NOTE: The split size of the generated d.ts file is configurable in `PrefsEditor` (or directly edit `js-bridge.json`).\r\n\r\n## Examples\r\n\r\n### Examples for Unity\r\nOpen ```Assets/Examples/Scenes/SampleScene.unity``` and select specific example you want to check.\r\n> If you use node_modules in your scripts, you need to package them via webpack/gulp when the game actually runs on target platform.\r\n\r\n### Example for dotnetcore\r\nOpen this project directory in VSCode, select ```dotnetcore example``` in ```Run And Debug``` panel, then just run it.\r\n\r\n## How \r\n\r\n# Some experimental works\r\n\r\n## Extra Features (Optional)\r\n* Websocket \r\n* XMLHttpRequest \r\n\r\n## JSX\r\n```tsx\r\nexport interface TestData {\r\n    name: string,\r\n    tick: number;\r\n}\r\n\r\n@ScriptType()\r\nexport class MyWidgetTest extends JSXWidgetBridge {\r\n    private _data: TestData;\r\n    private _timer: any;\r\n\r\n    get data() { return this._data; }\r\n\r\n    Awake() {\r\n        this._data = ViewModel.create({ name: \"Unity\", tick: 0 });\r\n        this._widget =\r\n            <widget class={this}>\r\n                <text name=\"label\" text=\"Hello {{this.name}} {{this.tick}}\" />\r\n            </widget>\r\n\r\n        this._timer = setInterval(() => {\r\n            this._data.tick++;\r\n        }, 1000);\r\n        this._data.tick++;\r\n    }\r\n\r\n    OnDestroy() {\r\n        super.OnDestroy();\r\n        clearInterval(this._timer);\r\n    }\r\n}\r\n```\r\n\r\n# Multi-threading\r\n> Multi-threading is not supported in a single runtime. You need to use worker.\r\n\r\n# Debugger\r\nRemote debugging is now available with Chrome DevTools.\r\n\r\n> NOTE: *It's still in experimental stage.*\r\n\r\n![v8_debugger](jsb_build/res/debug_with_devtools.png)\r\n\r\n# Referenced libraries\r\n\r\n* [QuickJS](https://bellard.org/quickjs/)\r\n* [v8](https://v8.dev)\r\n* [ECMAScript](https://github.com/Geequlim/ECMAScript.git) A Javascript (QuickJS) Binding for Godot \r\n* [xLua](https://github.com/Tencent/xLua)\r\n* [libwebsockets](https://github.com/warmcat/libwebsockets)\r\n* [mbedtls](https://github.com/ARMmbed/mbedtls)\r\n* [zlib](https://zlib.net/)\r\n* [sqlite3](https://sqlite.org/index.html)\r\n* [quickjspp](https://github.com/c-smile/quickjspp)\r\n* [Vue.js](https://github.com/vuejs/vue)\r\n"
  },
  {
    "path": "Scripts/config/data.json",
    "content": "﻿{\r\n    \"name\": \"Joe\", \r\n    \"id\": 9999\r\n}"
  },
  {
    "path": "Scripts/out/components/example_monobehaviour.js",
    "content": "\"use strict\";\r\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n};\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.Something5Behaviour = exports.RotateBehaviour = exports.MySubClass = exports.MyClass = exports.ASimpleGuiDialog = void 0;\r\ndebugger;\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst jsb = require(\"jsb\");\r\nconst UnityEngine_UI_1 = require(\"UnityEngine.UI\");\r\nconst class_decorators_1 = require(\"plover/runtime/class_decorators\");\r\nlet ASimpleGuiDialog = class ASimpleGuiDialog extends UnityEngine_1.MonoBehaviour {\r\n    //TODO: [NOT_IMPLEMENTED] 使 UnityEvent 识别并接受脚本函数作为回调\r\n    onClicked() {\r\n        console.log(\"you clicked the button\");\r\n    }\r\n};\r\n__decorate([\r\n    class_decorators_1.ScriptProperty({ type: \"object\", bind: { widget: UnityEngine_UI_1.Button } })\r\n], ASimpleGuiDialog.prototype, \"nameLabel\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptFunction()\r\n], ASimpleGuiDialog.prototype, \"onClicked\", null);\r\nASimpleGuiDialog = __decorate([\r\n    class_decorators_1.ScriptType()\r\n], ASimpleGuiDialog);\r\nexports.ASimpleGuiDialog = ASimpleGuiDialog;\r\n//TODO constructor is not called when using v8-bridge as backend\r\nlet MyClass = class MyClass extends UnityEngine_1.MonoBehaviour {\r\n    constructor() {\r\n        super(...arguments);\r\n        this.vv = 0;\r\n        this._tick = 0;\r\n    }\r\n    Awake() {\r\n        this.vv = 0;\r\n        this._tick = 0;\r\n        console.log(\"MyClass.Awake\", this._tick++);\r\n    }\r\n    async OnEnable() {\r\n        console.log(\"MyClass.OnEnable\", this._tick++);\r\n        await jsb.Yield(new UnityEngine_1.WaitForSeconds(1));\r\n        console.log(\"MyClass.OnEnable (delayed)\", this._tick++);\r\n    }\r\n    OnDisable() {\r\n        console.log(\"MyClass.OnDisable\", this._tick++);\r\n    }\r\n    OnDestroy() {\r\n        console.log(\"MyClass.OnDestroy\", this._tick++);\r\n    }\r\n    OnApplicationFocus(hasFocus) {\r\n        console.log(\"OnApplicationFocus:\", hasFocus);\r\n    }\r\n    OnApplicationPause(pause) {\r\n        console.log(\"OnApplicationPause:\", pause);\r\n    }\r\n    speak(text) {\r\n        console.log(\"modified\", text);\r\n    }\r\n    async test() {\r\n        console.log(\"MyClass.test (will be destroied after 5 secs.\", this.transform);\r\n        await jsb.Yield(new UnityEngine_1.WaitForSeconds(5));\r\n        UnityEngine_1.Object.Destroy(this.gameObject);\r\n    }\r\n};\r\n__decorate([\r\n    class_decorators_1.ScriptNumber()\r\n], MyClass.prototype, \"vv\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptInteger({ editable: false, serializable: false })\r\n], MyClass.prototype, \"_tick\", void 0);\r\nMyClass = __decorate([\r\n    class_decorators_1.ScriptType()\r\n], MyClass);\r\nexports.MyClass = MyClass;\r\nlet MySubClass = class MySubClass extends MyClass {\r\n    Awake() {\r\n        super.Awake();\r\n        console.log(\"MySubClass.Awake\", this._tick++);\r\n    }\r\n    Update() {\r\n        if (UnityEngine_1.Input.GetMouseButtonUp(0)) {\r\n            let ray = UnityEngine_1.Camera.main.ScreenPointToRay(UnityEngine_1.Input.mousePosition);\r\n            let hitInfo = { type: UnityEngine_1.RaycastHit };\r\n            let layerMask = 1 << UnityEngine_1.LayerMask.NameToLayer(\"Default\");\r\n            console.log(\"hittest\", layerMask);\r\n            if (UnityEngine_1.Physics.Raycast(ray, hitInfo, 1000, layerMask)) {\r\n                console.log(\"hit\", hitInfo.value.transform.name);\r\n            }\r\n        }\r\n    }\r\n    play() {\r\n        console.log(\"MySubClass.play\");\r\n    }\r\n};\r\nMySubClass = __decorate([\r\n    class_decorators_1.ScriptType()\r\n], MySubClass);\r\nexports.MySubClass = MySubClass;\r\nlet RotateBehaviour = class RotateBehaviour extends UnityEngine_1.MonoBehaviour {\r\n    constructor() {\r\n        super(...arguments);\r\n        this._rotation = 0;\r\n        this.rotationSpeed = 50;\r\n    }\r\n    Reset() {\r\n        this._rotation = 0;\r\n    }\r\n    Awake() {\r\n        this._rotation = 0;\r\n        this.rotationSpeed = 50;\r\n        let ps = this.GetComponent(UnityEngine_1.ParticleSystem);\r\n        if (ps) {\r\n            ps.main.simulationSpace = UnityEngine_1.ParticleSystemSimulationSpace.World;\r\n            console.log(\"ps.main.simulationSpace:\", ps.main.simulationSpace);\r\n        }\r\n    }\r\n    Update() {\r\n        this._rotation += this.rotationSpeed * UnityEngine_1.Time.deltaTime;\r\n        if (jsb.isOperatorOverloadingSupported) {\r\n            //@ts-ignore\r\n            let p = UnityEngine_1.Quaternion.Euler(0, this._rotation, 0) * UnityEngine_1.Vector3.right * 5;\r\n            p.z *= 0.5;\r\n            this.transform.localPosition = p;\r\n        }\r\n        else {\r\n            let p = UnityEngine_1.Vector3.op_Multiply(UnityEngine_1.Quaternion.op_Multiply(UnityEngine_1.Quaternion.Euler(0, this._rotation, 0), UnityEngine_1.Vector3.right), 5);\r\n            p.z *= 0.5;\r\n            this.transform.localPosition = p;\r\n        }\r\n    }\r\n};\r\n__decorate([\r\n    class_decorators_1.ScriptNumber({ serializable: false })\r\n], RotateBehaviour.prototype, \"rotationSpeed\", void 0);\r\nRotateBehaviour = __decorate([\r\n    class_decorators_1.ScriptType()\r\n], RotateBehaviour);\r\nexports.RotateBehaviour = RotateBehaviour;\r\nlet Something5Behaviour = class Something5Behaviour extends UnityEngine_1.MonoBehaviour {\r\n};\r\n__decorate([\r\n    class_decorators_1.ScriptProperty({ type: \"Vector3\" })\r\n], Something5Behaviour.prototype, \"pos\", void 0);\r\nSomething5Behaviour = __decorate([\r\n    class_decorators_1.ScriptType()\r\n], Something5Behaviour);\r\nexports.Something5Behaviour = Something5Behaviour;\r\nif (module == require.main) {\r\n    print(\"example_monobehaviour\");\r\n    let gameObject = new UnityEngine_1.GameObject();\r\n    let comp1 = gameObject.AddComponent(MySubClass);\r\n    let comp2 = gameObject.AddComponent(MyClass);\r\n    let cube = UnityEngine_1.GameObject.CreatePrimitive(UnityEngine_1.PrimitiveType.Cube);\r\n    cube.transform.localPosition = new UnityEngine_1.Vector3(1, 2, 3);\r\n    cube.transform.localRotation = UnityEngine_1.Quaternion.Euler(30, 60, 90);\r\n    cube.transform.localScale = new UnityEngine_1.Vector3(2, 3, 4);\r\n    comp1.vv = 1;\r\n    comp2.vv = 2;\r\n    comp1.play();\r\n    {\r\n        let results = gameObject.GetComponents(MySubClass);\r\n        results.forEach(it => console.log(\"GetComponents(MySubClass):\", it.vv));\r\n    }\r\n    {\r\n        let results = gameObject.GetComponents(MyClass);\r\n        results.forEach(it => console.log(\"GetComponents(MyClass):\", it.vv));\r\n    }\r\n    let ps = UnityEngine_1.GameObject.Find(\"/Particle System\");\r\n    if (!ps) {\r\n        ps = new UnityEngine_1.GameObject(\"Particle System\");\r\n        ps.AddComponent(UnityEngine_1.ParticleSystem);\r\n    }\r\n    console.log(\"Particle System:\", ps);\r\n    if (ps) {\r\n        ps.AddComponent(RotateBehaviour);\r\n    }\r\n    {\r\n        let sphere = UnityEngine_1.GameObject.CreatePrimitive(UnityEngine_1.PrimitiveType.Sphere);\r\n        sphere.transform.localScale = new UnityEngine_1.Vector3(2, 2, 2);\r\n        sphere.transform.TestWithScriptObject(function () {\r\n            console.warn(\"TestWithScriptObject\");\r\n        });\r\n        sphere.AddComponent(Something5Behaviour);\r\n    }\r\n}\r\n//# sourceMappingURL=example_monobehaviour.js.map"
  },
  {
    "path": "Scripts/out/components/sample_monobehaviour.js",
    "content": "\"use strict\";\r\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n};\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.Something5Behaviour = exports.RotateBehaviour = exports.MySubClass = exports.MyClass = exports.ASimpleGuiDialog = void 0;\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst jsb = require(\"jsb\");\r\nconst UnityEngine_UI_1 = require(\"UnityEngine.UI\");\r\nconst class_decorators_1 = require(\"plover/runtime/class_decorators\");\r\nlet ASimpleGuiDialog = class ASimpleGuiDialog extends UnityEngine_1.MonoBehaviour {\r\n    //TODO: [NOT_IMPLEMENTED] 使 UnityEvent 识别并接受脚本函数作为回调\r\n    onClicked() {\r\n        console.log(\"you clicked the button\");\r\n    }\r\n};\r\n__decorate([\r\n    class_decorators_1.ScriptProperty({ type: \"object\", bind: { widget: UnityEngine_UI_1.Button } })\r\n], ASimpleGuiDialog.prototype, \"nameLabel\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptFunction()\r\n], ASimpleGuiDialog.prototype, \"onClicked\", null);\r\nASimpleGuiDialog = __decorate([\r\n    class_decorators_1.ScriptType()\r\n], ASimpleGuiDialog);\r\nexports.ASimpleGuiDialog = ASimpleGuiDialog;\r\n//TODO constructor is not called when using v8-bridge as backend\r\nlet MyClass = class MyClass extends UnityEngine_1.MonoBehaviour {\r\n    constructor() {\r\n        super(...arguments);\r\n        this.vv = 0;\r\n        this._tick = 0;\r\n    }\r\n    Awake() {\r\n        this.vv = 0;\r\n        this._tick = 0;\r\n        console.log(\"MyClass.Awake\", this._tick++);\r\n    }\r\n    async OnEnable() {\r\n        console.log(\"MyClass.OnEnable\", this._tick++);\r\n        await jsb.Yield(new UnityEngine_1.WaitForSeconds(1));\r\n        console.log(\"MyClass.OnEnable (delayed)\", this._tick++);\r\n    }\r\n    OnDisable() {\r\n        console.log(\"MyClass.OnDisable\", this._tick++);\r\n    }\r\n    OnDestroy() {\r\n        console.log(\"MyClass.OnDestroy\", this._tick++);\r\n    }\r\n    OnApplicationFocus(hasFocus) {\r\n        console.log(\"OnApplicationFocus:\", hasFocus);\r\n    }\r\n    OnApplicationPause(pause) {\r\n        console.log(\"OnApplicationPause:\", pause);\r\n    }\r\n    speak(text) {\r\n        console.log(\"modified\", text);\r\n    }\r\n    async test() {\r\n        console.log(\"MyClass.test (will be destroied after 5 secs.\", this.transform);\r\n        await jsb.Yield(new UnityEngine_1.WaitForSeconds(5));\r\n        UnityEngine_1.Object.Destroy(this.gameObject);\r\n    }\r\n};\r\n__decorate([\r\n    class_decorators_1.ScriptNumber()\r\n], MyClass.prototype, \"vv\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptInteger({ editable: false, serializable: false })\r\n], MyClass.prototype, \"_tick\", void 0);\r\nMyClass = __decorate([\r\n    class_decorators_1.ScriptType()\r\n], MyClass);\r\nexports.MyClass = MyClass;\r\nlet MySubClass = class MySubClass extends MyClass {\r\n    Awake() {\r\n        super.Awake();\r\n        console.log(\"MySubClass.Awake\", this._tick++);\r\n    }\r\n    Update() {\r\n        if (UnityEngine_1.Input.GetMouseButtonUp(0)) {\r\n            let ray = UnityEngine_1.Camera.main.ScreenPointToRay(UnityEngine_1.Input.mousePosition);\r\n            let hitInfo = { type: UnityEngine_1.RaycastHit };\r\n            let layerMask = 1 << UnityEngine_1.LayerMask.NameToLayer(\"Default\");\r\n            console.log(\"hittest\", layerMask);\r\n            if (UnityEngine_1.Physics.Raycast(ray, hitInfo, 1000, layerMask)) {\r\n                console.log(\"hit\", hitInfo.value.transform.name);\r\n            }\r\n        }\r\n    }\r\n    play() {\r\n        console.log(\"MySubClass.play\");\r\n    }\r\n};\r\nMySubClass = __decorate([\r\n    class_decorators_1.ScriptType()\r\n], MySubClass);\r\nexports.MySubClass = MySubClass;\r\nlet RotateBehaviour = class RotateBehaviour extends UnityEngine_1.MonoBehaviour {\r\n    constructor() {\r\n        super(...arguments);\r\n        this._rotation = 0;\r\n        this.rotationSpeed = 50;\r\n    }\r\n    Reset() {\r\n        this._rotation = 0;\r\n    }\r\n    Awake() {\r\n        this._rotation = 0;\r\n        this.rotationSpeed = 50;\r\n        let ps = this.GetComponent(UnityEngine_1.ParticleSystem);\r\n        if (ps) {\r\n            ps.main.simulationSpace = UnityEngine_1.ParticleSystemSimulationSpace.World;\r\n            console.log(\"ps.main.simulationSpace:\", ps.main.simulationSpace);\r\n        }\r\n    }\r\n    Update() {\r\n        this._rotation += this.rotationSpeed * UnityEngine_1.Time.deltaTime;\r\n        if (jsb.isOperatorOverloadingSupported) {\r\n            //@ts-ignore\r\n            let p = UnityEngine_1.Quaternion.Euler(0, this._rotation, 0) * UnityEngine_1.Vector3.right * 5;\r\n            p.z *= 0.5;\r\n            this.transform.localPosition = p;\r\n        }\r\n        else {\r\n            let p = UnityEngine_1.Vector3.op_Multiply(UnityEngine_1.Quaternion.op_Multiply(UnityEngine_1.Quaternion.Euler(0, this._rotation, 0), UnityEngine_1.Vector3.right), 5);\r\n            p.z *= 0.5;\r\n            this.transform.localPosition = p;\r\n        }\r\n    }\r\n};\r\n__decorate([\r\n    class_decorators_1.ScriptNumber({ serializable: false })\r\n], RotateBehaviour.prototype, \"rotationSpeed\", void 0);\r\nRotateBehaviour = __decorate([\r\n    class_decorators_1.ScriptType()\r\n], RotateBehaviour);\r\nexports.RotateBehaviour = RotateBehaviour;\r\nlet Something5Behaviour = class Something5Behaviour extends UnityEngine_1.MonoBehaviour {\r\n};\r\n__decorate([\r\n    class_decorators_1.ScriptProperty({ type: \"Vector3\" })\r\n], Something5Behaviour.prototype, \"pos\", void 0);\r\nSomething5Behaviour = __decorate([\r\n    class_decorators_1.ScriptType()\r\n], Something5Behaviour);\r\nexports.Something5Behaviour = Something5Behaviour;\r\n//# sourceMappingURL=sample_monobehaviour.js.map"
  },
  {
    "path": "Scripts/out/data.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.test_data = void 0;\r\nexports.test_data = {\r\n    \"name\": \"Jane\",\r\n    \"id\": 1\r\n};\r\n//# sourceMappingURL=data.js.map"
  },
  {
    "path": "Scripts/out/do_from_cs.js",
    "content": "function x() {\r\n    console.log(\"xxxxxxxxxxxxxxxxxxx\");\r\n}\r\nx;\r\n//# sourceMappingURL=do_from_cs.js.map"
  },
  {
    "path": "Scripts/out/do_from_cs_v.js",
    "content": "let vv = {\r\n    \"test\": \"hello\"\r\n};\r\nvv;\r\n//# sourceMappingURL=do_from_cs_v.js.map"
  },
  {
    "path": "Scripts/out/dofile_test.js",
    "content": "print(\"dofile test\");\r\n//# sourceMappingURL=dofile_test.js.map"
  },
  {
    "path": "Scripts/out/editor/asset_postprocessor.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.OnPostprocessAllAssets = exports.OnPostProcessSprites = exports.OnPostprocessMaterial = exports.OnPostprocessAudio = exports.OnPostprocessModel = exports.OnPostprocessTexture = void 0;\r\n// You need to register this script into assetPostProcessors in js-bridge.json (or Prefs.cs) to activate these callbacks\r\nfunction OnPostprocessTexture(processor, tex) {\r\n    // console.log(\"OnPostprocessTexture\", processor.assetPath);\r\n}\r\nexports.OnPostprocessTexture = OnPostprocessTexture;\r\nfunction OnPostprocessModel(processor, model) {\r\n    // console.log(\"OnPostprocessModel\", processor.assetPath);\r\n}\r\nexports.OnPostprocessModel = OnPostprocessModel;\r\nfunction OnPostprocessAudio(processor, audioClip) {\r\n    // console.log(\"OnPostprocessAudio\", processor.assetPath);\r\n}\r\nexports.OnPostprocessAudio = OnPostprocessAudio;\r\nfunction OnPostprocessMaterial(processor, material) {\r\n    // console.log(\"OnPostprocessMaterial\", processor.assetPath);\r\n}\r\nexports.OnPostprocessMaterial = OnPostprocessMaterial;\r\nfunction OnPostProcessSprites(processor, texture, sprites) {\r\n    // console.log(\"OnPostProcessSprites\", processor.assetPath);\r\n}\r\nexports.OnPostProcessSprites = OnPostProcessSprites;\r\nfunction OnPostprocessAllAssets(importedAssets, deletedAssets, movedAssets, movedFromAssetPaths) {\r\n}\r\nexports.OnPostprocessAllAssets = OnPostprocessAllAssets;\r\n//# sourceMappingURL=asset_postprocessor.js.map"
  },
  {
    "path": "Scripts/out/editor/inspector/my_class_inspector.js",
    "content": "\"use strict\";\r\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n};\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.MyClassInspector = void 0;\r\nconst UnityEditor_1 = require(\"UnityEditor\");\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst sample_monobehaviour_1 = require(\"../../components/sample_monobehaviour\");\r\nconst editor_decorators_1 = require(\"plover/editor/editor_decorators\");\r\nlet MyClassInspector = class MyClassInspector extends editor_decorators_1.DefaultEditor {\r\n    Awake() {\r\n        console.log(\"my class inspector class awake\");\r\n    }\r\n    OnInspectorGUI() {\r\n        let p = this.target;\r\n        UnityEditor_1.EditorGUILayout.HelpBox(\"WHY ARE YOU SO SERIOUS?\", UnityEditor_1.MessageType.Info);\r\n        UnityEditor_1.EditorGUI.BeginDisabledGroup(true);\r\n        UnityEditor_1.EditorGUILayout.ObjectField(\"Object\", p.gameObject, UnityEngine_1.Object, true);\r\n        UnityEditor_1.EditorGUI.EndDisabledGroup();\r\n        super.OnInspectorGUI();\r\n        if (UnityEngine_1.GUILayout.Button(\"test\")) {\r\n            p.speak(\"hello\");\r\n        }\r\n    }\r\n};\r\nMyClassInspector = __decorate([\r\n    editor_decorators_1.ScriptEditor(sample_monobehaviour_1.MyClass)\r\n], MyClassInspector);\r\nexports.MyClassInspector = MyClassInspector;\r\n//# sourceMappingURL=my_class_inspector.js.map"
  },
  {
    "path": "Scripts/out/editor/inspector/rotate_inspector.js",
    "content": "\"use strict\";\r\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n};\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.RotateBehaviourInspector = void 0;\r\nconst UnityEditor_1 = require(\"UnityEditor\");\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst sample_monobehaviour_1 = require(\"../../components/sample_monobehaviour\");\r\nconst editor_decorators_1 = require(\"plover/editor/editor_decorators\");\r\nlet RotateBehaviourInspector = class RotateBehaviourInspector extends UnityEditor_1.Editor {\r\n    Awake() {\r\n        console.log(\"my class inspector class awake\");\r\n    }\r\n    OnInspectorGUI() {\r\n        let p = this.target;\r\n        UnityEditor_1.EditorGUILayout.ObjectField(\"Object\", p.gameObject, UnityEngine_1.Object, true);\r\n        p.rotationSpeed = UnityEditor_1.EditorGUILayout.FloatField(\"Rotation Speed\", p.rotationSpeed);\r\n        if (UnityEngine_1.GUILayout.Button(\"Reset\")) {\r\n            p.Reset();\r\n        }\r\n    }\r\n};\r\nRotateBehaviourInspector = __decorate([\r\n    editor_decorators_1.ScriptEditor(sample_monobehaviour_1.RotateBehaviour)\r\n], RotateBehaviourInspector);\r\nexports.RotateBehaviourInspector = RotateBehaviourInspector;\r\n//# sourceMappingURL=rotate_inspector.js.map"
  },
  {
    "path": "Scripts/out/editor/js_test.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst js_test2_1 = require(\"./js_test2\");\r\nconsole.log(\"[js_test] revision 4 ## read from \", js_test2_1.MyName);\r\n//# sourceMappingURL=js_test.js.map"
  },
  {
    "path": "Scripts/out/editor/js_test2.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.MyName = void 0;\r\nexports.MyName = \"jstest2 revision 6\";\r\nconsole.log(\"[js_test2]\", exports.MyName);\r\n//# sourceMappingURL=js_test2.js.map"
  },
  {
    "path": "Scripts/out/editor/main.js",
    "content": "require(\"./js_test\");\r\n//# sourceMappingURL=main.js.map"
  },
  {
    "path": "Scripts/out/editor/my_editor_window.js",
    "content": "\"use strict\";\r\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n};\r\nvar MyEditorWindow_1;\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.MyEditorWindow = void 0;\r\nconst System_1 = require(\"System\");\r\nconst UnityEditor_1 = require(\"UnityEditor\");\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst editor_decorators_1 = require(\"plover/editor/editor_decorators\");\r\nconst class_decorators_1 = require(\"plover/runtime/class_decorators\");\r\nconst jsb = require(\"jsb\");\r\nconst jsb_editor_1 = require(\"jsb.editor\");\r\nclass TempWindow extends UnityEditor_1.EditorWindow {\r\n    constructor() {\r\n        super(...arguments);\r\n        this._greeting = false;\r\n    }\r\n    static show(rect, size) {\r\n        for (let w of UnityEngine_1.Resources.FindObjectsOfTypeAll(TempWindow)) {\r\n            w.Close();\r\n            UnityEngine_1.Object.DestroyImmediate(w);\r\n        }\r\n        let inst = UnityEngine_1.ScriptableObject.CreateInstance(TempWindow);\r\n        inst.ShowAsDropDown(UnityEngine_1.GUIUtility.GUIToScreenRect(rect), size);\r\n    }\r\n    Awake() {\r\n        console.log(\"awake temp window\");\r\n    }\r\n    OnDestroy() {\r\n        console.log(\"destroy temp window\");\r\n    }\r\n    OnEnable() {\r\n        console.log(\"enable temp window\");\r\n    }\r\n    OnDisable() {\r\n        console.log(\"disable temp window\");\r\n    }\r\n    OnGUI() {\r\n        if (UnityEngine_1.GUILayout.Button(\"Hi\")) {\r\n            this._greeting = true;\r\n            this.Repaint();\r\n        }\r\n        if (UnityEngine_1.GUILayout.Button(\"Close\")) {\r\n            this.Close();\r\n        }\r\n        if (this._greeting) {\r\n            UnityEditor_1.EditorGUILayout.HelpBox(\"Hi, nice to meet you.\", UnityEditor_1.MessageType.Info);\r\n        }\r\n    }\r\n}\r\nlet MyEditorWindow = MyEditorWindow_1 = class MyEditorWindow extends UnityEditor_1.EditorWindow {\r\n    constructor() {\r\n        super(...arguments);\r\n        this._parentWindowRect = new UnityEngine_1.Rect(0, 0, 0, 0);\r\n        this._resizeStart = new UnityEngine_1.Rect(0, 0, 0, 0);\r\n        this._minWindowSize = new UnityEngine_1.Vector2(120, 100);\r\n        this._thisWindowRect = new UnityEngine_1.Rect(50, 50, 400, 300);\r\n        // @ScriptProperty({ type: \"object\", serializable: false })\r\n        this._resizerContent = new UnityEngine_1.GUIContent(\"* \", \"Resize\");\r\n        this._isResizing = false;\r\n        this._windowIndex = 0;\r\n        this.continuousInteger = 0;\r\n        this._lastHour = -1;\r\n        this._lastMinute = -1;\r\n        this._lastSecond = -1;\r\n    }\r\n    Awake() {\r\n    }\r\n    OnEnable() {\r\n        this._onSceneGui = this.onSceneGui.bind(this);\r\n        this._onMenuTest = this.onMenuTest.bind(this);\r\n        this._onWindowGUI = this.onWindowGUI.bind(this);\r\n        this.titleContent = new UnityEngine_1.GUIContent(\"Blablabla0\");\r\n        UnityEditor_1.SceneView.duringSceneGui(\"add\", this._onSceneGui);\r\n    }\r\n    OnDisable() {\r\n        console.log(\"on disable\");\r\n        UnityEditor_1.SceneView.duringSceneGui(\"remove\", this._onSceneGui);\r\n        this._onSceneGui = null;\r\n        this._onMenuTest = null;\r\n        this._onWindowGUI = null;\r\n    }\r\n    OnDestroy() {\r\n        console.log(\"on destroy\");\r\n        this._resizerContent = null;\r\n    }\r\n    onWindowGUI() {\r\n        if (UnityEngine_1.GUILayout.Button(\"Click\")) {\r\n            console.log(\"you clicked\");\r\n        }\r\n        let mousePosition = UnityEngine_1.Event.current.mousePosition;\r\n        if (this._styleWindowResize == null) {\r\n            this._styleWindowResize = UnityEngine_1.GUI.skin.box;\r\n        }\r\n        let resizerRect = UnityEngine_1.GUILayoutUtility.GetRect(this._resizerContent, this._styleWindowResize, UnityEngine_1.GUILayout.ExpandWidth(false));\r\n        resizerRect = new UnityEngine_1.Rect(this._thisWindowRect.width - resizerRect.width, this._thisWindowRect.height - resizerRect.height, resizerRect.width, resizerRect.height);\r\n        if (UnityEngine_1.Event.current.type == UnityEngine_1.EventType.MouseDown && resizerRect.Contains(mousePosition)) {\r\n            this._isResizing = true;\r\n            this._resizeStart = new UnityEngine_1.Rect(mousePosition.x, mousePosition.y, this._thisWindowRect.width, this._thisWindowRect.height);\r\n            //Event.current.Use();  // the GUI.Button below will eat the event, and this way it will show its active state\r\n        }\r\n        else if (UnityEngine_1.Event.current.type == UnityEngine_1.EventType.MouseUp && this._isResizing) {\r\n            this._isResizing = false;\r\n        }\r\n        else if (UnityEngine_1.Event.current.type != UnityEngine_1.EventType.MouseDrag && UnityEngine_1.Event.current.isMouse) {\r\n            // if the mouse is over some other window we won't get an event, this just kind of circumvents that by checking the button state directly\r\n            this._isResizing = false;\r\n        }\r\n        else if (this._isResizing) {\r\n            // console.log(\"resizing\");\r\n            this._thisWindowRect.width = Math.max(this._minWindowSize.x, this._resizeStart.width + (mousePosition.x - this._resizeStart.x));\r\n            this._thisWindowRect.height = Math.max(this._minWindowSize.y, this._resizeStart.height + (mousePosition.y - this._resizeStart.y));\r\n            this._thisWindowRect.xMax = Math.min(this._parentWindowRect.width, this._thisWindowRect.xMax); // modifying xMax affects width, not x\r\n            this._thisWindowRect.yMax = Math.min(this._parentWindowRect.height, this._thisWindowRect.yMax); // modifying yMax affects height, not y\r\n        }\r\n        UnityEngine_1.GUI.Button(resizerRect, this._resizerContent, this._styleWindowResize);\r\n        UnityEngine_1.GUI.DragWindow(new UnityEngine_1.Rect(0, 0, 10000, 10000));\r\n    }\r\n    onSceneGui(sv) {\r\n        let id = UnityEngine_1.GUIUtility.GetControlID(UnityEngine_1.FocusType.Passive);\r\n        this._parentWindowRect = sv.position;\r\n        if (this._thisWindowRect.yMax > this._parentWindowRect.height) {\r\n            this._thisWindowRect.yMax = this._parentWindowRect.height;\r\n        }\r\n        this._thisWindowRect = UnityEngine_1.GUILayout.Window(id, this._thisWindowRect, this._onWindowGUI, \"My JS Editor Window\");\r\n        UnityEditor_1.HandleUtility.AddDefaultControl(UnityEngine_1.GUIUtility.GetControlID(UnityEngine_1.FocusType.Passive));\r\n    }\r\n    onMenuTest() {\r\n        console.log(\"menu item test\");\r\n    }\r\n    AddItemsToMenu(menu) {\r\n        menu.AddItem(new UnityEngine_1.GUIContent(\"Test\"), false, this._onMenuTest);\r\n    }\r\n    Update() {\r\n        let d = System_1.DateTime.Now;\r\n        if (this._lastSecond != d.Second) {\r\n            this._lastSecond = d.Second;\r\n            this._lastMinute = d.Minute;\r\n            this._lastHour = d.Hour;\r\n            this.Repaint();\r\n        }\r\n    }\r\n    OnGUI() {\r\n        var _a, _b, _c;\r\n        UnityEditor_1.EditorGUILayout.HelpBox(\"Hello\", UnityEditor_1.MessageType.Info);\r\n        UnityEditor_1.EditorGUILayout.LabelField(\"Prefs.sourceDir\", ((_a = jsb_editor_1.EditorRuntime === null || jsb_editor_1.EditorRuntime === void 0 ? void 0 : jsb_editor_1.EditorRuntime.prefs) === null || _a === void 0 ? void 0 : _a.sourceDir) || \"No sourceDir\");\r\n        UnityEditor_1.EditorGUILayout.LabelField(\"TSConfig.outDir\", ((_c = (_b = jsb_editor_1.EditorRuntime === null || jsb_editor_1.EditorRuntime === void 0 ? void 0 : jsb_editor_1.EditorRuntime.tsconfig) === null || _b === void 0 ? void 0 : _b.compilerOptions) === null || _c === void 0 ? void 0 : _c.outDir) || \"No outDir\");\r\n        UnityEditor_1.EditorGUILayout.LabelField(typeof this.continuousInteger);\r\n        this.continuousInteger = UnityEditor_1.EditorGUILayout.IntField(\"ContinuousInteger\", this.continuousInteger || 0) + 1;\r\n        if (UnityEngine_1.GUILayout.Button(\"I am Javascript\")) {\r\n            console.log(\"Thanks!\", System_1.DateTime.Now);\r\n        }\r\n        let popRect = UnityEditor_1.EditorGUILayout.GetControlRect();\r\n        if (UnityEngine_1.GUI.Button(popRect, \"Pop A Temp Window\")) {\r\n            TempWindow.show(popRect, new UnityEngine_1.Vector2(200, 200));\r\n        }\r\n        if (UnityEngine_1.GUILayout.Button(\"CreateWindow\")) {\r\n            let child = UnityEditor_1.EditorWindow.CreateWindow(MyEditorWindow_1, MyEditorWindow_1);\r\n            if (child) {\r\n                child._windowIndex = this._windowIndex + 1;\r\n                child.titleContent = new UnityEngine_1.GUIContent(\"Blablabla\" + child._windowIndex);\r\n            }\r\n        }\r\n        let w = this.position.width;\r\n        let h = this.position.height;\r\n        let center = new UnityEngine_1.Vector3(w * 0.5, h * 0.5, 0);\r\n        let rotSecond = UnityEngine_1.Quaternion.Euler(0, 0, 360 * this._lastSecond / 60 + 180);\r\n        let rotHour = UnityEngine_1.Quaternion.Euler(0, 0, 360 * this._lastHour / 24 + 180);\r\n        let rotMinute = UnityEngine_1.Quaternion.Euler(0, 0, 360 * this._lastMinute / 60 + 180);\r\n        let lastHandlesColor = UnityEditor_1.Handles.color;\r\n        UnityEditor_1.Handles.color = UnityEngine_1.Color.white;\r\n        if (jsb.isOperatorOverloadingSupported) {\r\n            //@ts-ignore\r\n            UnityEditor_1.Handles.DrawLine(center, center + rotSecond * new UnityEngine_1.Vector3(0, 90, 0));\r\n            //@ts-ignore\r\n            UnityEditor_1.Handles.DrawLine(center, center + rotMinute * new UnityEngine_1.Vector3(0, 75, 0));\r\n            //@ts-ignore\r\n            UnityEditor_1.Handles.DrawLine(center, center + rotHour * new UnityEngine_1.Vector3(0, 60, 0));\r\n        }\r\n        else {\r\n            UnityEditor_1.Handles.DrawLine(center, UnityEngine_1.Vector3.op_Addition(center, UnityEngine_1.Quaternion.op_Multiply(rotSecond, new UnityEngine_1.Vector3(0, 90, 0))));\r\n            UnityEditor_1.Handles.DrawLine(center, UnityEngine_1.Vector3.op_Addition(center, UnityEngine_1.Quaternion.op_Multiply(rotMinute, new UnityEngine_1.Vector3(0, 75, 0))));\r\n            UnityEditor_1.Handles.DrawLine(center, UnityEngine_1.Vector3.op_Addition(center, UnityEngine_1.Quaternion.op_Multiply(rotHour, new UnityEngine_1.Vector3(0, 60, 0))));\r\n        }\r\n        UnityEditor_1.Handles.DrawWireDisc(center, UnityEngine_1.Vector3.back, 100);\r\n        UnityEditor_1.Handles.color = lastHandlesColor;\r\n        UnityEditor_1.EditorGUILayout.BeginHorizontal();\r\n        UnityEditor_1.EditorGUILayout.IntField(this._lastHour);\r\n        UnityEditor_1.EditorGUILayout.IntField(this._lastMinute);\r\n        UnityEditor_1.EditorGUILayout.IntField(this._lastSecond);\r\n        UnityEditor_1.EditorGUILayout.EndHorizontal();\r\n    }\r\n};\r\n__decorate([\r\n    class_decorators_1.ScriptProperty({ type: \"Rect\" })\r\n], MyEditorWindow.prototype, \"_parentWindowRect\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptProperty({ type: \"Rect\" })\r\n], MyEditorWindow.prototype, \"_resizeStart\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptProperty({ type: \"Vector2\" })\r\n], MyEditorWindow.prototype, \"_minWindowSize\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptProperty({ type: \"Rect\" })\r\n], MyEditorWindow.prototype, \"_thisWindowRect\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptProperty({ type: \"bool\" })\r\n], MyEditorWindow.prototype, \"_isResizing\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptProperty({ type: \"int\" })\r\n], MyEditorWindow.prototype, \"_windowIndex\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptInteger()\r\n], MyEditorWindow.prototype, \"continuousInteger\", void 0);\r\nMyEditorWindow = MyEditorWindow_1 = __decorate([\r\n    editor_decorators_1.ScriptEditorWindow()\r\n], MyEditorWindow);\r\nexports.MyEditorWindow = MyEditorWindow;\r\n//# sourceMappingURL=my_editor_window.js.map"
  },
  {
    "path": "Scripts/out/editor/my_test_editor.js",
    "content": "\"use strict\";\r\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n};\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.MyTestEditorWindow = void 0;\r\nconst jsb_1 = require(\"jsb\");\r\nconst System_1 = require(\"System\");\r\nconst UnityEditor_1 = require(\"UnityEditor\");\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst editor_decorators_1 = require(\"plover/editor/editor_decorators\");\r\nconst Example_1 = require(\"Example\");\r\nfunction _onWindowGUI() { }\r\nlet MyTestEditorWindow = class MyTestEditorWindow extends UnityEditor_1.EditorWindow {\r\n    constructor() {\r\n        super(...arguments);\r\n        this._testString = \"\";\r\n        this._sel = 0;\r\n        this._thisWindowRect = new UnityEngine_1.Rect(0, 0, 500, 100);\r\n    }\r\n    Awake() {\r\n        jsb_1.AddCacheString(\"Test\");\r\n        jsb_1.AddCacheString(\"\");\r\n        this._scenes = System_1.Array.CreateInstance(System_1.String, 1);\r\n        this._scenes.SetValue(\"Assets/Examples/Scenes/BasicRun.unity\", 0);\r\n    }\r\n    OnEnable() {\r\n        this.titleContent = new UnityEngine_1.GUIContent(\"Test EditorWindow\");\r\n    }\r\n    OnGUI() {\r\n        this._testString = UnityEditor_1.EditorGUILayout.TextField(\"Test\", this._testString || \"\");\r\n        this._sel = UnityEditor_1.EditorGUILayout.Popup(\"Pick\", this._sel, [\"1\", \"2\", \"3\", \"4\"]);\r\n        if (UnityEngine_1.GUILayout.Button(\"Test Delegate\")) {\r\n            // DelegateTest.UseDelegateInParameter(_onWindowGUI);\r\n            Example_1.DelegateTest.UseDelegateInParameter(function () { });\r\n        }\r\n        if (UnityEngine_1.GUILayout.Button(\"Test Build\")) {\r\n            UnityEditor_1.BuildPipeline.BuildPlayer(this._scenes, \"Build/macos.app\", UnityEditor_1.BuildTarget.StandaloneOSX, UnityEditor_1.BuildOptions.Development);\r\n        }\r\n        let id = UnityEngine_1.GUIUtility.GetControlID(UnityEngine_1.FocusType.Passive);\r\n        this._thisWindowRect = UnityEngine_1.GUILayout.Window(id, this._thisWindowRect, function () { }, \"My JS Editor Window\");\r\n        UnityEditor_1.HandleUtility.AddDefaultControl(UnityEngine_1.GUIUtility.GetControlID(UnityEngine_1.FocusType.Passive));\r\n    }\r\n};\r\nMyTestEditorWindow = __decorate([\r\n    editor_decorators_1.ScriptEditorWindow()\r\n], MyTestEditorWindow);\r\nexports.MyTestEditorWindow = MyTestEditorWindow;\r\n//# sourceMappingURL=my_test_editor.js.map"
  },
  {
    "path": "Scripts/out/example_async.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst Example_1 = require(\"Example\");\r\nconst jsb_1 = require(\"jsb\");\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nfunction delay(secs) {\r\n    return new Promise((resolve, reject) => {\r\n        setTimeout(() => {\r\n            print(\"[async] resolve\");\r\n            resolve(123);\r\n        }, secs * 1000);\r\n    });\r\n}\r\nasync function test() {\r\n    print(\"[async] begin\");\r\n    await delay(3);\r\n    print(\"[async] end\");\r\n    let result = await jsb_1.Yield(Example_1.AsyncTaskTest.GetHostEntryAsync(\"www.baidu.com\"));\r\n    console.log(\"host entry:\", result.HostName);\r\n    await jsb_1.Yield(Example_1.AsyncTaskTest.SimpleTest(3000));\r\n    console.log(\"after AsyncTaskTest.SimpleTest(1000)\");\r\n}\r\nasync function testUnityYieldInstructions() {\r\n    console.warn(\"wait for unity YieldInstruction, begin\");\r\n    await jsb_1.Yield(new UnityEngine_1.WaitForSeconds(3));\r\n    console.warn(\"wait for unity YieldInstruction, end;\", UnityEngine_1.Time.frameCount);\r\n    await jsb_1.Yield(null);\r\n    console.warn(\"wait for unity YieldInstruction, next frame;\", UnityEngine_1.Time.frameCount);\r\n}\r\ntest();\r\ntestUnityYieldInstructions();\r\n//# sourceMappingURL=example_async.js.map"
  },
  {
    "path": "Scripts/out/example_bytes.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst global_1 = require(\"global\");\r\nconst jsb_1 = require(\"jsb\");\r\nif (module == require.main) {\r\n    var takeBuffer = global_1.NoNamespaceClass.MakeBytes();\r\n    var testBuffer = new Uint8Array(jsb_1.ToArrayBuffer(takeBuffer));\r\n    var restoreBytes = jsb_1.ToBytes(testBuffer);\r\n    var backBuffer = new Uint8Array(jsb_1.ToArrayBuffer(global_1.NoNamespaceClass.TestBytes(restoreBytes)));\r\n    print(\"byte[] 处理\");\r\n    backBuffer.forEach(val => print(val));\r\n}\r\n//# sourceMappingURL=example_bytes.js.map"
  },
  {
    "path": "Scripts/out/example_csharp_promise.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst global_1 = require(\"global\");\r\nconst jsb_1 = require(\"jsb\");\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nasync function test_custom_promise1() {\r\n    print(\"想象3秒后弹出的是个对话框\");\r\n    await jsb_1.Yield(new UnityEngine_1.WaitForSeconds(3));\r\n    let go = new UnityEngine_1.GameObject(\"custome.promise.test1\");\r\n    let sb = go.AddComponent(global_1.SampleBehaviour);\r\n    print(\"想象这里是等待用户点击对话框按钮\");\r\n    print(\"完成 (promise in C#):\", await sb.SimpleWait(1));\r\n}\r\nasync function test_custom_promise2() {\r\n    let go = new UnityEngine_1.GameObject(\"custome.promise.test2\");\r\n    let sb = go.AddComponent(global_1.SampleBehaviour);\r\n    await sb.AnotherWait(123);\r\n    console.log(\"after another wait\");\r\n}\r\ntest_custom_promise1();\r\ntest_custom_promise2();\r\n//# sourceMappingURL=example_csharp_promise.js.map"
  },
  {
    "path": "Scripts/out/example_databinding.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst data_binding_1 = require(\"plover/events/data_binding\");\r\nconst dispatcher_1 = require(\"plover/events/dispatcher\");\r\n// data\r\nlet data = {\r\n    name: \"test name\",\r\n    age: 30,\r\n    address: \"somewhere\",\r\n};\r\nlet test = data_binding_1.DataBinding.bind(data);\r\nclass TextInput {\r\n    constructor() {\r\n        this.onchange = new dispatcher_1.Dispatcher();\r\n    }\r\n    get text() { return this._text; }\r\n    set text(value) {\r\n        this._text = value;\r\n        console.log(\"[TextInput] set text:\", value);\r\n        this.onchange.dispatch(this);\r\n    }\r\n}\r\nclass TextInputWatcher extends data_binding_1.Subscriber {\r\n    constructor(model, key, input) {\r\n        super(model, key);\r\n        this._input = input;\r\n        this._input.onchange.on(this, this.onchange);\r\n    }\r\n    update(value) {\r\n        this._input.text = value;\r\n    }\r\n    onchange(input) {\r\n        this.value = input.text;\r\n    }\r\n}\r\nlet input = new TextInput();\r\nlet sub = data_binding_1.DataBinding.subscribe(TextInputWatcher, test, \"name\", input);\r\ntest.name = \"temp name\";\r\nconsole.log(\"[数据变更]\", test.name, input.text);\r\ninput.text = \"输入文字\";\r\nconsole.log(\"[界面变更]\", test.name, input.text);\r\nsub.unsubscribe();\r\nconsole.log(test.name);\r\ntest.name = \"new name\";\r\nconsole.log(test.name);\r\nconsole.log(test.age);\r\nObject.keys(test).forEach(k => console.log(\"model access:\", k));\r\n//# sourceMappingURL=example_databinding.js.map"
  },
  {
    "path": "Scripts/out/example_delegate.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.run = void 0;\r\nconst Example_1 = require(\"Example\");\r\nfunction run() {\r\n    let actions = new Example_1.DelegateTest();\r\n    print(\"testcase: 无参数的委托\");\r\n    console.log(\"********** add\");\r\n    actions.onAction(\"add\", function () {\r\n        console.log(\"js action call\");\r\n    });\r\n    console.log(\"********** call\");\r\n    actions.CallAction();\r\n    actions.onAction(\"set\", null);\r\n    console.log(\"********** after clear, call again\");\r\n    actions.CallAction();\r\n    print(\"testcase: 带参数的委托\");\r\n    actions.onActionWithArgs(\"set\", (a, b, c) => {\r\n        console.log(a, b, c);\r\n    });\r\n    actions.CallActionWithArgs(\"string\", 123, 456);\r\n    actions.onFunc(\"set\", v => v * 2);\r\n    console.log(actions.CallFunc(111));\r\n    actions.onFunc(\"set\", undefined);\r\n    print(\"testcase: instance event\");\r\n    actions.onEvent(\"add\", v => print(\"instance event test 1:\", v));\r\n    function instanceEventHandler(v) { print(\"instance event test 2:\", v); }\r\n    actions.onEvent(\"add\", instanceEventHandler);\r\n    actions.DipatchEvent(123);\r\n    actions.onEvent(\"remove\", instanceEventHandler);\r\n    actions.DipatchEvent(123);\r\n    print(\"testcase: static event\");\r\n    Example_1.DelegateTest.onStaticEvent(\"add\", v => print(\"static event test 1:\", v));\r\n    function staticEventHandler(v) { print(\"static event test 2:\", v); }\r\n    Example_1.DelegateTest.onStaticEvent(\"add\", staticEventHandler);\r\n    Example_1.DelegateTest.DipatchStaticEvent(123);\r\n    Example_1.DelegateTest.onStaticEvent(\"remove\", staticEventHandler);\r\n    Example_1.DelegateTest.DipatchStaticEvent(123);\r\n    try {\r\n        print(\"testcase: delegate with ref/out parameters\");\r\n        actions.complexCall(\"add\", (b, a, v) => {\r\n            a.value += b;\r\n            v.value = 999;\r\n            return 789;\r\n        });\r\n        actions.complexCall2(\"add\", v => {\r\n            v.value.Set(v.value.x * 2, v.value.y * 2, v.value.z * 2);\r\n        });\r\n        actions.TestComplexCall();\r\n    }\r\n    catch (err) {\r\n        console.warn(err);\r\n        console.warn(\"dynamic code emitting doesn't work properly\");\r\n    }\r\n}\r\nexports.run = run;\r\nif (module == require.main) {\r\n    run();\r\n}\r\n//# sourceMappingURL=example_delegate.js.map"
  },
  {
    "path": "Scripts/out/example_disposable.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst Example_1 = require(\"Example\");\r\nfunction test() {\r\n    let obj = new Example_1.DisposableObject();\r\n    // 垃圾回收时将自动执行 obj.Dispose (JS主线程)\r\n    obj = undefined;\r\n}\r\nconsole.log(\"before test()\");\r\ntest();\r\nconsole.log(\"after test()\");\r\n//# sourceMappingURL=example_disposable.js.map"
  },
  {
    "path": "Scripts/out/example_editor_window.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst my_editor_window_1 = require(\"./editor/my_editor_window\");\r\nconst UnityEditor_1 = require(\"UnityEditor\");\r\nUnityEditor_1.EditorWindow.GetWindow(my_editor_window_1.MyEditorWindow);\r\n//# sourceMappingURL=example_editor_window.js.map"
  },
  {
    "path": "Scripts/out/example_hotfix.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst jsb = require(\"jsb\");\r\nlet HotfixTest = jsb.Import(\"HotfixTest\");\r\ntry {\r\n    // 反射导入的类型默认收到访问保护 (hotfix 后保护会被迫移除)\r\n    print(HotfixTest.static_value);\r\n}\r\ncatch (err) {\r\n    console.warn(\"默认拒绝访问私有成员\", err);\r\n}\r\ntry {\r\n    jsb.hotfix.replace_single(\"HotfixTest\", \".ctor\", function () {\r\n        print(\"[HOTFIX][JS] 构造函数\");\r\n    });\r\n    jsb.hotfix.replace_single(\"HotfixTest\", \"Foo\", function (x) {\r\n        print(\"[HOTFIX][JS] HotfixTest.Foo [private] this.value = \", this.value);\r\n        return typeof x === \"number\" ? x + 3 : x + \"~~~\";\r\n    });\r\n    jsb.hotfix.before_single(\"HotfixTest\", \"AnotherStaticCall\", function () {\r\n        print(\"[HOTFIX][JS] HotfixTest.AnotherStaticCall 在 C# 执行前插入 JS 代码\");\r\n    });\r\n    jsb.hotfix.replace_single(\"HotfixTest\", \"SimpleStaticCall\", function () {\r\n        this.AnotherStaticCall();\r\n        print(\"[HOTFIX][JS] HotfixTest.SimpleStaticCall [private] this.static_value = \", this.static_value);\r\n    });\r\n}\r\ncatch (err) {\r\n    console.warn(\"替换失败, 是否执行过dll注入?\");\r\n}\r\nlet hotfix = new HotfixTest();\r\nprint(\"[HOTFIX][JS] hotfix.Foo(1) 返回值:\", hotfix.Foo(1));\r\nprint(\"[HOTFIX][JS] hotfix.Foo(1) 返回值:\", hotfix.Foo(\"good day\"));\r\nHotfixTest.SimpleStaticCall();\r\n//# sourceMappingURL=example_hotfix.js.map"
  },
  {
    "path": "Scripts/out/example_hotload.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst data_1 = require(\"./data\");\r\nconsole.log(\"read data: \", data_1.test_data.name);\r\n//# sourceMappingURL=example_hotload.js.map"
  },
  {
    "path": "Scripts/out/example_jsx.js",
    "content": "\"use strict\";\r\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n};\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.MyWidgetTest = void 0;\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst bridge_1 = require(\"plover/jsx/bridge\");\r\nconst JSX = require(\"plover/jsx/element\");\r\nconst vue_1 = require(\"plover/jsx/vue\");\r\nconst class_decorators_1 = require(\"plover/runtime/class_decorators\");\r\nlet MyWidgetTest = class MyWidgetTest extends bridge_1.JSXWidgetBridge {\r\n    get data() { return this._data; }\r\n    Awake() {\r\n        this._data = vue_1.ViewModel.create({ name: \"Unity\", tick: 0 });\r\n        this._widget =\r\n            JSX.createElement(\"widget\", { class: this },\r\n                JSX.createElement(\"text\", { name: \"label\", text: \"Hello {{this.name}} {{this.tick}}\" }));\r\n        this._timer = setInterval(() => {\r\n            this._data.tick++;\r\n        }, 1000);\r\n        this._data.tick++;\r\n    }\r\n    OnDestroy() {\r\n        super.OnDestroy();\r\n        clearInterval(this._timer);\r\n    }\r\n};\r\nMyWidgetTest = __decorate([\r\n    class_decorators_1.ScriptType()\r\n], MyWidgetTest);\r\nexports.MyWidgetTest = MyWidgetTest;\r\nlet parent = UnityEngine_1.GameObject.Find(\"/Canvas\").transform;\r\nlet go = UnityEngine_1.Object.Instantiate(UnityEngine_1.Resources.Load(\"prefab/jsx_test_ui\"));\r\ngo.transform.SetParent(parent);\r\nlet rect = go.GetComponent(UnityEngine_1.RectTransform);\r\nrect.anchorMin = UnityEngine_1.Vector2.zero;\r\nrect.anchorMax = UnityEngine_1.Vector2.one;\r\nrect.anchoredPosition = UnityEngine_1.Vector2.zero;\r\nconsole.log(\"load\", go, go.AddComponent(MyWidgetTest));\r\n//# sourceMappingURL=example_jsx.js.map"
  },
  {
    "path": "Scripts/out/example_main.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nprint(\"isMain?\", module == require.main);\r\nconst Example_1 = require(\"Example\");\r\nconst jsb = require(\"jsb\");\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\n// import { fib } from \"./fib_module.js\";\r\nconst fib_1 = require(\"./fib\");\r\nconsole.assert(true, \"will not print\");\r\nconsole.assert(false, \"assert!!!\");\r\nprint(jsb.engine, jsb.version);\r\nprint(Example_1.DelegateTest);\r\nprint(Example_1.DelegateTest.InnerTest.hello);\r\ntry {\r\n    // 强行传入一个错误的参数 (期望参数为无参)\r\n    // @ts-ignore\r\n    Example_1.DelegateTest.GetArray(\"error\");\r\n}\r\ncatch (err) {\r\n    console.warn(err + '\\n' + err.stack);\r\n}\r\ntry {\r\n    // 注意: 因为效率上的考虑, 简单类型是不会抛异常的, 比如 Camera.main.orthographicSize = \"abc\" 结果 = 0\r\n    //       除非传入 any, 否则大部分情况下ts编译将提示类型错误\r\n    //       可能后续会通过 DEBUG 宏等进行更严格的检查\r\n    // 强行传入一个错误类型参数\r\n    // @ts-ignore\r\n    UnityEngine_1.Camera.main.transparencySortAxis = \"wrong value\";\r\n}\r\ncatch (err) {\r\n    console.warn(err);\r\n}\r\n// 一维数组的操作\r\nconsole.log(\"ValueTest.values1[2] = \", Example_1.ValueTest.values1.GetValue(2));\r\n// 多维数组的操作\r\nconsole.log(\"ValueTest.values2[0, 1] = \", Example_1.ValueTest.values2.GetValue(0, 1));\r\nprint(\"fib:\", fib_1.fib(12));\r\nsetTimeout(() => {\r\n    print(\"[timeout] test\");\r\n}, 1500);\r\nsetInterval(() => {\r\n    console.log(\"interval tick\");\r\n}, 1000 * 10);\r\nprint(\"require.require:\");\r\nprint(\"require 1:\", require(\"./req_test1\").test);\r\nprint(\"require 2:\", require(\"./req_test1\").test);\r\nprint(\"require 3:\", require(\"./req_test1\").test);\r\n// 通过 require 直接读 json\r\nprint(\"json:\", require(\"../config/data.json\").name);\r\n// Object.keys(require.cache).forEach(key => console.log(\"module loaded:\", key));\r\n// print(\"require (node_modules): \", require(\"blink1\").test);\r\n// print(\"require (node_modules): \", require(\"blink3\").test);\r\n// Optional Chaining/Nullish coalescing Operator 需要较新的 tsc 编译, 或者直接在 js 代码中使用\r\n// // Optional Chaining\r\n// let a: any = 1;\r\n// print(\"Optional Chaining\", a?.b?.c === undefined);\r\n// // Nullish coalescing Operator\r\n// print(\"Nullish coalescing Operator:\", a?.b ?? \"ok\");\r\n// const protobuf = require(\"protobufjs\");\r\n// print(\"protobufjs:\", protobuf);\r\njsb.DoFile(\"dofile_test\");\r\ntry {\r\n    jsb.DoFile(\"not_exists.file\");\r\n}\r\ncatch (e) {\r\n    console.warn(e);\r\n}\r\nglobalThis[\"testGlobalVar\"] = \"test\";\r\nObject.keys(require.cache).forEach(k => console.log(\"require.cache entry:\", k));\r\n//# sourceMappingURL=example_main.js.map"
  },
  {
    "path": "Scripts/out/example_matterjs.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst matter_js_1 = require(\"matter-js\");\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nlet engine = matter_js_1.Engine.create({\r\n    gravity: { y: -0.1 }\r\n});\r\nlet runner = matter_js_1.Runner.create();\r\nclass BoxUpdater extends UnityEngine_1.MonoBehaviour {\r\n    Update() {\r\n        this.transform.localRotation = UnityEngine_1.Quaternion.Euler(0, 0, this.body.angle * 180 / Math.PI);\r\n        this.transform.localPosition = new UnityEngine_1.Vector3(this.body.position.x, this.body.position.y, 0);\r\n    }\r\n}\r\nlet index = 0;\r\nfunction add_box(x, y, w, h) {\r\n    let box = matter_js_1.Bodies.rectangle(x, y, w, h);\r\n    let go = UnityEngine_1.GameObject.CreatePrimitive(UnityEngine_1.PrimitiveType.Cube);\r\n    let updater = go.AddComponent(BoxUpdater);\r\n    updater.body = matter_js_1.Composite.add(engine.world, box).bodies[index++];\r\n    go.transform.localScale = new UnityEngine_1.Vector3(w, h, 1);\r\n}\r\nfunction add_static_box(x, y, w, h) {\r\n    let box = matter_js_1.Bodies.rectangle(x, y, w, h, { isStatic: true });\r\n    let go = UnityEngine_1.GameObject.CreatePrimitive(UnityEngine_1.PrimitiveType.Cube);\r\n    let v = matter_js_1.Composite.add(engine.world, box).bodies[index++].position;\r\n    go.transform.localPosition = new UnityEngine_1.Vector3(v.x, v.y, 0);\r\n    go.transform.localScale = new UnityEngine_1.Vector3(w, h, 1);\r\n}\r\nadd_box(4, 100, 8, 8);\r\nadd_box(6, 70, 8, 8);\r\nadd_static_box(0, -100, 400, 6);\r\nmatter_js_1.Runner.run(runner, engine);\r\nUnityEngine_1.Camera.main.orthographicSize = 100;\r\n//# sourceMappingURL=example_matterjs.js.map"
  },
  {
    "path": "Scripts/out/example_monobehaviour.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\ndebugger;\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst sample_monobehaviour_1 = require(\"./components/sample_monobehaviour\");\r\nif (module == require.main) {\r\n    print(\"example_monobehaviour\");\r\n    let gameObject = new UnityEngine_1.GameObject();\r\n    let comp1 = gameObject.AddComponent(sample_monobehaviour_1.MySubClass);\r\n    let comp2 = gameObject.AddComponent(sample_monobehaviour_1.MyClass);\r\n    let cube = UnityEngine_1.GameObject.CreatePrimitive(UnityEngine_1.PrimitiveType.Cube);\r\n    cube.transform.localPosition = new UnityEngine_1.Vector3(1, 2, 3);\r\n    cube.transform.localRotation = UnityEngine_1.Quaternion.Euler(30, 60, 90);\r\n    cube.transform.localScale = new UnityEngine_1.Vector3(2, 3, 4);\r\n    comp1.vv = 1;\r\n    comp2.vv = 2;\r\n    comp1.play();\r\n    {\r\n        let results = gameObject.GetComponents(sample_monobehaviour_1.MySubClass);\r\n        results.forEach(it => console.log(\"GetComponents(MySubClass):\", it.vv));\r\n    }\r\n    {\r\n        let results = gameObject.GetComponents(sample_monobehaviour_1.MyClass);\r\n        results.forEach(it => console.log(\"GetComponents(MyClass):\", it.vv));\r\n    }\r\n    let ps = UnityEngine_1.GameObject.Find(\"/Particle System\");\r\n    if (!ps) {\r\n        ps = new UnityEngine_1.GameObject(\"Particle System\");\r\n        ps.AddComponent(UnityEngine_1.ParticleSystem);\r\n    }\r\n    console.log(\"Particle System:\", ps);\r\n    if (ps) {\r\n        ps.AddComponent(sample_monobehaviour_1.RotateBehaviour);\r\n    }\r\n    {\r\n        let sphere = UnityEngine_1.GameObject.CreatePrimitive(UnityEngine_1.PrimitiveType.Sphere);\r\n        sphere.transform.localScale = new UnityEngine_1.Vector3(2, 2, 2);\r\n        sphere.transform.TestWithScriptObject(function () {\r\n            console.warn(\"TestWithScriptObject\");\r\n        });\r\n        sphere.AddComponent(sample_monobehaviour_1.Something5Behaviour);\r\n    }\r\n}\r\n//# sourceMappingURL=example_monobehaviour.js.map"
  },
  {
    "path": "Scripts/out/example_operator_overload.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst jsb = require(\"jsb\");\r\nif (module == require.main) {\r\n    let support = jsb.isOperatorOverloadingSupported;\r\n    console.log(\"IsOperatorOverloadingSupported:\", support);\r\n    // operators\r\n    {\r\n        let vec1 = new UnityEngine_1.Vector3(1, 2, 3);\r\n        let vec2 = new UnityEngine_1.Vector3(9, 8, 7);\r\n        // @ts-ignore\r\n        let vec3 = support ? vec1 + vec2 : UnityEngine_1.Vector3.op_Addition(vec1, vec2);\r\n        // @ts-ignore\r\n        let vec4 = support ? vec1 + vec2 : UnityEngine_1.Vector3.op_Addition(vec1, vec2);\r\n        console.log(\"v1 = \", vec1);\r\n        console.log(\"v2 = \", vec2);\r\n        console.log(\"v1 + v2 =\", vec3);\r\n        // @ts-ignore\r\n        console.log(\"v3 * 2 =\", support ? vec3 * 2 : UnityEngine_1.Vector3.op_Multiply(vec3, 2));\r\n        // @ts-ignore\r\n        console.log(\"2 * v3=\", support ? 2 * vec3 : UnityEngine_1.Vector3.op_Multiply(2, vec3));\r\n        // @ts-ignore\r\n        console.log(\"v3 / 2 =\", support ? vec3 / 2 : UnityEngine_1.Vector3.op_Division(vec3, 2));\r\n        console.log(\"v3 == v4:\", support ? vec3 == vec4 : UnityEngine_1.Vector3.op_Equality(vec3, vec4));\r\n    }\r\n    {\r\n        let c1 = new UnityEngine_1.Color(0, 0, 0, 1);\r\n        let c2 = new UnityEngine_1.Color(0.5, 0.1, 0.2, 0);\r\n        // @ts-ignore\r\n        let r = support ? c2 / 3 : UnityEngine_1.Color.op_Division(c2, 3);\r\n        print(c1, c2, r);\r\n    }\r\n}\r\n//# sourceMappingURL=example_operator_overload.js.map"
  },
  {
    "path": "Scripts/out/example_pbjs_parse.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst pbjs = require(\"protobufjs\");\r\nconst System_IO_1 = require(\"System.IO\");\r\nconsole.log(\"please run 'npm install' at first if 'protobufjs' module can not be resolved\");\r\n// 直接解析的方式载入 proto 定义\r\nlet awesome = System_IO_1.File.ReadAllText(\"Assets/Examples/Data/awesome.proto\");\r\nlet pb = pbjs.parse(awesome);\r\nlet proto = pb.root.resolveAll();\r\nfor (let pb of proto.nestedArray) {\r\n    console.log(\"read reflected protobuf message type:\", pb);\r\n    let nestedArray = pb.nestedArray;\r\n    if (typeof nestedArray !== \"undefined\") {\r\n        for (let pb_nested of nestedArray) {\r\n            console.log(\"pb_nested:\", pb_nested);\r\n        }\r\n    }\r\n}\r\nlet type = proto.lookupType(\"awesomepackage.AwesomeMessage\");\r\nlet msg = type.fromObject({\r\n    awesomeField: \"hello, protobufjs\",\r\n});\r\nlet data = type.encode(msg).finish();\r\nconsole.log(\"encoded data (len):\", data.byteLength);\r\nlet decMsg = type.decode(data);\r\nconsole.log(\"decoded message:\", decMsg[\"awesomeField\"]);\r\n//# sourceMappingURL=example_pbjs_parse.js.map"
  },
  {
    "path": "Scripts/out/example_pbjs_static.js",
    "content": "\"use strict\";\r\n/*\r\n开发过程中可以使用 Default FileSystem 正常依赖 node_modules 中的库时\r\n当需要发布到 Resources/Assetbundle 时, 这种情况下需要使用 webpack 等打包工具将脚本依赖全部打包, 即可在最终环境中使用第三方库\r\n*/\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst aw = require(\"../protogen/pb.bundle\");\r\n/*\r\n具体参见 protobufjs 文档\r\nnpm: https://www.npmjs.com/package/protobufjs\r\ngithub: https://github.com/protobufjs/protobuf.js\r\n\r\npbjs -t static-module -w commonjs -o pb.bundle.js awesome.proto\r\npbts -o pb.bundle.d.ts pb.bundle.js\r\n*/\r\nconsole.log(\"please run 'npm install' at first if 'protobufjs' module can not be resolved\");\r\n// 预生成代码的方式使用 proto 定义\r\nlet msg = aw.awesomepackage.AwesomeMessage.create({\r\n    awesomeField: \"hello, protobufjs\",\r\n});\r\nconsole.log(msg.awesomeField);\r\nlet data = aw.awesomepackage.AwesomeMessage.encode(msg).finish();\r\nconsole.log(\"encoded data (len):\", data.byteLength);\r\nlet decMsg = aw.awesomepackage.AwesomeMessage.decode(data);\r\nconsole.log(\"decoded message:\", decMsg.awesomeField);\r\n//# sourceMappingURL=example_pbjs_static.js.map"
  },
  {
    "path": "Scripts/out/example_ref_out.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst global_1 = require(\"global\");\r\nfunction execute() {\r\n    if (module == require.main) {\r\n        let g = { value: 1 };\r\n        let x = {};\r\n        let z = {};\r\n        let y = 666;\r\n        global_1.NoNamespaceClass.TestRefOut(g, x, y, z);\r\n        console.assert(x.value == y * 1, \"x\");\r\n        console.assert(z.value == y + 1, \"z\");\r\n        console.assert(g.value == x.value + z.value, \"g\");\r\n        print(\"ref/out:\", g.value, x.value, z.value);\r\n    }\r\n    // a type description field for Out/Ref is optional but helpful to select the right overloaded method\r\n    if (module == require.main) {\r\n        let x = { type: Number };\r\n        let z = { type: Number };\r\n        let y = 233;\r\n        global_1.NoNamespaceClass.TestOut(x, y, z);\r\n        console.assert(x.value == y, \"x == y ?\");\r\n        console.assert(z.value == y, \"z == y ?\");\r\n        print(\"out:\", x.value, typeof x.value, z.value, typeof z.value);\r\n    }\r\n    if (module == require.main) {\r\n        let x = { type: String };\r\n        let z = { type: String };\r\n        let y = 999;\r\n        global_1.NoNamespaceClass.TestOut(x, 999, z);\r\n        console.assert(x.value == y.toString(), \"x == y ?\");\r\n        console.assert(z.value == y.toString(), \"z == y ?\");\r\n        print(\"out:\", x.value, typeof x.value, z.value, typeof z.value);\r\n    }\r\n}\r\nexecute();\r\n//# sourceMappingURL=example_ref_out.js.map"
  },
  {
    "path": "Scripts/out/example_reflect.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst Example_1 = require(\"Example\");\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst System_1 = require(\"System\");\r\nif (module == require.main) {\r\n    let camera = UnityEngine_1.GameObject.Find(\"/Main Camera\").GetComponent(UnityEngine_1.Camera);\r\n    // 通过反射方式建立未导出类型的交互\r\n    let unknown = Example_1.DelegateTest.GetNotExportedClass();\r\n    print(unknown.value);\r\n    print(unknown.GetType().value2);\r\n    print(unknown.Add(12, 21));\r\n    print(\"Equals(unknown, unknown):\", System_1.Object.Equals(unknown, unknown));\r\n    print(\"Equals(unknown, camera):\", System_1.Object.Equals(unknown, camera));\r\n    print(\"ReferenceEquals(unknown, unknown):\", System_1.Object.ReferenceEquals(unknown, unknown));\r\n    print(\"ReferenceEquals(unknown, camera):\", System_1.Object.ReferenceEquals(unknown, camera));\r\n}\r\n//# sourceMappingURL=example_reflect.js.map"
  },
  {
    "path": "Scripts/out/example_reflectbind_helloworld.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst Example_1 = require(\"Example\");\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconsole.log(\"hello, world\");\r\nUnityEngine_1.Debug.Log(\"hello, world\");\r\nlet go = new UnityEngine_1.GameObject(\"Happy Bot\");\r\nconsole.log(\"go.transform = \", go.transform);\r\nconsole.log(\"go.transform.localPosition.x = \", go.transform.localPosition.x);\r\nlet v = new UnityEngine_1.Vector3(1, 1, 1);\r\nv.x = 2;\r\nconsole.log(\"v.x = \", v.x);\r\nconsole.log(\"v.magnitude = \", v.magnitude);\r\ngo.transform.localPosition = new UnityEngine_1.Vector3(1, 1, 1);\r\nExample_1.DelegateTest.onStaticActionWithArgs(\"set\", (a1, a2, a3) => console.log(\"delegate in js:\", a1, a2, a3));\r\nExample_1.DelegateTest.CallStaticActionWithArgs(\"hello\", 123, 999);\r\nlet delegateTest = new Example_1.DelegateTest();\r\ndelegateTest.onActionWithArgs(\"add\", (a1, a2, a3) => console.log(\"delegate in js1:\", a1, a2, a3));\r\ndelegateTest.onActionWithArgs(\"add\", (a1, a2, a3) => console.log(\"delegate in js2:\", a1, a2, a3));\r\ndelegateTest.CallActionWithArgs(\"hello\", 123, 999);\r\nclass HelloBehaviour extends UnityEngine_1.MonoBehaviour {\r\n    Awake() {\r\n        console.log(\"Hello Behaviour Awake!\");\r\n    }\r\n    Greet() {\r\n        console.log(\"Good day!\");\r\n    }\r\n}\r\ngo.AddComponent(HelloBehaviour);\r\nlet helloBehaviour = go.GetComponent(HelloBehaviour);\r\nhelloBehaviour.Greet();\r\nconsole.log(go.AddComponent);\r\nlet box = go.AddComponent(UnityEngine_1.BoxCollider);\r\nconsole.log(box);\r\n//# sourceMappingURL=example_reflectbind_helloworld.js.map"
  },
  {
    "path": "Scripts/out/example_scriptable_object.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst my_scriptable_object_1 = require(\"./my_scriptable_object\");\r\nconsole.log(\"============ Load ScriptableObject from Resources ============\");\r\nlet js_data = UnityEngine_1.Resources.Load(\"data/js_data\");\r\nif (js_data) {\r\n    console.log(\"typeof:\", typeof js_data);\r\n    console.log(\"type check:\", js_data instanceof my_scriptable_object_1.MyScriptableObject);\r\n    console.log(\"type values:\", js_data.value1, js_data.value2);\r\n}\r\nelse {\r\n    console.error(\"failed to load js_data, please create the asset at first.\");\r\n}\r\ntry {\r\n    console.log(\"============ ScriptableObject.CreateInstance ============ 111\");\r\n    let so = UnityEngine_1.ScriptableObject.CreateInstance(my_scriptable_object_1.MyScriptableObject);\r\n    if (so) {\r\n        // Resources.FindObjectsOfTypeAll can also properly process script types now\r\n        let results = UnityEngine_1.Resources.FindObjectsOfTypeAll(my_scriptable_object_1.MyScriptableObject);\r\n        do {\r\n            if (results) {\r\n                let len = results.length;\r\n                if (len > 0) {\r\n                    for (let i = 0; i < len; i++) {\r\n                        console.log(\"!!! find object:\", results[i]);\r\n                    }\r\n                    break;\r\n                }\r\n            }\r\n            console.warn(\"something wrong, no object found.\");\r\n        } while (false);\r\n        for (let i of UnityEngine_1.Resources.FindObjectsOfTypeAll(UnityEngine_1.Camera)) {\r\n            console.log(\"!!! camera\", i);\r\n        }\r\n        so.value3 = new UnityEngine_1.Vector3(1, 2, 3);\r\n        so.value2 = \"Hello\";\r\n        console.log(\"value1:\", so.Process());\r\n        UnityEngine_1.Object.DestroyImmediate(so);\r\n    }\r\n    else {\r\n        console.error(\"fail to ScriptableObject.CreateInstance\");\r\n    }\r\n}\r\ncatch (err) {\r\n    console.error(\"fail to ScriptableObject.CreateInstance\", err);\r\n}\r\n//# sourceMappingURL=example_scriptable_object.js.map"
  },
  {
    "path": "Scripts/out/example_string_cache.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst Example_1 = require(\"Example\");\r\nconst jsb = require(\"jsb\");\r\n/*\r\n    jsb.AddCacheString is available to use to avoid unnecessary string allocations on frequently translating strings between Javascript and C#\r\n    NOTE: remove string from cache with jsb.RemoveCacheString\r\n*/\r\n{\r\n    console.log(\"string cache test:\");\r\n    let n = 100000;\r\n    let start = 0;\r\n    let end = 0;\r\n    let str = \"testing, testing, testing, testing, testing, testing, testing, testing\";\r\n    start = Date.now();\r\n    for (let i = 0; i < n; i++) {\r\n        Example_1.ValueTest.Foo(str);\r\n    }\r\n    end = Date.now();\r\n    console.log(\"time1:\", (end - start) / 1000);\r\n    jsb.AddCacheString(str);\r\n    start = Date.now();\r\n    for (let i = 0; i < n; i++) {\r\n        Example_1.ValueTest.Foo(str);\r\n    }\r\n    end = Date.now();\r\n    console.log(\"time2:\", (end - start) / 1000);\r\n}\r\n//# sourceMappingURL=example_string_cache.js.map"
  },
  {
    "path": "Scripts/out/example_timer.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst jsb = require(\"jsb\");\r\nlet _id = 0;\r\nfunction allocId() {\r\n    return ++_id;\r\n}\r\nlet all = 600;\r\nlet act = 0;\r\nfor (let i = 0; i < all; i++) {\r\n    let n = i;\r\n    let d1 = (n * 10 * Math.floor(UnityEngine_1.Random.Range(100, 10000))) % (3 * 60 * 1000);\r\n    let e1 = d1 + jsb.Now();\r\n    setTimeout(t1 => {\r\n        if (n % 10 == 0) {\r\n            all++;\r\n            let d2 = Math.floor(UnityEngine_1.Random.Range(1000 * 1, 1000 * 60 * 2));\r\n            let e2 = d2 + jsb.Now();\r\n            setTimeout(t2 => {\r\n                act++;\r\n                let n2 = jsb.Now();\r\n                let x2 = n2 - e2;\r\n                console.log(`    > ${n} ${t2.id} => Now: ${n2} Exp: ${e2} Delay: ${d2} Delta: ${x2} Act: ${act}/${all}`);\r\n            }, d2, { id: allocId() });\r\n        }\r\n        act++;\r\n        let n1 = jsb.Now();\r\n        let x1 = n1 - e1;\r\n        console.log(`TA ${n} ${t1.id} => Now: ${n1} Exp: ${e1} Delay: ${d1} Delta: ${x1} Act: ${act}/${all}`);\r\n    }, d1, { id: allocId() });\r\n}\r\n//# sourceMappingURL=example_timer.js.map"
  },
  {
    "path": "Scripts/out/example_unity.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst jsb_1 = require(\"jsb\");\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst sample_monobehaviour_1 = require(\"./components/sample_monobehaviour\");\r\nif (module == require.main) {\r\n    let go = new UnityEngine_1.GameObject(\"test\");\r\n    console.log(go.name);\r\n    go.name = \"testing\";\r\n    console.log(go.name);\r\n    async function destroy() {\r\n        await jsb_1.Yield(new UnityEngine_1.WaitForSeconds(5));\r\n        UnityEngine_1.Object.Destroy(go);\r\n        //! 机制原因, 无法直接利用 Object == 重载, 可以用 op_Implicit 判定 UnityEngine.Object 是否被销毁\r\n        console.log(\"after destroy, go == null?\", UnityEngine_1.Object.op_Implicit(go));\r\n    }\r\n    destroy();\r\n    let camera = UnityEngine_1.GameObject.Find(\"/Main Camera\").GetComponent(UnityEngine_1.Camera);\r\n    let arr = camera.GetComponents(UnityEngine_1.Camera);\r\n    print(\"array.length:\", arr.length);\r\n    print(\"array[0]:\", arr[0] == camera);\r\n    console.log(\"camera.name:\", camera.name);\r\n    UnityEngine_1.Debug.LogWarningFormat(\"blablabla... {0}\", 123);\r\n    let testPrefab = UnityEngine_1.Resources.Load(\"prefab/test\");\r\n    if (testPrefab) {\r\n        let testGameObject = UnityEngine_1.Object.Instantiate(testPrefab);\r\n        let testMyClass = testGameObject.GetComponent(sample_monobehaviour_1.MyClass);\r\n        console.log(testMyClass);\r\n    }\r\n    else {\r\n        console.warn(\"Resources/prefab/test.prefab not found\");\r\n    }\r\n}\r\n//# sourceMappingURL=example_unity.js.map"
  },
  {
    "path": "Scripts/out/example_valuetype.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst Example_1 = require(\"Example\");\r\nconst array_proxy_1 = require(\"./experimental/array_proxy\");\r\nlet u = new UnityEngine_1.Vector3(1, 2, 3);\r\nconsole.assert(u.x == 1, \"u.x should equals to 1\");\r\nu.Normalize();\r\nconsole.assert(Math.abs(u.magnitude - 1) < 0.00001, \"u.magnitude should equals to 1 after being normalized\");\r\nlet v1 = new UnityEngine_1.Vector3(0, 0, 0);\r\nlet start = Date.now();\r\nfor (let i = 1; i < 200000; i++) {\r\n    v1.Set(i, i, i);\r\n    v1.Normalize();\r\n}\r\nconsole.log(\"js/vector3/normailize\", (Date.now() - start) / 1000);\r\nlet null_value = null;\r\nlet undefined_value = undefined;\r\nconsole.assert(!(null_value instanceof UnityEngine_1.Vector3), \"null instanceof Vector3\");\r\nconsole.assert(!(undefined_value instanceof UnityEngine_1.Vector3), \"undefined instanceof Vector3\");\r\nconsole.assert(v1 instanceof UnityEngine_1.Vector3, \"(correct value) instanceof Vector3\");\r\nconsole.assert(!(UnityEngine_1.Vector2.zero instanceof UnityEngine_1.Vector3), \"(wrong value) instanceof Vector3\");\r\n// everytime you access Vector3.zero will return a new copy\r\nconsole.assert(UnityEngine_1.Vector3.zero.magnitude == 0, \"Vector3.zero\");\r\nUnityEngine_1.Vector3.zero.Set(1, 2, 3);\r\nconsole.assert(UnityEngine_1.Vector3.zero.magnitude == 0, \"Vector3.zero\");\r\n/** experimental\r\n *    CreateJSArrayProxy will be merged into value-conversion layer if possible. All of the System.Array objects will be treated as js array in d.ts after this feature implemented.\r\n */\r\nlet array1 = array_proxy_1.CreateJSArrayProxy(Example_1.ArrayTest.values1);\r\n// size change will cause side-effect, array proxy target will detach from the original csharp variable reference\r\n// array1.push(3, 4, 5, 6); \r\n// ArrayTest.values1 = GetUnderlyingObject(array1);\r\narray1[0] = 123;\r\nconsole.log(\"length\", array1.length);\r\nconsole.log(\"join\", array1.join());\r\nconsole.log(\"reduce\", array1.reduce((p, c) => p + c));\r\nconsole.log(array_proxy_1.GetUnderlyingArray(array1));\r\nconsole.log(\"eq\", Example_1.ArrayTest.values1 === array_proxy_1.GetUnderlyingArray(array1));\r\nconsole.log(\"len\", Example_1.ArrayTest.values1.Length);\r\nconsole.log(\"[1]\", Example_1.ArrayTest.values1.GetValue(0));\r\n//# sourceMappingURL=example_valuetype.js.map"
  },
  {
    "path": "Scripts/out/example_websocket.js",
    "content": "let ws = new WebSocket(\"ws://127.0.0.1:8080/websocket\", \"default\");\r\nconsole.log(\"websocket connecting:\", ws.url);\r\nws.onopen = function () {\r\n    console.log(\"[ws.onopen]\", ws.readyState);\r\n    let count = 0;\r\n    setInterval(function () {\r\n        ws.send(\"websocket message test\" + count++);\r\n    }, 1000);\r\n};\r\nws.onclose = function () {\r\n    console.log(\"[ws.onclose]\", ws.readyState);\r\n};\r\nws.onerror = function (err) {\r\n    console.log(\"[ws.onerror]\", err);\r\n};\r\nws.onmessage = function (msg) {\r\n    console.log(\"[ws.recv]\", msg);\r\n};\r\n//# sourceMappingURL=example_websocket.js.map"
  },
  {
    "path": "Scripts/out/example_worker.js",
    "content": "let worker = new Worker(\"worker\");\r\nlet messageId = 0;\r\nlet messageQueue = {};\r\n//TODO: 目前无法传递 C# 对象 (对象引用ID不共享)\r\nworker.onmessage = function (e) {\r\n    let data = e.data;\r\n    let p = messageQueue[data.id];\r\n    if (typeof p !== \"undefined\") {\r\n        p(data.result);\r\n    }\r\n};\r\nlet a = 1;\r\nlet b = 2;\r\nasync function test() {\r\n    a++;\r\n    b++;\r\n    let r = await remoteAdd(a, b);\r\n    console.log(`add(${a}, ${b}) = ${r}`);\r\n}\r\nasync function remoteAdd(a, b) {\r\n    let id = messageId++;\r\n    return new Promise(resolve => {\r\n        messageQueue[id] = resolve;\r\n        worker.postMessage({\r\n            \"id\": id,\r\n            \"method\": \"add\",\r\n            \"args\": [a, b]\r\n        });\r\n    });\r\n}\r\nconsole.log(\"test\");\r\ntest();\r\nsetInterval(() => test(), 3000);\r\n//# sourceMappingURL=example_worker.js.map"
  },
  {
    "path": "Scripts/out/example_xhr.js",
    "content": "let xhr = new XMLHttpRequest();\r\n// xhr.open(\"GET\", \"http://127.0.0.1:8080/windows/checksum.txt\");\r\nxhr.open(\"GET\", \"https://www.baidu.com\");\r\nxhr.timeout = 3000;\r\nxhr.onerror = function (e) {\r\n    console.error(e);\r\n};\r\nxhr.onreadystatechange = function () {\r\n    console.log(\"readyState:\", xhr.readyState);\r\n    if (xhr.readyState !== 4) {\r\n        return;\r\n    }\r\n    console.log(\"status:\", xhr.status);\r\n    if (xhr.status == 200) {\r\n        console.log(\"responseText:\", xhr.responseText);\r\n    }\r\n};\r\nxhr.send();\r\nconsole.log(\"after send\");\r\n//# sourceMappingURL=example_xhr.js.map"
  },
  {
    "path": "Scripts/out/example_xlsx.js",
    "content": "\"use strict\";\r\n/*\r\n开发过程中可以使用 Default FileSystem 正常依赖 node_modules 中的库时\r\n当需要发布到 Resources/Assetbundle 时, 这种情况下需要使用 webpack 等打包工具将脚本依赖全部打包, 即可在最终环境中使用第三方库\r\n*/\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\n//NOTE: 此处 xlsx 在 package.json 中以 devDependencies 方式依赖, 仅开发环境有效. \r\n//      可以改为 dev, 自行按需调整.\r\n//      如运行报错, 请先确认是否已安装依赖包 (npm install 即可).\r\nconsole.log(\"please run 'npm install' at first if 'xlsx' module can not be resolved\");\r\nconst jsb = require(\"jsb\");\r\nconst System_IO_1 = require(\"System.IO\");\r\nconst xlsx = require(\"xlsx\");\r\nlet filename = \"Assets/Examples/Data/test.xlsx\";\r\nlet bytes = System_IO_1.File.ReadAllBytes(filename);\r\nlet data = jsb.ToArrayBuffer(bytes);\r\nlet wb = xlsx.read(data, { type: \"buffer\" });\r\nconsole.log(\"read excel:\", filename);\r\nfor (var sheetIndex in wb.SheetNames) {\r\n    var sheetName = wb.SheetNames[sheetIndex];\r\n    console.log(`read sheet: ${sheetName}`);\r\n    var sheet = wb.Sheets[sheetName];\r\n    let csv = xlsx.utils.sheet_to_csv(sheet);\r\n    console.log(\"to_csv:\", csv);\r\n    var range = xlsx.utils.decode_range(sheet[\"!ref\"]);\r\n    for (var row = range.s.r; row <= range.e.r; row++) {\r\n        for (var col = range.s.c; col <= range.e.c; col++) {\r\n            var cell = sheet[xlsx.utils.encode_cell({ c: col, r: row })];\r\n            if (cell) {\r\n                console.log(cell.v);\r\n            }\r\n        }\r\n    }\r\n}\r\n//# sourceMappingURL=example_xlsx.js.map"
  },
  {
    "path": "Scripts/out/experimental/array_proxy.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.CreateJSArrayProxy = exports.GetUnderlyingArray = void 0;\r\nconst jsb = require(\"jsb\");\r\nconst $GetLength = jsb.ArrayUtils.GetLength;\r\nconst $SetValue = jsb.ArrayUtils.SetValue;\r\nconst $GetValue = jsb.ArrayUtils.GetValue;\r\nconst $RemoveAt = jsb.ArrayUtils.RemoveAt;\r\nconst $Insert = jsb.ArrayUtils.Insert;\r\nconst UnderlyingValueAccess = Symbol.for(\"Underlying Native Array\");\r\nfunction GetUnderlyingArray(p) {\r\n    return p[UnderlyingValueAccess];\r\n}\r\nexports.GetUnderlyingArray = GetUnderlyingArray;\r\nfunction CreateJSArrayProxy(target) {\r\n    let _members = {\r\n        /**\r\n         * Returns the value of the first element in the array where predicate is true, and undefined\r\n         * otherwise.\r\n         * @param predicate find calls predicate once for each element of the array, in ascending\r\n         * order, until it finds one where predicate returns true. If such an element is found, find\r\n         * immediately returns that element value. Otherwise, find returns undefined.\r\n         * @param thisArg If provided, it will be used as the this value for each invocation of\r\n         * predicate. If it is not provided, undefined is used instead.\r\n         */\r\n        // find<S extends T>(predicate: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined;\r\n        \"find\": function (predicate, thisArg) {\r\n            let copy = new Array(...this);\r\n            for (let i = 0, n = copy.length; i < n; ++i) {\r\n                let v = copy[i];\r\n                if (Boolean(predicate.call(thisArg, v, i, this))) {\r\n                    return v;\r\n                }\r\n            }\r\n            // return new Array(...this).find(predicate, thisArg);\r\n        },\r\n        /**\r\n         * Returns the index of the first element in the array where predicate is true, and -1\r\n         * otherwise.\r\n         * @param predicate find calls predicate once for each element of the array, in ascending\r\n         * order, until it finds one where predicate returns true. If such an element is found,\r\n         * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n         * @param thisArg If provided, it will be used as the this value for each invocation of\r\n         * predicate. If it is not provided, undefined is used instead.\r\n         */\r\n        \"findIndex\": function (predicate, thisArg) {\r\n            let copy = new Array(...this);\r\n            for (let i = 0, n = copy.length; i < n; ++i) {\r\n                let v = copy[i];\r\n                if (Boolean(predicate.call(thisArg, v, i, this))) {\r\n                    return i;\r\n                }\r\n            }\r\n            return -1;\r\n            // return new Array(...this).findIndex(predicate, thisArg);\r\n        },\r\n        /**\r\n         * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n         * @param value value to fill array section with\r\n         * @param start index to start filling the array at. If start is negative, it is treated as\r\n         * length+start where length is the length of the array.\r\n         * @param end index to stop filling the array at. If end is negative, it is treated as\r\n         * length+end.\r\n         */\r\n        fill(value, start, end) {\r\n            let n = $GetLength(target);\r\n            if (typeof start === \"undefined\") {\r\n                start = 0;\r\n            }\r\n            else if (start < 0) {\r\n                start = n + start;\r\n            }\r\n            if (typeof end === \"undefined\") {\r\n                end = n;\r\n            }\r\n            else if (end < 0) {\r\n                end = n + end;\r\n            }\r\n            for (let i = start; i < end; ++i) {\r\n                $SetValue(target, i, value);\r\n            }\r\n            return this;\r\n        },\r\n        /**\r\n         * Returns the this object after copying a section of the array identified by start and end\r\n         * to the same array starting at position target\r\n         * @param target If target is negative, it is treated as length+target where length is the\r\n         * length of the array.\r\n         * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n         * is treated as length+end.\r\n         * @param end If not specified, length of the this object is used as its default value.\r\n         */\r\n        \"copyWithin\": function (target_, start, end) {\r\n            let c = new Array(...this);\r\n            c.copyWithin(target_, start, end);\r\n            for (let i = 0, n = c.length; i < n; ++i) {\r\n                $SetValue(target, i, c[i]);\r\n            }\r\n            return this;\r\n        },\r\n        /** es2015.iterable */\r\n        [Symbol.iterator]: function () {\r\n            let i = 0;\r\n            return {\r\n                next: function () {\r\n                    let currentIndex = i++;\r\n                    return currentIndex < $GetLength(target) ? {\r\n                        value: $GetValue(target, currentIndex),\r\n                        done: false,\r\n                    } : { done: true };\r\n                },\r\n            };\r\n        },\r\n        /** es2015.iterable */\r\n        \"entries\": function () {\r\n            return {\r\n                [Symbol.iterator]: function () {\r\n                    let i = 0;\r\n                    return {\r\n                        next: function () {\r\n                            let currentIndex = i++;\r\n                            return currentIndex < $GetLength(target) ? {\r\n                                value: [currentIndex, $GetValue(target, currentIndex)],\r\n                                done: false,\r\n                            } : { done: true };\r\n                        },\r\n                    };\r\n                }\r\n            };\r\n        },\r\n        /** es2015.iterable */\r\n        \"keys\": function () {\r\n            return {\r\n                [Symbol.iterator]: function () {\r\n                    let i = 0;\r\n                    return {\r\n                        next: function () {\r\n                            let currentIndex = i++;\r\n                            return currentIndex < $GetLength(target) ? {\r\n                                value: currentIndex,\r\n                                done: false,\r\n                            } : { done: true };\r\n                        },\r\n                    };\r\n                }\r\n            };\r\n        },\r\n        /** es2015.iterable */\r\n        \"values\": function () {\r\n            return {\r\n                [Symbol.iterator]: function () {\r\n                    let i = 0;\r\n                    return {\r\n                        next: function () {\r\n                            let currentIndex = i++;\r\n                            return currentIndex < $GetLength(target) ? {\r\n                                value: $GetValue(target, currentIndex),\r\n                                done: false,\r\n                            } : { done: true };\r\n                        },\r\n                    };\r\n                }\r\n            };\r\n        },\r\n        /**\r\n         * es5\r\n         * Returns a string representation of an array.\r\n         */\r\n        \"toString\": function () {\r\n            return `ArrayWrapper(${this.length})`;\r\n        },\r\n        /**\r\n         * es5\r\n         * Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.\r\n         */\r\n        \"toLocaleString\": function () {\r\n            return `ArrayWrapper(${this.length})`;\r\n        },\r\n        /**\r\n         * es5\r\n         * Removes the last element from an array and returns it.\r\n         * If the array is empty, undefined is returned and the array is not modified.\r\n         */\r\n        \"pop\": function () {\r\n            if ($GetLength(target) > 0) {\r\n                let v = $GetValue(target, $GetLength(target) - 1);\r\n                $RemoveAt(target, $GetLength(target) - 1);\r\n                return v;\r\n            }\r\n        },\r\n        /**\r\n         * es5\r\n         * Appends new elements to the end of an array, and returns the new length of the array.\r\n         * @param items New elements to add to the array.\r\n         */\r\n        \"push\": function (...items) {\r\n            let n = $GetLength(target);\r\n            for (let i = 0; i < items.length; i++) {\r\n                console.log(\"set value\", i, n + 1);\r\n                $SetValue(target, n + i, items[i]);\r\n            }\r\n        },\r\n        /**\r\n         * es5\r\n         * Combines two or more arrays.\r\n         * This method returns a new array without modifying any existing arrays.\r\n         * @param items Additional arrays and/or items to add to the end of the array.\r\n         */\r\n        \"concat\": function (...items) {\r\n            let r = new Array(...this);\r\n            for (let ii = 0, il = items.length; ii < il; ++ii) {\r\n                let e = items[ii];\r\n                if (typeof e === \"object\" && e instanceof Array) {\r\n                    for (let si = 0, sl = e.length; si < sl; ++si) {\r\n                        r.push(e[si]);\r\n                    }\r\n                }\r\n                else {\r\n                    r.push(e);\r\n                }\r\n            }\r\n            return r;\r\n        },\r\n        /**\r\n         * es5\r\n         * Adds all the elements of an array into a string, separated by the specified separator string.\r\n         * @param separator A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.\r\n         */\r\n        \"join\": function (separator) {\r\n            if (typeof separator === \"undefined\") {\r\n                separator = \",\";\r\n            }\r\n            let r = \"\";\r\n            for (let i = 0, n = $GetLength(target); i < n; ++i) {\r\n                if (i != n - 1) {\r\n                    r += $GetValue(target, i) + separator;\r\n                }\r\n                else {\r\n                    r += $GetValue(target, i);\r\n                }\r\n            }\r\n            return r;\r\n        },\r\n        /**\r\n         * es5\r\n         * Reverses the elements in an array in place.\r\n         * This method mutates the array and returns a reference to the same array.\r\n         */\r\n        \"reverse\": function () {\r\n            let n = $GetLength(target);\r\n            let m = Math.floor(n / 2);\r\n            for (let i = 0; i < m; ++i) {\r\n                let i2 = n - i - 1;\r\n                let t1 = $GetValue(target, i2);\r\n                let t2 = $GetValue(target, i);\r\n                $SetValue(target, i, t1);\r\n                $SetValue(target, i2, t2);\r\n            }\r\n            return this;\r\n        },\r\n        /**\r\n         * es5\r\n         * Removes the first element from an array and returns it.\r\n         * If the array is empty, undefined is returned and the array is not modified.\r\n         */\r\n        \"shift\": function () {\r\n            if ($GetLength(target) > 0) {\r\n                let f = $GetValue(target, 0);\r\n                $RemoveAt(target, 0);\r\n                return f;\r\n            }\r\n        },\r\n        /**\r\n         * es5\r\n         * Returns a copy of a section of an array.\r\n         * For both start and end, a negative index can be used to indicate an offset from the end of the array.\r\n         * For example, -2 refers to the second to last element of the array.\r\n         * @param start The beginning index of the specified portion of the array.\r\n         * If start is undefined, then the slice begins at index 0.\r\n         * @param end The end index of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n         * If end is undefined, then the slice extends to the end of the array.\r\n         */\r\n        \"slice\": function (start, end) {\r\n            let n = $GetLength(target);\r\n            let r = [];\r\n            if (typeof start === \"undefined\") {\r\n                start = 0;\r\n            }\r\n            else if (start < 0) {\r\n                start = n + start;\r\n            }\r\n            if (typeof end === \"undefined\") {\r\n                end = 0;\r\n            }\r\n            else if (end < 0) {\r\n                end = n + end;\r\n            }\r\n            if (start < end) {\r\n                for (let i = start; i < end; ++i) {\r\n                    r.push($GetValue(target, i));\r\n                }\r\n            }\r\n            return r;\r\n        },\r\n        /**\r\n         * es5\r\n         * Sorts an array in place.\r\n         * This method mutates the array and returns a reference to the same array.\r\n         * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n         * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\r\n         * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.\r\n         * ```ts\r\n         * [11,2,22,1].sort((a, b) => a - b)\r\n         * ```\r\n         */\r\n        \"sort\": function (compareFn) {\r\n            let n = $GetLength(target);\r\n            if (n > 1) {\r\n                let r = new Array(...this).sort(compareFn);\r\n                for (let i = 0; i < n; ++i) {\r\n                    $SetValue(target, i, r[i]);\r\n                }\r\n            }\r\n            return this;\r\n        },\r\n        /**\r\n         * es5\r\n         * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.\r\n         * @param start The zero-based location in the array from which to start removing elements.\r\n         * @param deleteCount The number of elements to remove.\r\n         * @param items Elements to insert into the array in place of the deleted elements.\r\n         * @returns An array containing the elements that were deleted.\r\n         */\r\n        \"splice\": function (start, deleteCount, ...items) {\r\n            let len = $GetLength(target);\r\n            let res = [];\r\n            if (start < len) {\r\n                let m = len - start;\r\n                if (typeof deleteCount === \"number\" && m > deleteCount) {\r\n                    m = deleteCount;\r\n                }\r\n                for (let i = 0; i < m; ++i) {\r\n                    res.push($GetValue(target, start));\r\n                    $RemoveAt(target, start);\r\n                }\r\n                for (let i = 0, c = items.length; i < c; ++i) {\r\n                    $Insert(target, start, items[c - i - 1]);\r\n                }\r\n            }\r\n            else {\r\n                for (let i = 0, c = items.length; i < c; ++i) {\r\n                    $Insert(target, len, items[c - i - 1]);\r\n                }\r\n            }\r\n            return res;\r\n        },\r\n        /**\r\n         * es5\r\n         * Inserts new elements at the start of an array, and returns the new length of the array.\r\n         * @param items Elements to insert at the start of the array.\r\n         */\r\n        \"unshift\": function (...items) {\r\n            for (let i = 0, n = items.length; i < n; ++i) {\r\n                $Insert(target, 0, items[n - i - 1]);\r\n            }\r\n            return $GetLength(target);\r\n        },\r\n        /**\r\n         * es5\r\n         * Returns the index of the first occurrence of a value in an array, or -1 if it is not present.\r\n         * @param searchElement The value to locate in the array.\r\n         * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.\r\n         */\r\n        \"indexOf\": function (searchElement, fromIndex) {\r\n            if (typeof fromIndex !== \"number\") {\r\n                fromIndex = 0;\r\n            }\r\n            else {\r\n                fromIndex = fromIndex <= 0 ? 0 : Math.floor(fromIndex);\r\n            }\r\n            for (let i = fromIndex, n = $GetLength(target); i < n; ++i) {\r\n                if ($GetValue(target, i) == searchElement) {\r\n                    return i;\r\n                }\r\n            }\r\n            return -1;\r\n        },\r\n        /**\r\n         * es5\r\n         * Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.\r\n         * @param searchElement The value to locate in the array.\r\n         * @param fromIndex The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.\r\n         */\r\n        \"lastIndexOf\": function (searchElement, fromIndex) {\r\n            if (typeof fromIndex !== \"number\") {\r\n                fromIndex = $GetLength(target) - 1;\r\n            }\r\n            else {\r\n                if (fromIndex < 0) {\r\n                    fromIndex = $GetLength(target) + fromIndex;\r\n                }\r\n            }\r\n            for (let i = fromIndex; i >= 0; --i) {\r\n                if ($GetValue(target, i) == searchElement) {\r\n                    return i;\r\n                }\r\n            }\r\n            return -1;\r\n        },\r\n        /**\r\n         * es5\r\n         * Determines whether all the members of an array satisfy the specified test.\r\n         * @param predicate A function that accepts up to three arguments. The every method calls\r\n         * the predicate function for each element in the array until the predicate returns a value\r\n         * which is coercible to the Boolean value false, or until the end of the array.\r\n         * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n         * If thisArg is omitted, undefined is used as the this value.\r\n         */\r\n        \"every\": function (predicate, thisArg) {\r\n            for (let i = 0, n = $GetLength(target); i < n; ++i) {\r\n                let item = $GetValue(target, i);\r\n                if (!Boolean(predicate.call(thisArg, item, i, this))) {\r\n                    return false;\r\n                }\r\n            }\r\n            return true;\r\n        },\r\n        /**\r\n         * es5\r\n         * Determines whether the specified callback function returns true for any element of an array.\r\n         * @param predicate A function that accepts up to three arguments. The some method calls\r\n         * the predicate function for each element in the array until the predicate returns a value\r\n         * which is coercible to the Boolean value true, or until the end of the array.\r\n         * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n         * If thisArg is omitted, undefined is used as the this value.\r\n         */\r\n        \"some\": function (predicate, thisArg) {\r\n            for (let i = 0, n = $GetLength(target); i < n; ++i) {\r\n                let item = $GetValue(target, i);\r\n                if (Boolean(predicate.call(thisArg, item, i, this))) {\r\n                    return true;\r\n                }\r\n            }\r\n            return false;\r\n        },\r\n        /**\r\n         * es5\r\n         * Performs the specified action for each element in an array.\r\n         * @param callbackfn  A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.\r\n         * @param thisArg  An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\r\n         */\r\n        \"forEach\": function (callbackfn, thisArg) {\r\n            if (typeof thisArg !== \"undefined\") {\r\n                for (let i = 0, n = $GetLength(target); i < n; i++) {\r\n                    callbackfn.call(thisArg, $GetValue(target, i), i, this);\r\n                }\r\n            }\r\n            else {\r\n                for (let i = 0, n = $GetLength(target); i < n; i++) {\r\n                    callbackfn($GetValue(target, i), i, this);\r\n                }\r\n            }\r\n        },\r\n        /**\r\n         * es5\r\n         * Calls a defined callback function on each element of an array, and returns an array that contains the results.\r\n         * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\r\n         * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\r\n         */\r\n        map(callbackfn, thisArg) {\r\n            let n = $GetLength(target);\r\n            let r = new Array(n);\r\n            for (let i = 0; i < n; i++) {\r\n                let e = callbackfn.call(thisArg, $GetValue(target, i), i, this);\r\n                r.push(e);\r\n            }\r\n            return r;\r\n        },\r\n        /**\r\n         * es5\r\n         * Returns the elements of an array that meet the condition specified in a callback function.\r\n         * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.\r\n         * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.\r\n         */\r\n        \"filter\": function (predicate, thisArg) {\r\n            let res = [];\r\n            for (let i = 0, n = $GetLength(target); i < n; ++i) {\r\n                let item = $GetValue(target, i);\r\n                if (Boolean(predicate.call(thisArg, item, i, this))) {\r\n                    res.push(item);\r\n                }\r\n            }\r\n            return res;\r\n        },\r\n        /**\r\n         * es5\r\n         * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n         * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\r\n         * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n         */\r\n        \"reduce\": function (callbackfn, initialValue) {\r\n            let n = $GetLength(target);\r\n            if (n > 0) {\r\n                let previousValue, currentValue;\r\n                if (typeof initialValue !== \"undefined\") {\r\n                    previousValue = initialValue;\r\n                    for (let i = 0; i < n; ++i) {\r\n                        currentValue = $GetValue(target, i);\r\n                        previousValue = callbackfn(previousValue, currentValue, i, this);\r\n                    }\r\n                    return previousValue;\r\n                }\r\n                else {\r\n                    previousValue = $GetValue(target, 0);\r\n                    for (let i = 1; i < n; ++i) {\r\n                        currentValue = $GetValue(target, i);\r\n                        previousValue = callbackfn(previousValue, currentValue, i, this);\r\n                    }\r\n                    return previousValue;\r\n                }\r\n            }\r\n            return initialValue;\r\n        },\r\n        /**\r\n         * es5\r\n         * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n         * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\r\n         * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n         */\r\n        \"reduceRight\": function (callbackfn, initialValue) {\r\n            let n = $GetLength(target);\r\n            if (n > 0) {\r\n                let previousValue, currentValue;\r\n                if (typeof initialValue !== \"undefined\") {\r\n                    previousValue = initialValue;\r\n                    for (let i = n - 1; i >= 0; --i) {\r\n                        currentValue = $GetValue(target, i);\r\n                        previousValue = callbackfn(previousValue, currentValue, i, this);\r\n                    }\r\n                    return previousValue;\r\n                }\r\n                else {\r\n                    previousValue = $GetValue(target, n - 1);\r\n                    for (let i = n - 2; i >= 0; --i) {\r\n                        currentValue = $GetValue(target, i);\r\n                        previousValue = callbackfn(previousValue, currentValue, i, this);\r\n                    }\r\n                    return previousValue;\r\n                }\r\n            }\r\n            return initialValue;\r\n        },\r\n    };\r\n    let _getter = {\r\n        [UnderlyingValueAccess]: function () {\r\n            return target;\r\n        },\r\n        \"length\": function () {\r\n            return $GetLength(target);\r\n        },\r\n    };\r\n    let _setter = {\r\n        \"length\": function (value) {\r\n            throw new Error(\"unsupported\");\r\n        },\r\n    };\r\n    return new Proxy(target, {\r\n        get(target, p, receiver) {\r\n            if (typeof p === \"string\" && p.length > 0) {\r\n                let c = p.charCodeAt(0);\r\n                if (c >= 48 && c <= 57) {\r\n                    let index = Number.parseInt(p);\r\n                    return $GetValue(target, index);\r\n                }\r\n            }\r\n            let mf = Object.getOwnPropertyDescriptor(_members, p) && _members[p];\r\n            if (typeof mf !== \"undefined\") {\r\n                return mf;\r\n            }\r\n            let mp = Object.getOwnPropertyDescriptor(_getter, p) && _getter[p];\r\n            if (typeof mp !== \"undefined\") {\r\n                return mp();\r\n            }\r\n            console.warn(\"unknown property\", p);\r\n        },\r\n        set(target, p, value, receiver) {\r\n            if (typeof p === \"string\" && p.length > 0) {\r\n                let c = p.charCodeAt(0);\r\n                if (c >= 48 && c <= 57) {\r\n                    let index = Number.parseInt(p);\r\n                    $SetValue(target, index, value);\r\n                    return true;\r\n                }\r\n            }\r\n            let mp = Object.getOwnPropertyDescriptor(_setter, p) && _setter[p];\r\n            if (typeof mp !== \"undefined\") {\r\n                mp(value);\r\n                return true;\r\n            }\r\n            return false;\r\n        },\r\n        // getPrototypeOf(target: MyArray): object {\r\n        //     return Array.prototype;\r\n        // },\r\n        ownKeys(target) {\r\n            return new Proxy({}, {\r\n                get(_1, p) {\r\n                    if (typeof p === \"string\") {\r\n                        if (p === \"length\") {\r\n                            return $GetLength(target);\r\n                        }\r\n                    }\r\n                    return p;\r\n                },\r\n            });\r\n        },\r\n        getOwnPropertyDescriptor(target, p) {\r\n            return { enumerable: true, configurable: true, value: this[p] };\r\n        },\r\n    });\r\n}\r\nexports.CreateJSArrayProxy = CreateJSArrayProxy;\r\n//# sourceMappingURL=array_proxy.js.map"
  },
  {
    "path": "Scripts/out/experimental_gtype.js",
    "content": "// declare abstract class TWrapper<T> extends System.Object {\r\n//     constructor(obj: T)\r\n//     GetValue(): T\r\n//     SetValue(obj: T)\r\n//     static GetIntWrapper(): TWrapper<number>\r\n// }\r\n// declare class TWrapper_Int32 extends TWrapper<number> {\r\n// }\r\n// declare class TWrapper_Vector3 extends TWrapper<UnityEngine.Vector3> {\r\n// }\r\n// new TWrapper_Int32(1);\r\n//# sourceMappingURL=experimental_gtype.js.map"
  },
  {
    "path": "Scripts/out/fib.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.fib = void 0;\r\n/* fib module */\r\nfunction fib(n) {\r\n    if (n <= 0)\r\n        return 0;\r\n    else if (n == 1)\r\n        return 1;\r\n    else\r\n        return fib(n - 1) + fib(n - 2);\r\n}\r\nexports.fib = fib;\r\n//# sourceMappingURL=fib.js.map"
  },
  {
    "path": "Scripts/out/game/editor/king_human_controller_inspector.js",
    "content": "\"use strict\";\r\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n};\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.KingHumanControllerInspector = void 0;\r\nconst UnityEditor_1 = require(\"UnityEditor\");\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst editor_decorators_1 = require(\"plover/editor/editor_decorators\");\r\nconst king_human_controller_1 = require(\"../king_human_controller\");\r\nlet KingHumanControllerInspector = class KingHumanControllerInspector extends UnityEditor_1.Editor {\r\n    OnInspectorGUI() {\r\n        let p = this.target;\r\n        // EditorUtil.draw(p);\r\n        UnityEditor_1.EditorGUI.BeginChangeCheck();\r\n        p.animator = UnityEditor_1.EditorGUILayout.ObjectField(\"Animator\", p.animator, UnityEngine_1.Animator, true);\r\n        p.moveSpeed = UnityEditor_1.EditorGUILayout.FloatField(\"Move Speed\", p.moveSpeed);\r\n        if (!p.nestedValue) {\r\n            p.nestedValue = new king_human_controller_1.MyNestedPlainObject();\r\n        }\r\n        p.nestedValue.nestedString = UnityEditor_1.EditorGUILayout.TextField(\"nestedString\", p.nestedValue.nestedString);\r\n        p.nestedValue.nestedVector3 = UnityEditor_1.EditorGUILayout.Vector3Field(\"nestedVector3\", p.nestedValue.nestedVector3);\r\n        if (UnityEngine_1.GUILayout.Button(\"Add Position\")) {\r\n            if (p.nestedValue.positions == null) {\r\n                p.nestedValue.positions = [];\r\n            }\r\n            p.nestedValue.positions.push(UnityEngine_1.Vector2.zero);\r\n            UnityEditor_1.EditorUtility.SetDirty(p);\r\n        }\r\n        let positionCount = p.nestedValue.positions != null ? p.nestedValue.positions.length : 0;\r\n        for (let i = 0; i < positionCount; i++) {\r\n            p.nestedValue.positions[i] = UnityEditor_1.EditorGUILayout.Vector2Field(\"Position\", p.nestedValue.positions[i] || UnityEngine_1.Vector2.zero);\r\n        }\r\n        if (UnityEditor_1.EditorGUI.EndChangeCheck()) {\r\n            UnityEditor_1.EditorUtility.SetDirty(p);\r\n        }\r\n        if (UnityEngine_1.GUILayout.Button(\"Speak\")) {\r\n            console.log(\"Hello, world 666 !\");\r\n        }\r\n        if (UnityEngine_1.GUILayout.Button(\"Attack\")) {\r\n            p.animator.Play(\"Attack\", 0, 1);\r\n        }\r\n        if (UnityEngine_1.GUILayout.Button(\"Idle\")) {\r\n            p.animator.Play(\"Idle\", 0, 1);\r\n        }\r\n    }\r\n};\r\nKingHumanControllerInspector = __decorate([\r\n    editor_decorators_1.ScriptEditor(king_human_controller_1.KingHumanController)\r\n], KingHumanControllerInspector);\r\nexports.KingHumanControllerInspector = KingHumanControllerInspector;\r\n//# sourceMappingURL=king_human_controller_inspector.js.map"
  },
  {
    "path": "Scripts/out/game/king_human_controller.js",
    "content": "\"use strict\";\r\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n};\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.KingHumanController = exports.MyNestedPlainObject = void 0;\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst class_decorators_1 = require(\"plover/runtime/class_decorators\");\r\nlet MyNestedPlainObject = class MyNestedPlainObject {\r\n    constructor() {\r\n        this.nestedString = \"nestedString\";\r\n        this.nestedVector3 = UnityEngine_1.Vector3.zero;\r\n    }\r\n};\r\n__decorate([\r\n    class_decorators_1.ScriptString()\r\n], MyNestedPlainObject.prototype, \"nestedString\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptProperty({ type: \"Vector3\" })\r\n], MyNestedPlainObject.prototype, \"nestedVector3\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptProperty({ type: \"Vector2\" })\r\n], MyNestedPlainObject.prototype, \"positions\", void 0);\r\nMyNestedPlainObject = __decorate([\r\n    class_decorators_1.ScriptSerializable()\r\n], MyNestedPlainObject);\r\nexports.MyNestedPlainObject = MyNestedPlainObject;\r\nlet KingHumanController = class KingHumanController extends UnityEngine_1.MonoBehaviour {\r\n    constructor() {\r\n        super(...arguments);\r\n        this.moveSpeed = 1.8;\r\n        this.moving = false;\r\n    }\r\n    Awake() {\r\n        // this.transform.localScale = new Vector3(1, 1, 1);\r\n        // this.transform.localPosition = new Vector3(1.0, 2.2, 0);\r\n    }\r\n    OnAfterDeserialize() {\r\n        // 发生脚本重载时不会触发 Awake 所以在此处赋值\r\n        this.spriteRenderer = this.GetComponent(UnityEngine_1.SpriteRenderer);\r\n    }\r\n    Update() {\r\n        if (UnityEngine_1.Input.anyKey) {\r\n            let hori = 0;\r\n            let vert = 0;\r\n            if (UnityEngine_1.Input.GetKey(UnityEngine_1.KeyCode.A)) {\r\n                hori = -1;\r\n            }\r\n            else if (UnityEngine_1.Input.GetKey(UnityEngine_1.KeyCode.D)) {\r\n                hori = 1;\r\n            }\r\n            // if (Input.GetKey(KeyCode.W)) {\r\n            //     vert = 1;\r\n            // } else if (Input.GetKey(KeyCode.S)) {\r\n            //     vert = -1;\r\n            // }\r\n            if (hori != 0 || vert != 0) {\r\n                let scale = UnityEngine_1.Time.deltaTime * this.moveSpeed;\r\n                this.transform.Translate(hori * scale, vert * scale, 0);\r\n                if (hori != 0) {\r\n                    this.spriteRenderer.flipX = hori < 0;\r\n                }\r\n                if (!this.moving) {\r\n                    this.moving = true;\r\n                    this.animator.Play(\"Run\", 0);\r\n                    // console.log(\"go1\");\r\n                }\r\n            }\r\n            else {\r\n                if (this.moving) {\r\n                    this.moving = false;\r\n                    this.animator.Play(\"Idle\", 0);\r\n                }\r\n            }\r\n        }\r\n        else {\r\n            if (this.moving) {\r\n                this.moving = false;\r\n                this.animator.Play(\"Idle\", 0);\r\n            }\r\n        }\r\n    }\r\n};\r\n__decorate([\r\n    class_decorators_1.ScriptObject({ editorOnly: true })\r\n], KingHumanController.prototype, \"animator\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptNumber()\r\n], KingHumanController.prototype, \"moveSpeed\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptProperty({ type: MyNestedPlainObject })\r\n], KingHumanController.prototype, \"nestedValue\", void 0);\r\nKingHumanController = __decorate([\r\n    class_decorators_1.ScriptType()\r\n], KingHumanController);\r\nexports.KingHumanController = KingHumanController;\r\n//# sourceMappingURL=king_human_controller.js.map"
  },
  {
    "path": "Scripts/out/game_demo.js",
    "content": "\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nif (!UnityEngine_1.GameObject.Find(\"/game_stage\")) {\r\n    let path = \"prefab/game_stage\";\r\n    let prefab = UnityEngine_1.Resources.Load(path);\r\n    if (prefab) {\r\n        let inst = UnityEngine_1.Object.Instantiate(prefab);\r\n        inst.name = \"game_stage\";\r\n    }\r\n    else {\r\n        console.error(\"game stage not found:\", path);\r\n    }\r\n}\r\n//# sourceMappingURL=game_demo.js.map"
  },
  {
    "path": "Scripts/out/my_scriptable_object.js",
    "content": "\"use strict\";\r\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n};\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.MyScriptableObject = void 0;\r\nconst UnityEngine_1 = require(\"UnityEngine\");\r\nconst class_decorators_1 = require(\"plover/runtime/class_decorators\");\r\nlet MyScriptableObject = class MyScriptableObject extends UnityEngine_1.ScriptableObject {\r\n    constructor() {\r\n        super(...arguments);\r\n        this.value1 = 1;\r\n        this.value2 = \"hello\";\r\n        this.value3 = UnityEngine_1.Vector3.zero;\r\n        this.value5 = [];\r\n    }\r\n    Process() {\r\n        return `${this.value2} ${this.value3}`;\r\n    }\r\n    Reset() {\r\n        this.value1 = 0;\r\n        this.value2 = \"\";\r\n        this.value3 = UnityEngine_1.Vector3.zero;\r\n        this.value5 = [1, 2, 3];\r\n    }\r\n};\r\n__decorate([\r\n    class_decorators_1.ScriptNumber()\r\n], MyScriptableObject.prototype, \"value1\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptString()\r\n], MyScriptableObject.prototype, \"value2\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptProperty({ type: \"Vector3\" })\r\n], MyScriptableObject.prototype, \"value3\", void 0);\r\n__decorate([\r\n    class_decorators_1.ScriptNumber()\r\n], MyScriptableObject.prototype, \"value5\", void 0);\r\nMyScriptableObject = __decorate([\r\n    class_decorators_1.ScriptAsset()\r\n], MyScriptableObject);\r\nexports.MyScriptableObject = MyScriptableObject;\r\n//# sourceMappingURL=my_scriptable_object.js.map"
  },
  {
    "path": "Scripts/out/req_test1.js",
    "content": "var e2 = require(\"./req_test2\");\r\nexports.test = \"hello: \" + e2.test;\r\nconsole.log(\"[req_test1] \", exports.test, __dirname, __filename);\r\nconsole.log(\"req_test, isMain?\", module == require.main);\r\n//# sourceMappingURL=req_test1.js.map"
  },
  {
    "path": "Scripts/out/req_test2.js",
    "content": "console.log(\"[req_test2] i am test2\");\r\nexports.test = \"test 2\";\r\n//# sourceMappingURL=req_test2.js.map"
  },
  {
    "path": "Scripts/out/test.js",
    "content": "let s = Symbol.for(\"test\");\r\nclass Foo {\r\n    constructor() {\r\n        this.v1 = 1;\r\n        this.v2 = 2;\r\n    }\r\n    foo() {\r\n    }\r\n}\r\nlet foo = new Foo();\r\nfoo[s] = 1;\r\nfor (let k in foo) {\r\n    console.log(k, typeof foo[k]);\r\n}\r\nconsole.log(\"symbol\", foo[s]);\r\n//# sourceMappingURL=test.js.map"
  },
  {
    "path": "Scripts/out/worker.js",
    "content": "onmessage = function (e) {\r\n    let data = e.data;\r\n    switch (data.method) {\r\n        case \"add\": {\r\n            let x = 0;\r\n            let s = Date.now();\r\n            // 这里假装要处理很久很久\r\n            for (let i = 0; i < 10000000; i++) {\r\n                x++;\r\n            }\r\n            let d = Date.now() - s;\r\n            console.log(\"[worker] duration:\", d, \"repeated:\", x);\r\n            postMessage({\r\n                \"id\": data.id,\r\n                \"result\": data.args[0] + data.args[1],\r\n            });\r\n            break;\r\n        }\r\n        default: {\r\n            postMessage({\r\n                \"id\": data.id,\r\n                \"result\": \"unknown method\",\r\n            });\r\n            break;\r\n        }\r\n    }\r\n};\r\n//# sourceMappingURL=worker.js.map"
  },
  {
    "path": "Scripts/protogen/pb.bundle.d.ts",
    "content": "import * as $protobuf from \"protobufjs\";\n/** Namespace awesomepackage. */\nexport namespace awesomepackage {\n\n    /** Properties of an AwesomeMessage. */\n    interface IAwesomeMessage {\n\n        /** AwesomeMessage awesomeField */\n        awesomeField?: (string|null);\n    }\n\n    /** Represents an AwesomeMessage. */\n    class AwesomeMessage implements IAwesomeMessage {\n\n        /**\n         * Constructs a new AwesomeMessage.\n         * @param [properties] Properties to set\n         */\n        constructor(properties?: awesomepackage.IAwesomeMessage);\n\n        /** AwesomeMessage awesomeField. */\n        public awesomeField: string;\n\n        /**\n         * Creates a new AwesomeMessage instance using the specified properties.\n         * @param [properties] Properties to set\n         * @returns AwesomeMessage instance\n         */\n        public static create(properties?: awesomepackage.IAwesomeMessage): awesomepackage.AwesomeMessage;\n\n        /**\n         * Encodes the specified AwesomeMessage message. Does not implicitly {@link awesomepackage.AwesomeMessage.verify|verify} messages.\n         * @param message AwesomeMessage message or plain object to encode\n         * @param [writer] Writer to encode to\n         * @returns Writer\n         */\n        public static encode(message: awesomepackage.IAwesomeMessage, writer?: $protobuf.Writer): $protobuf.Writer;\n\n        /**\n         * Encodes the specified AwesomeMessage message, length delimited. Does not implicitly {@link awesomepackage.AwesomeMessage.verify|verify} messages.\n         * @param message AwesomeMessage message or plain object to encode\n         * @param [writer] Writer to encode to\n         * @returns Writer\n         */\n        public static encodeDelimited(message: awesomepackage.IAwesomeMessage, writer?: $protobuf.Writer): $protobuf.Writer;\n\n        /**\n         * Decodes an AwesomeMessage message from the specified reader or buffer.\n         * @param reader Reader or buffer to decode from\n         * @param [length] Message length if known beforehand\n         * @returns AwesomeMessage\n         * @throws {Error} If the payload is not a reader or valid buffer\n         * @throws {$protobuf.util.ProtocolError} If required fields are missing\n         */\n        public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): awesomepackage.AwesomeMessage;\n\n        /**\n         * Decodes an AwesomeMessage message from the specified reader or buffer, length delimited.\n         * @param reader Reader or buffer to decode from\n         * @returns AwesomeMessage\n         * @throws {Error} If the payload is not a reader or valid buffer\n         * @throws {$protobuf.util.ProtocolError} If required fields are missing\n         */\n        public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): awesomepackage.AwesomeMessage;\n\n        /**\n         * Verifies an AwesomeMessage message.\n         * @param message Plain object to verify\n         * @returns `null` if valid, otherwise the reason why it is not\n         */\n        public static verify(message: { [k: string]: any }): (string|null);\n\n        /**\n         * Creates an AwesomeMessage message from a plain object. Also converts values to their respective internal types.\n         * @param object Plain object\n         * @returns AwesomeMessage\n         */\n        public static fromObject(object: { [k: string]: any }): awesomepackage.AwesomeMessage;\n\n        /**\n         * Creates a plain object from an AwesomeMessage message. Also converts values to other types if specified.\n         * @param message AwesomeMessage\n         * @param [options] Conversion options\n         * @returns Plain object\n         */\n        public static toObject(message: awesomepackage.AwesomeMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };\n\n        /**\n         * Converts this AwesomeMessage to JSON.\n         * @returns JSON object\n         */\n        public toJSON(): { [k: string]: any };\n    }\n}\n"
  },
  {
    "path": "Scripts/protogen/pb.bundle.js",
    "content": "/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/\n\"use strict\";\n\nvar $protobuf = require(\"protobufjs/minimal\");\n\n// Common aliases\nvar $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;\n\n// Exported root namespace\nvar $root = $protobuf.roots[\"default\"] || ($protobuf.roots[\"default\"] = {});\n\n$root.awesomepackage = (function() {\n\n    /**\n     * Namespace awesomepackage.\n     * @exports awesomepackage\n     * @namespace\n     */\n    var awesomepackage = {};\n\n    awesomepackage.AwesomeMessage = (function() {\n\n        /**\n         * Properties of an AwesomeMessage.\n         * @memberof awesomepackage\n         * @interface IAwesomeMessage\n         * @property {string|null} [awesomeField] AwesomeMessage awesomeField\n         */\n\n        /**\n         * Constructs a new AwesomeMessage.\n         * @memberof awesomepackage\n         * @classdesc Represents an AwesomeMessage.\n         * @implements IAwesomeMessage\n         * @constructor\n         * @param {awesomepackage.IAwesomeMessage=} [properties] Properties to set\n         */\n        function AwesomeMessage(properties) {\n            if (properties)\n                for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)\n                    if (properties[keys[i]] != null)\n                        this[keys[i]] = properties[keys[i]];\n        }\n\n        /**\n         * AwesomeMessage awesomeField.\n         * @member {string} awesomeField\n         * @memberof awesomepackage.AwesomeMessage\n         * @instance\n         */\n        AwesomeMessage.prototype.awesomeField = \"\";\n\n        /**\n         * Creates a new AwesomeMessage instance using the specified properties.\n         * @function create\n         * @memberof awesomepackage.AwesomeMessage\n         * @static\n         * @param {awesomepackage.IAwesomeMessage=} [properties] Properties to set\n         * @returns {awesomepackage.AwesomeMessage} AwesomeMessage instance\n         */\n        AwesomeMessage.create = function create(properties) {\n            return new AwesomeMessage(properties);\n        };\n\n        /**\n         * Encodes the specified AwesomeMessage message. Does not implicitly {@link awesomepackage.AwesomeMessage.verify|verify} messages.\n         * @function encode\n         * @memberof awesomepackage.AwesomeMessage\n         * @static\n         * @param {awesomepackage.IAwesomeMessage} message AwesomeMessage message or plain object to encode\n         * @param {$protobuf.Writer} [writer] Writer to encode to\n         * @returns {$protobuf.Writer} Writer\n         */\n        AwesomeMessage.encode = function encode(message, writer) {\n            if (!writer)\n                writer = $Writer.create();\n            if (message.awesomeField != null && message.hasOwnProperty(\"awesomeField\"))\n                writer.uint32(/* id 1, wireType 2 =*/10).string(message.awesomeField);\n            return writer;\n        };\n\n        /**\n         * Encodes the specified AwesomeMessage message, length delimited. Does not implicitly {@link awesomepackage.AwesomeMessage.verify|verify} messages.\n         * @function encodeDelimited\n         * @memberof awesomepackage.AwesomeMessage\n         * @static\n         * @param {awesomepackage.IAwesomeMessage} message AwesomeMessage message or plain object to encode\n         * @param {$protobuf.Writer} [writer] Writer to encode to\n         * @returns {$protobuf.Writer} Writer\n         */\n        AwesomeMessage.encodeDelimited = function encodeDelimited(message, writer) {\n            return this.encode(message, writer).ldelim();\n        };\n\n        /**\n         * Decodes an AwesomeMessage message from the specified reader or buffer.\n         * @function decode\n         * @memberof awesomepackage.AwesomeMessage\n         * @static\n         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from\n         * @param {number} [length] Message length if known beforehand\n         * @returns {awesomepackage.AwesomeMessage} AwesomeMessage\n         * @throws {Error} If the payload is not a reader or valid buffer\n         * @throws {$protobuf.util.ProtocolError} If required fields are missing\n         */\n        AwesomeMessage.decode = function decode(reader, length) {\n            if (!(reader instanceof $Reader))\n                reader = $Reader.create(reader);\n            var end = length === undefined ? reader.len : reader.pos + length, message = new $root.awesomepackage.AwesomeMessage();\n            while (reader.pos < end) {\n                var tag = reader.uint32();\n                switch (tag >>> 3) {\n                case 1:\n                    message.awesomeField = reader.string();\n                    break;\n                default:\n                    reader.skipType(tag & 7);\n                    break;\n                }\n            }\n            return message;\n        };\n\n        /**\n         * Decodes an AwesomeMessage message from the specified reader or buffer, length delimited.\n         * @function decodeDelimited\n         * @memberof awesomepackage.AwesomeMessage\n         * @static\n         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from\n         * @returns {awesomepackage.AwesomeMessage} AwesomeMessage\n         * @throws {Error} If the payload is not a reader or valid buffer\n         * @throws {$protobuf.util.ProtocolError} If required fields are missing\n         */\n        AwesomeMessage.decodeDelimited = function decodeDelimited(reader) {\n            if (!(reader instanceof $Reader))\n                reader = new $Reader(reader);\n            return this.decode(reader, reader.uint32());\n        };\n\n        /**\n         * Verifies an AwesomeMessage message.\n         * @function verify\n         * @memberof awesomepackage.AwesomeMessage\n         * @static\n         * @param {Object.<string,*>} message Plain object to verify\n         * @returns {string|null} `null` if valid, otherwise the reason why it is not\n         */\n        AwesomeMessage.verify = function verify(message) {\n            if (typeof message !== \"object\" || message === null)\n                return \"object expected\";\n            if (message.awesomeField != null && message.hasOwnProperty(\"awesomeField\"))\n                if (!$util.isString(message.awesomeField))\n                    return \"awesomeField: string expected\";\n            return null;\n        };\n\n        /**\n         * Creates an AwesomeMessage message from a plain object. Also converts values to their respective internal types.\n         * @function fromObject\n         * @memberof awesomepackage.AwesomeMessage\n         * @static\n         * @param {Object.<string,*>} object Plain object\n         * @returns {awesomepackage.AwesomeMessage} AwesomeMessage\n         */\n        AwesomeMessage.fromObject = function fromObject(object) {\n            if (object instanceof $root.awesomepackage.AwesomeMessage)\n                return object;\n            var message = new $root.awesomepackage.AwesomeMessage();\n            if (object.awesomeField != null)\n                message.awesomeField = String(object.awesomeField);\n            return message;\n        };\n\n        /**\n         * Creates a plain object from an AwesomeMessage message. Also converts values to other types if specified.\n         * @function toObject\n         * @memberof awesomepackage.AwesomeMessage\n         * @static\n         * @param {awesomepackage.AwesomeMessage} message AwesomeMessage\n         * @param {$protobuf.IConversionOptions} [options] Conversion options\n         * @returns {Object.<string,*>} Plain object\n         */\n        AwesomeMessage.toObject = function toObject(message, options) {\n            if (!options)\n                options = {};\n            var object = {};\n            if (options.defaults)\n                object.awesomeField = \"\";\n            if (message.awesomeField != null && message.hasOwnProperty(\"awesomeField\"))\n                object.awesomeField = message.awesomeField;\n            return object;\n        };\n\n        /**\n         * Converts this AwesomeMessage to JSON.\n         * @function toJSON\n         * @memberof awesomepackage.AwesomeMessage\n         * @instance\n         * @returns {Object.<string,*>} JSON object\n         */\n        AwesomeMessage.prototype.toJSON = function toJSON() {\n            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);\n        };\n\n        return AwesomeMessage;\n    })();\n\n    return awesomepackage;\n})();\n\nmodule.exports = $root;\n"
  },
  {
    "path": "Scripts/src/components/sample_monobehaviour.ts",
    "content": "import { MonoBehaviour, WaitForSeconds, Object, Input, Camera, Vector3, Quaternion, Physics, LayerMask, RaycastHit, Time, ParticleSystem, ParticleSystemSimulationSpace } from \"UnityEngine\";\r\nimport * as jsb from \"jsb\";\r\nimport { Out } from \"jsb\";\r\nimport { Button } from \"UnityEngine.UI\";\r\nimport { ScriptType, ScriptProperty, ScriptFunction, ScriptNumber, ScriptInteger } from \"plover/runtime/class_decorators\";\r\n\r\n@ScriptType()\r\nexport class ASimpleGuiDialog extends MonoBehaviour {\r\n    //TODO: [NOT_IMPLEMENTED] 自动绑定界面组件\r\n    @ScriptProperty({ type: \"object\", bind: { widget: Button } })\r\n    nameLabel: Button;\r\n\r\n    //TODO: [NOT_IMPLEMENTED] 使 UnityEvent 识别并接受脚本函数作为回调\r\n    @ScriptFunction()\r\n    onClicked() {\r\n        console.log(\"you clicked the button\");\r\n    }\r\n}\r\n\r\n//TODO constructor is not called when using v8-bridge as backend\r\n@ScriptType()\r\nexport class MyClass extends MonoBehaviour {\r\n\r\n    @ScriptNumber()\r\n    vv = 0;\r\n\r\n    @ScriptInteger({ editable: false, serializable: false })\r\n    protected _tick = 0;\r\n\r\n    Awake() {\r\n        this.vv = 0;\r\n        this._tick = 0;\r\n        console.log(\"MyClass.Awake\", this._tick++);\r\n    }\r\n\r\n    async OnEnable() {\r\n        console.log(\"MyClass.OnEnable\", this._tick++);\r\n        await jsb.Yield(new WaitForSeconds(1));\r\n        console.log(\"MyClass.OnEnable (delayed)\", this._tick++);\r\n    }\r\n\r\n    OnDisable() {\r\n        console.log(\"MyClass.OnDisable\", this._tick++);\r\n    }\r\n\r\n    OnDestroy() {\r\n        console.log(\"MyClass.OnDestroy\", this._tick++);\r\n    }\r\n\r\n    OnApplicationFocus(hasFocus: boolean) {\r\n        console.log(\"OnApplicationFocus:\", hasFocus);\r\n    }\r\n\r\n    OnApplicationPause(pause: boolean) {\r\n        console.log(\"OnApplicationPause:\", pause);\r\n    }\r\n\r\n    speak(text: string) {\r\n        console.log(\"modified\", text);\r\n    }\r\n\r\n    async test() {\r\n        console.log(\"MyClass.test (will be destroied after 5 secs.\", this.transform);\r\n        await jsb.Yield(new WaitForSeconds(5));\r\n        Object.Destroy(this.gameObject);\r\n    }\r\n}\r\n\r\n@ScriptType()\r\nexport class MySubClass extends MyClass {\r\n    Awake() {\r\n        super.Awake();\r\n        console.log(\"MySubClass.Awake\", this._tick++);\r\n    }\r\n\r\n    Update() {\r\n        if (Input.GetMouseButtonUp(0)) {\r\n            let ray = Camera.main.ScreenPointToRay(Input.mousePosition);\r\n            let hitInfo: Out<RaycastHit> = { type: RaycastHit };\r\n            let layerMask = 1 << LayerMask.NameToLayer(\"Default\");\r\n\r\n            console.log(\"hittest\", layerMask);\r\n            if (Physics.Raycast(ray, hitInfo, 1000, layerMask)) {\r\n                console.log(\"hit\", hitInfo.value.transform.name);\r\n            }\r\n        }\r\n    }\r\n\r\n    play() {\r\n        console.log(\"MySubClass.play\");\r\n    }\r\n}\r\n\r\n@ScriptType()\r\nexport class RotateBehaviour extends MonoBehaviour {\r\n    private _rotation: number = 0;\r\n\r\n    @ScriptNumber({ serializable: false })\r\n    rotationSpeed = 50;\r\n\r\n    Reset() {\r\n        this._rotation = 0;\r\n    }\r\n\r\n    Awake() {\r\n        this._rotation = 0;\r\n        this.rotationSpeed = 50;\r\n        let ps = this.GetComponent(ParticleSystem);\r\n        if (ps) {\r\n            ps.main.simulationSpace = ParticleSystemSimulationSpace.World;\r\n            console.log(\"ps.main.simulationSpace:\", ps.main.simulationSpace);\r\n        }\r\n    }\r\n\r\n    Update() {\r\n        this._rotation += this.rotationSpeed * Time.deltaTime;\r\n        if (jsb.isOperatorOverloadingSupported) {\r\n            //@ts-ignore\r\n            let p: Vector3 = Quaternion.Euler(0, this._rotation, 0) * Vector3.right * 5;\r\n\r\n            p.z *= 0.5;\r\n            this.transform.localPosition = p;\r\n        } else {\r\n\r\n            let p: Vector3 = Vector3.op_Multiply(Quaternion.op_Multiply(Quaternion.Euler(0, this._rotation, 0), Vector3.right), 5);\r\n            p.z *= 0.5;\r\n            this.transform.localPosition = p;\r\n        }\r\n    }\r\n}\r\n\r\n@ScriptType()\r\nexport class Something5Behaviour extends MonoBehaviour {\r\n\r\n    @ScriptProperty({ type: \"Vector3\" })\r\n    pos: Vector3;\r\n\r\n}\r\n"
  },
  {
    "path": "Scripts/src/data.ts",
    "content": "\nexport let test_data = {\n    \"name\": \"Jane\", \n    \"id\": 1\n}\n"
  },
  {
    "path": "Scripts/src/do_from_cs.ts",
    "content": "function x() {\r\n    console.log(\"xxxxxxxxxxxxxxxxxxx\");\r\n}\r\n\r\nx"
  },
  {
    "path": "Scripts/src/do_from_cs_v.ts",
    "content": "let vv = {\r\n    \"test\": \"hello\"\r\n}\r\nvv"
  },
  {
    "path": "Scripts/src/dofile_test.ts",
    "content": "\r\nprint(\"dofile test\");\r\n"
  },
  {
    "path": "Scripts/src/editor/asset_postprocessor.ts",
    "content": "\r\nimport { Array } from \"System\";\r\nimport { AssetPostprocessor } from \"UnityEditor\";\r\nimport { AudioClip, GameObject, Material, Sprite, Texture2D } from \"UnityEngine\";\r\n\r\n// You need to register this script into assetPostProcessors in js-bridge.json (or Prefs.cs) to activate these callbacks\r\n\r\nexport function OnPostprocessTexture(processor: AssetPostprocessor, tex: Texture2D) {\r\n    // console.log(\"OnPostprocessTexture\", processor.assetPath);\r\n}\r\n\r\nexport function OnPostprocessModel(processor: AssetPostprocessor, model: GameObject) {\r\n    // console.log(\"OnPostprocessModel\", processor.assetPath);\r\n}\r\n\r\nexport function OnPostprocessAudio(processor: AssetPostprocessor, audioClip: AudioClip) {\r\n    // console.log(\"OnPostprocessAudio\", processor.assetPath);\r\n}\r\n\r\nexport function OnPostprocessMaterial(processor: AssetPostprocessor, material: Material) {\r\n    // console.log(\"OnPostprocessMaterial\", processor.assetPath);\r\n}\r\n\r\nexport function OnPostProcessSprites(processor: AssetPostprocessor, texture: Texture2D, sprites: Array<Sprite>) {\r\n    // console.log(\"OnPostProcessSprites\", processor.assetPath);\r\n}\r\n\r\nexport function OnPostprocessAllAssets(importedAssets: Array<string>, deletedAssets: Array<string>, movedAssets: Array<string>, movedFromAssetPaths: Array<string>) {\r\n    \r\n}\r\n"
  },
  {
    "path": "Scripts/src/editor/inspector/my_class_inspector.ts",
    "content": "import { Editor, EditorGUI, EditorGUILayout, EditorUtility, MessageType, Undo } from \"UnityEditor\";\r\nimport { GUILayout, Object } from \"UnityEngine\";\r\nimport { MyClass } from \"../../components/sample_monobehaviour\";\r\nimport { DefaultEditor, ScriptEditor } from \"plover/editor/editor_decorators\";\r\n\r\n@ScriptEditor(MyClass)\r\nexport class MyClassInspector extends DefaultEditor {\r\n    Awake() {\r\n        console.log(\"my class inspector class awake\");\r\n    }\r\n\r\n    OnInspectorGUI() {\r\n        let p = <MyClass>this.target;\r\n\r\n        EditorGUILayout.HelpBox(\"WHY ARE YOU SO SERIOUS?\", MessageType.Info);\r\n        EditorGUI.BeginDisabledGroup(true);\r\n        EditorGUILayout.ObjectField(\"Object\", p.gameObject, Object, true);\r\n        EditorGUI.EndDisabledGroup();\r\n        super.OnInspectorGUI();\r\n        if (GUILayout.Button(\"test\")) {\r\n            p.speak(\"hello\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "Scripts/src/editor/inspector/rotate_inspector.ts",
    "content": "import { Editor, EditorGUILayout, MessageType } from \"UnityEditor\";\nimport { GUILayout, Object } from \"UnityEngine\";\nimport { RotateBehaviour } from \"../../components/sample_monobehaviour\";\nimport { ScriptEditor } from \"plover/editor/editor_decorators\";\n\n@ScriptEditor(RotateBehaviour)\nexport class RotateBehaviourInspector extends Editor {\n    Awake() {\n        console.log(\"my class inspector class awake\");\n    }\n\n    OnInspectorGUI() {\n        let p = <RotateBehaviour>this.target;\n\n        EditorGUILayout.ObjectField(\"Object\", p.gameObject, Object, true);\n        p.rotationSpeed = EditorGUILayout.FloatField(\"Rotation Speed\", p.rotationSpeed);\n        if (GUILayout.Button(\"Reset\")) {\n            p.Reset();\n        }\n    }\n}"
  },
  {
    "path": "Scripts/src/editor/js_test.ts",
    "content": "import { MyName } from \"./js_test2\";\n\nconsole.log(\"[js_test] revision 4 ## read from \", MyName);\n"
  },
  {
    "path": "Scripts/src/editor/js_test2.ts",
    "content": "\nexport let MyName = \"jstest2 revision 6\";\n\nconsole.log(\"[js_test2]\", MyName);"
  },
  {
    "path": "Scripts/src/editor/main.ts",
    "content": "\r\nrequire(\"./js_test\");\r\n"
  },
  {
    "path": "Scripts/src/editor/my_editor_window.ts",
    "content": "import { DateTime } from \"System\";\r\nimport { EditorWindow, EditorGUILayout, MessageType, SceneView, Handles, GenericMenu, HandleUtility, EditorApplication, EditorGUI } from \"UnityEditor\";\r\nimport { FocusType, GUIContent, GUILayout, GUIUtility, Rect, Event, GUIStyle, GUI, Vector2, GUILayoutUtility, EventType, Vector3, Quaternion, Resources, ScriptableObject, Object, Color } from \"UnityEngine\";\r\nimport { ScriptEditorWindow } from \"plover/editor/editor_decorators\";\r\nimport { ScriptInteger, ScriptProperty, ScriptString } from \"plover/runtime/class_decorators\";\r\nimport * as jsb from \"jsb\";\r\nimport { EditorRuntime } from \"jsb.editor\";\r\n\r\nclass TempWindow extends EditorWindow {\r\n    private _greeting = false;\r\n\r\n    static show(rect: Rect, size: Vector2) {\r\n        for (let w of Resources.FindObjectsOfTypeAll(TempWindow)) {\r\n            w.Close();\r\n            Object.DestroyImmediate(w);\r\n        }\r\n\r\n        let inst = ScriptableObject.CreateInstance(TempWindow);\r\n        inst.ShowAsDropDown(GUIUtility.GUIToScreenRect(rect), size);\r\n    }\r\n\r\n    Awake() {\r\n        console.log(\"awake temp window\");\r\n    }\r\n\r\n    OnDestroy() {\r\n        console.log(\"destroy temp window\");\r\n    }\r\n\r\n    OnEnable() {\r\n        console.log(\"enable temp window\");\r\n    }\r\n\r\n    OnDisable() {\r\n        console.log(\"disable temp window\");\r\n    }\r\n\r\n    OnGUI() {\r\n        if (GUILayout.Button(\"Hi\")) {\r\n            this._greeting = true;\r\n            this.Repaint();\r\n        }\r\n\r\n        if (GUILayout.Button(\"Close\")) {\r\n            this.Close();\r\n        }\r\n\r\n        if (this._greeting) {\r\n            EditorGUILayout.HelpBox(\"Hi, nice to meet you.\", MessageType.Info);\r\n        }\r\n    }\r\n}\r\n\r\n@ScriptEditorWindow()\r\nexport class MyEditorWindow extends EditorWindow {\r\n    private _onSceneGui: (sv: SceneView) => void;\r\n    private _onMenuTest: () => void;\r\n    private _onWindowGUI: () => void;\r\n    private _styleWindowResize: GUIStyle;\r\n\r\n    @ScriptProperty({ type: \"Rect\" })\r\n    private _parentWindowRect = new Rect(0, 0, 0, 0);\r\n\r\n    @ScriptProperty({ type: \"Rect\" })\r\n    private _resizeStart = new Rect(0, 0, 0, 0);\r\n\r\n    @ScriptProperty({ type: \"Vector2\" })\r\n    private _minWindowSize = new Vector2(120, 100);\r\n\r\n    @ScriptProperty({ type: \"Rect\" })\r\n    private _thisWindowRect = new Rect(50, 50, 400, 300);\r\n\r\n    // @ScriptProperty({ type: \"object\", serializable: false })\r\n    private _resizerContent = new GUIContent(\"* \", \"Resize\");\r\n\r\n    @ScriptProperty({ type: \"bool\" })\r\n    private _isResizing = false;\r\n\r\n    @ScriptProperty({ type: \"int\" })\r\n    private _windowIndex = 0;\r\n\r\n    @ScriptInteger()\r\n    continuousInteger = 0;\r\n\r\n    Awake() {\r\n    }\r\n\r\n    OnEnable() {\r\n        this._onSceneGui = this.onSceneGui.bind(this);\r\n        this._onMenuTest = this.onMenuTest.bind(this);\r\n        this._onWindowGUI = this.onWindowGUI.bind(this);\r\n        this.titleContent = new GUIContent(\"Blablabla0\");\r\n        SceneView.duringSceneGui(\"add\", this._onSceneGui);\r\n    }\r\n\r\n    OnDisable() {\r\n        console.log(\"on disable\")\r\n        SceneView.duringSceneGui(\"remove\", this._onSceneGui);\r\n        \r\n        this._onSceneGui = null;\r\n        this._onMenuTest = null;\r\n        this._onWindowGUI = null;\r\n    }\r\n\r\n    OnDestroy() {\r\n        console.log(\"on destroy\")\r\n        this._resizerContent = null;\r\n    }\r\n\r\n    onWindowGUI() {\r\n        if (GUILayout.Button(\"Click\")) {\r\n            console.log(\"you clicked\");\r\n        }\r\n\r\n        let mousePosition = Event.current.mousePosition;\r\n        if (this._styleWindowResize == null) {\r\n            this._styleWindowResize = GUI.skin.box;\r\n        }\r\n\r\n        let resizerRect = GUILayoutUtility.GetRect(this._resizerContent, this._styleWindowResize, GUILayout.ExpandWidth(false));\r\n\r\n        resizerRect = new Rect(this._thisWindowRect.width - resizerRect.width, this._thisWindowRect.height - resizerRect.height, resizerRect.width, resizerRect.height);\r\n        if (Event.current.type == EventType.MouseDown && resizerRect.Contains(mousePosition)) {\r\n            this._isResizing = true;\r\n            this._resizeStart = new Rect(mousePosition.x, mousePosition.y, this._thisWindowRect.width, this._thisWindowRect.height);\r\n            //Event.current.Use();  // the GUI.Button below will eat the event, and this way it will show its active state\r\n        } else if (Event.current.type == EventType.MouseUp && this._isResizing) {\r\n            this._isResizing = false;\r\n        } else if (Event.current.type != EventType.MouseDrag && Event.current.isMouse) {\r\n            // if the mouse is over some other window we won't get an event, this just kind of circumvents that by checking the button state directly\r\n            this._isResizing = false;\r\n        } else if (this._isResizing) {\r\n            // console.log(\"resizing\");\r\n            this._thisWindowRect.width = Math.max(this._minWindowSize.x, this._resizeStart.width + (mousePosition.x - this._resizeStart.x));\r\n            this._thisWindowRect.height = Math.max(this._minWindowSize.y, this._resizeStart.height + (mousePosition.y - this._resizeStart.y));\r\n            this._thisWindowRect.xMax = Math.min(this._parentWindowRect.width, this._thisWindowRect.xMax); // modifying xMax affects width, not x\r\n            this._thisWindowRect.yMax = Math.min(this._parentWindowRect.height, this._thisWindowRect.yMax); // modifying yMax affects height, not y\r\n        }\r\n\r\n        GUI.Button(resizerRect, this._resizerContent, this._styleWindowResize);\r\n        GUI.DragWindow(new Rect(0, 0, 10000, 10000));\r\n    }\r\n\r\n    onSceneGui(sv: SceneView) {\r\n        let id = GUIUtility.GetControlID(FocusType.Passive);\r\n        this._parentWindowRect = sv.position;\r\n        if (this._thisWindowRect.yMax > this._parentWindowRect.height) {\r\n            this._thisWindowRect.yMax = this._parentWindowRect.height;\r\n        }\r\n\r\n        this._thisWindowRect = GUILayout.Window(id, this._thisWindowRect, this._onWindowGUI, \"My JS Editor Window\");\r\n        HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));\r\n    }\r\n\r\n    private onMenuTest() {\r\n        console.log(\"menu item test\");\r\n    }\r\n\r\n    AddItemsToMenu(menu: GenericMenu) {\r\n        menu.AddItem(new GUIContent(\"Test\"), false, this._onMenuTest);\r\n    }\r\n\r\n    private _lastHour = -1;\r\n    private _lastMinute = -1;\r\n    private _lastSecond = -1;\r\n\r\n    Update() {\r\n        let d = DateTime.Now;\r\n        if (this._lastSecond != d.Second) {\r\n            this._lastSecond = d.Second;\r\n            this._lastMinute = d.Minute;\r\n            this._lastHour = d.Hour;\r\n            this.Repaint();\r\n        }\r\n    }\r\n\r\n    OnGUI() {\r\n        EditorGUILayout.HelpBox(\"Hello\", MessageType.Info);\r\n        EditorGUILayout.LabelField(\"Prefs.sourceDir\", EditorRuntime?.prefs?.sourceDir || \"No sourceDir\");\r\n        EditorGUILayout.LabelField(\"TSConfig.outDir\", EditorRuntime?.tsconfig?.compilerOptions?.outDir || \"No outDir\");\r\n        EditorGUILayout.LabelField(typeof this.continuousInteger);\r\n        this.continuousInteger = EditorGUILayout.IntField(\"ContinuousInteger\", this.continuousInteger || 0) + 1;\r\n\r\n        if (GUILayout.Button(\"I am Javascript\")) {\r\n            console.log(\"Thanks!\", DateTime.Now);\r\n        }\r\n\r\n        let popRect = EditorGUILayout.GetControlRect();\r\n        if (GUI.Button(popRect, \"Pop A Temp Window\")) {\r\n            TempWindow.show(popRect, new Vector2(200, 200));\r\n        }\r\n\r\n        if (GUILayout.Button(\"CreateWindow\")) {\r\n            let child = EditorWindow.CreateWindow(MyEditorWindow, MyEditorWindow);\r\n            if (child) {\r\n                child._windowIndex = this._windowIndex + 1;\r\n                child.titleContent = new GUIContent(\"Blablabla\" + child._windowIndex);\r\n            }\r\n        }\r\n\r\n        let w = this.position.width;\r\n        let h = this.position.height;\r\n        let center = new Vector3(w * 0.5, h * 0.5, 0);\r\n        let rotSecond = Quaternion.Euler(0, 0, 360 * this._lastSecond / 60 + 180);\r\n        let rotHour = Quaternion.Euler(0, 0, 360 * this._lastHour / 24 + 180);\r\n        let rotMinute = Quaternion.Euler(0, 0, 360 * this._lastMinute / 60 + 180);\r\n        let lastHandlesColor = Handles.color;\r\n        Handles.color = Color.white;\r\n        if (jsb.isOperatorOverloadingSupported) {\r\n            //@ts-ignore\r\n            Handles.DrawLine(center, center + rotSecond * new Vector3(0, 90, 0));\r\n            //@ts-ignore\r\n            Handles.DrawLine(center, center + rotMinute * new Vector3(0, 75, 0));\r\n            //@ts-ignore\r\n            Handles.DrawLine(center, center + rotHour * new Vector3(0, 60, 0));\r\n        } else {\r\n            Handles.DrawLine(center, Vector3.op_Addition(center, Quaternion.op_Multiply(rotSecond, new Vector3(0, 90, 0))));\r\n            Handles.DrawLine(center, Vector3.op_Addition(center, Quaternion.op_Multiply(rotMinute, new Vector3(0, 75, 0))));\r\n            Handles.DrawLine(center, Vector3.op_Addition(center, Quaternion.op_Multiply(rotHour, new Vector3(0, 60, 0))));\r\n        }\r\n        Handles.DrawWireDisc(center, Vector3.back, 100);\r\n        Handles.color = lastHandlesColor;\r\n\r\n        EditorGUILayout.BeginHorizontal();\r\n        EditorGUILayout.IntField(this._lastHour);\r\n        EditorGUILayout.IntField(this._lastMinute);\r\n        EditorGUILayout.IntField(this._lastSecond);\r\n        EditorGUILayout.EndHorizontal();\r\n    }\r\n}\r\n"
  },
  {
    "path": "Scripts/src/editor/my_test_editor.ts",
    "content": "import { AddCacheString } from \"jsb\";\r\nimport { Array, String } from \"System\";\r\nimport { BuildOptions, BuildPipeline, BuildTarget, EditorGUILayout, EditorWindow, HandleUtility } from \"UnityEditor\";\r\nimport { FocusType, GUIContent, GUILayout, GUIUtility, Rect } from \"UnityEngine\";\r\nimport { ScriptEditorWindow } from \"plover/editor/editor_decorators\";\r\nimport { DelegateTest } from \"Example\";\r\n\r\nfunction _onWindowGUI() { }\r\n\r\n@ScriptEditorWindow()\r\nexport class MyTestEditorWindow extends EditorWindow {\r\n    private _testString = \"\";\r\n    private _sel = 0;\r\n    private _scenes: Array<string>;\r\n    private _thisWindowRect = new Rect(0, 0, 500, 100);\r\n\r\n    Awake() {\r\n        AddCacheString(\"Test\");\r\n        AddCacheString(\"\");\r\n        this._scenes = Array.CreateInstance(String, 1);\r\n        this._scenes.SetValue(\"Assets/Examples/Scenes/BasicRun.unity\", 0);\r\n    }\r\n\r\n    OnEnable() {\r\n        this.titleContent = new GUIContent(\"Test EditorWindow\");\r\n    }\r\n\r\n    OnGUI() {\r\n        this._testString = EditorGUILayout.TextField(\"Test\", this._testString || \"\");\r\n        this._sel = EditorGUILayout.Popup(<any>\"Pick\", <any>this._sel, <any>[\"1\", \"2\", \"3\", \"4\"]);\r\n\r\n        if (GUILayout.Button(\"Test Delegate\")) {\r\n            // DelegateTest.UseDelegateInParameter(_onWindowGUI);\r\n            DelegateTest.UseDelegateInParameter(function () { });\r\n        }\r\n\r\n        if (GUILayout.Button(\"Test Build\")) {\r\n            BuildPipeline.BuildPlayer(this._scenes, \"Build/macos.app\", BuildTarget.StandaloneOSX, BuildOptions.Development);\r\n        }\r\n\r\n        let id = GUIUtility.GetControlID(FocusType.Passive);\r\n        this._thisWindowRect = GUILayout.Window(id, this._thisWindowRect, function () { }, \"My JS Editor Window\");\r\n        HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));\r\n    }\r\n}\r\n\r\n"
  },
  {
    "path": "Scripts/src/example_async.ts",
    "content": "import { AsyncTaskTest } from \"Example\";\r\nimport { Yield } from \"jsb\";\r\nimport { IPHostEntry } from \"System.Net\";\r\nimport { WaitForSeconds, Time } from \"UnityEngine\";\r\n\r\nfunction delay(secs) {\r\n    return new Promise<number>((resolve, reject) => {\r\n        setTimeout(() => {\r\n            print(\"[async] resolve\");\r\n            resolve(123);\r\n        }, secs * 1000);\r\n    });\r\n}\r\n\r\nasync function test() {\r\n    print(\"[async] begin\");\r\n    await delay(3);\r\n    print(\"[async] end\");\r\n    let result = <IPHostEntry>await Yield(AsyncTaskTest.GetHostEntryAsync(\"www.baidu.com\"));\r\n    console.log(\"host entry:\", result.HostName);\r\n    await Yield(AsyncTaskTest.SimpleTest(3000));\r\n    console.log(\"after AsyncTaskTest.SimpleTest(1000)\");\r\n}\r\n\r\nasync function testUnityYieldInstructions() {\r\n    console.warn(\"wait for unity YieldInstruction, begin\");\r\n    await Yield(new WaitForSeconds(3));\r\n\r\n    console.warn(\"wait for unity YieldInstruction, end;\", Time.frameCount);\r\n    await Yield(null);\r\n    console.warn(\"wait for unity YieldInstruction, next frame;\", Time.frameCount);\r\n}\r\n\r\ntest();\r\ntestUnityYieldInstructions();\r\n"
  },
  {
    "path": "Scripts/src/example_bytes.ts",
    "content": "import { NoNamespaceClass } from \"global\";\r\nimport { ToArrayBuffer, ToBytes } from \"jsb\";\r\n\r\nif (module == require.main) {\r\n    var takeBuffer = NoNamespaceClass.MakeBytes();\r\n    var testBuffer = new Uint8Array(ToArrayBuffer(takeBuffer));\r\n    var restoreBytes = ToBytes(testBuffer);\r\n    var backBuffer = new Uint8Array(ToArrayBuffer(NoNamespaceClass.TestBytes(restoreBytes)));\r\n\r\n    print(\"byte[] 处理\");\r\n    backBuffer.forEach(val => print(val));\r\n}"
  },
  {
    "path": "Scripts/src/example_csharp_promise.ts",
    "content": "import { SampleBehaviour } from \"global\";\r\nimport { Yield } from \"jsb\";\r\nimport { WaitForSeconds, GameObject } from \"UnityEngine\";\r\n\r\nasync function test_custom_promise1() {\r\n    print(\"想象3秒后弹出的是个对话框\");\r\n    await Yield(new WaitForSeconds(3));\r\n    let go = new GameObject(\"custome.promise.test1\");\r\n    let sb = go.AddComponent(SampleBehaviour);\r\n    print(\"想象这里是等待用户点击对话框按钮\");\r\n    print(\"完成 (promise in C#):\", await sb.SimpleWait(1));\r\n}\r\n\r\nasync function test_custom_promise2() {\r\n    let go = new GameObject(\"custome.promise.test2\");\r\n    let sb = go.AddComponent(SampleBehaviour);\r\n    await sb.AnotherWait(123);\r\n    console.log(\"after another wait\");\r\n}\r\n\r\ntest_custom_promise1();\r\ntest_custom_promise2();\r\n"
  },
  {
    "path": "Scripts/src/example_databinding.ts",
    "content": "import { DataBinding, Subscriber } from \"plover/events/data_binding\"\r\nimport { Dispatcher } from \"plover/events/dispatcher\"\r\n\r\ninterface MyData {\r\n    name: string\r\n    age: number\r\n    address: string\r\n}\r\n\r\n// data\r\nlet data: MyData = {\r\n    name: \"test name\",\r\n    age: 30,\r\n    address: \"somewhere\",\r\n}\r\n\r\nlet test = DataBinding.bind(data);\r\n\r\nclass TextInput {\r\n    private _text: string;\r\n\r\n    onchange = new Dispatcher();\r\n\r\n    get text() { return this._text; }\r\n\r\n    set text(value: string) {\r\n        this._text = value;\r\n        console.log(\"[TextInput] set text:\", value);\r\n        this.onchange.dispatch(this);\r\n    }\r\n}\r\n\r\nclass TextInputWatcher extends Subscriber {\r\n    private _input: TextInput;\r\n\r\n    constructor(model: DataBinding, key: string, input: TextInput) {\r\n        super(model, key);\r\n        this._input = input;\r\n        this._input.onchange.on(this, this.onchange);\r\n    }\r\n\r\n    protected update(value: string) {\r\n        this._input.text = value;\r\n    }\r\n\r\n    onchange(input: TextInput) {\r\n        this.value = input.text;\r\n    }\r\n}\r\n\r\nlet input = new TextInput();\r\nlet sub = DataBinding.subscribe(TextInputWatcher, test, \"name\", input);\r\n\r\ntest.name = \"temp name\";\r\nconsole.log(\"[数据变更]\", test.name, input.text);\r\n\r\ninput.text = \"输入文字\";\r\nconsole.log(\"[界面变更]\", test.name, input.text);\r\n\r\nsub.unsubscribe();\r\n\r\nconsole.log(test.name);\r\ntest.name = \"new name\";\r\nconsole.log(test.name);\r\nconsole.log(test.age);\r\n\r\nObject.keys(test).forEach(k => console.log(\"model access:\", k));\r\n"
  },
  {
    "path": "Scripts/src/example_delegate.ts",
    "content": "import { DelegateTest } from \"Example\";\r\n\r\nexport function run() {\r\n    let actions = new DelegateTest();\r\n\r\n    print(\"testcase: 无参数的委托\");\r\n    console.log(\"********** add\");\r\n    actions.onAction(\"add\", function () {\r\n        console.log(\"js action call\");\r\n    });\r\n\r\n    console.log(\"********** call\");\r\n    actions.CallAction();\r\n\r\n    actions.onAction(\"set\", null);\r\n    console.log(\"********** after clear, call again\");\r\n    actions.CallAction();\r\n\r\n    print(\"testcase: 带参数的委托\");\r\n    actions.onActionWithArgs(\"set\", (a, b, c) => {\r\n        console.log(a, b, c);\r\n    });\r\n    actions.CallActionWithArgs(\"string\", 123, 456);\r\n\r\n    actions.onFunc(\"set\", v => v * 2);\r\n    console.log(actions.CallFunc(111));\r\n    actions.onFunc(\"set\", undefined);\r\n\r\n    print(\"testcase: instance event\");\r\n    actions.onEvent(\"add\", v => print(\"instance event test 1:\", v));\r\n    function instanceEventHandler(v: number) { print(\"instance event test 2:\", v) }\r\n    actions.onEvent(\"add\", instanceEventHandler);\r\n    actions.DipatchEvent(123);\r\n    actions.onEvent(\"remove\", instanceEventHandler);\r\n    actions.DipatchEvent(123);\r\n\r\n    print(\"testcase: static event\");\r\n    DelegateTest.onStaticEvent(\"add\", v => print(\"static event test 1:\", v));\r\n    function staticEventHandler(v: number) { print(\"static event test 2:\", v) }\r\n    DelegateTest.onStaticEvent(\"add\", staticEventHandler);\r\n    DelegateTest.DipatchStaticEvent(123);\r\n    DelegateTest.onStaticEvent(\"remove\", staticEventHandler);\r\n    DelegateTest.DipatchStaticEvent(123);\r\n\r\n    try {\r\n        print(\"testcase: delegate with ref/out parameters\");\r\n        actions.complexCall(\"add\", (b, a, v) => {\r\n            a.value += b;\r\n            v.value = 999;\r\n            return 789;\r\n        });\r\n        actions.complexCall2(\"add\", v => {\r\n            v.value.Set(v.value.x * 2, v.value.y * 2, v.value.z * 2);\r\n        });\r\n        actions.TestComplexCall();\r\n    } catch (err) {\r\n        console.warn(err);\r\n        console.warn(\"dynamic code emitting doesn't work properly\");\r\n    }\r\n}\r\n\r\nif (module == require.main) {\r\n    run();\r\n}\r\n"
  },
  {
    "path": "Scripts/src/example_disposable.ts",
    "content": "import { DisposableObject } from \"Example\";\r\n\r\nfunction test() {\r\n    let obj = new DisposableObject();\r\n\r\n    // 垃圾回收时将自动执行 obj.Dispose (JS主线程)\r\n    obj = undefined;\r\n}\r\n\r\nconsole.log(\"before test()\");\r\ntest();\r\nconsole.log(\"after test()\");\r\n"
  },
  {
    "path": "Scripts/src/example_editor_window.ts",
    "content": "\r\nimport { MyEditorWindow } from \"./editor/my_editor_window\"\r\nimport { EditorWindow } from \"UnityEditor\";\r\n\r\nEditorWindow.GetWindow(MyEditorWindow);\r\n"
  },
  {
    "path": "Scripts/src/example_hotfix.ts",
    "content": "import * as jsb from \"jsb\";\r\n\r\nlet HotfixTest: any = jsb.Import(\"HotfixTest\");\r\n\r\ntry {\r\n    // 反射导入的类型默认收到访问保护 (hotfix 后保护会被迫移除)\r\n    print(HotfixTest.static_value);\r\n} catch (err) {\r\n    console.warn(\"默认拒绝访问私有成员\", err);\r\n}\r\n\r\ntry {\r\n    jsb.hotfix.replace_single(\"HotfixTest\", \".ctor\", function () {\r\n        print(\"[HOTFIX][JS] 构造函数\");\r\n    });\r\n    jsb.hotfix.replace_single(\"HotfixTest\", \"Foo\", function (x: number | string) {\r\n        print(\"[HOTFIX][JS] HotfixTest.Foo [private] this.value = \", this.value);\r\n        return typeof x === \"number\" ? x + 3 : x + \"~~~\";\r\n    });\r\n    jsb.hotfix.before_single(\"HotfixTest\", \"AnotherStaticCall\", function () {\r\n        print(\"[HOTFIX][JS] HotfixTest.AnotherStaticCall 在 C# 执行前插入 JS 代码\");\r\n    });\r\n    jsb.hotfix.replace_single(\"HotfixTest\", \"SimpleStaticCall\", function () {\r\n        this.AnotherStaticCall();\r\n        print(\"[HOTFIX][JS] HotfixTest.SimpleStaticCall [private] this.static_value = \", this.static_value);\r\n    });\r\n} catch (err) {\r\n    console.warn(\"替换失败, 是否执行过dll注入?\");\r\n}\r\n\r\nlet hotfix: any = new HotfixTest();\r\n\r\nprint(\"[HOTFIX][JS] hotfix.Foo(1) 返回值:\", hotfix.Foo(1));\r\nprint(\"[HOTFIX][JS] hotfix.Foo(1) 返回值:\", hotfix.Foo(\"good day\"));\r\nHotfixTest.SimpleStaticCall();\r\n"
  },
  {
    "path": "Scripts/src/example_hotload.ts",
    "content": "\r\nimport { test_data } from \"./data\";\r\n\r\nconsole.log(\"read data: \", test_data.name);\r\n"
  },
  {
    "path": "Scripts/src/example_jsx.tsx",
    "content": "import { Object, GameObject, Resources, RectTransform, Vector2 } from \"UnityEngine\";\r\nimport { JSXWidgetBridge } from \"plover/jsx/bridge\";\r\nimport * as JSX from \"plover/jsx/element\";\r\nimport { ViewModel } from \"plover/jsx/vue\";\r\nimport { ScriptType } from \"plover/runtime/class_decorators\";\r\n\r\nexport interface TestData {\r\n    name: string,\r\n    tick: number;\r\n}\r\n\r\n@ScriptType()\r\nexport class MyWidgetTest extends JSXWidgetBridge {\r\n    private _data: TestData;\r\n    private _timer: any;\r\n\r\n    get data() { return this._data; }\r\n\r\n    Awake() {\r\n        this._data = ViewModel.create({ name: \"Unity\", tick: 0 });\r\n        this._widget =\r\n            <widget class={this}>\r\n                <text name=\"label\" text=\"Hello {{this.name}} {{this.tick}}\" />\r\n            </widget>\r\n\r\n        this._timer = setInterval(() => {\r\n            this._data.tick++;\r\n        }, 1000);\r\n        this._data.tick++;\r\n    }\r\n\r\n    OnDestroy() {\r\n        super.OnDestroy();\r\n        clearInterval(this._timer);\r\n    }\r\n}\r\n\r\nlet parent = GameObject.Find(\"/Canvas\").transform;\r\nlet go = Object.Instantiate(Resources.Load(\"prefab/jsx_test_ui\")) as GameObject;\r\n\r\ngo.transform.SetParent(parent);\r\nlet rect = go.GetComponent(RectTransform);\r\n\r\nrect.anchorMin = Vector2.zero;\r\nrect.anchorMax = Vector2.one;\r\nrect.anchoredPosition = Vector2.zero;\r\nconsole.log(\"load\", go, go.AddComponent(MyWidgetTest));\r\n"
  },
  {
    "path": "Scripts/src/example_main.ts",
    "content": "print(\"isMain?\", module == require.main);\r\n\r\nimport { DelegateTest, ValueTest } from \"Example\";\r\nimport * as jsb from \"jsb\";\r\nimport { Camera, Vector3 } from \"UnityEngine\";\r\n// import { fib } from \"./fib_module.js\";\r\nimport { fib } from \"./fib\";\r\n\r\nconsole.assert(true, \"will not print\");\r\nconsole.assert(false, \"assert!!!\");\r\n\r\nprint(jsb.engine, jsb.version);\r\nprint(DelegateTest);\r\nprint(DelegateTest.InnerTest.hello);\r\n\r\ntry {\r\n    // 强行传入一个错误的参数 (期望参数为无参)\r\n    // @ts-ignore\r\n    DelegateTest.GetArray(\"error\");\r\n} catch (err) {\r\n    console.warn(err + '\\n' + err.stack);\r\n}\r\n\r\ntry {\r\n    // 注意: 因为效率上的考虑, 简单类型是不会抛异常的, 比如 Camera.main.orthographicSize = \"abc\" 结果 = 0\r\n    //       除非传入 any, 否则大部分情况下ts编译将提示类型错误\r\n    //       可能后续会通过 DEBUG 宏等进行更严格的检查\r\n\r\n    // 强行传入一个错误类型参数\r\n    // @ts-ignore\r\n    Camera.main.transparencySortAxis = \"wrong value\";\r\n} catch (err) {\r\n    console.warn(err);\r\n}\r\n\r\n// 一维数组的操作\r\nconsole.log(\"ValueTest.values1[2] = \", ValueTest.values1.GetValue(2));\r\n// 多维数组的操作\r\nconsole.log(\"ValueTest.values2[0, 1] = \", ValueTest.values2.GetValue(0, 1));\r\n\r\nprint(\"fib:\", fib(12));\r\n\r\nsetTimeout(() => {\r\n    print(\"[timeout] test\");\r\n}, 1500);\r\n\r\nsetInterval(() => {\r\n    console.log(\"interval tick\");\r\n}, 1000 * 10);\r\n\r\nprint(\"require.require:\");\r\nprint(\"require 1:\", require(\"./req_test1\").test);\r\nprint(\"require 2:\", require(\"./req_test1\").test);\r\nprint(\"require 3:\", require(\"./req_test1\").test);\r\n\r\n// 通过 require 直接读 json\r\nprint(\"json:\", require(\"../config/data.json\").name);\r\n\r\n// Object.keys(require.cache).forEach(key => console.log(\"module loaded:\", key));\r\n\r\n// print(\"require (node_modules): \", require(\"blink1\").test);\r\n// print(\"require (node_modules): \", require(\"blink3\").test);\r\n\r\n// Optional Chaining/Nullish coalescing Operator 需要较新的 tsc 编译, 或者直接在 js 代码中使用\r\n// // Optional Chaining\r\n// let a: any = 1;\r\n// print(\"Optional Chaining\", a?.b?.c === undefined);\r\n// // Nullish coalescing Operator\r\n// print(\"Nullish coalescing Operator:\", a?.b ?? \"ok\");\r\n\r\n// const protobuf = require(\"protobufjs\");\r\n// print(\"protobufjs:\", protobuf);\r\n\r\njsb.DoFile(\"dofile_test\");\r\n\r\ntry {\r\n    jsb.DoFile(\"not_exists.file\");\r\n} catch (e) {\r\n    console.warn(e);\r\n}\r\n\r\nglobalThis[\"testGlobalVar\"] = \"test\";\r\n\r\nObject.keys(require.cache).forEach(k => console.log(\"require.cache entry:\", k));\r\n"
  },
  {
    "path": "Scripts/src/example_matterjs.ts",
    "content": "import { Bodies, Body, Composite, Engine, Runner } from \"matter-js\";\nimport { Camera, GameObject, MonoBehaviour, PrimitiveType, Quaternion, Random, Vector3 } from \"UnityEngine\";\n\nlet engine = Engine.create({\n    gravity: { y: -0.1 }\n});\n\nlet runner = Runner.create();\n\nclass BoxUpdater extends MonoBehaviour {\n    body: Body;\n\n    Update() {\n        this.transform.localRotation = Quaternion.Euler(0, 0, this.body.angle * 180 / Math.PI);\n        this.transform.localPosition = new Vector3(this.body.position.x, this.body.position.y, 0);\n    }\n}\n\nlet index = 0;\nfunction add_box(x: number, y:number, w: number, h: number) {\n    let box = Bodies.rectangle(x, y, w, h);\n    let go = GameObject.CreatePrimitive(PrimitiveType.Cube);\n    let updater = go.AddComponent(BoxUpdater);\n    updater.body = Composite.add(engine.world, box).bodies[index++];\n    go.transform.localScale = new Vector3(w, h, 1);\n}\n\nfunction add_static_box(x: number, y:number, w: number, h: number) {\n    let box = Bodies.rectangle(x, y, w, h, { isStatic: true });\n    let go = GameObject.CreatePrimitive(PrimitiveType.Cube);\n    let v = Composite.add(engine.world, box).bodies[index++].position;\n    go.transform.localPosition = new Vector3(v.x, v.y, 0);\n    go.transform.localScale = new Vector3(w, h, 1);\n}\n\nadd_box(4, 100, 8, 8);\nadd_box(6, 70, 8, 8);\nadd_static_box(0, -100, 400, 6);\n\nRunner.run(runner, engine);\nCamera.main.orthographicSize = 100;"
  },
  {
    "path": "Scripts/src/example_monobehaviour.ts",
    "content": "debugger;\r\nimport { GameObject, PrimitiveType, Vector3, Quaternion, ParticleSystem } from \"UnityEngine\";\r\nimport { MySubClass, MyClass, RotateBehaviour, Something5Behaviour } from \"./components/sample_monobehaviour\";\r\n\r\nif (module == require.main) {\r\n    print(\"example_monobehaviour\");\r\n    let gameObject = new GameObject();\r\n    let comp1 = gameObject.AddComponent(MySubClass);\r\n    let comp2 = gameObject.AddComponent(MyClass);\r\n\r\n    let cube = GameObject.CreatePrimitive(PrimitiveType.Cube);\r\n\r\n    cube.transform.localPosition = new Vector3(1, 2, 3);\r\n    cube.transform.localRotation = Quaternion.Euler(30, 60, 90);\r\n    cube.transform.localScale = new Vector3(2, 3, 4);\r\n\r\n    comp1.vv = 1;\r\n    comp2.vv = 2;\r\n\r\n    comp1.play();\r\n\r\n    {\r\n        let results = gameObject.GetComponents(MySubClass);\r\n        results.forEach(it => console.log(\"GetComponents(MySubClass):\", it.vv));\r\n    }\r\n\r\n    {\r\n        let results = gameObject.GetComponents(MyClass);\r\n        results.forEach(it => console.log(\"GetComponents(MyClass):\", it.vv));\r\n    }\r\n\r\n    let ps = GameObject.Find(\"/Particle System\");\r\n    if (!ps) {\r\n        ps = new GameObject(\"Particle System\");\r\n        ps.AddComponent(ParticleSystem);\r\n    }\r\n    console.log(\"Particle System:\", ps);\r\n    if (ps) {\r\n        ps.AddComponent(RotateBehaviour);\r\n    }\r\n\r\n    {\r\n        let sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);\r\n        sphere.transform.localScale = new Vector3(2, 2, 2);\r\n        sphere.transform.TestWithScriptObject(function () {\r\n            console.warn(\"TestWithScriptObject\");\r\n        });\r\n\r\n        sphere.AddComponent(Something5Behaviour);\r\n    }\r\n}\r\n"
  },
  {
    "path": "Scripts/src/example_operator_overload.ts",
    "content": "import { Color, Vector3 } from \"UnityEngine\";\r\nimport * as jsb from \"jsb\";\r\n\r\nif (module == require.main) {\r\n    let support = jsb.isOperatorOverloadingSupported;\r\n\r\n    console.log(\"IsOperatorOverloadingSupported:\", support);\r\n    // operators\r\n    {\r\n        let vec1 = new Vector3(1, 2, 3);\r\n        let vec2 = new Vector3(9, 8, 7);\r\n        // @ts-ignore\r\n        let vec3 = support ? vec1 + vec2 : Vector3.op_Addition(vec1, vec2);\r\n        // @ts-ignore\r\n        let vec4 = support ? vec1 + vec2 : Vector3.op_Addition(vec1, vec2);\r\n        console.log(\"v1 = \", vec1);\r\n        console.log(\"v2 = \", vec2);\r\n        console.log(\"v1 + v2 =\", vec3);\r\n        // @ts-ignore\r\n        console.log(\"v3 * 2 =\", support ? vec3 * 2 : Vector3.op_Multiply(vec3, 2));\r\n        // @ts-ignore\r\n        console.log(\"2 * v3=\", support ? 2 * vec3 : Vector3.op_Multiply(2, vec3));\r\n        // @ts-ignore\r\n        console.log(\"v3 / 2 =\", support ? vec3 / 2 : Vector3.op_Division(vec3, 2));\r\n        console.log(\"v3 == v4:\", support ? vec3 == vec4 : Vector3.op_Equality(vec3, vec4));\r\n    }\r\n\r\n    {\r\n        let c1 = new Color(0, 0, 0, 1);\r\n        let c2 = new Color(0.5, 0.1, 0.2, 0);\r\n        // @ts-ignore\r\n        let r = support ? c2 / 3 : Color.op_Division(c2, 3);\r\n        print(c1, c2, r);\r\n    }\r\n}\r\n"
  },
  {
    "path": "Scripts/src/example_pbjs_parse.ts",
    "content": "import * as pbjs from \"protobufjs\";\r\nimport { File } from \"System.IO\";\r\n\r\nconsole.log(\"please run 'npm install' at first if 'protobufjs' module can not be resolved\");\r\n\r\n// 直接解析的方式载入 proto 定义\r\n\r\nlet awesome = File.ReadAllText(\"Assets/Examples/Data/awesome.proto\");\r\nlet pb = pbjs.parse(awesome);\r\nlet proto = pb.root.resolveAll();\r\n\r\nfor (let pb of proto.nestedArray) {\r\n    console.log(\"read reflected protobuf message type:\", pb);\r\n    let nestedArray = (<pbjs.NamespaceBase>pb).nestedArray;\r\n    if (typeof nestedArray !== \"undefined\") {\r\n        for (let pb_nested of nestedArray) {\r\n            console.log(\"pb_nested:\", pb_nested);\r\n        }\r\n    }\r\n}\r\n\r\nlet type = proto.lookupType(\"awesomepackage.AwesomeMessage\");\r\nlet msg = type.fromObject({\r\n    awesomeField: \"hello, protobufjs\",\r\n});\r\n\r\nlet data = type.encode(msg).finish();\r\nconsole.log(\"encoded data (len):\", data.byteLength);\r\n\r\nlet decMsg = type.decode(data);\r\nconsole.log(\"decoded message:\", decMsg[\"awesomeField\"]);\r\n"
  },
  {
    "path": "Scripts/src/example_pbjs_static.ts",
    "content": "\r\n/*\r\n开发过程中可以使用 Default FileSystem 正常依赖 node_modules 中的库时\r\n当需要发布到 Resources/Assetbundle 时, 这种情况下需要使用 webpack 等打包工具将脚本依赖全部打包, 即可在最终环境中使用第三方库\r\n*/\r\n\r\nimport * as aw from \"../protogen/pb.bundle\";\r\n\r\n/*\r\n具体参见 protobufjs 文档\r\nnpm: https://www.npmjs.com/package/protobufjs\r\ngithub: https://github.com/protobufjs/protobuf.js\r\n\r\npbjs -t static-module -w commonjs -o pb.bundle.js awesome.proto\r\npbts -o pb.bundle.d.ts pb.bundle.js  \r\n*/\r\n\r\nconsole.log(\"please run 'npm install' at first if 'protobufjs' module can not be resolved\");\r\n\r\n// 预生成代码的方式使用 proto 定义\r\nlet msg = aw.awesomepackage.AwesomeMessage.create({\r\n    awesomeField: \"hello, protobufjs\",\r\n});\r\nconsole.log(msg.awesomeField);\r\n\r\nlet data = aw.awesomepackage.AwesomeMessage.encode(msg).finish();\r\nconsole.log(\"encoded data (len):\", data.byteLength);\r\n\r\nlet decMsg = aw.awesomepackage.AwesomeMessage.decode(data);\r\nconsole.log(\"decoded message:\", decMsg.awesomeField);\r\n"
  },
  {
    "path": "Scripts/src/example_ref_out.ts",
    "content": "import { NoNamespaceClass } from \"global\";\r\nimport * as jsb from \"jsb\";\r\n\r\nfunction execute() {\r\n    if (module == require.main) {\r\n        let g: jsb.Ref<number> = { value: 1 };\r\n        let x: jsb.Out<number> = {};\r\n        let z: jsb.Out<number> = {};\r\n        let y = 666;\r\n        NoNamespaceClass.TestRefOut(g, x, y, z);\r\n        console.assert(x.value == y * 1, \"x\");\r\n        console.assert(z.value == y + 1, \"z\");\r\n        console.assert(g.value == x.value + z.value, \"g\");\r\n        print(\"ref/out:\", g.value, x.value, z.value);\r\n    }\r\n\r\n    // a type description field for Out/Ref is optional but helpful to select the right overloaded method\r\n\r\n    if (module == require.main) {\r\n        let x: jsb.Out<number> = { type: Number };\r\n        let z: jsb.Out<number> = { type: Number };\r\n        let y = 233;\r\n        NoNamespaceClass.TestOut(x, y, z);\r\n        console.assert(x.value == y, \"x == y ?\");\r\n        console.assert(z.value == y, \"z == y ?\");\r\n        print(\"out:\", x.value, typeof x.value, z.value, typeof z.value);\r\n    }\r\n\r\n    if (module == require.main) {\r\n        let x: jsb.Out<string> = { type: String };\r\n        let z: jsb.Out<string> = { type: String };\r\n        let y = 999;\r\n        NoNamespaceClass.TestOut(x, 999, z);\r\n        console.assert(x.value == y.toString(), \"x == y ?\");\r\n        console.assert(z.value == y.toString(), \"z == y ?\");\r\n        print(\"out:\", x.value, typeof x.value, z.value, typeof z.value);\r\n    }\r\n}\r\n\r\nexecute();\r\n"
  },
  {
    "path": "Scripts/src/example_reflect.ts",
    "content": "import { DelegateTest } from \"Example\";\r\nimport { Camera, GameObject } from \"UnityEngine\";\r\nimport { Object } from \"System\";\r\n\r\nif (module == require.main) {\r\n    let camera = GameObject.Find(\"/Main Camera\").GetComponent(Camera);\r\n    // 通过反射方式建立未导出类型的交互\r\n    let unknown = DelegateTest.GetNotExportedClass();\r\n    print(unknown.value);\r\n    print(unknown.GetType().value2);\r\n    print(unknown.Add(12, 21));\r\n    print(\"Equals(unknown, unknown):\", Object.Equals(unknown, unknown));\r\n    print(\"Equals(unknown, camera):\", Object.Equals(unknown, camera));\r\n    print(\"ReferenceEquals(unknown, unknown):\", Object.ReferenceEquals(unknown, unknown));\r\n    print(\"ReferenceEquals(unknown, camera):\", Object.ReferenceEquals(unknown, camera));\r\n}\r\n"
  },
  {
    "path": "Scripts/src/example_reflectbind_helloworld.ts",
    "content": "import { DelegateTest } from \"Example\";\nimport { BoxCollider, Debug, GameObject, MonoBehaviour, Vector3 } from \"UnityEngine\";\n\nconsole.log(\"hello, world\");\nDebug.Log(<any>\"hello, world\");\n\nlet go = new GameObject(\"Happy Bot\");\n\nconsole.log(\"go.transform = \", go.transform);\nconsole.log(\"go.transform.localPosition.x = \", go.transform.localPosition.x);\n\nlet v = new Vector3(1, 1, 1);\nv.x = 2;\nconsole.log(\"v.x = \", v.x);\nconsole.log(\"v.magnitude = \", v.magnitude);\n\ngo.transform.localPosition = new Vector3(1, 1, 1);\n\nDelegateTest.onStaticActionWithArgs(\"set\", (a1, a2, a3) => console.log(\"delegate in js:\", a1, a2, a3));\nDelegateTest.CallStaticActionWithArgs(\"hello\", 123, 999);\n\nlet delegateTest = new DelegateTest();\ndelegateTest.onActionWithArgs(\"add\", (a1, a2, a3) => console.log(\"delegate in js1:\", a1, a2, a3));\ndelegateTest.onActionWithArgs(\"add\", (a1, a2, a3) => console.log(\"delegate in js2:\", a1, a2, a3));\ndelegateTest.CallActionWithArgs(\"hello\", 123, 999);\n\nclass HelloBehaviour extends MonoBehaviour {\n    Awake() {\n        console.log(\"Hello Behaviour Awake!\");\n    }\n\n    Greet() {\n        console.log(\"Good day!\");\n    }\n}\n\ngo.AddComponent(HelloBehaviour);\nlet helloBehaviour = go.GetComponent(HelloBehaviour);\nhelloBehaviour.Greet();\n\nconsole.log(go.AddComponent);\nlet box = go.AddComponent(BoxCollider);\nconsole.log(box);\n"
  },
  {
    "path": "Scripts/src/example_scriptable_object.ts",
    "content": "import { Camera, Object, Resources, ScriptableObject, Vector3 } from \"UnityEngine\";\nimport { MyScriptableObject } from \"./my_scriptable_object\";\n\nconsole.log(\"============ Load ScriptableObject from Resources ============\");\nlet js_data = <MyScriptableObject>Resources.Load(\"data/js_data\");\nif (js_data) {\n    console.log(\"typeof:\", typeof js_data);\n    console.log(\"type check:\", js_data instanceof MyScriptableObject);\n    console.log(\"type values:\", js_data.value1, js_data.value2);\n} else {\n    console.error(\"failed to load js_data, please create the asset at first.\");\n}\n\ntry {\n    console.log(\"============ ScriptableObject.CreateInstance ============ 111\");\n    let so = ScriptableObject.CreateInstance(MyScriptableObject);\n    if (so) {\n        // Resources.FindObjectsOfTypeAll can also properly process script types now\n        let results = Resources.FindObjectsOfTypeAll(MyScriptableObject);\n        do {\n            if (results) {\n                let len = results.length;\n                if (len > 0) {\n                    for (let i = 0; i < len; i++) {\n                        console.log(\"!!! find object:\", results[i]);\n                    }\n                    break;\n                }\n            }\n            console.warn(\"something wrong, no object found.\");\n        } while (false);\n\n        for (let i of Resources.FindObjectsOfTypeAll(Camera)) {\n            console.log(\"!!! camera\", i);\n        }\n\n        so.value3 = new Vector3(1, 2, 3);\n        so.value2 = \"Hello\";\n        console.log(\"value1:\", so.Process());\n        Object.DestroyImmediate(so);\n    } else {\n        console.error(\"fail to ScriptableObject.CreateInstance\");\n    }\n} catch (err) {\n    console.error(\"fail to ScriptableObject.CreateInstance\", err);\n}"
  },
  {
    "path": "Scripts/src/example_string_cache.ts",
    "content": "import { ValueTest } from \"Example\";\r\nimport * as jsb from \"jsb\";\r\n\r\n/*\r\n    jsb.AddCacheString is available to use to avoid unnecessary string allocations on frequently translating strings between Javascript and C#\r\n    NOTE: remove string from cache with jsb.RemoveCacheString\r\n*/\r\n\r\n{\r\n    console.log(\"string cache test:\")\r\n    let n = 100000;\r\n    let start = 0;\r\n    let end = 0;\r\n    let str = \"testing, testing, testing, testing, testing, testing, testing, testing\";\r\n\r\n    start = Date.now();\r\n    for (let i = 0; i < n; i++) {\r\n        ValueTest.Foo(str);\r\n    }\r\n    end = Date.now();\r\n    console.log(\"time1:\", (end - start) / 1000);\r\n\r\n    jsb.AddCacheString(str);\r\n\r\n    start = Date.now();\r\n    for (let i = 0; i < n; i++) {\r\n        ValueTest.Foo(str);\r\n    }\r\n    end = Date.now();\r\n    console.log(\"time2:\", (end - start) / 1000);\r\n}\r\n"
  },
  {
    "path": "Scripts/src/example_timer.ts",
    "content": "import { Random } from \"UnityEngine\";\r\nimport * as jsb from \"jsb\";\r\n\r\nlet _id = 0;\r\nfunction allocId() {\r\n    return ++_id;\r\n}\r\n\r\nlet all = 600;\r\nlet act = 0;\r\nfor (let i = 0; i < all; i++) {\r\n    let n = i;\r\n    let d1 = (n * 10 * Math.floor(Random.Range(100, 10000))) % (3 * 60 * 1000);\r\n    let e1 = d1 + jsb.Now();\r\n    setTimeout(t1 => {\r\n        if (n % 10 == 0) {\r\n            all++;\r\n            let d2 = Math.floor(Random.Range(1000 * 1, 1000 * 60 * 2));\r\n            let e2 = d2 + jsb.Now();\r\n            setTimeout(t2 => {\r\n                act++;\r\n                let n2 = jsb.Now();\r\n                let x2 = n2 - e2;\r\n                console.log(`    > ${n} ${t2.id} => Now: ${n2} Exp: ${e2} Delay: ${d2} Delta: ${x2} Act: ${act}/${all}`);\r\n            }, d2, { id: allocId() });\r\n        }\r\n        act++;\r\n        let n1 = jsb.Now();\r\n        let x1 = n1 - e1;\r\n        console.log(`TA ${n} ${t1.id} => Now: ${n1} Exp: ${e1} Delay: ${d1} Delta: ${x1} Act: ${act}/${all}`);\r\n    }, d1, { id: allocId() });\r\n}\r\n"
  },
  {
    "path": "Scripts/src/example_unity.ts",
    "content": "import { Yield } from \"jsb\";\r\nimport { Camera, Debug, GameObject, Object, Resources, WaitForSeconds } from \"UnityEngine\";\r\nimport { Object as Object1 } from \"System\";\r\nimport { MyClass } from \"./components/sample_monobehaviour\";\r\n\r\nif (module == require.main) {\r\n    let go = new GameObject(\"test\");\r\n    console.log(go.name);\r\n    go.name = \"testing\";\r\n    console.log(go.name);\r\n\r\n    async function destroy() {\r\n        await Yield(new WaitForSeconds(5));\r\n        Object.Destroy(go);\r\n\r\n        //! 机制原因, 无法直接利用 Object == 重载, 可以用 op_Implicit 判定 UnityEngine.Object 是否被销毁\r\n        console.log(\"after destroy, go == null?\", Object.op_Implicit(go));\r\n    }\r\n    destroy();\r\n\r\n    let camera = GameObject.Find(\"/Main Camera\").GetComponent(Camera);\r\n    let arr = camera.GetComponents(Camera);\r\n    print(\"array.length:\", arr.length);\r\n    print(\"array[0]:\", arr[0] == camera);\r\n\r\n    console.log(\"camera.name:\", camera.name);\r\n    Debug.LogWarningFormat(\"blablabla... {0}\", <Object1><any>123);\r\n\r\n    let testPrefab = Resources.Load(\"prefab/test\");\r\n    if (testPrefab) {\r\n        let testGameObject = <GameObject>Object.Instantiate(testPrefab);\r\n        let testMyClass = testGameObject.GetComponent(MyClass);\r\n\r\n        console.log(testMyClass);\r\n    } else {\r\n        console.warn(\"Resources/prefab/test.prefab not found\");\r\n    }\r\n}\r\n"
  },
  {
    "path": "Scripts/src/example_valuetype.ts",
    "content": "import { Vector2, Vector3 } from \"UnityEngine\";\r\n\r\nimport { ArrayTest } from \"Example\";\r\nimport { CreateJSArrayProxy, GetUnderlyingArray } from \"./experimental/array_proxy\";\r\n\r\nlet u = new Vector3(1, 2, 3);\r\n\r\nconsole.assert(u.x == 1, \"u.x should equals to 1\");\r\nu.Normalize();\r\nconsole.assert(Math.abs(u.magnitude - 1) < 0.00001, \"u.magnitude should equals to 1 after being normalized\");\r\n\r\nlet v1 = new Vector3(0, 0, 0)\r\nlet start = Date.now();\r\nfor (let i = 1; i < 200000; i++) {\r\n    v1.Set(i, i, i)\r\n    v1.Normalize()\r\n}\r\nconsole.log(\"js/vector3/normailize\", (Date.now() - start) / 1000);\r\n\r\nlet null_value = null;\r\nlet undefined_value = undefined;\r\nconsole.assert(!(null_value instanceof Vector3), \"null instanceof Vector3\");\r\nconsole.assert(!(undefined_value instanceof Vector3), \"undefined instanceof Vector3\");\r\nconsole.assert(v1 instanceof Vector3, \"(correct value) instanceof Vector3\");\r\nconsole.assert(!(Vector2.zero instanceof Vector3), \"(wrong value) instanceof Vector3\");\r\n\r\n// everytime you access Vector3.zero will return a new copy\r\nconsole.assert(Vector3.zero.magnitude == 0, \"Vector3.zero\");\r\nVector3.zero.Set(1, 2, 3);\r\nconsole.assert(Vector3.zero.magnitude == 0, \"Vector3.zero\");\r\n\r\n\r\n/** experimental\r\n *    CreateJSArrayProxy will be merged into value-conversion layer if possible. All of the System.Array objects will be treated as js array in d.ts after this feature implemented.\r\n */\r\nlet array1 = CreateJSArrayProxy(ArrayTest.values1);\r\n\r\n// size change will cause side-effect, array proxy target will detach from the original csharp variable reference\r\n// array1.push(3, 4, 5, 6); \r\n// ArrayTest.values1 = GetUnderlyingObject(array1);\r\n\r\narray1[0] = 123;\r\nconsole.log(\"length\", array1.length);\r\nconsole.log(\"join\", array1.join());\r\nconsole.log(\"reduce\", array1.reduce((p, c) => p + c));\r\nconsole.log(GetUnderlyingArray(array1));\r\nconsole.log(\"eq\", ArrayTest.values1 === GetUnderlyingArray(array1));\r\nconsole.log(\"len\", ArrayTest.values1.Length);\r\nconsole.log(\"[1]\", ArrayTest.values1.GetValue(0));\r\n"
  },
  {
    "path": "Scripts/src/example_websocket.ts",
    "content": "\r\nlet ws = new WebSocket(\"ws://127.0.0.1:8080/websocket\", \"default\");\r\n\r\nconsole.log(\"websocket connecting:\", ws.url);\r\n\r\nws.onopen = function () {\r\n    console.log(\"[ws.onopen]\", ws.readyState);\r\n    let count = 0;\r\n    setInterval(function () {\r\n        ws.send(\"websocket message test\" + count++);\r\n    }, 1000);\r\n};\r\nws.onclose = function () {\r\n    console.log(\"[ws.onclose]\", ws.readyState);\r\n};\r\nws.onerror = function (err) {\r\n    console.log(\"[ws.onerror]\", err);\r\n};\r\nws.onmessage = function (msg) {\r\n    console.log(\"[ws.recv]\", msg);\r\n};\r\n"
  },
  {
    "path": "Scripts/src/example_worker.ts",
    "content": "\r\nlet worker = new Worker(\"worker\");\r\nlet messageId = 0;\r\nlet messageQueue: { [k: number]: Function } = {};\r\n\r\n//TODO: 目前无法传递 C# 对象 (对象引用ID不共享)\r\n\r\nworker.onmessage = function (e: any) {\r\n    let data = e.data;\r\n    let p = messageQueue[data.id];\r\n    if (typeof p !== \"undefined\") {\r\n        p(data.result);\r\n    }\r\n}\r\n\r\nlet a = 1;\r\nlet b = 2;\r\n\r\nasync function test() {\r\n    a++;\r\n    b++;\r\n    let r = await remoteAdd(a, b);\r\n    console.log(`add(${a}, ${b}) = ${r}`);\r\n}\r\n\r\nasync function remoteAdd(a: number, b: number): Promise<number> {\r\n    let id = messageId++;\r\n    return new Promise(resolve => {\r\n        messageQueue[id] = resolve;\r\n        worker.postMessage({\r\n            \"id\": id,\r\n            \"method\": \"add\",\r\n            \"args\": [a, b]\r\n        });\r\n    });\r\n}\r\n\r\n\r\nconsole.log(\"test\");\r\ntest();\r\nsetInterval(() => test(), 3000);\r\n"
  },
  {
    "path": "Scripts/src/example_xhr.ts",
    "content": "\r\nlet xhr = new XMLHttpRequest();\r\n// xhr.open(\"GET\", \"http://127.0.0.1:8080/windows/checksum.txt\");\r\nxhr.open(\"GET\", \"https://www.baidu.com\");\r\nxhr.timeout = 3000;\r\nxhr.onerror = function (e) {\r\n    console.error(e);\r\n}\r\nxhr.onreadystatechange = function () {\r\n    console.log(\"readyState:\", xhr.readyState);\r\n    if (xhr.readyState !== 4) {\r\n        return;\r\n    }\r\n    console.log(\"status:\", xhr.status);\r\n    if (xhr.status == 200) {\r\n        console.log(\"responseText:\", xhr.responseText);\r\n    }\r\n}\r\nxhr.send();\r\nconsole.log(\"after send\");\r\n"
  },
  {
    "path": "Scripts/src/example_xlsx.ts",
    "content": "\r\n/*\r\n开发过程中可以使用 Default FileSystem 正常依赖 node_modules 中的库时\r\n当需要发布到 Resources/Assetbundle 时, 这种情况下需要使用 webpack 等打包工具将脚本依赖全部打包, 即可在最终环境中使用第三方库\r\n*/\r\n\r\n//NOTE: 此处 xlsx 在 package.json 中以 devDependencies 方式依赖, 仅开发环境有效. \r\n//      可以改为 dev, 自行按需调整.\r\n//      如运行报错, 请先确认是否已安装依赖包 (npm install 即可).\r\n\r\nconsole.log(\"please run 'npm install' at first if 'xlsx' module can not be resolved\");\r\n\r\nimport * as jsb from \"jsb\";\r\nimport { File } from \"System.IO\";\r\nimport * as xlsx from \"xlsx\";\r\n\r\nlet filename = \"Assets/Examples/Data/test.xlsx\";\r\nlet bytes = File.ReadAllBytes(filename);\r\nlet data = jsb.ToArrayBuffer(bytes);\r\nlet wb = xlsx.read(data, { type: \"buffer\" });\r\n\r\nconsole.log(\"read excel:\", filename);\r\nfor (var sheetIndex in wb.SheetNames) {\r\n    var sheetName = wb.SheetNames[sheetIndex]\r\n\r\n    console.log(`read sheet: ${sheetName}`);\r\n    var sheet = wb.Sheets[sheetName];\r\n    let csv = xlsx.utils.sheet_to_csv(sheet);\r\n    console.log(\"to_csv:\", csv);\r\n    var range = xlsx.utils.decode_range(sheet[\"!ref\"]);\r\n    for (var row = range.s.r; row <= range.e.r; row++) {\r\n        for (var col = range.s.c; col <= range.e.c; col++) {\r\n            var cell = sheet[xlsx.utils.encode_cell({ c: col, r: row })];\r\n            if (cell) {\r\n                console.log(cell.v);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Scripts/src/experimental/array_proxy.ts",
    "content": "import * as jsb from \"jsb\";\r\nimport { Array as CSharpArray } from \"System\";\r\n\r\nconst $GetLength = jsb.ArrayUtils.GetLength;\r\nconst $SetValue = jsb.ArrayUtils.SetValue;\r\nconst $GetValue = jsb.ArrayUtils.GetValue;\r\nconst $RemoveAt = jsb.ArrayUtils.RemoveAt;\r\nconst $Insert = jsb.ArrayUtils.Insert;\r\n\r\nconst UnderlyingValueAccess = Symbol.for(\"Underlying Native Array\");\r\n\r\nexport function GetUnderlyingArray(p) {\r\n    return p[UnderlyingValueAccess];\r\n}\r\n\r\nexport function CreateJSArrayProxy<T>(target: CSharpArray<T>): Array<T> {\r\n    let _members = {\r\n        /**\r\n         * Returns the value of the first element in the array where predicate is true, and undefined\r\n         * otherwise.\r\n         * @param predicate find calls predicate once for each element of the array, in ascending\r\n         * order, until it finds one where predicate returns true. If such an element is found, find\r\n         * immediately returns that element value. Otherwise, find returns undefined.\r\n         * @param thisArg If provided, it will be used as the this value for each invocation of\r\n         * predicate. If it is not provided, undefined is used instead.\r\n         */\r\n        // find<S extends T>(predicate: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined;\r\n        \"find\": function (predicate: (value: any, index: number, obj: any[]) => unknown, thisArg?: any): any | undefined {\r\n            let copy = new Array(...this);\r\n            for (let i = 0, n = copy.length; i < n; ++i) {\r\n                let v = copy[i];\r\n                if (Boolean(predicate.call(thisArg, v, i, this))) {\r\n                    return v;\r\n                }\r\n            }\r\n            // return new Array(...this).find(predicate, thisArg);\r\n        },\r\n\r\n        /**\r\n         * Returns the index of the first element in the array where predicate is true, and -1\r\n         * otherwise.\r\n         * @param predicate find calls predicate once for each element of the array, in ascending\r\n         * order, until it finds one where predicate returns true. If such an element is found,\r\n         * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n         * @param thisArg If provided, it will be used as the this value for each invocation of\r\n         * predicate. If it is not provided, undefined is used instead.\r\n         */\r\n        \"findIndex\": function (predicate: (value: any, index: number, obj: any[]) => unknown, thisArg?: any): number {\r\n            let copy = new Array(...this);\r\n            for (let i = 0, n = copy.length; i < n; ++i) {\r\n                let v = copy[i];\r\n                if (Boolean(predicate.call(thisArg, v, i, this))) {\r\n                    return i;\r\n                }\r\n            }\r\n            return -1;\r\n            // return new Array(...this).findIndex(predicate, thisArg);\r\n        },\r\n\r\n        /**\r\n         * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n         * @param value value to fill array section with\r\n         * @param start index to start filling the array at. If start is negative, it is treated as\r\n         * length+start where length is the length of the array.\r\n         * @param end index to stop filling the array at. If end is negative, it is treated as\r\n         * length+end.\r\n         */\r\n        fill(value: any, start?: number, end?: number): any {\r\n            let n = $GetLength(target);\r\n            if (typeof start === \"undefined\") {\r\n                start = 0;\r\n            } else if (start < 0) {\r\n                start = n + start;\r\n            }\r\n            if (typeof end === \"undefined\") {\r\n                end = n;\r\n            } else if (end < 0) {\r\n                end = n + end;\r\n            }\r\n            for (let i = start; i < end; ++i) {\r\n                $SetValue(target, i, value);\r\n            }\r\n            return this;\r\n        },\r\n\r\n        /**\r\n         * Returns the this object after copying a section of the array identified by start and end\r\n         * to the same array starting at position target\r\n         * @param target If target is negative, it is treated as length+target where length is the\r\n         * length of the array.\r\n         * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n         * is treated as length+end.\r\n         * @param end If not specified, length of the this object is used as its default value.\r\n         */\r\n        \"copyWithin\": function (target_: number, start: number, end?: number): any {\r\n            let c = new Array(...this);\r\n            c.copyWithin(target_, start, end);\r\n            for (let i = 0, n = c.length; i < n; ++i) {\r\n                $SetValue(target, i, c[i]);\r\n            }\r\n            return this;\r\n        },\r\n\r\n        /** es2015.iterable */\r\n        [Symbol.iterator]: function () {\r\n            let i = 0;\r\n\r\n            return {\r\n                next: function () {\r\n                    let currentIndex = i++;\r\n                    return currentIndex < $GetLength(target) ? {\r\n                        value: $GetValue(target, currentIndex),\r\n                        done: false,\r\n                    } : { done: true };\r\n                },\r\n            }\r\n        },\r\n\r\n        /** es2015.iterable */\r\n        \"entries\": function () {\r\n            return {\r\n                [Symbol.iterator]: function () {\r\n                    let i = 0;\r\n                    return {\r\n                        next: function () {\r\n                            let currentIndex = i++;\r\n                            return currentIndex < $GetLength(target) ? {\r\n                                value: [currentIndex, $GetValue(target, currentIndex)],\r\n                                done: false,\r\n                            } : { done: true };\r\n                        },\r\n                    }\r\n                }\r\n            }\r\n        },\r\n\r\n        /** es2015.iterable */\r\n        \"keys\": function () {\r\n            return {\r\n                [Symbol.iterator]: function () {\r\n                    let i = 0;\r\n                    return {\r\n                        next: function () {\r\n                            let currentIndex = i++;\r\n                            return currentIndex < $GetLength(target) ? {\r\n                                value: currentIndex,\r\n                                done: false,\r\n                            } : { done: true };\r\n                        },\r\n                    }\r\n                }\r\n            }\r\n        },\r\n\r\n        /** es2015.iterable */\r\n        \"values\": function () {\r\n            return {\r\n                [Symbol.iterator]: function () {\r\n                    let i = 0;\r\n                    return {\r\n                        next: function () {\r\n                            let currentIndex = i++;\r\n                            return currentIndex < $GetLength(target) ? {\r\n                                value: $GetValue(target, currentIndex),\r\n                                done: false,\r\n                            } : { done: true };\r\n                        },\r\n                    }\r\n                }\r\n            }\r\n        },\r\n\r\n        /**\r\n         * es5\r\n         * Returns a string representation of an array.\r\n         */\r\n        \"toString\": function () {\r\n            return `ArrayWrapper(${this.length})`;\r\n        },\r\n        /**\r\n         * es5\r\n         * Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.\r\n         */\r\n        \"toLocaleString\": function () {\r\n            return `ArrayWrapper(${this.length})`;\r\n        },\r\n        /**\r\n         * es5\r\n         * Removes the last element from an array and returns it.\r\n         * If the array is empty, undefined is returned and the array is not modified.\r\n         */\r\n        \"pop\": function () {\r\n            if ($GetLength(target) > 0) {\r\n                let v = $GetValue(target, $GetLength(target) - 1);\r\n                $RemoveAt(target, $GetLength(target) - 1);\r\n                return v;\r\n            }\r\n        },\r\n        /**\r\n         * es5\r\n         * Appends new elements to the end of an array, and returns the new length of the array.\r\n         * @param items New elements to add to the array.\r\n         */\r\n        \"push\": function (...items: any[]) {\r\n            let n = $GetLength(target);\r\n            for (let i = 0; i < items.length; i++) {\r\n                console.log(\"set value\", i, n + 1);\r\n                $SetValue(target, n + i, items[i]);\r\n            }\r\n        },\r\n        /**\r\n         * es5\r\n         * Combines two or more arrays.\r\n         * This method returns a new array without modifying any existing arrays.\r\n         * @param items Additional arrays and/or items to add to the end of the array.\r\n         */\r\n        \"concat\": function (...items: (any | ConcatArray<any>)[]): any[] {\r\n            let r = new Array(...this);\r\n            for (let ii = 0, il = items.length; ii < il; ++ii) {\r\n                let e = items[ii];\r\n                if (typeof e === \"object\" && e instanceof Array) {\r\n                    for (let si = 0, sl = e.length; si < sl; ++si) {\r\n                        r.push(e[si]);\r\n                    }\r\n                } else {\r\n                    r.push(e);\r\n                }\r\n            }\r\n            return r;\r\n        },\r\n        /**\r\n         * es5\r\n         * Adds all the elements of an array into a string, separated by the specified separator string.\r\n         * @param separator A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.\r\n         */\r\n        \"join\": function (separator?: string): string {\r\n            if (typeof separator === \"undefined\") {\r\n                separator = \",\";\r\n            }\r\n\r\n            let r = \"\";\r\n            for (let i = 0, n = $GetLength(target); i < n; ++i) {\r\n                if (i != n - 1) {\r\n                    r += $GetValue(target, i) + separator;\r\n                } else {\r\n                    r += $GetValue(target, i);\r\n                }\r\n            }\r\n            return r;\r\n        },\r\n        /**\r\n         * es5\r\n         * Reverses the elements in an array in place.\r\n         * This method mutates the array and returns a reference to the same array.\r\n         */\r\n        \"reverse\": function (): any[] {\r\n            let n = $GetLength(target);\r\n            let m = Math.floor(n / 2);\r\n            for (let i = 0; i < m; ++i) {\r\n                let i2 = n - i - 1;\r\n                let t1 = $GetValue(target, i2);\r\n                let t2 = $GetValue(target, i);\r\n                $SetValue(target, i, t1);\r\n                $SetValue(target, i2, t2);\r\n            }\r\n            return this;\r\n        },\r\n        /**\r\n         * es5\r\n         * Removes the first element from an array and returns it.\r\n         * If the array is empty, undefined is returned and the array is not modified.\r\n         */\r\n        \"shift\": function (): any | undefined {\r\n            if ($GetLength(target) > 0) {\r\n                let f = $GetValue(target, 0);\r\n                $RemoveAt(target, 0);\r\n                return f;\r\n            }\r\n        },\r\n        /**\r\n         * es5\r\n         * Returns a copy of a section of an array.\r\n         * For both start and end, a negative index can be used to indicate an offset from the end of the array.\r\n         * For example, -2 refers to the second to last element of the array.\r\n         * @param start The beginning index of the specified portion of the array.\r\n         * If start is undefined, then the slice begins at index 0.\r\n         * @param end The end index of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n         * If end is undefined, then the slice extends to the end of the array.\r\n         */\r\n        \"slice\": function (start?: number, end?: number): any[] {\r\n            let n = $GetLength(target);\r\n            let r = [];\r\n            if (typeof start === \"undefined\") {\r\n                start = 0;\r\n            } else if (start < 0) {\r\n                start = n + start;\r\n            }\r\n            if (typeof end === \"undefined\") {\r\n                end = 0;\r\n            } else if (end < 0) {\r\n                end = n + end;\r\n            }\r\n            if (start < end) {\r\n                for (let i = start; i < end; ++i) {\r\n                    r.push($GetValue(target, i));\r\n                }\r\n            }\r\n            return r;\r\n        },\r\n        /**\r\n         * es5\r\n         * Sorts an array in place.\r\n         * This method mutates the array and returns a reference to the same array.\r\n         * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n         * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\r\n         * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.\r\n         * ```ts\r\n         * [11,2,22,1].sort((a, b) => a - b)\r\n         * ```\r\n         */\r\n        \"sort\": function (compareFn?: (a: any, b: any) => number): any {\r\n            let n = $GetLength(target);\r\n            if (n > 1) {\r\n                let r = new Array(...this).sort(compareFn);\r\n                for (let i = 0; i < n; ++i) {\r\n                    $SetValue(target, i, r[i]);\r\n                }\r\n            }\r\n            return this;\r\n        },\r\n        /**\r\n         * es5\r\n         * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.\r\n         * @param start The zero-based location in the array from which to start removing elements.\r\n         * @param deleteCount The number of elements to remove.\r\n         * @param items Elements to insert into the array in place of the deleted elements.\r\n         * @returns An array containing the elements that were deleted.\r\n         */\r\n        \"splice\": function (start: number, deleteCount: number, ...items: any[]): any[] {\r\n            let len = $GetLength(target);\r\n            let res = [];\r\n            if (start < len) {\r\n                let m = len - start;\r\n                if (typeof deleteCount === \"number\" && m > deleteCount) {\r\n                    m = deleteCount;\r\n                }\r\n                for (let i = 0; i < m; ++i) {\r\n                    res.push($GetValue(target, start));\r\n                    $RemoveAt(target, start);\r\n                }\r\n                for (let i = 0, c = items.length; i < c; ++i) {\r\n                    $Insert(target, start, items[c - i - 1]);\r\n                }\r\n            } else {\r\n                for (let i = 0, c = items.length; i < c; ++i) {\r\n                    $Insert(target, len, items[c - i - 1]);\r\n                }\r\n            }\r\n            return res;\r\n        },\r\n        /**\r\n         * es5\r\n         * Inserts new elements at the start of an array, and returns the new length of the array.\r\n         * @param items Elements to insert at the start of the array.\r\n         */\r\n        \"unshift\": function (...items: any[]): number {\r\n            for (let i = 0, n = items.length; i < n; ++i) {\r\n                $Insert(target, 0, items[n - i - 1]);\r\n            }\r\n            return $GetLength(target);\r\n        },\r\n        /**\r\n         * es5\r\n         * Returns the index of the first occurrence of a value in an array, or -1 if it is not present.\r\n         * @param searchElement The value to locate in the array.\r\n         * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.\r\n         */\r\n        \"indexOf\": function (searchElement: any, fromIndex?: number): number {\r\n            if (typeof fromIndex !== \"number\") {\r\n                fromIndex = 0;\r\n            } else {\r\n                fromIndex = fromIndex <= 0 ? 0 : Math.floor(fromIndex);\r\n            }\r\n            for (let i = fromIndex, n = $GetLength(target); i < n; ++i) {\r\n                if ($GetValue(target, i) == searchElement) {\r\n                    return i;\r\n                }\r\n            }\r\n            return -1;\r\n        },\r\n        /**\r\n         * es5\r\n         * Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.\r\n         * @param searchElement The value to locate in the array.\r\n         * @param fromIndex The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.\r\n         */\r\n        \"lastIndexOf\": function (searchElement: any, fromIndex?: number): number {\r\n            if (typeof fromIndex !== \"number\") {\r\n                fromIndex = $GetLength(target) - 1;\r\n            } else {\r\n                if (fromIndex < 0) {\r\n                    fromIndex = $GetLength(target) + fromIndex;\r\n                }\r\n            }\r\n            for (let i = fromIndex; i >= 0; --i) {\r\n                if ($GetValue(target, i) == searchElement) {\r\n                    return i;\r\n                }\r\n            }\r\n            return -1;\r\n        },\r\n        /**\r\n         * es5\r\n         * Determines whether all the members of an array satisfy the specified test.\r\n         * @param predicate A function that accepts up to three arguments. The every method calls\r\n         * the predicate function for each element in the array until the predicate returns a value\r\n         * which is coercible to the Boolean value false, or until the end of the array.\r\n         * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n         * If thisArg is omitted, undefined is used as the this value.\r\n         */\r\n        \"every\": function (predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): boolean {\r\n            for (let i = 0, n = $GetLength(target); i < n; ++i) {\r\n                let item = $GetValue(target, i);\r\n                if (!Boolean(predicate.call(thisArg, item, i, this))) {\r\n                    return false;\r\n                }\r\n            }\r\n            return true;\r\n        },\r\n        /**\r\n         * es5\r\n         * Determines whether the specified callback function returns true for any element of an array.\r\n         * @param predicate A function that accepts up to three arguments. The some method calls\r\n         * the predicate function for each element in the array until the predicate returns a value\r\n         * which is coercible to the Boolean value true, or until the end of the array.\r\n         * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n         * If thisArg is omitted, undefined is used as the this value.\r\n         */\r\n        \"some\": function (predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): boolean {\r\n            for (let i = 0, n = $GetLength(target); i < n; ++i) {\r\n                let item = $GetValue(target, i);\r\n                if (Boolean(predicate.call(thisArg, item, i, this))) {\r\n                    return true;\r\n                }\r\n            }\r\n            return false;\r\n        },\r\n        /**\r\n         * es5\r\n         * Performs the specified action for each element in an array.\r\n         * @param callbackfn  A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.\r\n         * @param thisArg  An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\r\n         */\r\n        \"forEach\": function (callbackfn: (value: any, index: number, array: any[]) => void, thisArg?: any): void {\r\n            if (typeof thisArg !== \"undefined\") {\r\n                for (let i = 0, n = $GetLength(target); i < n; i++) {\r\n                    callbackfn.call(thisArg, $GetValue(target, i), i, this);\r\n                }\r\n            } else {\r\n                for (let i = 0, n = $GetLength(target); i < n; i++) {\r\n                    callbackfn($GetValue(target, i), i, this);\r\n                }\r\n            }\r\n        },\r\n        /**\r\n         * es5\r\n         * Calls a defined callback function on each element of an array, and returns an array that contains the results.\r\n         * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\r\n         * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\r\n         */\r\n        map(callbackfn: (value: any, index: number, array: any[]) => any, thisArg?: any): any[] {\r\n            let n = $GetLength(target);\r\n            let r = new Array(n);\r\n            for (let i = 0; i < n; i++) {\r\n                let e = callbackfn.call(thisArg, $GetValue(target, i), i, this);\r\n                r.push(e);\r\n            }\r\n            return r;\r\n        },\r\n        /**\r\n         * es5\r\n         * Returns the elements of an array that meet the condition specified in a callback function.\r\n         * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.\r\n         * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.\r\n         */\r\n        \"filter\": function (predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): any[] {\r\n            let res = [];\r\n            for (let i = 0, n = $GetLength(target); i < n; ++i) {\r\n                let item = $GetValue(target, i);\r\n                if (Boolean(predicate.call(thisArg, item, i, this))) {\r\n                    res.push(item);\r\n                }\r\n            }\r\n            return res;\r\n        },\r\n        /**\r\n         * es5\r\n         * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n         * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\r\n         * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n         */\r\n        \"reduce\": function (callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: any[]) => any, initialValue: any): any {\r\n            let n = $GetLength(target);\r\n            if (n > 0) {\r\n                let previousValue, currentValue;\r\n                if (typeof initialValue !== \"undefined\") {\r\n                    previousValue = initialValue;\r\n                    for (let i = 0; i < n; ++i) {\r\n                        currentValue = $GetValue(target, i);\r\n                        previousValue = callbackfn(previousValue, currentValue, i, this);\r\n                    }\r\n                    return previousValue;\r\n                } else {\r\n                    previousValue = $GetValue(target, 0);\r\n                    for (let i = 1; i < n; ++i) {\r\n                        currentValue = $GetValue(target, i);\r\n                        previousValue = callbackfn(previousValue, currentValue, i, this);\r\n                    }\r\n                    return previousValue;\r\n                }\r\n            }\r\n            return initialValue;\r\n        },\r\n        /**\r\n         * es5\r\n         * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n         * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\r\n         * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n         */\r\n        \"reduceRight\": function (callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: any[]) => any, initialValue: any): any {\r\n            let n = $GetLength(target);\r\n            if (n > 0) {\r\n                let previousValue, currentValue;\r\n                if (typeof initialValue !== \"undefined\") {\r\n                    previousValue = initialValue;\r\n                    for (let i = n - 1; i >= 0; --i) {\r\n                        currentValue = $GetValue(target, i);\r\n                        previousValue = callbackfn(previousValue, currentValue, i, this);\r\n                    }\r\n                    return previousValue;\r\n                } else {\r\n                    previousValue = $GetValue(target, n - 1);\r\n                    for (let i = n - 2; i >= 0; --i) {\r\n                        currentValue = $GetValue(target, i);\r\n                        previousValue = callbackfn(previousValue, currentValue, i, this);\r\n                    }\r\n                    return previousValue;\r\n                }\r\n            }\r\n            return initialValue;\r\n        },\r\n    }\r\n\r\n    let _getter = {\r\n        [UnderlyingValueAccess]: function () {\r\n            return target;\r\n        },\r\n        \"length\": function () {\r\n            return $GetLength(target);\r\n        },\r\n    }\r\n\r\n    let _setter = {\r\n        \"length\": function (value: number) {\r\n            throw new Error(\"unsupported\");\r\n        },\r\n    }\r\n\r\n    return <any>new Proxy(target, {\r\n        get(target: CSharpArray<T>, p: string | symbol, receiver: any): any {\r\n            if (typeof p === \"string\" && p.length > 0) {\r\n                let c = p.charCodeAt(0);\r\n                if (c >= 48 && c <= 57) {\r\n                    let index = Number.parseInt(p);\r\n                    return $GetValue(target, index);\r\n                }\r\n            }\r\n\r\n            let mf = Object.getOwnPropertyDescriptor(_members, p) && _members[p];\r\n            if (typeof mf !== \"undefined\") {\r\n                return mf;\r\n            }\r\n\r\n            let mp = Object.getOwnPropertyDescriptor(_getter, p) && _getter[p];\r\n            if (typeof mp !== \"undefined\") {\r\n                return mp();\r\n            }\r\n            console.warn(\"unknown property\", p);\r\n        },\r\n\r\n        set(target: CSharpArray<T>, p: string | symbol, value: any, receiver: any): boolean {\r\n            if (typeof p === \"string\" && p.length > 0) {\r\n                let c = p.charCodeAt(0);\r\n                if (c >= 48 && c <= 57) {\r\n                    let index = Number.parseInt(p);\r\n                    $SetValue(target, index, value);\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            let mp = Object.getOwnPropertyDescriptor(_setter, p) && _setter[p];\r\n            if (typeof mp !== \"undefined\") {\r\n                mp(value);\r\n                return true;\r\n            }\r\n            return false;\r\n        },\r\n\r\n        // getPrototypeOf(target: MyArray): object {\r\n        //     return Array.prototype;\r\n        // },\r\n\r\n        ownKeys(target: CSharpArray<T>): ArrayLike<string | symbol> {\r\n            return new Proxy({}, {\r\n                get(_1: any, p: string | symbol): any {\r\n                    if (typeof p === \"string\") {\r\n                        if (p === \"length\") {\r\n                            return $GetLength(target);\r\n                        }\r\n                    }\r\n                    return p;\r\n                },\r\n            });\r\n        },\r\n\r\n        getOwnPropertyDescriptor(target: CSharpArray<T>, p: string | symbol): PropertyDescriptor {\r\n            return { enumerable: true, configurable: true, value: this[p] };\r\n        },\r\n    });\r\n}\r\n"
  },
  {
    "path": "Scripts/src/experimental_gtype.ts",
    "content": "// declare abstract class TWrapper<T> extends System.Object {\r\n//     constructor(obj: T)\r\n//     GetValue(): T\r\n//     SetValue(obj: T)\r\n//     static GetIntWrapper(): TWrapper<number>\r\n// }\r\n// declare class TWrapper_Int32 extends TWrapper<number> {\r\n// }\r\n// declare class TWrapper_Vector3 extends TWrapper<UnityEngine.Vector3> {\r\n// }\r\n\r\n// new TWrapper_Int32(1);"
  },
  {
    "path": "Scripts/src/fib.ts",
    "content": "﻿\r\n/* fib module */\r\nexport function fib(n)\r\n{\r\n    if (n <= 0)\r\n        return 0;\r\n    else if (n == 1)\r\n        return 1;\r\n    else\r\n        return fib(n - 1) + fib(n - 2);\r\n}\r\n"
  },
  {
    "path": "Scripts/src/game/editor/king_human_controller_inspector.ts",
    "content": "import { Editor, EditorGUI, EditorGUILayout, EditorUtility, MessageType } from \"UnityEditor\";\nimport { Animator, GUILayout, Object, Vector2 } from \"UnityEngine\";\nimport { EditorUtil, ScriptEditor } from \"plover/editor/editor_decorators\";\nimport { KingHumanController, MyNestedPlainObject } from \"../king_human_controller\";\n\n@ScriptEditor(KingHumanController)\nexport class KingHumanControllerInspector extends Editor {\n    OnInspectorGUI() {\n        let p = <KingHumanController>this.target;\n\n        // EditorUtil.draw(p);\n        EditorGUI.BeginChangeCheck();\n        p.animator = <Animator>EditorGUILayout.ObjectField(\"Animator\", p.animator, Animator, true);\n        p.moveSpeed = EditorGUILayout.FloatField(\"Move Speed\", p.moveSpeed);\n        if (!p.nestedValue) {\n            p.nestedValue = new MyNestedPlainObject();\n        }\n        p.nestedValue.nestedString = EditorGUILayout.TextField(\"nestedString\", p.nestedValue.nestedString);\n        p.nestedValue.nestedVector3 = EditorGUILayout.Vector3Field(\"nestedVector3\", p.nestedValue.nestedVector3);\n\n        if (GUILayout.Button(\"Add Position\")) {\n            if (p.nestedValue.positions == null) {\n                p.nestedValue.positions = [];\n            }\n            p.nestedValue.positions.push(Vector2.zero);\n            EditorUtility.SetDirty(p);\n        }\n\n        let positionCount = p.nestedValue.positions != null ? p.nestedValue.positions.length : 0;\n        for (let i = 0; i < positionCount; i++) {\n            p.nestedValue.positions[i] = EditorGUILayout.Vector2Field(\"Position\", p.nestedValue.positions[i] || Vector2.zero);\n        }\n\n        if (EditorGUI.EndChangeCheck()) {\n            EditorUtility.SetDirty(p);\n        }\n\n        if (GUILayout.Button(\"Speak\")) {\n            console.log(\"Hello, world 666 !\");\n        }\n\n        if (GUILayout.Button(\"Attack\")) {\n            p.animator.Play(\"Attack\", 0, 1);\n        }\n\n        if (GUILayout.Button(\"Idle\")) {\n            p.animator.Play(\"Idle\", 0, 1);\n        }\n    }\n}\n"
  },
  {
    "path": "Scripts/src/game/king_human_controller.ts",
    "content": "import { Animator, Input, KeyCode, MonoBehaviour, SpriteRenderer, Time, Vector2, Vector3 } from \"UnityEngine\";\nimport { ScriptType, ScriptObject, ScriptNumber, ScriptSerializable, ScriptString, ScriptProperty } from \"plover/runtime/class_decorators\";\n\n@ScriptSerializable()\nexport class MyNestedPlainObject {\n    @ScriptString()\n    nestedString = \"nestedString\";\n\n    @ScriptProperty({ type: \"Vector3\" })\n    nestedVector3 = Vector3.zero;\n\n    @ScriptProperty({ type: \"Vector2\"})\n    positions: Array<Vector2>;\n}\n\n@ScriptType()\nexport class KingHumanController extends MonoBehaviour {\n    @ScriptObject({ editorOnly: true })\n    animator: Animator;\n\n    @ScriptNumber()\n    moveSpeed = 1.8;\n\n    @ScriptProperty({ type: MyNestedPlainObject })\n    nestedValue: MyNestedPlainObject;\n\n    private moving = false;\n    private spriteRenderer: SpriteRenderer;\n\n    Awake() {\n        // this.transform.localScale = new Vector3(1, 1, 1);\n        // this.transform.localPosition = new Vector3(1.0, 2.2, 0);\n    }\n\n    OnAfterDeserialize() {\n        // 发生脚本重载时不会触发 Awake 所以在此处赋值\n        this.spriteRenderer = this.GetComponent(SpriteRenderer);\n    }\n\n    Update() {\n        if (Input.anyKey) {\n            let hori = 0;\n            let vert = 0;\n\n            if (Input.GetKey(KeyCode.A)) {\n                hori = -1;\n            } else if (Input.GetKey(KeyCode.D)) {\n                hori = 1;\n            }\n\n            // if (Input.GetKey(KeyCode.W)) {\n            //     vert = 1;\n            // } else if (Input.GetKey(KeyCode.S)) {\n            //     vert = -1;\n            // }\n\n            if (hori != 0 || vert != 0) {\n                let scale = Time.deltaTime * this.moveSpeed;\n                this.transform.Translate(hori * scale, vert * scale, 0);\n                if (hori != 0) {\n                    this.spriteRenderer.flipX = hori < 0;\n                }\n                if (!this.moving) {\n                    this.moving = true;\n                    this.animator.Play(\"Run\", 0);\n                    // console.log(\"go1\");\n                }\n            } else {\n                if (this.moving) {\n                    this.moving = false;\n                    this.animator.Play(\"Idle\", 0);\n                }\n            }\n        } else {\n            if (this.moving) {\n                this.moving = false;\n                this.animator.Play(\"Idle\", 0);\n            }\n        }\n    }\n}\n\n"
  },
  {
    "path": "Scripts/src/game_demo.ts",
    "content": "import { GameObject, Object, Resources } from \"UnityEngine\";\n\nif (!GameObject.Find(\"/game_stage\")) {\n    let path = \"prefab/game_stage\";\n    let prefab = Resources.Load(path);\n\n    if (prefab) {\n        let inst = Object.Instantiate(prefab);\n        inst.name = \"game_stage\";\n    } else {\n        console.error(\"game stage not found:\", path);\n    }\n}\n"
  },
  {
    "path": "Scripts/src/index.html",
    "content": "<!DOCTYPE html>\r\n<html>\r\n\r\n<head>\r\n    <meta charset=\"UTF-8\" />\r\n    <title>index</title>\r\n</head>\r\n\r\n<body>\r\n    <h1>hello webpack</h1>\r\n</body>\r\n\r\n</html>"
  },
  {
    "path": "Scripts/src/my_scriptable_object.ts",
    "content": "import { ScriptableObject, Vector3 } from \"UnityEngine\";\r\nimport { ScriptAsset, ScriptNumber, ScriptString, ScriptProperty, ScriptSerializable } from \"plover/runtime/class_decorators\";\r\n\r\n@ScriptAsset()\r\nexport class MyScriptableObject extends ScriptableObject {\r\n    @ScriptNumber()\r\n    value1 = 1;\r\n\r\n    @ScriptString()\r\n    value2 = \"hello\";\r\n\r\n    @ScriptProperty({ type: \"Vector3\" })\r\n    value3 = Vector3.zero;\r\n\r\n    @ScriptNumber()\r\n    value5: Array<number> = [];\r\n\r\n    Process() {\r\n        return `${this.value2} ${this.value3}`;\r\n    }\r\n\r\n    Reset() {\r\n        this.value1 = 0;\r\n        this.value2 = \"\";\r\n        this.value3 = Vector3.zero;\r\n        this.value5 = [1, 2, 3];\r\n    }\r\n}\r\n"
  },
  {
    "path": "Scripts/src/req_test1.ts",
    "content": "﻿\r\nvar e2 = require(\"./req_test2\");\r\n\r\nexports.test = \"hello: \" + e2.test;\r\nconsole.log(\"[req_test1] \", exports.test, __dirname, __filename);\r\nconsole.log(\"req_test, isMain?\", module == require.main);\r\n"
  },
  {
    "path": "Scripts/src/req_test2.ts",
    "content": "﻿\r\nconsole.log(\"[req_test2] i am test2\");\r\nexports.test = \"test 2\";\r\n"
  },
  {
    "path": "Scripts/src/test.ts",
    "content": "﻿\nlet s = Symbol.for(\"test\");\n\nclass Foo {\n    v1 = 1;\n    private v2 = 2;\n\n    foo() {\n    }\n}\n\n\nlet foo = new Foo();\n\nfoo[s] = 1;\n\nfor (let k in foo) {\n    console.log(k, typeof foo[k]);\n}\n\nconsole.log(\"symbol\", foo[s]);\n"
  },
  {
    "path": "Scripts/src/worker.ts",
    "content": "\r\nonmessage = function (e: any) {\r\n    let data = e.data;\r\n    switch (data.method) {\r\n        case \"add\": {\r\n            let x = 0;\r\n            let s = Date.now();\r\n            // 这里假装要处理很久很久\r\n            for (let i = 0; i < 10000000; i++) {\r\n                x++;\r\n            }\r\n            let d = Date.now() - s;\r\n            console.log(\"[worker] duration:\", d, \"repeated:\", x);\r\n            \r\n            postMessage({\r\n                \"id\": data.id,\r\n                \"result\": data.args[0] + data.args[1],\r\n            });\r\n            break;\r\n        }\r\n        default: {\r\n            postMessage({\r\n                \"id\": data.id,\r\n                \"result\": \"unknown method\",\r\n            });\r\n            break;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Scripts/types/dummy.d.ts",
    "content": "\r\n\r\n//\r\n"
  },
  {
    "path": "gulpfile-config.json",
    "content": "{\r\n    \"source\": \"./Scripts/out/*.js\",\r\n    \"dist\": \"./Scripts/dist/\",\r\n    \"config\": \"./Scripts/config/*.json\",\r\n    \"protogen\": \"./Scripts/protogen/*.js\",\r\n    \"outputBase\": \"./Assets/Examples/Scripts/\",\r\n    \"resources\": \"./Assets/Examples/Resources/\"\r\n}\r\n"
  },
  {
    "path": "gulpfile.js",
    "content": "const gulp = require('gulp')\r\nconst fs = require('fs')\r\nconst path = require('path')\r\nconst concat = require('gulp-concat');\r\nconst rename = require('gulp-rename');\r\nconst uglifyes = require('uglify-es');\r\nconst composer = require('gulp-uglify/composer');\r\nconst minify = composer(uglifyes, console);\r\nconst babel = require('gulp-babel');\r\nconst clean = require('gulp-clean');\r\nconst sequence = require('run-sequence');\r\n// const oss = require('ali-oss')\r\nconst crypto = require('crypto')\r\n\r\nconst self_config = require('./gulpfile-config.json')\r\n\r\n// 合并用户JS\r\ngulp.task('compile', function () {\r\n    let stream = gulp.src(self_config.source)\r\n        // .pipe(babel())\r\n        // .pipe(concat('main.js'))\r\n        .pipe(minify())\r\n        .pipe(gulp.dest(self_config.dist));\r\n    return stream;\r\n});\r\n\r\ngulp.task('copy-res-scripts', function () {\r\n    let stream = gulp.src(self_config.dist + '*')\r\n        .pipe(rename({ 'extname': '.js.txt' }))\r\n        .pipe(gulp.dest(self_config.resources + \"dist\"))\r\n    return stream;\r\n});\r\n\r\ngulp.task('copy-res-config', function () {\r\n    let stream = gulp.src(self_config.config + '*')\r\n        .pipe(rename({ 'extname': '.json.txt' }))\r\n        .pipe(gulp.dest(self_config.resources + \"config\"))\r\n    return stream;\r\n});\r\n\r\ngulp.task('copy-res-protogen', function () {\r\n    let stream = gulp.src(self_config.protogen + '*')\r\n        .pipe(rename({ 'extname': '.js.txt' }))\r\n        .pipe(gulp.dest(self_config.resources + \"protogen\"))\r\n    return stream;\r\n});\r\n\r\ngulp.task('clean', function () {\r\n    let stream = gulp.src([\r\n        self_config.resources + 'dist/*',\r\n        self_config.resources + 'protogen/*',\r\n        self_config.resources + 'config/*'\r\n    ]).pipe(clean({ force: true }))\r\n    return stream;\r\n});\r\n\r\n// 打包 \r\ngulp.task('default', gulp.series(\r\n    'clean',\r\n    'compile',\r\n    'copy-res-scripts',\r\n    'copy-res-config',\r\n    'copy-res-protogen',\r\n    function (cb) {\r\n        // target_platform = \"release\"\r\n        cb();\r\n    }));\r\n"
  },
  {
    "path": "jsb_build/cmake/iOS.cmake",
    "content": "# This file is based off of the Platform/Darwin.cmake and Platform/UnixPaths.cmake\n# files which are included with CMake 2.8.4\n# It has been altered for iOS development\n\n# Options:\n#\n# IOS_PLATFORM = OS (default) or SIMULATOR\n#   This decides if SDKS will be selected from the iPhoneOS.platform or iPhoneSimulator.platform folders\n#   OS - the default, used to build for iPhone and iPad physical devices, which have an arm arch.\n#   SIMULATOR - used to build for the Simulator platforms, which have an x86 arch.\n#\n# CMAKE_IOS_DEVELOPER_ROOT = automatic(default) or /path/to/platform/Developer folder\n#   By default this location is automatcially chosen based on the IOS_PLATFORM value above.\n#   If set manually, it will override the default location and force the user of a particular Developer Platform\n#\n# CMAKE_IOS_SDK_ROOT = automatic(default) or /path/to/platform/Developer/SDKs/SDK folder\n#   By default this location is automatcially chosen based on the CMAKE_IOS_DEVELOPER_ROOT value.\n#   In this case it will always be the most up-to-date SDK found in the CMAKE_IOS_DEVELOPER_ROOT path.\n#   If set manually, this will force the use of a specific SDK version\n\n# Macros:\n#\n# set_xcode_property (TARGET XCODE_PROPERTY XCODE_VALUE)\n#  A convenience macro for setting xcode specific properties on targets\n#  example: set_xcode_property (myioslib IPHONEOS_DEPLOYMENT_TARGET \"3.1\")\n#\n# find_host_package (PROGRAM ARGS)\n#  A macro used to find executable programs on the host system, not within the iOS environment.\n#  Thanks to the android-cmake project for providing the command\n\n# Standard settings\nset (CMAKE_SYSTEM_NAME Darwin)\nset (CMAKE_SYSTEM_VERSION 1)\nset (UNIX True)\nset (APPLE True)\nset (IOS True)\n\n# Required as of cmake 2.8.10\nset (CMAKE_OSX_DEPLOYMENT_TARGET \"\" CACHE STRING \"Force unset of the deployment target for iOS\" FORCE)\n\n# Determine the cmake host system version so we know where to find the iOS SDKs\nfind_program (CMAKE_UNAME uname /bin /usr/bin /usr/local/bin)\nif (CMAKE_UNAME)\n\texec_program(uname ARGS -r OUTPUT_VARIABLE CMAKE_HOST_SYSTEM_VERSION)\n\tstring (REGEX REPLACE \"^([0-9]+)\\\\.([0-9]+).*$\" \"\\\\1\" DARWIN_MAJOR_VERSION \"${CMAKE_HOST_SYSTEM_VERSION}\")\nendif (CMAKE_UNAME)\n\n# Force the compilers to gcc for iOS\n#include (CMakeForceCompiler)\n#CMAKE_FORCE_C_COMPILER (/usr/bin/clang Apple)\n#CMAKE_FORCE_CXX_COMPILER (/usr/bin/clang++ Apple)\n#set(CMAKE_AR ar CACHE FILEPATH \"\" FORCE)\n\n# Skip the platform compiler checks for cross compiling\nset (CMAKE_CXX_COMPILER_WORKS TRUE)\nset (CMAKE_C_COMPILER_WORKS TRUE)\n\n# All iOS/Darwin specific settings - some may be redundant\nset (CMAKE_SHARED_LIBRARY_PREFIX \"lib\")\nset (CMAKE_SHARED_LIBRARY_SUFFIX \".dylib\")\nset (CMAKE_SHARED_MODULE_PREFIX \"lib\")\nset (CMAKE_SHARED_MODULE_SUFFIX \".so\")\nset (CMAKE_MODULE_EXISTS 1)\nset (CMAKE_DL_LIBS \"\")\n\nset (CMAKE_C_OSX_COMPATIBILITY_VERSION_FLAG \"-compatibility_version \")\nset (CMAKE_C_OSX_CURRENT_VERSION_FLAG \"-current_version \")\nset (CMAKE_CXX_OSX_COMPATIBILITY_VERSION_FLAG \"${CMAKE_C_OSX_COMPATIBILITY_VERSION_FLAG}\")\nset (CMAKE_CXX_OSX_CURRENT_VERSION_FLAG \"${CMAKE_C_OSX_CURRENT_VERSION_FLAG}\")\n\n# Hidden visibilty is required for cxx on iOS \nset (CMAKE_C_FLAGS_INIT \"\")\nset (CMAKE_CXX_FLAGS_INIT \"-fvisibility=hidden -fvisibility-inlines-hidden -isysroot ${CMAKE_OSX_SYSROOT}\")\n\nset (CMAKE_C_LINK_FLAGS \"-Wl,-search_paths_first ${CMAKE_C_LINK_FLAGS}\")\nset (CMAKE_CXX_LINK_FLAGS \"-Wl,-search_paths_first ${CMAKE_CXX_LINK_FLAGS}\")\n\nset (CMAKE_PLATFORM_HAS_INSTALLNAME 1)\nset (CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS \"-dynamiclib -headerpad_max_install_names\")\nset (CMAKE_SHARED_MODULE_CREATE_C_FLAGS \"-bundle -headerpad_max_install_names\")\nset (CMAKE_SHARED_MODULE_LOADER_C_FLAG \"-Wl,-bundle_loader,\")\nset (CMAKE_SHARED_MODULE_LOADER_CXX_FLAG \"-Wl,-bundle_loader,\")\nset (CMAKE_FIND_LIBRARY_SUFFIXES \".dylib\" \".so\" \".a\")\n\n# hack: if a new cmake (which uses CMAKE_INSTALL_NAME_TOOL) runs on an old build tree\n# (where install_name_tool was hardcoded) and where CMAKE_INSTALL_NAME_TOOL isn't in the cache\n# and still cmake didn't fail in CMakeFindBinUtils.cmake (because it isn't rerun)\n# hardcode CMAKE_INSTALL_NAME_TOOL here to install_name_tool, so it behaves as it did before, Alex\nif (NOT DEFINED CMAKE_INSTALL_NAME_TOOL)\n\tfind_program(CMAKE_INSTALL_NAME_TOOL install_name_tool)\nendif (NOT DEFINED CMAKE_INSTALL_NAME_TOOL)\n\n# Setup iOS platform unless specified manually with IOS_PLATFORM\nif (NOT DEFINED IOS_PLATFORM)\n\tset (IOS_PLATFORM \"OS\")\nendif (NOT DEFINED IOS_PLATFORM)\nset (IOS_PLATFORM ${IOS_PLATFORM} CACHE STRING \"Type of iOS Platform\")\n\n# Check the platform selection and setup for developer root\nif (${IOS_PLATFORM} STREQUAL \"OS\")\n\tset (IOS_PLATFORM_LOCATION \"iPhoneOS.platform\")\n\n\t# This causes the installers to properly locate the output libraries\n\tset (CMAKE_XCODE_EFFECTIVE_PLATFORMS \"-iphoneos\")\nelseif (${IOS_PLATFORM} STREQUAL \"SIMULATOR\")\n\tset (IOS_PLATFORM_LOCATION \"iPhoneSimulator.platform\")\n\n\t# This causes the installers to properly locate the output libraries\n\tset (CMAKE_XCODE_EFFECTIVE_PLATFORMS \"-iphonesimulator\")\nelse (${IOS_PLATFORM} STREQUAL \"OS\")\n\tmessage (FATAL_ERROR \"Unsupported IOS_PLATFORM value selected. Please choose OS or SIMULATOR\")\nendif (${IOS_PLATFORM} STREQUAL \"OS\")\n\n# Setup iOS developer location unless specified manually with CMAKE_IOS_DEVELOPER_ROOT\n# Note Xcode 4.3 changed the installation location, choose the most recent one available\nset (XCODE_POST_43_ROOT \"/Applications/Xcode.app/Contents/Developer/Platforms/${IOS_PLATFORM_LOCATION}/Developer\")\nset (XCODE_PRE_43_ROOT \"/Developer/Platforms/${IOS_PLATFORM_LOCATION}/Developer\")\nif (NOT DEFINED CMAKE_IOS_DEVELOPER_ROOT)\n\tif (EXISTS ${XCODE_POST_43_ROOT})\n\t\tset (CMAKE_IOS_DEVELOPER_ROOT ${XCODE_POST_43_ROOT})\n\telseif(EXISTS ${XCODE_PRE_43_ROOT})\n\t\tset (CMAKE_IOS_DEVELOPER_ROOT ${XCODE_PRE_43_ROOT})\n\tendif (EXISTS ${XCODE_POST_43_ROOT})\nendif (NOT DEFINED CMAKE_IOS_DEVELOPER_ROOT)\nset (CMAKE_IOS_DEVELOPER_ROOT ${CMAKE_IOS_DEVELOPER_ROOT} CACHE PATH \"Location of iOS Platform\")\n\n# Find and use the most recent iOS sdk unless specified manually with CMAKE_IOS_SDK_ROOT\nif (NOT DEFINED CMAKE_IOS_SDK_ROOT)\n\tfile (GLOB _CMAKE_IOS_SDKS \"${CMAKE_IOS_DEVELOPER_ROOT}/SDKs/*\")\n\tif (_CMAKE_IOS_SDKS) \n\t\tlist (SORT _CMAKE_IOS_SDKS)\n\t\tlist (REVERSE _CMAKE_IOS_SDKS)\n\t\tlist (GET _CMAKE_IOS_SDKS 0 CMAKE_IOS_SDK_ROOT)\n\telse (_CMAKE_IOS_SDKS)\n\t\tmessage (FATAL_ERROR \"No iOS SDK's found in default search path ${CMAKE_IOS_DEVELOPER_ROOT}. Manually set CMAKE_IOS_SDK_ROOT or install the iOS SDK.\")\n\tendif (_CMAKE_IOS_SDKS)\n\tmessage (STATUS \"Toolchain using default iOS SDK: ${CMAKE_IOS_SDK_ROOT}\")\nendif (NOT DEFINED CMAKE_IOS_SDK_ROOT)\nset (CMAKE_IOS_SDK_ROOT ${CMAKE_IOS_SDK_ROOT} CACHE PATH \"Location of the selected iOS SDK\")\n\n# Set the sysroot default to the most recent SDK\nset (CMAKE_OSX_SYSROOT ${CMAKE_IOS_SDK_ROOT} CACHE PATH \"Sysroot used for iOS support\")\n\n# set the architecture for iOS \n# NOTE: Currently both ARCHS_STANDARD_32_BIT and ARCHS_UNIVERSAL_IPHONE_OS set armv7 only, so set both manually\nif (${IOS_PLATFORM} STREQUAL \"OS\")\n\tset (IOS_ARCH armv7)\nelse (${IOS_PLATFORM} STREQUAL \"OS\")\n\tset (IOS_ARCH i386)\nendif (${IOS_PLATFORM} STREQUAL \"OS\")\n\nset (CMAKE_OSX_ARCHITECTURES ${IOS_ARCH} CACHE string  \"Build architecture for iOS\")\n\n# Set the find root to the iOS developer roots and to user defined paths\nset (CMAKE_FIND_ROOT_PATH ${CMAKE_IOS_DEVELOPER_ROOT} ${CMAKE_IOS_SDK_ROOT} ${CMAKE_PREFIX_PATH} CACHE string  \"iOS find search path root\")\n\n# default to searching for frameworks first\nset (CMAKE_FIND_FRAMEWORK FIRST)\n\n# set up the default search directories for frameworks\nset (CMAKE_SYSTEM_FRAMEWORK_PATH\n\t${CMAKE_IOS_SDK_ROOT}/System/Library/Frameworks\n\t${CMAKE_IOS_SDK_ROOT}/System/Library/PrivateFrameworks\n\t${CMAKE_IOS_SDK_ROOT}/Developer/Library/Frameworks\n)\n\n# only search the iOS sdks, not the remainder of the host filesystem\n#set (CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY)\n#set (CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)\n#set (CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)\n\n\n# This little macro lets you set any XCode specific property\nmacro (set_xcode_property TARGET XCODE_PROPERTY XCODE_VALUE)\n\tset_property (TARGET ${TARGET} PROPERTY XCODE_ATTRIBUTE_${XCODE_PROPERTY} ${XCODE_VALUE})\nendmacro (set_xcode_property)\n\n\n# This macro lets you find executable programs on the host system\nmacro (find_host_package)\n\tset (CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)\n\tset (CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER)\n\tset (CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER)\n\tset (IOS FALSE)\n\n\tfind_package(${ARGN})\n\n\tset (IOS TRUE)\n\tset (CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY)\n\tset (CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)\n\tset (CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)\nendmacro (find_host_package)\n\nmacro(ADD_FRAMEWORK fwname frameworks)\n    find_library(FRAMEWORK_${fwname}\n        NAMES ${fwname}\n        )\n    if( ${FRAMEWORK_${fwname}} STREQUAL FRAMEWORK_${fwname}-NOTFOUND)\n        MESSAGE(ERROR \": Framework ${fwname} not found\")\n    else()\n        list(APPEND ${frameworks} ${FRAMEWORK_${fwname}})\n        MESSAGE(STATUS \"Framework ${fwname} found at ${FRAMEWORK_${fwname}}\")\n    endif()\nendmacro(ADD_FRAMEWORK)\n\n# http://stackoverflow.com/questions/14171740/cmake-with-ios-toolchain-cant-find-threads\n# http://public.kitware.com/Bug/view.php?id=12288\n# Fix for try_compile\nSET(CMAKE_MACOSX_BUNDLE YES)\nSET(CMAKE_XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY \"iPhone Developer\")\nSET(MACOSX_BUNDLE_GUI_IDENTIFIER \"org.racing\")\n# http://stackoverflow.com/questions/11198878/how-do-you-specify-a-universal-ios-application-when-building-through-cmake\nSET(CMAKE_XCODE_ATTRIBUTE_TARGETED_DEVICE_FAMILY \"1,2\")\n"
  },
  {
    "path": "jsb_build/cmake/ios.toolchain.cmake",
    "content": "# This file is part of the ios-cmake project. It was retrieved from\n# https://github.com/cristeab/ios-cmake.git, which is a fork of\n# https://code.google.com/p/ios-cmake/. Which in turn is based off of\n# the Platform/Darwin.cmake and Platform/UnixPaths.cmake files which\n# are included with CMake 2.8.4\n#\n# The ios-cmake project is licensed under the new BSD license.\n#\n# Copyright (c) 2014, Bogdan Cristea and LTE Engineering Software,\n# Kitware, Inc., Insight Software Consortium.  All rights reserved.\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# This file is based off of the Platform/Darwin.cmake and\n# Platform/UnixPaths.cmake files which are included with CMake 2.8.4\n# It has been altered for iOS development.\n#\n# Updated by Alex Stewart (alexs.mac@gmail.com)\n#\n# *****************************************************************************\n#      Now maintained by Alexander Widerberg (widerbergaren [at] gmail.com)\n#                      under the BSD-3-Clause license\n#                   https://github.com/leetal/ios-cmake\n# *****************************************************************************\n#\n#                           INFORMATION / HELP\n#\n# The following variables control the behaviour of this toolchain:\n#\n# IOS_PLATFORM: OS (default) or SIMULATOR or SIMULATOR64 or TVOS or SIMULATOR_TVOS or WATCHOS or SIMULATOR_WATCHOS\n#    OS = Build for iPhoneOS.\n#    OS64 = Build for arm64 arm64e iPhoneOS.\n#    SIMULATOR = Build for x86 i386 iPhone Simulator.\n#    SIMULATOR64 = Build for x86_64 iPhone Simulator.\n#    TVOS = Build for AppleTVOS.\n#    SIMULATOR_TVOS = Build for x86_64 AppleTV Simulator.\n#    WATCHOS = Build for armv7k arm64_32 for WatchOS.\n#    SIMULATOR_WATCHOS = Build for x86_64 for Watch Simulator.\n# CMAKE_OSX_SYSROOT: Path to the iOS SDK to use.  By default this is\n#    automatically determined from IOS_PLATFORM and xcodebuild, but\n#    can also be manually specified (although this should not be required).\n# CMAKE_IOS_DEVELOPER_ROOT: Path to the Developer directory for the iOS platform\n#    being compiled for.  By default this is automatically determined from\n#    CMAKE_OSX_SYSROOT, but can also be manually specified (although this should\n#    not be required).\n# ENABLE_BITCODE: (1|0) Enables or disables bitcode support. Default 1 (true)\n# ENABLE_ARC: (1|0) Enables or disables ARC support. Default 1 (true, ARC enabled by default)\n# ENABLE_VISIBILITY: (1|0) Enables or disables symbol visibility support. Default 0 (false, visibility hidden by default)\n# IOS_ARCH: (armv7 armv7s armv7k arm64 arm64e arm64_32 i386 x86_64) If specified, will override the default architectures for the given IOS_PLATFORM\n#    OS = armv7 armv7s arm64 arm64e (if applicable)\n#    OS64 = arm64 arm64e (if applicable)\n#    SIMULATOR = i386\n#    SIMULATOR64 = x86_64\n#    TVOS = arm64\n#    SIMULATOR_TVOS = x86_64 (i386 has since long been deprecated)\n#    WATCHOS = armv7k arm64_32 (if applicable)\n#    SIMULATOR_WATCHOS = x86_64 (i386 has since long been deprecated)\n#\n# This toolchain defines the following variables for use externally:\n#\n# XCODE_VERSION: Version number (not including Build version) of Xcode detected.\n# IOS_SDK_VERSION: Version of iOS SDK being used.\n# CMAKE_OSX_ARCHITECTURES: Architectures being compiled for (generated from\n#    IOS_PLATFORM).\n#\n# This toolchain defines the following macros for use externally:\n#\n# set_xcode_property (TARGET XCODE_PROPERTY XCODE_VALUE XCODE_VARIANT)\n#   A convenience macro for setting xcode specific properties on targets.\n#   Available variants are: All, Release, RelWithDebInfo, Debug, MinSizeRel\n#   example: set_xcode_property (myioslib IPHONEOS_DEPLOYMENT_TARGET \"3.1\" \"all\").\n#\n# find_host_package (PROGRAM ARGS)\n#   A macro used to find executable programs on the host system, not within the\n#   iOS environment.  Thanks to the android-cmake project for providing the\n#   command.\n\n# Fix for PThread library not in path\nset(CMAKE_THREAD_LIBS_INIT \"-lpthread\")\nset(CMAKE_HAVE_THREADS_LIBRARY 1)\nset(CMAKE_USE_WIN32_THREADS_INIT 0)\nset(CMAKE_USE_PTHREADS_INIT 1)\n\n# Cache what generator is used\nset(USED_CMAKE_GENERATOR \"${CMAKE_GENERATOR}\" CACHE STRING \"Expose CMAKE_GENERATOR\" FORCE)\n\n# Get the Xcode version being used.\nexecute_process(COMMAND xcodebuild -version\n  OUTPUT_VARIABLE XCODE_VERSION\n  ERROR_QUIET\n  OUTPUT_STRIP_TRAILING_WHITESPACE)\nstring(REGEX MATCH \"Xcode [0-9\\\\.]+\" XCODE_VERSION \"${XCODE_VERSION}\")\nstring(REGEX REPLACE \"Xcode ([0-9\\\\.]+)\" \"\\\\1\" XCODE_VERSION \"${XCODE_VERSION}\")\nmessage(STATUS \"Building with Xcode version: ${XCODE_VERSION}\")\n# Default to building for iPhoneOS if not specified otherwise, and we cannot\n# determine the platform from the CMAKE_OSX_ARCHITECTURES variable. The use\n# of CMAKE_OSX_ARCHITECTURES is such that try_compile() projects can correctly\n# determine the value of IOS_PLATFORM from the root project, as\n# CMAKE_OSX_ARCHITECTURES is propagated to them by CMake.\nif (NOT DEFINED IOS_PLATFORM)\n  if (CMAKE_OSX_ARCHITECTURES)\n    if (CMAKE_OSX_ARCHITECTURES MATCHES \".*arm.*\")\n      set(IOS_PLATFORM \"OS\")\n    elseif (CMAKE_OSX_ARCHITECTURES MATCHES \"i386\")\n      set(IOS_PLATFORM \"SIMULATOR\")\n    elseif (CMAKE_OSX_ARCHITECTURES MATCHES \"x86_64\")\n      set(IOS_PLATFORM \"SIMULATOR64\")\n    elseif (CMAKE_OSX_ARCHITECTURES MATCHES \"armv7k\")\n      set(IOS_PLATFORM \"WATCHOS\")\n    endif()\n  endif()\n  if (NOT IOS_PLATFORM)\n    set(IOS_PLATFORM \"OS\")\n  endif()\nendif()\nset(IOS_PLATFORM ${IOS_PLATFORM} CACHE STRING\n  \"Type of iOS platform for which to build.\")\n# Determine the platform name and architectures for use in xcodebuild commands\n# from the specified IOS_PLATFORM name.\nif (IOS_PLATFORM STREQUAL \"OS\")\n  set(XCODE_IOS_PLATFORM iphoneos)\n  if(NOT IOS_ARCH)\n    if (XCODE_VERSION VERSION_GREATER 10.0)\n      set(IOS_ARCH armv7 armv7s arm64 arm64e)\n    else()\n      set(IOS_ARCH armv7 armv7s arm64)\n    endif()\n  endif()\n elseif (IOS_PLATFORM STREQUAL \"OS64\")\n  set(XCODE_IOS_PLATFORM iphoneos)\n  if(NOT IOS_ARCH)\n    if (XCODE_VERSION VERSION_GREATER 10.0)\n      set(IOS_ARCH arm64 arm64e)\n    else()\n      set(IOS_ARCH arm64)\n    endif()\n  endif()\nelseif (IOS_PLATFORM STREQUAL \"SIMULATOR\")\n  set(XCODE_IOS_PLATFORM iphonesimulator)\n  if(NOT IOS_ARCH)\n    set(IOS_ARCH i386)\n  endif()\n  message(WARNING \"SIMULATOR IS DEPRECATED. Consider using SIMULATOR64 instead.\")\nelseif(IOS_PLATFORM STREQUAL \"SIMULATOR64\")\n  set(XCODE_IOS_PLATFORM iphonesimulator)\n  if(NOT IOS_ARCH)\n    set(IOS_ARCH x86_64)\n  endif()\nelseif (IOS_PLATFORM STREQUAL \"TVOS\")\n  set(XCODE_IOS_PLATFORM appletvos)\n  if(NOT IOS_ARCH)\n    set(IOS_ARCH arm64)\n  endif()\nelseif (IOS_PLATFORM STREQUAL \"SIMULATOR_TVOS\")\n  set(XCODE_IOS_PLATFORM appletvsimulator)\n  if(NOT IOS_ARCH)\n    set(IOS_ARCH x86_64)\n  endif()\nelseif (IOS_PLATFORM STREQUAL \"WATCHOS\")\n  set(XCODE_IOS_PLATFORM watchos)\n  if(NOT IOS_ARCH)\n    if (XCODE_VERSION VERSION_GREATER 10.0)\n      set(IOS_ARCH armv7k arm64_32)\n    else()\n      set(IOS_ARCH armv7k)\n    endif()\n  endif()\nelseif (IOS_PLATFORM STREQUAL \"SIMULATOR_WATCHOS\")\n  set(XCODE_IOS_PLATFORM watchsimulator)\n  if(NOT IOS_ARCH)\n    set(IOS_ARCH x86_64)\n  endif()\nelse()\n  message(FATAL_ERROR \"Invalid IOS_PLATFORM: ${IOS_PLATFORM}\")\nendif()\nmessage(STATUS \"Configuring iOS build for platform: ${IOS_PLATFORM}, \"\n  \"architecture(s): ${IOS_ARCH}\")\n# If user did not specify the SDK root to use, then query xcodebuild for it.\nexecute_process(COMMAND xcodebuild -version -sdk ${XCODE_IOS_PLATFORM} Path\n    OUTPUT_VARIABLE CMAKE_OSX_SYSROOT_INT\n     OUTPUT_QUIET ERROR_QUIET\n    OUTPUT_STRIP_TRAILING_WHITESPACE)\n# If user did not specify the SDK root to use, then query xcodebuild for it.\nif (NOT DEFINED CMAKE_OSX_SYSROOT OR (NOT CMAKE_OSX_SYSROOT STREQUAL CMAKE_OSX_SYSROOT_INT))\n  execute_process(COMMAND xcodebuild -version -sdk ${XCODE_IOS_PLATFORM} Path\n    OUTPUT_VARIABLE CMAKE_OSX_SYSROOT\n    ERROR_QUIET\n    OUTPUT_STRIP_TRAILING_WHITESPACE)\nendif()\nif (NOT EXISTS ${CMAKE_OSX_SYSROOT})\n  message(SEND_ERROR \"Please make sure that Xcode is installed and that the toolchain\"\n  \"is pointing to the correct path. Please run:\"\n  \"sudo xcode-select -s /Applications/Xcode.app/Contents/Developer\"\n  \"and see if that fixes the problem for you.\")\n  message(FATAL_ERROR \"Invalid CMAKE_OSX_SYSROOT: ${CMAKE_OSX_SYSROOT} \"\n  \"does not exist.\")\nelseif(DEFINED CMAKE_OSX_SYSROOT)\n  message(STATUS \"Using manually set SDK path: ${CMAKE_OSX_SYSROOT} for platform: ${IOS_PLATFORM}\")\nelse()\n   message(STATUS \"Using SDK: ${CMAKE_OSX_SYSROOT} for platform: ${IOS_PLATFORM}\")\nendif()\n# Specify minimum version of deployment target.\nif (NOT DEFINED IOS_DEPLOYMENT_TARGET)\n  if (IOS_PLATFORM STREQUAL \"WATCHOS\" OR IOS_PLATFORM STREQUAL \"SIMULATOR_WATCHOS\")\n    # Unless specified, SDK version 2.0 is used by default as minimum target version (watchOS).\n    set(IOS_DEPLOYMENT_TARGET \"2.0\"\n            CACHE STRING \"Minimum iOS version to build for.\" )\n  else()\n    # Unless specified, SDK version 9.0 is used by default as minimum target version (iOS, tvOS).\n    set(IOS_DEPLOYMENT_TARGET \"9.0\"\n            CACHE STRING \"Minimum iOS version to build for.\" )\n  endif()\n  message(STATUS \"Using the default min-version since IOS_DEPLOYMENT_TARGET not provided!\")\nendif()\n# Use bitcode or not\nif (NOT DEFINED ENABLE_BITCODE AND NOT IOS_ARCH MATCHES \"((^|, )(i386|x86_64))+\")\n  # Unless specified, enable bitcode support by default\n  set(ENABLE_BITCODE TRUE CACHE BOOL \"Whether or not to enable bitcode\")\n  message(STATUS \"Enabling bitcode support by default. ENABLE_BITCODE not provided!\")\nendif()\nif (NOT DEFINED ENABLE_BITCODE)\n  message(STATUS \"Disabling bitcode support by default on simulators. ENABLE_BITCODE not provided for override!\")\nendif()\n# Use ARC or not\nif (NOT DEFINED ENABLE_ARC)\n  # Unless specified, enable ARC support by default\n  set(ENABLE_ARC TRUE CACHE BOOL \"Whether or not to enable ARC\")\n  message(STATUS \"Enabling ARC support by default. ENABLE_ARC not provided!\")\nendif()\n# Use hidden visibility or not\nif (NOT DEFINED ENABLE_VISIBILITY)\n  # Unless specified, disable symbols visibility by default\n  set(ENABLE_VISIBILITY FALSE CACHE BOOL \"Whether or not to hide symbols (-fvisibility=hidden)\")\n  message(STATUS \"Hiding symbols visibility by default. ENABLE_VISIBILITY not provided!\")\nendif()\n# Get the SDK version information.\nexecute_process(COMMAND xcodebuild -sdk ${CMAKE_OSX_SYSROOT} -version SDKVersion\n  OUTPUT_VARIABLE IOS_SDK_VERSION\n  ERROR_QUIET\n  OUTPUT_STRIP_TRAILING_WHITESPACE)\n# Find the Developer root for the specific iOS platform being compiled for\n# from CMAKE_OSX_SYSROOT.  Should be ../../ from SDK specified in\n# CMAKE_OSX_SYSROOT.  There does not appear to be a direct way to obtain\n# this information from xcrun or xcodebuild.\nif (NOT CMAKE_IOS_DEVELOPER_ROOT)\n  get_filename_component(IOS_PLATFORM_SDK_DIR ${CMAKE_OSX_SYSROOT} PATH)\n  get_filename_component(CMAKE_IOS_DEVELOPER_ROOT ${IOS_PLATFORM_SDK_DIR} PATH)\nendif()\nif (NOT EXISTS ${CMAKE_IOS_DEVELOPER_ROOT})\n  message(FATAL_ERROR \"Invalid CMAKE_IOS_DEVELOPER_ROOT: \"\n    \"${CMAKE_IOS_DEVELOPER_ROOT} does not exist.\")\nendif()\n# Find the C & C++ compilers for the specified SDK.\nif (NOT CMAKE_C_COMPILER)\n  execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT} -find clang\n    OUTPUT_VARIABLE CMAKE_C_COMPILER\n    ERROR_QUIET\n    OUTPUT_STRIP_TRAILING_WHITESPACE)\n  message(STATUS \"Using C compiler: ${CMAKE_C_COMPILER}\")\nendif()\nif (NOT CMAKE_CXX_COMPILER)\n  execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT} -find clang++\n    OUTPUT_VARIABLE CMAKE_CXX_COMPILER\n    ERROR_QUIET\n    OUTPUT_STRIP_TRAILING_WHITESPACE)\n  message(STATUS \"Using CXX compiler: ${CMAKE_CXX_COMPILER}\")\nendif()\n# Find (Apple's) libtool.\nexecute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT} -find libtool\n  OUTPUT_VARIABLE IOS_LIBTOOL\n  ERROR_QUIET\n  OUTPUT_STRIP_TRAILING_WHITESPACE)\nmessage(STATUS \"Using libtool: ${IOS_LIBTOOL}\")\n# Configure libtool to be used instead of ar + ranlib to build static libraries.\n# This is required on Xcode 7+, but should also work on previous versions of\n# Xcode.\nset(CMAKE_C_CREATE_STATIC_LIBRARY\n  \"${IOS_LIBTOOL} -static -o <TARGET> <LINK_FLAGS> <OBJECTS> \")\nset(CMAKE_CXX_CREATE_STATIC_LIBRARY\n  \"${IOS_LIBTOOL} -static -o <TARGET> <LINK_FLAGS> <OBJECTS> \")\n# Get the version of Darwin (OS X) of the host.\nexecute_process(COMMAND uname -r\n  OUTPUT_VARIABLE CMAKE_HOST_SYSTEM_VERSION\n  ERROR_QUIET\n  OUTPUT_STRIP_TRAILING_WHITESPACE)\n# Standard settings.\nset(CMAKE_SYSTEM_NAME Darwin CACHE INTERNAL \"\")\nset(CMAKE_SYSTEM_VERSION ${IOS_SDK_VERSION} CACHE INTERNAL \"\")\nset(UNIX TRUE CACHE BOOL \"\")\nset(APPLE TRUE CACHE BOOL \"\")\nset(IOS TRUE CACHE BOOL \"\")\nset(CMAKE_AR ar CACHE FILEPATH \"\" FORCE)\nset(CMAKE_RANLIB ranlib CACHE FILEPATH \"\" FORCE)\n# Force unset of OS X-specific deployment target (otherwise autopopulated),\n# required as of cmake 2.8.10.\nset(CMAKE_OSX_DEPLOYMENT_TARGET \"\" CACHE STRING\n  \"Must be empty for iOS builds.\" FORCE)\n# Set the architectures for which to build.\nset(CMAKE_OSX_ARCHITECTURES ${IOS_ARCH} CACHE STRING \"Build architecture for iOS\")\n# Change the type of target generated for try_compile() so it'll work when cross-compiling\nset(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)\n# All iOS/Darwin specific settings - some may be redundant.\nset(CMAKE_SHARED_LIBRARY_PREFIX \"lib\")\nset(CMAKE_SHARED_LIBRARY_SUFFIX \".dylib\")\nset(CMAKE_SHARED_MODULE_PREFIX \"lib\")\nset(CMAKE_SHARED_MODULE_SUFFIX \".so\")\nset(CMAKE_C_COMPILER_ABI ELF)\nset(CMAKE_CXX_COMPILER_ABI ELF)\nset(CMAKE_C_HAS_ISYSROOT 1)\nset(CMAKE_CXX_HAS_ISYSROOT 1)\nset(CMAKE_MODULE_EXISTS 1)\nset(CMAKE_DL_LIBS \"\")\nset(CMAKE_C_OSX_COMPATIBILITY_VERSION_FLAG \"-compatibility_version \")\nset(CMAKE_C_OSX_CURRENT_VERSION_FLAG \"-current_version \")\nset(CMAKE_CXX_OSX_COMPATIBILITY_VERSION_FLAG \"${CMAKE_C_OSX_COMPATIBILITY_VERSION_FLAG}\")\nset(CMAKE_CXX_OSX_CURRENT_VERSION_FLAG \"${CMAKE_C_OSX_CURRENT_VERSION_FLAG}\")\n\nif(IOS_ARCH MATCHES \"((^|, )(arm64|arm64e|x86_64))+\")\n  set(CMAKE_C_SIZEOF_DATA_PTR 8)\n  set(CMAKE_CXX_SIZEOF_DATA_PTR 8)\n  message(STATUS \"Using a data_ptr size of 8\")\nelse()\n  set(CMAKE_C_SIZEOF_DATA_PTR 4)\n  set(CMAKE_CXX_SIZEOF_DATA_PTR 4)\n  message(STATUS \"Using a data_ptr size of 4\")\nendif()\n\nmessage(STATUS \"Building for minimum iOS version: ${IOS_DEPLOYMENT_TARGET}\"\n               \" (SDK version: ${IOS_SDK_VERSION})\")\n# Note that only Xcode 7+ supports the newer more specific:\n# -m${XCODE_IOS_PLATFORM}-version-min flags, older versions of Xcode use:\n# -m(ios/ios-simulator)-version-min instead.\nif (IOS_PLATFORM STREQUAL \"OS\" OR IOS_PLATFORM STREQUAL \"OS64\")\n  if (XCODE_VERSION VERSION_LESS 7.0)\n    set(XCODE_IOS_PLATFORM_VERSION_FLAGS\n      \"-mios-version-min=${IOS_DEPLOYMENT_TARGET}\")\n  else()\n    # Xcode 7.0+ uses flags we can build directly from XCODE_IOS_PLATFORM.\n    set(XCODE_IOS_PLATFORM_VERSION_FLAGS\n      \"-m${XCODE_IOS_PLATFORM}-version-min=${IOS_DEPLOYMENT_TARGET}\")\n  endif()\nelseif (IOS_PLATFORM STREQUAL \"TVOS\")\n  set(XCODE_IOS_PLATFORM_VERSION_FLAGS\n    \"-mtvos-version-min=${IOS_DEPLOYMENT_TARGET}\")\nelseif (IOS_PLATFORM STREQUAL \"SIMULATOR_TVOS\")\n  set(XCODE_IOS_PLATFORM_VERSION_FLAGS\n    \"-mtvos-simulator-version-min=${IOS_DEPLOYMENT_TARGET}\")\nelseif (IOS_PLATFORM STREQUAL \"WATCHOS\")\n  set(XCODE_IOS_PLATFORM_VERSION_FLAGS\n    \"-mwatchos-version-min=${IOS_DEPLOYMENT_TARGET}\")\nelseif (IOS_PLATFORM STREQUAL \"SIMULATOR_WATCHOS\")\n  set(XCODE_IOS_PLATFORM_VERSION_FLAGS\n    \"-mwatchos-simulator-version-min=${IOS_DEPLOYMENT_TARGET}\")\nelse()\n  # SIMULATOR or SIMULATOR64 both use -mios-simulator-version-min.\n  set(XCODE_IOS_PLATFORM_VERSION_FLAGS\n    \"-mios-simulator-version-min=${IOS_DEPLOYMENT_TARGET}\")\nendif()\nmessage(STATUS \"Version flags set to: ${XCODE_IOS_PLATFORM_VERSION_FLAGS}\")\n\nif (ENABLE_BITCODE)\n  set(BITCODE \"-fembed-bitcode\")\n  set(HEADER_PAD \"\")\n  message(STATUS \"Enabling bitcode support.\")\nelse()\n  set(BITCODE \"\")\n  set(HEADER_PAD \"-headerpad_max_install_names\")\n  message(STATUS \"Disabling bitcode support.\")\nendif()\n\nif (ENABLE_ARC)\n  set(FOBJC_ARC \"-fobjc-arc\")\n  message(STATUS \"Enabling ARC support.\")\nelse()\n  set(FOBJC_ARC \"-fno-objc-arc\")\n  message(STATUS \"Disabling ARC support.\")\nendif()\n\nif (NOT ENABLE_VISIBILITY)\n  set(VISIBILITY \"-fvisibility=hidden\")\n  message(STATUS \"Hiding symbols (-fvisibility=hidden).\")\nelse()\n  set(VISIBILITY \"\")\nendif()\n\nset(CMAKE_C_FLAGS\n\"${XCODE_IOS_PLATFORM_VERSION_FLAGS} ${BITCODE} -fobjc-abi-version=2 ${FOBJC_ARC} ${CMAKE_C_FLAGS}\")\n# Hidden visibilty is required for C++ on iOS.\nset(CMAKE_CXX_FLAGS\n\"${XCODE_IOS_PLATFORM_VERSION_FLAGS} ${BITCODE} ${VISIBILITY} -fvisibility-inlines-hidden -fobjc-abi-version=2 ${FOBJC_ARC} ${CMAKE_CXX_FLAGS}\")\nset(CMAKE_CXX_FLAGS_DEBUG \"${CMAKE_CXX_FLAGS} -O0 -g ${BITCODE} ${CMAKE_CXX_FLAGS_DEBUG}\")\nset(CMAKE_CXX_FLAGS_MINSIZEREL \"${CMAKE_CXX_FLAGS} -DNDEBUG -Os -ffast-math ${BITCODE} ${CMAKE_CXX_FLAGS_MINSIZEREL}\")\nset(CMAKE_CXX_FLAGS_RELWITHDEBINFO \"${CMAKE_CXX_FLAGS} -DNDEBUG -O2 -g -ffast-math ${BITCODE} ${CMAKE_CXX_FLAGS_RELWITHDEBINFO}\")\nset(CMAKE_CXX_FLAGS_RELEASE \"${CMAKE_CXX_FLAGS} -DNDEBUG -O3 -ffast-math ${BITCODE} ${CMAKE_CXX_FLAGS_RELEASE}\")\nset(CMAKE_C_LINK_FLAGS \"${XCODE_IOS_PLATFORM_VERSION_FLAGS} -Wl,-search_paths_first ${CMAKE_C_LINK_FLAGS}\")\nset(CMAKE_CXX_LINK_FLAGS \"${XCODE_IOS_PLATFORM_VERSION_FLAGS}  -Wl,-search_paths_first ${CMAKE_CXX_LINK_FLAGS}\")\n\n# In order to ensure that the updated compiler flags are used in try_compile()\n# tests, we have to forcibly set them in the CMake cache, not merely set them\n# in the local scope.\nlist(APPEND VARS_TO_FORCE_IN_CACHE\n  CMAKE_C_FLAGS\n  CMAKE_CXX_FLAGS\n  CMAKE_CXX_FLAGS_DEBUG\n  CMAKE_CXX_FLAGS_RELWITHDEBINFO\n  CMAKE_CXX_FLAGS_MINSIZEREL\n  CMAKE_CXX_FLAGS_RELEASE\n  CMAKE_C_LINK_FLAGS\n  CMAKE_CXX_LINK_FLAGS)\nforeach(VAR_TO_FORCE ${VARS_TO_FORCE_IN_CACHE})\n  set(${VAR_TO_FORCE} \"${${VAR_TO_FORCE}}\" CACHE STRING \"\")\nendforeach()\n\nset(CMAKE_PLATFORM_HAS_INSTALLNAME 1)\nset (CMAKE_SHARED_LINKER_FLAGS \"-rpath @executable_path/Frameworks -rpath @loader_path/Frameworks\")\nset(CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS \"-dynamiclib ${HEADER_PAD}\")\nset(CMAKE_SHARED_MODULE_CREATE_C_FLAGS \"-bundle ${HEADER_PAD}\")\nset(CMAKE_SHARED_MODULE_LOADER_C_FLAG \"-Wl,-bundle_loader,\")\nset(CMAKE_SHARED_MODULE_LOADER_CXX_FLAG \"-Wl,-bundle_loader,\")\nset(CMAKE_FIND_LIBRARY_SUFFIXES \".dylib\" \".so\" \".a\")\n\n# Hack: if a new cmake (which uses CMAKE_INSTALL_NAME_TOOL) runs on an old\n# build tree (where install_name_tool was hardcoded) and where\n# CMAKE_INSTALL_NAME_TOOL isn't in the cache and still cmake didn't fail in\n# CMakeFindBinUtils.cmake (because it isn't rerun) hardcode\n# CMAKE_INSTALL_NAME_TOOL here to install_name_tool, so it behaves as it did\n# before, Alex.\nif (NOT DEFINED CMAKE_INSTALL_NAME_TOOL)\n  find_program(CMAKE_INSTALL_NAME_TOOL install_name_tool)\nendif (NOT DEFINED CMAKE_INSTALL_NAME_TOOL)\n\n# Set the find root to the iOS developer roots and to user defined paths.\nset(CMAKE_FIND_ROOT_PATH ${CMAKE_IOS_DEVELOPER_ROOT} ${CMAKE_OSX_SYSROOT}\n  ${CMAKE_PREFIX_PATH} CACHE string  \"iOS find search path root\" FORCE)\n# Default to searching for frameworks first.\nset(CMAKE_FIND_FRAMEWORK FIRST)\n# Set up the default search directories for frameworks.\nset(CMAKE_SYSTEM_FRAMEWORK_PATH\n  ${CMAKE_OSX_SYSROOT}/System/Library/Frameworks\n  ${CMAKE_OSX_SYSROOT}/System/Library/PrivateFrameworks\n  ${CMAKE_OSX_SYSROOT}/Developer/Library/Frameworks)\n# Only search the specified iOS SDK, not the remainder of the host filesystem.\nset(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY)\nset(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)\nset(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)\n# This little macro lets you set any XCode specific property.\nmacro(set_xcode_property TARGET XCODE_PROPERTY XCODE_VALUE XCODE_RELVERSION)\n  set(XCODE_RELVERSION_I \"${XCODE_RELVERSION}\")\n  if (XCODE_RELVERSION_I STREQUAL \"All\")\n    set_property(TARGET ${TARGET} PROPERTY\n    XCODE_ATTRIBUTE_${XCODE_PROPERTY} \"${XCODE_VALUE}\")\n  else()\n    set_property(TARGET ${TARGET} PROPERTY\n    XCODE_ATTRIBUTE_${XCODE_PROPERTY}[variant=${XCODE_RELVERSION_I}] \"${XCODE_VALUE}\")\n  endif()\nendmacro(set_xcode_property)\n# This macro lets you find executable programs on the host system.\nmacro(find_host_package)\n  set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)\n  set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER)\n  set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER)\n  set(IOS FALSE)\n  find_package(${ARGN})\n  set(IOS TRUE)\n  set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY)\n  set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)\n  set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)\nendmacro(find_host_package)\n"
  },
  {
    "path": "jsb_build/codegen/StaticBindingSourceGenerator.cs",
    "content": "﻿using System;\r\nusing Microsoft.CodeAnalysis;\r\n\r\nnamespace QuickJS.Experimental\r\n{\r\n    /// <summary>\r\n    /// Generates glue code for static binding with Roslyn source generator\r\n    /// </summary>\r\n    [Generator]\r\n    class StaticBindingSourceGenerator : ISourceGenerator\r\n    {\r\n        public void Initialize(GeneratorInitializationContext context)\r\n        {\r\n        }\r\n\r\n        public void Execute(GeneratorExecutionContext context)\r\n        {\r\n            context.AddSource(\"jsb.autogen.cs\", $@\"\r\n                using System;\r\n                namespace AutoGenerated {{\r\n                    public class Example {{\r\n                        public static string Test1() => \"\"Hello, AutoGenerated.\"\";\r\n                    }}\r\n                }}\r\n            \");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "jsb_build/codegen/codegen.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\r\n\r\n  <PropertyGroup>\r\n    <TargetFramework>netstandard2.0</TargetFramework>\r\n  </PropertyGroup>\r\n\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|AnyCPU'\">\r\n    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\r\n  </PropertyGroup>\r\n\r\n  <ItemGroup>\r\n    <PackageReference Include=\"Microsoft.CodeAnalysis\" Version=\"3.8.0\" />\r\n  </ItemGroup>\r\n\r\n</Project>\r\n"
  },
  {
    "path": "jsb_build/dotnetcore/.vscode/launch.json",
    "content": "{\n    // Use IntelliSense to learn about possible attributes.\n    // Hover to view descriptions of existing attributes.\n    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387\n    \"version\": \"0.2.0\",\n    \"configurations\": [\n        {\n            \"name\": \".NET Core Launch (console)\",\n            \"type\": \"coreclr\",\n            \"request\": \"launch\",\n            \"preLaunchTask\": \"build\",\n            \"program\": \"${workspaceFolder}/bin/Debug/example.dll\",\n            \"args\": [],\n            \"cwd\": \"${workspaceFolder}\",\n            \"console\": \"internalConsole\",\n            \"stopAtEntry\": false\n        },\n        {\n            \"name\": \".NET Core Attach\",\n            \"type\": \"coreclr\",\n            \"request\": \"attach\",\n            \"processId\": \"${command:pickProcess}\"\n        }\n    ]\n}"
  },
  {
    "path": "jsb_build/dotnetcore/.vscode/tasks.json",
    "content": "{\n    // See https://go.microsoft.com/fwlink/?LinkId=733558\n    // for the documentation about the tasks.json format\n    \"version\": \"2.0.0\",\n    \"tasks\": [\n        {\n            \"label\": \"build\",\n            \"command\": \"dotnet\",\n            \"type\": \"shell\",\n            \"args\": [\n                \"build\",\n                // Ask dotnet build to generate full paths for file names.\n                \"/property:GenerateFullPaths=true\",\n                // Do not generate summary otherwise it leads to duplicate errors in Problems panel\n                \"/consoleloggerparameters:NoSummary\"\n            ],\n            \"group\": \"build\",\n            \"presentation\": {\n                \"reveal\": \"silent\"\n            },\n            \"problemMatcher\": \"$msCompile\"\n        }\n    ]\n}"
  },
  {
    "path": "jsb_build/dotnetcore/CustomBinding.cs",
    "content": "using System.Reflection;\n\nnamespace Example.Editor\n{\n    using QuickJS.Binding;\n\n    public class CustomBinding : AbstractBindingProcess\n    {\n        public override void OnPreExporting(BindingManager bindingManager)\n        {\n            bindingManager.AddExportedType(typeof(System.Math));\n        }\n        \n        public override void OnPostExporting(BindingManager bindingManager)\n        {\n            bindingManager.ExportTypesInAssembly(typeof(System.Threading.Thread).Assembly, true);\n            bindingManager.ExportTypesInAssembly(typeof(System.Console).Assembly, true);\n        }\n    }\n}"
  },
  {
    "path": "jsb_build/dotnetcore/Program.cs",
    "content": "﻿using System;\nusing System.Threading;\nusing QuickJS;\nusing QuickJS.IO;\nusing QuickJS.Utils;\nusing QuickJS.Binding;\n\nnamespace DotnetCoreConsoleApp\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            // var t = typeof(Program).Assembly.GetType(\"AutoGenerated.Example\");\n            // var m = t.GetMethod(\"Test1\");\n            // var r = m.Invoke(null, null);\n            // Console.WriteLine(\"Output: {0}\", r);\n\n            var pathResolver = new PathResolver();\n            var fileSystem = new DefaultFileSystem();\n            var asyncManager = new DefaultAsyncManager();\n            var runtime = ScriptEngine.CreateRuntime();\n\n            runtime.AddModuleResolvers();\n            runtime.Initialize(new ScriptRuntimeArgs\n            {\n                fileSystem = fileSystem,\n                pathResolver = pathResolver,\n                asyncManager = asyncManager,\n                byteBufferAllocator = new ByteBufferPooledAllocator(),\n                binder = BindingManager.UnitylessReflectBind,\n            });\n            runtime.AddSearchPath(\"./\");\n            runtime.AddSearchPath(\"./node_modules\");\n            runtime.EvalMain(\"main\");\n            while (runtime.isRunning)\n            {\n                runtime.Update(1);\n                Thread.Sleep(1);\n            }\n            runtime.Shutdown();\n        }\n    }\n}\n"
  },
  {
    "path": "jsb_build/dotnetcore/Properties/launchSettings.json",
    "content": "{\r\n  \"profiles\": {\r\n    \"example\": {\r\n      \"commandName\": \"Project\",\r\n      \"workingDirectory\": \"$(ProjectDir)\"\r\n    }\r\n  }\r\n}"
  },
  {
    "path": "jsb_build/dotnetcore/example.csproj",
    "content": "<Project Sdk=\"Microsoft.NET.Sdk\">\r\n  <PropertyGroup>\r\n    <OutputType>Exe</OutputType>\r\n    <TargetFramework>netcoreapp3.1</TargetFramework>\r\n    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\r\n    <DefineConstants>TRACE;JSB_UNITYLESS</DefineConstants>\r\n    <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>\r\n    <AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>\r\n  </PropertyGroup>\r\n\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|AnyCPU'\">\r\n  </PropertyGroup>\r\n\r\n  <ItemGroup>\r\n    <Compile Include=\"../../Packages/cc.starlessnight.unity-jsb/Source/**/*.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"../codegen/codegen.csproj\" OutputItemType=\"Analyzer\" ReferenceOutputAssembly=\"false\" />\r\n  </ItemGroup>\r\n\r\n  <Target Name=\"CopyQuickJS\" AfterTargets=\"AfterBuild\">\r\n    <Copy SourceFiles=\"../../Packages/cc.starlessnight.unity-jsb/Plugins/x64/quickjs.dll\" DestinationFolder=\"$(OutDir)\" SkipUnchangedFiles=\"true\" OverwriteReadOnlyFiles=\"true\" />\r\n    <Copy SourceFiles=\"../../Packages/cc.starlessnight.unity-jsb/Plugins/x64/libquickjs.so\" DestinationFolder=\"$(OutDir)\" SkipUnchangedFiles=\"true\" OverwriteReadOnlyFiles=\"true\" />\r\n    <Copy SourceFiles=\"../../Packages/cc.starlessnight.unity-jsb/Plugins/quickjs.bundle/Contents/MacOS/quickjs\" DestinationFolder=\"$(OutDir)\" SkipUnchangedFiles=\"true\" OverwriteReadOnlyFiles=\"true\" />\r\n  </Target>\r\n</Project>\r\n"
  },
  {
    "path": "jsb_build/dotnetcore/main.js",
    "content": "let System = require(\"System\");\n\nconsole.log(\"hello\", System.Math.Abs(-123));\nSystem.Console.WriteLine(\"test\");\n\nlet start = Date.now();\nlet a = 0; for (let i = 0; i < 10000000; i++) { a++; a *= 2; a /= 3; }\nlet end = Date.now();\n\nconsole.log((end - start) / 1000);\n\n"
  },
  {
    "path": "jsb_build/hotfix/Program.cs",
    "content": "﻿using System;\r\n\r\nnamespace QuickJS.Hotfix\r\n{\r\n    public class Program\r\n    {\r\n        public static void Main(string[] args)\r\n        {\r\n            HotfixUtil.Run();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "jsb_build/hotfix/hotfix.csproj",
    "content": "<Project Sdk=\"Microsoft.NET.Sdk\">\r\n\r\n  <PropertyGroup>\r\n    <RootNamespace>QuickJS.Hotfix</RootNamespace>\r\n    <AssemblyName>QuickJS.Hotfix</AssemblyName>\r\n    <FileAlignment>512</FileAlignment>\r\n\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    \r\n    <OutputPath>..\\out\\hotfix\\</OutputPath>\r\n    <OutputType>Exe</OutputType>\r\n    <DefineConstants>TRACE;DEBUG;UNITY_2019_1_9;UNITY_2019_1;UNITY_2019;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_6_OR_NEWER;UNITY_2017_1_OR_NEWER;UNITY_2017_2_OR_NEWER;UNITY_2017_3_OR_NEWER;UNITY_2017_4_OR_NEWER;UNITY_2018_1_OR_NEWER;UNITY_2018_2_OR_NEWER;UNITY_2018_3_OR_NEWER;UNITY_2019_1_OR_NEWER;PLATFORM_ARCH_64;UNITY_64;UNITY_INCLUDE_TESTS;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_SPRITES;ENABLE_GRID;ENABLE_TILEMAP;ENABLE_TERRAIN;ENABLE_TEXTURE_STREAMING;ENABLE_DIRECTOR;ENABLE_UNET;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_COLLAB_SOFTLOCKS;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_USE_WEBREQUEST;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_HUB;ENABLE_EDITOR_HUB_LICENSE;ENABLE_WEBSOCKET_CLIENT;ENABLE_DIRECTOR_AUDIO;ENABLE_DIRECTOR_TEXTURE;ENABLE_TIMELINE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;ENABLE_MANAGED_JOBS;ENABLE_MANAGED_TRANSFORM_JOBS;ENABLE_MANAGED_ANIMATION_JOBS;ENABLE_MANAGED_AUDIO_JOBS;INCLUDE_DYNAMIC_GI;INCLUDE_GI;ENABLE_MONO_BDWGC;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;INCLUDE_PUBNUB;ENABLE_VIDEO;ENABLE_CUSTOM_RENDER_TEXTURE;ENABLE_LOCALIZATION;PLATFORM_STANDALONE_WIN;PLATFORM_STANDALONE;UNITY_STANDALONE_WIN;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITYWEBREQUEST;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_OUT_OF_PROCESS_CRASH_HANDLER;ENABLE_SCRIPTING_GC_WBARRIERS;ENABLE_EVENT_QUEUE;ENABLE_CLUSTER_SYNC;ENABLE_CLUSTERINPUT;ENABLE_VR;ENABLE_AR;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;NET_STANDARD_2_0;ENABLE_PROFILER;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;ENABLE_UNITY_COLLECTIONS_CHECKS;ENABLE_BURST_AOT;UNITY_TEAM_LICENSE;UNITY_PRO_LICENSE;CSHARP_7_OR_LATER;CSHARP_7_3_OR_NEWER</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n    <AllowUnsafeBlocks>false</AllowUnsafeBlocks>\r\n\r\n    <TargetFramework>netcoreapp2.0</TargetFramework>\r\n  </PropertyGroup>\r\n\r\n  <ItemGroup>\r\n\r\n    <Reference Include=\"Assembly-CSharp, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL\">\r\n      <SpecificVersion>False</SpecificVersion>\r\n      <HintPath>..\\..\\Library\\ScriptAssemblies\\Assembly-CSharp.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL\">\r\n      <SpecificVersion>False</SpecificVersion>\r\n      <HintPath>..\\..\\Library\\ScriptAssemblies\\Assembly-CSharp-Editor.dll</HintPath>\r\n    </Reference>\r\n\r\n    <Reference Include=\"UnityEngine\">\r\n      <HintPath>UnityEngine.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"UnityEditor\">\r\n      <HintPath>UnityEditor.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"Unity.Cecil\">\r\n      <HintPath>Unity.Cecil.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"Unity.Cecil.Mdb\">\r\n      <HintPath>Unity.Cecil.Mdb.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"Unity.Cecil.Pdb\">\r\n      <HintPath>Unity.Cecil.Pdb.dll</HintPath>\r\n    </Reference>\r\n\r\n  </ItemGroup>\r\n</Project>\r\n"
  },
  {
    "path": "jsb_build/httpserver/.gitignore",
    "content": "**/node_modules\r\njs-out\r\nbuild\r\nupload\r\npublic\r\n.vscode\r\n"
  },
  {
    "path": "jsb_build/httpserver/package.json",
    "content": "{\r\n  \"name\": \"tsnode\",\r\n  \"version\": \"1.0.0\",\r\n  \"description\": \"\",\r\n  \"main\": \"js-out/index.js\",\r\n  \"scripts\": {\r\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\r\n  },\r\n  \"keywords\": [],\r\n  \"author\": \"\",\r\n  \"license\": \"ISC\",\r\n  \"dependencies\": {\r\n    \"@types/body-parser\": \"^1.16.8\",\r\n    \"@types/express\": \"^4.0.36\",\r\n    \"@types/multer\": \"^1.3.6\",\r\n    \"@types/node\": \"^7.0.13\",\r\n    \"@types/sqlite3\": \"^2.2.33\",\r\n    \"acorn\": \"^7.1.1\",\r\n    \"body-parser\": \"^1.20.2\",\r\n    \"express\": \"^4.17.3\",\r\n    \"morgan\": \"^1.9.1\",\r\n    \"multer\": \"^1.3.0\",\r\n    \"protobufjs\": \"^6.11.3\",\r\n    \"pug\": \"^2.0.0-rc.3\",\r\n    \"ts-node\": \"^3.0.2\",\r\n    \"typescript\": \"^2.2.2\"\r\n  }\r\n}\r\n"
  },
  {
    "path": "jsb_build/httpserver/render/test.pug",
    "content": "doctype html\r\nhtml\r\nbody\r\n    h1 My Site #{title}\r\n    p Welcome #{name}\r\n"
  },
  {
    "path": "jsb_build/httpserver/src/index.js",
    "content": "\r\nvar express = require(\"express\");\r\nvar path = require(\"path\");\r\nvar morgan = require(\"morgan\");\r\nvar parser = require(\"body-parser\");\r\nvar multer = require(\"multer\");\r\nvar pub_port = 8080;\r\nvar pub_path = \"public\";\r\n\r\nfor (var i = 2; i < process.argv.length;) {\r\n    var arg = process.argv[i];\r\n    if (arg == \"--port\") {\r\n        pub_port = parseInt(process.argv[i + 1]);\r\n        i += 2;\r\n        continue;\r\n    }\r\n    if (arg == \"--path\") {\r\n        pub_path = process.argv[i + 1];\r\n        i += 2;\r\n        continue;\r\n    }\r\n    i++;\r\n}\r\n\r\nvar app = express();\r\napp.set(\"view engine\", \"pug\"); // 设置模板引擎\r\napp.set(\"views\", path.join(__dirname, \"../render\")); // 设置模板相对路径(相对当前目录)\r\napp.use(morgan(\"dev\"));\r\napp.use(express.static(pub_path));\r\nconsole.log(\"static files root:\", pub_path);\r\napp.get(\"/\", function (req, res) {\r\n    // req.path\r\n    res.send(\"网站建设中...\");\r\n});\r\napp.get(\"/render\", function (req, res) {\r\n    //console.log(req.param(\"name\"))\r\n    res.render(\"test\", { title: \"xxxTitlexxx\", name: req.param(\"name\") });\r\n});\r\nvar storage = multer.diskStorage({\r\n    destination: function (req, file, callback) {\r\n        // console.log(file)\r\n        callback(null, \"./upload/\");\r\n    },\r\n    filename: function (req, file, callback) {\r\n        // console.log(file.originalname)\r\n        callback(null, (new Date()).getTime() + \"_\" + file.originalname);\r\n    }\r\n});\r\n\r\nvar upload = multer({ storage: storage }).single(\"challenge\");\r\napp.post(\"/upload\", function (req, res) {\r\n    // console.log(req)\r\n    upload(req, res, function (err) {\r\n        if (err) {\r\n            return res.end(\"Error:\" + err);\r\n        }\r\n        return res.end(\"file uploaded.\");\r\n    });\r\n});\r\n\r\napp.use(function (req, res, next) {\r\n    res.status(404).send(\"Page Not Found\");\r\n});\r\n\r\napp.use(function (err, req, res, next) {\r\n    console.error(err.stack);\r\n    res.status(500).send(\"Broken\");\r\n});\r\n\r\napp.use(parser.json());\r\n\r\napp.listen(pub_port, function () {\r\n    console.log(\"listening ... \" + pub_port);\r\n});\r\n"
  },
  {
    "path": "jsb_build/httpserver/tsconfig.json",
    "content": "{\r\n    \"include\": [\r\n        \"./src\"\r\n    ],\r\n    \"compilerOptions\": {\r\n        \"module\": \"commonjs\",\r\n        \"target\": \"es5\",\r\n        \"outDir\": \"js-out\",\r\n        \"declaration\": false,\r\n        \"noImplicitAny\": false,\r\n        \"sourceMap\": false\r\n    }\r\n}"
  },
  {
    "path": "jsb_build/quickjs/CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.10)\r\n\r\n# before project definition\r\n\r\nif (APPLE) \r\n    if (NOT IOS)\r\n        # -DCMAKE_OSX_DEPLOYMENT_TARGET:STRING=10.13\r\n        set(CMAKE_OSX_DEPLOYMENT_TARGET \"10.13\" CACHE STRING \"Minimum OS X deployment version\")\r\n        set(CMAKE_XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH \"NO\")\r\n        # set(CMAKE_XCODE_ATTRIBUTE_ARCHS \"x84_64\")\r\n    endif ()\r\nendif ()\r\n\r\nif (CONFIG_WIN32)\r\n    if (CONFIG_WIN32_64)\r\n        set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc)\r\n        set(CMAKE_STRIP x86_64-w64-mingw32-strip)\r\n        if (CONFIG_LTO)\r\n            set(CMAKE_AR x86_64-w64-mingw32-gcc-ar)\r\n        else ()\r\n            set(CMAKE_AR x86_64-w64-mingw32-ar)\r\n        endif ()\r\n    else ()\r\n        set(CMAKE_C_COMPILER i686-w64-mingw32-gcc)\r\n        set(CMAKE_STRIP i686-w64-mingw32-strip)\r\n        if (CONFIG_LTO)\r\n            set(CMAKE_AR i686-w64-mingw32-gcc-ar)\r\n        else ()\r\n            set(CMAKE_AR i686-w64-mingw32-ar)\r\n        endif ()\r\n    endif ()\r\nendif ()\r\n\r\nproject(unity-jsb)\r\n\r\nset(TOP_DIR ${CMAKE_CURRENT_SOURCE_DIR})\r\nset(OUT_DIR ${TOP_DIR}/build)\r\n\r\nif (CONFIG_WSA)\r\n    # set(QJS_LIBS ${QJS_LIBS} -lwinstorecompat)\r\n    set(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} /wd\\\"4146\\\" /wd\\\"4703\\\"\")\r\n\r\n    add_definitions(\r\n        -D_CRT_SECURE_NO_WARNINGS\r\n    )\r\n\r\n    set(QJS_DIR ${TOP_DIR}/quickjs-wsa)\r\n    include_directories(${QJS_DIR})\r\n    set(QJS_SRCS \r\n        ${QJS_DIR}/quickjs.c\r\n        ${QJS_DIR}/libregexp.c\r\n        ${QJS_DIR}/libunicode.c\r\n        ${QJS_DIR}/cutils.c\r\n        ${QJS_DIR}/../unity_qjs.c\r\n    )\r\nelse ()\r\n    if (CONFIG_WIN32)\r\n        if (CONFIG_WIN32_64)\r\n            set(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -m64\")\r\n        else ()\r\n            set(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -m32\")\r\n        endif ()\r\n        set(QJS_LIBS -lm -static-libgcc -static-libstdc++ -Wl,-Bstatic -lstdc++ -lpthread -Wl,-Bdynamic)\r\n    else ()\r\n        set(QJS_LIBS -lm -ldl)\r\n        set(LDFLAGS \"${LDFLAGS} -rdynamic\")\r\n    endif ()\r\n\r\n    if (JSB_DEBUG)\r\n        add_definitions(-DJSB_DEBUG)\r\n        set(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -g\")\r\n    endif ()\r\n\r\n    add_definitions(\r\n        -DCONFIG_BIGNUM\r\n    )\r\n    \r\n    set(QJS_DIR ${TOP_DIR}/quickjs-latest)\r\n    include_directories(${QJS_DIR})\r\n    set(QJS_SRCS \r\n        ${QJS_DIR}/quickjs.c\r\n        ${QJS_DIR}/libregexp.c\r\n        ${QJS_DIR}/libunicode.c\r\n        ${QJS_DIR}/cutils.c\r\n        ${QJS_DIR}/libbf.c\r\n        ${QJS_DIR}/../unity_qjs.c\r\n    )\r\n    \r\n    if (APPLE)\r\n        set(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -fPIC -Wall -Wno-array-bounds -Wno-format-truncation\")\r\n    else ()\r\n        set(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -fPIC -shared -Wall -Wno-array-bounds -Wno-format-truncation\")\r\n    endif ()\r\nendif ()\r\n\r\nset(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -s\")\r\nif (CONFIG_LTO)\r\n    add_definitions(-DCONFIG_LTO)\r\n    set(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -O2 -flto\")\r\n    set(LDFLAGS \"${LDFLAGS} ${CMAKE_C_FLAGS} -g\")\r\nelse ()\r\n    set(LDFLAGS \"${LDFLAGS} ${CMAKE_C_FLAGS}\")\r\nendif ()\r\n\r\nif (CONFIG_WIN32)\r\n    add_definitions(\r\n        -D__USE_MINGW_ANSI_STDIO\r\n    )\r\nendif ()\r\n\r\nadd_definitions(\r\n    -DCONFIG_DISABLE_STACK_CHECK\r\n    -DCONFIG_VERSION=\"${QJS_VERSION}\"\r\n    -D_GNU_SOURCE # ok?\r\n\r\n    # do not throw error when set typed array out of bound index\r\n    -DJSB_TYPED_ARRAY_NO_THROW\r\n)\r\n\r\nif (JSB_DEF_LOG2)\r\n    add_definitions(-DJSB_DEF_LOG2)\r\nendif ()\r\n\r\nif (APPLE) \r\n    if (IOS)\r\n        set(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -fembed-bitcode\")\r\n        # set(CMAKE_STATIC_LINKER_FLAGS \"${CMAKE_STATIC_LINKER_FLAGS} ${LDFLAGS}\")\r\n        set(IOS_PLATFORM OS64)\r\n        set(ENABLE_BITCODE 1)\r\n        add_library(quickjs STATIC ${QJS_SRCS})\r\n        set_xcode_property(quickjs IPHONEOS_DEPLOYMENT_TARGET \"9.0\" \"all\")\r\n    else ()\r\n        set(CMAKE_OSX_ARCHITECTURES \"$(ARCHS_STANDARD)\")\r\n        set(CMAKE_MODULE_LINKER_FLAGS \"${CMAKE_MODULE_LINKER_FLAGS} ${LDFLAGS}\")\r\n        add_library(quickjs MODULE ${QJS_SRCS})\r\n        set_target_properties(quickjs PROPERTIES MACOSX_BUNDLE TRUE)\r\n        set_target_properties(quickjs PROPERTIES BUNDLE TRUE)\r\n    endif ()\r\nelse () # WINDOWS ANDROID LINUX\r\n    set(CMAKE_SHARED_LINKER_FLAGS \"${CMAKE_SHARED_LINKER_FLAGS} ${LDFLAGS}\")\r\n    set(CMAKE_STATIC_LINKER_FLAGS \"${CMAKE_STATIC_LINKER_FLAGS} ${LDFLAGS}\")\r\n    add_library(quickjs SHARED ${QJS_SRCS})\r\nendif ()\r\n\r\nif (CONFIG_WIN32) \r\n    set_target_properties(quickjs PROPERTIES SUFFIX \".dll\")\r\nendif()\r\n\r\ntarget_link_libraries(quickjs ${QJS_LIBS})\r\n\r\nif (CONFIG_LTO)\r\n#    set_target_properties(quickjs PROPERTIES INTERPROCEDURAL_OPTIMIZATION TRUE)\r\nendif ()\r\n"
  },
  {
    "path": "jsb_build/quickjs/copy_to_assets.sh",
    "content": "#!/usr/bin/env sh\n\n# windows\ncp ../prebuilt/Plugins/x86/quickjs.dll ../../Assets/jsb/Plugins/x86/\ncp ../prebuilt/Plugins/x64/quickjs.dll ../../Assets/jsb/Plugins/x64/\n\n\n# android\ncp ../prebuilt/Plugins/Android/libs/arm64-v8a/libquickjs.so ../../Assets/jsb/Plugins/Android/libs/arm64-v8a/\ncp ../prebuilt/Plugins/Android/libs/armeabi-v7a/libquickjs.so ../../Assets/jsb/Plugins/Android/libs/armeabi-v7a/\ncp ../prebuilt/Plugins/Android/libs/x86/libquickjs.so ../../Assets/jsb/Plugins/Android/libs/x86/\n\n# iphoneos\ncp ../prebuilt/Plugins/iOS/libquickjs.a ../../Assets/jsb/Plugins/iOS/\n\n# macos\ncp ../prebuilt/Plugins/quickjs.bundle/Contents/MacOS/quickjs ../../Assets/jsb/Plugins/quickjs.bundle/Contents/MacOS/\n"
  },
  {
    "path": "jsb_build/quickjs/demo.c",
    "content": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n#include \"../quickjs.h\"\n#include \"../quickjs-libc.h\"\n#include \"../unity_base.c\"\n\n// enum\n// {\n//     JS_ATOM_NULL,\n// #define DEF(name, str) JS_ATOM_##name,\n// #include \"../quickjs-atom.h\"\n// #undef DEF\n//     JS_ATOM_END,\n// };\n\nJS_BOOL JSB_SetBridgeType(JSContext *ctx, JSValue obj, int32_t type)\n{\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT)\n    {\n        JS_SetPropertyStr(ctx, obj, JS_HIDDEN_PROP(\"type\"), JS_NewInt32(ctx, type));\n        return TRUE;\n    }\n    return FALSE;\n}\n\nint32_t JSB_GetBridgeType(JSContext *ctx, JSValue obj)\n{\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT)\n    {\n        JSValue val = JS_GetPropertyStr(ctx, obj, JS_HIDDEN_PROP(\"type\"));\n        int32_t pres;\n        if (JS_ToInt32(ctx, &pres, val) == 0)\n        {\n            JS_FreeValue(ctx, val);\n            return pres;\n        }\n        JS_FreeValue(ctx, val);\n    }\n    return -1;\n}\n\nstatic int running = 1;\nstatic JSClassID unity_object_class_id;\n\nstatic void foo_finalizer(JSRuntime *rt, JSValue val)\n{\n    void *data = JS_GetOpaque(val, unity_object_class_id);\n    printf(\"unity_object_class.finalizer (%d)\\n\", (int)data);\n}\n\nstatic int iii = 123;\nstatic JSValue foo_constructor(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv)\n{\n    iii++;\n    printf(\"foo.constructor %d\\n\", iii);\n    JSValue proto = JS_GetProperty(ctx, new_target, JS_ATOM_prototype);\n    JSValue obj = JS_NewObjectProtoClass(ctx, proto, unity_object_class_id);\n    JS_SetOpaque(obj, (void *)iii);\n    JS_FreeValue(ctx, proto);\n    JSB_SetBridgeType(ctx, obj, 233);\n    // return new_target;\n    return obj;\n}\n\nstatic JSValue foo_call(JSContext *ctx, JSValueConst this_obj, int argc, JSValueConst *argv)\n{\n    void *data = JS_GetOpaque(this_obj, unity_object_class_id);\n    printf(\"foo.call %d\\n\", (int)data);\n    assert(JSB_GetBridgeType(ctx, this_obj) == 233);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue goo_constructor(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv)\n{\n    iii++;\n    printf(\"goo.constructor %d\\n\", iii);\n    JSValue proto = JS_GetProperty(ctx, new_target, JS_ATOM_prototype);\n    JSValue obj = JS_NewObjectProtoClass(ctx, proto, unity_object_class_id);\n    JS_SetOpaque(obj, (void *)iii);\n    JS_FreeValue(ctx, proto);\n    // return new_target;\n    return obj;\n}\n\nstatic char *read_file(const char *filename)\n{\n    FILE *fp = fopen(filename, \"r\");\n    if (fp)\n    {\n        fseek(fp, 0, SEEK_END);\n        long length = ftell(fp);\n        fseek(fp, 0, SEEK_SET);\n        char *buf = malloc(length + 1);\n        memset(buf, 0, length + 1);\n        fread(buf, length, 1, fp);\n        fclose(fp);\n        return buf;\n    }\n    return 0;\n}\n\nstatic void print_exception(JSContext *ctx, JSValueConst e)\n{\n    JSValue err_msg = JS_GetProperty(ctx, e, JS_ATOM_message);\n    size_t len = 0;\n    const char *msg_str = JS_ToCStringLen(ctx, &len, err_msg);\n    printf(\"exception: %s\\n\", msg_str);\n    JS_FreeCString(ctx, msg_str);\n    JS_FreeValue(ctx, err_msg);\n}\n\nstatic JSValue js_quit(JSContext *ctx, JSValueConst this_val,\n                       int argc, JSValueConst *argv)\n{\n    running = 0;\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_print(JSContext *ctx, JSValueConst this_val,\n                        int argc, JSValueConst *argv)\n{\n    int i;\n    const char *str;\n    size_t len;\n\n    for (i = 0; i < argc; i++)\n    {\n        if (i != 0)\n            putchar(' ');\n        str = JS_ToCStringLen(ctx, &len, argv[i]);\n        if (!str)\n            return JS_EXCEPTION;\n        fwrite(str, 1, len, stdout);\n        JS_FreeCString(ctx, str);\n    }\n    putchar('\\n');\n    return JS_UNDEFINED;\n}\n\nstatic JSModuleDef *js_module_loader_test(JSContext *ctx,\n                                          const char *module_name, void *opaque)\n{\n    printf(\"js_module_loader: %s\\n\", module_name);\n    size_t buf_len;\n    uint8_t *buf;\n    JSModuleDef *m;\n    JSValue func_val;\n\n    buf = js_load_file(ctx, &buf_len, module_name);\n    if (!buf)\n    {\n        JS_ThrowReferenceError(ctx, \"could not load module filename '%s'\",\n                               module_name);\n        return NULL;\n    }\n\n    /* compile the module */\n    func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name,\n                       JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);\n    js_free(ctx, buf);\n    if (JS_IsException(func_val))\n        return NULL;\n    /* the module is already referenced, so we must free it */\n    m = JS_VALUE_GET_PTR(func_val);\n    JS_FreeValue(ctx, func_val);\n    return m;\n}\n\nvoid foo()\n{\n    JSB_Init();\n    JSRuntime *rt = JS_NewRuntime();\n    JSContext *ctx = JS_NewContext(rt);\n    JS_AddIntrinsicOperators(ctx);\n\n    JSAtom op = JS_NewAtom(ctx, \"Operators\");\n    printf(\"Operators: %d ?? %d\\n\", op, JSB_ATOM_Operators());\n    JS_FreeAtom(ctx, op);\n\n    JSValue globalObj = JS_GetGlobalObject(ctx);\n    JSValue operators = JS_GetPropertyStr(ctx, globalObj, \"Operators\");\n    if (JS_IsUndefined(operators))\n    {\n        printf(\"?????????????????\\n\");\n    }\n    JS_FreeValue(ctx, operators);\n    JS_FreeValue(ctx, globalObj);\n\n    JS_SetModuleLoaderFunc(rt, NULL, js_module_loader_test, NULL);\n\n    js_init_module_std(ctx, \"std\");\n    js_init_module_os(ctx, \"os\");\n\n    JSClassID cls_id;\n    unity_object_class_id = JS_NewClassID(&cls_id);\n\n    JSClassDef cls_def;\n    cls_def.class_name = \"UnityObject\";\n    cls_def.finalizer = foo_finalizer;\n    cls_def.exotic = NULL;\n    cls_def.gc_mark = NULL;\n    cls_def.call = NULL;\n    JS_NewClass(rt, cls_id, &cls_def);\n\n    JSValue global_obj = JS_GetGlobalObject(ctx);\n\n    JS_SetPropertyStr(ctx, global_obj, \"print\", JS_NewCFunction(ctx, js_print, \"print\", 1));\n    JS_SetPropertyStr(ctx, global_obj, \"quit\", JS_NewCFunction(ctx, js_quit, \"quit\", 0));\n\n    JSAtom atom_test = JS_NewAtom(ctx, \"Foo\");\n    JSValue foo_proto_val = JS_NewObject(ctx);\n    JSValue foo_constructor_val = JSB_NewCFunction(ctx, foo_constructor, atom_test, 0, JS_CFUNC_constructor, 0);\n    JS_SetConstructor(ctx, foo_constructor_val, foo_proto_val);\n    // JS_SetClassProto(ctx, cls_id, foo_proto_val);\n    // JS_SetPrototype( __this_is_super_base_class__ );\n    JSB_SetBridgeType(ctx, foo_constructor_val, 123);\n    assert(JSB_GetBridgeType(ctx, foo_constructor_val) == 123);\n    JS_DefinePropertyValue(ctx, global_obj, atom_test, foo_constructor_val, JS_PROP_ENUMERABLE | JS_PROP_CONFIGURABLE);\n    JSValue foo_prop = JSB_NewPropertyObject(ctx, foo_constructor_val, atom_test, JS_PROP_ENUMERABLE | JS_PROP_CONFIGURABLE);\n\n    JSAtom atom_call = JS_NewAtom(ctx, \"call\");\n    JSValue foo_call_val = JSB_NewCFunction(ctx, foo_call, atom_call, 0, JS_CFUNC_generic, 0);\n    JS_DefinePropertyValue(ctx, foo_proto_val, atom_call, foo_call_val, JS_PROP_ENUMERABLE | JS_PROP_CONFIGURABLE);\n    JS_FreeAtom(ctx, atom_call);\n\n    JS_FreeValue(ctx, foo_prop);\n    JS_FreeAtom(ctx, atom_test);\n\n    JSValue goo_proto_val = JS_NewObject(ctx);\n    JSValue goo_constructor_val = JS_NewCFunction2(ctx, goo_constructor, \"Goo\", 0, JS_CFUNC_constructor, 0);\n    JS_SetConstructor(ctx, goo_constructor_val, goo_proto_val);\n    // JS_SetClassProto(ctx, cls_id, goo_proto_val);\n    JS_SetPrototype(ctx, goo_proto_val, foo_proto_val);\n    JS_DefinePropertyValueStr(ctx, global_obj, \"Goo\", goo_constructor_val, JS_PROP_ENUMERABLE | JS_PROP_CONFIGURABLE);\n\n    char *source = read_file(\"./examples/demo.js\");\n    JSValue rval = JS_Eval(ctx, source, strlen(source), \"eval\", JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_STRICT);\n    if (JS_IsException(rval))\n    {\n        JSValue e = JS_GetException(ctx);\n        print_exception(ctx, e);\n    }\n    free(source);\n    JS_FreeValue(ctx, rval);\n\nJS_FreeValue(ctx, foo_proto_val);\nJS_FreeValue(ctx, goo_proto_val);\n    // JS_FreeValue(ctx, foo_proto_val);\n    // JS_FreeValue(ctx, foo_constructor_val);\n    JS_FreeValue(ctx, global_obj);\n\n    while (running)\n    {\n        js_std_loop(ctx);\n    }\n\n    JS_RunGC(rt);\n    JS_FreeContext(ctx);\n    JS_FreeRuntime(rt);\n}\n\nint main()\n{\n    printf(\"demo running...\\n\");\n    foo();\n    fflush(stdout);\n    return 0;\n}\n"
  },
  {
    "path": "jsb_build/quickjs/demo.js",
    "content": "\nimport * as std from \"std\";\nimport * as os from \"os\";\n\nimport {fib as fib1} from \"./examples/fib_module.js\";\nimport {fib as fib2} from \"./examples/fib_module.js\";\n\nprint(\"fib1:\", fib1(6));\nprint(\"fib2:\", fib2(6));\n\nprint(\"Foo.Foo test\", Foo.Foo);\n\nlet fc = new Foo();\n\nfc.call();\n\nlet setTimeout = os.setTimeout;\n\nfor (var i = 0; i < 5; i++) {\n    let foo = new Foo();\n    foo = undefined;\n}\n\nlet goo = new Goo();\ngoo = undefined;\n\nlet goo2 = new Goo();\n\nfunction delay() {\n    return new Promise((resolve, reject) => {\n        setTimeout(() => {\n            print(\"[async] resolve\");\n            resolve();\n        }, 1000);\n    });\n}\n\nasync function test() {\n    print(\"[async] begin\");\n    await delay();\n    print(\"[async] end\");\n    quit();\n}\n\nsetTimeout(() => {\n    print(\"[timeout] test\");\n    quit();\n}, 1500);\n\ntest();\n\nprint(\"end of script\");\n\n"
  },
  {
    "path": "jsb_build/quickjs/make_jsb_android.bat",
    "content": "@echo off\r\n\r\nif not defined ANDROID_NDK (\r\n    set ANDROID_NDK=D:/android-ndk-r23b\r\n)\r\nset BASE_PATH=%~dp0\r\nset BUILD_PATH=%~dp0..\\out\\quickjs\r\necho %BUILD_PATH%\r\n\r\nmkdir %BUILD_PATH% 2>nul\r\ncd %BUILD_PATH%\r\n\r\nrd /s /q %BUILD_PATH%\\Android_v7a_release 2>nul\r\necho building v7a release\r\nmkdir %BUILD_PATH%\\Android_v7a_release\r\ncd %BUILD_PATH%\\Android_v7a_release\r\ncmake -DQJS_VERSION=2021-03-27 -DCONFIG_LTO=y -DCMAKE_BUILD_TYPE=RELEASE -DANDROID_ABI=armeabi-v7a -DCMAKE_TOOLCHAIN_FILE=%ANDROID_NDK%/build/cmake/android.toolchain.cmake -DANDROID_TOOLCHAIN_NAME=arm-linux-androideabi-clang -DANDROID_NATIVE_API_LEVEL=android-16 -G \"NMake Makefiles\" %BASE_PATH%\r\ncd %BUILD_PATH%\r\ncmake --build Android_v7a_release --config Release\r\nmkdir ..\\..\\prebuilt\\Plugins\\Android\\libs\\armeabi-v7a\\\r\nxcopy /Y .\\Android_v7a_release\\libquickjs.so ..\\..\\prebuilt\\Plugins\\Android\\libs\\armeabi-v7a\\\r\n\r\nrd /s /q %BUILD_PATH%\\Android_v8a_release 2>nul\r\necho building v8a release\r\nmkdir %BUILD_PATH%\\Android_v8a_release\r\ncd %BUILD_PATH%\\Android_v8a_release\r\ncmake -DQJS_VERSION=2021-03-27 -DCONFIG_LTO=y -DCMAKE_BUILD_TYPE=RELEASE -DANDROID_ABI=arm64-v8a -DCMAKE_TOOLCHAIN_FILE=%ANDROID_NDK%/build/cmake/android.toolchain.cmake -DANDROID_TOOLCHAIN_NAME=arm-linux-androideabi-clang -DANDROID_NATIVE_API_LEVEL=android-16 -G \"NMake Makefiles\" %BASE_PATH%\r\ncd %BUILD_PATH%\r\ncmake --build Android_v8a_release --config Release\r\nmkdir ..\\..\\prebuilt\\Plugins\\Android\\libs\\arm64-v8a\\\r\nxcopy /Y .\\Android_v8a_release\\libquickjs.so ..\\..\\prebuilt\\Plugins\\Android\\libs\\arm64-v8a\\\r\n\r\nrd /s /q %BUILD_PATH%\\Android_x86_release 2>nul\r\necho building x86 release\r\nmkdir %BUILD_PATH%\\Android_x86_release\r\ncd %BUILD_PATH%\\Android_x86_release\r\ncmake -DQJS_VERSION=2021-03-27 -DCONFIG_LTO=y -DCMAKE_BUILD_TYPE=RELEASE -DANDROID_ABI=x86 -DCMAKE_TOOLCHAIN_FILE=%ANDROID_NDK%/build/cmake/android.toolchain.cmake -DANDROID_TOOLCHAIN_NAME=x86-clang -DANDROID_NATIVE_API_LEVEL=android-16 -G \"NMake Makefiles\" %BASE_PATH%\r\ncd %BUILD_PATH%\r\ncmake --build Android_x86_release --config Release\r\nmkdir ..\\..\\prebuilt\\Plugins\\Android\\libs\\x86\\\r\nxcopy /Y .\\Android_x86_release\\libquickjs.so ..\\..\\prebuilt\\Plugins\\Android\\libs\\x86\\\r\n\r\ncd %BASE_PATH%\r\n"
  },
  {
    "path": "jsb_build/quickjs/make_jsb_android.sh",
    "content": "#!/usr/bin/env sh\n\nif [ -z \"$ANDROID_NDK\" ]; then\n    export ANDROID_NDK=~/android-ndk-r23b\nfi\n\nBASE_PATH=$(cd `dirname $0`;pwd)\nBUILD_PATH=$BASE_PATH/../out/quickjs\necho $BUILD_PATH\n\nmkdir -p $BUILD_PATH\ncd $BUILD_PATH\n\nrm -rf $BUILD_PATH/Android_v7a_release\necho building v7a release\nmkdir -p $BUILD_PATH/Android_v7a_release\ncd $BUILD_PATH/Android_v7a_release\ncmake -DQJS_VERSION=2021-03-27 -DCONFIG_LTO=y -DCMAKE_BUILD_TYPE=RELEASE -DANDROID_ABI=armeabi-v7a -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake -DANDROID_TOOLCHAIN_NAME=arm-linux-androideabi-clang -DANDROID_NATIVE_API_LEVEL=android-16 $BASE_PATH\ncd $BUILD_PATH\ncmake --build Android_v7a_release --config Release\nmkdir -p ../../prebuilt/Plugins/Android/libs/armeabi-v7a/\nls -l ./Android_v7a_release/\nfile ./Android_v7a_release/libquickjs.so\ncp ./Android_v7a_release/libquickjs.so ../../prebuilt/Plugins/Android/libs/armeabi-v7a/\n\nrm -rf $BUILD_PATH/Android_v8a_release\necho building v8a release\nmkdir -p $BUILD_PATH/Android_v8a_release\ncd $BUILD_PATH/Android_v8a_release\ncmake -DQJS_VERSION=2021-03-27 -DCONFIG_LTO=y -DCMAKE_BUILD_TYPE=RELEASE -DANDROID_ABI=arm64-v8a -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake -DANDROID_TOOLCHAIN_NAME=arm-linux-androideabi-clang -DANDROID_NATIVE_API_LEVEL=android-16 $BASE_PATH\ncd $BUILD_PATH\ncmake --build Android_v8a_release --config Release\nmkdir -p ../../prebuilt/Plugins/Android/libs/arm64-v8a/\nls -l ./Android_v8a_release/\nfile ./Android_v8a_release/libquickjs.so\ncp ./Android_v8a_release/libquickjs.so ../../prebuilt/Plugins/Android/libs/arm64-v8a/\n\nrm -rf $BUILD_PATH/Android_x86_release\necho building x86 release\nmkdir -p $BUILD_PATH/Android_x86_release\ncd $BUILD_PATH/Android_x86_release\ncmake -DQJS_VERSION=2021-03-27 -DCONFIG_LTO=y -DCMAKE_BUILD_TYPE=RELEASE -DANDROID_ABI=x86 -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake -DANDROID_TOOLCHAIN_NAME=x86-clang -DANDROID_NATIVE_API_LEVEL=android-16 $BASE_PATH\ncd $BUILD_PATH\ncmake --build Android_x86_release --config Release\nmkdir -p ../../prebuilt/Plugins/Android/libs/x86/\nls -l ./Android_x86_release/\nfile ./Android_x86_release/libquickjs.so\ncp ./Android_x86_release/libquickjs.so ../../prebuilt/Plugins/Android/libs/x86/\n\ncd $BASE_PATH\n"
  },
  {
    "path": "jsb_build/quickjs/make_jsb_ios.sh",
    "content": "#!/usr/bin/env sh\n\nrm -rf ../out/quickjs/ios_release\nmkdir -p ../out/quickjs/ios_release\ncd ../out/quickjs/ios_release\ncmake -DQJS_VERSION=2021-03-27 -DCONFIG_LTO=y -DIOS_PLATFORM=\"OS64\" -DIOS_ARCH=\"arm64 arm64e\" -DCMAKE_TOOLCHAIN_FILE=../../../cmake/ios.toolchain.cmake -DPLATFORM=OS64 -GXcode ../../../quickjs\ncd ..\necho building...\ncmake --build ios_release --config Release\nmkdir -p ../../prebuilt/Plugins/iOS/\npwd\nls -l ./ios_release/Release-iphoneos/\ncp ./ios_release/Release-iphoneos/libquickjs.a ../../prebuilt/Plugins/iOS/\ncd ..\n"
  },
  {
    "path": "jsb_build/quickjs/make_jsb_linux.sh",
    "content": "#!/usr/bin/env sh\n\nrm -rf ../out/quickjs/linux_release\nmkdir -p ../out/quickjs/linux_release\ncd ../out/quickjs/linux_release\ncmake -DQJS_VERSION=2021-03-27 -DCONFIG_LTO=y -G\"Unix Makefiles\" ../../../quickjs\ncd ..\necho building...\ncmake --build linux_release --config Release\nmkdir -p ../../prebuilt/Plugins/x64/\npwd\nls -l ./linux_release/\ncp ./linux_release/libquickjs.so ../../prebuilt/Plugins/x64/\ncd ..\n"
  },
  {
    "path": "jsb_build/quickjs/make_jsb_macos.sh",
    "content": "#!/usr/bin/env sh\n\nrm -rf ../out/quickjs/macos_release\nmkdir -p ../out/quickjs/macos_release\ncd ../out/quickjs/macos_release\ncmake -DQJS_VERSION=2021-03-27 -DCONFIG_LTO=y -GXcode ../../../quickjs\ncd ..\necho building...\ncmake --build macos_release --config Release\nmkdir -p ../../prebuilt/Plugins/quickjs.bundle/Contents/MacOS/\npwd\nls -l ./macos_release/Release/quickjs.bundle/Contents/MacOS/\ncp ./macos_release/Release/quickjs.bundle/Contents/Info.plist ../../prebuilt/Plugins/quickjs.bundle/Contents/\ncp ./macos_release/Release/quickjs.bundle/Contents/MacOS/quickjs ../../prebuilt/Plugins/quickjs.bundle/Contents/MacOS/\ncd ..\n"
  },
  {
    "path": "jsb_build/quickjs/make_jsb_win.sh",
    "content": "#!/usr/bin/env sh\n\nrm -rf ../out/quickjs/windows_x64\nmkdir -p ../out/quickjs/windows_x64\ncd ../out/quickjs/windows_x64\ncmake -DQJS_VERSION=2021-03-27 -DCONFIG_LTO=y -DCONFIG_WIN32=y -DCONFIG_WIN32_64=y -G\"Unix Makefiles\" ../../../quickjs\ncd ..\necho building...\ncmake --build windows_x64 --config Release\nmkdir -p ../../prebuilt/Plugins/x64/\npwd\nls -l ./windows_x64/\ncp ./windows_x64/libquickjs.dll ../../prebuilt/Plugins/x64/quickjs.dll\ncd ..\n\nrm -rf ../out/quickjs/windows_x86\nmkdir -p ../out/quickjs/windows_x86\ncd ../out/quickjs/windows_x86\ncmake -DQJS_VERSION=2021-03-27 -DCONFIG_LTO=y -DCONFIG_WIN32=y -G\"Unix Makefiles\" ../../../quickjs\ncd ..\necho building...\ncmake --build windows_x86 --config Release\nmkdir -p ../../prebuilt/Plugins/x86/\npwd\nls -l ./windows_x86/\ncp ./windows_x86/libquickjs.dll ../../prebuilt/Plugins/x86/quickjs.dll\ncd ..\n"
  },
  {
    "path": "jsb_build/quickjs/make_jsb_wsa.bat",
    "content": "@echo off\r\n\r\n@REM set VS_VERSION=\"Visual Studio 15 2017\"\r\n@REM set VS_VERSION=\"Visual Studio 16 2019\"\r\nset VS_VERSION=\"Visual Studio 17 2022\"\r\n\r\nset BASE_PATH=%~dp0\r\nset BUILD_PATH=%~dp0..\\out\\quickjs\r\necho %BUILD_PATH%\r\necho %VS_VERSION%\r\n\r\nmkdir %BUILD_PATH% 2>nul\r\ncd %BUILD_PATH%\r\n\r\nrd /s /q %BUILD_PATH%\\wsa_x86_release 2>nul\r\necho building wsa_x86_release\r\nmkdir %BUILD_PATH%\\wsa_x86_release\r\ncd %BUILD_PATH%\\wsa_x86_release\r\ncmake -DQJS_VERSION=2021-03-27 -DCONFIG_LTO=y -DCONFIG_WSA=y -DCMAKE_BUILD_TYPE=RELEASE -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 -G %VS_VERSION% -A Win32 %BASE_PATH%\r\ncd %BUILD_PATH%\r\ncmake --build wsa_x86_release --config Release\r\nmkdir ..\\..\\prebuilt\\Plugins\\WSA\\x86\\\r\nxcopy /Y .\\wsa_x86_release\\Release\\quickjs.dll ..\\..\\prebuilt\\Plugins\\WSA\\x86\\\r\n\r\nrd /s /q %BUILD_PATH%\\wsa_x64_release 2>nul\r\necho building wsa_x64_release\r\nmkdir %BUILD_PATH%\\wsa_x64_release\r\ncd %BUILD_PATH%\\wsa_x64_release\r\ncmake -DQJS_VERSION=2021-03-27 -DJSB_DEF_LOG2=y -DCONFIG_LTO=y -DCONFIG_WSA=y -DCMAKE_BUILD_TYPE=RELEASE -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 -G %VS_VERSION% -A x64 %BASE_PATH%\r\ncd %BUILD_PATH%\r\ncmake --build wsa_x64_release --config Release\r\nmkdir ..\\..\\prebuilt\\Plugins\\WSA\\x64\\\r\nxcopy /Y .\\wsa_x64_release\\Release\\quickjs.dll ..\\..\\prebuilt\\Plugins\\WSA\\x64\\\r\n\r\nrd /s /q %BUILD_PATH%\\wsa_ARM_release 2>nul\r\necho building wsa_ARM_release\r\nmkdir %BUILD_PATH%\\wsa_ARM_release\r\ncd %BUILD_PATH%\\wsa_ARM_release\r\ncmake -DQJS_VERSION=2021-03-27 -DCONFIG_LTO=y -DCONFIG_WSA=y -DCMAKE_BUILD_TYPE=RELEASE -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 -G %VS_VERSION% -A ARM %BASE_PATH%\r\ncd %BUILD_PATH%\r\ncmake --build wsa_ARM_release --config Release\r\nmkdir ..\\..\\prebuilt\\Plugins\\WSA\\ARM\\\r\nxcopy /Y .\\wsa_ARM_release\\Release\\quickjs.dll ..\\..\\prebuilt\\Plugins\\WSA\\ARM\\\r\n\r\nrd /s /q %BUILD_PATH%\\wsa_ARM64_release 2>nul\r\necho building wsa_ARM64_release\r\nmkdir %BUILD_PATH%\\wsa_ARM64_release\r\ncd %BUILD_PATH%\\wsa_ARM64_release\r\ncmake -DQJS_VERSION=2021-03-27 -DJSB_DEF_LOG2=y -DCONFIG_LTO=y -DCONFIG_WSA=y -DCMAKE_BUILD_TYPE=RELEASE -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 -G %VS_VERSION% -A ARM64 %BASE_PATH%\r\ncd %BUILD_PATH%\r\ncmake --build wsa_ARM64_release --config Release\r\nmkdir ..\\..\\prebuilt\\Plugins\\WSA\\ARM64\\\r\nxcopy /Y .\\wsa_ARM64_release\\Release\\quickjs.dll ..\\..\\prebuilt\\Plugins\\WSA\\ARM64\\\r\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/Changelog",
    "content": "2021-03-27:\n\n- faster Array.prototype.push and Array.prototype.unshift\n- added JS_UpdateStackTop()\n- fixed Windows console\n- misc bug fixes\n\n2020-11-08:\n\n- improved function parameter initializers\n- added std.setenv(), std.unsetenv() and std.getenviron()\n- added JS_EvalThis()\n- misc bug fixes\n\n2020-09-06:\n\n- added logical assignment operators\n- added IsHTMLDDA support\n- faster for-of loops\n- os.Worker now takes a module filename as parameter\n- qjsc: added -D option to compile dynamically loaded modules or workers\n- misc bug fixes\n\n2020-07-05:\n\n- modified JS_GetPrototype() to return a live value\n- REPL: support unicode characters larger than 16 bits\n- added os.Worker\n- improved object serialization\n- added std.parseExtJSON\n- misc bug fixes\n\n2020-04-12:\n\n- added cross realm support\n- added AggregateError and Promise.any\n- added env, uid and gid options in os.exec()\n- misc bug fixes\n\n2020-03-16:\n\n- reworked error handling in std and os libraries: suppressed I/O\n  exceptions in std FILE functions and return a positive errno value\n  when it is explicit\n- output exception messages to stderr\n- added std.loadFile(), std.strerror(), std.FILE.prototype.tello()\n- added JS_GetRuntimeOpaque(), JS_SetRuntimeOpaque(), JS_NewUint32()\n- updated to Unicode 13.0.0\n- misc bug fixes\n\n2020-01-19:\n\n- keep CONFIG_BIGNUM in the makefile\n- added os.chdir()\n- qjs: added -I option\n- more memory checks in the bignum operations\n- modified operator overloading semantics to be closer to the TC39\n  proposal\n- suppressed \"use bigint\" mode. Simplified \"use math\" mode\n- BigDecimal: changed suffix from 'd' to 'm'\n- misc bug fixes\n\n2020-01-05:\n\n- always compile the bignum code. Added '--bignum' option to qjs.\n- added BigDecimal\n- added String.prototype.replaceAll\n- misc bug fixes\n\n2019-12-21:\n\n- added nullish coalescing operator (ES2020)\n- added optional chaining (ES2020)\n- removed recursions in garbage collector\n- test stack overflow in the parser\n- improved backtrace logic\n- added JS_SetHostPromiseRejectionTracker()\n- allow exotic constructors\n- improved c++ compatibility\n- misc bug fixes\n\n2019-10-27:\n\n- added example of C class in a module (examples/test_point.js)\n- added JS_GetTypedArrayBuffer()\n- misc bug fixes\n\n2019-09-18:\n\n- added os.exec and other system calls\n- exported JS_ValueToAtom()\n- qjsc: added 'qjsc_' prefix to the generated C identifiers\n- added cross-compilation support\n- misc bug fixes\n\n2019-09-01:\n\n- added globalThis\n- documented JS_EVAL_FLAG_COMPILE_ONLY\n- added import.meta.url and import.meta.main\n- added 'debugger' statement\n- misc bug fixes\n\n2019-08-18:\n\n- added os.realpath, os.getcwd, os.mkdir, os.stat, os.lstat,\n  os.readlink, os.readdir, os.utimes, std.popen\n- module autodetection\n- added import.meta\n- misc bug fixes\n\n2019-08-10:\n\n- added public class fields and private class fields, methods and\n  accessors (TC39 proposal)\n- changed JS_ToCStringLen() prototype\n- qjsc: handle '-' in module names and modules with the same filename\n- added std.urlGet\n- exported JS_GetOwnPropertyNames() and JS_GetOwnProperty()\n- exported some bigint C functions\n- added support for eshost in run-test262\n- misc bug fixes\n\n2019-07-28:\n\n- added dynamic import\n- added Promise.allSettled\n- added String.prototype.matchAll\n- added Object.fromEntries\n- reduced number of ticks in await\n- added BigInt support in Atomics\n- exported JS_NewPromiseCapability()\n- misc async function and async generator fixes\n- enabled hashbang support by default\n\n2019-07-21:\n\n- updated test262 tests\n- updated to Unicode version 12.1.0\n- fixed missing Date object in qjsc\n- fixed multi-context creation\n- misc ES2020 related fixes\n- simplified power and division operators in bignum extension\n- fixed several crash conditions\n\n2019-07-09:\n\n- first public release\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/LICENSE",
    "content": "QuickJS Javascript Engine\n \nCopyright (c) 2017-2021 Fabrice Bellard\nCopyright (c) 2017-2021 Charlie Gordon\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/Makefile",
    "content": "#\n# QuickJS Javascript Engine\n# \n# Copyright (c) 2017-2021 Fabrice Bellard\n# Copyright (c) 2017-2021 Charlie Gordon\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nifeq ($(shell uname -s),Darwin)\nCONFIG_DARWIN=y\nendif\n# Windows cross compilation from Linux\n#CONFIG_WIN32=y\n# use link time optimization (smaller and faster executables but slower build)\nCONFIG_LTO=y\n# consider warnings as errors (for development)\n#CONFIG_WERROR=y\n# force 32 bit build for some utilities\n#CONFIG_M32=y\n\nifdef CONFIG_DARWIN\n# use clang instead of gcc\nCONFIG_CLANG=y\nCONFIG_DEFAULT_AR=y\nendif\n\n# installation directory\nprefix=/usr/local\n\n# use the gprof profiler\n#CONFIG_PROFILE=y\n# use address sanitizer\n#CONFIG_ASAN=y\n# include the code for BigInt/BigFloat/BigDecimal and math mode\nCONFIG_BIGNUM=y\n\nOBJDIR=.obj\n\nifdef CONFIG_WIN32\n  ifdef CONFIG_M32\n    CROSS_PREFIX=i686-w64-mingw32-\n  else\n    CROSS_PREFIX=x86_64-w64-mingw32-\n  endif\n  EXE=.exe\nelse\n  CROSS_PREFIX=\n  EXE=\nendif\nifdef CONFIG_CLANG\n  HOST_CC=clang\n  CC=$(CROSS_PREFIX)clang\n  CFLAGS=-g -Wall -MMD -MF $(OBJDIR)/$(@F).d\n  CFLAGS += -Wextra\n  CFLAGS += -Wno-sign-compare\n  CFLAGS += -Wno-missing-field-initializers\n  CFLAGS += -Wundef -Wuninitialized\n  CFLAGS += -Wunused -Wno-unused-parameter\n  CFLAGS += -Wwrite-strings\n  CFLAGS += -Wchar-subscripts -funsigned-char\n  CFLAGS += -MMD -MF $(OBJDIR)/$(@F).d\n  ifdef CONFIG_DEFAULT_AR\n    AR=$(CROSS_PREFIX)ar\n  else\n    ifdef CONFIG_LTO\n      AR=$(CROSS_PREFIX)llvm-ar\n    else\n      AR=$(CROSS_PREFIX)ar\n    endif\n  endif\nelse\n  HOST_CC=gcc\n  CC=$(CROSS_PREFIX)gcc\n  CFLAGS=-g -Wall -MMD -MF $(OBJDIR)/$(@F).d\n  CFLAGS += -Wno-array-bounds -Wno-format-truncation\n  ifdef CONFIG_LTO\n    AR=$(CROSS_PREFIX)gcc-ar\n  else\n    AR=$(CROSS_PREFIX)ar\n  endif\nendif\nSTRIP=$(CROSS_PREFIX)strip\nifdef CONFIG_WERROR\nCFLAGS+=-Werror\nendif\nDEFINES:=-D_GNU_SOURCE -DCONFIG_VERSION=\\\"$(shell cat VERSION)\\\"\nifdef CONFIG_BIGNUM\nDEFINES+=-DCONFIG_BIGNUM\nendif\nifdef CONFIG_WIN32\nDEFINES+=-D__USE_MINGW_ANSI_STDIO # for standard snprintf behavior\nendif\n\nCFLAGS+=$(DEFINES)\nCFLAGS_DEBUG=$(CFLAGS) -O0\nCFLAGS_SMALL=$(CFLAGS) -Os\nCFLAGS_OPT=$(CFLAGS) -O2\nCFLAGS_NOLTO:=$(CFLAGS_OPT)\nLDFLAGS=-g\nifdef CONFIG_LTO\nCFLAGS_SMALL+=-flto\nCFLAGS_OPT+=-flto\nLDFLAGS+=-flto\nendif\nifdef CONFIG_PROFILE\nCFLAGS+=-p\nLDFLAGS+=-p\nendif\nifdef CONFIG_ASAN\nCFLAGS+=-fsanitize=address -fno-omit-frame-pointer\nLDFLAGS+=-fsanitize=address -fno-omit-frame-pointer\nendif\nifdef CONFIG_WIN32\nLDEXPORT=\nelse\nLDEXPORT=-rdynamic\nendif\n\nPROGS=qjs$(EXE) qjsc$(EXE) run-test262\nifneq ($(CROSS_PREFIX),)\nQJSC_CC=gcc\nQJSC=./host-qjsc\nPROGS+=$(QJSC)\nelse\nQJSC_CC=$(CC)\nQJSC=./qjsc$(EXE)\nendif\nifndef CONFIG_WIN32\nPROGS+=qjscalc\nendif\nifdef CONFIG_M32\nPROGS+=qjs32 qjs32_s\nendif\nPROGS+=libquickjs.a\nifdef CONFIG_LTO\nPROGS+=libquickjs.lto.a\nendif\n\n# examples\nifeq ($(CROSS_PREFIX),)\nifdef CONFIG_ASAN\nPROGS+=\nelse\nPROGS+=examples/hello examples/hello_module examples/test_fib\nifndef CONFIG_DARWIN\nPROGS+=examples/fib.so examples/point.so\nendif\nendif\nendif\n\nall: $(OBJDIR) $(OBJDIR)/quickjs.check.o $(OBJDIR)/qjs.check.o $(PROGS)\n\nQJS_LIB_OBJS=$(OBJDIR)/quickjs.o $(OBJDIR)/libregexp.o $(OBJDIR)/libunicode.o $(OBJDIR)/cutils.o $(OBJDIR)/quickjs-libc.o\n\nQJS_OBJS=$(OBJDIR)/qjs.o $(OBJDIR)/repl.o $(QJS_LIB_OBJS)\nifdef CONFIG_BIGNUM\nQJS_LIB_OBJS+=$(OBJDIR)/libbf.o \nQJS_OBJS+=$(OBJDIR)/qjscalc.o\nendif\n\nHOST_LIBS=-lm -ldl -lpthread\nLIBS=-lm\nifndef CONFIG_WIN32\nLIBS+=-ldl -lpthread\nendif\nLIBS+=$(EXTRA_LIBS)\n\n$(OBJDIR):\n\tmkdir -p $(OBJDIR) $(OBJDIR)/examples $(OBJDIR)/tests\n\nqjs$(EXE): $(QJS_OBJS)\n\t$(CC) $(LDFLAGS) $(LDEXPORT) -o $@ $^ $(LIBS)\n\nqjs-debug$(EXE): $(patsubst %.o, %.debug.o, $(QJS_OBJS))\n\t$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)\n\nqjsc$(EXE): $(OBJDIR)/qjsc.o $(QJS_LIB_OBJS)\n\t$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)\n\nifneq ($(CROSS_PREFIX),)\n\n$(QJSC): $(OBJDIR)/qjsc.host.o \\\n    $(patsubst %.o, %.host.o, $(QJS_LIB_OBJS))\n\t$(HOST_CC) $(LDFLAGS) -o $@ $^ $(HOST_LIBS)\n\nendif #CROSS_PREFIX\n\nQJSC_DEFINES:=-DCONFIG_CC=\\\"$(QJSC_CC)\\\" -DCONFIG_PREFIX=\\\"$(prefix)\\\"\nifdef CONFIG_LTO\nQJSC_DEFINES+=-DCONFIG_LTO\nendif\nQJSC_HOST_DEFINES:=-DCONFIG_CC=\\\"$(HOST_CC)\\\" -DCONFIG_PREFIX=\\\"$(prefix)\\\"\n\n$(OBJDIR)/qjsc.o: CFLAGS+=$(QJSC_DEFINES)\n$(OBJDIR)/qjsc.host.o: CFLAGS+=$(QJSC_HOST_DEFINES)\n\nqjs32: $(patsubst %.o, %.m32.o, $(QJS_OBJS))\n\t$(CC) -m32 $(LDFLAGS) $(LDEXPORT) -o $@ $^ $(LIBS)\n\nqjs32_s: $(patsubst %.o, %.m32s.o, $(QJS_OBJS))\n\t$(CC) -m32 $(LDFLAGS) -o $@ $^ $(LIBS)\n\t@size $@\n\nqjscalc: qjs\n\tln -sf $< $@\n\nifdef CONFIG_LTO\nLTOEXT=.lto\nelse\nLTOEXT=\nendif\n\nlibquickjs$(LTOEXT).a: $(QJS_LIB_OBJS)\n\t$(AR) rcs $@ $^\n\nifdef CONFIG_LTO\nlibquickjs.a: $(patsubst %.o, %.nolto.o, $(QJS_LIB_OBJS))\n\t$(AR) rcs $@ $^\nendif # CONFIG_LTO\n\nrepl.c: $(QJSC) repl.js\n\t$(QJSC) -c -o $@ -m repl.js\n\nqjscalc.c: $(QJSC) qjscalc.js\n\t$(QJSC) -fbignum -c -o $@ qjscalc.js\n\nifneq ($(wildcard unicode/UnicodeData.txt),)\n$(OBJDIR)/libunicode.o $(OBJDIR)/libunicode.m32.o $(OBJDIR)/libunicode.m32s.o \\\n    $(OBJDIR)/libunicode.nolto.o: libunicode-table.h\n\nlibunicode-table.h: unicode_gen\n\t./unicode_gen unicode $@\nendif\n\nrun-test262: $(OBJDIR)/run-test262.o $(QJS_LIB_OBJS)\n\t$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)\n\nrun-test262-debug: $(patsubst %.o, %.debug.o, $(OBJDIR)/run-test262.o $(QJS_LIB_OBJS))\n\t$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)\n\nrun-test262-32: $(patsubst %.o, %.m32.o, $(OBJDIR)/run-test262.o $(QJS_LIB_OBJS))\n\t$(CC) -m32 $(LDFLAGS) -o $@ $^ $(LIBS)\n\n# object suffix order: nolto, [m32|m32s]\n\n$(OBJDIR)/%.o: %.c | $(OBJDIR)\n\t$(CC) $(CFLAGS_OPT) -c -o $@ $<\n\n$(OBJDIR)/%.host.o: %.c | $(OBJDIR)\n\t$(HOST_CC) $(CFLAGS_OPT) -c -o $@ $<\n\n$(OBJDIR)/%.pic.o: %.c | $(OBJDIR)\n\t$(CC) $(CFLAGS_OPT) -fPIC -DJS_SHARED_LIBRARY -c -o $@ $<\n\n$(OBJDIR)/%.nolto.o: %.c | $(OBJDIR)\n\t$(CC) $(CFLAGS_NOLTO) -c -o $@ $<\n\n$(OBJDIR)/%.m32.o: %.c | $(OBJDIR)\n\t$(CC) -m32 $(CFLAGS_OPT) -c -o $@ $<\n\n$(OBJDIR)/%.m32s.o: %.c | $(OBJDIR)\n\t$(CC) -m32 $(CFLAGS_SMALL) -c -o $@ $<\n\n$(OBJDIR)/%.debug.o: %.c | $(OBJDIR)\n\t$(CC) $(CFLAGS_DEBUG) -c -o $@ $<\n\n$(OBJDIR)/%.check.o: %.c | $(OBJDIR)\n\t$(CC) $(CFLAGS) -DCONFIG_CHECK_JSVALUE -c -o $@ $<\n\nregexp_test: libregexp.c libunicode.c cutils.c\n\t$(CC) $(LDFLAGS) $(CFLAGS) -DTEST -o $@ libregexp.c libunicode.c cutils.c $(LIBS)\n\nunicode_gen: $(OBJDIR)/unicode_gen.host.o $(OBJDIR)/cutils.host.o libunicode.c unicode_gen_def.h\n\t$(HOST_CC) $(LDFLAGS) $(CFLAGS) -o $@ $(OBJDIR)/unicode_gen.host.o $(OBJDIR)/cutils.host.o\n\nclean:\n\trm -f repl.c qjscalc.c out.c\n\trm -f *.a *.o *.d *~ unicode_gen regexp_test $(PROGS)\n\trm -f hello.c test_fib.c\n\trm -f examples/*.so tests/*.so\n\trm -rf $(OBJDIR)/ *.dSYM/ qjs-debug\n\trm -rf run-test262-debug run-test262-32\n\ninstall: all\n\tmkdir -p \"$(DESTDIR)$(prefix)/bin\"\n\t$(STRIP) qjs qjsc\n\tinstall -m755 qjs qjsc \"$(DESTDIR)$(prefix)/bin\"\n\tln -sf qjs \"$(DESTDIR)$(prefix)/bin/qjscalc\"\n\tmkdir -p \"$(DESTDIR)$(prefix)/lib/quickjs\"\n\tinstall -m644 libquickjs.a \"$(DESTDIR)$(prefix)/lib/quickjs\"\nifdef CONFIG_LTO\n\tinstall -m644 libquickjs.lto.a \"$(DESTDIR)$(prefix)/lib/quickjs\"\nendif\n\tmkdir -p \"$(DESTDIR)$(prefix)/include/quickjs\"\n\tinstall -m644 quickjs.h quickjs-libc.h \"$(DESTDIR)$(prefix)/include/quickjs\"\n\n###############################################################################\n# examples\n\n# example of static JS compilation\nHELLO_SRCS=examples/hello.js\nHELLO_OPTS=-fno-string-normalize -fno-map -fno-promise -fno-typedarray \\\n           -fno-typedarray -fno-regexp -fno-json -fno-eval -fno-proxy \\\n           -fno-date -fno-module-loader\nifdef CONFIG_BIGNUM\nHELLO_OPTS+=-fno-bigint\nendif\n\nhello.c: $(QJSC) $(HELLO_SRCS)\n\t$(QJSC) -e $(HELLO_OPTS) -o $@ $(HELLO_SRCS)\n\nifdef CONFIG_M32\nexamples/hello: $(OBJDIR)/hello.m32s.o $(patsubst %.o, %.m32s.o, $(QJS_LIB_OBJS))\n\t$(CC) -m32 $(LDFLAGS) -o $@ $^ $(LIBS)\nelse\nexamples/hello: $(OBJDIR)/hello.o $(QJS_LIB_OBJS)\n\t$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)\nendif\n\n# example of static JS compilation with modules\nHELLO_MODULE_SRCS=examples/hello_module.js\nHELLO_MODULE_OPTS=-fno-string-normalize -fno-map -fno-promise -fno-typedarray \\\n           -fno-typedarray -fno-regexp -fno-json -fno-eval -fno-proxy \\\n           -fno-date -m\nexamples/hello_module: $(QJSC) libquickjs$(LTOEXT).a $(HELLO_MODULE_SRCS)\n\t$(QJSC) $(HELLO_MODULE_OPTS) -o $@ $(HELLO_MODULE_SRCS)\n\n# use of an external C module (static compilation)\n\ntest_fib.c: $(QJSC) examples/test_fib.js\n\t$(QJSC) -e -M examples/fib.so,fib -m -o $@ examples/test_fib.js\n\nexamples/test_fib: $(OBJDIR)/test_fib.o $(OBJDIR)/examples/fib.o libquickjs$(LTOEXT).a\n\t$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)\n\nexamples/fib.so: $(OBJDIR)/examples/fib.pic.o\n\t$(CC) $(LDFLAGS) -shared -o $@ $^\n\nexamples/point.so: $(OBJDIR)/examples/point.pic.o\n\t$(CC) $(LDFLAGS) -shared -o $@ $^\n\n###############################################################################\n# documentation\n\nDOCS=doc/quickjs.pdf doc/quickjs.html doc/jsbignum.pdf doc/jsbignum.html \n\nbuild_doc: $(DOCS)\n\nclean_doc: \n\trm -f $(DOCS)\n\ndoc/%.pdf: doc/%.texi\n\ttexi2pdf --clean -o $@ -q $<\n\ndoc/%.html.pre: doc/%.texi\n\tmakeinfo --html --no-headers --no-split --number-sections -o $@ $<\n\ndoc/%.html: doc/%.html.pre\n\tsed -e 's|</style>|</style>\\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">|' < $< > $@\n\n###############################################################################\n# tests\n\nifndef CONFIG_DARWIN\ntest: tests/bjson.so examples/point.so\nendif\nifdef CONFIG_M32\ntest: qjs32\nendif\n\ntest: qjs\n\t./qjs tests/test_closure.js\n\t./qjs tests/test_language.js\n\t./qjs tests/test_builtin.js\n\t./qjs tests/test_loop.js\n\t./qjs tests/test_std.js\n\t./qjs tests/test_worker.js\nifndef CONFIG_DARWIN\nifdef CONFIG_BIGNUM\n\t./qjs --bignum tests/test_bjson.js\nelse\n\t./qjs tests/test_bjson.js\nendif\n\t./qjs examples/test_point.js\nendif\nifdef CONFIG_BIGNUM\n\t./qjs --bignum tests/test_op_overloading.js\n\t./qjs --bignum tests/test_bignum.js\n\t./qjs --qjscalc tests/test_qjscalc.js\nendif\nifdef CONFIG_M32\n\t./qjs32 tests/test_closure.js\n\t./qjs32 tests/test_language.js\n\t./qjs32 tests/test_builtin.js\n\t./qjs32 tests/test_loop.js\n\t./qjs32 tests/test_std.js\n\t./qjs32 tests/test_worker.js\nifdef CONFIG_BIGNUM\n\t./qjs32 --bignum tests/test_op_overloading.js\n\t./qjs32 --bignum tests/test_bignum.js\n\t./qjs32 --qjscalc tests/test_qjscalc.js\nendif\nendif\n\nstats: qjs qjs32\n\t./qjs -qd\n\t./qjs32 -qd\n\nmicrobench: qjs\n\t./qjs tests/microbench.js\n\nmicrobench-32: qjs32\n\t./qjs32 tests/microbench.js\n\n# ES5 tests (obsolete)\ntest2o: run-test262\n\ttime ./run-test262 -m -c test262o.conf\n\ntest2o-32: run-test262-32\n\ttime ./run-test262-32 -m -c test262o.conf\n\ntest2o-update: run-test262\n\t./run-test262 -u -c test262o.conf\n\n# Test262 tests\ntest2-default: run-test262\n\ttime ./run-test262 -m -c test262.conf\n\ntest2: run-test262\n\ttime ./run-test262 -m -c test262.conf -a\n\ntest2-32: run-test262-32\n\ttime ./run-test262-32 -m -c test262.conf -a\n\ntest2-update: run-test262\n\t./run-test262 -u -c test262.conf -a\n\ntest2-check: run-test262\n\ttime ./run-test262 -m -c test262.conf -E -a\n\ntestall: all test microbench test2o test2\n\ntestall-32: all test-32 microbench-32 test2o-32 test2-32\n\ntestall-complete: testall testall-32\n\nbench-v8: qjs\n\tmake -C tests/bench-v8\n\t./qjs -d tests/bench-v8/combined.js\n\ntests/bjson.so: $(OBJDIR)/tests/bjson.pic.o\n\t$(CC) $(LDFLAGS) -shared -o $@ $^ $(LIBS)\n\n-include $(wildcard $(OBJDIR)/*.d)\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/TODO",
    "content": "Bugs:\n- modules: better error handling with cyclic module references\n\nMisc ideas:\n- use custom printf to avoid compatibility issues with floating point numbers\n- consistent naming for preprocessor defines\n- unify coding style and naming conventions\n- use names from the ECMA spec in library implementation\n- use byte code emitters with typed arguments (for clarity)\n- use 2 bytecode DynBufs in JSFunctionDef, one for reading, one for writing\n  and use the same wrappers in all phases\n- use more generic method for line numbers in resolve_variables and resolve_labels\n- use custom timezone support to avoid C library compatibility issues\n\nMemory:\n- use memory pools for objects, etc?\n- test border cases for max number of atoms, object properties, string length\n- add emergency malloc mode for out of memory exceptions.\n- test all DynBuf memory errors\n- test all js_realloc memory errors\n- improve JS_ComputeMemoryUsage() with more info\n\nBuilt-in standard library:\n- BSD sockets\n- modules: use realpath in module name normalizer and put it in quickjs-libc\n- modules: if no \".\", use a well known module loading path ?\n- get rid of __loadScript, use more common name\n\nREPL:\n- debugger\n- readline: support MS Windows terminal\n- readline: handle dynamic terminal resizing\n- readline: handle double width unicode characters\n- multiline editing\n- runtime object and function inspectors\n- interactive object browser\n- use more generic approach to display evaluation results\n- improve directive handling: dispatch, colorize, completion...\n- save history\n- close all predefined methods in repl.js and jscalc.js\n\nOptimization ideas:\n- 64-bit atoms in 64-bit mode ?\n- 64-bit small bigint in 64-bit mode ?\n- reuse stack slots for disjoint scopes, if strip\n- add heuristic to avoid some cycles in closures\n- small String (0-2 charcodes) with immediate storage\n- perform static string concatenation at compile time\n- optimize string concatenation with ropes or miniropes?\n- add implicit numeric strings for Uint32 numbers?\n- optimize `s += a + b`, `s += a.b` and similar simple expressions\n- ensure string canonical representation and optimise comparisons and hashes?\n- remove JSObject.first_weak_ref, use bit+context based hashed array for weak references\n- property access optimization on the global object, functions,\n  prototypes and special non extensible objects.\n- create object literals with the correct length by backpatching length argument\n- remove redundant set_loc_uninitialized/check_uninitialized opcodes\n- peephole optim: push_atom_value, to_propkey -> push_atom_value\n- peephole optim: put_loc x, get_loc_check x -> set_loc x\n- convert slow array to fast array when all properties != length are numeric\n- optimize destructuring assignments for global and local variables\n- implement some form of tail-call-optimization\n- optimize OP_apply\n- optimize f(...b)\n\nTest262o:   0/11262 errors, 463 excluded\nTest262o commit: 7da91bceb9ce7613f87db47ddd1292a2dda58b42 (es5-tests branch)\n\nResult: 35/75280 errors, 909 excluded, 585 skipped\nTest262 commit: 31126581e7290f9233c29cefd93f66c6ac78f1c9\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/VERSION",
    "content": "2021-03-27\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/cutils.c",
    "content": "/*\n * C utilities\n * \n * Copyright (c) 2017 Fabrice Bellard\n * Copyright (c) 2018 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <string.h>\n\n#include \"cutils.h\"\n\nvoid pstrcpy(char *buf, int buf_size, const char *str)\n{\n    int c;\n    char *q = buf;\n\n    if (buf_size <= 0)\n        return;\n\n    for(;;) {\n        c = *str++;\n        if (c == 0 || q >= buf + buf_size - 1)\n            break;\n        *q++ = c;\n    }\n    *q = '\\0';\n}\n\n/* strcat and truncate. */\nchar *pstrcat(char *buf, int buf_size, const char *s)\n{\n    int len;\n    len = strlen(buf);\n    if (len < buf_size)\n        pstrcpy(buf + len, buf_size - len, s);\n    return buf;\n}\n\nint strstart(const char *str, const char *val, const char **ptr)\n{\n    const char *p, *q;\n    p = str;\n    q = val;\n    while (*q != '\\0') {\n        if (*p != *q)\n            return 0;\n        p++;\n        q++;\n    }\n    if (ptr)\n        *ptr = p;\n    return 1;\n}\n\nint has_suffix(const char *str, const char *suffix)\n{\n    size_t len = strlen(str);\n    size_t slen = strlen(suffix);\n    return (len >= slen && !memcmp(str + len - slen, suffix, slen));\n}\n\n/* Dynamic buffer package */\n\nstatic void *dbuf_default_realloc(void *opaque, void *ptr, size_t size)\n{\n    return realloc(ptr, size);\n}\n\nvoid dbuf_init2(DynBuf *s, void *opaque, DynBufReallocFunc *realloc_func)\n{\n    memset(s, 0, sizeof(*s));\n    if (!realloc_func)\n        realloc_func = dbuf_default_realloc;\n    s->opaque = opaque;\n    s->realloc_func = realloc_func;\n}\n\nvoid dbuf_init(DynBuf *s)\n{\n    dbuf_init2(s, NULL, NULL);\n}\n\n/* return < 0 if error */\nint dbuf_realloc(DynBuf *s, size_t new_size)\n{\n    size_t size;\n    uint8_t *new_buf;\n    if (new_size > s->allocated_size) {\n        if (s->error)\n            return -1;\n        size = s->allocated_size * 3 / 2;\n        if (size > new_size)\n            new_size = size;\n        new_buf = s->realloc_func(s->opaque, s->buf, new_size);\n        if (!new_buf) {\n            s->error = TRUE;\n            return -1;\n        }\n        s->buf = new_buf;\n        s->allocated_size = new_size;\n    }\n    return 0;\n}\n\nint dbuf_write(DynBuf *s, size_t offset, const uint8_t *data, size_t len)\n{\n    size_t end;\n    end = offset + len;\n    if (dbuf_realloc(s, end))\n        return -1;\n    memcpy(s->buf + offset, data, len);\n    if (end > s->size)\n        s->size = end;\n    return 0;\n}\n\nint dbuf_put(DynBuf *s, const uint8_t *data, size_t len)\n{\n    if (unlikely((s->size + len) > s->allocated_size)) {\n        if (dbuf_realloc(s, s->size + len))\n            return -1;\n    }\n    memcpy(s->buf + s->size, data, len);\n    s->size += len;\n    return 0;\n}\n\nint dbuf_put_self(DynBuf *s, size_t offset, size_t len)\n{\n    if (unlikely((s->size + len) > s->allocated_size)) {\n        if (dbuf_realloc(s, s->size + len))\n            return -1;\n    }\n    memcpy(s->buf + s->size, s->buf + offset, len);\n    s->size += len;\n    return 0;\n}\n\nint dbuf_putc(DynBuf *s, uint8_t c)\n{\n    return dbuf_put(s, &c, 1);\n}\n\nint dbuf_putstr(DynBuf *s, const char *str)\n{\n    return dbuf_put(s, (const uint8_t *)str, strlen(str));\n}\n\nint __attribute__((format(printf, 2, 3))) dbuf_printf(DynBuf *s,\n                                                      const char *fmt, ...)\n{\n    va_list ap;\n    char buf[128];\n    int len;\n    \n    va_start(ap, fmt);\n    len = vsnprintf(buf, sizeof(buf), fmt, ap);\n    va_end(ap);\n    if (len < sizeof(buf)) {\n        /* fast case */\n        return dbuf_put(s, (uint8_t *)buf, len);\n    } else {\n        if (dbuf_realloc(s, s->size + len + 1))\n            return -1;\n        va_start(ap, fmt);\n        vsnprintf((char *)(s->buf + s->size), s->allocated_size - s->size,\n                  fmt, ap);\n        va_end(ap);\n        s->size += len;\n    }\n    return 0;\n}\n\nvoid dbuf_free(DynBuf *s)\n{\n    /* we test s->buf as a fail safe to avoid crashing if dbuf_free()\n       is called twice */\n    if (s->buf) {\n        s->realloc_func(s->opaque, s->buf, 0);\n    }\n    memset(s, 0, sizeof(*s));\n}\n\n/* Note: at most 31 bits are encoded. At most UTF8_CHAR_LEN_MAX bytes\n   are output. */\nint unicode_to_utf8(uint8_t *buf, unsigned int c)\n{\n    uint8_t *q = buf;\n\n    if (c < 0x80) {\n        *q++ = c;\n    } else {\n        if (c < 0x800) {\n            *q++ = (c >> 6) | 0xc0;\n        } else {\n            if (c < 0x10000) {\n                *q++ = (c >> 12) | 0xe0;\n            } else {\n                if (c < 0x00200000) {\n                    *q++ = (c >> 18) | 0xf0;\n                } else {\n                    if (c < 0x04000000) {\n                        *q++ = (c >> 24) | 0xf8;\n                    } else if (c < 0x80000000) {\n                        *q++ = (c >> 30) | 0xfc;\n                        *q++ = ((c >> 24) & 0x3f) | 0x80;\n                    } else {\n                        return 0;\n                    }\n                    *q++ = ((c >> 18) & 0x3f) | 0x80;\n                }\n                *q++ = ((c >> 12) & 0x3f) | 0x80;\n            }\n            *q++ = ((c >> 6) & 0x3f) | 0x80;\n        }\n        *q++ = (c & 0x3f) | 0x80;\n    }\n    return q - buf;\n}\n\nstatic const unsigned int utf8_min_code[5] = {\n    0x80, 0x800, 0x10000, 0x00200000, 0x04000000,\n};\n\nstatic const unsigned char utf8_first_code_mask[5] = {\n    0x1f, 0xf, 0x7, 0x3, 0x1,\n};\n\n/* return -1 if error. *pp is not updated in this case. max_len must\n   be >= 1. The maximum length for a UTF8 byte sequence is 6 bytes. */\nint unicode_from_utf8(const uint8_t *p, int max_len, const uint8_t **pp)\n{\n    int l, c, b, i;\n\n    c = *p++;\n    if (c < 0x80) {\n        *pp = p;\n        return c;\n    }\n    switch(c) {\n    case 0xc0: case 0xc1: case 0xc2: case 0xc3:\n    case 0xc4: case 0xc5: case 0xc6: case 0xc7:\n    case 0xc8: case 0xc9: case 0xca: case 0xcb:\n    case 0xcc: case 0xcd: case 0xce: case 0xcf:\n    case 0xd0: case 0xd1: case 0xd2: case 0xd3:\n    case 0xd4: case 0xd5: case 0xd6: case 0xd7:\n    case 0xd8: case 0xd9: case 0xda: case 0xdb:\n    case 0xdc: case 0xdd: case 0xde: case 0xdf:\n        l = 1;\n        break;\n    case 0xe0: case 0xe1: case 0xe2: case 0xe3:\n    case 0xe4: case 0xe5: case 0xe6: case 0xe7:\n    case 0xe8: case 0xe9: case 0xea: case 0xeb:\n    case 0xec: case 0xed: case 0xee: case 0xef:\n        l = 2;\n        break;\n    case 0xf0: case 0xf1: case 0xf2: case 0xf3:\n    case 0xf4: case 0xf5: case 0xf6: case 0xf7:\n        l = 3;\n        break;\n    case 0xf8: case 0xf9: case 0xfa: case 0xfb:\n        l = 4;\n        break;\n    case 0xfc: case 0xfd:\n        l = 5;\n        break;\n    default:\n        return -1;\n    }\n    /* check that we have enough characters */\n    if (l > (max_len - 1))\n        return -1;\n    c &= utf8_first_code_mask[l - 1];\n    for(i = 0; i < l; i++) {\n        b = *p++;\n        if (b < 0x80 || b >= 0xc0)\n            return -1;\n        c = (c << 6) | (b & 0x3f);\n    }\n    if (c < utf8_min_code[l - 1])\n        return -1;\n    *pp = p;\n    return c;\n}\n\n#if 0\n\n#if defined(EMSCRIPTEN) || defined(__ANDROID__)\n\nstatic void *rqsort_arg;\nstatic int (*rqsort_cmp)(const void *, const void *, void *);\n\nstatic int rqsort_cmp2(const void *p1, const void *p2)\n{\n    return rqsort_cmp(p1, p2, rqsort_arg);\n}\n\n/* not reentrant, but not needed with emscripten */\nvoid rqsort(void *base, size_t nmemb, size_t size,\n            int (*cmp)(const void *, const void *, void *),\n            void *arg)\n{\n    rqsort_arg = arg;\n    rqsort_cmp = cmp;\n    qsort(base, nmemb, size, rqsort_cmp2);\n}\n\n#endif\n\n#else\n\ntypedef void (*exchange_f)(void *a, void *b, size_t size);\ntypedef int (*cmp_f)(const void *, const void *, void *opaque);\n\nstatic void exchange_bytes(void *a, void *b, size_t size) {\n    uint8_t *ap = (uint8_t *)a;\n    uint8_t *bp = (uint8_t *)b;\n\n    while (size-- != 0) {\n        uint8_t t = *ap;\n        *ap++ = *bp;\n        *bp++ = t;\n    }\n}\n\nstatic void exchange_one_byte(void *a, void *b, size_t size) {\n    uint8_t *ap = (uint8_t *)a;\n    uint8_t *bp = (uint8_t *)b;\n    uint8_t t = *ap;\n    *ap = *bp;\n    *bp = t;\n}\n\nstatic void exchange_int16s(void *a, void *b, size_t size) {\n    uint16_t *ap = (uint16_t *)a;\n    uint16_t *bp = (uint16_t *)b;\n\n    for (size /= sizeof(uint16_t); size-- != 0;) {\n        uint16_t t = *ap;\n        *ap++ = *bp;\n        *bp++ = t;\n    }\n}\n\nstatic void exchange_one_int16(void *a, void *b, size_t size) {\n    uint16_t *ap = (uint16_t *)a;\n    uint16_t *bp = (uint16_t *)b;\n    uint16_t t = *ap;\n    *ap = *bp;\n    *bp = t;\n}\n\nstatic void exchange_int32s(void *a, void *b, size_t size) {\n    uint32_t *ap = (uint32_t *)a;\n    uint32_t *bp = (uint32_t *)b;\n\n    for (size /= sizeof(uint32_t); size-- != 0;) {\n        uint32_t t = *ap;\n        *ap++ = *bp;\n        *bp++ = t;\n    }\n}\n\nstatic void exchange_one_int32(void *a, void *b, size_t size) {\n    uint32_t *ap = (uint32_t *)a;\n    uint32_t *bp = (uint32_t *)b;\n    uint32_t t = *ap;\n    *ap = *bp;\n    *bp = t;\n}\n\nstatic void exchange_int64s(void *a, void *b, size_t size) {\n    uint64_t *ap = (uint64_t *)a;\n    uint64_t *bp = (uint64_t *)b;\n\n    for (size /= sizeof(uint64_t); size-- != 0;) {\n        uint64_t t = *ap;\n        *ap++ = *bp;\n        *bp++ = t;\n    }\n}\n\nstatic void exchange_one_int64(void *a, void *b, size_t size) {\n    uint64_t *ap = (uint64_t *)a;\n    uint64_t *bp = (uint64_t *)b;\n    uint64_t t = *ap;\n    *ap = *bp;\n    *bp = t;\n}\n\nstatic void exchange_int128s(void *a, void *b, size_t size) {\n    uint64_t *ap = (uint64_t *)a;\n    uint64_t *bp = (uint64_t *)b;\n\n    for (size /= sizeof(uint64_t) * 2; size-- != 0; ap += 2, bp += 2) {\n        uint64_t t = ap[0];\n        uint64_t u = ap[1];\n        ap[0] = bp[0];\n        ap[1] = bp[1];\n        bp[0] = t;\n        bp[1] = u;\n    }\n}\n\nstatic void exchange_one_int128(void *a, void *b, size_t size) {\n    uint64_t *ap = (uint64_t *)a;\n    uint64_t *bp = (uint64_t *)b;\n    uint64_t t = ap[0];\n    uint64_t u = ap[1];\n    ap[0] = bp[0];\n    ap[1] = bp[1];\n    bp[0] = t;\n    bp[1] = u;\n}\n\nstatic inline exchange_f exchange_func(const void *base, size_t size) {\n    switch (((uintptr_t)base | (uintptr_t)size) & 15) {\n    case 0:\n        if (size == sizeof(uint64_t) * 2)\n            return exchange_one_int128;\n        else\n            return exchange_int128s;\n    case 8:\n        if (size == sizeof(uint64_t))\n            return exchange_one_int64;\n        else\n            return exchange_int64s;\n    case 4:\n    case 12:\n        if (size == sizeof(uint32_t))\n            return exchange_one_int32;\n        else\n            return exchange_int32s;\n    case 2:\n    case 6:\n    case 10:\n    case 14:\n        if (size == sizeof(uint16_t))\n            return exchange_one_int16;\n        else\n            return exchange_int16s;\n    default:\n        if (size == 1)\n            return exchange_one_byte;\n        else\n            return exchange_bytes;\n    }\n}\n\nstatic void heapsortx(void *base, size_t nmemb, size_t size, cmp_f cmp, void *opaque)\n{\n    uint8_t *basep = (uint8_t *)base;\n    size_t i, n, c, r;\n    exchange_f swap = exchange_func(base, size);\n\n    if (nmemb > 1) {\n        i = (nmemb / 2) * size;\n        n = nmemb * size;\n\n        while (i > 0) {\n            i -= size;\n            for (r = i; (c = r * 2 + size) < n; r = c) {\n                if (c < n - size && cmp(basep + c, basep + c + size, opaque) <= 0)\n                    c += size;\n                if (cmp(basep + r, basep + c, opaque) > 0)\n                    break;\n                swap(basep + r, basep + c, size);\n            }\n        }\n        for (i = n - size; i > 0; i -= size) {\n            swap(basep, basep + i, size);\n\n            for (r = 0; (c = r * 2 + size) < i; r = c) {\n                if (c < i - size && cmp(basep + c, basep + c + size, opaque) <= 0)\n                    c += size;\n                if (cmp(basep + r, basep + c, opaque) > 0)\n                    break;\n                swap(basep + r, basep + c, size);\n            }\n        }\n    }\n}\n\nstatic inline void *med3(void *a, void *b, void *c, cmp_f cmp, void *opaque)\n{\n    return cmp(a, b, opaque) < 0 ?\n        (cmp(b, c, opaque) < 0 ? b : (cmp(a, c, opaque) < 0 ? c : a )) :\n        (cmp(b, c, opaque) > 0 ? b : (cmp(a, c, opaque) < 0 ? a : c ));\n}\n\n/* pointer based version with local stack and insertion sort threshhold */\nvoid rqsort(void *base, size_t nmemb, size_t size, cmp_f cmp, void *opaque)\n{\n    struct { uint8_t *base; size_t count; int depth; } stack[50], *sp = stack;\n    uint8_t *ptr, *pi, *pj, *plt, *pgt, *top, *m;\n    size_t m4, i, lt, gt, span, span2;\n    int c, depth;\n    exchange_f swap = exchange_func(base, size);\n    exchange_f swap_block = exchange_func(base, size | 128);\n\n    if (nmemb < 2 || size <= 0)\n        return;\n\n    sp->base = (uint8_t *)base;\n    sp->count = nmemb;\n    sp->depth = 0;\n    sp++;\n\n    while (sp > stack) {\n        sp--;\n        ptr = sp->base;\n        nmemb = sp->count;\n        depth = sp->depth;\n\n        while (nmemb > 6) {\n            if (++depth > 50) {\n                /* depth check to ensure worst case logarithmic time */\n                heapsortx(ptr, nmemb, size, cmp, opaque);\n                nmemb = 0;\n                break;\n            }\n            /* select median of 3 from 1/4, 1/2, 3/4 positions */\n            /* should use median of 5 or 9? */\n            m4 = (nmemb >> 2) * size;\n            m = med3(ptr + m4, ptr + 2 * m4, ptr + 3 * m4, cmp, opaque);\n            swap(ptr, m, size);  /* move the pivot to the start or the array */\n            i = lt = 1;\n            pi = plt = ptr + size;\n            gt = nmemb;\n            pj = pgt = top = ptr + nmemb * size;\n            for (;;) {\n                while (pi < pj && (c = cmp(ptr, pi, opaque)) >= 0) {\n                    if (c == 0) {\n                        swap(plt, pi, size);\n                        lt++;\n                        plt += size;\n                    }\n                    i++;\n                    pi += size;\n                }\n                while (pi < (pj -= size) && (c = cmp(ptr, pj, opaque)) <= 0) {\n                    if (c == 0) {\n                        gt--;\n                        pgt -= size;\n                        swap(pgt, pj, size);\n                    }\n                }\n                if (pi >= pj)\n                    break;\n                swap(pi, pj, size);\n                i++;\n                pi += size;\n            }\n            /* array has 4 parts:\n             * from 0 to lt excluded: elements identical to pivot\n             * from lt to pi excluded: elements smaller than pivot\n             * from pi to gt excluded: elements greater than pivot\n             * from gt to n excluded: elements identical to pivot\n             */\n            /* move elements identical to pivot in the middle of the array: */\n            /* swap values in ranges [0..lt[ and [i-lt..i[\n               swapping the smallest span between lt and i-lt is sufficient\n             */\n            span = plt - ptr;\n            span2 = pi - plt;\n            lt = i - lt;\n            if (span > span2)\n                span = span2;\n            swap_block(ptr, pi - span, span);\n            /* swap values in ranges [gt..top[ and [i..top-(top-gt)[\n               swapping the smallest span between top-gt and gt-i is sufficient\n             */\n            span = top - pgt;\n            span2 = pgt - pi;\n            pgt = top - span2;\n            gt = nmemb - (gt - i);\n            if (span > span2)\n                span = span2;\n            swap_block(pi, top - span, span);\n\n            /* now array has 3 parts:\n             * from 0 to lt excluded: elements smaller than pivot\n             * from lt to gt excluded: elements identical to pivot\n             * from gt to n excluded: elements greater than pivot\n             */\n            /* stack the larger segment and keep processing the smaller one\n               to minimize stack use for pathological distributions */\n            if (lt > nmemb - gt) {\n                sp->base = ptr;\n                sp->count = lt;\n                sp->depth = depth;\n                sp++;\n                ptr = pgt;\n                nmemb -= gt;\n            } else {\n                sp->base = pgt;\n                sp->count = nmemb - gt;\n                sp->depth = depth;\n                sp++;\n                nmemb = lt;\n            }\n        }\n        /* Use insertion sort for small fragments */\n        for (pi = ptr + size, top = ptr + nmemb * size; pi < top; pi += size) {\n            for (pj = pi; pj > ptr && cmp(pj - size, pj, opaque) > 0; pj -= size)\n                swap(pj, pj - size, size);\n        }\n    }\n}\n\n#endif\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/cutils.h",
    "content": "/*\n * C utilities\n * \n * Copyright (c) 2017 Fabrice Bellard\n * Copyright (c) 2018 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#ifndef CUTILS_H\n#define CUTILS_H\n\n#include <stdlib.h>\n#include <inttypes.h>\n\n/* set if CPU is big endian */\n#undef WORDS_BIGENDIAN\n\n#define likely(x)       __builtin_expect(!!(x), 1)\n#define unlikely(x)     __builtin_expect(!!(x), 0)\n#define force_inline inline __attribute__((always_inline))\n#define no_inline __attribute__((noinline))\n#define __maybe_unused __attribute__((unused))\n\n#define xglue(x, y) x ## y\n#define glue(x, y) xglue(x, y)\n#define stringify(s)    tostring(s)\n#define tostring(s)     #s\n\n#ifndef offsetof\n#define offsetof(type, field) ((size_t) &((type *)0)->field)\n#endif\n#ifndef countof\n#define countof(x) (sizeof(x) / sizeof((x)[0]))\n#endif\n\ntypedef int BOOL;\n\n#ifndef FALSE\nenum {\n    FALSE = 0,\n    TRUE = 1,\n};\n#endif\n\nvoid pstrcpy(char *buf, int buf_size, const char *str);\nchar *pstrcat(char *buf, int buf_size, const char *s);\nint strstart(const char *str, const char *val, const char **ptr);\nint has_suffix(const char *str, const char *suffix);\n\nstatic inline int max_int(int a, int b)\n{\n    if (a > b)\n        return a;\n    else\n        return b;\n}\n\nstatic inline int min_int(int a, int b)\n{\n    if (a < b)\n        return a;\n    else\n        return b;\n}\n\nstatic inline uint32_t max_uint32(uint32_t a, uint32_t b)\n{\n    if (a > b)\n        return a;\n    else\n        return b;\n}\n\nstatic inline uint32_t min_uint32(uint32_t a, uint32_t b)\n{\n    if (a < b)\n        return a;\n    else\n        return b;\n}\n\nstatic inline int64_t max_int64(int64_t a, int64_t b)\n{\n    if (a > b)\n        return a;\n    else\n        return b;\n}\n\nstatic inline int64_t min_int64(int64_t a, int64_t b)\n{\n    if (a < b)\n        return a;\n    else\n        return b;\n}\n\n/* WARNING: undefined if a = 0 */\nstatic inline int clz32(unsigned int a)\n{\n    return __builtin_clz(a);\n}\n\n/* WARNING: undefined if a = 0 */\nstatic inline int clz64(uint64_t a)\n{\n    return __builtin_clzll(a);\n}\n\n/* WARNING: undefined if a = 0 */\nstatic inline int ctz32(unsigned int a)\n{\n    return __builtin_ctz(a);\n}\n\n/* WARNING: undefined if a = 0 */\nstatic inline int ctz64(uint64_t a)\n{\n    return __builtin_ctzll(a);\n}\n\nstruct __attribute__((packed)) packed_u64 {\n    uint64_t v;\n};\n\nstruct __attribute__((packed)) packed_u32 {\n    uint32_t v;\n};\n\nstruct __attribute__((packed)) packed_u16 {\n    uint16_t v;\n};\n\nstatic inline uint64_t get_u64(const uint8_t *tab)\n{\n    return ((const struct packed_u64 *)tab)->v;\n}\n\nstatic inline int64_t get_i64(const uint8_t *tab)\n{\n    return (int64_t)((const struct packed_u64 *)tab)->v;\n}\n\nstatic inline void put_u64(uint8_t *tab, uint64_t val)\n{\n    ((struct packed_u64 *)tab)->v = val;\n}\n\nstatic inline uint32_t get_u32(const uint8_t *tab)\n{\n    return ((const struct packed_u32 *)tab)->v;\n}\n\nstatic inline int32_t get_i32(const uint8_t *tab)\n{\n    return (int32_t)((const struct packed_u32 *)tab)->v;\n}\n\nstatic inline void put_u32(uint8_t *tab, uint32_t val)\n{\n    ((struct packed_u32 *)tab)->v = val;\n}\n\nstatic inline uint32_t get_u16(const uint8_t *tab)\n{\n    return ((const struct packed_u16 *)tab)->v;\n}\n\nstatic inline int32_t get_i16(const uint8_t *tab)\n{\n    return (int16_t)((const struct packed_u16 *)tab)->v;\n}\n\nstatic inline void put_u16(uint8_t *tab, uint16_t val)\n{\n    ((struct packed_u16 *)tab)->v = val;\n}\n\nstatic inline uint32_t get_u8(const uint8_t *tab)\n{\n    return *tab;\n}\n\nstatic inline int32_t get_i8(const uint8_t *tab)\n{\n    return (int8_t)*tab;\n}\n\nstatic inline void put_u8(uint8_t *tab, uint8_t val)\n{\n    *tab = val;\n}\n\nstatic inline uint16_t bswap16(uint16_t x)\n{\n    return (x >> 8) | (x << 8);\n}\n\nstatic inline uint32_t bswap32(uint32_t v)\n{\n    return ((v & 0xff000000) >> 24) | ((v & 0x00ff0000) >>  8) |\n        ((v & 0x0000ff00) <<  8) | ((v & 0x000000ff) << 24);\n}\n\nstatic inline uint64_t bswap64(uint64_t v)\n{\n    return ((v & ((uint64_t)0xff << (7 * 8))) >> (7 * 8)) | \n        ((v & ((uint64_t)0xff << (6 * 8))) >> (5 * 8)) | \n        ((v & ((uint64_t)0xff << (5 * 8))) >> (3 * 8)) | \n        ((v & ((uint64_t)0xff << (4 * 8))) >> (1 * 8)) | \n        ((v & ((uint64_t)0xff << (3 * 8))) << (1 * 8)) | \n        ((v & ((uint64_t)0xff << (2 * 8))) << (3 * 8)) | \n        ((v & ((uint64_t)0xff << (1 * 8))) << (5 * 8)) | \n        ((v & ((uint64_t)0xff << (0 * 8))) << (7 * 8));\n}\n\n/* XXX: should take an extra argument to pass slack information to the caller */\ntypedef void *DynBufReallocFunc(void *opaque, void *ptr, size_t size);\n\ntypedef struct DynBuf {\n    uint8_t *buf;\n    size_t size;\n    size_t allocated_size;\n    BOOL error; /* true if a memory allocation error occurred */\n    DynBufReallocFunc *realloc_func;\n    void *opaque; /* for realloc_func */\n} DynBuf;\n\nvoid dbuf_init(DynBuf *s);\nvoid dbuf_init2(DynBuf *s, void *opaque, DynBufReallocFunc *realloc_func);\nint dbuf_realloc(DynBuf *s, size_t new_size);\nint dbuf_write(DynBuf *s, size_t offset, const uint8_t *data, size_t len);\nint dbuf_put(DynBuf *s, const uint8_t *data, size_t len);\nint dbuf_put_self(DynBuf *s, size_t offset, size_t len);\nint dbuf_putc(DynBuf *s, uint8_t c);\nint dbuf_putstr(DynBuf *s, const char *str);\nstatic inline int dbuf_put_u16(DynBuf *s, uint16_t val)\n{\n    return dbuf_put(s, (uint8_t *)&val, 2);\n}\nstatic inline int dbuf_put_u32(DynBuf *s, uint32_t val)\n{\n    return dbuf_put(s, (uint8_t *)&val, 4);\n}\nstatic inline int dbuf_put_u64(DynBuf *s, uint64_t val)\n{\n    return dbuf_put(s, (uint8_t *)&val, 8);\n}\nint __attribute__((format(printf, 2, 3))) dbuf_printf(DynBuf *s,\n                                                      const char *fmt, ...);\nvoid dbuf_free(DynBuf *s);\nstatic inline BOOL dbuf_error(DynBuf *s) {\n    return s->error;\n}\nstatic inline void dbuf_set_error(DynBuf *s)\n{\n    s->error = TRUE;\n}\n\n#define UTF8_CHAR_LEN_MAX 6\n\nint unicode_to_utf8(uint8_t *buf, unsigned int c);\nint unicode_from_utf8(const uint8_t *p, int max_len, const uint8_t **pp);\n\nstatic inline int from_hex(int c)\n{\n    if (c >= '0' && c <= '9')\n        return c - '0';\n    else if (c >= 'A' && c <= 'F')\n        return c - 'A' + 10;\n    else if (c >= 'a' && c <= 'f')\n        return c - 'a' + 10;\n    else\n        return -1;\n}\n\nvoid rqsort(void *base, size_t nmemb, size_t size,\n            int (*cmp)(const void *, const void *, void *),\n            void *arg);\n\n#endif  /* CUTILS_H */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/doc/jsbignum.html",
    "content": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n<!-- Created by GNU Texinfo 6.1, http://www.gnu.org/software/texinfo/ -->\n<head>\n<title>Javascript Bignum Extensions</title>\n\n<meta name=\"description\" content=\"Javascript Bignum Extensions\">\n<meta name=\"keywords\" content=\"Javascript Bignum Extensions\">\n<meta name=\"resource-type\" content=\"document\">\n<meta name=\"distribution\" content=\"global\">\n<meta name=\"Generator\" content=\"makeinfo\">\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<link href=\"#SEC_Contents\" rel=\"contents\" title=\"Table of Contents\">\n<style type=\"text/css\">\n<!--\na.summary-letter {text-decoration: none}\nblockquote.indentedblock {margin-right: 0em}\nblockquote.smallindentedblock {margin-right: 0em; font-size: smaller}\nblockquote.smallquotation {font-size: smaller}\ndiv.display {margin-left: 3.2em}\ndiv.example {margin-left: 3.2em}\ndiv.lisp {margin-left: 3.2em}\ndiv.smalldisplay {margin-left: 3.2em}\ndiv.smallexample {margin-left: 3.2em}\ndiv.smalllisp {margin-left: 3.2em}\nkbd {font-style: oblique}\npre.display {font-family: inherit}\npre.format {font-family: inherit}\npre.menu-comment {font-family: serif}\npre.menu-preformatted {font-family: serif}\npre.smalldisplay {font-family: inherit; font-size: smaller}\npre.smallexample {font-size: smaller}\npre.smallformat {font-family: inherit; font-size: smaller}\npre.smalllisp {font-size: smaller}\nspan.nolinebreak {white-space: nowrap}\nspan.roman {font-family: initial; font-weight: normal}\nspan.sansserif {font-family: sans-serif; font-weight: normal}\nul.no-bullet {list-style: none}\n-->\n</style>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n\n\n</head>\n\n<body lang=\"en\">\n<h1 class=\"settitle\" align=\"center\">Javascript Bignum Extensions</h1>\n\n<a name=\"SEC_Contents\"></a>\n<h2 class=\"contents-heading\">Table of Contents</h2>\n\n<div class=\"contents\">\n<ul class=\"no-bullet\">\n<li><a name=\"toc-Introduction\" href=\"#Introduction\">1 Introduction</a></li>\n<li><a name=\"toc-Operator-overloading\" href=\"#Operator-overloading\">2 Operator overloading</a></li>\n<li><a name=\"toc-BigInt-extensions\" href=\"#BigInt-extensions\">3 BigInt extensions</a></li>\n<li><a name=\"toc-BigFloat\" href=\"#BigFloat\">4 BigFloat</a>\n<ul class=\"no-bullet\">\n  <li><a name=\"toc-Introduction-1\" href=\"#Introduction-1\">4.1 Introduction</a></li>\n  <li><a name=\"toc-Floating-point-rounding\" href=\"#Floating-point-rounding\">4.2 Floating point rounding</a></li>\n  <li><a name=\"toc-Operators\" href=\"#Operators\">4.3 Operators</a></li>\n  <li><a name=\"toc-BigFloat-literals\" href=\"#BigFloat-literals\">4.4 BigFloat literals</a></li>\n  <li><a name=\"toc-Builtin-Object-changes\" href=\"#Builtin-Object-changes\">4.5 Builtin Object changes</a>\n  <ul class=\"no-bullet\">\n    <li><a name=\"toc-BigFloat-function\" href=\"#BigFloat-function\">4.5.1 <code>BigFloat</code> function</a></li>\n    <li><a name=\"toc-BigFloat_002eprototype\" href=\"#BigFloat_002eprototype\">4.5.2 <code>BigFloat.prototype</code></a></li>\n    <li><a name=\"toc-BigFloatEnv-constructor\" href=\"#BigFloatEnv-constructor\">4.5.3 <code>BigFloatEnv</code> constructor</a></li>\n  </ul></li>\n</ul></li>\n<li><a name=\"toc-BigDecimal\" href=\"#BigDecimal\">5 BigDecimal</a>\n<ul class=\"no-bullet\">\n  <li><a name=\"toc-Operators-1\" href=\"#Operators-1\">5.1 Operators</a></li>\n  <li><a name=\"toc-BigDecimal-literals\" href=\"#BigDecimal-literals\">5.2 BigDecimal literals</a></li>\n  <li><a name=\"toc-Builtin-Object-changes-1\" href=\"#Builtin-Object-changes-1\">5.3 Builtin Object changes</a>\n  <ul class=\"no-bullet\">\n    <li><a name=\"toc-The-BigDecimal-function_002e\" href=\"#The-BigDecimal-function_002e\">5.3.1 The <code>BigDecimal</code> function.</a></li>\n    <li><a name=\"toc-Properties-of-the-BigDecimal-object\" href=\"#Properties-of-the-BigDecimal-object\">5.3.2 Properties of the <code>BigDecimal</code> object</a></li>\n    <li><a name=\"toc-Properties-of-the-BigDecimal_002eprototype-object\" href=\"#Properties-of-the-BigDecimal_002eprototype-object\">5.3.3 Properties of the <code>BigDecimal.prototype</code> object</a></li>\n  </ul></li>\n</ul></li>\n<li><a name=\"toc-Math-mode\" href=\"#Math-mode\">6 Math mode</a></li>\n\n</ul>\n</div>\n\n\n<a name=\"Introduction\"></a>\n<h2 class=\"chapter\">1 Introduction</h2>\n\n<p>The Bignum extensions add the following features to the Javascript\nlanguage while being 100% backward compatible:\n</p>\n<ul>\n<li> Operator overloading with a dispatch logic inspired from the proposal available at <a href=\"https://github.com/tc39/proposal-operator-overloading/\">https://github.com/tc39/proposal-operator-overloading/</a>.\n\n</li><li> Arbitrarily large floating point numbers (<code>BigFloat</code>) in base 2 using the IEEE 754 semantics.\n\n</li><li> Arbitrarily large floating point numbers (<code>BigDecimal</code>) in base 10 based on the proposal available at\n<a href=\"https://github.com/littledan/proposal-bigdecimal\">https://github.com/littledan/proposal-bigdecimal</a>.\n\n</li><li> <code>math</code> mode: arbitrarily large integers and floating point numbers are available by default. The integer division and power can be overloaded for example to return a fraction. The modulo operator (<code>%</code>) is defined as the Euclidian\nremainder. <code>^</code> is an alias to the power operator\n(<code>**</code>). <code>^^</code> is used as the exclusive or operator.\n\n</li></ul>\n\n<p>The extensions are independent from each other except the <code>math</code>\nmode which relies on BigFloat and operator overloading.\n</p>\n<a name=\"Operator-overloading\"></a>\n<h2 class=\"chapter\">2 Operator overloading</h2>\n\n<p>Operator overloading is inspired from the proposal available at\n<a href=\"https://github.com/tc39/proposal-operator-overloading/\">https://github.com/tc39/proposal-operator-overloading/</a>. It\nimplements the same dispatch logic but finds the operator sets by\nlooking at the <code>Symbol.operatorSet</code> property in the objects. The\nchanges were done in order to simplify the implementation.\n</p>\n<p>More precisely, the following modifications were made:\n</p>\n<ul>\n<li> <code>with operators from</code> is not supported. Operator overloading is always enabled.\n\n</li><li> The dispatch is not based on a static <code>[[OperatorSet]]</code> field in all instances. Instead, a dynamic lookup of the <code>Symbol.operatorSet</code> property is done. This property is typically added in the prototype of each object.\n\n</li><li> <code>Operators.create(...dictionaries)</code> is used to create a new OperatorSet object. The <code>Operators</code> function is supported as an helper to be closer to the TC39 proposal.\n\n</li><li> <code>[]</code> cannot be overloaded.\n\n</li><li> In math mode, the BigInt division and power operators can be overloaded with <code>Operators.updateBigIntOperators(dictionary)</code>.\n\n</li></ul>\n\n<a name=\"BigInt-extensions\"></a>\n<h2 class=\"chapter\">3 BigInt extensions</h2>\n\n<p>A few properties are added to the BigInt object:\n</p>\n<dl compact=\"compact\">\n<dt><code>tdiv(a, b)</code></dt>\n<dd><p>Return <em>trunc(a/b)</em>. <code>b = 0</code> raises a RangeError\nexception.\n</p>\n</dd>\n<dt><code>fdiv(a, b)</code></dt>\n<dd><p>Return <em>\\lfloor a/b \\rfloor</em>. <code>b = 0</code> raises a RangeError\nexception.\n</p>\n</dd>\n<dt><code>cdiv(a, b)</code></dt>\n<dd><p>Return <em>\\lceil a/b \\rceil</em>. <code>b = 0</code> raises a RangeError\nexception.\n</p>\n</dd>\n<dt><code>ediv(a, b)</code></dt>\n<dd><p>Return <em>sgn(b) \\lfloor a/{|b|} \\rfloor</em> (Euclidian\ndivision). <code>b = 0</code> raises a RangeError exception.\n</p>\n</dd>\n<dt><code>tdivrem(a, b)</code></dt>\n<dt><code>fdivrem(a, b)</code></dt>\n<dt><code>cdivrem(a, b)</code></dt>\n<dt><code>edivrem(a, b)</code></dt>\n<dd><p>Return an array of two elements. The first element is the quotient,\nthe second is the remainder. The same rounding is done as the\ncorresponding division operation.\n</p>\n</dd>\n<dt><code>sqrt(a)</code></dt>\n<dd><p>Return <em>\\lfloor \\sqrt(a) \\rfloor</em>. A RangeError exception is\nraised if <em>a &lt; 0</em>.\n</p>\n</dd>\n<dt><code>sqrtrem(a)</code></dt>\n<dd><p>Return an array of two elements. The first element is <em>\\lfloor\n\\sqrt{a} \\rfloor</em>. The second element is <em>a-\\lfloor \\sqrt{a}\n\\rfloor^2</em>. A RangeError exception is raised if <em>a &lt; 0</em>.\n</p>\n</dd>\n<dt><code>floorLog2(a)</code></dt>\n<dd><p>Return -1 if <em>a \\leq 0</em> otherwise return <em>\\lfloor \\log2(a) \\rfloor</em>.\n</p>\n</dd>\n<dt><code>ctz(a)</code></dt>\n<dd><p>Return the number of trailing zeros in the two&rsquo;s complement binary representation of a. Return -1 if <em>a=0</em>.\n</p>\n</dd>\n</dl>\n\n<a name=\"BigFloat\"></a>\n<h2 class=\"chapter\">4 BigFloat</h2>\n\n<a name=\"Introduction-1\"></a>\n<h3 class=\"section\">4.1 Introduction</h3>\n\n<p>This extension adds the <code>BigFloat</code> primitive type. The\n<code>BigFloat</code> type represents floating point numbers in base 2\nwith the IEEE 754 semantics. A floating\npoint number is represented as a sign, mantissa and exponent. The\nspecial values <code>NaN</code>, <code>+/-Infinity</code>, <code>+0</code> and <code>-0</code>\nare supported. The mantissa and exponent can have any bit length with\nan implementation specific minimum and maximum.\n</p>\n<a name=\"Floating-point-rounding\"></a>\n<h3 class=\"section\">4.2 Floating point rounding</h3>\n\n<p>Each floating point operation operates with infinite precision and\nthen rounds the result according to the specified floating point\nenvironment (<code>BigFloatEnv</code> object). The status flags of the\nenvironment are also set according to the result of the operation.\n</p>\n<p>If no floating point environment is provided, the global floating\npoint environment is used.\n</p>\n<p>The rounding mode of the global floating point environment is always\n<code>RNDN</code> (&ldquo;round to nearest with ties to even&rdquo;)<a name=\"DOCF1\" href=\"#FOOT1\"><sup>1</sup></a>. The status flags of the global environment cannot be\nread<a name=\"DOCF2\" href=\"#FOOT2\"><sup>2</sup></a>. The precision of the global environment is\n<code>BigFloatEnv.prec</code>. The number of exponent bits of the global\nenvironment is <code>BigFloatEnv.expBits</code>. The global environment\nsubnormal flag is set to <code>true</code>.\n</p>\n<p>For example, <code>prec = 53</code> and <code> expBits = 11</code> exactly give\nthe same precision as the IEEE 754 64 bit floating point format. The\ndefault precision is <code>prec = 113</code> and <code> expBits = 15</code> (IEEE\n754 128 bit floating point format).\n</p>\n<p>The global floating point environment can only be modified temporarily\nwhen calling a function (see <code>BigFloatEnv.setPrec</code>). Hence a\nfunction can change the global floating point environment for its\ncallees but not for its caller.\n</p>\n<a name=\"Operators\"></a>\n<h3 class=\"section\">4.3 Operators</h3>\n\n<p>The builtin operators are extended so that a BigFloat is returned if\nat least one operand is a BigFloat. The computations are always done\nwith infinite precision and rounded according to the global floating\npoint environment.\n</p>\n<p><code>typeof</code> applied on a <code>BigFloat</code> returns <code>bigfloat</code>.\n</p>\n<p>BigFloat can be compared with all the other numeric types and the\nresult follows the expected mathematical relations.\n</p>\n<p>However, since BigFloat and Number are different types they are never\nequal when using the strict comparison operators (e.g. <code>0.0 ===\n0.0l</code> is false).\n</p>\n<a name=\"BigFloat-literals\"></a>\n<h3 class=\"section\">4.4 BigFloat literals</h3>\n\n<p>BigFloat literals are floating point numbers with a trailing <code>l</code>\nsuffix. BigFloat literals have an infinite precision. They are rounded\naccording to the global floating point environment when they are\nevaluated.<a name=\"DOCF3\" href=\"#FOOT3\"><sup>3</sup></a>\n</p>\n<a name=\"Builtin-Object-changes\"></a>\n<h3 class=\"section\">4.5 Builtin Object changes</h3>\n\n<a name=\"BigFloat-function\"></a>\n<h4 class=\"subsection\">4.5.1 <code>BigFloat</code> function</h4>\n\n<p>The <code>BigFloat</code> function cannot be invoked as a constructor. When\ninvoked as a function: the parameter is converted to a primitive\ntype. If the result is a numeric type, it is converted to BigFloat\nwithout rounding. If the result is a string, it is converted to\nBigFloat using the precision of the global floating point environment.\n</p>\n<p><code>BigFloat</code> properties:\n</p>\n<dl compact=\"compact\">\n<dt><code>LN2</code></dt>\n<dt><code>PI</code></dt>\n<dd><p>Getter. Return the value of the corresponding mathematical constant\nrounded to nearest, ties to even with the current global\nprecision. The constant values are cached for small precisions.\n</p>\n</dd>\n<dt><code>MIN_VALUE</code></dt>\n<dt><code>MAX_VALUE</code></dt>\n<dt><code>EPSILON</code></dt>\n<dd><p>Getter. Return the minimum, maximum and epsilon <code>BigFloat</code> values\n(same definition as the corresponding <code>Number</code> constants).\n</p>\n</dd>\n<dt><code>fpRound(a[, e])</code></dt>\n<dd><p>Round the floating point number <code>a</code> according to the floating\npoint environment <code>e</code> or the global environment if <code>e</code> is\nundefined.\n</p>\n</dd>\n<dt><code>parseFloat(a[, radix[, e]])</code></dt>\n<dd><p>Parse the string <code>a</code> as a floating point number in radix\n<code>radix</code>. The radix is 0 (default) or from 2 to 36. The radix 0\nmeans radix 10 unless there is a hexadecimal or binary prefix. The\nresult is rounded according to the floating point environment <code>e</code>\nor the global environment if <code>e</code> is undefined.\n</p>\n</dd>\n<dt><code>isFinite(a)</code></dt>\n<dd><p>Return true if <code>a</code> is a finite bigfloat.\n</p>\n</dd>\n<dt><code>isNaN(a)</code></dt>\n<dd><p>Return true if <code>a</code> is a NaN bigfloat.\n</p>\n</dd>\n<dt><code>add(a, b[, e])</code></dt>\n<dt><code>sub(a, b[, e])</code></dt>\n<dt><code>mul(a, b[, e])</code></dt>\n<dt><code>div(a, b[, e])</code></dt>\n<dd><p>Perform the specified floating point operation and round the floating\npoint number <code>a</code> according to the floating point environment\n<code>e</code> or the global environment if <code>e</code> is undefined. If\n<code>e</code> is specified, the floating point status flags are updated.\n</p>\n</dd>\n<dt><code>floor(x)</code></dt>\n<dt><code>ceil(x)</code></dt>\n<dt><code>round(x)</code></dt>\n<dt><code>trunc(x)</code></dt>\n<dd><p>Round to an integer. No additional rounding is performed.\n</p>\n</dd>\n<dt><code>abs(x)</code></dt>\n<dd><p>Return the absolute value of x. No additional rounding is performed.\n</p>\n</dd>\n<dt><code>fmod(x, y[, e])</code></dt>\n<dt><code>remainder(x, y[, e])</code></dt>\n<dd><p>Floating point remainder. The quotient is truncated to zero (fmod) or\nto the nearest integer with ties to even (remainder). <code>e</code> is an\noptional floating point environment.\n</p>\n</dd>\n<dt><code>sqrt(x[, e])</code></dt>\n<dd><p>Square root. Return a rounded floating point number. <code>e</code> is an\noptional floating point environment.\n</p>\n</dd>\n<dt><code>sin(x[, e])</code></dt>\n<dt><code>cos(x[, e])</code></dt>\n<dt><code>tan(x[, e])</code></dt>\n<dt><code>asin(x[, e])</code></dt>\n<dt><code>acos(x[, e])</code></dt>\n<dt><code>atan(x[, e])</code></dt>\n<dt><code>atan2(x, y[, e])</code></dt>\n<dt><code>exp(x[, e])</code></dt>\n<dt><code>log(x[, e])</code></dt>\n<dt><code>pow(x, y[, e])</code></dt>\n<dd><p>Transcendental operations. Return a rounded floating point\nnumber. <code>e</code> is an optional floating point environment.\n</p>\n</dd>\n</dl>\n\n<a name=\"BigFloat_002eprototype\"></a>\n<h4 class=\"subsection\">4.5.2 <code>BigFloat.prototype</code></h4>\n\n<p>The following properties are modified:\n</p>\n<dl compact=\"compact\">\n<dt><code>valueOf()</code></dt>\n<dd><p>Return the bigfloat primitive value corresponding to <code>this</code>.\n</p>\n</dd>\n<dt><code>toString(radix)</code></dt>\n<dd>\n<p>For floating point numbers:\n</p>\n<ul>\n<li> If the radix is a power of two, the conversion is done with infinite\nprecision.\n</li><li> Otherwise, the number is rounded to nearest with ties to even using\nthe global precision. It is then converted to string using the minimum\nnumber of digits so that its conversion back to a floating point using\nthe global precision and round to nearest gives the same number. \n\n</li></ul>\n\n<p>The exponent letter is <code>e</code> for base 10, <code>p</code> for bases 2, 8,\n16 with a binary exponent and <code>@</code> for the other bases.\n</p>\n</dd>\n<dt><code>toPrecision(p, rnd_mode = BigFloatEnv.RNDNA, radix = 10)</code></dt>\n<dt><code>toFixed(p, rnd_mode = BigFloatEnv.RNDNA, radix = 10)</code></dt>\n<dt><code>toExponential(p, rnd_mode = BigFloatEnv.RNDNA, radix = 10)</code></dt>\n<dd><p>Same semantics as the corresponding <code>Number</code> functions with\nBigFloats. There is no limit on the accepted precision <code>p</code>. The\nrounding mode and radix can be optionally specified. The radix must be\nbetween 2 and 36.\n</p>\n</dd>\n</dl>\n\n<a name=\"BigFloatEnv-constructor\"></a>\n<h4 class=\"subsection\">4.5.3 <code>BigFloatEnv</code> constructor</h4>\n\n<p>The <code>BigFloatEnv([p, [,rndMode]]</code> constructor cannot be invoked as a\nfunction. The floating point environment contains:\n</p>\n<ul>\n<li> the mantissa precision in bits\n\n</li><li> the exponent size in bits assuming an IEEE 754 representation;\n\n</li><li> the subnormal flag (if true, subnormal floating point numbers can\nbe generated by the floating point operations).\n\n</li><li> the rounding mode\n\n</li><li> the floating point status. The status flags can only be set by the floating point operations. They can be reset with <code>BigFloatEnv.prototype.clearStatus()</code> or with the various status flag setters.\n\n</li></ul>\n\n<p><code>new BigFloatEnv([p, [,rndMode]]</code> creates a new floating point\nenvironment. The status flags are reset. If no parameter is given the\nprecision, exponent bits and subnormal flags are copied from the\nglobal floating point environment. Otherwise, the precision is set to\n<code>p</code>, the number of exponent bits is set to <code>expBitsMax</code> and the\nsubnormal flags is set to <code>false</code>. If <code>rndMode</code> is\n<code>undefined</code>, the rounding mode is set to <code>RNDN</code>.\n</p>\n<p><code>BigFloatEnv</code> properties:\n</p>\n<dl compact=\"compact\">\n<dt><code>prec</code></dt>\n<dd><p>Getter. Return the precision in bits of the global floating point\nenvironment. The initial value is <code>113</code>.\n</p>\n</dd>\n<dt><code>expBits</code></dt>\n<dd><p>Getter. Return the exponent size in bits of the global floating point\nenvironment assuming an IEEE 754 representation. The initial value is\n<code>15</code>.\n</p>\n</dd>\n<dt><code>setPrec(f, p[, e])</code></dt>\n<dd><p>Set the precision of the global floating point environment to <code>p</code>\nand the exponent size to <code>e</code> then call the function\n<code>f</code>. Then the Float precision and exponent size are reset to\ntheir precious value and the return value of <code>f</code> is returned (or\nan exception is raised if <code>f</code> raised an exception). If <code>e</code>\nis <code>undefined</code> it is set to <code>BigFloatEnv.expBitsMax</code>.\n</p>\n</dd>\n<dt><code>precMin</code></dt>\n<dd><p>Read-only integer. Return the minimum allowed precision. Must be at least 2.\n</p>\n</dd>\n<dt><code>precMax</code></dt>\n<dd><p>Read-only integer. Return the maximum allowed precision. Must be at least 113.\n</p>\n</dd>\n<dt><code>expBitsMin</code></dt>\n<dd><p>Read-only integer. Return the minimum allowed exponent size in\nbits. Must be at least 3.\n</p>\n</dd>\n<dt><code>expBitsMax</code></dt>\n<dd><p>Read-only integer. Return the maximum allowed exponent size in\nbits. Must be at least 15.\n</p>\n</dd>\n<dt><code>RNDN</code></dt>\n<dd><p>Read-only integer. Round to nearest, with ties to even rounding mode.\n</p>\n</dd>\n<dt><code>RNDZ</code></dt>\n<dd><p>Read-only integer. Round to zero rounding mode.\n</p>\n</dd>\n<dt><code>RNDD</code></dt>\n<dd><p>Read-only integer. Round to -Infinity rounding mode.\n</p>\n</dd>\n<dt><code>RNDU</code></dt>\n<dd><p>Read-only integer. Round to +Infinity rounding mode.\n</p>\n</dd>\n<dt><code>RNDNA</code></dt>\n<dd><p>Read-only integer. Round to nearest, with ties away from zero rounding mode.\n</p>\n</dd>\n<dt><code>RNDA</code></dt>\n<dd><p>Read-only integer. Round away from zero rounding mode.\n</p>\n</dd>\n<dt><code>RNDF<a name=\"DOCF4\" href=\"#FOOT4\"><sup>4</sup></a></code></dt>\n<dd><p>Read-only integer. Faithful rounding mode. The result is\nnon-deterministically rounded to -Infinity or +Infinity. This rounding\nmode usually gives a faster and deterministic running time for the\nfloating point operations.\n</p>\n</dd>\n</dl>\n\n<p><code>BigFloatEnv.prototype</code> properties:\n</p>\n<dl compact=\"compact\">\n<dt><code>prec</code></dt>\n<dd><p>Getter and setter (Integer). Return or set the precision in bits.\n</p>\n</dd>\n<dt><code>expBits</code></dt>\n<dd><p>Getter and setter (Integer). Return or set the exponent size in bits\nassuming an IEEE 754 representation.\n</p>\n</dd>\n<dt><code>rndMode</code></dt>\n<dd><p>Getter and setter (Integer). Return or set the rounding mode.\n</p>\n</dd>\n<dt><code>subnormal</code></dt>\n<dd><p>Getter and setter (Boolean). subnormal flag. It is false when\n<code>expBits = expBitsMax</code>.\n</p>\n</dd>\n<dt><code>clearStatus()</code></dt>\n<dd><p>Clear the status flags.\n</p>\n</dd>\n<dt><code>invalidOperation</code></dt>\n<dt><code>divideByZero</code></dt>\n<dt><code>overflow</code></dt>\n<dt><code>underflow</code></dt>\n<dt><code>inexact</code></dt>\n<dd><p>Getter and setter (Boolean). Status flags.\n</p>\n</dd>\n</dl>\n\n<a name=\"BigDecimal\"></a>\n<h2 class=\"chapter\">5 BigDecimal</h2>\n\n<p>This extension adds the <code>BigDecimal</code> primitive type. The\n<code>BigDecimal</code> type represents floating point numbers in base\n10. It is inspired from the proposal available at\n<a href=\"https://github.com/littledan/proposal-bigdecimal\">https://github.com/littledan/proposal-bigdecimal</a>.\n</p>\n<p>The <code>BigDecimal</code> floating point numbers are always normalized and\nfinite. There is no concept of <code>-0</code>, <code>Infinity</code> or\n<code>NaN</code>. By default, all the computations are done with infinite\nprecision.\n</p>\n<a name=\"Operators-1\"></a>\n<h3 class=\"section\">5.1 Operators</h3>\n\n<p>The following builtin operators support BigDecimal:\n</p>\n<dl compact=\"compact\">\n<dt><code>+</code></dt>\n<dt><code>-</code></dt>\n<dt><code>*</code></dt>\n<dd><p>Both operands must be BigDecimal. The result is computed with infinite\nprecision.\n</p></dd>\n<dt><code>%</code></dt>\n<dd><p>Both operands must be BigDecimal. The result is computed with infinite\nprecision. A range error is throws in case of division by zero.\n</p>\n</dd>\n<dt><code>/</code></dt>\n<dd><p>Both operands must be BigDecimal. A range error is throws in case of\ndivision by zero or if the result cannot be represented with infinite\nprecision (use <code>BigDecimal.div</code> to specify the rounding).\n</p>\n</dd>\n<dt><code>**</code></dt>\n<dd><p>Both operands must be BigDecimal. The exponent must be a positive\ninteger. The result is computed with infinite precision.\n</p>\n</dd>\n<dt><code>===</code></dt>\n<dd><p>When one of the operand is a BigDecimal, return true if both operands\nare a BigDecimal and if they are equal.\n</p>\n</dd>\n<dt><code>==</code></dt>\n<dt><code>!=</code></dt>\n<dt><code>&lt;=</code></dt>\n<dt><code>&gt;=</code></dt>\n<dt><code>&lt;</code></dt>\n<dt><code>&gt;</code></dt>\n<dd>\n<p>Numerical comparison. When one of the operand is not a BigDecimal, it is\nconverted to BigDecimal by using ToString(). Hence comparisons between\nNumber and BigDecimal do not use the exact mathematical value of the\nNumber value.\n</p>\n</dd>\n</dl>\n\n<a name=\"BigDecimal-literals\"></a>\n<h3 class=\"section\">5.2 BigDecimal literals</h3>\n\n<p>BigDecimal literals are decimal floating point numbers with a trailing\n<code>m</code> suffix.\n</p>\n<a name=\"Builtin-Object-changes-1\"></a>\n<h3 class=\"section\">5.3 Builtin Object changes</h3>\n\n<a name=\"The-BigDecimal-function_002e\"></a>\n<h4 class=\"subsection\">5.3.1 The <code>BigDecimal</code> function.</h4>\n\n<p>It returns <code>0m</code> if no parameter is provided. Otherwise the first\nparameter is converted to a bigdecimal by using ToString(). Hence\nNumber values are not converted to their exact numerical value as\nBigDecimal.\n</p>\n<a name=\"Properties-of-the-BigDecimal-object\"></a>\n<h4 class=\"subsection\">5.3.2 Properties of the <code>BigDecimal</code> object</h4>\n\n<dl compact=\"compact\">\n<dt><code>add(a, b[, e])</code></dt>\n<dt><code>sub(a, b[, e])</code></dt>\n<dt><code>mul(a, b[, e])</code></dt>\n<dt><code>div(a, b[, e])</code></dt>\n<dt><code>mod(a, b[, e])</code></dt>\n<dt><code>sqrt(a, e)</code></dt>\n<dt><code>round(a, e)</code></dt>\n<dd><p>Perform the specified floating point operation and round the floating\npoint result according to the rounding object <code>e</code>. If the\nrounding object is not present, the operation is executed with\ninfinite precision.\n</p>\n<p>For <code>div</code>, a <code>RangeError</code> exception is thrown in case of\ndivision by zero or if the result cannot be represented with infinite\nprecision if no rounding object is present.\n</p>\n<p>For <code>sqrt</code>, a range error is thrown if <code>a</code> is less than\nzero.\n</p>\n<p>The rounding object must contain the following properties:\n<code>roundingMode</code> is a string specifying the rounding mode\n(<code>&quot;floor&quot;</code>, <code>&quot;ceiling&quot;</code>, <code>&quot;down&quot;</code>, <code>&quot;up&quot;</code>,\n<code>&quot;half-even&quot;</code>, <code>&quot;half-up&quot;</code>). Either\n<code>maximumSignificantDigits</code> or <code>maximumFractionDigits</code> must\nbe present to specify respectively the number of significant digits\n(must be &gt;= 1) or the number of digits after the decimal point (must\nbe &gt;= 0).\n</p>\n</dd>\n</dl>\n\n<a name=\"Properties-of-the-BigDecimal_002eprototype-object\"></a>\n<h4 class=\"subsection\">5.3.3 Properties of the <code>BigDecimal.prototype</code> object</h4>\n\n<dl compact=\"compact\">\n<dt><code>valueOf()</code></dt>\n<dd><p>Return the bigdecimal primitive value corresponding to <code>this</code>.\n</p>\n</dd>\n<dt><code>toString()</code></dt>\n<dd><p>Convert <code>this</code> to a string with infinite precision in base 10.\n</p>\n</dd>\n<dt><code>toPrecision(p, rnd_mode = &quot;half-up&quot;)</code></dt>\n<dt><code>toFixed(p, rnd_mode = &quot;half-up&quot;)</code></dt>\n<dt><code>toExponential(p, rnd_mode = &quot;half-up&quot;)</code></dt>\n<dd><p>Convert the BigDecimal <code>this</code> to string with the specified\nprecision <code>p</code>. There is no limit on the accepted precision\n<code>p</code>. The rounding mode can be optionally\nspecified. <code>toPrecision</code> outputs either in decimal fixed notation\nor in decimal exponential notation with a <code>p</code> digits of\nprecision.  <code>toExponential</code> outputs in decimal exponential\nnotation with <code>p</code> digits after the decimal point. <code>toFixed</code>\noutputs in decimal notation with <code>p</code> digits after the decimal\npoint.\n</p>\n</dd>\n</dl>\n\n<a name=\"Math-mode\"></a>\n<h2 class=\"chapter\">6 Math mode</h2>\n\n<p>A new <em>math mode</em> is enabled with the <code>&quot;use math&quot;</code>\ndirective. It propagates the same way as the <em>strict mode</em>. It is\ndesigned so that arbitrarily large integers and floating point numbers\nare available by default. In order to minimize the number of changes\nin the Javascript semantics, integers are represented either as Number\nor BigInt depending on their magnitude. Floating point numbers are\nalways represented as BigFloat.\n</p>\n<p>The following changes are made to the Javascript semantics:\n</p>\n<ul>\n<li> Floating point literals (i.e. number with a decimal point or an exponent) are <code>BigFloat</code> by default (i.e. a <code>l</code> suffix is implied). Hence <code>typeof 1.0 === &quot;bigfloat&quot;</code>.\n\n</li><li> Integer literals (i.e. numbers without a decimal point or an exponent) with or without the <code>n</code> suffix are <code>BigInt</code> if their value cannot be represented as a safe integer. A safe integer is defined as a integer whose absolute value is smaller or equal to <code>2**53-1</code>. Hence <code>typeof 1 === &quot;number &quot;</code>, <code>typeof 1n === &quot;number&quot;</code> but <code>typeof 9007199254740992 === &quot;bigint&quot; </code>.\n\n</li><li> All the bigint builtin operators and functions are modified so that their result is returned as a Number if it is a safe integer. Otherwise the result stays a BigInt.\n\n</li><li> The builtin operators are modified so that they return an exact result (which can be a BigInt) if their operands are safe integers. Operands between Number and BigInt are accepted provided the Number operand is a safe integer. The integer power with a negative exponent returns a BigFloat as result. The integer division returns a BigFloat as result.\n\n</li><li> The <code>^</code> operator is an alias to the power operator (<code>**</code>).\n\n</li><li> The power operator (both <code>^</code> and <code>**</code>) grammar is modified so that <code>-2^2</code> is allowed and yields <code>-4</code>.\n\n</li><li> The logical xor operator is still available with the <code>^^</code> operator.\n\n</li><li> The modulo operator (<code>%</code>) returns the Euclidian remainder (always positive) instead of the truncated remainder.\n\n</li><li> The integer division operator can be overloaded with <code>Operators.updateBigIntOperators(dictionary)</code>.\n\n</li><li> The integer power operator with a non zero negative exponent can be overloaded with <code>Operators.updateBigIntOperators(dictionary)</code>.\n\n</li></ul>\n\n<div class=\"footnote\">\n<hr>\n<h4 class=\"footnotes-heading\">Footnotes</h4>\n\n<h3><a name=\"FOOT1\" href=\"#DOCF1\">(1)</a></h3>\n<p>The\nrationale is that the rounding mode changes must always be\nexplicit.</p>\n<h3><a name=\"FOOT2\" href=\"#DOCF2\">(2)</a></h3>\n<p>The rationale is to avoid side effects for the built-in\noperators.</p>\n<h3><a name=\"FOOT3\" href=\"#DOCF3\">(3)</a></h3>\n<p>Base 10 floating point literals cannot usually be\nexactly represented as base 2 floating point number. In order to\nensure that the literal is represented accurately with the current\nprecision, it must be evaluated at runtime.</p>\n<h3><a name=\"FOOT4\" href=\"#DOCF4\">(4)</a></h3>\n<p>Could be removed in case a deterministic behavior for floating point operations is required.</p>\n</div>\n<hr>\n\n\n\n</body>\n</html>\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/doc/jsbignum.texi",
    "content": "\\input texinfo\n\n@iftex\n@afourpaper\n@headings double\n@end iftex\n\n@titlepage\n@afourpaper\n@sp 7\n@center @titlefont{Javascript Bignum Extensions}\n@sp 3\n@center Version 2020-01-11\n@sp 3\n@center Author: Fabrice Bellard\n@end titlepage\n\n@setfilename jsbignum.info\n@settitle Javascript Bignum Extensions\n\n@contents\n\n@chapter Introduction\n\nThe Bignum extensions add the following features to the Javascript\nlanguage while being 100% backward compatible:\n\n@itemize\n\n@item Operator overloading with a dispatch logic inspired from the proposal available at @url{https://github.com/tc39/proposal-operator-overloading/}.\n\n@item Arbitrarily large floating point numbers (@code{BigFloat}) in base 2 using the IEEE 754 semantics.\n\n@item Arbitrarily large floating point numbers (@code{BigDecimal}) in base 10 based on the proposal available at\n@url{https://github.com/littledan/proposal-bigdecimal}.\n\n@item @code{math} mode: arbitrarily large integers and floating point numbers are available by default. The integer division and power can be overloaded for example to return a fraction. The modulo operator (@code{%}) is defined as the Euclidian\nremainder. @code{^} is an alias to the power operator\n(@code{**}). @code{^^} is used as the exclusive or operator.\n\n@end itemize\n\nThe extensions are independent from each other except the @code{math}\nmode which relies on BigFloat and operator overloading.\n\n@chapter Operator overloading\n\nOperator overloading is inspired from the proposal available at\n@url{https://github.com/tc39/proposal-operator-overloading/}. It\nimplements the same dispatch logic but finds the operator sets by\nlooking at the @code{Symbol.operatorSet} property in the objects. The\nchanges were done in order to simplify the implementation.\n\nMore precisely, the following modifications were made:\n\n@itemize\n\n@item @code{with operators from} is not supported. Operator overloading is always enabled.\n\n@item The dispatch is not based on a static @code{[[OperatorSet]]} field in all instances. Instead, a dynamic lookup of the @code{Symbol.operatorSet} property is done. This property is typically added in the prototype of each object.\n\n@item @code{Operators.create(...dictionaries)} is used to create a new OperatorSet object. The @code{Operators} function is supported as an helper to be closer to the TC39 proposal.\n\n@item @code{[]} cannot be overloaded.\n\n@item In math mode, the BigInt division and power operators can be overloaded with @code{Operators.updateBigIntOperators(dictionary)}.\n\n@end itemize\n\n@chapter BigInt extensions\n\nA few properties are added to the BigInt object:\n\n@table @code\n\n@item tdiv(a, b)\nReturn @math{trunc(a/b)}. @code{b = 0} raises a RangeError\nexception.\n\n@item fdiv(a, b)\nReturn @math{\\lfloor a/b \\rfloor}. @code{b = 0} raises a RangeError\nexception.\n\n@item cdiv(a, b)\nReturn @math{\\lceil a/b \\rceil}. @code{b = 0} raises a RangeError\nexception.\n\n@item ediv(a, b)\nReturn @math{sgn(b) \\lfloor a/{|b|} \\rfloor} (Euclidian\ndivision). @code{b = 0} raises a RangeError exception.\n\n@item tdivrem(a, b)\n@item fdivrem(a, b)\n@item cdivrem(a, b)\n@item edivrem(a, b)\nReturn an array of two elements. The first element is the quotient,\nthe second is the remainder. The same rounding is done as the\ncorresponding division operation.\n\n@item sqrt(a)\nReturn @math{\\lfloor \\sqrt(a) \\rfloor}. A RangeError exception is\nraised if @math{a < 0}.\n\n@item sqrtrem(a)\nReturn an array of two elements. The first element is @math{\\lfloor\n\\sqrt{a} \\rfloor}. The second element is @math{a-\\lfloor \\sqrt{a}\n\\rfloor^2}. A RangeError exception is raised if @math{a < 0}.\n\n@item floorLog2(a)\nReturn -1 if @math{a \\leq 0} otherwise return @math{\\lfloor \\log2(a) \\rfloor}.\n\n@item ctz(a)\nReturn the number of trailing zeros in the two's complement binary representation of a. Return -1 if @math{a=0}.\n\n@end table\n\n@chapter BigFloat\n\n@section Introduction\n\nThis extension adds the @code{BigFloat} primitive type. The\n@code{BigFloat} type represents floating point numbers in base 2\nwith the IEEE 754 semantics. A floating\npoint number is represented as a sign, mantissa and exponent. The\nspecial values @code{NaN}, @code{+/-Infinity}, @code{+0} and @code{-0}\nare supported. The mantissa and exponent can have any bit length with\nan implementation specific minimum and maximum.\n\n@section Floating point rounding\n\nEach floating point operation operates with infinite precision and\nthen rounds the result according to the specified floating point\nenvironment (@code{BigFloatEnv} object). The status flags of the\nenvironment are also set according to the result of the operation.\n\nIf no floating point environment is provided, the global floating\npoint environment is used.\n\nThe rounding mode of the global floating point environment is always\n@code{RNDN} (``round to nearest with ties to even'')@footnote{The\nrationale is that the rounding mode changes must always be\nexplicit.}. The status flags of the global environment cannot be\nread@footnote{The rationale is to avoid side effects for the built-in\noperators.}. The precision of the global environment is\n@code{BigFloatEnv.prec}. The number of exponent bits of the global\nenvironment is @code{BigFloatEnv.expBits}. The global environment\nsubnormal flag is set to @code{true}.\n\nFor example, @code{prec = 53} and @code{ expBits = 11} exactly give\nthe same precision as the IEEE 754 64 bit floating point format. The\ndefault precision is @code{prec = 113} and @code{ expBits = 15} (IEEE\n754 128 bit floating point format).\n\nThe global floating point environment can only be modified temporarily\nwhen calling a function (see @code{BigFloatEnv.setPrec}). Hence a\nfunction can change the global floating point environment for its\ncallees but not for its caller.\n\n@section Operators\n\nThe builtin operators are extended so that a BigFloat is returned if\nat least one operand is a BigFloat. The computations are always done\nwith infinite precision and rounded according to the global floating\npoint environment.\n\n@code{typeof} applied on a @code{BigFloat} returns @code{bigfloat}.\n\nBigFloat can be compared with all the other numeric types and the\nresult follows the expected mathematical relations.\n\nHowever, since BigFloat and Number are different types they are never\nequal when using the strict comparison operators (e.g. @code{0.0 ===\n0.0l} is false).\n\n@section BigFloat literals\n\nBigFloat literals are floating point numbers with a trailing @code{l}\nsuffix. BigFloat literals have an infinite precision. They are rounded\naccording to the global floating point environment when they are\nevaluated.@footnote{Base 10 floating point literals cannot usually be\nexactly represented as base 2 floating point number. In order to\nensure that the literal is represented accurately with the current\nprecision, it must be evaluated at runtime.}\n\n@section Builtin Object changes\n\n@subsection @code{BigFloat} function\n\nThe @code{BigFloat} function cannot be invoked as a constructor. When\ninvoked as a function: the parameter is converted to a primitive\ntype. If the result is a numeric type, it is converted to BigFloat\nwithout rounding. If the result is a string, it is converted to\nBigFloat using the precision of the global floating point environment.\n\n@code{BigFloat} properties:\n\n@table @code\n\n@item LN2\n@item PI\nGetter. Return the value of the corresponding mathematical constant\nrounded to nearest, ties to even with the current global\nprecision. The constant values are cached for small precisions.\n\n@item MIN_VALUE\n@item MAX_VALUE\n@item EPSILON\nGetter. Return the minimum, maximum and epsilon @code{BigFloat} values\n(same definition as the corresponding @code{Number} constants).\n\n@item fpRound(a[, e])\nRound the floating point number @code{a} according to the floating\npoint environment @code{e} or the global environment if @code{e} is\nundefined.\n\n@item parseFloat(a[, radix[, e]])\nParse the string @code{a} as a floating point number in radix\n@code{radix}. The radix is 0 (default) or from 2 to 36. The radix 0\nmeans radix 10 unless there is a hexadecimal or binary prefix. The\nresult is rounded according to the floating point environment @code{e}\nor the global environment if @code{e} is undefined.\n\n@item isFinite(a)\nReturn true if @code{a} is a finite bigfloat.\n\n@item isNaN(a)\nReturn true if @code{a} is a NaN bigfloat.\n\n@item add(a, b[, e])\n@item sub(a, b[, e])\n@item mul(a, b[, e])\n@item div(a, b[, e])\nPerform the specified floating point operation and round the floating\npoint number @code{a} according to the floating point environment\n@code{e} or the global environment if @code{e} is undefined. If\n@code{e} is specified, the floating point status flags are updated.\n\n@item floor(x)\n@item ceil(x)\n@item round(x)\n@item trunc(x)\nRound to an integer. No additional rounding is performed.\n\n@item abs(x)\nReturn the absolute value of x. No additional rounding is performed.\n\n@item fmod(x, y[, e])\n@item remainder(x, y[, e])\nFloating point remainder. The quotient is truncated to zero (fmod) or\nto the nearest integer with ties to even (remainder). @code{e} is an\noptional floating point environment.\n\n@item sqrt(x[, e])\nSquare root. Return a rounded floating point number. @code{e} is an\noptional floating point environment.\n\n@item sin(x[, e])\n@item cos(x[, e])\n@item tan(x[, e])\n@item asin(x[, e])\n@item acos(x[, e])\n@item atan(x[, e])\n@item atan2(x, y[, e])\n@item exp(x[, e])\n@item log(x[, e])\n@item pow(x, y[, e])\nTranscendental operations. Return a rounded floating point\nnumber. @code{e} is an optional floating point environment.\n\n@end table\n\n@subsection @code{BigFloat.prototype}\n\nThe following properties are modified:\n\n@table @code\n@item valueOf()\nReturn the bigfloat primitive value corresponding to @code{this}.\n\n@item toString(radix)\n\nFor floating point numbers:\n\n@itemize\n@item\nIf the radix is a power of two, the conversion is done with infinite\nprecision.\n@item\nOtherwise, the number is rounded to nearest with ties to even using\nthe global precision. It is then converted to string using the minimum\nnumber of digits so that its conversion back to a floating point using\nthe global precision and round to nearest gives the same number. \n\n@end itemize\n\nThe exponent letter is @code{e} for base 10, @code{p} for bases 2, 8,\n16 with a binary exponent and @code{@@} for the other bases.\n\n@item toPrecision(p, rnd_mode = BigFloatEnv.RNDNA, radix = 10)\n@item toFixed(p, rnd_mode = BigFloatEnv.RNDNA, radix = 10)\n@item toExponential(p, rnd_mode = BigFloatEnv.RNDNA, radix = 10)\nSame semantics as the corresponding @code{Number} functions with\nBigFloats. There is no limit on the accepted precision @code{p}. The\nrounding mode and radix can be optionally specified. The radix must be\nbetween 2 and 36.\n\n@end table\n\n@subsection @code{BigFloatEnv} constructor\n\nThe @code{BigFloatEnv([p, [,rndMode]]} constructor cannot be invoked as a\nfunction. The floating point environment contains:\n\n@itemize\n@item the mantissa precision in bits\n\n@item the exponent size in bits assuming an IEEE 754 representation;\n\n@item the subnormal flag (if true, subnormal floating point numbers can\nbe generated by the floating point operations).\n\n@item the rounding mode\n\n@item the floating point status. The status flags can only be set by the floating point operations. They can be reset with @code{BigFloatEnv.prototype.clearStatus()} or with the various status flag setters.\n\n@end itemize\n\n@code{new BigFloatEnv([p, [,rndMode]]} creates a new floating point\nenvironment. The status flags are reset. If no parameter is given the\nprecision, exponent bits and subnormal flags are copied from the\nglobal floating point environment. Otherwise, the precision is set to\n@code{p}, the number of exponent bits is set to @code{expBitsMax} and the\nsubnormal flags is set to @code{false}. If @code{rndMode} is\n@code{undefined}, the rounding mode is set to @code{RNDN}.\n\n@code{BigFloatEnv} properties:\n\n@table @code\n\n@item prec\nGetter. Return the precision in bits of the global floating point\nenvironment. The initial value is @code{113}.\n\n@item expBits\nGetter. Return the exponent size in bits of the global floating point\nenvironment assuming an IEEE 754 representation. The initial value is\n@code{15}.\n\n@item setPrec(f, p[, e])\nSet the precision of the global floating point environment to @code{p}\nand the exponent size to @code{e} then call the function\n@code{f}. Then the Float precision and exponent size are reset to\ntheir precious value and the return value of @code{f} is returned (or\nan exception is raised if @code{f} raised an exception). If @code{e}\nis @code{undefined} it is set to @code{BigFloatEnv.expBitsMax}.\n\n@item precMin\nRead-only integer. Return the minimum allowed precision. Must be at least 2.\n\n@item precMax\nRead-only integer. Return the maximum allowed precision. Must be at least 113.\n\n@item expBitsMin\nRead-only integer. Return the minimum allowed exponent size in\nbits. Must be at least 3.\n\n@item expBitsMax\nRead-only integer. Return the maximum allowed exponent size in\nbits. Must be at least 15.\n\n@item RNDN\nRead-only integer. Round to nearest, with ties to even rounding mode.\n\n@item RNDZ\nRead-only integer. Round to zero rounding mode.\n\n@item RNDD\nRead-only integer. Round to -Infinity rounding mode.\n\n@item RNDU\nRead-only integer. Round to +Infinity rounding mode.\n\n@item RNDNA\nRead-only integer. Round to nearest, with ties away from zero rounding mode.\n\n@item RNDA\nRead-only integer. Round away from zero rounding mode.\n\n@item RNDF@footnote{Could be removed in case a deterministic behavior for floating point operations is required.}\nRead-only integer. Faithful rounding mode. The result is\nnon-deterministically rounded to -Infinity or +Infinity. This rounding\nmode usually gives a faster and deterministic running time for the\nfloating point operations.\n\n@end table\n\n@code{BigFloatEnv.prototype} properties:\n\n@table @code\n\n@item prec\nGetter and setter (Integer). Return or set the precision in bits.\n\n@item expBits\nGetter and setter (Integer). Return or set the exponent size in bits\nassuming an IEEE 754 representation.\n\n@item rndMode\nGetter and setter (Integer). Return or set the rounding mode.\n\n@item subnormal\nGetter and setter (Boolean). subnormal flag. It is false when\n@code{expBits = expBitsMax}.\n\n@item clearStatus()\nClear the status flags.\n\n@item invalidOperation\n@item divideByZero\n@item overflow\n@item underflow\n@item inexact\nGetter and setter (Boolean). Status flags.\n\n@end table\n\n@chapter BigDecimal\n\nThis extension adds the @code{BigDecimal} primitive type. The\n@code{BigDecimal} type represents floating point numbers in base\n10. It is inspired from the proposal available at\n@url{https://github.com/littledan/proposal-bigdecimal}.\n\nThe @code{BigDecimal} floating point numbers are always normalized and\nfinite. There is no concept of @code{-0}, @code{Infinity} or\n@code{NaN}. By default, all the computations are done with infinite\nprecision.\n\n@section Operators\n\nThe following builtin operators support BigDecimal:\n\n@table @code\n\n@item +\n@item -\n@item *\nBoth operands must be BigDecimal. The result is computed with infinite\nprecision.\n@item %\nBoth operands must be BigDecimal. The result is computed with infinite\nprecision. A range error is throws in case of division by zero.\n\n@item /\nBoth operands must be BigDecimal. A range error is throws in case of\ndivision by zero or if the result cannot be represented with infinite\nprecision (use @code{BigDecimal.div} to specify the rounding).\n\n@item **\nBoth operands must be BigDecimal. The exponent must be a positive\ninteger. The result is computed with infinite precision.\n\n@item ===\nWhen one of the operand is a BigDecimal, return true if both operands\nare a BigDecimal and if they are equal.\n\n@item ==\n@item !=\n@item <=\n@item >=\n@item <\n@item >\n\nNumerical comparison. When one of the operand is not a BigDecimal, it is\nconverted to BigDecimal by using ToString(). Hence comparisons between\nNumber and BigDecimal do not use the exact mathematical value of the\nNumber value.\n\n@end table\n\n@section BigDecimal literals\n\nBigDecimal literals are decimal floating point numbers with a trailing\n@code{m} suffix.\n\n@section Builtin Object changes\n\n@subsection The @code{BigDecimal} function.\n\nIt returns @code{0m} if no parameter is provided. Otherwise the first\nparameter is converted to a bigdecimal by using ToString(). Hence\nNumber values are not converted to their exact numerical value as\nBigDecimal.\n\n@subsection Properties of the @code{BigDecimal} object\n\n@table @code\n\n@item add(a, b[, e])\n@item sub(a, b[, e])\n@item mul(a, b[, e])\n@item div(a, b[, e])\n@item mod(a, b[, e])\n@item sqrt(a, e)\n@item round(a, e)\nPerform the specified floating point operation and round the floating\npoint result according to the rounding object @code{e}. If the\nrounding object is not present, the operation is executed with\ninfinite precision.\n\nFor @code{div}, a @code{RangeError} exception is thrown in case of\ndivision by zero or if the result cannot be represented with infinite\nprecision if no rounding object is present.\n\nFor @code{sqrt}, a range error is thrown if @code{a} is less than\nzero.\n\nThe rounding object must contain the following properties:\n@code{roundingMode} is a string specifying the rounding mode\n(@code{\"floor\"}, @code{\"ceiling\"}, @code{\"down\"}, @code{\"up\"},\n@code{\"half-even\"}, @code{\"half-up\"}). Either\n@code{maximumSignificantDigits} or @code{maximumFractionDigits} must\nbe present to specify respectively the number of significant digits\n(must be >= 1) or the number of digits after the decimal point (must\nbe >= 0).\n\n@end table\n\n@subsection Properties of the @code{BigDecimal.prototype} object\n\n@table @code\n@item valueOf()\nReturn the bigdecimal primitive value corresponding to @code{this}.\n\n@item toString()\nConvert @code{this} to a string with infinite precision in base 10.\n\n@item toPrecision(p, rnd_mode = \"half-up\")\n@item toFixed(p, rnd_mode = \"half-up\")\n@item toExponential(p, rnd_mode = \"half-up\")\nConvert the BigDecimal @code{this} to string with the specified\nprecision @code{p}. There is no limit on the accepted precision\n@code{p}. The rounding mode can be optionally\nspecified. @code{toPrecision} outputs either in decimal fixed notation\nor in decimal exponential notation with a @code{p} digits of\nprecision.  @code{toExponential} outputs in decimal exponential\nnotation with @code{p} digits after the decimal point. @code{toFixed}\noutputs in decimal notation with @code{p} digits after the decimal\npoint.\n\n@end table\n\n@chapter Math mode\n\nA new @emph{math mode} is enabled with the @code{\"use math\"}\ndirective. It propagates the same way as the @emph{strict mode}. It is\ndesigned so that arbitrarily large integers and floating point numbers\nare available by default. In order to minimize the number of changes\nin the Javascript semantics, integers are represented either as Number\nor BigInt depending on their magnitude. Floating point numbers are\nalways represented as BigFloat.\n\nThe following changes are made to the Javascript semantics:\n\n@itemize\n\n@item Floating point literals (i.e. number with a decimal point or an exponent) are @code{BigFloat} by default (i.e. a @code{l} suffix is implied). Hence @code{typeof 1.0 === \"bigfloat\"}.\n\n@item Integer literals (i.e. numbers without a decimal point or an exponent) with or without the @code{n} suffix are @code{BigInt} if their value cannot be represented as a safe integer. A safe integer is defined as a integer whose absolute value is smaller or equal to @code{2**53-1}. Hence @code{typeof 1 === \"number \"}, @code{typeof 1n === \"number\"} but @code{typeof 9007199254740992 === \"bigint\" }.\n\n@item All the bigint builtin operators and functions are modified so that their result is returned as a Number if it is a safe integer. Otherwise the result stays a BigInt.\n\n@item The builtin operators are modified so that they return an exact result (which can be a BigInt) if their operands are safe integers. Operands between Number and BigInt are accepted provided the Number operand is a safe integer. The integer power with a negative exponent returns a BigFloat as result. The integer division returns a BigFloat as result.\n\n@item The @code{^} operator is an alias to the power operator (@code{**}).\n\n@item The power operator (both @code{^} and @code{**}) grammar is modified so that @code{-2^2} is allowed and yields @code{-4}.\n\n@item The logical xor operator is still available with the @code{^^} operator.\n\n@item The modulo operator (@code{%}) returns the Euclidian remainder (always positive) instead of the truncated remainder.\n\n@item The integer division operator can be overloaded with @code{Operators.updateBigIntOperators(dictionary)}.\n\n@item The integer power operator with a non zero negative exponent can be overloaded with @code{Operators.updateBigIntOperators(dictionary)}.\n\n@end itemize\n\n@bye\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/doc/quickjs.html",
    "content": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n<!-- Created by GNU Texinfo 6.1, http://www.gnu.org/software/texinfo/ -->\n<head>\n<title>QuickJS Javascript Engine</title>\n\n<meta name=\"description\" content=\"QuickJS Javascript Engine\">\n<meta name=\"keywords\" content=\"QuickJS Javascript Engine\">\n<meta name=\"resource-type\" content=\"document\">\n<meta name=\"distribution\" content=\"global\">\n<meta name=\"Generator\" content=\"makeinfo\">\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<link href=\"#SEC_Contents\" rel=\"contents\" title=\"Table of Contents\">\n<style type=\"text/css\">\n<!--\na.summary-letter {text-decoration: none}\nblockquote.indentedblock {margin-right: 0em}\nblockquote.smallindentedblock {margin-right: 0em; font-size: smaller}\nblockquote.smallquotation {font-size: smaller}\ndiv.display {margin-left: 3.2em}\ndiv.example {margin-left: 3.2em}\ndiv.lisp {margin-left: 3.2em}\ndiv.smalldisplay {margin-left: 3.2em}\ndiv.smallexample {margin-left: 3.2em}\ndiv.smalllisp {margin-left: 3.2em}\nkbd {font-style: oblique}\npre.display {font-family: inherit}\npre.format {font-family: inherit}\npre.menu-comment {font-family: serif}\npre.menu-preformatted {font-family: serif}\npre.smalldisplay {font-family: inherit; font-size: smaller}\npre.smallexample {font-size: smaller}\npre.smallformat {font-family: inherit; font-size: smaller}\npre.smalllisp {font-size: smaller}\nspan.nolinebreak {white-space: nowrap}\nspan.roman {font-family: initial; font-weight: normal}\nspan.sansserif {font-family: sans-serif; font-weight: normal}\nul.no-bullet {list-style: none}\n-->\n</style>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n\n\n</head>\n\n<body lang=\"en\">\n<h1 class=\"settitle\" align=\"center\">QuickJS Javascript Engine</h1>\n\n<a name=\"SEC_Contents\"></a>\n<h2 class=\"contents-heading\">Table of Contents</h2>\n\n<div class=\"contents\">\n<ul class=\"no-bullet\">\n<li><a name=\"toc-Introduction\" href=\"#Introduction\">1 Introduction</a>\n<ul class=\"no-bullet\">\n  <li><a name=\"toc-Main-Features\" href=\"#Main-Features\">1.1 Main Features</a></li>\n</ul></li>\n<li><a name=\"toc-Usage\" href=\"#Usage\">2 Usage</a>\n<ul class=\"no-bullet\">\n  <li><a name=\"toc-Installation\" href=\"#Installation\">2.1 Installation</a></li>\n  <li><a name=\"toc-Quick-start\" href=\"#Quick-start\">2.2 Quick start</a></li>\n  <li><a name=\"toc-Command-line-options\" href=\"#Command-line-options\">2.3 Command line options</a>\n  <ul class=\"no-bullet\">\n    <li><a name=\"toc-qjs-interpreter\" href=\"#qjs-interpreter\">2.3.1 <code>qjs</code> interpreter</a></li>\n    <li><a name=\"toc-qjsc-compiler\" href=\"#qjsc-compiler\">2.3.2 <code>qjsc</code> compiler</a></li>\n  </ul></li>\n  <li><a name=\"toc-qjscalc-application\" href=\"#qjscalc-application\">2.4 <code>qjscalc</code> application</a></li>\n  <li><a name=\"toc-Built_002din-tests\" href=\"#Built_002din-tests\">2.5 Built-in tests</a></li>\n  <li><a name=\"toc-Test262-_0028ECMAScript-Test-Suite_0029\" href=\"#Test262-_0028ECMAScript-Test-Suite_0029\">2.6 Test262 (ECMAScript Test Suite)</a></li>\n</ul></li>\n<li><a name=\"toc-Specifications\" href=\"#Specifications\">3 Specifications</a>\n<ul class=\"no-bullet\">\n  <li><a name=\"toc-Language-support\" href=\"#Language-support\">3.1 Language support</a>\n  <ul class=\"no-bullet\">\n    <li><a name=\"toc-ES2020-support\" href=\"#ES2020-support\">3.1.1 ES2020 support</a></li>\n    <li><a name=\"toc-ECMA402\" href=\"#ECMA402\">3.1.2 ECMA402</a></li>\n    <li><a name=\"toc-Extensions\" href=\"#Extensions\">3.1.3 Extensions</a></li>\n    <li><a name=\"toc-Mathematical-extensions\" href=\"#Mathematical-extensions\">3.1.4 Mathematical extensions</a></li>\n  </ul></li>\n  <li><a name=\"toc-Modules\" href=\"#Modules\">3.2 Modules</a></li>\n  <li><a name=\"toc-Standard-library\" href=\"#Standard-library\">3.3 Standard library</a>\n  <ul class=\"no-bullet\">\n    <li><a name=\"toc-Global-objects\" href=\"#Global-objects\">3.3.1 Global objects</a></li>\n    <li><a name=\"toc-std-module\" href=\"#std-module\">3.3.2 <code>std</code> module</a></li>\n    <li><a name=\"toc-os-module\" href=\"#os-module\">3.3.3 <code>os</code> module</a></li>\n  </ul></li>\n  <li><a name=\"toc-QuickJS-C-API\" href=\"#QuickJS-C-API\">3.4 QuickJS C API</a>\n  <ul class=\"no-bullet\">\n    <li><a name=\"toc-Runtime-and-contexts\" href=\"#Runtime-and-contexts\">3.4.1 Runtime and contexts</a></li>\n    <li><a name=\"toc-JSValue\" href=\"#JSValue\">3.4.2 JSValue</a></li>\n    <li><a name=\"toc-C-functions\" href=\"#C-functions\">3.4.3 C functions</a></li>\n    <li><a name=\"toc-Exceptions\" href=\"#Exceptions\">3.4.4 Exceptions</a></li>\n    <li><a name=\"toc-Script-evaluation\" href=\"#Script-evaluation\">3.4.5 Script evaluation</a></li>\n    <li><a name=\"toc-JS-Classes\" href=\"#JS-Classes\">3.4.6 JS Classes</a></li>\n    <li><a name=\"toc-C-Modules\" href=\"#C-Modules\">3.4.7 C Modules</a></li>\n    <li><a name=\"toc-Memory-handling\" href=\"#Memory-handling\">3.4.8 Memory handling</a></li>\n    <li><a name=\"toc-Execution-timeout-and-interrupts\" href=\"#Execution-timeout-and-interrupts\">3.4.9 Execution timeout and interrupts</a></li>\n  </ul></li>\n</ul></li>\n<li><a name=\"toc-Internals\" href=\"#Internals\">4 Internals</a>\n<ul class=\"no-bullet\">\n  <li><a name=\"toc-Bytecode\" href=\"#Bytecode\">4.1 Bytecode</a></li>\n  <li><a name=\"toc-Executable-generation\" href=\"#Executable-generation\">4.2 Executable generation</a>\n  <ul class=\"no-bullet\">\n    <li><a name=\"toc-qjsc-compiler-1\" href=\"#qjsc-compiler-1\">4.2.1 <code>qjsc</code> compiler</a></li>\n    <li><a name=\"toc-Binary-JSON\" href=\"#Binary-JSON\">4.2.2 Binary JSON</a></li>\n  </ul></li>\n  <li><a name=\"toc-Runtime\" href=\"#Runtime\">4.3 Runtime</a>\n  <ul class=\"no-bullet\">\n    <li><a name=\"toc-Strings\" href=\"#Strings\">4.3.1 Strings</a></li>\n    <li><a name=\"toc-Objects\" href=\"#Objects\">4.3.2 Objects</a></li>\n    <li><a name=\"toc-Atoms\" href=\"#Atoms\">4.3.3 Atoms</a></li>\n    <li><a name=\"toc-Numbers\" href=\"#Numbers\">4.3.4 Numbers</a></li>\n    <li><a name=\"toc-Garbage-collection\" href=\"#Garbage-collection\">4.3.5 Garbage collection</a></li>\n    <li><a name=\"toc-JSValue-1\" href=\"#JSValue-1\">4.3.6 JSValue</a></li>\n    <li><a name=\"toc-Function-call\" href=\"#Function-call\">4.3.7 Function call</a></li>\n  </ul></li>\n  <li><a name=\"toc-RegExp\" href=\"#RegExp\">4.4 RegExp</a></li>\n  <li><a name=\"toc-Unicode\" href=\"#Unicode\">4.5 Unicode</a></li>\n  <li><a name=\"toc-BigInt_002c-BigFloat_002c-BigDecimal\" href=\"#BigInt_002c-BigFloat_002c-BigDecimal\">4.6 BigInt, BigFloat, BigDecimal</a></li>\n</ul></li>\n<li><a name=\"toc-License\" href=\"#License\">5 License</a></li>\n\n</ul>\n</div>\n\n\n<a name=\"Introduction\"></a>\n<h2 class=\"chapter\">1 Introduction</h2>\n\n<p>QuickJS is a small and embeddable Javascript engine. It supports the\nES2020 specification\n<a name=\"DOCF1\" href=\"#FOOT1\"><sup>1</sup></a>\nincluding modules, asynchronous generators, proxies and BigInt.\n</p>\n<p>It supports mathematical extensions such as big decimal float float\nnumbers (BigDecimal), big binary floating point numbers (BigFloat),\nand operator overloading.\n</p>\n<a name=\"Main-Features\"></a>\n<h3 class=\"section\">1.1 Main Features</h3>\n\n<ul>\n<li> Small and easily embeddable: just a few C files, no external dependency, 210 KiB of x86 code for a simple &ldquo;hello world&rdquo; program.\n\n</li><li> Fast interpreter with very low startup time: runs the 69000 tests of the ECMAScript Test Suite<a name=\"DOCF2\" href=\"#FOOT2\"><sup>2</sup></a> in about 95 seconds on a single core of a desktop PC. The complete life cycle of a runtime instance completes in less than 300 microseconds.\n\n</li><li> Almost complete ES2020 support including modules, asynchronous\ngenerators and full Annex B support (legacy web compatibility). Many\nfeatures from the upcoming ES2021 specification\n<a name=\"DOCF3\" href=\"#FOOT3\"><sup>3</sup></a> are also supported.\n\n</li><li> Passes nearly 100% of the ECMAScript Test Suite tests when selecting the ES2020 features.\n\n</li><li> Compile Javascript sources to executables with no external dependency.\n\n</li><li> Garbage collection using reference counting (to reduce memory usage and have deterministic behavior) with cycle removal.\n\n</li><li> Mathematical extensions: BigDecimal, BigFloat, operator overloading, bigint mode, math mode.\n\n</li><li> Command line interpreter with contextual colorization and completion implemented in Javascript.\n\n</li><li> Small built-in standard library with C library wrappers.\n\n</li></ul>\n\n<a name=\"Usage\"></a>\n<h2 class=\"chapter\">2 Usage</h2>\n\n<a name=\"Installation\"></a>\n<h3 class=\"section\">2.1 Installation</h3>\n\n<p>A Makefile is provided to compile the engine on Linux or MacOS/X.  A\npreliminary Windows support is available thru cross compilation on a\nLinux host with the MingGW tools.\n</p>\n<p>Edit the top of the <code>Makefile</code> if you wish to select specific\noptions then run <code>make</code>.\n</p>\n<p>You can type <code>make install</code> as root if you wish to install the binaries and support files to\n<code>/usr/local</code> (this is not necessary to use QuickJS).\n</p>\n<a name=\"Quick-start\"></a>\n<h3 class=\"section\">2.2 Quick start</h3>\n\n<p><code>qjs</code> is the command line interpreter (Read-Eval-Print Loop). You can pass\nJavascript files and/or expressions as arguments to execute them:\n</p>\n<div class=\"example\">\n<pre class=\"example\">./qjs examples/hello.js\n</pre></div>\n\n<p><code>qjsc</code> is the command line compiler:\n</p>\n<div class=\"example\">\n<pre class=\"example\">./qjsc -o hello examples/hello.js\n./hello\n</pre></div>\n\n<p>generates a <code>hello</code> executable with no external dependency.\n</p>\n<a name=\"Command-line-options\"></a>\n<h3 class=\"section\">2.3 Command line options</h3>\n\n<a name=\"qjs-interpreter\"></a>\n<h4 class=\"subsection\">2.3.1 <code>qjs</code> interpreter</h4>\n\n<pre class=\"verbatim\">usage: qjs [options] [file [args]]\n</pre>\n<p>Options are:\n</p><dl compact=\"compact\">\n<dt><code>-h</code></dt>\n<dt><code>--help</code></dt>\n<dd><p>List options.\n</p>\n</dd>\n<dt><code>-e <code>EXPR</code></code></dt>\n<dt><code>--eval <code>EXPR</code></code></dt>\n<dd><p>Evaluate EXPR.\n</p>\n</dd>\n<dt><code>-i</code></dt>\n<dt><code>--interactive</code></dt>\n<dd><p>Go to interactive mode (it is not the default when files are provided on the command line).\n</p>\n</dd>\n<dt><code>-m</code></dt>\n<dt><code>--module</code></dt>\n<dd><p>Load as ES6 module (default=autodetect). A module is autodetected if\nthe filename extension is <code>.mjs</code> or if the first keyword of the\nsource is <code>import</code>.\n</p>\n</dd>\n<dt><code>--script</code></dt>\n<dd><p>Load as ES6 script (default=autodetect).\n</p>\n</dd>\n<dt><code>--bignum</code></dt>\n<dd><p>Enable the bignum extensions: BigDecimal object, BigFloat object and\nthe <code>&quot;use math&quot;</code> directive.\n</p>\n</dd>\n<dt><code>-I file</code></dt>\n<dt><code>--include file</code></dt>\n<dd><p>Include an additional file.\n</p>\n</dd>\n</dl>\n\n<p>Advanced options are:\n</p>\n<dl compact=\"compact\">\n<dt><code>--std</code></dt>\n<dd><p>Make the <code>std</code> and <code>os</code> modules available to the loaded\nscript even if it is not a module.\n</p>\n</dd>\n<dt><code>-d</code></dt>\n<dt><code>--dump</code></dt>\n<dd><p>Dump the memory usage stats.\n</p>\n</dd>\n<dt><code>-q</code></dt>\n<dt><code>--quit</code></dt>\n<dd><p>just instantiate the interpreter and quit.\n</p>\n</dd>\n</dl>\n\n<a name=\"qjsc-compiler\"></a>\n<h4 class=\"subsection\">2.3.2 <code>qjsc</code> compiler</h4>\n\n<pre class=\"verbatim\">usage: qjsc [options] [files]\n</pre>\n<p>Options are:\n</p><dl compact=\"compact\">\n<dt><code>-c</code></dt>\n<dd><p>Only output bytecode in a C file. The default is to output an executable file.\n</p></dd>\n<dt><code>-e</code></dt>\n<dd><p>Output <code>main()</code> and bytecode in a C file. The default is to output an\nexecutable file.\n</p></dd>\n<dt><code>-o output</code></dt>\n<dd><p>Set the output filename (default = <samp>out.c</samp> or <samp>a.out</samp>).\n</p>\n</dd>\n<dt><code>-N cname</code></dt>\n<dd><p>Set the C name of the generated data.\n</p>\n</dd>\n<dt><code>-m</code></dt>\n<dd><p>Compile as Javascript module (default=autodetect).\n</p>\n</dd>\n<dt><code>-D module_name</code></dt>\n<dd><p>Compile a dynamically loaded module and its dependencies. This option\nis needed when your code uses the <code>import</code> keyword or the\n<code>os.Worker</code> constructor because the compiler cannot statically\nfind the name of the dynamically loaded modules.\n</p>\n</dd>\n<dt><code>-M module_name[,cname]</code></dt>\n<dd><p>Add initialization code for an external C module. See the\n<code>c_module</code> example.\n</p>\n</dd>\n<dt><code>-x</code></dt>\n<dd><p>Byte swapped output (only used for cross compilation).\n</p>\n</dd>\n<dt><code>-flto</code></dt>\n<dd><p>Use link time optimization. The compilation is slower but the\nexecutable is smaller and faster. This option is automatically set\nwhen the <code>-fno-x</code> options are used.\n</p>\n</dd>\n<dt><code>-fno-[eval|string-normalize|regexp|json|proxy|map|typedarray|promise|bigint]</code></dt>\n<dd><p>Disable selected language features to produce a smaller executable file.\n</p>\n</dd>\n<dt><code>-fbignum</code></dt>\n<dd><p>Enable the bignum extensions: BigDecimal object, BigFloat object and\nthe <code>&quot;use math&quot;</code> directive.\n</p>\n</dd>\n</dl>\n\n<a name=\"qjscalc-application\"></a>\n<h3 class=\"section\">2.4 <code>qjscalc</code> application</h3>\n\n<p>The <code>qjscalc</code> application is a superset of the <code>qjs</code>\ncommand line interpreter implementing a Javascript calculator with\narbitrarily large integer and floating point numbers, fractions,\ncomplex numbers, polynomials and matrices. The source code is in\n<samp>qjscalc.js</samp>. More documentation and a web version are available at\n<a href=\"http://numcalc.com\">http://numcalc.com</a>.\n</p>\n<a name=\"Built_002din-tests\"></a>\n<h3 class=\"section\">2.5 Built-in tests</h3>\n\n<p>Run <code>make test</code> to run the few built-in tests included in the\nQuickJS archive.\n</p>\n<a name=\"Test262-_0028ECMAScript-Test-Suite_0029\"></a>\n<h3 class=\"section\">2.6 Test262 (ECMAScript Test Suite)</h3>\n\n<p>A test262 runner is included in the QuickJS archive. The test262 tests\ncan be installed in the QuickJS source directory with:\n</p>\n<div class=\"example\">\n<pre class=\"example\">git clone https://github.com/tc39/test262.git test262\ncd test262\npatch -p1 &lt; ../tests/test262.patch\ncd ..\n</pre></div>\n\n<p>The patch adds the implementation specific <code>harness</code> functions\nand optimizes the inefficient RegExp character classes and Unicode\nproperty escapes tests (the tests themselves are not modified, only a\nslow string initialization function is optimized).\n</p>\n<p>The tests can be run with\n</p><div class=\"example\">\n<pre class=\"example\">make test2\n</pre></div>\n\n<p>The configuration files <code>test262.conf</code>\n(resp. <code>test262o.conf</code> for the old ES5.1 tests<a name=\"DOCF4\" href=\"#FOOT4\"><sup>4</sup></a>))\ncontain the options to run the various tests. Tests can be excluded\nbased on features or filename.\n</p>\n<p>The file <code>test262_errors.txt</code> contains the current list of\nerrors. The runner displays a message when a new error appears or when\nan existing error is corrected or modified. Use the <code>-u</code> option\nto update the current list of errors (or <code>make test2-update</code>).\n</p>\n<p>The file <code>test262_report.txt</code> contains the logs of all the\ntests. It is useful to have a clearer analysis of a particular\nerror. In case of crash, the last line corresponds to the failing\ntest.\n</p>\n<p>Use the syntax <code>./run-test262 -c test262.conf -f filename.js</code> to\nrun a single test. Use the syntax <code>./run-test262 -c test262.conf\nN</code> to start testing at test number <code>N</code>.\n</p>\n<p>For more information, run <code>./run-test262</code> to see the command line\noptions of the test262 runner.\n</p>\n<p><code>run-test262</code> accepts the <code>-N</code> option to be invoked from\n<code>test262-harness</code><a name=\"DOCF5\" href=\"#FOOT5\"><sup>5</sup></a>\nthru <code>eshost</code>. Unless you want to compare QuickJS with other\nengines under the same conditions, we do not recommend to run the\ntests this way as it is much slower (typically half an hour instead of\nabout 100 seconds).\n</p>\n<a name=\"Specifications\"></a>\n<h2 class=\"chapter\">3 Specifications</h2>\n\n<a name=\"Language-support\"></a>\n<h3 class=\"section\">3.1 Language support</h3>\n\n<a name=\"ES2020-support\"></a>\n<h4 class=\"subsection\">3.1.1 ES2020 support</h4>\n\n<p>The ES2020 specification is almost fully supported including the Annex\nB (legacy web compatibility) and the Unicode related features.\n</p>\n<p>The following features are not supported yet:\n</p>\n<ul>\n<li> Tail calls<a name=\"DOCF6\" href=\"#FOOT6\"><sup>6</sup></a>\n\n</li></ul>\n\n<a name=\"ECMA402\"></a>\n<h4 class=\"subsection\">3.1.2 ECMA402</h4>\n\n<p>ECMA402 (Internationalization API) is not supported.\n</p>\n<a name=\"Extensions\"></a>\n<h4 class=\"subsection\">3.1.3 Extensions</h4>\n\n<ul>\n<li> The directive <code>&quot;use strip&quot;</code> indicates that the debug information (including the source code of the functions) should not be retained to save memory. As <code>&quot;use strict&quot;</code>, the directive can be global to a script or local to a function.\n\n</li><li> The first line of a script beginning with <code>#!</code> is ignored.\n\n</li></ul>\n\n<a name=\"Mathematical-extensions\"></a>\n<h4 class=\"subsection\">3.1.4 Mathematical extensions</h4>\n\n<p>The mathematical extensions are fully backward compatible with\nstandard Javascript. See <code>jsbignum.pdf</code> for more information.\n</p>\n<ul>\n<li> <code>BigDecimal</code> support: arbitrary large floating point numbers in base 10.\n\n</li><li> <code>BigFloat</code> support: arbitrary large floating point numbers in base 2.\n\n</li><li> Operator overloading.\n\n</li><li> The directive <code>&quot;use bigint&quot;</code> enables the bigint mode where integers are <code>BigInt</code> by default.\n\n</li><li> The directive <code>&quot;use math&quot;</code> enables the math mode where the division and power operators on integers produce fractions. Floating point literals are <code>BigFloat</code> by default and integers are <code>BigInt</code> by default.\n\n</li></ul>\n\n<a name=\"Modules\"></a>\n<h3 class=\"section\">3.2 Modules</h3>\n\n<p>ES6 modules are fully supported. The default name resolution is the\nfollowing:\n</p>\n<ul>\n<li> Module names with a leading <code>.</code> or <code>..</code> are relative\nto the current module path.\n\n</li><li> Module names without a leading <code>.</code> or <code>..</code> are system\nmodules, such as <code>std</code> or <code>os</code>.\n\n</li><li> Module names ending with <code>.so</code> are native modules using the\nQuickJS C API.\n\n</li></ul>\n\n<a name=\"Standard-library\"></a>\n<h3 class=\"section\">3.3 Standard library</h3>\n\n<p>The standard library is included by default in the command line\ninterpreter. It contains the two modules <code>std</code> and <code>os</code> and\na few global objects.\n</p>\n<a name=\"Global-objects\"></a>\n<h4 class=\"subsection\">3.3.1 Global objects</h4>\n\n<dl compact=\"compact\">\n<dt><code>scriptArgs</code></dt>\n<dd><p>Provides the command line arguments. The first argument is the script name.\n</p></dd>\n<dt><code>print(...args)</code></dt>\n<dd><p>Print the arguments separated by spaces and a trailing newline.\n</p></dd>\n<dt><code>console.log(...args)</code></dt>\n<dd><p>Same as print().\n</p>\n</dd>\n</dl>\n\n<a name=\"std-module\"></a>\n<h4 class=\"subsection\">3.3.2 <code>std</code> module</h4>\n\n<p>The <code>std</code> module provides wrappers to the libc <samp>stdlib.h</samp>\nand <samp>stdio.h</samp> and a few other utilities.\n</p>\n<p>Available exports:\n</p>\n<dl compact=\"compact\">\n<dt><code>exit(n)</code></dt>\n<dd><p>Exit the process.\n</p>\n</dd>\n<dt><code>evalScript(str, options = undefined)</code></dt>\n<dd><p>Evaluate the string <code>str</code> as a script (global\neval). <code>options</code> is an optional object containing the following\noptional properties:\n</p>\n<dl compact=\"compact\">\n<dt><code>backtrace_barrier</code></dt>\n<dd><p>Boolean (default = false). If true, error backtraces do not list the\n  stack frames below the evalScript.\n  </p></dd>\n</dl>\n\n</dd>\n<dt><code>loadScript(filename)</code></dt>\n<dd><p>Evaluate the file <code>filename</code> as a script (global eval).\n</p>\n</dd>\n<dt><code>loadFile(filename)</code></dt>\n<dd><p>Load the file <code>filename</code> and return it as a string assuming UTF-8\nencoding. Return <code>null</code> in case of I/O error.\n</p>\n</dd>\n<dt><code>open(filename, flags, errorObj = undefined)</code></dt>\n<dd><p>Open a file (wrapper to the libc <code>fopen()</code>). Return the FILE\nobject or <code>null</code> in case of I/O error. If <code>errorObj</code> is not\nundefined, set its <code>errno</code> property to the error code or to 0 if\nno error occured.\n</p>\n</dd>\n<dt><code>popen(command, flags, errorObj = undefined)</code></dt>\n<dd><p>Open a process by creating a pipe (wrapper to the libc\n<code>popen()</code>). Return the FILE\nobject or <code>null</code> in case of I/O error. If <code>errorObj</code> is not\nundefined, set its <code>errno</code> property to the error code or to 0 if\nno error occured.\n</p>\n</dd>\n<dt><code>fdopen(fd, flags, errorObj = undefined)</code></dt>\n<dd><p>Open a file from a file handle (wrapper to the libc\n<code>fdopen()</code>). Return the FILE\nobject or <code>null</code> in case of I/O error. If <code>errorObj</code> is not\nundefined, set its <code>errno</code> property to the error code or to 0 if\nno error occured.\n</p>\n</dd>\n<dt><code>tmpfile(errorObj = undefined)</code></dt>\n<dd><p>Open a temporary file. Return the FILE\nobject or <code>null</code> in case of I/O error. If <code>errorObj</code> is not\nundefined, set its <code>errno</code> property to the error code or to 0 if\nno error occured.\n</p>\n</dd>\n<dt><code>puts(str)</code></dt>\n<dd><p>Equivalent to <code>std.out.puts(str)</code>.\n</p>\n</dd>\n<dt><code>printf(fmt, ...args)</code></dt>\n<dd><p>Equivalent to <code>std.out.printf(fmt, ...args)</code>.\n</p>\n</dd>\n<dt><code>sprintf(fmt, ...args)</code></dt>\n<dd><p>Equivalent to the libc sprintf().\n</p>\n</dd>\n<dt><code>in</code></dt>\n<dt><code>out</code></dt>\n<dt><code>err</code></dt>\n<dd><p>Wrappers to the libc file <code>stdin</code>, <code>stdout</code>, <code>stderr</code>.\n</p>\n</dd>\n<dt><code>SEEK_SET</code></dt>\n<dt><code>SEEK_CUR</code></dt>\n<dt><code>SEEK_END</code></dt>\n<dd><p>Constants for seek().\n</p>\n</dd>\n<dt><code>Error</code></dt>\n<dd>\n<p>Enumeration object containing the integer value of common errors\n(additional error codes may be defined):\n</p>\n<dl compact=\"compact\">\n<dt><code>EINVAL</code></dt>\n<dt><code>EIO</code></dt>\n<dt><code>EACCES</code></dt>\n<dt><code>EEXIST</code></dt>\n<dt><code>ENOSPC</code></dt>\n<dt><code>ENOSYS</code></dt>\n<dt><code>EBUSY</code></dt>\n<dt><code>ENOENT</code></dt>\n<dt><code>EPERM</code></dt>\n<dt><code>EPIPE</code></dt>\n</dl>\n\n</dd>\n<dt><code>strerror(errno)</code></dt>\n<dd><p>Return a string that describes the error <code>errno</code>.\n</p>\n</dd>\n<dt><code>gc()</code></dt>\n<dd><p>Manually invoke the cycle removal algorithm. The cycle removal\nalgorithm is automatically started when needed, so this function is\nuseful in case of specific memory constraints or for testing.\n</p>\n</dd>\n<dt><code>getenv(name)</code></dt>\n<dd><p>Return the value of the environment variable <code>name</code> or\n<code>undefined</code> if it is not defined.\n</p>\n</dd>\n<dt><code>setenv(name, value)</code></dt>\n<dd><p>Set the value of the environment variable <code>name</code> to the string\n<code>value</code>.\n</p>\n</dd>\n<dt><code>unsetenv(name)</code></dt>\n<dd><p>Delete the environment variable <code>name</code>.\n</p>\n</dd>\n<dt><code>getenviron()</code></dt>\n<dd><p>Return an object containing the environment variables as key-value pairs.\n</p>\n</dd>\n<dt><code>urlGet(url, options = undefined)</code></dt>\n<dd>\n<p>Download <code>url</code> using the <samp>curl</samp> command line\nutility. <code>options</code> is an optional object containing the following\noptional properties:\n</p>\n<dl compact=\"compact\">\n<dt><code>binary</code></dt>\n<dd><p>Boolean (default = false). If true, the response is an ArrayBuffer\n  instead of a string. When a string is returned, the data is assumed\n  to be UTF-8 encoded.\n</p>\n</dd>\n<dt><code>full</code></dt>\n<dd>  \n<p>Boolean (default = false). If true, return the an object contains\n  the properties <code>response</code> (response content),\n  <code>responseHeaders</code> (headers separated by CRLF), <code>status</code>\n  (status code). <code>response</code> is <code>null</code> is case of protocol or\n  network error. If <code>full</code> is false, only the response is\n  returned if the status is between 200 and 299. Otherwise <code>null</code>\n  is returned.\n</p>\n</dd>\n</dl>\n\n</dd>\n<dt><code>parseExtJSON(str)</code></dt>\n<dd>\n<p>Parse <code>str</code> using a superset of <code>JSON.parse</code>. The\n  following extensions are accepted:\n</p>\n<ul>\n<li> Single line and multiline comments\n  </li><li> unquoted properties (ASCII-only Javascript identifiers)\n  </li><li> trailing comma in array and object definitions\n  </li><li> single quoted strings\n  </li><li> <code>\\f</code> and <code>\\v</code> are accepted as space characters\n  </li><li> leading plus in numbers\n  </li><li> octal (<code>0o</code> prefix) and hexadecimal (<code>0x</code> prefix) numbers\n  </li></ul>\n</dd>\n</dl>\n\n<p>FILE prototype:\n</p>\n<dl compact=\"compact\">\n<dt><code>close()</code></dt>\n<dd><p>Close the file. Return 0 if OK or <code>-errno</code> in case of I/O error.\n</p></dd>\n<dt><code>puts(str)</code></dt>\n<dd><p>Outputs the string with the UTF-8 encoding.\n</p></dd>\n<dt><code>printf(fmt, ...args)</code></dt>\n<dd><p>Formatted printf.\n</p>\n<p>The same formats as the standard C library <code>printf</code> are\nsupported. Integer format types (e.g. <code>%d</code>) truncate the Numbers\nor BigInts to 32 bits. Use the <code>l</code> modifier (e.g. <code>%ld</code>) to\ntruncate to 64 bits.\n</p>\n</dd>\n<dt><code>flush()</code></dt>\n<dd><p>Flush the buffered file.\n</p></dd>\n<dt><code>seek(offset, whence)</code></dt>\n<dd><p>Seek to a give file position (whence is\n<code>std.SEEK_*</code>). <code>offset</code> can be a number or a bigint. Return\n0 if OK or <code>-errno</code> in case of I/O error.\n</p></dd>\n<dt><code>tell()</code></dt>\n<dd><p>Return the current file position.\n</p></dd>\n<dt><code>tello()</code></dt>\n<dd><p>Return the current file position as a bigint.\n</p></dd>\n<dt><code>eof()</code></dt>\n<dd><p>Return true if end of file.\n</p></dd>\n<dt><code>fileno()</code></dt>\n<dd><p>Return the associated OS handle.\n</p></dd>\n<dt><code>error()</code></dt>\n<dd><p>Return true if there was an error.\n</p></dd>\n<dt><code>clearerr()</code></dt>\n<dd><p>Clear the error indication.\n</p>\n</dd>\n<dt><code>read(buffer, position, length)</code></dt>\n<dd><p>Read <code>length</code> bytes from the file to the ArrayBuffer <code>buffer</code> at byte\nposition <code>position</code> (wrapper to the libc <code>fread</code>).\n</p>\n</dd>\n<dt><code>write(buffer, position, length)</code></dt>\n<dd><p>Write <code>length</code> bytes to the file from the ArrayBuffer <code>buffer</code> at byte\nposition <code>position</code> (wrapper to the libc <code>fwrite</code>).\n</p>\n</dd>\n<dt><code>getline()</code></dt>\n<dd><p>Return the next line from the file, assuming UTF-8 encoding, excluding\nthe trailing line feed.\n</p>\n</dd>\n<dt><code>readAsString(max_size = undefined)</code></dt>\n<dd><p>Read <code>max_size</code> bytes from the file and return them as a string\nassuming UTF-8 encoding. If <code>max_size</code> is not present, the file\nis read up its end.\n</p>\n</dd>\n<dt><code>getByte()</code></dt>\n<dd><p>Return the next byte from the file. Return -1 if the end of file is reached.\n</p>\n</dd>\n<dt><code>putByte(c)</code></dt>\n<dd><p>Write one byte to the file.\n</p></dd>\n</dl>\n\n<a name=\"os-module\"></a>\n<h4 class=\"subsection\">3.3.3 <code>os</code> module</h4>\n\n<p>The <code>os</code> module provides Operating System specific functions:\n</p>\n<ul>\n<li> low level file access\n</li><li> signals\n</li><li> timers\n</li><li> asynchronous I/O\n</li><li> workers (threads)\n</li></ul>\n\n<p>The OS functions usually return 0 if OK or an OS specific negative\nerror code.\n</p>\n<p>Available exports:\n</p>\n<dl compact=\"compact\">\n<dt><code>open(filename, flags, mode = 0o666)</code></dt>\n<dd><p>Open a file. Return a handle or &lt; 0 if error.\n</p>\n</dd>\n<dt><code>O_RDONLY</code></dt>\n<dt><code>O_WRONLY</code></dt>\n<dt><code>O_RDWR</code></dt>\n<dt><code>O_APPEND</code></dt>\n<dt><code>O_CREAT</code></dt>\n<dt><code>O_EXCL</code></dt>\n<dt><code>O_TRUNC</code></dt>\n<dd><p>POSIX open flags.\n</p>\n</dd>\n<dt><code>O_TEXT</code></dt>\n<dd><p>(Windows specific). Open the file in text mode. The default is binary mode.\n</p>\n</dd>\n<dt><code>close(fd)</code></dt>\n<dd><p>Close the file handle <code>fd</code>.\n</p>\n</dd>\n<dt><code>seek(fd, offset, whence)</code></dt>\n<dd><p>Seek in the file. Use <code>std.SEEK_*</code> for\n<code>whence</code>. <code>offset</code> is either a number or a bigint. If\n<code>offset</code> is a bigint, a bigint is returned too.\n</p>\n</dd>\n<dt><code>read(fd, buffer, offset, length)</code></dt>\n<dd><p>Read <code>length</code> bytes from the file handle <code>fd</code> to the\nArrayBuffer <code>buffer</code> at byte position <code>offset</code>.\nReturn the number of read bytes or &lt; 0 if error.\n</p>\n</dd>\n<dt><code>write(fd, buffer, offset, length)</code></dt>\n<dd><p>Write <code>length</code> bytes to the file handle <code>fd</code> from the\nArrayBuffer <code>buffer</code> at byte position <code>offset</code>.\nReturn the number of written bytes or &lt; 0 if error.\n</p>\n</dd>\n<dt><code>isatty(fd)</code></dt>\n<dd><p>Return <code>true</code> is <code>fd</code> is a TTY (terminal) handle.\n</p>\n</dd>\n<dt><code>ttyGetWinSize(fd)</code></dt>\n<dd><p>Return the TTY size as <code>[width, height]</code> or <code>null</code> if not available.\n</p>\n</dd>\n<dt><code>ttySetRaw(fd)</code></dt>\n<dd><p>Set the TTY in raw mode.\n</p>\n</dd>\n<dt><code>remove(filename)</code></dt>\n<dd><p>Remove a file. Return 0 if OK or <code>-errno</code>.\n</p>\n</dd>\n<dt><code>rename(oldname, newname)</code></dt>\n<dd><p>Rename a file. Return 0 if OK or <code>-errno</code>.\n</p>\n</dd>\n<dt><code>realpath(path)</code></dt>\n<dd><p>Return <code>[str, err]</code> where <code>str</code> is the canonicalized absolute\npathname of <code>path</code> and <code>err</code> the error code.\n</p>\n</dd>\n<dt><code>getcwd()</code></dt>\n<dd><p>Return <code>[str, err]</code> where <code>str</code> is the current working directory\nand <code>err</code> the error code.\n</p>\n</dd>\n<dt><code>chdir(path)</code></dt>\n<dd><p>Change the current directory. Return 0 if OK or <code>-errno</code>.\n</p>\n</dd>\n<dt><code>mkdir(path, mode = 0o777)</code></dt>\n<dd><p>Create a directory at <code>path</code>. Return 0 if OK or <code>-errno</code>.\n</p>\n</dd>\n<dt><code>stat(path)</code></dt>\n<dt><code>lstat(path)</code></dt>\n<dd>\n<p>Return <code>[obj, err]</code> where <code>obj</code> is an object containing the\nfile status of <code>path</code>. <code>err</code> is the error code. The\nfollowing fields are defined in <code>obj</code>: dev, ino, mode, nlink,\nuid, gid, rdev, size, blocks, atime, mtime, ctime. The times are\nspecified in milliseconds since 1970. <code>lstat()</code> is the same as\n<code>stat()</code> excepts that it returns information about the link\nitself.\n</p>\n</dd>\n<dt><code>S_IFMT</code></dt>\n<dt><code>S_IFIFO</code></dt>\n<dt><code>S_IFCHR</code></dt>\n<dt><code>S_IFDIR</code></dt>\n<dt><code>S_IFBLK</code></dt>\n<dt><code>S_IFREG</code></dt>\n<dt><code>S_IFSOCK</code></dt>\n<dt><code>S_IFLNK</code></dt>\n<dt><code>S_ISGID</code></dt>\n<dt><code>S_ISUID</code></dt>\n<dd><p>Constants to interpret the <code>mode</code> property returned by\n<code>stat()</code>. They have the same value as in the C system header\n<samp>sys/stat.h</samp>.\n</p>\n</dd>\n<dt><code>utimes(path, atime, mtime)</code></dt>\n<dd><p>Change the access and modification times of the file <code>path</code>. The\ntimes are specified in milliseconds since 1970. Return 0 if OK or <code>-errno</code>.\n</p>\n</dd>\n<dt><code>symlink(target, linkpath)</code></dt>\n<dd><p>Create a link at <code>linkpath</code> containing the string <code>target</code>. Return 0 if OK or <code>-errno</code>.\n</p>\n</dd>\n<dt><code>readlink(path)</code></dt>\n<dd><p>Return <code>[str, err]</code> where <code>str</code> is the link target and <code>err</code>\nthe error code.\n</p>\n</dd>\n<dt><code>readdir(path)</code></dt>\n<dd><p>Return <code>[array, err]</code> where <code>array</code> is an array of strings\ncontaining the filenames of the directory <code>path</code>. <code>err</code> is\nthe error code.\n</p>\n</dd>\n<dt><code>setReadHandler(fd, func)</code></dt>\n<dd><p>Add a read handler to the file handle <code>fd</code>. <code>func</code> is called\neach time there is data pending for <code>fd</code>. A single read handler\nper file handle is supported. Use <code>func = null</code> to remove the\nhandler.\n</p>\n</dd>\n<dt><code>setWriteHandler(fd, func)</code></dt>\n<dd><p>Add a write handler to the file handle <code>fd</code>. <code>func</code> is\ncalled each time data can be written to <code>fd</code>. A single write\nhandler per file handle is supported. Use <code>func = null</code> to remove\nthe handler.\n</p>\n</dd>\n<dt><code>signal(signal, func)</code></dt>\n<dd><p>Call the function <code>func</code> when the signal <code>signal</code>\nhappens. Only a single handler per signal number is supported. Use\n<code>null</code> to set the default handler or <code>undefined</code> to ignore\nthe signal. Signal handlers can only be defined in the main thread.\n</p>\n</dd>\n<dt><code>SIGINT</code></dt>\n<dt><code>SIGABRT</code></dt>\n<dt><code>SIGFPE</code></dt>\n<dt><code>SIGILL</code></dt>\n<dt><code>SIGSEGV</code></dt>\n<dt><code>SIGTERM</code></dt>\n<dd><p>POSIX signal numbers.\n</p>\n</dd>\n<dt><code>kill(pid, sig)</code></dt>\n<dd><p>Send the signal <code>sig</code> to the process <code>pid</code>.\n</p>\n</dd>\n<dt><code>exec(args[, options])</code></dt>\n<dd><p>Execute a process with the arguments <code>args</code>. <code>options</code> is an\nobject containing optional parameters:\n</p>\n<dl compact=\"compact\">\n<dt><code>block</code></dt>\n<dd><p>Boolean (default = true). If true, wait until the process is\n  terminated. In this case, <code>exec</code> return the exit code if positive\n  or the negated signal number if the process was interrupted by a\n  signal. If false, do not block and return the process id of the child.\n</p>  \n</dd>\n<dt><code>usePath</code></dt>\n<dd><p>Boolean (default = true). If true, the file is searched in the\n  <code>PATH</code> environment variable.\n</p>\n</dd>\n<dt><code>file</code></dt>\n<dd><p>String (default = <code>args[0]</code>). Set the file to be executed.\n</p>\n</dd>\n<dt><code>cwd</code></dt>\n<dd><p>String. If present, set the working directory of the new process.\n</p>\n</dd>\n<dt><code>stdin</code></dt>\n<dt><code>stdout</code></dt>\n<dt><code>stderr</code></dt>\n<dd><p>If present, set the handle in the child for stdin, stdout or stderr.\n</p>\n</dd>\n<dt><code>env</code></dt>\n<dd><p>Object. If present, set the process environment from the object\n  key-value pairs. Otherwise use the same environment as the current\n  process.\n</p>\n</dd>\n<dt><code>uid</code></dt>\n<dd><p>Integer. If present, the process uid with <code>setuid</code>.\n</p>\n</dd>\n<dt><code>gid</code></dt>\n<dd><p>Integer. If present, the process gid with <code>setgid</code>.\n</p>\n</dd>\n</dl>\n\n</dd>\n<dt><code>waitpid(pid, options)</code></dt>\n<dd><p><code>waitpid</code> Unix system call. Return the array <code>[ret,\nstatus]</code>. <code>ret</code> contains <code>-errno</code> in case of error.\n</p>\n</dd>\n<dt><code>WNOHANG</code></dt>\n<dd><p>Constant for the <code>options</code> argument of <code>waitpid</code>.\n</p>\n</dd>\n<dt><code>dup(fd)</code></dt>\n<dd><p><code>dup</code> Unix system call.\n</p>\n</dd>\n<dt><code>dup2(oldfd, newfd)</code></dt>\n<dd><p><code>dup2</code> Unix system call.\n</p>\n</dd>\n<dt><code>pipe()</code></dt>\n<dd><p><code>pipe</code> Unix system call. Return two handles as <code>[read_fd,\nwrite_fd]</code> or null in case of error.\n</p>\n</dd>\n<dt><code>sleep(delay_ms)</code></dt>\n<dd><p>Sleep during <code>delay_ms</code> milliseconds.\n</p>\n</dd>\n<dt><code>setTimeout(func, delay)</code></dt>\n<dd><p>Call the function <code>func</code> after <code>delay</code> ms. Return a handle\nto the timer.\n</p>\n</dd>\n<dt><code>clearTimeout(handle)</code></dt>\n<dd><p>Cancel a timer.\n</p>\n</dd>\n<dt><code>platform</code></dt>\n<dd><p>Return a string representing the platform: <code>&quot;linux&quot;</code>, <code>&quot;darwin&quot;</code>,\n<code>&quot;win32&quot;</code> or <code>&quot;js&quot;</code>.\n</p>\n</dd>\n<dt><code>Worker(module_filename)</code></dt>\n<dd><p>Constructor to create a new thread (worker) with an API close to the\n<code>WebWorkers</code>. <code>module_filename</code> is a string specifying the\nmodule filename which is executed in the newly created thread. As for\ndynamically imported module, it is relative to the current script or\nmodule path. Threads normally don&rsquo;t share any data and communicate\nbetween each other with messages. Nested workers are not supported. An\nexample is available in <samp>tests/test_worker.js</samp>.\n</p>\n<p>The worker class has the following static properties:\n</p>\n<dl compact=\"compact\">\n<dt><code>parent</code></dt>\n<dd><p>In the created worker, <code>Worker.parent</code> represents the parent\n  worker and is used to send or receive messages.\n  </p></dd>\n</dl>\n\n<p>The worker instances have the following properties:\n</p>\n<dl compact=\"compact\">\n<dt><code>postMessage(msg)</code></dt>\n<dd>  \n<p>Send a message to the corresponding worker. <code>msg</code> is cloned in\n  the destination worker using an algorithm similar to the <code>HTML</code>\n  structured clone algorithm. <code>SharedArrayBuffer</code> are shared\n  between workers.\n</p>\n<p>Current limitations: <code>Map</code> and <code>Set</code> are not supported\n  yet.\n</p>\n</dd>\n<dt><code>onmessage</code></dt>\n<dd>\n<p>Getter and setter. Set a function which is called each time a\n  message is received. The function is called with a single\n  argument. It is an object with a <code>data</code> property containing the\n  received message. The thread is not terminated if there is at least\n  one non <code>null</code> <code>onmessage</code> handler.\n</p>\n</dd>\n</dl>\n\n</dd>\n</dl>\n\n<a name=\"QuickJS-C-API\"></a>\n<h3 class=\"section\">3.4 QuickJS C API</h3>\n\n<p>The C API was designed to be simple and efficient. The C API is\ndefined in the header <code>quickjs.h</code>.\n</p>\n<a name=\"Runtime-and-contexts\"></a>\n<h4 class=\"subsection\">3.4.1 Runtime and contexts</h4>\n\n<p><code>JSRuntime</code> represents a Javascript runtime corresponding to an\nobject heap. Several runtimes can exist at the same time but they\ncannot exchange objects. Inside a given runtime, no multi-threading is\nsupported.\n</p>\n<p><code>JSContext</code> represents a Javascript context (or Realm). Each\nJSContext has its own global objects and system objects. There can be\nseveral JSContexts per JSRuntime and they can share objects, similar\nto frames of the same origin sharing Javascript objects in a\nweb browser.\n</p>\n<a name=\"JSValue\"></a>\n<h4 class=\"subsection\">3.4.2 JSValue</h4>\n\n<p><code>JSValue</code> represents a Javascript value which can be a primitive\ntype or an object. Reference counting is used, so it is important to\nexplicitly duplicate (<code>JS_DupValue()</code>, increment the reference\ncount) or free (<code>JS_FreeValue()</code>, decrement the reference count)\nJSValues.\n</p>\n<a name=\"C-functions\"></a>\n<h4 class=\"subsection\">3.4.3 C functions</h4>\n\n<p>C functions can be created with\n<code>JS_NewCFunction()</code>. <code>JS_SetPropertyFunctionList()</code> is a\nshortcut to easily add functions, setters and getters properties to a\ngiven object.\n</p>\n<p>Unlike other embedded Javascript engines, there is no implicit stack,\nso C functions get their parameters as normal C parameters. As a\ngeneral rule, C functions take constant <code>JSValue</code>s as parameters\n(so they don&rsquo;t need to free them) and return a newly allocated (=live)\n<code>JSValue</code>.\n</p>\n<a name=\"Exceptions\"></a>\n<h4 class=\"subsection\">3.4.4 Exceptions</h4>\n\n<p>Exceptions: most C functions can return a Javascript exception. It\nmust be explicitly tested and handled by the C code. The specific\n<code>JSValue</code> <code>JS_EXCEPTION</code> indicates that an exception\noccurred. The actual exception object is stored in the\n<code>JSContext</code> and can be retrieved with <code>JS_GetException()</code>.\n</p>\n<a name=\"Script-evaluation\"></a>\n<h4 class=\"subsection\">3.4.5 Script evaluation</h4>\n\n<p>Use <code>JS_Eval()</code> to evaluate a script or module source.\n</p>\n<p>If the script or module was compiled to bytecode with <code>qjsc</code>, it\ncan be evaluated by calling <code>js_std_eval_binary()</code>. The advantage\nis that no compilation is needed so it is faster and smaller because\nthe compiler can be removed from the executable if no <code>eval</code> is\nrequired.\n</p>\n<p>Note: the bytecode format is linked to a given QuickJS\nversion. Moreover, no security check is done before its\nexecution. Hence the bytecode should not be loaded from untrusted\nsources. That&rsquo;s why there is no option to output the bytecode to a\nbinary file in <code>qjsc</code>.\n</p>\n<a name=\"JS-Classes\"></a>\n<h4 class=\"subsection\">3.4.6 JS Classes</h4>\n\n<p>C opaque data can be attached to a Javascript object. The type of the\nC opaque data is determined with the class ID (<code>JSClassID</code>) of\nthe object. Hence the first step is to register a new class ID and JS\nclass (<code>JS_NewClassID()</code>, <code>JS_NewClass()</code>). Then you can\ncreate objects of this class with <code>JS_NewObjectClass()</code> and get or\nset the C opaque point with\n<code>JS_GetOpaque()</code>/<code>JS_SetOpaque()</code>.\n</p>\n<p>When defining a new JS class, it is possible to declare a finalizer\nwhich is called when the object is destroyed. The finalizer should be\nused to release C resources. It is invalid to execute JS code from\nit. A <code>gc_mark</code> method can be provided so that the cycle removal\nalgorithm can find the other objects referenced by this object. Other\nmethods are available to define exotic object behaviors.\n</p>\n<p>The Class ID are globally allocated (i.e. for all runtimes). The\nJSClass are allocated per <code>JSRuntime</code>. <code>JS_SetClassProto()</code>\nis used to define a prototype for a given class in a given\nJSContext. <code>JS_NewObjectClass()</code> sets this prototype in the\ncreated object.\n</p>\n<p>Examples are available in <samp>quickjs-libc.c</samp>.\n</p>\n<a name=\"C-Modules\"></a>\n<h4 class=\"subsection\">3.4.7 C Modules</h4>\n\n<p>Native ES6 modules are supported and can be dynamically or statically\nlinked. Look at the <samp>test_bjson</samp> and <samp>bjson.so</samp>\nexamples. The standard library <samp>quickjs-libc.c</samp> is also a good example\nof a native module.\n</p>\n<a name=\"Memory-handling\"></a>\n<h4 class=\"subsection\">3.4.8 Memory handling</h4>\n\n<p>Use <code>JS_SetMemoryLimit()</code> to set a global memory allocation limit\nto a given JSRuntime.\n</p>\n<p>Custom memory allocation functions can be provided with\n<code>JS_NewRuntime2()</code>.\n</p>\n<p>The maximum system stack size can be set with <code>JS_SetMaxStackSize()</code>.\n</p>\n<a name=\"Execution-timeout-and-interrupts\"></a>\n<h4 class=\"subsection\">3.4.9 Execution timeout and interrupts</h4>\n\n<p>Use <code>JS_SetInterruptHandler()</code> to set a callback which is\nregularly called by the engine when it is executing code. This\ncallback can be used to implement an execution timeout.\n</p>\n<p>It is used by the command line interpreter to implement a\n<code>Ctrl-C</code> handler.\n</p>\n<a name=\"Internals\"></a>\n<h2 class=\"chapter\">4 Internals</h2>\n\n<a name=\"Bytecode\"></a>\n<h3 class=\"section\">4.1 Bytecode</h3>\n\n<p>The compiler generates bytecode directly with no intermediate\nrepresentation such as a parse tree, hence it is very fast. Several\noptimizations passes are done over the generated bytecode.\n</p>\n<p>A stack-based bytecode was chosen because it is simple and generates \ncompact code.\n</p>\n<p>For each function, the maximum stack size is computed at compile time so that\nno runtime stack overflow tests are needed.\n</p>\n<p>A separate compressed line number table is maintained for the debug\ninformation.\n</p>\n<p>Access to closure variables is optimized and is almost as fast as local\nvariables.\n</p>\n<p>Direct <code>eval</code> in strict mode is optimized.\n</p>\n<a name=\"Executable-generation\"></a>\n<h3 class=\"section\">4.2 Executable generation</h3>\n\n<a name=\"qjsc-compiler-1\"></a>\n<h4 class=\"subsection\">4.2.1 <code>qjsc</code> compiler</h4>\n\n<p>The <code>qjsc</code> compiler generates C sources from Javascript files. By\ndefault the C sources are compiled with the system compiler\n(<code>gcc</code> or <code>clang</code>).\n</p>\n<p>The generated C source contains the bytecode of the compiled functions\nor modules. If a full complete executable is needed, it also\ncontains a <code>main()</code> function with the necessary C code to initialize the\nJavascript engine and to load and execute the compiled functions and\nmodules.\n</p>\n<p>Javascript code can be mixed with C modules.\n</p>\n<p>In order to have smaller executables, specific Javascript features can\nbe disabled, in particular <code>eval</code> or the regular expressions. The\ncode removal relies on the Link Time Optimization of the system\ncompiler.\n</p>\n<a name=\"Binary-JSON\"></a>\n<h4 class=\"subsection\">4.2.2 Binary JSON</h4>\n\n<p><code>qjsc</code> works by compiling scripts or modules and then serializing\nthem to a binary format. A subset of this format (without functions or\nmodules) can be used as binary JSON. The example <samp>test_bjson.js</samp>\nshows how to use it.\n</p>\n<p>Warning: the binary JSON format may change without notice, so it\nshould not be used to store persistent data. The <samp>test_bjson.js</samp>\nexample is only used to test the binary object format functions.\n</p>\n<a name=\"Runtime\"></a>\n<h3 class=\"section\">4.3 Runtime</h3>\n\n<a name=\"Strings\"></a>\n<h4 class=\"subsection\">4.3.1 Strings</h4>\n\n<p>Strings are stored either as an 8 bit or a 16 bit array of\ncharacters. Hence random access to characters is always fast.\n</p>\n<p>The C API provides functions to convert Javascript Strings to C UTF-8 encoded\nstrings. The most common case where the Javascript string contains\nonly ASCII characters involves no copying.\n</p>\n<a name=\"Objects\"></a>\n<h4 class=\"subsection\">4.3.2 Objects</h4>\n\n<p>The object shapes (object prototype, property names and flags) are shared\nbetween objects to save memory.\n</p>\n<p>Arrays with no holes (except at the end of the array) are optimized.\n</p>\n<p>TypedArray accesses are optimized.\n</p>\n<a name=\"Atoms\"></a>\n<h4 class=\"subsection\">4.3.3 Atoms</h4>\n\n<p>Object property names and some strings are stored as Atoms (unique\nstrings) to save memory and allow fast comparison. Atoms are\nrepresented as a 32 bit integer. Half of the atom range is reserved for\nimmediate integer literals from <em>0</em> to <em>2^{31}-1</em>.\n</p>\n<a name=\"Numbers\"></a>\n<h4 class=\"subsection\">4.3.4 Numbers</h4>\n\n<p>Numbers are represented either as 32-bit signed integers or 64-bit IEEE-754\nfloating point values. Most operations have fast paths for the 32-bit\ninteger case.\n</p>\n<a name=\"Garbage-collection\"></a>\n<h4 class=\"subsection\">4.3.5 Garbage collection</h4>\n\n<p>Reference counting is used to free objects automatically and\ndeterministically. A separate cycle removal pass is done when the allocated\nmemory becomes too large. The cycle removal algorithm only uses the\nreference counts and the object content, so no explicit garbage\ncollection roots need to be manipulated in the C code.\n</p>\n<a name=\"JSValue-1\"></a>\n<h4 class=\"subsection\">4.3.6 JSValue</h4>\n\n<p>It is a Javascript value which can be a primitive type (such as\nNumber, String, ...) or an Object. NaN boxing is used in the 32-bit version\nto store 64-bit floating point numbers. The representation is\noptimized so that 32-bit integers and reference counted values can be\nefficiently tested.\n</p>\n<p>In 64-bit code, JSValue are 128-bit large and no NaN boxing is used. The\nrationale is that in 64-bit code memory usage is less critical.\n</p>\n<p>In both cases (32 or 64 bits), JSValue exactly fits two CPU registers,\nso it can be efficiently returned by C functions.\n</p>\n<a name=\"Function-call\"></a>\n<h4 class=\"subsection\">4.3.7 Function call</h4>\n\n<p>The engine is optimized so that function calls are fast. The system\nstack holds the Javascript parameters and local variables.\n</p>\n<a name=\"RegExp\"></a>\n<h3 class=\"section\">4.4 RegExp</h3>\n\n<p>A specific regular expression engine was developed. It is both small\nand efficient and supports all the ES2020 features including the\nUnicode properties. As the Javascript compiler, it directly generates\nbytecode without a parse tree.\n</p>\n<p>Backtracking with an explicit stack is used so that there is no\nrecursion on the system stack. Simple quantifiers are specifically\noptimized to avoid recursions.\n</p>\n<p>Infinite recursions coming from quantifiers with empty terms are\navoided.\n</p>\n<p>The full regexp library weights about 15 KiB (x86 code), excluding the\nUnicode library.\n</p>\n<a name=\"Unicode\"></a>\n<h3 class=\"section\">4.5 Unicode</h3>\n\n<p>A specific Unicode library was developed so that there is no\ndependency on an external large Unicode library such as ICU. All the\nUnicode tables are compressed while keeping a reasonable access\nspeed.\n</p>\n<p>The library supports case conversion, Unicode normalization, Unicode\nscript queries, Unicode general category queries and all Unicode\nbinary properties.\n</p>\n<p>The full Unicode library weights about 45 KiB (x86 code).\n</p>\n<a name=\"BigInt_002c-BigFloat_002c-BigDecimal\"></a>\n<h3 class=\"section\">4.6 BigInt, BigFloat, BigDecimal</h3>\n\n<p>BigInt, BigFloat and BigDecimal are implemented with the <code>libbf</code>\nlibrary<a name=\"DOCF7\" href=\"#FOOT7\"><sup>7</sup></a>. It weights about 90\nKiB (x86 code) and provides arbitrary precision IEEE 754 floating\npoint operations and transcendental functions with exact rounding.\n</p>\n<a name=\"License\"></a>\n<h2 class=\"chapter\">5 License</h2>\n\n<p>QuickJS is released under the MIT license.\n</p>\n<p>Unless otherwise specified, the QuickJS sources are copyright Fabrice\nBellard and Charlie Gordon.\n</p>\n<div class=\"footnote\">\n<hr>\n<h4 class=\"footnotes-heading\">Footnotes</h4>\n\n<h3><a name=\"FOOT1\" href=\"#DOCF1\">(1)</a></h3>\n<p><a href=\"https://tc39.es/ecma262/\">https://tc39.es/ecma262/</a></p>\n<h3><a name=\"FOOT2\" href=\"#DOCF2\">(2)</a></h3>\n<p><a href=\"https://github.com/tc39/test262\">https://github.com/tc39/test262</a></p>\n<h3><a name=\"FOOT3\" href=\"#DOCF3\">(3)</a></h3>\n<p><a href=\"https://tc39.github.io/ecma262/\">https://tc39.github.io/ecma262/</a></p>\n<h3><a name=\"FOOT4\" href=\"#DOCF4\">(4)</a></h3>\n<p>The old\nES5.1 tests can be extracted with <code>git clone --single-branch\n--branch es5-tests https://github.com/tc39/test262.git test262o</code></p>\n<h3><a name=\"FOOT5\" href=\"#DOCF5\">(5)</a></h3>\n<p><a href=\"https://github.com/bterlson/test262-harness\">https://github.com/bterlson/test262-harness</a></p>\n<h3><a name=\"FOOT6\" href=\"#DOCF6\">(6)</a></h3>\n<p>We believe the current specification of tails calls is too complicated and presents limited practical interests.</p>\n<h3><a name=\"FOOT7\" href=\"#DOCF7\">(7)</a></h3>\n<p><a href=\"https://bellard.org/libbf\">https://bellard.org/libbf</a></p>\n</div>\n<hr>\n\n\n\n</body>\n</html>\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/doc/quickjs.texi",
    "content": "\\input texinfo\n\n@iftex\n@afourpaper\n@headings double\n@end iftex\n\n@titlepage\n@afourpaper\n@sp 7\n@center @titlefont{QuickJS Javascript Engine}\n@sp 3\n@end titlepage\n\n@setfilename spec.info\n@settitle QuickJS Javascript Engine\n\n@contents\n\n@chapter Introduction\n\nQuickJS is a small and embeddable Javascript engine. It supports the\nES2020 specification\n@footnote{@url{https://tc39.es/ecma262/}}\nincluding modules, asynchronous generators, proxies and BigInt.\n\nIt supports mathematical extensions such as big decimal float float\nnumbers (BigDecimal), big binary floating point numbers (BigFloat),\nand operator overloading.\n\n@section Main Features\n\n@itemize\n\n@item Small and easily embeddable: just a few C files, no external dependency, 210 KiB of x86 code for a simple ``hello world'' program.\n\n@item Fast interpreter with very low startup time: runs the 69000 tests of the ECMAScript Test Suite@footnote{@url{https://github.com/tc39/test262}} in about 95 seconds on a single core of a desktop PC. The complete life cycle of a runtime instance completes in less than 300 microseconds.\n\n@item Almost complete ES2020 support including modules, asynchronous\ngenerators and full Annex B support (legacy web compatibility). Many\nfeatures from the upcoming ES2021 specification\n@footnote{@url{https://tc39.github.io/ecma262/}} are also supported.\n\n@item Passes nearly 100% of the ECMAScript Test Suite tests when selecting the ES2020 features.\n\n@item Compile Javascript sources to executables with no external dependency.\n\n@item Garbage collection using reference counting (to reduce memory usage and have deterministic behavior) with cycle removal.\n\n@item Mathematical extensions: BigDecimal, BigFloat, operator overloading, bigint mode, math mode.\n\n@item Command line interpreter with contextual colorization and completion implemented in Javascript.\n\n@item Small built-in standard library with C library wrappers.\n\n@end itemize\n\n@chapter Usage\n\n@section Installation\n\nA Makefile is provided to compile the engine on Linux or MacOS/X.  A\npreliminary Windows support is available thru cross compilation on a\nLinux host with the MingGW tools.\n\nEdit the top of the @code{Makefile} if you wish to select specific\noptions then run @code{make}.\n\nYou can type @code{make install} as root if you wish to install the binaries and support files to\n@code{/usr/local} (this is not necessary to use QuickJS).\n\n@section Quick start\n\n@code{qjs} is the command line interpreter (Read-Eval-Print Loop). You can pass\nJavascript files and/or expressions as arguments to execute them:\n\n@example\n./qjs examples/hello.js\n@end example\n\n@code{qjsc} is the command line compiler:\n\n@example\n./qjsc -o hello examples/hello.js\n./hello\n@end example\n\ngenerates a @code{hello} executable with no external dependency.\n\n@section Command line options\n\n@subsection @code{qjs} interpreter\n\n@verbatim\nusage: qjs [options] [file [args]]\n@end verbatim\n\nOptions are:\n@table @code\n@item -h\n@item --help\nList options.\n\n@item -e @code{EXPR}\n@item --eval @code{EXPR}\nEvaluate EXPR.\n\n@item -i\n@item --interactive\nGo to interactive mode (it is not the default when files are provided on the command line).\n\n@item -m\n@item --module\nLoad as ES6 module (default=autodetect). A module is autodetected if\nthe filename extension is @code{.mjs} or if the first keyword of the\nsource is @code{import}.\n\n@item --script\nLoad as ES6 script (default=autodetect).\n\n@item --bignum\nEnable the bignum extensions: BigDecimal object, BigFloat object and\nthe @code{\"use math\"} directive.\n\n@item -I file\n@item --include file\nInclude an additional file.\n\n@end table\n\nAdvanced options are:\n\n@table @code\n@item --std\nMake the @code{std} and @code{os} modules available to the loaded\nscript even if it is not a module.\n\n@item -d\n@item --dump\nDump the memory usage stats.\n\n@item -q\n@item --quit\njust instantiate the interpreter and quit.\n\n@end table\n\n@subsection @code{qjsc} compiler\n\n@verbatim\nusage: qjsc [options] [files]\n@end verbatim\n\nOptions are:\n@table @code\n@item -c\nOnly output bytecode in a C file. The default is to output an executable file.\n@item -e \nOutput @code{main()} and bytecode in a C file. The default is to output an\nexecutable file.\n@item -o output\nSet the output filename (default = @file{out.c} or @file{a.out}).\n\n@item -N cname\nSet the C name of the generated data.\n\n@item -m\nCompile as Javascript module (default=autodetect).\n\n@item -D module_name\nCompile a dynamically loaded module and its dependencies. This option\nis needed when your code uses the @code{import} keyword or the\n@code{os.Worker} constructor because the compiler cannot statically\nfind the name of the dynamically loaded modules.\n\n@item -M module_name[,cname]\nAdd initialization code for an external C module. See the\n@code{c_module} example.\n\n@item -x\nByte swapped output (only used for cross compilation).\n\n@item -flto\nUse link time optimization. The compilation is slower but the\nexecutable is smaller and faster. This option is automatically set\nwhen the @code{-fno-x} options are used.\n\n@item -fno-[eval|string-normalize|regexp|json|proxy|map|typedarray|promise|bigint]\nDisable selected language features to produce a smaller executable file.\n\n@item -fbignum\nEnable the bignum extensions: BigDecimal object, BigFloat object and\nthe @code{\"use math\"} directive.\n\n@end table\n\n@section @code{qjscalc} application\n\nThe @code{qjscalc} application is a superset of the @code{qjs}\ncommand line interpreter implementing a Javascript calculator with\narbitrarily large integer and floating point numbers, fractions,\ncomplex numbers, polynomials and matrices. The source code is in\n@file{qjscalc.js}. More documentation and a web version are available at\n@url{http://numcalc.com}.\n\n@section Built-in tests\n\nRun @code{make test} to run the few built-in tests included in the\nQuickJS archive.\n\n@section Test262 (ECMAScript Test Suite)\n\nA test262 runner is included in the QuickJS archive. The test262 tests\ncan be installed in the QuickJS source directory with:\n\n@example\ngit clone https://github.com/tc39/test262.git test262\ncd test262\npatch -p1 < ../tests/test262.patch\ncd ..\n@end example\n\nThe patch adds the implementation specific @code{harness} functions\nand optimizes the inefficient RegExp character classes and Unicode\nproperty escapes tests (the tests themselves are not modified, only a\nslow string initialization function is optimized).\n\nThe tests can be run with\n@example\nmake test2\n@end example\n\nThe configuration files @code{test262.conf}\n(resp. @code{test262o.conf} for the old ES5.1 tests@footnote{The old\nES5.1 tests can be extracted with @code{git clone --single-branch\n--branch es5-tests https://github.com/tc39/test262.git test262o}}))\ncontain the options to run the various tests. Tests can be excluded\nbased on features or filename.\n\nThe file @code{test262_errors.txt} contains the current list of\nerrors. The runner displays a message when a new error appears or when\nan existing error is corrected or modified. Use the @code{-u} option\nto update the current list of errors (or @code{make test2-update}).\n\nThe file @code{test262_report.txt} contains the logs of all the\ntests. It is useful to have a clearer analysis of a particular\nerror. In case of crash, the last line corresponds to the failing\ntest.\n\nUse the syntax @code{./run-test262 -c test262.conf -f filename.js} to\nrun a single test. Use the syntax @code{./run-test262 -c test262.conf\nN} to start testing at test number @code{N}.\n\nFor more information, run @code{./run-test262} to see the command line\noptions of the test262 runner.\n\n@code{run-test262} accepts the @code{-N} option to be invoked from\n@code{test262-harness}@footnote{@url{https://github.com/bterlson/test262-harness}}\nthru @code{eshost}. Unless you want to compare QuickJS with other\nengines under the same conditions, we do not recommend to run the\ntests this way as it is much slower (typically half an hour instead of\nabout 100 seconds).\n\n@chapter Specifications\n\n@section Language support\n\n@subsection ES2020 support\n\nThe ES2020 specification is almost fully supported including the Annex\nB (legacy web compatibility) and the Unicode related features.\n\nThe following features are not supported yet:\n\n@itemize\n\n@item Tail calls@footnote{We believe the current specification of tails calls is too complicated and presents limited practical interests.}\n\n@end itemize\n\n@subsection ECMA402\n\nECMA402 (Internationalization API) is not supported.\n\n@subsection Extensions\n\n@itemize\n\n@item The directive @code{\"use strip\"} indicates that the debug information (including the source code of the functions) should not be retained to save memory. As @code{\"use strict\"}, the directive can be global to a script or local to a function.\n\n@item The first line of a script beginning with @code{#!} is ignored.\n\n@end itemize\n\n@subsection Mathematical extensions\n\nThe mathematical extensions are fully backward compatible with\nstandard Javascript. See @code{jsbignum.pdf} for more information.\n\n@itemize\n\n@item @code{BigDecimal} support: arbitrary large floating point numbers in base 10.\n\n@item @code{BigFloat} support: arbitrary large floating point numbers in base 2.\n\n@item Operator overloading.\n\n@item The directive @code{\"use bigint\"} enables the bigint mode where integers are @code{BigInt} by default.\n\n@item The directive @code{\"use math\"} enables the math mode where the division and power operators on integers produce fractions. Floating point literals are @code{BigFloat} by default and integers are @code{BigInt} by default.\n\n@end itemize\n\n@section Modules\n\nES6 modules are fully supported. The default name resolution is the\nfollowing:\n\n@itemize\n\n@item Module names with a leading @code{.} or @code{..} are relative\nto the current module path.\n\n@item Module names without a leading @code{.} or @code{..} are system\nmodules, such as @code{std} or @code{os}.\n\n@item Module names ending with @code{.so} are native modules using the\nQuickJS C API.\n\n@end itemize\n\n@section Standard library\n\nThe standard library is included by default in the command line\ninterpreter. It contains the two modules @code{std} and @code{os} and\na few global objects.\n\n@subsection Global objects\n\n@table @code\n@item scriptArgs\nProvides the command line arguments. The first argument is the script name.\n@item print(...args)\nPrint the arguments separated by spaces and a trailing newline.\n@item console.log(...args)\nSame as print().\n\n@end table\n\n@subsection @code{std} module\n\nThe @code{std} module provides wrappers to the libc @file{stdlib.h}\nand @file{stdio.h} and a few other utilities.\n\nAvailable exports:\n\n@table @code\n\n@item exit(n)\nExit the process.\n\n@item evalScript(str, options = undefined)\nEvaluate the string @code{str} as a script (global\neval). @code{options} is an optional object containing the following\noptional properties:\n\n  @table @code\n  @item backtrace_barrier\n  Boolean (default = false). If true, error backtraces do not list the\n  stack frames below the evalScript.\n  @end table\n\n@item loadScript(filename)\nEvaluate the file @code{filename} as a script (global eval).\n\n@item loadFile(filename)\nLoad the file @code{filename} and return it as a string assuming UTF-8\nencoding. Return @code{null} in case of I/O error.\n\n@item open(filename, flags, errorObj = undefined)\nOpen a file (wrapper to the libc @code{fopen()}). Return the FILE\nobject or @code{null} in case of I/O error. If @code{errorObj} is not\nundefined, set its @code{errno} property to the error code or to 0 if\nno error occured.\n\n@item popen(command, flags, errorObj = undefined)\nOpen a process by creating a pipe (wrapper to the libc\n@code{popen()}). Return the FILE\nobject or @code{null} in case of I/O error. If @code{errorObj} is not\nundefined, set its @code{errno} property to the error code or to 0 if\nno error occured.\n\n@item fdopen(fd, flags, errorObj = undefined)\nOpen a file from a file handle (wrapper to the libc\n@code{fdopen()}). Return the FILE\nobject or @code{null} in case of I/O error. If @code{errorObj} is not\nundefined, set its @code{errno} property to the error code or to 0 if\nno error occured.\n\n@item tmpfile(errorObj = undefined)\nOpen a temporary file. Return the FILE\nobject or @code{null} in case of I/O error. If @code{errorObj} is not\nundefined, set its @code{errno} property to the error code or to 0 if\nno error occured.\n\n@item puts(str)\nEquivalent to @code{std.out.puts(str)}.\n\n@item printf(fmt, ...args)\nEquivalent to @code{std.out.printf(fmt, ...args)}.\n\n@item sprintf(fmt, ...args)\nEquivalent to the libc sprintf().\n\n@item in\n@item out\n@item err\nWrappers to the libc file @code{stdin}, @code{stdout}, @code{stderr}.\n\n@item SEEK_SET\n@item SEEK_CUR\n@item SEEK_END\nConstants for seek().\n\n@item Error\n\nEnumeration object containing the integer value of common errors\n(additional error codes may be defined):\n\n  @table @code\n  @item EINVAL\n  @item EIO\n  @item EACCES\n  @item EEXIST\n  @item ENOSPC\n  @item ENOSYS\n  @item EBUSY\n  @item ENOENT\n  @item EPERM\n  @item EPIPE\n  @end table\n\n@item strerror(errno)\nReturn a string that describes the error @code{errno}.\n\n@item gc()\nManually invoke the cycle removal algorithm. The cycle removal\nalgorithm is automatically started when needed, so this function is\nuseful in case of specific memory constraints or for testing.\n\n@item getenv(name)\nReturn the value of the environment variable @code{name} or\n@code{undefined} if it is not defined.\n\n@item setenv(name, value)\nSet the value of the environment variable @code{name} to the string\n@code{value}.\n\n@item unsetenv(name)\nDelete the environment variable @code{name}.\n\n@item getenviron()\nReturn an object containing the environment variables as key-value pairs.\n\n@item urlGet(url, options = undefined)\n\nDownload @code{url} using the @file{curl} command line\nutility. @code{options} is an optional object containing the following\noptional properties:\n\n  @table @code\n  @item binary\n  Boolean (default = false). If true, the response is an ArrayBuffer\n  instead of a string. When a string is returned, the data is assumed\n  to be UTF-8 encoded.\n\n  @item full\n  \n  Boolean (default = false). If true, return the an object contains\n  the properties @code{response} (response content),\n  @code{responseHeaders} (headers separated by CRLF), @code{status}\n  (status code). @code{response} is @code{null} is case of protocol or\n  network error. If @code{full} is false, only the response is\n  returned if the status is between 200 and 299. Otherwise @code{null}\n  is returned.\n\n  @end table\n\n@item parseExtJSON(str)\n\n  Parse @code{str} using a superset of @code{JSON.parse}. The\n  following extensions are accepted:\n\n  @itemize\n  @item Single line and multiline comments\n  @item unquoted properties (ASCII-only Javascript identifiers)\n  @item trailing comma in array and object definitions\n  @item single quoted strings\n  @item @code{\\f} and @code{\\v} are accepted as space characters\n  @item leading plus in numbers\n  @item octal (@code{0o} prefix) and hexadecimal (@code{0x} prefix) numbers\n  @end itemize\n@end table\n\nFILE prototype:\n\n@table @code\n@item close()\nClose the file. Return 0 if OK or @code{-errno} in case of I/O error.\n@item puts(str)\nOutputs the string with the UTF-8 encoding.\n@item printf(fmt, ...args)\nFormatted printf.\n\nThe same formats as the standard C library @code{printf} are\nsupported. Integer format types (e.g. @code{%d}) truncate the Numbers\nor BigInts to 32 bits. Use the @code{l} modifier (e.g. @code{%ld}) to\ntruncate to 64 bits.\n\n@item flush()\nFlush the buffered file.\n@item seek(offset, whence)\nSeek to a give file position (whence is\n@code{std.SEEK_*}). @code{offset} can be a number or a bigint. Return\n0 if OK or @code{-errno} in case of I/O error.\n@item tell()\nReturn the current file position.\n@item tello()\nReturn the current file position as a bigint.\n@item eof()\nReturn true if end of file.\n@item fileno()\nReturn the associated OS handle.\n@item error()\nReturn true if there was an error.\n@item clearerr()\nClear the error indication.\n\n@item read(buffer, position, length)\nRead @code{length} bytes from the file to the ArrayBuffer @code{buffer} at byte\nposition @code{position} (wrapper to the libc @code{fread}).\n\n@item write(buffer, position, length)\nWrite @code{length} bytes to the file from the ArrayBuffer @code{buffer} at byte\nposition @code{position} (wrapper to the libc @code{fwrite}).\n\n@item getline()\nReturn the next line from the file, assuming UTF-8 encoding, excluding\nthe trailing line feed.\n\n@item readAsString(max_size = undefined)\nRead @code{max_size} bytes from the file and return them as a string\nassuming UTF-8 encoding. If @code{max_size} is not present, the file\nis read up its end.\n\n@item getByte()\nReturn the next byte from the file. Return -1 if the end of file is reached.\n\n@item putByte(c)\nWrite one byte to the file.\n@end table\n\n@subsection @code{os} module\n\nThe @code{os} module provides Operating System specific functions:\n\n@itemize\n@item low level file access\n@item signals\n@item timers\n@item asynchronous I/O\n@item workers (threads)\n@end itemize\n\nThe OS functions usually return 0 if OK or an OS specific negative\nerror code.\n\nAvailable exports:\n\n@table @code\n@item open(filename, flags, mode = 0o666)\nOpen a file. Return a handle or < 0 if error.\n\n@item O_RDONLY\n@item O_WRONLY        \n@item O_RDWR\n@item O_APPEND\n@item O_CREAT\n@item O_EXCL\n@item O_TRUNC\nPOSIX open flags.\n\n@item O_TEXT\n(Windows specific). Open the file in text mode. The default is binary mode.\n\n@item close(fd)\nClose the file handle @code{fd}.\n\n@item seek(fd, offset, whence)\nSeek in the file. Use @code{std.SEEK_*} for\n@code{whence}. @code{offset} is either a number or a bigint. If\n@code{offset} is a bigint, a bigint is returned too.\n\n@item read(fd, buffer, offset, length)\nRead @code{length} bytes from the file handle @code{fd} to the\nArrayBuffer @code{buffer} at byte position @code{offset}.\nReturn the number of read bytes or < 0 if error.\n\n@item write(fd, buffer, offset, length)\nWrite @code{length} bytes to the file handle @code{fd} from the\nArrayBuffer @code{buffer} at byte position @code{offset}.\nReturn the number of written bytes or < 0 if error.\n\n@item isatty(fd)\nReturn @code{true} is @code{fd} is a TTY (terminal) handle.\n\n@item ttyGetWinSize(fd)\nReturn the TTY size as @code{[width, height]} or @code{null} if not available.\n\n@item ttySetRaw(fd)\nSet the TTY in raw mode.\n\n@item remove(filename)\nRemove a file. Return 0 if OK or @code{-errno}.\n\n@item rename(oldname, newname)\nRename a file. Return 0 if OK or @code{-errno}.\n\n@item realpath(path)\nReturn @code{[str, err]} where @code{str} is the canonicalized absolute\npathname of @code{path} and @code{err} the error code.\n\n@item getcwd()\nReturn @code{[str, err]} where @code{str} is the current working directory\nand @code{err} the error code.\n\n@item chdir(path)\nChange the current directory. Return 0 if OK or @code{-errno}.\n\n@item mkdir(path, mode = 0o777)\nCreate a directory at @code{path}. Return 0 if OK or @code{-errno}.\n\n@item stat(path)\n@item lstat(path)\n\nReturn @code{[obj, err]} where @code{obj} is an object containing the\nfile status of @code{path}. @code{err} is the error code. The\nfollowing fields are defined in @code{obj}: dev, ino, mode, nlink,\nuid, gid, rdev, size, blocks, atime, mtime, ctime. The times are\nspecified in milliseconds since 1970. @code{lstat()} is the same as\n@code{stat()} excepts that it returns information about the link\nitself.\n\n@item S_IFMT\n@item S_IFIFO\n@item S_IFCHR\n@item S_IFDIR\n@item S_IFBLK\n@item S_IFREG\n@item S_IFSOCK\n@item S_IFLNK\n@item S_ISGID\n@item S_ISUID\nConstants to interpret the @code{mode} property returned by\n@code{stat()}. They have the same value as in the C system header\n@file{sys/stat.h}.\n\n@item utimes(path, atime, mtime)\nChange the access and modification times of the file @code{path}. The\ntimes are specified in milliseconds since 1970. Return 0 if OK or @code{-errno}.\n\n@item symlink(target, linkpath)\nCreate a link at @code{linkpath} containing the string @code{target}. Return 0 if OK or @code{-errno}.\n\n@item readlink(path)\nReturn @code{[str, err]} where @code{str} is the link target and @code{err}\nthe error code.\n\n@item readdir(path)\nReturn @code{[array, err]} where @code{array} is an array of strings\ncontaining the filenames of the directory @code{path}. @code{err} is\nthe error code.\n\n@item setReadHandler(fd, func)\nAdd a read handler to the file handle @code{fd}. @code{func} is called\neach time there is data pending for @code{fd}. A single read handler\nper file handle is supported. Use @code{func = null} to remove the\nhandler.\n\n@item setWriteHandler(fd, func)\nAdd a write handler to the file handle @code{fd}. @code{func} is\ncalled each time data can be written to @code{fd}. A single write\nhandler per file handle is supported. Use @code{func = null} to remove\nthe handler.\n\n@item signal(signal, func)\nCall the function @code{func} when the signal @code{signal}\nhappens. Only a single handler per signal number is supported. Use\n@code{null} to set the default handler or @code{undefined} to ignore\nthe signal. Signal handlers can only be defined in the main thread.\n\n@item SIGINT\n@item SIGABRT\n@item SIGFPE\n@item SIGILL\n@item SIGSEGV\n@item SIGTERM\nPOSIX signal numbers.\n\n@item kill(pid, sig)\nSend the signal @code{sig} to the process @code{pid}.\n\n@item exec(args[, options])\nExecute a process with the arguments @code{args}. @code{options} is an\nobject containing optional parameters:\n\n  @table @code\n  @item block\n  Boolean (default = true). If true, wait until the process is\n  terminated. In this case, @code{exec} return the exit code if positive\n  or the negated signal number if the process was interrupted by a\n  signal. If false, do not block and return the process id of the child.\n  \n  @item usePath\n  Boolean (default = true). If true, the file is searched in the\n  @code{PATH} environment variable.\n\n  @item file\n  String (default = @code{args[0]}). Set the file to be executed.\n\n  @item cwd\n  String. If present, set the working directory of the new process.\n\n  @item stdin\n  @item stdout\n  @item stderr\n  If present, set the handle in the child for stdin, stdout or stderr.\n\n  @item env\n  Object. If present, set the process environment from the object\n  key-value pairs. Otherwise use the same environment as the current\n  process.\n\n  @item uid\n  Integer. If present, the process uid with @code{setuid}.\n\n  @item gid \n  Integer. If present, the process gid with @code{setgid}.\n\n  @end table\n\n@item waitpid(pid, options)\n@code{waitpid} Unix system call. Return the array @code{[ret,\nstatus]}. @code{ret} contains @code{-errno} in case of error.\n\n@item WNOHANG\nConstant for the @code{options} argument of @code{waitpid}.\n\n@item dup(fd)\n@code{dup} Unix system call.\n\n@item dup2(oldfd, newfd)\n@code{dup2} Unix system call.\n\n@item pipe()\n@code{pipe} Unix system call. Return two handles as @code{[read_fd,\nwrite_fd]} or null in case of error.\n\n@item sleep(delay_ms)\nSleep during @code{delay_ms} milliseconds.\n\n@item setTimeout(func, delay)\nCall the function @code{func} after @code{delay} ms. Return a handle\nto the timer.\n\n@item clearTimeout(handle)\nCancel a timer.\n\n@item platform\nReturn a string representing the platform: @code{\"linux\"}, @code{\"darwin\"},\n@code{\"win32\"} or @code{\"js\"}.\n\n@item Worker(module_filename)\nConstructor to create a new thread (worker) with an API close to the\n@code{WebWorkers}. @code{module_filename} is a string specifying the\nmodule filename which is executed in the newly created thread. As for\ndynamically imported module, it is relative to the current script or\nmodule path. Threads normally don't share any data and communicate\nbetween each other with messages. Nested workers are not supported. An\nexample is available in @file{tests/test_worker.js}.\n\nThe worker class has the following static properties:\n\n  @table @code\n  @item parent\n  In the created worker, @code{Worker.parent} represents the parent\n  worker and is used to send or receive messages.\n  @end table\n\nThe worker instances have the following properties:\n\n  @table @code\n  @item postMessage(msg)\n  \n  Send a message to the corresponding worker. @code{msg} is cloned in\n  the destination worker using an algorithm similar to the @code{HTML}\n  structured clone algorithm. @code{SharedArrayBuffer} are shared\n  between workers.\n\n  Current limitations: @code{Map} and @code{Set} are not supported\n  yet.\n\n  @item onmessage\n\n  Getter and setter. Set a function which is called each time a\n  message is received. The function is called with a single\n  argument. It is an object with a @code{data} property containing the\n  received message. The thread is not terminated if there is at least\n  one non @code{null} @code{onmessage} handler.\n\n  @end table\n\n@end table\n\n@section QuickJS C API\n\nThe C API was designed to be simple and efficient. The C API is\ndefined in the header @code{quickjs.h}.\n\n@subsection Runtime and contexts\n\n@code{JSRuntime} represents a Javascript runtime corresponding to an\nobject heap. Several runtimes can exist at the same time but they\ncannot exchange objects. Inside a given runtime, no multi-threading is\nsupported.\n\n@code{JSContext} represents a Javascript context (or Realm). Each\nJSContext has its own global objects and system objects. There can be\nseveral JSContexts per JSRuntime and they can share objects, similar\nto frames of the same origin sharing Javascript objects in a\nweb browser.\n\n@subsection JSValue\n\n@code{JSValue} represents a Javascript value which can be a primitive\ntype or an object. Reference counting is used, so it is important to\nexplicitly duplicate (@code{JS_DupValue()}, increment the reference\ncount) or free (@code{JS_FreeValue()}, decrement the reference count)\nJSValues.\n\n@subsection C functions\n\nC functions can be created with\n@code{JS_NewCFunction()}. @code{JS_SetPropertyFunctionList()} is a\nshortcut to easily add functions, setters and getters properties to a\ngiven object.\n\nUnlike other embedded Javascript engines, there is no implicit stack,\nso C functions get their parameters as normal C parameters. As a\ngeneral rule, C functions take constant @code{JSValue}s as parameters\n(so they don't need to free them) and return a newly allocated (=live)\n@code{JSValue}.\n\n@subsection Exceptions\n\nExceptions: most C functions can return a Javascript exception. It\nmust be explicitly tested and handled by the C code. The specific\n@code{JSValue} @code{JS_EXCEPTION} indicates that an exception\noccurred. The actual exception object is stored in the\n@code{JSContext} and can be retrieved with @code{JS_GetException()}.\n\n@subsection Script evaluation\n\nUse @code{JS_Eval()} to evaluate a script or module source.\n\nIf the script or module was compiled to bytecode with @code{qjsc}, it\ncan be evaluated by calling @code{js_std_eval_binary()}. The advantage\nis that no compilation is needed so it is faster and smaller because\nthe compiler can be removed from the executable if no @code{eval} is\nrequired.\n\nNote: the bytecode format is linked to a given QuickJS\nversion. Moreover, no security check is done before its\nexecution. Hence the bytecode should not be loaded from untrusted\nsources. That's why there is no option to output the bytecode to a\nbinary file in @code{qjsc}.\n\n@subsection JS Classes\n\nC opaque data can be attached to a Javascript object. The type of the\nC opaque data is determined with the class ID (@code{JSClassID}) of\nthe object. Hence the first step is to register a new class ID and JS\nclass (@code{JS_NewClassID()}, @code{JS_NewClass()}). Then you can\ncreate objects of this class with @code{JS_NewObjectClass()} and get or\nset the C opaque point with\n@code{JS_GetOpaque()}/@code{JS_SetOpaque()}.\n\nWhen defining a new JS class, it is possible to declare a finalizer\nwhich is called when the object is destroyed. The finalizer should be\nused to release C resources. It is invalid to execute JS code from\nit. A @code{gc_mark} method can be provided so that the cycle removal\nalgorithm can find the other objects referenced by this object. Other\nmethods are available to define exotic object behaviors.\n\nThe Class ID are globally allocated (i.e. for all runtimes). The\nJSClass are allocated per @code{JSRuntime}. @code{JS_SetClassProto()}\nis used to define a prototype for a given class in a given\nJSContext. @code{JS_NewObjectClass()} sets this prototype in the\ncreated object.\n\nExamples are available in @file{quickjs-libc.c}.\n\n@subsection C Modules\n\nNative ES6 modules are supported and can be dynamically or statically\nlinked. Look at the @file{test_bjson} and @file{bjson.so}\nexamples. The standard library @file{quickjs-libc.c} is also a good example\nof a native module.\n\n@subsection Memory handling\n\nUse @code{JS_SetMemoryLimit()} to set a global memory allocation limit\nto a given JSRuntime.\n\nCustom memory allocation functions can be provided with\n@code{JS_NewRuntime2()}.\n\nThe maximum system stack size can be set with @code{JS_SetMaxStackSize()}.\n\n@subsection Execution timeout and interrupts\n\nUse @code{JS_SetInterruptHandler()} to set a callback which is\nregularly called by the engine when it is executing code. This\ncallback can be used to implement an execution timeout.\n\nIt is used by the command line interpreter to implement a\n@code{Ctrl-C} handler.\n\n@chapter Internals\n\n@section Bytecode\n\nThe compiler generates bytecode directly with no intermediate\nrepresentation such as a parse tree, hence it is very fast. Several\noptimizations passes are done over the generated bytecode.\n\nA stack-based bytecode was chosen because it is simple and generates \ncompact code.\n\nFor each function, the maximum stack size is computed at compile time so that\nno runtime stack overflow tests are needed.\n\nA separate compressed line number table is maintained for the debug\ninformation.\n\nAccess to closure variables is optimized and is almost as fast as local\nvariables.\n\nDirect @code{eval} in strict mode is optimized.\n\n@section Executable generation\n\n@subsection @code{qjsc} compiler\n\nThe @code{qjsc} compiler generates C sources from Javascript files. By\ndefault the C sources are compiled with the system compiler\n(@code{gcc} or @code{clang}).\n\nThe generated C source contains the bytecode of the compiled functions\nor modules. If a full complete executable is needed, it also\ncontains a @code{main()} function with the necessary C code to initialize the\nJavascript engine and to load and execute the compiled functions and\nmodules.\n\nJavascript code can be mixed with C modules.\n\nIn order to have smaller executables, specific Javascript features can\nbe disabled, in particular @code{eval} or the regular expressions. The\ncode removal relies on the Link Time Optimization of the system\ncompiler.\n\n@subsection Binary JSON\n\n@code{qjsc} works by compiling scripts or modules and then serializing\nthem to a binary format. A subset of this format (without functions or\nmodules) can be used as binary JSON. The example @file{test_bjson.js}\nshows how to use it.\n\nWarning: the binary JSON format may change without notice, so it\nshould not be used to store persistent data. The @file{test_bjson.js}\nexample is only used to test the binary object format functions.\n\n@section Runtime\n\n@subsection Strings\n\nStrings are stored either as an 8 bit or a 16 bit array of\ncharacters. Hence random access to characters is always fast.\n\nThe C API provides functions to convert Javascript Strings to C UTF-8 encoded\nstrings. The most common case where the Javascript string contains\nonly ASCII characters involves no copying.\n\n@subsection Objects\n\nThe object shapes (object prototype, property names and flags) are shared\nbetween objects to save memory.\n\nArrays with no holes (except at the end of the array) are optimized.\n\nTypedArray accesses are optimized.\n\n@subsection Atoms\n\nObject property names and some strings are stored as Atoms (unique\nstrings) to save memory and allow fast comparison. Atoms are\nrepresented as a 32 bit integer. Half of the atom range is reserved for\nimmediate integer literals from @math{0} to @math{2^{31}-1}.\n\n@subsection Numbers\n\nNumbers are represented either as 32-bit signed integers or 64-bit IEEE-754\nfloating point values. Most operations have fast paths for the 32-bit\ninteger case.\n\n@subsection Garbage collection\n\nReference counting is used to free objects automatically and\ndeterministically. A separate cycle removal pass is done when the allocated\nmemory becomes too large. The cycle removal algorithm only uses the\nreference counts and the object content, so no explicit garbage\ncollection roots need to be manipulated in the C code.\n\n@subsection JSValue\n\nIt is a Javascript value which can be a primitive type (such as\nNumber, String, ...) or an Object. NaN boxing is used in the 32-bit version\nto store 64-bit floating point numbers. The representation is\noptimized so that 32-bit integers and reference counted values can be\nefficiently tested.\n\nIn 64-bit code, JSValue are 128-bit large and no NaN boxing is used. The\nrationale is that in 64-bit code memory usage is less critical.\n\nIn both cases (32 or 64 bits), JSValue exactly fits two CPU registers,\nso it can be efficiently returned by C functions.\n\n@subsection Function call\n\nThe engine is optimized so that function calls are fast. The system\nstack holds the Javascript parameters and local variables.\n\n@section RegExp\n\nA specific regular expression engine was developed. It is both small\nand efficient and supports all the ES2020 features including the\nUnicode properties. As the Javascript compiler, it directly generates\nbytecode without a parse tree.\n\nBacktracking with an explicit stack is used so that there is no\nrecursion on the system stack. Simple quantifiers are specifically\noptimized to avoid recursions.\n\nInfinite recursions coming from quantifiers with empty terms are\navoided.\n\nThe full regexp library weights about 15 KiB (x86 code), excluding the\nUnicode library.\n\n@section Unicode\n\nA specific Unicode library was developed so that there is no\ndependency on an external large Unicode library such as ICU. All the\nUnicode tables are compressed while keeping a reasonable access\nspeed.\n\nThe library supports case conversion, Unicode normalization, Unicode\nscript queries, Unicode general category queries and all Unicode\nbinary properties.\n\nThe full Unicode library weights about 45 KiB (x86 code).\n\n@section BigInt, BigFloat, BigDecimal\n\nBigInt, BigFloat and BigDecimal are implemented with the @code{libbf}\nlibrary@footnote{@url{https://bellard.org/libbf}}. It weights about 90\nKiB (x86 code) and provides arbitrary precision IEEE 754 floating\npoint operations and transcendental functions with exact rounding.\n\n@chapter License\n\nQuickJS is released under the MIT license.\n\nUnless otherwise specified, the QuickJS sources are copyright Fabrice\nBellard and Charlie Gordon.\n\n@bye\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/examples/fib.c",
    "content": "/*\n * QuickJS: Example of C module\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \"../quickjs.h\"\n\n#define countof(x) (sizeof(x) / sizeof((x)[0]))\n\nstatic int fib(int n)\n{\n    if (n <= 0)\n        return 0;\n    else if (n == 1)\n        return 1;\n    else\n        return fib(n - 1) + fib(n - 2);\n}\n\nstatic JSValue js_fib(JSContext *ctx, JSValueConst this_val,\n                      int argc, JSValueConst *argv)\n{\n    int n, res;\n    if (JS_ToInt32(ctx, &n, argv[0]))\n        return JS_EXCEPTION;\n    res = fib(n);\n    return JS_NewInt32(ctx, res);\n}\n\nstatic const JSCFunctionListEntry js_fib_funcs[] = {\n    JS_CFUNC_DEF(\"fib\", 1, js_fib ),\n};\n\nstatic int js_fib_init(JSContext *ctx, JSModuleDef *m)\n{\n    return JS_SetModuleExportList(ctx, m, js_fib_funcs,\n                                  countof(js_fib_funcs));\n}\n\n#ifdef JS_SHARED_LIBRARY\n#define JS_INIT_MODULE js_init_module\n#else\n#define JS_INIT_MODULE js_init_module_fib\n#endif\n\nJSModuleDef *JS_INIT_MODULE(JSContext *ctx, const char *module_name)\n{\n    JSModuleDef *m;\n    m = JS_NewCModule(ctx, module_name, js_fib_init);\n    if (!m)\n        return NULL;\n    JS_AddModuleExportList(ctx, m, js_fib_funcs, countof(js_fib_funcs));\n    return m;\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/examples/fib_module.js",
    "content": "/* fib module */\nexport function fib(n)\n{\n    if (n <= 0)\n        return 0;\n    else if (n == 1)\n        return 1;\n    else\n        return fib(n - 1) + fib(n - 2);\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/examples/hello.js",
    "content": "console.log(\"Hello World\");\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/examples/hello_module.js",
    "content": "/* example of JS module */\n\nimport { fib } from \"./fib_module.js\";\n\nconsole.log(\"Hello World\");\nconsole.log(\"fib(10)=\", fib(10));\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/examples/pi_bigdecimal.js",
    "content": "/*\n * PI computation in Javascript using the QuickJS bigdecimal type\n * (decimal floating point)\n */\n\"use strict\";\n\n/* compute PI with a precision of 'prec' digits */\nfunction calc_pi(prec) {\n    const CHUD_A = 13591409m;\n    const CHUD_B = 545140134m;\n    const CHUD_C = 640320m;\n    const CHUD_C3 = 10939058860032000m; /* C^3/24 */\n    const CHUD_DIGITS_PER_TERM = 14.18164746272548; /* log10(C/12)*3 */\n    \n    /* return [P, Q, G] */\n    function chud_bs(a, b, need_G) {\n        var c, P, Q, G, P1, Q1, G1, P2, Q2, G2, b1;\n        if (a == (b - 1n)) {\n            b1 = BigDecimal(b);\n            G = (2m * b1 - 1m) * (6m * b1 - 1m) * (6m * b1 - 5m);\n            P = G * (CHUD_B * b1 + CHUD_A);\n            if (b & 1n)\n                P = -P;\n            G = G;\n            Q = b1 * b1 * b1 * CHUD_C3;\n        } else {\n            c = (a + b) >> 1n;\n            [P1, Q1, G1] = chud_bs(a, c, true);\n            [P2, Q2, G2] = chud_bs(c, b, need_G);\n            P = P1 * Q2 + P2 * G1;\n            Q = Q1 * Q2;\n            if (need_G)\n                G = G1 * G2;\n            else\n                G = 0m;\n        }\n        return [P, Q, G];\n    }\n\n    var n, P, Q, G;\n    /* number of serie terms */\n    n = BigInt(Math.ceil(prec / CHUD_DIGITS_PER_TERM)) + 10n;\n    [P, Q, G] = chud_bs(0n, n, false);\n    Q = BigDecimal.div(Q, (P + Q * CHUD_A),\n                       { roundingMode: \"half-even\",\n                         maximumSignificantDigits: prec });\n    G = (CHUD_C / 12m) * BigDecimal.sqrt(CHUD_C,\n                                         { roundingMode: \"half-even\",\n                                           maximumSignificantDigits: prec });\n    return Q * G;\n}\n\n(function() {\n    var r, n_digits, n_bits;\n    if (typeof scriptArgs != \"undefined\") {\n        if (scriptArgs.length < 2) {\n            print(\"usage: pi n_digits\");\n            return;\n        }\n        n_digits = scriptArgs[1] | 0;\n    } else {\n        n_digits = 1000;\n    }\n    /* we add more digits to reduce the probability of bad rounding for\n       the last digits */\n    r = calc_pi(n_digits + 20);\n    print(r.toFixed(n_digits, \"down\"));\n})();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/examples/pi_bigfloat.js",
    "content": "/*\n * PI computation in Javascript using the QuickJS bigfloat type\n * (binary floating point)\n */\n\"use strict\";\n\n/* compute PI with a precision of 'prec' bits */\nfunction calc_pi() {\n    const CHUD_A = 13591409n;\n    const CHUD_B = 545140134n;\n    const CHUD_C = 640320n;\n    const CHUD_C3 = 10939058860032000n; /* C^3/24 */\n    const CHUD_BITS_PER_TERM = 47.11041313821584202247; /* log2(C/12)*3 */\n    \n    /* return [P, Q, G] */\n    function chud_bs(a, b, need_G) {\n        var c, P, Q, G, P1, Q1, G1, P2, Q2, G2;\n        if (a == (b - 1n)) {\n            G = (2n * b - 1n) * (6n * b - 1n) * (6n * b - 5n);\n            P = BigFloat(G * (CHUD_B * b + CHUD_A));\n            if (b & 1n)\n                P = -P;\n            G = BigFloat(G);\n            Q = BigFloat(b * b * b * CHUD_C3);\n        } else {\n            c = (a + b) >> 1n;\n            [P1, Q1, G1] = chud_bs(a, c, true);\n            [P2, Q2, G2] = chud_bs(c, b, need_G);\n            P = P1 * Q2 + P2 * G1;\n            Q = Q1 * Q2;\n            if (need_G)\n                G = G1 * G2;\n            else\n                G = 0l;\n        }\n        return [P, Q, G];\n    }\n\n    var n, P, Q, G;\n    /* number of serie terms */\n    n = BigInt(Math.ceil(BigFloatEnv.prec / CHUD_BITS_PER_TERM)) + 10n;\n    [P, Q, G] = chud_bs(0n, n, false);\n    Q = Q / (P + Q * BigFloat(CHUD_A));\n    G = BigFloat((CHUD_C / 12n)) * BigFloat.sqrt(BigFloat(CHUD_C));\n    return Q * G;\n}\n\n(function() {\n    var r, n_digits, n_bits;\n    if (typeof scriptArgs != \"undefined\") {\n        if (scriptArgs.length < 2) {\n            print(\"usage: pi n_digits\");\n            return;\n        }\n        n_digits = scriptArgs[1];\n    } else {\n        n_digits = 1000;\n    }\n    n_bits = Math.ceil(n_digits * Math.log2(10));\n    /* we add more bits to reduce the probability of bad rounding for\n       the last digits */\n    BigFloatEnv.setPrec( () => {\n        r = calc_pi();\n        print(r.toFixed(n_digits, BigFloatEnv.RNDZ));\n    }, n_bits + 32);\n})();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/examples/pi_bigint.js",
    "content": "/*\n * PI computation in Javascript using the BigInt type\n */\n\"use strict\";\n\n/* return floor(log2(a)) for a > 0 and 0 for a = 0 */\nfunction floor_log2(a)\n{\n    var k_max, a1, k, i;\n    k_max = 0n;\n    while ((a >> (2n ** k_max)) != 0n) {\n        k_max++;\n    }\n    k = 0n;\n    a1 = a;\n    for(i = k_max - 1n; i >= 0n; i--) {\n        a1 = a >> (2n ** i);\n        if (a1 != 0n) {\n            a = a1;\n            k |= (1n << i);\n        }\n    }\n    return k;\n}\n\n/* return ceil(log2(a)) for a > 0 */\nfunction ceil_log2(a)\n{\n    return floor_log2(a - 1n) + 1n;\n}\n\n/* return floor(sqrt(a)) (not efficient but simple) */\nfunction int_sqrt(a)\n{\n    var l, u, s;\n    if (a == 0n)\n        return a;\n    l = ceil_log2(a);\n    u = 1n << ((l + 1n) / 2n);\n    /* u >= floor(sqrt(a)) */\n    for(;;) {\n        s = u;\n        u = ((a / s) + s) / 2n;\n        if (u >= s)\n            break;\n    }\n    return s;\n}\n\n/* return pi * 2**prec */\nfunction calc_pi(prec) {\n    const CHUD_A = 13591409n;\n    const CHUD_B = 545140134n;\n    const CHUD_C = 640320n;\n    const CHUD_C3 = 10939058860032000n; /* C^3/24 */\n    const CHUD_BITS_PER_TERM = 47.11041313821584202247; /* log2(C/12)*3 */\n    \n    /* return [P, Q, G] */\n    function chud_bs(a, b, need_G) {\n        var c, P, Q, G, P1, Q1, G1, P2, Q2, G2;\n        if (a == (b - 1n)) {\n            G = (2n * b - 1n) * (6n * b - 1n) * (6n * b - 5n);\n            P = G * (CHUD_B * b + CHUD_A);\n            if (b & 1n)\n                P = -P;\n            Q = b * b * b * CHUD_C3;\n        } else {\n            c = (a + b) >> 1n;\n            [P1, Q1, G1] = chud_bs(a, c, true);\n            [P2, Q2, G2] = chud_bs(c, b, need_G);\n            P = P1 * Q2 + P2 * G1;\n            Q = Q1 * Q2;\n            if (need_G)\n                G = G1 * G2;\n            else\n                G = 0n;\n        }\n        return [P, Q, G];\n    }\n\n    var n, P, Q, G;\n    /* number of serie terms */\n    n = BigInt(Math.ceil(Number(prec) / CHUD_BITS_PER_TERM)) + 10n;\n    [P, Q, G] = chud_bs(0n, n, false);\n    Q = (CHUD_C / 12n) * (Q << prec) / (P + Q * CHUD_A);\n    G = int_sqrt(CHUD_C << (2n * prec));\n    return (Q * G) >> prec;\n}\n\nfunction main(args) {\n    var r, n_digits, n_bits, out;\n    if (args.length < 1) {\n        print(\"usage: pi n_digits\");\n        return;\n    }\n    n_digits = args[0] | 0;\n\n    /* we add more bits to reduce the probability of bad rounding for\n      the last digits */\n    n_bits = BigInt(Math.ceil(n_digits * Math.log2(10))) + 32n;\n    r = calc_pi(n_bits);\n    r = ((10n ** BigInt(n_digits)) * r) >> n_bits;\n    out = r.toString();\n    print(out[0] + \".\" + out.slice(1));\n}\n\nvar args;\nif (typeof scriptArgs != \"undefined\") {\n    args = scriptArgs;\n    args.shift();\n} else if (typeof arguments != \"undefined\") {\n    args = arguments;\n} else {\n    /* default: 1000 digits */\n    args=[1000];\n}\n\nmain(args);\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/examples/point.c",
    "content": "/*\n * QuickJS: Example of C module with a class\n * \n * Copyright (c) 2019 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \"../quickjs.h\"\n#include <math.h>\n\n#define countof(x) (sizeof(x) / sizeof((x)[0]))\n\n/* Point Class */\n\ntypedef struct {\n    int x;\n    int y;\n} JSPointData;\n\nstatic JSClassID js_point_class_id;\n\nstatic void js_point_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSPointData *s = JS_GetOpaque(val, js_point_class_id);\n    /* Note: 's' can be NULL in case JS_SetOpaque() was not called */\n    js_free_rt(rt, s);\n}\n\nstatic JSValue js_point_ctor(JSContext *ctx,\n                             JSValueConst new_target,\n                             int argc, JSValueConst *argv)\n{\n    JSPointData *s;\n    JSValue obj = JS_UNDEFINED;\n    JSValue proto;\n    \n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s)\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &s->x, argv[0]))\n        goto fail;\n    if (JS_ToInt32(ctx, &s->y, argv[1]))\n        goto fail;\n    /* using new_target to get the prototype is necessary when the\n       class is extended. */\n    proto = JS_GetPropertyStr(ctx, new_target, \"prototype\");\n    if (JS_IsException(proto))\n        goto fail;\n    obj = JS_NewObjectProtoClass(ctx, proto, js_point_class_id);\n    JS_FreeValue(ctx, proto);\n    if (JS_IsException(obj))\n        goto fail;\n    JS_SetOpaque(obj, s);\n    return obj;\n fail:\n    js_free(ctx, s);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_point_get_xy(JSContext *ctx, JSValueConst this_val, int magic)\n{\n    JSPointData *s = JS_GetOpaque2(ctx, this_val, js_point_class_id);\n    if (!s)\n        return JS_EXCEPTION;\n    if (magic == 0)\n        return JS_NewInt32(ctx, s->x);\n    else\n        return JS_NewInt32(ctx, s->y);\n}\n\nstatic JSValue js_point_set_xy(JSContext *ctx, JSValueConst this_val, JSValue val, int magic)\n{\n    JSPointData *s = JS_GetOpaque2(ctx, this_val, js_point_class_id);\n    int v;\n    if (!s)\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &v, val))\n        return JS_EXCEPTION;\n    if (magic == 0)\n        s->x = v;\n    else\n        s->y = v;\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_point_norm(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    JSPointData *s = JS_GetOpaque2(ctx, this_val, js_point_class_id);\n    if (!s)\n        return JS_EXCEPTION;\n    return JS_NewFloat64(ctx, sqrt((double)s->x * s->x + (double)s->y * s->y));\n}\n\nstatic JSClassDef js_point_class = {\n    \"Point\",\n    .finalizer = js_point_finalizer,\n}; \n\nstatic const JSCFunctionListEntry js_point_proto_funcs[] = {\n    JS_CGETSET_MAGIC_DEF(\"x\", js_point_get_xy, js_point_set_xy, 0),\n    JS_CGETSET_MAGIC_DEF(\"y\", js_point_get_xy, js_point_set_xy, 1),\n    JS_CFUNC_DEF(\"norm\", 0, js_point_norm),\n};\n\nstatic int js_point_init(JSContext *ctx, JSModuleDef *m)\n{\n    JSValue point_proto, point_class;\n    \n    /* create the Point class */\n    JS_NewClassID(&js_point_class_id);\n    JS_NewClass(JS_GetRuntime(ctx), js_point_class_id, &js_point_class);\n\n    point_proto = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, point_proto, js_point_proto_funcs, countof(js_point_proto_funcs));\n    \n    point_class = JS_NewCFunction2(ctx, js_point_ctor, \"Point\", 2, JS_CFUNC_constructor, 0);\n    /* set proto.constructor and ctor.prototype */\n    JS_SetConstructor(ctx, point_class, point_proto);\n    JS_SetClassProto(ctx, js_point_class_id, point_proto);\n                      \n    JS_SetModuleExport(ctx, m, \"Point\", point_class);\n    return 0;\n}\n\nJSModuleDef *js_init_module(JSContext *ctx, const char *module_name)\n{\n    JSModuleDef *m;\n    m = JS_NewCModule(ctx, module_name, js_point_init);\n    if (!m)\n        return NULL;\n    JS_AddModuleExport(ctx, m, \"Point\");\n    return m;\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/examples/test_fib.js",
    "content": "/* example of JS module importing a C module */\n\nimport { fib } from \"./fib.so\";\n\nconsole.log(\"Hello World\");\nconsole.log(\"fib(10)=\", fib(10));\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/examples/test_point.js",
    "content": "/* example of JS module importing a C module */\nimport { Point } from \"./point.so\";\n\nfunction assert(b, str)\n{\n    if (b) {\n        return;\n    } else {\n        throw Error(\"assertion failed: \" + str);\n    }\n}\n\nclass ColorPoint extends Point {\n    constructor(x, y, color) {\n        super(x, y);\n        this.color = color;\n    }\n    get_color() {\n        return this.color;\n    }\n};\n\nfunction main()\n{\n    var pt, pt2;\n\n    pt = new Point(2, 3);\n    assert(pt.x === 2);\n    assert(pt.y === 3);\n    pt.x = 4;\n    assert(pt.x === 4);\n    assert(pt.norm() == 5);\n\n    pt2 = new ColorPoint(2, 3, 0xffffff);\n    assert(pt2.x === 2);\n    assert(pt2.color === 0xffffff);\n    assert(pt2.get_color() === 0xffffff);\n}\n\nmain();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/libbf.c",
    "content": "/*\n * Tiny arbitrary precision floating point library\n * \n * Copyright (c) 2017-2021 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <inttypes.h>\n#include <math.h>\n#include <string.h>\n#include <assert.h>\n\n#ifdef __AVX2__\n#include <immintrin.h>\n#endif\n\n#include \"cutils.h\"\n#include \"libbf.h\"\n\n/* enable it to check the multiplication result */\n//#define USE_MUL_CHECK\n/* enable it to use FFT/NTT multiplication */\n#define USE_FFT_MUL\n/* enable decimal floating point support */\n#define USE_BF_DEC\n\n//#define inline __attribute__((always_inline))\n\n#ifdef __AVX2__\n#define FFT_MUL_THRESHOLD 100 /* in limbs of the smallest factor */\n#else\n#define FFT_MUL_THRESHOLD 100 /* in limbs of the smallest factor */\n#endif\n\n/* XXX: adjust */\n#define DIVNORM_LARGE_THRESHOLD 50\n#define UDIV1NORM_THRESHOLD 3\n\n#if LIMB_BITS == 64\n#define FMT_LIMB1 \"%\" PRIx64 \n#define FMT_LIMB \"%016\" PRIx64 \n#define PRId_LIMB PRId64\n#define PRIu_LIMB PRIu64\n\n#else\n\n#define FMT_LIMB1 \"%x\"\n#define FMT_LIMB \"%08x\"\n#define PRId_LIMB \"d\"\n#define PRIu_LIMB \"u\"\n\n#endif\n\ntypedef intptr_t mp_size_t;\n\ntypedef int bf_op2_func_t(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n                          bf_flags_t flags);\n\n#ifdef USE_FFT_MUL\n\n#define FFT_MUL_R_OVERLAP_A (1 << 0)\n#define FFT_MUL_R_OVERLAP_B (1 << 1)\n#define FFT_MUL_R_NORESIZE  (1 << 2)\n\nstatic no_inline int fft_mul(bf_context_t *s,\n                             bf_t *res, limb_t *a_tab, limb_t a_len,\n                             limb_t *b_tab, limb_t b_len, int mul_flags);\nstatic void fft_clear_cache(bf_context_t *s);\n#endif\n#ifdef USE_BF_DEC\nstatic limb_t get_digit(const limb_t *tab, limb_t len, slimb_t pos);\n#endif\n\n\n/* could leading zeros */\nstatic inline int clz(limb_t a)\n{\n    if (a == 0) {\n        return LIMB_BITS;\n    } else {\n#if LIMB_BITS == 64\n        return clz64(a);\n#else\n        return clz32(a);\n#endif\n    }\n}\n\nstatic inline int ctz(limb_t a)\n{\n    if (a == 0) {\n        return LIMB_BITS;\n    } else {\n#if LIMB_BITS == 64\n        return ctz64(a);\n#else\n        return ctz32(a);\n#endif\n    }\n}\n\nstatic inline int ceil_log2(limb_t a)\n{\n    if (a <= 1)\n        return 0;\n    else\n        return LIMB_BITS - clz(a - 1);\n}\n\n/* b must be >= 1 */\nstatic inline slimb_t ceil_div(slimb_t a, slimb_t b)\n{\n    if (a >= 0)\n        return (a + b - 1) / b;\n    else\n        return a / b;\n}\n\n/* b must be >= 1 */\nstatic inline slimb_t floor_div(slimb_t a, slimb_t b)\n{\n    if (a >= 0) {\n        return a / b;\n    } else {\n        return (a - b + 1) / b;\n    }\n}\n\n/* return r = a modulo b (0 <= r <= b - 1. b must be >= 1 */\nstatic inline limb_t smod(slimb_t a, slimb_t b)\n{\n    a = a % (slimb_t)b;\n    if (a < 0)\n        a += b;\n    return a;\n}\n\n/* signed addition with saturation */\nstatic inline slimb_t sat_add(slimb_t a, slimb_t b)\n{\n    slimb_t r;\n    r = a + b;\n    /* overflow ? */\n    if (((a ^ r) & (b ^ r)) < 0)\n        r = (a >> (LIMB_BITS - 1)) ^ (((limb_t)1 << (LIMB_BITS - 1)) - 1);\n    return r;\n}\n\n#define malloc(s) malloc_is_forbidden(s)\n#define free(p) free_is_forbidden(p)\n#define realloc(p, s) realloc_is_forbidden(p, s)\n\nvoid bf_context_init(bf_context_t *s, bf_realloc_func_t *realloc_func,\n                     void *realloc_opaque)\n{\n    memset(s, 0, sizeof(*s));\n    s->realloc_func = realloc_func;\n    s->realloc_opaque = realloc_opaque;\n}\n\nvoid bf_context_end(bf_context_t *s)\n{\n    bf_clear_cache(s);\n}\n\nvoid bf_init(bf_context_t *s, bf_t *r)\n{\n    r->ctx = s;\n    r->sign = 0;\n    r->expn = BF_EXP_ZERO;\n    r->len = 0;\n    r->tab = NULL;\n}\n\n/* return 0 if OK, -1 if alloc error */\nint bf_resize(bf_t *r, limb_t len)\n{\n    limb_t *tab;\n    \n    if (len != r->len) {\n        tab = bf_realloc(r->ctx, r->tab, len * sizeof(limb_t));\n        if (!tab && len != 0)\n            return -1;\n        r->tab = tab;\n        r->len = len;\n    }\n    return 0;\n}\n\n/* return 0 or BF_ST_MEM_ERROR */\nint bf_set_ui(bf_t *r, uint64_t a)\n{\n    r->sign = 0;\n    if (a == 0) {\n        r->expn = BF_EXP_ZERO;\n        bf_resize(r, 0); /* cannot fail */\n    } \n#if LIMB_BITS == 32\n    else if (a <= 0xffffffff)\n#else\n    else\n#endif\n    {\n        int shift;\n        if (bf_resize(r, 1))\n            goto fail;\n        shift = clz(a);\n        r->tab[0] = a << shift;\n        r->expn = LIMB_BITS - shift;\n    }\n#if LIMB_BITS == 32\n    else {\n        uint32_t a1, a0;\n        int shift;\n        if (bf_resize(r, 2))\n            goto fail;\n        a0 = a;\n        a1 = a >> 32;\n        shift = clz(a1);\n        r->tab[0] = a0 << shift;\n        r->tab[1] = (a1 << shift) | (a0 >> (LIMB_BITS - shift));\n        r->expn = 2 * LIMB_BITS - shift;\n    }\n#endif\n    return 0;\n fail:\n    bf_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\n/* return 0 or BF_ST_MEM_ERROR */\nint bf_set_si(bf_t *r, int64_t a)\n{\n    int ret;\n\n    if (a < 0) {\n        ret = bf_set_ui(r, -a);\n        r->sign = 1;\n    } else {\n        ret = bf_set_ui(r, a);\n    }\n    return ret;\n}\n\nvoid bf_set_nan(bf_t *r)\n{\n    bf_resize(r, 0); /* cannot fail */\n    r->expn = BF_EXP_NAN;\n    r->sign = 0;\n}\n\nvoid bf_set_zero(bf_t *r, int is_neg)\n{\n    bf_resize(r, 0); /* cannot fail */\n    r->expn = BF_EXP_ZERO;\n    r->sign = is_neg;\n}\n\nvoid bf_set_inf(bf_t *r, int is_neg)\n{\n    bf_resize(r, 0); /* cannot fail */\n    r->expn = BF_EXP_INF;\n    r->sign = is_neg;\n}\n\n/* return 0 or BF_ST_MEM_ERROR */\nint bf_set(bf_t *r, const bf_t *a)\n{\n    if (r == a)\n        return 0;\n    if (bf_resize(r, a->len)) {\n        bf_set_nan(r);\n        return BF_ST_MEM_ERROR;\n    }\n    r->sign = a->sign;\n    r->expn = a->expn;\n    memcpy(r->tab, a->tab, a->len * sizeof(limb_t));\n    return 0;\n}\n\n/* equivalent to bf_set(r, a); bf_delete(a) */\nvoid bf_move(bf_t *r, bf_t *a)\n{\n    bf_context_t *s = r->ctx;\n    if (r == a)\n        return;\n    bf_free(s, r->tab);\n    *r = *a;\n}\n\nstatic limb_t get_limbz(const bf_t *a, limb_t idx)\n{\n    if (idx >= a->len)\n        return 0;\n    else\n        return a->tab[idx];\n}\n\n/* get LIMB_BITS at bit position 'pos' in tab */\nstatic inline limb_t get_bits(const limb_t *tab, limb_t len, slimb_t pos)\n{\n    limb_t i, a0, a1;\n    int p;\n\n    i = pos >> LIMB_LOG2_BITS;\n    p = pos & (LIMB_BITS - 1);\n    if (i < len)\n        a0 = tab[i];\n    else\n        a0 = 0;\n    if (p == 0) {\n        return a0;\n    } else {\n        i++;\n        if (i < len)\n            a1 = tab[i];\n        else\n            a1 = 0;\n        return (a0 >> p) | (a1 << (LIMB_BITS - p));\n    }\n}\n\nstatic inline limb_t get_bit(const limb_t *tab, limb_t len, slimb_t pos)\n{\n    slimb_t i;\n    i = pos >> LIMB_LOG2_BITS;\n    if (i < 0 || i >= len)\n        return 0;\n    return (tab[i] >> (pos & (LIMB_BITS - 1))) & 1;\n}\n\nstatic inline limb_t limb_mask(int start, int last)\n{\n    limb_t v;\n    int n;\n    n = last - start + 1;\n    if (n == LIMB_BITS)\n        v = -1;\n    else\n        v = (((limb_t)1 << n) - 1) << start;\n    return v;\n}\n\nstatic limb_t mp_scan_nz(const limb_t *tab, mp_size_t n)\n{\n    mp_size_t i;\n    for(i = 0; i < n; i++) {\n        if (tab[i] != 0)\n            return 1;\n    }\n    return 0;\n}\n\n/* return != 0 if one bit between 0 and bit_pos inclusive is not zero. */\nstatic inline limb_t scan_bit_nz(const bf_t *r, slimb_t bit_pos)\n{\n    slimb_t pos;\n    limb_t v;\n    \n    pos = bit_pos >> LIMB_LOG2_BITS;\n    if (pos < 0)\n        return 0;\n    v = r->tab[pos] & limb_mask(0, bit_pos & (LIMB_BITS - 1));\n    if (v != 0)\n        return 1;\n    pos--;\n    while (pos >= 0) {\n        if (r->tab[pos] != 0)\n            return 1;\n        pos--;\n    }\n    return 0;\n}\n\n/* return the addend for rounding. Note that prec can be <= 0 (for\n   BF_FLAG_RADPNT_PREC) */\nstatic int bf_get_rnd_add(int *pret, const bf_t *r, limb_t l,\n                          slimb_t prec, int rnd_mode)\n{\n    int add_one, inexact;\n    limb_t bit1, bit0;\n    \n    if (rnd_mode == BF_RNDF) {\n        bit0 = 1; /* faithful rounding does not honor the INEXACT flag */\n    } else {\n        /* starting limb for bit 'prec + 1' */\n        bit0 = scan_bit_nz(r, l * LIMB_BITS - 1 - bf_max(0, prec + 1));\n    }\n\n    /* get the bit at 'prec' */\n    bit1 = get_bit(r->tab, l, l * LIMB_BITS - 1 - prec);\n    inexact = (bit1 | bit0) != 0;\n    \n    add_one = 0;\n    switch(rnd_mode) {\n    case BF_RNDZ:\n        break;\n    case BF_RNDN:\n        if (bit1) {\n            if (bit0) {\n                add_one = 1;\n            } else {\n                /* round to even */\n                add_one =\n                    get_bit(r->tab, l, l * LIMB_BITS - 1 - (prec - 1));\n            }\n        }\n        break;\n    case BF_RNDD:\n    case BF_RNDU:\n        if (r->sign == (rnd_mode == BF_RNDD))\n            add_one = inexact;\n        break;\n    case BF_RNDA:\n        add_one = inexact;\n        break;\n    case BF_RNDNA:\n    case BF_RNDF:\n        add_one = bit1;\n        break;\n    default:\n        abort();\n    }\n    \n    if (inexact)\n        *pret |= BF_ST_INEXACT;\n    return add_one;\n}\n\nstatic int bf_set_overflow(bf_t *r, int sign, limb_t prec, bf_flags_t flags)\n{\n    slimb_t i, l, e_max;\n    int rnd_mode;\n    \n    rnd_mode = flags & BF_RND_MASK;\n    if (prec == BF_PREC_INF ||\n        rnd_mode == BF_RNDN ||\n        rnd_mode == BF_RNDNA ||\n        rnd_mode == BF_RNDA ||\n        (rnd_mode == BF_RNDD && sign == 1) ||\n        (rnd_mode == BF_RNDU && sign == 0)) {\n        bf_set_inf(r, sign);\n    } else {\n        /* set to maximum finite number */\n        l = (prec + LIMB_BITS - 1) / LIMB_BITS;\n        if (bf_resize(r, l)) {\n            bf_set_nan(r);\n            return BF_ST_MEM_ERROR;\n        }\n        r->tab[0] = limb_mask((-prec) & (LIMB_BITS - 1),\n                              LIMB_BITS - 1);\n        for(i = 1; i < l; i++)\n            r->tab[i] = (limb_t)-1;\n        e_max = (limb_t)1 << (bf_get_exp_bits(flags) - 1);\n        r->expn = e_max;\n        r->sign = sign;\n    }\n    return BF_ST_OVERFLOW | BF_ST_INEXACT;\n}\n\n/* round to prec1 bits assuming 'r' is non zero and finite. 'r' is\n   assumed to have length 'l' (1 <= l <= r->len). Note: 'prec1' can be\n   infinite (BF_PREC_INF). 'ret' is 0 or BF_ST_INEXACT if the result\n   is known to be inexact. Can fail with BF_ST_MEM_ERROR in case of\n   overflow not returning infinity. */\nstatic int __bf_round(bf_t *r, limb_t prec1, bf_flags_t flags, limb_t l,\n                      int ret)\n{\n    limb_t v, a;\n    int shift, add_one, rnd_mode;\n    slimb_t i, bit_pos, pos, e_min, e_max, e_range, prec;\n\n    /* e_min and e_max are computed to match the IEEE 754 conventions */\n    e_range = (limb_t)1 << (bf_get_exp_bits(flags) - 1);\n    e_min = -e_range + 3;\n    e_max = e_range;\n    \n    if (flags & BF_FLAG_RADPNT_PREC) {\n        /* 'prec' is the precision after the radix point */\n        if (prec1 != BF_PREC_INF)\n            prec = r->expn + prec1;\n        else\n            prec = prec1;\n    } else if (unlikely(r->expn < e_min) && (flags & BF_FLAG_SUBNORMAL)) {\n        /* restrict the precision in case of potentially subnormal\n           result */\n        assert(prec1 != BF_PREC_INF);\n        prec = prec1 - (e_min - r->expn);\n    } else {\n        prec = prec1;\n    }\n\n    /* round to prec bits */\n    rnd_mode = flags & BF_RND_MASK;\n    add_one = bf_get_rnd_add(&ret, r, l, prec, rnd_mode);\n    \n    if (prec <= 0) {\n        if (add_one) {\n            bf_resize(r, 1); /* cannot fail */\n            r->tab[0] = (limb_t)1 << (LIMB_BITS - 1);\n            r->expn += 1 - prec;\n            ret |= BF_ST_UNDERFLOW | BF_ST_INEXACT;\n            return ret;\n        } else {\n            goto underflow;\n        }\n    } else if (add_one) {\n        limb_t carry;\n        \n        /* add one starting at digit 'prec - 1' */\n        bit_pos = l * LIMB_BITS - 1 - (prec - 1);\n        pos = bit_pos >> LIMB_LOG2_BITS;\n        carry = (limb_t)1 << (bit_pos & (LIMB_BITS - 1));\n        \n        for(i = pos; i < l; i++) {\n            v = r->tab[i] + carry;\n            carry = (v < carry);\n            r->tab[i] = v;\n            if (carry == 0)\n                break;\n        }\n        if (carry) {\n            /* shift right by one digit */\n            v = 1;\n            for(i = l - 1; i >= pos; i--) {\n                a = r->tab[i];\n                r->tab[i] = (a >> 1) | (v << (LIMB_BITS - 1));\n                v = a;\n            }\n            r->expn++;\n        }\n    }\n    \n    /* check underflow */\n    if (unlikely(r->expn < e_min)) {\n        if (flags & BF_FLAG_SUBNORMAL) {\n            /* if inexact, also set the underflow flag */\n            if (ret & BF_ST_INEXACT)\n                ret |= BF_ST_UNDERFLOW;\n        } else {\n        underflow:\n            ret |= BF_ST_UNDERFLOW | BF_ST_INEXACT;\n            bf_set_zero(r, r->sign);\n            return ret;\n        }\n    }\n    \n    /* check overflow */\n    if (unlikely(r->expn > e_max))\n        return bf_set_overflow(r, r->sign, prec1, flags);\n    \n    /* keep the bits starting at 'prec - 1' */\n    bit_pos = l * LIMB_BITS - 1 - (prec - 1);\n    i = bit_pos >> LIMB_LOG2_BITS;\n    if (i >= 0) {\n        shift = bit_pos & (LIMB_BITS - 1);\n        if (shift != 0)\n            r->tab[i] &= limb_mask(shift, LIMB_BITS - 1);\n    } else {\n        i = 0;\n    }\n    /* remove trailing zeros */\n    while (r->tab[i] == 0)\n        i++;\n    if (i > 0) {\n        l -= i;\n        memmove(r->tab, r->tab + i, l * sizeof(limb_t));\n    }\n    bf_resize(r, l); /* cannot fail */\n    return ret;\n}\n\n/* 'r' must be a finite number. */\nint bf_normalize_and_round(bf_t *r, limb_t prec1, bf_flags_t flags)\n{\n    limb_t l, v, a;\n    int shift, ret;\n    slimb_t i;\n    \n    //    bf_print_str(\"bf_renorm\", r);\n    l = r->len;\n    while (l > 0 && r->tab[l - 1] == 0)\n        l--;\n    if (l == 0) {\n        /* zero */\n        r->expn = BF_EXP_ZERO;\n        bf_resize(r, 0); /* cannot fail */\n        ret = 0;\n    } else {\n        r->expn -= (r->len - l) * LIMB_BITS;\n        /* shift to have the MSB set to '1' */\n        v = r->tab[l - 1];\n        shift = clz(v);\n        if (shift != 0) {\n            v = 0;\n            for(i = 0; i < l; i++) {\n                a = r->tab[i];\n                r->tab[i] = (a << shift) | (v >> (LIMB_BITS - shift));\n                v = a;\n            }\n            r->expn -= shift;\n        }\n        ret = __bf_round(r, prec1, flags, l, 0);\n    }\n    //    bf_print_str(\"r_final\", r);\n    return ret;\n}\n\n/* return true if rounding can be done at precision 'prec' assuming\n   the exact result r is such that |r-a| <= 2^(EXP(a)-k). */\n/* XXX: check the case where the exponent would be incremented by the\n   rounding */\nint bf_can_round(const bf_t *a, slimb_t prec, bf_rnd_t rnd_mode, slimb_t k)\n{\n    BOOL is_rndn;\n    slimb_t bit_pos, n;\n    limb_t bit;\n    \n    if (a->expn == BF_EXP_INF || a->expn == BF_EXP_NAN)\n        return FALSE;\n    if (rnd_mode == BF_RNDF) {\n        return (k >= (prec + 1));\n    }\n    if (a->expn == BF_EXP_ZERO)\n        return FALSE;\n    is_rndn = (rnd_mode == BF_RNDN || rnd_mode == BF_RNDNA);\n    if (k < (prec + 2))\n        return FALSE;\n    bit_pos = a->len * LIMB_BITS - 1 - prec;\n    n = k - prec;\n    /* bit pattern for RNDN or RNDNA: 0111.. or 1000...\n       for other rounding modes: 000... or 111... \n    */\n    bit = get_bit(a->tab, a->len, bit_pos);\n    bit_pos--;\n    n--;\n    bit ^= is_rndn;\n    /* XXX: slow, but a few iterations on average */\n    while (n != 0) {\n        if (get_bit(a->tab, a->len, bit_pos) != bit)\n            return TRUE;\n        bit_pos--;\n        n--;\n    }\n    return FALSE;\n}\n\n/* Cannot fail with BF_ST_MEM_ERROR. */\nint bf_round(bf_t *r, limb_t prec, bf_flags_t flags)\n{\n    if (r->len == 0)\n        return 0;\n    return __bf_round(r, prec, flags, r->len, 0);\n}\n\n/* for debugging */\nstatic __maybe_unused void dump_limbs(const char *str, const limb_t *tab, limb_t n)\n{\n    limb_t i;\n    printf(\"%s: len=%\" PRId_LIMB \"\\n\", str, n);\n    for(i = 0; i < n; i++) {\n        printf(\"%\" PRId_LIMB \": \" FMT_LIMB \"\\n\",\n               i, tab[i]);\n    }\n}\n\nvoid mp_print_str(const char *str, const limb_t *tab, limb_t n)\n{\n    slimb_t i;\n    printf(\"%s= 0x\", str);\n    for(i = n - 1; i >= 0; i--) {\n        if (i != (n - 1))\n            printf(\"_\");\n        printf(FMT_LIMB, tab[i]);\n    }\n    printf(\"\\n\");\n}\n\nstatic __maybe_unused void mp_print_str_h(const char *str,\n                                          const limb_t *tab, limb_t n,\n                                          limb_t high)\n{\n    slimb_t i;\n    printf(\"%s= 0x\", str);\n    printf(FMT_LIMB, high);\n    for(i = n - 1; i >= 0; i--) {\n        printf(\"_\");\n        printf(FMT_LIMB, tab[i]);\n    }\n    printf(\"\\n\");\n}\n\n/* for debugging */\nvoid bf_print_str(const char *str, const bf_t *a)\n{\n    slimb_t i;\n    printf(\"%s=\", str);\n\n    if (a->expn == BF_EXP_NAN) {\n        printf(\"NaN\");\n    } else {\n        if (a->sign)\n            putchar('-');\n        if (a->expn == BF_EXP_ZERO) {\n            putchar('0');\n        } else if (a->expn == BF_EXP_INF) {\n            printf(\"Inf\");\n        } else {\n            printf(\"0x0.\");\n            for(i = a->len - 1; i >= 0; i--)\n                printf(FMT_LIMB, a->tab[i]);\n            printf(\"p%\" PRId_LIMB, a->expn);\n        }\n    }\n    printf(\"\\n\");\n}\n\n/* compare the absolute value of 'a' and 'b'. Return < 0 if a < b, 0\n   if a = b and > 0 otherwise. */\nint bf_cmpu(const bf_t *a, const bf_t *b)\n{\n    slimb_t i;\n    limb_t len, v1, v2;\n    \n    if (a->expn != b->expn) {\n        if (a->expn < b->expn)\n            return -1;\n        else\n            return 1;\n    }\n    len = bf_max(a->len, b->len);\n    for(i = len - 1; i >= 0; i--) {\n        v1 = get_limbz(a, a->len - len + i);\n        v2 = get_limbz(b, b->len - len + i);\n        if (v1 != v2) {\n            if (v1 < v2)\n                return -1;\n            else\n                return 1;\n        }\n    }\n    return 0;\n}\n\n/* Full order: -0 < 0, NaN == NaN and NaN is larger than all other numbers */\nint bf_cmp_full(const bf_t *a, const bf_t *b)\n{\n    int res;\n    \n    if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {\n        if (a->expn == b->expn)\n            res = 0;\n        else if (a->expn == BF_EXP_NAN)\n            res = 1;\n        else\n            res = -1;\n    } else if (a->sign != b->sign) {\n        res = 1 - 2 * a->sign;\n    } else {\n        res = bf_cmpu(a, b);\n        if (a->sign)\n            res = -res;\n    }\n    return res;\n}\n\n/* Standard floating point comparison: return 2 if one of the operands\n   is NaN (unordered) or -1, 0, 1 depending on the ordering assuming\n   -0 == +0 */\nint bf_cmp(const bf_t *a, const bf_t *b)\n{\n    int res;\n    \n    if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {\n        res = 2;\n    } else if (a->sign != b->sign) {\n        if (a->expn == BF_EXP_ZERO && b->expn == BF_EXP_ZERO)\n            res = 0;\n        else\n            res = 1 - 2 * a->sign;\n    } else {\n        res = bf_cmpu(a, b);\n        if (a->sign)\n            res = -res;\n    }\n    return res;\n}\n\n/* Compute the number of bits 'n' matching the pattern:\n   a= X1000..0\n   b= X0111..1\n              \n   When computing a-b, the result will have at least n leading zero\n   bits.\n\n   Precondition: a > b and a.expn - b.expn = 0 or 1\n*/\nstatic limb_t count_cancelled_bits(const bf_t *a, const bf_t *b)\n{\n    slimb_t bit_offset, b_offset, n;\n    int p, p1;\n    limb_t v1, v2, mask;\n\n    bit_offset = a->len * LIMB_BITS - 1;\n    b_offset = (b->len - a->len) * LIMB_BITS - (LIMB_BITS - 1) +\n        a->expn - b->expn;\n    n = 0;\n\n    /* first search the equals bits */\n    for(;;) {\n        v1 = get_limbz(a, bit_offset >> LIMB_LOG2_BITS);\n        v2 = get_bits(b->tab, b->len, bit_offset + b_offset);\n        //        printf(\"v1=\" FMT_LIMB \" v2=\" FMT_LIMB \"\\n\", v1, v2);\n        if (v1 != v2)\n            break;\n        n += LIMB_BITS;\n        bit_offset -= LIMB_BITS;\n    }\n    /* find the position of the first different bit */\n    p = clz(v1 ^ v2) + 1;\n    n += p;\n    /* then search for '0' in a and '1' in b */\n    p = LIMB_BITS - p;\n    if (p > 0) {\n        /* search in the trailing p bits of v1 and v2 */\n        mask = limb_mask(0, p - 1);\n        p1 = bf_min(clz(v1 & mask), clz((~v2) & mask)) - (LIMB_BITS - p);\n        n += p1;\n        if (p1 != p)\n            goto done;\n    }\n    bit_offset -= LIMB_BITS;\n    for(;;) {\n        v1 = get_limbz(a, bit_offset >> LIMB_LOG2_BITS);\n        v2 = get_bits(b->tab, b->len, bit_offset + b_offset);\n        //        printf(\"v1=\" FMT_LIMB \" v2=\" FMT_LIMB \"\\n\", v1, v2);\n        if (v1 != 0 || v2 != -1) {\n            /* different: count the matching bits */\n            p1 = bf_min(clz(v1), clz(~v2));\n            n += p1;\n            break;\n        }\n        n += LIMB_BITS;\n        bit_offset -= LIMB_BITS;\n    }\n done:\n    return n;\n}\n\nstatic int bf_add_internal(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n                           bf_flags_t flags, int b_neg)\n{\n    const bf_t *tmp;\n    int is_sub, ret, cmp_res, a_sign, b_sign;\n\n    a_sign = a->sign;\n    b_sign = b->sign ^ b_neg;\n    is_sub = a_sign ^ b_sign;\n    cmp_res = bf_cmpu(a, b);\n    if (cmp_res < 0) {\n        tmp = a;\n        a = b;\n        b = tmp;\n        a_sign = b_sign; /* b_sign is never used later */\n    }\n    /* abs(a) >= abs(b) */\n    if (cmp_res == 0 && is_sub && a->expn < BF_EXP_INF) {\n        /* zero result */\n        bf_set_zero(r, (flags & BF_RND_MASK) == BF_RNDD);\n        ret = 0;\n    } else if (a->len == 0 || b->len == 0) {\n        ret = 0;\n        if (a->expn >= BF_EXP_INF) {\n            if (a->expn == BF_EXP_NAN) {\n                /* at least one operand is NaN */\n                bf_set_nan(r);\n            } else if (b->expn == BF_EXP_INF && is_sub) {\n                /* infinities with different signs */\n                bf_set_nan(r);\n                ret = BF_ST_INVALID_OP;\n            } else {\n                bf_set_inf(r, a_sign);\n            }\n        } else {\n            /* at least one zero and not subtract */\n            bf_set(r, a);\n            r->sign = a_sign;\n            goto renorm;\n        }\n    } else {\n        slimb_t d, a_offset, b_bit_offset, i, cancelled_bits;\n        limb_t carry, v1, v2, u, r_len, carry1, precl, tot_len, z, sub_mask;\n\n        r->sign = a_sign;\n        r->expn = a->expn;\n        d = a->expn - b->expn;\n        /* must add more precision for the leading cancelled bits in\n           subtraction */\n        if (is_sub) {\n            if (d <= 1)\n                cancelled_bits = count_cancelled_bits(a, b);\n            else\n                cancelled_bits = 1;\n        } else {\n            cancelled_bits = 0;\n        }\n        \n        /* add two extra bits for rounding */\n        precl = (cancelled_bits + prec + 2 + LIMB_BITS - 1) / LIMB_BITS;\n        tot_len = bf_max(a->len, b->len + (d + LIMB_BITS - 1) / LIMB_BITS);\n        r_len = bf_min(precl, tot_len);\n        if (bf_resize(r, r_len))\n            goto fail;\n        a_offset = a->len - r_len;\n        b_bit_offset = (b->len - r_len) * LIMB_BITS + d;\n\n        /* compute the bits before for the rounding */\n        carry = is_sub;\n        z = 0;\n        sub_mask = -is_sub;\n        i = r_len - tot_len;\n        while (i < 0) {\n            slimb_t ap, bp;\n            BOOL inflag;\n            \n            ap = a_offset + i;\n            bp = b_bit_offset + i * LIMB_BITS;\n            inflag = FALSE;\n            if (ap >= 0 && ap < a->len) {\n                v1 = a->tab[ap];\n                inflag = TRUE;\n            } else {\n                v1 = 0;\n            }\n            if (bp + LIMB_BITS > 0 && bp < (slimb_t)(b->len * LIMB_BITS)) {\n                v2 = get_bits(b->tab, b->len, bp);\n                inflag = TRUE;\n            } else {\n                v2 = 0;\n            }\n            if (!inflag) {\n                /* outside 'a' and 'b': go directly to the next value\n                   inside a or b so that the running time does not\n                   depend on the exponent difference */\n                i = 0;\n                if (ap < 0)\n                    i = bf_min(i, -a_offset);\n                /* b_bit_offset + i * LIMB_BITS + LIMB_BITS >= 1\n                   equivalent to \n                   i >= ceil(-b_bit_offset + 1 - LIMB_BITS) / LIMB_BITS)\n                */\n                if (bp + LIMB_BITS <= 0)\n                    i = bf_min(i, (-b_bit_offset) >> LIMB_LOG2_BITS);\n            } else {\n                i++;\n            }\n            v2 ^= sub_mask;\n            u = v1 + v2;\n            carry1 = u < v1;\n            u += carry;\n            carry = (u < carry) | carry1;\n            z |= u;\n        }\n        /* and the result */\n        for(i = 0; i < r_len; i++) {\n            v1 = get_limbz(a, a_offset + i);\n            v2 = get_bits(b->tab, b->len, b_bit_offset + i * LIMB_BITS);\n            v2 ^= sub_mask;\n            u = v1 + v2;\n            carry1 = u < v1;\n            u += carry;\n            carry = (u < carry) | carry1;\n            r->tab[i] = u;\n        }\n        /* set the extra bits for the rounding */\n        r->tab[0] |= (z != 0);\n\n        /* carry is only possible in add case */\n        if (!is_sub && carry) {\n            if (bf_resize(r, r_len + 1))\n                goto fail;\n            r->tab[r_len] = 1;\n            r->expn += LIMB_BITS;\n        }\n    renorm:\n        ret = bf_normalize_and_round(r, prec, flags);\n    }\n    return ret;\n fail:\n    bf_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\nstatic int __bf_add(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n                     bf_flags_t flags)\n{\n    return bf_add_internal(r, a, b, prec, flags, 0);\n}\n\nstatic int __bf_sub(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n                     bf_flags_t flags)\n{\n    return bf_add_internal(r, a, b, prec, flags, 1);\n}\n\nlimb_t mp_add(limb_t *res, const limb_t *op1, const limb_t *op2, \n              limb_t n, limb_t carry)\n{\n    slimb_t i;\n    limb_t k, a, v, k1;\n    \n    k = carry;\n    for(i=0;i<n;i++) {\n        v = op1[i];\n        a = v + op2[i];\n        k1 = a < v;\n        a = a + k;\n        k = (a < k) | k1;\n        res[i] = a;\n    }\n    return k;\n}\n\nlimb_t mp_add_ui(limb_t *tab, limb_t b, size_t n)\n{\n    size_t i;\n    limb_t k, a;\n\n    k=b;\n    for(i=0;i<n;i++) {\n        if (k == 0)\n            break;\n        a = tab[i] + k;\n        k = (a < k);\n        tab[i] = a;\n    }\n    return k;\n}\n\nlimb_t mp_sub(limb_t *res, const limb_t *op1, const limb_t *op2, \n              mp_size_t n, limb_t carry)\n{\n    int i;\n    limb_t k, a, v, k1;\n    \n    k = carry;\n    for(i=0;i<n;i++) {\n        v = op1[i];\n        a = v - op2[i];\n        k1 = a > v;\n        v = a - k;\n        k = (v > a) | k1;\n        res[i] = v;\n    }\n    return k;\n}\n\n/* compute 0 - op2 */\nstatic limb_t mp_neg(limb_t *res, const limb_t *op2, mp_size_t n, limb_t carry)\n{\n    int i;\n    limb_t k, a, v, k1;\n    \n    k = carry;\n    for(i=0;i<n;i++) {\n        v = 0;\n        a = v - op2[i];\n        k1 = a > v;\n        v = a - k;\n        k = (v > a) | k1;\n        res[i] = v;\n    }\n    return k;\n}\n\nlimb_t mp_sub_ui(limb_t *tab, limb_t b, mp_size_t n)\n{\n    mp_size_t i;\n    limb_t k, a, v;\n    \n    k=b;\n    for(i=0;i<n;i++) {\n        v = tab[i];\n        a = v - k;\n        k = a > v;\n        tab[i] = a;\n        if (k == 0)\n            break;\n    }\n    return k;\n}\n\n/* r = (a + high*B^n) >> shift. Return the remainder r (0 <= r < 2^shift). \n   1 <= shift <= LIMB_BITS - 1 */\nstatic limb_t mp_shr(limb_t *tab_r, const limb_t *tab, mp_size_t n, \n                     int shift, limb_t high)\n{\n    mp_size_t i;\n    limb_t l, a;\n\n    assert(shift >= 1 && shift < LIMB_BITS);\n    l = high;\n    for(i = n - 1; i >= 0; i--) {\n        a = tab[i];\n        tab_r[i] = (a >> shift) | (l << (LIMB_BITS - shift));\n        l = a;\n    }\n    return l & (((limb_t)1 << shift) - 1);\n}\n\n/* tabr[] = taba[] * b + l. Return the high carry */\nstatic limb_t mp_mul1(limb_t *tabr, const limb_t *taba, limb_t n, \n                      limb_t b, limb_t l)\n{\n    limb_t i;\n    dlimb_t t;\n\n    for(i = 0; i < n; i++) {\n        t = (dlimb_t)taba[i] * (dlimb_t)b + l;\n        tabr[i] = t;\n        l = t >> LIMB_BITS;\n    }\n    return l;\n}\n\n/* tabr[] += taba[] * b, return the high word. */\nstatic limb_t mp_add_mul1(limb_t *tabr, const limb_t *taba, limb_t n,\n                          limb_t b)\n{\n    limb_t i, l;\n    dlimb_t t;\n    \n    l = 0;\n    for(i = 0; i < n; i++) {\n        t = (dlimb_t)taba[i] * (dlimb_t)b + l + tabr[i];\n        tabr[i] = t;\n        l = t >> LIMB_BITS;\n    }\n    return l;\n}\n\n/* size of the result : op1_size + op2_size. */\nstatic void mp_mul_basecase(limb_t *result, \n                            const limb_t *op1, limb_t op1_size, \n                            const limb_t *op2, limb_t op2_size) \n{\n    limb_t i, r;\n    \n    result[op1_size] = mp_mul1(result, op1, op1_size, op2[0], 0);\n    for(i=1;i<op2_size;i++) {\n        r = mp_add_mul1(result + i, op1, op1_size, op2[i]);\n        result[i + op1_size] = r;\n    }\n}\n\n/* return 0 if OK, -1 if memory error */\n/* XXX: change API so that result can be allocated */\nint mp_mul(bf_context_t *s, limb_t *result, \n           const limb_t *op1, limb_t op1_size, \n           const limb_t *op2, limb_t op2_size) \n{\n#ifdef USE_FFT_MUL\n    if (unlikely(bf_min(op1_size, op2_size) >= FFT_MUL_THRESHOLD)) {\n        bf_t r_s, *r = &r_s;\n        r->tab = result;\n        /* XXX: optimize memory usage in API */\n        if (fft_mul(s, r, (limb_t *)op1, op1_size,\n                    (limb_t *)op2, op2_size, FFT_MUL_R_NORESIZE))\n            return -1;\n    } else\n#endif\n    {\n        mp_mul_basecase(result, op1, op1_size, op2, op2_size);\n    }\n    return 0;\n}\n\n/* tabr[] -= taba[] * b. Return the value to substract to the high\n   word. */\nstatic limb_t mp_sub_mul1(limb_t *tabr, const limb_t *taba, limb_t n,\n                          limb_t b)\n{\n    limb_t i, l;\n    dlimb_t t;\n    \n    l = 0;\n    for(i = 0; i < n; i++) {\n        t = tabr[i] - (dlimb_t)taba[i] * (dlimb_t)b - l;\n        tabr[i] = t;\n        l = -(t >> LIMB_BITS);\n    }\n    return l;\n}\n\n/* WARNING: d must be >= 2^(LIMB_BITS-1) */\nstatic inline limb_t udiv1norm_init(limb_t d)\n{\n    limb_t a0, a1;\n    a1 = -d - 1;\n    a0 = -1;\n    return (((dlimb_t)a1 << LIMB_BITS) | a0) / d;\n}\n\n/* return the quotient and the remainder in '*pr'of 'a1*2^LIMB_BITS+a0\n   / d' with 0 <= a1 < d. */\nstatic inline limb_t udiv1norm(limb_t *pr, limb_t a1, limb_t a0,\n                                limb_t d, limb_t d_inv)\n{\n    limb_t n1m, n_adj, q, r, ah;\n    dlimb_t a;\n    n1m = ((slimb_t)a0 >> (LIMB_BITS - 1));\n    n_adj = a0 + (n1m & d);\n    a = (dlimb_t)d_inv * (a1 - n1m) + n_adj;\n    q = (a >> LIMB_BITS) + a1;\n    /* compute a - q * r and update q so that the remainder is\\\n       between 0 and d - 1 */\n    a = ((dlimb_t)a1 << LIMB_BITS) | a0;\n    a = a - (dlimb_t)q * d - d;\n    ah = a >> LIMB_BITS;\n    q += 1 + ah;\n    r = (limb_t)a + (ah & d);\n    *pr = r;\n    return q;\n}\n\n/* b must be >= 1 << (LIMB_BITS - 1) */\nstatic limb_t mp_div1norm(limb_t *tabr, const limb_t *taba, limb_t n,\n                          limb_t b, limb_t r)\n{\n    slimb_t i;\n\n    if (n >= UDIV1NORM_THRESHOLD) {\n        limb_t b_inv;\n        b_inv = udiv1norm_init(b);\n        for(i = n - 1; i >= 0; i--) {\n            tabr[i] = udiv1norm(&r, r, taba[i], b, b_inv);\n        }\n    } else {\n        dlimb_t a1;\n        for(i = n - 1; i >= 0; i--) {\n            a1 = ((dlimb_t)r << LIMB_BITS) | taba[i];\n            tabr[i] = a1 / b;\n            r = a1 % b;\n        }\n    }\n    return r;\n}\n\nstatic int mp_divnorm_large(bf_context_t *s, \n                            limb_t *tabq, limb_t *taba, limb_t na, \n                            const limb_t *tabb, limb_t nb);\n\n/* base case division: divides taba[0..na-1] by tabb[0..nb-1]. tabb[nb\n   - 1] must be >= 1 << (LIMB_BITS - 1). na - nb must be >= 0. 'taba'\n   is modified and contains the remainder (nb limbs). tabq[0..na-nb]\n   contains the quotient with tabq[na - nb] <= 1. */\nstatic int mp_divnorm(bf_context_t *s, limb_t *tabq, limb_t *taba, limb_t na, \n                      const limb_t *tabb, limb_t nb)\n{\n    limb_t r, a, c, q, v, b1, b1_inv, n, dummy_r;\n    slimb_t i, j;\n\n    b1 = tabb[nb - 1];\n    if (nb == 1) {\n        taba[0] = mp_div1norm(tabq, taba, na, b1, 0);\n        return 0;\n    }\n    n = na - nb;\n    if (bf_min(n, nb) >= DIVNORM_LARGE_THRESHOLD) {\n        return mp_divnorm_large(s, tabq, taba, na, tabb, nb);\n    }\n    \n    if (n >= UDIV1NORM_THRESHOLD)\n        b1_inv = udiv1norm_init(b1);\n    else\n        b1_inv = 0;\n\n    /* first iteration: the quotient is only 0 or 1 */\n    q = 1;\n    for(j = nb - 1; j >= 0; j--) {\n        if (taba[n + j] != tabb[j]) {\n            if (taba[n + j] < tabb[j])\n                q = 0;\n            break;\n        }\n    }\n    tabq[n] = q;\n    if (q) {\n        mp_sub(taba + n, taba + n, tabb, nb, 0);\n    }\n    \n    for(i = n - 1; i >= 0; i--) {\n        if (unlikely(taba[i + nb] >= b1)) {\n            q = -1;\n        } else if (b1_inv) {\n            q = udiv1norm(&dummy_r, taba[i + nb], taba[i + nb - 1], b1, b1_inv);\n        } else {\n            dlimb_t al;\n            al = ((dlimb_t)taba[i + nb] << LIMB_BITS) | taba[i + nb - 1];\n            q = al / b1;\n            r = al % b1;\n        }\n        r = mp_sub_mul1(taba + i, tabb, nb, q);\n\n        v = taba[i + nb];\n        a = v - r;\n        c = (a > v);\n        taba[i + nb] = a;\n\n        if (c != 0) {\n            /* negative result */\n            for(;;) {\n                q--;\n                c = mp_add(taba + i, taba + i, tabb, nb, 0);\n                /* propagate carry and test if positive result */\n                if (c != 0) {\n                    if (++taba[i + nb] == 0) {\n                        break;\n                    }\n                }\n            }\n        }\n        tabq[i] = q;\n    }\n    return 0;\n}\n\n/* compute r=B^(2*n)/a such as a*r < B^(2*n) < a*r + 2 with n >= 1. 'a'\n   has n limbs with a[n-1] >= B/2 and 'r' has n+1 limbs with r[n] = 1.\n   \n   See Modern Computer Arithmetic by Richard P. Brent and Paul\n   Zimmermann, algorithm 3.5 */\nint mp_recip(bf_context_t *s, limb_t *tabr, const limb_t *taba, limb_t n)\n{\n    mp_size_t l, h, k, i;\n    limb_t *tabxh, *tabt, c, *tabu;\n    \n    if (n <= 2) {\n        /* return ceil(B^(2*n)/a) - 1 */\n        /* XXX: could avoid allocation */\n        tabu = bf_malloc(s, sizeof(limb_t) * (2 * n + 1));\n        tabt = bf_malloc(s, sizeof(limb_t) * (n + 2));\n        if (!tabt || !tabu)\n            goto fail;\n        for(i = 0; i < 2 * n; i++)\n            tabu[i] = 0;\n        tabu[2 * n] = 1;\n        if (mp_divnorm(s, tabt, tabu, 2 * n + 1, taba, n))\n            goto fail;\n        for(i = 0; i < n + 1; i++)\n            tabr[i] = tabt[i];\n        if (mp_scan_nz(tabu, n) == 0) {\n            /* only happens for a=B^n/2 */\n            mp_sub_ui(tabr, 1, n + 1);\n        }\n    } else {\n        l = (n - 1) / 2;\n        h = n - l;\n        /* n=2p  -> l=p-1, h = p + 1, k = p + 3\n           n=2p+1-> l=p,  h = p + 1; k = p + 2\n        */\n        tabt = bf_malloc(s, sizeof(limb_t) * (n + h + 1));\n        tabu = bf_malloc(s, sizeof(limb_t) * (n + 2 * h - l + 2));\n        if (!tabt || !tabu)\n            goto fail;\n        tabxh = tabr + l;\n        if (mp_recip(s, tabxh, taba + l, h))\n            goto fail;\n        if (mp_mul(s, tabt, taba, n, tabxh, h + 1)) /* n + h + 1 limbs */\n            goto fail;\n        while (tabt[n + h] != 0) {\n            mp_sub_ui(tabxh, 1, h + 1);\n            c = mp_sub(tabt, tabt, taba, n, 0);\n            mp_sub_ui(tabt + n, c, h + 1);\n        }\n        /* T = B^(n+h) - T */\n        mp_neg(tabt, tabt, n + h + 1, 0);\n        tabt[n + h]++;\n        if (mp_mul(s, tabu, tabt + l, n + h + 1 - l, tabxh, h + 1))\n            goto fail;\n        /* n + 2*h - l + 2 limbs */\n        k = 2 * h - l;\n        for(i = 0; i < l; i++)\n            tabr[i] = tabu[i + k];\n        mp_add(tabr + l, tabr + l, tabu + 2 * h, h, 0);\n    }\n    bf_free(s, tabt);\n    bf_free(s, tabu);\n    return 0;\n fail:\n    bf_free(s, tabt);\n    bf_free(s, tabu);\n    return -1;\n}\n\n/* return -1, 0 or 1 */\nstatic int mp_cmp(const limb_t *taba, const limb_t *tabb, mp_size_t n)\n{\n    mp_size_t i;\n    for(i = n - 1; i >= 0; i--) {\n        if (taba[i] != tabb[i]) {\n            if (taba[i] < tabb[i])\n                return -1;\n            else\n                return 1;\n        }\n    }\n    return 0;\n}\n\n//#define DEBUG_DIVNORM_LARGE\n//#define DEBUG_DIVNORM_LARGE2\n\n/* subquadratic divnorm */\nstatic int mp_divnorm_large(bf_context_t *s, \n                            limb_t *tabq, limb_t *taba, limb_t na, \n                            const limb_t *tabb, limb_t nb)\n{\n    limb_t *tabb_inv, nq, *tabt, i, n;\n    nq = na - nb;\n#ifdef DEBUG_DIVNORM_LARGE\n    printf(\"na=%d nb=%d nq=%d\\n\", (int)na, (int)nb, (int)nq);\n    mp_print_str(\"a\", taba, na);\n    mp_print_str(\"b\", tabb, nb);\n#endif\n    assert(nq >= 1);\n    n = nq;\n    if (nq < nb)\n        n++; \n    tabb_inv = bf_malloc(s, sizeof(limb_t) * (n + 1));\n    tabt = bf_malloc(s, sizeof(limb_t) * 2 * (n + 1));\n    if (!tabb_inv || !tabt)\n        goto fail;\n\n    if (n >= nb) {\n        for(i = 0; i < n - nb; i++)\n            tabt[i] = 0;\n        for(i = 0; i < nb; i++)\n            tabt[i + n - nb] = tabb[i];\n    } else {\n        /* truncate B: need to increment it so that the approximate\n           inverse is smaller that the exact inverse */\n        for(i = 0; i < n; i++)\n            tabt[i] = tabb[i + nb - n];\n        if (mp_add_ui(tabt, 1, n)) {\n            /* tabt = B^n : tabb_inv = B^n */\n            memset(tabb_inv, 0, n * sizeof(limb_t));\n            tabb_inv[n] = 1;\n            goto recip_done;\n        }\n    }\n    if (mp_recip(s, tabb_inv, tabt, n))\n        goto fail;\n recip_done:\n    /* Q=A*B^-1 */\n    if (mp_mul(s, tabt, tabb_inv, n + 1, taba + na - (n + 1), n + 1))\n        goto fail;\n    \n    for(i = 0; i < nq + 1; i++)\n        tabq[i] = tabt[i + 2 * (n + 1) - (nq + 1)];\n#ifdef DEBUG_DIVNORM_LARGE\n    mp_print_str(\"q\", tabq, nq + 1);\n#endif\n\n    bf_free(s, tabt);\n    bf_free(s, tabb_inv);\n    tabb_inv = NULL;\n    \n    /* R=A-B*Q */\n    tabt = bf_malloc(s, sizeof(limb_t) * (na + 1));\n    if (!tabt)\n        goto fail;\n    if (mp_mul(s, tabt, tabq, nq + 1, tabb, nb))\n        goto fail;\n    /* we add one more limb for the result */\n    mp_sub(taba, taba, tabt, nb + 1, 0);\n    bf_free(s, tabt);\n    /* the approximated quotient is smaller than than the exact one,\n       hence we may have to increment it */\n#ifdef DEBUG_DIVNORM_LARGE2\n    int cnt = 0;\n    static int cnt_max;\n#endif\n    for(;;) {\n        if (taba[nb] == 0 && mp_cmp(taba, tabb, nb) < 0)\n            break;\n        taba[nb] -= mp_sub(taba, taba, tabb, nb, 0);\n        mp_add_ui(tabq, 1, nq + 1);\n#ifdef DEBUG_DIVNORM_LARGE2\n        cnt++;\n#endif\n    }\n#ifdef DEBUG_DIVNORM_LARGE2\n    if (cnt > cnt_max) {\n        cnt_max = cnt;\n        printf(\"\\ncnt=%d nq=%d nb=%d\\n\", cnt_max, (int)nq, (int)nb);\n    }\n#endif\n    return 0;\n fail:\n    bf_free(s, tabb_inv);\n    bf_free(s, tabt);\n    return -1;\n}\n\nint bf_mul(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n           bf_flags_t flags)\n{\n    int ret, r_sign;\n\n    if (a->len < b->len) {\n        const bf_t *tmp = a;\n        a = b;\n        b = tmp;\n    }\n    r_sign = a->sign ^ b->sign;\n    /* here b->len <= a->len */\n    if (b->len == 0) {\n        if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            ret = 0;\n        } else if (a->expn == BF_EXP_INF || b->expn == BF_EXP_INF) {\n            if ((a->expn == BF_EXP_INF && b->expn == BF_EXP_ZERO) ||\n                (a->expn == BF_EXP_ZERO && b->expn == BF_EXP_INF)) {\n                bf_set_nan(r);\n                ret = BF_ST_INVALID_OP;\n            } else {\n                bf_set_inf(r, r_sign);\n                ret = 0;\n            }\n        } else {\n            bf_set_zero(r, r_sign);\n            ret = 0;\n        }\n    } else {\n        bf_t tmp, *r1 = NULL;\n        limb_t a_len, b_len, precl;\n        limb_t *a_tab, *b_tab;\n            \n        a_len = a->len;\n        b_len = b->len;\n        \n        if ((flags & BF_RND_MASK) == BF_RNDF) {\n            /* faithful rounding does not require using the full inputs */\n            precl = (prec + 2 + LIMB_BITS - 1) / LIMB_BITS;\n            a_len = bf_min(a_len, precl);\n            b_len = bf_min(b_len, precl);\n        }\n        a_tab = a->tab + a->len - a_len;\n        b_tab = b->tab + b->len - b_len;\n        \n#ifdef USE_FFT_MUL\n        if (b_len >= FFT_MUL_THRESHOLD) {\n            int mul_flags = 0;\n            if (r == a)\n                mul_flags |= FFT_MUL_R_OVERLAP_A;\n            if (r == b)\n                mul_flags |= FFT_MUL_R_OVERLAP_B;\n            if (fft_mul(r->ctx, r, a_tab, a_len, b_tab, b_len, mul_flags))\n                goto fail;\n        } else\n#endif\n        {\n            if (r == a || r == b) {\n                bf_init(r->ctx, &tmp);\n                r1 = r;\n                r = &tmp;\n            }\n            if (bf_resize(r, a_len + b_len)) {\n            fail:\n                bf_set_nan(r);\n                ret = BF_ST_MEM_ERROR;\n                goto done;\n            }\n            mp_mul_basecase(r->tab, a_tab, a_len, b_tab, b_len);\n        }\n        r->sign = r_sign;\n        r->expn = a->expn + b->expn;\n        ret = bf_normalize_and_round(r, prec, flags);\n    done:\n        if (r == &tmp)\n            bf_move(r1, &tmp);\n    }\n    return ret;\n}\n\n/* multiply 'r' by 2^e */\nint bf_mul_2exp(bf_t *r, slimb_t e, limb_t prec, bf_flags_t flags)\n{\n    slimb_t e_max;\n    if (r->len == 0)\n        return 0;\n    e_max = ((limb_t)1 << BF_EXT_EXP_BITS_MAX) - 1;\n    e = bf_max(e, -e_max);\n    e = bf_min(e, e_max);\n    r->expn += e;\n    return __bf_round(r, prec, flags, r->len, 0);\n}\n\n/* Return e such as a=m*2^e with m odd integer. return 0 if a is zero,\n   Infinite or Nan. */\nslimb_t bf_get_exp_min(const bf_t *a)\n{\n    slimb_t i;\n    limb_t v;\n    int k;\n    \n    for(i = 0; i < a->len; i++) {\n        v = a->tab[i];\n        if (v != 0) {\n            k = ctz(v);\n            return a->expn - (a->len - i) * LIMB_BITS + k;\n        }\n    }\n    return 0;\n}\n\n/* a and b must be finite numbers with a >= 0 and b > 0. 'q' is the\n   integer defined as floor(a/b) and r = a - q * b. */\nstatic void bf_tdivremu(bf_t *q, bf_t *r,\n                        const bf_t *a, const bf_t *b)\n{\n    if (bf_cmpu(a, b) < 0) {\n        bf_set_ui(q, 0);\n        bf_set(r, a);\n    } else {\n        bf_div(q, a, b, bf_max(a->expn - b->expn + 1, 2), BF_RNDZ);\n        bf_rint(q, BF_RNDZ);\n        bf_mul(r, q, b, BF_PREC_INF, BF_RNDZ);\n        bf_sub(r, a, r, BF_PREC_INF, BF_RNDZ);\n    }\n}\n\nstatic int __bf_div(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n                    bf_flags_t flags)\n{\n    bf_context_t *s = r->ctx;\n    int ret, r_sign;\n    limb_t n, nb, precl;\n    \n    r_sign = a->sign ^ b->sign;\n    if (a->expn >= BF_EXP_INF || b->expn >= BF_EXP_INF) {\n        if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF && b->expn == BF_EXP_INF) {\n            bf_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else if (a->expn == BF_EXP_INF) {\n            bf_set_inf(r, r_sign);\n            return 0;\n        } else {\n            bf_set_zero(r, r_sign);\n            return 0;\n        }\n    } else if (a->expn == BF_EXP_ZERO) {\n        if (b->expn == BF_EXP_ZERO) {\n            bf_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bf_set_zero(r, r_sign);\n            return 0;\n        }\n    } else if (b->expn == BF_EXP_ZERO) {\n        bf_set_inf(r, r_sign);\n        return BF_ST_DIVIDE_ZERO;\n    }\n\n    /* number of limbs of the quotient (2 extra bits for rounding) */\n    precl = (prec + 2 + LIMB_BITS - 1) / LIMB_BITS;\n    nb = b->len;\n    n = bf_max(a->len, precl);\n    \n    {\n        limb_t *taba, na;\n        slimb_t d;\n        \n        na = n + nb;\n        taba = bf_malloc(s, (na + 1) * sizeof(limb_t));\n        if (!taba)\n            goto fail;\n        d = na - a->len;\n        memset(taba, 0, d * sizeof(limb_t));\n        memcpy(taba + d, a->tab, a->len * sizeof(limb_t));\n        if (bf_resize(r, n + 1))\n            goto fail1;\n        if (mp_divnorm(s, r->tab, taba, na, b->tab, nb)) {\n        fail1:\n            bf_free(s, taba);\n            goto fail;\n        }\n        /* see if non zero remainder */\n        if (mp_scan_nz(taba, nb))\n            r->tab[0] |= 1;\n        bf_free(r->ctx, taba);\n        r->expn = a->expn - b->expn + LIMB_BITS;\n        r->sign = r_sign;\n        ret = bf_normalize_and_round(r, prec, flags);\n    }\n    return ret;\n fail:\n    bf_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\n/* division and remainder. \n   \n   rnd_mode is the rounding mode for the quotient. The additional\n   rounding mode BF_RND_EUCLIDIAN is supported.\n\n   'q' is an integer. 'r' is rounded with prec and flags (prec can be\n   BF_PREC_INF).\n*/\nint bf_divrem(bf_t *q, bf_t *r, const bf_t *a, const bf_t *b,\n              limb_t prec, bf_flags_t flags, int rnd_mode)\n{\n    bf_t a1_s, *a1 = &a1_s;\n    bf_t b1_s, *b1 = &b1_s;\n    int q_sign, ret;\n    BOOL is_ceil, is_rndn;\n    \n    assert(q != a && q != b);\n    assert(r != a && r != b);\n    assert(q != r);\n    \n    if (a->len == 0 || b->len == 0) {\n        bf_set_zero(q, 0);\n        if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF || b->expn == BF_EXP_ZERO) {\n            bf_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bf_set(r, a);\n            return bf_round(r, prec, flags);\n        }\n    }\n\n    q_sign = a->sign ^ b->sign;\n    is_rndn = (rnd_mode == BF_RNDN || rnd_mode == BF_RNDNA);\n    switch(rnd_mode) {\n    default:\n    case BF_RNDZ:\n    case BF_RNDN:\n    case BF_RNDNA:\n        is_ceil = FALSE;\n        break;\n    case BF_RNDD:\n        is_ceil = q_sign;\n        break;\n    case BF_RNDU:\n        is_ceil = q_sign ^ 1;\n        break;\n    case BF_RNDA:\n        is_ceil = TRUE;\n        break;\n    case BF_DIVREM_EUCLIDIAN:\n        is_ceil = a->sign;\n        break;\n    }\n\n    a1->expn = a->expn;\n    a1->tab = a->tab;\n    a1->len = a->len;\n    a1->sign = 0;\n    \n    b1->expn = b->expn;\n    b1->tab = b->tab;\n    b1->len = b->len;\n    b1->sign = 0;\n\n    /* XXX: could improve to avoid having a large 'q' */\n    bf_tdivremu(q, r, a1, b1);\n    if (bf_is_nan(q) || bf_is_nan(r))\n        goto fail;\n\n    if (r->len != 0) {\n        if (is_rndn) {\n            int res;\n            b1->expn--;\n            res = bf_cmpu(r, b1);\n            b1->expn++;\n            if (res > 0 ||\n                (res == 0 &&\n                 (rnd_mode == BF_RNDNA ||\n                  get_bit(q->tab, q->len, q->len * LIMB_BITS - q->expn)))) {\n                goto do_sub_r;\n            }\n        } else if (is_ceil) {\n        do_sub_r:\n            ret = bf_add_si(q, q, 1, BF_PREC_INF, BF_RNDZ);\n            ret |= bf_sub(r, r, b1, BF_PREC_INF, BF_RNDZ);\n            if (ret & BF_ST_MEM_ERROR)\n                goto fail;\n        }\n    }\n\n    r->sign ^= a->sign;\n    q->sign = q_sign;\n    return bf_round(r, prec, flags);\n fail:\n    bf_set_nan(q);\n    bf_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\nint bf_rem(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n           bf_flags_t flags, int rnd_mode)\n{\n    bf_t q_s, *q = &q_s;\n    int ret;\n    \n    bf_init(r->ctx, q);\n    ret = bf_divrem(q, r, a, b, prec, flags, rnd_mode);\n    bf_delete(q);\n    return ret;\n}\n\nstatic inline int bf_get_limb(slimb_t *pres, const bf_t *a, int flags)\n{\n#if LIMB_BITS == 32\n    return bf_get_int32(pres, a, flags);\n#else\n    return bf_get_int64(pres, a, flags);\n#endif\n}\n\nint bf_remquo(slimb_t *pq, bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n              bf_flags_t flags, int rnd_mode)\n{\n    bf_t q_s, *q = &q_s;\n    int ret;\n    \n    bf_init(r->ctx, q);\n    ret = bf_divrem(q, r, a, b, prec, flags, rnd_mode);\n    bf_get_limb(pq, q, BF_GET_INT_MOD);\n    bf_delete(q);\n    return ret;\n}\n\nstatic __maybe_unused inline limb_t mul_mod(limb_t a, limb_t b, limb_t m)\n{\n    dlimb_t t;\n    t = (dlimb_t)a * (dlimb_t)b;\n    return t % m;\n}\n\n#if defined(USE_MUL_CHECK)\nstatic limb_t mp_mod1(const limb_t *tab, limb_t n, limb_t m, limb_t r)\n{\n    slimb_t i;\n    dlimb_t t;\n\n    for(i = n - 1; i >= 0; i--) {\n        t = ((dlimb_t)r << LIMB_BITS) | tab[i];\n        r = t % m;\n    }\n    return r;\n}\n#endif\n\nstatic const uint16_t sqrt_table[192] = {\n128,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,144,145,146,147,148,149,150,150,151,152,153,154,155,155,156,157,158,159,160,160,161,162,163,163,164,165,166,167,167,168,169,170,170,171,172,173,173,174,175,176,176,177,178,178,179,180,181,181,182,183,183,184,185,185,186,187,187,188,189,189,190,191,192,192,193,193,194,195,195,196,197,197,198,199,199,200,201,201,202,203,203,204,204,205,206,206,207,208,208,209,209,210,211,211,212,212,213,214,214,215,215,216,217,217,218,218,219,219,220,221,221,222,222,223,224,224,225,225,226,226,227,227,228,229,229,230,230,231,231,232,232,233,234,234,235,235,236,236,237,237,238,238,239,240,240,241,241,242,242,243,243,244,244,245,245,246,246,247,247,248,248,249,249,250,250,251,251,252,252,253,253,254,254,255,\n};\n\n/* a >= 2^(LIMB_BITS - 2).  Return (s, r) with s=floor(sqrt(a)) and\n   r=a-s^2. 0 <= r <= 2 * s */\nstatic limb_t mp_sqrtrem1(limb_t *pr, limb_t a)\n{\n    limb_t s1, r1, s, r, q, u, num;\n    \n    /* use a table for the 16 -> 8 bit sqrt */\n    s1 = sqrt_table[(a >> (LIMB_BITS - 8)) - 64];\n    r1 = (a >> (LIMB_BITS - 16)) - s1 * s1;\n    if (r1 > 2 * s1) {\n        r1 -= 2 * s1 + 1;\n        s1++;\n    }\n    \n    /* one iteration to get a 32 -> 16 bit sqrt */\n    num = (r1 << 8) | ((a >> (LIMB_BITS - 32 + 8)) & 0xff);\n    q = num / (2 * s1); /* q <= 2^8 */\n    u = num % (2 * s1);\n    s = (s1 << 8) + q;\n    r = (u << 8) | ((a >> (LIMB_BITS - 32)) & 0xff);\n    r -= q * q;\n    if ((slimb_t)r < 0) {\n        s--;\n        r += 2 * s + 1;\n    }\n\n#if LIMB_BITS == 64\n    s1 = s;\n    r1 = r;\n    /* one more iteration for 64 -> 32 bit sqrt */\n    num = (r1 << 16) | ((a >> (LIMB_BITS - 64 + 16)) & 0xffff);\n    q = num / (2 * s1); /* q <= 2^16 */\n    u = num % (2 * s1);\n    s = (s1 << 16) + q;\n    r = (u << 16) | ((a >> (LIMB_BITS - 64)) & 0xffff);\n    r -= q * q;\n    if ((slimb_t)r < 0) {\n        s--;\n        r += 2 * s + 1;\n    }\n#endif\n    *pr = r;\n    return s;\n}\n\n/* return floor(sqrt(a)) */\nlimb_t bf_isqrt(limb_t a)\n{\n    limb_t s, r;\n    int k;\n\n    if (a == 0)\n        return 0;\n    k = clz(a) & ~1;\n    s = mp_sqrtrem1(&r, a << k);\n    s >>= (k >> 1);\n    return s;\n}\n\nstatic limb_t mp_sqrtrem2(limb_t *tabs, limb_t *taba)\n{\n    limb_t s1, r1, s, q, u, a0, a1;\n    dlimb_t r, num;\n    int l;\n\n    a0 = taba[0];\n    a1 = taba[1];\n    s1 = mp_sqrtrem1(&r1, a1);\n    l = LIMB_BITS / 2;\n    num = ((dlimb_t)r1 << l) | (a0 >> l);\n    q = num / (2 * s1);\n    u = num % (2 * s1);\n    s = (s1 << l) + q;\n    r = ((dlimb_t)u << l) | (a0 & (((limb_t)1 << l) - 1));\n    if (unlikely((q >> l) != 0))\n        r -= (dlimb_t)1 << LIMB_BITS; /* special case when q=2^l */\n    else\n        r -= q * q;\n    if ((slimb_t)(r >> LIMB_BITS) < 0) {\n        s--;\n        r += 2 * (dlimb_t)s + 1;\n    }\n    tabs[0] = s;\n    taba[0] = r;\n    return r >> LIMB_BITS;\n}\n\n//#define DEBUG_SQRTREM\n\n/* tmp_buf must contain (n / 2 + 1 limbs). *prh contains the highest\n   limb of the remainder. */\nstatic int mp_sqrtrem_rec(bf_context_t *s, limb_t *tabs, limb_t *taba, limb_t n,\n                          limb_t *tmp_buf, limb_t *prh)\n{\n    limb_t l, h, rh, ql, qh, c, i;\n    \n    if (n == 1) {\n        *prh = mp_sqrtrem2(tabs, taba);\n        return 0;\n    }\n#ifdef DEBUG_SQRTREM\n    mp_print_str(\"a\", taba, 2 * n);\n#endif\n    l = n / 2;\n    h = n - l;\n    if (mp_sqrtrem_rec(s, tabs + l, taba + 2 * l, h, tmp_buf, &qh))\n        return -1;\n#ifdef DEBUG_SQRTREM\n    mp_print_str(\"s1\", tabs + l, h);\n    mp_print_str_h(\"r1\", taba + 2 * l, h, qh);\n    mp_print_str_h(\"r2\", taba + l, n, qh);\n#endif\n    \n    /* the remainder is in taba + 2 * l. Its high bit is in qh */\n    if (qh) {\n        mp_sub(taba + 2 * l, taba + 2 * l, tabs + l, h, 0);\n    }\n    /* instead of dividing by 2*s, divide by s (which is normalized)\n       and update q and r */\n    if (mp_divnorm(s, tmp_buf, taba + l, n, tabs + l, h))\n        return -1;\n    qh += tmp_buf[l];\n    for(i = 0; i < l; i++)\n        tabs[i] = tmp_buf[i];\n    ql = mp_shr(tabs, tabs, l, 1, qh & 1);\n    qh = qh >> 1; /* 0 or 1 */\n    if (ql)\n        rh = mp_add(taba + l, taba + l, tabs + l, h, 0);\n    else\n        rh = 0;\n#ifdef DEBUG_SQRTREM\n    mp_print_str_h(\"q\", tabs, l, qh);\n    mp_print_str_h(\"u\", taba + l, h, rh);\n#endif\n    \n    mp_add_ui(tabs + l, qh, h);\n#ifdef DEBUG_SQRTREM\n    mp_print_str_h(\"s2\", tabs, n, sh);\n#endif\n    \n    /* q = qh, tabs[l - 1 ... 0], r = taba[n - 1 ... l] */\n    /* subtract q^2. if qh = 1 then q = B^l, so we can take shortcuts */\n    if (qh) {\n        c = qh;\n    } else {\n        if (mp_mul(s, taba + n, tabs, l, tabs, l))\n            return -1;\n        c = mp_sub(taba, taba, taba + n, 2 * l, 0);\n    }\n    rh -= mp_sub_ui(taba + 2 * l, c, n - 2 * l);\n    if ((slimb_t)rh < 0) {\n        mp_sub_ui(tabs, 1, n);\n        rh += mp_add_mul1(taba, tabs, n, 2);\n        rh += mp_add_ui(taba, 1, n);\n    }\n    *prh = rh;\n    return 0;\n}\n\n/* 'taba' has 2*n limbs with n >= 1 and taba[2*n-1] >= 2 ^ (LIMB_BITS\n   - 2). Return (s, r) with s=floor(sqrt(a)) and r=a-s^2. 0 <= r <= 2\n   * s. tabs has n limbs. r is returned in the lower n limbs of\n   taba. Its r[n] is the returned value of the function. */\n/* Algorithm from the article \"Karatsuba Square Root\" by Paul Zimmermann and\n   inspirated from its GMP implementation */\nint mp_sqrtrem(bf_context_t *s, limb_t *tabs, limb_t *taba, limb_t n)\n{\n    limb_t tmp_buf1[8];\n    limb_t *tmp_buf;\n    mp_size_t n2;\n    int ret;\n    n2 = n / 2 + 1;\n    if (n2 <= countof(tmp_buf1)) {\n        tmp_buf = tmp_buf1;\n    } else {\n        tmp_buf = bf_malloc(s, sizeof(limb_t) * n2);\n        if (!tmp_buf)\n            return -1;\n    }\n    ret = mp_sqrtrem_rec(s, tabs, taba, n, tmp_buf, taba + n);\n    if (tmp_buf != tmp_buf1)\n        bf_free(s, tmp_buf);\n    return ret;\n}\n\n/* Integer square root with remainder. 'a' must be an integer. r =\n   floor(sqrt(a)) and rem = a - r^2.  BF_ST_INEXACT is set if the result\n   is inexact. 'rem' can be NULL if the remainder is not needed. */\nint bf_sqrtrem(bf_t *r, bf_t *rem1, const bf_t *a)\n{\n    int ret;\n    \n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n        } else if (a->expn == BF_EXP_INF && a->sign) {\n            goto invalid_op;\n        } else {\n            bf_set(r, a);\n        }\n        if (rem1)\n            bf_set_ui(rem1, 0);\n        ret = 0;\n    } else if (a->sign) {\n invalid_op:\n        bf_set_nan(r);\n        if (rem1)\n            bf_set_ui(rem1, 0);\n        ret = BF_ST_INVALID_OP;\n    } else {\n        bf_t rem_s, *rem;\n        \n        bf_sqrt(r, a, (a->expn + 1) / 2, BF_RNDZ);\n        bf_rint(r, BF_RNDZ);\n        /* see if the result is exact by computing the remainder */\n        if (rem1) {\n            rem = rem1;\n        } else {\n            rem = &rem_s;\n            bf_init(r->ctx, rem);\n        }\n        /* XXX: could avoid recomputing the remainder */\n        bf_mul(rem, r, r, BF_PREC_INF, BF_RNDZ);\n        bf_neg(rem);\n        bf_add(rem, rem, a, BF_PREC_INF, BF_RNDZ);\n        if (bf_is_nan(rem)) {\n            ret = BF_ST_MEM_ERROR;\n            goto done;\n        }\n        if (rem->len != 0) {\n            ret = BF_ST_INEXACT;\n        } else {\n            ret = 0;\n        }\n    done:\n        if (!rem1)\n            bf_delete(rem);\n    }\n    return ret;\n}\n\nint bf_sqrt(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = a->ctx;\n    int ret;\n\n    assert(r != a);\n\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n        } else if (a->expn == BF_EXP_INF && a->sign) {\n            goto invalid_op;\n        } else {\n            bf_set(r, a);\n        }\n        ret = 0;\n    } else if (a->sign) {\n invalid_op:\n        bf_set_nan(r);\n        ret = BF_ST_INVALID_OP;\n    } else {\n        limb_t *a1;\n        slimb_t n, n1;\n        limb_t res;\n        \n        /* convert the mantissa to an integer with at least 2 *\n           prec + 4 bits */\n        n = (2 * (prec + 2) + 2 * LIMB_BITS - 1) / (2 * LIMB_BITS);\n        if (bf_resize(r, n))\n            goto fail;\n        a1 = bf_malloc(s, sizeof(limb_t) * 2 * n);\n        if (!a1)\n            goto fail;\n        n1 = bf_min(2 * n, a->len);\n        memset(a1, 0, (2 * n - n1) * sizeof(limb_t));\n        memcpy(a1 + 2 * n - n1, a->tab + a->len - n1, n1 * sizeof(limb_t));\n        if (a->expn & 1) {\n            res = mp_shr(a1, a1, 2 * n, 1, 0);\n        } else {\n            res = 0;\n        }\n        if (mp_sqrtrem(s, r->tab, a1, n)) {\n            bf_free(s, a1);\n            goto fail;\n        }\n        if (!res) {\n            res = mp_scan_nz(a1, n + 1);\n        }\n        bf_free(s, a1);\n        if (!res) {\n            res = mp_scan_nz(a->tab, a->len - n1);\n        }\n        if (res != 0)\n            r->tab[0] |= 1;\n        r->sign = 0;\n        r->expn = (a->expn + 1) >> 1;\n        ret = bf_round(r, prec, flags);\n    }\n    return ret;\n fail:\n    bf_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\nstatic no_inline int bf_op2(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n                            bf_flags_t flags, bf_op2_func_t *func)\n{\n    bf_t tmp;\n    int ret;\n    \n    if (r == a || r == b) {\n        bf_init(r->ctx, &tmp);\n        ret = func(&tmp, a, b, prec, flags);\n        bf_move(r, &tmp);\n    } else {\n        ret = func(r, a, b, prec, flags);\n    }\n    return ret;\n}\n\nint bf_add(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n            bf_flags_t flags)\n{\n    return bf_op2(r, a, b, prec, flags, __bf_add);\n}\n\nint bf_sub(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n            bf_flags_t flags)\n{\n    return bf_op2(r, a, b, prec, flags, __bf_sub);\n}\n\nint bf_div(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n           bf_flags_t flags)\n{\n    return bf_op2(r, a, b, prec, flags, __bf_div);\n}\n\nint bf_mul_ui(bf_t *r, const bf_t *a, uint64_t b1, limb_t prec,\n               bf_flags_t flags)\n{\n    bf_t b;\n    int ret;\n    bf_init(r->ctx, &b);\n    ret = bf_set_ui(&b, b1);\n    ret |= bf_mul(r, a, &b, prec, flags);\n    bf_delete(&b);\n    return ret;\n}\n\nint bf_mul_si(bf_t *r, const bf_t *a, int64_t b1, limb_t prec,\n               bf_flags_t flags)\n{\n    bf_t b;\n    int ret;\n    bf_init(r->ctx, &b);\n    ret = bf_set_si(&b, b1);\n    ret |= bf_mul(r, a, &b, prec, flags);\n    bf_delete(&b);\n    return ret;\n}\n\nint bf_add_si(bf_t *r, const bf_t *a, int64_t b1, limb_t prec,\n              bf_flags_t flags)\n{\n    bf_t b;\n    int ret;\n    \n    bf_init(r->ctx, &b);\n    ret = bf_set_si(&b, b1);\n    ret |= bf_add(r, a, &b, prec, flags);\n    bf_delete(&b);\n    return ret;\n}\n\nstatic int bf_pow_ui(bf_t *r, const bf_t *a, limb_t b, limb_t prec,\n                     bf_flags_t flags)\n{\n    int ret, n_bits, i;\n    \n    assert(r != a);\n    if (b == 0)\n        return bf_set_ui(r, 1);\n    ret = bf_set(r, a);\n    n_bits = LIMB_BITS - clz(b);\n    for(i = n_bits - 2; i >= 0; i--) {\n        ret |= bf_mul(r, r, r, prec, flags);\n        if ((b >> i) & 1)\n            ret |= bf_mul(r, r, a, prec, flags);\n    }\n    return ret;\n}\n\nstatic int bf_pow_ui_ui(bf_t *r, limb_t a1, limb_t b,\n                        limb_t prec, bf_flags_t flags)\n{\n    bf_t a;\n    int ret;\n    \n    if (a1 == 10 && b <= LIMB_DIGITS) {\n        /* use precomputed powers. We do not round at this point\n           because we expect the caller to do it */\n        ret = bf_set_ui(r, mp_pow_dec[b]);\n    } else {\n        bf_init(r->ctx, &a);\n        ret = bf_set_ui(&a, a1);\n        ret |= bf_pow_ui(r, &a, b, prec, flags);\n        bf_delete(&a);\n    }\n    return ret;\n}\n\n/* convert to integer (infinite precision) */\nint bf_rint(bf_t *r, int rnd_mode)\n{\n    return bf_round(r, 0, rnd_mode | BF_FLAG_RADPNT_PREC);\n}\n\n/* logical operations */\n#define BF_LOGIC_OR  0\n#define BF_LOGIC_XOR 1\n#define BF_LOGIC_AND 2\n\nstatic inline limb_t bf_logic_op1(limb_t a, limb_t b, int op)\n{\n    switch(op) {\n    case BF_LOGIC_OR:\n        return a | b;\n    case BF_LOGIC_XOR:\n        return a ^ b;\n    default:\n    case BF_LOGIC_AND:\n        return a & b;\n    }\n}\n\nstatic int bf_logic_op(bf_t *r, const bf_t *a1, const bf_t *b1, int op)\n{\n    bf_t b1_s, a1_s, *a, *b;\n    limb_t a_sign, b_sign, r_sign;\n    slimb_t l, i, a_bit_offset, b_bit_offset;\n    limb_t v1, v2, v1_mask, v2_mask, r_mask;\n    int ret;\n    \n    assert(r != a1 && r != b1);\n\n    if (a1->expn <= 0)\n        a_sign = 0; /* minus zero is considered as positive */\n    else\n        a_sign = a1->sign;\n\n    if (b1->expn <= 0)\n        b_sign = 0; /* minus zero is considered as positive */\n    else\n        b_sign = b1->sign;\n    \n    if (a_sign) {\n        a = &a1_s;\n        bf_init(r->ctx, a);\n        if (bf_add_si(a, a1, 1, BF_PREC_INF, BF_RNDZ)) {\n            b = NULL;\n            goto fail;\n        }\n    } else {\n        a = (bf_t *)a1;\n    }\n\n    if (b_sign) {\n        b = &b1_s;\n        bf_init(r->ctx, b);\n        if (bf_add_si(b, b1, 1, BF_PREC_INF, BF_RNDZ))\n            goto fail;\n    } else {\n        b = (bf_t *)b1;\n    }\n    \n    r_sign = bf_logic_op1(a_sign, b_sign, op);\n    if (op == BF_LOGIC_AND && r_sign == 0) {\n        /* no need to compute extra zeros for and */\n        if (a_sign == 0 && b_sign == 0)\n            l = bf_min(a->expn, b->expn);\n        else if (a_sign == 0)\n            l = a->expn;\n        else\n            l = b->expn;\n    } else {\n        l = bf_max(a->expn, b->expn);\n    }\n    /* Note: a or b can be zero */\n    l = (bf_max(l, 1) + LIMB_BITS - 1) / LIMB_BITS;\n    if (bf_resize(r, l))\n        goto fail;\n    a_bit_offset = a->len * LIMB_BITS - a->expn;\n    b_bit_offset = b->len * LIMB_BITS - b->expn;\n    v1_mask = -a_sign;\n    v2_mask = -b_sign;\n    r_mask = -r_sign;\n    for(i = 0; i < l; i++) {\n        v1 = get_bits(a->tab, a->len, a_bit_offset + i * LIMB_BITS) ^ v1_mask;\n        v2 = get_bits(b->tab, b->len, b_bit_offset + i * LIMB_BITS) ^ v2_mask;\n        r->tab[i] = bf_logic_op1(v1, v2, op) ^ r_mask;\n    }\n    r->expn = l * LIMB_BITS;\n    r->sign = r_sign;\n    bf_normalize_and_round(r, BF_PREC_INF, BF_RNDZ); /* cannot fail */\n    if (r_sign) {\n        if (bf_add_si(r, r, -1, BF_PREC_INF, BF_RNDZ))\n            goto fail;\n    }\n    ret = 0;\n done:\n    if (a == &a1_s)\n        bf_delete(a);\n    if (b == &b1_s)\n        bf_delete(b);\n    return ret;\n fail:\n    bf_set_nan(r);\n    ret = BF_ST_MEM_ERROR;\n    goto done;\n}\n\n/* 'a' and 'b' must be integers. Return 0 or BF_ST_MEM_ERROR. */\nint bf_logic_or(bf_t *r, const bf_t *a, const bf_t *b)\n{\n    return bf_logic_op(r, a, b, BF_LOGIC_OR);\n}\n\n/* 'a' and 'b' must be integers. Return 0 or BF_ST_MEM_ERROR. */\nint bf_logic_xor(bf_t *r, const bf_t *a, const bf_t *b)\n{\n    return bf_logic_op(r, a, b, BF_LOGIC_XOR);\n}\n\n/* 'a' and 'b' must be integers. Return 0 or BF_ST_MEM_ERROR. */\nint bf_logic_and(bf_t *r, const bf_t *a, const bf_t *b)\n{\n    return bf_logic_op(r, a, b, BF_LOGIC_AND);\n}\n\n/* conversion between fixed size types */\n\ntypedef union {\n    double d;\n    uint64_t u;\n} Float64Union;\n\nint bf_get_float64(const bf_t *a, double *pres, bf_rnd_t rnd_mode)\n{\n    Float64Union u;\n    int e, ret;\n    uint64_t m;\n    \n    ret = 0;\n    if (a->expn == BF_EXP_NAN) {\n        u.u = 0x7ff8000000000000; /* quiet nan */\n    } else {\n        bf_t b_s, *b = &b_s;\n        \n        bf_init(a->ctx, b);\n        bf_set(b, a);\n        if (bf_is_finite(b)) {\n            ret = bf_round(b, 53, rnd_mode | BF_FLAG_SUBNORMAL | bf_set_exp_bits(11));\n        }\n        if (b->expn == BF_EXP_INF) {\n            e = (1 << 11) - 1;\n            m = 0;\n        } else if (b->expn == BF_EXP_ZERO) {\n            e = 0;\n            m = 0;\n        } else {\n            e = b->expn + 1023 - 1;\n#if LIMB_BITS == 32\n            if (b->len == 2) {\n                m = ((uint64_t)b->tab[1] << 32) | b->tab[0];\n            } else {\n                m = ((uint64_t)b->tab[0] << 32);\n            }\n#else\n            m = b->tab[0];\n#endif\n            if (e <= 0) {\n                /* subnormal */\n                m = m >> (12 - e);\n                e = 0;\n            } else {\n                m = (m << 1) >> 12;\n            }\n        }\n        u.u = m | ((uint64_t)e << 52) | ((uint64_t)b->sign << 63);\n        bf_delete(b);\n    }\n    *pres = u.d;\n    return ret;\n}\n\nint bf_set_float64(bf_t *a, double d)\n{\n    Float64Union u;\n    uint64_t m;\n    int shift, e, sgn;\n    \n    u.d = d;\n    sgn = u.u >> 63;\n    e = (u.u >> 52) & ((1 << 11) - 1);\n    m = u.u & (((uint64_t)1 << 52) - 1);\n    if (e == ((1 << 11) - 1)) {\n        if (m != 0) {\n            bf_set_nan(a);\n        } else {\n            bf_set_inf(a, sgn);\n        }\n    } else if (e == 0) {\n        if (m == 0) {\n            bf_set_zero(a, sgn);\n        } else {\n            /* subnormal number */\n            m <<= 12;\n            shift = clz64(m);\n            m <<= shift;\n            e = -shift;\n            goto norm;\n        }\n    } else {\n        m = (m << 11) | ((uint64_t)1 << 63);\n    norm:\n        a->expn = e - 1023 + 1;\n#if LIMB_BITS == 32\n        if (bf_resize(a, 2))\n            goto fail;\n        a->tab[0] = m;\n        a->tab[1] = m >> 32;\n#else\n        if (bf_resize(a, 1))\n            goto fail;\n        a->tab[0] = m;\n#endif\n        a->sign = sgn;\n    }\n    return 0;\nfail:\n    bf_set_nan(a);\n    return BF_ST_MEM_ERROR;\n}\n\n/* The rounding mode is always BF_RNDZ. Return BF_ST_INVALID_OP if there\n   is an overflow and 0 otherwise. */\nint bf_get_int32(int *pres, const bf_t *a, int flags)\n{\n    uint32_t v;\n    int ret;\n    if (a->expn >= BF_EXP_INF) {\n        ret = BF_ST_INVALID_OP;\n        if (flags & BF_GET_INT_MOD) {\n            v = 0;\n        } else if (a->expn == BF_EXP_INF) {\n            v = (uint32_t)INT32_MAX + a->sign;\n        } else {\n            v = INT32_MAX;\n        }\n    } else if (a->expn <= 0) {\n        v = 0;\n        ret = 0;\n    } else if (a->expn <= 31) {\n        v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn);\n        if (a->sign)\n            v = -v;\n        ret = 0;\n    } else if (!(flags & BF_GET_INT_MOD)) {\n        ret = BF_ST_INVALID_OP;\n        if (a->sign) {\n            v = (uint32_t)INT32_MAX + 1;\n            if (a->expn == 32 && \n                (a->tab[a->len - 1] >> (LIMB_BITS - 32)) == v) {\n                ret = 0;\n            }\n        } else {\n            v = INT32_MAX;\n        }\n    } else {\n        v = get_bits(a->tab, a->len, a->len * LIMB_BITS - a->expn); \n        if (a->sign)\n            v = -v;\n        ret = 0;\n    }\n    *pres = v;\n    return ret;\n}\n\n/* The rounding mode is always BF_RNDZ. Return BF_ST_INVALID_OP if there\n   is an overflow and 0 otherwise. */\nint bf_get_int64(int64_t *pres, const bf_t *a, int flags)\n{\n    uint64_t v;\n    int ret;\n    if (a->expn >= BF_EXP_INF) {\n        ret = BF_ST_INVALID_OP;\n        if (flags & BF_GET_INT_MOD) {\n            v = 0;\n        } else if (a->expn == BF_EXP_INF) {\n            v = (uint64_t)INT64_MAX + a->sign;\n        } else {\n            v = INT64_MAX;\n        }\n    } else if (a->expn <= 0) {\n        v = 0;\n        ret = 0;\n    } else if (a->expn <= 63) {\n#if LIMB_BITS == 32\n        if (a->expn <= 32)\n            v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn);\n        else\n            v = (((uint64_t)a->tab[a->len - 1] << 32) |\n                 get_limbz(a, a->len - 2)) >> (64 - a->expn);\n#else\n        v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn);\n#endif\n        if (a->sign)\n            v = -v;\n        ret = 0;\n    } else if (!(flags & BF_GET_INT_MOD)) {\n        ret = BF_ST_INVALID_OP;\n        if (a->sign) {\n            uint64_t v1;\n            v = (uint64_t)INT64_MAX + 1;\n            if (a->expn == 64) {\n                v1 = a->tab[a->len - 1];\n#if LIMB_BITS == 32\n                v1 = (v1 << 32) | get_limbz(a, a->len - 2);\n#endif\n                if (v1 == v)\n                    ret = 0;\n            }\n        } else {\n            v = INT64_MAX;\n        }\n    } else {\n        slimb_t bit_pos = a->len * LIMB_BITS - a->expn;\n        v = get_bits(a->tab, a->len, bit_pos); \n#if LIMB_BITS == 32\n        v |= (uint64_t)get_bits(a->tab, a->len, bit_pos + 32) << 32;\n#endif\n        if (a->sign)\n            v = -v;\n        ret = 0;\n    }\n    *pres = v;\n    return ret;\n}\n\n/* The rounding mode is always BF_RNDZ. Return BF_ST_INVALID_OP if there\n   is an overflow and 0 otherwise. */\nint bf_get_uint64(uint64_t *pres, const bf_t *a)\n{\n    uint64_t v;\n    int ret;\n    if (a->expn == BF_EXP_NAN) {\n        goto overflow;\n    } else if (a->expn <= 0) {\n        v = 0;\n        ret = 0;\n    } else if (a->sign) {\n        v = 0;\n        ret = BF_ST_INVALID_OP;\n    } else if (a->expn <= 64) {\n#if LIMB_BITS == 32\n        if (a->expn <= 32)\n            v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn);\n        else\n            v = (((uint64_t)a->tab[a->len - 1] << 32) |\n                 get_limbz(a, a->len - 2)) >> (64 - a->expn);\n#else\n        v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn);\n#endif\n        ret = 0;\n    } else {\n    overflow:\n        v = UINT64_MAX;\n        ret = BF_ST_INVALID_OP;\n    }\n    *pres = v;\n    return ret;\n}\n\n/* base conversion from radix */\n\nstatic const uint8_t digits_per_limb_table[BF_RADIX_MAX - 1] = {\n#if LIMB_BITS == 32\n32,20,16,13,12,11,10,10, 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n#else\n64,40,32,27,24,22,21,20,19,18,17,17,16,16,16,15,15,15,14,14,14,14,13,13,13,13,13,13,13,12,12,12,12,12,12,\n#endif\n};\n\nstatic limb_t get_limb_radix(int radix)\n{\n    int i, k;\n    limb_t radixl;\n    \n    k = digits_per_limb_table[radix - 2];\n    radixl = radix;\n    for(i = 1; i < k; i++)\n        radixl *= radix;\n    return radixl;\n}\n\n/* return != 0 if error */\nstatic int bf_integer_from_radix_rec(bf_t *r, const limb_t *tab,\n                                     limb_t n, int level, limb_t n0,\n                                     limb_t radix, bf_t *pow_tab)\n{\n    int ret;\n    if (n == 1) {\n        ret = bf_set_ui(r, tab[0]);\n    } else {\n        bf_t T_s, *T = &T_s, *B;\n        limb_t n1, n2;\n        \n        n2 = (((n0 * 2) >> (level + 1)) + 1) / 2;\n        n1 = n - n2;\n        //        printf(\"level=%d n0=%ld n1=%ld n2=%ld\\n\", level, n0, n1, n2);\n        B = &pow_tab[level];\n        if (B->len == 0) {\n            ret = bf_pow_ui_ui(B, radix, n2, BF_PREC_INF, BF_RNDZ);\n            if (ret)\n                return ret;\n        }\n        ret = bf_integer_from_radix_rec(r, tab + n2, n1, level + 1, n0,\n                                        radix, pow_tab);\n        if (ret)\n            return ret;\n        ret = bf_mul(r, r, B, BF_PREC_INF, BF_RNDZ);\n        if (ret)\n            return ret;\n        bf_init(r->ctx, T);\n        ret = bf_integer_from_radix_rec(T, tab, n2, level + 1, n0,\n                                        radix, pow_tab);\n        if (!ret)\n            ret = bf_add(r, r, T, BF_PREC_INF, BF_RNDZ);\n        bf_delete(T);\n    }\n    return ret;\n    //    bf_print_str(\"  r=\", r);\n}\n\n/* return 0 if OK != 0 if memory error */\nstatic int bf_integer_from_radix(bf_t *r, const limb_t *tab,\n                                 limb_t n, limb_t radix)\n{\n    bf_context_t *s = r->ctx;\n    int pow_tab_len, i, ret;\n    limb_t radixl;\n    bf_t *pow_tab;\n    \n    radixl = get_limb_radix(radix);\n    pow_tab_len = ceil_log2(n) + 2; /* XXX: check */\n    pow_tab = bf_malloc(s, sizeof(pow_tab[0]) * pow_tab_len);\n    if (!pow_tab)\n        return -1;\n    for(i = 0; i < pow_tab_len; i++)\n        bf_init(r->ctx, &pow_tab[i]);\n    ret = bf_integer_from_radix_rec(r, tab, n, 0, n, radixl, pow_tab);\n    for(i = 0; i < pow_tab_len; i++) {\n        bf_delete(&pow_tab[i]);\n    }\n    bf_free(s, pow_tab);\n    return ret;\n}\n\n/* compute and round T * radix^expn. */\nint bf_mul_pow_radix(bf_t *r, const bf_t *T, limb_t radix,\n                     slimb_t expn, limb_t prec, bf_flags_t flags)\n{\n    int ret, expn_sign, overflow;\n    slimb_t e, extra_bits, prec1, ziv_extra_bits;\n    bf_t B_s, *B = &B_s;\n\n    if (T->len == 0) {\n        return bf_set(r, T);\n    } else if (expn == 0) {\n        ret = bf_set(r, T);\n        ret |= bf_round(r, prec, flags);\n        return ret;\n    }\n\n    e = expn;\n    expn_sign = 0;\n    if (e < 0) {\n        e = -e;\n        expn_sign = 1;\n    }\n    bf_init(r->ctx, B);\n    if (prec == BF_PREC_INF) {\n        /* infinite precision: only used if the result is known to be exact */\n        ret = bf_pow_ui_ui(B, radix, e, BF_PREC_INF, BF_RNDN);\n        if (expn_sign) {\n            ret |= bf_div(r, T, B, T->len * LIMB_BITS, BF_RNDN);\n        } else {\n            ret |= bf_mul(r, T, B, BF_PREC_INF, BF_RNDN);\n        }\n    } else {\n        ziv_extra_bits = 16;\n        for(;;) {\n            prec1 = prec + ziv_extra_bits;\n            /* XXX: correct overflow/underflow handling */\n            /* XXX: rigorous error analysis needed */\n            extra_bits = ceil_log2(e) * 2 + 1;\n            ret = bf_pow_ui_ui(B, radix, e, prec1 + extra_bits, BF_RNDN | BF_FLAG_EXT_EXP);\n            overflow = !bf_is_finite(B);\n            /* XXX: if bf_pow_ui_ui returns an exact result, can stop\n               after the next operation */\n            if (expn_sign)\n                ret |= bf_div(r, T, B, prec1 + extra_bits, BF_RNDN | BF_FLAG_EXT_EXP);\n            else\n                ret |= bf_mul(r, T, B, prec1 + extra_bits, BF_RNDN | BF_FLAG_EXT_EXP);\n            if (ret & BF_ST_MEM_ERROR)\n                break;\n            if ((ret & BF_ST_INEXACT) &&\n                !bf_can_round(r, prec, flags & BF_RND_MASK, prec1) &&\n                !overflow) {\n                /* and more precision and retry */\n                ziv_extra_bits = ziv_extra_bits  + (ziv_extra_bits / 2);\n            } else {\n                /* XXX: need to use __bf_round() to pass the inexact\n                   flag for the subnormal case */\n                ret = bf_round(r, prec, flags) | (ret & BF_ST_INEXACT);\n                break;\n            }\n        }\n    }\n    bf_delete(B);\n    return ret;\n}\n\nstatic inline int to_digit(int c)\n{\n    if (c >= '0' && c <= '9')\n        return c - '0';\n    else if (c >= 'A' && c <= 'Z')\n        return c - 'A' + 10;\n    else if (c >= 'a' && c <= 'z')\n        return c - 'a' + 10;\n    else\n        return 36;\n}\n\n/* add a limb at 'pos' and decrement pos. new space is created if\n   needed. Return 0 if OK, -1 if memory error */\nstatic int bf_add_limb(bf_t *a, slimb_t *ppos, limb_t v)\n{\n    slimb_t pos;\n    pos = *ppos;\n    if (unlikely(pos < 0)) {\n        limb_t new_size, d, *new_tab;\n        new_size = bf_max(a->len + 1, a->len * 3 / 2);\n        new_tab = bf_realloc(a->ctx, a->tab, sizeof(limb_t) * new_size);\n        if (!new_tab)\n            return -1;\n        a->tab = new_tab;\n        d = new_size - a->len;\n        memmove(a->tab + d, a->tab, a->len * sizeof(limb_t));\n        a->len = new_size;\n        pos += d;\n    }\n    a->tab[pos--] = v;\n    *ppos = pos;\n    return 0;\n}\n\nstatic int bf_tolower(int c)\n{\n    if (c >= 'A' && c <= 'Z')\n        c = c - 'A' + 'a';\n    return c;\n}\n\nstatic int strcasestart(const char *str, const char *val, const char **ptr)\n{\n    const char *p, *q;\n    p = str;\n    q = val;\n    while (*q != '\\0') {\n        if (bf_tolower(*p) != *q)\n            return 0;\n        p++;\n        q++;\n    }\n    if (ptr)\n        *ptr = p;\n    return 1;\n}\n\nstatic int bf_atof_internal(bf_t *r, slimb_t *pexponent,\n                            const char *str, const char **pnext, int radix,\n                            limb_t prec, bf_flags_t flags, BOOL is_dec)\n{\n    const char *p, *p_start;\n    int is_neg, radix_bits, exp_is_neg, ret, digits_per_limb, shift;\n    limb_t cur_limb;\n    slimb_t pos, expn, int_len, digit_count;\n    BOOL has_decpt, is_bin_exp;\n    bf_t a_s, *a;\n    \n    *pexponent = 0;\n    p = str;\n    if (!(flags & BF_ATOF_NO_NAN_INF) && radix <= 16 &&\n        strcasestart(p, \"nan\", &p)) {\n        bf_set_nan(r);\n        ret = 0;\n        goto done;\n    }\n    is_neg = 0;\n    \n    if (p[0] == '+') {\n        p++;\n        p_start = p;\n    } else if (p[0] == '-') {\n        is_neg = 1;\n        p++;\n        p_start = p;\n    } else {\n        p_start = p;\n    }\n    if (p[0] == '0') {\n        if ((p[1] == 'x' || p[1] == 'X') &&\n            (radix == 0 || radix == 16) &&\n            !(flags & BF_ATOF_NO_HEX)) {\n            radix = 16;\n            p += 2;\n        } else if ((p[1] == 'o' || p[1] == 'O') &&\n                   radix == 0 && (flags & BF_ATOF_BIN_OCT)) {\n            p += 2;\n            radix = 8;\n        } else if ((p[1] == 'b' || p[1] == 'B') &&\n                   radix == 0 && (flags & BF_ATOF_BIN_OCT)) {\n            p += 2;\n            radix = 2;\n        } else {\n            goto no_prefix;\n        }\n        /* there must be a digit after the prefix */\n        if (to_digit((uint8_t)*p) >= radix) {\n            bf_set_nan(r);\n            ret = 0;\n            goto done;\n        }\n    no_prefix: ;\n    } else {\n        if (!(flags & BF_ATOF_NO_NAN_INF) && radix <= 16 &&\n            strcasestart(p, \"inf\", &p)) {\n            bf_set_inf(r, is_neg);\n            ret = 0;\n            goto done;\n        }\n    }\n    \n    if (radix == 0)\n        radix = 10;\n    if (is_dec) {\n        assert(radix == 10);\n        radix_bits = 0;\n        a = r;\n    } else if ((radix & (radix - 1)) != 0) {\n        radix_bits = 0; /* base is not a power of two */\n        a = &a_s;\n        bf_init(r->ctx, a);\n    } else {\n        radix_bits = ceil_log2(radix);\n        a = r;\n    }\n\n    /* skip leading zeros */\n    /* XXX: could also skip zeros after the decimal point */\n    while (*p == '0')\n        p++;\n\n    if (radix_bits) {\n        shift = digits_per_limb = LIMB_BITS;\n    } else {\n        radix_bits = 0;\n        shift = digits_per_limb = digits_per_limb_table[radix - 2];\n    }\n    cur_limb = 0;\n    bf_resize(a, 1);\n    pos = 0;\n    has_decpt = FALSE;\n    int_len = digit_count = 0;\n    for(;;) {\n        limb_t c;\n        if (*p == '.' && (p > p_start || to_digit(p[1]) < radix)) {\n            if (has_decpt)\n                break;\n            has_decpt = TRUE;\n            int_len = digit_count;\n            p++;\n        }\n        c = to_digit(*p);\n        if (c >= radix)\n            break;\n        digit_count++;\n        p++;\n        if (radix_bits) {\n            shift -= radix_bits;\n            if (shift <= 0) {\n                cur_limb |= c >> (-shift);\n                if (bf_add_limb(a, &pos, cur_limb))\n                    goto mem_error;\n                if (shift < 0)\n                    cur_limb = c << (LIMB_BITS + shift);\n                else\n                    cur_limb = 0;\n                shift += LIMB_BITS;\n            } else {\n                cur_limb |= c << shift;\n            }\n        } else {\n            cur_limb = cur_limb * radix + c;\n            shift--;\n            if (shift == 0) {\n                if (bf_add_limb(a, &pos, cur_limb))\n                    goto mem_error;\n                shift = digits_per_limb;\n                cur_limb = 0;\n            }\n        }\n    }\n    if (!has_decpt)\n        int_len = digit_count;\n\n    /* add the last limb and pad with zeros */\n    if (shift != digits_per_limb) {\n        if (radix_bits == 0) {\n            while (shift != 0) {\n                cur_limb *= radix;\n                shift--;\n            }\n        }\n        if (bf_add_limb(a, &pos, cur_limb)) {\n        mem_error:\n            ret = BF_ST_MEM_ERROR;\n            if (!radix_bits)\n                bf_delete(a);\n            bf_set_nan(r);\n            goto done;\n        }\n    }\n            \n    /* reset the next limbs to zero (we prefer to reallocate in the\n       renormalization) */\n    memset(a->tab, 0, (pos + 1) * sizeof(limb_t));\n\n    if (p == p_start) {\n        ret = 0;\n        if (!radix_bits)\n            bf_delete(a);\n        bf_set_nan(r);\n        goto done;\n    }\n\n    /* parse the exponent, if any */\n    expn = 0;\n    is_bin_exp = FALSE;\n    if (((radix == 10 && (*p == 'e' || *p == 'E')) ||\n         (radix != 10 && (*p == '@' ||\n                          (radix_bits && (*p == 'p' || *p == 'P'))))) &&\n        p > p_start) {\n        is_bin_exp = (*p == 'p' || *p == 'P');\n        p++;\n        exp_is_neg = 0;\n        if (*p == '+') {\n            p++;\n        } else if (*p == '-') {\n            exp_is_neg = 1;\n            p++;\n        }\n        for(;;) {\n            int c;\n            c = to_digit(*p);\n            if (c >= 10)\n                break;\n            if (unlikely(expn > ((BF_RAW_EXP_MAX - 2 - 9) / 10))) {\n                /* exponent overflow */\n                if (exp_is_neg) {\n                    bf_set_zero(r, is_neg);\n                    ret = BF_ST_UNDERFLOW | BF_ST_INEXACT;\n                } else {\n                    bf_set_inf(r, is_neg);\n                    ret = BF_ST_OVERFLOW | BF_ST_INEXACT;\n                }\n                goto done;\n            }\n            p++;\n            expn = expn * 10 + c;\n        }\n        if (exp_is_neg)\n            expn = -expn;\n    }\n    if (is_dec) {\n        a->expn = expn + int_len;\n        a->sign = is_neg;\n        ret = bfdec_normalize_and_round((bfdec_t *)a, prec, flags);\n    } else if (radix_bits) {\n        /* XXX: may overflow */\n        if (!is_bin_exp)\n            expn *= radix_bits; \n        a->expn = expn + (int_len * radix_bits);\n        a->sign = is_neg;\n        ret = bf_normalize_and_round(a, prec, flags);\n    } else {\n        limb_t l;\n        pos++;\n        l = a->len - pos; /* number of limbs */\n        if (l == 0) {\n            bf_set_zero(r, is_neg);\n            ret = 0;\n        } else {\n            bf_t T_s, *T = &T_s;\n\n            expn -= l * digits_per_limb - int_len;\n            bf_init(r->ctx, T);\n            if (bf_integer_from_radix(T, a->tab + pos, l, radix)) {\n                bf_set_nan(r);\n                ret = BF_ST_MEM_ERROR;\n            } else {\n                T->sign = is_neg;\n                if (flags & BF_ATOF_EXPONENT) {\n                    /* return the exponent */\n                    *pexponent = expn;\n                    ret = bf_set(r, T);\n                } else {\n                    ret = bf_mul_pow_radix(r, T, radix, expn, prec, flags);\n                }\n            }\n            bf_delete(T);\n        }\n        bf_delete(a);\n    }\n done:\n    if (pnext)\n        *pnext = p;\n    return ret;\n}\n\n/* \n   Return (status, n, exp). 'status' is the floating point status. 'n'\n   is the parsed number. \n\n   If (flags & BF_ATOF_EXPONENT) and if the radix is not a power of\n   two, the parsed number is equal to r *\n   (*pexponent)^radix. Otherwise *pexponent = 0.\n*/\nint bf_atof2(bf_t *r, slimb_t *pexponent,\n             const char *str, const char **pnext, int radix,\n             limb_t prec, bf_flags_t flags)\n{\n    return bf_atof_internal(r, pexponent, str, pnext, radix, prec, flags,\n                            FALSE);\n}\n\nint bf_atof(bf_t *r, const char *str, const char **pnext, int radix,\n            limb_t prec, bf_flags_t flags)\n{\n    slimb_t dummy_exp;\n    return bf_atof_internal(r, &dummy_exp, str, pnext, radix, prec, flags, FALSE);\n}\n\n/* base conversion to radix */\n\n#if LIMB_BITS == 64\n#define RADIXL_10 UINT64_C(10000000000000000000)\n#else\n#define RADIXL_10 UINT64_C(1000000000)\n#endif\n\nstatic const uint32_t inv_log2_radix[BF_RADIX_MAX - 1][LIMB_BITS / 32 + 1] = {\n#if LIMB_BITS == 32\n{ 0x80000000, 0x00000000,},\n{ 0x50c24e60, 0xd4d4f4a7,},\n{ 0x40000000, 0x00000000,},\n{ 0x372068d2, 0x0a1ee5ca,},\n{ 0x3184648d, 0xb8153e7a,},\n{ 0x2d983275, 0x9d5369c4,},\n{ 0x2aaaaaaa, 0xaaaaaaab,},\n{ 0x28612730, 0x6a6a7a54,},\n{ 0x268826a1, 0x3ef3fde6,},\n{ 0x25001383, 0xbac8a744,},\n{ 0x23b46706, 0x82c0c709,},\n{ 0x229729f1, 0xb2c83ded,},\n{ 0x219e7ffd, 0xa5ad572b,},\n{ 0x20c33b88, 0xda7c29ab,},\n{ 0x20000000, 0x00000000,},\n{ 0x1f50b57e, 0xac5884b3,},\n{ 0x1eb22cc6, 0x8aa6e26f,},\n{ 0x1e21e118, 0x0c5daab2,},\n{ 0x1d9dcd21, 0x439834e4,},\n{ 0x1d244c78, 0x367a0d65,},\n{ 0x1cb40589, 0xac173e0c,},\n{ 0x1c4bd95b, 0xa8d72b0d,},\n{ 0x1bead768, 0x98f8ce4c,},\n{ 0x1b903469, 0x050f72e5,},\n{ 0x1b3b433f, 0x2eb06f15,},\n{ 0x1aeb6f75, 0x9c46fc38,},\n{ 0x1aa038eb, 0x0e3bfd17,},\n{ 0x1a593062, 0xb38d8c56,},\n{ 0x1a15f4c3, 0x2b95a2e6,},\n{ 0x19d630dc, 0xcc7ddef9,},\n{ 0x19999999, 0x9999999a,},\n{ 0x195fec80, 0x8a609431,},\n{ 0x1928ee7b, 0x0b4f22f9,},\n{ 0x18f46acf, 0x8c06e318,},\n{ 0x18c23246, 0xdc0a9f3d,},\n#else\n{ 0x80000000, 0x00000000, 0x00000000,},\n{ 0x50c24e60, 0xd4d4f4a7, 0x021f57bc,},\n{ 0x40000000, 0x00000000, 0x00000000,},\n{ 0x372068d2, 0x0a1ee5ca, 0x19ea911b,},\n{ 0x3184648d, 0xb8153e7a, 0x7fc2d2e1,},\n{ 0x2d983275, 0x9d5369c4, 0x4dec1661,},\n{ 0x2aaaaaaa, 0xaaaaaaaa, 0xaaaaaaab,},\n{ 0x28612730, 0x6a6a7a53, 0x810fabde,},\n{ 0x268826a1, 0x3ef3fde6, 0x23e2566b,},\n{ 0x25001383, 0xbac8a744, 0x385a3349,},\n{ 0x23b46706, 0x82c0c709, 0x3f891718,},\n{ 0x229729f1, 0xb2c83ded, 0x15fba800,},\n{ 0x219e7ffd, 0xa5ad572a, 0xe169744b,},\n{ 0x20c33b88, 0xda7c29aa, 0x9bddee52,},\n{ 0x20000000, 0x00000000, 0x00000000,},\n{ 0x1f50b57e, 0xac5884b3, 0x70e28eee,},\n{ 0x1eb22cc6, 0x8aa6e26f, 0x06d1a2a2,},\n{ 0x1e21e118, 0x0c5daab1, 0x81b4f4bf,},\n{ 0x1d9dcd21, 0x439834e3, 0x81667575,},\n{ 0x1d244c78, 0x367a0d64, 0xc8204d6d,},\n{ 0x1cb40589, 0xac173e0c, 0x3b7b16ba,},\n{ 0x1c4bd95b, 0xa8d72b0d, 0x5879f25a,},\n{ 0x1bead768, 0x98f8ce4c, 0x66cc2858,},\n{ 0x1b903469, 0x050f72e5, 0x0cf5488e,},\n{ 0x1b3b433f, 0x2eb06f14, 0x8c89719c,},\n{ 0x1aeb6f75, 0x9c46fc37, 0xab5fc7e9,},\n{ 0x1aa038eb, 0x0e3bfd17, 0x1bd62080,},\n{ 0x1a593062, 0xb38d8c56, 0x7998ab45,},\n{ 0x1a15f4c3, 0x2b95a2e6, 0x46aed6a0,},\n{ 0x19d630dc, 0xcc7ddef9, 0x5aadd61b,},\n{ 0x19999999, 0x99999999, 0x9999999a,},\n{ 0x195fec80, 0x8a609430, 0xe1106014,},\n{ 0x1928ee7b, 0x0b4f22f9, 0x5f69791d,},\n{ 0x18f46acf, 0x8c06e318, 0x4d2aeb2c,},\n{ 0x18c23246, 0xdc0a9f3d, 0x3fe16970,},\n#endif\n};\n\nstatic const limb_t log2_radix[BF_RADIX_MAX - 1] = {\n#if LIMB_BITS == 32\n0x20000000,\n0x32b80347,\n0x40000000,\n0x4a4d3c26,\n0x52b80347,\n0x59d5d9fd,\n0x60000000,\n0x6570068e,\n0x6a4d3c26,\n0x6eb3a9f0,\n0x72b80347,\n0x766a008e,\n0x79d5d9fd,\n0x7d053f6d,\n0x80000000,\n0x82cc7edf,\n0x8570068e,\n0x87ef05ae,\n0x8a4d3c26,\n0x8c8ddd45,\n0x8eb3a9f0,\n0x90c10501,\n0x92b80347,\n0x949a784c,\n0x966a008e,\n0x982809d6,\n0x99d5d9fd,\n0x9b74948f,\n0x9d053f6d,\n0x9e88c6b3,\n0xa0000000,\n0xa16bad37,\n0xa2cc7edf,\n0xa4231623,\n0xa570068e,\n#else\n0x2000000000000000,\n0x32b803473f7ad0f4,\n0x4000000000000000,\n0x4a4d3c25e68dc57f,\n0x52b803473f7ad0f4,\n0x59d5d9fd5010b366,\n0x6000000000000000,\n0x6570068e7ef5a1e8,\n0x6a4d3c25e68dc57f,\n0x6eb3a9f01975077f,\n0x72b803473f7ad0f4,\n0x766a008e4788cbcd,\n0x79d5d9fd5010b366,\n0x7d053f6d26089673,\n0x8000000000000000,\n0x82cc7edf592262d0,\n0x8570068e7ef5a1e8,\n0x87ef05ae409a0289,\n0x8a4d3c25e68dc57f,\n0x8c8ddd448f8b845a,\n0x8eb3a9f01975077f,\n0x90c10500d63aa659,\n0x92b803473f7ad0f4,\n0x949a784bcd1b8afe,\n0x966a008e4788cbcd,\n0x982809d5be7072dc,\n0x99d5d9fd5010b366,\n0x9b74948f5532da4b,\n0x9d053f6d26089673,\n0x9e88c6b3626a72aa,\n0xa000000000000000,\n0xa16bad3758efd873,\n0xa2cc7edf592262d0,\n0xa4231623369e78e6,\n0xa570068e7ef5a1e8,\n#endif\n};\n\n/* compute floor(a*b) or ceil(a*b) with b = log2(radix) or\n   b=1/log2(radix). For is_inv = 0, strict accuracy is not guaranteed\n   when radix is not a power of two. */\nslimb_t bf_mul_log2_radix(slimb_t a1, unsigned int radix, int is_inv,\n                          int is_ceil1)\n{\n    int is_neg;\n    limb_t a;\n    BOOL is_ceil;\n\n    is_ceil = is_ceil1;\n    a = a1;\n    if (a1 < 0) {\n        a = -a;\n        is_neg = 1;\n    } else {\n        is_neg = 0;\n    }\n    is_ceil ^= is_neg;\n    if ((radix & (radix - 1)) == 0) {\n        int radix_bits;\n        /* radix is a power of two */\n        radix_bits = ceil_log2(radix);\n        if (is_inv) {\n            if (is_ceil)\n                a += radix_bits - 1;\n            a = a / radix_bits;\n        } else {\n            a = a * radix_bits;\n        }\n    } else {\n        const uint32_t *tab;\n        limb_t b0, b1;\n        dlimb_t t;\n        \n        if (is_inv) {\n            tab = inv_log2_radix[radix - 2];\n#if LIMB_BITS == 32\n            b1 = tab[0];\n            b0 = tab[1];\n#else\n            b1 = ((limb_t)tab[0] << 32) | tab[1];\n            b0 = (limb_t)tab[2] << 32;\n#endif\n            t = (dlimb_t)b0 * (dlimb_t)a;\n            t = (dlimb_t)b1 * (dlimb_t)a + (t >> LIMB_BITS);\n            a = t >> (LIMB_BITS - 1);\n        } else {\n            b0 = log2_radix[radix - 2];\n            t = (dlimb_t)b0 * (dlimb_t)a;\n            a = t >> (LIMB_BITS - 3);\n        }\n        /* a = floor(result) and 'result' cannot be an integer */\n        a += is_ceil;\n    }\n    if (is_neg)\n        a = -a;\n    return a;\n}\n\n/* 'n' is the number of output limbs */\nstatic int bf_integer_to_radix_rec(bf_t *pow_tab,\n                                   limb_t *out, const bf_t *a, limb_t n,\n                                   int level, limb_t n0, limb_t radixl,\n                                   unsigned int radixl_bits)\n{\n    limb_t n1, n2, q_prec;\n    int ret;\n    \n    assert(n >= 1);\n    if (n == 1) {\n        out[0] = get_bits(a->tab, a->len, a->len * LIMB_BITS - a->expn);\n    } else if (n == 2) {\n        dlimb_t t;\n        slimb_t pos;\n        pos = a->len * LIMB_BITS - a->expn;\n        t = ((dlimb_t)get_bits(a->tab, a->len, pos + LIMB_BITS) << LIMB_BITS) |\n            get_bits(a->tab, a->len, pos);\n        if (likely(radixl == RADIXL_10)) {\n            /* use division by a constant when possible */\n            out[0] = t % RADIXL_10;\n            out[1] = t / RADIXL_10;\n        } else {\n            out[0] = t % radixl;\n            out[1] = t / radixl;\n        }\n    } else {\n        bf_t Q, R, *B, *B_inv;\n        int q_add;\n        bf_init(a->ctx, &Q);\n        bf_init(a->ctx, &R);\n        n2 = (((n0 * 2) >> (level + 1)) + 1) / 2;\n        n1 = n - n2;\n        B = &pow_tab[2 * level];\n        B_inv = &pow_tab[2 * level + 1];\n        ret = 0;\n        if (B->len == 0) {\n            /* compute BASE^n2 */\n            ret |= bf_pow_ui_ui(B, radixl, n2, BF_PREC_INF, BF_RNDZ);\n            /* we use enough bits for the maximum possible 'n1' value,\n               i.e. n2 + 1 */\n            ret |= bf_set_ui(&R, 1);\n            ret |= bf_div(B_inv, &R, B, (n2 + 1) * radixl_bits + 2, BF_RNDN);\n        }\n        //        printf(\"%d: n1=% \" PRId64 \" n2=%\" PRId64 \"\\n\", level, n1, n2);\n        q_prec = n1 * radixl_bits;\n        ret |= bf_mul(&Q, a, B_inv, q_prec, BF_RNDN);\n        ret |= bf_rint(&Q, BF_RNDZ);\n        \n        ret |= bf_mul(&R, &Q, B, BF_PREC_INF, BF_RNDZ);\n        ret |= bf_sub(&R, a, &R, BF_PREC_INF, BF_RNDZ);\n\n        if (ret & BF_ST_MEM_ERROR)\n            goto fail;\n        /* adjust if necessary */\n        q_add = 0;\n        while (R.sign && R.len != 0) {\n            if (bf_add(&R, &R, B, BF_PREC_INF, BF_RNDZ))\n                goto fail;\n            q_add--;\n        }\n        while (bf_cmpu(&R, B) >= 0) {\n            if (bf_sub(&R, &R, B, BF_PREC_INF, BF_RNDZ))\n                goto fail;\n            q_add++;\n        }\n        if (q_add != 0) {\n            if (bf_add_si(&Q, &Q, q_add, BF_PREC_INF, BF_RNDZ))\n                goto fail;\n        }\n        if (bf_integer_to_radix_rec(pow_tab, out + n2, &Q, n1, level + 1, n0,\n                                    radixl, radixl_bits))\n            goto fail;\n        if (bf_integer_to_radix_rec(pow_tab, out, &R, n2, level + 1, n0,\n                                    radixl, radixl_bits)) {\n        fail:\n            bf_delete(&Q);\n            bf_delete(&R);\n            return -1;\n        }\n        bf_delete(&Q);\n        bf_delete(&R);\n    }\n    return 0;\n}\n\n/* return 0 if OK != 0 if memory error */\nstatic int bf_integer_to_radix(bf_t *r, const bf_t *a, limb_t radixl)\n{\n    bf_context_t *s = r->ctx;\n    limb_t r_len;\n    bf_t *pow_tab;\n    int i, pow_tab_len, ret;\n    \n    r_len = r->len;\n    pow_tab_len = (ceil_log2(r_len) + 2) * 2; /* XXX: check */\n    pow_tab = bf_malloc(s, sizeof(pow_tab[0]) * pow_tab_len);\n    if (!pow_tab)\n        return -1;\n    for(i = 0; i < pow_tab_len; i++)\n        bf_init(r->ctx, &pow_tab[i]);\n\n    ret = bf_integer_to_radix_rec(pow_tab, r->tab, a, r_len, 0, r_len, radixl,\n                                  ceil_log2(radixl));\n\n    for(i = 0; i < pow_tab_len; i++) {\n        bf_delete(&pow_tab[i]);\n    }\n    bf_free(s, pow_tab);\n    return ret;\n}\n\n/* a must be >= 0. 'P' is the wanted number of digits in radix\n   'radix'. 'r' is the mantissa represented as an integer. *pE\n   contains the exponent. Return != 0 if memory error. */\nstatic int bf_convert_to_radix(bf_t *r, slimb_t *pE,\n                               const bf_t *a, int radix,\n                               limb_t P, bf_rnd_t rnd_mode,\n                               BOOL is_fixed_exponent)\n{\n    slimb_t E, e, prec, extra_bits, ziv_extra_bits, prec0;\n    bf_t B_s, *B = &B_s;\n    int e_sign, ret, res;\n    \n    if (a->len == 0) {\n        /* zero case */\n        *pE = 0;\n        return bf_set(r, a);\n    }\n\n    if (is_fixed_exponent) {\n        E = *pE;\n    } else {\n        /* compute the new exponent */\n        E = 1 + bf_mul_log2_radix(a->expn - 1, radix, TRUE, FALSE);\n    }\n    //    bf_print_str(\"a\", a);\n    //    printf(\"E=%ld P=%ld radix=%d\\n\", E, P, radix);\n    \n    for(;;) {\n        e = P - E;\n        e_sign = 0;\n        if (e < 0) {\n            e = -e;\n            e_sign = 1;\n        }\n        /* Note: precision for log2(radix) is not critical here */\n        prec0 = bf_mul_log2_radix(P, radix, FALSE, TRUE);\n        ziv_extra_bits = 16;\n        for(;;) {\n            prec = prec0 + ziv_extra_bits;\n            /* XXX: rigorous error analysis needed */\n            extra_bits = ceil_log2(e) * 2 + 1;\n            ret = bf_pow_ui_ui(r, radix, e, prec + extra_bits,\n                               BF_RNDN | BF_FLAG_EXT_EXP);\n            if (!e_sign)\n                ret |= bf_mul(r, r, a, prec + extra_bits,\n                              BF_RNDN | BF_FLAG_EXT_EXP);\n            else\n                ret |= bf_div(r, a, r, prec + extra_bits,\n                              BF_RNDN | BF_FLAG_EXT_EXP);\n            if (ret & BF_ST_MEM_ERROR)\n                return BF_ST_MEM_ERROR;\n            /* if the result is not exact, check that it can be safely\n               rounded to an integer */\n            if ((ret & BF_ST_INEXACT) &&\n                !bf_can_round(r, r->expn, rnd_mode, prec)) {\n                /* and more precision and retry */\n                ziv_extra_bits = ziv_extra_bits  + (ziv_extra_bits / 2);\n                continue;\n            } else {\n                ret = bf_rint(r, rnd_mode);\n                if (ret & BF_ST_MEM_ERROR)\n                    return BF_ST_MEM_ERROR;\n                break;\n            }\n        }\n        if (is_fixed_exponent)\n            break;\n        /* check that the result is < B^P */\n        /* XXX: do a fast approximate test first ? */\n        bf_init(r->ctx, B);\n        ret = bf_pow_ui_ui(B, radix, P, BF_PREC_INF, BF_RNDZ);\n        if (ret) {\n            bf_delete(B);\n            return ret;\n        }\n        res = bf_cmpu(r, B);\n        bf_delete(B);\n        if (res < 0)\n            break;\n        /* try a larger exponent */\n        E++;\n    }\n    *pE = E;\n    return 0;\n}\n\nstatic void limb_to_a(char *buf, limb_t n, unsigned int radix, int len)\n{\n    int digit, i;\n\n    if (radix == 10) {\n        /* specific case with constant divisor */\n        for(i = len - 1; i >= 0; i--) {\n            digit = (limb_t)n % 10;\n            n = (limb_t)n / 10;\n            buf[i] = digit + '0';\n        }\n    } else {\n        for(i = len - 1; i >= 0; i--) {\n            digit = (limb_t)n % radix;\n            n = (limb_t)n / radix;\n            if (digit < 10)\n                digit += '0';\n            else\n                digit += 'a' - 10;\n            buf[i] = digit;\n        }\n    }\n}\n\n/* for power of 2 radixes */\nstatic void limb_to_a2(char *buf, limb_t n, unsigned int radix_bits, int len)\n{\n    int digit, i;\n    unsigned int mask;\n\n    mask = (1 << radix_bits) - 1;\n    for(i = len - 1; i >= 0; i--) {\n        digit = n & mask;\n        n >>= radix_bits;\n        if (digit < 10)\n            digit += '0';\n        else\n            digit += 'a' - 10;\n        buf[i] = digit;\n    }\n}\n\n/* 'a' must be an integer if the is_dec = FALSE or if the radix is not\n   a power of two. A dot is added before the 'dot_pos' digit. dot_pos\n   = n_digits does not display the dot. 0 <= dot_pos <=\n   n_digits. n_digits >= 1. */\nstatic void output_digits(DynBuf *s, const bf_t *a1, int radix, limb_t n_digits,\n                          limb_t dot_pos, BOOL is_dec)\n{\n    limb_t i, v, l;\n    slimb_t pos, pos_incr;\n    int digits_per_limb, buf_pos, radix_bits, first_buf_pos;\n    char buf[65];\n    bf_t a_s, *a;\n\n    if (is_dec) {\n        digits_per_limb = LIMB_DIGITS;\n        a = (bf_t *)a1;\n        radix_bits = 0;\n        pos = a->len;\n        pos_incr = 1;\n        first_buf_pos = 0;\n    } else if ((radix & (radix - 1)) == 0) {\n        a = (bf_t *)a1;\n        radix_bits = ceil_log2(radix);\n        digits_per_limb = LIMB_BITS / radix_bits;\n        pos_incr = digits_per_limb * radix_bits;\n        /* digits are aligned relative to the radix point */\n        pos = a->len * LIMB_BITS + smod(-a->expn, radix_bits);\n        first_buf_pos = 0;\n    } else {\n        limb_t n, radixl;\n\n        digits_per_limb = digits_per_limb_table[radix - 2];\n        radixl = get_limb_radix(radix);\n        a = &a_s;\n        bf_init(a1->ctx, a);\n        n = (n_digits + digits_per_limb - 1) / digits_per_limb;\n        if (bf_resize(a, n)) {\n            dbuf_set_error(s);\n            goto done;\n        }\n        if (bf_integer_to_radix(a, a1, radixl)) {\n            dbuf_set_error(s);\n            goto done;\n        }\n        radix_bits = 0;\n        pos = n;\n        pos_incr = 1;\n        first_buf_pos = pos * digits_per_limb - n_digits;\n    }\n    buf_pos = digits_per_limb;\n    i = 0;\n    while (i < n_digits) {\n        if (buf_pos == digits_per_limb) {\n            pos -= pos_incr;\n            if (radix_bits == 0) {\n                v = get_limbz(a, pos);\n                limb_to_a(buf, v, radix, digits_per_limb);\n            } else {\n                v = get_bits(a->tab, a->len, pos);\n                limb_to_a2(buf, v, radix_bits, digits_per_limb);\n            }\n            buf_pos = first_buf_pos;\n            first_buf_pos = 0;\n        }\n        if (i < dot_pos) {\n            l = dot_pos;\n        } else {\n            if (i == dot_pos)\n                dbuf_putc(s, '.');\n            l = n_digits;\n        }\n        l = bf_min(digits_per_limb - buf_pos, l - i);\n        dbuf_put(s, (uint8_t *)(buf + buf_pos), l);\n        buf_pos += l;\n        i += l;\n    }\n done:\n    if (a != a1)\n        bf_delete(a);\n}\n\nstatic void *bf_dbuf_realloc(void *opaque, void *ptr, size_t size)\n{\n    bf_context_t *s = opaque;\n    return bf_realloc(s, ptr, size);\n}\n\n/* return the length in bytes. A trailing '\\0' is added */\nstatic char *bf_ftoa_internal(size_t *plen, const bf_t *a2, int radix,\n                              limb_t prec, bf_flags_t flags, BOOL is_dec)\n{\n    bf_context_t *ctx = a2->ctx;\n    DynBuf s_s, *s = &s_s;\n    int radix_bits;\n    \n    //    bf_print_str(\"ftoa\", a2);\n    //    printf(\"radix=%d\\n\", radix);\n    dbuf_init2(s, ctx, bf_dbuf_realloc);\n    if (a2->expn == BF_EXP_NAN) {\n        dbuf_putstr(s, \"NaN\");\n    } else {\n        if (a2->sign)\n            dbuf_putc(s, '-');\n        if (a2->expn == BF_EXP_INF) {\n            if (flags & BF_FTOA_JS_QUIRKS)\n                dbuf_putstr(s, \"Infinity\");\n            else\n                dbuf_putstr(s, \"Inf\");\n        } else {\n            int fmt, ret;\n            slimb_t n_digits, n, i, n_max, n1;\n            bf_t a1_s, *a1 = &a1_s;\n\n            if ((radix & (radix - 1)) != 0)\n                radix_bits = 0;\n            else\n                radix_bits = ceil_log2(radix);\n\n            fmt = flags & BF_FTOA_FORMAT_MASK;\n            bf_init(ctx, a1);\n            if (fmt == BF_FTOA_FORMAT_FRAC) {\n                if (is_dec || radix_bits != 0) {\n                    if (bf_set(a1, a2))\n                        goto fail1;\n#ifdef USE_BF_DEC\n                    if (is_dec) {\n                        if (bfdec_round((bfdec_t *)a1, prec, (flags & BF_RND_MASK) | BF_FLAG_RADPNT_PREC) & BF_ST_MEM_ERROR)\n                            goto fail1;\n                        n = a1->expn;\n                    } else\n#endif\n                    {\n                        if (bf_round(a1, prec * radix_bits, (flags & BF_RND_MASK) | BF_FLAG_RADPNT_PREC) & BF_ST_MEM_ERROR)\n                            goto fail1;\n                        n = ceil_div(a1->expn, radix_bits);\n                    }\n                    if (flags & BF_FTOA_ADD_PREFIX) {\n                        if (radix == 16)\n                            dbuf_putstr(s, \"0x\");\n                        else if (radix == 8)\n                            dbuf_putstr(s, \"0o\");\n                        else if (radix == 2)\n                            dbuf_putstr(s, \"0b\");\n                    }\n                    if (a1->expn == BF_EXP_ZERO) {\n                        dbuf_putstr(s, \"0\");\n                        if (prec > 0) {\n                            dbuf_putstr(s, \".\");\n                            for(i = 0; i < prec; i++) {\n                                dbuf_putc(s, '0');\n                            }\n                        }\n                    } else {\n                        n_digits = prec + n;\n                        if (n <= 0) {\n                            /* 0.x */\n                            dbuf_putstr(s, \"0.\");\n                            for(i = 0; i < -n; i++) {\n                                dbuf_putc(s, '0');\n                            }\n                            if (n_digits > 0) {\n                                output_digits(s, a1, radix, n_digits, n_digits, is_dec);\n                            }\n                        } else {\n                            output_digits(s, a1, radix, n_digits, n, is_dec);\n                        }\n                    }\n                } else {\n                    size_t pos, start;\n                    bf_t a_s, *a = &a_s;\n\n                    /* make a positive number */\n                    a->tab = a2->tab;\n                    a->len = a2->len;\n                    a->expn = a2->expn;\n                    a->sign = 0;\n                    \n                    /* one more digit for the rounding */\n                    n = 1 + bf_mul_log2_radix(bf_max(a->expn, 0), radix, TRUE, TRUE);\n                    n_digits = n + prec;\n                    n1 = n;\n                    if (bf_convert_to_radix(a1, &n1, a, radix, n_digits,\n                                            flags & BF_RND_MASK, TRUE))\n                        goto fail1;\n                    start = s->size;\n                    output_digits(s, a1, radix, n_digits, n, is_dec);\n                    /* remove leading zeros because we allocated one more digit */\n                    pos = start;\n                    while ((pos + 1) < s->size && s->buf[pos] == '0' &&\n                           s->buf[pos + 1] != '.')\n                        pos++;\n                    if (pos > start) {\n                        memmove(s->buf + start, s->buf + pos, s->size - pos);\n                        s->size -= (pos - start);\n                    }\n                }\n            } else {\n#ifdef USE_BF_DEC\n                if (is_dec) {\n                    if (bf_set(a1, a2))\n                        goto fail1;\n                    if (fmt == BF_FTOA_FORMAT_FIXED) {\n                        n_digits = prec;\n                        n_max = n_digits;\n                        if (bfdec_round((bfdec_t *)a1, prec, (flags & BF_RND_MASK)) & BF_ST_MEM_ERROR)\n                            goto fail1;\n                    } else {\n                        /* prec is ignored */\n                        prec = n_digits = a1->len * LIMB_DIGITS;\n                        /* remove the trailing zero digits */\n                        while (n_digits > 1 &&\n                               get_digit(a1->tab, a1->len, prec - n_digits) == 0) {\n                            n_digits--;\n                        }\n                        n_max = n_digits + 4;\n                    }\n                    n = a1->expn;\n                } else\n#endif\n                if (radix_bits != 0) {\n                    if (bf_set(a1, a2))\n                        goto fail1;\n                    if (fmt == BF_FTOA_FORMAT_FIXED) {\n                        slimb_t prec_bits;\n                        n_digits = prec;\n                        n_max = n_digits;\n                        /* align to the radix point */\n                        prec_bits = prec * radix_bits -\n                            smod(-a1->expn, radix_bits);\n                        if (bf_round(a1, prec_bits,\n                                     (flags & BF_RND_MASK)) & BF_ST_MEM_ERROR)\n                            goto fail1;\n                    } else {\n                        limb_t digit_mask;\n                        slimb_t pos;\n                        /* position of the digit before the most\n                           significant digit in bits */\n                        pos = a1->len * LIMB_BITS +\n                            smod(-a1->expn, radix_bits);\n                        n_digits = ceil_div(pos, radix_bits);\n                        /* remove the trailing zero digits */\n                        digit_mask = ((limb_t)1 << radix_bits) - 1;\n                        while (n_digits > 1 &&\n                               (get_bits(a1->tab, a1->len, pos - n_digits * radix_bits) & digit_mask) == 0) {\n                            n_digits--;\n                        }\n                        n_max = n_digits + 4;\n                    }\n                    n = ceil_div(a1->expn, radix_bits);\n                } else {\n                    bf_t a_s, *a = &a_s;\n                    \n                    /* make a positive number */\n                    a->tab = a2->tab;\n                    a->len = a2->len;\n                    a->expn = a2->expn;\n                    a->sign = 0;\n                    \n                    if (fmt == BF_FTOA_FORMAT_FIXED) {\n                        n_digits = prec;\n                        n_max = n_digits;\n                    } else {\n                        slimb_t n_digits_max, n_digits_min;\n                        \n                        assert(prec != BF_PREC_INF);\n                        n_digits = 1 + bf_mul_log2_radix(prec, radix, TRUE, TRUE);\n                        /* max number of digits for non exponential\n                           notation. The rational is to have the same rule\n                           as JS i.e. n_max = 21 for 64 bit float in base 10. */\n                        n_max = n_digits + 4;\n                        if (fmt == BF_FTOA_FORMAT_FREE_MIN) {\n                            bf_t b_s, *b = &b_s;\n                            \n                            /* find the minimum number of digits by\n                               dichotomy. */\n                            /* XXX: inefficient */\n                            n_digits_max = n_digits;\n                            n_digits_min = 1;\n                            bf_init(ctx, b);\n                            while (n_digits_min < n_digits_max) {\n                                n_digits = (n_digits_min + n_digits_max) / 2;\n                                if (bf_convert_to_radix(a1, &n, a, radix, n_digits,\n                                                        flags & BF_RND_MASK, FALSE)) {\n                                    bf_delete(b);\n                                    goto fail1;\n                                }\n                                /* convert back to a number and compare */\n                                ret = bf_mul_pow_radix(b, a1, radix, n - n_digits,\n                                                       prec,\n                                                       (flags & ~BF_RND_MASK) |\n                                                       BF_RNDN);\n                                if (ret & BF_ST_MEM_ERROR) {\n                                    bf_delete(b);\n                                    goto fail1;\n                                }\n                                if (bf_cmpu(b, a) == 0) {\n                                    n_digits_max = n_digits;\n                                } else {\n                                    n_digits_min = n_digits + 1;\n                                }\n                            }\n                            bf_delete(b);\n                            n_digits = n_digits_max;\n                        }\n                    }\n                    if (bf_convert_to_radix(a1, &n, a, radix, n_digits,\n                                            flags & BF_RND_MASK, FALSE)) {\n                    fail1:\n                        bf_delete(a1);\n                        goto fail;\n                    }\n                }\n                if (a1->expn == BF_EXP_ZERO &&\n                    fmt != BF_FTOA_FORMAT_FIXED &&\n                    !(flags & BF_FTOA_FORCE_EXP)) {\n                    /* just output zero */\n                    dbuf_putstr(s, \"0\");\n                } else {\n                    if (flags & BF_FTOA_ADD_PREFIX) {\n                        if (radix == 16)\n                            dbuf_putstr(s, \"0x\");\n                        else if (radix == 8)\n                            dbuf_putstr(s, \"0o\");\n                        else if (radix == 2)\n                            dbuf_putstr(s, \"0b\");\n                    }\n                    if (a1->expn == BF_EXP_ZERO)\n                        n = 1;\n                    if ((flags & BF_FTOA_FORCE_EXP) ||\n                        n <= -6 || n > n_max) {\n                        const char *fmt;\n                        /* exponential notation */\n                        output_digits(s, a1, radix, n_digits, 1, is_dec);\n                        if (radix_bits != 0 && radix <= 16) {\n                            if (flags & BF_FTOA_JS_QUIRKS)\n                                fmt = \"p%+\" PRId_LIMB;\n                            else\n                                fmt = \"p%\" PRId_LIMB;\n                            dbuf_printf(s, fmt, (n - 1) * radix_bits);\n                        } else {\n                            if (flags & BF_FTOA_JS_QUIRKS)\n                                fmt = \"%c%+\" PRId_LIMB;\n                            else\n                                fmt = \"%c%\" PRId_LIMB;\n                            dbuf_printf(s, fmt,\n                                        radix <= 10 ? 'e' : '@', n - 1);\n                        }\n                    } else if (n <= 0) {\n                        /* 0.x */\n                        dbuf_putstr(s, \"0.\");\n                        for(i = 0; i < -n; i++) {\n                            dbuf_putc(s, '0');\n                        }\n                        output_digits(s, a1, radix, n_digits, n_digits, is_dec);\n                    } else {\n                        if (n_digits <= n) {\n                            /* no dot */\n                            output_digits(s, a1, radix, n_digits, n_digits, is_dec);\n                            for(i = 0; i < (n - n_digits); i++)\n                                dbuf_putc(s, '0');\n                        } else {\n                            output_digits(s, a1, radix, n_digits, n, is_dec);\n                        }\n                    }\n                }\n            }\n            bf_delete(a1);\n        }\n    }\n    dbuf_putc(s, '\\0');\n    if (dbuf_error(s))\n        goto fail;\n    if (plen)\n        *plen = s->size - 1;\n    return (char *)s->buf;\n fail:\n    bf_free(ctx, s->buf);\n    if (plen)\n        *plen = 0;\n    return NULL;\n}\n\nchar *bf_ftoa(size_t *plen, const bf_t *a, int radix, limb_t prec,\n              bf_flags_t flags)\n{\n    return bf_ftoa_internal(plen, a, radix, prec, flags, FALSE);\n}\n\n/***************************************************************/\n/* transcendental functions */\n\n/* Note: the algorithm is from MPFR */\nstatic void bf_const_log2_rec(bf_t *T, bf_t *P, bf_t *Q, limb_t n1,\n                              limb_t n2, BOOL need_P)\n{\n    bf_context_t *s = T->ctx;\n    if ((n2 - n1) == 1) {\n        if (n1 == 0) {\n            bf_set_ui(P, 3);\n        } else {\n            bf_set_ui(P, n1);\n            P->sign = 1;\n        }\n        bf_set_ui(Q, 2 * n1 + 1);\n        Q->expn += 2;\n        bf_set(T, P);\n    } else {\n        limb_t m;\n        bf_t T1_s, *T1 = &T1_s;\n        bf_t P1_s, *P1 = &P1_s;\n        bf_t Q1_s, *Q1 = &Q1_s;\n        \n        m = n1 + ((n2 - n1) >> 1);\n        bf_const_log2_rec(T, P, Q, n1, m, TRUE);\n        bf_init(s, T1);\n        bf_init(s, P1);\n        bf_init(s, Q1);\n        bf_const_log2_rec(T1, P1, Q1, m, n2, need_P);\n        bf_mul(T, T, Q1, BF_PREC_INF, BF_RNDZ);\n        bf_mul(T1, T1, P, BF_PREC_INF, BF_RNDZ);\n        bf_add(T, T, T1, BF_PREC_INF, BF_RNDZ);\n        if (need_P)\n            bf_mul(P, P, P1, BF_PREC_INF, BF_RNDZ);\n        bf_mul(Q, Q, Q1, BF_PREC_INF, BF_RNDZ);\n        bf_delete(T1);\n        bf_delete(P1);\n        bf_delete(Q1);\n    }\n}\n\n/* compute log(2) with faithful rounding at precision 'prec' */\nstatic void bf_const_log2_internal(bf_t *T, limb_t prec)\n{\n    limb_t w, N;\n    bf_t P_s, *P = &P_s;\n    bf_t Q_s, *Q = &Q_s;\n\n    w = prec + 15;\n    N = w / 3 + 1;\n    bf_init(T->ctx, P);\n    bf_init(T->ctx, Q);\n    bf_const_log2_rec(T, P, Q, 0, N, FALSE);\n    bf_div(T, T, Q, prec, BF_RNDN);\n    bf_delete(P);\n    bf_delete(Q);\n}\n\n/* PI constant */\n\n#define CHUD_A 13591409\n#define CHUD_B 545140134\n#define CHUD_C 640320\n#define CHUD_BITS_PER_TERM 47\n\nstatic void chud_bs(bf_t *P, bf_t *Q, bf_t *G, int64_t a, int64_t b, int need_g,\n                    limb_t prec)\n{\n    bf_context_t *s = P->ctx;\n    int64_t c;\n\n    if (a == (b - 1)) {\n        bf_t T0, T1;\n        \n        bf_init(s, &T0);\n        bf_init(s, &T1);\n        bf_set_ui(G, 2 * b - 1);\n        bf_mul_ui(G, G, 6 * b - 1, prec, BF_RNDN);\n        bf_mul_ui(G, G, 6 * b - 5, prec, BF_RNDN);\n        bf_set_ui(&T0, CHUD_B);\n        bf_mul_ui(&T0, &T0, b, prec, BF_RNDN);\n        bf_set_ui(&T1, CHUD_A);\n        bf_add(&T0, &T0, &T1, prec, BF_RNDN);\n        bf_mul(P, G, &T0, prec, BF_RNDN);\n        P->sign = b & 1;\n\n        bf_set_ui(Q, b);\n        bf_mul_ui(Q, Q, b, prec, BF_RNDN);\n        bf_mul_ui(Q, Q, b, prec, BF_RNDN);\n        bf_mul_ui(Q, Q, (uint64_t)CHUD_C * CHUD_C * CHUD_C / 24, prec, BF_RNDN);\n        bf_delete(&T0);\n        bf_delete(&T1);\n    } else {\n        bf_t P2, Q2, G2;\n        \n        bf_init(s, &P2);\n        bf_init(s, &Q2);\n        bf_init(s, &G2);\n\n        c = (a + b) / 2;\n        chud_bs(P, Q, G, a, c, 1, prec);\n        chud_bs(&P2, &Q2, &G2, c, b, need_g, prec);\n        \n        /* Q = Q1 * Q2 */\n        /* G = G1 * G2 */\n        /* P = P1 * Q2 + P2 * G1 */\n        bf_mul(&P2, &P2, G, prec, BF_RNDN);\n        if (!need_g)\n            bf_set_ui(G, 0);\n        bf_mul(P, P, &Q2, prec, BF_RNDN);\n        bf_add(P, P, &P2, prec, BF_RNDN);\n        bf_delete(&P2);\n\n        bf_mul(Q, Q, &Q2, prec, BF_RNDN);\n        bf_delete(&Q2);\n        if (need_g)\n            bf_mul(G, G, &G2, prec, BF_RNDN);\n        bf_delete(&G2);\n    }\n}\n\n/* compute Pi with faithful rounding at precision 'prec' using the\n   Chudnovsky formula */\nstatic void bf_const_pi_internal(bf_t *Q, limb_t prec)\n{\n    bf_context_t *s = Q->ctx;\n    int64_t n, prec1;\n    bf_t P, G;\n\n    /* number of serie terms */\n    n = prec / CHUD_BITS_PER_TERM + 1;\n    /* XXX: precision analysis */\n    prec1 = prec + 32;\n\n    bf_init(s, &P);\n    bf_init(s, &G);\n\n    chud_bs(&P, Q, &G, 0, n, 0, BF_PREC_INF);\n    \n    bf_mul_ui(&G, Q, CHUD_A, prec1, BF_RNDN);\n    bf_add(&P, &G, &P, prec1, BF_RNDN);\n    bf_div(Q, Q, &P, prec1, BF_RNDF);\n \n    bf_set_ui(&P, CHUD_C);\n    bf_sqrt(&G, &P, prec1, BF_RNDF);\n    bf_mul_ui(&G, &G, (uint64_t)CHUD_C / 12, prec1, BF_RNDF);\n    bf_mul(Q, Q, &G, prec, BF_RNDN);\n    bf_delete(&P);\n    bf_delete(&G);\n}\n\nstatic int bf_const_get(bf_t *T, limb_t prec, bf_flags_t flags,\n                        BFConstCache *c,\n                        void (*func)(bf_t *res, limb_t prec), int sign)\n{\n    limb_t ziv_extra_bits, prec1;\n\n    ziv_extra_bits = 32;\n    for(;;) {\n        prec1 = prec + ziv_extra_bits;\n        if (c->prec < prec1) {\n            if (c->val.len == 0)\n                bf_init(T->ctx, &c->val);\n            func(&c->val, prec1);\n            c->prec = prec1;\n        } else {\n            prec1 = c->prec;\n        }\n        bf_set(T, &c->val);\n        T->sign = sign;\n        if (!bf_can_round(T, prec, flags & BF_RND_MASK, prec1)) {\n            /* and more precision and retry */\n            ziv_extra_bits = ziv_extra_bits  + (ziv_extra_bits / 2);\n        } else {\n            break;\n        }\n    }\n    return bf_round(T, prec, flags);\n}\n\nstatic void bf_const_free(BFConstCache *c)\n{\n    bf_delete(&c->val);\n    memset(c, 0, sizeof(*c));\n}\n\nint bf_const_log2(bf_t *T, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = T->ctx;\n    return bf_const_get(T, prec, flags, &s->log2_cache, bf_const_log2_internal, 0);\n}\n\n/* return rounded pi * (1 - 2 * sign) */\nstatic int bf_const_pi_signed(bf_t *T, int sign, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = T->ctx;\n    return bf_const_get(T, prec, flags, &s->pi_cache, bf_const_pi_internal,\n                        sign);\n}\n\nint bf_const_pi(bf_t *T, limb_t prec, bf_flags_t flags)\n{\n    return bf_const_pi_signed(T, 0, prec, flags);\n}\n\nvoid bf_clear_cache(bf_context_t *s)\n{\n#ifdef USE_FFT_MUL\n    fft_clear_cache(s);\n#endif\n    bf_const_free(&s->log2_cache);\n    bf_const_free(&s->pi_cache);\n}\n\n/* ZivFunc should compute the result 'r' with faithful rounding at\n   precision 'prec'. For efficiency purposes, the final bf_round()\n   does not need to be done in the function. */\ntypedef int ZivFunc(bf_t *r, const bf_t *a, limb_t prec, void *opaque);\n\nstatic int bf_ziv_rounding(bf_t *r, const bf_t *a,\n                           limb_t prec, bf_flags_t flags,\n                           ZivFunc *f, void *opaque)\n{\n    int rnd_mode, ret;\n    slimb_t prec1, ziv_extra_bits;\n    \n    rnd_mode = flags & BF_RND_MASK;\n    if (rnd_mode == BF_RNDF) {\n        /* no need to iterate */\n        f(r, a, prec, opaque);\n        ret = 0;\n    } else {\n        ziv_extra_bits = 32;\n        for(;;) {\n            prec1 = prec + ziv_extra_bits;\n            ret = f(r, a, prec1, opaque);\n            if (ret & (BF_ST_OVERFLOW | BF_ST_UNDERFLOW | BF_ST_MEM_ERROR)) {\n                /* overflow or underflow should never happen because\n                   it indicates the rounding cannot be done correctly,\n                   but we do not catch all the cases */\n                return ret;\n            }\n            /* if the result is exact, we can stop */\n            if (!(ret & BF_ST_INEXACT)) {\n                ret = 0;\n                break;\n            }\n            if (bf_can_round(r, prec, rnd_mode, prec1)) {\n                ret = BF_ST_INEXACT;\n                break;\n            }\n            ziv_extra_bits = ziv_extra_bits * 2;\n            //            printf(\"ziv_extra_bits=%\" PRId64 \"\\n\", (int64_t)ziv_extra_bits);\n        }\n    }\n    if (r->len == 0)\n        return ret;\n    else\n        return __bf_round(r, prec, flags, r->len, ret);\n}\n\n/* add (1 - 2*e_sign) * 2^e */\nstatic int bf_add_epsilon(bf_t *r, const bf_t *a, slimb_t e, int e_sign,\n                          limb_t prec, int flags)\n{\n    bf_t T_s, *T = &T_s;\n    int ret;\n    /* small argument case: result = 1 + epsilon * sign(x) */\n    bf_init(a->ctx, T);\n    bf_set_ui(T, 1);\n    T->sign = e_sign;\n    T->expn += e;\n    ret = bf_add(r, r, T, prec, flags);\n    bf_delete(T);\n    return ret;\n}\n\n/* Compute the exponential using faithful rounding at precision 'prec'.\n   Note: the algorithm is from MPFR */\nstatic int bf_exp_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    slimb_t n, K, l, i, prec1;\n    \n    assert(r != a);\n\n    /* argument reduction:\n       T = a - n*log(2) with 0 <= T < log(2) and n integer.\n    */\n    bf_init(s, T);\n    if (a->expn <= -1) {\n        /* 0 <= abs(a) <= 0.5 */\n        if (a->sign)\n            n = -1;\n        else\n            n = 0;\n    } else {\n        bf_const_log2(T, LIMB_BITS, BF_RNDZ);\n        bf_div(T, a, T, LIMB_BITS, BF_RNDD);\n        bf_get_limb(&n, T, 0);\n    }\n\n    K = bf_isqrt((prec + 1) / 2);\n    l = (prec - 1) / K + 1;\n    /* XXX: precision analysis ? */\n    prec1 = prec + (K + 2 * l + 18) + K + 8;\n    if (a->expn > 0)\n        prec1 += a->expn;\n    //    printf(\"n=%ld K=%ld prec1=%ld\\n\", n, K, prec1);\n\n    bf_const_log2(T, prec1, BF_RNDF);\n    bf_mul_si(T, T, n, prec1, BF_RNDN);\n    bf_sub(T, a, T, prec1, BF_RNDN);\n\n    /* reduce the range of T */\n    bf_mul_2exp(T, -K, BF_PREC_INF, BF_RNDZ);\n    \n    /* Taylor expansion around zero :\n     1 + x + x^2/2 + ... + x^n/n! \n     = (1 + x * (1 + x/2 * (1 + ... (x/n))))\n    */\n    {\n        bf_t U_s, *U = &U_s;\n        \n        bf_init(s, U);\n        bf_set_ui(r, 1);\n        for(i = l ; i >= 1; i--) {\n            bf_set_ui(U, i);\n            bf_div(U, T, U, prec1, BF_RNDN);\n            bf_mul(r, r, U, prec1, BF_RNDN);\n            bf_add_si(r, r, 1, prec1, BF_RNDN);\n        }\n        bf_delete(U);\n    }\n    bf_delete(T);\n    \n    /* undo the range reduction */\n    for(i = 0; i < K; i++) {\n        bf_mul(r, r, r, prec1, BF_RNDN | BF_FLAG_EXT_EXP);\n    }\n\n    /* undo the argument reduction */\n    bf_mul_2exp(r, n, BF_PREC_INF, BF_RNDZ | BF_FLAG_EXT_EXP);\n\n    return BF_ST_INEXACT;\n}\n\n/* crude overflow and underflow tests for exp(a). a_low <= a <= a_high */\nstatic int check_exp_underflow_overflow(bf_context_t *s, bf_t *r,\n                                        const bf_t *a_low, const bf_t *a_high,\n                                        limb_t prec, bf_flags_t flags)\n{\n    bf_t T_s, *T = &T_s;\n    bf_t log2_s, *log2 = &log2_s;\n    slimb_t e_min, e_max;\n    \n    if (a_high->expn <= 0)\n        return 0;\n\n    e_max = (limb_t)1 << (bf_get_exp_bits(flags) - 1);\n    e_min = -e_max + 3;\n    if (flags & BF_FLAG_SUBNORMAL)\n        e_min -= (prec - 1);\n    \n    bf_init(s, T);\n    bf_init(s, log2);\n    bf_const_log2(log2, LIMB_BITS, BF_RNDU);\n    bf_mul_ui(T, log2, e_max, LIMB_BITS, BF_RNDU);\n    /* a_low > e_max * log(2) implies exp(a) > e_max */\n    if (bf_cmp_lt(T, a_low) > 0) {\n        /* overflow */\n        bf_delete(T);\n        bf_delete(log2);\n        return bf_set_overflow(r, 0, prec, flags);\n    }\n    /* a_high < (e_min - 2) * log(2) implies exp(a) < (e_min - 2) */\n    bf_const_log2(log2, LIMB_BITS, BF_RNDD);\n    bf_mul_si(T, log2, e_min - 2, LIMB_BITS, BF_RNDD);\n    if (bf_cmp_lt(a_high, T)) {\n        int rnd_mode = flags & BF_RND_MASK;\n        \n        /* underflow */\n        bf_delete(T);\n        bf_delete(log2);\n        if (rnd_mode == BF_RNDU) {\n            /* set the smallest value */\n            bf_set_ui(r, 1);\n            r->expn = e_min;\n        } else {\n            bf_set_zero(r, 0);\n        }\n        return BF_ST_UNDERFLOW | BF_ST_INEXACT;\n    }\n    bf_delete(log2);\n    bf_delete(T);\n    return 0;\n}\n\nint bf_exp(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = r->ctx;\n    int ret;\n    assert(r != a);\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n        } else if (a->expn == BF_EXP_INF) {\n            if (a->sign)\n                bf_set_zero(r, 0);\n            else\n                bf_set_inf(r, 0);\n        } else {\n            bf_set_ui(r, 1);\n        }\n        return 0;\n    }\n\n    ret = check_exp_underflow_overflow(s, r, a, a, prec, flags);\n    if (ret)\n        return ret;\n    if (a->expn < 0 && (-a->expn) >= (prec + 2)) { \n        /* small argument case: result = 1 + epsilon * sign(x) */\n        bf_set_ui(r, 1);\n        return bf_add_epsilon(r, r, -(prec + 2), a->sign, prec, flags);\n    }\n                         \n    return bf_ziv_rounding(r, a, prec, flags, bf_exp_internal, NULL);\n}\n\nstatic int bf_log_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    bf_t U_s, *U = &U_s;\n    bf_t V_s, *V = &V_s;\n    slimb_t n, prec1, l, i, K;\n    \n    assert(r != a);\n\n    bf_init(s, T);\n    /* argument reduction 1 */\n    /* T=a*2^n with 2/3 <= T <= 4/3 */\n    {\n        bf_t U_s, *U = &U_s;\n        bf_set(T, a);\n        n = T->expn;\n        T->expn = 0;\n        /* U= ~ 2/3 */\n        bf_init(s, U);\n        bf_set_ui(U, 0xaaaaaaaa); \n        U->expn = 0;\n        if (bf_cmp_lt(T, U)) {\n            T->expn++;\n            n--;\n        }\n        bf_delete(U);\n    }\n    //    printf(\"n=%ld\\n\", n);\n    //    bf_print_str(\"T\", T);\n\n    /* XXX: precision analysis */\n    /* number of iterations for argument reduction 2 */\n    K = bf_isqrt((prec + 1) / 2); \n    /* order of Taylor expansion */\n    l = prec / (2 * K) + 1; \n    /* precision of the intermediate computations */\n    prec1 = prec + K + 2 * l + 32;\n\n    bf_init(s, U);\n    bf_init(s, V);\n    \n    /* Note: cancellation occurs here, so we use more precision (XXX:\n       reduce the precision by computing the exact cancellation) */\n    bf_add_si(T, T, -1, BF_PREC_INF, BF_RNDN); \n\n    /* argument reduction 2 */\n    for(i = 0; i < K; i++) {\n        /* T = T / (1 + sqrt(1 + T)) */\n        bf_add_si(U, T, 1, prec1, BF_RNDN);\n        bf_sqrt(V, U, prec1, BF_RNDF);\n        bf_add_si(U, V, 1, prec1, BF_RNDN);\n        bf_div(T, T, U, prec1, BF_RNDN);\n    }\n\n    {\n        bf_t Y_s, *Y = &Y_s;\n        bf_t Y2_s, *Y2 = &Y2_s;\n        bf_init(s, Y);\n        bf_init(s, Y2);\n\n        /* compute ln(1+x) = ln((1+y)/(1-y)) with y=x/(2+x)\n           = y + y^3/3 + ... + y^(2*l + 1) / (2*l+1) \n           with Y=Y^2\n           = y*(1+Y/3+Y^2/5+...) = y*(1+Y*(1/3+Y*(1/5 + ...)))\n        */\n        bf_add_si(Y, T, 2, prec1, BF_RNDN);\n        bf_div(Y, T, Y, prec1, BF_RNDN);\n\n        bf_mul(Y2, Y, Y, prec1, BF_RNDN);\n        bf_set_ui(r, 0);\n        for(i = l; i >= 1; i--) {\n            bf_set_ui(U, 1);\n            bf_set_ui(V, 2 * i + 1);\n            bf_div(U, U, V, prec1, BF_RNDN);\n            bf_add(r, r, U, prec1, BF_RNDN);\n            bf_mul(r, r, Y2, prec1, BF_RNDN);\n        }\n        bf_add_si(r, r, 1, prec1, BF_RNDN);\n        bf_mul(r, r, Y, prec1, BF_RNDN);\n        bf_delete(Y);\n        bf_delete(Y2);\n    }\n    bf_delete(V);\n    bf_delete(U);\n\n    /* multiplication by 2 for the Taylor expansion and undo the\n       argument reduction 2*/\n    bf_mul_2exp(r, K + 1, BF_PREC_INF, BF_RNDZ);\n    \n    /* undo the argument reduction 1 */\n    bf_const_log2(T, prec1, BF_RNDF);\n    bf_mul_si(T, T, n, prec1, BF_RNDN);\n    bf_add(r, r, T, prec1, BF_RNDN);\n    \n    bf_delete(T);\n    return BF_ST_INEXACT;\n}\n\nint bf_log(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    \n    assert(r != a);\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF) {\n            if (a->sign) {\n                bf_set_nan(r);\n                return BF_ST_INVALID_OP;\n            } else {\n                bf_set_inf(r, 0);\n                return 0;\n            }\n        } else {\n            bf_set_inf(r, 1);\n            return 0;\n        }\n    }\n    if (a->sign) {\n        bf_set_nan(r);\n        return BF_ST_INVALID_OP;\n    }\n    bf_init(s, T);\n    bf_set_ui(T, 1);\n    if (bf_cmp_eq(a, T)) {\n        bf_set_zero(r, 0);\n        bf_delete(T);\n        return 0;\n    }\n    bf_delete(T);\n\n    return bf_ziv_rounding(r, a, prec, flags, bf_log_internal, NULL);\n}\n\n/* x and y finite and x > 0 */\nstatic int bf_pow_generic(bf_t *r, const bf_t *x, limb_t prec, void *opaque)\n{\n    bf_context_t *s = r->ctx;\n    const bf_t *y = opaque;\n    bf_t T_s, *T = &T_s;\n    limb_t prec1;\n\n    bf_init(s, T);\n    /* XXX: proof for the added precision */\n    prec1 = prec + 32;\n    bf_log(T, x, prec1, BF_RNDF | BF_FLAG_EXT_EXP);\n    bf_mul(T, T, y, prec1, BF_RNDF | BF_FLAG_EXT_EXP);\n    if (bf_is_nan(T))\n        bf_set_nan(r);\n    else\n        bf_exp_internal(r, T, prec1, NULL); /* no overflow/underlow test needed */\n    bf_delete(T);\n    return BF_ST_INEXACT;\n}\n\n/* x and y finite, x > 0, y integer and y fits on one limb */\nstatic int bf_pow_int(bf_t *r, const bf_t *x, limb_t prec, void *opaque)\n{\n    bf_context_t *s = r->ctx;\n    const bf_t *y = opaque;\n    bf_t T_s, *T = &T_s;\n    limb_t prec1;\n    int ret;\n    slimb_t y1;\n    \n    bf_get_limb(&y1, y, 0);\n    if (y1 < 0)\n        y1 = -y1;\n    /* XXX: proof for the added precision */\n    prec1 = prec + ceil_log2(y1) * 2 + 8;\n    ret = bf_pow_ui(r, x, y1 < 0 ? -y1 : y1, prec1, BF_RNDN | BF_FLAG_EXT_EXP);\n    if (y->sign) {\n        bf_init(s, T);\n        bf_set_ui(T, 1);\n        ret |= bf_div(r, T, r, prec1, BF_RNDN | BF_FLAG_EXT_EXP);\n        bf_delete(T);\n    }\n    return ret;\n}\n\n/* x must be a finite non zero float. Return TRUE if there is a\n   floating point number r such as x=r^(2^n) and return this floating\n   point number 'r'. Otherwise return FALSE and r is undefined. */\nstatic BOOL check_exact_power2n(bf_t *r, const bf_t *x, slimb_t n)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    slimb_t e, i, er;\n    limb_t v;\n    \n    /* x = m*2^e with m odd integer */\n    e = bf_get_exp_min(x);\n    /* fast check on the exponent */\n    if (n > (LIMB_BITS - 1)) {\n        if (e != 0)\n            return FALSE;\n        er = 0;\n    } else {\n        if ((e & (((limb_t)1 << n) - 1)) != 0)\n            return FALSE;\n        er = e >> n;\n    }\n    /* every perfect odd square = 1 modulo 8 */\n    v = get_bits(x->tab, x->len, x->len * LIMB_BITS - x->expn + e);\n    if ((v & 7) != 1)\n        return FALSE;\n\n    bf_init(s, T);\n    bf_set(T, x);\n    T->expn -= e;\n    for(i = 0; i < n; i++) {\n        if (i != 0)\n            bf_set(T, r);\n        if (bf_sqrtrem(r, NULL, T) != 0)\n            return FALSE;\n    }\n    r->expn += er;\n    return TRUE;\n}\n\n/* prec = BF_PREC_INF is accepted for x and y integers and y >= 0 */\nint bf_pow(bf_t *r, const bf_t *x, const bf_t *y, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    bf_t ytmp_s;\n    BOOL y_is_int, y_is_odd;\n    int r_sign, ret, rnd_mode;\n    slimb_t y_emin;\n    \n    if (x->len == 0 || y->len == 0) {\n        if (y->expn == BF_EXP_ZERO) {\n            /* pow(x, 0) = 1 */\n            bf_set_ui(r, 1);\n        } else if (x->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n        } else {\n            int cmp_x_abs_1;\n            bf_set_ui(r, 1);\n            cmp_x_abs_1 = bf_cmpu(x, r);\n            if (cmp_x_abs_1 == 0 && (flags & BF_POW_JS_QUIRKS) &&\n                (y->expn >= BF_EXP_INF)) {\n                bf_set_nan(r);\n            } else if (cmp_x_abs_1 == 0 &&\n                       (!x->sign || y->expn != BF_EXP_NAN)) {\n                /* pow(1, y) = 1 even if y = NaN */\n                /* pow(-1, +/-inf) = 1 */\n            } else if (y->expn == BF_EXP_NAN) {\n                bf_set_nan(r);\n            } else if (y->expn == BF_EXP_INF) {\n                if (y->sign == (cmp_x_abs_1 > 0)) {\n                    bf_set_zero(r, 0);\n                } else {\n                    bf_set_inf(r, 0);\n                }\n            } else {\n                y_emin = bf_get_exp_min(y);\n                y_is_odd = (y_emin == 0);\n                if (y->sign == (x->expn == BF_EXP_ZERO)) {\n                    bf_set_inf(r, y_is_odd & x->sign);\n                    if (y->sign) {\n                        /* pow(0, y) with y < 0 */\n                        return BF_ST_DIVIDE_ZERO;\n                    }\n                } else {\n                    bf_set_zero(r, y_is_odd & x->sign);\n                }\n            }\n        }\n        return 0;\n    }\n    bf_init(s, T);\n    bf_set(T, x);\n    y_emin = bf_get_exp_min(y);\n    y_is_int = (y_emin >= 0);\n    rnd_mode = flags & BF_RND_MASK;\n    if (x->sign) {\n        if (!y_is_int) {\n            bf_set_nan(r);\n            bf_delete(T);\n            return BF_ST_INVALID_OP;\n        }\n        y_is_odd = (y_emin == 0);\n        r_sign = y_is_odd;\n        /* change the directed rounding mode if the sign of the result\n           is changed */\n        if (r_sign && (rnd_mode == BF_RNDD || rnd_mode == BF_RNDU))\n            flags ^= 1;\n        bf_neg(T);\n    } else {\n        r_sign = 0;\n    }\n\n    bf_set_ui(r, 1);\n    if (bf_cmp_eq(T, r)) {\n        /* abs(x) = 1: nothing more to do */\n        ret = 0;\n    } else {\n        /* check the overflow/underflow cases */\n        {\n            bf_t al_s, *al = &al_s;\n            bf_t ah_s, *ah = &ah_s;\n            limb_t precl = LIMB_BITS;\n            \n            bf_init(s, al);\n            bf_init(s, ah);\n            /* compute bounds of log(abs(x)) * y with a low precision */\n            /* XXX: compute bf_log() once */\n            /* XXX: add a fast test before this slow test */\n            bf_log(al, T, precl, BF_RNDD);\n            bf_log(ah, T, precl, BF_RNDU);\n            bf_mul(al, al, y, precl, BF_RNDD ^ y->sign);\n            bf_mul(ah, ah, y, precl, BF_RNDU ^ y->sign);\n            ret = check_exp_underflow_overflow(s, r, al, ah, prec, flags);\n            bf_delete(al);\n            bf_delete(ah);\n            if (ret)\n                goto done;\n        }\n        \n        if (y_is_int) {\n            slimb_t T_bits, e;\n        int_pow:\n            T_bits = T->expn - bf_get_exp_min(T);\n            if (T_bits == 1) {\n                /* pow(2^b, y) = 2^(b*y) */\n                bf_mul_si(T, y, T->expn - 1, LIMB_BITS, BF_RNDZ);\n                bf_get_limb(&e, T, 0);\n                bf_set_ui(r, 1);\n                ret = bf_mul_2exp(r, e, prec, flags);\n            } else if (prec == BF_PREC_INF) {\n                slimb_t y1;\n                /* specific case for infinite precision (integer case) */\n                bf_get_limb(&y1, y, 0);\n                assert(!y->sign);\n                /* x must be an integer, so abs(x) >= 2 */\n                if (y1 >= ((slimb_t)1 << BF_EXP_BITS_MAX)) {\n                    bf_delete(T);\n                    return bf_set_overflow(r, 0, BF_PREC_INF, flags);\n                }\n                ret = bf_pow_ui(r, T, y1, BF_PREC_INF, BF_RNDZ);\n            } else {\n                if (y->expn <= 31) {\n                    /* small enough power: use exponentiation in all cases */\n                } else if (y->sign) {\n                    /* cannot be exact */\n                    goto general_case;\n                } else {\n                    if (rnd_mode == BF_RNDF)\n                        goto general_case; /* no need to track exact results */\n                    /* see if the result has a chance to be exact:\n                       if x=a*2^b (a odd), x^y=a^y*2^(b*y)\n                       x^y needs a precision of at least floor_log2(a)*y bits\n                    */\n                    bf_mul_si(r, y, T_bits - 1, LIMB_BITS, BF_RNDZ);\n                    bf_get_limb(&e, r, 0);\n                    if (prec < e)\n                        goto general_case;\n                }\n                ret = bf_ziv_rounding(r, T, prec, flags, bf_pow_int, (void *)y);\n            }\n        } else {\n            if (rnd_mode != BF_RNDF) {\n                bf_t *y1;\n                if (y_emin < 0 && check_exact_power2n(r, T, -y_emin)) {\n                    /* the problem is reduced to a power to an integer */\n#if 0\n                    printf(\"\\nn=%\" PRId64 \"\\n\", -(int64_t)y_emin);\n                    bf_print_str(\"T\", T);\n                    bf_print_str(\"r\", r);\n#endif\n                    bf_set(T, r);\n                    y1 = &ytmp_s;\n                    y1->tab = y->tab;\n                    y1->len = y->len;\n                    y1->sign = y->sign;\n                    y1->expn = y->expn - y_emin;\n                    y = y1;\n                    goto int_pow;\n                }\n            }\n        general_case:\n            ret = bf_ziv_rounding(r, T, prec, flags, bf_pow_generic, (void *)y);\n        }\n    }\n done:\n    bf_delete(T);\n    r->sign = r_sign;\n    return ret;\n}\n\n/* compute sqrt(-2*x-x^2) to get |sin(x)| from cos(x) - 1. */\nstatic void bf_sqrt_sin(bf_t *r, const bf_t *x, limb_t prec1)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    bf_init(s, T);\n    bf_set(T, x);\n    bf_mul(r, T, T, prec1, BF_RNDN);\n    bf_mul_2exp(T, 1, BF_PREC_INF, BF_RNDZ);\n    bf_add(T, T, r, prec1, BF_RNDN);\n    bf_neg(T);\n    bf_sqrt(r, T, prec1, BF_RNDF);\n    bf_delete(T);\n}\n\nstatic int bf_sincos(bf_t *s, bf_t *c, const bf_t *a, limb_t prec)\n{\n    bf_context_t *s1 = a->ctx;\n    bf_t T_s, *T = &T_s;\n    bf_t U_s, *U = &U_s;\n    bf_t r_s, *r = &r_s;\n    slimb_t K, prec1, i, l, mod, prec2;\n    int is_neg;\n    \n    assert(c != a && s != a);\n\n    bf_init(s1, T);\n    bf_init(s1, U);\n    bf_init(s1, r);\n    \n    /* XXX: precision analysis */\n    K = bf_isqrt(prec / 2);\n    l = prec / (2 * K) + 1;\n    prec1 = prec + 2 * K + l + 8;\n    \n    /* after the modulo reduction, -pi/4 <= T <= pi/4 */\n    if (a->expn <= -1) {\n        /* abs(a) <= 0.25: no modulo reduction needed */\n        bf_set(T, a);\n        mod = 0;\n    } else {\n        slimb_t cancel;\n        cancel = 0;\n        for(;;) {\n            prec2 = prec1 + a->expn + cancel;\n            bf_const_pi(U, prec2, BF_RNDF);\n            bf_mul_2exp(U, -1, BF_PREC_INF, BF_RNDZ);\n            bf_remquo(&mod, T, a, U, prec2, BF_RNDN, BF_RNDN);\n            //            printf(\"T.expn=%ld prec2=%ld\\n\", T->expn, prec2);\n            if (mod == 0 || (T->expn != BF_EXP_ZERO &&\n                             (T->expn + prec2) >= (prec1 - 1)))\n                break;\n            /* increase the number of bits until the precision is good enough */\n            cancel = bf_max(-T->expn, (cancel + 1) * 3 / 2);\n        }\n        mod &= 3;\n    }\n    \n    is_neg = T->sign;\n        \n    /* compute cosm1(x) = cos(x) - 1 */\n    bf_mul(T, T, T, prec1, BF_RNDN);\n    bf_mul_2exp(T, -2 * K, BF_PREC_INF, BF_RNDZ);\n    \n    /* Taylor expansion:\n       -x^2/2 + x^4/4! - x^6/6! + ...\n    */\n    bf_set_ui(r, 1);\n    for(i = l ; i >= 1; i--) {\n        bf_set_ui(U, 2 * i - 1);\n        bf_mul_ui(U, U, 2 * i, BF_PREC_INF, BF_RNDZ);\n        bf_div(U, T, U, prec1, BF_RNDN);\n        bf_mul(r, r, U, prec1, BF_RNDN);\n        bf_neg(r);\n        if (i != 1)\n            bf_add_si(r, r, 1, prec1, BF_RNDN);\n    }\n    bf_delete(U);\n\n    /* undo argument reduction:\n       cosm1(2*x)= 2*(2*cosm1(x)+cosm1(x)^2)\n    */\n    for(i = 0; i < K; i++) {\n        bf_mul(T, r, r, prec1, BF_RNDN);\n        bf_mul_2exp(r, 1, BF_PREC_INF, BF_RNDZ);\n        bf_add(r, r, T, prec1, BF_RNDN);\n        bf_mul_2exp(r, 1, BF_PREC_INF, BF_RNDZ);\n    }\n    bf_delete(T);\n\n    if (c) {\n        if ((mod & 1) == 0) {\n            bf_add_si(c, r, 1, prec1, BF_RNDN);\n        } else {\n            bf_sqrt_sin(c, r, prec1);\n            c->sign = is_neg ^ 1;\n        }\n        c->sign ^= mod >> 1;\n    }\n    if (s) {\n        if ((mod & 1) == 0) {\n            bf_sqrt_sin(s, r, prec1);\n            s->sign = is_neg;\n        } else {\n            bf_add_si(s, r, 1, prec1, BF_RNDN);\n        }\n        s->sign ^= mod >> 1;\n    }\n    bf_delete(r);\n    return BF_ST_INEXACT;\n}\n\nstatic int bf_cos_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)\n{\n    return bf_sincos(NULL, r, a, prec);\n}\n\nint bf_cos(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF) {\n            bf_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bf_set_ui(r, 1);\n            return 0;\n        }\n    }\n\n    /* small argument case: result = 1+r(x) with r(x) = -x^2/2 +\n       O(X^4). We assume r(x) < 2^(2*EXP(x) - 1). */\n    if (a->expn < 0) {\n        slimb_t e;\n        e = 2 * a->expn - 1;\n        if (e < -(prec + 2)) {\n            bf_set_ui(r, 1);\n            return bf_add_epsilon(r, r, e, 1, prec, flags);\n        }\n    }\n    \n    return bf_ziv_rounding(r, a, prec, flags, bf_cos_internal, NULL);\n}\n\nstatic int bf_sin_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)\n{\n    return bf_sincos(r, NULL, a, prec);\n}\n\nint bf_sin(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF) {\n            bf_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bf_set_zero(r, a->sign);\n            return 0;\n        }\n    }\n\n    /* small argument case: result = x+r(x) with r(x) = -x^3/6 +\n       O(X^5). We assume r(x) < 2^(3*EXP(x) - 2). */\n    if (a->expn < 0) {\n        slimb_t e;\n        e = sat_add(2 * a->expn, a->expn - 2);\n        if (e < a->expn - bf_max(prec + 2, a->len * LIMB_BITS + 2)) {\n            bf_set(r, a);\n            return bf_add_epsilon(r, r, e, 1 - a->sign, prec, flags);\n        }\n    }\n\n    return bf_ziv_rounding(r, a, prec, flags, bf_sin_internal, NULL);\n}\n\nstatic int bf_tan_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    limb_t prec1;\n    \n    /* XXX: precision analysis */\n    prec1 = prec + 8;\n    bf_init(s, T);\n    bf_sincos(r, T, a, prec1);\n    bf_div(r, r, T, prec1, BF_RNDF);\n    bf_delete(T);\n    return BF_ST_INEXACT;\n}\n\nint bf_tan(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    assert(r != a);\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF) {\n            bf_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bf_set_zero(r, a->sign);\n            return 0;\n        }\n    }\n\n    /* small argument case: result = x+r(x) with r(x) = x^3/3 +\n       O(X^5). We assume r(x) < 2^(3*EXP(x) - 1). */\n    if (a->expn < 0) {\n        slimb_t e;\n        e = sat_add(2 * a->expn, a->expn - 1);\n        if (e < a->expn - bf_max(prec + 2, a->len * LIMB_BITS + 2)) {\n            bf_set(r, a);\n            return bf_add_epsilon(r, r, e, a->sign, prec, flags);\n        }\n    }\n            \n    return bf_ziv_rounding(r, a, prec, flags, bf_tan_internal, NULL);\n}\n\n/* if add_pi2 is true, add pi/2 to the result (used for acos(x) to\n   avoid cancellation) */\nstatic int bf_atan_internal(bf_t *r, const bf_t *a, limb_t prec,\n                            void *opaque)\n{\n    bf_context_t *s = r->ctx;\n    BOOL add_pi2 = (BOOL)(intptr_t)opaque;\n    bf_t T_s, *T = &T_s;\n    bf_t U_s, *U = &U_s;\n    bf_t V_s, *V = &V_s;\n    bf_t X2_s, *X2 = &X2_s;\n    int cmp_1;\n    slimb_t prec1, i, K, l;\n    \n    /* XXX: precision analysis */\n    K = bf_isqrt((prec + 1) / 2);\n    l = prec / (2 * K) + 1;\n    prec1 = prec + K + 2 * l + 32;\n    //    printf(\"prec=%d K=%d l=%d prec1=%d\\n\", (int)prec, (int)K, (int)l, (int)prec1);\n    \n    bf_init(s, T);\n    cmp_1 = (a->expn >= 1); /* a >= 1 */\n    if (cmp_1) {\n        bf_set_ui(T, 1);\n        bf_div(T, T, a, prec1, BF_RNDN);\n    } else {\n        bf_set(T, a);\n    }\n\n    /* abs(T) <= 1 */\n\n    /* argument reduction */\n\n    bf_init(s, U);\n    bf_init(s, V);\n    bf_init(s, X2);\n    for(i = 0; i < K; i++) {\n        /* T = T / (1 + sqrt(1 + T^2)) */\n        bf_mul(U, T, T, prec1, BF_RNDN);\n        bf_add_si(U, U, 1, prec1, BF_RNDN);\n        bf_sqrt(V, U, prec1, BF_RNDN);\n        bf_add_si(V, V, 1, prec1, BF_RNDN);\n        bf_div(T, T, V, prec1, BF_RNDN);\n    }\n\n    /* Taylor series: \n       x - x^3/3 + ... + (-1)^ l * y^(2*l + 1) / (2*l+1) \n    */\n    bf_mul(X2, T, T, prec1, BF_RNDN);\n    bf_set_ui(r, 0);\n    for(i = l; i >= 1; i--) {\n        bf_set_si(U, 1);\n        bf_set_ui(V, 2 * i + 1);\n        bf_div(U, U, V, prec1, BF_RNDN);\n        bf_neg(r);\n        bf_add(r, r, U, prec1, BF_RNDN);\n        bf_mul(r, r, X2, prec1, BF_RNDN);\n    }\n    bf_neg(r);\n    bf_add_si(r, r, 1, prec1, BF_RNDN);\n    bf_mul(r, r, T, prec1, BF_RNDN);\n\n    /* undo the argument reduction */\n    bf_mul_2exp(r, K, BF_PREC_INF, BF_RNDZ);\n    \n    bf_delete(U);\n    bf_delete(V);\n    bf_delete(X2);\n\n    i = add_pi2;\n    if (cmp_1 > 0) {\n        /* undo the inversion : r = sign(a)*PI/2 - r */\n        bf_neg(r);\n        i += 1 - 2 * a->sign;\n    }\n    /* add i*(pi/2) with -1 <= i <= 2 */\n    if (i != 0) {\n        bf_const_pi(T, prec1, BF_RNDF);\n        if (i != 2)\n            bf_mul_2exp(T, -1, BF_PREC_INF, BF_RNDZ);\n        T->sign = (i < 0);\n        bf_add(r, T, r, prec1, BF_RNDN);\n    }\n    \n    bf_delete(T);\n    return BF_ST_INEXACT;\n}\n\nint bf_atan(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    int res;\n    \n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF)  {\n            /* -PI/2 or PI/2 */\n            bf_const_pi_signed(r, a->sign, prec, flags);\n            bf_mul_2exp(r, -1, BF_PREC_INF, BF_RNDZ);\n            return BF_ST_INEXACT;\n        } else {\n            bf_set_zero(r, a->sign);\n            return 0;\n        }\n    }\n    \n    bf_init(s, T);\n    bf_set_ui(T, 1);\n    res = bf_cmpu(a, T);\n    bf_delete(T);\n    if (res == 0) {\n        /* short cut: abs(a) == 1 -> +/-pi/4 */\n        bf_const_pi_signed(r, a->sign, prec, flags);\n        bf_mul_2exp(r, -2, BF_PREC_INF, BF_RNDZ);\n        return BF_ST_INEXACT;\n    }\n\n    /* small argument case: result = x+r(x) with r(x) = -x^3/3 +\n       O(X^5). We assume r(x) < 2^(3*EXP(x) - 1). */\n    if (a->expn < 0) {\n        slimb_t e;\n        e = sat_add(2 * a->expn, a->expn - 1);\n        if (e < a->expn - bf_max(prec + 2, a->len * LIMB_BITS + 2)) {\n            bf_set(r, a);\n            return bf_add_epsilon(r, r, e, 1 - a->sign, prec, flags);\n        }\n    }\n    \n    return bf_ziv_rounding(r, a, prec, flags, bf_atan_internal, (void *)FALSE);\n}\n\nstatic int bf_atan2_internal(bf_t *r, const bf_t *y, limb_t prec, void *opaque)\n{\n    bf_context_t *s = r->ctx;\n    const bf_t *x = opaque;\n    bf_t T_s, *T = &T_s;\n    limb_t prec1;\n    int ret;\n    \n    if (y->expn == BF_EXP_NAN || x->expn == BF_EXP_NAN) {\n        bf_set_nan(r);\n        return 0;\n    }\n\n    /* compute atan(y/x) assumming inf/inf = 1 and 0/0 = 0 */\n    bf_init(s, T);\n    prec1 = prec + 32;\n    if (y->expn == BF_EXP_INF && x->expn == BF_EXP_INF) {\n        bf_set_ui(T, 1);\n        T->sign = y->sign ^ x->sign;\n    } else if (y->expn == BF_EXP_ZERO && x->expn == BF_EXP_ZERO) {\n        bf_set_zero(T, y->sign ^ x->sign);\n    } else {\n        bf_div(T, y, x, prec1, BF_RNDF);\n    }\n    ret = bf_atan(r, T, prec1, BF_RNDF);\n\n    if (x->sign) {\n        /* if x < 0 (it includes -0), return sign(y)*pi + atan(y/x) */\n        bf_const_pi(T, prec1, BF_RNDF);\n        T->sign = y->sign;\n        bf_add(r, r, T, prec1, BF_RNDN);\n        ret |= BF_ST_INEXACT;\n    }\n\n    bf_delete(T);\n    return ret;\n}\n\nint bf_atan2(bf_t *r, const bf_t *y, const bf_t *x,\n             limb_t prec, bf_flags_t flags)\n{\n    return bf_ziv_rounding(r, y, prec, flags, bf_atan2_internal, (void *)x);\n}\n\nstatic int bf_asin_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)\n{\n    bf_context_t *s = r->ctx;\n    BOOL is_acos = (BOOL)(intptr_t)opaque;\n    bf_t T_s, *T = &T_s;\n    limb_t prec1, prec2;\n    \n    /* asin(x) = atan(x/sqrt(1-x^2)) \n       acos(x) = pi/2 - asin(x) */\n    prec1 = prec + 8;\n    /* increase the precision in x^2 to compensate the cancellation in\n       (1-x^2) if x is close to 1 */\n    /* XXX: use less precision when possible */\n    if (a->expn >= 0)\n        prec2 = BF_PREC_INF;\n    else\n        prec2 = prec1;\n    bf_init(s, T);\n    bf_mul(T, a, a, prec2, BF_RNDN);\n    bf_neg(T);\n    bf_add_si(T, T, 1, prec2, BF_RNDN);\n\n    bf_sqrt(r, T, prec1, BF_RNDN);\n    bf_div(T, a, r, prec1, BF_RNDN);\n    if (is_acos)\n        bf_neg(T);\n    bf_atan_internal(r, T, prec1, (void *)(intptr_t)is_acos);\n    bf_delete(T);\n    return BF_ST_INEXACT;\n}\n\nint bf_asin(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    int res;\n\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF) {\n            bf_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bf_set_zero(r, a->sign);\n            return 0;\n        }\n    }\n    bf_init(s, T);\n    bf_set_ui(T, 1);\n    res = bf_cmpu(a, T);\n    bf_delete(T);\n    if (res > 0) {\n        bf_set_nan(r);\n        return BF_ST_INVALID_OP;\n    }\n    \n    /* small argument case: result = x+r(x) with r(x) = x^3/6 +\n       O(X^5). We assume r(x) < 2^(3*EXP(x) - 2). */\n    if (a->expn < 0) {\n        slimb_t e;\n        e = sat_add(2 * a->expn, a->expn - 2);\n        if (e < a->expn - bf_max(prec + 2, a->len * LIMB_BITS + 2)) {\n            bf_set(r, a);\n            return bf_add_epsilon(r, r, e, a->sign, prec, flags);\n        }\n    }\n\n    return bf_ziv_rounding(r, a, prec, flags, bf_asin_internal, (void *)FALSE);\n}\n\nint bf_acos(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    int res;\n\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF) {\n            bf_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bf_const_pi(r, prec, flags);\n            bf_mul_2exp(r, -1, BF_PREC_INF, BF_RNDZ);\n            return BF_ST_INEXACT;\n        }\n    }\n    bf_init(s, T);\n    bf_set_ui(T, 1);\n    res = bf_cmpu(a, T);\n    bf_delete(T);\n    if (res > 0) {\n        bf_set_nan(r);\n        return BF_ST_INVALID_OP;\n    } else if (res == 0 && a->sign == 0) {\n        bf_set_zero(r, 0);\n        return 0;\n    }\n    \n    return bf_ziv_rounding(r, a, prec, flags, bf_asin_internal, (void *)TRUE);\n}\n\n/***************************************************************/\n/* decimal floating point numbers */\n\n#ifdef USE_BF_DEC\n\n#define adddq(r1, r0, a1, a0)                   \\\n    do {                                        \\\n        limb_t __t = r0;                        \\\n        r0 += (a0);                             \\\n        r1 += (a1) + (r0 < __t);                \\\n    } while (0)\n\n#define subdq(r1, r0, a1, a0)                   \\\n    do {                                        \\\n        limb_t __t = r0;                        \\\n        r0 -= (a0);                             \\\n        r1 -= (a1) + (r0 > __t);                \\\n    } while (0)\n\n#if LIMB_BITS == 64\n\n/* Note: we assume __int128 is available */\n#define muldq(r1, r0, a, b)                     \\\n    do {                                        \\\n        unsigned __int128 __t;                          \\\n        __t = (unsigned __int128)(a) * (unsigned __int128)(b);  \\\n        r0 = __t;                               \\\n        r1 = __t >> 64;                         \\\n    } while (0)\n\n#define divdq(q, r, a1, a0, b)                  \\\n    do {                                        \\\n        unsigned __int128 __t;                  \\\n        limb_t __b = (b);                       \\\n        __t = ((unsigned __int128)(a1) << 64) | (a0);   \\\n        q = __t / __b;                                  \\\n        r = __t % __b;                                  \\\n    } while (0)\n\n#else\n\n#define muldq(r1, r0, a, b)                     \\\n    do {                                        \\\n        uint64_t __t;                          \\\n        __t = (uint64_t)(a) * (uint64_t)(b);  \\\n        r0 = __t;                               \\\n        r1 = __t >> 32;                         \\\n    } while (0)\n\n#define divdq(q, r, a1, a0, b)                  \\\n    do {                                        \\\n        uint64_t __t;                  \\\n        limb_t __b = (b);                       \\\n        __t = ((uint64_t)(a1) << 32) | (a0);   \\\n        q = __t / __b;                                  \\\n        r = __t % __b;                                  \\\n    } while (0)\n\n#endif /* LIMB_BITS != 64 */\n\nstatic inline __maybe_unused limb_t shrd(limb_t low, limb_t high, long shift)\n{\n    if (shift != 0)\n        low = (low >> shift) | (high << (LIMB_BITS - shift));\n    return low;\n}\n\nstatic inline __maybe_unused limb_t shld(limb_t a1, limb_t a0, long shift)\n{\n    if (shift != 0)\n        return (a1 << shift) | (a0 >> (LIMB_BITS - shift));\n    else\n        return a1;\n}\n\n#if LIMB_DIGITS == 19\n\n/* WARNING: hardcoded for b = 1e19. It is assumed that:\n   0 <= a1 < 2^63 */\n#define divdq_base(q, r, a1, a0)\\\ndo {\\\n    uint64_t __a0, __a1, __t0, __t1, __b = BF_DEC_BASE; \\\n    __a0 = a0;\\\n    __a1 = a1;\\\n    __t0 = __a1;\\\n    __t0 = shld(__t0, __a0, 1);\\\n    muldq(q, __t1, __t0, UINT64_C(17014118346046923173)); \\\n    muldq(__t1, __t0, q, __b);\\\n    subdq(__a1, __a0, __t1, __t0);\\\n    subdq(__a1, __a0, 1, __b * 2);    \\\n    __t0 = (slimb_t)__a1 >> 1; \\\n    q += 2 + __t0;\\\n    adddq(__a1, __a0, 0, __b & __t0);\\\n    q += __a1;                  \\\n    __a0 += __b & __a1;           \\\n    r = __a0;\\\n} while(0)\n\n#elif LIMB_DIGITS == 9\n\n/* WARNING: hardcoded for b = 1e9. It is assumed that:\n   0 <= a1 < 2^29 */\n#define divdq_base(q, r, a1, a0)\\\ndo {\\\n    uint32_t __t0, __t1, __b = BF_DEC_BASE; \\\n    __t0 = a1;\\\n    __t1 = a0;\\\n    __t0 = (__t0 << 3) | (__t1 >> (32 - 3));    \\\n    muldq(q, __t1, __t0, 2305843009U);\\\n    r = a0 - q * __b;\\\n    __t1 = (r >= __b);\\\n    q += __t1;\\\n    if (__t1)\\\n        r -= __b;\\\n} while(0)\n\n#endif\n\n/* fast integer division by a fixed constant */\n\ntypedef struct FastDivData {\n    limb_t m1; /* multiplier */\n    int8_t shift1;\n    int8_t shift2;\n} FastDivData;\n\n/* From \"Division by Invariant Integers using Multiplication\" by\n   Torborn Granlund and Peter L. Montgomery */\n/* d must be != 0 */\nstatic inline __maybe_unused void fast_udiv_init(FastDivData *s, limb_t d)\n{\n    int l;\n    limb_t q, r, m1;\n    if (d == 1)\n        l = 0;\n    else\n        l = 64 - clz64(d - 1);\n    divdq(q, r, ((limb_t)1 << l) - d, 0, d);\n    (void)r;\n    m1 = q + 1;\n    //    printf(\"d=%lu l=%d m1=0x%016lx\\n\", d, l, m1);\n    s->m1 = m1;\n    s->shift1 = l;\n    if (s->shift1 > 1)\n        s->shift1 = 1;\n    s->shift2 = l - 1;\n    if (s->shift2 < 0)\n        s->shift2 = 0;\n}\n\nstatic inline limb_t fast_udiv(limb_t a, const FastDivData *s)\n{\n    limb_t t0, t1;\n    muldq(t1, t0, s->m1, a);\n    t0 = (a - t1) >> s->shift1;\n    return (t1 + t0) >> s->shift2;\n}\n\n/* contains 10^i */\nconst limb_t mp_pow_dec[LIMB_DIGITS + 1] = {\n    1U,\n    10U,\n    100U,\n    1000U,\n    10000U,\n    100000U,\n    1000000U,\n    10000000U,\n    100000000U,\n    1000000000U,\n#if LIMB_BITS == 64\n    10000000000U,\n    100000000000U,\n    1000000000000U,\n    10000000000000U,\n    100000000000000U,\n    1000000000000000U,\n    10000000000000000U,\n    100000000000000000U,\n    1000000000000000000U,\n    10000000000000000000U,\n#endif\n};\n\n/* precomputed from fast_udiv_init(10^i) */\nstatic const FastDivData mp_pow_div[LIMB_DIGITS + 1] = {\n#if LIMB_BITS == 32\n    { 0x00000001, 0, 0 },\n    { 0x9999999a, 1, 3 },\n    { 0x47ae147b, 1, 6 },\n    { 0x0624dd30, 1, 9 },\n    { 0xa36e2eb2, 1, 13 },\n    { 0x4f8b588f, 1, 16 },\n    { 0x0c6f7a0c, 1, 19 },\n    { 0xad7f29ac, 1, 23 },\n    { 0x5798ee24, 1, 26 },\n    { 0x12e0be83, 1, 29 },\n#else\n    { 0x0000000000000001, 0, 0 },\n    { 0x999999999999999a, 1, 3 },\n    { 0x47ae147ae147ae15, 1, 6 },\n    { 0x0624dd2f1a9fbe77, 1, 9 },\n    { 0xa36e2eb1c432ca58, 1, 13 },\n    { 0x4f8b588e368f0847, 1, 16 },\n    { 0x0c6f7a0b5ed8d36c, 1, 19 },\n    { 0xad7f29abcaf48579, 1, 23 },\n    { 0x5798ee2308c39dfa, 1, 26 },\n    { 0x12e0be826d694b2f, 1, 29 },\n    { 0xb7cdfd9d7bdbab7e, 1, 33 },\n    { 0x5fd7fe17964955fe, 1, 36 },\n    { 0x19799812dea11198, 1, 39 },\n    { 0xc25c268497681c27, 1, 43 },\n    { 0x6849b86a12b9b01f, 1, 46 },\n    { 0x203af9ee756159b3, 1, 49 },\n    { 0xcd2b297d889bc2b7, 1, 53 },\n    { 0x70ef54646d496893, 1, 56 },\n    { 0x2725dd1d243aba0f, 1, 59 },\n    { 0xd83c94fb6d2ac34d, 1, 63 },\n#endif\n};\n\n/* divide by 10^shift with 0 <= shift <= LIMB_DIGITS */\nstatic inline limb_t fast_shr_dec(limb_t a, int shift)\n{\n    return fast_udiv(a, &mp_pow_div[shift]);\n}\n\n/* division and remainder by 10^shift */\n#define fast_shr_rem_dec(q, r, a, shift) q = fast_shr_dec(a, shift), r = a - q * mp_pow_dec[shift]\n    \nlimb_t mp_add_dec(limb_t *res, const limb_t *op1, const limb_t *op2, \n                  mp_size_t n, limb_t carry)\n{\n    limb_t base = BF_DEC_BASE;\n    mp_size_t i;\n    limb_t k, a, v;\n\n    k=carry;\n    for(i=0;i<n;i++) {\n        /* XXX: reuse the trick in add_mod */\n        v = op1[i];\n        a = v + op2[i] + k - base;\n        k = a <= v;\n        if (!k) \n            a += base;\n        res[i]=a;\n    }\n    return k;\n}\n\nlimb_t mp_add_ui_dec(limb_t *tab, limb_t b, mp_size_t n)\n{\n    limb_t base = BF_DEC_BASE;\n    mp_size_t i;\n    limb_t k, a, v;\n\n    k=b;\n    for(i=0;i<n;i++) {\n        v = tab[i];\n        a = v + k - base;\n        k = a <= v;\n        if (!k) \n            a += base;\n        tab[i] = a;\n        if (k == 0)\n            break;\n    }\n    return k;\n}\n\nlimb_t mp_sub_dec(limb_t *res, const limb_t *op1, const limb_t *op2, \n                  mp_size_t n, limb_t carry)\n{\n    limb_t base = BF_DEC_BASE;\n    mp_size_t i;\n    limb_t k, v, a;\n\n    k=carry;\n    for(i=0;i<n;i++) {\n        v = op1[i];\n        a = v - op2[i] - k;\n        k = a > v;\n        if (k)\n            a += base;\n        res[i] = a;\n    }\n    return k;\n}\n\nlimb_t mp_sub_ui_dec(limb_t *tab, limb_t b, mp_size_t n)\n{\n    limb_t base = BF_DEC_BASE;\n    mp_size_t i;\n    limb_t k, v, a;\n    \n    k=b;\n    for(i=0;i<n;i++) {\n        v = tab[i];\n        a = v - k;\n        k = a > v;\n        if (k)\n            a += base;\n        tab[i]=a;\n        if (k == 0)\n            break;\n    }\n    return k;\n}\n\n/* taba[] = taba[] * b + l. 0 <= b, l <= base - 1. Return the high carry */\nlimb_t mp_mul1_dec(limb_t *tabr, const limb_t *taba, mp_size_t n, \n                   limb_t b, limb_t l)\n{\n    mp_size_t i;\n    limb_t t0, t1, r;\n\n    for(i = 0; i < n; i++) {\n        muldq(t1, t0, taba[i], b);\n        adddq(t1, t0, 0, l);\n        divdq_base(l, r, t1, t0);\n        tabr[i] = r;\n    }\n    return l;\n}\n\n/* tabr[] += taba[] * b. 0 <= b <= base - 1. Return the value to add\n   to the high word */\nlimb_t mp_add_mul1_dec(limb_t *tabr, const limb_t *taba, mp_size_t n,\n                       limb_t b)\n{\n    mp_size_t i;\n    limb_t l, t0, t1, r;\n\n    l = 0;\n    for(i = 0; i < n; i++) {\n        muldq(t1, t0, taba[i], b);\n        adddq(t1, t0, 0, l);\n        adddq(t1, t0, 0, tabr[i]);\n        divdq_base(l, r, t1, t0);\n        tabr[i] = r;\n    }\n    return l;\n}\n\n/* tabr[] -= taba[] * b. 0 <= b <= base - 1. Return the value to\n   substract to the high word. */\nlimb_t mp_sub_mul1_dec(limb_t *tabr, const limb_t *taba, mp_size_t n,\n                       limb_t b)\n{\n    limb_t base = BF_DEC_BASE;\n    mp_size_t i;\n    limb_t l, t0, t1, r, a, v, c;\n\n    /* XXX: optimize */\n    l = 0;\n    for(i = 0; i < n; i++) {\n        muldq(t1, t0, taba[i], b);\n        adddq(t1, t0, 0, l);\n        divdq_base(l, r, t1, t0);\n        v = tabr[i];\n        a = v - r;\n        c = a > v;\n        if (c)\n            a += base;\n        /* never bigger than base because r = 0 when l = base - 1 */\n        l += c;\n        tabr[i] = a;\n    }\n    return l;\n}\n\n/* size of the result : op1_size + op2_size. */\nvoid mp_mul_basecase_dec(limb_t *result, \n                         const limb_t *op1, mp_size_t op1_size, \n                         const limb_t *op2, mp_size_t op2_size) \n{\n    mp_size_t i;\n    limb_t r;\n    \n    result[op1_size] = mp_mul1_dec(result, op1, op1_size, op2[0], 0);\n\n    for(i=1;i<op2_size;i++) {\n        r = mp_add_mul1_dec(result + i, op1, op1_size, op2[i]);\n        result[i + op1_size] = r;\n    }\n}\n\n/* taba[] = (taba[] + r*base^na) / b. 0 <= b < base. 0 <= r <\n   b. Return the remainder. */\nlimb_t mp_div1_dec(limb_t *tabr, const limb_t *taba, mp_size_t na, \n                   limb_t b, limb_t r)\n{\n    limb_t base = BF_DEC_BASE;\n    mp_size_t i;\n    limb_t t0, t1, q;\n    int shift;\n\n#if (BF_DEC_BASE % 2) == 0\n    if (b == 2) {\n        limb_t base_div2;\n        /* Note: only works if base is even */\n        base_div2 = base >> 1;\n        if (r)\n            r = base_div2;\n        for(i = na - 1; i >= 0; i--) {\n            t0 = taba[i];\n            tabr[i] = (t0 >> 1) + r;\n            r = 0;\n            if (t0 & 1)\n                r = base_div2;\n        }\n        if (r)\n            r = 1;\n    } else \n#endif\n    if (na >= UDIV1NORM_THRESHOLD) {\n        shift = clz(b);\n        if (shift == 0) {\n            /* normalized case: b >= 2^(LIMB_BITS-1) */\n            limb_t b_inv;\n            b_inv = udiv1norm_init(b);\n            for(i = na - 1; i >= 0; i--) {\n                muldq(t1, t0, r, base);\n                adddq(t1, t0, 0, taba[i]);\n                q = udiv1norm(&r, t1, t0, b, b_inv);\n                tabr[i] = q;\n            }\n        } else {\n            limb_t b_inv;\n            b <<= shift;\n            b_inv = udiv1norm_init(b);\n            for(i = na - 1; i >= 0; i--) {\n                muldq(t1, t0, r, base);\n                adddq(t1, t0, 0, taba[i]);\n                t1 = (t1 << shift) | (t0 >> (LIMB_BITS - shift));\n                t0 <<= shift;\n                q = udiv1norm(&r, t1, t0, b, b_inv);\n                r >>= shift;\n                tabr[i] = q;\n            }\n        }\n    } else {\n        for(i = na - 1; i >= 0; i--) {\n            muldq(t1, t0, r, base);\n            adddq(t1, t0, 0, taba[i]);\n            divdq(q, r, t1, t0, b);\n            tabr[i] = q;\n        }\n    }\n    return r;\n}\n\nstatic __maybe_unused void mp_print_str_dec(const char *str,\n                                       const limb_t *tab, slimb_t n)\n{\n    slimb_t i;\n    printf(\"%s=\", str);\n    for(i = n - 1; i >= 0; i--) {\n        if (i != n - 1)\n            printf(\"_\");\n        printf(\"%0*\" PRIu_LIMB, LIMB_DIGITS, tab[i]);\n    }\n    printf(\"\\n\");\n}\n\nstatic __maybe_unused void mp_print_str_h_dec(const char *str,\n                                              const limb_t *tab, slimb_t n,\n                                              limb_t high)\n{\n    slimb_t i;\n    printf(\"%s=\", str);\n    printf(\"%0*\" PRIu_LIMB, LIMB_DIGITS, high);\n    for(i = n - 1; i >= 0; i--) {\n        printf(\"_\");\n        printf(\"%0*\" PRIu_LIMB, LIMB_DIGITS, tab[i]);\n    }\n    printf(\"\\n\");\n}\n\n//#define DEBUG_DIV_SLOW\n\n#define DIV_STATIC_ALLOC_LEN 16\n\n/* return q = a / b and r = a % b. \n\n   taba[na] must be allocated if tabb1[nb - 1] < B / 2.  tabb1[nb - 1]\n   must be != zero. na must be >= nb. 's' can be NULL if tabb1[nb - 1]\n   >= B / 2.\n\n   The remainder is is returned in taba and contains nb libms. tabq\n   contains na - nb + 1 limbs. No overlap is permitted.\n\n   Running time of the standard method: (na - nb + 1) * nb\n   Return 0 if OK, -1 if memory alloc error\n*/\n/* XXX: optimize */\nstatic int mp_div_dec(bf_context_t *s, limb_t *tabq,\n                      limb_t *taba, mp_size_t na, \n                      const limb_t *tabb1, mp_size_t nb)\n{\n    limb_t base = BF_DEC_BASE;\n    limb_t r, mult, t0, t1, a, c, q, v, *tabb;\n    mp_size_t i, j;\n    limb_t static_tabb[DIV_STATIC_ALLOC_LEN];\n    \n#ifdef DEBUG_DIV_SLOW\n    mp_print_str_dec(\"a\", taba, na);\n    mp_print_str_dec(\"b\", tabb1, nb);\n#endif\n\n    /* normalize tabb */\n    r = tabb1[nb - 1];\n    assert(r != 0);\n    i = na - nb;\n    if (r >= BF_DEC_BASE / 2) {\n        mult = 1;\n        tabb = (limb_t *)tabb1;\n        q = 1;\n        for(j = nb - 1; j >= 0; j--) {\n            if (taba[i + j] != tabb[j]) {\n                if (taba[i + j] < tabb[j])\n                    q = 0;\n                break;\n            }\n        }\n        tabq[i] = q;\n        if (q) {\n            mp_sub_dec(taba + i, taba + i, tabb, nb, 0);\n        }\n        i--;\n    } else {\n        mult = base / (r + 1);\n        if (likely(nb <= DIV_STATIC_ALLOC_LEN)) {\n            tabb = static_tabb;\n        } else {\n            tabb = bf_malloc(s, sizeof(limb_t) * nb);\n            if (!tabb)\n                return -1;\n        }\n        mp_mul1_dec(tabb, tabb1, nb, mult, 0);\n        taba[na] = mp_mul1_dec(taba, taba, na, mult, 0);\n    }\n\n#ifdef DEBUG_DIV_SLOW\n    printf(\"mult=\" FMT_LIMB \"\\n\", mult);\n    mp_print_str_dec(\"a_norm\", taba, na + 1);\n    mp_print_str_dec(\"b_norm\", tabb, nb);\n#endif\n\n    for(; i >= 0; i--) {\n        if (unlikely(taba[i + nb] >= tabb[nb - 1])) {\n            /* XXX: check if it is really possible */\n            q = base - 1;\n        } else {\n            muldq(t1, t0, taba[i + nb], base);\n            adddq(t1, t0, 0, taba[i + nb - 1]);\n            divdq(q, r, t1, t0, tabb[nb - 1]);\n        }\n        //        printf(\"i=%d q1=%ld\\n\", i, q);\n\n        r = mp_sub_mul1_dec(taba + i, tabb, nb, q);\n        //        mp_dump(\"r1\", taba + i, nb, bd);\n        //        printf(\"r2=%ld\\n\", r);\n\n        v = taba[i + nb];\n        a = v - r;\n        c = a > v;\n        if (c)\n            a += base;\n        taba[i + nb] = a;\n\n        if (c != 0) {\n            /* negative result */\n            for(;;) {\n                q--;\n                c = mp_add_dec(taba + i, taba + i, tabb, nb, 0);\n                /* propagate carry and test if positive result */\n                if (c != 0) {\n                    if (++taba[i + nb] == base) {\n                        break;\n                    }\n                }\n            }\n        }\n        tabq[i] = q;\n    }\n\n#ifdef DEBUG_DIV_SLOW\n    mp_print_str_dec(\"q\", tabq, na - nb + 1);\n    mp_print_str_dec(\"r\", taba, nb);\n#endif\n\n    /* remove the normalization */\n    if (mult != 1) {\n        mp_div1_dec(taba, taba, nb, mult, 0);\n        if (unlikely(tabb != static_tabb))\n            bf_free(s, tabb);\n    }\n    return 0;\n}\n\n/* divide by 10^shift */\nstatic limb_t mp_shr_dec(limb_t *tab_r, const limb_t *tab, mp_size_t n, \n                         limb_t shift, limb_t high)\n{\n    mp_size_t i;\n    limb_t l, a, q, r;\n\n    assert(shift >= 1 && shift < LIMB_DIGITS);\n    l = high;\n    for(i = n - 1; i >= 0; i--) {\n        a = tab[i];\n        fast_shr_rem_dec(q, r, a, shift);\n        tab_r[i] = q + l * mp_pow_dec[LIMB_DIGITS - shift];\n        l = r;\n    }\n    return l;\n}\n\n/* multiply by 10^shift */\nstatic limb_t mp_shl_dec(limb_t *tab_r, const limb_t *tab, mp_size_t n, \n                         limb_t shift, limb_t low)\n{\n    mp_size_t i;\n    limb_t l, a, q, r;\n\n    assert(shift >= 1 && shift < LIMB_DIGITS);\n    l = low;\n    for(i = 0; i < n; i++) {\n        a = tab[i];\n        fast_shr_rem_dec(q, r, a, LIMB_DIGITS - shift);\n        tab_r[i] = r * mp_pow_dec[shift] + l;\n        l = q;\n    }\n    return l;\n}\n\nstatic limb_t mp_sqrtrem2_dec(limb_t *tabs, limb_t *taba)\n{\n    int k;\n    dlimb_t a, b, r;\n    limb_t taba1[2], s, r0, r1;\n\n    /* convert to binary and normalize */\n    a = (dlimb_t)taba[1] * BF_DEC_BASE + taba[0];\n    k = clz(a >> LIMB_BITS) & ~1;\n    b = a << k;\n    taba1[0] = b;\n    taba1[1] = b >> LIMB_BITS;\n    mp_sqrtrem2(&s, taba1);\n    s >>= (k >> 1);\n    /* convert the remainder back to decimal */\n    r = a - (dlimb_t)s * (dlimb_t)s;\n    divdq_base(r1, r0, r >> LIMB_BITS, r);\n    taba[0] = r0;\n    tabs[0] = s;\n    return r1;\n}\n\n//#define DEBUG_SQRTREM_DEC\n\n/* tmp_buf must contain (n / 2 + 1 limbs) */\nstatic limb_t mp_sqrtrem_rec_dec(limb_t *tabs, limb_t *taba, limb_t n,\n                                 limb_t *tmp_buf)\n{\n    limb_t l, h, rh, ql, qh, c, i;\n    \n    if (n == 1)\n        return mp_sqrtrem2_dec(tabs, taba);\n#ifdef DEBUG_SQRTREM_DEC\n    mp_print_str_dec(\"a\", taba, 2 * n);\n#endif\n    l = n / 2;\n    h = n - l;\n    qh = mp_sqrtrem_rec_dec(tabs + l, taba + 2 * l, h, tmp_buf);\n#ifdef DEBUG_SQRTREM_DEC\n    mp_print_str_dec(\"s1\", tabs + l, h);\n    mp_print_str_h_dec(\"r1\", taba + 2 * l, h, qh);\n    mp_print_str_h_dec(\"r2\", taba + l, n, qh);\n#endif\n    \n    /* the remainder is in taba + 2 * l. Its high bit is in qh */\n    if (qh) {\n        mp_sub_dec(taba + 2 * l, taba + 2 * l, tabs + l, h, 0);\n    }\n    /* instead of dividing by 2*s, divide by s (which is normalized)\n       and update q and r */\n    mp_div_dec(NULL, tmp_buf, taba + l, n, tabs + l, h);\n    qh += tmp_buf[l];\n    for(i = 0; i < l; i++)\n        tabs[i] = tmp_buf[i];\n    ql = mp_div1_dec(tabs, tabs, l, 2, qh & 1);\n    qh = qh >> 1; /* 0 or 1 */\n    if (ql)\n        rh = mp_add_dec(taba + l, taba + l, tabs + l, h, 0);\n    else\n        rh = 0;\n#ifdef DEBUG_SQRTREM_DEC\n    mp_print_str_h_dec(\"q\", tabs, l, qh);\n    mp_print_str_h_dec(\"u\", taba + l, h, rh);\n#endif\n    \n    mp_add_ui_dec(tabs + l, qh, h);\n#ifdef DEBUG_SQRTREM_DEC\n    mp_print_str_dec(\"s2\", tabs, n);\n#endif\n    \n    /* q = qh, tabs[l - 1 ... 0], r = taba[n - 1 ... l] */\n    /* subtract q^2. if qh = 1 then q = B^l, so we can take shortcuts */\n    if (qh) {\n        c = qh;\n    } else {\n        mp_mul_basecase_dec(taba + n, tabs, l, tabs, l);\n        c = mp_sub_dec(taba, taba, taba + n, 2 * l, 0);\n    }\n    rh -= mp_sub_ui_dec(taba + 2 * l, c, n - 2 * l);\n    if ((slimb_t)rh < 0) {\n        mp_sub_ui_dec(tabs, 1, n);\n        rh += mp_add_mul1_dec(taba, tabs, n, 2);\n        rh += mp_add_ui_dec(taba, 1, n);\n    }\n    return rh;\n}\n\n/* 'taba' has 2*n limbs with n >= 1 and taba[2*n-1] >= B/4. Return (s,\n   r) with s=floor(sqrt(a)) and r=a-s^2. 0 <= r <= 2 * s. tabs has n\n   limbs. r is returned in the lower n limbs of taba. Its r[n] is the\n   returned value of the function. */\nint mp_sqrtrem_dec(bf_context_t *s, limb_t *tabs, limb_t *taba, limb_t n)\n{\n    limb_t tmp_buf1[8];\n    limb_t *tmp_buf;\n    mp_size_t n2;\n    n2 = n / 2 + 1;\n    if (n2 <= countof(tmp_buf1)) {\n        tmp_buf = tmp_buf1;\n    } else {\n        tmp_buf = bf_malloc(s, sizeof(limb_t) * n2);\n        if (!tmp_buf)\n            return -1;\n    }\n    taba[n] = mp_sqrtrem_rec_dec(tabs, taba, n, tmp_buf);\n    if (tmp_buf != tmp_buf1)\n        bf_free(s, tmp_buf);\n    return 0;\n}\n\n/* return the number of leading zero digits, from 0 to LIMB_DIGITS */\nstatic int clz_dec(limb_t a)\n{\n    if (a == 0)\n        return LIMB_DIGITS;\n    switch(LIMB_BITS - 1 - clz(a)) {\n    case 0: /* 1-1 */\n        return LIMB_DIGITS - 1;\n    case 1: /* 2-3 */\n        return LIMB_DIGITS - 1;\n    case 2: /* 4-7 */\n        return LIMB_DIGITS - 1;\n    case 3: /* 8-15 */\n        if (a < 10)\n            return LIMB_DIGITS - 1;\n        else\n            return LIMB_DIGITS - 2;\n    case 4: /* 16-31 */\n        return LIMB_DIGITS - 2;\n    case 5: /* 32-63 */\n        return LIMB_DIGITS - 2;\n    case 6: /* 64-127 */\n        if (a < 100)\n            return LIMB_DIGITS - 2;\n        else\n            return LIMB_DIGITS - 3;\n    case 7: /* 128-255 */\n        return LIMB_DIGITS - 3;\n    case 8: /* 256-511 */\n        return LIMB_DIGITS - 3;\n    case 9: /* 512-1023 */\n        if (a < 1000)\n            return LIMB_DIGITS - 3;\n        else\n            return LIMB_DIGITS - 4;\n    case 10: /* 1024-2047 */\n        return LIMB_DIGITS - 4;\n    case 11: /* 2048-4095 */\n        return LIMB_DIGITS - 4;\n    case 12: /* 4096-8191 */\n        return LIMB_DIGITS - 4;\n    case 13: /* 8192-16383 */\n        if (a < 10000)\n            return LIMB_DIGITS - 4;\n        else\n            return LIMB_DIGITS - 5;\n    case 14: /* 16384-32767 */\n        return LIMB_DIGITS - 5;\n    case 15: /* 32768-65535 */\n        return LIMB_DIGITS - 5;\n    case 16: /* 65536-131071 */\n        if (a < 100000)\n            return LIMB_DIGITS - 5;\n        else\n            return LIMB_DIGITS - 6;\n    case 17: /* 131072-262143 */\n        return LIMB_DIGITS - 6;\n    case 18: /* 262144-524287 */\n        return LIMB_DIGITS - 6;\n    case 19: /* 524288-1048575 */\n        if (a < 1000000)\n            return LIMB_DIGITS - 6;\n        else\n            return LIMB_DIGITS - 7;\n    case 20: /* 1048576-2097151 */\n        return LIMB_DIGITS - 7;\n    case 21: /* 2097152-4194303 */\n        return LIMB_DIGITS - 7;\n    case 22: /* 4194304-8388607 */\n        return LIMB_DIGITS - 7;\n    case 23: /* 8388608-16777215 */\n        if (a < 10000000)\n            return LIMB_DIGITS - 7;\n        else\n            return LIMB_DIGITS - 8;\n    case 24: /* 16777216-33554431 */\n        return LIMB_DIGITS - 8;\n    case 25: /* 33554432-67108863 */\n        return LIMB_DIGITS - 8;\n    case 26: /* 67108864-134217727 */\n        if (a < 100000000)\n            return LIMB_DIGITS - 8;\n        else\n            return LIMB_DIGITS - 9;\n#if LIMB_BITS == 64\n    case 27: /* 134217728-268435455 */\n        return LIMB_DIGITS - 9;\n    case 28: /* 268435456-536870911 */\n        return LIMB_DIGITS - 9;\n    case 29: /* 536870912-1073741823 */\n        if (a < 1000000000)\n            return LIMB_DIGITS - 9;\n        else\n            return LIMB_DIGITS - 10;\n    case 30: /* 1073741824-2147483647 */\n        return LIMB_DIGITS - 10;\n    case 31: /* 2147483648-4294967295 */\n        return LIMB_DIGITS - 10;\n    case 32: /* 4294967296-8589934591 */\n        return LIMB_DIGITS - 10;\n    case 33: /* 8589934592-17179869183 */\n        if (a < 10000000000)\n            return LIMB_DIGITS - 10;\n        else\n            return LIMB_DIGITS - 11;\n    case 34: /* 17179869184-34359738367 */\n        return LIMB_DIGITS - 11;\n    case 35: /* 34359738368-68719476735 */\n        return LIMB_DIGITS - 11;\n    case 36: /* 68719476736-137438953471 */\n        if (a < 100000000000)\n            return LIMB_DIGITS - 11;\n        else\n            return LIMB_DIGITS - 12;\n    case 37: /* 137438953472-274877906943 */\n        return LIMB_DIGITS - 12;\n    case 38: /* 274877906944-549755813887 */\n        return LIMB_DIGITS - 12;\n    case 39: /* 549755813888-1099511627775 */\n        if (a < 1000000000000)\n            return LIMB_DIGITS - 12;\n        else\n            return LIMB_DIGITS - 13;\n    case 40: /* 1099511627776-2199023255551 */\n        return LIMB_DIGITS - 13;\n    case 41: /* 2199023255552-4398046511103 */\n        return LIMB_DIGITS - 13;\n    case 42: /* 4398046511104-8796093022207 */\n        return LIMB_DIGITS - 13;\n    case 43: /* 8796093022208-17592186044415 */\n        if (a < 10000000000000)\n            return LIMB_DIGITS - 13;\n        else\n            return LIMB_DIGITS - 14;\n    case 44: /* 17592186044416-35184372088831 */\n        return LIMB_DIGITS - 14;\n    case 45: /* 35184372088832-70368744177663 */\n        return LIMB_DIGITS - 14;\n    case 46: /* 70368744177664-140737488355327 */\n        if (a < 100000000000000)\n            return LIMB_DIGITS - 14;\n        else\n            return LIMB_DIGITS - 15;\n    case 47: /* 140737488355328-281474976710655 */\n        return LIMB_DIGITS - 15;\n    case 48: /* 281474976710656-562949953421311 */\n        return LIMB_DIGITS - 15;\n    case 49: /* 562949953421312-1125899906842623 */\n        if (a < 1000000000000000)\n            return LIMB_DIGITS - 15;\n        else\n            return LIMB_DIGITS - 16;\n    case 50: /* 1125899906842624-2251799813685247 */\n        return LIMB_DIGITS - 16;\n    case 51: /* 2251799813685248-4503599627370495 */\n        return LIMB_DIGITS - 16;\n    case 52: /* 4503599627370496-9007199254740991 */\n        return LIMB_DIGITS - 16;\n    case 53: /* 9007199254740992-18014398509481983 */\n        if (a < 10000000000000000)\n            return LIMB_DIGITS - 16;\n        else\n            return LIMB_DIGITS - 17;\n    case 54: /* 18014398509481984-36028797018963967 */\n        return LIMB_DIGITS - 17;\n    case 55: /* 36028797018963968-72057594037927935 */\n        return LIMB_DIGITS - 17;\n    case 56: /* 72057594037927936-144115188075855871 */\n        if (a < 100000000000000000)\n            return LIMB_DIGITS - 17;\n        else\n            return LIMB_DIGITS - 18;\n    case 57: /* 144115188075855872-288230376151711743 */\n        return LIMB_DIGITS - 18;\n    case 58: /* 288230376151711744-576460752303423487 */\n        return LIMB_DIGITS - 18;\n    case 59: /* 576460752303423488-1152921504606846975 */\n        if (a < 1000000000000000000)\n            return LIMB_DIGITS - 18;\n        else\n            return LIMB_DIGITS - 19;\n#endif\n    default:\n        return 0;\n    }\n}\n\n/* for debugging */\nvoid bfdec_print_str(const char *str, const bfdec_t *a)\n{\n    slimb_t i;\n    printf(\"%s=\", str);\n\n    if (a->expn == BF_EXP_NAN) {\n        printf(\"NaN\");\n    } else {\n        if (a->sign)\n            putchar('-');\n        if (a->expn == BF_EXP_ZERO) {\n            putchar('0');\n        } else if (a->expn == BF_EXP_INF) {\n            printf(\"Inf\");\n        } else {\n            printf(\"0.\");\n            for(i = a->len - 1; i >= 0; i--)\n                printf(\"%0*\" PRIu_LIMB, LIMB_DIGITS, a->tab[i]);\n            printf(\"e%\" PRId_LIMB, a->expn);\n        }\n    }\n    printf(\"\\n\");\n}\n\n/* return != 0 if one digit between 0 and bit_pos inclusive is not zero. */\nstatic inline limb_t scan_digit_nz(const bfdec_t *r, slimb_t bit_pos)\n{\n    slimb_t pos;\n    limb_t v, q;\n    int shift;\n\n    if (bit_pos < 0)\n        return 0;\n    pos = (limb_t)bit_pos / LIMB_DIGITS;\n    shift = (limb_t)bit_pos % LIMB_DIGITS;\n    fast_shr_rem_dec(q, v, r->tab[pos], shift + 1);\n    (void)q;\n    if (v != 0)\n        return 1;\n    pos--;\n    while (pos >= 0) {\n        if (r->tab[pos] != 0)\n            return 1;\n        pos--;\n    }\n    return 0;\n}\n\nstatic limb_t get_digit(const limb_t *tab, limb_t len, slimb_t pos)\n{\n    slimb_t i;\n    int shift;\n    i = floor_div(pos, LIMB_DIGITS);\n    if (i < 0 || i >= len)\n        return 0;\n    shift = pos - i * LIMB_DIGITS;\n    return fast_shr_dec(tab[i], shift) % 10;\n}\n\n#if 0\nstatic limb_t get_digits(const limb_t *tab, limb_t len, slimb_t pos)\n{\n    limb_t a0, a1;\n    int shift;\n    slimb_t i;\n    \n    i = floor_div(pos, LIMB_DIGITS);\n    shift = pos - i * LIMB_DIGITS;\n    if (i >= 0 && i < len)\n        a0 = tab[i];\n    else\n        a0 = 0;\n    if (shift == 0) {\n        return a0;\n    } else {\n        i++;\n        if (i >= 0 && i < len)\n            a1 = tab[i];\n        else\n            a1 = 0;\n        return fast_shr_dec(a0, shift) +\n            fast_urem(a1, &mp_pow_div[LIMB_DIGITS - shift]) *\n            mp_pow_dec[shift];\n    }\n}\n#endif\n\n/* return the addend for rounding. Note that prec can be <= 0 for bf_rint() */\nstatic int bfdec_get_rnd_add(int *pret, const bfdec_t *r, limb_t l,\n                             slimb_t prec, int rnd_mode)\n{\n    int add_one, inexact;\n    limb_t digit1, digit0;\n    \n    //    bfdec_print_str(\"get_rnd_add\", r);\n    if (rnd_mode == BF_RNDF) {\n        digit0 = 1; /* faithful rounding does not honor the INEXACT flag */\n    } else {\n        /* starting limb for bit 'prec + 1' */\n        digit0 = scan_digit_nz(r, l * LIMB_DIGITS - 1 - bf_max(0, prec + 1));\n    }\n\n    /* get the digit at 'prec' */\n    digit1 = get_digit(r->tab, l, l * LIMB_DIGITS - 1 - prec);\n    inexact = (digit1 | digit0) != 0;\n    \n    add_one = 0;\n    switch(rnd_mode) {\n    case BF_RNDZ:\n        break;\n    case BF_RNDN:\n        if (digit1 == 5) {\n            if (digit0) {\n                add_one = 1;\n            } else {\n                /* round to even */\n                add_one =\n                    get_digit(r->tab, l, l * LIMB_DIGITS - 1 - (prec - 1)) & 1;\n            }\n        } else if (digit1 > 5) {\n            add_one = 1;\n        }\n        break;\n    case BF_RNDD:\n    case BF_RNDU:\n        if (r->sign == (rnd_mode == BF_RNDD))\n            add_one = inexact;\n        break;\n    case BF_RNDNA:\n    case BF_RNDF:\n        add_one = (digit1 >= 5);\n        break;\n    case BF_RNDA:\n        add_one = inexact;\n        break;\n    default:\n        abort();\n    }\n    \n    if (inexact)\n        *pret |= BF_ST_INEXACT;\n    return add_one;\n}\n\n/* round to prec1 bits assuming 'r' is non zero and finite. 'r' is\n   assumed to have length 'l' (1 <= l <= r->len). prec1 can be\n   BF_PREC_INF. BF_FLAG_SUBNORMAL is not supported. Cannot fail with\n   BF_ST_MEM_ERROR.\n */\nstatic int __bfdec_round(bfdec_t *r, limb_t prec1, bf_flags_t flags, limb_t l)\n{\n    int shift, add_one, rnd_mode, ret;\n    slimb_t i, bit_pos, pos, e_min, e_max, e_range, prec;\n\n    /* XXX: align to IEEE 754 2008 for decimal numbers ? */\n    e_range = (limb_t)1 << (bf_get_exp_bits(flags) - 1);\n    e_min = -e_range + 3;\n    e_max = e_range;\n    \n    if (flags & BF_FLAG_RADPNT_PREC) {\n        /* 'prec' is the precision after the decimal point */\n        if (prec1 != BF_PREC_INF)\n            prec = r->expn + prec1;\n        else\n            prec = prec1;\n    } else if (unlikely(r->expn < e_min) && (flags & BF_FLAG_SUBNORMAL)) {\n        /* restrict the precision in case of potentially subnormal\n           result */\n        assert(prec1 != BF_PREC_INF);\n        prec = prec1 - (e_min - r->expn);\n    } else {\n        prec = prec1;\n    }\n    \n    /* round to prec bits */\n    rnd_mode = flags & BF_RND_MASK;\n    ret = 0;\n    add_one = bfdec_get_rnd_add(&ret, r, l, prec, rnd_mode);\n    \n    if (prec <= 0) {\n        if (add_one) {\n            bfdec_resize(r, 1); /* cannot fail because r is non zero */\n            r->tab[0] = BF_DEC_BASE / 10;\n            r->expn += 1 - prec;\n            ret |= BF_ST_UNDERFLOW | BF_ST_INEXACT;\n            return ret;\n        } else {\n            goto underflow;\n        }\n    } else if (add_one) {\n        limb_t carry;\n        \n        /* add one starting at digit 'prec - 1' */\n        bit_pos = l * LIMB_DIGITS - 1 - (prec - 1);\n        pos = bit_pos / LIMB_DIGITS;\n        carry = mp_pow_dec[bit_pos % LIMB_DIGITS];\n        carry = mp_add_ui_dec(r->tab + pos, carry, l - pos);\n        if (carry) {\n            /* shift right by one digit */\n            mp_shr_dec(r->tab + pos, r->tab + pos, l - pos, 1, 1);\n            r->expn++;\n        }\n    }\n    \n    /* check underflow */\n    if (unlikely(r->expn < e_min)) {\n        if (flags & BF_FLAG_SUBNORMAL) {\n            /* if inexact, also set the underflow flag */\n            if (ret & BF_ST_INEXACT)\n                ret |= BF_ST_UNDERFLOW;\n        } else {\n        underflow:\n            bfdec_set_zero(r, r->sign);\n            ret |= BF_ST_UNDERFLOW | BF_ST_INEXACT;\n            return ret;\n        }\n    }\n    \n    /* check overflow */\n    if (unlikely(r->expn > e_max)) {\n        bfdec_set_inf(r, r->sign);\n        ret |= BF_ST_OVERFLOW | BF_ST_INEXACT;\n        return ret;\n    }\n    \n    /* keep the bits starting at 'prec - 1' */\n    bit_pos = l * LIMB_DIGITS - 1 - (prec - 1);\n    i = floor_div(bit_pos, LIMB_DIGITS);\n    if (i >= 0) {\n        shift = smod(bit_pos, LIMB_DIGITS);\n        if (shift != 0) {\n            r->tab[i] = fast_shr_dec(r->tab[i], shift) *\n                mp_pow_dec[shift];\n        }\n    } else {\n        i = 0;\n    }\n    /* remove trailing zeros */\n    while (r->tab[i] == 0)\n        i++;\n    if (i > 0) {\n        l -= i;\n        memmove(r->tab, r->tab + i, l * sizeof(limb_t));\n    }\n    bfdec_resize(r, l); /* cannot fail */\n    return ret;\n}\n\n/* Cannot fail with BF_ST_MEM_ERROR. */\nint bfdec_round(bfdec_t *r, limb_t prec, bf_flags_t flags)\n{\n    if (r->len == 0)\n        return 0;\n    return __bfdec_round(r, prec, flags, r->len);\n}\n\n/* 'r' must be a finite number. Cannot fail with BF_ST_MEM_ERROR.  */\nint bfdec_normalize_and_round(bfdec_t *r, limb_t prec1, bf_flags_t flags)\n{\n    limb_t l, v;\n    int shift, ret;\n    \n    //    bfdec_print_str(\"bf_renorm\", r);\n    l = r->len;\n    while (l > 0 && r->tab[l - 1] == 0)\n        l--;\n    if (l == 0) {\n        /* zero */\n        r->expn = BF_EXP_ZERO;\n        bfdec_resize(r, 0); /* cannot fail */\n        ret = 0;\n    } else {\n        r->expn -= (r->len - l) * LIMB_DIGITS;\n        /* shift to have the MSB set to '1' */\n        v = r->tab[l - 1];\n        shift = clz_dec(v);\n        if (shift != 0) {\n            mp_shl_dec(r->tab, r->tab, l, shift, 0);\n            r->expn -= shift;\n        }\n        ret = __bfdec_round(r, prec1, flags, l);\n    }\n    //    bf_print_str(\"r_final\", r);\n    return ret;\n}\n\nint bfdec_set_ui(bfdec_t *r, uint64_t v)\n{\n#if LIMB_BITS == 32\n    if (v >= BF_DEC_BASE * BF_DEC_BASE) {\n        if (bfdec_resize(r, 3))\n            goto fail;\n        r->tab[0] = v % BF_DEC_BASE;\n        v /= BF_DEC_BASE;\n        r->tab[1] = v % BF_DEC_BASE;\n        r->tab[2] = v / BF_DEC_BASE;\n        r->expn = 3 * LIMB_DIGITS;\n    } else\n#endif\n    if (v >= BF_DEC_BASE) {\n        if (bfdec_resize(r, 2))\n            goto fail;\n        r->tab[0] = v % BF_DEC_BASE;\n        r->tab[1] = v / BF_DEC_BASE;\n        r->expn = 2 * LIMB_DIGITS;\n    } else {\n        if (bfdec_resize(r, 1))\n            goto fail;\n        r->tab[0] = v;\n        r->expn = LIMB_DIGITS;\n    }\n    r->sign = 0;\n    return bfdec_normalize_and_round(r, BF_PREC_INF, 0);\n fail:\n    bfdec_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\nint bfdec_set_si(bfdec_t *r, int64_t v)\n{\n    int ret;\n    if (v < 0) {\n        ret = bfdec_set_ui(r, -v);\n        r->sign = 1;\n    } else {\n        ret = bfdec_set_ui(r, v);\n    }\n    return ret;\n}\n\nstatic int bfdec_add_internal(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags, int b_neg)\n{\n    bf_context_t *s = r->ctx;\n    int is_sub, cmp_res, a_sign, b_sign, ret;\n\n    a_sign = a->sign;\n    b_sign = b->sign ^ b_neg;\n    is_sub = a_sign ^ b_sign;\n    cmp_res = bfdec_cmpu(a, b);\n    if (cmp_res < 0) {\n        const bfdec_t *tmp;\n        tmp = a;\n        a = b;\n        b = tmp;\n        a_sign = b_sign; /* b_sign is never used later */\n    }\n    /* abs(a) >= abs(b) */\n    if (cmp_res == 0 && is_sub && a->expn < BF_EXP_INF) {\n        /* zero result */\n        bfdec_set_zero(r, (flags & BF_RND_MASK) == BF_RNDD);\n        ret = 0;\n    } else if (a->len == 0 || b->len == 0) {\n        ret = 0;\n        if (a->expn >= BF_EXP_INF) {\n            if (a->expn == BF_EXP_NAN) {\n                /* at least one operand is NaN */\n                bfdec_set_nan(r);\n                ret = 0;\n            } else if (b->expn == BF_EXP_INF && is_sub) {\n                /* infinities with different signs */\n                bfdec_set_nan(r);\n                ret = BF_ST_INVALID_OP;\n            } else {\n                bfdec_set_inf(r, a_sign);\n            }\n        } else {\n            /* at least one zero and not subtract */\n            if (bfdec_set(r, a))\n                return BF_ST_MEM_ERROR;\n            r->sign = a_sign;\n            goto renorm;\n        }\n    } else {\n        slimb_t d, a_offset, b_offset, i, r_len;\n        limb_t carry;\n        limb_t *b1_tab;\n        int b_shift;\n        mp_size_t b1_len;\n        \n        d = a->expn - b->expn;\n\n        /* XXX: not efficient in time and memory if the precision is\n           not infinite */\n        r_len = bf_max(a->len, b->len + (d + LIMB_DIGITS - 1) / LIMB_DIGITS);\n        if (bfdec_resize(r, r_len))\n            goto fail;\n        r->sign = a_sign;\n        r->expn = a->expn;\n\n        a_offset = r_len - a->len;\n        for(i = 0; i < a_offset; i++)\n            r->tab[i] = 0;\n        for(i = 0; i < a->len; i++)\n            r->tab[a_offset + i] = a->tab[i];\n        \n        b_shift = d % LIMB_DIGITS;\n        if (b_shift == 0) {\n            b1_len = b->len;\n            b1_tab = (limb_t *)b->tab;\n        } else {\n            b1_len = b->len + 1;\n            b1_tab = bf_malloc(s, sizeof(limb_t) * b1_len);\n            if (!b1_tab)\n                goto fail;\n            b1_tab[0] = mp_shr_dec(b1_tab + 1, b->tab, b->len, b_shift, 0) *\n                mp_pow_dec[LIMB_DIGITS - b_shift];\n        }\n        b_offset = r_len - (b->len + (d + LIMB_DIGITS - 1) / LIMB_DIGITS);\n        \n        if (is_sub) {\n            carry = mp_sub_dec(r->tab + b_offset, r->tab + b_offset,\n                               b1_tab, b1_len, 0);\n            if (carry != 0) {\n                carry = mp_sub_ui_dec(r->tab + b_offset + b1_len, carry,\n                                      r_len - (b_offset + b1_len));\n                assert(carry == 0);\n            }\n        } else {\n            carry = mp_add_dec(r->tab + b_offset, r->tab + b_offset,\n                               b1_tab, b1_len, 0);\n            if (carry != 0) {\n                carry = mp_add_ui_dec(r->tab + b_offset + b1_len, carry,\n                                      r_len - (b_offset + b1_len));\n            }\n            if (carry != 0) {\n                if (bfdec_resize(r, r_len + 1)) {\n                    if (b_shift != 0)\n                        bf_free(s, b1_tab);\n                    goto fail;\n                }\n                r->tab[r_len] = 1;\n                r->expn += LIMB_DIGITS;\n            }\n        }\n        if (b_shift != 0)\n            bf_free(s, b1_tab);\n    renorm:\n        ret = bfdec_normalize_and_round(r, prec, flags);\n    }\n    return ret;\n fail:\n    bfdec_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\nstatic int __bfdec_add(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n                     bf_flags_t flags)\n{\n    return bfdec_add_internal(r, a, b, prec, flags, 0);\n}\n\nstatic int __bfdec_sub(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n                     bf_flags_t flags)\n{\n    return bfdec_add_internal(r, a, b, prec, flags, 1);\n}\n\nint bfdec_add(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags)\n{\n    return bf_op2((bf_t *)r, (bf_t *)a, (bf_t *)b, prec, flags,\n                  (bf_op2_func_t *)__bfdec_add);\n}\n\nint bfdec_sub(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags)\n{\n    return bf_op2((bf_t *)r, (bf_t *)a, (bf_t *)b, prec, flags,\n                  (bf_op2_func_t *)__bfdec_sub);\n}\n\nint bfdec_mul(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags)\n{\n    int ret, r_sign;\n\n    if (a->len < b->len) {\n        const bfdec_t *tmp = a;\n        a = b;\n        b = tmp;\n    }\n    r_sign = a->sign ^ b->sign;\n    /* here b->len <= a->len */\n    if (b->len == 0) {\n        if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {\n            bfdec_set_nan(r);\n            ret = 0;\n        } else if (a->expn == BF_EXP_INF || b->expn == BF_EXP_INF) {\n            if ((a->expn == BF_EXP_INF && b->expn == BF_EXP_ZERO) ||\n                (a->expn == BF_EXP_ZERO && b->expn == BF_EXP_INF)) {\n                bfdec_set_nan(r);\n                ret = BF_ST_INVALID_OP;\n            } else {\n                bfdec_set_inf(r, r_sign);\n                ret = 0;\n            }\n        } else {\n            bfdec_set_zero(r, r_sign);\n            ret = 0;\n        }\n    } else {\n        bfdec_t tmp, *r1 = NULL;\n        limb_t a_len, b_len;\n        limb_t *a_tab, *b_tab;\n            \n        a_len = a->len;\n        b_len = b->len;\n        a_tab = a->tab;\n        b_tab = b->tab;\n        \n        if (r == a || r == b) {\n            bfdec_init(r->ctx, &tmp);\n            r1 = r;\n            r = &tmp;\n        }\n        if (bfdec_resize(r, a_len + b_len)) {\n            bfdec_set_nan(r);\n            ret = BF_ST_MEM_ERROR;\n            goto done;\n        }\n        mp_mul_basecase_dec(r->tab, a_tab, a_len, b_tab, b_len);\n        r->sign = r_sign;\n        r->expn = a->expn + b->expn;\n        ret = bfdec_normalize_and_round(r, prec, flags);\n    done:\n        if (r == &tmp)\n            bfdec_move(r1, &tmp);\n    }\n    return ret;\n}\n\nint bfdec_mul_si(bfdec_t *r, const bfdec_t *a, int64_t b1, limb_t prec,\n                 bf_flags_t flags)\n{\n    bfdec_t b;\n    int ret;\n    bfdec_init(r->ctx, &b);\n    ret = bfdec_set_si(&b, b1);\n    ret |= bfdec_mul(r, a, &b, prec, flags);\n    bfdec_delete(&b);\n    return ret;\n}\n\nint bfdec_add_si(bfdec_t *r, const bfdec_t *a, int64_t b1, limb_t prec,\n                 bf_flags_t flags)\n{\n    bfdec_t b;\n    int ret;\n    \n    bfdec_init(r->ctx, &b);\n    ret = bfdec_set_si(&b, b1);\n    ret |= bfdec_add(r, a, &b, prec, flags);\n    bfdec_delete(&b);\n    return ret;\n}\n\nstatic int __bfdec_div(bfdec_t *r, const bfdec_t *a, const bfdec_t *b,\n                       limb_t prec, bf_flags_t flags)\n{\n    int ret, r_sign;\n    limb_t n, nb, precl;\n    \n    r_sign = a->sign ^ b->sign;\n    if (a->expn >= BF_EXP_INF || b->expn >= BF_EXP_INF) {\n        if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {\n            bfdec_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF && b->expn == BF_EXP_INF) {\n            bfdec_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else if (a->expn == BF_EXP_INF) {\n            bfdec_set_inf(r, r_sign);\n            return 0;\n        } else {\n            bfdec_set_zero(r, r_sign);\n            return 0;\n        }\n    } else if (a->expn == BF_EXP_ZERO) {\n        if (b->expn == BF_EXP_ZERO) {\n            bfdec_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bfdec_set_zero(r, r_sign);\n            return 0;\n        }\n    } else if (b->expn == BF_EXP_ZERO) {\n        bfdec_set_inf(r, r_sign);\n        return BF_ST_DIVIDE_ZERO;\n    }\n\n    nb = b->len;\n    if (prec == BF_PREC_INF) {\n        /* infinite precision: return BF_ST_INVALID_OP if not an exact\n           result */\n        /* XXX: check */\n        precl = nb + 1;\n    } else if (flags & BF_FLAG_RADPNT_PREC) {\n        /* number of digits after the decimal point */\n        /* XXX: check (2 extra digits for rounding + 2 digits) */\n        precl = (bf_max(a->expn - b->expn, 0) + 2 +\n                 prec + 2 + LIMB_DIGITS - 1) / LIMB_DIGITS;\n    } else {\n        /* number of limbs of the quotient (2 extra digits for rounding) */\n        precl = (prec + 2 + LIMB_DIGITS - 1) / LIMB_DIGITS;\n    }\n    n = bf_max(a->len, precl);\n    \n    {\n        limb_t *taba, na, i;\n        slimb_t d;\n        \n        na = n + nb;\n        taba = bf_malloc(r->ctx, (na + 1) * sizeof(limb_t));\n        if (!taba)\n            goto fail;\n        d = na - a->len;\n        memset(taba, 0, d * sizeof(limb_t));\n        memcpy(taba + d, a->tab, a->len * sizeof(limb_t));\n        if (bfdec_resize(r, n + 1))\n            goto fail1;\n        if (mp_div_dec(r->ctx, r->tab, taba, na, b->tab, nb)) {\n        fail1:\n            bf_free(r->ctx, taba);\n            goto fail;\n        }\n        /* see if non zero remainder */\n        for(i = 0; i < nb; i++) {\n            if (taba[i] != 0)\n                break;\n        }\n        bf_free(r->ctx, taba);\n        if (i != nb) {\n            if (prec == BF_PREC_INF) {\n                bfdec_set_nan(r);\n                return BF_ST_INVALID_OP;\n            } else {\n                r->tab[0] |= 1;\n            }\n        }\n        r->expn = a->expn - b->expn + LIMB_DIGITS;\n        r->sign = r_sign;\n        ret = bfdec_normalize_and_round(r, prec, flags);\n    }\n    return ret;\n fail:\n    bfdec_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\nint bfdec_div(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags)\n{\n    return bf_op2((bf_t *)r, (bf_t *)a, (bf_t *)b, prec, flags,\n                  (bf_op2_func_t *)__bfdec_div);\n}\n\n/* a and b must be finite numbers with a >= 0 and b > 0. 'q' is the\n   integer defined as floor(a/b) and r = a - q * b. */\nstatic void bfdec_tdivremu(bf_context_t *s, bfdec_t *q, bfdec_t *r,\n                           const bfdec_t *a, const bfdec_t *b)\n{\n    if (bfdec_cmpu(a, b) < 0) {\n        bfdec_set_ui(q, 0);\n        bfdec_set(r, a);\n    } else {\n        bfdec_div(q, a, b, 0, BF_RNDZ | BF_FLAG_RADPNT_PREC);\n        bfdec_mul(r, q, b, BF_PREC_INF, BF_RNDZ);\n        bfdec_sub(r, a, r, BF_PREC_INF, BF_RNDZ);\n    }\n}\n\n/* division and remainder. \n   \n   rnd_mode is the rounding mode for the quotient. The additional\n   rounding mode BF_RND_EUCLIDIAN is supported.\n\n   'q' is an integer. 'r' is rounded with prec and flags (prec can be\n   BF_PREC_INF).\n*/\nint bfdec_divrem(bfdec_t *q, bfdec_t *r, const bfdec_t *a, const bfdec_t *b,\n                 limb_t prec, bf_flags_t flags, int rnd_mode)\n{\n    bf_context_t *s = q->ctx;\n    bfdec_t a1_s, *a1 = &a1_s;\n    bfdec_t b1_s, *b1 = &b1_s;\n    bfdec_t r1_s, *r1 = &r1_s;\n    int q_sign, res;\n    BOOL is_ceil, is_rndn;\n    \n    assert(q != a && q != b);\n    assert(r != a && r != b);\n    assert(q != r);\n    \n    if (a->len == 0 || b->len == 0) {\n        bfdec_set_zero(q, 0);\n        if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {\n            bfdec_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF || b->expn == BF_EXP_ZERO) {\n            bfdec_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bfdec_set(r, a);\n            return bfdec_round(r, prec, flags);\n        }\n    }\n\n    q_sign = a->sign ^ b->sign;\n    is_rndn = (rnd_mode == BF_RNDN || rnd_mode == BF_RNDNA);\n    switch(rnd_mode) {\n    default:\n    case BF_RNDZ:\n    case BF_RNDN:\n    case BF_RNDNA:\n        is_ceil = FALSE;\n        break;\n    case BF_RNDD:\n        is_ceil = q_sign;\n        break;\n    case BF_RNDU:\n        is_ceil = q_sign ^ 1;\n        break;\n    case BF_RNDA:\n        is_ceil = TRUE;\n        break;\n    case BF_DIVREM_EUCLIDIAN:\n        is_ceil = a->sign;\n        break;\n    }\n\n    a1->expn = a->expn;\n    a1->tab = a->tab;\n    a1->len = a->len;\n    a1->sign = 0;\n    \n    b1->expn = b->expn;\n    b1->tab = b->tab;\n    b1->len = b->len;\n    b1->sign = 0;\n\n    //    bfdec_print_str(\"a1\", a1);\n    //    bfdec_print_str(\"b1\", b1);\n    /* XXX: could improve to avoid having a large 'q' */\n    bfdec_tdivremu(s, q, r, a1, b1);\n    if (bfdec_is_nan(q) || bfdec_is_nan(r))\n        goto fail;\n    //    bfdec_print_str(\"q\", q);\n    //    bfdec_print_str(\"r\", r);\n    \n    if (r->len != 0) {\n        if (is_rndn) {\n            bfdec_init(s, r1);\n            if (bfdec_set(r1, r))\n                goto fail;\n            if (bfdec_mul_si(r1, r1, 2, BF_PREC_INF, BF_RNDZ)) {\n                bfdec_delete(r1);\n                goto fail;\n            }\n            res = bfdec_cmpu(r1, b);\n            bfdec_delete(r1);\n            if (res > 0 ||\n                (res == 0 &&\n                 (rnd_mode == BF_RNDNA ||\n                  (get_digit(q->tab, q->len, q->len * LIMB_DIGITS - q->expn) & 1) != 0))) {\n                goto do_sub_r;\n            }\n        } else if (is_ceil) {\n        do_sub_r:\n            res = bfdec_add_si(q, q, 1, BF_PREC_INF, BF_RNDZ);\n            res |= bfdec_sub(r, r, b1, BF_PREC_INF, BF_RNDZ);\n            if (res & BF_ST_MEM_ERROR)\n                goto fail;\n        }\n    }\n\n    r->sign ^= a->sign;\n    q->sign = q_sign;\n    return bfdec_round(r, prec, flags);\n fail:\n    bfdec_set_nan(q);\n    bfdec_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\nint bfdec_rem(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags, int rnd_mode)\n{\n    bfdec_t q_s, *q = &q_s;\n    int ret;\n    \n    bfdec_init(r->ctx, q);\n    ret = bfdec_divrem(q, r, a, b, prec, flags, rnd_mode);\n    bfdec_delete(q);\n    return ret;\n}\n\n/* convert to integer (infinite precision) */\nint bfdec_rint(bfdec_t *r, int rnd_mode)\n{\n    return bfdec_round(r, 0, rnd_mode | BF_FLAG_RADPNT_PREC);\n}\n\nint bfdec_sqrt(bfdec_t *r, const bfdec_t *a, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = a->ctx;\n    int ret, k;\n    limb_t *a1, v;\n    slimb_t n, n1, prec1;\n    limb_t res;\n\n    assert(r != a);\n\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bfdec_set_nan(r);\n        } else if (a->expn == BF_EXP_INF && a->sign) {\n            goto invalid_op;\n        } else {\n            bfdec_set(r, a);\n        }\n        ret = 0;\n    } else if (a->sign || prec == BF_PREC_INF) {\n invalid_op:\n        bfdec_set_nan(r);\n        ret = BF_ST_INVALID_OP;\n    } else {\n        if (flags & BF_FLAG_RADPNT_PREC) {\n            prec1 = bf_max(floor_div(a->expn + 1, 2) + prec, 1);\n        } else {\n            prec1 = prec;\n        }\n        /* convert the mantissa to an integer with at least 2 *\n           prec + 4 digits */\n        n = (2 * (prec1 + 2) + 2 * LIMB_DIGITS - 1) / (2 * LIMB_DIGITS);\n        if (bfdec_resize(r, n))\n            goto fail;\n        a1 = bf_malloc(s, sizeof(limb_t) * 2 * n);\n        if (!a1)\n            goto fail;\n        n1 = bf_min(2 * n, a->len);\n        memset(a1, 0, (2 * n - n1) * sizeof(limb_t));\n        memcpy(a1 + 2 * n - n1, a->tab + a->len - n1, n1 * sizeof(limb_t));\n        if (a->expn & 1) {\n            res = mp_shr_dec(a1, a1, 2 * n, 1, 0);\n        } else {\n            res = 0;\n        }\n        /* normalize so that a1 >= B^(2*n)/4. Not need for n = 1\n           because mp_sqrtrem2_dec already does it */\n        k = 0;\n        if (n > 1) {\n            v = a1[2 * n - 1];\n            while (v < BF_DEC_BASE / 4) {\n                k++;\n                v *= 4;\n            }\n            if (k != 0)\n                mp_mul1_dec(a1, a1, 2 * n, 1 << (2 * k), 0);\n        }\n        if (mp_sqrtrem_dec(s, r->tab, a1, n)) {\n            bf_free(s, a1);\n            goto fail;\n        }\n        if (k != 0)\n            mp_div1_dec(r->tab, r->tab, n, 1 << k, 0);\n        if (!res) {\n            res = mp_scan_nz(a1, n + 1);\n        }\n        bf_free(s, a1);\n        if (!res) {\n            res = mp_scan_nz(a->tab, a->len - n1);\n        }\n        if (res != 0)\n            r->tab[0] |= 1;\n        r->sign = 0;\n        r->expn = (a->expn + 1) >> 1;\n        ret = bfdec_round(r, prec, flags);\n    }\n    return ret;\n fail:\n    bfdec_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\n/* The rounding mode is always BF_RNDZ. Return BF_ST_OVERFLOW if there\n   is an overflow and 0 otherwise. No memory error is possible. */\nint bfdec_get_int32(int *pres, const bfdec_t *a)\n{\n    uint32_t v;\n    int ret;\n    if (a->expn >= BF_EXP_INF) {\n        ret = 0;\n        if (a->expn == BF_EXP_INF) {\n            v = (uint32_t)INT32_MAX + a->sign;\n             /* XXX: return overflow ? */\n        } else {\n            v = INT32_MAX;\n        }\n    } else if (a->expn <= 0) {\n        v = 0;\n        ret = 0;\n    } else if (a->expn <= 9) {\n        v = fast_shr_dec(a->tab[a->len - 1], LIMB_DIGITS - a->expn);\n        if (a->sign)\n            v = -v;\n        ret = 0;\n    } else if (a->expn == 10) {\n        uint64_t v1;\n        uint32_t v_max;\n#if LIMB_BITS == 64\n        v1 = fast_shr_dec(a->tab[a->len - 1], LIMB_DIGITS - a->expn);\n#else\n        v1 = (uint64_t)a->tab[a->len - 1] * 10 +\n            get_digit(a->tab, a->len, (a->len - 1) * LIMB_DIGITS - 1);\n#endif\n        v_max = (uint32_t)INT32_MAX + a->sign;\n        if (v1 > v_max) {\n            v = v_max;\n            ret = BF_ST_OVERFLOW;\n        } else {\n            v = v1;\n            if (a->sign)\n                v = -v;\n            ret = 0;\n        }\n    } else {\n        v = (uint32_t)INT32_MAX + a->sign;\n        ret = BF_ST_OVERFLOW;\n    }\n    *pres = v;\n    return ret;\n}\n\n/* power to an integer with infinite precision */\nint bfdec_pow_ui(bfdec_t *r, const bfdec_t *a, limb_t b)\n{\n    int ret, n_bits, i;\n    \n    assert(r != a);\n    if (b == 0)\n        return bfdec_set_ui(r, 1);\n    ret = bfdec_set(r, a);\n    n_bits = LIMB_BITS - clz(b);\n    for(i = n_bits - 2; i >= 0; i--) {\n        ret |= bfdec_mul(r, r, r, BF_PREC_INF, BF_RNDZ);\n        if ((b >> i) & 1)\n            ret |= bfdec_mul(r, r, a, BF_PREC_INF, BF_RNDZ);\n    }\n    return ret;\n}\n\nchar *bfdec_ftoa(size_t *plen, const bfdec_t *a, limb_t prec, bf_flags_t flags)\n{\n    return bf_ftoa_internal(plen, (const bf_t *)a, 10, prec, flags, TRUE);\n}\n\nint bfdec_atof(bfdec_t *r, const char *str, const char **pnext,\n               limb_t prec, bf_flags_t flags)\n{\n    slimb_t dummy_exp;\n    return bf_atof_internal((bf_t *)r, &dummy_exp, str, pnext, 10, prec,\n                            flags, TRUE);\n}\n\n#endif /* USE_BF_DEC */\n\n#ifdef USE_FFT_MUL\n/***************************************************************/\n/* Integer multiplication with FFT */\n\n/* or LIMB_BITS at bit position 'pos' in tab */\nstatic inline void put_bits(limb_t *tab, limb_t len, slimb_t pos, limb_t val)\n{\n    limb_t i;\n    int p;\n\n    i = pos >> LIMB_LOG2_BITS;\n    p = pos & (LIMB_BITS - 1);\n    if (i < len)\n        tab[i] |= val << p;\n    if (p != 0) {\n        i++;\n        if (i < len) {\n            tab[i] |= val >> (LIMB_BITS - p);\n        }\n    }\n}\n\n#if defined(__AVX2__)\n\ntypedef double NTTLimb;\n\n/* we must have: modulo >= 1 << NTT_MOD_LOG2_MIN */\n#define NTT_MOD_LOG2_MIN 50\n#define NTT_MOD_LOG2_MAX 51\n#define NB_MODS 5\n#define NTT_PROOT_2EXP 39\nstatic const int ntt_int_bits[NB_MODS] = { 254, 203, 152, 101, 50, };\n\nstatic const limb_t ntt_mods[NB_MODS] = { 0x00073a8000000001, 0x0007858000000001, 0x0007a38000000001, 0x0007a68000000001, 0x0007fd8000000001,\n};\n\nstatic const limb_t ntt_proot[2][NB_MODS] = {\n    { 0x00056198d44332c8, 0x0002eb5d640aad39, 0x00047e31eaa35fd0, 0x0005271ac118a150, 0x00075e0ce8442bd5, },\n    { 0x000461169761bcc5, 0x0002dac3cb2da688, 0x0004abc97751e3bf, 0x000656778fc8c485, 0x0000dc6469c269fa, },\n};\n\nstatic const limb_t ntt_mods_cr[NB_MODS * (NB_MODS - 1) / 2] = {\n 0x00020e4da740da8e, 0x0004c3dc09c09c1d, 0x000063bd097b4271, 0x000799d8f18f18fd,\n 0x0005384222222264, 0x000572b07c1f07fe, 0x00035cd08888889a,\n 0x00066015555557e3, 0x000725960b60b623,\n 0x0002fc1fa1d6ce12,\n};\n\n#else\n\ntypedef limb_t NTTLimb;\n\n#if LIMB_BITS == 64\n\n#define NTT_MOD_LOG2_MIN 61\n#define NTT_MOD_LOG2_MAX 62\n#define NB_MODS 5\n#define NTT_PROOT_2EXP 51\nstatic const int ntt_int_bits[NB_MODS] = { 307, 246, 185, 123, 61, };\n\nstatic const limb_t ntt_mods[NB_MODS] = { 0x28d8000000000001, 0x2a88000000000001, 0x2ed8000000000001, 0x3508000000000001, 0x3aa8000000000001,\n};\n\nstatic const limb_t ntt_proot[2][NB_MODS] = {\n    { 0x1b8ea61034a2bea7, 0x21a9762de58206fb, 0x02ca782f0756a8ea, 0x278384537a3e50a1, 0x106e13fee74ce0ab, },\n    { 0x233513af133e13b8, 0x1d13140d1c6f75f1, 0x12cde57f97e3eeda, 0x0d6149e23cbe654f, 0x36cd204f522a1379, },\n};\n\nstatic const limb_t ntt_mods_cr[NB_MODS * (NB_MODS - 1) / 2] = {\n 0x08a9ed097b425eea, 0x18a44aaaaaaaaab3, 0x2493f57f57f57f5d, 0x126b8d0649a7f8d4,\n 0x09d80ed7303b5ccc, 0x25b8bcf3cf3cf3d5, 0x2ce6ce63398ce638,\n 0x0e31fad40a57eb59, 0x02a3529fd4a7f52f,\n 0x3a5493e93e93e94a,\n};\n\n#elif LIMB_BITS == 32\n\n/* we must have: modulo >= 1 << NTT_MOD_LOG2_MIN */\n#define NTT_MOD_LOG2_MIN 29\n#define NTT_MOD_LOG2_MAX 30\n#define NB_MODS 5\n#define NTT_PROOT_2EXP 20\nstatic const int ntt_int_bits[NB_MODS] = { 148, 119, 89, 59, 29, };\n\nstatic const limb_t ntt_mods[NB_MODS] = { 0x0000000032b00001, 0x0000000033700001, 0x0000000036d00001, 0x0000000037300001, 0x000000003e500001,\n};\n\nstatic const limb_t ntt_proot[2][NB_MODS] = {\n    { 0x0000000032525f31, 0x0000000005eb3b37, 0x00000000246eda9f, 0x0000000035f25901, 0x00000000022f5768, },\n    { 0x00000000051eba1a, 0x00000000107be10e, 0x000000001cd574e0, 0x00000000053806e6, 0x000000002cd6bf98, },\n};\n\nstatic const limb_t ntt_mods_cr[NB_MODS * (NB_MODS - 1) / 2] = {\n 0x000000000449559a, 0x000000001eba6ca9, 0x000000002ec18e46, 0x000000000860160b,\n 0x000000000d321307, 0x000000000bf51120, 0x000000000f662938,\n 0x000000000932ab3e, 0x000000002f40eef8,\n 0x000000002e760905,\n};\n\n#endif /* LIMB_BITS */\n\n#endif /* !AVX2 */\n\n#if defined(__AVX2__)\n#define NTT_TRIG_K_MAX 18\n#else\n#define NTT_TRIG_K_MAX 19\n#endif\n\ntypedef struct BFNTTState {\n    bf_context_t *ctx;\n    \n    /* used for mul_mod_fast() */\n    limb_t ntt_mods_div[NB_MODS];\n\n    limb_t ntt_proot_pow[NB_MODS][2][NTT_PROOT_2EXP + 1];\n    limb_t ntt_proot_pow_inv[NB_MODS][2][NTT_PROOT_2EXP + 1];\n    NTTLimb *ntt_trig[NB_MODS][2][NTT_TRIG_K_MAX + 1];\n    /* 1/2^n mod m */\n    limb_t ntt_len_inv[NB_MODS][NTT_PROOT_2EXP + 1][2];\n#if defined(__AVX2__)\n    __m256d ntt_mods_cr_vec[NB_MODS * (NB_MODS - 1) / 2];\n    __m256d ntt_mods_vec[NB_MODS];\n    __m256d ntt_mods_inv_vec[NB_MODS];\n#else\n    limb_t ntt_mods_cr_inv[NB_MODS * (NB_MODS - 1) / 2];\n#endif\n} BFNTTState;\n\nstatic NTTLimb *get_trig(BFNTTState *s, int k, int inverse, int m_idx);\n\n/* add modulo with up to (LIMB_BITS-1) bit modulo */\nstatic inline limb_t add_mod(limb_t a, limb_t b, limb_t m)\n{\n    limb_t r;\n    r = a + b;\n    if (r >= m)\n        r -= m;\n    return r;\n}\n\n/* sub modulo with up to LIMB_BITS bit modulo */\nstatic inline limb_t sub_mod(limb_t a, limb_t b, limb_t m)\n{\n    limb_t r;\n    r = a - b;\n    if (r > a)\n        r += m;\n    return r;\n}\n\n/* return (r0+r1*B) mod m \n   precondition: 0 <= r0+r1*B < 2^(64+NTT_MOD_LOG2_MIN) \n*/\nstatic inline limb_t mod_fast(dlimb_t r, \n                                limb_t m, limb_t m_inv)\n{\n    limb_t a1, q, t0, r1, r0;\n    \n    a1 = r >> NTT_MOD_LOG2_MIN;\n    \n    q = ((dlimb_t)a1 * m_inv) >> LIMB_BITS;\n    r = r - (dlimb_t)q * m - m * 2;\n    r1 = r >> LIMB_BITS;\n    t0 = (slimb_t)r1 >> 1;\n    r += m & t0;\n    r0 = r;\n    r1 = r >> LIMB_BITS;\n    r0 += m & r1;\n    return r0;\n}\n\n/* faster version using precomputed modulo inverse. \n   precondition: 0 <= a * b < 2^(64+NTT_MOD_LOG2_MIN) */\nstatic inline limb_t mul_mod_fast(limb_t a, limb_t b, \n                                    limb_t m, limb_t m_inv)\n{\n    dlimb_t r;\n    r = (dlimb_t)a * (dlimb_t)b;\n    return mod_fast(r, m, m_inv);\n}\n\nstatic inline limb_t init_mul_mod_fast(limb_t m)\n{\n    dlimb_t t;\n    assert(m < (limb_t)1 << NTT_MOD_LOG2_MAX);\n    assert(m >= (limb_t)1 << NTT_MOD_LOG2_MIN);\n    t = (dlimb_t)1 << (LIMB_BITS + NTT_MOD_LOG2_MIN);\n    return t / m;\n}\n\n/* Faster version used when the multiplier is constant. 0 <= a < 2^64,\n   0 <= b < m. */\nstatic inline limb_t mul_mod_fast2(limb_t a, limb_t b, \n                                     limb_t m, limb_t b_inv)\n{\n    limb_t r, q;\n\n    q = ((dlimb_t)a * (dlimb_t)b_inv) >> LIMB_BITS;\n    r = a * b - q * m;\n    if (r >= m)\n        r -= m;\n    return r;\n}\n\n/* Faster version used when the multiplier is constant. 0 <= a < 2^64,\n   0 <= b < m. Let r = a * b mod m. The return value is 'r' or 'r +\n   m'. */\nstatic inline limb_t mul_mod_fast3(limb_t a, limb_t b, \n                                     limb_t m, limb_t b_inv)\n{\n    limb_t r, q;\n\n    q = ((dlimb_t)a * (dlimb_t)b_inv) >> LIMB_BITS;\n    r = a * b - q * m;\n    return r;\n}\n\nstatic inline limb_t init_mul_mod_fast2(limb_t b, limb_t m)\n{\n    return ((dlimb_t)b << LIMB_BITS) / m;\n}\n\n#ifdef __AVX2__\n\nstatic inline limb_t ntt_limb_to_int(NTTLimb a, limb_t m)\n{\n    slimb_t v;\n    v = a;\n    if (v < 0)\n        v += m;\n    if (v >= m)\n        v -= m;\n    return v;\n}\n\nstatic inline NTTLimb int_to_ntt_limb(limb_t a, limb_t m)\n{\n    return (slimb_t)a;\n}\n\nstatic inline NTTLimb int_to_ntt_limb2(limb_t a, limb_t m)\n{\n    if (a >= (m / 2))\n        a -= m;\n    return (slimb_t)a;\n}\n\n/* return r + m if r < 0 otherwise r. */\nstatic inline __m256d ntt_mod1(__m256d r, __m256d m)\n{\n    return _mm256_blendv_pd(r, r + m, r);\n}\n\n/* input: abs(r) < 2 * m. Output: abs(r) < m */\nstatic inline __m256d ntt_mod(__m256d r, __m256d mf, __m256d m2f)\n{\n    return _mm256_blendv_pd(r, r + m2f, r) - mf;\n}\n\n/* input: abs(a*b) < 2 * m^2, output: abs(r) < m */\nstatic inline __m256d ntt_mul_mod(__m256d a, __m256d b, __m256d mf,\n                                  __m256d m_inv)\n{\n    __m256d r, q, ab1, ab0, qm0, qm1;\n    ab1 = a * b;\n    q = _mm256_round_pd(ab1 * m_inv, 0); /* round to nearest */\n    qm1 = q * mf;\n    qm0 = _mm256_fmsub_pd(q, mf, qm1); /* low part */\n    ab0 = _mm256_fmsub_pd(a, b, ab1); /* low part */\n    r = (ab1 - qm1) + (ab0 - qm0);\n    return r;\n}\n\nstatic void *bf_aligned_malloc(bf_context_t *s, size_t size, size_t align)\n{\n    void *ptr;\n    void **ptr1;\n    ptr = bf_malloc(s, size + sizeof(void *) + align - 1);\n    if (!ptr)\n        return NULL;\n    ptr1 = (void **)(((uintptr_t)ptr + sizeof(void *) + align - 1) &\n                     ~(align - 1));\n    ptr1[-1] = ptr;\n    return ptr1;\n}\n\nstatic void bf_aligned_free(bf_context_t *s, void *ptr)\n{\n    if (!ptr)\n        return;\n    bf_free(s, ((void **)ptr)[-1]);\n}\n\nstatic void *ntt_malloc(BFNTTState *s, size_t size)\n{\n    return bf_aligned_malloc(s->ctx, size, 64);\n}\n\nstatic void ntt_free(BFNTTState *s, void *ptr)\n{\n    bf_aligned_free(s->ctx, ptr);\n}\n\nstatic no_inline int ntt_fft(BFNTTState *s,\n                             NTTLimb *out_buf, NTTLimb *in_buf,\n                             NTTLimb *tmp_buf, int fft_len_log2,\n                             int inverse, int m_idx)\n{\n    limb_t nb_blocks, fft_per_block, p, k, n, stride_in, i, j;\n    NTTLimb *tab_in, *tab_out, *tmp, *trig;\n    __m256d m_inv, mf, m2f, c, a0, a1, b0, b1;\n    limb_t m;\n    int l;\n    \n    m = ntt_mods[m_idx];\n    \n    m_inv = _mm256_set1_pd(1.0 / (double)m);\n    mf = _mm256_set1_pd(m);\n    m2f = _mm256_set1_pd(m * 2);\n\n    n = (limb_t)1 << fft_len_log2;\n    assert(n >= 8);\n    stride_in = n / 2;\n\n    tab_in = in_buf;\n    tab_out = tmp_buf;\n    trig = get_trig(s, fft_len_log2, inverse, m_idx);\n    if (!trig)\n        return -1;\n    p = 0;\n    for(k = 0; k < stride_in; k += 4) {\n        a0 = _mm256_load_pd(&tab_in[k]);\n        a1 = _mm256_load_pd(&tab_in[k + stride_in]);\n        c = _mm256_load_pd(trig);\n        trig += 4;\n        b0 = ntt_mod(a0 + a1, mf, m2f);\n        b1 = ntt_mul_mod(a0 - a1, c, mf, m_inv);\n        a0 = _mm256_permute2f128_pd(b0, b1, 0x20);\n        a1 = _mm256_permute2f128_pd(b0, b1, 0x31);\n        a0 = _mm256_permute4x64_pd(a0, 0xd8);\n        a1 = _mm256_permute4x64_pd(a1, 0xd8);\n        _mm256_store_pd(&tab_out[p], a0);\n        _mm256_store_pd(&tab_out[p + 4], a1);\n        p += 2 * 4;\n    }\n    tmp = tab_in;\n    tab_in = tab_out;\n    tab_out = tmp;\n\n    trig = get_trig(s, fft_len_log2 - 1, inverse, m_idx);\n    if (!trig)\n        return -1;\n    p = 0;\n    for(k = 0; k < stride_in; k += 4) {\n        a0 = _mm256_load_pd(&tab_in[k]);\n        a1 = _mm256_load_pd(&tab_in[k + stride_in]);\n        c = _mm256_setr_pd(trig[0], trig[0], trig[1], trig[1]);\n        trig += 2;\n        b0 = ntt_mod(a0 + a1, mf, m2f);\n        b1 = ntt_mul_mod(a0 - a1, c, mf, m_inv);\n        a0 = _mm256_permute2f128_pd(b0, b1, 0x20);\n        a1 = _mm256_permute2f128_pd(b0, b1, 0x31);\n        _mm256_store_pd(&tab_out[p], a0);\n        _mm256_store_pd(&tab_out[p + 4], a1);\n        p += 2 * 4;\n    }\n    tmp = tab_in;\n    tab_in = tab_out;\n    tab_out = tmp;\n    \n    nb_blocks = n / 4;\n    fft_per_block = 4;\n\n    l = fft_len_log2 - 2;\n    while (nb_blocks != 2) {\n        nb_blocks >>= 1;\n        p = 0;\n        k = 0;\n        trig = get_trig(s, l, inverse, m_idx);\n        if (!trig)\n            return -1;\n        for(i = 0; i < nb_blocks; i++) {\n            c = _mm256_set1_pd(trig[0]);\n            trig++;\n            for(j = 0; j < fft_per_block; j += 4) {\n                a0 = _mm256_load_pd(&tab_in[k + j]);\n                a1 = _mm256_load_pd(&tab_in[k + j + stride_in]);\n                b0 = ntt_mod(a0 + a1, mf, m2f);\n                b1 = ntt_mul_mod(a0 - a1, c, mf, m_inv);\n                _mm256_store_pd(&tab_out[p + j], b0);\n                _mm256_store_pd(&tab_out[p + j + fft_per_block], b1);\n            }\n            k += fft_per_block;\n            p += 2 * fft_per_block;\n        }\n        fft_per_block <<= 1;\n        l--;\n        tmp = tab_in;\n        tab_in = tab_out;\n        tab_out = tmp;\n    }\n\n    tab_out = out_buf;\n    for(k = 0; k < stride_in; k += 4) {\n        a0 = _mm256_load_pd(&tab_in[k]);\n        a1 = _mm256_load_pd(&tab_in[k + stride_in]);\n        b0 = ntt_mod(a0 + a1, mf, m2f);\n        b1 = ntt_mod(a0 - a1, mf, m2f);\n        _mm256_store_pd(&tab_out[k], b0);\n        _mm256_store_pd(&tab_out[k + stride_in], b1);\n    }\n    return 0;\n}\n\nstatic void ntt_vec_mul(BFNTTState *s,\n                        NTTLimb *tab1, NTTLimb *tab2, limb_t fft_len_log2,\n                        int k_tot, int m_idx)\n{\n    limb_t i, c_inv, n, m;\n    __m256d m_inv, mf, a, b, c;\n    \n    m = ntt_mods[m_idx];\n    c_inv = s->ntt_len_inv[m_idx][k_tot][0];\n    m_inv = _mm256_set1_pd(1.0 / (double)m);\n    mf = _mm256_set1_pd(m);\n    c = _mm256_set1_pd(int_to_ntt_limb(c_inv, m));\n    n = (limb_t)1 << fft_len_log2;\n    for(i = 0; i < n; i += 4) {\n        a = _mm256_load_pd(&tab1[i]);\n        b = _mm256_load_pd(&tab2[i]);\n        a = ntt_mul_mod(a, b, mf, m_inv);\n        a = ntt_mul_mod(a, c, mf, m_inv);\n        _mm256_store_pd(&tab1[i], a);\n    }\n}\n\nstatic no_inline void mul_trig(NTTLimb *buf,\n                               limb_t n, limb_t c1, limb_t m, limb_t m_inv1)\n{\n    limb_t i, c2, c3, c4;\n    __m256d c, c_mul, a0, mf, m_inv;\n    assert(n >= 2);\n    \n    mf = _mm256_set1_pd(m);\n    m_inv = _mm256_set1_pd(1.0 / (double)m);\n\n    c2 = mul_mod_fast(c1, c1, m, m_inv1);\n    c3 = mul_mod_fast(c2, c1, m, m_inv1);\n    c4 = mul_mod_fast(c2, c2, m, m_inv1);\n    c = _mm256_setr_pd(1, int_to_ntt_limb(c1, m),\n                       int_to_ntt_limb(c2, m), int_to_ntt_limb(c3, m));\n    c_mul = _mm256_set1_pd(int_to_ntt_limb(c4, m));\n    for(i = 0; i < n; i += 4) {\n        a0 = _mm256_load_pd(&buf[i]);\n        a0 = ntt_mul_mod(a0, c, mf, m_inv);\n        _mm256_store_pd(&buf[i], a0);\n        c = ntt_mul_mod(c, c_mul, mf, m_inv);\n    }\n}\n\n#else\n\nstatic void *ntt_malloc(BFNTTState *s, size_t size)\n{\n    return bf_malloc(s->ctx, size);\n}\n\nstatic void ntt_free(BFNTTState *s, void *ptr)\n{\n    bf_free(s->ctx, ptr);\n}\n\nstatic inline limb_t ntt_limb_to_int(NTTLimb a, limb_t m)\n{\n    if (a >= m)\n        a -= m;\n    return a;\n}\n\nstatic inline NTTLimb int_to_ntt_limb(slimb_t a, limb_t m)\n{\n    return a;\n}\n\nstatic no_inline int ntt_fft(BFNTTState *s, NTTLimb *out_buf, NTTLimb *in_buf,\n                             NTTLimb *tmp_buf, int fft_len_log2,\n                             int inverse, int m_idx)\n{\n    limb_t nb_blocks, fft_per_block, p, k, n, stride_in, i, j, m, m2;\n    NTTLimb *tab_in, *tab_out, *tmp, a0, a1, b0, b1, c, *trig, c_inv;\n    int l;\n    \n    m = ntt_mods[m_idx];\n    m2 = 2 * m;\n    n = (limb_t)1 << fft_len_log2;\n    nb_blocks = n;\n    fft_per_block = 1;\n    stride_in = n / 2;\n    tab_in = in_buf;\n    tab_out = tmp_buf;\n    l = fft_len_log2;\n    while (nb_blocks != 2) {\n        nb_blocks >>= 1;\n        p = 0;\n        k = 0;\n        trig = get_trig(s, l, inverse, m_idx);\n        if (!trig)\n            return -1;\n        for(i = 0; i < nb_blocks; i++) {\n            c = trig[0];\n            c_inv = trig[1];\n            trig += 2;\n            for(j = 0; j < fft_per_block; j++) {\n                a0 = tab_in[k + j];\n                a1 = tab_in[k + j + stride_in];\n                b0 = add_mod(a0, a1, m2);\n                b1 = a0 - a1 + m2;\n                b1 = mul_mod_fast3(b1, c, m, c_inv);\n                tab_out[p + j] = b0;\n                tab_out[p + j + fft_per_block] = b1;\n            }\n            k += fft_per_block;\n            p += 2 * fft_per_block;\n        }\n        fft_per_block <<= 1;\n        l--;\n        tmp = tab_in;\n        tab_in = tab_out;\n        tab_out = tmp;\n    }\n    /* no twiddle in last step */\n    tab_out = out_buf; \n    for(k = 0; k < stride_in; k++) {\n        a0 = tab_in[k];\n        a1 = tab_in[k + stride_in];\n        b0 = add_mod(a0, a1, m2);\n        b1 = sub_mod(a0, a1, m2);\n        tab_out[k] = b0;\n        tab_out[k + stride_in] = b1;\n    }\n    return 0;\n}\n\nstatic void ntt_vec_mul(BFNTTState *s,\n                        NTTLimb *tab1, NTTLimb *tab2, int fft_len_log2,\n                        int k_tot, int m_idx)\n{\n    limb_t i, norm, norm_inv, a, n, m, m_inv;\n    \n    m = ntt_mods[m_idx];\n    m_inv = s->ntt_mods_div[m_idx];\n    norm = s->ntt_len_inv[m_idx][k_tot][0];\n    norm_inv = s->ntt_len_inv[m_idx][k_tot][1];\n    n = (limb_t)1 << fft_len_log2;\n    for(i = 0; i < n; i++) {\n        a = tab1[i];\n        /* need to reduce the range so that the product is <\n           2^(LIMB_BITS+NTT_MOD_LOG2_MIN) */\n        if (a >= m)\n            a -= m;\n        a = mul_mod_fast(a, tab2[i], m, m_inv);\n        a = mul_mod_fast3(a, norm, m, norm_inv);\n        tab1[i] = a;\n    }\n}\n\nstatic no_inline void mul_trig(NTTLimb *buf,\n                               limb_t n, limb_t c_mul, limb_t m, limb_t m_inv)\n{\n    limb_t i, c0, c_mul_inv;\n    \n    c0 = 1;\n    c_mul_inv = init_mul_mod_fast2(c_mul, m);\n    for(i = 0; i < n; i++) {\n        buf[i] = mul_mod_fast(buf[i], c0, m, m_inv);\n        c0 = mul_mod_fast2(c0, c_mul, m, c_mul_inv);\n    }\n}\n\n#endif /* !AVX2 */\n\nstatic no_inline NTTLimb *get_trig(BFNTTState *s,\n                                   int k, int inverse, int m_idx)\n{\n    NTTLimb *tab;\n    limb_t i, n2, c, c_mul, m, c_mul_inv;\n    \n    if (k > NTT_TRIG_K_MAX)\n        return NULL;\n\n    tab = s->ntt_trig[m_idx][inverse][k];\n    if (tab)\n        return tab;\n    n2 = (limb_t)1 << (k - 1);\n    m = ntt_mods[m_idx];\n#ifdef __AVX2__\n    tab = ntt_malloc(s, sizeof(NTTLimb) * n2);\n#else\n    tab = ntt_malloc(s, sizeof(NTTLimb) * n2 * 2);\n#endif\n    if (!tab)\n        return NULL;\n    c = 1;\n    c_mul = s->ntt_proot_pow[m_idx][inverse][k];\n    c_mul_inv = s->ntt_proot_pow_inv[m_idx][inverse][k];\n    for(i = 0; i < n2; i++) {\n#ifdef __AVX2__\n        tab[i] = int_to_ntt_limb2(c, m);\n#else\n        tab[2 * i] = int_to_ntt_limb(c, m);\n        tab[2 * i + 1] = init_mul_mod_fast2(c, m);\n#endif\n        c = mul_mod_fast2(c, c_mul, m, c_mul_inv);\n    }\n    s->ntt_trig[m_idx][inverse][k] = tab;\n    return tab;\n}\n\nvoid fft_clear_cache(bf_context_t *s1)\n{\n    int m_idx, inverse, k;\n    BFNTTState *s = s1->ntt_state;\n    if (s) {\n        for(m_idx = 0; m_idx < NB_MODS; m_idx++) {\n            for(inverse = 0; inverse < 2; inverse++) {\n                for(k = 0; k < NTT_TRIG_K_MAX + 1; k++) {\n                    if (s->ntt_trig[m_idx][inverse][k]) {\n                        ntt_free(s, s->ntt_trig[m_idx][inverse][k]);\n                        s->ntt_trig[m_idx][inverse][k] = NULL;\n                    }\n                }\n            }\n        }\n#if defined(__AVX2__)\n        bf_aligned_free(s1, s);\n#else\n        bf_free(s1, s);\n#endif\n        s1->ntt_state = NULL;\n    }\n}\n\n#define STRIP_LEN 16\n\n/* dst = buf1, src = buf2 */\nstatic int ntt_fft_partial(BFNTTState *s, NTTLimb *buf1,\n                           int k1, int k2, limb_t n1, limb_t n2, int inverse,\n                           limb_t m_idx)\n{\n    limb_t i, j, c_mul, c0, m, m_inv, strip_len, l;\n    NTTLimb *buf2, *buf3;\n    \n    buf2 = NULL;\n    buf3 = ntt_malloc(s, sizeof(NTTLimb) * n1);\n    if (!buf3)\n        goto fail;\n    if (k2 == 0) {\n        if (ntt_fft(s, buf1, buf1, buf3, k1, inverse, m_idx))\n            goto fail;\n    } else {\n        strip_len = STRIP_LEN;\n        buf2 = ntt_malloc(s, sizeof(NTTLimb) * n1 * strip_len);\n        if (!buf2)\n            goto fail;\n        m = ntt_mods[m_idx];\n        m_inv = s->ntt_mods_div[m_idx];\n        c0 = s->ntt_proot_pow[m_idx][inverse][k1 + k2];\n        c_mul = 1;\n        assert((n2 % strip_len) == 0);\n        for(j = 0; j < n2; j += strip_len) {\n            for(i = 0; i < n1; i++) {\n                for(l = 0; l < strip_len; l++) {\n                    buf2[i + l * n1] = buf1[i * n2 + (j + l)];\n                }\n            }\n            for(l = 0; l < strip_len; l++) {\n                if (inverse)\n                    mul_trig(buf2 + l * n1, n1, c_mul, m, m_inv);\n                if (ntt_fft(s, buf2 + l * n1, buf2 + l * n1, buf3, k1, inverse, m_idx))\n                    goto fail;\n                if (!inverse)\n                    mul_trig(buf2 + l * n1, n1, c_mul, m, m_inv);\n                c_mul = mul_mod_fast(c_mul, c0, m, m_inv);\n            }\n            \n            for(i = 0; i < n1; i++) {\n                for(l = 0; l < strip_len; l++) {\n                    buf1[i * n2 + (j + l)] = buf2[i + l *n1];\n                }\n            }\n        }\n        ntt_free(s, buf2);\n    }\n    ntt_free(s, buf3);\n    return 0;\n fail:\n    ntt_free(s, buf2);\n    ntt_free(s, buf3);\n    return -1;\n}\n\n\n/* dst = buf1, src = buf2, tmp = buf3 */\nstatic int ntt_conv(BFNTTState *s, NTTLimb *buf1, NTTLimb *buf2,\n                    int k, int k_tot, limb_t m_idx)\n{\n    limb_t n1, n2, i;\n    int k1, k2;\n    \n    if (k <= NTT_TRIG_K_MAX) {\n        k1 = k;\n    } else {\n        /* recursive split of the FFT */\n        k1 = bf_min(k / 2, NTT_TRIG_K_MAX);\n    }\n    k2 = k - k1;\n    n1 = (limb_t)1 << k1;\n    n2 = (limb_t)1 << k2;\n    \n    if (ntt_fft_partial(s, buf1, k1, k2, n1, n2, 0, m_idx))\n        return -1;\n    if (ntt_fft_partial(s, buf2, k1, k2, n1, n2, 0, m_idx))\n        return -1;\n    if (k2 == 0) {\n        ntt_vec_mul(s, buf1, buf2, k, k_tot, m_idx);\n    } else {\n        for(i = 0; i < n1; i++) {\n            ntt_conv(s, buf1 + i * n2, buf2 + i * n2, k2, k_tot, m_idx);\n        }\n    }\n    if (ntt_fft_partial(s, buf1, k1, k2, n1, n2, 1, m_idx))\n        return -1;\n    return 0;\n}\n\n\nstatic no_inline void limb_to_ntt(BFNTTState *s,\n                                  NTTLimb *tabr, limb_t fft_len,\n                                  const limb_t *taba, limb_t a_len, int dpl,\n                                  int first_m_idx, int nb_mods)\n{\n    slimb_t i, n;\n    dlimb_t a, b;\n    int j, shift;\n    limb_t base_mask1, a0, a1, a2, r, m, m_inv;\n    \n#if 0\n    for(i = 0; i < a_len; i++) {\n        printf(\"%\" PRId64 \": \" FMT_LIMB \"\\n\",\n               (int64_t)i, taba[i]);\n    }\n#endif   \n    memset(tabr, 0, sizeof(NTTLimb) * fft_len * nb_mods);\n    shift = dpl & (LIMB_BITS - 1);\n    if (shift == 0)\n        base_mask1 = -1;\n    else\n        base_mask1 = ((limb_t)1 << shift) - 1;\n    n = bf_min(fft_len, (a_len * LIMB_BITS + dpl - 1) / dpl);\n    for(i = 0; i < n; i++) {\n        a0 = get_bits(taba, a_len, i * dpl);\n        if (dpl <= LIMB_BITS) {\n            a0 &= base_mask1;\n            a = a0;\n        } else {\n            a1 = get_bits(taba, a_len, i * dpl + LIMB_BITS);\n            if (dpl <= (LIMB_BITS + NTT_MOD_LOG2_MIN)) {\n                a = a0 | ((dlimb_t)(a1 & base_mask1) << LIMB_BITS);\n            } else {\n                if (dpl > 2 * LIMB_BITS) {\n                    a2 = get_bits(taba, a_len, i * dpl + LIMB_BITS * 2) &\n                        base_mask1;\n                } else {\n                    a1 &= base_mask1;\n                    a2 = 0;\n                }\n                //            printf(\"a=0x%016lx%016lx%016lx\\n\", a2, a1, a0);\n                a = (a0 >> (LIMB_BITS - NTT_MOD_LOG2_MAX + NTT_MOD_LOG2_MIN)) |\n                    ((dlimb_t)a1 << (NTT_MOD_LOG2_MAX - NTT_MOD_LOG2_MIN)) |\n                    ((dlimb_t)a2 << (LIMB_BITS + NTT_MOD_LOG2_MAX - NTT_MOD_LOG2_MIN));\n                a0 &= ((limb_t)1 << (LIMB_BITS - NTT_MOD_LOG2_MAX + NTT_MOD_LOG2_MIN)) - 1;\n            }\n        }\n        for(j = 0; j < nb_mods; j++) {\n            m = ntt_mods[first_m_idx + j];\n            m_inv = s->ntt_mods_div[first_m_idx + j];\n            r = mod_fast(a, m, m_inv);\n            if (dpl > (LIMB_BITS + NTT_MOD_LOG2_MIN)) {\n                b = ((dlimb_t)r << (LIMB_BITS - NTT_MOD_LOG2_MAX + NTT_MOD_LOG2_MIN)) | a0;\n                r = mod_fast(b, m, m_inv);\n            }\n            tabr[i + j * fft_len] = int_to_ntt_limb(r, m);\n        }\n    }\n}\n\n#if defined(__AVX2__)\n\n#define VEC_LEN 4\n\ntypedef union {\n    __m256d v;\n    double d[4];\n} VecUnion;\n\nstatic no_inline void ntt_to_limb(BFNTTState *s, limb_t *tabr, limb_t r_len,\n                                  const NTTLimb *buf, int fft_len_log2, int dpl,\n                                  int nb_mods)\n{\n    const limb_t *mods = ntt_mods + NB_MODS - nb_mods;\n    const __m256d *mods_cr_vec, *mf, *m_inv;\n    VecUnion y[NB_MODS];\n    limb_t u[NB_MODS], carry[NB_MODS], fft_len, base_mask1, r;\n    slimb_t i, len, pos;\n    int j, k, l, shift, n_limb1, p;\n    dlimb_t t;\n        \n    j = NB_MODS * (NB_MODS - 1) / 2 - nb_mods * (nb_mods - 1) / 2;\n    mods_cr_vec = s->ntt_mods_cr_vec + j;\n    mf = s->ntt_mods_vec + NB_MODS - nb_mods;\n    m_inv = s->ntt_mods_inv_vec + NB_MODS - nb_mods;\n        \n    shift = dpl & (LIMB_BITS - 1);\n    if (shift == 0)\n        base_mask1 = -1;\n    else\n        base_mask1 = ((limb_t)1 << shift) - 1;\n    n_limb1 = ((unsigned)dpl - 1) / LIMB_BITS;\n    for(j = 0; j < NB_MODS; j++) \n        carry[j] = 0;\n    for(j = 0; j < NB_MODS; j++) \n        u[j] = 0; /* avoid warnings */\n    memset(tabr, 0, sizeof(limb_t) * r_len);\n    fft_len = (limb_t)1 << fft_len_log2;\n    len = bf_min(fft_len, (r_len * LIMB_BITS + dpl - 1) / dpl);\n    len = (len + VEC_LEN - 1) & ~(VEC_LEN - 1);\n    i = 0;\n    while (i < len) {\n        for(j = 0; j < nb_mods; j++)\n            y[j].v = *(__m256d *)&buf[i + fft_len * j];\n\n        /* Chinese remainder to get mixed radix representation */\n        l = 0;\n        for(j = 0; j < nb_mods - 1; j++) {\n            y[j].v = ntt_mod1(y[j].v, mf[j]);\n            for(k = j + 1; k < nb_mods; k++) {\n                y[k].v = ntt_mul_mod(y[k].v - y[j].v,\n                                     mods_cr_vec[l], mf[k], m_inv[k]);\n                l++;\n            }\n        }\n        y[j].v = ntt_mod1(y[j].v, mf[j]);\n        \n        for(p = 0; p < VEC_LEN; p++) {\n            /* back to normal representation */\n            u[0] = (int64_t)y[nb_mods - 1].d[p];\n            l = 1;\n            for(j = nb_mods - 2; j >= 1; j--) {\n                r = (int64_t)y[j].d[p];\n                for(k = 0; k < l; k++) {\n                    t = (dlimb_t)u[k] * mods[j] + r;\n                    r = t >> LIMB_BITS;\n                    u[k] = t;\n                }\n                u[l] = r;\n                l++;\n            }\n            /* XXX: for nb_mods = 5, l should be 4 */\n            \n            /* last step adds the carry */\n            r = (int64_t)y[0].d[p];\n            for(k = 0; k < l; k++) {\n                t = (dlimb_t)u[k] * mods[j] + r + carry[k];\n                r = t >> LIMB_BITS;\n                u[k] = t;\n            }\n            u[l] = r + carry[l];\n\n#if 0\n            printf(\"%\" PRId64 \": \", i);\n            for(j = nb_mods - 1; j >= 0; j--) {\n                printf(\" %019\" PRIu64, u[j]);\n            }\n            printf(\"\\n\");\n#endif\n            \n            /* write the digits */\n            pos = i * dpl;\n            for(j = 0; j < n_limb1; j++) {\n                put_bits(tabr, r_len, pos, u[j]);\n                pos += LIMB_BITS;\n            }\n            put_bits(tabr, r_len, pos, u[n_limb1] & base_mask1);\n            /* shift by dpl digits and set the carry */\n            if (shift == 0) {\n                for(j = n_limb1 + 1; j < nb_mods; j++)\n                    carry[j - (n_limb1 + 1)] = u[j];\n            } else {\n                for(j = n_limb1; j < nb_mods - 1; j++) {\n                    carry[j - n_limb1] = (u[j] >> shift) |\n                        (u[j + 1] << (LIMB_BITS - shift));\n                }\n                carry[nb_mods - 1 - n_limb1] = u[nb_mods - 1] >> shift;\n            }\n            i++;\n        }\n    }\n}\n#else\nstatic no_inline void ntt_to_limb(BFNTTState *s, limb_t *tabr, limb_t r_len,\n                                  const NTTLimb *buf, int fft_len_log2, int dpl,\n                                  int nb_mods)\n{\n    const limb_t *mods = ntt_mods + NB_MODS - nb_mods;\n    const limb_t *mods_cr, *mods_cr_inv;\n    limb_t y[NB_MODS], u[NB_MODS], carry[NB_MODS], fft_len, base_mask1, r;\n    slimb_t i, len, pos;\n    int j, k, l, shift, n_limb1;\n    dlimb_t t;\n        \n    j = NB_MODS * (NB_MODS - 1) / 2 - nb_mods * (nb_mods - 1) / 2;\n    mods_cr = ntt_mods_cr + j;\n    mods_cr_inv = s->ntt_mods_cr_inv + j;\n\n    shift = dpl & (LIMB_BITS - 1);\n    if (shift == 0)\n        base_mask1 = -1;\n    else\n        base_mask1 = ((limb_t)1 << shift) - 1;\n    n_limb1 = ((unsigned)dpl - 1) / LIMB_BITS;\n    for(j = 0; j < NB_MODS; j++) \n        carry[j] = 0;\n    for(j = 0; j < NB_MODS; j++) \n        u[j] = 0; /* avoid warnings */\n    memset(tabr, 0, sizeof(limb_t) * r_len);\n    fft_len = (limb_t)1 << fft_len_log2;\n    len = bf_min(fft_len, (r_len * LIMB_BITS + dpl - 1) / dpl);\n    for(i = 0; i < len; i++) {\n        for(j = 0; j < nb_mods; j++)  {\n            y[j] = ntt_limb_to_int(buf[i + fft_len * j], mods[j]);\n        }\n\n        /* Chinese remainder to get mixed radix representation */\n        l = 0;\n        for(j = 0; j < nb_mods - 1; j++) {\n            for(k = j + 1; k < nb_mods; k++) {\n                limb_t m;\n                m = mods[k];\n                /* Note: there is no overflow in the sub_mod() because\n                   the modulos are sorted by increasing order */\n                y[k] = mul_mod_fast2(y[k] - y[j] + m, \n                                     mods_cr[l], m, mods_cr_inv[l]);\n                l++;\n            }\n        }\n        \n        /* back to normal representation */\n        u[0] = y[nb_mods - 1];\n        l = 1;\n        for(j = nb_mods - 2; j >= 1; j--) {\n            r = y[j];\n            for(k = 0; k < l; k++) {\n                t = (dlimb_t)u[k] * mods[j] + r;\n                r = t >> LIMB_BITS;\n                u[k] = t;\n            }\n            u[l] = r;\n            l++;\n        }\n        \n        /* last step adds the carry */\n        r = y[0];\n        for(k = 0; k < l; k++) {\n            t = (dlimb_t)u[k] * mods[j] + r + carry[k];\n            r = t >> LIMB_BITS;\n            u[k] = t;\n        }\n        u[l] = r + carry[l];\n\n#if 0\n        printf(\"%\" PRId64 \": \", (int64_t)i);\n        for(j = nb_mods - 1; j >= 0; j--) {\n            printf(\" \" FMT_LIMB, u[j]);\n        }\n        printf(\"\\n\");\n#endif\n        \n        /* write the digits */\n        pos = i * dpl;\n        for(j = 0; j < n_limb1; j++) {\n            put_bits(tabr, r_len, pos, u[j]);\n            pos += LIMB_BITS;\n        }\n        put_bits(tabr, r_len, pos, u[n_limb1] & base_mask1);\n        /* shift by dpl digits and set the carry */\n        if (shift == 0) {\n            for(j = n_limb1 + 1; j < nb_mods; j++)\n                carry[j - (n_limb1 + 1)] = u[j];\n        } else {\n            for(j = n_limb1; j < nb_mods - 1; j++) {\n                carry[j - n_limb1] = (u[j] >> shift) |\n                    (u[j + 1] << (LIMB_BITS - shift));\n            }\n            carry[nb_mods - 1 - n_limb1] = u[nb_mods - 1] >> shift;\n        }\n    }\n}\n#endif\n\nstatic int ntt_static_init(bf_context_t *s1)\n{\n    BFNTTState *s;\n    int inverse, i, j, k, l;\n    limb_t c, c_inv, c_inv2, m, m_inv;\n\n    if (s1->ntt_state)\n        return 0;\n#if defined(__AVX2__)\n    s = bf_aligned_malloc(s1, sizeof(*s), 64);\n#else\n    s = bf_malloc(s1, sizeof(*s));\n#endif\n    if (!s)\n        return -1;\n    memset(s, 0, sizeof(*s));\n    s1->ntt_state = s;\n    s->ctx = s1;\n    \n    for(j = 0; j < NB_MODS; j++) {\n        m = ntt_mods[j];\n        m_inv = init_mul_mod_fast(m);\n        s->ntt_mods_div[j] = m_inv;\n#if defined(__AVX2__)\n        s->ntt_mods_vec[j] = _mm256_set1_pd(m);\n        s->ntt_mods_inv_vec[j] = _mm256_set1_pd(1.0 / (double)m);\n#endif\n        c_inv2 = (m + 1) / 2; /* 1/2 */\n        c_inv = 1;\n        for(i = 0; i <= NTT_PROOT_2EXP; i++) {\n            s->ntt_len_inv[j][i][0] = c_inv;\n            s->ntt_len_inv[j][i][1] = init_mul_mod_fast2(c_inv, m);\n            c_inv = mul_mod_fast(c_inv, c_inv2, m, m_inv);\n        }\n\n        for(inverse = 0; inverse < 2; inverse++) {\n            c = ntt_proot[inverse][j];\n            for(i = 0; i < NTT_PROOT_2EXP; i++) {\n                s->ntt_proot_pow[j][inverse][NTT_PROOT_2EXP - i] = c;\n                s->ntt_proot_pow_inv[j][inverse][NTT_PROOT_2EXP - i] =\n                    init_mul_mod_fast2(c, m);\n                c = mul_mod_fast(c, c, m, m_inv);\n            }\n        }\n    }\n\n    l = 0;\n    for(j = 0; j < NB_MODS - 1; j++) {\n        for(k = j + 1; k < NB_MODS; k++) {\n#if defined(__AVX2__)\n            s->ntt_mods_cr_vec[l] = _mm256_set1_pd(int_to_ntt_limb2(ntt_mods_cr[l],\n                                                                    ntt_mods[k]));\n#else\n            s->ntt_mods_cr_inv[l] = init_mul_mod_fast2(ntt_mods_cr[l],\n                                                       ntt_mods[k]);\n#endif\n            l++;\n        }\n    }\n    return 0;\n}\n\nint bf_get_fft_size(int *pdpl, int *pnb_mods, limb_t len)\n{\n    int dpl, fft_len_log2, n_bits, nb_mods, dpl_found, fft_len_log2_found;\n    int int_bits, nb_mods_found;\n    limb_t cost, min_cost;\n    \n    min_cost = -1;\n    dpl_found = 0;\n    nb_mods_found = 4;\n    fft_len_log2_found = 0;\n    for(nb_mods = 3; nb_mods <= NB_MODS; nb_mods++) {\n        int_bits = ntt_int_bits[NB_MODS - nb_mods];\n        dpl = bf_min((int_bits - 4) / 2,\n                     2 * LIMB_BITS + 2 * NTT_MOD_LOG2_MIN - NTT_MOD_LOG2_MAX);\n        for(;;) {\n            fft_len_log2 = ceil_log2((len * LIMB_BITS + dpl - 1) / dpl);\n            if (fft_len_log2 > NTT_PROOT_2EXP)\n                goto next;\n            n_bits = fft_len_log2 + 2 * dpl;\n            if (n_bits <= int_bits) {\n                cost = ((limb_t)(fft_len_log2 + 1) << fft_len_log2) * nb_mods;\n                //                printf(\"n=%d dpl=%d: cost=%\" PRId64 \"\\n\", nb_mods, dpl, (int64_t)cost);\n                if (cost < min_cost) {\n                    min_cost = cost;\n                    dpl_found = dpl;\n                    nb_mods_found = nb_mods;\n                    fft_len_log2_found = fft_len_log2;\n                }\n                break;\n            }\n            dpl--;\n            if (dpl == 0)\n                break;\n        }\n    next: ;\n    }\n    if (!dpl_found)\n        abort();\n    /* limit dpl if possible to reduce fixed cost of limb/NTT conversion */\n    if (dpl_found > (LIMB_BITS + NTT_MOD_LOG2_MIN) &&\n        ((limb_t)(LIMB_BITS + NTT_MOD_LOG2_MIN) << fft_len_log2_found) >=\n        len * LIMB_BITS) {\n        dpl_found = LIMB_BITS + NTT_MOD_LOG2_MIN;\n    }\n    *pnb_mods = nb_mods_found;\n    *pdpl = dpl_found;\n    return fft_len_log2_found;\n}\n\n/* return 0 if OK, -1 if memory error */\nstatic no_inline int fft_mul(bf_context_t *s1,\n                             bf_t *res, limb_t *a_tab, limb_t a_len,\n                             limb_t *b_tab, limb_t b_len, int mul_flags)\n{\n    BFNTTState *s;\n    int dpl, fft_len_log2, j, nb_mods, reduced_mem;\n    slimb_t len, fft_len;\n    NTTLimb *buf1, *buf2, *ptr;\n#if defined(USE_MUL_CHECK)\n    limb_t ha, hb, hr, h_ref;\n#endif\n    \n    if (ntt_static_init(s1))\n        return -1;\n    s = s1->ntt_state;\n    \n    /* find the optimal number of digits per limb (dpl) */\n    len = a_len + b_len;\n    fft_len_log2 = bf_get_fft_size(&dpl, &nb_mods, len);\n    fft_len = (uint64_t)1 << fft_len_log2;\n    //    printf(\"len=%\" PRId64 \" fft_len_log2=%d dpl=%d\\n\", len, fft_len_log2, dpl);\n#if defined(USE_MUL_CHECK)\n    ha = mp_mod1(a_tab, a_len, BF_CHKSUM_MOD, 0);\n    hb = mp_mod1(b_tab, b_len, BF_CHKSUM_MOD, 0);\n#endif\n    if ((mul_flags & (FFT_MUL_R_OVERLAP_A | FFT_MUL_R_OVERLAP_B)) == 0) {\n        if (!(mul_flags & FFT_MUL_R_NORESIZE))\n            bf_resize(res, 0);\n    } else if (mul_flags & FFT_MUL_R_OVERLAP_B) {\n        limb_t *tmp_tab, tmp_len;\n        /* it is better to free 'b' first */\n        tmp_tab = a_tab;\n        a_tab = b_tab;\n        b_tab = tmp_tab;\n        tmp_len = a_len;\n        a_len = b_len;\n        b_len = tmp_len;\n    }\n    buf1 = ntt_malloc(s, sizeof(NTTLimb) * fft_len * nb_mods);\n    if (!buf1)\n        return -1;\n    limb_to_ntt(s, buf1, fft_len, a_tab, a_len, dpl,\n                NB_MODS - nb_mods, nb_mods);\n    if ((mul_flags & (FFT_MUL_R_OVERLAP_A | FFT_MUL_R_OVERLAP_B)) == \n        FFT_MUL_R_OVERLAP_A) {\n        if (!(mul_flags & FFT_MUL_R_NORESIZE))\n            bf_resize(res, 0);\n    }\n    reduced_mem = (fft_len_log2 >= 14);\n    if (!reduced_mem) {\n        buf2 = ntt_malloc(s, sizeof(NTTLimb) * fft_len * nb_mods);\n        if (!buf2)\n            goto fail;\n        limb_to_ntt(s, buf2, fft_len, b_tab, b_len, dpl,\n                    NB_MODS - nb_mods, nb_mods);\n        if (!(mul_flags & FFT_MUL_R_NORESIZE))\n            bf_resize(res, 0); /* in case res == b */\n    } else {\n        buf2 = ntt_malloc(s, sizeof(NTTLimb) * fft_len);\n        if (!buf2)\n            goto fail;\n    }\n    for(j = 0; j < nb_mods; j++) {\n        if (reduced_mem) {\n            limb_to_ntt(s, buf2, fft_len, b_tab, b_len, dpl,\n                        NB_MODS - nb_mods + j, 1);\n            ptr = buf2;\n        } else {\n            ptr = buf2 + fft_len * j;\n        }\n        if (ntt_conv(s, buf1 + fft_len * j, ptr,\n                     fft_len_log2, fft_len_log2, j + NB_MODS - nb_mods))\n            goto fail;\n    }\n    if (!(mul_flags & FFT_MUL_R_NORESIZE))\n        bf_resize(res, 0); /* in case res == b and reduced mem */\n    ntt_free(s, buf2);\n    buf2 = NULL;\n    if (!(mul_flags & FFT_MUL_R_NORESIZE)) {\n        if (bf_resize(res, len))\n            goto fail;\n    }\n    ntt_to_limb(s, res->tab, len, buf1, fft_len_log2, dpl, nb_mods);\n    ntt_free(s, buf1);\n#if defined(USE_MUL_CHECK)\n    hr = mp_mod1(res->tab, len, BF_CHKSUM_MOD, 0);\n    h_ref = mul_mod(ha, hb, BF_CHKSUM_MOD);\n    if (hr != h_ref) {\n        printf(\"ntt_mul_error: len=%\" PRId_LIMB \" fft_len_log2=%d dpl=%d nb_mods=%d\\n\",\n               len, fft_len_log2, dpl, nb_mods);\n        //        printf(\"ha=0x\" FMT_LIMB\" hb=0x\" FMT_LIMB \" hr=0x\" FMT_LIMB \" expected=0x\" FMT_LIMB \"\\n\", ha, hb, hr, h_ref);\n        exit(1);\n    }\n#endif    \n    return 0;\n fail:\n    ntt_free(s, buf1);\n    ntt_free(s, buf2);\n    return -1;\n}\n\n#else /* USE_FFT_MUL */\n\nint bf_get_fft_size(int *pdpl, int *pnb_mods, limb_t len)\n{\n    return 0;\n}\n\n#endif /* !USE_FFT_MUL */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/libbf.h",
    "content": "/*\n * Tiny arbitrary precision floating point library\n * \n * Copyright (c) 2017-2021 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#ifndef LIBBF_H\n#define LIBBF_H\n\n#include <stddef.h>\n#include <stdint.h>\n\n#if INTPTR_MAX >= INT64_MAX\n#define LIMB_LOG2_BITS 6\n#else\n#define LIMB_LOG2_BITS 5\n#endif\n\n#define LIMB_BITS (1 << LIMB_LOG2_BITS)\n\n#if LIMB_BITS == 64\ntypedef __int128 int128_t;\ntypedef unsigned __int128 uint128_t;\ntypedef int64_t slimb_t;\ntypedef uint64_t limb_t;\ntypedef uint128_t dlimb_t;\n#define BF_RAW_EXP_MIN INT64_MIN\n#define BF_RAW_EXP_MAX INT64_MAX\n\n#define LIMB_DIGITS 19\n#define BF_DEC_BASE UINT64_C(10000000000000000000)\n\n#else\n\ntypedef int32_t slimb_t;\ntypedef uint32_t limb_t;\ntypedef uint64_t dlimb_t;\n#define BF_RAW_EXP_MIN INT32_MIN\n#define BF_RAW_EXP_MAX INT32_MAX\n\n#define LIMB_DIGITS 9\n#define BF_DEC_BASE 1000000000U\n\n#endif\n\n/* in bits */\n/* minimum number of bits for the exponent */\n#define BF_EXP_BITS_MIN 3\n/* maximum number of bits for the exponent */\n#define BF_EXP_BITS_MAX (LIMB_BITS - 3)\n/* extended range for exponent, used internally */\n#define BF_EXT_EXP_BITS_MAX (BF_EXP_BITS_MAX + 1)\n/* minimum possible precision */\n#define BF_PREC_MIN 2\n/* minimum possible precision */\n#define BF_PREC_MAX (((limb_t)1 << (LIMB_BITS - 2)) - 2)\n/* some operations support infinite precision */\n#define BF_PREC_INF (BF_PREC_MAX + 1) /* infinite precision */\n\n#if LIMB_BITS == 64\n#define BF_CHKSUM_MOD (UINT64_C(975620677) * UINT64_C(9795002197))\n#else\n#define BF_CHKSUM_MOD 975620677U\n#endif\n\n#define BF_EXP_ZERO BF_RAW_EXP_MIN\n#define BF_EXP_INF (BF_RAW_EXP_MAX - 1)\n#define BF_EXP_NAN BF_RAW_EXP_MAX\n\n/* +/-zero is represented with expn = BF_EXP_ZERO and len = 0,\n   +/-infinity is represented with expn = BF_EXP_INF and len = 0,\n   NaN is represented with expn = BF_EXP_NAN and len = 0 (sign is ignored)\n */\ntypedef struct {\n    struct bf_context_t *ctx;\n    int sign;\n    slimb_t expn;\n    limb_t len;\n    limb_t *tab;\n} bf_t;\n\ntypedef struct {\n    /* must be kept identical to bf_t */\n    struct bf_context_t *ctx;\n    int sign;\n    slimb_t expn;\n    limb_t len;\n    limb_t *tab;\n} bfdec_t;\n\ntypedef enum {\n    BF_RNDN, /* round to nearest, ties to even */\n    BF_RNDZ, /* round to zero */\n    BF_RNDD, /* round to -inf (the code relies on (BF_RNDD xor BF_RNDU) = 1) */\n    BF_RNDU, /* round to +inf */\n    BF_RNDNA, /* round to nearest, ties away from zero */\n    BF_RNDA, /* round away from zero */\n    BF_RNDF, /* faithful rounding (nondeterministic, either RNDD or RNDU,\n                inexact flag is always set)  */\n} bf_rnd_t;\n\n/* allow subnormal numbers. Only available if the number of exponent\n   bits is <= BF_EXP_BITS_USER_MAX and prec != BF_PREC_INF. */\n#define BF_FLAG_SUBNORMAL (1 << 3)\n/* 'prec' is the precision after the radix point instead of the whole\n   mantissa. Can only be used with bf_round() and\n   bfdec_[add|sub|mul|div|sqrt|round](). */\n#define BF_FLAG_RADPNT_PREC (1 << 4)\n\n#define BF_RND_MASK 0x7\n#define BF_EXP_BITS_SHIFT 5\n#define BF_EXP_BITS_MASK 0x3f\n\n/* shortcut for bf_set_exp_bits(BF_EXT_EXP_BITS_MAX) */\n#define BF_FLAG_EXT_EXP (BF_EXP_BITS_MASK << BF_EXP_BITS_SHIFT)\n\n/* contains the rounding mode and number of exponents bits */\ntypedef uint32_t bf_flags_t;\n\ntypedef void *bf_realloc_func_t(void *opaque, void *ptr, size_t size);\n\ntypedef struct {\n    bf_t val;\n    limb_t prec;\n} BFConstCache;\n\ntypedef struct bf_context_t {\n    void *realloc_opaque;\n    bf_realloc_func_t *realloc_func;\n    BFConstCache log2_cache;\n    BFConstCache pi_cache;\n    struct BFNTTState *ntt_state;\n} bf_context_t;\n\nstatic inline int bf_get_exp_bits(bf_flags_t flags)\n{\n    int e;\n    e = (flags >> BF_EXP_BITS_SHIFT) & BF_EXP_BITS_MASK;\n    if (e == BF_EXP_BITS_MASK)\n        return BF_EXP_BITS_MAX + 1;\n    else\n        return BF_EXP_BITS_MAX - e;\n}\n\nstatic inline bf_flags_t bf_set_exp_bits(int n)\n{\n    return ((BF_EXP_BITS_MAX - n) & BF_EXP_BITS_MASK) << BF_EXP_BITS_SHIFT;\n}\n\n/* returned status */\n#define BF_ST_INVALID_OP  (1 << 0)\n#define BF_ST_DIVIDE_ZERO (1 << 1)\n#define BF_ST_OVERFLOW    (1 << 2)\n#define BF_ST_UNDERFLOW   (1 << 3)\n#define BF_ST_INEXACT     (1 << 4)\n/* indicate that a memory allocation error occured. NaN is returned */\n#define BF_ST_MEM_ERROR   (1 << 5) \n\n#define BF_RADIX_MAX 36 /* maximum radix for bf_atof() and bf_ftoa() */\n\nstatic inline slimb_t bf_max(slimb_t a, slimb_t b)\n{\n    if (a > b)\n        return a;\n    else\n        return b;\n}\n\nstatic inline slimb_t bf_min(slimb_t a, slimb_t b)\n{\n    if (a < b)\n        return a;\n    else\n        return b;\n}\n\nvoid bf_context_init(bf_context_t *s, bf_realloc_func_t *realloc_func,\n                     void *realloc_opaque);\nvoid bf_context_end(bf_context_t *s);\n/* free memory allocated for the bf cache data */\nvoid bf_clear_cache(bf_context_t *s);\n\nstatic inline void *bf_realloc(bf_context_t *s, void *ptr, size_t size)\n{\n    return s->realloc_func(s->realloc_opaque, ptr, size);\n}\n\n/* 'size' must be != 0 */\nstatic inline void *bf_malloc(bf_context_t *s, size_t size)\n{\n    return bf_realloc(s, NULL, size);\n}\n\nstatic inline void bf_free(bf_context_t *s, void *ptr)\n{\n    /* must test ptr otherwise equivalent to malloc(0) */\n    if (ptr)\n        bf_realloc(s, ptr, 0);\n}\n\nvoid bf_init(bf_context_t *s, bf_t *r);\n\nstatic inline void bf_delete(bf_t *r)\n{\n    bf_context_t *s = r->ctx;\n    /* we accept to delete a zeroed bf_t structure */\n    if (s && r->tab) {\n        bf_realloc(s, r->tab, 0);\n    }\n}\n\nstatic inline void bf_neg(bf_t *r)\n{\n    r->sign ^= 1;\n}\n\nstatic inline int bf_is_finite(const bf_t *a)\n{\n    return (a->expn < BF_EXP_INF);\n}\n\nstatic inline int bf_is_nan(const bf_t *a)\n{\n    return (a->expn == BF_EXP_NAN);\n}\n\nstatic inline int bf_is_zero(const bf_t *a)\n{\n    return (a->expn == BF_EXP_ZERO);\n}\n\nstatic inline void bf_memcpy(bf_t *r, const bf_t *a)\n{\n    *r = *a;\n}\n\nint bf_set_ui(bf_t *r, uint64_t a);\nint bf_set_si(bf_t *r, int64_t a);\nvoid bf_set_nan(bf_t *r);\nvoid bf_set_zero(bf_t *r, int is_neg);\nvoid bf_set_inf(bf_t *r, int is_neg);\nint bf_set(bf_t *r, const bf_t *a);\nvoid bf_move(bf_t *r, bf_t *a);\nint bf_get_float64(const bf_t *a, double *pres, bf_rnd_t rnd_mode);\nint bf_set_float64(bf_t *a, double d);\n\nint bf_cmpu(const bf_t *a, const bf_t *b);\nint bf_cmp_full(const bf_t *a, const bf_t *b);\nint bf_cmp(const bf_t *a, const bf_t *b);\nstatic inline int bf_cmp_eq(const bf_t *a, const bf_t *b)\n{\n    return bf_cmp(a, b) == 0;\n}\n\nstatic inline int bf_cmp_le(const bf_t *a, const bf_t *b)\n{\n    return bf_cmp(a, b) <= 0;\n}\n\nstatic inline int bf_cmp_lt(const bf_t *a, const bf_t *b)\n{\n    return bf_cmp(a, b) < 0;\n}\n\nint bf_add(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags);\nint bf_sub(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags);\nint bf_add_si(bf_t *r, const bf_t *a, int64_t b1, limb_t prec, bf_flags_t flags);\nint bf_mul(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags);\nint bf_mul_ui(bf_t *r, const bf_t *a, uint64_t b1, limb_t prec, bf_flags_t flags);\nint bf_mul_si(bf_t *r, const bf_t *a, int64_t b1, limb_t prec, \n              bf_flags_t flags);\nint bf_mul_2exp(bf_t *r, slimb_t e, limb_t prec, bf_flags_t flags);\nint bf_div(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags);\n#define BF_DIVREM_EUCLIDIAN BF_RNDF\nint bf_divrem(bf_t *q, bf_t *r, const bf_t *a, const bf_t *b,\n              limb_t prec, bf_flags_t flags, int rnd_mode);\nint bf_rem(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n           bf_flags_t flags, int rnd_mode);\nint bf_remquo(slimb_t *pq, bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n              bf_flags_t flags, int rnd_mode);\n/* round to integer with infinite precision */\nint bf_rint(bf_t *r, int rnd_mode);\nint bf_round(bf_t *r, limb_t prec, bf_flags_t flags);\nint bf_sqrtrem(bf_t *r, bf_t *rem1, const bf_t *a);\nint bf_sqrt(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\nslimb_t bf_get_exp_min(const bf_t *a);\nint bf_logic_or(bf_t *r, const bf_t *a, const bf_t *b);\nint bf_logic_xor(bf_t *r, const bf_t *a, const bf_t *b);\nint bf_logic_and(bf_t *r, const bf_t *a, const bf_t *b);\n\n/* additional flags for bf_atof */\n/* do not accept hex radix prefix (0x or 0X) if radix = 0 or radix = 16 */\n#define BF_ATOF_NO_HEX       (1 << 16)\n/* accept binary (0b or 0B) or octal (0o or 0O) radix prefix if radix = 0 */\n#define BF_ATOF_BIN_OCT      (1 << 17)\n/* Do not parse NaN or Inf */\n#define BF_ATOF_NO_NAN_INF   (1 << 18)\n/* return the exponent separately */\n#define BF_ATOF_EXPONENT       (1 << 19)\n\nint bf_atof(bf_t *a, const char *str, const char **pnext, int radix,\n            limb_t prec, bf_flags_t flags);\n/* this version accepts prec = BF_PREC_INF and returns the radix\n   exponent */\nint bf_atof2(bf_t *r, slimb_t *pexponent,\n             const char *str, const char **pnext, int radix,\n             limb_t prec, bf_flags_t flags);\nint bf_mul_pow_radix(bf_t *r, const bf_t *T, limb_t radix,\n                     slimb_t expn, limb_t prec, bf_flags_t flags);\n\n\n/* Conversion of floating point number to string. Return a null\n   terminated string or NULL if memory error. *plen contains its\n   length if plen != NULL.  The exponent letter is \"e\" for base 10,\n   \"p\" for bases 2, 8, 16 with a binary exponent and \"@\" for the other\n   bases. */\n\n#define BF_FTOA_FORMAT_MASK (3 << 16)\n\n/* fixed format: prec significant digits rounded with (flags &\n   BF_RND_MASK). Exponential notation is used if too many zeros are\n   needed.*/\n#define BF_FTOA_FORMAT_FIXED (0 << 16)\n/* fractional format: prec digits after the decimal point rounded with\n   (flags & BF_RND_MASK) */\n#define BF_FTOA_FORMAT_FRAC  (1 << 16)\n/* free format: \n   \n   For binary radices with bf_ftoa() and for bfdec_ftoa(): use the minimum\n   number of digits to represent 'a'. The precision and the rounding\n   mode are ignored.\n   \n   For the non binary radices with bf_ftoa(): use as many digits as\n   necessary so that bf_atof() return the same number when using\n   precision 'prec', rounding to nearest and the subnormal\n   configuration of 'flags'. The result is meaningful only if 'a' is\n   already rounded to 'prec' bits. If the subnormal flag is set, the\n   exponent in 'flags' must also be set to the desired exponent range.\n*/\n#define BF_FTOA_FORMAT_FREE  (2 << 16)\n/* same as BF_FTOA_FORMAT_FREE but uses the minimum number of digits\n   (takes more computation time). Identical to BF_FTOA_FORMAT_FREE for\n   binary radices with bf_ftoa() and for bfdec_ftoa(). */\n#define BF_FTOA_FORMAT_FREE_MIN (3 << 16)\n\n/* force exponential notation for fixed or free format */\n#define BF_FTOA_FORCE_EXP    (1 << 20)\n/* add 0x prefix for base 16, 0o prefix for base 8 or 0b prefix for\n   base 2 if non zero value */\n#define BF_FTOA_ADD_PREFIX   (1 << 21)\n/* return \"Infinity\" instead of \"Inf\" and add a \"+\" for positive\n   exponents */\n#define BF_FTOA_JS_QUIRKS    (1 << 22)\n\nchar *bf_ftoa(size_t *plen, const bf_t *a, int radix, limb_t prec,\n              bf_flags_t flags);\n\n/* modulo 2^n instead of saturation. NaN and infinity return 0 */\n#define BF_GET_INT_MOD (1 << 0) \nint bf_get_int32(int *pres, const bf_t *a, int flags);\nint bf_get_int64(int64_t *pres, const bf_t *a, int flags);\nint bf_get_uint64(uint64_t *pres, const bf_t *a);\n\n/* the following functions are exported for testing only. */\nvoid mp_print_str(const char *str, const limb_t *tab, limb_t n);\nvoid bf_print_str(const char *str, const bf_t *a);\nint bf_resize(bf_t *r, limb_t len);\nint bf_get_fft_size(int *pdpl, int *pnb_mods, limb_t len);\nint bf_normalize_and_round(bf_t *r, limb_t prec1, bf_flags_t flags);\nint bf_can_round(const bf_t *a, slimb_t prec, bf_rnd_t rnd_mode, slimb_t k);\nslimb_t bf_mul_log2_radix(slimb_t a1, unsigned int radix, int is_inv,\n                          int is_ceil1);\nint mp_mul(bf_context_t *s, limb_t *result, \n           const limb_t *op1, limb_t op1_size, \n           const limb_t *op2, limb_t op2_size);\nlimb_t mp_add(limb_t *res, const limb_t *op1, const limb_t *op2, \n              limb_t n, limb_t carry);\nlimb_t mp_add_ui(limb_t *tab, limb_t b, size_t n);\nint mp_sqrtrem(bf_context_t *s, limb_t *tabs, limb_t *taba, limb_t n);\nint mp_recip(bf_context_t *s, limb_t *tabr, const limb_t *taba, limb_t n);\nlimb_t bf_isqrt(limb_t a);\n\n/* transcendental functions */\nint bf_const_log2(bf_t *T, limb_t prec, bf_flags_t flags);\nint bf_const_pi(bf_t *T, limb_t prec, bf_flags_t flags);\nint bf_exp(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\nint bf_log(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\n#define BF_POW_JS_QUIRKS (1 << 16) /* (+/-1)^(+/-Inf) = NaN, 1^NaN = NaN */\nint bf_pow(bf_t *r, const bf_t *x, const bf_t *y, limb_t prec, bf_flags_t flags);\nint bf_cos(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\nint bf_sin(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\nint bf_tan(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\nint bf_atan(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\nint bf_atan2(bf_t *r, const bf_t *y, const bf_t *x,\n             limb_t prec, bf_flags_t flags);\nint bf_asin(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\nint bf_acos(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\n\n/* decimal floating point */\n\nstatic inline void bfdec_init(bf_context_t *s, bfdec_t *r)\n{\n    bf_init(s, (bf_t *)r);\n}\nstatic inline void bfdec_delete(bfdec_t *r)\n{\n    bf_delete((bf_t *)r);\n}\n\nstatic inline void bfdec_neg(bfdec_t *r)\n{\n    r->sign ^= 1;\n}\n\nstatic inline int bfdec_is_finite(const bfdec_t *a)\n{\n    return (a->expn < BF_EXP_INF);\n}\n\nstatic inline int bfdec_is_nan(const bfdec_t *a)\n{\n    return (a->expn == BF_EXP_NAN);\n}\n\nstatic inline int bfdec_is_zero(const bfdec_t *a)\n{\n    return (a->expn == BF_EXP_ZERO);\n}\n\nstatic inline void bfdec_memcpy(bfdec_t *r, const bfdec_t *a)\n{\n    bf_memcpy((bf_t *)r, (const bf_t *)a);\n}\n\nint bfdec_set_ui(bfdec_t *r, uint64_t a);\nint bfdec_set_si(bfdec_t *r, int64_t a);\n\nstatic inline void bfdec_set_nan(bfdec_t *r)\n{\n    bf_set_nan((bf_t *)r);\n}\nstatic inline void bfdec_set_zero(bfdec_t *r, int is_neg)\n{\n    bf_set_zero((bf_t *)r, is_neg);\n}\nstatic inline void bfdec_set_inf(bfdec_t *r, int is_neg)\n{\n    bf_set_inf((bf_t *)r, is_neg);\n}\nstatic inline int bfdec_set(bfdec_t *r, const bfdec_t *a)\n{\n    return bf_set((bf_t *)r, (bf_t *)a);\n}\nstatic inline void bfdec_move(bfdec_t *r, bfdec_t *a)\n{\n    bf_move((bf_t *)r, (bf_t *)a);\n}\nstatic inline int bfdec_cmpu(const bfdec_t *a, const bfdec_t *b)\n{\n    return bf_cmpu((const bf_t *)a, (const bf_t *)b);\n}\nstatic inline int bfdec_cmp_full(const bfdec_t *a, const bfdec_t *b)\n{\n    return bf_cmp_full((const bf_t *)a, (const bf_t *)b);\n}\nstatic inline int bfdec_cmp(const bfdec_t *a, const bfdec_t *b)\n{\n    return bf_cmp((const bf_t *)a, (const bf_t *)b);\n}\nstatic inline int bfdec_cmp_eq(const bfdec_t *a, const bfdec_t *b)\n{\n    return bfdec_cmp(a, b) == 0;\n}\nstatic inline int bfdec_cmp_le(const bfdec_t *a, const bfdec_t *b)\n{\n    return bfdec_cmp(a, b) <= 0;\n}\nstatic inline int bfdec_cmp_lt(const bfdec_t *a, const bfdec_t *b)\n{\n    return bfdec_cmp(a, b) < 0;\n}\n\nint bfdec_add(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags);\nint bfdec_sub(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags);\nint bfdec_add_si(bfdec_t *r, const bfdec_t *a, int64_t b1, limb_t prec,\n                 bf_flags_t flags);\nint bfdec_mul(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags);\nint bfdec_mul_si(bfdec_t *r, const bfdec_t *a, int64_t b1, limb_t prec,\n                 bf_flags_t flags);\nint bfdec_div(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags);\nint bfdec_divrem(bfdec_t *q, bfdec_t *r, const bfdec_t *a, const bfdec_t *b,\n                 limb_t prec, bf_flags_t flags, int rnd_mode);\nint bfdec_rem(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags, int rnd_mode);\nint bfdec_rint(bfdec_t *r, int rnd_mode);\nint bfdec_sqrt(bfdec_t *r, const bfdec_t *a, limb_t prec, bf_flags_t flags);\nint bfdec_round(bfdec_t *r, limb_t prec, bf_flags_t flags);\nint bfdec_get_int32(int *pres, const bfdec_t *a);\nint bfdec_pow_ui(bfdec_t *r, const bfdec_t *a, limb_t b);\n\nchar *bfdec_ftoa(size_t *plen, const bfdec_t *a, limb_t prec, bf_flags_t flags);\nint bfdec_atof(bfdec_t *r, const char *str, const char **pnext,\n               limb_t prec, bf_flags_t flags);\n\n/* the following functions are exported for testing only. */\nextern const limb_t mp_pow_dec[LIMB_DIGITS + 1];\nvoid bfdec_print_str(const char *str, const bfdec_t *a);\nstatic inline int bfdec_resize(bfdec_t *r, limb_t len)\n{\n    return bf_resize((bf_t *)r, len);\n}\nint bfdec_normalize_and_round(bfdec_t *r, limb_t prec1, bf_flags_t flags);\n\n#endif /* LIBBF_H */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/libregexp-opcode.h",
    "content": "/*\n * Regular Expression Engine\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n#ifdef DEF\n\nDEF(invalid, 1) /* never used */\nDEF(char, 3)\nDEF(char32, 5)\nDEF(dot, 1)\nDEF(any, 1) /* same as dot but match any character including line terminator */\nDEF(line_start, 1)\nDEF(line_end, 1)\nDEF(goto, 5)\nDEF(split_goto_first, 5)\nDEF(split_next_first, 5)\nDEF(match, 1)\nDEF(save_start, 2) /* save start position */\nDEF(save_end, 2) /* save end position, must come after saved_start */\nDEF(save_reset, 3) /* reset save positions */\nDEF(loop, 5) /* decrement the top the stack and goto if != 0 */\nDEF(push_i32, 5) /* push integer on the stack */\nDEF(drop, 1)\nDEF(word_boundary, 1)\nDEF(not_word_boundary, 1)\nDEF(back_reference, 2)\nDEF(backward_back_reference, 2) /* must come after back_reference */\nDEF(range, 3) /* variable length */\nDEF(range32, 3) /* variable length */\nDEF(lookahead, 5)\nDEF(negative_lookahead, 5)\nDEF(push_char_pos, 1) /* push the character position on the stack */\nDEF(bne_char_pos, 5) /* pop one stack element and jump if equal to the character\n position */\nDEF(prev, 1) /* go to the previous char */\nDEF(simple_greedy_quant, 17)\n\n#endif /* DEF */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/libregexp.c",
    "content": "/*\n * Regular Expression Engine\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <inttypes.h>\n#include <string.h>\n#include <assert.h>\n\n#include \"cutils.h\"\n#include \"libregexp.h\"\n\n/*\n  TODO:\n\n  - Add full unicode canonicalize rules for character ranges (not\n    really useful but needed for exact \"ignorecase\" compatibility).\n\n  - Add a lock step execution mode (=linear time execution guaranteed)\n    when the regular expression is \"simple\" i.e. no backreference nor\n    complicated lookahead. The opcodes are designed for this execution\n    model.\n*/\n\n#if defined(TEST)\n#define DUMP_REOP\n#endif\n\ntypedef enum {\n#define DEF(id, size) REOP_ ## id,\n#include \"libregexp-opcode.h\"\n#undef DEF\n    REOP_COUNT,\n} REOPCodeEnum;\n\n#define CAPTURE_COUNT_MAX 255\n#define STACK_SIZE_MAX 255\n\n/* unicode code points */\n#define CP_LS   0x2028\n#define CP_PS   0x2029\n\n#define TMP_BUF_SIZE 128\n\ntypedef struct {\n    DynBuf byte_code;\n    const uint8_t *buf_ptr;\n    const uint8_t *buf_end;\n    const uint8_t *buf_start;\n    int re_flags;\n    BOOL is_utf16;\n    BOOL ignore_case;\n    BOOL dotall;\n    int capture_count;\n    int total_capture_count; /* -1 = not computed yet */\n    int has_named_captures; /* -1 = don't know, 0 = no, 1 = yes */\n    void *opaque;\n    DynBuf group_names;\n    union {\n        char error_msg[TMP_BUF_SIZE];\n        char tmp_buf[TMP_BUF_SIZE];\n    } u;\n} REParseState;\n\ntypedef struct {\n#ifdef DUMP_REOP\n    const char *name;\n#endif\n    uint8_t size;\n} REOpCode;\n\nstatic const REOpCode reopcode_info[REOP_COUNT] = {\n#ifdef DUMP_REOP\n#define DEF(id, size) { #id, size },\n#else\n#define DEF(id, size) { size },\n#endif\n#include \"libregexp-opcode.h\"\n#undef DEF\n};\n\n#define RE_HEADER_FLAGS         0\n#define RE_HEADER_CAPTURE_COUNT 1\n#define RE_HEADER_STACK_SIZE    2\n\n#define RE_HEADER_LEN 7\n\nstatic inline int is_digit(int c) {\n    return c >= '0' && c <= '9';\n}\n\n/* insert 'len' bytes at position 'pos'. Return < 0 if error. */\nstatic int dbuf_insert(DynBuf *s, int pos, int len)\n{\n    if (dbuf_realloc(s, s->size + len))\n        return -1;\n    memmove(s->buf + pos + len, s->buf + pos, s->size - pos);\n    s->size += len;\n    return 0;\n}\n\n/* canonicalize with the specific JS regexp rules */\nstatic uint32_t lre_canonicalize(uint32_t c, BOOL is_utf16)\n{\n    uint32_t res[LRE_CC_RES_LEN_MAX];\n    int len;\n    if (is_utf16) {\n        if (likely(c < 128)) {\n            if (c >= 'A' && c <= 'Z')\n                c = c - 'A' + 'a';\n        } else {\n            lre_case_conv(res, c, 2);\n            c = res[0];\n        }\n    } else {\n        if (likely(c < 128)) {\n            if (c >= 'a' && c <= 'z')\n                c = c - 'a' + 'A';\n        } else {\n            /* legacy regexp: to upper case if single char >= 128 */\n            len = lre_case_conv(res, c, FALSE);\n            if (len == 1 && res[0] >= 128)\n                c = res[0];\n        }\n    }\n    return c;\n}\n\nstatic const uint16_t char_range_d[] = {\n    1,\n    0x0030, 0x0039 + 1,\n};\n\n/* code point ranges for Zs,Zl or Zp property */\nstatic const uint16_t char_range_s[] = {\n    10,\n    0x0009, 0x000D + 1,\n    0x0020, 0x0020 + 1,\n    0x00A0, 0x00A0 + 1,\n    0x1680, 0x1680 + 1,\n    0x2000, 0x200A + 1,\n    /* 2028;LINE SEPARATOR;Zl;0;WS;;;;;N;;;;; */\n    /* 2029;PARAGRAPH SEPARATOR;Zp;0;B;;;;;N;;;;; */\n    0x2028, 0x2029 + 1,\n    0x202F, 0x202F + 1,\n    0x205F, 0x205F + 1,\n    0x3000, 0x3000 + 1,\n    /* FEFF;ZERO WIDTH NO-BREAK SPACE;Cf;0;BN;;;;;N;BYTE ORDER MARK;;;; */\n    0xFEFF, 0xFEFF + 1,\n};\n\nBOOL lre_is_space(int c)\n{\n    int i, n, low, high;\n    n = (countof(char_range_s) - 1) / 2;\n    for(i = 0; i < n; i++) {\n        low = char_range_s[2 * i + 1];\n        if (c < low)\n            return FALSE;\n        high = char_range_s[2 * i + 2];\n        if (c < high)\n            return TRUE;\n    }\n    return FALSE;\n}\n\nuint32_t const lre_id_start_table_ascii[4] = {\n    /* $ A-Z _ a-z */\n    0x00000000, 0x00000010, 0x87FFFFFE, 0x07FFFFFE\n};\n\nuint32_t const lre_id_continue_table_ascii[4] = {\n    /* $ 0-9 A-Z _ a-z */\n    0x00000000, 0x03FF0010, 0x87FFFFFE, 0x07FFFFFE\n};\n\n\nstatic const uint16_t char_range_w[] = {\n    4,\n    0x0030, 0x0039 + 1,\n    0x0041, 0x005A + 1,\n    0x005F, 0x005F + 1,\n    0x0061, 0x007A + 1,\n};\n\n#define CLASS_RANGE_BASE 0x40000000\n\ntypedef enum {\n    CHAR_RANGE_d,\n    CHAR_RANGE_D,\n    CHAR_RANGE_s,\n    CHAR_RANGE_S,\n    CHAR_RANGE_w,\n    CHAR_RANGE_W,\n} CharRangeEnum;\n\nstatic const uint16_t *char_range_table[] = {\n    char_range_d,\n    char_range_s,\n    char_range_w,\n};\n\nstatic int cr_init_char_range(REParseState *s, CharRange *cr, uint32_t c)\n{\n    BOOL invert;\n    const uint16_t *c_pt;\n    int len, i;\n    \n    invert = c & 1;\n    c_pt = char_range_table[c >> 1];\n    len = *c_pt++;\n    cr_init(cr, s->opaque, lre_realloc);\n    for(i = 0; i < len * 2; i++) {\n        if (cr_add_point(cr, c_pt[i]))\n            goto fail;\n    }\n    if (invert) {\n        if (cr_invert(cr))\n            goto fail;\n    }\n    return 0;\n fail:\n    cr_free(cr);\n    return -1;\n}\n\nstatic int cr_canonicalize(CharRange *cr)\n{\n    CharRange a;\n    uint32_t pt[2];\n    int i, ret;\n\n    cr_init(&a, cr->mem_opaque, lre_realloc);\n    pt[0] = 'a';\n    pt[1] = 'z' + 1;\n    ret = cr_op(&a, cr->points, cr->len, pt, 2, CR_OP_INTER);\n    if (ret)\n        goto fail;\n    /* convert to upper case */\n    /* XXX: the generic unicode case would be much more complicated\n       and not really useful */\n    for(i = 0; i < a.len; i++) {\n        a.points[i] += 'A' - 'a';\n    }\n    /* Note: for simplicity we keep the lower case ranges */\n    ret = cr_union1(cr, a.points, a.len);\n fail:\n    cr_free(&a);\n    return ret;\n}\n\n#ifdef DUMP_REOP\nstatic __maybe_unused void lre_dump_bytecode(const uint8_t *buf,\n                                                     int buf_len)\n{\n    int pos, len, opcode, bc_len, re_flags, i;\n    uint32_t val;\n    \n    assert(buf_len >= RE_HEADER_LEN);\n\n    re_flags=  buf[0];\n    bc_len = get_u32(buf + 3);\n    assert(bc_len + RE_HEADER_LEN <= buf_len);\n    printf(\"flags: 0x%x capture_count=%d stack_size=%d\\n\",\n           re_flags, buf[1], buf[2]);\n    if (re_flags & LRE_FLAG_NAMED_GROUPS) {\n        const char *p;\n        p = (char *)buf + RE_HEADER_LEN + bc_len;\n        printf(\"named groups: \");\n        for(i = 1; i < buf[1]; i++) {\n            if (i != 1)\n                printf(\",\");\n            printf(\"<%s>\", p);\n            p += strlen(p) + 1;\n        }\n        printf(\"\\n\");\n        assert(p == (char *)(buf + buf_len));\n    }\n    printf(\"bytecode_len=%d\\n\", bc_len);\n\n    buf += RE_HEADER_LEN;\n    pos = 0;\n    while (pos < bc_len) {\n        printf(\"%5u: \", pos);\n        opcode = buf[pos];\n        len = reopcode_info[opcode].size;\n        if (opcode >= REOP_COUNT) {\n            printf(\" invalid opcode=0x%02x\\n\", opcode);\n            break;\n        }\n        if ((pos + len) > bc_len) {\n            printf(\" buffer overflow (opcode=0x%02x)\\n\", opcode);\n            break;\n        }\n        printf(\"%s\", reopcode_info[opcode].name);\n        switch(opcode) {\n        case REOP_char:\n            val = get_u16(buf + pos + 1);\n            if (val >= ' ' && val <= 126)\n                printf(\" '%c'\", val);\n            else\n                printf(\" 0x%04x\", val);\n            break;\n        case REOP_char32:\n            val = get_u32(buf + pos + 1);\n            if (val >= ' ' && val <= 126)\n                printf(\" '%c'\", val);\n            else\n                printf(\" 0x%08x\", val);\n            break;\n        case REOP_goto:\n        case REOP_split_goto_first:\n        case REOP_split_next_first:\n        case REOP_loop:\n        case REOP_lookahead:\n        case REOP_negative_lookahead:\n        case REOP_bne_char_pos:\n            val = get_u32(buf + pos + 1);\n            val += (pos + 5);\n            printf(\" %u\", val);\n            break;\n        case REOP_simple_greedy_quant:\n            printf(\" %u %u %u %u\",\n                   get_u32(buf + pos + 1) + (pos + 17),\n                   get_u32(buf + pos + 1 + 4),\n                   get_u32(buf + pos + 1 + 8),\n                   get_u32(buf + pos + 1 + 12));\n            break;\n        case REOP_save_start:\n        case REOP_save_end:\n        case REOP_back_reference:\n        case REOP_backward_back_reference:\n            printf(\" %u\", buf[pos + 1]);\n            break;\n        case REOP_save_reset:\n            printf(\" %u %u\", buf[pos + 1], buf[pos + 2]);\n            break;\n        case REOP_push_i32:\n            val = get_u32(buf + pos + 1);\n            printf(\" %d\", val);\n            break;\n        case REOP_range:\n            {\n                int n, i;\n                n = get_u16(buf + pos + 1);\n                len += n * 4;\n                for(i = 0; i < n * 2; i++) {\n                    val = get_u16(buf + pos + 3 + i * 2);\n                    printf(\" 0x%04x\", val);\n                }\n            }\n            break;\n        case REOP_range32:\n            {\n                int n, i;\n                n = get_u16(buf + pos + 1);\n                len += n * 8;\n                for(i = 0; i < n * 2; i++) {\n                    val = get_u32(buf + pos + 3 + i * 4);\n                    printf(\" 0x%08x\", val);\n                }\n            }\n            break;\n        default:\n            break;\n        }\n        printf(\"\\n\");\n        pos += len;\n    }\n}\n#endif\n\nstatic void re_emit_op(REParseState *s, int op)\n{\n    dbuf_putc(&s->byte_code, op);\n}\n\n/* return the offset of the u32 value */\nstatic int re_emit_op_u32(REParseState *s, int op, uint32_t val)\n{\n    int pos;\n    dbuf_putc(&s->byte_code, op);\n    pos = s->byte_code.size;\n    dbuf_put_u32(&s->byte_code, val);\n    return pos;\n}\n\nstatic int re_emit_goto(REParseState *s, int op, uint32_t val)\n{\n    int pos;\n    dbuf_putc(&s->byte_code, op);\n    pos = s->byte_code.size;\n    dbuf_put_u32(&s->byte_code, val - (pos + 4));\n    return pos;\n}\n\nstatic void re_emit_op_u8(REParseState *s, int op, uint32_t val)\n{\n    dbuf_putc(&s->byte_code, op);\n    dbuf_putc(&s->byte_code, val);\n}\n\nstatic void re_emit_op_u16(REParseState *s, int op, uint32_t val)\n{\n    dbuf_putc(&s->byte_code, op);\n    dbuf_put_u16(&s->byte_code, val);\n}\n\nstatic int __attribute__((format(printf, 2, 3))) re_parse_error(REParseState *s, const char *fmt, ...)\n{\n    va_list ap;\n    va_start(ap, fmt);\n    vsnprintf(s->u.error_msg, sizeof(s->u.error_msg), fmt, ap);\n    va_end(ap);\n    return -1;\n}\n\nstatic int re_parse_out_of_memory(REParseState *s)\n{\n    return re_parse_error(s, \"out of memory\");\n}\n\n/* If allow_overflow is false, return -1 in case of\n   overflow. Otherwise return INT32_MAX. */\nstatic int parse_digits(const uint8_t **pp, BOOL allow_overflow)\n{\n    const uint8_t *p;\n    uint64_t v;\n    int c;\n    \n    p = *pp;\n    v = 0;\n    for(;;) {\n        c = *p;\n        if (c < '0' || c > '9')\n            break;\n        v = v * 10 + c - '0';\n        if (v >= INT32_MAX) {\n            if (allow_overflow)\n                v = INT32_MAX;\n            else\n                return -1;\n        }\n        p++;\n    }\n    *pp = p;\n    return v;\n}\n\nstatic int re_parse_expect(REParseState *s, const uint8_t **pp, int c)\n{\n    const uint8_t *p;\n    p = *pp;\n    if (*p != c)\n        return re_parse_error(s, \"expecting '%c'\", c);\n    p++;\n    *pp = p;\n    return 0;\n}\n\n/* Parse an escape sequence, *pp points after the '\\':\n   allow_utf16 value:\n   0 : no UTF-16 escapes allowed\n   1 : UTF-16 escapes allowed\n   2 : UTF-16 escapes allowed and escapes of surrogate pairs are\n   converted to a unicode character (unicode regexp case).\n\n   Return the unicode char and update *pp if recognized,\n   return -1 if malformed escape,\n   return -2 otherwise. */\nint lre_parse_escape(const uint8_t **pp, int allow_utf16)\n{\n    const uint8_t *p;\n    uint32_t c;\n\n    p = *pp;\n    c = *p++;\n    switch(c) {\n    case 'b':\n        c = '\\b';\n        break;\n    case 'f':\n        c = '\\f';\n        break;\n    case 'n':\n        c = '\\n';\n        break;\n    case 'r':\n        c = '\\r';\n        break;\n    case 't':\n        c = '\\t';\n        break;\n    case 'v':\n        c = '\\v';\n        break;\n    case 'x':\n    case 'u':\n        {\n            int h, n, i;\n            uint32_t c1;\n            \n            if (*p == '{' && allow_utf16) {\n                p++;\n                c = 0;\n                for(;;) {\n                    h = from_hex(*p++);\n                    if (h < 0)\n                        return -1;\n                    c = (c << 4) | h;\n                    if (c > 0x10FFFF)\n                        return -1;\n                    if (*p == '}')\n                        break;\n                }\n                p++;\n            } else {\n                if (c == 'x') {\n                    n = 2;\n                } else {\n                    n = 4;\n                }\n\n                c = 0;\n                for(i = 0; i < n; i++) {\n                    h = from_hex(*p++);\n                    if (h < 0) {\n                        return -1;\n                    }\n                    c = (c << 4) | h;\n                }\n                if (c >= 0xd800 && c < 0xdc00 &&\n                    allow_utf16 == 2 && p[0] == '\\\\' && p[1] == 'u') {\n                    /* convert an escaped surrogate pair into a\n                       unicode char */\n                    c1 = 0;\n                    for(i = 0; i < 4; i++) {\n                        h = from_hex(p[2 + i]);\n                        if (h < 0)\n                            break;\n                        c1 = (c1 << 4) | h;\n                    }\n                    if (i == 4 && c1 >= 0xdc00 && c1 < 0xe000) {\n                        p += 6;\n                        c = (((c & 0x3ff) << 10) | (c1 & 0x3ff)) + 0x10000;\n                    }\n                }\n            }\n        }\n        break;\n    case '0': case '1': case '2': case '3':\n    case '4': case '5': case '6': case '7':\n        c -= '0';\n        if (allow_utf16 == 2) {\n            /* only accept \\0 not followed by digit */\n            if (c != 0 || is_digit(*p))\n                return -1;\n        } else {\n            /* parse a legacy octal sequence */\n            uint32_t v;\n            v = *p - '0';\n            if (v > 7)\n                break;\n            c = (c << 3) | v;\n            p++;\n            if (c >= 32)\n                break;\n            v = *p - '0';\n            if (v > 7)\n                break;\n            c = (c << 3) | v;\n            p++;\n        }\n        break;\n    default:\n        return -2;\n    }\n    *pp = p;\n    return c;\n}\n\n#ifdef CONFIG_ALL_UNICODE\n/* XXX: we use the same chars for name and value */\nstatic BOOL is_unicode_char(int c)\n{\n    return ((c >= '0' && c <= '9') ||\n            (c >= 'A' && c <= 'Z') ||\n            (c >= 'a' && c <= 'z') ||\n            (c == '_'));\n}\n\nstatic int parse_unicode_property(REParseState *s, CharRange *cr,\n                                  const uint8_t **pp, BOOL is_inv)\n{\n    const uint8_t *p;\n    char name[64], value[64];\n    char *q;\n    BOOL script_ext;\n    int ret;\n\n    p = *pp;\n    if (*p != '{')\n        return re_parse_error(s, \"expecting '{' after \\\\p\");\n    p++;\n    q = name;\n    while (is_unicode_char(*p)) {\n        if ((q - name) >= sizeof(name) - 1)\n            goto unknown_property_name;\n        *q++ = *p++;\n    }\n    *q = '\\0';\n    q = value;\n    if (*p == '=') {\n        p++;\n        while (is_unicode_char(*p)) {\n            if ((q - value) >= sizeof(value) - 1)\n                return re_parse_error(s, \"unknown unicode property value\");\n            *q++ = *p++;\n        }\n    }\n    *q = '\\0';\n    if (*p != '}')\n        return re_parse_error(s, \"expecting '}'\");\n    p++;\n    //    printf(\"name=%s value=%s\\n\", name, value);\n\n    if (!strcmp(name, \"Script\") || !strcmp(name, \"sc\")) {\n        script_ext = FALSE;\n        goto do_script;\n    } else if (!strcmp(name, \"Script_Extensions\") || !strcmp(name, \"scx\")) {\n        script_ext = TRUE;\n    do_script:\n        cr_init(cr, s->opaque, lre_realloc);\n        ret = unicode_script(cr, value, script_ext);\n        if (ret) {\n            cr_free(cr);\n            if (ret == -2)\n                return re_parse_error(s, \"unknown unicode script\");\n            else\n                goto out_of_memory;\n        }\n    } else if (!strcmp(name, \"General_Category\") || !strcmp(name, \"gc\")) {\n        cr_init(cr, s->opaque, lre_realloc);\n        ret = unicode_general_category(cr, value);\n        if (ret) {\n            cr_free(cr);\n            if (ret == -2)\n                return re_parse_error(s, \"unknown unicode general category\");\n            else\n                goto out_of_memory;\n        }\n    } else if (value[0] == '\\0') {\n        cr_init(cr, s->opaque, lre_realloc);\n        ret = unicode_general_category(cr, name);\n        if (ret == -1) {\n            cr_free(cr);\n            goto out_of_memory;\n        }\n        if (ret < 0) {\n            ret = unicode_prop(cr, name);\n            if (ret) {\n                cr_free(cr);\n                if (ret == -2)\n                    goto unknown_property_name;\n                else\n                    goto out_of_memory;\n            }\n        }\n    } else {\n    unknown_property_name:\n        return re_parse_error(s, \"unknown unicode property name\");\n    }\n\n    if (is_inv) {\n        if (cr_invert(cr)) {\n            cr_free(cr);\n            return -1;\n        }\n    }\n    *pp = p;\n    return 0;\n out_of_memory:\n    return re_parse_out_of_memory(s);\n}\n#endif /* CONFIG_ALL_UNICODE */\n\n/* return -1 if error otherwise the character or a class range\n   (CLASS_RANGE_BASE). In case of class range, 'cr' is\n   initialized. Otherwise, it is ignored. */\nstatic int get_class_atom(REParseState *s, CharRange *cr,\n                          const uint8_t **pp, BOOL inclass)\n{\n    const uint8_t *p;\n    uint32_t c;\n    int ret;\n    \n    p = *pp;\n\n    c = *p;\n    switch(c) {\n    case '\\\\':\n        p++;\n        if (p >= s->buf_end)\n            goto unexpected_end;\n        c = *p++;\n        switch(c) {\n        case 'd':\n            c = CHAR_RANGE_d;\n            goto class_range;\n        case 'D':\n            c = CHAR_RANGE_D;\n            goto class_range;\n        case 's':\n            c = CHAR_RANGE_s;\n            goto class_range;\n        case 'S':\n            c = CHAR_RANGE_S;\n            goto class_range;\n        case 'w':\n            c = CHAR_RANGE_w;\n            goto class_range;\n        case 'W':\n            c = CHAR_RANGE_W;\n        class_range:\n            if (cr_init_char_range(s, cr, c))\n                return -1;\n            c = CLASS_RANGE_BASE;\n            break;\n        case 'c':\n            c = *p;\n            if ((c >= 'a' && c <= 'z') ||\n                (c >= 'A' && c <= 'Z') ||\n                (((c >= '0' && c <= '9') || c == '_') &&\n                 inclass && !s->is_utf16)) {   /* Annex B.1.4 */\n                c &= 0x1f;\n                p++;\n            } else if (s->is_utf16) {\n                goto invalid_escape;\n            } else {\n                /* otherwise return '\\' and 'c' */\n                p--;\n                c = '\\\\';\n            }\n            break;\n#ifdef CONFIG_ALL_UNICODE\n        case 'p':\n        case 'P':\n            if (s->is_utf16) {\n                if (parse_unicode_property(s, cr, &p, (c == 'P')))\n                    return -1;\n                c = CLASS_RANGE_BASE;\n                break;\n            }\n            /* fall thru */\n#endif\n        default:\n            p--;\n            ret = lre_parse_escape(&p, s->is_utf16 * 2);\n            if (ret >= 0) {\n                c = ret;\n            } else {\n                if (ret == -2 && *p != '\\0' && strchr(\"^$\\\\.*+?()[]{}|/\", *p)) {\n                    /* always valid to escape these characters */\n                    goto normal_char;\n                } else if (s->is_utf16) {\n                invalid_escape:\n                    return re_parse_error(s, \"invalid escape sequence in regular expression\");\n                } else {\n                    /* just ignore the '\\' */\n                    goto normal_char;\n                }\n            }\n            break;\n        }\n        break;\n    case '\\0':\n        if (p >= s->buf_end) {\n        unexpected_end:\n            return re_parse_error(s, \"unexpected end\");\n        }\n        /* fall thru */\n    default:\n    normal_char:\n        /* normal char */\n        if (c >= 128) {\n            c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);\n            if ((unsigned)c > 0xffff && !s->is_utf16) {\n                /* XXX: should handle non BMP-1 code points */\n                return re_parse_error(s, \"malformed unicode char\");\n            }\n        } else {\n            p++;\n        }\n        break;\n    }\n    *pp = p;\n    return c;\n}\n\nstatic int re_emit_range(REParseState *s, const CharRange *cr)\n{\n    int len, i;\n    uint32_t high;\n    \n    len = (unsigned)cr->len / 2;\n    if (len >= 65535)\n        return re_parse_error(s, \"too many ranges\");\n    if (len == 0) {\n        /* not sure it can really happen. Emit a match that is always\n           false */\n        re_emit_op_u32(s, REOP_char32, -1);\n    } else {\n        high = cr->points[cr->len - 1];\n        if (high == UINT32_MAX)\n            high = cr->points[cr->len - 2];\n        if (high <= 0xffff) {\n            /* can use 16 bit ranges with the conversion that 0xffff =\n               infinity */\n            re_emit_op_u16(s, REOP_range, len);\n            for(i = 0; i < cr->len; i += 2) {\n                dbuf_put_u16(&s->byte_code, cr->points[i]);\n                high = cr->points[i + 1] - 1;\n                if (high == UINT32_MAX - 1)\n                    high = 0xffff;\n                dbuf_put_u16(&s->byte_code, high);\n            }\n        } else {\n            re_emit_op_u16(s, REOP_range32, len);\n            for(i = 0; i < cr->len; i += 2) {\n                dbuf_put_u32(&s->byte_code, cr->points[i]);\n                dbuf_put_u32(&s->byte_code, cr->points[i + 1] - 1);\n            }\n        }\n    }\n    return 0;\n}\n\nstatic int re_parse_char_class(REParseState *s, const uint8_t **pp)\n{\n    const uint8_t *p;\n    uint32_t c1, c2;\n    CharRange cr_s, *cr = &cr_s;\n    CharRange cr1_s, *cr1 = &cr1_s;\n    BOOL invert;\n    \n    cr_init(cr, s->opaque, lre_realloc);\n    p = *pp;\n    p++;    /* skip '[' */\n    invert = FALSE;\n    if (*p == '^') {\n        p++;\n        invert = TRUE;\n    }\n    for(;;) {\n        if (*p == ']')\n            break;\n        c1 = get_class_atom(s, cr1, &p, TRUE);\n        if ((int)c1 < 0)\n            goto fail;\n        if (*p == '-' && p[1] != ']') {\n            const uint8_t *p0 = p + 1;\n            if (c1 >= CLASS_RANGE_BASE) {\n                if (s->is_utf16) {\n                    cr_free(cr1);\n                    goto invalid_class_range;\n                }\n                /* Annex B: match '-' character */\n                goto class_atom;\n            }\n            c2 = get_class_atom(s, cr1, &p0, TRUE);\n            if ((int)c2 < 0)\n                goto fail;\n            if (c2 >= CLASS_RANGE_BASE) {\n                cr_free(cr1);\n                if (s->is_utf16) {\n                    goto invalid_class_range;\n                }\n                /* Annex B: match '-' character */\n                goto class_atom;\n            }\n            p = p0;\n            if (c2 < c1) {\n            invalid_class_range:\n                re_parse_error(s, \"invalid class range\");\n                goto fail;\n            }\n            if (cr_union_interval(cr, c1, c2))\n                goto memory_error;\n        } else {\n        class_atom:\n            if (c1 >= CLASS_RANGE_BASE) {\n                int ret;\n                ret = cr_union1(cr, cr1->points, cr1->len);\n                cr_free(cr1);\n                if (ret)\n                    goto memory_error;\n            } else {\n                if (cr_union_interval(cr, c1, c1))\n                    goto memory_error;\n            }\n        }\n    }\n    if (s->ignore_case) {\n        if (cr_canonicalize(cr))\n            goto memory_error;\n    }\n    if (invert) {\n        if (cr_invert(cr))\n            goto memory_error;\n    }\n    if (re_emit_range(s, cr))\n        goto fail;\n    cr_free(cr);\n    p++;    /* skip ']' */\n    *pp = p;\n    return 0;\n memory_error:\n    re_parse_out_of_memory(s);\n fail:\n    cr_free(cr);\n    return -1;\n}\n\n/* Return:\n   1 if the opcodes in bc_buf[] always advance the character pointer.\n   0 if the character pointer may not be advanced.\n   -1 if the code may depend on side effects of its previous execution (backreference)\n*/\nstatic int re_check_advance(const uint8_t *bc_buf, int bc_buf_len)\n{\n    int pos, opcode, ret, len, i;\n    uint32_t val, last;\n    BOOL has_back_reference;\n    uint8_t capture_bitmap[CAPTURE_COUNT_MAX];\n    \n    ret = -2; /* not known yet */\n    pos = 0;\n    has_back_reference = FALSE;\n    memset(capture_bitmap, 0, sizeof(capture_bitmap));\n    \n    while (pos < bc_buf_len) {\n        opcode = bc_buf[pos];\n        len = reopcode_info[opcode].size;\n        switch(opcode) {\n        case REOP_range:\n            val = get_u16(bc_buf + pos + 1);\n            len += val * 4;\n            goto simple_char;\n        case REOP_range32:\n            val = get_u16(bc_buf + pos + 1);\n            len += val * 8;\n            goto simple_char;\n        case REOP_char:\n        case REOP_char32:\n        case REOP_dot:\n        case REOP_any:\n        simple_char:\n            if (ret == -2)\n                ret = 1;\n            break;\n        case REOP_line_start:\n        case REOP_line_end:\n        case REOP_push_i32:\n        case REOP_push_char_pos:\n        case REOP_drop:\n        case REOP_word_boundary:\n        case REOP_not_word_boundary:\n        case REOP_prev:\n            /* no effect */\n            break;\n        case REOP_save_start:\n        case REOP_save_end:\n            val = bc_buf[pos + 1];\n            capture_bitmap[val] |= 1;\n            break;\n        case REOP_save_reset:\n            {\n                val = bc_buf[pos + 1];\n                last = bc_buf[pos + 2];\n                while (val < last)\n                    capture_bitmap[val++] |= 1;\n            }\n            break;\n        case REOP_back_reference:\n        case REOP_backward_back_reference:\n            val = bc_buf[pos + 1];\n            capture_bitmap[val] |= 2;\n            has_back_reference = TRUE;\n            break;\n        default:\n            /* safe behvior: we cannot predict the outcome */\n            if (ret == -2)\n                ret = 0;\n            break;\n        }\n        pos += len;\n    }\n    if (has_back_reference) {\n        /* check if there is back reference which references a capture\n           made in the some code */\n        for(i = 0; i < CAPTURE_COUNT_MAX; i++) {\n            if (capture_bitmap[i] == 3)\n                return -1;\n        }\n    }\n    if (ret == -2)\n        ret = 0;\n    return ret;\n}\n\n/* return -1 if a simple quantifier cannot be used. Otherwise return\n   the number of characters in the atom. */\nstatic int re_is_simple_quantifier(const uint8_t *bc_buf, int bc_buf_len)\n{\n    int pos, opcode, len, count;\n    uint32_t val;\n    \n    count = 0;\n    pos = 0;\n    while (pos < bc_buf_len) {\n        opcode = bc_buf[pos];\n        len = reopcode_info[opcode].size;\n        switch(opcode) {\n        case REOP_range:\n            val = get_u16(bc_buf + pos + 1);\n            len += val * 4;\n            goto simple_char;\n        case REOP_range32:\n            val = get_u16(bc_buf + pos + 1);\n            len += val * 8;\n            goto simple_char;\n        case REOP_char:\n        case REOP_char32:\n        case REOP_dot:\n        case REOP_any:\n        simple_char:\n            count++;\n            break;\n        case REOP_line_start:\n        case REOP_line_end:\n        case REOP_word_boundary:\n        case REOP_not_word_boundary:\n            break;\n        default:\n            return -1;\n        }\n        pos += len;\n    }\n    return count;\n}\n\n/* '*pp' is the first char after '<' */\nstatic int re_parse_group_name(char *buf, int buf_size,\n                               const uint8_t **pp, BOOL is_utf16)\n{\n    const uint8_t *p;\n    uint32_t c;\n    char *q;\n\n    p = *pp;\n    q = buf;\n    for(;;) {\n        c = *p;\n        if (c == '\\\\') {\n            p++;\n            if (*p != 'u')\n                return -1;\n            c = lre_parse_escape(&p, is_utf16 * 2);\n        } else if (c == '>') {\n            break;\n        } else if (c >= 128) {\n            c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);\n        } else {\n            p++;\n        }\n        if (c > 0x10FFFF)\n            return -1;\n        if (q == buf) {\n            if (!lre_js_is_ident_first(c))\n                return -1;\n        } else {\n            if (!lre_js_is_ident_next(c))\n                return -1;\n        }\n        if ((q - buf + UTF8_CHAR_LEN_MAX + 1) > buf_size)\n            return -1;\n        if (c < 128) {\n            *q++ = c;\n        } else {\n            q += unicode_to_utf8((uint8_t*)q, c);\n        }\n    }\n    if (q == buf)\n        return -1;\n    *q = '\\0';\n    p++;\n    *pp = p;\n    return 0;\n}\n\n/* if capture_name = NULL: return the number of captures + 1.\n   Otherwise, return the capture index corresponding to capture_name\n   or -1 if none */\nstatic int re_parse_captures(REParseState *s, int *phas_named_captures,\n                             const char *capture_name)\n{\n    const uint8_t *p;\n    int capture_index;\n    char name[TMP_BUF_SIZE];\n\n    capture_index = 1;\n    *phas_named_captures = 0;\n    for (p = s->buf_start; p < s->buf_end; p++) {\n        switch (*p) {\n        case '(':\n            if (p[1] == '?') {\n                if (p[2] == '<' && p[3] != '=' && p[3] != '!') {\n                    *phas_named_captures = 1;\n                    /* potential named capture */\n                    if (capture_name) {\n                        p += 3;\n                        if (re_parse_group_name(name, sizeof(name), &p,\n                                                s->is_utf16) == 0) {\n                            if (!strcmp(name, capture_name))\n                                return capture_index;\n                        }\n                    }\n                    capture_index++;\n                    if (capture_index >= CAPTURE_COUNT_MAX)\n                        goto done;\n                }\n            } else {\n                capture_index++;\n                if (capture_index >= CAPTURE_COUNT_MAX)\n                    goto done;\n            }\n            break;\n        case '\\\\':\n            p++;\n            break;\n        case '[':\n            for (p += 1 + (*p == ']'); p < s->buf_end && *p != ']'; p++) {\n                if (*p == '\\\\')\n                    p++;\n            }\n            break;\n        }\n    }\n done:\n    if (capture_name)\n        return -1;\n    else\n        return capture_index;\n}\n\nstatic int re_count_captures(REParseState *s)\n{\n    if (s->total_capture_count < 0) {\n        s->total_capture_count = re_parse_captures(s, &s->has_named_captures,\n                                                   NULL);\n    }\n    return s->total_capture_count;\n}\n\nstatic BOOL re_has_named_captures(REParseState *s)\n{\n    if (s->has_named_captures < 0)\n        re_count_captures(s);\n    return s->has_named_captures;\n}\n\nstatic int find_group_name(REParseState *s, const char *name)\n{\n    const char *p, *buf_end;\n    size_t len, name_len;\n    int capture_index;\n    \n    name_len = strlen(name);\n    p = (char *)s->group_names.buf;\n    buf_end = (char *)s->group_names.buf + s->group_names.size;\n    capture_index = 1;\n    while (p < buf_end) {\n        len = strlen(p);\n        if (len == name_len && memcmp(name, p, name_len) == 0)\n            return capture_index;\n        p += len + 1;\n        capture_index++;\n    }\n    return -1;\n}\n\nstatic int re_parse_disjunction(REParseState *s, BOOL is_backward_dir);\n\nstatic int re_parse_term(REParseState *s, BOOL is_backward_dir)\n{\n    const uint8_t *p;\n    int c, last_atom_start, quant_min, quant_max, last_capture_count;\n    BOOL greedy, add_zero_advance_check, is_neg, is_backward_lookahead;\n    CharRange cr_s, *cr = &cr_s;\n    \n    last_atom_start = -1;\n    last_capture_count = 0;\n    p = s->buf_ptr;\n    c = *p;\n    switch(c) {\n    case '^':\n        p++;\n        re_emit_op(s, REOP_line_start);\n        break;\n    case '$':\n        p++;\n        re_emit_op(s, REOP_line_end);\n        break;\n    case '.':\n        p++;\n        last_atom_start = s->byte_code.size;\n        last_capture_count = s->capture_count;\n        if (is_backward_dir)\n            re_emit_op(s, REOP_prev);\n        re_emit_op(s, s->dotall ? REOP_any : REOP_dot);\n        if (is_backward_dir)\n            re_emit_op(s, REOP_prev);\n        break;\n    case '{':\n        if (s->is_utf16) {\n            return re_parse_error(s, \"syntax error\");\n        } else if (!is_digit(p[1])) {\n            /* Annex B: we accept '{' not followed by digits as a\n               normal atom */\n            goto parse_class_atom;\n        } else {\n            const uint8_t *p1 = p + 1;\n            /* Annex B: error if it is like a repetition count */\n            parse_digits(&p1, TRUE);\n            if (*p1 == ',') {\n                p1++;\n                if (is_digit(*p1)) {\n                    parse_digits(&p1, TRUE);\n                }\n            }\n            if (*p1 != '}') {\n                goto parse_class_atom;\n            }\n        }\n        /* fall thru */\n    case '*':\n    case '+':\n    case '?':\n        return re_parse_error(s, \"nothing to repeat\");\n    case '(':\n        if (p[1] == '?') {\n            if (p[2] == ':') {\n                p += 3;\n                last_atom_start = s->byte_code.size;\n                last_capture_count = s->capture_count;\n                s->buf_ptr = p;\n                if (re_parse_disjunction(s, is_backward_dir))\n                    return -1;\n                p = s->buf_ptr;\n                if (re_parse_expect(s, &p, ')'))\n                    return -1;\n            } else if ((p[2] == '=' || p[2] == '!')) {\n                is_neg = (p[2] == '!');\n                is_backward_lookahead = FALSE;\n                p += 3;\n                goto lookahead;\n            } else if (p[2] == '<' &&\n                       (p[3] == '=' || p[3] == '!')) {\n                int pos;\n                is_neg = (p[3] == '!');\n                is_backward_lookahead = TRUE;\n                p += 4;\n                /* lookahead */\n            lookahead:\n                /* Annex B allows lookahead to be used as an atom for\n                   the quantifiers */\n                if (!s->is_utf16 && !is_backward_lookahead)  {\n                    last_atom_start = s->byte_code.size;\n                    last_capture_count = s->capture_count;\n                }\n                pos = re_emit_op_u32(s, REOP_lookahead + is_neg, 0);\n                s->buf_ptr = p;\n                if (re_parse_disjunction(s, is_backward_lookahead))\n                    return -1;\n                p = s->buf_ptr;\n                if (re_parse_expect(s, &p, ')'))\n                    return -1;\n                re_emit_op(s, REOP_match);\n                /* jump after the 'match' after the lookahead is successful */\n                if (dbuf_error(&s->byte_code))\n                    return -1;\n                put_u32(s->byte_code.buf + pos, s->byte_code.size - (pos + 4));\n            } else if (p[2] == '<') {\n                p += 3;\n                if (re_parse_group_name(s->u.tmp_buf, sizeof(s->u.tmp_buf),\n                                        &p, s->is_utf16)) {\n                    return re_parse_error(s, \"invalid group name\");\n                }\n                if (find_group_name(s, s->u.tmp_buf) > 0) {\n                    return re_parse_error(s, \"duplicate group name\");\n                }\n                /* group name with a trailing zero */\n                dbuf_put(&s->group_names, (uint8_t *)s->u.tmp_buf,\n                         strlen(s->u.tmp_buf) + 1);\n                s->has_named_captures = 1;\n                goto parse_capture;\n            } else {\n                return re_parse_error(s, \"invalid group\");\n            }\n        } else {\n            int capture_index;\n            p++;\n            /* capture without group name */\n            dbuf_putc(&s->group_names, 0);\n        parse_capture:\n            if (s->capture_count >= CAPTURE_COUNT_MAX)\n                return re_parse_error(s, \"too many captures\");\n            last_atom_start = s->byte_code.size;\n            last_capture_count = s->capture_count;\n            capture_index = s->capture_count++;\n            re_emit_op_u8(s, REOP_save_start + is_backward_dir,\n                          capture_index);\n            \n            s->buf_ptr = p;\n            if (re_parse_disjunction(s, is_backward_dir))\n                return -1;\n            p = s->buf_ptr;\n            \n            re_emit_op_u8(s, REOP_save_start + 1 - is_backward_dir,\n                          capture_index);\n            \n            if (re_parse_expect(s, &p, ')'))\n                return -1;\n        }\n        break;\n    case '\\\\':\n        switch(p[1]) {\n        case 'b':\n        case 'B':\n            re_emit_op(s, REOP_word_boundary + (p[1] != 'b'));\n            p += 2;\n            break;\n        case 'k':\n            {\n                const uint8_t *p1;\n                int dummy_res;\n                \n                p1 = p;\n                if (p1[2] != '<') {\n                    /* annex B: we tolerate invalid group names in non\n                       unicode mode if there is no named capture\n                       definition */\n                    if (s->is_utf16 || re_has_named_captures(s))\n                        return re_parse_error(s, \"expecting group name\");\n                    else\n                        goto parse_class_atom;\n                }\n                p1 += 3;\n                if (re_parse_group_name(s->u.tmp_buf, sizeof(s->u.tmp_buf),\n                                        &p1, s->is_utf16)) {\n                    if (s->is_utf16 || re_has_named_captures(s))\n                        return re_parse_error(s, \"invalid group name\");\n                    else\n                        goto parse_class_atom;\n                }\n                c = find_group_name(s, s->u.tmp_buf);\n                if (c < 0) {\n                    /* no capture name parsed before, try to look\n                       after (inefficient, but hopefully not common */\n                    c = re_parse_captures(s, &dummy_res, s->u.tmp_buf);\n                    if (c < 0) {\n                        if (s->is_utf16 || re_has_named_captures(s))\n                            return re_parse_error(s, \"group name not defined\");\n                        else\n                            goto parse_class_atom;\n                    }\n                }\n                p = p1;\n            }\n            goto emit_back_reference;\n        case '0':\n            p += 2;\n            c = 0;\n            if (s->is_utf16) {\n                if (is_digit(*p)) {\n                    return re_parse_error(s, \"invalid decimal escape in regular expression\");\n                }\n            } else {\n                /* Annex B.1.4: accept legacy octal */\n                if (*p >= '0' && *p <= '7') {\n                    c = *p++ - '0';\n                    if (*p >= '0' && *p <= '7') {\n                        c = (c << 3) + *p++ - '0';\n                    }\n                }\n            }\n            goto normal_char;\n        case '1': case '2': case '3': case '4':\n        case '5': case '6': case '7': case '8':\n        case '9': \n            {\n                const uint8_t *q = ++p;\n                \n                c = parse_digits(&p, FALSE);\n                if (c < 0 || (c >= s->capture_count && c >= re_count_captures(s))) {\n                    if (!s->is_utf16) {\n                        /* Annex B.1.4: accept legacy octal */\n                        p = q;\n                        if (*p <= '7') {\n                            c = 0;\n                            if (*p <= '3')\n                                c = *p++ - '0';\n                            if (*p >= '0' && *p <= '7') {\n                                c = (c << 3) + *p++ - '0';\n                                if (*p >= '0' && *p <= '7') {\n                                    c = (c << 3) + *p++ - '0';\n                                }\n                            }\n                        } else {\n                            c = *p++;\n                        }\n                        goto normal_char;\n                    }\n                    return re_parse_error(s, \"back reference out of range in regular expression\");\n                }\n            emit_back_reference:\n                last_atom_start = s->byte_code.size;\n                last_capture_count = s->capture_count;\n                re_emit_op_u8(s, REOP_back_reference + is_backward_dir, c);\n            }\n            break;\n        default:\n            goto parse_class_atom;\n        }\n        break;\n    case '[':\n        last_atom_start = s->byte_code.size;\n        last_capture_count = s->capture_count;\n        if (is_backward_dir)\n            re_emit_op(s, REOP_prev);\n        if (re_parse_char_class(s, &p))\n            return -1;\n        if (is_backward_dir)\n            re_emit_op(s, REOP_prev);\n        break;\n    case ']':\n    case '}':\n        if (s->is_utf16)\n            return re_parse_error(s, \"syntax error\");\n        goto parse_class_atom;\n    default:\n    parse_class_atom:\n        c = get_class_atom(s, cr, &p, FALSE);\n        if ((int)c < 0)\n            return -1;\n    normal_char:\n        last_atom_start = s->byte_code.size;\n        last_capture_count = s->capture_count;\n        if (is_backward_dir)\n            re_emit_op(s, REOP_prev);\n        if (c >= CLASS_RANGE_BASE) {\n            int ret;\n            /* Note: canonicalization is not needed */\n            ret = re_emit_range(s, cr);\n            cr_free(cr);\n            if (ret)\n                return -1;\n        } else {\n            if (s->ignore_case)\n                c = lre_canonicalize(c, s->is_utf16);\n            if (c <= 0xffff)\n                re_emit_op_u16(s, REOP_char, c);\n            else\n                re_emit_op_u32(s, REOP_char32, c);\n        }\n        if (is_backward_dir)\n            re_emit_op(s, REOP_prev);\n        break;\n    }\n\n    /* quantifier */\n    if (last_atom_start >= 0) {\n        c = *p;\n        switch(c) {\n        case '*':\n            p++;\n            quant_min = 0;\n            quant_max = INT32_MAX;\n            goto quantifier;\n        case '+':\n            p++;\n            quant_min = 1;\n            quant_max = INT32_MAX;\n            goto quantifier;\n        case '?':\n            p++;\n            quant_min = 0;\n            quant_max = 1;\n            goto quantifier;\n        case '{':\n            {\n                const uint8_t *p1 = p;\n                /* As an extension (see ES6 annex B), we accept '{' not\n                   followed by digits as a normal atom */\n                if (!is_digit(p[1])) {\n                    if (s->is_utf16)\n                        goto invalid_quant_count;\n                    break;\n                }\n                p++;\n                quant_min = parse_digits(&p, TRUE);\n                quant_max = quant_min;\n                if (*p == ',') {\n                    p++;\n                    if (is_digit(*p)) {\n                        quant_max = parse_digits(&p, TRUE);\n                        if (quant_max < quant_min) {\n                        invalid_quant_count:\n                            return re_parse_error(s, \"invalid repetition count\");\n                        }\n                    } else {\n                        quant_max = INT32_MAX; /* infinity */\n                    }\n                }\n                if (*p != '}' && !s->is_utf16) {\n                    /* Annex B: normal atom if invalid '{' syntax */\n                    p = p1;\n                    break;\n                }\n                if (re_parse_expect(s, &p, '}'))\n                    return -1;\n            }\n        quantifier:\n            greedy = TRUE;\n            if (*p == '?') {\n                p++;\n                greedy = FALSE;\n            }\n            if (last_atom_start < 0) {\n                return re_parse_error(s, \"nothing to repeat\");\n            }\n            if (greedy) {\n                int len, pos;\n                \n                if (quant_max > 0) {\n                    /* specific optimization for simple quantifiers */\n                    if (dbuf_error(&s->byte_code))\n                        goto out_of_memory;\n                    len = re_is_simple_quantifier(s->byte_code.buf + last_atom_start,\n                                                 s->byte_code.size - last_atom_start);\n                    if (len > 0) {\n                        re_emit_op(s, REOP_match);\n                        \n                        if (dbuf_insert(&s->byte_code, last_atom_start, 17))\n                            goto out_of_memory;\n                        pos = last_atom_start;\n                        s->byte_code.buf[pos++] = REOP_simple_greedy_quant;\n                        put_u32(&s->byte_code.buf[pos],\n                                s->byte_code.size - last_atom_start - 17);\n                        pos += 4;\n                        put_u32(&s->byte_code.buf[pos], quant_min);\n                        pos += 4;\n                        put_u32(&s->byte_code.buf[pos], quant_max);\n                        pos += 4;\n                        put_u32(&s->byte_code.buf[pos], len);\n                        pos += 4;\n                        goto done;\n                    }\n                }\n                \n                if (dbuf_error(&s->byte_code))\n                    goto out_of_memory;\n                add_zero_advance_check = (re_check_advance(s->byte_code.buf + last_atom_start,\n                                                           s->byte_code.size - last_atom_start) == 0);\n            } else {\n                add_zero_advance_check = FALSE;\n            }\n            \n            {\n                int len, pos;\n                len = s->byte_code.size - last_atom_start;\n                if (quant_min == 0) {\n                    /* need to reset the capture in case the atom is\n                       not executed */\n                    if (last_capture_count != s->capture_count) {\n                        if (dbuf_insert(&s->byte_code, last_atom_start, 3))\n                            goto out_of_memory;\n                        s->byte_code.buf[last_atom_start++] = REOP_save_reset;\n                        s->byte_code.buf[last_atom_start++] = last_capture_count;\n                        s->byte_code.buf[last_atom_start++] = s->capture_count - 1;\n                    }\n                    if (quant_max == 0) {\n                        s->byte_code.size = last_atom_start;\n                    } else if (quant_max == 1) {\n                        if (dbuf_insert(&s->byte_code, last_atom_start, 5))\n                            goto out_of_memory;\n                        s->byte_code.buf[last_atom_start] = REOP_split_goto_first +\n                            greedy;\n                        put_u32(s->byte_code.buf + last_atom_start + 1, len);\n                    } else if (quant_max == INT32_MAX) {\n                        if (dbuf_insert(&s->byte_code, last_atom_start, 5 + add_zero_advance_check))\n                            goto out_of_memory;\n                        s->byte_code.buf[last_atom_start] = REOP_split_goto_first +\n                            greedy;\n                        put_u32(s->byte_code.buf + last_atom_start + 1,\n                                len + 5 + add_zero_advance_check);\n                        if (add_zero_advance_check) {\n                            /* avoid infinite loop by stoping the\n                               recursion if no advance was made in the\n                               atom (only works if the atom has no\n                               side effect) */\n                            s->byte_code.buf[last_atom_start + 1 + 4] = REOP_push_char_pos;\n                            re_emit_goto(s, REOP_bne_char_pos, last_atom_start); \n                        } else {\n                            re_emit_goto(s, REOP_goto, last_atom_start);\n                        }\n                    } else {\n                        if (dbuf_insert(&s->byte_code, last_atom_start, 10))\n                            goto out_of_memory;\n                        pos = last_atom_start;\n                        s->byte_code.buf[pos++] = REOP_push_i32;\n                        put_u32(s->byte_code.buf + pos, quant_max);\n                        pos += 4;\n                        s->byte_code.buf[pos++] = REOP_split_goto_first + greedy;\n                        put_u32(s->byte_code.buf + pos, len + 5);\n                        re_emit_goto(s, REOP_loop, last_atom_start + 5);\n                        re_emit_op(s, REOP_drop);\n                    }\n                } else if (quant_min == 1 && quant_max == INT32_MAX &&\n                           !add_zero_advance_check) {\n                    re_emit_goto(s, REOP_split_next_first - greedy,\n                                 last_atom_start);\n                } else {\n                    if (quant_min == 1) {\n                        /* nothing to add */\n                    } else {\n                        if (dbuf_insert(&s->byte_code, last_atom_start, 5))\n                            goto out_of_memory;\n                        s->byte_code.buf[last_atom_start] = REOP_push_i32;\n                        put_u32(s->byte_code.buf + last_atom_start + 1,\n                                quant_min);\n                        last_atom_start += 5;\n                        re_emit_goto(s, REOP_loop, last_atom_start);\n                        re_emit_op(s, REOP_drop);\n                    }\n                    if (quant_max == INT32_MAX) {\n                        pos = s->byte_code.size;\n                        re_emit_op_u32(s, REOP_split_goto_first + greedy,\n                                       len + 5 + add_zero_advance_check);\n                        if (add_zero_advance_check)\n                            re_emit_op(s, REOP_push_char_pos);\n                        /* copy the atom */\n                        dbuf_put_self(&s->byte_code, last_atom_start, len);\n                        if (add_zero_advance_check)\n                            re_emit_goto(s, REOP_bne_char_pos, pos);\n                        else\n                            re_emit_goto(s, REOP_goto, pos);\n                    } else if (quant_max > quant_min) {\n                        re_emit_op_u32(s, REOP_push_i32, quant_max - quant_min);\n                        pos = s->byte_code.size;\n                        re_emit_op_u32(s, REOP_split_goto_first + greedy, len + 5);\n                        /* copy the atom */\n                        dbuf_put_self(&s->byte_code, last_atom_start, len);\n                        \n                        re_emit_goto(s, REOP_loop, pos);\n                        re_emit_op(s, REOP_drop);\n                    }\n                }\n                last_atom_start = -1;\n            }\n            break;\n        default:\n            break;\n        }\n    }\n done:\n    s->buf_ptr = p;\n    return 0;\n out_of_memory:\n    return re_parse_out_of_memory(s);\n}\n\nstatic int re_parse_alternative(REParseState *s, BOOL is_backward_dir)\n{\n    const uint8_t *p;\n    int ret;\n    size_t start, term_start, end, term_size;\n\n    start = s->byte_code.size;\n    for(;;) {\n        p = s->buf_ptr;\n        if (p >= s->buf_end)\n            break;\n        if (*p == '|' || *p == ')')\n            break;\n        term_start = s->byte_code.size;\n        ret = re_parse_term(s, is_backward_dir);\n        if (ret)\n            return ret;\n        if (is_backward_dir) {\n            /* reverse the order of the terms (XXX: inefficient, but\n               speed is not really critical here) */\n            end = s->byte_code.size;\n            term_size = end - term_start;\n            if (dbuf_realloc(&s->byte_code, end + term_size))\n                return -1;\n            memmove(s->byte_code.buf + start + term_size,\n                    s->byte_code.buf + start,\n                    end - start);\n            memcpy(s->byte_code.buf + start, s->byte_code.buf + end,\n                   term_size);\n        }\n    }\n    return 0;\n}\n    \nstatic int re_parse_disjunction(REParseState *s, BOOL is_backward_dir)\n{\n    int start, len, pos;\n\n    if (lre_check_stack_overflow(s->opaque, 0))\n        return re_parse_error(s, \"stack overflow\");\n    \n    start = s->byte_code.size;\n    if (re_parse_alternative(s, is_backward_dir))\n        return -1;\n    while (*s->buf_ptr == '|') {\n        s->buf_ptr++;\n\n        len = s->byte_code.size - start;\n\n        /* insert a split before the first alternative */\n        if (dbuf_insert(&s->byte_code, start, 5)) {\n            return re_parse_out_of_memory(s);\n        }\n        s->byte_code.buf[start] = REOP_split_next_first;\n        put_u32(s->byte_code.buf + start + 1, len + 5);\n\n        pos = re_emit_op_u32(s, REOP_goto, 0);\n\n        if (re_parse_alternative(s, is_backward_dir))\n            return -1;\n        \n        /* patch the goto */\n        len = s->byte_code.size - (pos + 4);\n        put_u32(s->byte_code.buf + pos, len);\n    }\n    return 0;\n}\n\n/* the control flow is recursive so the analysis can be linear */\nstatic int compute_stack_size(const uint8_t *bc_buf, int bc_buf_len)\n{\n    int stack_size, stack_size_max, pos, opcode, len;\n    uint32_t val;\n    \n    stack_size = 0;\n    stack_size_max = 0;\n    bc_buf += RE_HEADER_LEN;\n    bc_buf_len -= RE_HEADER_LEN;\n    pos = 0;\n    while (pos < bc_buf_len) {\n        opcode = bc_buf[pos];\n        len = reopcode_info[opcode].size;\n        assert(opcode < REOP_COUNT);\n        assert((pos + len) <= bc_buf_len);\n        switch(opcode) {\n        case REOP_push_i32:\n        case REOP_push_char_pos:\n            stack_size++;\n            if (stack_size > stack_size_max) {\n                if (stack_size > STACK_SIZE_MAX)\n                    return -1;\n                stack_size_max = stack_size;\n            }\n            break;\n        case REOP_drop:\n        case REOP_bne_char_pos:\n            assert(stack_size > 0);\n            stack_size--;\n            break;\n        case REOP_range:\n            val = get_u16(bc_buf + pos + 1);\n            len += val * 4;\n            break;\n        case REOP_range32:\n            val = get_u16(bc_buf + pos + 1);\n            len += val * 8;\n            break;\n        }\n        pos += len;\n    }\n    return stack_size_max;\n}\n\n/* 'buf' must be a zero terminated UTF-8 string of length buf_len.\n   Return NULL if error and allocate an error message in *perror_msg,\n   otherwise the compiled bytecode and its length in plen.\n*/\nuint8_t *lre_compile(int *plen, char *error_msg, int error_msg_size,\n                     const char *buf, size_t buf_len, int re_flags,\n                     void *opaque)\n{\n    REParseState s_s, *s = &s_s;\n    int stack_size;\n    BOOL is_sticky;\n    \n    memset(s, 0, sizeof(*s));\n    s->opaque = opaque;\n    s->buf_ptr = (const uint8_t *)buf;\n    s->buf_end = s->buf_ptr + buf_len;\n    s->buf_start = s->buf_ptr;\n    s->re_flags = re_flags;\n    s->is_utf16 = ((re_flags & LRE_FLAG_UTF16) != 0);\n    is_sticky = ((re_flags & LRE_FLAG_STICKY) != 0);\n    s->ignore_case = ((re_flags & LRE_FLAG_IGNORECASE) != 0);\n    s->dotall = ((re_flags & LRE_FLAG_DOTALL) != 0);\n    s->capture_count = 1;\n    s->total_capture_count = -1;\n    s->has_named_captures = -1;\n    \n    dbuf_init2(&s->byte_code, opaque, lre_realloc);\n    dbuf_init2(&s->group_names, opaque, lre_realloc);\n\n    dbuf_putc(&s->byte_code, re_flags); /* first element is the flags */\n    dbuf_putc(&s->byte_code, 0); /* second element is the number of captures */\n    dbuf_putc(&s->byte_code, 0); /* stack size */\n    dbuf_put_u32(&s->byte_code, 0); /* bytecode length */\n    \n    if (!is_sticky) {\n        /* iterate thru all positions (about the same as .*?( ... ) )\n           .  We do it without an explicit loop so that lock step\n           thread execution will be possible in an optimized\n           implementation */\n        re_emit_op_u32(s, REOP_split_goto_first, 1 + 5);\n        re_emit_op(s, REOP_any);\n        re_emit_op_u32(s, REOP_goto, -(5 + 1 + 5));\n    }\n    re_emit_op_u8(s, REOP_save_start, 0);\n\n    if (re_parse_disjunction(s, FALSE)) {\n    error:\n        dbuf_free(&s->byte_code);\n        dbuf_free(&s->group_names);\n        pstrcpy(error_msg, error_msg_size, s->u.error_msg);\n        *plen = 0;\n        return NULL;\n    }\n\n    re_emit_op_u8(s, REOP_save_end, 0);\n    \n    re_emit_op(s, REOP_match);\n\n    if (*s->buf_ptr != '\\0') {\n        re_parse_error(s, \"extraneous characters at the end\");\n        goto error;\n    }\n\n    if (dbuf_error(&s->byte_code)) {\n        re_parse_out_of_memory(s);\n        goto error;\n    }\n    \n    stack_size = compute_stack_size(s->byte_code.buf, s->byte_code.size);\n    if (stack_size < 0) {\n        re_parse_error(s, \"too many imbricated quantifiers\");\n        goto error;\n    }\n    \n    s->byte_code.buf[RE_HEADER_CAPTURE_COUNT] = s->capture_count;\n    s->byte_code.buf[RE_HEADER_STACK_SIZE] = stack_size;\n    put_u32(s->byte_code.buf + 3, s->byte_code.size - RE_HEADER_LEN);\n\n    /* add the named groups if needed */\n    if (s->group_names.size > (s->capture_count - 1)) {\n        dbuf_put(&s->byte_code, s->group_names.buf, s->group_names.size);\n        s->byte_code.buf[RE_HEADER_FLAGS] |= LRE_FLAG_NAMED_GROUPS;\n    }\n    dbuf_free(&s->group_names);\n    \n#ifdef DUMP_REOP\n    lre_dump_bytecode(s->byte_code.buf, s->byte_code.size);\n#endif\n    \n    error_msg[0] = '\\0';\n    *plen = s->byte_code.size;\n    return s->byte_code.buf;\n}\n\nstatic BOOL is_line_terminator(uint32_t c)\n{\n    return (c == '\\n' || c == '\\r' || c == CP_LS || c == CP_PS);\n}\n\nstatic BOOL is_word_char(uint32_t c)\n{\n    return ((c >= '0' && c <= '9') ||\n            (c >= 'a' && c <= 'z') ||\n            (c >= 'A' && c <= 'Z') ||\n            (c == '_'));\n}\n\n#define GET_CHAR(c, cptr, cbuf_end)                                     \\\n    do {                                                                \\\n        if (cbuf_type == 0) {                                           \\\n            c = *cptr++;                                                \\\n        } else {                                                        \\\n            uint32_t __c1;                                              \\\n            c = *(uint16_t *)cptr;                                      \\\n            cptr += 2;                                                  \\\n            if (c >= 0xd800 && c < 0xdc00 &&                            \\\n                cbuf_type == 2 && cptr < cbuf_end) {                    \\\n                __c1 = *(uint16_t *)cptr;                               \\\n                if (__c1 >= 0xdc00 && __c1 < 0xe000) {                  \\\n                    c = (((c & 0x3ff) << 10) | (__c1 & 0x3ff)) + 0x10000; \\\n                    cptr += 2;                                          \\\n                }                                                       \\\n            }                                                           \\\n        }                                                               \\\n    } while (0)\n\n#define PEEK_CHAR(c, cptr, cbuf_end)             \\\n    do {                                         \\\n        if (cbuf_type == 0) {                    \\\n            c = cptr[0];                         \\\n        } else {                                 \\\n            uint32_t __c1;                                              \\\n            c = ((uint16_t *)cptr)[0];                                  \\\n            if (c >= 0xd800 && c < 0xdc00 &&                            \\\n                cbuf_type == 2 && (cptr + 2) < cbuf_end) {              \\\n                __c1 = ((uint16_t *)cptr)[1];                           \\\n                if (__c1 >= 0xdc00 && __c1 < 0xe000) {                  \\\n                    c = (((c & 0x3ff) << 10) | (__c1 & 0x3ff)) + 0x10000; \\\n                }                                                       \\\n            }                                                           \\\n        }                                        \\\n    } while (0)\n\n#define PEEK_PREV_CHAR(c, cptr, cbuf_start)                 \\\n    do {                                         \\\n        if (cbuf_type == 0) {                    \\\n            c = cptr[-1];                        \\\n        } else {                                 \\\n            uint32_t __c1;                                              \\\n            c = ((uint16_t *)cptr)[-1];                                 \\\n            if (c >= 0xdc00 && c < 0xe000 &&                            \\\n                cbuf_type == 2 && (cptr - 4) >= cbuf_start) {              \\\n                __c1 = ((uint16_t *)cptr)[-2];                          \\\n                if (__c1 >= 0xd800 && __c1 < 0xdc00 ) {                 \\\n                    c = (((__c1 & 0x3ff) << 10) | (c & 0x3ff)) + 0x10000; \\\n                }                                                       \\\n            }                                                           \\\n        }                                                               \\\n    } while (0)\n\n#define GET_PREV_CHAR(c, cptr, cbuf_start)       \\\n    do {                                         \\\n        if (cbuf_type == 0) {                    \\\n            cptr--;                              \\\n            c = cptr[0];                         \\\n        } else {                                 \\\n            uint32_t __c1;                                              \\\n            cptr -= 2;                                                  \\\n            c = ((uint16_t *)cptr)[0];                                 \\\n            if (c >= 0xdc00 && c < 0xe000 &&                            \\\n                cbuf_type == 2 && cptr > cbuf_start) {                  \\\n                __c1 = ((uint16_t *)cptr)[-1];                          \\\n                if (__c1 >= 0xd800 && __c1 < 0xdc00 ) {                 \\\n                    cptr -= 2;                                          \\\n                    c = (((__c1 & 0x3ff) << 10) | (c & 0x3ff)) + 0x10000; \\\n                }                                                       \\\n            }                                                           \\\n        }                                                               \\\n    } while (0)\n\n#define PREV_CHAR(cptr, cbuf_start)       \\\n    do {                                  \\\n        if (cbuf_type == 0) {             \\\n            cptr--;                       \\\n        } else {                          \\\n            cptr -= 2;                          \\\n            if (cbuf_type == 2) {                                       \\\n                c = ((uint16_t *)cptr)[0];                              \\\n                if (c >= 0xdc00 && c < 0xe000 && cptr > cbuf_start) {   \\\n                    c = ((uint16_t *)cptr)[-1];                         \\\n                    if (c >= 0xd800 && c < 0xdc00)                      \\\n                        cptr -= 2;                                      \\\n                }                                                       \\\n            }                                                           \\\n        }                                                               \\\n    } while (0)\n\ntypedef uintptr_t StackInt;\n\ntypedef enum {\n    RE_EXEC_STATE_SPLIT,\n    RE_EXEC_STATE_LOOKAHEAD,\n    RE_EXEC_STATE_NEGATIVE_LOOKAHEAD,\n    RE_EXEC_STATE_GREEDY_QUANT,\n} REExecStateEnum;\n\ntypedef struct REExecState {\n    REExecStateEnum type : 8;\n    uint8_t stack_len;\n    size_t count; /* only used for RE_EXEC_STATE_GREEDY_QUANT */\n    const uint8_t *cptr;\n    const uint8_t *pc;\n    void *buf[0];\n} REExecState;\n\ntypedef struct {\n    const uint8_t *cbuf;\n    const uint8_t *cbuf_end;\n    /* 0 = 8 bit chars, 1 = 16 bit chars, 2 = 16 bit chars, UTF-16 */\n    int cbuf_type; \n    int capture_count;\n    int stack_size_max;\n    BOOL multi_line;\n    BOOL ignore_case;\n    BOOL is_utf16;\n    void *opaque; /* used for stack overflow check */\n\n    size_t state_size;\n    uint8_t *state_stack;\n    size_t state_stack_size;\n    size_t state_stack_len;\n} REExecContext;\n\nstatic int push_state(REExecContext *s,\n                      uint8_t **capture,\n                      StackInt *stack, size_t stack_len,\n                      const uint8_t *pc, const uint8_t *cptr,\n                      REExecStateEnum type, size_t count)\n{\n    REExecState *rs;\n    uint8_t *new_stack;\n    size_t new_size, i, n;\n    StackInt *stack_buf;\n\n    if (unlikely((s->state_stack_len + 1) > s->state_stack_size)) {\n        /* reallocate the stack */\n        new_size = s->state_stack_size * 3 / 2;\n        if (new_size < 8)\n            new_size = 8;\n        new_stack = lre_realloc(s->opaque, s->state_stack, new_size * s->state_size);\n        if (!new_stack)\n            return -1;\n        s->state_stack_size = new_size;\n        s->state_stack = new_stack;\n    }\n    rs = (REExecState *)(s->state_stack + s->state_stack_len * s->state_size);\n    s->state_stack_len++;\n    rs->type = type;\n    rs->count = count;\n    rs->stack_len = stack_len;\n    rs->cptr = cptr;\n    rs->pc = pc;\n    n = 2 * s->capture_count;\n    for(i = 0; i < n; i++)\n        rs->buf[i] = capture[i];\n    stack_buf = (StackInt *)(rs->buf + n);\n    for(i = 0; i < stack_len; i++)\n        stack_buf[i] = stack[i];\n    return 0;\n}\n\n/* return 1 if match, 0 if not match or -1 if error. */\nstatic intptr_t lre_exec_backtrack(REExecContext *s, uint8_t **capture,\n                                   StackInt *stack, int stack_len,\n                                   const uint8_t *pc, const uint8_t *cptr,\n                                   BOOL no_recurse)\n{\n    int opcode, ret;\n    int cbuf_type;\n    uint32_t val, c;\n    const uint8_t *cbuf_end;\n    \n    cbuf_type = s->cbuf_type;\n    cbuf_end = s->cbuf_end;\n\n    for(;;) {\n        //        printf(\"top=%p: pc=%d\\n\", th_list.top, (int)(pc - (bc_buf + RE_HEADER_LEN)));\n        opcode = *pc++;\n        switch(opcode) {\n        case REOP_match:\n            {\n                REExecState *rs;\n                if (no_recurse)\n                    return (intptr_t)cptr;\n                ret = 1;\n                goto recurse;\n            no_match:\n                if (no_recurse)\n                    return 0;\n                ret = 0;\n            recurse:\n                for(;;) {\n                    if (s->state_stack_len == 0)\n                        return ret;\n                    rs = (REExecState *)(s->state_stack +\n                                         (s->state_stack_len - 1) * s->state_size);\n                    if (rs->type == RE_EXEC_STATE_SPLIT) {\n                        if (!ret) {\n                        pop_state:\n                            memcpy(capture, rs->buf,\n                                   sizeof(capture[0]) * 2 * s->capture_count);\n                        pop_state1:\n                            pc = rs->pc;\n                            cptr = rs->cptr;\n                            stack_len = rs->stack_len;\n                            memcpy(stack, rs->buf + 2 * s->capture_count,\n                                   stack_len * sizeof(stack[0]));\n                            s->state_stack_len--;\n                            break;\n                        }\n                    } else if (rs->type == RE_EXEC_STATE_GREEDY_QUANT) {\n                        if (!ret) {\n                            uint32_t char_count, i;\n                            memcpy(capture, rs->buf,\n                                   sizeof(capture[0]) * 2 * s->capture_count);\n                            stack_len = rs->stack_len;\n                            memcpy(stack, rs->buf + 2 * s->capture_count,\n                                   stack_len * sizeof(stack[0]));\n                            pc = rs->pc;\n                            cptr = rs->cptr;\n                            /* go backward */\n                            char_count = get_u32(pc + 12);\n                            for(i = 0; i < char_count; i++) {\n                                PREV_CHAR(cptr, s->cbuf);\n                            }\n                            pc = (pc + 16) + (int)get_u32(pc);\n                            rs->cptr = cptr;\n                            rs->count--;\n                            if (rs->count == 0) {\n                                s->state_stack_len--;\n                            }\n                            break;\n                        }\n                    } else {\n                        ret = ((rs->type == RE_EXEC_STATE_LOOKAHEAD && ret) ||\n                               (rs->type == RE_EXEC_STATE_NEGATIVE_LOOKAHEAD && !ret));\n                        if (ret) {\n                            /* keep the capture in case of positive lookahead */\n                            if (rs->type == RE_EXEC_STATE_LOOKAHEAD)\n                                goto pop_state1;\n                            else\n                                goto pop_state;\n                        }\n                    }\n                    s->state_stack_len--;\n                }\n            }\n            break;\n        case REOP_char32:\n            val = get_u32(pc);\n            pc += 4;\n            goto test_char;\n        case REOP_char:\n            val = get_u16(pc);\n            pc += 2;\n        test_char:\n            if (cptr >= cbuf_end)\n                goto no_match;\n            GET_CHAR(c, cptr, cbuf_end);\n            if (s->ignore_case) {\n                c = lre_canonicalize(c, s->is_utf16);\n            }\n            if (val != c)\n                goto no_match;\n            break;\n        case REOP_split_goto_first:\n        case REOP_split_next_first:\n            {\n                const uint8_t *pc1;\n                \n                val = get_u32(pc);\n                pc += 4;\n                if (opcode == REOP_split_next_first) {\n                    pc1 = pc + (int)val;\n                } else {\n                    pc1 = pc;\n                    pc = pc + (int)val;\n                }\n                ret = push_state(s, capture, stack, stack_len,\n                                 pc1, cptr, RE_EXEC_STATE_SPLIT, 0);\n                if (ret < 0)\n                    return -1;\n                break;\n            }\n        case REOP_lookahead:\n        case REOP_negative_lookahead:\n            val = get_u32(pc);\n            pc += 4;\n            ret = push_state(s, capture, stack, stack_len,\n                             pc + (int)val, cptr,\n                             RE_EXEC_STATE_LOOKAHEAD + opcode - REOP_lookahead,\n                             0);\n            if (ret < 0)\n                return -1;\n            break;\n            \n        case REOP_goto:\n            val = get_u32(pc);\n            pc += 4 + (int)val;\n            break;\n        case REOP_line_start:\n            if (cptr == s->cbuf)\n                break;\n            if (!s->multi_line)\n                goto no_match;\n            PEEK_PREV_CHAR(c, cptr, s->cbuf);\n            if (!is_line_terminator(c))\n                goto no_match;\n            break;\n        case REOP_line_end:\n            if (cptr == cbuf_end)\n                break;\n            if (!s->multi_line)\n                goto no_match;\n            PEEK_CHAR(c, cptr, cbuf_end);\n            if (!is_line_terminator(c))\n                goto no_match;\n            break;\n        case REOP_dot:\n            if (cptr == cbuf_end)\n                goto no_match;\n            GET_CHAR(c, cptr, cbuf_end);\n            if (is_line_terminator(c))\n                goto no_match;\n            break;\n        case REOP_any:\n            if (cptr == cbuf_end)\n                goto no_match;\n            GET_CHAR(c, cptr, cbuf_end);\n            break;\n        case REOP_save_start:\n        case REOP_save_end:\n            val = *pc++;\n            assert(val < s->capture_count);\n            capture[2 * val + opcode - REOP_save_start] = (uint8_t *)cptr;\n            break;\n        case REOP_save_reset:\n            {\n                uint32_t val2;\n                val = pc[0];\n                val2 = pc[1];\n                pc += 2;\n                assert(val2 < s->capture_count);\n                while (val <= val2) {\n                    capture[2 * val] = NULL;\n                    capture[2 * val + 1] = NULL;\n                    val++;\n                }\n            }\n            break;\n        case REOP_push_i32:\n            val = get_u32(pc);\n            pc += 4;\n            stack[stack_len++] = val;\n            break;\n        case REOP_drop:\n            stack_len--;\n            break;\n        case REOP_loop:\n            val = get_u32(pc);\n            pc += 4;\n            if (--stack[stack_len - 1] != 0) {\n                pc += (int)val;\n            }\n            break;\n        case REOP_push_char_pos:\n            stack[stack_len++] = (uintptr_t)cptr;\n            break;\n        case REOP_bne_char_pos:\n            val = get_u32(pc);\n            pc += 4;\n            if (stack[--stack_len] != (uintptr_t)cptr)\n                pc += (int)val;\n            break;\n        case REOP_word_boundary:\n        case REOP_not_word_boundary:\n            {\n                BOOL v1, v2;\n                /* char before */\n                if (cptr == s->cbuf) {\n                    v1 = FALSE;\n                } else {\n                    PEEK_PREV_CHAR(c, cptr, s->cbuf);\n                    v1 = is_word_char(c);\n                }\n                /* current char */\n                if (cptr >= cbuf_end) {\n                    v2 = FALSE;\n                } else {\n                    PEEK_CHAR(c, cptr, cbuf_end);\n                    v2 = is_word_char(c);\n                }\n                if (v1 ^ v2 ^ (REOP_not_word_boundary - opcode))\n                    goto no_match;\n            }\n            break;\n        case REOP_back_reference:\n        case REOP_backward_back_reference:\n            {\n                const uint8_t *cptr1, *cptr1_end, *cptr1_start;\n                uint32_t c1, c2;\n                \n                val = *pc++;\n                if (val >= s->capture_count)\n                    goto no_match;\n                cptr1_start = capture[2 * val];\n                cptr1_end = capture[2 * val + 1];\n                if (!cptr1_start || !cptr1_end)\n                    break;\n                if (opcode == REOP_back_reference) {\n                    cptr1 = cptr1_start;\n                    while (cptr1 < cptr1_end) {\n                        if (cptr >= cbuf_end)\n                            goto no_match;\n                        GET_CHAR(c1, cptr1, cptr1_end);\n                        GET_CHAR(c2, cptr, cbuf_end);\n                        if (s->ignore_case) {\n                            c1 = lre_canonicalize(c1, s->is_utf16);\n                            c2 = lre_canonicalize(c2, s->is_utf16);\n                        }\n                        if (c1 != c2)\n                            goto no_match;\n                    }\n                } else {\n                    cptr1 = cptr1_end;\n                    while (cptr1 > cptr1_start) {\n                        if (cptr == s->cbuf)\n                            goto no_match;\n                        GET_PREV_CHAR(c1, cptr1, cptr1_start);\n                        GET_PREV_CHAR(c2, cptr, s->cbuf);\n                        if (s->ignore_case) {\n                            c1 = lre_canonicalize(c1, s->is_utf16);\n                            c2 = lre_canonicalize(c2, s->is_utf16);\n                        }\n                        if (c1 != c2)\n                            goto no_match;\n                    }\n                }\n            }\n            break;\n        case REOP_range:\n            {\n                int n;\n                uint32_t low, high, idx_min, idx_max, idx;\n                \n                n = get_u16(pc); /* n must be >= 1 */\n                pc += 2;\n                if (cptr >= cbuf_end)\n                    goto no_match;\n                GET_CHAR(c, cptr, cbuf_end);\n                if (s->ignore_case) {\n                    c = lre_canonicalize(c, s->is_utf16);\n                }\n                idx_min = 0;\n                low = get_u16(pc + 0 * 4);\n                if (c < low)\n                    goto no_match;\n                idx_max = n - 1;\n                high = get_u16(pc + idx_max * 4 + 2);\n                /* 0xffff in for last value means +infinity */\n                if (unlikely(c >= 0xffff) && high == 0xffff)\n                    goto range_match;\n                if (c > high)\n                    goto no_match;\n                while (idx_min <= idx_max) {\n                    idx = (idx_min + idx_max) / 2;\n                    low = get_u16(pc + idx * 4);\n                    high = get_u16(pc + idx * 4 + 2);\n                    if (c < low)\n                        idx_max = idx - 1;\n                    else if (c > high)\n                        idx_min = idx + 1;\n                    else\n                        goto range_match;\n                }\n                goto no_match;\n            range_match:\n                pc += 4 * n;\n            }\n            break;\n        case REOP_range32:\n            {\n                int n;\n                uint32_t low, high, idx_min, idx_max, idx;\n                \n                n = get_u16(pc); /* n must be >= 1 */\n                pc += 2;\n                if (cptr >= cbuf_end)\n                    goto no_match;\n                GET_CHAR(c, cptr, cbuf_end);\n                if (s->ignore_case) {\n                    c = lre_canonicalize(c, s->is_utf16);\n                }\n                idx_min = 0;\n                low = get_u32(pc + 0 * 8);\n                if (c < low)\n                    goto no_match;\n                idx_max = n - 1;\n                high = get_u32(pc + idx_max * 8 + 4);\n                if (c > high)\n                    goto no_match;\n                while (idx_min <= idx_max) {\n                    idx = (idx_min + idx_max) / 2;\n                    low = get_u32(pc + idx * 8);\n                    high = get_u32(pc + idx * 8 + 4);\n                    if (c < low)\n                        idx_max = idx - 1;\n                    else if (c > high)\n                        idx_min = idx + 1;\n                    else\n                        goto range32_match;\n                }\n                goto no_match;\n            range32_match:\n                pc += 8 * n;\n            }\n            break;\n        case REOP_prev:\n            /* go to the previous char */\n            if (cptr == s->cbuf)\n                goto no_match;\n            PREV_CHAR(cptr, s->cbuf);\n            break;\n        case REOP_simple_greedy_quant:\n            {\n                uint32_t next_pos, quant_min, quant_max;\n                size_t q;\n                intptr_t res;\n                const uint8_t *pc1;\n                \n                next_pos = get_u32(pc);\n                quant_min = get_u32(pc + 4);\n                quant_max = get_u32(pc + 8);\n                pc += 16;\n                pc1 = pc;\n                pc += (int)next_pos;\n                \n                q = 0;\n                for(;;) {\n                    res = lre_exec_backtrack(s, capture, stack, stack_len,\n                                             pc1, cptr, TRUE);\n                    if (res == -1)\n                        return res;\n                    if (!res)\n                        break;\n                    cptr = (uint8_t *)res;\n                    q++;\n                    if (q >= quant_max && quant_max != INT32_MAX)\n                        break;\n                }\n                if (q < quant_min)\n                    goto no_match;\n                if (q > quant_min) {\n                    /* will examine all matches down to quant_min */\n                    ret = push_state(s, capture, stack, stack_len,\n                                     pc1 - 16, cptr,\n                                     RE_EXEC_STATE_GREEDY_QUANT,\n                                     q - quant_min);\n                    if (ret < 0)\n                        return -1;\n                }\n            }\n            break;\n        default:\n            abort();\n        }\n    }\n}\n\n/* Return 1 if match, 0 if not match or -1 if error. cindex is the\n   starting position of the match and must be such as 0 <= cindex <=\n   clen. */\nint lre_exec(uint8_t **capture,\n             const uint8_t *bc_buf, const uint8_t *cbuf, int cindex, int clen,\n             int cbuf_type, void *opaque)\n{\n    REExecContext s_s, *s = &s_s;\n    int re_flags, i, alloca_size, ret;\n    StackInt *stack_buf;\n    \n    re_flags = bc_buf[RE_HEADER_FLAGS];\n    s->multi_line = (re_flags & LRE_FLAG_MULTILINE) != 0;\n    s->ignore_case = (re_flags & LRE_FLAG_IGNORECASE) != 0;\n    s->is_utf16 = (re_flags & LRE_FLAG_UTF16) != 0;\n    s->capture_count = bc_buf[RE_HEADER_CAPTURE_COUNT];\n    s->stack_size_max = bc_buf[RE_HEADER_STACK_SIZE];\n    s->cbuf = cbuf;\n    s->cbuf_end = cbuf + (clen << cbuf_type);\n    s->cbuf_type = cbuf_type;\n    if (s->cbuf_type == 1 && s->is_utf16)\n        s->cbuf_type = 2;\n    s->opaque = opaque;\n\n    s->state_size = sizeof(REExecState) +\n        s->capture_count * sizeof(capture[0]) * 2 +\n        s->stack_size_max * sizeof(stack_buf[0]);\n    s->state_stack = NULL;\n    s->state_stack_len = 0;\n    s->state_stack_size = 0;\n    \n    for(i = 0; i < s->capture_count * 2; i++)\n        capture[i] = NULL;\n    alloca_size = s->stack_size_max * sizeof(stack_buf[0]);\n    stack_buf = alloca(alloca_size);\n    ret = lre_exec_backtrack(s, capture, stack_buf, 0, bc_buf + RE_HEADER_LEN,\n                             cbuf + (cindex << cbuf_type), FALSE);\n    lre_realloc(s->opaque, s->state_stack, 0);\n    return ret;\n}\n\nint lre_get_capture_count(const uint8_t *bc_buf)\n{\n    return bc_buf[RE_HEADER_CAPTURE_COUNT];\n}\n\nint lre_get_flags(const uint8_t *bc_buf)\n{\n    return bc_buf[RE_HEADER_FLAGS];\n}\n\n/* Return NULL if no group names. Otherwise, return a pointer to\n   'capture_count - 1' zero terminated UTF-8 strings. */\nconst char *lre_get_groupnames(const uint8_t *bc_buf)\n{\n    uint32_t re_bytecode_len;\n    if ((lre_get_flags(bc_buf) & LRE_FLAG_NAMED_GROUPS) == 0)\n        return NULL;\n    re_bytecode_len = get_u32(bc_buf + 3);\n    return (const char *)(bc_buf + 7 + re_bytecode_len);\n}\n\n#ifdef TEST\n\nBOOL lre_check_stack_overflow(void *opaque, size_t alloca_size)\n{\n    return FALSE;\n}\n\nvoid *lre_realloc(void *opaque, void *ptr, size_t size)\n{\n    return realloc(ptr, size);\n}\n\nint main(int argc, char **argv)\n{\n    int len, ret, i;\n    uint8_t *bc;\n    char error_msg[64];\n    uint8_t *capture[CAPTURE_COUNT_MAX * 2];\n    const char *input;\n    int input_len, capture_count;\n    \n    if (argc < 3) {\n        printf(\"usage: %s regexp input\\n\", argv[0]);\n        exit(1);\n    }\n    bc = lre_compile(&len, error_msg, sizeof(error_msg), argv[1],\n                     strlen(argv[1]), 0, NULL);\n    if (!bc) {\n        fprintf(stderr, \"error: %s\\n\", error_msg);\n        exit(1);\n    }\n\n    input = argv[2];\n    input_len = strlen(input);\n    \n    ret = lre_exec(capture, bc, (uint8_t *)input, 0, input_len, 0, NULL);\n    printf(\"ret=%d\\n\", ret);\n    if (ret == 1) {\n        capture_count = lre_get_capture_count(bc);\n        for(i = 0; i < 2 * capture_count; i++) {\n            uint8_t *ptr;\n            ptr = capture[i];\n            printf(\"%d: \", i);\n            if (!ptr)\n                printf(\"<nil>\");\n            else\n                printf(\"%u\", (int)(ptr - (uint8_t *)input));\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n#endif\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/libregexp.h",
    "content": "/*\n * Regular Expression Engine\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#ifndef LIBREGEXP_H\n#define LIBREGEXP_H\n\n#include <stddef.h>\n\n#include \"libunicode.h\"\n\n#define LRE_BOOL  int       /* for documentation purposes */\n\n#define LRE_FLAG_GLOBAL     (1 << 0)\n#define LRE_FLAG_IGNORECASE (1 << 1)\n#define LRE_FLAG_MULTILINE  (1 << 2)\n#define LRE_FLAG_DOTALL     (1 << 3)\n#define LRE_FLAG_UTF16      (1 << 4)\n#define LRE_FLAG_STICKY     (1 << 5)\n\n#define LRE_FLAG_NAMED_GROUPS (1 << 7) /* named groups are present in the regexp */\n\nuint8_t *lre_compile(int *plen, char *error_msg, int error_msg_size,\n                     const char *buf, size_t buf_len, int re_flags,\n                     void *opaque);\nint lre_get_capture_count(const uint8_t *bc_buf);\nint lre_get_flags(const uint8_t *bc_buf);\nconst char *lre_get_groupnames(const uint8_t *bc_buf);\nint lre_exec(uint8_t **capture,\n             const uint8_t *bc_buf, const uint8_t *cbuf, int cindex, int clen,\n             int cbuf_type, void *opaque);\n\nint lre_parse_escape(const uint8_t **pp, int allow_utf16);\nLRE_BOOL lre_is_space(int c);\n\n/* must be provided by the user */\nLRE_BOOL lre_check_stack_overflow(void *opaque, size_t alloca_size); \nvoid *lre_realloc(void *opaque, void *ptr, size_t size);\n\n/* JS identifier test */\nextern uint32_t const lre_id_start_table_ascii[4];\nextern uint32_t const lre_id_continue_table_ascii[4];\n\nstatic inline int lre_js_is_ident_first(int c)\n{\n    if ((uint32_t)c < 128) {\n        return (lre_id_start_table_ascii[c >> 5] >> (c & 31)) & 1;\n    } else {\n#ifdef CONFIG_ALL_UNICODE\n        return lre_is_id_start(c);\n#else\n        return !lre_is_space(c);\n#endif\n    }\n}\n\nstatic inline int lre_js_is_ident_next(int c)\n{\n    if ((uint32_t)c < 128) {\n        return (lre_id_continue_table_ascii[c >> 5] >> (c & 31)) & 1;\n    } else {\n        /* ZWNJ and ZWJ are accepted in identifiers */\n#ifdef CONFIG_ALL_UNICODE\n        return lre_is_id_continue(c) || c == 0x200C || c == 0x200D;\n#else\n        return !lre_is_space(c) || c == 0x200C || c == 0x200D;\n#endif\n    }\n}\n\n#undef LRE_BOOL\n\n#endif /* LIBREGEXP_H */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/libunicode-table.h",
    "content": "/* Compressed unicode tables */\n/* Automatically generated file - do not edit */\n\n#include <stdint.h>\n\nstatic const uint32_t case_conv_table1[361] = {\n    0x00209a30, 0x00309a00, 0x005a8173, 0x00601730,\n    0x006c0730, 0x006f81b3, 0x00701700, 0x007c0700,\n    0x007f8100, 0x00803040, 0x009801c3, 0x00988190,\n    0x00990640, 0x009c9040, 0x00a481b4, 0x00a52e40,\n    0x00bc0130, 0x00bc8640, 0x00bf8170, 0x00c00100,\n    0x00c08130, 0x00c10440, 0x00c30130, 0x00c38240,\n    0x00c48230, 0x00c58240, 0x00c70130, 0x00c78130,\n    0x00c80130, 0x00c88240, 0x00c98130, 0x00ca0130,\n    0x00ca8100, 0x00cb0130, 0x00cb8130, 0x00cc0240,\n    0x00cd0100, 0x00ce0130, 0x00ce8130, 0x00cf0100,\n    0x00cf8130, 0x00d00640, 0x00d30130, 0x00d38240,\n    0x00d48130, 0x00d60240, 0x00d70130, 0x00d78240,\n    0x00d88230, 0x00d98440, 0x00db8130, 0x00dc0240,\n    0x00de0240, 0x00df8100, 0x00e20350, 0x00e38350,\n    0x00e50350, 0x00e69040, 0x00ee8100, 0x00ef1240,\n    0x00f801b4, 0x00f88350, 0x00fa0240, 0x00fb0130,\n    0x00fb8130, 0x00fc2840, 0x01100130, 0x01111240,\n    0x011d0131, 0x011d8240, 0x011e8130, 0x011f0131,\n    0x011f8201, 0x01208240, 0x01218130, 0x01220130,\n    0x01228130, 0x01230a40, 0x01280101, 0x01288101,\n    0x01290101, 0x01298100, 0x012a0100, 0x012b0200,\n    0x012c8100, 0x012d8100, 0x012e0101, 0x01300100,\n    0x01308101, 0x01318100, 0x01328101, 0x01330101,\n    0x01340100, 0x01348100, 0x01350101, 0x01358101,\n    0x01360101, 0x01378100, 0x01388101, 0x01390100,\n    0x013a8100, 0x013e8101, 0x01400100, 0x01410101,\n    0x01418100, 0x01438101, 0x01440100, 0x01448100,\n    0x01450200, 0x01460100, 0x01490100, 0x014e8101,\n    0x014f0101, 0x01a28173, 0x01b80440, 0x01bb0240,\n    0x01bd8300, 0x01bf8130, 0x01c30130, 0x01c40330,\n    0x01c60130, 0x01c70230, 0x01c801d0, 0x01c89130,\n    0x01d18930, 0x01d60100, 0x01d68300, 0x01d801d3,\n    0x01d89100, 0x01e10173, 0x01e18900, 0x01e60100,\n    0x01e68200, 0x01e78130, 0x01e80173, 0x01e88173,\n    0x01ea8173, 0x01eb0173, 0x01eb8100, 0x01ec1840,\n    0x01f80173, 0x01f88173, 0x01f90100, 0x01f98100,\n    0x01fa01a0, 0x01fa8173, 0x01fb8240, 0x01fc8130,\n    0x01fd0240, 0x01fe8330, 0x02001030, 0x02082030,\n    0x02182000, 0x02281000, 0x02302240, 0x02453640,\n    0x02600130, 0x02608e40, 0x02678100, 0x02686040,\n    0x0298a630, 0x02b0a600, 0x02c381b5, 0x08502631,\n    0x08638131, 0x08668131, 0x08682b00, 0x087e8300,\n    0x09d05011, 0x09f80610, 0x09fc0620, 0x0e400174,\n    0x0e408174, 0x0e410174, 0x0e418174, 0x0e420174,\n    0x0e428174, 0x0e430174, 0x0e438180, 0x0e440180,\n    0x0e482b30, 0x0e5e8330, 0x0ebc8101, 0x0ebe8101,\n    0x0ec70101, 0x0f007e40, 0x0f3f1840, 0x0f4b01b5,\n    0x0f4b81b6, 0x0f4c01b6, 0x0f4c81b6, 0x0f4d01b7,\n    0x0f4d8180, 0x0f4f0130, 0x0f506040, 0x0f800800,\n    0x0f840830, 0x0f880600, 0x0f8c0630, 0x0f900800,\n    0x0f940830, 0x0f980800, 0x0f9c0830, 0x0fa00600,\n    0x0fa40630, 0x0fa801b0, 0x0fa88100, 0x0fa901d3,\n    0x0fa98100, 0x0faa01d3, 0x0faa8100, 0x0fab01d3,\n    0x0fab8100, 0x0fac8130, 0x0fad8130, 0x0fae8130,\n    0x0faf8130, 0x0fb00800, 0x0fb40830, 0x0fb80200,\n    0x0fb90400, 0x0fbb0200, 0x0fbc0201, 0x0fbd0201,\n    0x0fbe0201, 0x0fc008b7, 0x0fc40867, 0x0fc808b8,\n    0x0fcc0868, 0x0fd008b8, 0x0fd40868, 0x0fd80200,\n    0x0fd901b9, 0x0fd981b1, 0x0fda01b9, 0x0fdb01b1,\n    0x0fdb81d7, 0x0fdc0230, 0x0fdd0230, 0x0fde0161,\n    0x0fdf0173, 0x0fe101b9, 0x0fe181b2, 0x0fe201ba,\n    0x0fe301b2, 0x0fe381d8, 0x0fe40430, 0x0fe60162,\n    0x0fe80200, 0x0fe901d0, 0x0fe981d0, 0x0feb01b0,\n    0x0feb81d0, 0x0fec0230, 0x0fed0230, 0x0ff00201,\n    0x0ff101d3, 0x0ff181d3, 0x0ff201ba, 0x0ff28101,\n    0x0ff301b0, 0x0ff381d3, 0x0ff40230, 0x0ff50230,\n    0x0ff60131, 0x0ff901ba, 0x0ff981b2, 0x0ffa01bb,\n    0x0ffb01b2, 0x0ffb81d9, 0x0ffc0230, 0x0ffd0230,\n    0x0ffe0162, 0x109301a0, 0x109501a0, 0x109581a0,\n    0x10990131, 0x10a70101, 0x10b01031, 0x10b81001,\n    0x10c18240, 0x125b1a31, 0x12681a01, 0x16002f31,\n    0x16182f01, 0x16300240, 0x16310130, 0x16318130,\n    0x16320130, 0x16328100, 0x16330100, 0x16338640,\n    0x16368130, 0x16370130, 0x16378130, 0x16380130,\n    0x16390240, 0x163a8240, 0x163f0230, 0x16406440,\n    0x16758440, 0x16790240, 0x16802600, 0x16938100,\n    0x16968100, 0x53202e40, 0x53401c40, 0x53910e40,\n    0x53993e40, 0x53bc8440, 0x53be8130, 0x53bf0a40,\n    0x53c58240, 0x53c68130, 0x53c80440, 0x53ca0101,\n    0x53cb1440, 0x53d50130, 0x53d58130, 0x53d60130,\n    0x53d68130, 0x53d70130, 0x53d80130, 0x53d88130,\n    0x53d90130, 0x53d98131, 0x53da0c40, 0x53e10240,\n    0x53e20131, 0x53e28130, 0x53e30130, 0x53e38440,\n    0x53fa8240, 0x55a98101, 0x55b85020, 0x7d8001b2,\n    0x7d8081b2, 0x7d8101b2, 0x7d8181da, 0x7d8201da,\n    0x7d8281b3, 0x7d8301b3, 0x7d8981bb, 0x7d8a01bb,\n    0x7d8a81bb, 0x7d8b01bc, 0x7d8b81bb, 0x7f909a31,\n    0x7fa09a01, 0x82002831, 0x82142801, 0x82582431,\n    0x826c2401, 0x86403331, 0x86603301, 0x8c502031,\n    0x8c602001, 0xb7202031, 0xb7302001, 0xf4802231,\n    0xf4912201,\n};\n\nstatic const uint8_t case_conv_table2[361] = {\n    0x01, 0x00, 0x9c, 0x06, 0x07, 0x4d, 0x03, 0x04,\n    0x10, 0x00, 0x8f, 0x0b, 0x00, 0x00, 0x11, 0x00,\n    0x08, 0x00, 0x53, 0x4a, 0x51, 0x00, 0x52, 0x00,\n    0x53, 0x00, 0x3a, 0x54, 0x55, 0x00, 0x57, 0x59,\n    0x3f, 0x5d, 0x5c, 0x00, 0x46, 0x61, 0x63, 0x42,\n    0x64, 0x00, 0x66, 0x00, 0x68, 0x00, 0x6a, 0x00,\n    0x6c, 0x00, 0x6e, 0x00, 0x00, 0x40, 0x00, 0x00,\n    0x00, 0x00, 0x1a, 0x00, 0x93, 0x00, 0x00, 0x20,\n    0x35, 0x00, 0x27, 0x00, 0x21, 0x00, 0x24, 0x22,\n    0x2a, 0x00, 0x13, 0x6b, 0x6d, 0x00, 0x26, 0x24,\n    0x27, 0x14, 0x16, 0x18, 0x1b, 0x1c, 0x3e, 0x1e,\n    0x3f, 0x1f, 0x39, 0x3d, 0x22, 0x21, 0x41, 0x1e,\n    0x40, 0x25, 0x25, 0x26, 0x28, 0x20, 0x2a, 0x49,\n    0x2c, 0x43, 0x2e, 0x4b, 0x30, 0x4c, 0x32, 0x44,\n    0x42, 0x99, 0x00, 0x00, 0x95, 0x8f, 0x7d, 0x7e,\n    0x83, 0x84, 0x12, 0x80, 0x82, 0x76, 0x77, 0x12,\n    0x7b, 0xa3, 0x7c, 0x78, 0x79, 0x8a, 0x92, 0x98,\n    0xa6, 0xa0, 0x85, 0x00, 0x9a, 0xa1, 0x93, 0x75,\n    0x33, 0x95, 0x00, 0x8e, 0x00, 0x74, 0x99, 0x98,\n    0x97, 0x96, 0x00, 0x00, 0x9e, 0x00, 0x9c, 0x00,\n    0xa1, 0xa0, 0x15, 0x2e, 0x2f, 0x30, 0xb4, 0xb5,\n    0x4e, 0xaa, 0xa9, 0x12, 0x14, 0x1e, 0x21, 0x22,\n    0x22, 0x2a, 0x34, 0x35, 0xa6, 0xa7, 0x36, 0x1f,\n    0x4a, 0x00, 0x00, 0x97, 0x01, 0x5a, 0xda, 0x1d,\n    0x36, 0x05, 0x00, 0xc4, 0xc3, 0xc6, 0xc5, 0xc8,\n    0xc7, 0xca, 0xc9, 0xcc, 0xcb, 0xc4, 0xd5, 0x45,\n    0xd6, 0x42, 0xd7, 0x46, 0xd8, 0xce, 0xd0, 0xd2,\n    0xd4, 0xda, 0xd9, 0xee, 0xf6, 0xfe, 0x0e, 0x07,\n    0x0f, 0x80, 0x9f, 0x00, 0x21, 0x80, 0xa3, 0xed,\n    0x00, 0xc0, 0x40, 0xc6, 0x60, 0xe7, 0xdb, 0xe6,\n    0x99, 0xc0, 0x00, 0x00, 0x06, 0x60, 0xdc, 0x29,\n    0xfd, 0x15, 0x12, 0x06, 0x16, 0xf8, 0xdd, 0x06,\n    0x15, 0x12, 0x84, 0x08, 0xc6, 0x16, 0xff, 0xdf,\n    0x03, 0xc0, 0x40, 0x00, 0x46, 0x60, 0xde, 0xe0,\n    0x6d, 0x37, 0x38, 0x39, 0x15, 0x14, 0x17, 0x16,\n    0x00, 0x1a, 0x19, 0x1c, 0x1b, 0x00, 0x5f, 0xb7,\n    0x65, 0x44, 0x47, 0x00, 0x4f, 0x62, 0x4e, 0x50,\n    0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0xa3, 0xa4,\n    0xa5, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb6, 0x00,\n    0x00, 0x5a, 0x00, 0x48, 0x00, 0x5b, 0x56, 0x58,\n    0x60, 0x5e, 0x70, 0x69, 0x6f, 0x4d, 0x00, 0x00,\n    0x3b, 0x67, 0xb8, 0x00, 0x00, 0x45, 0xa8, 0x8a,\n    0x8b, 0x8c, 0xab, 0xac, 0x58, 0x58, 0xaf, 0x94,\n    0xb0, 0x6f, 0xb2, 0x5c, 0x5b, 0x5e, 0x5d, 0x60,\n    0x5f, 0x62, 0x61, 0x64, 0x63, 0x66, 0x65, 0x68,\n    0x67,\n};\n\nstatic const uint16_t case_conv_ext[58] = {\n    0x0399, 0x0308, 0x0301, 0x03a5, 0x0313, 0x0300, 0x0342, 0x0391,\n    0x0397, 0x03a9, 0x0046, 0x0049, 0x004c, 0x0053, 0x0069, 0x0307,\n    0x02bc, 0x004e, 0x004a, 0x030c, 0x0535, 0x0552, 0x0048, 0x0331,\n    0x0054, 0x0057, 0x030a, 0x0059, 0x0041, 0x02be, 0x1f08, 0x1f80,\n    0x1f28, 0x1f90, 0x1f68, 0x1fa0, 0x1fba, 0x0386, 0x1fb3, 0x1fca,\n    0x0389, 0x1fc3, 0x03a1, 0x1ffa, 0x038f, 0x1ff3, 0x0544, 0x0546,\n    0x053b, 0x054e, 0x053d, 0x03b8, 0x0462, 0xa64a, 0x1e60, 0x03c9,\n    0x006b, 0x00e5,\n};\n\nstatic const uint8_t unicode_prop_Cased1_table[172] = {\n    0x40, 0xa9, 0x80, 0x8e, 0x80, 0xfc, 0x80, 0xd3,\n    0x80, 0x8c, 0x80, 0x8d, 0x81, 0x8d, 0x02, 0x80,\n    0xe1, 0x80, 0x91, 0x85, 0x9a, 0x01, 0x00, 0x01,\n    0x11, 0x00, 0x01, 0x04, 0x08, 0x01, 0x08, 0x30,\n    0x08, 0x01, 0x15, 0x20, 0x00, 0x39, 0x99, 0x31,\n    0x9d, 0x84, 0x40, 0x94, 0x80, 0xd6, 0x82, 0xa6,\n    0x80, 0x41, 0x62, 0x80, 0xa6, 0x80, 0x57, 0x76,\n    0xf8, 0x02, 0x80, 0x8f, 0x80, 0xb0, 0x40, 0xdb,\n    0x08, 0x80, 0x41, 0xd0, 0x80, 0x8c, 0x80, 0x8f,\n    0x8c, 0xe4, 0x03, 0x01, 0x89, 0x00, 0x14, 0x28,\n    0x10, 0x11, 0x02, 0x01, 0x18, 0x0b, 0x24, 0x4b,\n    0x26, 0x01, 0x01, 0x86, 0xe5, 0x80, 0x60, 0x79,\n    0xb6, 0x81, 0x40, 0x91, 0x81, 0xbd, 0x88, 0x94,\n    0x05, 0x80, 0x98, 0x80, 0xc7, 0x82, 0x43, 0x34,\n    0xa2, 0x06, 0x80, 0x8c, 0x61, 0x28, 0x96, 0xd4,\n    0x80, 0xc6, 0x01, 0x08, 0x09, 0x0b, 0x80, 0x8b,\n    0x00, 0x06, 0x80, 0xc0, 0x03, 0x0f, 0x06, 0x80,\n    0x9b, 0x03, 0x04, 0x00, 0x16, 0x80, 0x41, 0x53,\n    0x81, 0x98, 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98,\n    0x80, 0x9e, 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98,\n    0x80, 0x9e, 0x80, 0x98, 0x07, 0x59, 0x63, 0x99,\n    0x85, 0x99, 0x85, 0x99,\n};\n\nstatic const uint8_t unicode_prop_Cased1_index[18] = {\n    0xb9, 0x02, 0xe0, 0xa0, 0x1e, 0x40, 0x9e, 0xa6,\n    0x40, 0xba, 0xd4, 0x01, 0x89, 0xd7, 0x01, 0x8a,\n    0xf1, 0x01,\n};\n\nstatic const uint8_t unicode_prop_Case_Ignorable_table[692] = {\n    0xa6, 0x05, 0x80, 0x8a, 0x80, 0xa2, 0x00, 0x80,\n    0xc6, 0x03, 0x00, 0x03, 0x01, 0x81, 0x41, 0xf6,\n    0x40, 0xbf, 0x19, 0x18, 0x88, 0x08, 0x80, 0x40,\n    0xfa, 0x86, 0x40, 0xce, 0x04, 0x80, 0xb0, 0xac,\n    0x00, 0x01, 0x01, 0x00, 0xab, 0x80, 0x8a, 0x85,\n    0x89, 0x8a, 0x00, 0xa2, 0x80, 0x89, 0x94, 0x8f,\n    0x80, 0xe4, 0x38, 0x89, 0x03, 0xa0, 0x00, 0x80,\n    0x9d, 0x9a, 0xda, 0x8a, 0xb9, 0x8a, 0x18, 0x08,\n    0x97, 0x97, 0xaa, 0x82, 0xf6, 0xaf, 0xb6, 0x00,\n    0x03, 0x3b, 0x02, 0x86, 0x89, 0x81, 0x8c, 0x80,\n    0x8e, 0x80, 0xb9, 0x03, 0x1f, 0x80, 0x93, 0x81,\n    0x99, 0x01, 0x81, 0xb8, 0x03, 0x0b, 0x09, 0x12,\n    0x80, 0x9d, 0x0a, 0x80, 0x8a, 0x81, 0xb8, 0x03,\n    0x20, 0x0b, 0x80, 0x93, 0x81, 0x95, 0x28, 0x80,\n    0xb9, 0x01, 0x00, 0x1f, 0x06, 0x81, 0x8a, 0x81,\n    0x9d, 0x80, 0xbc, 0x80, 0x8b, 0x80, 0xb1, 0x02,\n    0x80, 0xb8, 0x14, 0x10, 0x1e, 0x81, 0x8a, 0x81,\n    0x9c, 0x80, 0xb9, 0x01, 0x05, 0x04, 0x81, 0x93,\n    0x81, 0x9b, 0x81, 0xb8, 0x0b, 0x1f, 0x80, 0x93,\n    0x81, 0x9c, 0x80, 0xc7, 0x06, 0x10, 0x80, 0xd9,\n    0x01, 0x86, 0x8a, 0x88, 0xe1, 0x01, 0x88, 0x88,\n    0x00, 0x85, 0xc9, 0x81, 0x9a, 0x00, 0x00, 0x80,\n    0xb6, 0x8d, 0x04, 0x01, 0x84, 0x8a, 0x80, 0xa3,\n    0x88, 0x80, 0xe5, 0x18, 0x28, 0x09, 0x81, 0x98,\n    0x0b, 0x82, 0x8f, 0x83, 0x8c, 0x01, 0x0d, 0x80,\n    0x8e, 0x80, 0xdd, 0x80, 0x42, 0x5f, 0x82, 0x43,\n    0xb1, 0x82, 0x9c, 0x82, 0x9c, 0x81, 0x9d, 0x81,\n    0xbf, 0x08, 0x37, 0x01, 0x8a, 0x10, 0x20, 0xac,\n    0x83, 0xb3, 0x80, 0xc0, 0x81, 0xa1, 0x80, 0xf5,\n    0x13, 0x81, 0x88, 0x05, 0x82, 0x40, 0xda, 0x09,\n    0x80, 0xb9, 0x00, 0x30, 0x00, 0x01, 0x3d, 0x89,\n    0x08, 0xa6, 0x07, 0x90, 0xbe, 0x83, 0xaf, 0x00,\n    0x20, 0x04, 0x80, 0xa7, 0x88, 0x8b, 0x81, 0x9f,\n    0x19, 0x08, 0x82, 0xb7, 0x00, 0x0a, 0x00, 0x82,\n    0xb9, 0x39, 0x81, 0xbf, 0x85, 0xd1, 0x10, 0x8c,\n    0x06, 0x18, 0x28, 0x11, 0xb1, 0xbe, 0x8c, 0x80,\n    0xa1, 0xde, 0x04, 0x41, 0xbc, 0x00, 0x82, 0x8a,\n    0x82, 0x8c, 0x82, 0x8c, 0x82, 0x8c, 0x81, 0x8b,\n    0x27, 0x81, 0x89, 0x01, 0x01, 0x84, 0xb0, 0x20,\n    0x89, 0x00, 0x8c, 0x80, 0x8f, 0x8c, 0xb2, 0xa0,\n    0x4b, 0x8a, 0x81, 0xf0, 0x82, 0xfc, 0x80, 0x8e,\n    0x80, 0xdf, 0x9f, 0xae, 0x80, 0x41, 0xd4, 0x80,\n    0xa3, 0x1a, 0x24, 0x80, 0xdc, 0x85, 0xdc, 0x82,\n    0x60, 0x6f, 0x15, 0x80, 0x44, 0xe1, 0x85, 0x41,\n    0x0d, 0x80, 0xe1, 0x18, 0x89, 0x00, 0x9b, 0x83,\n    0xcf, 0x81, 0x8d, 0xa1, 0xcd, 0x80, 0x96, 0x82,\n    0xec, 0x0f, 0x02, 0x03, 0x80, 0x98, 0x0c, 0x80,\n    0x40, 0x96, 0x81, 0x99, 0x91, 0x8c, 0x80, 0xa5,\n    0x87, 0x98, 0x8a, 0xad, 0x82, 0xaf, 0x01, 0x19,\n    0x81, 0x90, 0x80, 0x94, 0x81, 0xc1, 0x29, 0x09,\n    0x81, 0x8b, 0x07, 0x80, 0xa2, 0x80, 0x8a, 0x80,\n    0xb2, 0x00, 0x11, 0x0c, 0x08, 0x80, 0x9a, 0x80,\n    0x8d, 0x0c, 0x08, 0x80, 0xe3, 0x84, 0x88, 0x82,\n    0xf8, 0x01, 0x03, 0x80, 0x60, 0x4f, 0x2f, 0x80,\n    0x40, 0x92, 0x8f, 0x42, 0x3d, 0x8f, 0x10, 0x8b,\n    0x8f, 0xa1, 0x01, 0x80, 0x40, 0xa8, 0x06, 0x05,\n    0x80, 0x8a, 0x80, 0xa2, 0x00, 0x80, 0xae, 0x80,\n    0xac, 0x81, 0xc2, 0x80, 0x94, 0x82, 0x42, 0x00,\n    0x80, 0x40, 0xe1, 0x80, 0x40, 0x94, 0x84, 0x46,\n    0x85, 0x10, 0x0c, 0x83, 0xa7, 0x13, 0x80, 0x40,\n    0xa4, 0x81, 0x42, 0x3c, 0x83, 0x41, 0x82, 0x81,\n    0x40, 0x98, 0x8a, 0x40, 0xaf, 0x80, 0xb5, 0x8e,\n    0xb7, 0x82, 0xb0, 0x19, 0x09, 0x80, 0x8e, 0x80,\n    0xb1, 0x82, 0xa3, 0x20, 0x87, 0xbd, 0x80, 0x8b,\n    0x81, 0xb3, 0x88, 0x89, 0x19, 0x80, 0xde, 0x11,\n    0x00, 0x0d, 0x80, 0x40, 0x9f, 0x02, 0x87, 0x94,\n    0x81, 0xb8, 0x0a, 0x80, 0xa4, 0x32, 0x84, 0x40,\n    0xc2, 0x39, 0x10, 0x80, 0x96, 0x80, 0xd3, 0x28,\n    0x03, 0x08, 0x81, 0x40, 0xed, 0x1d, 0x08, 0x81,\n    0x9a, 0x81, 0xd4, 0x39, 0x00, 0x81, 0xe9, 0x00,\n    0x01, 0x28, 0x80, 0xe4, 0x11, 0x18, 0x84, 0x41,\n    0x02, 0x88, 0x01, 0x40, 0xff, 0x08, 0x03, 0x80,\n    0x40, 0x8f, 0x19, 0x0b, 0x80, 0x9f, 0x89, 0xa7,\n    0x29, 0x1f, 0x80, 0x88, 0x29, 0x82, 0xad, 0x8c,\n    0x01, 0x41, 0x95, 0x30, 0x28, 0x80, 0xd1, 0x95,\n    0x0e, 0x01, 0x01, 0xf9, 0x2a, 0x00, 0x08, 0x30,\n    0x80, 0xc7, 0x0a, 0x00, 0x80, 0x41, 0x5a, 0x81,\n    0x55, 0x3a, 0x88, 0x60, 0x36, 0xb6, 0x84, 0xba,\n    0x86, 0x88, 0x83, 0x44, 0x0a, 0x80, 0xbe, 0x90,\n    0xbf, 0x08, 0x81, 0x60, 0x4c, 0xb7, 0x08, 0x83,\n    0x54, 0xc2, 0x82, 0x88, 0x8f, 0x0e, 0x9d, 0x83,\n    0x40, 0x93, 0x82, 0x47, 0xba, 0xb6, 0x83, 0xb1,\n    0x38, 0x8d, 0x80, 0x95, 0x20, 0x8e, 0x45, 0x4f,\n    0x30, 0x90, 0x0e, 0x01, 0x04, 0x41, 0x04, 0x8d,\n    0x41, 0xad, 0x83, 0x45, 0xdf, 0x86, 0xec, 0x87,\n    0x4a, 0xae, 0x84, 0x6c, 0x0c, 0x00, 0x80, 0x9d,\n    0xdf, 0xff, 0x40, 0xef,\n};\n\nstatic const uint8_t unicode_prop_Case_Ignorable_index[66] = {\n    0xbe, 0x05, 0x00, 0xfe, 0x07, 0x00, 0x52, 0x0a,\n    0x20, 0x05, 0x0c, 0x20, 0x3b, 0x0e, 0x40, 0x61,\n    0x10, 0x40, 0x0f, 0x18, 0x20, 0x43, 0x1b, 0x60,\n    0x79, 0x1d, 0x00, 0xf1, 0x20, 0x00, 0x0d, 0xa6,\n    0x40, 0x2e, 0xa9, 0x20, 0xde, 0xaa, 0x00, 0x0f,\n    0xff, 0x20, 0xe7, 0x0a, 0x41, 0x82, 0x11, 0x21,\n    0xc4, 0x14, 0x61, 0x44, 0x19, 0x01, 0x48, 0x1d,\n    0x21, 0xa4, 0xbc, 0x01, 0x3e, 0xe1, 0x01, 0xf0,\n    0x01, 0x0e,\n};\n\nstatic const uint8_t unicode_prop_ID_Start_table[1045] = {\n    0xc0, 0x99, 0x85, 0x99, 0xae, 0x80, 0x89, 0x03,\n    0x04, 0x96, 0x80, 0x9e, 0x80, 0x41, 0xc9, 0x83,\n    0x8b, 0x8d, 0x26, 0x00, 0x80, 0x40, 0x80, 0x20,\n    0x09, 0x18, 0x05, 0x00, 0x10, 0x00, 0x93, 0x80,\n    0xd2, 0x80, 0x40, 0x8a, 0x87, 0x40, 0xa5, 0x80,\n    0xa5, 0x08, 0x85, 0xa8, 0xc6, 0x9a, 0x1b, 0xac,\n    0xaa, 0xa2, 0x08, 0xe2, 0x00, 0x8e, 0x0e, 0x81,\n    0x89, 0x11, 0x80, 0x8f, 0x00, 0x9d, 0x9c, 0xd8,\n    0x8a, 0x80, 0x97, 0xa0, 0x88, 0x0b, 0x04, 0x95,\n    0x18, 0x88, 0x02, 0x80, 0x96, 0x98, 0x86, 0x8a,\n    0xb4, 0x94, 0x80, 0x91, 0xbb, 0xb5, 0x10, 0x91,\n    0x06, 0x89, 0x8e, 0x8f, 0x1f, 0x09, 0x81, 0x95,\n    0x06, 0x00, 0x13, 0x10, 0x8f, 0x80, 0x8c, 0x08,\n    0x82, 0x8d, 0x81, 0x89, 0x07, 0x2b, 0x09, 0x95,\n    0x06, 0x01, 0x01, 0x01, 0x9e, 0x18, 0x80, 0x92,\n    0x82, 0x8f, 0x88, 0x02, 0x80, 0x95, 0x06, 0x01,\n    0x04, 0x10, 0x91, 0x80, 0x8e, 0x81, 0x96, 0x80,\n    0x8a, 0x39, 0x09, 0x95, 0x06, 0x01, 0x04, 0x10,\n    0x9d, 0x08, 0x82, 0x8e, 0x80, 0x90, 0x00, 0x2a,\n    0x10, 0x1a, 0x08, 0x00, 0x0a, 0x0a, 0x12, 0x8b,\n    0x95, 0x80, 0xb3, 0x38, 0x10, 0x96, 0x80, 0x8f,\n    0x10, 0x99, 0x14, 0x81, 0x9d, 0x03, 0x38, 0x10,\n    0x96, 0x80, 0x89, 0x04, 0x10, 0x9f, 0x00, 0x81,\n    0x8e, 0x81, 0x90, 0x88, 0x02, 0x80, 0xa8, 0x08,\n    0x8f, 0x04, 0x17, 0x82, 0x97, 0x2c, 0x91, 0x82,\n    0x97, 0x80, 0x88, 0x00, 0x0e, 0xb9, 0xaf, 0x01,\n    0x8b, 0x86, 0xb9, 0x08, 0x00, 0x20, 0x97, 0x00,\n    0x80, 0x89, 0x01, 0x88, 0x01, 0x20, 0x80, 0x94,\n    0x83, 0x9f, 0x80, 0xbe, 0x38, 0xa3, 0x9a, 0x84,\n    0xf2, 0xaa, 0x93, 0x80, 0x8f, 0x2b, 0x1a, 0x02,\n    0x0e, 0x13, 0x8c, 0x8b, 0x80, 0x90, 0xa5, 0x00,\n    0x20, 0x81, 0xaa, 0x80, 0x41, 0x4c, 0x03, 0x0e,\n    0x00, 0x03, 0x81, 0xa8, 0x03, 0x81, 0xa0, 0x03,\n    0x0e, 0x00, 0x03, 0x81, 0x8e, 0x80, 0xb8, 0x03,\n    0x81, 0xc2, 0xa4, 0x8f, 0x8f, 0xd5, 0x0d, 0x82,\n    0x42, 0x6b, 0x81, 0x90, 0x80, 0x99, 0x84, 0xca,\n    0x82, 0x8a, 0x86, 0x8c, 0x03, 0x8d, 0x91, 0x8d,\n    0x91, 0x8d, 0x8c, 0x02, 0x8e, 0xb3, 0xa2, 0x03,\n    0x80, 0xc2, 0xd8, 0x86, 0xa8, 0x00, 0x84, 0xc5,\n    0x89, 0x9e, 0xb0, 0x9d, 0x0c, 0x8a, 0xab, 0x83,\n    0x99, 0xb5, 0x96, 0x88, 0xb4, 0xd1, 0x80, 0xdc,\n    0xae, 0x90, 0x86, 0xb6, 0x9d, 0x8c, 0x81, 0x89,\n    0xab, 0x99, 0xa3, 0xa8, 0x82, 0x89, 0xa3, 0x81,\n    0x88, 0x86, 0xaa, 0x0a, 0xa8, 0x18, 0x28, 0x0a,\n    0x04, 0x40, 0xbf, 0xbf, 0x41, 0x15, 0x0d, 0x81,\n    0xa5, 0x0d, 0x0f, 0x00, 0x00, 0x00, 0x80, 0x9e,\n    0x81, 0xb4, 0x06, 0x00, 0x12, 0x06, 0x13, 0x0d,\n    0x83, 0x8c, 0x22, 0x06, 0xf3, 0x80, 0x8c, 0x80,\n    0x8f, 0x8c, 0xe4, 0x03, 0x01, 0x89, 0x00, 0x0d,\n    0x28, 0x00, 0x00, 0x80, 0x8f, 0x0b, 0x24, 0x18,\n    0x90, 0xa8, 0x4a, 0x76, 0xae, 0x80, 0xae, 0x80,\n    0x40, 0x84, 0x2b, 0x11, 0x8b, 0xa5, 0x00, 0x20,\n    0x81, 0xb7, 0x30, 0x8f, 0x96, 0x88, 0x30, 0x30,\n    0x30, 0x30, 0x30, 0x30, 0x30, 0x86, 0x42, 0x25,\n    0x82, 0x98, 0x88, 0x34, 0x0c, 0x83, 0xd5, 0x1c,\n    0x80, 0xd9, 0x03, 0x84, 0xaa, 0x80, 0xdd, 0x90,\n    0x9f, 0xaf, 0x8f, 0x41, 0xff, 0x59, 0xbf, 0xbf,\n    0x60, 0x51, 0xfc, 0x82, 0x44, 0x8c, 0xc2, 0xad,\n    0x81, 0x41, 0x0c, 0x82, 0x8f, 0x89, 0x81, 0x93,\n    0xae, 0x8f, 0x9e, 0x81, 0xcf, 0xa6, 0x88, 0x81,\n    0xe6, 0x81, 0xb4, 0x81, 0x88, 0xa9, 0x8c, 0x02,\n    0x03, 0x80, 0x96, 0x9c, 0xb3, 0x8d, 0xb1, 0xbd,\n    0x2a, 0x00, 0x81, 0x8a, 0x9b, 0x89, 0x96, 0x98,\n    0x9c, 0x86, 0xae, 0x9b, 0x80, 0x8f, 0x20, 0x89,\n    0x89, 0x20, 0xa8, 0x96, 0x10, 0x87, 0x93, 0x96,\n    0x10, 0x82, 0xb1, 0x00, 0x11, 0x0c, 0x08, 0x00,\n    0x97, 0x11, 0x8a, 0x32, 0x8b, 0x29, 0x29, 0x85,\n    0x88, 0x30, 0x30, 0xaa, 0x80, 0x8d, 0x85, 0xf2,\n    0x9c, 0x60, 0x2b, 0xa3, 0x8b, 0x96, 0x83, 0xb0,\n    0x60, 0x21, 0x03, 0x41, 0x6d, 0x81, 0xe9, 0xa5,\n    0x86, 0x8b, 0x24, 0x00, 0x89, 0x80, 0x8c, 0x04,\n    0x00, 0x01, 0x01, 0x80, 0xeb, 0xa0, 0x41, 0x6a,\n    0x91, 0xbf, 0x81, 0xb5, 0xa7, 0x8b, 0xf3, 0x20,\n    0x40, 0x86, 0xa3, 0x99, 0x85, 0x99, 0x8a, 0xd8,\n    0x15, 0x0d, 0x0d, 0x0a, 0xa2, 0x8b, 0x80, 0x99,\n    0x80, 0x92, 0x01, 0x80, 0x8e, 0x81, 0x8d, 0xa1,\n    0xfa, 0xc4, 0xb4, 0x41, 0x0a, 0x9c, 0x82, 0xb0,\n    0xae, 0x9f, 0x8c, 0x9d, 0x84, 0xa5, 0x89, 0x9d,\n    0x81, 0xa3, 0x1f, 0x04, 0xa9, 0x40, 0x9d, 0x91,\n    0xa3, 0x83, 0xa3, 0x83, 0xa7, 0x87, 0xb3, 0x40,\n    0x9b, 0x41, 0x36, 0x88, 0x95, 0x89, 0x87, 0x40,\n    0x97, 0x29, 0x00, 0xab, 0x01, 0x10, 0x81, 0x96,\n    0x89, 0x96, 0x88, 0x9e, 0xc0, 0x92, 0x01, 0x89,\n    0x95, 0x89, 0x99, 0xc5, 0xb7, 0x29, 0xbf, 0x80,\n    0x8e, 0x18, 0x10, 0x9c, 0xa9, 0x9c, 0x82, 0x9c,\n    0xa2, 0x38, 0x9b, 0x9a, 0xb5, 0x89, 0x95, 0x89,\n    0x92, 0x8c, 0x91, 0xed, 0xc8, 0xb6, 0xb2, 0x8c,\n    0xb2, 0x8c, 0xa3, 0x41, 0x5b, 0xa9, 0x29, 0xcd,\n    0x9c, 0x89, 0x07, 0x95, 0xe9, 0x94, 0x9a, 0x96,\n    0x8b, 0xb4, 0xca, 0xac, 0x9f, 0x98, 0x99, 0xa3,\n    0x9c, 0x01, 0x07, 0xa2, 0x10, 0x8b, 0xaf, 0x8d,\n    0x83, 0x94, 0x00, 0x80, 0xa2, 0x91, 0x80, 0x98,\n    0xd3, 0x30, 0x00, 0x18, 0x8e, 0x80, 0x89, 0x86,\n    0xae, 0xa5, 0x39, 0x09, 0x95, 0x06, 0x01, 0x04,\n    0x10, 0x91, 0x80, 0x8b, 0x84, 0x40, 0x9d, 0xb4,\n    0x91, 0x83, 0x93, 0x82, 0x9d, 0xaf, 0x93, 0x08,\n    0x80, 0x40, 0xb7, 0xae, 0xa8, 0x83, 0xa3, 0xaf,\n    0x93, 0x80, 0xba, 0xaa, 0x8c, 0x80, 0xc6, 0x9a,\n    0x40, 0xe4, 0xab, 0xf3, 0xbf, 0x9e, 0x39, 0x01,\n    0x38, 0x08, 0x97, 0x8e, 0x00, 0x80, 0xdd, 0x39,\n    0xa6, 0x8f, 0x00, 0x80, 0x9b, 0x80, 0x89, 0xa7,\n    0x30, 0x94, 0x80, 0x8a, 0xad, 0x92, 0x80, 0xa1,\n    0xb8, 0x41, 0x06, 0x88, 0x80, 0xa4, 0x90, 0x80,\n    0xb0, 0x9d, 0xef, 0x30, 0x08, 0xa5, 0x94, 0x80,\n    0x98, 0x28, 0x08, 0x9f, 0x8d, 0x80, 0x41, 0x46,\n    0x92, 0x40, 0xbc, 0x80, 0xce, 0x43, 0x99, 0xe5,\n    0xee, 0x90, 0x40, 0xc3, 0x4a, 0xbb, 0x44, 0x2e,\n    0x4f, 0xd0, 0x42, 0x46, 0x60, 0x21, 0xb8, 0x42,\n    0x38, 0x86, 0x9e, 0xf0, 0x9d, 0x91, 0xaf, 0x8f,\n    0x83, 0x9e, 0x94, 0x84, 0x92, 0x42, 0xaf, 0xbf,\n    0xff, 0xca, 0x20, 0xc1, 0x8c, 0xbf, 0x08, 0x80,\n    0x9b, 0x57, 0xf7, 0x87, 0x44, 0xd5, 0xa9, 0x88,\n    0x60, 0x22, 0xf6, 0x41, 0x1e, 0xb0, 0x82, 0x90,\n    0x1f, 0x41, 0x8b, 0x49, 0x03, 0xea, 0x84, 0x8c,\n    0x82, 0x88, 0x86, 0x89, 0x57, 0x65, 0xd4, 0x80,\n    0xc6, 0x01, 0x08, 0x09, 0x0b, 0x80, 0x8b, 0x00,\n    0x06, 0x80, 0xc0, 0x03, 0x0f, 0x06, 0x80, 0x9b,\n    0x03, 0x04, 0x00, 0x16, 0x80, 0x41, 0x53, 0x81,\n    0x98, 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98, 0x80,\n    0x9e, 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98, 0x80,\n    0x9e, 0x80, 0x98, 0x07, 0x49, 0x33, 0xac, 0x89,\n    0x86, 0x8f, 0x80, 0x41, 0x70, 0xab, 0x45, 0x13,\n    0x40, 0xc4, 0xba, 0xc3, 0x30, 0x44, 0xb3, 0x18,\n    0x9a, 0x01, 0x00, 0x08, 0x80, 0x89, 0x03, 0x00,\n    0x00, 0x28, 0x18, 0x00, 0x00, 0x02, 0x01, 0x00,\n    0x08, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x0b,\n    0x06, 0x03, 0x03, 0x00, 0x80, 0x89, 0x80, 0x90,\n    0x22, 0x04, 0x80, 0x90, 0x51, 0x43, 0x60, 0xa6,\n    0xdd, 0xa1, 0x50, 0x34, 0x8a, 0x40, 0xdd, 0x81,\n    0x56, 0x81, 0x8d, 0x5d, 0x30, 0x4c, 0x1e, 0x42,\n    0x1d, 0x45, 0xe1, 0x53, 0x4a,\n};\n\nstatic const uint8_t unicode_prop_ID_Start_index[99] = {\n    0xf6, 0x03, 0x20, 0xa6, 0x07, 0x00, 0xa9, 0x09,\n    0x00, 0xb4, 0x0a, 0x00, 0xba, 0x0b, 0x00, 0x3e,\n    0x0d, 0x00, 0xe0, 0x0e, 0x20, 0x57, 0x12, 0x00,\n    0xeb, 0x16, 0x00, 0xca, 0x19, 0x20, 0xc0, 0x1d,\n    0x60, 0x80, 0x20, 0x00, 0x2e, 0x2d, 0x00, 0xc0,\n    0x31, 0x20, 0x89, 0xa7, 0x20, 0xf0, 0xa9, 0x00,\n    0xe3, 0xab, 0x00, 0x3e, 0xfd, 0x00, 0xfb, 0x00,\n    0x21, 0x37, 0x07, 0x61, 0x01, 0x0a, 0x01, 0x1d,\n    0x0f, 0x21, 0x2c, 0x12, 0x01, 0xc8, 0x14, 0x21,\n    0xd1, 0x19, 0x21, 0x47, 0x1d, 0x01, 0x39, 0x6a,\n    0x21, 0x09, 0x8d, 0x01, 0xbc, 0xd4, 0x01, 0xa9,\n    0xd7, 0x21, 0x3a, 0xee, 0x01, 0xde, 0xa6, 0x22,\n    0x4b, 0x13, 0x03,\n};\n\nstatic const uint8_t unicode_prop_ID_Continue1_table[626] = {\n    0xaf, 0x89, 0xa4, 0x80, 0xd6, 0x80, 0x42, 0x47,\n    0xef, 0x96, 0x80, 0x40, 0xfa, 0x84, 0x41, 0x08,\n    0xac, 0x00, 0x01, 0x01, 0x00, 0xc7, 0x8a, 0xaf,\n    0x9e, 0x28, 0xe4, 0x31, 0x29, 0x08, 0x19, 0x89,\n    0x96, 0x80, 0x9d, 0x9a, 0xda, 0x8a, 0x8e, 0x89,\n    0xa0, 0x88, 0x88, 0x80, 0x97, 0x18, 0x88, 0x02,\n    0x04, 0xaa, 0x82, 0xf6, 0x8e, 0x80, 0xa0, 0xb5,\n    0x10, 0x91, 0x06, 0x89, 0x09, 0x89, 0x90, 0x82,\n    0xb7, 0x00, 0x31, 0x09, 0x82, 0x88, 0x80, 0x89,\n    0x09, 0x89, 0x8d, 0x01, 0x82, 0xb7, 0x00, 0x23,\n    0x09, 0x12, 0x80, 0x93, 0x8b, 0x10, 0x8a, 0x82,\n    0xb7, 0x00, 0x38, 0x10, 0x82, 0x93, 0x09, 0x89,\n    0x89, 0x28, 0x82, 0xb7, 0x00, 0x31, 0x09, 0x16,\n    0x82, 0x89, 0x09, 0x89, 0x91, 0x80, 0xba, 0x22,\n    0x10, 0x83, 0x88, 0x80, 0x8d, 0x89, 0x8f, 0x84,\n    0xb8, 0x30, 0x10, 0x1e, 0x81, 0x8a, 0x09, 0x89,\n    0x90, 0x82, 0xb7, 0x00, 0x30, 0x10, 0x1e, 0x81,\n    0x8a, 0x09, 0x89, 0x8f, 0x83, 0xb6, 0x08, 0x30,\n    0x10, 0x83, 0x88, 0x80, 0x89, 0x09, 0x89, 0x90,\n    0x82, 0xc5, 0x03, 0x28, 0x00, 0x3d, 0x89, 0x09,\n    0xbc, 0x01, 0x86, 0x8b, 0x38, 0x89, 0xd6, 0x01,\n    0x88, 0x8a, 0x29, 0x89, 0xbd, 0x0d, 0x89, 0x8a,\n    0x00, 0x00, 0x03, 0x81, 0xb0, 0x93, 0x01, 0x84,\n    0x8a, 0x80, 0xa3, 0x88, 0x80, 0xe3, 0x93, 0x80,\n    0x89, 0x8b, 0x1b, 0x10, 0x11, 0x32, 0x83, 0x8c,\n    0x8b, 0x80, 0x8e, 0x42, 0xbe, 0x82, 0x88, 0x88,\n    0x43, 0x9f, 0x82, 0x9c, 0x82, 0x9c, 0x81, 0x9d,\n    0x81, 0xbf, 0x9f, 0x88, 0x01, 0x89, 0xa0, 0x11,\n    0x89, 0x40, 0x8e, 0x80, 0xf5, 0x8b, 0x83, 0x8b,\n    0x89, 0x89, 0xff, 0x8a, 0xbb, 0x84, 0xb8, 0x89,\n    0x80, 0x9c, 0x81, 0x8a, 0x85, 0x89, 0x95, 0x8d,\n    0x01, 0xbe, 0x84, 0xae, 0x90, 0x8a, 0x89, 0x90,\n    0x88, 0x8b, 0x82, 0x9d, 0x8c, 0x81, 0x89, 0xab,\n    0x8d, 0xaf, 0x93, 0x87, 0x89, 0x85, 0x89, 0xf5,\n    0x10, 0x94, 0x18, 0x28, 0x0a, 0x40, 0xc5, 0xb9,\n    0x04, 0x42, 0x3e, 0x81, 0x92, 0x80, 0xfa, 0x8c,\n    0x18, 0x82, 0x8b, 0x4b, 0xfd, 0x82, 0x40, 0x8c,\n    0x80, 0xdf, 0x9f, 0x42, 0x29, 0x85, 0xe8, 0x81,\n    0x60, 0x75, 0x84, 0x89, 0xc4, 0x03, 0x89, 0x9f,\n    0x81, 0xcf, 0x81, 0x41, 0x0f, 0x02, 0x03, 0x80,\n    0x96, 0x23, 0x80, 0xd2, 0x81, 0xb1, 0x91, 0x89,\n    0x89, 0x85, 0x91, 0x8c, 0x8a, 0x9b, 0x87, 0x98,\n    0x8c, 0xab, 0x83, 0xae, 0x8d, 0x8e, 0x89, 0x8a,\n    0x80, 0x89, 0x89, 0xae, 0x8d, 0x8b, 0x07, 0x09,\n    0x89, 0xa0, 0x82, 0xb1, 0x00, 0x11, 0x0c, 0x08,\n    0x80, 0xa8, 0x24, 0x81, 0x40, 0xeb, 0x38, 0x09,\n    0x89, 0x60, 0x4f, 0x23, 0x80, 0x42, 0xe0, 0x8f,\n    0x8f, 0x8f, 0x11, 0x97, 0x82, 0x40, 0xbf, 0x89,\n    0xa4, 0x80, 0x42, 0xbc, 0x80, 0x40, 0xe1, 0x80,\n    0x40, 0x94, 0x84, 0x41, 0x24, 0x89, 0x45, 0x56,\n    0x10, 0x0c, 0x83, 0xa7, 0x13, 0x80, 0x40, 0xa4,\n    0x81, 0x42, 0x3c, 0x1f, 0x89, 0x41, 0x70, 0x81,\n    0x40, 0x98, 0x8a, 0x40, 0xae, 0x82, 0xb4, 0x8e,\n    0x9e, 0x89, 0x8e, 0x83, 0xac, 0x8a, 0xb4, 0x89,\n    0x2a, 0xa3, 0x8d, 0x80, 0x89, 0x21, 0xab, 0x80,\n    0x8b, 0x82, 0xaf, 0x8d, 0x3b, 0x80, 0x8b, 0xd1,\n    0x8b, 0x28, 0x40, 0x9f, 0x8b, 0x84, 0x89, 0x2b,\n    0xb6, 0x08, 0x31, 0x09, 0x82, 0x88, 0x80, 0x89,\n    0x09, 0x32, 0x84, 0x40, 0xbf, 0x91, 0x88, 0x89,\n    0x18, 0xd0, 0x93, 0x8b, 0x89, 0x40, 0xd4, 0x31,\n    0x88, 0x9a, 0x81, 0xd1, 0x90, 0x8e, 0x89, 0xd0,\n    0x8c, 0x87, 0x89, 0xd2, 0x8e, 0x83, 0x89, 0x40,\n    0xf1, 0x8e, 0x40, 0xa4, 0x89, 0xc5, 0x28, 0x09,\n    0x18, 0x00, 0x81, 0x8b, 0x89, 0xf6, 0x31, 0x32,\n    0x80, 0x9b, 0x89, 0xa7, 0x30, 0x1f, 0x80, 0x88,\n    0x8a, 0xad, 0x8f, 0x41, 0x94, 0x38, 0x87, 0x8f,\n    0x89, 0xb7, 0x95, 0x80, 0x8d, 0xf9, 0x2a, 0x00,\n    0x08, 0x30, 0x07, 0x89, 0xaf, 0x20, 0x08, 0x27,\n    0x89, 0x41, 0x48, 0x83, 0x60, 0x4b, 0x68, 0x89,\n    0x40, 0x85, 0x84, 0xba, 0x86, 0x98, 0x89, 0x43,\n    0xf4, 0x00, 0xb6, 0x33, 0xd0, 0x80, 0x8a, 0x81,\n    0x60, 0x4c, 0xaa, 0x81, 0x54, 0xc5, 0x22, 0x2f,\n    0x39, 0x86, 0x9d, 0x83, 0x40, 0x93, 0x82, 0x45,\n    0x88, 0xb1, 0x41, 0xff, 0xb6, 0x83, 0xb1, 0x38,\n    0x8d, 0x80, 0x95, 0x20, 0x8e, 0x45, 0x4f, 0x30,\n    0x90, 0x0e, 0x01, 0x04, 0x41, 0x04, 0x86, 0x88,\n    0x89, 0x41, 0xa1, 0x8d, 0x45, 0xd5, 0x86, 0xec,\n    0x34, 0x89, 0x52, 0x95, 0x89, 0x6c, 0x05, 0x05,\n    0x40, 0xef,\n};\n\nstatic const uint8_t unicode_prop_ID_Continue1_index[60] = {\n    0xfa, 0x06, 0x00, 0x84, 0x09, 0x00, 0xf0, 0x0a,\n    0x00, 0x70, 0x0c, 0x00, 0xf4, 0x0d, 0x00, 0x4a,\n    0x10, 0x20, 0x1a, 0x18, 0x20, 0x74, 0x1b, 0x20,\n    0xdd, 0x20, 0x00, 0x0c, 0xa8, 0x00, 0x5a, 0xaa,\n    0x20, 0x1a, 0xff, 0x00, 0xad, 0x0e, 0x01, 0x38,\n    0x12, 0x21, 0xc1, 0x15, 0x21, 0xe5, 0x19, 0x21,\n    0xaa, 0x1d, 0x21, 0x8c, 0xd1, 0x41, 0x4a, 0xe1,\n    0x21, 0xf0, 0x01, 0x0e,\n};\n\n#ifdef CONFIG_ALL_UNICODE\n\nstatic const uint8_t unicode_cc_table[851] = {\n    0xb2, 0xcf, 0xd4, 0x00, 0xe8, 0x03, 0xdc, 0x00,\n    0xe8, 0x00, 0xd8, 0x04, 0xdc, 0x01, 0xca, 0x03,\n    0xdc, 0x01, 0xca, 0x0a, 0xdc, 0x04, 0x01, 0x03,\n    0xdc, 0xc7, 0x00, 0xf0, 0xc0, 0x02, 0xdc, 0xc2,\n    0x01, 0xdc, 0x80, 0xc2, 0x03, 0xdc, 0xc0, 0x00,\n    0xe8, 0x01, 0xdc, 0xc0, 0x41, 0xe9, 0x00, 0xea,\n    0x41, 0xe9, 0x00, 0xea, 0x00, 0xe9, 0xcc, 0xb0,\n    0xe2, 0xc4, 0xb0, 0xd8, 0x00, 0xdc, 0xc3, 0x00,\n    0xdc, 0xc2, 0x00, 0xde, 0x00, 0xdc, 0xc5, 0x05,\n    0xdc, 0xc1, 0x00, 0xdc, 0xc1, 0x00, 0xde, 0x00,\n    0xe4, 0xc0, 0x49, 0x0a, 0x43, 0x13, 0x80, 0x00,\n    0x17, 0x80, 0x41, 0x18, 0x80, 0xc0, 0x00, 0xdc,\n    0x80, 0x00, 0x12, 0xb0, 0x17, 0xc7, 0x42, 0x1e,\n    0xaf, 0x47, 0x1b, 0xc1, 0x01, 0xdc, 0xc4, 0x00,\n    0xdc, 0xc1, 0x00, 0xdc, 0x8f, 0x00, 0x23, 0xb0,\n    0x34, 0xc6, 0x81, 0xc3, 0x00, 0xdc, 0xc0, 0x81,\n    0xc1, 0x80, 0x00, 0xdc, 0xc1, 0x00, 0xdc, 0xa2,\n    0x00, 0x24, 0x9d, 0xc0, 0x00, 0xdc, 0xc1, 0x00,\n    0xdc, 0xc1, 0x02, 0xdc, 0xc0, 0x01, 0xdc, 0xc0,\n    0x00, 0xdc, 0xc2, 0x00, 0xdc, 0xc0, 0x00, 0xdc,\n    0xc0, 0x00, 0xdc, 0xc0, 0x00, 0xdc, 0xc1, 0xb0,\n    0x6f, 0xc6, 0x00, 0xdc, 0xc0, 0x88, 0x00, 0xdc,\n    0x97, 0xc3, 0x80, 0xc8, 0x80, 0xc2, 0x80, 0xc4,\n    0xaa, 0x02, 0xdc, 0xb0, 0x46, 0x00, 0xdc, 0xcd,\n    0x80, 0x00, 0xdc, 0xc1, 0x00, 0xdc, 0xc1, 0x00,\n    0xdc, 0xc2, 0x02, 0xdc, 0x42, 0x1b, 0xc2, 0x00,\n    0xdc, 0xc1, 0x01, 0xdc, 0xc4, 0xb0, 0x0b, 0x00,\n    0x07, 0x8f, 0x00, 0x09, 0x82, 0xc0, 0x00, 0xdc,\n    0xc1, 0xb0, 0x36, 0x00, 0x07, 0x8f, 0x00, 0x09,\n    0xaf, 0xc0, 0xb0, 0x0c, 0x00, 0x07, 0x8f, 0x00,\n    0x09, 0xb0, 0x3d, 0x00, 0x07, 0x8f, 0x00, 0x09,\n    0xb0, 0x3d, 0x00, 0x07, 0x8f, 0x00, 0x09, 0xb0,\n    0x4e, 0x00, 0x09, 0xb0, 0x4e, 0x00, 0x09, 0x86,\n    0x00, 0x54, 0x00, 0x5b, 0xb0, 0x34, 0x00, 0x07,\n    0x8f, 0x00, 0x09, 0xb0, 0x3c, 0x01, 0x09, 0x8f,\n    0x00, 0x09, 0xb0, 0x4b, 0x00, 0x09, 0xb0, 0x3c,\n    0x01, 0x67, 0x00, 0x09, 0x8c, 0x03, 0x6b, 0xb0,\n    0x3b, 0x01, 0x76, 0x00, 0x09, 0x8c, 0x03, 0x7a,\n    0xb0, 0x1b, 0x01, 0xdc, 0x9a, 0x00, 0xdc, 0x80,\n    0x00, 0xdc, 0x80, 0x00, 0xd8, 0xb0, 0x06, 0x41,\n    0x81, 0x80, 0x00, 0x84, 0x84, 0x03, 0x82, 0x81,\n    0x00, 0x82, 0x80, 0xc1, 0x00, 0x09, 0x80, 0xc1,\n    0xb0, 0x0d, 0x00, 0xdc, 0xb0, 0x3f, 0x00, 0x07,\n    0x80, 0x01, 0x09, 0xb0, 0x21, 0x00, 0xdc, 0xb2,\n    0x9e, 0xc2, 0xb3, 0x83, 0x00, 0x09, 0x9e, 0x00,\n    0x09, 0xb0, 0x6c, 0x00, 0x09, 0x89, 0xc0, 0xb0,\n    0x9a, 0x00, 0xe4, 0xb0, 0x5e, 0x00, 0xde, 0xc0,\n    0x00, 0xdc, 0xb0, 0xaa, 0xc0, 0x00, 0xdc, 0xb0,\n    0x16, 0x00, 0x09, 0x93, 0xc7, 0x81, 0x00, 0xdc,\n    0xaf, 0xc4, 0x05, 0xdc, 0xc1, 0x00, 0xdc, 0x80,\n    0x01, 0xdc, 0xb0, 0x42, 0x00, 0x07, 0x8e, 0x00,\n    0x09, 0xa5, 0xc0, 0x00, 0xdc, 0xc6, 0xb0, 0x05,\n    0x01, 0x09, 0xb0, 0x09, 0x00, 0x07, 0x8a, 0x01,\n    0x09, 0xb0, 0x12, 0x00, 0x07, 0xb0, 0x67, 0xc2,\n    0x41, 0x00, 0x04, 0xdc, 0xc1, 0x03, 0xdc, 0xc0,\n    0x41, 0x00, 0x05, 0x01, 0x83, 0x00, 0xdc, 0x85,\n    0xc0, 0x82, 0xc1, 0xb0, 0x95, 0xc1, 0x00, 0xdc,\n    0xc6, 0x00, 0xdc, 0xc1, 0x00, 0xea, 0x00, 0xd6,\n    0x00, 0xdc, 0x00, 0xca, 0xe4, 0x00, 0xe8, 0x01,\n    0xe4, 0x00, 0xdc, 0x80, 0xc0, 0x00, 0xe9, 0x00,\n    0xdc, 0xc0, 0x00, 0xdc, 0xb2, 0x9f, 0xc1, 0x01,\n    0x01, 0xc3, 0x02, 0x01, 0xc1, 0x83, 0xc0, 0x82,\n    0x01, 0x01, 0xc0, 0x00, 0xdc, 0xc0, 0x01, 0x01,\n    0x03, 0xdc, 0xc0, 0xb8, 0x03, 0xcd, 0xc2, 0xb0,\n    0x5c, 0x00, 0x09, 0xb0, 0x2f, 0xdf, 0xb1, 0xf9,\n    0x00, 0xda, 0x00, 0xe4, 0x00, 0xe8, 0x00, 0xde,\n    0x01, 0xe0, 0xb0, 0x38, 0x01, 0x08, 0xb8, 0x6d,\n    0xa3, 0xc0, 0x83, 0xc9, 0x9f, 0xc1, 0xb0, 0x1f,\n    0xc1, 0xb0, 0xe3, 0x00, 0x09, 0xa4, 0x00, 0x09,\n    0xb0, 0x66, 0x00, 0x09, 0x9a, 0xd1, 0xb0, 0x08,\n    0x02, 0xdc, 0xa4, 0x00, 0x09, 0xb0, 0x2e, 0x00,\n    0x07, 0x8b, 0x00, 0x09, 0xb0, 0xbe, 0xc0, 0x80,\n    0xc1, 0x00, 0xdc, 0x81, 0xc1, 0x84, 0xc1, 0x80,\n    0xc0, 0xb0, 0x03, 0x00, 0x09, 0xb0, 0xc5, 0x00,\n    0x09, 0xb8, 0x46, 0xff, 0x00, 0x1a, 0xb2, 0xd0,\n    0xc6, 0x06, 0xdc, 0xc1, 0xb3, 0x9c, 0x00, 0xdc,\n    0xb0, 0xb1, 0x00, 0xdc, 0xb0, 0x64, 0xc4, 0xb6,\n    0x61, 0x00, 0xdc, 0x80, 0xc0, 0xa7, 0xc0, 0x00,\n    0x01, 0x00, 0xdc, 0x83, 0x00, 0x09, 0xb0, 0x74,\n    0xc0, 0x00, 0xdc, 0xb2, 0x0c, 0xc3, 0xb1, 0x52,\n    0xc1, 0xb0, 0x68, 0x01, 0xdc, 0xc2, 0x00, 0xdc,\n    0xc0, 0x03, 0xdc, 0xb0, 0xc4, 0x00, 0x09, 0xb0,\n    0x07, 0x00, 0x09, 0xb0, 0x08, 0x00, 0x09, 0x00,\n    0x07, 0xb0, 0x14, 0xc2, 0xaf, 0x01, 0x09, 0xb0,\n    0x0d, 0x00, 0x07, 0xb0, 0x1b, 0x00, 0x09, 0x88,\n    0x00, 0x07, 0xb0, 0x39, 0x00, 0x09, 0x00, 0x07,\n    0xb0, 0x81, 0x00, 0x07, 0x00, 0x09, 0xb0, 0x1f,\n    0x01, 0x07, 0x8f, 0x00, 0x09, 0x97, 0xc6, 0x82,\n    0xc4, 0xb0, 0x9c, 0x00, 0x09, 0x82, 0x00, 0x07,\n    0x96, 0xc0, 0xb0, 0x32, 0x00, 0x09, 0x00, 0x07,\n    0xb0, 0xca, 0x00, 0x09, 0x00, 0x07, 0xb0, 0x4d,\n    0x00, 0x09, 0xb0, 0x45, 0x00, 0x09, 0x00, 0x07,\n    0xb0, 0x42, 0x00, 0x09, 0xb0, 0xdc, 0x00, 0x09,\n    0x00, 0x07, 0xb0, 0xd1, 0x01, 0x09, 0x83, 0x00,\n    0x07, 0xb0, 0x6b, 0x00, 0x09, 0xb0, 0x22, 0x00,\n    0x09, 0x91, 0x00, 0x09, 0xb0, 0x20, 0x00, 0x09,\n    0xb1, 0x74, 0x00, 0x09, 0xb0, 0xd1, 0x00, 0x07,\n    0x80, 0x01, 0x09, 0xb0, 0x20, 0x00, 0x09, 0xb8,\n    0x45, 0x27, 0x04, 0x01, 0xb0, 0x0a, 0xc6, 0xb4,\n    0x88, 0x01, 0x06, 0xb8, 0x44, 0x7b, 0x00, 0x01,\n    0xb8, 0x0c, 0x95, 0x01, 0xd8, 0x02, 0x01, 0x82,\n    0x00, 0xe2, 0x04, 0xd8, 0x87, 0x07, 0xdc, 0x81,\n    0xc4, 0x01, 0xdc, 0x9d, 0xc3, 0xb0, 0x63, 0xc2,\n    0xb8, 0x05, 0x8a, 0xc6, 0x80, 0xd0, 0x81, 0xc6,\n    0x80, 0xc1, 0x80, 0xc4, 0xb0, 0xd4, 0xc6, 0xb1,\n    0x84, 0xc3, 0xb5, 0xaf, 0x06, 0xdc, 0xb0, 0x3c,\n    0xc5, 0x00, 0x07,\n};\n\nstatic const uint8_t unicode_cc_index[81] = {\n    0x4d, 0x03, 0x00, 0x97, 0x05, 0x20, 0xc6, 0x05,\n    0x00, 0xe7, 0x06, 0x00, 0x45, 0x07, 0x00, 0xe2,\n    0x08, 0x00, 0x53, 0x09, 0x00, 0xcd, 0x0b, 0x20,\n    0x38, 0x0e, 0x00, 0x73, 0x0f, 0x20, 0x5d, 0x13,\n    0x20, 0x60, 0x1a, 0x20, 0xaa, 0x1b, 0x00, 0xf4,\n    0x1c, 0x00, 0xfe, 0x1d, 0x20, 0x7f, 0x2d, 0x20,\n    0xf0, 0xa6, 0x00, 0xb2, 0xaa, 0x00, 0xfe, 0x01,\n    0x01, 0xab, 0x0e, 0x01, 0x73, 0x11, 0x21, 0x70,\n    0x13, 0x01, 0xb8, 0x16, 0x01, 0x9a, 0x1a, 0x01,\n    0x9f, 0xbc, 0x01, 0x22, 0xe0, 0x01, 0x4b, 0xe9,\n    0x01,\n};\n\nstatic const uint32_t unicode_decomp_table1[690] = {\n    0x00280081, 0x002a0097, 0x002a8081, 0x002bc097,\n    0x002c8115, 0x002d0097, 0x002d4081, 0x002e0097,\n    0x002e4115, 0x002f0199, 0x00302016, 0x00400842,\n    0x00448a42, 0x004a0442, 0x004c0096, 0x004c8117,\n    0x004d0242, 0x004e4342, 0x004fc12f, 0x0050c342,\n    0x005240bf, 0x00530342, 0x00550942, 0x005a0842,\n    0x005e0096, 0x005e4342, 0x005fc081, 0x00680142,\n    0x006bc142, 0x00710185, 0x0071c317, 0x00734844,\n    0x00778344, 0x00798342, 0x007b02be, 0x007c4197,\n    0x007d0142, 0x007e0444, 0x00800e42, 0x00878142,\n    0x00898744, 0x00ac0483, 0x00b60317, 0x00b80283,\n    0x00d00214, 0x00d10096, 0x00dd0080, 0x00de8097,\n    0x00df8080, 0x00e10097, 0x00e1413e, 0x00e1c080,\n    0x00e204be, 0x00ea83ae, 0x00f282ae, 0x00f401ad,\n    0x00f4c12e, 0x00f54103, 0x00fc0303, 0x00fe4081,\n    0x0100023e, 0x0101c0be, 0x010301be, 0x010640be,\n    0x010e40be, 0x0114023e, 0x0115c0be, 0x011701be,\n    0x011d8144, 0x01304144, 0x01340244, 0x01358144,\n    0x01368344, 0x01388344, 0x013a8644, 0x013e0144,\n    0x0161c085, 0x018882ae, 0x019d422f, 0x01b00184,\n    0x01b4c084, 0x024a4084, 0x024c4084, 0x024d0084,\n    0x0256042e, 0x0272c12e, 0x02770120, 0x0277c084,\n    0x028cc084, 0x028d8084, 0x029641ae, 0x02978084,\n    0x02d20084, 0x02d2c12e, 0x02d70120, 0x02e50084,\n    0x02f281ae, 0x03120084, 0x03300084, 0x0331c122,\n    0x0332812e, 0x035281ae, 0x03768084, 0x037701ae,\n    0x038cc085, 0x03acc085, 0x03b7012f, 0x03c30081,\n    0x03d0c084, 0x03d34084, 0x03d48084, 0x03d5c084,\n    0x03d70084, 0x03da4084, 0x03dcc084, 0x03dd412e,\n    0x03ddc085, 0x03de0084, 0x03de4085, 0x03e04084,\n    0x03e4c084, 0x03e74084, 0x03e88084, 0x03e9c084,\n    0x03eb0084, 0x03ee4084, 0x04098084, 0x043f0081,\n    0x06c18484, 0x06c48084, 0x06cec184, 0x06d00120,\n    0x06d0c084, 0x074b0383, 0x074cc41f, 0x074f1783,\n    0x075e0081, 0x0766d283, 0x07801d44, 0x078e8942,\n    0x07931844, 0x079f0d42, 0x07a58216, 0x07a68085,\n    0x07a6c0be, 0x07a80d44, 0x07aea044, 0x07c00122,\n    0x07c08344, 0x07c20122, 0x07c28344, 0x07c40122,\n    0x07c48244, 0x07c60122, 0x07c68244, 0x07c8113e,\n    0x07d08244, 0x07d20122, 0x07d28244, 0x07d40122,\n    0x07d48344, 0x07d64c3e, 0x07dc4080, 0x07dc80be,\n    0x07dcc080, 0x07dd00be, 0x07dd4080, 0x07dd80be,\n    0x07ddc080, 0x07de00be, 0x07de4080, 0x07de80be,\n    0x07dec080, 0x07df00be, 0x07df4080, 0x07e00820,\n    0x07e40820, 0x07e80820, 0x07ec05be, 0x07eec080,\n    0x07ef00be, 0x07ef4097, 0x07ef8080, 0x07efc117,\n    0x07f0443e, 0x07f24080, 0x07f280be, 0x07f2c080,\n    0x07f303be, 0x07f4c080, 0x07f582ae, 0x07f6c080,\n    0x07f7433e, 0x07f8c080, 0x07f903ae, 0x07fac080,\n    0x07fb013e, 0x07fb8102, 0x07fc83be, 0x07fe4080,\n    0x07fe80be, 0x07fec080, 0x07ff00be, 0x07ff4080,\n    0x07ff8097, 0x0800011e, 0x08008495, 0x08044081,\n    0x0805c097, 0x08090081, 0x08094097, 0x08098099,\n    0x080bc081, 0x080cc085, 0x080d00b1, 0x080d8085,\n    0x080dc0b1, 0x080f0197, 0x0811c197, 0x0815c0b3,\n    0x0817c081, 0x081c0595, 0x081ec081, 0x081f0215,\n    0x0820051f, 0x08228583, 0x08254415, 0x082a0097,\n    0x08400119, 0x08408081, 0x0840c0bf, 0x08414119,\n    0x0841c081, 0x084240bf, 0x0842852d, 0x08454081,\n    0x08458097, 0x08464295, 0x08480097, 0x08484099,\n    0x08488097, 0x08490081, 0x08498080, 0x084a0081,\n    0x084a8102, 0x084b0495, 0x084d421f, 0x084e4081,\n    0x084ec099, 0x084f0283, 0x08514295, 0x08540119,\n    0x0854809b, 0x0854c619, 0x0857c097, 0x08580081,\n    0x08584097, 0x08588099, 0x0858c097, 0x08590081,\n    0x08594097, 0x08598099, 0x0859c09b, 0x085a0097,\n    0x085a4081, 0x085a8097, 0x085ac099, 0x085b0295,\n    0x085c4097, 0x085c8099, 0x085cc097, 0x085d0081,\n    0x085d4097, 0x085d8099, 0x085dc09b, 0x085e0097,\n    0x085e4081, 0x085e8097, 0x085ec099, 0x085f0215,\n    0x08624099, 0x0866813e, 0x086b80be, 0x087341be,\n    0x088100be, 0x088240be, 0x088300be, 0x088901be,\n    0x088b0085, 0x088b40b1, 0x088bc085, 0x088c00b1,\n    0x089040be, 0x089100be, 0x0891c1be, 0x089801be,\n    0x089b42be, 0x089d0144, 0x089e0144, 0x08a00144,\n    0x08a10144, 0x08a20144, 0x08ab023e, 0x08b80244,\n    0x08ba8220, 0x08ca411e, 0x0918049f, 0x091a4523,\n    0x091cc097, 0x091d04a5, 0x091f452b, 0x0921c09b,\n    0x092204a1, 0x09244525, 0x0926c099, 0x09270d25,\n    0x092d8d1f, 0x09340d1f, 0x093a8081, 0x0a8300b3,\n    0x0a9d0099, 0x0a9d4097, 0x0a9d8099, 0x0ab700be,\n    0x0b1f0115, 0x0b5bc081, 0x0ba7c081, 0x0bbcc081,\n    0x0bc004ad, 0x0bc244ad, 0x0bc484ad, 0x0bc6f383,\n    0x0be0852d, 0x0be31d03, 0x0bf1882d, 0x0c000081,\n    0x0c0d8283, 0x0c130b84, 0x0c194284, 0x0c1c0122,\n    0x0c1cc122, 0x0c1d8122, 0x0c1e4122, 0x0c1f0122,\n    0x0c250084, 0x0c26c123, 0x0c278084, 0x0c27c085,\n    0x0c2b0b84, 0x0c314284, 0x0c340122, 0x0c34c122,\n    0x0c358122, 0x0c364122, 0x0c370122, 0x0c3d0084,\n    0x0c3dc220, 0x0c3f8084, 0x0c3fc085, 0x0c4c4a2d,\n    0x0c51451f, 0x0c53ca9f, 0x0c5915ad, 0x0c648703,\n    0x0c800741, 0x0c838089, 0x0c83c129, 0x0c8441a9,\n    0x0c850089, 0x0c854129, 0x0c85c2a9, 0x0c870089,\n    0x0c87408f, 0x0c87808d, 0x0c881241, 0x0c910203,\n    0x0c940099, 0x0c9444a3, 0x0c968323, 0x0c98072d,\n    0x0c9b84af, 0x0c9dc2a1, 0x0c9f00b5, 0x0c9f40b3,\n    0x0c9f8085, 0x0ca01883, 0x0cac4223, 0x0cad4523,\n    0x0cafc097, 0x0cb004a1, 0x0cb241a5, 0x0cb30097,\n    0x0cb34099, 0x0cb38097, 0x0cb3c099, 0x0cb417ad,\n    0x0cbfc085, 0x0cc001b3, 0x0cc0c0b1, 0x0cc100b3,\n    0x0cc14131, 0x0cc1c0b5, 0x0cc200b3, 0x0cc241b1,\n    0x0cc30133, 0x0cc38131, 0x0cc40085, 0x0cc440b1,\n    0x0cc48133, 0x0cc50085, 0x0cc540b5, 0x0cc580b7,\n    0x0cc5c0b5, 0x0cc600b1, 0x0cc64135, 0x0cc6c0b3,\n    0x0cc701b1, 0x0cc7c0b3, 0x0cc800b5, 0x0cc840b3,\n    0x0cc881b1, 0x0cc9422f, 0x0cca4131, 0x0ccac0b5,\n    0x0ccb00b1, 0x0ccb40b3, 0x0ccb80b5, 0x0ccbc0b1,\n    0x0ccc012f, 0x0ccc80b5, 0x0cccc0b3, 0x0ccd00b5,\n    0x0ccd40b1, 0x0ccd80b5, 0x0ccdc085, 0x0cce02b1,\n    0x0ccf40b3, 0x0ccf80b1, 0x0ccfc085, 0x0cd001b1,\n    0x0cd0c0b3, 0x0cd101b1, 0x0cd1c0b5, 0x0cd200b3,\n    0x0cd24085, 0x0cd280b5, 0x0cd2c085, 0x0cd30133,\n    0x0cd381b1, 0x0cd440b3, 0x0cd48085, 0x0cd4c0b1,\n    0x0cd500b3, 0x0cd54085, 0x0cd580b5, 0x0cd5c0b1,\n    0x0cd60521, 0x0cd88525, 0x0cdb02a5, 0x0cdc4099,\n    0x0cdc8117, 0x0cdd0099, 0x0cdd4197, 0x0cde0127,\n    0x0cde8285, 0x0cdfc089, 0x0ce0043f, 0x0ce20099,\n    0x0ce2409b, 0x0ce283bf, 0x0ce44219, 0x0ce54205,\n    0x0ce6433f, 0x0ce7c131, 0x0ce84085, 0x0ce881b1,\n    0x0ce94085, 0x0ce98107, 0x0cea0089, 0x0cea4097,\n    0x0cea8219, 0x0ceb809d, 0x0cebc08d, 0x0cec083f,\n    0x0cf00105, 0x0cf0809b, 0x0cf0c197, 0x0cf1809b,\n    0x0cf1c099, 0x0cf20517, 0x0cf48099, 0x0cf4c117,\n    0x0cf54119, 0x0cf5c097, 0x0cf6009b, 0x0cf64099,\n    0x0cf68217, 0x0cf78119, 0x0cf804a1, 0x0cfa4525,\n    0x0cfcc525, 0x0cff4125, 0x0cffc099, 0x29a70103,\n    0x29dc0081, 0x29fe0103, 0x2ad70203, 0x2ada4081,\n    0x3e401482, 0x3e4a7f82, 0x3e6a3f82, 0x3e8aa102,\n    0x3e9b0110, 0x3e9c2f82, 0x3eb3c590, 0x3ec00197,\n    0x3ec0c119, 0x3ec1413f, 0x3ec4c2af, 0x3ec74184,\n    0x3ec804ad, 0x3eca4081, 0x3eca8304, 0x3ecc03a0,\n    0x3ece02a0, 0x3ecf8084, 0x3ed00120, 0x3ed0c120,\n    0x3ed184ae, 0x3ed3c085, 0x3ed4312d, 0x3ef4cbad,\n    0x3efa892f, 0x3eff022d, 0x3f002f2f, 0x3f1782a5,\n    0x3f18c0b1, 0x3f1907af, 0x3f1cffaf, 0x3f3c81a5,\n    0x3f3d64af, 0x3f542031, 0x3f649b31, 0x3f7c0131,\n    0x3f7c83b3, 0x3f7e40b1, 0x3f7e80bd, 0x3f7ec0bb,\n    0x3f7f00b3, 0x3f840503, 0x3f8c01ad, 0x3f8cc315,\n    0x3f8e462d, 0x3f91cc03, 0x3f97c695, 0x3f9c01af,\n    0x3f9d0085, 0x3f9d852f, 0x3fa03aad, 0x3fbd442f,\n    0x3fc06f1f, 0x3fd7c11f, 0x3fd85fad, 0x3fe80081,\n    0x3fe84f1f, 0x3ff0831f, 0x3ff2831f, 0x3ff4831f,\n    0x3ff6819f, 0x3ff80783, 0x44268192, 0x442ac092,\n    0x444b8112, 0x44d2c112, 0x452ec212, 0x456e8112,\n    0x464e0092, 0x74578392, 0x746ec312, 0x75000d1f,\n    0x75068d1f, 0x750d0d1f, 0x7513839f, 0x7515891f,\n    0x751a0d1f, 0x75208d1f, 0x75271015, 0x752f439f,\n    0x7531459f, 0x75340d1f, 0x753a8d1f, 0x75410395,\n    0x7543441f, 0x7545839f, 0x75478d1f, 0x754e0795,\n    0x7552839f, 0x75548d1f, 0x755b0d1f, 0x75618d1f,\n    0x75680d1f, 0x756e8d1f, 0x75750d1f, 0x757b8d1f,\n    0x75820d1f, 0x75888d1f, 0x758f0d1f, 0x75958d1f,\n    0x759c0d1f, 0x75a28d1f, 0x75a90103, 0x75aa089f,\n    0x75ae4081, 0x75ae839f, 0x75b04081, 0x75b08c9f,\n    0x75b6c081, 0x75b7032d, 0x75b8889f, 0x75bcc081,\n    0x75bd039f, 0x75bec081, 0x75bf0c9f, 0x75c54081,\n    0x75c5832d, 0x75c7089f, 0x75cb4081, 0x75cb839f,\n    0x75cd4081, 0x75cd8c9f, 0x75d3c081, 0x75d4032d,\n    0x75d5889f, 0x75d9c081, 0x75da039f, 0x75dbc081,\n    0x75dc0c9f, 0x75e24081, 0x75e2832d, 0x75e4089f,\n    0x75e84081, 0x75e8839f, 0x75ea4081, 0x75ea8c9f,\n    0x75f0c081, 0x75f1042d, 0x75f3851f, 0x75f6051f,\n    0x75f8851f, 0x75fb051f, 0x75fd851f, 0x7b80022d,\n    0x7b814dad, 0x7b884203, 0x7b89c081, 0x7b8a452d,\n    0x7b8d0403, 0x7b908081, 0x7b91dc03, 0x7ba0052d,\n    0x7ba2c8ad, 0x7ba84483, 0x7baac8ad, 0x7c400097,\n    0x7c404521, 0x7c440d25, 0x7c4a8087, 0x7c4ac115,\n    0x7c4b4117, 0x7c4c0d1f, 0x7c528217, 0x7c538099,\n    0x7c53c097, 0x7c5a8197, 0x7c640097, 0x7c80012f,\n    0x7c808081, 0x7c841603, 0x7c9004c1, 0x7c940103,\n    0x7efc051f, 0xbe0001ac, 0xbe00d110, 0xbe0947ac,\n    0xbe0d3910, 0xbe29872c, 0xbe2d022c, 0xbe2e3790,\n    0xbe49ff90, 0xbe69bc10,\n};\n\nstatic const uint16_t unicode_decomp_table2[690] = {\n    0x0020, 0x0000, 0x0061, 0x0002, 0x0004, 0x0006, 0x03bc, 0x0008,\n    0x000a, 0x000c, 0x0015, 0x0095, 0x00a5, 0x00b9, 0x00c1, 0x00c3,\n    0x00c7, 0x00cb, 0x00d1, 0x00d7, 0x00dd, 0x00e0, 0x00e6, 0x00f8,\n    0x0108, 0x010a, 0x0073, 0x0110, 0x0112, 0x0114, 0x0120, 0x012c,\n    0x0144, 0x014d, 0x0153, 0x0162, 0x0168, 0x016a, 0x0176, 0x0192,\n    0x0194, 0x01a9, 0x01bb, 0x01c7, 0x01d1, 0x01d5, 0x02b9, 0x01d7,\n    0x003b, 0x01d9, 0x01db, 0x00b7, 0x01e1, 0x01fc, 0x020c, 0x0218,\n    0x021d, 0x0223, 0x0227, 0x03a3, 0x0233, 0x023f, 0x0242, 0x024b,\n    0x024e, 0x0251, 0x025d, 0x0260, 0x0269, 0x026c, 0x026f, 0x0275,\n    0x0278, 0x0281, 0x028a, 0x029c, 0x029f, 0x02a3, 0x02af, 0x02b9,\n    0x02c5, 0x02c9, 0x02cd, 0x02d1, 0x02d5, 0x02e7, 0x02ed, 0x02f1,\n    0x02f5, 0x02f9, 0x02fd, 0x0305, 0x0309, 0x030d, 0x0313, 0x0317,\n    0x031b, 0x0323, 0x0327, 0x032b, 0x032f, 0x0335, 0x033d, 0x0341,\n    0x0349, 0x034d, 0x0351, 0x0f0b, 0x0357, 0x035b, 0x035f, 0x0363,\n    0x0367, 0x036b, 0x036f, 0x0373, 0x0379, 0x037d, 0x0381, 0x0385,\n    0x0389, 0x038d, 0x0391, 0x0395, 0x0399, 0x039d, 0x03a1, 0x10dc,\n    0x03a5, 0x03c9, 0x03cd, 0x03d9, 0x03dd, 0x03e1, 0x03ef, 0x03f1,\n    0x043d, 0x044f, 0x0499, 0x04f0, 0x0502, 0x054a, 0x0564, 0x056c,\n    0x0570, 0x0573, 0x059a, 0x05fa, 0x05fe, 0x0607, 0x060b, 0x0614,\n    0x0618, 0x061e, 0x0622, 0x0628, 0x068e, 0x0694, 0x0698, 0x069e,\n    0x06a2, 0x06ab, 0x03ac, 0x06f3, 0x03ad, 0x06f6, 0x03ae, 0x06f9,\n    0x03af, 0x06fc, 0x03cc, 0x06ff, 0x03cd, 0x0702, 0x03ce, 0x0705,\n    0x0709, 0x070d, 0x0711, 0x0386, 0x0732, 0x0735, 0x03b9, 0x0737,\n    0x073b, 0x0388, 0x0753, 0x0389, 0x0756, 0x0390, 0x076b, 0x038a,\n    0x0777, 0x03b0, 0x0789, 0x038e, 0x0799, 0x079f, 0x07a3, 0x038c,\n    0x07b8, 0x038f, 0x07bb, 0x00b4, 0x07be, 0x07c0, 0x07c2, 0x2010,\n    0x07cb, 0x002e, 0x07cd, 0x07cf, 0x0020, 0x07d2, 0x07d6, 0x07db,\n    0x07df, 0x07e4, 0x07ea, 0x07f0, 0x0020, 0x07f6, 0x2212, 0x0801,\n    0x0805, 0x0807, 0x081d, 0x0825, 0x0827, 0x0043, 0x082d, 0x0830,\n    0x0190, 0x0836, 0x0839, 0x004e, 0x0845, 0x0847, 0x084c, 0x084e,\n    0x0851, 0x005a, 0x03a9, 0x005a, 0x0853, 0x0857, 0x0860, 0x0069,\n    0x0862, 0x0865, 0x086f, 0x0874, 0x087a, 0x087e, 0x08a2, 0x0049,\n    0x08a4, 0x08a6, 0x08a9, 0x0056, 0x08ab, 0x08ad, 0x08b0, 0x08b4,\n    0x0058, 0x08b6, 0x08b8, 0x08bb, 0x08c0, 0x08c2, 0x08c5, 0x0076,\n    0x08c7, 0x08c9, 0x08cc, 0x08d0, 0x0078, 0x08d2, 0x08d4, 0x08d7,\n    0x08db, 0x08de, 0x08e4, 0x08e7, 0x08f0, 0x08f3, 0x08f6, 0x08f9,\n    0x0902, 0x0906, 0x090b, 0x090f, 0x0914, 0x0917, 0x091a, 0x0923,\n    0x092c, 0x093b, 0x093e, 0x0941, 0x0944, 0x0947, 0x094a, 0x0956,\n    0x095c, 0x0960, 0x0962, 0x0964, 0x0968, 0x096a, 0x0970, 0x0978,\n    0x097c, 0x0980, 0x0986, 0x0989, 0x098f, 0x0991, 0x0030, 0x0993,\n    0x0999, 0x099c, 0x099e, 0x09a1, 0x09a4, 0x2d61, 0x6bcd, 0x9f9f,\n    0x09a6, 0x09b1, 0x09bc, 0x09c7, 0x0a95, 0x0aa1, 0x0b15, 0x0020,\n    0x0b27, 0x0b31, 0x0b8d, 0x0ba1, 0x0ba5, 0x0ba9, 0x0bad, 0x0bb1,\n    0x0bb5, 0x0bb9, 0x0bbd, 0x0bc1, 0x0bc5, 0x0c21, 0x0c35, 0x0c39,\n    0x0c3d, 0x0c41, 0x0c45, 0x0c49, 0x0c4d, 0x0c51, 0x0c55, 0x0c59,\n    0x0c6f, 0x0c71, 0x0c73, 0x0ca0, 0x0cbc, 0x0cdc, 0x0ce4, 0x0cec,\n    0x0cf4, 0x0cfc, 0x0d04, 0x0d0c, 0x0d14, 0x0d22, 0x0d2e, 0x0d7a,\n    0x0d82, 0x0d85, 0x0d89, 0x0d8d, 0x0d9d, 0x0db1, 0x0db5, 0x0dbc,\n    0x0dc2, 0x0dc6, 0x0e28, 0x0e2c, 0x0e30, 0x0e32, 0x0e36, 0x0e3c,\n    0x0e3e, 0x0e41, 0x0e43, 0x0e46, 0x0e77, 0x0e7b, 0x0e89, 0x0e8e,\n    0x0e94, 0x0e9c, 0x0ea3, 0x0ea9, 0x0eb4, 0x0ebe, 0x0ec6, 0x0eca,\n    0x0ecf, 0x0ed9, 0x0edd, 0x0ee4, 0x0eec, 0x0ef3, 0x0ef8, 0x0f04,\n    0x0f0a, 0x0f15, 0x0f1b, 0x0f22, 0x0f28, 0x0f33, 0x0f3d, 0x0f45,\n    0x0f4c, 0x0f51, 0x0f57, 0x0f5e, 0x0f63, 0x0f69, 0x0f70, 0x0f76,\n    0x0f7d, 0x0f82, 0x0f89, 0x0f8d, 0x0f9e, 0x0fa4, 0x0fa9, 0x0fad,\n    0x0fb8, 0x0fbe, 0x0fc9, 0x0fd0, 0x0fd6, 0x0fda, 0x0fe1, 0x0fe5,\n    0x0fef, 0x0ffa, 0x1000, 0x1004, 0x1009, 0x100f, 0x1013, 0x101a,\n    0x101f, 0x1023, 0x1029, 0x102f, 0x1032, 0x1036, 0x1039, 0x103f,\n    0x1045, 0x1059, 0x1061, 0x1079, 0x107c, 0x1080, 0x1095, 0x10a1,\n    0x10b1, 0x10c3, 0x10cb, 0x10cf, 0x10da, 0x10de, 0x10ea, 0x10f2,\n    0x10f4, 0x1100, 0x1105, 0x1111, 0x1141, 0x1149, 0x114d, 0x1153,\n    0x1157, 0x115a, 0x116e, 0x1171, 0x1175, 0x117b, 0x117d, 0x1181,\n    0x1184, 0x118c, 0x1192, 0x1196, 0x119c, 0x11a2, 0x11a8, 0x11ab,\n    0xa76f, 0x11af, 0x11b3, 0x028d, 0x11bb, 0x120d, 0x130b, 0x1409,\n    0x148d, 0x1492, 0x1550, 0x1569, 0x156f, 0x1575, 0x157b, 0x1587,\n    0x1593, 0x002b, 0x159e, 0x15b6, 0x15ba, 0x15be, 0x15c2, 0x15c6,\n    0x15ca, 0x15de, 0x15e2, 0x1646, 0x165f, 0x1685, 0x168b, 0x1749,\n    0x174f, 0x1754, 0x1774, 0x1874, 0x187a, 0x190e, 0x19d0, 0x1a74,\n    0x1a7c, 0x1a9a, 0x1a9f, 0x1ab3, 0x1abd, 0x1ac3, 0x1ad7, 0x1adc,\n    0x1ae2, 0x1af0, 0x1b20, 0x1b2d, 0x1b35, 0x1b39, 0x1b4f, 0x1bc6,\n    0x1bd8, 0x1bda, 0x1bdc, 0x3164, 0x1c1d, 0x1c1f, 0x1c21, 0x1c23,\n    0x1c25, 0x1c27, 0x1c45, 0x1c53, 0x1c58, 0x1c61, 0x1c6a, 0x1c7c,\n    0x1c85, 0x1c8a, 0x1caa, 0x1cc5, 0x1cc7, 0x1cc9, 0x1ccb, 0x1ccd,\n    0x1ccf, 0x1cd1, 0x1cd3, 0x1cf3, 0x1cf5, 0x1cf7, 0x1cf9, 0x1cfb,\n    0x1d02, 0x1d04, 0x1d06, 0x1d08, 0x1d17, 0x1d19, 0x1d1b, 0x1d1d,\n    0x1d1f, 0x1d21, 0x1d23, 0x1d25, 0x1d27, 0x1d29, 0x1d2b, 0x1d2d,\n    0x1d2f, 0x1d31, 0x1d33, 0x1d37, 0x03f4, 0x1d39, 0x2207, 0x1d3b,\n    0x2202, 0x1d3d, 0x1d45, 0x03f4, 0x1d47, 0x2207, 0x1d49, 0x2202,\n    0x1d4b, 0x1d53, 0x03f4, 0x1d55, 0x2207, 0x1d57, 0x2202, 0x1d59,\n    0x1d61, 0x03f4, 0x1d63, 0x2207, 0x1d65, 0x2202, 0x1d67, 0x1d6f,\n    0x03f4, 0x1d71, 0x2207, 0x1d73, 0x2202, 0x1d75, 0x1d7f, 0x1d81,\n    0x1d83, 0x1d85, 0x1d87, 0x1d89, 0x1d8f, 0x1dac, 0x062d, 0x1db4,\n    0x1dc0, 0x062c, 0x1dd0, 0x1e40, 0x1e4c, 0x1e5f, 0x1e71, 0x1e84,\n    0x1e86, 0x1e8a, 0x1e90, 0x1e96, 0x1e98, 0x1e9c, 0x1e9e, 0x1ea6,\n    0x1ea9, 0x1eab, 0x1eb1, 0x1eb3, 0x30b5, 0x1eb9, 0x1f11, 0x1f27,\n    0x1f2b, 0x1f2d, 0x1f32, 0x1f7f, 0x1f90, 0x2091, 0x20a1, 0x20a7,\n    0x21a1, 0x22bf,\n};\n\nstatic const uint8_t unicode_decomp_data[9165] = {\n    0x20, 0x88, 0x20, 0x84, 0x32, 0x33, 0x20, 0x81,\n    0x20, 0xa7, 0x31, 0x6f, 0x31, 0xd0, 0x34, 0x31,\n    0xd0, 0x32, 0x33, 0xd0, 0x34, 0x41, 0x80, 0x41,\n    0x81, 0x41, 0x82, 0x41, 0x83, 0x41, 0x88, 0x41,\n    0x8a, 0x00, 0x00, 0x43, 0xa7, 0x45, 0x80, 0x45,\n    0x81, 0x45, 0x82, 0x45, 0x88, 0x49, 0x80, 0x49,\n    0x81, 0x49, 0x82, 0x49, 0x88, 0x00, 0x00, 0x4e,\n    0x83, 0x4f, 0x80, 0x4f, 0x81, 0x4f, 0x82, 0x4f,\n    0x83, 0x4f, 0x88, 0x00, 0x00, 0x00, 0x00, 0x55,\n    0x80, 0x55, 0x81, 0x55, 0x82, 0x55, 0x88, 0x59,\n    0x81, 0x00, 0x00, 0x00, 0x00, 0x61, 0x80, 0x61,\n    0x81, 0x61, 0x82, 0x61, 0x83, 0x61, 0x88, 0x61,\n    0x8a, 0x00, 0x00, 0x63, 0xa7, 0x65, 0x80, 0x65,\n    0x81, 0x65, 0x82, 0x65, 0x88, 0x69, 0x80, 0x69,\n    0x81, 0x69, 0x82, 0x69, 0x88, 0x00, 0x00, 0x6e,\n    0x83, 0x6f, 0x80, 0x6f, 0x81, 0x6f, 0x82, 0x6f,\n    0x83, 0x6f, 0x88, 0x00, 0x00, 0x00, 0x00, 0x75,\n    0x80, 0x75, 0x81, 0x75, 0x82, 0x75, 0x88, 0x79,\n    0x81, 0x00, 0x00, 0x79, 0x88, 0x41, 0x84, 0x41,\n    0x86, 0x41, 0xa8, 0x43, 0x81, 0x43, 0x82, 0x43,\n    0x87, 0x43, 0x8c, 0x44, 0x8c, 0x45, 0x84, 0x45,\n    0x86, 0x45, 0x87, 0x45, 0xa8, 0x45, 0x8c, 0x47,\n    0x82, 0x47, 0x86, 0x47, 0x87, 0x47, 0xa7, 0x48,\n    0x82, 0x49, 0x83, 0x49, 0x84, 0x49, 0x86, 0x49,\n    0xa8, 0x49, 0x87, 0x49, 0x4a, 0x69, 0x6a, 0x4a,\n    0x82, 0x4b, 0xa7, 0x4c, 0x81, 0x4c, 0xa7, 0x4c,\n    0x8c, 0x4c, 0x00, 0x00, 0x6b, 0x20, 0x6b, 0x4e,\n    0x81, 0x4e, 0xa7, 0x4e, 0x8c, 0xbc, 0x02, 0x6e,\n    0x4f, 0x84, 0x4f, 0x86, 0x4f, 0x8b, 0x52, 0x81,\n    0x52, 0xa7, 0x52, 0x8c, 0x53, 0x81, 0x53, 0x82,\n    0x53, 0xa7, 0x53, 0x8c, 0x54, 0xa7, 0x54, 0x8c,\n    0x55, 0x83, 0x55, 0x84, 0x55, 0x86, 0x55, 0x8a,\n    0x55, 0x8b, 0x55, 0xa8, 0x57, 0x82, 0x59, 0x82,\n    0x59, 0x88, 0x5a, 0x81, 0x5a, 0x87, 0x5a, 0x8c,\n    0x4f, 0x9b, 0x55, 0x9b, 0x44, 0x00, 0x7d, 0x01,\n    0x44, 0x00, 0x7e, 0x01, 0x64, 0x00, 0x7e, 0x01,\n    0x4c, 0x4a, 0x4c, 0x6a, 0x6c, 0x6a, 0x4e, 0x4a,\n    0x4e, 0x6a, 0x6e, 0x6a, 0x41, 0x00, 0x8c, 0x49,\n    0x00, 0x8c, 0x4f, 0x00, 0x8c, 0x55, 0x00, 0x8c,\n    0xdc, 0x00, 0x84, 0xdc, 0x00, 0x81, 0xdc, 0x00,\n    0x8c, 0xdc, 0x00, 0x80, 0xc4, 0x00, 0x84, 0x26,\n    0x02, 0x84, 0xc6, 0x00, 0x84, 0x47, 0x8c, 0x4b,\n    0x8c, 0x4f, 0xa8, 0xea, 0x01, 0x84, 0xeb, 0x01,\n    0x84, 0xb7, 0x01, 0x8c, 0x92, 0x02, 0x8c, 0x6a,\n    0x00, 0x8c, 0x44, 0x5a, 0x44, 0x7a, 0x64, 0x7a,\n    0x47, 0x81, 0x4e, 0x00, 0x80, 0xc5, 0x00, 0x81,\n    0xc6, 0x00, 0x81, 0xd8, 0x00, 0x81, 0x41, 0x8f,\n    0x41, 0x91, 0x45, 0x8f, 0x45, 0x91, 0x49, 0x8f,\n    0x49, 0x91, 0x4f, 0x8f, 0x4f, 0x91, 0x52, 0x8f,\n    0x52, 0x91, 0x55, 0x8f, 0x55, 0x91, 0x53, 0xa6,\n    0x54, 0xa6, 0x48, 0x8c, 0x41, 0x00, 0x87, 0x45,\n    0x00, 0xa7, 0xd6, 0x00, 0x84, 0xd5, 0x00, 0x84,\n    0x4f, 0x00, 0x87, 0x2e, 0x02, 0x84, 0x59, 0x00,\n    0x84, 0x68, 0x00, 0x66, 0x02, 0x6a, 0x00, 0x72,\n    0x00, 0x79, 0x02, 0x7b, 0x02, 0x81, 0x02, 0x77,\n    0x00, 0x79, 0x00, 0x20, 0x86, 0x20, 0x87, 0x20,\n    0x8a, 0x20, 0xa8, 0x20, 0x83, 0x20, 0x8b, 0x63,\n    0x02, 0x6c, 0x00, 0x73, 0x00, 0x78, 0x00, 0x95,\n    0x02, 0x80, 0x81, 0x00, 0x93, 0x88, 0x81, 0x20,\n    0xc5, 0x20, 0x81, 0xa8, 0x00, 0x81, 0x91, 0x03,\n    0x81, 0x95, 0x03, 0x81, 0x97, 0x03, 0x81, 0x99,\n    0x03, 0x81, 0x00, 0x00, 0x00, 0x9f, 0x03, 0x81,\n    0x00, 0x00, 0x00, 0xa5, 0x03, 0x81, 0xa9, 0x03,\n    0x81, 0xca, 0x03, 0x81, 0x01, 0x03, 0x98, 0x07,\n    0xa4, 0x07, 0xb0, 0x00, 0xb4, 0x00, 0xb6, 0x00,\n    0xb8, 0x00, 0xca, 0x00, 0x01, 0x03, 0xb8, 0x07,\n    0xc4, 0x07, 0xbe, 0x00, 0xc4, 0x00, 0xc8, 0x00,\n    0xa5, 0x03, 0x0d, 0x13, 0x00, 0x01, 0x03, 0xd1,\n    0x00, 0xd1, 0x07, 0xc6, 0x03, 0xc0, 0x03, 0xba,\n    0x03, 0xc1, 0x03, 0xc2, 0x03, 0x00, 0x00, 0x98,\n    0x03, 0xb5, 0x03, 0x15, 0x04, 0x80, 0x15, 0x04,\n    0x88, 0x00, 0x00, 0x00, 0x13, 0x04, 0x81, 0x06,\n    0x04, 0x88, 0x1a, 0x04, 0x81, 0x18, 0x04, 0x80,\n    0x23, 0x04, 0x86, 0x18, 0x04, 0x86, 0x38, 0x04,\n    0x86, 0x35, 0x04, 0x80, 0x35, 0x04, 0x88, 0x00,\n    0x00, 0x00, 0x33, 0x04, 0x81, 0x56, 0x04, 0x88,\n    0x3a, 0x04, 0x81, 0x38, 0x04, 0x80, 0x43, 0x04,\n    0x86, 0x74, 0x04, 0x8f, 0x16, 0x04, 0x86, 0x10,\n    0x04, 0x86, 0x10, 0x04, 0x88, 0x15, 0x04, 0x86,\n    0xd8, 0x04, 0x88, 0x16, 0x04, 0x88, 0x17, 0x04,\n    0x88, 0x18, 0x04, 0x84, 0x18, 0x04, 0x88, 0x1e,\n    0x04, 0x88, 0xe8, 0x04, 0x88, 0x2d, 0x04, 0x88,\n    0x23, 0x04, 0x84, 0x23, 0x04, 0x88, 0x23, 0x04,\n    0x8b, 0x27, 0x04, 0x88, 0x2b, 0x04, 0x88, 0x65,\n    0x05, 0x82, 0x05, 0x27, 0x06, 0x00, 0x2c, 0x00,\n    0x2d, 0x21, 0x2d, 0x00, 0x2e, 0x23, 0x2d, 0x27,\n    0x06, 0x00, 0x4d, 0x21, 0x4d, 0xa0, 0x4d, 0x23,\n    0x4d, 0xd5, 0x06, 0x54, 0x06, 0x00, 0x00, 0x00,\n    0x00, 0xc1, 0x06, 0x54, 0x06, 0xd2, 0x06, 0x54,\n    0x06, 0x28, 0x09, 0x3c, 0x09, 0x30, 0x09, 0x3c,\n    0x09, 0x33, 0x09, 0x3c, 0x09, 0x15, 0x09, 0x00,\n    0x27, 0x01, 0x27, 0x02, 0x27, 0x07, 0x27, 0x0c,\n    0x27, 0x0d, 0x27, 0x16, 0x27, 0x1a, 0x27, 0xbe,\n    0x09, 0x09, 0x00, 0x09, 0x19, 0xa1, 0x09, 0xbc,\n    0x09, 0xaf, 0x09, 0xbc, 0x09, 0x32, 0x0a, 0x3c,\n    0x0a, 0x38, 0x0a, 0x3c, 0x0a, 0x16, 0x0a, 0x00,\n    0x26, 0x01, 0x26, 0x06, 0x26, 0x2b, 0x0a, 0x3c,\n    0x0a, 0x47, 0x0b, 0x56, 0x0b, 0x3e, 0x0b, 0x09,\n    0x00, 0x09, 0x19, 0x21, 0x0b, 0x3c, 0x0b, 0x92,\n    0x0b, 0xd7, 0x0b, 0xbe, 0x0b, 0x08, 0x00, 0x09,\n    0x00, 0x08, 0x19, 0x46, 0x0c, 0x56, 0x0c, 0xbf,\n    0x0c, 0xd5, 0x0c, 0xc6, 0x0c, 0xd5, 0x0c, 0xc2,\n    0x0c, 0x04, 0x00, 0x08, 0x13, 0x3e, 0x0d, 0x08,\n    0x00, 0x09, 0x00, 0x08, 0x19, 0xd9, 0x0d, 0xca,\n    0x0d, 0xca, 0x0d, 0x0f, 0x05, 0x12, 0x00, 0x0f,\n    0x15, 0x4d, 0x0e, 0x32, 0x0e, 0xcd, 0x0e, 0xb2,\n    0x0e, 0x99, 0x0e, 0x12, 0x00, 0x12, 0x08, 0x42,\n    0x0f, 0xb7, 0x0f, 0x4c, 0x0f, 0xb7, 0x0f, 0x51,\n    0x0f, 0xb7, 0x0f, 0x56, 0x0f, 0xb7, 0x0f, 0x5b,\n    0x0f, 0xb7, 0x0f, 0x40, 0x0f, 0xb5, 0x0f, 0x71,\n    0x0f, 0x72, 0x0f, 0x71, 0x0f, 0x00, 0x03, 0x41,\n    0x0f, 0xb2, 0x0f, 0x81, 0x0f, 0xb3, 0x0f, 0x80,\n    0x0f, 0xb3, 0x0f, 0x81, 0x0f, 0x71, 0x0f, 0x80,\n    0x0f, 0x92, 0x0f, 0xb7, 0x0f, 0x9c, 0x0f, 0xb7,\n    0x0f, 0xa1, 0x0f, 0xb7, 0x0f, 0xa6, 0x0f, 0xb7,\n    0x0f, 0xab, 0x0f, 0xb7, 0x0f, 0x90, 0x0f, 0xb5,\n    0x0f, 0x25, 0x10, 0x2e, 0x10, 0x05, 0x1b, 0x35,\n    0x1b, 0x00, 0x00, 0x00, 0x00, 0x07, 0x1b, 0x35,\n    0x1b, 0x00, 0x00, 0x00, 0x00, 0x09, 0x1b, 0x35,\n    0x1b, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x1b, 0x35,\n    0x1b, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x1b, 0x35,\n    0x1b, 0x11, 0x1b, 0x35, 0x1b, 0x3a, 0x1b, 0x35,\n    0x1b, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x1b, 0x35,\n    0x1b, 0x3e, 0x1b, 0x35, 0x1b, 0x42, 0x1b, 0x35,\n    0x1b, 0x41, 0x00, 0xc6, 0x00, 0x42, 0x00, 0x00,\n    0x00, 0x44, 0x00, 0x45, 0x00, 0x8e, 0x01, 0x47,\n    0x00, 0x4f, 0x00, 0x22, 0x02, 0x50, 0x00, 0x52,\n    0x00, 0x54, 0x00, 0x55, 0x00, 0x57, 0x00, 0x61,\n    0x00, 0x50, 0x02, 0x51, 0x02, 0x02, 0x1d, 0x62,\n    0x00, 0x64, 0x00, 0x65, 0x00, 0x59, 0x02, 0x5b,\n    0x02, 0x5c, 0x02, 0x67, 0x00, 0x00, 0x00, 0x6b,\n    0x00, 0x6d, 0x00, 0x4b, 0x01, 0x6f, 0x00, 0x54,\n    0x02, 0x16, 0x1d, 0x17, 0x1d, 0x70, 0x00, 0x74,\n    0x00, 0x75, 0x00, 0x1d, 0x1d, 0x6f, 0x02, 0x76,\n    0x00, 0x25, 0x1d, 0xb2, 0x03, 0xb3, 0x03, 0xb4,\n    0x03, 0xc6, 0x03, 0xc7, 0x03, 0x69, 0x00, 0x72,\n    0x00, 0x75, 0x00, 0x76, 0x00, 0xb2, 0x03, 0xb3,\n    0x03, 0xc1, 0x03, 0xc6, 0x03, 0xc7, 0x03, 0x52,\n    0x02, 0x63, 0x00, 0x55, 0x02, 0xf0, 0x00, 0x5c,\n    0x02, 0x66, 0x00, 0x5f, 0x02, 0x61, 0x02, 0x65,\n    0x02, 0x68, 0x02, 0x69, 0x02, 0x6a, 0x02, 0x7b,\n    0x1d, 0x9d, 0x02, 0x6d, 0x02, 0x85, 0x1d, 0x9f,\n    0x02, 0x71, 0x02, 0x70, 0x02, 0x72, 0x02, 0x73,\n    0x02, 0x74, 0x02, 0x75, 0x02, 0x78, 0x02, 0x82,\n    0x02, 0x83, 0x02, 0xab, 0x01, 0x89, 0x02, 0x8a,\n    0x02, 0x1c, 0x1d, 0x8b, 0x02, 0x8c, 0x02, 0x7a,\n    0x00, 0x90, 0x02, 0x91, 0x02, 0x92, 0x02, 0xb8,\n    0x03, 0x41, 0x00, 0xa5, 0x42, 0x00, 0x87, 0x42,\n    0x00, 0xa3, 0x42, 0x00, 0xb1, 0xc7, 0x00, 0x81,\n    0x44, 0x00, 0x87, 0x44, 0x00, 0xa3, 0x44, 0x00,\n    0xb1, 0x44, 0x00, 0xa7, 0x44, 0x00, 0xad, 0x12,\n    0x01, 0x80, 0x12, 0x01, 0x81, 0x45, 0x00, 0xad,\n    0x45, 0x00, 0xb0, 0x28, 0x02, 0x86, 0x46, 0x00,\n    0x87, 0x47, 0x00, 0x84, 0x48, 0x00, 0x87, 0x48,\n    0x00, 0xa3, 0x48, 0x00, 0x88, 0x48, 0x00, 0xa7,\n    0x48, 0x00, 0xae, 0x49, 0x00, 0xb0, 0xcf, 0x00,\n    0x81, 0x4b, 0x00, 0x81, 0x4b, 0x00, 0xa3, 0x4b,\n    0x00, 0xb1, 0x4c, 0x00, 0xa3, 0x36, 0x1e, 0x84,\n    0x4c, 0xb1, 0x4c, 0xad, 0x4d, 0x81, 0x4d, 0x87,\n    0x4d, 0xa3, 0x4e, 0x87, 0x4e, 0xa3, 0x4e, 0xb1,\n    0x4e, 0xad, 0xd5, 0x00, 0x81, 0xd5, 0x00, 0x88,\n    0x4c, 0x01, 0x80, 0x4c, 0x01, 0x81, 0x50, 0x00,\n    0x81, 0x50, 0x00, 0x87, 0x52, 0x00, 0x87, 0x52,\n    0x00, 0xa3, 0x5a, 0x1e, 0x84, 0x52, 0x00, 0xb1,\n    0x53, 0x00, 0x87, 0x53, 0x00, 0xa3, 0x5a, 0x01,\n    0x87, 0x60, 0x01, 0x87, 0x62, 0x1e, 0x87, 0x54,\n    0x00, 0x87, 0x54, 0x00, 0xa3, 0x54, 0x00, 0xb1,\n    0x54, 0x00, 0xad, 0x55, 0x00, 0xa4, 0x55, 0x00,\n    0xb0, 0x55, 0x00, 0xad, 0x68, 0x01, 0x81, 0x6a,\n    0x01, 0x88, 0x56, 0x83, 0x56, 0xa3, 0x57, 0x80,\n    0x57, 0x81, 0x57, 0x88, 0x57, 0x87, 0x57, 0xa3,\n    0x58, 0x87, 0x58, 0x88, 0x59, 0x87, 0x5a, 0x82,\n    0x5a, 0xa3, 0x5a, 0xb1, 0x68, 0xb1, 0x74, 0x88,\n    0x77, 0x8a, 0x79, 0x8a, 0x61, 0x00, 0xbe, 0x02,\n    0x7f, 0x01, 0x87, 0x41, 0x00, 0xa3, 0x41, 0x00,\n    0x89, 0xc2, 0x00, 0x81, 0xc2, 0x00, 0x80, 0xc2,\n    0x00, 0x89, 0xc2, 0x00, 0x83, 0xa0, 0x1e, 0x82,\n    0x02, 0x01, 0x81, 0x02, 0x01, 0x80, 0x02, 0x01,\n    0x89, 0x02, 0x01, 0x83, 0xa0, 0x1e, 0x86, 0x45,\n    0x00, 0xa3, 0x45, 0x00, 0x89, 0x45, 0x00, 0x83,\n    0xca, 0x00, 0x81, 0xca, 0x00, 0x80, 0xca, 0x00,\n    0x89, 0xca, 0x00, 0x83, 0xb8, 0x1e, 0x82, 0x49,\n    0x00, 0x89, 0x49, 0x00, 0xa3, 0x4f, 0x00, 0xa3,\n    0x4f, 0x00, 0x89, 0xd4, 0x00, 0x81, 0xd4, 0x00,\n    0x80, 0xd4, 0x00, 0x89, 0xd4, 0x00, 0x83, 0xcc,\n    0x1e, 0x82, 0xa0, 0x01, 0x81, 0xa0, 0x01, 0x80,\n    0xa0, 0x01, 0x89, 0xa0, 0x01, 0x83, 0xa0, 0x01,\n    0xa3, 0x55, 0x00, 0xa3, 0x55, 0x00, 0x89, 0xaf,\n    0x01, 0x81, 0xaf, 0x01, 0x80, 0xaf, 0x01, 0x89,\n    0xaf, 0x01, 0x83, 0xaf, 0x01, 0xa3, 0x59, 0x00,\n    0x80, 0x59, 0x00, 0xa3, 0x59, 0x00, 0x89, 0x59,\n    0x00, 0x83, 0xb1, 0x03, 0x13, 0x03, 0x00, 0x1f,\n    0x80, 0x00, 0x1f, 0x81, 0x00, 0x1f, 0xc2, 0x91,\n    0x03, 0x13, 0x03, 0x08, 0x1f, 0x80, 0x08, 0x1f,\n    0x81, 0x08, 0x1f, 0xc2, 0xb5, 0x03, 0x13, 0x03,\n    0x10, 0x1f, 0x80, 0x10, 0x1f, 0x81, 0x95, 0x03,\n    0x13, 0x03, 0x18, 0x1f, 0x80, 0x18, 0x1f, 0x81,\n    0xb7, 0x03, 0x93, 0xb7, 0x03, 0x94, 0x20, 0x1f,\n    0x80, 0x21, 0x1f, 0x80, 0x20, 0x1f, 0x81, 0x21,\n    0x1f, 0x81, 0x20, 0x1f, 0xc2, 0x21, 0x1f, 0xc2,\n    0x97, 0x03, 0x93, 0x97, 0x03, 0x94, 0x28, 0x1f,\n    0x80, 0x29, 0x1f, 0x80, 0x28, 0x1f, 0x81, 0x29,\n    0x1f, 0x81, 0x28, 0x1f, 0xc2, 0x29, 0x1f, 0xc2,\n    0xb9, 0x03, 0x93, 0xb9, 0x03, 0x94, 0x30, 0x1f,\n    0x80, 0x31, 0x1f, 0x80, 0x30, 0x1f, 0x81, 0x31,\n    0x1f, 0x81, 0x30, 0x1f, 0xc2, 0x31, 0x1f, 0xc2,\n    0x99, 0x03, 0x93, 0x99, 0x03, 0x94, 0x38, 0x1f,\n    0x80, 0x39, 0x1f, 0x80, 0x38, 0x1f, 0x81, 0x39,\n    0x1f, 0x81, 0x38, 0x1f, 0xc2, 0x39, 0x1f, 0xc2,\n    0xbf, 0x03, 0x93, 0xbf, 0x03, 0x94, 0x40, 0x1f,\n    0x80, 0x40, 0x1f, 0x81, 0x9f, 0x03, 0x13, 0x03,\n    0x48, 0x1f, 0x80, 0x48, 0x1f, 0x81, 0xc5, 0x03,\n    0x13, 0x03, 0x50, 0x1f, 0x80, 0x50, 0x1f, 0x81,\n    0x50, 0x1f, 0xc2, 0xa5, 0x03, 0x94, 0x00, 0x00,\n    0x00, 0x59, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x59,\n    0x1f, 0x81, 0x00, 0x00, 0x00, 0x59, 0x1f, 0xc2,\n    0xc9, 0x03, 0x93, 0xc9, 0x03, 0x94, 0x60, 0x1f,\n    0x80, 0x61, 0x1f, 0x80, 0x60, 0x1f, 0x81, 0x61,\n    0x1f, 0x81, 0x60, 0x1f, 0xc2, 0x61, 0x1f, 0xc2,\n    0xa9, 0x03, 0x93, 0xa9, 0x03, 0x94, 0x68, 0x1f,\n    0x80, 0x69, 0x1f, 0x80, 0x68, 0x1f, 0x81, 0x69,\n    0x1f, 0x81, 0x68, 0x1f, 0xc2, 0x69, 0x1f, 0xc2,\n    0xb1, 0x03, 0x80, 0xb5, 0x03, 0x80, 0xb7, 0x03,\n    0x80, 0xb9, 0x03, 0x80, 0xbf, 0x03, 0x80, 0xc5,\n    0x03, 0x80, 0xc9, 0x03, 0x80, 0x00, 0x1f, 0x45,\n    0x03, 0x20, 0x1f, 0x45, 0x03, 0x60, 0x1f, 0x45,\n    0x03, 0xb1, 0x03, 0x86, 0xb1, 0x03, 0x84, 0x70,\n    0x1f, 0xc5, 0xb1, 0x03, 0xc5, 0xac, 0x03, 0xc5,\n    0x00, 0x00, 0x00, 0xb1, 0x03, 0xc2, 0xb6, 0x1f,\n    0xc5, 0x91, 0x03, 0x86, 0x91, 0x03, 0x84, 0x91,\n    0x03, 0x80, 0x91, 0x03, 0xc5, 0x20, 0x93, 0x20,\n    0x93, 0x20, 0xc2, 0xa8, 0x00, 0xc2, 0x74, 0x1f,\n    0xc5, 0xb7, 0x03, 0xc5, 0xae, 0x03, 0xc5, 0x00,\n    0x00, 0x00, 0xb7, 0x03, 0xc2, 0xc6, 0x1f, 0xc5,\n    0x95, 0x03, 0x80, 0x97, 0x03, 0x80, 0x97, 0x03,\n    0xc5, 0xbf, 0x1f, 0x80, 0xbf, 0x1f, 0x81, 0xbf,\n    0x1f, 0xc2, 0xb9, 0x03, 0x86, 0xb9, 0x03, 0x84,\n    0xca, 0x03, 0x80, 0x00, 0x03, 0xb9, 0x42, 0xca,\n    0x42, 0x99, 0x06, 0x99, 0x04, 0x99, 0x00, 0xfe,\n    0x1f, 0x80, 0xfe, 0x1f, 0x81, 0xfe, 0x1f, 0xc2,\n    0xc5, 0x03, 0x86, 0xc5, 0x03, 0x84, 0xcb, 0x03,\n    0x80, 0x00, 0x03, 0xc1, 0x13, 0xc1, 0x14, 0xc5,\n    0x42, 0xcb, 0x42, 0xa5, 0x06, 0xa5, 0x04, 0xa5,\n    0x00, 0xa1, 0x03, 0x94, 0xa8, 0x00, 0x80, 0x85,\n    0x03, 0x60, 0x00, 0x7c, 0x1f, 0xc5, 0xc9, 0x03,\n    0xc5, 0xce, 0x03, 0xc5, 0x00, 0x00, 0x00, 0xc9,\n    0x03, 0xc2, 0xf6, 0x1f, 0xc5, 0x9f, 0x03, 0x80,\n    0xa9, 0x03, 0x80, 0xa9, 0x03, 0xc5, 0x20, 0x94,\n    0x02, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,\n    0x20, 0x20, 0x20, 0x20, 0xb3, 0x2e, 0x2e, 0x2e,\n    0x2e, 0x2e, 0x32, 0x20, 0x32, 0x20, 0x32, 0x20,\n    0x00, 0x00, 0x00, 0x35, 0x20, 0x35, 0x20, 0x35,\n    0x20, 0x00, 0x00, 0x00, 0x21, 0x21, 0x00, 0x00,\n    0x20, 0x85, 0x3f, 0x3f, 0x3f, 0x21, 0x21, 0x3f,\n    0x32, 0x20, 0x00, 0x00, 0x00, 0x00, 0x30, 0x69,\n    0x00, 0x00, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,\n    0x2b, 0x3d, 0x28, 0x29, 0x6e, 0x30, 0x00, 0x2b,\n    0x00, 0x12, 0x22, 0x3d, 0x00, 0x28, 0x00, 0x29,\n    0x00, 0x00, 0x00, 0x61, 0x00, 0x65, 0x00, 0x6f,\n    0x00, 0x78, 0x00, 0x59, 0x02, 0x68, 0x6b, 0x6c,\n    0x6d, 0x6e, 0x70, 0x73, 0x74, 0x52, 0x73, 0x61,\n    0x2f, 0x63, 0x61, 0x2f, 0x73, 0xb0, 0x00, 0x43,\n    0x63, 0x2f, 0x6f, 0x63, 0x2f, 0x75, 0xb0, 0x00,\n    0x46, 0x48, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x20,\n    0xdf, 0x01, 0x01, 0x04, 0x24, 0x4e, 0x6f, 0x50,\n    0x51, 0x52, 0x52, 0x52, 0x53, 0x4d, 0x54, 0x45,\n    0x4c, 0x54, 0x4d, 0x4b, 0x00, 0xc5, 0x00, 0x42,\n    0x43, 0x00, 0x65, 0x45, 0x46, 0x00, 0x4d, 0x6f,\n    0xd0, 0x05, 0x46, 0x41, 0x58, 0xc0, 0x03, 0xb3,\n    0x03, 0x93, 0x03, 0xa0, 0x03, 0x11, 0x22, 0x44,\n    0x64, 0x65, 0x69, 0x6a, 0x31, 0xd0, 0x37, 0x31,\n    0xd0, 0x39, 0x31, 0xd0, 0x31, 0x30, 0x31, 0xd0,\n    0x33, 0x32, 0xd0, 0x33, 0x31, 0xd0, 0x35, 0x32,\n    0xd0, 0x35, 0x33, 0xd0, 0x35, 0x34, 0xd0, 0x35,\n    0x31, 0xd0, 0x36, 0x35, 0xd0, 0x36, 0x31, 0xd0,\n    0x38, 0x33, 0xd0, 0x38, 0x35, 0xd0, 0x38, 0x37,\n    0xd0, 0x38, 0x31, 0xd0, 0x49, 0x49, 0x49, 0x49,\n    0x49, 0x49, 0x56, 0x56, 0x49, 0x56, 0x49, 0x49,\n    0x56, 0x49, 0x49, 0x49, 0x49, 0x58, 0x58, 0x49,\n    0x58, 0x49, 0x49, 0x4c, 0x43, 0x44, 0x4d, 0x69,\n    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x76, 0x76,\n    0x69, 0x76, 0x69, 0x69, 0x76, 0x69, 0x69, 0x69,\n    0x69, 0x78, 0x78, 0x69, 0x78, 0x69, 0x69, 0x6c,\n    0x63, 0x64, 0x6d, 0x30, 0xd0, 0x33, 0x90, 0x21,\n    0xb8, 0x92, 0x21, 0xb8, 0x94, 0x21, 0xb8, 0xd0,\n    0x21, 0xb8, 0xd4, 0x21, 0xb8, 0xd2, 0x21, 0xb8,\n    0x03, 0x22, 0xb8, 0x08, 0x22, 0xb8, 0x0b, 0x22,\n    0xb8, 0x23, 0x22, 0xb8, 0x00, 0x00, 0x00, 0x25,\n    0x22, 0xb8, 0x2b, 0x22, 0x2b, 0x22, 0x2b, 0x22,\n    0x00, 0x00, 0x00, 0x2e, 0x22, 0x2e, 0x22, 0x2e,\n    0x22, 0x00, 0x00, 0x00, 0x3c, 0x22, 0xb8, 0x43,\n    0x22, 0xb8, 0x45, 0x22, 0xb8, 0x00, 0x00, 0x00,\n    0x48, 0x22, 0xb8, 0x3d, 0x00, 0xb8, 0x00, 0x00,\n    0x00, 0x61, 0x22, 0xb8, 0x4d, 0x22, 0xb8, 0x3c,\n    0x00, 0xb8, 0x3e, 0x00, 0xb8, 0x64, 0x22, 0xb8,\n    0x65, 0x22, 0xb8, 0x72, 0x22, 0xb8, 0x76, 0x22,\n    0xb8, 0x7a, 0x22, 0xb8, 0x82, 0x22, 0xb8, 0x86,\n    0x22, 0xb8, 0xa2, 0x22, 0xb8, 0xa8, 0x22, 0xb8,\n    0xa9, 0x22, 0xb8, 0xab, 0x22, 0xb8, 0x7c, 0x22,\n    0xb8, 0x91, 0x22, 0xb8, 0xb2, 0x22, 0x38, 0x03,\n    0x08, 0x30, 0x31, 0x00, 0x31, 0x00, 0x30, 0x00,\n    0x32, 0x30, 0x28, 0x00, 0x31, 0x00, 0x29, 0x00,\n    0x28, 0x00, 0x31, 0x00, 0x30, 0x00, 0x29, 0x00,\n    0x28, 0x32, 0x30, 0x29, 0x31, 0x00, 0x2e, 0x00,\n    0x31, 0x00, 0x30, 0x00, 0x2e, 0x00, 0x32, 0x30,\n    0x2e, 0x28, 0x00, 0x61, 0x00, 0x29, 0x00, 0x41,\n    0x00, 0x61, 0x00, 0x2b, 0x22, 0x00, 0x00, 0x00,\n    0x00, 0x3a, 0x3a, 0x3d, 0x3d, 0x3d, 0x3d, 0x3d,\n    0x3d, 0xdd, 0x2a, 0xb8, 0x6a, 0x56, 0x00, 0x4e,\n    0x00, 0x28, 0x36, 0x3f, 0x59, 0x85, 0x8c, 0xa0,\n    0xba, 0x3f, 0x51, 0x00, 0x26, 0x2c, 0x43, 0x57,\n    0x6c, 0xa1, 0xb6, 0xc1, 0x9b, 0x52, 0x00, 0x5e,\n    0x7a, 0x7f, 0x9d, 0xa6, 0xc1, 0xce, 0xe7, 0xb6,\n    0x53, 0xc8, 0x53, 0xe3, 0x53, 0xd7, 0x56, 0x1f,\n    0x57, 0xeb, 0x58, 0x02, 0x59, 0x0a, 0x59, 0x15,\n    0x59, 0x27, 0x59, 0x73, 0x59, 0x50, 0x5b, 0x80,\n    0x5b, 0xf8, 0x5b, 0x0f, 0x5c, 0x22, 0x5c, 0x38,\n    0x5c, 0x6e, 0x5c, 0x71, 0x5c, 0xdb, 0x5d, 0xe5,\n    0x5d, 0xf1, 0x5d, 0xfe, 0x5d, 0x72, 0x5e, 0x7a,\n    0x5e, 0x7f, 0x5e, 0xf4, 0x5e, 0xfe, 0x5e, 0x0b,\n    0x5f, 0x13, 0x5f, 0x50, 0x5f, 0x61, 0x5f, 0x73,\n    0x5f, 0xc3, 0x5f, 0x08, 0x62, 0x36, 0x62, 0x4b,\n    0x62, 0x2f, 0x65, 0x34, 0x65, 0x87, 0x65, 0x97,\n    0x65, 0xa4, 0x65, 0xb9, 0x65, 0xe0, 0x65, 0xe5,\n    0x65, 0xf0, 0x66, 0x08, 0x67, 0x28, 0x67, 0x20,\n    0x6b, 0x62, 0x6b, 0x79, 0x6b, 0xb3, 0x6b, 0xcb,\n    0x6b, 0xd4, 0x6b, 0xdb, 0x6b, 0x0f, 0x6c, 0x14,\n    0x6c, 0x34, 0x6c, 0x6b, 0x70, 0x2a, 0x72, 0x36,\n    0x72, 0x3b, 0x72, 0x3f, 0x72, 0x47, 0x72, 0x59,\n    0x72, 0x5b, 0x72, 0xac, 0x72, 0x84, 0x73, 0x89,\n    0x73, 0xdc, 0x74, 0xe6, 0x74, 0x18, 0x75, 0x1f,\n    0x75, 0x28, 0x75, 0x30, 0x75, 0x8b, 0x75, 0x92,\n    0x75, 0x76, 0x76, 0x7d, 0x76, 0xae, 0x76, 0xbf,\n    0x76, 0xee, 0x76, 0xdb, 0x77, 0xe2, 0x77, 0xf3,\n    0x77, 0x3a, 0x79, 0xb8, 0x79, 0xbe, 0x79, 0x74,\n    0x7a, 0xcb, 0x7a, 0xf9, 0x7a, 0x73, 0x7c, 0xf8,\n    0x7c, 0x36, 0x7f, 0x51, 0x7f, 0x8a, 0x7f, 0xbd,\n    0x7f, 0x01, 0x80, 0x0c, 0x80, 0x12, 0x80, 0x33,\n    0x80, 0x7f, 0x80, 0x89, 0x80, 0xe3, 0x81, 0x00,\n    0x07, 0x10, 0x19, 0x29, 0x38, 0x3c, 0x8b, 0x8f,\n    0x95, 0x4d, 0x86, 0x6b, 0x86, 0x40, 0x88, 0x4c,\n    0x88, 0x63, 0x88, 0x7e, 0x89, 0x8b, 0x89, 0xd2,\n    0x89, 0x00, 0x8a, 0x37, 0x8c, 0x46, 0x8c, 0x55,\n    0x8c, 0x78, 0x8c, 0x9d, 0x8c, 0x64, 0x8d, 0x70,\n    0x8d, 0xb3, 0x8d, 0xab, 0x8e, 0xca, 0x8e, 0x9b,\n    0x8f, 0xb0, 0x8f, 0xb5, 0x8f, 0x91, 0x90, 0x49,\n    0x91, 0xc6, 0x91, 0xcc, 0x91, 0xd1, 0x91, 0x77,\n    0x95, 0x80, 0x95, 0x1c, 0x96, 0xb6, 0x96, 0xb9,\n    0x96, 0xe8, 0x96, 0x51, 0x97, 0x5e, 0x97, 0x62,\n    0x97, 0x69, 0x97, 0xcb, 0x97, 0xed, 0x97, 0xf3,\n    0x97, 0x01, 0x98, 0xa8, 0x98, 0xdb, 0x98, 0xdf,\n    0x98, 0x96, 0x99, 0x99, 0x99, 0xac, 0x99, 0xa8,\n    0x9a, 0xd8, 0x9a, 0xdf, 0x9a, 0x25, 0x9b, 0x2f,\n    0x9b, 0x32, 0x9b, 0x3c, 0x9b, 0x5a, 0x9b, 0xe5,\n    0x9c, 0x75, 0x9e, 0x7f, 0x9e, 0xa5, 0x9e, 0x00,\n    0x16, 0x1e, 0x28, 0x2c, 0x54, 0x58, 0x69, 0x6e,\n    0x7b, 0x96, 0xa5, 0xad, 0xe8, 0xf7, 0xfb, 0x12,\n    0x30, 0x00, 0x00, 0x41, 0x53, 0x44, 0x53, 0x45,\n    0x53, 0x4b, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x4d, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x4f, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x51, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x53, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x55, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x57, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x59, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x5b, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x5d, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x5f, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x61, 0x30, 0x99, 0x30, 0x64, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0x66, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0x68, 0x30, 0x99,\n    0x30, 0x6f, 0x30, 0x99, 0x30, 0x72, 0x30, 0x99,\n    0x30, 0x75, 0x30, 0x99, 0x30, 0x78, 0x30, 0x99,\n    0x30, 0x7b, 0x30, 0x99, 0x30, 0x46, 0x30, 0x99,\n    0x30, 0x20, 0x00, 0x99, 0x30, 0x9d, 0x30, 0x99,\n    0x30, 0x88, 0x30, 0x8a, 0x30, 0xab, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xad, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xaf, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xb1, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xb3, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xb5, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xb7, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xb9, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xbb, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xbd, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xbf, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xc1, 0x30, 0x99,\n    0x30, 0xc4, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0xc6, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0xc8, 0x30, 0x99, 0x30, 0xcf, 0x30, 0x99,\n    0x30, 0xd2, 0x30, 0x99, 0x30, 0xd5, 0x30, 0x99,\n    0x30, 0xd8, 0x30, 0x99, 0x30, 0xdb, 0x30, 0x99,\n    0x30, 0xa6, 0x30, 0x99, 0x30, 0xef, 0x30, 0x99,\n    0x30, 0xfd, 0x30, 0x99, 0x30, 0xb3, 0x30, 0xc8,\n    0x30, 0x00, 0x11, 0x00, 0x01, 0xaa, 0x02, 0xac,\n    0xad, 0x03, 0x04, 0x05, 0xb0, 0xb1, 0xb2, 0xb3,\n    0xb4, 0xb5, 0x1a, 0x06, 0x07, 0x08, 0x21, 0x09,\n    0x11, 0x61, 0x11, 0x14, 0x11, 0x4c, 0x00, 0x01,\n    0xb3, 0xb4, 0xb8, 0xba, 0xbf, 0xc3, 0xc5, 0x08,\n    0xc9, 0xcb, 0x09, 0x0a, 0x0c, 0x0e, 0x0f, 0x13,\n    0x15, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1e, 0x22,\n    0x2c, 0x33, 0x38, 0xdd, 0xde, 0x43, 0x44, 0x45,\n    0x70, 0x71, 0x74, 0x7d, 0x7e, 0x80, 0x8a, 0x8d,\n    0x00, 0x4e, 0x8c, 0x4e, 0x09, 0x4e, 0xdb, 0x56,\n    0x0a, 0x4e, 0x2d, 0x4e, 0x0b, 0x4e, 0x32, 0x75,\n    0x59, 0x4e, 0x19, 0x4e, 0x01, 0x4e, 0x29, 0x59,\n    0x30, 0x57, 0xba, 0x4e, 0x28, 0x00, 0x29, 0x00,\n    0x00, 0x11, 0x02, 0x11, 0x03, 0x11, 0x05, 0x11,\n    0x06, 0x11, 0x07, 0x11, 0x09, 0x11, 0x0b, 0x11,\n    0x0c, 0x11, 0x0e, 0x11, 0x0f, 0x11, 0x10, 0x11,\n    0x11, 0x11, 0x12, 0x11, 0x28, 0x00, 0x00, 0x11,\n    0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x02, 0x11,\n    0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x05, 0x11,\n    0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x09, 0x11,\n    0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x0b, 0x11,\n    0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x0e, 0x11,\n    0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x0c, 0x11,\n    0x6e, 0x11, 0x29, 0x00, 0x28, 0x00, 0x0b, 0x11,\n    0x69, 0x11, 0x0c, 0x11, 0x65, 0x11, 0xab, 0x11,\n    0x29, 0x00, 0x28, 0x00, 0x0b, 0x11, 0x69, 0x11,\n    0x12, 0x11, 0x6e, 0x11, 0x29, 0x00, 0x28, 0x00,\n    0x29, 0x00, 0x00, 0x4e, 0x8c, 0x4e, 0x09, 0x4e,\n    0xdb, 0x56, 0x94, 0x4e, 0x6d, 0x51, 0x03, 0x4e,\n    0x6b, 0x51, 0x5d, 0x4e, 0x41, 0x53, 0x08, 0x67,\n    0x6b, 0x70, 0x34, 0x6c, 0x28, 0x67, 0xd1, 0x91,\n    0x1f, 0x57, 0xe5, 0x65, 0x2a, 0x68, 0x09, 0x67,\n    0x3e, 0x79, 0x0d, 0x54, 0x79, 0x72, 0xa1, 0x8c,\n    0x5d, 0x79, 0xb4, 0x52, 0xe3, 0x4e, 0x7c, 0x54,\n    0x66, 0x5b, 0xe3, 0x76, 0x01, 0x4f, 0xc7, 0x8c,\n    0x54, 0x53, 0x6d, 0x79, 0x11, 0x4f, 0xea, 0x81,\n    0xf3, 0x81, 0x4f, 0x55, 0x7c, 0x5e, 0x87, 0x65,\n    0x8f, 0x7b, 0x50, 0x54, 0x45, 0x32, 0x00, 0x31,\n    0x00, 0x33, 0x00, 0x30, 0x00, 0x00, 0x11, 0x00,\n    0x02, 0x03, 0x05, 0x06, 0x07, 0x09, 0x0b, 0x0c,\n    0x0e, 0x0f, 0x10, 0x11, 0x12, 0x00, 0x11, 0x00,\n    0x61, 0x02, 0x61, 0x03, 0x61, 0x05, 0x61, 0x06,\n    0x61, 0x07, 0x61, 0x09, 0x61, 0x0b, 0x61, 0x0c,\n    0x61, 0x0e, 0x11, 0x61, 0x11, 0x00, 0x11, 0x0e,\n    0x61, 0xb7, 0x00, 0x69, 0x0b, 0x11, 0x01, 0x63,\n    0x00, 0x69, 0x0b, 0x11, 0x6e, 0x11, 0x00, 0x4e,\n    0x8c, 0x4e, 0x09, 0x4e, 0xdb, 0x56, 0x94, 0x4e,\n    0x6d, 0x51, 0x03, 0x4e, 0x6b, 0x51, 0x5d, 0x4e,\n    0x41, 0x53, 0x08, 0x67, 0x6b, 0x70, 0x34, 0x6c,\n    0x28, 0x67, 0xd1, 0x91, 0x1f, 0x57, 0xe5, 0x65,\n    0x2a, 0x68, 0x09, 0x67, 0x3e, 0x79, 0x0d, 0x54,\n    0x79, 0x72, 0xa1, 0x8c, 0x5d, 0x79, 0xb4, 0x52,\n    0xd8, 0x79, 0x37, 0x75, 0x73, 0x59, 0x69, 0x90,\n    0x2a, 0x51, 0x70, 0x53, 0xe8, 0x6c, 0x05, 0x98,\n    0x11, 0x4f, 0x99, 0x51, 0x63, 0x6b, 0x0a, 0x4e,\n    0x2d, 0x4e, 0x0b, 0x4e, 0xe6, 0x5d, 0xf3, 0x53,\n    0x3b, 0x53, 0x97, 0x5b, 0x66, 0x5b, 0xe3, 0x76,\n    0x01, 0x4f, 0xc7, 0x8c, 0x54, 0x53, 0x1c, 0x59,\n    0x33, 0x00, 0x36, 0x00, 0x34, 0x00, 0x30, 0x00,\n    0x35, 0x30, 0x31, 0x00, 0x08, 0x67, 0x31, 0x00,\n    0x30, 0x00, 0x08, 0x67, 0x48, 0x67, 0x65, 0x72,\n    0x67, 0x65, 0x56, 0x4c, 0x54, 0x44, 0xa2, 0x30,\n    0x00, 0x02, 0x04, 0x06, 0x08, 0x09, 0x0b, 0x0d,\n    0x0f, 0x11, 0x13, 0x15, 0x17, 0x19, 0x1b, 0x1d,\n    0x1f, 0x22, 0x24, 0x26, 0x28, 0x29, 0x2a, 0x2b,\n    0x2c, 0x2d, 0x30, 0x33, 0x36, 0x39, 0x3c, 0x3d,\n    0x3e, 0x3f, 0x40, 0x42, 0x44, 0x46, 0x47, 0x48,\n    0x49, 0x4a, 0x4b, 0x4d, 0x4e, 0x4f, 0x50, 0xe4,\n    0x4e, 0x8c, 0x54, 0xa1, 0x30, 0x01, 0x30, 0x5b,\n    0x27, 0x01, 0x4a, 0x34, 0x00, 0x01, 0x52, 0x39,\n    0x01, 0xa2, 0x30, 0x00, 0x5a, 0x49, 0xa4, 0x30,\n    0x00, 0x27, 0x4f, 0x0c, 0xa4, 0x30, 0x00, 0x4f,\n    0x1d, 0x02, 0x05, 0x4f, 0xa8, 0x30, 0x00, 0x11,\n    0x07, 0x54, 0x21, 0xa8, 0x30, 0x00, 0x54, 0x03,\n    0x54, 0xa4, 0x30, 0x06, 0x4f, 0x15, 0x06, 0x58,\n    0x3c, 0x07, 0x00, 0x46, 0xab, 0x30, 0x00, 0x3e,\n    0x18, 0x1d, 0x00, 0x42, 0x3f, 0x51, 0xac, 0x30,\n    0x00, 0x41, 0x47, 0x00, 0x47, 0x32, 0xae, 0x30,\n    0xac, 0x30, 0xae, 0x30, 0x00, 0x1d, 0x4e, 0xad,\n    0x30, 0x00, 0x38, 0x3d, 0x4f, 0x01, 0x3e, 0x13,\n    0x4f, 0xad, 0x30, 0xed, 0x30, 0xad, 0x30, 0x00,\n    0x40, 0x03, 0x3c, 0x33, 0xad, 0x30, 0x00, 0x40,\n    0x34, 0x4f, 0x1b, 0x3e, 0xad, 0x30, 0x00, 0x40,\n    0x42, 0x16, 0x1b, 0xb0, 0x30, 0x00, 0x39, 0x30,\n    0xa4, 0x30, 0x0c, 0x45, 0x3c, 0x24, 0x4f, 0x0b,\n    0x47, 0x18, 0x00, 0x49, 0xaf, 0x30, 0x00, 0x3e,\n    0x4d, 0x1e, 0xb1, 0x30, 0x00, 0x4b, 0x08, 0x02,\n    0x3a, 0x19, 0x02, 0x4b, 0x2c, 0xa4, 0x30, 0x11,\n    0x00, 0x0b, 0x47, 0xb5, 0x30, 0x00, 0x3e, 0x0c,\n    0x47, 0x2b, 0xb0, 0x30, 0x07, 0x3a, 0x43, 0x00,\n    0xb9, 0x30, 0x02, 0x3a, 0x08, 0x02, 0x3a, 0x0f,\n    0x07, 0x43, 0x00, 0xb7, 0x30, 0x10, 0x00, 0x12,\n    0x34, 0x11, 0x3c, 0x13, 0x17, 0xa4, 0x30, 0x2a,\n    0x1f, 0x24, 0x2b, 0x00, 0x20, 0xbb, 0x30, 0x16,\n    0x41, 0x00, 0x38, 0x0d, 0xc4, 0x30, 0x0d, 0x38,\n    0x00, 0xd0, 0x30, 0x00, 0x2c, 0x1c, 0x1b, 0xa2,\n    0x30, 0x32, 0x00, 0x17, 0x26, 0x49, 0xaf, 0x30,\n    0x25, 0x00, 0x3c, 0xb3, 0x30, 0x21, 0x00, 0x20,\n    0x38, 0xa1, 0x30, 0x34, 0x00, 0x48, 0x22, 0x28,\n    0xa3, 0x30, 0x32, 0x00, 0x59, 0x25, 0xa7, 0x30,\n    0x2f, 0x1c, 0x10, 0x00, 0x44, 0xd5, 0x30, 0x00,\n    0x14, 0x1e, 0xaf, 0x30, 0x29, 0x00, 0x10, 0x4d,\n    0x3c, 0xda, 0x30, 0xbd, 0x30, 0xb8, 0x30, 0x22,\n    0x13, 0x1a, 0x20, 0x33, 0x0c, 0x22, 0x3b, 0x01,\n    0x22, 0x44, 0x00, 0x21, 0x44, 0x07, 0xa4, 0x30,\n    0x39, 0x00, 0x4f, 0x24, 0xc8, 0x30, 0x14, 0x23,\n    0x00, 0xdb, 0x30, 0xf3, 0x30, 0xc9, 0x30, 0x14,\n    0x2a, 0x00, 0x12, 0x33, 0x22, 0x12, 0x33, 0x2a,\n    0xa4, 0x30, 0x3a, 0x00, 0x0b, 0x49, 0xa4, 0x30,\n    0x3a, 0x00, 0x47, 0x3a, 0x1f, 0x2b, 0x3a, 0x47,\n    0x0b, 0xb7, 0x30, 0x27, 0x3c, 0x00, 0x30, 0x3c,\n    0xaf, 0x30, 0x30, 0x00, 0x3e, 0x44, 0xdf, 0x30,\n    0xea, 0x30, 0xd0, 0x30, 0x0f, 0x1a, 0x00, 0x2c,\n    0x1b, 0xe1, 0x30, 0xac, 0x30, 0xac, 0x30, 0x35,\n    0x00, 0x1c, 0x47, 0x35, 0x50, 0x1c, 0x3f, 0xa2,\n    0x30, 0x42, 0x5a, 0x27, 0x42, 0x5a, 0x49, 0x44,\n    0x00, 0x51, 0xc3, 0x30, 0x27, 0x00, 0x05, 0x28,\n    0xea, 0x30, 0xe9, 0x30, 0xd4, 0x30, 0x17, 0x00,\n    0x28, 0xd6, 0x30, 0x15, 0x26, 0x00, 0x15, 0xec,\n    0x30, 0xe0, 0x30, 0xb2, 0x30, 0x3a, 0x41, 0x16,\n    0x00, 0x41, 0xc3, 0x30, 0x2c, 0x00, 0x05, 0x30,\n    0x00, 0xb9, 0x70, 0x31, 0x00, 0x30, 0x00, 0xb9,\n    0x70, 0x32, 0x00, 0x30, 0x00, 0xb9, 0x70, 0x68,\n    0x50, 0x61, 0x64, 0x61, 0x41, 0x55, 0x62, 0x61,\n    0x72, 0x6f, 0x56, 0x70, 0x63, 0x64, 0x6d, 0x64,\n    0x00, 0x6d, 0x00, 0xb2, 0x00, 0x49, 0x00, 0x55,\n    0x00, 0x73, 0x5e, 0x10, 0x62, 0x2d, 0x66, 0x8c,\n    0x54, 0x27, 0x59, 0x63, 0x6b, 0x0e, 0x66, 0xbb,\n    0x6c, 0x2a, 0x68, 0x0f, 0x5f, 0x1a, 0x4f, 0x3e,\n    0x79, 0x70, 0x00, 0x41, 0x6e, 0x00, 0x41, 0xbc,\n    0x03, 0x41, 0x6d, 0x00, 0x41, 0x6b, 0x00, 0x41,\n    0x4b, 0x00, 0x42, 0x4d, 0x00, 0x42, 0x47, 0x00,\n    0x42, 0x63, 0x61, 0x6c, 0x6b, 0x63, 0x61, 0x6c,\n    0x70, 0x00, 0x46, 0x6e, 0x00, 0x46, 0xbc, 0x03,\n    0x46, 0xbc, 0x03, 0x67, 0x6d, 0x00, 0x67, 0x6b,\n    0x00, 0x67, 0x48, 0x00, 0x7a, 0x6b, 0x48, 0x7a,\n    0x4d, 0x48, 0x7a, 0x47, 0x48, 0x7a, 0x54, 0x48,\n    0x7a, 0xbc, 0x03, 0x13, 0x21, 0x6d, 0x00, 0x13,\n    0x21, 0x64, 0x00, 0x13, 0x21, 0x6b, 0x00, 0x13,\n    0x21, 0x66, 0x00, 0x6d, 0x6e, 0x00, 0x6d, 0xbc,\n    0x03, 0x6d, 0x6d, 0x00, 0x6d, 0x63, 0x00, 0x6d,\n    0x6b, 0x00, 0x6d, 0x63, 0x00, 0x0a, 0x0a, 0x4f,\n    0x00, 0x0a, 0x4f, 0x6d, 0x00, 0xb2, 0x00, 0x63,\n    0x00, 0x08, 0x0a, 0x4f, 0x0a, 0x0a, 0x50, 0x00,\n    0x0a, 0x50, 0x6d, 0x00, 0xb3, 0x00, 0x6b, 0x00,\n    0x6d, 0x00, 0xb3, 0x00, 0x6d, 0x00, 0x15, 0x22,\n    0x73, 0x00, 0x6d, 0x00, 0x15, 0x22, 0x73, 0x00,\n    0xb2, 0x00, 0x50, 0x61, 0x6b, 0x50, 0x61, 0x4d,\n    0x50, 0x61, 0x47, 0x50, 0x61, 0x72, 0x61, 0x64,\n    0x72, 0x61, 0x64, 0xd1, 0x73, 0x72, 0x00, 0x61,\n    0x00, 0x64, 0x00, 0x15, 0x22, 0x73, 0x00, 0xb2,\n    0x00, 0x70, 0x00, 0x73, 0x6e, 0x00, 0x73, 0xbc,\n    0x03, 0x73, 0x6d, 0x00, 0x73, 0x70, 0x00, 0x56,\n    0x6e, 0x00, 0x56, 0xbc, 0x03, 0x56, 0x6d, 0x00,\n    0x56, 0x6b, 0x00, 0x56, 0x4d, 0x00, 0x56, 0x70,\n    0x00, 0x57, 0x6e, 0x00, 0x57, 0xbc, 0x03, 0x57,\n    0x6d, 0x00, 0x57, 0x6b, 0x00, 0x57, 0x4d, 0x00,\n    0x57, 0x6b, 0x00, 0xa9, 0x03, 0x4d, 0x00, 0xa9,\n    0x03, 0x61, 0x2e, 0x6d, 0x2e, 0x42, 0x71, 0x63,\n    0x63, 0x63, 0x64, 0x43, 0xd1, 0x6b, 0x67, 0x43,\n    0x6f, 0x2e, 0x64, 0x42, 0x47, 0x79, 0x68, 0x61,\n    0x48, 0x50, 0x69, 0x6e, 0x4b, 0x4b, 0x4b, 0x4d,\n    0x6b, 0x74, 0x6c, 0x6d, 0x6c, 0x6e, 0x6c, 0x6f,\n    0x67, 0x6c, 0x78, 0x6d, 0x62, 0x6d, 0x69, 0x6c,\n    0x6d, 0x6f, 0x6c, 0x50, 0x48, 0x70, 0x2e, 0x6d,\n    0x2e, 0x50, 0x50, 0x4d, 0x50, 0x52, 0x73, 0x72,\n    0x53, 0x76, 0x57, 0x62, 0x56, 0xd1, 0x6d, 0x41,\n    0xd1, 0x6d, 0x31, 0x00, 0xe5, 0x65, 0x31, 0x00,\n    0x30, 0x00, 0xe5, 0x65, 0x32, 0x00, 0x30, 0x00,\n    0xe5, 0x65, 0x33, 0x00, 0x30, 0x00, 0xe5, 0x65,\n    0x67, 0x61, 0x6c, 0x4a, 0x04, 0x4c, 0x04, 0x26,\n    0x01, 0x53, 0x01, 0x27, 0xa7, 0x37, 0xab, 0x6b,\n    0x02, 0x52, 0xab, 0x48, 0x8c, 0xf4, 0x66, 0xca,\n    0x8e, 0xc8, 0x8c, 0xd1, 0x6e, 0x32, 0x4e, 0xe5,\n    0x53, 0x9c, 0x9f, 0x9c, 0x9f, 0x51, 0x59, 0xd1,\n    0x91, 0x87, 0x55, 0x48, 0x59, 0xf6, 0x61, 0x69,\n    0x76, 0x85, 0x7f, 0x3f, 0x86, 0xba, 0x87, 0xf8,\n    0x88, 0x8f, 0x90, 0x02, 0x6a, 0x1b, 0x6d, 0xd9,\n    0x70, 0xde, 0x73, 0x3d, 0x84, 0x6a, 0x91, 0xf1,\n    0x99, 0x82, 0x4e, 0x75, 0x53, 0x04, 0x6b, 0x1b,\n    0x72, 0x2d, 0x86, 0x1e, 0x9e, 0x50, 0x5d, 0xeb,\n    0x6f, 0xcd, 0x85, 0x64, 0x89, 0xc9, 0x62, 0xd8,\n    0x81, 0x1f, 0x88, 0xca, 0x5e, 0x17, 0x67, 0x6a,\n    0x6d, 0xfc, 0x72, 0xce, 0x90, 0x86, 0x4f, 0xb7,\n    0x51, 0xde, 0x52, 0xc4, 0x64, 0xd3, 0x6a, 0x10,\n    0x72, 0xe7, 0x76, 0x01, 0x80, 0x06, 0x86, 0x5c,\n    0x86, 0xef, 0x8d, 0x32, 0x97, 0x6f, 0x9b, 0xfa,\n    0x9d, 0x8c, 0x78, 0x7f, 0x79, 0xa0, 0x7d, 0xc9,\n    0x83, 0x04, 0x93, 0x7f, 0x9e, 0xd6, 0x8a, 0xdf,\n    0x58, 0x04, 0x5f, 0x60, 0x7c, 0x7e, 0x80, 0x62,\n    0x72, 0xca, 0x78, 0xc2, 0x8c, 0xf7, 0x96, 0xd8,\n    0x58, 0x62, 0x5c, 0x13, 0x6a, 0xda, 0x6d, 0x0f,\n    0x6f, 0x2f, 0x7d, 0x37, 0x7e, 0x4b, 0x96, 0xd2,\n    0x52, 0x8b, 0x80, 0xdc, 0x51, 0xcc, 0x51, 0x1c,\n    0x7a, 0xbe, 0x7d, 0xf1, 0x83, 0x75, 0x96, 0x80,\n    0x8b, 0xcf, 0x62, 0x02, 0x6a, 0xfe, 0x8a, 0x39,\n    0x4e, 0xe7, 0x5b, 0x12, 0x60, 0x87, 0x73, 0x70,\n    0x75, 0x17, 0x53, 0xfb, 0x78, 0xbf, 0x4f, 0xa9,\n    0x5f, 0x0d, 0x4e, 0xcc, 0x6c, 0x78, 0x65, 0x22,\n    0x7d, 0xc3, 0x53, 0x5e, 0x58, 0x01, 0x77, 0x49,\n    0x84, 0xaa, 0x8a, 0xba, 0x6b, 0xb0, 0x8f, 0x88,\n    0x6c, 0xfe, 0x62, 0xe5, 0x82, 0xa0, 0x63, 0x65,\n    0x75, 0xae, 0x4e, 0x69, 0x51, 0xc9, 0x51, 0x81,\n    0x68, 0xe7, 0x7c, 0x6f, 0x82, 0xd2, 0x8a, 0xcf,\n    0x91, 0xf5, 0x52, 0x42, 0x54, 0x73, 0x59, 0xec,\n    0x5e, 0xc5, 0x65, 0xfe, 0x6f, 0x2a, 0x79, 0xad,\n    0x95, 0x6a, 0x9a, 0x97, 0x9e, 0xce, 0x9e, 0x9b,\n    0x52, 0xc6, 0x66, 0x77, 0x6b, 0x62, 0x8f, 0x74,\n    0x5e, 0x90, 0x61, 0x00, 0x62, 0x9a, 0x64, 0x23,\n    0x6f, 0x49, 0x71, 0x89, 0x74, 0xca, 0x79, 0xf4,\n    0x7d, 0x6f, 0x80, 0x26, 0x8f, 0xee, 0x84, 0x23,\n    0x90, 0x4a, 0x93, 0x17, 0x52, 0xa3, 0x52, 0xbd,\n    0x54, 0xc8, 0x70, 0xc2, 0x88, 0xaa, 0x8a, 0xc9,\n    0x5e, 0xf5, 0x5f, 0x7b, 0x63, 0xae, 0x6b, 0x3e,\n    0x7c, 0x75, 0x73, 0xe4, 0x4e, 0xf9, 0x56, 0xe7,\n    0x5b, 0xba, 0x5d, 0x1c, 0x60, 0xb2, 0x73, 0x69,\n    0x74, 0x9a, 0x7f, 0x46, 0x80, 0x34, 0x92, 0xf6,\n    0x96, 0x48, 0x97, 0x18, 0x98, 0x8b, 0x4f, 0xae,\n    0x79, 0xb4, 0x91, 0xb8, 0x96, 0xe1, 0x60, 0x86,\n    0x4e, 0xda, 0x50, 0xee, 0x5b, 0x3f, 0x5c, 0x99,\n    0x65, 0x02, 0x6a, 0xce, 0x71, 0x42, 0x76, 0xfc,\n    0x84, 0x7c, 0x90, 0x8d, 0x9f, 0x88, 0x66, 0x2e,\n    0x96, 0x89, 0x52, 0x7b, 0x67, 0xf3, 0x67, 0x41,\n    0x6d, 0x9c, 0x6e, 0x09, 0x74, 0x59, 0x75, 0x6b,\n    0x78, 0x10, 0x7d, 0x5e, 0x98, 0x6d, 0x51, 0x2e,\n    0x62, 0x78, 0x96, 0x2b, 0x50, 0x19, 0x5d, 0xea,\n    0x6d, 0x2a, 0x8f, 0x8b, 0x5f, 0x44, 0x61, 0x17,\n    0x68, 0x87, 0x73, 0x86, 0x96, 0x29, 0x52, 0x0f,\n    0x54, 0x65, 0x5c, 0x13, 0x66, 0x4e, 0x67, 0xa8,\n    0x68, 0xe5, 0x6c, 0x06, 0x74, 0xe2, 0x75, 0x79,\n    0x7f, 0xcf, 0x88, 0xe1, 0x88, 0xcc, 0x91, 0xe2,\n    0x96, 0x3f, 0x53, 0xba, 0x6e, 0x1d, 0x54, 0xd0,\n    0x71, 0x98, 0x74, 0xfa, 0x85, 0xa3, 0x96, 0x57,\n    0x9c, 0x9f, 0x9e, 0x97, 0x67, 0xcb, 0x6d, 0xe8,\n    0x81, 0xcb, 0x7a, 0x20, 0x7b, 0x92, 0x7c, 0xc0,\n    0x72, 0x99, 0x70, 0x58, 0x8b, 0xc0, 0x4e, 0x36,\n    0x83, 0x3a, 0x52, 0x07, 0x52, 0xa6, 0x5e, 0xd3,\n    0x62, 0xd6, 0x7c, 0x85, 0x5b, 0x1e, 0x6d, 0xb4,\n    0x66, 0x3b, 0x8f, 0x4c, 0x88, 0x4d, 0x96, 0x8b,\n    0x89, 0xd3, 0x5e, 0x40, 0x51, 0xc0, 0x55, 0x00,\n    0x00, 0x00, 0x00, 0x5a, 0x58, 0x00, 0x00, 0x74,\n    0x66, 0x00, 0x00, 0x00, 0x00, 0xde, 0x51, 0x2a,\n    0x73, 0xca, 0x76, 0x3c, 0x79, 0x5e, 0x79, 0x65,\n    0x79, 0x8f, 0x79, 0x56, 0x97, 0xbe, 0x7c, 0xbd,\n    0x7f, 0x00, 0x00, 0x12, 0x86, 0x00, 0x00, 0xf8,\n    0x8a, 0x00, 0x00, 0x00, 0x00, 0x38, 0x90, 0xfd,\n    0x90, 0xef, 0x98, 0xfc, 0x98, 0x28, 0x99, 0xb4,\n    0x9d, 0xde, 0x90, 0xb7, 0x96, 0xae, 0x4f, 0xe7,\n    0x50, 0x4d, 0x51, 0xc9, 0x52, 0xe4, 0x52, 0x51,\n    0x53, 0x9d, 0x55, 0x06, 0x56, 0x68, 0x56, 0x40,\n    0x58, 0xa8, 0x58, 0x64, 0x5c, 0x6e, 0x5c, 0x94,\n    0x60, 0x68, 0x61, 0x8e, 0x61, 0xf2, 0x61, 0x4f,\n    0x65, 0xe2, 0x65, 0x91, 0x66, 0x85, 0x68, 0x77,\n    0x6d, 0x1a, 0x6e, 0x22, 0x6f, 0x6e, 0x71, 0x2b,\n    0x72, 0x22, 0x74, 0x91, 0x78, 0x3e, 0x79, 0x49,\n    0x79, 0x48, 0x79, 0x50, 0x79, 0x56, 0x79, 0x5d,\n    0x79, 0x8d, 0x79, 0x8e, 0x79, 0x40, 0x7a, 0x81,\n    0x7a, 0xc0, 0x7b, 0xf4, 0x7d, 0x09, 0x7e, 0x41,\n    0x7e, 0x72, 0x7f, 0x05, 0x80, 0xed, 0x81, 0x79,\n    0x82, 0x79, 0x82, 0x57, 0x84, 0x10, 0x89, 0x96,\n    0x89, 0x01, 0x8b, 0x39, 0x8b, 0xd3, 0x8c, 0x08,\n    0x8d, 0xb6, 0x8f, 0x38, 0x90, 0xe3, 0x96, 0xff,\n    0x97, 0x3b, 0x98, 0x75, 0x60, 0xee, 0x42, 0x18,\n    0x82, 0x02, 0x26, 0x4e, 0xb5, 0x51, 0x68, 0x51,\n    0x80, 0x4f, 0x45, 0x51, 0x80, 0x51, 0xc7, 0x52,\n    0xfa, 0x52, 0x9d, 0x55, 0x55, 0x55, 0x99, 0x55,\n    0xe2, 0x55, 0x5a, 0x58, 0xb3, 0x58, 0x44, 0x59,\n    0x54, 0x59, 0x62, 0x5a, 0x28, 0x5b, 0xd2, 0x5e,\n    0xd9, 0x5e, 0x69, 0x5f, 0xad, 0x5f, 0xd8, 0x60,\n    0x4e, 0x61, 0x08, 0x61, 0x8e, 0x61, 0x60, 0x61,\n    0xf2, 0x61, 0x34, 0x62, 0xc4, 0x63, 0x1c, 0x64,\n    0x52, 0x64, 0x56, 0x65, 0x74, 0x66, 0x17, 0x67,\n    0x1b, 0x67, 0x56, 0x67, 0x79, 0x6b, 0xba, 0x6b,\n    0x41, 0x6d, 0xdb, 0x6e, 0xcb, 0x6e, 0x22, 0x6f,\n    0x1e, 0x70, 0x6e, 0x71, 0xa7, 0x77, 0x35, 0x72,\n    0xaf, 0x72, 0x2a, 0x73, 0x71, 0x74, 0x06, 0x75,\n    0x3b, 0x75, 0x1d, 0x76, 0x1f, 0x76, 0xca, 0x76,\n    0xdb, 0x76, 0xf4, 0x76, 0x4a, 0x77, 0x40, 0x77,\n    0xcc, 0x78, 0xb1, 0x7a, 0xc0, 0x7b, 0x7b, 0x7c,\n    0x5b, 0x7d, 0xf4, 0x7d, 0x3e, 0x7f, 0x05, 0x80,\n    0x52, 0x83, 0xef, 0x83, 0x79, 0x87, 0x41, 0x89,\n    0x86, 0x89, 0x96, 0x89, 0xbf, 0x8a, 0xf8, 0x8a,\n    0xcb, 0x8a, 0x01, 0x8b, 0xfe, 0x8a, 0xed, 0x8a,\n    0x39, 0x8b, 0x8a, 0x8b, 0x08, 0x8d, 0x38, 0x8f,\n    0x72, 0x90, 0x99, 0x91, 0x76, 0x92, 0x7c, 0x96,\n    0xe3, 0x96, 0x56, 0x97, 0xdb, 0x97, 0xff, 0x97,\n    0x0b, 0x98, 0x3b, 0x98, 0x12, 0x9b, 0x9c, 0x9f,\n    0x4a, 0x28, 0x44, 0x28, 0xd5, 0x33, 0x9d, 0x3b,\n    0x18, 0x40, 0x39, 0x40, 0x49, 0x52, 0xd0, 0x5c,\n    0xd3, 0x7e, 0x43, 0x9f, 0x8e, 0x9f, 0x2a, 0xa0,\n    0x02, 0x66, 0x66, 0x66, 0x69, 0x66, 0x6c, 0x66,\n    0x66, 0x69, 0x66, 0x66, 0x6c, 0x7f, 0x01, 0x74,\n    0x73, 0x00, 0x74, 0x65, 0x05, 0x0f, 0x11, 0x0f,\n    0x00, 0x0f, 0x06, 0x19, 0x11, 0x0f, 0x08, 0xd9,\n    0x05, 0xb4, 0x05, 0x00, 0x00, 0x00, 0x00, 0xf2,\n    0x05, 0xb7, 0x05, 0xd0, 0x05, 0x12, 0x00, 0x03,\n    0x04, 0x0b, 0x0c, 0x0d, 0x18, 0x1a, 0xe9, 0x05,\n    0xc1, 0x05, 0xe9, 0x05, 0xc2, 0x05, 0x49, 0xfb,\n    0xc1, 0x05, 0x49, 0xfb, 0xc2, 0x05, 0xd0, 0x05,\n    0xb7, 0x05, 0xd0, 0x05, 0xb8, 0x05, 0xd0, 0x05,\n    0xbc, 0x05, 0xd8, 0x05, 0xbc, 0x05, 0xde, 0x05,\n    0xbc, 0x05, 0xe0, 0x05, 0xbc, 0x05, 0xe3, 0x05,\n    0xbc, 0x05, 0xb9, 0x05, 0x2d, 0x03, 0x2e, 0x03,\n    0x2f, 0x03, 0x30, 0x03, 0x31, 0x03, 0x1c, 0x00,\n    0x18, 0x06, 0x22, 0x06, 0x2b, 0x06, 0xd0, 0x05,\n    0xdc, 0x05, 0x71, 0x06, 0x00, 0x00, 0x0a, 0x0a,\n    0x0a, 0x0a, 0x0d, 0x0d, 0x0d, 0x0d, 0x0f, 0x0f,\n    0x0f, 0x0f, 0x09, 0x09, 0x09, 0x09, 0x0e, 0x0e,\n    0x0e, 0x0e, 0x08, 0x08, 0x08, 0x08, 0x33, 0x33,\n    0x33, 0x33, 0x35, 0x35, 0x35, 0x35, 0x13, 0x13,\n    0x13, 0x13, 0x12, 0x12, 0x12, 0x12, 0x15, 0x15,\n    0x15, 0x15, 0x16, 0x16, 0x16, 0x16, 0x1c, 0x1c,\n    0x1b, 0x1b, 0x1d, 0x1d, 0x17, 0x17, 0x27, 0x27,\n    0x20, 0x20, 0x38, 0x38, 0x38, 0x38, 0x3e, 0x3e,\n    0x3e, 0x3e, 0x42, 0x42, 0x42, 0x42, 0x40, 0x40,\n    0x40, 0x40, 0x49, 0x49, 0x4a, 0x4a, 0x4a, 0x4a,\n    0x4f, 0x4f, 0x50, 0x50, 0x50, 0x50, 0x4d, 0x4d,\n    0x4d, 0x4d, 0x61, 0x61, 0x62, 0x62, 0x49, 0x06,\n    0x64, 0x64, 0x64, 0x64, 0x7e, 0x7e, 0x7d, 0x7d,\n    0x7f, 0x7f, 0x2e, 0x82, 0x82, 0x7c, 0x7c, 0x80,\n    0x80, 0x87, 0x87, 0x87, 0x87, 0x00, 0x00, 0x26,\n    0x06, 0x00, 0x01, 0x00, 0x01, 0x00, 0xaf, 0x00,\n    0xaf, 0x00, 0x22, 0x00, 0x22, 0x00, 0xa1, 0x00,\n    0xa1, 0x00, 0xa0, 0x00, 0xa0, 0x00, 0xa2, 0x00,\n    0xa2, 0x00, 0xaa, 0x00, 0xaa, 0x00, 0xaa, 0x00,\n    0x23, 0x00, 0x23, 0x00, 0x23, 0xcc, 0x06, 0x00,\n    0x00, 0x00, 0x00, 0x26, 0x06, 0x00, 0x06, 0x00,\n    0x07, 0x00, 0x1f, 0x00, 0x23, 0x00, 0x24, 0x02,\n    0x06, 0x02, 0x07, 0x02, 0x08, 0x02, 0x1f, 0x02,\n    0x23, 0x02, 0x24, 0x04, 0x06, 0x04, 0x07, 0x04,\n    0x08, 0x04, 0x1f, 0x04, 0x23, 0x04, 0x24, 0x05,\n    0x06, 0x05, 0x1f, 0x05, 0x23, 0x05, 0x24, 0x06,\n    0x07, 0x06, 0x1f, 0x07, 0x06, 0x07, 0x1f, 0x08,\n    0x06, 0x08, 0x07, 0x08, 0x1f, 0x0d, 0x06, 0x0d,\n    0x07, 0x0d, 0x08, 0x0d, 0x1f, 0x0f, 0x07, 0x0f,\n    0x1f, 0x10, 0x06, 0x10, 0x07, 0x10, 0x08, 0x10,\n    0x1f, 0x11, 0x07, 0x11, 0x1f, 0x12, 0x1f, 0x13,\n    0x06, 0x13, 0x1f, 0x14, 0x06, 0x14, 0x1f, 0x1b,\n    0x06, 0x1b, 0x07, 0x1b, 0x08, 0x1b, 0x1f, 0x1b,\n    0x23, 0x1b, 0x24, 0x1c, 0x07, 0x1c, 0x1f, 0x1c,\n    0x23, 0x1c, 0x24, 0x1d, 0x01, 0x1d, 0x06, 0x1d,\n    0x07, 0x1d, 0x08, 0x1d, 0x1e, 0x1d, 0x1f, 0x1d,\n    0x23, 0x1d, 0x24, 0x1e, 0x06, 0x1e, 0x07, 0x1e,\n    0x08, 0x1e, 0x1f, 0x1e, 0x23, 0x1e, 0x24, 0x1f,\n    0x06, 0x1f, 0x07, 0x1f, 0x08, 0x1f, 0x1f, 0x1f,\n    0x23, 0x1f, 0x24, 0x20, 0x06, 0x20, 0x07, 0x20,\n    0x08, 0x20, 0x1f, 0x20, 0x23, 0x20, 0x24, 0x21,\n    0x06, 0x21, 0x1f, 0x21, 0x23, 0x21, 0x24, 0x24,\n    0x06, 0x24, 0x07, 0x24, 0x08, 0x24, 0x1f, 0x24,\n    0x23, 0x24, 0x24, 0x0a, 0x4a, 0x0b, 0x4a, 0x23,\n    0x4a, 0x20, 0x00, 0x4c, 0x06, 0x51, 0x06, 0x51,\n    0x06, 0xff, 0x00, 0x1f, 0x26, 0x06, 0x00, 0x0b,\n    0x00, 0x0c, 0x00, 0x1f, 0x00, 0x20, 0x00, 0x23,\n    0x00, 0x24, 0x02, 0x0b, 0x02, 0x0c, 0x02, 0x1f,\n    0x02, 0x20, 0x02, 0x23, 0x02, 0x24, 0x04, 0x0b,\n    0x04, 0x0c, 0x04, 0x1f, 0x26, 0x06, 0x04, 0x20,\n    0x04, 0x23, 0x04, 0x24, 0x05, 0x0b, 0x05, 0x0c,\n    0x05, 0x1f, 0x05, 0x20, 0x05, 0x23, 0x05, 0x24,\n    0x1b, 0x23, 0x1b, 0x24, 0x1c, 0x23, 0x1c, 0x24,\n    0x1d, 0x01, 0x1d, 0x1e, 0x1d, 0x1f, 0x1d, 0x23,\n    0x1d, 0x24, 0x1e, 0x1f, 0x1e, 0x23, 0x1e, 0x24,\n    0x1f, 0x01, 0x1f, 0x1f, 0x20, 0x0b, 0x20, 0x0c,\n    0x20, 0x1f, 0x20, 0x20, 0x20, 0x23, 0x20, 0x24,\n    0x23, 0x4a, 0x24, 0x0b, 0x24, 0x0c, 0x24, 0x1f,\n    0x24, 0x20, 0x24, 0x23, 0x24, 0x24, 0x00, 0x06,\n    0x00, 0x07, 0x00, 0x08, 0x00, 0x1f, 0x00, 0x21,\n    0x02, 0x06, 0x02, 0x07, 0x02, 0x08, 0x02, 0x1f,\n    0x02, 0x21, 0x04, 0x06, 0x04, 0x07, 0x04, 0x08,\n    0x04, 0x1f, 0x04, 0x21, 0x05, 0x1f, 0x06, 0x07,\n    0x06, 0x1f, 0x07, 0x06, 0x07, 0x1f, 0x08, 0x06,\n    0x08, 0x1f, 0x0d, 0x06, 0x0d, 0x07, 0x0d, 0x08,\n    0x0d, 0x1f, 0x0f, 0x07, 0x0f, 0x08, 0x0f, 0x1f,\n    0x10, 0x06, 0x10, 0x07, 0x10, 0x08, 0x10, 0x1f,\n    0x11, 0x07, 0x12, 0x1f, 0x13, 0x06, 0x13, 0x1f,\n    0x14, 0x06, 0x14, 0x1f, 0x1b, 0x06, 0x1b, 0x07,\n    0x1b, 0x08, 0x1b, 0x1f, 0x1c, 0x07, 0x1c, 0x1f,\n    0x1d, 0x06, 0x1d, 0x07, 0x1d, 0x08, 0x1d, 0x1e,\n    0x1d, 0x1f, 0x1e, 0x06, 0x1e, 0x07, 0x1e, 0x08,\n    0x1e, 0x1f, 0x1e, 0x21, 0x1f, 0x06, 0x1f, 0x07,\n    0x1f, 0x08, 0x1f, 0x1f, 0x20, 0x06, 0x20, 0x07,\n    0x20, 0x08, 0x20, 0x1f, 0x20, 0x21, 0x21, 0x06,\n    0x21, 0x1f, 0x21, 0x4a, 0x24, 0x06, 0x24, 0x07,\n    0x24, 0x08, 0x24, 0x1f, 0x24, 0x21, 0x00, 0x1f,\n    0x00, 0x21, 0x02, 0x1f, 0x02, 0x21, 0x04, 0x1f,\n    0x04, 0x21, 0x05, 0x1f, 0x05, 0x21, 0x0d, 0x1f,\n    0x0d, 0x21, 0x0e, 0x1f, 0x0e, 0x21, 0x1d, 0x1e,\n    0x1d, 0x1f, 0x1e, 0x1f, 0x20, 0x1f, 0x20, 0x21,\n    0x24, 0x1f, 0x24, 0x21, 0x40, 0x06, 0x4e, 0x06,\n    0x51, 0x06, 0x27, 0x06, 0x10, 0x22, 0x10, 0x23,\n    0x12, 0x22, 0x12, 0x23, 0x13, 0x22, 0x13, 0x23,\n    0x0c, 0x22, 0x0c, 0x23, 0x0d, 0x22, 0x0d, 0x23,\n    0x06, 0x22, 0x06, 0x23, 0x05, 0x22, 0x05, 0x23,\n    0x07, 0x22, 0x07, 0x23, 0x0e, 0x22, 0x0e, 0x23,\n    0x0f, 0x22, 0x0f, 0x23, 0x0d, 0x05, 0x0d, 0x06,\n    0x0d, 0x07, 0x0d, 0x1e, 0x0d, 0x0a, 0x0c, 0x0a,\n    0x0e, 0x0a, 0x0f, 0x0a, 0x10, 0x22, 0x10, 0x23,\n    0x12, 0x22, 0x12, 0x23, 0x13, 0x22, 0x13, 0x23,\n    0x0c, 0x22, 0x0c, 0x23, 0x0d, 0x22, 0x0d, 0x23,\n    0x06, 0x22, 0x06, 0x23, 0x05, 0x22, 0x05, 0x23,\n    0x07, 0x22, 0x07, 0x23, 0x0e, 0x22, 0x0e, 0x23,\n    0x0f, 0x22, 0x0f, 0x23, 0x0d, 0x05, 0x0d, 0x06,\n    0x0d, 0x07, 0x0d, 0x1e, 0x0d, 0x0a, 0x0c, 0x0a,\n    0x0e, 0x0a, 0x0f, 0x0a, 0x0d, 0x05, 0x0d, 0x06,\n    0x0d, 0x07, 0x0d, 0x1e, 0x0c, 0x20, 0x0d, 0x20,\n    0x10, 0x1e, 0x0c, 0x05, 0x0c, 0x06, 0x0c, 0x07,\n    0x0d, 0x05, 0x0d, 0x06, 0x0d, 0x07, 0x10, 0x1e,\n    0x11, 0x1e, 0x00, 0x24, 0x00, 0x24, 0x2a, 0x06,\n    0x00, 0x02, 0x1b, 0x00, 0x03, 0x02, 0x00, 0x03,\n    0x02, 0x00, 0x03, 0x1b, 0x00, 0x04, 0x1b, 0x00,\n    0x1b, 0x02, 0x00, 0x1b, 0x03, 0x00, 0x1b, 0x04,\n    0x02, 0x1b, 0x03, 0x02, 0x1b, 0x03, 0x03, 0x1b,\n    0x20, 0x03, 0x1b, 0x1f, 0x09, 0x03, 0x02, 0x09,\n    0x02, 0x03, 0x09, 0x02, 0x1f, 0x09, 0x1b, 0x03,\n    0x09, 0x1b, 0x03, 0x09, 0x1b, 0x02, 0x09, 0x1b,\n    0x1b, 0x09, 0x1b, 0x1b, 0x0b, 0x03, 0x03, 0x0b,\n    0x03, 0x03, 0x0b, 0x1b, 0x1b, 0x0a, 0x03, 0x1b,\n    0x0a, 0x03, 0x1b, 0x0a, 0x02, 0x20, 0x0a, 0x1b,\n    0x04, 0x0a, 0x1b, 0x04, 0x0a, 0x1b, 0x1b, 0x0a,\n    0x1b, 0x1b, 0x0c, 0x03, 0x1f, 0x0c, 0x04, 0x1b,\n    0x0c, 0x04, 0x1b, 0x0d, 0x1b, 0x03, 0x0d, 0x1b,\n    0x03, 0x0d, 0x1b, 0x1b, 0x0d, 0x1b, 0x20, 0x0f,\n    0x02, 0x1b, 0x0f, 0x1b, 0x1b, 0x0f, 0x1b, 0x1b,\n    0x0f, 0x1b, 0x1f, 0x10, 0x1b, 0x1b, 0x10, 0x1b,\n    0x20, 0x10, 0x1b, 0x1f, 0x17, 0x04, 0x1b, 0x17,\n    0x04, 0x1b, 0x18, 0x1b, 0x03, 0x18, 0x1b, 0x1b,\n    0x1a, 0x03, 0x1b, 0x1a, 0x03, 0x20, 0x1a, 0x03,\n    0x1f, 0x1a, 0x02, 0x02, 0x1a, 0x02, 0x02, 0x1a,\n    0x04, 0x1b, 0x1a, 0x04, 0x1b, 0x1a, 0x1b, 0x03,\n    0x1a, 0x1b, 0x03, 0x1b, 0x03, 0x02, 0x1b, 0x03,\n    0x1b, 0x1b, 0x03, 0x20, 0x1b, 0x02, 0x03, 0x1b,\n    0x02, 0x1b, 0x1b, 0x04, 0x02, 0x1b, 0x04, 0x1b,\n    0x28, 0x06, 0x1d, 0x04, 0x06, 0x1f, 0x1d, 0x04,\n    0x1f, 0x1d, 0x1d, 0x1e, 0x05, 0x1d, 0x1e, 0x05,\n    0x21, 0x1e, 0x04, 0x1d, 0x1e, 0x04, 0x1d, 0x1e,\n    0x04, 0x21, 0x1e, 0x1d, 0x22, 0x1e, 0x1d, 0x21,\n    0x22, 0x1d, 0x1d, 0x22, 0x1d, 0x1d, 0x00, 0x06,\n    0x22, 0x02, 0x04, 0x22, 0x02, 0x04, 0x21, 0x02,\n    0x06, 0x22, 0x02, 0x06, 0x21, 0x02, 0x1d, 0x22,\n    0x02, 0x1d, 0x21, 0x04, 0x1d, 0x22, 0x04, 0x05,\n    0x21, 0x04, 0x1d, 0x21, 0x0b, 0x06, 0x21, 0x0d,\n    0x05, 0x22, 0x0c, 0x05, 0x22, 0x0e, 0x05, 0x22,\n    0x1c, 0x04, 0x22, 0x1c, 0x1d, 0x22, 0x22, 0x05,\n    0x22, 0x22, 0x04, 0x22, 0x22, 0x1d, 0x22, 0x1d,\n    0x1d, 0x22, 0x1a, 0x1d, 0x22, 0x1e, 0x05, 0x22,\n    0x1a, 0x1d, 0x05, 0x1c, 0x05, 0x1d, 0x11, 0x1d,\n    0x22, 0x1b, 0x1d, 0x22, 0x1e, 0x04, 0x05, 0x1d,\n    0x06, 0x22, 0x1c, 0x04, 0x1d, 0x1b, 0x1d, 0x1d,\n    0x1c, 0x04, 0x1d, 0x1e, 0x04, 0x05, 0x04, 0x05,\n    0x22, 0x05, 0x04, 0x22, 0x1d, 0x04, 0x22, 0x19,\n    0x1d, 0x22, 0x00, 0x05, 0x22, 0x1b, 0x1d, 0x1d,\n    0x11, 0x04, 0x1d, 0x0d, 0x1d, 0x1d, 0x0b, 0x06,\n    0x22, 0x1e, 0x04, 0x22, 0x35, 0x06, 0x00, 0x0f,\n    0x9d, 0x0d, 0x0f, 0x9d, 0x27, 0x06, 0x00, 0x1d,\n    0x1d, 0x20, 0x00, 0x1c, 0x01, 0x0a, 0x1e, 0x06,\n    0x1e, 0x08, 0x0e, 0x1d, 0x12, 0x1e, 0x0a, 0x0c,\n    0x21, 0x1d, 0x12, 0x1d, 0x23, 0x20, 0x21, 0x0c,\n    0x1d, 0x1e, 0x35, 0x06, 0x00, 0x0f, 0x14, 0x27,\n    0x06, 0x0e, 0x1d, 0x22, 0xff, 0x00, 0x1d, 0x1d,\n    0x20, 0xff, 0x12, 0x1d, 0x23, 0x20, 0xff, 0x21,\n    0x0c, 0x1d, 0x1e, 0x27, 0x06, 0x05, 0x1d, 0xff,\n    0x05, 0x1d, 0x00, 0x1d, 0x20, 0x27, 0x06, 0x0a,\n    0xa5, 0x00, 0x1d, 0x2c, 0x00, 0x01, 0x30, 0x02,\n    0x30, 0x3a, 0x00, 0x3b, 0x00, 0x21, 0x00, 0x3f,\n    0x00, 0x16, 0x30, 0x17, 0x30, 0x26, 0x20, 0x13,\n    0x20, 0x12, 0x01, 0x00, 0x5f, 0x5f, 0x28, 0x29,\n    0x7b, 0x7d, 0x08, 0x30, 0x0c, 0x0d, 0x08, 0x09,\n    0x02, 0x03, 0x00, 0x01, 0x04, 0x05, 0x06, 0x07,\n    0x5b, 0x00, 0x5d, 0x00, 0x3e, 0x20, 0x3e, 0x20,\n    0x3e, 0x20, 0x3e, 0x20, 0x5f, 0x00, 0x5f, 0x00,\n    0x5f, 0x00, 0x2c, 0x00, 0x01, 0x30, 0x2e, 0x00,\n    0x00, 0x00, 0x3b, 0x00, 0x3a, 0x00, 0x3f, 0x00,\n    0x21, 0x00, 0x14, 0x20, 0x28, 0x00, 0x29, 0x00,\n    0x7b, 0x00, 0x7d, 0x00, 0x14, 0x30, 0x15, 0x30,\n    0x23, 0x26, 0x2a, 0x2b, 0x2d, 0x3c, 0x3e, 0x3d,\n    0x00, 0x5c, 0x24, 0x25, 0x40, 0x40, 0x06, 0xff,\n    0x0b, 0x00, 0x0b, 0xff, 0x0c, 0x20, 0x00, 0x4d,\n    0x06, 0x40, 0x06, 0xff, 0x0e, 0x00, 0x0e, 0xff,\n    0x0f, 0x00, 0x0f, 0xff, 0x10, 0x00, 0x10, 0xff,\n    0x11, 0x00, 0x11, 0xff, 0x12, 0x00, 0x12, 0x21,\n    0x06, 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, 0x03,\n    0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x06, 0x06,\n    0x07, 0x07, 0x07, 0x07, 0x08, 0x08, 0x09, 0x09,\n    0x09, 0x09, 0x0a, 0x0a, 0x0a, 0x0a, 0x0b, 0x0b,\n    0x0b, 0x0b, 0x0c, 0x0c, 0x0c, 0x0c, 0x0d, 0x0d,\n    0x0d, 0x0d, 0x0e, 0x0e, 0x0f, 0x0f, 0x10, 0x10,\n    0x11, 0x11, 0x12, 0x12, 0x12, 0x12, 0x13, 0x13,\n    0x13, 0x13, 0x14, 0x14, 0x14, 0x14, 0x15, 0x15,\n    0x15, 0x15, 0x16, 0x16, 0x16, 0x16, 0x17, 0x17,\n    0x17, 0x17, 0x18, 0x18, 0x18, 0x18, 0x19, 0x19,\n    0x19, 0x19, 0x20, 0x20, 0x20, 0x20, 0x21, 0x21,\n    0x21, 0x21, 0x22, 0x22, 0x22, 0x22, 0x23, 0x23,\n    0x23, 0x23, 0x24, 0x24, 0x24, 0x24, 0x25, 0x25,\n    0x25, 0x25, 0x26, 0x26, 0x26, 0x26, 0x27, 0x27,\n    0x28, 0x28, 0x29, 0x29, 0x29, 0x29, 0x22, 0x06,\n    0x22, 0x00, 0x22, 0x00, 0x22, 0x01, 0x22, 0x01,\n    0x22, 0x03, 0x22, 0x03, 0x22, 0x05, 0x22, 0x05,\n    0x21, 0x00, 0x85, 0x29, 0x01, 0x30, 0x01, 0x0b,\n    0x0c, 0x00, 0xfa, 0xf1, 0xa0, 0xa2, 0xa4, 0xa6,\n    0xa8, 0xe2, 0xe4, 0xe6, 0xc2, 0xfb, 0xa1, 0xa3,\n    0xa5, 0xa7, 0xa9, 0xaa, 0xac, 0xae, 0xb0, 0xb2,\n    0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe, 0xc0, 0xc3,\n    0xc5, 0xc7, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce,\n    0xd1, 0xd4, 0xd7, 0xda, 0xdd, 0xde, 0xdf, 0xe0,\n    0xe1, 0xe3, 0xe5, 0xe7, 0xe8, 0xe9, 0xea, 0xeb,\n    0xec, 0xee, 0xf2, 0x98, 0x99, 0x31, 0x31, 0x4f,\n    0x31, 0x55, 0x31, 0x5b, 0x31, 0x61, 0x31, 0xa2,\n    0x00, 0xa3, 0x00, 0xac, 0x00, 0xaf, 0x00, 0xa6,\n    0x00, 0xa5, 0x00, 0xa9, 0x20, 0x00, 0x00, 0x02,\n    0x25, 0x90, 0x21, 0x91, 0x21, 0x92, 0x21, 0x93,\n    0x21, 0xa0, 0x25, 0xcb, 0x25, 0x99, 0x10, 0xba,\n    0x10, 0x00, 0x00, 0x00, 0x00, 0x9b, 0x10, 0xba,\n    0x10, 0x05, 0x05, 0xa5, 0x10, 0xba, 0x10, 0x05,\n    0x31, 0x11, 0x27, 0x11, 0x32, 0x11, 0x27, 0x11,\n    0x55, 0x47, 0x13, 0x3e, 0x13, 0x47, 0x13, 0x57,\n    0x13, 0x55, 0xb9, 0x14, 0xba, 0x14, 0xb9, 0x14,\n    0xb0, 0x14, 0x00, 0x00, 0x00, 0x00, 0xb9, 0x14,\n    0xbd, 0x14, 0x55, 0x50, 0xb8, 0x15, 0xaf, 0x15,\n    0xb9, 0x15, 0xaf, 0x15, 0x55, 0x35, 0x19, 0x30,\n    0x19, 0x05, 0x57, 0xd1, 0x65, 0xd1, 0x58, 0xd1,\n    0x65, 0xd1, 0x5f, 0xd1, 0x6e, 0xd1, 0x5f, 0xd1,\n    0x6f, 0xd1, 0x5f, 0xd1, 0x70, 0xd1, 0x5f, 0xd1,\n    0x71, 0xd1, 0x5f, 0xd1, 0x72, 0xd1, 0x55, 0x55,\n    0x55, 0x05, 0xb9, 0xd1, 0x65, 0xd1, 0xba, 0xd1,\n    0x65, 0xd1, 0xbb, 0xd1, 0x6e, 0xd1, 0xbc, 0xd1,\n    0x6e, 0xd1, 0xbb, 0xd1, 0x6f, 0xd1, 0xbc, 0xd1,\n    0x6f, 0xd1, 0x55, 0x55, 0x55, 0x41, 0x00, 0x61,\n    0x00, 0x41, 0x00, 0x61, 0x00, 0x69, 0x00, 0x41,\n    0x00, 0x61, 0x00, 0x41, 0x00, 0x43, 0x44, 0x00,\n    0x00, 0x47, 0x00, 0x00, 0x4a, 0x4b, 0x00, 0x00,\n    0x4e, 0x4f, 0x50, 0x51, 0x00, 0x53, 0x54, 0x55,\n    0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63,\n    0x64, 0x00, 0x66, 0x68, 0x00, 0x70, 0x00, 0x41,\n    0x00, 0x61, 0x00, 0x41, 0x42, 0x00, 0x44, 0x45,\n    0x46, 0x47, 0x4a, 0x00, 0x53, 0x00, 0x61, 0x00,\n    0x41, 0x42, 0x00, 0x44, 0x45, 0x46, 0x47, 0x00,\n    0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x00, 0x4f, 0x53,\n    0x00, 0x61, 0x00, 0x41, 0x00, 0x61, 0x00, 0x41,\n    0x00, 0x61, 0x00, 0x41, 0x00, 0x61, 0x00, 0x41,\n    0x00, 0x61, 0x00, 0x41, 0x00, 0x61, 0x00, 0x41,\n    0x00, 0x61, 0x00, 0x31, 0x01, 0x37, 0x02, 0x91,\n    0x03, 0xa3, 0x03, 0xb1, 0x03, 0xd1, 0x03, 0x24,\n    0x00, 0x1f, 0x04, 0x20, 0x05, 0x91, 0x03, 0xa3,\n    0x03, 0xb1, 0x03, 0xd1, 0x03, 0x24, 0x00, 0x1f,\n    0x04, 0x20, 0x05, 0x91, 0x03, 0xa3, 0x03, 0xb1,\n    0x03, 0xd1, 0x03, 0x24, 0x00, 0x1f, 0x04, 0x20,\n    0x05, 0x91, 0x03, 0xa3, 0x03, 0xb1, 0x03, 0xd1,\n    0x03, 0x24, 0x00, 0x1f, 0x04, 0x20, 0x05, 0x91,\n    0x03, 0xa3, 0x03, 0xb1, 0x03, 0xd1, 0x03, 0x24,\n    0x00, 0x1f, 0x04, 0x20, 0x05, 0x0b, 0x0c, 0x30,\n    0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30,\n    0x00, 0x27, 0x06, 0x00, 0x01, 0x05, 0x08, 0x2a,\n    0x06, 0x1e, 0x08, 0x03, 0x0d, 0x20, 0x19, 0x1a,\n    0x1b, 0x1c, 0x09, 0x0f, 0x17, 0x0b, 0x18, 0x07,\n    0x0a, 0x00, 0x01, 0x04, 0x06, 0x0c, 0x0e, 0x10,\n    0x44, 0x90, 0x77, 0x45, 0x28, 0x06, 0x2c, 0x06,\n    0x00, 0x00, 0x47, 0x06, 0x33, 0x06, 0x17, 0x10,\n    0x11, 0x12, 0x13, 0x00, 0x06, 0x0e, 0x02, 0x0f,\n    0x34, 0x06, 0x2a, 0x06, 0x2b, 0x06, 0x2e, 0x06,\n    0x00, 0x00, 0x36, 0x06, 0x00, 0x00, 0x3a, 0x06,\n    0x2d, 0x06, 0x00, 0x00, 0x4a, 0x06, 0x00, 0x00,\n    0x44, 0x06, 0x00, 0x00, 0x46, 0x06, 0x33, 0x06,\n    0x39, 0x06, 0x00, 0x00, 0x35, 0x06, 0x42, 0x06,\n    0x00, 0x00, 0x34, 0x06, 0x00, 0x00, 0x00, 0x00,\n    0x2e, 0x06, 0x00, 0x00, 0x36, 0x06, 0x00, 0x00,\n    0x3a, 0x06, 0x00, 0x00, 0xba, 0x06, 0x00, 0x00,\n    0x6f, 0x06, 0x00, 0x00, 0x28, 0x06, 0x2c, 0x06,\n    0x00, 0x00, 0x47, 0x06, 0x00, 0x00, 0x00, 0x00,\n    0x2d, 0x06, 0x37, 0x06, 0x4a, 0x06, 0x43, 0x06,\n    0x00, 0x00, 0x45, 0x06, 0x46, 0x06, 0x33, 0x06,\n    0x39, 0x06, 0x41, 0x06, 0x35, 0x06, 0x42, 0x06,\n    0x00, 0x00, 0x34, 0x06, 0x2a, 0x06, 0x2b, 0x06,\n    0x2e, 0x06, 0x00, 0x00, 0x36, 0x06, 0x38, 0x06,\n    0x3a, 0x06, 0x6e, 0x06, 0x00, 0x00, 0xa1, 0x06,\n    0x27, 0x06, 0x00, 0x01, 0x05, 0x08, 0x20, 0x21,\n    0x0b, 0x06, 0x10, 0x23, 0x2a, 0x06, 0x1a, 0x1b,\n    0x1c, 0x09, 0x0f, 0x17, 0x0b, 0x18, 0x07, 0x0a,\n    0x00, 0x01, 0x04, 0x06, 0x0c, 0x0e, 0x10, 0x28,\n    0x06, 0x2c, 0x06, 0x2f, 0x06, 0x00, 0x00, 0x48,\n    0x06, 0x32, 0x06, 0x2d, 0x06, 0x37, 0x06, 0x4a,\n    0x06, 0x2a, 0x06, 0x1a, 0x1b, 0x1c, 0x09, 0x0f,\n    0x17, 0x0b, 0x18, 0x07, 0x0a, 0x00, 0x01, 0x04,\n    0x06, 0x0c, 0x0e, 0x10, 0x30, 0x2e, 0x30, 0x00,\n    0x2c, 0x00, 0x28, 0x00, 0x41, 0x00, 0x29, 0x00,\n    0x14, 0x30, 0x53, 0x00, 0x15, 0x30, 0x43, 0x52,\n    0x43, 0x44, 0x57, 0x5a, 0x41, 0x00, 0x48, 0x56,\n    0x4d, 0x56, 0x53, 0x44, 0x53, 0x53, 0x50, 0x50,\n    0x56, 0x57, 0x43, 0x4d, 0x43, 0x4d, 0x44, 0x4d,\n    0x52, 0x44, 0x4a, 0x4b, 0x30, 0x30, 0x00, 0x68,\n    0x68, 0x4b, 0x62, 0x57, 0x5b, 0xcc, 0x53, 0xc7,\n    0x30, 0x8c, 0x4e, 0x1a, 0x59, 0xe3, 0x89, 0x29,\n    0x59, 0xa4, 0x4e, 0x20, 0x66, 0x21, 0x71, 0x99,\n    0x65, 0x4d, 0x52, 0x8c, 0x5f, 0x8d, 0x51, 0xb0,\n    0x65, 0x1d, 0x52, 0x42, 0x7d, 0x1f, 0x75, 0xa9,\n    0x8c, 0xf0, 0x58, 0x39, 0x54, 0x14, 0x6f, 0x95,\n    0x62, 0x55, 0x63, 0x00, 0x4e, 0x09, 0x4e, 0x4a,\n    0x90, 0xe6, 0x5d, 0x2d, 0x4e, 0xf3, 0x53, 0x07,\n    0x63, 0x70, 0x8d, 0x53, 0x62, 0x81, 0x79, 0x7a,\n    0x7a, 0x08, 0x54, 0x80, 0x6e, 0x09, 0x67, 0x08,\n    0x67, 0x33, 0x75, 0x72, 0x52, 0xb6, 0x55, 0x4d,\n    0x91, 0x14, 0x30, 0x15, 0x30, 0x2c, 0x67, 0x09,\n    0x4e, 0x8c, 0x4e, 0x89, 0x5b, 0xb9, 0x70, 0x53,\n    0x62, 0xd7, 0x76, 0xdd, 0x52, 0x57, 0x65, 0x97,\n    0x5f, 0xef, 0x53, 0x30, 0x00, 0x38, 0x4e, 0x05,\n    0x00, 0x09, 0x22, 0x01, 0x60, 0x4f, 0xae, 0x4f,\n    0xbb, 0x4f, 0x02, 0x50, 0x7a, 0x50, 0x99, 0x50,\n    0xe7, 0x50, 0xcf, 0x50, 0x9e, 0x34, 0x3a, 0x06,\n    0x4d, 0x51, 0x54, 0x51, 0x64, 0x51, 0x77, 0x51,\n    0x1c, 0x05, 0xb9, 0x34, 0x67, 0x51, 0x8d, 0x51,\n    0x4b, 0x05, 0x97, 0x51, 0xa4, 0x51, 0xcc, 0x4e,\n    0xac, 0x51, 0xb5, 0x51, 0xdf, 0x91, 0xf5, 0x51,\n    0x03, 0x52, 0xdf, 0x34, 0x3b, 0x52, 0x46, 0x52,\n    0x72, 0x52, 0x77, 0x52, 0x15, 0x35, 0x02, 0x00,\n    0x20, 0x80, 0x80, 0x00, 0x08, 0x00, 0x00, 0xc7,\n    0x52, 0x00, 0x02, 0x1d, 0x33, 0x3e, 0x3f, 0x50,\n    0x82, 0x8a, 0x93, 0xac, 0xb6, 0xb8, 0xb8, 0xb8,\n    0x2c, 0x0a, 0x70, 0x70, 0xca, 0x53, 0xdf, 0x53,\n    0x63, 0x0b, 0xeb, 0x53, 0xf1, 0x53, 0x06, 0x54,\n    0x9e, 0x54, 0x38, 0x54, 0x48, 0x54, 0x68, 0x54,\n    0xa2, 0x54, 0xf6, 0x54, 0x10, 0x55, 0x53, 0x55,\n    0x63, 0x55, 0x84, 0x55, 0x84, 0x55, 0x99, 0x55,\n    0xab, 0x55, 0xb3, 0x55, 0xc2, 0x55, 0x16, 0x57,\n    0x06, 0x56, 0x17, 0x57, 0x51, 0x56, 0x74, 0x56,\n    0x07, 0x52, 0xee, 0x58, 0xce, 0x57, 0xf4, 0x57,\n    0x0d, 0x58, 0x8b, 0x57, 0x32, 0x58, 0x31, 0x58,\n    0xac, 0x58, 0xe4, 0x14, 0xf2, 0x58, 0xf7, 0x58,\n    0x06, 0x59, 0x1a, 0x59, 0x22, 0x59, 0x62, 0x59,\n    0xa8, 0x16, 0xea, 0x16, 0xec, 0x59, 0x1b, 0x5a,\n    0x27, 0x5a, 0xd8, 0x59, 0x66, 0x5a, 0xee, 0x36,\n    0xfc, 0x36, 0x08, 0x5b, 0x3e, 0x5b, 0x3e, 0x5b,\n    0xc8, 0x19, 0xc3, 0x5b, 0xd8, 0x5b, 0xe7, 0x5b,\n    0xf3, 0x5b, 0x18, 0x1b, 0xff, 0x5b, 0x06, 0x5c,\n    0x53, 0x5f, 0x22, 0x5c, 0x81, 0x37, 0x60, 0x5c,\n    0x6e, 0x5c, 0xc0, 0x5c, 0x8d, 0x5c, 0xe4, 0x1d,\n    0x43, 0x5d, 0xe6, 0x1d, 0x6e, 0x5d, 0x6b, 0x5d,\n    0x7c, 0x5d, 0xe1, 0x5d, 0xe2, 0x5d, 0x2f, 0x38,\n    0xfd, 0x5d, 0x28, 0x5e, 0x3d, 0x5e, 0x69, 0x5e,\n    0x62, 0x38, 0x83, 0x21, 0x7c, 0x38, 0xb0, 0x5e,\n    0xb3, 0x5e, 0xb6, 0x5e, 0xca, 0x5e, 0x92, 0xa3,\n    0xfe, 0x5e, 0x31, 0x23, 0x31, 0x23, 0x01, 0x82,\n    0x22, 0x5f, 0x22, 0x5f, 0xc7, 0x38, 0xb8, 0x32,\n    0xda, 0x61, 0x62, 0x5f, 0x6b, 0x5f, 0xe3, 0x38,\n    0x9a, 0x5f, 0xcd, 0x5f, 0xd7, 0x5f, 0xf9, 0x5f,\n    0x81, 0x60, 0x3a, 0x39, 0x1c, 0x39, 0x94, 0x60,\n    0xd4, 0x26, 0xc7, 0x60, 0x02, 0x02, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0a,\n    0x00, 0x00, 0x02, 0x08, 0x00, 0x80, 0x08, 0x00,\n    0x00, 0x08, 0x80, 0x28, 0x80, 0x02, 0x00, 0x00,\n    0x02, 0x48, 0x61, 0x00, 0x04, 0x06, 0x04, 0x32,\n    0x46, 0x6a, 0x5c, 0x67, 0x96, 0xaa, 0xae, 0xc8,\n    0xd3, 0x5d, 0x62, 0x00, 0x54, 0x77, 0xf3, 0x0c,\n    0x2b, 0x3d, 0x63, 0xfc, 0x62, 0x68, 0x63, 0x83,\n    0x63, 0xe4, 0x63, 0xf1, 0x2b, 0x22, 0x64, 0xc5,\n    0x63, 0xa9, 0x63, 0x2e, 0x3a, 0x69, 0x64, 0x7e,\n    0x64, 0x9d, 0x64, 0x77, 0x64, 0x6c, 0x3a, 0x4f,\n    0x65, 0x6c, 0x65, 0x0a, 0x30, 0xe3, 0x65, 0xf8,\n    0x66, 0x49, 0x66, 0x19, 0x3b, 0x91, 0x66, 0x08,\n    0x3b, 0xe4, 0x3a, 0x92, 0x51, 0x95, 0x51, 0x00,\n    0x67, 0x9c, 0x66, 0xad, 0x80, 0xd9, 0x43, 0x17,\n    0x67, 0x1b, 0x67, 0x21, 0x67, 0x5e, 0x67, 0x53,\n    0x67, 0xc3, 0x33, 0x49, 0x3b, 0xfa, 0x67, 0x85,\n    0x67, 0x52, 0x68, 0x85, 0x68, 0x6d, 0x34, 0x8e,\n    0x68, 0x1f, 0x68, 0x14, 0x69, 0x9d, 0x3b, 0x42,\n    0x69, 0xa3, 0x69, 0xea, 0x69, 0xa8, 0x6a, 0xa3,\n    0x36, 0xdb, 0x6a, 0x18, 0x3c, 0x21, 0x6b, 0xa7,\n    0x38, 0x54, 0x6b, 0x4e, 0x3c, 0x72, 0x6b, 0x9f,\n    0x6b, 0xba, 0x6b, 0xbb, 0x6b, 0x8d, 0x3a, 0x0b,\n    0x1d, 0xfa, 0x3a, 0x4e, 0x6c, 0xbc, 0x3c, 0xbf,\n    0x6c, 0xcd, 0x6c, 0x67, 0x6c, 0x16, 0x6d, 0x3e,\n    0x6d, 0x77, 0x6d, 0x41, 0x6d, 0x69, 0x6d, 0x78,\n    0x6d, 0x85, 0x6d, 0x1e, 0x3d, 0x34, 0x6d, 0x2f,\n    0x6e, 0x6e, 0x6e, 0x33, 0x3d, 0xcb, 0x6e, 0xc7,\n    0x6e, 0xd1, 0x3e, 0xf9, 0x6d, 0x6e, 0x6f, 0x5e,\n    0x3f, 0x8e, 0x3f, 0xc6, 0x6f, 0x39, 0x70, 0x1e,\n    0x70, 0x1b, 0x70, 0x96, 0x3d, 0x4a, 0x70, 0x7d,\n    0x70, 0x77, 0x70, 0xad, 0x70, 0x25, 0x05, 0x45,\n    0x71, 0x63, 0x42, 0x9c, 0x71, 0xab, 0x43, 0x28,\n    0x72, 0x35, 0x72, 0x50, 0x72, 0x08, 0x46, 0x80,\n    0x72, 0x95, 0x72, 0x35, 0x47, 0x02, 0x20, 0x00,\n    0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x08, 0x80,\n    0x00, 0x00, 0x02, 0x02, 0x80, 0x8a, 0x00, 0x00,\n    0x20, 0x00, 0x08, 0x0a, 0x00, 0x80, 0x88, 0x80,\n    0x20, 0x14, 0x48, 0x7a, 0x73, 0x8b, 0x73, 0xac,\n    0x3e, 0xa5, 0x73, 0xb8, 0x3e, 0xb8, 0x3e, 0x47,\n    0x74, 0x5c, 0x74, 0x71, 0x74, 0x85, 0x74, 0xca,\n    0x74, 0x1b, 0x3f, 0x24, 0x75, 0x36, 0x4c, 0x3e,\n    0x75, 0x92, 0x4c, 0x70, 0x75, 0x9f, 0x21, 0x10,\n    0x76, 0xa1, 0x4f, 0xb8, 0x4f, 0x44, 0x50, 0xfc,\n    0x3f, 0x08, 0x40, 0xf4, 0x76, 0xf3, 0x50, 0xf2,\n    0x50, 0x19, 0x51, 0x33, 0x51, 0x1e, 0x77, 0x1f,\n    0x77, 0x1f, 0x77, 0x4a, 0x77, 0x39, 0x40, 0x8b,\n    0x77, 0x46, 0x40, 0x96, 0x40, 0x1d, 0x54, 0x4e,\n    0x78, 0x8c, 0x78, 0xcc, 0x78, 0xe3, 0x40, 0x26,\n    0x56, 0x56, 0x79, 0x9a, 0x56, 0xc5, 0x56, 0x8f,\n    0x79, 0xeb, 0x79, 0x2f, 0x41, 0x40, 0x7a, 0x4a,\n    0x7a, 0x4f, 0x7a, 0x7c, 0x59, 0xa7, 0x5a, 0xa7,\n    0x5a, 0xee, 0x7a, 0x02, 0x42, 0xab, 0x5b, 0xc6,\n    0x7b, 0xc9, 0x7b, 0x27, 0x42, 0x80, 0x5c, 0xd2,\n    0x7c, 0xa0, 0x42, 0xe8, 0x7c, 0xe3, 0x7c, 0x00,\n    0x7d, 0x86, 0x5f, 0x63, 0x7d, 0x01, 0x43, 0xc7,\n    0x7d, 0x02, 0x7e, 0x45, 0x7e, 0x34, 0x43, 0x28,\n    0x62, 0x47, 0x62, 0x59, 0x43, 0xd9, 0x62, 0x7a,\n    0x7f, 0x3e, 0x63, 0x95, 0x7f, 0xfa, 0x7f, 0x05,\n    0x80, 0xda, 0x64, 0x23, 0x65, 0x60, 0x80, 0xa8,\n    0x65, 0x70, 0x80, 0x5f, 0x33, 0xd5, 0x43, 0xb2,\n    0x80, 0x03, 0x81, 0x0b, 0x44, 0x3e, 0x81, 0xb5,\n    0x5a, 0xa7, 0x67, 0xb5, 0x67, 0x93, 0x33, 0x9c,\n    0x33, 0x01, 0x82, 0x04, 0x82, 0x9e, 0x8f, 0x6b,\n    0x44, 0x91, 0x82, 0x8b, 0x82, 0x9d, 0x82, 0xb3,\n    0x52, 0xb1, 0x82, 0xb3, 0x82, 0xbd, 0x82, 0xe6,\n    0x82, 0x3c, 0x6b, 0xe5, 0x82, 0x1d, 0x83, 0x63,\n    0x83, 0xad, 0x83, 0x23, 0x83, 0xbd, 0x83, 0xe7,\n    0x83, 0x57, 0x84, 0x53, 0x83, 0xca, 0x83, 0xcc,\n    0x83, 0xdc, 0x83, 0x36, 0x6c, 0x6b, 0x6d, 0x02,\n    0x00, 0x00, 0x20, 0x22, 0x2a, 0xa0, 0x0a, 0x00,\n    0x20, 0x80, 0x28, 0x00, 0xa8, 0x20, 0x20, 0x00,\n    0x02, 0x80, 0x22, 0x02, 0x8a, 0x08, 0x00, 0xaa,\n    0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x28, 0xd5,\n    0x6c, 0x2b, 0x45, 0xf1, 0x84, 0xf3, 0x84, 0x16,\n    0x85, 0xca, 0x73, 0x64, 0x85, 0x2c, 0x6f, 0x5d,\n    0x45, 0x61, 0x45, 0xb1, 0x6f, 0xd2, 0x70, 0x6b,\n    0x45, 0x50, 0x86, 0x5c, 0x86, 0x67, 0x86, 0x69,\n    0x86, 0xa9, 0x86, 0x88, 0x86, 0x0e, 0x87, 0xe2,\n    0x86, 0x79, 0x87, 0x28, 0x87, 0x6b, 0x87, 0x86,\n    0x87, 0xd7, 0x45, 0xe1, 0x87, 0x01, 0x88, 0xf9,\n    0x45, 0x60, 0x88, 0x63, 0x88, 0x67, 0x76, 0xd7,\n    0x88, 0xde, 0x88, 0x35, 0x46, 0xfa, 0x88, 0xbb,\n    0x34, 0xae, 0x78, 0x66, 0x79, 0xbe, 0x46, 0xc7,\n    0x46, 0xa0, 0x8a, 0xed, 0x8a, 0x8a, 0x8b, 0x55,\n    0x8c, 0xa8, 0x7c, 0xab, 0x8c, 0xc1, 0x8c, 0x1b,\n    0x8d, 0x77, 0x8d, 0x2f, 0x7f, 0x04, 0x08, 0xcb,\n    0x8d, 0xbc, 0x8d, 0xf0, 0x8d, 0xde, 0x08, 0xd4,\n    0x8e, 0x38, 0x8f, 0xd2, 0x85, 0xed, 0x85, 0x94,\n    0x90, 0xf1, 0x90, 0x11, 0x91, 0x2e, 0x87, 0x1b,\n    0x91, 0x38, 0x92, 0xd7, 0x92, 0xd8, 0x92, 0x7c,\n    0x92, 0xf9, 0x93, 0x15, 0x94, 0xfa, 0x8b, 0x8b,\n    0x95, 0x95, 0x49, 0xb7, 0x95, 0x77, 0x8d, 0xe6,\n    0x49, 0xc3, 0x96, 0xb2, 0x5d, 0x23, 0x97, 0x45,\n    0x91, 0x1a, 0x92, 0x6e, 0x4a, 0x76, 0x4a, 0xe0,\n    0x97, 0x0a, 0x94, 0xb2, 0x4a, 0x96, 0x94, 0x0b,\n    0x98, 0x0b, 0x98, 0x29, 0x98, 0xb6, 0x95, 0xe2,\n    0x98, 0x33, 0x4b, 0x29, 0x99, 0xa7, 0x99, 0xc2,\n    0x99, 0xfe, 0x99, 0xce, 0x4b, 0x30, 0x9b, 0x12,\n    0x9b, 0x40, 0x9c, 0xfd, 0x9c, 0xce, 0x4c, 0xed,\n    0x4c, 0x67, 0x9d, 0xce, 0xa0, 0xf8, 0x4c, 0x05,\n    0xa1, 0x0e, 0xa2, 0x91, 0xa2, 0xbb, 0x9e, 0x56,\n    0x4d, 0xf9, 0x9e, 0xfe, 0x9e, 0x05, 0x9f, 0x0f,\n    0x9f, 0x16, 0x9f, 0x3b, 0x9f, 0x00, 0xa6, 0x02,\n    0x88, 0xa0, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00,\n    0x28, 0x00, 0x08, 0xa0, 0x80, 0xa0, 0x80, 0x00,\n    0x80, 0x80, 0x00, 0x0a, 0x88, 0x80, 0x00, 0x80,\n    0x00, 0x20, 0x2a, 0x00, 0x80,\n};\n\nstatic const uint16_t unicode_comp_table[945] = {\n    0x4a01, 0x49c0, 0x4a02, 0x0280, 0x0281, 0x0282, 0x0283, 0x02c0,\n    0x02c2, 0x0a00, 0x0284, 0x2442, 0x0285, 0x07c0, 0x0980, 0x0982,\n    0x2440, 0x2280, 0x02c4, 0x2282, 0x2284, 0x2286, 0x02c6, 0x02c8,\n    0x02ca, 0x02cc, 0x0287, 0x228a, 0x02ce, 0x228c, 0x2290, 0x2292,\n    0x228e, 0x0288, 0x0289, 0x028a, 0x2482, 0x0300, 0x0302, 0x0304,\n    0x028b, 0x2480, 0x0308, 0x0984, 0x0986, 0x2458, 0x0a02, 0x0306,\n    0x2298, 0x229a, 0x229e, 0x0900, 0x030a, 0x22a0, 0x030c, 0x030e,\n    0x0840, 0x0310, 0x0312, 0x22a2, 0x22a6, 0x09c0, 0x22a4, 0x22a8,\n    0x22aa, 0x028c, 0x028d, 0x028e, 0x0340, 0x0342, 0x0344, 0x0380,\n    0x028f, 0x248e, 0x07c2, 0x0988, 0x098a, 0x2490, 0x0346, 0x22ac,\n    0x0400, 0x22b0, 0x0842, 0x22b2, 0x0402, 0x22b4, 0x0440, 0x0444,\n    0x22b6, 0x0442, 0x22c2, 0x22c0, 0x22c4, 0x22c6, 0x22c8, 0x0940,\n    0x04c0, 0x0291, 0x22ca, 0x04c4, 0x22cc, 0x04c2, 0x22d0, 0x22ce,\n    0x0292, 0x0293, 0x0294, 0x0295, 0x0540, 0x0542, 0x0a08, 0x0296,\n    0x2494, 0x0544, 0x07c4, 0x098c, 0x098e, 0x06c0, 0x2492, 0x0844,\n    0x2308, 0x230a, 0x0580, 0x230c, 0x0584, 0x0990, 0x0992, 0x230e,\n    0x0582, 0x2312, 0x0586, 0x0588, 0x2314, 0x058c, 0x2316, 0x0998,\n    0x058a, 0x231e, 0x0590, 0x2320, 0x099a, 0x058e, 0x2324, 0x2322,\n    0x0299, 0x029a, 0x029b, 0x05c0, 0x05c2, 0x05c4, 0x029c, 0x24ac,\n    0x05c6, 0x05c8, 0x07c6, 0x0994, 0x0996, 0x0700, 0x24aa, 0x2326,\n    0x05ca, 0x232a, 0x2328, 0x2340, 0x2342, 0x2344, 0x2346, 0x05cc,\n    0x234a, 0x2348, 0x234c, 0x234e, 0x2350, 0x24b8, 0x029d, 0x05ce,\n    0x24be, 0x0a0c, 0x2352, 0x0600, 0x24bc, 0x24ba, 0x0640, 0x2354,\n    0x0642, 0x0644, 0x2356, 0x2358, 0x02a0, 0x02a1, 0x02a2, 0x02a3,\n    0x02c1, 0x02c3, 0x0a01, 0x02a4, 0x2443, 0x02a5, 0x07c1, 0x0981,\n    0x0983, 0x2441, 0x2281, 0x02c5, 0x2283, 0x2285, 0x2287, 0x02c7,\n    0x02c9, 0x02cb, 0x02cd, 0x02a7, 0x228b, 0x02cf, 0x228d, 0x2291,\n    0x2293, 0x228f, 0x02a8, 0x02a9, 0x02aa, 0x2483, 0x0301, 0x0303,\n    0x0305, 0x02ab, 0x2481, 0x0309, 0x0985, 0x0987, 0x2459, 0x0a03,\n    0x0307, 0x2299, 0x229b, 0x229f, 0x0901, 0x030b, 0x22a1, 0x030d,\n    0x030f, 0x0841, 0x0311, 0x0313, 0x22a3, 0x22a7, 0x09c1, 0x22a5,\n    0x22a9, 0x22ab, 0x2380, 0x02ac, 0x02ad, 0x02ae, 0x0341, 0x0343,\n    0x0345, 0x02af, 0x248f, 0x07c3, 0x0989, 0x098b, 0x2491, 0x0347,\n    0x22ad, 0x0401, 0x0884, 0x22b1, 0x0843, 0x22b3, 0x0403, 0x22b5,\n    0x0441, 0x0445, 0x22b7, 0x0443, 0x22c3, 0x22c1, 0x22c5, 0x22c7,\n    0x22c9, 0x0941, 0x04c1, 0x02b1, 0x22cb, 0x04c5, 0x22cd, 0x04c3,\n    0x22d1, 0x22cf, 0x02b2, 0x02b3, 0x02b4, 0x02b5, 0x0541, 0x0543,\n    0x0a09, 0x02b6, 0x2495, 0x0545, 0x07c5, 0x098d, 0x098f, 0x06c1,\n    0x2493, 0x0845, 0x2309, 0x230b, 0x0581, 0x230d, 0x0585, 0x0991,\n    0x0993, 0x230f, 0x0583, 0x2313, 0x0587, 0x0589, 0x2315, 0x058d,\n    0x2317, 0x0999, 0x058b, 0x231f, 0x2381, 0x0591, 0x2321, 0x099b,\n    0x058f, 0x2325, 0x2323, 0x02b9, 0x02ba, 0x02bb, 0x05c1, 0x05c3,\n    0x05c5, 0x02bc, 0x24ad, 0x05c7, 0x05c9, 0x07c7, 0x0995, 0x0997,\n    0x0701, 0x24ab, 0x2327, 0x05cb, 0x232b, 0x2329, 0x2341, 0x2343,\n    0x2345, 0x2347, 0x05cd, 0x234b, 0x2349, 0x2382, 0x234d, 0x234f,\n    0x2351, 0x24b9, 0x02bd, 0x05cf, 0x24bf, 0x0a0d, 0x2353, 0x02bf,\n    0x24bd, 0x2383, 0x24bb, 0x0641, 0x2355, 0x0643, 0x0645, 0x2357,\n    0x2359, 0x3101, 0x0c80, 0x2e00, 0x2446, 0x2444, 0x244a, 0x2448,\n    0x0800, 0x0942, 0x0944, 0x0804, 0x2288, 0x2486, 0x2484, 0x248a,\n    0x2488, 0x22ae, 0x2498, 0x2496, 0x249c, 0x249a, 0x2300, 0x0a06,\n    0x2302, 0x0a04, 0x0946, 0x07ce, 0x07ca, 0x07c8, 0x07cc, 0x2447,\n    0x2445, 0x244b, 0x2449, 0x0801, 0x0943, 0x0945, 0x0805, 0x2289,\n    0x2487, 0x2485, 0x248b, 0x2489, 0x22af, 0x2499, 0x2497, 0x249d,\n    0x249b, 0x2301, 0x0a07, 0x2303, 0x0a05, 0x0947, 0x07cf, 0x07cb,\n    0x07c9, 0x07cd, 0x2450, 0x244e, 0x2454, 0x2452, 0x2451, 0x244f,\n    0x2455, 0x2453, 0x2294, 0x2296, 0x2295, 0x2297, 0x2304, 0x2306,\n    0x2305, 0x2307, 0x2318, 0x2319, 0x231a, 0x231b, 0x232c, 0x232d,\n    0x232e, 0x232f, 0x2400, 0x24a2, 0x24a0, 0x24a6, 0x24a4, 0x24a8,\n    0x24a3, 0x24a1, 0x24a7, 0x24a5, 0x24a9, 0x24b0, 0x24ae, 0x24b4,\n    0x24b2, 0x24b6, 0x24b1, 0x24af, 0x24b5, 0x24b3, 0x24b7, 0x0882,\n    0x0880, 0x0881, 0x0802, 0x0803, 0x229c, 0x229d, 0x0a0a, 0x0a0b,\n    0x0883, 0x0b40, 0x2c8a, 0x0c81, 0x2c89, 0x2c88, 0x2540, 0x2541,\n    0x2d00, 0x2e07, 0x0d00, 0x2640, 0x2641, 0x2e80, 0x0d01, 0x26c8,\n    0x26c9, 0x2f00, 0x2f84, 0x0d02, 0x2f83, 0x2f82, 0x0d40, 0x26d8,\n    0x26d9, 0x3186, 0x0d04, 0x2740, 0x2741, 0x3100, 0x3086, 0x0d06,\n    0x3085, 0x3084, 0x0d41, 0x2840, 0x3200, 0x0d07, 0x284f, 0x2850,\n    0x3280, 0x2c84, 0x2e03, 0x2857, 0x0d42, 0x2c81, 0x2c80, 0x24c0,\n    0x24c1, 0x2c86, 0x2c83, 0x28c0, 0x0d43, 0x25c0, 0x25c1, 0x2940,\n    0x0d44, 0x26c0, 0x26c1, 0x2e05, 0x2e02, 0x29c0, 0x0d45, 0x2f05,\n    0x2f04, 0x0d80, 0x26d0, 0x26d1, 0x2f80, 0x2a40, 0x0d82, 0x26e0,\n    0x26e1, 0x3080, 0x3081, 0x2ac0, 0x0d83, 0x3004, 0x3003, 0x0d81,\n    0x27c0, 0x27c1, 0x3082, 0x2b40, 0x0d84, 0x2847, 0x2848, 0x3184,\n    0x3181, 0x2f06, 0x0d08, 0x2f81, 0x3005, 0x0d46, 0x3083, 0x3182,\n    0x0e00, 0x0e01, 0x0f40, 0x1180, 0x1182, 0x0f03, 0x0f00, 0x11c0,\n    0x0f01, 0x1140, 0x1202, 0x1204, 0x0f81, 0x1240, 0x0fc0, 0x1242,\n    0x0f80, 0x1244, 0x1284, 0x0f82, 0x1286, 0x1288, 0x128a, 0x12c0,\n    0x1282, 0x1181, 0x1183, 0x1043, 0x1040, 0x11c1, 0x1041, 0x1141,\n    0x1203, 0x1205, 0x10c1, 0x1241, 0x1000, 0x1243, 0x10c0, 0x1245,\n    0x1285, 0x10c2, 0x1287, 0x1289, 0x128b, 0x12c1, 0x1283, 0x1080,\n    0x1100, 0x1101, 0x1200, 0x1201, 0x1280, 0x1281, 0x1340, 0x1341,\n    0x1343, 0x1342, 0x1344, 0x13c2, 0x1400, 0x13c0, 0x1440, 0x1480,\n    0x14c0, 0x1540, 0x1541, 0x1740, 0x1700, 0x1741, 0x17c0, 0x1800,\n    0x1802, 0x1801, 0x1840, 0x1880, 0x1900, 0x18c0, 0x18c1, 0x1901,\n    0x1940, 0x1942, 0x1941, 0x1980, 0x19c0, 0x19c2, 0x19c1, 0x1c80,\n    0x1cc0, 0x1dc0, 0x1f80, 0x2000, 0x2002, 0x2004, 0x2006, 0x2008,\n    0x2040, 0x2080, 0x2082, 0x20c0, 0x20c1, 0x2100, 0x22b8, 0x22b9,\n    0x2310, 0x2311, 0x231c, 0x231d, 0x244c, 0x2456, 0x244d, 0x2457,\n    0x248c, 0x248d, 0x249e, 0x249f, 0x2500, 0x2502, 0x2504, 0x2bc0,\n    0x2501, 0x2503, 0x2505, 0x2bc1, 0x2bc2, 0x2bc3, 0x2bc4, 0x2bc5,\n    0x2bc6, 0x2bc7, 0x2580, 0x2582, 0x2584, 0x2bc8, 0x2581, 0x2583,\n    0x2585, 0x2bc9, 0x2bca, 0x2bcb, 0x2bcc, 0x2bcd, 0x2bce, 0x2bcf,\n    0x2600, 0x2602, 0x2601, 0x2603, 0x2680, 0x2682, 0x2681, 0x2683,\n    0x26c2, 0x26c4, 0x26c6, 0x2c00, 0x26c3, 0x26c5, 0x26c7, 0x2c01,\n    0x2c02, 0x2c03, 0x2c04, 0x2c05, 0x2c06, 0x2c07, 0x26ca, 0x26cc,\n    0x26ce, 0x2c08, 0x26cb, 0x26cd, 0x26cf, 0x2c09, 0x2c0a, 0x2c0b,\n    0x2c0c, 0x2c0d, 0x2c0e, 0x2c0f, 0x26d2, 0x26d4, 0x26d6, 0x26d3,\n    0x26d5, 0x26d7, 0x26da, 0x26dc, 0x26de, 0x26db, 0x26dd, 0x26df,\n    0x2700, 0x2702, 0x2701, 0x2703, 0x2780, 0x2782, 0x2781, 0x2783,\n    0x2800, 0x2802, 0x2804, 0x2801, 0x2803, 0x2805, 0x2842, 0x2844,\n    0x2846, 0x2849, 0x284b, 0x284d, 0x2c40, 0x284a, 0x284c, 0x284e,\n    0x2c41, 0x2c42, 0x2c43, 0x2c44, 0x2c45, 0x2c46, 0x2c47, 0x2851,\n    0x2853, 0x2855, 0x2c48, 0x2852, 0x2854, 0x2856, 0x2c49, 0x2c4a,\n    0x2c4b, 0x2c4c, 0x2c4d, 0x2c4e, 0x2c4f, 0x2c82, 0x2e01, 0x3180,\n    0x2c87, 0x2f01, 0x2f02, 0x2f03, 0x2e06, 0x3185, 0x3000, 0x3001,\n    0x3002, 0x4640, 0x4641, 0x4680, 0x46c0, 0x46c2, 0x46c1, 0x4700,\n    0x4740, 0x4780, 0x47c0, 0x47c2, 0x4900, 0x4940, 0x4980, 0x4982,\n    0x4a00, 0x49c2, 0x4a03, 0x4a04, 0x4a40, 0x4a41, 0x4a80, 0x4a81,\n    0x4ac0, 0x4ac1, 0x4bc0, 0x4bc1, 0x4b00, 0x4b01, 0x4b40, 0x4b41,\n    0x4bc2, 0x4bc3, 0x4b80, 0x4b81, 0x4b82, 0x4b83, 0x4c00, 0x4c01,\n    0x4c02, 0x4c03, 0x5600, 0x5440, 0x5442, 0x5444, 0x5446, 0x5448,\n    0x544a, 0x544c, 0x544e, 0x5450, 0x5452, 0x5454, 0x5456, 0x5480,\n    0x5482, 0x5484, 0x54c0, 0x54c1, 0x5500, 0x5501, 0x5540, 0x5541,\n    0x5580, 0x5581, 0x55c0, 0x55c1, 0x5680, 0x58c0, 0x5700, 0x5702,\n    0x5704, 0x5706, 0x5708, 0x570a, 0x570c, 0x570e, 0x5710, 0x5712,\n    0x5714, 0x5716, 0x5740, 0x5742, 0x5744, 0x5780, 0x5781, 0x57c0,\n    0x57c1, 0x5800, 0x5801, 0x5840, 0x5841, 0x5880, 0x5881, 0x5900,\n    0x5901, 0x5902, 0x5903, 0x5940, 0x8e80, 0x8e82, 0x8ec0, 0x8f00,\n    0x8f01, 0x8f40, 0x8f41, 0x8f81, 0x8f80, 0x8f83, 0x8fc0, 0x8fc1,\n    0x9000,\n};\n\ntypedef enum {\n    UNICODE_GC_Cn,\n    UNICODE_GC_Lu,\n    UNICODE_GC_Ll,\n    UNICODE_GC_Lt,\n    UNICODE_GC_Lm,\n    UNICODE_GC_Lo,\n    UNICODE_GC_Mn,\n    UNICODE_GC_Mc,\n    UNICODE_GC_Me,\n    UNICODE_GC_Nd,\n    UNICODE_GC_Nl,\n    UNICODE_GC_No,\n    UNICODE_GC_Sm,\n    UNICODE_GC_Sc,\n    UNICODE_GC_Sk,\n    UNICODE_GC_So,\n    UNICODE_GC_Pc,\n    UNICODE_GC_Pd,\n    UNICODE_GC_Ps,\n    UNICODE_GC_Pe,\n    UNICODE_GC_Pi,\n    UNICODE_GC_Pf,\n    UNICODE_GC_Po,\n    UNICODE_GC_Zs,\n    UNICODE_GC_Zl,\n    UNICODE_GC_Zp,\n    UNICODE_GC_Cc,\n    UNICODE_GC_Cf,\n    UNICODE_GC_Cs,\n    UNICODE_GC_Co,\n    UNICODE_GC_LC,\n    UNICODE_GC_L,\n    UNICODE_GC_M,\n    UNICODE_GC_N,\n    UNICODE_GC_S,\n    UNICODE_GC_P,\n    UNICODE_GC_Z,\n    UNICODE_GC_C,\n    UNICODE_GC_COUNT,\n} UnicodeGCEnum;\n\nstatic const char unicode_gc_name_table[] =\n    \"Cn,Unassigned\"            \"\\0\"\n    \"Lu,Uppercase_Letter\"      \"\\0\"\n    \"Ll,Lowercase_Letter\"      \"\\0\"\n    \"Lt,Titlecase_Letter\"      \"\\0\"\n    \"Lm,Modifier_Letter\"       \"\\0\"\n    \"Lo,Other_Letter\"          \"\\0\"\n    \"Mn,Nonspacing_Mark\"       \"\\0\"\n    \"Mc,Spacing_Mark\"          \"\\0\"\n    \"Me,Enclosing_Mark\"        \"\\0\"\n    \"Nd,Decimal_Number,digit\"  \"\\0\"\n    \"Nl,Letter_Number\"         \"\\0\"\n    \"No,Other_Number\"          \"\\0\"\n    \"Sm,Math_Symbol\"           \"\\0\"\n    \"Sc,Currency_Symbol\"       \"\\0\"\n    \"Sk,Modifier_Symbol\"       \"\\0\"\n    \"So,Other_Symbol\"          \"\\0\"\n    \"Pc,Connector_Punctuation\" \"\\0\"\n    \"Pd,Dash_Punctuation\"      \"\\0\"\n    \"Ps,Open_Punctuation\"      \"\\0\"\n    \"Pe,Close_Punctuation\"     \"\\0\"\n    \"Pi,Initial_Punctuation\"   \"\\0\"\n    \"Pf,Final_Punctuation\"     \"\\0\"\n    \"Po,Other_Punctuation\"     \"\\0\"\n    \"Zs,Space_Separator\"       \"\\0\"\n    \"Zl,Line_Separator\"        \"\\0\"\n    \"Zp,Paragraph_Separator\"   \"\\0\"\n    \"Cc,Control,cntrl\"         \"\\0\"\n    \"Cf,Format\"                \"\\0\"\n    \"Cs,Surrogate\"             \"\\0\"\n    \"Co,Private_Use\"           \"\\0\"\n    \"LC,Cased_Letter\"          \"\\0\"\n    \"L,Letter\"                 \"\\0\"\n    \"M,Mark,Combining_Mark\"    \"\\0\"\n    \"N,Number\"                 \"\\0\"\n    \"S,Symbol\"                 \"\\0\"\n    \"P,Punctuation,punct\"      \"\\0\"\n    \"Z,Separator\"              \"\\0\"\n    \"C,Other\"                  \"\\0\"\n;\n\nstatic const uint8_t unicode_gc_table[3790] = {\n    0xfa, 0x18, 0x17, 0x56, 0x0d, 0x56, 0x12, 0x13,\n    0x16, 0x0c, 0x16, 0x11, 0x36, 0xe9, 0x02, 0x36,\n    0x4c, 0x36, 0xe1, 0x12, 0x12, 0x16, 0x13, 0x0e,\n    0x10, 0x0e, 0xe2, 0x12, 0x12, 0x0c, 0x13, 0x0c,\n    0xfa, 0x19, 0x17, 0x16, 0x6d, 0x0f, 0x16, 0x0e,\n    0x0f, 0x05, 0x14, 0x0c, 0x1b, 0x0f, 0x0e, 0x0f,\n    0x0c, 0x2b, 0x0e, 0x02, 0x36, 0x0e, 0x0b, 0x05,\n    0x15, 0x4b, 0x16, 0xe1, 0x0f, 0x0c, 0xc1, 0xe2,\n    0x10, 0x0c, 0xe2, 0x00, 0xff, 0x30, 0x02, 0xff,\n    0x08, 0x02, 0xff, 0x27, 0xbf, 0x22, 0x21, 0x02,\n    0x5f, 0x5f, 0x21, 0x22, 0x61, 0x02, 0x21, 0x02,\n    0x41, 0x42, 0x21, 0x02, 0x21, 0x02, 0x9f, 0x7f,\n    0x02, 0x5f, 0x5f, 0x21, 0x02, 0x5f, 0x3f, 0x02,\n    0x05, 0x3f, 0x22, 0x65, 0x01, 0x03, 0x02, 0x01,\n    0x03, 0x02, 0x01, 0x03, 0x02, 0xff, 0x08, 0x02,\n    0xff, 0x0a, 0x02, 0x01, 0x03, 0x02, 0x5f, 0x21,\n    0x02, 0xff, 0x32, 0xa2, 0x21, 0x02, 0x21, 0x22,\n    0x5f, 0x41, 0x02, 0xff, 0x00, 0xe2, 0x3c, 0x05,\n    0xe2, 0x13, 0xe4, 0x0a, 0x6e, 0xe4, 0x04, 0xee,\n    0x06, 0x84, 0xce, 0x04, 0x0e, 0x04, 0xee, 0x09,\n    0xe6, 0x68, 0x7f, 0x04, 0x0e, 0x3f, 0x20, 0x04,\n    0x42, 0x16, 0x01, 0x60, 0x2e, 0x01, 0x16, 0x41,\n    0x00, 0x01, 0x00, 0x21, 0x02, 0xe1, 0x09, 0x00,\n    0xe1, 0x01, 0xe2, 0x1b, 0x3f, 0x02, 0x41, 0x42,\n    0xff, 0x10, 0x62, 0x3f, 0x0c, 0x5f, 0x3f, 0x02,\n    0xe1, 0x2b, 0xe2, 0x28, 0xff, 0x1a, 0x0f, 0x86,\n    0x28, 0xff, 0x2f, 0xff, 0x06, 0x02, 0xff, 0x58,\n    0x00, 0xe1, 0x1e, 0x20, 0x04, 0xb6, 0xe2, 0x21,\n    0x16, 0x11, 0x20, 0x2f, 0x0d, 0x00, 0xe6, 0x25,\n    0x11, 0x06, 0x16, 0x26, 0x16, 0x26, 0x16, 0x06,\n    0xe0, 0x00, 0xe5, 0x13, 0x60, 0x65, 0x36, 0xe0,\n    0x03, 0xbb, 0x4c, 0x36, 0x0d, 0x36, 0x2f, 0xe6,\n    0x03, 0x16, 0x1b, 0x00, 0x36, 0xe5, 0x18, 0x04,\n    0xe5, 0x02, 0xe6, 0x0d, 0xe9, 0x02, 0x76, 0x25,\n    0x06, 0xe5, 0x5b, 0x16, 0x05, 0xc6, 0x1b, 0x0f,\n    0xa6, 0x24, 0x26, 0x0f, 0x66, 0x25, 0xe9, 0x02,\n    0x45, 0x2f, 0x05, 0xf6, 0x06, 0x00, 0x1b, 0x05,\n    0x06, 0xe5, 0x16, 0xe6, 0x13, 0x20, 0xe5, 0x51,\n    0xe6, 0x03, 0x05, 0xe0, 0x06, 0xe9, 0x02, 0xe5,\n    0x19, 0xe6, 0x01, 0x24, 0x0f, 0x56, 0x04, 0x20,\n    0x06, 0x2d, 0xe5, 0x0e, 0x66, 0x04, 0xe6, 0x01,\n    0x04, 0x46, 0x04, 0x86, 0x20, 0xf6, 0x07, 0x00,\n    0xe5, 0x11, 0x46, 0x20, 0x16, 0x00, 0xe5, 0x03,\n    0xe0, 0x2d, 0xe5, 0x0d, 0x00, 0xe5, 0x0a, 0xe0,\n    0x03, 0xe6, 0x07, 0x1b, 0xe6, 0x18, 0x07, 0xe5,\n    0x2e, 0x06, 0x07, 0x06, 0x05, 0x47, 0xe6, 0x00,\n    0x67, 0x06, 0x27, 0x05, 0xc6, 0xe5, 0x02, 0x26,\n    0x36, 0xe9, 0x02, 0x16, 0x04, 0xe5, 0x07, 0x06,\n    0x27, 0x00, 0xe5, 0x00, 0x20, 0x25, 0x20, 0xe5,\n    0x0e, 0x00, 0xc5, 0x00, 0x05, 0x40, 0x65, 0x20,\n    0x06, 0x05, 0x47, 0x66, 0x20, 0x27, 0x20, 0x27,\n    0x06, 0x05, 0xe0, 0x00, 0x07, 0x60, 0x25, 0x00,\n    0x45, 0x26, 0x20, 0xe9, 0x02, 0x25, 0x2d, 0xab,\n    0x0f, 0x0d, 0x05, 0x16, 0x06, 0x20, 0x26, 0x07,\n    0x00, 0xa5, 0x60, 0x25, 0x20, 0xe5, 0x0e, 0x00,\n    0xc5, 0x00, 0x25, 0x00, 0x25, 0x00, 0x25, 0x20,\n    0x06, 0x00, 0x47, 0x26, 0x60, 0x26, 0x20, 0x46,\n    0x40, 0x06, 0xc0, 0x65, 0x00, 0x05, 0xc0, 0xe9,\n    0x02, 0x26, 0x45, 0x06, 0x16, 0xe0, 0x02, 0x26,\n    0x07, 0x00, 0xe5, 0x01, 0x00, 0x45, 0x00, 0xe5,\n    0x0e, 0x00, 0xc5, 0x00, 0x25, 0x00, 0x85, 0x20,\n    0x06, 0x05, 0x47, 0x86, 0x00, 0x26, 0x07, 0x00,\n    0x27, 0x06, 0x20, 0x05, 0xe0, 0x07, 0x25, 0x26,\n    0x20, 0xe9, 0x02, 0x16, 0x0d, 0xc0, 0x05, 0xa6,\n    0x00, 0x06, 0x27, 0x00, 0xe5, 0x00, 0x20, 0x25,\n    0x20, 0xe5, 0x0e, 0x00, 0xc5, 0x00, 0x25, 0x00,\n    0x85, 0x20, 0x06, 0x05, 0x07, 0x06, 0x07, 0x66,\n    0x20, 0x27, 0x20, 0x27, 0x06, 0xc0, 0x26, 0x07,\n    0x60, 0x25, 0x00, 0x45, 0x26, 0x20, 0xe9, 0x02,\n    0x0f, 0x05, 0xab, 0xe0, 0x02, 0x06, 0x05, 0x00,\n    0xa5, 0x40, 0x45, 0x00, 0x65, 0x40, 0x25, 0x00,\n    0x05, 0x00, 0x25, 0x40, 0x25, 0x40, 0x45, 0x40,\n    0xe5, 0x04, 0x60, 0x27, 0x06, 0x27, 0x40, 0x47,\n    0x00, 0x47, 0x06, 0x20, 0x05, 0xa0, 0x07, 0xe0,\n    0x06, 0xe9, 0x02, 0x4b, 0xaf, 0x0d, 0x0f, 0x80,\n    0x06, 0x47, 0x06, 0xe5, 0x00, 0x00, 0x45, 0x00,\n    0xe5, 0x0f, 0x00, 0xe5, 0x08, 0x40, 0x05, 0x46,\n    0x67, 0x00, 0x46, 0x00, 0x66, 0xc0, 0x26, 0x00,\n    0x45, 0x80, 0x25, 0x26, 0x20, 0xe9, 0x02, 0xc0,\n    0x16, 0xcb, 0x0f, 0x05, 0x06, 0x27, 0x16, 0xe5,\n    0x00, 0x00, 0x45, 0x00, 0xe5, 0x0f, 0x00, 0xe5,\n    0x02, 0x00, 0x85, 0x20, 0x06, 0x05, 0x07, 0x06,\n    0x87, 0x00, 0x06, 0x27, 0x00, 0x27, 0x26, 0xc0,\n    0x27, 0xc0, 0x05, 0x00, 0x25, 0x26, 0x20, 0xe9,\n    0x02, 0x00, 0x25, 0xe0, 0x05, 0x26, 0x27, 0xe5,\n    0x01, 0x00, 0x45, 0x00, 0xe5, 0x21, 0x26, 0x05,\n    0x47, 0x66, 0x00, 0x47, 0x00, 0x47, 0x06, 0x05,\n    0x0f, 0x60, 0x45, 0x07, 0xcb, 0x45, 0x26, 0x20,\n    0xe9, 0x02, 0xeb, 0x01, 0x0f, 0xa5, 0x00, 0x06,\n    0x27, 0x00, 0xe5, 0x0a, 0x40, 0xe5, 0x10, 0x00,\n    0xe5, 0x01, 0x00, 0x05, 0x20, 0xc5, 0x40, 0x06,\n    0x60, 0x47, 0x46, 0x00, 0x06, 0x00, 0xe7, 0x00,\n    0xa0, 0xe9, 0x02, 0x20, 0x27, 0x16, 0xe0, 0x04,\n    0xe5, 0x28, 0x06, 0x25, 0xc6, 0x60, 0x0d, 0xa5,\n    0x04, 0xe6, 0x00, 0x16, 0xe9, 0x02, 0x36, 0xe0,\n    0x1d, 0x25, 0x00, 0x05, 0x00, 0x85, 0x00, 0xe5,\n    0x10, 0x00, 0x05, 0x00, 0xe5, 0x02, 0x06, 0x25,\n    0xe6, 0x01, 0x05, 0x20, 0x85, 0x00, 0x04, 0x00,\n    0xa6, 0x20, 0xe9, 0x02, 0x20, 0x65, 0xe0, 0x18,\n    0x05, 0x4f, 0xf6, 0x07, 0x0f, 0x16, 0x4f, 0x26,\n    0xaf, 0xe9, 0x02, 0xeb, 0x02, 0x0f, 0x06, 0x0f,\n    0x06, 0x0f, 0x06, 0x12, 0x13, 0x12, 0x13, 0x27,\n    0xe5, 0x00, 0x00, 0xe5, 0x1c, 0x60, 0xe6, 0x06,\n    0x07, 0x86, 0x16, 0x26, 0x85, 0xe6, 0x03, 0x00,\n    0xe6, 0x1c, 0x00, 0xef, 0x00, 0x06, 0xaf, 0x00,\n    0x2f, 0x96, 0x6f, 0x36, 0xe0, 0x1d, 0xe5, 0x23,\n    0x27, 0x66, 0x07, 0xa6, 0x07, 0x26, 0x27, 0x26,\n    0x05, 0xe9, 0x02, 0xb6, 0xa5, 0x27, 0x26, 0x65,\n    0x46, 0x05, 0x47, 0x25, 0xc7, 0x45, 0x66, 0xe5,\n    0x05, 0x06, 0x27, 0x26, 0xa7, 0x06, 0x05, 0x07,\n    0xe9, 0x02, 0x47, 0x06, 0x2f, 0xe1, 0x1e, 0x00,\n    0x01, 0x80, 0x01, 0x20, 0xe2, 0x23, 0x16, 0x04,\n    0x42, 0xe5, 0x80, 0xc1, 0x00, 0x65, 0x20, 0xc5,\n    0x00, 0x05, 0x00, 0x65, 0x20, 0xe5, 0x21, 0x00,\n    0x65, 0x20, 0xe5, 0x19, 0x00, 0x65, 0x20, 0xc5,\n    0x00, 0x05, 0x00, 0x65, 0x20, 0xe5, 0x07, 0x00,\n    0xe5, 0x31, 0x00, 0x65, 0x20, 0xe5, 0x3b, 0x20,\n    0x46, 0xf6, 0x01, 0xeb, 0x0c, 0x40, 0xe5, 0x08,\n    0xef, 0x02, 0xa0, 0xe1, 0x4e, 0x20, 0xa2, 0x20,\n    0x11, 0xe5, 0x81, 0xe4, 0x0f, 0x16, 0xe5, 0x09,\n    0x17, 0xe5, 0x12, 0x12, 0x13, 0x40, 0xe5, 0x43,\n    0x56, 0x4a, 0xe5, 0x00, 0xc0, 0xe5, 0x05, 0x00,\n    0x65, 0x46, 0xe0, 0x03, 0xe5, 0x0a, 0x46, 0x36,\n    0xe0, 0x01, 0xe5, 0x0a, 0x26, 0xe0, 0x04, 0xe5,\n    0x05, 0x00, 0x45, 0x00, 0x26, 0xe0, 0x04, 0xe5,\n    0x2c, 0x26, 0x07, 0xc6, 0xe7, 0x00, 0x06, 0x27,\n    0xe6, 0x03, 0x56, 0x04, 0x56, 0x0d, 0x05, 0x06,\n    0x20, 0xe9, 0x02, 0xa0, 0xeb, 0x02, 0xa0, 0xb6,\n    0x11, 0x76, 0x46, 0x1b, 0x00, 0xe9, 0x02, 0xa0,\n    0xe5, 0x1b, 0x04, 0xe5, 0x2d, 0xc0, 0x85, 0x26,\n    0xe5, 0x1a, 0x06, 0x05, 0x80, 0xe5, 0x3e, 0xe0,\n    0x02, 0xe5, 0x17, 0x00, 0x46, 0x67, 0x26, 0x47,\n    0x60, 0x27, 0x06, 0xa7, 0x46, 0x60, 0x0f, 0x40,\n    0x36, 0xe9, 0x02, 0xe5, 0x16, 0x20, 0x85, 0xe0,\n    0x03, 0xe5, 0x24, 0x60, 0xe5, 0x12, 0xa0, 0xe9,\n    0x02, 0x0b, 0x40, 0xef, 0x1a, 0xe5, 0x0f, 0x26,\n    0x27, 0x06, 0x20, 0x36, 0xe5, 0x2d, 0x07, 0x06,\n    0x07, 0xc6, 0x00, 0x06, 0x07, 0x06, 0x27, 0xe6,\n    0x00, 0xa7, 0xe6, 0x02, 0x20, 0x06, 0xe9, 0x02,\n    0xa0, 0xe9, 0x02, 0xa0, 0xd6, 0x04, 0xb6, 0x20,\n    0xe6, 0x06, 0x08, 0x26, 0xe0, 0x37, 0x66, 0x07,\n    0xe5, 0x27, 0x06, 0x07, 0x86, 0x07, 0x06, 0x87,\n    0x06, 0x27, 0xc5, 0x60, 0xe9, 0x02, 0xd6, 0xef,\n    0x02, 0xe6, 0x01, 0xef, 0x01, 0x40, 0x26, 0x07,\n    0xe5, 0x16, 0x07, 0x66, 0x27, 0x26, 0x07, 0x46,\n    0x25, 0xe9, 0x02, 0xe5, 0x24, 0x06, 0x07, 0x26,\n    0x47, 0x06, 0x07, 0x46, 0x27, 0xe0, 0x00, 0x76,\n    0xe5, 0x1c, 0xe7, 0x00, 0xe6, 0x00, 0x27, 0x26,\n    0x40, 0x96, 0xe9, 0x02, 0x40, 0x45, 0xe9, 0x02,\n    0xe5, 0x16, 0xa4, 0x36, 0xe2, 0x01, 0xc0, 0xe1,\n    0x23, 0x20, 0x41, 0xf6, 0x00, 0xe0, 0x00, 0x46,\n    0x16, 0xe6, 0x05, 0x07, 0xc6, 0x65, 0x06, 0xa5,\n    0x06, 0x25, 0x07, 0x26, 0x05, 0x80, 0xe2, 0x24,\n    0xe4, 0x37, 0xe2, 0x05, 0x04, 0xe2, 0x1a, 0xe4,\n    0x1d, 0xe6, 0x32, 0x00, 0x86, 0xff, 0x80, 0x0e,\n    0xe2, 0x00, 0xff, 0x5a, 0xe2, 0x00, 0xe1, 0x00,\n    0xa2, 0x20, 0xa1, 0x20, 0xe2, 0x00, 0xe1, 0x00,\n    0xe2, 0x00, 0xe1, 0x00, 0xa2, 0x20, 0xa1, 0x20,\n    0xe2, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01,\n    0x00, 0x3f, 0xc2, 0xe1, 0x00, 0xe2, 0x06, 0x20,\n    0xe2, 0x00, 0xe3, 0x00, 0xe2, 0x00, 0xe3, 0x00,\n    0xe2, 0x00, 0xe3, 0x00, 0x82, 0x00, 0x22, 0x61,\n    0x03, 0x0e, 0x02, 0x4e, 0x42, 0x00, 0x22, 0x61,\n    0x03, 0x4e, 0x62, 0x20, 0x22, 0x61, 0x00, 0x4e,\n    0xe2, 0x00, 0x81, 0x4e, 0x20, 0x42, 0x00, 0x22,\n    0x61, 0x03, 0x2e, 0x00, 0xf7, 0x03, 0x9b, 0xb1,\n    0x36, 0x14, 0x15, 0x12, 0x34, 0x15, 0x12, 0x14,\n    0xf6, 0x00, 0x18, 0x19, 0x9b, 0x17, 0xf6, 0x01,\n    0x14, 0x15, 0x76, 0x30, 0x56, 0x0c, 0x12, 0x13,\n    0xf6, 0x03, 0x0c, 0x16, 0x10, 0xf6, 0x02, 0x17,\n    0x9b, 0x00, 0xfb, 0x02, 0x0b, 0x04, 0x20, 0xab,\n    0x4c, 0x12, 0x13, 0x04, 0xeb, 0x02, 0x4c, 0x12,\n    0x13, 0x00, 0xe4, 0x05, 0x40, 0xed, 0x18, 0xe0,\n    0x08, 0xe6, 0x05, 0x68, 0x06, 0x48, 0xe6, 0x04,\n    0xe0, 0x07, 0x2f, 0x01, 0x6f, 0x01, 0x2f, 0x02,\n    0x41, 0x22, 0x41, 0x02, 0x0f, 0x01, 0x2f, 0x0c,\n    0x81, 0xaf, 0x01, 0x0f, 0x01, 0x0f, 0x01, 0x0f,\n    0x61, 0x0f, 0x02, 0x61, 0x02, 0x65, 0x02, 0x2f,\n    0x22, 0x21, 0x8c, 0x3f, 0x42, 0x0f, 0x0c, 0x2f,\n    0x02, 0x0f, 0xeb, 0x08, 0xea, 0x1b, 0x3f, 0x6a,\n    0x0b, 0x2f, 0x60, 0x8c, 0x8f, 0x2c, 0x6f, 0x0c,\n    0x2f, 0x0c, 0x2f, 0x0c, 0xcf, 0x0c, 0xef, 0x17,\n    0x2c, 0x2f, 0x0c, 0x0f, 0x0c, 0xef, 0x17, 0xec,\n    0x80, 0x84, 0xef, 0x00, 0x12, 0x13, 0x12, 0x13,\n    0xef, 0x0c, 0x2c, 0xcf, 0x12, 0x13, 0xef, 0x49,\n    0x0c, 0xef, 0x16, 0xec, 0x11, 0xef, 0x20, 0xac,\n    0xef, 0x3d, 0xe0, 0x11, 0xef, 0x03, 0xe0, 0x0d,\n    0xeb, 0x34, 0xef, 0x46, 0xeb, 0x0e, 0xef, 0x80,\n    0x2f, 0x0c, 0xef, 0x01, 0x0c, 0xef, 0x2e, 0xec,\n    0x00, 0xef, 0x67, 0x0c, 0xef, 0x80, 0x70, 0x12,\n    0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12,\n    0x13, 0x12, 0x13, 0x12, 0x13, 0xeb, 0x16, 0xef,\n    0x24, 0x8c, 0x12, 0x13, 0xec, 0x17, 0x12, 0x13,\n    0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13,\n    0xec, 0x08, 0xef, 0x80, 0x78, 0xec, 0x7b, 0x12,\n    0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12,\n    0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12,\n    0x13, 0x12, 0x13, 0x12, 0x13, 0xec, 0x37, 0x12,\n    0x13, 0x12, 0x13, 0xec, 0x18, 0x12, 0x13, 0xec,\n    0x80, 0x7a, 0xef, 0x28, 0xec, 0x0d, 0x2f, 0xac,\n    0xef, 0x1f, 0x20, 0xef, 0x18, 0x00, 0xef, 0x61,\n    0xe1, 0x27, 0x00, 0xe2, 0x27, 0x00, 0x5f, 0x21,\n    0x22, 0xdf, 0x41, 0x02, 0x3f, 0x02, 0x3f, 0x82,\n    0x24, 0x41, 0x02, 0xff, 0x5a, 0x02, 0xaf, 0x7f,\n    0x46, 0x3f, 0x80, 0x76, 0x0b, 0x36, 0xe2, 0x1e,\n    0x00, 0x02, 0x80, 0x02, 0x20, 0xe5, 0x30, 0xc0,\n    0x04, 0x16, 0xe0, 0x06, 0x06, 0xe5, 0x0f, 0xe0,\n    0x01, 0xc5, 0x00, 0xc5, 0x00, 0xc5, 0x00, 0xc5,\n    0x00, 0xc5, 0x00, 0xc5, 0x00, 0xc5, 0x00, 0xc5,\n    0x00, 0xe6, 0x18, 0x36, 0x14, 0x15, 0x14, 0x15,\n    0x56, 0x14, 0x15, 0x16, 0x14, 0x15, 0xf6, 0x01,\n    0x11, 0x36, 0x11, 0x16, 0x14, 0x15, 0x36, 0x14,\n    0x15, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12,\n    0x13, 0x96, 0x04, 0xf6, 0x02, 0x31, 0x76, 0x11,\n    0x16, 0x12, 0xf6, 0x05, 0x2f, 0x16, 0xe0, 0x25,\n    0xef, 0x12, 0x00, 0xef, 0x51, 0xe0, 0x04, 0xef,\n    0x80, 0x4e, 0xe0, 0x12, 0xef, 0x04, 0x60, 0x17,\n    0x56, 0x0f, 0x04, 0x05, 0x0a, 0x12, 0x13, 0x12,\n    0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x2f,\n    0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13,\n    0x11, 0x12, 0x33, 0x0f, 0xea, 0x01, 0x66, 0x27,\n    0x11, 0x84, 0x2f, 0x4a, 0x04, 0x05, 0x16, 0x2f,\n    0x00, 0xe5, 0x4e, 0x20, 0x26, 0x2e, 0x24, 0x05,\n    0x11, 0xe5, 0x52, 0x16, 0x44, 0x05, 0x80, 0xe5,\n    0x23, 0x00, 0xe5, 0x56, 0x00, 0x2f, 0x6b, 0xef,\n    0x02, 0xe5, 0x18, 0xef, 0x1c, 0xe0, 0x04, 0xe5,\n    0x08, 0xef, 0x17, 0x00, 0xeb, 0x02, 0xef, 0x16,\n    0xeb, 0x00, 0x0f, 0xeb, 0x07, 0xef, 0x18, 0xeb,\n    0x02, 0xef, 0x1f, 0xeb, 0x07, 0xef, 0x80, 0xb8,\n    0xe5, 0x99, 0x38, 0xef, 0x38, 0xe5, 0xc0, 0x11,\n    0x75, 0x40, 0xe5, 0x0d, 0x04, 0xe5, 0x83, 0xef,\n    0x40, 0xef, 0x2f, 0xe0, 0x01, 0xe5, 0x20, 0xa4,\n    0x36, 0xe5, 0x80, 0x84, 0x04, 0x56, 0xe5, 0x08,\n    0xe9, 0x02, 0x25, 0xe0, 0x0c, 0xff, 0x26, 0x05,\n    0x06, 0x48, 0x16, 0xe6, 0x02, 0x16, 0x04, 0xff,\n    0x14, 0x24, 0x26, 0xe5, 0x3e, 0xea, 0x02, 0x26,\n    0xb6, 0xe0, 0x00, 0xee, 0x0f, 0xe4, 0x01, 0x2e,\n    0xff, 0x06, 0x22, 0xff, 0x36, 0x04, 0xe2, 0x00,\n    0x9f, 0xff, 0x02, 0x04, 0x2e, 0x7f, 0x05, 0x7f,\n    0x22, 0xff, 0x0d, 0x61, 0x02, 0x81, 0x02, 0xff,\n    0x02, 0x20, 0x5f, 0x41, 0x02, 0x3f, 0xe0, 0x22,\n    0x3f, 0x05, 0x24, 0x02, 0xc5, 0x06, 0x45, 0x06,\n    0x65, 0x06, 0xe5, 0x0f, 0x27, 0x26, 0x07, 0x6f,\n    0x06, 0x40, 0xab, 0x2f, 0x0d, 0x0f, 0xa0, 0xe5,\n    0x2c, 0x76, 0xe0, 0x00, 0x27, 0xe5, 0x2a, 0xe7,\n    0x08, 0x26, 0xe0, 0x00, 0x36, 0xe9, 0x02, 0xa0,\n    0xe6, 0x0a, 0xa5, 0x56, 0x05, 0x16, 0x25, 0x06,\n    0xe9, 0x02, 0xe5, 0x14, 0xe6, 0x00, 0x36, 0xe5,\n    0x0f, 0xe6, 0x03, 0x27, 0xe0, 0x03, 0x16, 0xe5,\n    0x15, 0x40, 0x46, 0x07, 0xe5, 0x27, 0x06, 0x27,\n    0x66, 0x27, 0x26, 0x47, 0xf6, 0x05, 0x00, 0x04,\n    0xe9, 0x02, 0x60, 0x36, 0x85, 0x06, 0x04, 0xe5,\n    0x01, 0xe9, 0x02, 0x85, 0x00, 0xe5, 0x21, 0xa6,\n    0x27, 0x26, 0x27, 0x26, 0xe0, 0x01, 0x45, 0x06,\n    0xe5, 0x00, 0x06, 0x07, 0x20, 0xe9, 0x02, 0x20,\n    0x76, 0xe5, 0x08, 0x04, 0xa5, 0x4f, 0x05, 0x07,\n    0x06, 0x07, 0xe5, 0x2a, 0x06, 0x05, 0x46, 0x25,\n    0x26, 0x85, 0x26, 0x05, 0x06, 0x05, 0xe0, 0x10,\n    0x25, 0x04, 0x36, 0xe5, 0x03, 0x07, 0x26, 0x27,\n    0x36, 0x05, 0x24, 0x07, 0x06, 0xe0, 0x02, 0xa5,\n    0x20, 0xa5, 0x20, 0xa5, 0xe0, 0x01, 0xc5, 0x00,\n    0xc5, 0x00, 0xe2, 0x23, 0x0e, 0x64, 0xe2, 0x01,\n    0x04, 0x2e, 0x60, 0xe2, 0x48, 0xe5, 0x1b, 0x27,\n    0x06, 0x27, 0x06, 0x27, 0x16, 0x07, 0x06, 0x20,\n    0xe9, 0x02, 0xa0, 0xe5, 0xab, 0x1c, 0xe0, 0x04,\n    0xe5, 0x0f, 0x60, 0xe5, 0x29, 0x60, 0xfc, 0x87,\n    0x78, 0xfd, 0x98, 0x78, 0xe5, 0x80, 0xe6, 0x20,\n    0xe5, 0x62, 0xe0, 0x1e, 0xc2, 0xe0, 0x04, 0x82,\n    0x80, 0x05, 0x06, 0xe5, 0x02, 0x0c, 0xe5, 0x05,\n    0x00, 0x85, 0x00, 0x05, 0x00, 0x25, 0x00, 0x25,\n    0x00, 0xe5, 0x64, 0xee, 0x08, 0xe0, 0x09, 0xe5,\n    0x80, 0xe3, 0x13, 0x12, 0xe0, 0x08, 0xe5, 0x38,\n    0x20, 0xe5, 0x2e, 0xe0, 0x20, 0xe5, 0x04, 0x0d,\n    0x0f, 0x20, 0xe6, 0x08, 0xd6, 0x12, 0x13, 0x16,\n    0xa0, 0xe6, 0x08, 0x16, 0x31, 0x30, 0x12, 0x13,\n    0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13,\n    0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x36, 0x12,\n    0x13, 0x76, 0x50, 0x56, 0x00, 0x76, 0x11, 0x12,\n    0x13, 0x12, 0x13, 0x12, 0x13, 0x56, 0x0c, 0x11,\n    0x4c, 0x00, 0x16, 0x0d, 0x36, 0x60, 0x85, 0x00,\n    0xe5, 0x7f, 0x20, 0x1b, 0x00, 0x56, 0x0d, 0x56,\n    0x12, 0x13, 0x16, 0x0c, 0x16, 0x11, 0x36, 0xe9,\n    0x02, 0x36, 0x4c, 0x36, 0xe1, 0x12, 0x12, 0x16,\n    0x13, 0x0e, 0x10, 0x0e, 0xe2, 0x12, 0x12, 0x0c,\n    0x13, 0x0c, 0x12, 0x13, 0x16, 0x12, 0x13, 0x36,\n    0xe5, 0x02, 0x04, 0xe5, 0x25, 0x24, 0xe5, 0x17,\n    0x40, 0xa5, 0x20, 0xa5, 0x20, 0xa5, 0x20, 0x45,\n    0x40, 0x2d, 0x0c, 0x0e, 0x0f, 0x2d, 0x00, 0x0f,\n    0x6c, 0x2f, 0xe0, 0x02, 0x5b, 0x2f, 0x20, 0xe5,\n    0x04, 0x00, 0xe5, 0x12, 0x00, 0xe5, 0x0b, 0x00,\n    0x25, 0x00, 0xe5, 0x07, 0x20, 0xe5, 0x06, 0xe0,\n    0x1a, 0xe5, 0x73, 0x80, 0x56, 0x60, 0xeb, 0x25,\n    0x40, 0xef, 0x01, 0xea, 0x2d, 0x6b, 0xef, 0x09,\n    0x2b, 0x4f, 0x00, 0xef, 0x05, 0x40, 0x0f, 0xe0,\n    0x27, 0xef, 0x25, 0x06, 0xe0, 0x7a, 0xe5, 0x15,\n    0x40, 0xe5, 0x29, 0xe0, 0x07, 0x06, 0xeb, 0x13,\n    0x60, 0xe5, 0x18, 0x6b, 0xe0, 0x01, 0xe5, 0x0c,\n    0x0a, 0xe5, 0x00, 0x0a, 0x80, 0xe5, 0x1e, 0x86,\n    0x80, 0xe5, 0x16, 0x00, 0x16, 0xe5, 0x1c, 0x60,\n    0xe5, 0x00, 0x16, 0x8a, 0xe0, 0x22, 0xe1, 0x20,\n    0xe2, 0x20, 0xe5, 0x46, 0x20, 0xe9, 0x02, 0xa0,\n    0xe1, 0x1c, 0x60, 0xe2, 0x1c, 0x60, 0xe5, 0x20,\n    0xe0, 0x00, 0xe5, 0x2c, 0xe0, 0x03, 0x16, 0xe0,\n    0x80, 0x08, 0xe5, 0x80, 0xaf, 0xe0, 0x01, 0xe5,\n    0x0e, 0xe0, 0x02, 0xe5, 0x00, 0xe0, 0x80, 0x10,\n    0xa5, 0x20, 0x05, 0x00, 0xe5, 0x24, 0x00, 0x25,\n    0x40, 0x05, 0x20, 0xe5, 0x0f, 0x00, 0x16, 0xeb,\n    0x00, 0xe5, 0x0f, 0x2f, 0xcb, 0xe5, 0x17, 0xe0,\n    0x00, 0xeb, 0x01, 0xe0, 0x28, 0xe5, 0x0b, 0x00,\n    0x25, 0x80, 0x8b, 0xe5, 0x0e, 0xab, 0x40, 0x16,\n    0xe5, 0x12, 0x80, 0x16, 0xe0, 0x38, 0xe5, 0x30,\n    0x60, 0x2b, 0x25, 0xeb, 0x08, 0x20, 0xeb, 0x26,\n    0x05, 0x46, 0x00, 0x26, 0x80, 0x66, 0x65, 0x00,\n    0x45, 0x00, 0xe5, 0x15, 0x20, 0x46, 0x60, 0x06,\n    0xeb, 0x01, 0xc0, 0xf6, 0x01, 0xc0, 0xe5, 0x15,\n    0x2b, 0x16, 0xe5, 0x15, 0x4b, 0xe0, 0x18, 0xe5,\n    0x00, 0x0f, 0xe5, 0x14, 0x26, 0x60, 0x8b, 0xd6,\n    0xe0, 0x01, 0xe5, 0x2e, 0x40, 0xd6, 0xe5, 0x0e,\n    0x20, 0xeb, 0x00, 0xe5, 0x0b, 0x80, 0xeb, 0x00,\n    0xe5, 0x0a, 0xc0, 0x76, 0xe0, 0x04, 0xcb, 0xe0,\n    0x48, 0xe5, 0x41, 0xe0, 0x2f, 0xe1, 0x2b, 0xe0,\n    0x05, 0xe2, 0x2b, 0xc0, 0xab, 0xe5, 0x1c, 0x66,\n    0xe0, 0x00, 0xe9, 0x02, 0xe0, 0x80, 0x9e, 0xeb,\n    0x17, 0x00, 0xe5, 0x22, 0x00, 0x26, 0x11, 0x20,\n    0x25, 0xe0, 0x46, 0xe5, 0x15, 0xeb, 0x02, 0x05,\n    0xe0, 0x00, 0xe5, 0x0e, 0xe6, 0x03, 0x6b, 0x96,\n    0xe0, 0x4e, 0xe5, 0x0d, 0xcb, 0xe0, 0x0c, 0xe5,\n    0x0f, 0xe0, 0x01, 0x07, 0x06, 0x07, 0xe5, 0x2d,\n    0xe6, 0x07, 0xd6, 0x60, 0xeb, 0x0c, 0xe9, 0x02,\n    0xe0, 0x07, 0x46, 0x07, 0xe5, 0x25, 0x47, 0x66,\n    0x27, 0x26, 0x36, 0x1b, 0x76, 0xe0, 0x03, 0x1b,\n    0x20, 0xe5, 0x11, 0xc0, 0xe9, 0x02, 0xa0, 0x46,\n    0xe5, 0x1c, 0x86, 0x07, 0xe6, 0x00, 0x00, 0xe9,\n    0x02, 0x76, 0x05, 0x27, 0x05, 0xe0, 0x00, 0xe5,\n    0x1b, 0x06, 0x36, 0x05, 0xe0, 0x01, 0x26, 0x07,\n    0xe5, 0x28, 0x47, 0xe6, 0x01, 0x27, 0x65, 0x76,\n    0x66, 0x16, 0x07, 0x06, 0xe9, 0x02, 0x05, 0x16,\n    0x05, 0x56, 0x00, 0xeb, 0x0c, 0xe0, 0x03, 0xe5,\n    0x0a, 0x00, 0xe5, 0x11, 0x47, 0x46, 0x27, 0x06,\n    0x07, 0x26, 0xb6, 0x06, 0xe0, 0x39, 0xc5, 0x00,\n    0x05, 0x00, 0x65, 0x00, 0xe5, 0x07, 0x00, 0xe5,\n    0x02, 0x16, 0xa0, 0xe5, 0x27, 0x06, 0x47, 0xe6,\n    0x00, 0x80, 0xe9, 0x02, 0xa0, 0x26, 0x27, 0x00,\n    0xe5, 0x00, 0x20, 0x25, 0x20, 0xe5, 0x0e, 0x00,\n    0xc5, 0x00, 0x25, 0x00, 0x85, 0x00, 0x26, 0x05,\n    0x27, 0x06, 0x67, 0x20, 0x27, 0x20, 0x47, 0x20,\n    0x05, 0xa0, 0x07, 0x80, 0x85, 0x27, 0x20, 0xc6,\n    0x40, 0x86, 0xe0, 0x80, 0x03, 0xe5, 0x2d, 0x47,\n    0xe6, 0x00, 0x27, 0x46, 0x07, 0x06, 0x65, 0x96,\n    0xe9, 0x02, 0x36, 0x00, 0x16, 0x06, 0x45, 0xe0,\n    0x16, 0xe5, 0x28, 0x47, 0xa6, 0x07, 0x06, 0x67,\n    0x26, 0x07, 0x26, 0x25, 0x16, 0x05, 0xe0, 0x00,\n    0xe9, 0x02, 0xe0, 0x80, 0x1e, 0xe5, 0x27, 0x47,\n    0x66, 0x20, 0x67, 0x26, 0x07, 0x26, 0xf6, 0x0f,\n    0x65, 0x26, 0xe0, 0x1a, 0xe5, 0x28, 0x47, 0xe6,\n    0x00, 0x27, 0x06, 0x07, 0x26, 0x56, 0x05, 0xe0,\n    0x03, 0xe9, 0x02, 0xa0, 0xf6, 0x05, 0xe0, 0x0b,\n    0xe5, 0x23, 0x06, 0x07, 0x06, 0x27, 0xa6, 0x07,\n    0x06, 0x05, 0xc0, 0xe9, 0x02, 0xe0, 0x2e, 0xe5,\n    0x13, 0x20, 0x46, 0x27, 0x66, 0x07, 0x86, 0x60,\n    0xe9, 0x02, 0x2b, 0x56, 0x0f, 0xe0, 0x80, 0x38,\n    0xe5, 0x24, 0x47, 0xe6, 0x01, 0x07, 0x26, 0x16,\n    0xe0, 0x5c, 0xe1, 0x18, 0xe2, 0x18, 0xe9, 0x02,\n    0xeb, 0x01, 0xe0, 0x04, 0xe5, 0x00, 0x20, 0x05,\n    0x20, 0xe5, 0x00, 0x00, 0x25, 0x00, 0xe5, 0x10,\n    0xa7, 0x00, 0x27, 0x20, 0x26, 0x07, 0x06, 0x05,\n    0x07, 0x05, 0x07, 0x06, 0x56, 0xe0, 0x01, 0xe9,\n    0x02, 0xe0, 0x3e, 0xe5, 0x00, 0x20, 0xe5, 0x1f,\n    0x47, 0x66, 0x20, 0x26, 0x67, 0x06, 0x05, 0x16,\n    0x05, 0x07, 0xe0, 0x13, 0x05, 0xe6, 0x02, 0xe5,\n    0x20, 0xa6, 0x07, 0x05, 0x66, 0xf6, 0x00, 0x06,\n    0xe0, 0x00, 0x05, 0xa6, 0x27, 0x46, 0xe5, 0x26,\n    0xe6, 0x05, 0x07, 0x26, 0x56, 0x05, 0x96, 0xe0,\n    0x15, 0xe5, 0x31, 0xe0, 0x80, 0x7f, 0xe5, 0x01,\n    0x00, 0xe5, 0x1d, 0x07, 0xc6, 0x00, 0xa6, 0x07,\n    0x06, 0x05, 0x96, 0xe0, 0x02, 0xe9, 0x02, 0xeb,\n    0x0b, 0x40, 0x36, 0xe5, 0x16, 0x20, 0xe6, 0x0e,\n    0x00, 0x07, 0xc6, 0x07, 0x26, 0x07, 0x26, 0xe0,\n    0x41, 0xc5, 0x00, 0x25, 0x00, 0xe5, 0x1e, 0xa6,\n    0x40, 0x06, 0x00, 0x26, 0x00, 0xc6, 0x05, 0x06,\n    0xe0, 0x00, 0xe9, 0x02, 0xa0, 0xa5, 0x00, 0x25,\n    0x00, 0xe5, 0x18, 0x87, 0x00, 0x26, 0x00, 0x27,\n    0x06, 0x07, 0x06, 0x05, 0xc0, 0xe9, 0x02, 0xe0,\n    0x80, 0xae, 0xe5, 0x0b, 0x26, 0x27, 0x36, 0xe0,\n    0x80, 0x2f, 0x05, 0xe0, 0x07, 0xeb, 0x0d, 0xef,\n    0x00, 0x6d, 0xef, 0x09, 0xe0, 0x05, 0x16, 0xe5,\n    0x83, 0x12, 0xe0, 0x5e, 0xea, 0x67, 0x00, 0x96,\n    0xe0, 0x03, 0xe5, 0x80, 0x3c, 0xe0, 0x8a, 0x34,\n    0xe5, 0x83, 0xa7, 0x00, 0xfb, 0x01, 0xe0, 0x8f,\n    0x3f, 0xe5, 0x81, 0xbf, 0xe0, 0xa1, 0x31, 0xe5,\n    0x81, 0xb1, 0xc0, 0xe5, 0x17, 0x00, 0xe9, 0x02,\n    0x60, 0x36, 0xe0, 0x58, 0xe5, 0x16, 0x20, 0x86,\n    0x16, 0xe0, 0x02, 0xe5, 0x28, 0xc6, 0x96, 0x6f,\n    0x64, 0x16, 0x0f, 0xe0, 0x02, 0xe9, 0x02, 0x00,\n    0xcb, 0x00, 0xe5, 0x0d, 0x80, 0xe5, 0x0b, 0xe0,\n    0x82, 0x28, 0xe1, 0x18, 0xe2, 0x18, 0xeb, 0x0f,\n    0x76, 0xe0, 0x5d, 0xe5, 0x43, 0x60, 0x06, 0x05,\n    0xe7, 0x2f, 0xc0, 0x66, 0xe4, 0x05, 0xe0, 0x38,\n    0x24, 0x16, 0x04, 0x06, 0xe0, 0x03, 0x27, 0xe0,\n    0x06, 0xe5, 0x97, 0x70, 0xe0, 0x00, 0xe5, 0x84,\n    0x4e, 0xe0, 0x22, 0xe5, 0x01, 0xe0, 0xa2, 0x6f,\n    0xe5, 0x80, 0x97, 0xe0, 0x29, 0x45, 0xe0, 0x09,\n    0x65, 0xe0, 0x00, 0xe5, 0x81, 0x04, 0xe0, 0x88,\n    0x7c, 0xe5, 0x63, 0x80, 0xe5, 0x05, 0x40, 0xe5,\n    0x01, 0xc0, 0xe5, 0x02, 0x20, 0x0f, 0x26, 0x16,\n    0x7b, 0xe0, 0x92, 0xd4, 0xef, 0x80, 0x6e, 0xe0,\n    0x02, 0xef, 0x1f, 0x20, 0xef, 0x34, 0x27, 0x46,\n    0x4f, 0xa7, 0xfb, 0x00, 0xe6, 0x00, 0x2f, 0xc6,\n    0xef, 0x16, 0x66, 0xef, 0x33, 0xe0, 0x0f, 0xef,\n    0x3a, 0x46, 0x0f, 0xe0, 0x80, 0x12, 0xeb, 0x0c,\n    0xe0, 0x04, 0xef, 0x4f, 0xe0, 0x01, 0xeb, 0x11,\n    0xe0, 0x7f, 0xe1, 0x12, 0xe2, 0x12, 0xe1, 0x12,\n    0xc2, 0x00, 0xe2, 0x0a, 0xe1, 0x12, 0xe2, 0x12,\n    0x01, 0x00, 0x21, 0x20, 0x01, 0x20, 0x21, 0x20,\n    0x61, 0x00, 0xe1, 0x00, 0x62, 0x00, 0x02, 0x00,\n    0xc2, 0x00, 0xe2, 0x03, 0xe1, 0x12, 0xe2, 0x12,\n    0x21, 0x00, 0x61, 0x20, 0xe1, 0x00, 0x00, 0xc1,\n    0x00, 0xe2, 0x12, 0x21, 0x00, 0x61, 0x00, 0x81,\n    0x00, 0x01, 0x40, 0xc1, 0x00, 0xe2, 0x12, 0xe1,\n    0x12, 0xe2, 0x12, 0xe1, 0x12, 0xe2, 0x12, 0xe1,\n    0x12, 0xe2, 0x12, 0xe1, 0x12, 0xe2, 0x12, 0xe1,\n    0x12, 0xe2, 0x12, 0xe1, 0x12, 0xe2, 0x14, 0x20,\n    0xe1, 0x11, 0x0c, 0xe2, 0x11, 0x0c, 0xa2, 0xe1,\n    0x11, 0x0c, 0xe2, 0x11, 0x0c, 0xa2, 0xe1, 0x11,\n    0x0c, 0xe2, 0x11, 0x0c, 0xa2, 0xe1, 0x11, 0x0c,\n    0xe2, 0x11, 0x0c, 0xa2, 0xe1, 0x11, 0x0c, 0xe2,\n    0x11, 0x0c, 0xa2, 0x3f, 0x20, 0xe9, 0x2a, 0xef,\n    0x81, 0x78, 0xe6, 0x2f, 0x6f, 0xe6, 0x2a, 0xef,\n    0x00, 0x06, 0xef, 0x06, 0x06, 0x2f, 0x96, 0xe0,\n    0x07, 0x86, 0x00, 0xe6, 0x07, 0xe0, 0x84, 0xc8,\n    0xc6, 0x00, 0xe6, 0x09, 0x20, 0xc6, 0x00, 0x26,\n    0x00, 0x86, 0xe0, 0x80, 0x4d, 0xe5, 0x25, 0x40,\n    0xc6, 0xc4, 0x20, 0xe9, 0x02, 0x60, 0x05, 0x0f,\n    0xe0, 0x80, 0xe8, 0xe5, 0x24, 0x66, 0xe9, 0x02,\n    0x80, 0x0d, 0xe0, 0x84, 0x78, 0xe5, 0x80, 0x3d,\n    0x20, 0xeb, 0x01, 0xc6, 0xe0, 0x21, 0xe1, 0x1a,\n    0xe2, 0x1a, 0xc6, 0x04, 0x60, 0xe9, 0x02, 0x60,\n    0x36, 0xe0, 0x82, 0x89, 0xeb, 0x33, 0x0f, 0x4b,\n    0x0d, 0x6b, 0xe0, 0x44, 0xeb, 0x25, 0x0f, 0xeb,\n    0x07, 0xe0, 0x80, 0x3a, 0x65, 0x00, 0xe5, 0x13,\n    0x00, 0x25, 0x00, 0x05, 0x20, 0x05, 0x00, 0xe5,\n    0x02, 0x00, 0x65, 0x00, 0x05, 0x00, 0x05, 0xa0,\n    0x05, 0x60, 0x05, 0x00, 0x05, 0x00, 0x05, 0x00,\n    0x45, 0x00, 0x25, 0x00, 0x05, 0x20, 0x05, 0x00,\n    0x05, 0x00, 0x05, 0x00, 0x05, 0x00, 0x05, 0x00,\n    0x25, 0x00, 0x05, 0x20, 0x65, 0x00, 0xc5, 0x00,\n    0x65, 0x00, 0x65, 0x00, 0x05, 0x00, 0xe5, 0x02,\n    0x00, 0xe5, 0x09, 0x80, 0x45, 0x00, 0x85, 0x00,\n    0xe5, 0x09, 0xe0, 0x2c, 0x2c, 0xe0, 0x80, 0x86,\n    0xef, 0x24, 0x60, 0xef, 0x5c, 0xe0, 0x04, 0xef,\n    0x07, 0x20, 0xef, 0x07, 0x00, 0xef, 0x07, 0x00,\n    0xef, 0x1d, 0xe0, 0x02, 0xeb, 0x05, 0xef, 0x80,\n    0x19, 0xe0, 0x30, 0xef, 0x15, 0xe0, 0x05, 0xef,\n    0x24, 0x60, 0xef, 0x01, 0xc0, 0x2f, 0xe0, 0x06,\n    0xaf, 0xe0, 0x80, 0x12, 0xef, 0x80, 0x73, 0x8e,\n    0xef, 0x82, 0x50, 0xe0, 0x00, 0xef, 0x05, 0x40,\n    0xef, 0x05, 0x40, 0xef, 0x6c, 0xe0, 0x04, 0xef,\n    0x51, 0xc0, 0xef, 0x04, 0xe0, 0x0c, 0xef, 0x04,\n    0x60, 0xef, 0x30, 0xe0, 0x00, 0xef, 0x02, 0xa0,\n    0xef, 0x20, 0xe0, 0x00, 0xef, 0x16, 0x20, 0x2f,\n    0xe0, 0x46, 0xef, 0x71, 0x00, 0xef, 0x4a, 0x00,\n    0xef, 0x7f, 0xe0, 0x04, 0xef, 0x06, 0x20, 0x8f,\n    0x40, 0x4f, 0x80, 0xcf, 0xe0, 0x01, 0xef, 0x11,\n    0xc0, 0xcf, 0xe0, 0x01, 0x4f, 0xe0, 0x05, 0xcf,\n    0xe0, 0x21, 0xef, 0x80, 0x0b, 0x00, 0xef, 0x2f,\n    0xe0, 0x1d, 0xe9, 0x02, 0xe0, 0x83, 0x7e, 0xe5,\n    0xc0, 0x66, 0x56, 0xe0, 0x1a, 0xe5, 0x8f, 0xad,\n    0xe0, 0x03, 0xe5, 0x80, 0x56, 0x20, 0xe5, 0x95,\n    0xfa, 0xe0, 0x06, 0xe5, 0x9c, 0xa9, 0xe0, 0x8b,\n    0x97, 0xe5, 0x81, 0x96, 0xe0, 0x85, 0x5a, 0xe5,\n    0x92, 0xc3, 0xe0, 0xca, 0xac, 0x2e, 0x1b, 0xe0,\n    0x16, 0xfb, 0x58, 0xe0, 0x78, 0xe6, 0x80, 0x68,\n    0xe0, 0xc0, 0xbd, 0x88, 0xfd, 0xc0, 0xbf, 0x76,\n    0x20, 0xfd, 0xc0, 0xbf, 0x76, 0x20,\n};\n\ntypedef enum {\n    UNICODE_SCRIPT_Unknown,\n    UNICODE_SCRIPT_Adlam,\n    UNICODE_SCRIPT_Ahom,\n    UNICODE_SCRIPT_Anatolian_Hieroglyphs,\n    UNICODE_SCRIPT_Arabic,\n    UNICODE_SCRIPT_Armenian,\n    UNICODE_SCRIPT_Avestan,\n    UNICODE_SCRIPT_Balinese,\n    UNICODE_SCRIPT_Bamum,\n    UNICODE_SCRIPT_Bassa_Vah,\n    UNICODE_SCRIPT_Batak,\n    UNICODE_SCRIPT_Bengali,\n    UNICODE_SCRIPT_Bhaiksuki,\n    UNICODE_SCRIPT_Bopomofo,\n    UNICODE_SCRIPT_Brahmi,\n    UNICODE_SCRIPT_Braille,\n    UNICODE_SCRIPT_Buginese,\n    UNICODE_SCRIPT_Buhid,\n    UNICODE_SCRIPT_Canadian_Aboriginal,\n    UNICODE_SCRIPT_Carian,\n    UNICODE_SCRIPT_Caucasian_Albanian,\n    UNICODE_SCRIPT_Chakma,\n    UNICODE_SCRIPT_Cham,\n    UNICODE_SCRIPT_Cherokee,\n    UNICODE_SCRIPT_Chorasmian,\n    UNICODE_SCRIPT_Common,\n    UNICODE_SCRIPT_Coptic,\n    UNICODE_SCRIPT_Cuneiform,\n    UNICODE_SCRIPT_Cypriot,\n    UNICODE_SCRIPT_Cyrillic,\n    UNICODE_SCRIPT_Deseret,\n    UNICODE_SCRIPT_Devanagari,\n    UNICODE_SCRIPT_Dives_Akuru,\n    UNICODE_SCRIPT_Dogra,\n    UNICODE_SCRIPT_Duployan,\n    UNICODE_SCRIPT_Egyptian_Hieroglyphs,\n    UNICODE_SCRIPT_Elbasan,\n    UNICODE_SCRIPT_Elymaic,\n    UNICODE_SCRIPT_Ethiopic,\n    UNICODE_SCRIPT_Georgian,\n    UNICODE_SCRIPT_Glagolitic,\n    UNICODE_SCRIPT_Gothic,\n    UNICODE_SCRIPT_Grantha,\n    UNICODE_SCRIPT_Greek,\n    UNICODE_SCRIPT_Gujarati,\n    UNICODE_SCRIPT_Gunjala_Gondi,\n    UNICODE_SCRIPT_Gurmukhi,\n    UNICODE_SCRIPT_Han,\n    UNICODE_SCRIPT_Hangul,\n    UNICODE_SCRIPT_Hanifi_Rohingya,\n    UNICODE_SCRIPT_Hanunoo,\n    UNICODE_SCRIPT_Hatran,\n    UNICODE_SCRIPT_Hebrew,\n    UNICODE_SCRIPT_Hiragana,\n    UNICODE_SCRIPT_Imperial_Aramaic,\n    UNICODE_SCRIPT_Inherited,\n    UNICODE_SCRIPT_Inscriptional_Pahlavi,\n    UNICODE_SCRIPT_Inscriptional_Parthian,\n    UNICODE_SCRIPT_Javanese,\n    UNICODE_SCRIPT_Kaithi,\n    UNICODE_SCRIPT_Kannada,\n    UNICODE_SCRIPT_Katakana,\n    UNICODE_SCRIPT_Kayah_Li,\n    UNICODE_SCRIPT_Kharoshthi,\n    UNICODE_SCRIPT_Khmer,\n    UNICODE_SCRIPT_Khojki,\n    UNICODE_SCRIPT_Khitan_Small_Script,\n    UNICODE_SCRIPT_Khudawadi,\n    UNICODE_SCRIPT_Lao,\n    UNICODE_SCRIPT_Latin,\n    UNICODE_SCRIPT_Lepcha,\n    UNICODE_SCRIPT_Limbu,\n    UNICODE_SCRIPT_Linear_A,\n    UNICODE_SCRIPT_Linear_B,\n    UNICODE_SCRIPT_Lisu,\n    UNICODE_SCRIPT_Lycian,\n    UNICODE_SCRIPT_Lydian,\n    UNICODE_SCRIPT_Makasar,\n    UNICODE_SCRIPT_Mahajani,\n    UNICODE_SCRIPT_Malayalam,\n    UNICODE_SCRIPT_Mandaic,\n    UNICODE_SCRIPT_Manichaean,\n    UNICODE_SCRIPT_Marchen,\n    UNICODE_SCRIPT_Masaram_Gondi,\n    UNICODE_SCRIPT_Medefaidrin,\n    UNICODE_SCRIPT_Meetei_Mayek,\n    UNICODE_SCRIPT_Mende_Kikakui,\n    UNICODE_SCRIPT_Meroitic_Cursive,\n    UNICODE_SCRIPT_Meroitic_Hieroglyphs,\n    UNICODE_SCRIPT_Miao,\n    UNICODE_SCRIPT_Modi,\n    UNICODE_SCRIPT_Mongolian,\n    UNICODE_SCRIPT_Mro,\n    UNICODE_SCRIPT_Multani,\n    UNICODE_SCRIPT_Myanmar,\n    UNICODE_SCRIPT_Nabataean,\n    UNICODE_SCRIPT_Nandinagari,\n    UNICODE_SCRIPT_New_Tai_Lue,\n    UNICODE_SCRIPT_Newa,\n    UNICODE_SCRIPT_Nko,\n    UNICODE_SCRIPT_Nushu,\n    UNICODE_SCRIPT_Nyiakeng_Puachue_Hmong,\n    UNICODE_SCRIPT_Ogham,\n    UNICODE_SCRIPT_Ol_Chiki,\n    UNICODE_SCRIPT_Old_Hungarian,\n    UNICODE_SCRIPT_Old_Italic,\n    UNICODE_SCRIPT_Old_North_Arabian,\n    UNICODE_SCRIPT_Old_Permic,\n    UNICODE_SCRIPT_Old_Persian,\n    UNICODE_SCRIPT_Old_Sogdian,\n    UNICODE_SCRIPT_Old_South_Arabian,\n    UNICODE_SCRIPT_Old_Turkic,\n    UNICODE_SCRIPT_Oriya,\n    UNICODE_SCRIPT_Osage,\n    UNICODE_SCRIPT_Osmanya,\n    UNICODE_SCRIPT_Pahawh_Hmong,\n    UNICODE_SCRIPT_Palmyrene,\n    UNICODE_SCRIPT_Pau_Cin_Hau,\n    UNICODE_SCRIPT_Phags_Pa,\n    UNICODE_SCRIPT_Phoenician,\n    UNICODE_SCRIPT_Psalter_Pahlavi,\n    UNICODE_SCRIPT_Rejang,\n    UNICODE_SCRIPT_Runic,\n    UNICODE_SCRIPT_Samaritan,\n    UNICODE_SCRIPT_Saurashtra,\n    UNICODE_SCRIPT_Sharada,\n    UNICODE_SCRIPT_Shavian,\n    UNICODE_SCRIPT_Siddham,\n    UNICODE_SCRIPT_SignWriting,\n    UNICODE_SCRIPT_Sinhala,\n    UNICODE_SCRIPT_Sogdian,\n    UNICODE_SCRIPT_Sora_Sompeng,\n    UNICODE_SCRIPT_Soyombo,\n    UNICODE_SCRIPT_Sundanese,\n    UNICODE_SCRIPT_Syloti_Nagri,\n    UNICODE_SCRIPT_Syriac,\n    UNICODE_SCRIPT_Tagalog,\n    UNICODE_SCRIPT_Tagbanwa,\n    UNICODE_SCRIPT_Tai_Le,\n    UNICODE_SCRIPT_Tai_Tham,\n    UNICODE_SCRIPT_Tai_Viet,\n    UNICODE_SCRIPT_Takri,\n    UNICODE_SCRIPT_Tamil,\n    UNICODE_SCRIPT_Tangut,\n    UNICODE_SCRIPT_Telugu,\n    UNICODE_SCRIPT_Thaana,\n    UNICODE_SCRIPT_Thai,\n    UNICODE_SCRIPT_Tibetan,\n    UNICODE_SCRIPT_Tifinagh,\n    UNICODE_SCRIPT_Tirhuta,\n    UNICODE_SCRIPT_Ugaritic,\n    UNICODE_SCRIPT_Vai,\n    UNICODE_SCRIPT_Wancho,\n    UNICODE_SCRIPT_Warang_Citi,\n    UNICODE_SCRIPT_Yezidi,\n    UNICODE_SCRIPT_Yi,\n    UNICODE_SCRIPT_Zanabazar_Square,\n    UNICODE_SCRIPT_COUNT,\n} UnicodeScriptEnum;\n\nstatic const char unicode_script_name_table[] =\n    \"Adlam,Adlm\"                  \"\\0\"\n    \"Ahom,Ahom\"                   \"\\0\"\n    \"Anatolian_Hieroglyphs,Hluw\"  \"\\0\"\n    \"Arabic,Arab\"                 \"\\0\"\n    \"Armenian,Armn\"               \"\\0\"\n    \"Avestan,Avst\"                \"\\0\"\n    \"Balinese,Bali\"               \"\\0\"\n    \"Bamum,Bamu\"                  \"\\0\"\n    \"Bassa_Vah,Bass\"              \"\\0\"\n    \"Batak,Batk\"                  \"\\0\"\n    \"Bengali,Beng\"                \"\\0\"\n    \"Bhaiksuki,Bhks\"              \"\\0\"\n    \"Bopomofo,Bopo\"               \"\\0\"\n    \"Brahmi,Brah\"                 \"\\0\"\n    \"Braille,Brai\"                \"\\0\"\n    \"Buginese,Bugi\"               \"\\0\"\n    \"Buhid,Buhd\"                  \"\\0\"\n    \"Canadian_Aboriginal,Cans\"    \"\\0\"\n    \"Carian,Cari\"                 \"\\0\"\n    \"Caucasian_Albanian,Aghb\"     \"\\0\"\n    \"Chakma,Cakm\"                 \"\\0\"\n    \"Cham,Cham\"                   \"\\0\"\n    \"Cherokee,Cher\"               \"\\0\"\n    \"Chorasmian,Chrs\"             \"\\0\"\n    \"Common,Zyyy\"                 \"\\0\"\n    \"Coptic,Copt,Qaac\"            \"\\0\"\n    \"Cuneiform,Xsux\"              \"\\0\"\n    \"Cypriot,Cprt\"                \"\\0\"\n    \"Cyrillic,Cyrl\"               \"\\0\"\n    \"Deseret,Dsrt\"                \"\\0\"\n    \"Devanagari,Deva\"             \"\\0\"\n    \"Dives_Akuru,Diak\"            \"\\0\"\n    \"Dogra,Dogr\"                  \"\\0\"\n    \"Duployan,Dupl\"               \"\\0\"\n    \"Egyptian_Hieroglyphs,Egyp\"   \"\\0\"\n    \"Elbasan,Elba\"                \"\\0\"\n    \"Elymaic,Elym\"                \"\\0\"\n    \"Ethiopic,Ethi\"               \"\\0\"\n    \"Georgian,Geor\"               \"\\0\"\n    \"Glagolitic,Glag\"             \"\\0\"\n    \"Gothic,Goth\"                 \"\\0\"\n    \"Grantha,Gran\"                \"\\0\"\n    \"Greek,Grek\"                  \"\\0\"\n    \"Gujarati,Gujr\"               \"\\0\"\n    \"Gunjala_Gondi,Gong\"          \"\\0\"\n    \"Gurmukhi,Guru\"               \"\\0\"\n    \"Han,Hani\"                    \"\\0\"\n    \"Hangul,Hang\"                 \"\\0\"\n    \"Hanifi_Rohingya,Rohg\"        \"\\0\"\n    \"Hanunoo,Hano\"                \"\\0\"\n    \"Hatran,Hatr\"                 \"\\0\"\n    \"Hebrew,Hebr\"                 \"\\0\"\n    \"Hiragana,Hira\"               \"\\0\"\n    \"Imperial_Aramaic,Armi\"       \"\\0\"\n    \"Inherited,Zinh,Qaai\"         \"\\0\"\n    \"Inscriptional_Pahlavi,Phli\"  \"\\0\"\n    \"Inscriptional_Parthian,Prti\" \"\\0\"\n    \"Javanese,Java\"               \"\\0\"\n    \"Kaithi,Kthi\"                 \"\\0\"\n    \"Kannada,Knda\"                \"\\0\"\n    \"Katakana,Kana\"               \"\\0\"\n    \"Kayah_Li,Kali\"               \"\\0\"\n    \"Kharoshthi,Khar\"             \"\\0\"\n    \"Khmer,Khmr\"                  \"\\0\"\n    \"Khojki,Khoj\"                 \"\\0\"\n    \"Khitan_Small_Script,Kits\"    \"\\0\"\n    \"Khudawadi,Sind\"              \"\\0\"\n    \"Lao,Laoo\"                    \"\\0\"\n    \"Latin,Latn\"                  \"\\0\"\n    \"Lepcha,Lepc\"                 \"\\0\"\n    \"Limbu,Limb\"                  \"\\0\"\n    \"Linear_A,Lina\"               \"\\0\"\n    \"Linear_B,Linb\"               \"\\0\"\n    \"Lisu,Lisu\"                   \"\\0\"\n    \"Lycian,Lyci\"                 \"\\0\"\n    \"Lydian,Lydi\"                 \"\\0\"\n    \"Makasar,Maka\"                \"\\0\"\n    \"Mahajani,Mahj\"               \"\\0\"\n    \"Malayalam,Mlym\"              \"\\0\"\n    \"Mandaic,Mand\"                \"\\0\"\n    \"Manichaean,Mani\"             \"\\0\"\n    \"Marchen,Marc\"                \"\\0\"\n    \"Masaram_Gondi,Gonm\"          \"\\0\"\n    \"Medefaidrin,Medf\"            \"\\0\"\n    \"Meetei_Mayek,Mtei\"           \"\\0\"\n    \"Mende_Kikakui,Mend\"          \"\\0\"\n    \"Meroitic_Cursive,Merc\"       \"\\0\"\n    \"Meroitic_Hieroglyphs,Mero\"   \"\\0\"\n    \"Miao,Plrd\"                   \"\\0\"\n    \"Modi,Modi\"                   \"\\0\"\n    \"Mongolian,Mong\"              \"\\0\"\n    \"Mro,Mroo\"                    \"\\0\"\n    \"Multani,Mult\"                \"\\0\"\n    \"Myanmar,Mymr\"                \"\\0\"\n    \"Nabataean,Nbat\"              \"\\0\"\n    \"Nandinagari,Nand\"            \"\\0\"\n    \"New_Tai_Lue,Talu\"            \"\\0\"\n    \"Newa,Newa\"                   \"\\0\"\n    \"Nko,Nkoo\"                    \"\\0\"\n    \"Nushu,Nshu\"                  \"\\0\"\n    \"Nyiakeng_Puachue_Hmong,Hmnp\" \"\\0\"\n    \"Ogham,Ogam\"                  \"\\0\"\n    \"Ol_Chiki,Olck\"               \"\\0\"\n    \"Old_Hungarian,Hung\"          \"\\0\"\n    \"Old_Italic,Ital\"             \"\\0\"\n    \"Old_North_Arabian,Narb\"      \"\\0\"\n    \"Old_Permic,Perm\"             \"\\0\"\n    \"Old_Persian,Xpeo\"            \"\\0\"\n    \"Old_Sogdian,Sogo\"            \"\\0\"\n    \"Old_South_Arabian,Sarb\"      \"\\0\"\n    \"Old_Turkic,Orkh\"             \"\\0\"\n    \"Oriya,Orya\"                  \"\\0\"\n    \"Osage,Osge\"                  \"\\0\"\n    \"Osmanya,Osma\"                \"\\0\"\n    \"Pahawh_Hmong,Hmng\"           \"\\0\"\n    \"Palmyrene,Palm\"              \"\\0\"\n    \"Pau_Cin_Hau,Pauc\"            \"\\0\"\n    \"Phags_Pa,Phag\"               \"\\0\"\n    \"Phoenician,Phnx\"             \"\\0\"\n    \"Psalter_Pahlavi,Phlp\"        \"\\0\"\n    \"Rejang,Rjng\"                 \"\\0\"\n    \"Runic,Runr\"                  \"\\0\"\n    \"Samaritan,Samr\"              \"\\0\"\n    \"Saurashtra,Saur\"             \"\\0\"\n    \"Sharada,Shrd\"                \"\\0\"\n    \"Shavian,Shaw\"                \"\\0\"\n    \"Siddham,Sidd\"                \"\\0\"\n    \"SignWriting,Sgnw\"            \"\\0\"\n    \"Sinhala,Sinh\"                \"\\0\"\n    \"Sogdian,Sogd\"                \"\\0\"\n    \"Sora_Sompeng,Sora\"           \"\\0\"\n    \"Soyombo,Soyo\"                \"\\0\"\n    \"Sundanese,Sund\"              \"\\0\"\n    \"Syloti_Nagri,Sylo\"           \"\\0\"\n    \"Syriac,Syrc\"                 \"\\0\"\n    \"Tagalog,Tglg\"                \"\\0\"\n    \"Tagbanwa,Tagb\"               \"\\0\"\n    \"Tai_Le,Tale\"                 \"\\0\"\n    \"Tai_Tham,Lana\"               \"\\0\"\n    \"Tai_Viet,Tavt\"               \"\\0\"\n    \"Takri,Takr\"                  \"\\0\"\n    \"Tamil,Taml\"                  \"\\0\"\n    \"Tangut,Tang\"                 \"\\0\"\n    \"Telugu,Telu\"                 \"\\0\"\n    \"Thaana,Thaa\"                 \"\\0\"\n    \"Thai,Thai\"                   \"\\0\"\n    \"Tibetan,Tibt\"                \"\\0\"\n    \"Tifinagh,Tfng\"               \"\\0\"\n    \"Tirhuta,Tirh\"                \"\\0\"\n    \"Ugaritic,Ugar\"               \"\\0\"\n    \"Vai,Vaii\"                    \"\\0\"\n    \"Wancho,Wcho\"                 \"\\0\"\n    \"Warang_Citi,Wara\"            \"\\0\"\n    \"Yezidi,Yezi\"                 \"\\0\"\n    \"Yi,Yiii\"                     \"\\0\"\n    \"Zanabazar_Square,Zanb\"       \"\\0\"\n;\n\nstatic const uint8_t unicode_script_table[2609] = {\n    0xc0, 0x19, 0x99, 0x45, 0x85, 0x19, 0x99, 0x45,\n    0xae, 0x19, 0x80, 0x45, 0x8e, 0x19, 0x80, 0x45,\n    0x84, 0x19, 0x96, 0x45, 0x80, 0x19, 0x9e, 0x45,\n    0x80, 0x19, 0xe1, 0x60, 0x45, 0xa6, 0x19, 0x84,\n    0x45, 0x84, 0x19, 0x81, 0x0d, 0x93, 0x19, 0xe0,\n    0x0f, 0x37, 0x83, 0x2b, 0x80, 0x19, 0x82, 0x2b,\n    0x01, 0x83, 0x2b, 0x80, 0x19, 0x80, 0x2b, 0x03,\n    0x80, 0x2b, 0x80, 0x19, 0x80, 0x2b, 0x80, 0x19,\n    0x82, 0x2b, 0x00, 0x80, 0x2b, 0x00, 0x93, 0x2b,\n    0x00, 0xbe, 0x2b, 0x8d, 0x1a, 0x8f, 0x2b, 0xe0,\n    0x24, 0x1d, 0x81, 0x37, 0xe0, 0x48, 0x1d, 0x00,\n    0xa5, 0x05, 0x01, 0xb1, 0x05, 0x01, 0x82, 0x05,\n    0x00, 0xb6, 0x34, 0x07, 0x9a, 0x34, 0x03, 0x85,\n    0x34, 0x0a, 0x84, 0x04, 0x80, 0x19, 0x85, 0x04,\n    0x80, 0x19, 0x8d, 0x04, 0x80, 0x19, 0x80, 0x04,\n    0x00, 0x80, 0x04, 0x80, 0x19, 0x9f, 0x04, 0x80,\n    0x19, 0x89, 0x04, 0x8a, 0x37, 0x99, 0x04, 0x80,\n    0x37, 0xe0, 0x0b, 0x04, 0x80, 0x19, 0xa1, 0x04,\n    0x8d, 0x87, 0x00, 0xbb, 0x87, 0x01, 0x82, 0x87,\n    0xaf, 0x04, 0xb1, 0x91, 0x0d, 0xba, 0x63, 0x01,\n    0x82, 0x63, 0xad, 0x7b, 0x01, 0x8e, 0x7b, 0x00,\n    0x9b, 0x50, 0x01, 0x80, 0x50, 0x00, 0x8a, 0x87,\n    0x34, 0x94, 0x04, 0x00, 0x91, 0x04, 0x0a, 0x8e,\n    0x04, 0x80, 0x19, 0x9c, 0x04, 0xd0, 0x1f, 0x83,\n    0x37, 0x8e, 0x1f, 0x81, 0x19, 0x99, 0x1f, 0x83,\n    0x0b, 0x00, 0x87, 0x0b, 0x01, 0x81, 0x0b, 0x01,\n    0x95, 0x0b, 0x00, 0x86, 0x0b, 0x00, 0x80, 0x0b,\n    0x02, 0x83, 0x0b, 0x01, 0x88, 0x0b, 0x01, 0x81,\n    0x0b, 0x01, 0x83, 0x0b, 0x07, 0x80, 0x0b, 0x03,\n    0x81, 0x0b, 0x00, 0x84, 0x0b, 0x01, 0x98, 0x0b,\n    0x01, 0x82, 0x2e, 0x00, 0x85, 0x2e, 0x03, 0x81,\n    0x2e, 0x01, 0x95, 0x2e, 0x00, 0x86, 0x2e, 0x00,\n    0x81, 0x2e, 0x00, 0x81, 0x2e, 0x00, 0x81, 0x2e,\n    0x01, 0x80, 0x2e, 0x00, 0x84, 0x2e, 0x03, 0x81,\n    0x2e, 0x01, 0x82, 0x2e, 0x02, 0x80, 0x2e, 0x06,\n    0x83, 0x2e, 0x00, 0x80, 0x2e, 0x06, 0x90, 0x2e,\n    0x09, 0x82, 0x2c, 0x00, 0x88, 0x2c, 0x00, 0x82,\n    0x2c, 0x00, 0x95, 0x2c, 0x00, 0x86, 0x2c, 0x00,\n    0x81, 0x2c, 0x00, 0x84, 0x2c, 0x01, 0x89, 0x2c,\n    0x00, 0x82, 0x2c, 0x00, 0x82, 0x2c, 0x01, 0x80,\n    0x2c, 0x0e, 0x83, 0x2c, 0x01, 0x8b, 0x2c, 0x06,\n    0x86, 0x2c, 0x00, 0x82, 0x70, 0x00, 0x87, 0x70,\n    0x01, 0x81, 0x70, 0x01, 0x95, 0x70, 0x00, 0x86,\n    0x70, 0x00, 0x81, 0x70, 0x00, 0x84, 0x70, 0x01,\n    0x88, 0x70, 0x01, 0x81, 0x70, 0x01, 0x82, 0x70,\n    0x06, 0x82, 0x70, 0x03, 0x81, 0x70, 0x00, 0x84,\n    0x70, 0x01, 0x91, 0x70, 0x09, 0x81, 0x8e, 0x00,\n    0x85, 0x8e, 0x02, 0x82, 0x8e, 0x00, 0x83, 0x8e,\n    0x02, 0x81, 0x8e, 0x00, 0x80, 0x8e, 0x00, 0x81,\n    0x8e, 0x02, 0x81, 0x8e, 0x02, 0x82, 0x8e, 0x02,\n    0x8b, 0x8e, 0x03, 0x84, 0x8e, 0x02, 0x82, 0x8e,\n    0x00, 0x83, 0x8e, 0x01, 0x80, 0x8e, 0x05, 0x80,\n    0x8e, 0x0d, 0x94, 0x8e, 0x04, 0x8c, 0x90, 0x00,\n    0x82, 0x90, 0x00, 0x96, 0x90, 0x00, 0x8f, 0x90,\n    0x02, 0x87, 0x90, 0x00, 0x82, 0x90, 0x00, 0x83,\n    0x90, 0x06, 0x81, 0x90, 0x00, 0x82, 0x90, 0x04,\n    0x83, 0x90, 0x01, 0x89, 0x90, 0x06, 0x88, 0x90,\n    0x8c, 0x3c, 0x00, 0x82, 0x3c, 0x00, 0x96, 0x3c,\n    0x00, 0x89, 0x3c, 0x00, 0x84, 0x3c, 0x01, 0x88,\n    0x3c, 0x00, 0x82, 0x3c, 0x00, 0x83, 0x3c, 0x06,\n    0x81, 0x3c, 0x06, 0x80, 0x3c, 0x00, 0x83, 0x3c,\n    0x01, 0x89, 0x3c, 0x00, 0x81, 0x3c, 0x0c, 0x8c,\n    0x4f, 0x00, 0x82, 0x4f, 0x00, 0xb2, 0x4f, 0x00,\n    0x82, 0x4f, 0x00, 0x85, 0x4f, 0x03, 0x8f, 0x4f,\n    0x01, 0x99, 0x4f, 0x00, 0x82, 0x81, 0x00, 0x91,\n    0x81, 0x02, 0x97, 0x81, 0x00, 0x88, 0x81, 0x00,\n    0x80, 0x81, 0x01, 0x86, 0x81, 0x02, 0x80, 0x81,\n    0x03, 0x85, 0x81, 0x00, 0x80, 0x81, 0x00, 0x87,\n    0x81, 0x05, 0x89, 0x81, 0x01, 0x82, 0x81, 0x0b,\n    0xb9, 0x92, 0x03, 0x80, 0x19, 0x9b, 0x92, 0x24,\n    0x81, 0x44, 0x00, 0x80, 0x44, 0x00, 0x84, 0x44,\n    0x00, 0x97, 0x44, 0x00, 0x80, 0x44, 0x00, 0x96,\n    0x44, 0x01, 0x84, 0x44, 0x00, 0x80, 0x44, 0x00,\n    0x85, 0x44, 0x01, 0x89, 0x44, 0x01, 0x83, 0x44,\n    0x1f, 0xc7, 0x93, 0x00, 0xa3, 0x93, 0x03, 0xa6,\n    0x93, 0x00, 0xa3, 0x93, 0x00, 0x8e, 0x93, 0x00,\n    0x86, 0x93, 0x83, 0x19, 0x81, 0x93, 0x24, 0xe0,\n    0x3f, 0x5e, 0xa5, 0x27, 0x00, 0x80, 0x27, 0x04,\n    0x80, 0x27, 0x01, 0xaa, 0x27, 0x80, 0x19, 0x83,\n    0x27, 0xe0, 0x9f, 0x30, 0xc8, 0x26, 0x00, 0x83,\n    0x26, 0x01, 0x86, 0x26, 0x00, 0x80, 0x26, 0x00,\n    0x83, 0x26, 0x01, 0xa8, 0x26, 0x00, 0x83, 0x26,\n    0x01, 0xa0, 0x26, 0x00, 0x83, 0x26, 0x01, 0x86,\n    0x26, 0x00, 0x80, 0x26, 0x00, 0x83, 0x26, 0x01,\n    0x8e, 0x26, 0x00, 0xb8, 0x26, 0x00, 0x83, 0x26,\n    0x01, 0xc2, 0x26, 0x01, 0x9f, 0x26, 0x02, 0x99,\n    0x26, 0x05, 0xd5, 0x17, 0x01, 0x85, 0x17, 0x01,\n    0xe2, 0x1f, 0x12, 0x9c, 0x66, 0x02, 0xca, 0x7a,\n    0x82, 0x19, 0x8a, 0x7a, 0x06, 0x8c, 0x88, 0x00,\n    0x86, 0x88, 0x0a, 0x94, 0x32, 0x81, 0x19, 0x08,\n    0x93, 0x11, 0x0b, 0x8c, 0x89, 0x00, 0x82, 0x89,\n    0x00, 0x81, 0x89, 0x0b, 0xdd, 0x40, 0x01, 0x89,\n    0x40, 0x05, 0x89, 0x40, 0x05, 0x81, 0x5b, 0x81,\n    0x19, 0x80, 0x5b, 0x80, 0x19, 0x88, 0x5b, 0x00,\n    0x89, 0x5b, 0x05, 0xd8, 0x5b, 0x06, 0xaa, 0x5b,\n    0x04, 0xc5, 0x12, 0x09, 0x9e, 0x47, 0x00, 0x8b,\n    0x47, 0x03, 0x8b, 0x47, 0x03, 0x80, 0x47, 0x02,\n    0x8b, 0x47, 0x9d, 0x8a, 0x01, 0x84, 0x8a, 0x0a,\n    0xab, 0x61, 0x03, 0x99, 0x61, 0x05, 0x8a, 0x61,\n    0x02, 0x81, 0x61, 0x9f, 0x40, 0x9b, 0x10, 0x01,\n    0x81, 0x10, 0xbe, 0x8b, 0x00, 0x9c, 0x8b, 0x01,\n    0x8a, 0x8b, 0x05, 0x89, 0x8b, 0x05, 0x8d, 0x8b,\n    0x01, 0x90, 0x37, 0x3e, 0xcb, 0x07, 0x03, 0xac,\n    0x07, 0x02, 0xbf, 0x85, 0xb3, 0x0a, 0x07, 0x83,\n    0x0a, 0xb7, 0x46, 0x02, 0x8e, 0x46, 0x02, 0x82,\n    0x46, 0xaf, 0x67, 0x88, 0x1d, 0x06, 0xaa, 0x27,\n    0x01, 0x82, 0x27, 0x87, 0x85, 0x07, 0x82, 0x37,\n    0x80, 0x19, 0x8c, 0x37, 0x80, 0x19, 0x86, 0x37,\n    0x83, 0x19, 0x80, 0x37, 0x85, 0x19, 0x80, 0x37,\n    0x82, 0x19, 0x81, 0x37, 0x80, 0x19, 0x04, 0xa5,\n    0x45, 0x84, 0x2b, 0x80, 0x1d, 0xb0, 0x45, 0x84,\n    0x2b, 0x83, 0x45, 0x84, 0x2b, 0x8c, 0x45, 0x80,\n    0x1d, 0xc5, 0x45, 0x80, 0x2b, 0xb9, 0x37, 0x00,\n    0x84, 0x37, 0xe0, 0x9f, 0x45, 0x95, 0x2b, 0x01,\n    0x85, 0x2b, 0x01, 0xa5, 0x2b, 0x01, 0x85, 0x2b,\n    0x01, 0x87, 0x2b, 0x00, 0x80, 0x2b, 0x00, 0x80,\n    0x2b, 0x00, 0x80, 0x2b, 0x00, 0x9e, 0x2b, 0x01,\n    0xb4, 0x2b, 0x00, 0x8e, 0x2b, 0x00, 0x8d, 0x2b,\n    0x01, 0x85, 0x2b, 0x00, 0x92, 0x2b, 0x01, 0x82,\n    0x2b, 0x00, 0x88, 0x2b, 0x00, 0x8b, 0x19, 0x81,\n    0x37, 0xd6, 0x19, 0x00, 0x8a, 0x19, 0x80, 0x45,\n    0x01, 0x8a, 0x19, 0x80, 0x45, 0x8e, 0x19, 0x00,\n    0x8c, 0x45, 0x02, 0x9f, 0x19, 0x0f, 0xa0, 0x37,\n    0x0e, 0xa5, 0x19, 0x80, 0x2b, 0x82, 0x19, 0x81,\n    0x45, 0x85, 0x19, 0x80, 0x45, 0x9a, 0x19, 0x80,\n    0x45, 0x90, 0x19, 0xa8, 0x45, 0x82, 0x19, 0x03,\n    0xe2, 0x36, 0x19, 0x18, 0x8a, 0x19, 0x14, 0xe3,\n    0x3f, 0x19, 0xe0, 0x9f, 0x0f, 0xe2, 0x13, 0x19,\n    0x01, 0x9f, 0x19, 0x00, 0xe0, 0x08, 0x19, 0xae,\n    0x28, 0x00, 0xae, 0x28, 0x00, 0x9f, 0x45, 0xe0,\n    0x13, 0x1a, 0x04, 0x86, 0x1a, 0xa5, 0x27, 0x00,\n    0x80, 0x27, 0x04, 0x80, 0x27, 0x01, 0xb7, 0x94,\n    0x06, 0x81, 0x94, 0x0d, 0x80, 0x94, 0x96, 0x26,\n    0x08, 0x86, 0x26, 0x00, 0x86, 0x26, 0x00, 0x86,\n    0x26, 0x00, 0x86, 0x26, 0x00, 0x86, 0x26, 0x00,\n    0x86, 0x26, 0x00, 0x86, 0x26, 0x00, 0x86, 0x26,\n    0x00, 0x9f, 0x1d, 0xd2, 0x19, 0x2c, 0x99, 0x2f,\n    0x00, 0xd8, 0x2f, 0x0b, 0xe0, 0x75, 0x2f, 0x19,\n    0x8b, 0x19, 0x03, 0x84, 0x19, 0x80, 0x2f, 0x80,\n    0x19, 0x80, 0x2f, 0x98, 0x19, 0x88, 0x2f, 0x83,\n    0x37, 0x81, 0x30, 0x87, 0x19, 0x83, 0x2f, 0x83,\n    0x19, 0x00, 0xd5, 0x35, 0x01, 0x81, 0x37, 0x81,\n    0x19, 0x82, 0x35, 0x80, 0x19, 0xd9, 0x3d, 0x81,\n    0x19, 0x82, 0x3d, 0x04, 0xaa, 0x0d, 0x00, 0xdd,\n    0x30, 0x00, 0x8f, 0x19, 0x9f, 0x0d, 0xa3, 0x19,\n    0x0b, 0x8f, 0x3d, 0x9e, 0x30, 0x00, 0xbf, 0x19,\n    0x9e, 0x30, 0xd0, 0x19, 0xae, 0x3d, 0x80, 0x19,\n    0xd7, 0x3d, 0xe0, 0x47, 0x19, 0xf0, 0x09, 0x5f,\n    0x2f, 0xbf, 0x19, 0xf0, 0x41, 0x9c, 0x2f, 0x02,\n    0xe4, 0x2c, 0x9b, 0x02, 0xb6, 0x9b, 0x08, 0xaf,\n    0x4a, 0xe0, 0xcb, 0x97, 0x13, 0xdf, 0x1d, 0xd7,\n    0x08, 0x07, 0xa1, 0x19, 0xe0, 0x05, 0x45, 0x82,\n    0x19, 0xb4, 0x45, 0x01, 0x88, 0x45, 0x29, 0x8a,\n    0x45, 0xac, 0x86, 0x02, 0x89, 0x19, 0x05, 0xb7,\n    0x76, 0x07, 0xc5, 0x7c, 0x07, 0x8b, 0x7c, 0x05,\n    0x9f, 0x1f, 0xad, 0x3e, 0x80, 0x19, 0x80, 0x3e,\n    0xa3, 0x79, 0x0a, 0x80, 0x79, 0x9c, 0x30, 0x02,\n    0xcd, 0x3a, 0x00, 0x80, 0x19, 0x89, 0x3a, 0x03,\n    0x81, 0x3a, 0x9e, 0x5e, 0x00, 0xb6, 0x16, 0x08,\n    0x8d, 0x16, 0x01, 0x89, 0x16, 0x01, 0x83, 0x16,\n    0x9f, 0x5e, 0xc2, 0x8c, 0x17, 0x84, 0x8c, 0x96,\n    0x55, 0x09, 0x85, 0x26, 0x01, 0x85, 0x26, 0x01,\n    0x85, 0x26, 0x08, 0x86, 0x26, 0x00, 0x86, 0x26,\n    0x00, 0xaa, 0x45, 0x80, 0x19, 0x88, 0x45, 0x80,\n    0x2b, 0x83, 0x45, 0x81, 0x19, 0x03, 0xcf, 0x17,\n    0xad, 0x55, 0x01, 0x89, 0x55, 0x05, 0xf0, 0x1b,\n    0x43, 0x30, 0x0b, 0x96, 0x30, 0x03, 0xb0, 0x30,\n    0x70, 0x10, 0xa3, 0xe1, 0x0d, 0x2f, 0x01, 0xe0,\n    0x09, 0x2f, 0x25, 0x86, 0x45, 0x0b, 0x84, 0x05,\n    0x04, 0x99, 0x34, 0x00, 0x84, 0x34, 0x00, 0x80,\n    0x34, 0x00, 0x81, 0x34, 0x00, 0x81, 0x34, 0x00,\n    0x89, 0x34, 0xe0, 0x11, 0x04, 0x10, 0xe1, 0x0a,\n    0x04, 0x81, 0x19, 0x0f, 0xbf, 0x04, 0x01, 0xb5,\n    0x04, 0x27, 0x8d, 0x04, 0x01, 0x8f, 0x37, 0x89,\n    0x19, 0x05, 0x8d, 0x37, 0x81, 0x1d, 0xa2, 0x19,\n    0x00, 0x92, 0x19, 0x00, 0x83, 0x19, 0x03, 0x84,\n    0x04, 0x00, 0xe0, 0x26, 0x04, 0x01, 0x80, 0x19,\n    0x00, 0x9f, 0x19, 0x99, 0x45, 0x85, 0x19, 0x99,\n    0x45, 0x8a, 0x19, 0x89, 0x3d, 0x80, 0x19, 0xac,\n    0x3d, 0x81, 0x19, 0x9e, 0x30, 0x02, 0x85, 0x30,\n    0x01, 0x85, 0x30, 0x01, 0x85, 0x30, 0x01, 0x82,\n    0x30, 0x02, 0x86, 0x19, 0x00, 0x86, 0x19, 0x09,\n    0x84, 0x19, 0x01, 0x8b, 0x49, 0x00, 0x99, 0x49,\n    0x00, 0x92, 0x49, 0x00, 0x81, 0x49, 0x00, 0x8e,\n    0x49, 0x01, 0x8d, 0x49, 0x21, 0xe0, 0x1a, 0x49,\n    0x04, 0x82, 0x19, 0x03, 0xac, 0x19, 0x02, 0x88,\n    0x19, 0xce, 0x2b, 0x00, 0x8c, 0x19, 0x02, 0x80,\n    0x2b, 0x2e, 0xac, 0x19, 0x80, 0x37, 0x60, 0x21,\n    0x9c, 0x4b, 0x02, 0xb0, 0x13, 0x0e, 0x80, 0x37,\n    0x9a, 0x19, 0x03, 0xa3, 0x69, 0x08, 0x82, 0x69,\n    0x9a, 0x29, 0x04, 0xaa, 0x6b, 0x04, 0x9d, 0x96,\n    0x00, 0x80, 0x96, 0xa3, 0x6c, 0x03, 0x8d, 0x6c,\n    0x29, 0xcf, 0x1e, 0xaf, 0x7e, 0x9d, 0x72, 0x01,\n    0x89, 0x72, 0x05, 0xa3, 0x71, 0x03, 0xa3, 0x71,\n    0x03, 0xa7, 0x24, 0x07, 0xb3, 0x14, 0x0a, 0x80,\n    0x14, 0x60, 0x2f, 0xe0, 0xd6, 0x48, 0x08, 0x95,\n    0x48, 0x09, 0x87, 0x48, 0x60, 0x37, 0x85, 0x1c,\n    0x01, 0x80, 0x1c, 0x00, 0xab, 0x1c, 0x00, 0x81,\n    0x1c, 0x02, 0x80, 0x1c, 0x01, 0x80, 0x1c, 0x95,\n    0x36, 0x00, 0x88, 0x36, 0x9f, 0x74, 0x9e, 0x5f,\n    0x07, 0x88, 0x5f, 0x2f, 0x92, 0x33, 0x00, 0x81,\n    0x33, 0x04, 0x84, 0x33, 0x9b, 0x77, 0x02, 0x80,\n    0x77, 0x99, 0x4c, 0x04, 0x80, 0x4c, 0x3f, 0x9f,\n    0x58, 0x97, 0x57, 0x03, 0x93, 0x57, 0x01, 0xad,\n    0x57, 0x83, 0x3f, 0x00, 0x81, 0x3f, 0x04, 0x87,\n    0x3f, 0x00, 0x82, 0x3f, 0x00, 0x9c, 0x3f, 0x01,\n    0x82, 0x3f, 0x03, 0x89, 0x3f, 0x06, 0x88, 0x3f,\n    0x06, 0x9f, 0x6e, 0x9f, 0x6a, 0x1f, 0xa6, 0x51,\n    0x03, 0x8b, 0x51, 0x08, 0xb5, 0x06, 0x02, 0x86,\n    0x06, 0x95, 0x39, 0x01, 0x87, 0x39, 0x92, 0x38,\n    0x04, 0x87, 0x38, 0x91, 0x78, 0x06, 0x83, 0x78,\n    0x0b, 0x86, 0x78, 0x4f, 0xc8, 0x6f, 0x36, 0xb2,\n    0x68, 0x0c, 0xb2, 0x68, 0x06, 0x85, 0x68, 0xa7,\n    0x31, 0x07, 0x89, 0x31, 0x60, 0xc5, 0x9e, 0x04,\n    0x00, 0xa9, 0x9a, 0x00, 0x82, 0x9a, 0x01, 0x81,\n    0x9a, 0x4d, 0xa7, 0x6d, 0x07, 0xa9, 0x82, 0x55,\n    0x9b, 0x18, 0x13, 0x96, 0x25, 0x08, 0xcd, 0x0e,\n    0x03, 0x9d, 0x0e, 0x0e, 0x80, 0x0e, 0xc1, 0x3b,\n    0x0a, 0x80, 0x3b, 0x01, 0x98, 0x83, 0x06, 0x89,\n    0x83, 0x05, 0xb4, 0x15, 0x00, 0x91, 0x15, 0x07,\n    0xa6, 0x4e, 0x08, 0xdf, 0x7d, 0x00, 0x93, 0x81,\n    0x0a, 0x91, 0x41, 0x00, 0xab, 0x41, 0x40, 0x86,\n    0x5d, 0x00, 0x80, 0x5d, 0x00, 0x83, 0x5d, 0x00,\n    0x8e, 0x5d, 0x00, 0x8a, 0x5d, 0x05, 0xba, 0x43,\n    0x04, 0x89, 0x43, 0x05, 0x83, 0x2a, 0x00, 0x87,\n    0x2a, 0x01, 0x81, 0x2a, 0x01, 0x95, 0x2a, 0x00,\n    0x86, 0x2a, 0x00, 0x81, 0x2a, 0x00, 0x84, 0x2a,\n    0x00, 0x80, 0x37, 0x88, 0x2a, 0x01, 0x81, 0x2a,\n    0x01, 0x82, 0x2a, 0x01, 0x80, 0x2a, 0x05, 0x80,\n    0x2a, 0x04, 0x86, 0x2a, 0x01, 0x86, 0x2a, 0x02,\n    0x84, 0x2a, 0x60, 0x2a, 0xdb, 0x62, 0x00, 0x84,\n    0x62, 0x1d, 0xc7, 0x95, 0x07, 0x89, 0x95, 0x60,\n    0x45, 0xb5, 0x7f, 0x01, 0xa5, 0x7f, 0x21, 0xc4,\n    0x5a, 0x0a, 0x89, 0x5a, 0x05, 0x8c, 0x5b, 0x12,\n    0xb8, 0x8d, 0x06, 0x89, 0x8d, 0x35, 0x9a, 0x02,\n    0x01, 0x8e, 0x02, 0x03, 0x8f, 0x02, 0x60, 0x5f,\n    0xbb, 0x21, 0x60, 0x03, 0xd2, 0x99, 0x0b, 0x80,\n    0x99, 0x86, 0x20, 0x01, 0x80, 0x20, 0x01, 0x87,\n    0x20, 0x00, 0x81, 0x20, 0x00, 0x9d, 0x20, 0x00,\n    0x81, 0x20, 0x01, 0x8b, 0x20, 0x08, 0x89, 0x20,\n    0x45, 0x87, 0x60, 0x01, 0xad, 0x60, 0x01, 0x8a,\n    0x60, 0x1a, 0xc7, 0x9c, 0x07, 0xd2, 0x84, 0x1c,\n    0xb8, 0x75, 0x60, 0xa6, 0x88, 0x0c, 0x00, 0xac,\n    0x0c, 0x00, 0x8d, 0x0c, 0x09, 0x9c, 0x0c, 0x02,\n    0x9f, 0x52, 0x01, 0x95, 0x52, 0x00, 0x8d, 0x52,\n    0x48, 0x86, 0x53, 0x00, 0x81, 0x53, 0x00, 0xab,\n    0x53, 0x02, 0x80, 0x53, 0x00, 0x81, 0x53, 0x00,\n    0x88, 0x53, 0x07, 0x89, 0x53, 0x05, 0x85, 0x2d,\n    0x00, 0x81, 0x2d, 0x00, 0xa4, 0x2d, 0x00, 0x81,\n    0x2d, 0x00, 0x85, 0x2d, 0x06, 0x89, 0x2d, 0x60,\n    0xd5, 0x98, 0x4d, 0x60, 0x56, 0x80, 0x4a, 0x0e,\n    0xb1, 0x8e, 0x0c, 0x80, 0x8e, 0xe3, 0x39, 0x1b,\n    0x60, 0x05, 0xe0, 0x0e, 0x1b, 0x00, 0x84, 0x1b,\n    0x0a, 0xe0, 0x63, 0x1b, 0x6a, 0x5b, 0xe3, 0xce,\n    0x23, 0x00, 0x88, 0x23, 0x6f, 0x66, 0xe1, 0xe6,\n    0x03, 0x70, 0x11, 0x58, 0xe1, 0xd8, 0x08, 0x06,\n    0x9e, 0x5c, 0x00, 0x89, 0x5c, 0x03, 0x81, 0x5c,\n    0x5f, 0x9d, 0x09, 0x01, 0x85, 0x09, 0x09, 0xc5,\n    0x73, 0x09, 0x89, 0x73, 0x00, 0x86, 0x73, 0x00,\n    0x94, 0x73, 0x04, 0x92, 0x73, 0x62, 0x4f, 0xda,\n    0x54, 0x60, 0x04, 0xca, 0x59, 0x03, 0xb8, 0x59,\n    0x06, 0x90, 0x59, 0x3f, 0x80, 0x8f, 0x80, 0x64,\n    0x81, 0x19, 0x80, 0x42, 0x0a, 0x81, 0x2f, 0x0d,\n    0xf0, 0x07, 0x97, 0x8f, 0x07, 0xe2, 0x9f, 0x8f,\n    0xe1, 0x75, 0x42, 0x29, 0x88, 0x8f, 0x70, 0x12,\n    0x96, 0x80, 0x3d, 0xe0, 0xbd, 0x35, 0x30, 0x82,\n    0x35, 0x10, 0x83, 0x3d, 0x07, 0xe1, 0x2b, 0x64,\n    0x68, 0xa3, 0xe0, 0x0a, 0x22, 0x04, 0x8c, 0x22,\n    0x02, 0x88, 0x22, 0x06, 0x89, 0x22, 0x01, 0x83,\n    0x22, 0x83, 0x19, 0x70, 0x02, 0xfb, 0xe0, 0x95,\n    0x19, 0x09, 0xa6, 0x19, 0x01, 0xbd, 0x19, 0x82,\n    0x37, 0x90, 0x19, 0x87, 0x37, 0x81, 0x19, 0x86,\n    0x37, 0x9d, 0x19, 0x83, 0x37, 0xba, 0x19, 0x16,\n    0xc5, 0x2b, 0x60, 0x39, 0x93, 0x19, 0x0b, 0xd6,\n    0x19, 0x08, 0x98, 0x19, 0x60, 0x26, 0xd4, 0x19,\n    0x00, 0xc6, 0x19, 0x00, 0x81, 0x19, 0x01, 0x80,\n    0x19, 0x01, 0x81, 0x19, 0x01, 0x83, 0x19, 0x00,\n    0x8b, 0x19, 0x00, 0x80, 0x19, 0x00, 0x86, 0x19,\n    0x00, 0xc0, 0x19, 0x00, 0x83, 0x19, 0x01, 0x87,\n    0x19, 0x00, 0x86, 0x19, 0x00, 0x9b, 0x19, 0x00,\n    0x83, 0x19, 0x00, 0x84, 0x19, 0x00, 0x80, 0x19,\n    0x02, 0x86, 0x19, 0x00, 0xe0, 0xf3, 0x19, 0x01,\n    0xe0, 0xc3, 0x19, 0x01, 0xb1, 0x19, 0xe2, 0x2b,\n    0x80, 0x0e, 0x84, 0x80, 0x00, 0x8e, 0x80, 0x64,\n    0xef, 0x86, 0x28, 0x00, 0x90, 0x28, 0x01, 0x86,\n    0x28, 0x00, 0x81, 0x28, 0x00, 0x84, 0x28, 0x60,\n    0x74, 0xac, 0x65, 0x02, 0x8d, 0x65, 0x01, 0x89,\n    0x65, 0x03, 0x81, 0x65, 0x61, 0x0f, 0xb9, 0x98,\n    0x04, 0x80, 0x98, 0x64, 0x9f, 0xe0, 0x64, 0x56,\n    0x01, 0x8f, 0x56, 0x28, 0xcb, 0x01, 0x03, 0x89,\n    0x01, 0x03, 0x81, 0x01, 0x62, 0xb0, 0xc3, 0x19,\n    0x4b, 0xbc, 0x19, 0x60, 0x61, 0x83, 0x04, 0x00,\n    0x9a, 0x04, 0x00, 0x81, 0x04, 0x00, 0x80, 0x04,\n    0x01, 0x80, 0x04, 0x00, 0x89, 0x04, 0x00, 0x83,\n    0x04, 0x00, 0x80, 0x04, 0x00, 0x80, 0x04, 0x05,\n    0x80, 0x04, 0x03, 0x80, 0x04, 0x00, 0x80, 0x04,\n    0x00, 0x80, 0x04, 0x00, 0x82, 0x04, 0x00, 0x81,\n    0x04, 0x00, 0x80, 0x04, 0x01, 0x80, 0x04, 0x00,\n    0x80, 0x04, 0x00, 0x80, 0x04, 0x00, 0x80, 0x04,\n    0x00, 0x80, 0x04, 0x00, 0x81, 0x04, 0x00, 0x80,\n    0x04, 0x01, 0x83, 0x04, 0x00, 0x86, 0x04, 0x00,\n    0x83, 0x04, 0x00, 0x83, 0x04, 0x00, 0x80, 0x04,\n    0x00, 0x89, 0x04, 0x00, 0x90, 0x04, 0x04, 0x82,\n    0x04, 0x00, 0x84, 0x04, 0x00, 0x90, 0x04, 0x33,\n    0x81, 0x04, 0x60, 0xad, 0xab, 0x19, 0x03, 0xe0,\n    0x03, 0x19, 0x0b, 0x8e, 0x19, 0x01, 0x8e, 0x19,\n    0x00, 0x8e, 0x19, 0x00, 0xa4, 0x19, 0x09, 0xe0,\n    0x4d, 0x19, 0x37, 0x99, 0x19, 0x80, 0x35, 0x81,\n    0x19, 0x0c, 0xab, 0x19, 0x03, 0x88, 0x19, 0x06,\n    0x81, 0x19, 0x0d, 0x85, 0x19, 0x60, 0x39, 0xe3,\n    0x77, 0x19, 0x07, 0x8c, 0x19, 0x02, 0x8c, 0x19,\n    0x02, 0xe0, 0x13, 0x19, 0x0b, 0xd8, 0x19, 0x06,\n    0x8b, 0x19, 0x13, 0x8b, 0x19, 0x03, 0xb7, 0x19,\n    0x07, 0x89, 0x19, 0x05, 0xa7, 0x19, 0x07, 0x9d,\n    0x19, 0x01, 0x81, 0x19, 0x4d, 0xe0, 0x18, 0x19,\n    0x00, 0xd1, 0x19, 0x00, 0xe0, 0x26, 0x19, 0x0b,\n    0x8d, 0x19, 0x01, 0x84, 0x19, 0x02, 0x82, 0x19,\n    0x04, 0x86, 0x19, 0x08, 0x98, 0x19, 0x06, 0x86,\n    0x19, 0x08, 0x82, 0x19, 0x0c, 0x86, 0x19, 0x28,\n    0xe0, 0x32, 0x19, 0x00, 0xb6, 0x19, 0x24, 0x89,\n    0x19, 0x63, 0xa5, 0xf0, 0x96, 0x7d, 0x2f, 0x21,\n    0xef, 0xd4, 0x2f, 0x0a, 0xe0, 0x7d, 0x2f, 0x01,\n    0xf0, 0x06, 0x21, 0x2f, 0x0d, 0xf0, 0x0c, 0xd0,\n    0x2f, 0x6b, 0xbe, 0xe1, 0xbd, 0x2f, 0x65, 0x81,\n    0xf0, 0x02, 0xea, 0x2f, 0x7a, 0xdc, 0x55, 0x80,\n    0x19, 0x1d, 0xdf, 0x19, 0x60, 0x1f, 0xe0, 0x8f,\n    0x37,\n};\n\nstatic const uint8_t unicode_script_ext_table[799] = {\n    0x82, 0xc1, 0x00, 0x00, 0x01, 0x2b, 0x01, 0x00,\n    0x00, 0x01, 0x2b, 0x1c, 0x00, 0x0c, 0x01, 0x45,\n    0x80, 0x92, 0x00, 0x00, 0x02, 0x1d, 0x6b, 0x00,\n    0x02, 0x1d, 0x28, 0x01, 0x02, 0x1d, 0x45, 0x00,\n    0x02, 0x1d, 0x28, 0x81, 0x03, 0x00, 0x00, 0x05,\n    0x04, 0x31, 0x87, 0x91, 0x9a, 0x0d, 0x00, 0x00,\n    0x05, 0x04, 0x31, 0x87, 0x91, 0x9a, 0x00, 0x03,\n    0x04, 0x87, 0x91, 0x01, 0x00, 0x00, 0x05, 0x04,\n    0x31, 0x87, 0x91, 0x9a, 0x1f, 0x00, 0x00, 0x08,\n    0x01, 0x04, 0x50, 0x51, 0x78, 0x31, 0x82, 0x87,\n    0x09, 0x00, 0x0a, 0x02, 0x04, 0x87, 0x09, 0x00,\n    0x09, 0x03, 0x04, 0x91, 0x9a, 0x05, 0x00, 0x00,\n    0x02, 0x04, 0x87, 0x62, 0x00, 0x00, 0x02, 0x04,\n    0x31, 0x81, 0xfb, 0x00, 0x00, 0x0d, 0x0b, 0x1f,\n    0x2a, 0x2c, 0x2e, 0x3c, 0x45, 0x4f, 0x70, 0x7d,\n    0x8e, 0x90, 0x95, 0x00, 0x0c, 0x0b, 0x1f, 0x2a,\n    0x2c, 0x2e, 0x3c, 0x45, 0x4f, 0x70, 0x8e, 0x90,\n    0x95, 0x10, 0x00, 0x00, 0x14, 0x0b, 0x1f, 0x21,\n    0x2d, 0x53, 0x2a, 0x2c, 0x2e, 0x3c, 0x4e, 0x4f,\n    0x60, 0x70, 0x43, 0x81, 0x86, 0x8d, 0x8e, 0x90,\n    0x95, 0x00, 0x15, 0x0b, 0x1f, 0x21, 0x2d, 0x53,\n    0x2a, 0x2c, 0x2e, 0x3c, 0x47, 0x4e, 0x4f, 0x60,\n    0x70, 0x43, 0x81, 0x86, 0x8d, 0x8e, 0x90, 0x95,\n    0x09, 0x04, 0x1f, 0x21, 0x3b, 0x4e, 0x75, 0x00,\n    0x09, 0x03, 0x0b, 0x15, 0x86, 0x75, 0x00, 0x09,\n    0x02, 0x2e, 0x5d, 0x75, 0x00, 0x09, 0x02, 0x2c,\n    0x41, 0x80, 0x75, 0x00, 0x0d, 0x02, 0x2a, 0x8e,\n    0x80, 0x71, 0x00, 0x09, 0x02, 0x3c, 0x60, 0x82,\n    0xcf, 0x00, 0x09, 0x03, 0x15, 0x5e, 0x8a, 0x80,\n    0x30, 0x00, 0x00, 0x02, 0x27, 0x45, 0x85, 0xb8,\n    0x00, 0x01, 0x04, 0x11, 0x32, 0x89, 0x88, 0x80,\n    0x4a, 0x00, 0x01, 0x02, 0x5b, 0x76, 0x00, 0x00,\n    0x00, 0x02, 0x5b, 0x76, 0x84, 0x49, 0x00, 0x00,\n    0x04, 0x0b, 0x1f, 0x2a, 0x3c, 0x00, 0x01, 0x1f,\n    0x00, 0x04, 0x0b, 0x1f, 0x2a, 0x3c, 0x00, 0x02,\n    0x1f, 0x2a, 0x00, 0x01, 0x1f, 0x01, 0x02, 0x0b,\n    0x1f, 0x00, 0x02, 0x1f, 0x7d, 0x00, 0x02, 0x0b,\n    0x1f, 0x00, 0x02, 0x1f, 0x7d, 0x00, 0x06, 0x1f,\n    0x3c, 0x4f, 0x70, 0x8e, 0x90, 0x00, 0x01, 0x1f,\n    0x01, 0x02, 0x1f, 0x7d, 0x01, 0x01, 0x1f, 0x00,\n    0x02, 0x1f, 0x7d, 0x00, 0x02, 0x0b, 0x1f, 0x06,\n    0x01, 0x1f, 0x00, 0x02, 0x1f, 0x60, 0x00, 0x02,\n    0x0b, 0x1f, 0x01, 0x01, 0x1f, 0x00, 0x02, 0x0b,\n    0x1f, 0x03, 0x01, 0x1f, 0x00, 0x08, 0x0b, 0x1f,\n    0x2a, 0x3c, 0x60, 0x70, 0x90, 0x95, 0x00, 0x02,\n    0x1f, 0x2a, 0x00, 0x03, 0x1f, 0x2a, 0x3c, 0x01,\n    0x02, 0x0b, 0x1f, 0x00, 0x01, 0x0b, 0x01, 0x02,\n    0x1f, 0x2a, 0x00, 0x01, 0x60, 0x80, 0x44, 0x00,\n    0x01, 0x01, 0x2b, 0x35, 0x00, 0x00, 0x02, 0x1d,\n    0x87, 0x81, 0xb5, 0x00, 0x00, 0x02, 0x45, 0x5b,\n    0x80, 0x3f, 0x00, 0x00, 0x03, 0x1f, 0x2a, 0x45,\n    0x8c, 0xd1, 0x00, 0x00, 0x02, 0x1d, 0x28, 0x81,\n    0x3c, 0x00, 0x01, 0x06, 0x0d, 0x30, 0x2f, 0x35,\n    0x3d, 0x9b, 0x00, 0x05, 0x0d, 0x30, 0x2f, 0x35,\n    0x3d, 0x01, 0x00, 0x00, 0x01, 0x2f, 0x00, 0x00,\n    0x09, 0x06, 0x0d, 0x30, 0x2f, 0x35, 0x3d, 0x9b,\n    0x00, 0x00, 0x00, 0x05, 0x0d, 0x30, 0x2f, 0x35,\n    0x3d, 0x07, 0x06, 0x0d, 0x30, 0x2f, 0x35, 0x3d,\n    0x9b, 0x03, 0x05, 0x0d, 0x30, 0x2f, 0x35, 0x3d,\n    0x09, 0x00, 0x03, 0x02, 0x0d, 0x2f, 0x01, 0x00,\n    0x00, 0x05, 0x0d, 0x30, 0x2f, 0x35, 0x3d, 0x04,\n    0x02, 0x35, 0x3d, 0x00, 0x00, 0x00, 0x05, 0x0d,\n    0x30, 0x2f, 0x35, 0x3d, 0x03, 0x00, 0x01, 0x03,\n    0x2f, 0x35, 0x3d, 0x01, 0x01, 0x2f, 0x58, 0x00,\n    0x03, 0x02, 0x35, 0x3d, 0x02, 0x00, 0x00, 0x02,\n    0x35, 0x3d, 0x59, 0x00, 0x00, 0x06, 0x0d, 0x30,\n    0x2f, 0x35, 0x3d, 0x9b, 0x00, 0x02, 0x35, 0x3d,\n    0x80, 0x12, 0x00, 0x0f, 0x01, 0x2f, 0x1f, 0x00,\n    0x23, 0x01, 0x2f, 0x3b, 0x00, 0x27, 0x01, 0x2f,\n    0x37, 0x00, 0x30, 0x01, 0x2f, 0x0e, 0x00, 0x0b,\n    0x01, 0x2f, 0x32, 0x00, 0x00, 0x01, 0x2f, 0x57,\n    0x00, 0x18, 0x01, 0x2f, 0x09, 0x00, 0x04, 0x01,\n    0x2f, 0x5f, 0x00, 0x1e, 0x01, 0x2f, 0xc0, 0x31,\n    0xef, 0x00, 0x00, 0x02, 0x1d, 0x28, 0x80, 0x0f,\n    0x00, 0x07, 0x02, 0x2f, 0x45, 0x80, 0xa7, 0x00,\n    0x02, 0x0e, 0x1f, 0x21, 0x2c, 0x2e, 0x41, 0x3c,\n    0x3b, 0x4e, 0x4f, 0x5a, 0x60, 0x43, 0x8d, 0x95,\n    0x02, 0x0d, 0x1f, 0x21, 0x2c, 0x2e, 0x41, 0x3c,\n    0x3b, 0x4e, 0x5a, 0x60, 0x43, 0x8d, 0x95, 0x03,\n    0x0b, 0x1f, 0x21, 0x2c, 0x2e, 0x41, 0x3b, 0x4e,\n    0x5a, 0x43, 0x8d, 0x95, 0x80, 0x36, 0x00, 0x00,\n    0x02, 0x0b, 0x1f, 0x00, 0x00, 0x00, 0x02, 0x1f,\n    0x8e, 0x39, 0x00, 0x00, 0x03, 0x3e, 0x45, 0x5e,\n    0x80, 0x1f, 0x00, 0x00, 0x02, 0x10, 0x3a, 0xc0,\n    0x13, 0xa1, 0x00, 0x00, 0x02, 0x04, 0x91, 0x09,\n    0x00, 0x00, 0x02, 0x04, 0x91, 0x46, 0x00, 0x01,\n    0x05, 0x0d, 0x30, 0x2f, 0x35, 0x3d, 0x80, 0x99,\n    0x00, 0x04, 0x06, 0x0d, 0x30, 0x2f, 0x35, 0x3d,\n    0x9b, 0x09, 0x00, 0x00, 0x02, 0x35, 0x3d, 0x2c,\n    0x00, 0x01, 0x02, 0x35, 0x3d, 0x80, 0xdf, 0x00,\n    0x02, 0x02, 0x1c, 0x49, 0x03, 0x00, 0x2c, 0x03,\n    0x1c, 0x48, 0x49, 0x02, 0x00, 0x08, 0x02, 0x1c,\n    0x49, 0x81, 0x1f, 0x00, 0x1b, 0x02, 0x04, 0x1a,\n    0x8f, 0x84, 0x00, 0x00, 0x02, 0x2a, 0x8e, 0x00,\n    0x00, 0x00, 0x02, 0x2a, 0x8e, 0x36, 0x00, 0x01,\n    0x02, 0x2a, 0x8e, 0x8c, 0x12, 0x00, 0x01, 0x02,\n    0x2a, 0x8e, 0x00, 0x00, 0x00, 0x02, 0x2a, 0x8e,\n    0xc0, 0x5c, 0x4b, 0x00, 0x03, 0x01, 0x22, 0x96,\n    0x3b, 0x00, 0x11, 0x01, 0x2f, 0x9e, 0x5d, 0x00,\n    0x01, 0x01, 0x2f, 0xce, 0xcd, 0x2d, 0x00,\n};\n\nstatic const uint8_t unicode_prop_Hyphen_table[28] = {\n    0xac, 0x80, 0xfe, 0x80, 0x44, 0xdb, 0x80, 0x52,\n    0x7a, 0x80, 0x48, 0x08, 0x81, 0x4e, 0x04, 0x80,\n    0x42, 0xe2, 0x80, 0x60, 0xcd, 0x66, 0x80, 0x40,\n    0xa8, 0x80, 0xd6, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Other_Math_table[200] = {\n    0xdd, 0x80, 0x43, 0x70, 0x11, 0x80, 0x99, 0x09,\n    0x81, 0x5c, 0x1f, 0x80, 0x9a, 0x82, 0x8a, 0x80,\n    0x9f, 0x83, 0x97, 0x81, 0x8d, 0x81, 0xc0, 0x8c,\n    0x18, 0x11, 0x1c, 0x91, 0x03, 0x01, 0x89, 0x00,\n    0x14, 0x28, 0x11, 0x09, 0x02, 0x05, 0x13, 0x24,\n    0xca, 0x21, 0x18, 0x08, 0x08, 0x00, 0x21, 0x0b,\n    0x0b, 0x91, 0x09, 0x00, 0x06, 0x00, 0x29, 0x41,\n    0x21, 0x83, 0x40, 0xa7, 0x08, 0x80, 0x97, 0x80,\n    0x90, 0x80, 0x41, 0xbc, 0x81, 0x8b, 0x88, 0x24,\n    0x21, 0x09, 0x14, 0x8d, 0x00, 0x01, 0x85, 0x97,\n    0x81, 0xb8, 0x00, 0x80, 0x9c, 0x83, 0x88, 0x81,\n    0x41, 0x55, 0x81, 0x9e, 0x89, 0x41, 0x92, 0x95,\n    0xbe, 0x83, 0x9f, 0x81, 0x60, 0xd4, 0x62, 0x00,\n    0x03, 0x80, 0x40, 0xd2, 0x00, 0x80, 0x60, 0xd4,\n    0xc0, 0xd4, 0x80, 0xc6, 0x01, 0x08, 0x09, 0x0b,\n    0x80, 0x8b, 0x00, 0x06, 0x80, 0xc0, 0x03, 0x0f,\n    0x06, 0x80, 0x9b, 0x03, 0x04, 0x00, 0x16, 0x80,\n    0x41, 0x53, 0x81, 0x98, 0x80, 0x98, 0x80, 0x9e,\n    0x80, 0x98, 0x80, 0x9e, 0x80, 0x98, 0x80, 0x9e,\n    0x80, 0x98, 0x80, 0x9e, 0x80, 0x98, 0x07, 0x81,\n    0xb1, 0x55, 0xff, 0x18, 0x9a, 0x01, 0x00, 0x08,\n    0x80, 0x89, 0x03, 0x00, 0x00, 0x28, 0x18, 0x00,\n    0x00, 0x02, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00,\n    0x00, 0x01, 0x00, 0x0b, 0x06, 0x03, 0x03, 0x00,\n    0x80, 0x89, 0x80, 0x90, 0x22, 0x04, 0x80, 0x90,\n};\n\nstatic const uint8_t unicode_prop_Other_Alphabetic_table[411] = {\n    0x43, 0x44, 0x80, 0x42, 0x69, 0x8d, 0x00, 0x01,\n    0x01, 0x00, 0xc7, 0x8a, 0xaf, 0x8c, 0x06, 0x8f,\n    0x80, 0xe4, 0x33, 0x19, 0x0b, 0x80, 0xa2, 0x80,\n    0x9d, 0x8f, 0xe5, 0x8a, 0xe4, 0x0a, 0x88, 0x02,\n    0x03, 0x40, 0xa6, 0x8b, 0x16, 0x85, 0x93, 0xb5,\n    0x09, 0x8e, 0x01, 0x22, 0x89, 0x81, 0x9c, 0x82,\n    0xb9, 0x31, 0x09, 0x81, 0x89, 0x80, 0x89, 0x81,\n    0x9c, 0x82, 0xb9, 0x23, 0x09, 0x0b, 0x80, 0x9d,\n    0x0a, 0x80, 0x8a, 0x82, 0xb9, 0x38, 0x10, 0x81,\n    0x94, 0x81, 0x95, 0x13, 0x82, 0xb9, 0x31, 0x09,\n    0x81, 0x88, 0x81, 0x89, 0x81, 0x9d, 0x80, 0xba,\n    0x22, 0x10, 0x82, 0x89, 0x80, 0xa7, 0x83, 0xb9,\n    0x30, 0x10, 0x17, 0x81, 0x8a, 0x81, 0x9c, 0x82,\n    0xb9, 0x30, 0x10, 0x17, 0x81, 0x8a, 0x81, 0x9b,\n    0x83, 0xb9, 0x30, 0x10, 0x82, 0x89, 0x80, 0x89,\n    0x81, 0x9c, 0x82, 0xca, 0x28, 0x00, 0x87, 0x91,\n    0x81, 0xbc, 0x01, 0x86, 0x91, 0x80, 0xe2, 0x01,\n    0x28, 0x81, 0x8f, 0x80, 0x40, 0xa2, 0x90, 0x8a,\n    0x8a, 0x80, 0xa3, 0xed, 0x8b, 0x00, 0x0b, 0x96,\n    0x1b, 0x10, 0x11, 0x32, 0x83, 0x8c, 0x8b, 0x00,\n    0x89, 0x83, 0x46, 0x73, 0x81, 0x9d, 0x81, 0x9d,\n    0x81, 0x9d, 0x81, 0xc1, 0x92, 0x40, 0xbb, 0x81,\n    0xa1, 0x80, 0xf5, 0x8b, 0x83, 0x88, 0x40, 0xdd,\n    0x84, 0xb8, 0x89, 0x81, 0x93, 0xc9, 0x81, 0xbe,\n    0x84, 0xaf, 0x8e, 0xbb, 0x82, 0x9d, 0x88, 0x09,\n    0xb8, 0x8a, 0xb1, 0x92, 0x41, 0xaf, 0x8d, 0x46,\n    0xc0, 0xb3, 0x48, 0xf5, 0x9f, 0x60, 0x78, 0x73,\n    0x87, 0xa1, 0x81, 0x41, 0x61, 0x07, 0x80, 0x96,\n    0x84, 0xd7, 0x81, 0xb1, 0x8f, 0x00, 0xb8, 0x80,\n    0xa5, 0x84, 0x9b, 0x8b, 0xac, 0x83, 0xaf, 0x8b,\n    0xa4, 0x80, 0xc2, 0x8d, 0x8b, 0x07, 0x81, 0xac,\n    0x82, 0xb1, 0x00, 0x11, 0x0c, 0x80, 0xab, 0x24,\n    0x80, 0x40, 0xec, 0x87, 0x60, 0x4f, 0x32, 0x80,\n    0x48, 0x56, 0x84, 0x46, 0x85, 0x10, 0x0c, 0x83,\n    0x43, 0x13, 0x83, 0x41, 0x82, 0x81, 0x41, 0x52,\n    0x82, 0xb4, 0x8d, 0xbb, 0x80, 0xac, 0x88, 0xc6,\n    0x82, 0xa3, 0x8b, 0x91, 0x81, 0xb8, 0x82, 0xaf,\n    0x8c, 0x8d, 0x81, 0xdb, 0x88, 0x08, 0x28, 0x40,\n    0x9f, 0x89, 0x96, 0x83, 0xb9, 0x31, 0x09, 0x81,\n    0x89, 0x80, 0x89, 0x81, 0x40, 0xd0, 0x8c, 0x02,\n    0xe9, 0x91, 0x40, 0xec, 0x31, 0x86, 0x9c, 0x81,\n    0xd1, 0x8e, 0x00, 0xe9, 0x8a, 0xe6, 0x8d, 0x41,\n    0x00, 0x8c, 0x40, 0xf6, 0x28, 0x09, 0x0a, 0x00,\n    0x80, 0x40, 0x8d, 0x31, 0x2b, 0x80, 0x9b, 0x89,\n    0xa9, 0x20, 0x83, 0x91, 0x8a, 0xad, 0x8d, 0x41,\n    0x96, 0x38, 0x86, 0xd2, 0x95, 0x80, 0x8d, 0xf9,\n    0x2a, 0x00, 0x08, 0x10, 0x02, 0x80, 0xc1, 0x20,\n    0x08, 0x83, 0x41, 0x5b, 0x83, 0x60, 0x50, 0x57,\n    0x00, 0xb6, 0x33, 0xdc, 0x81, 0x60, 0x4c, 0xab,\n    0x80, 0x60, 0x23, 0x60, 0x30, 0x90, 0x0e, 0x01,\n    0x04, 0x49, 0x1b, 0x80, 0x47, 0xe7, 0x99, 0x85,\n    0x99, 0x85, 0x99,\n};\n\nstatic const uint8_t unicode_prop_Other_Lowercase_table[51] = {\n    0x40, 0xa9, 0x80, 0x8e, 0x80, 0x41, 0xf4, 0x88,\n    0x31, 0x9d, 0x84, 0xdf, 0x80, 0xb3, 0x80, 0x59,\n    0xb0, 0xbe, 0x8c, 0x80, 0xa1, 0xa4, 0x42, 0xb0,\n    0x80, 0x8c, 0x80, 0x8f, 0x8c, 0x40, 0xd2, 0x8f,\n    0x43, 0x4f, 0x99, 0x47, 0x91, 0x81, 0x60, 0x7a,\n    0x1d, 0x81, 0x40, 0xd1, 0x80, 0x40, 0x86, 0x81,\n    0x43, 0x61, 0x83,\n};\n\nstatic const uint8_t unicode_prop_Other_Uppercase_table[15] = {\n    0x60, 0x21, 0x5f, 0x8f, 0x43, 0x45, 0x99, 0x61,\n    0xcc, 0x5f, 0x99, 0x85, 0x99, 0x85, 0x99,\n};\n\nstatic const uint8_t unicode_prop_Other_Grapheme_Extend_table[65] = {\n    0x49, 0xbd, 0x80, 0x97, 0x80, 0x41, 0x65, 0x80,\n    0x97, 0x80, 0xe5, 0x80, 0x97, 0x80, 0x40, 0xe9,\n    0x80, 0x91, 0x81, 0xe6, 0x80, 0x97, 0x80, 0xf6,\n    0x80, 0x8e, 0x80, 0x4d, 0x54, 0x80, 0x44, 0xd5,\n    0x80, 0x50, 0x20, 0x81, 0x60, 0xcf, 0x6d, 0x81,\n    0x53, 0x9d, 0x80, 0x97, 0x80, 0x41, 0x57, 0x80,\n    0x8b, 0x80, 0x40, 0xf0, 0x80, 0x43, 0x7f, 0x80,\n    0x60, 0xb8, 0x33, 0x07, 0x84, 0x6c, 0x2e, 0xac,\n    0xdf,\n};\n\nstatic const uint8_t unicode_prop_Other_Default_Ignorable_Code_Point_table[32] = {\n    0x43, 0x4e, 0x80, 0x4e, 0x0e, 0x81, 0x46, 0x52,\n    0x81, 0x48, 0xae, 0x80, 0x50, 0xfd, 0x80, 0x60,\n    0xce, 0x3a, 0x80, 0xce, 0x88, 0x6d, 0x00, 0x06,\n    0x00, 0x9d, 0xdf, 0xff, 0x40, 0xef, 0x4e, 0x0f,\n};\n\nstatic const uint8_t unicode_prop_Other_ID_Start_table[11] = {\n    0x58, 0x84, 0x81, 0x48, 0x90, 0x80, 0x94, 0x80,\n    0x4f, 0x6b, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Other_ID_Continue_table[12] = {\n    0x40, 0xb6, 0x80, 0x42, 0xce, 0x80, 0x4f, 0xe0,\n    0x88, 0x46, 0x67, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Prepended_Concatenation_Mark_table[17] = {\n    0x45, 0xff, 0x85, 0x40, 0xd6, 0x80, 0xb0, 0x80,\n    0x41, 0xd1, 0x80, 0x61, 0x07, 0xd9, 0x80, 0x8e,\n    0x80,\n};\n\nstatic const uint8_t unicode_prop_XID_Start1_table[31] = {\n    0x43, 0x79, 0x80, 0x4a, 0xb7, 0x80, 0xfe, 0x80,\n    0x60, 0x21, 0xe6, 0x81, 0x60, 0xcb, 0xc0, 0x85,\n    0x41, 0x95, 0x81, 0xf3, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x80, 0x41, 0x1e, 0x81,\n};\n\nstatic const uint8_t unicode_prop_XID_Continue1_table[23] = {\n    0x43, 0x79, 0x80, 0x60, 0x2d, 0x1f, 0x81, 0x60,\n    0xcb, 0xc0, 0x85, 0x41, 0x95, 0x81, 0xf3, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Changes_When_Titlecased1_table[22] = {\n    0x41, 0xc3, 0x08, 0x08, 0x81, 0xa4, 0x81, 0x4e,\n    0xdc, 0xaa, 0x0a, 0x4e, 0x87, 0x3f, 0x3f, 0x87,\n    0x8b, 0x80, 0x8e, 0x80, 0xae, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Changes_When_Casefolded1_table[33] = {\n    0x40, 0xde, 0x80, 0xcf, 0x80, 0x97, 0x80, 0x44,\n    0x3c, 0x80, 0x59, 0x11, 0x80, 0x40, 0xe4, 0x3f,\n    0x3f, 0x87, 0x89, 0x11, 0x05, 0x02, 0x11, 0x80,\n    0xa9, 0x11, 0x80, 0x60, 0xdb, 0x07, 0x86, 0x8b,\n    0x84,\n};\n\nstatic const uint8_t unicode_prop_Changes_When_NFKC_Casefolded1_table[441] = {\n    0x40, 0x9f, 0x06, 0x00, 0x01, 0x00, 0x01, 0x12,\n    0x10, 0x82, 0x9f, 0x80, 0xcf, 0x01, 0x80, 0x8b,\n    0x07, 0x80, 0xfb, 0x01, 0x01, 0x80, 0xa5, 0x80,\n    0x40, 0xbb, 0x88, 0x9e, 0x29, 0x84, 0xda, 0x08,\n    0x81, 0x89, 0x80, 0xa3, 0x04, 0x02, 0x04, 0x08,\n    0x80, 0xc9, 0x82, 0x9c, 0x80, 0x41, 0x93, 0x80,\n    0x40, 0x93, 0x80, 0xd7, 0x83, 0x42, 0xde, 0x87,\n    0xfb, 0x08, 0x80, 0xd2, 0x01, 0x80, 0xa1, 0x11,\n    0x80, 0x40, 0xfc, 0x81, 0x42, 0xd4, 0x80, 0xfe,\n    0x80, 0xa7, 0x81, 0xad, 0x80, 0xb5, 0x80, 0x88,\n    0x03, 0x03, 0x03, 0x80, 0x8b, 0x80, 0x88, 0x00,\n    0x26, 0x80, 0x90, 0x80, 0x88, 0x03, 0x03, 0x03,\n    0x80, 0x8b, 0x80, 0x41, 0x41, 0x80, 0xe1, 0x81,\n    0x46, 0x52, 0x81, 0xd4, 0x83, 0x45, 0x1c, 0x10,\n    0x8a, 0x80, 0x91, 0x80, 0x9b, 0x8c, 0x80, 0xa1,\n    0xa4, 0x40, 0xd9, 0x80, 0x40, 0xd5, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x01, 0x3f, 0x3f, 0x87,\n    0x89, 0x11, 0x04, 0x00, 0x29, 0x04, 0x12, 0x80,\n    0x88, 0x12, 0x80, 0x88, 0x11, 0x11, 0x04, 0x08,\n    0x8f, 0x00, 0x20, 0x8b, 0x12, 0x2a, 0x08, 0x0b,\n    0x00, 0x07, 0x82, 0x8c, 0x06, 0x92, 0x81, 0x9a,\n    0x80, 0x8c, 0x8a, 0x80, 0xd6, 0x18, 0x10, 0x8a,\n    0x01, 0x0c, 0x0a, 0x00, 0x10, 0x11, 0x02, 0x06,\n    0x05, 0x1c, 0x85, 0x8f, 0x8f, 0x8f, 0x88, 0x80,\n    0x40, 0xa1, 0x08, 0x81, 0x40, 0xf7, 0x81, 0x41,\n    0x34, 0xd5, 0x99, 0x9a, 0x45, 0x20, 0x80, 0xe6,\n    0x82, 0xe4, 0x80, 0x41, 0x9e, 0x81, 0x40, 0xf0,\n    0x80, 0x41, 0x2e, 0x80, 0xd2, 0x80, 0x8b, 0x40,\n    0xd5, 0xa9, 0x80, 0xb4, 0x00, 0x82, 0xdf, 0x09,\n    0x80, 0xde, 0x80, 0xb0, 0xdd, 0x82, 0x8d, 0xdf,\n    0x9e, 0x80, 0xa7, 0x87, 0xae, 0x80, 0x41, 0x7f,\n    0x60, 0x72, 0x9b, 0x81, 0x40, 0xd1, 0x80, 0x40,\n    0x86, 0x81, 0x43, 0x61, 0x83, 0x88, 0x80, 0x60,\n    0x4d, 0x95, 0x41, 0x0d, 0x08, 0x00, 0x81, 0x89,\n    0x00, 0x00, 0x09, 0x82, 0xc3, 0x81, 0xe9, 0xa5,\n    0x86, 0x8b, 0x24, 0x00, 0x97, 0x04, 0x00, 0x01,\n    0x01, 0x80, 0xeb, 0xa0, 0x41, 0x6a, 0x91, 0xbf,\n    0x81, 0xb5, 0xa7, 0x8c, 0x82, 0x99, 0x95, 0x94,\n    0x81, 0x8b, 0x80, 0x92, 0x03, 0x1a, 0x00, 0x80,\n    0x40, 0x86, 0x08, 0x80, 0x9f, 0x99, 0x40, 0x83,\n    0x15, 0x0d, 0x0d, 0x0a, 0x16, 0x06, 0x80, 0x88,\n    0x60, 0xbc, 0xa6, 0x83, 0x54, 0xb9, 0x86, 0x8d,\n    0x87, 0xbf, 0x85, 0x42, 0x3e, 0xd4, 0x80, 0xc6,\n    0x01, 0x08, 0x09, 0x0b, 0x80, 0x8b, 0x00, 0x06,\n    0x80, 0xc0, 0x03, 0x0f, 0x06, 0x80, 0x9b, 0x03,\n    0x04, 0x00, 0x16, 0x80, 0x41, 0x53, 0x81, 0x41,\n    0x23, 0x81, 0xb1, 0x55, 0xff, 0x18, 0x9a, 0x01,\n    0x00, 0x08, 0x80, 0x89, 0x03, 0x00, 0x00, 0x28,\n    0x18, 0x00, 0x00, 0x02, 0x01, 0x00, 0x08, 0x00,\n    0x00, 0x00, 0x00, 0x01, 0x00, 0x0b, 0x06, 0x03,\n    0x03, 0x00, 0x80, 0x89, 0x80, 0x90, 0x22, 0x04,\n    0x80, 0x90, 0x42, 0x43, 0x8a, 0x84, 0x9e, 0x80,\n    0x9f, 0x99, 0x82, 0xa2, 0x80, 0xee, 0x82, 0x8c,\n    0xab, 0x83, 0x88, 0x31, 0x49, 0x9d, 0x89, 0x60,\n    0xfc, 0x05, 0x42, 0x1d, 0x6b, 0x05, 0xe1, 0x4f,\n    0xff,\n};\n\nstatic const uint8_t unicode_prop_ASCII_Hex_Digit_table[5] = {\n    0xaf, 0x89, 0x35, 0x99, 0x85,\n};\n\nstatic const uint8_t unicode_prop_Bidi_Control_table[10] = {\n    0x46, 0x1b, 0x80, 0x59, 0xf0, 0x81, 0x99, 0x84,\n    0xb6, 0x83,\n};\n\nstatic const uint8_t unicode_prop_Dash_table[53] = {\n    0xac, 0x80, 0x45, 0x5b, 0x80, 0xb2, 0x80, 0x4e,\n    0x40, 0x80, 0x44, 0x04, 0x80, 0x48, 0x08, 0x85,\n    0xbc, 0x80, 0xa6, 0x80, 0x8e, 0x80, 0x41, 0x85,\n    0x80, 0x4c, 0x03, 0x01, 0x80, 0x9e, 0x0b, 0x80,\n    0x41, 0xda, 0x80, 0x92, 0x80, 0xee, 0x80, 0x60,\n    0xcd, 0x8f, 0x81, 0xa4, 0x80, 0x89, 0x80, 0x40,\n    0xa8, 0x80, 0x4f, 0x9e, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Deprecated_table[23] = {\n    0x41, 0x48, 0x80, 0x45, 0x28, 0x80, 0x49, 0x02,\n    0x00, 0x80, 0x48, 0x28, 0x81, 0x48, 0xc4, 0x85,\n    0x42, 0xb8, 0x81, 0x6d, 0xdc, 0xd5, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Diacritic_table[358] = {\n    0xdd, 0x00, 0x80, 0xc6, 0x05, 0x03, 0x01, 0x81,\n    0x41, 0xf6, 0x40, 0x9e, 0x07, 0x25, 0x90, 0x0b,\n    0x80, 0x88, 0x81, 0x40, 0xfc, 0x84, 0x40, 0xd0,\n    0x80, 0xb6, 0x90, 0x80, 0x9a, 0x00, 0x01, 0x00,\n    0x40, 0x85, 0x3b, 0x81, 0x40, 0x85, 0x0b, 0x0a,\n    0x82, 0xc2, 0x9a, 0xda, 0x8a, 0xb9, 0x8a, 0xa1,\n    0x81, 0x40, 0xc8, 0x9b, 0xbc, 0x80, 0x8f, 0x02,\n    0x83, 0x9b, 0x80, 0xc9, 0x80, 0x8f, 0x80, 0xed,\n    0x80, 0x8f, 0x80, 0xed, 0x80, 0x8f, 0x80, 0xae,\n    0x82, 0xbb, 0x80, 0x8f, 0x06, 0x80, 0xf6, 0x80,\n    0xfe, 0x80, 0xed, 0x80, 0x8f, 0x80, 0xec, 0x81,\n    0x8f, 0x80, 0xfb, 0x80, 0xfb, 0x28, 0x80, 0xea,\n    0x80, 0x8c, 0x84, 0xca, 0x81, 0x9a, 0x00, 0x00,\n    0x03, 0x81, 0xc1, 0x10, 0x81, 0xbd, 0x80, 0xef,\n    0x00, 0x81, 0xa7, 0x0b, 0x84, 0x98, 0x30, 0x80,\n    0x89, 0x81, 0x42, 0xc0, 0x82, 0x44, 0x68, 0x8a,\n    0x88, 0x80, 0x41, 0x5a, 0x82, 0x41, 0x38, 0x39,\n    0x80, 0xaf, 0x8d, 0xf5, 0x80, 0x8e, 0x80, 0xa5,\n    0x88, 0xb5, 0x81, 0x40, 0x89, 0x81, 0xbf, 0x85,\n    0xd1, 0x98, 0x18, 0x28, 0x0a, 0xb1, 0xbe, 0xd8,\n    0x8b, 0xa4, 0x22, 0x82, 0x41, 0xbc, 0x00, 0x82,\n    0x8a, 0x82, 0x8c, 0x82, 0x8c, 0x82, 0x8c, 0x81,\n    0x4c, 0xef, 0x82, 0x41, 0x3c, 0x80, 0x41, 0xf9,\n    0x85, 0xe8, 0x83, 0xde, 0x80, 0x60, 0x75, 0x71,\n    0x80, 0x8b, 0x08, 0x80, 0x9b, 0x81, 0xd1, 0x81,\n    0x8d, 0xa1, 0xe5, 0x82, 0xec, 0x81, 0x40, 0xc9,\n    0x80, 0x9a, 0x91, 0xb8, 0x83, 0xa3, 0x80, 0xde,\n    0x80, 0x8b, 0x80, 0xa3, 0x80, 0x40, 0x94, 0x82,\n    0xc0, 0x83, 0xb2, 0x80, 0xe3, 0x84, 0x88, 0x82,\n    0xff, 0x81, 0x60, 0x4f, 0x2f, 0x80, 0x43, 0x00,\n    0x8f, 0x41, 0x0d, 0x00, 0x80, 0xae, 0x80, 0xac,\n    0x81, 0xc2, 0x80, 0x42, 0xfb, 0x80, 0x48, 0x03,\n    0x81, 0x42, 0x3a, 0x85, 0x42, 0x1d, 0x8a, 0x41,\n    0x67, 0x81, 0xf7, 0x81, 0xbd, 0x80, 0xcb, 0x80,\n    0x88, 0x82, 0xe7, 0x81, 0x40, 0xb1, 0x81, 0xd0,\n    0x80, 0x8f, 0x80, 0x97, 0x32, 0x84, 0x40, 0xcc,\n    0x02, 0x80, 0xfa, 0x81, 0x40, 0xfa, 0x81, 0xfd,\n    0x80, 0xf5, 0x81, 0xf2, 0x80, 0x41, 0x0c, 0x81,\n    0x41, 0x01, 0x0b, 0x80, 0x40, 0x9b, 0x80, 0xd2,\n    0x80, 0x91, 0x80, 0xd0, 0x80, 0x41, 0xa4, 0x80,\n    0x41, 0x01, 0x00, 0x81, 0xd0, 0x80, 0x60, 0x4d,\n    0x57, 0x84, 0xba, 0x86, 0x44, 0x57, 0x90, 0xcf,\n    0x81, 0x60, 0x61, 0x74, 0x12, 0x2f, 0x39, 0x86,\n    0x9d, 0x83, 0x4f, 0x81, 0x86, 0x41, 0xb4, 0x83,\n    0x45, 0xdf, 0x86, 0xec, 0x10, 0x82,\n};\n\nstatic const uint8_t unicode_prop_Extender_table[89] = {\n    0x40, 0xb6, 0x80, 0x42, 0x17, 0x81, 0x43, 0x6d,\n    0x80, 0x41, 0xb8, 0x80, 0x43, 0x59, 0x80, 0x42,\n    0xef, 0x80, 0xfe, 0x80, 0x49, 0x42, 0x80, 0xb7,\n    0x80, 0x42, 0x62, 0x80, 0x41, 0x8d, 0x80, 0xc3,\n    0x80, 0x53, 0x88, 0x80, 0xaa, 0x84, 0xe6, 0x81,\n    0xdc, 0x82, 0x60, 0x6f, 0x15, 0x80, 0x45, 0xf5,\n    0x80, 0x43, 0xc1, 0x80, 0x95, 0x80, 0x40, 0x88,\n    0x80, 0xeb, 0x80, 0x94, 0x81, 0x60, 0x54, 0x7a,\n    0x80, 0x53, 0xeb, 0x80, 0x42, 0x67, 0x82, 0x44,\n    0xce, 0x80, 0x60, 0x50, 0xa8, 0x81, 0x44, 0x9b,\n    0x08, 0x80, 0x60, 0x71, 0x57, 0x81, 0x48, 0x05,\n    0x82,\n};\n\nstatic const uint8_t unicode_prop_Hex_Digit_table[12] = {\n    0xaf, 0x89, 0x35, 0x99, 0x85, 0x60, 0xfe, 0xa8,\n    0x89, 0x35, 0x99, 0x85,\n};\n\nstatic const uint8_t unicode_prop_IDS_Binary_Operator_table[5] = {\n    0x60, 0x2f, 0xef, 0x09, 0x87,\n};\n\nstatic const uint8_t unicode_prop_IDS_Trinary_Operator_table[4] = {\n    0x60, 0x2f, 0xf1, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Ideographic_table[66] = {\n    0x60, 0x30, 0x05, 0x81, 0x98, 0x88, 0x8d, 0x82,\n    0x43, 0xc4, 0x59, 0xbf, 0xbf, 0x60, 0x51, 0xfc,\n    0x60, 0x59, 0x02, 0x41, 0x6d, 0x81, 0xe9, 0x60,\n    0x75, 0x09, 0x80, 0x9a, 0x57, 0xf7, 0x87, 0x44,\n    0xd5, 0xa9, 0x88, 0x60, 0x24, 0x66, 0x41, 0x8b,\n    0x60, 0x4d, 0x03, 0x60, 0xa6, 0xdd, 0xa1, 0x50,\n    0x34, 0x8a, 0x40, 0xdd, 0x81, 0x56, 0x81, 0x8d,\n    0x5d, 0x30, 0x4c, 0x1e, 0x42, 0x1d, 0x45, 0xe1,\n    0x53, 0x4a,\n};\n\nstatic const uint8_t unicode_prop_Join_Control_table[4] = {\n    0x60, 0x20, 0x0b, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Logical_Order_Exception_table[15] = {\n    0x4e, 0x3f, 0x84, 0xfa, 0x84, 0x4a, 0xef, 0x11,\n    0x80, 0x60, 0x90, 0xf9, 0x09, 0x00, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Noncharacter_Code_Point_table[71] = {\n    0x60, 0xfd, 0xcf, 0x9f, 0x42, 0x0d, 0x81, 0x60,\n    0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,\n    0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,\n    0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,\n    0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,\n    0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,\n    0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,\n    0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,\n    0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Pattern_Syntax_table[58] = {\n    0xa0, 0x8e, 0x89, 0x86, 0x99, 0x18, 0x80, 0x99,\n    0x83, 0xa1, 0x30, 0x00, 0x08, 0x00, 0x0b, 0x03,\n    0x02, 0x80, 0x96, 0x80, 0x9e, 0x80, 0x5f, 0x17,\n    0x97, 0x87, 0x8e, 0x81, 0x92, 0x80, 0x89, 0x41,\n    0x30, 0x42, 0xcf, 0x40, 0x9f, 0x42, 0x75, 0x9d,\n    0x44, 0x6b, 0x41, 0xff, 0xff, 0x41, 0x80, 0x13,\n    0x98, 0x8e, 0x80, 0x60, 0xcd, 0x0c, 0x81, 0x41,\n    0x04, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Pattern_White_Space_table[11] = {\n    0x88, 0x84, 0x91, 0x80, 0xe3, 0x80, 0x5f, 0x87,\n    0x81, 0x97, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Quotation_Mark_table[31] = {\n    0xa1, 0x03, 0x80, 0x40, 0x82, 0x80, 0x8e, 0x80,\n    0x5f, 0x5b, 0x87, 0x98, 0x81, 0x4e, 0x06, 0x80,\n    0x41, 0xc8, 0x83, 0x8c, 0x82, 0x60, 0xce, 0x20,\n    0x83, 0x40, 0xbc, 0x03, 0x80, 0xd9, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Radical_table[9] = {\n    0x60, 0x2e, 0x7f, 0x99, 0x80, 0xd8, 0x8b, 0x40,\n    0xd5,\n};\n\nstatic const uint8_t unicode_prop_Regional_Indicator_table[4] = {\n    0x61, 0xf1, 0xe5, 0x99,\n};\n\nstatic const uint8_t unicode_prop_Sentence_Terminal_table[188] = {\n    0xa0, 0x80, 0x8b, 0x80, 0x8f, 0x80, 0x45, 0x48,\n    0x80, 0x40, 0x93, 0x81, 0x40, 0xb3, 0x80, 0xaa,\n    0x82, 0x40, 0xf5, 0x80, 0xbc, 0x00, 0x02, 0x81,\n    0x41, 0x24, 0x81, 0x46, 0xe3, 0x81, 0x43, 0x15,\n    0x03, 0x81, 0x43, 0x04, 0x80, 0x40, 0xc5, 0x81,\n    0x40, 0xcb, 0x04, 0x80, 0x41, 0x39, 0x81, 0x41,\n    0x61, 0x83, 0x40, 0xad, 0x09, 0x81, 0x40, 0xda,\n    0x81, 0xc0, 0x81, 0x43, 0xbb, 0x81, 0x88, 0x82,\n    0x4d, 0xe3, 0x80, 0x8c, 0x80, 0x41, 0xc4, 0x80,\n    0x60, 0x74, 0xfb, 0x80, 0x41, 0x0d, 0x81, 0x40,\n    0xe2, 0x02, 0x80, 0x41, 0x7d, 0x81, 0xd5, 0x81,\n    0xde, 0x80, 0x40, 0x97, 0x81, 0x40, 0x92, 0x82,\n    0x40, 0x8f, 0x81, 0x40, 0xf8, 0x80, 0x60, 0x52,\n    0x65, 0x02, 0x81, 0x40, 0xa8, 0x80, 0x8b, 0x80,\n    0x8f, 0x80, 0xc0, 0x80, 0x4a, 0xf3, 0x81, 0x44,\n    0xfc, 0x84, 0x40, 0xec, 0x81, 0xf4, 0x83, 0xfe,\n    0x82, 0x40, 0x80, 0x0d, 0x80, 0x8f, 0x81, 0xd7,\n    0x08, 0x81, 0xeb, 0x80, 0x41, 0xa0, 0x81, 0x41,\n    0x74, 0x0c, 0x8e, 0xe8, 0x81, 0x40, 0xf8, 0x82,\n    0x42, 0x04, 0x00, 0x80, 0x40, 0xfa, 0x81, 0xd6,\n    0x81, 0x41, 0xa3, 0x81, 0x42, 0xb3, 0x81, 0x60,\n    0x4b, 0x74, 0x81, 0x40, 0x84, 0x80, 0xc0, 0x81,\n    0x8a, 0x80, 0x43, 0x52, 0x80, 0x60, 0x4e, 0x05,\n    0x80, 0x5d, 0xe7, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Soft_Dotted_table[71] = {\n    0xe8, 0x81, 0x40, 0xc3, 0x80, 0x41, 0x18, 0x80,\n    0x9d, 0x80, 0xb3, 0x80, 0x93, 0x80, 0x41, 0x3f,\n    0x80, 0xe1, 0x00, 0x80, 0x59, 0x08, 0x80, 0xb2,\n    0x80, 0x8c, 0x02, 0x80, 0x40, 0x83, 0x80, 0x40,\n    0x9c, 0x80, 0x41, 0xa4, 0x80, 0x40, 0xd5, 0x81,\n    0x4b, 0x31, 0x80, 0x61, 0xa7, 0xa4, 0x81, 0xb1,\n    0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1,\n    0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1,\n    0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Terminal_Punctuation_table[241] = {\n    0xa0, 0x80, 0x89, 0x00, 0x80, 0x8a, 0x0a, 0x80,\n    0x43, 0x3d, 0x07, 0x80, 0x42, 0x00, 0x80, 0xb8,\n    0x80, 0xc7, 0x80, 0x8d, 0x01, 0x81, 0x40, 0xb3,\n    0x80, 0xaa, 0x8a, 0x00, 0x40, 0xea, 0x81, 0xb5,\n    0x8e, 0x9e, 0x80, 0x41, 0x04, 0x81, 0x44, 0xf3,\n    0x81, 0x40, 0xab, 0x03, 0x85, 0x41, 0x36, 0x81,\n    0x43, 0x14, 0x87, 0x43, 0x04, 0x80, 0xfb, 0x82,\n    0xc6, 0x81, 0x40, 0x9c, 0x12, 0x80, 0xa6, 0x19,\n    0x81, 0x41, 0x39, 0x81, 0x41, 0x61, 0x83, 0x40,\n    0xad, 0x08, 0x82, 0x40, 0xda, 0x84, 0xbd, 0x81,\n    0x43, 0xbb, 0x81, 0x88, 0x82, 0x4d, 0xe3, 0x80,\n    0x8c, 0x03, 0x80, 0x89, 0x00, 0x81, 0x41, 0xb0,\n    0x81, 0x60, 0x74, 0xfa, 0x81, 0x41, 0x0c, 0x82,\n    0x40, 0xe2, 0x84, 0x41, 0x7d, 0x81, 0xd5, 0x81,\n    0xde, 0x80, 0x40, 0x96, 0x82, 0x40, 0x92, 0x82,\n    0xfe, 0x80, 0x8f, 0x81, 0x40, 0xf8, 0x80, 0x60,\n    0x52, 0x63, 0x10, 0x83, 0x40, 0xa8, 0x80, 0x89,\n    0x00, 0x80, 0x8a, 0x0a, 0x80, 0xc0, 0x01, 0x80,\n    0x44, 0x39, 0x80, 0xaf, 0x80, 0x44, 0x85, 0x80,\n    0x40, 0xc6, 0x80, 0x41, 0x35, 0x81, 0x40, 0x97,\n    0x85, 0xc3, 0x85, 0xd8, 0x83, 0x43, 0xb7, 0x84,\n    0x40, 0xec, 0x86, 0xef, 0x83, 0xfe, 0x82, 0x40,\n    0x80, 0x0d, 0x80, 0x8f, 0x81, 0xd7, 0x84, 0xeb,\n    0x80, 0x41, 0xa0, 0x82, 0x8b, 0x81, 0x41, 0x65,\n    0x1a, 0x8e, 0xe8, 0x81, 0x40, 0xf8, 0x82, 0x42,\n    0x04, 0x00, 0x80, 0x40, 0xfa, 0x81, 0xd6, 0x0b,\n    0x81, 0x41, 0x9d, 0x82, 0xac, 0x80, 0x42, 0x84,\n    0x81, 0x45, 0x76, 0x84, 0x60, 0x45, 0xf8, 0x81,\n    0x40, 0x84, 0x80, 0xc0, 0x82, 0x89, 0x80, 0x43,\n    0x51, 0x81, 0x60, 0x4e, 0x05, 0x80, 0x5d, 0xe6,\n    0x83,\n};\n\nstatic const uint8_t unicode_prop_Unified_Ideograph_table[42] = {\n    0x60, 0x33, 0xff, 0x59, 0xbf, 0xbf, 0x60, 0x51,\n    0xfc, 0x60, 0x5a, 0x10, 0x08, 0x00, 0x81, 0x89,\n    0x00, 0x00, 0x09, 0x82, 0x61, 0x05, 0xd5, 0x60,\n    0xa6, 0xdd, 0xa1, 0x50, 0x34, 0x8a, 0x40, 0xdd,\n    0x81, 0x56, 0x81, 0x8d, 0x5d, 0x30, 0x54, 0x1e,\n    0x53, 0x4a,\n};\n\nstatic const uint8_t unicode_prop_Variation_Selector_table[12] = {\n    0x58, 0x0a, 0x82, 0x60, 0xe5, 0xf1, 0x8f, 0x6d,\n    0x02, 0xef, 0x40, 0xef,\n};\n\nstatic const uint8_t unicode_prop_White_Space_table[22] = {\n    0x88, 0x84, 0x91, 0x80, 0xe3, 0x80, 0x99, 0x80,\n    0x55, 0xde, 0x80, 0x49, 0x7e, 0x8a, 0x9c, 0x0c,\n    0x80, 0xae, 0x80, 0x4f, 0x9f, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Bidi_Mirrored_table[171] = {\n    0xa7, 0x81, 0x91, 0x00, 0x80, 0x9b, 0x00, 0x80,\n    0x9c, 0x00, 0x80, 0xac, 0x80, 0x8e, 0x80, 0x4e,\n    0x7d, 0x83, 0x47, 0x5c, 0x81, 0x49, 0x9b, 0x81,\n    0x89, 0x81, 0xb5, 0x81, 0x8d, 0x81, 0x40, 0xb0,\n    0x80, 0x40, 0xbf, 0x1a, 0x2a, 0x02, 0x0a, 0x18,\n    0x18, 0x00, 0x03, 0x88, 0x20, 0x80, 0x91, 0x23,\n    0x88, 0x08, 0x00, 0x39, 0x9e, 0x0b, 0x20, 0x88,\n    0x09, 0x92, 0x21, 0x88, 0x21, 0x0b, 0x97, 0x81,\n    0x8f, 0x3b, 0x93, 0x0e, 0x81, 0x44, 0x3c, 0x8d,\n    0xc9, 0x01, 0x18, 0x08, 0x14, 0x1c, 0x12, 0x8d,\n    0x41, 0x92, 0x95, 0x0d, 0x80, 0x8d, 0x38, 0x35,\n    0x10, 0x1c, 0x01, 0x0c, 0x18, 0x02, 0x09, 0x89,\n    0x29, 0x81, 0x8b, 0x92, 0x03, 0x08, 0x00, 0x08,\n    0x03, 0x21, 0x2a, 0x97, 0x81, 0x8a, 0x0b, 0x18,\n    0x09, 0x0b, 0xaa, 0x0f, 0x80, 0xa7, 0x20, 0x00,\n    0x14, 0x22, 0x18, 0x14, 0x00, 0x40, 0xff, 0x80,\n    0x42, 0x02, 0x1a, 0x08, 0x81, 0x8d, 0x09, 0x89,\n    0x41, 0xdd, 0x89, 0x0f, 0x60, 0xce, 0x3c, 0x2c,\n    0x81, 0x40, 0xa1, 0x81, 0x91, 0x00, 0x80, 0x9b,\n    0x00, 0x80, 0x9c, 0x00, 0x00, 0x08, 0x81, 0x60,\n    0xd7, 0x76, 0x80, 0xb8, 0x80, 0xb8, 0x80, 0xb8,\n    0x80, 0xb8, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Emoji_table[238] = {\n    0xa2, 0x05, 0x04, 0x89, 0xee, 0x03, 0x80, 0x5f,\n    0x8c, 0x80, 0x8b, 0x80, 0x40, 0xd7, 0x80, 0x95,\n    0x80, 0xd9, 0x85, 0x8e, 0x81, 0x41, 0x6e, 0x81,\n    0x8b, 0x80, 0x40, 0xa5, 0x80, 0x98, 0x8a, 0x1a,\n    0x40, 0xc6, 0x80, 0x40, 0xe6, 0x81, 0x89, 0x80,\n    0x88, 0x80, 0xb9, 0x18, 0x84, 0x88, 0x01, 0x01,\n    0x09, 0x03, 0x01, 0x00, 0x09, 0x02, 0x02, 0x0f,\n    0x14, 0x00, 0x04, 0x8b, 0x8a, 0x09, 0x00, 0x08,\n    0x80, 0x91, 0x01, 0x81, 0x91, 0x28, 0x00, 0x0a,\n    0x0c, 0x01, 0x0b, 0x81, 0x8a, 0x0c, 0x09, 0x04,\n    0x08, 0x00, 0x81, 0x93, 0x0c, 0x28, 0x19, 0x03,\n    0x01, 0x01, 0x28, 0x01, 0x00, 0x00, 0x05, 0x02,\n    0x05, 0x80, 0x89, 0x81, 0x8e, 0x01, 0x03, 0x00,\n    0x03, 0x10, 0x80, 0x8a, 0x81, 0xaf, 0x82, 0x88,\n    0x80, 0x8d, 0x80, 0x8d, 0x80, 0x41, 0x73, 0x81,\n    0x41, 0xce, 0x82, 0x92, 0x81, 0xb2, 0x03, 0x80,\n    0x44, 0xd9, 0x80, 0x8b, 0x80, 0x42, 0x58, 0x00,\n    0x80, 0x61, 0xbd, 0x69, 0x80, 0x40, 0xc9, 0x80,\n    0x40, 0x9f, 0x81, 0x8b, 0x81, 0x8d, 0x01, 0x89,\n    0xca, 0x99, 0x01, 0x96, 0x80, 0x93, 0x01, 0x88,\n    0x94, 0x81, 0x40, 0xad, 0xa1, 0x81, 0xef, 0x09,\n    0x02, 0x81, 0xd2, 0x0a, 0x80, 0x41, 0x06, 0x80,\n    0xbe, 0x8a, 0x28, 0x97, 0x31, 0x0f, 0x8b, 0x01,\n    0x19, 0x03, 0x81, 0x8c, 0x09, 0x07, 0x81, 0x88,\n    0x04, 0x82, 0x8b, 0x17, 0x11, 0x00, 0x03, 0x05,\n    0x02, 0x05, 0xd5, 0xaf, 0xc5, 0x27, 0x0a, 0x3d,\n    0x10, 0x01, 0x10, 0x81, 0x89, 0x40, 0xe2, 0x8b,\n    0x41, 0x1f, 0xae, 0x80, 0x89, 0x80, 0xb1, 0x80,\n    0xd1, 0x80, 0xb2, 0xef, 0x22, 0x14, 0x86, 0x88,\n    0x98, 0x36, 0x88, 0x82, 0x8c, 0x86,\n};\n\nstatic const uint8_t unicode_prop_Emoji_Component_table[28] = {\n    0xa2, 0x05, 0x04, 0x89, 0x5f, 0xd2, 0x80, 0x40,\n    0xd4, 0x80, 0x60, 0xdd, 0x2a, 0x80, 0x60, 0xf3,\n    0xd5, 0x99, 0x41, 0xfa, 0x84, 0x45, 0xaf, 0x83,\n    0x6c, 0x06, 0x6b, 0xdf,\n};\n\nstatic const uint8_t unicode_prop_Emoji_Modifier_table[4] = {\n    0x61, 0xf3, 0xfa, 0x84,\n};\n\nstatic const uint8_t unicode_prop_Emoji_Modifier_Base_table[66] = {\n    0x60, 0x26, 0x1c, 0x80, 0x40, 0xda, 0x80, 0x8f,\n    0x83, 0x61, 0xcc, 0x76, 0x80, 0xbb, 0x11, 0x01,\n    0x82, 0xf4, 0x09, 0x8a, 0x94, 0x92, 0x10, 0x1a,\n    0x02, 0x30, 0x00, 0x97, 0x80, 0x40, 0xc8, 0x0b,\n    0x80, 0x94, 0x03, 0x81, 0x40, 0xad, 0x12, 0x84,\n    0xd2, 0x80, 0x8f, 0x82, 0x88, 0x80, 0x8a, 0x80,\n    0x42, 0x3e, 0x01, 0x07, 0x3d, 0x80, 0x88, 0x89,\n    0x0a, 0xb7, 0x80, 0xbc, 0x08, 0x08, 0x80, 0x90,\n    0x10, 0x8c,\n};\n\nstatic const uint8_t unicode_prop_Emoji_Presentation_table[144] = {\n    0x60, 0x23, 0x19, 0x81, 0x40, 0xcc, 0x1a, 0x01,\n    0x80, 0x42, 0x08, 0x81, 0x94, 0x81, 0xb1, 0x8b,\n    0xaa, 0x80, 0x92, 0x80, 0x8c, 0x07, 0x81, 0x90,\n    0x0c, 0x0f, 0x04, 0x80, 0x94, 0x06, 0x08, 0x03,\n    0x01, 0x06, 0x03, 0x81, 0x9b, 0x80, 0xa2, 0x00,\n    0x03, 0x10, 0x80, 0xbc, 0x82, 0x97, 0x80, 0x8d,\n    0x80, 0x43, 0x5a, 0x81, 0xb2, 0x03, 0x80, 0x61,\n    0xc4, 0xad, 0x80, 0x40, 0xc9, 0x80, 0x40, 0xbd,\n    0x01, 0x89, 0xca, 0x99, 0x00, 0x97, 0x80, 0x93,\n    0x01, 0x20, 0x82, 0x94, 0x81, 0x40, 0xad, 0xa0,\n    0x8b, 0x88, 0x80, 0xc5, 0x80, 0x95, 0x8b, 0xaa,\n    0x1c, 0x8b, 0x90, 0x10, 0x82, 0xc6, 0x00, 0x80,\n    0x40, 0xba, 0x81, 0xbe, 0x8c, 0x18, 0x97, 0x91,\n    0x80, 0x99, 0x81, 0x8c, 0x80, 0xd5, 0xd4, 0xaf,\n    0xc5, 0x28, 0x12, 0x0a, 0x92, 0x0e, 0x88, 0x40,\n    0xe2, 0x8b, 0x41, 0x1f, 0xae, 0x80, 0x89, 0x80,\n    0xb1, 0x80, 0xd1, 0x80, 0xb2, 0xef, 0x22, 0x14,\n    0x86, 0x88, 0x98, 0x36, 0x88, 0x82, 0x8c, 0x86,\n};\n\nstatic const uint8_t unicode_prop_Extended_Pictographic_table[156] = {\n    0x40, 0xa8, 0x03, 0x80, 0x5f, 0x8c, 0x80, 0x8b,\n    0x80, 0x40, 0xd7, 0x80, 0x95, 0x80, 0xd9, 0x85,\n    0x8e, 0x81, 0x41, 0x6e, 0x81, 0x8b, 0x80, 0xde,\n    0x80, 0xc5, 0x80, 0x98, 0x8a, 0x1a, 0x40, 0xc6,\n    0x80, 0x40, 0xe6, 0x81, 0x89, 0x80, 0x88, 0x80,\n    0xb9, 0x18, 0x28, 0x8b, 0x80, 0xf1, 0x89, 0xf5,\n    0x81, 0x8a, 0x00, 0x00, 0x28, 0x10, 0x28, 0x89,\n    0x81, 0x8e, 0x01, 0x03, 0x00, 0x03, 0x10, 0x80,\n    0x8a, 0x84, 0xac, 0x82, 0x88, 0x80, 0x8d, 0x80,\n    0x8d, 0x80, 0x41, 0x73, 0x81, 0x41, 0xce, 0x82,\n    0x92, 0x81, 0xb2, 0x03, 0x80, 0x44, 0xd9, 0x80,\n    0x8b, 0x80, 0x42, 0x58, 0x00, 0x80, 0x61, 0xbd,\n    0x65, 0x40, 0xff, 0x8c, 0x82, 0x9e, 0x80, 0xbb,\n    0x85, 0x8b, 0x81, 0x8d, 0x01, 0x89, 0x91, 0xb8,\n    0x9a, 0x8e, 0x89, 0x80, 0x93, 0x01, 0x88, 0x03,\n    0x88, 0x41, 0xb1, 0x84, 0x41, 0x3d, 0x87, 0x41,\n    0x09, 0xaf, 0xff, 0xf3, 0x8b, 0xd4, 0xaa, 0x8b,\n    0x83, 0xb7, 0x87, 0x89, 0x85, 0xa7, 0x87, 0x9d,\n    0xd1, 0x8b, 0xae, 0x80, 0x89, 0x80, 0x41, 0xb8,\n    0x40, 0xff, 0x43, 0xfd,\n};\n\nstatic const uint8_t unicode_prop_Default_Ignorable_Code_Point_table[51] = {\n    0x40, 0xac, 0x80, 0x42, 0xa0, 0x80, 0x42, 0xcb,\n    0x80, 0x4b, 0x41, 0x81, 0x46, 0x52, 0x81, 0xd4,\n    0x83, 0x47, 0xfb, 0x84, 0x99, 0x84, 0xb0, 0x8f,\n    0x50, 0xf3, 0x80, 0x60, 0xcc, 0x9a, 0x8f, 0x40,\n    0xee, 0x80, 0x40, 0x9f, 0x80, 0xce, 0x88, 0x60,\n    0xbc, 0xa6, 0x83, 0x54, 0xce, 0x87, 0x6c, 0x2e,\n    0x84, 0x4f, 0xff,\n};\n\ntypedef enum {\n    UNICODE_PROP_Hyphen,\n    UNICODE_PROP_Other_Math,\n    UNICODE_PROP_Other_Alphabetic,\n    UNICODE_PROP_Other_Lowercase,\n    UNICODE_PROP_Other_Uppercase,\n    UNICODE_PROP_Other_Grapheme_Extend,\n    UNICODE_PROP_Other_Default_Ignorable_Code_Point,\n    UNICODE_PROP_Other_ID_Start,\n    UNICODE_PROP_Other_ID_Continue,\n    UNICODE_PROP_Prepended_Concatenation_Mark,\n    UNICODE_PROP_ID_Continue1,\n    UNICODE_PROP_XID_Start1,\n    UNICODE_PROP_XID_Continue1,\n    UNICODE_PROP_Changes_When_Titlecased1,\n    UNICODE_PROP_Changes_When_Casefolded1,\n    UNICODE_PROP_Changes_When_NFKC_Casefolded1,\n    UNICODE_PROP_ASCII_Hex_Digit,\n    UNICODE_PROP_Bidi_Control,\n    UNICODE_PROP_Dash,\n    UNICODE_PROP_Deprecated,\n    UNICODE_PROP_Diacritic,\n    UNICODE_PROP_Extender,\n    UNICODE_PROP_Hex_Digit,\n    UNICODE_PROP_IDS_Binary_Operator,\n    UNICODE_PROP_IDS_Trinary_Operator,\n    UNICODE_PROP_Ideographic,\n    UNICODE_PROP_Join_Control,\n    UNICODE_PROP_Logical_Order_Exception,\n    UNICODE_PROP_Noncharacter_Code_Point,\n    UNICODE_PROP_Pattern_Syntax,\n    UNICODE_PROP_Pattern_White_Space,\n    UNICODE_PROP_Quotation_Mark,\n    UNICODE_PROP_Radical,\n    UNICODE_PROP_Regional_Indicator,\n    UNICODE_PROP_Sentence_Terminal,\n    UNICODE_PROP_Soft_Dotted,\n    UNICODE_PROP_Terminal_Punctuation,\n    UNICODE_PROP_Unified_Ideograph,\n    UNICODE_PROP_Variation_Selector,\n    UNICODE_PROP_White_Space,\n    UNICODE_PROP_Bidi_Mirrored,\n    UNICODE_PROP_Emoji,\n    UNICODE_PROP_Emoji_Component,\n    UNICODE_PROP_Emoji_Modifier,\n    UNICODE_PROP_Emoji_Modifier_Base,\n    UNICODE_PROP_Emoji_Presentation,\n    UNICODE_PROP_Extended_Pictographic,\n    UNICODE_PROP_Default_Ignorable_Code_Point,\n    UNICODE_PROP_ID_Start,\n    UNICODE_PROP_Case_Ignorable,\n    UNICODE_PROP_ASCII,\n    UNICODE_PROP_Alphabetic,\n    UNICODE_PROP_Any,\n    UNICODE_PROP_Assigned,\n    UNICODE_PROP_Cased,\n    UNICODE_PROP_Changes_When_Casefolded,\n    UNICODE_PROP_Changes_When_Casemapped,\n    UNICODE_PROP_Changes_When_Lowercased,\n    UNICODE_PROP_Changes_When_NFKC_Casefolded,\n    UNICODE_PROP_Changes_When_Titlecased,\n    UNICODE_PROP_Changes_When_Uppercased,\n    UNICODE_PROP_Grapheme_Base,\n    UNICODE_PROP_Grapheme_Extend,\n    UNICODE_PROP_ID_Continue,\n    UNICODE_PROP_Lowercase,\n    UNICODE_PROP_Math,\n    UNICODE_PROP_Uppercase,\n    UNICODE_PROP_XID_Continue,\n    UNICODE_PROP_XID_Start,\n    UNICODE_PROP_Cased1,\n    UNICODE_PROP_COUNT,\n} UnicodePropertyEnum;\n\nstatic const char unicode_prop_name_table[] =\n    \"ASCII_Hex_Digit,AHex\"               \"\\0\"\n    \"Bidi_Control,Bidi_C\"                \"\\0\"\n    \"Dash\"                               \"\\0\"\n    \"Deprecated,Dep\"                     \"\\0\"\n    \"Diacritic,Dia\"                      \"\\0\"\n    \"Extender,Ext\"                       \"\\0\"\n    \"Hex_Digit,Hex\"                      \"\\0\"\n    \"IDS_Binary_Operator,IDSB\"           \"\\0\"\n    \"IDS_Trinary_Operator,IDST\"          \"\\0\"\n    \"Ideographic,Ideo\"                   \"\\0\"\n    \"Join_Control,Join_C\"                \"\\0\"\n    \"Logical_Order_Exception,LOE\"        \"\\0\"\n    \"Noncharacter_Code_Point,NChar\"      \"\\0\"\n    \"Pattern_Syntax,Pat_Syn\"             \"\\0\"\n    \"Pattern_White_Space,Pat_WS\"         \"\\0\"\n    \"Quotation_Mark,QMark\"               \"\\0\"\n    \"Radical\"                            \"\\0\"\n    \"Regional_Indicator,RI\"              \"\\0\"\n    \"Sentence_Terminal,STerm\"            \"\\0\"\n    \"Soft_Dotted,SD\"                     \"\\0\"\n    \"Terminal_Punctuation,Term\"          \"\\0\"\n    \"Unified_Ideograph,UIdeo\"            \"\\0\"\n    \"Variation_Selector,VS\"              \"\\0\"\n    \"White_Space,space\"                  \"\\0\"\n    \"Bidi_Mirrored,Bidi_M\"               \"\\0\"\n    \"Emoji\"                              \"\\0\"\n    \"Emoji_Component,EComp\"              \"\\0\"\n    \"Emoji_Modifier,EMod\"                \"\\0\"\n    \"Emoji_Modifier_Base,EBase\"          \"\\0\"\n    \"Emoji_Presentation,EPres\"           \"\\0\"\n    \"Extended_Pictographic,ExtPict\"      \"\\0\"\n    \"Default_Ignorable_Code_Point,DI\"    \"\\0\"\n    \"ID_Start,IDS\"                       \"\\0\"\n    \"Case_Ignorable,CI\"                  \"\\0\"\n    \"ASCII\"                              \"\\0\"\n    \"Alphabetic,Alpha\"                   \"\\0\"\n    \"Any\"                                \"\\0\"\n    \"Assigned\"                           \"\\0\"\n    \"Cased\"                              \"\\0\"\n    \"Changes_When_Casefolded,CWCF\"       \"\\0\"\n    \"Changes_When_Casemapped,CWCM\"       \"\\0\"\n    \"Changes_When_Lowercased,CWL\"        \"\\0\"\n    \"Changes_When_NFKC_Casefolded,CWKCF\" \"\\0\"\n    \"Changes_When_Titlecased,CWT\"        \"\\0\"\n    \"Changes_When_Uppercased,CWU\"        \"\\0\"\n    \"Grapheme_Base,Gr_Base\"              \"\\0\"\n    \"Grapheme_Extend,Gr_Ext\"             \"\\0\"\n    \"ID_Continue,IDC\"                    \"\\0\"\n    \"Lowercase,Lower\"                    \"\\0\"\n    \"Math\"                               \"\\0\"\n    \"Uppercase,Upper\"                    \"\\0\"\n    \"XID_Continue,XIDC\"                  \"\\0\"\n    \"XID_Start,XIDS\"                     \"\\0\"\n;\n\nstatic const uint8_t * const unicode_prop_table[] = {\n    unicode_prop_Hyphen_table,\n    unicode_prop_Other_Math_table,\n    unicode_prop_Other_Alphabetic_table,\n    unicode_prop_Other_Lowercase_table,\n    unicode_prop_Other_Uppercase_table,\n    unicode_prop_Other_Grapheme_Extend_table,\n    unicode_prop_Other_Default_Ignorable_Code_Point_table,\n    unicode_prop_Other_ID_Start_table,\n    unicode_prop_Other_ID_Continue_table,\n    unicode_prop_Prepended_Concatenation_Mark_table,\n    unicode_prop_ID_Continue1_table,\n    unicode_prop_XID_Start1_table,\n    unicode_prop_XID_Continue1_table,\n    unicode_prop_Changes_When_Titlecased1_table,\n    unicode_prop_Changes_When_Casefolded1_table,\n    unicode_prop_Changes_When_NFKC_Casefolded1_table,\n    unicode_prop_ASCII_Hex_Digit_table,\n    unicode_prop_Bidi_Control_table,\n    unicode_prop_Dash_table,\n    unicode_prop_Deprecated_table,\n    unicode_prop_Diacritic_table,\n    unicode_prop_Extender_table,\n    unicode_prop_Hex_Digit_table,\n    unicode_prop_IDS_Binary_Operator_table,\n    unicode_prop_IDS_Trinary_Operator_table,\n    unicode_prop_Ideographic_table,\n    unicode_prop_Join_Control_table,\n    unicode_prop_Logical_Order_Exception_table,\n    unicode_prop_Noncharacter_Code_Point_table,\n    unicode_prop_Pattern_Syntax_table,\n    unicode_prop_Pattern_White_Space_table,\n    unicode_prop_Quotation_Mark_table,\n    unicode_prop_Radical_table,\n    unicode_prop_Regional_Indicator_table,\n    unicode_prop_Sentence_Terminal_table,\n    unicode_prop_Soft_Dotted_table,\n    unicode_prop_Terminal_Punctuation_table,\n    unicode_prop_Unified_Ideograph_table,\n    unicode_prop_Variation_Selector_table,\n    unicode_prop_White_Space_table,\n    unicode_prop_Bidi_Mirrored_table,\n    unicode_prop_Emoji_table,\n    unicode_prop_Emoji_Component_table,\n    unicode_prop_Emoji_Modifier_table,\n    unicode_prop_Emoji_Modifier_Base_table,\n    unicode_prop_Emoji_Presentation_table,\n    unicode_prop_Extended_Pictographic_table,\n    unicode_prop_Default_Ignorable_Code_Point_table,\n    unicode_prop_ID_Start_table,\n    unicode_prop_Case_Ignorable_table,\n};\n\nstatic const uint16_t unicode_prop_len_table[] = {\n    countof(unicode_prop_Hyphen_table),\n    countof(unicode_prop_Other_Math_table),\n    countof(unicode_prop_Other_Alphabetic_table),\n    countof(unicode_prop_Other_Lowercase_table),\n    countof(unicode_prop_Other_Uppercase_table),\n    countof(unicode_prop_Other_Grapheme_Extend_table),\n    countof(unicode_prop_Other_Default_Ignorable_Code_Point_table),\n    countof(unicode_prop_Other_ID_Start_table),\n    countof(unicode_prop_Other_ID_Continue_table),\n    countof(unicode_prop_Prepended_Concatenation_Mark_table),\n    countof(unicode_prop_ID_Continue1_table),\n    countof(unicode_prop_XID_Start1_table),\n    countof(unicode_prop_XID_Continue1_table),\n    countof(unicode_prop_Changes_When_Titlecased1_table),\n    countof(unicode_prop_Changes_When_Casefolded1_table),\n    countof(unicode_prop_Changes_When_NFKC_Casefolded1_table),\n    countof(unicode_prop_ASCII_Hex_Digit_table),\n    countof(unicode_prop_Bidi_Control_table),\n    countof(unicode_prop_Dash_table),\n    countof(unicode_prop_Deprecated_table),\n    countof(unicode_prop_Diacritic_table),\n    countof(unicode_prop_Extender_table),\n    countof(unicode_prop_Hex_Digit_table),\n    countof(unicode_prop_IDS_Binary_Operator_table),\n    countof(unicode_prop_IDS_Trinary_Operator_table),\n    countof(unicode_prop_Ideographic_table),\n    countof(unicode_prop_Join_Control_table),\n    countof(unicode_prop_Logical_Order_Exception_table),\n    countof(unicode_prop_Noncharacter_Code_Point_table),\n    countof(unicode_prop_Pattern_Syntax_table),\n    countof(unicode_prop_Pattern_White_Space_table),\n    countof(unicode_prop_Quotation_Mark_table),\n    countof(unicode_prop_Radical_table),\n    countof(unicode_prop_Regional_Indicator_table),\n    countof(unicode_prop_Sentence_Terminal_table),\n    countof(unicode_prop_Soft_Dotted_table),\n    countof(unicode_prop_Terminal_Punctuation_table),\n    countof(unicode_prop_Unified_Ideograph_table),\n    countof(unicode_prop_Variation_Selector_table),\n    countof(unicode_prop_White_Space_table),\n    countof(unicode_prop_Bidi_Mirrored_table),\n    countof(unicode_prop_Emoji_table),\n    countof(unicode_prop_Emoji_Component_table),\n    countof(unicode_prop_Emoji_Modifier_table),\n    countof(unicode_prop_Emoji_Modifier_Base_table),\n    countof(unicode_prop_Emoji_Presentation_table),\n    countof(unicode_prop_Extended_Pictographic_table),\n    countof(unicode_prop_Default_Ignorable_Code_Point_table),\n    countof(unicode_prop_ID_Start_table),\n    countof(unicode_prop_Case_Ignorable_table),\n};\n\n#endif /* CONFIG_ALL_UNICODE */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/libunicode.c",
    "content": "/*\n * Unicode utilities\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <string.h>\n#include <assert.h>\n\n#include \"cutils.h\"\n#include \"libunicode.h\"\n#include \"libunicode-table.h\"\n\nenum {\n    RUN_TYPE_U,\n    RUN_TYPE_L,\n    RUN_TYPE_UF,\n    RUN_TYPE_LF,\n    RUN_TYPE_UL,\n    RUN_TYPE_LSU,\n    RUN_TYPE_U2L_399_EXT2,\n    RUN_TYPE_UF_D20,\n    RUN_TYPE_UF_D1_EXT,\n    RUN_TYPE_U_EXT,\n    RUN_TYPE_LF_EXT,\n    RUN_TYPE_U_EXT2,\n    RUN_TYPE_L_EXT2,\n    RUN_TYPE_U_EXT3,\n};\n\n/* conv_type:\n   0 = to upper \n   1 = to lower\n   2 = case folding (= to lower with modifications) \n*/\nint lre_case_conv(uint32_t *res, uint32_t c, int conv_type)\n{\n    if (c < 128) {\n        if (conv_type) {\n            if (c >= 'A' && c <= 'Z') {\n                c = c - 'A' + 'a';\n            }\n        } else {\n            if (c >= 'a' && c <= 'z') {\n                c = c - 'a' + 'A';\n            }\n        }\n    } else {\n        uint32_t v, code, data, type, len, a, is_lower;\n        int idx, idx_min, idx_max;\n        \n        is_lower = (conv_type != 0);\n        idx_min = 0;\n        idx_max = countof(case_conv_table1) - 1;\n        while (idx_min <= idx_max) {\n            idx = (unsigned)(idx_max + idx_min) / 2;\n            v = case_conv_table1[idx];\n            code = v >> (32 - 17);\n            len = (v >> (32 - 17 - 7)) & 0x7f;\n            if (c < code) {\n                idx_max = idx - 1;\n            } else if (c >= code + len) {\n                idx_min = idx + 1;\n            } else {\n                type = (v >> (32 - 17 - 7 - 4)) & 0xf;\n                data = ((v & 0xf) << 8) | case_conv_table2[idx];\n                switch(type) {\n                case RUN_TYPE_U:\n                case RUN_TYPE_L:\n                case RUN_TYPE_UF:\n                case RUN_TYPE_LF:\n                    if (conv_type == (type & 1) ||\n                        (type >= RUN_TYPE_UF && conv_type == 2)) {\n                        c = c - code + (case_conv_table1[data] >> (32 - 17));\n                    }\n                    break;\n                case RUN_TYPE_UL:\n                    a = c - code;\n                    if ((a & 1) != (1 - is_lower))\n                        break;\n                    c = (a ^ 1) + code;\n                    break;\n                case RUN_TYPE_LSU:\n                    a = c - code;\n                    if (a == 1) {\n                        c += 2 * is_lower - 1;\n                    } else if (a == (1 - is_lower) * 2) {\n                        c += (2 * is_lower - 1) * 2;\n                    }\n                    break;\n                case RUN_TYPE_U2L_399_EXT2:\n                    if (!is_lower) {\n                        res[0] = c - code + case_conv_ext[data >> 6];\n                        res[1] = 0x399;\n                        return 2;\n                    } else {\n                        c = c - code + case_conv_ext[data & 0x3f];\n                    }\n                    break;\n                case RUN_TYPE_UF_D20:\n                    if (conv_type == 1)\n                        break;\n                    c = data + (conv_type == 2) * 0x20;\n                    break;\n                case RUN_TYPE_UF_D1_EXT:\n                    if (conv_type == 1)\n                        break;\n                    c = case_conv_ext[data] + (conv_type == 2);\n                    break;\n                case RUN_TYPE_U_EXT:\n                case RUN_TYPE_LF_EXT:\n                    if (is_lower != (type - RUN_TYPE_U_EXT))\n                        break;\n                    c = case_conv_ext[data];\n                    break;\n                case RUN_TYPE_U_EXT2:\n                case RUN_TYPE_L_EXT2:\n                    if (conv_type != (type - RUN_TYPE_U_EXT2))\n                        break;\n                    res[0] = c - code + case_conv_ext[data >> 6];\n                    res[1] = case_conv_ext[data & 0x3f];\n                    return 2;\n                default:\n                case RUN_TYPE_U_EXT3:\n                    if (conv_type != 0)\n                        break;\n                    res[0] = case_conv_ext[data >> 8];\n                    res[1] = case_conv_ext[(data >> 4) & 0xf];\n                    res[2] = case_conv_ext[data & 0xf];\n                    return 3;\n                }\n                break;\n            }\n        }\n    }\n    res[0] = c;\n    return 1;\n}\n\nstatic uint32_t get_le24(const uint8_t *ptr)\n{\n#if defined(__x86__) || defined(__x86_64__)\n    return *(uint16_t *)ptr | (ptr[2] << 16);\n#else\n    return ptr[0] | (ptr[1] << 8) | (ptr[2] << 16);\n#endif\n}\n\n#define UNICODE_INDEX_BLOCK_LEN 32\n\n/* return -1 if not in table, otherwise the offset in the block */\nstatic int get_index_pos(uint32_t *pcode, uint32_t c,\n                         const uint8_t *index_table, int index_table_len)\n{\n    uint32_t code, v;\n    int idx_min, idx_max, idx;\n\n    idx_min = 0;\n    v = get_le24(index_table);\n    code = v & ((1 << 21) - 1);\n    if (c < code) {\n        *pcode = 0;\n        return 0;\n    }\n    idx_max = index_table_len - 1;\n    code = get_le24(index_table + idx_max * 3);\n    if (c >= code)\n        return -1;\n    /* invariant: tab[idx_min] <= c < tab2[idx_max] */\n    while ((idx_max - idx_min) > 1) {\n        idx = (idx_max + idx_min) / 2;\n        v = get_le24(index_table + idx * 3);\n        code = v & ((1 << 21) - 1);\n        if (c < code) {\n            idx_max = idx;\n        } else {\n            idx_min = idx;\n        }\n    }\n    v = get_le24(index_table + idx_min * 3);\n    *pcode = v & ((1 << 21) - 1);\n    return (idx_min + 1) * UNICODE_INDEX_BLOCK_LEN + (v >> 21);\n}\n\nstatic BOOL lre_is_in_table(uint32_t c, const uint8_t *table,\n                            const uint8_t *index_table, int index_table_len)\n{\n    uint32_t code, b, bit;\n    int pos;\n    const uint8_t *p;\n    \n    pos = get_index_pos(&code, c, index_table, index_table_len);\n    if (pos < 0)\n        return FALSE; /* outside the table */\n    p = table + pos;\n    bit = 0;\n    for(;;) {\n        b = *p++;\n        if (b < 64) {\n            code += (b >> 3) + 1;\n            if (c < code)\n                return bit;\n            bit ^= 1;\n            code += (b & 7) + 1;\n        } else if (b >= 0x80) {\n            code += b - 0x80 + 1;\n        } else if (b < 0x60) {\n            code += (((b - 0x40) << 8) | p[0]) + 1;\n            p++;\n        } else {\n            code += (((b - 0x60) << 16) | (p[0] << 8) | p[1]) + 1;\n            p += 2;\n        }\n        if (c < code)\n            return bit;\n        bit ^= 1;\n    }\n}\n\nBOOL lre_is_cased(uint32_t c)\n{\n    uint32_t v, code, len;\n    int idx, idx_min, idx_max;\n        \n    idx_min = 0;\n    idx_max = countof(case_conv_table1) - 1;\n    while (idx_min <= idx_max) {\n        idx = (unsigned)(idx_max + idx_min) / 2;\n        v = case_conv_table1[idx];\n        code = v >> (32 - 17);\n        len = (v >> (32 - 17 - 7)) & 0x7f;\n        if (c < code) {\n            idx_max = idx - 1;\n        } else if (c >= code + len) {\n            idx_min = idx + 1;\n        } else {\n            return TRUE;\n        }\n    }\n    return lre_is_in_table(c, unicode_prop_Cased1_table,\n                           unicode_prop_Cased1_index,\n                           sizeof(unicode_prop_Cased1_index) / 3);\n}\n\nBOOL lre_is_case_ignorable(uint32_t c)\n{\n    return lre_is_in_table(c, unicode_prop_Case_Ignorable_table,\n                           unicode_prop_Case_Ignorable_index,\n                           sizeof(unicode_prop_Case_Ignorable_index) / 3);\n}\n\n/* character range */\n\nstatic __maybe_unused void cr_dump(CharRange *cr)\n{\n    int i;\n    for(i = 0; i < cr->len; i++)\n        printf(\"%d: 0x%04x\\n\", i, cr->points[i]);\n}\n\nstatic void *cr_default_realloc(void *opaque, void *ptr, size_t size)\n{\n    return realloc(ptr, size);\n}\n\nvoid cr_init(CharRange *cr, void *mem_opaque, DynBufReallocFunc *realloc_func)\n{\n    cr->len = cr->size = 0;\n    cr->points = NULL;\n    cr->mem_opaque = mem_opaque;\n    cr->realloc_func = realloc_func ? realloc_func : cr_default_realloc;\n}\n\nvoid cr_free(CharRange *cr)\n{\n    cr->realloc_func(cr->mem_opaque, cr->points, 0);\n}\n\nint cr_realloc(CharRange *cr, int size)\n{\n    int new_size;\n    uint32_t *new_buf;\n    \n    if (size > cr->size) {\n        new_size = max_int(size, cr->size * 3 / 2);\n        new_buf = cr->realloc_func(cr->mem_opaque, cr->points,\n                                   new_size * sizeof(cr->points[0]));\n        if (!new_buf)\n            return -1;\n        cr->points = new_buf;\n        cr->size = new_size;\n    }\n    return 0;\n}\n\nint cr_copy(CharRange *cr, const CharRange *cr1)\n{\n    if (cr_realloc(cr, cr1->len))\n        return -1;\n    memcpy(cr->points, cr1->points, sizeof(cr->points[0]) * cr1->len);\n    cr->len = cr1->len;\n    return 0;\n}\n\n/* merge consecutive intervals and remove empty intervals */\nstatic void cr_compress(CharRange *cr)\n{\n    int i, j, k, len;\n    uint32_t *pt;\n    \n    pt = cr->points;\n    len = cr->len;\n    i = 0;\n    j = 0;\n    k = 0;\n    while ((i + 1) < len) {\n        if (pt[i] == pt[i + 1]) {\n            /* empty interval */\n            i += 2;\n        } else {\n            j = i;\n            while ((j + 3) < len && pt[j + 1] == pt[j + 2])\n                j += 2;\n            /* just copy */\n            pt[k] = pt[i];\n            pt[k + 1] = pt[j + 1];\n            k += 2;\n            i = j + 2;\n        }\n    }\n    cr->len = k;\n}\n\n/* union or intersection */\nint cr_op(CharRange *cr, const uint32_t *a_pt, int a_len,\n          const uint32_t *b_pt, int b_len, int op)\n{\n    int a_idx, b_idx, is_in;\n    uint32_t v;\n    \n    a_idx = 0;\n    b_idx = 0;\n    for(;;) {\n        /* get one more point from a or b in increasing order */\n        if (a_idx < a_len && b_idx < b_len) {\n            if (a_pt[a_idx] < b_pt[b_idx]) {\n                goto a_add;\n            } else if (a_pt[a_idx] == b_pt[b_idx]) {\n                v = a_pt[a_idx];\n                a_idx++;\n                b_idx++;\n            } else {\n                goto b_add;\n            }\n        } else if (a_idx < a_len) {\n        a_add:\n            v = a_pt[a_idx++];\n        } else if (b_idx < b_len) {\n        b_add:\n            v = b_pt[b_idx++];\n        } else {\n            break;\n        }\n        /* add the point if the in/out status changes */\n        switch(op) {\n        case CR_OP_UNION:\n            is_in = (a_idx & 1) | (b_idx & 1);\n            break;\n        case CR_OP_INTER:\n            is_in = (a_idx & 1) & (b_idx & 1);\n            break;\n        case CR_OP_XOR:\n            is_in = (a_idx & 1) ^ (b_idx & 1);\n            break;\n        default:\n            abort();\n        }\n        if (is_in != (cr->len & 1)) {\n            if (cr_add_point(cr, v))\n                return -1;\n        }\n    }\n    cr_compress(cr);\n    return 0;\n}\n\nint cr_union1(CharRange *cr, const uint32_t *b_pt, int b_len)\n{\n    CharRange a = *cr;\n    int ret;\n    cr->len = 0;\n    cr->size = 0;\n    cr->points = NULL;\n    ret = cr_op(cr, a.points, a.len, b_pt, b_len, CR_OP_UNION);\n    cr_free(&a);\n    return ret;\n}\n\nint cr_invert(CharRange *cr)\n{\n    int len;\n    len = cr->len;\n    if (cr_realloc(cr, len + 2))\n        return -1;\n    memmove(cr->points + 1, cr->points, len * sizeof(cr->points[0]));\n    cr->points[0] = 0;\n    cr->points[len + 1] = UINT32_MAX;\n    cr->len = len + 2;\n    cr_compress(cr);\n    return 0;\n}\n\n#ifdef CONFIG_ALL_UNICODE\n\nBOOL lre_is_id_start(uint32_t c)\n{\n    return lre_is_in_table(c, unicode_prop_ID_Start_table,\n                           unicode_prop_ID_Start_index,\n                           sizeof(unicode_prop_ID_Start_index) / 3);\n}\n\nBOOL lre_is_id_continue(uint32_t c)\n{\n    return lre_is_id_start(c) ||\n        lre_is_in_table(c, unicode_prop_ID_Continue1_table,\n                        unicode_prop_ID_Continue1_index,\n                        sizeof(unicode_prop_ID_Continue1_index) / 3);\n}\n\n#define UNICODE_DECOMP_LEN_MAX 18\n\ntypedef enum {\n    DECOMP_TYPE_C1, /* 16 bit char */\n    DECOMP_TYPE_L1, /* 16 bit char table */\n    DECOMP_TYPE_L2,\n    DECOMP_TYPE_L3,\n    DECOMP_TYPE_L4,\n    DECOMP_TYPE_L5, /* XXX: not used */\n    DECOMP_TYPE_L6, /* XXX: could remove */\n    DECOMP_TYPE_L7, /* XXX: could remove */\n    DECOMP_TYPE_LL1, /* 18 bit char table */\n    DECOMP_TYPE_LL2,\n    DECOMP_TYPE_S1, /* 8 bit char table */\n    DECOMP_TYPE_S2,\n    DECOMP_TYPE_S3,\n    DECOMP_TYPE_S4,\n    DECOMP_TYPE_S5,\n    DECOMP_TYPE_I1, /* increment 16 bit char value */\n    DECOMP_TYPE_I2_0,\n    DECOMP_TYPE_I2_1,\n    DECOMP_TYPE_I3_1,\n    DECOMP_TYPE_I3_2,\n    DECOMP_TYPE_I4_1,\n    DECOMP_TYPE_I4_2,\n    DECOMP_TYPE_B1, /* 16 bit base + 8 bit offset */\n    DECOMP_TYPE_B2,\n    DECOMP_TYPE_B3,\n    DECOMP_TYPE_B4,\n    DECOMP_TYPE_B5,\n    DECOMP_TYPE_B6,\n    DECOMP_TYPE_B7,\n    DECOMP_TYPE_B8,\n    DECOMP_TYPE_B18,\n    DECOMP_TYPE_LS2,\n    DECOMP_TYPE_PAT3,\n    DECOMP_TYPE_S2_UL,\n    DECOMP_TYPE_LS2_UL,\n} DecompTypeEnum;\n\nstatic uint32_t unicode_get_short_code(uint32_t c)\n{\n    static const uint16_t unicode_short_table[2] = { 0x2044, 0x2215 };\n\n    if (c < 0x80)\n        return c;\n    else if (c < 0x80 + 0x50)\n        return c - 0x80 + 0x300;\n    else\n        return unicode_short_table[c - 0x80 - 0x50];\n}\n\nstatic uint32_t unicode_get_lower_simple(uint32_t c)\n{\n    if (c < 0x100 || (c >= 0x410 && c <= 0x42f))\n        c += 0x20;\n    else\n        c++;\n    return c;\n}\n\nstatic uint16_t unicode_get16(const uint8_t *p)\n{\n    return p[0] | (p[1] << 8);\n}\n\nstatic int unicode_decomp_entry(uint32_t *res, uint32_t c,\n                                int idx, uint32_t code, uint32_t len,\n                                uint32_t type)\n{\n    uint32_t c1;\n    int l, i, p;\n    const uint8_t *d;\n\n    if (type == DECOMP_TYPE_C1) {\n        res[0] = unicode_decomp_table2[idx];\n        return 1;\n    } else {\n        d = unicode_decomp_data + unicode_decomp_table2[idx];\n        switch(type) {\n        case DECOMP_TYPE_L1:\n        case DECOMP_TYPE_L2:\n        case DECOMP_TYPE_L3:\n        case DECOMP_TYPE_L4:\n        case DECOMP_TYPE_L5:\n        case DECOMP_TYPE_L6:\n        case DECOMP_TYPE_L7:\n            l = type - DECOMP_TYPE_L1 + 1;\n            d += (c - code) * l * 2;\n            for(i = 0; i < l; i++) {\n                if ((res[i] = unicode_get16(d + 2 * i)) == 0)\n                    return 0;\n            }\n            return l;\n        case DECOMP_TYPE_LL1:\n        case DECOMP_TYPE_LL2:\n            {\n                uint32_t k, p;\n                l = type - DECOMP_TYPE_LL1 + 1;\n                k = (c - code) * l;\n                p = len * l * 2;\n                for(i = 0; i < l; i++) {\n                    c1 = unicode_get16(d + 2 * k) |\n                        (((d[p + (k / 4)] >> ((k % 4) * 2)) & 3) << 16);\n                    if (!c1)\n                        return 0;\n                    res[i] = c1;\n                    k++;\n                }\n            }\n            return l;\n        case DECOMP_TYPE_S1:\n        case DECOMP_TYPE_S2:\n        case DECOMP_TYPE_S3:\n        case DECOMP_TYPE_S4:\n        case DECOMP_TYPE_S5:\n            l = type - DECOMP_TYPE_S1 + 1;\n            d += (c - code) * l;\n            for(i = 0; i < l; i++) {\n                if ((res[i] = unicode_get_short_code(d[i])) == 0)\n                    return 0;\n            }\n            return l;\n        case DECOMP_TYPE_I1:\n            l = 1;\n            p = 0;\n            goto decomp_type_i;\n        case DECOMP_TYPE_I2_0:\n        case DECOMP_TYPE_I2_1:\n        case DECOMP_TYPE_I3_1:\n        case DECOMP_TYPE_I3_2:\n        case DECOMP_TYPE_I4_1:\n        case DECOMP_TYPE_I4_2:\n            l = 2 + ((type - DECOMP_TYPE_I2_0) >> 1);\n            p = ((type - DECOMP_TYPE_I2_0) & 1) + (l > 2);\n        decomp_type_i:\n            for(i = 0; i < l; i++) {\n                c1 = unicode_get16(d + 2 * i);\n                if (i == p)\n                    c1 += c - code;\n                res[i] = c1;\n            }\n            return l;\n        case DECOMP_TYPE_B18:\n            l = 18;\n            goto decomp_type_b;\n        case DECOMP_TYPE_B1:\n        case DECOMP_TYPE_B2:\n        case DECOMP_TYPE_B3:\n        case DECOMP_TYPE_B4:\n        case DECOMP_TYPE_B5:\n        case DECOMP_TYPE_B6:\n        case DECOMP_TYPE_B7:\n        case DECOMP_TYPE_B8:\n            l = type - DECOMP_TYPE_B1 + 1;\n        decomp_type_b:\n            {\n                uint32_t c_min;\n                c_min = unicode_get16(d);\n                d += 2 + (c - code) * l;\n                for(i = 0; i < l; i++) {\n                    c1 = d[i];\n                    if (c1 == 0xff)\n                        c1 = 0x20;\n                    else\n                        c1 += c_min;\n                    res[i] = c1;\n                }\n            }\n            return l;\n        case DECOMP_TYPE_LS2:\n            d += (c - code) * 3;\n            if (!(res[0] = unicode_get16(d)))\n                return 0;\n            res[1] = unicode_get_short_code(d[2]);\n            return 2;\n        case DECOMP_TYPE_PAT3:\n            res[0] = unicode_get16(d);\n            res[2] = unicode_get16(d + 2);\n            d += 4 + (c - code) * 2;\n            res[1] = unicode_get16(d);\n            return 3;\n        case DECOMP_TYPE_S2_UL:\n        case DECOMP_TYPE_LS2_UL:\n            c1 = c - code;\n            if (type == DECOMP_TYPE_S2_UL) {\n                d += c1 & ~1;\n                c = unicode_get_short_code(*d);\n                d++;\n            } else {\n                d += (c1 >> 1) * 3;\n                c = unicode_get16(d);\n                d += 2;\n            }\n            if (c1 & 1)\n                c = unicode_get_lower_simple(c);\n            res[0] = c;\n            res[1] = unicode_get_short_code(*d);\n            return 2;\n        }\n    }\n    return 0;\n}\n\n\n/* return the length of the decomposition (length <=\n   UNICODE_DECOMP_LEN_MAX) or 0 if no decomposition */\nstatic int unicode_decomp_char(uint32_t *res, uint32_t c, BOOL is_compat1)\n{\n    uint32_t v, type, is_compat, code, len;\n    int idx_min, idx_max, idx;\n    \n    idx_min = 0;\n    idx_max = countof(unicode_decomp_table1) - 1;\n    while (idx_min <= idx_max) {\n        idx = (idx_max + idx_min) / 2;\n        v = unicode_decomp_table1[idx];\n        code = v >> (32 - 18);\n        len = (v >> (32 - 18 - 7)) & 0x7f;\n        //        printf(\"idx=%d code=%05x len=%d\\n\", idx, code, len);\n        if (c < code) {\n            idx_max = idx - 1;\n        } else if (c >= code + len) {\n            idx_min = idx + 1;\n        } else {\n            is_compat = v & 1;\n            if (is_compat1 < is_compat)\n                break;\n            type = (v >> (32 - 18 - 7 - 6)) & 0x3f;\n            return unicode_decomp_entry(res, c, idx, code, len, type);\n        }\n    }\n    return 0;\n}\n\n/* return 0 if no pair found */\nstatic int unicode_compose_pair(uint32_t c0, uint32_t c1)\n{\n    uint32_t code, len, type, v, idx1, d_idx, d_offset, ch;\n    int idx_min, idx_max, idx, d;\n    uint32_t pair[2];\n    \n    idx_min = 0;\n    idx_max = countof(unicode_comp_table) - 1;\n    while (idx_min <= idx_max) {\n        idx = (idx_max + idx_min) / 2;\n        idx1 = unicode_comp_table[idx];\n\n        /* idx1 represent an entry of the decomposition table */\n        d_idx = idx1 >> 6;\n        d_offset = idx1 & 0x3f;\n        v = unicode_decomp_table1[d_idx];\n        code = v >> (32 - 18);\n        len = (v >> (32 - 18 - 7)) & 0x7f;\n        type = (v >> (32 - 18 - 7 - 6)) & 0x3f;\n        ch = code + d_offset;\n        unicode_decomp_entry(pair, ch, d_idx, code, len, type);\n        d = c0 - pair[0];\n        if (d == 0)\n            d = c1 - pair[1];\n        if (d < 0) {\n            idx_max = idx - 1;\n        } else if (d > 0) {\n            idx_min = idx + 1;\n        } else {\n            return ch;\n        }\n    }\n    return 0;\n}\n\n/* return the combining class of character c (between 0 and 255) */\nstatic int unicode_get_cc(uint32_t c)\n{\n    uint32_t code, n, type, cc, c1, b;\n    int pos;\n    const uint8_t *p;\n    \n    pos = get_index_pos(&code, c,\n                        unicode_cc_index, sizeof(unicode_cc_index) / 3);\n    if (pos < 0)\n        return 0;\n    p = unicode_cc_table + pos;\n    for(;;) {\n        b = *p++;\n        type = b >> 6;\n        n = b & 0x3f;\n        if (n < 48) {\n        } else if (n < 56) {\n            n = (n - 48) << 8;\n            n |= *p++;\n            n += 48;\n        } else {\n            n = (n - 56) << 8;\n            n |= *p++ << 8;\n            n |= *p++;\n            n += 48 + (1 << 11);\n        }\n        if (type <= 1)\n            p++;\n        c1 = code + n + 1;\n        if (c < c1) {\n            switch(type) {\n            case 0:\n                cc = p[-1];\n                break;\n            case 1:\n                cc = p[-1] + c - code;\n                break;\n            case 2:\n                cc = 0;\n                break;\n            default:\n            case 3:\n                cc = 230;\n                break;\n            }\n            return cc;\n        }\n        code = c1;\n    }\n}\n\nstatic void sort_cc(int *buf, int len)\n{\n    int i, j, k, cc, cc1, start, ch1;\n    \n    for(i = 0; i < len; i++) {\n        cc = unicode_get_cc(buf[i]);\n        if (cc != 0) {\n            start = i;\n            j = i + 1;\n            while (j < len) {\n                ch1 = buf[j];\n                cc1 = unicode_get_cc(ch1);\n                if (cc1 == 0)\n                    break;\n                k = j - 1;\n                while (k >= start) {\n                    if (unicode_get_cc(buf[k]) <= cc1)\n                        break;\n                    buf[k + 1] = buf[k];\n                    k--;\n                }\n                buf[k + 1] = ch1;\n                j++;\n            }\n#if 0\n            printf(\"cc:\");\n            for(k = start; k < j; k++) {\n                printf(\" %3d\", unicode_get_cc(buf[k]));\n            }\n            printf(\"\\n\");\n#endif\n            i = j;\n        }\n    }\n}\n\nstatic void to_nfd_rec(DynBuf *dbuf,\n                       const int *src, int src_len, int is_compat)\n{\n    uint32_t c, v;\n    int i, l;\n    uint32_t res[UNICODE_DECOMP_LEN_MAX];\n    \n    for(i = 0; i < src_len; i++) {\n        c = src[i];\n        if (c >= 0xac00 && c < 0xd7a4) {\n            /* Hangul decomposition */\n            c -= 0xac00;\n            dbuf_put_u32(dbuf, 0x1100 + c / 588);\n            dbuf_put_u32(dbuf, 0x1161 + (c % 588) / 28);\n            v = c % 28;\n            if (v != 0)\n                dbuf_put_u32(dbuf, 0x11a7 + v);\n        } else {\n            l = unicode_decomp_char(res, c, is_compat);\n            if (l) {\n                to_nfd_rec(dbuf, (int *)res, l, is_compat);\n            } else {\n                dbuf_put_u32(dbuf, c);\n            }\n        }\n    }\n}\n\n/* return 0 if not found */\nstatic int compose_pair(uint32_t c0, uint32_t c1)\n{\n    /* Hangul composition */\n    if (c0 >= 0x1100 && c0 < 0x1100 + 19 &&\n        c1 >= 0x1161 && c1 < 0x1161 + 21) {\n        return 0xac00 + (c0 - 0x1100) * 588 + (c1 - 0x1161) * 28;\n    } else if (c0 >= 0xac00 && c0 < 0xac00 + 11172 &&\n               (c0 - 0xac00) % 28 == 0 &&\n               c1 >= 0x11a7 && c1 < 0x11a7 + 28) {\n        return c0 + c1 - 0x11a7;\n    } else {\n        return unicode_compose_pair(c0, c1);\n    }\n}\n\nint unicode_normalize(uint32_t **pdst, const uint32_t *src, int src_len,\n                      UnicodeNormalizationEnum n_type,\n                      void *opaque, DynBufReallocFunc *realloc_func)\n{\n    int *buf, buf_len, i, p, starter_pos, cc, last_cc, out_len;\n    BOOL is_compat;\n    DynBuf dbuf_s, *dbuf = &dbuf_s;\n    \n    is_compat = n_type >> 1;\n\n    dbuf_init2(dbuf, opaque, realloc_func);\n    if (dbuf_realloc(dbuf, sizeof(int) * src_len))\n        goto fail;\n\n    /* common case: latin1 is unaffected by NFC */\n    if (n_type == UNICODE_NFC) {\n        for(i = 0; i < src_len; i++) {\n            if (src[i] >= 0x100)\n                goto not_latin1;\n        }\n        buf = (int *)dbuf->buf;\n        memcpy(buf, src, src_len * sizeof(int));\n        *pdst = (uint32_t *)buf;\n        return src_len;\n    not_latin1: ;\n    }\n\n    to_nfd_rec(dbuf, (const int *)src, src_len, is_compat);\n    if (dbuf_error(dbuf)) {\n    fail:\n        *pdst = NULL;\n        return -1;\n    }\n    buf = (int *)dbuf->buf;\n    buf_len = dbuf->size / sizeof(int);\n        \n    sort_cc(buf, buf_len);\n    \n    if (buf_len <= 1 || (n_type & 1) != 0) {\n        /* NFD / NFKD */\n        *pdst = (uint32_t *)buf;\n        return buf_len;\n    }\n    \n    i = 1;\n    out_len = 1;\n    while (i < buf_len) {\n        /* find the starter character and test if it is blocked from\n           the character at 'i' */\n        last_cc = unicode_get_cc(buf[i]);\n        starter_pos = out_len - 1;\n        while (starter_pos >= 0) {\n            cc = unicode_get_cc(buf[starter_pos]);\n            if (cc == 0)\n                break;\n            if (cc >= last_cc)\n                goto next;\n            last_cc = 256;\n            starter_pos--;\n        }\n        if (starter_pos >= 0 &&\n            (p = compose_pair(buf[starter_pos], buf[i])) != 0) {\n            buf[starter_pos] = p;\n            i++;\n        } else {\n        next:\n            buf[out_len++] = buf[i++];\n        }\n    }\n    *pdst = (uint32_t *)buf;\n    return out_len;\n}\n\n/* char ranges for various unicode properties */\n\nstatic int unicode_find_name(const char *name_table, const char *name)\n{\n    const char *p, *r;\n    int pos;\n    size_t name_len, len;\n    \n    p = name_table;\n    pos = 0;\n    name_len = strlen(name);\n    while (*p) {\n        for(;;) {\n            r = strchr(p, ',');\n            if (!r)\n                len = strlen(p);\n            else\n                len = r - p;\n            if (len == name_len && !memcmp(p, name, name_len))\n                return pos;\n            p += len + 1;\n            if (!r)\n                break;\n        }\n        pos++;\n    }\n    return -1;\n}\n\n/* 'cr' must be initialized and empty. Return 0 if OK, -1 if error, -2\n   if not found */\nint unicode_script(CharRange *cr,\n                   const char *script_name, BOOL is_ext)\n{\n    int script_idx;\n    const uint8_t *p, *p_end;\n    uint32_t c, c1, b, n, v, v_len, i, type;\n    CharRange cr1_s, *cr1;\n    CharRange cr2_s, *cr2 = &cr2_s;\n    BOOL is_common;\n    \n    script_idx = unicode_find_name(unicode_script_name_table, script_name);\n    if (script_idx < 0)\n        return -2;\n    /* Note: we remove the \"Unknown\" Script */\n    script_idx += UNICODE_SCRIPT_Unknown + 1;\n        \n    is_common = (script_idx == UNICODE_SCRIPT_Common ||\n                 script_idx == UNICODE_SCRIPT_Inherited);\n    if (is_ext) {\n        cr1 = &cr1_s;\n        cr_init(cr1, cr->mem_opaque, cr->realloc_func);\n        cr_init(cr2, cr->mem_opaque, cr->realloc_func);\n    } else {\n        cr1 = cr;\n    }\n\n    p = unicode_script_table;\n    p_end = unicode_script_table + countof(unicode_script_table);\n    c = 0;\n    while (p < p_end) {\n        b = *p++;\n        type = b >> 7;\n        n = b & 0x7f;\n        if (n < 96) {\n        } else if (n < 112) {\n            n = (n - 96) << 8;\n            n |= *p++;\n            n += 96;\n        } else {\n            n = (n - 112) << 16;\n            n |= *p++ << 8;\n            n |= *p++;\n            n += 96 + (1 << 12);\n        }\n        if (type == 0)\n            v = 0;\n        else\n            v = *p++;\n        c1 = c + n + 1;\n        if (v == script_idx) {\n            if (cr_add_interval(cr1, c, c1))\n                goto fail;\n        }\n        c = c1;\n    }\n\n    if (is_ext) {\n        /* add the script extensions */\n        p = unicode_script_ext_table;\n        p_end = unicode_script_ext_table + countof(unicode_script_ext_table);\n        c = 0;\n        while (p < p_end) {\n            b = *p++;\n            if (b < 128) {\n                n = b;\n            } else if (b < 128 + 64) {\n                n = (b - 128) << 8;\n                n |= *p++;\n                n += 128;\n            } else {\n                n = (b - 128 - 64) << 16;\n                n |= *p++ << 8;\n                n |= *p++;\n                n += 128 + (1 << 14);\n            }\n            c1 = c + n + 1;\n            v_len = *p++;\n            if (is_common) {\n                if (v_len != 0) {\n                    if (cr_add_interval(cr2, c, c1))\n                        goto fail;\n                }\n            } else {\n                for(i = 0; i < v_len; i++) {\n                    if (p[i] == script_idx) {\n                        if (cr_add_interval(cr2, c, c1))\n                            goto fail;\n                        break;\n                    }\n                }\n            }\n            p += v_len;\n            c = c1;\n        }\n        if (is_common) {\n            /* remove all the characters with script extensions */\n            if (cr_invert(cr2))\n                goto fail;\n            if (cr_op(cr, cr1->points, cr1->len, cr2->points, cr2->len,\n                      CR_OP_INTER))\n                goto fail;\n        } else {\n            if (cr_op(cr, cr1->points, cr1->len, cr2->points, cr2->len,\n                      CR_OP_UNION))\n                goto fail;\n        }\n        cr_free(cr1);\n        cr_free(cr2);\n    }\n    return 0;\n fail:\n    if (is_ext) {\n        cr_free(cr1);\n        cr_free(cr2);\n    }\n    goto fail;\n}\n\n#define M(id) (1U << UNICODE_GC_ ## id)\n\nstatic int unicode_general_category1(CharRange *cr, uint32_t gc_mask)\n{\n    const uint8_t *p, *p_end;\n    uint32_t c, c0, b, n, v;\n\n    p = unicode_gc_table;\n    p_end = unicode_gc_table + countof(unicode_gc_table);\n    c = 0;\n    while (p < p_end) {\n        b = *p++;\n        n = b >> 5;\n        v = b & 0x1f;\n        if (n == 7) {\n            n = *p++;\n            if (n < 128) {\n                n += 7;\n            } else if (n < 128 + 64) {\n                n = (n - 128) << 8;\n                n |= *p++;\n                n += 7 + 128;\n            } else {\n                n = (n - 128 - 64) << 16;\n                n |= *p++ << 8;\n                n |= *p++;\n                n += 7 + 128 + (1 << 14);\n            }\n        }\n        c0 = c;\n        c += n + 1;\n        if (v == 31) {\n            /* run of Lu / Ll */\n            b = gc_mask & (M(Lu) | M(Ll));\n            if (b != 0) {\n                if (b == (M(Lu) | M(Ll))) {\n                    goto add_range;\n                } else {\n                    c0 += ((gc_mask & M(Ll)) != 0);\n                    for(; c0 < c; c0 += 2) {\n                        if (cr_add_interval(cr, c0, c0 + 1))\n                            return -1;\n                    }\n                }\n            }\n        } else if ((gc_mask >> v) & 1) {\n        add_range:\n            if (cr_add_interval(cr, c0, c))\n                return -1;\n        }\n    }\n    return 0;\n}\n\nstatic int unicode_prop1(CharRange *cr, int prop_idx)\n{\n    const uint8_t *p, *p_end;\n    uint32_t c, c0, b, bit;\n\n    p = unicode_prop_table[prop_idx];\n    p_end = p + unicode_prop_len_table[prop_idx];\n    c = 0;\n    bit = 0;\n    while (p < p_end) {\n        c0 = c;\n        b = *p++;\n        if (b < 64) {\n            c += (b >> 3) + 1;\n            if (bit)  {\n                if (cr_add_interval(cr, c0, c))\n                    return -1;\n            }\n            bit ^= 1;\n            c0 = c;\n            c += (b & 7) + 1;\n        } else if (b >= 0x80) {\n            c += b - 0x80 + 1;\n        } else if (b < 0x60) {\n            c += (((b - 0x40) << 8) | p[0]) + 1;\n            p++;\n        } else {\n            c += (((b - 0x60) << 16) | (p[0] << 8) | p[1]) + 1;\n            p += 2;\n        }\n        if (bit)  {\n            if (cr_add_interval(cr, c0, c))\n                return -1;\n        }\n        bit ^= 1;\n    }\n    return 0;\n}\n\n#define CASE_U (1 << 0)\n#define CASE_L (1 << 1)\n#define CASE_F (1 << 2)\n\n/* use the case conversion table to generate range of characters.\n   CASE_U: set char if modified by uppercasing,\n   CASE_L: set char if modified by lowercasing,\n   CASE_F: set char if modified by case folding,\n */\nstatic int unicode_case1(CharRange *cr, int case_mask)\n{\n#define MR(x) (1 << RUN_TYPE_ ## x)\n    const uint32_t tab_run_mask[3] = {\n        MR(U) | MR(UF) | MR(UL) | MR(LSU) | MR(U2L_399_EXT2) | MR(UF_D20) |\n        MR(UF_D1_EXT) | MR(U_EXT) | MR(U_EXT2) | MR(U_EXT3),\n\n        MR(L) | MR(LF) | MR(UL) | MR(LSU) | MR(U2L_399_EXT2) | MR(LF_EXT) | MR(L_EXT2),\n\n        MR(UF) | MR(LF) | MR(UL) | MR(LSU) | MR(U2L_399_EXT2) | MR(LF_EXT) | MR(UF_D20) | MR(UF_D1_EXT) | MR(LF_EXT),\n    };\n#undef MR\n    uint32_t mask, v, code, type, len, i, idx;\n\n    if (case_mask == 0)\n        return 0;\n    mask = 0;\n    for(i = 0; i < 3; i++) {\n        if ((case_mask >> i) & 1)\n            mask |= tab_run_mask[i];\n    }\n    for(idx = 0; idx < countof(case_conv_table1); idx++) {\n        v = case_conv_table1[idx];\n        type = (v >> (32 - 17 - 7 - 4)) & 0xf;\n        code = v >> (32 - 17);\n        len = (v >> (32 - 17 - 7)) & 0x7f;\n        if ((mask >> type) & 1) {\n            //            printf(\"%d: type=%d %04x %04x\\n\", idx, type, code, code + len - 1);\n            switch(type) {\n            case RUN_TYPE_UL:\n                if ((case_mask & CASE_U) && (case_mask & (CASE_L | CASE_F)))\n                    goto def_case;\n                code += ((case_mask & CASE_U) != 0);\n                for(i = 0; i < len; i += 2) {\n                    if (cr_add_interval(cr, code + i, code + i + 1))\n                        return -1;\n                }\n                break;\n            case RUN_TYPE_LSU:\n                if ((case_mask & CASE_U) && (case_mask & (CASE_L | CASE_F)))\n                    goto def_case;\n                if (!(case_mask & CASE_U)) {\n                    if (cr_add_interval(cr, code, code + 1))\n                        return -1;\n                }\n                if (cr_add_interval(cr, code + 1, code + 2))\n                    return -1;\n                if (case_mask & CASE_U) {\n                    if (cr_add_interval(cr, code + 2, code + 3))\n                        return -1;\n                }\n                break;\n            default:\n            def_case:\n                if (cr_add_interval(cr, code, code + len))\n                    return -1;\n                break;\n            }\n        }\n    }\n    return 0;\n}\n        \ntypedef enum {\n    POP_GC,\n    POP_PROP,\n    POP_CASE,\n    POP_UNION,\n    POP_INTER,\n    POP_XOR,\n    POP_INVERT,\n    POP_END,\n} PropOPEnum;\n\n#define POP_STACK_LEN_MAX 4\n\nstatic int unicode_prop_ops(CharRange *cr, ...)\n{\n    va_list ap;\n    CharRange stack[POP_STACK_LEN_MAX];\n    int stack_len, op, ret, i;\n    uint32_t a;\n    \n    va_start(ap, cr);\n    stack_len = 0;\n    for(;;) {\n        op = va_arg(ap, int);\n        switch(op) {\n        case POP_GC:\n            assert(stack_len < POP_STACK_LEN_MAX);\n            a = va_arg(ap, int);\n            cr_init(&stack[stack_len++], cr->mem_opaque, cr->realloc_func);\n            if (unicode_general_category1(&stack[stack_len - 1], a))\n                goto fail;\n            break;\n        case POP_PROP:\n            assert(stack_len < POP_STACK_LEN_MAX);\n            a = va_arg(ap, int);\n            cr_init(&stack[stack_len++], cr->mem_opaque, cr->realloc_func);\n            if (unicode_prop1(&stack[stack_len - 1], a))\n                goto fail;\n            break;\n        case POP_CASE:\n            assert(stack_len < POP_STACK_LEN_MAX);\n            a = va_arg(ap, int);\n            cr_init(&stack[stack_len++], cr->mem_opaque, cr->realloc_func);\n            if (unicode_case1(&stack[stack_len - 1], a))\n                goto fail;\n            break;\n        case POP_UNION:\n        case POP_INTER:\n        case POP_XOR:\n            {\n                CharRange *cr1, *cr2, *cr3;\n                assert(stack_len >= 2);\n                assert(stack_len < POP_STACK_LEN_MAX);\n                cr1 = &stack[stack_len - 2];\n                cr2 = &stack[stack_len - 1];\n                cr3 = &stack[stack_len++];\n                cr_init(cr3, cr->mem_opaque, cr->realloc_func);\n                if (cr_op(cr3, cr1->points, cr1->len,\n                          cr2->points, cr2->len, op - POP_UNION + CR_OP_UNION))\n                    goto fail;\n                cr_free(cr1);\n                cr_free(cr2);\n                *cr1 = *cr3;\n                stack_len -= 2;\n            }\n            break;\n        case POP_INVERT:\n            assert(stack_len >= 1);\n            if (cr_invert(&stack[stack_len - 1]))\n                goto fail;\n            break;\n        case POP_END:\n            goto done;\n        default:\n            abort();\n        }\n    }\n done:\n    assert(stack_len == 1);\n    ret = cr_copy(cr, &stack[0]);\n    cr_free(&stack[0]);\n    return ret;\n fail:\n    for(i = 0; i < stack_len; i++)\n        cr_free(&stack[i]);\n    return -1;\n}\n\nstatic const uint32_t unicode_gc_mask_table[] = {\n    M(Lu) | M(Ll) | M(Lt), /* LC */\n    M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo), /* L */\n    M(Mn) | M(Mc) | M(Me), /* M */\n    M(Nd) | M(Nl) | M(No), /* N */\n    M(Sm) | M(Sc) | M(Sk) | M(So), /* S */\n    M(Pc) | M(Pd) | M(Ps) | M(Pe) | M(Pi) | M(Pf) | M(Po), /* P */\n    M(Zs) | M(Zl) | M(Zp), /* Z */\n    M(Cc) | M(Cf) | M(Cs) | M(Co) | M(Cn), /* C */\n};\n\n/* 'cr' must be initialized and empty. Return 0 if OK, -1 if error, -2\n   if not found */\nint unicode_general_category(CharRange *cr, const char *gc_name)\n{\n    int gc_idx;\n    uint32_t gc_mask;\n    \n    gc_idx = unicode_find_name(unicode_gc_name_table, gc_name);\n    if (gc_idx < 0)\n        return -2;\n    if (gc_idx <= UNICODE_GC_Co) {\n        gc_mask = (uint64_t)1 << gc_idx;\n    } else {\n        gc_mask = unicode_gc_mask_table[gc_idx - UNICODE_GC_LC];\n    }\n    return unicode_general_category1(cr, gc_mask);\n}\n\n\n/* 'cr' must be initialized and empty. Return 0 if OK, -1 if error, -2\n   if not found */\nint unicode_prop(CharRange *cr, const char *prop_name)\n{\n    int prop_idx, ret;\n    \n    prop_idx = unicode_find_name(unicode_prop_name_table, prop_name);\n    if (prop_idx < 0)\n        return -2;\n    prop_idx += UNICODE_PROP_ASCII_Hex_Digit;\n\n    ret = 0;\n    switch(prop_idx) {\n    case UNICODE_PROP_ASCII:\n        if (cr_add_interval(cr, 0x00, 0x7f + 1))\n            return -1;\n        break;\n    case UNICODE_PROP_Any:\n        if (cr_add_interval(cr, 0x00000, 0x10ffff + 1))\n            return -1;\n        break;\n    case UNICODE_PROP_Assigned:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Cn),\n                               POP_INVERT,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Math:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Sm),\n                               POP_PROP, UNICODE_PROP_Other_Math,\n                               POP_UNION,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Lowercase:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Ll),\n                               POP_PROP, UNICODE_PROP_Other_Lowercase,\n                               POP_UNION,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Uppercase:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Lu),\n                               POP_PROP, UNICODE_PROP_Other_Uppercase,\n                               POP_UNION,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Cased:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Lu) | M(Ll) | M(Lt),\n                               POP_PROP, UNICODE_PROP_Other_Uppercase,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Other_Lowercase,\n                               POP_UNION,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Alphabetic:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl),\n                               POP_PROP, UNICODE_PROP_Other_Uppercase,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Other_Lowercase,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Other_Alphabetic,\n                               POP_UNION,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Grapheme_Base:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Cc) | M(Cf) | M(Cs) | M(Co) | M(Cn) | M(Zl) | M(Zp) | M(Me) | M(Mn),\n                               POP_PROP, UNICODE_PROP_Other_Grapheme_Extend,\n                               POP_UNION,\n                               POP_INVERT,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Grapheme_Extend:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Me) | M(Mn),\n                               POP_PROP, UNICODE_PROP_Other_Grapheme_Extend,\n                               POP_UNION,\n                               POP_END);\n        break;\n    case UNICODE_PROP_XID_Start:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl),\n                               POP_PROP, UNICODE_PROP_Other_ID_Start,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Pattern_Syntax,\n                               POP_PROP, UNICODE_PROP_Pattern_White_Space,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_XID_Start1,\n                               POP_UNION,\n                               POP_INVERT,\n                               POP_INTER,\n                               POP_END);\n        break;\n    case UNICODE_PROP_XID_Continue:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl) |\n                               M(Mn) | M(Mc) | M(Nd) | M(Pc),\n                               POP_PROP, UNICODE_PROP_Other_ID_Start,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Other_ID_Continue,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Pattern_Syntax,\n                               POP_PROP, UNICODE_PROP_Pattern_White_Space,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_XID_Continue1,\n                               POP_UNION,\n                               POP_INVERT,\n                               POP_INTER,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Changes_When_Uppercased:\n        ret = unicode_case1(cr, CASE_U);\n        break;\n    case UNICODE_PROP_Changes_When_Lowercased:\n        ret = unicode_case1(cr, CASE_L);\n        break;\n    case UNICODE_PROP_Changes_When_Casemapped:\n        ret = unicode_case1(cr, CASE_U | CASE_L | CASE_F);\n        break;\n    case UNICODE_PROP_Changes_When_Titlecased:\n        ret = unicode_prop_ops(cr,\n                               POP_CASE, CASE_U,\n                               POP_PROP, UNICODE_PROP_Changes_When_Titlecased1,\n                               POP_XOR,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Changes_When_Casefolded:\n        ret = unicode_prop_ops(cr,\n                               POP_CASE, CASE_F,\n                               POP_PROP, UNICODE_PROP_Changes_When_Casefolded1,\n                               POP_XOR,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Changes_When_NFKC_Casefolded:\n        ret = unicode_prop_ops(cr,\n                               POP_CASE, CASE_F,\n                               POP_PROP, UNICODE_PROP_Changes_When_NFKC_Casefolded1,\n                               POP_XOR,\n                               POP_END);\n        break;\n#if 0\n    case UNICODE_PROP_ID_Start:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl),\n                               POP_PROP, UNICODE_PROP_Other_ID_Start,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Pattern_Syntax,\n                               POP_PROP, UNICODE_PROP_Pattern_White_Space,\n                               POP_UNION,\n                               POP_INVERT,\n                               POP_INTER,\n                               POP_END);\n        break;\n    case UNICODE_PROP_ID_Continue:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl) |\n                               M(Mn) | M(Mc) | M(Nd) | M(Pc),\n                               POP_PROP, UNICODE_PROP_Other_ID_Start,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Other_ID_Continue,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Pattern_Syntax,\n                               POP_PROP, UNICODE_PROP_Pattern_White_Space,\n                               POP_UNION,\n                               POP_INVERT,\n                               POP_INTER,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Case_Ignorable:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Mn) | M(Cf) | M(Lm) | M(Sk),\n                               POP_PROP, UNICODE_PROP_Case_Ignorable1,\n                               POP_XOR,\n                               POP_END);\n        break;\n#else\n        /* we use the existing tables */\n    case UNICODE_PROP_ID_Continue:\n        ret = unicode_prop_ops(cr,\n                               POP_PROP, UNICODE_PROP_ID_Start,\n                               POP_PROP, UNICODE_PROP_ID_Continue1,\n                               POP_XOR,\n                               POP_END);\n        break;\n#endif\n    default:\n        if (prop_idx >= countof(unicode_prop_table))\n            return -2;\n        ret = unicode_prop1(cr, prop_idx);\n        break;\n    }\n    return ret;\n}\n\n#endif /* CONFIG_ALL_UNICODE */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/libunicode.h",
    "content": "/*\n * Unicode utilities\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#ifndef LIBUNICODE_H\n#define LIBUNICODE_H\n\n#include <inttypes.h>\n\n#define LRE_BOOL  int       /* for documentation purposes */\n\n/* define it to include all the unicode tables (40KB larger) */\n#define CONFIG_ALL_UNICODE\n\n#define LRE_CC_RES_LEN_MAX 3\n\ntypedef enum {\n    UNICODE_NFC,\n    UNICODE_NFD,\n    UNICODE_NFKC,\n    UNICODE_NFKD,\n} UnicodeNormalizationEnum;\n\nint lre_case_conv(uint32_t *res, uint32_t c, int conv_type);\nLRE_BOOL lre_is_cased(uint32_t c);\nLRE_BOOL lre_is_case_ignorable(uint32_t c);\n\n/* char ranges */\n\ntypedef struct {\n    int len; /* in points, always even */\n    int size;\n    uint32_t *points; /* points sorted by increasing value */\n    void *mem_opaque;\n    void *(*realloc_func)(void *opaque, void *ptr, size_t size);\n} CharRange;\n\ntypedef enum {\n    CR_OP_UNION,\n    CR_OP_INTER,\n    CR_OP_XOR,\n} CharRangeOpEnum;\n\nvoid cr_init(CharRange *cr, void *mem_opaque, void *(*realloc_func)(void *opaque, void *ptr, size_t size));\nvoid cr_free(CharRange *cr);\nint cr_realloc(CharRange *cr, int size);\nint cr_copy(CharRange *cr, const CharRange *cr1);\n\nstatic inline int cr_add_point(CharRange *cr, uint32_t v)\n{\n    if (cr->len >= cr->size) {\n        if (cr_realloc(cr, cr->len + 1))\n            return -1;\n    }\n    cr->points[cr->len++] = v;\n    return 0;\n}\n\nstatic inline int cr_add_interval(CharRange *cr, uint32_t c1, uint32_t c2)\n{\n    if ((cr->len + 2) > cr->size) {\n        if (cr_realloc(cr, cr->len + 2))\n            return -1;\n    }\n    cr->points[cr->len++] = c1;\n    cr->points[cr->len++] = c2;\n    return 0;\n}\n\nint cr_union1(CharRange *cr, const uint32_t *b_pt, int b_len);\n\nstatic inline int cr_union_interval(CharRange *cr, uint32_t c1, uint32_t c2)\n{\n    uint32_t b_pt[2];\n    b_pt[0] = c1;\n    b_pt[1] = c2 + 1;\n    return cr_union1(cr, b_pt, 2);\n}\n\nint cr_op(CharRange *cr, const uint32_t *a_pt, int a_len,\n          const uint32_t *b_pt, int b_len, int op);\n\nint cr_invert(CharRange *cr);\n\n#ifdef CONFIG_ALL_UNICODE\n\nLRE_BOOL lre_is_id_start(uint32_t c);\nLRE_BOOL lre_is_id_continue(uint32_t c);\n\nint unicode_normalize(uint32_t **pdst, const uint32_t *src, int src_len,\n                      UnicodeNormalizationEnum n_type,\n                      void *opaque, void *(*realloc_func)(void *opaque, void *ptr, size_t size));\n\n/* Unicode character range functions */\n\nint unicode_script(CharRange *cr,\n                   const char *script_name, LRE_BOOL is_ext);\nint unicode_general_category(CharRange *cr, const char *gc_name);\nint unicode_prop(CharRange *cr, const char *prop_name);\n\n#endif /* CONFIG_ALL_UNICODE */\n\n#undef LRE_BOOL\n\n#endif /* LIBUNICODE_H */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/list.h",
    "content": "/*\n * Linux klist like system\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#ifndef LIST_H\n#define LIST_H\n\n#ifndef NULL\n#include <stddef.h>\n#endif\n\nstruct list_head {\n    struct list_head *prev;\n    struct list_head *next;\n};\n\n#define LIST_HEAD_INIT(el) { &(el), &(el) }\n\n/* return the pointer of type 'type *' containing 'el' as field 'member' */\n#define list_entry(el, type, member) \\\n    ((type *)((uint8_t *)(el) - offsetof(type, member)))\n\nstatic inline void init_list_head(struct list_head *head)\n{\n    head->prev = head;\n    head->next = head;\n}\n\n/* insert 'el' between 'prev' and 'next' */\nstatic inline void __list_add(struct list_head *el, \n                              struct list_head *prev, struct list_head *next)\n{\n    prev->next = el;\n    el->prev = prev;\n    el->next = next;\n    next->prev = el;\n}\n\n/* add 'el' at the head of the list 'head' (= after element head) */\nstatic inline void list_add(struct list_head *el, struct list_head *head)\n{\n    __list_add(el, head, head->next);\n}\n\n/* add 'el' at the end of the list 'head' (= before element head) */\nstatic inline void list_add_tail(struct list_head *el, struct list_head *head)\n{\n    __list_add(el, head->prev, head);\n}\n\nstatic inline void list_del(struct list_head *el)\n{\n    struct list_head *prev, *next;\n    prev = el->prev;\n    next = el->next;\n    prev->next = next;\n    next->prev = prev;\n    el->prev = NULL; /* fail safe */\n    el->next = NULL; /* fail safe */\n}\n\nstatic inline int list_empty(struct list_head *el)\n{\n    return el->next == el;\n}\n\n#define list_for_each(el, head) \\\n  for(el = (head)->next; el != (head); el = el->next)\n\n#define list_for_each_safe(el, el1, head)                \\\n    for(el = (head)->next, el1 = el->next; el != (head); \\\n        el = el1, el1 = el->next)\n\n#define list_for_each_prev(el, head) \\\n  for(el = (head)->prev; el != (head); el = el->prev)\n\n#define list_for_each_prev_safe(el, el1, head)           \\\n    for(el = (head)->prev, el1 = el->prev; el != (head); \\\n        el = el1, el1 = el->prev)\n\n#endif /* LIST_H */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/qjs.c",
    "content": "/*\n * QuickJS stand alone interpreter\n * \n * Copyright (c) 2017-2021 Fabrice Bellard\n * Copyright (c) 2017-2021 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <inttypes.h>\n#include <string.h>\n#include <assert.h>\n#include <unistd.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <time.h>\n#if defined(__APPLE__)\n#include <malloc/malloc.h>\n#elif defined(__linux__)\n#include <malloc.h>\n#endif\n\n#include \"cutils.h\"\n#include \"quickjs-libc.h\"\n\nextern const uint8_t qjsc_repl[];\nextern const uint32_t qjsc_repl_size;\n#ifdef CONFIG_BIGNUM\nextern const uint8_t qjsc_qjscalc[];\nextern const uint32_t qjsc_qjscalc_size;\nstatic int bignum_ext;\n#endif\n\nstatic int eval_buf(JSContext *ctx, const void *buf, int buf_len,\n                    const char *filename, int eval_flags)\n{\n    JSValue val;\n    int ret;\n\n    if ((eval_flags & JS_EVAL_TYPE_MASK) == JS_EVAL_TYPE_MODULE) {\n        /* for the modules, we compile then run to be able to set\n           import.meta */\n        val = JS_Eval(ctx, buf, buf_len, filename,\n                      eval_flags | JS_EVAL_FLAG_COMPILE_ONLY);\n        if (!JS_IsException(val)) {\n            js_module_set_import_meta(ctx, val, TRUE, TRUE);\n            val = JS_EvalFunction(ctx, val);\n        }\n    } else {\n        val = JS_Eval(ctx, buf, buf_len, filename, eval_flags);\n    }\n    if (JS_IsException(val)) {\n        js_std_dump_error(ctx);\n        ret = -1;\n    } else {\n        ret = 0;\n    }\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nstatic int eval_file(JSContext *ctx, const char *filename, int module)\n{\n    uint8_t *buf;\n    int ret, eval_flags;\n    size_t buf_len;\n    \n    buf = js_load_file(ctx, &buf_len, filename);\n    if (!buf) {\n        perror(filename);\n        exit(1);\n    }\n\n    if (module < 0) {\n        module = (has_suffix(filename, \".mjs\") ||\n                  JS_DetectModule((const char *)buf, buf_len));\n    }\n    if (module)\n        eval_flags = JS_EVAL_TYPE_MODULE;\n    else\n        eval_flags = JS_EVAL_TYPE_GLOBAL;\n    ret = eval_buf(ctx, buf, buf_len, filename, eval_flags);\n    js_free(ctx, buf);\n    return ret;\n}\n\n/* also used to initialize the worker context */\nstatic JSContext *JS_NewCustomContext(JSRuntime *rt)\n{\n    JSContext *ctx;\n    ctx = JS_NewContext(rt);\n    if (!ctx)\n        return NULL;\n#ifdef CONFIG_BIGNUM\n    if (bignum_ext) {\n        JS_AddIntrinsicBigFloat(ctx);\n        JS_AddIntrinsicBigDecimal(ctx);\n        JS_AddIntrinsicOperators(ctx);\n        JS_EnableBignumExt(ctx, TRUE);\n    }\n#endif\n    /* system modules */\n    js_init_module_std(ctx, \"std\");\n    js_init_module_os(ctx, \"os\");\n    return ctx;\n}\n\n#if defined(__APPLE__)\n#define MALLOC_OVERHEAD  0\n#else\n#define MALLOC_OVERHEAD  8\n#endif\n\nstruct trace_malloc_data {\n    uint8_t *base;\n};\n\nstatic inline unsigned long long js_trace_malloc_ptr_offset(uint8_t *ptr,\n                                                struct trace_malloc_data *dp)\n{\n    return ptr - dp->base;\n}\n\n/* default memory allocation functions with memory limitation */\nstatic inline size_t js_trace_malloc_usable_size(void *ptr)\n{\n#if defined(__APPLE__)\n    return malloc_size(ptr);\n#elif defined(_WIN32)\n    return _msize(ptr);\n#elif defined(EMSCRIPTEN)\n    return 0;\n#elif defined(__linux__)\n    return malloc_usable_size(ptr);\n#else\n    /* change this to `return 0;` if compilation fails */\n    return malloc_usable_size(ptr);\n#endif\n}\n\nstatic void\n#ifdef _WIN32\n/* mingw printf is used */\n__attribute__((format(gnu_printf, 2, 3)))\n#else\n__attribute__((format(printf, 2, 3)))\n#endif\n    js_trace_malloc_printf(JSMallocState *s, const char *fmt, ...)\n{\n    va_list ap;\n    int c;\n\n    va_start(ap, fmt);\n    while ((c = *fmt++) != '\\0') {\n        if (c == '%') {\n            /* only handle %p and %zd */\n            if (*fmt == 'p') {\n                uint8_t *ptr = va_arg(ap, void *);\n                if (ptr == NULL) {\n                    printf(\"NULL\");\n                } else {\n                    printf(\"H%+06lld.%zd\",\n                           js_trace_malloc_ptr_offset(ptr, s->opaque),\n                           js_trace_malloc_usable_size(ptr));\n                }\n                fmt++;\n                continue;\n            }\n            if (fmt[0] == 'z' && fmt[1] == 'd') {\n                size_t sz = va_arg(ap, size_t);\n                printf(\"%zd\", sz);\n                fmt += 2;\n                continue;\n            }\n        }\n        putc(c, stdout);\n    }\n    va_end(ap);\n}\n\nstatic void js_trace_malloc_init(struct trace_malloc_data *s)\n{\n    free(s->base = malloc(8));\n}\n\nstatic void *js_trace_malloc(JSMallocState *s, size_t size)\n{\n    void *ptr;\n\n    /* Do not allocate zero bytes: behavior is platform dependent */\n    assert(size != 0);\n\n    if (unlikely(s->malloc_size + size > s->malloc_limit))\n        return NULL;\n    ptr = malloc(size);\n    js_trace_malloc_printf(s, \"A %zd -> %p\\n\", size, ptr);\n    if (ptr) {\n        s->malloc_count++;\n        s->malloc_size += js_trace_malloc_usable_size(ptr) + MALLOC_OVERHEAD;\n    }\n    return ptr;\n}\n\nstatic void js_trace_free(JSMallocState *s, void *ptr)\n{\n    if (!ptr)\n        return;\n\n    js_trace_malloc_printf(s, \"F %p\\n\", ptr);\n    s->malloc_count--;\n    s->malloc_size -= js_trace_malloc_usable_size(ptr) + MALLOC_OVERHEAD;\n    free(ptr);\n}\n\nstatic void *js_trace_realloc(JSMallocState *s, void *ptr, size_t size)\n{\n    size_t old_size;\n\n    if (!ptr) {\n        if (size == 0)\n            return NULL;\n        return js_trace_malloc(s, size);\n    }\n    old_size = js_trace_malloc_usable_size(ptr);\n    if (size == 0) {\n        js_trace_malloc_printf(s, \"R %zd %p\\n\", size, ptr);\n        s->malloc_count--;\n        s->malloc_size -= old_size + MALLOC_OVERHEAD;\n        free(ptr);\n        return NULL;\n    }\n    if (s->malloc_size + size - old_size > s->malloc_limit)\n        return NULL;\n\n    js_trace_malloc_printf(s, \"R %zd %p\", size, ptr);\n\n    ptr = realloc(ptr, size);\n    js_trace_malloc_printf(s, \" -> %p\\n\", ptr);\n    if (ptr) {\n        s->malloc_size += js_trace_malloc_usable_size(ptr) - old_size;\n    }\n    return ptr;\n}\n\nstatic const JSMallocFunctions trace_mf = {\n    js_trace_malloc,\n    js_trace_free,\n    js_trace_realloc,\n#if defined(__APPLE__)\n    malloc_size,\n#elif defined(_WIN32)\n    (size_t (*)(const void *))_msize,\n#elif defined(EMSCRIPTEN)\n    NULL,\n#elif defined(__linux__)\n    (size_t (*)(const void *))malloc_usable_size,\n#else\n    /* change this to `NULL,` if compilation fails */\n    malloc_usable_size,\n#endif\n};\n\n#define PROG_NAME \"qjs\"\n\nvoid help(void)\n{\n    printf(\"QuickJS version \" CONFIG_VERSION \"\\n\"\n           \"usage: \" PROG_NAME \" [options] [file [args]]\\n\"\n           \"-h  --help         list options\\n\"\n           \"-e  --eval EXPR    evaluate EXPR\\n\"\n           \"-i  --interactive  go to interactive mode\\n\"\n           \"-m  --module       load as ES6 module (default=autodetect)\\n\"\n           \"    --script       load as ES6 script (default=autodetect)\\n\"\n           \"-I  --include file include an additional file\\n\"\n           \"    --std          make 'std' and 'os' available to the loaded script\\n\"\n#ifdef CONFIG_BIGNUM\n           \"    --bignum       enable the bignum extensions (BigFloat, BigDecimal)\\n\"\n           \"    --qjscalc      load the QJSCalc runtime (default if invoked as qjscalc)\\n\"\n#endif\n           \"-T  --trace        trace memory allocation\\n\"\n           \"-d  --dump         dump the memory usage stats\\n\"\n           \"    --memory-limit n       limit the memory usage to 'n' bytes\\n\"\n           \"    --stack-size n         limit the stack size to 'n' bytes\\n\"\n           \"    --unhandled-rejection  dump unhandled promise rejections\\n\"\n           \"-q  --quit         just instantiate the interpreter and quit\\n\");\n    exit(1);\n}\n\nint main(int argc, char **argv)\n{\n    JSRuntime *rt;\n    JSContext *ctx;\n    struct trace_malloc_data trace_data = { NULL };\n    int optind;\n    char *expr = NULL;\n    int interactive = 0;\n    int dump_memory = 0;\n    int trace_memory = 0;\n    int empty_run = 0;\n    int module = -1;\n    int load_std = 0;\n    int dump_unhandled_promise_rejection = 0;\n    size_t memory_limit = 0;\n    char *include_list[32];\n    int i, include_count = 0;\n#ifdef CONFIG_BIGNUM\n    int load_jscalc;\n#endif\n    size_t stack_size = 0;\n    \n#ifdef CONFIG_BIGNUM\n    /* load jscalc runtime if invoked as 'qjscalc' */\n    {\n        const char *p, *exename;\n        exename = argv[0];\n        p = strrchr(exename, '/');\n        if (p)\n            exename = p + 1;\n        load_jscalc = !strcmp(exename, \"qjscalc\");\n    }\n#endif\n    \n    /* cannot use getopt because we want to pass the command line to\n       the script */\n    optind = 1;\n    while (optind < argc && *argv[optind] == '-') {\n        char *arg = argv[optind] + 1;\n        const char *longopt = \"\";\n        /* a single - is not an option, it also stops argument scanning */\n        if (!*arg)\n            break;\n        optind++;\n        if (*arg == '-') {\n            longopt = arg + 1;\n            arg += strlen(arg);\n            /* -- stops argument scanning */\n            if (!*longopt)\n                break;\n        }\n        for (; *arg || *longopt; longopt = \"\") {\n            char opt = *arg;\n            if (opt)\n                arg++;\n            if (opt == 'h' || opt == '?' || !strcmp(longopt, \"help\")) {\n                help();\n                continue;\n            }\n            if (opt == 'e' || !strcmp(longopt, \"eval\")) {\n                if (*arg) {\n                    expr = arg;\n                    break;\n                }\n                if (optind < argc) {\n                    expr = argv[optind++];\n                    break;\n                }\n                fprintf(stderr, \"qjs: missing expression for -e\\n\");\n                exit(2);\n            }\n            if (opt == 'I' || !strcmp(longopt, \"include\")) {\n                if (optind >= argc) {\n                    fprintf(stderr, \"expecting filename\");\n                    exit(1);\n                }\n                if (include_count >= countof(include_list)) {\n                    fprintf(stderr, \"too many included files\");\n                    exit(1);\n                }\n                include_list[include_count++] = argv[optind++];\n                continue;\n            }\n            if (opt == 'i' || !strcmp(longopt, \"interactive\")) {\n                interactive++;\n                continue;\n            }\n            if (opt == 'm' || !strcmp(longopt, \"module\")) {\n                module = 1;\n                continue;\n            }\n            if (!strcmp(longopt, \"script\")) {\n                module = 0;\n                continue;\n            }\n            if (opt == 'd' || !strcmp(longopt, \"dump\")) {\n                dump_memory++;\n                continue;\n            }\n            if (opt == 'T' || !strcmp(longopt, \"trace\")) {\n                trace_memory++;\n                continue;\n            }\n            if (!strcmp(longopt, \"std\")) {\n                load_std = 1;\n                continue;\n            }\n            if (!strcmp(longopt, \"unhandled-rejection\")) {\n                dump_unhandled_promise_rejection = 1;\n                continue;\n            }\n#ifdef CONFIG_BIGNUM\n            if (!strcmp(longopt, \"bignum\")) {\n                bignum_ext = 1;\n                continue;\n            }\n            if (!strcmp(longopt, \"qjscalc\")) {\n                load_jscalc = 1;\n                continue;\n            }\n#endif\n            if (opt == 'q' || !strcmp(longopt, \"quit\")) {\n                empty_run++;\n                continue;\n            }\n            if (!strcmp(longopt, \"memory-limit\")) {\n                if (optind >= argc) {\n                    fprintf(stderr, \"expecting memory limit\");\n                    exit(1);\n                }\n                memory_limit = (size_t)strtod(argv[optind++], NULL);\n                continue;\n            }\n            if (!strcmp(longopt, \"stack-size\")) {\n                if (optind >= argc) {\n                    fprintf(stderr, \"expecting stack size\");\n                    exit(1);\n                }\n                stack_size = (size_t)strtod(argv[optind++], NULL);\n                continue;\n            }\n            if (opt) {\n                fprintf(stderr, \"qjs: unknown option '-%c'\\n\", opt);\n            } else {\n                fprintf(stderr, \"qjs: unknown option '--%s'\\n\", longopt);\n            }\n            help();\n        }\n    }\n\n    if (load_jscalc)\n        bignum_ext = 1;\n\n    if (trace_memory) {\n        js_trace_malloc_init(&trace_data);\n        rt = JS_NewRuntime2(&trace_mf, &trace_data);\n    } else {\n        rt = JS_NewRuntime();\n    }\n    if (!rt) {\n        fprintf(stderr, \"qjs: cannot allocate JS runtime\\n\");\n        exit(2);\n    }\n    if (memory_limit != 0)\n        JS_SetMemoryLimit(rt, memory_limit);\n    if (stack_size != 0)\n        JS_SetMaxStackSize(rt, stack_size);\n    js_std_set_worker_new_context_func(JS_NewCustomContext);\n    js_std_init_handlers(rt);\n    ctx = JS_NewCustomContext(rt);\n    if (!ctx) {\n        fprintf(stderr, \"qjs: cannot allocate JS context\\n\");\n        exit(2);\n    }\n\n    /* loader for ES6 modules */\n    JS_SetModuleLoaderFunc(rt, NULL, js_module_loader, NULL);\n\n    if (dump_unhandled_promise_rejection) {\n        JS_SetHostPromiseRejectionTracker(rt, js_std_promise_rejection_tracker,\n                                          NULL);\n    }\n    \n    if (!empty_run) {\n#ifdef CONFIG_BIGNUM\n        if (load_jscalc) {\n            js_std_eval_binary(ctx, qjsc_qjscalc, qjsc_qjscalc_size, 0);\n        }\n#endif\n        js_std_add_helpers(ctx, argc - optind, argv + optind);\n\n        /* make 'std' and 'os' visible to non module code */\n        if (load_std) {\n            const char *str = \"import * as std from 'std';\\n\"\n                \"import * as os from 'os';\\n\"\n                \"globalThis.std = std;\\n\"\n                \"globalThis.os = os;\\n\";\n            eval_buf(ctx, str, strlen(str), \"<input>\", JS_EVAL_TYPE_MODULE);\n        }\n\n        for(i = 0; i < include_count; i++) {\n            if (eval_file(ctx, include_list[i], module))\n                goto fail;\n        }\n\n        if (expr) {\n            if (eval_buf(ctx, expr, strlen(expr), \"<cmdline>\", 0))\n                goto fail;\n        } else\n        if (optind >= argc) {\n            /* interactive mode */\n            interactive = 1;\n        } else {\n            const char *filename;\n            filename = argv[optind];\n            if (eval_file(ctx, filename, module))\n                goto fail;\n        }\n        if (interactive) {\n            js_std_eval_binary(ctx, qjsc_repl, qjsc_repl_size, 0);\n        }\n        js_std_loop(ctx);\n    }\n    \n    if (dump_memory) {\n        JSMemoryUsage stats;\n        JS_ComputeMemoryUsage(rt, &stats);\n        JS_DumpMemoryUsage(stdout, &stats, rt);\n    }\n    js_std_free_handlers(rt);\n    JS_FreeContext(ctx);\n    JS_FreeRuntime(rt);\n\n    if (empty_run && dump_memory) {\n        clock_t t[5];\n        double best[5];\n        int i, j;\n        for (i = 0; i < 100; i++) {\n            t[0] = clock();\n            rt = JS_NewRuntime();\n            t[1] = clock();\n            ctx = JS_NewContext(rt);\n            t[2] = clock();\n            JS_FreeContext(ctx);\n            t[3] = clock();\n            JS_FreeRuntime(rt);\n            t[4] = clock();\n            for (j = 4; j > 0; j--) {\n                double ms = 1000.0 * (t[j] - t[j - 1]) / CLOCKS_PER_SEC;\n                if (i == 0 || best[j] > ms)\n                    best[j] = ms;\n            }\n        }\n        printf(\"\\nInstantiation times (ms): %.3f = %.3f+%.3f+%.3f+%.3f\\n\",\n               best[1] + best[2] + best[3] + best[4],\n               best[1], best[2], best[3], best[4]);\n    }\n    return 0;\n fail:\n    js_std_free_handlers(rt);\n    JS_FreeContext(ctx);\n    JS_FreeRuntime(rt);\n    return 1;\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/qjsc.c",
    "content": "/*\n * QuickJS command line compiler\n * \n * Copyright (c) 2018-2021 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <inttypes.h>\n#include <string.h>\n#include <assert.h>\n#include <unistd.h>\n#include <errno.h>\n#if !defined(_WIN32)\n#include <sys/wait.h>\n#endif\n\n#include \"cutils.h\"\n#include \"quickjs-libc.h\"\n\ntypedef struct {\n    char *name;\n    char *short_name;\n    int flags;\n} namelist_entry_t;\n\ntypedef struct namelist_t {\n    namelist_entry_t *array;\n    int count;\n    int size;\n} namelist_t;\n\ntypedef struct {\n    const char *option_name;\n    const char *init_name;\n} FeatureEntry;\n\nstatic namelist_t cname_list;\nstatic namelist_t cmodule_list;\nstatic namelist_t init_module_list;\nstatic uint64_t feature_bitmap;\nstatic FILE *outfile;\nstatic BOOL byte_swap;\nstatic BOOL dynamic_export;\nstatic const char *c_ident_prefix = \"qjsc_\";\n\n#define FE_ALL (-1)\n\nstatic const FeatureEntry feature_list[] = {\n    { \"date\", \"Date\" },\n    { \"eval\", \"Eval\" },\n    { \"string-normalize\", \"StringNormalize\" },\n    { \"regexp\", \"RegExp\" },\n    { \"json\", \"JSON\" },\n    { \"proxy\", \"Proxy\" },\n    { \"map\", \"MapSet\" },\n    { \"typedarray\", \"TypedArrays\" },\n    { \"promise\", \"Promise\" },\n#define FE_MODULE_LOADER 9\n    { \"module-loader\", NULL },\n#ifdef CONFIG_BIGNUM\n    { \"bigint\", \"BigInt\" },\n#endif\n};\n\nvoid namelist_add(namelist_t *lp, const char *name, const char *short_name,\n                  int flags)\n{\n    namelist_entry_t *e;\n    if (lp->count == lp->size) {\n        size_t newsize = lp->size + (lp->size >> 1) + 4;\n        namelist_entry_t *a =\n            realloc(lp->array, sizeof(lp->array[0]) * newsize);\n        /* XXX: check for realloc failure */\n        lp->array = a;\n        lp->size = newsize;\n    }\n    e =  &lp->array[lp->count++];\n    e->name = strdup(name);\n    if (short_name)\n        e->short_name = strdup(short_name);\n    else\n        e->short_name = NULL;\n    e->flags = flags;\n}\n\nvoid namelist_free(namelist_t *lp)\n{\n    while (lp->count > 0) {\n        namelist_entry_t *e = &lp->array[--lp->count];\n        free(e->name);\n        free(e->short_name);\n    }\n    free(lp->array);\n    lp->array = NULL;\n    lp->size = 0;\n}\n\nnamelist_entry_t *namelist_find(namelist_t *lp, const char *name)\n{\n    int i;\n    for(i = 0; i < lp->count; i++) {\n        namelist_entry_t *e = &lp->array[i];\n        if (!strcmp(e->name, name))\n            return e;\n    }\n    return NULL;\n}\n\nstatic void get_c_name(char *buf, size_t buf_size, const char *file)\n{\n    const char *p, *r;\n    size_t len, i;\n    int c;\n    char *q;\n    \n    p = strrchr(file, '/');\n    if (!p)\n        p = file;\n    else\n        p++;\n    r = strrchr(p, '.');\n    if (!r)\n        len = strlen(p);\n    else\n        len = r - p;\n    pstrcpy(buf, buf_size, c_ident_prefix);\n    q = buf + strlen(buf);\n    for(i = 0; i < len; i++) {\n        c = p[i];\n        if (!((c >= '0' && c <= '9') ||\n              (c >= 'A' && c <= 'Z') ||\n              (c >= 'a' && c <= 'z'))) {\n            c = '_';\n        }\n        if ((q - buf) < buf_size - 1)\n            *q++ = c;\n    }\n    *q = '\\0';\n}\n\nstatic void dump_hex(FILE *f, const uint8_t *buf, size_t len)\n{\n    size_t i, col;\n    col = 0;\n    for(i = 0; i < len; i++) {\n        fprintf(f, \" 0x%02x,\", buf[i]);\n        if (++col == 8) {\n            fprintf(f, \"\\n\");\n            col = 0;\n        }\n    }\n    if (col != 0)\n        fprintf(f, \"\\n\");\n}\n\nstatic void output_object_code(JSContext *ctx,\n                               FILE *fo, JSValueConst obj, const char *c_name,\n                               BOOL load_only)\n{\n    uint8_t *out_buf;\n    size_t out_buf_len;\n    int flags;\n    flags = JS_WRITE_OBJ_BYTECODE;\n    if (byte_swap)\n        flags |= JS_WRITE_OBJ_BSWAP;\n    out_buf = JS_WriteObject(ctx, &out_buf_len, obj, flags);\n    if (!out_buf) {\n        js_std_dump_error(ctx);\n        exit(1);\n    }\n\n    namelist_add(&cname_list, c_name, NULL, load_only);\n    \n    fprintf(fo, \"const uint32_t %s_size = %u;\\n\\n\", \n            c_name, (unsigned int)out_buf_len);\n    fprintf(fo, \"const uint8_t %s[%u] = {\\n\",\n            c_name, (unsigned int)out_buf_len);\n    dump_hex(fo, out_buf, out_buf_len);\n    fprintf(fo, \"};\\n\\n\");\n\n    js_free(ctx, out_buf);\n}\n\nstatic int js_module_dummy_init(JSContext *ctx, JSModuleDef *m)\n{\n    /* should never be called when compiling JS code */\n    abort();\n}\n\nstatic void find_unique_cname(char *cname, size_t cname_size)\n{\n    char cname1[1024];\n    int suffix_num;\n    size_t len, max_len;\n    assert(cname_size >= 32);\n    /* find a C name not matching an existing module C name by\n       adding a numeric suffix */\n    len = strlen(cname);\n    max_len = cname_size - 16;\n    if (len > max_len)\n        cname[max_len] = '\\0';\n    suffix_num = 1;\n    for(;;) {\n        snprintf(cname1, sizeof(cname1), \"%s_%d\", cname, suffix_num);\n        if (!namelist_find(&cname_list, cname1))\n            break;\n        suffix_num++;\n    }\n    pstrcpy(cname, cname_size, cname1);\n}\n\nJSModuleDef *jsc_module_loader(JSContext *ctx,\n                              const char *module_name, void *opaque)\n{\n    JSModuleDef *m;\n    namelist_entry_t *e;\n\n    /* check if it is a declared C or system module */\n    e = namelist_find(&cmodule_list, module_name);\n    if (e) {\n        /* add in the static init module list */\n        namelist_add(&init_module_list, e->name, e->short_name, 0);\n        /* create a dummy module */\n        m = JS_NewCModule(ctx, module_name, js_module_dummy_init);\n    } else if (has_suffix(module_name, \".so\")) {\n        fprintf(stderr, \"Warning: binary module '%s' will be dynamically loaded\\n\", module_name);\n        /* create a dummy module */\n        m = JS_NewCModule(ctx, module_name, js_module_dummy_init);\n        /* the resulting executable will export its symbols for the\n           dynamic library */\n        dynamic_export = TRUE;\n    } else {\n        size_t buf_len;\n        uint8_t *buf;\n        JSValue func_val;\n        char cname[1024];\n        \n        buf = js_load_file(ctx, &buf_len, module_name);\n        if (!buf) {\n            JS_ThrowReferenceError(ctx, \"could not load module filename '%s'\",\n                                   module_name);\n            return NULL;\n        }\n        \n        /* compile the module */\n        func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name,\n                           JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);\n        js_free(ctx, buf);\n        if (JS_IsException(func_val))\n            return NULL;\n        get_c_name(cname, sizeof(cname), module_name);\n        if (namelist_find(&cname_list, cname)) {\n            find_unique_cname(cname, sizeof(cname));\n        }\n        output_object_code(ctx, outfile, func_val, cname, TRUE);\n        \n        /* the module is already referenced, so we must free it */\n        m = JS_VALUE_GET_PTR(func_val);\n        JS_FreeValue(ctx, func_val);\n    }\n    return m;\n}\n\nstatic void compile_file(JSContext *ctx, FILE *fo,\n                         const char *filename,\n                         const char *c_name1,\n                         int module)\n{\n    uint8_t *buf;\n    char c_name[1024];\n    int eval_flags;\n    JSValue obj;\n    size_t buf_len;\n    \n    buf = js_load_file(ctx, &buf_len, filename);\n    if (!buf) {\n        fprintf(stderr, \"Could not load '%s'\\n\", filename);\n        exit(1);\n    }\n    eval_flags = JS_EVAL_FLAG_COMPILE_ONLY;\n    if (module < 0) {\n        module = (has_suffix(filename, \".mjs\") ||\n                  JS_DetectModule((const char *)buf, buf_len));\n    }\n    if (module)\n        eval_flags |= JS_EVAL_TYPE_MODULE;\n    else\n        eval_flags |= JS_EVAL_TYPE_GLOBAL;\n    obj = JS_Eval(ctx, (const char *)buf, buf_len, filename, eval_flags);\n    if (JS_IsException(obj)) {\n        js_std_dump_error(ctx);\n        exit(1);\n    }\n    js_free(ctx, buf);\n    if (c_name1) {\n        pstrcpy(c_name, sizeof(c_name), c_name1);\n    } else {\n        get_c_name(c_name, sizeof(c_name), filename);\n    }\n    output_object_code(ctx, fo, obj, c_name, FALSE);\n    JS_FreeValue(ctx, obj);\n}\n\nstatic const char main_c_template1[] =\n    \"int main(int argc, char **argv)\\n\"\n    \"{\\n\"\n    \"  JSRuntime *rt;\\n\"\n    \"  JSContext *ctx;\\n\"\n    \"  rt = JS_NewRuntime();\\n\"\n    \"  js_std_set_worker_new_context_func(JS_NewCustomContext);\\n\"\n    \"  js_std_init_handlers(rt);\\n\"\n    ;\n\nstatic const char main_c_template2[] =\n    \"  js_std_loop(ctx);\\n\"\n    \"  JS_FreeContext(ctx);\\n\"\n    \"  JS_FreeRuntime(rt);\\n\"\n    \"  return 0;\\n\"\n    \"}\\n\";\n\n#define PROG_NAME \"qjsc\"\n\nvoid help(void)\n{\n    printf(\"QuickJS Compiler version \" CONFIG_VERSION \"\\n\"\n           \"usage: \" PROG_NAME \" [options] [files]\\n\"\n           \"\\n\"\n           \"options are:\\n\"\n           \"-c          only output bytecode in a C file\\n\"\n           \"-e          output main() and bytecode in a C file (default = executable output)\\n\"\n           \"-o output   set the output filename\\n\"\n           \"-N cname    set the C name of the generated data\\n\"\n           \"-m          compile as Javascript module (default=autodetect)\\n\"\n           \"-D module_name         compile a dynamically loaded module or worker\\n\"\n           \"-M module_name[,cname] add initialization code for an external C module\\n\"\n           \"-x          byte swapped output\\n\"\n           \"-p prefix   set the prefix of the generated C names\\n\"\n           \"-S n        set the maximum stack size to 'n' bytes (default=%d)\\n\",\n           JS_DEFAULT_STACK_SIZE);\n#ifdef CONFIG_LTO\n    {\n        int i;\n        printf(\"-flto       use link time optimization\\n\");\n        printf(\"-fbignum    enable bignum extensions\\n\");\n        printf(\"-fno-[\");\n        for(i = 0; i < countof(feature_list); i++) {\n            if (i != 0)\n                printf(\"|\");\n            printf(\"%s\", feature_list[i].option_name);\n        }\n        printf(\"]\\n\"\n               \"            disable selected language features (smaller code size)\\n\");\n    }\n#endif\n    exit(1);\n}\n\n#if defined(CONFIG_CC) && !defined(_WIN32)\n\nint exec_cmd(char **argv)\n{\n    int pid, status, ret;\n\n    pid = fork();\n    if (pid == 0) {\n        execvp(argv[0], argv);\n        exit(1);\n    } \n\n    for(;;) {\n        ret = waitpid(pid, &status, 0);\n        if (ret == pid && WIFEXITED(status))\n            break;\n    }\n    return WEXITSTATUS(status);\n}\n\nstatic int output_executable(const char *out_filename, const char *cfilename,\n                             BOOL use_lto, BOOL verbose, const char *exename)\n{\n    const char *argv[64];\n    const char **arg, *bn_suffix, *lto_suffix;\n    char libjsname[1024];\n    char exe_dir[1024], inc_dir[1024], lib_dir[1024], buf[1024], *p;\n    int ret;\n    \n    /* get the directory of the executable */\n    pstrcpy(exe_dir, sizeof(exe_dir), exename);\n    p = strrchr(exe_dir, '/');\n    if (p) {\n        *p = '\\0';\n    } else {\n        pstrcpy(exe_dir, sizeof(exe_dir), \".\");\n    }\n\n    /* if 'quickjs.h' is present at the same path as the executable, we\n       use it as include and lib directory */\n    snprintf(buf, sizeof(buf), \"%s/quickjs.h\", exe_dir);\n    if (access(buf, R_OK) == 0) {\n        pstrcpy(inc_dir, sizeof(inc_dir), exe_dir);\n        pstrcpy(lib_dir, sizeof(lib_dir), exe_dir);\n    } else {\n        snprintf(inc_dir, sizeof(inc_dir), \"%s/include/quickjs\", CONFIG_PREFIX);\n        snprintf(lib_dir, sizeof(lib_dir), \"%s/lib/quickjs\", CONFIG_PREFIX);\n    }\n    \n    lto_suffix = \"\";\n    bn_suffix = \"\";\n    \n    arg = argv;\n    *arg++ = CONFIG_CC;\n    *arg++ = \"-O2\";\n#ifdef CONFIG_LTO\n    if (use_lto) {\n        *arg++ = \"-flto\";\n        lto_suffix = \".lto\";\n    }\n#endif\n    /* XXX: use the executable path to find the includes files and\n       libraries */\n    *arg++ = \"-D\";\n    *arg++ = \"_GNU_SOURCE\";\n    *arg++ = \"-I\";\n    *arg++ = inc_dir;\n    *arg++ = \"-o\";\n    *arg++ = out_filename;\n    if (dynamic_export)\n        *arg++ = \"-rdynamic\";\n    *arg++ = cfilename;\n    snprintf(libjsname, sizeof(libjsname), \"%s/libquickjs%s%s.a\",\n             lib_dir, bn_suffix, lto_suffix);\n    *arg++ = libjsname;\n    *arg++ = \"-lm\";\n    *arg++ = \"-ldl\";\n    *arg++ = \"-lpthread\";\n    *arg = NULL;\n    \n    if (verbose) {\n        for(arg = argv; *arg != NULL; arg++)\n            printf(\"%s \", *arg);\n        printf(\"\\n\");\n    }\n    \n    ret = exec_cmd((char **)argv);\n    unlink(cfilename);\n    return ret;\n}\n#else\nstatic int output_executable(const char *out_filename, const char *cfilename,\n                             BOOL use_lto, BOOL verbose, const char *exename)\n{\n    fprintf(stderr, \"Executable output is not supported for this target\\n\");\n    exit(1);\n    return 0;\n}\n#endif\n\n\ntypedef enum {\n    OUTPUT_C,\n    OUTPUT_C_MAIN,\n    OUTPUT_EXECUTABLE,\n} OutputTypeEnum;\n\nint main(int argc, char **argv)\n{\n    int c, i, verbose;\n    const char *out_filename, *cname;\n    char cfilename[1024];\n    FILE *fo;\n    JSRuntime *rt;\n    JSContext *ctx;\n    BOOL use_lto;\n    int module;\n    OutputTypeEnum output_type;\n    size_t stack_size;\n#ifdef CONFIG_BIGNUM\n    BOOL bignum_ext = FALSE;\n#endif\n    namelist_t dynamic_module_list;\n    \n    out_filename = NULL;\n    output_type = OUTPUT_EXECUTABLE;\n    cname = NULL;\n    feature_bitmap = FE_ALL;\n    module = -1;\n    byte_swap = FALSE;\n    verbose = 0;\n    use_lto = FALSE;\n    stack_size = 0;\n    memset(&dynamic_module_list, 0, sizeof(dynamic_module_list));\n    \n    /* add system modules */\n    namelist_add(&cmodule_list, \"std\", \"std\", 0);\n    namelist_add(&cmodule_list, \"os\", \"os\", 0);\n\n    for(;;) {\n        c = getopt(argc, argv, \"ho:cN:f:mxevM:p:S:D:\");\n        if (c == -1)\n            break;\n        switch(c) {\n        case 'h':\n            help();\n        case 'o':\n            out_filename = optarg;\n            break;\n        case 'c':\n            output_type = OUTPUT_C;\n            break;\n        case 'e':\n            output_type = OUTPUT_C_MAIN;\n            break;\n        case 'N':\n            cname = optarg;\n            break;\n        case 'f':\n            {\n                const char *p;\n                p = optarg;\n                if (!strcmp(optarg, \"lto\")) {\n                    use_lto = TRUE;\n                } else if (strstart(p, \"no-\", &p)) {\n                    use_lto = TRUE;\n                    for(i = 0; i < countof(feature_list); i++) {\n                        if (!strcmp(p, feature_list[i].option_name)) {\n                            feature_bitmap &= ~((uint64_t)1 << i);\n                            break;\n                        }\n                    }\n                    if (i == countof(feature_list))\n                        goto bad_feature;\n                } else\n#ifdef CONFIG_BIGNUM\n                if (!strcmp(optarg, \"bignum\")) {\n                    bignum_ext = TRUE;\n                } else\n#endif\n                {\n                bad_feature:\n                    fprintf(stderr, \"unsupported feature: %s\\n\", optarg);\n                    exit(1);\n                }\n            }\n            break;\n        case 'm':\n            module = 1;\n            break;\n        case 'M':\n            {\n                char *p;\n                char path[1024];\n                char cname[1024];\n                pstrcpy(path, sizeof(path), optarg);\n                p = strchr(path, ',');\n                if (p) {\n                    *p = '\\0';\n                    pstrcpy(cname, sizeof(cname), p + 1);\n                } else {\n                    get_c_name(cname, sizeof(cname), path);\n                }\n                namelist_add(&cmodule_list, path, cname, 0);\n            }\n            break;\n        case 'D':\n            namelist_add(&dynamic_module_list, optarg, NULL, 0);\n            break;\n        case 'x':\n            byte_swap = TRUE;\n            break;\n        case 'v':\n            verbose++;\n            break;\n        case 'p':\n            c_ident_prefix = optarg;\n            break;\n        case 'S':\n            stack_size = (size_t)strtod(optarg, NULL);\n            break;\n        default:\n            break;\n        }\n    }\n\n    if (optind >= argc)\n        help();\n\n    if (!out_filename) {\n        if (output_type == OUTPUT_EXECUTABLE) {\n            out_filename = \"a.out\";\n        } else {\n            out_filename = \"out.c\";\n        }\n    }\n\n    if (output_type == OUTPUT_EXECUTABLE) {\n#if defined(_WIN32) || defined(__ANDROID__)\n        /* XXX: find a /tmp directory ? */\n        snprintf(cfilename, sizeof(cfilename), \"out%d.c\", getpid());\n#else\n        snprintf(cfilename, sizeof(cfilename), \"/tmp/out%d.c\", getpid());\n#endif\n    } else {\n        pstrcpy(cfilename, sizeof(cfilename), out_filename);\n    }\n    \n    fo = fopen(cfilename, \"w\");\n    if (!fo) {\n        perror(cfilename);\n        exit(1);\n    }\n    outfile = fo;\n    \n    rt = JS_NewRuntime();\n    ctx = JS_NewContext(rt);\n#ifdef CONFIG_BIGNUM\n    if (bignum_ext) {\n        JS_AddIntrinsicBigFloat(ctx);\n        JS_AddIntrinsicBigDecimal(ctx);\n        JS_AddIntrinsicOperators(ctx);\n        JS_EnableBignumExt(ctx, TRUE);\n    }\n#endif\n    \n    /* loader for ES6 modules */\n    JS_SetModuleLoaderFunc(rt, NULL, jsc_module_loader, NULL);\n\n    fprintf(fo, \"/* File generated automatically by the QuickJS compiler. */\\n\"\n            \"\\n\"\n            );\n    \n    if (output_type != OUTPUT_C) {\n        fprintf(fo, \"#include \\\"quickjs-libc.h\\\"\\n\"\n                \"\\n\"\n                );\n    } else {\n        fprintf(fo, \"#include <inttypes.h>\\n\"\n                \"\\n\"\n                );\n    }\n\n    for(i = optind; i < argc; i++) {\n        const char *filename = argv[i];\n        compile_file(ctx, fo, filename, cname, module);\n        cname = NULL;\n    }\n\n    for(i = 0; i < dynamic_module_list.count; i++) {\n        if (!jsc_module_loader(ctx, dynamic_module_list.array[i].name, NULL)) {\n            fprintf(stderr, \"Could not load dynamic module '%s'\\n\",\n                    dynamic_module_list.array[i].name);\n            exit(1);\n        }\n    }\n    \n    if (output_type != OUTPUT_C) {\n        fprintf(fo,\n                \"static JSContext *JS_NewCustomContext(JSRuntime *rt)\\n\"\n                \"{\\n\"\n                \"  JSContext *ctx = JS_NewContextRaw(rt);\\n\"\n                \"  if (!ctx)\\n\"\n                \"    return NULL;\\n\");\n        /* add the basic objects */\n        fprintf(fo, \"  JS_AddIntrinsicBaseObjects(ctx);\\n\");\n        for(i = 0; i < countof(feature_list); i++) {\n            if ((feature_bitmap & ((uint64_t)1 << i)) &&\n                feature_list[i].init_name) {\n                fprintf(fo, \"  JS_AddIntrinsic%s(ctx);\\n\",\n                        feature_list[i].init_name);\n            }\n        }\n#ifdef CONFIG_BIGNUM\n        if (bignum_ext) {\n            fprintf(fo,\n                    \"  JS_AddIntrinsicBigFloat(ctx);\\n\"\n                    \"  JS_AddIntrinsicBigDecimal(ctx);\\n\"\n                    \"  JS_AddIntrinsicOperators(ctx);\\n\"\n                    \"  JS_EnableBignumExt(ctx, 1);\\n\");\n        }\n#endif\n        /* add the precompiled modules (XXX: could modify the module\n           loader instead) */\n        for(i = 0; i < init_module_list.count; i++) {\n            namelist_entry_t *e = &init_module_list.array[i];\n            /* initialize the static C modules */\n            \n            fprintf(fo,\n                    \"  {\\n\"\n                    \"    extern JSModuleDef *js_init_module_%s(JSContext *ctx, const char *name);\\n\"\n                    \"    js_init_module_%s(ctx, \\\"%s\\\");\\n\"\n                    \"  }\\n\",\n                    e->short_name, e->short_name, e->name);\n        }\n        for(i = 0; i < cname_list.count; i++) {\n            namelist_entry_t *e = &cname_list.array[i];\n            if (e->flags) {\n                fprintf(fo, \"  js_std_eval_binary(ctx, %s, %s_size, 1);\\n\",\n                        e->name, e->name);\n            }\n        }\n        fprintf(fo,\n                \"  return ctx;\\n\"\n                \"}\\n\\n\");\n        \n        fputs(main_c_template1, fo);\n\n        if (stack_size != 0) {\n            fprintf(fo, \"  JS_SetMaxStackSize(rt, %u);\\n\",\n                    (unsigned int)stack_size);\n        }\n        \n        /* add the module loader if necessary */\n        if (feature_bitmap & (1 << FE_MODULE_LOADER)) {\n            fprintf(fo, \"  JS_SetModuleLoaderFunc(rt, NULL, js_module_loader, NULL);\\n\");\n        }\n        \n        fprintf(fo,\n                \"  ctx = JS_NewCustomContext(rt);\\n\"\n                \"  js_std_add_helpers(ctx, argc, argv);\\n\");\n\n        for(i = 0; i < cname_list.count; i++) {\n            namelist_entry_t *e = &cname_list.array[i];\n            if (!e->flags) {\n                fprintf(fo, \"  js_std_eval_binary(ctx, %s, %s_size, 0);\\n\",\n                        e->name, e->name);\n            }\n        }\n        fputs(main_c_template2, fo);\n    }\n    \n    JS_FreeContext(ctx);\n    JS_FreeRuntime(rt);\n\n    fclose(fo);\n\n    if (output_type == OUTPUT_EXECUTABLE) {\n        return output_executable(out_filename, cfilename, use_lto, verbose,\n                                 argv[0]);\n    }\n    namelist_free(&cname_list);\n    namelist_free(&cmodule_list);\n    namelist_free(&init_module_list);\n    return 0;\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/qjscalc.js",
    "content": "/*\n * QuickJS Javascript Calculator\n * \n * Copyright (c) 2017-2020 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\"use strict\";\n\"use math\";\n\nvar Integer, Float, Fraction, Complex, Mod, Polynomial, PolyMod, RationalFunction, Series, Matrix;\n\n(function(global) {\n    global.Integer = global.BigInt;\n    global.Float = global.BigFloat;\n    global.algebraicMode = true;\n    \n    /* add non enumerable properties */\n    function add_props(obj, props) {\n        var i, val, prop, tab, desc;\n        tab = Reflect.ownKeys(props);\n        for(i = 0; i < tab.length; i++) {\n            prop = tab[i];\n            desc = Object.getOwnPropertyDescriptor(props, prop);\n            desc.enumerable = false;\n            if (\"value\" in desc) {\n                if (typeof desc.value !== \"function\") {\n                    desc.writable = false;\n                    desc.configurable = false;\n                }\n            } else {\n                /* getter/setter */\n                desc.configurable = false;\n            }\n            Object.defineProperty(obj, prop, desc);\n        }\n    }\n\n    /* same as proto[Symbol.operatorSet] = Operators.create(..op_list)\n       but allow shortcuts: left: [], right: [] or both\n    */\n    function operators_set(proto, ...op_list)\n    {\n        var new_op_list, i, a, j, b, k, obj, tab;\n        var fields = [ \"left\", \"right\" ];\n        new_op_list = [];\n        for(i = 0; i < op_list.length; i++) {\n            a = op_list[i];\n            if (a.left || a.right) {\n                tab = [ a.left, a.right ];\n                delete a.left;\n                delete a.right;\n                for(k = 0; k < 2; k++) {\n                    obj = tab[k];\n                    if (obj) {\n                        if (!Array.isArray(obj)) {\n                            obj = [ obj ];\n                        }\n                        for(j = 0; j < obj.length; j++) {\n                            b = {};\n                            Object.assign(b, a);\n                            b[fields[k]] = obj[j];\n                            new_op_list.push(b);\n                        }\n                    }\n                }\n            } else {\n                new_op_list.push(a);\n            }\n        }\n        proto[Symbol.operatorSet] =\n            Operators.create.call(null, ...new_op_list); \n    }\n    \n    /* Integer */\n\n    function generic_pow(a, b) {\n        var r, is_neg, i;\n        if (!Integer.isInteger(b)) {\n            return exp(log(a) * b);\n        }\n        if (Array.isArray(a) && !(a instanceof Polynomial ||\n                                  a instanceof Series)) {\n            r = idn(Matrix.check_square(a));\n        } else {\n            r = 1;\n        }\n        if (b == 0)\n            return r;\n        is_neg = false;\n        if (b < 0) {\n            is_neg = true;\n            b = -b;\n        }\n        r = a;\n        for(i = Integer.floorLog2(b) - 1; i >= 0; i--) {\n            r *= r;\n            if ((b >> i) & 1)\n                r *= a;\n        }\n        if (is_neg) {\n            if (typeof r.inverse != \"function\")\n                throw \"negative powers are not supported for this type\";\n            r = r.inverse();\n        }\n        return r;\n    }\n    \n    var small_primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499 ];\n\n    function miller_rabin_test(n, t) {\n        var d, r, s, i, j, a;\n        d = n - 1;\n        s = 0;\n        while ((d & 1) == 0) {\n            d >>= 1;\n            s++;\n        }\n        if (small_primes.length < t)\n            t = small_primes.length;\n        loop: for(j = 0; j < t; j++) {\n            a = small_primes[j];\n            r = Integer.pmod(a, d, n);\n            if (r == 1 || r == (n - 1))\n                continue;\n            for(i = 1; i < s; i++) {\n                r = (r * r) % n;\n                if (r == 1)\n                    return false;\n                if (r == (n - 1))\n                    continue loop;\n            }\n            return false; /* n is composite */\n        }\n        return true; /* n is probably prime with probability (1-0.5^t) */\n    }\n\n    function fact_rec(a, b) {  /* assumes a <= b */\n        var i, r;\n        if ((b - a) <= 5) {\n            r = a;\n            for(i = a + 1; i <= b; i++)\n                r *= i;\n            return r;\n        } else {\n            /* to avoid a quadratic running time it is better to\n               multiply numbers of similar size */\n            i = (a + b) >> 1;\n            return fact_rec(a, i) * fact_rec(i + 1, b);\n        }\n    }\n\n    /* math mode specific quirk to overload the integer division and power */\n    Operators.updateBigIntOperators(\n        {\n            \"/\"(a, b) {\n                if (algebraicMode) {\n                    return Fraction.toFraction(a, b);\n                } else {\n                    return Float(a) / Float(b);\n                }\n            },\n            \"**\"(a, b) {\n                if (algebraicMode) {\n                    return generic_pow(a, b);\n                } else {\n                    return Float(a) ** Float(b);\n                }\n            }\n        });\n            \n    add_props(Integer, {\n        isInteger(a) {\n            /* integers are represented either as bigint or as number */\n            return typeof a === \"bigint\" ||\n                (typeof a === \"number\" && Number.isSafeInteger(a));\n        },\n        gcd(a, b) {\n            var r;\n            while (b != 0) {\n                r = a % b;\n                a = b;\n                b = r;\n            }\n            return a;\n        },\n        fact(n) {\n            return n <= 0 ? 1 : fact_rec(1, n);\n        },\n        /* binomial coefficient */\n        comb(n, k) {\n            if (k < 0 || k > n)\n                return 0;\n            if (k > n - k)\n                k = n - k;\n            if (k == 0)\n                return 1;\n            return Integer.tdiv(fact_rec(n - k + 1, n), fact_rec(1, k));\n        },\n        /* inverse of x modulo y */\n        invmod(x, y) {\n            var q, u, v, a, c, t;\n            u = x;\n            v = y;\n            c = 1;\n            a = 0;\n            while (u != 0) {\n                t = Integer.fdivrem(v, u);\n                q = t[0];\n                v = u;\n                u = t[1];\n                t = c;\n                c = a - q * c;\n                a = t;\n            }\n            /* v = gcd(x, y) */\n            if (v != 1)\n                throw RangeError(\"not invertible\");\n            return a % y;\n        },\n        /* return a ^ b modulo m */\n        pmod(a, b, m) {\n            var r;\n            if (b == 0)\n                return 1;\n            if (b < 0) {\n                a = Integer.invmod(a, m);\n                b = -b;\n            }\n            r = 1;\n            for(;;) {\n                if (b & 1) {\n                    r = (r * a) % m;\n                }\n                b >>= 1;\n                if (b == 0)\n                    break;\n                a = (a * a) % m;\n            }\n            return r;\n        },\n\n        /* return true if n is prime (or probably prime with\n           probability 1-0.5^t) */\n        isPrime(n, t) {\n            var i, d, n1;\n            if (!Integer.isInteger(n))\n                throw TypeError(\"invalid type\");\n            if (n <= 1)\n                return false;\n            n1 = small_primes.length;\n            /* XXX: need Integer.sqrt() */\n            for(i = 0; i < n1; i++) {\n                d = small_primes[i];\n                if (d == n)\n                    return true;\n                if (d > n)\n                    return false;\n                if ((n % d) == 0)\n                    return false;\n            }\n            if (n < d * d)\n                return true;\n            if (typeof t == \"undefined\")\n                t = 64;\n            return miller_rabin_test(n, t);\n        },\n        nextPrime(n) {\n            if (!Integer.isInteger(n))\n                throw TypeError(\"invalid type\");\n            if (n < 1)\n                n = 1;\n            for(;;) {\n                n++;\n                if (Integer.isPrime(n))\n                    return n;\n            }\n        },\n        factor(n) {\n            var r, d;\n            if (!Integer.isInteger(n))\n                throw TypeError(\"invalid type\");\n            r = [];\n            if (abs(n) <= 1) {\n                r.push(n);\n                return r;\n            }\n            if (n < 0) {\n                r.push(-1);\n                n = -n;\n            }\n            \n            while ((n % 2) == 0) {\n                n >>= 1;\n                r.push(2);\n            }\n\n            d = 3;\n            while (n != 1) {\n                if (Integer.isPrime(n)) {\n                    r.push(n);\n                    break;\n                }\n                /* we are sure there is at least one divisor, so one test */\n                for(;;) {\n                    if ((n % d) == 0)\n                        break;\n                    d += 2;\n                }\n                for(;;) {\n                    r.push(d);\n                    n = Integer.tdiv(n, d);\n                    if ((n % d) != 0)\n                        break;\n                }\n            }\n            return r;\n        },\n    });\n\n    add_props(Integer.prototype, {\n        inverse() {\n            return 1 / this;\n        },\n        norm2() {\n            return this * this;\n        },\n        abs() {\n            var v = this;\n            if (v < 0)\n                v = -v;\n            return v;\n        },\n        conj() {\n            return this;\n        },\n        arg() {\n            if (this >= 0)\n                return 0;\n            else\n                return Float.PI;\n        },\n        exp() {\n            if (this == 0)\n                return 1;\n            else\n                return Float.exp(this);\n        },\n        log() {\n            if (this == 1)\n                return 0;\n            else\n                return Float(this).log();\n        },\n    });\n\n    /* Fraction */\n\n    Fraction = function Fraction(a, b)\n    {\n        var d, r, obj;\n\n        if (new.target)\n            throw TypeError(\"not a constructor\");\n        if (a instanceof Fraction)\n            return a;\n        if (!Integer.isInteger(a))\n            throw TypeError(\"integer expected\");\n        if (typeof b === \"undefined\") {\n            b = 1;\n        } else {\n            if (!Integer.isInteger(b))\n                throw TypeError(\"integer expected\");\n            if (b == 0)\n                throw RangeError(\"division by zero\");\n            d = Integer.gcd(a, b);\n            if (d != 1) {\n                a = Integer.tdiv(a, d);\n                b = Integer.tdiv(b, d);\n            }\n            \n            /* the fractions are normalized with den > 0 */\n            if (b < 0) {\n                a = -a;\n                b = -b;\n            }\n        }\n        obj = Object.create(Fraction.prototype);\n        obj.num = a;\n        obj.den = b;\n        return obj;\n    }\n\n    function fraction_add(a, b) {\n        a = Fraction(a);\n        b = Fraction(b);\n        return Fraction.toFraction(a.num * b.den + a.den * b.num, a.den * b.den);\n    }\n    function fraction_sub(a, b) {\n        a = Fraction(a);\n        b = Fraction(b);\n        return Fraction.toFraction(a.num * b.den - a.den * b.num, a.den * b.den);\n    }\n    function fraction_mul(a, b) {\n        a = Fraction(a);\n        b = Fraction(b);\n        return Fraction.toFraction(a.num * b.num, a.den * b.den);\n    }\n    function fraction_div(a, b) {\n        a = Fraction(a);\n        b = Fraction(b);\n        return Fraction.toFraction(a.num * b.den, a.den * b.num);\n    }\n    function fraction_mod(a, b) {\n        var a1 = Fraction(a);\n        var b1 = Fraction(b);\n        return a - Integer.ediv(a1.num * b1.den, a1.den * b1.num) * b;\n    }\n    function fraction_eq(a, b) {\n        a = Fraction(a);\n        b = Fraction(b);\n        /* we assume the fractions are normalized */\n        return (a.num == b.num && a.den == b.den);\n    }\n    function fraction_lt(a, b) {\n        a = Fraction(a);\n        b = Fraction(b);\n        return (a.num * b.den < b.num * a.den);\n    }\n\n    /* operators are needed for fractions */\n    function float_add(a, b) {\n        return Float(a) + Float(b);\n    }\n    function float_sub(a, b) {\n        return Float(a) - Float(b);\n    }\n    function float_mul(a, b) {\n        return Float(a) * Float(b);\n    }\n    function float_div(a, b) {\n        return Float(a) / Float(b);\n    }\n    function float_mod(a, b) {\n        return Float(a) % Float(b);\n    }\n    function float_pow(a, b) {\n        return Float(a) ** Float(b);\n    }\n    function float_eq(a, b) {\n        /* XXX: may be better to use infinite precision for the comparison */\n        return Float(a) === Float(b);\n    }\n    function float_lt(a, b) {\n        a = Float(a);\n        b = Float(b);\n        /* XXX: may be better to use infinite precision for the comparison */\n        if (Float.isNaN(a) || Float.isNaN(b))\n            return undefined;\n        else\n            return a < b;\n    }\n    \n    operators_set(Fraction.prototype,\n        {\n            \"+\": fraction_add,\n            \"-\": fraction_sub,\n            \"*\": fraction_mul,\n            \"/\": fraction_div,\n            \"%\": fraction_mod,\n            \"**\": generic_pow,\n            \"==\": fraction_eq,\n            \"<\": fraction_lt,\n            \"pos\"(a) {\n                return a;\n            },\n            \"neg\"(a) {\n                return Fraction(-a.num, a.den);\n            },\n        },\n        {\n            left: [Number, BigInt],\n            right: [Number, BigInt],\n            \"+\": fraction_add,\n            \"-\": fraction_sub,\n            \"*\": fraction_mul,\n            \"/\": fraction_div,\n            \"%\": fraction_mod,\n            \"**\": generic_pow,\n            \"==\": fraction_eq,\n            \"<\": fraction_lt,\n        },\n        {\n            left: Float,\n            right: Float,\n            \"+\": float_add,\n            \"-\": float_sub,\n            \"*\": float_mul,\n            \"/\": float_div,\n            \"%\": float_mod,\n            \"**\": float_pow,\n            \"==\": float_eq,\n            \"<\": float_lt,\n        });\n    \n    add_props(Fraction, {\n        /* (internal use) simplify 'a' to an integer when possible */\n        toFraction(a, b) {\n            var r = Fraction(a, b);\n            if (algebraicMode && r.den == 1)\n                return r.num;\n            else\n                return r;\n        },\n    });\n\n    add_props(Fraction.prototype, {\n        [Symbol.toPrimitive](hint) {\n            if (hint === \"string\") {\n                return this.toString();\n            } else {\n                return Float(this.num) / this.den;\n            }\n        },\n        inverse() {\n            return Fraction(this.den, this.num);\n        },\n        toString() {\n            return this.num + \"/\" + this.den;\n        },\n        norm2() {\n            return this * this;\n        },\n        abs() {\n            if (this.num < 0)\n                return -this;\n            else\n                return this;\n        },\n        conj() {\n            return this;\n        },\n        arg() {\n            if (this.num >= 0)\n                return 0;\n            else\n                return Float.PI;\n        },\n        exp() {\n            return Float.exp(Float(this));\n        },\n        log() {\n            return Float(this).log();\n        },\n    });\n\n    /* Number (Float64) */\n\n    add_props(Number.prototype, {\n        inverse() {\n            return 1 / this;\n        },\n        norm2() {\n            return this * this;\n        },\n        abs() {\n            return Math.abs(this);\n        },\n        conj() {\n            return this;\n        },\n        arg() {\n            if (this >= 0)\n                return 0;\n            else\n                return Float.PI;\n        },\n        exp() {\n            return Float.exp(this);\n        },\n        log() {\n            if (this < 0) {\n                return Complex(this).log();\n            } else {\n                return Float.log(this);\n            }\n        },\n    });\n    \n    /* Float */\n\n    var const_tab = [];\n    \n    /* we cache the constants for small precisions */\n    function get_const(n) {\n        var t, c, p;\n        t = const_tab[n];\n        p = BigFloatEnv.prec;\n        if (t && t.prec == p) {\n            return t.val;\n        } else {\n            switch(n) {\n            case 0: c = Float.exp(1); break;\n            case 1: c = Float.log(10); break;\n//            case 2: c = Float.log(2); break;\n            case 3: c = 1/Float.log(2); break;\n            case 4: c = 1/Float.log(10); break;\n//            case 5: c = Float.atan(1) * 4; break;\n            case 6: c = Float.sqrt(0.5); break;\n            case 7: c = Float.sqrt(2); break;\n            }\n            if (p <= 1024) {\n                const_tab[n] = { prec: p, val: c };\n            }\n            return c;\n        }\n    }\n    \n    add_props(Float, {\n        isFloat(a) {\n            return typeof a === \"number\" || typeof a === \"bigfloat\";\n        },\n        bestappr(u, b) {\n            var num1, num0, den1, den0, u, num, den, n;\n\n            if (typeof b === \"undefined\")\n                throw TypeError(\"second argument expected\");\n            num1 = 1;\n            num0 = 0;\n            den1 = 0;\n            den0 = 1;\n            for(;;) {\n                n = Integer(Float.floor(u));\n                num = n * num1 + num0;\n                den = n * den1 + den0;\n                if (den > b)\n                    break;\n                u = 1.0 / (u - n);\n                num0 = num1;\n                num1 = num;\n                den0 = den1;\n                den1 = den;\n            }\n            return Fraction(num1, den1);\n        },\n        /* similar constants as Math.x */\n        get E() { return get_const(0); },\n        get LN10() { return get_const(1); },\n//        get LN2() { return get_const(2); },\n        get LOG2E() { return get_const(3); },\n        get LOG10E() { return get_const(4); },\n//        get PI() { return get_const(5); },\n        get SQRT1_2() { return get_const(6); },\n        get SQRT2() { return get_const(7); },\n    });\n\n    add_props(Float.prototype, {\n        inverse() {\n            return 1.0 / this;\n        },\n        norm2() {\n            return this * this;\n        },\n        abs() {\n            return Float.abs(this);\n        },\n        conj() {\n            return this;\n        },\n        arg() {\n            if (this >= 0)\n                return 0;\n            else\n                return Float.PI;\n        },\n        exp() {\n            return Float.exp(this);\n        },\n        log() {\n            if (this < 0) {\n                return Complex(this).log();\n            } else {\n                return Float.log(this);\n            }\n        },\n    });\n       \n    /* Complex */\n    \n    Complex = function Complex(re, im)\n    {\n        var obj;\n        if (new.target)\n            throw TypeError(\"not a constructor\");\n        if (re instanceof Complex)\n            return re;\n        if (typeof im === \"undefined\") {\n            im = 0;\n        }\n        obj = Object.create(Complex.prototype);\n        obj.re = re;\n        obj.im = im;\n        return obj;\n    }\n\n        \n    function complex_add(a, b) {\n        a = Complex(a);\n        b = Complex(b);\n        return Complex.toComplex(a.re + b.re, a.im + b.im);\n    }\n    function complex_sub(a, b) {\n        a = Complex(a);\n        b = Complex(b);\n        return Complex.toComplex(a.re - b.re, a.im - b.im);\n    }\n    function complex_mul(a, b) {\n        a = Complex(a);\n        b = Complex(b);\n        return Complex.toComplex(a.re * b.re - a.im * b.im,\n                                 a.re * b.im + a.im * b.re);\n    }\n    function complex_div(a, b) {\n        a = Complex(a);\n        b = Complex(b);\n        return a * b.inverse();\n    }\n    function complex_eq(a, b) {\n        a = Complex(a);\n        b = Complex(b);\n        return a.re == b.re && a.im == b.im;\n    }\n    \n    operators_set(Complex.prototype,\n        {\n            \"+\": complex_add,\n            \"-\": complex_sub,\n            \"*\": complex_mul,\n            \"/\": complex_div,\n            \"**\": generic_pow,\n            \"==\": complex_eq,\n            \"pos\"(a) {\n                return a;\n            },\n            \"neg\"(a) {\n                return Complex(-a.re, -a.im);\n            }\n        },\n        {\n            left: [Number, BigInt, Float, Fraction],\n            right: [Number, BigInt, Float, Fraction],\n            \"+\": complex_add,\n            \"-\": complex_sub,\n            \"*\": complex_mul,\n            \"/\": complex_div,\n            \"**\": generic_pow,\n            \"==\": complex_eq,\n        });\n    \n    add_props(Complex, {\n        /* simplify to real number when possible */\n        toComplex(re, im) {\n            if (algebraicMode && im == 0)\n                return re;\n            else\n                return Complex(re, im);\n        },\n    });\n\n    add_props(Complex.prototype, {\n        inverse() {\n            var c = this.norm2();\n            return Complex(this.re / c, -this.im / c);\n        },\n        toString() {\n            var v, s = \"\", a = this;\n            if (a.re != 0)\n                s += a.re.toString();\n            if (a.im == 1) {\n                if (s != \"\")\n                    s += \"+\";\n                s += \"I\";\n            } else if (a.im == -1) {\n                s += \"-I\";\n            } else {\n                v = a.im.toString();\n                if (v[0] != \"-\" && s != \"\")\n                    s += \"+\";\n                s += v + \"*I\";\n            }\n            return s;\n        },\n        norm2() {\n            return this.re * this.re + this.im * this.im;\n        },\n        abs() {\n            return Float.sqrt(norm2(this));\n        },\n        conj() {\n            return Complex(this.re, -this.im);\n        },\n        arg() {\n            return Float.atan2(this.im, this.re);\n        },\n        exp() {\n            var arg = this.im, r = this.re.exp();\n            return Complex(r * cos(arg), r * sin(arg));\n        },\n        log() {\n            return Complex(abs(this).log(), atan2(this.im, this.re));\n        },\n    });\n\n    /* Mod */\n\n    Mod = function Mod(a, m) {\n        var obj, t;\n        if (new.target)\n            throw TypeError(\"not a constructor\");\n        obj = Object.create(Mod.prototype);\n        if (Integer.isInteger(m)) {\n            if (m <= 0)\n                throw RangeError(\"the modulo cannot be <= 0\");\n            if (Integer.isInteger(a)) {\n                a %= m;\n            } else if (a instanceof Fraction) {\n                return Mod(a.num, m) / a.den;\n            } else {\n                throw TypeError(\"invalid types\");\n            }\n        } else {\n            throw TypeError(\"invalid types\");\n        }\n        obj.res = a;\n        obj.mod = m;\n        return obj;\n    };\n    \n    function mod_add(a, b) {\n        if (!(a instanceof Mod)) {\n            return Mod(a + b.res, b.mod);\n        } else if (!(b instanceof Mod)) {\n            return Mod(a.res + b, a.mod);\n        } else {\n            if (a.mod != b.mod)\n                throw TypeError(\"different modulo for binary operator\");\n            return Mod(a.res + b.res, a.mod);\n        }\n    }\n    function mod_sub(a, b) {\n        if (!(a instanceof Mod)) {\n            return Mod(a - b.res, b.mod);\n        } else if (!(b instanceof Mod)) {\n            return Mod(a.res - b, a.mod);\n        } else {\n            if (a.mod != b.mod)\n                throw TypeError(\"different modulo for binary operator\");\n            return Mod(a.res - b.res, a.mod);\n        }\n    }\n    function mod_mul(a, b) {\n        if (!(a instanceof Mod)) {\n            return Mod(a * b.res, b.mod);\n        } else if (!(b instanceof Mod)) {\n            return Mod(a.res * b, a.mod);\n        } else {\n            if (a.mod != b.mod)\n                throw TypeError(\"different modulo for binary operator\");\n            return Mod(a.res * b.res, a.mod);\n        }\n    }\n    function mod_div(a, b) {\n        if (!(b instanceof Mod))\n            b = Mod(b, a.mod);\n        return mod_mul(a, b.inverse());\n    }\n    function mod_eq(a, b) {\n        return (a.mod == b.mod && a.res == b.res);\n    }\n\n    operators_set(Mod.prototype,\n        {\n            \"+\": mod_add,\n            \"-\": mod_sub,\n            \"*\": mod_mul,\n            \"/\": mod_div,\n            \"**\": generic_pow,\n            \"==\": mod_eq,\n            \"pos\"(a) {\n                return a;\n            },\n            \"neg\"(a) {\n                return Mod(-a.res, a.mod);\n            }\n        },\n        {\n            left: [Number, BigInt, Float, Fraction],\n            right: [Number, BigInt, Float, Fraction],\n            \"+\": mod_add,\n            \"-\": mod_sub,\n            \"*\": mod_mul,\n            \"/\": mod_div,\n            \"**\": generic_pow,\n        });\n\n    add_props(Mod.prototype, {\n        inverse() {\n            var a = this, m = a.mod;\n            if (Integer.isInteger(m)) {\n                return Mod(Integer.invmod(a.res, m), m);\n            } else {\n                throw TypeError(\"unsupported type\");\n            }\n        },\n        toString() {\n            return \"Mod(\" + this.res + \",\" + this.mod + \")\";\n        },\n    });\n\n    /* Polynomial */\n\n    function polynomial_is_scalar(a)\n    {\n        if (typeof a === \"number\" ||\n            typeof a === \"bigint\" ||\n            typeof a === \"bigfloat\")\n            return true;\n        if (a instanceof Fraction ||\n            a instanceof Complex ||\n            a instanceof Mod)\n            return true;\n        return false;\n    }\n    \n    Polynomial = function Polynomial(a)\n    {\n        if (new.target)\n            throw TypeError(\"not a constructor\");\n        if (a instanceof Polynomial) {\n            return a;\n        } else if (Array.isArray(a)) {\n            if (a.length == 0)\n                a = [ 0 ];\n            Object.setPrototypeOf(a, Polynomial.prototype);\n            return a.trim();\n        } else if (polynomial_is_scalar(a)) {\n            a = [a];\n            Object.setPrototypeOf(a, Polynomial.prototype);\n            return a;\n        } else {\n            throw TypeError(\"invalid type\");\n        }\n    }\n\n    function number_need_paren(c)\n    {\n        return !(Integer.isInteger(c) ||\n                 Float.isFloat(c) ||\n                 c instanceof Fraction ||\n                 (c instanceof Complex && c.re == 0));\n    }\n\n    /* string for c*X^i */\n    function monomial_toString(c, i)\n    {\n        var str1;\n        if (i == 0) {\n            str1 = c.toString();\n        } else {\n            if (c == 1) {\n                str1 = \"\";\n            } else if (c == -1) {\n                str1 = \"-\";\n            } else {\n                if (number_need_paren(c)) {\n                    str1 = \"(\" + c + \")\";\n                } else {\n                    str1 = String(c);\n                }\n                str1 += \"*\";\n            }\n            str1 += \"X\";\n            if (i != 1) {\n                str1 += \"^\" + i;\n            }\n        }\n        return str1;\n    }\n\n    /* find one complex root of 'p' starting from z at precision eps using\n       at most max_it iterations. Return null if could not find root. */\n    function poly_root_laguerre1(p, z, max_it)\n    {\n        var p1, p2, i, z0, z1, z2, d, t0, t1, d1, d2, e, el, zl;\n\n        d = p.deg();\n        if (d == 1) {\n            /* monomial case */\n            return -p[0] / p[1];\n        }\n        /* trivial zero */\n        if (p[0] == 0)\n            return 0.0;\n        \n        p1 = p.deriv();\n        p2 = p1.deriv();\n        el = 0.0;\n        zl = 0.0;\n        for(i = 0; i < max_it; i++) {\n            z0 = p.apply(z);\n            if (z0 == 0)\n                return z; /* simple exit case */\n\n            /* Ward stopping criteria */\n            e = abs(z - zl);\n//            print(\"e\", i, e);\n            if (i >= 2 && e >= el) {\n                if (abs(zl) < 1e-4) {\n                    if (e < 1e-7)\n                        return zl;\n                } else {\n                    if (e < abs(zl) * 1e-3)\n                        return zl;\n                }\n            }\n            el = e;\n            zl = z;\n            \n            z1 = p1.apply(z);\n            z2 = p2.apply(z);\n            t0 = (d - 1) * z1;\n            t0 = t0 * t0;\n            t1 = d * (d - 1) * z0 * z2;\n            t0 = sqrt(t0 - t1);\n            d1 = z1 + t0;\n            d2 = z1 - t0;\n            if (norm2(d2) > norm2(d1))\n                d1 = d2;\n            if (d1 == 0) \n                return null;\n            z = z - d * z0 / d1;\n        }\n        return null;\n    }\n\n    function poly_roots(p)\n    {\n        var d, i, roots, j, z, eps;\n        var start_points = [ 0.1, -1.4, 1.7 ];\n\n        if (!(p instanceof Polynomial))\n            throw TypeError(\"polynomial expected\");\n        d = p.deg();\n        if (d <= 0)\n            return [];\n        eps = 2.0 ^ (-BigFloatEnv.prec);\n        roots = [];\n        for(i = 0; i < d; i++) {\n            /* XXX: should select another start point if error */\n            for(j = 0; j < 3; j++) {\n                z = poly_root_laguerre1(p, start_points[j], 100);\n                if (z !== null)\n                    break;\n            }\n            if (j == 3)\n                throw RangeError(\"error in root finding algorithm\");\n            roots[i] = z;\n            p = Polynomial.divrem(p, X - z)[0];\n        }\n        return roots;\n    }\n\n    add_props(Polynomial.prototype, {\n        trim() {\n            var a = this, i;\n            i = a.length;\n            while (i > 1 && a[i - 1] == 0)\n                i--;\n            a.length = i;\n            return a;\n        },\n        conj() {\n            var r, i, n, a;\n            a = this;\n            n = a.length;\n            r = [];\n            for(i = 0; i < n; i++)\n                r[i] = a[i].conj();\n            return Polynomial(r);\n        },\n        inverse() {\n            return RationalFunction(Polynomial([1]), this);\n        },\n        toString() {\n            var i, str, str1, c, a = this;\n            if (a.length == 1) {\n                return a[0].toString();\n            }\n            str=\"\";\n            for(i = a.length - 1; i >= 0; i--) {\n                c = a[i];\n                if (c == 0 ||\n                    (c instanceof Mod) && c.res == 0)\n                    continue;\n                str1 = monomial_toString(c, i);\n                if (str1[0] != \"-\") {\n                    if (str != \"\")\n                        str += \"+\";\n                }\n                str += str1;\n            }\n            return str;\n        },\n        deg() {\n            if (this.length == 1 && this[0] == 0)\n                return -Infinity;\n            else\n                return this.length - 1;\n        },\n        apply(b) {\n            var i, n, r, a = this;\n            n = a.length - 1;\n            r = a[n];\n            while (n > 0) {\n                n--;\n                r = r * b + a[n];\n            }\n            return r;\n        },\n        deriv() {\n            var a = this, n, r, i;\n            n = a.length;\n            if (n == 1) {\n                return Polynomial(0);\n            } else {\n                r = [];\n                for(i = 1; i < n; i++) {\n                    r[i - 1] = i * a[i];\n                }\n                return Polynomial(r);\n            }\n        },\n        integ() {\n            var a = this, n, r, i;\n            n = a.length;\n            r = [0];\n            for(i = 0; i < n; i++) {\n                r[i + 1] = a[i] / (i + 1);\n            }\n            return Polynomial(r);\n        },\n        norm2() {\n            var a = this, n, r, i;\n            n = a.length;\n            r = 0;\n            for(i = 0; i < n; i++) {\n                r += a[i].norm2();\n            }\n            return r;\n        },\n    });\n\n\n    function polynomial_add(a, b) {\n        var tmp, r, i, n1, n2;\n        a = Polynomial(a);\n        b = Polynomial(b);\n        if (a.length < b.length) {\n            tmp = a;\n            a = b;\n            b = tmp;\n        }\n        n1 = b.length;\n        n2 = a.length;\n        r = [];\n        for(i = 0; i < n1; i++)\n            r[i] = a[i] + b[i];\n        for(i = n1; i < n2; i++)\n            r[i] = a[i];\n        return Polynomial(r);\n    }\n    function polynomial_sub(a, b) {\n        return polynomial_add(a, -b);\n    }\n    function polynomial_mul(a, b) {\n        var i, j, n1, n2, n, r;\n        a = Polynomial(a);\n        b = Polynomial(b);\n        n1 = a.length;\n        n2 = b.length;\n        n = n1 + n2 - 1;\n        r = [];\n        for(i = 0; i < n; i++)\n            r[i] = 0;\n        for(i = 0; i < n1; i++) {\n            for(j = 0; j < n2; j++) {\n                r[i + j] += a[i] * b[j];\n            }\n        }\n        return Polynomial(r);\n    }\n    function polynomial_div_scalar(a, b) {\n        return a * (1 / b);\n    }\n    function polynomial_div(a, b)\n    {\n        return RationalFunction(Polynomial(a),\n                                Polynomial(b));\n    }\n    function polynomial_mod(a, b) {\n        return Polynomial.divrem(a, b)[1];\n    }\n    function polynomial_eq(a, b) {\n        var n, i;\n        n = a.length;\n        if (n != b.length)\n            return false;\n        for(i = 0; i < n; i++) {\n            if (a[i] != b[i])\n                return false;\n        }\n        return true;\n    }\n\n    operators_set(Polynomial.prototype,\n        {\n            \"+\": polynomial_add,\n            \"-\": polynomial_sub,\n            \"*\": polynomial_mul,\n            \"/\": polynomial_div,\n            \"**\": generic_pow,\n            \"==\": polynomial_eq,\n            \"pos\"(a) {\n                return a;\n            },\n            \"neg\"(a) {\n                var r, i, n, a;\n                n = a.length;\n                r = [];\n                for(i = 0; i < n; i++)\n                r[i] = -a[i];\n                return Polynomial(r);\n            },\n        },\n        {\n            left: [Number, BigInt, Float, Fraction, Complex, Mod],\n            \"+\": polynomial_add,\n            \"-\": polynomial_sub,\n            \"*\": polynomial_mul,\n            \"/\": polynomial_div,\n            \"**\": generic_pow, /* XXX: only for integer */\n        },\n        {\n            right: [Number, BigInt, Float, Fraction, Complex, Mod],\n            \"+\": polynomial_add,\n            \"-\": polynomial_sub,\n            \"*\": polynomial_mul,\n            \"/\": polynomial_div_scalar,\n            \"**\": generic_pow, /* XXX: only for integer */\n        });\n    \n    add_props(Polynomial, {\n        divrem(a, b) {\n            var n1, n2, i, j, q, r, n, c;\n            if (b.deg() < 0)\n                throw RangeError(\"division by zero\");\n            n1 = a.length;\n            n2 = b.length;\n            if (n1 < n2)\n                return [Polynomial([0]), a];\n            r = Array.prototype.dup.call(a);\n            q = [];\n            n2--;\n            n = n1 - n2;\n            for(i = 0; i < n; i++)\n                q[i] = 0;\n            for(i = n - 1; i >= 0; i--) {\n                c = r[i + n2];\n                if (c != 0) {\n                    c = c / b[n2];\n                    r[i + n2] = 0;\n                    for(j = 0; j < n2; j++) {\n                        r[i + j] -= b[j] * c;\n                    }\n                    q[i] = c;\n                }\n            }\n            return [Polynomial(q), Polynomial(r)];\n        },\n        gcd(a, b) {\n            var t;\n            while (b.deg() >= 0) {\n                t = Polynomial.divrem(a, b);\n                a = b;\n                b = t[1];\n            }\n            /* convert to monic form */\n            return a / a[a.length - 1];\n        },\n        invmod(x, y) {\n            var q, u, v, a, c, t;\n            u = x;\n            v = y;\n            c = Polynomial([1]);\n            a = Polynomial([0]);\n            while (u.deg() >= 0) {\n                t = Polynomial.divrem(v, u);\n                q = t[0];\n                v = u;\n                u = t[1];\n                t = c;\n                c = a - q * c;\n                a = t;\n            }\n            /* v = gcd(x, y) */\n            if (v.deg() > 0)\n                throw RangeError(\"not invertible\");\n            return Polynomial.divrem(a, y)[1];\n        },\n        roots(p) {\n            return poly_roots(p);\n        }\n    });\n\n    /* Polynomial Modulo Q */\n\n    PolyMod = function PolyMod(a, m) {\n        var obj, t;\n        if (new.target)\n            throw TypeError(\"not a constructor\");\n        obj = Object.create(PolyMod.prototype);\n        if (m instanceof Polynomial) {\n            if (m.deg() <= 0)\n                throw RangeError(\"the modulo cannot have a degree <= 0\");\n            if (a instanceof RationalFunction) {\n                return PolyMod(a.num, m) / a.den;\n            } else {\n                a = Polynomial(a);\n                t = Polynomial.divrem(a, m);\n                a = t[1];\n            }\n        } else {\n            throw TypeError(\"invalid types\");\n        }\n        obj.res = a;\n        obj.mod = m;\n        return obj;\n    };\n\n    function polymod_add(a, b) {\n        if (!(a instanceof PolyMod)) {\n            return PolyMod(a + b.res, b.mod);\n        } else if (!(b instanceof PolyMod)) {\n            return PolyMod(a.res + b, a.mod);\n        } else {\n            if (a.mod != b.mod)\n                throw TypeError(\"different modulo for binary operator\");\n            return PolyMod(a.res + b.res, a.mod);\n        }\n    }\n    function polymod_sub(a, b) {\n        return polymod_add(a, -b);\n    }\n    function polymod_mul(a, b) {\n        if (!(a instanceof PolyMod)) {\n            return PolyMod(a * b.res, b.mod);\n        } else if (!(b instanceof PolyMod)) {\n            return PolyMod(a.res * b, a.mod);\n        } else {\n            if (a.mod != b.mod)\n                    throw TypeError(\"different modulo for binary operator\");\n            return PolyMod(a.res * b.res, a.mod);\n        }\n    }\n    function polymod_div(a, b) {\n        if (!(b instanceof PolyMod))\n            b = PolyMod(b, a.mod);\n        return polymod_mul(a, b.inverse());\n    }\n    function polymod_eq(a, b) {\n        return (a.mod == b.mod && a.res == b.res);\n    }\n\n    operators_set(PolyMod.prototype,\n        {\n            \"+\": polymod_add,\n            \"-\": polymod_sub,\n            \"*\": polymod_mul,\n            \"/\": polymod_div,\n            \"**\": generic_pow,\n            \"==\": polymod_eq,\n            \"pos\"(a) {\n                return a;\n            },\n            \"neg\"(a) {\n                return PolyMod(-a.res, a.mod);\n            },\n        },\n        {\n            left: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial],\n            right: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial],\n            \"+\": polymod_add,\n            \"-\": polymod_sub,\n            \"*\": polymod_mul,\n            \"/\": polymod_div,\n            \"**\": generic_pow, /* XXX: only for integer */\n        });\n\n    add_props(PolyMod.prototype, {\n        inverse() {\n            var a = this, m = a.mod;\n            if (m instanceof Polynomial) {\n                return PolyMod(Polynomial.invmod(a.res, m), m);\n            } else {\n                throw TypeError(\"unsupported type\");\n            }\n        },\n        toString() {\n            return \"PolyMod(\" + this.res + \",\" + this.mod + \")\";\n        },\n    });\n\n    /* Rational function */\n    \n    RationalFunction = function RationalFunction(a, b)\n    {\n        var t, r, d, obj;\n        if (new.target)\n            throw TypeError(\"not a constructor\");\n        if (!(a instanceof Polynomial) ||\n            !(b instanceof Polynomial))\n            throw TypeError(\"polynomial expected\");\n        t = Polynomial.divrem(a, b);\n        r = t[1];\n        if (r.deg() < 0)\n            return t[0]; /* no need for a fraction */\n        d = Polynomial.gcd(b, r);\n        if (d.deg() > 0) {\n            a = Polynomial.divrem(a, d)[0];\n            b = Polynomial.divrem(b, d)[0];\n        }\n        obj = Object.create(RationalFunction.prototype);\n        obj.num = a;\n        obj.den = b;\n        return obj;\n    }\n\n    add_props(RationalFunction.prototype, {\n        inverse() {\n            return RationalFunction(this.den, this.num);\n        },\n        conj() {\n            return RationalFunction(this.num.conj(), this.den.conj());\n        },\n        toString() {\n            var str;\n            if (this.num.deg() <= 0 &&\n                !number_need_paren(this.num[0]))\n                str = this.num.toString();\n            else\n                str = \"(\" + this.num.toString() + \")\";\n            str += \"/(\" + this.den.toString() + \")\"\n            return str;\n        },\n        apply(b) {\n            return this.num.apply(b) / this.den.apply(b);\n        },\n        deriv() {\n            var n = this.num, d = this.den;\n            return RationalFunction(n.deriv() * d - n * d.deriv(), d * d);\n        },\n    });\n\n    function ratfunc_add(a, b) {\n        a = RationalFunction.toRationalFunction(a);\n        b = RationalFunction.toRationalFunction(b);\n        return RationalFunction(a.num * b.den + a.den * b.num, a.den * b.den);\n    }\n    function ratfunc_sub(a, b) {\n        a = RationalFunction.toRationalFunction(a);\n        b = RationalFunction.toRationalFunction(b);\n        return RationalFunction(a.num * b.den - a.den * b.num, a.den * b.den);\n    }\n    function ratfunc_mul(a, b) {\n        a = RationalFunction.toRationalFunction(a);\n        b = RationalFunction.toRationalFunction(b);\n        return RationalFunction(a.num * b.num, a.den * b.den);\n    }\n    function ratfunc_div(a, b) {\n        a = RationalFunction.toRationalFunction(a);\n        b = RationalFunction.toRationalFunction(b);\n        return RationalFunction(a.num * b.den, a.den * b.num);\n    }\n    function ratfunc_eq(a, b) {\n        a = RationalFunction.toRationalFunction(a);\n        b = RationalFunction.toRationalFunction(b);\n        /* we assume the fractions are normalized */\n        return (a.num == b.num && a.den == b.den);\n    }\n\n    operators_set(RationalFunction.prototype,\n        {\n            \"+\": ratfunc_add,\n            \"-\": ratfunc_sub,\n            \"*\": ratfunc_mul,\n            \"/\": ratfunc_div,\n            \"**\": generic_pow,\n            \"==\": ratfunc_eq,\n            \"pos\"(a) {\n                return a;\n            },\n            \"neg\"(a) {\n                return RationalFunction(-this.num, this.den);\n            },\n        },\n        {\n            left: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial],\n            right: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial],\n            \"+\": ratfunc_add,\n            \"-\": ratfunc_sub,\n            \"*\": ratfunc_mul,\n            \"/\": ratfunc_div,\n            \"**\": generic_pow, /* should only be used with integers */\n        });\n    \n    add_props(RationalFunction, {\n        /* This function always return a RationalFunction object even\n           if it could simplified to a polynomial, so it is not\n           equivalent to RationalFunction(a) */\n        toRationalFunction(a) {\n            var obj;\n            if (a instanceof RationalFunction) {\n                return a;\n            } else {\n                obj = Object.create(RationalFunction.prototype);\n                obj.num = Polynomial(a);\n                obj.den = Polynomial(1);\n                return obj;\n            }\n        },\n    });\n              \n    /* Power series */\n\n    /* 'a' is an array */\n    function get_emin(a) {\n        var i, n;\n        n = a.length;\n        for(i = 0; i < n; i++) {\n            if (a[i] != 0)\n                return i;\n        }\n        return n;\n    };\n\n    function series_is_scalar_or_polynomial(a)\n    {\n        return polynomial_is_scalar(a) ||\n            (a instanceof Polynomial);\n    }\n    \n    /* n is the maximum number of terms if 'a' is not a serie */\n    Series = function Series(a, n) {\n        var emin, r, i;\n        \n        if (a instanceof Series) {\n            return a;\n        } else if (series_is_scalar_or_polynomial(a)) {\n            if (n <= 0) {\n                /* XXX: should still use the polynomial degree */\n                return Series.zero(0, 0);\n            } else {\n                a = Polynomial(a);\n                emin = get_emin(a);\n                r = Series.zero(n, emin);\n                n = Math.min(a.length - emin, n);\n                for(i = 0; i < n; i++)\n                    r[i] = a[i + emin];\n                return r;\n            }\n        } else if (a instanceof RationalFunction) {\n            return Series(a.num, n) / a.den;\n        } else {\n            throw TypeError(\"invalid type\");\n        }\n    };\n\n    function series_add(v1, v2) {\n        var tmp, d, emin, n, r, i, j, v2_emin, c1, c2;\n        if (!(v1 instanceof Series)) {\n            tmp = v1;\n            v1 = v2;\n            v2 = tmp;\n        }\n        d = v1.emin + v1.length;\n        if (series_is_scalar_or_polynomial(v2)) {\n            v2 = Polynomial(v2);\n            if (d <= 0)\n                return v1;\n            v2_emin = 0;\n        } else if (v2 instanceof RationalFunction) {\n            /* compute the emin of the rational fonction */\n            i = get_emin(v2.num) - get_emin(v2.den);\n            if (d <= i)\n                return v1;\n            /* compute the serie with the required terms */\n            v2 = Series(v2, d - i);\n            v2_emin = v2.emin;\n        } else {\n            v2_emin = v2.emin;\n            d = Math.min(d, v2_emin + v2.length);\n        }\n        emin = Math.min(v1.emin, v2_emin);\n        n = d - emin;\n        r = Series.zero(n, emin);\n        /* XXX: slow */\n        for(i = emin; i < d; i++) {\n            j = i - v1.emin;\n            if (j >= 0 && j < v1.length)\n                c1 = v1[j];\n            else\n                c1 = 0;\n            j = i - v2_emin;\n            if (j >= 0 && j < v2.length)\n                c2 = v2[j];\n            else\n                c2 = 0;\n            r[i - emin] = c1 + c2;\n        }\n        return r.trim();\n    }\n    function series_sub(a, b) {\n        return series_add(a, -b);\n    }\n    function series_mul(v1, v2) {\n        var n, i, j, r, n, emin, n1, n2, k;\n        if (!(v1 instanceof Series))\n            v1 = Series(v1, v2.length);\n        else if (!(v2 instanceof Series))\n            v2 = Series(v2, v1.length);\n        emin = v1.emin + v2.emin;\n        n = Math.min(v1.length, v2.length);\n        n1 = v1.length;\n        n2 = v2.length;\n        r = Series.zero(n, emin);\n        for(i = 0; i < n1; i++) {\n            k = Math.min(n2, n - i);\n            for(j = 0; j < k; j++) {\n                r[i + j] += v1[i] * v2[j];\n            }\n        }\n        return r.trim();\n    }\n    function series_div(v1, v2) {\n        if (!(v2 instanceof Series))\n            v2 = Series(v2, v1.length);\n        return series_mul(v1, v2.inverse());\n    }\n    function series_pow(a, b) {\n        if (Integer.isInteger(b)) {\n            return generic_pow(a, b);\n        } else {\n            if (!(a instanceof Series))\n                a = Series(a, b.length);\n            return exp(log(a) * b);\n        }\n    }\n    function series_eq(a, b) {\n        var n, i;\n        if (a.emin != b.emin)\n            return false;\n        n = a.length;\n        if (n != b.length)\n            return false;\n        for(i = 0; i < n; i++) {\n            if (a[i] != b[i])\n                return false;\n        }\n        return true;\n    }\n\n    operators_set(Series.prototype,\n        {\n            \"+\": series_add,\n            \"-\": series_sub,\n            \"*\": series_mul,\n            \"/\": series_div,\n            \"**\": series_pow,\n            \"==\": series_eq,\n            \"pos\"(a) {\n                return a;\n            },\n            \"neg\"(a) {\n                var obj, n, i;\n                n = a.length;\n                obj = Series.zero(a.length, a.emin);\n                for(i = 0; i < n; i++) {\n                    obj[i] = -a[i];\n                }\n                return obj;\n            },\n        },\n        {\n            left: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial],\n            right: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial],\n            \"+\": series_add,\n            \"-\": series_sub,\n            \"*\": series_mul,\n            \"/\": series_div,\n            \"**\": series_pow,\n        });\n\n    add_props(Series.prototype, {\n        conj() {\n            var obj, n, i;\n            n = this.length;\n            obj = Series.zero(this.length, this.emin);\n            for(i = 0; i < n; i++) {\n                obj[i] = this[i].conj();\n            }\n            return obj;\n        },\n        inverse() {\n            var r, n, i, j, sum, v1 = this;\n            n = v1.length;\n            if (n == 0)\n                throw RangeError(\"division by zero\");\n            r = Series.zero(n, -v1.emin);\n            r[0] = 1 / v1[0];\n            for(i = 1; i < n; i++) {\n                sum = 0;\n                for(j = 1; j <= i; j++) {\n                    sum += v1[j] * r[i - j];\n                }\n                r[i] = -sum * r[0];\n            }\n            return r;\n        },\n        /* remove leading zero terms */\n        trim() {\n            var i, j, n, r, v1 = this;\n            n = v1.length;\n            i = 0;\n            while (i < n && v1[i] == 0)\n                i++;\n            if (i == 0)\n                return v1;\n            for(j = i; j < n; j++)\n                v1[j - i] = v1[j];\n            v1.length = n - i;\n            v1.__proto__.emin += i;\n            return v1;\n        },\n        toString() {\n            var i, j, str, str1, c, a = this, emin, n;\n            str=\"\";\n            emin = this.emin;\n            n = this.length;\n            for(j = 0; j < n; j++) {\n                i = j + emin;\n                c = a[j];\n                if (c != 0) {\n                    str1 = monomial_toString(c, i);\n                    if (str1[0] != \"-\") {\n                        if (str != \"\")\n                            str += \"+\";\n                    }\n                    str += str1;\n                }\n            }\n            if (str != \"\")\n                str += \"+\";\n            str += \"O(\" + monomial_toString(1, n + emin) + \")\";\n            return str;\n        },\n        apply(b) {\n            var i, n, r, a = this;\n            n = a.length;\n            if (n == 0)\n                return 0;\n            r = a[--n];\n            while (n > 0) {\n                n--;\n                r = r * b + a[n];\n            }\n            if (a.emin != 0)\n                r *= b ^ a.emin;\n            return r;\n        },\n        deriv() {\n            var a = this, n = a.length, emin = a.emin, r, i, j;\n            if (n == 0 && emin == 0) {\n                return Series.zero(0, 0);\n            } else {\n                r = Series.zero(n, emin - 1);\n                for(i = 0; i < n; i++) {\n                    j = emin + i;\n                    if (j == 0)\n                        r[i] = 0;\n                    else\n                        r[i] = j * a[i];\n                }\n                return r.trim();\n            }\n        },\n        integ() {\n            var a = this, n = a.length, emin = a.emin, i, j, r;\n            r = Series.zero(n, emin + 1);\n            for(i = 0; i < n; i++) {\n                j = emin + i;\n                if (j == -1) {\n                    if (a[i] != 0)\n                        throw RangeError(\"cannot represent integ(1/X)\");\n                } else {\n                    r[i] = a[i] / (j + 1);\n                }\n            }\n            return r.trim();\n        },\n        exp() {\n            var c, i, r, n, a = this;\n            if (a.emin < 0)\n                throw RangeError(\"negative exponent in exp\");\n            n = a.emin + a.length;\n            if (a.emin > 0 || a[0] == 0) {\n                c = 1;\n            } else {\n                c = global.exp(a[0]);\n                a -= a[0];\n            }\n            r = Series.zero(n, 0);\n            for(i = 0; i < n; i++) {\n                r[i] = c / fact(i);\n            }\n            return r.apply(a);\n        },\n        log() {\n            var a = this, r;\n            if (a.emin != 0)\n                throw RangeError(\"log argument must have a non zero constant term\");\n            r = integ(deriv(a) / a);\n            /* add the constant term */\n            r += global.log(a[0]);\n            return r;\n        },\n    });\n\n    add_props(Series, {\n        /* new series of length n and first exponent emin */\n        zero(n, emin) {\n            var r, i, obj;\n\n            r = [];\n            for(i = 0; i < n; i++)\n                r[i] = 0;\n            /* we return an array and store emin in its prototype */\n            obj = Object.create(Series.prototype);\n            obj.emin = emin;\n            Object.setPrototypeOf(r, obj);\n            return r;\n        },\n        O(a) {\n            function ErrorO() {\n                return TypeError(\"invalid O() argument\");\n            }\n            var n;\n            if (series_is_scalar_or_polynomial(a)) {\n                a = Polynomial(a);\n                n = a.deg();\n                if (n < 0)\n                    throw ErrorO();\n            } else if (a instanceof RationalFunction) {\n                if (a.num.deg() != 0)\n                    throw ErrorO();\n                n = a.den.deg();\n                if (n < 0)\n                    throw ErrorO();\n                n = -n;\n            } else\n                throw ErrorO();\n            return Series.zero(0, n);\n        },\n    });\n    \n    /* Array (Matrix) */\n\n    Matrix = function Matrix(h, w) {\n        var i, j, r, rl;\n        if (typeof w === \"undefined\")\n            w = h;\n        r = [];\n        for(i = 0; i < h; i++) {\n            rl = [];\n            for(j = 0; j < w; j++)\n                rl[j] = 0;\n            r[i] = rl;\n        }\n        return r;\n    };\n\n    add_props(Matrix, {\n        idn(n) {\n            var r, i;\n            r = Matrix(n, n);\n            for(i = 0; i < n; i++)\n                r[i][i] = 1;\n            return r;\n        },\n        diag(a) {\n            var r, i, n;\n            n = a.length;\n            r = Matrix(n, n);\n            for(i = 0; i < n; i++)\n                r[i][i] = a[i];\n            return r;\n        },\n        hilbert(n) {\n            var i, j, r;\n            r = Matrix(n);\n            for(i = 0; i < n; i++) {\n                for(j = 0; j < n; j++) {\n                    r[i][j] = 1 / (1 + i + j);\n                }\n            }\n            return r;\n        },\n        trans(a) {\n            var h, w, r, i, j;\n            if (!Array.isArray(a))\n                throw TypeError(\"matrix expected\");\n            h = a.length;\n            if (!Array.isArray(a[0])) {\n                w = 1;\n                r = Matrix(w, h);\n                for(i = 0; i < h; i++) {\n                    r[0][i] = a[i];\n                }\n            } else {\n                w = a[0].length;\n                r = Matrix(w, h);\n                for(i = 0; i < h; i++) {\n                    for(j = 0; j < w; j++) {\n                        r[j][i] = a[i][j];\n                    }\n                }\n            }\n            return r;\n        },\n        check_square(a) {\n            var a, n;\n            if (!Array.isArray(a))\n                throw TypeError(\"array expected\");\n            n = a.length;\n            if (!Array.isArray(a[0]) || n != a[0].length)\n                throw TypeError(\"square matrix expected\");\n            return n;\n        },\n        trace(a) {\n            var n, r, i;\n            n = Matrix.check_square(a);\n            r = a[0][0];\n            for(i = 1; i < n; i++) {\n                r += a[i][i];\n            }\n            return r;\n        },\n        charpoly(a) {\n            var n, p, c, i, j, coef;\n            n = Matrix.check_square(a);\n            p = [];\n            for(i = 0; i < n + 1; i++)\n                p[i] = 0;\n            p[n] = 1;\n            c = Matrix.idn(n);\n            for(i = 0; i < n; i++) {\n                c = c * a;\n                coef = -trace(c) / (i + 1);\n                p[n - i - 1] = coef;\n                for(j = 0; j < n; j++)\n                    c[j][j] += coef;\n            }\n            return Polynomial(p);\n        },\n        eigenvals(a) {\n            return Polynomial.roots(Matrix.charpoly(a));\n        },\n        det(a) {\n            var n, i, j, k, s, src, v, c;\n            \n            n = Matrix.check_square(a);\n            s = 1;\n            src = a.dup();\n            for(i=0;i<n;i++) {\n                for(j = i; j < n; j++) {\n                    if (src[j][i] != 0)\n                        break;\n                }\n                if (j == n)\n                    return 0;\n                if (j != i) {\n                    for(k = 0;k < n; k++) {\n                        v = src[j][k];\n                        src[j][k] = src[i][k];\n                        src[i][k] = v;\n                    }\n                    s = -s;\n                }\n                c = src[i][i].inverse();\n                for(j = i + 1; j < n; j++) {\n                    v = c * src[j][i];\n                    for(k = 0;k < n; k++) {\n                        src[j][k] -= src[i][k] * v;\n                    }\n                }\n            }\n            c = s;\n            for(i=0;i<n;i++)\n                c *= src[i][i];\n            return c;\n        },\n        inverse(a) {\n            var n, dst, src, i, j, k, n2, r, c, v;\n            n = Matrix.check_square(a);\n            src = a.dup();\n            dst = Matrix.idn(n);\n            for(i=0;i<n;i++) {\n                for(j = i; j < n; j++) {\n                    if (src[j][i] != 0)\n                        break;\n                }\n                if (j == n)\n                    throw RangeError(\"matrix is not invertible\");\n                if (j != i) {\n                    /* swap lines in src and dst */\n                    v = src[j];\n                    src[j] = src[i];\n                    src[i] = v;\n                    v = dst[j];\n                    dst[j] = dst[i];\n                    dst[i] = v;\n                }\n\n                c = src[i][i].inverse();\n                for(k = 0; k < n; k++) {\n                    src[i][k] *= c;\n                    dst[i][k] *= c;\n                }\n                \n                for(j = 0; j < n; j++) {\n                    if (j != i) {\n                        c = src[j][i];\n                        for(k = i; k < n; k++) {\n                            src[j][k] -= src[i][k] * c;\n                        }\n                        for(k = 0; k < n; k++) {\n                            dst[j][k] -= dst[i][k] * c;\n                        }\n                    }\n                }\n            }\n            return dst;\n        },\n        rank(a) {\n            var src, i, j, k, w, h, l, c;\n            \n            if (!Array.isArray(a) ||\n                !Array.isArray(a[0]))\n                throw TypeError(\"matrix expected\");\n            h = a.length;\n            w = a[0].length;\n            src = a.dup();\n            l = 0;\n            for(i=0;i<w;i++) {\n                for(j = l; j < h; j++) {\n                    if (src[j][i] != 0)\n                        break;\n                }\n                if (j == h)\n                    continue;\n                if (j != l) {\n                    /* swap lines */\n                    for(k = 0; k < w; k++) {\n                        v = src[j][k];\n                        src[j][k] = src[l][k];\n                        src[l][k] = v;\n                    }\n                }\n                \n                c = src[l][i].inverse();\n                for(k = 0; k < w; k++) {\n                    src[l][k] *= c;\n                }\n                \n                for(j = l + 1; j < h; j++) {\n                    c = src[j][i];\n                    for(k = i; k < w; k++) {\n                        src[j][k] -= src[l][k] * c;\n                    }\n                }\n                l++;\n            }\n            return l;\n        },\n        ker(a) {\n            var src, i, j, k, w, h, l, m, r, im_cols, ker_dim, c;\n            \n            if (!Array.isArray(a) ||\n                !Array.isArray(a[0]))\n                throw TypeError(\"matrix expected\");\n            h = a.length;\n            w = a[0].length;\n            src = a.dup();\n            im_cols = [];\n            l = 0;\n            for(i=0;i<w;i++) {\n                im_cols[i] = false;\n                for(j = l; j < h; j++) {\n                    if (src[j][i] != 0)\n                        break;\n                }\n                if (j == h)\n                    continue;\n                im_cols[i] = true;\n                if (j != l) {\n                    /* swap lines */\n                    for(k = 0; k < w; k++) {\n                        v = src[j][k];\n                        src[j][k] = src[l][k];\n                        src[l][k] = v;\n                    }\n                }\n                \n                c = src[l][i].inverse();\n                for(k = 0; k < w; k++) {\n                    src[l][k] *= c;\n                }\n                \n                for(j = 0; j < h; j++) {\n                    if (j != l) {\n                        c = src[j][i];\n                        for(k = i; k < w; k++) {\n                            src[j][k] -= src[l][k] * c;\n                        }\n                    }\n                }\n                l++;\n                //        log_str(\"m=\" + cval_toString(v1) + \"\\n\");\n            }\n            //    log_str(\"im cols=\"+im_cols+\"\\n\");\n\n            /* build the kernel vectors */\n            ker_dim = w - l;\n            r = Matrix(w, ker_dim);\n            k = 0;\n            for(i = 0; i < w; i++) {\n                if (!im_cols[i]) {\n                    /* select this column from the matrix */\n                    l = 0;\n                    m = 0;\n                    for(j = 0; j < w; j++) {\n                        if (im_cols[j]) {\n                            r[j][k] = -src[m][i];\n                            m++;\n                        } else {\n                            if (l == k) {\n                                r[j][k] = 1;\n                            } else {\n                                r[j][k] = 0;\n                            }\n                            l++;\n                        }\n                    }\n                    k++;\n                }\n            }\n            return r;\n        },\n        dp(a, b) {\n            var i, n, r;\n            n = a.length;\n            if (n != b.length)\n                throw TypeError(\"incompatible array length\");\n            /* XXX: could do complex product */\n            r = 0;\n            for(i = 0; i < n; i++) {\n                r += a[i] * b[i];\n            }\n            return r;\n        },\n        /* cross product */\n        cp(v1, v2) {\n            var r;\n            if (v1.length != 3 || v2.length != 3)\n                throw TypeError(\"vectors must have 3 elements\");\n            r = [];\n            r[0] = v1[1] * v2[2] - v1[2] * v2[1];\n            r[1] = v1[2] * v2[0] - v1[0] * v2[2];\n            r[2] = v1[0] * v2[1] - v1[1] * v2[0];\n            return r;\n        },\n    });\n\n    function array_add(a, b) {\n        var r, i, n;\n        n = a.length;\n        if (n != b.length)\n            throw TypeError(\"incompatible array size\");\n        r = [];\n        for(i = 0; i < n; i++)\n            r[i] = a[i] + b[i];\n        return r;\n    }\n    function array_sub(a, b) {\n        var r, i, n;\n        n = a.length;\n        if (n != b.length)\n            throw TypeError(\"incompatible array size\");\n        r = [];\n        for(i = 0; i < n; i++)\n            r[i] = a[i] - b[i];\n        return r;\n    }\n    function array_scalar_mul(a, b) {\n        var r, i, n;\n        n = a.length;\n        r = [];\n        for(i = 0; i < n; i++)\n            r[i] = a[i] * b;\n        return r;\n    }\n    function array_mul(a, b) {\n        var h, w, l, i, j, k, r, rl, sum, a_mat, b_mat;\n        h = a.length;\n        a_mat = Array.isArray(a[0]);\n        if (a_mat) {\n            l = a[0].length;\n        } else {\n            l = 1;\n        }\n        if (l != b.length)\n            throw RangeError(\"incompatible matrix size\");\n        b_mat = Array.isArray(b[0]);\n        if (b_mat)\n            w = b[0].length;\n        else\n            w = 1;\n        r = [];\n        if (a_mat && b_mat) {\n            for(i = 0; i < h; i++) {\n                rl = [];\n                for(j = 0; j < w; j++) {\n                    sum = 0;\n                    for(k = 0; k < l; k++) {\n                        sum += a[i][k] * b[k][j];\n                    }\n                    rl[j] = sum;\n                }\n                r[i] = rl;\n            }\n        } else if (a_mat && !b_mat) {\n            for(i = 0; i < h; i++) {\n                sum = 0;\n                for(k = 0; k < l; k++) {\n                    sum += a[i][k] * b[k];\n                }\n                r[i] = sum;\n            }\n        } else if (!a_mat && b_mat) {\n            for(i = 0; i < h; i++) {\n                rl = [];\n                for(j = 0; j < w; j++) {\n                    rl[j] = a[i] * b[0][j];\n                }\n                r[i] = rl;\n            }\n        } else {\n            for(i = 0; i < h; i++) {\n                r[i] = a[i] * b[0];\n            }\n        }\n        return r;\n    }\n    function array_div(a, b) {\n        return array_mul(a, b.inverse());\n    }\n    function array_element_wise_inverse(a) {\n        var r, i, n;\n        n = a.length;\n        r = [];\n        for(i = 0; i < n; i++)\n            r[i] = a[i].inverse();\n        return r;\n    }\n    function array_eq(a, b) {\n        var n, i;\n        n = a.length;\n        if (n != b.length)\n            return false;\n        for(i = 0; i < n; i++) {\n            if (a[i] != b[i])\n                return false;\n        }\n        return true;\n    }\n\n    operators_set(Array.prototype,\n        {\n            \"+\": array_add,\n            \"-\": array_sub,\n            \"*\": array_mul,\n            \"/\": array_div,\n            \"==\": array_eq,\n            \"pos\"(a) {\n                return a;\n            },\n            \"neg\"(a) {\n                var i, n, r;\n                n = a.length;\n                r = [];\n                for(i = 0; i < n; i++)\n                    r[i] = -a[i];\n                return r;\n            }\n        },\n        {\n            right: [Number, BigInt, Float, Fraction, Complex, Mod,\n                    Polynomial, PolyMod, RationalFunction, Series],\n            \"*\": array_scalar_mul,\n            \"/\"(a, b) { return a * b.inverse(); },\n            \"**\": generic_pow, /* XXX: only for integer */\n        },\n        {\n            left: [Number, BigInt, Float, Fraction, Complex, Mod,\n                   Polynomial, PolyMod, RationalFunction, Series],\n            \"*\"(a, b) { return array_scalar_mul(b, a); },\n            \"/\"(a, b) { return a * array_element_wise_inverse(b); },\n        });\n\n    add_props(Array.prototype, {\n        conj() {\n            var i, n, r;\n            n = this.length;\n            r = [];\n            for(i = 0; i < n; i++)\n                r[i] = this[i].conj();\n            return r;\n        },\n        dup() {\n            var r, i, n, el, a = this;\n            r = [];\n            n = a.length;\n            for(i = 0; i < n; i++) {\n                el = a[i];\n                if (Array.isArray(el))\n                    el = el.dup();\n                r[i] = el;\n            }\n            return r;\n        },\n        inverse() {\n            return Matrix.inverse(this);\n        },\n        norm2: Polynomial.prototype.norm2,\n    });\n\n})(this);\n\n/* global definitions */\nvar I = Complex(0, 1);\nvar X = Polynomial([0, 1]);\nvar O = Series.O;\n\nObject.defineProperty(this, \"PI\", { get: function () { return Float.PI } });\n\n/* put frequently used functions in the global context */\nvar gcd = Integer.gcd;\nvar fact = Integer.fact;\nvar comb = Integer.comb;\nvar pmod = Integer.pmod;\nvar invmod = Integer.invmod;\nvar factor = Integer.factor;\nvar isprime = Integer.isPrime;\nvar nextprime = Integer.nextPrime;\n\nfunction deriv(a)\n{\n    return a.deriv();\n}\n\nfunction integ(a)\n{\n    return a.integ();\n}\n\nfunction norm2(a)\n{\n    return a.norm2();\n}\n\nfunction abs(a)\n{\n    return a.abs();\n}\n\nfunction conj(a)\n{\n    return a.conj();\n}\n\nfunction arg(a)\n{\n    return a.arg();\n}\n\nfunction inverse(a)\n{\n    return a.inverse();\n}\n\nfunction trunc(a)\n{\n    if (Integer.isInteger(a)) {\n        return a;\n    } else if (a instanceof Fraction) {\n        return Integer.tdiv(a.num, a.den);\n    } else if (a instanceof Polynomial) {\n        return a;\n    } else if (a instanceof RationalFunction) {\n        return Polynomial.divrem(a.num, a.den)[0];\n    } else {\n        return Float.ceil(a);\n    }\n}\n\nfunction floor(a)\n{\n    if (Integer.isInteger(a)) {\n        return a;\n    } else if (a instanceof Fraction) {\n        return Integer.fdiv(a.num, a.den);\n    } else {\n        return Float.floor(a);\n    }\n}\n\nfunction ceil(a)\n{\n    if (Integer.isInteger(a)) {\n        return a;\n    } else if (a instanceof Fraction) {\n        return Integer.cdiv(a.num, a.den);\n    } else {\n        return Float.ceil(a);\n    }\n}\n\nfunction sqrt(a)\n{\n    var t, u, re, im;\n    if (a instanceof Series) {\n        return a ^ (1/2);\n    } else if (a instanceof Complex) {\n        t = abs(a);\n        u = a.re;\n        re = sqrt((t + u) / 2);\n        im = sqrt((t - u) / 2);\n        if (a.im < 0)\n            im = -im;\n        return Complex.toComplex(re, im);\n    } else {\n        a = Float(a);\n        if (a < 0) {\n            return Complex(0, Float.sqrt(-a));\n        } else {\n            return Float.sqrt(a);\n        }\n    }\n}\n\nfunction exp(a)\n{\n    return a.exp();\n}\n\nfunction log(a)\n{\n    return a.log();\n}\n\nfunction log2(a)\n{\n    return log(a) * Float.LOG2E;\n}\n\nfunction log10(a)\n{\n    return log(a) * Float.LOG10E;\n}\n\nfunction todb(a)\n{\n    return log10(a) * 10;\n}\n\nfunction fromdb(a)\n{\n    return 10 ^ (a / 10);\n}\n\nfunction sin(a)\n{\n    var t;\n    if (a instanceof Complex || a instanceof Series) {\n        t = exp(a * I);\n        return (t - 1/t) / (2 * I);\n    } else {\n        return Float.sin(Float(a));\n    }\n}\n\nfunction cos(a)\n{\n    var t;\n    if (a instanceof Complex || a instanceof Series) {\n        t = exp(a * I);\n        return (t + 1/t) / 2;\n    } else {\n        return Float.cos(Float(a));\n    }\n}\n\nfunction tan(a)\n{\n    if (a instanceof Complex || a instanceof Series) {\n        return sin(a) / cos(a);\n    } else {\n        return Float.tan(Float(a));\n    }\n}\n\nfunction asin(a)\n{\n    return Float.asin(Float(a));\n}\n\nfunction acos(a)\n{\n    return Float.acos(Float(a));\n}\n\nfunction atan(a)\n{\n    return Float.atan(Float(a));\n}\n\nfunction atan2(a, b)\n{\n    return Float.atan2(Float(a), Float(b));\n}\n\nfunction sinc(a)\n{\n    if (a == 0) {\n        return 1;\n    } else {\n        a *= Float.PI;\n        return sin(a) / a;\n    }\n}\n\nfunction todeg(a)\n{\n    return a * 180 / Float.PI;\n}\n\nfunction fromdeg(a)\n{\n    return a * Float.PI / 180;\n}\n\nfunction sinh(a)\n{\n    var e = Float.exp(Float(a));\n    return (e - 1/e) * 0.5;\n}\n\nfunction cosh(a)\n{\n    var e = Float.exp(Float(a));\n    return (e + 1/e) * 0.5;\n}\n\nfunction tanh(a)\n{\n    var e = Float.exp(Float(a) * 2);\n    return (e - 1) / (e + 1);\n}\n\nfunction asinh(a)\n{\n    var x = Float(a);\n    return log(sqrt(x * x + 1) + x);\n}\n\nfunction acosh(a)\n{\n    var x = Float(a);\n    return log(sqrt(x * x - 1) + x);\n}\n\nfunction atanh(a)\n{\n    var x = Float(a);\n    return 0.5 * log((1 + x) / (1 - x));\n}\n\nfunction sigmoid(x)\n{\n    x = Float(x);\n    return 1 / (1 + exp(-x));\n}\n\nfunction lerp(a, b, t)\n{\n    return a + (b - a) * t;\n}\n\nvar idn = Matrix.idn;\nvar diag = Matrix.diag;\nvar trans = Matrix.trans;\nvar trace = Matrix.trace;\nvar charpoly = Matrix.charpoly;\nvar eigenvals = Matrix.eigenvals;\nvar det = Matrix.det;\nvar rank = Matrix.rank;\nvar ker = Matrix.ker;\nvar cp = Matrix.cp;\nvar dp = Matrix.dp;\n\nvar polroots = Polynomial.roots;\nvar bestappr = Float.bestappr;\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/quickjs-atom.h",
    "content": "/*\n * QuickJS atom definitions\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n * Copyright (c) 2017-2018 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n#ifdef DEF\n\n/* Note: first atoms are considered as keywords in the parser */\nDEF(null, \"null\") /* must be first */\nDEF(false, \"false\")\nDEF(true, \"true\")\nDEF(if, \"if\")\nDEF(else, \"else\")\nDEF(return, \"return\")\nDEF(var, \"var\")\nDEF(this, \"this\")\nDEF(delete, \"delete\")\nDEF(void, \"void\")\nDEF(typeof, \"typeof\")\nDEF(new, \"new\")\nDEF(in, \"in\")\nDEF(instanceof, \"instanceof\")\nDEF(do, \"do\")\nDEF(while, \"while\")\nDEF(for, \"for\")\nDEF(break, \"break\")\nDEF(continue, \"continue\")\nDEF(switch, \"switch\")\nDEF(case, \"case\")\nDEF(default, \"default\")\nDEF(throw, \"throw\")\nDEF(try, \"try\")\nDEF(catch, \"catch\")\nDEF(finally, \"finally\")\nDEF(function, \"function\")\nDEF(debugger, \"debugger\")\nDEF(with, \"with\")\n/* FutureReservedWord */\nDEF(class, \"class\")\nDEF(const, \"const\")\nDEF(enum, \"enum\")\nDEF(export, \"export\")\nDEF(extends, \"extends\")\nDEF(import, \"import\")\nDEF(super, \"super\")\n/* FutureReservedWords when parsing strict mode code */\nDEF(implements, \"implements\")\nDEF(interface, \"interface\")\nDEF(let, \"let\")\nDEF(package, \"package\")\nDEF(private, \"private\")\nDEF(protected, \"protected\")\nDEF(public, \"public\")\nDEF(static, \"static\")\nDEF(yield, \"yield\")\nDEF(await, \"await\")\n\n/* empty string */\nDEF(empty_string, \"\")\n/* identifiers */\nDEF(length, \"length\")\nDEF(fileName, \"fileName\")\nDEF(lineNumber, \"lineNumber\")\nDEF(message, \"message\")\nDEF(errors, \"errors\")\nDEF(stack, \"stack\")\nDEF(name, \"name\")\nDEF(toString, \"toString\")\nDEF(toLocaleString, \"toLocaleString\")\nDEF(valueOf, \"valueOf\")\nDEF(eval, \"eval\")\nDEF(prototype, \"prototype\")\nDEF(constructor, \"constructor\")\nDEF(configurable, \"configurable\")\nDEF(writable, \"writable\")\nDEF(enumerable, \"enumerable\")\nDEF(value, \"value\")\nDEF(get, \"get\")\nDEF(set, \"set\")\nDEF(of, \"of\")\nDEF(__proto__, \"__proto__\")\nDEF(undefined, \"undefined\")\nDEF(number, \"number\")\nDEF(boolean, \"boolean\")\nDEF(string, \"string\")\nDEF(object, \"object\")\nDEF(symbol, \"symbol\")\nDEF(integer, \"integer\")\nDEF(unknown, \"unknown\")\nDEF(arguments, \"arguments\")\nDEF(callee, \"callee\")\nDEF(caller, \"caller\")\nDEF(_eval_, \"<eval>\")\nDEF(_ret_, \"<ret>\")\nDEF(_var_, \"<var>\")\nDEF(_arg_var_, \"<arg_var>\")\nDEF(_with_, \"<with>\")\nDEF(lastIndex, \"lastIndex\")\nDEF(target, \"target\")\nDEF(index, \"index\")\nDEF(input, \"input\")\nDEF(defineProperties, \"defineProperties\")\nDEF(apply, \"apply\")\nDEF(join, \"join\")\nDEF(concat, \"concat\")\nDEF(split, \"split\")\nDEF(construct, \"construct\")\nDEF(getPrototypeOf, \"getPrototypeOf\")\nDEF(setPrototypeOf, \"setPrototypeOf\")\nDEF(isExtensible, \"isExtensible\")\nDEF(preventExtensions, \"preventExtensions\")\nDEF(has, \"has\")\nDEF(deleteProperty, \"deleteProperty\")\nDEF(defineProperty, \"defineProperty\")\nDEF(getOwnPropertyDescriptor, \"getOwnPropertyDescriptor\")\nDEF(ownKeys, \"ownKeys\")\nDEF(add, \"add\")\nDEF(done, \"done\")\nDEF(next, \"next\")\nDEF(values, \"values\")\nDEF(source, \"source\")\nDEF(flags, \"flags\")\nDEF(global, \"global\")\nDEF(unicode, \"unicode\")\nDEF(raw, \"raw\")\nDEF(new_target, \"new.target\")\nDEF(this_active_func, \"this.active_func\")\nDEF(home_object, \"<home_object>\")\nDEF(computed_field, \"<computed_field>\")\nDEF(static_computed_field, \"<static_computed_field>\") /* must come after computed_fields */\nDEF(class_fields_init, \"<class_fields_init>\")\nDEF(brand, \"<brand>\")\nDEF(hash_constructor, \"#constructor\")\nDEF(as, \"as\")\nDEF(from, \"from\")\nDEF(meta, \"meta\")\nDEF(_default_, \"*default*\")\nDEF(_star_, \"*\")\nDEF(Module, \"Module\")\nDEF(then, \"then\")\nDEF(resolve, \"resolve\")\nDEF(reject, \"reject\")\nDEF(promise, \"promise\")\nDEF(proxy, \"proxy\")\nDEF(revoke, \"revoke\")\nDEF(async, \"async\")\nDEF(exec, \"exec\")\nDEF(groups, \"groups\")\nDEF(status, \"status\")\nDEF(reason, \"reason\")\nDEF(globalThis, \"globalThis\")\n#ifdef CONFIG_BIGNUM\nDEF(bigint, \"bigint\")\nDEF(bigfloat, \"bigfloat\")\nDEF(bigdecimal, \"bigdecimal\")\nDEF(roundingMode, \"roundingMode\")\nDEF(maximumSignificantDigits, \"maximumSignificantDigits\")\nDEF(maximumFractionDigits, \"maximumFractionDigits\")\n#endif\n#ifdef CONFIG_ATOMICS\nDEF(not_equal, \"not-equal\")\nDEF(timed_out, \"timed-out\")\nDEF(ok, \"ok\")\n#endif\nDEF(toJSON, \"toJSON\")\n/* class names */\nDEF(Object, \"Object\")\nDEF(Array, \"Array\")\nDEF(Error, \"Error\")\nDEF(Number, \"Number\")\nDEF(String, \"String\")\nDEF(Boolean, \"Boolean\")\nDEF(Symbol, \"Symbol\")\nDEF(Arguments, \"Arguments\")\nDEF(Math, \"Math\")\nDEF(JSON, \"JSON\")\nDEF(Date, \"Date\")\nDEF(Function, \"Function\")\nDEF(GeneratorFunction, \"GeneratorFunction\")\nDEF(ForInIterator, \"ForInIterator\")\nDEF(RegExp, \"RegExp\")\nDEF(ArrayBuffer, \"ArrayBuffer\")\nDEF(SharedArrayBuffer, \"SharedArrayBuffer\")\n/* must keep same order as class IDs for typed arrays */\nDEF(Uint8ClampedArray, \"Uint8ClampedArray\") \nDEF(Int8Array, \"Int8Array\")\nDEF(Uint8Array, \"Uint8Array\")\nDEF(Int16Array, \"Int16Array\")\nDEF(Uint16Array, \"Uint16Array\")\nDEF(Int32Array, \"Int32Array\")\nDEF(Uint32Array, \"Uint32Array\")\n#ifdef CONFIG_BIGNUM\nDEF(BigInt64Array, \"BigInt64Array\")\nDEF(BigUint64Array, \"BigUint64Array\")\n#endif\nDEF(Float32Array, \"Float32Array\")\nDEF(Float64Array, \"Float64Array\")\nDEF(DataView, \"DataView\")\n#ifdef CONFIG_BIGNUM\nDEF(BigInt, \"BigInt\")\nDEF(BigFloat, \"BigFloat\")\nDEF(BigFloatEnv, \"BigFloatEnv\")\nDEF(BigDecimal, \"BigDecimal\")\nDEF(OperatorSet, \"OperatorSet\")\nDEF(Operators, \"Operators\")\n#endif\nDEF(Map, \"Map\")\nDEF(Set, \"Set\") /* Map + 1 */\nDEF(WeakMap, \"WeakMap\") /* Map + 2 */\nDEF(WeakSet, \"WeakSet\") /* Map + 3 */\nDEF(Map_Iterator, \"Map Iterator\")\nDEF(Set_Iterator, \"Set Iterator\")\nDEF(Array_Iterator, \"Array Iterator\")\nDEF(String_Iterator, \"String Iterator\")\nDEF(RegExp_String_Iterator, \"RegExp String Iterator\")\nDEF(Generator, \"Generator\")\nDEF(Proxy, \"Proxy\")\nDEF(Promise, \"Promise\")\nDEF(PromiseResolveFunction, \"PromiseResolveFunction\")\nDEF(PromiseRejectFunction, \"PromiseRejectFunction\")\nDEF(AsyncFunction, \"AsyncFunction\")\nDEF(AsyncFunctionResolve, \"AsyncFunctionResolve\")\nDEF(AsyncFunctionReject, \"AsyncFunctionReject\")\nDEF(AsyncGeneratorFunction, \"AsyncGeneratorFunction\")\nDEF(AsyncGenerator, \"AsyncGenerator\")\nDEF(EvalError, \"EvalError\")\nDEF(RangeError, \"RangeError\")\nDEF(ReferenceError, \"ReferenceError\")\nDEF(SyntaxError, \"SyntaxError\")\nDEF(TypeError, \"TypeError\")\nDEF(URIError, \"URIError\")\nDEF(InternalError, \"InternalError\")\n/* private symbols */\nDEF(Private_brand, \"<brand>\")\n/* symbols */\nDEF(Symbol_toPrimitive, \"Symbol.toPrimitive\")\nDEF(Symbol_iterator, \"Symbol.iterator\")\nDEF(Symbol_match, \"Symbol.match\")\nDEF(Symbol_matchAll, \"Symbol.matchAll\")\nDEF(Symbol_replace, \"Symbol.replace\")\nDEF(Symbol_search, \"Symbol.search\")\nDEF(Symbol_split, \"Symbol.split\")\nDEF(Symbol_toStringTag, \"Symbol.toStringTag\")\nDEF(Symbol_isConcatSpreadable, \"Symbol.isConcatSpreadable\")\nDEF(Symbol_hasInstance, \"Symbol.hasInstance\")\nDEF(Symbol_species, \"Symbol.species\")\nDEF(Symbol_unscopables, \"Symbol.unscopables\")\nDEF(Symbol_asyncIterator, \"Symbol.asyncIterator\")\n#ifdef CONFIG_BIGNUM\nDEF(Symbol_operatorSet, \"Symbol.operatorSet\")\n#endif\n    \n#endif /* DEF */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/quickjs-libc.c",
    "content": "/*\n * QuickJS C library\n * \n * Copyright (c) 2017-2021 Fabrice Bellard\n * Copyright (c) 2017-2021 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <inttypes.h>\n#include <string.h>\n#include <assert.h>\n#include <unistd.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sys/time.h>\n#include <time.h>\n#include <signal.h>\n#include <limits.h>\n#include <sys/stat.h>\n#include <dirent.h>\n#if defined(_WIN32)\n#include <windows.h>\n#include <conio.h>\n#include <utime.h>\n#else\n#include <dlfcn.h>\n#include <termios.h>\n#include <sys/ioctl.h>\n#include <sys/wait.h>\n\n#if defined(__APPLE__)\ntypedef sig_t sighandler_t;\n#if !defined(environ)\n#include <crt_externs.h>\n#define environ (*_NSGetEnviron())\n#endif\n#endif /* __APPLE__ */\n\n#endif\n\n#if !defined(_WIN32)\n/* enable the os.Worker API. IT relies on POSIX threads */\n#define USE_WORKER\n#endif\n\n#ifdef USE_WORKER\n#include <pthread.h>\n#include <stdatomic.h>\n#endif\n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"quickjs-libc.h\"\n\n/* TODO:\n   - add socket calls\n*/\n\ntypedef struct {\n    struct list_head link;\n    int fd;\n    JSValue rw_func[2];\n} JSOSRWHandler;\n\ntypedef struct {\n    struct list_head link;\n    int sig_num;\n    JSValue func;\n} JSOSSignalHandler;\n\ntypedef struct {\n    struct list_head link;\n    BOOL has_object;\n    int64_t timeout;\n    JSValue func;\n} JSOSTimer;\n\ntypedef struct {\n    struct list_head link;\n    uint8_t *data;\n    size_t data_len;\n    /* list of SharedArrayBuffers, necessary to free the message */\n    uint8_t **sab_tab;\n    size_t sab_tab_len;\n} JSWorkerMessage;\n\ntypedef struct {\n    int ref_count;\n#ifdef USE_WORKER\n    pthread_mutex_t mutex;\n#endif\n    struct list_head msg_queue; /* list of JSWorkerMessage.link */\n    int read_fd;\n    int write_fd;\n} JSWorkerMessagePipe;\n\ntypedef struct {\n    struct list_head link;\n    JSWorkerMessagePipe *recv_pipe;\n    JSValue on_message_func;\n} JSWorkerMessageHandler;\n\ntypedef struct JSThreadState {\n    struct list_head os_rw_handlers; /* list of JSOSRWHandler.link */\n    struct list_head os_signal_handlers; /* list JSOSSignalHandler.link */\n    struct list_head os_timers; /* list of JSOSTimer.link */\n    struct list_head port_list; /* list of JSWorkerMessageHandler.link */\n    int eval_script_recurse; /* only used in the main thread */\n    /* not used in the main thread */\n    JSWorkerMessagePipe *recv_pipe, *send_pipe;\n} JSThreadState;\n\nstatic uint64_t os_pending_signals;\nstatic int (*os_poll_func)(JSContext *ctx);\n\nstatic void js_std_dbuf_init(JSContext *ctx, DynBuf *s)\n{\n    dbuf_init2(s, JS_GetRuntime(ctx), (DynBufReallocFunc *)js_realloc_rt);\n}\n\nstatic BOOL my_isdigit(int c)\n{\n    return (c >= '0' && c <= '9');\n}\n\nstatic JSValue js_printf_internal(JSContext *ctx,\n                                  int argc, JSValueConst *argv, FILE *fp)\n{\n    char fmtbuf[32];\n    uint8_t cbuf[UTF8_CHAR_LEN_MAX+1];\n    JSValue res;\n    DynBuf dbuf;\n    const char *fmt_str;\n    const uint8_t *fmt, *fmt_end;\n    const uint8_t *p;\n    char *q;\n    int i, c, len, mod;\n    size_t fmt_len;\n    int32_t int32_arg;\n    int64_t int64_arg;\n    double double_arg;\n    const char *string_arg;\n    /* Use indirect call to dbuf_printf to prevent gcc warning */\n    int (*dbuf_printf_fun)(DynBuf *s, const char *fmt, ...) = (void*)dbuf_printf;\n\n    js_std_dbuf_init(ctx, &dbuf);\n\n    if (argc > 0) {\n        fmt_str = JS_ToCStringLen(ctx, &fmt_len, argv[0]);\n        if (!fmt_str)\n            goto fail;\n\n        i = 1;\n        fmt = (const uint8_t *)fmt_str;\n        fmt_end = fmt + fmt_len;\n        while (fmt < fmt_end) {\n            for (p = fmt; fmt < fmt_end && *fmt != '%'; fmt++)\n                continue;\n            dbuf_put(&dbuf, p, fmt - p);\n            if (fmt >= fmt_end)\n                break;\n            q = fmtbuf;\n            *q++ = *fmt++;  /* copy '%' */\n            \n            /* flags */\n            for(;;) {\n                c = *fmt;\n                if (c == '0' || c == '#' || c == '+' || c == '-' || c == ' ' ||\n                    c == '\\'') {\n                    if (q >= fmtbuf + sizeof(fmtbuf) - 1)\n                        goto invalid;\n                    *q++ = c;\n                    fmt++;\n                } else {\n                    break;\n                }\n            }\n            /* width */\n            if (*fmt == '*') {\n                if (i >= argc)\n                    goto missing;\n                if (JS_ToInt32(ctx, &int32_arg, argv[i++]))\n                    goto fail;\n                q += snprintf(q, fmtbuf + sizeof(fmtbuf) - q, \"%d\", int32_arg);\n                fmt++;\n            } else {\n                while (my_isdigit(*fmt)) {\n                    if (q >= fmtbuf + sizeof(fmtbuf) - 1)\n                        goto invalid;\n                    *q++ = *fmt++;\n                }\n            }\n            if (*fmt == '.') {\n                if (q >= fmtbuf + sizeof(fmtbuf) - 1)\n                    goto invalid;\n                *q++ = *fmt++;\n                if (*fmt == '*') {\n                    if (i >= argc)\n                        goto missing;\n                    if (JS_ToInt32(ctx, &int32_arg, argv[i++]))\n                        goto fail;\n                    q += snprintf(q, fmtbuf + sizeof(fmtbuf) - q, \"%d\", int32_arg);\n                    fmt++;\n                } else {\n                    while (my_isdigit(*fmt)) {\n                        if (q >= fmtbuf + sizeof(fmtbuf) - 1)\n                            goto invalid;\n                        *q++ = *fmt++;\n                    }\n                }\n            }\n\n            /* we only support the \"l\" modifier for 64 bit numbers */\n            mod = ' ';\n            if (*fmt == 'l') {\n                mod = *fmt++;\n            }\n            \n            /* type */\n            c = *fmt++;\n            if (q >= fmtbuf + sizeof(fmtbuf) - 1)\n                goto invalid;\n            *q++ = c;\n            *q = '\\0';\n            \n            switch (c) {\n            case 'c':\n                if (i >= argc)\n                    goto missing;\n                if (JS_IsString(argv[i])) {\n                    string_arg = JS_ToCString(ctx, argv[i++]);\n                    if (!string_arg)\n                        goto fail;\n                    int32_arg = unicode_from_utf8((uint8_t *)string_arg, UTF8_CHAR_LEN_MAX, &p);\n                    JS_FreeCString(ctx, string_arg);\n                } else {\n                    if (JS_ToInt32(ctx, &int32_arg, argv[i++]))\n                        goto fail;\n                }\n                /* handle utf-8 encoding explicitly */\n                if ((unsigned)int32_arg > 0x10FFFF)\n                    int32_arg = 0xFFFD;\n                /* ignore conversion flags, width and precision */\n                len = unicode_to_utf8(cbuf, int32_arg);\n                dbuf_put(&dbuf, cbuf, len);\n                break;\n                \n            case 'd':\n            case 'i':\n            case 'o':\n            case 'u':\n            case 'x':\n            case 'X':\n                if (i >= argc)\n                    goto missing;\n                if (JS_ToInt64Ext(ctx, &int64_arg, argv[i++]))\n                    goto fail;\n                if (mod == 'l') {\n                    /* 64 bit number */\n#if defined(_WIN32)\n                    if (q >= fmtbuf + sizeof(fmtbuf) - 3)\n                        goto invalid;\n                    q[2] = q[-1];\n                    q[-1] = 'I';\n                    q[0] = '6';\n                    q[1] = '4';\n                    q[3] = '\\0';\n                    dbuf_printf_fun(&dbuf, fmtbuf, (int64_t)int64_arg);\n#else\n                    if (q >= fmtbuf + sizeof(fmtbuf) - 2)\n                        goto invalid;\n                    q[1] = q[-1];\n                    q[-1] = q[0] = 'l';\n                    q[2] = '\\0';\n                    dbuf_printf_fun(&dbuf, fmtbuf, (long long)int64_arg);\n#endif\n                } else {\n                    dbuf_printf_fun(&dbuf, fmtbuf, (int)int64_arg);\n                }\n                break;\n\n            case 's':\n                if (i >= argc)\n                    goto missing;\n                /* XXX: handle strings containing null characters */\n                string_arg = JS_ToCString(ctx, argv[i++]);\n                if (!string_arg)\n                    goto fail;\n                dbuf_printf_fun(&dbuf, fmtbuf, string_arg);\n                JS_FreeCString(ctx, string_arg);\n                break;\n                \n            case 'e':\n            case 'f':\n            case 'g':\n            case 'a':\n            case 'E':\n            case 'F':\n            case 'G':\n            case 'A':\n                if (i >= argc)\n                    goto missing;\n                if (JS_ToFloat64(ctx, &double_arg, argv[i++]))\n                    goto fail;\n                dbuf_printf_fun(&dbuf, fmtbuf, double_arg);\n                break;\n                \n            case '%':\n                dbuf_putc(&dbuf, '%');\n                break;\n                \n            default:\n                /* XXX: should support an extension mechanism */\n            invalid:\n                JS_ThrowTypeError(ctx, \"invalid conversion specifier in format string\");\n                goto fail;\n            missing:\n                JS_ThrowReferenceError(ctx, \"missing argument for conversion specifier\");\n                goto fail;\n            }\n        }\n        JS_FreeCString(ctx, fmt_str);\n    }\n    if (dbuf.error) {\n        res = JS_ThrowOutOfMemory(ctx);\n    } else {\n        if (fp) {\n            len = fwrite(dbuf.buf, 1, dbuf.size, fp);\n            res = JS_NewInt32(ctx, len);\n        } else {\n            res = JS_NewStringLen(ctx, (char *)dbuf.buf, dbuf.size);\n        }\n    }\n    dbuf_free(&dbuf);\n    return res;\n\nfail:\n    dbuf_free(&dbuf);\n    return JS_EXCEPTION;\n}\n\nuint8_t *js_load_file(JSContext *ctx, size_t *pbuf_len, const char *filename)\n{\n    FILE *f;\n    uint8_t *buf;\n    size_t buf_len;\n    long lret;\n    \n    f = fopen(filename, \"rb\");\n    if (!f)\n        return NULL;\n    if (fseek(f, 0, SEEK_END) < 0)\n        goto fail;\n    lret = ftell(f);\n    if (lret < 0)\n        goto fail;\n    /* XXX: on Linux, ftell() return LONG_MAX for directories */\n    if (lret == LONG_MAX) {\n        errno = EISDIR;\n        goto fail;\n    }\n    buf_len = lret;\n    if (fseek(f, 0, SEEK_SET) < 0)\n        goto fail;\n    if (ctx)\n        buf = js_malloc(ctx, buf_len + 1);\n    else\n        buf = malloc(buf_len + 1);\n    if (!buf)\n        goto fail;\n    if (fread(buf, 1, buf_len, f) != buf_len) {\n        errno = EIO;\n        if (ctx)\n            js_free(ctx, buf);\n        else\n            free(buf);\n    fail:\n        fclose(f);\n        return NULL;\n    }\n    buf[buf_len] = '\\0';\n    fclose(f);\n    *pbuf_len = buf_len;\n    return buf;\n}\n\n/* load and evaluate a file */\nstatic JSValue js_loadScript(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    uint8_t *buf;\n    const char *filename;\n    JSValue ret;\n    size_t buf_len;\n    \n    filename = JS_ToCString(ctx, argv[0]);\n    if (!filename)\n        return JS_EXCEPTION;\n    buf = js_load_file(ctx, &buf_len, filename);\n    if (!buf) {\n        JS_ThrowReferenceError(ctx, \"could not load '%s'\", filename);\n        JS_FreeCString(ctx, filename);\n        return JS_EXCEPTION;\n    }\n    ret = JS_Eval(ctx, (char *)buf, buf_len, filename,\n                  JS_EVAL_TYPE_GLOBAL);\n    js_free(ctx, buf);\n    JS_FreeCString(ctx, filename);\n    return ret;\n}\n\n/* load a file as a UTF-8 encoded string */\nstatic JSValue js_std_loadFile(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    uint8_t *buf;\n    const char *filename;\n    JSValue ret;\n    size_t buf_len;\n    \n    filename = JS_ToCString(ctx, argv[0]);\n    if (!filename)\n        return JS_EXCEPTION;\n    buf = js_load_file(ctx, &buf_len, filename);\n    JS_FreeCString(ctx, filename);\n    if (!buf)\n        return JS_NULL;\n    ret = JS_NewStringLen(ctx, (char *)buf, buf_len);\n    js_free(ctx, buf);\n    return ret;\n}\n\ntypedef JSModuleDef *(JSInitModuleFunc)(JSContext *ctx,\n                                        const char *module_name);\n\n\n#if defined(_WIN32)\nstatic JSModuleDef *js_module_loader_so(JSContext *ctx,\n                                        const char *module_name)\n{\n    JS_ThrowReferenceError(ctx, \"shared library modules are not supported yet\");\n    return NULL;\n}\n#else\nstatic JSModuleDef *js_module_loader_so(JSContext *ctx,\n                                        const char *module_name)\n{\n    JSModuleDef *m;\n    void *hd;\n    JSInitModuleFunc *init;\n    char *filename;\n    \n    if (!strchr(module_name, '/')) {\n        /* must add a '/' so that the DLL is not searched in the\n           system library paths */\n        filename = js_malloc(ctx, strlen(module_name) + 2 + 1);\n        if (!filename)\n            return NULL;\n        strcpy(filename, \"./\");\n        strcpy(filename + 2, module_name);\n    } else {\n        filename = (char *)module_name;\n    }\n    \n    /* C module */\n    hd = dlopen(filename, RTLD_NOW | RTLD_LOCAL);\n    if (filename != module_name)\n        js_free(ctx, filename);\n    if (!hd) {\n        JS_ThrowReferenceError(ctx, \"could not load module filename '%s' as shared library\",\n                               module_name);\n        goto fail;\n    }\n\n    init = dlsym(hd, \"js_init_module\");\n    if (!init) {\n        JS_ThrowReferenceError(ctx, \"could not load module filename '%s': js_init_module not found\",\n                               module_name);\n        goto fail;\n    }\n\n    m = init(ctx, module_name);\n    if (!m) {\n        JS_ThrowReferenceError(ctx, \"could not load module filename '%s': initialization error\",\n                               module_name);\n    fail:\n        if (hd)\n            dlclose(hd);\n        return NULL;\n    }\n    return m;\n}\n#endif /* !_WIN32 */\n\nint js_module_set_import_meta(JSContext *ctx, JSValueConst func_val,\n                              JS_BOOL use_realpath, JS_BOOL is_main)\n{\n    JSModuleDef *m;\n    char buf[PATH_MAX + 16];\n    JSValue meta_obj;\n    JSAtom module_name_atom;\n    const char *module_name;\n    \n    assert(JS_VALUE_GET_TAG(func_val) == JS_TAG_MODULE);\n    m = JS_VALUE_GET_PTR(func_val);\n\n    module_name_atom = JS_GetModuleName(ctx, m);\n    module_name = JS_AtomToCString(ctx, module_name_atom);\n    JS_FreeAtom(ctx, module_name_atom);\n    if (!module_name)\n        return -1;\n    if (!strchr(module_name, ':')) {\n        strcpy(buf, \"file://\");\n#if !defined(_WIN32)\n        /* realpath() cannot be used with modules compiled with qjsc\n           because the corresponding module source code is not\n           necessarily present */\n        if (use_realpath) {\n            char *res = realpath(module_name, buf + strlen(buf));\n            if (!res) {\n                JS_ThrowTypeError(ctx, \"realpath failure\");\n                JS_FreeCString(ctx, module_name);\n                return -1;\n            }\n        } else\n#endif\n        {\n            pstrcat(buf, sizeof(buf), module_name);\n        }\n    } else {\n        pstrcpy(buf, sizeof(buf), module_name);\n    }\n    JS_FreeCString(ctx, module_name);\n    \n    meta_obj = JS_GetImportMeta(ctx, m);\n    if (JS_IsException(meta_obj))\n        return -1;\n    JS_DefinePropertyValueStr(ctx, meta_obj, \"url\",\n                              JS_NewString(ctx, buf),\n                              JS_PROP_C_W_E);\n    JS_DefinePropertyValueStr(ctx, meta_obj, \"main\",\n                              JS_NewBool(ctx, is_main),\n                              JS_PROP_C_W_E);\n    JS_FreeValue(ctx, meta_obj);\n    return 0;\n}\n\nJSModuleDef *js_module_loader(JSContext *ctx,\n                              const char *module_name, void *opaque)\n{\n    JSModuleDef *m;\n\n    if (has_suffix(module_name, \".so\")) {\n        m = js_module_loader_so(ctx, module_name);\n    } else {\n        size_t buf_len;\n        uint8_t *buf;\n        JSValue func_val;\n    \n        buf = js_load_file(ctx, &buf_len, module_name);\n        if (!buf) {\n            JS_ThrowReferenceError(ctx, \"could not load module filename '%s'\",\n                                   module_name);\n            return NULL;\n        }\n        \n        /* compile the module */\n        func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name,\n                           JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);\n        js_free(ctx, buf);\n        if (JS_IsException(func_val))\n            return NULL;\n        /* XXX: could propagate the exception */\n        js_module_set_import_meta(ctx, func_val, TRUE, FALSE);\n        /* the module is already referenced, so we must free it */\n        m = JS_VALUE_GET_PTR(func_val);\n        JS_FreeValue(ctx, func_val);\n    }\n    return m;\n}\n\nstatic JSValue js_std_exit(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    int status;\n    if (JS_ToInt32(ctx, &status, argv[0]))\n        status = -1;\n    exit(status);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_std_getenv(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    const char *name, *str;\n    name = JS_ToCString(ctx, argv[0]);\n    if (!name)\n        return JS_EXCEPTION;\n    str = getenv(name);\n    JS_FreeCString(ctx, name);\n    if (!str)\n        return JS_UNDEFINED;\n    else\n        return JS_NewString(ctx, str);\n}\n\n#if defined(_WIN32)\nstatic void setenv(const char *name, const char *value, int overwrite)\n{\n    char *str;\n    size_t name_len, value_len;\n    name_len = strlen(name);\n    value_len = strlen(value);\n    str = malloc(name_len + 1 + value_len + 1);\n    memcpy(str, name, name_len);\n    str[name_len] = '=';\n    memcpy(str + name_len + 1, value, value_len);\n    str[name_len + 1 + value_len] = '\\0';\n    _putenv(str);\n    free(str);\n}\n\nstatic void unsetenv(const char *name)\n{\n    setenv(name, \"\", TRUE);\n}\n#endif /* _WIN32 */\n\nstatic JSValue js_std_setenv(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    const char *name, *value;\n    name = JS_ToCString(ctx, argv[0]);\n    if (!name)\n        return JS_EXCEPTION;\n    value = JS_ToCString(ctx, argv[1]);\n    if (!value) {\n        JS_FreeCString(ctx, name);\n        return JS_EXCEPTION;\n    }\n    setenv(name, value, TRUE);\n    JS_FreeCString(ctx, name);\n    JS_FreeCString(ctx, value);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_std_unsetenv(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    const char *name;\n    name = JS_ToCString(ctx, argv[0]);\n    if (!name)\n        return JS_EXCEPTION;\n    unsetenv(name);\n    JS_FreeCString(ctx, name);\n    return JS_UNDEFINED;\n}\n\n/* return an object containing the list of the available environment\n   variables. */\nstatic JSValue js_std_getenviron(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    char **envp;\n    const char *name, *p, *value;\n    JSValue obj;\n    uint32_t idx;\n    size_t name_len;\n    JSAtom atom;\n    int ret;\n\n    obj = JS_NewObject(ctx);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    envp = environ;\n    for(idx = 0; envp[idx] != NULL; idx++) {\n        name = envp[idx];\n        p = strchr(name, '=');\n        name_len = p - name;\n        if (!p)\n            continue;\n        value = p + 1;\n        atom = JS_NewAtomLen(ctx, name, name_len);\n        if (atom == JS_ATOM_NULL)\n            goto fail;\n        ret = JS_DefinePropertyValue(ctx, obj, atom, JS_NewString(ctx, value),\n                                     JS_PROP_C_W_E);\n        JS_FreeAtom(ctx, atom);\n        if (ret < 0)\n            goto fail;\n    }\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_std_gc(JSContext *ctx, JSValueConst this_val,\n                         int argc, JSValueConst *argv)\n{\n    JS_RunGC(JS_GetRuntime(ctx));\n    return JS_UNDEFINED;\n}\n\nstatic int interrupt_handler(JSRuntime *rt, void *opaque)\n{\n    return (os_pending_signals >> SIGINT) & 1;\n}\n\nstatic int get_bool_option(JSContext *ctx, BOOL *pbool,\n                           JSValueConst obj,\n                           const char *option)\n{\n    JSValue val;\n    val = JS_GetPropertyStr(ctx, obj, option);\n    if (JS_IsException(val))\n        return -1;\n    if (!JS_IsUndefined(val)) {\n        *pbool = JS_ToBool(ctx, val);\n    }\n    JS_FreeValue(ctx, val);\n    return 0;\n}\n\nstatic JSValue js_evalScript(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    JSRuntime *rt = JS_GetRuntime(ctx);\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    const char *str;\n    size_t len;\n    JSValue ret;\n    JSValueConst options_obj;\n    BOOL backtrace_barrier = FALSE;\n    int flags;\n    \n    if (argc >= 2) {\n        options_obj = argv[1];\n        if (get_bool_option(ctx, &backtrace_barrier, options_obj,\n                            \"backtrace_barrier\"))\n            return JS_EXCEPTION;\n    }\n\n    str = JS_ToCStringLen(ctx, &len, argv[0]);\n    if (!str)\n        return JS_EXCEPTION;\n    if (!ts->recv_pipe && ++ts->eval_script_recurse == 1) {\n        /* install the interrupt handler */\n        JS_SetInterruptHandler(JS_GetRuntime(ctx), interrupt_handler, NULL);\n    }\n    flags = JS_EVAL_TYPE_GLOBAL; \n    if (backtrace_barrier)\n        flags |= JS_EVAL_FLAG_BACKTRACE_BARRIER;\n    ret = JS_Eval(ctx, str, len, \"<evalScript>\", flags);\n    JS_FreeCString(ctx, str);\n    if (!ts->recv_pipe && --ts->eval_script_recurse == 0) {\n        /* remove the interrupt handler */\n        JS_SetInterruptHandler(JS_GetRuntime(ctx), NULL, NULL);\n        os_pending_signals &= ~((uint64_t)1 << SIGINT);\n        /* convert the uncatchable \"interrupted\" error into a normal error\n           so that it can be caught by the REPL */\n        if (JS_IsException(ret))\n            JS_ResetUncatchableError(ctx);\n    }\n    return ret;\n}\n\nstatic JSClassID js_std_file_class_id;\n\ntypedef struct {\n    FILE *f;\n    BOOL close_in_finalizer;\n    BOOL is_popen;\n} JSSTDFile;\n\nstatic void js_std_file_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSSTDFile *s = JS_GetOpaque(val, js_std_file_class_id);\n    if (s) {\n        if (s->f && s->close_in_finalizer) {\n            if (s->is_popen)\n                pclose(s->f);\n            else\n                fclose(s->f);\n        }\n        js_free_rt(rt, s);\n    }\n}\n\nstatic ssize_t js_get_errno(ssize_t ret)\n{\n    if (ret == -1)\n        ret = -errno;\n    return ret;\n}\n\nstatic JSValue js_std_strerror(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    int err;\n    if (JS_ToInt32(ctx, &err, argv[0]))\n        return JS_EXCEPTION;\n    return JS_NewString(ctx, strerror(err));\n}\n\nstatic JSValue js_std_parseExtJSON(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    JSValue obj;\n    const char *str;\n    size_t len;\n\n    str = JS_ToCStringLen(ctx, &len, argv[0]);\n    if (!str)\n        return JS_EXCEPTION;\n    obj = JS_ParseJSON2(ctx, str, len, \"<input>\", JS_PARSE_JSON_EXT);\n    JS_FreeCString(ctx, str);\n    return obj;\n}\n\nstatic JSValue js_new_std_file(JSContext *ctx, FILE *f,\n                               BOOL close_in_finalizer,\n                               BOOL is_popen)\n{\n    JSSTDFile *s;\n    JSValue obj;\n    obj = JS_NewObjectClass(ctx, js_std_file_class_id);\n    if (JS_IsException(obj))\n        return obj;\n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s) {\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    s->close_in_finalizer = close_in_finalizer;\n    s->is_popen = is_popen;\n    s->f = f;\n    JS_SetOpaque(obj, s);\n    return obj;\n}\n\nstatic void js_set_error_object(JSContext *ctx, JSValue obj, int err)\n{\n    if (!JS_IsUndefined(obj)) {\n        JS_SetPropertyStr(ctx, obj, \"errno\", JS_NewInt32(ctx, err));\n    }\n}\n\nstatic JSValue js_std_open(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    const char *filename, *mode = NULL;\n    FILE *f;\n    int err;\n    \n    filename = JS_ToCString(ctx, argv[0]);\n    if (!filename)\n        goto fail;\n    mode = JS_ToCString(ctx, argv[1]);\n    if (!mode)\n        goto fail;\n    if (mode[strspn(mode, \"rwa+b\")] != '\\0') {\n        JS_ThrowTypeError(ctx, \"invalid file mode\");\n        goto fail;\n    }\n\n    f = fopen(filename, mode);\n    if (!f)\n        err = errno;\n    else\n        err = 0;\n    if (argc >= 3)\n        js_set_error_object(ctx, argv[2], err);\n    JS_FreeCString(ctx, filename);\n    JS_FreeCString(ctx, mode);\n    if (!f)\n        return JS_NULL;\n    return js_new_std_file(ctx, f, TRUE, FALSE);\n fail:\n    JS_FreeCString(ctx, filename);\n    JS_FreeCString(ctx, mode);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_std_popen(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv)\n{\n    const char *filename, *mode = NULL;\n    FILE *f;\n    int err;\n    \n    filename = JS_ToCString(ctx, argv[0]);\n    if (!filename)\n        goto fail;\n    mode = JS_ToCString(ctx, argv[1]);\n    if (!mode)\n        goto fail;\n    if (mode[strspn(mode, \"rw\")] != '\\0') {\n        JS_ThrowTypeError(ctx, \"invalid file mode\");\n        goto fail;\n    }\n\n    f = popen(filename, mode);\n    if (!f)\n        err = errno;\n    else\n        err = 0;\n    if (argc >= 3)\n        js_set_error_object(ctx, argv[2], err);\n    JS_FreeCString(ctx, filename);\n    JS_FreeCString(ctx, mode);\n    if (!f)\n        return JS_NULL;\n    return js_new_std_file(ctx, f, TRUE, TRUE);\n fail:\n    JS_FreeCString(ctx, filename);\n    JS_FreeCString(ctx, mode);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_std_fdopen(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    const char *mode;\n    FILE *f;\n    int fd, err;\n\n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    mode = JS_ToCString(ctx, argv[1]);\n    if (!mode)\n        goto fail;\n    if (mode[strspn(mode, \"rwa+\")] != '\\0') {\n        JS_ThrowTypeError(ctx, \"invalid file mode\");\n        goto fail;\n    }\n\n    f = fdopen(fd, mode);\n    if (!f)\n        err = errno;\n    else\n        err = 0;\n    if (argc >= 3)\n        js_set_error_object(ctx, argv[2], err);\n    JS_FreeCString(ctx, mode);\n    if (!f)\n        return JS_NULL;\n    return js_new_std_file(ctx, f, TRUE, FALSE);\n fail:\n    JS_FreeCString(ctx, mode);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_std_tmpfile(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    FILE *f;\n    f = tmpfile();\n    if (argc >= 1)\n        js_set_error_object(ctx, argv[0], f ? 0 : errno);\n    if (!f)\n        return JS_NULL;\n    return js_new_std_file(ctx, f, TRUE, FALSE);\n}\n\nstatic JSValue js_std_sprintf(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv)\n{\n    return js_printf_internal(ctx, argc, argv, NULL);\n}\n\nstatic JSValue js_std_printf(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    return js_printf_internal(ctx, argc, argv, stdout);\n}\n\nstatic FILE *js_std_file_get(JSContext *ctx, JSValueConst obj)\n{\n    JSSTDFile *s = JS_GetOpaque2(ctx, obj, js_std_file_class_id);\n    if (!s)\n        return NULL;\n    if (!s->f) {\n        JS_ThrowTypeError(ctx, \"invalid file handle\");\n        return NULL;\n    }\n    return s->f;\n}\n\nstatic JSValue js_std_file_puts(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv, int magic)\n{\n    FILE *f;\n    int i;\n    const char *str;\n    size_t len;\n\n    if (magic == 0) {\n        f = stdout;\n    } else {\n        f = js_std_file_get(ctx, this_val);\n        if (!f)\n            return JS_EXCEPTION;\n    }\n    \n    for(i = 0; i < argc; i++) {\n        str = JS_ToCStringLen(ctx, &len, argv[i]);\n        if (!str)\n            return JS_EXCEPTION;\n        fwrite(str, 1, len, f);\n        JS_FreeCString(ctx, str);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_std_file_close(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSSTDFile *s = JS_GetOpaque2(ctx, this_val, js_std_file_class_id);\n    int err;\n    if (!s)\n        return JS_EXCEPTION;\n    if (!s->f)\n        return JS_ThrowTypeError(ctx, \"invalid file handle\");\n    if (s->is_popen)\n        err = js_get_errno(pclose(s->f));\n    else\n        err = js_get_errno(fclose(s->f));\n    s->f = NULL;\n    return JS_NewInt32(ctx, err);\n}\n\nstatic JSValue js_std_file_printf(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    if (!f)\n        return JS_EXCEPTION;\n    return js_printf_internal(ctx, argc, argv, f);\n}\n\nstatic JSValue js_std_file_flush(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    if (!f)\n        return JS_EXCEPTION;\n    fflush(f);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_std_file_tell(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv, int is_bigint)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    int64_t pos;\n    if (!f)\n        return JS_EXCEPTION;\n#if defined(__linux__)\n    pos = ftello(f);\n#else\n    pos = ftell(f);\n#endif\n    if (is_bigint)\n        return JS_NewBigInt64(ctx, pos);\n    else\n        return JS_NewInt64(ctx, pos);\n}\n\nstatic JSValue js_std_file_seek(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    int64_t pos;\n    int whence, ret;\n    if (!f)\n        return JS_EXCEPTION;\n    if (JS_ToInt64Ext(ctx, &pos, argv[0]))\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &whence, argv[1]))\n        return JS_EXCEPTION;\n#if defined(__linux__)\n    ret = fseeko(f, pos, whence);\n#else\n    ret = fseek(f, pos, whence);\n#endif\n    if (ret < 0)\n        ret = -errno;\n    return JS_NewInt32(ctx, ret);\n}\n\nstatic JSValue js_std_file_eof(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    if (!f)\n        return JS_EXCEPTION;\n    return JS_NewBool(ctx, feof(f));\n}\n\nstatic JSValue js_std_file_error(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    if (!f)\n        return JS_EXCEPTION;\n    return JS_NewBool(ctx, ferror(f));\n}\n\nstatic JSValue js_std_file_clearerr(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    if (!f)\n        return JS_EXCEPTION;\n    clearerr(f);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_std_file_fileno(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    if (!f)\n        return JS_EXCEPTION;\n    return JS_NewInt32(ctx, fileno(f));\n}\n\nstatic JSValue js_std_file_read_write(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv, int magic)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    uint64_t pos, len;\n    size_t size, ret;\n    uint8_t *buf;\n    \n    if (!f)\n        return JS_EXCEPTION;\n    if (JS_ToIndex(ctx, &pos, argv[1]))\n        return JS_EXCEPTION;\n    if (JS_ToIndex(ctx, &len, argv[2]))\n        return JS_EXCEPTION;\n    buf = JS_GetArrayBuffer(ctx, &size, argv[0]);\n    if (!buf)\n        return JS_EXCEPTION;\n    if (pos + len > size)\n        return JS_ThrowRangeError(ctx, \"read/write array buffer overflow\");\n    if (magic)\n        ret = fwrite(buf + pos, 1, len, f);\n    else\n        ret = fread(buf + pos, 1, len, f);\n    return JS_NewInt64(ctx, ret);\n}\n\n/* XXX: could use less memory and go faster */\nstatic JSValue js_std_file_getline(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    int c;\n    DynBuf dbuf;\n    JSValue obj;\n    \n    if (!f)\n        return JS_EXCEPTION;\n\n    js_std_dbuf_init(ctx, &dbuf);\n    for(;;) {\n        c = fgetc(f);\n        if (c == EOF) {\n            if (dbuf.size == 0) {\n                /* EOF */\n                dbuf_free(&dbuf);\n                return JS_NULL;\n            } else {\n                break;\n            }\n        }\n        if (c == '\\n')\n            break;\n        if (dbuf_putc(&dbuf, c)) {\n            dbuf_free(&dbuf);\n            return JS_ThrowOutOfMemory(ctx);\n        }\n    }\n    obj = JS_NewStringLen(ctx, (const char *)dbuf.buf, dbuf.size);\n    dbuf_free(&dbuf);\n    return obj;\n}\n\n/* XXX: could use less memory and go faster */\nstatic JSValue js_std_file_readAsString(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    int c;\n    DynBuf dbuf;\n    JSValue obj;\n    uint64_t max_size64;\n    size_t max_size;\n    JSValueConst max_size_val;\n    \n    if (!f)\n        return JS_EXCEPTION;\n\n    if (argc >= 1)\n        max_size_val = argv[0];\n    else\n        max_size_val = JS_UNDEFINED;\n    max_size = (size_t)-1;\n    if (!JS_IsUndefined(max_size_val)) {\n        if (JS_ToIndex(ctx, &max_size64, max_size_val))\n            return JS_EXCEPTION;\n        if (max_size64 < max_size)\n            max_size = max_size64;\n    }\n\n    js_std_dbuf_init(ctx, &dbuf);\n    while (max_size != 0) {\n        c = fgetc(f);\n        if (c == EOF)\n            break;\n        if (dbuf_putc(&dbuf, c)) {\n            dbuf_free(&dbuf);\n            return JS_EXCEPTION;\n        }\n        max_size--;\n    }\n    obj = JS_NewStringLen(ctx, (const char *)dbuf.buf, dbuf.size);\n    dbuf_free(&dbuf);\n    return obj;\n}\n\nstatic JSValue js_std_file_getByte(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    if (!f)\n        return JS_EXCEPTION;\n    return JS_NewInt32(ctx, fgetc(f));\n}\n\nstatic JSValue js_std_file_putByte(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    int c;\n    if (!f)\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &c, argv[0]))\n        return JS_EXCEPTION;\n    c = fputc(c, f);\n    return JS_NewInt32(ctx, c);\n}\n\n/* urlGet */\n\n#define URL_GET_PROGRAM \"curl -s -i\"\n#define URL_GET_BUF_SIZE 4096\n\nstatic int http_get_header_line(FILE *f, char *buf, size_t buf_size,\n                                DynBuf *dbuf)\n{\n    int c;\n    char *p;\n    \n    p = buf;\n    for(;;) {\n        c = fgetc(f);\n        if (c < 0)\n            return -1;\n        if ((p - buf) < buf_size - 1)\n            *p++ = c;\n        if (dbuf)\n            dbuf_putc(dbuf, c);\n        if (c == '\\n')\n            break;\n    }\n    *p = '\\0';\n    return 0;\n}\n\nstatic int http_get_status(const char *buf)\n{\n    const char *p = buf;\n    while (*p != ' ' && *p != '\\0')\n        p++;\n    if (*p != ' ')\n        return 0;\n    while (*p == ' ')\n        p++;\n    return atoi(p);\n}\n\nstatic JSValue js_std_urlGet(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    const char *url;\n    DynBuf cmd_buf;\n    DynBuf data_buf_s, *data_buf = &data_buf_s;\n    DynBuf header_buf_s, *header_buf = &header_buf_s;\n    char *buf; \n    size_t i, len;\n    int c, status;\n    JSValue response = JS_UNDEFINED, ret_obj;\n    JSValueConst options_obj;\n    FILE *f;\n    BOOL binary_flag, full_flag;\n    \n    url = JS_ToCString(ctx, argv[0]);\n    if (!url)\n        return JS_EXCEPTION;\n    \n    binary_flag = FALSE;\n    full_flag = FALSE;\n    \n    if (argc >= 2) {\n        options_obj = argv[1];\n\n        if (get_bool_option(ctx, &binary_flag, options_obj, \"binary\"))\n            goto fail_obj;\n\n        if (get_bool_option(ctx, &full_flag, options_obj, \"full\")) {\n        fail_obj:\n            JS_FreeCString(ctx, url);\n            return JS_EXCEPTION;\n        }\n    }\n    \n    js_std_dbuf_init(ctx, &cmd_buf);\n    dbuf_printf(&cmd_buf, \"%s ''\", URL_GET_PROGRAM);\n    len = strlen(url);\n    for(i = 0; i < len; i++) {\n        c = url[i];\n        if (c == '\\'' || c == '\\\\')\n            dbuf_putc(&cmd_buf, '\\\\');\n        dbuf_putc(&cmd_buf, c);\n    }\n    JS_FreeCString(ctx, url);\n    dbuf_putstr(&cmd_buf, \"''\");\n    dbuf_putc(&cmd_buf, '\\0');\n    if (dbuf_error(&cmd_buf)) {\n        dbuf_free(&cmd_buf);\n        return JS_EXCEPTION;\n    }\n    //    printf(\"%s\\n\", (char *)cmd_buf.buf);\n    f = popen((char *)cmd_buf.buf, \"r\");\n    dbuf_free(&cmd_buf);\n    if (!f) {\n        return JS_ThrowTypeError(ctx, \"could not start curl\");\n    }\n\n    js_std_dbuf_init(ctx, data_buf);\n    js_std_dbuf_init(ctx, header_buf);\n    \n    buf = js_malloc(ctx, URL_GET_BUF_SIZE);\n    if (!buf)\n        goto fail;\n\n    /* get the HTTP status */\n    if (http_get_header_line(f, buf, URL_GET_BUF_SIZE, NULL) < 0) {\n        status = 0;\n        goto bad_header;\n    }\n    status = http_get_status(buf);\n    if (!full_flag && !(status >= 200 && status <= 299)) {\n        goto bad_header;\n    }\n    \n    /* wait until there is an empty line */\n    for(;;) {\n        if (http_get_header_line(f, buf, URL_GET_BUF_SIZE, header_buf) < 0) {\n        bad_header:\n            response = JS_NULL;\n            goto done;\n        }\n        if (!strcmp(buf, \"\\r\\n\"))\n            break;\n    }\n    if (dbuf_error(header_buf))\n        goto fail;\n    header_buf->size -= 2; /* remove the trailing CRLF */\n\n    /* download the data */\n    for(;;) {\n        len = fread(buf, 1, URL_GET_BUF_SIZE, f);\n        if (len == 0)\n            break;\n        dbuf_put(data_buf, (uint8_t *)buf, len);\n    }\n    if (dbuf_error(data_buf))\n        goto fail;\n    if (binary_flag) {\n        response = JS_NewArrayBufferCopy(ctx,\n                                         data_buf->buf, data_buf->size);\n    } else {\n        response = JS_NewStringLen(ctx, (char *)data_buf->buf, data_buf->size);\n    }\n    if (JS_IsException(response))\n        goto fail;\n done:\n    js_free(ctx, buf);\n    buf = NULL;\n    pclose(f);\n    f = NULL;\n    dbuf_free(data_buf);\n    data_buf = NULL;\n\n    if (full_flag) {\n        ret_obj = JS_NewObject(ctx);\n        if (JS_IsException(ret_obj))\n            goto fail;\n        JS_DefinePropertyValueStr(ctx, ret_obj, \"response\",\n                                  response,\n                                  JS_PROP_C_W_E);\n        if (!JS_IsNull(response)) {\n            JS_DefinePropertyValueStr(ctx, ret_obj, \"responseHeaders\",\n                                      JS_NewStringLen(ctx, (char *)header_buf->buf,\n                                                      header_buf->size),\n                                      JS_PROP_C_W_E);\n            JS_DefinePropertyValueStr(ctx, ret_obj, \"status\",\n                                      JS_NewInt32(ctx, status),\n                                      JS_PROP_C_W_E);\n        }\n    } else {\n        ret_obj = response;\n    }\n    dbuf_free(header_buf);\n    return ret_obj;\n fail:\n    if (f)\n        pclose(f);\n    js_free(ctx, buf);\n    if (data_buf)\n        dbuf_free(data_buf);\n    if (header_buf)\n        dbuf_free(header_buf);\n    JS_FreeValue(ctx, response);\n    return JS_EXCEPTION;\n}\n\nstatic JSClassDef js_std_file_class = {\n    \"FILE\",\n    .finalizer = js_std_file_finalizer,\n}; \n\nstatic const JSCFunctionListEntry js_std_error_props[] = {\n    /* various errno values */\n#define DEF(x) JS_PROP_INT32_DEF(#x, x, JS_PROP_CONFIGURABLE )\n    DEF(EINVAL),\n    DEF(EIO),\n    DEF(EACCES),\n    DEF(EEXIST),\n    DEF(ENOSPC),\n    DEF(ENOSYS),\n    DEF(EBUSY),\n    DEF(ENOENT),\n    DEF(EPERM),\n    DEF(EPIPE),\n    DEF(EBADF),\n#undef DEF\n};\n\nstatic const JSCFunctionListEntry js_std_funcs[] = {\n    JS_CFUNC_DEF(\"exit\", 1, js_std_exit ),\n    JS_CFUNC_DEF(\"gc\", 0, js_std_gc ),\n    JS_CFUNC_DEF(\"evalScript\", 1, js_evalScript ),\n    JS_CFUNC_DEF(\"loadScript\", 1, js_loadScript ),\n    JS_CFUNC_DEF(\"getenv\", 1, js_std_getenv ),\n    JS_CFUNC_DEF(\"setenv\", 1, js_std_setenv ),\n    JS_CFUNC_DEF(\"unsetenv\", 1, js_std_unsetenv ),\n    JS_CFUNC_DEF(\"getenviron\", 1, js_std_getenviron ),\n    JS_CFUNC_DEF(\"urlGet\", 1, js_std_urlGet ),\n    JS_CFUNC_DEF(\"loadFile\", 1, js_std_loadFile ),\n    JS_CFUNC_DEF(\"strerror\", 1, js_std_strerror ),\n    JS_CFUNC_DEF(\"parseExtJSON\", 1, js_std_parseExtJSON ),\n    \n    /* FILE I/O */\n    JS_CFUNC_DEF(\"open\", 2, js_std_open ),\n    JS_CFUNC_DEF(\"popen\", 2, js_std_popen ),\n    JS_CFUNC_DEF(\"fdopen\", 2, js_std_fdopen ),\n    JS_CFUNC_DEF(\"tmpfile\", 0, js_std_tmpfile ),\n    JS_CFUNC_MAGIC_DEF(\"puts\", 1, js_std_file_puts, 0 ),\n    JS_CFUNC_DEF(\"printf\", 1, js_std_printf ),\n    JS_CFUNC_DEF(\"sprintf\", 1, js_std_sprintf ),\n    JS_PROP_INT32_DEF(\"SEEK_SET\", SEEK_SET, JS_PROP_CONFIGURABLE ),\n    JS_PROP_INT32_DEF(\"SEEK_CUR\", SEEK_CUR, JS_PROP_CONFIGURABLE ),\n    JS_PROP_INT32_DEF(\"SEEK_END\", SEEK_END, JS_PROP_CONFIGURABLE ),\n    JS_OBJECT_DEF(\"Error\", js_std_error_props, countof(js_std_error_props), JS_PROP_CONFIGURABLE),\n};\n    \nstatic const JSCFunctionListEntry js_std_file_proto_funcs[] = {\n    JS_CFUNC_DEF(\"close\", 0, js_std_file_close ),\n    JS_CFUNC_MAGIC_DEF(\"puts\", 1, js_std_file_puts, 1 ),\n    JS_CFUNC_DEF(\"printf\", 1, js_std_file_printf ),\n    JS_CFUNC_DEF(\"flush\", 0, js_std_file_flush ),\n    JS_CFUNC_MAGIC_DEF(\"tell\", 0, js_std_file_tell, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"tello\", 0, js_std_file_tell, 1 ),\n    JS_CFUNC_DEF(\"seek\", 2, js_std_file_seek ),\n    JS_CFUNC_DEF(\"eof\", 0, js_std_file_eof ),\n    JS_CFUNC_DEF(\"fileno\", 0, js_std_file_fileno ),\n    JS_CFUNC_DEF(\"error\", 0, js_std_file_error ),\n    JS_CFUNC_DEF(\"clearerr\", 0, js_std_file_clearerr ),\n    JS_CFUNC_MAGIC_DEF(\"read\", 3, js_std_file_read_write, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"write\", 3, js_std_file_read_write, 1 ),\n    JS_CFUNC_DEF(\"getline\", 0, js_std_file_getline ),\n    JS_CFUNC_DEF(\"readAsString\", 0, js_std_file_readAsString ),\n    JS_CFUNC_DEF(\"getByte\", 0, js_std_file_getByte ),\n    JS_CFUNC_DEF(\"putByte\", 1, js_std_file_putByte ),\n    /* setvbuf, ...  */\n};\n\nstatic int js_std_init(JSContext *ctx, JSModuleDef *m)\n{\n    JSValue proto;\n    \n    /* FILE class */\n    /* the class ID is created once */\n    JS_NewClassID(&js_std_file_class_id);\n    /* the class is created once per runtime */\n    JS_NewClass(JS_GetRuntime(ctx), js_std_file_class_id, &js_std_file_class);\n    proto = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, proto, js_std_file_proto_funcs,\n                               countof(js_std_file_proto_funcs));\n    JS_SetClassProto(ctx, js_std_file_class_id, proto);\n\n    JS_SetModuleExportList(ctx, m, js_std_funcs,\n                           countof(js_std_funcs));\n    JS_SetModuleExport(ctx, m, \"in\", js_new_std_file(ctx, stdin, FALSE, FALSE));\n    JS_SetModuleExport(ctx, m, \"out\", js_new_std_file(ctx, stdout, FALSE, FALSE));\n    JS_SetModuleExport(ctx, m, \"err\", js_new_std_file(ctx, stderr, FALSE, FALSE));\n    return 0;\n}\n\nJSModuleDef *js_init_module_std(JSContext *ctx, const char *module_name)\n{\n    JSModuleDef *m;\n    m = JS_NewCModule(ctx, module_name, js_std_init);\n    if (!m)\n        return NULL;\n    JS_AddModuleExportList(ctx, m, js_std_funcs, countof(js_std_funcs));\n    JS_AddModuleExport(ctx, m, \"in\");\n    JS_AddModuleExport(ctx, m, \"out\");\n    JS_AddModuleExport(ctx, m, \"err\");\n    return m;\n}\n\n/**********************************************************/\n/* 'os' object */\n\nstatic JSValue js_os_open(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv)\n{\n    const char *filename;\n    int flags, mode, ret;\n\n    filename = JS_ToCString(ctx, argv[0]);\n    if (!filename)\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &flags, argv[1]))\n        goto fail;\n    if (argc >= 3 && !JS_IsUndefined(argv[2])) {\n        if (JS_ToInt32(ctx, &mode, argv[2])) {\n        fail:\n            JS_FreeCString(ctx, filename);\n            return JS_EXCEPTION;\n        }\n    } else {\n        mode = 0666;\n    }\n#if defined(_WIN32)\n    /* force binary mode by default */\n    if (!(flags & O_TEXT))\n        flags |= O_BINARY;\n#endif\n    ret = js_get_errno(open(filename, flags, mode));\n    JS_FreeCString(ctx, filename);\n    return JS_NewInt32(ctx, ret);\n}\n\nstatic JSValue js_os_close(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    int fd, ret;\n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    ret = js_get_errno(close(fd));\n    return JS_NewInt32(ctx, ret);\n}\n\nstatic JSValue js_os_seek(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv)\n{\n    int fd, whence;\n    int64_t pos, ret;\n    BOOL is_bigint;\n    \n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    is_bigint = JS_IsBigInt(ctx, argv[1]);\n    if (JS_ToInt64Ext(ctx, &pos, argv[1]))\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &whence, argv[2]))\n        return JS_EXCEPTION;\n    ret = lseek(fd, pos, whence);\n    if (ret == -1)\n        ret = -errno;\n    if (is_bigint)\n        return JS_NewBigInt64(ctx, ret);\n    else\n        return JS_NewInt64(ctx, ret);\n}\n\nstatic JSValue js_os_read_write(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv, int magic)\n{\n    int fd;\n    uint64_t pos, len;\n    size_t size;\n    ssize_t ret;\n    uint8_t *buf;\n    \n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    if (JS_ToIndex(ctx, &pos, argv[2]))\n        return JS_EXCEPTION;\n    if (JS_ToIndex(ctx, &len, argv[3]))\n        return JS_EXCEPTION;\n    buf = JS_GetArrayBuffer(ctx, &size, argv[1]);\n    if (!buf)\n        return JS_EXCEPTION;\n    if (pos + len > size)\n        return JS_ThrowRangeError(ctx, \"read/write array buffer overflow\");\n    if (magic)\n        ret = js_get_errno(write(fd, buf + pos, len));\n    else\n        ret = js_get_errno(read(fd, buf + pos, len));\n    return JS_NewInt64(ctx, ret);\n}\n\nstatic JSValue js_os_isatty(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv)\n{\n    int fd;\n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    return JS_NewBool(ctx, (isatty(fd) != 0));\n}\n\n#if defined(_WIN32)\nstatic JSValue js_os_ttyGetWinSize(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    int fd;\n    HANDLE handle;\n    CONSOLE_SCREEN_BUFFER_INFO info;\n    JSValue obj;\n\n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    handle = (HANDLE)_get_osfhandle(fd);\n    \n    if (!GetConsoleScreenBufferInfo(handle, &info))\n        return JS_NULL;\n    obj = JS_NewArray(ctx);\n    if (JS_IsException(obj))\n        return obj;\n    JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, info.dwSize.X), JS_PROP_C_W_E);\n    JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, info.dwSize.Y), JS_PROP_C_W_E);\n    return obj;\n}\n\n/* Windows 10 built-in VT100 emulation */\n#define __ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004\n#define __ENABLE_VIRTUAL_TERMINAL_INPUT 0x0200\n\nstatic JSValue js_os_ttySetRaw(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    int fd;\n    HANDLE handle;\n\n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    handle = (HANDLE)_get_osfhandle(fd);\n    SetConsoleMode(handle, ENABLE_WINDOW_INPUT | __ENABLE_VIRTUAL_TERMINAL_INPUT);\n    _setmode(fd, _O_BINARY);\n    if (fd == 0) {\n        handle = (HANDLE)_get_osfhandle(1); /* corresponding output */\n        SetConsoleMode(handle, ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT | __ENABLE_VIRTUAL_TERMINAL_PROCESSING);\n    }\n    return JS_UNDEFINED;\n}\n#else\nstatic JSValue js_os_ttyGetWinSize(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    int fd;\n    struct winsize ws;\n    JSValue obj;\n    \n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    if (ioctl(fd, TIOCGWINSZ, &ws) == 0 &&\n        ws.ws_col >= 4 && ws.ws_row >= 4) {\n        obj = JS_NewArray(ctx);\n        if (JS_IsException(obj))\n            return obj;\n        JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, ws.ws_col), JS_PROP_C_W_E);\n        JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, ws.ws_row), JS_PROP_C_W_E);\n        return obj;\n    } else {\n        return JS_NULL;\n    }\n}\n\nstatic struct termios oldtty;\n\nstatic void term_exit(void)\n{\n    tcsetattr(0, TCSANOW, &oldtty);\n}\n\n/* XXX: should add a way to go back to normal mode */\nstatic JSValue js_os_ttySetRaw(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    struct termios tty;\n    int fd;\n    \n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    \n    memset(&tty, 0, sizeof(tty));\n    tcgetattr(fd, &tty);\n    oldtty = tty;\n\n    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP\n                          |INLCR|IGNCR|ICRNL|IXON);\n    tty.c_oflag |= OPOST;\n    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);\n    tty.c_cflag &= ~(CSIZE|PARENB);\n    tty.c_cflag |= CS8;\n    tty.c_cc[VMIN] = 1;\n    tty.c_cc[VTIME] = 0;\n\n    tcsetattr(fd, TCSANOW, &tty);\n\n    atexit(term_exit);\n    return JS_UNDEFINED;\n}\n\n#endif /* !_WIN32 */\n\nstatic JSValue js_os_remove(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    const char *filename;\n    int ret;\n    \n    filename = JS_ToCString(ctx, argv[0]);\n    if (!filename)\n        return JS_EXCEPTION;\n#if defined(_WIN32)\n    {\n        struct stat st;\n        if (stat(filename, &st) == 0 && S_ISDIR(st.st_mode)) {\n            ret = rmdir(filename);\n        } else {\n            ret = unlink(filename);\n        }\n    }\n#else\n    ret = remove(filename);\n#endif\n    ret = js_get_errno(ret);\n    JS_FreeCString(ctx, filename);\n    return JS_NewInt32(ctx, ret);\n}\n\nstatic JSValue js_os_rename(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv)\n{\n    const char *oldpath, *newpath;\n    int ret;\n    \n    oldpath = JS_ToCString(ctx, argv[0]);\n    if (!oldpath)\n        return JS_EXCEPTION;\n    newpath = JS_ToCString(ctx, argv[1]);\n    if (!newpath) {\n        JS_FreeCString(ctx, oldpath);\n        return JS_EXCEPTION;\n    }\n    ret = js_get_errno(rename(oldpath, newpath));\n    JS_FreeCString(ctx, oldpath);\n    JS_FreeCString(ctx, newpath);\n    return JS_NewInt32(ctx, ret);\n}\n\nstatic BOOL is_main_thread(JSRuntime *rt)\n{\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    return !ts->recv_pipe;\n}\n\nstatic JSOSRWHandler *find_rh(JSThreadState *ts, int fd)\n{\n    JSOSRWHandler *rh;\n    struct list_head *el;\n\n    list_for_each(el, &ts->os_rw_handlers) {\n        rh = list_entry(el, JSOSRWHandler, link);\n        if (rh->fd == fd)\n            return rh;\n    }\n    return NULL;\n}\n\nstatic void free_rw_handler(JSRuntime *rt, JSOSRWHandler *rh)\n{\n    int i;\n    list_del(&rh->link);\n    for(i = 0; i < 2; i++) {\n        JS_FreeValueRT(rt, rh->rw_func[i]);\n    }\n    js_free_rt(rt, rh);\n}\n\nstatic JSValue js_os_setReadHandler(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv, int magic)\n{\n    JSRuntime *rt = JS_GetRuntime(ctx);\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    JSOSRWHandler *rh;\n    int fd;\n    JSValueConst func;\n    \n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    func = argv[1];\n    if (JS_IsNull(func)) {\n        rh = find_rh(ts, fd);\n        if (rh) {\n            JS_FreeValue(ctx, rh->rw_func[magic]);\n            rh->rw_func[magic] = JS_NULL;\n            if (JS_IsNull(rh->rw_func[0]) &&\n                JS_IsNull(rh->rw_func[1])) {\n                /* remove the entry */\n                free_rw_handler(JS_GetRuntime(ctx), rh);\n            }\n        }\n    } else {\n        if (!JS_IsFunction(ctx, func))\n            return JS_ThrowTypeError(ctx, \"not a function\");\n        rh = find_rh(ts, fd);\n        if (!rh) {\n            rh = js_mallocz(ctx, sizeof(*rh));\n            if (!rh)\n                return JS_EXCEPTION;\n            rh->fd = fd;\n            rh->rw_func[0] = JS_NULL;\n            rh->rw_func[1] = JS_NULL;\n            list_add_tail(&rh->link, &ts->os_rw_handlers);\n        }\n        JS_FreeValue(ctx, rh->rw_func[magic]);\n        rh->rw_func[magic] = JS_DupValue(ctx, func);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSOSSignalHandler *find_sh(JSThreadState *ts, int sig_num)\n{\n    JSOSSignalHandler *sh;\n    struct list_head *el;\n    list_for_each(el, &ts->os_signal_handlers) {\n        sh = list_entry(el, JSOSSignalHandler, link);\n        if (sh->sig_num == sig_num)\n            return sh;\n    }\n    return NULL;\n}\n\nstatic void free_sh(JSRuntime *rt, JSOSSignalHandler *sh)\n{\n    list_del(&sh->link);\n    JS_FreeValueRT(rt, sh->func);\n    js_free_rt(rt, sh);\n}\n\nstatic void os_signal_handler(int sig_num)\n{\n    os_pending_signals |= ((uint64_t)1 << sig_num);\n}\n\n#if defined(_WIN32)\ntypedef void (*sighandler_t)(int sig_num);\n#endif\n\nstatic JSValue js_os_signal(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv)\n{\n    JSRuntime *rt = JS_GetRuntime(ctx);\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    JSOSSignalHandler *sh;\n    uint32_t sig_num;\n    JSValueConst func;\n    sighandler_t handler;\n\n    if (!is_main_thread(rt))\n        return JS_ThrowTypeError(ctx, \"signal handler can only be set in the main thread\");\n    \n    if (JS_ToUint32(ctx, &sig_num, argv[0]))\n        return JS_EXCEPTION;\n    if (sig_num >= 64)\n        return JS_ThrowRangeError(ctx, \"invalid signal number\");\n    func = argv[1];\n    /* func = null: SIG_DFL, func = undefined, SIG_IGN */\n    if (JS_IsNull(func) || JS_IsUndefined(func)) {\n        sh = find_sh(ts, sig_num);\n        if (sh) {\n            free_sh(JS_GetRuntime(ctx), sh);\n        }\n        if (JS_IsNull(func))\n            handler = SIG_DFL;\n        else\n            handler = SIG_IGN;\n        signal(sig_num, handler);\n    } else {\n        if (!JS_IsFunction(ctx, func))\n            return JS_ThrowTypeError(ctx, \"not a function\");\n        sh = find_sh(ts, sig_num);\n        if (!sh) {\n            sh = js_mallocz(ctx, sizeof(*sh));\n            if (!sh)\n                return JS_EXCEPTION;\n            sh->sig_num = sig_num;\n            list_add_tail(&sh->link, &ts->os_signal_handlers);\n        }\n        JS_FreeValue(ctx, sh->func);\n        sh->func = JS_DupValue(ctx, func);\n        signal(sig_num, os_signal_handler);\n    }\n    return JS_UNDEFINED;\n}\n\n#if defined(__linux__) || defined(__APPLE__)\nstatic int64_t get_time_ms(void)\n{\n    struct timespec ts;\n    clock_gettime(CLOCK_MONOTONIC, &ts);\n    return (uint64_t)ts.tv_sec * 1000 + (ts.tv_nsec / 1000000);\n}\n#else\n/* more portable, but does not work if the date is updated */\nstatic int64_t get_time_ms(void)\n{\n    struct timeval tv;\n    gettimeofday(&tv, NULL);\n    return (int64_t)tv.tv_sec * 1000 + (tv.tv_usec / 1000);\n}\n#endif\n\nstatic void unlink_timer(JSRuntime *rt, JSOSTimer *th)\n{\n    if (th->link.prev) {\n        list_del(&th->link);\n        th->link.prev = th->link.next = NULL;\n    }\n}\n\nstatic void free_timer(JSRuntime *rt, JSOSTimer *th)\n{\n    JS_FreeValueRT(rt, th->func);\n    js_free_rt(rt, th);\n}\n\nstatic JSClassID js_os_timer_class_id;\n\nstatic void js_os_timer_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSOSTimer *th = JS_GetOpaque(val, js_os_timer_class_id);\n    if (th) {\n        th->has_object = FALSE;\n        if (!th->link.prev)\n            free_timer(rt, th);\n    }\n}\n\nstatic void js_os_timer_mark(JSRuntime *rt, JSValueConst val,\n                             JS_MarkFunc *mark_func)\n{\n    JSOSTimer *th = JS_GetOpaque(val, js_os_timer_class_id);\n    if (th) {\n        JS_MarkValue(rt, th->func, mark_func);\n    }\n}\n\nstatic JSValue js_os_setTimeout(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSRuntime *rt = JS_GetRuntime(ctx);\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    int64_t delay;\n    JSValueConst func;\n    JSOSTimer *th;\n    JSValue obj;\n\n    func = argv[0];\n    if (!JS_IsFunction(ctx, func))\n        return JS_ThrowTypeError(ctx, \"not a function\");\n    if (JS_ToInt64(ctx, &delay, argv[1]))\n        return JS_EXCEPTION;\n    obj = JS_NewObjectClass(ctx, js_os_timer_class_id);\n    if (JS_IsException(obj))\n        return obj;\n    th = js_mallocz(ctx, sizeof(*th));\n    if (!th) {\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    th->has_object = TRUE;\n    th->timeout = get_time_ms() + delay;\n    th->func = JS_DupValue(ctx, func);\n    list_add_tail(&th->link, &ts->os_timers);\n    JS_SetOpaque(obj, th);\n    return obj;\n}\n\nstatic JSValue js_os_clearTimeout(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    JSOSTimer *th = JS_GetOpaque2(ctx, argv[0], js_os_timer_class_id);\n    if (!th)\n        return JS_EXCEPTION;\n    unlink_timer(JS_GetRuntime(ctx), th);\n    return JS_UNDEFINED;\n}\n\nstatic JSClassDef js_os_timer_class = {\n    \"OSTimer\",\n    .finalizer = js_os_timer_finalizer,\n    .gc_mark = js_os_timer_mark,\n}; \n\nstatic void call_handler(JSContext *ctx, JSValueConst func)\n{\n    JSValue ret, func1;\n    /* 'func' might be destroyed when calling itself (if it frees the\n       handler), so must take extra care */\n    func1 = JS_DupValue(ctx, func);\n    ret = JS_Call(ctx, func1, JS_UNDEFINED, 0, NULL);\n    JS_FreeValue(ctx, func1);\n    if (JS_IsException(ret))\n        js_std_dump_error(ctx);\n    JS_FreeValue(ctx, ret);\n}\n\n#if defined(_WIN32)\n\nstatic int js_os_poll(JSContext *ctx)\n{\n    JSRuntime *rt = JS_GetRuntime(ctx);\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    int min_delay, console_fd;\n    int64_t cur_time, delay;\n    JSOSRWHandler *rh;\n    struct list_head *el;\n    \n    /* XXX: handle signals if useful */\n\n    if (list_empty(&ts->os_rw_handlers) && list_empty(&ts->os_timers))\n        return -1; /* no more events */\n    \n    /* XXX: only timers and basic console input are supported */\n    if (!list_empty(&ts->os_timers)) {\n        cur_time = get_time_ms();\n        min_delay = 10000;\n        list_for_each(el, &ts->os_timers) {\n            JSOSTimer *th = list_entry(el, JSOSTimer, link);\n            delay = th->timeout - cur_time;\n            if (delay <= 0) {\n                JSValue func;\n                /* the timer expired */\n                func = th->func;\n                th->func = JS_UNDEFINED;\n                unlink_timer(rt, th);\n                if (!th->has_object)\n                    free_timer(rt, th);\n                call_handler(ctx, func);\n                JS_FreeValue(ctx, func);\n                return 0;\n            } else if (delay < min_delay) {\n                min_delay = delay;\n            }\n        }\n    } else {\n        min_delay = -1;\n    }\n\n    console_fd = -1;\n    list_for_each(el, &ts->os_rw_handlers) {\n        rh = list_entry(el, JSOSRWHandler, link);\n        if (rh->fd == 0 && !JS_IsNull(rh->rw_func[0])) {\n            console_fd = rh->fd;\n            break;\n        }\n    }\n\n    if (console_fd >= 0) {\n        DWORD ti, ret;\n        HANDLE handle;\n        if (min_delay == -1)\n            ti = INFINITE;\n        else\n            ti = min_delay;\n        handle = (HANDLE)_get_osfhandle(console_fd);\n        ret = WaitForSingleObject(handle, ti);\n        if (ret == WAIT_OBJECT_0) {\n            list_for_each(el, &ts->os_rw_handlers) {\n                rh = list_entry(el, JSOSRWHandler, link);\n                if (rh->fd == console_fd && !JS_IsNull(rh->rw_func[0])) {\n                    call_handler(ctx, rh->rw_func[0]);\n                    /* must stop because the list may have been modified */\n                    break;\n                }\n            }\n        }\n    } else {\n        Sleep(min_delay);\n    }\n    return 0;\n}\n#else\n\n#ifdef USE_WORKER\n\nstatic void js_free_message(JSWorkerMessage *msg);\n\n/* return 1 if a message was handled, 0 if no message */\nstatic int handle_posted_message(JSRuntime *rt, JSContext *ctx,\n                                 JSWorkerMessageHandler *port)\n{\n    JSWorkerMessagePipe *ps = port->recv_pipe;\n    int ret;\n    struct list_head *el;\n    JSWorkerMessage *msg;\n    JSValue obj, data_obj, func, retval;\n    \n    pthread_mutex_lock(&ps->mutex);\n    if (!list_empty(&ps->msg_queue)) {\n        el = ps->msg_queue.next;\n        msg = list_entry(el, JSWorkerMessage, link);\n\n        /* remove the message from the queue */\n        list_del(&msg->link);\n\n        if (list_empty(&ps->msg_queue)) {\n            uint8_t buf[16];\n            int ret;\n            for(;;) {\n                ret = read(ps->read_fd, buf, sizeof(buf));\n                if (ret >= 0)\n                    break;\n                if (errno != EAGAIN && errno != EINTR)\n                    break;\n            }\n        }\n\n        pthread_mutex_unlock(&ps->mutex);\n\n        data_obj = JS_ReadObject(ctx, msg->data, msg->data_len,\n                                 JS_READ_OBJ_SAB | JS_READ_OBJ_REFERENCE);\n\n        js_free_message(msg);\n        \n        if (JS_IsException(data_obj))\n            goto fail;\n        obj = JS_NewObject(ctx);\n        if (JS_IsException(obj)) {\n            JS_FreeValue(ctx, data_obj);\n            goto fail;\n        }\n        JS_DefinePropertyValueStr(ctx, obj, \"data\", data_obj, JS_PROP_C_W_E);\n\n        /* 'func' might be destroyed when calling itself (if it frees the\n           handler), so must take extra care */\n        func = JS_DupValue(ctx, port->on_message_func);\n        retval = JS_Call(ctx, func, JS_UNDEFINED, 1, (JSValueConst *)&obj);\n        JS_FreeValue(ctx, obj);\n        JS_FreeValue(ctx, func);\n        if (JS_IsException(retval)) {\n        fail:\n            js_std_dump_error(ctx);\n        } else {\n            JS_FreeValue(ctx, retval);\n        }\n        ret = 1;\n    } else {\n        pthread_mutex_unlock(&ps->mutex);\n        ret = 0;\n    }\n    return ret;\n}\n#else\nstatic int handle_posted_message(JSRuntime *rt, JSContext *ctx,\n                                 JSWorkerMessageHandler *port)\n{\n    return 0;\n}\n#endif\n\nstatic int js_os_poll(JSContext *ctx)\n{\n    JSRuntime *rt = JS_GetRuntime(ctx);\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    int ret, fd_max, min_delay;\n    int64_t cur_time, delay;\n    fd_set rfds, wfds;\n    JSOSRWHandler *rh;\n    struct list_head *el;\n    struct timeval tv, *tvp;\n\n    /* only check signals in the main thread */\n    if (!ts->recv_pipe &&\n        unlikely(os_pending_signals != 0)) {\n        JSOSSignalHandler *sh;\n        uint64_t mask;\n        \n        list_for_each(el, &ts->os_signal_handlers) {\n            sh = list_entry(el, JSOSSignalHandler, link);\n            mask = (uint64_t)1 << sh->sig_num;\n            if (os_pending_signals & mask) {\n                os_pending_signals &= ~mask;\n                call_handler(ctx, sh->func);\n                return 0;\n            }\n        }\n    }\n\n    if (list_empty(&ts->os_rw_handlers) && list_empty(&ts->os_timers) &&\n        list_empty(&ts->port_list))\n        return -1; /* no more events */\n    \n    if (!list_empty(&ts->os_timers)) {\n        cur_time = get_time_ms();\n        min_delay = 10000;\n        list_for_each(el, &ts->os_timers) {\n            JSOSTimer *th = list_entry(el, JSOSTimer, link);\n            delay = th->timeout - cur_time;\n            if (delay <= 0) {\n                JSValue func;\n                /* the timer expired */\n                func = th->func;\n                th->func = JS_UNDEFINED;\n                unlink_timer(rt, th);\n                if (!th->has_object)\n                    free_timer(rt, th);\n                call_handler(ctx, func);\n                JS_FreeValue(ctx, func);\n                return 0;\n            } else if (delay < min_delay) {\n                min_delay = delay;\n            }\n        }\n        tv.tv_sec = min_delay / 1000;\n        tv.tv_usec = (min_delay % 1000) * 1000;\n        tvp = &tv;\n    } else {\n        tvp = NULL;\n    }\n    \n    FD_ZERO(&rfds);\n    FD_ZERO(&wfds);\n    fd_max = -1;\n    list_for_each(el, &ts->os_rw_handlers) {\n        rh = list_entry(el, JSOSRWHandler, link);\n        fd_max = max_int(fd_max, rh->fd);\n        if (!JS_IsNull(rh->rw_func[0]))\n            FD_SET(rh->fd, &rfds);\n        if (!JS_IsNull(rh->rw_func[1]))\n            FD_SET(rh->fd, &wfds);\n    }\n\n    list_for_each(el, &ts->port_list) {\n        JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link);\n        if (!JS_IsNull(port->on_message_func)) {\n            JSWorkerMessagePipe *ps = port->recv_pipe;\n            fd_max = max_int(fd_max, ps->read_fd);\n            FD_SET(ps->read_fd, &rfds);\n        }\n    }\n\n    ret = select(fd_max + 1, &rfds, &wfds, NULL, tvp);\n    if (ret > 0) {\n        list_for_each(el, &ts->os_rw_handlers) {\n            rh = list_entry(el, JSOSRWHandler, link);\n            if (!JS_IsNull(rh->rw_func[0]) &&\n                FD_ISSET(rh->fd, &rfds)) {\n                call_handler(ctx, rh->rw_func[0]);\n                /* must stop because the list may have been modified */\n                goto done;\n            }\n            if (!JS_IsNull(rh->rw_func[1]) &&\n                FD_ISSET(rh->fd, &wfds)) {\n                call_handler(ctx, rh->rw_func[1]);\n                /* must stop because the list may have been modified */\n                goto done;\n            }\n        }\n\n        list_for_each(el, &ts->port_list) {\n            JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link);\n            if (!JS_IsNull(port->on_message_func)) {\n                JSWorkerMessagePipe *ps = port->recv_pipe;\n                if (FD_ISSET(ps->read_fd, &rfds)) {\n                    if (handle_posted_message(rt, ctx, port))\n                        goto done;\n                }\n            }\n        }\n    }\n    done:\n    return 0;\n}\n#endif /* !_WIN32 */\n\nstatic JSValue make_obj_error(JSContext *ctx,\n                              JSValue obj,\n                              int err)\n{\n    JSValue arr;\n    if (JS_IsException(obj))\n        return obj;\n    arr = JS_NewArray(ctx);\n    if (JS_IsException(arr))\n        return JS_EXCEPTION;\n    JS_DefinePropertyValueUint32(ctx, arr, 0, obj,\n                                 JS_PROP_C_W_E);\n    JS_DefinePropertyValueUint32(ctx, arr, 1, JS_NewInt32(ctx, err),\n                                 JS_PROP_C_W_E);\n    return arr;\n}\n\nstatic JSValue make_string_error(JSContext *ctx,\n                                 const char *buf,\n                                 int err)\n{\n    return make_obj_error(ctx, JS_NewString(ctx, buf), err);\n}\n\n/* return [cwd, errorcode] */\nstatic JSValue js_os_getcwd(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv)\n{\n    char buf[PATH_MAX];\n    int err;\n    \n    if (!getcwd(buf, sizeof(buf))) {\n        buf[0] = '\\0';\n        err = errno;\n    } else {\n        err = 0;\n    }\n    return make_string_error(ctx, buf, err);\n}\n\nstatic JSValue js_os_chdir(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    const char *target;\n    int err;\n\n    target = JS_ToCString(ctx, argv[0]);\n    if (!target)\n        return JS_EXCEPTION;\n    err = js_get_errno(chdir(target));\n    JS_FreeCString(ctx, target);\n    return JS_NewInt32(ctx, err);\n}\n\nstatic JSValue js_os_mkdir(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    int mode, ret;\n    const char *path;\n    \n    if (argc >= 2) {\n        if (JS_ToInt32(ctx, &mode, argv[1]))\n            return JS_EXCEPTION;\n    } else {\n        mode = 0777;\n    }\n    path = JS_ToCString(ctx, argv[0]);\n    if (!path)\n        return JS_EXCEPTION;\n#if defined(_WIN32)\n    (void)mode;\n    ret = js_get_errno(mkdir(path));\n#else\n    ret = js_get_errno(mkdir(path, mode));\n#endif\n    JS_FreeCString(ctx, path);\n    return JS_NewInt32(ctx, ret);\n}\n\n/* return [array, errorcode] */\nstatic JSValue js_os_readdir(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    const char *path;\n    DIR *f;\n    struct dirent *d;\n    JSValue obj;\n    int err;\n    uint32_t len;\n    \n    path = JS_ToCString(ctx, argv[0]);\n    if (!path)\n        return JS_EXCEPTION;\n    obj = JS_NewArray(ctx);\n    if (JS_IsException(obj)) {\n        JS_FreeCString(ctx, path);\n        return JS_EXCEPTION;\n    }\n    f = opendir(path);\n    if (!f)\n        err = errno;\n    else\n        err = 0;\n    JS_FreeCString(ctx, path);\n    if (!f)\n        goto done;\n    len = 0;\n    for(;;) {\n        errno = 0;\n        d = readdir(f);\n        if (!d) {\n            err = errno;\n            break;\n        }\n        JS_DefinePropertyValueUint32(ctx, obj, len++,\n                                     JS_NewString(ctx, d->d_name),\n                                     JS_PROP_C_W_E);\n    }\n    closedir(f);\n done:\n    return make_obj_error(ctx, obj, err);\n}\n\n#if !defined(_WIN32)\nstatic int64_t timespec_to_ms(const struct timespec *tv)\n{\n    return (int64_t)tv->tv_sec * 1000 + (tv->tv_nsec / 1000000);\n}\n#endif\n\n/* return [obj, errcode] */\nstatic JSValue js_os_stat(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv, int is_lstat)\n{\n    const char *path;\n    int err, res;\n    struct stat st;\n    JSValue obj;\n\n    path = JS_ToCString(ctx, argv[0]);\n    if (!path)\n        return JS_EXCEPTION;\n#if defined(_WIN32)\n    res = stat(path, &st);\n#else\n    if (is_lstat)\n        res = lstat(path, &st);\n    else\n        res = stat(path, &st);\n#endif\n    JS_FreeCString(ctx, path);\n    if (res < 0) {\n        err = errno;\n        obj = JS_NULL;\n    } else {\n        err = 0;\n        obj = JS_NewObject(ctx);\n        if (JS_IsException(obj))\n            return JS_EXCEPTION;\n        JS_DefinePropertyValueStr(ctx, obj, \"dev\",\n                                  JS_NewInt64(ctx, st.st_dev),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"ino\",\n                                  JS_NewInt64(ctx, st.st_ino),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"mode\",\n                                  JS_NewInt32(ctx, st.st_mode),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"nlink\",\n                                  JS_NewInt64(ctx, st.st_nlink),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"uid\",\n                                  JS_NewInt64(ctx, st.st_uid),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"gid\",\n                                  JS_NewInt64(ctx, st.st_gid),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"rdev\",\n                                  JS_NewInt64(ctx, st.st_rdev),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"size\",\n                                  JS_NewInt64(ctx, st.st_size),\n                                  JS_PROP_C_W_E);\n#if !defined(_WIN32)\n        JS_DefinePropertyValueStr(ctx, obj, \"blocks\",\n                                  JS_NewInt64(ctx, st.st_blocks),\n                                  JS_PROP_C_W_E);\n#endif\n#if defined(_WIN32)\n        JS_DefinePropertyValueStr(ctx, obj, \"atime\",\n                                  JS_NewInt64(ctx, (int64_t)st.st_atime * 1000),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"mtime\",\n                                  JS_NewInt64(ctx, (int64_t)st.st_mtime * 1000),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"ctime\",\n                                  JS_NewInt64(ctx, (int64_t)st.st_ctime * 1000),\n                                  JS_PROP_C_W_E);\n#elif defined(__APPLE__)\n        JS_DefinePropertyValueStr(ctx, obj, \"atime\",\n                                  JS_NewInt64(ctx, timespec_to_ms(&st.st_atimespec)),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"mtime\",\n                                  JS_NewInt64(ctx, timespec_to_ms(&st.st_mtimespec)),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"ctime\",\n                                  JS_NewInt64(ctx, timespec_to_ms(&st.st_ctimespec)),\n                                  JS_PROP_C_W_E);\n#else\n        JS_DefinePropertyValueStr(ctx, obj, \"atime\",\n                                  JS_NewInt64(ctx, timespec_to_ms(&st.st_atim)),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"mtime\",\n                                  JS_NewInt64(ctx, timespec_to_ms(&st.st_mtim)),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"ctime\",\n                                  JS_NewInt64(ctx, timespec_to_ms(&st.st_ctim)),\n                                  JS_PROP_C_W_E);\n#endif\n    }\n    return make_obj_error(ctx, obj, err);\n}\n\n#if !defined(_WIN32)\nstatic void ms_to_timeval(struct timeval *tv, uint64_t v)\n{\n    tv->tv_sec = v / 1000;\n    tv->tv_usec = (v % 1000) * 1000;\n}\n#endif\n\nstatic JSValue js_os_utimes(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv)\n{\n    const char *path;\n    int64_t atime, mtime;\n    int ret;\n    \n    if (JS_ToInt64(ctx, &atime, argv[1]))\n        return JS_EXCEPTION;\n    if (JS_ToInt64(ctx, &mtime, argv[2]))\n        return JS_EXCEPTION;\n    path = JS_ToCString(ctx, argv[0]);\n    if (!path)\n        return JS_EXCEPTION;\n#if defined(_WIN32)\n    {\n        struct _utimbuf times;\n        times.actime = atime / 1000;\n        times.modtime = mtime / 1000;\n        ret = js_get_errno(_utime(path, &times));\n    }\n#else\n    {\n        struct timeval times[2];\n        ms_to_timeval(&times[0], atime);\n        ms_to_timeval(&times[1], mtime);\n        ret = js_get_errno(utimes(path, times));\n    }\n#endif\n    JS_FreeCString(ctx, path);\n    return JS_NewInt32(ctx, ret);\n}\n\n/* sleep(delay_ms) */\nstatic JSValue js_os_sleep(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv)\n{\n    int64_t delay;\n    int ret;\n    \n    if (JS_ToInt64(ctx, &delay, argv[0]))\n        return JS_EXCEPTION;\n    if (delay < 0)\n        delay = 0;\n#if defined(_WIN32)\n    {\n        if (delay > INT32_MAX)\n            delay = INT32_MAX;\n        Sleep(delay);\n        ret = 0;\n    }\n#else\n    {\n        struct timespec ts;\n\n        ts.tv_sec = delay / 1000;\n        ts.tv_nsec = (delay % 1000) * 1000000;\n        ret = js_get_errno(nanosleep(&ts, NULL));\n    }\n#endif\n    return JS_NewInt32(ctx, ret);\n}\n\n#if defined(_WIN32)\nstatic char *realpath(const char *path, char *buf)\n{\n    if (!_fullpath(buf, path, PATH_MAX)) {\n        errno = ENOENT;\n        return NULL;\n    } else {\n        return buf;\n    }\n}\n#endif\n\n/* return [path, errorcode] */\nstatic JSValue js_os_realpath(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    const char *path;\n    char buf[PATH_MAX], *res;\n    int err;\n\n    path = JS_ToCString(ctx, argv[0]);\n    if (!path)\n        return JS_EXCEPTION;\n    res = realpath(path, buf);\n    JS_FreeCString(ctx, path);\n    if (!res) {\n        buf[0] = '\\0';\n        err = errno;\n    } else {\n        err = 0;\n    }\n    return make_string_error(ctx, buf, err);\n}\n\n#if !defined(_WIN32)\nstatic JSValue js_os_symlink(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    const char *target, *linkpath;\n    int err;\n    \n    target = JS_ToCString(ctx, argv[0]);\n    if (!target)\n        return JS_EXCEPTION;\n    linkpath = JS_ToCString(ctx, argv[1]);\n    if (!linkpath) {\n        JS_FreeCString(ctx, target);\n        return JS_EXCEPTION;\n    }\n    err = js_get_errno(symlink(target, linkpath));\n    JS_FreeCString(ctx, target);\n    JS_FreeCString(ctx, linkpath);\n    return JS_NewInt32(ctx, err);\n}\n\n/* return [path, errorcode] */\nstatic JSValue js_os_readlink(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    const char *path;\n    char buf[PATH_MAX];\n    int err;\n    ssize_t res;\n    \n    path = JS_ToCString(ctx, argv[0]);\n    if (!path)\n        return JS_EXCEPTION;\n    res = readlink(path, buf, sizeof(buf) - 1);\n    if (res < 0) {\n        buf[0] = '\\0';\n        err = errno;\n    } else {\n        buf[res] = '\\0';\n        err = 0;\n    }\n    JS_FreeCString(ctx, path);\n    return make_string_error(ctx, buf, err);\n}\n\nstatic char **build_envp(JSContext *ctx, JSValueConst obj)\n{\n    uint32_t len, i;\n    JSPropertyEnum *tab;\n    char **envp, *pair;\n    const char *key, *str;\n    JSValue val;\n    size_t key_len, str_len;\n    \n    if (JS_GetOwnPropertyNames(ctx, &tab, &len, obj,\n                               JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) < 0)\n        return NULL;\n    envp = js_mallocz(ctx, sizeof(envp[0]) * ((size_t)len + 1));\n    if (!envp)\n        goto fail;\n    for(i = 0; i < len; i++) {\n        val = JS_GetProperty(ctx, obj, tab[i].atom);\n        if (JS_IsException(val))\n            goto fail;\n        str = JS_ToCString(ctx, val);\n        JS_FreeValue(ctx, val);\n        if (!str)\n            goto fail;\n        key = JS_AtomToCString(ctx, tab[i].atom);\n        if (!key) {\n            JS_FreeCString(ctx, str);\n            goto fail;\n        }\n        key_len = strlen(key);\n        str_len = strlen(str);\n        pair = js_malloc(ctx, key_len + str_len + 2);\n        if (!pair) {\n            JS_FreeCString(ctx, key);\n            JS_FreeCString(ctx, str);\n            goto fail;\n        }\n        memcpy(pair, key, key_len);\n        pair[key_len] = '=';\n        memcpy(pair + key_len + 1, str, str_len);\n        pair[key_len + 1 + str_len] = '\\0';\n        envp[i] = pair;\n        JS_FreeCString(ctx, key);\n        JS_FreeCString(ctx, str);\n    }\n done:\n    for(i = 0; i < len; i++)\n        JS_FreeAtom(ctx, tab[i].atom);\n    js_free(ctx, tab);\n    return envp;\n fail:\n    if (envp) {\n        for(i = 0; i < len; i++)\n            js_free(ctx, envp[i]);\n        js_free(ctx, envp);\n        envp = NULL;\n    }\n    goto done;\n}\n\n/* execvpe is not available on non GNU systems */\nstatic int my_execvpe(const char *filename, char **argv, char **envp)\n{\n    char *path, *p, *p_next, *p1;\n    char buf[PATH_MAX];\n    size_t filename_len, path_len;\n    BOOL eacces_error;\n    \n    filename_len = strlen(filename);\n    if (filename_len == 0) {\n        errno = ENOENT;\n        return -1;\n    }\n    if (strchr(filename, '/'))\n        return execve(filename, argv, envp);\n    \n    path = getenv(\"PATH\");\n    if (!path)\n        path = (char *)\"/bin:/usr/bin\";\n    eacces_error = FALSE;\n    p = path;\n    for(p = path; p != NULL; p = p_next) {\n        p1 = strchr(p, ':');\n        if (!p1) {\n            p_next = NULL;\n            path_len = strlen(p);\n        } else {\n            p_next = p1 + 1;\n            path_len = p1 - p;\n        }\n        /* path too long */\n        if ((path_len + 1 + filename_len + 1) > PATH_MAX)\n            continue;\n        memcpy(buf, p, path_len);\n        buf[path_len] = '/';\n        memcpy(buf + path_len + 1, filename, filename_len);\n        buf[path_len + 1 + filename_len] = '\\0';\n        \n        execve(buf, argv, envp);\n\n        switch(errno) {\n        case EACCES:\n            eacces_error = TRUE;\n            break;\n        case ENOENT:\n        case ENOTDIR:\n            break;\n        default:\n            return -1;\n        }\n    }\n    if (eacces_error)\n        errno = EACCES;\n    return -1;\n}\n\n/* exec(args[, options]) -> exitcode */\nstatic JSValue js_os_exec(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv)\n{\n    JSValueConst options, args = argv[0];\n    JSValue val, ret_val;\n    const char **exec_argv, *file = NULL, *str, *cwd = NULL;\n    char **envp = environ;\n    uint32_t exec_argc, i;\n    int ret, pid, status;\n    BOOL block_flag = TRUE, use_path = TRUE;\n    static const char *std_name[3] = { \"stdin\", \"stdout\", \"stderr\" };\n    int std_fds[3];\n    uint32_t uid = -1, gid = -1;\n    \n    val = JS_GetPropertyStr(ctx, args, \"length\");\n    if (JS_IsException(val))\n        return JS_EXCEPTION;\n    ret = JS_ToUint32(ctx, &exec_argc, val);\n    JS_FreeValue(ctx, val);\n    if (ret)\n        return JS_EXCEPTION;\n    /* arbitrary limit to avoid overflow */\n    if (exec_argc < 1 || exec_argc > 65535) {\n        return JS_ThrowTypeError(ctx, \"invalid number of arguments\");\n    }\n    exec_argv = js_mallocz(ctx, sizeof(exec_argv[0]) * (exec_argc + 1));\n    if (!exec_argv)\n        return JS_EXCEPTION;\n    for(i = 0; i < exec_argc; i++) {\n        val = JS_GetPropertyUint32(ctx, args, i);\n        if (JS_IsException(val))\n            goto exception;\n        str = JS_ToCString(ctx, val);\n        JS_FreeValue(ctx, val);\n        if (!str)\n            goto exception;\n        exec_argv[i] = str;\n    }\n    exec_argv[exec_argc] = NULL;\n\n    for(i = 0; i < 3; i++)\n        std_fds[i] = i;\n    \n    /* get the options, if any */\n    if (argc >= 2) {\n        options = argv[1];\n\n        if (get_bool_option(ctx, &block_flag, options, \"block\"))\n            goto exception;\n        if (get_bool_option(ctx, &use_path, options, \"usePath\"))\n            goto exception;\n        \n        val = JS_GetPropertyStr(ctx, options, \"file\");\n        if (JS_IsException(val))\n            goto exception;\n        if (!JS_IsUndefined(val)) {\n            file = JS_ToCString(ctx, val);\n            JS_FreeValue(ctx, val);\n            if (!file)\n                goto exception;\n        }\n\n        val = JS_GetPropertyStr(ctx, options, \"cwd\");\n        if (JS_IsException(val))\n            goto exception;\n        if (!JS_IsUndefined(val)) {\n            cwd = JS_ToCString(ctx, val);\n            JS_FreeValue(ctx, val);\n            if (!cwd)\n                goto exception;\n        }\n\n        /* stdin/stdout/stderr handles */\n        for(i = 0; i < 3; i++) {\n            val = JS_GetPropertyStr(ctx, options, std_name[i]);\n            if (JS_IsException(val))\n                goto exception;\n            if (!JS_IsUndefined(val)) {\n                int fd;\n                ret = JS_ToInt32(ctx, &fd, val);\n                JS_FreeValue(ctx, val);\n                if (ret)\n                    goto exception;\n                std_fds[i] = fd;\n            }\n        }\n\n        val = JS_GetPropertyStr(ctx, options, \"env\");\n        if (JS_IsException(val))\n            goto exception;\n        if (!JS_IsUndefined(val)) {\n            envp = build_envp(ctx, val);\n            JS_FreeValue(ctx, val);\n            if (!envp)\n                goto exception;\n        }\n        \n        val = JS_GetPropertyStr(ctx, options, \"uid\");\n        if (JS_IsException(val))\n            goto exception;\n        if (!JS_IsUndefined(val)) {\n            ret = JS_ToUint32(ctx, &uid, val);\n            JS_FreeValue(ctx, val);\n            if (ret)\n                goto exception;\n        }\n\n        val = JS_GetPropertyStr(ctx, options, \"gid\");\n        if (JS_IsException(val))\n            goto exception;\n        if (!JS_IsUndefined(val)) {\n            ret = JS_ToUint32(ctx, &gid, val);\n            JS_FreeValue(ctx, val);\n            if (ret)\n                goto exception;\n        }\n    }\n\n    pid = fork();\n    if (pid < 0) {\n        JS_ThrowTypeError(ctx, \"fork error\");\n        goto exception;\n    }\n    if (pid == 0) {\n        /* child */\n        int fd_max = sysconf(_SC_OPEN_MAX);\n\n        /* remap the stdin/stdout/stderr handles if necessary */\n        for(i = 0; i < 3; i++) {\n            if (std_fds[i] != i) {\n                if (dup2(std_fds[i], i) < 0)\n                    _exit(127);\n            }\n        }\n\n        for(i = 3; i < fd_max; i++)\n            close(i);\n        if (cwd) {\n            if (chdir(cwd) < 0)\n                _exit(127);\n        }\n        if (uid != -1) {\n            if (setuid(uid) < 0)\n                _exit(127);\n        }\n        if (gid != -1) {\n            if (setgid(gid) < 0)\n                _exit(127);\n        }\n\n        if (!file)\n            file = exec_argv[0];\n        if (use_path)\n            ret = my_execvpe(file, (char **)exec_argv, envp);\n        else\n            ret = execve(file, (char **)exec_argv, envp);\n        _exit(127);\n    }\n    /* parent */\n    if (block_flag) {\n        for(;;) {\n            ret = waitpid(pid, &status, 0);\n            if (ret == pid) {\n                if (WIFEXITED(status)) {\n                    ret = WEXITSTATUS(status);\n                    break;\n                } else if (WIFSIGNALED(status)) {\n                    ret = -WTERMSIG(status);\n                    break;\n                }\n            }\n        }\n    } else {\n        ret = pid;\n    }\n    ret_val = JS_NewInt32(ctx, ret);\n done:\n    JS_FreeCString(ctx, file);\n    JS_FreeCString(ctx, cwd);\n    for(i = 0; i < exec_argc; i++)\n        JS_FreeCString(ctx, exec_argv[i]);\n    js_free(ctx, exec_argv);\n    if (envp != environ) {\n        char **p;\n        p = envp;\n        while (*p != NULL) {\n            js_free(ctx, *p);\n            p++;\n        }\n        js_free(ctx, envp);\n    }\n    return ret_val;\n exception:\n    ret_val = JS_EXCEPTION;\n    goto done;\n}\n\n/* waitpid(pid, block) -> [pid, status] */\nstatic JSValue js_os_waitpid(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    int pid, status, options, ret;\n    JSValue obj;\n    \n    if (JS_ToInt32(ctx, &pid, argv[0]))\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &options, argv[1]))\n        return JS_EXCEPTION;\n\n    ret = waitpid(pid, &status, options);\n    if (ret < 0) {\n        ret = -errno;\n        status = 0;\n    }\n\n    obj = JS_NewArray(ctx);\n    if (JS_IsException(obj))\n        return obj;\n    JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, ret),\n                                 JS_PROP_C_W_E);\n    JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, status),\n                                 JS_PROP_C_W_E);\n    return obj;\n}    \n\n/* pipe() -> [read_fd, write_fd] or null if error */\nstatic JSValue js_os_pipe(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv)\n{\n    int pipe_fds[2], ret;\n    JSValue obj;\n    \n    ret = pipe(pipe_fds);\n    if (ret < 0)\n        return JS_NULL;\n    obj = JS_NewArray(ctx);\n    if (JS_IsException(obj))\n        return obj;\n    JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, pipe_fds[0]),\n                                 JS_PROP_C_W_E);\n    JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, pipe_fds[1]),\n                                 JS_PROP_C_W_E);\n    return obj;\n}\n\n/* kill(pid, sig) */\nstatic JSValue js_os_kill(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv)\n{\n    int pid, sig, ret;\n    \n    if (JS_ToInt32(ctx, &pid, argv[0]))\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &sig, argv[1]))\n        return JS_EXCEPTION;\n    ret = js_get_errno(kill(pid, sig));\n    return JS_NewInt32(ctx, ret);\n}\n\n/* dup(fd) */\nstatic JSValue js_os_dup(JSContext *ctx, JSValueConst this_val,\n                         int argc, JSValueConst *argv)\n{\n    int fd, ret;\n    \n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    ret = js_get_errno(dup(fd));\n    return JS_NewInt32(ctx, ret);\n}\n\n/* dup2(fd) */\nstatic JSValue js_os_dup2(JSContext *ctx, JSValueConst this_val,\n                         int argc, JSValueConst *argv)\n{\n    int fd, fd2, ret;\n    \n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &fd2, argv[1]))\n        return JS_EXCEPTION;\n    ret = js_get_errno(dup2(fd, fd2));\n    return JS_NewInt32(ctx, ret);\n}\n\n#endif /* !_WIN32 */\n\n#ifdef USE_WORKER\n\n/* Worker */\n\ntypedef struct {\n    JSWorkerMessagePipe *recv_pipe;\n    JSWorkerMessagePipe *send_pipe;\n    JSWorkerMessageHandler *msg_handler;\n} JSWorkerData;\n\ntypedef struct {\n    char *filename; /* module filename */\n    char *basename; /* module base name */\n    JSWorkerMessagePipe *recv_pipe, *send_pipe;\n} WorkerFuncArgs;\n\ntypedef struct {\n    int ref_count;\n    uint64_t buf[0];\n} JSSABHeader;\n\nstatic JSClassID js_worker_class_id;\nstatic JSContext *(*js_worker_new_context_func)(JSRuntime *rt);\n\nstatic int atomic_add_int(int *ptr, int v)\n{\n    return atomic_fetch_add((_Atomic(uint32_t) *)ptr, v) + v;\n}\n\n/* shared array buffer allocator */\nstatic void *js_sab_alloc(void *opaque, size_t size)\n{\n    JSSABHeader *sab;\n    sab = malloc(sizeof(JSSABHeader) + size);\n    if (!sab)\n        return NULL;\n    sab->ref_count = 1;\n    return sab->buf;\n}\n\nstatic void js_sab_free(void *opaque, void *ptr)\n{\n    JSSABHeader *sab;\n    int ref_count;\n    sab = (JSSABHeader *)((uint8_t *)ptr - sizeof(JSSABHeader));\n    ref_count = atomic_add_int(&sab->ref_count, -1);\n    assert(ref_count >= 0);\n    if (ref_count == 0) {\n        free(sab);\n    }\n}\n\nstatic void js_sab_dup(void *opaque, void *ptr)\n{\n    JSSABHeader *sab;\n    sab = (JSSABHeader *)((uint8_t *)ptr - sizeof(JSSABHeader));\n    atomic_add_int(&sab->ref_count, 1);\n}\n\nstatic JSWorkerMessagePipe *js_new_message_pipe(void)\n{\n    JSWorkerMessagePipe *ps;\n    int pipe_fds[2];\n    \n    if (pipe(pipe_fds) < 0)\n        return NULL;\n\n    ps = malloc(sizeof(*ps));\n    if (!ps) {\n        close(pipe_fds[0]);\n        close(pipe_fds[1]);\n        return NULL;\n    }\n    ps->ref_count = 1;\n    init_list_head(&ps->msg_queue);\n    pthread_mutex_init(&ps->mutex, NULL);\n    ps->read_fd = pipe_fds[0];\n    ps->write_fd = pipe_fds[1];\n    return ps;\n}\n\nstatic JSWorkerMessagePipe *js_dup_message_pipe(JSWorkerMessagePipe *ps)\n{\n    atomic_add_int(&ps->ref_count, 1);\n    return ps;\n}\n\nstatic void js_free_message(JSWorkerMessage *msg)\n{\n    size_t i;\n    /* free the SAB */\n    for(i = 0; i < msg->sab_tab_len; i++) {\n        js_sab_free(NULL, msg->sab_tab[i]);\n    }\n    free(msg->sab_tab);\n    free(msg->data);\n    free(msg);\n}\n\nstatic void js_free_message_pipe(JSWorkerMessagePipe *ps)\n{\n    struct list_head *el, *el1;\n    JSWorkerMessage *msg;\n    int ref_count;\n    \n    if (!ps)\n        return;\n    \n    ref_count = atomic_add_int(&ps->ref_count, -1);\n    assert(ref_count >= 0);\n    if (ref_count == 0) {\n        list_for_each_safe(el, el1, &ps->msg_queue) {\n            msg = list_entry(el, JSWorkerMessage, link);\n            js_free_message(msg);\n        }\n        pthread_mutex_destroy(&ps->mutex);\n        close(ps->read_fd);\n        close(ps->write_fd);\n        free(ps);\n    }\n}\n\nstatic void js_free_port(JSRuntime *rt, JSWorkerMessageHandler *port)\n{\n    if (port) {\n        js_free_message_pipe(port->recv_pipe);\n        JS_FreeValueRT(rt, port->on_message_func);\n        list_del(&port->link);\n        js_free_rt(rt, port);\n    }\n}\n\nstatic void js_worker_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSWorkerData *worker = JS_GetOpaque(val, js_worker_class_id);\n    if (worker) {\n        js_free_message_pipe(worker->recv_pipe);\n        js_free_message_pipe(worker->send_pipe);\n        js_free_port(rt, worker->msg_handler);\n        js_free_rt(rt, worker);\n    }\n}\n\nstatic JSClassDef js_worker_class = {\n    \"Worker\",\n    .finalizer = js_worker_finalizer,\n}; \n\nstatic void *worker_func(void *opaque)\n{\n    WorkerFuncArgs *args = opaque;\n    JSRuntime *rt;\n    JSThreadState *ts;\n    JSContext *ctx;\n    \n    rt = JS_NewRuntime();\n    if (rt == NULL) {\n        fprintf(stderr, \"JS_NewRuntime failure\");\n        exit(1);\n    }        \n    js_std_init_handlers(rt);\n\n    JS_SetModuleLoaderFunc(rt, NULL, js_module_loader, NULL);\n\n    /* set the pipe to communicate with the parent */\n    ts = JS_GetRuntimeOpaque(rt);\n    ts->recv_pipe = args->recv_pipe;\n    ts->send_pipe = args->send_pipe;\n    \n    /* function pointer to avoid linking the whole JS_NewContext() if\n       not needed */\n    ctx = js_worker_new_context_func(rt);\n    if (ctx == NULL) {\n        fprintf(stderr, \"JS_NewContext failure\");\n    }\n\n    JS_SetCanBlock(rt, TRUE);\n\n    js_std_add_helpers(ctx, -1, NULL);\n\n    if (!JS_RunModule(ctx, args->basename, args->filename))\n        js_std_dump_error(ctx);\n    free(args->filename);\n    free(args->basename);\n    free(args);\n\n    js_std_loop(ctx);\n\n    JS_FreeContext(ctx);\n    js_std_free_handlers(rt);\n    JS_FreeRuntime(rt);\n    return NULL;\n}\n\nstatic JSValue js_worker_ctor_internal(JSContext *ctx, JSValueConst new_target,\n                                       JSWorkerMessagePipe *recv_pipe,\n                                       JSWorkerMessagePipe *send_pipe)\n{\n    JSValue obj = JS_UNDEFINED, proto;\n    JSWorkerData *s;\n    \n    /* create the object */\n    if (JS_IsUndefined(new_target)) {\n        proto = JS_GetClassProto(ctx, js_worker_class_id);\n    } else {\n        proto = JS_GetPropertyStr(ctx, new_target, \"prototype\");\n        if (JS_IsException(proto))\n            goto fail;\n    }\n    obj = JS_NewObjectProtoClass(ctx, proto, js_worker_class_id);\n    JS_FreeValue(ctx, proto);\n    if (JS_IsException(obj))\n        goto fail;\n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s)\n        goto fail;\n    s->recv_pipe = js_dup_message_pipe(recv_pipe);\n    s->send_pipe = js_dup_message_pipe(send_pipe);\n\n    JS_SetOpaque(obj, s);\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_worker_ctor(JSContext *ctx, JSValueConst new_target,\n                              int argc, JSValueConst *argv)\n{\n    JSRuntime *rt = JS_GetRuntime(ctx);\n    WorkerFuncArgs *args = NULL;\n    pthread_t tid;\n    pthread_attr_t attr;\n    JSValue obj = JS_UNDEFINED;\n    int ret;\n    const char *filename = NULL, *basename;\n    JSAtom basename_atom;\n    \n    /* XXX: in order to avoid problems with resource liberation, we\n       don't support creating workers inside workers */\n    if (!is_main_thread(rt))\n        return JS_ThrowTypeError(ctx, \"cannot create a worker inside a worker\");\n\n    /* base name, assuming the calling function is a normal JS\n       function */\n    basename_atom = JS_GetScriptOrModuleName(ctx, 1);\n    if (basename_atom == JS_ATOM_NULL) {\n        return JS_ThrowTypeError(ctx, \"could not determine calling script or module name\");\n    }\n    basename = JS_AtomToCString(ctx, basename_atom);\n    JS_FreeAtom(ctx, basename_atom);\n    if (!basename)\n        goto fail;\n    \n    /* module name */\n    filename = JS_ToCString(ctx, argv[0]);\n    if (!filename)\n        goto fail;\n\n    args = malloc(sizeof(*args));\n    if (!args)\n        goto oom_fail;\n    memset(args, 0, sizeof(*args));\n    args->filename = strdup(filename);\n    args->basename = strdup(basename);\n\n    /* ports */\n    args->recv_pipe = js_new_message_pipe();\n    if (!args->recv_pipe)\n        goto oom_fail;\n    args->send_pipe = js_new_message_pipe();\n    if (!args->send_pipe)\n        goto oom_fail;\n\n    obj = js_worker_ctor_internal(ctx, new_target,\n                                  args->send_pipe, args->recv_pipe);\n    if (JS_IsException(obj))\n        goto fail;\n    \n    pthread_attr_init(&attr);\n    /* no join at the end */\n    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);\n    ret = pthread_create(&tid, &attr, worker_func, args);\n    pthread_attr_destroy(&attr);\n    if (ret != 0) {\n        JS_ThrowTypeError(ctx, \"could not create worker\");\n        goto fail;\n    }\n    JS_FreeCString(ctx, basename);\n    JS_FreeCString(ctx, filename);\n    return obj;\n oom_fail:\n    JS_ThrowOutOfMemory(ctx);\n fail:\n    JS_FreeCString(ctx, basename);\n    JS_FreeCString(ctx, filename);\n    if (args) {\n        free(args->filename);\n        free(args->basename);\n        js_free_message_pipe(args->recv_pipe);\n        js_free_message_pipe(args->send_pipe);\n        free(args);\n    }\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_worker_postMessage(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, js_worker_class_id);\n    JSWorkerMessagePipe *ps;\n    size_t data_len, sab_tab_len, i;\n    uint8_t *data;\n    JSWorkerMessage *msg;\n    uint8_t **sab_tab;\n    \n    if (!worker)\n        return JS_EXCEPTION;\n    \n    data = JS_WriteObject2(ctx, &data_len, argv[0],\n                           JS_WRITE_OBJ_SAB | JS_WRITE_OBJ_REFERENCE,\n                           &sab_tab, &sab_tab_len);\n    if (!data)\n        return JS_EXCEPTION;\n\n    msg = malloc(sizeof(*msg));\n    if (!msg)\n        goto fail;\n    msg->data = NULL;\n    msg->sab_tab = NULL;\n\n    /* must reallocate because the allocator may be different */\n    msg->data = malloc(data_len);\n    if (!msg->data)\n        goto fail;\n    memcpy(msg->data, data, data_len);\n    msg->data_len = data_len;\n\n    msg->sab_tab = malloc(sizeof(msg->sab_tab[0]) * sab_tab_len);\n    if (!msg->sab_tab)\n        goto fail;\n    memcpy(msg->sab_tab, sab_tab, sizeof(msg->sab_tab[0]) * sab_tab_len);\n    msg->sab_tab_len = sab_tab_len;\n\n    js_free(ctx, data);\n    js_free(ctx, sab_tab);\n    \n    /* increment the SAB reference counts */\n    for(i = 0; i < msg->sab_tab_len; i++) {\n        js_sab_dup(NULL, msg->sab_tab[i]);\n    }\n\n    ps = worker->send_pipe;\n    pthread_mutex_lock(&ps->mutex);\n    /* indicate that data is present */\n    if (list_empty(&ps->msg_queue)) {\n        uint8_t ch = '\\0';\n        int ret;\n        for(;;) {\n            ret = write(ps->write_fd, &ch, 1);\n            if (ret == 1)\n                break;\n            if (ret < 0 && (errno != EAGAIN || errno != EINTR))\n                break;\n        }\n    }\n    list_add_tail(&msg->link, &ps->msg_queue);\n    pthread_mutex_unlock(&ps->mutex);\n    return JS_UNDEFINED;\n fail:\n    if (msg) {\n        free(msg->data);\n        free(msg->sab_tab);\n        free(msg);\n    }\n    js_free(ctx, data);\n    js_free(ctx, sab_tab);\n    return JS_EXCEPTION;\n    \n}\n\nstatic JSValue js_worker_set_onmessage(JSContext *ctx, JSValueConst this_val,\n                                   JSValueConst func)\n{\n    JSRuntime *rt = JS_GetRuntime(ctx);\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, js_worker_class_id);\n    JSWorkerMessageHandler *port;\n    \n    if (!worker)\n        return JS_EXCEPTION;\n\n    port = worker->msg_handler;\n    if (JS_IsNull(func)) {\n        if (port) {\n            js_free_port(rt, port);\n            worker->msg_handler = NULL;\n        }\n    } else {\n        if (!JS_IsFunction(ctx, func))\n            return JS_ThrowTypeError(ctx, \"not a function\");\n        if (!port) {\n            port = js_mallocz(ctx, sizeof(*port));\n            if (!port)\n                return JS_EXCEPTION;\n            port->recv_pipe = js_dup_message_pipe(worker->recv_pipe);\n            port->on_message_func = JS_NULL;\n            list_add_tail(&port->link, &ts->port_list);\n            worker->msg_handler = port;\n        }\n        JS_FreeValue(ctx, port->on_message_func);\n        port->on_message_func = JS_DupValue(ctx, func);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_worker_get_onmessage(JSContext *ctx, JSValueConst this_val)\n{\n    JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, js_worker_class_id);\n    JSWorkerMessageHandler *port;\n    if (!worker)\n        return JS_EXCEPTION;\n    port = worker->msg_handler;\n    if (port) {\n        return JS_DupValue(ctx, port->on_message_func);\n    } else {\n        return JS_NULL;\n    }\n}\n\nstatic const JSCFunctionListEntry js_worker_proto_funcs[] = {\n    JS_CFUNC_DEF(\"postMessage\", 1, js_worker_postMessage ),\n    JS_CGETSET_DEF(\"onmessage\", js_worker_get_onmessage, js_worker_set_onmessage ),\n};\n\n#endif /* USE_WORKER */\n\nvoid js_std_set_worker_new_context_func(JSContext *(*func)(JSRuntime *rt))\n{\n#ifdef USE_WORKER\n    js_worker_new_context_func = func;\n#endif\n}\n\n#if defined(_WIN32)\n#define OS_PLATFORM \"win32\"\n#elif defined(__APPLE__)\n#define OS_PLATFORM \"darwin\"\n#elif defined(EMSCRIPTEN)\n#define OS_PLATFORM \"js\"\n#else\n#define OS_PLATFORM \"linux\"\n#endif\n\n#define OS_FLAG(x) JS_PROP_INT32_DEF(#x, x, JS_PROP_CONFIGURABLE )\n\nstatic const JSCFunctionListEntry js_os_funcs[] = {\n    JS_CFUNC_DEF(\"open\", 2, js_os_open ),\n    OS_FLAG(O_RDONLY),\n    OS_FLAG(O_WRONLY),\n    OS_FLAG(O_RDWR),\n    OS_FLAG(O_APPEND),\n    OS_FLAG(O_CREAT),\n    OS_FLAG(O_EXCL),\n    OS_FLAG(O_TRUNC),\n#if defined(_WIN32)\n    OS_FLAG(O_BINARY),\n    OS_FLAG(O_TEXT),\n#endif\n    JS_CFUNC_DEF(\"close\", 1, js_os_close ),\n    JS_CFUNC_DEF(\"seek\", 3, js_os_seek ),\n    JS_CFUNC_MAGIC_DEF(\"read\", 4, js_os_read_write, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"write\", 4, js_os_read_write, 1 ),\n    JS_CFUNC_DEF(\"isatty\", 1, js_os_isatty ),\n    JS_CFUNC_DEF(\"ttyGetWinSize\", 1, js_os_ttyGetWinSize ),\n    JS_CFUNC_DEF(\"ttySetRaw\", 1, js_os_ttySetRaw ),\n    JS_CFUNC_DEF(\"remove\", 1, js_os_remove ),\n    JS_CFUNC_DEF(\"rename\", 2, js_os_rename ),\n    JS_CFUNC_MAGIC_DEF(\"setReadHandler\", 2, js_os_setReadHandler, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"setWriteHandler\", 2, js_os_setReadHandler, 1 ),\n    JS_CFUNC_DEF(\"signal\", 2, js_os_signal ),\n    OS_FLAG(SIGINT),\n    OS_FLAG(SIGABRT),\n    OS_FLAG(SIGFPE),\n    OS_FLAG(SIGILL),\n    OS_FLAG(SIGSEGV),\n    OS_FLAG(SIGTERM),\n#if !defined(_WIN32)\n    OS_FLAG(SIGQUIT),\n    OS_FLAG(SIGPIPE),\n    OS_FLAG(SIGALRM),\n    OS_FLAG(SIGUSR1),\n    OS_FLAG(SIGUSR2),\n    OS_FLAG(SIGCHLD),\n    OS_FLAG(SIGCONT),\n    OS_FLAG(SIGSTOP),\n    OS_FLAG(SIGTSTP),\n    OS_FLAG(SIGTTIN),\n    OS_FLAG(SIGTTOU),\n#endif\n    JS_CFUNC_DEF(\"setTimeout\", 2, js_os_setTimeout ),\n    JS_CFUNC_DEF(\"clearTimeout\", 1, js_os_clearTimeout ),\n    JS_PROP_STRING_DEF(\"platform\", OS_PLATFORM, 0 ),\n    JS_CFUNC_DEF(\"getcwd\", 0, js_os_getcwd ),\n    JS_CFUNC_DEF(\"chdir\", 0, js_os_chdir ),\n    JS_CFUNC_DEF(\"mkdir\", 1, js_os_mkdir ),\n    JS_CFUNC_DEF(\"readdir\", 1, js_os_readdir ),\n    /* st_mode constants */\n    OS_FLAG(S_IFMT),\n    OS_FLAG(S_IFIFO),\n    OS_FLAG(S_IFCHR),\n    OS_FLAG(S_IFDIR),\n    OS_FLAG(S_IFBLK),\n    OS_FLAG(S_IFREG),\n#if !defined(_WIN32)\n    OS_FLAG(S_IFSOCK),\n    OS_FLAG(S_IFLNK),\n    OS_FLAG(S_ISGID),\n    OS_FLAG(S_ISUID),\n#endif\n    JS_CFUNC_MAGIC_DEF(\"stat\", 1, js_os_stat, 0 ),\n    JS_CFUNC_DEF(\"utimes\", 3, js_os_utimes ),\n    JS_CFUNC_DEF(\"sleep\", 1, js_os_sleep ),\n    JS_CFUNC_DEF(\"realpath\", 1, js_os_realpath ),\n#if !defined(_WIN32)\n    JS_CFUNC_MAGIC_DEF(\"lstat\", 1, js_os_stat, 1 ),\n    JS_CFUNC_DEF(\"symlink\", 2, js_os_symlink ),\n    JS_CFUNC_DEF(\"readlink\", 1, js_os_readlink ),\n    JS_CFUNC_DEF(\"exec\", 1, js_os_exec ),\n    JS_CFUNC_DEF(\"waitpid\", 2, js_os_waitpid ),\n    OS_FLAG(WNOHANG),\n    JS_CFUNC_DEF(\"pipe\", 0, js_os_pipe ),\n    JS_CFUNC_DEF(\"kill\", 2, js_os_kill ),\n    JS_CFUNC_DEF(\"dup\", 1, js_os_dup ),\n    JS_CFUNC_DEF(\"dup2\", 2, js_os_dup2 ),\n#endif\n};\n\nstatic int js_os_init(JSContext *ctx, JSModuleDef *m)\n{\n    os_poll_func = js_os_poll;\n    \n    /* OSTimer class */\n    JS_NewClassID(&js_os_timer_class_id);\n    JS_NewClass(JS_GetRuntime(ctx), js_os_timer_class_id, &js_os_timer_class);\n\n#ifdef USE_WORKER\n    {\n        JSRuntime *rt = JS_GetRuntime(ctx);\n        JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n        JSValue proto, obj;\n        /* Worker class */\n        JS_NewClassID(&js_worker_class_id);\n        JS_NewClass(JS_GetRuntime(ctx), js_worker_class_id, &js_worker_class);\n        proto = JS_NewObject(ctx);\n        JS_SetPropertyFunctionList(ctx, proto, js_worker_proto_funcs, countof(js_worker_proto_funcs));\n        \n        obj = JS_NewCFunction2(ctx, js_worker_ctor, \"Worker\", 1,\n                               JS_CFUNC_constructor, 0);\n        JS_SetConstructor(ctx, obj, proto);\n        \n        JS_SetClassProto(ctx, js_worker_class_id, proto);\n        \n        /* set 'Worker.parent' if necessary */\n        if (ts->recv_pipe && ts->send_pipe) {\n            JS_DefinePropertyValueStr(ctx, obj, \"parent\",\n                                      js_worker_ctor_internal(ctx, JS_UNDEFINED, ts->recv_pipe, ts->send_pipe),\n                                      JS_PROP_C_W_E);\n        }\n        \n        JS_SetModuleExport(ctx, m, \"Worker\", obj);\n    }\n#endif /* USE_WORKER */\n\n    return JS_SetModuleExportList(ctx, m, js_os_funcs,\n                                  countof(js_os_funcs));\n}\n\nJSModuleDef *js_init_module_os(JSContext *ctx, const char *module_name)\n{\n    JSModuleDef *m;\n    m = JS_NewCModule(ctx, module_name, js_os_init);\n    if (!m)\n        return NULL;\n    JS_AddModuleExportList(ctx, m, js_os_funcs, countof(js_os_funcs));\n#ifdef USE_WORKER\n    JS_AddModuleExport(ctx, m, \"Worker\");\n#endif\n    return m;\n}\n\n/**********************************************************/\n\nstatic JSValue js_print(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    int i;\n    const char *str;\n    size_t len;\n\n    for(i = 0; i < argc; i++) {\n        if (i != 0)\n            putchar(' ');\n        str = JS_ToCStringLen(ctx, &len, argv[i]);\n        if (!str)\n            return JS_EXCEPTION;\n        fwrite(str, 1, len, stdout);\n        JS_FreeCString(ctx, str);\n    }\n    putchar('\\n');\n    return JS_UNDEFINED;\n}\n\nvoid js_std_add_helpers(JSContext *ctx, int argc, char **argv)\n{\n    JSValue global_obj, console, args;\n    int i;\n\n    /* XXX: should these global definitions be enumerable? */\n    global_obj = JS_GetGlobalObject(ctx);\n\n    console = JS_NewObject(ctx);\n    JS_SetPropertyStr(ctx, console, \"log\",\n                      JS_NewCFunction(ctx, js_print, \"log\", 1));\n    JS_SetPropertyStr(ctx, global_obj, \"console\", console);\n\n    /* same methods as the mozilla JS shell */\n    if (argc >= 0) {\n        args = JS_NewArray(ctx);\n        for(i = 0; i < argc; i++) {\n            JS_SetPropertyUint32(ctx, args, i, JS_NewString(ctx, argv[i]));\n        }\n        JS_SetPropertyStr(ctx, global_obj, \"scriptArgs\", args);\n    }\n    \n    JS_SetPropertyStr(ctx, global_obj, \"print\",\n                      JS_NewCFunction(ctx, js_print, \"print\", 1));\n    JS_SetPropertyStr(ctx, global_obj, \"__loadScript\",\n                      JS_NewCFunction(ctx, js_loadScript, \"__loadScript\", 1));\n    \n    JS_FreeValue(ctx, global_obj);\n}\n\nvoid js_std_init_handlers(JSRuntime *rt)\n{\n    JSThreadState *ts;\n\n    ts = malloc(sizeof(*ts));\n    if (!ts) {\n        fprintf(stderr, \"Could not allocate memory for the worker\");\n        exit(1);\n    }\n    memset(ts, 0, sizeof(*ts));\n    init_list_head(&ts->os_rw_handlers);\n    init_list_head(&ts->os_signal_handlers);\n    init_list_head(&ts->os_timers);\n    init_list_head(&ts->port_list);\n\n    JS_SetRuntimeOpaque(rt, ts);\n\n#ifdef USE_WORKER\n    /* set the SharedArrayBuffer memory handlers */\n    {\n        JSSharedArrayBufferFunctions sf;\n        memset(&sf, 0, sizeof(sf));\n        sf.sab_alloc = js_sab_alloc;\n        sf.sab_free = js_sab_free;\n        sf.sab_dup = js_sab_dup;\n        JS_SetSharedArrayBufferFunctions(rt, &sf);\n    }\n#endif\n}\n\nvoid js_std_free_handlers(JSRuntime *rt)\n{\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    struct list_head *el, *el1;\n\n    list_for_each_safe(el, el1, &ts->os_rw_handlers) {\n        JSOSRWHandler *rh = list_entry(el, JSOSRWHandler, link);\n        free_rw_handler(rt, rh);\n    }\n\n    list_for_each_safe(el, el1, &ts->os_signal_handlers) {\n        JSOSSignalHandler *sh = list_entry(el, JSOSSignalHandler, link);\n        free_sh(rt, sh);\n    }\n    \n    list_for_each_safe(el, el1, &ts->os_timers) {\n        JSOSTimer *th = list_entry(el, JSOSTimer, link);\n        unlink_timer(rt, th);\n        if (!th->has_object)\n            free_timer(rt, th);\n    }\n\n#ifdef USE_WORKER\n    /* XXX: free port_list ? */\n    js_free_message_pipe(ts->recv_pipe);\n    js_free_message_pipe(ts->send_pipe);\n#endif\n\n    free(ts);\n    JS_SetRuntimeOpaque(rt, NULL); /* fail safe */\n}\n\nstatic void js_dump_obj(JSContext *ctx, FILE *f, JSValueConst val)\n{\n    const char *str;\n    \n    str = JS_ToCString(ctx, val);\n    if (str) {\n        fprintf(f, \"%s\\n\", str);\n        JS_FreeCString(ctx, str);\n    } else {\n        fprintf(f, \"[exception]\\n\");\n    }\n}\n\nstatic void js_std_dump_error1(JSContext *ctx, JSValueConst exception_val)\n{\n    JSValue val;\n    BOOL is_error;\n    \n    is_error = JS_IsError(ctx, exception_val);\n    js_dump_obj(ctx, stderr, exception_val);\n    if (is_error) {\n        val = JS_GetPropertyStr(ctx, exception_val, \"stack\");\n        if (!JS_IsUndefined(val)) {\n            js_dump_obj(ctx, stderr, val);\n        }\n        JS_FreeValue(ctx, val);\n    }\n}\n\nvoid js_std_dump_error(JSContext *ctx)\n{\n    JSValue exception_val;\n    \n    exception_val = JS_GetException(ctx);\n    js_std_dump_error1(ctx, exception_val);\n    JS_FreeValue(ctx, exception_val);\n}\n\nvoid js_std_promise_rejection_tracker(JSContext *ctx, JSValueConst promise,\n                                      JSValueConst reason,\n                                      BOOL is_handled, void *opaque)\n{\n    if (!is_handled) {\n        fprintf(stderr, \"Possibly unhandled promise rejection: \");\n        js_std_dump_error1(ctx, reason);\n    }\n}\n\n/* main loop which calls the user JS callbacks */\nvoid js_std_loop(JSContext *ctx)\n{\n    JSContext *ctx1;\n    int err;\n\n    for(;;) {\n        /* execute the pending jobs */\n        for(;;) {\n            err = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1);\n            if (err <= 0) {\n                if (err < 0) {\n                    js_std_dump_error(ctx1);\n                }\n                break;\n            }\n        }\n\n        if (!os_poll_func || os_poll_func(ctx))\n            break;\n    }\n}\n\nvoid js_std_eval_binary(JSContext *ctx, const uint8_t *buf, size_t buf_len,\n                        int load_only)\n{\n    JSValue obj, val;\n    obj = JS_ReadObject(ctx, buf, buf_len, JS_READ_OBJ_BYTECODE);\n    if (JS_IsException(obj))\n        goto exception;\n    if (load_only) {\n        if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) {\n            js_module_set_import_meta(ctx, obj, FALSE, FALSE);\n        }\n    } else {\n        if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) {\n            if (JS_ResolveModule(ctx, obj) < 0) {\n                JS_FreeValue(ctx, obj);\n                goto exception;\n            }\n            js_module_set_import_meta(ctx, obj, FALSE, TRUE);\n        }\n        val = JS_EvalFunction(ctx, obj);\n        if (JS_IsException(val)) {\n        exception:\n            js_std_dump_error(ctx);\n            exit(1);\n        }\n        JS_FreeValue(ctx, val);\n    }\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/quickjs-libc.h",
    "content": "/*\n * QuickJS C library\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#ifndef QUICKJS_LIBC_H\n#define QUICKJS_LIBC_H\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"quickjs.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nJSModuleDef *js_init_module_std(JSContext *ctx, const char *module_name);\nJSModuleDef *js_init_module_os(JSContext *ctx, const char *module_name);\nvoid js_std_add_helpers(JSContext *ctx, int argc, char **argv);\nvoid js_std_loop(JSContext *ctx);\nvoid js_std_init_handlers(JSRuntime *rt);\nvoid js_std_free_handlers(JSRuntime *rt);\nvoid js_std_dump_error(JSContext *ctx);\nuint8_t *js_load_file(JSContext *ctx, size_t *pbuf_len, const char *filename);\nint js_module_set_import_meta(JSContext *ctx, JSValueConst func_val,\n                              JS_BOOL use_realpath, JS_BOOL is_main);\nJSModuleDef *js_module_loader(JSContext *ctx,\n                              const char *module_name, void *opaque);\nvoid js_std_eval_binary(JSContext *ctx, const uint8_t *buf, size_t buf_len,\n                        int flags);\nvoid js_std_promise_rejection_tracker(JSContext *ctx, JSValueConst promise,\n                                      JSValueConst reason,\n                                      JS_BOOL is_handled, void *opaque);\nvoid js_std_set_worker_new_context_func(JSContext *(*func)(JSRuntime *rt));\n                                        \n#ifdef __cplusplus\n} /* extern \"C\" { */\n#endif\n\n#endif /* QUICKJS_LIBC_H */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/quickjs-opcode.h",
    "content": "/*\n * QuickJS opcode definitions\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n * Copyright (c) 2017-2018 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n#ifdef FMT\nFMT(none)\nFMT(none_int)\nFMT(none_loc)\nFMT(none_arg)\nFMT(none_var_ref)\nFMT(u8)\nFMT(i8)\nFMT(loc8)\nFMT(const8)\nFMT(label8)\nFMT(u16)\nFMT(i16)\nFMT(label16)\nFMT(npop)\nFMT(npopx)\nFMT(npop_u16)\nFMT(loc)\nFMT(arg)\nFMT(var_ref)\nFMT(u32)\nFMT(i32)\nFMT(const)\nFMT(label)\nFMT(atom)\nFMT(atom_u8)\nFMT(atom_u16)\nFMT(atom_label_u8)\nFMT(atom_label_u16)\nFMT(label_u16)\n#undef FMT\n#endif /* FMT */\n\n#ifdef DEF\n\n#ifndef def\n#define def(id, size, n_pop, n_push, f) DEF(id, size, n_pop, n_push, f)\n#endif\n\nDEF(invalid, 1, 0, 0, none) /* never emitted */\n\n/* push values */\nDEF(       push_i32, 5, 0, 1, i32)\nDEF(     push_const, 5, 0, 1, const)\nDEF(       fclosure, 5, 0, 1, const) /* must follow push_const */\nDEF(push_atom_value, 5, 0, 1, atom)\nDEF( private_symbol, 5, 0, 1, atom)\nDEF(      undefined, 1, 0, 1, none)\nDEF(           null, 1, 0, 1, none)\nDEF(      push_this, 1, 0, 1, none) /* only used at the start of a function */\nDEF(     push_false, 1, 0, 1, none)\nDEF(      push_true, 1, 0, 1, none)\nDEF(         object, 1, 0, 1, none)\nDEF( special_object, 2, 0, 1, u8) /* only used at the start of a function */\nDEF(           rest, 3, 0, 1, u16) /* only used at the start of a function */\n\nDEF(           drop, 1, 1, 0, none) /* a -> */\nDEF(            nip, 1, 2, 1, none) /* a b -> b */\nDEF(           nip1, 1, 3, 2, none) /* a b c -> b c */\nDEF(            dup, 1, 1, 2, none) /* a -> a a */\nDEF(           dup1, 1, 2, 3, none) /* a b -> a a b */\nDEF(           dup2, 1, 2, 4, none) /* a b -> a b a b */\nDEF(           dup3, 1, 3, 6, none) /* a b c -> a b c a b c */\nDEF(        insert2, 1, 2, 3, none) /* obj a -> a obj a (dup_x1) */\nDEF(        insert3, 1, 3, 4, none) /* obj prop a -> a obj prop a (dup_x2) */\nDEF(        insert4, 1, 4, 5, none) /* this obj prop a -> a this obj prop a */\nDEF(          perm3, 1, 3, 3, none) /* obj a b -> a obj b */\nDEF(          perm4, 1, 4, 4, none) /* obj prop a b -> a obj prop b */\nDEF(          perm5, 1, 5, 5, none) /* this obj prop a b -> a this obj prop b */\nDEF(           swap, 1, 2, 2, none) /* a b -> b a */\nDEF(          swap2, 1, 4, 4, none) /* a b c d -> c d a b */\nDEF(          rot3l, 1, 3, 3, none) /* x a b -> a b x */\nDEF(          rot3r, 1, 3, 3, none) /* a b x -> x a b */\nDEF(          rot4l, 1, 4, 4, none) /* x a b c -> a b c x */\nDEF(          rot5l, 1, 5, 5, none) /* x a b c d -> a b c d x */\n\nDEF(call_constructor, 3, 2, 1, npop) /* func new.target args -> ret. arguments are not counted in n_pop */\nDEF(           call, 3, 1, 1, npop) /* arguments are not counted in n_pop */\nDEF(      tail_call, 3, 1, 0, npop) /* arguments are not counted in n_pop */\nDEF(    call_method, 3, 2, 1, npop) /* arguments are not counted in n_pop */\nDEF(tail_call_method, 3, 2, 0, npop) /* arguments are not counted in n_pop */\nDEF(     array_from, 3, 0, 1, npop) /* arguments are not counted in n_pop */\nDEF(          apply, 3, 3, 1, u16)\nDEF(         return, 1, 1, 0, none)\nDEF(   return_undef, 1, 0, 0, none)\nDEF(check_ctor_return, 1, 1, 2, none)\nDEF(     check_ctor, 1, 0, 0, none)\nDEF(    check_brand, 1, 2, 2, none) /* this_obj func -> this_obj func */\nDEF(      add_brand, 1, 2, 0, none) /* this_obj home_obj -> */\nDEF(   return_async, 1, 1, 0, none)\nDEF(          throw, 1, 1, 0, none)\nDEF(    throw_error, 6, 0, 0, atom_u8)\nDEF(           eval, 5, 1, 1, npop_u16) /* func args... -> ret_val */\nDEF(     apply_eval, 3, 2, 1, u16) /* func array -> ret_eval */\nDEF(         regexp, 1, 2, 1, none) /* create a RegExp object from the pattern and a\n                                       bytecode string */\nDEF(      get_super, 1, 1, 1, none)\nDEF(         import, 1, 1, 1, none) /* dynamic module import */\n\nDEF(      check_var, 5, 0, 1, atom) /* check if a variable exists */\nDEF(  get_var_undef, 5, 0, 1, atom) /* push undefined if the variable does not exist */\nDEF(        get_var, 5, 0, 1, atom) /* throw an exception if the variable does not exist */\nDEF(        put_var, 5, 1, 0, atom) /* must come after get_var */\nDEF(   put_var_init, 5, 1, 0, atom) /* must come after put_var. Used to initialize a global lexical variable */\nDEF( put_var_strict, 5, 2, 0, atom) /* for strict mode variable write */\n\nDEF(  get_ref_value, 1, 2, 3, none)\nDEF(  put_ref_value, 1, 3, 0, none)\n\nDEF(     define_var, 6, 0, 0, atom_u8)\nDEF(check_define_var, 6, 0, 0, atom_u8)\nDEF(    define_func, 6, 1, 0, atom_u8)\nDEF(      get_field, 5, 1, 1, atom)\nDEF(     get_field2, 5, 1, 2, atom)\nDEF(      put_field, 5, 2, 0, atom)\nDEF( get_private_field, 1, 2, 1, none) /* obj prop -> value */\nDEF( put_private_field, 1, 3, 0, none) /* obj value prop -> */\nDEF(define_private_field, 1, 3, 1, none) /* obj prop value -> obj */\nDEF(   get_array_el, 1, 2, 1, none)\nDEF(  get_array_el2, 1, 2, 2, none) /* obj prop -> obj value */\nDEF(   put_array_el, 1, 3, 0, none)\nDEF(get_super_value, 1, 3, 1, none) /* this obj prop -> value */\nDEF(put_super_value, 1, 4, 0, none) /* this obj prop value -> */\nDEF(   define_field, 5, 2, 1, atom)\nDEF(       set_name, 5, 1, 1, atom)\nDEF(set_name_computed, 1, 2, 2, none)\nDEF(      set_proto, 1, 2, 1, none)\nDEF(set_home_object, 1, 2, 2, none)\nDEF(define_array_el, 1, 3, 2, none)\nDEF(         append, 1, 3, 2, none) /* append enumerated object, update length */\nDEF(copy_data_properties, 2, 3, 3, u8)\nDEF(  define_method, 6, 2, 1, atom_u8)\nDEF(define_method_computed, 2, 3, 1, u8) /* must come after define_method */\nDEF(   define_class, 6, 2, 2, atom_u8) /* parent ctor -> ctor proto */\nDEF(   define_class_computed, 6, 3, 3, atom_u8) /* field_name parent ctor -> field_name ctor proto (class with computed name) */\n\nDEF(        get_loc, 3, 0, 1, loc)\nDEF(        put_loc, 3, 1, 0, loc) /* must come after get_loc */\nDEF(        set_loc, 3, 1, 1, loc) /* must come after put_loc */\nDEF(        get_arg, 3, 0, 1, arg)\nDEF(        put_arg, 3, 1, 0, arg) /* must come after get_arg */\nDEF(        set_arg, 3, 1, 1, arg) /* must come after put_arg */\nDEF(    get_var_ref, 3, 0, 1, var_ref) \nDEF(    put_var_ref, 3, 1, 0, var_ref) /* must come after get_var_ref */\nDEF(    set_var_ref, 3, 1, 1, var_ref) /* must come after put_var_ref */\nDEF(set_loc_uninitialized, 3, 0, 0, loc)\nDEF(  get_loc_check, 3, 0, 1, loc)\nDEF(  put_loc_check, 3, 1, 0, loc) /* must come after get_loc_check */\nDEF(  put_loc_check_init, 3, 1, 0, loc)\nDEF(get_var_ref_check, 3, 0, 1, var_ref) \nDEF(put_var_ref_check, 3, 1, 0, var_ref) /* must come after get_var_ref_check */\nDEF(put_var_ref_check_init, 3, 1, 0, var_ref)\nDEF(      close_loc, 3, 0, 0, loc)\nDEF(       if_false, 5, 1, 0, label)\nDEF(        if_true, 5, 1, 0, label) /* must come after if_false */\nDEF(           goto, 5, 0, 0, label) /* must come after if_true */\nDEF(          catch, 5, 0, 1, label)\nDEF(          gosub, 5, 0, 0, label) /* used to execute the finally block */\nDEF(            ret, 1, 1, 0, none) /* used to return from the finally block */\n\nDEF(      to_object, 1, 1, 1, none)\n//DEF(      to_string, 1, 1, 1, none)\nDEF(     to_propkey, 1, 1, 1, none)\nDEF(    to_propkey2, 1, 2, 2, none)\n\nDEF(   with_get_var, 10, 1, 0, atom_label_u8)     /* must be in the same order as scope_xxx */\nDEF(   with_put_var, 10, 2, 1, atom_label_u8)     /* must be in the same order as scope_xxx */\nDEF(with_delete_var, 10, 1, 0, atom_label_u8)     /* must be in the same order as scope_xxx */\nDEF(  with_make_ref, 10, 1, 0, atom_label_u8)     /* must be in the same order as scope_xxx */\nDEF(   with_get_ref, 10, 1, 0, atom_label_u8)     /* must be in the same order as scope_xxx */\nDEF(with_get_ref_undef, 10, 1, 0, atom_label_u8)\n\nDEF(   make_loc_ref, 7, 0, 2, atom_u16)\nDEF(   make_arg_ref, 7, 0, 2, atom_u16)\nDEF(make_var_ref_ref, 7, 0, 2, atom_u16)\nDEF(   make_var_ref, 5, 0, 2, atom)\n\nDEF(   for_in_start, 1, 1, 1, none)\nDEF(   for_of_start, 1, 1, 3, none)\nDEF(for_await_of_start, 1, 1, 3, none)\nDEF(    for_in_next, 1, 1, 3, none)\nDEF(    for_of_next, 2, 3, 5, u8)\nDEF(iterator_check_object, 1, 1, 1, none)\nDEF(iterator_get_value_done, 1, 1, 2, none)\nDEF( iterator_close, 1, 3, 0, none)\nDEF(iterator_close_return, 1, 4, 4, none)\nDEF(  iterator_next, 1, 4, 4, none)\nDEF(  iterator_call, 2, 4, 5, u8)\nDEF(  initial_yield, 1, 0, 0, none)\nDEF(          yield, 1, 1, 2, none)\nDEF(     yield_star, 1, 1, 2, none)\nDEF(async_yield_star, 1, 1, 2, none)\nDEF(          await, 1, 1, 1, none)\n\n/* arithmetic/logic operations */\nDEF(            neg, 1, 1, 1, none)\nDEF(           plus, 1, 1, 1, none)\nDEF(            dec, 1, 1, 1, none)\nDEF(            inc, 1, 1, 1, none)\nDEF(       post_dec, 1, 1, 2, none)\nDEF(       post_inc, 1, 1, 2, none)\nDEF(        dec_loc, 2, 0, 0, loc8)\nDEF(        inc_loc, 2, 0, 0, loc8)\nDEF(        add_loc, 2, 1, 0, loc8)\nDEF(            not, 1, 1, 1, none)\nDEF(           lnot, 1, 1, 1, none)\nDEF(         typeof, 1, 1, 1, none)\nDEF(         delete, 1, 2, 1, none)\nDEF(     delete_var, 5, 0, 1, atom)\n\nDEF(            mul, 1, 2, 1, none)\nDEF(            div, 1, 2, 1, none)\nDEF(            mod, 1, 2, 1, none)\nDEF(            add, 1, 2, 1, none)\nDEF(            sub, 1, 2, 1, none)\nDEF(            pow, 1, 2, 1, none)\nDEF(            shl, 1, 2, 1, none)\nDEF(            sar, 1, 2, 1, none)\nDEF(            shr, 1, 2, 1, none)\nDEF(             lt, 1, 2, 1, none)\nDEF(            lte, 1, 2, 1, none)\nDEF(             gt, 1, 2, 1, none)\nDEF(            gte, 1, 2, 1, none)\nDEF(     instanceof, 1, 2, 1, none)\nDEF(             in, 1, 2, 1, none)\nDEF(             eq, 1, 2, 1, none)\nDEF(            neq, 1, 2, 1, none)\nDEF(      strict_eq, 1, 2, 1, none)\nDEF(     strict_neq, 1, 2, 1, none)\nDEF(            and, 1, 2, 1, none)\nDEF(            xor, 1, 2, 1, none)\nDEF(             or, 1, 2, 1, none)\nDEF(is_undefined_or_null, 1, 1, 1, none)\n#ifdef CONFIG_BIGNUM\nDEF(      mul_pow10, 1, 2, 1, none)\nDEF(       math_mod, 1, 2, 1, none)\n#endif\n/* must be the last non short and non temporary opcode */\nDEF(            nop, 1, 0, 0, none) \n\n/* temporary opcodes: never emitted in the final bytecode */\n\ndef(    enter_scope, 3, 0, 0, u16)  /* emitted in phase 1, removed in phase 2 */\ndef(    leave_scope, 3, 0, 0, u16)  /* emitted in phase 1, removed in phase 2 */\n\ndef(          label, 5, 0, 0, label) /* emitted in phase 1, removed in phase 3 */\n\ndef(scope_get_var_undef, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */\ndef(  scope_get_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */\ndef(  scope_put_var, 7, 1, 0, atom_u16) /* emitted in phase 1, removed in phase 2 */\ndef(scope_delete_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */\ndef( scope_make_ref, 11, 0, 2, atom_label_u16) /* emitted in phase 1, removed in phase 2 */\ndef(  scope_get_ref, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */\ndef(scope_put_var_init, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */\ndef(scope_get_private_field, 7, 1, 1, atom_u16) /* obj -> value, emitted in phase 1, removed in phase 2 */\ndef(scope_get_private_field2, 7, 1, 2, atom_u16) /* obj -> obj value, emitted in phase 1, removed in phase 2 */\ndef(scope_put_private_field, 7, 1, 1, atom_u16) /* obj value ->, emitted in phase 1, removed in phase 2 */\n\ndef( set_class_name, 5, 1, 1, u32) /* emitted in phase 1, removed in phase 2 */\n    \ndef(       line_num, 5, 0, 0, u32) /* emitted in phase 1, removed in phase 3 */\n\n#if SHORT_OPCODES\nDEF(    push_minus1, 1, 0, 1, none_int)\nDEF(         push_0, 1, 0, 1, none_int)\nDEF(         push_1, 1, 0, 1, none_int)\nDEF(         push_2, 1, 0, 1, none_int)\nDEF(         push_3, 1, 0, 1, none_int)\nDEF(         push_4, 1, 0, 1, none_int)\nDEF(         push_5, 1, 0, 1, none_int)\nDEF(         push_6, 1, 0, 1, none_int)\nDEF(         push_7, 1, 0, 1, none_int)\nDEF(        push_i8, 2, 0, 1, i8)\nDEF(       push_i16, 3, 0, 1, i16)\nDEF(    push_const8, 2, 0, 1, const8)\nDEF(      fclosure8, 2, 0, 1, const8) /* must follow push_const8 */\nDEF(push_empty_string, 1, 0, 1, none)\n\nDEF(       get_loc8, 2, 0, 1, loc8)\nDEF(       put_loc8, 2, 1, 0, loc8)\nDEF(       set_loc8, 2, 1, 1, loc8)\n\nDEF(       get_loc0, 1, 0, 1, none_loc)\nDEF(       get_loc1, 1, 0, 1, none_loc)\nDEF(       get_loc2, 1, 0, 1, none_loc)\nDEF(       get_loc3, 1, 0, 1, none_loc)\nDEF(       put_loc0, 1, 1, 0, none_loc)\nDEF(       put_loc1, 1, 1, 0, none_loc)\nDEF(       put_loc2, 1, 1, 0, none_loc)\nDEF(       put_loc3, 1, 1, 0, none_loc)\nDEF(       set_loc0, 1, 1, 1, none_loc)\nDEF(       set_loc1, 1, 1, 1, none_loc)\nDEF(       set_loc2, 1, 1, 1, none_loc)\nDEF(       set_loc3, 1, 1, 1, none_loc)\nDEF(       get_arg0, 1, 0, 1, none_arg)\nDEF(       get_arg1, 1, 0, 1, none_arg)\nDEF(       get_arg2, 1, 0, 1, none_arg)\nDEF(       get_arg3, 1, 0, 1, none_arg)\nDEF(       put_arg0, 1, 1, 0, none_arg)\nDEF(       put_arg1, 1, 1, 0, none_arg)\nDEF(       put_arg2, 1, 1, 0, none_arg)\nDEF(       put_arg3, 1, 1, 0, none_arg)\nDEF(       set_arg0, 1, 1, 1, none_arg)\nDEF(       set_arg1, 1, 1, 1, none_arg)\nDEF(       set_arg2, 1, 1, 1, none_arg)\nDEF(       set_arg3, 1, 1, 1, none_arg)\nDEF(   get_var_ref0, 1, 0, 1, none_var_ref)\nDEF(   get_var_ref1, 1, 0, 1, none_var_ref)\nDEF(   get_var_ref2, 1, 0, 1, none_var_ref)\nDEF(   get_var_ref3, 1, 0, 1, none_var_ref)\nDEF(   put_var_ref0, 1, 1, 0, none_var_ref)\nDEF(   put_var_ref1, 1, 1, 0, none_var_ref)\nDEF(   put_var_ref2, 1, 1, 0, none_var_ref)\nDEF(   put_var_ref3, 1, 1, 0, none_var_ref)\nDEF(   set_var_ref0, 1, 1, 1, none_var_ref)\nDEF(   set_var_ref1, 1, 1, 1, none_var_ref)\nDEF(   set_var_ref2, 1, 1, 1, none_var_ref)\nDEF(   set_var_ref3, 1, 1, 1, none_var_ref)\n\nDEF(     get_length, 1, 1, 1, none)\n\nDEF(      if_false8, 2, 1, 0, label8)\nDEF(       if_true8, 2, 1, 0, label8) /* must come after if_false8 */\nDEF(          goto8, 2, 0, 0, label8) /* must come after if_true8 */\nDEF(         goto16, 3, 0, 0, label16)\n\nDEF(          call0, 1, 1, 1, npopx)\nDEF(          call1, 1, 1, 1, npopx)\nDEF(          call2, 1, 1, 1, npopx)\nDEF(          call3, 1, 1, 1, npopx)\n\nDEF(   is_undefined, 1, 1, 1, none)\nDEF(        is_null, 1, 1, 1, none)\nDEF(typeof_is_undefined, 1, 1, 1, none)\nDEF( typeof_is_function, 1, 1, 1, none)\n#endif\n\n#undef DEF\n#undef def\n#endif  /* DEF */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/quickjs.c",
    "content": "/*\n * QuickJS Javascript Engine\n * \n * Copyright (c) 2017-2021 Fabrice Bellard\n * Copyright (c) 2017-2021 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <inttypes.h>\n#include <string.h>\n#include <assert.h>\n#include <sys/time.h>\n#include <time.h>\n#include <fenv.h>\n#include <math.h>\n#if defined(__APPLE__)\n#include <malloc/malloc.h>\n#elif defined(__linux__)\n#include <malloc.h>\n#elif defined(__FreeBSD__)\n#include <malloc_np.h>\n#endif\n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"quickjs.h\"\n#include \"libregexp.h\"\n#ifdef CONFIG_BIGNUM\n#include \"libbf.h\"\n#endif\n\n#define OPTIMIZE         1\n#define SHORT_OPCODES    1\n#if defined(EMSCRIPTEN)\n#define DIRECT_DISPATCH  0\n#else\n#define DIRECT_DISPATCH  1\n#endif\n\n#if defined(__APPLE__)\n#define MALLOC_OVERHEAD  0\n#else\n#define MALLOC_OVERHEAD  8\n#endif\n\n#if !defined(_WIN32)\n/* define it if printf uses the RNDN rounding mode instead of RNDNA */\n#define CONFIG_PRINTF_RNDN\n#endif\n\n/* define to include Atomics.* operations which depend on the OS\n   threads */\n#if !defined(EMSCRIPTEN)\n#define CONFIG_ATOMICS\n#endif\n\n#if !defined(EMSCRIPTEN)\n/* enable stack limitation */\n#define CONFIG_STACK_CHECK\n#endif\n\n#if defined(__ANDROID__)\nstatic double __log2(double v) { return log(v) / log(2.0); }\n#endif\n\n/* dump object free */\n//#define DUMP_FREE\n//#define DUMP_CLOSURE\n/* dump the bytecode of the compiled functions: combination of bits\n   1: dump pass 3 final byte code\n   2: dump pass 2 code\n   4: dump pass 1 code\n   8: dump stdlib functions\n  16: dump bytecode in hex\n  32: dump line number table\n */\n//#define DUMP_BYTECODE  (1)\n/* dump the occurence of the automatic GC */\n//#define DUMP_GC\n/* dump objects freed by the garbage collector */\n//#define DUMP_GC_FREE\n/* dump objects leaking when freeing the runtime */\n//#define DUMP_LEAKS  1\n/* dump memory usage before running the garbage collector */\n//#define DUMP_MEM\n//#define DUMP_OBJECTS    /* dump objects in JS_FreeContext */\n//#define DUMP_ATOMS      /* dump atoms in JS_FreeContext */\n//#define DUMP_SHAPES     /* dump shapes in JS_FreeContext */\n//#define DUMP_MODULE_RESOLVE\n//#define DUMP_PROMISE\n//#define DUMP_READ_OBJECT\n\n/* test the GC by forcing it before each object allocation */\n//#define FORCE_GC_AT_MALLOC\n\n#ifdef CONFIG_ATOMICS\n#include <pthread.h>\n#include <stdatomic.h>\n#include <errno.h>\n#endif\n\nenum {\n    /* classid tag        */    /* union usage   | properties */\n    JS_CLASS_OBJECT = 1,        /* must be first */\n    JS_CLASS_ARRAY,             /* u.array       | length */\n    JS_CLASS_ERROR,\n    JS_CLASS_NUMBER,            /* u.object_data */\n    JS_CLASS_STRING,            /* u.object_data */\n    JS_CLASS_BOOLEAN,           /* u.object_data */\n    JS_CLASS_SYMBOL,            /* u.object_data */\n    JS_CLASS_ARGUMENTS,         /* u.array       | length */\n    JS_CLASS_MAPPED_ARGUMENTS,  /*               | length */\n    JS_CLASS_DATE,              /* u.object_data */\n    JS_CLASS_MODULE_NS,\n    JS_CLASS_C_FUNCTION,        /* u.cfunc */\n    JS_CLASS_BYTECODE_FUNCTION, /* u.func */\n    JS_CLASS_BOUND_FUNCTION,    /* u.bound_function */\n    JS_CLASS_C_FUNCTION_DATA,   /* u.c_function_data_record */\n    JS_CLASS_GENERATOR_FUNCTION, /* u.func */\n    JS_CLASS_FOR_IN_ITERATOR,   /* u.for_in_iterator */\n    JS_CLASS_REGEXP,            /* u.regexp */\n    JS_CLASS_ARRAY_BUFFER,      /* u.array_buffer */\n    JS_CLASS_SHARED_ARRAY_BUFFER, /* u.array_buffer */\n    JS_CLASS_UINT8C_ARRAY,      /* u.array (typed_array) */\n    JS_CLASS_INT8_ARRAY,        /* u.array (typed_array) */\n    JS_CLASS_UINT8_ARRAY,       /* u.array (typed_array) */\n    JS_CLASS_INT16_ARRAY,       /* u.array (typed_array) */\n    JS_CLASS_UINT16_ARRAY,      /* u.array (typed_array) */\n    JS_CLASS_INT32_ARRAY,       /* u.array (typed_array) */\n    JS_CLASS_UINT32_ARRAY,      /* u.array (typed_array) */\n#ifdef CONFIG_BIGNUM\n    JS_CLASS_BIG_INT64_ARRAY,   /* u.array (typed_array) */\n    JS_CLASS_BIG_UINT64_ARRAY,  /* u.array (typed_array) */\n#endif\n    JS_CLASS_FLOAT32_ARRAY,     /* u.array (typed_array) */\n    JS_CLASS_FLOAT64_ARRAY,     /* u.array (typed_array) */\n    JS_CLASS_DATAVIEW,          /* u.typed_array */\n#ifdef CONFIG_BIGNUM\n    JS_CLASS_BIG_INT,           /* u.object_data */\n    JS_CLASS_BIG_FLOAT,         /* u.object_data */\n    JS_CLASS_FLOAT_ENV,         /* u.float_env */\n    JS_CLASS_BIG_DECIMAL,       /* u.object_data */\n    JS_CLASS_OPERATOR_SET,      /* u.operator_set */\n#endif\n    JS_CLASS_MAP,               /* u.map_state */\n    JS_CLASS_SET,               /* u.map_state */\n    JS_CLASS_WEAKMAP,           /* u.map_state */\n    JS_CLASS_WEAKSET,           /* u.map_state */\n    JS_CLASS_MAP_ITERATOR,      /* u.map_iterator_data */\n    JS_CLASS_SET_ITERATOR,      /* u.map_iterator_data */\n    JS_CLASS_ARRAY_ITERATOR,    /* u.array_iterator_data */\n    JS_CLASS_STRING_ITERATOR,   /* u.array_iterator_data */\n    JS_CLASS_REGEXP_STRING_ITERATOR,   /* u.regexp_string_iterator_data */\n    JS_CLASS_GENERATOR,         /* u.generator_data */\n    JS_CLASS_PROXY,             /* u.proxy_data */\n    JS_CLASS_PROMISE,           /* u.promise_data */\n    JS_CLASS_PROMISE_RESOLVE_FUNCTION,  /* u.promise_function_data */\n    JS_CLASS_PROMISE_REJECT_FUNCTION,   /* u.promise_function_data */\n    JS_CLASS_ASYNC_FUNCTION,            /* u.func */\n    JS_CLASS_ASYNC_FUNCTION_RESOLVE,    /* u.async_function_data */\n    JS_CLASS_ASYNC_FUNCTION_REJECT,     /* u.async_function_data */\n    JS_CLASS_ASYNC_FROM_SYNC_ITERATOR,  /* u.async_from_sync_iterator_data */\n    JS_CLASS_ASYNC_GENERATOR_FUNCTION,  /* u.func */\n    JS_CLASS_ASYNC_GENERATOR,   /* u.async_generator_data */\n\n    JS_CLASS_INIT_COUNT, /* last entry for predefined classes */\n};\n\n/* number of typed array types */\n#define JS_TYPED_ARRAY_COUNT  (JS_CLASS_FLOAT64_ARRAY - JS_CLASS_UINT8C_ARRAY + 1)\nstatic uint8_t const typed_array_size_log2[JS_TYPED_ARRAY_COUNT];\n#define typed_array_size_log2(classid)  (typed_array_size_log2[(classid)- JS_CLASS_UINT8C_ARRAY])\n\ntypedef enum JSErrorEnum {\n    JS_EVAL_ERROR,\n    JS_RANGE_ERROR,\n    JS_REFERENCE_ERROR,\n    JS_SYNTAX_ERROR,\n    JS_TYPE_ERROR,\n    JS_URI_ERROR,\n    JS_INTERNAL_ERROR,\n    JS_AGGREGATE_ERROR,\n    \n    JS_NATIVE_ERROR_COUNT, /* number of different NativeError objects */\n} JSErrorEnum;\n\n#define JS_MAX_LOCAL_VARS 65536\n#define JS_STACK_SIZE_MAX 65534\n#define JS_STRING_LEN_MAX ((1 << 30) - 1)\n\n#define __exception __attribute__((warn_unused_result))\n\ntypedef struct JSShape JSShape;\ntypedef struct JSString JSString;\ntypedef struct JSString JSAtomStruct;\n\ntypedef enum {\n    JS_GC_PHASE_NONE,\n    JS_GC_PHASE_DECREF,\n    JS_GC_PHASE_REMOVE_CYCLES,\n} JSGCPhaseEnum;\n\ntypedef enum OPCodeEnum OPCodeEnum;\n\n#ifdef CONFIG_BIGNUM\n/* function pointers are used for numeric operations so that it is\n   possible to remove some numeric types */\ntypedef struct {\n    JSValue (*to_string)(JSContext *ctx, JSValueConst val);\n    JSValue (*from_string)(JSContext *ctx, const char *buf,\n                           int radix, int flags, slimb_t *pexponent);\n    int (*unary_arith)(JSContext *ctx,\n                       JSValue *pres, OPCodeEnum op, JSValue op1);\n    int (*binary_arith)(JSContext *ctx, OPCodeEnum op,\n                        JSValue *pres, JSValue op1, JSValue op2);\n    int (*compare)(JSContext *ctx, OPCodeEnum op,\n                   JSValue op1, JSValue op2);\n    /* only for bigfloat: */\n    JSValue (*mul_pow10_to_float64)(JSContext *ctx, const bf_t *a,\n                                    int64_t exponent);\n    int (*mul_pow10)(JSContext *ctx, JSValue *sp);\n} JSNumericOperations;\n#endif\n\nstruct JSRuntime {\n    JSMallocFunctions mf;\n    JSMallocState malloc_state;\n    const char *rt_info;\n\n    int atom_hash_size; /* power of two */\n    int atom_count;\n    int atom_size;\n    int atom_count_resize; /* resize hash table at this count */\n    uint32_t *atom_hash;\n    JSAtomStruct **atom_array;\n    int atom_free_index; /* 0 = none */\n\n    int class_count;    /* size of class_array */\n    JSClass *class_array;\n\n    struct list_head context_list; /* list of JSContext.link */\n    /* list of JSGCObjectHeader.link. List of allocated GC objects (used\n       by the garbage collector) */\n    struct list_head gc_obj_list;\n    /* list of JSGCObjectHeader.link. Used during JS_FreeValueRT() */\n    struct list_head gc_zero_ref_count_list; \n    struct list_head tmp_obj_list; /* used during GC */\n    JSGCPhaseEnum gc_phase : 8;\n    size_t malloc_gc_threshold;\n#ifdef DUMP_LEAKS\n    struct list_head string_list; /* list of JSString.link */\n#endif\n    /* stack limitation */\n    uintptr_t stack_size; /* in bytes, 0 if no limit */\n    uintptr_t stack_top;\n    uintptr_t stack_limit; /* lower stack limit */\n    \n    JSValue current_exception;\n    /* true if inside an out of memory error, to avoid recursing */\n    BOOL in_out_of_memory : 8;\n\n    struct JSStackFrame *current_stack_frame;\n\n    JSInterruptHandler *interrupt_handler;\n    void *interrupt_opaque;\n\n    JSHostPromiseRejectionTracker *host_promise_rejection_tracker;\n    void *host_promise_rejection_tracker_opaque;\n    \n    struct list_head job_list; /* list of JSJobEntry.link */\n\n    JSModuleNormalizeFunc *module_normalize_func;\n    JSModuleLoaderFunc *module_loader_func;\n    void *module_loader_opaque;\n\n    BOOL can_block : 8; /* TRUE if Atomics.wait can block */\n    /* used to allocate, free and clone SharedArrayBuffers */\n    JSSharedArrayBufferFunctions sab_funcs;\n    \n    /* Shape hash table */\n    int shape_hash_bits;\n    int shape_hash_size;\n    int shape_hash_count; /* number of hashed shapes */\n    JSShape **shape_hash;\n#ifdef CONFIG_BIGNUM\n    bf_context_t bf_ctx;\n    JSNumericOperations bigint_ops;\n    JSNumericOperations bigfloat_ops;\n    JSNumericOperations bigdecimal_ops;\n    uint32_t operator_count;\n#endif\n    void *user_opaque;\n};\n\nstruct JSClass {\n    uint32_t class_id; /* 0 means free entry */\n    JSAtom class_name;\n    JSClassFinalizer *finalizer;\n    JSClassGCMark *gc_mark;\n    JSClassCall *call;\n    /* pointers for exotic behavior, can be NULL if none are present */\n    const JSClassExoticMethods *exotic;\n};\n\n#define JS_MODE_STRICT (1 << 0)\n#define JS_MODE_STRIP  (1 << 1)\n#define JS_MODE_MATH   (1 << 2)\n\ntypedef struct JSStackFrame {\n    struct JSStackFrame *prev_frame; /* NULL if first stack frame */\n    JSValue cur_func; /* current function, JS_UNDEFINED if the frame is detached */\n    JSValue *arg_buf; /* arguments */\n    JSValue *var_buf; /* variables */\n    struct list_head var_ref_list; /* list of JSVarRef.link */\n    const uint8_t *cur_pc; /* only used in bytecode functions : PC of the\n                        instruction after the call */\n    int arg_count;\n    int js_mode; /* 0 or JS_MODE_MATH for C functions */\n    /* only used in generators. Current stack pointer value. NULL if\n       the function is running. */ \n    JSValue *cur_sp;\n} JSStackFrame;\n\ntypedef enum {\n    JS_GC_OBJ_TYPE_JS_OBJECT,\n    JS_GC_OBJ_TYPE_FUNCTION_BYTECODE,\n    JS_GC_OBJ_TYPE_SHAPE,\n    JS_GC_OBJ_TYPE_VAR_REF,\n    JS_GC_OBJ_TYPE_ASYNC_FUNCTION,\n    JS_GC_OBJ_TYPE_JS_CONTEXT,\n} JSGCObjectTypeEnum;\n\n/* header for GC objects. GC objects are C data structures with a\n   reference count that can reference other GC objects. JS Objects are\n   a particular type of GC object. */\nstruct JSGCObjectHeader {\n    int ref_count; /* must come first, 32-bit */\n    JSGCObjectTypeEnum gc_obj_type : 4;\n    uint8_t mark : 4; /* used by the GC */\n    uint8_t dummy1; /* not used by the GC */\n    uint16_t dummy2; /* not used by the GC */\n    struct list_head link;\n};\n\ntypedef struct JSVarRef {\n    union {\n        JSGCObjectHeader header; /* must come first */\n        struct {\n            int __gc_ref_count; /* corresponds to header.ref_count */\n            uint8_t __gc_mark; /* corresponds to header.mark/gc_obj_type */\n\n            /* 0 : the JSVarRef is on the stack. header.link is an element\n               of JSStackFrame.var_ref_list.\n               1 : the JSVarRef is detached. header.link has the normal meanning \n            */\n            uint8_t is_detached : 1; \n            uint8_t is_arg : 1;\n            uint16_t var_idx; /* index of the corresponding function variable on\n                                 the stack */\n        };\n    };\n    JSValue *pvalue; /* pointer to the value, either on the stack or\n                        to 'value' */\n    JSValue value; /* used when the variable is no longer on the stack */\n} JSVarRef;\n\n#ifdef CONFIG_BIGNUM\ntypedef struct JSFloatEnv {\n    limb_t prec;\n    bf_flags_t flags;\n    unsigned int status;\n} JSFloatEnv;\n\n/* the same structure is used for big integers and big floats. Big\n   integers are never infinite or NaNs */\ntypedef struct JSBigFloat {\n    JSRefCountHeader header; /* must come first, 32-bit */\n    bf_t num;\n} JSBigFloat;\n\ntypedef struct JSBigDecimal {\n    JSRefCountHeader header; /* must come first, 32-bit */\n    bfdec_t num;\n} JSBigDecimal;\n#endif\n\ntypedef enum {\n    JS_AUTOINIT_ID_PROTOTYPE,\n    JS_AUTOINIT_ID_MODULE_NS,\n    JS_AUTOINIT_ID_PROP,\n} JSAutoInitIDEnum;\n\n/* must be large enough to have a negligible runtime cost and small\n   enough to call the interrupt callback often. */\n#define JS_INTERRUPT_COUNTER_INIT 10000\n\nstruct JSContext {\n    JSGCObjectHeader header; /* must come first */\n    JSRuntime *rt;\n    struct list_head link;\n\n    uint16_t binary_object_count;\n    int binary_object_size;\n\n    JSShape *array_shape;   /* initial shape for Array objects */\n\n    JSValue *class_proto;\n    JSValue function_proto;\n    JSValue function_ctor;\n    JSValue array_ctor;\n    JSValue regexp_ctor;\n    JSValue promise_ctor;\n    JSValue native_error_proto[JS_NATIVE_ERROR_COUNT];\n    JSValue iterator_proto;\n    JSValue async_iterator_proto;\n    JSValue array_proto_values;\n    JSValue throw_type_error;\n    JSValue eval_obj;\n\n    JSValue global_obj; /* global object */\n    JSValue global_var_obj; /* contains the global let/const definitions */\n\n    uint64_t random_state;\n#ifdef CONFIG_BIGNUM\n    bf_context_t *bf_ctx;   /* points to rt->bf_ctx, shared by all contexts */\n    JSFloatEnv fp_env; /* global FP environment */\n    BOOL bignum_ext : 8; /* enable math mode */\n    BOOL allow_operator_overloading : 8;\n#endif\n    /* when the counter reaches zero, JSRutime.interrupt_handler is called */\n    int interrupt_counter;\n    BOOL is_error_property_enabled;\n\n    struct list_head loaded_modules; /* list of JSModuleDef.link */\n\n    /* if NULL, RegExp compilation is not supported */\n    JSValue (*compile_regexp)(JSContext *ctx, JSValueConst pattern,\n                              JSValueConst flags);\n    /* if NULL, eval is not supported */\n    JSValue (*eval_internal)(JSContext *ctx, JSValueConst this_obj,\n                             const char *input, size_t input_len,\n                             const char *filename, int flags, int scope_idx);\n    void *user_opaque;\n};\n\ntypedef union JSFloat64Union {\n    double d;\n    uint64_t u64;\n    uint32_t u32[2];\n} JSFloat64Union;\n\nenum {\n    JS_ATOM_TYPE_STRING = 1,\n    JS_ATOM_TYPE_GLOBAL_SYMBOL,\n    JS_ATOM_TYPE_SYMBOL,\n    JS_ATOM_TYPE_PRIVATE,\n};\n\nenum {\n    JS_ATOM_HASH_SYMBOL,\n    JS_ATOM_HASH_PRIVATE,\n};\n\ntypedef enum {\n    JS_ATOM_KIND_STRING,\n    JS_ATOM_KIND_SYMBOL,\n    JS_ATOM_KIND_PRIVATE,\n} JSAtomKindEnum;\n\n#define JS_ATOM_HASH_MASK  ((1 << 30) - 1)\n\nstruct JSString {\n    JSRefCountHeader header; /* must come first, 32-bit */\n    uint32_t len : 31;\n    uint8_t is_wide_char : 1; /* 0 = 8 bits, 1 = 16 bits characters */\n    /* for JS_ATOM_TYPE_SYMBOL: hash = 0, atom_type = 3,\n       for JS_ATOM_TYPE_PRIVATE: hash = 1, atom_type = 3\n       XXX: could change encoding to have one more bit in hash */\n    uint32_t hash : 30;\n    uint8_t atom_type : 2; /* != 0 if atom, JS_ATOM_TYPE_x */\n    uint32_t hash_next; /* atom_index for JS_ATOM_TYPE_SYMBOL */\n#ifdef DUMP_LEAKS\n    struct list_head link; /* string list */\n#endif\n    union {\n        uint8_t str8[0]; /* 8 bit strings will get an extra null terminator */\n        uint16_t str16[0];\n    } u;\n};\n\ntypedef struct JSClosureVar {\n    uint8_t is_local : 1;\n    uint8_t is_arg : 1;\n    uint8_t is_const : 1;\n    uint8_t is_lexical : 1;\n    uint8_t var_kind : 4; /* see JSVarKindEnum */\n    /* 8 bits available */\n    uint16_t var_idx; /* is_local = TRUE: index to a normal variable of the\n                    parent function. otherwise: index to a closure\n                    variable of the parent function */\n    JSAtom var_name;\n} JSClosureVar;\n\n#define ARG_SCOPE_INDEX 1\n#define ARG_SCOPE_END (-2)\n\ntypedef struct JSVarScope {\n    int parent;  /* index into fd->scopes of the enclosing scope */\n    int first;   /* index into fd->vars of the last variable in this scope */\n} JSVarScope;\n\ntypedef enum {\n    /* XXX: add more variable kinds here instead of using bit fields */\n    JS_VAR_NORMAL,\n    JS_VAR_FUNCTION_DECL, /* lexical var with function declaration */\n    JS_VAR_NEW_FUNCTION_DECL, /* lexical var with async/generator\n                                 function declaration */\n    JS_VAR_CATCH,\n    JS_VAR_FUNCTION_NAME, /* function expression name */\n    JS_VAR_PRIVATE_FIELD,\n    JS_VAR_PRIVATE_METHOD,\n    JS_VAR_PRIVATE_GETTER,\n    JS_VAR_PRIVATE_SETTER, /* must come after JS_VAR_PRIVATE_GETTER */\n    JS_VAR_PRIVATE_GETTER_SETTER, /* must come after JS_VAR_PRIVATE_SETTER */\n} JSVarKindEnum;\n\n/* XXX: could use a different structure in bytecode functions to save\n   memory */\ntypedef struct JSVarDef {\n    JSAtom var_name;\n    /* index into fd->scopes of this variable lexical scope */\n    int scope_level;\n    /* during compilation: \n        - if scope_level = 0: scope in which the variable is defined\n        - if scope_level != 0: index into fd->vars of the next\n          variable in the same or enclosing lexical scope\n       in a bytecode function:\n       index into fd->vars of the next\n       variable in the same or enclosing lexical scope\n    */\n    int scope_next;    \n    uint8_t is_const : 1;\n    uint8_t is_lexical : 1;\n    uint8_t is_captured : 1;\n    uint8_t var_kind : 4; /* see JSVarKindEnum */\n    /* only used during compilation: function pool index for lexical\n       variables with var_kind =\n       JS_VAR_FUNCTION_DECL/JS_VAR_NEW_FUNCTION_DECL or scope level of\n       the definition of the 'var' variables (they have scope_level =\n       0) */\n    int func_pool_idx : 24; /* only used during compilation : index in\n                               the constant pool for hoisted function\n                               definition */\n} JSVarDef;\n\n/* for the encoding of the pc2line table */\n#define PC2LINE_BASE     (-1)\n#define PC2LINE_RANGE    5\n#define PC2LINE_OP_FIRST 1\n#define PC2LINE_DIFF_PC_MAX ((255 - PC2LINE_OP_FIRST) / PC2LINE_RANGE)\n\ntypedef enum JSFunctionKindEnum {\n    JS_FUNC_NORMAL = 0,\n    JS_FUNC_GENERATOR = (1 << 0),\n    JS_FUNC_ASYNC = (1 << 1),\n    JS_FUNC_ASYNC_GENERATOR = (JS_FUNC_GENERATOR | JS_FUNC_ASYNC),\n} JSFunctionKindEnum;\n\ntypedef struct JSFunctionBytecode {\n    JSGCObjectHeader header; /* must come first */\n    uint8_t js_mode;\n    uint8_t has_prototype : 1; /* true if a prototype field is necessary */\n    uint8_t has_simple_parameter_list : 1;\n    uint8_t is_derived_class_constructor : 1;\n    /* true if home_object needs to be initialized */\n    uint8_t need_home_object : 1;\n    uint8_t func_kind : 2;\n    uint8_t new_target_allowed : 1;\n    uint8_t super_call_allowed : 1;\n    uint8_t super_allowed : 1;\n    uint8_t arguments_allowed : 1;\n    uint8_t has_debug : 1;\n    uint8_t backtrace_barrier : 1; /* stop backtrace on this function */\n    uint8_t read_only_bytecode : 1;\n    /* XXX: 4 bits available */\n    uint8_t *byte_code_buf; /* (self pointer) */\n    int byte_code_len;\n    JSAtom func_name;\n    JSVarDef *vardefs; /* arguments + local variables (arg_count + var_count) (self pointer) */\n    JSClosureVar *closure_var; /* list of variables in the closure (self pointer) */\n    uint16_t arg_count;\n    uint16_t var_count;\n    uint16_t defined_arg_count; /* for length function property */\n    uint16_t stack_size; /* maximum stack size */\n    JSContext *realm; /* function realm */\n    JSValue *cpool; /* constant pool (self pointer) */\n    int cpool_count;\n    int closure_var_count;\n    struct {\n        /* debug info, move to separate structure to save memory? */\n        JSAtom filename;\n        int line_num;\n        int source_len;\n        int pc2line_len;\n        uint8_t *pc2line_buf;\n        char *source;\n    } debug;\n} JSFunctionBytecode;\n\ntypedef struct JSBoundFunction {\n    JSValue func_obj;\n    JSValue this_val;\n    int argc;\n    JSValue argv[0];\n} JSBoundFunction;\n\ntypedef enum JSIteratorKindEnum {\n    JS_ITERATOR_KIND_KEY,\n    JS_ITERATOR_KIND_VALUE,\n    JS_ITERATOR_KIND_KEY_AND_VALUE,\n} JSIteratorKindEnum;\n\ntypedef struct JSForInIterator {\n    JSValue obj;\n    BOOL is_array;\n    uint32_t array_length;\n    uint32_t idx;\n} JSForInIterator;\n\ntypedef struct JSRegExp {\n    JSString *pattern;\n    JSString *bytecode; /* also contains the flags */\n} JSRegExp;\n\ntypedef struct JSProxyData {\n    JSValue target;\n    JSValue handler;\n    uint8_t is_func;\n    uint8_t is_revoked;\n} JSProxyData;\n\ntypedef struct JSArrayBuffer {\n    int byte_length; /* 0 if detached */\n    uint8_t detached;\n    uint8_t shared; /* if shared, the array buffer cannot be detached */\n    uint8_t *data; /* NULL if detached */\n    struct list_head array_list;\n    void *opaque;\n    JSFreeArrayBufferDataFunc *free_func;\n} JSArrayBuffer;\n\ntypedef struct JSTypedArray {\n    struct list_head link; /* link to arraybuffer */\n    JSObject *obj; /* back pointer to the TypedArray/DataView object */\n    JSObject *buffer; /* based array buffer */\n    uint32_t offset; /* offset in the array buffer */\n    uint32_t length; /* length in the array buffer */\n} JSTypedArray;\n\ntypedef struct JSAsyncFunctionState {\n    JSValue this_val; /* 'this' generator argument */\n    int argc; /* number of function arguments */\n    BOOL throw_flag; /* used to throw an exception in JS_CallInternal() */\n    JSStackFrame frame;\n} JSAsyncFunctionState;\n\n/* XXX: could use an object instead to avoid the\n   JS_TAG_ASYNC_FUNCTION tag for the GC */\ntypedef struct JSAsyncFunctionData {\n    JSGCObjectHeader header; /* must come first */\n    JSValue resolving_funcs[2];\n    BOOL is_active; /* true if the async function state is valid */\n    JSAsyncFunctionState func_state;\n} JSAsyncFunctionData;\n\ntypedef enum {\n   /* binary operators */\n   JS_OVOP_ADD,\n   JS_OVOP_SUB,\n   JS_OVOP_MUL,\n   JS_OVOP_DIV,\n   JS_OVOP_MOD,\n   JS_OVOP_POW,\n   JS_OVOP_OR,\n   JS_OVOP_AND,\n   JS_OVOP_XOR,\n   JS_OVOP_SHL,\n   JS_OVOP_SAR,\n   JS_OVOP_SHR,\n   JS_OVOP_EQ,\n   JS_OVOP_LESS,\n\n   JS_OVOP_BINARY_COUNT,\n   /* unary operators */\n   JS_OVOP_POS = JS_OVOP_BINARY_COUNT,\n   JS_OVOP_NEG,\n   JS_OVOP_INC,\n   JS_OVOP_DEC,\n   JS_OVOP_NOT,\n\n   JS_OVOP_COUNT,\n} JSOverloadableOperatorEnum;\n\ntypedef struct {\n    uint32_t operator_index;\n    JSObject *ops[JS_OVOP_BINARY_COUNT]; /* self operators */\n} JSBinaryOperatorDefEntry;\n\ntypedef struct {\n    int count;\n    JSBinaryOperatorDefEntry *tab;\n} JSBinaryOperatorDef;\n\ntypedef struct {\n    uint32_t operator_counter;\n    BOOL is_primitive; /* OperatorSet for a primitive type */\n    /* NULL if no operator is defined */\n    JSObject *self_ops[JS_OVOP_COUNT]; /* self operators */\n    JSBinaryOperatorDef left;\n    JSBinaryOperatorDef right;\n} JSOperatorSetData;\n\ntypedef struct JSReqModuleEntry {\n    JSAtom module_name;\n    JSModuleDef *module; /* used using resolution */\n} JSReqModuleEntry;\n\ntypedef enum JSExportTypeEnum {\n    JS_EXPORT_TYPE_LOCAL,\n    JS_EXPORT_TYPE_INDIRECT,\n} JSExportTypeEnum;\n\ntypedef struct JSExportEntry {\n    union {\n        struct {\n            int var_idx; /* closure variable index */\n            JSVarRef *var_ref; /* if != NULL, reference to the variable */\n        } local; /* for local export */\n        int req_module_idx; /* module for indirect export */\n    } u;\n    JSExportTypeEnum export_type;\n    JSAtom local_name; /* '*' if export ns from. not used for local\n                          export after compilation */\n    JSAtom export_name; /* exported variable name */\n} JSExportEntry;\n\ntypedef struct JSStarExportEntry {\n    int req_module_idx; /* in req_module_entries */\n} JSStarExportEntry;\n\ntypedef struct JSImportEntry {\n    int var_idx; /* closure variable index */\n    JSAtom import_name;\n    int req_module_idx; /* in req_module_entries */\n} JSImportEntry;\n\nstruct JSModuleDef {\n    JSRefCountHeader header; /* must come first, 32-bit */\n    JSAtom module_name;\n    struct list_head link;\n\n    JSReqModuleEntry *req_module_entries;\n    int req_module_entries_count;\n    int req_module_entries_size;\n\n    JSExportEntry *export_entries;\n    int export_entries_count;\n    int export_entries_size;\n\n    JSStarExportEntry *star_export_entries;\n    int star_export_entries_count;\n    int star_export_entries_size;\n\n    JSImportEntry *import_entries;\n    int import_entries_count;\n    int import_entries_size;\n\n    JSValue module_ns;\n    JSValue func_obj; /* only used for JS modules */\n    JSModuleInitFunc *init_func; /* only used for C modules */\n    BOOL resolved : 8;\n    BOOL func_created : 8;\n    BOOL instantiated : 8;\n    BOOL evaluated : 8;\n    BOOL eval_mark : 8; /* temporary use during js_evaluate_module() */\n    /* true if evaluation yielded an exception. It is saved in\n       eval_exception */\n    BOOL eval_has_exception : 8; \n    JSValue eval_exception;\n    JSValue meta_obj; /* for import.meta */\n};\n\ntypedef struct JSJobEntry {\n    struct list_head link;\n    JSContext *ctx;\n    JSJobFunc *job_func;\n    int argc;\n    JSValue argv[0];\n} JSJobEntry;\n\ntypedef struct JSProperty {\n    union {\n        JSValue value;      /* JS_PROP_NORMAL */\n        struct {            /* JS_PROP_GETSET */\n            JSObject *getter; /* NULL if undefined */\n            JSObject *setter; /* NULL if undefined */\n        } getset;\n        JSVarRef *var_ref;  /* JS_PROP_VARREF */\n        struct {            /* JS_PROP_AUTOINIT */\n            /* in order to use only 2 pointers, we compress the realm\n               and the init function pointer */\n            uintptr_t realm_and_id; /* realm and init_id (JS_AUTOINIT_ID_x)\n                                       in the 2 low bits */\n            void *opaque;\n        } init;\n    } u;\n} JSProperty;\n\n#define JS_PROP_INITIAL_SIZE 2\n#define JS_PROP_INITIAL_HASH_SIZE 4 /* must be a power of two */\n#define JS_ARRAY_INITIAL_SIZE 2\n\ntypedef struct JSShapeProperty {\n    uint32_t hash_next : 26; /* 0 if last in list */\n    uint32_t flags : 6;   /* JS_PROP_XXX */\n    JSAtom atom; /* JS_ATOM_NULL = free property entry */\n} JSShapeProperty;\n\nstruct JSShape {\n    /* hash table of size hash_mask + 1 before the start of the\n       structure (see prop_hash_end()). */\n    JSGCObjectHeader header;\n    /* true if the shape is inserted in the shape hash table. If not,\n       JSShape.hash is not valid */\n    uint8_t is_hashed;\n    /* If true, the shape may have small array index properties 'n' with 0\n       <= n <= 2^31-1. If false, the shape is guaranteed not to have\n       small array index properties */\n    uint8_t has_small_array_index;\n    uint32_t hash; /* current hash value */\n    uint32_t prop_hash_mask;\n    int prop_size; /* allocated properties */\n    int prop_count; /* include deleted properties */\n    int deleted_prop_count;\n    JSShape *shape_hash_next; /* in JSRuntime.shape_hash[h] list */\n    JSObject *proto;\n    JSShapeProperty prop[0]; /* prop_size elements */\n};\n\nstruct JSObject {\n    union {\n        JSGCObjectHeader header;\n        struct {\n            int __gc_ref_count; /* corresponds to header.ref_count */\n            uint8_t __gc_mark; /* corresponds to header.mark/gc_obj_type */\n            \n            uint8_t extensible : 1;\n            uint8_t free_mark : 1; /* only used when freeing objects with cycles */\n            uint8_t is_exotic : 1; /* TRUE if object has exotic property handlers */\n            uint8_t fast_array : 1; /* TRUE if u.array is used for get/put (for JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS and typed arrays) */\n            uint8_t is_constructor : 1; /* TRUE if object is a constructor function */\n            uint8_t is_uncatchable_error : 1; /* if TRUE, error is not catchable */\n            uint8_t tmp_mark : 1; /* used in JS_WriteObjectRec() */\n            uint8_t is_HTMLDDA : 1; /* specific annex B IsHtmlDDA behavior */\n            uint16_t class_id; /* see JS_CLASS_x */\n        };\n    };\n    /* byte offsets: 16/24 */\n    JSShape *shape; /* prototype and property names + flag */\n    JSProperty *prop; /* array of properties */\n    /* byte offsets: 24/40 */\n    struct JSMapRecord *first_weak_ref; /* XXX: use a bit and an external hash table? */\n    /* byte offsets: 28/48 */\n    union {\n        void *opaque;\n        struct JSBoundFunction *bound_function; /* JS_CLASS_BOUND_FUNCTION */\n        struct JSCFunctionDataRecord *c_function_data_record; /* JS_CLASS_C_FUNCTION_DATA */\n        struct JSForInIterator *for_in_iterator; /* JS_CLASS_FOR_IN_ITERATOR */\n        struct JSArrayBuffer *array_buffer; /* JS_CLASS_ARRAY_BUFFER, JS_CLASS_SHARED_ARRAY_BUFFER */\n        struct JSTypedArray *typed_array; /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_DATAVIEW */\n#ifdef CONFIG_BIGNUM\n        struct JSFloatEnv *float_env; /* JS_CLASS_FLOAT_ENV */\n        struct JSOperatorSetData *operator_set; /* JS_CLASS_OPERATOR_SET */\n#endif\n        struct JSMapState *map_state;   /* JS_CLASS_MAP..JS_CLASS_WEAKSET */\n        struct JSMapIteratorData *map_iterator_data; /* JS_CLASS_MAP_ITERATOR, JS_CLASS_SET_ITERATOR */\n        struct JSArrayIteratorData *array_iterator_data; /* JS_CLASS_ARRAY_ITERATOR, JS_CLASS_STRING_ITERATOR */\n        struct JSRegExpStringIteratorData *regexp_string_iterator_data; /* JS_CLASS_REGEXP_STRING_ITERATOR */\n        struct JSGeneratorData *generator_data; /* JS_CLASS_GENERATOR */\n        struct JSProxyData *proxy_data; /* JS_CLASS_PROXY */\n        struct JSPromiseData *promise_data; /* JS_CLASS_PROMISE */\n        struct JSPromiseFunctionData *promise_function_data; /* JS_CLASS_PROMISE_RESOLVE_FUNCTION, JS_CLASS_PROMISE_REJECT_FUNCTION */\n        struct JSAsyncFunctionData *async_function_data; /* JS_CLASS_ASYNC_FUNCTION_RESOLVE, JS_CLASS_ASYNC_FUNCTION_REJECT */\n        struct JSAsyncFromSyncIteratorData *async_from_sync_iterator_data; /* JS_CLASS_ASYNC_FROM_SYNC_ITERATOR */\n        struct JSAsyncGeneratorData *async_generator_data; /* JS_CLASS_ASYNC_GENERATOR */\n        struct { /* JS_CLASS_BYTECODE_FUNCTION: 12/24 bytes */\n            /* also used by JS_CLASS_GENERATOR_FUNCTION, JS_CLASS_ASYNC_FUNCTION and JS_CLASS_ASYNC_GENERATOR_FUNCTION */\n            struct JSFunctionBytecode *function_bytecode;\n            JSVarRef **var_refs;\n            JSObject *home_object; /* for 'super' access */\n        } func;\n        struct { /* JS_CLASS_C_FUNCTION: 12/20 bytes */\n            JSContext *realm;\n            JSCFunctionType c_function;\n            uint8_t length;\n            uint8_t cproto;\n            int32_t magic;\n        } cfunc;\n        /* array part for fast arrays and typed arrays */\n        struct { /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS, JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */\n            union {\n                uint32_t size;          /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS */\n                struct JSTypedArray *typed_array; /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */\n            } u1;\n            union {\n                JSValue *values;        /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS */ \n                void *ptr;              /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */\n                int8_t *int8_ptr;       /* JS_CLASS_INT8_ARRAY */\n                uint8_t *uint8_ptr;     /* JS_CLASS_UINT8_ARRAY, JS_CLASS_UINT8C_ARRAY */\n                int16_t *int16_ptr;     /* JS_CLASS_INT16_ARRAY */\n                uint16_t *uint16_ptr;   /* JS_CLASS_UINT16_ARRAY */\n                int32_t *int32_ptr;     /* JS_CLASS_INT32_ARRAY */\n                uint32_t *uint32_ptr;   /* JS_CLASS_UINT32_ARRAY */\n                int64_t *int64_ptr;     /* JS_CLASS_INT64_ARRAY */\n                uint64_t *uint64_ptr;   /* JS_CLASS_UINT64_ARRAY */\n                float *float_ptr;       /* JS_CLASS_FLOAT32_ARRAY */\n                double *double_ptr;     /* JS_CLASS_FLOAT64_ARRAY */\n            } u;\n            uint32_t count; /* <= 2^31-1. 0 for a detached typed array */\n        } array;    /* 12/20 bytes */\n        JSRegExp regexp;    /* JS_CLASS_REGEXP: 8/16 bytes */\n        JSValue object_data;    /* for JS_SetObjectData(): 8/16/16 bytes */\n    } u;\n    /* byte sizes: 40/48/72 */\n};\nenum {\n    __JS_ATOM_NULL = JS_ATOM_NULL,\n#define DEF(name, str) JS_ATOM_ ## name,\n#include \"quickjs-atom.h\"\n#undef DEF\n    JS_ATOM_END,\n};\n#define JS_ATOM_LAST_KEYWORD JS_ATOM_super\n#define JS_ATOM_LAST_STRICT_KEYWORD JS_ATOM_yield\n\nstatic const char js_atom_init[] =\n#define DEF(name, str) str \"\\0\"\n#include \"quickjs-atom.h\"\n#undef DEF\n;\n\ntypedef enum OPCodeFormat {\n#define FMT(f) OP_FMT_ ## f,\n#define DEF(id, size, n_pop, n_push, f)\n#include \"quickjs-opcode.h\"\n#undef DEF\n#undef FMT\n} OPCodeFormat;\n\nenum OPCodeEnum {\n#define FMT(f)\n#define DEF(id, size, n_pop, n_push, f) OP_ ## id,\n#define def(id, size, n_pop, n_push, f)\n#include \"quickjs-opcode.h\"\n#undef def\n#undef DEF\n#undef FMT\n    OP_COUNT, /* excluding temporary opcodes */\n    /* temporary opcodes : overlap with the short opcodes */\n    OP_TEMP_START = OP_nop + 1,\n    OP___dummy = OP_TEMP_START - 1,\n#define FMT(f)\n#define DEF(id, size, n_pop, n_push, f)\n#define def(id, size, n_pop, n_push, f) OP_ ## id,\n#include \"quickjs-opcode.h\"\n#undef def\n#undef DEF\n#undef FMT\n    OP_TEMP_END,\n};\n\nstatic int JS_InitAtoms(JSRuntime *rt);\nstatic JSAtom __JS_NewAtomInit(JSRuntime *rt, const char *str, int len,\n                               int atom_type);\nstatic void JS_FreeAtomStruct(JSRuntime *rt, JSAtomStruct *p);\nstatic void free_function_bytecode(JSRuntime *rt, JSFunctionBytecode *b);\nstatic JSValue js_call_c_function(JSContext *ctx, JSValueConst func_obj,\n                                  JSValueConst this_obj,\n                                  int argc, JSValueConst *argv, int flags);\nstatic JSValue js_call_bound_function(JSContext *ctx, JSValueConst func_obj,\n                                      JSValueConst this_obj,\n                                      int argc, JSValueConst *argv, int flags);\nstatic JSValue JS_CallInternal(JSContext *ctx, JSValueConst func_obj,\n                               JSValueConst this_obj, JSValueConst new_target,\n                               int argc, JSValue *argv, int flags);\nstatic JSValue JS_CallConstructorInternal(JSContext *ctx,\n                                          JSValueConst func_obj,\n                                          JSValueConst new_target,\n                                          int argc, JSValue *argv, int flags);\nstatic JSValue JS_CallFree(JSContext *ctx, JSValue func_obj, JSValueConst this_obj,\n                           int argc, JSValueConst *argv);\nstatic JSValue JS_InvokeFree(JSContext *ctx, JSValue this_val, JSAtom atom,\n                             int argc, JSValueConst *argv);\nstatic __exception int JS_ToArrayLengthFree(JSContext *ctx, uint32_t *plen,\n                                            JSValue val, BOOL is_array_ctor);\nstatic JSValue JS_EvalObject(JSContext *ctx, JSValueConst this_obj,\n                             JSValueConst val, int flags, int scope_idx);\nJSValue __attribute__((format(printf, 2, 3))) JS_ThrowInternalError(JSContext *ctx, const char *fmt, ...);\nstatic __maybe_unused void JS_DumpAtoms(JSRuntime *rt);\nstatic __maybe_unused void JS_DumpString(JSRuntime *rt,\n                                                  const JSString *p);\nstatic __maybe_unused void JS_DumpObjectHeader(JSRuntime *rt);\nstatic __maybe_unused void JS_DumpObject(JSRuntime *rt, JSObject *p);\nstatic __maybe_unused void JS_DumpGCObject(JSRuntime *rt, JSGCObjectHeader *p);\nstatic __maybe_unused void JS_DumpValueShort(JSRuntime *rt,\n                                                      JSValueConst val);\nstatic __maybe_unused void JS_DumpValue(JSContext *ctx, JSValueConst val);\nstatic __maybe_unused void JS_PrintValue(JSContext *ctx,\n                                                  const char *str,\n                                                  JSValueConst val);\nstatic __maybe_unused void JS_DumpShapes(JSRuntime *rt);\nstatic JSValue js_function_apply(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv, int magic);\nstatic void js_array_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_array_mark(JSRuntime *rt, JSValueConst val,\n                          JS_MarkFunc *mark_func);\nstatic void js_object_data_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_object_data_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_c_function_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_c_function_mark(JSRuntime *rt, JSValueConst val,\n                               JS_MarkFunc *mark_func);\nstatic void js_bytecode_function_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_bytecode_function_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_bound_function_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_bound_function_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_for_in_iterator_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_for_in_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_regexp_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_array_buffer_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_typed_array_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_typed_array_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_proxy_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_proxy_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_map_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_map_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_map_iterator_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_map_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_array_iterator_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_array_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_regexp_string_iterator_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_regexp_string_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_generator_finalizer(JSRuntime *rt, JSValue obj);\nstatic void js_generator_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_promise_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_promise_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_promise_resolve_function_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_promise_resolve_function_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\n#ifdef CONFIG_BIGNUM\nstatic void js_operator_set_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_operator_set_mark(JSRuntime *rt, JSValueConst val,\n                                 JS_MarkFunc *mark_func);\n#endif\nstatic JSValue JS_ToStringFree(JSContext *ctx, JSValue val);\nstatic int JS_ToBoolFree(JSContext *ctx, JSValue val);\nstatic int JS_ToInt32Free(JSContext *ctx, int32_t *pres, JSValue val);\nstatic int JS_ToFloat64Free(JSContext *ctx, double *pres, JSValue val);\nstatic int JS_ToUint8ClampFree(JSContext *ctx, int32_t *pres, JSValue val);\nstatic JSValue js_compile_regexp(JSContext *ctx, JSValueConst pattern,\n                                 JSValueConst flags);\nstatic JSValue js_regexp_constructor_internal(JSContext *ctx, JSValueConst ctor,\n                                              JSValue pattern, JSValue bc);\nstatic void gc_decref(JSRuntime *rt);\nstatic int JS_NewClass1(JSRuntime *rt, JSClassID class_id,\n                        const JSClassDef *class_def, JSAtom name);\n\ntypedef enum JSStrictEqModeEnum {\n    JS_EQ_STRICT,\n    JS_EQ_SAME_VALUE,\n    JS_EQ_SAME_VALUE_ZERO,\n} JSStrictEqModeEnum;\n\nstatic BOOL js_strict_eq2(JSContext *ctx, JSValue op1, JSValue op2,\n                          JSStrictEqModeEnum eq_mode);\nstatic BOOL js_strict_eq(JSContext *ctx, JSValue op1, JSValue op2);\nstatic BOOL js_same_value(JSContext *ctx, JSValueConst op1, JSValueConst op2);\nstatic BOOL js_same_value_zero(JSContext *ctx, JSValueConst op1, JSValueConst op2);\nstatic JSValue JS_ToObject(JSContext *ctx, JSValueConst val);\nstatic JSValue JS_ToObjectFree(JSContext *ctx, JSValue val);\nstatic JSProperty *add_property(JSContext *ctx,\n                                JSObject *p, JSAtom prop, int prop_flags);\n#ifdef CONFIG_BIGNUM\nstatic void js_float_env_finalizer(JSRuntime *rt, JSValue val);\nstatic JSValue JS_NewBigFloat(JSContext *ctx);\nstatic inline bf_t *JS_GetBigFloat(JSValueConst val)\n{\n    JSBigFloat *p = JS_VALUE_GET_PTR(val);\n    return &p->num;\n}\nstatic JSValue JS_NewBigDecimal(JSContext *ctx);\nstatic inline bfdec_t *JS_GetBigDecimal(JSValueConst val)\n{\n    JSBigDecimal *p = JS_VALUE_GET_PTR(val);\n    return &p->num;\n}\nstatic JSValue JS_NewBigInt(JSContext *ctx);\nstatic inline bf_t *JS_GetBigInt(JSValueConst val)\n{\n    JSBigFloat *p = JS_VALUE_GET_PTR(val);\n    return &p->num;\n}\nstatic JSValue JS_CompactBigInt1(JSContext *ctx, JSValue val,\n                                 BOOL convert_to_safe_integer);\nstatic JSValue JS_CompactBigInt(JSContext *ctx, JSValue val);\nstatic int JS_ToBigInt64Free(JSContext *ctx, int64_t *pres, JSValue val);\nstatic bf_t *JS_ToBigInt(JSContext *ctx, bf_t *buf, JSValueConst val);\nstatic void JS_FreeBigInt(JSContext *ctx, bf_t *a, bf_t *buf);\nstatic bf_t *JS_ToBigFloat(JSContext *ctx, bf_t *buf, JSValueConst val);\nstatic JSValue JS_ToBigDecimalFree(JSContext *ctx, JSValue val,\n                                   BOOL allow_null_or_undefined);\nstatic bfdec_t *JS_ToBigDecimal(JSContext *ctx, JSValueConst val);\n#endif\nJSValue JS_ThrowOutOfMemory(JSContext *ctx);\nstatic JSValue JS_ThrowTypeErrorRevokedProxy(JSContext *ctx);\nstatic JSValue js_proxy_getPrototypeOf(JSContext *ctx, JSValueConst obj);\nstatic int js_proxy_setPrototypeOf(JSContext *ctx, JSValueConst obj,\n                                   JSValueConst proto_val, BOOL throw_flag);\nstatic int js_proxy_isExtensible(JSContext *ctx, JSValueConst obj);\nstatic int js_proxy_preventExtensions(JSContext *ctx, JSValueConst obj);\nstatic int js_proxy_isArray(JSContext *ctx, JSValueConst obj);\nstatic int JS_CreateProperty(JSContext *ctx, JSObject *p,\n                             JSAtom prop, JSValueConst val,\n                             JSValueConst getter, JSValueConst setter,\n                             int flags);\nstatic int js_string_memcmp(const JSString *p1, const JSString *p2, int len);\nstatic void reset_weak_ref(JSRuntime *rt, JSObject *p);\nstatic JSValue js_array_buffer_constructor3(JSContext *ctx,\n                                            JSValueConst new_target,\n                                            uint64_t len, JSClassID class_id,\n                                            uint8_t *buf,\n                                            JSFreeArrayBufferDataFunc *free_func,\n                                            void *opaque, BOOL alloc_flag);\nstatic JSArrayBuffer *js_get_array_buffer(JSContext *ctx, JSValueConst obj);\nstatic JSValue js_typed_array_constructor(JSContext *ctx,\n                                          JSValueConst this_val,\n                                          int argc, JSValueConst *argv,\n                                          int classid);\nstatic BOOL typed_array_is_detached(JSContext *ctx, JSObject *p);\nstatic uint32_t typed_array_get_length(JSContext *ctx, JSObject *p);\nstatic JSValue JS_ThrowTypeErrorDetachedArrayBuffer(JSContext *ctx);\nstatic JSVarRef *get_var_ref(JSContext *ctx, JSStackFrame *sf, int var_idx,\n                             BOOL is_arg);\nstatic JSValue js_generator_function_call(JSContext *ctx, JSValueConst func_obj,\n                                          JSValueConst this_obj,\n                                          int argc, JSValueConst *argv,\n                                          int flags);\nstatic void js_async_function_resolve_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_async_function_resolve_mark(JSRuntime *rt, JSValueConst val,\n                                           JS_MarkFunc *mark_func);\nstatic JSValue JS_EvalInternal(JSContext *ctx, JSValueConst this_obj,\n                               const char *input, size_t input_len,\n                               const char *filename, int flags, int scope_idx);\nstatic void js_free_module_def(JSContext *ctx, JSModuleDef *m);\nstatic void js_mark_module_def(JSRuntime *rt, JSModuleDef *m,\n                               JS_MarkFunc *mark_func);\nstatic JSValue js_import_meta(JSContext *ctx);\nstatic JSValue js_dynamic_import(JSContext *ctx, JSValueConst specifier);\nstatic void free_var_ref(JSRuntime *rt, JSVarRef *var_ref);\nstatic JSValue js_new_promise_capability(JSContext *ctx,\n                                         JSValue *resolving_funcs,\n                                         JSValueConst ctor);\nstatic __exception int perform_promise_then(JSContext *ctx,\n                                            JSValueConst promise,\n                                            JSValueConst *resolve_reject,\n                                            JSValueConst *cap_resolving_funcs);\nstatic JSValue js_promise_resolve(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv, int magic);\nstatic int js_string_compare(JSContext *ctx,\n                             const JSString *p1, const JSString *p2);\nstatic JSValue JS_ToNumber(JSContext *ctx, JSValueConst val);\nstatic int JS_SetPropertyValue(JSContext *ctx, JSValueConst this_obj,\n                               JSValue prop, JSValue val, int flags);\nstatic int JS_NumberIsInteger(JSContext *ctx, JSValueConst val);\nstatic BOOL JS_NumberIsNegativeOrMinusZero(JSContext *ctx, JSValueConst val);\nstatic JSValue JS_ToNumberFree(JSContext *ctx, JSValue val);\nstatic int JS_GetOwnPropertyInternal(JSContext *ctx, JSPropertyDescriptor *desc,\n                                     JSObject *p, JSAtom prop);\nstatic void js_free_desc(JSContext *ctx, JSPropertyDescriptor *desc);\nstatic void async_func_mark(JSRuntime *rt, JSAsyncFunctionState *s,\n                            JS_MarkFunc *mark_func);\nstatic void JS_AddIntrinsicBasicObjects(JSContext *ctx);\nstatic void js_free_shape(JSRuntime *rt, JSShape *sh);\nstatic void js_free_shape_null(JSRuntime *rt, JSShape *sh);\nstatic int js_shape_prepare_update(JSContext *ctx, JSObject *p,\n                                   JSShapeProperty **pprs);\nstatic int init_shape_hash(JSRuntime *rt);\nstatic __exception int js_get_length32(JSContext *ctx, uint32_t *pres,\n                                       JSValueConst obj);\nstatic __exception int js_get_length64(JSContext *ctx, int64_t *pres,\n                                       JSValueConst obj);\nstatic void free_arg_list(JSContext *ctx, JSValue *tab, uint32_t len);\nstatic JSValue *build_arg_list(JSContext *ctx, uint32_t *plen,\n                               JSValueConst array_arg);\nstatic BOOL js_get_fast_array(JSContext *ctx, JSValueConst obj,\n                              JSValue **arrpp, uint32_t *countp);\nstatic JSValue JS_CreateAsyncFromSyncIterator(JSContext *ctx,\n                                              JSValueConst sync_iter);\nstatic void js_c_function_data_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_c_function_data_mark(JSRuntime *rt, JSValueConst val,\n                                    JS_MarkFunc *mark_func);\nstatic JSValue js_c_function_data_call(JSContext *ctx, JSValueConst func_obj,\n                                       JSValueConst this_val,\n                                       int argc, JSValueConst *argv, int flags);\nstatic JSAtom js_symbol_to_atom(JSContext *ctx, JSValue val);\nstatic void add_gc_object(JSRuntime *rt, JSGCObjectHeader *h,\n                          JSGCObjectTypeEnum type);\nstatic void remove_gc_object(JSGCObjectHeader *h);\nstatic void js_async_function_free0(JSRuntime *rt, JSAsyncFunctionData *s);\nstatic JSValue js_instantiate_prototype(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque);\nstatic JSValue js_module_ns_autoinit(JSContext *ctx, JSObject *p, JSAtom atom,\n                                 void *opaque);\nstatic JSValue JS_InstantiateFunctionListItem2(JSContext *ctx, JSObject *p,\n                                               JSAtom atom, void *opaque);\nvoid JS_SetUncatchableError(JSContext *ctx, JSValueConst val, BOOL flag);\n\nstatic const JSClassExoticMethods js_arguments_exotic_methods;\nstatic const JSClassExoticMethods js_string_exotic_methods;\nstatic const JSClassExoticMethods js_proxy_exotic_methods;\nstatic const JSClassExoticMethods js_module_ns_exotic_methods;\nstatic JSClassID js_class_id_alloc = JS_CLASS_INIT_COUNT;\n\nstatic void js_trigger_gc(JSRuntime *rt, size_t size)\n{\n    BOOL force_gc;\n#ifdef FORCE_GC_AT_MALLOC\n    force_gc = TRUE;\n#else\n    force_gc = ((rt->malloc_state.malloc_size + size) >\n                rt->malloc_gc_threshold);\n#endif\n    if (force_gc) {\n#ifdef DUMP_GC\n        printf(\"GC: size=%\" PRIu64 \"\\n\",\n               (uint64_t)rt->malloc_state.malloc_size);\n#endif\n        JS_RunGC(rt);\n        rt->malloc_gc_threshold = rt->malloc_state.malloc_size +\n            (rt->malloc_state.malloc_size >> 1);\n    }\n}\n\nstatic size_t js_malloc_usable_size_unknown(const void *ptr)\n{\n    return 0;\n}\n\nvoid *js_malloc_rt(JSRuntime *rt, size_t size)\n{\n    return rt->mf.js_malloc(&rt->malloc_state, size);\n}\n\nvoid js_free_rt(JSRuntime *rt, void *ptr)\n{\n    rt->mf.js_free(&rt->malloc_state, ptr);\n}\n\nvoid *js_realloc_rt(JSRuntime *rt, void *ptr, size_t size)\n{\n    return rt->mf.js_realloc(&rt->malloc_state, ptr, size);\n}\n\nsize_t js_malloc_usable_size_rt(JSRuntime *rt, const void *ptr)\n{\n    return rt->mf.js_malloc_usable_size(ptr);\n}\n\nvoid *js_mallocz_rt(JSRuntime *rt, size_t size)\n{\n    void *ptr;\n    ptr = js_malloc_rt(rt, size);\n    if (!ptr)\n        return NULL;\n    return memset(ptr, 0, size);\n}\n\n#ifdef CONFIG_BIGNUM\n/* called by libbf */\nstatic void *js_bf_realloc(void *opaque, void *ptr, size_t size)\n{\n    JSRuntime *rt = opaque;\n    return js_realloc_rt(rt, ptr, size);\n}\n#endif /* CONFIG_BIGNUM */\n\n/* Throw out of memory in case of error */\nvoid *js_malloc(JSContext *ctx, size_t size)\n{\n    void *ptr;\n    ptr = js_malloc_rt(ctx->rt, size);\n    if (unlikely(!ptr)) {\n        JS_ThrowOutOfMemory(ctx);\n        return NULL;\n    }\n    return ptr;\n}\n\n/* Throw out of memory in case of error */\nvoid *js_mallocz(JSContext *ctx, size_t size)\n{\n    void *ptr;\n    ptr = js_mallocz_rt(ctx->rt, size);\n    if (unlikely(!ptr)) {\n        JS_ThrowOutOfMemory(ctx);\n        return NULL;\n    }\n    return ptr;\n}\n\nvoid js_free(JSContext *ctx, void *ptr)\n{\n    js_free_rt(ctx->rt, ptr);\n}\n\n/* Throw out of memory in case of error */\nvoid *js_realloc(JSContext *ctx, void *ptr, size_t size)\n{\n    void *ret;\n    ret = js_realloc_rt(ctx->rt, ptr, size);\n    if (unlikely(!ret && size != 0)) {\n        JS_ThrowOutOfMemory(ctx);\n        return NULL;\n    }\n    return ret;\n}\n\n/* store extra allocated size in *pslack if successful */\nvoid *js_realloc2(JSContext *ctx, void *ptr, size_t size, size_t *pslack)\n{\n    void *ret;\n    ret = js_realloc_rt(ctx->rt, ptr, size);\n    if (unlikely(!ret && size != 0)) {\n        JS_ThrowOutOfMemory(ctx);\n        return NULL;\n    }\n    if (pslack) {\n        size_t new_size = js_malloc_usable_size_rt(ctx->rt, ret);\n        *pslack = (new_size > size) ? new_size - size : 0;\n    }\n    return ret;\n}\n\nsize_t js_malloc_usable_size(JSContext *ctx, const void *ptr)\n{\n    return js_malloc_usable_size_rt(ctx->rt, ptr);\n}\n\n/* Throw out of memory exception in case of error */\nchar *js_strndup(JSContext *ctx, const char *s, size_t n)\n{\n    char *ptr;\n    ptr = js_malloc(ctx, n + 1);\n    if (ptr) {\n        memcpy(ptr, s, n);\n        ptr[n] = '\\0';\n    }\n    return ptr;\n}\n\nchar *js_strdup(JSContext *ctx, const char *str)\n{\n    return js_strndup(ctx, str, strlen(str));\n}\n\nstatic no_inline int js_realloc_array(JSContext *ctx, void **parray,\n                                      int elem_size, int *psize, int req_size)\n{\n    int new_size;\n    size_t slack;\n    void *new_array;\n    /* XXX: potential arithmetic overflow */\n    new_size = max_int(req_size, *psize * 3 / 2);\n    new_array = js_realloc2(ctx, *parray, new_size * elem_size, &slack);\n    if (!new_array)\n        return -1;\n    new_size += slack / elem_size;\n    *psize = new_size;\n    *parray = new_array;\n    return 0;\n}\n\n/* resize the array and update its size if req_size > *psize */\nstatic inline int js_resize_array(JSContext *ctx, void **parray, int elem_size,\n                                  int *psize, int req_size)\n{\n    if (unlikely(req_size > *psize))\n        return js_realloc_array(ctx, parray, elem_size, psize, req_size);\n    else\n        return 0;\n}\n\nstatic inline void js_dbuf_init(JSContext *ctx, DynBuf *s)\n{\n    dbuf_init2(s, ctx->rt, (DynBufReallocFunc *)js_realloc_rt);\n}\n\nstatic inline int is_digit(int c) {\n    return c >= '0' && c <= '9';\n}\n\ntypedef struct JSClassShortDef {\n    JSAtom class_name;\n    JSClassFinalizer *finalizer;\n    JSClassGCMark *gc_mark;\n} JSClassShortDef;\n\nstatic JSClassShortDef const js_std_class_def[] = {\n    { JS_ATOM_Object, NULL, NULL },                             /* JS_CLASS_OBJECT */\n    { JS_ATOM_Array, js_array_finalizer, js_array_mark },       /* JS_CLASS_ARRAY */\n    { JS_ATOM_Error, NULL, NULL }, /* JS_CLASS_ERROR */\n    { JS_ATOM_Number, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_NUMBER */\n    { JS_ATOM_String, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_STRING */\n    { JS_ATOM_Boolean, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_BOOLEAN */\n    { JS_ATOM_Symbol, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_SYMBOL */\n    { JS_ATOM_Arguments, js_array_finalizer, js_array_mark },   /* JS_CLASS_ARGUMENTS */\n    { JS_ATOM_Arguments, NULL, NULL },                          /* JS_CLASS_MAPPED_ARGUMENTS */\n    { JS_ATOM_Date, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_DATE */\n    { JS_ATOM_Object, NULL, NULL },                             /* JS_CLASS_MODULE_NS */\n    { JS_ATOM_Function, js_c_function_finalizer, js_c_function_mark }, /* JS_CLASS_C_FUNCTION */\n    { JS_ATOM_Function, js_bytecode_function_finalizer, js_bytecode_function_mark }, /* JS_CLASS_BYTECODE_FUNCTION */\n    { JS_ATOM_Function, js_bound_function_finalizer, js_bound_function_mark }, /* JS_CLASS_BOUND_FUNCTION */\n    { JS_ATOM_Function, js_c_function_data_finalizer, js_c_function_data_mark }, /* JS_CLASS_C_FUNCTION_DATA */\n    { JS_ATOM_GeneratorFunction, js_bytecode_function_finalizer, js_bytecode_function_mark },  /* JS_CLASS_GENERATOR_FUNCTION */\n    { JS_ATOM_ForInIterator, js_for_in_iterator_finalizer, js_for_in_iterator_mark },      /* JS_CLASS_FOR_IN_ITERATOR */\n    { JS_ATOM_RegExp, js_regexp_finalizer, NULL },                              /* JS_CLASS_REGEXP */\n    { JS_ATOM_ArrayBuffer, js_array_buffer_finalizer, NULL },                   /* JS_CLASS_ARRAY_BUFFER */\n    { JS_ATOM_SharedArrayBuffer, js_array_buffer_finalizer, NULL },             /* JS_CLASS_SHARED_ARRAY_BUFFER */\n    { JS_ATOM_Uint8ClampedArray, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_UINT8C_ARRAY */\n    { JS_ATOM_Int8Array, js_typed_array_finalizer, js_typed_array_mark },       /* JS_CLASS_INT8_ARRAY */\n    { JS_ATOM_Uint8Array, js_typed_array_finalizer, js_typed_array_mark },      /* JS_CLASS_UINT8_ARRAY */\n    { JS_ATOM_Int16Array, js_typed_array_finalizer, js_typed_array_mark },      /* JS_CLASS_INT16_ARRAY */\n    { JS_ATOM_Uint16Array, js_typed_array_finalizer, js_typed_array_mark },     /* JS_CLASS_UINT16_ARRAY */\n    { JS_ATOM_Int32Array, js_typed_array_finalizer, js_typed_array_mark },      /* JS_CLASS_INT32_ARRAY */\n    { JS_ATOM_Uint32Array, js_typed_array_finalizer, js_typed_array_mark },     /* JS_CLASS_UINT32_ARRAY */\n#ifdef CONFIG_BIGNUM\n    { JS_ATOM_BigInt64Array, js_typed_array_finalizer, js_typed_array_mark },   /* JS_CLASS_BIG_INT64_ARRAY */\n    { JS_ATOM_BigUint64Array, js_typed_array_finalizer, js_typed_array_mark },  /* JS_CLASS_BIG_UINT64_ARRAY */\n#endif\n    { JS_ATOM_Float32Array, js_typed_array_finalizer, js_typed_array_mark },    /* JS_CLASS_FLOAT32_ARRAY */\n    { JS_ATOM_Float64Array, js_typed_array_finalizer, js_typed_array_mark },    /* JS_CLASS_FLOAT64_ARRAY */\n    { JS_ATOM_DataView, js_typed_array_finalizer, js_typed_array_mark },        /* JS_CLASS_DATAVIEW */\n#ifdef CONFIG_BIGNUM\n    { JS_ATOM_BigInt, js_object_data_finalizer, js_object_data_mark },      /* JS_CLASS_BIG_INT */\n    { JS_ATOM_BigFloat, js_object_data_finalizer, js_object_data_mark },    /* JS_CLASS_BIG_FLOAT */\n    { JS_ATOM_BigFloatEnv, js_float_env_finalizer, NULL },      /* JS_CLASS_FLOAT_ENV */\n    { JS_ATOM_BigDecimal, js_object_data_finalizer, js_object_data_mark },    /* JS_CLASS_BIG_DECIMAL */\n    { JS_ATOM_OperatorSet, js_operator_set_finalizer, js_operator_set_mark },    /* JS_CLASS_OPERATOR_SET */\n#endif\n    { JS_ATOM_Map, js_map_finalizer, js_map_mark },             /* JS_CLASS_MAP */\n    { JS_ATOM_Set, js_map_finalizer, js_map_mark },             /* JS_CLASS_SET */\n    { JS_ATOM_WeakMap, js_map_finalizer, js_map_mark },         /* JS_CLASS_WEAKMAP */\n    { JS_ATOM_WeakSet, js_map_finalizer, js_map_mark },         /* JS_CLASS_WEAKSET */\n    { JS_ATOM_Map_Iterator, js_map_iterator_finalizer, js_map_iterator_mark }, /* JS_CLASS_MAP_ITERATOR */\n    { JS_ATOM_Set_Iterator, js_map_iterator_finalizer, js_map_iterator_mark }, /* JS_CLASS_SET_ITERATOR */\n    { JS_ATOM_Array_Iterator, js_array_iterator_finalizer, js_array_iterator_mark }, /* JS_CLASS_ARRAY_ITERATOR */\n    { JS_ATOM_String_Iterator, js_array_iterator_finalizer, js_array_iterator_mark }, /* JS_CLASS_STRING_ITERATOR */\n    { JS_ATOM_RegExp_String_Iterator, js_regexp_string_iterator_finalizer, js_regexp_string_iterator_mark }, /* JS_CLASS_REGEXP_STRING_ITERATOR */\n    { JS_ATOM_Generator, js_generator_finalizer, js_generator_mark }, /* JS_CLASS_GENERATOR */\n};\n\nstatic int init_class_range(JSRuntime *rt, JSClassShortDef const *tab,\n                            int start, int count)\n{\n    JSClassDef cm_s, *cm = &cm_s;\n    int i, class_id;\n\n    for(i = 0; i < count; i++) {\n        class_id = i + start;\n        memset(cm, 0, sizeof(*cm));\n        cm->finalizer = tab[i].finalizer;\n        cm->gc_mark = tab[i].gc_mark;\n        if (JS_NewClass1(rt, class_id, cm, tab[i].class_name) < 0)\n            return -1;\n    }\n    return 0;\n}\n\n#ifdef CONFIG_BIGNUM\nstatic JSValue JS_ThrowUnsupportedOperation(JSContext *ctx)\n{\n    return JS_ThrowTypeError(ctx, \"unsupported operation\");\n}\n\nstatic JSValue invalid_to_string(JSContext *ctx, JSValueConst val)\n{\n    return JS_ThrowUnsupportedOperation(ctx);\n}\n\nstatic JSValue invalid_from_string(JSContext *ctx, const char *buf,\n                                   int radix, int flags, slimb_t *pexponent)\n{\n    return JS_NAN;\n}\n\nstatic int invalid_unary_arith(JSContext *ctx,\n                               JSValue *pres, OPCodeEnum op, JSValue op1)\n{\n    JS_FreeValue(ctx, op1);\n    JS_ThrowUnsupportedOperation(ctx);\n    return -1;\n}\n\nstatic int invalid_binary_arith(JSContext *ctx, OPCodeEnum op,\n                                JSValue *pres, JSValue op1, JSValue op2)\n{\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    JS_ThrowUnsupportedOperation(ctx);\n    return -1;\n}\n\nstatic JSValue invalid_mul_pow10_to_float64(JSContext *ctx, const bf_t *a,\n                                            int64_t exponent)\n{\n    return JS_ThrowUnsupportedOperation(ctx);\n}\n\nstatic int invalid_mul_pow10(JSContext *ctx, JSValue *sp)\n{\n    JS_ThrowUnsupportedOperation(ctx);\n    return -1;\n}\n\nstatic void set_dummy_numeric_ops(JSNumericOperations *ops)\n{\n    ops->to_string = invalid_to_string;\n    ops->from_string = invalid_from_string;\n    ops->unary_arith = invalid_unary_arith;\n    ops->binary_arith = invalid_binary_arith;\n    ops->mul_pow10_to_float64 = invalid_mul_pow10_to_float64;\n    ops->mul_pow10 = invalid_mul_pow10;\n}\n\n#endif /* CONFIG_BIGNUM */\n\n#if !defined(CONFIG_STACK_CHECK) || defined(CONFIG_DISABLE_STACK_CHECK)\n/* no stack limitation */\nstatic inline uintptr_t js_get_stack_pointer(void)\n{\n    return 0;\n}\n\nstatic inline BOOL js_check_stack_overflow(JSRuntime *rt, size_t alloca_size)\n{\n    return FALSE;\n}\n#else\n/* Note: OS and CPU dependent */\nstatic inline uintptr_t js_get_stack_pointer(void)\n{\n    return (uintptr_t)__builtin_frame_address(0);\n}\n\nstatic inline BOOL js_check_stack_overflow(JSRuntime *rt, size_t alloca_size)\n{\n    uintptr_t sp;\n    sp = js_get_stack_pointer() - alloca_size;\n    return unlikely(sp < rt->stack_limit);\n}\n#endif\n\nJSRuntime *JS_NewRuntime2(const JSMallocFunctions *mf, void *opaque)\n{\n    JSRuntime *rt;\n    JSMallocState ms;\n\n    memset(&ms, 0, sizeof(ms));\n    ms.opaque = opaque;\n    ms.malloc_limit = -1;\n\n    rt = mf->js_malloc(&ms, sizeof(JSRuntime));\n    if (!rt)\n        return NULL;\n    memset(rt, 0, sizeof(*rt));\n    rt->mf = *mf;\n    if (!rt->mf.js_malloc_usable_size) {\n        /* use dummy function if none provided */\n        rt->mf.js_malloc_usable_size = js_malloc_usable_size_unknown;\n    }\n    rt->malloc_state = ms;\n    rt->malloc_gc_threshold = 256 * 1024;\n\n#ifdef CONFIG_BIGNUM\n    bf_context_init(&rt->bf_ctx, js_bf_realloc, rt);\n    set_dummy_numeric_ops(&rt->bigint_ops);\n    set_dummy_numeric_ops(&rt->bigfloat_ops);\n    set_dummy_numeric_ops(&rt->bigdecimal_ops);\n#endif\n\n    init_list_head(&rt->context_list);\n    init_list_head(&rt->gc_obj_list);\n    init_list_head(&rt->gc_zero_ref_count_list);\n    rt->gc_phase = JS_GC_PHASE_NONE;\n    \n#ifdef DUMP_LEAKS\n    init_list_head(&rt->string_list);\n#endif\n    init_list_head(&rt->job_list);\n\n    if (JS_InitAtoms(rt))\n        goto fail;\n\n    /* create the object, array and function classes */\n    if (init_class_range(rt, js_std_class_def, JS_CLASS_OBJECT,\n                         countof(js_std_class_def)) < 0)\n        goto fail;\n    rt->class_array[JS_CLASS_ARGUMENTS].exotic = &js_arguments_exotic_methods;\n    rt->class_array[JS_CLASS_STRING].exotic = &js_string_exotic_methods;\n    rt->class_array[JS_CLASS_MODULE_NS].exotic = &js_module_ns_exotic_methods;\n\n    rt->class_array[JS_CLASS_C_FUNCTION].call = js_call_c_function;\n    rt->class_array[JS_CLASS_C_FUNCTION_DATA].call = js_c_function_data_call;\n    rt->class_array[JS_CLASS_BOUND_FUNCTION].call = js_call_bound_function;\n    rt->class_array[JS_CLASS_GENERATOR_FUNCTION].call = js_generator_function_call;\n    if (init_shape_hash(rt))\n        goto fail;\n\n    rt->stack_size = JS_DEFAULT_STACK_SIZE;\n    JS_UpdateStackTop(rt);\n\n    rt->current_exception = JS_NULL;\n\n    return rt;\n fail:\n    JS_FreeRuntime(rt);\n    return NULL;\n}\n\nvoid *JS_GetRuntimeOpaque(JSRuntime *rt)\n{\n    return rt->user_opaque;\n}\n\nvoid JS_SetRuntimeOpaque(JSRuntime *rt, void *opaque)\n{\n    rt->user_opaque = opaque;\n}\n\n/* default memory allocation functions with memory limitation */\nstatic inline size_t js_def_malloc_usable_size(void *ptr)\n{\n#if defined(__APPLE__)\n    return malloc_size(ptr);\n#elif defined(_WIN32)\n    return _msize(ptr);\n#elif defined(EMSCRIPTEN)\n    return 0;\n#elif defined(__ANDROID__)\n    return 0;\n#elif defined(__linux__)\n    return malloc_usable_size(ptr);\n#else\n    /* change this to `return 0;` if compilation fails */\n    return 0;\n#endif\n}\n\nstatic void *js_def_malloc(JSMallocState *s, size_t size)\n{\n    void *ptr;\n\n    /* Do not allocate zero bytes: behavior is platform dependent */\n    assert(size != 0);\n\n    if (unlikely(s->malloc_size + size > s->malloc_limit))\n        return NULL;\n\n    ptr = malloc(size);\n    if (!ptr)\n        return NULL;\n\n    s->malloc_count++;\n    s->malloc_size += js_def_malloc_usable_size(ptr) + MALLOC_OVERHEAD;\n    return ptr;\n}\n\nstatic void js_def_free(JSMallocState *s, void *ptr)\n{\n    if (!ptr)\n        return;\n\n    s->malloc_count--;\n    s->malloc_size -= js_def_malloc_usable_size(ptr) + MALLOC_OVERHEAD;\n    free(ptr);\n}\n\nstatic void *js_def_realloc(JSMallocState *s, void *ptr, size_t size)\n{\n    size_t old_size;\n\n    if (!ptr) {\n        if (size == 0)\n            return NULL;\n        return js_def_malloc(s, size);\n    }\n    old_size = js_def_malloc_usable_size(ptr);\n    if (size == 0) {\n        s->malloc_count--;\n        s->malloc_size -= old_size + MALLOC_OVERHEAD;\n        free(ptr);\n        return NULL;\n    }\n    if (s->malloc_size + size - old_size > s->malloc_limit)\n        return NULL;\n\n    ptr = realloc(ptr, size);\n    if (!ptr)\n        return NULL;\n\n    s->malloc_size += js_def_malloc_usable_size(ptr) - old_size;\n    return ptr;\n}\n\nstatic const JSMallocFunctions def_malloc_funcs = {\n    js_def_malloc,\n    js_def_free,\n    js_def_realloc,\n#if defined(__APPLE__)\n    malloc_size,\n#elif defined(_WIN32)\n    (size_t (*)(const void *))_msize,\n#elif defined(EMSCRIPTEN)\n    NULL,\n#elif defined(__ANDROID__)\n    NULL, \n#elif defined(__linux__)\n    (size_t (*)(const void *))malloc_usable_size,\n#else\n    /* change this to `NULL,` if compilation fails */\n    malloc_usable_size,\n#endif\n};\n\nJSRuntime *JS_NewRuntime(void)\n{\n    return JS_NewRuntime2(&def_malloc_funcs, NULL);\n}\n\nvoid JS_SetMemoryLimit(JSRuntime *rt, size_t limit)\n{\n    rt->malloc_state.malloc_limit = limit;\n}\n\n/* use -1 to disable automatic GC */\nvoid JS_SetGCThreshold(JSRuntime *rt, size_t gc_threshold)\n{\n    rt->malloc_gc_threshold = gc_threshold;\n}\n\n#define malloc(s) malloc_is_forbidden(s)\n#define free(p) free_is_forbidden(p)\n#define realloc(p,s) realloc_is_forbidden(p,s)\n\nvoid JS_SetInterruptHandler(JSRuntime *rt, JSInterruptHandler *cb, void *opaque)\n{\n    rt->interrupt_handler = cb;\n    rt->interrupt_opaque = opaque;\n}\n\nvoid JS_SetCanBlock(JSRuntime *rt, BOOL can_block)\n{\n    rt->can_block = can_block;\n}\n\nvoid JS_SetSharedArrayBufferFunctions(JSRuntime *rt,\n                                      const JSSharedArrayBufferFunctions *sf)\n{\n    rt->sab_funcs = *sf;\n}\n\n/* return 0 if OK, < 0 if exception */\nint JS_EnqueueJob(JSContext *ctx, JSJobFunc *job_func,\n                  int argc, JSValueConst *argv)\n{\n    JSRuntime *rt = ctx->rt;\n    JSJobEntry *e;\n    int i;\n\n    e = js_malloc(ctx, sizeof(*e) + argc * sizeof(JSValue));\n    if (!e)\n        return -1;\n    e->ctx = ctx;\n    e->job_func = job_func;\n    e->argc = argc;\n    for(i = 0; i < argc; i++) {\n        e->argv[i] = JS_DupValue(ctx, argv[i]);\n    }\n    list_add_tail(&e->link, &rt->job_list);\n    return 0;\n}\n\nBOOL JS_IsJobPending(JSRuntime *rt)\n{\n    return !list_empty(&rt->job_list);\n}\n\n/* return < 0 if exception, 0 if no job pending, 1 if a job was\n   executed successfully. the context of the job is stored in '*pctx' */\nint JS_ExecutePendingJob(JSRuntime *rt, JSContext **pctx)\n{\n    JSContext *ctx;\n    JSJobEntry *e;\n    JSValue res;\n    int i, ret;\n\n    if (list_empty(&rt->job_list)) {\n        *pctx = NULL;\n        return 0;\n    }\n\n    /* get the first pending job and execute it */\n    e = list_entry(rt->job_list.next, JSJobEntry, link);\n    list_del(&e->link);\n    ctx = e->ctx;\n    res = e->job_func(e->ctx, e->argc, (JSValueConst *)e->argv);\n    for(i = 0; i < e->argc; i++)\n        JS_FreeValue(ctx, e->argv[i]);\n    if (JS_IsException(res))\n        ret = -1;\n    else\n        ret = 1;\n    JS_FreeValue(ctx, res);\n    js_free(ctx, e);\n    *pctx = ctx;\n    return ret;\n}\n\nstatic inline uint32_t atom_get_free(const JSAtomStruct *p)\n{\n    return (uintptr_t)p >> 1;\n}\n\nstatic inline BOOL atom_is_free(const JSAtomStruct *p)\n{\n    return (uintptr_t)p & 1;\n}\n\nstatic inline JSAtomStruct *atom_set_free(uint32_t v)\n{\n    return (JSAtomStruct *)(((uintptr_t)v << 1) | 1);\n}\n\n/* Note: the string contents are uninitialized */\nstatic JSString *js_alloc_string_rt(JSRuntime *rt, int max_len, int is_wide_char)\n{\n    JSString *str;\n    str = js_malloc_rt(rt, sizeof(JSString) + (max_len << is_wide_char) + 1 - is_wide_char);\n    if (unlikely(!str))\n        return NULL;\n    str->header.ref_count = 1;\n    str->is_wide_char = is_wide_char;\n    str->len = max_len;\n    str->atom_type = 0;\n    str->hash = 0;          /* optional but costless */\n    str->hash_next = 0;     /* optional */\n#ifdef DUMP_LEAKS\n    list_add_tail(&str->link, &rt->string_list);\n#endif\n    return str;\n}\n\nstatic JSString *js_alloc_string(JSContext *ctx, int max_len, int is_wide_char)\n{\n    JSString *p;\n    p = js_alloc_string_rt(ctx->rt, max_len, is_wide_char);\n    if (unlikely(!p)) {\n        JS_ThrowOutOfMemory(ctx);\n        return NULL;\n    }\n    return p;\n}\n\n/* same as JS_FreeValueRT() but faster */\nstatic inline void js_free_string(JSRuntime *rt, JSString *str)\n{\n    if (--str->header.ref_count <= 0) {\n        if (str->atom_type) {\n            JS_FreeAtomStruct(rt, str);\n        } else {\n#ifdef DUMP_LEAKS\n            list_del(&str->link);\n#endif\n            js_free_rt(rt, str);\n        }\n    }\n}\n\nvoid JS_SetRuntimeInfo(JSRuntime *rt, const char *s)\n{\n    if (rt)\n        rt->rt_info = s;\n}\n\nint JS_FreeRuntime(JSRuntime *rt)\n{\n    struct list_head *el, *el1;\n    int i;\n    int ret_leaks;\n\n    JS_FreeValueRT(rt, rt->current_exception);\n\n    list_for_each_safe(el, el1, &rt->job_list) {\n        JSJobEntry *e = list_entry(el, JSJobEntry, link);\n        for(i = 0; i < e->argc; i++)\n            JS_FreeValueRT(rt, e->argv[i]);\n        js_free_rt(rt, e);\n    }\n    init_list_head(&rt->job_list);\n\n    JS_RunGC(rt);\n\n#ifdef DUMP_LEAKS\n    /* leaking objects */\n    {\n        BOOL header_done;\n        JSGCObjectHeader *p;\n        int count;\n\n        /* remove the internal refcounts to display only the object\n           referenced externally */\n        list_for_each(el, &rt->gc_obj_list) {\n            p = list_entry(el, JSGCObjectHeader, link);\n            p->mark = 0;\n        }\n        gc_decref(rt);\n\n        header_done = FALSE;\n        list_for_each(el, &rt->gc_obj_list) {\n            p = list_entry(el, JSGCObjectHeader, link);\n            if (p->ref_count != 0) {\n                if (!header_done) {\n                    printf(\"Object leaks:\\n\");\n                    JS_DumpObjectHeader(rt);\n                    header_done = TRUE;\n                }\n                JS_DumpGCObject(rt, p);\n            }\n        }\n\n        count = 0;\n        list_for_each(el, &rt->gc_obj_list) {\n            p = list_entry(el, JSGCObjectHeader, link);\n            if (p->ref_count == 0) {\n                count++;\n            }\n        }\n        if (count != 0)\n            printf(\"Secondary object leaks: %d\\n\", count);\n    }\n#endif\n    ret_leaks = (list_empty(&rt->gc_obj_list));\n\n    /* free the classes */\n    for(i = 0; i < rt->class_count; i++) {\n        JSClass *cl = &rt->class_array[i];\n        if (cl->class_id != 0) {\n            JS_FreeAtomRT(rt, cl->class_name);\n        }\n    }\n    js_free_rt(rt, rt->class_array);\n\n#ifdef CONFIG_BIGNUM\n    bf_context_end(&rt->bf_ctx);\n#endif\n\n#ifdef DUMP_LEAKS\n    /* only the atoms defined in JS_InitAtoms() should be left */\n    {\n        BOOL header_done = FALSE;\n\n        for(i = 0; i < rt->atom_size; i++) {\n            JSAtomStruct *p = rt->atom_array[i];\n            if (!atom_is_free(p) /* && p->str*/) {\n                if (i >= JS_ATOM_END || p->header.ref_count != 1) {\n                    if (!header_done) {\n                        header_done = TRUE;\n                        if (rt->rt_info) {\n                            printf(\"%s:1: atom leakage:\", rt->rt_info);\n                        } else {\n                            printf(\"Atom leaks:\\n\"\n                                   \"    %6s %6s %s\\n\",\n                                   \"ID\", \"REFCNT\", \"NAME\");\n                        }\n                    }\n                    if (rt->rt_info) {\n                        printf(\" \");\n                    } else {\n                        printf(\"    %6u %6u \", i, p->header.ref_count);\n                    }\n                    switch (p->atom_type) {\n                    case JS_ATOM_TYPE_STRING:\n                        JS_DumpString(rt, p);\n                        break;\n                    case JS_ATOM_TYPE_GLOBAL_SYMBOL:\n                        printf(\"Symbol.for(\");\n                        JS_DumpString(rt, p);\n                        printf(\")\");\n                        break;\n                    case JS_ATOM_TYPE_SYMBOL:\n                        if (p->hash == JS_ATOM_HASH_SYMBOL) {\n                            printf(\"Symbol(\");\n                            JS_DumpString(rt, p);\n                            printf(\")\");\n                        } else {\n                            printf(\"Private(\");\n                            JS_DumpString(rt, p);\n                            printf(\")\");\n                        }\n                        break;\n                    }\n                    if (rt->rt_info) {\n                        printf(\":%u\", p->header.ref_count);\n                    } else {\n                        printf(\"\\n\");\n                    }\n                }\n            }\n        }\n        if (rt->rt_info && header_done)\n            printf(\"\\n\");\n    }\n#endif\n\n    /* free the atoms */\n    for(i = 0; i < rt->atom_size; i++) {\n        JSAtomStruct *p = rt->atom_array[i];\n        if (!atom_is_free(p)) {\n#ifdef DUMP_LEAKS\n            list_del(&p->link);\n#endif\n            js_free_rt(rt, p);\n        }\n    }\n    js_free_rt(rt, rt->atom_array);\n    js_free_rt(rt, rt->atom_hash);\n    js_free_rt(rt, rt->shape_hash);\n#ifdef DUMP_LEAKS\n    if (!list_empty(&rt->string_list)) {\n        if (rt->rt_info) {\n            printf(\"%s:1: string leakage:\", rt->rt_info);\n        } else {\n            printf(\"String leaks:\\n\"\n                   \"    %6s %s\\n\",\n                   \"REFCNT\", \"VALUE\");\n        }\n        list_for_each_safe(el, el1, &rt->string_list) {\n            JSString *str = list_entry(el, JSString, link);\n            if (rt->rt_info) {\n                printf(\" \");\n            } else {\n                printf(\"    %6u \", str->header.ref_count);\n            }\n            JS_DumpString(rt, str);\n            if (rt->rt_info) {\n                printf(\":%u\", str->header.ref_count);\n            } else {\n                printf(\"\\n\");\n            }\n            list_del(&str->link);\n            js_free_rt(rt, str);\n        }\n        if (rt->rt_info)\n            printf(\"\\n\");\n    }\n    {\n        JSMallocState *s = &rt->malloc_state;\n        if (s->malloc_count > 1) {\n            if (rt->rt_info)\n                printf(\"%s:1: \", rt->rt_info);\n            printf(\"Memory leak: %\"PRIu64\" bytes lost in %\"PRIu64\" block%s\\n\",\n                   (uint64_t)(s->malloc_size - sizeof(JSRuntime)),\n                   (uint64_t)(s->malloc_count - 1), &\"s\"[s->malloc_count == 2]);\n        }\n    }\n#endif\n\n    {\n        JSMallocState ms = rt->malloc_state;\n        rt->mf.js_free(&ms, rt);\n    }\n    return ret_leaks;\n}\n\nJSContext *JS_NewContextRaw(JSRuntime *rt)\n{\n    JSContext *ctx;\n    int i;\n\n    ctx = js_mallocz_rt(rt, sizeof(JSContext));\n    if (!ctx)\n        return NULL;\n    ctx->header.ref_count = 1;\n    add_gc_object(rt, &ctx->header, JS_GC_OBJ_TYPE_JS_CONTEXT);\n\n    ctx->class_proto = js_malloc_rt(rt, sizeof(ctx->class_proto[0]) *\n                                    rt->class_count);\n    if (!ctx->class_proto) {\n        js_free_rt(rt, ctx);\n        return NULL;\n    }\n    ctx->rt = rt;\n    list_add_tail(&ctx->link, &rt->context_list);\n#ifdef CONFIG_BIGNUM\n    ctx->bf_ctx = &rt->bf_ctx;\n    ctx->fp_env.prec = 113;\n    ctx->fp_env.flags = bf_set_exp_bits(15) | BF_RNDN | BF_FLAG_SUBNORMAL;\n#endif\n    for(i = 0; i < rt->class_count; i++)\n        ctx->class_proto[i] = JS_NULL;\n    ctx->array_ctor = JS_NULL;\n    ctx->regexp_ctor = JS_NULL;\n    ctx->promise_ctor = JS_NULL;\n    init_list_head(&ctx->loaded_modules);\n\n    JS_AddIntrinsicBasicObjects(ctx);\n    return ctx;\n}\n\nJSContext *JS_NewContext(JSRuntime *rt)\n{\n    JSContext *ctx;\n\n    ctx = JS_NewContextRaw(rt);\n    if (!ctx)\n        return NULL;\n\n    JS_AddIntrinsicBaseObjects(ctx);\n    JS_AddIntrinsicDate(ctx);\n    JS_AddIntrinsicEval(ctx);\n    JS_AddIntrinsicStringNormalize(ctx);\n    JS_AddIntrinsicRegExp(ctx);\n    JS_AddIntrinsicJSON(ctx);\n    JS_AddIntrinsicProxy(ctx);\n    JS_AddIntrinsicMapSet(ctx);\n    JS_AddIntrinsicTypedArrays(ctx);\n    JS_AddIntrinsicPromise(ctx);\n#ifdef CONFIG_BIGNUM\n    JS_AddIntrinsicBigInt(ctx);\n#endif\n    return ctx;\n}\n\nvoid *JS_GetContextOpaque(JSContext *ctx)\n{\n    return ctx->user_opaque;\n}\n\nvoid JS_SetContextOpaque(JSContext *ctx, void *opaque)\n{\n    ctx->user_opaque = opaque;\n}\n\n/* set the new value and free the old value after (freeing the value\n   can reallocate the object data) */\nstatic inline void set_value(JSContext *ctx, JSValue *pval, JSValue new_val)\n{\n    JSValue old_val;\n    old_val = *pval;\n    *pval = new_val;\n    JS_FreeValue(ctx, old_val);\n}\n\nvoid JS_SetClassProto(JSContext *ctx, JSClassID class_id, JSValue obj)\n{\n    JSRuntime *rt = ctx->rt;\n    assert(class_id < rt->class_count);\n    set_value(ctx, &ctx->class_proto[class_id], obj);\n}\n\nJSValue JS_GetClassProto(JSContext *ctx, JSClassID class_id)\n{\n    JSRuntime *rt = ctx->rt;\n    assert(class_id < rt->class_count);\n    return JS_DupValue(ctx, ctx->class_proto[class_id]);\n}\n\ntypedef enum JSFreeModuleEnum {\n    JS_FREE_MODULE_ALL,\n    JS_FREE_MODULE_NOT_RESOLVED,\n    JS_FREE_MODULE_NOT_EVALUATED,\n} JSFreeModuleEnum;\n\n/* XXX: would be more efficient with separate module lists */\nstatic void js_free_modules(JSContext *ctx, JSFreeModuleEnum flag)\n{\n    struct list_head *el, *el1;\n    list_for_each_safe(el, el1, &ctx->loaded_modules) {\n        JSModuleDef *m = list_entry(el, JSModuleDef, link);\n        if (flag == JS_FREE_MODULE_ALL ||\n            (flag == JS_FREE_MODULE_NOT_RESOLVED && !m->resolved) ||\n            (flag == JS_FREE_MODULE_NOT_EVALUATED && !m->evaluated)) {\n            js_free_module_def(ctx, m);\n        }\n    }\n}\n\nJSContext *JS_DupContext(JSContext *ctx)\n{\n    ctx->header.ref_count++;\n    return ctx;\n}\n\n/* used by the GC */\nstatic void JS_MarkContext(JSRuntime *rt, JSContext *ctx,\n                           JS_MarkFunc *mark_func)\n{\n    int i;\n    struct list_head *el;\n\n    /* modules are not seen by the GC, so we directly mark the objects\n       referenced by each module */\n    list_for_each(el, &ctx->loaded_modules) {\n        JSModuleDef *m = list_entry(el, JSModuleDef, link);\n        js_mark_module_def(rt, m, mark_func);\n    }\n\n    JS_MarkValue(rt, ctx->global_obj, mark_func);\n    JS_MarkValue(rt, ctx->global_var_obj, mark_func);\n\n    JS_MarkValue(rt, ctx->throw_type_error, mark_func);\n    JS_MarkValue(rt, ctx->eval_obj, mark_func);\n\n    JS_MarkValue(rt, ctx->array_proto_values, mark_func);\n    for(i = 0; i < JS_NATIVE_ERROR_COUNT; i++) {\n        JS_MarkValue(rt, ctx->native_error_proto[i], mark_func);\n    }\n    for(i = 0; i < rt->class_count; i++) {\n        JS_MarkValue(rt, ctx->class_proto[i], mark_func);\n    }\n    JS_MarkValue(rt, ctx->iterator_proto, mark_func);\n    JS_MarkValue(rt, ctx->async_iterator_proto, mark_func);\n    JS_MarkValue(rt, ctx->promise_ctor, mark_func);\n    JS_MarkValue(rt, ctx->array_ctor, mark_func);\n    JS_MarkValue(rt, ctx->regexp_ctor, mark_func);\n    JS_MarkValue(rt, ctx->function_ctor, mark_func);\n    JS_MarkValue(rt, ctx->function_proto, mark_func);\n\n    if (ctx->array_shape)\n        mark_func(rt, &ctx->array_shape->header);\n}\n\nvoid JS_FreeContext(JSContext *ctx)\n{\n    JSRuntime *rt = ctx->rt;\n    int i;\n\n    if (--ctx->header.ref_count > 0)\n        return;\n    assert(ctx->header.ref_count == 0);\n    \n#ifdef DUMP_ATOMS\n    JS_DumpAtoms(ctx->rt);\n#endif\n#ifdef DUMP_SHAPES\n    JS_DumpShapes(ctx->rt);\n#endif\n#ifdef DUMP_OBJECTS\n    {\n        struct list_head *el;\n        JSGCObjectHeader *p;\n        printf(\"JSObjects: {\\n\");\n        JS_DumpObjectHeader(ctx->rt);\n        list_for_each(el, &rt->gc_obj_list) {\n            p = list_entry(el, JSGCObjectHeader, link);\n            JS_DumpGCObject(rt, p);\n        }\n        printf(\"}\\n\");\n    }\n#endif\n#ifdef DUMP_MEM\n    {\n        JSMemoryUsage stats;\n        JS_ComputeMemoryUsage(rt, &stats);\n        JS_DumpMemoryUsage(stdout, &stats, rt);\n    }\n#endif\n\n    js_free_modules(ctx, JS_FREE_MODULE_ALL);\n\n    JS_FreeValue(ctx, ctx->global_obj);\n    JS_FreeValue(ctx, ctx->global_var_obj);\n\n    JS_FreeValue(ctx, ctx->throw_type_error);\n    JS_FreeValue(ctx, ctx->eval_obj);\n\n    JS_FreeValue(ctx, ctx->array_proto_values);\n    for(i = 0; i < JS_NATIVE_ERROR_COUNT; i++) {\n        JS_FreeValue(ctx, ctx->native_error_proto[i]);\n    }\n    for(i = 0; i < rt->class_count; i++) {\n        JS_FreeValue(ctx, ctx->class_proto[i]);\n    }\n    js_free_rt(rt, ctx->class_proto);\n    JS_FreeValue(ctx, ctx->iterator_proto);\n    JS_FreeValue(ctx, ctx->async_iterator_proto);\n    JS_FreeValue(ctx, ctx->promise_ctor);\n    JS_FreeValue(ctx, ctx->array_ctor);\n    JS_FreeValue(ctx, ctx->regexp_ctor);\n    JS_FreeValue(ctx, ctx->function_ctor);\n    JS_FreeValue(ctx, ctx->function_proto);\n\n    js_free_shape_null(ctx->rt, ctx->array_shape);\n\n    list_del(&ctx->link);\n    remove_gc_object(&ctx->header);\n    js_free_rt(ctx->rt, ctx);\n}\n\nJSRuntime *JS_GetRuntime(JSContext *ctx)\n{\n    return ctx->rt;\n}\n\nstatic void update_stack_limit(JSRuntime *rt)\n{\n    if (rt->stack_size == 0) {\n        rt->stack_limit = 0; /* no limit */\n    } else {\n        rt->stack_limit = rt->stack_top - rt->stack_size;\n    }\n}\n\nvoid JS_SetMaxStackSize(JSRuntime *rt, size_t stack_size)\n{\n    rt->stack_size = stack_size;\n    update_stack_limit(rt);\n}\n\nvoid JS_UpdateStackTop(JSRuntime *rt)\n{\n    rt->stack_top = js_get_stack_pointer();\n    update_stack_limit(rt);\n}\n\nstatic inline BOOL is_strict_mode(JSContext *ctx)\n{\n    JSStackFrame *sf = ctx->rt->current_stack_frame;\n    return (sf && (sf->js_mode & JS_MODE_STRICT));\n}\n\n#ifdef CONFIG_BIGNUM\nstatic inline BOOL is_math_mode(JSContext *ctx)\n{\n    JSStackFrame *sf = ctx->rt->current_stack_frame;\n    return (sf && (sf->js_mode & JS_MODE_MATH));\n}\n#endif\n\n/* JSAtom support */\n\n#define JS_ATOM_TAG_INT (1U << 31)\n#define JS_ATOM_MAX_INT (JS_ATOM_TAG_INT - 1)\n#define JS_ATOM_MAX     ((1U << 30) - 1)\n\n/* return the max count from the hash size */\n#define JS_ATOM_COUNT_RESIZE(n) ((n) * 2)\n\nstatic inline BOOL __JS_AtomIsConst(JSAtom v)\n{\n#if defined(DUMP_LEAKS) && DUMP_LEAKS > 1\n        return (int32_t)v <= 0;\n#else\n        return (int32_t)v < JS_ATOM_END;\n#endif\n}\n\nstatic inline BOOL __JS_AtomIsTaggedInt(JSAtom v)\n{\n    return (v & JS_ATOM_TAG_INT) != 0;\n}\n\nstatic inline JSAtom __JS_AtomFromUInt32(uint32_t v)\n{\n    return v | JS_ATOM_TAG_INT;\n}\n\nstatic inline uint32_t __JS_AtomToUInt32(JSAtom atom)\n{\n    return atom & ~JS_ATOM_TAG_INT;\n}\n\nstatic inline int is_num(int c)\n{\n    return c >= '0' && c <= '9';\n}\n\n/* return TRUE if the string is a number n with 0 <= n <= 2^32-1 */\nstatic inline BOOL is_num_string(uint32_t *pval, const JSString *p)\n{\n    uint32_t n;\n    uint64_t n64;\n    int c, i, len;\n\n    len = p->len;\n    if (len == 0 || len > 10)\n        return FALSE;\n    if (p->is_wide_char)\n        c = p->u.str16[0];\n    else\n        c = p->u.str8[0];\n    if (is_num(c)) {\n        if (c == '0') {\n            if (len != 1)\n                return FALSE;\n            n = 0;\n        } else {\n            n = c - '0';\n            for(i = 1; i < len; i++) {\n                if (p->is_wide_char)\n                    c = p->u.str16[i];\n                else\n                    c = p->u.str8[i];\n                if (!is_num(c))\n                    return FALSE;\n                n64 = (uint64_t)n * 10 + (c - '0');\n                if ((n64 >> 32) != 0)\n                    return FALSE;\n                n = n64;\n            }\n        }\n        *pval = n;\n        return TRUE;\n    } else {\n        return FALSE;\n    }\n}\n\n/* XXX: could use faster version ? */\nstatic inline uint32_t hash_string8(const uint8_t *str, size_t len, uint32_t h)\n{\n    size_t i;\n\n    for(i = 0; i < len; i++)\n        h = h * 263 + str[i];\n    return h;\n}\n\nstatic inline uint32_t hash_string16(const uint16_t *str,\n                                     size_t len, uint32_t h)\n{\n    size_t i;\n\n    for(i = 0; i < len; i++)\n        h = h * 263 + str[i];\n    return h;\n}\n\nstatic uint32_t hash_string(const JSString *str, uint32_t h)\n{\n    if (str->is_wide_char)\n        h = hash_string16(str->u.str16, str->len, h);\n    else\n        h = hash_string8(str->u.str8, str->len, h);\n    return h;\n}\n\nstatic __maybe_unused void JS_DumpString(JSRuntime *rt,\n                                                  const JSString *p)\n{\n    int i, c, sep;\n\n    if (p == NULL) {\n        printf(\"<null>\");\n        return;\n    }\n    printf(\"%d\", p->header.ref_count);\n    sep = (p->header.ref_count == 1) ? '\\\"' : '\\'';\n    putchar(sep);\n    for(i = 0; i < p->len; i++) {\n        if (p->is_wide_char)\n            c = p->u.str16[i];\n        else\n            c = p->u.str8[i];\n        if (c == sep || c == '\\\\') {\n            putchar('\\\\');\n            putchar(c);\n        } else if (c >= ' ' && c <= 126) {\n            putchar(c);\n        } else if (c == '\\n') {\n            putchar('\\\\');\n            putchar('n');\n        } else {\n            printf(\"\\\\u%04x\", c);\n        }\n    }\n    putchar(sep);\n}\n\nstatic __maybe_unused void JS_DumpAtoms(JSRuntime *rt)\n{\n    JSAtomStruct *p;\n    int h, i;\n    /* This only dumps hashed atoms, not JS_ATOM_TYPE_SYMBOL atoms */\n    printf(\"JSAtom count=%d size=%d hash_size=%d:\\n\",\n           rt->atom_count, rt->atom_size, rt->atom_hash_size);\n    printf(\"JSAtom hash table: {\\n\");\n    for(i = 0; i < rt->atom_hash_size; i++) {\n        h = rt->atom_hash[i];\n        if (h) {\n            printf(\"  %d:\", i);\n            while (h) {\n                p = rt->atom_array[h];\n                printf(\" \");\n                JS_DumpString(rt, p);\n                h = p->hash_next;\n            }\n            printf(\"\\n\");\n        }\n    }\n    printf(\"}\\n\");\n    printf(\"JSAtom table: {\\n\");\n    for(i = 0; i < rt->atom_size; i++) {\n        p = rt->atom_array[i];\n        if (!atom_is_free(p)) {\n            printf(\"  %d: { %d %08x \", i, p->atom_type, p->hash);\n            if (!(p->len == 0 && p->is_wide_char != 0))\n                JS_DumpString(rt, p);\n            printf(\" %d }\\n\", p->hash_next);\n        }\n    }\n    printf(\"}\\n\");\n}\n\nstatic int JS_ResizeAtomHash(JSRuntime *rt, int new_hash_size)\n{\n    JSAtomStruct *p;\n    uint32_t new_hash_mask, h, i, hash_next1, j, *new_hash;\n\n    assert((new_hash_size & (new_hash_size - 1)) == 0); /* power of two */\n    new_hash_mask = new_hash_size - 1;\n    new_hash = js_mallocz_rt(rt, sizeof(rt->atom_hash[0]) * new_hash_size);\n    if (!new_hash)\n        return -1;\n    for(i = 0; i < rt->atom_hash_size; i++) {\n        h = rt->atom_hash[i];\n        while (h != 0) {\n            p = rt->atom_array[h];\n            hash_next1 = p->hash_next;\n            /* add in new hash table */\n            j = p->hash & new_hash_mask;\n            p->hash_next = new_hash[j];\n            new_hash[j] = h;\n            h = hash_next1;\n        }\n    }\n    js_free_rt(rt, rt->atom_hash);\n    rt->atom_hash = new_hash;\n    rt->atom_hash_size = new_hash_size;\n    rt->atom_count_resize = JS_ATOM_COUNT_RESIZE(new_hash_size);\n    //    JS_DumpAtoms(rt);\n    return 0;\n}\n\n#if defined(__APPLE__)\n// not best solution\n#include <mach/mach_time.h>\n#ifndef CLOCK_REALTIME\n#define CLOCK_REALTIME 0\nint clock_gettime(int clk_id, struct timespec *t){\n    mach_timebase_info_data_t timebase;\n    mach_timebase_info(&timebase);\n    uint64_t time;\n    time = mach_absolute_time();\n    double nseconds = ((double)time * (double)timebase.numer)/((double)timebase.denom);\n    double seconds = ((double)time * (double)timebase.numer)/((double)timebase.denom * 1e9);\n    t->tv_sec = seconds;\n    t->tv_nsec = nseconds;\n    return 0;\n}\n#endif\n#endif\n\nstatic int JS_InitAtoms(JSRuntime *rt)\n{\n    int i, len, atom_type;\n    const char *p;\n\n    rt->atom_hash_size = 0;\n    rt->atom_hash = NULL;\n    rt->atom_count = 0;\n    rt->atom_size = 0;\n    rt->atom_free_index = 0;\n    if (JS_ResizeAtomHash(rt, 256))     /* there are at least 195 predefined atoms */\n        return -1;\n\n    p = js_atom_init;\n    for(i = 1; i < JS_ATOM_END; i++) {\n        if (i == JS_ATOM_Private_brand)\n            atom_type = JS_ATOM_TYPE_PRIVATE;\n        else if (i >= JS_ATOM_Symbol_toPrimitive)\n            atom_type = JS_ATOM_TYPE_SYMBOL;\n        else\n            atom_type = JS_ATOM_TYPE_STRING;\n        len = strlen(p);\n        if (__JS_NewAtomInit(rt, p, len, atom_type) == JS_ATOM_NULL)\n            return -1;\n        p = p + len + 1;\n    }\n    return 0;\n}\n\nstatic JSAtom JS_DupAtomRT(JSRuntime *rt, JSAtom v)\n{\n    JSAtomStruct *p;\n\n    if (!__JS_AtomIsConst(v)) {\n        p = rt->atom_array[v];\n        p->header.ref_count++;\n    }\n    return v;\n}\n\nJSAtom JS_DupAtom(JSContext *ctx, JSAtom v)\n{\n    JSRuntime *rt;\n    JSAtomStruct *p;\n\n    if (!__JS_AtomIsConst(v)) {\n        rt = ctx->rt;\n        p = rt->atom_array[v];\n        p->header.ref_count++;\n    }\n    return v;\n}\n\nstatic JSAtomKindEnum JS_AtomGetKind(JSContext *ctx, JSAtom v)\n{\n    JSRuntime *rt;\n    JSAtomStruct *p;\n\n    rt = ctx->rt;\n    if (__JS_AtomIsTaggedInt(v))\n        return JS_ATOM_KIND_STRING;\n    p = rt->atom_array[v];\n    switch(p->atom_type) {\n    case JS_ATOM_TYPE_STRING:\n        return JS_ATOM_KIND_STRING;\n    case JS_ATOM_TYPE_GLOBAL_SYMBOL:\n        return JS_ATOM_KIND_SYMBOL;\n    case JS_ATOM_TYPE_SYMBOL:\n        switch(p->hash) {\n        case JS_ATOM_HASH_SYMBOL:\n            return JS_ATOM_KIND_SYMBOL;\n        case JS_ATOM_HASH_PRIVATE:\n            return JS_ATOM_KIND_PRIVATE;\n        default:\n            abort();\n        }\n    default:\n        abort();\n    }\n}\n\nstatic BOOL JS_AtomIsString(JSContext *ctx, JSAtom v)\n{\n    return JS_AtomGetKind(ctx, v) == JS_ATOM_KIND_STRING;\n}\n\nstatic JSAtom js_get_atom_index(JSRuntime *rt, JSAtomStruct *p)\n{\n    uint32_t i = p->hash_next;  /* atom_index */\n    if (p->atom_type != JS_ATOM_TYPE_SYMBOL) {\n        JSAtomStruct *p1;\n\n        i = rt->atom_hash[p->hash & (rt->atom_hash_size - 1)];\n        p1 = rt->atom_array[i];\n        while (p1 != p) {\n            assert(i != 0);\n            i = p1->hash_next;\n            p1 = rt->atom_array[i];\n        }\n    }\n    return i;\n}\n\n/* string case (internal). Return JS_ATOM_NULL if error. 'str' is\n   freed. */\nstatic JSAtom __JS_NewAtom(JSRuntime *rt, JSString *str, int atom_type)\n{\n    uint32_t h, h1, i;\n    JSAtomStruct *p;\n    int len;\n\n#if 0\n    printf(\"__JS_NewAtom: \");  JS_DumpString(rt, str); printf(\"\\n\");\n#endif\n    if (atom_type < JS_ATOM_TYPE_SYMBOL) {\n        /* str is not NULL */\n        if (str->atom_type == atom_type) {\n            /* str is the atom, return its index */\n            i = js_get_atom_index(rt, str);\n            /* reduce string refcount and increase atom's unless constant */\n            if (__JS_AtomIsConst(i))\n                str->header.ref_count--;\n            return i;\n        }\n        /* try and locate an already registered atom */\n        len = str->len;\n        h = hash_string(str, atom_type);\n        h &= JS_ATOM_HASH_MASK;\n        h1 = h & (rt->atom_hash_size - 1);\n        i = rt->atom_hash[h1];\n        while (i != 0) {\n            p = rt->atom_array[i];\n            if (p->hash == h &&\n                p->atom_type == atom_type &&\n                p->len == len &&\n                js_string_memcmp(p, str, len) == 0) {\n                if (!__JS_AtomIsConst(i))\n                    p->header.ref_count++;\n                goto done;\n            }\n            i = p->hash_next;\n        }\n    } else {\n        h1 = 0; /* avoid warning */\n        if (atom_type == JS_ATOM_TYPE_SYMBOL) {\n            h = JS_ATOM_HASH_SYMBOL;\n        } else {\n            h = JS_ATOM_HASH_PRIVATE;\n            atom_type = JS_ATOM_TYPE_SYMBOL;\n        }\n    }\n\n    if (rt->atom_free_index == 0) {\n        /* allow new atom entries */\n        uint32_t new_size, start;\n        JSAtomStruct **new_array;\n\n        /* alloc new with size progression 3/2:\n           4 6 9 13 19 28 42 63 94 141 211 316 474 711 1066 1599 2398 3597 5395 8092\n           preallocating space for predefined atoms (at least 195).\n         */\n        new_size = max_int(211, rt->atom_size * 3 / 2);\n        if (new_size > JS_ATOM_MAX)\n            goto fail;\n        /* XXX: should use realloc2 to use slack space */\n        new_array = js_realloc_rt(rt, rt->atom_array, sizeof(*new_array) * new_size);\n        if (!new_array)\n            goto fail;\n        /* Note: the atom 0 is not used */\n        start = rt->atom_size;\n        if (start == 0) {\n            /* JS_ATOM_NULL entry */\n            p = js_mallocz_rt(rt, sizeof(JSAtomStruct));\n            if (!p) {\n                js_free_rt(rt, new_array);\n                goto fail;\n            }\n            p->header.ref_count = 1;  /* not refcounted */\n            p->atom_type = JS_ATOM_TYPE_SYMBOL;\n#ifdef DUMP_LEAKS\n            list_add_tail(&p->link, &rt->string_list);\n#endif\n            new_array[0] = p;\n            rt->atom_count++;\n            start = 1;\n        }\n        rt->atom_size = new_size;\n        rt->atom_array = new_array;\n        rt->atom_free_index = start;\n        for(i = start; i < new_size; i++) {\n            uint32_t next;\n            if (i == (new_size - 1))\n                next = 0;\n            else\n                next = i + 1;\n            rt->atom_array[i] = atom_set_free(next);\n        }\n    }\n\n    if (str) {\n        if (str->atom_type == 0) {\n            p = str;\n            p->atom_type = atom_type;\n        } else {\n            p = js_malloc_rt(rt, sizeof(JSString) +\n                             (str->len << str->is_wide_char) +\n                             1 - str->is_wide_char);\n            if (unlikely(!p))\n                goto fail;\n            p->header.ref_count = 1;\n            p->is_wide_char = str->is_wide_char;\n            p->len = str->len;\n#ifdef DUMP_LEAKS\n            list_add_tail(&p->link, &rt->string_list);\n#endif\n            memcpy(p->u.str8, str->u.str8, (str->len << str->is_wide_char) +\n                   1 - str->is_wide_char);\n            js_free_string(rt, str);\n        }\n    } else {\n        p = js_malloc_rt(rt, sizeof(JSAtomStruct)); /* empty wide string */\n        if (!p)\n            return JS_ATOM_NULL;\n        p->header.ref_count = 1;\n        p->is_wide_char = 1;    /* Hack to represent NULL as a JSString */\n        p->len = 0;\n#ifdef DUMP_LEAKS\n        list_add_tail(&p->link, &rt->string_list);\n#endif\n    }\n\n    /* use an already free entry */\n    i = rt->atom_free_index;\n    rt->atom_free_index = atom_get_free(rt->atom_array[i]);\n    rt->atom_array[i] = p;\n\n    p->hash = h;\n    p->hash_next = i;   /* atom_index */\n    p->atom_type = atom_type;\n\n    rt->atom_count++;\n\n    if (atom_type != JS_ATOM_TYPE_SYMBOL) {\n        p->hash_next = rt->atom_hash[h1];\n        rt->atom_hash[h1] = i;\n        if (unlikely(rt->atom_count >= rt->atom_count_resize))\n            JS_ResizeAtomHash(rt, rt->atom_hash_size * 2);\n    }\n\n    //    JS_DumpAtoms(rt);\n    return i;\n\n fail:\n    i = JS_ATOM_NULL;\n done:\n    if (str)\n        js_free_string(rt, str);\n    return i;\n}\n\n/* only works with zero terminated 8 bit strings */\nstatic JSAtom __JS_NewAtomInit(JSRuntime *rt, const char *str, int len,\n                               int atom_type)\n{\n    JSString *p;\n    p = js_alloc_string_rt(rt, len, 0);\n    if (!p)\n        return JS_ATOM_NULL;\n    memcpy(p->u.str8, str, len);\n    p->u.str8[len] = '\\0';\n    return __JS_NewAtom(rt, p, atom_type);\n}\n\nstatic JSAtom __JS_FindAtom(JSRuntime *rt, const char *str, size_t len,\n                            int atom_type)\n{\n    uint32_t h, h1, i;\n    JSAtomStruct *p;\n\n    h = hash_string8((const uint8_t *)str, len, JS_ATOM_TYPE_STRING);\n    h &= JS_ATOM_HASH_MASK;\n    h1 = h & (rt->atom_hash_size - 1);\n    i = rt->atom_hash[h1];\n    while (i != 0) {\n        p = rt->atom_array[i];\n        if (p->hash == h &&\n            p->atom_type == JS_ATOM_TYPE_STRING &&\n            p->len == len &&\n            p->is_wide_char == 0 &&\n            memcmp(p->u.str8, str, len) == 0) {\n            if (!__JS_AtomIsConst(i))\n                p->header.ref_count++;\n            return i;\n        }\n        i = p->hash_next;\n    }\n    return JS_ATOM_NULL;\n}\n\nstatic void JS_FreeAtomStruct(JSRuntime *rt, JSAtomStruct *p)\n{\n#if 0   /* JS_ATOM_NULL is not refcounted: __JS_AtomIsConst() includes 0 */\n    if (unlikely(i == JS_ATOM_NULL)) {\n        p->header.ref_count = INT32_MAX / 2;\n        return;\n    }\n#endif\n    uint32_t i = p->hash_next;  /* atom_index */\n    if (p->atom_type != JS_ATOM_TYPE_SYMBOL) {\n        JSAtomStruct *p0, *p1;\n        uint32_t h0;\n\n        h0 = p->hash & (rt->atom_hash_size - 1);\n        i = rt->atom_hash[h0];\n        p1 = rt->atom_array[i];\n        if (p1 == p) {\n            rt->atom_hash[h0] = p1->hash_next;\n        } else {\n            for(;;) {\n                assert(i != 0);\n                p0 = p1;\n                i = p1->hash_next;\n                p1 = rt->atom_array[i];\n                if (p1 == p) {\n                    p0->hash_next = p1->hash_next;\n                    break;\n                }\n            }\n        }\n    }\n    /* insert in free atom list */\n    rt->atom_array[i] = atom_set_free(rt->atom_free_index);\n    rt->atom_free_index = i;\n    /* free the string structure */\n#ifdef DUMP_LEAKS\n    list_del(&p->link);\n#endif\n    js_free_rt(rt, p);\n    rt->atom_count--;\n    assert(rt->atom_count >= 0);\n}\n\nstatic void __JS_FreeAtom(JSRuntime *rt, uint32_t i)\n{\n    JSAtomStruct *p;\n\n    p = rt->atom_array[i];\n    if (--p->header.ref_count > 0)\n        return;\n    JS_FreeAtomStruct(rt, p);\n}\n\n/* Warning: 'p' is freed */\nstatic JSAtom JS_NewAtomStr(JSContext *ctx, JSString *p)\n{\n    JSRuntime *rt = ctx->rt;\n    uint32_t n;\n    if (is_num_string(&n, p)) {\n        if (n <= JS_ATOM_MAX_INT) {\n            js_free_string(rt, p);\n            return __JS_AtomFromUInt32(n);\n        }\n    }\n    /* XXX: should generate an exception */\n    return __JS_NewAtom(rt, p, JS_ATOM_TYPE_STRING);\n}\n\nJSAtom JS_NewAtomLen(JSContext *ctx, const char *str, size_t len)\n{\n    JSValue val;\n\n    if (len == 0 || !is_digit(*str)) {\n        JSAtom atom = __JS_FindAtom(ctx->rt, str, len, JS_ATOM_TYPE_STRING);\n        if (atom)\n            return atom;\n    }\n    val = JS_NewStringLen(ctx, str, len);\n    if (JS_IsException(val))\n        return JS_ATOM_NULL;\n    return JS_NewAtomStr(ctx, JS_VALUE_GET_STRING(val));\n}\n\nJSAtom JS_NewAtom(JSContext *ctx, const char *str)\n{\n    return JS_NewAtomLen(ctx, str, strlen(str));\n}\n\nJSAtom JS_NewAtomUInt32(JSContext *ctx, uint32_t n)\n{\n    if (n <= JS_ATOM_MAX_INT) {\n        return __JS_AtomFromUInt32(n);\n    } else {\n        char buf[11];\n        JSValue val;\n        snprintf(buf, sizeof(buf), \"%u\", n);\n        val = JS_NewString(ctx, buf);\n        if (JS_IsException(val))\n            return JS_ATOM_NULL;\n        return __JS_NewAtom(ctx->rt, JS_VALUE_GET_STRING(val),\n                            JS_ATOM_TYPE_STRING);\n    }\n}\n\nstatic JSAtom JS_NewAtomInt64(JSContext *ctx, int64_t n)\n{\n    if ((uint64_t)n <= JS_ATOM_MAX_INT) {\n        return __JS_AtomFromUInt32((uint32_t)n);\n    } else {\n        char buf[24];\n        JSValue val;\n        snprintf(buf, sizeof(buf), \"%\" PRId64 , n);\n        val = JS_NewString(ctx, buf);\n        if (JS_IsException(val))\n            return JS_ATOM_NULL;\n        return __JS_NewAtom(ctx->rt, JS_VALUE_GET_STRING(val),\n                            JS_ATOM_TYPE_STRING);\n    }\n}\n\n/* 'p' is freed */\nstatic JSValue JS_NewSymbol(JSContext *ctx, JSString *p, int atom_type)\n{\n    JSRuntime *rt = ctx->rt;\n    JSAtom atom;\n    atom = __JS_NewAtom(rt, p, atom_type);\n    if (atom == JS_ATOM_NULL)\n        return JS_ThrowOutOfMemory(ctx);\n    return JS_MKPTR(JS_TAG_SYMBOL, rt->atom_array[atom]);\n}\n\n/* descr must be a non-numeric string atom */\nstatic JSValue JS_NewSymbolFromAtom(JSContext *ctx, JSAtom descr,\n                                    int atom_type)\n{\n    JSRuntime *rt = ctx->rt;\n    JSString *p;\n\n    assert(!__JS_AtomIsTaggedInt(descr));\n    assert(descr < rt->atom_size);\n    p = rt->atom_array[descr];\n    JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, p));\n    return JS_NewSymbol(ctx, p, atom_type);\n}\n\n#define ATOM_GET_STR_BUF_SIZE 64\n\n/* Should only be used for debug. */\nstatic const char *JS_AtomGetStrRT(JSRuntime *rt, char *buf, int buf_size,\n                                   JSAtom atom)\n{\n    if (__JS_AtomIsTaggedInt(atom)) {\n        snprintf(buf, buf_size, \"%u\", __JS_AtomToUInt32(atom));\n    } else {\n        JSAtomStruct *p;\n        assert(atom < rt->atom_size);\n        if (atom == JS_ATOM_NULL) {\n            snprintf(buf, buf_size, \"<null>\");\n        } else {\n            int i, c;\n            char *q;\n            JSString *str;\n\n            q = buf;\n            p = rt->atom_array[atom];\n            assert(!atom_is_free(p));\n            str = p;\n            if (str) {\n                if (!str->is_wide_char) {\n                    /* special case ASCII strings */\n                    c = 0;\n                    for(i = 0; i < str->len; i++) {\n                        c |= str->u.str8[i];\n                    }\n                    if (c < 0x80)\n                        return (const char *)str->u.str8;\n                }\n                for(i = 0; i < str->len; i++) {\n                    if (str->is_wide_char)\n                        c = str->u.str16[i];\n                    else\n                        c = str->u.str8[i];\n                    if ((q - buf) >= buf_size - UTF8_CHAR_LEN_MAX)\n                        break;\n                    if (c < 128) {\n                        *q++ = c;\n                    } else {\n                        q += unicode_to_utf8((uint8_t *)q, c);\n                    }\n                }\n            }\n            *q = '\\0';\n        }\n    }\n    return buf;\n}\n\nstatic const char *JS_AtomGetStr(JSContext *ctx, char *buf, int buf_size, JSAtom atom)\n{\n    return JS_AtomGetStrRT(ctx->rt, buf, buf_size, atom);\n}\n\nstatic JSValue __JS_AtomToValue(JSContext *ctx, JSAtom atom, BOOL force_string)\n{\n    char buf[ATOM_GET_STR_BUF_SIZE];\n\n    if (__JS_AtomIsTaggedInt(atom)) {\n        snprintf(buf, sizeof(buf), \"%u\", __JS_AtomToUInt32(atom));\n        return JS_NewString(ctx, buf);\n    } else {\n        JSRuntime *rt = ctx->rt;\n        JSAtomStruct *p;\n        assert(atom < rt->atom_size);\n        p = rt->atom_array[atom];\n        if (p->atom_type == JS_ATOM_TYPE_STRING) {\n            goto ret_string;\n        } else if (force_string) {\n            if (p->len == 0 && p->is_wide_char != 0) {\n                /* no description string */\n                p = rt->atom_array[JS_ATOM_empty_string];\n            }\n        ret_string:\n            return JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, p));\n        } else {\n            return JS_DupValue(ctx, JS_MKPTR(JS_TAG_SYMBOL, p));\n        }\n    }\n}\n\nJSValue JS_AtomToValue(JSContext *ctx, JSAtom atom)\n{\n    return __JS_AtomToValue(ctx, atom, FALSE);\n}\n\nJSValue JS_AtomToString(JSContext *ctx, JSAtom atom)\n{\n    return __JS_AtomToValue(ctx, atom, TRUE);\n}\n\n/* return TRUE if the atom is an array index (i.e. 0 <= index <=\n   2^32-2 and return its value */\nstatic BOOL JS_AtomIsArrayIndex(JSContext *ctx, uint32_t *pval, JSAtom atom)\n{\n    if (__JS_AtomIsTaggedInt(atom)) {\n        *pval = __JS_AtomToUInt32(atom);\n        return TRUE;\n    } else {\n        JSRuntime *rt = ctx->rt;\n        JSAtomStruct *p;\n        uint32_t val;\n\n        assert(atom < rt->atom_size);\n        p = rt->atom_array[atom];\n        if (p->atom_type == JS_ATOM_TYPE_STRING &&\n            is_num_string(&val, p) && val != -1) {\n            *pval = val;\n            return TRUE;\n        } else {\n            *pval = 0;\n            return FALSE;\n        }\n    }\n}\n\n/* This test must be fast if atom is not a numeric index (e.g. a\n   method name). Return JS_UNDEFINED if not a numeric\n   index. JS_EXCEPTION can also be returned. */\nstatic JSValue JS_AtomIsNumericIndex1(JSContext *ctx, JSAtom atom)\n{\n    JSRuntime *rt = ctx->rt;\n    JSAtomStruct *p1;\n    JSString *p;\n    int c, len, ret;\n    JSValue num, str;\n\n    if (__JS_AtomIsTaggedInt(atom))\n        return JS_NewInt32(ctx, __JS_AtomToUInt32(atom));\n    assert(atom < rt->atom_size);\n    p1 = rt->atom_array[atom];\n    if (p1->atom_type != JS_ATOM_TYPE_STRING)\n        return JS_UNDEFINED;\n    p = p1;\n    len = p->len;\n    if (p->is_wide_char) {\n        const uint16_t *r = p->u.str16, *r_end = p->u.str16 + len;\n        if (r >= r_end)\n            return JS_UNDEFINED;\n        c = *r;\n        if (c == '-') {\n            if (r >= r_end)\n                return JS_UNDEFINED;\n            r++;\n            c = *r;\n            /* -0 case is specific */\n            if (c == '0' && len == 2)\n                goto minus_zero;\n        }\n        /* XXX: should test NaN, but the tests do not check it */\n        if (!is_num(c)) {\n            /* XXX: String should be normalized, therefore 8-bit only */\n            const uint16_t nfinity16[7] = { 'n', 'f', 'i', 'n', 'i', 't', 'y' };\n            if (!(c =='I' && (r_end - r) == 8 &&\n                  !memcmp(r + 1, nfinity16, sizeof(nfinity16))))\n                return JS_UNDEFINED;\n        }\n    } else {\n        const uint8_t *r = p->u.str8, *r_end = p->u.str8 + len;\n        if (r >= r_end)\n            return JS_UNDEFINED;\n        c = *r;\n        if (c == '-') {\n            if (r >= r_end)\n                return JS_UNDEFINED;\n            r++;\n            c = *r;\n            /* -0 case is specific */\n            if (c == '0' && len == 2) {\n            minus_zero:\n                return __JS_NewFloat64(ctx, -0.0);\n            }\n        }\n        if (!is_num(c)) {\n            if (!(c =='I' && (r_end - r) == 8 &&\n                  !memcmp(r + 1, \"nfinity\", 7)))\n                return JS_UNDEFINED;\n        }\n    }\n    /* XXX: bignum: would be better to only accept integer to avoid\n       relying on current floating point precision */\n    /* this is ECMA CanonicalNumericIndexString primitive */\n    num = JS_ToNumber(ctx, JS_MKPTR(JS_TAG_STRING, p));\n    if (JS_IsException(num))\n        return num;\n    str = JS_ToString(ctx, num);\n    if (JS_IsException(str)) {\n        JS_FreeValue(ctx, num);\n        return str;\n    }\n    ret = js_string_compare(ctx, p, JS_VALUE_GET_STRING(str));\n    JS_FreeValue(ctx, str);\n    if (ret == 0) {\n        return num;\n    } else {\n        JS_FreeValue(ctx, num);\n        return JS_UNDEFINED;\n    }\n}\n\n/* return -1 if exception or TRUE/FALSE */\nstatic int JS_AtomIsNumericIndex(JSContext *ctx, JSAtom atom)\n{\n    JSValue num;\n    num = JS_AtomIsNumericIndex1(ctx, atom);\n    if (likely(JS_IsUndefined(num)))\n        return FALSE;\n    if (JS_IsException(num))\n        return -1;\n    JS_FreeValue(ctx, num);\n    return TRUE;\n}\n\nvoid JS_FreeAtom(JSContext *ctx, JSAtom v)\n{\n    if (!__JS_AtomIsConst(v))\n        __JS_FreeAtom(ctx->rt, v);\n}\n\nvoid JS_FreeAtomRT(JSRuntime *rt, JSAtom v)\n{\n    if (!__JS_AtomIsConst(v))\n        __JS_FreeAtom(rt, v);\n}\n\n/* return TRUE if 'v' is a symbol with a string description */\nstatic BOOL JS_AtomSymbolHasDescription(JSContext *ctx, JSAtom v)\n{\n    JSRuntime *rt;\n    JSAtomStruct *p;\n\n    rt = ctx->rt;\n    if (__JS_AtomIsTaggedInt(v))\n        return FALSE;\n    p = rt->atom_array[v];\n    return (((p->atom_type == JS_ATOM_TYPE_SYMBOL &&\n              p->hash == JS_ATOM_HASH_SYMBOL) ||\n             p->atom_type == JS_ATOM_TYPE_GLOBAL_SYMBOL) &&\n            !(p->len == 0 && p->is_wide_char != 0));\n}\n\nstatic __maybe_unused void print_atom(JSContext *ctx, JSAtom atom)\n{\n    char buf[ATOM_GET_STR_BUF_SIZE];\n    const char *p;\n    int i;\n\n    /* XXX: should handle embedded null characters */\n    /* XXX: should move encoding code to JS_AtomGetStr */\n    p = JS_AtomGetStr(ctx, buf, sizeof(buf), atom);\n    for (i = 0; p[i]; i++) {\n        int c = (unsigned char)p[i];\n        if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||\n              (c == '_' || c == '$') || (c >= '0' && c <= '9' && i > 0)))\n            break;\n    }\n    if (i > 0 && p[i] == '\\0') {\n        printf(\"%s\", p);\n    } else {\n        putchar('\"');\n        printf(\"%.*s\", i, p);\n        for (; p[i]; i++) {\n            int c = (unsigned char)p[i];\n            if (c == '\\\"' || c == '\\\\') {\n                putchar('\\\\');\n                putchar(c);\n            } else if (c >= ' ' && c <= 126) {\n                putchar(c);\n            } else if (c == '\\n') {\n                putchar('\\\\');\n                putchar('n');\n            } else {\n                printf(\"\\\\u%04x\", c);\n            }\n        }\n        putchar('\\\"');\n    }\n}\n\n/* free with JS_FreeCString() */\nconst char *JS_AtomToCString(JSContext *ctx, JSAtom atom)\n{\n    JSValue str;\n    const char *cstr;\n\n    str = JS_AtomToString(ctx, atom);\n    if (JS_IsException(str))\n        return NULL;\n    cstr = JS_ToCString(ctx, str);\n    JS_FreeValue(ctx, str);\n    return cstr;\n}\n\n/* return a string atom containing name concatenated with str1 */\nstatic JSAtom js_atom_concat_str(JSContext *ctx, JSAtom name, const char *str1)\n{\n    JSValue str;\n    JSAtom atom;\n    const char *cstr;\n    char *cstr2;\n    size_t len, len1;\n    \n    str = JS_AtomToString(ctx, name);\n    if (JS_IsException(str))\n        return JS_ATOM_NULL;\n    cstr = JS_ToCStringLen(ctx, &len, str);\n    if (!cstr)\n        goto fail;\n    len1 = strlen(str1);\n    cstr2 = js_malloc(ctx, len + len1 + 1);\n    if (!cstr2)\n        goto fail;\n    memcpy(cstr2, cstr, len);\n    memcpy(cstr2 + len, str1, len1);\n    cstr2[len + len1] = '\\0';\n    atom = JS_NewAtomLen(ctx, cstr2, len + len1);\n    js_free(ctx, cstr2);\n    JS_FreeCString(ctx, cstr);\n    JS_FreeValue(ctx, str);\n    return atom;\n fail:\n    JS_FreeCString(ctx, cstr);\n    JS_FreeValue(ctx, str);\n    return JS_ATOM_NULL;\n}\n\nstatic JSAtom js_atom_concat_num(JSContext *ctx, JSAtom name, uint32_t n)\n{\n    char buf[16];\n    snprintf(buf, sizeof(buf), \"%u\", n);\n    return js_atom_concat_str(ctx, name, buf);\n}\n\nstatic inline BOOL JS_IsEmptyString(JSValueConst v)\n{\n    return JS_VALUE_GET_TAG(v) == JS_TAG_STRING && JS_VALUE_GET_STRING(v)->len == 0;\n}\n\n/* JSClass support */\n\n/* a new class ID is allocated if *pclass_id != 0 */\nJSClassID JS_NewClassID(JSClassID *pclass_id)\n{\n    JSClassID class_id;\n    /* XXX: make it thread safe */\n    class_id = *pclass_id;\n    if (class_id == 0) {\n        class_id = js_class_id_alloc++;\n        *pclass_id = class_id;\n    }\n    return class_id;\n}\n\nBOOL JS_IsRegisteredClass(JSRuntime *rt, JSClassID class_id)\n{\n    return (class_id < rt->class_count &&\n            rt->class_array[class_id].class_id != 0);\n}\n\n/* create a new object internal class. Return -1 if error, 0 if\n   OK. The finalizer can be NULL if none is needed. */\nstatic int JS_NewClass1(JSRuntime *rt, JSClassID class_id,\n                        const JSClassDef *class_def, JSAtom name)\n{\n    int new_size, i;\n    JSClass *cl, *new_class_array;\n    struct list_head *el;\n\n    if (class_id >= (1 << 16))\n        return -1;\n    if (class_id < rt->class_count &&\n        rt->class_array[class_id].class_id != 0)\n        return -1;\n\n    if (class_id >= rt->class_count) {\n        new_size = max_int(JS_CLASS_INIT_COUNT,\n                           max_int(class_id + 1, rt->class_count * 3 / 2));\n\n        /* reallocate the context class prototype array, if any */\n        list_for_each(el, &rt->context_list) {\n            JSContext *ctx = list_entry(el, JSContext, link);\n            JSValue *new_tab;\n            new_tab = js_realloc_rt(rt, ctx->class_proto,\n                                    sizeof(ctx->class_proto[0]) * new_size);\n            if (!new_tab)\n                return -1;\n            for(i = rt->class_count; i < new_size; i++)\n                new_tab[i] = JS_NULL;\n            ctx->class_proto = new_tab;\n        }\n        /* reallocate the class array */\n        new_class_array = js_realloc_rt(rt, rt->class_array,\n                                        sizeof(JSClass) * new_size);\n        if (!new_class_array)\n            return -1;\n        memset(new_class_array + rt->class_count, 0,\n               (new_size - rt->class_count) * sizeof(JSClass));\n        rt->class_array = new_class_array;\n        rt->class_count = new_size;\n    }\n    cl = &rt->class_array[class_id];\n    cl->class_id = class_id;\n    cl->class_name = JS_DupAtomRT(rt, name);\n    cl->finalizer = class_def->finalizer;\n    cl->gc_mark = class_def->gc_mark;\n    cl->call = class_def->call;\n    cl->exotic = class_def->exotic;\n    return 0;\n}\n\nint JS_NewClass(JSRuntime *rt, JSClassID class_id, const JSClassDef *class_def)\n{\n    int ret, len;\n    JSAtom name;\n\n    len = strlen(class_def->class_name);\n    name = __JS_FindAtom(rt, class_def->class_name, len, JS_ATOM_TYPE_STRING);\n    if (name == JS_ATOM_NULL) {\n        name = __JS_NewAtomInit(rt, class_def->class_name, len, JS_ATOM_TYPE_STRING);\n        if (name == JS_ATOM_NULL)\n            return -1;\n    }\n    ret = JS_NewClass1(rt, class_id, class_def, name);\n    JS_FreeAtomRT(rt, name);\n    return ret;\n}\n\nstatic JSValue js_new_string8(JSContext *ctx, const uint8_t *buf, int len)\n{\n    JSString *str;\n\n    if (len <= 0) {\n        return JS_AtomToString(ctx, JS_ATOM_empty_string);\n    }\n    str = js_alloc_string(ctx, len, 0);\n    if (!str)\n        return JS_EXCEPTION;\n    memcpy(str->u.str8, buf, len);\n    str->u.str8[len] = '\\0';\n    return JS_MKPTR(JS_TAG_STRING, str);\n}\n\nstatic JSValue js_new_string16(JSContext *ctx, const uint16_t *buf, int len)\n{\n    JSString *str;\n    str = js_alloc_string(ctx, len, 1);\n    if (!str)\n        return JS_EXCEPTION;\n    memcpy(str->u.str16, buf, len * 2);\n    return JS_MKPTR(JS_TAG_STRING, str);\n}\n\nstatic JSValue js_new_string_char(JSContext *ctx, uint16_t c)\n{\n    if (c < 0x100) {\n        uint8_t ch8 = c;\n        return js_new_string8(ctx, &ch8, 1);\n    } else {\n        uint16_t ch16 = c;\n        return js_new_string16(ctx, &ch16, 1);\n    }\n}\n\nstatic JSValue js_sub_string(JSContext *ctx, JSString *p, int start, int end)\n{\n    int len = end - start;\n    if (start == 0 && end == p->len) {\n        return JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, p));\n    }\n    if (p->is_wide_char && len > 0) {\n        JSString *str;\n        int i;\n        uint16_t c = 0;\n        for (i = start; i < end; i++) {\n            c |= p->u.str16[i];\n        }\n        if (c > 0xFF)\n            return js_new_string16(ctx, p->u.str16 + start, len);\n\n        str = js_alloc_string(ctx, len, 0);\n        if (!str)\n            return JS_EXCEPTION;\n        for (i = 0; i < len; i++) {\n            str->u.str8[i] = p->u.str16[start + i];\n        }\n        str->u.str8[len] = '\\0';\n        return JS_MKPTR(JS_TAG_STRING, str);\n    } else {\n        return js_new_string8(ctx, p->u.str8 + start, len);\n    }\n}\n\ntypedef struct StringBuffer {\n    JSContext *ctx;\n    JSString *str;\n    int len;\n    int size;\n    int is_wide_char;\n    int error_status;\n} StringBuffer;\n\n/* It is valid to call string_buffer_end() and all string_buffer functions even\n   if string_buffer_init() or another string_buffer function returns an error.\n   If the error_status is set, string_buffer_end() returns JS_EXCEPTION.\n */\nstatic int string_buffer_init2(JSContext *ctx, StringBuffer *s, int size,\n                               int is_wide)\n{\n    s->ctx = ctx;\n    s->size = size;\n    s->len = 0;\n    s->is_wide_char = is_wide;\n    s->error_status = 0;\n    s->str = js_alloc_string(ctx, size, is_wide);\n    if (unlikely(!s->str)) {\n        s->size = 0;\n        return s->error_status = -1;\n    }\n#ifdef DUMP_LEAKS\n    /* the StringBuffer may reallocate the JSString, only link it at the end */\n    list_del(&s->str->link);\n#endif\n    return 0;\n}\n\nstatic inline int string_buffer_init(JSContext *ctx, StringBuffer *s, int size)\n{\n    return string_buffer_init2(ctx, s, size, 0);\n}\n\nstatic void string_buffer_free(StringBuffer *s)\n{\n    js_free(s->ctx, s->str);\n    s->str = NULL;\n}\n\nstatic int string_buffer_set_error(StringBuffer *s)\n{\n    js_free(s->ctx, s->str);\n    s->str = NULL;\n    s->size = 0;\n    s->len = 0;\n    return s->error_status = -1;\n}\n\nstatic no_inline int string_buffer_widen(StringBuffer *s, int size)\n{\n    JSString *str;\n    size_t slack;\n    int i;\n\n    if (s->error_status)\n        return -1;\n\n    str = js_realloc2(s->ctx, s->str, sizeof(JSString) + (size << 1), &slack);\n    if (!str)\n        return string_buffer_set_error(s);\n    size += slack >> 1;\n    for(i = s->len; i-- > 0;) {\n        str->u.str16[i] = str->u.str8[i];\n    }\n    s->is_wide_char = 1;\n    s->size = size;\n    s->str = str;\n    return 0;\n}\n\nstatic no_inline int string_buffer_realloc(StringBuffer *s, int new_len, int c)\n{\n    JSString *new_str;\n    int new_size;\n    size_t new_size_bytes, slack;\n\n    if (s->error_status)\n        return -1;\n\n    if (new_len > JS_STRING_LEN_MAX) {\n        JS_ThrowInternalError(s->ctx, \"string too long\");\n        return string_buffer_set_error(s);\n    }\n    new_size = min_int(max_int(new_len, s->size * 3 / 2), JS_STRING_LEN_MAX);\n    if (!s->is_wide_char && c >= 0x100) {\n        return string_buffer_widen(s, new_size);\n    }\n    new_size_bytes = sizeof(JSString) + (new_size << s->is_wide_char) + 1 - s->is_wide_char;\n    new_str = js_realloc2(s->ctx, s->str, new_size_bytes, &slack);\n    if (!new_str)\n        return string_buffer_set_error(s);\n    new_size = min_int(new_size + (slack >> s->is_wide_char), JS_STRING_LEN_MAX);\n    s->size = new_size;\n    s->str = new_str;\n    return 0;\n}\n\nstatic no_inline int string_buffer_putc_slow(StringBuffer *s, uint32_t c)\n{\n    if (unlikely(s->len >= s->size)) {\n        if (string_buffer_realloc(s, s->len + 1, c))\n            return -1;\n    }\n    if (s->is_wide_char) {\n        s->str->u.str16[s->len++] = c;\n    } else if (c < 0x100) {\n        s->str->u.str8[s->len++] = c;\n    } else {\n        if (string_buffer_widen(s, s->size))\n            return -1;\n        s->str->u.str16[s->len++] = c;\n    }\n    return 0;\n}\n\n/* 0 <= c <= 0xff */\nstatic int string_buffer_putc8(StringBuffer *s, uint32_t c)\n{\n    if (unlikely(s->len >= s->size)) {\n        if (string_buffer_realloc(s, s->len + 1, c))\n            return -1;\n    }\n    if (s->is_wide_char) {\n        s->str->u.str16[s->len++] = c;\n    } else {\n        s->str->u.str8[s->len++] = c;\n    }\n    return 0;\n}\n\n/* 0 <= c <= 0xffff */\nstatic int string_buffer_putc16(StringBuffer *s, uint32_t c)\n{\n    if (likely(s->len < s->size)) {\n        if (s->is_wide_char) {\n            s->str->u.str16[s->len++] = c;\n            return 0;\n        } else if (c < 0x100) {\n            s->str->u.str8[s->len++] = c;\n            return 0;\n        }\n    }\n    return string_buffer_putc_slow(s, c);\n}\n\n/* 0 <= c <= 0x10ffff */\nstatic int string_buffer_putc(StringBuffer *s, uint32_t c)\n{\n    if (unlikely(c >= 0x10000)) {\n        /* surrogate pair */\n        c -= 0x10000;\n        if (string_buffer_putc16(s, (c >> 10) + 0xd800))\n            return -1;\n        c = (c & 0x3ff) + 0xdc00;\n    }\n    return string_buffer_putc16(s, c);\n}\n\nstatic int string_get(const JSString *p, int idx) {\n    return p->is_wide_char ? p->u.str16[idx] : p->u.str8[idx];\n}\n\nstatic int string_getc(const JSString *p, int *pidx)\n{\n    int idx, c, c1;\n    idx = *pidx;\n    if (p->is_wide_char) {\n        c = p->u.str16[idx++];\n        if (c >= 0xd800 && c < 0xdc00 && idx < p->len) {\n            c1 = p->u.str16[idx];\n            if (c1 >= 0xdc00 && c1 < 0xe000) {\n                c = (((c & 0x3ff) << 10) | (c1 & 0x3ff)) + 0x10000;\n                idx++;\n            }\n        }\n    } else {\n        c = p->u.str8[idx++];\n    }\n    *pidx = idx;\n    return c;\n}\n\nstatic int string_buffer_write8(StringBuffer *s, const uint8_t *p, int len)\n{\n    int i;\n\n    if (s->len + len > s->size) {\n        if (string_buffer_realloc(s, s->len + len, 0))\n            return -1;\n    }\n    if (s->is_wide_char) {\n        for (i = 0; i < len; i++) {\n            s->str->u.str16[s->len + i] = p[i];\n        }\n        s->len += len;\n    } else {\n        memcpy(&s->str->u.str8[s->len], p, len);\n        s->len += len;\n    }\n    return 0;\n}\n\nstatic int string_buffer_write16(StringBuffer *s, const uint16_t *p, int len)\n{\n    int c = 0, i;\n\n    for (i = 0; i < len; i++) {\n        c |= p[i];\n    }\n    if (s->len + len > s->size) {\n        if (string_buffer_realloc(s, s->len + len, c))\n            return -1;\n    } else if (!s->is_wide_char && c >= 0x100) {\n        if (string_buffer_widen(s, s->size))\n            return -1;\n    }\n    if (s->is_wide_char) {\n        memcpy(&s->str->u.str16[s->len], p, len << 1);\n        s->len += len;\n    } else {\n        for (i = 0; i < len; i++) {\n            s->str->u.str8[s->len + i] = p[i];\n        }\n        s->len += len;\n    }\n    return 0;\n}\n\n/* appending an ASCII string */\nstatic int string_buffer_puts8(StringBuffer *s, const char *str)\n{\n    return string_buffer_write8(s, (const uint8_t *)str, strlen(str));\n}\n\nstatic int string_buffer_concat(StringBuffer *s, const JSString *p,\n                                uint32_t from, uint32_t to)\n{\n    if (to <= from)\n        return 0;\n    if (p->is_wide_char)\n        return string_buffer_write16(s, p->u.str16 + from, to - from);\n    else\n        return string_buffer_write8(s, p->u.str8 + from, to - from);\n}\n\nstatic int string_buffer_concat_value(StringBuffer *s, JSValueConst v)\n{\n    JSString *p;\n    JSValue v1;\n    int res;\n\n    if (s->error_status) {\n        /* prevent exception overload */\n        return -1;\n    }\n    if (unlikely(JS_VALUE_GET_TAG(v) != JS_TAG_STRING)) {\n        v1 = JS_ToString(s->ctx, v);\n        if (JS_IsException(v1))\n            return string_buffer_set_error(s);\n        p = JS_VALUE_GET_STRING(v1);\n        res = string_buffer_concat(s, p, 0, p->len);\n        JS_FreeValue(s->ctx, v1);\n        return res;\n    }\n    p = JS_VALUE_GET_STRING(v);\n    return string_buffer_concat(s, p, 0, p->len);\n}\n\nstatic int string_buffer_concat_value_free(StringBuffer *s, JSValue v)\n{\n    JSString *p;\n    int res;\n\n    if (s->error_status) {\n        /* prevent exception overload */\n        JS_FreeValue(s->ctx, v);\n        return -1;\n    }\n    if (unlikely(JS_VALUE_GET_TAG(v) != JS_TAG_STRING)) {\n        v = JS_ToStringFree(s->ctx, v);\n        if (JS_IsException(v))\n            return string_buffer_set_error(s);\n    }\n    p = JS_VALUE_GET_STRING(v);\n    res = string_buffer_concat(s, p, 0, p->len);\n    JS_FreeValue(s->ctx, v);\n    return res;\n}\n\nstatic int string_buffer_fill(StringBuffer *s, int c, int count)\n{\n    /* XXX: optimize */\n    if (s->len + count > s->size) {\n        if (string_buffer_realloc(s, s->len + count, c))\n            return -1;\n    }\n    while (count-- > 0) {\n        if (string_buffer_putc16(s, c))\n            return -1;\n    }\n    return 0;\n}\n\nstatic JSValue string_buffer_end(StringBuffer *s)\n{\n    JSString *str;\n    str = s->str;\n    if (s->error_status)\n        return JS_EXCEPTION;\n    if (s->len == 0) {\n        js_free(s->ctx, str);\n        s->str = NULL;\n        return JS_AtomToString(s->ctx, JS_ATOM_empty_string);\n    }\n    if (s->len < s->size) {\n        /* smaller size so js_realloc should not fail, but OK if it does */\n        /* XXX: should add some slack to avoid unnecessary calls */\n        /* XXX: might need to use malloc+free to ensure smaller size */\n        str = js_realloc_rt(s->ctx->rt, str, sizeof(JSString) +\n                            (s->len << s->is_wide_char) + 1 - s->is_wide_char);\n        if (str == NULL)\n            str = s->str;\n        s->str = str;\n    }\n    if (!s->is_wide_char)\n        str->u.str8[s->len] = 0;\n#ifdef DUMP_LEAKS\n    list_add_tail(&str->link, &s->ctx->rt->string_list);\n#endif\n    str->is_wide_char = s->is_wide_char;\n    str->len = s->len;\n    s->str = NULL;\n    return JS_MKPTR(JS_TAG_STRING, str);\n}\n\n/* create a string from a UTF-8 buffer */\nJSValue JS_NewStringLen(JSContext *ctx, const char *buf, size_t buf_len)\n{\n    const uint8_t *p, *p_end, *p_start, *p_next;\n    uint32_t c;\n    StringBuffer b_s, *b = &b_s;\n    size_t len1;\n    \n    p_start = (const uint8_t *)buf;\n    p_end = p_start + buf_len;\n    p = p_start;\n    while (p < p_end && *p < 128)\n        p++;\n    len1 = p - p_start;\n    if (len1 > JS_STRING_LEN_MAX)\n        return JS_ThrowInternalError(ctx, \"string too long\");\n    if (p == p_end) {\n        /* ASCII string */\n        return js_new_string8(ctx, (const uint8_t *)buf, buf_len);\n    } else {\n        if (string_buffer_init(ctx, b, buf_len))\n            goto fail;\n        string_buffer_write8(b, p_start, len1);\n        while (p < p_end) {\n            if (*p < 128) {\n                string_buffer_putc8(b, *p++);\n            } else {\n                /* parse utf-8 sequence, return 0xFFFFFFFF for error */\n                c = unicode_from_utf8(p, p_end - p, &p_next);\n                if (c < 0x10000) {\n                    p = p_next;\n                } else if (c <= 0x10FFFF) {\n                    p = p_next;\n                    /* surrogate pair */\n                    c -= 0x10000;\n                    string_buffer_putc16(b, (c >> 10) + 0xd800);\n                    c = (c & 0x3ff) + 0xdc00;\n                } else {\n                    /* invalid char */\n                    c = 0xfffd;\n                    /* skip the invalid chars */\n                    /* XXX: seems incorrect. Why not just use c = *p++; ? */\n                    while (p < p_end && (*p >= 0x80 && *p < 0xc0))\n                        p++;\n                    if (p < p_end) {\n                        p++;\n                        while (p < p_end && (*p >= 0x80 && *p < 0xc0))\n                            p++;\n                    }\n                }\n                string_buffer_putc16(b, c);\n            }\n        }\n    }\n    return string_buffer_end(b);\n\n fail:\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ConcatString3(JSContext *ctx, const char *str1,\n                                JSValue str2, const char *str3)\n{\n    StringBuffer b_s, *b = &b_s;\n    int len1, len3;\n    JSString *p;\n\n    if (unlikely(JS_VALUE_GET_TAG(str2) != JS_TAG_STRING)) {\n        str2 = JS_ToStringFree(ctx, str2);\n        if (JS_IsException(str2))\n            goto fail;\n    }\n    p = JS_VALUE_GET_STRING(str2);\n    len1 = strlen(str1);\n    len3 = strlen(str3);\n\n    if (string_buffer_init2(ctx, b, len1 + p->len + len3, p->is_wide_char))\n        goto fail;\n\n    string_buffer_write8(b, (const uint8_t *)str1, len1);\n    string_buffer_concat(b, p, 0, p->len);\n    string_buffer_write8(b, (const uint8_t *)str3, len3);\n\n    JS_FreeValue(ctx, str2);\n    return string_buffer_end(b);\n\n fail:\n    JS_FreeValue(ctx, str2);\n    return JS_EXCEPTION;\n}\n\nJSValue JS_NewString(JSContext *ctx, const char *str)\n{\n    return JS_NewStringLen(ctx, str, strlen(str));\n}\n\nJSValue JS_NewAtomString(JSContext *ctx, const char *str)\n{\n    JSAtom atom = JS_NewAtom(ctx, str);\n    if (atom == JS_ATOM_NULL)\n        return JS_EXCEPTION;\n    JSValue val = JS_AtomToString(ctx, atom);\n    JS_FreeAtom(ctx, atom);\n    return val;\n}\n\n/* return (NULL, 0) if exception. */\n/* return pointer into a JSString with a live ref_count */\n/* cesu8 determines if non-BMP1 codepoints are encoded as 1 or 2 utf-8 sequences */\nconst char *JS_ToCStringLen2(JSContext *ctx, size_t *plen, JSValueConst val1, BOOL cesu8)\n{\n    JSValue val;\n    JSString *str, *str_new;\n    int pos, len, c, c1;\n    uint8_t *q;\n\n    if (JS_VALUE_GET_TAG(val1) != JS_TAG_STRING) {\n        val = JS_ToString(ctx, val1);\n        if (JS_IsException(val))\n            goto fail;\n    } else {\n        val = JS_DupValue(ctx, val1);\n    }\n\n    str = JS_VALUE_GET_STRING(val);\n    len = str->len;\n    if (!str->is_wide_char) {\n        const uint8_t *src = str->u.str8;\n        int count;\n\n        /* count the number of non-ASCII characters */\n        /* Scanning the whole string is required for ASCII strings,\n           and computing the number of non-ASCII bytes is less expensive\n           than testing each byte, hence this method is faster for ASCII\n           strings, which is the most common case.\n         */\n        count = 0;\n        for (pos = 0; pos < len; pos++) {\n            count += src[pos] >> 7;\n        }\n        if (count == 0) {\n            if (plen)\n                *plen = len;\n            return (const char *)src;\n        }\n        str_new = js_alloc_string(ctx, len + count, 0);\n        if (!str_new)\n            goto fail;\n        q = str_new->u.str8;\n        for (pos = 0; pos < len; pos++) {\n            c = src[pos];\n            if (c < 0x80) {\n                *q++ = c;\n            } else {\n                *q++ = (c >> 6) | 0xc0;\n                *q++ = (c & 0x3f) | 0x80;\n            }\n        }\n    } else {\n        const uint16_t *src = str->u.str16;\n        /* Allocate 3 bytes per 16 bit code point. Surrogate pairs may\n           produce 4 bytes but use 2 code points.\n         */\n        str_new = js_alloc_string(ctx, len * 3, 0);\n        if (!str_new)\n            goto fail;\n        q = str_new->u.str8;\n        pos = 0;\n        while (pos < len) {\n            c = src[pos++];\n            if (c < 0x80) {\n                *q++ = c;\n            } else {\n                if (c >= 0xd800 && c < 0xdc00) {\n                    if (pos < len && !cesu8) {\n                        c1 = src[pos];\n                        if (c1 >= 0xdc00 && c1 < 0xe000) {\n                            pos++;\n                            /* surrogate pair */\n                            c = (((c & 0x3ff) << 10) | (c1 & 0x3ff)) + 0x10000;\n                        } else {\n                            /* Keep unmatched surrogate code points */\n                            /* c = 0xfffd; */ /* error */\n                        }\n                    } else {\n                        /* Keep unmatched surrogate code points */\n                        /* c = 0xfffd; */ /* error */\n                    }\n                }\n                q += unicode_to_utf8(q, c);\n            }\n        }\n    }\n\n    *q = '\\0';\n    str_new->len = q - str_new->u.str8;\n    JS_FreeValue(ctx, val);\n    if (plen)\n        *plen = str_new->len;\n    return (const char *)str_new->u.str8;\n fail:\n    if (plen)\n        *plen = 0;\n    return NULL;\n}\n\nvoid JS_FreeCString(JSContext *ctx, const char *ptr)\n{\n    JSString *p;\n    if (!ptr)\n        return;\n    /* purposely removing constness */\n    p = (JSString *)(void *)(ptr - offsetof(JSString, u));\n    JS_FreeValue(ctx, JS_MKPTR(JS_TAG_STRING, p));\n}\n\nstatic int memcmp16_8(const uint16_t *src1, const uint8_t *src2, int len)\n{\n    int c, i;\n    for(i = 0; i < len; i++) {\n        c = src1[i] - src2[i];\n        if (c != 0)\n            return c;\n    }\n    return 0;\n}\n\nstatic int memcmp16(const uint16_t *src1, const uint16_t *src2, int len)\n{\n    int c, i;\n    for(i = 0; i < len; i++) {\n        c = src1[i] - src2[i];\n        if (c != 0)\n            return c;\n    }\n    return 0;\n}\n\nstatic int js_string_memcmp(const JSString *p1, const JSString *p2, int len)\n{\n    int res;\n\n    if (likely(!p1->is_wide_char)) {\n        if (likely(!p2->is_wide_char))\n            res = memcmp(p1->u.str8, p2->u.str8, len);\n        else\n            res = -memcmp16_8(p2->u.str16, p1->u.str8, len);\n    } else {\n        if (!p2->is_wide_char)\n            res = memcmp16_8(p1->u.str16, p2->u.str8, len);\n        else\n            res = memcmp16(p1->u.str16, p2->u.str16, len);\n    }\n    return res;\n}\n\n/* return < 0, 0 or > 0 */\nint js_string_compare(JSContext *ctx,\n                             const JSString *p1, const JSString *p2)\n{\n    int res, len;\n    len = min_int(p1->len, p2->len);\n    res = js_string_memcmp(p1, p2, len);\n    if (res == 0) {\n        if (p1->len == p2->len)\n            res = 0;\n        else if (p1->len < p2->len)\n            res = -1;\n        else\n            res = 1;\n    }\n    return res;\n}\n\nstatic void copy_str16(uint16_t *dst, const JSString *p, int offset, int len)\n{\n    if (p->is_wide_char) {\n        memcpy(dst, p->u.str16 + offset, len * 2);\n    } else {\n        const uint8_t *src1 = p->u.str8 + offset;\n        int i;\n\n        for(i = 0; i < len; i++)\n            dst[i] = src1[i];\n    }\n}\n\nstatic JSValue JS_ConcatString1(JSContext *ctx,\n                                const JSString *p1, const JSString *p2)\n{\n    JSString *p;\n    uint32_t len;\n    int is_wide_char;\n\n    len = p1->len + p2->len;\n    if (len > JS_STRING_LEN_MAX)\n        return JS_ThrowInternalError(ctx, \"string too long\");\n    is_wide_char = p1->is_wide_char | p2->is_wide_char;\n    p = js_alloc_string(ctx, len, is_wide_char);\n    if (!p)\n        return JS_EXCEPTION;\n    if (!is_wide_char) {\n        memcpy(p->u.str8, p1->u.str8, p1->len);\n        memcpy(p->u.str8 + p1->len, p2->u.str8, p2->len);\n        p->u.str8[len] = '\\0';\n    } else {\n        copy_str16(p->u.str16, p1, 0, p1->len);\n        copy_str16(p->u.str16 + p1->len, p2, 0, p2->len);\n    }\n    return JS_MKPTR(JS_TAG_STRING, p);\n}\n\n/* op1 and op2 are converted to strings. For convience, op1 or op2 =\n   JS_EXCEPTION are accepted and return JS_EXCEPTION.  */\nstatic JSValue JS_ConcatString(JSContext *ctx, JSValue op1, JSValue op2)\n{\n    JSValue ret;\n    JSString *p1, *p2;\n\n    if (unlikely(JS_VALUE_GET_TAG(op1) != JS_TAG_STRING)) {\n        op1 = JS_ToStringFree(ctx, op1);\n        if (JS_IsException(op1)) {\n            JS_FreeValue(ctx, op2);\n            return JS_EXCEPTION;\n        }\n    }\n    if (unlikely(JS_VALUE_GET_TAG(op2) != JS_TAG_STRING)) {\n        op2 = JS_ToStringFree(ctx, op2);\n        if (JS_IsException(op2)) {\n            JS_FreeValue(ctx, op1);\n            return JS_EXCEPTION;\n        }\n    }\n    p1 = JS_VALUE_GET_STRING(op1);\n    p2 = JS_VALUE_GET_STRING(op2);\n\n    /* XXX: could also check if p1 is empty */\n    if (p2->len == 0) {\n        goto ret_op1;\n    }\n    if (p1->header.ref_count == 1 && p1->is_wide_char == p2->is_wide_char\n    &&  js_malloc_usable_size(ctx, p1) >= sizeof(*p1) + ((p1->len + p2->len) << p2->is_wide_char) + 1 - p1->is_wide_char) {\n        /* Concatenate in place in available space at the end of p1 */\n        if (p1->is_wide_char) {\n            memcpy(p1->u.str16 + p1->len, p2->u.str16, p2->len << 1);\n            p1->len += p2->len;\n        } else {\n            memcpy(p1->u.str8 + p1->len, p2->u.str8, p2->len);\n            p1->len += p2->len;\n            p1->u.str8[p1->len] = '\\0';\n        }\n    ret_op1:\n        JS_FreeValue(ctx, op2);\n        return op1;\n    }\n    ret = JS_ConcatString1(ctx, p1, p2);\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    return ret;\n}\n\n/* Shape support */\n\nstatic inline size_t get_shape_size(size_t hash_size, size_t prop_size)\n{\n    return hash_size * sizeof(uint32_t) + sizeof(JSShape) +\n        prop_size * sizeof(JSShapeProperty);\n}\n\nstatic inline JSShape *get_shape_from_alloc(void *sh_alloc, size_t hash_size)\n{\n    return (JSShape *)(void *)((uint32_t *)sh_alloc + hash_size);\n}\n\nstatic inline uint32_t *prop_hash_end(JSShape *sh)\n{\n    return (uint32_t *)sh;\n}\n\nstatic inline void *get_alloc_from_shape(JSShape *sh)\n{\n    return prop_hash_end(sh) - ((intptr_t)sh->prop_hash_mask + 1);\n}\n\nstatic inline JSShapeProperty *get_shape_prop(JSShape *sh)\n{\n    return sh->prop;\n}\n\nstatic int init_shape_hash(JSRuntime *rt)\n{\n    rt->shape_hash_bits = 4;   /* 16 shapes */\n    rt->shape_hash_size = 1 << rt->shape_hash_bits;\n    rt->shape_hash_count = 0;\n    rt->shape_hash = js_mallocz_rt(rt, sizeof(rt->shape_hash[0]) *\n                                   rt->shape_hash_size);\n    if (!rt->shape_hash)\n        return -1;\n    return 0;\n}\n\n/* same magic hash multiplier as the Linux kernel */\nstatic uint32_t shape_hash(uint32_t h, uint32_t val)\n{\n    return (h + val) * 0x9e370001;\n}\n\n/* truncate the shape hash to 'hash_bits' bits */\nstatic uint32_t get_shape_hash(uint32_t h, int hash_bits)\n{\n    return h >> (32 - hash_bits);\n}\n\nstatic uint32_t shape_initial_hash(JSObject *proto)\n{\n    uint32_t h;\n    h = shape_hash(1, (uintptr_t)proto);\n    if (sizeof(proto) > 4)\n        h = shape_hash(h, (uint64_t)(uintptr_t)proto >> 32);\n    return h;\n}\n\nstatic int resize_shape_hash(JSRuntime *rt, int new_shape_hash_bits)\n{\n    int new_shape_hash_size, i;\n    uint32_t h;\n    JSShape **new_shape_hash, *sh, *sh_next;\n\n    new_shape_hash_size = 1 << new_shape_hash_bits;\n    new_shape_hash = js_mallocz_rt(rt, sizeof(rt->shape_hash[0]) *\n                                   new_shape_hash_size);\n    if (!new_shape_hash)\n        return -1;\n    for(i = 0; i < rt->shape_hash_size; i++) {\n        for(sh = rt->shape_hash[i]; sh != NULL; sh = sh_next) {\n            sh_next = sh->shape_hash_next;\n            h = get_shape_hash(sh->hash, new_shape_hash_bits);\n            sh->shape_hash_next = new_shape_hash[h];\n            new_shape_hash[h] = sh;\n        }\n    }\n    js_free_rt(rt, rt->shape_hash);\n    rt->shape_hash_bits = new_shape_hash_bits;\n    rt->shape_hash_size = new_shape_hash_size;\n    rt->shape_hash = new_shape_hash;\n    return 0;\n}\n\nstatic void js_shape_hash_link(JSRuntime *rt, JSShape *sh)\n{\n    uint32_t h;\n    h = get_shape_hash(sh->hash, rt->shape_hash_bits);\n    sh->shape_hash_next = rt->shape_hash[h];\n    rt->shape_hash[h] = sh;\n    rt->shape_hash_count++;\n}\n\nstatic void js_shape_hash_unlink(JSRuntime *rt, JSShape *sh)\n{\n    uint32_t h;\n    JSShape **psh;\n\n    h = get_shape_hash(sh->hash, rt->shape_hash_bits);\n    psh = &rt->shape_hash[h];\n    while (*psh != sh)\n        psh = &(*psh)->shape_hash_next;\n    *psh = sh->shape_hash_next;\n    rt->shape_hash_count--;\n}\n\n/* create a new empty shape with prototype 'proto' */\nstatic no_inline JSShape *js_new_shape2(JSContext *ctx, JSObject *proto,\n                                        int hash_size, int prop_size)\n{\n    JSRuntime *rt = ctx->rt;\n    void *sh_alloc;\n    JSShape *sh;\n\n    /* resize the shape hash table if necessary */\n    if (2 * (rt->shape_hash_count + 1) > rt->shape_hash_size) {\n        resize_shape_hash(rt, rt->shape_hash_bits + 1);\n    }\n\n    sh_alloc = js_malloc(ctx, get_shape_size(hash_size, prop_size));\n    if (!sh_alloc)\n        return NULL;\n    sh = get_shape_from_alloc(sh_alloc, hash_size);\n    sh->header.ref_count = 1;\n    add_gc_object(rt, &sh->header, JS_GC_OBJ_TYPE_SHAPE);\n    if (proto)\n        JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, proto));\n    sh->proto = proto;\n    memset(prop_hash_end(sh) - hash_size, 0, sizeof(prop_hash_end(sh)[0]) *\n           hash_size);\n    sh->prop_hash_mask = hash_size - 1;\n    sh->prop_size = prop_size;\n    sh->prop_count = 0;\n    sh->deleted_prop_count = 0;\n    \n    /* insert in the hash table */\n    sh->hash = shape_initial_hash(proto);\n    sh->is_hashed = TRUE;\n    sh->has_small_array_index = FALSE;\n    js_shape_hash_link(ctx->rt, sh);\n    return sh;\n}\n\nstatic JSShape *js_new_shape(JSContext *ctx, JSObject *proto)\n{\n    return js_new_shape2(ctx, proto, JS_PROP_INITIAL_HASH_SIZE,\n                         JS_PROP_INITIAL_SIZE);\n}\n\n/* The shape is cloned. The new shape is not inserted in the shape\n   hash table */\nstatic JSShape *js_clone_shape(JSContext *ctx, JSShape *sh1)\n{\n    JSShape *sh;\n    void *sh_alloc, *sh_alloc1;\n    size_t size;\n    JSShapeProperty *pr;\n    uint32_t i, hash_size;\n\n    hash_size = sh1->prop_hash_mask + 1;\n    size = get_shape_size(hash_size, sh1->prop_size);\n    sh_alloc = js_malloc(ctx, size);\n    if (!sh_alloc)\n        return NULL;\n    sh_alloc1 = get_alloc_from_shape(sh1);\n    memcpy(sh_alloc, sh_alloc1, size);\n    sh = get_shape_from_alloc(sh_alloc, hash_size);\n    sh->header.ref_count = 1;\n    add_gc_object(ctx->rt, &sh->header, JS_GC_OBJ_TYPE_SHAPE);\n    sh->is_hashed = FALSE;\n    if (sh->proto) {\n        JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, sh->proto));\n    }\n    for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count; i++, pr++) {\n        JS_DupAtom(ctx, pr->atom);\n    }\n    return sh;\n}\n\nstatic JSShape *js_dup_shape(JSShape *sh)\n{\n    sh->header.ref_count++;\n    return sh;\n}\n\nstatic void js_free_shape0(JSRuntime *rt, JSShape *sh)\n{\n    uint32_t i;\n    JSShapeProperty *pr;\n\n    assert(sh->header.ref_count == 0);\n    if (sh->is_hashed)\n        js_shape_hash_unlink(rt, sh);\n    if (sh->proto != NULL) {\n        JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, sh->proto));\n    }\n    pr = get_shape_prop(sh);\n    for(i = 0; i < sh->prop_count; i++) {\n        JS_FreeAtomRT(rt, pr->atom);\n        pr++;\n    }\n    remove_gc_object(&sh->header);\n    js_free_rt(rt, get_alloc_from_shape(sh));\n}\n\nstatic void js_free_shape(JSRuntime *rt, JSShape *sh)\n{\n    if (unlikely(--sh->header.ref_count <= 0)) {\n        js_free_shape0(rt, sh);\n    }\n}\n\nstatic void js_free_shape_null(JSRuntime *rt, JSShape *sh)\n{\n    if (sh)\n        js_free_shape(rt, sh);\n}\n\n/* make space to hold at least 'count' properties */\nstatic no_inline int resize_properties(JSContext *ctx, JSShape **psh,\n                                       JSObject *p, uint32_t count)\n{\n    JSShape *sh;\n    uint32_t new_size, new_hash_size, new_hash_mask, i;\n    JSShapeProperty *pr;\n    void *sh_alloc;\n    intptr_t h;\n\n    sh = *psh;\n    new_size = max_int(count, sh->prop_size * 3 / 2);\n    /* Reallocate prop array first to avoid crash or size inconsistency\n       in case of memory allocation failure */\n    if (p) {\n        JSProperty *new_prop;\n        new_prop = js_realloc(ctx, p->prop, sizeof(new_prop[0]) * new_size);\n        if (unlikely(!new_prop))\n            return -1;\n        p->prop = new_prop;\n    }\n    new_hash_size = sh->prop_hash_mask + 1;\n    while (new_hash_size < new_size)\n        new_hash_size = 2 * new_hash_size;\n    if (new_hash_size != (sh->prop_hash_mask + 1)) {\n        JSShape *old_sh;\n        /* resize the hash table and the properties */\n        old_sh = sh;\n        sh_alloc = js_malloc(ctx, get_shape_size(new_hash_size, new_size));\n        if (!sh_alloc)\n            return -1;\n        sh = get_shape_from_alloc(sh_alloc, new_hash_size);\n        list_del(&old_sh->header.link);\n        /* copy all the fields and the properties */\n        memcpy(sh, old_sh,\n               sizeof(JSShape) + sizeof(sh->prop[0]) * old_sh->prop_count);\n        list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list);\n        new_hash_mask = new_hash_size - 1;\n        sh->prop_hash_mask = new_hash_mask;\n        memset(prop_hash_end(sh) - new_hash_size, 0,\n               sizeof(prop_hash_end(sh)[0]) * new_hash_size);\n        for(i = 0, pr = sh->prop; i < sh->prop_count; i++, pr++) {\n            if (pr->atom != JS_ATOM_NULL) {\n                h = ((uintptr_t)pr->atom & new_hash_mask);\n                pr->hash_next = prop_hash_end(sh)[-h - 1];\n                prop_hash_end(sh)[-h - 1] = i + 1;\n            }\n        }\n        js_free(ctx, get_alloc_from_shape(old_sh));\n    } else {\n        /* only resize the properties */\n        list_del(&sh->header.link);\n        sh_alloc = js_realloc(ctx, get_alloc_from_shape(sh),\n                              get_shape_size(new_hash_size, new_size));\n        if (unlikely(!sh_alloc)) {\n            /* insert again in the GC list */\n            list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list);\n            return -1;\n        }\n        sh = get_shape_from_alloc(sh_alloc, new_hash_size);\n        list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list);\n    }\n    *psh = sh;\n    sh->prop_size = new_size;\n    return 0;\n}\n\n/* remove the deleted properties. */\nstatic int compact_properties(JSContext *ctx, JSObject *p)\n{\n    JSShape *sh, *old_sh;\n    void *sh_alloc;\n    intptr_t h;\n    uint32_t new_hash_size, i, j, new_hash_mask, new_size;\n    JSShapeProperty *old_pr, *pr;\n    JSProperty *prop, *new_prop;\n    \n    sh = p->shape;\n    assert(!sh->is_hashed);\n\n    new_size = max_int(JS_PROP_INITIAL_SIZE,\n                       sh->prop_count - sh->deleted_prop_count);\n    assert(new_size <= sh->prop_size);\n\n    new_hash_size = sh->prop_hash_mask + 1;\n    while ((new_hash_size / 2) >= new_size)\n        new_hash_size = new_hash_size / 2;\n    new_hash_mask = new_hash_size - 1;\n\n    /* resize the hash table and the properties */\n    old_sh = sh;\n    sh_alloc = js_malloc(ctx, get_shape_size(new_hash_size, new_size));\n    if (!sh_alloc)\n        return -1;\n    sh = get_shape_from_alloc(sh_alloc, new_hash_size);\n    list_del(&old_sh->header.link);\n    memcpy(sh, old_sh, sizeof(JSShape));\n    list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list);\n    \n    memset(prop_hash_end(sh) - new_hash_size, 0,\n           sizeof(prop_hash_end(sh)[0]) * new_hash_size);\n\n    j = 0;\n    old_pr = old_sh->prop;\n    pr = sh->prop;\n    prop = p->prop;\n    for(i = 0; i < sh->prop_count; i++) {\n        if (old_pr->atom != JS_ATOM_NULL) {\n            pr->atom = old_pr->atom;\n            pr->flags = old_pr->flags;\n            h = ((uintptr_t)old_pr->atom & new_hash_mask);\n            pr->hash_next = prop_hash_end(sh)[-h - 1];\n            prop_hash_end(sh)[-h - 1] = j + 1;\n            prop[j] = prop[i];\n            j++;\n            pr++;\n        }\n        old_pr++;\n    }\n    assert(j == (sh->prop_count - sh->deleted_prop_count));\n    sh->prop_hash_mask = new_hash_mask;\n    sh->prop_size = new_size;\n    sh->deleted_prop_count = 0;\n    sh->prop_count = j;\n\n    p->shape = sh;\n    js_free(ctx, get_alloc_from_shape(old_sh));\n    \n    /* reduce the size of the object properties */\n    new_prop = js_realloc(ctx, p->prop, sizeof(new_prop[0]) * new_size);\n    if (new_prop)\n        p->prop = new_prop;\n    return 0;\n}\n\nstatic int add_shape_property(JSContext *ctx, JSShape **psh,\n                              JSObject *p, JSAtom atom, int prop_flags)\n{\n    JSRuntime *rt = ctx->rt;\n    JSShape *sh = *psh;\n    JSShapeProperty *pr, *prop;\n    uint32_t hash_mask, new_shape_hash = 0;\n    intptr_t h;\n\n    /* update the shape hash */\n    if (sh->is_hashed) {\n        js_shape_hash_unlink(rt, sh);\n        new_shape_hash = shape_hash(shape_hash(sh->hash, atom), prop_flags);\n    }\n\n    if (unlikely(sh->prop_count >= sh->prop_size)) {\n        if (resize_properties(ctx, psh, p, sh->prop_count + 1)) {\n            /* in case of error, reinsert in the hash table.\n               sh is still valid if resize_properties() failed */\n            if (sh->is_hashed)\n                js_shape_hash_link(rt, sh);\n            return -1;\n        }\n        sh = *psh;\n    }\n    if (sh->is_hashed) {\n        sh->hash = new_shape_hash;\n        js_shape_hash_link(rt, sh);\n    }\n    /* Initialize the new shape property.\n       The object property at p->prop[sh->prop_count] is uninitialized */\n    prop = get_shape_prop(sh);\n    pr = &prop[sh->prop_count++];\n    pr->atom = JS_DupAtom(ctx, atom);\n    pr->flags = prop_flags;\n    sh->has_small_array_index |= __JS_AtomIsTaggedInt(atom);\n    /* add in hash table */\n    hash_mask = sh->prop_hash_mask;\n    h = atom & hash_mask;\n    pr->hash_next = prop_hash_end(sh)[-h - 1];\n    prop_hash_end(sh)[-h - 1] = sh->prop_count;\n    return 0;\n}\n\n/* find a hashed empty shape matching the prototype. Return NULL if\n   not found */\nstatic JSShape *find_hashed_shape_proto(JSRuntime *rt, JSObject *proto)\n{\n    JSShape *sh1;\n    uint32_t h, h1;\n\n    h = shape_initial_hash(proto);\n    h1 = get_shape_hash(h, rt->shape_hash_bits);\n    for(sh1 = rt->shape_hash[h1]; sh1 != NULL; sh1 = sh1->shape_hash_next) {\n        if (sh1->hash == h &&\n            sh1->proto == proto &&\n            sh1->prop_count == 0) {\n            return sh1;\n        }\n    }\n    return NULL;\n}\n\n/* find a hashed shape matching sh + (prop, prop_flags). Return NULL if\n   not found */\nstatic JSShape *find_hashed_shape_prop(JSRuntime *rt, JSShape *sh,\n                                       JSAtom atom, int prop_flags)\n{\n    JSShape *sh1;\n    uint32_t h, h1, i, n;\n\n    h = sh->hash;\n    h = shape_hash(h, atom);\n    h = shape_hash(h, prop_flags);\n    h1 = get_shape_hash(h, rt->shape_hash_bits);\n    for(sh1 = rt->shape_hash[h1]; sh1 != NULL; sh1 = sh1->shape_hash_next) {\n        /* we test the hash first so that the rest is done only if the\n           shapes really match */\n        if (sh1->hash == h &&\n            sh1->proto == sh->proto &&\n            sh1->prop_count == ((n = sh->prop_count) + 1)) {\n            for(i = 0; i < n; i++) {\n                if (unlikely(sh1->prop[i].atom != sh->prop[i].atom) ||\n                    unlikely(sh1->prop[i].flags != sh->prop[i].flags))\n                    goto next;\n            }\n            if (unlikely(sh1->prop[n].atom != atom) ||\n                unlikely(sh1->prop[n].flags != prop_flags))\n                goto next;\n            return sh1;\n        }\n    next: ;\n    }\n    return NULL;\n}\n\nstatic __maybe_unused void JS_DumpShape(JSRuntime *rt, int i, JSShape *sh)\n{\n    char atom_buf[ATOM_GET_STR_BUF_SIZE];\n    int j;\n\n    /* XXX: should output readable class prototype */\n    printf(\"%5d %3d%c %14p %5d %5d\", i,\n           sh->header.ref_count, \" *\"[sh->is_hashed],\n           (void *)sh->proto, sh->prop_size, sh->prop_count);\n    for(j = 0; j < sh->prop_count; j++) {\n        printf(\" %s\", JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf),\n                                      sh->prop[j].atom));\n    }\n    printf(\"\\n\");\n}\n\nstatic __maybe_unused void JS_DumpShapes(JSRuntime *rt)\n{\n    int i;\n    JSShape *sh;\n    struct list_head *el;\n    JSObject *p;\n    JSGCObjectHeader *gp;\n    \n    printf(\"JSShapes: {\\n\");\n    printf(\"%5s %4s %14s %5s %5s %s\\n\", \"SLOT\", \"REFS\", \"PROTO\", \"SIZE\", \"COUNT\", \"PROPS\");\n    for(i = 0; i < rt->shape_hash_size; i++) {\n        for(sh = rt->shape_hash[i]; sh != NULL; sh = sh->shape_hash_next) {\n            JS_DumpShape(rt, i, sh);\n            assert(sh->is_hashed);\n        }\n    }\n    /* dump non-hashed shapes */\n    list_for_each(el, &rt->gc_obj_list) {\n        gp = list_entry(el, JSGCObjectHeader, link);\n        if (gp->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT) {\n            p = (JSObject *)gp;\n            if (!p->shape->is_hashed) {\n                JS_DumpShape(rt, -1, p->shape);\n            }\n        }\n    }\n    printf(\"}\\n\");\n}\n\nstatic JSValue JS_NewObjectFromShape(JSContext *ctx, JSShape *sh, JSClassID class_id)\n{\n    JSObject *p;\n\n    js_trigger_gc(ctx->rt, sizeof(JSObject));\n    p = js_malloc(ctx, sizeof(JSObject));\n    if (unlikely(!p))\n        goto fail;\n    p->class_id = class_id;\n    p->extensible = TRUE;\n    p->free_mark = 0;\n    p->is_exotic = 0;\n    p->fast_array = 0;\n    p->is_constructor = 0;\n    p->is_uncatchable_error = 0;\n    p->tmp_mark = 0;\n    p->is_HTMLDDA = 0;\n    p->first_weak_ref = NULL;\n    p->u.opaque = NULL;\n    p->shape = sh;\n    p->prop = js_malloc(ctx, sizeof(JSProperty) * sh->prop_size);\n    if (unlikely(!p->prop)) {\n        js_free(ctx, p);\n    fail:\n        js_free_shape(ctx->rt, sh);\n        return JS_EXCEPTION;\n    }\n\n    switch(class_id) {\n    case JS_CLASS_OBJECT:\n        break;\n    case JS_CLASS_ARRAY:\n        {\n            JSProperty *pr;\n            p->is_exotic = 1;\n            p->fast_array = 1;\n            p->u.array.u.values = NULL;\n            p->u.array.count = 0;\n            p->u.array.u1.size = 0;\n            /* the length property is always the first one */\n            if (likely(sh == ctx->array_shape)) {\n                pr = &p->prop[0];\n            } else {\n                /* only used for the first array */\n                /* cannot fail */\n                pr = add_property(ctx, p, JS_ATOM_length,\n                                  JS_PROP_WRITABLE | JS_PROP_LENGTH);\n            }\n            pr->u.value = JS_NewInt32(ctx, 0);\n        }\n        break;\n    case JS_CLASS_C_FUNCTION:\n        p->prop[0].u.value = JS_UNDEFINED;\n        break;\n    case JS_CLASS_ARGUMENTS:\n    case JS_CLASS_UINT8C_ARRAY:\n    case JS_CLASS_INT8_ARRAY:\n    case JS_CLASS_UINT8_ARRAY:\n    case JS_CLASS_INT16_ARRAY:\n    case JS_CLASS_UINT16_ARRAY:\n    case JS_CLASS_INT32_ARRAY:\n    case JS_CLASS_UINT32_ARRAY:\n#ifdef CONFIG_BIGNUM\n    case JS_CLASS_BIG_INT64_ARRAY:\n    case JS_CLASS_BIG_UINT64_ARRAY:\n#endif\n    case JS_CLASS_FLOAT32_ARRAY:\n    case JS_CLASS_FLOAT64_ARRAY:\n        p->is_exotic = 1;\n        p->fast_array = 1;\n        p->u.array.u.ptr = NULL;\n        p->u.array.count = 0;\n        break;\n    case JS_CLASS_DATAVIEW:\n        p->u.array.u.ptr = NULL;\n        p->u.array.count = 0;\n        break;\n    case JS_CLASS_NUMBER:\n    case JS_CLASS_STRING:\n    case JS_CLASS_BOOLEAN:\n    case JS_CLASS_SYMBOL:\n    case JS_CLASS_DATE:\n#ifdef CONFIG_BIGNUM\n    case JS_CLASS_BIG_INT:\n    case JS_CLASS_BIG_FLOAT:\n    case JS_CLASS_BIG_DECIMAL:\n#endif\n        p->u.object_data = JS_UNDEFINED;\n        goto set_exotic;\n    case JS_CLASS_REGEXP:\n        p->u.regexp.pattern = NULL;\n        p->u.regexp.bytecode = NULL;\n        goto set_exotic;\n    default:\n    set_exotic:\n        if (ctx->rt->class_array[class_id].exotic) {\n            p->is_exotic = 1;\n        }\n        break;\n    }\n    p->header.ref_count = 1;\n    add_gc_object(ctx->rt, &p->header, JS_GC_OBJ_TYPE_JS_OBJECT);\n    return JS_MKPTR(JS_TAG_OBJECT, p);\n}\n\nstatic JSObject *get_proto_obj(JSValueConst proto_val)\n{\n    if (JS_VALUE_GET_TAG(proto_val) != JS_TAG_OBJECT)\n        return NULL;\n    else\n        return JS_VALUE_GET_OBJ(proto_val);\n}\n\n/* WARNING: proto must be an object or JS_NULL */\nJSValue JS_NewObjectProtoClass(JSContext *ctx, JSValueConst proto_val,\n                               JSClassID class_id)\n{\n    JSShape *sh;\n    JSObject *proto;\n\n    proto = get_proto_obj(proto_val);\n    sh = find_hashed_shape_proto(ctx->rt, proto);\n    if (likely(sh)) {\n        sh = js_dup_shape(sh);\n    } else {\n        sh = js_new_shape(ctx, proto);\n        if (!sh)\n            return JS_EXCEPTION;\n    }\n    return JS_NewObjectFromShape(ctx, sh, class_id);\n}\n\n#if 0\nstatic JSValue JS_GetObjectData(JSContext *ctx, JSValueConst obj)\n{\n    JSObject *p;\n\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        p = JS_VALUE_GET_OBJ(obj);\n        switch(p->class_id) {\n        case JS_CLASS_NUMBER:\n        case JS_CLASS_STRING:\n        case JS_CLASS_BOOLEAN:\n        case JS_CLASS_SYMBOL:\n        case JS_CLASS_DATE:\n#ifdef CONFIG_BIGNUM\n        case JS_CLASS_BIG_INT:\n        case JS_CLASS_BIG_FLOAT:\n        case JS_CLASS_BIG_DECIMAL:\n#endif\n            return JS_DupValue(ctx, p->u.object_data);\n        }\n    }\n    return JS_UNDEFINED;\n}\n#endif\n\nstatic int JS_SetObjectData(JSContext *ctx, JSValueConst obj, JSValue val)\n{\n    JSObject *p;\n\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        p = JS_VALUE_GET_OBJ(obj);\n        switch(p->class_id) {\n        case JS_CLASS_NUMBER:\n        case JS_CLASS_STRING:\n        case JS_CLASS_BOOLEAN:\n        case JS_CLASS_SYMBOL:\n        case JS_CLASS_DATE:\n#ifdef CONFIG_BIGNUM\n        case JS_CLASS_BIG_INT:\n        case JS_CLASS_BIG_FLOAT:\n        case JS_CLASS_BIG_DECIMAL:\n#endif\n            JS_FreeValue(ctx, p->u.object_data);\n            p->u.object_data = val;\n            return 0;\n        }\n    }\n    JS_FreeValue(ctx, val);\n    if (!JS_IsException(obj))\n        JS_ThrowTypeError(ctx, \"invalid object type\");\n    return -1;\n}\n\nJSValue JS_NewObjectClass(JSContext *ctx, int class_id)\n{\n    return JS_NewObjectProtoClass(ctx, ctx->class_proto[class_id], class_id);\n}\n\nJSValue JS_NewObjectProto(JSContext *ctx, JSValueConst proto)\n{\n    return JS_NewObjectProtoClass(ctx, proto, JS_CLASS_OBJECT);\n}\n\nJSValue JS_NewArray(JSContext *ctx)\n{\n    return JS_NewObjectFromShape(ctx, js_dup_shape(ctx->array_shape),\n                                 JS_CLASS_ARRAY);\n}\n\nJSValue JS_NewObject(JSContext *ctx)\n{\n    /* inline JS_NewObjectClass(ctx, JS_CLASS_OBJECT); */\n    return JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT], JS_CLASS_OBJECT);\n}\n\nstatic void js_function_set_properties(JSContext *ctx, JSValueConst func_obj,\n                                       JSAtom name, int len)\n{\n    /* ES6 feature non compatible with ES5.1: length is configurable */\n    JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_length, JS_NewInt32(ctx, len),\n                           JS_PROP_CONFIGURABLE);\n    JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_name,\n                           JS_AtomToString(ctx, name), JS_PROP_CONFIGURABLE);\n}\n\nstatic BOOL js_class_has_bytecode(JSClassID class_id)\n{\n    return (class_id == JS_CLASS_BYTECODE_FUNCTION ||\n            class_id == JS_CLASS_GENERATOR_FUNCTION ||\n            class_id == JS_CLASS_ASYNC_FUNCTION ||\n            class_id == JS_CLASS_ASYNC_GENERATOR_FUNCTION);\n}\n\n/* return NULL without exception if not a function or no bytecode */\nstatic JSFunctionBytecode *JS_GetFunctionBytecode(JSValueConst val)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return NULL;\n    p = JS_VALUE_GET_OBJ(val);\n    if (!js_class_has_bytecode(p->class_id))\n        return NULL;\n    return p->u.func.function_bytecode;\n}\n\nstatic void js_method_set_home_object(JSContext *ctx, JSValueConst func_obj,\n                                      JSValueConst home_obj)\n{\n    JSObject *p, *p1;\n    JSFunctionBytecode *b;\n\n    if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT)\n        return;\n    p = JS_VALUE_GET_OBJ(func_obj);\n    if (!js_class_has_bytecode(p->class_id))\n        return;\n    b = p->u.func.function_bytecode;\n    if (b->need_home_object) {\n        p1 = p->u.func.home_object;\n        if (p1) {\n            JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p1));\n        }\n        if (JS_VALUE_GET_TAG(home_obj) == JS_TAG_OBJECT)\n            p1 = JS_VALUE_GET_OBJ(JS_DupValue(ctx, home_obj));\n        else\n            p1 = NULL;\n        p->u.func.home_object = p1;\n    }\n}\n\nstatic JSValue js_get_function_name(JSContext *ctx, JSAtom name)\n{\n    JSValue name_str;\n\n    name_str = JS_AtomToString(ctx, name);\n    if (JS_AtomSymbolHasDescription(ctx, name)) {\n        name_str = JS_ConcatString3(ctx, \"[\", name_str, \"]\");\n    }\n    return name_str;\n}\n\n/* Modify the name of a method according to the atom and\n   'flags'. 'flags' is a bitmask of JS_PROP_HAS_GET and\n   JS_PROP_HAS_SET. Also set the home object of the method.\n   Return < 0 if exception. */\nstatic int js_method_set_properties(JSContext *ctx, JSValueConst func_obj,\n                                    JSAtom name, int flags, JSValueConst home_obj)\n{\n    JSValue name_str;\n\n    name_str = js_get_function_name(ctx, name);\n    if (flags & JS_PROP_HAS_GET) {\n        name_str = JS_ConcatString3(ctx, \"get \", name_str, \"\");\n    } else if (flags & JS_PROP_HAS_SET) {\n        name_str = JS_ConcatString3(ctx, \"set \", name_str, \"\");\n    }\n    if (JS_IsException(name_str))\n        return -1;\n    if (JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_name, name_str,\n                               JS_PROP_CONFIGURABLE) < 0)\n        return -1;\n    js_method_set_home_object(ctx, func_obj, home_obj);\n    return 0;\n}\n\n/* Note: at least 'length' arguments will be readable in 'argv' */\nstatic JSValue JS_NewCFunction3(JSContext *ctx, JSCFunction *func,\n                                const char *name,\n                                int length, JSCFunctionEnum cproto, int magic,\n                                JSValueConst proto_val)\n{\n    JSValue func_obj;\n    JSObject *p;\n    JSAtom name_atom;\n    \n    func_obj = JS_NewObjectProtoClass(ctx, proto_val, JS_CLASS_C_FUNCTION);\n    if (JS_IsException(func_obj))\n        return func_obj;\n    p = JS_VALUE_GET_OBJ(func_obj);\n    p->u.cfunc.realm = JS_DupContext(ctx);\n    p->u.cfunc.c_function.generic = func;\n    p->u.cfunc.length = length;\n    p->u.cfunc.cproto = cproto;\n    p->u.cfunc.magic = magic;\n    p->is_constructor = (cproto == JS_CFUNC_constructor ||\n                         cproto == JS_CFUNC_constructor_magic ||\n                         cproto == JS_CFUNC_constructor_or_func ||\n                         cproto == JS_CFUNC_constructor_or_func_magic);\n    if (!name)\n        name = \"\";\n    name_atom = JS_NewAtom(ctx, name);\n    js_function_set_properties(ctx, func_obj, name_atom, length);\n    JS_FreeAtom(ctx, name_atom);\n    return func_obj;\n}\n\n/* Note: at least 'length' arguments will be readable in 'argv' */\nJSValue JS_NewCFunction2(JSContext *ctx, JSCFunction *func,\n                         const char *name,\n                         int length, JSCFunctionEnum cproto, int magic)\n{\n    return JS_NewCFunction3(ctx, func, name, length, cproto, magic,\n                            ctx->function_proto);\n}\n\ntypedef struct JSCFunctionDataRecord {\n    JSCFunctionData *func;\n    uint8_t length;\n    uint8_t data_len;\n    uint16_t magic;\n    JSValue data[0];\n} JSCFunctionDataRecord;\n\nstatic void js_c_function_data_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSCFunctionDataRecord *s = JS_GetOpaque(val, JS_CLASS_C_FUNCTION_DATA);\n    int i;\n\n    if (s) {\n        for(i = 0; i < s->data_len; i++) {\n            JS_FreeValueRT(rt, s->data[i]);\n        }\n        js_free_rt(rt, s);\n    }\n}\n\nstatic void js_c_function_data_mark(JSRuntime *rt, JSValueConst val,\n                                    JS_MarkFunc *mark_func)\n{\n    JSCFunctionDataRecord *s = JS_GetOpaque(val, JS_CLASS_C_FUNCTION_DATA);\n    int i;\n\n    if (s) {\n        for(i = 0; i < s->data_len; i++) {\n            JS_MarkValue(rt, s->data[i], mark_func);\n        }\n    }\n}\n\nstatic JSValue js_c_function_data_call(JSContext *ctx, JSValueConst func_obj,\n                                       JSValueConst this_val,\n                                       int argc, JSValueConst *argv, int flags)\n{\n    JSCFunctionDataRecord *s = JS_GetOpaque(func_obj, JS_CLASS_C_FUNCTION_DATA);\n    JSValueConst *arg_buf;\n    int i;\n\n    /* XXX: could add the function on the stack for debug */\n    if (unlikely(argc < s->length)) {\n        arg_buf = alloca(sizeof(arg_buf[0]) * s->length);\n        for(i = 0; i < argc; i++)\n            arg_buf[i] = argv[i];\n        for(i = argc; i < s->length; i++)\n            arg_buf[i] = JS_UNDEFINED;\n    } else {\n        arg_buf = argv;\n    }\n\n    return s->func(ctx, this_val, argc, arg_buf, s->magic, s->data);\n}\n\nJSValue JS_NewCFunctionData(JSContext *ctx, JSCFunctionData *func,\n                            int length, int magic, int data_len,\n                            JSValueConst *data)\n{\n    JSCFunctionDataRecord *s;\n    JSValue func_obj;\n    int i;\n\n    func_obj = JS_NewObjectProtoClass(ctx, ctx->function_proto,\n                                      JS_CLASS_C_FUNCTION_DATA);\n    if (JS_IsException(func_obj))\n        return func_obj;\n    s = js_malloc(ctx, sizeof(*s) + data_len * sizeof(JSValue));\n    if (!s) {\n        JS_FreeValue(ctx, func_obj);\n        return JS_EXCEPTION;\n    }\n    s->func = func;\n    s->length = length;\n    s->data_len = data_len;\n    s->magic = magic;\n    for(i = 0; i < data_len; i++)\n        s->data[i] = JS_DupValue(ctx, data[i]);\n    JS_SetOpaque(func_obj, s);\n    js_function_set_properties(ctx, func_obj,\n                               JS_ATOM_empty_string, length);\n    return func_obj;\n}\n\nstatic JSContext *js_autoinit_get_realm(JSProperty *pr)\n{\n    return (JSContext *)(pr->u.init.realm_and_id & ~3);\n}\n\nstatic JSAutoInitIDEnum js_autoinit_get_id(JSProperty *pr)\n{\n    return pr->u.init.realm_and_id & 3;\n}\n\nstatic void js_autoinit_free(JSRuntime *rt, JSProperty *pr)\n{\n    JS_FreeContext(js_autoinit_get_realm(pr));\n}\n\nstatic void js_autoinit_mark(JSRuntime *rt, JSProperty *pr,\n                             JS_MarkFunc *mark_func)\n{\n    mark_func(rt, &js_autoinit_get_realm(pr)->header);\n}\n\nstatic void free_property(JSRuntime *rt, JSProperty *pr, int prop_flags)\n{\n    if (unlikely(prop_flags & JS_PROP_TMASK)) {\n        if ((prop_flags & JS_PROP_TMASK) == JS_PROP_GETSET) {\n            if (pr->u.getset.getter)\n                JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter));\n            if (pr->u.getset.setter)\n                JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter));\n        } else if ((prop_flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n            free_var_ref(rt, pr->u.var_ref);\n        } else if ((prop_flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n            js_autoinit_free(rt, pr);\n        }\n    } else {\n        JS_FreeValueRT(rt, pr->u.value);\n    }\n}\n\nstatic force_inline JSShapeProperty *find_own_property1(JSObject *p,\n                                                        JSAtom atom)\n{\n    JSShape *sh;\n    JSShapeProperty *pr, *prop;\n    intptr_t h;\n    sh = p->shape;\n    h = (uintptr_t)atom & sh->prop_hash_mask;\n    h = prop_hash_end(sh)[-h - 1];\n    prop = get_shape_prop(sh);\n    while (h) {\n        pr = &prop[h - 1];\n        if (likely(pr->atom == atom)) {\n            return pr;\n        }\n        h = pr->hash_next;\n    }\n    return NULL;\n}\n\nstatic force_inline JSShapeProperty *find_own_property(JSProperty **ppr,\n                                                       JSObject *p,\n                                                       JSAtom atom)\n{\n    JSShape *sh;\n    JSShapeProperty *pr, *prop;\n    intptr_t h;\n    sh = p->shape;\n    h = (uintptr_t)atom & sh->prop_hash_mask;\n    h = prop_hash_end(sh)[-h - 1];\n    prop = get_shape_prop(sh);\n    while (h) {\n        pr = &prop[h - 1];\n        if (likely(pr->atom == atom)) {\n            *ppr = &p->prop[h - 1];\n            /* the compiler should be able to assume that pr != NULL here */\n            return pr;\n        }\n        h = pr->hash_next;\n    }\n    *ppr = NULL;\n    return NULL;\n}\n\n/* indicate that the object may be part of a function prototype cycle */\nstatic void set_cycle_flag(JSContext *ctx, JSValueConst obj)\n{\n}\n\nstatic void free_var_ref(JSRuntime *rt, JSVarRef *var_ref)\n{\n    if (var_ref) {\n        assert(var_ref->header.ref_count > 0);\n        if (--var_ref->header.ref_count == 0) {\n            if (var_ref->is_detached) {\n                JS_FreeValueRT(rt, var_ref->value);\n                remove_gc_object(&var_ref->header);\n            } else {\n                list_del(&var_ref->header.link); /* still on the stack */\n            }\n            js_free_rt(rt, var_ref);\n        }\n    }\n}\n\nstatic void js_array_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    int i;\n\n    for(i = 0; i < p->u.array.count; i++) {\n        JS_FreeValueRT(rt, p->u.array.u.values[i]);\n    }\n    js_free_rt(rt, p->u.array.u.values);\n}\n\nstatic void js_array_mark(JSRuntime *rt, JSValueConst val,\n                          JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    int i;\n\n    for(i = 0; i < p->u.array.count; i++) {\n        JS_MarkValue(rt, p->u.array.u.values[i], mark_func);\n    }\n}\n\nstatic void js_object_data_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JS_FreeValueRT(rt, p->u.object_data);\n    p->u.object_data = JS_UNDEFINED;\n}\n\nstatic void js_object_data_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JS_MarkValue(rt, p->u.object_data, mark_func);\n}\n\nstatic void js_c_function_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n\n    if (p->u.cfunc.realm)\n        JS_FreeContext(p->u.cfunc.realm);\n}\n\nstatic void js_c_function_mark(JSRuntime *rt, JSValueConst val,\n                               JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n\n    if (p->u.cfunc.realm)\n        mark_func(rt, &p->u.cfunc.realm->header);\n}\n\nstatic void js_bytecode_function_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p1, *p = JS_VALUE_GET_OBJ(val);\n    JSFunctionBytecode *b;\n    JSVarRef **var_refs;\n    int i;\n\n    p1 = p->u.func.home_object;\n    if (p1) {\n        JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, p1));\n    }\n    b = p->u.func.function_bytecode;\n    if (b) {\n        var_refs = p->u.func.var_refs;\n        if (var_refs) {\n            for(i = 0; i < b->closure_var_count; i++)\n                free_var_ref(rt, var_refs[i]);\n            js_free_rt(rt, var_refs);\n        }\n        JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_FUNCTION_BYTECODE, b));\n    }\n}\n\nstatic void js_bytecode_function_mark(JSRuntime *rt, JSValueConst val,\n                                      JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSVarRef **var_refs = p->u.func.var_refs;\n    JSFunctionBytecode *b = p->u.func.function_bytecode;\n    int i;\n\n    if (p->u.func.home_object) {\n        JS_MarkValue(rt, JS_MKPTR(JS_TAG_OBJECT, p->u.func.home_object),\n                     mark_func);\n    }\n    if (b) {\n        if (var_refs) {\n            for(i = 0; i < b->closure_var_count; i++) {\n                JSVarRef *var_ref = var_refs[i];\n                if (var_ref && var_ref->is_detached) {\n                    mark_func(rt, &var_ref->header);\n                }\n            }\n        }\n        /* must mark the function bytecode because template objects may be\n           part of a cycle */\n        JS_MarkValue(rt, JS_MKPTR(JS_TAG_FUNCTION_BYTECODE, b), mark_func);\n    }\n}\n\nstatic void js_bound_function_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSBoundFunction *bf = p->u.bound_function;\n    int i;\n\n    JS_FreeValueRT(rt, bf->func_obj);\n    JS_FreeValueRT(rt, bf->this_val);\n    for(i = 0; i < bf->argc; i++) {\n        JS_FreeValueRT(rt, bf->argv[i]);\n    }\n    js_free_rt(rt, bf);\n}\n\nstatic void js_bound_function_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSBoundFunction *bf = p->u.bound_function;\n    int i;\n\n    JS_MarkValue(rt, bf->func_obj, mark_func);\n    JS_MarkValue(rt, bf->this_val, mark_func);\n    for(i = 0; i < bf->argc; i++)\n        JS_MarkValue(rt, bf->argv[i], mark_func);\n}\n\nstatic void js_for_in_iterator_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSForInIterator *it = p->u.for_in_iterator;\n    JS_FreeValueRT(rt, it->obj);\n    js_free_rt(rt, it);\n}\n\nstatic void js_for_in_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSForInIterator *it = p->u.for_in_iterator;\n    JS_MarkValue(rt, it->obj, mark_func);\n}\n\nstatic void free_object(JSRuntime *rt, JSObject *p)\n{\n    int i;\n    JSClassFinalizer *finalizer;\n    JSShape *sh;\n    JSShapeProperty *pr;\n\n    p->free_mark = 1; /* used to tell the object is invalid when\n                         freeing cycles */\n    /* free all the fields */\n    sh = p->shape;\n    pr = get_shape_prop(sh);\n    for(i = 0; i < sh->prop_count; i++) {\n        free_property(rt, &p->prop[i], pr->flags);\n        pr++;\n    }\n    js_free_rt(rt, p->prop);\n    /* as an optimization we destroy the shape immediately without\n       putting it in gc_zero_ref_count_list */\n    js_free_shape(rt, sh);\n\n    /* fail safe */\n    p->shape = NULL;\n    p->prop = NULL;\n\n    if (unlikely(p->first_weak_ref)) {\n        reset_weak_ref(rt, p);\n    }\n\n    finalizer = rt->class_array[p->class_id].finalizer;\n    if (finalizer)\n        (*finalizer)(rt, JS_MKPTR(JS_TAG_OBJECT, p));\n\n    /* fail safe */\n    p->class_id = 0;\n    p->u.opaque = NULL;\n    p->u.func.var_refs = NULL;\n    p->u.func.home_object = NULL;\n\n    remove_gc_object(&p->header);\n    if (rt->gc_phase == JS_GC_PHASE_REMOVE_CYCLES && p->header.ref_count != 0) {\n        list_add_tail(&p->header.link, &rt->gc_zero_ref_count_list);\n    } else {\n        js_free_rt(rt, p);\n    }\n}\n\nstatic void free_gc_object(JSRuntime *rt, JSGCObjectHeader *gp)\n{\n    switch(gp->gc_obj_type) {\n    case JS_GC_OBJ_TYPE_JS_OBJECT:\n        free_object(rt, (JSObject *)gp);\n        break;\n    case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE:\n        free_function_bytecode(rt, (JSFunctionBytecode *)gp);\n        break;\n    default:\n        abort();\n    }\n}\n\nstatic void free_zero_refcount(JSRuntime *rt)\n{\n    struct list_head *el;\n    JSGCObjectHeader *p;\n    \n    rt->gc_phase = JS_GC_PHASE_DECREF;\n    for(;;) {\n        el = rt->gc_zero_ref_count_list.next;\n        if (el == &rt->gc_zero_ref_count_list)\n            break;\n        p = list_entry(el, JSGCObjectHeader, link);\n        assert(p->ref_count == 0);\n        free_gc_object(rt, p);\n    }\n    rt->gc_phase = JS_GC_PHASE_NONE;\n}\n\n/* called with the ref_count of 'v' reaches zero. */\nvoid __JS_FreeValueRT(JSRuntime *rt, JSValue v)\n{\n    uint32_t tag = JS_VALUE_GET_TAG(v);\n\n#ifdef DUMP_FREE\n    {\n        printf(\"Freeing \");\n        if (tag == JS_TAG_OBJECT) {\n            JS_DumpObject(rt, JS_VALUE_GET_OBJ(v));\n        } else {\n            JS_DumpValueShort(rt, v);\n            printf(\"\\n\");\n        }\n    }\n#endif\n\n    switch(tag) {\n    case JS_TAG_STRING:\n        {\n            JSString *p = JS_VALUE_GET_STRING(v);\n            if (p->atom_type) {\n                JS_FreeAtomStruct(rt, p);\n            } else {\n#ifdef DUMP_LEAKS\n                list_del(&p->link);\n#endif\n                js_free_rt(rt, p);\n            }\n        }\n        break;\n    case JS_TAG_OBJECT:\n    case JS_TAG_FUNCTION_BYTECODE:\n        {\n            JSGCObjectHeader *p = JS_VALUE_GET_PTR(v);\n            if (rt->gc_phase != JS_GC_PHASE_REMOVE_CYCLES) {\n                list_del(&p->link);\n                list_add(&p->link, &rt->gc_zero_ref_count_list);\n                if (rt->gc_phase == JS_GC_PHASE_NONE) {\n                    free_zero_refcount(rt);\n                }\n            }\n        }\n        break;\n    case JS_TAG_MODULE:\n        abort(); /* never freed here */\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *bf = JS_VALUE_GET_PTR(v);\n            bf_delete(&bf->num);\n            js_free_rt(rt, bf);\n        }\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        {\n            JSBigDecimal *bf = JS_VALUE_GET_PTR(v);\n            bfdec_delete(&bf->num);\n            js_free_rt(rt, bf);\n        }\n        break;\n#endif\n    case JS_TAG_SYMBOL:\n        {\n            JSAtomStruct *p = JS_VALUE_GET_PTR(v);\n            JS_FreeAtomStruct(rt, p);\n        }\n        break;\n    default:\n        printf(\"__JS_FreeValue: unknown tag=%d\\n\", tag);\n        abort();\n    }\n}\n\nvoid __JS_FreeValue(JSContext *ctx, JSValue v)\n{\n    __JS_FreeValueRT(ctx->rt, v);\n}\n\n/* garbage collection */\n\nstatic void add_gc_object(JSRuntime *rt, JSGCObjectHeader *h,\n                          JSGCObjectTypeEnum type)\n{\n    h->mark = 0;\n    h->gc_obj_type = type;\n    list_add_tail(&h->link, &rt->gc_obj_list);\n}\n\nstatic void remove_gc_object(JSGCObjectHeader *h)\n{\n    list_del(&h->link);\n}\n\nvoid JS_MarkValue(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func)\n{\n    if (JS_VALUE_HAS_REF_COUNT(val)) {\n        switch(JS_VALUE_GET_TAG(val)) {\n        case JS_TAG_OBJECT:\n        case JS_TAG_FUNCTION_BYTECODE:\n            mark_func(rt, JS_VALUE_GET_PTR(val));\n            break;\n        default:\n            break;\n        }\n    }\n}\n\nstatic void mark_children(JSRuntime *rt, JSGCObjectHeader *gp,\n                          JS_MarkFunc *mark_func)\n{\n    switch(gp->gc_obj_type) {\n    case JS_GC_OBJ_TYPE_JS_OBJECT:\n        {\n            JSObject *p = (JSObject *)gp;\n            JSShapeProperty *prs;\n            JSShape *sh;\n            int i;\n            sh = p->shape;\n            mark_func(rt, &sh->header);\n            /* mark all the fields */\n            prs = get_shape_prop(sh);\n            for(i = 0; i < sh->prop_count; i++) {\n                JSProperty *pr = &p->prop[i];\n                if (prs->atom != JS_ATOM_NULL) {\n                    if (prs->flags & JS_PROP_TMASK) {\n                        if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {\n                            if (pr->u.getset.getter)\n                                mark_func(rt, &pr->u.getset.getter->header);\n                            if (pr->u.getset.setter)\n                                mark_func(rt, &pr->u.getset.setter->header);\n                        } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n                            if (pr->u.var_ref->is_detached) {\n                                /* Note: the tag does not matter\n                                   provided it is a GC object */\n                                mark_func(rt, &pr->u.var_ref->header);\n                            }\n                        } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n                            js_autoinit_mark(rt, pr, mark_func);\n                        }\n                    } else {\n                        JS_MarkValue(rt, pr->u.value, mark_func);\n                    }\n                }\n                prs++;\n            }\n\n            if (p->class_id != JS_CLASS_OBJECT) {\n                JSClassGCMark *gc_mark;\n                gc_mark = rt->class_array[p->class_id].gc_mark;\n                if (gc_mark)\n                    gc_mark(rt, JS_MKPTR(JS_TAG_OBJECT, p), mark_func);\n            }\n        }\n        break;\n    case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE:\n        /* the template objects can be part of a cycle */\n        {\n            JSFunctionBytecode *b = (JSFunctionBytecode *)gp;\n            int i;\n            for(i = 0; i < b->cpool_count; i++) {\n                JS_MarkValue(rt, b->cpool[i], mark_func);\n            }\n            if (b->realm)\n                mark_func(rt, &b->realm->header);\n        }\n        break;\n    case JS_GC_OBJ_TYPE_VAR_REF:\n        {\n            JSVarRef *var_ref = (JSVarRef *)gp;\n            /* only detached variable referenced are taken into account */\n            assert(var_ref->is_detached);\n            JS_MarkValue(rt, *var_ref->pvalue, mark_func);\n        }\n        break;\n    case JS_GC_OBJ_TYPE_ASYNC_FUNCTION:\n        {\n            JSAsyncFunctionData *s = (JSAsyncFunctionData *)gp;\n            if (s->is_active)\n                async_func_mark(rt, &s->func_state, mark_func);\n            JS_MarkValue(rt, s->resolving_funcs[0], mark_func);\n            JS_MarkValue(rt, s->resolving_funcs[1], mark_func);\n        }\n        break;\n    case JS_GC_OBJ_TYPE_SHAPE:\n        {\n            JSShape *sh = (JSShape *)gp;\n            if (sh->proto != NULL) {\n                mark_func(rt, &sh->proto->header);\n            }\n        }\n        break;\n    case JS_GC_OBJ_TYPE_JS_CONTEXT:\n        {\n            JSContext *ctx = (JSContext *)gp;\n            JS_MarkContext(rt, ctx, mark_func);\n        }\n        break;\n    default:\n        abort();\n    }\n}\n\nstatic void gc_decref_child(JSRuntime *rt, JSGCObjectHeader *p)\n{\n    assert(p->ref_count > 0);\n    p->ref_count--;\n    if (p->ref_count == 0 && p->mark == 1) {\n        list_del(&p->link);\n        list_add_tail(&p->link, &rt->tmp_obj_list);\n    }\n}\n\nstatic void gc_decref(JSRuntime *rt)\n{\n    struct list_head *el, *el1;\n    JSGCObjectHeader *p;\n    \n    init_list_head(&rt->tmp_obj_list);\n\n    /* decrement the refcount of all the children of all the GC\n       objects and move the GC objects with zero refcount to\n       tmp_obj_list */\n    list_for_each_safe(el, el1, &rt->gc_obj_list) {\n        p = list_entry(el, JSGCObjectHeader, link);\n        assert(p->mark == 0);\n        mark_children(rt, p, gc_decref_child);\n        p->mark = 1;\n        if (p->ref_count == 0) {\n            list_del(&p->link);\n            list_add_tail(&p->link, &rt->tmp_obj_list);\n        }\n    }\n}\n\nstatic void gc_scan_incref_child(JSRuntime *rt, JSGCObjectHeader *p)\n{\n    p->ref_count++;\n    if (p->ref_count == 1) {\n        /* ref_count was 0: remove from tmp_obj_list and add at the\n           end of gc_obj_list */\n        list_del(&p->link);\n        list_add_tail(&p->link, &rt->gc_obj_list);\n        p->mark = 0; /* reset the mark for the next GC call */\n    }\n}\n\nstatic void gc_scan_incref_child2(JSRuntime *rt, JSGCObjectHeader *p)\n{\n    p->ref_count++;\n}\n\nstatic void gc_scan(JSRuntime *rt)\n{\n    struct list_head *el;\n    JSGCObjectHeader *p;\n\n    /* keep the objects with a refcount > 0 and their children. */\n    list_for_each(el, &rt->gc_obj_list) {\n        p = list_entry(el, JSGCObjectHeader, link);\n        assert(p->ref_count > 0);\n        p->mark = 0; /* reset the mark for the next GC call */\n        mark_children(rt, p, gc_scan_incref_child);\n    }\n    \n    /* restore the refcount of the objects to be deleted. */\n    list_for_each(el, &rt->tmp_obj_list) {\n        p = list_entry(el, JSGCObjectHeader, link);\n        mark_children(rt, p, gc_scan_incref_child2);\n    }\n}\n\nstatic void gc_free_cycles(JSRuntime *rt)\n{\n    struct list_head *el, *el1;\n    JSGCObjectHeader *p;\n#ifdef DUMP_GC_FREE\n    BOOL header_done = FALSE;\n#endif\n\n    rt->gc_phase = JS_GC_PHASE_REMOVE_CYCLES;\n\n    for(;;) {\n        el = rt->tmp_obj_list.next;\n        if (el == &rt->tmp_obj_list)\n            break;\n        p = list_entry(el, JSGCObjectHeader, link);\n        /* Only need to free the GC object associated with JS\n           values. The rest will be automatically removed because they\n           must be referenced by them. */\n        switch(p->gc_obj_type) {\n        case JS_GC_OBJ_TYPE_JS_OBJECT:\n        case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE:\n#ifdef DUMP_GC_FREE\n            if (!header_done) {\n                printf(\"Freeing cycles:\\n\");\n                JS_DumpObjectHeader(rt);\n                header_done = TRUE;\n            }\n            JS_DumpGCObject(rt, p);\n#endif\n            free_gc_object(rt, p);\n            break;\n        default:\n            list_del(&p->link);\n            list_add_tail(&p->link, &rt->gc_zero_ref_count_list);\n            break;\n        }\n    }\n    rt->gc_phase = JS_GC_PHASE_NONE;\n           \n    list_for_each_safe(el, el1, &rt->gc_zero_ref_count_list) {\n        p = list_entry(el, JSGCObjectHeader, link);\n        assert(p->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT ||\n               p->gc_obj_type == JS_GC_OBJ_TYPE_FUNCTION_BYTECODE);\n        js_free_rt(rt, p);\n    }\n\n    init_list_head(&rt->gc_zero_ref_count_list);\n}\n\nvoid JS_RunGC(JSRuntime *rt)\n{\n    /* decrement the reference of the children of each object. mark =\n       1 after this pass. */\n    gc_decref(rt);\n\n    /* keep the GC objects with a non zero refcount and their childs */\n    gc_scan(rt);\n\n    /* free the GC objects in a cycle */\n    gc_free_cycles(rt);\n}\n\n/* Return false if not an object or if the object has already been\n   freed (zombie objects are visible in finalizers when freeing\n   cycles). */\nBOOL JS_IsLiveObject(JSRuntime *rt, JSValueConst obj)\n{\n    JSObject *p;\n    if (!JS_IsObject(obj))\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(obj);\n    return !p->free_mark;\n}\n\n/* Compute memory used by various object types */\n/* XXX: poor man's approach to handling multiply referenced objects */\ntypedef struct JSMemoryUsage_helper {\n    double memory_used_count;\n    double str_count;\n    double str_size;\n    int64_t js_func_count;\n    double js_func_size;\n    int64_t js_func_code_size;\n    int64_t js_func_pc2line_count;\n    int64_t js_func_pc2line_size;\n} JSMemoryUsage_helper;\n\nstatic void compute_value_size(JSValueConst val, JSMemoryUsage_helper *hp);\n\nstatic void compute_jsstring_size(JSString *str, JSMemoryUsage_helper *hp)\n{\n    if (!str->atom_type) {  /* atoms are handled separately */\n        double s_ref_count = str->header.ref_count;\n        hp->str_count += 1 / s_ref_count;\n        hp->str_size += ((sizeof(*str) + (str->len << str->is_wide_char) +\n                          1 - str->is_wide_char) / s_ref_count);\n    }\n}\n\nstatic void compute_bytecode_size(JSFunctionBytecode *b, JSMemoryUsage_helper *hp)\n{\n    int memory_used_count, js_func_size, i;\n\n    memory_used_count = 0;\n    js_func_size = offsetof(JSFunctionBytecode, debug);\n    if (b->vardefs) {\n        js_func_size += (b->arg_count + b->var_count) * sizeof(*b->vardefs);\n    }\n    if (b->cpool) {\n        js_func_size += b->cpool_count * sizeof(*b->cpool);\n        for (i = 0; i < b->cpool_count; i++) {\n            JSValueConst val = b->cpool[i];\n            compute_value_size(val, hp);\n        }\n    }\n    if (b->closure_var) {\n        js_func_size += b->closure_var_count * sizeof(*b->closure_var);\n    }\n    if (!b->read_only_bytecode && b->byte_code_buf) {\n        hp->js_func_code_size += b->byte_code_len;\n    }\n    if (b->has_debug) {\n        js_func_size += sizeof(*b) - offsetof(JSFunctionBytecode, debug);\n        if (b->debug.source) {\n            memory_used_count++;\n            js_func_size += b->debug.source_len + 1;\n        }\n        if (b->debug.pc2line_len) {\n            memory_used_count++;\n            hp->js_func_pc2line_count += 1;\n            hp->js_func_pc2line_size += b->debug.pc2line_len;\n        }\n    }\n    hp->js_func_size += js_func_size;\n    hp->js_func_count += 1;\n    hp->memory_used_count += memory_used_count;\n}\n\nstatic void compute_value_size(JSValueConst val, JSMemoryUsage_helper *hp)\n{\n    switch(JS_VALUE_GET_TAG(val)) {\n    case JS_TAG_STRING:\n        compute_jsstring_size(JS_VALUE_GET_STRING(val), hp);\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n    case JS_TAG_BIG_FLOAT:\n    case JS_TAG_BIG_DECIMAL:\n        /* should track JSBigFloat usage */\n        break;\n#endif\n    }\n}\n\nvoid JS_ComputeMemoryUsage(JSRuntime *rt, JSMemoryUsage *s)\n{\n    struct list_head *el, *el1;\n    int i;\n    JSMemoryUsage_helper mem = { 0 }, *hp = &mem;\n\n    memset(s, 0, sizeof(*s));\n    s->malloc_count = rt->malloc_state.malloc_count;\n    s->malloc_size = rt->malloc_state.malloc_size;\n    s->malloc_limit = rt->malloc_state.malloc_limit;\n\n    s->memory_used_count = 2; /* rt + rt->class_array */\n    s->memory_used_size = sizeof(JSRuntime) + sizeof(JSValue) * rt->class_count;\n\n    list_for_each(el, &rt->context_list) {\n        JSContext *ctx = list_entry(el, JSContext, link);\n        JSShape *sh = ctx->array_shape;\n        s->memory_used_count += 2; /* ctx + ctx->class_proto */\n        s->memory_used_size += sizeof(JSContext) +\n            sizeof(JSValue) * rt->class_count;\n        s->binary_object_count += ctx->binary_object_count;\n        s->binary_object_size += ctx->binary_object_size;\n\n        /* the hashed shapes are counted separately */\n        if (sh && !sh->is_hashed) {\n            int hash_size = sh->prop_hash_mask + 1;\n            s->shape_count++;\n            s->shape_size += get_shape_size(hash_size, sh->prop_size);\n        }\n        list_for_each(el1, &ctx->loaded_modules) {\n            JSModuleDef *m = list_entry(el1, JSModuleDef, link);\n            s->memory_used_count += 1;\n            s->memory_used_size += sizeof(*m);\n            if (m->req_module_entries) {\n                s->memory_used_count += 1;\n                s->memory_used_size += m->req_module_entries_count * sizeof(*m->req_module_entries);\n            }\n            if (m->export_entries) {\n                s->memory_used_count += 1;\n                s->memory_used_size += m->export_entries_count * sizeof(*m->export_entries);\n                for (i = 0; i < m->export_entries_count; i++) {\n                    JSExportEntry *me = &m->export_entries[i];\n                    if (me->export_type == JS_EXPORT_TYPE_LOCAL && me->u.local.var_ref) {\n                        /* potential multiple count */\n                        s->memory_used_count += 1;\n                        compute_value_size(me->u.local.var_ref->value, hp);\n                    }\n                }\n            }\n            if (m->star_export_entries) {\n                s->memory_used_count += 1;\n                s->memory_used_size += m->star_export_entries_count * sizeof(*m->star_export_entries);\n            }\n            if (m->import_entries) {\n                s->memory_used_count += 1;\n                s->memory_used_size += m->import_entries_count * sizeof(*m->import_entries);\n            }\n            compute_value_size(m->module_ns, hp);\n            compute_value_size(m->func_obj, hp);\n        }\n    }\n\n    list_for_each(el, &rt->gc_obj_list) {\n        JSGCObjectHeader *gp = list_entry(el, JSGCObjectHeader, link);\n        JSObject *p;\n        JSShape *sh;\n        JSShapeProperty *prs;\n\n        /* XXX: could count the other GC object types too */\n        if (gp->gc_obj_type == JS_GC_OBJ_TYPE_FUNCTION_BYTECODE) {\n            compute_bytecode_size((JSFunctionBytecode *)gp, hp);\n            continue;\n        } else if (gp->gc_obj_type != JS_GC_OBJ_TYPE_JS_OBJECT) {\n            continue;\n        }\n        p = (JSObject *)gp;\n        sh = p->shape;\n        s->obj_count++;\n        if (p->prop) {\n            s->memory_used_count++;\n            s->prop_size += sh->prop_size * sizeof(*p->prop);\n            s->prop_count += sh->prop_count;\n            prs = get_shape_prop(sh);\n            for(i = 0; i < sh->prop_count; i++) {\n                JSProperty *pr = &p->prop[i];\n                if (prs->atom != JS_ATOM_NULL && !(prs->flags & JS_PROP_TMASK)) {\n                    compute_value_size(pr->u.value, hp);\n                }\n                prs++;\n            }\n        }\n        /* the hashed shapes are counted separately */\n        if (!sh->is_hashed) {\n            int hash_size = sh->prop_hash_mask + 1;\n            s->shape_count++;\n            s->shape_size += get_shape_size(hash_size, sh->prop_size);\n        }\n\n        switch(p->class_id) {\n        case JS_CLASS_ARRAY:             /* u.array | length */\n        case JS_CLASS_ARGUMENTS:         /* u.array | length */\n            s->array_count++;\n            if (p->fast_array) {\n                s->fast_array_count++;\n                if (p->u.array.u.values) {\n                    s->memory_used_count++;\n                    s->memory_used_size += p->u.array.count *\n                        sizeof(*p->u.array.u.values);\n                    s->fast_array_elements += p->u.array.count;\n                    for (i = 0; i < p->u.array.count; i++) {\n                        compute_value_size(p->u.array.u.values[i], hp);\n                    }\n                }\n            }\n            break;\n        case JS_CLASS_NUMBER:            /* u.object_data */\n        case JS_CLASS_STRING:            /* u.object_data */\n        case JS_CLASS_BOOLEAN:           /* u.object_data */\n        case JS_CLASS_SYMBOL:            /* u.object_data */\n        case JS_CLASS_DATE:              /* u.object_data */\n#ifdef CONFIG_BIGNUM\n        case JS_CLASS_BIG_INT:           /* u.object_data */\n        case JS_CLASS_BIG_FLOAT:         /* u.object_data */\n        case JS_CLASS_BIG_DECIMAL:         /* u.object_data */\n#endif\n            compute_value_size(p->u.object_data, hp);\n            break;\n        case JS_CLASS_C_FUNCTION:        /* u.cfunc */\n            s->c_func_count++;\n            break;\n        case JS_CLASS_BYTECODE_FUNCTION: /* u.func */\n            {\n                JSFunctionBytecode *b = p->u.func.function_bytecode;\n                JSVarRef **var_refs = p->u.func.var_refs;\n                /* home_object: object will be accounted for in list scan */\n                if (var_refs) {\n                    s->memory_used_count++;\n                    s->js_func_size += b->closure_var_count * sizeof(*var_refs);\n                    for (i = 0; i < b->closure_var_count; i++) {\n                        if (var_refs[i]) {\n                            double ref_count = var_refs[i]->header.ref_count;\n                            s->memory_used_count += 1 / ref_count;\n                            s->js_func_size += sizeof(*var_refs[i]) / ref_count;\n                            /* handle non object closed values */\n                            if (var_refs[i]->pvalue == &var_refs[i]->value) {\n                                /* potential multiple count */\n                                compute_value_size(var_refs[i]->value, hp);\n                            }\n                        }\n                    }\n                }\n            }\n            break;\n        case JS_CLASS_BOUND_FUNCTION:    /* u.bound_function */\n            {\n                JSBoundFunction *bf = p->u.bound_function;\n                /* func_obj and this_val are objects */\n                for (i = 0; i < bf->argc; i++) {\n                    compute_value_size(bf->argv[i], hp);\n                }\n                s->memory_used_count += 1;\n                s->memory_used_size += sizeof(*bf) + bf->argc * sizeof(*bf->argv);\n            }\n            break;\n        case JS_CLASS_C_FUNCTION_DATA:   /* u.c_function_data_record */\n            {\n                JSCFunctionDataRecord *fd = p->u.c_function_data_record;\n                if (fd) {\n                    for (i = 0; i < fd->data_len; i++) {\n                        compute_value_size(fd->data[i], hp);\n                    }\n                    s->memory_used_count += 1;\n                    s->memory_used_size += sizeof(*fd) + fd->data_len * sizeof(*fd->data);\n                }\n            }\n            break;\n        case JS_CLASS_REGEXP:            /* u.regexp */\n            compute_jsstring_size(p->u.regexp.pattern, hp);\n            compute_jsstring_size(p->u.regexp.bytecode, hp);\n            break;\n\n        case JS_CLASS_FOR_IN_ITERATOR:   /* u.for_in_iterator */\n            {\n                JSForInIterator *it = p->u.for_in_iterator;\n                if (it) {\n                    compute_value_size(it->obj, hp);\n                    s->memory_used_count += 1;\n                    s->memory_used_size += sizeof(*it);\n                }\n            }\n            break;\n        case JS_CLASS_ARRAY_BUFFER:      /* u.array_buffer */\n        case JS_CLASS_SHARED_ARRAY_BUFFER: /* u.array_buffer */\n            {\n                JSArrayBuffer *abuf = p->u.array_buffer;\n                if (abuf) {\n                    s->memory_used_count += 1;\n                    s->memory_used_size += sizeof(*abuf);\n                    if (abuf->data) {\n                        s->memory_used_count += 1;\n                        s->memory_used_size += abuf->byte_length;\n                    }\n                }\n            }\n            break;\n        case JS_CLASS_GENERATOR:         /* u.generator_data */\n        case JS_CLASS_UINT8C_ARRAY:      /* u.typed_array / u.array */\n        case JS_CLASS_INT8_ARRAY:        /* u.typed_array / u.array */\n        case JS_CLASS_UINT8_ARRAY:       /* u.typed_array / u.array */\n        case JS_CLASS_INT16_ARRAY:       /* u.typed_array / u.array */\n        case JS_CLASS_UINT16_ARRAY:      /* u.typed_array / u.array */\n        case JS_CLASS_INT32_ARRAY:       /* u.typed_array / u.array */\n        case JS_CLASS_UINT32_ARRAY:      /* u.typed_array / u.array */\n#ifdef CONFIG_BIGNUM\n        case JS_CLASS_BIG_INT64_ARRAY:   /* u.typed_array / u.array */\n        case JS_CLASS_BIG_UINT64_ARRAY:  /* u.typed_array / u.array */\n#endif\n        case JS_CLASS_FLOAT32_ARRAY:     /* u.typed_array / u.array */\n        case JS_CLASS_FLOAT64_ARRAY:     /* u.typed_array / u.array */\n        case JS_CLASS_DATAVIEW:          /* u.typed_array */\n#ifdef CONFIG_BIGNUM\n        case JS_CLASS_FLOAT_ENV:         /* u.float_env */\n#endif\n        case JS_CLASS_MAP:               /* u.map_state */\n        case JS_CLASS_SET:               /* u.map_state */\n        case JS_CLASS_WEAKMAP:           /* u.map_state */\n        case JS_CLASS_WEAKSET:           /* u.map_state */\n        case JS_CLASS_MAP_ITERATOR:      /* u.map_iterator_data */\n        case JS_CLASS_SET_ITERATOR:      /* u.map_iterator_data */\n        case JS_CLASS_ARRAY_ITERATOR:    /* u.array_iterator_data */\n        case JS_CLASS_STRING_ITERATOR:   /* u.array_iterator_data */\n        case JS_CLASS_PROXY:             /* u.proxy_data */\n        case JS_CLASS_PROMISE:           /* u.promise_data */\n        case JS_CLASS_PROMISE_RESOLVE_FUNCTION:  /* u.promise_function_data */\n        case JS_CLASS_PROMISE_REJECT_FUNCTION:   /* u.promise_function_data */\n        case JS_CLASS_ASYNC_FUNCTION_RESOLVE:    /* u.async_function_data */\n        case JS_CLASS_ASYNC_FUNCTION_REJECT:     /* u.async_function_data */\n        case JS_CLASS_ASYNC_FROM_SYNC_ITERATOR:  /* u.async_from_sync_iterator_data */\n        case JS_CLASS_ASYNC_GENERATOR:   /* u.async_generator_data */\n            /* TODO */\n        default:\n            /* XXX: class definition should have an opaque block size */\n            if (p->u.opaque) {\n                s->memory_used_count += 1;\n            }\n            break;\n        }\n    }\n    s->obj_size += s->obj_count * sizeof(JSObject);\n\n    /* hashed shapes */\n    s->memory_used_count++; /* rt->shape_hash */\n    s->memory_used_size += sizeof(rt->shape_hash[0]) * rt->shape_hash_size;\n    for(i = 0; i < rt->shape_hash_size; i++) {\n        JSShape *sh;\n        for(sh = rt->shape_hash[i]; sh != NULL; sh = sh->shape_hash_next) {\n            int hash_size = sh->prop_hash_mask + 1;\n            s->shape_count++;\n            s->shape_size += get_shape_size(hash_size, sh->prop_size);\n        }\n    }\n\n    /* atoms */\n    s->memory_used_count += 2; /* rt->atom_array, rt->atom_hash */\n    s->atom_count = rt->atom_count;\n    s->atom_size = sizeof(rt->atom_array[0]) * rt->atom_size +\n        sizeof(rt->atom_hash[0]) * rt->atom_hash_size;\n    for(i = 0; i < rt->atom_size; i++) {\n        JSAtomStruct *p = rt->atom_array[i];\n        if (!atom_is_free(p)) {\n            s->atom_size += (sizeof(*p) + (p->len << p->is_wide_char) +\n                             1 - p->is_wide_char);\n        }\n    }\n    s->str_count = round(mem.str_count);\n    s->str_size = round(mem.str_size);\n    s->js_func_count = mem.js_func_count;\n    s->js_func_size = round(mem.js_func_size);\n    s->js_func_code_size = mem.js_func_code_size;\n    s->js_func_pc2line_count = mem.js_func_pc2line_count;\n    s->js_func_pc2line_size = mem.js_func_pc2line_size;\n    s->memory_used_count += round(mem.memory_used_count) +\n        s->atom_count + s->str_count +\n        s->obj_count + s->shape_count +\n        s->js_func_count + s->js_func_pc2line_count;\n    s->memory_used_size += s->atom_size + s->str_size +\n        s->obj_size + s->prop_size + s->shape_size +\n        s->js_func_size + s->js_func_code_size + s->js_func_pc2line_size;\n}\n\nvoid JS_DumpMemoryUsage(FILE *fp, const JSMemoryUsage *s, JSRuntime *rt)\n{\n    fprintf(fp, \"QuickJS memory usage -- \"\n#ifdef CONFIG_BIGNUM\n            \"BigNum \"\n#endif\n            CONFIG_VERSION \" version, %d-bit, malloc limit: %\"PRId64\"\\n\\n\",\n            (int)sizeof(void *) * 8, (int64_t)(ssize_t)s->malloc_limit);\n#if 1\n    if (rt) {\n        static const struct {\n            const char *name;\n            size_t size;\n        } object_types[] = {\n            { \"JSRuntime\", sizeof(JSRuntime) },\n            { \"JSContext\", sizeof(JSContext) },\n            { \"JSObject\", sizeof(JSObject) },\n            { \"JSString\", sizeof(JSString) },\n            { \"JSFunctionBytecode\", sizeof(JSFunctionBytecode) },\n        };\n        int i, usage_size_ok = 0;\n        for(i = 0; i < countof(object_types); i++) {\n            unsigned int size = object_types[i].size;\n            void *p = js_malloc_rt(rt, size);\n            if (p) {\n                unsigned int size1 = js_malloc_usable_size_rt(rt, p);\n                if (size1 >= size) {\n                    usage_size_ok = 1;\n                    fprintf(fp, \"  %3u + %-2u  %s\\n\",\n                            size, size1 - size, object_types[i].name);\n                }\n                js_free_rt(rt, p);\n            }\n        }\n        if (!usage_size_ok) {\n            fprintf(fp, \"  malloc_usable_size unavailable\\n\");\n        }\n        {\n            int obj_classes[JS_CLASS_INIT_COUNT + 1] = { 0 };\n            int class_id;\n            struct list_head *el;\n            list_for_each(el, &rt->gc_obj_list) {\n                JSGCObjectHeader *gp = list_entry(el, JSGCObjectHeader, link);\n                JSObject *p;\n                if (gp->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT) {\n                    p = (JSObject *)gp;\n                    obj_classes[min_uint32(p->class_id, JS_CLASS_INIT_COUNT)]++;\n                }\n            }\n            fprintf(fp, \"\\n\" \"JSObject classes\\n\");\n            if (obj_classes[0])\n                fprintf(fp, \"  %5d  %2.0d %s\\n\", obj_classes[0], 0, \"none\");\n            for (class_id = 1; class_id < JS_CLASS_INIT_COUNT; class_id++) {\n                if (obj_classes[class_id]) {\n                    char buf[ATOM_GET_STR_BUF_SIZE];\n                    fprintf(fp, \"  %5d  %2.0d %s\\n\", obj_classes[class_id], class_id,\n                            JS_AtomGetStrRT(rt, buf, sizeof(buf), js_std_class_def[class_id - 1].class_name));\n                }\n            }\n            if (obj_classes[JS_CLASS_INIT_COUNT])\n                fprintf(fp, \"  %5d  %2.0d %s\\n\", obj_classes[JS_CLASS_INIT_COUNT], 0, \"other\");\n        }\n        fprintf(fp, \"\\n\");\n    }\n#endif\n    fprintf(fp, \"%-20s %8s %8s\\n\", \"NAME\", \"COUNT\", \"SIZE\");\n\n    if (s->malloc_count) {\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per block)\\n\",\n                \"memory allocated\", s->malloc_count, s->malloc_size,\n                (double)s->malloc_size / s->malloc_count);\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%d overhead, %0.1f average slack)\\n\",\n                \"memory used\", s->memory_used_count, s->memory_used_size,\n                MALLOC_OVERHEAD, ((double)(s->malloc_size - s->memory_used_size) /\n                                  s->memory_used_count));\n    }\n    if (s->atom_count) {\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per atom)\\n\",\n                \"atoms\", s->atom_count, s->atom_size,\n                (double)s->atom_size / s->atom_count);\n    }\n    if (s->str_count) {\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per string)\\n\",\n                \"strings\", s->str_count, s->str_size,\n                (double)s->str_size / s->str_count);\n    }\n    if (s->obj_count) {\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per object)\\n\",\n                \"objects\", s->obj_count, s->obj_size,\n                (double)s->obj_size / s->obj_count);\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per object)\\n\",\n                \"  properties\", s->prop_count, s->prop_size,\n                (double)s->prop_count / s->obj_count);\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per shape)\\n\",\n                \"  shapes\", s->shape_count, s->shape_size,\n                (double)s->shape_size / s->shape_count);\n    }\n    if (s->js_func_count) {\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"\\n\",\n                \"bytecode functions\", s->js_func_count, s->js_func_size);\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per function)\\n\",\n                \"  bytecode\", s->js_func_count, s->js_func_code_size,\n                (double)s->js_func_code_size / s->js_func_count);\n        if (s->js_func_pc2line_count) {\n            fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per function)\\n\",\n                    \"  pc2line\", s->js_func_pc2line_count,\n                    s->js_func_pc2line_size,\n                    (double)s->js_func_pc2line_size / s->js_func_pc2line_count);\n        }\n    }\n    if (s->c_func_count) {\n        fprintf(fp, \"%-20s %8\"PRId64\"\\n\", \"C functions\", s->c_func_count);\n    }\n    if (s->array_count) {\n        fprintf(fp, \"%-20s %8\"PRId64\"\\n\", \"arrays\", s->array_count);\n        if (s->fast_array_count) {\n            fprintf(fp, \"%-20s %8\"PRId64\"\\n\", \"  fast arrays\", s->fast_array_count);\n            fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per fast array)\\n\",\n                    \"  elements\", s->fast_array_elements,\n                    s->fast_array_elements * (int)sizeof(JSValue),\n                    (double)s->fast_array_elements / s->fast_array_count);\n        }\n    }\n    if (s->binary_object_count) {\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"\\n\",\n                \"binary objects\", s->binary_object_count, s->binary_object_size);\n    }\n}\n\nJSValue JS_GetGlobalObject(JSContext *ctx)\n{\n    return JS_DupValue(ctx, ctx->global_obj);\n}\n\n/* WARNING: obj is freed */\nJSValue JS_Throw(JSContext *ctx, JSValue obj)\n{\n    JSRuntime *rt = ctx->rt;\n    JS_FreeValue(ctx, rt->current_exception);\n    rt->current_exception = obj;\n    return JS_EXCEPTION;\n}\n\n/* return the pending exception (cannot be called twice). */\nJSValue JS_GetException(JSContext *ctx)\n{\n    JSValue val;\n    JSRuntime *rt = ctx->rt;\n    val = rt->current_exception;\n    rt->current_exception = JS_NULL;\n    return val;\n}\n\nstatic void dbuf_put_leb128(DynBuf *s, uint32_t v)\n{\n    uint32_t a;\n    for(;;) {\n        a = v & 0x7f;\n        v >>= 7;\n        if (v != 0) {\n            dbuf_putc(s, a | 0x80);\n        } else {\n            dbuf_putc(s, a);\n            break;\n        }\n    }\n}\n\nstatic void dbuf_put_sleb128(DynBuf *s, int32_t v1)\n{\n    uint32_t v = v1;\n    dbuf_put_leb128(s, (2 * v) ^ -(v >> 31));\n}\n\nstatic int get_leb128(uint32_t *pval, const uint8_t *buf,\n                      const uint8_t *buf_end)\n{\n    const uint8_t *ptr = buf;\n    uint32_t v, a, i;\n    v = 0;\n    for(i = 0; i < 5; i++) {\n        if (unlikely(ptr >= buf_end))\n            break;\n        a = *ptr++;\n        v |= (a & 0x7f) << (i * 7);\n        if (!(a & 0x80)) {\n            *pval = v;\n            return ptr - buf;\n        }\n    }\n    *pval = 0;\n    return -1;\n}\n\nstatic int get_sleb128(int32_t *pval, const uint8_t *buf,\n                       const uint8_t *buf_end)\n{\n    int ret;\n    uint32_t val;\n    ret = get_leb128(&val, buf, buf_end);\n    if (ret < 0) {\n        *pval = 0;\n        return -1;\n    }\n    *pval = (val >> 1) ^ -(val & 1);\n    return ret;\n}\n\nstatic int find_line_num(JSContext *ctx, JSFunctionBytecode *b,\n                         uint32_t pc_value)\n{\n    const uint8_t *p_end, *p;\n    int new_line_num, line_num, pc, v, ret;\n    unsigned int op;\n\n    if (!b->has_debug || !b->debug.pc2line_buf) {\n        /* function was stripped */\n        return -1;\n    }\n\n    p = b->debug.pc2line_buf;\n    p_end = p + b->debug.pc2line_len;\n    pc = 0;\n    line_num = b->debug.line_num;\n    while (p < p_end) {\n        op = *p++;\n        if (op == 0) {\n            uint32_t val;\n            ret = get_leb128(&val, p, p_end);\n            if (ret < 0)\n                goto fail;\n            pc += val;\n            p += ret;\n            ret = get_sleb128(&v, p, p_end);\n            if (ret < 0) {\n            fail:\n                /* should never happen */\n                return b->debug.line_num;\n            }\n            p += ret;\n            new_line_num = line_num + v;\n        } else {\n            op -= PC2LINE_OP_FIRST;\n            pc += (op / PC2LINE_RANGE);\n            new_line_num = line_num + (op % PC2LINE_RANGE) + PC2LINE_BASE;\n        }\n        if (pc_value < pc)\n            return line_num;\n        line_num = new_line_num;\n    }\n    return line_num;\n}\n\n/* in order to avoid executing arbitrary code during the stack trace\n   generation, we only look at simple 'name' properties containing a\n   string. */\nstatic const char *get_func_name(JSContext *ctx, JSValueConst func)\n{\n    JSProperty *pr;\n    JSShapeProperty *prs;\n    JSValueConst val;\n    \n    if (JS_VALUE_GET_TAG(func) != JS_TAG_OBJECT)\n        return NULL;\n    prs = find_own_property(&pr, JS_VALUE_GET_OBJ(func), JS_ATOM_name);\n    if (!prs)\n        return NULL;\n    if ((prs->flags & JS_PROP_TMASK) != JS_PROP_NORMAL)\n        return NULL;\n    val = pr->u.value;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_STRING)\n        return NULL;\n    return JS_ToCString(ctx, val);\n}\n\n#define JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL (1 << 0)\n/* only taken into account if filename is provided */\n#define JS_BACKTRACE_FLAG_SINGLE_LEVEL     (1 << 1)\n\n/* if filename != NULL, an additional level is added with the filename\n   and line number information (used for parse error). */\nstatic void build_backtrace(JSContext *ctx, JSValueConst error_obj,\n                            const char *filename, int line_num,\n                            int backtrace_flags)\n{\n    JSStackFrame *sf;\n    JSValue str;\n    DynBuf dbuf;\n    const char *func_name_str;\n    const char *str1;\n    JSObject *p;\n    BOOL backtrace_barrier;\n    \n    js_dbuf_init(ctx, &dbuf);\n    if (filename) {\n        dbuf_printf(&dbuf, \"    at %s\", filename);\n        if (line_num != -1)\n            dbuf_printf(&dbuf, \":%d\", line_num);\n        dbuf_putc(&dbuf, '\\n');\n        str = JS_NewString(ctx, filename);\n        JS_DefinePropertyValue(ctx, error_obj, JS_ATOM_fileName, str,\n                               JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n        JS_DefinePropertyValue(ctx, error_obj, JS_ATOM_lineNumber, JS_NewInt32(ctx, line_num),\n                               JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n        if (backtrace_flags & JS_BACKTRACE_FLAG_SINGLE_LEVEL)\n            goto done;\n    }\n    for(sf = ctx->rt->current_stack_frame; sf != NULL; sf = sf->prev_frame) {\n        if (backtrace_flags & JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL) {\n            backtrace_flags &= ~JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL;\n            continue;\n        }\n        func_name_str = get_func_name(ctx, sf->cur_func);\n        if (!func_name_str || func_name_str[0] == '\\0')\n            str1 = \"<anonymous>\";\n        else\n            str1 = func_name_str;\n        dbuf_printf(&dbuf, \"    at %s\", str1);\n        JS_FreeCString(ctx, func_name_str);\n\n        p = JS_VALUE_GET_OBJ(sf->cur_func);\n        backtrace_barrier = FALSE;\n        if (js_class_has_bytecode(p->class_id)) {\n            JSFunctionBytecode *b;\n            const char *atom_str;\n            int line_num1;\n\n            b = p->u.func.function_bytecode;\n            backtrace_barrier = b->backtrace_barrier;\n            if (b->has_debug) {\n                line_num1 = find_line_num(ctx, b,\n                                          sf->cur_pc - b->byte_code_buf - 1);\n                atom_str = JS_AtomToCString(ctx, b->debug.filename);\n                dbuf_printf(&dbuf, \" (%s\",\n                            atom_str ? atom_str : \"<null>\");\n                JS_FreeCString(ctx, atom_str);\n                if (line_num1 != -1)\n                    dbuf_printf(&dbuf, \":%d\", line_num1);\n                dbuf_putc(&dbuf, ')');\n            }\n        } else {\n            dbuf_printf(&dbuf, \" (native)\");\n        }\n        dbuf_putc(&dbuf, '\\n');\n        /* stop backtrace if JS_EVAL_FLAG_BACKTRACE_BARRIER was used */\n        if (backtrace_barrier)\n            break;\n    }\n done:\n    dbuf_putc(&dbuf, '\\0');\n    if (dbuf_error(&dbuf))\n        str = JS_NULL;\n    else\n        str = JS_NewString(ctx, (char *)dbuf.buf);\n    dbuf_free(&dbuf);\n    JS_DefinePropertyValue(ctx, error_obj, JS_ATOM_stack, str,\n                           JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n}\n\n/* Note: it is important that no exception is returned by this function */\nstatic BOOL is_backtrace_needed(JSContext *ctx, JSValueConst obj)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(obj);\n    if (p->class_id != JS_CLASS_ERROR)\n        return FALSE;\n    if (find_own_property1(p, JS_ATOM_stack))\n        return FALSE;\n    return TRUE;\n}\n\nJSValue JS_NewError(JSContext *ctx)\n{\n    return JS_NewObjectClass(ctx, JS_CLASS_ERROR);\n}\n\nstatic JSValue JS_ThrowError2(JSContext *ctx, JSErrorEnum error_num,\n                              const char *fmt, va_list ap, BOOL add_backtrace)\n{\n    char buf[256];\n    JSValue obj, ret;\n\n    vsnprintf(buf, sizeof(buf), fmt, ap);\n    obj = JS_NewObjectProtoClass(ctx, ctx->native_error_proto[error_num],\n                                 JS_CLASS_ERROR);\n    if (unlikely(JS_IsException(obj))) {\n        /* out of memory: throw JS_NULL to avoid recursing */\n        obj = JS_NULL;\n    } else {\n        JS_DefinePropertyValue(ctx, obj, JS_ATOM_message,\n                               JS_NewString(ctx, buf),\n                               JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    }\n    if (add_backtrace) {\n        build_backtrace(ctx, obj, NULL, 0, 0);\n    }\n    ret = JS_Throw(ctx, obj);\n    return ret;\n}\n\nstatic JSValue JS_ThrowError(JSContext *ctx, JSErrorEnum error_num,\n                             const char *fmt, va_list ap)\n{\n    JSRuntime *rt = ctx->rt;\n    JSStackFrame *sf;\n    BOOL add_backtrace;\n\n    /* the backtrace is added later if called from a bytecode function */\n    sf = rt->current_stack_frame;\n    add_backtrace = !rt->in_out_of_memory &&\n        (!sf || (JS_GetFunctionBytecode(sf->cur_func) == NULL));\n    return JS_ThrowError2(ctx, error_num, fmt, ap, add_backtrace);\n}\n\nJSValue __attribute__((format(printf, 2, 3))) JS_ThrowSyntaxError(JSContext *ctx, const char *fmt, ...)\n{\n    JSValue val;\n    va_list ap;\n\n    va_start(ap, fmt);\n    val = JS_ThrowError(ctx, JS_SYNTAX_ERROR, fmt, ap);\n    va_end(ap);\n    return val;\n}\n\nJSValue __attribute__((format(printf, 2, 3))) JS_ThrowTypeError(JSContext *ctx, const char *fmt, ...)\n{\n    JSValue val;\n    va_list ap;\n\n    va_start(ap, fmt);\n    val = JS_ThrowError(ctx, JS_TYPE_ERROR, fmt, ap);\n    va_end(ap);\n    return val;\n}\n\nstatic int __attribute__((format(printf, 3, 4))) JS_ThrowTypeErrorOrFalse(JSContext *ctx, int flags, const char *fmt, ...)\n{\n    va_list ap;\n\n    if ((flags & JS_PROP_THROW) ||\n        ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) {\n        va_start(ap, fmt);\n        JS_ThrowError(ctx, JS_TYPE_ERROR, fmt, ap);\n        va_end(ap);\n        return -1;\n    } else {\n        return FALSE;\n    }\n}\n\n/* never use it directly */\nstatic JSValue __attribute__((format(printf, 3, 4))) __JS_ThrowTypeErrorAtom(JSContext *ctx, JSAtom atom, const char *fmt, ...)\n{\n    char buf[ATOM_GET_STR_BUF_SIZE];\n    return JS_ThrowTypeError(ctx, fmt,\n                             JS_AtomGetStr(ctx, buf, sizeof(buf), atom));\n}\n\n/* never use it directly */\nstatic JSValue __attribute__((format(printf, 3, 4))) __JS_ThrowSyntaxErrorAtom(JSContext *ctx, JSAtom atom, const char *fmt, ...)\n{\n    char buf[ATOM_GET_STR_BUF_SIZE];\n    return JS_ThrowSyntaxError(ctx, fmt,\n                             JS_AtomGetStr(ctx, buf, sizeof(buf), atom));\n}\n\n/* %s is replaced by 'atom'. The macro is used so that gcc can check\n    the format string. */\n#define JS_ThrowTypeErrorAtom(ctx, fmt, atom) __JS_ThrowTypeErrorAtom(ctx, atom, fmt, \"\")\n#define JS_ThrowSyntaxErrorAtom(ctx, fmt, atom) __JS_ThrowSyntaxErrorAtom(ctx, atom, fmt, \"\")\n\nstatic int JS_ThrowTypeErrorReadOnly(JSContext *ctx, int flags, JSAtom atom)\n{\n    if ((flags & JS_PROP_THROW) ||\n        ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) {\n        JS_ThrowTypeErrorAtom(ctx, \"'%s' is read-only\", atom);\n        return -1;\n    } else {\n        return FALSE;\n    }\n}\n\nJSValue __attribute__((format(printf, 2, 3))) JS_ThrowReferenceError(JSContext *ctx, const char *fmt, ...)\n{\n    JSValue val;\n    va_list ap;\n\n    va_start(ap, fmt);\n    val = JS_ThrowError(ctx, JS_REFERENCE_ERROR, fmt, ap);\n    va_end(ap);\n    return val;\n}\n\nJSValue __attribute__((format(printf, 2, 3))) JS_ThrowRangeError(JSContext *ctx, const char *fmt, ...)\n{\n    JSValue val;\n    va_list ap;\n\n    va_start(ap, fmt);\n    val = JS_ThrowError(ctx, JS_RANGE_ERROR, fmt, ap);\n    va_end(ap);\n    return val;\n}\n\nJSValue __attribute__((format(printf, 2, 3))) JS_ThrowInternalError(JSContext *ctx, const char *fmt, ...)\n{\n    JSValue val;\n    va_list ap;\n\n    va_start(ap, fmt);\n    val = JS_ThrowError(ctx, JS_INTERNAL_ERROR, fmt, ap);\n    va_end(ap);\n    return val;\n}\n\nJSValue JS_ThrowOutOfMemory(JSContext *ctx)\n{\n    JSRuntime *rt = ctx->rt;\n    if (!rt->in_out_of_memory) {\n        rt->in_out_of_memory = TRUE;\n        JS_ThrowInternalError(ctx, \"out of memory\");\n        rt->in_out_of_memory = FALSE;\n    }\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ThrowStackOverflow(JSContext *ctx)\n{\n    return JS_ThrowInternalError(ctx, \"stack overflow\");\n}\n\nstatic JSValue JS_ThrowTypeErrorNotAnObject(JSContext *ctx)\n{\n    return JS_ThrowTypeError(ctx, \"not an object\");\n}\n\nstatic JSValue JS_ThrowTypeErrorNotASymbol(JSContext *ctx)\n{\n    return JS_ThrowTypeError(ctx, \"not a symbol\");\n}\n\nstatic JSValue JS_ThrowReferenceErrorNotDefined(JSContext *ctx, JSAtom name)\n{\n    char buf[ATOM_GET_STR_BUF_SIZE];\n    return JS_ThrowReferenceError(ctx, \"'%s' is not defined\",\n                                  JS_AtomGetStr(ctx, buf, sizeof(buf), name));\n}\n\nstatic JSValue JS_ThrowReferenceErrorUninitialized(JSContext *ctx, JSAtom name)\n{\n    char buf[ATOM_GET_STR_BUF_SIZE];\n    return JS_ThrowReferenceError(ctx, \"%s is not initialized\",\n                                  name == JS_ATOM_NULL ? \"lexical variable\" :\n                                  JS_AtomGetStr(ctx, buf, sizeof(buf), name));\n}\n\nstatic JSValue JS_ThrowReferenceErrorUninitialized2(JSContext *ctx,\n                                                    JSFunctionBytecode *b,\n                                                    int idx, BOOL is_ref)\n{\n    JSAtom atom = JS_ATOM_NULL;\n    if (is_ref) {\n        atom = b->closure_var[idx].var_name;\n    } else {\n        /* not present if the function is stripped and contains no eval() */\n        if (b->vardefs)\n            atom = b->vardefs[b->arg_count + idx].var_name;\n    }\n    return JS_ThrowReferenceErrorUninitialized(ctx, atom);\n}\n\nstatic JSValue JS_ThrowTypeErrorInvalidClass(JSContext *ctx, int class_id)\n{\n    JSRuntime *rt = ctx->rt;\n    JSAtom name;\n    name = rt->class_array[class_id].class_name;\n    return JS_ThrowTypeErrorAtom(ctx, \"%s object expected\", name);\n}\n\nstatic no_inline __exception int __js_poll_interrupts(JSContext *ctx)\n{\n    JSRuntime *rt = ctx->rt;\n    ctx->interrupt_counter = JS_INTERRUPT_COUNTER_INIT;\n    if (rt->interrupt_handler) {\n        if (rt->interrupt_handler(rt, rt->interrupt_opaque)) {\n            /* XXX: should set a specific flag to avoid catching */\n            JS_ThrowInternalError(ctx, \"interrupted\");\n            JS_SetUncatchableError(ctx, ctx->rt->current_exception, TRUE);\n            return -1;\n        }\n    }\n    return 0;\n}\n\nstatic inline __exception int js_poll_interrupts(JSContext *ctx)\n{\n    if (unlikely(--ctx->interrupt_counter <= 0)) {\n        return __js_poll_interrupts(ctx);\n    } else {\n        return 0;\n    }\n}\n\n/* return -1 (exception) or TRUE/FALSE */\nstatic int JS_SetPrototypeInternal(JSContext *ctx, JSValueConst obj,\n                                   JSValueConst proto_val,\n                                   BOOL throw_flag)\n{\n    JSObject *proto, *p, *p1;\n    JSShape *sh;\n\n    if (throw_flag) {\n        if (JS_VALUE_GET_TAG(obj) == JS_TAG_NULL ||\n            JS_VALUE_GET_TAG(obj) == JS_TAG_UNDEFINED)\n            goto not_obj;\n    } else {\n        if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n            goto not_obj;\n    }\n    p = JS_VALUE_GET_OBJ(obj);\n    if (JS_VALUE_GET_TAG(proto_val) != JS_TAG_OBJECT) {\n        if (JS_VALUE_GET_TAG(proto_val) != JS_TAG_NULL) {\n        not_obj:\n            JS_ThrowTypeErrorNotAnObject(ctx);\n            return -1;\n        }\n        proto = NULL;\n    } else {\n        proto = JS_VALUE_GET_OBJ(proto_val);\n    }\n\n    if (throw_flag && JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return TRUE;\n\n    if (unlikely(p->class_id == JS_CLASS_PROXY))\n        return js_proxy_setPrototypeOf(ctx, obj, proto_val, throw_flag);\n    sh = p->shape;\n    if (sh->proto == proto)\n        return TRUE;\n    if (!p->extensible) {\n        if (throw_flag) {\n            JS_ThrowTypeError(ctx, \"object is not extensible\");\n            return -1;\n        } else {\n            return FALSE;\n        }\n    }\n    if (proto) {\n        /* check if there is a cycle */\n        p1 = proto;\n        do {\n            if (p1 == p) {\n                if (throw_flag) {\n                    JS_ThrowTypeError(ctx, \"circular prototype chain\");\n                    return -1;\n                } else {\n                    return FALSE;\n                }\n            }\n            /* Note: for Proxy objects, proto is NULL */\n            p1 = p1->shape->proto;\n        } while (p1 != NULL);\n        JS_DupValue(ctx, proto_val);\n    }\n\n    if (js_shape_prepare_update(ctx, p, NULL))\n        return -1;\n    sh = p->shape;\n    if (sh->proto)\n        JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, sh->proto));\n    sh->proto = proto;\n    return TRUE;\n}\n\n/* return -1 (exception) or TRUE/FALSE */\nint JS_SetPrototype(JSContext *ctx, JSValueConst obj, JSValueConst proto_val)\n{\n    return JS_SetPrototypeInternal(ctx, obj, proto_val, TRUE);\n}\n\n/* Only works for primitive types, otherwise return JS_NULL. */\nstatic JSValueConst JS_GetPrototypePrimitive(JSContext *ctx, JSValueConst val)\n{\n    switch(JS_VALUE_GET_NORM_TAG(val)) {\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n        val = ctx->class_proto[JS_CLASS_BIG_INT];\n        break;\n    case JS_TAG_BIG_FLOAT:\n        val = ctx->class_proto[JS_CLASS_BIG_FLOAT];\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        val = ctx->class_proto[JS_CLASS_BIG_DECIMAL];\n        break;\n#endif\n    case JS_TAG_INT:\n    case JS_TAG_FLOAT64:\n        val = ctx->class_proto[JS_CLASS_NUMBER];\n        break;\n    case JS_TAG_BOOL:\n        val = ctx->class_proto[JS_CLASS_BOOLEAN];\n        break;\n    case JS_TAG_STRING:\n        val = ctx->class_proto[JS_CLASS_STRING];\n        break;\n    case JS_TAG_SYMBOL:\n        val = ctx->class_proto[JS_CLASS_SYMBOL];\n        break;\n    case JS_TAG_OBJECT:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n    default:\n        val = JS_NULL;\n        break;\n    }\n    return val;\n}\n\n/* Return an Object, JS_NULL or JS_EXCEPTION in case of Proxy object. */\nJSValue JS_GetPrototype(JSContext *ctx, JSValueConst obj)\n{\n    JSValue val;\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        JSObject *p;\n        p = JS_VALUE_GET_OBJ(obj);\n        if (unlikely(p->class_id == JS_CLASS_PROXY)) {\n            val = js_proxy_getPrototypeOf(ctx, obj);\n        } else {\n            p = p->shape->proto;\n            if (!p)\n                val = JS_NULL;\n            else\n                val = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n        }\n    } else {\n        val = JS_DupValue(ctx, JS_GetPrototypePrimitive(ctx, obj));\n    }\n    return val;\n}\n\nstatic JSValue JS_GetPrototypeFree(JSContext *ctx, JSValue obj)\n{\n    JSValue obj1;\n    obj1 = JS_GetPrototype(ctx, obj);\n    JS_FreeValue(ctx, obj);\n    return obj1;\n}\n\n/* return TRUE, FALSE or (-1) in case of exception */\nstatic int JS_OrdinaryIsInstanceOf(JSContext *ctx, JSValueConst val,\n                                   JSValueConst obj)\n{\n    JSValue obj_proto;\n    JSObject *proto;\n    const JSObject *p, *proto1;\n    BOOL ret;\n\n    if (!JS_IsFunction(ctx, obj))\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(obj);\n    if (p->class_id == JS_CLASS_BOUND_FUNCTION) {\n        JSBoundFunction *s = p->u.bound_function;\n        return JS_IsInstanceOf(ctx, val, s->func_obj);\n    }\n\n    /* Only explicitly boxed values are instances of constructors */\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return FALSE;\n    obj_proto = JS_GetProperty(ctx, obj, JS_ATOM_prototype);\n    if (JS_VALUE_GET_TAG(obj_proto) != JS_TAG_OBJECT) {\n        if (!JS_IsException(obj_proto))\n            JS_ThrowTypeError(ctx, \"operand 'prototype' property is not an object\");\n        ret = -1;\n        goto done;\n    }\n    proto = JS_VALUE_GET_OBJ(obj_proto);\n    p = JS_VALUE_GET_OBJ(val);\n    for(;;) {\n        proto1 = p->shape->proto;\n        if (!proto1) {\n            /* slow case if proxy in the prototype chain */\n            if (unlikely(p->class_id == JS_CLASS_PROXY)) {\n                JSValue obj1;\n                obj1 = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, (JSObject *)p));\n                for(;;) {\n                    obj1 = JS_GetPrototypeFree(ctx, obj1);\n                    if (JS_IsException(obj1)) {\n                        ret = -1;\n                        break;\n                    }\n                    if (JS_IsNull(obj1)) {\n                        ret = FALSE;\n                        break;\n                    }\n                    if (proto == JS_VALUE_GET_OBJ(obj1)) {\n                        JS_FreeValue(ctx, obj1);\n                        ret = TRUE;\n                        break;\n                    }\n                    /* must check for timeout to avoid infinite loop */\n                    if (js_poll_interrupts(ctx)) {\n                        JS_FreeValue(ctx, obj1);\n                        ret = -1;\n                        break;\n                    }\n                }\n            } else {\n                ret = FALSE;\n            }\n            break;\n        }\n        p = proto1;\n        if (proto == p) {\n            ret = TRUE;\n            break;\n        }\n    }\ndone:\n    JS_FreeValue(ctx, obj_proto);\n    return ret;\n}\n\n/* return TRUE, FALSE or (-1) in case of exception */\nint JS_IsInstanceOf(JSContext *ctx, JSValueConst val, JSValueConst obj)\n{\n    JSValue method;\n\n    if (!JS_IsObject(obj))\n        goto fail;\n    method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_hasInstance);\n    if (JS_IsException(method))\n        return -1;\n    if (!JS_IsNull(method) && !JS_IsUndefined(method)) {\n        JSValue ret;\n        ret = JS_CallFree(ctx, method, obj, 1, &val);\n        return JS_ToBoolFree(ctx, ret);\n    }\n\n    /* legacy case */\n    if (!JS_IsFunction(ctx, obj)) {\n    fail:\n        JS_ThrowTypeError(ctx, \"invalid 'instanceof' right operand\");\n        return -1;\n    }\n    return JS_OrdinaryIsInstanceOf(ctx, val, obj);\n}\n\n/* return the value associated to the autoinit property or an exception */\ntypedef JSValue JSAutoInitFunc(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque);\n\nstatic JSAutoInitFunc *js_autoinit_func_table[] = {\n    js_instantiate_prototype, /* JS_AUTOINIT_ID_PROTOTYPE */\n    js_module_ns_autoinit, /* JS_AUTOINIT_ID_MODULE_NS */\n    JS_InstantiateFunctionListItem2, /* JS_AUTOINIT_ID_PROP */\n};\n\n/* warning: 'prs' is reallocated after it */\nstatic int JS_AutoInitProperty(JSContext *ctx, JSObject *p, JSAtom prop,\n                               JSProperty *pr, JSShapeProperty *prs)\n{\n    JSValue val;\n    JSContext *realm;\n    JSAutoInitFunc *func;\n\n    if (js_shape_prepare_update(ctx, p, &prs))\n        return -1;\n\n    realm = js_autoinit_get_realm(pr);\n    func = js_autoinit_func_table[js_autoinit_get_id(pr)];\n    /* 'func' shall not modify the object properties 'pr' */\n    val = func(realm, p, prop, pr->u.init.opaque);\n    js_autoinit_free(ctx->rt, pr);\n    prs->flags &= ~JS_PROP_TMASK;\n    pr->u.value = JS_UNDEFINED;\n    if (JS_IsException(val))\n        return -1;\n    pr->u.value = val;\n    return 0;\n}\n\nJSValue JS_GetPropertyInternal(JSContext *ctx, JSValueConst obj,\n                               JSAtom prop, JSValueConst this_obj,\n                               BOOL throw_ref_error)\n{\n    JSObject *p;\n    JSProperty *pr;\n    JSShapeProperty *prs;\n    uint32_t tag;\n\n    tag = JS_VALUE_GET_TAG(obj);\n    if (unlikely(tag != JS_TAG_OBJECT)) {\n        switch(tag) {\n        case JS_TAG_NULL:\n            return JS_ThrowTypeErrorAtom(ctx, \"cannot read property '%s' of null\", prop);\n        case JS_TAG_UNDEFINED:\n            return JS_ThrowTypeErrorAtom(ctx, \"cannot read property '%s' of undefined\", prop);\n        case JS_TAG_EXCEPTION:\n            return JS_EXCEPTION;\n        case JS_TAG_STRING:\n            {\n                JSString *p1 = JS_VALUE_GET_STRING(obj);\n                if (__JS_AtomIsTaggedInt(prop)) {\n                    uint32_t idx, ch;\n                    idx = __JS_AtomToUInt32(prop);\n                    if (idx < p1->len) {\n                        if (p1->is_wide_char)\n                            ch = p1->u.str16[idx];\n                        else\n                            ch = p1->u.str8[idx];\n                        return js_new_string_char(ctx, ch);\n                    }\n                } else if (prop == JS_ATOM_length) {\n                    return JS_NewInt32(ctx, p1->len);\n                }\n            }\n            break;\n        default:\n            break;\n        }\n        /* cannot raise an exception */\n        p = JS_VALUE_GET_OBJ(JS_GetPrototypePrimitive(ctx, obj));\n        if (!p)\n            return JS_UNDEFINED;\n    } else {\n        p = JS_VALUE_GET_OBJ(obj);\n    }\n\n    for(;;) {\n        prs = find_own_property(&pr, p, prop);\n        if (prs) {\n            /* found */\n            if (unlikely(prs->flags & JS_PROP_TMASK)) {\n                if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {\n                    if (unlikely(!pr->u.getset.getter)) {\n                        return JS_UNDEFINED;\n                    } else {\n                        JSValue func = JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter);\n                        /* Note: the field could be removed in the getter */\n                        func = JS_DupValue(ctx, func);\n                        return JS_CallFree(ctx, func, this_obj, 0, NULL);\n                    }\n                } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n                    JSValue val = *pr->u.var_ref->pvalue;\n                    if (unlikely(JS_IsUninitialized(val)))\n                        return JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);\n                    return JS_DupValue(ctx, val);\n                } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n                    /* Instantiate property and retry */\n                    if (JS_AutoInitProperty(ctx, p, prop, pr, prs))\n                        return JS_EXCEPTION;\n                    continue;\n                }\n            } else {\n                return JS_DupValue(ctx, pr->u.value);\n            }\n        }\n        if (unlikely(p->is_exotic)) {\n            /* exotic behaviors */\n            if (p->fast_array) {\n                if (__JS_AtomIsTaggedInt(prop)) {\n                    uint32_t idx = __JS_AtomToUInt32(prop);\n                    if (idx < p->u.array.count) {\n                        /* we avoid duplicating the code */\n                        return JS_GetPropertyUint32(ctx, JS_MKPTR(JS_TAG_OBJECT, p), idx);\n                    } else if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n                               p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n                        return JS_UNDEFINED;\n                    }\n                } else if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n                           p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n                    int ret;\n                    ret = JS_AtomIsNumericIndex(ctx, prop);\n                    if (ret != 0) {\n                        if (ret < 0)\n                            return JS_EXCEPTION;\n                        return JS_UNDEFINED;\n                    }\n                }\n            } else {\n                const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;\n                if (em) {\n                    if (em->get_property) {\n                        JSValue obj1, retval;\n                        /* XXX: should pass throw_ref_error */\n                        /* Note: if 'p' is a prototype, it can be\n                           freed in the called function */\n                        obj1 = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n                        retval = em->get_property(ctx, obj1, prop, this_obj);\n                        JS_FreeValue(ctx, obj1);\n                        return retval;\n                    }\n                    if (em->get_own_property) {\n                        JSPropertyDescriptor desc;\n                        int ret;\n                        JSValue obj1;\n\n                        /* Note: if 'p' is a prototype, it can be\n                           freed in the called function */\n                        obj1 = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n                        ret = em->get_own_property(ctx, &desc, obj1, prop);\n                        JS_FreeValue(ctx, obj1);\n                        if (ret < 0)\n                            return JS_EXCEPTION;\n                        if (ret) {\n                            if (desc.flags & JS_PROP_GETSET) {\n                                JS_FreeValue(ctx, desc.setter);\n                                return JS_CallFree(ctx, desc.getter, this_obj, 0, NULL);\n                            } else {\n                                return desc.value;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        p = p->shape->proto;\n        if (!p)\n            break;\n    }\n    if (unlikely(throw_ref_error)) {\n        return JS_ThrowReferenceErrorNotDefined(ctx, prop);\n    } else {\n        return JS_UNDEFINED;\n    }\n}\n\nstatic JSValue JS_ThrowTypeErrorPrivateNotFound(JSContext *ctx, JSAtom atom)\n{\n    return JS_ThrowTypeErrorAtom(ctx, \"private class field '%s' does not exist\",\n                                 atom);\n}\n\n/* Private fields can be added even on non extensible objects or\n   Proxies */\nstatic int JS_DefinePrivateField(JSContext *ctx, JSValueConst obj,\n                                 JSValueConst name, JSValue val)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    JSAtom prop;\n\n    if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        goto fail;\n    }\n    /* safety check */\n    if (unlikely(JS_VALUE_GET_TAG(name) != JS_TAG_SYMBOL)) {\n        JS_ThrowTypeErrorNotASymbol(ctx);\n        goto fail;\n    }\n    prop = js_symbol_to_atom(ctx, (JSValue)name);\n    p = JS_VALUE_GET_OBJ(obj);\n    prs = find_own_property(&pr, p, prop);\n    if (prs) {\n        JS_ThrowTypeErrorAtom(ctx, \"private class field '%s' already exists\",\n                              prop);\n        goto fail;\n    }\n    pr = add_property(ctx, p, prop, JS_PROP_C_W_E);\n    if (unlikely(!pr)) {\n    fail:\n        JS_FreeValue(ctx, val);\n        return -1;\n    }\n    pr->u.value = val;\n    return 0;\n}\n\nstatic JSValue JS_GetPrivateField(JSContext *ctx, JSValueConst obj,\n                                  JSValueConst name)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    JSAtom prop;\n\n    if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    /* safety check */\n    if (unlikely(JS_VALUE_GET_TAG(name) != JS_TAG_SYMBOL))\n        return JS_ThrowTypeErrorNotASymbol(ctx);\n    prop = js_symbol_to_atom(ctx, (JSValue)name);\n    p = JS_VALUE_GET_OBJ(obj);\n    prs = find_own_property(&pr, p, prop);\n    if (!prs) {\n        JS_ThrowTypeErrorPrivateNotFound(ctx, prop);\n        return JS_EXCEPTION;\n    }\n    return JS_DupValue(ctx, pr->u.value);\n}\n\nstatic int JS_SetPrivateField(JSContext *ctx, JSValueConst obj,\n                              JSValueConst name, JSValue val)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    JSAtom prop;\n\n    if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        goto fail;\n    }\n    /* safety check */\n    if (unlikely(JS_VALUE_GET_TAG(name) != JS_TAG_SYMBOL)) {\n        JS_ThrowTypeErrorNotASymbol(ctx);\n        goto fail;\n    }\n    prop = js_symbol_to_atom(ctx, (JSValue)name);\n    p = JS_VALUE_GET_OBJ(obj);\n    prs = find_own_property(&pr, p, prop);\n    if (!prs) {\n        JS_ThrowTypeErrorPrivateNotFound(ctx, prop);\n    fail:\n        JS_FreeValue(ctx, val);\n        return -1;\n    }\n    set_value(ctx, &pr->u.value, val);\n    return 0;\n}\n\nstatic int JS_AddBrand(JSContext *ctx, JSValueConst obj, JSValueConst home_obj)\n{\n    JSObject *p, *p1;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    JSValue brand;\n    JSAtom brand_atom;\n    \n    if (unlikely(JS_VALUE_GET_TAG(home_obj) != JS_TAG_OBJECT)) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        return -1;\n    }\n    p = JS_VALUE_GET_OBJ(home_obj);\n    prs = find_own_property(&pr, p, JS_ATOM_Private_brand);\n    if (!prs) {\n        brand = JS_NewSymbolFromAtom(ctx, JS_ATOM_brand, JS_ATOM_TYPE_PRIVATE);\n        if (JS_IsException(brand))\n            return -1;\n        /* if the brand is not present, add it */\n        pr = add_property(ctx, p, JS_ATOM_Private_brand, JS_PROP_C_W_E);\n        if (!pr) {\n            JS_FreeValue(ctx, brand);\n            return -1;\n        }\n        pr->u.value = JS_DupValue(ctx, brand);\n    } else {\n        brand = JS_DupValue(ctx, pr->u.value);\n    }\n    brand_atom = js_symbol_to_atom(ctx, brand);\n    \n    if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        JS_FreeAtom(ctx, brand_atom);\n        return -1;\n    }\n    p1 = JS_VALUE_GET_OBJ(obj);\n    pr = add_property(ctx, p1, brand_atom, JS_PROP_C_W_E);\n    JS_FreeAtom(ctx, brand_atom);\n    if (!pr)\n        return -1;\n    pr->u.value = JS_UNDEFINED;\n    return 0;\n}\n\nstatic int JS_CheckBrand(JSContext *ctx, JSValueConst obj, JSValueConst func)\n{\n    JSObject *p, *p1, *home_obj;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    JSValueConst brand;\n    \n    /* get the home object of 'func' */\n    if (unlikely(JS_VALUE_GET_TAG(func) != JS_TAG_OBJECT)) {\n    not_obj:\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        return -1;\n    }\n    p1 = JS_VALUE_GET_OBJ(func);\n    if (!js_class_has_bytecode(p1->class_id))\n        goto not_obj;\n    home_obj = p1->u.func.home_object;\n    if (!home_obj)\n        goto not_obj;\n    prs = find_own_property(&pr, home_obj, JS_ATOM_Private_brand);\n    if (!prs) {\n        JS_ThrowTypeError(ctx, \"expecting <brand> private field\");\n        return -1;\n    }\n    brand = pr->u.value;\n    /* safety check */\n    if (unlikely(JS_VALUE_GET_TAG(brand) != JS_TAG_SYMBOL))\n        goto not_obj;\n    \n    /* get the brand array of 'obj' */\n    if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT))\n        goto not_obj;\n    p = JS_VALUE_GET_OBJ(obj);\n    prs = find_own_property(&pr, p, js_symbol_to_atom(ctx, (JSValue)brand));\n    if (!prs) {\n        JS_ThrowTypeError(ctx, \"invalid brand on object\");\n        return -1;\n    }\n    return 0;\n}\n\nstatic uint32_t js_string_obj_get_length(JSContext *ctx,\n                                         JSValueConst obj)\n{\n    JSObject *p;\n    JSString *p1;\n    uint32_t len = 0;\n\n    /* This is a class exotic method: obj class_id is JS_CLASS_STRING */\n    p = JS_VALUE_GET_OBJ(obj);\n    if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_STRING) {\n        p1 = JS_VALUE_GET_STRING(p->u.object_data);\n        len = p1->len;\n    }\n    return len;\n}\n\nstatic int num_keys_cmp(const void *p1, const void *p2, void *opaque)\n{\n    JSContext *ctx = opaque;\n    JSAtom atom1 = ((const JSPropertyEnum *)p1)->atom;\n    JSAtom atom2 = ((const JSPropertyEnum *)p2)->atom;\n    uint32_t v1, v2;\n    BOOL atom1_is_integer, atom2_is_integer;\n\n    atom1_is_integer = JS_AtomIsArrayIndex(ctx, &v1, atom1);\n    atom2_is_integer = JS_AtomIsArrayIndex(ctx, &v2, atom2);\n    assert(atom1_is_integer && atom2_is_integer);\n    if (v1 < v2)\n        return -1;\n    else if (v1 == v2)\n        return 0;\n    else\n        return 1;\n}\n\nstatic void js_free_prop_enum(JSContext *ctx, JSPropertyEnum *tab, uint32_t len)\n{\n    uint32_t i;\n    if (tab) {\n        for(i = 0; i < len; i++)\n            JS_FreeAtom(ctx, tab[i].atom);\n        js_free(ctx, tab);\n    }\n}\n\n/* return < 0 in case if exception, 0 if OK. ptab and its atoms must\n   be freed by the user. */\nstatic int __exception JS_GetOwnPropertyNamesInternal(JSContext *ctx,\n                                                      JSPropertyEnum **ptab,\n                                                      uint32_t *plen,\n                                                      JSObject *p, int flags)\n{\n    int i, j;\n    JSShape *sh;\n    JSShapeProperty *prs;\n    JSPropertyEnum *tab_atom, *tab_exotic;\n    JSAtom atom;\n    uint32_t num_keys_count, str_keys_count, sym_keys_count, atom_count;\n    uint32_t num_index, str_index, sym_index, exotic_count, exotic_keys_count;\n    BOOL is_enumerable, num_sorted;\n    uint32_t num_key;\n    JSAtomKindEnum kind;\n    \n    /* clear pointer for consistency in case of failure */\n    *ptab = NULL;\n    *plen = 0;\n\n    /* compute the number of returned properties */\n    num_keys_count = 0;\n    str_keys_count = 0;\n    sym_keys_count = 0;\n    exotic_keys_count = 0;\n    exotic_count = 0;\n    tab_exotic = NULL;\n    sh = p->shape;\n    for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) {\n        atom = prs->atom;\n        if (atom != JS_ATOM_NULL) {\n            is_enumerable = ((prs->flags & JS_PROP_ENUMERABLE) != 0);\n            kind = JS_AtomGetKind(ctx, atom);\n            if ((!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) &&\n                ((flags >> kind) & 1) != 0) {\n                /* need to raise an exception in case of the module\n                   name space (implicit GetOwnProperty) */\n                if (unlikely((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) &&\n                    (flags & (JS_GPN_SET_ENUM | JS_GPN_ENUM_ONLY))) {\n                    JSVarRef *var_ref = p->prop[i].u.var_ref;\n                    if (unlikely(JS_IsUninitialized(*var_ref->pvalue))) {\n                        JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);\n                        return -1;\n                    }\n                }\n                if (JS_AtomIsArrayIndex(ctx, &num_key, atom)) {\n                    num_keys_count++;\n                } else if (kind == JS_ATOM_KIND_STRING) {\n                    str_keys_count++;\n                } else {\n                    sym_keys_count++;\n                }\n            }\n        }\n    }\n\n    if (p->is_exotic) {\n        if (p->fast_array) {\n            if (flags & JS_GPN_STRING_MASK) {\n                num_keys_count += p->u.array.count;\n            }\n        } else if (p->class_id == JS_CLASS_STRING) {\n            if (flags & JS_GPN_STRING_MASK) {\n                num_keys_count += js_string_obj_get_length(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n            }\n        } else {\n            const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;\n            if (em && em->get_own_property_names) {\n                if (em->get_own_property_names(ctx, &tab_exotic, &exotic_count,\n                                               JS_MKPTR(JS_TAG_OBJECT, p)))\n                    return -1;\n                for(i = 0; i < exotic_count; i++) {\n                    atom = tab_exotic[i].atom;\n                    kind = JS_AtomGetKind(ctx, atom);\n                    if (((flags >> kind) & 1) != 0) {\n                        is_enumerable = FALSE;\n                        if (flags & (JS_GPN_SET_ENUM | JS_GPN_ENUM_ONLY)) {\n                            JSPropertyDescriptor desc;\n                            int res;\n                            /* set the \"is_enumerable\" field if necessary */\n                            res = JS_GetOwnPropertyInternal(ctx, &desc, p, atom);\n                            if (res < 0) {\n                                js_free_prop_enum(ctx, tab_exotic, exotic_count);\n                                return -1;\n                            }\n                            if (res) {\n                                is_enumerable =\n                                    ((desc.flags & JS_PROP_ENUMERABLE) != 0);\n                                js_free_desc(ctx, &desc);\n                            }\n                            tab_exotic[i].is_enumerable = is_enumerable;\n                        }\n                        if (!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) {\n                            exotic_keys_count++;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    /* fill them */\n\n    atom_count = num_keys_count + str_keys_count + sym_keys_count + exotic_keys_count;\n    /* avoid allocating 0 bytes */\n    tab_atom = js_malloc(ctx, sizeof(tab_atom[0]) * max_int(atom_count, 1));\n    if (!tab_atom) {\n        js_free_prop_enum(ctx, tab_exotic, exotic_count);\n        return -1;\n    }\n\n    num_index = 0;\n    str_index = num_keys_count;\n    sym_index = str_index + str_keys_count;\n\n    num_sorted = TRUE;\n    sh = p->shape;\n    for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) {\n        atom = prs->atom;\n        if (atom != JS_ATOM_NULL) {\n            is_enumerable = ((prs->flags & JS_PROP_ENUMERABLE) != 0);\n            kind = JS_AtomGetKind(ctx, atom);\n            if ((!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) &&\n                ((flags >> kind) & 1) != 0) {\n                if (JS_AtomIsArrayIndex(ctx, &num_key, atom)) {\n                    j = num_index++;\n                    num_sorted = FALSE;\n                } else if (kind == JS_ATOM_KIND_STRING) {\n                    j = str_index++;\n                } else {\n                    j = sym_index++;\n                }\n                tab_atom[j].atom = JS_DupAtom(ctx, atom);\n                tab_atom[j].is_enumerable = is_enumerable;\n            }\n        }\n    }\n\n    if (p->is_exotic) {\n        int len;\n        if (p->fast_array) {\n            if (flags & JS_GPN_STRING_MASK) {\n                len = p->u.array.count;\n                goto add_array_keys;\n            }\n        } else if (p->class_id == JS_CLASS_STRING) {\n            if (flags & JS_GPN_STRING_MASK) {\n                len = js_string_obj_get_length(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n            add_array_keys:\n                for(i = 0; i < len; i++) {\n                    tab_atom[num_index].atom = __JS_AtomFromUInt32(i);\n                    if (tab_atom[num_index].atom == JS_ATOM_NULL) {\n                        js_free_prop_enum(ctx, tab_atom, num_index);\n                        return -1;\n                    }\n                    tab_atom[num_index].is_enumerable = TRUE;\n                    num_index++;\n                }\n            }\n        } else {\n            /* Note: exotic keys are not reordered and comes after the object own properties. */\n            for(i = 0; i < exotic_count; i++) {\n                atom = tab_exotic[i].atom;\n                is_enumerable = tab_exotic[i].is_enumerable;\n                kind = JS_AtomGetKind(ctx, atom);\n                if ((!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) &&\n                    ((flags >> kind) & 1) != 0) {\n                    tab_atom[sym_index].atom = atom;\n                    tab_atom[sym_index].is_enumerable = is_enumerable;\n                    sym_index++;\n                } else {\n                    JS_FreeAtom(ctx, atom);\n                }\n            }\n            js_free(ctx, tab_exotic);\n        }\n    }\n\n    assert(num_index == num_keys_count);\n    assert(str_index == num_keys_count + str_keys_count);\n    assert(sym_index == atom_count);\n\n    if (num_keys_count != 0 && !num_sorted) {\n        rqsort(tab_atom, num_keys_count, sizeof(tab_atom[0]), num_keys_cmp,\n               ctx);\n    }\n    *ptab = tab_atom;\n    *plen = atom_count;\n    return 0;\n}\n\nint JS_GetOwnPropertyNames(JSContext *ctx, JSPropertyEnum **ptab,\n                           uint32_t *plen, JSValueConst obj, int flags)\n{\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        return -1;\n    }\n    return JS_GetOwnPropertyNamesInternal(ctx, ptab, plen,\n                                          JS_VALUE_GET_OBJ(obj), flags);\n}\n\n/* Return -1 if exception,\n   FALSE if the property does not exist, TRUE if it exists. If TRUE is\n   returned, the property descriptor 'desc' is filled present. */\nstatic int JS_GetOwnPropertyInternal(JSContext *ctx, JSPropertyDescriptor *desc,\n                                     JSObject *p, JSAtom prop)\n{\n    JSShapeProperty *prs;\n    JSProperty *pr;\n\nretry:\n    prs = find_own_property(&pr, p, prop);\n    if (prs) {\n        if (desc) {\n            desc->flags = prs->flags & JS_PROP_C_W_E;\n            desc->getter = JS_UNDEFINED;\n            desc->setter = JS_UNDEFINED;\n            desc->value = JS_UNDEFINED;\n            if (unlikely(prs->flags & JS_PROP_TMASK)) {\n                if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {\n                    desc->flags |= JS_PROP_GETSET;\n                    if (pr->u.getset.getter)\n                        desc->getter = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter));\n                    if (pr->u.getset.setter)\n                        desc->setter = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter));\n                } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n                    JSValue val = *pr->u.var_ref->pvalue;\n                    if (unlikely(JS_IsUninitialized(val))) {\n                        JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);\n                        return -1;\n                    }\n                    desc->value = JS_DupValue(ctx, val);\n                } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n                    /* Instantiate property and retry */\n                    if (JS_AutoInitProperty(ctx, p, prop, pr, prs))\n                        return -1;\n                    goto retry;\n                }\n            } else {\n                desc->value = JS_DupValue(ctx, pr->u.value);\n            }\n        } else {\n            /* for consistency, send the exception even if desc is NULL */\n            if (unlikely((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF)) {\n                if (unlikely(JS_IsUninitialized(*pr->u.var_ref->pvalue))) {\n                    JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);\n                    return -1;\n                }\n            } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n                /* nothing to do: delay instantiation until actual value and/or attributes are read */\n            }\n        }\n        return TRUE;\n    }\n    if (p->is_exotic) {\n        if (p->fast_array) {\n            /* specific case for fast arrays */\n            if (__JS_AtomIsTaggedInt(prop)) {\n                uint32_t idx;\n                idx = __JS_AtomToUInt32(prop);\n                if (idx < p->u.array.count) {\n                    if (desc) {\n                        desc->flags = JS_PROP_WRITABLE | JS_PROP_ENUMERABLE |\n                            JS_PROP_CONFIGURABLE;\n                        desc->getter = JS_UNDEFINED;\n                        desc->setter = JS_UNDEFINED;\n                        desc->value = JS_GetPropertyUint32(ctx, JS_MKPTR(JS_TAG_OBJECT, p), idx);\n                    }\n                    return TRUE;\n                }\n            }\n        } else {\n            const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;\n            if (em && em->get_own_property) {\n                return em->get_own_property(ctx, desc,\n                                            JS_MKPTR(JS_TAG_OBJECT, p), prop);\n            }\n        }\n    }\n    return FALSE;\n}\n\nint JS_GetOwnProperty(JSContext *ctx, JSPropertyDescriptor *desc,\n                      JSValueConst obj, JSAtom prop)\n{\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        return -1;\n    }\n    return JS_GetOwnPropertyInternal(ctx, desc, JS_VALUE_GET_OBJ(obj), prop);\n}\n\n/* return -1 if exception (Proxy object only) or TRUE/FALSE */\nint JS_IsExtensible(JSContext *ctx, JSValueConst obj)\n{\n    JSObject *p;\n\n    if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT))\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(obj);\n    if (unlikely(p->class_id == JS_CLASS_PROXY))\n        return js_proxy_isExtensible(ctx, obj);\n    else\n        return p->extensible;\n}\n\n/* return -1 if exception (Proxy object only) or TRUE/FALSE */\nint JS_PreventExtensions(JSContext *ctx, JSValueConst obj)\n{\n    JSObject *p;\n\n    if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT))\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(obj);\n    if (unlikely(p->class_id == JS_CLASS_PROXY))\n        return js_proxy_preventExtensions(ctx, obj);\n    p->extensible = FALSE;\n    return TRUE;\n}\n\n/* return -1 if exception otherwise TRUE or FALSE */\nint JS_HasProperty(JSContext *ctx, JSValueConst obj, JSAtom prop)\n{\n    JSObject *p;\n    int ret;\n    JSValue obj1;\n\n    if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT))\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(obj);\n    for(;;) {\n        if (p->is_exotic) {\n            const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;\n            if (em && em->has_property) {\n                /* has_property can free the prototype */\n                obj1 = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n                ret = em->has_property(ctx, obj1, prop);\n                JS_FreeValue(ctx, obj1);\n                return ret;\n            }\n        }\n        /* JS_GetOwnPropertyInternal can free the prototype */\n        JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n        ret = JS_GetOwnPropertyInternal(ctx, NULL, p, prop);\n        JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n        if (ret != 0)\n            return ret;\n        if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n            p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n            ret = JS_AtomIsNumericIndex(ctx, prop);\n            if (ret != 0) {\n                if (ret < 0)\n                    return -1;\n                return FALSE;\n            }\n        }\n        p = p->shape->proto;\n        if (!p)\n            break;\n    }\n    return FALSE;\n}\n\n/* val must be a symbol */\nstatic JSAtom js_symbol_to_atom(JSContext *ctx, JSValue val)\n{\n    JSAtomStruct *p = JS_VALUE_GET_PTR(val);\n    return js_get_atom_index(ctx->rt, p);\n}\n\n/* return JS_ATOM_NULL in case of exception */\nJSAtom JS_ValueToAtom(JSContext *ctx, JSValueConst val)\n{\n    JSAtom atom;\n    uint32_t tag;\n    tag = JS_VALUE_GET_TAG(val);\n    if (tag == JS_TAG_INT &&\n        (uint32_t)JS_VALUE_GET_INT(val) <= JS_ATOM_MAX_INT) {\n        /* fast path for integer values */\n        atom = __JS_AtomFromUInt32(JS_VALUE_GET_INT(val));\n    } else if (tag == JS_TAG_SYMBOL) {\n        JSAtomStruct *p = JS_VALUE_GET_PTR(val);\n        atom = JS_DupAtom(ctx, js_get_atom_index(ctx->rt, p));\n    } else {\n        JSValue str;\n        str = JS_ToPropertyKey(ctx, val);\n        if (JS_IsException(str))\n            return JS_ATOM_NULL;\n        if (JS_VALUE_GET_TAG(str) == JS_TAG_SYMBOL) {\n            atom = js_symbol_to_atom(ctx, str);\n        } else {\n            atom = JS_NewAtomStr(ctx, JS_VALUE_GET_STRING(str));\n        }\n    }\n    return atom;\n}\n\nstatic JSValue JS_GetPropertyValue(JSContext *ctx, JSValueConst this_obj,\n                                   JSValue prop)\n{\n    JSAtom atom;\n    JSValue ret;\n\n    if (likely(JS_VALUE_GET_TAG(this_obj) == JS_TAG_OBJECT &&\n               JS_VALUE_GET_TAG(prop) == JS_TAG_INT)) {\n        JSObject *p;\n        uint32_t idx, len;\n        /* fast path for array access */\n        p = JS_VALUE_GET_OBJ(this_obj);\n        idx = JS_VALUE_GET_INT(prop);\n        len = (uint32_t)p->u.array.count;\n        if (unlikely(idx >= len))\n            goto slow_path;\n        switch(p->class_id) {\n        case JS_CLASS_ARRAY:\n        case JS_CLASS_ARGUMENTS:\n            return JS_DupValue(ctx, p->u.array.u.values[idx]);\n        case JS_CLASS_INT8_ARRAY:\n            return JS_NewInt32(ctx, p->u.array.u.int8_ptr[idx]);\n        case JS_CLASS_UINT8C_ARRAY:\n        case JS_CLASS_UINT8_ARRAY:\n            return JS_NewInt32(ctx, p->u.array.u.uint8_ptr[idx]);\n        case JS_CLASS_INT16_ARRAY:\n            return JS_NewInt32(ctx, p->u.array.u.int16_ptr[idx]);\n        case JS_CLASS_UINT16_ARRAY:\n            return JS_NewInt32(ctx, p->u.array.u.uint16_ptr[idx]);\n        case JS_CLASS_INT32_ARRAY:\n            return JS_NewInt32(ctx, p->u.array.u.int32_ptr[idx]);\n        case JS_CLASS_UINT32_ARRAY:\n            return JS_NewUint32(ctx, p->u.array.u.uint32_ptr[idx]);\n#ifdef CONFIG_BIGNUM\n        case JS_CLASS_BIG_INT64_ARRAY:\n            return JS_NewBigInt64(ctx, p->u.array.u.int64_ptr[idx]);\n        case JS_CLASS_BIG_UINT64_ARRAY:\n            return JS_NewBigUint64(ctx, p->u.array.u.uint64_ptr[idx]);\n#endif\n        case JS_CLASS_FLOAT32_ARRAY:\n            return __JS_NewFloat64(ctx, p->u.array.u.float_ptr[idx]);\n        case JS_CLASS_FLOAT64_ARRAY:\n            return __JS_NewFloat64(ctx, p->u.array.u.double_ptr[idx]);\n        default:\n            goto slow_path;\n        }\n    } else {\n    slow_path:\n        atom = JS_ValueToAtom(ctx, prop);\n        JS_FreeValue(ctx, prop);\n        if (unlikely(atom == JS_ATOM_NULL))\n            return JS_EXCEPTION;\n        ret = JS_GetProperty(ctx, this_obj, atom);\n        JS_FreeAtom(ctx, atom);\n        return ret;\n    }\n}\n\nJSValue JS_GetPropertyUint32(JSContext *ctx, JSValueConst this_obj,\n                             uint32_t idx)\n{\n    return JS_GetPropertyValue(ctx, this_obj, JS_NewUint32(ctx, idx));\n}\n\n/* Check if an object has a generalized numeric property. Return value:\n   -1 for exception,\n   TRUE if property exists, stored into *pval,\n   FALSE if proprty does not exist.\n */\nstatic int JS_TryGetPropertyInt64(JSContext *ctx, JSValueConst obj, int64_t idx, JSValue *pval)\n{\n    JSValue val = JS_UNDEFINED;\n    JSAtom prop;\n    int present;\n\n    if (likely((uint64_t)idx <= JS_ATOM_MAX_INT)) {\n        /* fast path */\n        present = JS_HasProperty(ctx, obj, __JS_AtomFromUInt32(idx));\n        if (present > 0) {\n            val = JS_GetPropertyValue(ctx, obj, JS_NewInt32(ctx, idx));\n            if (unlikely(JS_IsException(val)))\n                present = -1;\n        }\n    } else {\n        prop = JS_NewAtomInt64(ctx, idx);\n        present = -1;\n        if (likely(prop != JS_ATOM_NULL)) {\n            present = JS_HasProperty(ctx, obj, prop);\n            if (present > 0) {\n                val = JS_GetProperty(ctx, obj, prop);\n                if (unlikely(JS_IsException(val)))\n                    present = -1;\n            }\n            JS_FreeAtom(ctx, prop);\n        }\n    }\n    *pval = val;\n    return present;\n}\n\nstatic JSValue JS_GetPropertyInt64(JSContext *ctx, JSValueConst obj, int64_t idx)\n{\n    JSAtom prop;\n    JSValue val;\n\n    if ((uint64_t)idx <= INT32_MAX) {\n        /* fast path for fast arrays */\n        return JS_GetPropertyValue(ctx, obj, JS_NewInt32(ctx, idx));\n    }\n    prop = JS_NewAtomInt64(ctx, idx);\n    if (prop == JS_ATOM_NULL)\n        return JS_EXCEPTION;\n\n    val = JS_GetProperty(ctx, obj, prop);\n    JS_FreeAtom(ctx, prop);\n    return val;\n}\n\nJSValue JS_GetPropertyStr(JSContext *ctx, JSValueConst this_obj,\n                          const char *prop)\n{\n    JSAtom atom;\n    JSValue ret;\n    atom = JS_NewAtom(ctx, prop);\n    ret = JS_GetProperty(ctx, this_obj, atom);\n    JS_FreeAtom(ctx, atom);\n    return ret;\n}\n\n/* Note: the property value is not initialized. Return NULL if memory\n   error. */\nstatic JSProperty *add_property(JSContext *ctx,\n                                JSObject *p, JSAtom prop, int prop_flags)\n{\n    JSShape *sh, *new_sh;\n\n    sh = p->shape;\n    if (sh->is_hashed) {\n        /* try to find an existing shape */\n        new_sh = find_hashed_shape_prop(ctx->rt, sh, prop, prop_flags);\n        if (new_sh) {\n            /* matching shape found: use it */\n            /*  the property array may need to be resized */\n            if (new_sh->prop_size != sh->prop_size) {\n                JSProperty *new_prop;\n                new_prop = js_realloc(ctx, p->prop, sizeof(p->prop[0]) *\n                                      new_sh->prop_size);\n                if (!new_prop)\n                    return NULL;\n                p->prop = new_prop;\n            }\n            p->shape = js_dup_shape(new_sh);\n            js_free_shape(ctx->rt, sh);\n            return &p->prop[new_sh->prop_count - 1];\n        } else if (sh->header.ref_count != 1) {\n            /* if the shape is shared, clone it */\n            new_sh = js_clone_shape(ctx, sh);\n            if (!new_sh)\n                return NULL;\n            /* hash the cloned shape */\n            new_sh->is_hashed = TRUE;\n            js_shape_hash_link(ctx->rt, new_sh);\n            js_free_shape(ctx->rt, p->shape);\n            p->shape = new_sh;\n        }\n    }\n    assert(p->shape->header.ref_count == 1);\n    if (add_shape_property(ctx, &p->shape, p, prop, prop_flags))\n        return NULL;\n    return &p->prop[p->shape->prop_count - 1];\n}\n\n/* can be called on Array or Arguments objects. return < 0 if\n   memory alloc error. */\nstatic no_inline __exception int convert_fast_array_to_array(JSContext *ctx,\n                                                             JSObject *p)\n{\n    JSProperty *pr;\n    JSShape *sh;\n    JSValue *tab;\n    uint32_t i, len, new_count;\n\n    if (js_shape_prepare_update(ctx, p, NULL))\n        return -1;\n    len = p->u.array.count;\n    /* resize the properties once to simplify the error handling */\n    sh = p->shape;\n    new_count = sh->prop_count + len;\n    if (new_count > sh->prop_size) {\n        if (resize_properties(ctx, &p->shape, p, new_count))\n            return -1;\n    }\n\n    tab = p->u.array.u.values;\n    for(i = 0; i < len; i++) {\n        /* add_property cannot fail here but\n           __JS_AtomFromUInt32(i) fails for i > INT32_MAX */\n        pr = add_property(ctx, p, __JS_AtomFromUInt32(i), JS_PROP_C_W_E);\n        pr->u.value = *tab++;\n    }\n    js_free(ctx, p->u.array.u.values);\n    p->u.array.count = 0;\n    p->u.array.u.values = NULL; /* fail safe */\n    p->u.array.u1.size = 0;\n    p->fast_array = 0;\n    return 0;\n}\n\nstatic int delete_property(JSContext *ctx, JSObject *p, JSAtom atom)\n{\n    JSShape *sh;\n    JSShapeProperty *pr, *lpr, *prop;\n    JSProperty *pr1;\n    uint32_t lpr_idx;\n    intptr_t h, h1;\n\n redo:\n    sh = p->shape;\n    h1 = atom & sh->prop_hash_mask;\n    h = prop_hash_end(sh)[-h1 - 1];\n    prop = get_shape_prop(sh);\n    lpr = NULL;\n    lpr_idx = 0;   /* prevent warning */\n    while (h != 0) {\n        pr = &prop[h - 1];\n        if (likely(pr->atom == atom)) {\n            /* found ! */\n            if (!(pr->flags & JS_PROP_CONFIGURABLE))\n                return FALSE;\n            /* realloc the shape if needed */\n            if (lpr)\n                lpr_idx = lpr - get_shape_prop(sh);\n            if (js_shape_prepare_update(ctx, p, &pr))\n                return -1;\n            sh = p->shape;\n            /* remove property */\n            if (lpr) {\n                lpr = get_shape_prop(sh) + lpr_idx;\n                lpr->hash_next = pr->hash_next;\n            } else {\n                prop_hash_end(sh)[-h1 - 1] = pr->hash_next;\n            }\n            sh->deleted_prop_count++;\n            /* free the entry */\n            pr1 = &p->prop[h - 1];\n            free_property(ctx->rt, pr1, pr->flags);\n            JS_FreeAtom(ctx, pr->atom);\n            /* put default values */\n            pr->flags = 0;\n            pr->atom = JS_ATOM_NULL;\n            pr1->u.value = JS_UNDEFINED;\n\n            /* compact the properties if too many deleted properties */\n            if (sh->deleted_prop_count >= 8 &&\n                sh->deleted_prop_count >= ((unsigned)sh->prop_count / 2)) {\n                compact_properties(ctx, p);\n            }\n            return TRUE;\n        }\n        lpr = pr;\n        h = pr->hash_next;\n    }\n\n    if (p->is_exotic) {\n        if (p->fast_array) {\n            uint32_t idx;\n            if (JS_AtomIsArrayIndex(ctx, &idx, atom) &&\n                idx < p->u.array.count) {\n                if (p->class_id == JS_CLASS_ARRAY ||\n                    p->class_id == JS_CLASS_ARGUMENTS) {\n                    /* Special case deleting the last element of a fast Array */\n                    if (idx == p->u.array.count - 1) {\n                        JS_FreeValue(ctx, p->u.array.u.values[idx]);\n                        p->u.array.count = idx;\n                        return TRUE;\n                    }\n                    if (convert_fast_array_to_array(ctx, p))\n                        return -1;\n                    goto redo;\n                } else {\n                    return FALSE;\n                }\n            }\n        } else {\n            const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;\n            if (em && em->delete_property) {\n                return em->delete_property(ctx, JS_MKPTR(JS_TAG_OBJECT, p), atom);\n            }\n        }\n    }\n    /* not found */\n    return TRUE;\n}\n\nstatic int call_setter(JSContext *ctx, JSObject *setter,\n                       JSValueConst this_obj, JSValue val, int flags)\n{\n    JSValue ret, func;\n    if (likely(setter)) {\n        func = JS_MKPTR(JS_TAG_OBJECT, setter);\n        /* Note: the field could be removed in the setter */\n        func = JS_DupValue(ctx, func);\n        ret = JS_CallFree(ctx, func, this_obj, 1, (JSValueConst *)&val);\n        JS_FreeValue(ctx, val);\n        if (JS_IsException(ret))\n            return -1;\n        JS_FreeValue(ctx, ret);\n        return TRUE;\n    } else {\n        JS_FreeValue(ctx, val);\n        if ((flags & JS_PROP_THROW) ||\n            ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) {\n            JS_ThrowTypeError(ctx, \"no setter for property\");\n            return -1;\n        }\n        return FALSE;\n    }\n}\n\n/* set the array length and remove the array elements if necessary. */\nstatic int set_array_length(JSContext *ctx, JSObject *p, JSValue val,\n                            int flags)\n{\n    uint32_t len, idx, cur_len;\n    int i, ret;\n\n    /* Note: this call can reallocate the properties of 'p' */\n    ret = JS_ToArrayLengthFree(ctx, &len, val, FALSE);\n    if (ret)\n        return -1;\n    /* JS_ToArrayLengthFree() must be done before the read-only test */\n    if (unlikely(!(p->shape->prop[0].flags & JS_PROP_WRITABLE)))\n        return JS_ThrowTypeErrorReadOnly(ctx, flags, JS_ATOM_length);\n\n    if (likely(p->fast_array)) {\n        uint32_t old_len = p->u.array.count;\n        if (len < old_len) {\n            for(i = len; i < old_len; i++) {\n                JS_FreeValue(ctx, p->u.array.u.values[i]);\n            }\n            p->u.array.count = len;\n        }\n        p->prop[0].u.value = JS_NewUint32(ctx, len);\n    } else {\n        /* Note: length is always a uint32 because the object is an\n           array */\n        JS_ToUint32(ctx, &cur_len, p->prop[0].u.value);\n        if (len < cur_len) {\n            uint32_t d;\n            JSShape *sh;\n            JSShapeProperty *pr;\n\n            d = cur_len - len;\n            sh = p->shape;\n            if (d <= sh->prop_count) {\n                JSAtom atom;\n\n                /* faster to iterate */\n                while (cur_len > len) {\n                    atom = JS_NewAtomUInt32(ctx, cur_len - 1);\n                    ret = delete_property(ctx, p, atom);\n                    JS_FreeAtom(ctx, atom);\n                    if (unlikely(!ret)) {\n                        /* unlikely case: property is not\n                           configurable */\n                        break;\n                    }\n                    cur_len--;\n                }\n            } else {\n                /* faster to iterate thru all the properties. Need two\n                   passes in case one of the property is not\n                   configurable */\n                cur_len = len;\n                for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count;\n                    i++, pr++) {\n                    if (pr->atom != JS_ATOM_NULL &&\n                        JS_AtomIsArrayIndex(ctx, &idx, pr->atom)) {\n                        if (idx >= cur_len &&\n                            !(pr->flags & JS_PROP_CONFIGURABLE)) {\n                            cur_len = idx + 1;\n                        }\n                    }\n                }\n\n                for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count;\n                    i++, pr++) {\n                    if (pr->atom != JS_ATOM_NULL &&\n                        JS_AtomIsArrayIndex(ctx, &idx, pr->atom)) {\n                        if (idx >= cur_len) {\n                            /* remove the property */\n                            delete_property(ctx, p, pr->atom);\n                            /* WARNING: the shape may have been modified */\n                            sh = p->shape;\n                            pr = get_shape_prop(sh) + i;\n                        }\n                    }\n                }\n            }\n        } else {\n            cur_len = len;\n        }\n        set_value(ctx, &p->prop[0].u.value, JS_NewUint32(ctx, cur_len));\n        if (unlikely(cur_len > len)) {\n            return JS_ThrowTypeErrorOrFalse(ctx, flags, \"not configurable\");\n        }\n    }\n    return TRUE;\n}\n\n/* return -1 if exception */\nstatic int expand_fast_array(JSContext *ctx, JSObject *p, uint32_t new_len)\n{\n    uint32_t new_size;\n    size_t slack;\n    JSValue *new_array_prop;\n    /* XXX: potential arithmetic overflow */\n    new_size = max_int(new_len, p->u.array.u1.size * 3 / 2);\n    new_array_prop = js_realloc2(ctx, p->u.array.u.values, sizeof(JSValue) * new_size, &slack);\n    if (!new_array_prop)\n        return -1;\n    new_size += slack / sizeof(*new_array_prop);\n    p->u.array.u.values = new_array_prop;\n    p->u.array.u1.size = new_size;\n    return 0;\n}\n\n/* Preconditions: 'p' must be of class JS_CLASS_ARRAY, p->fast_array =\n   TRUE and p->extensible = TRUE */\nstatic int add_fast_array_element(JSContext *ctx, JSObject *p,\n                                  JSValue val, int flags)\n{\n    uint32_t new_len, array_len;\n    /* extend the array by one */\n    /* XXX: convert to slow array if new_len > 2^31-1 elements */\n    new_len = p->u.array.count + 1;\n    /* update the length if necessary. We assume that if the length is\n       not an integer, then if it >= 2^31.  */\n    if (likely(JS_VALUE_GET_TAG(p->prop[0].u.value) == JS_TAG_INT)) {\n        array_len = JS_VALUE_GET_INT(p->prop[0].u.value);\n        if (new_len > array_len) {\n            if (unlikely(!(get_shape_prop(p->shape)->flags & JS_PROP_WRITABLE))) {\n                JS_FreeValue(ctx, val);\n                return JS_ThrowTypeErrorReadOnly(ctx, flags, JS_ATOM_length);\n            }\n            p->prop[0].u.value = JS_NewInt32(ctx, new_len);\n        }\n    }\n    if (unlikely(new_len > p->u.array.u1.size)) {\n        if (expand_fast_array(ctx, p, new_len)) {\n            JS_FreeValue(ctx, val);\n            return -1;\n        }\n    }\n    p->u.array.u.values[new_len - 1] = val;\n    p->u.array.count = new_len;\n    return TRUE;\n}\n\nstatic void js_free_desc(JSContext *ctx, JSPropertyDescriptor *desc)\n{\n    JS_FreeValue(ctx, desc->getter);\n    JS_FreeValue(ctx, desc->setter);\n    JS_FreeValue(ctx, desc->value);\n}\n\n/* generic (and slower) version of JS_SetProperty() for\n * Reflect.set(). 'obj' must be an object.  */\nstatic int JS_SetPropertyGeneric(JSContext *ctx,\n                                 JSValueConst obj, JSAtom prop,\n                                 JSValue val, JSValueConst this_obj,\n                                 int flags)\n{\n    int ret;\n    JSPropertyDescriptor desc;\n    JSValue obj1;\n    JSObject *p;\n    \n    obj1 = JS_DupValue(ctx, obj);\n    for(;;) {\n        p = JS_VALUE_GET_OBJ(obj1);\n        if (p->is_exotic) {\n            const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;\n            if (em && em->set_property) {\n                ret = em->set_property(ctx, obj1, prop,\n                                       val, this_obj, flags);\n                JS_FreeValue(ctx, obj1);\n                JS_FreeValue(ctx, val);\n                return ret;\n            }\n        }\n\n        ret = JS_GetOwnPropertyInternal(ctx, &desc, p, prop);\n        if (ret < 0) {\n            JS_FreeValue(ctx, obj1);\n            JS_FreeValue(ctx, val);\n            return ret;\n        }\n        if (ret) {\n            if (desc.flags & JS_PROP_GETSET) {\n                JSObject *setter;\n                if (JS_IsUndefined(desc.setter))\n                    setter = NULL;\n                else\n                    setter = JS_VALUE_GET_OBJ(desc.setter);\n                ret = call_setter(ctx, setter, this_obj, val, flags);\n                JS_FreeValue(ctx, desc.getter);\n                JS_FreeValue(ctx, desc.setter);\n                JS_FreeValue(ctx, obj1);\n                return ret;\n            } else {\n                JS_FreeValue(ctx, desc.value);\n                if (!(desc.flags & JS_PROP_WRITABLE)) {\n                    JS_FreeValue(ctx, obj1);\n                    goto read_only_error;\n                }\n            }\n            break;\n        }\n        /* Note: at this point 'obj1' cannot be a proxy. XXX: may have\n           to check recursion */\n        obj1 = JS_GetPrototypeFree(ctx, obj1);\n        if (JS_IsNull(obj1))\n            break;\n    }\n    JS_FreeValue(ctx, obj1);\n\n    if (!JS_IsObject(this_obj)) {\n        JS_FreeValue(ctx, val);\n        return JS_ThrowTypeErrorOrFalse(ctx, flags, \"receiver is not an object\");\n    }\n    \n    p = JS_VALUE_GET_OBJ(this_obj);\n\n    /* modify the property in this_obj if it already exists */\n    ret = JS_GetOwnPropertyInternal(ctx, &desc, p, prop);\n    if (ret < 0) {\n        JS_FreeValue(ctx, val);\n        return ret;\n    }\n    if (ret) {\n        if (desc.flags & JS_PROP_GETSET) {\n            JS_FreeValue(ctx, desc.getter);\n            JS_FreeValue(ctx, desc.setter);\n            JS_FreeValue(ctx, val);\n            return JS_ThrowTypeErrorOrFalse(ctx, flags, \"setter is forbidden\");\n        } else {\n            JS_FreeValue(ctx, desc.value);\n            if (!(desc.flags & JS_PROP_WRITABLE) ||\n                p->class_id == JS_CLASS_MODULE_NS) {\n            read_only_error:\n                JS_FreeValue(ctx, val);\n                return JS_ThrowTypeErrorReadOnly(ctx, flags, prop);\n            }\n        }\n        ret = JS_DefineProperty(ctx, this_obj, prop, val,\n                                JS_UNDEFINED, JS_UNDEFINED,\n                                JS_PROP_HAS_VALUE);\n        JS_FreeValue(ctx, val);\n        return ret;\n    }\n\n    ret = JS_CreateProperty(ctx, p, prop, val, JS_UNDEFINED, JS_UNDEFINED,\n                            flags |\n                            JS_PROP_HAS_VALUE |\n                            JS_PROP_HAS_ENUMERABLE |\n                            JS_PROP_HAS_WRITABLE |\n                            JS_PROP_HAS_CONFIGURABLE |\n                            JS_PROP_C_W_E);\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\n/* return -1 in case of exception or TRUE or FALSE. Warning: 'val' is\n   freed by the function. 'flags' is a bitmask of JS_PROP_NO_ADD,\n   JS_PROP_THROW or JS_PROP_THROW_STRICT. If JS_PROP_NO_ADD is set,\n   the new property is not added and an error is raised. */\nint JS_SetPropertyInternal(JSContext *ctx, JSValueConst this_obj,\n                           JSAtom prop, JSValue val, int flags)\n{\n    JSObject *p, *p1;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    uint32_t tag;\n    JSPropertyDescriptor desc;\n    int ret;\n#if 0\n    printf(\"JS_SetPropertyInternal: \"); print_atom(ctx, prop); printf(\"\\n\");\n#endif\n    tag = JS_VALUE_GET_TAG(this_obj);\n    if (unlikely(tag != JS_TAG_OBJECT)) {\n        switch(tag) {\n        case JS_TAG_NULL:\n            JS_FreeValue(ctx, val);\n            JS_ThrowTypeErrorAtom(ctx, \"cannot set property '%s' of null\", prop);\n            return -1;\n        case JS_TAG_UNDEFINED:\n            JS_FreeValue(ctx, val);\n            JS_ThrowTypeErrorAtom(ctx, \"cannot set property '%s' of undefined\", prop);\n            return -1;\n        default:\n            /* even on a primitive type we can have setters on the prototype */\n            p = NULL;\n            p1 = JS_VALUE_GET_OBJ(JS_GetPrototypePrimitive(ctx, this_obj));\n            goto prototype_lookup;\n        }\n    }\n    p = JS_VALUE_GET_OBJ(this_obj);\nretry:\n    prs = find_own_property(&pr, p, prop);\n    if (prs) {\n        if (likely((prs->flags & (JS_PROP_TMASK | JS_PROP_WRITABLE |\n                                  JS_PROP_LENGTH)) == JS_PROP_WRITABLE)) {\n            /* fast case */\n            set_value(ctx, &pr->u.value, val);\n            return TRUE;\n        } else if (prs->flags & JS_PROP_LENGTH) {\n            assert(p->class_id == JS_CLASS_ARRAY);\n            assert(prop == JS_ATOM_length);\n            return set_array_length(ctx, p, val, flags);\n        } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {\n            return call_setter(ctx, pr->u.getset.setter, this_obj, val, flags);\n        } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n            /* JS_PROP_WRITABLE is always true for variable\n               references, but they are write protected in module name\n               spaces. */\n            if (p->class_id == JS_CLASS_MODULE_NS)\n                goto read_only_prop;\n            set_value(ctx, pr->u.var_ref->pvalue, val);\n            return TRUE;\n        } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n            /* Instantiate property and retry (potentially useless) */\n            if (JS_AutoInitProperty(ctx, p, prop, pr, prs)) {\n                JS_FreeValue(ctx, val);\n                return -1;\n            }\n            goto retry;\n        } else {\n            goto read_only_prop;\n        }\n    }\n\n    p1 = p;\n    for(;;) {\n        if (p1->is_exotic) {\n            if (p1->fast_array) {\n                if (__JS_AtomIsTaggedInt(prop)) {\n                    uint32_t idx = __JS_AtomToUInt32(prop);\n                    if (idx < p1->u.array.count) {\n                        if (unlikely(p == p1))\n                            return JS_SetPropertyValue(ctx, this_obj, JS_NewInt32(ctx, idx), val, flags);\n                        else\n                            break;\n                    } else if (p1->class_id >= JS_CLASS_UINT8C_ARRAY &&\n                               p1->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n                        goto typed_array_oob;\n                    }\n                } else if (p1->class_id >= JS_CLASS_UINT8C_ARRAY &&\n                           p1->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n                    ret = JS_AtomIsNumericIndex(ctx, prop);\n                    if (ret != 0) {\n                        if (ret < 0) {\n                            JS_FreeValue(ctx, val);\n                            return -1;\n                        }\n                    typed_array_oob:\n                        val = JS_ToNumberFree(ctx, val);\n                        JS_FreeValue(ctx, val);\n                        if (JS_IsException(val))\n                            return -1;\n#ifdef JSB_TYPED_ARRAY_NO_THROW\n                        return TRUE;\n#else                        \n                        return JS_ThrowTypeErrorOrFalse(ctx, flags, \"out-of-bound numeric index\");\n#endif\n                    }\n                }\n            } else {\n                const JSClassExoticMethods *em = ctx->rt->class_array[p1->class_id].exotic;\n                if (em) {\n                    JSValue obj1;\n                    if (em->set_property) {\n                        /* set_property can free the prototype */\n                        obj1 = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p1));\n                        ret = em->set_property(ctx, obj1, prop,\n                                               val, this_obj, flags);\n                        JS_FreeValue(ctx, obj1);\n                        JS_FreeValue(ctx, val);\n                        return ret;\n                    }\n                    if (em->get_own_property) {\n                        /* get_own_property can free the prototype */\n                        obj1 = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p1));\n                        ret = em->get_own_property(ctx, &desc,\n                                                   obj1, prop);\n                        JS_FreeValue(ctx, obj1);\n                        if (ret < 0) {\n                            JS_FreeValue(ctx, val);\n                            return ret;\n                        }\n                        if (ret) {\n                            if (desc.flags & JS_PROP_GETSET) {\n                                JSObject *setter;\n                                if (JS_IsUndefined(desc.setter))\n                                    setter = NULL;\n                                else\n                                    setter = JS_VALUE_GET_OBJ(desc.setter);\n                                ret = call_setter(ctx, setter, this_obj, val, flags);\n                                JS_FreeValue(ctx, desc.getter);\n                                JS_FreeValue(ctx, desc.setter);\n                                return ret;\n                            } else {\n                                JS_FreeValue(ctx, desc.value);\n                                if (!(desc.flags & JS_PROP_WRITABLE))\n                                    goto read_only_prop;\n                                if (likely(p == p1)) {\n                                    ret = JS_DefineProperty(ctx, this_obj, prop, val,\n                                                            JS_UNDEFINED, JS_UNDEFINED,\n                                                            JS_PROP_HAS_VALUE);\n                                    JS_FreeValue(ctx, val);\n                                    return ret;\n                                } else {\n                                    break;\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        p1 = p1->shape->proto;\n    prototype_lookup:\n        if (!p1)\n            break;\n\n    retry2:\n        prs = find_own_property(&pr, p1, prop);\n        if (prs) {\n            if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {\n                return call_setter(ctx, pr->u.getset.setter, this_obj, val, flags);\n            } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n                /* Instantiate property and retry (potentially useless) */\n                if (JS_AutoInitProperty(ctx, p1, prop, pr, prs))\n                    return -1;\n                goto retry2;\n            } else if (!(prs->flags & JS_PROP_WRITABLE)) {\n            read_only_prop:\n                JS_FreeValue(ctx, val);\n                return JS_ThrowTypeErrorReadOnly(ctx, flags, prop);\n            }\n        }\n    }\n\n    if (unlikely(flags & JS_PROP_NO_ADD)) {\n        JS_FreeValue(ctx, val);\n        JS_ThrowReferenceErrorNotDefined(ctx, prop);\n        return -1;\n    }\n\n    if (unlikely(!p)) {\n        JS_FreeValue(ctx, val);\n        return JS_ThrowTypeErrorOrFalse(ctx, flags, \"not an object\");\n    }\n\n    if (unlikely(!p->extensible)) {\n        JS_FreeValue(ctx, val);\n        return JS_ThrowTypeErrorOrFalse(ctx, flags, \"object is not extensible\");\n    }\n\n    if (p->is_exotic) {\n        if (p->class_id == JS_CLASS_ARRAY && p->fast_array &&\n            __JS_AtomIsTaggedInt(prop)) {\n            uint32_t idx = __JS_AtomToUInt32(prop);\n            if (idx == p->u.array.count) {\n                /* fast case */\n                return add_fast_array_element(ctx, p, val, flags);\n            } else {\n                goto generic_create_prop;\n            }\n        } else {\n        generic_create_prop:\n            ret = JS_CreateProperty(ctx, p, prop, val, JS_UNDEFINED, JS_UNDEFINED,\n                                    flags |\n                                    JS_PROP_HAS_VALUE |\n                                    JS_PROP_HAS_ENUMERABLE |\n                                    JS_PROP_HAS_WRITABLE |\n                                    JS_PROP_HAS_CONFIGURABLE |\n                                    JS_PROP_C_W_E);\n            JS_FreeValue(ctx, val);\n            return ret;\n        }\n    }\n\n    pr = add_property(ctx, p, prop, JS_PROP_C_W_E);\n    if (unlikely(!pr)) {\n        JS_FreeValue(ctx, val);\n        return -1;\n    }\n    pr->u.value = val;\n    return TRUE;\n}\n\n/* flags can be JS_PROP_THROW or JS_PROP_THROW_STRICT */\nstatic int JS_SetPropertyValue(JSContext *ctx, JSValueConst this_obj,\n                               JSValue prop, JSValue val, int flags)\n{\n    if (likely(JS_VALUE_GET_TAG(this_obj) == JS_TAG_OBJECT &&\n               JS_VALUE_GET_TAG(prop) == JS_TAG_INT)) {\n        JSObject *p;\n        uint32_t idx;\n        double d;\n        int32_t v;\n\n        /* fast path for array access */\n        p = JS_VALUE_GET_OBJ(this_obj);\n        idx = JS_VALUE_GET_INT(prop);\n        switch(p->class_id) {\n        case JS_CLASS_ARRAY:\n            if (unlikely(idx >= (uint32_t)p->u.array.count)) {\n                JSObject *p1;\n                JSShape *sh1;\n\n                /* fast path to add an element to the array */\n                if (idx != (uint32_t)p->u.array.count ||\n                    !p->fast_array || !p->extensible)\n                    goto slow_path;\n                /* check if prototype chain has a numeric property */\n                p1 = p->shape->proto;\n                while (p1 != NULL) {\n                    sh1 = p1->shape;\n                    if (p1->class_id == JS_CLASS_ARRAY) {\n                        if (unlikely(!p1->fast_array))\n                            goto slow_path;\n                    } else if (p1->class_id == JS_CLASS_OBJECT) {\n                        if (unlikely(sh1->has_small_array_index))\n                            goto slow_path;\n                    } else {\n                        goto slow_path;\n                    }\n                    p1 = sh1->proto;\n                }\n                /* add element */\n                return add_fast_array_element(ctx, p, val, flags);\n            }\n            set_value(ctx, &p->u.array.u.values[idx], val);\n            break;\n        case JS_CLASS_ARGUMENTS:\n            if (unlikely(idx >= (uint32_t)p->u.array.count))\n                goto slow_path;\n            set_value(ctx, &p->u.array.u.values[idx], val);\n            break;\n        case JS_CLASS_UINT8C_ARRAY:\n            if (JS_ToUint8ClampFree(ctx, &v, val))\n                return -1;\n            /* Note: the conversion can detach the typed array, so the\n               array bound check must be done after */\n            if (unlikely(idx >= (uint32_t)p->u.array.count))\n                goto ta_out_of_bound;\n            p->u.array.u.uint8_ptr[idx] = v;\n            break;\n        case JS_CLASS_INT8_ARRAY:\n        case JS_CLASS_UINT8_ARRAY:\n            if (JS_ToInt32Free(ctx, &v, val))\n                return -1;\n            if (unlikely(idx >= (uint32_t)p->u.array.count))\n                goto ta_out_of_bound;\n            p->u.array.u.uint8_ptr[idx] = v;\n            break;\n        case JS_CLASS_INT16_ARRAY:\n        case JS_CLASS_UINT16_ARRAY:\n            if (JS_ToInt32Free(ctx, &v, val))\n                return -1;\n            if (unlikely(idx >= (uint32_t)p->u.array.count))\n                goto ta_out_of_bound;\n            p->u.array.u.uint16_ptr[idx] = v;\n            break;\n        case JS_CLASS_INT32_ARRAY:\n        case JS_CLASS_UINT32_ARRAY:\n            if (JS_ToInt32Free(ctx, &v, val))\n                return -1;\n            if (unlikely(idx >= (uint32_t)p->u.array.count))\n                goto ta_out_of_bound;\n            p->u.array.u.uint32_ptr[idx] = v;\n            break;\n#ifdef CONFIG_BIGNUM\n        case JS_CLASS_BIG_INT64_ARRAY:\n        case JS_CLASS_BIG_UINT64_ARRAY:\n            /* XXX: need specific conversion function */\n            {\n                int64_t v;\n                if (JS_ToBigInt64Free(ctx, &v, val))\n                    return -1;\n                if (unlikely(idx >= (uint32_t)p->u.array.count))\n                    goto ta_out_of_bound;\n                p->u.array.u.uint64_ptr[idx] = v;\n            }\n            break;\n#endif\n        case JS_CLASS_FLOAT32_ARRAY:\n            if (JS_ToFloat64Free(ctx, &d, val))\n                return -1;\n            if (unlikely(idx >= (uint32_t)p->u.array.count))\n                goto ta_out_of_bound;\n            p->u.array.u.float_ptr[idx] = d;\n            break;\n        case JS_CLASS_FLOAT64_ARRAY:\n            if (JS_ToFloat64Free(ctx, &d, val))\n                return -1;\n            if (unlikely(idx >= (uint32_t)p->u.array.count)) {\n            ta_out_of_bound:\n#ifdef JSB_TYPED_ARRAY_NO_THROW\n                break;\n#else\n                return JS_ThrowTypeErrorOrFalse(ctx, flags, \"out-of-bound numeric index\");\n#endif\n            }\n            p->u.array.u.double_ptr[idx] = d;\n            break;\n        default:\n            goto slow_path;\n        }\n        return TRUE;\n    } else {\n        JSAtom atom;\n        int ret;\n    slow_path:\n        atom = JS_ValueToAtom(ctx, prop);\n        JS_FreeValue(ctx, prop);\n        if (unlikely(atom == JS_ATOM_NULL)) {\n            JS_FreeValue(ctx, val);\n            return -1;\n        }\n        ret = JS_SetPropertyInternal(ctx, this_obj, atom, val, flags);\n        JS_FreeAtom(ctx, atom);\n        return ret;\n    }\n}\n\nint JS_SetPropertyUint32(JSContext *ctx, JSValueConst this_obj,\n                         uint32_t idx, JSValue val)\n{\n    return JS_SetPropertyValue(ctx, this_obj, JS_NewUint32(ctx, idx), val,\n                               JS_PROP_THROW);\n}\n\nint JS_SetPropertyInt64(JSContext *ctx, JSValueConst this_obj,\n                        int64_t idx, JSValue val)\n{\n    JSAtom prop;\n    int res;\n\n    if ((uint64_t)idx <= INT32_MAX) {\n        /* fast path for fast arrays */\n        return JS_SetPropertyValue(ctx, this_obj, JS_NewInt32(ctx, idx), val,\n                                   JS_PROP_THROW);\n    }\n    prop = JS_NewAtomInt64(ctx, idx);\n    if (prop == JS_ATOM_NULL) {\n        JS_FreeValue(ctx, val);\n        return -1;\n    }\n    res = JS_SetProperty(ctx, this_obj, prop, val);\n    JS_FreeAtom(ctx, prop);\n    return res;\n}\n\nint JS_SetPropertyStr(JSContext *ctx, JSValueConst this_obj,\n                      const char *prop, JSValue val)\n{\n    JSAtom atom;\n    int ret;\n    atom = JS_NewAtom(ctx, prop);\n    ret = JS_SetPropertyInternal(ctx, this_obj, atom, val, JS_PROP_THROW);\n    JS_FreeAtom(ctx, atom);\n    return ret;\n}\n\n/* compute the property flags. For each flag: (JS_PROP_HAS_x forces\n   it, otherwise def_flags is used)\n   Note: makes assumption about the bit pattern of the flags\n*/\nstatic int get_prop_flags(int flags, int def_flags)\n{\n    int mask;\n    mask = (flags >> JS_PROP_HAS_SHIFT) & JS_PROP_C_W_E;\n    return (flags & mask) | (def_flags & ~mask);\n}\n\nstatic int JS_CreateProperty(JSContext *ctx, JSObject *p,\n                             JSAtom prop, JSValueConst val,\n                             JSValueConst getter, JSValueConst setter,\n                             int flags)\n{\n    JSProperty *pr;\n    int ret, prop_flags;\n\n    /* add a new property or modify an existing exotic one */\n    if (p->is_exotic) {\n        if (p->class_id == JS_CLASS_ARRAY) {\n            uint32_t idx, len;\n\n            if (p->fast_array) {\n                if (__JS_AtomIsTaggedInt(prop)) {\n                    idx = __JS_AtomToUInt32(prop);\n                    if (idx == p->u.array.count) {\n                        if (!p->extensible)\n                            goto not_extensible;\n                        if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET))\n                            goto convert_to_array;\n                        prop_flags = get_prop_flags(flags, 0);\n                        if (prop_flags != JS_PROP_C_W_E)\n                            goto convert_to_array;\n                        return add_fast_array_element(ctx, p,\n                                                      JS_DupValue(ctx, val), flags);\n                    } else {\n                        goto convert_to_array;\n                    }\n                } else if (JS_AtomIsArrayIndex(ctx, &idx, prop)) {\n                    /* convert the fast array to normal array */\n                convert_to_array:\n                    if (convert_fast_array_to_array(ctx, p))\n                        return -1;\n                    goto generic_array;\n                }\n            } else if (JS_AtomIsArrayIndex(ctx, &idx, prop)) {\n                JSProperty *plen;\n                JSShapeProperty *pslen;\n            generic_array:\n                /* update the length field */\n                plen = &p->prop[0];\n                JS_ToUint32(ctx, &len, plen->u.value);\n                if ((idx + 1) > len) {\n                    pslen = get_shape_prop(p->shape);\n                    if (unlikely(!(pslen->flags & JS_PROP_WRITABLE)))\n                        return JS_ThrowTypeErrorReadOnly(ctx, flags, JS_ATOM_length);\n                    /* XXX: should update the length after defining\n                       the property */\n                    len = idx + 1;\n                    set_value(ctx, &plen->u.value, JS_NewUint32(ctx, len));\n                }\n            }\n        } else if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n                   p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n            ret = JS_AtomIsNumericIndex(ctx, prop);\n            if (ret != 0) {\n                if (ret < 0)\n                    return -1;\n                return JS_ThrowTypeErrorOrFalse(ctx, flags, \"cannot create numeric index in typed array\");\n            }\n        } else if (!(flags & JS_PROP_NO_EXOTIC)) {\n            const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;\n            if (em) {\n                if (em->define_own_property) {\n                    return em->define_own_property(ctx, JS_MKPTR(JS_TAG_OBJECT, p),\n                                                   prop, val, getter, setter, flags);\n                }\n                ret = JS_IsExtensible(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n                if (ret < 0)\n                    return -1;\n                if (!ret)\n                    goto not_extensible;\n            }\n        }\n    }\n\n    if (!p->extensible) {\n    not_extensible:\n        return JS_ThrowTypeErrorOrFalse(ctx, flags, \"object is not extensible\");\n    }\n\n    if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {\n        prop_flags = (flags & (JS_PROP_CONFIGURABLE | JS_PROP_ENUMERABLE)) |\n            JS_PROP_GETSET;\n    } else {\n        prop_flags = flags & JS_PROP_C_W_E;\n    }\n    pr = add_property(ctx, p, prop, prop_flags);\n    if (unlikely(!pr))\n        return -1;\n    if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {\n        pr->u.getset.getter = NULL;\n        if ((flags & JS_PROP_HAS_GET) && JS_IsFunction(ctx, getter)) {\n            pr->u.getset.getter =\n                JS_VALUE_GET_OBJ(JS_DupValue(ctx, getter));\n        }\n        pr->u.getset.setter = NULL;\n        if ((flags & JS_PROP_HAS_SET) && JS_IsFunction(ctx, setter)) {\n            pr->u.getset.setter =\n                JS_VALUE_GET_OBJ(JS_DupValue(ctx, setter));\n        }\n    } else {\n        if (flags & JS_PROP_HAS_VALUE) {\n            pr->u.value = JS_DupValue(ctx, val);\n        } else {\n            pr->u.value = JS_UNDEFINED;\n        }\n    }\n    return TRUE;\n}\n\n/* return FALSE if not OK */\nstatic BOOL check_define_prop_flags(int prop_flags, int flags)\n{\n    BOOL has_accessor, is_getset;\n\n    if (!(prop_flags & JS_PROP_CONFIGURABLE)) {\n        if ((flags & (JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE)) ==\n            (JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE)) {\n            return FALSE;\n        }\n        if ((flags & JS_PROP_HAS_ENUMERABLE) &&\n            (flags & JS_PROP_ENUMERABLE) != (prop_flags & JS_PROP_ENUMERABLE))\n            return FALSE;\n    }\n    if (flags & (JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE |\n                 JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {\n        if (!(prop_flags & JS_PROP_CONFIGURABLE)) {\n            has_accessor = ((flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) != 0);\n            is_getset = ((prop_flags & JS_PROP_TMASK) == JS_PROP_GETSET);\n            if (has_accessor != is_getset)\n                return FALSE;\n            if (!has_accessor && !is_getset && !(prop_flags & JS_PROP_WRITABLE)) {\n                /* not writable: cannot set the writable bit */\n                if ((flags & (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) ==\n                    (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE))\n                    return FALSE;\n            }\n        }\n    }\n    return TRUE;\n}\n\n/* ensure that the shape can be safely modified */\nstatic int js_shape_prepare_update(JSContext *ctx, JSObject *p,\n                                   JSShapeProperty **pprs)\n{\n    JSShape *sh;\n    uint32_t idx = 0;    /* prevent warning */\n\n    sh = p->shape;\n    if (sh->is_hashed) {\n        if (sh->header.ref_count != 1) {\n            if (pprs)\n                idx = *pprs - get_shape_prop(sh);\n            /* clone the shape (the resulting one is no longer hashed) */\n            sh = js_clone_shape(ctx, sh);\n            if (!sh)\n                return -1;\n            js_free_shape(ctx->rt, p->shape);\n            p->shape = sh;\n            if (pprs)\n                *pprs = get_shape_prop(sh) + idx;\n        } else {\n            js_shape_hash_unlink(ctx->rt, sh);\n            sh->is_hashed = FALSE;\n        }\n    }\n    return 0;\n}\n\nstatic int js_update_property_flags(JSContext *ctx, JSObject *p,\n                                    JSShapeProperty **pprs, int flags)\n{\n    if (flags != (*pprs)->flags) {\n        if (js_shape_prepare_update(ctx, p, pprs))\n            return -1;\n        (*pprs)->flags = flags;\n    }\n    return 0;\n}\n\n/* allowed flags:\n   JS_PROP_CONFIGURABLE, JS_PROP_WRITABLE, JS_PROP_ENUMERABLE\n   JS_PROP_HAS_GET, JS_PROP_HAS_SET, JS_PROP_HAS_VALUE,\n   JS_PROP_HAS_CONFIGURABLE, JS_PROP_HAS_WRITABLE, JS_PROP_HAS_ENUMERABLE,\n   JS_PROP_THROW, JS_PROP_NO_EXOTIC.\n   If JS_PROP_THROW is set, return an exception instead of FALSE.\n   if JS_PROP_NO_EXOTIC is set, do not call the exotic\n   define_own_property callback.\n   return -1 (exception), FALSE or TRUE.\n*/\nint JS_DefineProperty(JSContext *ctx, JSValueConst this_obj,\n                      JSAtom prop, JSValueConst val,\n                      JSValueConst getter, JSValueConst setter, int flags)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    int mask, res;\n\n    if (JS_VALUE_GET_TAG(this_obj) != JS_TAG_OBJECT) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        return -1;\n    }\n    p = JS_VALUE_GET_OBJ(this_obj);\n\n redo_prop_update:\n    prs = find_own_property(&pr, p, prop);\n    if (prs) {\n        /* the range of the Array length property is always tested before */\n        if ((prs->flags & JS_PROP_LENGTH) && (flags & JS_PROP_HAS_VALUE)) {\n            uint32_t array_length;\n            if (JS_ToArrayLengthFree(ctx, &array_length,\n                                     JS_DupValue(ctx, val), FALSE)) {\n                return -1;\n            }\n            /* this code relies on the fact that Uint32 are never allocated */\n            val = (JSValueConst)JS_NewUint32(ctx, array_length);\n            /* prs may have been modified */\n            prs = find_own_property(&pr, p, prop);\n            assert(prs != NULL);\n        }\n        /* property already exists */\n        if (!check_define_prop_flags(prs->flags, flags)) {\n        not_configurable:\n            return JS_ThrowTypeErrorOrFalse(ctx, flags, \"property is not configurable\");\n        }\n\n        if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n            /* Instantiate property and retry */\n            if (JS_AutoInitProperty(ctx, p, prop, pr, prs))\n                return -1;\n            goto redo_prop_update;\n        }\n\n        if (flags & (JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE |\n                     JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {\n            if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {\n                JSObject *new_getter, *new_setter;\n\n                if (JS_IsFunction(ctx, getter)) {\n                    new_getter = JS_VALUE_GET_OBJ(getter);\n                } else {\n                    new_getter = NULL;\n                }\n                if (JS_IsFunction(ctx, setter)) {\n                    new_setter = JS_VALUE_GET_OBJ(setter);\n                } else {\n                    new_setter = NULL;\n                }\n\n                if ((prs->flags & JS_PROP_TMASK) != JS_PROP_GETSET) {\n                    if (js_shape_prepare_update(ctx, p, &prs))\n                        return -1;\n                    /* convert to getset */\n                    if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n                        free_var_ref(ctx->rt, pr->u.var_ref);\n                    } else {\n                        JS_FreeValue(ctx, pr->u.value);\n                    }\n                    prs->flags = (prs->flags &\n                                  (JS_PROP_CONFIGURABLE | JS_PROP_ENUMERABLE)) |\n                        JS_PROP_GETSET;\n                    pr->u.getset.getter = NULL;\n                    pr->u.getset.setter = NULL;\n                } else {\n                    if (!(prs->flags & JS_PROP_CONFIGURABLE)) {\n                        if ((flags & JS_PROP_HAS_GET) &&\n                            new_getter != pr->u.getset.getter) {\n                            goto not_configurable;\n                        }\n                        if ((flags & JS_PROP_HAS_SET) &&\n                            new_setter != pr->u.getset.setter) {\n                            goto not_configurable;\n                        }\n                    }\n                }\n                if (flags & JS_PROP_HAS_GET) {\n                    if (pr->u.getset.getter)\n                        JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter));\n                    if (new_getter)\n                        JS_DupValue(ctx, getter);\n                    pr->u.getset.getter = new_getter;\n                }\n                if (flags & JS_PROP_HAS_SET) {\n                    if (pr->u.getset.setter)\n                        JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter));\n                    if (new_setter)\n                        JS_DupValue(ctx, setter);\n                    pr->u.getset.setter = new_setter;\n                }\n            } else {\n                if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {\n                    /* convert to data descriptor */\n                    if (js_shape_prepare_update(ctx, p, &prs))\n                        return -1;\n                    if (pr->u.getset.getter)\n                        JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter));\n                    if (pr->u.getset.setter)\n                        JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter));\n                    prs->flags &= ~(JS_PROP_TMASK | JS_PROP_WRITABLE);\n                    pr->u.value = JS_UNDEFINED;\n                } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n                    /* Note: JS_PROP_VARREF is always writable */\n                } else {\n                    if ((prs->flags & (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) == 0 &&\n                        (flags & JS_PROP_HAS_VALUE)) {\n                        if (!js_same_value(ctx, val, pr->u.value)) {\n                            goto not_configurable;\n                        } else {\n                            return TRUE;\n                        }\n                    }\n                }\n                if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n                    if (flags & JS_PROP_HAS_VALUE) {\n                        if (p->class_id == JS_CLASS_MODULE_NS) {\n                            /* JS_PROP_WRITABLE is always true for variable\n                               references, but they are write protected in module name\n                               spaces. */\n                            if (!js_same_value(ctx, val, *pr->u.var_ref->pvalue))\n                                goto not_configurable;\n                        }\n                        /* update the reference */\n                        set_value(ctx, pr->u.var_ref->pvalue,\n                                  JS_DupValue(ctx, val));\n                    }\n                    /* if writable is set to false, no longer a\n                       reference (for mapped arguments) */\n                    if ((flags & (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) == JS_PROP_HAS_WRITABLE) {\n                        JSValue val1;\n                        if (js_shape_prepare_update(ctx, p, &prs))\n                            return -1;\n                        val1 = JS_DupValue(ctx, *pr->u.var_ref->pvalue);\n                        free_var_ref(ctx->rt, pr->u.var_ref);\n                        pr->u.value = val1;\n                        prs->flags &= ~(JS_PROP_TMASK | JS_PROP_WRITABLE);\n                    }\n                } else if (prs->flags & JS_PROP_LENGTH) {\n                    if (flags & JS_PROP_HAS_VALUE) {\n                        /* Note: no JS code is executable because\n                           'val' is guaranted to be a Uint32 */\n                        res = set_array_length(ctx, p, JS_DupValue(ctx, val),\n                                               flags);\n                    } else {\n                        res = TRUE;\n                    }\n                    /* still need to reset the writable flag if\n                       needed.  The JS_PROP_LENGTH is kept because the\n                       Uint32 test is still done if the length\n                       property is read-only. */\n                    if ((flags & (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) ==\n                        JS_PROP_HAS_WRITABLE) {\n                        prs = get_shape_prop(p->shape);\n                        if (js_update_property_flags(ctx, p, &prs,\n                                                     prs->flags & ~JS_PROP_WRITABLE))\n                            return -1;\n                    }\n                    return res;\n                } else {\n                    if (flags & JS_PROP_HAS_VALUE) {\n                        JS_FreeValue(ctx, pr->u.value);\n                        pr->u.value = JS_DupValue(ctx, val);\n                    }\n                    if (flags & JS_PROP_HAS_WRITABLE) {\n                        if (js_update_property_flags(ctx, p, &prs,\n                                                     (prs->flags & ~JS_PROP_WRITABLE) |\n                                                     (flags & JS_PROP_WRITABLE)))\n                            return -1;\n                    }\n                }\n            }\n        }\n        mask = 0;\n        if (flags & JS_PROP_HAS_CONFIGURABLE)\n            mask |= JS_PROP_CONFIGURABLE;\n        if (flags & JS_PROP_HAS_ENUMERABLE)\n            mask |= JS_PROP_ENUMERABLE;\n        if (js_update_property_flags(ctx, p, &prs,\n                                     (prs->flags & ~mask) | (flags & mask)))\n            return -1;\n        return TRUE;\n    }\n\n    /* handle modification of fast array elements */\n    if (p->fast_array) {\n        uint32_t idx;\n        uint32_t prop_flags;\n        if (p->class_id == JS_CLASS_ARRAY) {\n            if (__JS_AtomIsTaggedInt(prop)) {\n                idx = __JS_AtomToUInt32(prop);\n                if (idx < p->u.array.count) {\n                    prop_flags = get_prop_flags(flags, JS_PROP_C_W_E);\n                    if (prop_flags != JS_PROP_C_W_E)\n                        goto convert_to_slow_array;\n                    if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {\n                    convert_to_slow_array:\n                        if (convert_fast_array_to_array(ctx, p))\n                            return -1;\n                        else\n                            goto redo_prop_update;\n                    }\n                    if (flags & JS_PROP_HAS_VALUE) {\n                        set_value(ctx, &p->u.array.u.values[idx], JS_DupValue(ctx, val));\n                    }\n                    return TRUE;\n                }\n            }\n        } else if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n                   p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n            JSValue num;\n            int ret;\n\n            if (!__JS_AtomIsTaggedInt(prop)) {\n                /* slow path with to handle all numeric indexes */\n                num = JS_AtomIsNumericIndex1(ctx, prop);\n                if (JS_IsUndefined(num))\n                    goto typed_array_done;\n                if (JS_IsException(num))\n                    return -1;\n                ret = JS_NumberIsInteger(ctx, num);\n                if (ret < 0) {\n                    JS_FreeValue(ctx, num);\n                    return -1;\n                }\n                if (!ret) {\n                    JS_FreeValue(ctx, num);\n                    return JS_ThrowTypeErrorOrFalse(ctx, flags, \"non integer index in typed array\");\n                }\n                ret = JS_NumberIsNegativeOrMinusZero(ctx, num);\n                JS_FreeValue(ctx, num);\n                if (ret) {\n                    return JS_ThrowTypeErrorOrFalse(ctx, flags, \"negative index in typed array\");\n                }\n                if (!__JS_AtomIsTaggedInt(prop))\n                    goto typed_array_oob;\n            }\n            idx = __JS_AtomToUInt32(prop);\n            /* if the typed array is detached, p->u.array.count = 0 */\n            if (idx >= typed_array_get_length(ctx, p)) {\n            typed_array_oob:\n                return JS_ThrowTypeErrorOrFalse(ctx, flags, \"out-of-bound index in typed array\");\n            }\n            prop_flags = get_prop_flags(flags, JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n            if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET) ||\n                prop_flags != (JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE)) {\n                return JS_ThrowTypeErrorOrFalse(ctx, flags, \"invalid descriptor flags\");\n            }\n            if (flags & JS_PROP_HAS_VALUE) {\n                return JS_SetPropertyValue(ctx, this_obj, JS_NewInt32(ctx, idx), JS_DupValue(ctx, val), flags);\n            }\n            return TRUE;\n        typed_array_done: ;\n        }\n    }\n\n    return JS_CreateProperty(ctx, p, prop, val, getter, setter, flags);\n}\n\nstatic int JS_DefineAutoInitProperty(JSContext *ctx, JSValueConst this_obj,\n                                     JSAtom prop, JSAutoInitIDEnum id,\n                                     void *opaque, int flags)\n{\n    JSObject *p;\n    JSProperty *pr;\n\n    if (JS_VALUE_GET_TAG(this_obj) != JS_TAG_OBJECT)\n        return FALSE;\n\n    p = JS_VALUE_GET_OBJ(this_obj);\n\n    if (find_own_property(&pr, p, prop)) {\n        /* property already exists */\n        abort();\n        return FALSE;\n    }\n\n    /* Specialized CreateProperty */\n    pr = add_property(ctx, p, prop, (flags & JS_PROP_C_W_E) | JS_PROP_AUTOINIT);\n    if (unlikely(!pr))\n        return -1;\n    pr->u.init.realm_and_id = (uintptr_t)JS_DupContext(ctx);\n    assert((pr->u.init.realm_and_id & 3) == 0);\n    assert(id <= 3);\n    pr->u.init.realm_and_id |= id;\n    pr->u.init.opaque = opaque;\n    return TRUE;\n}\n\n/* shortcut to add or redefine a new property value */\nint JS_DefinePropertyValue(JSContext *ctx, JSValueConst this_obj,\n                           JSAtom prop, JSValue val, int flags)\n{\n    int ret;\n    ret = JS_DefineProperty(ctx, this_obj, prop, val, JS_UNDEFINED, JS_UNDEFINED,\n                            flags | JS_PROP_HAS_VALUE | JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_WRITABLE | JS_PROP_HAS_ENUMERABLE);\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nint JS_DefinePropertyValueValue(JSContext *ctx, JSValueConst this_obj,\n                                JSValue prop, JSValue val, int flags)\n{\n    JSAtom atom;\n    int ret;\n    atom = JS_ValueToAtom(ctx, prop);\n    JS_FreeValue(ctx, prop);\n    if (unlikely(atom == JS_ATOM_NULL)) {\n        JS_FreeValue(ctx, val);\n        return -1;\n    }\n    ret = JS_DefinePropertyValue(ctx, this_obj, atom, val, flags);\n    JS_FreeAtom(ctx, atom);\n    return ret;\n}\n\nint JS_DefinePropertyValueUint32(JSContext *ctx, JSValueConst this_obj,\n                                 uint32_t idx, JSValue val, int flags)\n{\n    return JS_DefinePropertyValueValue(ctx, this_obj, JS_NewUint32(ctx, idx),\n                                       val, flags);\n}\n\nint JS_DefinePropertyValueInt64(JSContext *ctx, JSValueConst this_obj,\n                                int64_t idx, JSValue val, int flags)\n{\n    return JS_DefinePropertyValueValue(ctx, this_obj, JS_NewInt64(ctx, idx),\n                                       val, flags);\n}\n\nint JS_DefinePropertyValueStr(JSContext *ctx, JSValueConst this_obj,\n                              const char *prop, JSValue val, int flags)\n{\n    JSAtom atom;\n    int ret;\n    atom = JS_NewAtom(ctx, prop);\n    ret = JS_DefinePropertyValue(ctx, this_obj, atom, val, flags);\n    JS_FreeAtom(ctx, atom);\n    return ret;\n}\n\n/* shortcut to add getter & setter */\nint JS_DefinePropertyGetSet(JSContext *ctx, JSValueConst this_obj,\n                            JSAtom prop, JSValue getter, JSValue setter,\n                            int flags)\n{\n    int ret;\n    ret = JS_DefineProperty(ctx, this_obj, prop, JS_UNDEFINED, getter, setter,\n                            flags | JS_PROP_HAS_GET | JS_PROP_HAS_SET |\n                            JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_ENUMERABLE);\n    JS_FreeValue(ctx, getter);\n    JS_FreeValue(ctx, setter);\n    return ret;\n}\n\nstatic int JS_CreateDataPropertyUint32(JSContext *ctx, JSValueConst this_obj,\n                                       int64_t idx, JSValue val, int flags)\n{\n    return JS_DefinePropertyValueValue(ctx, this_obj, JS_NewInt64(ctx, idx),\n                                       val, flags | JS_PROP_CONFIGURABLE |\n                                       JS_PROP_ENUMERABLE | JS_PROP_WRITABLE);\n}\n\n\n/* return TRUE if 'obj' has a non empty 'name' string */\nstatic BOOL js_object_has_name(JSContext *ctx, JSValueConst obj)\n{\n    JSProperty *pr;\n    JSShapeProperty *prs;\n    JSValueConst val;\n    JSString *p;\n    \n    prs = find_own_property(&pr, JS_VALUE_GET_OBJ(obj), JS_ATOM_name);\n    if (!prs)\n        return FALSE;\n    if ((prs->flags & JS_PROP_TMASK) != JS_PROP_NORMAL)\n        return TRUE;\n    val = pr->u.value;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_STRING)\n        return TRUE;\n    p = JS_VALUE_GET_STRING(val);\n    return (p->len != 0);\n}\n\nstatic int JS_DefineObjectName(JSContext *ctx, JSValueConst obj,\n                               JSAtom name, int flags)\n{\n    if (name != JS_ATOM_NULL\n    &&  JS_IsObject(obj)\n    &&  !js_object_has_name(ctx, obj)\n    &&  JS_DefinePropertyValue(ctx, obj, JS_ATOM_name, JS_AtomToString(ctx, name), flags) < 0) {\n        return -1;\n    }\n    return 0;\n}\n\nstatic int JS_DefineObjectNameComputed(JSContext *ctx, JSValueConst obj,\n                                       JSValueConst str, int flags)\n{\n    if (JS_IsObject(obj) &&\n        !js_object_has_name(ctx, obj)) {\n        JSAtom prop;\n        JSValue name_str;\n        prop = JS_ValueToAtom(ctx, str);\n        if (prop == JS_ATOM_NULL)\n            return -1;\n        name_str = js_get_function_name(ctx, prop);\n        JS_FreeAtom(ctx, prop);\n        if (JS_IsException(name_str))\n            return -1;\n        if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_name, name_str, flags) < 0)\n            return -1;\n    }\n    return 0;\n}\n\n#define DEFINE_GLOBAL_LEX_VAR (1 << 7)\n#define DEFINE_GLOBAL_FUNC_VAR (1 << 6)\n\nstatic JSValue JS_ThrowSyntaxErrorVarRedeclaration(JSContext *ctx, JSAtom prop)\n{\n    return JS_ThrowSyntaxErrorAtom(ctx, \"redeclaration of '%s'\", prop);\n}\n\n/* flags is 0, DEFINE_GLOBAL_LEX_VAR or DEFINE_GLOBAL_FUNC_VAR */\n/* XXX: could support exotic global object. */\nstatic int JS_CheckDefineGlobalVar(JSContext *ctx, JSAtom prop, int flags)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n\n    p = JS_VALUE_GET_OBJ(ctx->global_obj);\n    prs = find_own_property1(p, prop);\n    /* XXX: should handle JS_PROP_AUTOINIT */\n    if (flags & DEFINE_GLOBAL_LEX_VAR) {\n        if (prs && !(prs->flags & JS_PROP_CONFIGURABLE))\n            goto fail_redeclaration;\n    } else {\n        if (!prs && !p->extensible)\n            goto define_error;\n        if (flags & DEFINE_GLOBAL_FUNC_VAR) {\n            if (prs) {\n                if (!(prs->flags & JS_PROP_CONFIGURABLE) &&\n                    ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET ||\n                     ((prs->flags & (JS_PROP_WRITABLE | JS_PROP_ENUMERABLE)) !=\n                      (JS_PROP_WRITABLE | JS_PROP_ENUMERABLE)))) {\n                define_error:\n                    JS_ThrowTypeErrorAtom(ctx, \"cannot define variable '%s'\",\n                                          prop);\n                    return -1;\n                }\n            }\n        }\n    }\n    /* check if there already is a lexical declaration */\n    p = JS_VALUE_GET_OBJ(ctx->global_var_obj);\n    prs = find_own_property1(p, prop);\n    if (prs) {\n    fail_redeclaration:\n        JS_ThrowSyntaxErrorVarRedeclaration(ctx, prop);\n        return -1;\n    }\n    return 0;\n}\n\n/* def_flags is (0, DEFINE_GLOBAL_LEX_VAR) |\n   JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE */\n/* XXX: could support exotic global object. */\nstatic int JS_DefineGlobalVar(JSContext *ctx, JSAtom prop, int def_flags)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    JSValue val;\n    int flags;\n\n    if (def_flags & DEFINE_GLOBAL_LEX_VAR) {\n        p = JS_VALUE_GET_OBJ(ctx->global_var_obj);\n        flags = JS_PROP_ENUMERABLE | (def_flags & JS_PROP_WRITABLE) |\n            JS_PROP_CONFIGURABLE;\n        val = JS_UNINITIALIZED;\n    } else {\n        p = JS_VALUE_GET_OBJ(ctx->global_obj);\n        flags = JS_PROP_ENUMERABLE | JS_PROP_WRITABLE |\n            (def_flags & JS_PROP_CONFIGURABLE);\n        val = JS_UNDEFINED;\n    }\n    prs = find_own_property1(p, prop);\n    if (prs)\n        return 0;\n    if (!p->extensible)\n        return 0;\n    pr = add_property(ctx, p, prop, flags);\n    if (unlikely(!pr))\n        return -1;\n    pr->u.value = val;\n    return 0;\n}\n\n/* 'def_flags' is 0 or JS_PROP_CONFIGURABLE. */\n/* XXX: could support exotic global object. */\nstatic int JS_DefineGlobalFunction(JSContext *ctx, JSAtom prop,\n                                   JSValueConst func, int def_flags)\n{\n\n    JSObject *p;\n    JSShapeProperty *prs;\n    int flags;\n\n    p = JS_VALUE_GET_OBJ(ctx->global_obj);\n    prs = find_own_property1(p, prop);\n    flags = JS_PROP_HAS_VALUE | JS_PROP_THROW;\n    if (!prs || (prs->flags & JS_PROP_CONFIGURABLE)) {\n        flags |= JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | def_flags |\n            JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_WRITABLE | JS_PROP_HAS_ENUMERABLE;\n    }\n    if (JS_DefineProperty(ctx, ctx->global_obj, prop, func,\n                          JS_UNDEFINED, JS_UNDEFINED, flags) < 0)\n        return -1;\n    return 0;\n}\n\nstatic JSValue JS_GetGlobalVar(JSContext *ctx, JSAtom prop,\n                               BOOL throw_ref_error)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n\n    /* no exotic behavior is possible in global_var_obj */\n    p = JS_VALUE_GET_OBJ(ctx->global_var_obj);\n    prs = find_own_property(&pr, p, prop);\n    if (prs) {\n        /* XXX: should handle JS_PROP_TMASK properties */\n        if (unlikely(JS_IsUninitialized(pr->u.value)))\n            return JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);\n        return JS_DupValue(ctx, pr->u.value);\n    }\n    return JS_GetPropertyInternal(ctx, ctx->global_obj, prop,\n                                 ctx->global_obj, throw_ref_error);\n}\n\n/* construct a reference to a global variable */\nstatic int JS_GetGlobalVarRef(JSContext *ctx, JSAtom prop, JSValue *sp)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n\n    /* no exotic behavior is possible in global_var_obj */\n    p = JS_VALUE_GET_OBJ(ctx->global_var_obj);\n    prs = find_own_property(&pr, p, prop);\n    if (prs) {\n        /* XXX: should handle JS_PROP_AUTOINIT properties? */\n        /* XXX: conformance: do these tests in\n           OP_put_var_ref/OP_get_var_ref ? */\n        if (unlikely(JS_IsUninitialized(pr->u.value))) {\n            JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);\n            return -1;\n        }\n        if (unlikely(!(prs->flags & JS_PROP_WRITABLE))) {\n            return JS_ThrowTypeErrorReadOnly(ctx, JS_PROP_THROW, prop);\n        }\n        sp[0] = JS_DupValue(ctx, ctx->global_var_obj);\n    } else {\n        int ret;\n        ret = JS_HasProperty(ctx, ctx->global_obj, prop);\n        if (ret < 0)\n            return -1;\n        if (ret) {\n            sp[0] = JS_DupValue(ctx, ctx->global_obj);\n        } else {\n            sp[0] = JS_UNDEFINED;\n        }\n    }\n    sp[1] = JS_AtomToValue(ctx, prop);\n    return 0;\n}\n\n/* use for strict variable access: test if the variable exists */\nstatic int JS_CheckGlobalVar(JSContext *ctx, JSAtom prop)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    int ret;\n\n    /* no exotic behavior is possible in global_var_obj */\n    p = JS_VALUE_GET_OBJ(ctx->global_var_obj);\n    prs = find_own_property1(p, prop);\n    if (prs) {\n        ret = TRUE;\n    } else {\n        ret = JS_HasProperty(ctx, ctx->global_obj, prop);\n        if (ret < 0)\n            return -1;\n    }\n    return ret;\n}\n\n/* flag = 0: normal variable write\n   flag = 1: initialize lexical variable\n   flag = 2: normal variable write, strict check was done before\n*/\nstatic int JS_SetGlobalVar(JSContext *ctx, JSAtom prop, JSValue val,\n                           int flag)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    int flags;\n\n    /* no exotic behavior is possible in global_var_obj */\n    p = JS_VALUE_GET_OBJ(ctx->global_var_obj);\n    prs = find_own_property(&pr, p, prop);\n    if (prs) {\n        /* XXX: should handle JS_PROP_AUTOINIT properties? */\n        if (flag != 1) {\n            if (unlikely(JS_IsUninitialized(pr->u.value))) {\n                JS_FreeValue(ctx, val);\n                JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);\n                return -1;\n            }\n            if (unlikely(!(prs->flags & JS_PROP_WRITABLE))) {\n                JS_FreeValue(ctx, val);\n                return JS_ThrowTypeErrorReadOnly(ctx, JS_PROP_THROW, prop);\n            }\n        }\n        set_value(ctx, &pr->u.value, val);\n        return 0;\n    }\n    flags = JS_PROP_THROW_STRICT;\n    if (is_strict_mode(ctx)) \n        flags |= JS_PROP_NO_ADD;\n    return JS_SetPropertyInternal(ctx, ctx->global_obj, prop, val, flags);\n}\n\n/* return -1, FALSE or TRUE. return FALSE if not configurable or\n   invalid object. return -1 in case of exception.\n   flags can be 0, JS_PROP_THROW or JS_PROP_THROW_STRICT */\nint JS_DeleteProperty(JSContext *ctx, JSValueConst obj, JSAtom prop, int flags)\n{\n    JSValue obj1;\n    JSObject *p;\n    int res;\n    \n    obj1 = JS_ToObject(ctx, obj);\n    if (JS_IsException(obj1))\n        return -1;\n    p = JS_VALUE_GET_OBJ(obj1);\n    res = delete_property(ctx, p, prop);\n    JS_FreeValue(ctx, obj1);\n    if (res != FALSE)\n        return res;\n    if ((flags & JS_PROP_THROW) ||\n        ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) {\n        JS_ThrowTypeError(ctx, \"could not delete property\");\n        return -1;\n    }\n    return FALSE;\n}\n\nint JS_DeletePropertyInt64(JSContext *ctx, JSValueConst obj, int64_t idx, int flags)\n{\n    JSAtom prop;\n    int res;\n\n    if ((uint64_t)idx <= JS_ATOM_MAX_INT) {\n        /* fast path for fast arrays */\n        return JS_DeleteProperty(ctx, obj, __JS_AtomFromUInt32(idx), flags);\n    }\n    prop = JS_NewAtomInt64(ctx, idx);\n    if (prop == JS_ATOM_NULL)\n        return -1;\n    res = JS_DeleteProperty(ctx, obj, prop, flags);\n    JS_FreeAtom(ctx, prop);\n    return res;\n}\n\nBOOL JS_IsFunction(JSContext *ctx, JSValueConst val)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(val);\n    switch(p->class_id) {\n    case JS_CLASS_BYTECODE_FUNCTION:\n        return TRUE;\n    case JS_CLASS_PROXY:\n        return p->u.proxy_data->is_func;\n    default:\n        return (ctx->rt->class_array[p->class_id].call != NULL);\n    }\n}\n\nBOOL JS_IsCFunction(JSContext *ctx, JSValueConst val, JSCFunction *func, int magic)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(val);\n    if (p->class_id == JS_CLASS_C_FUNCTION)\n        return (p->u.cfunc.c_function.generic == func && p->u.cfunc.magic == magic);\n    else\n        return FALSE;\n}\n\nBOOL JS_IsConstructor(JSContext *ctx, JSValueConst val)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(val);\n    return p->is_constructor;\n}\n\nBOOL JS_SetConstructorBit(JSContext *ctx, JSValueConst func_obj, BOOL val)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT)\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(func_obj);\n    p->is_constructor = val;\n    return TRUE;\n}\n\nBOOL JS_IsError(JSContext *ctx, JSValueConst val)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(val);\n    return (p->class_id == JS_CLASS_ERROR);\n}\n\n/* used to avoid catching interrupt exceptions */\nBOOL JS_IsUncatchableError(JSContext *ctx, JSValueConst val)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(val);\n    return p->class_id == JS_CLASS_ERROR && p->is_uncatchable_error;\n}\n\nvoid JS_SetUncatchableError(JSContext *ctx, JSValueConst val, BOOL flag)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return;\n    p = JS_VALUE_GET_OBJ(val);\n    if (p->class_id == JS_CLASS_ERROR)\n        p->is_uncatchable_error = flag;\n}\n\nvoid JS_ResetUncatchableError(JSContext *ctx)\n{\n    JS_SetUncatchableError(ctx, ctx->rt->current_exception, FALSE);\n}\n\nvoid JS_SetOpaque(JSValue obj, void *opaque)\n{\n   JSObject *p;\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        p = JS_VALUE_GET_OBJ(obj);\n        p->u.opaque = opaque;\n    }\n}\n\n/* return NULL if not an object of class class_id */\nvoid *JS_GetOpaque(JSValueConst obj, JSClassID class_id)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return NULL;\n    p = JS_VALUE_GET_OBJ(obj);\n    if (p->class_id != class_id)\n        return NULL;\n    return p->u.opaque;\n}\n\nvoid *JS_GetOpaque2(JSContext *ctx, JSValueConst obj, JSClassID class_id)\n{\n    void *p = JS_GetOpaque(obj, class_id);\n    if (unlikely(!p)) {\n        JS_ThrowTypeErrorInvalidClass(ctx, class_id);\n    }\n    return p;\n}\n\n#define HINT_STRING  0\n#define HINT_NUMBER  1\n#define HINT_NONE    2\n/* don't try Symbol.toPrimitive */\n#define HINT_FORCE_ORDINARY (1 << 4)\n\nstatic JSValue JS_ToPrimitiveFree(JSContext *ctx, JSValue val, int hint)\n{\n    int i;\n    BOOL force_ordinary;\n\n    JSAtom method_name;\n    JSValue method, ret;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return val;\n    force_ordinary = hint & HINT_FORCE_ORDINARY;\n    hint &= ~HINT_FORCE_ORDINARY;\n    if (!force_ordinary) {\n        method = JS_GetProperty(ctx, val, JS_ATOM_Symbol_toPrimitive);\n        if (JS_IsException(method))\n            goto exception;\n        /* ECMA says *If exoticToPrim is not undefined* but tests in\n           test262 use null as a non callable converter */\n        if (!JS_IsUndefined(method) && !JS_IsNull(method)) {\n            JSAtom atom;\n            JSValue arg;\n            switch(hint) {\n            case HINT_STRING:\n                atom = JS_ATOM_string;\n                break;\n            case HINT_NUMBER:\n                atom = JS_ATOM_number;\n                break;\n            default:\n            case HINT_NONE:\n                atom = JS_ATOM_default;\n                break;\n            }\n            arg = JS_AtomToString(ctx, atom);\n            ret = JS_CallFree(ctx, method, val, 1, (JSValueConst *)&arg);\n            JS_FreeValue(ctx, arg);\n            if (JS_IsException(ret))\n                goto exception;\n            JS_FreeValue(ctx, val);\n            if (JS_VALUE_GET_TAG(ret) != JS_TAG_OBJECT)\n                return ret;\n            JS_FreeValue(ctx, ret);\n            return JS_ThrowTypeError(ctx, \"toPrimitive\");\n        }\n    }\n    if (hint != HINT_STRING)\n        hint = HINT_NUMBER;\n    for(i = 0; i < 2; i++) {\n        if ((i ^ hint) == 0) {\n            method_name = JS_ATOM_toString;\n        } else {\n            method_name = JS_ATOM_valueOf;\n        }\n        method = JS_GetProperty(ctx, val, method_name);\n        if (JS_IsException(method))\n            goto exception;\n        if (JS_IsFunction(ctx, method)) {\n            ret = JS_CallFree(ctx, method, val, 0, NULL);\n            if (JS_IsException(ret))\n                goto exception;\n            if (JS_VALUE_GET_TAG(ret) != JS_TAG_OBJECT) {\n                JS_FreeValue(ctx, val);\n                return ret;\n            }\n            JS_FreeValue(ctx, ret);\n        } else {\n            JS_FreeValue(ctx, method);\n        }\n    }\n    JS_ThrowTypeError(ctx, \"toPrimitive\");\nexception:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ToPrimitive(JSContext *ctx, JSValueConst val, int hint)\n{\n    return JS_ToPrimitiveFree(ctx, JS_DupValue(ctx, val), hint);\n}\n\nvoid JS_SetIsHTMLDDA(JSContext *ctx, JSValueConst obj)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return;\n    p = JS_VALUE_GET_OBJ(obj);\n    p->is_HTMLDDA = TRUE;\n}\n\nstatic inline BOOL JS_IsHTMLDDA(JSContext *ctx, JSValueConst obj)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(obj);\n    return p->is_HTMLDDA;\n}\n                         \nstatic int JS_ToBoolFree(JSContext *ctx, JSValue val)\n{\n    uint32_t tag = JS_VALUE_GET_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n        return JS_VALUE_GET_INT(val) != 0;\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        return JS_VALUE_GET_INT(val);\n    case JS_TAG_EXCEPTION:\n        return -1;\n    case JS_TAG_STRING:\n        {\n            BOOL ret = JS_VALUE_GET_STRING(val)->len != 0;\n            JS_FreeValue(ctx, val);\n            return ret;\n        }\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            BOOL ret;\n            ret = p->num.expn != BF_EXP_ZERO && p->num.expn != BF_EXP_NAN;\n            JS_FreeValue(ctx, val);\n            return ret;\n        }\n    case JS_TAG_BIG_DECIMAL:\n        {\n            JSBigDecimal *p = JS_VALUE_GET_PTR(val);\n            BOOL ret;\n            ret = p->num.expn != BF_EXP_ZERO && p->num.expn != BF_EXP_NAN;\n            JS_FreeValue(ctx, val);\n            return ret;\n        }\n#endif\n    case JS_TAG_OBJECT:\n        {\n            JSObject *p = JS_VALUE_GET_OBJ(val);\n            BOOL ret;\n            ret = !p->is_HTMLDDA;\n            JS_FreeValue(ctx, val);\n            return ret;\n        }\n        break;\n    default:\n        if (JS_TAG_IS_FLOAT64(tag)) {\n            double d = JS_VALUE_GET_FLOAT64(val);\n            return !isnan(d) && d != 0;\n        } else {\n            JS_FreeValue(ctx, val);\n            return TRUE;\n        }\n    }\n}\n\nint JS_ToBool(JSContext *ctx, JSValueConst val)\n{\n    return JS_ToBoolFree(ctx, JS_DupValue(ctx, val));\n}\n\nstatic int skip_spaces(const char *pc)\n{\n    const uint8_t *p, *p_next, *p_start;\n    uint32_t c;\n\n    p = p_start = (const uint8_t *)pc;\n    for (;;) {\n        c = *p;\n        if (c < 128) {\n            if (!((c >= 0x09 && c <= 0x0d) || (c == 0x20)))\n                break;\n            p++;\n        } else {\n            c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p_next);\n            if (!lre_is_space(c))\n                break;\n            p = p_next;\n        }\n    }\n    return p - p_start;\n}\n\nstatic inline int to_digit(int c)\n{\n    if (c >= '0' && c <= '9')\n        return c - '0';\n    else if (c >= 'A' && c <= 'Z')\n        return c - 'A' + 10;\n    else if (c >= 'a' && c <= 'z')\n        return c - 'a' + 10;\n    else\n        return 36;\n}\n\n/* XXX: remove */\nstatic double js_strtod(const char *p, int radix, BOOL is_float)\n{\n    double d;\n    int c;\n    \n    if (!is_float || radix != 10) {\n        uint64_t n_max, n;\n        int int_exp, is_neg;\n        \n        is_neg = 0;\n        if (*p == '-') {\n            is_neg = 1;\n            p++;\n        }\n\n        /* skip leading zeros */\n        while (*p == '0')\n            p++;\n        n = 0;\n        if (radix == 10)\n            n_max = ((uint64_t)-1 - 9) / 10; /* most common case */\n        else\n            n_max = ((uint64_t)-1 - (radix - 1)) / radix;\n        /* XXX: could be more precise */\n        int_exp = 0;\n        while (*p != '\\0') {\n            c = to_digit((uint8_t)*p);\n            if (c >= radix)\n                break;\n            if (n <= n_max) {\n                n = n * radix + c;\n            } else {\n                int_exp++;\n            }\n            p++;\n        }\n        d = n;\n        if (int_exp != 0) {\n            d *= pow(radix, int_exp);\n        }\n        if (is_neg)\n            d = -d;\n    } else {\n        d = strtod(p, NULL);\n    }\n    return d;\n}\n\n#define ATOD_INT_ONLY        (1 << 0)\n/* accept Oo and Ob prefixes in addition to 0x prefix if radix = 0 */\n#define ATOD_ACCEPT_BIN_OCT  (1 << 2)\n/* accept O prefix as octal if radix == 0 and properly formed (Annex B) */\n#define ATOD_ACCEPT_LEGACY_OCTAL  (1 << 4)\n/* accept _ between digits as a digit separator */\n#define ATOD_ACCEPT_UNDERSCORES  (1 << 5)\n/* allow a suffix to override the type */\n#define ATOD_ACCEPT_SUFFIX    (1 << 6) \n/* default type */\n#define ATOD_TYPE_MASK        (3 << 7)\n#define ATOD_TYPE_FLOAT64     (0 << 7)\n#define ATOD_TYPE_BIG_INT     (1 << 7)\n#define ATOD_TYPE_BIG_FLOAT   (2 << 7)\n#define ATOD_TYPE_BIG_DECIMAL (3 << 7)\n/* assume bigint mode: floats are parsed as integers if no decimal\n   point nor exponent */\n#define ATOD_MODE_BIGINT      (1 << 9) \n/* accept -0x1 */\n#define ATOD_ACCEPT_PREFIX_AFTER_SIGN (1 << 10)\n\n#ifdef CONFIG_BIGNUM\nstatic JSValue js_string_to_bigint(JSContext *ctx, const char *buf,\n                                   int radix, int flags, slimb_t *pexponent)\n{\n    bf_t a_s, *a = &a_s;\n    int ret;\n    JSValue val;\n    val = JS_NewBigInt(ctx);\n    if (JS_IsException(val))\n        return val;\n    a = JS_GetBigInt(val);\n    ret = bf_atof(a, buf, NULL, radix, BF_PREC_INF, BF_RNDZ);\n    if (ret & BF_ST_MEM_ERROR) {\n        JS_FreeValue(ctx, val);\n        return JS_ThrowOutOfMemory(ctx);\n    }\n    val = JS_CompactBigInt1(ctx, val, (flags & ATOD_MODE_BIGINT) != 0);\n    return val;\n}\n\nstatic JSValue js_string_to_bigfloat(JSContext *ctx, const char *buf,\n                                     int radix, int flags, slimb_t *pexponent)\n{\n    bf_t *a;\n    int ret;\n    JSValue val;\n    \n    val = JS_NewBigFloat(ctx);\n    if (JS_IsException(val))\n        return val;\n    a = JS_GetBigFloat(val);\n    if (flags & ATOD_ACCEPT_SUFFIX) {\n        /* return the exponent to get infinite precision */\n        ret = bf_atof2(a, pexponent, buf, NULL, radix, BF_PREC_INF,\n                       BF_RNDZ | BF_ATOF_EXPONENT);\n    } else {\n        ret = bf_atof(a, buf, NULL, radix, ctx->fp_env.prec,\n                      ctx->fp_env.flags);\n    }\n    if (ret & BF_ST_MEM_ERROR) {\n        JS_FreeValue(ctx, val);\n        return JS_ThrowOutOfMemory(ctx);\n    }\n    return val;\n}\n\nstatic JSValue js_string_to_bigdecimal(JSContext *ctx, const char *buf,\n                                       int radix, int flags, slimb_t *pexponent)\n{\n    bfdec_t *a;\n    int ret;\n    JSValue val;\n    \n    val = JS_NewBigDecimal(ctx);\n    if (JS_IsException(val))\n        return val;\n    a = JS_GetBigDecimal(val);\n    ret = bfdec_atof(a, buf, NULL, BF_PREC_INF,\n                     BF_RNDZ | BF_ATOF_NO_NAN_INF);\n    if (ret & BF_ST_MEM_ERROR) {\n        JS_FreeValue(ctx, val);\n        return JS_ThrowOutOfMemory(ctx);\n    }\n    return val;\n}\n\n#endif\n\n/* return an exception in case of memory error. Return JS_NAN if\n   invalid syntax */\n#ifdef CONFIG_BIGNUM\nstatic JSValue js_atof2(JSContext *ctx, const char *str, const char **pp,\n                        int radix, int flags, slimb_t *pexponent)\n#else\nstatic JSValue js_atof(JSContext *ctx, const char *str, const char **pp,\n                       int radix, int flags)\n#endif\n{\n    const char *p, *p_start;\n    int sep, is_neg;\n    BOOL is_float, has_legacy_octal;\n    int atod_type = flags & ATOD_TYPE_MASK;\n    char buf1[64], *buf;\n    int i, j, len;\n    BOOL buf_allocated = FALSE;\n    JSValue val;\n    \n    /* optional separator between digits */\n    sep = (flags & ATOD_ACCEPT_UNDERSCORES) ? '_' : 256;\n    has_legacy_octal = FALSE;\n    \n    p = str;\n    p_start = p;\n    is_neg = 0;\n    if (p[0] == '+') {\n        p++;\n        p_start++;\n        if (!(flags & ATOD_ACCEPT_PREFIX_AFTER_SIGN))\n            goto no_radix_prefix;\n    } else if (p[0] == '-') {\n        p++;\n        p_start++;\n        is_neg = 1;\n        if (!(flags & ATOD_ACCEPT_PREFIX_AFTER_SIGN))\n            goto no_radix_prefix;\n    }\n    if (p[0] == '0') {\n        if ((p[1] == 'x' || p[1] == 'X') &&\n            (radix == 0 || radix == 16)) {\n            p += 2;\n            radix = 16;\n        } else if ((p[1] == 'o' || p[1] == 'O') &&\n                   radix == 0 && (flags & ATOD_ACCEPT_BIN_OCT)) {\n            p += 2;\n            radix = 8;\n        } else if ((p[1] == 'b' || p[1] == 'B') &&\n                   radix == 0 && (flags & ATOD_ACCEPT_BIN_OCT)) {\n            p += 2;\n            radix = 2;\n        } else if ((p[1] >= '0' && p[1] <= '9') &&\n                   radix == 0 && (flags & ATOD_ACCEPT_LEGACY_OCTAL)) {\n            int i;\n            has_legacy_octal = TRUE;\n            sep = 256;\n            for (i = 1; (p[i] >= '0' && p[i] <= '7'); i++)\n                continue;\n            if (p[i] == '8' || p[i] == '9')\n                goto no_prefix;\n            p += 1;\n            radix = 8;\n        } else {\n            goto no_prefix;\n        }\n        /* there must be a digit after the prefix */\n        if (to_digit((uint8_t)*p) >= radix)\n            goto fail;\n    no_prefix: ;\n    } else {\n no_radix_prefix:\n        if (!(flags & ATOD_INT_ONLY) &&\n            (atod_type == ATOD_TYPE_FLOAT64 ||\n             atod_type == ATOD_TYPE_BIG_FLOAT) &&\n            strstart(p, \"Infinity\", &p)) {\n#ifdef CONFIG_BIGNUM\n            if (atod_type == ATOD_TYPE_BIG_FLOAT) {\n                bf_t *a;\n                val = JS_NewBigFloat(ctx);\n                if (JS_IsException(val))\n                    goto done;\n                a = JS_GetBigFloat(val);\n                bf_set_inf(a, is_neg);\n            } else\n#endif\n            {\n                double d = 1.0 / 0.0;\n                if (is_neg)\n                    d = -d;\n                val = JS_NewFloat64(ctx, d);\n            }\n            goto done;\n        }\n    }\n    if (radix == 0)\n        radix = 10;\n    is_float = FALSE;\n    p_start = p;\n    while (to_digit((uint8_t)*p) < radix\n           ||  (*p == sep && (radix != 10 ||\n                              p != p_start + 1 || p[-1] != '0') &&\n                to_digit((uint8_t)p[1]) < radix)) {\n        p++;\n    }\n    if (!(flags & ATOD_INT_ONLY)) {\n        if (*p == '.' && (p > p_start || to_digit((uint8_t)p[1]) < radix)) {\n            is_float = TRUE;\n            p++;\n            if (*p == sep)\n                goto fail;\n            while (to_digit((uint8_t)*p) < radix ||\n                   (*p == sep && to_digit((uint8_t)p[1]) < radix))\n                p++;\n        }\n        if (p > p_start &&\n            (((*p == 'e' || *p == 'E') && radix == 10) ||\n             ((*p == 'p' || *p == 'P') && (radix == 2 || radix == 8 || radix == 16)))) {\n            const char *p1 = p + 1;\n            is_float = TRUE;\n            if (*p1 == '+') {\n                p1++;\n            } else if (*p1 == '-') {\n                p1++;\n            }\n            if (is_digit((uint8_t)*p1)) {\n                p = p1 + 1;\n                while (is_digit((uint8_t)*p) || (*p == sep && is_digit((uint8_t)p[1])))\n                    p++;\n            }\n        }\n    }\n    if (p == p_start)\n        goto fail;\n\n    buf = buf1;\n    buf_allocated = FALSE;\n    len = p - p_start;\n    if (unlikely((len + 2) > sizeof(buf1))) {\n        buf = js_malloc_rt(ctx->rt, len + 2); /* no exception raised */\n        if (!buf)\n            goto mem_error;\n        buf_allocated = TRUE;\n    }\n    /* remove the separators and the radix prefixes */\n    j = 0;\n    if (is_neg)\n        buf[j++] = '-';\n    for (i = 0; i < len; i++) {\n        if (p_start[i] != '_')\n            buf[j++] = p_start[i];\n    }\n    buf[j] = '\\0';\n\n#ifdef CONFIG_BIGNUM\n    if (flags & ATOD_ACCEPT_SUFFIX) {\n        if (*p == 'n') {\n            p++;\n            atod_type = ATOD_TYPE_BIG_INT;\n        } else if (*p == 'l') {\n            p++;\n            atod_type = ATOD_TYPE_BIG_FLOAT;\n        } else if (*p == 'm') {\n            p++;\n            atod_type = ATOD_TYPE_BIG_DECIMAL;\n        } else {\n            if (flags & ATOD_MODE_BIGINT) {\n                if (!is_float)\n                    atod_type = ATOD_TYPE_BIG_INT;\n                if (has_legacy_octal)\n                    goto fail;\n            } else {\n                if (is_float && radix != 10)\n                    goto fail;\n            }\n        }\n    } else {\n        if (atod_type == ATOD_TYPE_FLOAT64) {\n            if (flags & ATOD_MODE_BIGINT) {\n                if (!is_float)\n                    atod_type = ATOD_TYPE_BIG_INT;\n                if (has_legacy_octal)\n                    goto fail;\n            } else {\n                if (is_float && radix != 10)\n                    goto fail;\n            }\n        }\n    }\n\n    switch(atod_type) {\n    case ATOD_TYPE_FLOAT64:\n        {\n            double d;\n            d = js_strtod(buf, radix, is_float);\n            /* return int or float64 */\n            val = JS_NewFloat64(ctx, d);\n        }\n        break;\n    case ATOD_TYPE_BIG_INT:\n        if (has_legacy_octal || is_float)\n            goto fail;\n        val = ctx->rt->bigint_ops.from_string(ctx, buf, radix, flags, NULL);\n        break;\n    case ATOD_TYPE_BIG_FLOAT:\n        if (has_legacy_octal)\n            goto fail;\n        val = ctx->rt->bigfloat_ops.from_string(ctx, buf, radix, flags,\n                                                pexponent);\n        break;\n    case ATOD_TYPE_BIG_DECIMAL:\n        if (radix != 10)\n            goto fail;\n        val = ctx->rt->bigdecimal_ops.from_string(ctx, buf, radix, flags, NULL);\n        break;\n    default:\n        abort();\n    }\n#else\n    {\n        double d;\n        (void)has_legacy_octal;\n        if (is_float && radix != 10)\n            goto fail;\n        d = js_strtod(buf, radix, is_float);\n        val = JS_NewFloat64(ctx, d);\n    }\n#endif\n    \ndone:\n    if (buf_allocated)\n        js_free_rt(ctx->rt, buf);\n    if (pp)\n        *pp = p;\n    return val;\n fail:\n    val = JS_NAN;\n    goto done;\n mem_error:\n    val = JS_ThrowOutOfMemory(ctx);\n    goto done;\n}\n\n#ifdef CONFIG_BIGNUM\nstatic JSValue js_atof(JSContext *ctx, const char *str, const char **pp,\n                       int radix, int flags)\n{\n    return js_atof2(ctx, str, pp, radix, flags, NULL);\n}\n#endif\n\ntypedef enum JSToNumberHintEnum {\n    TON_FLAG_NUMBER,\n    TON_FLAG_NUMERIC,\n} JSToNumberHintEnum;\n\nstatic JSValue JS_ToNumberHintFree(JSContext *ctx, JSValue val,\n                                   JSToNumberHintEnum flag)\n{\n    uint32_t tag;\n    JSValue ret;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_DECIMAL:\n        if (flag != TON_FLAG_NUMERIC) {\n            JS_FreeValue(ctx, val);\n            return JS_ThrowTypeError(ctx, \"cannot convert bigdecimal to number\");\n        }\n        ret = val;\n        break;\n    case JS_TAG_BIG_INT:\n        if (flag != TON_FLAG_NUMERIC) {\n            JS_FreeValue(ctx, val);\n            return JS_ThrowTypeError(ctx, \"cannot convert bigint to number\");\n        }\n        ret = val;\n        break;\n    case JS_TAG_BIG_FLOAT:\n        if (flag != TON_FLAG_NUMERIC) {\n            JS_FreeValue(ctx, val);\n            return JS_ThrowTypeError(ctx, \"cannot convert bigfloat to number\");\n        }\n        ret = val;\n        break;\n#endif\n    case JS_TAG_FLOAT64:\n    case JS_TAG_INT:\n    case JS_TAG_EXCEPTION:\n        ret = val;\n        break;\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n        ret = JS_NewInt32(ctx, JS_VALUE_GET_INT(val));\n        break;\n    case JS_TAG_UNDEFINED:\n        ret = JS_NAN;\n        break;\n    case JS_TAG_OBJECT:\n        val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER);\n        if (JS_IsException(val))\n            return JS_EXCEPTION;\n        goto redo;\n    case JS_TAG_STRING:\n        {\n            const char *str;\n            const char *p;\n            size_t len;\n            \n            str = JS_ToCStringLen(ctx, &len, val);\n            JS_FreeValue(ctx, val);\n            if (!str)\n                return JS_EXCEPTION;\n            p = str;\n            p += skip_spaces(p);\n            if ((p - str) == len) {\n                ret = JS_NewInt32(ctx, 0);\n            } else {\n                int flags = ATOD_ACCEPT_BIN_OCT;\n                ret = js_atof(ctx, p, &p, 0, flags);\n                if (!JS_IsException(ret)) {\n                    p += skip_spaces(p);\n                    if ((p - str) != len) {\n                        JS_FreeValue(ctx, ret);\n                        ret = JS_NAN;\n                    }\n                }\n            }\n            JS_FreeCString(ctx, str);\n        }\n        break;\n    case JS_TAG_SYMBOL:\n        JS_FreeValue(ctx, val);\n        return JS_ThrowTypeError(ctx, \"cannot convert symbol to number\");\n    default:\n        JS_FreeValue(ctx, val);\n        ret = JS_NAN;\n        break;\n    }\n    return ret;\n}\n\nstatic JSValue JS_ToNumberFree(JSContext *ctx, JSValue val)\n{\n    return JS_ToNumberHintFree(ctx, val, TON_FLAG_NUMBER);\n}\n\nstatic JSValue JS_ToNumericFree(JSContext *ctx, JSValue val)\n{\n    return JS_ToNumberHintFree(ctx, val, TON_FLAG_NUMERIC);\n}\n\nstatic JSValue JS_ToNumeric(JSContext *ctx, JSValueConst val)\n{\n    return JS_ToNumericFree(ctx, JS_DupValue(ctx, val));\n}\n\nstatic __exception int __JS_ToFloat64Free(JSContext *ctx, double *pres,\n                                          JSValue val)\n{\n    double d;\n    uint32_t tag;\n\n    val = JS_ToNumberFree(ctx, val);\n    if (JS_IsException(val)) {\n        *pres = JS_FLOAT64_NAN;\n        return -1;\n    }\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n        d = JS_VALUE_GET_INT(val);\n        break;\n    case JS_TAG_FLOAT64:\n        d = JS_VALUE_GET_FLOAT64(val);\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            /* XXX: there can be a double rounding issue with some\n               primitives (such as JS_ToUint8ClampFree()), but it is\n               not critical to fix it. */\n            bf_get_float64(&p->num, &d, BF_RNDN);\n            JS_FreeValue(ctx, val);\n        }\n        break;\n#endif\n    default:\n        abort();\n    }\n    *pres = d;\n    return 0;\n}\n\nstatic inline int JS_ToFloat64Free(JSContext *ctx, double *pres, JSValue val)\n{\n    uint32_t tag;\n\n    tag = JS_VALUE_GET_TAG(val);\n    if (tag <= JS_TAG_NULL) {\n        *pres = JS_VALUE_GET_INT(val);\n        return 0;\n    } else if (JS_TAG_IS_FLOAT64(tag)) {\n        *pres = JS_VALUE_GET_FLOAT64(val);\n        return 0;\n    } else {\n        return __JS_ToFloat64Free(ctx, pres, val);\n    }\n}\n\nint JS_ToFloat64(JSContext *ctx, double *pres, JSValueConst val)\n{\n    return JS_ToFloat64Free(ctx, pres, JS_DupValue(ctx, val));\n}\n\nstatic JSValue JS_ToNumber(JSContext *ctx, JSValueConst val)\n{\n    return JS_ToNumberFree(ctx, JS_DupValue(ctx, val));\n}\n\n/* same as JS_ToNumber() but return 0 in case of NaN/Undefined */\nstatic __maybe_unused JSValue JS_ToIntegerFree(JSContext *ctx, JSValue val)\n{\n    uint32_t tag;\n    JSValue ret;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        ret = JS_NewInt32(ctx, JS_VALUE_GET_INT(val));\n        break;\n    case JS_TAG_FLOAT64:\n        {\n            double d = JS_VALUE_GET_FLOAT64(val);\n            if (isnan(d)) {\n                ret = JS_NewInt32(ctx, 0);\n            } else {\n                /* convert -0 to +0 */\n                d = trunc(d) + 0.0;\n                ret = JS_NewFloat64(ctx, d);\n            }\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_FLOAT:\n        {\n            bf_t a_s, *a, r_s, *r = &r_s;\n            BOOL is_nan;\n\n            a = JS_ToBigFloat(ctx, &a_s, val);\n            if (!bf_is_finite(a)) {\n                is_nan = bf_is_nan(a);\n                if (is_nan)\n                    ret = JS_NewInt32(ctx, 0);\n                else\n                    ret = JS_DupValue(ctx, val);\n            } else {\n                ret = JS_NewBigInt(ctx);\n                if (!JS_IsException(ret)) {\n                    r = JS_GetBigInt(ret);\n                    bf_set(r, a);\n                    bf_rint(r, BF_RNDZ);\n                    ret = JS_CompactBigInt(ctx, ret);\n                }\n            }\n            if (a == &a_s)\n                bf_delete(a);\n            JS_FreeValue(ctx, val);\n        }\n        break;\n#endif\n    default:\n        val = JS_ToNumberFree(ctx, val);\n        if (JS_IsException(val))\n            return val;\n        goto redo;\n    }\n    return ret;\n}\n\n/* Note: the integer value is satured to 32 bits */\nstatic int JS_ToInt32SatFree(JSContext *ctx, int *pres, JSValue val)\n{\n    uint32_t tag;\n    int ret;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        ret = JS_VALUE_GET_INT(val);\n        break;\n    case JS_TAG_EXCEPTION:\n        *pres = 0;\n        return -1;\n    case JS_TAG_FLOAT64:\n        {\n            double d = JS_VALUE_GET_FLOAT64(val);\n            if (isnan(d)) {\n                ret = 0;\n            } else {\n                if (d < INT32_MIN)\n                    ret = INT32_MIN;\n                else if (d > INT32_MAX)\n                    ret = INT32_MAX;\n                else\n                    ret = (int)d;\n            }\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            bf_get_int32(&ret, &p->num, 0);\n            JS_FreeValue(ctx, val);\n        }\n        break;\n#endif\n    default:\n        val = JS_ToNumberFree(ctx, val);\n        if (JS_IsException(val)) {\n            *pres = 0;\n            return -1;\n        }\n        goto redo;\n    }\n    *pres = ret;\n    return 0;\n}\n\nint JS_ToInt32Sat(JSContext *ctx, int *pres, JSValueConst val)\n{\n    return JS_ToInt32SatFree(ctx, pres, JS_DupValue(ctx, val));\n}\n\nint JS_ToInt32Clamp(JSContext *ctx, int *pres, JSValueConst val,\n                    int min, int max, int min_offset)\n{\n    int res = JS_ToInt32SatFree(ctx, pres, JS_DupValue(ctx, val));\n    if (res == 0) {\n        if (*pres < min) {\n            *pres += min_offset;\n            if (*pres < min)\n                *pres = min;\n        } else {\n            if (*pres > max)\n                *pres = max;\n        }\n    }\n    return res;\n}\n\nstatic int JS_ToInt64SatFree(JSContext *ctx, int64_t *pres, JSValue val)\n{\n    uint32_t tag;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        *pres = JS_VALUE_GET_INT(val);\n        return 0;\n    case JS_TAG_EXCEPTION:\n        *pres = 0;\n        return -1;\n    case JS_TAG_FLOAT64:\n        {\n            double d = JS_VALUE_GET_FLOAT64(val);\n            if (isnan(d)) {\n                *pres = 0;\n            } else {\n                if (d < INT64_MIN)\n                    *pres = INT64_MIN;\n                else if (d > INT64_MAX)\n                    *pres = INT64_MAX;\n                else\n                    *pres = (int64_t)d;\n            }\n        }\n        return 0;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            bf_get_int64(pres, &p->num, 0);\n            JS_FreeValue(ctx, val);\n        }\n        return 0;\n#endif\n    default:\n        val = JS_ToNumberFree(ctx, val);\n        if (JS_IsException(val)) {\n            *pres = 0;\n            return -1;\n        }\n        goto redo;\n    }\n}\n\nint JS_ToInt64Sat(JSContext *ctx, int64_t *pres, JSValueConst val)\n{\n    return JS_ToInt64SatFree(ctx, pres, JS_DupValue(ctx, val));\n}\n\nint JS_ToInt64Clamp(JSContext *ctx, int64_t *pres, JSValueConst val,\n                    int64_t min, int64_t max, int64_t neg_offset)\n{\n    int res = JS_ToInt64SatFree(ctx, pres, JS_DupValue(ctx, val));\n    if (res == 0) {\n        if (*pres < 0)\n            *pres += neg_offset;\n        if (*pres < min)\n            *pres = min;\n        else if (*pres > max)\n            *pres = max;\n    }\n    return res;\n}\n\n/* Same as JS_ToInt32Free() but with a 64 bit result. Return (<0, 0)\n   in case of exception */\nstatic int JS_ToInt64Free(JSContext *ctx, int64_t *pres, JSValue val)\n{\n    uint32_t tag;\n    int64_t ret;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        ret = JS_VALUE_GET_INT(val);\n        break;\n    case JS_TAG_FLOAT64:\n        {\n            JSFloat64Union u;\n            double d;\n            int e;\n            d = JS_VALUE_GET_FLOAT64(val);\n            u.d = d;\n            /* we avoid doing fmod(x, 2^64) */\n            e = (u.u64 >> 52) & 0x7ff;\n            if (likely(e <= (1023 + 62))) {\n                /* fast case */\n                ret = (int64_t)d;\n            } else if (e <= (1023 + 62 + 53)) {\n                uint64_t v;\n                /* remainder modulo 2^64 */\n                v = (u.u64 & (((uint64_t)1 << 52) - 1)) | ((uint64_t)1 << 52);\n                ret = v << ((e - 1023) - 52);\n                /* take the sign into account */\n                if (u.u64 >> 63)\n                    ret = -ret;\n            } else {\n                ret = 0; /* also handles NaN and +inf */\n            }\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            bf_get_int64(&ret, &p->num, BF_GET_INT_MOD);\n            JS_FreeValue(ctx, val);\n        }\n        break;\n#endif\n    default:\n        val = JS_ToNumberFree(ctx, val);\n        if (JS_IsException(val)) {\n            *pres = 0;\n            return -1;\n        }\n        goto redo;\n    }\n    *pres = ret;\n    return 0;\n}\n\nint JS_ToInt64(JSContext *ctx, int64_t *pres, JSValueConst val)\n{\n    return JS_ToInt64Free(ctx, pres, JS_DupValue(ctx, val));\n}\n\nint JS_ToInt64Ext(JSContext *ctx, int64_t *pres, JSValueConst val)\n{\n    if (JS_IsBigInt(ctx, val))\n        return JS_ToBigInt64(ctx, pres, val);\n    else\n        return JS_ToInt64(ctx, pres, val);\n}\n\n/* return (<0, 0) in case of exception */\nstatic int JS_ToInt32Free(JSContext *ctx, int32_t *pres, JSValue val)\n{\n    uint32_t tag;\n    int32_t ret;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        ret = JS_VALUE_GET_INT(val);\n        break;\n    case JS_TAG_FLOAT64:\n        {\n            JSFloat64Union u;\n            double d;\n            int e;\n            d = JS_VALUE_GET_FLOAT64(val);\n            u.d = d;\n            /* we avoid doing fmod(x, 2^32) */\n            e = (u.u64 >> 52) & 0x7ff;\n            if (likely(e <= (1023 + 30))) {\n                /* fast case */\n                ret = (int32_t)d;\n            } else if (e <= (1023 + 30 + 53)) {\n                uint64_t v;\n                /* remainder modulo 2^32 */\n                v = (u.u64 & (((uint64_t)1 << 52) - 1)) | ((uint64_t)1 << 52);\n                v = v << ((e - 1023) - 52 + 32);\n                ret = v >> 32;\n                /* take the sign into account */\n                if (u.u64 >> 63)\n                    ret = -ret;\n            } else {\n                ret = 0; /* also handles NaN and +inf */\n            }\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            bf_get_int32(&ret, &p->num, BF_GET_INT_MOD);\n            JS_FreeValue(ctx, val);\n        }\n        break;\n#endif\n    default:\n        val = JS_ToNumberFree(ctx, val);\n        if (JS_IsException(val)) {\n            *pres = 0;\n            return -1;\n        }\n        goto redo;\n    }\n    *pres = ret;\n    return 0;\n}\n\nint JS_ToInt32(JSContext *ctx, int32_t *pres, JSValueConst val)\n{\n    return JS_ToInt32Free(ctx, pres, JS_DupValue(ctx, val));\n}\n\nstatic inline int JS_ToUint32Free(JSContext *ctx, uint32_t *pres, JSValue val)\n{\n    return JS_ToInt32Free(ctx, (int32_t *)pres, val);\n}\n\nstatic int JS_ToUint8ClampFree(JSContext *ctx, int32_t *pres, JSValue val)\n{\n    uint32_t tag;\n    int res;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        res = JS_VALUE_GET_INT(val);\n#ifdef CONFIG_BIGNUM\n    int_clamp:\n#endif\n        res = max_int(0, min_int(255, res));\n        break;\n    case JS_TAG_FLOAT64:\n        {\n            double d = JS_VALUE_GET_FLOAT64(val);\n            if (isnan(d)) {\n                res = 0;\n            } else {\n                if (d < 0)\n                    res = 0;\n                else if (d > 255)\n                    res = 255;\n                else\n                    res = lrint(d);\n            }\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            bf_t r_s, *r = &r_s;\n            bf_init(ctx->bf_ctx, r);\n            bf_set(r, &p->num);\n            bf_rint(r, BF_RNDN);\n            bf_get_int32(&res, r, 0);\n            bf_delete(r);\n            JS_FreeValue(ctx, val);\n        }\n        goto int_clamp;\n#endif\n    default:\n        val = JS_ToNumberFree(ctx, val);\n        if (JS_IsException(val)) {\n            *pres = 0;\n            return -1;\n        }\n        goto redo;\n    }\n    *pres = res;\n    return 0;\n}\n\nstatic __exception int JS_ToArrayLengthFree(JSContext *ctx, uint32_t *plen,\n                                            JSValue val, BOOL is_array_ctor)\n{\n    uint32_t tag, len;\n\n    tag = JS_VALUE_GET_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n        {\n            int v;\n            v = JS_VALUE_GET_INT(val);\n            if (v < 0)\n                goto fail;\n            len = v;\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            bf_t a;\n            BOOL res;\n            bf_get_int32((int32_t *)&len, &p->num, BF_GET_INT_MOD);\n            bf_init(ctx->bf_ctx, &a);\n            bf_set_ui(&a, len);\n            res = bf_cmp_eq(&a, &p->num);\n            bf_delete(&a);\n            JS_FreeValue(ctx, val);\n            if (!res)\n                goto fail;\n        }\n        break;\n#endif\n    default:\n        if (JS_TAG_IS_FLOAT64(tag)) {\n            double d;\n            d = JS_VALUE_GET_FLOAT64(val);\n            len = (uint32_t)d;\n            if (len != d)\n                goto fail;\n        } else {\n            uint32_t len1;\n\n            if (is_array_ctor) {\n                val = JS_ToNumberFree(ctx, val);\n                if (JS_IsException(val))\n                    return -1;\n                /* cannot recurse because val is a number */\n                if (JS_ToArrayLengthFree(ctx, &len, val, TRUE))\n                    return -1;\n            } else {\n                /* legacy behavior: must do the conversion twice and compare */\n                if (JS_ToUint32(ctx, &len, val)) {\n                    JS_FreeValue(ctx, val);\n                    return -1;\n                }\n                val = JS_ToNumberFree(ctx, val);\n                if (JS_IsException(val))\n                    return -1;\n                /* cannot recurse because val is a number */\n                if (JS_ToArrayLengthFree(ctx, &len1, val, FALSE))\n                    return -1;\n                if (len1 != len) {\n                fail:\n                    JS_ThrowRangeError(ctx, \"invalid array length\");\n                    return -1;\n                }\n            }\n        }\n        break;\n    }\n    *plen = len;\n    return 0;\n}\n\n#define MAX_SAFE_INTEGER (((int64_t)1 << 53) - 1)\n\nstatic BOOL is_safe_integer(double d)\n{\n    return isfinite(d) && floor(d) == d &&\n        fabs(d) <= (double)MAX_SAFE_INTEGER;\n}\n\nint JS_ToIndex(JSContext *ctx, uint64_t *plen, JSValueConst val)\n{\n    int64_t v;\n    if (JS_ToInt64Sat(ctx, &v, val))\n        return -1;\n    if (v < 0 || v > MAX_SAFE_INTEGER) {\n        JS_ThrowRangeError(ctx, \"invalid array index\");\n        *plen = 0;\n        return -1;\n    }\n    *plen = v;\n    return 0;\n}\n\n/* convert a value to a length between 0 and MAX_SAFE_INTEGER.\n   return -1 for exception */\nstatic __exception int JS_ToLengthFree(JSContext *ctx, int64_t *plen,\n                                       JSValue val)\n{\n    int res = JS_ToInt64Clamp(ctx, plen, val, 0, MAX_SAFE_INTEGER, 0);\n    JS_FreeValue(ctx, val);\n    return res;\n}\n\n/* Note: can return an exception */\nstatic int JS_NumberIsInteger(JSContext *ctx, JSValueConst val)\n{\n    double d;\n    if (!JS_IsNumber(val))\n        return FALSE;\n    if (unlikely(JS_ToFloat64(ctx, &d, val)))\n        return -1;\n    return isfinite(d) && floor(d) == d;\n}\n\nstatic BOOL JS_NumberIsNegativeOrMinusZero(JSContext *ctx, JSValueConst val)\n{\n    uint32_t tag;\n\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n        {\n            int v;\n            v = JS_VALUE_GET_INT(val);\n            return (v < 0);\n        }\n    case JS_TAG_FLOAT64:\n        {\n            JSFloat64Union u;\n            u.d = JS_VALUE_GET_FLOAT64(val);\n            return (u.u64 >> 63);\n        }\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            /* Note: integer zeros are not necessarily positive */\n            return p->num.sign && !bf_is_zero(&p->num);\n        }\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            return p->num.sign;\n        }\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        {\n            JSBigDecimal *p = JS_VALUE_GET_PTR(val);\n            return p->num.sign;\n        }\n        break;\n#endif\n    default:\n        return FALSE;\n    }\n}\n\n#ifdef CONFIG_BIGNUM\n\nstatic JSValue js_bigint_to_string1(JSContext *ctx, JSValueConst val, int radix)\n{\n    JSValue ret;\n    bf_t a_s, *a;\n    char *str;\n    int saved_sign;\n\n    a = JS_ToBigInt(ctx, &a_s, val);\n    if (!a)\n        return JS_EXCEPTION;\n    saved_sign = a->sign;\n    if (a->expn == BF_EXP_ZERO)\n        a->sign = 0;\n    str = bf_ftoa(NULL, a, radix, 0, BF_RNDZ | BF_FTOA_FORMAT_FRAC |\n                  BF_FTOA_JS_QUIRKS);\n    a->sign = saved_sign;\n    JS_FreeBigInt(ctx, a, &a_s);\n    if (!str)\n        return JS_ThrowOutOfMemory(ctx);\n    ret = JS_NewString(ctx, str);\n    bf_free(ctx->bf_ctx, str);\n    return ret;\n}\n\nstatic JSValue js_bigint_to_string(JSContext *ctx, JSValueConst val)\n{\n    return js_bigint_to_string1(ctx, val, 10);\n}\n\nstatic JSValue js_ftoa(JSContext *ctx, JSValueConst val1, int radix,\n                       limb_t prec, bf_flags_t flags)\n{\n    JSValue val, ret;\n    bf_t a_s, *a;\n    char *str;\n    int saved_sign;\n\n    val = JS_ToNumeric(ctx, val1);\n    if (JS_IsException(val))\n        return val;\n    a = JS_ToBigFloat(ctx, &a_s, val);\n    saved_sign = a->sign;\n    if (a->expn == BF_EXP_ZERO)\n        a->sign = 0;\n    flags |= BF_FTOA_JS_QUIRKS;\n    if ((flags & BF_FTOA_FORMAT_MASK) == BF_FTOA_FORMAT_FREE_MIN) {\n        /* Note: for floating point numbers with a radix which is not\n           a power of two, the current precision is used to compute\n           the number of digits. */\n        if ((radix & (radix - 1)) != 0) {\n            bf_t r_s, *r = &r_s;\n            int prec, flags1;\n            /* must round first */\n            if (JS_VALUE_GET_TAG(val) == JS_TAG_BIG_FLOAT) {\n                prec = ctx->fp_env.prec;\n                flags1 = ctx->fp_env.flags &\n                    (BF_FLAG_SUBNORMAL | (BF_EXP_BITS_MASK << BF_EXP_BITS_SHIFT));\n            } else {\n                prec = 53;\n                flags1 = bf_set_exp_bits(11) | BF_FLAG_SUBNORMAL;\n            }\n            bf_init(ctx->bf_ctx, r);\n            bf_set(r, a);\n            bf_round(r, prec, flags1 | BF_RNDN);\n            str = bf_ftoa(NULL, r, radix, prec, flags1 | flags);\n            bf_delete(r);\n        } else {\n            str = bf_ftoa(NULL, a, radix, BF_PREC_INF, flags);\n        }\n    } else {\n        str = bf_ftoa(NULL, a, radix, prec, flags);\n    }\n    a->sign = saved_sign;\n    if (a == &a_s)\n        bf_delete(a);\n    JS_FreeValue(ctx, val);\n    if (!str)\n        return JS_ThrowOutOfMemory(ctx);\n    ret = JS_NewString(ctx, str);\n    bf_free(ctx->bf_ctx, str);\n    return ret;\n}\n\nstatic JSValue js_bigfloat_to_string(JSContext *ctx, JSValueConst val)\n{\n    return js_ftoa(ctx, val, 10, 0, BF_RNDN | BF_FTOA_FORMAT_FREE_MIN);\n}\n\nstatic JSValue js_bigdecimal_to_string1(JSContext *ctx, JSValueConst val,\n                                        limb_t prec, int flags)\n{\n    JSValue ret;\n    bfdec_t *a;\n    char *str;\n    int saved_sign;\n\n    a = JS_ToBigDecimal(ctx, val);\n    saved_sign = a->sign;\n    if (a->expn == BF_EXP_ZERO)\n        a->sign = 0;\n    str = bfdec_ftoa(NULL, a, prec, flags | BF_FTOA_JS_QUIRKS);\n    a->sign = saved_sign;\n    if (!str)\n        return JS_ThrowOutOfMemory(ctx);\n    ret = JS_NewString(ctx, str);\n    bf_free(ctx->bf_ctx, str);\n    return ret;\n}\n\nstatic JSValue js_bigdecimal_to_string(JSContext *ctx, JSValueConst val)\n{\n    return js_bigdecimal_to_string1(ctx, val, 0,\n                                    BF_RNDZ | BF_FTOA_FORMAT_FREE);\n}\n\n#endif /* CONFIG_BIGNUM */\n\n/* 2 <= base <= 36 */\nstatic char *i64toa(char *buf_end, int64_t n, unsigned int base)\n{\n    char *q = buf_end;\n    int digit, is_neg;\n\n    is_neg = 0;\n    if (n < 0) {\n        is_neg = 1;\n        n = -n;\n    }\n    *--q = '\\0';\n    do {\n        digit = (uint64_t)n % base;\n        n = (uint64_t)n / base;\n        if (digit < 10)\n            digit += '0';\n        else\n            digit += 'a' - 10;\n        *--q = digit;\n    } while (n != 0);\n    if (is_neg)\n        *--q = '-';\n    return q;\n}\n\n/* buf1 contains the printf result */\nstatic void js_ecvt1(double d, int n_digits, int *decpt, int *sign, char *buf,\n                     int rounding_mode, char *buf1, int buf1_size)\n{\n    if (rounding_mode != FE_TONEAREST)\n        fesetround(rounding_mode);\n    snprintf(buf1, buf1_size, \"%+.*e\", n_digits - 1, d);\n    if (rounding_mode != FE_TONEAREST)\n        fesetround(FE_TONEAREST);\n    *sign = (buf1[0] == '-');\n    /* mantissa */\n    buf[0] = buf1[1];\n    if (n_digits > 1)\n        memcpy(buf + 1, buf1 + 3, n_digits - 1);\n    buf[n_digits] = '\\0';\n    /* exponent */\n    *decpt = atoi(buf1 + n_digits + 2 + (n_digits > 1)) + 1;\n}\n\n/* maximum buffer size for js_dtoa */\n#define JS_DTOA_BUF_SIZE 128\n\n/* needed because ecvt usually limits the number of digits to\n   17. Return the number of digits. */\nstatic int js_ecvt(double d, int n_digits, int *decpt, int *sign, char *buf,\n                   BOOL is_fixed)\n{\n    int rounding_mode;\n    char buf_tmp[JS_DTOA_BUF_SIZE];\n\n    if (!is_fixed) {\n        unsigned int n_digits_min, n_digits_max;\n        /* find the minimum amount of digits (XXX: inefficient but simple) */\n        n_digits_min = 1;\n        n_digits_max = 17;\n        while (n_digits_min < n_digits_max) {\n            n_digits = (n_digits_min + n_digits_max) / 2;\n            js_ecvt1(d, n_digits, decpt, sign, buf, FE_TONEAREST,\n                     buf_tmp, sizeof(buf_tmp));\n            if (strtod(buf_tmp, NULL) == d) {\n                /* no need to keep the trailing zeros */\n                while (n_digits >= 2 && buf[n_digits - 1] == '0')\n                    n_digits--;\n                n_digits_max = n_digits;\n            } else {\n                n_digits_min = n_digits + 1;\n            }\n        }\n        n_digits = n_digits_max;\n        rounding_mode = FE_TONEAREST;\n    } else {\n        rounding_mode = FE_TONEAREST;\n#ifdef CONFIG_PRINTF_RNDN\n        {\n            char buf1[JS_DTOA_BUF_SIZE], buf2[JS_DTOA_BUF_SIZE];\n            int decpt1, sign1, decpt2, sign2;\n            /* The JS rounding is specified as round to nearest ties away\n               from zero (RNDNA), but in printf the \"ties\" case is not\n               specified (for example it is RNDN for glibc, RNDNA for\n               Windows), so we must round manually. */\n            js_ecvt1(d, n_digits + 1, &decpt1, &sign1, buf1, FE_TONEAREST,\n                     buf_tmp, sizeof(buf_tmp));\n            /* XXX: could use 2 digits to reduce the average running time */\n            if (buf1[n_digits] == '5') {\n                js_ecvt1(d, n_digits + 1, &decpt1, &sign1, buf1, FE_DOWNWARD,\n                         buf_tmp, sizeof(buf_tmp));\n                js_ecvt1(d, n_digits + 1, &decpt2, &sign2, buf2, FE_UPWARD,\n                         buf_tmp, sizeof(buf_tmp));\n                if (memcmp(buf1, buf2, n_digits + 1) == 0 && decpt1 == decpt2) {\n                    /* exact result: round away from zero */\n                    if (sign1)\n                        rounding_mode = FE_DOWNWARD;\n                    else\n                        rounding_mode = FE_UPWARD;\n                }\n            }\n        }\n#endif /* CONFIG_PRINTF_RNDN */\n    }\n    js_ecvt1(d, n_digits, decpt, sign, buf, rounding_mode,\n             buf_tmp, sizeof(buf_tmp));\n    return n_digits;\n}\n\nstatic int js_fcvt1(char *buf, int buf_size, double d, int n_digits,\n                    int rounding_mode)\n{\n    int n;\n    if (rounding_mode != FE_TONEAREST)\n        fesetround(rounding_mode);\n    n = snprintf(buf, buf_size, \"%.*f\", n_digits, d);\n    if (rounding_mode != FE_TONEAREST)\n        fesetround(FE_TONEAREST);\n    assert(n < buf_size);\n    return n;\n}\n\nstatic void js_fcvt(char *buf, int buf_size, double d, int n_digits)\n{\n    int rounding_mode;\n    rounding_mode = FE_TONEAREST;\n#ifdef CONFIG_PRINTF_RNDN\n    {\n        int n1, n2;\n        char buf1[JS_DTOA_BUF_SIZE];\n        char buf2[JS_DTOA_BUF_SIZE];\n\n        /* The JS rounding is specified as round to nearest ties away from\n           zero (RNDNA), but in printf the \"ties\" case is not specified\n           (for example it is RNDN for glibc, RNDNA for Windows), so we\n           must round manually. */\n        n1 = js_fcvt1(buf1, sizeof(buf1), d, n_digits + 1, FE_TONEAREST);\n        rounding_mode = FE_TONEAREST;\n        /* XXX: could use 2 digits to reduce the average running time */\n        if (buf1[n1 - 1] == '5') {\n            n1 = js_fcvt1(buf1, sizeof(buf1), d, n_digits + 1, FE_DOWNWARD);\n            n2 = js_fcvt1(buf2, sizeof(buf2), d, n_digits + 1, FE_UPWARD);\n            if (n1 == n2 && memcmp(buf1, buf2, n1) == 0) {\n                /* exact result: round away from zero */\n                if (buf1[0] == '-')\n                    rounding_mode = FE_DOWNWARD;\n                else\n                    rounding_mode = FE_UPWARD;\n            }\n        }\n    }\n#endif /* CONFIG_PRINTF_RNDN */\n    js_fcvt1(buf, buf_size, d, n_digits, rounding_mode);\n}\n\n/* radix != 10 is only supported with flags = JS_DTOA_VAR_FORMAT */\n/* use as many digits as necessary */\n#define JS_DTOA_VAR_FORMAT   (0 << 0)\n/* use n_digits significant digits (1 <= n_digits <= 101) */\n#define JS_DTOA_FIXED_FORMAT (1 << 0)\n/* force fractional format: [-]dd.dd with n_digits fractional digits */\n#define JS_DTOA_FRAC_FORMAT  (2 << 0)\n/* force exponential notation either in fixed or variable format */\n#define JS_DTOA_FORCE_EXP    (1 << 2)\n\n/* XXX: slow and maybe not fully correct. Use libbf when it is fast enough.\n   XXX: radix != 10 is only supported for small integers\n*/\nstatic void js_dtoa1(char *buf, double d, int radix, int n_digits, int flags)\n{\n    char *q;\n\n    if (!isfinite(d)) {\n        if (isnan(d)) {\n            strcpy(buf, \"NaN\");\n        } else {\n            q = buf;\n            if (d < 0)\n                *q++ = '-';\n            strcpy(q, \"Infinity\");\n        }\n    } else if (flags == JS_DTOA_VAR_FORMAT) {\n        int64_t i64;\n        char buf1[70], *ptr;\n        i64 = (int64_t)d;\n        if (d != i64 || i64 > MAX_SAFE_INTEGER || i64 < -MAX_SAFE_INTEGER)\n            goto generic_conv;\n        /* fast path for integers */\n        ptr = i64toa(buf1 + sizeof(buf1), i64, radix);\n        strcpy(buf, ptr);\n    } else {\n        if (d == 0.0)\n            d = 0.0; /* convert -0 to 0 */\n        if (flags == JS_DTOA_FRAC_FORMAT) {\n            js_fcvt(buf, JS_DTOA_BUF_SIZE, d, n_digits);\n        } else {\n            char buf1[JS_DTOA_BUF_SIZE];\n            int sign, decpt, k, n, i, p, n_max;\n            BOOL is_fixed;\n        generic_conv:\n            is_fixed = ((flags & 3) == JS_DTOA_FIXED_FORMAT);\n            if (is_fixed) {\n                n_max = n_digits;\n            } else {\n                n_max = 21;\n            }\n            /* the number has k digits (k >= 1) */\n            k = js_ecvt(d, n_digits, &decpt, &sign, buf1, is_fixed);\n            n = decpt; /* d=10^(n-k)*(buf1) i.e. d= < x.yyyy 10^(n-1) */\n            q = buf;\n            if (sign)\n                *q++ = '-';\n            if (flags & JS_DTOA_FORCE_EXP)\n                goto force_exp;\n            if (n >= 1 && n <= n_max) {\n                if (k <= n) {\n                    memcpy(q, buf1, k);\n                    q += k;\n                    for(i = 0; i < (n - k); i++)\n                        *q++ = '0';\n                    *q = '\\0';\n                } else {\n                    /* k > n */\n                    memcpy(q, buf1, n);\n                    q += n;\n                    *q++ = '.';\n                    for(i = 0; i < (k - n); i++)\n                        *q++ = buf1[n + i];\n                    *q = '\\0';\n                }\n            } else if (n >= -5 && n <= 0) {\n                *q++ = '0';\n                *q++ = '.';\n                for(i = 0; i < -n; i++)\n                    *q++ = '0';\n                memcpy(q, buf1, k);\n                q += k;\n                *q = '\\0';\n            } else {\n            force_exp:\n                /* exponential notation */\n                *q++ = buf1[0];\n                if (k > 1) {\n                    *q++ = '.';\n                    for(i = 1; i < k; i++)\n                        *q++ = buf1[i];\n                }\n                *q++ = 'e';\n                p = n - 1;\n                if (p >= 0)\n                    *q++ = '+';\n                sprintf(q, \"%d\", p);\n            }\n        }\n    }\n}\n\nstatic JSValue js_dtoa(JSContext *ctx,\n                       double d, int radix, int n_digits, int flags)\n{\n    char buf[JS_DTOA_BUF_SIZE];\n    js_dtoa1(buf, d, radix, n_digits, flags);\n    return JS_NewString(ctx, buf);\n}\n\nJSValue JS_ToStringInternal(JSContext *ctx, JSValueConst val, BOOL is_ToPropertyKey)\n{\n    uint32_t tag;\n    const char *str;\n    char buf[32];\n\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_STRING:\n        return JS_DupValue(ctx, val);\n    case JS_TAG_INT:\n        snprintf(buf, sizeof(buf), \"%d\", JS_VALUE_GET_INT(val));\n        str = buf;\n        goto new_string;\n    case JS_TAG_BOOL:\n        return JS_AtomToString(ctx, JS_VALUE_GET_BOOL(val) ?\n                          JS_ATOM_true : JS_ATOM_false);\n    case JS_TAG_NULL:\n        return JS_AtomToString(ctx, JS_ATOM_null);\n    case JS_TAG_UNDEFINED:\n        return JS_AtomToString(ctx, JS_ATOM_undefined);\n    case JS_TAG_EXCEPTION:\n        return JS_EXCEPTION;\n    case JS_TAG_OBJECT:\n        {\n            JSValue val1, ret;\n            val1 = JS_ToPrimitive(ctx, val, HINT_STRING);\n            if (JS_IsException(val1))\n                return val1;\n            ret = JS_ToStringInternal(ctx, val1, is_ToPropertyKey);\n            JS_FreeValue(ctx, val1);\n            return ret;\n        }\n        break;\n    case JS_TAG_FUNCTION_BYTECODE:\n        str = \"[function bytecode]\";\n        goto new_string;\n    case JS_TAG_SYMBOL:\n        if (is_ToPropertyKey) {\n            return JS_DupValue(ctx, val);\n        } else {\n            return JS_ThrowTypeError(ctx, \"cannot convert symbol to string\");\n        }\n    case JS_TAG_FLOAT64:\n        return js_dtoa(ctx, JS_VALUE_GET_FLOAT64(val), 10, 0,\n                       JS_DTOA_VAR_FORMAT);\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n        return ctx->rt->bigint_ops.to_string(ctx, val);\n    case JS_TAG_BIG_FLOAT:\n        return ctx->rt->bigfloat_ops.to_string(ctx, val);\n    case JS_TAG_BIG_DECIMAL:\n        return ctx->rt->bigdecimal_ops.to_string(ctx, val);\n#endif\n    default:\n        str = \"[unsupported type]\";\n    new_string:\n        return JS_NewString(ctx, str);\n    }\n}\n\nJSValue JS_ToString(JSContext *ctx, JSValueConst val)\n{\n    return JS_ToStringInternal(ctx, val, FALSE);\n}\n\nstatic JSValue JS_ToStringFree(JSContext *ctx, JSValue val)\n{\n    JSValue ret;\n    ret = JS_ToString(ctx, val);\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nstatic JSValue JS_ToLocaleStringFree(JSContext *ctx, JSValue val)\n{\n    if (JS_IsUndefined(val) || JS_IsNull(val))\n        return JS_ToStringFree(ctx, val);\n    return JS_InvokeFree(ctx, val, JS_ATOM_toLocaleString, 0, NULL);\n}\n\nJSValue JS_ToPropertyKey(JSContext *ctx, JSValueConst val)\n{\n    return JS_ToStringInternal(ctx, val, TRUE);\n}\n\nstatic JSValue JS_ToStringCheckObject(JSContext *ctx, JSValueConst val)\n{\n    uint32_t tag = JS_VALUE_GET_TAG(val);\n    if (tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED)\n        return JS_ThrowTypeError(ctx, \"null or undefined are forbidden\");\n    return JS_ToString(ctx, val);\n}\n\nstatic JSValue JS_ToQuotedString(JSContext *ctx, JSValueConst val1)\n{\n    JSValue val;\n    JSString *p;\n    int i;\n    uint32_t c;\n    StringBuffer b_s, *b = &b_s;\n    char buf[16];\n\n    val = JS_ToStringCheckObject(ctx, val1);\n    if (JS_IsException(val))\n        return val;\n    p = JS_VALUE_GET_STRING(val);\n\n    if (string_buffer_init(ctx, b, p->len + 2))\n        goto fail;\n\n    if (string_buffer_putc8(b, '\\\"'))\n        goto fail;\n    for(i = 0; i < p->len; ) {\n        c = string_getc(p, &i);\n        switch(c) {\n        case '\\t':\n            c = 't';\n            goto quote;\n        case '\\r':\n            c = 'r';\n            goto quote;\n        case '\\n':\n            c = 'n';\n            goto quote;\n        case '\\b':\n            c = 'b';\n            goto quote;\n        case '\\f':\n            c = 'f';\n            goto quote;\n        case '\\\"':\n        case '\\\\':\n        quote:\n            if (string_buffer_putc8(b, '\\\\'))\n                goto fail;\n            if (string_buffer_putc8(b, c))\n                goto fail;\n            break;\n        default:\n            if (c < 32 || (c >= 0xd800 && c < 0xe000)) {\n                snprintf(buf, sizeof(buf), \"\\\\u%04x\", c);\n                if (string_buffer_puts8(b, buf))\n                    goto fail;\n            } else {\n                if (string_buffer_putc(b, c))\n                    goto fail;\n            }\n            break;\n        }\n    }\n    if (string_buffer_putc8(b, '\\\"'))\n        goto fail;\n    JS_FreeValue(ctx, val);\n    return string_buffer_end(b);\n fail:\n    JS_FreeValue(ctx, val);\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nstatic __maybe_unused void JS_DumpObjectHeader(JSRuntime *rt)\n{\n    printf(\"%14s %4s %4s %14s %10s %s\\n\",\n           \"ADDRESS\", \"REFS\", \"SHRF\", \"PROTO\", \"CLASS\", \"PROPS\");\n}\n\n/* for debug only: dump an object without side effect */\nstatic __maybe_unused void JS_DumpObject(JSRuntime *rt, JSObject *p)\n{\n    uint32_t i;\n    char atom_buf[ATOM_GET_STR_BUF_SIZE];\n    JSShape *sh;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    BOOL is_first = TRUE;\n\n    /* XXX: should encode atoms with special characters */\n    sh = p->shape; /* the shape can be NULL while freeing an object */\n    printf(\"%14p %4d \",\n           (void *)p,\n           p->header.ref_count);\n    if (sh) {\n        printf(\"%3d%c %14p \",\n               sh->header.ref_count,\n               \" *\"[sh->is_hashed],\n               (void *)sh->proto);\n    } else {\n        printf(\"%3s  %14s \", \"-\", \"-\");\n    }\n    printf(\"%10s \",\n           JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), rt->class_array[p->class_id].class_name));\n    if (p->is_exotic && p->fast_array) {\n        printf(\"[ \");\n        for(i = 0; i < p->u.array.count; i++) {\n            if (i != 0)\n                printf(\", \");\n            switch (p->class_id) {\n            case JS_CLASS_ARRAY:\n            case JS_CLASS_ARGUMENTS:\n                JS_DumpValueShort(rt, p->u.array.u.values[i]);\n                break;\n            case JS_CLASS_UINT8C_ARRAY:\n            case JS_CLASS_INT8_ARRAY:\n            case JS_CLASS_UINT8_ARRAY:\n            case JS_CLASS_INT16_ARRAY:\n            case JS_CLASS_UINT16_ARRAY:\n            case JS_CLASS_INT32_ARRAY:\n            case JS_CLASS_UINT32_ARRAY:\n#ifdef CONFIG_BIGNUM\n            case JS_CLASS_BIG_INT64_ARRAY:\n            case JS_CLASS_BIG_UINT64_ARRAY:\n#endif\n            case JS_CLASS_FLOAT32_ARRAY:\n            case JS_CLASS_FLOAT64_ARRAY:\n                {\n                    int size = 1 << typed_array_size_log2(p->class_id);\n                    const uint8_t *b = p->u.array.u.uint8_ptr + i * size;\n                    while (size-- > 0)\n                        printf(\"%02X\", *b++);\n                }\n                break;\n            }\n        }\n        printf(\" ] \");\n    }\n\n    if (sh) {\n        printf(\"{ \");\n        for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) {\n            if (prs->atom != JS_ATOM_NULL) {\n                pr = &p->prop[i];\n                if (!is_first)\n                    printf(\", \");\n                printf(\"%s: \",\n                       JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), prs->atom));\n                if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {\n                    printf(\"[getset %p %p]\", (void *)pr->u.getset.getter,\n                           (void *)pr->u.getset.setter);\n                } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n                    printf(\"[varref %p]\", (void *)pr->u.var_ref);\n                } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n                    printf(\"[autoinit %p %d %p]\",\n                           (void *)js_autoinit_get_realm(pr),\n                           js_autoinit_get_id(pr),\n                           (void *)pr->u.init.opaque);\n                } else {\n                    JS_DumpValueShort(rt, pr->u.value);\n                }\n                is_first = FALSE;\n            }\n        }\n        printf(\" }\");\n    }\n    \n    if (js_class_has_bytecode(p->class_id)) {\n        JSFunctionBytecode *b = p->u.func.function_bytecode;\n        JSVarRef **var_refs;\n        if (b->closure_var_count) {\n            var_refs = p->u.func.var_refs;\n            printf(\" Closure:\");\n            for(i = 0; i < b->closure_var_count; i++) {\n                printf(\" \");\n                JS_DumpValueShort(rt, var_refs[i]->value);\n            }\n            if (p->u.func.home_object) {\n                printf(\" HomeObject: \");\n                JS_DumpValueShort(rt, JS_MKPTR(JS_TAG_OBJECT, p->u.func.home_object));\n            }\n        }\n    }\n    printf(\"\\n\");\n}\n\nstatic __maybe_unused void JS_DumpGCObject(JSRuntime *rt, JSGCObjectHeader *p)\n{\n    if (p->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT) {\n        JS_DumpObject(rt, (JSObject *)p);\n    } else {\n        printf(\"%14p %4d \",\n               (void *)p,\n               p->ref_count);\n        switch(p->gc_obj_type) {\n        case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE:\n            printf(\"[function bytecode]\");\n            break;\n        case JS_GC_OBJ_TYPE_SHAPE:\n            printf(\"[shape]\");\n            break;\n        case JS_GC_OBJ_TYPE_VAR_REF:\n            printf(\"[var_ref]\");\n            break;\n        case JS_GC_OBJ_TYPE_ASYNC_FUNCTION:\n            printf(\"[async_function]\");\n            break;\n        case JS_GC_OBJ_TYPE_JS_CONTEXT:\n            printf(\"[js_context]\");\n            break;\n        default:\n            printf(\"[unknown %d]\", p->gc_obj_type);\n            break;\n        }\n        printf(\"\\n\");\n    }\n}\n\nstatic __maybe_unused void JS_DumpValueShort(JSRuntime *rt,\n                                                      JSValueConst val)\n{\n    uint32_t tag = JS_VALUE_GET_NORM_TAG(val);\n    const char *str;\n\n    switch(tag) {\n    case JS_TAG_INT:\n        printf(\"%d\", JS_VALUE_GET_INT(val));\n        break;\n    case JS_TAG_BOOL:\n        if (JS_VALUE_GET_BOOL(val))\n            str = \"true\";\n        else\n            str = \"false\";\n        goto print_str;\n    case JS_TAG_NULL:\n        str = \"null\";\n        goto print_str;\n    case JS_TAG_EXCEPTION:\n        str = \"exception\";\n        goto print_str;\n    case JS_TAG_UNINITIALIZED:\n        str = \"uninitialized\";\n        goto print_str;\n    case JS_TAG_UNDEFINED:\n        str = \"undefined\";\n    print_str:\n        printf(\"%s\", str);\n        break;\n    case JS_TAG_FLOAT64:\n        printf(\"%.14g\", JS_VALUE_GET_FLOAT64(val));\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            char *str;\n            str = bf_ftoa(NULL, &p->num, 10, 0,\n                          BF_RNDZ | BF_FTOA_FORMAT_FRAC);\n            printf(\"%sn\", str);\n            bf_realloc(&rt->bf_ctx, str, 0);\n        }\n        break;\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            char *str;\n            str = bf_ftoa(NULL, &p->num, 16, BF_PREC_INF,\n                          BF_RNDZ | BF_FTOA_FORMAT_FREE | BF_FTOA_ADD_PREFIX);\n            printf(\"%sl\", str);\n            bf_free(&rt->bf_ctx, str);\n        }\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        {\n            JSBigDecimal *p = JS_VALUE_GET_PTR(val);\n            char *str;\n            str = bfdec_ftoa(NULL, &p->num, BF_PREC_INF,\n                             BF_RNDZ | BF_FTOA_FORMAT_FREE);\n            printf(\"%sm\", str);\n            bf_free(&rt->bf_ctx, str);\n        }\n        break;\n#endif\n    case JS_TAG_STRING:\n        {\n            JSString *p;\n            p = JS_VALUE_GET_STRING(val);\n            JS_DumpString(rt, p);\n        }\n        break;\n    case JS_TAG_FUNCTION_BYTECODE:\n        {\n            JSFunctionBytecode *b = JS_VALUE_GET_PTR(val);\n            char buf[ATOM_GET_STR_BUF_SIZE];\n            printf(\"[bytecode %s]\", JS_AtomGetStrRT(rt, buf, sizeof(buf), b->func_name));\n        }\n        break;\n    case JS_TAG_OBJECT:\n        {\n            JSObject *p = JS_VALUE_GET_OBJ(val);\n            JSAtom atom = rt->class_array[p->class_id].class_name;\n            char atom_buf[ATOM_GET_STR_BUF_SIZE];\n            printf(\"[%s %p]\",\n                   JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), atom), (void *)p);\n        }\n        break;\n    case JS_TAG_SYMBOL:\n        {\n            JSAtomStruct *p = JS_VALUE_GET_PTR(val);\n            char atom_buf[ATOM_GET_STR_BUF_SIZE];\n            printf(\"Symbol(%s)\",\n                   JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), js_get_atom_index(rt, p)));\n        }\n        break;\n    case JS_TAG_MODULE:\n        printf(\"[module]\");\n        break;\n    default:\n        printf(\"[unknown tag %d]\", tag);\n        break;\n    }\n}\n\nstatic __maybe_unused void JS_DumpValue(JSContext *ctx,\n                                                 JSValueConst val)\n{\n    JS_DumpValueShort(ctx->rt, val);\n}\n\nstatic __maybe_unused void JS_PrintValue(JSContext *ctx,\n                                                  const char *str,\n                                                  JSValueConst val)\n{\n    printf(\"%s=\", str);\n    JS_DumpValueShort(ctx->rt, val);\n    printf(\"\\n\");\n}\n\n/* return -1 if exception (proxy case) or TRUE/FALSE */\nint JS_IsArray(JSContext *ctx, JSValueConst val)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(val) == JS_TAG_OBJECT) {\n        p = JS_VALUE_GET_OBJ(val);\n        if (unlikely(p->class_id == JS_CLASS_PROXY))\n            return js_proxy_isArray(ctx, val);\n        else\n            return p->class_id == JS_CLASS_ARRAY;\n    } else {\n        return FALSE;\n    }\n}\n\nstatic double js_pow(double a, double b)\n{\n    if (unlikely(!isfinite(b)) && fabs(a) == 1) {\n        /* not compatible with IEEE 754 */\n        return JS_FLOAT64_NAN;\n    } else {\n        return pow(a, b);\n    }\n}\n\n#ifdef CONFIG_BIGNUM\n\nJSValue JS_NewBigInt64_1(JSContext *ctx, int64_t v)\n{\n    JSValue val;\n    bf_t *a;\n    val = JS_NewBigInt(ctx);\n    if (JS_IsException(val))\n        return val;\n    a = JS_GetBigInt(val);\n    if (bf_set_si(a, v)) {\n        JS_FreeValue(ctx, val);\n        return JS_ThrowOutOfMemory(ctx);\n    }\n    return val;\n}\n\nJSValue JS_NewBigInt64(JSContext *ctx, int64_t v)\n{\n    if (is_math_mode(ctx) &&\n        v >= -MAX_SAFE_INTEGER && v <= MAX_SAFE_INTEGER) {\n        return JS_NewInt64(ctx, v);\n    } else {\n        return JS_NewBigInt64_1(ctx, v);\n    }\n}\n\nJSValue JS_NewBigUint64(JSContext *ctx, uint64_t v)\n{\n    JSValue val;\n    if (is_math_mode(ctx) && v <= MAX_SAFE_INTEGER) {\n        val = JS_NewInt64(ctx, v);\n    } else {\n        bf_t *a;\n        val = JS_NewBigInt(ctx);\n        if (JS_IsException(val))\n            return val;\n        a = JS_GetBigInt(val);\n        if (bf_set_ui(a, v)) {\n            JS_FreeValue(ctx, val);\n            return JS_ThrowOutOfMemory(ctx);\n        }\n    }\n    return val;\n}\n\n/* if the returned bigfloat is allocated it is equal to\n   'buf'. Otherwise it is a pointer to the bigfloat in 'val'. Return\n   NULL in case of error. */\nstatic bf_t *JS_ToBigFloat(JSContext *ctx, bf_t *buf, JSValueConst val)\n{\n    uint32_t tag;\n    bf_t *r;\n    JSBigFloat *p;\n\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n        r = buf;\n        bf_init(ctx->bf_ctx, r);\n        if (bf_set_si(r, JS_VALUE_GET_INT(val)))\n            goto fail;\n        break;\n    case JS_TAG_FLOAT64:\n        r = buf;\n        bf_init(ctx->bf_ctx, r);\n        if (bf_set_float64(r, JS_VALUE_GET_FLOAT64(val))) {\n        fail:\n            bf_delete(r);\n            return NULL;\n        }\n        break;\n    case JS_TAG_BIG_INT:\n    case JS_TAG_BIG_FLOAT:\n        p = JS_VALUE_GET_PTR(val);\n        r = &p->num;\n        break;\n    case JS_TAG_UNDEFINED:\n    default:\n        r = buf;\n        bf_init(ctx->bf_ctx, r);\n        bf_set_nan(r);\n        break;\n    }\n    return r;\n}\n\n/* return NULL if invalid type */\nstatic bfdec_t *JS_ToBigDecimal(JSContext *ctx, JSValueConst val)\n{\n    uint32_t tag;\n    JSBigDecimal *p;\n    bfdec_t *r;\n    \n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_BIG_DECIMAL:\n        p = JS_VALUE_GET_PTR(val);\n        r = &p->num;\n        break;\n    default:\n        JS_ThrowTypeError(ctx, \"bigdecimal expected\");\n        r = NULL;\n        break;\n    }\n    return r;\n}\n\n/* return NaN if bad bigint literal */\nstatic JSValue JS_StringToBigInt(JSContext *ctx, JSValue val)\n{\n    const char *str, *p;\n    size_t len;\n    int flags;\n    \n    str = JS_ToCStringLen(ctx, &len, val);\n    JS_FreeValue(ctx, val);\n    if (!str)\n        return JS_EXCEPTION;\n    p = str;\n    p += skip_spaces(p);\n    if ((p - str) == len) {\n        val = JS_NewBigInt64(ctx, 0);\n    } else {\n        flags = ATOD_INT_ONLY | ATOD_ACCEPT_BIN_OCT | ATOD_TYPE_BIG_INT;\n        if (is_math_mode(ctx))\n            flags |= ATOD_MODE_BIGINT;\n        val = js_atof(ctx, p, &p, 0, flags);\n        p += skip_spaces(p);\n        if (!JS_IsException(val)) {\n            if ((p - str) != len) {\n                JS_FreeValue(ctx, val);\n                val = JS_NAN;\n            }\n        }\n    }\n    JS_FreeCString(ctx, str);\n    return val;\n}\n\nstatic JSValue JS_StringToBigIntErr(JSContext *ctx, JSValue val)\n{\n    val = JS_StringToBigInt(ctx, val);\n    if (JS_VALUE_IS_NAN(val))\n        return JS_ThrowSyntaxError(ctx, \"invalid bigint literal\");\n    return val;\n}\n\n/* if the returned bigfloat is allocated it is equal to\n   'buf'. Otherwise it is a pointer to the bigfloat in 'val'. */\nstatic bf_t *JS_ToBigIntFree(JSContext *ctx, bf_t *buf, JSValue val)\n{\n    uint32_t tag;\n    bf_t *r;\n    JSBigFloat *p;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        if (!is_math_mode(ctx))\n            goto fail;\n        /* fall tru */\n    case JS_TAG_BOOL:\n        r = buf;\n        bf_init(ctx->bf_ctx, r);\n        bf_set_si(r, JS_VALUE_GET_INT(val));\n        break;\n    case JS_TAG_FLOAT64:\n        {\n            double d = JS_VALUE_GET_FLOAT64(val);\n            if (!is_math_mode(ctx))\n                goto fail;\n            if (!isfinite(d))\n                goto fail;\n            r = buf;\n            bf_init(ctx->bf_ctx, r);\n            d = trunc(d);\n            bf_set_float64(r, d);\n        }\n        break;\n    case JS_TAG_BIG_INT:\n        p = JS_VALUE_GET_PTR(val);\n        r = &p->num;\n        break;\n    case JS_TAG_BIG_FLOAT:\n        if (!is_math_mode(ctx))\n            goto fail;\n        p = JS_VALUE_GET_PTR(val);\n        if (!bf_is_finite(&p->num))\n            goto fail;\n        r = buf;\n        bf_init(ctx->bf_ctx, r);\n        bf_set(r, &p->num);\n        bf_rint(r, BF_RNDZ);\n        JS_FreeValue(ctx, val);\n        break;\n    case JS_TAG_STRING:\n        val = JS_StringToBigIntErr(ctx, val);\n        if (JS_IsException(val))\n            return NULL;\n        goto redo;\n    case JS_TAG_OBJECT:\n        val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER);\n        if (JS_IsException(val))\n            return NULL;\n        goto redo;\n    default:\n    fail:\n        JS_FreeValue(ctx, val);\n        JS_ThrowTypeError(ctx, \"cannot convert to bigint\");\n        return NULL;\n    }\n    return r;\n}\n\nstatic bf_t *JS_ToBigInt(JSContext *ctx, bf_t *buf, JSValueConst val)\n{\n    return JS_ToBigIntFree(ctx, buf, JS_DupValue(ctx, val));\n}\n\nstatic __maybe_unused JSValue JS_ToBigIntValueFree(JSContext *ctx, JSValue val)\n{\n    if (JS_VALUE_GET_TAG(val) == JS_TAG_BIG_INT) {\n        return val;\n    } else {\n        bf_t a_s, *a, *r;\n        int ret;\n        JSValue res; \n\n        res = JS_NewBigInt(ctx);\n        if (JS_IsException(res))\n            return JS_EXCEPTION;\n        a = JS_ToBigIntFree(ctx, &a_s, val);\n        if (!a) {\n            JS_FreeValue(ctx, res);\n            return JS_EXCEPTION;\n        }\n        r = JS_GetBigInt(res);\n        ret = bf_set(r, a);\n        JS_FreeBigInt(ctx, a, &a_s);\n        if (ret) {\n            JS_FreeValue(ctx, res);\n            return JS_ThrowOutOfMemory(ctx);\n        }\n        return JS_CompactBigInt(ctx, res);\n    }\n}\n\n/* free the bf_t allocated by JS_ToBigInt */\nstatic void JS_FreeBigInt(JSContext *ctx, bf_t *a, bf_t *buf)\n{\n    if (a == buf) {\n        bf_delete(a);\n    } else {\n        JSBigFloat *p = (JSBigFloat *)((uint8_t *)a -\n                                       offsetof(JSBigFloat, num));\n        JS_FreeValue(ctx, JS_MKPTR(JS_TAG_BIG_FLOAT, p));\n    }\n}\n\n/* XXX: merge with JS_ToInt64Free with a specific flag */\nstatic int JS_ToBigInt64Free(JSContext *ctx, int64_t *pres, JSValue val)\n{\n    bf_t a_s, *a;\n\n    a = JS_ToBigIntFree(ctx, &a_s, val);\n    if (!a) {\n        *pres = 0;\n        return -1;\n    }\n    bf_get_int64(pres, a, BF_GET_INT_MOD);\n    JS_FreeBigInt(ctx, a, &a_s);\n    return 0;\n}\n\nint JS_ToBigInt64(JSContext *ctx, int64_t *pres, JSValueConst val)\n{\n    return JS_ToBigInt64Free(ctx, pres, JS_DupValue(ctx, val));\n}\n\nstatic JSBigFloat *js_new_bf(JSContext *ctx)\n{\n    JSBigFloat *p;\n    p = js_malloc(ctx, sizeof(*p));\n    if (!p)\n        return NULL;\n    p->header.ref_count = 1;\n    bf_init(ctx->bf_ctx, &p->num);\n    return p;\n}\n\nstatic JSValue JS_NewBigFloat(JSContext *ctx)\n{\n    JSBigFloat *p;\n    p = js_malloc(ctx, sizeof(*p));\n    if (!p)\n        return JS_EXCEPTION;\n    p->header.ref_count = 1;\n    bf_init(ctx->bf_ctx, &p->num);\n    return JS_MKPTR(JS_TAG_BIG_FLOAT, p);\n}\n\nstatic JSValue JS_NewBigDecimal(JSContext *ctx)\n{\n    JSBigDecimal *p;\n    p = js_malloc(ctx, sizeof(*p));\n    if (!p)\n        return JS_EXCEPTION;\n    p->header.ref_count = 1;\n    bfdec_init(ctx->bf_ctx, &p->num);\n    return JS_MKPTR(JS_TAG_BIG_DECIMAL, p);\n}\n\nstatic JSValue JS_NewBigInt(JSContext *ctx)\n{\n    JSBigFloat *p;\n    p = js_malloc(ctx, sizeof(*p));\n    if (!p)\n        return JS_EXCEPTION;\n    p->header.ref_count = 1;\n    bf_init(ctx->bf_ctx, &p->num);\n    return JS_MKPTR(JS_TAG_BIG_INT, p);\n}\n\nstatic JSValue JS_CompactBigInt1(JSContext *ctx, JSValue val,\n                                 BOOL convert_to_safe_integer)\n{\n    int64_t v;\n    bf_t *a;\n    \n    if (JS_VALUE_GET_TAG(val) != JS_TAG_BIG_INT)\n        return val; /* fail safe */\n    a = JS_GetBigInt(val);\n    if (convert_to_safe_integer && bf_get_int64(&v, a, 0) == 0 &&\n        v >= -MAX_SAFE_INTEGER && v <= MAX_SAFE_INTEGER) {\n        JS_FreeValue(ctx, val);\n        return JS_NewInt64(ctx, v);\n    } else if (a->expn == BF_EXP_ZERO && a->sign) {\n        JSBigFloat *p = JS_VALUE_GET_PTR(val);\n        assert(p->header.ref_count == 1);\n        a->sign = 0;\n    }\n    return val;\n}\n\n/* Convert the big int to a safe integer if in math mode. normalize\n   the zero representation. Could also be used to convert the bigint\n   to a short bigint value. The reference count of the value must be\n   1. Cannot fail */\nstatic JSValue JS_CompactBigInt(JSContext *ctx, JSValue val)\n{\n    return JS_CompactBigInt1(ctx, val, is_math_mode(ctx));\n}\n\n/* must be kept in sync with JSOverloadableOperatorEnum */\n/* XXX: use atoms ? */\nstatic const char js_overloadable_operator_names[JS_OVOP_COUNT][4] = {\n    \"+\",\n    \"-\",\n    \"*\",\n    \"/\",\n    \"%\",\n    \"**\",\n    \"|\",\n    \"&\",\n    \"^\",\n    \"<<\",\n    \">>\",\n    \">>>\",\n    \"==\",\n    \"<\",\n    \"pos\",\n    \"neg\",\n    \"++\",\n    \"--\",\n    \"~\",\n};\n\nstatic int get_ovop_from_opcode(OPCodeEnum op)\n{\n    switch(op) {\n    case OP_add:\n        return JS_OVOP_ADD;\n    case OP_sub:\n        return JS_OVOP_SUB;\n    case OP_mul:\n        return JS_OVOP_MUL;\n    case OP_div:\n        return JS_OVOP_DIV;\n    case OP_mod:\n    case OP_math_mod:\n        return JS_OVOP_MOD;\n    case OP_pow:\n        return JS_OVOP_POW;\n    case OP_or:\n        return JS_OVOP_OR;\n    case OP_and:\n        return JS_OVOP_AND;\n    case OP_xor:\n        return JS_OVOP_XOR;\n    case OP_shl:\n        return JS_OVOP_SHL;\n    case OP_sar:\n        return JS_OVOP_SAR;\n    case OP_shr:\n        return JS_OVOP_SHR;\n    case OP_eq:\n    case OP_neq:\n        return JS_OVOP_EQ;\n    case OP_lt:\n    case OP_lte:\n    case OP_gt:\n    case OP_gte:\n        return JS_OVOP_LESS;\n    case OP_plus:\n        return JS_OVOP_POS;\n    case OP_neg:\n        return JS_OVOP_NEG;\n    case OP_inc:\n        return JS_OVOP_INC;\n    case OP_dec:\n        return JS_OVOP_DEC;\n    default:\n        abort();\n    }\n}\n\n/* return NULL if not present */\nstatic JSObject *find_binary_op(JSBinaryOperatorDef *def,\n                                uint32_t operator_index,\n                                JSOverloadableOperatorEnum op)\n{\n    JSBinaryOperatorDefEntry *ent;\n    int i;\n    for(i = 0; i < def->count; i++) {\n        ent = &def->tab[i];\n        if (ent->operator_index == operator_index)\n            return ent->ops[op];\n    }\n    return NULL;\n}\n\n/* return -1 if exception, 0 if no operator overloading, 1 if\n   overloaded operator called */\nstatic __exception int js_call_binary_op_fallback(JSContext *ctx,\n                                                  JSValue *pret,\n                                                  JSValueConst op1,\n                                                  JSValueConst op2,\n                                                  OPCodeEnum op,\n                                                  BOOL is_numeric,\n                                                  int hint)\n{\n    JSValue opset1_obj, opset2_obj, method, ret, new_op1, new_op2;\n    JSOperatorSetData *opset1, *opset2;\n    JSOverloadableOperatorEnum ovop;\n    JSObject *p;\n    JSValueConst args[2];\n    \n    if (!ctx->allow_operator_overloading)\n        return 0;\n    \n    opset2_obj = JS_UNDEFINED;\n    opset1_obj = JS_GetProperty(ctx, op1, JS_ATOM_Symbol_operatorSet);\n    if (JS_IsException(opset1_obj))\n        goto exception;\n    if (JS_IsUndefined(opset1_obj))\n        return 0;\n    opset1 = JS_GetOpaque2(ctx, opset1_obj, JS_CLASS_OPERATOR_SET);\n    if (!opset1)\n        goto exception;\n\n    opset2_obj = JS_GetProperty(ctx, op2, JS_ATOM_Symbol_operatorSet);\n    if (JS_IsException(opset2_obj))\n        goto exception;\n    if (JS_IsUndefined(opset2_obj)) {\n        JS_FreeValue(ctx, opset1_obj);\n        return 0;\n    }\n    opset2 = JS_GetOpaque2(ctx, opset2_obj, JS_CLASS_OPERATOR_SET);\n    if (!opset2)\n        goto exception;\n\n    if (opset1->is_primitive && opset2->is_primitive) {\n        JS_FreeValue(ctx, opset1_obj);\n        JS_FreeValue(ctx, opset2_obj);\n        return 0;\n    }\n\n    ovop = get_ovop_from_opcode(op);\n    \n    if (opset1->operator_counter == opset2->operator_counter) {\n        p = opset1->self_ops[ovop];\n    } else if (opset1->operator_counter > opset2->operator_counter) {\n        p = find_binary_op(&opset1->left, opset2->operator_counter, ovop);\n    } else {\n        p = find_binary_op(&opset2->right, opset1->operator_counter, ovop);\n    }\n    if (!p) {\n        JS_ThrowTypeError(ctx, \"operator %s: no function defined\",\n                          js_overloadable_operator_names[ovop]);\n        goto exception;\n    }\n\n    if (opset1->is_primitive) {\n        if (is_numeric) {\n            new_op1 = JS_ToNumeric(ctx, op1);\n        } else {\n            new_op1 = JS_ToPrimitive(ctx, op1, hint);\n        }\n        if (JS_IsException(new_op1))\n            goto exception;\n    } else {\n        new_op1 = JS_DupValue(ctx, op1);\n    }\n    \n    if (opset2->is_primitive) {\n        if (is_numeric) {\n            new_op2 = JS_ToNumeric(ctx, op2);\n        } else {\n            new_op2 = JS_ToPrimitive(ctx, op2, hint);\n        }\n        if (JS_IsException(new_op2)) {\n            JS_FreeValue(ctx, new_op1);\n            goto exception;\n        }\n    } else {\n        new_op2 = JS_DupValue(ctx, op2);\n    }\n\n    /* XXX: could apply JS_ToPrimitive() if primitive type so that the\n       operator function does not get a value object */\n    \n    method = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n    if (ovop == JS_OVOP_LESS && (op == OP_lte || op == OP_gt)) {\n        args[0] = new_op2;\n        args[1] = new_op1;\n    } else {\n        args[0] = new_op1;\n        args[1] = new_op2;\n    }\n    ret = JS_CallFree(ctx, method, JS_UNDEFINED, 2, args);\n    JS_FreeValue(ctx, new_op1);\n    JS_FreeValue(ctx, new_op2);\n    if (JS_IsException(ret))\n        goto exception;\n    if (ovop == JS_OVOP_EQ) {\n        BOOL res = JS_ToBoolFree(ctx, ret);\n        if (op == OP_neq)\n            res ^= 1;\n        ret = JS_NewBool(ctx, res);\n    } else if (ovop == JS_OVOP_LESS) {\n        if (JS_IsUndefined(ret)) {\n            ret = JS_FALSE;\n        } else {\n            BOOL res = JS_ToBoolFree(ctx, ret);\n            if (op == OP_lte || op == OP_gte)\n                res ^= 1;\n            ret = JS_NewBool(ctx, res);\n        }\n    }\n    JS_FreeValue(ctx, opset1_obj);\n    JS_FreeValue(ctx, opset2_obj);\n    *pret = ret;\n    return 1;\n exception:\n    JS_FreeValue(ctx, opset1_obj);\n    JS_FreeValue(ctx, opset2_obj);\n    *pret = JS_UNDEFINED;\n    return -1;\n}\n\n/* try to call the operation on the operatorSet field of 'obj'. Only\n   used for \"/\" and \"**\" on the BigInt prototype in math mode */\nstatic __exception int js_call_binary_op_simple(JSContext *ctx,\n                                                JSValue *pret,\n                                                JSValueConst obj,\n                                                JSValueConst op1,\n                                                JSValueConst op2,\n                                                OPCodeEnum op)\n{\n    JSValue opset1_obj, method, ret, new_op1, new_op2;\n    JSOperatorSetData *opset1;\n    JSOverloadableOperatorEnum ovop;\n    JSObject *p;\n    JSValueConst args[2];\n\n    opset1_obj = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_operatorSet);\n    if (JS_IsException(opset1_obj))\n        goto exception;\n    if (JS_IsUndefined(opset1_obj))\n        return 0;\n    opset1 = JS_GetOpaque2(ctx, opset1_obj, JS_CLASS_OPERATOR_SET);\n    if (!opset1)\n        goto exception;\n    ovop = get_ovop_from_opcode(op);\n\n    p = opset1->self_ops[ovop];\n    if (!p) {\n        JS_FreeValue(ctx, opset1_obj);\n        return 0;\n    }\n\n    new_op1 = JS_ToNumeric(ctx, op1);\n    if (JS_IsException(new_op1))\n        goto exception;\n    new_op2 = JS_ToNumeric(ctx, op2);\n    if (JS_IsException(new_op2)) {\n        JS_FreeValue(ctx, new_op1);\n        goto exception;\n    }\n\n    method = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n    args[0] = new_op1;\n    args[1] = new_op2;\n    ret = JS_CallFree(ctx, method, JS_UNDEFINED, 2, args);\n    JS_FreeValue(ctx, new_op1);\n    JS_FreeValue(ctx, new_op2);\n    if (JS_IsException(ret))\n        goto exception;\n    JS_FreeValue(ctx, opset1_obj);\n    *pret = ret;\n    return 1;\n exception:\n    JS_FreeValue(ctx, opset1_obj);\n    *pret = JS_UNDEFINED;\n    return -1;\n}\n\n/* return -1 if exception, 0 if no operator overloading, 1 if\n   overloaded operator called */\nstatic __exception int js_call_unary_op_fallback(JSContext *ctx,\n                                                 JSValue *pret,\n                                                 JSValueConst op1,\n                                                 OPCodeEnum op)\n{\n    JSValue opset1_obj, method, ret;\n    JSOperatorSetData *opset1;\n    JSOverloadableOperatorEnum ovop;\n    JSObject *p;\n\n    if (!ctx->allow_operator_overloading)\n        return 0;\n    \n    opset1_obj = JS_GetProperty(ctx, op1, JS_ATOM_Symbol_operatorSet);\n    if (JS_IsException(opset1_obj))\n        goto exception;\n    if (JS_IsUndefined(opset1_obj))\n        return 0;\n    opset1 = JS_GetOpaque2(ctx, opset1_obj, JS_CLASS_OPERATOR_SET);\n    if (!opset1)\n        goto exception;\n    if (opset1->is_primitive) {\n        JS_FreeValue(ctx, opset1_obj);\n        return 0;\n    }\n\n    ovop = get_ovop_from_opcode(op);\n\n    p = opset1->self_ops[ovop];\n    if (!p) {\n        JS_ThrowTypeError(ctx, \"no overloaded operator %s\",\n                          js_overloadable_operator_names[ovop]);\n        goto exception;\n    }\n    method = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n    ret = JS_CallFree(ctx, method, JS_UNDEFINED, 1, &op1);\n    if (JS_IsException(ret))\n        goto exception;\n    JS_FreeValue(ctx, opset1_obj);\n    *pret = ret;\n    return 1;\n exception:\n    JS_FreeValue(ctx, opset1_obj);\n    *pret = JS_UNDEFINED;\n    return -1;\n}\n\nstatic JSValue throw_bf_exception(JSContext *ctx, int status)\n{\n    const char *str;\n    if (status & BF_ST_MEM_ERROR)\n        return JS_ThrowOutOfMemory(ctx);\n    if (status & BF_ST_DIVIDE_ZERO) {\n        str = \"division by zero\";\n    } else if (status & BF_ST_INVALID_OP) {\n        str = \"invalid operation\";\n    } else {\n        str = \"integer overflow\";\n    }\n    return JS_ThrowRangeError(ctx, \"%s\", str);\n}\n\nstatic int js_unary_arith_bigint(JSContext *ctx,\n                                 JSValue *pres, OPCodeEnum op, JSValue op1)\n{\n    bf_t a_s, *r, *a;\n    int ret, v;\n    JSValue res;\n    \n    if (op == OP_plus && !is_math_mode(ctx)) {\n        JS_ThrowTypeError(ctx, \"bigint argument with unary +\");\n        JS_FreeValue(ctx, op1);\n        return -1;\n    }\n    res = JS_NewBigInt(ctx);\n    if (JS_IsException(res)) {\n        JS_FreeValue(ctx, op1);\n        return -1;\n    }\n    r = JS_GetBigInt(res);\n    a = JS_ToBigInt(ctx, &a_s, op1);\n    ret = 0;\n    switch(op) {\n    case OP_inc:\n    case OP_dec:\n        v = 2 * (op - OP_dec) - 1;\n        ret = bf_add_si(r, a, v, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_plus:\n        ret = bf_set(r, a);\n        break;\n    case OP_neg:\n        ret = bf_set(r, a);\n        bf_neg(r);\n        break;\n    case OP_not:\n        ret = bf_add_si(r, a, 1, BF_PREC_INF, BF_RNDZ);\n        bf_neg(r);\n        break;\n    default:\n        abort();\n    }\n    JS_FreeBigInt(ctx, a, &a_s);\n    JS_FreeValue(ctx, op1);\n    if (unlikely(ret)) {\n        JS_FreeValue(ctx, res);\n        throw_bf_exception(ctx, ret);\n        return -1;\n    }\n    res = JS_CompactBigInt(ctx, res);\n    *pres = res;\n    return 0;\n}\n\nstatic int js_unary_arith_bigfloat(JSContext *ctx,\n                                   JSValue *pres, OPCodeEnum op, JSValue op1)\n{\n    bf_t a_s, *r, *a;\n    int ret, v;\n    JSValue res;\n    \n    if (op == OP_plus && !is_math_mode(ctx)) {\n        JS_ThrowTypeError(ctx, \"bigfloat argument with unary +\");\n        JS_FreeValue(ctx, op1);\n        return -1;\n    }\n\n    res = JS_NewBigFloat(ctx);\n    if (JS_IsException(res)) {\n        JS_FreeValue(ctx, op1);\n        return -1;\n    }\n    r = JS_GetBigFloat(res);\n    a = JS_ToBigFloat(ctx, &a_s, op1);\n    ret = 0;\n    switch(op) {\n    case OP_inc:\n    case OP_dec:\n        v = 2 * (op - OP_dec) - 1;\n        ret = bf_add_si(r, a, v, ctx->fp_env.prec, ctx->fp_env.flags);\n        break;\n    case OP_plus:\n        ret = bf_set(r, a);\n        break;\n    case OP_neg:\n        ret = bf_set(r, a);\n        bf_neg(r);\n        break;\n    default:\n        abort();\n    }\n    if (a == &a_s)\n        bf_delete(a);\n    JS_FreeValue(ctx, op1);\n    if (unlikely(ret & BF_ST_MEM_ERROR)) {\n        JS_FreeValue(ctx, res);\n        throw_bf_exception(ctx, ret);\n        return -1;\n    }\n    *pres = res;\n    return 0;\n}\n\nstatic int js_unary_arith_bigdecimal(JSContext *ctx,\n                                     JSValue *pres, OPCodeEnum op, JSValue op1)\n{\n    bfdec_t *r, *a;\n    int ret, v;\n    JSValue res;\n    \n    if (op == OP_plus && !is_math_mode(ctx)) {\n        JS_ThrowTypeError(ctx, \"bigdecimal argument with unary +\");\n        JS_FreeValue(ctx, op1);\n        return -1;\n    }\n\n    res = JS_NewBigDecimal(ctx);\n    if (JS_IsException(res)) {\n        JS_FreeValue(ctx, op1);\n        return -1;\n    }\n    r = JS_GetBigDecimal(res);\n    a = JS_ToBigDecimal(ctx, op1);\n    ret = 0;\n    switch(op) {\n    case OP_inc:\n    case OP_dec:\n        v = 2 * (op - OP_dec) - 1;\n        ret = bfdec_add_si(r, a, v, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_plus:\n        ret = bfdec_set(r, a);\n        break;\n    case OP_neg:\n        ret = bfdec_set(r, a);\n        bfdec_neg(r);\n        break;\n    default:\n        abort();\n    }\n    JS_FreeValue(ctx, op1);\n    if (unlikely(ret)) {\n        JS_FreeValue(ctx, res);\n        throw_bf_exception(ctx, ret);\n        return -1;\n    }\n    *pres = res;\n    return 0;\n}\n\nstatic no_inline __exception int js_unary_arith_slow(JSContext *ctx,\n                                                     JSValue *sp,\n                                                     OPCodeEnum op)\n{\n    JSValue op1, val;\n    int v, ret;\n    uint32_t tag;\n\n    op1 = sp[-1];\n    /* fast path for float64 */\n    if (JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(op1)))\n        goto handle_float64;\n    if (JS_IsObject(op1)) {\n        ret = js_call_unary_op_fallback(ctx, &val, op1, op);\n        if (ret < 0)\n            return -1;\n        if (ret) {\n            JS_FreeValue(ctx, op1);\n            sp[-1] = val;\n            return 0;\n        }\n    }\n\n    op1 = JS_ToNumericFree(ctx, op1);\n    if (JS_IsException(op1))\n        goto exception;\n    tag = JS_VALUE_GET_TAG(op1);\n    switch(tag) {\n    case JS_TAG_INT:\n        {\n            int64_t v64;\n            v64 = JS_VALUE_GET_INT(op1);\n            switch(op) {\n            case OP_inc:\n            case OP_dec:\n                v = 2 * (op - OP_dec) - 1;\n                v64 += v;\n                break;\n            case OP_plus:\n                break;\n            case OP_neg:\n                if (v64 == 0) {\n                    sp[-1] = __JS_NewFloat64(ctx, -0.0);\n                    return 0;\n                } else {\n                    v64 = -v64;\n                }\n                break;\n            default:\n                abort();\n            }\n            sp[-1] = JS_NewInt64(ctx, v64);\n        }\n        break;\n    case JS_TAG_BIG_INT:\n    handle_bigint:\n        if (ctx->rt->bigint_ops.unary_arith(ctx, sp - 1, op, op1))\n            goto exception;\n        break;\n    case JS_TAG_BIG_FLOAT:\n        if (ctx->rt->bigfloat_ops.unary_arith(ctx, sp - 1, op, op1))\n            goto exception;\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        if (ctx->rt->bigdecimal_ops.unary_arith(ctx, sp - 1, op, op1))\n            goto exception;\n        break;\n    default:\n    handle_float64:\n        {\n            double d;\n            if (is_math_mode(ctx))\n                goto handle_bigint;\n            d = JS_VALUE_GET_FLOAT64(op1);\n            switch(op) {\n            case OP_inc:\n            case OP_dec:\n                v = 2 * (op - OP_dec) - 1;\n                d += v;\n                break;\n            case OP_plus:\n                break;\n            case OP_neg:\n                d = -d;\n                break;\n            default:\n                abort();\n            }\n            sp[-1] = __JS_NewFloat64(ctx, d);\n        }\n        break;\n    }\n    return 0;\n exception:\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic __exception int js_post_inc_slow(JSContext *ctx,\n                                        JSValue *sp, OPCodeEnum op)\n{\n    JSValue op1;\n\n    /* XXX: allow custom operators */\n    op1 = sp[-1];\n    op1 = JS_ToNumericFree(ctx, op1);\n    if (JS_IsException(op1)) {\n        sp[-1] = JS_UNDEFINED;\n        return -1;\n    }\n    sp[-1] = op1;\n    sp[0] = JS_DupValue(ctx, op1);\n    return js_unary_arith_slow(ctx, sp + 1, op - OP_post_dec + OP_dec);\n}\n\nstatic no_inline int js_not_slow(JSContext *ctx, JSValue *sp)\n{\n    JSValue op1, val;\n    int ret;\n    \n    op1 = sp[-1];\n    if (JS_IsObject(op1)) {\n        ret = js_call_unary_op_fallback(ctx, &val, op1, OP_not);\n        if (ret < 0)\n            return -1;\n        if (ret) {\n            JS_FreeValue(ctx, op1);\n            sp[-1] = val;\n            return 0;\n        }\n    }\n\n    op1 = JS_ToNumericFree(ctx, op1);\n    if (JS_IsException(op1))\n        goto exception;\n    if (is_math_mode(ctx) || JS_VALUE_GET_TAG(op1) == JS_TAG_BIG_INT) {\n        if (ctx->rt->bigint_ops.unary_arith(ctx, sp - 1, OP_not, op1))\n            goto exception;\n    } else {\n        int32_t v1;\n        if (unlikely(JS_ToInt32Free(ctx, &v1, op1)))\n            goto exception;\n        sp[-1] = JS_NewInt32(ctx, ~v1);\n    }\n    return 0;\n exception:\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic int js_binary_arith_bigfloat(JSContext *ctx, OPCodeEnum op,\n                                    JSValue *pres, JSValue op1, JSValue op2)\n{\n    bf_t a_s, b_s, *r, *a, *b;\n    int ret;\n    JSValue res;\n    \n    res = JS_NewBigFloat(ctx);\n    if (JS_IsException(res)) {\n        JS_FreeValue(ctx, op1);\n        JS_FreeValue(ctx, op2);\n        return -1;\n    }\n    r = JS_GetBigFloat(res);\n    a = JS_ToBigFloat(ctx, &a_s, op1);\n    b = JS_ToBigFloat(ctx, &b_s, op2);\n    bf_init(ctx->bf_ctx, r);\n    switch(op) {\n    case OP_add:\n        ret = bf_add(r, a, b, ctx->fp_env.prec, ctx->fp_env.flags);\n        break;\n    case OP_sub:\n        ret = bf_sub(r, a, b, ctx->fp_env.prec, ctx->fp_env.flags);\n        break;\n    case OP_mul:\n        ret = bf_mul(r, a, b, ctx->fp_env.prec, ctx->fp_env.flags);\n        break;\n    case OP_div:\n        ret = bf_div(r, a, b, ctx->fp_env.prec, ctx->fp_env.flags);\n        break;\n    case OP_math_mod:\n        /* Euclidian remainder */\n        ret = bf_rem(r, a, b, ctx->fp_env.prec, ctx->fp_env.flags,\n                     BF_DIVREM_EUCLIDIAN);\n        break;\n    case OP_mod:\n        ret = bf_rem(r, a, b, ctx->fp_env.prec, ctx->fp_env.flags,\n                     BF_RNDZ);\n        break;\n    case OP_pow:\n        ret = bf_pow(r, a, b, ctx->fp_env.prec,\n                     ctx->fp_env.flags | BF_POW_JS_QUIRKS);\n        break;\n    default:\n        abort();\n    }\n    if (a == &a_s)\n        bf_delete(a);\n    if (b == &b_s)\n        bf_delete(b);\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    if (unlikely(ret & BF_ST_MEM_ERROR)) {\n        JS_FreeValue(ctx, res);\n        throw_bf_exception(ctx, ret);\n        return -1;\n    }\n    *pres = res;\n    return 0;\n}\n\nstatic int js_binary_arith_bigint(JSContext *ctx, OPCodeEnum op,\n                                  JSValue *pres, JSValue op1, JSValue op2)\n{\n    bf_t a_s, b_s, *r, *a, *b;\n    int ret;\n    JSValue res;\n    \n    res = JS_NewBigInt(ctx);\n    if (JS_IsException(res))\n        goto fail;\n    a = JS_ToBigInt(ctx, &a_s, op1);\n    if (!a)\n        goto fail;\n    b = JS_ToBigInt(ctx, &b_s, op2);\n    if (!b) {\n        JS_FreeBigInt(ctx, a, &a_s);\n        goto fail;\n    }\n    r = JS_GetBigInt(res);\n    ret = 0;\n    switch(op) {\n    case OP_add:\n        ret = bf_add(r, a, b, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_sub:\n        ret = bf_sub(r, a, b, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_mul:\n        ret = bf_mul(r, a, b, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_div:\n        if (!is_math_mode(ctx)) {\n            bf_t rem_s, *rem = &rem_s;\n            bf_init(ctx->bf_ctx, rem);\n            ret = bf_divrem(r, rem, a, b, BF_PREC_INF, BF_RNDZ,\n                            BF_RNDZ);\n            bf_delete(rem);\n        } else {\n            goto math_mode_div_pow;\n        }\n        break;\n    case OP_math_mod:\n        /* Euclidian remainder */\n        ret = bf_rem(r, a, b, BF_PREC_INF, BF_RNDZ,\n                     BF_DIVREM_EUCLIDIAN) & BF_ST_INVALID_OP;\n        break;\n    case OP_mod:\n        ret = bf_rem(r, a, b, BF_PREC_INF, BF_RNDZ,\n                     BF_RNDZ) & BF_ST_INVALID_OP;\n        break;\n    case OP_pow:\n        if (b->sign) {\n            if (!is_math_mode(ctx)) {\n                ret = BF_ST_INVALID_OP;\n            } else {\n            math_mode_div_pow:\n                JS_FreeValue(ctx, res);\n                ret = js_call_binary_op_simple(ctx, &res, ctx->class_proto[JS_CLASS_BIG_INT], op1, op2, op);\n                if (ret != 0) {\n                    JS_FreeBigInt(ctx, a, &a_s);\n                    JS_FreeBigInt(ctx, b, &b_s);\n                    JS_FreeValue(ctx, op1);\n                    JS_FreeValue(ctx, op2);\n                    if (ret < 0) {\n                        return -1;\n                    } else {\n                        *pres = res;\n                        return 0;\n                    }\n                }\n                /* if no BigInt power operator defined, return a\n                   bigfloat */\n                res = JS_NewBigFloat(ctx);\n                if (JS_IsException(res)) {\n                    JS_FreeBigInt(ctx, a, &a_s);\n                    JS_FreeBigInt(ctx, b, &b_s);\n                    goto fail;\n                }\n                r = JS_GetBigFloat(res);\n                if (op == OP_div) {\n                    ret = bf_div(r, a, b, ctx->fp_env.prec, ctx->fp_env.flags) & BF_ST_MEM_ERROR;\n                } else {\n                    ret = bf_pow(r, a, b, ctx->fp_env.prec,\n                                 ctx->fp_env.flags | BF_POW_JS_QUIRKS) & BF_ST_MEM_ERROR;\n                }\n                JS_FreeBigInt(ctx, a, &a_s);\n                JS_FreeBigInt(ctx, b, &b_s);\n                JS_FreeValue(ctx, op1);\n                JS_FreeValue(ctx, op2);\n                if (unlikely(ret)) {\n                    JS_FreeValue(ctx, res);\n                    throw_bf_exception(ctx, ret);\n                    return -1;\n                }\n                *pres = res;\n                return 0;\n            }\n        } else {\n            ret = bf_pow(r, a, b, BF_PREC_INF, BF_RNDZ | BF_POW_JS_QUIRKS);\n        }\n        break;\n\n        /* logical operations */\n    case OP_shl:\n    case OP_sar:\n        {\n            slimb_t v2;\n#if LIMB_BITS == 32\n            bf_get_int32(&v2, b, 0);\n            if (v2 == INT32_MIN)\n                v2 = INT32_MIN + 1;\n#else\n            bf_get_int64(&v2, b, 0);\n            if (v2 == INT64_MIN)\n                v2 = INT64_MIN + 1;\n#endif\n            if (op == OP_sar)\n                v2 = -v2;\n            ret = bf_set(r, a);\n            ret |= bf_mul_2exp(r, v2, BF_PREC_INF, BF_RNDZ);\n            if (v2 < 0) {\n                ret |= bf_rint(r, BF_RNDD) & (BF_ST_OVERFLOW | BF_ST_MEM_ERROR);\n            }\n        }\n        break;\n    case OP_and:\n        ret = bf_logic_and(r, a, b);\n        break;\n    case OP_or:\n        ret = bf_logic_or(r, a, b);\n        break;\n    case OP_xor:\n        ret = bf_logic_xor(r, a, b);\n        break;\n    default:\n        abort();\n    }\n    JS_FreeBigInt(ctx, a, &a_s);\n    JS_FreeBigInt(ctx, b, &b_s);\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    if (unlikely(ret)) {\n        JS_FreeValue(ctx, res);\n        throw_bf_exception(ctx, ret);\n        return -1;\n    }\n    *pres = JS_CompactBigInt(ctx, res);\n    return 0;\n fail:\n    JS_FreeValue(ctx, res);\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    return -1;\n}\n\n/* b must be a positive integer */\nstatic int js_bfdec_pow(bfdec_t *r, const bfdec_t *a, const bfdec_t *b)\n{\n    bfdec_t b1;\n    int32_t b2;\n    int ret;\n\n    bfdec_init(b->ctx, &b1);\n    ret = bfdec_set(&b1, b);\n    if (ret) {\n        bfdec_delete(&b1);\n        return ret;\n    }\n    ret = bfdec_rint(&b1, BF_RNDZ);\n    if (ret) {\n        bfdec_delete(&b1);\n        return BF_ST_INVALID_OP; /* must be an integer */\n    }\n    ret = bfdec_get_int32(&b2, &b1);\n    bfdec_delete(&b1);\n    if (ret)\n        return ret; /* overflow */\n    if (b2 < 0)\n        return BF_ST_INVALID_OP; /* must be positive */\n    return bfdec_pow_ui(r, a, b2);\n}\n\nstatic int js_binary_arith_bigdecimal(JSContext *ctx, OPCodeEnum op,\n                                      JSValue *pres, JSValue op1, JSValue op2)\n{\n    bfdec_t *r, *a, *b;\n    int ret;\n    JSValue res;\n\n    res = JS_NewBigDecimal(ctx);\n    if (JS_IsException(res))\n        goto fail;\n    r = JS_GetBigDecimal(res);\n    \n    a = JS_ToBigDecimal(ctx, op1);\n    if (!a)\n        goto fail;\n    b = JS_ToBigDecimal(ctx, op2);\n    if (!b)\n        goto fail;\n    switch(op) {\n    case OP_add:\n        ret = bfdec_add(r, a, b, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_sub:\n        ret = bfdec_sub(r, a, b, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_mul:\n        ret = bfdec_mul(r, a, b, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_div:\n        ret = bfdec_div(r, a, b, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_math_mod:\n        /* Euclidian remainder */\n        ret = bfdec_rem(r, a, b, BF_PREC_INF, BF_RNDZ, BF_DIVREM_EUCLIDIAN);\n        break;\n    case OP_mod:\n        ret = bfdec_rem(r, a, b, BF_PREC_INF, BF_RNDZ, BF_RNDZ);\n        break;\n    case OP_pow:\n        ret = js_bfdec_pow(r, a, b);\n        break;\n    default:\n        abort();\n    }\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    if (unlikely(ret)) {\n        JS_FreeValue(ctx, res);\n        throw_bf_exception(ctx, ret);\n        return -1;\n    }\n    *pres = res;\n    return 0;\n fail:\n    JS_FreeValue(ctx, res);\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    return -1;\n}\n\nstatic no_inline __exception int js_binary_arith_slow(JSContext *ctx, JSValue *sp,\n                                                      OPCodeEnum op)\n{\n    JSValue op1, op2, res;\n    uint32_t tag1, tag2;\n    int ret;\n    double d1, d2;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n    /* fast path for float operations */\n    if (tag1 == JS_TAG_FLOAT64 && tag2 == JS_TAG_FLOAT64) {\n        d1 = JS_VALUE_GET_FLOAT64(op1);\n        d2 = JS_VALUE_GET_FLOAT64(op2);\n        goto handle_float64;\n    }\n\n    /* try to call an overloaded operator */\n    if ((tag1 == JS_TAG_OBJECT &&\n         (tag2 != JS_TAG_NULL && tag2 != JS_TAG_UNDEFINED)) ||\n        (tag2 == JS_TAG_OBJECT &&\n         (tag1 != JS_TAG_NULL && tag1 != JS_TAG_UNDEFINED))) {\n        ret = js_call_binary_op_fallback(ctx, &res, op1, op2, op, TRUE, 0);\n        if (ret != 0) {\n            JS_FreeValue(ctx, op1);\n            JS_FreeValue(ctx, op2);\n            if (ret < 0) {\n                goto exception;\n            } else {\n                sp[-2] = res;\n                return 0;\n            }\n        }\n    }\n\n    op1 = JS_ToNumericFree(ctx, op1);\n    if (JS_IsException(op1)) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    op2 = JS_ToNumericFree(ctx, op2);\n    if (JS_IsException(op2)) {\n        JS_FreeValue(ctx, op1);\n        goto exception;\n    }\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n\n    if (tag1 == JS_TAG_INT && tag2 == JS_TAG_INT) {\n        int32_t v1, v2;\n        int64_t v;\n        v1 = JS_VALUE_GET_INT(op1);\n        v2 = JS_VALUE_GET_INT(op2);\n        switch(op) {\n        case OP_sub:\n            v = (int64_t)v1 - (int64_t)v2;\n            break;\n        case OP_mul:\n            v = (int64_t)v1 * (int64_t)v2;\n            if (is_math_mode(ctx) &&\n                (v < -MAX_SAFE_INTEGER || v > MAX_SAFE_INTEGER))\n                goto handle_bigint;\n            if (v == 0 && (v1 | v2) < 0) {\n                sp[-2] = __JS_NewFloat64(ctx, -0.0);\n                return 0;\n            }\n            break;\n        case OP_div:\n            if (is_math_mode(ctx))\n                goto handle_bigint;\n            sp[-2] = __JS_NewFloat64(ctx, (double)v1 / (double)v2);\n            return 0;\n        case OP_math_mod:\n            if (unlikely(v2 == 0)) {\n                throw_bf_exception(ctx, BF_ST_DIVIDE_ZERO);\n                goto exception;\n            }\n            v = (int64_t)v1 % (int64_t)v2;\n            if (v < 0) {\n                if (v2 < 0)\n                    v -= v2;\n                else\n                    v += v2;\n            }\n            break;\n        case OP_mod:\n            if (v1 < 0 || v2 <= 0) {\n                sp[-2] = JS_NewFloat64(ctx, fmod(v1, v2));\n                return 0;\n            } else {\n                v = (int64_t)v1 % (int64_t)v2;\n            }\n            break;\n        case OP_pow:\n            if (!is_math_mode(ctx)) {\n                sp[-2] = JS_NewFloat64(ctx, js_pow(v1, v2));\n                return 0;\n            } else {\n                goto handle_bigint;\n            }\n            break;\n        default:\n            abort();\n        }\n        sp[-2] = JS_NewInt64(ctx, v);\n    } else if (tag1 == JS_TAG_BIG_DECIMAL || tag2 == JS_TAG_BIG_DECIMAL) {\n        if (ctx->rt->bigdecimal_ops.binary_arith(ctx, op, sp - 2, op1, op2))\n            goto exception;\n    } else if (tag1 == JS_TAG_BIG_FLOAT || tag2 == JS_TAG_BIG_FLOAT) {\n        if (ctx->rt->bigfloat_ops.binary_arith(ctx, op, sp - 2, op1, op2))\n            goto exception;\n    } else if (tag1 == JS_TAG_BIG_INT || tag2 == JS_TAG_BIG_INT) {\n    handle_bigint:\n        if (ctx->rt->bigint_ops.binary_arith(ctx, op, sp - 2, op1, op2))\n            goto exception;\n    } else {\n        double dr;\n        /* float64 result */\n        if (JS_ToFloat64Free(ctx, &d1, op1)) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n        if (JS_ToFloat64Free(ctx, &d2, op2))\n            goto exception;\n    handle_float64:\n        if (is_math_mode(ctx) && is_safe_integer(d1) && is_safe_integer(d2))\n            goto handle_bigint;\n        switch(op) {\n        case OP_sub:\n            dr = d1 - d2;\n            break;\n        case OP_mul:\n            dr = d1 * d2;\n            break;\n        case OP_div:\n            dr = d1 / d2;\n            break;\n        case OP_mod:\n            dr = fmod(d1, d2);\n            break;\n        case OP_math_mod:\n            d2 = fabs(d2);\n            dr = fmod(d1, d2);\n            /* XXX: loss of accuracy if dr < 0 */\n            if (dr < 0)\n                dr += d2;\n            break;\n        case OP_pow:\n            dr = js_pow(d1, d2);\n            break;\n        default:\n            abort();\n        }\n        sp[-2] = __JS_NewFloat64(ctx, dr);\n    }\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic no_inline __exception int js_add_slow(JSContext *ctx, JSValue *sp)\n{\n    JSValue op1, op2, res;\n    uint32_t tag1, tag2;\n    int ret;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n    /* fast path for float64 */\n    if (tag1 == JS_TAG_FLOAT64 && tag2 == JS_TAG_FLOAT64) {\n        double d1, d2;\n        d1 = JS_VALUE_GET_FLOAT64(op1);\n        d2 = JS_VALUE_GET_FLOAT64(op2);\n        sp[-2] = __JS_NewFloat64(ctx, d1 + d2);\n        return 0;\n    }\n\n    if (tag1 == JS_TAG_OBJECT || tag2 == JS_TAG_OBJECT) {\n        /* try to call an overloaded operator */\n        if ((tag1 == JS_TAG_OBJECT &&\n             (tag2 != JS_TAG_NULL && tag2 != JS_TAG_UNDEFINED &&\n              tag2 != JS_TAG_STRING)) ||\n            (tag2 == JS_TAG_OBJECT &&\n             (tag1 != JS_TAG_NULL && tag1 != JS_TAG_UNDEFINED &&\n              tag1 != JS_TAG_STRING))) {\n            ret = js_call_binary_op_fallback(ctx, &res, op1, op2, OP_add,\n                                             FALSE, HINT_NONE);\n            if (ret != 0) {\n                JS_FreeValue(ctx, op1);\n                JS_FreeValue(ctx, op2);\n                if (ret < 0) {\n                    goto exception;\n                } else {\n                    sp[-2] = res;\n                    return 0;\n                }\n            }\n        }\n\n        op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE);\n        if (JS_IsException(op1)) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n\n        op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NONE);\n        if (JS_IsException(op2)) {\n            JS_FreeValue(ctx, op1);\n            goto exception;\n        }\n        tag1 = JS_VALUE_GET_NORM_TAG(op1);\n        tag2 = JS_VALUE_GET_NORM_TAG(op2);\n    }\n\n    if (tag1 == JS_TAG_STRING || tag2 == JS_TAG_STRING) {\n        sp[-2] = JS_ConcatString(ctx, op1, op2);\n        if (JS_IsException(sp[-2]))\n            goto exception;\n        return 0;\n    }\n\n    op1 = JS_ToNumericFree(ctx, op1);\n    if (JS_IsException(op1)) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    op2 = JS_ToNumericFree(ctx, op2);\n    if (JS_IsException(op2)) {\n        JS_FreeValue(ctx, op1);\n        goto exception;\n    }\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n\n    if (tag1 == JS_TAG_INT && tag2 == JS_TAG_INT) {\n        int32_t v1, v2;\n        int64_t v;\n        v1 = JS_VALUE_GET_INT(op1);\n        v2 = JS_VALUE_GET_INT(op2);\n        v = (int64_t)v1 + (int64_t)v2;\n        sp[-2] = JS_NewInt64(ctx, v);\n    } else if (tag1 == JS_TAG_BIG_DECIMAL || tag2 == JS_TAG_BIG_DECIMAL) {\n        if (ctx->rt->bigdecimal_ops.binary_arith(ctx, OP_add, sp - 2, op1, op2))\n            goto exception;\n    } else if (tag1 == JS_TAG_BIG_FLOAT || tag2 == JS_TAG_BIG_FLOAT) {\n        if (ctx->rt->bigfloat_ops.binary_arith(ctx, OP_add, sp - 2, op1, op2))\n            goto exception;\n    } else if (tag1 == JS_TAG_BIG_INT || tag2 == JS_TAG_BIG_INT) {\n    handle_bigint:\n        if (ctx->rt->bigint_ops.binary_arith(ctx, OP_add, sp - 2, op1, op2))\n            goto exception;\n    } else {\n        double d1, d2;\n        /* float64 result */\n        if (JS_ToFloat64Free(ctx, &d1, op1)) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n        if (JS_ToFloat64Free(ctx, &d2, op2))\n            goto exception;\n        if (is_math_mode(ctx) && is_safe_integer(d1) && is_safe_integer(d2))\n            goto handle_bigint;\n        sp[-2] = __JS_NewFloat64(ctx, d1 + d2);\n    }\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic no_inline __exception int js_binary_logic_slow(JSContext *ctx,\n                                                      JSValue *sp,\n                                                      OPCodeEnum op)\n{\n    JSValue op1, op2, res;\n    int ret;\n    uint32_t tag1, tag2;\n    uint32_t v1, v2, r;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n\n    /* try to call an overloaded operator */\n    if ((tag1 == JS_TAG_OBJECT &&\n         (tag2 != JS_TAG_NULL && tag2 != JS_TAG_UNDEFINED)) ||\n        (tag2 == JS_TAG_OBJECT &&\n         (tag1 != JS_TAG_NULL && tag1 != JS_TAG_UNDEFINED))) {\n        ret = js_call_binary_op_fallback(ctx, &res, op1, op2, op, TRUE, 0);\n        if (ret != 0) {\n            JS_FreeValue(ctx, op1);\n            JS_FreeValue(ctx, op2);\n            if (ret < 0) {\n                goto exception;\n            } else {\n                sp[-2] = res;\n                return 0;\n            }\n        }\n    }\n\n    op1 = JS_ToNumericFree(ctx, op1);\n    if (JS_IsException(op1)) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    op2 = JS_ToNumericFree(ctx, op2);\n    if (JS_IsException(op2)) {\n        JS_FreeValue(ctx, op1);\n        goto exception;\n    }\n\n    if (is_math_mode(ctx))\n        goto bigint_op;\n\n    tag1 = JS_VALUE_GET_TAG(op1);\n    tag2 = JS_VALUE_GET_TAG(op2);\n    if (tag1 == JS_TAG_BIG_INT || tag2 == JS_TAG_BIG_INT) {\n        if (tag1 != tag2) {\n            JS_FreeValue(ctx, op1);\n            JS_FreeValue(ctx, op2);\n            JS_ThrowTypeError(ctx, \"both operands must be bigint\");\n            goto exception;\n        } else {\n        bigint_op:\n            if (ctx->rt->bigint_ops.binary_arith(ctx, op, sp - 2, op1, op2))\n                goto exception;\n        }\n    } else {\n        if (unlikely(JS_ToInt32Free(ctx, (int32_t *)&v1, op1))) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n        if (unlikely(JS_ToInt32Free(ctx, (int32_t *)&v2, op2)))\n            goto exception;\n        switch(op) {\n        case OP_shl:\n            r = v1 << (v2 & 0x1f);\n            break;\n        case OP_sar:\n            r = (int)v1 >> (v2 & 0x1f);\n            break;\n        case OP_and:\n            r = v1 & v2;\n            break;\n        case OP_or:\n            r = v1 | v2;\n            break;\n        case OP_xor:\n            r = v1 ^ v2;\n            break;\n        default:\n            abort();\n        }\n        sp[-2] = JS_NewInt32(ctx, r);\n    }\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\n/* Note: also used for bigint */\nstatic int js_compare_bigfloat(JSContext *ctx, OPCodeEnum op,\n                               JSValue op1, JSValue op2)\n{\n    bf_t a_s, b_s, *a, *b;\n    int res;\n    \n    a = JS_ToBigFloat(ctx, &a_s, op1);\n    if (!a) {\n        JS_FreeValue(ctx, op2);\n        return -1;\n    }\n    b = JS_ToBigFloat(ctx, &b_s, op2);\n    if (!b) {\n        if (a == &a_s)\n            bf_delete(a);\n        JS_FreeValue(ctx, op1);\n        return -1;\n    }\n    switch(op) {\n    case OP_lt:\n        res = bf_cmp_lt(a, b); /* if NaN return false */\n        break;\n    case OP_lte:\n        res = bf_cmp_le(a, b); /* if NaN return false */\n        break;\n    case OP_gt:\n        res = bf_cmp_lt(b, a); /* if NaN return false */\n        break;\n    case OP_gte:\n        res = bf_cmp_le(b, a); /* if NaN return false */\n        break;\n    case OP_eq:\n        res = bf_cmp_eq(a, b); /* if NaN return false */\n        break;\n    default:\n        abort();\n    }\n    if (a == &a_s)\n        bf_delete(a);\n    if (b == &b_s)\n        bf_delete(b);\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    return res;\n}\n\nstatic int js_compare_bigdecimal(JSContext *ctx, OPCodeEnum op,\n                                 JSValue op1, JSValue op2)\n{\n    bfdec_t *a, *b;\n    int res;\n\n    /* Note: binary floats are converted to bigdecimal with\n       toString(). It is not mathematically correct but is consistent\n       with the BigDecimal() constructor behavior */\n    op1 = JS_ToBigDecimalFree(ctx, op1, TRUE);\n    if (JS_IsException(op1)) {\n        JS_FreeValue(ctx, op2);\n        return -1;\n    }\n    op2 = JS_ToBigDecimalFree(ctx, op2, TRUE);\n    if (JS_IsException(op2)) {\n        JS_FreeValue(ctx, op1);\n        return -1;\n    }\n    a = JS_ToBigDecimal(ctx, op1);\n    b = JS_ToBigDecimal(ctx, op2);\n    \n    switch(op) {\n    case OP_lt:\n        res = bfdec_cmp_lt(a, b); /* if NaN return false */\n        break;\n    case OP_lte:\n        res = bfdec_cmp_le(a, b); /* if NaN return false */\n        break;\n    case OP_gt:\n        res = bfdec_cmp_lt(b, a); /* if NaN return false */\n        break;\n    case OP_gte:\n        res = bfdec_cmp_le(b, a); /* if NaN return false */\n        break;\n    case OP_eq:\n        res = bfdec_cmp_eq(a, b); /* if NaN return false */\n        break;\n    default:\n        abort();\n    }\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    return res;\n}\n\nstatic no_inline int js_relational_slow(JSContext *ctx, JSValue *sp,\n                                        OPCodeEnum op)\n{\n    JSValue op1, op2, ret;\n    int res;\n    uint32_t tag1, tag2;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n    /* try to call an overloaded operator */\n    if ((tag1 == JS_TAG_OBJECT &&\n         (tag2 != JS_TAG_NULL && tag2 != JS_TAG_UNDEFINED)) ||\n        (tag2 == JS_TAG_OBJECT &&\n         (tag1 != JS_TAG_NULL && tag1 != JS_TAG_UNDEFINED))) {\n        res = js_call_binary_op_fallback(ctx, &ret, op1, op2, op,\n                                         FALSE, HINT_NUMBER);\n        if (res != 0) {\n            JS_FreeValue(ctx, op1);\n            JS_FreeValue(ctx, op2);\n            if (res < 0) {\n                goto exception;\n            } else {\n                sp[-2] = ret;\n                return 0;\n            }\n        }\n    }\n    op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NUMBER);\n    if (JS_IsException(op1)) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NUMBER);\n    if (JS_IsException(op2)) {\n        JS_FreeValue(ctx, op1);\n        goto exception;\n    }\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n\n    if (tag1 == JS_TAG_STRING && tag2 == JS_TAG_STRING) {\n        JSString *p1, *p2;\n        p1 = JS_VALUE_GET_STRING(op1);\n        p2 = JS_VALUE_GET_STRING(op2);\n        res = js_string_compare(ctx, p1, p2);\n        switch(op) {\n        case OP_lt:\n            res = (res < 0);\n            break;\n        case OP_lte:\n            res = (res <= 0);\n            break;\n        case OP_gt:\n            res = (res > 0);\n            break;\n        default:\n        case OP_gte:\n            res = (res >= 0);\n            break;\n        }\n        JS_FreeValue(ctx, op1);\n        JS_FreeValue(ctx, op2);\n    } else if ((tag1 <= JS_TAG_NULL || tag1 == JS_TAG_FLOAT64) &&\n               (tag2 <= JS_TAG_NULL || tag2 == JS_TAG_FLOAT64)) {\n        /* fast path for float64/int */\n        goto float64_compare;\n    } else {\n        if (((tag1 == JS_TAG_BIG_INT && tag2 == JS_TAG_STRING) ||\n             (tag2 == JS_TAG_BIG_INT && tag1 == JS_TAG_STRING)) &&\n            !is_math_mode(ctx)) {\n            if (tag1 == JS_TAG_STRING) {\n                op1 = JS_StringToBigInt(ctx, op1);\n                if (JS_VALUE_GET_TAG(op1) != JS_TAG_BIG_INT)\n                    goto invalid_bigint_string;\n            }\n            if (tag2 == JS_TAG_STRING) {\n                op2 = JS_StringToBigInt(ctx, op2);\n                if (JS_VALUE_GET_TAG(op2) != JS_TAG_BIG_INT) {\n                invalid_bigint_string:\n                    JS_FreeValue(ctx, op1);\n                    JS_FreeValue(ctx, op2);\n                    res = FALSE;\n                    goto done;\n                }\n            }\n        } else {\n            op1 = JS_ToNumericFree(ctx, op1);\n            if (JS_IsException(op1)) {\n                JS_FreeValue(ctx, op2);\n                goto exception;\n            }\n            op2 = JS_ToNumericFree(ctx, op2);\n            if (JS_IsException(op2)) {\n                JS_FreeValue(ctx, op1);\n                goto exception;\n            }\n        }\n\n        tag1 = JS_VALUE_GET_NORM_TAG(op1);\n        tag2 = JS_VALUE_GET_NORM_TAG(op2);\n\n        if (tag1 == JS_TAG_BIG_DECIMAL || tag2 == JS_TAG_BIG_DECIMAL) {\n            res = ctx->rt->bigdecimal_ops.compare(ctx, op, op1, op2);\n            if (res < 0)\n                goto exception;\n        } else if (tag1 == JS_TAG_BIG_FLOAT || tag2 == JS_TAG_BIG_FLOAT) {\n            res = ctx->rt->bigfloat_ops.compare(ctx, op, op1, op2);\n            if (res < 0)\n                goto exception;\n        } else if (tag1 == JS_TAG_BIG_INT || tag2 == JS_TAG_BIG_INT) {\n            res = ctx->rt->bigint_ops.compare(ctx, op, op1, op2);\n            if (res < 0)\n                goto exception;\n        } else {\n            double d1, d2;\n\n        float64_compare:\n            /* can use floating point comparison */\n            if (tag1 == JS_TAG_FLOAT64) {\n                d1 = JS_VALUE_GET_FLOAT64(op1);\n            } else {\n                d1 = JS_VALUE_GET_INT(op1);\n            }\n            if (tag2 == JS_TAG_FLOAT64) {\n                d2 = JS_VALUE_GET_FLOAT64(op2);\n            } else {\n                d2 = JS_VALUE_GET_INT(op2);\n            }\n            switch(op) {\n            case OP_lt:\n                res = (d1 < d2); /* if NaN return false */\n                break;\n            case OP_lte:\n                res = (d1 <= d2); /* if NaN return false */\n                break;\n            case OP_gt:\n                res = (d1 > d2); /* if NaN return false */\n                break;\n            default:\n            case OP_gte:\n                res = (d1 >= d2); /* if NaN return false */\n                break;\n            }\n        }\n    }\n done:\n    sp[-2] = JS_NewBool(ctx, res);\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic BOOL tag_is_number(uint32_t tag)\n{\n    return (tag == JS_TAG_INT || tag == JS_TAG_BIG_INT ||\n            tag == JS_TAG_FLOAT64 || tag == JS_TAG_BIG_FLOAT ||\n            tag == JS_TAG_BIG_DECIMAL);\n}\n\nstatic no_inline __exception int js_eq_slow(JSContext *ctx, JSValue *sp,\n                                            BOOL is_neq)\n{\n    JSValue op1, op2, ret;\n    int res;\n    uint32_t tag1, tag2;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n redo:\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n    if (tag_is_number(tag1) && tag_is_number(tag2)) {\n        if (tag1 == JS_TAG_INT && tag2 == JS_TAG_INT) {\n            res = JS_VALUE_GET_INT(op1) == JS_VALUE_GET_INT(op2);\n        } else if ((tag1 == JS_TAG_FLOAT64 &&\n                    (tag2 == JS_TAG_INT || tag2 == JS_TAG_FLOAT64)) ||\n                   (tag2 == JS_TAG_FLOAT64 &&\n                    (tag1 == JS_TAG_INT || tag1 == JS_TAG_FLOAT64))) {\n            double d1, d2;\n            if (tag1 == JS_TAG_FLOAT64) {\n                d1 = JS_VALUE_GET_FLOAT64(op1);\n            } else {\n                d1 = JS_VALUE_GET_INT(op1);\n            }\n            if (tag2 == JS_TAG_FLOAT64) {\n                d2 = JS_VALUE_GET_FLOAT64(op2);\n            } else {\n                d2 = JS_VALUE_GET_INT(op2);\n            }\n            res = (d1 == d2);\n        } else if (tag1 == JS_TAG_BIG_DECIMAL || tag2 == JS_TAG_BIG_DECIMAL) {\n            res = ctx->rt->bigdecimal_ops.compare(ctx, OP_eq, op1, op2);\n            if (res < 0)\n                goto exception;\n        } else if (tag1 == JS_TAG_BIG_FLOAT || tag2 == JS_TAG_BIG_FLOAT) {\n            res = ctx->rt->bigfloat_ops.compare(ctx, OP_eq, op1, op2);\n            if (res < 0)\n                goto exception;\n        } else {\n            res = ctx->rt->bigint_ops.compare(ctx, OP_eq, op1, op2);\n            if (res < 0)\n                goto exception;\n        }\n    } else if (tag1 == tag2) {\n        if (tag1 == JS_TAG_OBJECT) {\n            /* try the fallback operator */\n            res = js_call_binary_op_fallback(ctx, &ret, op1, op2,\n                                             is_neq ? OP_neq : OP_eq,\n                                             FALSE, HINT_NONE);\n            if (res != 0) {\n                JS_FreeValue(ctx, op1);\n                JS_FreeValue(ctx, op2);\n                if (res < 0) {\n                    goto exception;\n                } else {\n                    sp[-2] = ret;\n                    return 0;\n                }\n            }\n        }\n        res = js_strict_eq2(ctx, op1, op2, JS_EQ_STRICT);\n    } else if ((tag1 == JS_TAG_NULL && tag2 == JS_TAG_UNDEFINED) ||\n               (tag2 == JS_TAG_NULL && tag1 == JS_TAG_UNDEFINED)) {\n        res = TRUE;\n    } else if ((tag1 == JS_TAG_STRING && tag_is_number(tag2)) ||\n               (tag2 == JS_TAG_STRING && tag_is_number(tag1))) {\n\n        if ((tag1 == JS_TAG_BIG_INT || tag2 == JS_TAG_BIG_INT) &&\n            !is_math_mode(ctx)) {\n            if (tag1 == JS_TAG_STRING) {\n                op1 = JS_StringToBigInt(ctx, op1);\n                if (JS_VALUE_GET_TAG(op1) != JS_TAG_BIG_INT)\n                    goto invalid_bigint_string;\n            }\n            if (tag2 == JS_TAG_STRING) {\n                op2 = JS_StringToBigInt(ctx, op2);\n                if (JS_VALUE_GET_TAG(op2) != JS_TAG_BIG_INT) {\n                invalid_bigint_string:\n                    JS_FreeValue(ctx, op1);\n                    JS_FreeValue(ctx, op2);\n                    res = FALSE;\n                    goto done;\n                }\n            }\n        } else {\n            op1 = JS_ToNumericFree(ctx, op1);\n            if (JS_IsException(op1)) {\n                JS_FreeValue(ctx, op2);\n                goto exception;\n            }\n            op2 = JS_ToNumericFree(ctx, op2);\n            if (JS_IsException(op2)) {\n                JS_FreeValue(ctx, op1);\n                goto exception;\n            }\n        }\n        res = js_strict_eq(ctx, op1, op2);\n    } else if (tag1 == JS_TAG_BOOL) {\n        op1 = JS_NewInt32(ctx, JS_VALUE_GET_INT(op1));\n        goto redo;\n    } else if (tag2 == JS_TAG_BOOL) {\n        op2 = JS_NewInt32(ctx, JS_VALUE_GET_INT(op2));\n        goto redo;\n    } else if ((tag1 == JS_TAG_OBJECT &&\n                (tag_is_number(tag2) || tag2 == JS_TAG_STRING || tag2 == JS_TAG_SYMBOL)) ||\n               (tag2 == JS_TAG_OBJECT &&\n                (tag_is_number(tag1) || tag1 == JS_TAG_STRING || tag1 == JS_TAG_SYMBOL))) {\n\n        /* try the fallback operator */\n        res = js_call_binary_op_fallback(ctx, &ret, op1, op2,\n                                         is_neq ? OP_neq : OP_eq,\n                                         FALSE, HINT_NONE);\n        if (res != 0) {\n            JS_FreeValue(ctx, op1);\n            JS_FreeValue(ctx, op2);\n            if (res < 0) {\n                goto exception;\n            } else {\n                sp[-2] = ret;\n                return 0;\n            }\n        }\n\n        op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE);\n        if (JS_IsException(op1)) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n        op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NONE);\n        if (JS_IsException(op2)) {\n            JS_FreeValue(ctx, op1);\n            goto exception;\n        }\n        goto redo;\n    } else {\n        /* IsHTMLDDA object is equivalent to undefined for '==' and '!=' */\n        if ((JS_IsHTMLDDA(ctx, op1) &&\n             (tag2 == JS_TAG_NULL || tag2 == JS_TAG_UNDEFINED)) ||\n            (JS_IsHTMLDDA(ctx, op2) &&\n             (tag1 == JS_TAG_NULL || tag1 == JS_TAG_UNDEFINED))) {\n            res = TRUE;\n        } else {\n            res = FALSE;\n        }\n        JS_FreeValue(ctx, op1);\n        JS_FreeValue(ctx, op2);\n    }\n done:\n    sp[-2] = JS_NewBool(ctx, res ^ is_neq);\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic no_inline int js_shr_slow(JSContext *ctx, JSValue *sp)\n{\n    JSValue op1, op2;\n    uint32_t v1, v2, r;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    op1 = JS_ToNumericFree(ctx, op1);\n    if (JS_IsException(op1)) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    op2 = JS_ToNumericFree(ctx, op2);\n    if (JS_IsException(op2)) {\n        JS_FreeValue(ctx, op1);\n        goto exception;\n    }\n    /* XXX: could forbid >>> in bignum mode */\n    if (!is_math_mode(ctx) &&\n        (JS_VALUE_GET_TAG(op1) == JS_TAG_BIG_INT ||\n         JS_VALUE_GET_TAG(op2) == JS_TAG_BIG_INT)) {\n        JS_ThrowTypeError(ctx, \"bigint operands are forbidden for >>>\");\n        JS_FreeValue(ctx, op1);\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    /* cannot give an exception */\n    JS_ToUint32Free(ctx, &v1, op1);\n    JS_ToUint32Free(ctx, &v2, op2);\n    r = v1 >> (v2 & 0x1f);\n    sp[-2] = JS_NewUint32(ctx, r);\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic JSValue js_mul_pow10_to_float64(JSContext *ctx, const bf_t *a,\n                                       int64_t exponent)\n{\n    bf_t r_s, *r = &r_s;\n    double d;\n    int ret;\n    \n    /* always convert to Float64 */\n    bf_init(ctx->bf_ctx, r);\n    ret = bf_mul_pow_radix(r, a, 10, exponent,\n                           53, bf_set_exp_bits(11) | BF_RNDN |\n                           BF_FLAG_SUBNORMAL);\n    bf_get_float64(r, &d, BF_RNDN);\n    bf_delete(r);\n    if (ret & BF_ST_MEM_ERROR)\n        return JS_ThrowOutOfMemory(ctx);\n    else\n        return __JS_NewFloat64(ctx, d);\n}\n\nstatic no_inline int js_mul_pow10(JSContext *ctx, JSValue *sp)\n{\n    bf_t a_s, *a, *r;\n    JSValue op1, op2, res;\n    int64_t e;\n    int ret;\n\n    res = JS_NewBigFloat(ctx);\n    if (JS_IsException(res))\n        return -1;\n    r = JS_GetBigFloat(res);\n    op1 = sp[-2];\n    op2 = sp[-1];\n    a = JS_ToBigFloat(ctx, &a_s, op1);\n    if (!a)\n        return -1;\n    if (JS_IsBigInt(ctx, op2)) {\n        ret = JS_ToBigInt64(ctx, &e, op2);\n    } else {\n        ret = JS_ToInt64(ctx, &e, op2);\n    }\n    if (ret) {\n        if (a == &a_s)\n            bf_delete(a);\n        JS_FreeValue(ctx, res);\n        return -1;\n    }\n\n    bf_mul_pow_radix(r, a, 10, e, ctx->fp_env.prec, ctx->fp_env.flags);\n    if (a == &a_s)\n        bf_delete(a);\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    sp[-2] = res;\n    return 0;\n}\n\n#else /* !CONFIG_BIGNUM */\n\nstatic JSValue JS_ThrowUnsupportedBigint(JSContext *ctx)\n{\n    return JS_ThrowTypeError(ctx, \"bigint is not supported\");\n}\n\nJSValue JS_NewBigInt64(JSContext *ctx, int64_t v)\n{\n    return JS_ThrowUnsupportedBigint(ctx);\n}\n\nJSValue JS_NewBigUint64(JSContext *ctx, uint64_t v)\n{\n    return JS_ThrowUnsupportedBigint(ctx);\n}\n\nint JS_ToBigInt64(JSContext *ctx, int64_t *pres, JSValueConst val)\n{\n    JS_ThrowUnsupportedBigint(ctx);\n    *pres = 0;\n    return -1;\n}\n\nstatic no_inline __exception int js_unary_arith_slow(JSContext *ctx,\n                                                     JSValue *sp,\n                                                     OPCodeEnum op)\n{\n    JSValue op1;\n    double d;\n\n    op1 = sp[-1];\n    if (unlikely(JS_ToFloat64Free(ctx, &d, op1))) {\n        sp[-1] = JS_UNDEFINED;\n        return -1;\n    }\n    switch(op) {\n    case OP_inc:\n        d++;\n        break;\n    case OP_dec:\n        d--;\n        break;\n    case OP_plus:\n        break;\n    case OP_neg:\n        d = -d;\n        break;\n    default:\n        abort();\n    }\n    sp[-1] = JS_NewFloat64(ctx, d);\n    return 0;\n}\n\n/* specific case necessary for correct return value semantics */\nstatic __exception int js_post_inc_slow(JSContext *ctx,\n                                        JSValue *sp, OPCodeEnum op)\n{\n    JSValue op1;\n    double d, r;\n\n    op1 = sp[-1];\n    if (unlikely(JS_ToFloat64Free(ctx, &d, op1))) {\n        sp[-1] = JS_UNDEFINED;\n        return -1;\n    }\n    r = d + 2 * (op - OP_post_dec) - 1;\n    sp[0] = JS_NewFloat64(ctx, r);\n    sp[-1] = JS_NewFloat64(ctx, d);\n    return 0;\n}\n\nstatic no_inline __exception int js_binary_arith_slow(JSContext *ctx, JSValue *sp,\n                                                      OPCodeEnum op)\n{\n    JSValue op1, op2;\n    double d1, d2, r;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    if (unlikely(JS_ToFloat64Free(ctx, &d1, op1))) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    if (unlikely(JS_ToFloat64Free(ctx, &d2, op2))) {\n        goto exception;\n    }\n    switch(op) {\n    case OP_sub:\n        r = d1 - d2;\n        break;\n    case OP_mul:\n        r = d1 * d2;\n        break;\n    case OP_div:\n        r = d1 / d2;\n        break;\n    case OP_mod:\n        r = fmod(d1, d2);\n        break;\n    case OP_pow:\n        r = js_pow(d1, d2);\n        break;\n    default:\n        abort();\n    }\n    sp[-2] = JS_NewFloat64(ctx, r);\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic no_inline __exception int js_add_slow(JSContext *ctx, JSValue *sp)\n{\n    JSValue op1, op2;\n    uint32_t tag1, tag2;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    tag1 = JS_VALUE_GET_TAG(op1);\n    tag2 = JS_VALUE_GET_TAG(op2);\n    if ((tag1 == JS_TAG_INT || JS_TAG_IS_FLOAT64(tag1)) &&\n        (tag2 == JS_TAG_INT || JS_TAG_IS_FLOAT64(tag2))) {\n        goto add_numbers;\n    } else {\n        op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE);\n        if (JS_IsException(op1)) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n        op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NONE);\n        if (JS_IsException(op2)) {\n            JS_FreeValue(ctx, op1);\n            goto exception;\n        }\n        tag1 = JS_VALUE_GET_TAG(op1);\n        tag2 = JS_VALUE_GET_TAG(op2);\n        if (tag1 == JS_TAG_STRING || tag2 == JS_TAG_STRING) {\n            sp[-2] = JS_ConcatString(ctx, op1, op2);\n            if (JS_IsException(sp[-2]))\n                goto exception;\n        } else {\n            double d1, d2;\n        add_numbers:\n            if (JS_ToFloat64Free(ctx, &d1, op1)) {\n                JS_FreeValue(ctx, op2);\n                goto exception;\n            }\n            if (JS_ToFloat64Free(ctx, &d2, op2))\n                goto exception;\n            sp[-2] = JS_NewFloat64(ctx, d1 + d2);\n        }\n    }\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic no_inline __exception int js_binary_logic_slow(JSContext *ctx,\n                                                      JSValue *sp,\n                                                      OPCodeEnum op)\n{\n    JSValue op1, op2;\n    uint32_t v1, v2, r;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    if (unlikely(JS_ToInt32Free(ctx, (int32_t *)&v1, op1))) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    if (unlikely(JS_ToInt32Free(ctx, (int32_t *)&v2, op2)))\n        goto exception;\n    switch(op) {\n    case OP_shl:\n        r = v1 << (v2 & 0x1f);\n        break;\n    case OP_sar:\n        r = (int)v1 >> (v2 & 0x1f);\n        break;\n    case OP_and:\n        r = v1 & v2;\n        break;\n    case OP_or:\n        r = v1 | v2;\n        break;\n    case OP_xor:\n        r = v1 ^ v2;\n        break;\n    default:\n        abort();\n    }\n    sp[-2] = JS_NewInt32(ctx, r);\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic no_inline int js_not_slow(JSContext *ctx, JSValue *sp)\n{\n    int32_t v1;\n\n    if (unlikely(JS_ToInt32Free(ctx, &v1, sp[-1]))) {\n        sp[-1] = JS_UNDEFINED;\n        return -1;\n    }\n    sp[-1] = JS_NewInt32(ctx, ~v1);\n    return 0;\n}\n\nstatic no_inline int js_relational_slow(JSContext *ctx, JSValue *sp,\n                                        OPCodeEnum op)\n{\n    JSValue op1, op2;\n    int res;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NUMBER);\n    if (JS_IsException(op1)) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NUMBER);\n    if (JS_IsException(op2)) {\n        JS_FreeValue(ctx, op1);\n        goto exception;\n    }\n    if (JS_VALUE_GET_TAG(op1) == JS_TAG_STRING &&\n        JS_VALUE_GET_TAG(op2) == JS_TAG_STRING) {\n        JSString *p1, *p2;\n        p1 = JS_VALUE_GET_STRING(op1);\n        p2 = JS_VALUE_GET_STRING(op2);\n        res = js_string_compare(ctx, p1, p2);\n        JS_FreeValue(ctx, op1);\n        JS_FreeValue(ctx, op2);\n        switch(op) {\n        case OP_lt:\n            res = (res < 0);\n            break;\n        case OP_lte:\n            res = (res <= 0);\n            break;\n        case OP_gt:\n            res = (res > 0);\n            break;\n        default:\n        case OP_gte:\n            res = (res >= 0);\n            break;\n        }\n    } else {\n        double d1, d2;\n        if (JS_ToFloat64Free(ctx, &d1, op1)) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n        if (JS_ToFloat64Free(ctx, &d2, op2))\n            goto exception;\n        switch(op) {\n        case OP_lt:\n            res = (d1 < d2); /* if NaN return false */\n            break;\n        case OP_lte:\n            res = (d1 <= d2); /* if NaN return false */\n            break;\n        case OP_gt:\n            res = (d1 > d2); /* if NaN return false */\n            break;\n        default:\n        case OP_gte:\n            res = (d1 >= d2); /* if NaN return false */\n            break;\n        }\n    }\n    sp[-2] = JS_NewBool(ctx, res);\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic no_inline __exception int js_eq_slow(JSContext *ctx, JSValue *sp,\n                                            BOOL is_neq)\n{\n    JSValue op1, op2;\n    int tag1, tag2;\n    BOOL res;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n redo:\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n    if (tag1 == tag2 ||\n        (tag1 == JS_TAG_INT && tag2 == JS_TAG_FLOAT64) ||\n        (tag2 == JS_TAG_INT && tag1 == JS_TAG_FLOAT64)) {\n        res = js_strict_eq(ctx, op1, op2);\n    } else if ((tag1 == JS_TAG_NULL && tag2 == JS_TAG_UNDEFINED) ||\n               (tag2 == JS_TAG_NULL && tag1 == JS_TAG_UNDEFINED)) {\n        res = TRUE;\n    } else if ((tag1 == JS_TAG_STRING && (tag2 == JS_TAG_INT ||\n                                   tag2 == JS_TAG_FLOAT64)) ||\n        (tag2 == JS_TAG_STRING && (tag1 == JS_TAG_INT ||\n                                   tag1 == JS_TAG_FLOAT64))) {\n        double d1;\n        double d2;\n        if (JS_ToFloat64Free(ctx, &d1, op1)) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n        if (JS_ToFloat64Free(ctx, &d2, op2))\n            goto exception;\n        res = (d1 == d2);\n    } else if (tag1 == JS_TAG_BOOL) {\n        op1 = JS_NewInt32(ctx, JS_VALUE_GET_INT(op1));\n        goto redo;\n    } else if (tag2 == JS_TAG_BOOL) {\n        op2 = JS_NewInt32(ctx, JS_VALUE_GET_INT(op2));\n        goto redo;\n    } else if (tag1 == JS_TAG_OBJECT &&\n               (tag2 == JS_TAG_INT || tag2 == JS_TAG_FLOAT64 || tag2 == JS_TAG_STRING || tag2 == JS_TAG_SYMBOL)) {\n        op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE);\n        if (JS_IsException(op1)) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n        goto redo;\n    } else if (tag2 == JS_TAG_OBJECT &&\n               (tag1 == JS_TAG_INT || tag1 == JS_TAG_FLOAT64 || tag1 == JS_TAG_STRING || tag1 == JS_TAG_SYMBOL)) {\n        op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NONE);\n        if (JS_IsException(op2)) {\n            JS_FreeValue(ctx, op1);\n            goto exception;\n        }\n        goto redo;\n    } else {\n        /* IsHTMLDDA object is equivalent to undefined for '==' and '!=' */\n        if ((JS_IsHTMLDDA(ctx, op1) &&\n             (tag2 == JS_TAG_NULL || tag2 == JS_TAG_UNDEFINED)) ||\n            (JS_IsHTMLDDA(ctx, op2) &&\n             (tag1 == JS_TAG_NULL || tag1 == JS_TAG_UNDEFINED))) {\n            res = TRUE;\n        } else {\n            res = FALSE;\n        }\n        JS_FreeValue(ctx, op1);\n        JS_FreeValue(ctx, op2);\n    }\n    sp[-2] = JS_NewBool(ctx, res ^ is_neq);\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic no_inline int js_shr_slow(JSContext *ctx, JSValue *sp)\n{\n    JSValue op1, op2;\n    uint32_t v1, v2, r;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    if (unlikely(JS_ToUint32Free(ctx, &v1, op1))) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    if (unlikely(JS_ToUint32Free(ctx, &v2, op2)))\n        goto exception;\n    r = v1 >> (v2 & 0x1f);\n    sp[-2] = JS_NewUint32(ctx, r);\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\n#endif /* !CONFIG_BIGNUM */\n\n/* XXX: Should take JSValueConst arguments */\nstatic BOOL js_strict_eq2(JSContext *ctx, JSValue op1, JSValue op2,\n                          JSStrictEqModeEnum eq_mode)\n{\n    BOOL res;\n    int tag1, tag2;\n    double d1, d2;\n\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n    switch(tag1) {\n    case JS_TAG_BOOL:\n        if (tag1 != tag2) {\n            res = FALSE;\n        } else {\n            res = JS_VALUE_GET_INT(op1) == JS_VALUE_GET_INT(op2);\n            goto done_no_free;\n        }\n        break;\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        res = (tag1 == tag2);\n        break;\n    case JS_TAG_STRING:\n        {\n            JSString *p1, *p2;\n            if (tag1 != tag2) {\n                res = FALSE;\n            } else {\n                p1 = JS_VALUE_GET_STRING(op1);\n                p2 = JS_VALUE_GET_STRING(op2);\n                res = (js_string_compare(ctx, p1, p2) == 0);\n            }\n        }\n        break;\n    case JS_TAG_SYMBOL:\n        {\n            JSAtomStruct *p1, *p2;\n            if (tag1 != tag2) {\n                res = FALSE;\n            } else {\n                p1 = JS_VALUE_GET_PTR(op1);\n                p2 = JS_VALUE_GET_PTR(op2);\n                res = (p1 == p2);\n            }\n        }\n        break;\n    case JS_TAG_OBJECT:\n        if (tag1 != tag2)\n            res = FALSE;\n        else\n            res = JS_VALUE_GET_OBJ(op1) == JS_VALUE_GET_OBJ(op2);\n        break;\n    case JS_TAG_INT:\n        d1 = JS_VALUE_GET_INT(op1);\n        if (tag2 == JS_TAG_INT) {\n            d2 = JS_VALUE_GET_INT(op2);\n            goto number_test;\n        } else if (tag2 == JS_TAG_FLOAT64) {\n            d2 = JS_VALUE_GET_FLOAT64(op2);\n            goto number_test;\n        } else {\n            res = FALSE;\n        }\n        break;\n    case JS_TAG_FLOAT64:\n        d1 = JS_VALUE_GET_FLOAT64(op1);\n        if (tag2 == JS_TAG_FLOAT64) {\n            d2 = JS_VALUE_GET_FLOAT64(op2);\n        } else if (tag2 == JS_TAG_INT) {\n            d2 = JS_VALUE_GET_INT(op2);\n        } else {\n            res = FALSE;\n            break;\n        }\n    number_test:\n        if (unlikely(eq_mode >= JS_EQ_SAME_VALUE)) {\n            JSFloat64Union u1, u2;\n            /* NaN is not always normalized, so this test is necessary */\n            if (isnan(d1) || isnan(d2)) {\n                res = isnan(d1) == isnan(d2);\n            } else if (eq_mode == JS_EQ_SAME_VALUE_ZERO) {\n                res = (d1 == d2); /* +0 == -0 */\n            } else {\n                u1.d = d1;\n                u2.d = d2;\n                res = (u1.u64 == u2.u64); /* +0 != -0 */\n            }\n        } else {\n            res = (d1 == d2); /* if NaN return false and +0 == -0 */\n        }\n        goto done_no_free;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n        {\n            bf_t a_s, *a, b_s, *b;\n            if (tag1 != tag2) {\n                res = FALSE;\n                break;\n            }\n            a = JS_ToBigFloat(ctx, &a_s, op1);\n            b = JS_ToBigFloat(ctx, &b_s, op2);\n            res = bf_cmp_eq(a, b);\n            if (a == &a_s)\n                bf_delete(a);\n            if (b == &b_s)\n                bf_delete(b);\n        }\n        break;\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p1, *p2;\n            const bf_t *a, *b;\n            if (tag1 != tag2) {\n                res = FALSE;\n                break;\n            }\n            p1 = JS_VALUE_GET_PTR(op1);\n            p2 = JS_VALUE_GET_PTR(op2);\n            a = &p1->num;\n            b = &p2->num;\n            if (unlikely(eq_mode >= JS_EQ_SAME_VALUE)) {\n                if (eq_mode == JS_EQ_SAME_VALUE_ZERO &&\n                           a->expn == BF_EXP_ZERO && b->expn == BF_EXP_ZERO) {\n                    res = TRUE;\n                } else {\n                    res = (bf_cmp_full(a, b) == 0);\n                }\n            } else {\n                res = bf_cmp_eq(a, b);\n            }\n        }\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        {\n            JSBigDecimal *p1, *p2;\n            const bfdec_t *a, *b;\n            if (tag1 != tag2) {\n                res = FALSE;\n                break;\n            }\n            p1 = JS_VALUE_GET_PTR(op1);\n            p2 = JS_VALUE_GET_PTR(op2);\n            a = &p1->num;\n            b = &p2->num;\n            res = bfdec_cmp_eq(a, b);\n        }\n        break;\n#endif\n    default:\n        res = FALSE;\n        break;\n    }\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n done_no_free:\n    return res;\n}\n\nstatic BOOL js_strict_eq(JSContext *ctx, JSValue op1, JSValue op2)\n{\n    return js_strict_eq2(ctx, op1, op2, JS_EQ_STRICT);\n}\n\nstatic BOOL js_same_value(JSContext *ctx, JSValueConst op1, JSValueConst op2)\n{\n    return js_strict_eq2(ctx,\n                         JS_DupValue(ctx, op1), JS_DupValue(ctx, op2),\n                         JS_EQ_SAME_VALUE);\n}\n\nstatic BOOL js_same_value_zero(JSContext *ctx, JSValueConst op1, JSValueConst op2)\n{\n    return js_strict_eq2(ctx,\n                         JS_DupValue(ctx, op1), JS_DupValue(ctx, op2),\n                         JS_EQ_SAME_VALUE_ZERO);\n}\n\nstatic no_inline int js_strict_eq_slow(JSContext *ctx, JSValue *sp,\n                                       BOOL is_neq)\n{\n    BOOL res;\n    res = js_strict_eq(ctx, sp[-2], sp[-1]);\n    sp[-2] = JS_NewBool(ctx, res ^ is_neq);\n    return 0;\n}\n\nstatic __exception int js_operator_in(JSContext *ctx, JSValue *sp)\n{\n    JSValue op1, op2;\n    JSAtom atom;\n    int ret;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n\n    if (JS_VALUE_GET_TAG(op2) != JS_TAG_OBJECT) {\n        JS_ThrowTypeError(ctx, \"invalid 'in' operand\");\n        return -1;\n    }\n    atom = JS_ValueToAtom(ctx, op1);\n    if (unlikely(atom == JS_ATOM_NULL))\n        return -1;\n    ret = JS_HasProperty(ctx, op2, atom);\n    JS_FreeAtom(ctx, atom);\n    if (ret < 0)\n        return -1;\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    sp[-2] = JS_NewBool(ctx, ret);\n    return 0;\n}\n\nstatic __exception int js_has_unscopable(JSContext *ctx, JSValueConst obj,\n                                         JSAtom atom)\n{\n    JSValue arr, val;\n    int ret;\n\n    arr = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_unscopables);\n    if (JS_IsException(arr))\n        return -1;\n    ret = 0;\n    if (JS_IsObject(arr)) {\n        val = JS_GetProperty(ctx, arr, atom);\n        ret = JS_ToBoolFree(ctx, val);\n    }\n    JS_FreeValue(ctx, arr);\n    return ret;\n}\n\nstatic __exception int js_operator_instanceof(JSContext *ctx, JSValue *sp)\n{\n    JSValue op1, op2;\n    BOOL ret;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    ret = JS_IsInstanceOf(ctx, op1, op2);\n    if (ret < 0)\n        return ret;\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    sp[-2] = JS_NewBool(ctx, ret);\n    return 0;\n}\n\nstatic __exception int js_operator_typeof(JSContext *ctx, JSValueConst op1)\n{\n    JSAtom atom;\n    uint32_t tag;\n\n    tag = JS_VALUE_GET_NORM_TAG(op1);\n    switch(tag) {\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n        atom = JS_ATOM_bigint;\n        break;\n    case JS_TAG_BIG_FLOAT:\n        atom = JS_ATOM_bigfloat;\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        atom = JS_ATOM_bigdecimal;\n        break;\n#endif\n    case JS_TAG_INT:\n    case JS_TAG_FLOAT64:\n        atom = JS_ATOM_number;\n        break;\n    case JS_TAG_UNDEFINED:\n        atom = JS_ATOM_undefined;\n        break;\n    case JS_TAG_BOOL:\n        atom = JS_ATOM_boolean;\n        break;\n    case JS_TAG_STRING:\n        atom = JS_ATOM_string;\n        break;\n    case JS_TAG_OBJECT:\n        {\n            JSObject *p;\n            p = JS_VALUE_GET_OBJ(op1);\n            if (unlikely(p->is_HTMLDDA)) \n                atom = JS_ATOM_undefined;\n            else if (JS_IsFunction(ctx, op1))\n                atom = JS_ATOM_function;\n            else\n                goto obj_type;\n        }\n        break;\n    case JS_TAG_NULL:\n    obj_type:\n        atom = JS_ATOM_object;\n        break;\n    case JS_TAG_SYMBOL:\n        atom = JS_ATOM_symbol;\n        break;\n    default:\n        atom = JS_ATOM_unknown;\n        break;\n    }\n    return atom;\n}\n\nstatic __exception int js_operator_delete(JSContext *ctx, JSValue *sp)\n{\n    JSValue op1, op2;\n    JSAtom atom;\n    int ret;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    atom = JS_ValueToAtom(ctx, op2);\n    if (unlikely(atom == JS_ATOM_NULL))\n        return -1;\n    ret = JS_DeleteProperty(ctx, op1, atom, JS_PROP_THROW_STRICT);\n    JS_FreeAtom(ctx, atom);\n    if (unlikely(ret < 0))\n        return -1;\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    sp[-2] = JS_NewBool(ctx, ret);\n    return 0;\n}\n\nstatic JSValue js_throw_type_error(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    return JS_ThrowTypeError(ctx, \"invalid property access\");\n}\n\n/* XXX: not 100% compatible, but mozilla seems to use a similar\n   implementation to ensure that caller in non strict mode does not\n   throw (ES5 compatibility) */\nstatic JSValue js_function_proto_caller(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv)\n{\n    JSFunctionBytecode *b = JS_GetFunctionBytecode(this_val);\n    if (!b || (b->js_mode & JS_MODE_STRICT) || !b->has_prototype) {\n        return js_throw_type_error(ctx, this_val, 0, NULL);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_function_proto_fileName(JSContext *ctx,\n                                          JSValueConst this_val)\n{\n    JSFunctionBytecode *b = JS_GetFunctionBytecode(this_val);\n    if (b && b->has_debug) {\n        return JS_AtomToString(ctx, b->debug.filename);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_function_proto_lineNumber(JSContext *ctx,\n                                            JSValueConst this_val)\n{\n    JSFunctionBytecode *b = JS_GetFunctionBytecode(this_val);\n    if (b && b->has_debug) {\n        return JS_NewInt32(ctx, b->debug.line_num);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic int js_arguments_define_own_property(JSContext *ctx,\n                                            JSValueConst this_obj,\n                                            JSAtom prop, JSValueConst val,\n                                            JSValueConst getter, JSValueConst setter, int flags)\n{\n    JSObject *p;\n    uint32_t idx;\n    p = JS_VALUE_GET_OBJ(this_obj);\n    /* convert to normal array when redefining an existing numeric field */\n    if (p->fast_array && JS_AtomIsArrayIndex(ctx, &idx, prop) &&\n        idx < p->u.array.count) {\n        if (convert_fast_array_to_array(ctx, p))\n            return -1;\n    }\n    /* run the default define own property */\n    return JS_DefineProperty(ctx, this_obj, prop, val, getter, setter,\n                             flags | JS_PROP_NO_EXOTIC);\n}\n\nstatic const JSClassExoticMethods js_arguments_exotic_methods = {\n    .define_own_property = js_arguments_define_own_property,\n};\n\nstatic JSValue js_build_arguments(JSContext *ctx, int argc, JSValueConst *argv)\n{\n    JSValue val, *tab;\n    JSProperty *pr;\n    JSObject *p;\n    int i;\n\n    val = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],\n                                 JS_CLASS_ARGUMENTS);\n    if (JS_IsException(val))\n        return val;\n    p = JS_VALUE_GET_OBJ(val);\n\n    /* add the length field (cannot fail) */\n    pr = add_property(ctx, p, JS_ATOM_length,\n                      JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    pr->u.value = JS_NewInt32(ctx, argc);\n\n    /* initialize the fast array part */\n    tab = NULL;\n    if (argc > 0) {\n        tab = js_malloc(ctx, sizeof(tab[0]) * argc);\n        if (!tab) {\n            JS_FreeValue(ctx, val);\n            return JS_EXCEPTION;\n        }\n        for(i = 0; i < argc; i++) {\n            tab[i] = JS_DupValue(ctx, argv[i]);\n        }\n    }\n    p->u.array.u.values = tab;\n    p->u.array.count = argc;\n\n    JS_DefinePropertyValue(ctx, val, JS_ATOM_Symbol_iterator,\n                           JS_DupValue(ctx, ctx->array_proto_values),\n                           JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE);\n    /* add callee property to throw a TypeError in strict mode */\n    JS_DefineProperty(ctx, val, JS_ATOM_callee, JS_UNDEFINED,\n                      ctx->throw_type_error, ctx->throw_type_error,\n                      JS_PROP_HAS_GET | JS_PROP_HAS_SET);\n    return val;\n}\n\n#define GLOBAL_VAR_OFFSET 0x40000000\n#define ARGUMENT_VAR_OFFSET 0x20000000\n\n/* legacy arguments object: add references to the function arguments */\nstatic JSValue js_build_mapped_arguments(JSContext *ctx, int argc,\n                                         JSValueConst *argv,\n                                         JSStackFrame *sf, int arg_count)\n{\n    JSValue val;\n    JSProperty *pr;\n    JSObject *p;\n    int i;\n\n    val = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],\n                                 JS_CLASS_MAPPED_ARGUMENTS);\n    if (JS_IsException(val))\n        return val;\n    p = JS_VALUE_GET_OBJ(val);\n\n    /* add the length field (cannot fail) */\n    pr = add_property(ctx, p, JS_ATOM_length,\n                      JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    pr->u.value = JS_NewInt32(ctx, argc);\n\n    for(i = 0; i < arg_count; i++) {\n        JSVarRef *var_ref;\n        var_ref = get_var_ref(ctx, sf, i, TRUE);\n        if (!var_ref)\n            goto fail;\n        pr = add_property(ctx, p, __JS_AtomFromUInt32(i), JS_PROP_C_W_E | JS_PROP_VARREF);\n        if (!pr) {\n            free_var_ref(ctx->rt, var_ref);\n            goto fail;\n        }\n        pr->u.var_ref = var_ref;\n    }\n\n    /* the arguments not mapped to the arguments of the function can\n       be normal properties */\n    for(i = arg_count; i < argc; i++) {\n        if (JS_DefinePropertyValueUint32(ctx, val, i,\n                                         JS_DupValue(ctx, argv[i]),\n                                         JS_PROP_C_W_E) < 0)\n            goto fail;\n    }\n\n    JS_DefinePropertyValue(ctx, val, JS_ATOM_Symbol_iterator,\n                           JS_DupValue(ctx, ctx->array_proto_values),\n                           JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE);\n    /* callee returns this function in non strict mode */\n    JS_DefinePropertyValue(ctx, val, JS_ATOM_callee,\n                           JS_DupValue(ctx, ctx->rt->current_stack_frame->cur_func),\n                           JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE);\n    return val;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_build_rest(JSContext *ctx, int first, int argc, JSValueConst *argv)\n{\n    JSValue val;\n    int i, ret;\n\n    val = JS_NewArray(ctx);\n    if (JS_IsException(val))\n        return val;\n    for (i = first; i < argc; i++) {\n        ret = JS_DefinePropertyValueUint32(ctx, val, i - first,\n                                           JS_DupValue(ctx, argv[i]),\n                                           JS_PROP_C_W_E);\n        if (ret < 0) {\n            JS_FreeValue(ctx, val);\n            return JS_EXCEPTION;\n        }\n    }\n    return val;\n}\n\nstatic JSValue build_for_in_iterator(JSContext *ctx, JSValue obj)\n{\n    JSObject *p;\n    JSPropertyEnum *tab_atom;\n    int i;\n    JSValue enum_obj, obj1;\n    JSForInIterator *it;\n    uint32_t tag, tab_atom_count;\n\n    tag = JS_VALUE_GET_TAG(obj);\n    if (tag != JS_TAG_OBJECT && tag != JS_TAG_NULL && tag != JS_TAG_UNDEFINED) {\n        obj = JS_ToObjectFree(ctx, obj);\n    }\n\n    it = js_malloc(ctx, sizeof(*it));\n    if (!it) {\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    enum_obj = JS_NewObjectProtoClass(ctx, JS_NULL, JS_CLASS_FOR_IN_ITERATOR);\n    if (JS_IsException(enum_obj)) {\n        js_free(ctx, it);\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    it->is_array = FALSE;\n    it->obj = obj;\n    it->idx = 0;\n    p = JS_VALUE_GET_OBJ(enum_obj);\n    p->u.for_in_iterator = it;\n\n    if (tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED)\n        return enum_obj;\n\n    /* fast path: assume no enumerable properties in the prototype chain */\n    obj1 = JS_DupValue(ctx, obj);\n    for(;;) {\n        obj1 = JS_GetPrototypeFree(ctx, obj1);\n        if (JS_IsNull(obj1))\n            break;\n        if (JS_IsException(obj1))\n            goto fail;\n        if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count,\n                                           JS_VALUE_GET_OBJ(obj1),\n                                           JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY)) {\n            JS_FreeValue(ctx, obj1);\n            goto fail;\n        }\n        js_free_prop_enum(ctx, tab_atom, tab_atom_count);\n        if (tab_atom_count != 0) {\n            JS_FreeValue(ctx, obj1);\n            goto slow_path;\n        }\n        /* must check for timeout to avoid infinite loop */\n        if (js_poll_interrupts(ctx)) {\n            JS_FreeValue(ctx, obj1);\n            goto fail;\n        }\n    }\n\n    p = JS_VALUE_GET_OBJ(obj);\n\n    if (p->fast_array) {\n        JSShape *sh;\n        JSShapeProperty *prs;\n        /* check that there are no enumerable normal fields */\n        sh = p->shape;\n        for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) {\n            if (prs->flags & JS_PROP_ENUMERABLE)\n                goto normal_case;\n        }\n        /* for fast arrays, we only store the number of elements */\n        it->is_array = TRUE;\n        it->array_length = p->u.array.count;\n    } else {\n    normal_case:\n        if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count, p,\n                                   JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY))\n            goto fail;\n        for(i = 0; i < tab_atom_count; i++) {\n            JS_SetPropertyInternal(ctx, enum_obj, tab_atom[i].atom, JS_NULL, 0);\n        }\n        js_free_prop_enum(ctx, tab_atom, tab_atom_count);\n    }\n    return enum_obj;\n\n slow_path:\n    /* non enumerable properties hide the enumerables ones in the\n       prototype chain */\n    obj1 = JS_DupValue(ctx, obj);\n    for(;;) {\n        if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count,\n                                           JS_VALUE_GET_OBJ(obj1),\n                                           JS_GPN_STRING_MASK | JS_GPN_SET_ENUM)) {\n            JS_FreeValue(ctx, obj1);\n            goto fail;\n        }\n        for(i = 0; i < tab_atom_count; i++) {\n            JS_DefinePropertyValue(ctx, enum_obj, tab_atom[i].atom, JS_NULL,\n                                   (tab_atom[i].is_enumerable ?\n                                    JS_PROP_ENUMERABLE : 0));\n        }\n        js_free_prop_enum(ctx, tab_atom, tab_atom_count);\n        obj1 = JS_GetPrototypeFree(ctx, obj1);\n        if (JS_IsNull(obj1))\n            break;\n        if (JS_IsException(obj1))\n            goto fail;\n        /* must check for timeout to avoid infinite loop */\n        if (js_poll_interrupts(ctx)) {\n            JS_FreeValue(ctx, obj1);\n            goto fail;\n        }\n    }\n    return enum_obj;\n\n fail:\n    JS_FreeValue(ctx, enum_obj);\n    return JS_EXCEPTION;\n}\n\n/* obj -> enum_obj */\nstatic __exception int js_for_in_start(JSContext *ctx, JSValue *sp)\n{\n    sp[-1] = build_for_in_iterator(ctx, sp[-1]);\n    if (JS_IsException(sp[-1]))\n        return -1;\n    return 0;\n}\n\n/* enum_obj -> enum_obj value done */\nstatic __exception int js_for_in_next(JSContext *ctx, JSValue *sp)\n{\n    JSValueConst enum_obj;\n    JSObject *p;\n    JSAtom prop;\n    JSForInIterator *it;\n    int ret;\n\n    enum_obj = sp[-1];\n    /* fail safe */\n    if (JS_VALUE_GET_TAG(enum_obj) != JS_TAG_OBJECT)\n        goto done;\n    p = JS_VALUE_GET_OBJ(enum_obj);\n    if (p->class_id != JS_CLASS_FOR_IN_ITERATOR)\n        goto done;\n    it = p->u.for_in_iterator;\n\n    for(;;) {\n        if (it->is_array) {\n            if (it->idx >= it->array_length)\n                goto done;\n            prop = __JS_AtomFromUInt32(it->idx);\n            it->idx++;\n        } else {\n            JSShape *sh = p->shape;\n            JSShapeProperty *prs;\n            if (it->idx >= sh->prop_count)\n                goto done;\n            prs = get_shape_prop(sh) + it->idx;\n            prop = prs->atom;\n            it->idx++;\n            if (prop == JS_ATOM_NULL || !(prs->flags & JS_PROP_ENUMERABLE))\n                continue;\n        }\n        /* check if the property was deleted */\n        ret = JS_HasProperty(ctx, it->obj, prop);\n        if (ret < 0)\n            return ret;\n        if (ret)\n            break;\n    }\n    /* return the property */\n    sp[0] = JS_AtomToValue(ctx, prop);\n    sp[1] = JS_FALSE;\n    return 0;\n done:\n    /* return the end */\n    sp[0] = JS_UNDEFINED;\n    sp[1] = JS_TRUE;\n    return 0;\n}\n\nstatic JSValue JS_GetIterator2(JSContext *ctx, JSValueConst obj,\n                               JSValueConst method)\n{\n    JSValue enum_obj;\n\n    enum_obj = JS_Call(ctx, method, obj, 0, NULL);\n    if (JS_IsException(enum_obj))\n        return enum_obj;\n    if (!JS_IsObject(enum_obj)) {\n        JS_FreeValue(ctx, enum_obj);\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    }\n    return enum_obj;\n}\n\nstatic JSValue JS_GetIterator(JSContext *ctx, JSValueConst obj, BOOL is_async)\n{\n    JSValue method, ret, sync_iter;\n\n    if (is_async) {\n        method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_asyncIterator);\n        if (JS_IsException(method))\n            return method;\n        if (JS_IsUndefined(method) || JS_IsNull(method)) {\n            method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_iterator);\n            if (JS_IsException(method))\n                return method;\n            sync_iter = JS_GetIterator2(ctx, obj, method);\n            JS_FreeValue(ctx, method);\n            if (JS_IsException(sync_iter))\n                return sync_iter;\n            ret = JS_CreateAsyncFromSyncIterator(ctx, sync_iter);\n            JS_FreeValue(ctx, sync_iter);\n            return ret;\n        }\n    } else {\n        method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_iterator);\n        if (JS_IsException(method))\n            return method;\n    }\n    if (!JS_IsFunction(ctx, method)) {\n        JS_FreeValue(ctx, method);\n        return JS_ThrowTypeError(ctx, \"value is not iterable\");\n    }\n    ret = JS_GetIterator2(ctx, obj, method);\n    JS_FreeValue(ctx, method);\n    return ret;\n}\n\n/* return *pdone = 2 if the iterator object is not parsed */\nstatic JSValue JS_IteratorNext2(JSContext *ctx, JSValueConst enum_obj,\n                                JSValueConst method,\n                                int argc, JSValueConst *argv, int *pdone)\n{\n    JSValue obj;\n\n    /* fast path for the built-in iterators (avoid creating the\n       intermediate result object) */\n    if (JS_IsObject(method)) {\n        JSObject *p = JS_VALUE_GET_OBJ(method);\n        if (p->class_id == JS_CLASS_C_FUNCTION &&\n            p->u.cfunc.cproto == JS_CFUNC_iterator_next) {\n            JSCFunctionType func;\n            JSValueConst args[1];\n\n            /* in case the function expects one argument */\n            if (argc == 0) {\n                args[0] = JS_UNDEFINED;\n                argv = args;\n            }\n            func = p->u.cfunc.c_function;\n            return func.iterator_next(ctx, enum_obj, argc, argv,\n                                      pdone, p->u.cfunc.magic);\n        }\n    }\n    obj = JS_Call(ctx, method, enum_obj, argc, argv);\n    if (JS_IsException(obj))\n        goto fail;\n    if (!JS_IsObject(obj)) {\n        JS_FreeValue(ctx, obj);\n        JS_ThrowTypeError(ctx, \"iterator must return an object\");\n        goto fail;\n    }\n    *pdone = 2;\n    return obj;\n fail:\n    *pdone = FALSE;\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_IteratorNext(JSContext *ctx, JSValueConst enum_obj,\n                               JSValueConst method,\n                               int argc, JSValueConst *argv, BOOL *pdone)\n{\n    JSValue obj, value, done_val;\n    int done;\n\n    obj = JS_IteratorNext2(ctx, enum_obj, method, argc, argv, &done);\n    if (JS_IsException(obj))\n        goto fail;\n    if (done != 2) {\n        *pdone = done;\n        return obj;\n    } else {\n        done_val = JS_GetProperty(ctx, obj, JS_ATOM_done);\n        if (JS_IsException(done_val))\n            goto fail;\n        *pdone = JS_ToBoolFree(ctx, done_val);\n        value = JS_UNDEFINED;\n        if (!*pdone) {\n            value = JS_GetProperty(ctx, obj, JS_ATOM_value);\n        }\n        JS_FreeValue(ctx, obj);\n        return value;\n    }\n fail:\n    JS_FreeValue(ctx, obj);\n    *pdone = FALSE;\n    return JS_EXCEPTION;\n}\n\n/* return < 0 in case of exception */\nstatic int JS_IteratorClose(JSContext *ctx, JSValueConst enum_obj,\n                            BOOL is_exception_pending)\n{\n    JSValue method, ret, ex_obj;\n    int res;\n\n    if (is_exception_pending) {\n        ex_obj = ctx->rt->current_exception;\n        ctx->rt->current_exception = JS_NULL;\n        res = -1;\n    } else {\n        ex_obj = JS_UNDEFINED;\n        res = 0;\n    }\n    method = JS_GetProperty(ctx, enum_obj, JS_ATOM_return);\n    if (JS_IsException(method)) {\n        res = -1;\n        goto done;\n    }\n    if (JS_IsUndefined(method) || JS_IsNull(method)) {\n        goto done;\n    }\n    ret = JS_CallFree(ctx, method, enum_obj, 0, NULL);\n    if (!is_exception_pending) {\n        if (JS_IsException(ret)) {\n            res = -1;\n        } else if (!JS_IsObject(ret)) {\n            JS_ThrowTypeErrorNotAnObject(ctx);\n            res = -1;\n        }\n    }\n    JS_FreeValue(ctx, ret);\n done:\n    if (is_exception_pending) {\n        JS_Throw(ctx, ex_obj);\n    }\n    return res;\n}\n\n/* obj -> enum_rec (3 slots) */\nstatic __exception int js_for_of_start(JSContext *ctx, JSValue *sp,\n                                       BOOL is_async)\n{\n    JSValue op1, obj, method;\n    op1 = sp[-1];\n    obj = JS_GetIterator(ctx, op1, is_async);\n    if (JS_IsException(obj))\n        return -1;\n    JS_FreeValue(ctx, op1);\n    sp[-1] = obj;\n    method = JS_GetProperty(ctx, obj, JS_ATOM_next);\n    if (JS_IsException(method))\n        return -1;\n    sp[0] = method;\n    return 0;\n}\n\n/* enum_rec [objs] -> enum_rec [objs] value done. There are 'offset'\n   objs. If 'done' is true or in case of exception, 'enum_rec' is set\n   to undefined. If 'done' is true, 'value' is always set to\n   undefined. */\nstatic __exception int js_for_of_next(JSContext *ctx, JSValue *sp, int offset)\n{\n    JSValue value = JS_UNDEFINED;\n    int done = 1;\n\n    if (likely(!JS_IsUndefined(sp[offset]))) {\n        value = JS_IteratorNext(ctx, sp[offset], sp[offset + 1], 0, NULL, &done);\n        if (JS_IsException(value))\n            done = -1;\n        if (done) {\n            /* value is JS_UNDEFINED or JS_EXCEPTION */\n            /* replace the iteration object with undefined */\n            JS_FreeValue(ctx, sp[offset]);\n            sp[offset] = JS_UNDEFINED;\n            if (done < 0) {\n                return -1;\n            } else {\n                JS_FreeValue(ctx, value);\n                value = JS_UNDEFINED;\n            }\n        }\n    }\n    sp[0] = value;\n    sp[1] = JS_NewBool(ctx, done);\n    return 0;\n}\n\nstatic JSValue JS_IteratorGetCompleteValue(JSContext *ctx, JSValueConst obj,\n                                           BOOL *pdone)\n{\n    JSValue done_val, value;\n    BOOL done;\n    done_val = JS_GetProperty(ctx, obj, JS_ATOM_done);\n    if (JS_IsException(done_val))\n        goto fail;\n    done = JS_ToBoolFree(ctx, done_val);\n    value = JS_GetProperty(ctx, obj, JS_ATOM_value);\n    if (JS_IsException(value))\n        goto fail;\n    *pdone = done;\n    return value;\n fail:\n    *pdone = FALSE;\n    return JS_EXCEPTION;\n}\n\nstatic __exception int js_iterator_get_value_done(JSContext *ctx, JSValue *sp)\n{\n    JSValue obj, value;\n    BOOL done;\n    obj = sp[-1];\n    if (!JS_IsObject(obj)) {\n        JS_ThrowTypeError(ctx, \"iterator must return an object\");\n        return -1;\n    }\n    value = JS_IteratorGetCompleteValue(ctx, obj, &done);\n    if (JS_IsException(value))\n        return -1;\n    JS_FreeValue(ctx, obj);\n    sp[-1] = value;\n    sp[0] = JS_NewBool(ctx, done);\n    return 0;\n}\n\nstatic JSValue js_create_iterator_result(JSContext *ctx,\n                                         JSValue val,\n                                         BOOL done)\n{\n    JSValue obj;\n    obj = JS_NewObject(ctx);\n    if (JS_IsException(obj)) {\n        JS_FreeValue(ctx, val);\n        return obj;\n    }\n    if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_value,\n                               val, JS_PROP_C_W_E) < 0) {\n        goto fail;\n    }\n    if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_done,\n                               JS_NewBool(ctx, done), JS_PROP_C_W_E) < 0) {\n    fail:\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    return obj;\n}\n\nstatic JSValue js_array_iterator_next(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv,\n                                      BOOL *pdone, int magic);\n\nstatic JSValue js_create_array_iterator(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv, int magic);\n\nstatic BOOL js_is_fast_array(JSContext *ctx, JSValueConst obj)\n{\n    /* Try and handle fast arrays explicitly */\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(obj);\n        if (p->class_id == JS_CLASS_ARRAY && p->fast_array) {\n            return TRUE;\n        }\n    }\n    return FALSE;\n}\n\n/* Access an Array's internal JSValue array if available */\nstatic BOOL js_get_fast_array(JSContext *ctx, JSValueConst obj,\n                              JSValue **arrpp, uint32_t *countp)\n{\n    /* Try and handle fast arrays explicitly */\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(obj);\n        if (p->class_id == JS_CLASS_ARRAY && p->fast_array) {\n            *countp = p->u.array.count;\n            *arrpp = p->u.array.u.values;\n            return TRUE;\n        }\n    }\n    return FALSE;\n}\n\nstatic __exception int js_append_enumerate(JSContext *ctx, JSValue *sp)\n{\n    JSValue iterator, enumobj, method, value;\n    int is_array_iterator;\n    JSValue *arrp;\n    uint32_t i, count32, pos;\n    \n    if (JS_VALUE_GET_TAG(sp[-2]) != JS_TAG_INT) {\n        JS_ThrowInternalError(ctx, \"invalid index for append\");\n        return -1;\n    }\n\n    pos = JS_VALUE_GET_INT(sp[-2]);\n\n    /* XXX: further optimisations:\n       - use ctx->array_proto_values?\n       - check if array_iterator_prototype next method is built-in and\n         avoid constructing actual iterator object?\n       - build this into js_for_of_start and use in all `for (x of o)` loops\n     */\n    iterator = JS_GetProperty(ctx, sp[-1], JS_ATOM_Symbol_iterator);\n    if (JS_IsException(iterator))\n        return -1;\n    is_array_iterator = JS_IsCFunction(ctx, iterator,\n                                       (JSCFunction *)js_create_array_iterator,\n                                       JS_ITERATOR_KIND_VALUE);\n    JS_FreeValue(ctx, iterator);\n\n    enumobj = JS_GetIterator(ctx, sp[-1], FALSE);\n    if (JS_IsException(enumobj))\n        return -1;\n    method = JS_GetProperty(ctx, enumobj, JS_ATOM_next);\n    if (JS_IsException(method)) {\n        JS_FreeValue(ctx, enumobj);\n        return -1;\n    }\n    if (is_array_iterator\n    &&  JS_IsCFunction(ctx, method, (JSCFunction *)js_array_iterator_next, 0)\n    &&  js_get_fast_array(ctx, sp[-1], &arrp, &count32)) {\n        uint32_t len;\n        if (js_get_length32(ctx, &len, sp[-1]))\n            goto exception;\n        /* if len > count32, the elements >= count32 might be read in\n           the prototypes and might have side effects */\n        if (len != count32)\n            goto general_case;\n        /* Handle fast arrays explicitly */\n        for (i = 0; i < count32; i++) {\n            if (JS_DefinePropertyValueUint32(ctx, sp[-3], pos++,\n                                             JS_DupValue(ctx, arrp[i]), JS_PROP_C_W_E) < 0)\n                goto exception;\n        }\n    } else {\n    general_case:\n        for (;;) {\n            BOOL done;\n            value = JS_IteratorNext(ctx, enumobj, method, 0, NULL, &done);\n            if (JS_IsException(value))\n                goto exception;\n            if (done) {\n                /* value is JS_UNDEFINED */\n                break;\n            }\n            if (JS_DefinePropertyValueUint32(ctx, sp[-3], pos++, value, JS_PROP_C_W_E) < 0)\n                goto exception;\n        }\n    }\n    /* Note: could raise an error if too many elements */\n    sp[-2] = JS_NewInt32(ctx, pos);\n    JS_FreeValue(ctx, enumobj);\n    JS_FreeValue(ctx, method);\n    return 0;\n\nexception:\n    JS_IteratorClose(ctx, enumobj, TRUE);\n    JS_FreeValue(ctx, enumobj);\n    JS_FreeValue(ctx, method);\n    return -1;\n}\n\nstatic __exception int JS_CopyDataProperties(JSContext *ctx,\n                                             JSValueConst target,\n                                             JSValueConst source,\n                                             JSValueConst excluded,\n                                             BOOL setprop)\n{\n    JSPropertyEnum *tab_atom;\n    JSValue val;\n    uint32_t i, tab_atom_count;\n    JSObject *p;\n    JSObject *pexcl = NULL;\n    int ret, gpn_flags;\n    JSPropertyDescriptor desc;\n    BOOL is_enumerable;\n    \n    if (JS_VALUE_GET_TAG(source) != JS_TAG_OBJECT)\n        return 0;\n\n    if (JS_VALUE_GET_TAG(excluded) == JS_TAG_OBJECT)\n        pexcl = JS_VALUE_GET_OBJ(excluded);\n\n    p = JS_VALUE_GET_OBJ(source);\n\n    gpn_flags = JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK | JS_GPN_ENUM_ONLY;\n    if (p->is_exotic) {\n        const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;\n        /* cannot use JS_GPN_ENUM_ONLY with e.g. proxies because it\n           introduces a visible change */\n        if (em && em->get_own_property_names) {\n            gpn_flags &= ~JS_GPN_ENUM_ONLY;\n        }\n    }\n    if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count, p,\n                                       gpn_flags))\n        return -1;\n    \n    for (i = 0; i < tab_atom_count; i++) {\n        if (pexcl) {\n            ret = JS_GetOwnPropertyInternal(ctx, NULL, pexcl, tab_atom[i].atom);\n            if (ret) {\n                if (ret < 0)\n                    goto exception;\n                continue;\n            }\n        }\n        if (!(gpn_flags & JS_GPN_ENUM_ONLY)) {\n            /* test if the property is enumerable */\n            ret = JS_GetOwnPropertyInternal(ctx, &desc, p, tab_atom[i].atom);\n            if (ret < 0)\n                goto exception;\n            if (!ret)\n                continue;\n            is_enumerable = (desc.flags & JS_PROP_ENUMERABLE) != 0;\n            js_free_desc(ctx, &desc);\n            if (!is_enumerable)\n                continue;\n        }\n        val = JS_GetProperty(ctx, source, tab_atom[i].atom);\n        if (JS_IsException(val))\n            goto exception;\n        if (setprop)\n            ret = JS_SetProperty(ctx, target, tab_atom[i].atom, val);\n        else\n            ret = JS_DefinePropertyValue(ctx, target, tab_atom[i].atom, val,\n                                         JS_PROP_C_W_E);\n        if (ret < 0)\n            goto exception;\n    }\n    js_free_prop_enum(ctx, tab_atom, tab_atom_count);\n    return 0;\n exception:\n    js_free_prop_enum(ctx, tab_atom, tab_atom_count);\n    return -1;\n}\n\n/* only valid inside C functions */\nJSValueConst JS_GetActiveFunction(JSContext *ctx)\n{\n    return ctx->rt->current_stack_frame->cur_func;\n}\n\nstatic JSVarRef *get_var_ref(JSContext *ctx, JSStackFrame *sf,\n                             int var_idx, BOOL is_arg)\n{\n    JSVarRef *var_ref;\n    struct list_head *el;\n\n    list_for_each(el, &sf->var_ref_list) {\n        var_ref = list_entry(el, JSVarRef, header.link);\n        if (var_ref->var_idx == var_idx && var_ref->is_arg == is_arg) {\n            var_ref->header.ref_count++;\n            return var_ref;\n        }\n    }\n    /* create a new one */\n    var_ref = js_malloc(ctx, sizeof(JSVarRef));\n    if (!var_ref)\n        return NULL;\n    var_ref->header.ref_count = 1;\n    var_ref->is_detached = FALSE;\n    var_ref->is_arg = is_arg;\n    var_ref->var_idx = var_idx;\n    list_add_tail(&var_ref->header.link, &sf->var_ref_list);\n    if (is_arg)\n        var_ref->pvalue = &sf->arg_buf[var_idx];\n    else\n        var_ref->pvalue = &sf->var_buf[var_idx];\n    var_ref->value = JS_UNDEFINED;\n    return var_ref;\n}\n\nstatic JSValue js_closure2(JSContext *ctx, JSValue func_obj,\n                           JSFunctionBytecode *b,\n                           JSVarRef **cur_var_refs,\n                           JSStackFrame *sf)\n{\n    JSObject *p;\n    JSVarRef **var_refs;\n    int i;\n\n    p = JS_VALUE_GET_OBJ(func_obj);\n    p->u.func.function_bytecode = b;\n    p->u.func.home_object = NULL;\n    p->u.func.var_refs = NULL;\n    if (b->closure_var_count) {\n        var_refs = js_mallocz(ctx, sizeof(var_refs[0]) * b->closure_var_count);\n        if (!var_refs)\n            goto fail;\n        p->u.func.var_refs = var_refs;\n        for(i = 0; i < b->closure_var_count; i++) {\n            JSClosureVar *cv = &b->closure_var[i];\n            JSVarRef *var_ref;\n            if (cv->is_local) {\n                /* reuse the existing variable reference if it already exists */\n                var_ref = get_var_ref(ctx, sf, cv->var_idx, cv->is_arg);\n                if (!var_ref)\n                    goto fail;\n            } else {\n                var_ref = cur_var_refs[cv->var_idx];\n                var_ref->header.ref_count++;\n            }\n            var_refs[i] = var_ref;\n        }\n    }\n    return func_obj;\n fail:\n    /* bfunc is freed when func_obj is freed */\n    JS_FreeValue(ctx, func_obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_instantiate_prototype(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque)\n{\n    JSValue obj, this_val;\n    int ret;\n\n    this_val = JS_MKPTR(JS_TAG_OBJECT, p);\n    obj = JS_NewObject(ctx);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    set_cycle_flag(ctx, obj);\n    set_cycle_flag(ctx, this_val);\n    ret = JS_DefinePropertyValue(ctx, obj, JS_ATOM_constructor,\n                                 JS_DupValue(ctx, this_val),\n                                 JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    if (ret < 0) {\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    return obj;\n}\n\nstatic const uint16_t func_kind_to_class_id[] = {\n    [JS_FUNC_NORMAL] = JS_CLASS_BYTECODE_FUNCTION,\n    [JS_FUNC_GENERATOR] = JS_CLASS_GENERATOR_FUNCTION,\n    [JS_FUNC_ASYNC] = JS_CLASS_ASYNC_FUNCTION,\n    [JS_FUNC_ASYNC_GENERATOR] = JS_CLASS_ASYNC_GENERATOR_FUNCTION,\n};\n\nstatic JSValue js_closure(JSContext *ctx, JSValue bfunc,\n                          JSVarRef **cur_var_refs,\n                          JSStackFrame *sf)\n{\n    JSFunctionBytecode *b;\n    JSValue func_obj;\n    JSAtom name_atom;\n\n    b = JS_VALUE_GET_PTR(bfunc);\n    func_obj = JS_NewObjectClass(ctx, func_kind_to_class_id[b->func_kind]);\n    if (JS_IsException(func_obj)) {\n        JS_FreeValue(ctx, bfunc);\n        return JS_EXCEPTION;\n    }\n    func_obj = js_closure2(ctx, func_obj, b, cur_var_refs, sf);\n    if (JS_IsException(func_obj)) {\n        /* bfunc has been freed */\n        goto fail;\n    }\n    name_atom = b->func_name;\n    if (name_atom == JS_ATOM_NULL)\n        name_atom = JS_ATOM_empty_string;\n    js_function_set_properties(ctx, func_obj, name_atom,\n                               b->defined_arg_count);\n\n    if (b->func_kind & JS_FUNC_GENERATOR) {\n        JSValue proto;\n        int proto_class_id;\n        /* generators have a prototype field which is used as\n           prototype for the generator object */\n        if (b->func_kind == JS_FUNC_ASYNC_GENERATOR)\n            proto_class_id = JS_CLASS_ASYNC_GENERATOR;\n        else\n            proto_class_id = JS_CLASS_GENERATOR;\n        proto = JS_NewObjectProto(ctx, ctx->class_proto[proto_class_id]);\n        if (JS_IsException(proto))\n            goto fail;\n        JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_prototype, proto,\n                               JS_PROP_WRITABLE);\n    } else if (b->has_prototype) {\n        /* add the 'prototype' property: delay instantiation to avoid\n           creating cycles for every javascript function. The prototype\n           object is created on the fly when first accessed */\n        JS_SetConstructorBit(ctx, func_obj, TRUE);\n        JS_DefineAutoInitProperty(ctx, func_obj, JS_ATOM_prototype,\n                                  JS_AUTOINIT_ID_PROTOTYPE, NULL,\n                                  JS_PROP_WRITABLE);\n    }\n    return func_obj;\n fail:\n    /* bfunc is freed when func_obj is freed */\n    JS_FreeValue(ctx, func_obj);\n    return JS_EXCEPTION;\n}\n\n#define JS_DEFINE_CLASS_HAS_HERITAGE     (1 << 0)\n\nstatic int js_op_define_class(JSContext *ctx, JSValue *sp,\n                              JSAtom class_name, int class_flags,\n                              JSVarRef **cur_var_refs,\n                              JSStackFrame *sf, BOOL is_computed_name)\n{\n    JSValue bfunc, parent_class, proto = JS_UNDEFINED;\n    JSValue ctor = JS_UNDEFINED, parent_proto = JS_UNDEFINED;\n    JSFunctionBytecode *b;\n\n    parent_class = sp[-2];\n    bfunc = sp[-1];\n\n    if (class_flags & JS_DEFINE_CLASS_HAS_HERITAGE) {\n        if (JS_IsNull(parent_class)) {\n            parent_proto = JS_NULL;\n            parent_class = JS_DupValue(ctx, ctx->function_proto);\n        } else {\n            if (!JS_IsConstructor(ctx, parent_class)) {\n                JS_ThrowTypeError(ctx, \"parent class must be constructor\");\n                goto fail;\n            }\n            parent_proto = JS_GetProperty(ctx, parent_class, JS_ATOM_prototype);\n            if (JS_IsException(parent_proto))\n                goto fail;\n            if (!JS_IsNull(parent_proto) && !JS_IsObject(parent_proto)) {\n                JS_ThrowTypeError(ctx, \"parent prototype must be an object or null\");\n                goto fail;\n            }\n        }\n    } else {\n        /* parent_class is JS_UNDEFINED in this case */\n        parent_proto = JS_DupValue(ctx, ctx->class_proto[JS_CLASS_OBJECT]);\n        parent_class = JS_DupValue(ctx, ctx->function_proto);\n    }\n    proto = JS_NewObjectProto(ctx, parent_proto);\n    if (JS_IsException(proto))\n        goto fail;\n\n    b = JS_VALUE_GET_PTR(bfunc);\n    assert(b->func_kind == JS_FUNC_NORMAL);\n    ctor = JS_NewObjectProtoClass(ctx, parent_class,\n                                  JS_CLASS_BYTECODE_FUNCTION);\n    if (JS_IsException(ctor))\n        goto fail;\n    ctor = js_closure2(ctx, ctor, b, cur_var_refs, sf);\n    bfunc = JS_UNDEFINED;\n    if (JS_IsException(ctor))\n        goto fail;\n    js_method_set_home_object(ctx, ctor, proto);\n    JS_SetConstructorBit(ctx, ctor, TRUE);\n\n    JS_DefinePropertyValue(ctx, ctor, JS_ATOM_length,\n                           JS_NewInt32(ctx, b->defined_arg_count),\n                           JS_PROP_CONFIGURABLE);\n\n    if (is_computed_name) {\n        if (JS_DefineObjectNameComputed(ctx, ctor, sp[-3],\n                                        JS_PROP_CONFIGURABLE) < 0)\n            goto fail;\n    } else {\n        if (JS_DefineObjectName(ctx, ctor, class_name, JS_PROP_CONFIGURABLE) < 0)\n            goto fail;\n    }\n\n    /* the constructor property must be first. It can be overriden by\n       computed property names */\n    if (JS_DefinePropertyValue(ctx, proto, JS_ATOM_constructor,\n                               JS_DupValue(ctx, ctor),\n                               JS_PROP_CONFIGURABLE |\n                               JS_PROP_WRITABLE | JS_PROP_THROW) < 0)\n        goto fail;\n    /* set the prototype property */\n    if (JS_DefinePropertyValue(ctx, ctor, JS_ATOM_prototype,\n                               JS_DupValue(ctx, proto), JS_PROP_THROW) < 0)\n        goto fail;\n    set_cycle_flag(ctx, ctor);\n    set_cycle_flag(ctx, proto);\n\n    JS_FreeValue(ctx, parent_proto);\n    JS_FreeValue(ctx, parent_class);\n\n    sp[-2] = ctor;\n    sp[-1] = proto;\n    return 0;\n fail:\n    JS_FreeValue(ctx, parent_class);\n    JS_FreeValue(ctx, parent_proto);\n    JS_FreeValue(ctx, bfunc);\n    JS_FreeValue(ctx, proto);\n    JS_FreeValue(ctx, ctor);\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic void close_var_refs(JSRuntime *rt, JSStackFrame *sf)\n{\n    struct list_head *el, *el1;\n    JSVarRef *var_ref;\n    int var_idx;\n\n    list_for_each_safe(el, el1, &sf->var_ref_list) {\n        var_ref = list_entry(el, JSVarRef, header.link);\n        var_idx = var_ref->var_idx;\n        if (var_ref->is_arg)\n            var_ref->value = JS_DupValueRT(rt, sf->arg_buf[var_idx]);\n        else\n            var_ref->value = JS_DupValueRT(rt, sf->var_buf[var_idx]);\n        var_ref->pvalue = &var_ref->value;\n        /* the reference is no longer to a local variable */\n        var_ref->is_detached = TRUE;\n        add_gc_object(rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF);\n    }\n}\n\nstatic void close_lexical_var(JSContext *ctx, JSStackFrame *sf, int idx, int is_arg)\n{\n    struct list_head *el, *el1;\n    JSVarRef *var_ref;\n    int var_idx = idx;\n\n    list_for_each_safe(el, el1, &sf->var_ref_list) {\n        var_ref = list_entry(el, JSVarRef, header.link);\n        if (var_idx == var_ref->var_idx && var_ref->is_arg == is_arg) {\n            var_ref->value = JS_DupValue(ctx, sf->var_buf[var_idx]);\n            var_ref->pvalue = &var_ref->value;\n            list_del(&var_ref->header.link);\n            /* the reference is no longer to a local variable */\n            var_ref->is_detached = TRUE;\n            add_gc_object(ctx->rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF);\n        }\n    }\n}\n\n#define JS_CALL_FLAG_COPY_ARGV   (1 << 1)\n#define JS_CALL_FLAG_GENERATOR   (1 << 2)\n\nstatic JSValue js_call_c_function(JSContext *ctx, JSValueConst func_obj,\n                                  JSValueConst this_obj,\n                                  int argc, JSValueConst *argv, int flags)\n{\n    JSRuntime *rt = ctx->rt;\n    JSCFunctionType func;\n    JSObject *p;\n    JSStackFrame sf_s, *sf = &sf_s, *prev_sf;\n    JSValue ret_val;\n    JSValueConst *arg_buf;\n    int arg_count, i;\n    JSCFunctionEnum cproto;\n\n    p = JS_VALUE_GET_OBJ(func_obj);\n    cproto = p->u.cfunc.cproto;\n    arg_count = p->u.cfunc.length;\n\n    /* better to always check stack overflow */\n    if (js_check_stack_overflow(rt, sizeof(arg_buf[0]) * arg_count))\n        return JS_ThrowStackOverflow(ctx);\n\n    prev_sf = rt->current_stack_frame;\n    sf->prev_frame = prev_sf;\n    rt->current_stack_frame = sf;\n    ctx = p->u.cfunc.realm; /* change the current realm */\n    \n#ifdef CONFIG_BIGNUM\n    /* we only propagate the bignum mode as some runtime functions\n       test it */\n    if (prev_sf)\n        sf->js_mode = prev_sf->js_mode & JS_MODE_MATH;\n    else\n        sf->js_mode = 0;\n#else\n    sf->js_mode = 0;\n#endif\n    sf->cur_func = (JSValue)func_obj;\n    sf->arg_count = argc;\n    arg_buf = argv;\n\n    if (unlikely(argc < arg_count)) {\n        /* ensure that at least argc_count arguments are readable */\n        arg_buf = alloca(sizeof(arg_buf[0]) * arg_count);\n        for(i = 0; i < argc; i++)\n            arg_buf[i] = argv[i];\n        for(i = argc; i < arg_count; i++)\n            arg_buf[i] = JS_UNDEFINED;\n        sf->arg_count = arg_count;\n    }\n    sf->arg_buf = (JSValue*)arg_buf;\n\n    func = p->u.cfunc.c_function;\n    switch(cproto) {\n    case JS_CFUNC_constructor:\n    case JS_CFUNC_constructor_or_func:\n        if (!(flags & JS_CALL_FLAG_CONSTRUCTOR)) {\n            if (cproto == JS_CFUNC_constructor) {\n            not_a_constructor:\n                ret_val = JS_ThrowTypeError(ctx, \"must be called with new\");\n                break;\n            } else {\n                this_obj = JS_UNDEFINED;\n            }\n        }\n        /* here this_obj is new_target */\n        /* fall thru */\n    case JS_CFUNC_generic:\n        ret_val = func.generic(ctx, this_obj, argc, arg_buf);\n        break;\n    case JS_CFUNC_constructor_magic:\n    case JS_CFUNC_constructor_or_func_magic:\n        if (!(flags & JS_CALL_FLAG_CONSTRUCTOR)) {\n            if (cproto == JS_CFUNC_constructor_magic) {\n                goto not_a_constructor;\n            } else {\n                this_obj = JS_UNDEFINED;\n            }\n        }\n        /* fall thru */\n    case JS_CFUNC_generic_magic:\n        ret_val = func.generic_magic(ctx, this_obj, argc, arg_buf,\n                                     p->u.cfunc.magic);\n        break;\n    case JS_CFUNC_getter:\n        ret_val = func.getter(ctx, this_obj);\n        break;\n    case JS_CFUNC_setter:\n        ret_val = func.setter(ctx, this_obj, arg_buf[0]);\n        break;\n    case JS_CFUNC_getter_magic:\n        ret_val = func.getter_magic(ctx, this_obj, p->u.cfunc.magic);\n        break;\n    case JS_CFUNC_setter_magic:\n        ret_val = func.setter_magic(ctx, this_obj, arg_buf[0], p->u.cfunc.magic);\n        break;\n    case JS_CFUNC_f_f:\n        {\n            double d1;\n\n            if (unlikely(JS_ToFloat64(ctx, &d1, arg_buf[0]))) {\n                ret_val = JS_EXCEPTION;\n                break;\n            }\n            ret_val = JS_NewFloat64(ctx, func.f_f(d1));\n        }\n        break;\n    case JS_CFUNC_f_f_f:\n        {\n            double d1, d2;\n\n            if (unlikely(JS_ToFloat64(ctx, &d1, arg_buf[0]))) {\n                ret_val = JS_EXCEPTION;\n                break;\n            }\n            if (unlikely(JS_ToFloat64(ctx, &d2, arg_buf[1]))) {\n                ret_val = JS_EXCEPTION;\n                break;\n            }\n            ret_val = JS_NewFloat64(ctx, func.f_f_f(d1, d2));\n        }\n        break;\n    case JS_CFUNC_iterator_next:\n        {\n            int done;\n            ret_val = func.iterator_next(ctx, this_obj, argc, arg_buf,\n                                         &done, p->u.cfunc.magic);\n            if (!JS_IsException(ret_val) && done != 2) {\n                ret_val = js_create_iterator_result(ctx, ret_val, done);\n            }\n        }\n        break;\n    default:\n        abort();\n    }\n\n    rt->current_stack_frame = sf->prev_frame;\n    return ret_val;\n}\n\nstatic JSValue js_call_bound_function(JSContext *ctx, JSValueConst func_obj,\n                                      JSValueConst this_obj,\n                                      int argc, JSValueConst *argv, int flags)\n{\n    JSObject *p;\n    JSBoundFunction *bf;\n    JSValueConst *arg_buf, new_target;\n    int arg_count, i;\n\n    p = JS_VALUE_GET_OBJ(func_obj);\n    bf = p->u.bound_function;\n    arg_count = bf->argc + argc;\n    if (js_check_stack_overflow(ctx->rt, sizeof(JSValue) * arg_count))\n        return JS_ThrowStackOverflow(ctx);\n    arg_buf = alloca(sizeof(JSValue) * arg_count);\n    for(i = 0; i < bf->argc; i++) {\n        arg_buf[i] = bf->argv[i];\n    }\n    for(i = 0; i < argc; i++) {\n        arg_buf[bf->argc + i] = argv[i];\n    }\n    if (flags & JS_CALL_FLAG_CONSTRUCTOR) {\n        new_target = this_obj;\n        if (js_same_value(ctx, func_obj, new_target))\n            new_target = bf->func_obj;\n        return JS_CallConstructor2(ctx, bf->func_obj, new_target,\n                                   arg_count, arg_buf);\n    } else {\n        return JS_Call(ctx, bf->func_obj, bf->this_val,\n                       arg_count, arg_buf);\n    }\n}\n\n/* argument of OP_special_object */\ntypedef enum {\n    OP_SPECIAL_OBJECT_ARGUMENTS,\n    OP_SPECIAL_OBJECT_MAPPED_ARGUMENTS,\n    OP_SPECIAL_OBJECT_THIS_FUNC,\n    OP_SPECIAL_OBJECT_NEW_TARGET,\n    OP_SPECIAL_OBJECT_HOME_OBJECT,\n    OP_SPECIAL_OBJECT_VAR_OBJECT,\n    OP_SPECIAL_OBJECT_IMPORT_META,\n} OPSpecialObjectEnum;\n\n#define FUNC_RET_AWAIT      0\n#define FUNC_RET_YIELD      1\n#define FUNC_RET_YIELD_STAR 2\n\n/* argv[] is modified if (flags & JS_CALL_FLAG_COPY_ARGV) = 0. */\nstatic JSValue JS_CallInternal(JSContext *caller_ctx, JSValueConst func_obj,\n                               JSValueConst this_obj, JSValueConst new_target,\n                               int argc, JSValue *argv, int flags)\n{\n    JSRuntime *rt = caller_ctx->rt;\n    JSContext *ctx;\n    JSObject *p;\n    JSFunctionBytecode *b;\n    JSStackFrame sf_s, *sf = &sf_s;\n    const uint8_t *pc;\n    int opcode, arg_allocated_size, i;\n    JSValue *local_buf, *stack_buf, *var_buf, *arg_buf, *sp, ret_val, *pval;\n    JSVarRef **var_refs;\n    size_t alloca_size;\n\n#if !DIRECT_DISPATCH\n#define SWITCH(pc)      switch (opcode = *pc++)\n#define CASE(op)        case op\n#define DEFAULT         default\n#define BREAK           break\n#else\n    static const void * const dispatch_table[256] = {\n#define DEF(id, size, n_pop, n_push, f) && case_OP_ ## id,\n#if SHORT_OPCODES\n#define def(id, size, n_pop, n_push, f)\n#else                                                     \n#define def(id, size, n_pop, n_push, f) && case_default,\n#endif\n#include \"quickjs-opcode.h\"\n        [ OP_COUNT ... 255 ] = &&case_default\n    };\n#define SWITCH(pc)      goto *dispatch_table[opcode = *pc++];\n#define CASE(op)        case_ ## op\n#define DEFAULT         case_default\n#define BREAK           SWITCH(pc)\n#endif\n\n    if (js_poll_interrupts(caller_ctx))\n        return JS_EXCEPTION;\n    if (unlikely(JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT)) {\n        if (flags & JS_CALL_FLAG_GENERATOR) {\n            JSAsyncFunctionState *s = JS_VALUE_GET_PTR(func_obj);\n            /* func_obj get contains a pointer to JSFuncAsyncState */\n            /* the stack frame is already allocated */\n            sf = &s->frame;\n            p = JS_VALUE_GET_OBJ(sf->cur_func);\n            b = p->u.func.function_bytecode;\n            ctx = b->realm;\n            var_refs = p->u.func.var_refs;\n            local_buf = arg_buf = sf->arg_buf;\n            var_buf = sf->var_buf;\n            stack_buf = sf->var_buf + b->var_count;\n            sp = sf->cur_sp;\n            sf->cur_sp = NULL; /* cur_sp is NULL if the function is running */\n            pc = sf->cur_pc;\n            sf->prev_frame = rt->current_stack_frame;\n            rt->current_stack_frame = sf;\n            if (s->throw_flag)\n                goto exception;\n            else\n                goto restart;\n        } else {\n            goto not_a_function;\n        }\n    }\n    p = JS_VALUE_GET_OBJ(func_obj);\n    if (unlikely(p->class_id != JS_CLASS_BYTECODE_FUNCTION)) {\n        JSClassCall *call_func;\n        call_func = rt->class_array[p->class_id].call;\n        if (!call_func) {\n        not_a_function:\n            return JS_ThrowTypeError(caller_ctx, \"not a function\");\n        }\n        return call_func(caller_ctx, func_obj, this_obj, argc,\n                         (JSValueConst *)argv, flags);\n    }\n    b = p->u.func.function_bytecode;\n\n    if (unlikely(argc < b->arg_count || (flags & JS_CALL_FLAG_COPY_ARGV))) {\n        arg_allocated_size = b->arg_count;\n    } else {\n        arg_allocated_size = 0;\n    }\n\n    alloca_size = sizeof(JSValue) * (arg_allocated_size + b->var_count +\n                                     b->stack_size);\n    if (js_check_stack_overflow(rt, alloca_size))\n        return JS_ThrowStackOverflow(caller_ctx);\n\n    sf->js_mode = b->js_mode;\n    arg_buf = argv;\n    sf->arg_count = argc;\n    sf->cur_func = (JSValue)func_obj;\n    init_list_head(&sf->var_ref_list);\n    var_refs = p->u.func.var_refs;\n\n    local_buf = alloca(alloca_size);\n    if (unlikely(arg_allocated_size)) {\n        int n = min_int(argc, b->arg_count);\n        arg_buf = local_buf;\n        for(i = 0; i < n; i++)\n            arg_buf[i] = JS_DupValue(caller_ctx, argv[i]);\n        for(; i < b->arg_count; i++)\n            arg_buf[i] = JS_UNDEFINED;\n        sf->arg_count = b->arg_count;\n    }\n    var_buf = local_buf + arg_allocated_size;\n    sf->var_buf = var_buf;\n    sf->arg_buf = arg_buf;\n\n    for(i = 0; i < b->var_count; i++)\n        var_buf[i] = JS_UNDEFINED;\n\n    stack_buf = var_buf + b->var_count;\n    sp = stack_buf;\n    pc = b->byte_code_buf;\n    sf->prev_frame = rt->current_stack_frame;\n    rt->current_stack_frame = sf;\n    ctx = b->realm; /* set the current realm */\n    \n restart:\n    for(;;) {\n        int call_argc;\n        JSValue *call_argv;\n\n        SWITCH(pc) {\n        CASE(OP_push_i32):\n            *sp++ = JS_NewInt32(ctx, get_u32(pc));\n            pc += 4;\n            BREAK;\n        CASE(OP_push_const):\n            *sp++ = JS_DupValue(ctx, b->cpool[get_u32(pc)]);\n            pc += 4;\n            BREAK;\n#if SHORT_OPCODES\n        CASE(OP_push_minus1):\n        CASE(OP_push_0):\n        CASE(OP_push_1):\n        CASE(OP_push_2):\n        CASE(OP_push_3):\n        CASE(OP_push_4):\n        CASE(OP_push_5):\n        CASE(OP_push_6):\n        CASE(OP_push_7):\n            *sp++ = JS_NewInt32(ctx, opcode - OP_push_0);\n            BREAK;\n        CASE(OP_push_i8):\n            *sp++ = JS_NewInt32(ctx, get_i8(pc));\n            pc += 1;\n            BREAK;\n        CASE(OP_push_i16):\n            *sp++ = JS_NewInt32(ctx, get_i16(pc));\n            pc += 2;\n            BREAK;\n        CASE(OP_push_const8):\n            *sp++ = JS_DupValue(ctx, b->cpool[*pc++]);\n            BREAK;\n        CASE(OP_fclosure8):\n            *sp++ = js_closure(ctx, JS_DupValue(ctx, b->cpool[*pc++]), var_refs, sf);\n            if (unlikely(JS_IsException(sp[-1])))\n                goto exception;\n            BREAK;\n        CASE(OP_push_empty_string):\n            *sp++ = JS_AtomToString(ctx, JS_ATOM_empty_string);\n            BREAK;\n        CASE(OP_get_length):\n            {\n                JSValue val;\n\n                val = JS_GetProperty(ctx, sp[-1], JS_ATOM_length);\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = val;\n            }\n            BREAK;\n#endif\n        CASE(OP_push_atom_value):\n            *sp++ = JS_AtomToValue(ctx, get_u32(pc));\n            pc += 4;\n            BREAK;\n        CASE(OP_undefined):\n            *sp++ = JS_UNDEFINED;\n            BREAK;\n        CASE(OP_null):\n            *sp++ = JS_NULL;\n            BREAK;\n        CASE(OP_push_this):\n            /* OP_push_this is only called at the start of a function */\n            {\n                JSValue val;\n                if (!(b->js_mode & JS_MODE_STRICT)) {\n                    uint32_t tag = JS_VALUE_GET_TAG(this_obj);\n                    if (likely(tag == JS_TAG_OBJECT))\n                        goto normal_this;\n                    if (tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED) {\n                        val = JS_DupValue(ctx, ctx->global_obj);\n                    } else {\n                        val = JS_ToObject(ctx, this_obj);\n                        if (JS_IsException(val))\n                            goto exception;\n                    }\n                } else {\n                normal_this:\n                    val = JS_DupValue(ctx, this_obj);\n                }\n                *sp++ = val;\n            }\n            BREAK;\n        CASE(OP_push_false):\n            *sp++ = JS_FALSE;\n            BREAK;\n        CASE(OP_push_true):\n            *sp++ = JS_TRUE;\n            BREAK;\n        CASE(OP_object):\n            *sp++ = JS_NewObject(ctx);\n            if (unlikely(JS_IsException(sp[-1])))\n                goto exception;\n            BREAK;\n        CASE(OP_special_object):\n            {\n                int arg = *pc++;\n                switch(arg) {\n                case OP_SPECIAL_OBJECT_ARGUMENTS:\n                    *sp++ = js_build_arguments(ctx, argc, (JSValueConst *)argv);\n                    if (unlikely(JS_IsException(sp[-1])))\n                        goto exception;\n                    break;\n                case OP_SPECIAL_OBJECT_MAPPED_ARGUMENTS:\n                    *sp++ = js_build_mapped_arguments(ctx, argc, (JSValueConst *)argv,\n                                                      sf, min_int(argc, b->arg_count));\n                    if (unlikely(JS_IsException(sp[-1])))\n                        goto exception;\n                    break;\n                case OP_SPECIAL_OBJECT_THIS_FUNC:\n                    *sp++ = JS_DupValue(ctx, sf->cur_func);\n                    break;\n                case OP_SPECIAL_OBJECT_NEW_TARGET:\n                    *sp++ = JS_DupValue(ctx, new_target);\n                    break;\n                case OP_SPECIAL_OBJECT_HOME_OBJECT:\n                    {\n                        JSObject *p1;\n                        p1 = p->u.func.home_object;\n                        if (unlikely(!p1))\n                            *sp++ = JS_UNDEFINED;\n                        else\n                            *sp++ = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p1));\n                    }\n                    break;\n                case OP_SPECIAL_OBJECT_VAR_OBJECT:\n                    *sp++ = JS_NewObjectProto(ctx, JS_NULL);\n                    if (unlikely(JS_IsException(sp[-1])))\n                        goto exception;\n                    break;\n                case OP_SPECIAL_OBJECT_IMPORT_META:\n                    *sp++ = js_import_meta(ctx);\n                    if (unlikely(JS_IsException(sp[-1])))\n                        goto exception;\n                    break;\n                default:\n                    abort();\n                }\n            }\n            BREAK;\n        CASE(OP_rest):\n            {\n                int first = get_u16(pc);\n                pc += 2;\n                *sp++ = js_build_rest(ctx, first, argc, (JSValueConst *)argv);\n                if (unlikely(JS_IsException(sp[-1])))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_drop):\n            JS_FreeValue(ctx, sp[-1]);\n            sp--;\n            BREAK;\n        CASE(OP_nip):\n            JS_FreeValue(ctx, sp[-2]);\n            sp[-2] = sp[-1];\n            sp--;\n            BREAK;\n        CASE(OP_nip1): /* a b c -> b c */\n            JS_FreeValue(ctx, sp[-3]);\n            sp[-3] = sp[-2];\n            sp[-2] = sp[-1];\n            sp--;\n            BREAK;\n        CASE(OP_dup):\n            sp[0] = JS_DupValue(ctx, sp[-1]);\n            sp++;\n            BREAK;\n        CASE(OP_dup2): /* a b -> a b a b */\n            sp[0] = JS_DupValue(ctx, sp[-2]);\n            sp[1] = JS_DupValue(ctx, sp[-1]);\n            sp += 2;\n            BREAK;\n        CASE(OP_dup3): /* a b c -> a b c a b c */\n            sp[0] = JS_DupValue(ctx, sp[-3]);\n            sp[1] = JS_DupValue(ctx, sp[-2]);\n            sp[2] = JS_DupValue(ctx, sp[-1]);\n            sp += 3;\n            BREAK;\n        CASE(OP_dup1): /* a b -> a a b */\n            sp[0] = sp[-1];\n            sp[-1] = JS_DupValue(ctx, sp[-2]);\n            sp++;\n            BREAK;\n        CASE(OP_insert2): /* obj a -> a obj a (dup_x1) */\n            sp[0] = sp[-1];\n            sp[-1] = sp[-2];\n            sp[-2] = JS_DupValue(ctx, sp[0]);\n            sp++;\n            BREAK;\n        CASE(OP_insert3): /* obj prop a -> a obj prop a (dup_x2) */\n            sp[0] = sp[-1];\n            sp[-1] = sp[-2];\n            sp[-2] = sp[-3];\n            sp[-3] = JS_DupValue(ctx, sp[0]);\n            sp++;\n            BREAK;\n        CASE(OP_insert4): /* this obj prop a -> a this obj prop a */\n            sp[0] = sp[-1];\n            sp[-1] = sp[-2];\n            sp[-2] = sp[-3];\n            sp[-3] = sp[-4];\n            sp[-4] = JS_DupValue(ctx, sp[0]);\n            sp++;\n            BREAK;\n        CASE(OP_perm3): /* obj a b -> a obj b (213) */\n            {\n                JSValue tmp;\n                tmp = sp[-2];\n                sp[-2] = sp[-3];\n                sp[-3] = tmp;\n            }\n            BREAK;\n        CASE(OP_rot3l): /* x a b -> a b x (231) */\n            {\n                JSValue tmp;\n                tmp = sp[-3];\n                sp[-3] = sp[-2];\n                sp[-2] = sp[-1];\n                sp[-1] = tmp;\n            }\n            BREAK;\n        CASE(OP_rot4l): /* x a b c -> a b c x */\n            {\n                JSValue tmp;\n                tmp = sp[-4];\n                sp[-4] = sp[-3];\n                sp[-3] = sp[-2];\n                sp[-2] = sp[-1];\n                sp[-1] = tmp;\n            }\n            BREAK;\n        CASE(OP_rot5l): /* x a b c d -> a b c d x */\n            {\n                JSValue tmp;\n                tmp = sp[-5];\n                sp[-5] = sp[-4];\n                sp[-4] = sp[-3];\n                sp[-3] = sp[-2];\n                sp[-2] = sp[-1];\n                sp[-1] = tmp;\n            }\n            BREAK;\n        CASE(OP_rot3r): /* a b x -> x a b (312) */\n            {\n                JSValue tmp;\n                tmp = sp[-1];\n                sp[-1] = sp[-2];\n                sp[-2] = sp[-3];\n                sp[-3] = tmp;\n            }\n            BREAK;\n        CASE(OP_perm4): /* obj prop a b -> a obj prop b */\n            {\n                JSValue tmp;\n                tmp = sp[-2];\n                sp[-2] = sp[-3];\n                sp[-3] = sp[-4];\n                sp[-4] = tmp;\n            }\n            BREAK;\n        CASE(OP_perm5): /* this obj prop a b -> a this obj prop b */\n            {\n                JSValue tmp;\n                tmp = sp[-2];\n                sp[-2] = sp[-3];\n                sp[-3] = sp[-4];\n                sp[-4] = sp[-5];\n                sp[-5] = tmp;\n            }\n            BREAK;\n        CASE(OP_swap): /* a b -> b a */\n            {\n                JSValue tmp;\n                tmp = sp[-2];\n                sp[-2] = sp[-1];\n                sp[-1] = tmp;\n            }\n            BREAK;\n        CASE(OP_swap2): /* a b c d -> c d a b */\n            {\n                JSValue tmp1, tmp2;\n                tmp1 = sp[-4];\n                tmp2 = sp[-3];\n                sp[-4] = sp[-2];\n                sp[-3] = sp[-1];\n                sp[-2] = tmp1;\n                sp[-1] = tmp2;\n            }\n            BREAK;\n\n        CASE(OP_fclosure):\n            {\n                JSValue bfunc = JS_DupValue(ctx, b->cpool[get_u32(pc)]);\n                pc += 4;\n                *sp++ = js_closure(ctx, bfunc, var_refs, sf);\n                if (unlikely(JS_IsException(sp[-1])))\n                    goto exception;\n            }\n            BREAK;\n#if SHORT_OPCODES\n        CASE(OP_call0):\n        CASE(OP_call1):\n        CASE(OP_call2):\n        CASE(OP_call3):\n            call_argc = opcode - OP_call0;\n            goto has_call_argc;\n#endif\n        CASE(OP_call):\n        CASE(OP_tail_call):\n            {\n                call_argc = get_u16(pc);\n                pc += 2;\n                goto has_call_argc;\n            has_call_argc:\n                call_argv = sp - call_argc;\n                sf->cur_pc = pc;\n                ret_val = JS_CallInternal(ctx, call_argv[-1], JS_UNDEFINED,\n                                          JS_UNDEFINED, call_argc, call_argv, 0);\n                if (unlikely(JS_IsException(ret_val)))\n                    goto exception;\n                if (opcode == OP_tail_call)\n                    goto done;\n                for(i = -1; i < call_argc; i++)\n                    JS_FreeValue(ctx, call_argv[i]);\n                sp -= call_argc + 1;\n                *sp++ = ret_val;\n            }\n            BREAK;\n        CASE(OP_call_constructor):\n            {\n                call_argc = get_u16(pc);\n                pc += 2;\n                call_argv = sp - call_argc;\n                sf->cur_pc = pc;\n                ret_val = JS_CallConstructorInternal(ctx, call_argv[-2],\n                                                     call_argv[-1],\n                                                     call_argc, call_argv, 0);\n                if (unlikely(JS_IsException(ret_val)))\n                    goto exception;\n                for(i = -2; i < call_argc; i++)\n                    JS_FreeValue(ctx, call_argv[i]);\n                sp -= call_argc + 2;\n                *sp++ = ret_val;\n            }\n            BREAK;\n        CASE(OP_call_method):\n        CASE(OP_tail_call_method):\n            {\n                call_argc = get_u16(pc);\n                pc += 2;\n                call_argv = sp - call_argc;\n                sf->cur_pc = pc;\n                ret_val = JS_CallInternal(ctx, call_argv[-1], call_argv[-2],\n                                          JS_UNDEFINED, call_argc, call_argv, 0);\n                if (unlikely(JS_IsException(ret_val)))\n                    goto exception;\n                if (opcode == OP_tail_call_method)\n                    goto done;\n                for(i = -2; i < call_argc; i++)\n                    JS_FreeValue(ctx, call_argv[i]);\n                sp -= call_argc + 2;\n                *sp++ = ret_val;\n            }\n            BREAK;\n        CASE(OP_array_from):\n            {\n                int i, ret;\n\n                call_argc = get_u16(pc);\n                pc += 2;\n                ret_val = JS_NewArray(ctx);\n                if (unlikely(JS_IsException(ret_val)))\n                    goto exception;\n                call_argv = sp - call_argc;\n                for(i = 0; i < call_argc; i++) {\n                    ret = JS_DefinePropertyValue(ctx, ret_val, __JS_AtomFromUInt32(i), call_argv[i],\n                                                 JS_PROP_C_W_E | JS_PROP_THROW);\n                    call_argv[i] = JS_UNDEFINED;\n                    if (ret < 0) {\n                        JS_FreeValue(ctx, ret_val);\n                        goto exception;\n                    }\n                }\n                sp -= call_argc;\n                *sp++ = ret_val;\n            }\n            BREAK;\n\n        CASE(OP_apply):\n            {\n                int magic;\n                magic = get_u16(pc);\n                pc += 2;\n\n                ret_val = js_function_apply(ctx, sp[-3], 2, (JSValueConst *)&sp[-2], magic);\n                if (unlikely(JS_IsException(ret_val)))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-3]);\n                JS_FreeValue(ctx, sp[-2]);\n                JS_FreeValue(ctx, sp[-1]);\n                sp -= 3;\n                *sp++ = ret_val;\n            }\n            BREAK;\n        CASE(OP_return):\n            ret_val = *--sp;\n            goto done;\n        CASE(OP_return_undef):\n            ret_val = JS_UNDEFINED;\n            goto done;\n\n        CASE(OP_check_ctor_return):\n            /* return TRUE if 'this' should be returned */\n            if (!JS_IsObject(sp[-1])) {\n                if (!JS_IsUndefined(sp[-1])) {\n                    JS_ThrowTypeError(caller_ctx, \"derived class constructor must return an object or undefined\");\n                    goto exception;\n                }\n                sp[0] = JS_TRUE;\n            } else {\n                sp[0] = JS_FALSE;\n            }\n            sp++;\n            BREAK;\n        CASE(OP_check_ctor):\n            if (JS_IsUndefined(new_target)) {\n                JS_ThrowTypeError(ctx, \"class constructors must be invoked with 'new'\");\n                goto exception;\n            }\n            BREAK;\n        CASE(OP_check_brand):\n            if (JS_CheckBrand(ctx, sp[-2], sp[-1]) < 0)\n                goto exception;\n            BREAK;\n        CASE(OP_add_brand):\n            if (JS_AddBrand(ctx, sp[-2], sp[-1]) < 0)\n                goto exception;\n            JS_FreeValue(ctx, sp[-2]);\n            JS_FreeValue(ctx, sp[-1]);\n            sp -= 2;\n            BREAK;\n            \n        CASE(OP_throw):\n            JS_Throw(ctx, *--sp);\n            goto exception;\n\n        CASE(OP_throw_error):\n#define JS_THROW_VAR_RO             0\n#define JS_THROW_VAR_REDECL         1\n#define JS_THROW_VAR_UNINITIALIZED  2\n#define JS_THROW_ERROR_DELETE_SUPER   3\n#define JS_THROW_ERROR_ITERATOR_THROW 4\n            {\n                JSAtom atom;\n                int type;\n                atom = get_u32(pc);\n                type = pc[4];\n                pc += 5;\n                if (type == JS_THROW_VAR_RO)\n                    JS_ThrowTypeErrorReadOnly(ctx, JS_PROP_THROW, atom);\n                else\n                if (type == JS_THROW_VAR_REDECL)\n                    JS_ThrowSyntaxErrorVarRedeclaration(ctx, atom);\n                else\n                if (type == JS_THROW_VAR_UNINITIALIZED)\n                    JS_ThrowReferenceErrorUninitialized(ctx, atom);\n                else\n                if (type == JS_THROW_ERROR_DELETE_SUPER)\n                    JS_ThrowReferenceError(ctx, \"unsupported reference to 'super'\");\n                else\n                if (type == JS_THROW_ERROR_ITERATOR_THROW)\n                    JS_ThrowTypeError(ctx, \"iterator does not have a throw method\");\n                else\n                    JS_ThrowInternalError(ctx, \"invalid throw var type %d\", type);\n            }\n            goto exception;\n\n        CASE(OP_eval):\n            {\n                JSValueConst obj;\n                int scope_idx;\n                call_argc = get_u16(pc);\n                scope_idx = get_u16(pc + 2) - 1;\n                pc += 4;\n                call_argv = sp - call_argc;\n                sf->cur_pc = pc;\n                if (js_same_value(ctx, call_argv[-1], ctx->eval_obj)) {\n                    if (call_argc >= 1)\n                        obj = call_argv[0];\n                    else\n                        obj = JS_UNDEFINED;\n                    ret_val = JS_EvalObject(ctx, JS_UNDEFINED, obj,\n                                            JS_EVAL_TYPE_DIRECT, scope_idx);\n                } else {\n                    ret_val = JS_CallInternal(ctx, call_argv[-1], JS_UNDEFINED,\n                                              JS_UNDEFINED, call_argc, call_argv, 0);\n                }\n                if (unlikely(JS_IsException(ret_val)))\n                    goto exception;\n                for(i = -1; i < call_argc; i++)\n                    JS_FreeValue(ctx, call_argv[i]);\n                sp -= call_argc + 1;\n                *sp++ = ret_val;\n            }\n            BREAK;\n            /* could merge with OP_apply */\n        CASE(OP_apply_eval):\n            {\n                int scope_idx;\n                uint32_t len;\n                JSValue *tab;\n                JSValueConst obj;\n\n                scope_idx = get_u16(pc) - 1;\n                pc += 2;\n                tab = build_arg_list(ctx, &len, sp[-1]);\n                if (!tab)\n                    goto exception;\n                if (js_same_value(ctx, sp[-2], ctx->eval_obj)) {\n                    if (len >= 1)\n                        obj = tab[0];\n                    else\n                        obj = JS_UNDEFINED;\n                    ret_val = JS_EvalObject(ctx, JS_UNDEFINED, obj,\n                                            JS_EVAL_TYPE_DIRECT, scope_idx);\n                } else {\n                    ret_val = JS_Call(ctx, sp[-2], JS_UNDEFINED, len,\n                                      (JSValueConst *)tab);\n                }\n                free_arg_list(ctx, tab, len);\n                if (unlikely(JS_IsException(ret_val)))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-2]);\n                JS_FreeValue(ctx, sp[-1]);\n                sp -= 2;\n                *sp++ = ret_val;\n            }\n            BREAK;\n\n        CASE(OP_regexp):\n            {\n                sp[-2] = js_regexp_constructor_internal(ctx, JS_UNDEFINED,\n                                                        sp[-2], sp[-1]);\n                sp--;\n            }\n            BREAK;\n\n        CASE(OP_get_super):\n            {\n                JSValue proto;\n                proto = JS_GetPrototype(ctx, sp[-1]);\n                if (JS_IsException(proto))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = proto;\n            }\n            BREAK;\n\n        CASE(OP_import):\n            {\n                JSValue val;\n                val = js_dynamic_import(ctx, sp[-1]);\n                if (JS_IsException(val))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = val;\n            }\n            BREAK;\n\n        CASE(OP_check_var):\n            {\n                int ret;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                ret = JS_CheckGlobalVar(ctx, atom);\n                if (ret < 0)\n                    goto exception;\n                *sp++ = JS_NewBool(ctx, ret);\n            }\n            BREAK;\n\n        CASE(OP_get_var_undef):\n        CASE(OP_get_var):\n            {\n                JSValue val;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                val = JS_GetGlobalVar(ctx, atom, opcode - OP_get_var_undef);\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n                *sp++ = val;\n            }\n            BREAK;\n\n        CASE(OP_put_var):\n        CASE(OP_put_var_init):\n            {\n                int ret;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                ret = JS_SetGlobalVar(ctx, atom, sp[-1], opcode - OP_put_var);\n                sp--;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_put_var_strict):\n            {\n                int ret;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                /* sp[-2] is JS_TRUE or JS_FALSE */\n                if (unlikely(!JS_VALUE_GET_INT(sp[-2]))) {\n                    JS_ThrowReferenceErrorNotDefined(ctx, atom);\n                    goto exception;\n                }\n                ret = JS_SetGlobalVar(ctx, atom, sp[-1], 2);\n                sp -= 2;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_check_define_var):\n            {\n                JSAtom atom;\n                int flags;\n                atom = get_u32(pc);\n                flags = pc[4];\n                pc += 5;\n                if (JS_CheckDefineGlobalVar(ctx, atom, flags))\n                    goto exception;\n            }\n            BREAK;\n        CASE(OP_define_var):\n            {\n                JSAtom atom;\n                int flags;\n                atom = get_u32(pc);\n                flags = pc[4];\n                pc += 5;\n                if (JS_DefineGlobalVar(ctx, atom, flags))\n                    goto exception;\n            }\n            BREAK;\n        CASE(OP_define_func):\n            {\n                JSAtom atom;\n                int flags;\n                atom = get_u32(pc);\n                flags = pc[4];\n                pc += 5;\n                if (JS_DefineGlobalFunction(ctx, atom, sp[-1], flags))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp--;\n            }\n            BREAK;\n\n        CASE(OP_get_loc):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                sp[0] = JS_DupValue(ctx, var_buf[idx]);\n                sp++;\n            }\n            BREAK;\n        CASE(OP_put_loc):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                set_value(ctx, &var_buf[idx], sp[-1]);\n                sp--;\n            }\n            BREAK;\n        CASE(OP_set_loc):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                set_value(ctx, &var_buf[idx], JS_DupValue(ctx, sp[-1]));\n            }\n            BREAK;\n        CASE(OP_get_arg):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                sp[0] = JS_DupValue(ctx, arg_buf[idx]);\n                sp++;\n            }\n            BREAK;\n        CASE(OP_put_arg):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                set_value(ctx, &arg_buf[idx], sp[-1]);\n                sp--;\n            }\n            BREAK;\n        CASE(OP_set_arg):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                set_value(ctx, &arg_buf[idx], JS_DupValue(ctx, sp[-1]));\n            }\n            BREAK;\n\n#if SHORT_OPCODES\n        CASE(OP_get_loc8): *sp++ = JS_DupValue(ctx, var_buf[*pc++]); BREAK;\n        CASE(OP_put_loc8): set_value(ctx, &var_buf[*pc++], *--sp); BREAK;\n        CASE(OP_set_loc8): set_value(ctx, &var_buf[*pc++], JS_DupValue(ctx, sp[-1])); BREAK;\n\n        CASE(OP_get_loc0): *sp++ = JS_DupValue(ctx, var_buf[0]); BREAK;\n        CASE(OP_get_loc1): *sp++ = JS_DupValue(ctx, var_buf[1]); BREAK;\n        CASE(OP_get_loc2): *sp++ = JS_DupValue(ctx, var_buf[2]); BREAK;\n        CASE(OP_get_loc3): *sp++ = JS_DupValue(ctx, var_buf[3]); BREAK;\n        CASE(OP_put_loc0): set_value(ctx, &var_buf[0], *--sp); BREAK;\n        CASE(OP_put_loc1): set_value(ctx, &var_buf[1], *--sp); BREAK;\n        CASE(OP_put_loc2): set_value(ctx, &var_buf[2], *--sp); BREAK;\n        CASE(OP_put_loc3): set_value(ctx, &var_buf[3], *--sp); BREAK;\n        CASE(OP_set_loc0): set_value(ctx, &var_buf[0], JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_loc1): set_value(ctx, &var_buf[1], JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_loc2): set_value(ctx, &var_buf[2], JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_loc3): set_value(ctx, &var_buf[3], JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_get_arg0): *sp++ = JS_DupValue(ctx, arg_buf[0]); BREAK;\n        CASE(OP_get_arg1): *sp++ = JS_DupValue(ctx, arg_buf[1]); BREAK;\n        CASE(OP_get_arg2): *sp++ = JS_DupValue(ctx, arg_buf[2]); BREAK;\n        CASE(OP_get_arg3): *sp++ = JS_DupValue(ctx, arg_buf[3]); BREAK;\n        CASE(OP_put_arg0): set_value(ctx, &arg_buf[0], *--sp); BREAK;\n        CASE(OP_put_arg1): set_value(ctx, &arg_buf[1], *--sp); BREAK;\n        CASE(OP_put_arg2): set_value(ctx, &arg_buf[2], *--sp); BREAK;\n        CASE(OP_put_arg3): set_value(ctx, &arg_buf[3], *--sp); BREAK;\n        CASE(OP_set_arg0): set_value(ctx, &arg_buf[0], JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_arg1): set_value(ctx, &arg_buf[1], JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_arg2): set_value(ctx, &arg_buf[2], JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_arg3): set_value(ctx, &arg_buf[3], JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_get_var_ref0): *sp++ = JS_DupValue(ctx, *var_refs[0]->pvalue); BREAK;\n        CASE(OP_get_var_ref1): *sp++ = JS_DupValue(ctx, *var_refs[1]->pvalue); BREAK;\n        CASE(OP_get_var_ref2): *sp++ = JS_DupValue(ctx, *var_refs[2]->pvalue); BREAK;\n        CASE(OP_get_var_ref3): *sp++ = JS_DupValue(ctx, *var_refs[3]->pvalue); BREAK;\n        CASE(OP_put_var_ref0): set_value(ctx, var_refs[0]->pvalue, *--sp); BREAK;\n        CASE(OP_put_var_ref1): set_value(ctx, var_refs[1]->pvalue, *--sp); BREAK;\n        CASE(OP_put_var_ref2): set_value(ctx, var_refs[2]->pvalue, *--sp); BREAK;\n        CASE(OP_put_var_ref3): set_value(ctx, var_refs[3]->pvalue, *--sp); BREAK;\n        CASE(OP_set_var_ref0): set_value(ctx, var_refs[0]->pvalue, JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_var_ref1): set_value(ctx, var_refs[1]->pvalue, JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_var_ref2): set_value(ctx, var_refs[2]->pvalue, JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_var_ref3): set_value(ctx, var_refs[3]->pvalue, JS_DupValue(ctx, sp[-1])); BREAK;\n#endif\n\n        CASE(OP_get_var_ref):\n            {\n                int idx;\n                JSValue val;\n                idx = get_u16(pc);\n                pc += 2;\n                val = *var_refs[idx]->pvalue;\n                sp[0] = JS_DupValue(ctx, val);\n                sp++;\n            }\n            BREAK;\n        CASE(OP_put_var_ref):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                set_value(ctx, var_refs[idx]->pvalue, sp[-1]);\n                sp--;\n            }\n            BREAK;\n        CASE(OP_set_var_ref):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                set_value(ctx, var_refs[idx]->pvalue, JS_DupValue(ctx, sp[-1]));\n            }\n            BREAK;\n        CASE(OP_get_var_ref_check):\n            {\n                int idx;\n                JSValue val;\n                idx = get_u16(pc);\n                pc += 2;\n                val = *var_refs[idx]->pvalue;\n                if (unlikely(JS_IsUninitialized(val))) {\n                    JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, TRUE);\n                    goto exception;\n                }\n                sp[0] = JS_DupValue(ctx, val);\n                sp++;\n            }\n            BREAK;\n        CASE(OP_put_var_ref_check):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                if (unlikely(JS_IsUninitialized(*var_refs[idx]->pvalue))) {\n                    JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, TRUE);\n                    goto exception;\n                }\n                set_value(ctx, var_refs[idx]->pvalue, sp[-1]);\n                sp--;\n            }\n            BREAK;\n        CASE(OP_put_var_ref_check_init):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                if (unlikely(!JS_IsUninitialized(*var_refs[idx]->pvalue))) {\n                    JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, TRUE);\n                    goto exception;\n                }\n                set_value(ctx, var_refs[idx]->pvalue, sp[-1]);\n                sp--;\n            }\n            BREAK;\n        CASE(OP_set_loc_uninitialized):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                set_value(ctx, &var_buf[idx], JS_UNINITIALIZED);\n            }\n            BREAK;\n        CASE(OP_get_loc_check):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                if (unlikely(JS_IsUninitialized(var_buf[idx]))) {\n                    JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, FALSE);\n                    goto exception;\n                }\n                sp[0] = JS_DupValue(ctx, var_buf[idx]);\n                sp++;\n            }\n            BREAK;\n        CASE(OP_put_loc_check):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                if (unlikely(JS_IsUninitialized(var_buf[idx]))) {\n                    JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, FALSE);\n                    goto exception;\n                }\n                set_value(ctx, &var_buf[idx], sp[-1]);\n                sp--;\n            }\n            BREAK;\n        CASE(OP_put_loc_check_init):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                if (unlikely(!JS_IsUninitialized(var_buf[idx]))) {\n                    JS_ThrowReferenceError(ctx, \"'this' can be initialized only once\");\n                    goto exception;\n                }\n                set_value(ctx, &var_buf[idx], sp[-1]);\n                sp--;\n            }\n            BREAK;\n        CASE(OP_close_loc):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                close_lexical_var(ctx, sf, idx, FALSE);\n            }\n            BREAK;\n\n        CASE(OP_make_loc_ref):\n        CASE(OP_make_arg_ref):\n        CASE(OP_make_var_ref_ref):\n            {\n                JSVarRef *var_ref;\n                JSProperty *pr;\n                JSAtom atom;\n                int idx;\n                atom = get_u32(pc);\n                idx = get_u16(pc + 4);\n                pc += 6;\n                *sp++ = JS_NewObjectProto(ctx, JS_NULL);\n                if (unlikely(JS_IsException(sp[-1])))\n                    goto exception;\n                if (opcode == OP_make_var_ref_ref) {\n                    var_ref = var_refs[idx];\n                    var_ref->header.ref_count++;\n                } else {\n                    var_ref = get_var_ref(ctx, sf, idx, opcode == OP_make_arg_ref);\n                    if (!var_ref)\n                        goto exception;\n                }\n                pr = add_property(ctx, JS_VALUE_GET_OBJ(sp[-1]), atom,\n                                  JS_PROP_WRITABLE | JS_PROP_VARREF);\n                if (!pr) {\n                    free_var_ref(rt, var_ref);\n                    goto exception;\n                }\n                pr->u.var_ref = var_ref;\n                *sp++ = JS_AtomToValue(ctx, atom);\n            }\n            BREAK;\n        CASE(OP_make_var_ref):\n            {\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                if (JS_GetGlobalVarRef(ctx, atom, sp))\n                    goto exception;\n                sp += 2;\n            }\n            BREAK;\n\n        CASE(OP_goto):\n            pc += (int32_t)get_u32(pc);\n            if (unlikely(js_poll_interrupts(ctx)))\n                goto exception;\n            BREAK;\n#if SHORT_OPCODES\n        CASE(OP_goto16):\n            pc += (int16_t)get_u16(pc);\n            if (unlikely(js_poll_interrupts(ctx)))\n                goto exception;\n            BREAK;\n        CASE(OP_goto8):\n            pc += (int8_t)pc[0];\n            if (unlikely(js_poll_interrupts(ctx)))\n                goto exception;\n            BREAK;\n#endif\n        CASE(OP_if_true):\n            {\n                int res;\n                JSValue op1;\n\n                op1 = sp[-1];\n                pc += 4;\n                if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) {\n                    res = JS_VALUE_GET_INT(op1);\n                } else {\n                    res = JS_ToBoolFree(ctx, op1);\n                }\n                sp--;\n                if (res) {\n                    pc += (int32_t)get_u32(pc - 4) - 4;\n                }\n                if (unlikely(js_poll_interrupts(ctx)))\n                    goto exception;\n            }\n            BREAK;\n        CASE(OP_if_false):\n            {\n                int res;\n                JSValue op1;\n\n                op1 = sp[-1];\n                pc += 4;\n                if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) {\n                    res = JS_VALUE_GET_INT(op1);\n                } else {\n                    res = JS_ToBoolFree(ctx, op1);\n                }\n                sp--;\n                if (!res) {\n                    pc += (int32_t)get_u32(pc - 4) - 4;\n                }\n                if (unlikely(js_poll_interrupts(ctx)))\n                    goto exception;\n            }\n            BREAK;\n#if SHORT_OPCODES\n        CASE(OP_if_true8):\n            {\n                int res;\n                JSValue op1;\n\n                op1 = sp[-1];\n                pc += 1;\n                if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) {\n                    res = JS_VALUE_GET_INT(op1);\n                } else {\n                    res = JS_ToBoolFree(ctx, op1);\n                }\n                sp--;\n                if (res) {\n                    pc += (int8_t)pc[-1] - 1;\n                }\n                if (unlikely(js_poll_interrupts(ctx)))\n                    goto exception;\n            }\n            BREAK;\n        CASE(OP_if_false8):\n            {\n                int res;\n                JSValue op1;\n\n                op1 = sp[-1];\n                pc += 1;\n                if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) {\n                    res = JS_VALUE_GET_INT(op1);\n                } else {\n                    res = JS_ToBoolFree(ctx, op1);\n                }\n                sp--;\n                if (!res) {\n                    pc += (int8_t)pc[-1] - 1;\n                }\n                if (unlikely(js_poll_interrupts(ctx)))\n                    goto exception;\n            }\n            BREAK;\n#endif\n        CASE(OP_catch):\n            {\n                int32_t diff;\n                diff = get_u32(pc);\n                sp[0] = JS_NewCatchOffset(ctx, pc + diff - b->byte_code_buf);\n                sp++;\n                pc += 4;\n            }\n            BREAK;\n        CASE(OP_gosub):\n            {\n                int32_t diff;\n                diff = get_u32(pc);\n                /* XXX: should have a different tag to avoid security flaw */\n                sp[0] = JS_NewInt32(ctx, pc + 4 - b->byte_code_buf);\n                sp++;\n                pc += diff;\n            }\n            BREAK;\n        CASE(OP_ret):\n            {\n                JSValue op1;\n                uint32_t pos;\n                op1 = sp[-1];\n                if (unlikely(JS_VALUE_GET_TAG(op1) != JS_TAG_INT))\n                    goto ret_fail;\n                pos = JS_VALUE_GET_INT(op1);\n                if (unlikely(pos >= b->byte_code_len)) {\n                ret_fail:\n                    JS_ThrowInternalError(ctx, \"invalid ret value\");\n                    goto exception;\n                }\n                sp--;\n                pc = b->byte_code_buf + pos;\n            }\n            BREAK;\n\n        CASE(OP_for_in_start):\n            if (js_for_in_start(ctx, sp))\n                goto exception;\n            BREAK;\n        CASE(OP_for_in_next):\n            if (js_for_in_next(ctx, sp))\n                goto exception;\n            sp += 2;\n            BREAK;\n        CASE(OP_for_of_start):\n            if (js_for_of_start(ctx, sp, FALSE))\n                goto exception;\n            sp += 1;\n            *sp++ = JS_NewCatchOffset(ctx, 0);\n            BREAK;\n        CASE(OP_for_of_next):\n            {\n                int offset = -3 - pc[0];\n                pc += 1;\n                if (js_for_of_next(ctx, sp, offset))\n                    goto exception;\n                sp += 2;\n            }\n            BREAK;\n        CASE(OP_for_await_of_start):\n            if (js_for_of_start(ctx, sp, TRUE))\n                goto exception;\n            sp += 1;\n            *sp++ = JS_NewCatchOffset(ctx, 0);\n            BREAK;\n        CASE(OP_iterator_get_value_done):\n            if (js_iterator_get_value_done(ctx, sp))\n                goto exception;\n            sp += 1;\n            BREAK;\n        CASE(OP_iterator_check_object):\n            if (unlikely(!JS_IsObject(sp[-1]))) {\n                JS_ThrowTypeError(ctx, \"iterator must return an object\");\n                goto exception;\n            }\n            BREAK;\n\n        CASE(OP_iterator_close):\n            /* iter_obj next catch_offset -> */\n            sp--; /* drop the catch offset to avoid getting caught by exception */\n            JS_FreeValue(ctx, sp[-1]); /* drop the next method */\n            sp--;\n            if (!JS_IsUndefined(sp[-1])) {\n                if (JS_IteratorClose(ctx, sp[-1], FALSE))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n            }\n            sp--;\n            BREAK;\n        CASE(OP_iterator_close_return):\n            {\n                JSValue ret_val;\n                /* iter_obj next catch_offset ... ret_val ->\n                   ret_eval iter_obj next catch_offset */\n                ret_val = *--sp;\n                while (sp > stack_buf &&\n                       JS_VALUE_GET_TAG(sp[-1]) != JS_TAG_CATCH_OFFSET) {\n                    JS_FreeValue(ctx, *--sp);\n                }\n                if (unlikely(sp < stack_buf + 3)) {\n                    JS_ThrowInternalError(ctx, \"iterator_close_return\");\n                    JS_FreeValue(ctx, ret_val);\n                    goto exception;\n                }\n                sp[0] = sp[-1];\n                sp[-1] = sp[-2];\n                sp[-2] = sp[-3];\n                sp[-3] = ret_val;\n                sp++;\n            }\n            BREAK;\n\n        CASE(OP_iterator_next):\n            /* stack: iter_obj next catch_offset val */\n            {\n                JSValue ret;\n                ret = JS_Call(ctx, sp[-3], sp[-4],\n                              1, (JSValueConst *)(sp - 1));\n                if (JS_IsException(ret))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = ret;\n            }\n            BREAK;\n\n        CASE(OP_iterator_call):\n            /* stack: iter_obj next catch_offset val */\n            {\n                JSValue method, ret;\n                BOOL ret_flag;\n                int flags;\n                flags = *pc++;\n                method = JS_GetProperty(ctx, sp[-4], (flags & 1) ?\n                                        JS_ATOM_throw : JS_ATOM_return);\n                if (JS_IsException(method))\n                    goto exception;\n                if (JS_IsUndefined(method) || JS_IsNull(method)) {\n                    ret_flag = TRUE;\n                } else {\n                    if (flags & 2) {\n                        /* no argument */\n                        ret = JS_CallFree(ctx, method, sp[-4],\n                                          0, NULL);\n                    } else {\n                        ret = JS_CallFree(ctx, method, sp[-4],\n                                          1, (JSValueConst *)(sp - 1));\n                    }\n                    if (JS_IsException(ret))\n                        goto exception;\n                    JS_FreeValue(ctx, sp[-1]);\n                    sp[-1] = ret;\n                    ret_flag = FALSE;\n                }\n                sp[0] = JS_NewBool(ctx, ret_flag);\n                sp += 1;\n            }\n            BREAK;\n\n        CASE(OP_lnot):\n            {\n                int res;\n                JSValue op1;\n\n                op1 = sp[-1];\n                if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) {\n                    res = JS_VALUE_GET_INT(op1) != 0;\n                } else {\n                    res = JS_ToBoolFree(ctx, op1);\n                }\n                sp[-1] = JS_NewBool(ctx, !res);\n            }\n            BREAK;\n\n        CASE(OP_get_field):\n            {\n                JSValue val;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                val = JS_GetProperty(ctx, sp[-1], atom);\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = val;\n            }\n            BREAK;\n\n        CASE(OP_get_field2):\n            {\n                JSValue val;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                val = JS_GetProperty(ctx, sp[-1], atom);\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n                *sp++ = val;\n            }\n            BREAK;\n\n        CASE(OP_put_field):\n            {\n                int ret;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                ret = JS_SetPropertyInternal(ctx, sp[-2], atom, sp[-1],\n                                             JS_PROP_THROW_STRICT);\n                JS_FreeValue(ctx, sp[-2]);\n                sp -= 2;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_private_symbol):\n            {\n                JSAtom atom;\n                JSValue val;\n                \n                atom = get_u32(pc);\n                pc += 4;\n                val = JS_NewSymbolFromAtom(ctx, atom, JS_ATOM_TYPE_PRIVATE);\n                if (JS_IsException(val))\n                    goto exception;\n                *sp++ = val;\n            }\n            BREAK;\n            \n        CASE(OP_get_private_field):\n            {\n                JSValue val;\n\n                val = JS_GetPrivateField(ctx, sp[-2], sp[-1]);\n                JS_FreeValue(ctx, sp[-1]);\n                JS_FreeValue(ctx, sp[-2]);\n                sp[-2] = val;\n                sp--;\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_put_private_field):\n            {\n                int ret;\n                ret = JS_SetPrivateField(ctx, sp[-3], sp[-1], sp[-2]);\n                JS_FreeValue(ctx, sp[-3]);\n                JS_FreeValue(ctx, sp[-1]);\n                sp -= 3;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_define_private_field):\n            {\n                int ret;\n                ret = JS_DefinePrivateField(ctx, sp[-3], sp[-2], sp[-1]);\n                JS_FreeValue(ctx, sp[-2]);\n                sp -= 2;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_define_field):\n            {\n                int ret;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                ret = JS_DefinePropertyValue(ctx, sp[-2], atom, sp[-1],\n                                             JS_PROP_C_W_E | JS_PROP_THROW);\n                sp--;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_set_name):\n            {\n                int ret;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                ret = JS_DefineObjectName(ctx, sp[-1], atom, JS_PROP_CONFIGURABLE);\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n        CASE(OP_set_name_computed):\n            {\n                int ret;\n                ret = JS_DefineObjectNameComputed(ctx, sp[-1], sp[-2], JS_PROP_CONFIGURABLE);\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n        CASE(OP_set_proto):\n            {\n                JSValue proto;\n                proto = sp[-1];\n                if (JS_IsObject(proto) || JS_IsNull(proto)) {\n                    if (JS_SetPrototypeInternal(ctx, sp[-2], proto, TRUE) < 0)\n                        goto exception;\n                }\n                JS_FreeValue(ctx, proto);\n                sp--;\n            }\n            BREAK;\n        CASE(OP_set_home_object):\n            js_method_set_home_object(ctx, sp[-1], sp[-2]);\n            BREAK;\n        CASE(OP_define_method):\n        CASE(OP_define_method_computed):\n            {\n                JSValue getter, setter, value;\n                JSValueConst obj;\n                JSAtom atom;\n                int flags, ret, op_flags;\n                BOOL is_computed;\n#define OP_DEFINE_METHOD_METHOD 0\n#define OP_DEFINE_METHOD_GETTER 1\n#define OP_DEFINE_METHOD_SETTER 2\n#define OP_DEFINE_METHOD_ENUMERABLE 4\n\n                is_computed = (opcode == OP_define_method_computed);\n                if (is_computed) {\n                    atom = JS_ValueToAtom(ctx, sp[-2]);\n                    if (unlikely(atom == JS_ATOM_NULL))\n                        goto exception;\n                    opcode += OP_define_method - OP_define_method_computed;\n                } else {\n                    atom = get_u32(pc);\n                    pc += 4;\n                }\n                op_flags = *pc++;\n\n                obj = sp[-2 - is_computed];\n                flags = JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE |\n                    JS_PROP_HAS_ENUMERABLE | JS_PROP_THROW;\n                if (op_flags & OP_DEFINE_METHOD_ENUMERABLE)\n                    flags |= JS_PROP_ENUMERABLE;\n                op_flags &= 3;\n                value = JS_UNDEFINED;\n                getter = JS_UNDEFINED;\n                setter = JS_UNDEFINED;\n                if (op_flags == OP_DEFINE_METHOD_METHOD) {\n                    value = sp[-1];\n                    flags |= JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE;\n                } else if (op_flags == OP_DEFINE_METHOD_GETTER) {\n                    getter = sp[-1];\n                    flags |= JS_PROP_HAS_GET;\n                } else {\n                    setter = sp[-1];\n                    flags |= JS_PROP_HAS_SET;\n                }\n                ret = js_method_set_properties(ctx, sp[-1], atom, flags, obj);\n                if (ret >= 0) {\n                    ret = JS_DefineProperty(ctx, obj, atom, value,\n                                            getter, setter, flags);\n                }\n                JS_FreeValue(ctx, sp[-1]);\n                if (is_computed) {\n                    JS_FreeAtom(ctx, atom);\n                    JS_FreeValue(ctx, sp[-2]);\n                }\n                sp -= 1 + is_computed;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_define_class):\n        CASE(OP_define_class_computed):\n            {\n                int class_flags;\n                JSAtom atom;\n                \n                atom = get_u32(pc);\n                class_flags = pc[4];\n                pc += 5;\n                if (js_op_define_class(ctx, sp, atom, class_flags,\n                                       var_refs, sf,\n                                       (opcode == OP_define_class_computed)) < 0)\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_get_array_el):\n            {\n                JSValue val;\n\n                val = JS_GetPropertyValue(ctx, sp[-2], sp[-1]);\n                JS_FreeValue(ctx, sp[-2]);\n                sp[-2] = val;\n                sp--;\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_get_array_el2):\n            {\n                JSValue val;\n\n                val = JS_GetPropertyValue(ctx, sp[-2], sp[-1]);\n                sp[-1] = val;\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_get_ref_value):\n            {\n                JSValue val;\n                if (unlikely(JS_IsUndefined(sp[-2]))) {\n                    JSAtom atom = JS_ValueToAtom(ctx, sp[-1]);\n                    if (atom != JS_ATOM_NULL) {\n                        JS_ThrowReferenceErrorNotDefined(ctx, atom);\n                        JS_FreeAtom(ctx, atom);\n                    }\n                    goto exception;\n                }\n                val = JS_GetPropertyValue(ctx, sp[-2],\n                                          JS_DupValue(ctx, sp[-1]));\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n                sp[0] = val;\n                sp++;\n            }\n            BREAK;\n\n        CASE(OP_get_super_value):\n            {\n                JSValue val;\n                JSAtom atom;\n                atom = JS_ValueToAtom(ctx, sp[-1]);\n                if (unlikely(atom == JS_ATOM_NULL))\n                    goto exception;\n                val = JS_GetPropertyInternal(ctx, sp[-2], atom, sp[-3], FALSE);\n                JS_FreeAtom(ctx, atom);\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                JS_FreeValue(ctx, sp[-2]);\n                JS_FreeValue(ctx, sp[-3]);\n                sp[-3] = val;\n                sp -= 2;\n            }\n            BREAK;\n\n        CASE(OP_put_array_el):\n            {\n                int ret;\n\n                ret = JS_SetPropertyValue(ctx, sp[-3], sp[-2], sp[-1], JS_PROP_THROW_STRICT);\n                JS_FreeValue(ctx, sp[-3]);\n                sp -= 3;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_put_ref_value):\n            {\n                int ret, flags;\n                flags = JS_PROP_THROW_STRICT;\n                if (unlikely(JS_IsUndefined(sp[-3]))) {\n                    if (is_strict_mode(ctx)) {\n                        JSAtom atom = JS_ValueToAtom(ctx, sp[-2]);\n                        if (atom != JS_ATOM_NULL) {\n                            JS_ThrowReferenceErrorNotDefined(ctx, atom);\n                            JS_FreeAtom(ctx, atom);\n                        }\n                        goto exception;\n                    } else {\n                        sp[-3] = JS_DupValue(ctx, ctx->global_obj);\n                    }\n                } else {\n                    if (is_strict_mode(ctx))\n                        flags |= JS_PROP_NO_ADD;\n                }\n                ret = JS_SetPropertyValue(ctx, sp[-3], sp[-2], sp[-1], flags);\n                JS_FreeValue(ctx, sp[-3]);\n                sp -= 3;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_put_super_value):\n            {\n                int ret;\n                JSAtom atom;\n                if (JS_VALUE_GET_TAG(sp[-3]) != JS_TAG_OBJECT) {\n                    JS_ThrowTypeErrorNotAnObject(ctx);\n                    goto exception;\n                }\n                atom = JS_ValueToAtom(ctx, sp[-2]);\n                if (unlikely(atom == JS_ATOM_NULL))\n                    goto exception;\n                ret = JS_SetPropertyGeneric(ctx, sp[-3], atom, sp[-1], sp[-4],\n                                            JS_PROP_THROW_STRICT);\n                JS_FreeAtom(ctx, atom);\n                JS_FreeValue(ctx, sp[-4]);\n                JS_FreeValue(ctx, sp[-3]);\n                JS_FreeValue(ctx, sp[-2]);\n                sp -= 4;\n                if (ret < 0)\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_define_array_el):\n            {\n                int ret;\n                ret = JS_DefinePropertyValueValue(ctx, sp[-3], JS_DupValue(ctx, sp[-2]), sp[-1],\n                                                  JS_PROP_C_W_E | JS_PROP_THROW);\n                sp -= 1;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_append):    /* array pos enumobj -- array pos */\n            {\n                if (js_append_enumerate(ctx, sp))\n                    goto exception;\n                JS_FreeValue(ctx, *--sp);\n            }\n            BREAK;\n\n        CASE(OP_copy_data_properties):    /* target source excludeList */\n            {\n                /* stack offsets (-1 based):\n                   2 bits for target,\n                   3 bits for source,\n                   2 bits for exclusionList */\n                int mask;\n\n                mask = *pc++;\n                if (JS_CopyDataProperties(ctx, sp[-1 - (mask & 3)],\n                                          sp[-1 - ((mask >> 2) & 7)],\n                                          sp[-1 - ((mask >> 5) & 7)], 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_add):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    int64_t r;\n                    r = (int64_t)JS_VALUE_GET_INT(op1) + JS_VALUE_GET_INT(op2);\n                    if (unlikely((int)r != r))\n                        goto add_slow;\n                    sp[-2] = JS_NewInt32(ctx, r);\n                    sp--;\n                } else if (JS_VALUE_IS_BOTH_FLOAT(op1, op2)) {\n                    sp[-2] = __JS_NewFloat64(ctx, JS_VALUE_GET_FLOAT64(op1) +\n                                             JS_VALUE_GET_FLOAT64(op2));\n                    sp--;\n                } else {\n                add_slow:\n                    if (js_add_slow(ctx, sp))\n                        goto exception;\n                    sp--;\n                }\n            }\n            BREAK;\n        CASE(OP_add_loc):\n            {\n                JSValue *pv;\n                int idx;\n                idx = *pc;\n                pc += 1;\n\n                pv = &var_buf[idx];\n                if (likely(JS_VALUE_IS_BOTH_INT(*pv, sp[-1]))) {\n                    int64_t r;\n                    r = (int64_t)JS_VALUE_GET_INT(*pv) +\n                        JS_VALUE_GET_INT(sp[-1]);\n                    if (unlikely((int)r != r))\n                        goto add_loc_slow;\n                    *pv = JS_NewInt32(ctx, r);\n                    sp--;\n                } else if (JS_VALUE_GET_TAG(*pv) == JS_TAG_STRING) {\n                    JSValue op1;\n                    op1 = sp[-1];\n                    sp--;\n                    op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE);\n                    if (JS_IsException(op1))\n                        goto exception;\n                    op1 = JS_ConcatString(ctx, JS_DupValue(ctx, *pv), op1);\n                    if (JS_IsException(op1))\n                        goto exception;\n                    set_value(ctx, pv, op1);\n                } else {\n                    JSValue ops[2];\n                add_loc_slow:\n                    /* In case of exception, js_add_slow frees ops[0]\n                       and ops[1], so we must duplicate *pv */\n                    ops[0] = JS_DupValue(ctx, *pv);\n                    ops[1] = sp[-1];\n                    sp--;\n                    if (js_add_slow(ctx, ops + 2))\n                        goto exception;\n                    set_value(ctx, pv, ops[0]);\n                }\n            }\n            BREAK;\n        CASE(OP_sub):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    int64_t r;\n                    r = (int64_t)JS_VALUE_GET_INT(op1) - JS_VALUE_GET_INT(op2);\n                    if (unlikely((int)r != r))\n                        goto binary_arith_slow;\n                    sp[-2] = JS_NewInt32(ctx, r);\n                    sp--;\n                } else if (JS_VALUE_IS_BOTH_FLOAT(op1, op2)) {\n                    sp[-2] = __JS_NewFloat64(ctx, JS_VALUE_GET_FLOAT64(op1) -\n                                             JS_VALUE_GET_FLOAT64(op2));\n                    sp--;\n                } else {\n                    goto binary_arith_slow;\n                }\n            }\n            BREAK;\n        CASE(OP_mul):\n            {\n                JSValue op1, op2;\n                double d;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    int32_t v1, v2;\n                    int64_t r;\n                    v1 = JS_VALUE_GET_INT(op1);\n                    v2 = JS_VALUE_GET_INT(op2);\n                    r = (int64_t)v1 * v2;\n                    if (unlikely((int)r != r)) {\n#ifdef CONFIG_BIGNUM\n                        if (unlikely(sf->js_mode & JS_MODE_MATH) &&\n                            (r < -MAX_SAFE_INTEGER || r > MAX_SAFE_INTEGER))\n                            goto binary_arith_slow;\n#endif\n                        d = (double)r;\n                        goto mul_fp_res;\n                    }\n                    /* need to test zero case for -0 result */\n                    if (unlikely(r == 0 && (v1 | v2) < 0)) {\n                        d = -0.0;\n                        goto mul_fp_res;\n                    }\n                    sp[-2] = JS_NewInt32(ctx, r);\n                    sp--;\n                } else if (JS_VALUE_IS_BOTH_FLOAT(op1, op2)) {\n#ifdef CONFIG_BIGNUM\n                    if (unlikely(sf->js_mode & JS_MODE_MATH))\n                        goto binary_arith_slow;\n#endif\n                    d = JS_VALUE_GET_FLOAT64(op1) * JS_VALUE_GET_FLOAT64(op2);\n                mul_fp_res:\n                    sp[-2] = __JS_NewFloat64(ctx, d);\n                    sp--;\n                } else {\n                    goto binary_arith_slow;\n                }\n            }\n            BREAK;\n        CASE(OP_div):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    int v1, v2;\n                    if (unlikely(sf->js_mode & JS_MODE_MATH))\n                        goto binary_arith_slow;\n                    v1 = JS_VALUE_GET_INT(op1);\n                    v2 = JS_VALUE_GET_INT(op2);\n                    sp[-2] = JS_NewFloat64(ctx, (double)v1 / (double)v2);\n                    sp--;\n                } else {\n                    goto binary_arith_slow;\n                }\n            }\n            BREAK;\n        CASE(OP_mod):\n#ifdef CONFIG_BIGNUM\n        CASE(OP_math_mod):\n#endif\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    int v1, v2, r;\n                    v1 = JS_VALUE_GET_INT(op1);\n                    v2 = JS_VALUE_GET_INT(op2);\n                    /* We must avoid v2 = 0, v1 = INT32_MIN and v2 =\n                       -1 and the cases where the result is -0. */\n                    if (unlikely(v1 < 0 || v2 <= 0))\n                        goto binary_arith_slow;\n                    r = v1 % v2;\n                    sp[-2] = JS_NewInt32(ctx, r);\n                    sp--;\n                } else {\n                    goto binary_arith_slow;\n                }\n            }\n            BREAK;\n        CASE(OP_pow):\n        binary_arith_slow:\n            if (js_binary_arith_slow(ctx, sp, opcode))\n                goto exception;\n            sp--;\n            BREAK;\n\n        CASE(OP_plus):\n            {\n                JSValue op1;\n                uint32_t tag;\n                op1 = sp[-1];\n                tag = JS_VALUE_GET_TAG(op1);\n                if (tag == JS_TAG_INT || JS_TAG_IS_FLOAT64(tag)) {\n                } else {\n                    if (js_unary_arith_slow(ctx, sp, opcode))\n                        goto exception;\n                }\n            }\n            BREAK;\n        CASE(OP_neg):\n            {\n                JSValue op1;\n                uint32_t tag;\n                int val;\n                double d;\n                op1 = sp[-1];\n                tag = JS_VALUE_GET_TAG(op1);\n                if (tag == JS_TAG_INT) {\n                    val = JS_VALUE_GET_INT(op1);\n                    /* Note: -0 cannot be expressed as integer */\n                    if (unlikely(val == 0)) {\n                        d = -0.0;\n                        goto neg_fp_res;\n                    }\n                    if (unlikely(val == INT32_MIN)) {\n                        d = -(double)val;\n                        goto neg_fp_res;\n                    }\n                    sp[-1] = JS_NewInt32(ctx, -val);\n                } else if (JS_TAG_IS_FLOAT64(tag)) {\n                    d = -JS_VALUE_GET_FLOAT64(op1);\n                neg_fp_res:\n                    sp[-1] = __JS_NewFloat64(ctx, d);\n                } else {\n                    if (js_unary_arith_slow(ctx, sp, opcode))\n                        goto exception;\n                }\n            }\n            BREAK;\n        CASE(OP_inc):\n            {\n                JSValue op1;\n                int val;\n                op1 = sp[-1];\n                if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) {\n                    val = JS_VALUE_GET_INT(op1);\n                    if (unlikely(val == INT32_MAX))\n                        goto inc_slow;\n                    sp[-1] = JS_NewInt32(ctx, val + 1);\n                } else {\n                inc_slow:\n                    if (js_unary_arith_slow(ctx, sp, opcode))\n                        goto exception;\n                }\n            }\n            BREAK;\n        CASE(OP_dec):\n            {\n                JSValue op1;\n                int val;\n                op1 = sp[-1];\n                if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) {\n                    val = JS_VALUE_GET_INT(op1);\n                    if (unlikely(val == INT32_MIN))\n                        goto dec_slow;\n                    sp[-1] = JS_NewInt32(ctx, val - 1);\n                } else {\n                dec_slow:\n                    if (js_unary_arith_slow(ctx, sp, opcode))\n                        goto exception;\n                }\n            }\n            BREAK;\n        CASE(OP_post_inc):\n        CASE(OP_post_dec):\n            if (js_post_inc_slow(ctx, sp, opcode))\n                goto exception;\n            sp++;\n            BREAK;\n        CASE(OP_inc_loc):\n            {\n                JSValue op1;\n                int val;\n                int idx;\n                idx = *pc;\n                pc += 1;\n\n                op1 = var_buf[idx];\n                if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) {\n                    val = JS_VALUE_GET_INT(op1);\n                    if (unlikely(val == INT32_MAX))\n                        goto inc_loc_slow;\n                    var_buf[idx] = JS_NewInt32(ctx, val + 1);\n                } else {\n                inc_loc_slow:\n                    /* must duplicate otherwise the variable value may\n                       be destroyed before JS code accesses it */\n                    op1 = JS_DupValue(ctx, op1);\n                    if (js_unary_arith_slow(ctx, &op1 + 1, OP_inc))\n                        goto exception;\n                    set_value(ctx, &var_buf[idx], op1);\n                }\n            }\n            BREAK;\n        CASE(OP_dec_loc):\n            {\n                JSValue op1;\n                int val;\n                int idx;\n                idx = *pc;\n                pc += 1;\n\n                op1 = var_buf[idx];\n                if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) {\n                    val = JS_VALUE_GET_INT(op1);\n                    if (unlikely(val == INT32_MIN))\n                        goto dec_loc_slow;\n                    var_buf[idx] = JS_NewInt32(ctx, val - 1);\n                } else {\n                dec_loc_slow:\n                    /* must duplicate otherwise the variable value may\n                       be destroyed before JS code accesses it */\n                    op1 = JS_DupValue(ctx, op1);\n                    if (js_unary_arith_slow(ctx, &op1 + 1, OP_dec))\n                        goto exception;\n                    set_value(ctx, &var_buf[idx], op1);\n                }\n            }\n            BREAK;\n        CASE(OP_not):\n            {\n                JSValue op1;\n                op1 = sp[-1];\n                if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) {\n                    sp[-1] = JS_NewInt32(ctx, ~JS_VALUE_GET_INT(op1));\n                } else {\n                    if (js_not_slow(ctx, sp))\n                        goto exception;\n                }\n            }\n            BREAK;\n\n        CASE(OP_shl):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    uint32_t v1, v2;\n                    v1 = JS_VALUE_GET_INT(op1);\n                    v2 = JS_VALUE_GET_INT(op2);\n#ifdef CONFIG_BIGNUM\n                    {\n                        int64_t r;\n                        if (unlikely(sf->js_mode & JS_MODE_MATH)) {\n                            if (v2 > 0x1f)\n                                goto shl_slow;\n                            r = (int64_t)v1 << v2;\n                            if ((int)r != r)\n                                goto shl_slow;\n                        } else {\n                            v2 &= 0x1f;\n                        }\n                    }\n#else\n                    v2 &= 0x1f;\n#endif\n                    sp[-2] = JS_NewInt32(ctx, v1 << v2);\n                    sp--;\n                } else {\n#ifdef CONFIG_BIGNUM\n                shl_slow:\n#endif\n                    if (js_binary_logic_slow(ctx, sp, opcode))\n                        goto exception;\n                    sp--;\n                }\n            }\n            BREAK;\n        CASE(OP_shr):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    uint32_t v2;\n                    v2 = JS_VALUE_GET_INT(op2);\n                    /* v1 >>> v2 retains its JS semantics if CONFIG_BIGNUM */\n                    v2 &= 0x1f;\n                    sp[-2] = JS_NewUint32(ctx,\n                                          (uint32_t)JS_VALUE_GET_INT(op1) >>\n                                          v2);\n                    sp--;\n                } else {\n                    if (js_shr_slow(ctx, sp))\n                        goto exception;\n                    sp--;\n                }\n            }\n            BREAK;\n        CASE(OP_sar):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    uint32_t v2;\n                    v2 = JS_VALUE_GET_INT(op2);\n#ifdef CONFIG_BIGNUM\n                    if (unlikely(v2 > 0x1f)) {\n                        if (unlikely(sf->js_mode & JS_MODE_MATH))\n                            goto sar_slow;\n                        else\n                            v2 &= 0x1f;\n                    }\n#else\n                    v2 &= 0x1f;\n#endif\n                    sp[-2] = JS_NewInt32(ctx,\n                                          (int)JS_VALUE_GET_INT(op1) >> v2);\n                    sp--;\n                } else {\n#ifdef CONFIG_BIGNUM\n                sar_slow:\n#endif\n                    if (js_binary_logic_slow(ctx, sp, opcode))\n                        goto exception;\n                    sp--;\n                }\n            }\n            BREAK;\n        CASE(OP_and):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    sp[-2] = JS_NewInt32(ctx,\n                                         JS_VALUE_GET_INT(op1) &\n                                         JS_VALUE_GET_INT(op2));\n                    sp--;\n                } else {\n                    if (js_binary_logic_slow(ctx, sp, opcode))\n                        goto exception;\n                    sp--;\n                }\n            }\n            BREAK;\n        CASE(OP_or):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    sp[-2] = JS_NewInt32(ctx,\n                                         JS_VALUE_GET_INT(op1) |\n                                         JS_VALUE_GET_INT(op2));\n                    sp--;\n                } else {\n                    if (js_binary_logic_slow(ctx, sp, opcode))\n                        goto exception;\n                    sp--;\n                }\n            }\n            BREAK;\n        CASE(OP_xor):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    sp[-2] = JS_NewInt32(ctx,\n                                         JS_VALUE_GET_INT(op1) ^\n                                         JS_VALUE_GET_INT(op2));\n                    sp--;\n                } else {\n                    if (js_binary_logic_slow(ctx, sp, opcode))\n                        goto exception;\n                    sp--;\n                }\n            }\n            BREAK;\n\n\n#define OP_CMP(opcode, binary_op, slow_call)              \\\n            CASE(opcode):                                 \\\n                {                                         \\\n                JSValue op1, op2;                         \\\n                op1 = sp[-2];                             \\\n                op2 = sp[-1];                                   \\\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {           \\\n                    sp[-2] = JS_NewBool(ctx, JS_VALUE_GET_INT(op1) binary_op JS_VALUE_GET_INT(op2)); \\\n                    sp--;                                               \\\n                } else {                                                \\\n                    if (slow_call)                                      \\\n                        goto exception;                                 \\\n                    sp--;                                               \\\n                }                                                       \\\n                }                                                       \\\n            BREAK\n\n            OP_CMP(OP_lt, <, js_relational_slow(ctx, sp, opcode));\n            OP_CMP(OP_lte, <=, js_relational_slow(ctx, sp, opcode));\n            OP_CMP(OP_gt, >, js_relational_slow(ctx, sp, opcode));\n            OP_CMP(OP_gte, >=, js_relational_slow(ctx, sp, opcode));\n            OP_CMP(OP_eq, ==, js_eq_slow(ctx, sp, 0));\n            OP_CMP(OP_neq, !=, js_eq_slow(ctx, sp, 1));\n            OP_CMP(OP_strict_eq, ==, js_strict_eq_slow(ctx, sp, 0));\n            OP_CMP(OP_strict_neq, !=, js_strict_eq_slow(ctx, sp, 1));\n\n#ifdef CONFIG_BIGNUM\n        CASE(OP_mul_pow10):\n            if (rt->bigfloat_ops.mul_pow10(ctx, sp))\n                goto exception;\n            sp--;\n            BREAK;\n#endif\n        CASE(OP_in):\n            if (js_operator_in(ctx, sp))\n                goto exception;\n            sp--;\n            BREAK;\n        CASE(OP_instanceof):\n            if (js_operator_instanceof(ctx, sp))\n                goto exception;\n            sp--;\n            BREAK;\n        CASE(OP_typeof):\n            {\n                JSValue op1;\n                JSAtom atom;\n\n                op1 = sp[-1];\n                atom = js_operator_typeof(ctx, op1);\n                JS_FreeValue(ctx, op1);\n                sp[-1] = JS_AtomToString(ctx, atom);\n            }\n            BREAK;\n        CASE(OP_delete):\n            if (js_operator_delete(ctx, sp))\n                goto exception;\n            sp--;\n            BREAK;\n        CASE(OP_delete_var):\n            {\n                JSAtom atom;\n                int ret;\n\n                atom = get_u32(pc);\n                pc += 4;\n\n                ret = JS_DeleteProperty(ctx, ctx->global_obj, atom, 0);\n                if (unlikely(ret < 0))\n                    goto exception;\n                *sp++ = JS_NewBool(ctx, ret);\n            }\n            BREAK;\n\n        CASE(OP_to_object):\n            if (JS_VALUE_GET_TAG(sp[-1]) != JS_TAG_OBJECT) {\n                ret_val = JS_ToObject(ctx, sp[-1]);\n                if (JS_IsException(ret_val))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = ret_val;\n            }\n            BREAK;\n\n        CASE(OP_to_propkey):\n            switch (JS_VALUE_GET_TAG(sp[-1])) {\n            case JS_TAG_INT:\n            case JS_TAG_STRING:\n            case JS_TAG_SYMBOL:\n                break;\n            default:\n                ret_val = JS_ToPropertyKey(ctx, sp[-1]);\n                if (JS_IsException(ret_val))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = ret_val;\n                break;\n            }\n            BREAK;\n\n        CASE(OP_to_propkey2):\n            /* must be tested first */\n            if (unlikely(JS_IsUndefined(sp[-2]) || JS_IsNull(sp[-2]))) {\n                JS_ThrowTypeError(ctx, \"value has no property\");\n                goto exception;\n            }\n            switch (JS_VALUE_GET_TAG(sp[-1])) {\n            case JS_TAG_INT:\n            case JS_TAG_STRING:\n            case JS_TAG_SYMBOL:\n                break;\n            default:\n                ret_val = JS_ToPropertyKey(ctx, sp[-1]);\n                if (JS_IsException(ret_val))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = ret_val;\n                break;\n            }\n            BREAK;\n#if 0\n        CASE(OP_to_string):\n            if (JS_VALUE_GET_TAG(sp[-1]) != JS_TAG_STRING) {\n                ret_val = JS_ToString(ctx, sp[-1]);\n                if (JS_IsException(ret_val))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = ret_val;\n            }\n            BREAK;\n#endif\n        CASE(OP_with_get_var):\n        CASE(OP_with_put_var):\n        CASE(OP_with_delete_var):\n        CASE(OP_with_make_ref):\n        CASE(OP_with_get_ref):\n        CASE(OP_with_get_ref_undef):\n            {\n                JSAtom atom;\n                int32_t diff;\n                JSValue obj, val;\n                int ret, is_with;\n                atom = get_u32(pc);\n                diff = get_u32(pc + 4);\n                is_with = pc[8];\n                pc += 9;\n\n                obj = sp[-1];\n                ret = JS_HasProperty(ctx, obj, atom);\n                if (unlikely(ret < 0))\n                    goto exception;\n                if (ret) {\n                    if (is_with) {\n                        ret = js_has_unscopable(ctx, obj, atom);\n                        if (unlikely(ret < 0))\n                            goto exception;\n                        if (ret)\n                            goto no_with;\n                    }\n                    switch (opcode) {\n                    case OP_with_get_var:\n                        val = JS_GetProperty(ctx, obj, atom);\n                        if (unlikely(JS_IsException(val)))\n                            goto exception;\n                        set_value(ctx, &sp[-1], val);\n                        break;\n                    case OP_with_put_var:\n                        /* XXX: check if strict mode */\n                        ret = JS_SetPropertyInternal(ctx, obj, atom, sp[-2],\n                                                     JS_PROP_THROW_STRICT);\n                        JS_FreeValue(ctx, sp[-1]);\n                        sp -= 2;\n                        if (unlikely(ret < 0))\n                            goto exception;\n                        break;\n                    case OP_with_delete_var:\n                        ret = JS_DeleteProperty(ctx, obj, atom, 0);\n                        if (unlikely(ret < 0))\n                            goto exception;\n                        JS_FreeValue(ctx, sp[-1]);\n                        sp[-1] = JS_NewBool(ctx, ret);\n                        break;\n                    case OP_with_make_ref:\n                        /* produce a pair object/propname on the stack */\n                        *sp++ = JS_AtomToValue(ctx, atom);\n                        break;\n                    case OP_with_get_ref:\n                        /* produce a pair object/method on the stack */\n                        val = JS_GetProperty(ctx, obj, atom);\n                        if (unlikely(JS_IsException(val)))\n                            goto exception;\n                        *sp++ = val;\n                        break;\n                    case OP_with_get_ref_undef:\n                        /* produce a pair undefined/function on the stack */\n                        val = JS_GetProperty(ctx, obj, atom);\n                        if (unlikely(JS_IsException(val)))\n                            goto exception;\n                        JS_FreeValue(ctx, sp[-1]);\n                        sp[-1] = JS_UNDEFINED;\n                        *sp++ = val;\n                        break;\n                    }\n                    pc += diff - 5;\n                } else {\n                no_with:\n                    /* if not jumping, drop the object argument */\n                    JS_FreeValue(ctx, sp[-1]);\n                    sp--;\n                }\n            }\n            BREAK;\n\n        CASE(OP_await):\n            ret_val = JS_NewInt32(ctx, FUNC_RET_AWAIT);\n            goto done_generator;\n        CASE(OP_yield):\n            ret_val = JS_NewInt32(ctx, FUNC_RET_YIELD);\n            goto done_generator;\n        CASE(OP_yield_star):\n        CASE(OP_async_yield_star):\n            ret_val = JS_NewInt32(ctx, FUNC_RET_YIELD_STAR);\n            goto done_generator;\n        CASE(OP_return_async):\n        CASE(OP_initial_yield):\n            ret_val = JS_UNDEFINED;\n            goto done_generator;\n\n        CASE(OP_nop):\n            BREAK;\n        CASE(OP_is_undefined_or_null):\n            if (JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_UNDEFINED ||\n                JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_NULL) {\n                goto set_true;\n            } else {\n                goto free_and_set_false;\n            }\n#if SHORT_OPCODES\n        CASE(OP_is_undefined):\n            if (JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_UNDEFINED) {\n                goto set_true;\n            } else {\n                goto free_and_set_false;\n            }\n        CASE(OP_is_null):\n            if (JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_NULL) {\n                goto set_true;\n            } else {\n                goto free_and_set_false;\n            }\n            /* XXX: could merge to a single opcode */\n        CASE(OP_typeof_is_undefined):\n            /* different from OP_is_undefined because of isHTMLDDA */\n            if (js_operator_typeof(ctx, sp[-1]) == JS_ATOM_undefined) {\n                goto free_and_set_true;\n            } else {\n                goto free_and_set_false;\n            }\n        CASE(OP_typeof_is_function):\n            if (js_operator_typeof(ctx, sp[-1]) == JS_ATOM_function) {\n                goto free_and_set_true;\n            } else {\n                goto free_and_set_false;\n            }\n        free_and_set_true:\n            JS_FreeValue(ctx, sp[-1]);\n#endif\n        set_true:\n            sp[-1] = JS_TRUE;\n            BREAK;\n        free_and_set_false:\n            JS_FreeValue(ctx, sp[-1]);\n            sp[-1] = JS_FALSE;\n            BREAK;\n        CASE(OP_invalid):\n        DEFAULT:\n            JS_ThrowInternalError(ctx, \"invalid opcode: pc=%u opcode=0x%02x\",\n                                  (int)(pc - b->byte_code_buf - 1), opcode);\n            goto exception;\n        }\n    }\n exception:\n    if (is_backtrace_needed(ctx, rt->current_exception)) {\n        /* add the backtrace information now (it is not done\n           before if the exception happens in a bytecode\n           operation */\n        sf->cur_pc = pc;\n        build_backtrace(ctx, rt->current_exception, NULL, 0, 0);\n    }\n    if (!JS_IsUncatchableError(ctx, rt->current_exception)) {\n        while (sp > stack_buf) {\n            JSValue val = *--sp;\n            JS_FreeValue(ctx, val);\n            if (JS_VALUE_GET_TAG(val) == JS_TAG_CATCH_OFFSET) {\n                int pos = JS_VALUE_GET_INT(val);\n                if (pos == 0) {\n                    /* enumerator: close it with a throw */\n                    JS_FreeValue(ctx, sp[-1]); /* drop the next method */\n                    sp--;\n                    JS_IteratorClose(ctx, sp[-1], TRUE);\n                } else {\n                    *sp++ = rt->current_exception;\n                    rt->current_exception = JS_NULL;\n                    pc = b->byte_code_buf + pos;\n                    goto restart;\n                }\n            }\n        }\n    }\n    ret_val = JS_EXCEPTION;\n    /* the local variables are freed by the caller in the generator\n       case. Hence the label 'done' should never be reached in a\n       generator function. */\n    if (b->func_kind != JS_FUNC_NORMAL) {\n    done_generator:\n        sf->cur_pc = pc;\n        sf->cur_sp = sp;\n    } else {\n    done:\n        if (unlikely(!list_empty(&sf->var_ref_list))) {\n            /* variable references reference the stack: must close them */\n            close_var_refs(rt, sf);\n        }\n        /* free the local variables and stack */\n        for(pval = local_buf; pval < sp; pval++) {\n            JS_FreeValue(ctx, *pval);\n        }\n    }\n    rt->current_stack_frame = sf->prev_frame;\n    return ret_val;\n}\n\nJSValue JS_Call(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj,\n                int argc, JSValueConst *argv)\n{\n    return JS_CallInternal(ctx, func_obj, this_obj, JS_UNDEFINED,\n                           argc, (JSValue *)argv, JS_CALL_FLAG_COPY_ARGV);\n}\n\nstatic JSValue JS_CallFree(JSContext *ctx, JSValue func_obj, JSValueConst this_obj,\n                           int argc, JSValueConst *argv)\n{\n    JSValue res = JS_CallInternal(ctx, func_obj, this_obj, JS_UNDEFINED,\n                                  argc, (JSValue *)argv, JS_CALL_FLAG_COPY_ARGV);\n    JS_FreeValue(ctx, func_obj);\n    return res;\n}\n\n/* warning: the refcount of the context is not incremented. Return\n   NULL in case of exception (case of revoked proxy only) */\nstatic JSContext *JS_GetFunctionRealm(JSContext *ctx, JSValueConst func_obj)\n{\n    JSObject *p;\n    JSContext *realm;\n    \n    if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT)\n        return ctx;\n    p = JS_VALUE_GET_OBJ(func_obj);\n    switch(p->class_id) {\n    case JS_CLASS_C_FUNCTION:\n        realm = p->u.cfunc.realm;\n        break;\n    case JS_CLASS_BYTECODE_FUNCTION:\n    case JS_CLASS_GENERATOR_FUNCTION:\n    case JS_CLASS_ASYNC_FUNCTION:\n    case JS_CLASS_ASYNC_GENERATOR_FUNCTION:\n        {\n            JSFunctionBytecode *b;\n            b = p->u.func.function_bytecode;\n            realm = b->realm;\n        }\n        break;\n    case JS_CLASS_PROXY:\n        {\n            JSProxyData *s = p->u.opaque;\n            if (!s)\n                return ctx;\n            if (s->is_revoked) {\n                JS_ThrowTypeErrorRevokedProxy(ctx);\n                return NULL;\n            } else {\n                realm = JS_GetFunctionRealm(ctx, s->target);\n            }\n        }\n        break;\n    case JS_CLASS_BOUND_FUNCTION:\n        {\n            JSBoundFunction *bf = p->u.bound_function;\n            realm = JS_GetFunctionRealm(ctx, bf->func_obj);\n        }\n        break;\n    default:\n        realm = ctx;\n        break;\n    }\n    return realm;\n}\n\nstatic JSValue js_create_from_ctor(JSContext *ctx, JSValueConst ctor,\n                                   int class_id)\n{\n    JSValue proto, obj;\n    JSContext *realm;\n    \n    if (JS_IsUndefined(ctor)) {\n        proto = JS_DupValue(ctx, ctx->class_proto[class_id]);\n    } else {\n        proto = JS_GetProperty(ctx, ctor, JS_ATOM_prototype);\n        if (JS_IsException(proto))\n            return proto;\n        if (!JS_IsObject(proto)) {\n            JS_FreeValue(ctx, proto);\n            realm = JS_GetFunctionRealm(ctx, ctor);\n            if (!realm)\n                return JS_EXCEPTION;\n            proto = JS_DupValue(ctx, realm->class_proto[class_id]);\n        }\n    }\n    obj = JS_NewObjectProtoClass(ctx, proto, class_id);\n    JS_FreeValue(ctx, proto);\n    return obj;\n}\n\n/* argv[] is modified if (flags & JS_CALL_FLAG_COPY_ARGV) = 0. */\nstatic JSValue JS_CallConstructorInternal(JSContext *ctx,\n                                          JSValueConst func_obj,\n                                          JSValueConst new_target,\n                                          int argc, JSValue *argv, int flags)\n{\n    JSObject *p;\n    JSFunctionBytecode *b;\n\n    if (js_poll_interrupts(ctx))\n        return JS_EXCEPTION;\n    flags |= JS_CALL_FLAG_CONSTRUCTOR;\n    if (unlikely(JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT))\n        goto not_a_function;\n    p = JS_VALUE_GET_OBJ(func_obj);\n    if (unlikely(!p->is_constructor))\n        return JS_ThrowTypeError(ctx, \"not a constructor\");\n    if (unlikely(p->class_id != JS_CLASS_BYTECODE_FUNCTION)) {\n        JSClassCall *call_func;\n        call_func = ctx->rt->class_array[p->class_id].call;\n        if (!call_func) {\n        not_a_function:\n            return JS_ThrowTypeError(ctx, \"not a function\");\n        }\n        return call_func(ctx, func_obj, new_target, argc,\n                         (JSValueConst *)argv, flags);\n    }\n\n    b = p->u.func.function_bytecode;\n    if (b->is_derived_class_constructor) {\n        return JS_CallInternal(ctx, func_obj, JS_UNDEFINED, new_target, argc, argv, flags);\n    } else {\n        JSValue obj, ret;\n        /* legacy constructor behavior */\n        obj = js_create_from_ctor(ctx, new_target, JS_CLASS_OBJECT);\n        if (JS_IsException(obj))\n            return JS_EXCEPTION;\n        ret = JS_CallInternal(ctx, func_obj, obj, new_target, argc, argv, flags);\n        if (JS_VALUE_GET_TAG(ret) == JS_TAG_OBJECT ||\n            JS_IsException(ret)) {\n            JS_FreeValue(ctx, obj);\n            return ret;\n        } else {\n            JS_FreeValue(ctx, ret);\n            return obj;\n        }\n    }\n}\n\nJSValue JS_CallConstructor2(JSContext *ctx, JSValueConst func_obj,\n                            JSValueConst new_target,\n                            int argc, JSValueConst *argv)\n{\n    return JS_CallConstructorInternal(ctx, func_obj, new_target,\n                                      argc, (JSValue *)argv,\n                                      JS_CALL_FLAG_COPY_ARGV);\n}\n\nJSValue JS_CallConstructor(JSContext *ctx, JSValueConst func_obj,\n                           int argc, JSValueConst *argv)\n{\n    return JS_CallConstructorInternal(ctx, func_obj, func_obj,\n                                      argc, (JSValue *)argv,\n                                      JS_CALL_FLAG_COPY_ARGV);\n}\n\nJSValue JS_Invoke(JSContext *ctx, JSValueConst this_val, JSAtom atom,\n                  int argc, JSValueConst *argv)\n{\n    JSValue func_obj;\n    func_obj = JS_GetProperty(ctx, this_val, atom);\n    if (JS_IsException(func_obj))\n        return func_obj;\n    return JS_CallFree(ctx, func_obj, this_val, argc, argv);\n}\n\nstatic JSValue JS_InvokeFree(JSContext *ctx, JSValue this_val, JSAtom atom,\n                             int argc, JSValueConst *argv)\n{\n    JSValue res = JS_Invoke(ctx, this_val, atom, argc, argv);\n    JS_FreeValue(ctx, this_val);\n    return res;\n}\n\n/* JSAsyncFunctionState (used by generator and async functions) */\nstatic __exception int async_func_init(JSContext *ctx, JSAsyncFunctionState *s,\n                                       JSValueConst func_obj, JSValueConst this_obj,\n                                       int argc, JSValueConst *argv)\n{\n    JSObject *p;\n    JSFunctionBytecode *b;\n    JSStackFrame *sf;\n    int local_count, i, arg_buf_len, n;\n\n    sf = &s->frame;\n    init_list_head(&sf->var_ref_list);\n    p = JS_VALUE_GET_OBJ(func_obj);\n    b = p->u.func.function_bytecode;\n    sf->js_mode = b->js_mode;\n    sf->cur_pc = b->byte_code_buf;\n    arg_buf_len = max_int(b->arg_count, argc);\n    local_count = arg_buf_len + b->var_count + b->stack_size;\n    sf->arg_buf = js_malloc(ctx, sizeof(JSValue) * max_int(local_count, 1));\n    if (!sf->arg_buf)\n        return -1;\n    sf->cur_func = JS_DupValue(ctx, func_obj);\n    s->this_val = JS_DupValue(ctx, this_obj);\n    s->argc = argc;\n    sf->arg_count = arg_buf_len;\n    sf->var_buf = sf->arg_buf + arg_buf_len;\n    sf->cur_sp = sf->var_buf + b->var_count;\n    for(i = 0; i < argc; i++)\n        sf->arg_buf[i] = JS_DupValue(ctx, argv[i]);\n    n = arg_buf_len + b->var_count;\n    for(i = argc; i < n; i++)\n        sf->arg_buf[i] = JS_UNDEFINED;\n    return 0;\n}\n\nstatic void async_func_mark(JSRuntime *rt, JSAsyncFunctionState *s,\n                            JS_MarkFunc *mark_func)\n{\n    JSStackFrame *sf;\n    JSValue *sp;\n\n    sf = &s->frame;\n    JS_MarkValue(rt, sf->cur_func, mark_func);\n    JS_MarkValue(rt, s->this_val, mark_func);\n    if (sf->cur_sp) {\n        /* if the function is running, cur_sp is not known so we\n           cannot mark the stack. Marking the variables is not needed\n           because a running function cannot be part of a removable\n           cycle */\n        for(sp = sf->arg_buf; sp < sf->cur_sp; sp++)\n            JS_MarkValue(rt, *sp, mark_func);\n    }\n}\n\nstatic void async_func_free(JSRuntime *rt, JSAsyncFunctionState *s)\n{\n    JSStackFrame *sf;\n    JSValue *sp;\n\n    sf = &s->frame;\n\n    /* close the closure variables. */\n    close_var_refs(rt, sf);\n    \n    if (sf->arg_buf) {\n        /* cannot free the function if it is running */\n        assert(sf->cur_sp != NULL);\n        for(sp = sf->arg_buf; sp < sf->cur_sp; sp++) {\n            JS_FreeValueRT(rt, *sp);\n        }\n        js_free_rt(rt, sf->arg_buf);\n    }\n    JS_FreeValueRT(rt, sf->cur_func);\n    JS_FreeValueRT(rt, s->this_val);\n}\n\nstatic JSValue async_func_resume(JSContext *ctx, JSAsyncFunctionState *s)\n{\n    JSValue func_obj;\n\n    if (js_check_stack_overflow(ctx->rt, 0))\n        return JS_ThrowStackOverflow(ctx);\n\n    /* the tag does not matter provided it is not an object */\n    func_obj = JS_MKPTR(JS_TAG_INT, s);\n    return JS_CallInternal(ctx, func_obj, s->this_val, JS_UNDEFINED,\n                           s->argc, s->frame.arg_buf, JS_CALL_FLAG_GENERATOR);\n}\n\n\n/* Generators */\n\ntypedef enum JSGeneratorStateEnum {\n    JS_GENERATOR_STATE_SUSPENDED_START,\n    JS_GENERATOR_STATE_SUSPENDED_YIELD,\n    JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR,\n    JS_GENERATOR_STATE_EXECUTING,\n    JS_GENERATOR_STATE_COMPLETED,\n} JSGeneratorStateEnum;\n\ntypedef struct JSGeneratorData {\n    JSGeneratorStateEnum state;\n    JSAsyncFunctionState func_state;\n} JSGeneratorData;\n\nstatic void free_generator_stack_rt(JSRuntime *rt, JSGeneratorData *s)\n{\n    if (s->state == JS_GENERATOR_STATE_COMPLETED)\n        return;\n    async_func_free(rt, &s->func_state);\n    s->state = JS_GENERATOR_STATE_COMPLETED;\n}\n\nstatic void js_generator_finalizer(JSRuntime *rt, JSValue obj)\n{\n    JSGeneratorData *s = JS_GetOpaque(obj, JS_CLASS_GENERATOR);\n\n    if (s) {\n        free_generator_stack_rt(rt, s);\n        js_free_rt(rt, s);\n    }\n}\n\nstatic void free_generator_stack(JSContext *ctx, JSGeneratorData *s)\n{\n    free_generator_stack_rt(ctx->rt, s);\n}\n\nstatic void js_generator_mark(JSRuntime *rt, JSValueConst val,\n                              JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSGeneratorData *s = p->u.generator_data;\n\n    if (!s || s->state == JS_GENERATOR_STATE_COMPLETED)\n        return;\n    async_func_mark(rt, &s->func_state, mark_func);\n}\n\n/* XXX: use enum */\n#define GEN_MAGIC_NEXT   0\n#define GEN_MAGIC_RETURN 1\n#define GEN_MAGIC_THROW  2\n\nstatic JSValue js_generator_next(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv,\n                                 BOOL *pdone, int magic)\n{\n    JSGeneratorData *s = JS_GetOpaque(this_val, JS_CLASS_GENERATOR);\n    JSStackFrame *sf;\n    JSValue ret, func_ret;\n\n    *pdone = TRUE;\n    if (!s)\n        return JS_ThrowTypeError(ctx, \"not a generator\");\n    sf = &s->func_state.frame;\n    switch(s->state) {\n    default:\n    case JS_GENERATOR_STATE_SUSPENDED_START:\n        if (magic == GEN_MAGIC_NEXT) {\n            goto exec_no_arg;\n        } else {\n            free_generator_stack(ctx, s);\n            goto done;\n        }\n        break;\n    case JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR:\n    case JS_GENERATOR_STATE_SUSPENDED_YIELD:\n        /* cur_sp[-1] was set to JS_UNDEFINED in the previous call */\n        ret = JS_DupValue(ctx, argv[0]);\n        if (magic == GEN_MAGIC_THROW &&\n            s->state == JS_GENERATOR_STATE_SUSPENDED_YIELD) {\n            JS_Throw(ctx, ret);\n            s->func_state.throw_flag = TRUE;\n        } else {\n            sf->cur_sp[-1] = ret;\n            sf->cur_sp[0] = JS_NewInt32(ctx, magic);\n            sf->cur_sp++;\n        exec_no_arg:\n            s->func_state.throw_flag = FALSE;\n        }\n        s->state = JS_GENERATOR_STATE_EXECUTING;\n        func_ret = async_func_resume(ctx, &s->func_state);\n        s->state = JS_GENERATOR_STATE_SUSPENDED_YIELD;\n        if (JS_IsException(func_ret)) {\n            /* finalize the execution in case of exception */\n            free_generator_stack(ctx, s);\n            return func_ret;\n        }\n        if (JS_VALUE_GET_TAG(func_ret) == JS_TAG_INT) {\n            /* get the returned yield value at the top of the stack */\n            ret = sf->cur_sp[-1];\n            sf->cur_sp[-1] = JS_UNDEFINED;\n            if (JS_VALUE_GET_INT(func_ret) == FUNC_RET_YIELD_STAR) {\n                s->state = JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR;\n                /* return (value, done) object */\n                *pdone = 2;\n            } else {\n                *pdone = FALSE;\n            }\n        } else {\n            /* end of iterator */\n            ret = sf->cur_sp[-1];\n            sf->cur_sp[-1] = JS_UNDEFINED;\n            JS_FreeValue(ctx, func_ret);\n            free_generator_stack(ctx, s);\n        }\n        break;\n    case JS_GENERATOR_STATE_COMPLETED:\n    done:\n        /* execution is finished */\n        switch(magic) {\n        default:\n        case GEN_MAGIC_NEXT:\n            ret = JS_UNDEFINED;\n            break;\n        case GEN_MAGIC_RETURN:\n            ret = JS_DupValue(ctx, argv[0]);\n            break;\n        case GEN_MAGIC_THROW:\n            ret = JS_Throw(ctx, JS_DupValue(ctx, argv[0]));\n            break;\n        }\n        break;\n    case JS_GENERATOR_STATE_EXECUTING:\n        ret = JS_ThrowTypeError(ctx, \"cannot invoke a running generator\");\n        break;\n    }\n    return ret;\n}\n\nstatic JSValue js_generator_function_call(JSContext *ctx, JSValueConst func_obj,\n                                          JSValueConst this_obj,\n                                          int argc, JSValueConst *argv,\n                                          int flags)\n{\n    JSValue obj, func_ret;\n    JSGeneratorData *s;\n\n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s)\n        return JS_EXCEPTION;\n    s->state = JS_GENERATOR_STATE_SUSPENDED_START;\n    if (async_func_init(ctx, &s->func_state, func_obj, this_obj, argc, argv)) {\n        s->state = JS_GENERATOR_STATE_COMPLETED;\n        goto fail;\n    }\n\n    /* execute the function up to 'OP_initial_yield' */\n    func_ret = async_func_resume(ctx, &s->func_state);\n    if (JS_IsException(func_ret))\n        goto fail;\n    JS_FreeValue(ctx, func_ret);\n\n    obj = js_create_from_ctor(ctx, func_obj, JS_CLASS_GENERATOR);\n    if (JS_IsException(obj))\n        goto fail;\n    JS_SetOpaque(obj, s);\n    return obj;\n fail:\n    free_generator_stack_rt(ctx->rt, s);\n    js_free(ctx, s);\n    return JS_EXCEPTION;\n}\n\n/* AsyncFunction */\n\nstatic void js_async_function_terminate(JSRuntime *rt, JSAsyncFunctionData *s)\n{\n    if (s->is_active) {\n        async_func_free(rt, &s->func_state);\n        s->is_active = FALSE;\n    }\n}\n\nstatic void js_async_function_free0(JSRuntime *rt, JSAsyncFunctionData *s)\n{\n    js_async_function_terminate(rt, s);\n    JS_FreeValueRT(rt, s->resolving_funcs[0]);\n    JS_FreeValueRT(rt, s->resolving_funcs[1]);\n    remove_gc_object(&s->header);\n    js_free_rt(rt, s);\n}\n\nstatic void js_async_function_free(JSRuntime *rt, JSAsyncFunctionData *s)\n{\n    if (--s->header.ref_count == 0) {\n        js_async_function_free0(rt, s);\n    }\n}\n\nstatic void js_async_function_resolve_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSAsyncFunctionData *s = p->u.async_function_data;\n    if (s) {\n        js_async_function_free(rt, s);\n    }\n}\n\nstatic void js_async_function_resolve_mark(JSRuntime *rt, JSValueConst val,\n                                           JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSAsyncFunctionData *s = p->u.async_function_data;\n    if (s) {\n        mark_func(rt, &s->header);\n    }\n}\n\nstatic int js_async_function_resolve_create(JSContext *ctx,\n                                            JSAsyncFunctionData *s,\n                                            JSValue *resolving_funcs)\n{\n    int i;\n    JSObject *p;\n\n    for(i = 0; i < 2; i++) {\n        resolving_funcs[i] =\n            JS_NewObjectProtoClass(ctx, ctx->function_proto,\n                                   JS_CLASS_ASYNC_FUNCTION_RESOLVE + i);\n        if (JS_IsException(resolving_funcs[i])) {\n            if (i == 1)\n                JS_FreeValue(ctx, resolving_funcs[0]);\n            return -1;\n        }\n        p = JS_VALUE_GET_OBJ(resolving_funcs[i]);\n        s->header.ref_count++;\n        p->u.async_function_data = s;\n    }\n    return 0;\n}\n\nstatic void js_async_function_resume(JSContext *ctx, JSAsyncFunctionData *s)\n{\n    JSValue func_ret, ret2;\n\n    func_ret = async_func_resume(ctx, &s->func_state);\n    if (JS_IsException(func_ret)) {\n        JSValue error;\n    fail:\n        error = JS_GetException(ctx);\n        ret2 = JS_Call(ctx, s->resolving_funcs[1], JS_UNDEFINED,\n                       1, (JSValueConst *)&error);\n        JS_FreeValue(ctx, error);\n        js_async_function_terminate(ctx->rt, s);\n        JS_FreeValue(ctx, ret2); /* XXX: what to do if exception ? */\n    } else {\n        JSValue value;\n        value = s->func_state.frame.cur_sp[-1];\n        s->func_state.frame.cur_sp[-1] = JS_UNDEFINED;\n        if (JS_IsUndefined(func_ret)) {\n            /* function returned */\n            ret2 = JS_Call(ctx, s->resolving_funcs[0], JS_UNDEFINED,\n                           1, (JSValueConst *)&value);\n            JS_FreeValue(ctx, ret2); /* XXX: what to do if exception ? */\n            JS_FreeValue(ctx, value);\n            js_async_function_terminate(ctx->rt, s);\n        } else {\n            JSValue promise, resolving_funcs[2], resolving_funcs1[2];\n            int i, res;\n\n            /* await */\n            JS_FreeValue(ctx, func_ret); /* not used */\n            promise = js_promise_resolve(ctx, ctx->promise_ctor,\n                                         1, (JSValueConst *)&value, 0);\n            JS_FreeValue(ctx, value);\n            if (JS_IsException(promise))\n                goto fail;\n            if (js_async_function_resolve_create(ctx, s, resolving_funcs)) {\n                JS_FreeValue(ctx, promise);\n                goto fail;\n            }\n\n            /* Note: no need to create 'thrownawayCapability' as in\n               the spec */\n            for(i = 0; i < 2; i++)\n                resolving_funcs1[i] = JS_UNDEFINED;\n            res = perform_promise_then(ctx, promise,\n                                       (JSValueConst *)resolving_funcs,\n                                       (JSValueConst *)resolving_funcs1);\n            JS_FreeValue(ctx, promise);\n            for(i = 0; i < 2; i++)\n                JS_FreeValue(ctx, resolving_funcs[i]);\n            if (res)\n                goto fail;\n        }\n    }\n}\n\nstatic JSValue js_async_function_resolve_call(JSContext *ctx,\n                                              JSValueConst func_obj,\n                                              JSValueConst this_obj,\n                                              int argc, JSValueConst *argv,\n                                              int flags)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(func_obj);\n    JSAsyncFunctionData *s = p->u.async_function_data;\n    BOOL is_reject = p->class_id - JS_CLASS_ASYNC_FUNCTION_RESOLVE;\n    JSValueConst arg;\n\n    if (argc > 0)\n        arg = argv[0];\n    else\n        arg = JS_UNDEFINED;\n    s->func_state.throw_flag = is_reject;\n    if (is_reject) {\n        JS_Throw(ctx, JS_DupValue(ctx, arg));\n    } else {\n        /* return value of await */\n        s->func_state.frame.cur_sp[-1] = JS_DupValue(ctx, arg);\n    }\n    js_async_function_resume(ctx, s);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_async_function_call(JSContext *ctx, JSValueConst func_obj,\n                                      JSValueConst this_obj,\n                                      int argc, JSValueConst *argv, int flags)\n{\n    JSValue promise;\n    JSAsyncFunctionData *s;\n\n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s)\n        return JS_EXCEPTION;\n    s->header.ref_count = 1;\n    add_gc_object(ctx->rt, &s->header, JS_GC_OBJ_TYPE_ASYNC_FUNCTION);\n    s->is_active = FALSE;\n    s->resolving_funcs[0] = JS_UNDEFINED;\n    s->resolving_funcs[1] = JS_UNDEFINED;\n\n    promise = JS_NewPromiseCapability(ctx, s->resolving_funcs);\n    if (JS_IsException(promise))\n        goto fail;\n\n    if (async_func_init(ctx, &s->func_state, func_obj, this_obj, argc, argv)) {\n    fail:\n        JS_FreeValue(ctx, promise);\n        js_async_function_free(ctx->rt, s);\n        return JS_EXCEPTION;\n    }\n    s->is_active = TRUE;\n\n    js_async_function_resume(ctx, s);\n\n    js_async_function_free(ctx->rt, s);\n\n    return promise;\n}\n\n/* AsyncGenerator */\n\ntypedef enum JSAsyncGeneratorStateEnum {\n    JS_ASYNC_GENERATOR_STATE_SUSPENDED_START,\n    JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD,\n    JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD_STAR,\n    JS_ASYNC_GENERATOR_STATE_EXECUTING,\n    JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN,\n    JS_ASYNC_GENERATOR_STATE_COMPLETED,\n} JSAsyncGeneratorStateEnum;\n\ntypedef struct JSAsyncGeneratorRequest {\n    struct list_head link;\n    /* completion */\n    int completion_type; /* GEN_MAGIC_x */\n    JSValue result;\n    /* promise capability */\n    JSValue promise;\n    JSValue resolving_funcs[2];\n} JSAsyncGeneratorRequest;\n\ntypedef struct JSAsyncGeneratorData {\n    JSObject *generator; /* back pointer to the object (const) */\n    JSAsyncGeneratorStateEnum state;\n    JSAsyncFunctionState func_state;\n    struct list_head queue; /* list of JSAsyncGeneratorRequest.link */\n} JSAsyncGeneratorData;\n\nstatic void js_async_generator_free(JSRuntime *rt,\n                                    JSAsyncGeneratorData *s)\n{\n    struct list_head *el, *el1;\n    JSAsyncGeneratorRequest *req;\n\n    list_for_each_safe(el, el1, &s->queue) {\n        req = list_entry(el, JSAsyncGeneratorRequest, link);\n        JS_FreeValueRT(rt, req->result);\n        JS_FreeValueRT(rt, req->promise);\n        JS_FreeValueRT(rt, req->resolving_funcs[0]);\n        JS_FreeValueRT(rt, req->resolving_funcs[1]);\n        js_free_rt(rt, req);\n    }\n    if (s->state != JS_ASYNC_GENERATOR_STATE_COMPLETED &&\n        s->state != JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN) {\n        async_func_free(rt, &s->func_state);\n    }\n    js_free_rt(rt, s);\n}\n\nstatic void js_async_generator_finalizer(JSRuntime *rt, JSValue obj)\n{\n    JSAsyncGeneratorData *s = JS_GetOpaque(obj, JS_CLASS_ASYNC_GENERATOR);\n\n    if (s) {\n        js_async_generator_free(rt, s);\n    }\n}\n\nstatic void js_async_generator_mark(JSRuntime *rt, JSValueConst val,\n                                    JS_MarkFunc *mark_func)\n{\n    JSAsyncGeneratorData *s = JS_GetOpaque(val, JS_CLASS_ASYNC_GENERATOR);\n    struct list_head *el;\n    JSAsyncGeneratorRequest *req;\n    if (s) {\n        list_for_each(el, &s->queue) {\n            req = list_entry(el, JSAsyncGeneratorRequest, link);\n            JS_MarkValue(rt, req->result, mark_func);\n            JS_MarkValue(rt, req->promise, mark_func);\n            JS_MarkValue(rt, req->resolving_funcs[0], mark_func);\n            JS_MarkValue(rt, req->resolving_funcs[1], mark_func);\n        }\n        if (s->state != JS_ASYNC_GENERATOR_STATE_COMPLETED &&\n            s->state != JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN) {\n            async_func_mark(rt, &s->func_state, mark_func);\n        }\n    }\n}\n\nstatic JSValue js_async_generator_resolve_function(JSContext *ctx,\n                                          JSValueConst this_obj,\n                                          int argc, JSValueConst *argv,\n                                          int magic, JSValue *func_data);\n\nstatic int js_async_generator_resolve_function_create(JSContext *ctx,\n                                                      JSValueConst generator,\n                                                      JSValue *resolving_funcs,\n                                                      BOOL is_resume_next)\n{\n    int i;\n    JSValue func;\n\n    for(i = 0; i < 2; i++) {\n        func = JS_NewCFunctionData(ctx, js_async_generator_resolve_function, 1,\n                                   i + is_resume_next * 2, 1, &generator);\n        if (JS_IsException(func)) {\n            if (i == 1)\n                JS_FreeValue(ctx, resolving_funcs[0]);\n            return -1;\n        }\n        resolving_funcs[i] = func;\n    }\n    return 0;\n}\n\nstatic int js_async_generator_await(JSContext *ctx,\n                                    JSAsyncGeneratorData *s,\n                                    JSValueConst value)\n{\n    JSValue promise, resolving_funcs[2], resolving_funcs1[2];\n    int i, res;\n\n    promise = js_promise_resolve(ctx, ctx->promise_ctor,\n                                 1, &value, 0);\n    if (JS_IsException(promise))\n        goto fail;\n\n    if (js_async_generator_resolve_function_create(ctx, JS_MKPTR(JS_TAG_OBJECT, s->generator),\n                                                   resolving_funcs, FALSE)) {\n        JS_FreeValue(ctx, promise);\n        goto fail;\n    }\n\n    /* Note: no need to create 'thrownawayCapability' as in\n       the spec */\n    for(i = 0; i < 2; i++)\n        resolving_funcs1[i] = JS_UNDEFINED;\n    res = perform_promise_then(ctx, promise,\n                               (JSValueConst *)resolving_funcs,\n                               (JSValueConst *)resolving_funcs1);\n    JS_FreeValue(ctx, promise);\n    for(i = 0; i < 2; i++)\n        JS_FreeValue(ctx, resolving_funcs[i]);\n    if (res)\n        goto fail;\n    return 0;\n fail:\n    return -1;\n}\n\nstatic void js_async_generator_resolve_or_reject(JSContext *ctx,\n                                                 JSAsyncGeneratorData *s,\n                                                 JSValueConst result,\n                                                 int is_reject)\n{\n    JSAsyncGeneratorRequest *next;\n    JSValue ret;\n\n    next = list_entry(s->queue.next, JSAsyncGeneratorRequest, link);\n    list_del(&next->link);\n    ret = JS_Call(ctx, next->resolving_funcs[is_reject], JS_UNDEFINED, 1,\n                  &result);\n    JS_FreeValue(ctx, ret);\n    JS_FreeValue(ctx, next->result);\n    JS_FreeValue(ctx, next->promise);\n    JS_FreeValue(ctx, next->resolving_funcs[0]);\n    JS_FreeValue(ctx, next->resolving_funcs[1]);\n    js_free(ctx, next);\n}\n\nstatic void js_async_generator_resolve(JSContext *ctx,\n                                       JSAsyncGeneratorData *s,\n                                       JSValueConst value,\n                                       BOOL done)\n{\n    JSValue result;\n    result = js_create_iterator_result(ctx, JS_DupValue(ctx, value), done);\n    /* XXX: better exception handling ? */\n    js_async_generator_resolve_or_reject(ctx, s, result, 0);\n    JS_FreeValue(ctx, result);\n }\n\nstatic void js_async_generator_reject(JSContext *ctx,\n                                       JSAsyncGeneratorData *s,\n                                       JSValueConst exception)\n{\n    js_async_generator_resolve_or_reject(ctx, s, exception, 1);\n}\n\nstatic void js_async_generator_complete(JSContext *ctx,\n                                        JSAsyncGeneratorData *s)\n{\n    if (s->state != JS_ASYNC_GENERATOR_STATE_COMPLETED) {\n        s->state = JS_ASYNC_GENERATOR_STATE_COMPLETED;\n        async_func_free(ctx->rt, &s->func_state);\n    }\n}\n\nstatic int js_async_generator_completed_return(JSContext *ctx,\n                                               JSAsyncGeneratorData *s,\n                                               JSValueConst value)\n{\n    JSValue promise, resolving_funcs[2], resolving_funcs1[2];\n    int res;\n\n    promise = js_promise_resolve(ctx, ctx->promise_ctor,\n                                 1, (JSValueConst *)&value, 0);\n    if (JS_IsException(promise))\n        return -1;\n    if (js_async_generator_resolve_function_create(ctx,\n                                                   JS_MKPTR(JS_TAG_OBJECT, s->generator),\n                                                   resolving_funcs1,\n                                                   TRUE)) {\n        JS_FreeValue(ctx, promise);\n        return -1;\n    }\n    resolving_funcs[0] = JS_UNDEFINED;\n    resolving_funcs[1] = JS_UNDEFINED;\n    res = perform_promise_then(ctx, promise,\n                               (JSValueConst *)resolving_funcs1,\n                               (JSValueConst *)resolving_funcs);\n    JS_FreeValue(ctx, resolving_funcs1[0]);\n    JS_FreeValue(ctx, resolving_funcs1[1]);\n    JS_FreeValue(ctx, promise);\n    return res;\n}\n\nstatic void js_async_generator_resume_next(JSContext *ctx,\n                                           JSAsyncGeneratorData *s)\n{\n    JSAsyncGeneratorRequest *next;\n    JSValue func_ret, value;\n\n    for(;;) {\n        if (list_empty(&s->queue))\n            break;\n        next = list_entry(s->queue.next, JSAsyncGeneratorRequest, link);\n        switch(s->state) {\n        case JS_ASYNC_GENERATOR_STATE_EXECUTING:\n            /* only happens when restarting execution after await() */\n            goto resume_exec;\n        case JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN:\n            goto done;\n        case JS_ASYNC_GENERATOR_STATE_SUSPENDED_START:\n            if (next->completion_type == GEN_MAGIC_NEXT) {\n                goto exec_no_arg;\n            } else {\n                js_async_generator_complete(ctx, s);\n            }\n            break;\n        case JS_ASYNC_GENERATOR_STATE_COMPLETED:\n            if (next->completion_type == GEN_MAGIC_NEXT) {\n                js_async_generator_resolve(ctx, s, JS_UNDEFINED, TRUE);\n            } else if (next->completion_type == GEN_MAGIC_RETURN) {\n                s->state = JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN;\n                js_async_generator_completed_return(ctx, s, next->result);\n                goto done;\n            } else {\n                js_async_generator_reject(ctx, s, next->result);\n            }\n            goto done;\n        case JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD:\n        case JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD_STAR:\n            value = JS_DupValue(ctx, next->result);\n            if (next->completion_type == GEN_MAGIC_THROW &&\n                s->state == JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD) {\n                JS_Throw(ctx, value);\n                s->func_state.throw_flag = TRUE;\n            } else {\n                /* 'yield' returns a value. 'yield *' also returns a value\n                   in case the 'throw' method is called */\n                s->func_state.frame.cur_sp[-1] = value;\n                s->func_state.frame.cur_sp[0] =\n                    JS_NewInt32(ctx, next->completion_type);\n                s->func_state.frame.cur_sp++;\n            exec_no_arg:\n                s->func_state.throw_flag = FALSE;\n            }\n            s->state = JS_ASYNC_GENERATOR_STATE_EXECUTING;\n        resume_exec:\n            func_ret = async_func_resume(ctx, &s->func_state);\n            if (JS_IsException(func_ret)) {\n                value = JS_GetException(ctx);\n                js_async_generator_complete(ctx, s);\n                js_async_generator_reject(ctx, s, value);\n                JS_FreeValue(ctx, value);\n            } else if (JS_VALUE_GET_TAG(func_ret) == JS_TAG_INT) {\n                int func_ret_code;\n                value = s->func_state.frame.cur_sp[-1];\n                s->func_state.frame.cur_sp[-1] = JS_UNDEFINED;\n                func_ret_code = JS_VALUE_GET_INT(func_ret);\n                switch(func_ret_code) {\n                case FUNC_RET_YIELD:\n                case FUNC_RET_YIELD_STAR:\n                    if (func_ret_code == FUNC_RET_YIELD_STAR)\n                        s->state = JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD_STAR;\n                    else\n                        s->state = JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD;\n                    js_async_generator_resolve(ctx, s, value, FALSE);\n                    JS_FreeValue(ctx, value);\n                    break;\n                case FUNC_RET_AWAIT:\n                    js_async_generator_await(ctx, s, value);\n                    JS_FreeValue(ctx, value);\n                    goto done;\n                default:\n                    abort();\n                }\n            } else {\n                assert(JS_IsUndefined(func_ret));\n                /* end of function */\n                value = s->func_state.frame.cur_sp[-1];\n                s->func_state.frame.cur_sp[-1] = JS_UNDEFINED;\n                js_async_generator_complete(ctx, s);\n                js_async_generator_resolve(ctx, s, value, TRUE);\n                JS_FreeValue(ctx, value);\n            }\n            break;\n        default:\n            abort();\n        }\n    }\n done: ;\n}\n\nstatic JSValue js_async_generator_resolve_function(JSContext *ctx,\n                                                   JSValueConst this_obj,\n                                                   int argc, JSValueConst *argv,\n                                                   int magic, JSValue *func_data)\n{\n    BOOL is_reject = magic & 1;\n    JSAsyncGeneratorData *s = JS_GetOpaque(func_data[0], JS_CLASS_ASYNC_GENERATOR);\n    JSValueConst arg = argv[0];\n\n    /* XXX: what if s == NULL */\n\n    if (magic >= 2) {\n        /* resume next case in AWAITING_RETURN state */\n        assert(s->state == JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN ||\n               s->state == JS_ASYNC_GENERATOR_STATE_COMPLETED);\n        s->state = JS_ASYNC_GENERATOR_STATE_COMPLETED;\n        if (is_reject) {\n            js_async_generator_reject(ctx, s, arg);\n        } else {\n            js_async_generator_resolve(ctx, s, arg, TRUE);\n        }\n    } else {\n        /* restart function execution after await() */\n        assert(s->state == JS_ASYNC_GENERATOR_STATE_EXECUTING);\n        s->func_state.throw_flag = is_reject;\n        if (is_reject) {\n            JS_Throw(ctx, JS_DupValue(ctx, arg));\n        } else {\n            /* return value of await */\n            s->func_state.frame.cur_sp[-1] = JS_DupValue(ctx, arg);\n        }\n        js_async_generator_resume_next(ctx, s);\n    }\n    return JS_UNDEFINED;\n}\n\n/* magic = GEN_MAGIC_x */\nstatic JSValue js_async_generator_next(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv,\n                                       int magic)\n{\n    JSAsyncGeneratorData *s = JS_GetOpaque(this_val, JS_CLASS_ASYNC_GENERATOR);\n    JSValue promise, resolving_funcs[2];\n    JSAsyncGeneratorRequest *req;\n\n    promise = JS_NewPromiseCapability(ctx, resolving_funcs);\n    if (JS_IsException(promise))\n        return JS_EXCEPTION;\n    if (!s) {\n        JSValue err, res2;\n        JS_ThrowTypeError(ctx, \"not an AsyncGenerator object\");\n        err = JS_GetException(ctx);\n        res2 = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED,\n                       1, (JSValueConst *)&err);\n        JS_FreeValue(ctx, err);\n        JS_FreeValue(ctx, res2);\n        JS_FreeValue(ctx, resolving_funcs[0]);\n        JS_FreeValue(ctx, resolving_funcs[1]);\n        return promise;\n    }\n    req = js_mallocz(ctx, sizeof(*req));\n    if (!req)\n        goto fail;\n    req->completion_type = magic;\n    req->result = JS_DupValue(ctx, argv[0]);\n    req->promise = JS_DupValue(ctx, promise);\n    req->resolving_funcs[0] = resolving_funcs[0];\n    req->resolving_funcs[1] = resolving_funcs[1];\n    list_add_tail(&req->link, &s->queue);\n    if (s->state != JS_ASYNC_GENERATOR_STATE_EXECUTING) {\n        js_async_generator_resume_next(ctx, s);\n    }\n    return promise;\n fail:\n    JS_FreeValue(ctx, resolving_funcs[0]);\n    JS_FreeValue(ctx, resolving_funcs[1]);\n    JS_FreeValue(ctx, promise);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_async_generator_function_call(JSContext *ctx, JSValueConst func_obj,\n                                                JSValueConst this_obj,\n                                                int argc, JSValueConst *argv,\n                                                int flags)\n{\n    JSValue obj, func_ret;\n    JSAsyncGeneratorData *s;\n\n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s)\n        return JS_EXCEPTION;\n    s->state = JS_ASYNC_GENERATOR_STATE_SUSPENDED_START;\n    init_list_head(&s->queue);\n    if (async_func_init(ctx, &s->func_state, func_obj, this_obj, argc, argv)) {\n        s->state = JS_ASYNC_GENERATOR_STATE_COMPLETED;\n        goto fail;\n    }\n\n    /* execute the function up to 'OP_initial_yield' (no yield nor\n       await are possible) */\n    func_ret = async_func_resume(ctx, &s->func_state);\n    if (JS_IsException(func_ret))\n        goto fail;\n    JS_FreeValue(ctx, func_ret);\n\n    obj = js_create_from_ctor(ctx, func_obj, JS_CLASS_ASYNC_GENERATOR);\n    if (JS_IsException(obj))\n        goto fail;\n    s->generator = JS_VALUE_GET_OBJ(obj);\n    JS_SetOpaque(obj, s);\n    return obj;\n fail:\n    js_async_generator_free(ctx->rt, s);\n    return JS_EXCEPTION;\n}\n\n/* JS parser */\n\nenum {\n    TOK_NUMBER = -128,\n    TOK_STRING,\n    TOK_TEMPLATE,\n    TOK_IDENT,\n    TOK_REGEXP,\n    /* warning: order matters (see js_parse_assign_expr) */\n    TOK_MUL_ASSIGN,\n    TOK_DIV_ASSIGN,\n    TOK_MOD_ASSIGN,\n    TOK_PLUS_ASSIGN,\n    TOK_MINUS_ASSIGN,\n    TOK_SHL_ASSIGN,\n    TOK_SAR_ASSIGN,\n    TOK_SHR_ASSIGN,\n    TOK_AND_ASSIGN,\n    TOK_XOR_ASSIGN,\n    TOK_OR_ASSIGN,\n#ifdef CONFIG_BIGNUM\n    TOK_MATH_POW_ASSIGN,\n#endif\n    TOK_POW_ASSIGN,\n    TOK_LAND_ASSIGN,\n    TOK_LOR_ASSIGN,\n    TOK_DOUBLE_QUESTION_MARK_ASSIGN,\n    TOK_DEC,\n    TOK_INC,\n    TOK_SHL,\n    TOK_SAR,\n    TOK_SHR,\n    TOK_LT,\n    TOK_LTE,\n    TOK_GT,\n    TOK_GTE,\n    TOK_EQ,\n    TOK_STRICT_EQ,\n    TOK_NEQ,\n    TOK_STRICT_NEQ,\n    TOK_LAND,\n    TOK_LOR,\n#ifdef CONFIG_BIGNUM\n    TOK_MATH_POW,\n#endif\n    TOK_POW,\n    TOK_ARROW,\n    TOK_ELLIPSIS,\n    TOK_DOUBLE_QUESTION_MARK,\n    TOK_QUESTION_MARK_DOT,\n    TOK_ERROR,\n    TOK_PRIVATE_NAME,\n    TOK_EOF,\n    /* keywords: WARNING: same order as atoms */\n    TOK_NULL, /* must be first */\n    TOK_FALSE,\n    TOK_TRUE,\n    TOK_IF,\n    TOK_ELSE,\n    TOK_RETURN,\n    TOK_VAR,\n    TOK_THIS,\n    TOK_DELETE,\n    TOK_VOID,\n    TOK_TYPEOF,\n    TOK_NEW,\n    TOK_IN,\n    TOK_INSTANCEOF,\n    TOK_DO,\n    TOK_WHILE,\n    TOK_FOR,\n    TOK_BREAK,\n    TOK_CONTINUE,\n    TOK_SWITCH,\n    TOK_CASE,\n    TOK_DEFAULT,\n    TOK_THROW,\n    TOK_TRY,\n    TOK_CATCH,\n    TOK_FINALLY,\n    TOK_FUNCTION,\n    TOK_DEBUGGER,\n    TOK_WITH,\n    /* FutureReservedWord */\n    TOK_CLASS,\n    TOK_CONST,\n    TOK_ENUM,\n    TOK_EXPORT,\n    TOK_EXTENDS,\n    TOK_IMPORT,\n    TOK_SUPER,\n    /* FutureReservedWords when parsing strict mode code */\n    TOK_IMPLEMENTS,\n    TOK_INTERFACE,\n    TOK_LET,\n    TOK_PACKAGE,\n    TOK_PRIVATE,\n    TOK_PROTECTED,\n    TOK_PUBLIC,\n    TOK_STATIC,\n    TOK_YIELD,\n    TOK_AWAIT, /* must be last */\n    TOK_OF,     /* only used for js_parse_skip_parens_token() */\n};\n\n#define TOK_FIRST_KEYWORD   TOK_NULL\n#define TOK_LAST_KEYWORD    TOK_AWAIT\n\n/* unicode code points */\n#define CP_NBSP 0x00a0\n#define CP_BOM  0xfeff\n\n#define CP_LS   0x2028\n#define CP_PS   0x2029\n\ntypedef struct BlockEnv {\n    struct BlockEnv *prev;\n    JSAtom label_name; /* JS_ATOM_NULL if none */\n    int label_break; /* -1 if none */\n    int label_cont; /* -1 if none */\n    int drop_count; /* number of stack elements to drop */\n    int label_finally; /* -1 if none */\n    int scope_level;\n    int has_iterator;\n} BlockEnv;\n\ntypedef struct JSGlobalVar {\n    int cpool_idx; /* if >= 0, index in the constant pool for hoisted\n                      function defintion*/\n    uint8_t force_init : 1; /* force initialization to undefined */\n    uint8_t is_lexical : 1; /* global let/const definition */\n    uint8_t is_const   : 1; /* const definition */\n    int scope_level;    /* scope of definition */\n    JSAtom var_name;  /* variable name */\n} JSGlobalVar;\n\ntypedef struct RelocEntry {\n    struct RelocEntry *next;\n    uint32_t addr; /* address to patch */\n    int size;   /* address size: 1, 2 or 4 bytes */\n} RelocEntry;\n\ntypedef struct JumpSlot {\n    int op;\n    int size;\n    int pos;\n    int label;\n} JumpSlot;\n\ntypedef struct LabelSlot {\n    int ref_count;\n    int pos;    /* phase 1 address, -1 means not resolved yet */\n    int pos2;   /* phase 2 address, -1 means not resolved yet */\n    int addr;   /* phase 3 address, -1 means not resolved yet */\n    RelocEntry *first_reloc;\n} LabelSlot;\n\ntypedef struct LineNumberSlot {\n    uint32_t pc;\n    int line_num;\n} LineNumberSlot;\n\ntypedef enum JSParseFunctionEnum {\n    JS_PARSE_FUNC_STATEMENT,\n    JS_PARSE_FUNC_VAR,\n    JS_PARSE_FUNC_EXPR,\n    JS_PARSE_FUNC_ARROW,\n    JS_PARSE_FUNC_GETTER,\n    JS_PARSE_FUNC_SETTER,\n    JS_PARSE_FUNC_METHOD,\n    JS_PARSE_FUNC_CLASS_CONSTRUCTOR,\n    JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR,\n} JSParseFunctionEnum;\n\ntypedef enum JSParseExportEnum {\n    JS_PARSE_EXPORT_NONE,\n    JS_PARSE_EXPORT_NAMED,\n    JS_PARSE_EXPORT_DEFAULT,\n} JSParseExportEnum;\n\ntypedef struct JSFunctionDef {\n    JSContext *ctx;\n    struct JSFunctionDef *parent;\n    int parent_cpool_idx; /* index in the constant pool of the parent\n                             or -1 if none */\n    int parent_scope_level; /* scope level in parent at point of definition */\n    struct list_head child_list; /* list of JSFunctionDef.link */\n    struct list_head link;\n\n    BOOL is_eval; /* TRUE if eval code */\n    int eval_type; /* only valid if is_eval = TRUE */\n    BOOL is_global_var; /* TRUE if variables are not defined locally:\n                           eval global, eval module or non strict eval */\n    BOOL is_func_expr; /* TRUE if function expression */\n    BOOL has_home_object; /* TRUE if the home object is available */\n    BOOL has_prototype; /* true if a prototype field is necessary */\n    BOOL has_simple_parameter_list;\n    BOOL has_parameter_expressions; /* if true, an argument scope is created */\n    BOOL has_use_strict; /* to reject directive in special cases */\n    BOOL has_eval_call; /* true if the function contains a call to eval() */\n    BOOL has_arguments_binding; /* true if the 'arguments' binding is\n                                   available in the function */\n    BOOL has_this_binding; /* true if the 'this' and new.target binding are\n                              available in the function */\n    BOOL new_target_allowed; /* true if the 'new.target' does not\n                                throw a syntax error */\n    BOOL super_call_allowed; /* true if super() is allowed */\n    BOOL super_allowed; /* true if super. or super[] is allowed */\n    BOOL arguments_allowed; /* true if the 'arguments' identifier is allowed */\n    BOOL is_derived_class_constructor;\n    BOOL in_function_body;\n    BOOL backtrace_barrier;\n    JSFunctionKindEnum func_kind : 8;\n    JSParseFunctionEnum func_type : 8;\n    uint8_t js_mode; /* bitmap of JS_MODE_x */\n    JSAtom func_name; /* JS_ATOM_NULL if no name */\n\n    JSVarDef *vars;\n    int var_size; /* allocated size for vars[] */\n    int var_count;\n    JSVarDef *args;\n    int arg_size; /* allocated size for args[] */\n    int arg_count; /* number of arguments */\n    int defined_arg_count;\n    int var_object_idx; /* -1 if none */\n    int arg_var_object_idx; /* -1 if none (var object for the argument scope) */\n    int arguments_var_idx; /* -1 if none */\n    int arguments_arg_idx; /* argument variable definition in argument scope, \n                              -1 if none */\n    int func_var_idx; /* variable containing the current function (-1\n                         if none, only used if is_func_expr is true) */\n    int eval_ret_idx; /* variable containing the return value of the eval, -1 if none */\n    int this_var_idx; /* variable containg the 'this' value, -1 if none */\n    int new_target_var_idx; /* variable containg the 'new.target' value, -1 if none */\n    int this_active_func_var_idx; /* variable containg the 'this.active_func' value, -1 if none */\n    int home_object_var_idx;\n    BOOL need_home_object;\n    \n    int scope_level;    /* index into fd->scopes if the current lexical scope */\n    int scope_first;    /* index into vd->vars of first lexically scoped variable */\n    int scope_size;     /* allocated size of fd->scopes array */\n    int scope_count;    /* number of entries used in the fd->scopes array */\n    JSVarScope *scopes;\n    JSVarScope def_scope_array[4];\n    int body_scope; /* scope of the body of the function or eval */\n\n    int global_var_count;\n    int global_var_size;\n    JSGlobalVar *global_vars;\n\n    DynBuf byte_code;\n    int last_opcode_pos; /* -1 if no last opcode */\n    int last_opcode_line_num;\n    BOOL use_short_opcodes; /* true if short opcodes are used in byte_code */\n    \n    LabelSlot *label_slots;\n    int label_size; /* allocated size for label_slots[] */\n    int label_count;\n    BlockEnv *top_break; /* break/continue label stack */\n\n    /* constant pool (strings, functions, numbers) */\n    JSValue *cpool;\n    int cpool_count;\n    int cpool_size;\n\n    /* list of variables in the closure */\n    int closure_var_count;\n    int closure_var_size;\n    JSClosureVar *closure_var;\n\n    JumpSlot *jump_slots;\n    int jump_size;\n    int jump_count;\n\n    LineNumberSlot *line_number_slots;\n    int line_number_size;\n    int line_number_count;\n    int line_number_last;\n    int line_number_last_pc;\n\n    /* pc2line table */\n    JSAtom filename;\n    int line_num;\n    DynBuf pc2line;\n\n    char *source;  /* raw source, utf-8 encoded */\n    int source_len;\n\n    JSModuleDef *module; /* != NULL when parsing a module */\n} JSFunctionDef;\n\ntypedef struct JSToken {\n    int val;\n    int line_num;   /* line number of token start */\n    const uint8_t *ptr;\n    union {\n        struct {\n            JSValue str;\n            int sep;\n        } str;\n        struct {\n            JSValue val;\n#ifdef CONFIG_BIGNUM\n            slimb_t exponent; /* may be != 0 only if val is a float */\n#endif\n        } num;\n        struct {\n            JSAtom atom;\n            BOOL has_escape;\n            BOOL is_reserved;\n        } ident;\n        struct {\n            JSValue body;\n            JSValue flags;\n        } regexp;\n    } u;\n} JSToken;\n\ntypedef struct JSParseState {\n    JSContext *ctx;\n    int last_line_num;  /* line number of last token */\n    int line_num;       /* line number of current offset */\n    const char *filename;\n    JSToken token;\n    BOOL got_lf; /* true if got line feed before the current token */\n    const uint8_t *last_ptr;\n    const uint8_t *buf_ptr;\n    const uint8_t *buf_end;\n\n    /* current function code */\n    JSFunctionDef *cur_func;\n    BOOL is_module; /* parsing a module */\n    BOOL allow_html_comments;\n    BOOL ext_json; /* true if accepting JSON superset */\n} JSParseState;\n\ntypedef struct JSOpCode {\n#ifdef DUMP_BYTECODE\n    const char *name;\n#endif\n    uint8_t size; /* in bytes */\n    /* the opcodes remove n_pop items from the top of the stack, then\n       pushes n_push items */\n    uint8_t n_pop;\n    uint8_t n_push;\n    uint8_t fmt;\n} JSOpCode;\n\nstatic const JSOpCode opcode_info[OP_COUNT + (OP_TEMP_END - OP_TEMP_START)] = {\n#define FMT(f)\n#ifdef DUMP_BYTECODE\n#define DEF(id, size, n_pop, n_push, f) { #id, size, n_pop, n_push, OP_FMT_ ## f },\n#else\n#define DEF(id, size, n_pop, n_push, f) { size, n_pop, n_push, OP_FMT_ ## f },\n#endif\n#include \"quickjs-opcode.h\"\n#undef DEF\n#undef FMT\n};\n\n#if SHORT_OPCODES\n/* After the final compilation pass, short opcodes are used. Their\n   opcodes overlap with the temporary opcodes which cannot appear in\n   the final bytecode. Their description is after the temporary\n   opcodes in opcode_info[]. */\n#define short_opcode_info(op)           \\\n    opcode_info[(op) >= OP_TEMP_START ? \\\n                (op) + (OP_TEMP_END - OP_TEMP_START) : (op)]\n#else\n#define short_opcode_info(op) opcode_info[op]\n#endif\n\nstatic __exception int next_token(JSParseState *s);\n\nstatic void free_token(JSParseState *s, JSToken *token)\n{\n    switch(token->val) {\n#ifdef CONFIG_BIGNUM\n    case TOK_NUMBER:\n        JS_FreeValue(s->ctx, token->u.num.val);\n        break;\n#endif\n    case TOK_STRING:\n    case TOK_TEMPLATE:\n        JS_FreeValue(s->ctx, token->u.str.str);\n        break;\n    case TOK_REGEXP:\n        JS_FreeValue(s->ctx, token->u.regexp.body);\n        JS_FreeValue(s->ctx, token->u.regexp.flags);\n        break;\n    case TOK_IDENT:\n    case TOK_PRIVATE_NAME:\n        JS_FreeAtom(s->ctx, token->u.ident.atom);\n        break;\n    default:\n        if (token->val >= TOK_FIRST_KEYWORD &&\n            token->val <= TOK_LAST_KEYWORD) {\n            JS_FreeAtom(s->ctx, token->u.ident.atom);\n        }\n        break;\n    }\n}\n\nstatic void __attribute((unused)) dump_token(JSParseState *s,\n                                             const JSToken *token)\n{\n    switch(token->val) {\n    case TOK_NUMBER:\n        {\n            double d;\n            JS_ToFloat64(s->ctx, &d, token->u.num.val);  /* no exception possible */\n            printf(\"number: %.14g\\n\", d);\n        }\n        break;\n    case TOK_IDENT:\n    dump_atom:\n        {\n            char buf[ATOM_GET_STR_BUF_SIZE];\n            printf(\"ident: '%s'\\n\",\n                   JS_AtomGetStr(s->ctx, buf, sizeof(buf), token->u.ident.atom));\n        }\n        break;\n    case TOK_STRING:\n        {\n            const char *str;\n            /* XXX: quote the string */\n            str = JS_ToCString(s->ctx, token->u.str.str);\n            printf(\"string: '%s'\\n\", str);\n            JS_FreeCString(s->ctx, str);\n        }\n        break;\n    case TOK_TEMPLATE:\n        {\n            const char *str;\n            str = JS_ToCString(s->ctx, token->u.str.str);\n            printf(\"template: `%s`\\n\", str);\n            JS_FreeCString(s->ctx, str);\n        }\n        break;\n    case TOK_REGEXP:\n        {\n            const char *str, *str2;\n            str = JS_ToCString(s->ctx, token->u.regexp.body);\n            str2 = JS_ToCString(s->ctx, token->u.regexp.flags);\n            printf(\"regexp: '%s' '%s'\\n\", str, str2);\n            JS_FreeCString(s->ctx, str);\n            JS_FreeCString(s->ctx, str2);\n        }\n        break;\n    case TOK_EOF:\n        printf(\"eof\\n\");\n        break;\n    default:\n        if (s->token.val >= TOK_NULL && s->token.val <= TOK_LAST_KEYWORD) {\n            goto dump_atom;\n        } else if (s->token.val >= 256) {\n            printf(\"token: %d\\n\", token->val);\n        } else {\n            printf(\"token: '%c'\\n\", token->val);\n        }\n        break;\n    }\n}\n\nint __attribute__((format(printf, 2, 3))) js_parse_error(JSParseState *s, const char *fmt, ...)\n{\n    JSContext *ctx = s->ctx;\n    va_list ap;\n    int backtrace_flags;\n    \n    va_start(ap, fmt);\n    JS_ThrowError2(ctx, JS_SYNTAX_ERROR, fmt, ap, FALSE);\n    va_end(ap);\n    backtrace_flags = 0;\n    if (s->cur_func && s->cur_func->backtrace_barrier)\n        backtrace_flags = JS_BACKTRACE_FLAG_SINGLE_LEVEL;\n    build_backtrace(ctx, ctx->rt->current_exception, s->filename, s->line_num,\n                    backtrace_flags);\n    return -1;\n}\n\nstatic int js_parse_expect(JSParseState *s, int tok)\n{\n    if (s->token.val != tok) {\n        /* XXX: dump token correctly in all cases */\n        return js_parse_error(s, \"expecting '%c'\", tok);\n    }\n    return next_token(s);\n}\n\nstatic int js_parse_expect_semi(JSParseState *s)\n{\n    if (s->token.val != ';') {\n        /* automatic insertion of ';' */\n        if (s->token.val == TOK_EOF || s->token.val == '}' || s->got_lf) {\n            return 0;\n        }\n        return js_parse_error(s, \"expecting '%c'\", ';');\n    }\n    return next_token(s);\n}\n\nstatic int js_parse_error_reserved_identifier(JSParseState *s)\n{\n    char buf1[ATOM_GET_STR_BUF_SIZE];\n    return js_parse_error(s, \"'%s' is a reserved identifier\",\n                          JS_AtomGetStr(s->ctx, buf1, sizeof(buf1),\n                                        s->token.u.ident.atom));\n}\n\nstatic __exception int js_parse_template_part(JSParseState *s, const uint8_t *p)\n{\n    uint32_t c;\n    StringBuffer b_s, *b = &b_s;\n\n    /* p points to the first byte of the template part */\n    if (string_buffer_init(s->ctx, b, 32))\n        goto fail;\n    for(;;) {\n        if (p >= s->buf_end)\n            goto unexpected_eof;\n        c = *p++;\n        if (c == '`') {\n            /* template end part */\n            break;\n        }\n        if (c == '$' && *p == '{') {\n            /* template start or middle part */\n            p++;\n            break;\n        }\n        if (c == '\\\\') {\n            if (string_buffer_putc8(b, c))\n                goto fail;\n            if (p >= s->buf_end)\n                goto unexpected_eof;\n            c = *p++;\n        }\n        /* newline sequences are normalized as single '\\n' bytes */\n        if (c == '\\r') {\n            if (*p == '\\n')\n                p++;\n            c = '\\n';\n        }\n        if (c == '\\n') {\n            s->line_num++;\n        } else if (c >= 0x80) {\n            const uint8_t *p_next;\n            c = unicode_from_utf8(p - 1, UTF8_CHAR_LEN_MAX, &p_next);\n            if (c > 0x10FFFF) {\n                js_parse_error(s, \"invalid UTF-8 sequence\");\n                goto fail;\n            }\n            p = p_next;\n        }\n        if (string_buffer_putc(b, c))\n            goto fail;\n    }\n    s->token.val = TOK_TEMPLATE;\n    s->token.u.str.sep = c;\n    s->token.u.str.str = string_buffer_end(b);\n    s->buf_ptr = p;\n    return 0;\n\n unexpected_eof:\n    js_parse_error(s, \"unexpected end of string\");\n fail:\n    string_buffer_free(b);\n    return -1;\n}\n\nstatic __exception int js_parse_string(JSParseState *s, int sep,\n                                       BOOL do_throw, const uint8_t *p,\n                                       JSToken *token, const uint8_t **pp)\n{\n    int ret;\n    uint32_t c;\n    StringBuffer b_s, *b = &b_s;\n\n    /* string */\n    if (string_buffer_init(s->ctx, b, 32))\n        goto fail;\n    for(;;) {\n        if (p >= s->buf_end)\n            goto invalid_char;\n        c = *p;\n        if (c < 0x20) {\n            if (!s->cur_func) {\n                if (do_throw)\n                    js_parse_error(s, \"invalid character in a JSON string\");\n                goto fail;\n            }\n            if (sep == '`') {\n                if (c == '\\r') {\n                    if (p[1] == '\\n')\n                        p++;\n                    c = '\\n';\n                }\n                /* do not update s->line_num */\n            } else if (c == '\\n' || c == '\\r')\n                goto invalid_char;\n        }\n        p++;\n        if (c == sep)\n            break;\n        if (c == '$' && *p == '{' && sep == '`') {\n            /* template start or middle part */\n            p++;\n            break;\n        }\n        if (c == '\\\\') {\n            c = *p;\n            /* XXX: need a specific JSON case to avoid\n               accepting invalid escapes */\n            switch(c) {\n            case '\\0':\n                if (p >= s->buf_end)\n                    goto invalid_char;\n                p++;\n                break;\n            case '\\'':\n            case '\\\"':\n            case '\\\\':\n                p++;\n                break;\n            case '\\r':  /* accept DOS and MAC newline sequences */\n                if (p[1] == '\\n') {\n                    p++;\n                }\n                /* fall thru */\n            case '\\n':\n                /* ignore escaped newline sequence */\n                p++;\n                if (sep != '`')\n                    s->line_num++;\n                continue;\n            default:\n                if (c >= '0' && c <= '9') {\n                    if (!s->cur_func)\n                        goto invalid_escape; /* JSON case */\n                    if (!(s->cur_func->js_mode & JS_MODE_STRICT) && sep != '`')\n                        goto parse_escape;\n                    if (c == '0' && !(p[1] >= '0' && p[1] <= '9')) {\n                        p++;\n                        c = '\\0';\n                    } else {\n                        if (c >= '8' || sep == '`') {\n                            /* Note: according to ES2021, \\8 and \\9 are not\n                               accepted in strict mode or in templates. */\n                            goto invalid_escape;\n                        } else {\n                            if (do_throw)\n                                js_parse_error(s, \"octal escape sequences are not allowed in strict mode\");\n                        }\n                        goto fail;\n                    }\n                } else if (c >= 0x80) {\n                    const uint8_t *p_next;\n                    c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p_next);\n                    if (c > 0x10FFFF) {\n                        goto invalid_utf8;\n                    }\n                    p = p_next;\n                    /* LS or PS are skipped */\n                    if (c == CP_LS || c == CP_PS)\n                        continue;\n                } else {\n                parse_escape:\n                    ret = lre_parse_escape(&p, TRUE);\n                    if (ret == -1) {\n                    invalid_escape:\n                        if (do_throw)\n                            js_parse_error(s, \"malformed escape sequence in string literal\");\n                        goto fail;\n                    } else if (ret < 0) {\n                        /* ignore the '\\' (could output a warning) */\n                        p++;\n                    } else {\n                        c = ret;\n                    }\n                }\n                break;\n            }\n        } else if (c >= 0x80) {\n            const uint8_t *p_next;\n            c = unicode_from_utf8(p - 1, UTF8_CHAR_LEN_MAX, &p_next);\n            if (c > 0x10FFFF)\n                goto invalid_utf8;\n            p = p_next;\n        }\n        if (string_buffer_putc(b, c))\n            goto fail;\n    }\n    token->val = TOK_STRING;\n    token->u.str.sep = c;\n    token->u.str.str = string_buffer_end(b);\n    *pp = p;\n    return 0;\n\n invalid_utf8:\n    if (do_throw)\n        js_parse_error(s, \"invalid UTF-8 sequence\");\n    goto fail;\n invalid_char:\n    if (do_throw)\n        js_parse_error(s, \"unexpected end of string\");\n fail:\n    string_buffer_free(b);\n    return -1;\n}\n\nstatic inline BOOL token_is_pseudo_keyword(JSParseState *s, JSAtom atom) {\n    return s->token.val == TOK_IDENT && s->token.u.ident.atom == atom &&\n        !s->token.u.ident.has_escape;\n}\n\nstatic __exception int js_parse_regexp(JSParseState *s)\n{\n    const uint8_t *p;\n    BOOL in_class;\n    StringBuffer b_s, *b = &b_s;\n    StringBuffer b2_s, *b2 = &b2_s;\n    uint32_t c;\n\n    p = s->buf_ptr;\n    p++;\n    in_class = FALSE;\n    if (string_buffer_init(s->ctx, b, 32))\n        return -1;\n    if (string_buffer_init(s->ctx, b2, 1))\n        goto fail;\n    for(;;) {\n        if (p >= s->buf_end) {\n        eof_error:\n            js_parse_error(s, \"unexpected end of regexp\");\n            goto fail;\n        }\n        c = *p++;\n        if (c == '\\n' || c == '\\r') {\n            goto eol_error;\n        } else if (c == '/') {\n            if (!in_class)\n                break;\n        } else if (c == '[') {\n            in_class = TRUE;\n        } else if (c == ']') {\n            /* XXX: incorrect as the first character in a class */\n            in_class = FALSE;\n        } else if (c == '\\\\') {\n            if (string_buffer_putc8(b, c))\n                goto fail;\n            c = *p++;\n            if (c == '\\n' || c == '\\r')\n                goto eol_error;\n            else if (c == '\\0' && p >= s->buf_end)\n                goto eof_error;\n            else if (c >= 0x80) {\n                const uint8_t *p_next;\n                c = unicode_from_utf8(p - 1, UTF8_CHAR_LEN_MAX, &p_next);\n                if (c > 0x10FFFF) {\n                    goto invalid_utf8;\n                }\n                p = p_next;\n                if (c == CP_LS || c == CP_PS)\n                    goto eol_error;\n            }\n        } else if (c >= 0x80) {\n            const uint8_t *p_next;\n            c = unicode_from_utf8(p - 1, UTF8_CHAR_LEN_MAX, &p_next);\n            if (c > 0x10FFFF) {\n            invalid_utf8:\n                js_parse_error(s, \"invalid UTF-8 sequence\");\n                goto fail;\n            }\n            p = p_next;\n            /* LS or PS are considered as line terminator */\n            if (c == CP_LS || c == CP_PS) {\n            eol_error:\n                js_parse_error(s, \"unexpected line terminator in regexp\");\n                goto fail;\n            }\n        }\n        if (string_buffer_putc(b, c))\n            goto fail;\n    }\n\n    /* flags */\n    for(;;) {\n        const uint8_t *p_next = p;\n        c = *p_next++;\n        if (c >= 0x80) {\n            c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p_next);\n            if (c > 0x10FFFF) {\n                goto invalid_utf8;\n            }\n        }\n        if (!lre_js_is_ident_next(c))\n            break;\n        if (string_buffer_putc(b2, c))\n            goto fail;\n        p = p_next;\n    }\n\n    s->token.val = TOK_REGEXP;\n    s->token.u.regexp.body = string_buffer_end(b);\n    s->token.u.regexp.flags = string_buffer_end(b2);\n    s->buf_ptr = p;\n    return 0;\n fail:\n    string_buffer_free(b);\n    string_buffer_free(b2);\n    return -1;\n}\n\nstatic __exception int ident_realloc(JSContext *ctx, char **pbuf, size_t *psize,\n                                     char *static_buf)\n{\n    char *buf, *new_buf;\n    size_t size, new_size;\n    \n    buf = *pbuf;\n    size = *psize;\n    if (size >= (SIZE_MAX / 3) * 2)\n        new_size = SIZE_MAX;\n    else\n        new_size = size + (size >> 1);\n    if (buf == static_buf) {\n        new_buf = js_malloc(ctx, new_size);\n        if (!new_buf)\n            return -1;\n        memcpy(new_buf, buf, size);\n    } else {\n        new_buf = js_realloc(ctx, buf, new_size);\n        if (!new_buf)\n            return -1;\n    }\n    *pbuf = new_buf;\n    *psize = new_size;\n    return 0;\n}\n\n/* 'c' is the first character. Return JS_ATOM_NULL in case of error */\nstatic JSAtom parse_ident(JSParseState *s, const uint8_t **pp,\n                          BOOL *pident_has_escape, int c, BOOL is_private)\n{\n    const uint8_t *p, *p1;\n    char ident_buf[128], *buf;\n    size_t ident_size, ident_pos;\n    JSAtom atom;\n    \n    p = *pp;\n    buf = ident_buf;\n    ident_size = sizeof(ident_buf);\n    ident_pos = 0;\n    if (is_private)\n        buf[ident_pos++] = '#';\n    for(;;) {\n        p1 = p;\n        \n        if (c < 128) {\n            buf[ident_pos++] = c;\n        } else {\n            ident_pos += unicode_to_utf8((uint8_t*)buf + ident_pos, c);\n        }\n        c = *p1++;\n        if (c == '\\\\' && *p1 == 'u') {\n            c = lre_parse_escape(&p1, TRUE);\n            *pident_has_escape = TRUE;\n        } else if (c >= 128) {\n            c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p1);\n        }\n        if (!lre_js_is_ident_next(c))\n            break;\n        p = p1;\n        if (unlikely(ident_pos >= ident_size - UTF8_CHAR_LEN_MAX)) {\n            if (ident_realloc(s->ctx, &buf, &ident_size, ident_buf)) {\n                atom = JS_ATOM_NULL;\n                goto done;\n            }\n        }\n    }\n    atom = JS_NewAtomLen(s->ctx, buf, ident_pos);\n done:\n    if (unlikely(buf != ident_buf))\n        js_free(s->ctx, buf);\n    *pp = p;\n    return atom;\n}\n\n\nstatic __exception int next_token(JSParseState *s)\n{\n    const uint8_t *p;\n    int c;\n    BOOL ident_has_escape;\n    JSAtom atom;\n    \n    if (js_check_stack_overflow(s->ctx->rt, 0)) {\n        return js_parse_error(s, \"stack overflow\");\n    }\n    \n    free_token(s, &s->token);\n\n    p = s->last_ptr = s->buf_ptr;\n    s->got_lf = FALSE;\n    s->last_line_num = s->token.line_num;\n redo:\n    s->token.line_num = s->line_num;\n    s->token.ptr = p;\n    c = *p;\n    switch(c) {\n    case 0:\n        if (p >= s->buf_end) {\n            s->token.val = TOK_EOF;\n        } else {\n            goto def_token;\n        }\n        break;\n    case '`':\n        if (js_parse_template_part(s, p + 1))\n            goto fail;\n        p = s->buf_ptr;\n        break;\n    case '\\'':\n    case '\\\"':\n        if (js_parse_string(s, c, TRUE, p + 1, &s->token, &p))\n            goto fail;\n        break;\n    case '\\r':  /* accept DOS and MAC newline sequences */\n        if (p[1] == '\\n') {\n            p++;\n        }\n        /* fall thru */\n    case '\\n':\n        p++;\n    line_terminator:\n        s->got_lf = TRUE;\n        s->line_num++;\n        goto redo;\n    case '\\f':\n    case '\\v':\n    case ' ':\n    case '\\t':\n        p++;\n        goto redo;\n    case '/':\n        if (p[1] == '*') {\n            /* comment */\n            p += 2;\n            for(;;) {\n                if (*p == '\\0' && p >= s->buf_end) {\n                    js_parse_error(s, \"unexpected end of comment\");\n                    goto fail;\n                }\n                if (p[0] == '*' && p[1] == '/') {\n                    p += 2;\n                    break;\n                }\n                if (*p == '\\n') {\n                    s->line_num++;\n                    s->got_lf = TRUE; /* considered as LF for ASI */\n                    p++;\n                } else if (*p == '\\r') {\n                    s->got_lf = TRUE; /* considered as LF for ASI */\n                    p++;\n                } else if (*p >= 0x80) {\n                    c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);\n                    if (c == CP_LS || c == CP_PS) {\n                        s->got_lf = TRUE; /* considered as LF for ASI */\n                    } else if (c == -1) {\n                        p++; /* skip invalid UTF-8 */\n                    }\n                } else {\n                    p++;\n                }\n            }\n            goto redo;\n        } else if (p[1] == '/') {\n            /* line comment */\n            p += 2;\n        skip_line_comment:\n            for(;;) {\n                if (*p == '\\0' && p >= s->buf_end)\n                    break;\n                if (*p == '\\r' || *p == '\\n')\n                    break;\n                if (*p >= 0x80) {\n                    c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);\n                    /* LS or PS are considered as line terminator */\n                    if (c == CP_LS || c == CP_PS) {\n                        break;\n                    } else if (c == -1) {\n                        p++; /* skip invalid UTF-8 */\n                    }\n                } else {\n                    p++;\n                }\n            }\n            goto redo;\n        } else if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_DIV_ASSIGN;\n        } else {\n            p++;\n            s->token.val = c;\n        }\n        break;\n    case '\\\\':\n        if (p[1] == 'u') {\n            const uint8_t *p1 = p + 1;\n            int c1 = lre_parse_escape(&p1, TRUE);\n            if (c1 >= 0 && lre_js_is_ident_first(c1)) {\n                c = c1;\n                p = p1;\n                ident_has_escape = TRUE;\n                goto has_ident;\n            } else {\n                /* XXX: syntax error? */\n            }\n        }\n        goto def_token;\n    case 'a': case 'b': case 'c': case 'd':\n    case 'e': case 'f': case 'g': case 'h':\n    case 'i': case 'j': case 'k': case 'l':\n    case 'm': case 'n': case 'o': case 'p':\n    case 'q': case 'r': case 's': case 't':\n    case 'u': case 'v': case 'w': case 'x':\n    case 'y': case 'z': \n    case 'A': case 'B': case 'C': case 'D':\n    case 'E': case 'F': case 'G': case 'H':\n    case 'I': case 'J': case 'K': case 'L':\n    case 'M': case 'N': case 'O': case 'P':\n    case 'Q': case 'R': case 'S': case 'T':\n    case 'U': case 'V': case 'W': case 'X':\n    case 'Y': case 'Z': \n    case '_':\n    case '$':\n        /* identifier */\n        p++;\n        ident_has_escape = FALSE;\n    has_ident:\n        atom = parse_ident(s, &p, &ident_has_escape, c, FALSE);\n        if (atom == JS_ATOM_NULL)\n            goto fail;\n        s->token.u.ident.atom = atom;\n        s->token.u.ident.has_escape = ident_has_escape;\n        s->token.u.ident.is_reserved = FALSE;\n        if (s->token.u.ident.atom <= JS_ATOM_LAST_KEYWORD ||\n            (s->token.u.ident.atom <= JS_ATOM_LAST_STRICT_KEYWORD &&\n             (s->cur_func->js_mode & JS_MODE_STRICT)) ||\n            (s->token.u.ident.atom == JS_ATOM_yield &&\n             ((s->cur_func->func_kind & JS_FUNC_GENERATOR) ||\n              (s->cur_func->func_type == JS_PARSE_FUNC_ARROW &&\n               !s->cur_func->in_function_body && s->cur_func->parent &&\n               (s->cur_func->parent->func_kind & JS_FUNC_GENERATOR)))) ||\n            (s->token.u.ident.atom == JS_ATOM_await &&\n             (s->is_module ||\n              (((s->cur_func->func_kind & JS_FUNC_ASYNC) ||\n                (s->cur_func->func_type == JS_PARSE_FUNC_ARROW &&\n                 !s->cur_func->in_function_body && s->cur_func->parent &&\n                 (s->cur_func->parent->func_kind & JS_FUNC_ASYNC))))))) {\n                  if (ident_has_escape) {\n                      s->token.u.ident.is_reserved = TRUE;\n                      s->token.val = TOK_IDENT;\n                  } else {\n                      /* The keywords atoms are pre allocated */\n                      s->token.val = s->token.u.ident.atom - 1 + TOK_FIRST_KEYWORD;\n                  }\n        } else {\n            s->token.val = TOK_IDENT;\n        }\n        break;\n    case '#':\n        /* private name */\n        {\n            const uint8_t *p1;\n            p++;\n            p1 = p;\n            c = *p1++;\n            if (c == '\\\\' && *p1 == 'u') {\n                c = lre_parse_escape(&p1, TRUE);\n            } else if (c >= 128) {\n                c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p1);\n            }\n            if (!lre_js_is_ident_first(c)) {\n                js_parse_error(s, \"invalid first character of private name\");\n                goto fail;\n            }\n            p = p1;\n            ident_has_escape = FALSE; /* not used */\n            atom = parse_ident(s, &p, &ident_has_escape, c, TRUE);\n            if (atom == JS_ATOM_NULL)\n                goto fail;\n            s->token.u.ident.atom = atom;\n            s->token.val = TOK_PRIVATE_NAME;\n        }\n        break;\n    case '.':\n        if (p[1] == '.' && p[2] == '.') {\n            p += 3;\n            s->token.val = TOK_ELLIPSIS;\n            break;\n        }\n        if (p[1] >= '0' && p[1] <= '9') {\n            goto parse_number;\n        } else {\n            goto def_token;\n        }\n        break;\n    case '0':\n        /* in strict mode, octal literals are not accepted */\n        if (is_digit(p[1]) && (s->cur_func->js_mode & JS_MODE_STRICT)) {\n            js_parse_error(s, \"octal literals are deprecated in strict mode\");\n            goto fail;\n        }\n        goto parse_number;\n    case '1': case '2': case '3': case '4':\n    case '5': case '6': case '7': case '8':\n    case '9': \n        /* number */\n    parse_number:\n        {\n            JSValue ret;\n            const uint8_t *p1;\n            int flags, radix;\n            flags = ATOD_ACCEPT_BIN_OCT | ATOD_ACCEPT_LEGACY_OCTAL |\n                ATOD_ACCEPT_UNDERSCORES;\n#ifdef CONFIG_BIGNUM\n            flags |= ATOD_ACCEPT_SUFFIX;\n            if (s->cur_func->js_mode & JS_MODE_MATH) {\n                flags |= ATOD_MODE_BIGINT;\n                if (s->cur_func->js_mode & JS_MODE_MATH)\n                    flags |= ATOD_TYPE_BIG_FLOAT;\n            }\n#endif\n            radix = 0;\n#ifdef CONFIG_BIGNUM\n            s->token.u.num.exponent = 0;\n            ret = js_atof2(s->ctx, (const char *)p, (const char **)&p, radix,\n                           flags, &s->token.u.num.exponent);\n#else\n            ret = js_atof(s->ctx, (const char *)p, (const char **)&p, radix,\n                          flags);\n#endif\n            if (JS_IsException(ret))\n                goto fail;\n            /* reject `10instanceof Number` */\n            if (JS_VALUE_IS_NAN(ret) ||\n                lre_js_is_ident_next(unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p1))) {\n                JS_FreeValue(s->ctx, ret);\n                js_parse_error(s, \"invalid number literal\");\n                goto fail;\n            }\n            s->token.val = TOK_NUMBER;\n            s->token.u.num.val = ret;\n        }\n        break;\n    case '*':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_MUL_ASSIGN;\n        } else if (p[1] == '*') {\n            if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_POW_ASSIGN;\n            } else {\n                p += 2;\n                s->token.val = TOK_POW;\n            }\n        } else {\n            goto def_token;\n        }\n        break;\n    case '%':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_MOD_ASSIGN;\n        } else {\n            goto def_token;\n        }\n        break;\n    case '+':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_PLUS_ASSIGN;\n        } else if (p[1] == '+') {\n            p += 2;\n            s->token.val = TOK_INC;\n        } else {\n            goto def_token;\n        }\n        break;\n    case '-':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_MINUS_ASSIGN;\n        } else if (p[1] == '-') {\n            if (s->allow_html_comments &&\n                p[2] == '>' && s->last_line_num != s->line_num) {\n                /* Annex B: `-->` at beginning of line is an html comment end.\n                   It extends to the end of the line.\n                 */\n                goto skip_line_comment;\n            }\n            p += 2;\n            s->token.val = TOK_DEC;\n        } else {\n            goto def_token;\n        }\n        break;\n    case '<':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_LTE;\n        } else if (p[1] == '<') {\n            if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_SHL_ASSIGN;\n            } else {\n                p += 2;\n                s->token.val = TOK_SHL;\n            }\n        } else if (s->allow_html_comments &&\n                   p[1] == '!' && p[2] == '-' && p[3] == '-') {\n            /* Annex B: handle `<!--` single line html comments */\n            goto skip_line_comment;\n        } else {\n            goto def_token;\n        }\n        break;\n    case '>':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_GTE;\n        } else if (p[1] == '>') {\n            if (p[2] == '>') {\n                if (p[3] == '=') {\n                    p += 4;\n                    s->token.val = TOK_SHR_ASSIGN;\n                } else {\n                    p += 3;\n                    s->token.val = TOK_SHR;\n                }\n            } else if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_SAR_ASSIGN;\n            } else {\n                p += 2;\n                s->token.val = TOK_SAR;\n            }\n        } else {\n            goto def_token;\n        }\n        break;\n    case '=':\n        if (p[1] == '=') {\n            if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_STRICT_EQ;\n            } else {\n                p += 2;\n                s->token.val = TOK_EQ;\n            }\n        } else if (p[1] == '>') {\n            p += 2;\n            s->token.val = TOK_ARROW;\n        } else {\n            goto def_token;\n        }\n        break;\n    case '!':\n        if (p[1] == '=') {\n            if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_STRICT_NEQ;\n            } else {\n                p += 2;\n                s->token.val = TOK_NEQ;\n            }\n        } else {\n            goto def_token;\n        }\n        break;\n    case '&':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_AND_ASSIGN;\n        } else if (p[1] == '&') {\n            if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_LAND_ASSIGN;\n            } else {\n                p += 2;\n                s->token.val = TOK_LAND;\n            }\n        } else {\n            goto def_token;\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n        /* in math mode, '^' is the power operator. '^^' is always the\n           xor operator and '**' is always the power operator */\n    case '^':\n        if (p[1] == '=') {\n            p += 2;\n            if (s->cur_func->js_mode & JS_MODE_MATH)\n                s->token.val = TOK_MATH_POW_ASSIGN;\n            else\n                s->token.val = TOK_XOR_ASSIGN;\n        } else if (p[1] == '^') {\n            if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_XOR_ASSIGN;\n            } else {\n                p += 2;\n                s->token.val = '^';\n            }\n        } else {\n            p++;\n            if (s->cur_func->js_mode & JS_MODE_MATH)\n                s->token.val = TOK_MATH_POW;\n            else\n                s->token.val = '^';\n        }\n        break;\n#else\n    case '^':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_XOR_ASSIGN;\n        } else {\n            goto def_token;\n        }\n        break;\n#endif\n    case '|':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_OR_ASSIGN;\n        } else if (p[1] == '|') {\n            if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_LOR_ASSIGN;\n            } else {\n                p += 2;\n                s->token.val = TOK_LOR;\n            }\n        } else {\n            goto def_token;\n        }\n        break;\n    case '?':\n        if (p[1] == '?') {\n            if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_DOUBLE_QUESTION_MARK_ASSIGN;\n            } else {\n                p += 2;\n                s->token.val = TOK_DOUBLE_QUESTION_MARK;\n            }\n        } else if (p[1] == '.' && !(p[2] >= '0' && p[2] <= '9')) {\n            p += 2;\n            s->token.val = TOK_QUESTION_MARK_DOT;\n        } else {\n            goto def_token;\n        }\n        break;\n    default:\n        if (c >= 128) {\n            /* unicode value */\n            c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);\n            switch(c) {\n            case CP_PS:\n            case CP_LS:\n                /* XXX: should avoid incrementing line_number, but\n                   needed to handle HTML comments */\n                goto line_terminator; \n            default:\n                if (lre_is_space(c)) {\n                    goto redo;\n                } else if (lre_js_is_ident_first(c)) {\n                    ident_has_escape = FALSE;\n                    goto has_ident;\n                } else {\n                    js_parse_error(s, \"unexpected character\");\n                    goto fail;\n                }\n            }\n        }\n    def_token:\n        s->token.val = c;\n        p++;\n        break;\n    }\n    s->buf_ptr = p;\n\n    //    dump_token(s, &s->token);\n    return 0;\n\n fail:\n    s->token.val = TOK_ERROR;\n    return -1;\n}\n\n/* 'c' is the first character. Return JS_ATOM_NULL in case of error */\nstatic JSAtom json_parse_ident(JSParseState *s, const uint8_t **pp, int c)\n{\n    const uint8_t *p;\n    char ident_buf[128], *buf;\n    size_t ident_size, ident_pos;\n    JSAtom atom;\n    \n    p = *pp;\n    buf = ident_buf;\n    ident_size = sizeof(ident_buf);\n    ident_pos = 0;\n    for(;;) {\n        buf[ident_pos++] = c;\n        c = *p;\n        if (c >= 128 ||\n            !((lre_id_continue_table_ascii[c >> 5] >> (c & 31)) & 1))\n            break;\n        p++;\n        if (unlikely(ident_pos >= ident_size - UTF8_CHAR_LEN_MAX)) {\n            if (ident_realloc(s->ctx, &buf, &ident_size, ident_buf)) {\n                atom = JS_ATOM_NULL;\n                goto done;\n            }\n        }\n    }\n    atom = JS_NewAtomLen(s->ctx, buf, ident_pos);\n done:\n    if (unlikely(buf != ident_buf))\n        js_free(s->ctx, buf);\n    *pp = p;\n    return atom;\n}\n\nstatic __exception int json_next_token(JSParseState *s)\n{\n    const uint8_t *p;\n    int c;\n    JSAtom atom;\n    \n    if (js_check_stack_overflow(s->ctx->rt, 0)) {\n        return js_parse_error(s, \"stack overflow\");\n    }\n    \n    free_token(s, &s->token);\n\n    p = s->last_ptr = s->buf_ptr;\n    s->last_line_num = s->token.line_num;\n redo:\n    s->token.line_num = s->line_num;\n    s->token.ptr = p;\n    c = *p;\n    switch(c) {\n    case 0:\n        if (p >= s->buf_end) {\n            s->token.val = TOK_EOF;\n        } else {\n            goto def_token;\n        }\n        break;\n    case '\\'':\n        if (!s->ext_json) {\n            /* JSON does not accept single quoted strings */\n            goto def_token;\n        }\n        /* fall through */\n    case '\\\"':\n        if (js_parse_string(s, c, TRUE, p + 1, &s->token, &p))\n            goto fail;\n        break;\n    case '\\r':  /* accept DOS and MAC newline sequences */\n        if (p[1] == '\\n') {\n            p++;\n        }\n        /* fall thru */\n    case '\\n':\n        p++;\n        s->line_num++;\n        goto redo;\n    case '\\f':\n    case '\\v':\n        if (!s->ext_json) {\n            /* JSONWhitespace does not match <VT>, nor <FF> */\n            goto def_token;\n        }\n        /* fall through */\n    case ' ':\n    case '\\t':\n        p++;\n        goto redo;\n    case '/':\n        if (!s->ext_json) {\n            /* JSON does not accept comments */\n            goto def_token;\n        }\n        if (p[1] == '*') {\n            /* comment */\n            p += 2;\n            for(;;) {\n                if (*p == '\\0' && p >= s->buf_end) {\n                    js_parse_error(s, \"unexpected end of comment\");\n                    goto fail;\n                }\n                if (p[0] == '*' && p[1] == '/') {\n                    p += 2;\n                    break;\n                }\n                if (*p == '\\n') {\n                    s->line_num++;\n                    p++;\n                } else if (*p == '\\r') {\n                    p++;\n                } else if (*p >= 0x80) {\n                    c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);\n                    if (c == -1) {\n                        p++; /* skip invalid UTF-8 */\n                    }\n                } else {\n                    p++;\n                }\n            }\n            goto redo;\n        } else if (p[1] == '/') {\n            /* line comment */\n            p += 2;\n            for(;;) {\n                if (*p == '\\0' && p >= s->buf_end)\n                    break;\n                if (*p == '\\r' || *p == '\\n')\n                    break;\n                if (*p >= 0x80) {\n                    c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);\n                    /* LS or PS are considered as line terminator */\n                    if (c == CP_LS || c == CP_PS) {\n                        break;\n                    } else if (c == -1) {\n                        p++; /* skip invalid UTF-8 */\n                    }\n                } else {\n                    p++;\n                }\n            }\n            goto redo;\n        } else {\n            goto def_token;\n        }\n        break;\n    case 'a': case 'b': case 'c': case 'd':\n    case 'e': case 'f': case 'g': case 'h':\n    case 'i': case 'j': case 'k': case 'l':\n    case 'm': case 'n': case 'o': case 'p':\n    case 'q': case 'r': case 's': case 't':\n    case 'u': case 'v': case 'w': case 'x':\n    case 'y': case 'z': \n    case 'A': case 'B': case 'C': case 'D':\n    case 'E': case 'F': case 'G': case 'H':\n    case 'I': case 'J': case 'K': case 'L':\n    case 'M': case 'N': case 'O': case 'P':\n    case 'Q': case 'R': case 'S': case 'T':\n    case 'U': case 'V': case 'W': case 'X':\n    case 'Y': case 'Z': \n    case '_':\n    case '$':\n        /* identifier : only pure ascii characters are accepted */\n        p++;\n        atom = json_parse_ident(s, &p, c);\n        if (atom == JS_ATOM_NULL)\n            goto fail;\n        s->token.u.ident.atom = atom;\n        s->token.u.ident.has_escape = FALSE;\n        s->token.u.ident.is_reserved = FALSE;\n        s->token.val = TOK_IDENT;\n        break;\n    case '+':\n        if (!s->ext_json || !is_digit(p[1]))\n            goto def_token;\n        goto parse_number;\n    case '0':\n        if (is_digit(p[1]))\n            goto def_token;\n        goto parse_number;\n    case '-':\n        if (!is_digit(p[1]))\n            goto def_token;\n        goto parse_number;\n    case '1': case '2': case '3': case '4':\n    case '5': case '6': case '7': case '8':\n    case '9': \n        /* number */\n    parse_number:\n        {\n            JSValue ret;\n            int flags, radix;\n            if (!s->ext_json) {\n                flags = 0;\n                radix = 10;\n            } else {\n                flags = ATOD_ACCEPT_BIN_OCT;\n                radix = 0;\n            }\n            ret = js_atof(s->ctx, (const char *)p, (const char **)&p, radix,\n                          flags);\n            if (JS_IsException(ret))\n                goto fail;\n            s->token.val = TOK_NUMBER;\n            s->token.u.num.val = ret;\n        }\n        break;\n    default:\n        if (c >= 128) {\n            js_parse_error(s, \"unexpected character\");\n            goto fail;\n        }\n    def_token:\n        s->token.val = c;\n        p++;\n        break;\n    }\n    s->buf_ptr = p;\n\n    //    dump_token(s, &s->token);\n    return 0;\n\n fail:\n    s->token.val = TOK_ERROR;\n    return -1;\n}\n\n/* only used for ':' and '=>', 'let' or 'function' look-ahead. *pp is\n   only set if TOK_IMPORT is returned */\n/* XXX: handle all unicode cases */\nstatic int simple_next_token(const uint8_t **pp, BOOL no_line_terminator)\n{\n    const uint8_t *p;\n    uint32_t c;\n    \n    /* skip spaces and comments */\n    p = *pp;\n    for (;;) {\n        switch(c = *p++) {\n        case '\\r':\n        case '\\n':\n            if (no_line_terminator)\n                return '\\n';\n            continue;\n        case ' ':\n        case '\\t':\n        case '\\v':\n        case '\\f':\n            continue;\n        case '/':\n            if (*p == '/') {\n                if (no_line_terminator)\n                    return '\\n';\n                while (*p && *p != '\\r' && *p != '\\n')\n                    p++;\n                continue;\n            }\n            if (*p == '*') {\n                while (*++p) {\n                    if ((*p == '\\r' || *p == '\\n') && no_line_terminator)\n                        return '\\n';\n                    if (*p == '*' && p[1] == '/') {\n                        p += 2;\n                        break;\n                    }\n                }\n                continue;\n            }\n            break;\n        case '=':\n            if (*p == '>')\n                return TOK_ARROW;\n            break;\n        default:\n            if (lre_js_is_ident_first(c)) {\n                if (c == 'i') {\n                    if (p[0] == 'n' && !lre_js_is_ident_next(p[1])) {\n                        return TOK_IN;\n                    }\n                    if (p[0] == 'm' && p[1] == 'p' && p[2] == 'o' &&\n                        p[3] == 'r' && p[4] == 't' &&\n                        !lre_js_is_ident_next(p[5])) {\n                        *pp = p + 5;\n                        return TOK_IMPORT;\n                    }\n                } else if (c == 'o' && *p == 'f' && !lre_js_is_ident_next(p[1])) {\n                    return TOK_OF;\n                } else if (c == 'e' &&\n                           p[0] == 'x' && p[1] == 'p' && p[2] == 'o' &&\n                           p[3] == 'r' && p[4] == 't' &&\n                           !lre_js_is_ident_next(p[5])) {\n                    *pp = p + 5;\n                    return TOK_EXPORT;\n                } else if (c == 'f' && p[0] == 'u' && p[1] == 'n' &&\n                         p[2] == 'c' && p[3] == 't' && p[4] == 'i' &&\n                         p[5] == 'o' && p[6] == 'n' && !lre_js_is_ident_next(p[7])) {\n                    return TOK_FUNCTION;\n                }\n                return TOK_IDENT;\n            }\n            break;\n        }\n        return c;\n    }\n}\n\nstatic int peek_token(JSParseState *s, BOOL no_line_terminator)\n{\n    const uint8_t *p = s->buf_ptr;\n    return simple_next_token(&p, no_line_terminator);\n}\n\n/* return true if 'input' contains the source of a module\n   (heuristic). 'input' must be a zero terminated.\n\n   Heuristic: skip comments and expect 'import' keyword not followed\n   by '(' or '.' or export keyword.\n*/\nBOOL JS_DetectModule(const char *input, size_t input_len)\n{\n    const uint8_t *p = (const uint8_t *)input;\n    int tok;\n    switch(simple_next_token(&p, FALSE)) {\n    case TOK_IMPORT:\n        tok = simple_next_token(&p, FALSE);\n        return (tok != '.' && tok != '(');\n    case TOK_EXPORT:\n        return TRUE;\n    default:\n        return FALSE;\n    }\n}\n\nstatic inline int get_prev_opcode(JSFunctionDef *fd) {\n    if (fd->last_opcode_pos < 0)\n        return OP_invalid;\n    else\n        return fd->byte_code.buf[fd->last_opcode_pos];\n}\n\nstatic BOOL js_is_live_code(JSParseState *s) {\n    switch (get_prev_opcode(s->cur_func)) {\n    case OP_tail_call:\n    case OP_tail_call_method:\n    case OP_return:\n    case OP_return_undef:\n    case OP_return_async:\n    case OP_throw:\n    case OP_throw_error:\n    case OP_goto:\n#if SHORT_OPCODES\n    case OP_goto8:\n    case OP_goto16:\n#endif\n    case OP_ret:\n        return FALSE;\n    default:\n        return TRUE;\n    }\n}\n\nstatic void emit_u8(JSParseState *s, uint8_t val)\n{\n    dbuf_putc(&s->cur_func->byte_code, val);\n}\n\nstatic void emit_u16(JSParseState *s, uint16_t val)\n{\n    dbuf_put_u16(&s->cur_func->byte_code, val);\n}\n\nstatic void emit_u32(JSParseState *s, uint32_t val)\n{\n    dbuf_put_u32(&s->cur_func->byte_code, val);\n}\n\nstatic void emit_op(JSParseState *s, uint8_t val)\n{\n    JSFunctionDef *fd = s->cur_func;\n    DynBuf *bc = &fd->byte_code;\n\n    /* Use the line number of the last token used, not the next token,\n       nor the current offset in the source file.\n     */\n    if (unlikely(fd->last_opcode_line_num != s->last_line_num)) {\n        dbuf_putc(bc, OP_line_num);\n        dbuf_put_u32(bc, s->last_line_num);\n        fd->last_opcode_line_num = s->last_line_num;\n    }\n    fd->last_opcode_pos = bc->size;\n    dbuf_putc(bc, val);\n}\n\nstatic void emit_atom(JSParseState *s, JSAtom name)\n{\n    emit_u32(s, JS_DupAtom(s->ctx, name));\n}\n\nstatic int update_label(JSFunctionDef *s, int label, int delta)\n{\n    LabelSlot *ls;\n\n    assert(label >= 0 && label < s->label_count);\n    ls = &s->label_slots[label];\n    ls->ref_count += delta;\n    assert(ls->ref_count >= 0);\n    return ls->ref_count;\n}\n\nstatic int new_label_fd(JSFunctionDef *fd, int label)\n{\n    LabelSlot *ls;\n\n    if (label < 0) {\n        if (js_resize_array(fd->ctx, (void *)&fd->label_slots,\n                            sizeof(fd->label_slots[0]),\n                            &fd->label_size, fd->label_count + 1))\n            return -1;\n        label = fd->label_count++;\n        ls = &fd->label_slots[label];\n        ls->ref_count = 0;\n        ls->pos = -1;\n        ls->pos2 = -1;\n        ls->addr = -1;\n        ls->first_reloc = NULL;\n    }\n    return label;\n}\n\nstatic int new_label(JSParseState *s)\n{\n    return new_label_fd(s->cur_func, -1);\n}\n\n/* return the label ID offset */\nstatic int emit_label(JSParseState *s, int label)\n{\n    if (label >= 0) {\n        emit_op(s, OP_label);\n        emit_u32(s, label);\n        s->cur_func->label_slots[label].pos = s->cur_func->byte_code.size;\n        return s->cur_func->byte_code.size - 4;\n    } else {\n        return -1;\n    }\n}\n\n/* return label or -1 if dead code */\nstatic int emit_goto(JSParseState *s, int opcode, int label)\n{\n    if (js_is_live_code(s)) {\n        if (label < 0)\n            label = new_label(s);\n        emit_op(s, opcode);\n        emit_u32(s, label);\n        s->cur_func->label_slots[label].ref_count++;\n        return label;\n    }\n    return -1;\n}\n\n/* return the constant pool index. 'val' is not duplicated. */\nstatic int cpool_add(JSParseState *s, JSValue val)\n{\n    JSFunctionDef *fd = s->cur_func;\n    \n    if (js_resize_array(s->ctx, (void *)&fd->cpool, sizeof(fd->cpool[0]),\n                        &fd->cpool_size, fd->cpool_count + 1))\n        return -1;\n    fd->cpool[fd->cpool_count++] = val;\n    return fd->cpool_count - 1;\n}\n\nstatic __exception int emit_push_const(JSParseState *s, JSValueConst val,\n                                       BOOL as_atom)\n{\n    int idx;\n\n    if (JS_VALUE_GET_TAG(val) == JS_TAG_STRING && as_atom) {\n        JSAtom atom;\n        /* warning: JS_NewAtomStr frees the string value */\n        JS_DupValue(s->ctx, val);\n        atom = JS_NewAtomStr(s->ctx, JS_VALUE_GET_STRING(val));\n        if (atom != JS_ATOM_NULL && !__JS_AtomIsTaggedInt(atom)) {\n            emit_op(s, OP_push_atom_value);\n            emit_u32(s, atom);\n            return 0;\n        }\n    }\n\n    idx = cpool_add(s, JS_DupValue(s->ctx, val));\n    if (idx < 0)\n        return -1;\n    emit_op(s, OP_push_const);\n    emit_u32(s, idx);\n    return 0;\n}\n\n/* return the variable index or -1 if not found,\n   add ARGUMENT_VAR_OFFSET for argument variables */\nstatic int find_arg(JSContext *ctx, JSFunctionDef *fd, JSAtom name)\n{\n    int i;\n    for(i = fd->arg_count; i-- > 0;) {\n        if (fd->args[i].var_name == name)\n            return i | ARGUMENT_VAR_OFFSET;\n    }\n    return -1;\n}\n\nstatic int find_var(JSContext *ctx, JSFunctionDef *fd, JSAtom name)\n{\n    int i;\n    for(i = fd->var_count; i-- > 0;) {\n        if (fd->vars[i].var_name == name && fd->vars[i].scope_level == 0)\n            return i;\n    }\n    return find_arg(ctx, fd, name);\n}\n\n/* find a variable declaration in a given scope */\nstatic int find_var_in_scope(JSContext *ctx, JSFunctionDef *fd,\n                             JSAtom name, int scope_level)\n{\n    int scope_idx;\n    for(scope_idx = fd->scopes[scope_level].first; scope_idx >= 0;\n        scope_idx = fd->vars[scope_idx].scope_next) {\n        if (fd->vars[scope_idx].scope_level != scope_level)\n            break;\n        if (fd->vars[scope_idx].var_name == name)\n            return scope_idx;\n    }\n    return -1;\n}\n\n/* return true if scope == parent_scope or if scope is a child of\n   parent_scope */\nstatic BOOL is_child_scope(JSContext *ctx, JSFunctionDef *fd,\n                           int scope, int parent_scope)\n{\n    while (scope >= 0) {\n        if (scope == parent_scope)\n            return TRUE;\n        scope = fd->scopes[scope].parent;\n    }\n    return FALSE;\n}\n\n/* find a 'var' declaration in the same scope or a child scope */\nstatic int find_var_in_child_scope(JSContext *ctx, JSFunctionDef *fd,\n                                   JSAtom name, int scope_level)\n{\n    int i;\n    for(i = 0; i < fd->var_count; i++) {\n        JSVarDef *vd = &fd->vars[i];\n        if (vd->var_name == name && vd->scope_level == 0) {\n            if (is_child_scope(ctx, fd, vd->scope_next,\n                               scope_level))\n                return i;\n        }\n    }\n    return -1;\n}\n\n\nstatic JSGlobalVar *find_global_var(JSFunctionDef *fd, JSAtom name)\n{\n    int i;\n    for(i = 0; i < fd->global_var_count; i++) {\n        JSGlobalVar *hf = &fd->global_vars[i];\n        if (hf->var_name == name)\n            return hf;\n    }\n    return NULL;\n\n}\n\nstatic JSGlobalVar *find_lexical_global_var(JSFunctionDef *fd, JSAtom name)\n{\n    JSGlobalVar *hf = find_global_var(fd, name);\n    if (hf && hf->is_lexical)\n        return hf;\n    else\n        return NULL;\n}\n\nstatic int find_lexical_decl(JSContext *ctx, JSFunctionDef *fd, JSAtom name,\n                             int scope_idx, BOOL check_catch_var)\n{\n    while (scope_idx >= 0) {\n        JSVarDef *vd = &fd->vars[scope_idx];\n        if (vd->var_name == name &&\n            (vd->is_lexical || (vd->var_kind == JS_VAR_CATCH &&\n                                check_catch_var)))\n            return scope_idx;\n        scope_idx = vd->scope_next;\n    }\n\n    if (fd->is_eval && fd->eval_type == JS_EVAL_TYPE_GLOBAL) {\n        if (find_lexical_global_var(fd, name))\n            return GLOBAL_VAR_OFFSET;\n    }\n    return -1;\n}\n\nstatic int push_scope(JSParseState *s) {\n    if (s->cur_func) {\n        JSFunctionDef *fd = s->cur_func;\n        int scope = fd->scope_count;\n        /* XXX: should check for scope overflow */\n        if ((fd->scope_count + 1) > fd->scope_size) {\n            int new_size;\n            size_t slack;\n            JSVarScope *new_buf;\n            /* XXX: potential arithmetic overflow */\n            new_size = max_int(fd->scope_count + 1, fd->scope_size * 3 / 2);\n            if (fd->scopes == fd->def_scope_array) {\n                new_buf = js_realloc2(s->ctx, NULL, new_size * sizeof(*fd->scopes), &slack);\n                if (!new_buf)\n                    return -1;\n                memcpy(new_buf, fd->scopes, fd->scope_count * sizeof(*fd->scopes));\n            } else {\n                new_buf = js_realloc2(s->ctx, fd->scopes, new_size * sizeof(*fd->scopes), &slack);\n                if (!new_buf)\n                    return -1;\n            }\n            new_size += slack / sizeof(*new_buf);\n            fd->scopes = new_buf;\n            fd->scope_size = new_size;\n        }\n        fd->scope_count++;\n        fd->scopes[scope].parent = fd->scope_level;\n        fd->scopes[scope].first = fd->scope_first;\n        emit_op(s, OP_enter_scope);\n        emit_u16(s, scope);\n        return fd->scope_level = scope;\n    }\n    return 0;\n}\n\nstatic int get_first_lexical_var(JSFunctionDef *fd, int scope)\n{\n    while (scope >= 0) {\n        int scope_idx = fd->scopes[scope].first;\n        if (scope_idx >= 0)\n            return scope_idx;\n        scope = fd->scopes[scope].parent;\n    }\n    return -1;\n}\n\nstatic void pop_scope(JSParseState *s) {\n    if (s->cur_func) {\n        /* disable scoped variables */\n        JSFunctionDef *fd = s->cur_func;\n        int scope = fd->scope_level;\n        emit_op(s, OP_leave_scope);\n        emit_u16(s, scope);\n        fd->scope_level = fd->scopes[scope].parent;\n        fd->scope_first = get_first_lexical_var(fd, fd->scope_level);\n    }\n}\n\nstatic void close_scopes(JSParseState *s, int scope, int scope_stop)\n{\n    while (scope > scope_stop) {\n        emit_op(s, OP_leave_scope);\n        emit_u16(s, scope);\n        scope = s->cur_func->scopes[scope].parent;\n    }\n}\n\n/* return the variable index or -1 if error */\nstatic int add_var(JSContext *ctx, JSFunctionDef *fd, JSAtom name)\n{\n    JSVarDef *vd;\n\n    /* the local variable indexes are currently stored on 16 bits */\n    if (fd->var_count >= JS_MAX_LOCAL_VARS) {\n        JS_ThrowInternalError(ctx, \"too many local variables\");\n        return -1;\n    }\n    if (js_resize_array(ctx, (void **)&fd->vars, sizeof(fd->vars[0]),\n                        &fd->var_size, fd->var_count + 1))\n        return -1;\n    vd = &fd->vars[fd->var_count++];\n    memset(vd, 0, sizeof(*vd));\n    vd->var_name = JS_DupAtom(ctx, name);\n    vd->func_pool_idx = -1;\n    return fd->var_count - 1;\n}\n\nstatic int add_scope_var(JSContext *ctx, JSFunctionDef *fd, JSAtom name,\n                         JSVarKindEnum var_kind)\n{\n    int idx = add_var(ctx, fd, name);\n    if (idx >= 0) {\n        JSVarDef *vd = &fd->vars[idx];\n        vd->var_kind = var_kind;\n        vd->scope_level = fd->scope_level;\n        vd->scope_next = fd->scope_first;\n        fd->scopes[fd->scope_level].first = idx;\n        fd->scope_first = idx;\n    }\n    return idx;\n}\n\nstatic int add_func_var(JSContext *ctx, JSFunctionDef *fd, JSAtom name)\n{\n    int idx = fd->func_var_idx;\n    if (idx < 0 && (idx = add_var(ctx, fd, name)) >= 0) {\n        fd->func_var_idx = idx;\n        fd->vars[idx].var_kind = JS_VAR_FUNCTION_NAME;\n        if (fd->js_mode & JS_MODE_STRICT)\n            fd->vars[idx].is_const = TRUE;\n    }\n    return idx;\n}\n\nstatic int add_arguments_var(JSContext *ctx, JSFunctionDef *fd)\n{\n    int idx = fd->arguments_var_idx;\n    if (idx < 0 && (idx = add_var(ctx, fd, JS_ATOM_arguments)) >= 0) {\n        fd->arguments_var_idx = idx;\n    }\n    return idx;\n}\n\n/* add an argument definition in the argument scope. Only needed when\n   \"eval()\" may be called in the argument scope. Return 0 if OK. */\nstatic int add_arguments_arg(JSContext *ctx, JSFunctionDef *fd)\n{\n    int idx;\n    if (fd->arguments_arg_idx < 0) {\n        idx = find_var_in_scope(ctx, fd, JS_ATOM_arguments, ARG_SCOPE_INDEX);\n        if (idx < 0) {\n            /* XXX: the scope links are not fully updated. May be an\n               issue if there are child scopes of the argument\n               scope */\n            idx = add_var(ctx, fd, JS_ATOM_arguments);\n            if (idx < 0)\n                return -1;\n            fd->vars[idx].scope_next = fd->scopes[ARG_SCOPE_INDEX].first;\n            fd->scopes[ARG_SCOPE_INDEX].first = idx;\n            fd->vars[idx].scope_level = ARG_SCOPE_INDEX;\n            fd->vars[idx].is_lexical = TRUE;\n\n            fd->arguments_arg_idx = idx;\n        }\n    }\n    return 0;\n}\n\nstatic int add_arg(JSContext *ctx, JSFunctionDef *fd, JSAtom name)\n{\n    JSVarDef *vd;\n\n    /* the local variable indexes are currently stored on 16 bits */\n    if (fd->arg_count >= JS_MAX_LOCAL_VARS) {\n        JS_ThrowInternalError(ctx, \"too many arguments\");\n        return -1;\n    }\n    if (js_resize_array(ctx, (void **)&fd->args, sizeof(fd->args[0]),\n                        &fd->arg_size, fd->arg_count + 1))\n        return -1;\n    vd = &fd->args[fd->arg_count++];\n    memset(vd, 0, sizeof(*vd));\n    vd->var_name = JS_DupAtom(ctx, name);\n    vd->func_pool_idx = -1;\n    return fd->arg_count - 1;\n}\n\n/* add a global variable definition */\nstatic JSGlobalVar *add_global_var(JSContext *ctx, JSFunctionDef *s,\n                                     JSAtom name)\n{\n    JSGlobalVar *hf;\n\n    if (js_resize_array(ctx, (void **)&s->global_vars,\n                        sizeof(s->global_vars[0]),\n                        &s->global_var_size, s->global_var_count + 1))\n        return NULL;\n    hf = &s->global_vars[s->global_var_count++];\n    hf->cpool_idx = -1;\n    hf->force_init = FALSE;\n    hf->is_lexical = FALSE;\n    hf->is_const = FALSE;\n    hf->scope_level = s->scope_level;\n    hf->var_name = JS_DupAtom(ctx, name);\n    return hf;\n}\n\ntypedef enum {\n    JS_VAR_DEF_WITH,\n    JS_VAR_DEF_LET,\n    JS_VAR_DEF_CONST,\n    JS_VAR_DEF_FUNCTION_DECL, /* function declaration */\n    JS_VAR_DEF_NEW_FUNCTION_DECL, /* async/generator function declaration */\n    JS_VAR_DEF_CATCH,\n    JS_VAR_DEF_VAR,\n} JSVarDefEnum;\n\nstatic int define_var(JSParseState *s, JSFunctionDef *fd, JSAtom name,\n                      JSVarDefEnum var_def_type)\n{\n    JSContext *ctx = s->ctx;\n    JSVarDef *vd;\n    int idx;\n\n    switch (var_def_type) {\n    case JS_VAR_DEF_WITH:\n        idx = add_scope_var(ctx, fd, name, JS_VAR_NORMAL);\n        break;\n\n    case JS_VAR_DEF_LET:\n    case JS_VAR_DEF_CONST:\n    case JS_VAR_DEF_FUNCTION_DECL:\n    case JS_VAR_DEF_NEW_FUNCTION_DECL:\n        idx = find_lexical_decl(ctx, fd, name, fd->scope_first, TRUE);\n        if (idx >= 0) {\n            if (idx < GLOBAL_VAR_OFFSET) {\n                if (fd->vars[idx].scope_level == fd->scope_level) {\n                    /* same scope: in non strict mode, functions\n                       can be redefined (annex B.3.3.4). */\n                    if (!(!(fd->js_mode & JS_MODE_STRICT) &&\n                          var_def_type == JS_VAR_DEF_FUNCTION_DECL &&\n                          fd->vars[idx].var_kind == JS_VAR_FUNCTION_DECL)) {\n                        goto redef_lex_error;\n                    }\n                } else if (fd->vars[idx].var_kind == JS_VAR_CATCH && (fd->vars[idx].scope_level + 2) == fd->scope_level) {\n                    goto redef_lex_error;\n                }\n            } else {\n                if (fd->scope_level == fd->body_scope) {\n                redef_lex_error:\n                    /* redefining a scoped var in the same scope: error */\n                    return js_parse_error(s, \"invalid redefinition of lexical identifier\");\n                }\n            }\n        }\n        if (var_def_type != JS_VAR_DEF_FUNCTION_DECL &&\n            var_def_type != JS_VAR_DEF_NEW_FUNCTION_DECL &&\n            fd->scope_level == fd->body_scope &&\n            find_arg(ctx, fd, name) >= 0) {\n            /* lexical variable redefines a parameter name */\n            return js_parse_error(s, \"invalid redefinition of parameter name\");\n        }\n\n        if (find_var_in_child_scope(ctx, fd, name, fd->scope_level) >= 0) {\n            return js_parse_error(s, \"invalid redefinition of a variable\");\n        }\n        \n        if (fd->is_global_var) {\n            JSGlobalVar *hf;\n            hf = find_global_var(fd, name);\n            if (hf && is_child_scope(ctx, fd, hf->scope_level,\n                                     fd->scope_level)) {\n                return js_parse_error(s, \"invalid redefinition of global identifier\");\n            }\n        }\n        \n        if (fd->is_eval &&\n            (fd->eval_type == JS_EVAL_TYPE_GLOBAL ||\n             fd->eval_type == JS_EVAL_TYPE_MODULE) &&\n            fd->scope_level == fd->body_scope) {\n            JSGlobalVar *hf;\n            hf = add_global_var(s->ctx, fd, name);\n            if (!hf)\n                return -1;\n            hf->is_lexical = TRUE;\n            hf->is_const = (var_def_type == JS_VAR_DEF_CONST);\n            idx = GLOBAL_VAR_OFFSET;\n        } else {\n            JSVarKindEnum var_kind;\n            if (var_def_type == JS_VAR_DEF_FUNCTION_DECL)\n                var_kind = JS_VAR_FUNCTION_DECL;\n            else if (var_def_type == JS_VAR_DEF_NEW_FUNCTION_DECL)\n                var_kind = JS_VAR_NEW_FUNCTION_DECL;\n            else\n                var_kind = JS_VAR_NORMAL;\n            idx = add_scope_var(ctx, fd, name, var_kind);\n            if (idx >= 0) {\n                vd = &fd->vars[idx];\n                vd->is_lexical = 1;\n                vd->is_const = (var_def_type == JS_VAR_DEF_CONST);\n            }\n        }\n        break;\n\n    case JS_VAR_DEF_CATCH:\n        idx = add_scope_var(ctx, fd, name, JS_VAR_CATCH);\n        break;\n\n    case JS_VAR_DEF_VAR:\n        if (find_lexical_decl(ctx, fd, name, fd->scope_first,\n                              FALSE) >= 0) {\n       invalid_lexical_redefinition:\n            /* error to redefine a var that inside a lexical scope */\n            return js_parse_error(s, \"invalid redefinition of lexical identifier\");\n        }\n        if (fd->is_global_var) {\n            JSGlobalVar *hf;\n            hf = find_global_var(fd, name);\n            if (hf && hf->is_lexical && hf->scope_level == fd->scope_level &&\n                fd->eval_type == JS_EVAL_TYPE_MODULE) {\n                goto invalid_lexical_redefinition;\n            }\n            hf = add_global_var(s->ctx, fd, name);\n            if (!hf)\n                return -1;\n            idx = GLOBAL_VAR_OFFSET;\n        } else {\n            /* if the variable already exists, don't add it again  */\n            idx = find_var(ctx, fd, name);\n            if (idx >= 0)\n                break;\n            idx = add_var(ctx, fd, name);\n            if (idx >= 0) {\n                if (name == JS_ATOM_arguments && fd->has_arguments_binding)\n                    fd->arguments_var_idx = idx;\n                fd->vars[idx].scope_next = fd->scope_level;\n            }\n        }\n        break;\n    default:\n        abort();\n    }\n    return idx;\n}\n\n/* add a private field variable in the current scope */\nstatic int add_private_class_field(JSParseState *s, JSFunctionDef *fd,\n                                   JSAtom name, JSVarKindEnum var_kind)\n{\n    JSContext *ctx = s->ctx;\n    JSVarDef *vd;\n    int idx;\n\n    idx = add_scope_var(ctx, fd, name, var_kind);\n    if (idx < 0)\n        return idx;\n    vd = &fd->vars[idx];\n    vd->is_lexical = 1;\n    vd->is_const = 1;\n    return idx;\n}\n\nstatic __exception int js_parse_expr(JSParseState *s);\nstatic __exception int js_parse_function_decl(JSParseState *s,\n                                              JSParseFunctionEnum func_type,\n                                              JSFunctionKindEnum func_kind,\n                                              JSAtom func_name, const uint8_t *ptr,\n                                              int start_line);\nstatic JSFunctionDef *js_parse_function_class_fields_init(JSParseState *s);\nstatic __exception int js_parse_function_decl2(JSParseState *s,\n                                               JSParseFunctionEnum func_type,\n                                               JSFunctionKindEnum func_kind,\n                                               JSAtom func_name,\n                                               const uint8_t *ptr,\n                                               int function_line_num,\n                                               JSParseExportEnum export_flag,\n                                               JSFunctionDef **pfd);\nstatic __exception int js_parse_assign_expr2(JSParseState *s, int parse_flags);\nstatic __exception int js_parse_assign_expr(JSParseState *s);\nstatic __exception int js_parse_unary(JSParseState *s, int parse_flags);\nstatic void push_break_entry(JSFunctionDef *fd, BlockEnv *be,\n                             JSAtom label_name,\n                             int label_break, int label_cont,\n                             int drop_count);\nstatic void pop_break_entry(JSFunctionDef *fd);\nstatic JSExportEntry *add_export_entry(JSParseState *s, JSModuleDef *m,\n                                       JSAtom local_name, JSAtom export_name,\n                                       JSExportTypeEnum export_type);\n\n/* Note: all the fields are already sealed except length */\nstatic int seal_template_obj(JSContext *ctx, JSValueConst obj)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n\n    p = JS_VALUE_GET_OBJ(obj);\n    prs = find_own_property1(p, JS_ATOM_length);\n    if (prs) {\n        if (js_update_property_flags(ctx, p, &prs,\n                                     prs->flags & ~(JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)))\n            return -1;\n    }\n    p->extensible = FALSE;\n    return 0;\n}\n\nstatic __exception int js_parse_template(JSParseState *s, int call, int *argc)\n{\n    JSContext *ctx = s->ctx;\n    JSValue raw_array, template_object;\n    JSToken cooked;\n    int depth, ret;\n\n    raw_array = JS_UNDEFINED; /* avoid warning */\n    template_object = JS_UNDEFINED; /* avoid warning */\n    if (call) {\n        /* Create a template object: an array of cooked strings */\n        /* Create an array of raw strings and store it to the raw property */\n        template_object = JS_NewArray(ctx);\n        if (JS_IsException(template_object))\n            return -1;\n        //        pool_idx = s->cur_func->cpool_count;\n        ret = emit_push_const(s, template_object, 0);\n        JS_FreeValue(ctx, template_object);\n        if (ret)\n            return -1;\n        raw_array = JS_NewArray(ctx);\n        if (JS_IsException(raw_array))\n            return -1;\n        if (JS_DefinePropertyValue(ctx, template_object, JS_ATOM_raw,\n                                   raw_array, JS_PROP_THROW) < 0) {\n            return -1;\n        }\n    }\n\n    depth = 0;\n    while (s->token.val == TOK_TEMPLATE) {\n        const uint8_t *p = s->token.ptr + 1;\n        cooked = s->token;\n        if (call) {\n            if (JS_DefinePropertyValueUint32(ctx, raw_array, depth,\n                                             JS_DupValue(ctx, s->token.u.str.str),\n                                             JS_PROP_ENUMERABLE | JS_PROP_THROW) < 0) {\n                return -1;\n            }\n            /* re-parse the string with escape sequences but do not throw a\n               syntax error if it contains invalid sequences\n             */\n            if (js_parse_string(s, '`', FALSE, p, &cooked, &p)) {\n                cooked.u.str.str = JS_UNDEFINED;\n            }\n            if (JS_DefinePropertyValueUint32(ctx, template_object, depth,\n                                             cooked.u.str.str,\n                                             JS_PROP_ENUMERABLE | JS_PROP_THROW) < 0) {\n                return -1;\n            }\n        } else {\n            JSString *str;\n            /* re-parse the string with escape sequences and throw a\n               syntax error if it contains invalid sequences\n             */\n            JS_FreeValue(ctx, s->token.u.str.str);\n            s->token.u.str.str = JS_UNDEFINED;\n            if (js_parse_string(s, '`', TRUE, p, &cooked, &p))\n                return -1;\n            str = JS_VALUE_GET_STRING(cooked.u.str.str);\n            if (str->len != 0 || depth == 0) {\n                ret = emit_push_const(s, cooked.u.str.str, 1);\n                JS_FreeValue(s->ctx, cooked.u.str.str);\n                if (ret)\n                    return -1;\n                if (depth == 0) {\n                    if (s->token.u.str.sep == '`')\n                        goto done1;\n                    emit_op(s, OP_get_field2);\n                    emit_atom(s, JS_ATOM_concat);\n                }\n                depth++;\n            } else {\n                JS_FreeValue(s->ctx, cooked.u.str.str);\n            }\n        }\n        if (s->token.u.str.sep == '`')\n            goto done;\n        if (next_token(s))\n            return -1;\n        if (js_parse_expr(s))\n            return -1;\n        depth++;\n        if (s->token.val != '}') {\n            return js_parse_error(s, \"expected '}' after template expression\");\n        }\n        /* XXX: should convert to string at this stage? */\n        free_token(s, &s->token);\n        /* Resume TOK_TEMPLATE parsing (s->token.line_num and\n         * s->token.ptr are OK) */\n        s->got_lf = FALSE;\n        s->last_line_num = s->token.line_num;\n        if (js_parse_template_part(s, s->buf_ptr))\n            return -1;\n    }\n    return js_parse_expect(s, TOK_TEMPLATE);\n\n done:\n    if (call) {\n        /* Seal the objects */\n        seal_template_obj(ctx, raw_array);\n        seal_template_obj(ctx, template_object);\n        *argc = depth + 1;\n    } else {\n        emit_op(s, OP_call_method);\n        emit_u16(s, depth - 1);\n    }\n done1:\n    return next_token(s);\n}\n\n\n#define PROP_TYPE_IDENT 0\n#define PROP_TYPE_VAR   1\n#define PROP_TYPE_GET   2\n#define PROP_TYPE_SET   3\n#define PROP_TYPE_STAR  4\n#define PROP_TYPE_ASYNC 5\n#define PROP_TYPE_ASYNC_STAR 6\n\n#define PROP_TYPE_PRIVATE (1 << 4)\n\nstatic BOOL token_is_ident(int tok)\n{\n    /* Accept keywords and reserved words as property names */\n    return (tok == TOK_IDENT ||\n            (tok >= TOK_FIRST_KEYWORD &&\n             tok <= TOK_LAST_KEYWORD));\n}\n\n/* if the property is an expression, name = JS_ATOM_NULL */\nstatic int __exception js_parse_property_name(JSParseState *s,\n                                              JSAtom *pname,\n                                              BOOL allow_method, BOOL allow_var,\n                                              BOOL allow_private)\n{\n    int is_private = 0;\n    BOOL is_non_reserved_ident;\n    JSAtom name;\n    int prop_type;\n    \n    prop_type = PROP_TYPE_IDENT;\n    if (allow_method) {\n        if (token_is_pseudo_keyword(s, JS_ATOM_get)\n        ||  token_is_pseudo_keyword(s, JS_ATOM_set)) {\n            /* get x(), set x() */\n            name = JS_DupAtom(s->ctx, s->token.u.ident.atom);\n            if (next_token(s))\n                goto fail1;\n            if (s->token.val == ':' || s->token.val == ',' ||\n                s->token.val == '}' || s->token.val == '(') {\n                is_non_reserved_ident = TRUE;\n                goto ident_found;\n            }\n            prop_type = PROP_TYPE_GET + (name == JS_ATOM_set);\n            JS_FreeAtom(s->ctx, name);\n        } else if (s->token.val == '*') {\n            if (next_token(s))\n                goto fail;\n            prop_type = PROP_TYPE_STAR;\n        } else if (token_is_pseudo_keyword(s, JS_ATOM_async) &&\n                   peek_token(s, TRUE) != '\\n') {\n            name = JS_DupAtom(s->ctx, s->token.u.ident.atom);\n            if (next_token(s))\n                goto fail1;\n            if (s->token.val == ':' || s->token.val == ',' ||\n                s->token.val == '}' || s->token.val == '(') {\n                is_non_reserved_ident = TRUE;\n                goto ident_found;\n            }\n            JS_FreeAtom(s->ctx, name);\n            if (s->token.val == '*') {\n                if (next_token(s))\n                    goto fail;\n                prop_type = PROP_TYPE_ASYNC_STAR;\n            } else {\n                prop_type = PROP_TYPE_ASYNC;\n            }\n        }\n    }\n\n    if (token_is_ident(s->token.val)) {\n        /* variable can only be a non-reserved identifier */\n        is_non_reserved_ident =\n            (s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved);\n        /* keywords and reserved words have a valid atom */\n        name = JS_DupAtom(s->ctx, s->token.u.ident.atom);\n        if (next_token(s))\n            goto fail1;\n    ident_found:\n        if (is_non_reserved_ident &&\n            prop_type == PROP_TYPE_IDENT && allow_var) {\n            if (!(s->token.val == ':' ||\n                  (s->token.val == '(' && allow_method))) {\n                prop_type = PROP_TYPE_VAR;\n            }\n        }\n    } else if (s->token.val == TOK_STRING) {\n        name = JS_ValueToAtom(s->ctx, s->token.u.str.str);\n        if (name == JS_ATOM_NULL)\n            goto fail;\n        if (next_token(s))\n            goto fail1;\n    } else if (s->token.val == TOK_NUMBER) {\n        JSValue val;\n        val = s->token.u.num.val;\n#ifdef CONFIG_BIGNUM\n        if (JS_VALUE_GET_TAG(val) == JS_TAG_BIG_FLOAT) {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            val = s->ctx->rt->bigfloat_ops.\n                mul_pow10_to_float64(s->ctx, &p->num,\n                                     s->token.u.num.exponent);\n            if (JS_IsException(val))\n                goto fail;\n            name = JS_ValueToAtom(s->ctx, val);\n            JS_FreeValue(s->ctx, val);\n        } else\n#endif\n        {\n            name = JS_ValueToAtom(s->ctx, val);\n        }\n        if (name == JS_ATOM_NULL)\n            goto fail;\n        if (next_token(s))\n            goto fail1;\n    } else if (s->token.val == '[') {\n        if (next_token(s))\n            goto fail;\n        if (js_parse_expr(s))\n            goto fail;\n        if (js_parse_expect(s, ']'))\n            goto fail;\n        name = JS_ATOM_NULL;\n    } else if (s->token.val == TOK_PRIVATE_NAME && allow_private) {\n        name = JS_DupAtom(s->ctx, s->token.u.ident.atom);\n        if (next_token(s))\n            goto fail1;\n        is_private = PROP_TYPE_PRIVATE;\n    } else {\n        goto invalid_prop;\n    }\n    if (prop_type != PROP_TYPE_IDENT && prop_type != PROP_TYPE_VAR &&\n        s->token.val != '(') {\n        JS_FreeAtom(s->ctx, name);\n    invalid_prop:\n        js_parse_error(s, \"invalid property name\");\n        goto fail;\n    }\n    *pname = name;\n    return prop_type | is_private;\n fail1:\n    JS_FreeAtom(s->ctx, name);\n fail:\n    *pname = JS_ATOM_NULL;\n    return -1;\n}\n\ntypedef struct JSParsePos {\n    int last_line_num;\n    int line_num;\n    BOOL got_lf;\n    const uint8_t *ptr;\n} JSParsePos;\n\nstatic int js_parse_get_pos(JSParseState *s, JSParsePos *sp)\n{\n    sp->last_line_num = s->last_line_num;\n    sp->line_num = s->token.line_num;\n    sp->ptr = s->token.ptr;\n    sp->got_lf = s->got_lf;\n    return 0;\n}\n\nstatic __exception int js_parse_seek_token(JSParseState *s, const JSParsePos *sp)\n{\n    s->token.line_num = sp->last_line_num;\n    s->line_num = sp->line_num;\n    s->buf_ptr = sp->ptr;\n    s->got_lf = sp->got_lf;\n    return next_token(s);\n}\n\n/* return TRUE if a regexp literal is allowed after this token */\nstatic BOOL is_regexp_allowed(int tok)\n{\n    switch (tok) {\n    case TOK_NUMBER:\n    case TOK_STRING:\n    case TOK_REGEXP:\n    case TOK_DEC:\n    case TOK_INC:\n    case TOK_NULL:\n    case TOK_FALSE:\n    case TOK_TRUE:\n    case TOK_THIS:\n    case ')':\n    case ']':\n    case '}': /* XXX: regexp may occur after */\n    case TOK_IDENT:\n        return FALSE;\n    default:\n        return TRUE;\n    }\n}\n\n#define SKIP_HAS_SEMI       (1 << 0)\n#define SKIP_HAS_ELLIPSIS   (1 << 1)\n#define SKIP_HAS_ASSIGNMENT (1 << 2)\n\n/* XXX: improve speed with early bailout */\n/* XXX: no longer works if regexps are present. Could use previous\n   regexp parsing heuristics to handle most cases */\nstatic int js_parse_skip_parens_token(JSParseState *s, int *pbits, BOOL no_line_terminator)\n{\n    char state[256];\n    size_t level = 0;\n    JSParsePos pos;\n    int last_tok, tok = TOK_EOF;\n    int c, tok_len, bits = 0;\n\n    /* protect from underflow */\n    state[level++] = 0;\n\n    js_parse_get_pos(s, &pos);\n    last_tok = 0;\n    for (;;) {\n        switch(s->token.val) {\n        case '(':\n        case '[':\n        case '{':\n            if (level >= sizeof(state))\n                goto done;\n            state[level++] = s->token.val;\n            break;\n        case ')':\n            if (state[--level] != '(')\n                goto done;\n            break;\n        case ']':\n            if (state[--level] != '[')\n                goto done;\n            break;\n        case '}':\n            c = state[--level];\n            if (c == '`') {\n                /* continue the parsing of the template */\n                free_token(s, &s->token);\n                /* Resume TOK_TEMPLATE parsing (s->token.line_num and\n                 * s->token.ptr are OK) */\n                s->got_lf = FALSE;\n                s->last_line_num = s->token.line_num;\n                if (js_parse_template_part(s, s->buf_ptr))\n                    goto done;\n                goto handle_template;\n            } else if (c != '{') {\n                goto done;\n            }\n            break;\n        case TOK_TEMPLATE:\n        handle_template:\n            if (s->token.u.str.sep != '`') {\n                /* '${' inside the template : closing '}' and continue\n                   parsing the template */\n                if (level >= sizeof(state))\n                    goto done;\n                state[level++] = '`';\n            } \n            break;\n        case TOK_EOF:\n            goto done;\n        case ';':\n            if (level == 2) {\n                bits |= SKIP_HAS_SEMI;\n            }\n            break;\n        case TOK_ELLIPSIS:\n            if (level == 2) {\n                bits |= SKIP_HAS_ELLIPSIS;\n            }\n            break;\n        case '=':\n            bits |= SKIP_HAS_ASSIGNMENT;\n            break;\n            \n        case TOK_DIV_ASSIGN:\n            tok_len = 2;\n            goto parse_regexp;\n        case '/':\n            tok_len = 1;\n        parse_regexp:\n            if (is_regexp_allowed(last_tok)) {\n                s->buf_ptr -= tok_len;\n                if (js_parse_regexp(s)) {\n                    /* XXX: should clear the exception */\n                    goto done;\n                }\n            }\n            break;\n        }\n        /* last_tok is only used to recognize regexps */\n        if (s->token.val == TOK_IDENT &&\n            (token_is_pseudo_keyword(s, JS_ATOM_of) ||\n             token_is_pseudo_keyword(s, JS_ATOM_yield))) {\n            last_tok = TOK_OF;\n        } else {\n            last_tok = s->token.val;\n        }\n        if (next_token(s)) {\n            /* XXX: should clear the exception generated by next_token() */\n            break;\n        }\n        if (level <= 1) {\n            tok = s->token.val;\n            if (token_is_pseudo_keyword(s, JS_ATOM_of))\n                tok = TOK_OF;\n            if (no_line_terminator && s->last_line_num != s->token.line_num)\n                tok = '\\n';\n            break;\n        }\n    }\n done:\n    if (pbits) {\n        *pbits = bits;\n    }\n    if (js_parse_seek_token(s, &pos))\n        return -1;\n    return tok;\n}\n\nstatic void set_object_name(JSParseState *s, JSAtom name)\n{\n    JSFunctionDef *fd = s->cur_func;\n    int opcode;\n\n    opcode = get_prev_opcode(fd);\n    if (opcode == OP_set_name) {\n        /* XXX: should free atom after OP_set_name? */\n        fd->byte_code.size = fd->last_opcode_pos;\n        fd->last_opcode_pos = -1;\n        emit_op(s, OP_set_name);\n        emit_atom(s, name);\n    } else if (opcode == OP_set_class_name) {\n        int define_class_pos;\n        JSAtom atom;\n        define_class_pos = fd->last_opcode_pos + 1 -\n            get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);\n        assert(fd->byte_code.buf[define_class_pos] == OP_define_class);\n        /* for consistency we free the previous atom which is\n           JS_ATOM_empty_string */\n        atom = get_u32(fd->byte_code.buf + define_class_pos + 1);\n        JS_FreeAtom(s->ctx, atom);\n        put_u32(fd->byte_code.buf + define_class_pos + 1,\n                JS_DupAtom(s->ctx, name));\n        fd->last_opcode_pos = -1;\n    }\n}\n\nstatic void set_object_name_computed(JSParseState *s)\n{\n    JSFunctionDef *fd = s->cur_func;\n    int opcode;\n\n    opcode = get_prev_opcode(fd);\n    if (opcode == OP_set_name) {\n        /* XXX: should free atom after OP_set_name? */\n        fd->byte_code.size = fd->last_opcode_pos;\n        fd->last_opcode_pos = -1;\n        emit_op(s, OP_set_name_computed);\n    } else if (opcode == OP_set_class_name) {\n        int define_class_pos;\n        define_class_pos = fd->last_opcode_pos + 1 -\n            get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);\n        assert(fd->byte_code.buf[define_class_pos] == OP_define_class);\n        fd->byte_code.buf[define_class_pos] = OP_define_class_computed;\n        fd->last_opcode_pos = -1;\n    }\n}\n\nstatic __exception int js_parse_object_literal(JSParseState *s)\n{\n    JSAtom name = JS_ATOM_NULL;\n    const uint8_t *start_ptr;\n    int start_line, prop_type;\n    BOOL has_proto;\n\n    if (next_token(s))\n        goto fail;\n    /* XXX: add an initial length that will be patched back */\n    emit_op(s, OP_object);\n    has_proto = FALSE;\n    while (s->token.val != '}') {\n        /* specific case for getter/setter */\n        start_ptr = s->token.ptr;\n        start_line = s->token.line_num;\n\n        if (s->token.val == TOK_ELLIPSIS) {\n            if (next_token(s))\n                return -1;\n            if (js_parse_assign_expr(s))\n                return -1;\n            emit_op(s, OP_null);  /* dummy excludeList */\n            emit_op(s, OP_copy_data_properties);\n            emit_u8(s, 2 | (1 << 2) | (0 << 5));\n            emit_op(s, OP_drop); /* pop excludeList */\n            emit_op(s, OP_drop); /* pop src object */\n            goto next;\n        }\n\n        prop_type = js_parse_property_name(s, &name, TRUE, TRUE, FALSE);\n        if (prop_type < 0)\n            goto fail;\n\n        if (prop_type == PROP_TYPE_VAR) {\n            /* shortcut for x: x */\n            emit_op(s, OP_scope_get_var);\n            emit_atom(s, name);\n            emit_u16(s, s->cur_func->scope_level);\n            emit_op(s, OP_define_field);\n            emit_atom(s, name);\n        } else if (s->token.val == '(') {\n            BOOL is_getset = (prop_type == PROP_TYPE_GET ||\n                              prop_type == PROP_TYPE_SET);\n            JSParseFunctionEnum func_type;\n            JSFunctionKindEnum func_kind;\n            int op_flags;\n\n            func_kind = JS_FUNC_NORMAL;\n            if (is_getset) {\n                func_type = JS_PARSE_FUNC_GETTER + prop_type - PROP_TYPE_GET;\n            } else {\n                func_type = JS_PARSE_FUNC_METHOD;\n                if (prop_type == PROP_TYPE_STAR)\n                    func_kind = JS_FUNC_GENERATOR;\n                else if (prop_type == PROP_TYPE_ASYNC)\n                    func_kind = JS_FUNC_ASYNC;\n                else if (prop_type == PROP_TYPE_ASYNC_STAR)\n                    func_kind = JS_FUNC_ASYNC_GENERATOR;\n            }\n            if (js_parse_function_decl(s, func_type, func_kind, JS_ATOM_NULL,\n                                       start_ptr, start_line))\n                goto fail;\n            if (name == JS_ATOM_NULL) {\n                emit_op(s, OP_define_method_computed);\n            } else {\n                emit_op(s, OP_define_method);\n                emit_atom(s, name);\n            }\n            if (is_getset) {\n                op_flags = OP_DEFINE_METHOD_GETTER +\n                    prop_type - PROP_TYPE_GET;\n            } else {\n                op_flags = OP_DEFINE_METHOD_METHOD;\n            }\n            emit_u8(s, op_flags | OP_DEFINE_METHOD_ENUMERABLE);\n        } else {\n            if (js_parse_expect(s, ':'))\n                goto fail;\n            if (js_parse_assign_expr(s))\n                goto fail;\n            if (name == JS_ATOM_NULL) {\n                set_object_name_computed(s);\n                emit_op(s, OP_define_array_el);\n                emit_op(s, OP_drop);\n            } else if (name == JS_ATOM___proto__) {\n                if (has_proto) {\n                    js_parse_error(s, \"duplicate __proto__ property name\");\n                    goto fail;\n                }\n                emit_op(s, OP_set_proto);\n                has_proto = TRUE;\n            } else {\n                set_object_name(s, name);\n                emit_op(s, OP_define_field);\n                emit_atom(s, name);\n            }\n        }\n        JS_FreeAtom(s->ctx, name);\n    next:\n        name = JS_ATOM_NULL;\n        if (s->token.val != ',')\n            break;\n        if (next_token(s))\n            goto fail;\n    }\n    if (js_parse_expect(s, '}'))\n        goto fail;\n    return 0;\n fail:\n    JS_FreeAtom(s->ctx, name);\n    return -1;\n}\n\n/* allow the 'in' binary operator */\n#define PF_IN_ACCEPTED  (1 << 0) \n/* allow function calls parsing in js_parse_postfix_expr() */\n#define PF_POSTFIX_CALL (1 << 1) \n/* allow arrow functions parsing in js_parse_postfix_expr() */\n#define PF_ARROW_FUNC   (1 << 2) \n/* allow the exponentiation operator in js_parse_unary() */\n#define PF_POW_ALLOWED  (1 << 3) \n/* forbid the exponentiation operator in js_parse_unary() */\n#define PF_POW_FORBIDDEN (1 << 4) \n\nstatic __exception int js_parse_postfix_expr(JSParseState *s, int parse_flags);\n\nstatic __exception int js_parse_left_hand_side_expr(JSParseState *s)\n{\n    return js_parse_postfix_expr(s, PF_POSTFIX_CALL);\n}\n\n/* XXX: could generate specific bytecode */\nstatic __exception int js_parse_class_default_ctor(JSParseState *s,\n                                                   BOOL has_super,\n                                                   JSFunctionDef **pfd)\n{\n    JSParsePos pos;\n    const char *str;\n    int ret, line_num;\n    JSParseFunctionEnum func_type;\n    const uint8_t *saved_buf_end;\n    \n    js_parse_get_pos(s, &pos);\n    if (has_super) {\n        /* spec change: no argument evaluation */\n        str = \"(){super(...arguments);}\";\n        func_type = JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR;\n    } else {\n        str = \"(){}\";\n        func_type = JS_PARSE_FUNC_CLASS_CONSTRUCTOR;\n    }\n    line_num = s->token.line_num;\n    saved_buf_end = s->buf_end;\n    s->buf_ptr = (uint8_t *)str;\n    s->buf_end = (uint8_t *)(str + strlen(str));\n    ret = next_token(s);\n    if (!ret) {\n        ret = js_parse_function_decl2(s, func_type, JS_FUNC_NORMAL,\n                                      JS_ATOM_NULL, (uint8_t *)str,\n                                      line_num, JS_PARSE_EXPORT_NONE, pfd);\n    }\n    s->buf_end = saved_buf_end;\n    ret |= js_parse_seek_token(s, &pos);\n    return ret;\n}\n\n/* find field in the current scope */\nstatic int find_private_class_field(JSContext *ctx, JSFunctionDef *fd,\n                                    JSAtom name, int scope_level)\n{\n    int idx;\n    idx = fd->scopes[scope_level].first;\n    while (idx != -1) {\n        if (fd->vars[idx].scope_level != scope_level)\n            break;\n        if (fd->vars[idx].var_name == name)\n            return idx;\n        idx = fd->vars[idx].scope_next;\n    }\n    return -1;\n}\n\n/* initialize the class fields, called by the constructor. Note:\n   super() can be called in an arrow function, so <this> and\n   <class_fields_init> can be variable references */\nstatic void emit_class_field_init(JSParseState *s)\n{\n    int label_next;\n    \n    emit_op(s, OP_scope_get_var);\n    emit_atom(s, JS_ATOM_class_fields_init);\n    emit_u16(s, s->cur_func->scope_level);\n\n    /* no need to call the class field initializer if not defined */\n    emit_op(s, OP_dup);\n    label_next = emit_goto(s, OP_if_false, -1);\n    \n    emit_op(s, OP_scope_get_var);\n    emit_atom(s, JS_ATOM_this);\n    emit_u16(s, 0);\n    \n    emit_op(s, OP_swap);\n    \n    emit_op(s, OP_call_method);\n    emit_u16(s, 0);\n\n    emit_label(s, label_next);\n    emit_op(s, OP_drop);\n}\n\n/* build a private setter function name from the private getter name */\nstatic JSAtom get_private_setter_name(JSContext *ctx, JSAtom name)\n{\n    return js_atom_concat_str(ctx, name, \"<set>\");\n}\n\ntypedef struct {\n    JSFunctionDef *fields_init_fd;\n    int computed_fields_count;\n    BOOL has_brand;\n    int brand_push_pos;\n} ClassFieldsDef;\n\nstatic __exception int emit_class_init_start(JSParseState *s,\n                                             ClassFieldsDef *cf)\n{\n    int label_add_brand;\n    \n    cf->fields_init_fd = js_parse_function_class_fields_init(s);\n    if (!cf->fields_init_fd)\n        return -1;\n\n    s->cur_func = cf->fields_init_fd;\n    \n    /* XXX: would be better to add the code only if needed, maybe in a\n       later pass */\n    emit_op(s, OP_push_false); /* will be patched later */\n    cf->brand_push_pos = cf->fields_init_fd->last_opcode_pos;\n    label_add_brand = emit_goto(s, OP_if_false, -1);\n    \n    emit_op(s, OP_scope_get_var);\n    emit_atom(s, JS_ATOM_this);\n    emit_u16(s, 0);\n    \n    emit_op(s, OP_scope_get_var);\n    emit_atom(s, JS_ATOM_home_object);\n    emit_u16(s, 0);\n    \n    emit_op(s, OP_add_brand);\n    \n    emit_label(s, label_add_brand);\n\n    s->cur_func = s->cur_func->parent;\n    return 0;\n}\n\nstatic __exception int add_brand(JSParseState *s, ClassFieldsDef *cf)\n{\n    if (!cf->has_brand) {\n        /* define the brand field in 'this' of the initializer */\n        if (!cf->fields_init_fd) {\n            if (emit_class_init_start(s, cf))\n                return -1;\n        }\n        /* patch the start of the function to enable the OP_add_brand code */\n        cf->fields_init_fd->byte_code.buf[cf->brand_push_pos] = OP_push_true;\n        \n        cf->has_brand = TRUE;\n    }\n    return 0;\n}\n\nstatic void emit_class_init_end(JSParseState *s, ClassFieldsDef *cf)\n{\n    int cpool_idx;\n        \n    s->cur_func = cf->fields_init_fd;\n    emit_op(s, OP_return_undef);\n    s->cur_func = s->cur_func->parent;\n    \n    cpool_idx = cpool_add(s, JS_NULL);\n    cf->fields_init_fd->parent_cpool_idx = cpool_idx;\n    emit_op(s, OP_fclosure);\n    emit_u32(s, cpool_idx);\n    emit_op(s, OP_set_home_object);\n}\n\n\nstatic __exception int js_parse_class(JSParseState *s, BOOL is_class_expr,\n                                      JSParseExportEnum export_flag)\n{\n    JSContext *ctx = s->ctx;\n    JSFunctionDef *fd = s->cur_func;\n    JSAtom name = JS_ATOM_NULL, class_name = JS_ATOM_NULL, class_name1;\n    JSAtom class_var_name = JS_ATOM_NULL;\n    JSFunctionDef *method_fd, *ctor_fd;\n    int saved_js_mode, class_name_var_idx, prop_type, ctor_cpool_offset;\n    int class_flags = 0, i, define_class_offset;\n    BOOL is_static, is_private;\n    const uint8_t *class_start_ptr = s->token.ptr;\n    const uint8_t *start_ptr;\n    ClassFieldsDef class_fields[2];\n        \n    /* classes are parsed and executed in strict mode */\n    saved_js_mode = fd->js_mode;\n    fd->js_mode |= JS_MODE_STRICT;\n    if (next_token(s))\n        goto fail;\n    if (s->token.val == TOK_IDENT) {\n        if (s->token.u.ident.is_reserved) {\n            js_parse_error_reserved_identifier(s);\n            goto fail;\n        }\n        class_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n        if (next_token(s))\n            goto fail;\n    } else if (!is_class_expr && export_flag != JS_PARSE_EXPORT_DEFAULT) {\n        js_parse_error(s, \"class statement requires a name\");\n        goto fail;\n    }\n    if (!is_class_expr) {\n        if (class_name == JS_ATOM_NULL)\n            class_var_name = JS_ATOM__default_; /* export default */\n        else\n            class_var_name = class_name;\n        class_var_name = JS_DupAtom(ctx, class_var_name);\n    }\n\n    push_scope(s);\n\n    if (s->token.val == TOK_EXTENDS) {\n        class_flags = JS_DEFINE_CLASS_HAS_HERITAGE;\n        if (next_token(s))\n            goto fail;\n        if (js_parse_left_hand_side_expr(s))\n            goto fail;\n    } else {\n        emit_op(s, OP_undefined);\n    }\n\n    /* add a 'const' definition for the class name */\n    if (class_name != JS_ATOM_NULL) {\n        class_name_var_idx = define_var(s, fd, class_name, JS_VAR_DEF_CONST);\n        if (class_name_var_idx < 0)\n            goto fail;\n    }\n\n    if (js_parse_expect(s, '{'))\n        goto fail;\n\n    /* this scope contains the private fields */\n    push_scope(s);\n\n    emit_op(s, OP_push_const);\n    ctor_cpool_offset = fd->byte_code.size;\n    emit_u32(s, 0); /* will be patched at the end of the class parsing */\n\n    if (class_name == JS_ATOM_NULL) {\n        if (class_var_name != JS_ATOM_NULL)\n            class_name1 = JS_ATOM_default;\n        else\n            class_name1 = JS_ATOM_empty_string;\n    } else {\n        class_name1 = class_name;\n    }\n    \n    emit_op(s, OP_define_class);\n    emit_atom(s, class_name1);\n    emit_u8(s, class_flags);\n    define_class_offset = fd->last_opcode_pos;\n\n    for(i = 0; i < 2; i++) {\n        ClassFieldsDef *cf = &class_fields[i];\n        cf->fields_init_fd = NULL;\n        cf->computed_fields_count = 0;\n        cf->has_brand = FALSE;\n    }\n    \n    ctor_fd = NULL;\n    while (s->token.val != '}') {\n        if (s->token.val == ';') {\n            if (next_token(s))\n                goto fail;\n            continue;\n        }\n        is_static = (s->token.val == TOK_STATIC);\n        prop_type = -1;\n        if (is_static) {\n            if (next_token(s))\n                goto fail;\n            /* allow \"static\" field name */\n            if (s->token.val == ';' || s->token.val == '=') {\n                is_static = FALSE;\n                name = JS_DupAtom(ctx, JS_ATOM_static);\n                prop_type = PROP_TYPE_IDENT;\n            }\n        }\n        if (is_static)\n            emit_op(s, OP_swap);\n        start_ptr = s->token.ptr;\n        if (prop_type < 0) {\n            prop_type = js_parse_property_name(s, &name, TRUE, FALSE, TRUE);\n            if (prop_type < 0)\n                goto fail;\n        }\n        is_private = prop_type & PROP_TYPE_PRIVATE;\n        prop_type &= ~PROP_TYPE_PRIVATE;\n        \n        if ((name == JS_ATOM_constructor && !is_static &&\n             prop_type != PROP_TYPE_IDENT) ||\n            (name == JS_ATOM_prototype && is_static) ||\n            name == JS_ATOM_hash_constructor) {\n            js_parse_error(s, \"invalid method name\");\n            goto fail;\n        }\n        if (prop_type == PROP_TYPE_GET || prop_type == PROP_TYPE_SET) {\n            BOOL is_set = prop_type - PROP_TYPE_GET;\n            JSFunctionDef *method_fd;\n\n            if (is_private) {\n                int idx, var_kind;\n                idx = find_private_class_field(ctx, fd, name, fd->scope_level);\n                if (idx >= 0) {\n                    var_kind = fd->vars[idx].var_kind;\n                    if (var_kind == JS_VAR_PRIVATE_FIELD ||\n                        var_kind == JS_VAR_PRIVATE_METHOD ||\n                        var_kind == JS_VAR_PRIVATE_GETTER_SETTER ||\n                        var_kind == (JS_VAR_PRIVATE_GETTER + is_set)) {\n                        goto private_field_already_defined;\n                    }\n                    fd->vars[idx].var_kind = JS_VAR_PRIVATE_GETTER_SETTER;\n                } else {\n                    if (add_private_class_field(s, fd, name,\n                                                JS_VAR_PRIVATE_GETTER + is_set) < 0)\n                        goto fail;\n                }\n                if (add_brand(s, &class_fields[is_static]) < 0)\n                    goto fail;\n            }\n\n            if (js_parse_function_decl2(s, JS_PARSE_FUNC_GETTER + is_set,\n                                        JS_FUNC_NORMAL, JS_ATOM_NULL,\n                                        start_ptr, s->token.line_num,\n                                        JS_PARSE_EXPORT_NONE, &method_fd))\n                goto fail;\n            if (is_private) {\n                method_fd->need_home_object = TRUE; /* needed for brand check */\n                emit_op(s, OP_set_home_object);\n                /* XXX: missing function name */\n                emit_op(s, OP_scope_put_var_init);\n                if (is_set) {\n                    JSAtom setter_name;\n                    int ret;\n                    \n                    setter_name = get_private_setter_name(ctx, name);\n                    if (setter_name == JS_ATOM_NULL)\n                        goto fail;\n                    emit_atom(s, setter_name);\n                    ret = add_private_class_field(s, fd, setter_name,\n                                                  JS_VAR_PRIVATE_SETTER);\n                    JS_FreeAtom(ctx, setter_name);\n                    if (ret < 0)\n                        goto fail;\n                } else {\n                    emit_atom(s, name);\n                }\n                emit_u16(s, s->cur_func->scope_level);\n            } else {\n                if (name == JS_ATOM_NULL) {\n                    emit_op(s, OP_define_method_computed);\n                } else {\n                    emit_op(s, OP_define_method);\n                    emit_atom(s, name);\n                }\n                emit_u8(s, OP_DEFINE_METHOD_GETTER + is_set);\n            }\n        } else if (prop_type == PROP_TYPE_IDENT && s->token.val != '(') {\n            ClassFieldsDef *cf = &class_fields[is_static];\n            JSAtom field_var_name = JS_ATOM_NULL;\n            \n            /* class field */\n\n            /* XXX: spec: not consistent with method name checks */\n            if (name == JS_ATOM_constructor || name == JS_ATOM_prototype) {\n                js_parse_error(s, \"invalid field name\");\n                goto fail;\n            }\n            \n            if (is_private) {\n                if (find_private_class_field(ctx, fd, name,\n                                             fd->scope_level) >= 0) {\n                    goto private_field_already_defined;\n                }\n                if (add_private_class_field(s, fd, name,\n                                            JS_VAR_PRIVATE_FIELD) < 0)\n                    goto fail;\n                emit_op(s, OP_private_symbol);\n                emit_atom(s, name);\n                emit_op(s, OP_scope_put_var_init);\n                emit_atom(s, name);\n                emit_u16(s, s->cur_func->scope_level);\n            }\n\n            if (!cf->fields_init_fd) {\n                if (emit_class_init_start(s, cf))\n                    goto fail;\n            }\n            if (name == JS_ATOM_NULL ) {\n                /* save the computed field name into a variable */\n                field_var_name = js_atom_concat_num(ctx, JS_ATOM_computed_field + is_static, cf->computed_fields_count);\n                if (field_var_name == JS_ATOM_NULL)\n                    goto fail;\n                if (define_var(s, fd, field_var_name, JS_VAR_DEF_CONST) < 0) {\n                    JS_FreeAtom(ctx, field_var_name);\n                    goto fail;\n                }\n                emit_op(s, OP_to_propkey);\n                emit_op(s, OP_scope_put_var_init);\n                emit_atom(s, field_var_name);\n                emit_u16(s, s->cur_func->scope_level);\n            }\n            s->cur_func = cf->fields_init_fd;\n            emit_op(s, OP_scope_get_var);\n            emit_atom(s, JS_ATOM_this);\n            emit_u16(s, 0);\n\n            if (name == JS_ATOM_NULL) {\n                emit_op(s, OP_scope_get_var);\n                emit_atom(s, field_var_name);\n                emit_u16(s, s->cur_func->scope_level);\n                cf->computed_fields_count++;\n                JS_FreeAtom(ctx, field_var_name);\n            } else if (is_private) {\n                emit_op(s, OP_scope_get_var);\n                emit_atom(s, name);\n                emit_u16(s, s->cur_func->scope_level);\n            }\n            \n            if (s->token.val == '=') {\n                if (next_token(s))\n                    goto fail;\n                if (js_parse_assign_expr(s))\n                    goto fail;\n            } else {\n                emit_op(s, OP_undefined);\n            }\n            if (is_private) {\n                set_object_name_computed(s);\n                emit_op(s, OP_define_private_field);\n            } else if (name == JS_ATOM_NULL) {\n                set_object_name_computed(s);\n                emit_op(s, OP_define_array_el);\n                emit_op(s, OP_drop);\n            } else {\n                set_object_name(s, name);\n                emit_op(s, OP_define_field);\n                emit_atom(s, name);\n            }\n            s->cur_func = s->cur_func->parent;\n            if (js_parse_expect_semi(s))\n                goto fail;\n        } else {\n            JSParseFunctionEnum func_type;\n            JSFunctionKindEnum func_kind;\n            \n            func_type = JS_PARSE_FUNC_METHOD;\n            func_kind = JS_FUNC_NORMAL;\n            if (prop_type == PROP_TYPE_STAR) {\n                func_kind = JS_FUNC_GENERATOR;\n            } else if (prop_type == PROP_TYPE_ASYNC) {\n                func_kind = JS_FUNC_ASYNC;\n            } else if (prop_type == PROP_TYPE_ASYNC_STAR) {\n                func_kind = JS_FUNC_ASYNC_GENERATOR;\n            } else if (name == JS_ATOM_constructor && !is_static) {\n                if (ctor_fd) {\n                    js_parse_error(s, \"property constructor appears more than once\");\n                    goto fail;\n                }\n                if (class_flags & JS_DEFINE_CLASS_HAS_HERITAGE)\n                    func_type = JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR;\n                else\n                    func_type = JS_PARSE_FUNC_CLASS_CONSTRUCTOR;\n            }\n            if (is_private) {\n                if (add_brand(s, &class_fields[is_static]) < 0)\n                    goto fail;\n            }\n            if (js_parse_function_decl2(s, func_type, func_kind, JS_ATOM_NULL, start_ptr, s->token.line_num, JS_PARSE_EXPORT_NONE, &method_fd))\n                goto fail;\n            if (func_type == JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR ||\n                func_type == JS_PARSE_FUNC_CLASS_CONSTRUCTOR) {\n                ctor_fd = method_fd;\n            } else if (is_private) {\n                method_fd->need_home_object = TRUE; /* needed for brand check */\n                if (find_private_class_field(ctx, fd, name,\n                                             fd->scope_level) >= 0) {\n                private_field_already_defined:\n                    js_parse_error(s, \"private class field is already defined\");\n                    goto fail;\n                }\n                if (add_private_class_field(s, fd, name,\n                                            JS_VAR_PRIVATE_METHOD) < 0)\n                    goto fail;\n                emit_op(s, OP_set_home_object);\n                emit_op(s, OP_set_name);\n                emit_atom(s, name);\n                emit_op(s, OP_scope_put_var_init);\n                emit_atom(s, name);\n                emit_u16(s, s->cur_func->scope_level);\n            } else {\n                if (name == JS_ATOM_NULL) {\n                    emit_op(s, OP_define_method_computed);\n                } else {\n                    emit_op(s, OP_define_method);\n                    emit_atom(s, name);\n                }\n                emit_u8(s, OP_DEFINE_METHOD_METHOD);\n            }\n        }\n        if (is_static)\n            emit_op(s, OP_swap);\n        JS_FreeAtom(ctx, name);\n        name = JS_ATOM_NULL;\n    }\n\n    if (s->token.val != '}') {\n        js_parse_error(s, \"expecting '%c'\", '}');\n        goto fail;\n    }\n\n    if (!ctor_fd) {\n        if (js_parse_class_default_ctor(s, class_flags & JS_DEFINE_CLASS_HAS_HERITAGE, &ctor_fd))\n            goto fail;\n    }\n    /* patch the constant pool index for the constructor */\n    put_u32(fd->byte_code.buf + ctor_cpool_offset, ctor_fd->parent_cpool_idx);\n\n    /* store the class source code in the constructor. */\n    if (!(fd->js_mode & JS_MODE_STRIP)) {\n        js_free(ctx, ctor_fd->source);\n        ctor_fd->source_len = s->buf_ptr - class_start_ptr;\n        ctor_fd->source = js_strndup(ctx, (const char *)class_start_ptr,\n                                     ctor_fd->source_len);\n        if (!ctor_fd->source)\n            goto fail;\n    }\n\n    /* consume the '}' */\n    if (next_token(s))\n        goto fail;\n\n    /* store the function to initialize the fields to that it can be\n       referenced by the constructor */\n    {\n        ClassFieldsDef *cf = &class_fields[0];\n        int var_idx;\n        \n        var_idx = define_var(s, fd, JS_ATOM_class_fields_init,\n                             JS_VAR_DEF_CONST);\n        if (var_idx < 0)\n            goto fail;\n        if (cf->fields_init_fd) {\n            emit_class_init_end(s, cf);\n        } else {\n            emit_op(s, OP_undefined);\n        }\n        emit_op(s, OP_scope_put_var_init);\n        emit_atom(s, JS_ATOM_class_fields_init);\n        emit_u16(s, s->cur_func->scope_level);\n    }\n\n    /* drop the prototype */\n    emit_op(s, OP_drop);\n\n    /* initialize the static fields */\n    if (class_fields[1].fields_init_fd != NULL) {\n        ClassFieldsDef *cf = &class_fields[1];\n        emit_op(s, OP_dup);\n        emit_class_init_end(s, cf);\n        emit_op(s, OP_call_method);\n        emit_u16(s, 0);\n        emit_op(s, OP_drop);\n    }\n    \n    if (class_name != JS_ATOM_NULL) {\n        /* store the class name in the scoped class name variable (it\n           is independent from the class statement variable\n           definition) */\n        emit_op(s, OP_dup);\n        emit_op(s, OP_scope_put_var_init);\n        emit_atom(s, class_name);\n        emit_u16(s, fd->scope_level);\n    }\n    pop_scope(s);\n    pop_scope(s);\n\n    /* the class statements have a block level scope */\n    if (class_var_name != JS_ATOM_NULL) {\n        if (define_var(s, fd, class_var_name, JS_VAR_DEF_LET) < 0)\n            goto fail;\n        emit_op(s, OP_scope_put_var_init);\n        emit_atom(s, class_var_name);\n        emit_u16(s, fd->scope_level);\n    } else {\n        if (class_name == JS_ATOM_NULL) {\n            /* cannot use OP_set_name because the name of the class\n               must be defined before the static initializers are\n               executed */\n            emit_op(s, OP_set_class_name);\n            emit_u32(s, fd->last_opcode_pos + 1 - define_class_offset);\n        }\n    }\n\n    if (export_flag != JS_PARSE_EXPORT_NONE) {\n        if (!add_export_entry(s, fd->module,\n                              class_var_name,\n                              export_flag == JS_PARSE_EXPORT_NAMED ? class_var_name : JS_ATOM_default,\n                              JS_EXPORT_TYPE_LOCAL))\n            goto fail;\n    }\n\n    JS_FreeAtom(ctx, class_name);\n    JS_FreeAtom(ctx, class_var_name);\n    fd->js_mode = saved_js_mode;\n    return 0;\n fail:\n    JS_FreeAtom(ctx, name);\n    JS_FreeAtom(ctx, class_name);\n    JS_FreeAtom(ctx, class_var_name);\n    fd->js_mode = saved_js_mode;\n    return -1;\n}\n\nstatic __exception int js_parse_array_literal(JSParseState *s)\n{\n    uint32_t idx;\n    BOOL need_length;\n\n    if (next_token(s))\n        return -1;\n    /* small regular arrays are created on the stack */\n    idx = 0;\n    while (s->token.val != ']' && idx < 32) {\n        if (s->token.val == ',' || s->token.val == TOK_ELLIPSIS)\n            break;\n        if (js_parse_assign_expr(s))\n            return -1;\n        idx++;\n        /* accept trailing comma */\n        if (s->token.val == ',') {\n            if (next_token(s))\n                return -1;\n        } else\n        if (s->token.val != ']')\n            goto done;\n    }\n    emit_op(s, OP_array_from);\n    emit_u16(s, idx);\n\n    /* larger arrays and holes are handled with explicit indices */\n    need_length = FALSE;\n    while (s->token.val != ']' && idx < 0x7fffffff) {\n        if (s->token.val == TOK_ELLIPSIS)\n            break;\n        need_length = TRUE;\n        if (s->token.val != ',') {\n            if (js_parse_assign_expr(s))\n                return -1;\n            emit_op(s, OP_define_field);\n            emit_u32(s, __JS_AtomFromUInt32(idx));\n            need_length = FALSE;\n        }\n        idx++;\n        /* accept trailing comma */\n        if (s->token.val == ',') {\n            if (next_token(s))\n                return -1;\n        }\n    }\n    if (s->token.val == ']') {\n        if (need_length) {\n            /* Set the length: Cannot use OP_define_field because\n               length is not configurable */\n            emit_op(s, OP_dup);\n            emit_op(s, OP_push_i32);\n            emit_u32(s, idx);\n            emit_op(s, OP_put_field);\n            emit_atom(s, JS_ATOM_length);\n        }\n        goto done;\n    }\n\n    /* huge arrays and spread elements require a dynamic index on the stack */\n    emit_op(s, OP_push_i32);\n    emit_u32(s, idx);\n\n    /* stack has array, index */\n    while (s->token.val != ']') {\n        if (s->token.val == TOK_ELLIPSIS) {\n            if (next_token(s))\n                return -1;\n            if (js_parse_assign_expr(s))\n                return -1;\n#if 1\n            emit_op(s, OP_append);\n#else\n            int label_next, label_done;\n            label_next = new_label(s);\n            label_done = new_label(s);\n            /* enumerate object */\n            emit_op(s, OP_for_of_start);\n            emit_op(s, OP_rot5l);\n            emit_op(s, OP_rot5l);\n            emit_label(s, label_next);\n            /* on stack: enum_rec array idx */\n            emit_op(s, OP_for_of_next);\n            emit_u8(s, 2);\n            emit_goto(s, OP_if_true, label_done);\n            /* append element */\n            /* enum_rec array idx val -> enum_rec array new_idx */\n            emit_op(s, OP_define_array_el);\n            emit_op(s, OP_inc);\n            emit_goto(s, OP_goto, label_next);\n            emit_label(s, label_done);\n            /* close enumeration */\n            emit_op(s, OP_drop); /* drop undef val */\n            emit_op(s, OP_nip1); /* drop enum_rec */\n            emit_op(s, OP_nip1);\n            emit_op(s, OP_nip1);\n#endif\n        } else {\n            need_length = TRUE;\n            if (s->token.val != ',') {\n                if (js_parse_assign_expr(s))\n                    return -1;\n                /* a idx val */\n                emit_op(s, OP_define_array_el);\n                need_length = FALSE;\n            }\n            emit_op(s, OP_inc);\n        }\n        if (s->token.val != ',')\n            break;\n        if (next_token(s))\n            return -1;\n    }\n    if (need_length) {\n        /* Set the length: cannot use OP_define_field because\n           length is not configurable */\n        emit_op(s, OP_dup1);    /* array length - array array length */\n        emit_op(s, OP_put_field);\n        emit_atom(s, JS_ATOM_length);\n    } else {\n        emit_op(s, OP_drop);    /* array length - array */\n    }\ndone:\n    return js_parse_expect(s, ']');\n}\n\n/* XXX: remove */\nstatic BOOL has_with_scope(JSFunctionDef *s, int scope_level)\n{\n    /* check if scope chain contains a with statement */\n    while (s) {\n        int scope_idx = s->scopes[scope_level].first;\n        while (scope_idx >= 0) {\n            JSVarDef *vd = &s->vars[scope_idx];\n\n            if (vd->var_name == JS_ATOM__with_)\n                return TRUE;\n            scope_idx = vd->scope_next;\n        }\n        /* check parent scopes */\n        scope_level = s->parent_scope_level;\n        s = s->parent;\n    }\n    return FALSE;\n}\n\nstatic __exception int get_lvalue(JSParseState *s, int *popcode, int *pscope,\n                                  JSAtom *pname, int *plabel, int *pdepth, BOOL keep,\n                                  int tok)\n{\n    JSFunctionDef *fd;\n    int opcode, scope, label, depth;\n    JSAtom name;\n\n    /* we check the last opcode to get the lvalue type */\n    fd = s->cur_func;\n    scope = 0;\n    name = JS_ATOM_NULL;\n    label = -1;\n    depth = 0;\n    switch(opcode = get_prev_opcode(fd)) {\n    case OP_scope_get_var:\n        name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);\n        scope = get_u16(fd->byte_code.buf + fd->last_opcode_pos + 5);\n        if ((name == JS_ATOM_arguments || name == JS_ATOM_eval) &&\n            (fd->js_mode & JS_MODE_STRICT)) {\n            return js_parse_error(s, \"invalid lvalue in strict mode\");\n        }\n        if (name == JS_ATOM_this || name == JS_ATOM_new_target)\n            goto invalid_lvalue;\n        depth = 2;  /* will generate OP_get_ref_value */\n        break;\n    case OP_get_field:\n        name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);\n        depth = 1;\n        break;\n    case OP_scope_get_private_field:\n        name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);\n        scope = get_u16(fd->byte_code.buf + fd->last_opcode_pos + 5);\n        depth = 1;\n        break;\n    case OP_get_array_el:\n        depth = 2;\n        break;\n    case OP_get_super_value:\n        depth = 3;\n        break;\n    default:\n    invalid_lvalue:\n        if (tok == TOK_FOR) {\n            return js_parse_error(s, \"invalid for in/of left hand-side\");\n        } else if (tok == TOK_INC || tok == TOK_DEC) {\n            return js_parse_error(s, \"invalid increment/decrement operand\");\n        } else if (tok == '[' || tok == '{') {\n            return js_parse_error(s, \"invalid destructuring target\");\n        } else {\n            return js_parse_error(s, \"invalid assignment left-hand side\");\n        }\n    }\n    /* remove the last opcode */\n    fd->byte_code.size = fd->last_opcode_pos;\n    fd->last_opcode_pos = -1;\n\n    if (keep) {\n        /* get the value but keep the object/fields on the stack */\n        switch(opcode) {\n        case OP_scope_get_var:\n            label = new_label(s);\n            emit_op(s, OP_scope_make_ref);\n            emit_atom(s, name);\n            emit_u32(s, label);\n            emit_u16(s, scope);\n            update_label(fd, label, 1);\n            emit_op(s, OP_get_ref_value);\n            opcode = OP_get_ref_value;\n            break;\n        case OP_get_field:\n            emit_op(s, OP_get_field2);\n            emit_atom(s, name);\n            break;\n        case OP_scope_get_private_field:\n            emit_op(s, OP_scope_get_private_field2);\n            emit_atom(s, name);\n            emit_u16(s, scope);\n            break;\n        case OP_get_array_el:\n            /* XXX: replace by a single opcode ? */\n            emit_op(s, OP_to_propkey2);\n            emit_op(s, OP_dup2);\n            emit_op(s, OP_get_array_el);\n            break;\n        case OP_get_super_value:\n            emit_op(s, OP_to_propkey);\n            emit_op(s, OP_dup3);\n            emit_op(s, OP_get_super_value);\n            break;\n        default:\n            abort();\n        }\n    } else {\n        switch(opcode) {\n        case OP_scope_get_var:\n            label = new_label(s);\n            emit_op(s, OP_scope_make_ref);\n            emit_atom(s, name);\n            emit_u32(s, label);\n            emit_u16(s, scope);\n            update_label(fd, label, 1);\n            opcode = OP_get_ref_value;\n            break;\n        case OP_get_array_el:\n            emit_op(s, OP_to_propkey2);\n            break;\n        case OP_get_super_value:\n            emit_op(s, OP_to_propkey);\n            break;\n        }\n    }\n\n    *popcode = opcode;\n    *pscope = scope;\n    /* name has refcount for OP_get_field and OP_get_ref_value,\n       and JS_ATOM_NULL for other opcodes */\n    *pname = name;\n    *plabel = label;\n    if (pdepth)\n        *pdepth = depth;\n    return 0;\n}\n\ntypedef enum {\n    PUT_LVALUE_NOKEEP, /* [depth] v -> */\n    PUT_LVALUE_NOKEEP_DEPTH, /* [depth] v -> , keep depth (currently\n                                just disable optimizations) */\n    PUT_LVALUE_KEEP_TOP,  /* [depth] v -> v */\n    PUT_LVALUE_KEEP_SECOND, /* [depth] v0 v -> v0 */\n    PUT_LVALUE_NOKEEP_BOTTOM, /* v [depth] -> */\n} PutLValueEnum;\n\n/* name has a live reference. 'is_let' is only used with opcode =\n   OP_scope_get_var which is never generated by get_lvalue(). */\nstatic void put_lvalue(JSParseState *s, int opcode, int scope,\n                       JSAtom name, int label, PutLValueEnum special,\n                       BOOL is_let)\n{\n    switch(opcode) {\n    case OP_get_field:\n    case OP_scope_get_private_field:\n        /* depth = 1 */\n        switch(special) {\n        case PUT_LVALUE_NOKEEP:\n        case PUT_LVALUE_NOKEEP_DEPTH:\n            break;\n        case PUT_LVALUE_KEEP_TOP:\n            emit_op(s, OP_insert2); /* obj v -> v obj v */\n            break;\n        case PUT_LVALUE_KEEP_SECOND:\n            emit_op(s, OP_perm3); /* obj v0 v -> v0 obj v */\n            break;\n        case PUT_LVALUE_NOKEEP_BOTTOM:\n            emit_op(s, OP_swap);\n            break;\n        default:\n            abort();\n        }\n        break;\n    case OP_get_array_el:\n    case OP_get_ref_value:\n        /* depth = 2 */\n        if (opcode == OP_get_ref_value) {\n            JS_FreeAtom(s->ctx, name);\n            emit_label(s, label);\n        }\n        switch(special) {\n        case PUT_LVALUE_NOKEEP:\n            emit_op(s, OP_nop); /* will trigger optimization */\n            break;\n        case PUT_LVALUE_NOKEEP_DEPTH:\n            break;\n        case PUT_LVALUE_KEEP_TOP:\n            emit_op(s, OP_insert3); /* obj prop v -> v obj prop v */\n            break;\n        case PUT_LVALUE_KEEP_SECOND:\n            emit_op(s, OP_perm4); /* obj prop v0 v -> v0 obj prop v */\n            break;\n        case PUT_LVALUE_NOKEEP_BOTTOM:\n            emit_op(s, OP_rot3l);\n            break;\n        default:\n            abort();\n        }\n        break;\n    case OP_get_super_value:\n        /* depth = 3 */\n        switch(special) {\n        case PUT_LVALUE_NOKEEP:\n        case PUT_LVALUE_NOKEEP_DEPTH:\n            break;\n        case PUT_LVALUE_KEEP_TOP:\n            emit_op(s, OP_insert4); /* this obj prop v -> v this obj prop v */\n            break;\n        case PUT_LVALUE_KEEP_SECOND:\n            emit_op(s, OP_perm5); /* this obj prop v0 v -> v0 this obj prop v */\n            break;\n        case PUT_LVALUE_NOKEEP_BOTTOM:\n            emit_op(s, OP_rot4l);\n            break;\n        default:\n            abort();\n        }\n        break;\n    default:\n        break;\n    }\n    \n    switch(opcode) {\n    case OP_scope_get_var:  /* val -- */\n        assert(special == PUT_LVALUE_NOKEEP ||\n               special == PUT_LVALUE_NOKEEP_DEPTH);\n        emit_op(s, is_let ? OP_scope_put_var_init : OP_scope_put_var);\n        emit_u32(s, name);  /* has refcount */\n        emit_u16(s, scope);\n        break;\n    case OP_get_field:\n        emit_op(s, OP_put_field);\n        emit_u32(s, name);  /* name has refcount */\n        break;\n    case OP_scope_get_private_field:\n        emit_op(s, OP_scope_put_private_field);\n        emit_u32(s, name);  /* name has refcount */\n        emit_u16(s, scope);\n        break;\n    case OP_get_array_el:\n        emit_op(s, OP_put_array_el);\n        break;\n    case OP_get_ref_value:\n        emit_op(s, OP_put_ref_value);\n        break;\n    case OP_get_super_value:\n        emit_op(s, OP_put_super_value);\n        break;\n    default:\n        abort();\n    }\n}\n\nstatic __exception int js_parse_expr_paren(JSParseState *s)\n{\n    if (js_parse_expect(s, '('))\n        return -1;\n    if (js_parse_expr(s))\n        return -1;\n    if (js_parse_expect(s, ')'))\n        return -1;\n    return 0;\n}\n\nstatic int js_unsupported_keyword(JSParseState *s, JSAtom atom)\n{\n    char buf[ATOM_GET_STR_BUF_SIZE];\n    return js_parse_error(s, \"unsupported keyword: %s\",\n                          JS_AtomGetStr(s->ctx, buf, sizeof(buf), atom));\n}\n\nstatic __exception int js_define_var(JSParseState *s, JSAtom name, int tok)\n{\n    JSFunctionDef *fd = s->cur_func;\n    JSVarDefEnum var_def_type;\n    \n    if (name == JS_ATOM_yield && fd->func_kind == JS_FUNC_GENERATOR) {\n        return js_parse_error(s, \"yield is a reserved identifier\");\n    }\n    if ((name == JS_ATOM_arguments || name == JS_ATOM_eval)\n    &&  (fd->js_mode & JS_MODE_STRICT)) {\n        return js_parse_error(s, \"invalid variable name in strict mode\");\n    }\n    if ((name == JS_ATOM_let || name == JS_ATOM_undefined)\n    &&  (tok == TOK_LET || tok == TOK_CONST)) {\n        return js_parse_error(s, \"invalid lexical variable name\");\n    }\n    switch(tok) {\n    case TOK_LET:\n        var_def_type = JS_VAR_DEF_LET;\n        break;\n    case TOK_CONST:\n        var_def_type = JS_VAR_DEF_CONST;\n        break;\n    case TOK_VAR:\n        var_def_type = JS_VAR_DEF_VAR;\n        break;\n    case TOK_CATCH:\n        var_def_type = JS_VAR_DEF_CATCH;\n        break;\n    default:\n        abort();\n    }\n    if (define_var(s, fd, name, var_def_type) < 0)\n        return -1;\n    return 0;\n}\n\nstatic void js_emit_spread_code(JSParseState *s, int depth)\n{\n    int label_rest_next, label_rest_done;\n\n    /* XXX: could check if enum object is an actual array and optimize\n       slice extraction. enumeration record and target array are in a\n       different order from OP_append case. */\n    /* enum_rec xxx -- enum_rec xxx array 0 */\n    emit_op(s, OP_array_from);\n    emit_u16(s, 0);\n    emit_op(s, OP_push_i32);\n    emit_u32(s, 0);\n    emit_label(s, label_rest_next = new_label(s));\n    emit_op(s, OP_for_of_next);\n    emit_u8(s, 2 + depth);\n    label_rest_done = emit_goto(s, OP_if_true, -1);\n    /* array idx val -- array idx */\n    emit_op(s, OP_define_array_el);\n    emit_op(s, OP_inc);\n    emit_goto(s, OP_goto, label_rest_next);\n    emit_label(s, label_rest_done);\n    /* enum_rec xxx array idx undef -- enum_rec xxx array */\n    emit_op(s, OP_drop);\n    emit_op(s, OP_drop);\n}\n\nstatic int js_parse_check_duplicate_parameter(JSParseState *s, JSAtom name)\n{\n    /* Check for duplicate parameter names */\n    JSFunctionDef *fd = s->cur_func;\n    int i;\n    for (i = 0; i < fd->arg_count; i++) {\n        if (fd->args[i].var_name == name)\n            goto duplicate;\n    }\n    for (i = 0; i < fd->var_count; i++) {\n        if (fd->vars[i].var_name == name)\n            goto duplicate;\n    }\n    return 0;\n\nduplicate:\n    return js_parse_error(s, \"duplicate parameter names not allowed in this context\");\n}\n\nstatic JSAtom js_parse_destructuring_var(JSParseState *s, int tok, int is_arg)\n{\n    JSAtom name;\n\n    if (!(s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved)\n    ||  ((s->cur_func->js_mode & JS_MODE_STRICT) &&\n         (s->token.u.ident.atom == JS_ATOM_eval || s->token.u.ident.atom == JS_ATOM_arguments))) {\n        js_parse_error(s, \"invalid destructuring target\");\n        return JS_ATOM_NULL;\n    }\n    name = JS_DupAtom(s->ctx, s->token.u.ident.atom);\n    if (is_arg && js_parse_check_duplicate_parameter(s, name))\n        goto fail;\n    if (next_token(s))\n        goto fail;\n\n    return name;\nfail:\n    JS_FreeAtom(s->ctx, name);\n    return JS_ATOM_NULL;\n}\n\n/* Return -1 if error, 0 if no initializer, 1 if an initializer is\n   present at the top level. */\nstatic int js_parse_destructuring_element(JSParseState *s, int tok, int is_arg,\n                                        int hasval, int has_ellipsis,\n                                        BOOL allow_initializer)\n{\n    int label_parse, label_assign, label_done, label_lvalue, depth_lvalue;\n    int start_addr, assign_addr;\n    JSAtom prop_name, var_name;\n    int opcode, scope, tok1, skip_bits;\n    BOOL has_initializer;\n    \n    if (has_ellipsis < 0) {\n        /* pre-parse destructuration target for spread detection */\n        js_parse_skip_parens_token(s, &skip_bits, FALSE);\n        has_ellipsis = skip_bits & SKIP_HAS_ELLIPSIS;\n    }\n\n    label_parse = new_label(s);\n    label_assign = new_label(s);\n\n    start_addr = s->cur_func->byte_code.size;\n    if (hasval) {\n        /* consume value from the stack */\n        emit_op(s, OP_dup);\n        emit_op(s, OP_undefined);\n        emit_op(s, OP_strict_eq);\n        emit_goto(s, OP_if_true, label_parse);\n        emit_label(s, label_assign);\n    } else {\n        emit_goto(s, OP_goto, label_parse);\n        emit_label(s, label_assign);\n        /* leave value on the stack */\n        emit_op(s, OP_dup);\n    }\n    assign_addr = s->cur_func->byte_code.size;\n    if (s->token.val == '{') {\n        if (next_token(s))\n            return -1;\n        /* throw an exception if the value cannot be converted to an object */\n        emit_op(s, OP_to_object);\n        if (has_ellipsis) {\n            /* add excludeList on stack just below src object */\n            emit_op(s, OP_object);\n            emit_op(s, OP_swap);\n        }\n        while (s->token.val != '}') {\n            int prop_type;\n            if (s->token.val == TOK_ELLIPSIS) {\n                if (!has_ellipsis) {\n                    JS_ThrowInternalError(s->ctx, \"unexpected ellipsis token\");\n                    return -1;\n                }\n                if (next_token(s))\n                    return -1;\n                if (tok) {\n                    var_name = js_parse_destructuring_var(s, tok, is_arg);\n                    if (var_name == JS_ATOM_NULL)\n                        return -1;\n                    opcode = OP_scope_get_var;\n                    scope = s->cur_func->scope_level;\n                    label_lvalue = -1;\n                    depth_lvalue = 0;\n                } else {\n                    if (js_parse_left_hand_side_expr(s))\n                        return -1;\n\n                    if (get_lvalue(s, &opcode, &scope, &var_name,\n                                   &label_lvalue, &depth_lvalue, FALSE, '{'))\n                        return -1;\n                }\n                if (s->token.val != '}') {\n                    js_parse_error(s, \"assignment rest property must be last\");\n                    goto var_error;\n                }\n                emit_op(s, OP_object);  /* target */\n                emit_op(s, OP_copy_data_properties);\n                emit_u8(s, 0 | ((depth_lvalue + 1) << 2) | ((depth_lvalue + 2) << 5));\n                goto set_val;\n            }\n            prop_type = js_parse_property_name(s, &prop_name, FALSE, TRUE, FALSE);\n            if (prop_type < 0)\n                return -1;\n            var_name = JS_ATOM_NULL;\n            opcode = OP_scope_get_var;\n            scope = s->cur_func->scope_level;\n            label_lvalue = -1;\n            depth_lvalue = 0;\n            if (prop_type == PROP_TYPE_IDENT) {\n                if (next_token(s))\n                    goto prop_error;\n                if ((s->token.val == '[' || s->token.val == '{')\n                    &&  ((tok1 = js_parse_skip_parens_token(s, &skip_bits, FALSE)) == ',' ||\n                         tok1 == '=' || tok1 == '}')) {\n                    if (prop_name == JS_ATOM_NULL) {\n                        /* computed property name on stack */\n                        if (has_ellipsis) {\n                            /* define the property in excludeList */\n                            emit_op(s, OP_to_propkey); /* avoid calling ToString twice */\n                            emit_op(s, OP_perm3); /* TOS: src excludeList prop */\n                            emit_op(s, OP_null); /* TOS: src excludeList prop null */\n                            emit_op(s, OP_define_array_el); /* TOS: src excludeList prop */\n                            emit_op(s, OP_perm3); /* TOS: excludeList src prop */\n                        }\n                        /* get the computed property from the source object */\n                        emit_op(s, OP_get_array_el2);\n                    } else {\n                        /* named property */\n                        if (has_ellipsis) {\n                            /* define the property in excludeList */\n                            emit_op(s, OP_swap); /* TOS: src excludeList */\n                            emit_op(s, OP_null); /* TOS: src excludeList null */\n                            emit_op(s, OP_define_field); /* TOS: src excludeList */\n                            emit_atom(s, prop_name);\n                            emit_op(s, OP_swap); /* TOS: excludeList src */\n                        }\n                        /* get the named property from the source object */\n                        emit_op(s, OP_get_field2);\n                        emit_u32(s, prop_name);\n                    }\n                    if (js_parse_destructuring_element(s, tok, is_arg, TRUE, -1, TRUE) < 0)\n                        return -1;\n                    if (s->token.val == '}')\n                        break;\n                    /* accept a trailing comma before the '}' */\n                    if (js_parse_expect(s, ','))\n                        return -1;\n                    continue;\n                }\n                if (prop_name == JS_ATOM_NULL) {\n                    emit_op(s, OP_to_propkey2);\n                    if (has_ellipsis) {\n                        /* define the property in excludeList */\n                        emit_op(s, OP_perm3);\n                        emit_op(s, OP_null);\n                        emit_op(s, OP_define_array_el);\n                        emit_op(s, OP_perm3);\n                    }\n                    /* source prop -- source source prop */\n                    emit_op(s, OP_dup1);\n                } else {\n                    if (has_ellipsis) {\n                        /* define the property in excludeList */\n                        emit_op(s, OP_swap);\n                        emit_op(s, OP_null);\n                        emit_op(s, OP_define_field);\n                        emit_atom(s, prop_name);\n                        emit_op(s, OP_swap);\n                    }\n                    /* source -- source source */\n                    emit_op(s, OP_dup);\n                }\n                if (tok) {\n                    var_name = js_parse_destructuring_var(s, tok, is_arg);\n                    if (var_name == JS_ATOM_NULL)\n                        goto prop_error;\n                } else {\n                    if (js_parse_left_hand_side_expr(s))\n                        goto prop_error;\n                lvalue:\n                    if (get_lvalue(s, &opcode, &scope, &var_name,\n                                   &label_lvalue, &depth_lvalue, FALSE, '{'))\n                        goto prop_error;\n                    /* swap ref and lvalue object if any */\n                    if (prop_name == JS_ATOM_NULL) {\n                        switch(depth_lvalue) {\n                        case 1:\n                            /* source prop x -> x source prop */\n                            emit_op(s, OP_rot3r);\n                            break;\n                        case 2:\n                            /* source prop x y -> x y source prop */\n                            emit_op(s, OP_swap2);   /* t p2 s p1 */\n                            break;\n                        case 3:\n                            /* source prop x y z -> x y z source prop */\n                            emit_op(s, OP_rot5l);\n                            emit_op(s, OP_rot5l);\n                            break;\n                        }\n                    } else {\n                        switch(depth_lvalue) {\n                        case 1:\n                            /* source x -> x source */\n                            emit_op(s, OP_swap);\n                            break;\n                        case 2:\n                            /* source x y -> x y source */\n                            emit_op(s, OP_rot3l);\n                            break;\n                        case 3:\n                            /* source x y z -> x y z source */\n                            emit_op(s, OP_rot4l);\n                            break;\n                        }\n                    }\n                }\n                if (prop_name == JS_ATOM_NULL) {\n                    /* computed property name on stack */\n                    /* XXX: should have OP_get_array_el2x with depth */\n                    /* source prop -- val */\n                    emit_op(s, OP_get_array_el);\n                } else {\n                    /* named property */\n                    /* XXX: should have OP_get_field2x with depth */\n                    /* source -- val */\n                    emit_op(s, OP_get_field);\n                    emit_u32(s, prop_name);\n                }\n            } else {\n                /* prop_type = PROP_TYPE_VAR, cannot be a computed property */\n                if (is_arg && js_parse_check_duplicate_parameter(s, prop_name))\n                    goto prop_error;\n                if ((s->cur_func->js_mode & JS_MODE_STRICT) &&\n                    (prop_name == JS_ATOM_eval || prop_name == JS_ATOM_arguments)) {\n                    js_parse_error(s, \"invalid destructuring target\");\n                    goto prop_error;\n                }\n                if (has_ellipsis) {\n                    /* define the property in excludeList */\n                    emit_op(s, OP_swap);\n                    emit_op(s, OP_null);\n                    emit_op(s, OP_define_field);\n                    emit_atom(s, prop_name);\n                    emit_op(s, OP_swap);\n                }\n                if (!tok || tok == TOK_VAR) {\n                    /* generate reference */\n                    /* source -- source source */\n                    emit_op(s, OP_dup);\n                    emit_op(s, OP_scope_get_var);\n                    emit_atom(s, prop_name);\n                    emit_u16(s, s->cur_func->scope_level);\n                    goto lvalue;\n                }\n                var_name = JS_DupAtom(s->ctx, prop_name);\n                /* source -- source val */\n                emit_op(s, OP_get_field2);\n                emit_u32(s, prop_name);\n            }\n        set_val:\n            if (tok) {\n                if (js_define_var(s, var_name, tok))\n                    goto var_error;\n                scope = s->cur_func->scope_level;\n            }\n            if (s->token.val == '=') {  /* handle optional default value */\n                int label_hasval;\n                emit_op(s, OP_dup);\n                emit_op(s, OP_undefined);\n                emit_op(s, OP_strict_eq);\n                label_hasval = emit_goto(s, OP_if_false, -1);\n                if (next_token(s))\n                    goto var_error;\n                emit_op(s, OP_drop);\n                if (js_parse_assign_expr(s))\n                    goto var_error;\n                if (opcode == OP_scope_get_var || opcode == OP_get_ref_value)\n                    set_object_name(s, var_name);\n                emit_label(s, label_hasval);\n            }\n            /* store value into lvalue object */\n            put_lvalue(s, opcode, scope, var_name, label_lvalue,\n                       PUT_LVALUE_NOKEEP_DEPTH,\n                       (tok == TOK_CONST || tok == TOK_LET));\n            if (s->token.val == '}')\n                break;\n            /* accept a trailing comma before the '}' */\n            if (js_parse_expect(s, ','))\n                return -1;\n        }\n        /* drop the source object */\n        emit_op(s, OP_drop);\n        if (has_ellipsis) {\n            emit_op(s, OP_drop); /* pop excludeList */\n        }\n        if (next_token(s))\n            return -1;\n    } else if (s->token.val == '[') {\n        BOOL has_spread;\n        int enum_depth;\n        BlockEnv block_env;\n\n        if (next_token(s))\n            return -1;\n        /* the block environment is only needed in generators in case\n           'yield' triggers a 'return' */\n        push_break_entry(s->cur_func, &block_env,\n                         JS_ATOM_NULL, -1, -1, 2);\n        block_env.has_iterator = TRUE;\n        emit_op(s, OP_for_of_start);\n        has_spread = FALSE;\n        while (s->token.val != ']') {\n            /* get the next value */\n            if (s->token.val == TOK_ELLIPSIS) {\n                if (next_token(s))\n                    return -1;\n                if (s->token.val == ',' || s->token.val == ']')\n                    return js_parse_error(s, \"missing binding pattern...\");\n                has_spread = TRUE;\n            }\n            if (s->token.val == ',') {\n                /* do nothing, skip the value, has_spread is false */\n                emit_op(s, OP_for_of_next);\n                emit_u8(s, 0);\n                emit_op(s, OP_drop);\n                emit_op(s, OP_drop);\n            } else if ((s->token.val == '[' || s->token.val == '{')\n                   &&  ((tok1 = js_parse_skip_parens_token(s, &skip_bits, FALSE)) == ',' ||\n                        tok1 == '=' || tok1 == ']')) {\n                if (has_spread) {\n                    if (tok1 == '=')\n                        return js_parse_error(s, \"rest element cannot have a default value\");\n                    js_emit_spread_code(s, 0);\n                } else {\n                    emit_op(s, OP_for_of_next);\n                    emit_u8(s, 0);\n                    emit_op(s, OP_drop);\n                }\n                if (js_parse_destructuring_element(s, tok, is_arg, TRUE, skip_bits & SKIP_HAS_ELLIPSIS, TRUE) < 0)\n                    return -1;\n            } else {\n                var_name = JS_ATOM_NULL;\n                enum_depth = 0;\n                if (tok) {\n                    var_name = js_parse_destructuring_var(s, tok, is_arg);\n                    if (var_name == JS_ATOM_NULL)\n                        goto var_error;\n                    if (js_define_var(s, var_name, tok))\n                        goto var_error;\n                    opcode = OP_scope_get_var;\n                    scope = s->cur_func->scope_level;\n                } else {\n                    if (js_parse_left_hand_side_expr(s))\n                        return -1;\n                    if (get_lvalue(s, &opcode, &scope, &var_name,\n                                   &label_lvalue, &enum_depth, FALSE, '[')) {\n                        return -1;\n                    }\n                }\n                if (has_spread) {\n                    js_emit_spread_code(s, enum_depth);\n                } else {\n                    emit_op(s, OP_for_of_next);\n                    emit_u8(s, enum_depth);\n                    emit_op(s, OP_drop);\n                }\n                if (s->token.val == '=' && !has_spread) {\n                    /* handle optional default value */\n                    int label_hasval;\n                    emit_op(s, OP_dup);\n                    emit_op(s, OP_undefined);\n                    emit_op(s, OP_strict_eq);\n                    label_hasval = emit_goto(s, OP_if_false, -1);\n                    if (next_token(s))\n                        goto var_error;\n                    emit_op(s, OP_drop);\n                    if (js_parse_assign_expr(s))\n                        goto var_error;\n                    if (opcode == OP_scope_get_var || opcode == OP_get_ref_value)\n                        set_object_name(s, var_name);\n                    emit_label(s, label_hasval);\n                }\n                /* store value into lvalue object */\n                put_lvalue(s, opcode, scope, var_name,\n                           label_lvalue, PUT_LVALUE_NOKEEP_DEPTH,\n                           (tok == TOK_CONST || tok == TOK_LET));\n            }\n            if (s->token.val == ']')\n                break;\n            if (has_spread)\n                return js_parse_error(s, \"rest element must be the last one\");\n            /* accept a trailing comma before the ']' */\n            if (js_parse_expect(s, ','))\n                return -1;\n        }\n        /* close iterator object:\n           if completed, enum_obj has been replaced by undefined */\n        emit_op(s, OP_iterator_close);\n        pop_break_entry(s->cur_func);\n        if (next_token(s))\n            return -1;\n    } else {\n        return js_parse_error(s, \"invalid assignment syntax\");\n    }\n    if (s->token.val == '=' && allow_initializer) {\n        label_done = emit_goto(s, OP_goto, -1);\n        if (next_token(s))\n            return -1;\n        emit_label(s, label_parse);\n        if (hasval)\n            emit_op(s, OP_drop);\n        if (js_parse_assign_expr(s))\n            return -1;\n        emit_goto(s, OP_goto, label_assign);\n        emit_label(s, label_done);\n        has_initializer = TRUE;\n    } else {\n        /* normally hasval is true except if\n           js_parse_skip_parens_token() was wrong in the parsing */\n        //        assert(hasval);\n        if (!hasval) {\n            js_parse_error(s, \"too complicated destructuring expression\");\n            return -1;\n        }\n        /* remove test and decrement label ref count */\n        memset(s->cur_func->byte_code.buf + start_addr, OP_nop,\n               assign_addr - start_addr);\n        s->cur_func->label_slots[label_parse].ref_count--;\n        has_initializer = FALSE;\n    }\n    return has_initializer;\n\n prop_error:\n    JS_FreeAtom(s->ctx, prop_name);\n var_error:\n    JS_FreeAtom(s->ctx, var_name);\n    return -1;\n}\n\ntypedef enum FuncCallType {\n    FUNC_CALL_NORMAL,\n    FUNC_CALL_NEW,\n    FUNC_CALL_SUPER_CTOR,\n    FUNC_CALL_TEMPLATE,\n} FuncCallType;\n\nstatic void optional_chain_test(JSParseState *s, int *poptional_chaining_label,\n                                int drop_count)\n{\n    int label_next, i;\n    if (*poptional_chaining_label < 0)\n        *poptional_chaining_label = new_label(s);\n   /* XXX: could be more efficient with a specific opcode */\n    emit_op(s, OP_dup);\n    emit_op(s, OP_is_undefined_or_null);\n    label_next = emit_goto(s, OP_if_false, -1);\n    for(i = 0; i < drop_count; i++)\n        emit_op(s, OP_drop);\n    emit_op(s, OP_undefined);\n    emit_goto(s, OP_goto, *poptional_chaining_label);\n    emit_label(s, label_next);\n}\n\n/* allowed parse_flags: PF_POSTFIX_CALL, PF_ARROW_FUNC */\nstatic __exception int js_parse_postfix_expr(JSParseState *s, int parse_flags)\n{\n    FuncCallType call_type;\n    int optional_chaining_label;\n    BOOL accept_lparen = (parse_flags & PF_POSTFIX_CALL) != 0;\n    \n    call_type = FUNC_CALL_NORMAL;\n    switch(s->token.val) {\n    case TOK_NUMBER:\n        {\n            JSValue val;\n            val = s->token.u.num.val;\n\n            if (JS_VALUE_GET_TAG(val) == JS_TAG_INT) {\n                emit_op(s, OP_push_i32);\n                emit_u32(s, JS_VALUE_GET_INT(val));\n            } else\n#ifdef CONFIG_BIGNUM\n            if (JS_VALUE_GET_TAG(val) == JS_TAG_BIG_FLOAT) {\n                slimb_t e;\n                int ret;\n\n                /* need a runtime conversion */\n                /* XXX: could add a cache and/or do it once at\n                   the start of the function */\n                if (emit_push_const(s, val, 0) < 0)\n                    return -1;\n                e = s->token.u.num.exponent;\n                if (e == (int32_t)e) {\n                    emit_op(s, OP_push_i32);\n                    emit_u32(s, e);\n                } else {\n                    val = JS_NewBigInt64_1(s->ctx, e);\n                    if (JS_IsException(val))\n                        return -1;\n                    ret = emit_push_const(s, val, 0);\n                    JS_FreeValue(s->ctx, val);\n                    if (ret < 0)\n                        return -1;\n                }\n                emit_op(s, OP_mul_pow10);\n            } else\n#endif\n            {\n                if (emit_push_const(s, val, 0) < 0)\n                    return -1;\n            }\n        }\n        if (next_token(s))\n            return -1;\n        break;\n    case TOK_TEMPLATE:\n        if (js_parse_template(s, 0, NULL))\n            return -1;\n        break;\n    case TOK_STRING:\n        if (emit_push_const(s, s->token.u.str.str, 1))\n            return -1;\n        if (next_token(s))\n            return -1;\n        break;\n        \n    case TOK_DIV_ASSIGN:\n        s->buf_ptr -= 2;\n        goto parse_regexp;\n    case '/':\n        s->buf_ptr--;\n    parse_regexp:\n        {\n            JSValue str;\n            int ret, backtrace_flags;\n            if (!s->ctx->compile_regexp)\n                return js_parse_error(s, \"RegExp are not supported\");\n            /* the previous token is '/' or '/=', so no need to free */\n            if (js_parse_regexp(s))\n                return -1;\n            ret = emit_push_const(s, s->token.u.regexp.body, 0);\n            str = s->ctx->compile_regexp(s->ctx, s->token.u.regexp.body,\n                                         s->token.u.regexp.flags);\n            if (JS_IsException(str)) {\n                /* add the line number info */\n                backtrace_flags = 0;\n                if (s->cur_func && s->cur_func->backtrace_barrier)\n                    backtrace_flags = JS_BACKTRACE_FLAG_SINGLE_LEVEL;\n                build_backtrace(s->ctx, s->ctx->rt->current_exception,\n                                s->filename, s->token.line_num,\n                                backtrace_flags);\n                return -1;\n            }\n            ret = emit_push_const(s, str, 0);\n            JS_FreeValue(s->ctx, str);\n            if (ret)\n                return -1;\n            /* we use a specific opcode to be sure the correct\n               function is called (otherwise the bytecode would have\n               to be verified by the RegExp constructor) */\n            emit_op(s, OP_regexp);\n            if (next_token(s))\n                return -1;\n        }\n        break;\n    case '(':\n        if ((parse_flags & PF_ARROW_FUNC) &&\n            js_parse_skip_parens_token(s, NULL, TRUE) == TOK_ARROW) {\n            if (js_parse_function_decl(s, JS_PARSE_FUNC_ARROW,\n                                       JS_FUNC_NORMAL, JS_ATOM_NULL,\n                                       s->token.ptr, s->token.line_num))\n                return -1;\n        } else {\n            if (js_parse_expr_paren(s))\n                return -1;\n        }\n        break;\n    case TOK_FUNCTION:\n        if (js_parse_function_decl(s, JS_PARSE_FUNC_EXPR,\n                                   JS_FUNC_NORMAL, JS_ATOM_NULL,\n                                   s->token.ptr, s->token.line_num))\n            return -1;\n        break;\n    case TOK_CLASS:\n        if (js_parse_class(s, TRUE, JS_PARSE_EXPORT_NONE))\n            return -1;\n        break;\n    case TOK_NULL:\n        if (next_token(s))\n            return -1;\n        emit_op(s, OP_null);\n        break;\n    case TOK_THIS:\n        if (next_token(s))\n            return -1;\n        emit_op(s, OP_scope_get_var);\n        emit_atom(s, JS_ATOM_this);\n        emit_u16(s, 0);\n        break;\n    case TOK_FALSE:\n        if (next_token(s))\n            return -1;\n        emit_op(s, OP_push_false);\n        break;\n    case TOK_TRUE:\n        if (next_token(s))\n            return -1;\n        emit_op(s, OP_push_true);\n        break;\n    case TOK_IDENT:\n        {\n            JSAtom name;\n            if (s->token.u.ident.is_reserved) {\n                return js_parse_error_reserved_identifier(s);\n            }\n            if ((parse_flags & PF_ARROW_FUNC) &&\n                peek_token(s, TRUE) == TOK_ARROW) {\n                if (js_parse_function_decl(s, JS_PARSE_FUNC_ARROW,\n                                           JS_FUNC_NORMAL, JS_ATOM_NULL,\n                                           s->token.ptr, s->token.line_num))\n                    return -1;\n            } else if (token_is_pseudo_keyword(s, JS_ATOM_async) &&\n                       peek_token(s, TRUE) != '\\n') {\n                const uint8_t *source_ptr;\n                int source_line_num;\n\n                source_ptr = s->token.ptr;\n                source_line_num = s->token.line_num;\n                if (next_token(s))\n                    return -1;\n                if (s->token.val == TOK_FUNCTION) {\n                    if (js_parse_function_decl(s, JS_PARSE_FUNC_EXPR,\n                                               JS_FUNC_ASYNC, JS_ATOM_NULL,\n                                               source_ptr, source_line_num))\n                        return -1;\n                } else if ((parse_flags & PF_ARROW_FUNC) &&\n                           ((s->token.val == '(' &&\n                             js_parse_skip_parens_token(s, NULL, TRUE) == TOK_ARROW) ||\n                            (s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved &&\n                             peek_token(s, TRUE) == TOK_ARROW))) {\n                    if (js_parse_function_decl(s, JS_PARSE_FUNC_ARROW,\n                                               JS_FUNC_ASYNC, JS_ATOM_NULL,\n                                               source_ptr, source_line_num))\n                        return -1;\n                } else {\n                    name = JS_DupAtom(s->ctx, JS_ATOM_async);\n                    goto do_get_var;\n                }\n            } else {\n                if (s->token.u.ident.atom == JS_ATOM_arguments &&\n                    !s->cur_func->arguments_allowed) {\n                    js_parse_error(s, \"'arguments' identifier is not allowed in class field initializer\");\n                    return -1;\n                }\n                name = JS_DupAtom(s->ctx, s->token.u.ident.atom);\n                if (next_token(s))  /* update line number before emitting code */\n                    return -1;\n            do_get_var:\n                emit_op(s, OP_scope_get_var);\n                emit_u32(s, name);\n                emit_u16(s, s->cur_func->scope_level);\n            }\n        }\n        break;\n    case '{':\n    case '[':\n        {\n            int skip_bits;\n            if (js_parse_skip_parens_token(s, &skip_bits, FALSE) == '=') {\n                if (js_parse_destructuring_element(s, 0, 0, FALSE, skip_bits & SKIP_HAS_ELLIPSIS, TRUE) < 0)\n                    return -1;\n            } else {\n                if (s->token.val == '{') {\n                    if (js_parse_object_literal(s))\n                        return -1;\n                } else {\n                    if (js_parse_array_literal(s))\n                        return -1;\n                }\n            }\n        }\n        break;\n    case TOK_NEW:\n        if (next_token(s))\n            return -1;\n        if (s->token.val == '.') {\n            if (next_token(s))\n                return -1;\n            if (!token_is_pseudo_keyword(s, JS_ATOM_target))\n                return js_parse_error(s, \"expecting target\");\n            if (!s->cur_func->new_target_allowed)\n                return js_parse_error(s, \"new.target only allowed within functions\");\n            if (next_token(s))\n                return -1;\n            emit_op(s, OP_scope_get_var);\n            emit_atom(s, JS_ATOM_new_target);\n            emit_u16(s, 0);\n        } else {\n            if (js_parse_postfix_expr(s, 0))\n                return -1;\n            accept_lparen = TRUE;\n            if (s->token.val != '(') {\n                /* new operator on an object */\n                emit_op(s, OP_dup);\n                emit_op(s, OP_call_constructor);\n                emit_u16(s, 0);\n            } else {\n                call_type = FUNC_CALL_NEW;\n            }\n        }\n        break;\n    case TOK_SUPER:\n        if (next_token(s))\n            return -1;\n        if (s->token.val == '(') {\n            if (!s->cur_func->super_call_allowed)\n                return js_parse_error(s, \"super() is only valid in a derived class constructor\");\n            call_type = FUNC_CALL_SUPER_CTOR;\n        } else if (s->token.val == '.' || s->token.val == '[') {\n            if (!s->cur_func->super_allowed)\n                return js_parse_error(s, \"'super' is only valid in a method\");\n            emit_op(s, OP_scope_get_var);\n            emit_atom(s, JS_ATOM_this);\n            emit_u16(s, 0);\n            emit_op(s, OP_scope_get_var);\n            emit_atom(s, JS_ATOM_home_object);\n            emit_u16(s, 0);\n            emit_op(s, OP_get_super);\n        } else {\n            return js_parse_error(s, \"invalid use of 'super'\");\n        }\n        break;\n    case TOK_IMPORT:\n        if (next_token(s))\n            return -1;\n        if (s->token.val == '.') {\n            if (next_token(s))\n                return -1;\n            if (!token_is_pseudo_keyword(s, JS_ATOM_meta))\n                return js_parse_error(s, \"meta expected\");\n            if (!s->is_module)\n                return js_parse_error(s, \"import.meta only valid in module code\");\n            if (next_token(s))\n                return -1;\n            emit_op(s, OP_special_object);\n            emit_u8(s, OP_SPECIAL_OBJECT_IMPORT_META);\n        } else {\n            if (js_parse_expect(s, '('))\n                return -1;\n            if (!accept_lparen)\n                return js_parse_error(s, \"invalid use of 'import()'\");\n            if (js_parse_assign_expr(s))\n                return -1;\n            if (js_parse_expect(s, ')'))\n                return -1;\n            emit_op(s, OP_import);\n        }\n        break;\n    default:\n        return js_parse_error(s, \"unexpected token in expression: '%.*s'\",\n                              (int)(s->buf_ptr - s->token.ptr), s->token.ptr);\n    }\n\n    optional_chaining_label = -1;\n    for(;;) {\n        JSFunctionDef *fd = s->cur_func;\n        BOOL has_optional_chain = FALSE;\n        \n        if (s->token.val == TOK_QUESTION_MARK_DOT) {\n            /* optional chaining */\n            if (next_token(s))\n                return -1;\n            has_optional_chain = TRUE;\n            if (s->token.val == '(' && accept_lparen) {\n                goto parse_func_call;\n            } else if (s->token.val == '[') {\n                goto parse_array_access;\n            } else {\n                goto parse_property;\n            }\n        } else if (s->token.val == TOK_TEMPLATE &&\n                   call_type == FUNC_CALL_NORMAL) {\n            if (optional_chaining_label >= 0) {\n                return js_parse_error(s, \"template literal cannot appear in an optional chain\");\n            }\n            call_type = FUNC_CALL_TEMPLATE;\n            goto parse_func_call2;\n        } else if (s->token.val == '(' && accept_lparen) {\n            int opcode, arg_count, drop_count;\n\n            /* function call */\n        parse_func_call:\n            if (next_token(s))\n                return -1;\n\n            if (call_type == FUNC_CALL_NORMAL) {\n            parse_func_call2:\n                switch(opcode = get_prev_opcode(fd)) {\n                case OP_get_field:\n                    /* keep the object on the stack */\n                    fd->byte_code.buf[fd->last_opcode_pos] = OP_get_field2;\n                    drop_count = 2;\n                    break;\n                case OP_scope_get_private_field:\n                    /* keep the object on the stack */\n                    fd->byte_code.buf[fd->last_opcode_pos] = OP_scope_get_private_field2;\n                    drop_count = 2;\n                    break;\n                case OP_get_array_el:\n                    /* keep the object on the stack */\n                    fd->byte_code.buf[fd->last_opcode_pos] = OP_get_array_el2;\n                    drop_count = 2;\n                    break;\n                case OP_scope_get_var:\n                    {\n                        JSAtom name;\n                        int scope;\n                        name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);\n                        scope = get_u16(fd->byte_code.buf + fd->last_opcode_pos + 5);\n                        if (name == JS_ATOM_eval && call_type == FUNC_CALL_NORMAL && !has_optional_chain) {\n                            /* direct 'eval' */\n                            opcode = OP_eval;\n                        } else {\n                            /* verify if function name resolves to a simple\n                               get_loc/get_arg: a function call inside a `with`\n                               statement can resolve to a method call of the\n                               `with` context object\n                             */\n                            /* XXX: always generate the OP_scope_get_ref\n                               and remove it in variable resolution\n                               pass ? */\n                            if (has_with_scope(fd, scope)) {\n                                opcode = OP_scope_get_ref;\n                                fd->byte_code.buf[fd->last_opcode_pos] = opcode;\n                            }\n                        }\n                        drop_count = 1;\n                    }\n                    break;\n                case OP_get_super_value:\n                    fd->byte_code.buf[fd->last_opcode_pos] = OP_get_array_el;\n                    /* on stack: this func_obj */\n                    opcode = OP_get_array_el;\n                    drop_count = 2;\n                    break;\n                default:\n                    opcode = OP_invalid;\n                    drop_count = 1;\n                    break;\n                }\n                if (has_optional_chain) {\n                    optional_chain_test(s, &optional_chaining_label,\n                                        drop_count);\n                }\n            } else {\n                opcode = OP_invalid;\n            }\n\n            if (call_type == FUNC_CALL_TEMPLATE) {\n                if (js_parse_template(s, 1, &arg_count))\n                    return -1;\n                goto emit_func_call;\n            } else if (call_type == FUNC_CALL_SUPER_CTOR) {\n                emit_op(s, OP_scope_get_var);\n                emit_atom(s, JS_ATOM_this_active_func);\n                emit_u16(s, 0);\n\n                emit_op(s, OP_get_super);\n\n                emit_op(s, OP_scope_get_var);\n                emit_atom(s, JS_ATOM_new_target);\n                emit_u16(s, 0);\n            } else if (call_type == FUNC_CALL_NEW) {\n                emit_op(s, OP_dup); /* new.target = function */\n            }\n\n            /* parse arguments */\n            arg_count = 0;\n            while (s->token.val != ')') {\n                if (arg_count >= 65535) {\n                    return js_parse_error(s, \"Too many call arguments\");\n                }\n                if (s->token.val == TOK_ELLIPSIS)\n                    break;\n                if (js_parse_assign_expr(s))\n                    return -1;\n                arg_count++;\n                if (s->token.val == ')')\n                    break;\n                /* accept a trailing comma before the ')' */\n                if (js_parse_expect(s, ','))\n                    return -1;\n            }\n            if (s->token.val == TOK_ELLIPSIS) {\n                emit_op(s, OP_array_from);\n                emit_u16(s, arg_count);\n                emit_op(s, OP_push_i32);\n                emit_u32(s, arg_count);\n\n                /* on stack: array idx */\n                while (s->token.val != ')') {\n                    if (s->token.val == TOK_ELLIPSIS) {\n                        if (next_token(s))\n                            return -1;\n                        if (js_parse_assign_expr(s))\n                            return -1;\n#if 1\n                        /* XXX: could pass is_last indicator? */\n                        emit_op(s, OP_append);\n#else\n                        int label_next, label_done;\n                        label_next = new_label(s);\n                        label_done = new_label(s);\n                        /* push enumerate object below array/idx pair */\n                        emit_op(s, OP_for_of_start);\n                        emit_op(s, OP_rot5l);\n                        emit_op(s, OP_rot5l);\n                        emit_label(s, label_next);\n                        /* on stack: enum_rec array idx */\n                        emit_op(s, OP_for_of_next);\n                        emit_u8(s, 2);\n                        emit_goto(s, OP_if_true, label_done);\n                        /* append element */\n                        /* enum_rec array idx val -> enum_rec array new_idx */\n                        emit_op(s, OP_define_array_el);\n                        emit_op(s, OP_inc);\n                        emit_goto(s, OP_goto, label_next);\n                        emit_label(s, label_done);\n                        /* close enumeration, drop enum_rec and idx */\n                        emit_op(s, OP_drop); /* drop undef */\n                        emit_op(s, OP_nip1); /* drop enum_rec */\n                        emit_op(s, OP_nip1);\n                        emit_op(s, OP_nip1);\n#endif\n                    } else {\n                        if (js_parse_assign_expr(s))\n                            return -1;\n                        /* array idx val */\n                        emit_op(s, OP_define_array_el);\n                        emit_op(s, OP_inc);\n                    }\n                    if (s->token.val == ')')\n                        break;\n                    /* accept a trailing comma before the ')' */\n                    if (js_parse_expect(s, ','))\n                        return -1;\n                }\n                if (next_token(s))\n                    return -1;\n                /* drop the index */\n                emit_op(s, OP_drop);\n\n                /* apply function call */\n                switch(opcode) {\n                case OP_get_field:\n                case OP_scope_get_private_field:\n                case OP_get_array_el:\n                case OP_scope_get_ref:\n                    /* obj func array -> func obj array */\n                    emit_op(s, OP_perm3);\n                    emit_op(s, OP_apply);\n                    emit_u16(s, call_type == FUNC_CALL_NEW);\n                    break;\n                case OP_eval:\n                    emit_op(s, OP_apply_eval);\n                    emit_u16(s, fd->scope_level);\n                    fd->has_eval_call = TRUE;\n                    break;\n                default:\n                    if (call_type == FUNC_CALL_SUPER_CTOR) {\n                        emit_op(s, OP_apply);\n                        emit_u16(s, 1);\n                        /* set the 'this' value */\n                        emit_op(s, OP_dup);\n                        emit_op(s, OP_scope_put_var_init);\n                        emit_atom(s, JS_ATOM_this);\n                        emit_u16(s, 0);\n\n                        emit_class_field_init(s);\n                    } else if (call_type == FUNC_CALL_NEW) {\n                        /* obj func array -> func obj array */\n                        emit_op(s, OP_perm3);\n                        emit_op(s, OP_apply);\n                        emit_u16(s, 1);\n                    } else {\n                        /* func array -> func undef array */\n                        emit_op(s, OP_undefined);\n                        emit_op(s, OP_swap);\n                        emit_op(s, OP_apply);\n                        emit_u16(s, 0);\n                    }\n                    break;\n                }\n            } else {\n                if (next_token(s))\n                    return -1;\n            emit_func_call:\n                switch(opcode) {\n                case OP_get_field:\n                case OP_scope_get_private_field:\n                case OP_get_array_el:\n                case OP_scope_get_ref:\n                    emit_op(s, OP_call_method);\n                    emit_u16(s, arg_count);\n                    break;\n                case OP_eval:\n                    emit_op(s, OP_eval);\n                    emit_u16(s, arg_count);\n                    emit_u16(s, fd->scope_level);\n                    fd->has_eval_call = TRUE;\n                    break;\n                default:\n                    if (call_type == FUNC_CALL_SUPER_CTOR) {\n                        emit_op(s, OP_call_constructor);\n                        emit_u16(s, arg_count);\n\n                        /* set the 'this' value */\n                        emit_op(s, OP_dup);\n                        emit_op(s, OP_scope_put_var_init);\n                        emit_atom(s, JS_ATOM_this);\n                        emit_u16(s, 0);\n\n                        emit_class_field_init(s);\n                    } else if (call_type == FUNC_CALL_NEW) {\n                        emit_op(s, OP_call_constructor);\n                        emit_u16(s, arg_count);\n                    } else {\n                        emit_op(s, OP_call);\n                        emit_u16(s, arg_count);\n                    }\n                    break;\n                }\n            }\n            call_type = FUNC_CALL_NORMAL;\n        } else if (s->token.val == '.') {\n            if (next_token(s))\n                return -1;\n        parse_property:\n            if (s->token.val == TOK_PRIVATE_NAME) {\n                /* private class field */\n                if (get_prev_opcode(fd) == OP_get_super) {\n                    return js_parse_error(s, \"private class field forbidden after super\");\n                }\n                if (has_optional_chain) {\n                    optional_chain_test(s, &optional_chaining_label, 1);\n                }\n                emit_op(s, OP_scope_get_private_field);\n                emit_atom(s, s->token.u.ident.atom);\n                emit_u16(s, s->cur_func->scope_level);\n            } else {\n                if (!token_is_ident(s->token.val)) {\n                    return js_parse_error(s, \"expecting field name\");\n                }\n                if (get_prev_opcode(fd) == OP_get_super) {\n                    JSValue val;\n                    int ret;\n                    val = JS_AtomToValue(s->ctx, s->token.u.ident.atom);\n                    ret = emit_push_const(s, val, 1);\n                    JS_FreeValue(s->ctx, val);\n                    if (ret)\n                        return -1;\n                    emit_op(s, OP_get_super_value);\n                } else {\n                    if (has_optional_chain) {\n                        optional_chain_test(s, &optional_chaining_label, 1);\n                    }\n                    emit_op(s, OP_get_field);\n                    emit_atom(s, s->token.u.ident.atom);\n                }\n            }\n            if (next_token(s))\n                return -1;\n        } else if (s->token.val == '[') {\n            int prev_op;\n\n        parse_array_access:\n            prev_op = get_prev_opcode(fd);\n            if (has_optional_chain) {\n                optional_chain_test(s, &optional_chaining_label, 1);\n            }\n            if (next_token(s))\n                return -1;\n            if (js_parse_expr(s))\n                return -1;\n            if (js_parse_expect(s, ']'))\n                return -1;\n            if (prev_op == OP_get_super) {\n                emit_op(s, OP_get_super_value);\n            } else {\n                emit_op(s, OP_get_array_el);\n            }\n        } else {\n            break;\n        }\n    }\n    if (optional_chaining_label >= 0)\n        emit_label(s, optional_chaining_label);\n    return 0;\n}\n\nstatic __exception int js_parse_delete(JSParseState *s)\n{\n    JSFunctionDef *fd = s->cur_func;\n    JSAtom name;\n    int opcode;\n\n    if (next_token(s))\n        return -1;\n    if (js_parse_unary(s, PF_POW_FORBIDDEN))\n        return -1;\n    switch(opcode = get_prev_opcode(fd)) {\n    case OP_get_field:\n        {\n            JSValue val;\n            int ret;\n\n            name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);\n            fd->byte_code.size = fd->last_opcode_pos;\n            fd->last_opcode_pos = -1;\n            val = JS_AtomToValue(s->ctx, name);\n            ret = emit_push_const(s, val, 1);\n            JS_FreeValue(s->ctx, val);\n            JS_FreeAtom(s->ctx, name);\n            if (ret)\n                return ret;\n        }\n        goto do_delete;\n    case OP_get_array_el:\n        fd->byte_code.size = fd->last_opcode_pos;\n        fd->last_opcode_pos = -1;\n    do_delete:\n        emit_op(s, OP_delete);\n        break;\n    case OP_scope_get_var:\n        /* 'delete this': this is not a reference */\n        name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);\n        if (name == JS_ATOM_this || name == JS_ATOM_new_target)\n            goto ret_true;\n        if (fd->js_mode & JS_MODE_STRICT) {\n            return js_parse_error(s, \"cannot delete a direct reference in strict mode\");\n        } else {\n            fd->byte_code.buf[fd->last_opcode_pos] = OP_scope_delete_var;\n        }\n        break;\n    case OP_scope_get_private_field:\n        return js_parse_error(s, \"cannot delete a private class field\");\n    case OP_get_super_value:\n        emit_op(s, OP_throw_error);\n        emit_atom(s, JS_ATOM_NULL);\n        emit_u8(s, JS_THROW_ERROR_DELETE_SUPER);\n        break;\n    default:\n    ret_true:\n        emit_op(s, OP_drop);\n        emit_op(s, OP_push_true);\n        break;\n    }\n    return 0;\n}\n\n/* allowed parse_flags: PF_ARROW_FUNC, PF_POW_ALLOWED, PF_POW_FORBIDDEN */\nstatic __exception int js_parse_unary(JSParseState *s, int parse_flags)\n{\n    int op;\n\n    switch(s->token.val) {\n    case '+':\n    case '-':\n    case '!':\n    case '~':\n    case TOK_VOID:\n        op = s->token.val;\n        if (next_token(s))\n            return -1;\n        if (js_parse_unary(s, PF_POW_FORBIDDEN))\n            return -1;\n        switch(op) {\n        case '-':\n            emit_op(s, OP_neg);\n            break;\n        case '+':\n            emit_op(s, OP_plus);\n            break;\n        case '!':\n            emit_op(s, OP_lnot);\n            break;\n        case '~':\n            emit_op(s, OP_not);\n            break;\n        case TOK_VOID:\n            emit_op(s, OP_drop);\n            emit_op(s, OP_undefined);\n            break;\n        default:\n            abort();\n        }\n        parse_flags = 0;\n        break;\n    case TOK_DEC:\n    case TOK_INC:\n        {\n            int opcode, op, scope, label;\n            JSAtom name;\n            op = s->token.val;\n            if (next_token(s))\n                return -1;\n            if (js_parse_unary(s, 0))\n                return -1;\n            if (get_lvalue(s, &opcode, &scope, &name, &label, NULL, TRUE, op))\n                return -1;\n            emit_op(s, OP_dec + op - TOK_DEC);\n            put_lvalue(s, opcode, scope, name, label, PUT_LVALUE_KEEP_TOP,\n                       FALSE);\n        }\n        break;\n    case TOK_TYPEOF:\n        {\n            JSFunctionDef *fd;\n            if (next_token(s))\n                return -1;\n            if (js_parse_unary(s, PF_POW_FORBIDDEN))\n                return -1;\n            /* reference access should not return an exception, so we\n               patch the get_var */\n            fd = s->cur_func;\n            if (get_prev_opcode(fd) == OP_scope_get_var) {\n                fd->byte_code.buf[fd->last_opcode_pos] = OP_scope_get_var_undef;\n            }\n            emit_op(s, OP_typeof);\n            parse_flags = 0;\n        }\n        break;\n    case TOK_DELETE:\n        if (js_parse_delete(s))\n            return -1;\n        parse_flags = 0;\n        break;\n    case TOK_AWAIT:\n        if (!(s->cur_func->func_kind & JS_FUNC_ASYNC))\n            return js_parse_error(s, \"unexpected 'await' keyword\");\n        if (!s->cur_func->in_function_body)\n            return js_parse_error(s, \"await in default expression\");\n        if (next_token(s))\n            return -1;\n        if (js_parse_unary(s, PF_POW_FORBIDDEN))\n            return -1;\n        emit_op(s, OP_await);\n        parse_flags = 0;\n        break;\n    default:\n        if (js_parse_postfix_expr(s, (parse_flags & PF_ARROW_FUNC) |\n                                  PF_POSTFIX_CALL))\n            return -1;\n        if (!s->got_lf &&\n            (s->token.val == TOK_DEC || s->token.val == TOK_INC)) {\n            int opcode, op, scope, label;\n            JSAtom name;\n            op = s->token.val;\n            if (get_lvalue(s, &opcode, &scope, &name, &label, NULL, TRUE, op))\n                return -1;\n            emit_op(s, OP_post_dec + op - TOK_DEC);\n            put_lvalue(s, opcode, scope, name, label, PUT_LVALUE_KEEP_SECOND,\n                       FALSE);\n            if (next_token(s))\n                return -1;        \n        }\n        break;\n    }\n    if (parse_flags & (PF_POW_ALLOWED | PF_POW_FORBIDDEN)) {\n#ifdef CONFIG_BIGNUM\n        if (s->token.val == TOK_POW || s->token.val == TOK_MATH_POW) {\n            /* Extended exponentiation syntax rules: we extend the ES7\n               grammar in order to have more intuitive semantics:\n               -2**2 evaluates to -4. */\n            if (!(s->cur_func->js_mode & JS_MODE_MATH)) {\n                if (parse_flags & PF_POW_FORBIDDEN) {\n                    JS_ThrowSyntaxError(s->ctx, \"unparenthesized unary expression can't appear on the left-hand side of '**'\");\n                    return -1;\n                }\n            }\n            if (next_token(s))\n                return -1;\n            if (js_parse_unary(s, PF_POW_ALLOWED))\n                return -1;\n            emit_op(s, OP_pow);\n        }\n#else\n        if (s->token.val == TOK_POW) {\n            /* Strict ES7 exponentiation syntax rules: To solve\n               conficting semantics between different implementations\n               regarding the precedence of prefix operators and the\n               postifx exponential, ES7 specifies that -2**2 is a\n               syntax error. */\n            if (parse_flags & PF_POW_FORBIDDEN) {\n                JS_ThrowSyntaxError(s->ctx, \"unparenthesized unary expression can't appear on the left-hand side of '**'\");\n                return -1;\n            }\n            if (next_token(s))\n                return -1;\n            if (js_parse_unary(s, PF_POW_ALLOWED))\n                return -1;\n            emit_op(s, OP_pow);\n        }\n#endif\n    }\n    return 0;\n}\n\n/* allowed parse_flags: PF_ARROW_FUNC, PF_IN_ACCEPTED */\nstatic __exception int js_parse_expr_binary(JSParseState *s, int level,\n                                            int parse_flags)\n{\n    int op, opcode;\n\n    if (level == 0) {\n        return js_parse_unary(s, (parse_flags & PF_ARROW_FUNC) |\n                              PF_POW_ALLOWED);\n    }\n    if (js_parse_expr_binary(s, level - 1, parse_flags))\n        return -1;\n    for(;;) {\n        op = s->token.val;\n        switch(level) {\n        case 1:\n            switch(op) {\n            case '*':\n                opcode = OP_mul;\n                break;\n            case '/':\n                opcode = OP_div;\n                break;\n            case '%':\n#ifdef CONFIG_BIGNUM\n                if (s->cur_func->js_mode & JS_MODE_MATH)\n                    opcode = OP_math_mod;\n                else\n#endif\n                    opcode = OP_mod;\n                break;\n            default:\n                return 0;\n            }\n            break;\n        case 2:\n            switch(op) {\n            case '+':\n                opcode = OP_add;\n                break;\n            case '-':\n                opcode = OP_sub;\n                break;\n            default:\n                return 0;\n            }\n            break;\n        case 3:\n            switch(op) {\n            case TOK_SHL:\n                opcode = OP_shl;\n                break;\n            case TOK_SAR:\n                opcode = OP_sar;\n                break;\n            case TOK_SHR:\n                opcode = OP_shr;\n                break;\n            default:\n                return 0;\n            }\n            break;\n        case 4:\n            switch(op) {\n            case '<':\n                opcode = OP_lt;\n                break;\n            case '>':\n                opcode = OP_gt;\n                break;\n            case TOK_LTE:\n                opcode = OP_lte;\n                break;\n            case TOK_GTE:\n                opcode = OP_gte;\n                break;\n            case TOK_INSTANCEOF:\n                opcode = OP_instanceof;\n                break;\n            case TOK_IN:\n                if (parse_flags & PF_IN_ACCEPTED) {\n                    opcode = OP_in;\n                } else {\n                    return 0;\n                }\n                break;\n            default:\n                return 0;\n            }\n            break;\n        case 5:\n            switch(op) {\n            case TOK_EQ:\n                opcode = OP_eq;\n                break;\n            case TOK_NEQ:\n                opcode = OP_neq;\n                break;\n            case TOK_STRICT_EQ:\n                opcode = OP_strict_eq;\n                break;\n            case TOK_STRICT_NEQ:\n                opcode = OP_strict_neq;\n                break;\n            default:\n                return 0;\n            }\n            break;\n        case 6:\n            switch(op) {\n            case '&':\n                opcode = OP_and;\n                break;\n            default:\n                return 0;\n            }\n            break;\n        case 7:\n            switch(op) {\n            case '^':\n                opcode = OP_xor;\n                break;\n            default:\n                return 0;\n            }\n            break;\n        case 8:\n            switch(op) {\n            case '|':\n                opcode = OP_or;\n                break;\n            default:\n                return 0;\n            }\n            break;\n        default:\n            abort();\n        }\n        if (next_token(s))\n            return -1;\n        if (js_parse_expr_binary(s, level - 1, parse_flags & ~PF_ARROW_FUNC))\n            return -1;\n        emit_op(s, opcode);\n    }\n    return 0;\n}\n\n/* allowed parse_flags: PF_ARROW_FUNC, PF_IN_ACCEPTED */\nstatic __exception int js_parse_logical_and_or(JSParseState *s, int op,\n                                               int parse_flags)\n{\n    int label1;\n\n    if (op == TOK_LAND) {\n        if (js_parse_expr_binary(s, 8, parse_flags))\n            return -1;\n    } else {\n        if (js_parse_logical_and_or(s, TOK_LAND, parse_flags))\n            return -1;\n    }\n    if (s->token.val == op) {\n        label1 = new_label(s);\n\n        for(;;) {\n            if (next_token(s))\n                return -1;\n            emit_op(s, OP_dup);\n            emit_goto(s, op == TOK_LAND ? OP_if_false : OP_if_true, label1);\n            emit_op(s, OP_drop);\n\n            if (op == TOK_LAND) {\n                if (js_parse_expr_binary(s, 8, parse_flags & ~PF_ARROW_FUNC))\n                    return -1;\n            } else {\n                if (js_parse_logical_and_or(s, TOK_LAND,\n                                            parse_flags & ~PF_ARROW_FUNC))\n                    return -1;\n            }\n            if (s->token.val != op) {\n                if (s->token.val == TOK_DOUBLE_QUESTION_MARK)\n                    return js_parse_error(s, \"cannot mix ?? with && or ||\");\n                break;\n            }\n        }\n\n        emit_label(s, label1);\n    }\n    return 0;\n}\n\nstatic __exception int js_parse_coalesce_expr(JSParseState *s, int parse_flags)\n{\n    int label1;\n    \n    if (js_parse_logical_and_or(s, TOK_LOR, parse_flags))\n        return -1;\n    if (s->token.val == TOK_DOUBLE_QUESTION_MARK) {\n        label1 = new_label(s);\n        for(;;) {\n            if (next_token(s))\n                return -1;\n            \n            emit_op(s, OP_dup);\n            emit_op(s, OP_is_undefined_or_null);\n            emit_goto(s, OP_if_false, label1);\n            emit_op(s, OP_drop);\n            \n            if (js_parse_expr_binary(s, 8, parse_flags & ~PF_ARROW_FUNC))\n                return -1;\n            if (s->token.val != TOK_DOUBLE_QUESTION_MARK)\n                break;\n        }\n        emit_label(s, label1);\n    }\n    return 0;\n}\n\n/* allowed parse_flags: PF_ARROW_FUNC, PF_IN_ACCEPTED */\nstatic __exception int js_parse_cond_expr(JSParseState *s, int parse_flags)\n{\n    int label1, label2;\n\n    if (js_parse_coalesce_expr(s, parse_flags))\n        return -1;\n    if (s->token.val == '?') {\n        if (next_token(s))\n            return -1;\n        label1 = emit_goto(s, OP_if_false, -1);\n\n        if (js_parse_assign_expr(s))\n            return -1;\n        if (js_parse_expect(s, ':'))\n            return -1;\n\n        label2 = emit_goto(s, OP_goto, -1);\n\n        emit_label(s, label1);\n\n        if (js_parse_assign_expr2(s, parse_flags & PF_IN_ACCEPTED))\n            return -1;\n\n        emit_label(s, label2);\n    }\n    return 0;\n}\n\nstatic void emit_return(JSParseState *s, BOOL hasval);\n\n/* allowed parse_flags: PF_IN_ACCEPTED */\nstatic __exception int js_parse_assign_expr2(JSParseState *s, int parse_flags)\n{\n    int opcode, op, scope;\n    JSAtom name0 = JS_ATOM_NULL;\n    JSAtom name;\n\n    if (s->token.val == TOK_YIELD) {\n        BOOL is_star = FALSE, is_async;\n        \n        if (!(s->cur_func->func_kind & JS_FUNC_GENERATOR))\n            return js_parse_error(s, \"unexpected 'yield' keyword\");\n        if (!s->cur_func->in_function_body)\n            return js_parse_error(s, \"yield in default expression\");\n        if (next_token(s))\n            return -1;\n        /* XXX: is there a better method to detect 'yield' without\n           parameters ? */\n        if (s->token.val != ';' && s->token.val != ')' &&\n            s->token.val != ']' && s->token.val != '}' &&\n            s->token.val != ',' && s->token.val != ':' && !s->got_lf) {\n            if (s->token.val == '*') {\n                is_star = TRUE;\n                if (next_token(s))\n                    return -1;\n            }\n            if (js_parse_assign_expr2(s, parse_flags))\n                return -1;\n        } else {\n            emit_op(s, OP_undefined);\n        }\n        is_async = (s->cur_func->func_kind == JS_FUNC_ASYNC_GENERATOR);\n\n        if (is_star) {\n            int label_loop, label_return, label_next;\n            int label_return1, label_yield, label_throw, label_throw1;\n            int label_throw2;\n\n            label_loop = new_label(s);\n            label_yield = new_label(s);\n\n            emit_op(s, is_async ? OP_for_await_of_start : OP_for_of_start);\n\n            /* remove the catch offset (XXX: could avoid pushing back\n               undefined) */\n            emit_op(s, OP_drop);\n            emit_op(s, OP_undefined);\n            \n            emit_op(s, OP_undefined); /* initial value */\n            \n            emit_label(s, label_loop);\n            emit_op(s, OP_iterator_next);\n            if (is_async)\n                emit_op(s, OP_await);\n            emit_op(s, OP_iterator_check_object);\n            emit_op(s, OP_get_field2);\n            emit_atom(s, JS_ATOM_done);\n            label_next = emit_goto(s, OP_if_true, -1); /* end of loop */\n            emit_label(s, label_yield);\n            if (is_async) {\n                /* OP_async_yield_star takes the value as parameter */\n                emit_op(s, OP_get_field);\n                emit_atom(s, JS_ATOM_value);\n                emit_op(s, OP_await);\n                emit_op(s, OP_async_yield_star);\n            } else {\n                /* OP_yield_star takes (value, done) as parameter */\n                emit_op(s, OP_yield_star);\n            }\n            emit_op(s, OP_dup);\n            label_return = emit_goto(s, OP_if_true, -1);\n            emit_op(s, OP_drop);\n            emit_goto(s, OP_goto, label_loop);\n            \n            emit_label(s, label_return);\n            emit_op(s, OP_push_i32);\n            emit_u32(s, 2);\n            emit_op(s, OP_strict_eq);\n            label_throw = emit_goto(s, OP_if_true, -1);\n            \n            /* return handling */\n            if (is_async)\n                emit_op(s, OP_await);\n            emit_op(s, OP_iterator_call);\n            emit_u8(s, 0);\n            label_return1 = emit_goto(s, OP_if_true, -1);\n            if (is_async)\n                emit_op(s, OP_await);\n            emit_op(s, OP_iterator_check_object);\n            emit_op(s, OP_get_field2);\n            emit_atom(s, JS_ATOM_done);\n            emit_goto(s, OP_if_false, label_yield);\n\n            emit_op(s, OP_get_field);\n            emit_atom(s, JS_ATOM_value);\n            \n            emit_label(s, label_return1);\n            emit_op(s, OP_nip);\n            emit_op(s, OP_nip);\n            emit_op(s, OP_nip);\n            emit_return(s, TRUE);\n            \n            /* throw handling */\n            emit_label(s, label_throw);\n            emit_op(s, OP_iterator_call);\n            emit_u8(s, 1);\n            label_throw1 = emit_goto(s, OP_if_true, -1);\n            if (is_async)\n                emit_op(s, OP_await);\n            emit_op(s, OP_iterator_check_object);\n            emit_op(s, OP_get_field2);\n            emit_atom(s, JS_ATOM_done);\n            emit_goto(s, OP_if_false, label_yield);\n            emit_goto(s, OP_goto, label_next);\n            /* close the iterator and throw a type error exception */\n            emit_label(s, label_throw1);\n            emit_op(s, OP_iterator_call);\n            emit_u8(s, 2);\n            label_throw2 = emit_goto(s, OP_if_true, -1);\n            if (is_async)\n                emit_op(s, OP_await);\n            emit_label(s, label_throw2);\n\n            emit_op(s, OP_throw_error);\n            emit_atom(s, JS_ATOM_NULL);\n            emit_u8(s, JS_THROW_ERROR_ITERATOR_THROW);\n            \n            emit_label(s, label_next);\n            emit_op(s, OP_get_field);\n            emit_atom(s, JS_ATOM_value);\n            emit_op(s, OP_nip); /* keep the value associated with\n                                   done = true */\n            emit_op(s, OP_nip);\n            emit_op(s, OP_nip);\n        } else {\n            int label_next;\n            \n            if (is_async)\n                emit_op(s, OP_await);\n            emit_op(s, OP_yield);\n            label_next = emit_goto(s, OP_if_false, -1);\n            emit_return(s, TRUE);\n            emit_label(s, label_next);\n        }\n        return 0;\n    }\n    if (s->token.val == TOK_IDENT) {\n        /* name0 is used to check for OP_set_name pattern, not duplicated */\n        name0 = s->token.u.ident.atom;\n    }\n    if (js_parse_cond_expr(s, parse_flags | PF_ARROW_FUNC))\n        return -1;\n\n    op = s->token.val;\n    if (op == '=' || (op >= TOK_MUL_ASSIGN && op <= TOK_POW_ASSIGN)) {\n        int label;\n        if (next_token(s))\n            return -1;\n        if (get_lvalue(s, &opcode, &scope, &name, &label, NULL, (op != '='), op) < 0)\n            return -1;\n\n        if (js_parse_assign_expr2(s, parse_flags)) {\n            JS_FreeAtom(s->ctx, name);\n            return -1;\n        }\n\n        if (op == '=') {\n            if (opcode == OP_get_ref_value && name == name0) {\n                set_object_name(s, name);\n            }\n        } else {\n            static const uint8_t assign_opcodes[] = {\n                OP_mul, OP_div, OP_mod, OP_add, OP_sub,\n                OP_shl, OP_sar, OP_shr, OP_and, OP_xor, OP_or,\n#ifdef CONFIG_BIGNUM\n                OP_pow,\n#endif\n                OP_pow,\n            };\n            op = assign_opcodes[op - TOK_MUL_ASSIGN];\n#ifdef CONFIG_BIGNUM\n            if (s->cur_func->js_mode & JS_MODE_MATH) {\n                if (op == OP_mod)\n                    op = OP_math_mod;\n            }\n#endif\n            emit_op(s, op);\n        }\n        put_lvalue(s, opcode, scope, name, label, PUT_LVALUE_KEEP_TOP, FALSE);\n    } else if (op >= TOK_LAND_ASSIGN && op <= TOK_DOUBLE_QUESTION_MARK_ASSIGN) {\n        int label, label1, depth_lvalue, label2;\n        \n        if (next_token(s))\n            return -1;\n        if (get_lvalue(s, &opcode, &scope, &name, &label,\n                       &depth_lvalue, TRUE, op) < 0)\n            return -1;\n\n        emit_op(s, OP_dup);\n        if (op == TOK_DOUBLE_QUESTION_MARK_ASSIGN)\n            emit_op(s, OP_is_undefined_or_null);\n        label1 = emit_goto(s, op == TOK_LOR_ASSIGN ? OP_if_true : OP_if_false,\n                           -1);\n        emit_op(s, OP_drop);\n        \n        if (js_parse_assign_expr2(s, parse_flags)) {\n            JS_FreeAtom(s->ctx, name);\n            return -1;\n        }\n\n        if (opcode == OP_get_ref_value && name == name0) {\n            set_object_name(s, name);\n        }\n        \n        switch(depth_lvalue) {\n        case 1:\n            emit_op(s, OP_insert2);\n            break;\n        case 2:\n            emit_op(s, OP_insert3);\n            break;\n        case 3:\n            emit_op(s, OP_insert4);\n            break;\n        default:\n            abort();\n        }\n\n        /* XXX: we disable the OP_put_ref_value optimization by not\n           using put_lvalue() otherwise depth_lvalue is not correct */\n        put_lvalue(s, opcode, scope, name, label, PUT_LVALUE_NOKEEP_DEPTH,\n                   FALSE);\n        label2 = emit_goto(s, OP_goto, -1);\n        \n        emit_label(s, label1);\n\n        /* remove the lvalue stack entries */\n        while (depth_lvalue != 0) {\n            emit_op(s, OP_nip);\n            depth_lvalue--;\n        }\n\n        emit_label(s, label2);\n    }\n    return 0;\n}\n\nstatic __exception int js_parse_assign_expr(JSParseState *s)\n{\n    return js_parse_assign_expr2(s, PF_IN_ACCEPTED);\n}\n\n/* allowed parse_flags: PF_IN_ACCEPTED */\nstatic __exception int js_parse_expr2(JSParseState *s, int parse_flags)\n{\n    BOOL comma = FALSE;\n    for(;;) {\n        if (js_parse_assign_expr2(s, parse_flags))\n            return -1;\n        if (comma) {\n            /* prevent get_lvalue from using the last expression\n               as an lvalue. This also prevents the conversion of\n               of get_var to get_ref for method lookup in function\n               call inside `with` statement.\n             */\n            s->cur_func->last_opcode_pos = -1;\n        }\n        if (s->token.val != ',')\n            break;\n        comma = TRUE;\n        if (next_token(s))\n            return -1;\n        emit_op(s, OP_drop);\n    }\n    return 0;\n}\n\nstatic __exception int js_parse_expr(JSParseState *s)\n{\n    return js_parse_expr2(s, PF_IN_ACCEPTED);\n}\n\nstatic void push_break_entry(JSFunctionDef *fd, BlockEnv *be,\n                             JSAtom label_name,\n                             int label_break, int label_cont,\n                             int drop_count)\n{\n    be->prev = fd->top_break;\n    fd->top_break = be;\n    be->label_name = label_name;\n    be->label_break = label_break;\n    be->label_cont = label_cont;\n    be->drop_count = drop_count;\n    be->label_finally = -1;\n    be->scope_level = fd->scope_level;\n    be->has_iterator = FALSE;\n}\n\nstatic void pop_break_entry(JSFunctionDef *fd)\n{\n    BlockEnv *be;\n    be = fd->top_break;\n    fd->top_break = be->prev;\n}\n\nstatic __exception int emit_break(JSParseState *s, JSAtom name, int is_cont)\n{\n    BlockEnv *top;\n    int i, scope_level;\n\n    scope_level = s->cur_func->scope_level;\n    top = s->cur_func->top_break;\n    while (top != NULL) {\n        close_scopes(s, scope_level, top->scope_level);\n        scope_level = top->scope_level;\n        if (is_cont &&\n            top->label_cont != -1 &&\n            (name == JS_ATOM_NULL || top->label_name == name)) {\n            /* continue stays inside the same block */\n            emit_goto(s, OP_goto, top->label_cont);\n            return 0;\n        }\n        if (!is_cont &&\n            top->label_break != -1 &&\n            (name == JS_ATOM_NULL || top->label_name == name)) {\n            emit_goto(s, OP_goto, top->label_break);\n            return 0;\n        }\n        i = 0;\n        if (top->has_iterator) {\n            emit_op(s, OP_iterator_close);\n            i += 3;\n        }\n        for(; i < top->drop_count; i++)\n            emit_op(s, OP_drop);\n        if (top->label_finally != -1) {\n            /* must push dummy value to keep same stack depth */\n            emit_op(s, OP_undefined);\n            emit_goto(s, OP_gosub, top->label_finally);\n            emit_op(s, OP_drop);\n        }\n        top = top->prev;\n    }\n    if (name == JS_ATOM_NULL) {\n        if (is_cont)\n            return js_parse_error(s, \"continue must be inside loop\");\n        else\n            return js_parse_error(s, \"break must be inside loop or switch\");\n    } else {\n        return js_parse_error(s, \"break/continue label not found\");\n    }\n}\n\n/* execute the finally blocks before return */\nstatic void emit_return(JSParseState *s, BOOL hasval)\n{\n    BlockEnv *top;\n    int drop_count;\n\n    drop_count = 0;\n    top = s->cur_func->top_break;\n    while (top != NULL) {\n        /* XXX: emit the appropriate OP_leave_scope opcodes? Probably not\n           required as all local variables will be closed upon returning\n           from JS_CallInternal, but not in the same order. */\n        if (top->has_iterator) {\n            /* with 'yield', the exact number of OP_drop to emit is\n               unknown, so we use a specific operation to look for\n               the catch offset */\n            if (!hasval) {\n                emit_op(s, OP_undefined);\n                hasval = TRUE;\n            }\n            emit_op(s, OP_iterator_close_return);\n            if (s->cur_func->func_kind == JS_FUNC_ASYNC_GENERATOR) {\n                int label_next, label_next2;\n\n                emit_op(s, OP_drop); /* catch offset */\n                emit_op(s, OP_drop); /* next */\n                emit_op(s, OP_get_field2);\n                emit_atom(s, JS_ATOM_return);\n                /* stack: iter_obj return_func */\n                emit_op(s, OP_dup);\n                emit_op(s, OP_is_undefined_or_null);\n                label_next = emit_goto(s, OP_if_true, -1);\n                emit_op(s, OP_call_method);\n                emit_u16(s, 0);\n                emit_op(s, OP_iterator_check_object);\n                emit_op(s, OP_await);\n                label_next2 = emit_goto(s, OP_goto, -1);\n                emit_label(s, label_next);\n                emit_op(s, OP_drop);\n                emit_label(s, label_next2);\n                emit_op(s, OP_drop);\n            } else {\n                emit_op(s, OP_iterator_close);\n            }\n            drop_count = -3;\n        }\n        drop_count += top->drop_count;\n        if (top->label_finally != -1) {\n            while(drop_count) {\n                /* must keep the stack top if hasval */\n                emit_op(s, hasval ? OP_nip : OP_drop);\n                drop_count--;\n            }\n            if (!hasval) {\n                /* must push return value to keep same stack size */\n                emit_op(s, OP_undefined);\n                hasval = TRUE;\n            }\n            emit_goto(s, OP_gosub, top->label_finally);\n        }\n        top = top->prev;\n    }\n    if (s->cur_func->is_derived_class_constructor) {\n        int label_return;\n\n        /* 'this' can be uninitialized, so it may be accessed only if\n           the derived class constructor does not return an object */\n        if (hasval) {\n            emit_op(s, OP_check_ctor_return);\n            label_return = emit_goto(s, OP_if_false, -1);\n            emit_op(s, OP_drop);\n        } else {\n            label_return = -1;\n        }\n\n        /* XXX: if this is not initialized, should throw the\n           ReferenceError in the caller realm */\n        emit_op(s, OP_scope_get_var);\n        emit_atom(s, JS_ATOM_this);\n        emit_u16(s, 0);\n\n        emit_label(s, label_return);\n        emit_op(s, OP_return);\n    } else if (s->cur_func->func_kind != JS_FUNC_NORMAL) {\n        if (!hasval) {\n            emit_op(s, OP_undefined);\n        } else if (s->cur_func->func_kind == JS_FUNC_ASYNC_GENERATOR) {\n            emit_op(s, OP_await);\n        }\n        emit_op(s, OP_return_async);\n    } else {\n        emit_op(s, hasval ? OP_return : OP_return_undef);\n    }\n}\n\n#define DECL_MASK_FUNC  (1 << 0) /* allow normal function declaration */\n/* ored with DECL_MASK_FUNC if function declarations are allowed with a label */\n#define DECL_MASK_FUNC_WITH_LABEL (1 << 1)\n#define DECL_MASK_OTHER (1 << 2) /* all other declarations */\n#define DECL_MASK_ALL   (DECL_MASK_FUNC | DECL_MASK_FUNC_WITH_LABEL | DECL_MASK_OTHER)\n\nstatic __exception int js_parse_statement_or_decl(JSParseState *s,\n                                                  int decl_mask);\n\nstatic __exception int js_parse_statement(JSParseState *s)\n{\n    return js_parse_statement_or_decl(s, 0);\n}\n\nstatic __exception int js_parse_block(JSParseState *s)\n{\n    if (js_parse_expect(s, '{'))\n        return -1;\n    if (s->token.val != '}') {\n        push_scope(s);\n        for(;;) {\n            if (js_parse_statement_or_decl(s, DECL_MASK_ALL))\n                return -1;\n            if (s->token.val == '}')\n                break;\n        }\n        pop_scope(s);\n    }\n    if (next_token(s))\n        return -1;\n    return 0;\n}\n\n/* allowed parse_flags: PF_IN_ACCEPTED */\nstatic __exception int js_parse_var(JSParseState *s, int parse_flags, int tok,\n                                    BOOL export_flag)\n{\n    JSContext *ctx = s->ctx;\n    JSFunctionDef *fd = s->cur_func;\n    JSAtom name = JS_ATOM_NULL;\n\n    for (;;) {\n        if (s->token.val == TOK_IDENT) {\n            if (s->token.u.ident.is_reserved) {\n                return js_parse_error_reserved_identifier(s);\n            }\n            name = JS_DupAtom(ctx, s->token.u.ident.atom);\n            if (name == JS_ATOM_let && (tok == TOK_LET || tok == TOK_CONST)) {\n                js_parse_error(s, \"'let' is not a valid lexical identifier\");\n                goto var_error;\n            }\n            if (next_token(s))\n                goto var_error;\n            if (js_define_var(s, name, tok))\n                goto var_error;\n            if (export_flag) {\n                if (!add_export_entry(s, s->cur_func->module, name, name,\n                                      JS_EXPORT_TYPE_LOCAL))\n                    goto var_error;\n            }\n\n            if (s->token.val == '=') {\n                if (next_token(s))\n                    goto var_error;\n                if (tok == TOK_VAR) {\n                    /* Must make a reference for proper `with` semantics */\n                    int opcode, scope, label;\n                    JSAtom name1;\n\n                    emit_op(s, OP_scope_get_var);\n                    emit_atom(s, name);\n                    emit_u16(s, fd->scope_level);\n                    if (get_lvalue(s, &opcode, &scope, &name1, &label, NULL, FALSE, '=') < 0)\n                        goto var_error;\n                    if (js_parse_assign_expr2(s, parse_flags)) {\n                        JS_FreeAtom(ctx, name1);\n                        goto var_error;\n                    }\n                    set_object_name(s, name);\n                    put_lvalue(s, opcode, scope, name1, label,\n                               PUT_LVALUE_NOKEEP, FALSE);\n                } else {\n                    if (js_parse_assign_expr2(s, parse_flags))\n                        goto var_error;\n                    set_object_name(s, name);\n                    emit_op(s, (tok == TOK_CONST || tok == TOK_LET) ?\n                        OP_scope_put_var_init : OP_scope_put_var);\n                    emit_atom(s, name);\n                    emit_u16(s, fd->scope_level);\n                }\n            } else {\n                if (tok == TOK_CONST) {\n                    js_parse_error(s, \"missing initializer for const variable\");\n                    goto var_error;\n                }\n                if (tok == TOK_LET) {\n                    /* initialize lexical variable upon entering its scope */\n                    emit_op(s, OP_undefined);\n                    emit_op(s, OP_scope_put_var_init);\n                    emit_atom(s, name);\n                    emit_u16(s, fd->scope_level);\n                }\n            }\n            JS_FreeAtom(ctx, name);\n        } else {\n            int skip_bits;\n            if ((s->token.val == '[' || s->token.val == '{')\n            &&  js_parse_skip_parens_token(s, &skip_bits, FALSE) == '=') {\n                emit_op(s, OP_undefined);\n                if (js_parse_destructuring_element(s, tok, 0, TRUE, skip_bits & SKIP_HAS_ELLIPSIS, TRUE) < 0)\n                    return -1;\n            } else {\n                return js_parse_error(s, \"variable name expected\");\n            }\n        }\n        if (s->token.val != ',')\n            break;\n        if (next_token(s))\n            return -1;\n    }\n    return 0;\n\n var_error:\n    JS_FreeAtom(ctx, name);\n    return -1;\n}\n\n/* test if the current token is a label. Use simplistic look-ahead scanner */\nstatic BOOL is_label(JSParseState *s)\n{\n    return (s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved &&\n            peek_token(s, FALSE) == ':');\n}\n\n/* test if the current token is a let keyword. Use simplistic look-ahead scanner */\nstatic int is_let(JSParseState *s, int decl_mask)\n{\n    int res = FALSE;\n\n    if (token_is_pseudo_keyword(s, JS_ATOM_let)) {\n#if 1\n        JSParsePos pos;\n        js_parse_get_pos(s, &pos);\n        for (;;) {\n            if (next_token(s)) {\n                res = -1;\n                break;\n            }\n            if (s->token.val == '[') {\n                /* let [ is a syntax restriction:\n                   it never introduces an ExpressionStatement */\n                res = TRUE;\n                break;\n            }\n            if (s->token.val == '{' ||\n                (s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved) ||\n                s->token.val == TOK_LET ||\n                s->token.val == TOK_YIELD ||\n                s->token.val == TOK_AWAIT) {\n                /* Check for possible ASI if not scanning for Declaration */\n                /* XXX: should also check that `{` introduces a BindingPattern,\n                   but Firefox does not and rejects eval(\"let=1;let\\n{if(1)2;}\") */\n                if (s->last_line_num == s->token.line_num || (decl_mask & DECL_MASK_OTHER)) {\n                    res = TRUE;\n                    break;\n                }\n                break;\n            }\n            break;\n        }\n        if (js_parse_seek_token(s, &pos)) {\n            res = -1;\n        }\n#else\n        int tok = peek_token(s, TRUE);\n        if (tok == '{' || tok == TOK_IDENT || peek_token(s, FALSE) == '[') {\n            res = TRUE;\n        }\n#endif\n    }\n    return res;\n}\n\n/* XXX: handle IteratorClose when exiting the loop before the\n   enumeration is done */\nstatic __exception int js_parse_for_in_of(JSParseState *s, int label_name,\n                                          BOOL is_async)\n{\n    JSContext *ctx = s->ctx;\n    JSFunctionDef *fd = s->cur_func;\n    JSAtom var_name;\n    BOOL has_initializer, is_for_of, has_destructuring;\n    int tok, tok1, opcode, scope, block_scope_level;\n    int label_next, label_expr, label_cont, label_body, label_break;\n    int pos_next, pos_expr;\n    BlockEnv break_entry;\n\n    has_initializer = FALSE;\n    has_destructuring = FALSE;\n    is_for_of = FALSE;\n    block_scope_level = fd->scope_level;\n    label_cont = new_label(s);\n    label_body = new_label(s);\n    label_break = new_label(s);\n    label_next = new_label(s);\n\n    /* create scope for the lexical variables declared in the enumeration\n       expressions. XXX: Not completely correct because of weird capturing\n       semantics in `for (i of o) a.push(function(){return i})` */\n    push_scope(s);\n\n    /* local for_in scope starts here so individual elements\n       can be closed in statement. */\n    push_break_entry(s->cur_func, &break_entry,\n                     label_name, label_break, label_cont, 1);\n    break_entry.scope_level = block_scope_level;\n\n    label_expr = emit_goto(s, OP_goto, -1);\n\n    pos_next = s->cur_func->byte_code.size;\n    emit_label(s, label_next);\n\n    tok = s->token.val;\n    switch (is_let(s, DECL_MASK_OTHER)) {\n    case TRUE:\n        tok = TOK_LET;\n        break;\n    case FALSE:\n        break;\n    default:\n        return -1;\n    }\n    if (tok == TOK_VAR || tok == TOK_LET || tok == TOK_CONST) {\n        if (next_token(s))\n            return -1;\n\n        if (!(s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved)) {\n            if (s->token.val == '[' || s->token.val == '{') {\n                if (js_parse_destructuring_element(s, tok, 0, TRUE, -1, FALSE) < 0)\n                    return -1;\n                has_destructuring = TRUE;\n            } else {\n                return js_parse_error(s, \"variable name expected\");\n            }\n            var_name = JS_ATOM_NULL;\n        } else {\n            var_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n            if (next_token(s)) {\n                JS_FreeAtom(s->ctx, var_name);\n                return -1;\n            }\n            if (js_define_var(s, var_name, tok)) {\n                JS_FreeAtom(s->ctx, var_name);\n                return -1;\n            }\n            emit_op(s, (tok == TOK_CONST || tok == TOK_LET) ?\n                    OP_scope_put_var_init : OP_scope_put_var);\n            emit_atom(s, var_name);\n            emit_u16(s, fd->scope_level);\n        }\n    } else {\n        int skip_bits;\n        if ((s->token.val == '[' || s->token.val == '{')\n        &&  ((tok1 = js_parse_skip_parens_token(s, &skip_bits, FALSE)) == TOK_IN || tok1 == TOK_OF)) {\n            if (js_parse_destructuring_element(s, 0, 0, TRUE, skip_bits & SKIP_HAS_ELLIPSIS, TRUE) < 0)\n                return -1;\n        } else {\n            int lvalue_label;\n            if (js_parse_left_hand_side_expr(s))\n                return -1;\n            if (get_lvalue(s, &opcode, &scope, &var_name, &lvalue_label,\n                           NULL, FALSE, TOK_FOR))\n                return -1;\n            put_lvalue(s, opcode, scope, var_name, lvalue_label,\n                       PUT_LVALUE_NOKEEP_BOTTOM, FALSE);\n        }\n        var_name = JS_ATOM_NULL;\n    }\n    emit_goto(s, OP_goto, label_body);\n\n    pos_expr = s->cur_func->byte_code.size;\n    emit_label(s, label_expr);\n    if (s->token.val == '=') {\n        /* XXX: potential scoping issue if inside `with` statement */\n        has_initializer = TRUE;\n        /* parse and evaluate initializer prior to evaluating the\n           object (only used with \"for in\" with a non lexical variable\n           in non strict mode */\n        if (next_token(s) || js_parse_assign_expr2(s, 0)) {\n            JS_FreeAtom(ctx, var_name);\n            return -1;\n        }\n        if (var_name != JS_ATOM_NULL) {\n            emit_op(s, OP_scope_put_var);\n            emit_atom(s, var_name);\n            emit_u16(s, fd->scope_level);\n        }\n    }\n    JS_FreeAtom(ctx, var_name);\n\n    if (token_is_pseudo_keyword(s, JS_ATOM_of)) {\n        break_entry.has_iterator = is_for_of = TRUE;\n        break_entry.drop_count += 2;\n        if (has_initializer)\n            goto initializer_error;\n    } else if (s->token.val == TOK_IN) {\n        if (is_async)\n            return js_parse_error(s, \"'for await' loop should be used with 'of'\");\n        if (has_initializer &&\n            (tok != TOK_VAR || (fd->js_mode & JS_MODE_STRICT) ||\n             has_destructuring)) {\n        initializer_error:\n            return js_parse_error(s, \"a declaration in the head of a for-%s loop can't have an initializer\",\n                                  is_for_of ? \"of\" : \"in\");\n        }\n    } else {\n        return js_parse_error(s, \"expected 'of' or 'in' in for control expression\");\n    }\n    if (next_token(s))\n        return -1;\n    if (is_for_of) {\n        if (js_parse_assign_expr(s))\n            return -1;\n    } else {\n        if (js_parse_expr(s))\n            return -1;\n    }\n    /* close the scope after having evaluated the expression so that\n       the TDZ values are in the closures */\n    close_scopes(s, s->cur_func->scope_level, block_scope_level);\n    if (is_for_of) {\n        if (is_async)\n            emit_op(s, OP_for_await_of_start);\n        else\n            emit_op(s, OP_for_of_start);\n        /* on stack: enum_rec */\n    } else {\n        emit_op(s, OP_for_in_start);\n        /* on stack: enum_obj */\n    }\n    emit_goto(s, OP_goto, label_cont);\n\n    if (js_parse_expect(s, ')'))\n        return -1;\n\n    if (OPTIMIZE) {\n        /* move the `next` code here */\n        DynBuf *bc = &s->cur_func->byte_code;\n        int chunk_size = pos_expr - pos_next;\n        int offset = bc->size - pos_next;\n        int i;\n        dbuf_realloc(bc, bc->size + chunk_size);\n        dbuf_put(bc, bc->buf + pos_next, chunk_size);\n        memset(bc->buf + pos_next, OP_nop, chunk_size);\n        /* `next` part ends with a goto */\n        s->cur_func->last_opcode_pos = bc->size - 5;\n        /* relocate labels */\n        for (i = label_cont; i < s->cur_func->label_count; i++) {\n            LabelSlot *ls = &s->cur_func->label_slots[i];\n            if (ls->pos >= pos_next && ls->pos < pos_expr)\n                ls->pos += offset;\n        }\n    }\n\n    emit_label(s, label_body);\n    if (js_parse_statement(s))\n        return -1;\n\n    close_scopes(s, s->cur_func->scope_level, block_scope_level);\n\n    emit_label(s, label_cont);\n    if (is_for_of) {\n        if (is_async) {\n            /* call the next method */\n            /* stack: iter_obj next catch_offset */\n            emit_op(s, OP_dup3);\n            emit_op(s, OP_drop);\n            emit_op(s, OP_call_method);\n            emit_u16(s, 0);\n            /* get the result of the promise */\n            emit_op(s, OP_await);\n            /* unwrap the value and done values */\n            emit_op(s, OP_iterator_get_value_done);\n        } else {\n            emit_op(s, OP_for_of_next);\n            emit_u8(s, 0);\n        }\n    } else {\n        emit_op(s, OP_for_in_next);\n    }\n    /* on stack: enum_rec / enum_obj value bool */\n    emit_goto(s, OP_if_false, label_next);\n    /* drop the undefined value from for_xx_next */\n    emit_op(s, OP_drop);\n\n    emit_label(s, label_break);\n    if (is_for_of) {\n        /* close and drop enum_rec */\n        emit_op(s, OP_iterator_close);\n    } else {\n        emit_op(s, OP_drop);\n    }\n    pop_break_entry(s->cur_func);\n    pop_scope(s);\n    return 0;\n}\n\nstatic void set_eval_ret_undefined(JSParseState *s)\n{\n    if (s->cur_func->eval_ret_idx >= 0) {\n        emit_op(s, OP_undefined);\n        emit_op(s, OP_put_loc);\n        emit_u16(s, s->cur_func->eval_ret_idx);\n    }\n}\n\nstatic __exception int js_parse_statement_or_decl(JSParseState *s,\n                                                  int decl_mask)\n{\n    JSContext *ctx = s->ctx;\n    JSAtom label_name;\n    int tok;\n\n    /* specific label handling */\n    /* XXX: support multiple labels on loop statements */\n    label_name = JS_ATOM_NULL;\n    if (is_label(s)) {\n        BlockEnv *be;\n\n        label_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n\n        for (be = s->cur_func->top_break; be; be = be->prev) {\n            if (be->label_name == label_name) {\n                js_parse_error(s, \"duplicate label name\");\n                goto fail;\n            }\n        }\n\n        if (next_token(s))\n            goto fail;\n        if (js_parse_expect(s, ':'))\n            goto fail;\n        if (s->token.val != TOK_FOR\n        &&  s->token.val != TOK_DO\n        &&  s->token.val != TOK_WHILE) {\n            /* labelled regular statement */\n            int label_break, mask;\n            BlockEnv break_entry;\n\n            label_break = new_label(s);\n            push_break_entry(s->cur_func, &break_entry,\n                             label_name, label_break, -1, 0);\n            if (!(s->cur_func->js_mode & JS_MODE_STRICT) &&\n                (decl_mask & DECL_MASK_FUNC_WITH_LABEL)) {\n                mask = DECL_MASK_FUNC | DECL_MASK_FUNC_WITH_LABEL;\n            } else {\n                mask = 0;\n            }\n            if (js_parse_statement_or_decl(s, mask))\n                goto fail;\n            emit_label(s, label_break);\n            pop_break_entry(s->cur_func);\n            goto done;\n        }\n    }\n\n    switch(tok = s->token.val) {\n    case '{':\n        if (js_parse_block(s))\n            goto fail;\n        break;\n    case TOK_RETURN:\n        if (s->cur_func->is_eval) {\n            js_parse_error(s, \"return not in a function\");\n            goto fail;\n        }\n        if (next_token(s))\n            goto fail;\n        if (s->token.val != ';' && s->token.val != '}' && !s->got_lf) {\n            if (js_parse_expr(s))\n                goto fail;\n            emit_return(s, TRUE);\n        } else {\n            emit_return(s, FALSE);\n        }\n        if (js_parse_expect_semi(s))\n            goto fail;\n        break;\n    case TOK_THROW:\n        if (next_token(s))\n            goto fail;\n        if (s->got_lf) {\n            js_parse_error(s, \"line terminator not allowed after throw\");\n            goto fail;\n        }\n        if (js_parse_expr(s))\n            goto fail;\n        emit_op(s, OP_throw);\n        if (js_parse_expect_semi(s))\n            goto fail;\n        break;\n    case TOK_LET:\n    case TOK_CONST:\n    haslet:\n        if (!(decl_mask & DECL_MASK_OTHER)) {\n            js_parse_error(s, \"lexical declarations can't appear in single-statement context\");\n            goto fail;\n        }\n        /* fall thru */\n    case TOK_VAR:\n        if (next_token(s))\n            goto fail;\n        if (js_parse_var(s, TRUE, tok, FALSE))\n            goto fail;\n        if (js_parse_expect_semi(s))\n            goto fail;\n        break;\n    case TOK_IF:\n        {\n            int label1, label2, mask;\n            if (next_token(s))\n                goto fail;\n            /* create a new scope for `let f;if(1) function f(){}` */\n            push_scope(s);\n            set_eval_ret_undefined(s);\n            if (js_parse_expr_paren(s))\n                goto fail;\n            label1 = emit_goto(s, OP_if_false, -1);\n            if (s->cur_func->js_mode & JS_MODE_STRICT)\n                mask = 0;\n            else\n                mask = DECL_MASK_FUNC; /* Annex B.3.4 */\n\n            if (js_parse_statement_or_decl(s, mask))\n                goto fail;\n\n            if (s->token.val == TOK_ELSE) {\n                label2 = emit_goto(s, OP_goto, -1);\n                if (next_token(s))\n                    goto fail;\n\n                emit_label(s, label1);\n                if (js_parse_statement_or_decl(s, mask))\n                    goto fail;\n\n                label1 = label2;\n            }\n            emit_label(s, label1);\n            pop_scope(s);\n        }\n        break;\n    case TOK_WHILE:\n        {\n            int label_cont, label_break;\n            BlockEnv break_entry;\n\n            label_cont = new_label(s);\n            label_break = new_label(s);\n\n            push_break_entry(s->cur_func, &break_entry,\n                             label_name, label_break, label_cont, 0);\n\n            if (next_token(s))\n                goto fail;\n\n            set_eval_ret_undefined(s);\n\n            emit_label(s, label_cont);\n            if (js_parse_expr_paren(s))\n                goto fail;\n            emit_goto(s, OP_if_false, label_break);\n\n            if (js_parse_statement(s))\n                goto fail;\n            emit_goto(s, OP_goto, label_cont);\n\n            emit_label(s, label_break);\n\n            pop_break_entry(s->cur_func);\n        }\n        break;\n    case TOK_DO:\n        {\n            int label_cont, label_break, label1;\n            BlockEnv break_entry;\n\n            label_cont = new_label(s);\n            label_break = new_label(s);\n            label1 = new_label(s);\n\n            push_break_entry(s->cur_func, &break_entry,\n                             label_name, label_break, label_cont, 0);\n\n            if (next_token(s))\n                goto fail;\n\n            emit_label(s, label1);\n\n            set_eval_ret_undefined(s);\n\n            if (js_parse_statement(s))\n                goto fail;\n\n            emit_label(s, label_cont);\n            if (js_parse_expect(s, TOK_WHILE))\n                goto fail;\n            if (js_parse_expr_paren(s))\n                goto fail;\n            /* Insert semicolon if missing */\n            if (s->token.val == ';') {\n                if (next_token(s))\n                    goto fail;\n            }\n            emit_goto(s, OP_if_true, label1);\n\n            emit_label(s, label_break);\n\n            pop_break_entry(s->cur_func);\n        }\n        break;\n    case TOK_FOR:\n        {\n            int label_cont, label_break, label_body, label_test;\n            int pos_cont, pos_body, block_scope_level;\n            BlockEnv break_entry;\n            int tok, bits;\n            BOOL is_async;\n\n            if (next_token(s))\n                goto fail;\n\n            set_eval_ret_undefined(s);\n            bits = 0;\n            is_async = FALSE;\n            if (s->token.val == '(') {\n                js_parse_skip_parens_token(s, &bits, FALSE);\n            } else if (s->token.val == TOK_AWAIT) {\n                if (!(s->cur_func->func_kind & JS_FUNC_ASYNC)) {\n                    js_parse_error(s, \"for await is only valid in asynchronous functions\");\n                    goto fail;\n                }\n                is_async = TRUE;\n                if (next_token(s))\n                    goto fail;\n            }\n            if (js_parse_expect(s, '('))\n                goto fail;\n\n            if (!(bits & SKIP_HAS_SEMI)) {\n                /* parse for/in or for/of */\n                if (js_parse_for_in_of(s, label_name, is_async))\n                    goto fail;\n                break;\n            }\n            block_scope_level = s->cur_func->scope_level;\n\n            /* create scope for the lexical variables declared in the initial,\n               test and increment expressions */\n            push_scope(s);\n            /* initial expression */\n            tok = s->token.val;\n            if (tok != ';') {\n                switch (is_let(s, DECL_MASK_OTHER)) {\n                case TRUE:\n                    tok = TOK_LET;\n                    break;\n                case FALSE:\n                    break;\n                default:\n                    goto fail;\n                }\n                if (tok == TOK_VAR || tok == TOK_LET || tok == TOK_CONST) {\n                    if (next_token(s))\n                        goto fail;\n                    if (js_parse_var(s, FALSE, tok, FALSE))\n                        goto fail;\n                } else {\n                    if (js_parse_expr2(s, FALSE))\n                        goto fail;\n                    emit_op(s, OP_drop);\n                }\n\n                /* close the closures before the first iteration */\n                close_scopes(s, s->cur_func->scope_level, block_scope_level);\n            }\n            if (js_parse_expect(s, ';'))\n                goto fail;\n\n            label_test = new_label(s);\n            label_cont = new_label(s);\n            label_body = new_label(s);\n            label_break = new_label(s);\n\n            push_break_entry(s->cur_func, &break_entry,\n                             label_name, label_break, label_cont, 0);\n\n            /* test expression */\n            if (s->token.val == ';') {\n                /* no test expression */\n                label_test = label_body;\n            } else {\n                emit_label(s, label_test);\n                if (js_parse_expr(s))\n                    goto fail;\n                emit_goto(s, OP_if_false, label_break);\n            }\n            if (js_parse_expect(s, ';'))\n                goto fail;\n\n            if (s->token.val == ')') {\n                /* no end expression */\n                break_entry.label_cont = label_cont = label_test;\n                pos_cont = 0; /* avoid warning */\n            } else {\n                /* skip the end expression */\n                emit_goto(s, OP_goto, label_body);\n\n                pos_cont = s->cur_func->byte_code.size;\n                emit_label(s, label_cont);\n                if (js_parse_expr(s))\n                    goto fail;\n                emit_op(s, OP_drop);\n                if (label_test != label_body)\n                    emit_goto(s, OP_goto, label_test);\n            }\n            if (js_parse_expect(s, ')'))\n                goto fail;\n\n            pos_body = s->cur_func->byte_code.size;\n            emit_label(s, label_body);\n            if (js_parse_statement(s))\n                goto fail;\n\n            /* close the closures before the next iteration */\n            /* XXX: check continue case */\n            close_scopes(s, s->cur_func->scope_level, block_scope_level);\n\n            if (OPTIMIZE && label_test != label_body && label_cont != label_test) {\n                /* move the increment code here */\n                DynBuf *bc = &s->cur_func->byte_code;\n                int chunk_size = pos_body - pos_cont;\n                int offset = bc->size - pos_cont;\n                int i;\n                dbuf_realloc(bc, bc->size + chunk_size);\n                dbuf_put(bc, bc->buf + pos_cont, chunk_size);\n                memset(bc->buf + pos_cont, OP_nop, chunk_size);\n                /* increment part ends with a goto */\n                s->cur_func->last_opcode_pos = bc->size - 5;\n                /* relocate labels */\n                for (i = label_cont; i < s->cur_func->label_count; i++) {\n                    LabelSlot *ls = &s->cur_func->label_slots[i];\n                    if (ls->pos >= pos_cont && ls->pos < pos_body)\n                        ls->pos += offset;\n                }\n            } else {\n                emit_goto(s, OP_goto, label_cont);\n            }\n\n            emit_label(s, label_break);\n\n            pop_break_entry(s->cur_func);\n            pop_scope(s);\n        }\n        break;\n    case TOK_BREAK:\n    case TOK_CONTINUE:\n        {\n            int is_cont = s->token.val - TOK_BREAK;\n            int label;\n\n            if (next_token(s))\n                goto fail;\n            if (!s->got_lf && s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved)\n                label = s->token.u.ident.atom;\n            else\n                label = JS_ATOM_NULL;\n            if (emit_break(s, label, is_cont))\n                goto fail;\n            if (label != JS_ATOM_NULL) {\n                if (next_token(s))\n                    goto fail;\n            }\n            if (js_parse_expect_semi(s))\n                goto fail;\n        }\n        break;\n    case TOK_SWITCH:\n        {\n            int label_case, label_break, label1;\n            int default_label_pos;\n            BlockEnv break_entry;\n\n            if (next_token(s))\n                goto fail;\n\n            set_eval_ret_undefined(s);\n            if (js_parse_expr_paren(s))\n                goto fail;\n\n            push_scope(s);\n            label_break = new_label(s);\n            push_break_entry(s->cur_func, &break_entry,\n                             label_name, label_break, -1, 1);\n\n            if (js_parse_expect(s, '{'))\n                goto fail;\n\n            default_label_pos = -1;\n            label_case = -1;\n            while (s->token.val != '}') {\n                if (s->token.val == TOK_CASE) {\n                    label1 = -1;\n                    if (label_case >= 0) {\n                        /* skip the case if needed */\n                        label1 = emit_goto(s, OP_goto, -1);\n                    }\n                    emit_label(s, label_case);\n                    label_case = -1;\n                    for (;;) {\n                        /* parse a sequence of case clauses */\n                        if (next_token(s))\n                            goto fail;\n                        emit_op(s, OP_dup);\n                        if (js_parse_expr(s))\n                            goto fail;\n                        if (js_parse_expect(s, ':'))\n                            goto fail;\n                        emit_op(s, OP_strict_eq);\n                        if (s->token.val == TOK_CASE) {\n                            label1 = emit_goto(s, OP_if_true, label1);\n                        } else {\n                            label_case = emit_goto(s, OP_if_false, -1);\n                            emit_label(s, label1);\n                            break;\n                        }\n                    }\n                } else if (s->token.val == TOK_DEFAULT) {\n                    if (next_token(s))\n                        goto fail;\n                    if (js_parse_expect(s, ':'))\n                        goto fail;\n                    if (default_label_pos >= 0) {\n                        js_parse_error(s, \"duplicate default\");\n                        goto fail;\n                    }\n                    if (label_case < 0) {\n                        /* falling thru direct from switch expression */\n                        label_case = emit_goto(s, OP_goto, -1);\n                    }\n                    /* Emit a dummy label opcode. Label will be patched after\n                       the end of the switch body. Do not use emit_label(s, 0)\n                       because it would clobber label 0 address, preventing\n                       proper optimizer operation.\n                     */\n                    emit_op(s, OP_label);\n                    emit_u32(s, 0);\n                    default_label_pos = s->cur_func->byte_code.size - 4;\n                } else {\n                    if (label_case < 0) {\n                        /* falling thru direct from switch expression */\n                        js_parse_error(s, \"invalid switch statement\");\n                        goto fail;\n                    }\n                    if (js_parse_statement_or_decl(s, DECL_MASK_ALL))\n                        goto fail;\n                }\n            }\n            if (js_parse_expect(s, '}'))\n                goto fail;\n            if (default_label_pos >= 0) {\n                /* Ugly patch for the the `default` label, shameful and risky */\n                put_u32(s->cur_func->byte_code.buf + default_label_pos,\n                        label_case);\n                s->cur_func->label_slots[label_case].pos = default_label_pos + 4;\n            } else {\n                emit_label(s, label_case);\n            }\n            emit_label(s, label_break);\n            emit_op(s, OP_drop); /* drop the switch expression */\n\n            pop_break_entry(s->cur_func);\n            pop_scope(s);\n        }\n        break;\n    case TOK_TRY:\n        {\n            int label_catch, label_catch2, label_finally, label_end;\n            JSAtom name;\n            BlockEnv block_env;\n\n            set_eval_ret_undefined(s);\n            if (next_token(s))\n                goto fail;\n            label_catch = new_label(s);\n            label_catch2 = new_label(s);\n            label_finally = new_label(s);\n            label_end = new_label(s);\n\n            emit_goto(s, OP_catch, label_catch);\n\n            push_break_entry(s->cur_func, &block_env,\n                             JS_ATOM_NULL, -1, -1, 1);\n            block_env.label_finally = label_finally;\n\n            if (js_parse_block(s))\n                goto fail;\n\n            pop_break_entry(s->cur_func);\n\n            if (js_is_live_code(s)) {\n                /* drop the catch offset */\n                emit_op(s, OP_drop);\n                /* must push dummy value to keep same stack size */\n                emit_op(s, OP_undefined);\n                emit_goto(s, OP_gosub, label_finally);\n                emit_op(s, OP_drop);\n\n                emit_goto(s, OP_goto, label_end);\n            }\n\n            if (s->token.val == TOK_CATCH) {\n                if (next_token(s))\n                    goto fail;\n\n                push_scope(s);  /* catch variable */\n                emit_label(s, label_catch);\n\n                if (s->token.val == '{') {\n                    /* support optional-catch-binding feature */\n                    emit_op(s, OP_drop);    /* pop the exception object */\n                } else {\n                    if (js_parse_expect(s, '('))\n                        goto fail;\n                    if (!(s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved)) {\n                        if (s->token.val == '[' || s->token.val == '{') {\n                            /* XXX: TOK_LET is not completely correct */\n                            if (js_parse_destructuring_element(s, TOK_LET, 0, TRUE, -1, TRUE) < 0)\n                                goto fail;\n                        } else {\n                            js_parse_error(s, \"identifier expected\");\n                            goto fail;\n                        }\n                    } else {\n                        name = JS_DupAtom(ctx, s->token.u.ident.atom);\n                        if (next_token(s)\n                        ||  js_define_var(s, name, TOK_CATCH) < 0) {\n                            JS_FreeAtom(ctx, name);\n                            goto fail;\n                        }\n                        /* store the exception value in the catch variable */\n                        emit_op(s, OP_scope_put_var);\n                        emit_u32(s, name);\n                        emit_u16(s, s->cur_func->scope_level);\n                    }\n                    if (js_parse_expect(s, ')'))\n                        goto fail;\n                }\n                /* XXX: should keep the address to nop it out if there is no finally block */\n                emit_goto(s, OP_catch, label_catch2);\n\n                push_scope(s);  /* catch block */\n                push_break_entry(s->cur_func, &block_env, JS_ATOM_NULL,\n                                 -1, -1, 1);\n                block_env.label_finally = label_finally;\n\n                if (js_parse_block(s))\n                    goto fail;\n\n                pop_break_entry(s->cur_func);\n                pop_scope(s);  /* catch block */\n                pop_scope(s);  /* catch variable */\n\n                if (js_is_live_code(s)) {\n                    /* drop the catch2 offset */\n                    emit_op(s, OP_drop);\n                    /* XXX: should keep the address to nop it out if there is no finally block */\n                    /* must push dummy value to keep same stack size */\n                    emit_op(s, OP_undefined);\n                    emit_goto(s, OP_gosub, label_finally);\n                    emit_op(s, OP_drop);\n                    emit_goto(s, OP_goto, label_end);\n                }\n                /* catch exceptions thrown in the catch block to execute the\n                 * finally clause and rethrow the exception */\n                emit_label(s, label_catch2);\n                /* catch value is at TOS, no need to push undefined */\n                emit_goto(s, OP_gosub, label_finally);\n                emit_op(s, OP_throw);\n\n            } else if (s->token.val == TOK_FINALLY) {\n                /* finally without catch : execute the finally clause\n                 * and rethrow the exception */\n                emit_label(s, label_catch);\n                /* catch value is at TOS, no need to push undefined */\n                emit_goto(s, OP_gosub, label_finally);\n                emit_op(s, OP_throw);\n            } else {\n                js_parse_error(s, \"expecting catch or finally\");\n                goto fail;\n            }\n            emit_label(s, label_finally);\n            if (s->token.val == TOK_FINALLY) {\n                int saved_eval_ret_idx = 0; /* avoid warning */\n                \n                if (next_token(s))\n                    goto fail;\n                /* on the stack: ret_value gosub_ret_value */\n                push_break_entry(s->cur_func, &block_env, JS_ATOM_NULL,\n                                 -1, -1, 2);\n\n                if (s->cur_func->eval_ret_idx >= 0) {\n                    /* 'finally' updates eval_ret only if not a normal\n                       termination */\n                    saved_eval_ret_idx =\n                        add_var(s->ctx, s->cur_func, JS_ATOM__ret_);\n                    if (saved_eval_ret_idx < 0)\n                        goto fail;\n                    emit_op(s, OP_get_loc);\n                    emit_u16(s, s->cur_func->eval_ret_idx);\n                    emit_op(s, OP_put_loc);\n                    emit_u16(s, saved_eval_ret_idx);\n                    set_eval_ret_undefined(s);\n                }\n                \n                if (js_parse_block(s))\n                    goto fail;\n\n                if (s->cur_func->eval_ret_idx >= 0) {\n                    emit_op(s, OP_get_loc);\n                    emit_u16(s, saved_eval_ret_idx);\n                    emit_op(s, OP_put_loc);\n                    emit_u16(s, s->cur_func->eval_ret_idx);\n                }\n                pop_break_entry(s->cur_func);\n            }\n            emit_op(s, OP_ret);\n            emit_label(s, label_end);\n        }\n        break;\n    case ';':\n        /* empty statement */\n        if (next_token(s))\n            goto fail;\n        break;\n    case TOK_WITH:\n        if (s->cur_func->js_mode & JS_MODE_STRICT) {\n            js_parse_error(s, \"invalid keyword: with\");\n            goto fail;\n        } else {\n            int with_idx;\n\n            if (next_token(s))\n                goto fail;\n\n            if (js_parse_expr_paren(s))\n                goto fail;\n\n            push_scope(s);\n            with_idx = define_var(s, s->cur_func, JS_ATOM__with_,\n                                  JS_VAR_DEF_WITH);\n            if (with_idx < 0)\n                goto fail;\n            emit_op(s, OP_to_object);\n            emit_op(s, OP_put_loc);\n            emit_u16(s, with_idx);\n\n            set_eval_ret_undefined(s);\n            if (js_parse_statement(s))\n                goto fail;\n\n            /* Popping scope drops lexical context for the with object variable */\n            pop_scope(s);\n        }\n        break;\n    case TOK_FUNCTION:\n        /* ES6 Annex B.3.2 and B.3.3 semantics */\n        if (!(decl_mask & DECL_MASK_FUNC))\n            goto func_decl_error;\n        if (!(decl_mask & DECL_MASK_OTHER) && peek_token(s, FALSE) == '*')\n            goto func_decl_error;\n        goto parse_func_var;\n    case TOK_IDENT:\n        if (s->token.u.ident.is_reserved) {\n            js_parse_error_reserved_identifier(s);\n            goto fail;\n        }\n        /* Determine if `let` introduces a Declaration or an ExpressionStatement */\n        switch (is_let(s, decl_mask)) {\n        case TRUE:\n            tok = TOK_LET;\n            goto haslet;\n        case FALSE:\n            break;\n        default:\n            goto fail;\n        }\n        if (token_is_pseudo_keyword(s, JS_ATOM_async) &&\n            peek_token(s, TRUE) == TOK_FUNCTION) {\n            if (!(decl_mask & DECL_MASK_OTHER)) {\n            func_decl_error:\n                js_parse_error(s, \"function declarations can't appear in single-statement context\");\n                goto fail;\n            }\n        parse_func_var:\n            if (js_parse_function_decl(s, JS_PARSE_FUNC_VAR,\n                                       JS_FUNC_NORMAL, JS_ATOM_NULL,\n                                       s->token.ptr, s->token.line_num))\n                goto fail;\n            break;\n        }\n        goto hasexpr;\n\n    case TOK_CLASS:\n        if (!(decl_mask & DECL_MASK_OTHER)) {\n            js_parse_error(s, \"class declarations can't appear in single-statement context\");\n            goto fail;\n        }\n        if (js_parse_class(s, FALSE, JS_PARSE_EXPORT_NONE))\n            return -1;\n        break;\n\n    case TOK_DEBUGGER:\n        /* currently no debugger, so just skip the keyword */\n        if (next_token(s))\n            goto fail;\n        if (js_parse_expect_semi(s))\n            goto fail;\n        break;\n        \n    case TOK_ENUM:\n    case TOK_EXPORT:\n    case TOK_EXTENDS:\n        js_unsupported_keyword(s, s->token.u.ident.atom);\n        goto fail;\n\n    default:\n    hasexpr:\n        if (js_parse_expr(s))\n            goto fail;\n        if (s->cur_func->eval_ret_idx >= 0) {\n            /* store the expression value so that it can be returned\n               by eval() */\n            emit_op(s, OP_put_loc);\n            emit_u16(s, s->cur_func->eval_ret_idx);\n        } else {\n            emit_op(s, OP_drop); /* drop the result */\n        }\n        if (js_parse_expect_semi(s))\n            goto fail;\n        break;\n    }\ndone:\n    JS_FreeAtom(ctx, label_name);\n    return 0;\nfail:\n    JS_FreeAtom(ctx, label_name);\n    return -1;\n}\n\n/* 'name' is freed */\nstatic JSModuleDef *js_new_module_def(JSContext *ctx, JSAtom name)\n{\n    JSModuleDef *m;\n    m = js_mallocz(ctx, sizeof(*m));\n    if (!m) {\n        JS_FreeAtom(ctx, name);\n        return NULL;\n    }\n    m->header.ref_count = 1;\n    m->module_name = name;\n    m->module_ns = JS_UNDEFINED;\n    m->func_obj = JS_UNDEFINED;\n    m->eval_exception = JS_UNDEFINED;\n    m->meta_obj = JS_UNDEFINED;\n    list_add_tail(&m->link, &ctx->loaded_modules);\n    return m;\n}\n\nstatic void js_mark_module_def(JSRuntime *rt, JSModuleDef *m,\n                               JS_MarkFunc *mark_func)\n{\n    int i;\n\n    for(i = 0; i < m->export_entries_count; i++) {\n        JSExportEntry *me = &m->export_entries[i];\n        if (me->export_type == JS_EXPORT_TYPE_LOCAL &&\n            me->u.local.var_ref) {\n            mark_func(rt, &me->u.local.var_ref->header);\n        }\n    }\n\n    JS_MarkValue(rt, m->module_ns, mark_func);\n    JS_MarkValue(rt, m->func_obj, mark_func);\n    JS_MarkValue(rt, m->eval_exception, mark_func);\n    JS_MarkValue(rt, m->meta_obj, mark_func);\n}\n\nstatic void js_free_module_def(JSContext *ctx, JSModuleDef *m)\n{\n    int i;\n\n    JS_FreeAtom(ctx, m->module_name);\n\n    for(i = 0; i < m->req_module_entries_count; i++) {\n        JSReqModuleEntry *rme = &m->req_module_entries[i];\n        JS_FreeAtom(ctx, rme->module_name);\n    }\n    js_free(ctx, m->req_module_entries);\n\n    for(i = 0; i < m->export_entries_count; i++) {\n        JSExportEntry *me = &m->export_entries[i];\n        if (me->export_type == JS_EXPORT_TYPE_LOCAL)\n            free_var_ref(ctx->rt, me->u.local.var_ref);\n        JS_FreeAtom(ctx, me->export_name);\n        JS_FreeAtom(ctx, me->local_name);\n    }\n    js_free(ctx, m->export_entries);\n\n    js_free(ctx, m->star_export_entries);\n\n    for(i = 0; i < m->import_entries_count; i++) {\n        JSImportEntry *mi = &m->import_entries[i];\n        JS_FreeAtom(ctx, mi->import_name);\n    }\n    js_free(ctx, m->import_entries);\n\n    JS_FreeValue(ctx, m->module_ns);\n    JS_FreeValue(ctx, m->func_obj);\n    JS_FreeValue(ctx, m->eval_exception);\n    JS_FreeValue(ctx, m->meta_obj);\n    list_del(&m->link);\n    js_free(ctx, m);\n}\n\nstatic int add_req_module_entry(JSContext *ctx, JSModuleDef *m,\n                                JSAtom module_name)\n{\n    JSReqModuleEntry *rme;\n    int i;\n\n    /* no need to add the module request if it is already present */\n    for(i = 0; i < m->req_module_entries_count; i++) {\n        rme = &m->req_module_entries[i];\n        if (rme->module_name == module_name)\n            return i;\n    }\n\n    if (js_resize_array(ctx, (void **)&m->req_module_entries,\n                        sizeof(JSReqModuleEntry),\n                        &m->req_module_entries_size,\n                        m->req_module_entries_count + 1))\n        return -1;\n    rme = &m->req_module_entries[m->req_module_entries_count++];\n    rme->module_name = JS_DupAtom(ctx, module_name);\n    rme->module = NULL;\n    return i;\n}\n\nstatic JSExportEntry *find_export_entry(JSContext *ctx, JSModuleDef *m,\n                                        JSAtom export_name)\n{\n    JSExportEntry *me;\n    int i;\n    for(i = 0; i < m->export_entries_count; i++) {\n        me = &m->export_entries[i];\n        if (me->export_name == export_name)\n            return me;\n    }\n    return NULL;\n}\n\nstatic JSExportEntry *add_export_entry2(JSContext *ctx,\n                                        JSParseState *s, JSModuleDef *m,\n                                       JSAtom local_name, JSAtom export_name,\n                                       JSExportTypeEnum export_type)\n{\n    JSExportEntry *me;\n\n    if (find_export_entry(ctx, m, export_name)) {\n        char buf1[ATOM_GET_STR_BUF_SIZE];\n        if (s) {\n            js_parse_error(s, \"duplicate exported name '%s'\",\n                           JS_AtomGetStr(ctx, buf1, sizeof(buf1), export_name));\n        } else {\n            JS_ThrowSyntaxErrorAtom(ctx, \"duplicate exported name '%s'\", export_name);\n        }\n        return NULL;\n    }\n\n    if (js_resize_array(ctx, (void **)&m->export_entries,\n                        sizeof(JSExportEntry),\n                        &m->export_entries_size,\n                        m->export_entries_count + 1))\n        return NULL;\n    me = &m->export_entries[m->export_entries_count++];\n    memset(me, 0, sizeof(*me));\n    me->local_name = JS_DupAtom(ctx, local_name);\n    me->export_name = JS_DupAtom(ctx, export_name);\n    me->export_type = export_type;\n    return me;\n}\n\nstatic JSExportEntry *add_export_entry(JSParseState *s, JSModuleDef *m,\n                                       JSAtom local_name, JSAtom export_name,\n                                       JSExportTypeEnum export_type)\n{\n    return add_export_entry2(s->ctx, s, m, local_name, export_name,\n                             export_type);\n}\n\nstatic int add_star_export_entry(JSContext *ctx, JSModuleDef *m,\n                                 int req_module_idx)\n{\n    JSStarExportEntry *se;\n\n    if (js_resize_array(ctx, (void **)&m->star_export_entries,\n                        sizeof(JSStarExportEntry),\n                        &m->star_export_entries_size,\n                        m->star_export_entries_count + 1))\n        return -1;\n    se = &m->star_export_entries[m->star_export_entries_count++];\n    se->req_module_idx = req_module_idx;\n    return 0;\n}\n\n/* create a C module */\nJSModuleDef *JS_NewCModule(JSContext *ctx, const char *name_str,\n                           JSModuleInitFunc *func)\n{\n    JSModuleDef *m;\n    JSAtom name;\n    name = JS_NewAtom(ctx, name_str);\n    if (name == JS_ATOM_NULL)\n        return NULL;\n    m = js_new_module_def(ctx, name);\n    m->init_func = func;\n    return m;\n}\n\nint JS_AddModuleExport(JSContext *ctx, JSModuleDef *m, const char *export_name)\n{\n    JSExportEntry *me;\n    JSAtom name;\n    name = JS_NewAtom(ctx, export_name);\n    if (name == JS_ATOM_NULL)\n        return -1;\n    me = add_export_entry2(ctx, NULL, m, JS_ATOM_NULL, name,\n                           JS_EXPORT_TYPE_LOCAL);\n    JS_FreeAtom(ctx, name);\n    if (!me)\n        return -1;\n    else\n        return 0;\n}\n\nint JS_SetModuleExport(JSContext *ctx, JSModuleDef *m, const char *export_name,\n                       JSValue val)\n{\n    JSExportEntry *me;\n    JSAtom name;\n    name = JS_NewAtom(ctx, export_name);\n    if (name == JS_ATOM_NULL)\n        goto fail;\n    me = find_export_entry(ctx, m, name);\n    JS_FreeAtom(ctx, name);\n    if (!me)\n        goto fail;\n    set_value(ctx, me->u.local.var_ref->pvalue, val);\n    return 0;\n fail:\n    JS_FreeValue(ctx, val);\n    return -1;\n}\n\nvoid JS_SetModuleLoaderFunc(JSRuntime *rt,\n                            JSModuleNormalizeFunc *module_normalize,\n                            JSModuleLoaderFunc *module_loader, void *opaque)\n{\n    rt->module_normalize_func = module_normalize;\n    rt->module_loader_func = module_loader;\n    rt->module_loader_opaque = opaque;\n}\n\n/* default module filename normalizer */\nstatic char *js_default_module_normalize_name(JSContext *ctx,\n                                              const char *base_name,\n                                              const char *name)\n{\n    char *filename, *p;\n    const char *r;\n    int len;\n\n    if (name[0] != '.') {\n        /* if no initial dot, the module name is not modified */\n        return js_strdup(ctx, name);\n    }\n\n    p = strrchr(base_name, '/');\n    if (p)\n        len = p - base_name;\n    else\n        len = 0;\n\n    filename = js_malloc(ctx, len + strlen(name) + 1 + 1);\n    if (!filename)\n        return NULL;\n    memcpy(filename, base_name, len);\n    filename[len] = '\\0';\n\n    /* we only normalize the leading '..' or '.' */\n    r = name;\n    for(;;) {\n        if (r[0] == '.' && r[1] == '/') {\n            r += 2;\n        } else if (r[0] == '.' && r[1] == '.' && r[2] == '/') {\n            /* remove the last path element of filename, except if \".\"\n               or \"..\" */\n            if (filename[0] == '\\0')\n                break;\n            p = strrchr(filename, '/');\n            if (!p)\n                p = filename;\n            else\n                p++;\n            if (!strcmp(p, \".\") || !strcmp(p, \"..\"))\n                break;\n            if (p > filename)\n                p--;\n            *p = '\\0';\n            r += 3;\n        } else {\n            break;\n        }\n    }\n    if (filename[0] != '\\0')\n        strcat(filename, \"/\");\n    strcat(filename, r);\n    //    printf(\"normalize: %s %s -> %s\\n\", base_name, name, filename);\n    return filename;\n}\n\nstatic JSModuleDef *js_find_loaded_module(JSContext *ctx, JSAtom name)\n{\n    struct list_head *el;\n    JSModuleDef *m;\n    \n    /* first look at the loaded modules */\n    list_for_each(el, &ctx->loaded_modules) {\n        m = list_entry(el, JSModuleDef, link);\n        if (m->module_name == name)\n            return m;\n    }\n    return NULL;\n}\n\n/* return NULL in case of exception (e.g. module could not be loaded) */\nstatic JSModuleDef *js_host_resolve_imported_module(JSContext *ctx,\n                                                    const char *base_cname,\n                                                    const char *cname1)\n{\n    JSRuntime *rt = ctx->rt;\n    JSModuleDef *m;\n    char *cname;\n    JSAtom module_name;\n\n    if (!rt->module_normalize_func) {\n        cname = js_default_module_normalize_name(ctx, base_cname, cname1);\n    } else {\n        cname = rt->module_normalize_func(ctx, base_cname, cname1,\n                                          rt->module_loader_opaque);\n    }\n    if (!cname)\n        return NULL;\n\n    module_name = JS_NewAtom(ctx, cname);\n    if (module_name == JS_ATOM_NULL) {\n        js_free(ctx, cname);\n        return NULL;\n    }\n\n    /* first look at the loaded modules */\n    m = js_find_loaded_module(ctx, module_name);\n    if (m) {\n        js_free(ctx, cname);\n        JS_FreeAtom(ctx, module_name);\n        return m;\n    }\n\n    JS_FreeAtom(ctx, module_name);\n\n    /* load the module */\n    if (!rt->module_loader_func) {\n        /* XXX: use a syntax error ? */\n        JS_ThrowReferenceError(ctx, \"could not load module '%s'\",\n                               cname);\n        js_free(ctx, cname);\n        return NULL;\n    }\n\n    m = rt->module_loader_func(ctx, cname, rt->module_loader_opaque);\n    js_free(ctx, cname);\n    return m;\n}\n\nstatic JSModuleDef *js_host_resolve_imported_module_atom(JSContext *ctx,\n                                                    JSAtom base_module_name,\n                                                    JSAtom module_name1)\n{\n    const char *base_cname, *cname;\n    JSModuleDef *m;\n    \n    base_cname = JS_AtomToCString(ctx, base_module_name);\n    if (!base_cname)\n        return NULL;\n    cname = JS_AtomToCString(ctx, module_name1);\n    if (!cname) {\n        JS_FreeCString(ctx, base_cname);\n        return NULL;\n    }\n    m = js_host_resolve_imported_module(ctx, base_cname, cname);\n    JS_FreeCString(ctx, base_cname);\n    JS_FreeCString(ctx, cname);\n    return m;\n}\n\ntypedef struct JSResolveEntry {\n    JSModuleDef *module;\n    JSAtom name;\n} JSResolveEntry;\n\ntypedef struct JSResolveState {\n    JSResolveEntry *array;\n    int size;\n    int count;\n} JSResolveState;\n\nstatic int find_resolve_entry(JSResolveState *s,\n                              JSModuleDef *m, JSAtom name)\n{\n    int i;\n    for(i = 0; i < s->count; i++) {\n        JSResolveEntry *re = &s->array[i];\n        if (re->module == m && re->name == name)\n            return i;\n    }\n    return -1;\n}\n\nstatic int add_resolve_entry(JSContext *ctx, JSResolveState *s,\n                             JSModuleDef *m, JSAtom name)\n{\n    JSResolveEntry *re;\n\n    if (js_resize_array(ctx, (void **)&s->array,\n                        sizeof(JSResolveEntry),\n                        &s->size, s->count + 1))\n        return -1;\n    re = &s->array[s->count++];\n    re->module = m;\n    re->name = JS_DupAtom(ctx, name);\n    return 0;\n}\n\ntypedef enum JSResolveResultEnum {\n    JS_RESOLVE_RES_EXCEPTION = -1, /* memory alloc error */\n    JS_RESOLVE_RES_FOUND = 0,\n    JS_RESOLVE_RES_NOT_FOUND,\n    JS_RESOLVE_RES_CIRCULAR,\n    JS_RESOLVE_RES_AMBIGUOUS,\n} JSResolveResultEnum;\n\nstatic JSResolveResultEnum js_resolve_export1(JSContext *ctx,\n                                              JSModuleDef **pmodule,\n                                              JSExportEntry **pme,\n                                              JSModuleDef *m,\n                                              JSAtom export_name,\n                                              JSResolveState *s)\n{\n    JSExportEntry *me;\n\n    *pmodule = NULL;\n    *pme = NULL;\n    if (find_resolve_entry(s, m, export_name) >= 0)\n        return JS_RESOLVE_RES_CIRCULAR;\n    if (add_resolve_entry(ctx, s, m, export_name) < 0)\n        return JS_RESOLVE_RES_EXCEPTION;\n    me = find_export_entry(ctx, m, export_name);\n    if (me) {\n        if (me->export_type == JS_EXPORT_TYPE_LOCAL) {\n            /* local export */\n            *pmodule = m;\n            *pme = me;\n            return JS_RESOLVE_RES_FOUND;\n        } else {\n            /* indirect export */\n            JSModuleDef *m1;\n            m1 = m->req_module_entries[me->u.req_module_idx].module;\n            if (me->local_name == JS_ATOM__star_) {\n                /* export ns from */\n                *pmodule = m;\n                *pme = me;\n                return JS_RESOLVE_RES_FOUND;\n            } else {\n                return js_resolve_export1(ctx, pmodule, pme, m1,\n                                          me->local_name, s);\n            }\n        }\n    } else {\n        if (export_name != JS_ATOM_default) {\n            /* not found in direct or indirect exports: try star exports */\n            int i;\n\n            for(i = 0; i < m->star_export_entries_count; i++) {\n                JSStarExportEntry *se = &m->star_export_entries[i];\n                JSModuleDef *m1, *res_m;\n                JSExportEntry *res_me;\n                JSResolveResultEnum ret;\n\n                m1 = m->req_module_entries[se->req_module_idx].module;\n                ret = js_resolve_export1(ctx, &res_m, &res_me, m1,\n                                         export_name, s);\n                if (ret == JS_RESOLVE_RES_AMBIGUOUS ||\n                    ret == JS_RESOLVE_RES_EXCEPTION) {\n                    return ret;\n                } else if (ret == JS_RESOLVE_RES_FOUND) {\n                    if (*pme != NULL) {\n                        if (*pmodule != res_m ||\n                            res_me->local_name != (*pme)->local_name) {\n                            *pmodule = NULL;\n                            *pme = NULL;\n                            return JS_RESOLVE_RES_AMBIGUOUS;\n                        }\n                    } else {\n                        *pmodule = res_m;\n                        *pme = res_me;\n                    }\n                }\n            }\n            if (*pme != NULL)\n                return JS_RESOLVE_RES_FOUND;\n        }\n        return JS_RESOLVE_RES_NOT_FOUND;\n    }\n}\n\n/* If the return value is JS_RESOLVE_RES_FOUND, return the module\n  (*pmodule) and the corresponding local export entry\n  (*pme). Otherwise return (NULL, NULL) */\nstatic JSResolveResultEnum js_resolve_export(JSContext *ctx,\n                                             JSModuleDef **pmodule,\n                                             JSExportEntry **pme,\n                                             JSModuleDef *m,\n                                             JSAtom export_name)\n{\n    JSResolveState ss, *s = &ss;\n    int i;\n    JSResolveResultEnum ret;\n\n    s->array = NULL;\n    s->size = 0;\n    s->count = 0;\n\n    ret = js_resolve_export1(ctx, pmodule, pme, m, export_name, s);\n\n    for(i = 0; i < s->count; i++)\n        JS_FreeAtom(ctx, s->array[i].name);\n    js_free(ctx, s->array);\n\n    return ret;\n}\n\nstatic void js_resolve_export_throw_error(JSContext *ctx,\n                                          JSResolveResultEnum res,\n                                          JSModuleDef *m, JSAtom export_name)\n{\n    char buf1[ATOM_GET_STR_BUF_SIZE];\n    char buf2[ATOM_GET_STR_BUF_SIZE];\n    switch(res) {\n    case JS_RESOLVE_RES_EXCEPTION:\n        break;\n    default:\n    case JS_RESOLVE_RES_NOT_FOUND:\n        JS_ThrowSyntaxError(ctx, \"Could not find export '%s' in module '%s'\",\n                            JS_AtomGetStr(ctx, buf1, sizeof(buf1), export_name),\n                            JS_AtomGetStr(ctx, buf2, sizeof(buf2), m->module_name));\n        break;\n    case JS_RESOLVE_RES_CIRCULAR:\n        JS_ThrowSyntaxError(ctx, \"circular reference when looking for export '%s' in module '%s'\",\n                            JS_AtomGetStr(ctx, buf1, sizeof(buf1), export_name),\n                            JS_AtomGetStr(ctx, buf2, sizeof(buf2), m->module_name));\n        break;\n    case JS_RESOLVE_RES_AMBIGUOUS:\n        JS_ThrowSyntaxError(ctx, \"export '%s' in module '%s' is ambiguous\",\n                            JS_AtomGetStr(ctx, buf1, sizeof(buf1), export_name),\n                            JS_AtomGetStr(ctx, buf2, sizeof(buf2), m->module_name));\n        break;\n    }\n}\n\n\ntypedef enum {\n    EXPORTED_NAME_AMBIGUOUS,\n    EXPORTED_NAME_NORMAL,\n    EXPORTED_NAME_NS,\n} ExportedNameEntryEnum;\n\ntypedef struct ExportedNameEntry {\n    JSAtom export_name;\n    ExportedNameEntryEnum export_type;\n    union {\n        JSExportEntry *me; /* using when the list is built */\n        JSVarRef *var_ref; /* EXPORTED_NAME_NORMAL */\n        JSModuleDef *module; /* for EXPORTED_NAME_NS */\n    } u;\n} ExportedNameEntry;\n\ntypedef struct GetExportNamesState {\n    JSModuleDef **modules;\n    int modules_size;\n    int modules_count;\n\n    ExportedNameEntry *exported_names;\n    int exported_names_size;\n    int exported_names_count;\n} GetExportNamesState;\n\nstatic int find_exported_name(GetExportNamesState *s, JSAtom name)\n{\n    int i;\n    for(i = 0; i < s->exported_names_count; i++) {\n        if (s->exported_names[i].export_name == name)\n            return i;\n    }\n    return -1;\n}\n\nstatic __exception int get_exported_names(JSContext *ctx,\n                                          GetExportNamesState *s,\n                                          JSModuleDef *m, BOOL from_star)\n{\n    ExportedNameEntry *en;\n    int i, j;\n\n    /* check circular reference */\n    for(i = 0; i < s->modules_count; i++) {\n        if (s->modules[i] == m)\n            return 0;\n    }\n    if (js_resize_array(ctx, (void **)&s->modules, sizeof(s->modules[0]),\n                        &s->modules_size, s->modules_count + 1))\n        return -1;\n    s->modules[s->modules_count++] = m;\n\n    for(i = 0; i < m->export_entries_count; i++) {\n        JSExportEntry *me = &m->export_entries[i];\n        if (from_star && me->export_name == JS_ATOM_default)\n            continue;\n        j = find_exported_name(s, me->export_name);\n        if (j < 0) {\n            if (js_resize_array(ctx, (void **)&s->exported_names, sizeof(s->exported_names[0]),\n                                &s->exported_names_size,\n                                s->exported_names_count + 1))\n                return -1;\n            en = &s->exported_names[s->exported_names_count++];\n            en->export_name = me->export_name;\n            /* avoid a second lookup for simple module exports */\n            if (from_star || me->export_type != JS_EXPORT_TYPE_LOCAL)\n                en->u.me = NULL;\n            else\n                en->u.me = me;\n        } else {\n            en = &s->exported_names[j];\n            en->u.me = NULL;\n        }\n    }\n    for(i = 0; i < m->star_export_entries_count; i++) {\n        JSStarExportEntry *se = &m->star_export_entries[i];\n        JSModuleDef *m1;\n        m1 = m->req_module_entries[se->req_module_idx].module;\n        if (get_exported_names(ctx, s, m1, TRUE))\n            return -1;\n    }\n    return 0;\n}\n\n/* Unfortunately, the spec gives a different behavior from GetOwnProperty ! */\nstatic int js_module_ns_has(JSContext *ctx, JSValueConst obj, JSAtom atom)\n{\n    return (find_own_property1(JS_VALUE_GET_OBJ(obj), atom) != NULL);\n}\n\nstatic const JSClassExoticMethods js_module_ns_exotic_methods = {\n    .has_property = js_module_ns_has,\n};\n\nstatic int exported_names_cmp(const void *p1, const void *p2, void *opaque)\n{\n    JSContext *ctx = opaque;\n    const ExportedNameEntry *me1 = p1;\n    const ExportedNameEntry *me2 = p2;\n    JSValue str1, str2;\n    int ret;\n\n    /* XXX: should avoid allocation memory in atom comparison */\n    str1 = JS_AtomToString(ctx, me1->export_name);\n    str2 = JS_AtomToString(ctx, me2->export_name);\n    if (JS_IsException(str1) || JS_IsException(str2)) {\n        /* XXX: raise an error ? */\n        ret = 0;\n    } else {\n        ret = js_string_compare(ctx, JS_VALUE_GET_STRING(str1),\n                                JS_VALUE_GET_STRING(str2));\n    }\n    JS_FreeValue(ctx, str1);\n    JS_FreeValue(ctx, str2);\n    return ret;\n}\n\nstatic JSValue js_get_module_ns(JSContext *ctx, JSModuleDef *m);\n\nstatic JSValue js_module_ns_autoinit(JSContext *ctx, JSObject *p, JSAtom atom,\n                                     void *opaque)\n{\n    JSModuleDef *m = opaque;\n    return js_get_module_ns(ctx, m);\n}\n\nstatic JSValue js_build_module_ns(JSContext *ctx, JSModuleDef *m)\n{\n    JSValue obj;\n    JSObject *p;\n    GetExportNamesState s_s, *s = &s_s;\n    int i, ret;\n    JSProperty *pr;\n\n    obj = JS_NewObjectClass(ctx, JS_CLASS_MODULE_NS);\n    if (JS_IsException(obj))\n        return obj;\n    p = JS_VALUE_GET_OBJ(obj);\n\n    memset(s, 0, sizeof(*s));\n    ret = get_exported_names(ctx, s, m, FALSE);\n    js_free(ctx, s->modules);\n    if (ret)\n        goto fail;\n\n    /* Resolve the exported names. The ambiguous exports are removed */\n    for(i = 0; i < s->exported_names_count; i++) {\n        ExportedNameEntry *en = &s->exported_names[i];\n        JSResolveResultEnum res;\n        JSExportEntry *res_me;\n        JSModuleDef *res_m;\n\n        if (en->u.me) {\n            res_me = en->u.me; /* fast case: no resolution needed */\n            res_m = m;\n            res = JS_RESOLVE_RES_FOUND;\n        } else {\n            res = js_resolve_export(ctx, &res_m, &res_me, m,\n                                    en->export_name);\n        }\n        if (res != JS_RESOLVE_RES_FOUND) {\n            if (res != JS_RESOLVE_RES_AMBIGUOUS) {\n                js_resolve_export_throw_error(ctx, res, m, en->export_name);\n                goto fail;\n            }\n            en->export_type = EXPORTED_NAME_AMBIGUOUS;\n        } else {\n            if (res_me->local_name == JS_ATOM__star_) {\n                en->export_type = EXPORTED_NAME_NS;\n                en->u.module = res_m->req_module_entries[res_me->u.req_module_idx].module;\n            } else {\n                en->export_type = EXPORTED_NAME_NORMAL;\n                if (res_me->u.local.var_ref) {\n                    en->u.var_ref = res_me->u.local.var_ref;\n                } else {\n                    JSObject *p1 = JS_VALUE_GET_OBJ(res_m->func_obj);\n                    p1 = JS_VALUE_GET_OBJ(res_m->func_obj);\n                    en->u.var_ref = p1->u.func.var_refs[res_me->u.local.var_idx];\n                }\n            }\n        }\n    }\n\n    /* sort the exported names */\n    rqsort(s->exported_names, s->exported_names_count,\n           sizeof(s->exported_names[0]), exported_names_cmp, ctx);\n\n    for(i = 0; i < s->exported_names_count; i++) {\n        ExportedNameEntry *en = &s->exported_names[i];\n        switch(en->export_type) {\n        case EXPORTED_NAME_NORMAL:\n            {\n                JSVarRef *var_ref = en->u.var_ref;\n                pr = add_property(ctx, p, en->export_name,\n                                  JS_PROP_ENUMERABLE | JS_PROP_WRITABLE |\n                                  JS_PROP_VARREF);\n                if (!pr)\n                    goto fail;\n                var_ref->header.ref_count++;\n                pr->u.var_ref = var_ref;\n            }\n            break;\n        case EXPORTED_NAME_NS:\n            /* the exported namespace must be created on demand */\n            if (JS_DefineAutoInitProperty(ctx, obj,\n                                          en->export_name,\n                                          JS_AUTOINIT_ID_MODULE_NS,\n                                          en->u.module, JS_PROP_ENUMERABLE | JS_PROP_WRITABLE) < 0)\n                goto fail;\n            break;\n        default:\n            break;\n        }\n    }\n\n    js_free(ctx, s->exported_names);\n\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_Symbol_toStringTag,\n                           JS_AtomToString(ctx, JS_ATOM_Module),\n                           0);\n\n    p->extensible = FALSE;\n    return obj;\n fail:\n    js_free(ctx, s->exported_names);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_get_module_ns(JSContext *ctx, JSModuleDef *m)\n{\n    if (JS_IsUndefined(m->module_ns)) {\n        JSValue val;\n        val = js_build_module_ns(ctx, m);\n        if (JS_IsException(val))\n            return JS_EXCEPTION;\n        m->module_ns = val;\n    }\n    return JS_DupValue(ctx, m->module_ns);\n}\n\n/* Load all the required modules for module 'm' */\nstatic int js_resolve_module(JSContext *ctx, JSModuleDef *m)\n{\n    int i;\n    JSModuleDef *m1;\n\n    if (m->resolved)\n        return 0;\n#ifdef DUMP_MODULE_RESOLVE\n    {\n        char buf1[ATOM_GET_STR_BUF_SIZE];\n        printf(\"resolving module '%s':\\n\", JS_AtomGetStr(ctx, buf1, sizeof(buf1), m->module_name));\n    }\n#endif\n    m->resolved = TRUE;\n    /* resolve each requested module */\n    for(i = 0; i < m->req_module_entries_count; i++) {\n        JSReqModuleEntry *rme = &m->req_module_entries[i];\n        m1 = js_host_resolve_imported_module_atom(ctx, m->module_name,\n                                                  rme->module_name);\n        if (!m1)\n            return -1;\n        rme->module = m1;\n        /* already done in js_host_resolve_imported_module() except if\n           the module was loaded with JS_EvalBinary() */\n        if (js_resolve_module(ctx, m1) < 0)\n            return -1;\n    }\n    return 0;\n}\n\nstatic JSVarRef *js_create_module_var(JSContext *ctx, BOOL is_lexical)\n{\n    JSVarRef *var_ref;\n    var_ref = js_malloc(ctx, sizeof(JSVarRef));\n    if (!var_ref)\n        return NULL;\n    var_ref->header.ref_count = 1;\n    if (is_lexical)\n        var_ref->value = JS_UNINITIALIZED;\n    else\n        var_ref->value = JS_UNDEFINED;\n    var_ref->pvalue = &var_ref->value;\n    var_ref->is_detached = TRUE;\n    add_gc_object(ctx->rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF);\n    return var_ref;\n}\n\n/* Create the <eval> function associated with the module */\nstatic int js_create_module_bytecode_function(JSContext *ctx, JSModuleDef *m)\n{\n    JSFunctionBytecode *b;\n    int i;\n    JSVarRef **var_refs;\n    JSValue func_obj, bfunc;\n    JSObject *p;\n\n    bfunc = m->func_obj;\n    func_obj = JS_NewObjectProtoClass(ctx, ctx->function_proto,\n                                      JS_CLASS_BYTECODE_FUNCTION);\n\n    if (JS_IsException(func_obj))\n        return -1;\n    b = JS_VALUE_GET_PTR(bfunc);\n\n    p = JS_VALUE_GET_OBJ(func_obj);\n    p->u.func.function_bytecode = b;\n    b->header.ref_count++;\n    p->u.func.home_object = NULL;\n    p->u.func.var_refs = NULL;\n    if (b->closure_var_count) {\n        var_refs = js_mallocz(ctx, sizeof(var_refs[0]) * b->closure_var_count);\n        if (!var_refs)\n            goto fail;\n        p->u.func.var_refs = var_refs;\n\n        /* create the global variables. The other variables are\n           imported from other modules */\n        for(i = 0; i < b->closure_var_count; i++) {\n            JSClosureVar *cv = &b->closure_var[i];\n            JSVarRef *var_ref;\n            if (cv->is_local) {\n                var_ref = js_create_module_var(ctx, cv->is_lexical);\n                if (!var_ref)\n                    goto fail;\n#ifdef DUMP_MODULE_RESOLVE\n                printf(\"local %d: %p\\n\", i, var_ref);\n#endif\n                var_refs[i] = var_ref;\n            }\n        }\n    }\n    m->func_obj = func_obj;\n    JS_FreeValue(ctx, bfunc);\n    return 0;\n fail:\n    JS_FreeValue(ctx, func_obj);\n    return -1;\n}\n\n/* must be done before js_link_module() because of cyclic references */\nstatic int js_create_module_function(JSContext *ctx, JSModuleDef *m)\n{\n    BOOL is_c_module;\n    int i;\n    JSVarRef *var_ref;\n    \n    if (m->func_created)\n        return 0;\n\n    is_c_module = (m->init_func != NULL);\n\n    if (is_c_module) {\n        /* initialize the exported variables */\n        for(i = 0; i < m->export_entries_count; i++) {\n            JSExportEntry *me = &m->export_entries[i];\n            if (me->export_type == JS_EXPORT_TYPE_LOCAL) {\n                var_ref = js_create_module_var(ctx, FALSE);\n                if (!var_ref)\n                    return -1;\n                me->u.local.var_ref = var_ref;\n            }\n        }\n    } else {\n        if (js_create_module_bytecode_function(ctx, m))\n            return -1;\n    }\n    m->func_created = TRUE;\n\n    /* do it on the dependencies */\n    \n    for(i = 0; i < m->req_module_entries_count; i++) {\n        JSReqModuleEntry *rme = &m->req_module_entries[i];\n        if (js_create_module_function(ctx, rme->module) < 0)\n            return -1;\n    }\n\n    return 0;\n}    \n\n    \n/* Prepare a module to be executed by resolving all the imported\n   variables. */\nstatic int js_link_module(JSContext *ctx, JSModuleDef *m)\n{\n    int i;\n    JSImportEntry *mi;\n    JSModuleDef *m1;\n    JSVarRef **var_refs, *var_ref;\n    JSObject *p;\n    BOOL is_c_module;\n    JSValue ret_val;\n    \n    if (m->instantiated)\n        return 0;\n    m->instantiated = TRUE;\n\n#ifdef DUMP_MODULE_RESOLVE\n    {\n        char buf1[ATOM_GET_STR_BUF_SIZE];\n        printf(\"start instantiating module '%s':\\n\", JS_AtomGetStr(ctx, buf1, sizeof(buf1), m->module_name));\n    }\n#endif\n\n    for(i = 0; i < m->req_module_entries_count; i++) {\n        JSReqModuleEntry *rme = &m->req_module_entries[i];\n        if (js_link_module(ctx, rme->module) < 0)\n            goto fail;\n    }\n\n#ifdef DUMP_MODULE_RESOLVE\n    {\n        char buf1[ATOM_GET_STR_BUF_SIZE];\n        printf(\"instantiating module '%s':\\n\", JS_AtomGetStr(ctx, buf1, sizeof(buf1), m->module_name));\n    }\n#endif\n    /* check the indirect exports */\n    for(i = 0; i < m->export_entries_count; i++) {\n        JSExportEntry *me = &m->export_entries[i];\n        if (me->export_type == JS_EXPORT_TYPE_INDIRECT &&\n            me->local_name != JS_ATOM__star_) {\n            JSResolveResultEnum ret;\n            JSExportEntry *res_me;\n            JSModuleDef *res_m, *m1;\n            m1 = m->req_module_entries[me->u.req_module_idx].module;\n            ret = js_resolve_export(ctx, &res_m, &res_me, m1, me->local_name);\n            if (ret != JS_RESOLVE_RES_FOUND) {\n                js_resolve_export_throw_error(ctx, ret, m, me->export_name);\n                goto fail;\n            }\n        }\n    }\n\n#ifdef DUMP_MODULE_RESOLVE\n    {\n        printf(\"exported bindings:\\n\");\n        for(i = 0; i < m->export_entries_count; i++) {\n            JSExportEntry *me = &m->export_entries[i];\n            printf(\" name=\"); print_atom(ctx, me->export_name);\n            printf(\" local=\"); print_atom(ctx, me->local_name);\n            printf(\" type=%d idx=%d\\n\", me->export_type, me->u.local.var_idx);\n        }\n    }\n#endif\n\n    is_c_module = (m->init_func != NULL);\n\n    if (!is_c_module) {\n        p = JS_VALUE_GET_OBJ(m->func_obj);\n        var_refs = p->u.func.var_refs;\n\n        for(i = 0; i < m->import_entries_count; i++) {\n            mi = &m->import_entries[i];\n#ifdef DUMP_MODULE_RESOLVE\n            printf(\"import var_idx=%d name=\", mi->var_idx);\n            print_atom(ctx, mi->import_name);\n            printf(\": \");\n#endif\n            m1 = m->req_module_entries[mi->req_module_idx].module;\n            if (mi->import_name == JS_ATOM__star_) {\n                JSValue val;\n                /* name space import */\n                val = js_get_module_ns(ctx, m1);\n                if (JS_IsException(val))\n                    goto fail;\n                set_value(ctx, &var_refs[mi->var_idx]->value, val);\n#ifdef DUMP_MODULE_RESOLVE\n                printf(\"namespace\\n\");\n#endif\n            } else {\n                JSResolveResultEnum ret;\n                JSExportEntry *res_me;\n                JSModuleDef *res_m;\n                JSObject *p1;\n\n                ret = js_resolve_export(ctx, &res_m,\n                                        &res_me, m1, mi->import_name);\n                if (ret != JS_RESOLVE_RES_FOUND) {\n                    js_resolve_export_throw_error(ctx, ret, m1, mi->import_name);\n                    goto fail;\n                }\n                if (res_me->local_name == JS_ATOM__star_) {\n                    JSValue val;\n                    JSModuleDef *m2;\n                    /* name space import from */\n                    m2 = res_m->req_module_entries[res_me->u.req_module_idx].module;\n                    val = js_get_module_ns(ctx, m2);\n                    if (JS_IsException(val))\n                        goto fail;\n                    var_ref = js_create_module_var(ctx, TRUE);\n                    if (!var_ref) {\n                        JS_FreeValue(ctx, val);\n                        goto fail;\n                    }\n                    set_value(ctx, &var_ref->value, val);\n                    var_refs[mi->var_idx] = var_ref;\n#ifdef DUMP_MODULE_RESOLVE\n                    printf(\"namespace from\\n\");\n#endif\n                } else {\n                    var_ref = res_me->u.local.var_ref;\n                    if (!var_ref) {\n                        p1 = JS_VALUE_GET_OBJ(res_m->func_obj);\n                        var_ref = p1->u.func.var_refs[res_me->u.local.var_idx];\n                    }\n                    var_ref->header.ref_count++;\n                    var_refs[mi->var_idx] = var_ref;\n#ifdef DUMP_MODULE_RESOLVE\n                    printf(\"local export (var_ref=%p)\\n\", var_ref);\n#endif\n                }\n            }\n        }\n\n        /* keep the exported variables in the module export entries (they\n           are used when the eval function is deleted and cannot be\n           initialized before in case imports are exported) */\n        for(i = 0; i < m->export_entries_count; i++) {\n            JSExportEntry *me = &m->export_entries[i];\n            if (me->export_type == JS_EXPORT_TYPE_LOCAL) {\n                var_ref = var_refs[me->u.local.var_idx];\n                var_ref->header.ref_count++;\n                me->u.local.var_ref = var_ref;\n            }\n        }\n\n        /* initialize the global variables */\n        ret_val = JS_Call(ctx, m->func_obj, JS_TRUE, 0, NULL);\n        if (JS_IsException(ret_val))\n            goto fail;\n        JS_FreeValue(ctx, ret_val);\n    }\n\n#ifdef DUMP_MODULE_RESOLVE\n    printf(\"done instantiate\\n\");\n#endif\n    return 0;\n fail:\n    return -1;\n}\n\n/* return JS_ATOM_NULL if the name cannot be found. Only works with\n   not striped bytecode functions. */\nJSAtom JS_GetScriptOrModuleName(JSContext *ctx, int n_stack_levels)\n{\n    JSStackFrame *sf;\n    JSFunctionBytecode *b;\n    JSObject *p;\n    /* XXX: currently we just use the filename of the englobing\n       function. It does not work for eval(). Need to add a\n       ScriptOrModule info in JSFunctionBytecode */\n    sf = ctx->rt->current_stack_frame;\n    if (!sf)\n        return JS_ATOM_NULL;\n    while (n_stack_levels-- > 0) {\n        sf = sf->prev_frame;\n        if (!sf)\n            return JS_ATOM_NULL;\n    }\n    if (JS_VALUE_GET_TAG(sf->cur_func) != JS_TAG_OBJECT)\n        return JS_ATOM_NULL;\n    p = JS_VALUE_GET_OBJ(sf->cur_func);\n    if (!js_class_has_bytecode(p->class_id))\n        return JS_ATOM_NULL;\n    b = p->u.func.function_bytecode;\n    if (!b->has_debug)\n        return JS_ATOM_NULL;\n    return JS_DupAtom(ctx, b->debug.filename);\n}\n\nJSAtom JS_GetModuleName(JSContext *ctx, JSModuleDef *m)\n{\n    return JS_DupAtom(ctx, m->module_name);\n}\n\nJSValue JS_GetImportMeta(JSContext *ctx, JSModuleDef *m)\n{\n    JSValue obj;\n    /* allocate meta_obj only if requested to save memory */\n    obj = m->meta_obj;\n    if (JS_IsUndefined(obj)) {\n        obj = JS_NewObjectProto(ctx, JS_NULL);\n        if (JS_IsException(obj))\n            return JS_EXCEPTION;\n        m->meta_obj = obj;\n    }\n    return JS_DupValue(ctx, obj);\n}\n\nstatic JSValue js_import_meta(JSContext *ctx)\n{\n    JSAtom filename;\n    JSModuleDef *m;\n    \n    filename = JS_GetScriptOrModuleName(ctx, 0);\n    if (filename == JS_ATOM_NULL)\n        goto fail;\n\n    /* XXX: inefficient, need to add a module or script pointer in\n       JSFunctionBytecode */\n    m = js_find_loaded_module(ctx, filename);\n    JS_FreeAtom(ctx, filename);\n    if (!m) {\n    fail:\n        JS_ThrowTypeError(ctx, \"import.meta not supported in this context\");\n        return JS_EXCEPTION;\n    }\n    return JS_GetImportMeta(ctx, m);\n}\n\n/* used by os.Worker() and import() */\nJSModuleDef *JS_RunModule(JSContext *ctx, const char *basename,\n                          const char *filename)\n{\n    JSModuleDef *m;\n    JSValue ret, func_obj;\n    \n    m = js_host_resolve_imported_module(ctx, basename, filename);\n    if (!m)\n        return NULL;\n    \n    if (js_resolve_module(ctx, m) < 0) {\n        js_free_modules(ctx, JS_FREE_MODULE_NOT_RESOLVED);\n        return NULL;\n    }\n\n    /* Evaluate the module code */\n    func_obj = JS_DupValue(ctx, JS_MKPTR(JS_TAG_MODULE, m));\n    ret = JS_EvalFunction(ctx, func_obj);\n    if (JS_IsException(ret))\n        return NULL;\n    JS_FreeValue(ctx, ret);\n    return m;\n}\n\nstatic JSValue js_dynamic_import_job(JSContext *ctx,\n                                     int argc, JSValueConst *argv)\n{\n    JSValueConst *resolving_funcs = argv;\n    JSValueConst basename_val = argv[2];\n    JSValueConst specifier = argv[3];\n    JSModuleDef *m;\n    const char *basename = NULL, *filename;\n    JSValue ret, err, ns;\n\n    if (!JS_IsString(basename_val)) {\n        JS_ThrowTypeError(ctx, \"no function filename for import()\");\n        goto exception;\n    }\n    basename = JS_ToCString(ctx, basename_val);\n    if (!basename)\n        goto exception;\n\n    filename = JS_ToCString(ctx, specifier);\n    if (!filename)\n        goto exception;\n                     \n    m = JS_RunModule(ctx, basename, filename);\n    JS_FreeCString(ctx, filename);\n    if (!m)\n        goto exception;\n\n    /* return the module namespace */\n    ns = js_get_module_ns(ctx, m);\n    if (JS_IsException(ns))\n        goto exception;\n\n    ret = JS_Call(ctx, resolving_funcs[0], JS_UNDEFINED,\n                   1, (JSValueConst *)&ns);\n    JS_FreeValue(ctx, ret); /* XXX: what to do if exception ? */\n    JS_FreeValue(ctx, ns);\n    JS_FreeCString(ctx, basename);\n    return JS_UNDEFINED;\n exception:\n\n    err = JS_GetException(ctx);\n    ret = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED,\n                   1, (JSValueConst *)&err);\n    JS_FreeValue(ctx, ret); /* XXX: what to do if exception ? */\n    JS_FreeValue(ctx, err);\n    JS_FreeCString(ctx, basename);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_dynamic_import(JSContext *ctx, JSValueConst specifier)\n{\n    JSAtom basename;\n    JSValue promise, resolving_funcs[2], basename_val;\n    JSValueConst args[4];\n\n    basename = JS_GetScriptOrModuleName(ctx, 0);\n    if (basename == JS_ATOM_NULL)\n        basename_val = JS_NULL;\n    else\n        basename_val = JS_AtomToValue(ctx, basename);\n    JS_FreeAtom(ctx, basename);\n    if (JS_IsException(basename_val))\n        return basename_val;\n    \n    promise = JS_NewPromiseCapability(ctx, resolving_funcs);\n    if (JS_IsException(promise)) {\n        JS_FreeValue(ctx, basename_val);\n        return promise;\n    }\n\n    args[0] = resolving_funcs[0];\n    args[1] = resolving_funcs[1];\n    args[2] = basename_val;\n    args[3] = specifier;\n    \n    JS_EnqueueJob(ctx, js_dynamic_import_job, 4, args);\n\n    JS_FreeValue(ctx, basename_val);\n    JS_FreeValue(ctx, resolving_funcs[0]);\n    JS_FreeValue(ctx, resolving_funcs[1]);\n    return promise;\n}\n\n/* Run the <eval> function of the module and of all its requested\n   modules. */\nstatic JSValue js_evaluate_module(JSContext *ctx, JSModuleDef *m)\n{\n    JSModuleDef *m1;\n    int i;\n    JSValue ret_val;\n\n    if (m->eval_mark)\n        return JS_UNDEFINED; /* avoid cycles */\n\n    if (m->evaluated) {\n        /* if the module was already evaluated, rethrow the exception\n           it raised */\n        if (m->eval_has_exception) {\n            return JS_Throw(ctx, JS_DupValue(ctx, m->eval_exception));\n        } else {\n            return JS_UNDEFINED;\n        }\n    }\n\n    m->eval_mark = TRUE;\n\n    for(i = 0; i < m->req_module_entries_count; i++) {\n        JSReqModuleEntry *rme = &m->req_module_entries[i];\n        m1 = rme->module;\n        if (!m1->eval_mark) {\n            ret_val = js_evaluate_module(ctx, m1);\n            if (JS_IsException(ret_val)) {\n                m->eval_mark = FALSE;\n                return ret_val;\n            }\n            JS_FreeValue(ctx, ret_val);\n        }\n    }\n\n    if (m->init_func) {\n        /* C module init */\n        if (m->init_func(ctx, m) < 0)\n            ret_val = JS_EXCEPTION;\n        else\n            ret_val = JS_UNDEFINED;\n    } else {\n        ret_val = JS_CallFree(ctx, m->func_obj, JS_UNDEFINED, 0, NULL);\n        m->func_obj = JS_UNDEFINED;\n    }\n    if (JS_IsException(ret_val)) {\n        /* save the thrown exception value */\n        m->eval_has_exception = TRUE;\n        m->eval_exception = JS_DupValue(ctx, ctx->rt->current_exception);\n    }\n    m->eval_mark = FALSE;\n    m->evaluated = TRUE;\n    return ret_val;\n}\n\nstatic __exception JSAtom js_parse_from_clause(JSParseState *s)\n{\n    JSAtom module_name;\n    if (!token_is_pseudo_keyword(s, JS_ATOM_from)) {\n        js_parse_error(s, \"from clause expected\");\n        return JS_ATOM_NULL;\n    }\n    if (next_token(s))\n        return JS_ATOM_NULL;\n    if (s->token.val != TOK_STRING) {\n        js_parse_error(s, \"string expected\");\n        return JS_ATOM_NULL;\n    }\n    module_name = JS_ValueToAtom(s->ctx, s->token.u.str.str);\n    if (module_name == JS_ATOM_NULL)\n        return JS_ATOM_NULL;\n    if (next_token(s)) {\n        JS_FreeAtom(s->ctx, module_name);\n        return JS_ATOM_NULL;\n    }\n    return module_name;\n}\n\nstatic __exception int js_parse_export(JSParseState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSModuleDef *m = s->cur_func->module;\n    JSAtom local_name, export_name;\n    int first_export, idx, i, tok;\n    JSAtom module_name;\n    JSExportEntry *me;\n\n    if (next_token(s))\n        return -1;\n\n    tok = s->token.val;\n    if (tok == TOK_CLASS) {\n        return js_parse_class(s, FALSE, JS_PARSE_EXPORT_NAMED);\n    } else if (tok == TOK_FUNCTION ||\n               (token_is_pseudo_keyword(s, JS_ATOM_async) &&\n                peek_token(s, TRUE) == TOK_FUNCTION)) {\n        return js_parse_function_decl2(s, JS_PARSE_FUNC_STATEMENT,\n                                       JS_FUNC_NORMAL, JS_ATOM_NULL,\n                                       s->token.ptr, s->token.line_num,\n                                       JS_PARSE_EXPORT_NAMED, NULL);\n    }\n\n    if (next_token(s))\n        return -1;\n\n    switch(tok) {\n    case '{':\n        first_export = m->export_entries_count;\n        while (s->token.val != '}') {\n            if (!token_is_ident(s->token.val)) {\n                js_parse_error(s, \"identifier expected\");\n                return -1;\n            }\n            local_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n            export_name = JS_ATOM_NULL;\n            if (next_token(s))\n                goto fail;\n            if (token_is_pseudo_keyword(s, JS_ATOM_as)) {\n                if (next_token(s))\n                    goto fail;\n                if (!token_is_ident(s->token.val)) {\n                    js_parse_error(s, \"identifier expected\");\n                    goto fail;\n                }\n                export_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n                if (next_token(s)) {\n                fail:\n                    JS_FreeAtom(ctx, local_name);\n                fail1:\n                    JS_FreeAtom(ctx, export_name);\n                    return -1;\n                }\n            } else {\n                export_name = JS_DupAtom(ctx, local_name);\n            }\n            me = add_export_entry(s, m, local_name, export_name,\n                                  JS_EXPORT_TYPE_LOCAL);\n            JS_FreeAtom(ctx, local_name);\n            JS_FreeAtom(ctx, export_name);\n            if (!me)\n                return -1;\n            if (s->token.val != ',')\n                break;\n            if (next_token(s))\n                return -1;\n        }\n        if (js_parse_expect(s, '}'))\n            return -1;\n        if (token_is_pseudo_keyword(s, JS_ATOM_from)) {\n            module_name = js_parse_from_clause(s);\n            if (module_name == JS_ATOM_NULL)\n                return -1;\n            idx = add_req_module_entry(ctx, m, module_name);\n            JS_FreeAtom(ctx, module_name);\n            if (idx < 0)\n                return -1;\n            for(i = first_export; i < m->export_entries_count; i++) {\n                me = &m->export_entries[i];\n                me->export_type = JS_EXPORT_TYPE_INDIRECT;\n                me->u.req_module_idx = idx;\n            }\n        }\n        break;\n    case '*':\n        if (token_is_pseudo_keyword(s, JS_ATOM_as)) {\n            /* export ns from */\n            if (next_token(s))\n                return -1;\n            if (!token_is_ident(s->token.val)) {\n                js_parse_error(s, \"identifier expected\");\n                return -1;\n            }\n            export_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n            if (next_token(s))\n                goto fail1;\n            module_name = js_parse_from_clause(s);\n            if (module_name == JS_ATOM_NULL)\n                goto fail1;\n            idx = add_req_module_entry(ctx, m, module_name);\n            JS_FreeAtom(ctx, module_name);\n            if (idx < 0)\n                goto fail1;\n            me = add_export_entry(s, m, JS_ATOM__star_, export_name,\n                                  JS_EXPORT_TYPE_INDIRECT);\n            JS_FreeAtom(ctx, export_name);\n            if (!me)\n                return -1;\n            me->u.req_module_idx = idx;\n        } else {\n            module_name = js_parse_from_clause(s);\n            if (module_name == JS_ATOM_NULL)\n                return -1;\n            idx = add_req_module_entry(ctx, m, module_name);\n            JS_FreeAtom(ctx, module_name);\n            if (idx < 0)\n                return -1;\n            if (add_star_export_entry(ctx, m, idx) < 0)\n                return -1;\n        }\n        break;\n    case TOK_DEFAULT:\n        if (s->token.val == TOK_CLASS) {\n            return js_parse_class(s, FALSE, JS_PARSE_EXPORT_DEFAULT);\n        } else if (s->token.val == TOK_FUNCTION ||\n                   (token_is_pseudo_keyword(s, JS_ATOM_async) &&\n                    peek_token(s, TRUE) == TOK_FUNCTION)) {\n            return js_parse_function_decl2(s, JS_PARSE_FUNC_STATEMENT,\n                                           JS_FUNC_NORMAL, JS_ATOM_NULL,\n                                           s->token.ptr, s->token.line_num,\n                                           JS_PARSE_EXPORT_DEFAULT, NULL);\n        } else {\n            if (js_parse_assign_expr(s))\n                return -1;\n        }\n        /* set the name of anonymous functions */\n        set_object_name(s, JS_ATOM_default);\n\n        /* store the value in the _default_ global variable and export\n           it */\n        local_name = JS_ATOM__default_;\n        if (define_var(s, s->cur_func, local_name, JS_VAR_DEF_LET) < 0)\n            return -1;\n        emit_op(s, OP_scope_put_var_init);\n        emit_atom(s, local_name);\n        emit_u16(s, 0);\n\n        if (!add_export_entry(s, m, local_name, JS_ATOM_default,\n                              JS_EXPORT_TYPE_LOCAL))\n            return -1;\n        break;\n    case TOK_VAR:\n    case TOK_LET:\n    case TOK_CONST:\n        return js_parse_var(s, TRUE, tok, TRUE);\n    default:\n        return js_parse_error(s, \"invalid export syntax\");\n    }\n    return js_parse_expect_semi(s);\n}\n\nstatic int add_closure_var(JSContext *ctx, JSFunctionDef *s,\n                           BOOL is_local, BOOL is_arg,\n                           int var_idx, JSAtom var_name,\n                           BOOL is_const, BOOL is_lexical,\n                           JSVarKindEnum var_kind);\n\nstatic int add_import(JSParseState *s, JSModuleDef *m,\n                      JSAtom local_name, JSAtom import_name)\n{\n    JSContext *ctx = s->ctx;\n    int i, var_idx;\n    JSImportEntry *mi;\n    BOOL is_local;\n\n    if (local_name == JS_ATOM_arguments || local_name == JS_ATOM_eval)\n        return js_parse_error(s, \"invalid import binding\");\n\n    if (local_name != JS_ATOM_default) {\n        for (i = 0; i < s->cur_func->closure_var_count; i++) {\n            if (s->cur_func->closure_var[i].var_name == local_name)\n                return js_parse_error(s, \"duplicate import binding\");\n        }\n    }\n\n    is_local = (import_name == JS_ATOM__star_);\n    var_idx = add_closure_var(ctx, s->cur_func, is_local, FALSE,\n                              m->import_entries_count,\n                              local_name, TRUE, TRUE, FALSE);\n    if (var_idx < 0)\n        return -1;\n    if (js_resize_array(ctx, (void **)&m->import_entries,\n                        sizeof(JSImportEntry),\n                        &m->import_entries_size,\n                        m->import_entries_count + 1))\n        return -1;\n    mi = &m->import_entries[m->import_entries_count++];\n    mi->import_name = JS_DupAtom(ctx, import_name);\n    mi->var_idx = var_idx;\n    return 0;\n}\n\nstatic __exception int js_parse_import(JSParseState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSModuleDef *m = s->cur_func->module;\n    JSAtom local_name, import_name, module_name;\n    int first_import, i, idx;\n\n    if (next_token(s))\n        return -1;\n\n    first_import = m->import_entries_count;\n    if (s->token.val == TOK_STRING) {\n        module_name = JS_ValueToAtom(ctx, s->token.u.str.str);\n        if (module_name == JS_ATOM_NULL)\n            return -1;\n        if (next_token(s)) {\n            JS_FreeAtom(ctx, module_name);\n            return -1;\n        }\n    } else {\n        if (s->token.val == TOK_IDENT) {\n            if (s->token.u.ident.is_reserved) {\n                return js_parse_error_reserved_identifier(s);\n            }\n            /* \"default\" import */\n            local_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n            import_name = JS_ATOM_default;\n            if (next_token(s))\n                goto fail;\n            if (add_import(s, m, local_name, import_name))\n                goto fail;\n            JS_FreeAtom(ctx, local_name);\n\n            if (s->token.val != ',')\n                goto end_import_clause;\n            if (next_token(s))\n                return -1;\n        }\n\n        if (s->token.val == '*') {\n            /* name space import */\n            if (next_token(s))\n                return -1;\n            if (!token_is_pseudo_keyword(s, JS_ATOM_as))\n                return js_parse_error(s, \"expecting 'as'\");\n            if (next_token(s))\n                return -1;\n            if (!token_is_ident(s->token.val)) {\n                js_parse_error(s, \"identifier expected\");\n                return -1;\n            }\n            local_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n            import_name = JS_ATOM__star_;\n            if (next_token(s))\n                goto fail;\n            if (add_import(s, m, local_name, import_name))\n                goto fail;\n            JS_FreeAtom(ctx, local_name);\n        } else if (s->token.val == '{') {\n            if (next_token(s))\n                return -1;\n\n            while (s->token.val != '}') {\n                if (!token_is_ident(s->token.val)) {\n                    js_parse_error(s, \"identifier expected\");\n                    return -1;\n                }\n                import_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n                local_name = JS_ATOM_NULL;\n                if (next_token(s))\n                    goto fail;\n                if (token_is_pseudo_keyword(s, JS_ATOM_as)) {\n                    if (next_token(s))\n                        goto fail;\n                    if (!token_is_ident(s->token.val)) {\n                        js_parse_error(s, \"identifier expected\");\n                        goto fail;\n                    }\n                    local_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n                    if (next_token(s)) {\n                    fail:\n                        JS_FreeAtom(ctx, local_name);\n                        JS_FreeAtom(ctx, import_name);\n                        return -1;\n                    }\n                } else {\n                    local_name = JS_DupAtom(ctx, import_name);\n                }\n                if (add_import(s, m, local_name, import_name))\n                    goto fail;\n                JS_FreeAtom(ctx, local_name);\n                JS_FreeAtom(ctx, import_name);\n                if (s->token.val != ',')\n                    break;\n                if (next_token(s))\n                    return -1;\n            }\n            if (js_parse_expect(s, '}'))\n                return -1;\n        }\n    end_import_clause:\n        module_name = js_parse_from_clause(s);\n        if (module_name == JS_ATOM_NULL)\n            return -1;\n    }\n    idx = add_req_module_entry(ctx, m, module_name);\n    JS_FreeAtom(ctx, module_name);\n    if (idx < 0)\n        return -1;\n    for(i = first_import; i < m->import_entries_count; i++)\n        m->import_entries[i].req_module_idx = idx;\n\n    return js_parse_expect_semi(s);\n}\n\nstatic __exception int js_parse_source_element(JSParseState *s)\n{\n    JSFunctionDef *fd = s->cur_func;\n    int tok;\n    \n    if (s->token.val == TOK_FUNCTION ||\n        (token_is_pseudo_keyword(s, JS_ATOM_async) &&\n         peek_token(s, TRUE) == TOK_FUNCTION)) {\n        if (js_parse_function_decl(s, JS_PARSE_FUNC_STATEMENT,\n                                   JS_FUNC_NORMAL, JS_ATOM_NULL,\n                                   s->token.ptr, s->token.line_num))\n            return -1;\n    } else if (s->token.val == TOK_EXPORT && fd->module) {\n        if (js_parse_export(s))\n            return -1;\n    } else if (s->token.val == TOK_IMPORT && fd->module &&\n               ((tok = peek_token(s, FALSE)) != '(' && tok != '.'))  {\n        /* the peek_token is needed to avoid confusion with ImportCall\n           (dynamic import) or import.meta */\n        if (js_parse_import(s))\n            return -1;\n    } else {\n        if (js_parse_statement_or_decl(s, DECL_MASK_ALL))\n            return -1;\n    }\n    return 0;\n}\n\nstatic JSFunctionDef *js_new_function_def(JSContext *ctx,\n                                          JSFunctionDef *parent,\n                                          BOOL is_eval,\n                                          BOOL is_func_expr,\n                                          const char *filename, int line_num)\n{\n    JSFunctionDef *fd;\n\n    fd = js_mallocz(ctx, sizeof(*fd));\n    if (!fd)\n        return NULL;\n\n    fd->ctx = ctx;\n    init_list_head(&fd->child_list);\n\n    /* insert in parent list */\n    fd->parent = parent;\n    fd->parent_cpool_idx = -1;\n    if (parent) {\n        list_add_tail(&fd->link, &parent->child_list);\n        fd->js_mode = parent->js_mode;\n        fd->parent_scope_level = parent->scope_level;\n    }\n\n    fd->is_eval = is_eval;\n    fd->is_func_expr = is_func_expr;\n    js_dbuf_init(ctx, &fd->byte_code);\n    fd->last_opcode_pos = -1;\n    fd->func_name = JS_ATOM_NULL;\n    fd->var_object_idx = -1;\n    fd->arg_var_object_idx = -1;\n    fd->arguments_var_idx = -1;\n    fd->arguments_arg_idx = -1;\n    fd->func_var_idx = -1;\n    fd->eval_ret_idx = -1;\n    fd->this_var_idx = -1;\n    fd->new_target_var_idx = -1;\n    fd->this_active_func_var_idx = -1;\n    fd->home_object_var_idx = -1;\n\n    /* XXX: should distinguish arg, var and var object and body scopes */\n    fd->scopes = fd->def_scope_array;\n    fd->scope_size = countof(fd->def_scope_array);\n    fd->scope_count = 1;\n    fd->scopes[0].first = -1;\n    fd->scopes[0].parent = -1;\n    fd->scope_level = 0;  /* 0: var/arg scope */\n    fd->scope_first = -1;\n    fd->body_scope = -1;\n\n    fd->filename = JS_NewAtom(ctx, filename);\n    fd->line_num = line_num;\n\n    js_dbuf_init(ctx, &fd->pc2line);\n    //fd->pc2line_last_line_num = line_num;\n    //fd->pc2line_last_pc = 0;\n    fd->last_opcode_line_num = line_num;\n\n    return fd;\n}\n\nstatic void free_bytecode_atoms(JSRuntime *rt,\n                                const uint8_t *bc_buf, int bc_len,\n                                BOOL use_short_opcodes)\n{\n    int pos, len, op;\n    JSAtom atom;\n    const JSOpCode *oi;\n    \n    pos = 0;\n    while (pos < bc_len) {\n        op = bc_buf[pos];\n        if (use_short_opcodes)\n            oi = &short_opcode_info(op);\n        else\n            oi = &opcode_info[op];\n            \n        len = oi->size;\n        switch(oi->fmt) {\n        case OP_FMT_atom:\n        case OP_FMT_atom_u8:\n        case OP_FMT_atom_u16:\n        case OP_FMT_atom_label_u8:\n        case OP_FMT_atom_label_u16:\n            atom = get_u32(bc_buf + pos + 1);\n            JS_FreeAtomRT(rt, atom);\n            break;\n        default:\n            break;\n        }\n        pos += len;\n    }\n}\n\nstatic void js_free_function_def(JSContext *ctx, JSFunctionDef *fd)\n{\n    int i;\n    struct list_head *el, *el1;\n\n    /* free the child functions */\n    list_for_each_safe(el, el1, &fd->child_list) {\n        JSFunctionDef *fd1;\n        fd1 = list_entry(el, JSFunctionDef, link);\n        js_free_function_def(ctx, fd1);\n    }\n\n    free_bytecode_atoms(ctx->rt, fd->byte_code.buf, fd->byte_code.size,\n                        fd->use_short_opcodes);\n    dbuf_free(&fd->byte_code);\n    js_free(ctx, fd->jump_slots);\n    js_free(ctx, fd->label_slots);\n    js_free(ctx, fd->line_number_slots);\n\n    for(i = 0; i < fd->cpool_count; i++) {\n        JS_FreeValue(ctx, fd->cpool[i]);\n    }\n    js_free(ctx, fd->cpool);\n\n    JS_FreeAtom(ctx, fd->func_name);\n\n    for(i = 0; i < fd->var_count; i++) {\n        JS_FreeAtom(ctx, fd->vars[i].var_name);\n    }\n    js_free(ctx, fd->vars);\n    for(i = 0; i < fd->arg_count; i++) {\n        JS_FreeAtom(ctx, fd->args[i].var_name);\n    }\n    js_free(ctx, fd->args);\n\n    for(i = 0; i < fd->global_var_count; i++) {\n        JS_FreeAtom(ctx, fd->global_vars[i].var_name);\n    }\n    js_free(ctx, fd->global_vars);\n\n    for(i = 0; i < fd->closure_var_count; i++) {\n        JSClosureVar *cv = &fd->closure_var[i];\n        JS_FreeAtom(ctx, cv->var_name);\n    }\n    js_free(ctx, fd->closure_var);\n\n    if (fd->scopes != fd->def_scope_array)\n        js_free(ctx, fd->scopes);\n\n    JS_FreeAtom(ctx, fd->filename);\n    dbuf_free(&fd->pc2line);\n\n    js_free(ctx, fd->source);\n\n    if (fd->parent) {\n        /* remove in parent list */\n        list_del(&fd->link);\n    }\n    js_free(ctx, fd);\n}\n\n#ifdef DUMP_BYTECODE\nstatic const char *skip_lines(const char *p, int n) {\n    while (n-- > 0 && *p) {\n        while (*p && *p++ != '\\n')\n            continue;\n    }\n    return p;\n}\n\nstatic void print_lines(const char *source, int line, int line1) {\n    const char *s = source;\n    const char *p = skip_lines(s, line);\n    if (*p) {\n        while (line++ < line1) {\n            p = skip_lines(s = p, 1);\n            printf(\";; %.*s\", (int)(p - s), s);\n            if (!*p) {\n                if (p[-1] != '\\n')\n                    printf(\"\\n\");\n                break;\n            }\n        }\n    }\n}\n\nstatic void dump_byte_code(JSContext *ctx, int pass,\n                           const uint8_t *tab, int len,\n                           const JSVarDef *args, int arg_count,\n                           const JSVarDef *vars, int var_count,\n                           const JSClosureVar *closure_var, int closure_var_count,\n                           const JSValue *cpool, uint32_t cpool_count,\n                           const char *source, int line_num,\n                           const LabelSlot *label_slots, JSFunctionBytecode *b)\n{\n    const JSOpCode *oi;\n    int pos, pos_next, op, size, idx, addr, line, line1, in_source;\n    uint8_t *bits = js_mallocz(ctx, len * sizeof(*bits));\n    BOOL use_short_opcodes = (b != NULL);\n\n    /* scan for jump targets */\n    for (pos = 0; pos < len; pos = pos_next) {\n        op = tab[pos];\n        if (use_short_opcodes)\n            oi = &short_opcode_info(op);\n        else\n            oi = &opcode_info[op];\n        pos_next = pos + oi->size;\n        if (op < OP_COUNT) {\n            switch (oi->fmt) {\n#if SHORT_OPCODES\n            case OP_FMT_label8:\n                pos++;\n                addr = (int8_t)tab[pos];\n                goto has_addr;\n            case OP_FMT_label16:\n                pos++;\n                addr = (int16_t)get_u16(tab + pos);\n                goto has_addr;\n#endif\n            case OP_FMT_atom_label_u8:\n            case OP_FMT_atom_label_u16:\n                pos += 4;\n                /* fall thru */\n            case OP_FMT_label:\n            case OP_FMT_label_u16:\n                pos++;\n                addr = get_u32(tab + pos);\n                goto has_addr;\n            has_addr:\n                if (pass == 1)\n                    addr = label_slots[addr].pos;\n                if (pass == 2)\n                    addr = label_slots[addr].pos2;\n                if (pass == 3)\n                    addr += pos;\n                if (addr >= 0 && addr < len)\n                    bits[addr] |= 1;\n                break;\n            }\n        }\n    }\n    in_source = 0;\n    if (source) {\n        /* Always print first line: needed if single line */\n        print_lines(source, 0, 1);\n        in_source = 1;\n    }\n    line1 = line = 1;\n    pos = 0;\n    while (pos < len) {\n        op = tab[pos];\n        if (source) {\n            if (b) {\n                line1 = find_line_num(ctx, b, pos) - line_num + 1;\n            } else if (op == OP_line_num) {\n                line1 = get_u32(tab + pos + 1) - line_num + 1;\n            }\n            if (line1 > line) {\n                if (!in_source)\n                    printf(\"\\n\");\n                in_source = 1;\n                print_lines(source, line, line1);\n                line = line1;\n                //bits[pos] |= 2;\n            }\n        }\n        if (in_source)\n            printf(\"\\n\");\n        in_source = 0;\n        if (op >= OP_COUNT) {\n            printf(\"invalid opcode (0x%02x)\\n\", op);\n            pos++;\n            continue;\n        }\n        if (use_short_opcodes)\n            oi = &short_opcode_info(op);\n        else\n            oi = &opcode_info[op];\n        size = oi->size;\n        if (pos + size > len) {\n            printf(\"truncated opcode (0x%02x)\\n\", op);\n            break;\n        }\n#if defined(DUMP_BYTECODE) && (DUMP_BYTECODE & 16)\n        {\n            int i, x, x0;\n            x = x0 = printf(\"%5d \", pos);\n            for (i = 0; i < size; i++) {\n                if (i == 6) {\n                    printf(\"\\n%*s\", x = x0, \"\");\n                }\n                x += printf(\" %02X\", tab[pos + i]);\n            }\n            printf(\"%*s\", x0 + 20 - x, \"\");\n        }\n#endif\n        if (bits[pos]) {\n            printf(\"%5d:  \", pos);\n        } else {\n            printf(\"        \");\n        }\n        printf(\"%s\", oi->name);\n        pos++;\n        switch(oi->fmt) {\n        case OP_FMT_none_int:\n            printf(\" %d\", op - OP_push_0);\n            break;\n        case OP_FMT_npopx:\n            printf(\" %d\", op - OP_call0);\n            break;\n        case OP_FMT_u8:\n            printf(\" %u\", get_u8(tab + pos));\n            break;\n        case OP_FMT_i8:\n            printf(\" %d\", get_i8(tab + pos));\n            break;\n        case OP_FMT_u16:\n        case OP_FMT_npop:\n            printf(\" %u\", get_u16(tab + pos));\n            break;\n        case OP_FMT_npop_u16:\n            printf(\" %u,%u\", get_u16(tab + pos), get_u16(tab + pos + 2));\n            break;\n        case OP_FMT_i16:\n            printf(\" %d\", get_i16(tab + pos));\n            break;\n        case OP_FMT_i32:\n            printf(\" %d\", get_i32(tab + pos));\n            break;\n        case OP_FMT_u32:\n            printf(\" %u\", get_u32(tab + pos));\n            break;\n#if SHORT_OPCODES\n        case OP_FMT_label8:\n            addr = get_i8(tab + pos);\n            goto has_addr1;\n        case OP_FMT_label16:\n            addr = get_i16(tab + pos);\n            goto has_addr1;\n#endif\n        case OP_FMT_label:\n            addr = get_u32(tab + pos);\n            goto has_addr1;\n        has_addr1:\n            if (pass == 1)\n                printf(\" %u:%u\", addr, label_slots[addr].pos);\n            if (pass == 2)\n                printf(\" %u:%u\", addr, label_slots[addr].pos2);\n            if (pass == 3)\n                printf(\" %u\", addr + pos);\n            break;\n        case OP_FMT_label_u16:\n            addr = get_u32(tab + pos);\n            if (pass == 1)\n                printf(\" %u:%u\", addr, label_slots[addr].pos);\n            if (pass == 2)\n                printf(\" %u:%u\", addr, label_slots[addr].pos2);\n            if (pass == 3)\n                printf(\" %u\", addr + pos);\n            printf(\",%u\", get_u16(tab + pos + 4));\n            break;\n#if SHORT_OPCODES\n        case OP_FMT_const8:\n            idx = get_u8(tab + pos);\n            goto has_pool_idx;\n#endif\n        case OP_FMT_const:\n            idx = get_u32(tab + pos);\n            goto has_pool_idx;\n        has_pool_idx:\n            printf(\" %u: \", idx);\n            if (idx < cpool_count) {\n                JS_DumpValue(ctx, cpool[idx]);\n            }\n            break;\n        case OP_FMT_atom:\n            printf(\" \");\n            print_atom(ctx, get_u32(tab + pos));\n            break;\n        case OP_FMT_atom_u8:\n            printf(\" \");\n            print_atom(ctx, get_u32(tab + pos));\n            printf(\",%d\", get_u8(tab + pos + 4));\n            break;\n        case OP_FMT_atom_u16:\n            printf(\" \");\n            print_atom(ctx, get_u32(tab + pos));\n            printf(\",%d\", get_u16(tab + pos + 4));\n            break;\n        case OP_FMT_atom_label_u8:\n        case OP_FMT_atom_label_u16:\n            printf(\" \");\n            print_atom(ctx, get_u32(tab + pos));\n            addr = get_u32(tab + pos + 4);\n            if (pass == 1)\n                printf(\",%u:%u\", addr, label_slots[addr].pos);\n            if (pass == 2)\n                printf(\",%u:%u\", addr, label_slots[addr].pos2);\n            if (pass == 3)\n                printf(\",%u\", addr + pos + 4);\n            if (oi->fmt == OP_FMT_atom_label_u8)\n                printf(\",%u\", get_u8(tab + pos + 8));\n            else\n                printf(\",%u\", get_u16(tab + pos + 8));\n            break;\n        case OP_FMT_none_loc:\n            idx = (op - OP_get_loc0) % 4;\n            goto has_loc;\n        case OP_FMT_loc8:\n            idx = get_u8(tab + pos);\n            goto has_loc;\n        case OP_FMT_loc:\n            idx = get_u16(tab + pos);\n        has_loc:\n            printf(\" %d: \", idx);\n            if (idx < var_count) {\n                print_atom(ctx, vars[idx].var_name);\n            }\n            break;\n        case OP_FMT_none_arg:\n            idx = (op - OP_get_arg0) % 4;\n            goto has_arg;\n        case OP_FMT_arg:\n            idx = get_u16(tab + pos);\n        has_arg:\n            printf(\" %d: \", idx);\n            if (idx < arg_count) {\n                print_atom(ctx, args[idx].var_name);\n            }\n            break;\n        case OP_FMT_none_var_ref:\n            idx = (op - OP_get_var_ref0) % 4;\n            goto has_var_ref;\n        case OP_FMT_var_ref:\n            idx = get_u16(tab + pos);\n        has_var_ref:\n            printf(\" %d: \", idx);\n            if (idx < closure_var_count) {\n                print_atom(ctx, closure_var[idx].var_name);\n            }\n            break;\n        default:\n            break;\n        }\n        printf(\"\\n\");\n        pos += oi->size - 1;\n    }\n    if (source) {\n        if (!in_source)\n            printf(\"\\n\");\n        print_lines(source, line, INT32_MAX);\n    }\n    js_free(ctx, bits);\n}\n\nstatic __maybe_unused void dump_pc2line(JSContext *ctx, const uint8_t *buf, int len,\n                                                 int line_num)\n{\n    const uint8_t *p_end, *p_next, *p;\n    int pc, v;\n    unsigned int op;\n\n    if (len <= 0)\n        return;\n\n    printf(\"%5s %5s\\n\", \"PC\", \"LINE\");\n\n    p = buf;\n    p_end = buf + len;\n    pc = 0;\n    while (p < p_end) {\n        op = *p++;\n        if (op == 0) {\n            v = unicode_from_utf8(p, p_end - p, &p_next);\n            if (v < 0)\n                goto fail;\n            pc += v;\n            p = p_next;\n            v = unicode_from_utf8(p, p_end - p, &p_next);\n            if (v < 0) {\n            fail:\n                printf(\"invalid pc2line encode pos=%d\\n\", (int)(p - buf));\n                return;\n            }\n            if (!(v & 1)) {\n                v = v >> 1;\n            } else {\n                v = -(v >> 1) - 1;\n            }\n            line_num += v;\n            p = p_next;\n        } else {\n            op -= PC2LINE_OP_FIRST;\n            pc += (op / PC2LINE_RANGE);\n            line_num += (op % PC2LINE_RANGE) + PC2LINE_BASE;\n        }\n        printf(\"%5d %5d\\n\", pc, line_num);\n    }\n}\n\nstatic __maybe_unused void js_dump_function_bytecode(JSContext *ctx, JSFunctionBytecode *b)\n{\n    int i;\n    char atom_buf[ATOM_GET_STR_BUF_SIZE];\n    const char *str;\n\n    if (b->has_debug && b->debug.filename != JS_ATOM_NULL) {\n        str = JS_AtomGetStr(ctx, atom_buf, sizeof(atom_buf), b->debug.filename);\n        printf(\"%s:%d: \", str, b->debug.line_num);\n    }\n\n    str = JS_AtomGetStr(ctx, atom_buf, sizeof(atom_buf), b->func_name);\n    printf(\"function: %s%s\\n\", &\"*\"[b->func_kind != JS_FUNC_GENERATOR], str);\n    if (b->js_mode) {\n        printf(\"  mode:\");\n        if (b->js_mode & JS_MODE_STRICT)\n            printf(\" strict\");\n#ifdef CONFIG_BIGNUM\n        if (b->js_mode & JS_MODE_MATH)\n            printf(\" math\");\n#endif\n        printf(\"\\n\");\n    }\n    if (b->arg_count && b->vardefs) {\n        printf(\"  args:\");\n        for(i = 0; i < b->arg_count; i++) {\n            printf(\" %s\", JS_AtomGetStr(ctx, atom_buf, sizeof(atom_buf),\n                                        b->vardefs[i].var_name));\n        }\n        printf(\"\\n\");\n    }\n    if (b->var_count && b->vardefs) {\n        printf(\"  locals:\\n\");\n        for(i = 0; i < b->var_count; i++) {\n            JSVarDef *vd = &b->vardefs[b->arg_count + i];\n            printf(\"%5d: %s %s\", i,\n                   vd->var_kind == JS_VAR_CATCH ? \"catch\" :\n                   (vd->var_kind == JS_VAR_FUNCTION_DECL ||\n                    vd->var_kind == JS_VAR_NEW_FUNCTION_DECL) ? \"function\" :\n                   vd->is_const ? \"const\" :\n                   vd->is_lexical ? \"let\" : \"var\",\n                   JS_AtomGetStr(ctx, atom_buf, sizeof(atom_buf), vd->var_name));\n            if (vd->scope_level)\n                printf(\" [level:%d next:%d]\", vd->scope_level, vd->scope_next);\n            printf(\"\\n\");\n        }\n    }\n    if (b->closure_var_count) {\n        printf(\"  closure vars:\\n\");\n        for(i = 0; i < b->closure_var_count; i++) {\n            JSClosureVar *cv = &b->closure_var[i];\n            printf(\"%5d: %s %s:%s%d %s\\n\", i,\n                   JS_AtomGetStr(ctx, atom_buf, sizeof(atom_buf), cv->var_name),\n                   cv->is_local ? \"local\" : \"parent\",\n                   cv->is_arg ? \"arg\" : \"loc\", cv->var_idx,\n                   cv->is_const ? \"const\" :\n                   cv->is_lexical ? \"let\" : \"var\");\n        }\n    }\n    printf(\"  stack_size: %d\\n\", b->stack_size);\n    printf(\"  opcodes:\\n\");\n    dump_byte_code(ctx, 3, b->byte_code_buf, b->byte_code_len,\n                   b->vardefs, b->arg_count,\n                   b->vardefs ? b->vardefs + b->arg_count : NULL, b->var_count,\n                   b->closure_var, b->closure_var_count,\n                   b->cpool, b->cpool_count,\n                   b->has_debug ? b->debug.source : NULL,\n                   b->has_debug ? b->debug.line_num : -1, NULL, b);\n#if defined(DUMP_BYTECODE) && (DUMP_BYTECODE & 32)\n    if (b->has_debug)\n        dump_pc2line(ctx, b->debug.pc2line_buf, b->debug.pc2line_len, b->debug.line_num);\n#endif\n    printf(\"\\n\");\n}\n#endif\n\nstatic int add_closure_var(JSContext *ctx, JSFunctionDef *s,\n                           BOOL is_local, BOOL is_arg,\n                           int var_idx, JSAtom var_name,\n                           BOOL is_const, BOOL is_lexical,\n                           JSVarKindEnum var_kind)\n{\n    JSClosureVar *cv;\n\n    /* the closure variable indexes are currently stored on 16 bits */\n    if (s->closure_var_count >= JS_MAX_LOCAL_VARS) {\n        JS_ThrowInternalError(ctx, \"too many closure variables\");\n        return -1;\n    }\n\n    if (js_resize_array(ctx, (void **)&s->closure_var,\n                        sizeof(s->closure_var[0]),\n                        &s->closure_var_size, s->closure_var_count + 1))\n        return -1;\n    cv = &s->closure_var[s->closure_var_count++];\n    cv->is_local = is_local;\n    cv->is_arg = is_arg;\n    cv->is_const = is_const;\n    cv->is_lexical = is_lexical;\n    cv->var_kind = var_kind;\n    cv->var_idx = var_idx;\n    cv->var_name = JS_DupAtom(ctx, var_name);\n    return s->closure_var_count - 1;\n}\n\nstatic int find_closure_var(JSContext *ctx, JSFunctionDef *s,\n                            JSAtom var_name)\n{\n    int i;\n    for(i = 0; i < s->closure_var_count; i++) {\n        JSClosureVar *cv = &s->closure_var[i];\n        if (cv->var_name == var_name)\n            return i;\n    }\n    return -1;\n}\n\n/* 'fd' must be a parent of 's'. Create in 's' a closure referencing a\n   local variable (is_local = TRUE) or a closure (is_local = FALSE) in\n   'fd' */\nstatic int get_closure_var2(JSContext *ctx, JSFunctionDef *s,\n                            JSFunctionDef *fd, BOOL is_local,\n                            BOOL is_arg, int var_idx, JSAtom var_name,\n                            BOOL is_const, BOOL is_lexical,\n                            JSVarKindEnum var_kind)\n{\n    int i;\n\n    if (fd != s->parent) {\n        var_idx = get_closure_var2(ctx, s->parent, fd, is_local,\n                                   is_arg, var_idx, var_name,\n                                   is_const, is_lexical, var_kind);\n        if (var_idx < 0)\n            return -1;\n        is_local = FALSE;\n    }\n    for(i = 0; i < s->closure_var_count; i++) {\n        JSClosureVar *cv = &s->closure_var[i];\n        if (cv->var_idx == var_idx && cv->is_arg == is_arg &&\n            cv->is_local == is_local)\n            return i;\n    }\n    return add_closure_var(ctx, s, is_local, is_arg, var_idx, var_name,\n                           is_const, is_lexical, var_kind);\n}\n\nstatic int get_closure_var(JSContext *ctx, JSFunctionDef *s,\n                           JSFunctionDef *fd, BOOL is_arg,\n                           int var_idx, JSAtom var_name,\n                           BOOL is_const, BOOL is_lexical,\n                           JSVarKindEnum var_kind)\n{\n    return get_closure_var2(ctx, s, fd, TRUE, is_arg,\n                            var_idx, var_name, is_const, is_lexical,\n                            var_kind);\n}\n\nstatic int get_with_scope_opcode(int op)\n{\n    if (op == OP_scope_get_var_undef)\n        return OP_with_get_var;\n    else\n        return OP_with_get_var + (op - OP_scope_get_var);\n}\n\nstatic BOOL can_opt_put_ref_value(const uint8_t *bc_buf, int pos)\n{\n    int opcode = bc_buf[pos];\n    return (bc_buf[pos + 1] == OP_put_ref_value &&\n            (opcode == OP_insert3 ||\n             opcode == OP_perm4 ||\n             opcode == OP_nop ||\n             opcode == OP_rot3l));\n}\n\nstatic BOOL can_opt_put_global_ref_value(const uint8_t *bc_buf, int pos)\n{\n    int opcode = bc_buf[pos];\n    return (bc_buf[pos + 1] == OP_put_ref_value &&\n            (opcode == OP_insert3 ||\n             opcode == OP_perm4 ||\n             opcode == OP_nop ||\n             opcode == OP_rot3l));\n}\n\nstatic int optimize_scope_make_ref(JSContext *ctx, JSFunctionDef *s,\n                                   DynBuf *bc, uint8_t *bc_buf,\n                                   LabelSlot *ls, int pos_next,\n                                   int get_op, int var_idx)\n{\n    int label_pos, end_pos, pos;\n\n    /* XXX: should optimize `loc(a) += expr` as `expr add_loc(a)`\n       but only if expr does not modify `a`.\n       should scan the code between pos_next and label_pos\n       for operations that can potentially change `a`:\n       OP_scope_make_ref(a), function calls, jumps and gosub.\n     */\n    /* replace the reference get/put with normal variable\n       accesses */\n    if (bc_buf[pos_next] == OP_get_ref_value) {\n        dbuf_putc(bc, get_op);\n        dbuf_put_u16(bc, var_idx);\n        pos_next++;\n    }\n    /* remove the OP_label to make room for replacement */\n    /* label should have a refcount of 0 anyway */\n    /* XXX: should avoid this patch by inserting nops in phase 1 */\n    label_pos = ls->pos;\n    pos = label_pos - 5;\n    assert(bc_buf[pos] == OP_label);\n    /* label points to an instruction pair:\n       - insert3 / put_ref_value\n       - perm4 / put_ref_value\n       - rot3l / put_ref_value\n       - nop / put_ref_value\n     */\n    end_pos = label_pos + 2;\n    if (bc_buf[label_pos] == OP_insert3)\n        bc_buf[pos++] = OP_dup;\n    bc_buf[pos] = get_op + 1;\n    put_u16(bc_buf + pos + 1, var_idx);\n    pos += 3;\n    /* pad with OP_nop */\n    while (pos < end_pos)\n        bc_buf[pos++] = OP_nop;\n    return pos_next;\n}\n\nstatic int optimize_scope_make_global_ref(JSContext *ctx, JSFunctionDef *s,\n                                          DynBuf *bc, uint8_t *bc_buf,\n                                          LabelSlot *ls, int pos_next,\n                                          JSAtom var_name)\n{\n    int label_pos, end_pos, pos, op;\n    BOOL is_strict;\n    is_strict = ((s->js_mode & JS_MODE_STRICT) != 0);\n\n    /* replace the reference get/put with normal variable\n       accesses */\n    if (is_strict) {\n        /* need to check if the variable exists before evaluating the right\n           expression */\n        /* XXX: need an extra OP_true if destructuring an array */\n        dbuf_putc(bc, OP_check_var);\n        dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n    } else {\n        /* XXX: need 2 extra OP_true if destructuring an array */\n    }\n    if (bc_buf[pos_next] == OP_get_ref_value) {\n        dbuf_putc(bc, OP_get_var);\n        dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n        pos_next++;\n    }\n    /* remove the OP_label to make room for replacement */\n    /* label should have a refcount of 0 anyway */\n    /* XXX: should have emitted several OP_nop to avoid this kludge */\n    label_pos = ls->pos;\n    pos = label_pos - 5;\n    assert(bc_buf[pos] == OP_label);\n    end_pos = label_pos + 2;\n    op = bc_buf[label_pos];\n    if (is_strict) {\n        if (op != OP_nop) {\n            switch(op) {\n            case OP_insert3:\n                op = OP_insert2;\n                break;\n            case OP_perm4:\n                op = OP_perm3;\n                break;\n            case OP_rot3l:\n                op = OP_swap;\n                break;\n            default:\n                abort();\n            }\n            bc_buf[pos++] = op;\n        }\n    } else {\n        if (op == OP_insert3)\n            bc_buf[pos++] = OP_dup;\n    }\n    if (is_strict) {\n        bc_buf[pos] = OP_put_var_strict;\n        /* XXX: need 1 extra OP_drop if destructuring an array */\n    } else {\n        bc_buf[pos] = OP_put_var;\n        /* XXX: need 2 extra OP_drop if destructuring an array */\n    }\n    put_u32(bc_buf + pos + 1, JS_DupAtom(ctx, var_name));\n    pos += 5;\n    /* pad with OP_nop */\n    while (pos < end_pos)\n        bc_buf[pos++] = OP_nop;\n    return pos_next;\n}\n\nstatic int add_var_this(JSContext *ctx, JSFunctionDef *fd)\n{\n    int idx;\n    idx = add_var(ctx, fd, JS_ATOM_this);\n    if (idx >= 0 && fd->is_derived_class_constructor) {\n        JSVarDef *vd = &fd->vars[idx];\n        /* XXX: should have is_this flag or var type */\n        vd->is_lexical = 1; /* used to trigger 'uninitialized' checks\n                               in a derived class constructor */\n    }\n    return idx;\n}\n\nstatic int resolve_pseudo_var(JSContext *ctx, JSFunctionDef *s,\n                               JSAtom var_name)\n{\n    int var_idx;\n\n    if (!s->has_this_binding)\n        return -1;\n    switch(var_name) {\n    case JS_ATOM_home_object:\n        /* 'home_object' pseudo variable */\n        if (s->home_object_var_idx < 0)\n            s->home_object_var_idx = add_var(ctx, s, var_name);\n        var_idx = s->home_object_var_idx;\n        break;\n    case JS_ATOM_this_active_func:\n        /* 'this.active_func' pseudo variable */\n        if (s->this_active_func_var_idx < 0)\n            s->this_active_func_var_idx = add_var(ctx, s, var_name);\n        var_idx = s->this_active_func_var_idx;\n        break;\n    case JS_ATOM_new_target:\n        /* 'new.target' pseudo variable */\n        if (s->new_target_var_idx < 0)\n            s->new_target_var_idx = add_var(ctx, s, var_name);\n        var_idx = s->new_target_var_idx;\n        break;\n    case JS_ATOM_this:\n        /* 'this' pseudo variable */\n        if (s->this_var_idx < 0)\n            s->this_var_idx = add_var_this(ctx, s);\n        var_idx = s->this_var_idx;\n        break;\n    default:\n        var_idx = -1;\n        break;\n    }\n    return var_idx;\n}\n\n/* test if 'var_name' is in the variable object on the stack. If is it\n   the case, handle it and jump to 'label_done' */\nstatic void var_object_test(JSContext *ctx, JSFunctionDef *s,\n                            JSAtom var_name, int op, DynBuf *bc,\n                            int *plabel_done, BOOL is_with)\n{\n    dbuf_putc(bc, get_with_scope_opcode(op));\n    dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n    *plabel_done = new_label_fd(s, *plabel_done);\n    dbuf_put_u32(bc, *plabel_done);\n    dbuf_putc(bc, is_with);\n    update_label(s, *plabel_done, 1);\n    s->jump_size++;\n}\n    \n/* return the position of the next opcode */\nstatic int resolve_scope_var(JSContext *ctx, JSFunctionDef *s,\n                             JSAtom var_name, int scope_level, int op,\n                             DynBuf *bc, uint8_t *bc_buf,\n                             LabelSlot *ls, int pos_next)\n{\n    int idx, var_idx, is_put;\n    int label_done;\n    JSFunctionDef *fd;\n    JSVarDef *vd;\n    BOOL is_pseudo_var, is_arg_scope;\n\n    label_done = -1;\n\n    /* XXX: could be simpler to use a specific function to\n       resolve the pseudo variables */\n    is_pseudo_var = (var_name == JS_ATOM_home_object ||\n                     var_name == JS_ATOM_this_active_func ||\n                     var_name == JS_ATOM_new_target ||\n                     var_name == JS_ATOM_this);\n\n    /* resolve local scoped variables */\n    var_idx = -1;\n    for (idx = s->scopes[scope_level].first; idx >= 0;) {\n        vd = &s->vars[idx];\n        if (vd->var_name == var_name) {\n            if (op == OP_scope_put_var || op == OP_scope_make_ref) {\n                if (vd->is_const) {\n                    dbuf_putc(bc, OP_throw_error);\n                    dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                    dbuf_putc(bc, JS_THROW_VAR_RO);\n                    goto done;\n                }\n            }\n            var_idx = idx;\n            break;\n        } else\n        if (vd->var_name == JS_ATOM__with_ && !is_pseudo_var) {\n            dbuf_putc(bc, OP_get_loc);\n            dbuf_put_u16(bc, idx);\n            var_object_test(ctx, s, var_name, op, bc, &label_done, 1);\n        }\n        idx = vd->scope_next;\n    }\n    is_arg_scope = (idx == ARG_SCOPE_END);\n    if (var_idx < 0) {\n        /* argument scope: variables are not visible but pseudo\n           variables are visible */\n        if (!is_arg_scope) {\n            var_idx = find_var(ctx, s, var_name);\n        }\n\n        if (var_idx < 0 && is_pseudo_var)\n            var_idx = resolve_pseudo_var(ctx, s, var_name);\n\n        if (var_idx < 0 && var_name == JS_ATOM_arguments &&\n            s->has_arguments_binding) {\n            /* 'arguments' pseudo variable */\n            var_idx = add_arguments_var(ctx, s);\n        }\n        if (var_idx < 0 && s->is_func_expr && var_name == s->func_name) {\n            /* add a new variable with the function name */\n            var_idx = add_func_var(ctx, s, var_name);\n        }\n    }\n    if (var_idx >= 0) {\n        if ((op == OP_scope_put_var || op == OP_scope_make_ref) &&\n            !(var_idx & ARGUMENT_VAR_OFFSET) &&\n            s->vars[var_idx].is_const) {\n            /* only happens when assigning a function expression name\n               in strict mode */\n            dbuf_putc(bc, OP_throw_error);\n            dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n            dbuf_putc(bc, JS_THROW_VAR_RO);\n            goto done;\n        }\n        /* OP_scope_put_var_init is only used to initialize a\n           lexical variable, so it is never used in a with or var object. It\n           can be used with a closure (module global variable case). */\n        switch (op) {\n        case OP_scope_make_ref:\n            if (!(var_idx & ARGUMENT_VAR_OFFSET) &&\n                s->vars[var_idx].var_kind == JS_VAR_FUNCTION_NAME) {\n                /* Create a dummy object reference for the func_var */\n                dbuf_putc(bc, OP_object);\n                dbuf_putc(bc, OP_get_loc);\n                dbuf_put_u16(bc, var_idx);\n                dbuf_putc(bc, OP_define_field);\n                dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                dbuf_putc(bc, OP_push_atom_value);\n                dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n            } else\n            if (label_done == -1 && can_opt_put_ref_value(bc_buf, ls->pos)) {\n                int get_op;\n                if (var_idx & ARGUMENT_VAR_OFFSET) {\n                    get_op = OP_get_arg;\n                    var_idx -= ARGUMENT_VAR_OFFSET;\n                } else {\n                    if (s->vars[var_idx].is_lexical)\n                        get_op = OP_get_loc_check;\n                    else\n                        get_op = OP_get_loc;\n                }\n                pos_next = optimize_scope_make_ref(ctx, s, bc, bc_buf, ls,\n                                                   pos_next, get_op, var_idx);\n            } else {\n                /* Create a dummy object with a named slot that is\n                   a reference to the local variable */\n                if (var_idx & ARGUMENT_VAR_OFFSET) {\n                    dbuf_putc(bc, OP_make_arg_ref);\n                    dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                    dbuf_put_u16(bc, var_idx - ARGUMENT_VAR_OFFSET);\n                } else {\n                    dbuf_putc(bc, OP_make_loc_ref);\n                    dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                    dbuf_put_u16(bc, var_idx);\n                }\n            }\n            break;\n        case OP_scope_get_ref:\n            dbuf_putc(bc, OP_undefined);\n            /* fall thru */\n        case OP_scope_get_var_undef:\n        case OP_scope_get_var:\n        case OP_scope_put_var:\n        case OP_scope_put_var_init:\n            is_put = (op == OP_scope_put_var || op == OP_scope_put_var_init);\n            if (var_idx & ARGUMENT_VAR_OFFSET) {\n                dbuf_putc(bc, OP_get_arg + is_put);\n                dbuf_put_u16(bc, var_idx - ARGUMENT_VAR_OFFSET);\n            } else {\n                if (is_put) {\n                    if (s->vars[var_idx].is_lexical) {\n                        if (op == OP_scope_put_var_init) {\n                            /* 'this' can only be initialized once */\n                            if (var_name == JS_ATOM_this)\n                                dbuf_putc(bc, OP_put_loc_check_init);\n                            else\n                                dbuf_putc(bc, OP_put_loc);\n                        } else {\n                            dbuf_putc(bc, OP_put_loc_check);\n                        }\n                    } else {\n                        dbuf_putc(bc, OP_put_loc);\n                    }\n                } else {\n                    if (s->vars[var_idx].is_lexical) {\n                        dbuf_putc(bc, OP_get_loc_check);\n                    } else {\n                        dbuf_putc(bc, OP_get_loc);\n                    }\n                }\n                dbuf_put_u16(bc, var_idx);\n            }\n            break;\n        case OP_scope_delete_var:\n            dbuf_putc(bc, OP_push_false);\n            break;\n        }\n        goto done;\n    }\n    /* check eval object */\n    if (!is_arg_scope && s->var_object_idx >= 0 && !is_pseudo_var) {\n        dbuf_putc(bc, OP_get_loc);\n        dbuf_put_u16(bc, s->var_object_idx);\n        var_object_test(ctx, s, var_name, op, bc, &label_done, 0);\n    }\n    /* check eval object in argument scope */\n    if (s->arg_var_object_idx >= 0 && !is_pseudo_var) {\n        dbuf_putc(bc, OP_get_loc);\n        dbuf_put_u16(bc, s->arg_var_object_idx);\n        var_object_test(ctx, s, var_name, op, bc, &label_done, 0);\n    }\n\n    /* check parent scopes */\n    for (fd = s; fd->parent;) {\n        scope_level = fd->parent_scope_level;\n        fd = fd->parent;\n        for (idx = fd->scopes[scope_level].first; idx >= 0;) {\n            vd = &fd->vars[idx];\n            if (vd->var_name == var_name) {\n                if (op == OP_scope_put_var || op == OP_scope_make_ref) {\n                    if (vd->is_const) {\n                        dbuf_putc(bc, OP_throw_error);\n                        dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                        dbuf_putc(bc, JS_THROW_VAR_RO);\n                        goto done;\n                    }\n                }\n                var_idx = idx;\n                break;\n            } else if (vd->var_name == JS_ATOM__with_ && !is_pseudo_var) {\n                vd->is_captured = 1;\n                idx = get_closure_var(ctx, s, fd, FALSE, idx, vd->var_name, FALSE, FALSE, JS_VAR_NORMAL);\n                if (idx >= 0) {\n                    dbuf_putc(bc, OP_get_var_ref);\n                    dbuf_put_u16(bc, idx);\n                    var_object_test(ctx, s, var_name, op, bc, &label_done, 1);\n                }\n            }\n            idx = vd->scope_next;\n        }\n        is_arg_scope = (idx == ARG_SCOPE_END);\n        if (var_idx >= 0)\n            break;\n        \n        if (!is_arg_scope) {\n            var_idx = find_var(ctx, fd, var_name);\n            if (var_idx >= 0)\n                break;\n        }\n        if (is_pseudo_var) {\n            var_idx = resolve_pseudo_var(ctx, fd, var_name);\n            if (var_idx >= 0)\n                break;\n        }\n        if (var_name == JS_ATOM_arguments && fd->has_arguments_binding) {\n            var_idx = add_arguments_var(ctx, fd);\n            break;\n        }\n        if (fd->is_func_expr && fd->func_name == var_name) {\n            /* add a new variable with the function name */\n            var_idx = add_func_var(ctx, fd, var_name);\n            break;\n        }\n\n        /* check eval object */\n        if (!is_arg_scope && fd->var_object_idx >= 0 && !is_pseudo_var) {\n            vd = &fd->vars[fd->var_object_idx];\n            vd->is_captured = 1;\n            idx = get_closure_var(ctx, s, fd, FALSE,\n                                  fd->var_object_idx, vd->var_name,\n                                  FALSE, FALSE, JS_VAR_NORMAL);\n            dbuf_putc(bc, OP_get_var_ref);\n            dbuf_put_u16(bc, idx);\n            var_object_test(ctx, s, var_name, op, bc, &label_done, 0);\n        }\n\n        /* check eval object in argument scope */\n        if (fd->arg_var_object_idx >= 0 && !is_pseudo_var) {\n            vd = &fd->vars[fd->arg_var_object_idx];\n            vd->is_captured = 1;\n            idx = get_closure_var(ctx, s, fd, FALSE,\n                                  fd->arg_var_object_idx, vd->var_name,\n                                  FALSE, FALSE, JS_VAR_NORMAL);\n            dbuf_putc(bc, OP_get_var_ref);\n            dbuf_put_u16(bc, idx);\n            var_object_test(ctx, s, var_name, op, bc, &label_done, 0);\n        }\n        \n        if (fd->is_eval)\n            break; /* it it necessarily the top level function */\n    }\n\n    /* check direct eval scope (in the closure of the eval function\n       which is necessarily at the top level) */\n    if (!fd)\n        fd = s;\n    if (var_idx < 0 && fd->is_eval) {\n        int idx1;\n        for (idx1 = 0; idx1 < fd->closure_var_count; idx1++) {\n            JSClosureVar *cv = &fd->closure_var[idx1];\n            if (var_name == cv->var_name) {\n                if (fd != s) {\n                    idx = get_closure_var2(ctx, s, fd,\n                                           FALSE,\n                                           cv->is_arg, idx1,\n                                           cv->var_name, cv->is_const,\n                                           cv->is_lexical, cv->var_kind);\n                } else {\n                    idx = idx1;\n                }\n                goto has_idx;\n            } else if ((cv->var_name == JS_ATOM__var_ ||\n                        cv->var_name == JS_ATOM__arg_var_ ||\n                        cv->var_name == JS_ATOM__with_) && !is_pseudo_var) {\n                int is_with = (cv->var_name == JS_ATOM__with_);\n                if (fd != s) {\n                    idx = get_closure_var2(ctx, s, fd,\n                                           FALSE,\n                                           cv->is_arg, idx1,\n                                           cv->var_name, FALSE, FALSE,\n                                           JS_VAR_NORMAL);\n                } else {\n                    idx = idx1;\n                }\n                dbuf_putc(bc, OP_get_var_ref);\n                dbuf_put_u16(bc, idx);\n                var_object_test(ctx, s, var_name, op, bc, &label_done, is_with);\n            }\n        }\n    }\n\n    if (var_idx >= 0) {\n        /* find the corresponding closure variable */\n        if (var_idx & ARGUMENT_VAR_OFFSET) {\n            fd->args[var_idx - ARGUMENT_VAR_OFFSET].is_captured = 1;\n            idx = get_closure_var(ctx, s, fd,\n                                  TRUE, var_idx - ARGUMENT_VAR_OFFSET,\n                                  var_name, FALSE, FALSE, JS_VAR_NORMAL);\n        } else {\n            fd->vars[var_idx].is_captured = 1;\n            idx = get_closure_var(ctx, s, fd,\n                                  FALSE, var_idx,\n                                  var_name,\n                                  fd->vars[var_idx].is_const,\n                                  fd->vars[var_idx].is_lexical,\n                                  fd->vars[var_idx].var_kind);\n        }\n        if (idx >= 0) {\n        has_idx:\n            if ((op == OP_scope_put_var || op == OP_scope_make_ref) &&\n                s->closure_var[idx].is_const) {\n                dbuf_putc(bc, OP_throw_error);\n                dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                dbuf_putc(bc, JS_THROW_VAR_RO);\n                goto done;\n            }\n            switch (op) {\n            case OP_scope_make_ref:\n                if (s->closure_var[idx].var_kind == JS_VAR_FUNCTION_NAME) {\n                    /* Create a dummy object reference for the func_var */\n                    dbuf_putc(bc, OP_object);\n                    dbuf_putc(bc, OP_get_var_ref);\n                    dbuf_put_u16(bc, idx);\n                    dbuf_putc(bc, OP_define_field);\n                    dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                    dbuf_putc(bc, OP_push_atom_value);\n                    dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                } else\n                if (label_done == -1 &&\n                    can_opt_put_ref_value(bc_buf, ls->pos)) {\n                    int get_op;\n                    if (s->closure_var[idx].is_lexical)\n                        get_op = OP_get_var_ref_check;\n                    else\n                        get_op = OP_get_var_ref;\n                    pos_next = optimize_scope_make_ref(ctx, s, bc, bc_buf, ls,\n                                                       pos_next,\n                                                       get_op, idx);\n                } else {\n                    /* Create a dummy object with a named slot that is\n                       a reference to the closure variable */\n                    dbuf_putc(bc, OP_make_var_ref_ref);\n                    dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                    dbuf_put_u16(bc, idx);\n                }\n                break;\n            case OP_scope_get_ref:\n                /* XXX: should create a dummy object with a named slot that is\n                   a reference to the closure variable */\n                dbuf_putc(bc, OP_undefined);\n                /* fall thru */\n            case OP_scope_get_var_undef:\n            case OP_scope_get_var:\n            case OP_scope_put_var:\n            case OP_scope_put_var_init:\n                is_put = (op == OP_scope_put_var ||\n                          op == OP_scope_put_var_init);\n                if (is_put) {\n                    if (s->closure_var[idx].is_lexical) {\n                        if (op == OP_scope_put_var_init) {\n                            /* 'this' can only be initialized once */\n                            if (var_name == JS_ATOM_this)\n                                dbuf_putc(bc, OP_put_var_ref_check_init);\n                            else\n                                dbuf_putc(bc, OP_put_var_ref);\n                        } else {\n                            dbuf_putc(bc, OP_put_var_ref_check);\n                        }\n                    } else {\n                        dbuf_putc(bc, OP_put_var_ref);\n                    }\n                } else {\n                    if (s->closure_var[idx].is_lexical) {\n                        dbuf_putc(bc, OP_get_var_ref_check);\n                    } else {\n                        dbuf_putc(bc, OP_get_var_ref);\n                    }\n                }\n                dbuf_put_u16(bc, idx);\n                break;\n            case OP_scope_delete_var:\n                dbuf_putc(bc, OP_push_false);\n                break;\n            }\n            goto done;\n        }\n    }\n\n    /* global variable access */\n\n    switch (op) {\n    case OP_scope_make_ref:\n        if (label_done == -1 && can_opt_put_global_ref_value(bc_buf, ls->pos)) {\n            pos_next = optimize_scope_make_global_ref(ctx, s, bc, bc_buf, ls,\n                                                      pos_next, var_name);\n        } else {\n            dbuf_putc(bc, OP_make_var_ref);\n            dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n        }\n        break;\n    case OP_scope_get_ref:\n        /* XXX: should create a dummy object with a named slot that is\n           a reference to the global variable */\n        dbuf_putc(bc, OP_undefined);\n        dbuf_putc(bc, OP_get_var);\n        dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n        break;\n    case OP_scope_get_var_undef:\n    case OP_scope_get_var:\n    case OP_scope_put_var:\n        dbuf_putc(bc, OP_get_var_undef + (op - OP_scope_get_var_undef));\n        dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n        break;\n    case OP_scope_put_var_init:\n        dbuf_putc(bc, OP_put_var_init);\n        dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n        break;\n    case OP_scope_delete_var:\n        dbuf_putc(bc, OP_delete_var);\n        dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n        break;\n    }\ndone:\n    if (label_done >= 0) {\n        dbuf_putc(bc, OP_label);\n        dbuf_put_u32(bc, label_done);\n        s->label_slots[label_done].pos2 = bc->size;\n    }\n    return pos_next;\n}\n\n/* search in all scopes */\nstatic int find_private_class_field_all(JSContext *ctx, JSFunctionDef *fd,\n                                        JSAtom name, int scope_level)\n{\n    int idx;\n\n    idx = fd->scopes[scope_level].first;\n    while (idx >= 0) {\n        if (fd->vars[idx].var_name == name)\n            return idx;\n        idx = fd->vars[idx].scope_next;\n    }\n    return -1;\n}\n\nstatic void get_loc_or_ref(DynBuf *bc, BOOL is_ref, int idx)\n{\n    /* if the field is not initialized, the error is catched when\n       accessing it */\n    if (is_ref) \n        dbuf_putc(bc, OP_get_var_ref);\n    else\n        dbuf_putc(bc, OP_get_loc);\n    dbuf_put_u16(bc, idx);\n}\n\nstatic int resolve_scope_private_field1(JSContext *ctx,\n                                        BOOL *pis_ref, int *pvar_kind,\n                                        JSFunctionDef *s,\n                                        JSAtom var_name, int scope_level)\n{\n    int idx, var_kind;\n    JSFunctionDef *fd;\n    BOOL is_ref;\n    \n    fd = s;\n    is_ref = FALSE;\n    for(;;) {\n        idx = find_private_class_field_all(ctx, fd, var_name, scope_level);\n        if (idx >= 0) {\n            var_kind = fd->vars[idx].var_kind;\n            if (is_ref) {\n                idx = get_closure_var(ctx, s, fd, FALSE, idx, var_name,\n                                      TRUE, TRUE, JS_VAR_NORMAL);\n                if (idx < 0)\n                    return -1;\n            }\n            break;\n        }\n        scope_level = fd->parent_scope_level;\n        if (!fd->parent) {\n            if (fd->is_eval) {\n                /* closure of the eval function (top level) */\n                for (idx = 0; idx < fd->closure_var_count; idx++) {\n                    JSClosureVar *cv = &fd->closure_var[idx];\n                    if (cv->var_name == var_name) {\n                        var_kind = cv->var_kind;\n                        is_ref = TRUE;\n                        if (fd != s) {\n                            idx = get_closure_var2(ctx, s, fd,\n                                                   FALSE,\n                                                   cv->is_arg, idx,\n                                                   cv->var_name, cv->is_const,\n                                                   cv->is_lexical,\n                                                   cv->var_kind);\n                            if (idx < 0)\n                                return -1;\n                        }\n                        goto done;\n                    }\n                }\n            }\n            /* XXX: no line number info */\n            JS_ThrowSyntaxErrorAtom(ctx, \"undefined private field '%s'\",\n                                    var_name);\n            return -1;\n        } else {\n            fd = fd->parent;\n        }\n        is_ref = TRUE;\n    }\n done:\n    *pis_ref = is_ref;\n    *pvar_kind = var_kind;\n    return idx;\n}\n\n/* return 0 if OK or -1 if the private field could not be resolved */\nstatic int resolve_scope_private_field(JSContext *ctx, JSFunctionDef *s,\n                                       JSAtom var_name, int scope_level, int op,\n                                       DynBuf *bc)\n{\n    int idx, var_kind;\n    BOOL is_ref;\n\n    idx = resolve_scope_private_field1(ctx, &is_ref, &var_kind, s,\n                                       var_name, scope_level);\n    if (idx < 0)\n        return -1;\n    assert(var_kind != JS_VAR_NORMAL);\n    switch (op) {\n    case OP_scope_get_private_field:\n    case OP_scope_get_private_field2:\n        switch(var_kind) {\n        case JS_VAR_PRIVATE_FIELD:\n            if (op == OP_scope_get_private_field2)\n                dbuf_putc(bc, OP_dup);\n            get_loc_or_ref(bc, is_ref, idx);\n            dbuf_putc(bc, OP_get_private_field);\n            break;\n        case JS_VAR_PRIVATE_METHOD:\n            get_loc_or_ref(bc, is_ref, idx);\n            dbuf_putc(bc, OP_check_brand);\n            if (op != OP_scope_get_private_field2)\n                dbuf_putc(bc, OP_nip);\n            break;\n        case JS_VAR_PRIVATE_GETTER:\n        case JS_VAR_PRIVATE_GETTER_SETTER:\n            if (op == OP_scope_get_private_field2)\n                dbuf_putc(bc, OP_dup);\n            get_loc_or_ref(bc, is_ref, idx);\n            dbuf_putc(bc, OP_check_brand);\n            dbuf_putc(bc, OP_call_method);\n            dbuf_put_u16(bc, 0);\n            break;\n        case JS_VAR_PRIVATE_SETTER:\n            /* XXX: add clearer error message */\n            dbuf_putc(bc, OP_throw_error);\n            dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n            dbuf_putc(bc, JS_THROW_VAR_RO);\n            break;\n        default:\n            abort();\n        }\n        break;\n    case OP_scope_put_private_field:\n        switch(var_kind) {\n        case JS_VAR_PRIVATE_FIELD:\n            get_loc_or_ref(bc, is_ref, idx);\n            dbuf_putc(bc, OP_put_private_field);\n            break;\n        case JS_VAR_PRIVATE_METHOD:\n        case JS_VAR_PRIVATE_GETTER:\n            /* XXX: add clearer error message */\n            dbuf_putc(bc, OP_throw_error);\n            dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n            dbuf_putc(bc, JS_THROW_VAR_RO);\n            break;\n        case JS_VAR_PRIVATE_SETTER:\n        case JS_VAR_PRIVATE_GETTER_SETTER:\n            {\n                JSAtom setter_name = get_private_setter_name(ctx, var_name);\n                if (setter_name == JS_ATOM_NULL)\n                    return -1;\n                idx = resolve_scope_private_field1(ctx, &is_ref,\n                                                   &var_kind, s,\n                                                   setter_name, scope_level);\n                JS_FreeAtom(ctx, setter_name);\n                if (idx < 0)\n                    return -1;\n                assert(var_kind == JS_VAR_PRIVATE_SETTER);\n                get_loc_or_ref(bc, is_ref, idx);\n                dbuf_putc(bc, OP_swap);\n                /* obj func value */\n                dbuf_putc(bc, OP_rot3r);\n                /* value obj func */\n                dbuf_putc(bc, OP_check_brand);\n                dbuf_putc(bc, OP_rot3l);\n                /* obj func value */\n                dbuf_putc(bc, OP_call_method);\n                dbuf_put_u16(bc, 1);\n            }\n            break;\n        default:\n            abort();\n        }\n        break;\n    default:\n        abort();\n    }\n    return 0;\n}\n\nstatic void mark_eval_captured_variables(JSContext *ctx, JSFunctionDef *s,\n                                         int scope_level)\n{\n    int idx;\n    JSVarDef *vd;\n\n    for (idx = s->scopes[scope_level].first; idx >= 0;) {\n        vd = &s->vars[idx];\n        vd->is_captured = 1;\n        idx = vd->scope_next;\n    }\n}\n\n/* XXX: should handle the argument scope generically */\nstatic BOOL is_var_in_arg_scope(const JSVarDef *vd)\n{\n    return (vd->var_name == JS_ATOM_home_object ||\n            vd->var_name == JS_ATOM_this_active_func ||\n            vd->var_name == JS_ATOM_new_target ||\n            vd->var_name == JS_ATOM_this ||\n            vd->var_name == JS_ATOM__arg_var_ ||\n            vd->var_kind == JS_VAR_FUNCTION_NAME);\n}\n\nstatic void add_eval_variables(JSContext *ctx, JSFunctionDef *s)\n{\n    JSFunctionDef *fd;\n    JSVarDef *vd;\n    int i, scope_level, scope_idx;\n    BOOL has_arguments_binding, has_this_binding, is_arg_scope;\n\n    /* in non strict mode, variables are created in the caller's\n       environment object */\n    if (!s->is_eval && !(s->js_mode & JS_MODE_STRICT)) {\n        s->var_object_idx = add_var(ctx, s, JS_ATOM__var_);\n        if (s->has_parameter_expressions) {\n            /* an additional variable object is needed for the\n               argument scope */\n            s->arg_var_object_idx = add_var(ctx, s, JS_ATOM__arg_var_);\n        }\n    }\n\n    /* eval can potentially use 'arguments' so we must define it */\n    has_this_binding = s->has_this_binding;\n    if (has_this_binding) {\n        if (s->this_var_idx < 0)\n            s->this_var_idx = add_var_this(ctx, s);\n        if (s->new_target_var_idx < 0)\n            s->new_target_var_idx = add_var(ctx, s, JS_ATOM_new_target);\n        if (s->is_derived_class_constructor && s->this_active_func_var_idx < 0)\n            s->this_active_func_var_idx = add_var(ctx, s, JS_ATOM_this_active_func);\n        if (s->has_home_object && s->home_object_var_idx < 0)\n            s->home_object_var_idx = add_var(ctx, s, JS_ATOM_home_object);\n    }\n    has_arguments_binding = s->has_arguments_binding;\n    if (has_arguments_binding) {\n        add_arguments_var(ctx, s);\n        /* also add an arguments binding in the argument scope to\n           raise an error if a direct eval in the argument scope tries\n           to redefine it */\n        if (s->has_parameter_expressions && !(s->js_mode & JS_MODE_STRICT))\n            add_arguments_arg(ctx, s);\n    }\n    if (s->is_func_expr && s->func_name != JS_ATOM_NULL)\n        add_func_var(ctx, s, s->func_name);\n\n    /* eval can use all the variables of the enclosing functions, so\n       they must be all put in the closure. The closure variables are\n       ordered by scope. It works only because no closure are created\n       before. */\n    assert(s->is_eval || s->closure_var_count == 0);\n\n    /* XXX: inefficient, but eval performance is less critical */\n    fd = s;\n    for(;;) {\n        scope_level = fd->parent_scope_level;\n        fd = fd->parent;\n        if (!fd)\n            break;\n        /* add 'this' if it was not previously added */\n        if (!has_this_binding && fd->has_this_binding) {\n            if (fd->this_var_idx < 0)\n                fd->this_var_idx = add_var_this(ctx, fd);\n            if (fd->new_target_var_idx < 0)\n                fd->new_target_var_idx = add_var(ctx, fd, JS_ATOM_new_target);\n            if (fd->is_derived_class_constructor && fd->this_active_func_var_idx < 0)\n                fd->this_active_func_var_idx = add_var(ctx, fd, JS_ATOM_this_active_func);\n            if (fd->has_home_object && fd->home_object_var_idx < 0)\n                fd->home_object_var_idx = add_var(ctx, fd, JS_ATOM_home_object);\n            has_this_binding = TRUE;\n        }\n        /* add 'arguments' if it was not previously added */\n        if (!has_arguments_binding && fd->has_arguments_binding) {\n            add_arguments_var(ctx, fd);\n            has_arguments_binding = TRUE;\n        }\n        /* add function name */\n        if (fd->is_func_expr && fd->func_name != JS_ATOM_NULL)\n            add_func_var(ctx, fd, fd->func_name);\n\n        /* add lexical variables */\n        scope_idx = fd->scopes[scope_level].first;\n        while (scope_idx >= 0) {\n            vd = &fd->vars[scope_idx];\n            vd->is_captured = 1;\n            get_closure_var(ctx, s, fd, FALSE, scope_idx,\n                            vd->var_name, vd->is_const, vd->is_lexical, vd->var_kind);\n            scope_idx = vd->scope_next;\n        }\n        is_arg_scope = (scope_idx == ARG_SCOPE_END);\n        if (!is_arg_scope) {\n            /* add unscoped variables */\n            for(i = 0; i < fd->arg_count; i++) {\n                vd = &fd->args[i];\n                if (vd->var_name != JS_ATOM_NULL) {\n                    get_closure_var(ctx, s, fd,\n                                    TRUE, i, vd->var_name, FALSE, FALSE,\n                                    JS_VAR_NORMAL);\n                }\n            }\n            for(i = 0; i < fd->var_count; i++) {\n                vd = &fd->vars[i];\n                /* do not close top level last result */\n                if (vd->scope_level == 0 &&\n                    vd->var_name != JS_ATOM__ret_ &&\n                    vd->var_name != JS_ATOM_NULL) {\n                    get_closure_var(ctx, s, fd,\n                                    FALSE, i, vd->var_name, FALSE, FALSE,\n                                    JS_VAR_NORMAL);\n                }\n            }\n        } else {\n            for(i = 0; i < fd->var_count; i++) {\n                vd = &fd->vars[i];\n                /* do not close top level last result */\n                if (vd->scope_level == 0 && is_var_in_arg_scope(vd)) {\n                    get_closure_var(ctx, s, fd,\n                                    FALSE, i, vd->var_name, FALSE, FALSE,\n                                    JS_VAR_NORMAL);\n                }\n            }\n        }\n        if (fd->is_eval) {\n            int idx;\n            /* add direct eval variables (we are necessarily at the\n               top level) */\n            for (idx = 0; idx < fd->closure_var_count; idx++) {\n                JSClosureVar *cv = &fd->closure_var[idx];\n                get_closure_var2(ctx, s, fd,\n                                 FALSE, cv->is_arg,\n                                 idx, cv->var_name, cv->is_const,\n                                 cv->is_lexical, cv->var_kind);\n            }\n        }\n    }\n}\n\nstatic void set_closure_from_var(JSContext *ctx, JSClosureVar *cv,\n                                 JSVarDef *vd, int var_idx)\n{\n    cv->is_local = TRUE;\n    cv->is_arg = FALSE;\n    cv->is_const = vd->is_const;\n    cv->is_lexical = vd->is_lexical;\n    cv->var_kind = vd->var_kind;\n    cv->var_idx = var_idx;\n    cv->var_name = JS_DupAtom(ctx, vd->var_name);\n}\n\n/* for direct eval compilation: add references to the variables of the\n   calling function */\nstatic __exception int add_closure_variables(JSContext *ctx, JSFunctionDef *s,\n                                             JSFunctionBytecode *b, int scope_idx)\n{\n    int i, count;\n    JSVarDef *vd;\n    BOOL is_arg_scope;\n    \n    count = b->arg_count + b->var_count + b->closure_var_count;\n    s->closure_var = NULL;\n    s->closure_var_count = 0;\n    s->closure_var_size = count;\n    if (count == 0)\n        return 0;\n    s->closure_var = js_malloc(ctx, sizeof(s->closure_var[0]) * count);\n    if (!s->closure_var)\n        return -1;\n    /* Add lexical variables in scope at the point of evaluation */\n    for (i = scope_idx; i >= 0;) {\n        vd = &b->vardefs[b->arg_count + i];\n        if (vd->scope_level > 0) {\n            JSClosureVar *cv = &s->closure_var[s->closure_var_count++];\n            set_closure_from_var(ctx, cv, vd, i);\n        }\n        i = vd->scope_next;\n    }\n    is_arg_scope = (i == ARG_SCOPE_END);\n    if (!is_arg_scope) {\n        /* Add argument variables */\n        for(i = 0; i < b->arg_count; i++) {\n            JSClosureVar *cv = &s->closure_var[s->closure_var_count++];\n            vd = &b->vardefs[i];\n            cv->is_local = TRUE;\n            cv->is_arg = TRUE;\n            cv->is_const = FALSE;\n            cv->is_lexical = FALSE;\n            cv->var_kind = JS_VAR_NORMAL;\n            cv->var_idx = i;\n            cv->var_name = JS_DupAtom(ctx, vd->var_name);\n        }\n        /* Add local non lexical variables */\n        for(i = 0; i < b->var_count; i++) {\n            vd = &b->vardefs[b->arg_count + i];\n            if (vd->scope_level == 0 && vd->var_name != JS_ATOM__ret_) {\n                JSClosureVar *cv = &s->closure_var[s->closure_var_count++];\n                set_closure_from_var(ctx, cv, vd, i);\n            }\n        }\n    } else {\n        /* only add pseudo variables */\n        for(i = 0; i < b->var_count; i++) {\n            vd = &b->vardefs[b->arg_count + i];\n            if (vd->scope_level == 0 && is_var_in_arg_scope(vd)) {\n                JSClosureVar *cv = &s->closure_var[s->closure_var_count++];\n                set_closure_from_var(ctx, cv, vd, i);\n            }\n        }\n    }\n    for(i = 0; i < b->closure_var_count; i++) {\n        JSClosureVar *cv0 = &b->closure_var[i];\n        JSClosureVar *cv = &s->closure_var[s->closure_var_count++];\n        cv->is_local = FALSE;\n        cv->is_arg = cv0->is_arg;\n        cv->is_const = cv0->is_const;\n        cv->is_lexical = cv0->is_lexical;\n        cv->var_kind = cv0->var_kind;\n        cv->var_idx = i;\n        cv->var_name = JS_DupAtom(ctx, cv0->var_name);\n    }\n    return 0;\n}\n\ntypedef struct CodeContext {\n    const uint8_t *bc_buf; /* code buffer */\n    int bc_len;   /* length of the code buffer */\n    int pos;      /* position past the matched code pattern */\n    int line_num; /* last visited OP_line_num parameter or -1 */\n    int op;\n    int idx;\n    int label;\n    int val;\n    JSAtom atom;\n} CodeContext;\n\n#define M2(op1, op2)            ((op1) | ((op2) << 8))\n#define M3(op1, op2, op3)       ((op1) | ((op2) << 8) | ((op3) << 16))\n#define M4(op1, op2, op3, op4)  ((op1) | ((op2) << 8) | ((op3) << 16) | ((op4) << 24))\n\nstatic BOOL code_match(CodeContext *s, int pos, ...)\n{\n    const uint8_t *tab = s->bc_buf;\n    int op, len, op1, line_num, pos_next;\n    va_list ap;\n    BOOL ret = FALSE;\n\n    line_num = -1;\n    va_start(ap, pos);\n\n    for(;;) {\n        op1 = va_arg(ap, int);\n        if (op1 == -1) {\n            s->pos = pos;\n            s->line_num = line_num;\n            ret = TRUE;\n            break;\n        }\n        for (;;) {\n            if (pos >= s->bc_len)\n                goto done;\n            op = tab[pos];\n            len = opcode_info[op].size;\n            pos_next = pos + len;\n            if (pos_next > s->bc_len)\n                goto done;\n            if (op == OP_line_num) {\n                line_num = get_u32(tab + pos + 1);\n                pos = pos_next;\n            } else {\n                break;\n            }\n        }\n        if (op != op1) {\n            if (op1 == (uint8_t)op1 || !op)\n                break;\n            if (op != (uint8_t)op1\n            &&  op != (uint8_t)(op1 >> 8)\n            &&  op != (uint8_t)(op1 >> 16)\n            &&  op != (uint8_t)(op1 >> 24)) {\n                break;\n            }\n            s->op = op;\n        }\n\n        pos++;\n        switch(opcode_info[op].fmt) {\n        case OP_FMT_loc8:\n        case OP_FMT_u8:\n            {\n                int idx = tab[pos];\n                int arg = va_arg(ap, int);\n                if (arg == -1) {\n                    s->idx = idx;\n                } else {\n                    if (arg != idx)\n                        goto done;\n                }\n                break;\n            }\n        case OP_FMT_u16:\n        case OP_FMT_npop:\n        case OP_FMT_loc:\n        case OP_FMT_arg:\n        case OP_FMT_var_ref:\n            {\n                int idx = get_u16(tab + pos);\n                int arg = va_arg(ap, int);\n                if (arg == -1) {\n                    s->idx = idx;\n                } else {\n                    if (arg != idx)\n                        goto done;\n                }\n                break;\n            }\n        case OP_FMT_i32:\n        case OP_FMT_u32:\n        case OP_FMT_label:\n        case OP_FMT_const:\n            {\n                s->label = get_u32(tab + pos);\n                break;\n            }\n        case OP_FMT_label_u16:\n            {\n                s->label = get_u32(tab + pos);\n                s->val = get_u16(tab + pos + 4);\n                break;\n            }\n        case OP_FMT_atom:\n            {\n                s->atom = get_u32(tab + pos);\n                break;\n            }\n        case OP_FMT_atom_u8:\n            {\n                s->atom = get_u32(tab + pos);\n                s->val = get_u8(tab + pos + 4);\n                break;\n            }\n        case OP_FMT_atom_u16:\n            {\n                s->atom = get_u32(tab + pos);\n                s->val = get_u16(tab + pos + 4);\n                break;\n            }\n        case OP_FMT_atom_label_u8:\n            {\n                s->atom = get_u32(tab + pos);\n                s->label = get_u32(tab + pos + 4);\n                s->val = get_u8(tab + pos + 8);\n                break;\n            }\n        default:\n            break;\n        }\n        pos = pos_next;\n    }\n done:\n    va_end(ap);\n    return ret;\n}\n\nstatic void instantiate_hoisted_definitions(JSContext *ctx, JSFunctionDef *s, DynBuf *bc)\n{\n    int i, idx, label_next = -1;\n\n    /* add the hoisted functions in arguments and local variables */\n    for(i = 0; i < s->arg_count; i++) {\n        JSVarDef *vd = &s->args[i];\n        if (vd->func_pool_idx >= 0) {\n            dbuf_putc(bc, OP_fclosure);\n            dbuf_put_u32(bc, vd->func_pool_idx);\n            dbuf_putc(bc, OP_put_arg);\n            dbuf_put_u16(bc, i);\n        }\n    }\n    for(i = 0; i < s->var_count; i++) {\n        JSVarDef *vd = &s->vars[i];\n        if (vd->scope_level == 0 && vd->func_pool_idx >= 0) {\n            dbuf_putc(bc, OP_fclosure);\n            dbuf_put_u32(bc, vd->func_pool_idx);\n            dbuf_putc(bc, OP_put_loc);\n            dbuf_put_u16(bc, i);\n        }\n    }\n\n    /* the module global variables must be initialized before\n       evaluating the module so that the exported functions are\n       visible if there are cyclic module references */\n    if (s->module) {\n        label_next = new_label_fd(s, -1);\n        \n        /* if 'this' is true, initialize the global variables and return */\n        dbuf_putc(bc, OP_push_this);\n        dbuf_putc(bc, OP_if_false);\n        dbuf_put_u32(bc, label_next);\n        update_label(s, label_next, 1);\n        s->jump_size++;\n    }\n    \n    /* add the global variables (only happens if s->is_global_var is\n       true) */\n    for(i = 0; i < s->global_var_count; i++) {\n        JSGlobalVar *hf = &s->global_vars[i];\n        int has_closure = 0;\n        BOOL force_init = hf->force_init;\n        /* we are in an eval, so the closure contains all the\n           enclosing variables */\n        /* If the outer function has a variable environment,\n           create a property for the variable there */\n        for(idx = 0; idx < s->closure_var_count; idx++) {\n            JSClosureVar *cv = &s->closure_var[idx];\n            if (cv->var_name == hf->var_name) {\n                has_closure = 2;\n                force_init = FALSE;\n                break;\n            }\n            if (cv->var_name == JS_ATOM__var_ ||\n                cv->var_name == JS_ATOM__arg_var_) {\n                dbuf_putc(bc, OP_get_var_ref);\n                dbuf_put_u16(bc, idx);\n                has_closure = 1;\n                force_init = TRUE;\n                break;\n            }\n        }\n        if (!has_closure) {\n            int flags;\n            \n            flags = 0;\n            if (s->eval_type != JS_EVAL_TYPE_GLOBAL)\n                flags |= JS_PROP_CONFIGURABLE;\n            if (hf->cpool_idx >= 0 && !hf->is_lexical) {\n                /* global function definitions need a specific handling */\n                dbuf_putc(bc, OP_fclosure);\n                dbuf_put_u32(bc, hf->cpool_idx);\n                \n                dbuf_putc(bc, OP_define_func);\n                dbuf_put_u32(bc, JS_DupAtom(ctx, hf->var_name));\n                dbuf_putc(bc, flags);\n                \n                goto done_global_var;\n            } else {\n                if (hf->is_lexical) {\n                    flags |= DEFINE_GLOBAL_LEX_VAR;\n                    if (!hf->is_const)\n                        flags |= JS_PROP_WRITABLE;\n                }\n                dbuf_putc(bc, OP_define_var);\n                dbuf_put_u32(bc, JS_DupAtom(ctx, hf->var_name));\n                dbuf_putc(bc, flags);\n            }\n        }\n        if (hf->cpool_idx >= 0 || force_init) {\n            if (hf->cpool_idx >= 0) {\n                dbuf_putc(bc, OP_fclosure);\n                dbuf_put_u32(bc, hf->cpool_idx);\n                if (hf->var_name == JS_ATOM__default_) {\n                    /* set default export function name */\n                    dbuf_putc(bc, OP_set_name);\n                    dbuf_put_u32(bc, JS_DupAtom(ctx, JS_ATOM_default));\n                }\n            } else {\n                dbuf_putc(bc, OP_undefined);\n            }\n            if (has_closure == 2) {\n                dbuf_putc(bc, OP_put_var_ref);\n                dbuf_put_u16(bc, idx);\n            } else if (has_closure == 1) {\n                dbuf_putc(bc, OP_define_field);\n                dbuf_put_u32(bc, JS_DupAtom(ctx, hf->var_name));\n                dbuf_putc(bc, OP_drop);\n            } else {\n                /* XXX: Check if variable is writable and enumerable */\n                dbuf_putc(bc, OP_put_var);\n                dbuf_put_u32(bc, JS_DupAtom(ctx, hf->var_name));\n            }\n        }\n    done_global_var:\n        JS_FreeAtom(ctx, hf->var_name);\n    }\n\n    if (s->module) {\n        dbuf_putc(bc, OP_return_undef);\n        \n        dbuf_putc(bc, OP_label);\n        dbuf_put_u32(bc, label_next);\n        s->label_slots[label_next].pos2 = bc->size;\n    }\n\n    js_free(ctx, s->global_vars);\n    s->global_vars = NULL;\n    s->global_var_count = 0;\n    s->global_var_size = 0;\n}\n\nstatic int skip_dead_code(JSFunctionDef *s, const uint8_t *bc_buf, int bc_len,\n                          int pos, int *linep)\n{\n    int op, len, label;\n\n    for (; pos < bc_len; pos += len) {\n        op = bc_buf[pos];\n        len = opcode_info[op].size;\n        if (op == OP_line_num) {\n            *linep = get_u32(bc_buf + pos + 1);\n        } else\n        if (op == OP_label) {\n            label = get_u32(bc_buf + pos + 1);\n            if (update_label(s, label, 0) > 0)\n                break;\n#if 0\n            if (s->label_slots[label].first_reloc) {\n                printf(\"line %d: unreferenced label %d:%d has relocations\\n\",\n                       *linep, label, s->label_slots[label].pos2);\n            }\n#endif\n            assert(s->label_slots[label].first_reloc == NULL);\n        } else {\n            /* XXX: output a warning for unreachable code? */\n            JSAtom atom;\n            switch(opcode_info[op].fmt) {\n            case OP_FMT_label:\n            case OP_FMT_label_u16:\n                label = get_u32(bc_buf + pos + 1);\n                update_label(s, label, -1);\n                break;\n            case OP_FMT_atom_label_u8:\n            case OP_FMT_atom_label_u16:\n                label = get_u32(bc_buf + pos + 5);\n                update_label(s, label, -1);\n                /* fall thru */\n            case OP_FMT_atom:\n            case OP_FMT_atom_u8:\n            case OP_FMT_atom_u16:\n                atom = get_u32(bc_buf + pos + 1);\n                JS_FreeAtom(s->ctx, atom);\n                break;\n            default:\n                break;\n            }\n        }\n    }\n    return pos;\n}\n\nstatic int get_label_pos(JSFunctionDef *s, int label)\n{\n    int i, pos;\n    for (i = 0; i < 20; i++) {\n        pos = s->label_slots[label].pos;\n        for (;;) {\n            switch (s->byte_code.buf[pos]) {\n            case OP_line_num:\n            case OP_label:\n                pos += 5;\n                continue;\n            case OP_goto:\n                label = get_u32(s->byte_code.buf + pos + 1);\n                break;\n            default:\n                return pos;\n            }\n            break;\n        }\n    }\n    return pos;\n}\n\n/* convert global variable accesses to local variables or closure\n   variables when necessary */\nstatic __exception int resolve_variables(JSContext *ctx, JSFunctionDef *s)\n{\n    int pos, pos_next, bc_len, op, len, i, idx, line_num;\n    uint8_t *bc_buf;\n    JSAtom var_name;\n    DynBuf bc_out;\n    CodeContext cc;\n    int scope;\n\n    cc.bc_buf = bc_buf = s->byte_code.buf;\n    cc.bc_len = bc_len = s->byte_code.size;\n    js_dbuf_init(ctx, &bc_out);\n\n    /* first pass for runtime checks (must be done before the\n       variables are created) */\n    for(i = 0; i < s->global_var_count; i++) {\n        JSGlobalVar *hf = &s->global_vars[i];\n        int flags;\n        \n        /* check if global variable (XXX: simplify) */\n        for(idx = 0; idx < s->closure_var_count; idx++) {\n            JSClosureVar *cv = &s->closure_var[idx];\n            if (cv->var_name == hf->var_name) {\n                if (s->eval_type == JS_EVAL_TYPE_DIRECT &&\n                    cv->is_lexical) {\n                    /* Check if a lexical variable is\n                       redefined as 'var'. XXX: Could abort\n                       compilation here, but for consistency\n                       with the other checks, we delay the\n                       error generation. */\n                    dbuf_putc(&bc_out, OP_throw_error);\n                    dbuf_put_u32(&bc_out, JS_DupAtom(ctx, hf->var_name));\n                    dbuf_putc(&bc_out, JS_THROW_VAR_REDECL);\n                }\n                goto next;\n            }\n            if (cv->var_name == JS_ATOM__var_ ||\n                cv->var_name == JS_ATOM__arg_var_)\n                goto next;\n        }\n        \n        dbuf_putc(&bc_out, OP_check_define_var);\n        dbuf_put_u32(&bc_out, JS_DupAtom(ctx, hf->var_name));\n        flags = 0;\n        if (hf->is_lexical)\n            flags |= DEFINE_GLOBAL_LEX_VAR;\n        if (hf->cpool_idx >= 0)\n            flags |= DEFINE_GLOBAL_FUNC_VAR;\n        dbuf_putc(&bc_out, flags);\n    next: ;\n    }\n\n    line_num = 0; /* avoid warning */\n    for (pos = 0; pos < bc_len; pos = pos_next) {\n        op = bc_buf[pos];\n        len = opcode_info[op].size;\n        pos_next = pos + len;\n        switch(op) {\n        case OP_line_num:\n            line_num = get_u32(bc_buf + pos + 1);\n            s->line_number_size++;\n            goto no_change;\n\n        case OP_eval: /* convert scope index to adjusted variable index */\n            {\n                int call_argc = get_u16(bc_buf + pos + 1);\n                scope = get_u16(bc_buf + pos + 1 + 2);\n                mark_eval_captured_variables(ctx, s, scope);\n                dbuf_putc(&bc_out, op);\n                dbuf_put_u16(&bc_out, call_argc);\n                dbuf_put_u16(&bc_out, s->scopes[scope].first + 1);\n            }\n            break;\n        case OP_apply_eval: /* convert scope index to adjusted variable index */\n            scope = get_u16(bc_buf + pos + 1);\n            mark_eval_captured_variables(ctx, s, scope);\n            dbuf_putc(&bc_out, op);\n            dbuf_put_u16(&bc_out, s->scopes[scope].first + 1);\n            break;\n        case OP_scope_get_var_undef:\n        case OP_scope_get_var:\n        case OP_scope_put_var:\n        case OP_scope_delete_var:\n        case OP_scope_get_ref:\n        case OP_scope_put_var_init:\n            var_name = get_u32(bc_buf + pos + 1);\n            scope = get_u16(bc_buf + pos + 5);\n            pos_next = resolve_scope_var(ctx, s, var_name, scope, op, &bc_out,\n                                         NULL, NULL, pos_next);\n            JS_FreeAtom(ctx, var_name);\n            break;\n        case OP_scope_make_ref:\n            {\n                int label;\n                LabelSlot *ls;\n                var_name = get_u32(bc_buf + pos + 1);\n                label = get_u32(bc_buf + pos + 5);\n                scope = get_u16(bc_buf + pos + 9);\n                ls = &s->label_slots[label];\n                ls->ref_count--;  /* always remove label reference */\n                pos_next = resolve_scope_var(ctx, s, var_name, scope, op, &bc_out,\n                                             bc_buf, ls, pos_next);\n                JS_FreeAtom(ctx, var_name);\n            }\n            break;\n        case OP_scope_get_private_field:\n        case OP_scope_get_private_field2:\n        case OP_scope_put_private_field:\n            {\n                int ret;\n                var_name = get_u32(bc_buf + pos + 1);\n                scope = get_u16(bc_buf + pos + 5);\n                ret = resolve_scope_private_field(ctx, s, var_name, scope, op, &bc_out);\n                if (ret < 0)\n                    goto fail;\n                JS_FreeAtom(ctx, var_name);\n            }\n            break;\n        case OP_gosub:\n            s->jump_size++;\n            if (OPTIMIZE) {\n                /* remove calls to empty finalizers  */\n                int label;\n                LabelSlot *ls;\n\n                label = get_u32(bc_buf + pos + 1);\n                assert(label >= 0 && label < s->label_count);\n                ls = &s->label_slots[label];\n                if (code_match(&cc, ls->pos, OP_ret, -1)) {\n                    ls->ref_count--;\n                    break;\n                }\n            }\n            goto no_change;\n        case OP_drop:\n            if (0) {\n                /* remove drops before return_undef */\n                /* do not perform this optimization in pass2 because\n                   it breaks patterns recognised in resolve_labels */\n                int pos1 = pos_next;\n                int line1 = line_num;\n                while (code_match(&cc, pos1, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line1 = cc.line_num;\n                    pos1 = cc.pos;\n                }\n                if (code_match(&cc, pos1, OP_return_undef, -1)) {\n                    pos_next = pos1;\n                    if (line1 != -1 && line1 != line_num) {\n                        line_num = line1;\n                        s->line_number_size++;\n                        dbuf_putc(&bc_out, OP_line_num);\n                        dbuf_put_u32(&bc_out, line_num);\n                    }\n                    break;\n                }\n            }\n            goto no_change;\n        case OP_insert3:\n            if (OPTIMIZE) {\n                /* Transformation: insert3 put_array_el|put_ref_value drop -> put_array_el|put_ref_value */\n                if (code_match(&cc, pos_next, M2(OP_put_array_el, OP_put_ref_value), OP_drop, -1)) {\n                    dbuf_putc(&bc_out, cc.op);\n                    pos_next = cc.pos;\n                    if (cc.line_num != -1 && cc.line_num != line_num) {\n                        line_num = cc.line_num;\n                        s->line_number_size++;\n                        dbuf_putc(&bc_out, OP_line_num);\n                        dbuf_put_u32(&bc_out, line_num);\n                    }\n                    break;\n                }\n            }\n            goto no_change;\n\n        case OP_goto:\n            s->jump_size++;\n            /* fall thru */\n        case OP_tail_call:\n        case OP_tail_call_method:\n        case OP_return:\n        case OP_return_undef:\n        case OP_throw:\n        case OP_throw_error:\n        case OP_ret:\n            if (OPTIMIZE) {\n                /* remove dead code */\n                int line = -1;\n                dbuf_put(&bc_out, bc_buf + pos, len);\n                pos = skip_dead_code(s, bc_buf, bc_len, pos + len, &line);\n                pos_next = pos;\n                if (pos < bc_len && line >= 0 && line_num != line) {\n                    line_num = line;\n                    s->line_number_size++;\n                    dbuf_putc(&bc_out, OP_line_num);\n                    dbuf_put_u32(&bc_out, line_num);\n                }\n                break;\n            }\n            goto no_change;\n\n        case OP_label:\n            {\n                int label;\n                LabelSlot *ls;\n\n                label = get_u32(bc_buf + pos + 1);\n                assert(label >= 0 && label < s->label_count);\n                ls = &s->label_slots[label];\n                ls->pos2 = bc_out.size + opcode_info[op].size;\n            }\n            goto no_change;\n\n        case OP_enter_scope:\n            {\n                int scope_idx, scope = get_u16(bc_buf + pos + 1);\n\n                if (scope == s->body_scope) {\n                    instantiate_hoisted_definitions(ctx, s, &bc_out);\n                }\n\n                for(scope_idx = s->scopes[scope].first; scope_idx >= 0;) {\n                    JSVarDef *vd = &s->vars[scope_idx];\n                    if (vd->scope_level == scope) {\n                        if (scope_idx != s->arguments_arg_idx) {\n                            if (vd->var_kind == JS_VAR_FUNCTION_DECL ||\n                                vd->var_kind == JS_VAR_NEW_FUNCTION_DECL) {\n                                /* Initialize lexical variable upon entering scope */\n                                dbuf_putc(&bc_out, OP_fclosure);\n                                dbuf_put_u32(&bc_out, vd->func_pool_idx);\n                                dbuf_putc(&bc_out, OP_put_loc);\n                                dbuf_put_u16(&bc_out, scope_idx);\n                            } else {\n                                /* XXX: should check if variable can be used\n                                   before initialization */\n                                dbuf_putc(&bc_out, OP_set_loc_uninitialized);\n                                dbuf_put_u16(&bc_out, scope_idx);\n                            }\n                        }\n                        scope_idx = vd->scope_next;\n                    } else {\n                        break;\n                    }\n                }\n            }\n            break;\n\n        case OP_leave_scope:\n            {\n                int scope_idx, scope = get_u16(bc_buf + pos + 1);\n\n                for(scope_idx = s->scopes[scope].first; scope_idx >= 0;) {\n                    JSVarDef *vd = &s->vars[scope_idx];\n                    if (vd->scope_level == scope) {\n                        if (vd->is_captured) {\n                            dbuf_putc(&bc_out, OP_close_loc);\n                            dbuf_put_u16(&bc_out, scope_idx);\n                        }\n                        scope_idx = vd->scope_next;\n                    } else {\n                        break;\n                    }\n                }\n            }\n            break;\n\n        case OP_set_name:\n            {\n                /* remove dummy set_name opcodes */\n                JSAtom name = get_u32(bc_buf + pos + 1);\n                if (name == JS_ATOM_NULL)\n                    break;\n            }\n            goto no_change;\n\n        case OP_if_false:\n        case OP_if_true:\n        case OP_catch:\n            s->jump_size++;\n            goto no_change;\n\n        case OP_dup:\n            if (OPTIMIZE) {\n                /* Transformation: dup if_false(l1) drop, l1: if_false(l2) -> if_false(l2) */\n                /* Transformation: dup if_true(l1) drop, l1: if_true(l2) -> if_true(l2) */\n                if (code_match(&cc, pos_next, M2(OP_if_false, OP_if_true), OP_drop, -1)) {\n                    int lab0, lab1, op1, pos1, line1, pos2;\n                    lab0 = lab1 = cc.label;\n                    assert(lab1 >= 0 && lab1 < s->label_count);\n                    op1 = cc.op;\n                    pos1 = cc.pos;\n                    line1 = cc.line_num;\n                    while (code_match(&cc, (pos2 = get_label_pos(s, lab1)), OP_dup, op1, OP_drop, -1)) {\n                        lab1 = cc.label;\n                    }\n                    if (code_match(&cc, pos2, op1, -1)) {\n                        s->jump_size++;\n                        update_label(s, lab0, -1);\n                        update_label(s, cc.label, +1);\n                        dbuf_putc(&bc_out, op1);\n                        dbuf_put_u32(&bc_out, cc.label);\n                        pos_next = pos1;\n                        if (line1 != -1 && line1 != line_num) {\n                            line_num = line1;\n                            s->line_number_size++;\n                            dbuf_putc(&bc_out, OP_line_num);\n                            dbuf_put_u32(&bc_out, line_num);\n                        }\n                        break;\n                    }\n                }\n            }\n            goto no_change;\n\n        case OP_nop:\n            /* remove erased code */\n            break;\n        case OP_set_class_name:\n            /* only used during parsing */\n            break;\n            \n        default:\n        no_change:\n            dbuf_put(&bc_out, bc_buf + pos, len);\n            break;\n        }\n    }\n\n    /* set the new byte code */\n    dbuf_free(&s->byte_code);\n    s->byte_code = bc_out;\n    if (dbuf_error(&s->byte_code)) {\n        JS_ThrowOutOfMemory(ctx);\n        return -1;\n    }\n    return 0;\n fail:\n    /* continue the copy to keep the atom refcounts consistent */\n    /* XXX: find a better solution ? */\n    for (; pos < bc_len; pos = pos_next) {\n        op = bc_buf[pos];\n        len = opcode_info[op].size;\n        pos_next = pos + len;\n        dbuf_put(&bc_out, bc_buf + pos, len);\n    }\n    dbuf_free(&s->byte_code);\n    s->byte_code = bc_out;\n    return -1;\n}\n\n/* the pc2line table gives a line number for each PC value */\nstatic void add_pc2line_info(JSFunctionDef *s, uint32_t pc, int line_num)\n{\n    if (s->line_number_slots != NULL\n    &&  s->line_number_count < s->line_number_size\n    &&  pc >= s->line_number_last_pc\n    &&  line_num != s->line_number_last) {\n        s->line_number_slots[s->line_number_count].pc = pc;\n        s->line_number_slots[s->line_number_count].line_num = line_num;\n        s->line_number_count++;\n        s->line_number_last_pc = pc;\n        s->line_number_last = line_num;\n    }\n}\n\nstatic void compute_pc2line_info(JSFunctionDef *s)\n{\n    if (!(s->js_mode & JS_MODE_STRIP) && s->line_number_slots) {\n        int last_line_num = s->line_num;\n        uint32_t last_pc = 0;\n        int i;\n\n        js_dbuf_init(s->ctx, &s->pc2line);\n        for (i = 0; i < s->line_number_count; i++) {\n            uint32_t pc = s->line_number_slots[i].pc;\n            int line_num = s->line_number_slots[i].line_num;\n            int diff_pc, diff_line;\n\n            if (line_num < 0)\n                continue;\n\n            diff_pc = pc - last_pc;\n            diff_line = line_num - last_line_num;\n            if (diff_line == 0 || diff_pc < 0)\n                continue;\n\n            if (diff_line >= PC2LINE_BASE &&\n                diff_line < PC2LINE_BASE + PC2LINE_RANGE &&\n                diff_pc <= PC2LINE_DIFF_PC_MAX) {\n                dbuf_putc(&s->pc2line, (diff_line - PC2LINE_BASE) +\n                          diff_pc * PC2LINE_RANGE + PC2LINE_OP_FIRST);\n            } else {\n                /* longer encoding */\n                dbuf_putc(&s->pc2line, 0);\n                dbuf_put_leb128(&s->pc2line, diff_pc);\n                dbuf_put_sleb128(&s->pc2line, diff_line);\n            }\n            last_pc = pc;\n            last_line_num = line_num;\n        }\n    }\n}\n\nstatic RelocEntry *add_reloc(JSContext *ctx, LabelSlot *ls, uint32_t addr, int size)\n{\n    RelocEntry *re;\n    re = js_malloc(ctx, sizeof(*re));\n    if (!re)\n        return NULL;\n    re->addr = addr;\n    re->size = size;\n    re->next = ls->first_reloc;\n    ls->first_reloc = re;\n    return re;\n}\n\nstatic BOOL code_has_label(CodeContext *s, int pos, int label)\n{\n    while (pos < s->bc_len) {\n        int op = s->bc_buf[pos];\n        if (op == OP_line_num) {\n            pos += 5;\n            continue;\n        }\n        if (op == OP_label) {\n            int lab = get_u32(s->bc_buf + pos + 1);\n            if (lab == label)\n                return TRUE;\n            pos += 5;\n            continue;\n        }\n        if (op == OP_goto) {\n            int lab = get_u32(s->bc_buf + pos + 1);\n            if (lab == label)\n                return TRUE;\n        }\n        break;\n    }\n    return FALSE;\n}\n\n/* return the target label, following the OP_goto jumps\n   the first opcode at destination is stored in *pop\n */\nstatic int find_jump_target(JSFunctionDef *s, int label, int *pop, int *pline)\n{\n    int i, pos, op;\n\n    update_label(s, label, -1);\n    for (i = 0; i < 10; i++) {\n        assert(label >= 0 && label < s->label_count);\n        pos = s->label_slots[label].pos2;\n        for (;;) {\n            switch(op = s->byte_code.buf[pos]) {\n            case OP_line_num:\n                if (pline)\n                    *pline = get_u32(s->byte_code.buf + pos + 1);\n                /* fall thru */\n            case OP_label:\n                pos += opcode_info[op].size;\n                continue;\n            case OP_goto:\n                label = get_u32(s->byte_code.buf + pos + 1);\n                break;\n            case OP_drop:\n                /* ignore drop opcodes if followed by OP_return_undef */\n                while (s->byte_code.buf[++pos] == OP_drop)\n                    continue;\n                if (s->byte_code.buf[pos] == OP_return_undef)\n                    op = OP_return_undef;\n                /* fall thru */\n            default:\n                goto done;\n            }\n            break;\n        }\n    }\n    /* cycle detected, could issue a warning */\n done:\n    *pop = op;\n    update_label(s, label, +1);\n    return label;\n}\n\nstatic void push_short_int(DynBuf *bc_out, int val)\n{\n#if SHORT_OPCODES\n    if (val >= -1 && val <= 7) {\n        dbuf_putc(bc_out, OP_push_0 + val);\n        return;\n    }\n    if (val == (int8_t)val) {\n        dbuf_putc(bc_out, OP_push_i8);\n        dbuf_putc(bc_out, val);\n        return;\n    }\n    if (val == (int16_t)val) {\n        dbuf_putc(bc_out, OP_push_i16);\n        dbuf_put_u16(bc_out, val);\n        return;\n    }\n#endif\n    dbuf_putc(bc_out, OP_push_i32);\n    dbuf_put_u32(bc_out, val);\n}\n\nstatic void put_short_code(DynBuf *bc_out, int op, int idx)\n{\n#if SHORT_OPCODES\n    if (idx < 4) {\n        switch (op) {\n        case OP_get_loc:\n            dbuf_putc(bc_out, OP_get_loc0 + idx);\n            return;\n        case OP_put_loc:\n            dbuf_putc(bc_out, OP_put_loc0 + idx);\n            return;\n        case OP_set_loc:\n            dbuf_putc(bc_out, OP_set_loc0 + idx);\n            return;\n        case OP_get_arg:\n            dbuf_putc(bc_out, OP_get_arg0 + idx);\n            return;\n        case OP_put_arg:\n            dbuf_putc(bc_out, OP_put_arg0 + idx);\n            return;\n        case OP_set_arg:\n            dbuf_putc(bc_out, OP_set_arg0 + idx);\n            return;\n        case OP_get_var_ref:\n            dbuf_putc(bc_out, OP_get_var_ref0 + idx);\n            return;\n        case OP_put_var_ref:\n            dbuf_putc(bc_out, OP_put_var_ref0 + idx);\n            return;\n        case OP_set_var_ref:\n            dbuf_putc(bc_out, OP_set_var_ref0 + idx);\n            return;\n        case OP_call:\n            dbuf_putc(bc_out, OP_call0 + idx);\n            return;\n        }\n    }\n    if (idx < 256) {\n        switch (op) {\n        case OP_get_loc:\n            dbuf_putc(bc_out, OP_get_loc8);\n            dbuf_putc(bc_out, idx);\n            return;\n        case OP_put_loc:\n            dbuf_putc(bc_out, OP_put_loc8);\n            dbuf_putc(bc_out, idx);\n            return;\n        case OP_set_loc:\n            dbuf_putc(bc_out, OP_set_loc8);\n            dbuf_putc(bc_out, idx);\n            return;\n        }\n    }\n#endif\n    dbuf_putc(bc_out, op);\n    dbuf_put_u16(bc_out, idx);\n}\n\n/* peephole optimizations and resolve goto/labels */\nstatic __exception int resolve_labels(JSContext *ctx, JSFunctionDef *s)\n{\n    int pos, pos_next, bc_len, op, op1, len, i, line_num;\n    const uint8_t *bc_buf;\n    DynBuf bc_out;\n    LabelSlot *label_slots, *ls;\n    RelocEntry *re, *re_next;\n    CodeContext cc;\n    int label;\n#if SHORT_OPCODES\n    JumpSlot *jp;\n#endif\n\n    label_slots = s->label_slots;\n\n    line_num = s->line_num;\n\n    cc.bc_buf = bc_buf = s->byte_code.buf;\n    cc.bc_len = bc_len = s->byte_code.size;\n    js_dbuf_init(ctx, &bc_out);\n\n#if SHORT_OPCODES\n    if (s->jump_size) {\n        s->jump_slots = js_mallocz(s->ctx, sizeof(*s->jump_slots) * s->jump_size);\n        if (s->jump_slots == NULL)\n            return -1;\n    }\n#endif\n    /* XXX: Should skip this phase if not generating SHORT_OPCODES */\n    if (s->line_number_size && !(s->js_mode & JS_MODE_STRIP)) {\n        s->line_number_slots = js_mallocz(s->ctx, sizeof(*s->line_number_slots) * s->line_number_size);\n        if (s->line_number_slots == NULL)\n            return -1;\n        s->line_number_last = s->line_num;\n        s->line_number_last_pc = 0;\n    }\n\n    /* initialize the 'home_object' variable if needed */\n    if (s->home_object_var_idx >= 0) {\n        dbuf_putc(&bc_out, OP_special_object);\n        dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_HOME_OBJECT);\n        put_short_code(&bc_out, OP_put_loc, s->home_object_var_idx);\n    }\n    /* initialize the 'this.active_func' variable if needed */\n    if (s->this_active_func_var_idx >= 0) {\n        dbuf_putc(&bc_out, OP_special_object);\n        dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_THIS_FUNC);\n        put_short_code(&bc_out, OP_put_loc, s->this_active_func_var_idx);\n    }\n    /* initialize the 'new.target' variable if needed */\n    if (s->new_target_var_idx >= 0) {\n        dbuf_putc(&bc_out, OP_special_object);\n        dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_NEW_TARGET);\n        put_short_code(&bc_out, OP_put_loc, s->new_target_var_idx);\n    }\n    /* initialize the 'this' variable if needed. In a derived class\n       constructor, this is initially uninitialized. */\n    if (s->this_var_idx >= 0) {\n        if (s->is_derived_class_constructor) {\n            dbuf_putc(&bc_out, OP_set_loc_uninitialized);\n            dbuf_put_u16(&bc_out, s->this_var_idx);\n        } else {\n            dbuf_putc(&bc_out, OP_push_this);\n            put_short_code(&bc_out, OP_put_loc, s->this_var_idx);\n        }\n    }\n    /* initialize the 'arguments' variable if needed */\n    if (s->arguments_var_idx >= 0) {\n        if ((s->js_mode & JS_MODE_STRICT) || !s->has_simple_parameter_list) {\n            dbuf_putc(&bc_out, OP_special_object);\n            dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_ARGUMENTS);\n        } else {\n            dbuf_putc(&bc_out, OP_special_object);\n            dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_MAPPED_ARGUMENTS);\n        }\n        if (s->arguments_arg_idx >= 0)\n            put_short_code(&bc_out, OP_set_loc, s->arguments_arg_idx);\n        put_short_code(&bc_out, OP_put_loc, s->arguments_var_idx);\n    }\n    /* initialize a reference to the current function if needed */\n    if (s->func_var_idx >= 0) {\n        dbuf_putc(&bc_out, OP_special_object);\n        dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_THIS_FUNC);\n        put_short_code(&bc_out, OP_put_loc, s->func_var_idx);\n    }\n    /* initialize the variable environment object if needed */\n    if (s->var_object_idx >= 0) {\n        dbuf_putc(&bc_out, OP_special_object);\n        dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_VAR_OBJECT);\n        put_short_code(&bc_out, OP_put_loc, s->var_object_idx);\n    }\n    if (s->arg_var_object_idx >= 0) {\n        dbuf_putc(&bc_out, OP_special_object);\n        dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_VAR_OBJECT);\n        put_short_code(&bc_out, OP_put_loc, s->arg_var_object_idx);\n    }\n\n    for (pos = 0; pos < bc_len; pos = pos_next) {\n        int val;\n        op = bc_buf[pos];\n        len = opcode_info[op].size;\n        pos_next = pos + len;\n        switch(op) {\n        case OP_line_num:\n            /* line number info (for debug). We put it in a separate\n               compressed table to reduce memory usage and get better\n               performance */\n            line_num = get_u32(bc_buf + pos + 1);\n            break;\n\n        case OP_label:\n            {\n                label = get_u32(bc_buf + pos + 1);\n                assert(label >= 0 && label < s->label_count);\n                ls = &label_slots[label];\n                assert(ls->addr == -1);\n                ls->addr = bc_out.size;\n                /* resolve the relocation entries */\n                for(re = ls->first_reloc; re != NULL; re = re_next) {\n                    int diff = ls->addr - re->addr;\n                    re_next = re->next;\n                    switch (re->size) {\n                    case 4:\n                        put_u32(bc_out.buf + re->addr, diff);\n                        break;\n                    case 2:\n                        assert(diff == (int16_t)diff);\n                        put_u16(bc_out.buf + re->addr, diff);\n                        break;\n                    case 1:\n                        assert(diff == (int8_t)diff);\n                        put_u8(bc_out.buf + re->addr, diff);\n                        break;\n                    }\n                    js_free(ctx, re);\n                }\n                ls->first_reloc = NULL;\n            }\n            break;\n\n        case OP_call:\n        case OP_call_method:\n            {\n                /* detect and transform tail calls */\n                int argc;\n                argc = get_u16(bc_buf + pos + 1);\n                if (code_match(&cc, pos_next, OP_return, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    put_short_code(&bc_out, op + 1, argc);\n                    pos_next = skip_dead_code(s, bc_buf, bc_len, cc.pos, &line_num);\n                    break;\n                }\n                add_pc2line_info(s, bc_out.size, line_num);\n                put_short_code(&bc_out, op, argc);\n                break;\n            }\n            goto no_change;\n\n        case OP_return:\n        case OP_return_undef:\n        case OP_return_async:\n        case OP_throw:\n        case OP_throw_error:\n            pos_next = skip_dead_code(s, bc_buf, bc_len, pos_next, &line_num);\n            goto no_change;\n\n        case OP_goto:\n            label = get_u32(bc_buf + pos + 1);\n        has_goto:\n            if (OPTIMIZE) {\n                int line1 = -1;\n                /* Use custom matcher because multiple labels can follow */\n                label = find_jump_target(s, label, &op1, &line1);\n                if (code_has_label(&cc, pos_next, label)) {\n                    /* jump to next instruction: remove jump */\n                    update_label(s, label, -1);\n                    break;\n                }\n                if (op1 == OP_return || op1 == OP_return_undef || op1 == OP_throw) {\n                    /* jump to return/throw: remove jump, append return/throw */\n                    /* updating the line number obfuscates assembly listing */\n                    //if (line1 >= 0) line_num = line1;\n                    update_label(s, label, -1);\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, op1);\n                    pos_next = skip_dead_code(s, bc_buf, bc_len, pos_next, &line_num);\n                    break;\n                }\n                /* XXX: should duplicate single instructions followed by goto or return */\n                /* For example, can match one of these followed by return:\n                   push_i32 / push_const / push_atom_value / get_var /\n                   undefined / null / push_false / push_true / get_ref_value /\n                   get_loc / get_arg / get_var_ref\n                 */\n            }\n            goto has_label;\n\n        case OP_gosub:\n            label = get_u32(bc_buf + pos + 1);\n            if (0 && OPTIMIZE) {\n                label = find_jump_target(s, label, &op1, NULL);\n                if (op1 == OP_ret) {\n                    update_label(s, label, -1);\n                    /* empty finally clause: remove gosub */\n                    break;\n                }\n            }\n            goto has_label;\n\n        case OP_catch:\n            label = get_u32(bc_buf + pos + 1);\n            goto has_label;\n\n        case OP_if_true:\n        case OP_if_false:\n            label = get_u32(bc_buf + pos + 1);\n            if (OPTIMIZE) {\n                label = find_jump_target(s, label, &op1, NULL);\n                /* transform if_false/if_true(l1) label(l1) -> drop label(l1) */\n                if (code_has_label(&cc, pos_next, label)) {\n                    update_label(s, label, -1);\n                    dbuf_putc(&bc_out, OP_drop);\n                    break;\n                }\n                /* transform if_false(l1) goto(l2) label(l1) -> if_false(l2) label(l1) */\n                if (code_match(&cc, pos_next, OP_goto, -1)) {\n                    int pos1 = cc.pos;\n                    int line1 = cc.line_num;\n                    if (code_has_label(&cc, pos1, label)) {\n                        if (line1 >= 0) line_num = line1;\n                        pos_next = pos1;\n                        update_label(s, label, -1);\n                        label = cc.label;\n                        op ^= OP_if_true ^ OP_if_false;\n                    }\n                }\n            }\n        has_label:\n            add_pc2line_info(s, bc_out.size, line_num);\n            if (op == OP_goto) {\n                pos_next = skip_dead_code(s, bc_buf, bc_len, pos_next, &line_num);\n            }\n            assert(label >= 0 && label < s->label_count);\n            ls = &label_slots[label];\n#if SHORT_OPCODES\n            jp = &s->jump_slots[s->jump_count++];\n            jp->op = op;\n            jp->size = 4;\n            jp->pos = bc_out.size + 1;\n            jp->label = label;\n\n            if (ls->addr == -1) {\n                int diff = ls->pos2 - pos - 1;\n                if (diff < 128 && (op == OP_if_false || op == OP_if_true || op == OP_goto)) {\n                    jp->size = 1;\n                    jp->op = OP_if_false8 + (op - OP_if_false);\n                    dbuf_putc(&bc_out, OP_if_false8 + (op - OP_if_false));\n                    dbuf_putc(&bc_out, 0);\n                    if (!add_reloc(ctx, ls, bc_out.size - 1, 1))\n                        goto fail;\n                    break;\n                }\n                if (diff < 32768 && op == OP_goto) {\n                    jp->size = 2;\n                    jp->op = OP_goto16;\n                    dbuf_putc(&bc_out, OP_goto16);\n                    dbuf_put_u16(&bc_out, 0);\n                    if (!add_reloc(ctx, ls, bc_out.size - 2, 2))\n                        goto fail;\n                    break;\n                }\n            } else {\n                int diff = ls->addr - bc_out.size - 1;\n                if (diff == (int8_t)diff && (op == OP_if_false || op == OP_if_true || op == OP_goto)) {\n                    jp->size = 1;\n                    jp->op = OP_if_false8 + (op - OP_if_false);\n                    dbuf_putc(&bc_out, OP_if_false8 + (op - OP_if_false));\n                    dbuf_putc(&bc_out, diff);\n                    break;\n                }\n                if (diff == (int16_t)diff && op == OP_goto) {\n                    jp->size = 2;\n                    jp->op = OP_goto16;\n                    dbuf_putc(&bc_out, OP_goto16);\n                    dbuf_put_u16(&bc_out, diff);\n                    break;\n                }\n            }\n#endif\n            dbuf_putc(&bc_out, op);\n            dbuf_put_u32(&bc_out, ls->addr - bc_out.size);\n            if (ls->addr == -1) {\n                /* unresolved yet: create a new relocation entry */\n                if (!add_reloc(ctx, ls, bc_out.size - 4, 4))\n                    goto fail;\n            }\n            break;\n        case OP_with_get_var:\n        case OP_with_put_var:\n        case OP_with_delete_var:\n        case OP_with_make_ref:\n        case OP_with_get_ref:\n        case OP_with_get_ref_undef:\n            {\n                JSAtom atom;\n                int is_with;\n\n                atom = get_u32(bc_buf + pos + 1);\n                label = get_u32(bc_buf + pos + 5);\n                is_with = bc_buf[pos + 9];\n                if (OPTIMIZE) {\n                    label = find_jump_target(s, label, &op1, NULL);\n                }\n                assert(label >= 0 && label < s->label_count);\n                ls = &label_slots[label];\n                add_pc2line_info(s, bc_out.size, line_num);\n#if SHORT_OPCODES\n                jp = &s->jump_slots[s->jump_count++];\n                jp->op = op;\n                jp->size = 4;\n                jp->pos = bc_out.size + 5;\n                jp->label = label;\n#endif\n                dbuf_putc(&bc_out, op);\n                dbuf_put_u32(&bc_out, atom);\n                dbuf_put_u32(&bc_out, ls->addr - bc_out.size);\n                if (ls->addr == -1) {\n                    /* unresolved yet: create a new relocation entry */\n                    if (!add_reloc(ctx, ls, bc_out.size - 4, 4))\n                        goto fail;\n                }\n                dbuf_putc(&bc_out, is_with);\n            }\n            break;\n\n        case OP_drop:\n            if (OPTIMIZE) {\n                /* remove useless drops before return */\n                if (code_match(&cc, pos_next, OP_return_undef, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    break;\n                }\n            }\n            goto no_change;\n\n        case OP_null:\n#if SHORT_OPCODES\n            if (OPTIMIZE) {\n                /* transform null strict_eq into is_null */\n                if (code_match(&cc, pos_next, OP_strict_eq, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_is_null);\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* transform null strict_neq if_false/if_true -> is_null if_true/if_false */\n                if (code_match(&cc, pos_next, OP_strict_neq, M2(OP_if_false, OP_if_true), -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_is_null);\n                    pos_next = cc.pos;\n                    label = cc.label;\n                    op = cc.op ^ OP_if_false ^ OP_if_true;\n                    goto has_label;\n                }\n            }\n#endif\n            /* fall thru */\n        case OP_push_false:\n        case OP_push_true:\n            if (OPTIMIZE) {\n                val = (op == OP_push_true);\n                if (code_match(&cc, pos_next, M2(OP_if_false, OP_if_true), -1)) {\n                has_constant_test:\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    if (val == cc.op - OP_if_false) {\n                        /* transform null if_false(l1) -> goto l1 */\n                        /* transform false if_false(l1) -> goto l1 */\n                        /* transform true if_true(l1) -> goto l1 */\n                        pos_next = cc.pos;\n                        op = OP_goto;\n                        label = cc.label;\n                        goto has_goto;\n                    } else {\n                        /* transform null if_true(l1) -> nop */\n                        /* transform false if_true(l1) -> nop */\n                        /* transform true if_false(l1) -> nop */\n                        pos_next = cc.pos;\n                        update_label(s, cc.label, -1);\n                        break;\n                    }\n                }\n            }\n            goto no_change;\n\n        case OP_push_i32:\n            if (OPTIMIZE) {\n                /* transform i32(val) neg -> i32(-val) */\n                val = get_i32(bc_buf + pos + 1);\n                if ((val != INT32_MIN && val != 0)\n                &&  code_match(&cc, pos_next, OP_neg, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    if (code_match(&cc, cc.pos, OP_drop, -1)) {\n                        if (cc.line_num >= 0) line_num = cc.line_num;\n                    } else {\n                        add_pc2line_info(s, bc_out.size, line_num);\n                        push_short_int(&bc_out, -val);\n                    }\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* remove push/drop pairs generated by the parser */\n                if (code_match(&cc, pos_next, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* Optimize constant tests: `if (0)`, `if (1)`, `if (!0)`... */\n                if (code_match(&cc, pos_next, M2(OP_if_false, OP_if_true), -1)) {\n                    val = (val != 0);\n                    goto has_constant_test;\n                }\n                add_pc2line_info(s, bc_out.size, line_num);\n                push_short_int(&bc_out, val);\n                break;\n            }\n            goto no_change;\n\n#if SHORT_OPCODES\n        case OP_push_const:\n        case OP_fclosure:\n            if (OPTIMIZE) {\n                int idx = get_u32(bc_buf + pos + 1);\n                if (idx < 256) {\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_push_const8 + op - OP_push_const);\n                    dbuf_putc(&bc_out, idx);\n                    break;\n                }\n            }\n            goto no_change;\n\n        case OP_get_field:\n            if (OPTIMIZE) {\n                JSAtom atom = get_u32(bc_buf + pos + 1);\n                if (atom == JS_ATOM_length) {\n                    JS_FreeAtom(ctx, atom);\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_get_length);\n                    break;\n                }\n            }\n            goto no_change;\n#endif\n        case OP_push_atom_value:\n            if (OPTIMIZE) {\n                JSAtom atom = get_u32(bc_buf + pos + 1);\n                /* remove push/drop pairs generated by the parser */\n                if (code_match(&cc, pos_next, OP_drop, -1)) {\n                    JS_FreeAtom(ctx, atom);\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    pos_next = cc.pos;\n                    break;\n                }\n#if SHORT_OPCODES\n                if (atom == JS_ATOM_empty_string) {\n                    JS_FreeAtom(ctx, atom);\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_push_empty_string);\n                    break;\n                }\n#endif\n            }\n            goto no_change;\n\n        case OP_to_propkey:\n        case OP_to_propkey2:\n            if (OPTIMIZE) {\n                /* remove redundant to_propkey/to_propkey2 opcodes when storing simple data */\n                if (code_match(&cc, pos_next, M3(OP_get_loc, OP_get_arg, OP_get_var_ref), -1, OP_put_array_el, -1)\n                ||  code_match(&cc, pos_next, M3(OP_push_i32, OP_push_const, OP_push_atom_value), OP_put_array_el, -1)\n                ||  code_match(&cc, pos_next, M4(OP_undefined, OP_null, OP_push_true, OP_push_false), OP_put_array_el, -1)) {\n                    break;\n                }\n            }\n            goto no_change;\n\n        case OP_undefined:\n            if (OPTIMIZE) {\n                /* remove push/drop pairs generated by the parser */\n                if (code_match(&cc, pos_next, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* transform undefined return -> return_undefined */\n                if (code_match(&cc, pos_next, OP_return, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_return_undef);\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* transform undefined if_true(l1)/if_false(l1) -> nop/goto(l1) */\n                if (code_match(&cc, pos_next, M2(OP_if_false, OP_if_true), -1)) {\n                    val = 0;\n                    goto has_constant_test;\n                }\n#if SHORT_OPCODES\n                /* transform undefined strict_eq -> is_undefined */\n                if (code_match(&cc, pos_next, OP_strict_eq, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_is_undefined);\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* transform undefined strict_neq if_false/if_true -> is_undefined if_true/if_false */\n                if (code_match(&cc, pos_next, OP_strict_neq, M2(OP_if_false, OP_if_true), -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_is_undefined);\n                    pos_next = cc.pos;\n                    label = cc.label;\n                    op = cc.op ^ OP_if_false ^ OP_if_true;\n                    goto has_label;\n                }\n#endif\n            }\n            goto no_change;\n\n        case OP_insert2:\n            if (OPTIMIZE) {\n                /* Transformation:\n                   insert2 put_field(a) drop -> put_field(a)\n                   insert2 put_var_strict(a) drop -> put_var_strict(a)\n                */\n                if (code_match(&cc, pos_next, M2(OP_put_field, OP_put_var_strict), OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, cc.op);\n                    dbuf_put_u32(&bc_out, cc.atom);\n                    pos_next = cc.pos;\n                    break;\n                }\n            }\n            goto no_change;\n\n        case OP_dup:\n            if (OPTIMIZE) {\n                /* Transformation: dup put_x(n) drop -> put_x(n) */\n                int op1, line2 = -1;\n                /* Transformation: dup put_x(n) -> set_x(n) */\n                if (code_match(&cc, pos_next, M3(OP_put_loc, OP_put_arg, OP_put_var_ref), -1, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    op1 = cc.op + 1;  /* put_x -> set_x */\n                    pos_next = cc.pos;\n                    if (code_match(&cc, cc.pos, OP_drop, -1)) {\n                        if (cc.line_num >= 0) line_num = cc.line_num;\n                        op1 -= 1; /* set_x drop -> put_x */\n                        pos_next = cc.pos;\n                        if (code_match(&cc, cc.pos, op1 - 1, cc.idx, -1)) {\n                            line2 = cc.line_num; /* delay line number update */\n                            op1 += 1;   /* put_x(n) get_x(n) -> set_x(n) */\n                            pos_next = cc.pos;\n                        }\n                    }\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    put_short_code(&bc_out, op1, cc.idx);\n                    if (line2 >= 0) line_num = line2;\n                    break;\n                }\n            }\n            goto no_change;\n\n        case OP_get_loc:\n            if (OPTIMIZE) {\n                /* transformation:\n                   get_loc(n) post_dec put_loc(n) drop -> dec_loc(n)\n                   get_loc(n) post_inc put_loc(n) drop -> inc_loc(n)\n                   get_loc(n) dec dup put_loc(n) drop -> dec_loc(n)\n                   get_loc(n) inc dup put_loc(n) drop -> inc_loc(n)\n                 */\n                int idx;\n                idx = get_u16(bc_buf + pos + 1);\n                if (idx >= 256)\n                    goto no_change;\n                if (code_match(&cc, pos_next, M2(OP_post_dec, OP_post_inc), OP_put_loc, idx, OP_drop, -1) ||\n                    code_match(&cc, pos_next, M2(OP_dec, OP_inc), OP_dup, OP_put_loc, idx, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, (cc.op == OP_inc || cc.op == OP_post_inc) ? OP_inc_loc : OP_dec_loc);\n                    dbuf_putc(&bc_out, idx);\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* transformation:\n                   get_loc(n) push_atom_value(x) add dup put_loc(n) drop -> push_atom_value(x) add_loc(n)\n                 */\n                if (code_match(&cc, pos_next, OP_push_atom_value, OP_add, OP_dup, OP_put_loc, idx, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n#if SHORT_OPCODES\n                    if (cc.atom == JS_ATOM_empty_string) {\n                        JS_FreeAtom(ctx, cc.atom);\n                        dbuf_putc(&bc_out, OP_push_empty_string);\n                    } else\n#endif\n                    {\n                        dbuf_putc(&bc_out, OP_push_atom_value);\n                        dbuf_put_u32(&bc_out, cc.atom);\n                    }\n                    dbuf_putc(&bc_out, OP_add_loc);\n                    dbuf_putc(&bc_out, idx);\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* transformation:\n                   get_loc(n) push_i32(x) add dup put_loc(n) drop -> push_i32(x) add_loc(n)\n                 */\n                if (code_match(&cc, pos_next, OP_push_i32, OP_add, OP_dup, OP_put_loc, idx, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    push_short_int(&bc_out, cc.label);\n                    dbuf_putc(&bc_out, OP_add_loc);\n                    dbuf_putc(&bc_out, idx);\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* transformation: XXX: also do these:\n                   get_loc(n) get_loc(x) add dup put_loc(n) drop -> get_loc(x) add_loc(n)\n                   get_loc(n) get_arg(x) add dup put_loc(n) drop -> get_arg(x) add_loc(n)\n                   get_loc(n) get_var_ref(x) add dup put_loc(n) drop -> get_var_ref(x) add_loc(n)\n                 */\n                if (code_match(&cc, pos_next, M3(OP_get_loc, OP_get_arg, OP_get_var_ref), -1, OP_add, OP_dup, OP_put_loc, idx, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    put_short_code(&bc_out, cc.op, cc.idx);\n                    dbuf_putc(&bc_out, OP_add_loc);\n                    dbuf_putc(&bc_out, idx);\n                    pos_next = cc.pos;\n                    break;\n                }\n                add_pc2line_info(s, bc_out.size, line_num);\n                put_short_code(&bc_out, op, idx);\n                break;\n            }\n            goto no_change;\n#if SHORT_OPCODES\n        case OP_get_arg:\n        case OP_get_var_ref:\n            if (OPTIMIZE) {\n                int idx;\n                idx = get_u16(bc_buf + pos + 1);\n                add_pc2line_info(s, bc_out.size, line_num);\n                put_short_code(&bc_out, op, idx);\n                break;\n            }\n            goto no_change;\n#endif\n        case OP_put_loc:\n        case OP_put_arg:\n        case OP_put_var_ref:\n            if (OPTIMIZE) {\n                /* transformation: put_x(n) get_x(n) -> set_x(n) */\n                int idx;\n                idx = get_u16(bc_buf + pos + 1);\n                if (code_match(&cc, pos_next, op - 1, idx, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    put_short_code(&bc_out, op + 1, idx);\n                    pos_next = cc.pos;\n                    break;\n                }\n                add_pc2line_info(s, bc_out.size, line_num);\n                put_short_code(&bc_out, op, idx);\n                break;\n            }\n            goto no_change;\n\n        case OP_post_inc:\n        case OP_post_dec:\n            if (OPTIMIZE) {\n                /* transformation:\n                   post_inc put_x drop -> inc put_x\n                   post_inc perm3 put_field drop -> inc put_field\n                   post_inc perm3 put_var_strict drop -> inc put_var_strict\n                   post_inc perm4 put_array_el drop -> inc put_array_el\n                 */\n                int op1, idx;\n                if (code_match(&cc, pos_next, M3(OP_put_loc, OP_put_arg, OP_put_var_ref), -1, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    op1 = cc.op;\n                    idx = cc.idx;\n                    pos_next = cc.pos;\n                    if (code_match(&cc, cc.pos, op1 - 1, idx, -1)) {\n                        if (cc.line_num >= 0) line_num = cc.line_num;\n                        op1 += 1;   /* put_x(n) get_x(n) -> set_x(n) */\n                        pos_next = cc.pos;\n                    }\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_dec + (op - OP_post_dec));\n                    put_short_code(&bc_out, op1, idx);\n                    break;\n                }\n                if (code_match(&cc, pos_next, OP_perm3, M2(OP_put_field, OP_put_var_strict), OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_dec + (op - OP_post_dec));\n                    dbuf_putc(&bc_out, cc.op);\n                    dbuf_put_u32(&bc_out, cc.atom);\n                    pos_next = cc.pos;\n                    break;\n                }\n                if (code_match(&cc, pos_next, OP_perm4, OP_put_array_el, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_dec + (op - OP_post_dec));\n                    dbuf_putc(&bc_out, OP_put_array_el);\n                    pos_next = cc.pos;\n                    break;\n                }\n            }\n            goto no_change;\n\n#if SHORT_OPCODES\n        case OP_typeof:\n            if (OPTIMIZE) {\n                /* simplify typeof tests */\n                if (code_match(&cc, pos_next, OP_push_atom_value, M4(OP_strict_eq, OP_strict_neq, OP_eq, OP_neq), -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    int op1 = (cc.op == OP_strict_eq || cc.op == OP_eq) ? OP_strict_eq : OP_strict_neq;\n                    int op2 = -1;\n                    switch (cc.atom) {\n                    case JS_ATOM_undefined:\n                        op2 = OP_typeof_is_undefined;\n                        break;\n                    case JS_ATOM_function:\n                        op2 = OP_typeof_is_function;\n                        break;\n                    }\n                    if (op2 >= 0) {\n                        /* transform typeof(s) == \"<type>\" into is_<type> */\n                        if (op1 == OP_strict_eq) {\n                            add_pc2line_info(s, bc_out.size, line_num);\n                            dbuf_putc(&bc_out, op2);\n                            JS_FreeAtom(ctx, cc.atom);\n                            pos_next = cc.pos;\n                            break;\n                        }\n                        if (op1 == OP_strict_neq && code_match(&cc, cc.pos, OP_if_false, -1)) {\n                            /* transform typeof(s) != \"<type>\" if_false into is_<type> if_true */\n                            if (cc.line_num >= 0) line_num = cc.line_num;\n                            add_pc2line_info(s, bc_out.size, line_num);\n                            dbuf_putc(&bc_out, op2);\n                            JS_FreeAtom(ctx, cc.atom);\n                            pos_next = cc.pos;\n                            label = cc.label;\n                            op = OP_if_true;\n                            goto has_label;\n                        }\n                    }\n                }\n            }\n            goto no_change;\n#endif\n\n        default:\n        no_change:\n            add_pc2line_info(s, bc_out.size, line_num);\n            dbuf_put(&bc_out, bc_buf + pos, len);\n            break;\n        }\n    }\n\n    /* check that there were no missing labels */\n    for(i = 0; i < s->label_count; i++) {\n        assert(label_slots[i].first_reloc == NULL);\n    }\n#if SHORT_OPCODES\n    if (OPTIMIZE) {\n        /* more jump optimizations */\n        int patch_offsets = 0;\n        for (i = 0, jp = s->jump_slots; i < s->jump_count; i++, jp++) {\n            LabelSlot *ls;\n            JumpSlot *jp1;\n            int j, pos, diff, delta;\n\n            delta = 3;\n            switch (op = jp->op) {\n            case OP_goto16:\n                delta = 1;\n                /* fall thru */\n            case OP_if_false:\n            case OP_if_true:\n            case OP_goto:\n                pos = jp->pos;\n                diff = s->label_slots[jp->label].addr - pos;\n                if (diff >= -128 && diff <= 127 + delta) {\n                    //put_u8(bc_out.buf + pos, diff);\n                    jp->size = 1;\n                    if (op == OP_goto16) {\n                        bc_out.buf[pos - 1] = jp->op = OP_goto8;\n                    } else {\n                        bc_out.buf[pos - 1] = jp->op = OP_if_false8 + (op - OP_if_false);\n                    }\n                    goto shrink;\n                } else\n                if (diff == (int16_t)diff && op == OP_goto) {\n                    //put_u16(bc_out.buf + pos, diff);\n                    jp->size = 2;\n                    delta = 2;\n                    bc_out.buf[pos - 1] = jp->op = OP_goto16;\n                shrink:\n                    /* XXX: should reduce complexity, using 2 finger copy scheme */\n                    memmove(bc_out.buf + pos + jp->size, bc_out.buf + pos + jp->size + delta,\n                            bc_out.size - pos - jp->size - delta);\n                    bc_out.size -= delta;\n                    patch_offsets++;\n                    for (j = 0, ls = s->label_slots; j < s->label_count; j++, ls++) {\n                        if (ls->addr > pos)\n                            ls->addr -= delta;\n                    }\n                    for (j = i + 1, jp1 = jp + 1; j < s->jump_count; j++, jp1++) {\n                        if (jp1->pos > pos)\n                            jp1->pos -= delta;\n                    }\n                    for (j = 0; j < s->line_number_count; j++) {\n                        if (s->line_number_slots[j].pc > pos)\n                            s->line_number_slots[j].pc -= delta;\n                    }\n                    continue;\n                }\n                break;\n            }\n        }\n        if (patch_offsets) {\n            JumpSlot *jp1;\n            int j;\n            for (j = 0, jp1 = s->jump_slots; j < s->jump_count; j++, jp1++) {\n                int diff1 = s->label_slots[jp1->label].addr - jp1->pos;\n                switch (jp1->size) {\n                case 1:\n                    put_u8(bc_out.buf + jp1->pos, diff1);\n                    break;\n                case 2:\n                    put_u16(bc_out.buf + jp1->pos, diff1);\n                    break;\n                case 4:\n                    put_u32(bc_out.buf + jp1->pos, diff1);\n                    break;\n                }\n            }\n        }\n    }\n    js_free(ctx, s->jump_slots);\n    s->jump_slots = NULL;\n#endif\n    js_free(ctx, s->label_slots);\n    s->label_slots = NULL;\n    /* XXX: should delay until copying to runtime bytecode function */\n    compute_pc2line_info(s);\n    js_free(ctx, s->line_number_slots);\n    s->line_number_slots = NULL;\n    /* set the new byte code */\n    dbuf_free(&s->byte_code);\n    s->byte_code = bc_out;\n    s->use_short_opcodes = TRUE;\n    if (dbuf_error(&s->byte_code)) {\n        JS_ThrowOutOfMemory(ctx);\n        return -1;\n    }\n    return 0;\n fail:\n    /* XXX: not safe */\n    dbuf_free(&bc_out);\n    return -1;\n}\n\n/* compute the maximum stack size needed by the function */\n\ntypedef struct StackSizeState {\n    int bc_len;\n    int stack_len_max;\n    uint16_t *stack_level_tab;\n    int *pc_stack;\n    int pc_stack_len;\n    int pc_stack_size;\n} StackSizeState;\n\n/* 'op' is only used for error indication */\nstatic __exception int ss_check(JSContext *ctx, StackSizeState *s,\n                                int pos, int op, int stack_len)\n{\n    if ((unsigned)pos >= s->bc_len) {\n        JS_ThrowInternalError(ctx, \"bytecode buffer overflow (op=%d, pc=%d)\", op, pos);\n        return -1;\n    }\n    if (stack_len > s->stack_len_max) {\n        s->stack_len_max = stack_len;\n        if (s->stack_len_max > JS_STACK_SIZE_MAX) {\n            JS_ThrowInternalError(ctx, \"stack overflow (op=%d, pc=%d)\", op, pos);\n            return -1;\n        }\n    }\n    if (s->stack_level_tab[pos] != 0xffff) {\n        /* already explored: check that the stack size is consistent */\n        if (s->stack_level_tab[pos] != stack_len) {\n            JS_ThrowInternalError(ctx, \"unconsistent stack size: %d %d (pc=%d)\",\n                                  s->stack_level_tab[pos], stack_len, pos);\n            return -1;\n        } else {\n            return 0;\n        }\n    }\n\n    /* mark as explored and store the stack size */\n    s->stack_level_tab[pos] = stack_len;\n\n    /* queue the new PC to explore */\n    if (js_resize_array(ctx, (void **)&s->pc_stack, sizeof(s->pc_stack[0]),\n                        &s->pc_stack_size, s->pc_stack_len + 1))\n        return -1;\n    s->pc_stack[s->pc_stack_len++] = pos;\n    return 0;\n}\n\nstatic __exception int compute_stack_size(JSContext *ctx,\n                                          JSFunctionDef *fd,\n                                          int *pstack_size)\n{\n    StackSizeState s_s, *s = &s_s;\n    int i, diff, n_pop, pos_next, stack_len, pos, op;\n    const JSOpCode *oi;\n    const uint8_t *bc_buf;\n\n    bc_buf = fd->byte_code.buf;\n    s->bc_len = fd->byte_code.size;\n    /* bc_len > 0 */\n    s->stack_level_tab = js_malloc(ctx, sizeof(s->stack_level_tab[0]) *\n                                   s->bc_len);\n    if (!s->stack_level_tab)\n        return -1;\n    for(i = 0; i < s->bc_len; i++)\n        s->stack_level_tab[i] = 0xffff;\n    s->stack_len_max = 0;\n    s->pc_stack = NULL;\n    s->pc_stack_len = 0;\n    s->pc_stack_size = 0;\n\n    /* breadth-first graph exploration */\n    if (ss_check(ctx, s, 0, OP_invalid, 0))\n        goto fail;\n\n    while (s->pc_stack_len > 0) {\n        pos = s->pc_stack[--s->pc_stack_len];\n        stack_len = s->stack_level_tab[pos];\n        op = bc_buf[pos];\n        if (op == 0 || op >= OP_COUNT) {\n            JS_ThrowInternalError(ctx, \"invalid opcode (op=%d, pc=%d)\", op, pos);\n            goto fail;\n        }\n        oi = &short_opcode_info(op);\n        pos_next = pos + oi->size;\n        if (pos_next > s->bc_len) {\n            JS_ThrowInternalError(ctx, \"bytecode buffer overflow (op=%d, pc=%d)\", op, pos);\n            goto fail;\n        }\n        n_pop = oi->n_pop;\n        /* call pops a variable number of arguments */\n        if (oi->fmt == OP_FMT_npop || oi->fmt == OP_FMT_npop_u16) {\n            n_pop += get_u16(bc_buf + pos + 1);\n        } else {\n#if SHORT_OPCODES\n            if (oi->fmt == OP_FMT_npopx) {\n                n_pop += op - OP_call0;\n            }\n#endif\n        }\n\n        if (stack_len < n_pop) {\n            JS_ThrowInternalError(ctx, \"stack underflow (op=%d, pc=%d)\", op, pos);\n            goto fail;\n        }\n        stack_len += oi->n_push - n_pop;\n        if (stack_len > s->stack_len_max) {\n            s->stack_len_max = stack_len;\n            if (s->stack_len_max > JS_STACK_SIZE_MAX) {\n                JS_ThrowInternalError(ctx, \"stack overflow (op=%d, pc=%d)\", op, pos);\n                goto fail;\n            }\n        }\n        switch(op) {\n        case OP_tail_call:\n        case OP_tail_call_method:\n        case OP_return:\n        case OP_return_undef:\n        case OP_return_async:\n        case OP_throw:\n        case OP_throw_error:\n        case OP_ret:\n            goto done_insn;\n        case OP_goto:\n            diff = get_u32(bc_buf + pos + 1);\n            pos_next = pos + 1 + diff;\n            break;\n#if SHORT_OPCODES\n        case OP_goto16:\n            diff = (int16_t)get_u16(bc_buf + pos + 1);\n            pos_next = pos + 1 + diff;\n            break;\n        case OP_goto8:\n            diff = (int8_t)bc_buf[pos + 1];\n            pos_next = pos + 1 + diff;\n            break;\n        case OP_if_true8:\n        case OP_if_false8:\n            diff = (int8_t)bc_buf[pos + 1];\n            if (ss_check(ctx, s, pos + 1 + diff, op, stack_len))\n                goto fail;\n            break;\n#endif\n        case OP_if_true:\n        case OP_if_false:\n        case OP_catch:\n            diff = get_u32(bc_buf + pos + 1);\n            if (ss_check(ctx, s, pos + 1 + diff, op, stack_len))\n                goto fail;\n            break;\n        case OP_gosub:\n            diff = get_u32(bc_buf + pos + 1);\n            if (ss_check(ctx, s, pos + 1 + diff, op, stack_len + 1))\n                goto fail;\n            break;\n        case OP_with_get_var:\n        case OP_with_delete_var:\n            diff = get_u32(bc_buf + pos + 5);\n            if (ss_check(ctx, s, pos + 5 + diff, op, stack_len + 1))\n                goto fail;\n            break;\n        case OP_with_make_ref:\n        case OP_with_get_ref:\n        case OP_with_get_ref_undef:\n            diff = get_u32(bc_buf + pos + 5);\n            if (ss_check(ctx, s, pos + 5 + diff, op, stack_len + 2))\n                goto fail;\n            break;\n        case OP_with_put_var:\n            diff = get_u32(bc_buf + pos + 5);\n            if (ss_check(ctx, s, pos + 5 + diff, op, stack_len - 1))\n                goto fail;\n            break;\n\n        default:\n            break;\n        }\n        if (ss_check(ctx, s, pos_next, op, stack_len))\n            goto fail;\n    done_insn: ;\n    }\n    js_free(ctx, s->stack_level_tab);\n    js_free(ctx, s->pc_stack);\n    *pstack_size = s->stack_len_max;\n    return 0;\n fail:\n    js_free(ctx, s->stack_level_tab);\n    js_free(ctx, s->pc_stack);\n    *pstack_size = 0;\n    return -1;\n}\n\nstatic int add_module_variables(JSContext *ctx, JSFunctionDef *fd)\n{\n    int i, idx;\n    JSModuleDef *m = fd->module;\n    JSExportEntry *me;\n    JSGlobalVar *hf;\n\n    /* The imported global variables were added as closure variables\n       in js_parse_import(). We add here the module global\n       variables. */\n\n    for(i = 0; i < fd->global_var_count; i++) {\n        hf = &fd->global_vars[i];\n        if (add_closure_var(ctx, fd, TRUE, FALSE, i, hf->var_name, hf->is_const,\n                            hf->is_lexical, FALSE) < 0)\n            return -1;\n    }\n\n    /* resolve the variable names of the local exports */\n    for(i = 0; i < m->export_entries_count; i++) {\n        me = &m->export_entries[i];\n        if (me->export_type == JS_EXPORT_TYPE_LOCAL) {\n            idx = find_closure_var(ctx, fd, me->local_name);\n            if (idx < 0) {\n                JS_ThrowSyntaxErrorAtom(ctx, \"exported variable '%s' does not exist\",\n                                        me->local_name);\n                return -1;\n            }\n            me->u.local.var_idx = idx;\n        }\n    }\n    return 0;\n}\n\n/* create a function object from a function definition. The function\n   definition is freed. All the child functions are also created. It\n   must be done this way to resolve all the variables. */\nstatic JSValue js_create_function(JSContext *ctx, JSFunctionDef *fd)\n{\n    JSValue func_obj;\n    JSFunctionBytecode *b;\n    struct list_head *el, *el1;\n    int stack_size, scope, idx;\n    int function_size, byte_code_offset, cpool_offset;\n    int closure_var_offset, vardefs_offset;\n\n    /* recompute scope linkage */\n    for (scope = 0; scope < fd->scope_count; scope++) {\n        fd->scopes[scope].first = -1;\n    }\n    if (fd->has_parameter_expressions) {\n        /* special end of variable list marker for the argument scope */\n        fd->scopes[ARG_SCOPE_INDEX].first = ARG_SCOPE_END;\n    }\n    for (idx = 0; idx < fd->var_count; idx++) {\n        JSVarDef *vd = &fd->vars[idx];\n        vd->scope_next = fd->scopes[vd->scope_level].first;\n        fd->scopes[vd->scope_level].first = idx;\n    }\n    for (scope = 2; scope < fd->scope_count; scope++) {\n        JSVarScope *sd = &fd->scopes[scope];\n        if (sd->first < 0)\n            sd->first = fd->scopes[sd->parent].first;\n    }\n    for (idx = 0; idx < fd->var_count; idx++) {\n        JSVarDef *vd = &fd->vars[idx];\n        if (vd->scope_next < 0 && vd->scope_level > 1) {\n            scope = fd->scopes[vd->scope_level].parent;\n            vd->scope_next = fd->scopes[scope].first;\n        }\n    }\n\n    /* if the function contains an eval call, the closure variables\n       are used to compile the eval and they must be ordered by scope,\n       so it is necessary to create the closure variables before any\n       other variable lookup is done. */\n    if (fd->has_eval_call)\n        add_eval_variables(ctx, fd);\n\n    /* add the module global variables in the closure */\n    if (fd->module) {\n        if (add_module_variables(ctx, fd))\n            goto fail;\n    }\n\n    /* first create all the child functions */\n    list_for_each_safe(el, el1, &fd->child_list) {\n        JSFunctionDef *fd1;\n        int cpool_idx;\n\n        fd1 = list_entry(el, JSFunctionDef, link);\n        cpool_idx = fd1->parent_cpool_idx;\n        func_obj = js_create_function(ctx, fd1);\n        if (JS_IsException(func_obj))\n            goto fail;\n        /* save it in the constant pool */\n        assert(cpool_idx >= 0);\n        fd->cpool[cpool_idx] = func_obj;\n    }\n\n#if defined(DUMP_BYTECODE) && (DUMP_BYTECODE & 4)\n    if (!(fd->js_mode & JS_MODE_STRIP)) {\n        printf(\"pass 1\\n\");\n        dump_byte_code(ctx, 1, fd->byte_code.buf, fd->byte_code.size,\n                       fd->args, fd->arg_count, fd->vars, fd->var_count,\n                       fd->closure_var, fd->closure_var_count,\n                       fd->cpool, fd->cpool_count, fd->source, fd->line_num,\n                       fd->label_slots, NULL);\n        printf(\"\\n\");\n    }\n#endif\n\n    if (resolve_variables(ctx, fd))\n        goto fail;\n\n#if defined(DUMP_BYTECODE) && (DUMP_BYTECODE & 2)\n    if (!(fd->js_mode & JS_MODE_STRIP)) {\n        printf(\"pass 2\\n\");\n        dump_byte_code(ctx, 2, fd->byte_code.buf, fd->byte_code.size,\n                       fd->args, fd->arg_count, fd->vars, fd->var_count,\n                       fd->closure_var, fd->closure_var_count,\n                       fd->cpool, fd->cpool_count, fd->source, fd->line_num,\n                       fd->label_slots, NULL);\n        printf(\"\\n\");\n    }\n#endif\n\n    if (resolve_labels(ctx, fd))\n        goto fail;\n\n    if (compute_stack_size(ctx, fd, &stack_size) < 0)\n        goto fail;\n\n    if (fd->js_mode & JS_MODE_STRIP) {\n        function_size = offsetof(JSFunctionBytecode, debug);\n    } else {\n        function_size = sizeof(*b);\n    }\n    cpool_offset = function_size;\n    function_size += fd->cpool_count * sizeof(*fd->cpool);\n    vardefs_offset = function_size;\n    if (!(fd->js_mode & JS_MODE_STRIP) || fd->has_eval_call) {\n        function_size += (fd->arg_count + fd->var_count) * sizeof(*b->vardefs);\n    }\n    closure_var_offset = function_size;\n    function_size += fd->closure_var_count * sizeof(*fd->closure_var);\n    byte_code_offset = function_size;\n    function_size += fd->byte_code.size;\n\n    b = js_mallocz(ctx, function_size);\n    if (!b)\n        goto fail;\n    b->header.ref_count = 1;\n\n    b->byte_code_buf = (void *)((uint8_t*)b + byte_code_offset);\n    b->byte_code_len = fd->byte_code.size;\n    memcpy(b->byte_code_buf, fd->byte_code.buf, fd->byte_code.size);\n    js_free(ctx, fd->byte_code.buf);\n    fd->byte_code.buf = NULL;\n\n    b->func_name = fd->func_name;\n    if (fd->arg_count + fd->var_count > 0) {\n        if ((fd->js_mode & JS_MODE_STRIP) && !fd->has_eval_call) {\n            /* Strip variable definitions not needed at runtime */\n            int i;\n            for(i = 0; i < fd->var_count; i++) {\n                JS_FreeAtom(ctx, fd->vars[i].var_name);\n            }\n            for(i = 0; i < fd->arg_count; i++) {\n                JS_FreeAtom(ctx, fd->args[i].var_name);\n            }\n            for(i = 0; i < fd->closure_var_count; i++) {\n                JS_FreeAtom(ctx, fd->closure_var[i].var_name);\n                fd->closure_var[i].var_name = JS_ATOM_NULL;\n            }\n        } else {\n            b->vardefs = (void *)((uint8_t*)b + vardefs_offset);\n            memcpy(b->vardefs, fd->args, fd->arg_count * sizeof(fd->args[0]));\n            memcpy(b->vardefs + fd->arg_count, fd->vars, fd->var_count * sizeof(fd->vars[0]));\n        }\n        b->var_count = fd->var_count;\n        b->arg_count = fd->arg_count;\n        b->defined_arg_count = fd->defined_arg_count;\n        js_free(ctx, fd->args);\n        js_free(ctx, fd->vars);\n    }\n    b->cpool_count = fd->cpool_count;\n    if (b->cpool_count) {\n        b->cpool = (void *)((uint8_t*)b + cpool_offset);\n        memcpy(b->cpool, fd->cpool, b->cpool_count * sizeof(*b->cpool));\n    }\n    js_free(ctx, fd->cpool);\n    fd->cpool = NULL;\n\n    b->stack_size = stack_size;\n\n    if (fd->js_mode & JS_MODE_STRIP) {\n        JS_FreeAtom(ctx, fd->filename);\n        dbuf_free(&fd->pc2line);    // probably useless\n    } else {\n        /* XXX: source and pc2line info should be packed at the end of the\n           JSFunctionBytecode structure, avoiding allocation overhead\n         */\n        b->has_debug = 1;\n        b->debug.filename = fd->filename;\n        b->debug.line_num = fd->line_num;\n\n        //DynBuf pc2line;\n        //compute_pc2line_info(fd, &pc2line);\n        //js_free(ctx, fd->line_number_slots)\n        b->debug.pc2line_buf = js_realloc(ctx, fd->pc2line.buf, fd->pc2line.size);\n        if (!b->debug.pc2line_buf)\n            b->debug.pc2line_buf = fd->pc2line.buf;\n        b->debug.pc2line_len = fd->pc2line.size;\n        b->debug.source = fd->source;\n        b->debug.source_len = fd->source_len;\n    }\n    if (fd->scopes != fd->def_scope_array)\n        js_free(ctx, fd->scopes);\n\n    b->closure_var_count = fd->closure_var_count;\n    if (b->closure_var_count) {\n        b->closure_var = (void *)((uint8_t*)b + closure_var_offset);\n        memcpy(b->closure_var, fd->closure_var, b->closure_var_count * sizeof(*b->closure_var));\n    }\n    js_free(ctx, fd->closure_var);\n    fd->closure_var = NULL;\n\n    b->has_prototype = fd->has_prototype;\n    b->has_simple_parameter_list = fd->has_simple_parameter_list;\n    b->js_mode = fd->js_mode;\n    b->is_derived_class_constructor = fd->is_derived_class_constructor;\n    b->func_kind = fd->func_kind;\n    b->need_home_object = (fd->home_object_var_idx >= 0 ||\n                           fd->need_home_object);\n    b->new_target_allowed = fd->new_target_allowed;\n    b->super_call_allowed = fd->super_call_allowed;\n    b->super_allowed = fd->super_allowed;\n    b->arguments_allowed = fd->arguments_allowed;\n    b->backtrace_barrier = fd->backtrace_barrier;\n    b->realm = JS_DupContext(ctx);\n\n    add_gc_object(ctx->rt, &b->header, JS_GC_OBJ_TYPE_FUNCTION_BYTECODE);\n    \n#if defined(DUMP_BYTECODE) && (DUMP_BYTECODE & 1)\n    if (!(fd->js_mode & JS_MODE_STRIP)) {\n        js_dump_function_bytecode(ctx, b);\n    }\n#endif\n\n    if (fd->parent) {\n        /* remove from parent list */\n        list_del(&fd->link);\n    }\n\n    js_free(ctx, fd);\n    return JS_MKPTR(JS_TAG_FUNCTION_BYTECODE, b);\n fail:\n    js_free_function_def(ctx, fd);\n    return JS_EXCEPTION;\n}\n\nstatic void free_function_bytecode(JSRuntime *rt, JSFunctionBytecode *b)\n{\n    int i;\n\n#if 0\n    {\n        char buf[ATOM_GET_STR_BUF_SIZE];\n        printf(\"freeing %s\\n\",\n               JS_AtomGetStrRT(rt, buf, sizeof(buf), b->func_name));\n    }\n#endif\n    free_bytecode_atoms(rt, b->byte_code_buf, b->byte_code_len, TRUE);\n\n    if (b->vardefs) {\n        for(i = 0; i < b->arg_count + b->var_count; i++) {\n            JS_FreeAtomRT(rt, b->vardefs[i].var_name);\n        }\n    }\n    for(i = 0; i < b->cpool_count; i++)\n        JS_FreeValueRT(rt, b->cpool[i]);\n\n    for(i = 0; i < b->closure_var_count; i++) {\n        JSClosureVar *cv = &b->closure_var[i];\n        JS_FreeAtomRT(rt, cv->var_name);\n    }\n    if (b->realm)\n        JS_FreeContext(b->realm);\n\n    JS_FreeAtomRT(rt, b->func_name);\n    if (b->has_debug) {\n        JS_FreeAtomRT(rt, b->debug.filename);\n        js_free_rt(rt, b->debug.pc2line_buf);\n        js_free_rt(rt, b->debug.source);\n    }\n\n    remove_gc_object(&b->header);\n    if (rt->gc_phase == JS_GC_PHASE_REMOVE_CYCLES && b->header.ref_count != 0) {\n        list_add_tail(&b->header.link, &rt->gc_zero_ref_count_list);\n    } else {\n        js_free_rt(rt, b);\n    }\n}\n\nstatic __exception int js_parse_directives(JSParseState *s)\n{\n    char str[20];\n    JSParsePos pos;\n    BOOL has_semi;\n\n    if (s->token.val != TOK_STRING)\n        return 0;\n\n    js_parse_get_pos(s, &pos);\n\n    while(s->token.val == TOK_STRING) {\n        /* Copy actual source string representation */\n        snprintf(str, sizeof str, \"%.*s\",\n                 (int)(s->buf_ptr - s->token.ptr - 2), s->token.ptr + 1);\n\n        if (next_token(s))\n            return -1;\n\n        has_semi = FALSE;\n        switch (s->token.val) {\n        case ';':\n            if (next_token(s))\n                return -1;\n            has_semi = TRUE;\n            break;\n        case '}':\n        case TOK_EOF:\n            has_semi = TRUE;\n            break;\n        case TOK_NUMBER:\n        case TOK_STRING:\n        case TOK_TEMPLATE:\n        case TOK_IDENT:\n        case TOK_REGEXP:\n        case TOK_DEC:\n        case TOK_INC:\n        case TOK_NULL:\n        case TOK_FALSE:\n        case TOK_TRUE:\n        case TOK_IF:\n        case TOK_RETURN:\n        case TOK_VAR:\n        case TOK_THIS:\n        case TOK_DELETE:\n        case TOK_TYPEOF:\n        case TOK_NEW:\n        case TOK_DO:\n        case TOK_WHILE:\n        case TOK_FOR:\n        case TOK_SWITCH:\n        case TOK_THROW:\n        case TOK_TRY:\n        case TOK_FUNCTION:\n        case TOK_DEBUGGER:\n        case TOK_WITH:\n        case TOK_CLASS:\n        case TOK_CONST:\n        case TOK_ENUM:\n        case TOK_EXPORT:\n        case TOK_IMPORT:\n        case TOK_SUPER:\n        case TOK_INTERFACE:\n        case TOK_LET:\n        case TOK_PACKAGE:\n        case TOK_PRIVATE:\n        case TOK_PROTECTED:\n        case TOK_PUBLIC:\n        case TOK_STATIC:\n            /* automatic insertion of ';' */\n            if (s->got_lf)\n                has_semi = TRUE;\n            break;\n        default:\n            break;\n        }\n        if (!has_semi)\n            break;\n        if (!strcmp(str, \"use strict\")) {\n            s->cur_func->has_use_strict = TRUE;\n            s->cur_func->js_mode |= JS_MODE_STRICT;\n        }\n#if !defined(DUMP_BYTECODE) || !(DUMP_BYTECODE & 8)\n        else if (!strcmp(str, \"use strip\")) {\n            s->cur_func->js_mode |= JS_MODE_STRIP;\n        }\n#endif\n#ifdef CONFIG_BIGNUM\n        else if (s->ctx->bignum_ext && !strcmp(str, \"use math\")) {\n            s->cur_func->js_mode |= JS_MODE_MATH;\n        }\n#endif\n    }\n    return js_parse_seek_token(s, &pos);\n}\n\nstatic int js_parse_function_check_names(JSParseState *s, JSFunctionDef *fd,\n                                         JSAtom func_name)\n{\n    JSAtom name;\n    int i, idx;\n\n    if (fd->js_mode & JS_MODE_STRICT) {\n        if (!fd->has_simple_parameter_list && fd->has_use_strict) {\n            return js_parse_error(s, \"\\\"use strict\\\" not allowed in function with default or destructuring parameter\");\n        }\n        if (func_name == JS_ATOM_eval || func_name == JS_ATOM_arguments) {\n            return js_parse_error(s, \"invalid function name in strict code\");\n        }\n        for (idx = 0; idx < fd->arg_count; idx++) {\n            name = fd->args[idx].var_name;\n\n            if (name == JS_ATOM_eval || name == JS_ATOM_arguments) {\n                return js_parse_error(s, \"invalid argument name in strict code\");\n            }\n        }\n    }\n    /* check async_generator case */\n    if ((fd->js_mode & JS_MODE_STRICT)\n    ||  !fd->has_simple_parameter_list\n    ||  (fd->func_type == JS_PARSE_FUNC_METHOD && fd->func_kind == JS_FUNC_ASYNC)\n    ||  fd->func_type == JS_PARSE_FUNC_ARROW\n    ||  fd->func_type == JS_PARSE_FUNC_METHOD) {\n        for (idx = 0; idx < fd->arg_count; idx++) {\n            name = fd->args[idx].var_name;\n            if (name != JS_ATOM_NULL) {\n                for (i = 0; i < idx; i++) {\n                    if (fd->args[i].var_name == name)\n                        goto duplicate;\n                }\n                /* Check if argument name duplicates a destructuring parameter */\n                /* XXX: should have a flag for such variables */\n                for (i = 0; i < fd->var_count; i++) {\n                    if (fd->vars[i].var_name == name &&\n                        fd->vars[i].scope_level == 0)\n                        goto duplicate;\n                }\n            }\n        }\n    }\n    return 0;\n\nduplicate:\n    return js_parse_error(s, \"duplicate argument names not allowed in this context\");\n}\n\n/* create a function to initialize class fields */\nstatic JSFunctionDef *js_parse_function_class_fields_init(JSParseState *s)\n{\n    JSFunctionDef *fd;\n    \n    fd = js_new_function_def(s->ctx, s->cur_func, FALSE, FALSE,\n                             s->filename, 0);\n    if (!fd)\n        return NULL;\n    fd->func_name = JS_ATOM_NULL;\n    fd->has_prototype = FALSE;\n    fd->has_home_object = TRUE;\n    \n    fd->has_arguments_binding = FALSE;\n    fd->has_this_binding = TRUE;\n    fd->is_derived_class_constructor = FALSE;\n    fd->new_target_allowed = TRUE;\n    fd->super_call_allowed = FALSE;\n    fd->super_allowed = fd->has_home_object;\n    fd->arguments_allowed = FALSE;\n    \n    fd->func_kind = JS_FUNC_NORMAL;\n    fd->func_type = JS_PARSE_FUNC_METHOD;\n    return fd;\n}\n\n/* func_name must be JS_ATOM_NULL for JS_PARSE_FUNC_STATEMENT and\n   JS_PARSE_FUNC_EXPR, JS_PARSE_FUNC_ARROW and JS_PARSE_FUNC_VAR */\nstatic __exception int js_parse_function_decl2(JSParseState *s,\n                                               JSParseFunctionEnum func_type,\n                                               JSFunctionKindEnum func_kind,\n                                               JSAtom func_name,\n                                               const uint8_t *ptr,\n                                               int function_line_num,\n                                               JSParseExportEnum export_flag,\n                                               JSFunctionDef **pfd)\n{\n    JSContext *ctx = s->ctx;\n    JSFunctionDef *fd = s->cur_func;\n    BOOL is_expr;\n    int func_idx, lexical_func_idx = -1;\n    BOOL has_opt_arg;\n    BOOL create_func_var = FALSE;\n\n    is_expr = (func_type != JS_PARSE_FUNC_STATEMENT &&\n               func_type != JS_PARSE_FUNC_VAR);\n\n    if (func_type == JS_PARSE_FUNC_STATEMENT ||\n        func_type == JS_PARSE_FUNC_VAR ||\n        func_type == JS_PARSE_FUNC_EXPR) {\n        if (func_kind == JS_FUNC_NORMAL &&\n            token_is_pseudo_keyword(s, JS_ATOM_async) &&\n            peek_token(s, TRUE) != '\\n') {\n            if (next_token(s))\n                return -1;\n            func_kind = JS_FUNC_ASYNC;\n        }\n        if (next_token(s))\n            return -1;\n        if (s->token.val == '*') {\n            if (next_token(s))\n                return -1;\n            func_kind |= JS_FUNC_GENERATOR;\n        }\n\n        if (s->token.val == TOK_IDENT) {\n            if (s->token.u.ident.is_reserved ||\n                (s->token.u.ident.atom == JS_ATOM_yield &&\n                 func_type == JS_PARSE_FUNC_EXPR &&\n                 (func_kind & JS_FUNC_GENERATOR)) ||\n                (s->token.u.ident.atom == JS_ATOM_await &&\n                 func_type == JS_PARSE_FUNC_EXPR &&\n                 (func_kind & JS_FUNC_ASYNC))) {\n                return js_parse_error_reserved_identifier(s);\n            }\n        }\n        if (s->token.val == TOK_IDENT ||\n            (((s->token.val == TOK_YIELD && !(fd->js_mode & JS_MODE_STRICT)) ||\n             (s->token.val == TOK_AWAIT && !s->is_module)) &&\n             func_type == JS_PARSE_FUNC_EXPR)) {\n            func_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n            if (next_token(s)) {\n                JS_FreeAtom(ctx, func_name);\n                return -1;\n            }\n        } else {\n            if (func_type != JS_PARSE_FUNC_EXPR &&\n                export_flag != JS_PARSE_EXPORT_DEFAULT) {\n                return js_parse_error(s, \"function name expected\");\n            }\n        }\n    } else if (func_type != JS_PARSE_FUNC_ARROW) {\n        func_name = JS_DupAtom(ctx, func_name);\n    }\n\n    if (fd->is_eval && fd->eval_type == JS_EVAL_TYPE_MODULE &&\n        (func_type == JS_PARSE_FUNC_STATEMENT || func_type == JS_PARSE_FUNC_VAR)) {\n        JSGlobalVar *hf;\n        hf = find_global_var(fd, func_name);\n        /* XXX: should check scope chain */\n        if (hf && hf->scope_level == fd->scope_level) {\n            js_parse_error(s, \"invalid redefinition of global identifier in module code\");\n            JS_FreeAtom(ctx, func_name);\n            return -1;\n        }\n    }\n\n    if (func_type == JS_PARSE_FUNC_VAR) {\n        if (!(fd->js_mode & JS_MODE_STRICT)\n        && func_kind == JS_FUNC_NORMAL\n        &&  find_lexical_decl(ctx, fd, func_name, fd->scope_first, FALSE) < 0\n        &&  !((func_idx = find_var(ctx, fd, func_name)) >= 0 && (func_idx & ARGUMENT_VAR_OFFSET))\n        &&  !(func_name == JS_ATOM_arguments && fd->has_arguments_binding)) {\n            create_func_var = TRUE;\n        }\n        /* Create the lexical name here so that the function closure\n           contains it */\n        if (fd->is_eval &&\n            (fd->eval_type == JS_EVAL_TYPE_GLOBAL ||\n             fd->eval_type == JS_EVAL_TYPE_MODULE) &&\n            fd->scope_level == fd->body_scope) {\n            /* avoid creating a lexical variable in the global\n               scope. XXX: check annex B */\n            JSGlobalVar *hf;\n            hf = find_global_var(fd, func_name);\n            /* XXX: should check scope chain */\n            if (hf && hf->scope_level == fd->scope_level) {\n                js_parse_error(s, \"invalid redefinition of global identifier\");\n                JS_FreeAtom(ctx, func_name);\n                return -1;\n            }\n        } else {\n            /* Always create a lexical name, fail if at the same scope as\n               existing name */\n            /* Lexical variable will be initialized upon entering scope */\n            lexical_func_idx = define_var(s, fd, func_name,\n                                          func_kind != JS_FUNC_NORMAL ?\n                                          JS_VAR_DEF_NEW_FUNCTION_DECL :\n                                          JS_VAR_DEF_FUNCTION_DECL);\n            if (lexical_func_idx < 0) {\n                JS_FreeAtom(ctx, func_name);\n                return -1;\n            }\n        }\n    }\n\n    fd = js_new_function_def(ctx, fd, FALSE, is_expr,\n                             s->filename, function_line_num);\n    if (!fd) {\n        JS_FreeAtom(ctx, func_name);\n        return -1;\n    }\n    if (pfd)\n        *pfd = fd;\n    s->cur_func = fd;\n    fd->func_name = func_name;\n    /* XXX: test !fd->is_generator is always false */\n    fd->has_prototype = (func_type == JS_PARSE_FUNC_STATEMENT ||\n                         func_type == JS_PARSE_FUNC_VAR ||\n                         func_type == JS_PARSE_FUNC_EXPR) &&\n                        func_kind == JS_FUNC_NORMAL;\n    fd->has_home_object = (func_type == JS_PARSE_FUNC_METHOD ||\n                           func_type == JS_PARSE_FUNC_GETTER ||\n                           func_type == JS_PARSE_FUNC_SETTER ||\n                           func_type == JS_PARSE_FUNC_CLASS_CONSTRUCTOR ||\n                           func_type == JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR);\n    fd->has_arguments_binding = (func_type != JS_PARSE_FUNC_ARROW);\n    fd->has_this_binding = fd->has_arguments_binding;\n    fd->is_derived_class_constructor = (func_type == JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR);\n    if (func_type == JS_PARSE_FUNC_ARROW) {\n        fd->new_target_allowed = fd->parent->new_target_allowed;\n        fd->super_call_allowed = fd->parent->super_call_allowed;\n        fd->super_allowed = fd->parent->super_allowed;\n        fd->arguments_allowed = fd->parent->arguments_allowed;\n    } else {\n        fd->new_target_allowed = TRUE;\n        fd->super_call_allowed = fd->is_derived_class_constructor;\n        fd->super_allowed = fd->has_home_object;\n        fd->arguments_allowed = TRUE;\n    }\n\n    /* fd->in_function_body == FALSE prevents yield/await during the parsing\n       of the arguments in generator/async functions. They are parsed as\n       regular identifiers for other function kinds. */\n    fd->func_kind = func_kind;\n    fd->func_type = func_type;\n\n    if (func_type == JS_PARSE_FUNC_CLASS_CONSTRUCTOR ||\n        func_type == JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR) {\n        /* error if not invoked as a constructor */\n        emit_op(s, OP_check_ctor);\n    }\n\n    if (func_type == JS_PARSE_FUNC_CLASS_CONSTRUCTOR) {\n        emit_class_field_init(s);\n    }\n    \n    /* parse arguments */\n    fd->has_simple_parameter_list = TRUE;\n    fd->has_parameter_expressions = FALSE;\n    has_opt_arg = FALSE;\n    if (func_type == JS_PARSE_FUNC_ARROW && s->token.val == TOK_IDENT) {\n        JSAtom name;\n        if (s->token.u.ident.is_reserved) {\n            js_parse_error_reserved_identifier(s);\n            goto fail;\n        }\n        name = s->token.u.ident.atom;\n        if (add_arg(ctx, fd, name) < 0)\n            goto fail;\n        fd->defined_arg_count = 1;\n    } else {\n        if (s->token.val == '(') {\n            int skip_bits;\n            /* if there is an '=' inside the parameter list, we\n               consider there is a parameter expression inside */\n            js_parse_skip_parens_token(s, &skip_bits, FALSE);\n            if (skip_bits & SKIP_HAS_ASSIGNMENT)\n                fd->has_parameter_expressions = TRUE;\n            if (next_token(s))\n                goto fail;\n        } else {\n            if (js_parse_expect(s, '('))\n                goto fail;\n        }\n\n        if (fd->has_parameter_expressions) {\n            fd->scope_level = -1; /* force no parent scope */\n            if (push_scope(s) < 0)\n                return -1;\n        }\n        \n        while (s->token.val != ')') {\n            JSAtom name;\n            BOOL rest = FALSE;\n            int idx, has_initializer;\n\n            if (s->token.val == TOK_ELLIPSIS) {\n                fd->has_simple_parameter_list = FALSE;\n                rest = TRUE;\n                if (next_token(s))\n                    goto fail;\n            }\n            if (s->token.val == '[' || s->token.val == '{') {\n                fd->has_simple_parameter_list = FALSE;\n                if (rest) {\n                    emit_op(s, OP_rest);\n                    emit_u16(s, fd->arg_count);\n                } else {\n                    /* unnamed arg for destructuring */\n                    idx = add_arg(ctx, fd, JS_ATOM_NULL);\n                    emit_op(s, OP_get_arg);\n                    emit_u16(s, idx);\n                }\n                has_initializer = js_parse_destructuring_element(s, fd->has_parameter_expressions ? TOK_LET : TOK_VAR, 1, TRUE, -1, TRUE);\n                if (has_initializer < 0)\n                    goto fail;\n                if (has_initializer)\n                    has_opt_arg = TRUE;\n                if (!has_opt_arg)\n                    fd->defined_arg_count++;\n            } else if (s->token.val == TOK_IDENT) {\n                if (s->token.u.ident.is_reserved) {\n                    js_parse_error_reserved_identifier(s);\n                    goto fail;\n                }\n                name = s->token.u.ident.atom;\n                if (name == JS_ATOM_yield && fd->func_kind == JS_FUNC_GENERATOR) {\n                    js_parse_error_reserved_identifier(s);\n                    goto fail;\n                }\n                if (fd->has_parameter_expressions) {\n                    if (define_var(s, fd, name, JS_VAR_DEF_LET) < 0)\n                        goto fail;\n                }\n                /* XXX: could avoid allocating an argument if rest is true */\n                idx = add_arg(ctx, fd, name);\n                if (idx < 0)\n                    goto fail;\n                if (next_token(s))\n                    goto fail;\n                if (rest) {\n                    emit_op(s, OP_rest);\n                    emit_u16(s, idx);\n                    if (fd->has_parameter_expressions) {\n                        emit_op(s, OP_dup);\n                        emit_op(s, OP_scope_put_var_init);\n                        emit_atom(s, name);\n                        emit_u16(s, fd->scope_level);\n                    }\n                    emit_op(s, OP_put_arg);\n                    emit_u16(s, idx);\n                    fd->has_simple_parameter_list = FALSE;\n                    has_opt_arg = TRUE;\n                } else if (s->token.val == '=') {\n                    int label;\n                    \n                    fd->has_simple_parameter_list = FALSE;\n                    has_opt_arg = TRUE;\n\n                    if (next_token(s))\n                        goto fail;\n\n                    label = new_label(s);\n                    emit_op(s, OP_get_arg);\n                    emit_u16(s, idx);\n                    emit_op(s, OP_dup);\n                    emit_op(s, OP_undefined);\n                    emit_op(s, OP_strict_eq);\n                    emit_goto(s, OP_if_false, label);\n                    emit_op(s, OP_drop);\n                    if (js_parse_assign_expr(s))\n                        goto fail;\n                    set_object_name(s, name);\n                    emit_op(s, OP_dup);\n                    emit_op(s, OP_put_arg);\n                    emit_u16(s, idx);\n                    emit_label(s, label);\n                    emit_op(s, OP_scope_put_var_init);\n                    emit_atom(s, name);\n                    emit_u16(s, fd->scope_level);\n                } else {\n                    if (!has_opt_arg) {\n                        fd->defined_arg_count++;\n                    }\n                    if (fd->has_parameter_expressions) {\n                        /* copy the argument to the argument scope */\n                        emit_op(s, OP_get_arg);\n                        emit_u16(s, idx);\n                        emit_op(s, OP_scope_put_var_init);\n                        emit_atom(s, name);\n                        emit_u16(s, fd->scope_level);\n                    }\n                }\n            } else {\n                js_parse_error(s, \"missing formal parameter\");\n                goto fail;\n            }\n            if (rest && s->token.val != ')') {\n                js_parse_expect(s, ')');\n                goto fail;\n            }\n            if (s->token.val == ')')\n                break;\n            if (js_parse_expect(s, ','))\n                goto fail;\n        }\n        if ((func_type == JS_PARSE_FUNC_GETTER && fd->arg_count != 0) ||\n            (func_type == JS_PARSE_FUNC_SETTER && fd->arg_count != 1)) {\n            js_parse_error(s, \"invalid number of arguments for getter or setter\");\n            goto fail;\n        }\n    }\n\n    if (fd->has_parameter_expressions) {\n        int idx;\n\n        /* Copy the variables in the argument scope to the variable\n           scope (see FunctionDeclarationInstantiation() in spec). The\n           normal arguments are already present, so no need to copy\n           them. */\n        idx = fd->scopes[fd->scope_level].first;\n        while (idx >= 0) {\n            JSVarDef *vd = &fd->vars[idx];\n            if (vd->scope_level != fd->scope_level)\n                break;\n            if (find_var(ctx, fd, vd->var_name) < 0) {\n                if (add_var(ctx, fd, vd->var_name) < 0)\n                    goto fail;\n                vd = &fd->vars[idx]; /* fd->vars may have been reallocated */\n                emit_op(s, OP_scope_get_var);\n                emit_atom(s, vd->var_name);\n                emit_u16(s, fd->scope_level);\n                emit_op(s, OP_scope_put_var);\n                emit_atom(s, vd->var_name);\n                emit_u16(s, 0);\n            }\n            idx = vd->scope_next;\n        }\n        \n        /* the argument scope has no parent, hence we don't use pop_scope(s) */\n        emit_op(s, OP_leave_scope);\n        emit_u16(s, fd->scope_level);\n\n        /* set the variable scope as the current scope */\n        fd->scope_level = 0;\n        fd->scope_first = fd->scopes[fd->scope_level].first;\n    }\n    \n    if (next_token(s))\n        goto fail;\n\n    /* generator function: yield after the parameters are evaluated */\n    if (func_kind == JS_FUNC_GENERATOR ||\n        func_kind == JS_FUNC_ASYNC_GENERATOR)\n        emit_op(s, OP_initial_yield);\n\n    /* in generators, yield expression is forbidden during the parsing\n       of the arguments */\n    fd->in_function_body = TRUE;\n    push_scope(s);  /* enter body scope */\n    fd->body_scope = fd->scope_level;\n\n    if (s->token.val == TOK_ARROW) {\n        if (next_token(s))\n            goto fail;\n\n        if (s->token.val != '{') {\n            if (js_parse_function_check_names(s, fd, func_name))\n                goto fail;\n\n            if (js_parse_assign_expr(s))\n                goto fail;\n\n            if (func_kind != JS_FUNC_NORMAL)\n                emit_op(s, OP_return_async);\n            else\n                emit_op(s, OP_return);\n\n            if (!(fd->js_mode & JS_MODE_STRIP)) {\n                /* save the function source code */\n                /* the end of the function source code is after the last\n                   token of the function source stored into s->last_ptr */\n                fd->source_len = s->last_ptr - ptr;\n                fd->source = js_strndup(ctx, (const char *)ptr, fd->source_len);\n                if (!fd->source)\n                    goto fail;\n            }\n            goto done;\n        }\n    }\n\n    if (js_parse_expect(s, '{'))\n        goto fail;\n\n    if (js_parse_directives(s))\n        goto fail;\n\n    /* in strict_mode, check function and argument names */\n    if (js_parse_function_check_names(s, fd, func_name))\n        goto fail;\n\n    while (s->token.val != '}') {\n        if (js_parse_source_element(s))\n            goto fail;\n    }\n    if (!(fd->js_mode & JS_MODE_STRIP)) {\n        /* save the function source code */\n        fd->source_len = s->buf_ptr - ptr;\n        fd->source = js_strndup(ctx, (const char *)ptr, fd->source_len);\n        if (!fd->source)\n            goto fail;\n    }\n\n    if (next_token(s)) {\n        /* consume the '}' */\n        goto fail;\n    }\n\n    /* in case there is no return, add one */\n    if (js_is_live_code(s)) {\n        emit_return(s, FALSE);\n    }\ndone:\n    s->cur_func = fd->parent;\n\n    /* create the function object */\n    {\n        int idx;\n        JSAtom func_name = fd->func_name;\n\n        /* the real object will be set at the end of the compilation */\n        idx = cpool_add(s, JS_NULL);\n        fd->parent_cpool_idx = idx;\n\n        if (is_expr) {\n            /* for constructors, no code needs to be generated here */\n            if (func_type != JS_PARSE_FUNC_CLASS_CONSTRUCTOR &&\n                func_type != JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR) {\n                /* OP_fclosure creates the function object from the bytecode\n                   and adds the scope information */\n                emit_op(s, OP_fclosure);\n                emit_u32(s, idx);\n                if (func_name == JS_ATOM_NULL) {\n                    emit_op(s, OP_set_name);\n                    emit_u32(s, JS_ATOM_NULL);\n                }\n            }\n        } else if (func_type == JS_PARSE_FUNC_VAR) {\n            emit_op(s, OP_fclosure);\n            emit_u32(s, idx);\n            if (create_func_var) {\n                if (s->cur_func->is_global_var) {\n                    JSGlobalVar *hf;\n                    /* the global variable must be defined at the start of the\n                       function */\n                    hf = add_global_var(ctx, s->cur_func, func_name);\n                    if (!hf)\n                        goto fail;\n                    /* it is considered as defined at the top level\n                       (needed for annex B.3.3.4 and B.3.3.5\n                       checks) */\n                    hf->scope_level = 0; \n                    hf->force_init = ((s->cur_func->js_mode & JS_MODE_STRICT) != 0);\n                    /* store directly into global var, bypass lexical scope */\n                    emit_op(s, OP_dup);\n                    emit_op(s, OP_scope_put_var);\n                    emit_atom(s, func_name);\n                    emit_u16(s, 0);\n                } else {\n                    /* do not call define_var to bypass lexical scope check */\n                    func_idx = find_var(ctx, s->cur_func, func_name);\n                    if (func_idx < 0) {\n                        func_idx = add_var(ctx, s->cur_func, func_name);\n                        if (func_idx < 0)\n                            goto fail;\n                    }\n                    /* store directly into local var, bypass lexical catch scope */\n                    emit_op(s, OP_dup);\n                    emit_op(s, OP_scope_put_var);\n                    emit_atom(s, func_name);\n                    emit_u16(s, 0);\n                }\n            }\n            if (lexical_func_idx >= 0) {\n                /* lexical variable will be initialized upon entering scope */\n                s->cur_func->vars[lexical_func_idx].func_pool_idx = idx;\n                emit_op(s, OP_drop);\n            } else {\n                /* store function object into its lexical name */\n                /* XXX: could use OP_put_loc directly */\n                emit_op(s, OP_scope_put_var_init);\n                emit_atom(s, func_name);\n                emit_u16(s, s->cur_func->scope_level);\n            }\n        } else {\n            if (!s->cur_func->is_global_var) {\n                int var_idx = define_var(s, s->cur_func, func_name, JS_VAR_DEF_VAR);\n\n                if (var_idx < 0)\n                    goto fail;\n                /* the variable will be assigned at the top of the function */\n                if (var_idx & ARGUMENT_VAR_OFFSET) {\n                    s->cur_func->args[var_idx - ARGUMENT_VAR_OFFSET].func_pool_idx = idx;\n                } else {\n                    s->cur_func->vars[var_idx].func_pool_idx = idx;\n                }\n            } else {\n                JSAtom func_var_name;\n                JSGlobalVar *hf;\n                if (func_name == JS_ATOM_NULL)\n                    func_var_name = JS_ATOM__default_; /* export default */\n                else\n                    func_var_name = func_name;\n                /* the variable will be assigned at the top of the function */\n                hf = add_global_var(ctx, s->cur_func, func_var_name);\n                if (!hf)\n                    goto fail;\n                hf->cpool_idx = idx;\n                if (export_flag != JS_PARSE_EXPORT_NONE) {\n                    if (!add_export_entry(s, s->cur_func->module, func_var_name,\n                                          export_flag == JS_PARSE_EXPORT_NAMED ? func_var_name : JS_ATOM_default, JS_EXPORT_TYPE_LOCAL))\n                        goto fail;\n                }\n            }\n        }\n    }\n    return 0;\n fail:\n    s->cur_func = fd->parent;\n    js_free_function_def(ctx, fd);\n    if (pfd)\n        *pfd = NULL;\n    return -1;\n}\n\nstatic __exception int js_parse_function_decl(JSParseState *s,\n                                              JSParseFunctionEnum func_type,\n                                              JSFunctionKindEnum func_kind,\n                                              JSAtom func_name,\n                                              const uint8_t *ptr,\n                                              int function_line_num)\n{\n    return js_parse_function_decl2(s, func_type, func_kind, func_name, ptr,\n                                   function_line_num, JS_PARSE_EXPORT_NONE,\n                                   NULL);\n}\n\nstatic __exception int js_parse_program(JSParseState *s)\n{\n    JSFunctionDef *fd = s->cur_func;\n    int idx;\n\n    if (next_token(s))\n        return -1;\n\n    if (js_parse_directives(s))\n        return -1;\n\n    fd->is_global_var = (fd->eval_type == JS_EVAL_TYPE_GLOBAL) ||\n        (fd->eval_type == JS_EVAL_TYPE_MODULE) ||\n        !(fd->js_mode & JS_MODE_STRICT);\n\n    if (!s->is_module) {\n        /* hidden variable for the return value */\n        fd->eval_ret_idx = idx = add_var(s->ctx, fd, JS_ATOM__ret_);\n        if (idx < 0)\n            return -1;\n    }\n\n    while (s->token.val != TOK_EOF) {\n        if (js_parse_source_element(s))\n            return -1;\n    }\n\n    if (!s->is_module) {\n        /* return the value of the hidden variable eval_ret_idx  */\n        emit_op(s, OP_get_loc);\n        emit_u16(s, fd->eval_ret_idx);\n\n        emit_op(s, OP_return);\n    } else {\n        emit_op(s, OP_return_undef);\n    }\n\n    return 0;\n}\n\nstatic void js_parse_init(JSContext *ctx, JSParseState *s,\n                          const char *input, size_t input_len,\n                          const char *filename)\n{\n    memset(s, 0, sizeof(*s));\n    s->ctx = ctx;\n    s->filename = filename;\n    s->line_num = 1;\n    s->buf_ptr = (const uint8_t *)input;\n    s->buf_end = s->buf_ptr + input_len;\n    s->token.val = ' ';\n    s->token.line_num = 1;\n}\n\nstatic JSValue JS_EvalFunctionInternal(JSContext *ctx, JSValue fun_obj,\n                                       JSValueConst this_obj,\n                                       JSVarRef **var_refs, JSStackFrame *sf)\n{\n    JSValue ret_val;\n    uint32_t tag;\n\n    tag = JS_VALUE_GET_TAG(fun_obj);\n    if (tag == JS_TAG_FUNCTION_BYTECODE) {\n        fun_obj = js_closure(ctx, fun_obj, var_refs, sf);\n        ret_val = JS_CallFree(ctx, fun_obj, this_obj, 0, NULL);\n    } else if (tag == JS_TAG_MODULE) {\n        JSModuleDef *m;\n        m = JS_VALUE_GET_PTR(fun_obj);\n        /* the module refcount should be >= 2 */\n        JS_FreeValue(ctx, fun_obj);\n        if (js_create_module_function(ctx, m) < 0)\n            goto fail;\n        if (js_link_module(ctx, m) < 0)\n            goto fail;\n        ret_val = js_evaluate_module(ctx, m);\n        if (JS_IsException(ret_val)) {\n        fail:\n            js_free_modules(ctx, JS_FREE_MODULE_NOT_EVALUATED);\n            return JS_EXCEPTION;\n        }\n    } else {\n        JS_FreeValue(ctx, fun_obj);\n        ret_val = JS_ThrowTypeError(ctx, \"bytecode function expected\");\n    }\n    return ret_val;\n}\n\nJSValue JS_EvalFunction(JSContext *ctx, JSValue fun_obj)\n{\n    return JS_EvalFunctionInternal(ctx, fun_obj, ctx->global_obj, NULL, NULL);\n}\n\nstatic void skip_shebang(JSParseState *s)\n{\n    const uint8_t *p = s->buf_ptr;\n    int c;\n\n    if (p[0] == '#' && p[1] == '!') {\n        p += 2;\n        while (p < s->buf_end) {\n            if (*p == '\\n' || *p == '\\r') {\n                break;\n            } else if (*p >= 0x80) {\n                c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);\n                if (c == CP_LS || c == CP_PS) {\n                    break;\n                } else if (c == -1) {\n                    p++; /* skip invalid UTF-8 */\n                }\n            } else {\n                p++;\n            }\n        }\n        s->buf_ptr = p;\n    }\n}\n\n/* 'input' must be zero terminated i.e. input[input_len] = '\\0'. */\nstatic JSValue __JS_EvalInternal(JSContext *ctx, JSValueConst this_obj,\n                                 const char *input, size_t input_len,\n                                 const char *filename, int flags, int scope_idx)\n{\n    JSParseState s1, *s = &s1;\n    int err, js_mode, eval_type;\n    JSValue fun_obj, ret_val;\n    JSStackFrame *sf;\n    JSVarRef **var_refs;\n    JSFunctionBytecode *b;\n    JSFunctionDef *fd;\n    JSModuleDef *m;\n\n    js_parse_init(ctx, s, input, input_len, filename);\n    skip_shebang(s);\n\n    eval_type = flags & JS_EVAL_TYPE_MASK;\n    m = NULL;\n    if (eval_type == JS_EVAL_TYPE_DIRECT) {\n        JSObject *p;\n        sf = ctx->rt->current_stack_frame;\n        assert(sf != NULL);\n        assert(JS_VALUE_GET_TAG(sf->cur_func) == JS_TAG_OBJECT);\n        p = JS_VALUE_GET_OBJ(sf->cur_func);\n        assert(js_class_has_bytecode(p->class_id));\n        b = p->u.func.function_bytecode;\n        var_refs = p->u.func.var_refs;\n        js_mode = b->js_mode;\n    } else {\n        sf = NULL;\n        b = NULL;\n        var_refs = NULL;\n        js_mode = 0;\n        if (flags & JS_EVAL_FLAG_STRICT)\n            js_mode |= JS_MODE_STRICT;\n        if (flags & JS_EVAL_FLAG_STRIP)\n            js_mode |= JS_MODE_STRIP;\n        if (eval_type == JS_EVAL_TYPE_MODULE) {\n            JSAtom module_name = JS_NewAtom(ctx, filename);\n            if (module_name == JS_ATOM_NULL)\n                return JS_EXCEPTION;\n            m = js_new_module_def(ctx, module_name);\n            if (!m)\n                return JS_EXCEPTION;\n            js_mode |= JS_MODE_STRICT;\n        }\n    }\n    fd = js_new_function_def(ctx, NULL, TRUE, FALSE, filename, 1);\n    if (!fd)\n        goto fail1;\n    s->cur_func = fd;\n    fd->eval_type = eval_type;\n    fd->has_this_binding = (eval_type != JS_EVAL_TYPE_DIRECT);\n    fd->backtrace_barrier = ((flags & JS_EVAL_FLAG_BACKTRACE_BARRIER) != 0);\n    if (eval_type == JS_EVAL_TYPE_DIRECT) {\n        fd->new_target_allowed = b->new_target_allowed;\n        fd->super_call_allowed = b->super_call_allowed;\n        fd->super_allowed = b->super_allowed;\n        fd->arguments_allowed = b->arguments_allowed;\n    } else {\n        fd->new_target_allowed = FALSE;\n        fd->super_call_allowed = FALSE;\n        fd->super_allowed = FALSE;\n        fd->arguments_allowed = TRUE;\n    }\n    fd->js_mode = js_mode;\n    fd->func_name = JS_DupAtom(ctx, JS_ATOM__eval_);\n    if (b) {\n        if (add_closure_variables(ctx, fd, b, scope_idx))\n            goto fail;\n    }\n    fd->module = m;\n    s->is_module = (m != NULL);\n    s->allow_html_comments = !s->is_module;\n\n    push_scope(s); /* body scope */\n    fd->body_scope = fd->scope_level;\n    \n    err = js_parse_program(s);\n    if (err) {\n    fail:\n        free_token(s, &s->token);\n        js_free_function_def(ctx, fd);\n        goto fail1;\n    }\n\n    /* create the function object and all the enclosed functions */\n    fun_obj = js_create_function(ctx, fd);\n    if (JS_IsException(fun_obj))\n        goto fail1;\n    /* Could add a flag to avoid resolution if necessary */\n    if (m) {\n        m->func_obj = fun_obj;\n        if (js_resolve_module(ctx, m) < 0)\n            goto fail1;\n        fun_obj = JS_DupValue(ctx, JS_MKPTR(JS_TAG_MODULE, m));\n    }\n    if (flags & JS_EVAL_FLAG_COMPILE_ONLY) {\n        ret_val = fun_obj;\n    } else {\n        ret_val = JS_EvalFunctionInternal(ctx, fun_obj, this_obj, var_refs, sf);\n    }\n    return ret_val;\n fail1:\n    /* XXX: should free all the unresolved dependencies */\n    if (m)\n        js_free_module_def(ctx, m);\n    return JS_EXCEPTION;\n}\n\n/* the indirection is needed to make 'eval' optional */\nstatic JSValue JS_EvalInternal(JSContext *ctx, JSValueConst this_obj,\n                               const char *input, size_t input_len,\n                               const char *filename, int flags, int scope_idx)\n{\n    if (unlikely(!ctx->eval_internal)) {\n        return JS_ThrowTypeError(ctx, \"eval is not supported\");\n    }\n    return ctx->eval_internal(ctx, this_obj, input, input_len, filename,\n                              flags, scope_idx);\n}\n\nstatic JSValue JS_EvalObject(JSContext *ctx, JSValueConst this_obj,\n                             JSValueConst val, int flags, int scope_idx)\n{\n    JSValue ret;\n    const char *str;\n    size_t len;\n\n    if (!JS_IsString(val))\n        return JS_DupValue(ctx, val);\n    str = JS_ToCStringLen(ctx, &len, val);\n    if (!str)\n        return JS_EXCEPTION;\n    ret = JS_EvalInternal(ctx, this_obj, str, len, \"<input>\", flags, scope_idx);\n    JS_FreeCString(ctx, str);\n    return ret;\n\n}\n\nJSValue JS_EvalThis(JSContext *ctx, JSValueConst this_obj,\n                    const char *input, size_t input_len,\n                    const char *filename, int eval_flags)\n{\n    int eval_type = eval_flags & JS_EVAL_TYPE_MASK;\n    JSValue ret;\n\n    assert(eval_type == JS_EVAL_TYPE_GLOBAL ||\n           eval_type == JS_EVAL_TYPE_MODULE);\n    ret = JS_EvalInternal(ctx, this_obj, input, input_len, filename,\n                          eval_flags, -1);\n    return ret;\n}\n\nJSValue JS_Eval(JSContext *ctx, const char *input, size_t input_len,\n                const char *filename, int eval_flags)\n{\n    return JS_EvalThis(ctx, ctx->global_obj, input, input_len, filename,\n                       eval_flags);\n}\n\nint JS_ResolveModule(JSContext *ctx, JSValueConst obj)\n{\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) {\n        JSModuleDef *m = JS_VALUE_GET_PTR(obj);\n        if (js_resolve_module(ctx, m) < 0) {\n            js_free_modules(ctx, JS_FREE_MODULE_NOT_RESOLVED);\n            return -1;\n        }\n    }\n    return 0;\n}\n\n/*******************************************************************/\n/* object list */\n\ntypedef struct {\n    JSObject *obj;\n    uint32_t hash_next; /* -1 if no next entry */\n} JSObjectListEntry;\n\n/* XXX: reuse it to optimize weak references */\ntypedef struct {\n    JSObjectListEntry *object_tab;\n    int object_count;\n    int object_size;\n    uint32_t *hash_table;\n    uint32_t hash_size;\n} JSObjectList;\n\nstatic void js_object_list_init(JSObjectList *s)\n{\n    memset(s, 0, sizeof(*s));\n}\n\nstatic uint32_t js_object_list_get_hash(JSObject *p, uint32_t hash_size)\n{\n    return ((uintptr_t)p * 3163) & (hash_size - 1);\n}\n\nstatic int js_object_list_resize_hash(JSContext *ctx, JSObjectList *s,\n                                 uint32_t new_hash_size)\n{\n    JSObjectListEntry *e;\n    uint32_t i, h, *new_hash_table;\n\n    new_hash_table = js_malloc(ctx, sizeof(new_hash_table[0]) * new_hash_size);\n    if (!new_hash_table)\n        return -1;\n    js_free(ctx, s->hash_table);\n    s->hash_table = new_hash_table;\n    s->hash_size = new_hash_size;\n    \n    for(i = 0; i < s->hash_size; i++) {\n        s->hash_table[i] = -1;\n    }\n    for(i = 0; i < s->object_count; i++) {\n        e = &s->object_tab[i];\n        h = js_object_list_get_hash(e->obj, s->hash_size); \n        e->hash_next = s->hash_table[h];\n        s->hash_table[h] = i;\n    }\n    return 0;\n}\n\n/* the reference count of 'obj' is not modified. Return 0 if OK, -1 if\n   memory error */\nstatic int js_object_list_add(JSContext *ctx, JSObjectList *s, JSObject *obj)\n{\n    JSObjectListEntry *e;\n    uint32_t h, new_hash_size;\n    \n    if (js_resize_array(ctx, (void *)&s->object_tab,\n                        sizeof(s->object_tab[0]),\n                        &s->object_size, s->object_count + 1))\n        return -1;\n    if (unlikely((s->object_count + 1) >= s->hash_size)) {\n        new_hash_size = max_uint32(s->hash_size, 4);\n        while (new_hash_size <= s->object_count)\n            new_hash_size *= 2;\n        if (js_object_list_resize_hash(ctx, s, new_hash_size))\n            return -1;\n    }\n    e = &s->object_tab[s->object_count++];\n    h = js_object_list_get_hash(obj, s->hash_size); \n    e->obj = obj;\n    e->hash_next = s->hash_table[h];\n    s->hash_table[h] = s->object_count - 1;\n    return 0;\n}\n\n/* return -1 if not present or the object index */\nstatic int js_object_list_find(JSContext *ctx, JSObjectList *s, JSObject *obj)\n{\n    JSObjectListEntry *e;\n    uint32_t h, p;\n\n    /* must test empty size because there is no hash table */\n    if (s->object_count == 0)\n        return -1;\n    h = js_object_list_get_hash(obj, s->hash_size); \n    p = s->hash_table[h];\n    while (p != -1) {\n        e = &s->object_tab[p];\n        if (e->obj == obj)\n            return p;\n        p = e->hash_next;\n    }\n    return -1;\n}\n\nstatic void js_object_list_end(JSContext *ctx, JSObjectList *s)\n{\n    js_free(ctx, s->object_tab);\n    js_free(ctx, s->hash_table);\n}\n\n/*******************************************************************/\n/* binary object writer & reader */\n\ntypedef enum BCTagEnum {\n    BC_TAG_NULL = 1,\n    BC_TAG_UNDEFINED,\n    BC_TAG_BOOL_FALSE,\n    BC_TAG_BOOL_TRUE,\n    BC_TAG_INT32,\n    BC_TAG_FLOAT64,\n    BC_TAG_STRING,\n    BC_TAG_OBJECT,\n    BC_TAG_ARRAY,\n    BC_TAG_BIG_INT,\n    BC_TAG_BIG_FLOAT,\n    BC_TAG_BIG_DECIMAL,\n    BC_TAG_TEMPLATE_OBJECT,\n    BC_TAG_FUNCTION_BYTECODE,\n    BC_TAG_MODULE,\n    BC_TAG_TYPED_ARRAY,\n    BC_TAG_ARRAY_BUFFER,\n    BC_TAG_SHARED_ARRAY_BUFFER,\n    BC_TAG_DATE,\n    BC_TAG_OBJECT_VALUE,\n    BC_TAG_OBJECT_REFERENCE,\n} BCTagEnum;\n\n#ifdef CONFIG_BIGNUM\n#define BC_BASE_VERSION 2\n#else\n#define BC_BASE_VERSION 1\n#endif\n#define BC_BE_VERSION 0x40\n#ifdef WORDS_BIGENDIAN\n#define BC_VERSION (BC_BASE_VERSION | BC_BE_VERSION)\n#else\n#define BC_VERSION BC_BASE_VERSION\n#endif\n\ntypedef struct BCWriterState {\n    JSContext *ctx;\n    DynBuf dbuf;\n    BOOL byte_swap : 8;\n    BOOL allow_bytecode : 8;\n    BOOL allow_sab : 8;\n    BOOL allow_reference : 8;\n    uint32_t first_atom;\n    uint32_t *atom_to_idx;\n    int atom_to_idx_size;\n    JSAtom *idx_to_atom;\n    int idx_to_atom_count;\n    int idx_to_atom_size;\n    uint8_t **sab_tab;\n    int sab_tab_len;\n    int sab_tab_size;\n    /* list of referenced objects (used if allow_reference = TRUE) */\n    JSObjectList object_list;\n} BCWriterState;\n\n#ifdef DUMP_READ_OBJECT\nstatic const char * const bc_tag_str[] = {\n    \"invalid\",\n    \"null\",\n    \"undefined\",\n    \"false\",\n    \"true\",\n    \"int32\",\n    \"float64\",\n    \"string\",\n    \"object\",\n    \"array\",\n    \"bigint\",\n    \"bigfloat\",\n    \"bigdecimal\",\n    \"template\",\n    \"function\",\n    \"module\",\n    \"TypedArray\",\n    \"ArrayBuffer\",\n    \"SharedArrayBuffer\",\n    \"Date\",\n    \"ObjectValue\",\n    \"ObjectReference\",\n};\n#endif\n\nstatic void bc_put_u8(BCWriterState *s, uint8_t v)\n{\n    dbuf_putc(&s->dbuf, v);\n}\n\nstatic void bc_put_u16(BCWriterState *s, uint16_t v)\n{\n    if (s->byte_swap)\n        v = bswap16(v);\n    dbuf_put_u16(&s->dbuf, v);\n}\n\nstatic __maybe_unused void bc_put_u32(BCWriterState *s, uint32_t v)\n{\n    if (s->byte_swap)\n        v = bswap32(v);\n    dbuf_put_u32(&s->dbuf, v);\n}\n\nstatic void bc_put_u64(BCWriterState *s, uint64_t v)\n{\n    if (s->byte_swap)\n        v = bswap64(v);\n    dbuf_put(&s->dbuf, (uint8_t *)&v, sizeof(v));\n}\n\nstatic void bc_put_leb128(BCWriterState *s, uint32_t v)\n{\n    dbuf_put_leb128(&s->dbuf, v);\n}\n\nstatic void bc_put_sleb128(BCWriterState *s, int32_t v)\n{\n    dbuf_put_sleb128(&s->dbuf, v);\n}\n\nstatic void bc_set_flags(uint32_t *pflags, int *pidx, uint32_t val, int n)\n{\n    *pflags = *pflags | (val << *pidx);\n    *pidx += n;\n}\n\nstatic int bc_atom_to_idx(BCWriterState *s, uint32_t *pres, JSAtom atom)\n{\n    uint32_t v;\n\n    if (atom < s->first_atom || __JS_AtomIsTaggedInt(atom)) {\n        *pres = atom;\n        return 0;\n    }\n    atom -= s->first_atom;\n    if (atom < s->atom_to_idx_size && s->atom_to_idx[atom] != 0) {\n        *pres = s->atom_to_idx[atom];\n        return 0;\n    }\n    if (atom >= s->atom_to_idx_size) {\n        int old_size, i;\n        old_size = s->atom_to_idx_size;\n        if (js_resize_array(s->ctx, (void **)&s->atom_to_idx,\n                            sizeof(s->atom_to_idx[0]), &s->atom_to_idx_size,\n                            atom + 1))\n            return -1;\n        /* XXX: could add a specific js_resize_array() function to do it */\n        for(i = old_size; i < s->atom_to_idx_size; i++)\n            s->atom_to_idx[i] = 0;\n    }\n    if (js_resize_array(s->ctx, (void **)&s->idx_to_atom,\n                        sizeof(s->idx_to_atom[0]),\n                        &s->idx_to_atom_size, s->idx_to_atom_count + 1))\n        goto fail;\n\n    v = s->idx_to_atom_count++;\n    s->idx_to_atom[v] = atom + s->first_atom;\n    v += s->first_atom;\n    s->atom_to_idx[atom] = v;\n    *pres = v;\n    return 0;\n fail:\n    *pres = 0;\n    return -1;\n}\n\nstatic int bc_put_atom(BCWriterState *s, JSAtom atom)\n{\n    uint32_t v;\n\n    if (__JS_AtomIsTaggedInt(atom)) {\n        v = (__JS_AtomToUInt32(atom) << 1) | 1;\n    } else {\n        if (bc_atom_to_idx(s, &v, atom))\n            return -1;\n        v <<= 1;\n    }\n    bc_put_leb128(s, v);\n    return 0;\n}\n\nstatic void bc_byte_swap(uint8_t *bc_buf, int bc_len)\n{\n    int pos, len, op, fmt;\n\n    pos = 0;\n    while (pos < bc_len) {\n        op = bc_buf[pos];\n        len = short_opcode_info(op).size;\n        fmt = short_opcode_info(op).fmt;\n        switch(fmt) {\n        case OP_FMT_u16:\n        case OP_FMT_i16:\n        case OP_FMT_label16:\n        case OP_FMT_npop:\n        case OP_FMT_loc:\n        case OP_FMT_arg:\n        case OP_FMT_var_ref:\n            put_u16(bc_buf + pos + 1,\n                    bswap16(get_u16(bc_buf + pos + 1)));\n            break;\n        case OP_FMT_i32:\n        case OP_FMT_u32:\n        case OP_FMT_const:\n        case OP_FMT_label:\n        case OP_FMT_atom:\n        case OP_FMT_atom_u8:\n            put_u32(bc_buf + pos + 1,\n                    bswap32(get_u32(bc_buf + pos + 1)));\n            break;\n        case OP_FMT_atom_u16:\n        case OP_FMT_label_u16:\n            put_u32(bc_buf + pos + 1,\n                    bswap32(get_u32(bc_buf + pos + 1)));\n            put_u16(bc_buf + pos + 1 + 4,\n                    bswap16(get_u16(bc_buf + pos + 1 + 4)));\n            break;\n        case OP_FMT_atom_label_u8:\n        case OP_FMT_atom_label_u16:\n            put_u32(bc_buf + pos + 1,\n                    bswap32(get_u32(bc_buf + pos + 1)));\n            put_u32(bc_buf + pos + 1 + 4,\n                    bswap32(get_u32(bc_buf + pos + 1 + 4)));\n            if (fmt == OP_FMT_atom_label_u16) {\n                put_u16(bc_buf + pos + 1 + 4 + 4,\n                        bswap16(get_u16(bc_buf + pos + 1 + 4 + 4)));\n            }\n            break;\n        case OP_FMT_npop_u16:\n            put_u16(bc_buf + pos + 1,\n                    bswap16(get_u16(bc_buf + pos + 1)));\n            put_u16(bc_buf + pos + 1 + 2,\n                    bswap16(get_u16(bc_buf + pos + 1 + 2)));\n            break;\n        default:\n            break;\n        }\n        pos += len;\n    }\n}\n\nstatic int JS_WriteFunctionBytecode(BCWriterState *s,\n                                    const uint8_t *bc_buf1, int bc_len)\n{\n    int pos, len, op;\n    JSAtom atom;\n    uint8_t *bc_buf;\n    uint32_t val;\n\n    bc_buf = js_malloc(s->ctx, bc_len);\n    if (!bc_buf)\n        return -1;\n    memcpy(bc_buf, bc_buf1, bc_len);\n\n    pos = 0;\n    while (pos < bc_len) {\n        op = bc_buf[pos];\n        len = short_opcode_info(op).size;\n        switch(short_opcode_info(op).fmt) {\n        case OP_FMT_atom:\n        case OP_FMT_atom_u8:\n        case OP_FMT_atom_u16:\n        case OP_FMT_atom_label_u8:\n        case OP_FMT_atom_label_u16:\n            atom = get_u32(bc_buf + pos + 1);\n            if (bc_atom_to_idx(s, &val, atom))\n                goto fail;\n            put_u32(bc_buf + pos + 1, val);\n            break;\n        default:\n            break;\n        }\n        pos += len;\n    }\n\n    if (s->byte_swap)\n        bc_byte_swap(bc_buf, bc_len);\n\n    dbuf_put(&s->dbuf, bc_buf, bc_len);\n\n    js_free(s->ctx, bc_buf);\n    return 0;\n fail:\n    js_free(s->ctx, bc_buf);\n    return -1;\n}\n\nstatic void JS_WriteString(BCWriterState *s, JSString *p)\n{\n    int i;\n    bc_put_leb128(s, ((uint32_t)p->len << 1) | p->is_wide_char);\n    if (p->is_wide_char) {\n        for(i = 0; i < p->len; i++)\n            bc_put_u16(s, p->u.str16[i]);\n    } else {\n        dbuf_put(&s->dbuf, p->u.str8, p->len);\n    }\n}\n\n#ifdef CONFIG_BIGNUM\nstatic int JS_WriteBigNum(BCWriterState *s, JSValueConst obj)\n{\n    uint32_t tag, tag1;\n    int64_t e;\n    JSBigFloat *bf = JS_VALUE_GET_PTR(obj);\n    bf_t *a = &bf->num;\n    size_t len, i, n1, j;\n    limb_t v;\n\n    tag = JS_VALUE_GET_TAG(obj);\n    switch(tag) {\n    case JS_TAG_BIG_INT:\n        tag1 = BC_TAG_BIG_INT;\n        break;\n    case JS_TAG_BIG_FLOAT:\n        tag1 = BC_TAG_BIG_FLOAT;\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        tag1 = BC_TAG_BIG_DECIMAL;\n        break;\n    default:\n        abort();\n    }\n    bc_put_u8(s, tag1);\n\n    /* sign + exponent */\n    if (a->expn == BF_EXP_ZERO)\n        e = 0;\n    else if (a->expn == BF_EXP_INF)\n        e = 1;\n    else if (a->expn == BF_EXP_NAN)\n        e = 2;\n    else if (a->expn >= 0)\n        e = a->expn + 3;\n    else\n        e = a->expn;\n    e = (e << 1) | a->sign;\n    if (e < INT32_MIN || e > INT32_MAX) {\n        JS_ThrowInternalError(s->ctx, \"bignum exponent is too large\");\n        return -1;\n    }\n    bc_put_sleb128(s, e);\n\n    /* mantissa */\n    if (a->len != 0) {\n        if (tag != JS_TAG_BIG_DECIMAL) {\n            i = 0;\n            while (i < a->len && a->tab[i] == 0)\n                i++;\n            assert(i < a->len);\n            v = a->tab[i];\n            n1 = sizeof(limb_t);\n            while ((v & 0xff) == 0) {\n                n1--;\n                v >>= 8;\n            }\n            i++;\n            len = (a->len - i) * sizeof(limb_t) + n1;\n            if (len > INT32_MAX) {\n                JS_ThrowInternalError(s->ctx, \"bignum is too large\");\n                return -1;\n            }\n            bc_put_leb128(s, len);\n            /* always saved in byte based little endian representation */\n            for(j = 0; j < n1; j++) {\n                dbuf_putc(&s->dbuf, v >> (j * 8));\n            }\n            for(; i < a->len; i++) {\n                limb_t v = a->tab[i];\n#if LIMB_BITS == 32\n#ifdef WORDS_BIGENDIAN\n                v = bswap32(v);\n#endif\n                dbuf_put_u32(&s->dbuf, v);\n#else\n#ifdef WORDS_BIGENDIAN\n                v = bswap64(v);\n#endif\n                dbuf_put_u64(&s->dbuf, v);\n#endif\n            }\n        } else {\n            int bpos, d;\n            uint8_t v8;\n            size_t i0;\n            \n            /* little endian BCD */\n            i = 0;\n            while (i < a->len && a->tab[i] == 0)\n                i++;\n            assert(i < a->len);\n            len = a->len * LIMB_DIGITS;\n            v = a->tab[i];\n            j = 0;\n            while ((v % 10) == 0) {\n                j++;\n                v /= 10;\n            }\n            len -= j;\n            assert(len > 0);\n            if (len > INT32_MAX) {\n                JS_ThrowInternalError(s->ctx, \"bignum is too large\");\n                return -1;\n            }\n            bc_put_leb128(s, len);\n            \n            bpos = 0;\n            v8 = 0;\n            i0 = i;\n            for(; i < a->len; i++) {\n                if (i != i0) {\n                    v = a->tab[i];\n                    j = 0;\n                }\n                for(; j < LIMB_DIGITS; j++) {\n                    d = v % 10;\n                    v /= 10;\n                    if (bpos == 0) {\n                        v8 = d;\n                        bpos = 1;\n                    } else {\n                        dbuf_putc(&s->dbuf, v8 | (d << 4));\n                        bpos = 0;\n                    }\n                }\n            }\n            /* flush the last digit */\n            if (bpos) {\n                dbuf_putc(&s->dbuf, v8);\n            }\n        }\n    }\n    return 0;\n}\n#endif /* CONFIG_BIGNUM */\n\nstatic int JS_WriteObjectRec(BCWriterState *s, JSValueConst obj);\n\nstatic int JS_WriteFunctionTag(BCWriterState *s, JSValueConst obj)\n{\n    JSFunctionBytecode *b = JS_VALUE_GET_PTR(obj);\n    uint32_t flags;\n    int idx, i;\n    \n    bc_put_u8(s, BC_TAG_FUNCTION_BYTECODE);\n    flags = idx = 0;\n    bc_set_flags(&flags, &idx, b->has_prototype, 1);\n    bc_set_flags(&flags, &idx, b->has_simple_parameter_list, 1);\n    bc_set_flags(&flags, &idx, b->is_derived_class_constructor, 1);\n    bc_set_flags(&flags, &idx, b->need_home_object, 1);\n    bc_set_flags(&flags, &idx, b->func_kind, 2);\n    bc_set_flags(&flags, &idx, b->new_target_allowed, 1);\n    bc_set_flags(&flags, &idx, b->super_call_allowed, 1);\n    bc_set_flags(&flags, &idx, b->super_allowed, 1);\n    bc_set_flags(&flags, &idx, b->arguments_allowed, 1);\n    bc_set_flags(&flags, &idx, b->has_debug, 1);\n    bc_set_flags(&flags, &idx, b->backtrace_barrier, 1);\n    assert(idx <= 16);\n    bc_put_u16(s, flags);\n    bc_put_u8(s, b->js_mode);\n    bc_put_atom(s, b->func_name);\n    \n    bc_put_leb128(s, b->arg_count);\n    bc_put_leb128(s, b->var_count);\n    bc_put_leb128(s, b->defined_arg_count);\n    bc_put_leb128(s, b->stack_size);\n    bc_put_leb128(s, b->closure_var_count);\n    bc_put_leb128(s, b->cpool_count);\n    bc_put_leb128(s, b->byte_code_len);\n    if (b->vardefs) {\n        /* XXX: this field is redundant */\n        bc_put_leb128(s, b->arg_count + b->var_count);\n        for(i = 0; i < b->arg_count + b->var_count; i++) {\n            JSVarDef *vd = &b->vardefs[i];\n            bc_put_atom(s, vd->var_name);\n            bc_put_leb128(s, vd->scope_level);\n            bc_put_leb128(s, vd->scope_next + 1);\n            flags = idx = 0;\n            bc_set_flags(&flags, &idx, vd->var_kind, 4);\n            bc_set_flags(&flags, &idx, vd->is_const, 1);\n            bc_set_flags(&flags, &idx, vd->is_lexical, 1);\n            bc_set_flags(&flags, &idx, vd->is_captured, 1);\n            assert(idx <= 8);\n            bc_put_u8(s, flags);\n        }\n    } else {\n        bc_put_leb128(s, 0);\n    }\n    \n    for(i = 0; i < b->closure_var_count; i++) {\n        JSClosureVar *cv = &b->closure_var[i];\n        bc_put_atom(s, cv->var_name);\n        bc_put_leb128(s, cv->var_idx);\n        flags = idx = 0;\n        bc_set_flags(&flags, &idx, cv->is_local, 1);\n        bc_set_flags(&flags, &idx, cv->is_arg, 1);\n        bc_set_flags(&flags, &idx, cv->is_const, 1);\n        bc_set_flags(&flags, &idx, cv->is_lexical, 1);\n        bc_set_flags(&flags, &idx, cv->var_kind, 4);\n        assert(idx <= 8);\n        bc_put_u8(s, flags);\n    }\n    \n    if (JS_WriteFunctionBytecode(s, b->byte_code_buf, b->byte_code_len))\n        goto fail;\n    \n    if (b->has_debug) {\n        bc_put_atom(s, b->debug.filename);\n        bc_put_leb128(s, b->debug.line_num);\n        bc_put_leb128(s, b->debug.pc2line_len);\n        dbuf_put(&s->dbuf, b->debug.pc2line_buf, b->debug.pc2line_len);\n    }\n    \n    for(i = 0; i < b->cpool_count; i++) {\n        if (JS_WriteObjectRec(s, b->cpool[i]))\n            goto fail;\n    }\n    return 0;\n fail:\n    return -1;\n}\n\nstatic int JS_WriteModule(BCWriterState *s, JSValueConst obj)\n{\n    JSModuleDef *m = JS_VALUE_GET_PTR(obj);\n    int i;\n    \n    bc_put_u8(s, BC_TAG_MODULE);\n    bc_put_atom(s, m->module_name);\n    \n    bc_put_leb128(s, m->req_module_entries_count);\n    for(i = 0; i < m->req_module_entries_count; i++) {\n        JSReqModuleEntry *rme = &m->req_module_entries[i];\n        bc_put_atom(s, rme->module_name);\n    }\n    \n    bc_put_leb128(s, m->export_entries_count);\n    for(i = 0; i < m->export_entries_count; i++) {\n        JSExportEntry *me = &m->export_entries[i];\n        bc_put_u8(s, me->export_type);\n        if (me->export_type == JS_EXPORT_TYPE_LOCAL) {\n            bc_put_leb128(s, me->u.local.var_idx);\n        } else {\n            bc_put_leb128(s, me->u.req_module_idx);\n            bc_put_atom(s, me->local_name);\n        }\n        bc_put_atom(s, me->export_name);\n    }\n    \n    bc_put_leb128(s, m->star_export_entries_count);\n    for(i = 0; i < m->star_export_entries_count; i++) {\n        JSStarExportEntry *se = &m->star_export_entries[i];\n        bc_put_leb128(s, se->req_module_idx);\n    }\n    \n    bc_put_leb128(s, m->import_entries_count);\n    for(i = 0; i < m->import_entries_count; i++) {\n        JSImportEntry *mi = &m->import_entries[i];\n        bc_put_leb128(s, mi->var_idx);\n        bc_put_atom(s, mi->import_name);\n        bc_put_leb128(s, mi->req_module_idx);\n    }\n    \n    if (JS_WriteObjectRec(s, m->func_obj))\n        goto fail;\n    return 0;\n fail:\n    return -1;\n}\n\nstatic int JS_WriteArray(BCWriterState *s, JSValueConst obj)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(obj);\n    uint32_t i, len;\n    JSValue val;\n    int ret;\n    BOOL is_template;\n    \n    if (s->allow_bytecode && !p->extensible) {\n        /* not extensible array: we consider it is a\n           template when we are saving bytecode */\n        bc_put_u8(s, BC_TAG_TEMPLATE_OBJECT);\n        is_template = TRUE;\n    } else {\n        bc_put_u8(s, BC_TAG_ARRAY);\n        is_template = FALSE;\n    }\n    if (js_get_length32(s->ctx, &len, obj))\n        goto fail1;\n    bc_put_leb128(s, len);\n    for(i = 0; i < len; i++) {\n        val = JS_GetPropertyUint32(s->ctx, obj, i);\n        if (JS_IsException(val))\n            goto fail1;\n        ret = JS_WriteObjectRec(s, val);\n        JS_FreeValue(s->ctx, val);\n        if (ret)\n            goto fail1;\n    }\n    if (is_template) {\n        val = JS_GetProperty(s->ctx, obj, JS_ATOM_raw);\n        if (JS_IsException(val))\n            goto fail1;\n        ret = JS_WriteObjectRec(s, val);\n        JS_FreeValue(s->ctx, val);\n        if (ret)\n            goto fail1;\n    }\n    return 0;\n fail1:\n    return -1;\n}\n\nstatic int JS_WriteObjectTag(BCWriterState *s, JSValueConst obj)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(obj);\n    uint32_t i, prop_count;\n    JSShape *sh;\n    JSShapeProperty *pr;\n    int pass;\n    JSAtom atom;\n\n    bc_put_u8(s, BC_TAG_OBJECT);\n    prop_count = 0;\n    sh = p->shape;\n    for(pass = 0; pass < 2; pass++) {\n        if (pass == 1)\n            bc_put_leb128(s, prop_count);\n        for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count; i++, pr++) {\n            atom = pr->atom;\n            if (atom != JS_ATOM_NULL &&\n                JS_AtomIsString(s->ctx, atom) &&\n                (pr->flags & JS_PROP_ENUMERABLE)) {\n                if (pr->flags & JS_PROP_TMASK) {\n                    JS_ThrowTypeError(s->ctx, \"only value properties are supported\");\n                    goto fail;\n                }\n                if (pass == 0) {\n                    prop_count++;\n                } else {\n                    bc_put_atom(s, atom);\n                    if (JS_WriteObjectRec(s, p->prop[i].u.value))\n                        goto fail;\n                }\n            }\n        }\n    }\n    return 0;\n fail:\n    return -1;\n}\n\nstatic int JS_WriteTypedArray(BCWriterState *s, JSValueConst obj)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(obj);\n    JSTypedArray *ta = p->u.typed_array;\n\n    bc_put_u8(s, BC_TAG_TYPED_ARRAY);\n    bc_put_u8(s, p->class_id - JS_CLASS_UINT8C_ARRAY);\n    bc_put_leb128(s, p->u.array.count);\n    bc_put_leb128(s, ta->offset);\n    if (JS_WriteObjectRec(s, JS_MKPTR(JS_TAG_OBJECT, ta->buffer)))\n        return -1;\n    return 0;\n}\n\nstatic int JS_WriteArrayBuffer(BCWriterState *s, JSValueConst obj)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(obj);\n    JSArrayBuffer *abuf = p->u.array_buffer;\n    if (abuf->detached) {\n        JS_ThrowTypeErrorDetachedArrayBuffer(s->ctx);\n        return -1;\n    }\n    bc_put_u8(s, BC_TAG_ARRAY_BUFFER);\n    bc_put_leb128(s, abuf->byte_length);\n    dbuf_put(&s->dbuf, abuf->data, abuf->byte_length);\n    return 0;\n}\n\nstatic int JS_WriteSharedArrayBuffer(BCWriterState *s, JSValueConst obj)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(obj);\n    JSArrayBuffer *abuf = p->u.array_buffer;\n    assert(!abuf->detached); /* SharedArrayBuffer are never detached */\n    bc_put_u8(s, BC_TAG_SHARED_ARRAY_BUFFER);\n    bc_put_leb128(s, abuf->byte_length);\n    bc_put_u64(s, (uintptr_t)abuf->data);\n    if (js_resize_array(s->ctx, (void **)&s->sab_tab, sizeof(s->sab_tab[0]),\n                        &s->sab_tab_size, s->sab_tab_len + 1))\n        return -1;\n    /* keep the SAB pointer so that the user can clone it or free it */\n    s->sab_tab[s->sab_tab_len++] = abuf->data;\n    return 0;\n}\n\nstatic int JS_WriteObjectRec(BCWriterState *s, JSValueConst obj)\n{\n    uint32_t tag;\n\n    if (js_check_stack_overflow(s->ctx->rt, 0)) {\n        JS_ThrowStackOverflow(s->ctx);\n        return -1;\n    }\n\n    tag = JS_VALUE_GET_NORM_TAG(obj);\n    switch(tag) {\n    case JS_TAG_NULL:\n        bc_put_u8(s, BC_TAG_NULL);\n        break;\n    case JS_TAG_UNDEFINED:\n        bc_put_u8(s, BC_TAG_UNDEFINED);\n        break;\n    case JS_TAG_BOOL:\n        bc_put_u8(s, BC_TAG_BOOL_FALSE + JS_VALUE_GET_INT(obj));\n        break;\n    case JS_TAG_INT:\n        bc_put_u8(s, BC_TAG_INT32);\n        bc_put_sleb128(s, JS_VALUE_GET_INT(obj));\n        break;\n    case JS_TAG_FLOAT64:\n        {\n            JSFloat64Union u;\n            bc_put_u8(s, BC_TAG_FLOAT64);\n            u.d = JS_VALUE_GET_FLOAT64(obj);\n            bc_put_u64(s, u.u64);\n        }\n        break;\n    case JS_TAG_STRING:\n        {\n            JSString *p = JS_VALUE_GET_STRING(obj);\n            bc_put_u8(s, BC_TAG_STRING);\n            JS_WriteString(s, p);\n        }\n        break;\n    case JS_TAG_FUNCTION_BYTECODE:\n        if (!s->allow_bytecode)\n            goto invalid_tag;\n        if (JS_WriteFunctionTag(s, obj))\n            goto fail;\n        break;\n    case JS_TAG_MODULE:\n        if (!s->allow_bytecode)\n            goto invalid_tag;\n        if (JS_WriteModule(s, obj))\n            goto fail;\n        break;\n    case JS_TAG_OBJECT:\n        {\n            JSObject *p = JS_VALUE_GET_OBJ(obj);\n            int ret, idx;\n            \n            if (s->allow_reference) {\n                idx = js_object_list_find(s->ctx, &s->object_list, p);\n                if (idx >= 0) {\n                    bc_put_u8(s, BC_TAG_OBJECT_REFERENCE);\n                    bc_put_leb128(s, idx);\n                    break;\n                } else {\n                    if (js_object_list_add(s->ctx, &s->object_list, p))\n                        goto fail;\n                }\n            } else {\n                if (p->tmp_mark) {\n                    JS_ThrowTypeError(s->ctx, \"circular reference\");\n                    goto fail;\n                }\n                p->tmp_mark = 1;\n            }\n            switch(p->class_id) {\n            case JS_CLASS_ARRAY:\n                ret = JS_WriteArray(s, obj);\n                break;\n            case JS_CLASS_OBJECT:\n                ret = JS_WriteObjectTag(s, obj);\n                break;\n            case JS_CLASS_ARRAY_BUFFER:\n                ret = JS_WriteArrayBuffer(s, obj);\n                break;\n            case JS_CLASS_SHARED_ARRAY_BUFFER:\n                if (!s->allow_sab)\n                    goto invalid_tag;\n                ret = JS_WriteSharedArrayBuffer(s, obj);\n                break;\n            case JS_CLASS_DATE:\n                bc_put_u8(s, BC_TAG_DATE);\n                ret = JS_WriteObjectRec(s, p->u.object_data);\n                break;\n            case JS_CLASS_NUMBER:\n            case JS_CLASS_STRING:\n            case JS_CLASS_BOOLEAN:\n#ifdef CONFIG_BIGNUM\n            case JS_CLASS_BIG_INT:\n            case JS_CLASS_BIG_FLOAT:\n            case JS_CLASS_BIG_DECIMAL:\n#endif\n                bc_put_u8(s, BC_TAG_OBJECT_VALUE);\n                ret = JS_WriteObjectRec(s, p->u.object_data);\n                break;\n            default:\n                if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n                    p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n                    ret = JS_WriteTypedArray(s, obj);\n                } else {\n                    JS_ThrowTypeError(s->ctx, \"unsupported object class\");\n                    ret = -1;\n                }\n                break;\n            }\n            p->tmp_mark = 0;\n            if (ret)\n                goto fail;\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n    case JS_TAG_BIG_FLOAT:\n    case JS_TAG_BIG_DECIMAL:\n        if (JS_WriteBigNum(s, obj))\n            goto fail;\n        break;\n#endif\n    default:\n    invalid_tag:\n        JS_ThrowInternalError(s->ctx, \"unsupported tag (%d)\", tag);\n        goto fail;\n    }\n    return 0;\n\n fail:\n    return -1;\n}\n\n/* create the atom table */\nstatic int JS_WriteObjectAtoms(BCWriterState *s)\n{\n    JSRuntime *rt = s->ctx->rt;\n    DynBuf dbuf1;\n    int i, atoms_size;\n    uint8_t version;\n\n    dbuf1 = s->dbuf;\n    js_dbuf_init(s->ctx, &s->dbuf);\n\n    version = BC_VERSION;\n    if (s->byte_swap)\n        version ^= BC_BE_VERSION;\n    bc_put_u8(s, version);\n\n    bc_put_leb128(s, s->idx_to_atom_count);\n    for(i = 0; i < s->idx_to_atom_count; i++) {\n        JSAtomStruct *p = rt->atom_array[s->idx_to_atom[i]];\n        JS_WriteString(s, p);\n    }\n    /* XXX: should check for OOM in above phase */\n\n    /* move the atoms at the start */\n    /* XXX: could just append dbuf1 data, but it uses more memory if\n       dbuf1 is larger than dbuf */\n    atoms_size = s->dbuf.size;\n    if (dbuf_realloc(&dbuf1, dbuf1.size + atoms_size))\n        goto fail;\n    memmove(dbuf1.buf + atoms_size, dbuf1.buf, dbuf1.size);\n    memcpy(dbuf1.buf, s->dbuf.buf, atoms_size);\n    dbuf1.size += atoms_size;\n    dbuf_free(&s->dbuf);\n    s->dbuf = dbuf1;\n    return 0;\n fail:\n    dbuf_free(&dbuf1);\n    return -1;\n}\n\nuint8_t *JS_WriteObject2(JSContext *ctx, size_t *psize, JSValueConst obj,\n                         int flags, uint8_t ***psab_tab, size_t *psab_tab_len)\n{\n    BCWriterState ss, *s = &ss;\n\n    memset(s, 0, sizeof(*s));\n    s->ctx = ctx;\n    /* XXX: byte swapped output is untested */\n    s->byte_swap = ((flags & JS_WRITE_OBJ_BSWAP) != 0);\n    s->allow_bytecode = ((flags & JS_WRITE_OBJ_BYTECODE) != 0);\n    s->allow_sab = ((flags & JS_WRITE_OBJ_SAB) != 0);\n    s->allow_reference = ((flags & JS_WRITE_OBJ_REFERENCE) != 0);\n    /* XXX: could use a different version when bytecode is included */\n    if (s->allow_bytecode)\n        s->first_atom = JS_ATOM_END;\n    else\n        s->first_atom = 1;\n    js_dbuf_init(ctx, &s->dbuf);\n    js_object_list_init(&s->object_list);\n    \n    if (JS_WriteObjectRec(s, obj))\n        goto fail;\n    if (JS_WriteObjectAtoms(s))\n        goto fail;\n    js_object_list_end(ctx, &s->object_list);\n    js_free(ctx, s->atom_to_idx);\n    js_free(ctx, s->idx_to_atom);\n    *psize = s->dbuf.size;\n    if (psab_tab)\n        *psab_tab = s->sab_tab;\n    if (psab_tab_len)\n        *psab_tab_len = s->sab_tab_len;\n    return s->dbuf.buf;\n fail:\n    js_object_list_end(ctx, &s->object_list);\n    js_free(ctx, s->atom_to_idx);\n    js_free(ctx, s->idx_to_atom);\n    dbuf_free(&s->dbuf);\n    *psize = 0;\n    if (psab_tab)\n        *psab_tab = NULL;\n    if (psab_tab_len)\n        *psab_tab_len = 0;\n    return NULL;\n}\n\nuint8_t *JS_WriteObject(JSContext *ctx, size_t *psize, JSValueConst obj,\n                        int flags)\n{\n    return JS_WriteObject2(ctx, psize, obj, flags, NULL, NULL);\n}\n\ntypedef struct BCReaderState {\n    JSContext *ctx;\n    const uint8_t *buf_start, *ptr, *buf_end;\n    uint32_t first_atom;\n    uint32_t idx_to_atom_count;\n    JSAtom *idx_to_atom;\n    int error_state;\n    BOOL allow_sab : 8;\n    BOOL allow_bytecode : 8;\n    BOOL is_rom_data : 8;\n    BOOL allow_reference : 8;\n    /* object references */\n    JSObject **objects;\n    int objects_count;\n    int objects_size;\n    \n#ifdef DUMP_READ_OBJECT\n    const uint8_t *ptr_last;\n    int level;\n#endif\n} BCReaderState;\n\n#ifdef DUMP_READ_OBJECT\nstatic void __attribute__((format(printf, 2, 3))) bc_read_trace(BCReaderState *s, const char *fmt, ...) {\n    va_list ap;\n    int i, n, n0;\n\n    if (!s->ptr_last)\n        s->ptr_last = s->buf_start;\n\n    n = n0 = 0;\n    if (s->ptr > s->ptr_last || s->ptr == s->buf_start) {\n        n0 = printf(\"%04x: \", (int)(s->ptr_last - s->buf_start));\n        n += n0;\n    }\n    for (i = 0; s->ptr_last < s->ptr; i++) {\n        if ((i & 7) == 0 && i > 0) {\n            printf(\"\\n%*s\", n0, \"\");\n            n = n0;\n        }\n        n += printf(\" %02x\", *s->ptr_last++);\n    }\n    if (*fmt == '}')\n        s->level--;\n    if (n < 32 + s->level * 2) {\n        printf(\"%*s\", 32 + s->level * 2 - n, \"\");\n    }\n    va_start(ap, fmt);\n    vfprintf(stdout, fmt, ap);\n    va_end(ap);\n    if (strchr(fmt, '{'))\n        s->level++;\n}\n#else\n#define bc_read_trace(...)\n#endif\n\nstatic int bc_read_error_end(BCReaderState *s)\n{\n    if (!s->error_state) {\n        JS_ThrowSyntaxError(s->ctx, \"read after the end of the buffer\");\n    }\n    return s->error_state = -1;\n}\n\nstatic int bc_get_u8(BCReaderState *s, uint8_t *pval)\n{\n    if (unlikely(s->buf_end - s->ptr < 1)) {\n        *pval = 0; /* avoid warning */\n        return bc_read_error_end(s);\n    }\n    *pval = *s->ptr++;\n    return 0;\n}\n\nstatic int bc_get_u16(BCReaderState *s, uint16_t *pval)\n{\n    if (unlikely(s->buf_end - s->ptr < 2)) {\n        *pval = 0; /* avoid warning */\n        return bc_read_error_end(s);\n    }\n    *pval = get_u16(s->ptr);\n    s->ptr += 2;\n    return 0;\n}\n\nstatic __maybe_unused int bc_get_u32(BCReaderState *s, uint32_t *pval)\n{\n    if (unlikely(s->buf_end - s->ptr < 4)) {\n        *pval = 0; /* avoid warning */\n        return bc_read_error_end(s);\n    }\n    *pval = get_u32(s->ptr);\n    s->ptr += 4;\n    return 0;\n}\n\nstatic int bc_get_u64(BCReaderState *s, uint64_t *pval)\n{\n    if (unlikely(s->buf_end - s->ptr < 8)) {\n        *pval = 0; /* avoid warning */\n        return bc_read_error_end(s);\n    }\n    *pval = get_u64(s->ptr);\n    s->ptr += 8;\n    return 0;\n}\n\nstatic int bc_get_leb128(BCReaderState *s, uint32_t *pval)\n{\n    int ret;\n    ret = get_leb128(pval, s->ptr, s->buf_end);\n    if (unlikely(ret < 0))\n        return bc_read_error_end(s);\n    s->ptr += ret;\n    return 0;\n}\n\nstatic int bc_get_sleb128(BCReaderState *s, int32_t *pval)\n{\n    int ret;\n    ret = get_sleb128(pval, s->ptr, s->buf_end);\n    if (unlikely(ret < 0))\n        return bc_read_error_end(s);\n    s->ptr += ret;\n    return 0;\n}\n\n/* XXX: used to read an `int` with a positive value */\nstatic int bc_get_leb128_int(BCReaderState *s, int *pval)\n{\n    return bc_get_leb128(s, (uint32_t *)pval);\n}\n\nstatic int bc_get_leb128_u16(BCReaderState *s, uint16_t *pval)\n{\n    uint32_t val;\n    if (bc_get_leb128(s, &val)) {\n        *pval = 0;\n        return -1;\n    }\n    *pval = val;\n    return 0;\n}\n\nstatic int bc_get_buf(BCReaderState *s, uint8_t *buf, uint32_t buf_len)\n{\n    if (buf_len != 0) {\n        if (unlikely(!buf || s->buf_end - s->ptr < buf_len))\n            return bc_read_error_end(s);\n        memcpy(buf, s->ptr, buf_len);\n        s->ptr += buf_len;\n    }\n    return 0;\n}\n\nstatic int bc_idx_to_atom(BCReaderState *s, JSAtom *patom, uint32_t idx)\n{\n    JSAtom atom;\n\n    if (__JS_AtomIsTaggedInt(idx)) {\n        atom = idx;\n    } else if (idx < s->first_atom) {\n        atom = JS_DupAtom(s->ctx, idx);\n    } else {\n        idx -= s->first_atom;\n        if (idx >= s->idx_to_atom_count) {\n            JS_ThrowSyntaxError(s->ctx, \"invalid atom index (pos=%u)\",\n                                (unsigned int)(s->ptr - s->buf_start));\n            *patom = JS_ATOM_NULL;\n            return s->error_state = -1;\n        }\n        atom = JS_DupAtom(s->ctx, s->idx_to_atom[idx]);\n    }\n    *patom = atom;\n    return 0;\n}\n\nstatic int bc_get_atom(BCReaderState *s, JSAtom *patom)\n{\n    uint32_t v;\n    if (bc_get_leb128(s, &v))\n        return -1;\n    if (v & 1) {\n        *patom = __JS_AtomFromUInt32(v >> 1);\n        return 0;\n    } else {\n        return bc_idx_to_atom(s, patom, v >> 1);\n    }\n}\n\nstatic JSString *JS_ReadString(BCReaderState *s)\n{\n    uint32_t len;\n    size_t size;\n    BOOL is_wide_char;\n    JSString *p;\n\n    if (bc_get_leb128(s, &len))\n        return NULL;\n    is_wide_char = len & 1;\n    len >>= 1;\n    p = js_alloc_string(s->ctx, len, is_wide_char);\n    if (!p) {\n        s->error_state = -1;\n        return NULL;\n    }\n    size = (size_t)len << is_wide_char;\n    if ((s->buf_end - s->ptr) < size) {\n        bc_read_error_end(s);\n        js_free_string(s->ctx->rt, p);\n        return NULL;\n    }\n    memcpy(p->u.str8, s->ptr, size);\n    s->ptr += size;\n    if (!is_wide_char) {\n        p->u.str8[size] = '\\0'; /* add the trailing zero for 8 bit strings */\n    }\n#ifdef DUMP_READ_OBJECT\n    JS_DumpString(s->ctx->rt, p); printf(\"\\n\");\n#endif\n    return p;\n}\n\nstatic uint32_t bc_get_flags(uint32_t flags, int *pidx, int n)\n{\n    uint32_t val;\n    /* XXX: this does not work for n == 32 */\n    val = (flags >> *pidx) & ((1U << n) - 1);\n    *pidx += n;\n    return val;\n}\n\nstatic int JS_ReadFunctionBytecode(BCReaderState *s, JSFunctionBytecode *b,\n                                   int byte_code_offset, uint32_t bc_len)\n{\n    uint8_t *bc_buf;\n    int pos, len, op;\n    JSAtom atom;\n    uint32_t idx;\n\n    if (s->is_rom_data) {\n        /* directly use the input buffer */\n        if (unlikely(s->buf_end - s->ptr < bc_len))\n            return bc_read_error_end(s);\n        bc_buf = (uint8_t *)s->ptr;\n        s->ptr += bc_len;\n    } else {\n        bc_buf = (void *)((uint8_t*)b + byte_code_offset);\n        if (bc_get_buf(s, bc_buf, bc_len))\n            return -1;\n    }\n    b->byte_code_buf = bc_buf;\n\n    pos = 0;\n    while (pos < bc_len) {\n        op = bc_buf[pos];\n        len = short_opcode_info(op).size;\n        switch(short_opcode_info(op).fmt) {\n        case OP_FMT_atom:\n        case OP_FMT_atom_u8:\n        case OP_FMT_atom_u16:\n        case OP_FMT_atom_label_u8:\n        case OP_FMT_atom_label_u16:\n            idx = get_u32(bc_buf + pos + 1);\n            if (s->is_rom_data) {\n                /* just increment the reference count of the atom */\n                JS_DupAtom(s->ctx, (JSAtom)idx);\n            } else {\n                if (bc_idx_to_atom(s, &atom, idx)) {\n                    /* Note: the atoms will be freed up to this position */\n                    b->byte_code_len = pos;\n                    return -1;\n                }\n                put_u32(bc_buf + pos + 1, atom);\n#ifdef DUMP_READ_OBJECT\n                bc_read_trace(s, \"at %d, fixup atom: \", pos + 1); print_atom(s->ctx, atom); printf(\"\\n\");\n#endif\n            }\n            break;\n        default:\n            break;\n        }\n        pos += len;\n    }\n    return 0;\n}\n\n#ifdef CONFIG_BIGNUM\nstatic JSValue JS_ReadBigNum(BCReaderState *s, int tag)\n{\n    JSValue obj = JS_UNDEFINED;\n    uint8_t v8;\n    int32_t e;\n    uint32_t len;\n    limb_t l, i, n, j;\n    JSBigFloat *p;\n    limb_t v;\n    bf_t *a;\n    int bpos, d;\n    \n    p = js_new_bf(s->ctx);\n    if (!p)\n        goto fail;\n    switch(tag) {\n    case BC_TAG_BIG_INT:\n        obj = JS_MKPTR(JS_TAG_BIG_INT, p);\n        break;\n    case BC_TAG_BIG_FLOAT:\n        obj = JS_MKPTR(JS_TAG_BIG_FLOAT, p);\n        break;\n    case BC_TAG_BIG_DECIMAL:\n        obj = JS_MKPTR(JS_TAG_BIG_DECIMAL, p);\n        break;\n    default:\n        abort();\n    }\n\n    /* sign + exponent */\n    if (bc_get_sleb128(s, &e))\n        goto fail;\n\n    a = &p->num;\n    a->sign = e & 1;\n    e >>= 1;\n    if (e == 0)\n        a->expn = BF_EXP_ZERO;\n    else if (e == 1)\n        a->expn = BF_EXP_INF;\n    else if (e == 2)\n        a->expn = BF_EXP_NAN;\n    else if (e >= 3)\n        a->expn = e - 3;\n    else\n        a->expn = e;\n\n    /* mantissa */\n    if (a->expn != BF_EXP_ZERO &&\n        a->expn != BF_EXP_INF &&\n        a->expn != BF_EXP_NAN) {\n        if (bc_get_leb128(s, &len))\n            goto fail;\n        bc_read_trace(s, \"len=%\" PRId64 \"\\n\", (int64_t)len);\n        if (len == 0) {\n            JS_ThrowInternalError(s->ctx, \"invalid bignum length\");\n            goto fail;\n        }\n        if (tag != BC_TAG_BIG_DECIMAL)\n            l = (len + sizeof(limb_t) - 1) / sizeof(limb_t);\n        else\n            l = (len + LIMB_DIGITS - 1) / LIMB_DIGITS;\n        if (bf_resize(a, l)) {\n            JS_ThrowOutOfMemory(s->ctx);\n            goto fail;\n        }\n        if (tag != BC_TAG_BIG_DECIMAL) {\n            n = len & (sizeof(limb_t) - 1);\n            if (n != 0) {\n                v = 0;\n                for(i = 0; i < n; i++) {\n                    if (bc_get_u8(s, &v8))\n                        goto fail;\n                    v |= (limb_t)v8 << ((sizeof(limb_t) - n + i) * 8);\n                }\n                a->tab[0] = v;\n                i = 1;\n            } else {\n                i = 0;\n            }\n            for(; i < l; i++) {\n#if LIMB_BITS == 32\n                if (bc_get_u32(s, &v))\n                    goto fail;\n#ifdef WORDS_BIGENDIAN\n                v = bswap32(v);\n#endif\n#else\n                if (bc_get_u64(s, &v))\n                    goto fail;\n#ifdef WORDS_BIGENDIAN\n                v = bswap64(v);\n#endif\n#endif\n                a->tab[i] = v;\n            }\n        } else {\n            bpos = 0;\n            for(i = 0; i < l; i++) {\n                if (i == 0 && (n = len % LIMB_DIGITS) != 0) {\n                    j = LIMB_DIGITS - n;\n                } else {\n                    j = 0;\n                }\n                v = 0;\n                for(; j < LIMB_DIGITS; j++) {\n                    if (bpos == 0) {\n                        if (bc_get_u8(s, &v8))\n                            goto fail;\n                        d = v8 & 0xf;\n                        bpos = 1;\n                    } else {\n                        d = v8 >> 4;\n                        bpos = 0;\n                    }\n                    if (d >= 10) {\n                        JS_ThrowInternalError(s->ctx, \"invalid digit\");\n                        goto fail;\n                    }\n                    v += mp_pow_dec[j] * d;\n                }\n                a->tab[i] = v;\n            }\n        }\n    }\n    bc_read_trace(s, \"}\\n\");\n    return obj;\n fail:\n    JS_FreeValue(s->ctx, obj);\n    return JS_EXCEPTION;\n}\n#endif /* CONFIG_BIGNUM */\n\nstatic JSValue JS_ReadObjectRec(BCReaderState *s);\n\nstatic int BC_add_object_ref1(BCReaderState *s, JSObject *p)\n{\n    if (s->allow_reference) {\n        if (js_resize_array(s->ctx, (void *)&s->objects,\n                            sizeof(s->objects[0]),\n                            &s->objects_size, s->objects_count + 1))\n            return -1;\n        s->objects[s->objects_count++] = p;\n    }\n    return 0;\n}\n\nstatic int BC_add_object_ref(BCReaderState *s, JSValueConst obj)\n{\n    return BC_add_object_ref1(s, JS_VALUE_GET_OBJ(obj));\n}\n\nstatic JSValue JS_ReadFunctionTag(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSFunctionBytecode bc, *b;\n    JSValue obj = JS_UNDEFINED;\n    uint16_t v16;\n    uint8_t v8;\n    int idx, i, local_count;\n    int function_size, cpool_offset, byte_code_offset;\n    int closure_var_offset, vardefs_offset;\n\n    memset(&bc, 0, sizeof(bc));\n    bc.header.ref_count = 1;\n    //bc.gc_header.mark = 0;\n\n    if (bc_get_u16(s, &v16))\n        goto fail;\n    idx = 0;\n    bc.has_prototype = bc_get_flags(v16, &idx, 1);\n    bc.has_simple_parameter_list = bc_get_flags(v16, &idx, 1);\n    bc.is_derived_class_constructor = bc_get_flags(v16, &idx, 1);\n    bc.need_home_object = bc_get_flags(v16, &idx, 1);\n    bc.func_kind = bc_get_flags(v16, &idx, 2);\n    bc.new_target_allowed = bc_get_flags(v16, &idx, 1);\n    bc.super_call_allowed = bc_get_flags(v16, &idx, 1);\n    bc.super_allowed = bc_get_flags(v16, &idx, 1);\n    bc.arguments_allowed = bc_get_flags(v16, &idx, 1);\n    bc.has_debug = bc_get_flags(v16, &idx, 1);\n    bc.backtrace_barrier = bc_get_flags(v16, &idx, 1);\n    bc.read_only_bytecode = s->is_rom_data;\n    if (bc_get_u8(s, &v8))\n        goto fail;\n    bc.js_mode = v8;\n    if (bc_get_atom(s, &bc.func_name))  //@ atom leak if failure\n        goto fail;\n    if (bc_get_leb128_u16(s, &bc.arg_count))\n        goto fail;\n    if (bc_get_leb128_u16(s, &bc.var_count))\n        goto fail;\n    if (bc_get_leb128_u16(s, &bc.defined_arg_count))\n        goto fail;\n    if (bc_get_leb128_u16(s, &bc.stack_size))\n        goto fail;\n    if (bc_get_leb128_int(s, &bc.closure_var_count))\n        goto fail;\n    if (bc_get_leb128_int(s, &bc.cpool_count))\n        goto fail;\n    if (bc_get_leb128_int(s, &bc.byte_code_len))\n        goto fail;\n    if (bc_get_leb128_int(s, &local_count))\n        goto fail;\n\n    if (bc.has_debug) {\n        function_size = sizeof(*b);\n    } else {\n        function_size = offsetof(JSFunctionBytecode, debug);\n    }\n    cpool_offset = function_size;\n    function_size += bc.cpool_count * sizeof(*bc.cpool);\n    vardefs_offset = function_size;\n    function_size += local_count * sizeof(*bc.vardefs);\n    closure_var_offset = function_size;\n    function_size += bc.closure_var_count * sizeof(*bc.closure_var);\n    byte_code_offset = function_size;\n    if (!bc.read_only_bytecode) {\n        function_size += bc.byte_code_len;\n    }\n\n    b = js_mallocz(ctx, function_size);\n    if (!b)\n        return JS_EXCEPTION;\n            \n    memcpy(b, &bc, offsetof(JSFunctionBytecode, debug));\n    b->header.ref_count = 1;\n    if (local_count != 0) {\n        b->vardefs = (void *)((uint8_t*)b + vardefs_offset);\n    }\n    if (b->closure_var_count != 0) {\n        b->closure_var = (void *)((uint8_t*)b + closure_var_offset);\n    }\n    if (b->cpool_count != 0) {\n        b->cpool = (void *)((uint8_t*)b + cpool_offset);\n    }\n    \n    add_gc_object(ctx->rt, &b->header, JS_GC_OBJ_TYPE_FUNCTION_BYTECODE);\n            \n    obj = JS_MKPTR(JS_TAG_FUNCTION_BYTECODE, b);\n\n#ifdef DUMP_READ_OBJECT\n    bc_read_trace(s, \"name: \"); print_atom(s->ctx, b->func_name); printf(\"\\n\");\n#endif\n    bc_read_trace(s, \"args=%d vars=%d defargs=%d closures=%d cpool=%d\\n\",\n                  b->arg_count, b->var_count, b->defined_arg_count,\n                  b->closure_var_count, b->cpool_count);\n    bc_read_trace(s, \"stack=%d bclen=%d locals=%d\\n\",\n                  b->stack_size, b->byte_code_len, local_count);\n\n    if (local_count != 0) {\n        bc_read_trace(s, \"vars {\\n\");\n        for(i = 0; i < local_count; i++) {\n            JSVarDef *vd = &b->vardefs[i];\n            if (bc_get_atom(s, &vd->var_name))\n                goto fail;\n            if (bc_get_leb128_int(s, &vd->scope_level))\n                goto fail;\n            if (bc_get_leb128_int(s, &vd->scope_next))\n                goto fail;\n            vd->scope_next--;\n            if (bc_get_u8(s, &v8))\n                goto fail;\n            idx = 0;\n            vd->var_kind = bc_get_flags(v8, &idx, 4);\n            vd->is_const = bc_get_flags(v8, &idx, 1);\n            vd->is_lexical = bc_get_flags(v8, &idx, 1);\n            vd->is_captured = bc_get_flags(v8, &idx, 1);\n#ifdef DUMP_READ_OBJECT\n            bc_read_trace(s, \"name: \"); print_atom(s->ctx, vd->var_name); printf(\"\\n\");\n#endif\n        }\n        bc_read_trace(s, \"}\\n\");\n    }\n    if (b->closure_var_count != 0) {\n        bc_read_trace(s, \"closure vars {\\n\");\n        for(i = 0; i < b->closure_var_count; i++) {\n            JSClosureVar *cv = &b->closure_var[i];\n            int var_idx;\n            if (bc_get_atom(s, &cv->var_name))\n                goto fail;\n            if (bc_get_leb128_int(s, &var_idx))\n                goto fail;\n            cv->var_idx = var_idx;\n            if (bc_get_u8(s, &v8))\n                goto fail;\n            idx = 0;\n            cv->is_local = bc_get_flags(v8, &idx, 1);\n            cv->is_arg = bc_get_flags(v8, &idx, 1);\n            cv->is_const = bc_get_flags(v8, &idx, 1);\n            cv->is_lexical = bc_get_flags(v8, &idx, 1);\n            cv->var_kind = bc_get_flags(v8, &idx, 4);\n#ifdef DUMP_READ_OBJECT\n            bc_read_trace(s, \"name: \"); print_atom(s->ctx, cv->var_name); printf(\"\\n\");\n#endif\n        }\n        bc_read_trace(s, \"}\\n\");\n    }\n    {\n        bc_read_trace(s, \"bytecode {\\n\");\n        if (JS_ReadFunctionBytecode(s, b, byte_code_offset, b->byte_code_len))\n            goto fail;\n        bc_read_trace(s, \"}\\n\");\n    }\n    if (b->has_debug) {\n        /* read optional debug information */\n        bc_read_trace(s, \"debug {\\n\");\n        if (bc_get_atom(s, &b->debug.filename))\n            goto fail;\n        if (bc_get_leb128_int(s, &b->debug.line_num))\n            goto fail;\n        if (bc_get_leb128_int(s, &b->debug.pc2line_len))\n            goto fail;\n        if (b->debug.pc2line_len) {\n            b->debug.pc2line_buf = js_mallocz(ctx, b->debug.pc2line_len);\n            if (!b->debug.pc2line_buf)\n                goto fail;\n            if (bc_get_buf(s, b->debug.pc2line_buf, b->debug.pc2line_len))\n                goto fail;\n        }\n#ifdef DUMP_READ_OBJECT\n        bc_read_trace(s, \"filename: \"); print_atom(s->ctx, b->debug.filename); printf(\"\\n\");\n#endif\n        bc_read_trace(s, \"}\\n\");\n    }\n    if (b->cpool_count != 0) {\n        bc_read_trace(s, \"cpool {\\n\");\n        for(i = 0; i < b->cpool_count; i++) {\n            JSValue val;\n            val = JS_ReadObjectRec(s);\n            if (JS_IsException(val))\n                goto fail;\n            b->cpool[i] = val;\n        }\n        bc_read_trace(s, \"}\\n\");\n    }\n    b->realm = JS_DupContext(ctx);\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadModule(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSValue obj;\n    JSModuleDef *m = NULL;\n    JSAtom module_name;\n    int i;\n    uint8_t v8;\n    \n    if (bc_get_atom(s, &module_name))\n        goto fail;\n#ifdef DUMP_READ_OBJECT\n    bc_read_trace(s, \"name: \"); print_atom(s->ctx, module_name); printf(\"\\n\");\n#endif\n    m = js_new_module_def(ctx, module_name);\n    if (!m)\n        goto fail;\n    obj = JS_DupValue(ctx, JS_MKPTR(JS_TAG_MODULE, m));\n    if (bc_get_leb128_int(s, &m->req_module_entries_count))\n        goto fail;\n    if (m->req_module_entries_count != 0) {\n        m->req_module_entries_size = m->req_module_entries_count;\n        m->req_module_entries = js_mallocz(ctx, sizeof(m->req_module_entries[0]) * m->req_module_entries_size);\n        if (!m->req_module_entries)\n            goto fail;\n        for(i = 0; i < m->req_module_entries_count; i++) {\n            JSReqModuleEntry *rme = &m->req_module_entries[i];\n            if (bc_get_atom(s, &rme->module_name))\n                goto fail;\n        }\n    }\n\n    if (bc_get_leb128_int(s, &m->export_entries_count))\n        goto fail;\n    if (m->export_entries_count != 0) {\n        m->export_entries_size = m->export_entries_count;\n        m->export_entries = js_mallocz(ctx, sizeof(m->export_entries[0]) * m->export_entries_size);\n        if (!m->export_entries)\n            goto fail;\n        for(i = 0; i < m->export_entries_count; i++) {\n            JSExportEntry *me = &m->export_entries[i];\n            if (bc_get_u8(s, &v8))\n                goto fail;\n            me->export_type = v8;\n            if (me->export_type == JS_EXPORT_TYPE_LOCAL) {\n                if (bc_get_leb128_int(s, &me->u.local.var_idx))\n                    goto fail;\n            } else {\n                if (bc_get_leb128_int(s, &me->u.req_module_idx))\n                    goto fail;\n                if (bc_get_atom(s, &me->local_name))\n                    goto fail;\n            }\n            if (bc_get_atom(s, &me->export_name))\n                goto fail;\n        }\n    }\n\n    if (bc_get_leb128_int(s, &m->star_export_entries_count))\n        goto fail;\n    if (m->star_export_entries_count != 0) {\n        m->star_export_entries_size = m->star_export_entries_count;\n        m->star_export_entries = js_mallocz(ctx, sizeof(m->star_export_entries[0]) * m->star_export_entries_size);\n        if (!m->star_export_entries)\n            goto fail;\n        for(i = 0; i < m->star_export_entries_count; i++) {\n            JSStarExportEntry *se = &m->star_export_entries[i];\n            if (bc_get_leb128_int(s, &se->req_module_idx))\n                goto fail;\n        }\n    }\n\n    if (bc_get_leb128_int(s, &m->import_entries_count))\n        goto fail;\n    if (m->import_entries_count != 0) {\n        m->import_entries_size = m->import_entries_count;\n        m->import_entries = js_mallocz(ctx, sizeof(m->import_entries[0]) * m->import_entries_size);\n        if (!m->import_entries)\n            goto fail;\n        for(i = 0; i < m->import_entries_count; i++) {\n            JSImportEntry *mi = &m->import_entries[i];\n            if (bc_get_leb128_int(s, &mi->var_idx))\n                goto fail;\n            if (bc_get_atom(s, &mi->import_name))\n                goto fail;\n            if (bc_get_leb128_int(s, &mi->req_module_idx))\n                goto fail;\n        }\n    }\n\n    m->func_obj = JS_ReadObjectRec(s);\n    if (JS_IsException(m->func_obj))\n        goto fail;\n    return obj;\n fail:\n    if (m) {\n        js_free_module_def(ctx, m);\n    }\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadObjectTag(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSValue obj;\n    uint32_t prop_count, i;\n    JSAtom atom;\n    JSValue val;\n    int ret;\n    \n    obj = JS_NewObject(ctx);\n    if (BC_add_object_ref(s, obj))\n        goto fail;\n    if (bc_get_leb128(s, &prop_count))\n        goto fail;\n    for(i = 0; i < prop_count; i++) {\n        if (bc_get_atom(s, &atom))\n            goto fail;\n#ifdef DUMP_READ_OBJECT\n        bc_read_trace(s, \"propname: \"); print_atom(s->ctx, atom); printf(\"\\n\");\n#endif\n        val = JS_ReadObjectRec(s);\n        if (JS_IsException(val)) {\n            JS_FreeAtom(ctx, atom);\n            goto fail;\n        }\n        ret = JS_DefinePropertyValue(ctx, obj, atom, val, JS_PROP_C_W_E);\n        JS_FreeAtom(ctx, atom);\n        if (ret < 0)\n            goto fail;\n    }\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadArray(BCReaderState *s, int tag)\n{\n    JSContext *ctx = s->ctx;\n    JSValue obj;\n    uint32_t len, i;\n    JSValue val;\n    int ret, prop_flags;\n    BOOL is_template;\n\n    obj = JS_NewArray(ctx);\n    if (BC_add_object_ref(s, obj))\n        goto fail;\n    is_template = (tag == BC_TAG_TEMPLATE_OBJECT);\n    if (bc_get_leb128(s, &len))\n        goto fail;\n    for(i = 0; i < len; i++) {\n        val = JS_ReadObjectRec(s);\n        if (JS_IsException(val))\n            goto fail;\n        if (is_template)\n            prop_flags = JS_PROP_ENUMERABLE;\n        else\n            prop_flags = JS_PROP_C_W_E;\n        ret = JS_DefinePropertyValueUint32(ctx, obj, i, val,\n                                           prop_flags);\n        if (ret < 0)\n            goto fail;\n    }\n    if (is_template) {\n        val = JS_ReadObjectRec(s);\n        if (JS_IsException(val))\n            goto fail;\n        if (!JS_IsUndefined(val)) {\n            ret = JS_DefinePropertyValue(ctx, obj, JS_ATOM_raw, val, 0);\n            if (ret < 0)\n                goto fail;\n        }\n        JS_PreventExtensions(ctx, obj);\n    }\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadTypedArray(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSValue obj = JS_UNDEFINED, array_buffer = JS_UNDEFINED;\n    uint8_t array_tag;\n    JSValueConst args[3];\n    uint32_t offset, len, idx;\n    \n    if (bc_get_u8(s, &array_tag))\n        return JS_EXCEPTION;\n    if (array_tag >= JS_TYPED_ARRAY_COUNT)\n        return JS_ThrowTypeError(ctx, \"invalid typed array\");\n    if (bc_get_leb128(s, &len))\n        return JS_EXCEPTION;\n    if (bc_get_leb128(s, &offset))\n        return JS_EXCEPTION;\n    /* XXX: this hack could be avoided if the typed array could be\n       created before the array buffer */\n    idx = s->objects_count;\n    if (BC_add_object_ref1(s, NULL))\n        goto fail;\n    array_buffer = JS_ReadObjectRec(s);\n    if (JS_IsException(array_buffer))\n        return JS_EXCEPTION;\n    if (!js_get_array_buffer(ctx, array_buffer)) {\n        JS_FreeValue(ctx, array_buffer);\n        return JS_EXCEPTION;\n    }\n    args[0] = array_buffer;\n    args[1] = JS_NewInt64(ctx, offset);\n    args[2] = JS_NewInt64(ctx, len);\n    obj = js_typed_array_constructor(ctx, JS_UNDEFINED,\n                                     3, args,\n                                     JS_CLASS_UINT8C_ARRAY + array_tag);\n    if (JS_IsException(obj))\n        goto fail;\n    if (s->allow_reference) {\n        s->objects[idx] = JS_VALUE_GET_OBJ(obj);\n    }\n    JS_FreeValue(ctx, array_buffer);\n    return obj;\n fail:\n    JS_FreeValue(ctx, array_buffer);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadArrayBuffer(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    uint32_t byte_length;\n    JSValue obj;\n    \n    if (bc_get_leb128(s, &byte_length))\n        return JS_EXCEPTION;\n    if (unlikely(s->buf_end - s->ptr < byte_length)) {\n        bc_read_error_end(s);\n        return JS_EXCEPTION;\n    }\n    obj = JS_NewArrayBufferCopy(ctx, s->ptr, byte_length);\n    if (JS_IsException(obj))\n        goto fail;\n    if (BC_add_object_ref(s, obj))\n        goto fail;\n    s->ptr += byte_length;\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadSharedArrayBuffer(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    uint32_t byte_length;\n    uint8_t *data_ptr;\n    JSValue obj;\n    uint64_t u64;\n    \n    if (bc_get_leb128(s, &byte_length))\n        return JS_EXCEPTION;\n    if (bc_get_u64(s, &u64))\n        return JS_EXCEPTION;\n    data_ptr = (uint8_t *)(uintptr_t)u64;\n    /* the SharedArrayBuffer is cloned */\n    obj = js_array_buffer_constructor3(ctx, JS_UNDEFINED, byte_length,\n                                       JS_CLASS_SHARED_ARRAY_BUFFER,\n                                       data_ptr,\n                                       NULL, NULL, FALSE);\n    if (JS_IsException(obj))\n        goto fail;\n    if (BC_add_object_ref(s, obj))\n        goto fail;\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadDate(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSValue val, obj = JS_UNDEFINED;\n\n    val = JS_ReadObjectRec(s);\n    if (JS_IsException(val))\n        goto fail;\n    if (!JS_IsNumber(val)) {\n        JS_ThrowTypeError(ctx, \"Number tag expected for date\");\n        goto fail;\n    }\n    obj = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_DATE],\n                                 JS_CLASS_DATE);\n    if (JS_IsException(obj))\n        goto fail;\n    if (BC_add_object_ref(s, obj))\n        goto fail;\n    JS_SetObjectData(ctx, obj, val);\n    return obj;\n fail:\n    JS_FreeValue(ctx, val);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadObjectValue(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSValue val, obj = JS_UNDEFINED;\n\n    val = JS_ReadObjectRec(s);\n    if (JS_IsException(val))\n        goto fail;\n    obj = JS_ToObject(ctx, val);\n    if (JS_IsException(obj))\n        goto fail;\n    if (BC_add_object_ref(s, obj))\n        goto fail;\n    JS_FreeValue(ctx, val);\n    return obj;\n fail:\n    JS_FreeValue(ctx, val);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadObjectRec(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    uint8_t tag;\n    JSValue obj = JS_UNDEFINED;\n\n    if (js_check_stack_overflow(ctx->rt, 0))\n        return JS_ThrowStackOverflow(ctx);\n\n    if (bc_get_u8(s, &tag))\n        return JS_EXCEPTION;\n\n    bc_read_trace(s, \"%s {\\n\", bc_tag_str[tag]);\n\n    switch(tag) {\n    case BC_TAG_NULL:\n        obj = JS_NULL;\n        break;\n    case BC_TAG_UNDEFINED:\n        obj = JS_UNDEFINED;\n        break;\n    case BC_TAG_BOOL_FALSE:\n    case BC_TAG_BOOL_TRUE:\n        obj = JS_NewBool(ctx, tag - BC_TAG_BOOL_FALSE);\n        break;\n    case BC_TAG_INT32:\n        {\n            int32_t val;\n            if (bc_get_sleb128(s, &val))\n                return JS_EXCEPTION;\n            bc_read_trace(s, \"%d\\n\", val);\n            obj = JS_NewInt32(ctx, val);\n        }\n        break;\n    case BC_TAG_FLOAT64:\n        {\n            JSFloat64Union u;\n            if (bc_get_u64(s, &u.u64))\n                return JS_EXCEPTION;\n            bc_read_trace(s, \"%g\\n\", u.d);\n            obj = __JS_NewFloat64(ctx, u.d);\n        }\n        break;\n    case BC_TAG_STRING:\n        {\n            JSString *p;\n            p = JS_ReadString(s);\n            if (!p)\n                return JS_EXCEPTION;\n            obj = JS_MKPTR(JS_TAG_STRING, p);\n        }\n        break;\n    case BC_TAG_FUNCTION_BYTECODE:\n        if (!s->allow_bytecode)\n            goto invalid_tag;\n        obj = JS_ReadFunctionTag(s);\n        break;\n    case BC_TAG_MODULE:\n        if (!s->allow_bytecode)\n            goto invalid_tag;\n        obj = JS_ReadModule(s);\n        break;\n    case BC_TAG_OBJECT:\n        obj = JS_ReadObjectTag(s);\n        break;\n    case BC_TAG_ARRAY:\n    case BC_TAG_TEMPLATE_OBJECT:\n        obj = JS_ReadArray(s, tag);\n        break;\n    case BC_TAG_TYPED_ARRAY:\n        obj = JS_ReadTypedArray(s);\n        break;\n    case BC_TAG_ARRAY_BUFFER:\n        obj = JS_ReadArrayBuffer(s);\n        break;\n    case BC_TAG_SHARED_ARRAY_BUFFER:\n        if (!s->allow_sab || !ctx->rt->sab_funcs.sab_dup)\n            goto invalid_tag;\n        obj = JS_ReadSharedArrayBuffer(s);\n        break;\n    case BC_TAG_DATE:\n        obj = JS_ReadDate(s);\n        break;\n    case BC_TAG_OBJECT_VALUE:\n        obj = JS_ReadObjectValue(s);\n        break;\n#ifdef CONFIG_BIGNUM\n    case BC_TAG_BIG_INT:\n    case BC_TAG_BIG_FLOAT:\n    case BC_TAG_BIG_DECIMAL:\n        obj = JS_ReadBigNum(s, tag);\n        break;\n#endif\n    case BC_TAG_OBJECT_REFERENCE:\n        {\n            uint32_t val;\n            if (!s->allow_reference)\n                return JS_ThrowSyntaxError(ctx, \"object references are not allowed\");\n            if (bc_get_leb128(s, &val))\n                return JS_EXCEPTION;\n            bc_read_trace(s, \"%u\\n\", val);\n            if (val >= s->objects_count) {\n                return JS_ThrowSyntaxError(ctx, \"invalid object reference (%u >= %u)\",\n                                           val, s->objects_count);\n            }\n            obj = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, s->objects[val]));\n        }\n        break;\n    default:\n    invalid_tag:\n        return JS_ThrowSyntaxError(ctx, \"invalid tag (tag=%d pos=%u)\",\n                                   tag, (unsigned int)(s->ptr - s->buf_start));\n    }\n    bc_read_trace(s, \"}\\n\");\n    return obj;\n}\n\nstatic int JS_ReadObjectAtoms(BCReaderState *s)\n{\n    uint8_t v8;\n    JSString *p;\n    int i;\n    JSAtom atom;\n\n    if (bc_get_u8(s, &v8))\n        return -1;\n    /* XXX: could support byte swapped input */\n    if (v8 != BC_VERSION) {\n        JS_ThrowSyntaxError(s->ctx, \"invalid version (%d expected=%d)\",\n                            v8, BC_VERSION);\n        return -1;\n    }\n    if (bc_get_leb128(s, &s->idx_to_atom_count))\n        return -1;\n\n    bc_read_trace(s, \"%d atom indexes {\\n\", s->idx_to_atom_count);\n\n    if (s->idx_to_atom_count != 0) {\n        s->idx_to_atom = js_mallocz(s->ctx, s->idx_to_atom_count *\n                                    sizeof(s->idx_to_atom[0]));\n        if (!s->idx_to_atom)\n            return s->error_state = -1;\n    }\n    for(i = 0; i < s->idx_to_atom_count; i++) {\n        p = JS_ReadString(s);\n        if (!p)\n            return -1;\n        atom = JS_NewAtomStr(s->ctx, p);\n        if (atom == JS_ATOM_NULL)\n            return s->error_state = -1;\n        s->idx_to_atom[i] = atom;\n        if (s->is_rom_data && (atom != (i + s->first_atom)))\n            s->is_rom_data = FALSE; /* atoms must be relocated */\n    }\n    bc_read_trace(s, \"}\\n\");\n    return 0;\n}\n\nstatic void bc_reader_free(BCReaderState *s)\n{\n    int i;\n    if (s->idx_to_atom) {\n        for(i = 0; i < s->idx_to_atom_count; i++) {\n            JS_FreeAtom(s->ctx, s->idx_to_atom[i]);\n        }\n        js_free(s->ctx, s->idx_to_atom);\n    }\n    js_free(s->ctx, s->objects);\n}\n\nJSValue JS_ReadObject(JSContext *ctx, const uint8_t *buf, size_t buf_len,\n                       int flags)\n{\n    BCReaderState ss, *s = &ss;\n    JSValue obj;\n\n    ctx->binary_object_count += 1;\n    ctx->binary_object_size += buf_len;\n\n    memset(s, 0, sizeof(*s));\n    s->ctx = ctx;\n    s->buf_start = buf;\n    s->buf_end = buf + buf_len;\n    s->ptr = buf;\n    s->allow_bytecode = ((flags & JS_READ_OBJ_BYTECODE) != 0);\n    s->is_rom_data = ((flags & JS_READ_OBJ_ROM_DATA) != 0);\n    s->allow_sab = ((flags & JS_READ_OBJ_SAB) != 0);\n    s->allow_reference = ((flags & JS_READ_OBJ_REFERENCE) != 0);\n    if (s->allow_bytecode)\n        s->first_atom = JS_ATOM_END;\n    else\n        s->first_atom = 1;\n    if (JS_ReadObjectAtoms(s)) {\n        obj = JS_EXCEPTION;\n    } else {\n        obj = JS_ReadObjectRec(s);\n    }\n    bc_reader_free(s);\n    return obj;\n}\n\n/*******************************************************************/\n/* runtime functions & objects */\n\nstatic JSValue js_string_constructor(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv);\nstatic JSValue js_boolean_constructor(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv);\nstatic JSValue js_number_constructor(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv);\n\nstatic int check_function(JSContext *ctx, JSValueConst obj)\n{\n    if (likely(JS_IsFunction(ctx, obj)))\n        return 0;\n    JS_ThrowTypeError(ctx, \"not a function\");\n    return -1;\n}\n\nstatic int check_exception_free(JSContext *ctx, JSValue obj)\n{\n    JS_FreeValue(ctx, obj);\n    return JS_IsException(obj);\n}\n\nstatic JSAtom find_atom(JSContext *ctx, const char *name)\n{\n    JSAtom atom;\n    int len;\n\n    if (*name == '[') {\n        name++;\n        len = strlen(name) - 1;\n        /* We assume 8 bit non null strings, which is the case for these\n           symbols */\n        for(atom = JS_ATOM_Symbol_toPrimitive; atom < JS_ATOM_END; atom++) {\n            JSAtomStruct *p = ctx->rt->atom_array[atom];\n            JSString *str = p;\n            if (str->len == len && !memcmp(str->u.str8, name, len))\n                return JS_DupAtom(ctx, atom);\n        }\n        abort();\n    } else {\n        atom = JS_NewAtom(ctx, name);\n    }\n    return atom;\n}\n\nstatic JSValue JS_InstantiateFunctionListItem2(JSContext *ctx, JSObject *p,\n                                               JSAtom atom, void *opaque)\n{\n    const JSCFunctionListEntry *e = opaque;\n    JSValue val;\n\n    switch(e->def_type) {\n    case JS_DEF_CFUNC:\n        val = JS_NewCFunction2(ctx, e->u.func.cfunc.generic,\n                               e->name, e->u.func.length, e->u.func.cproto, e->magic);\n        break;\n    case JS_DEF_PROP_STRING:\n        val = JS_NewAtomString(ctx, e->u.str);\n        break;\n    case JS_DEF_OBJECT:\n        val = JS_NewObject(ctx);\n        JS_SetPropertyFunctionList(ctx, val, e->u.prop_list.tab, e->u.prop_list.len);\n        break;\n    default:\n        abort();\n    }\n    return val;\n}\n\nstatic int JS_InstantiateFunctionListItem(JSContext *ctx, JSValueConst obj,\n                                          JSAtom atom,\n                                          const JSCFunctionListEntry *e)\n{\n    JSValue val;\n    int prop_flags = e->prop_flags;\n\n    switch(e->def_type) {\n    case JS_DEF_ALIAS: /* using autoinit for aliases is not safe */\n        {\n            JSAtom atom1 = find_atom(ctx, e->u.alias.name);\n            switch (e->u.alias.base) {\n            case -1:\n                val = JS_GetProperty(ctx, obj, atom1);\n                break;\n            case 0:\n                val = JS_GetProperty(ctx, ctx->global_obj, atom1);\n                break;\n            case 1:\n                val = JS_GetProperty(ctx, ctx->class_proto[JS_CLASS_ARRAY], atom1);\n                break;\n            default:\n                abort();\n            }\n            JS_FreeAtom(ctx, atom1);\n            if (atom == JS_ATOM_Symbol_toPrimitive) {\n                /* Symbol.toPrimitive functions are not writable */\n                prop_flags = JS_PROP_CONFIGURABLE;\n            } else if (atom == JS_ATOM_Symbol_hasInstance) {\n                /* Function.prototype[Symbol.hasInstance] is not writable nor configurable */\n                prop_flags = 0;\n            }\n        }\n        break;\n    case JS_DEF_CFUNC:\n        if (atom == JS_ATOM_Symbol_toPrimitive) {\n            /* Symbol.toPrimitive functions are not writable */\n            prop_flags = JS_PROP_CONFIGURABLE;\n        } else if (atom == JS_ATOM_Symbol_hasInstance) {\n            /* Function.prototype[Symbol.hasInstance] is not writable nor configurable */\n            prop_flags = 0;\n        }\n        JS_DefineAutoInitProperty(ctx, obj, atom, JS_AUTOINIT_ID_PROP,\n                                  (void *)e, prop_flags);\n        return 0;\n    case JS_DEF_CGETSET: /* XXX: use autoinit again ? */\n    case JS_DEF_CGETSET_MAGIC:\n        {\n            JSValue getter, setter;\n            char buf[64];\n\n            getter = JS_UNDEFINED;\n            if (e->u.getset.get.generic) {\n                snprintf(buf, sizeof(buf), \"get %s\", e->name);\n                getter = JS_NewCFunction2(ctx, e->u.getset.get.generic,\n                                          buf, 0, e->def_type == JS_DEF_CGETSET_MAGIC ? JS_CFUNC_getter_magic : JS_CFUNC_getter,\n                                          e->magic);\n            }\n            setter = JS_UNDEFINED;\n            if (e->u.getset.set.generic) {\n                snprintf(buf, sizeof(buf), \"set %s\", e->name);\n                setter = JS_NewCFunction2(ctx, e->u.getset.set.generic,\n                                          buf, 1, e->def_type == JS_DEF_CGETSET_MAGIC ? JS_CFUNC_setter_magic : JS_CFUNC_setter,\n                                          e->magic);\n            }\n            JS_DefinePropertyGetSet(ctx, obj, atom, getter, setter, prop_flags);\n            return 0;\n        }\n        break;\n    case JS_DEF_PROP_INT32:\n        val = JS_NewInt32(ctx, e->u.i32);\n        break;\n    case JS_DEF_PROP_INT64:\n        val = JS_NewInt64(ctx, e->u.i64);\n        break;\n    case JS_DEF_PROP_DOUBLE:\n        val = __JS_NewFloat64(ctx, e->u.f64);\n        break;\n    case JS_DEF_PROP_UNDEFINED:\n        val = JS_UNDEFINED;\n        break;\n    case JS_DEF_PROP_STRING:\n    case JS_DEF_OBJECT:\n        JS_DefineAutoInitProperty(ctx, obj, atom, JS_AUTOINIT_ID_PROP,\n                                  (void *)e, prop_flags);\n        return 0;\n    default:\n        abort();\n    }\n    JS_DefinePropertyValue(ctx, obj, atom, val, prop_flags);\n    return 0;\n}\n\nvoid JS_SetPropertyFunctionList(JSContext *ctx, JSValueConst obj,\n                                const JSCFunctionListEntry *tab, int len)\n{\n    int i;\n\n    for (i = 0; i < len; i++) {\n        const JSCFunctionListEntry *e = &tab[i];\n        JSAtom atom = find_atom(ctx, e->name);\n        JS_InstantiateFunctionListItem(ctx, obj, atom, e);\n        JS_FreeAtom(ctx, atom);\n    }\n}\n\nint JS_AddModuleExportList(JSContext *ctx, JSModuleDef *m,\n                           const JSCFunctionListEntry *tab, int len)\n{\n    int i;\n    for(i = 0; i < len; i++) {\n        if (JS_AddModuleExport(ctx, m, tab[i].name))\n            return -1;\n    }\n    return 0;\n}\n\nint JS_SetModuleExportList(JSContext *ctx, JSModuleDef *m,\n                           const JSCFunctionListEntry *tab, int len)\n{\n    int i;\n    JSValue val;\n\n    for(i = 0; i < len; i++) {\n        const JSCFunctionListEntry *e = &tab[i];\n        switch(e->def_type) {\n        case JS_DEF_CFUNC:\n            val = JS_NewCFunction2(ctx, e->u.func.cfunc.generic,\n                                   e->name, e->u.func.length, e->u.func.cproto, e->magic);\n            break;\n        case JS_DEF_PROP_STRING:\n            val = JS_NewString(ctx, e->u.str);\n            break;\n        case JS_DEF_PROP_INT32:\n            val = JS_NewInt32(ctx, e->u.i32);\n            break;\n        case JS_DEF_PROP_INT64:\n            val = JS_NewInt64(ctx, e->u.i64);\n            break;\n        case JS_DEF_PROP_DOUBLE:\n            val = __JS_NewFloat64(ctx, e->u.f64);\n            break;\n        case JS_DEF_OBJECT:\n            val = JS_NewObject(ctx);\n            JS_SetPropertyFunctionList(ctx, val, e->u.prop_list.tab, e->u.prop_list.len);\n            break;\n        default:\n            abort();\n        }\n        if (JS_SetModuleExport(ctx, m, e->name, val))\n            return -1;\n    }\n    return 0;\n}\n\n/* Note: 'func_obj' is not necessarily a constructor */\nstatic void JS_SetConstructor2(JSContext *ctx,\n                               JSValueConst func_obj,\n                               JSValueConst proto,\n                               int proto_flags, int ctor_flags)\n{\n    JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_prototype,\n                           JS_DupValue(ctx, proto), proto_flags);\n    JS_DefinePropertyValue(ctx, proto, JS_ATOM_constructor,\n                           JS_DupValue(ctx, func_obj),\n                           ctor_flags);\n    set_cycle_flag(ctx, func_obj);\n    set_cycle_flag(ctx, proto);\n}\n\nvoid JS_SetConstructor(JSContext *ctx, JSValueConst func_obj, \n                       JSValueConst proto)\n{\n    JS_SetConstructor2(ctx, func_obj, proto,\n                       0, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n}\n\nstatic void JS_NewGlobalCConstructor2(JSContext *ctx,\n                                      JSValue func_obj,\n                                      const char *name,\n                                      JSValueConst proto)\n{\n    JS_DefinePropertyValueStr(ctx, ctx->global_obj, name,\n                           JS_DupValue(ctx, func_obj),\n                           JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    JS_SetConstructor(ctx, func_obj, proto);\n    JS_FreeValue(ctx, func_obj);\n}\n\nstatic JSValueConst JS_NewGlobalCConstructor(JSContext *ctx, const char *name,\n                                             JSCFunction *func, int length,\n                                             JSValueConst proto)\n{\n    JSValue func_obj;\n    func_obj = JS_NewCFunction2(ctx, func, name, length, JS_CFUNC_constructor_or_func, 0);\n    JS_NewGlobalCConstructor2(ctx, func_obj, name, proto);\n    return func_obj;\n}\n\nstatic JSValueConst JS_NewGlobalCConstructorOnly(JSContext *ctx, const char *name,\n                                                 JSCFunction *func, int length,\n                                                 JSValueConst proto)\n{\n    JSValue func_obj;\n    func_obj = JS_NewCFunction2(ctx, func, name, length, JS_CFUNC_constructor, 0);\n    JS_NewGlobalCConstructor2(ctx, func_obj, name, proto);\n    return func_obj;\n}\n\nstatic JSValue js_global_eval(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    return JS_EvalObject(ctx, ctx->global_obj, argv[0], JS_EVAL_TYPE_INDIRECT, -1);\n}\n\nstatic JSValue js_global_isNaN(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    double d;\n\n    /* XXX: does this work for bigfloat? */\n    if (unlikely(JS_ToFloat64(ctx, &d, argv[0])))\n        return JS_EXCEPTION;\n    return JS_NewBool(ctx, isnan(d));\n}\n\nstatic JSValue js_global_isFinite(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    BOOL res;\n    double d;\n    if (unlikely(JS_ToFloat64(ctx, &d, argv[0])))\n        return JS_EXCEPTION;\n    res = isfinite(d);\n    return JS_NewBool(ctx, res);\n}\n\n/* Object class */\n\nstatic JSValue JS_ToObject(JSContext *ctx, JSValueConst val)\n{\n    int tag = JS_VALUE_GET_NORM_TAG(val);\n    JSValue obj;\n\n    switch(tag) {\n    default:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        return JS_ThrowTypeError(ctx, \"cannot convert to object\");\n    case JS_TAG_OBJECT:\n    case JS_TAG_EXCEPTION:\n        return JS_DupValue(ctx, val);\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n        obj = JS_NewObjectClass(ctx, JS_CLASS_BIG_INT);\n        goto set_value;\n    case JS_TAG_BIG_FLOAT:\n        obj = JS_NewObjectClass(ctx, JS_CLASS_BIG_FLOAT);\n        goto set_value;\n    case JS_TAG_BIG_DECIMAL:\n        obj = JS_NewObjectClass(ctx, JS_CLASS_BIG_DECIMAL);\n        goto set_value;\n#endif\n    case JS_TAG_INT:\n    case JS_TAG_FLOAT64:\n        obj = JS_NewObjectClass(ctx, JS_CLASS_NUMBER);\n        goto set_value;\n    case JS_TAG_STRING:\n        /* XXX: should call the string constructor */\n        {\n            JSString *p1 = JS_VALUE_GET_STRING(val);\n            obj = JS_NewObjectClass(ctx, JS_CLASS_STRING);\n            JS_DefinePropertyValue(ctx, obj, JS_ATOM_length, JS_NewInt32(ctx, p1->len), 0);\n        }\n        goto set_value;\n    case JS_TAG_BOOL:\n        obj = JS_NewObjectClass(ctx, JS_CLASS_BOOLEAN);\n        goto set_value;\n    case JS_TAG_SYMBOL:\n        obj = JS_NewObjectClass(ctx, JS_CLASS_SYMBOL);\n    set_value:\n        if (!JS_IsException(obj))\n            JS_SetObjectData(ctx, obj, JS_DupValue(ctx, val));\n        return obj;\n    }\n}\n\nstatic JSValue JS_ToObjectFree(JSContext *ctx, JSValue val)\n{\n    JSValue obj = JS_ToObject(ctx, val);\n    JS_FreeValue(ctx, val);\n    return obj;\n}\n\nstatic int js_obj_to_desc(JSContext *ctx, JSPropertyDescriptor *d,\n                          JSValueConst desc)\n{\n    JSValue val, getter, setter;\n    int flags;\n\n    if (!JS_IsObject(desc)) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        return -1;\n    }\n    flags = 0;\n    val = JS_UNDEFINED;\n    getter = JS_UNDEFINED;\n    setter = JS_UNDEFINED;\n    if (JS_HasProperty(ctx, desc, JS_ATOM_configurable)) {\n        JSValue prop = JS_GetProperty(ctx, desc, JS_ATOM_configurable);\n        if (JS_IsException(prop))\n            goto fail;\n        flags |= JS_PROP_HAS_CONFIGURABLE;\n        if (JS_ToBoolFree(ctx, prop))\n            flags |= JS_PROP_CONFIGURABLE;\n    }\n    if (JS_HasProperty(ctx, desc, JS_ATOM_writable)) {\n        JSValue prop = JS_GetProperty(ctx, desc, JS_ATOM_writable);\n        if (JS_IsException(prop))\n            goto fail;\n        flags |= JS_PROP_HAS_WRITABLE;\n        if (JS_ToBoolFree(ctx, prop))\n            flags |= JS_PROP_WRITABLE;\n    }\n    if (JS_HasProperty(ctx, desc, JS_ATOM_enumerable)) {\n        JSValue prop = JS_GetProperty(ctx, desc, JS_ATOM_enumerable);\n        if (JS_IsException(prop))\n            goto fail;\n        flags |= JS_PROP_HAS_ENUMERABLE;\n        if (JS_ToBoolFree(ctx, prop))\n            flags |= JS_PROP_ENUMERABLE;\n    }\n    if (JS_HasProperty(ctx, desc, JS_ATOM_value)) {\n        flags |= JS_PROP_HAS_VALUE;\n        val = JS_GetProperty(ctx, desc, JS_ATOM_value);\n        if (JS_IsException(val))\n            goto fail;\n    }\n    if (JS_HasProperty(ctx, desc, JS_ATOM_get)) {\n        flags |= JS_PROP_HAS_GET;\n        getter = JS_GetProperty(ctx, desc, JS_ATOM_get);\n        if (JS_IsException(getter) ||\n            !(JS_IsUndefined(getter) || JS_IsFunction(ctx, getter))) {\n            JS_ThrowTypeError(ctx, \"invalid getter\");\n            goto fail;\n        }\n    }\n    if (JS_HasProperty(ctx, desc, JS_ATOM_set)) {\n        flags |= JS_PROP_HAS_SET;\n        setter = JS_GetProperty(ctx, desc, JS_ATOM_set);\n        if (JS_IsException(setter) ||\n            !(JS_IsUndefined(setter) || JS_IsFunction(ctx, setter))) {\n            JS_ThrowTypeError(ctx, \"invalid setter\");\n            goto fail;\n        }\n    }\n    if ((flags & (JS_PROP_HAS_SET | JS_PROP_HAS_GET)) &&\n        (flags & (JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE))) {\n        JS_ThrowTypeError(ctx, \"cannot have setter/getter and value or writable\");\n        goto fail;\n    }\n    d->flags = flags;\n    d->value = val;\n    d->getter = getter;\n    d->setter = setter;\n    return 0;\n fail:\n    JS_FreeValue(ctx, val);\n    JS_FreeValue(ctx, getter);\n    JS_FreeValue(ctx, setter);\n    return -1;\n}\n\nstatic __exception int JS_DefinePropertyDesc(JSContext *ctx, JSValueConst obj,\n                                             JSAtom prop, JSValueConst desc,\n                                             int flags)\n{\n    JSPropertyDescriptor d;\n    int ret;\n\n    if (js_obj_to_desc(ctx, &d, desc) < 0)\n        return -1;\n\n    ret = JS_DefineProperty(ctx, obj, prop,\n                            d.value, d.getter, d.setter, d.flags | flags);\n    js_free_desc(ctx, &d);\n    return ret;\n}\n\nstatic __exception int JS_ObjectDefineProperties(JSContext *ctx,\n                                                 JSValueConst obj,\n                                                 JSValueConst properties)\n{\n    JSValue props, desc;\n    JSObject *p;\n    JSPropertyEnum *atoms;\n    uint32_t len, i;\n    int ret = -1;\n\n    if (!JS_IsObject(obj)) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        return -1;\n    }\n    desc = JS_UNDEFINED;\n    props = JS_ToObject(ctx, properties);\n    if (JS_IsException(props))\n        return -1;\n    p = JS_VALUE_GET_OBJ(props);\n    if (JS_GetOwnPropertyNamesInternal(ctx, &atoms, &len, p, JS_GPN_ENUM_ONLY | JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK) < 0)\n        goto exception;\n    for(i = 0; i < len; i++) {\n        JS_FreeValue(ctx, desc);\n        desc = JS_GetProperty(ctx, props, atoms[i].atom);\n        if (JS_IsException(desc))\n            goto exception;\n        if (JS_DefinePropertyDesc(ctx, obj, atoms[i].atom, desc, JS_PROP_THROW) < 0)\n            goto exception;\n    }\n    ret = 0;\n\nexception:\n    js_free_prop_enum(ctx, atoms, len);\n    JS_FreeValue(ctx, props);\n    JS_FreeValue(ctx, desc);\n    return ret;\n}\n\nstatic JSValue js_object_constructor(JSContext *ctx, JSValueConst new_target,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue ret;\n    if (!JS_IsUndefined(new_target) &&\n        JS_VALUE_GET_OBJ(new_target) !=\n        JS_VALUE_GET_OBJ(JS_GetActiveFunction(ctx))) {\n        ret = js_create_from_ctor(ctx, new_target, JS_CLASS_OBJECT);\n    } else {\n        int tag = JS_VALUE_GET_NORM_TAG(argv[0]);\n        switch(tag) {\n        case JS_TAG_NULL:\n        case JS_TAG_UNDEFINED:\n            ret = JS_NewObject(ctx);\n            break;\n        default:\n            ret = JS_ToObject(ctx, argv[0]);\n            break;\n        }\n    }\n    return ret;\n}\n\nstatic JSValue js_object_create(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValueConst proto, props;\n    JSValue obj;\n\n    proto = argv[0];\n    if (!JS_IsObject(proto) && !JS_IsNull(proto))\n        return JS_ThrowTypeError(ctx, \"not a prototype\");\n    obj = JS_NewObjectProto(ctx, proto);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    props = argv[1];\n    if (!JS_IsUndefined(props)) {\n        if (JS_ObjectDefineProperties(ctx, obj, props)) {\n            JS_FreeValue(ctx, obj);\n            return JS_EXCEPTION;\n        }\n    }\n    return obj;\n}\n\nstatic JSValue js_object_getPrototypeOf(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv, int magic)\n{\n    JSValueConst val;\n\n    val = argv[0];\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) {\n        /* ES6 feature non compatible with ES5.1: primitive types are\n           accepted */\n        if (magic || JS_VALUE_GET_TAG(val) == JS_TAG_NULL ||\n            JS_VALUE_GET_TAG(val) == JS_TAG_UNDEFINED)\n            return JS_ThrowTypeErrorNotAnObject(ctx);\n    }\n    return JS_GetPrototype(ctx, val);\n}\n\nstatic JSValue js_object_setPrototypeOf(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv)\n{\n    JSValueConst obj;\n    obj = argv[0];\n    if (JS_SetPrototypeInternal(ctx, obj, argv[1], TRUE) < 0)\n        return JS_EXCEPTION;\n    return JS_DupValue(ctx, obj);\n}\n\n/* magic = 1 if called as Reflect.defineProperty */\nstatic JSValue js_object_defineProperty(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv, int magic)\n{\n    JSValueConst obj, prop, desc;\n    int ret, flags;\n    JSAtom atom;\n\n    obj = argv[0];\n    prop = argv[1];\n    desc = argv[2];\n\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    atom = JS_ValueToAtom(ctx, prop);\n    if (unlikely(atom == JS_ATOM_NULL))\n        return JS_EXCEPTION;\n    flags = 0;\n    if (!magic)\n        flags |= JS_PROP_THROW;\n    ret = JS_DefinePropertyDesc(ctx, obj, atom, desc, flags);\n    JS_FreeAtom(ctx, atom);\n    if (ret < 0) {\n        return JS_EXCEPTION;\n    } else if (magic) {\n        return JS_NewBool(ctx, ret);\n    } else {\n        return JS_DupValue(ctx, obj);\n    }\n}\n\nstatic JSValue js_object_defineProperties(JSContext *ctx, JSValueConst this_val,\n                                          int argc, JSValueConst *argv)\n{\n    // defineProperties(obj, properties)\n    JSValueConst obj = argv[0];\n\n    if (JS_ObjectDefineProperties(ctx, obj, argv[1]))\n        return JS_EXCEPTION;\n    else\n        return JS_DupValue(ctx, obj);\n}\n\n/* magic = 1 if called as __defineSetter__ */\nstatic JSValue js_object___defineGetter__(JSContext *ctx, JSValueConst this_val,\n                                          int argc, JSValueConst *argv, int magic)\n{\n    JSValue obj;\n    JSValueConst prop, value, get, set;\n    int ret, flags;\n    JSAtom atom;\n\n    prop = argv[0];\n    value = argv[1];\n\n    obj = JS_ToObject(ctx, this_val);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n\n    if (check_function(ctx, value)) {\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    atom = JS_ValueToAtom(ctx, prop);\n    if (unlikely(atom == JS_ATOM_NULL)) {\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    flags = JS_PROP_THROW |\n        JS_PROP_HAS_ENUMERABLE | JS_PROP_ENUMERABLE |\n        JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE;\n    if (magic) {\n        get = JS_UNDEFINED;\n        set = value;\n        flags |= JS_PROP_HAS_SET;\n    } else {\n        get = value;\n        set = JS_UNDEFINED;\n        flags |= JS_PROP_HAS_GET;\n    }\n    ret = JS_DefineProperty(ctx, obj, atom, JS_UNDEFINED, get, set, flags);\n    JS_FreeValue(ctx, obj);\n    JS_FreeAtom(ctx, atom);\n    if (ret < 0) {\n        return JS_EXCEPTION;\n    } else {\n        return JS_UNDEFINED;\n    }\n}\n\nstatic JSValue js_object_getOwnPropertyDescriptor(JSContext *ctx, JSValueConst this_val,\n                                                  int argc, JSValueConst *argv, int magic)\n{\n    JSValueConst prop;\n    JSAtom atom;\n    JSValue ret, obj;\n    JSPropertyDescriptor desc;\n    int res, flags;\n\n    if (magic) {\n        /* Reflect.getOwnPropertyDescriptor case */\n        if (JS_VALUE_GET_TAG(argv[0]) != JS_TAG_OBJECT)\n            return JS_ThrowTypeErrorNotAnObject(ctx);\n        obj = JS_DupValue(ctx, argv[0]);\n    } else {\n        obj = JS_ToObject(ctx, argv[0]);\n        if (JS_IsException(obj))\n            return obj;\n    }\n    prop = argv[1];\n    atom = JS_ValueToAtom(ctx, prop);\n    if (unlikely(atom == JS_ATOM_NULL))\n        goto exception;\n    ret = JS_UNDEFINED;\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        res = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(obj), atom);\n        if (res < 0)\n            goto exception;\n        if (res) {\n            ret = JS_NewObject(ctx);\n            if (JS_IsException(ret))\n                goto exception1;\n            flags = JS_PROP_C_W_E | JS_PROP_THROW;\n            if (desc.flags & JS_PROP_GETSET) {\n                if (JS_DefinePropertyValue(ctx, ret, JS_ATOM_get, JS_DupValue(ctx, desc.getter), flags) < 0\n                ||  JS_DefinePropertyValue(ctx, ret, JS_ATOM_set, JS_DupValue(ctx, desc.setter), flags) < 0)\n                    goto exception1;\n            } else {\n                if (JS_DefinePropertyValue(ctx, ret, JS_ATOM_value, JS_DupValue(ctx, desc.value), flags) < 0\n                ||  JS_DefinePropertyValue(ctx, ret, JS_ATOM_writable,\n                                           JS_NewBool(ctx, (desc.flags & JS_PROP_WRITABLE) != 0), flags) < 0)\n                    goto exception1;\n            }\n            if (JS_DefinePropertyValue(ctx, ret, JS_ATOM_enumerable,\n                                       JS_NewBool(ctx, (desc.flags & JS_PROP_ENUMERABLE) != 0), flags) < 0\n            ||  JS_DefinePropertyValue(ctx, ret, JS_ATOM_configurable,\n                                       JS_NewBool(ctx, (desc.flags & JS_PROP_CONFIGURABLE) != 0), flags) < 0)\n                goto exception1;\n            js_free_desc(ctx, &desc);\n        }\n    }\n    JS_FreeAtom(ctx, atom);\n    JS_FreeValue(ctx, obj);\n    return ret;\n\nexception1:\n    js_free_desc(ctx, &desc);\n    JS_FreeValue(ctx, ret);\nexception:\n    JS_FreeAtom(ctx, atom);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_object_getOwnPropertyDescriptors(JSContext *ctx, JSValueConst this_val,\n                                                   int argc, JSValueConst *argv)\n{\n    //getOwnPropertyDescriptors(obj)\n    JSValue obj, r;\n    JSObject *p;\n    JSPropertyEnum *props;\n    uint32_t len, i;\n\n    r = JS_UNDEFINED;\n    obj = JS_ToObject(ctx, argv[0]);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n\n    p = JS_VALUE_GET_OBJ(obj);\n    if (JS_GetOwnPropertyNamesInternal(ctx, &props, &len, p,\n                               JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK))\n        goto exception;\n    r = JS_NewObject(ctx);\n    if (JS_IsException(r))\n        goto exception;\n    for(i = 0; i < len; i++) {\n        JSValue atomValue, desc;\n        JSValueConst args[2];\n\n        atomValue = JS_AtomToValue(ctx, props[i].atom);\n        if (JS_IsException(atomValue))\n            goto exception;\n        args[0] = obj;\n        args[1] = atomValue;\n        desc = js_object_getOwnPropertyDescriptor(ctx, JS_UNDEFINED, 2, args, 0);\n        JS_FreeValue(ctx, atomValue);\n        if (JS_IsException(desc))\n            goto exception;\n        if (!JS_IsUndefined(desc)) {\n            if (JS_DefinePropertyValue(ctx, r, props[i].atom, desc,\n                                       JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                goto exception;\n        }\n    }\n    js_free_prop_enum(ctx, props, len);\n    JS_FreeValue(ctx, obj);\n    return r;\n\nexception:\n    js_free_prop_enum(ctx, props, len);\n    JS_FreeValue(ctx, obj);\n    JS_FreeValue(ctx, r);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_GetOwnPropertyNames2(JSContext *ctx, JSValueConst obj1,\n                                       int flags, int kind)\n{\n    JSValue obj, r, val, key, value;\n    JSObject *p;\n    JSPropertyEnum *atoms;\n    uint32_t len, i, j;\n\n    r = JS_UNDEFINED;\n    val = JS_UNDEFINED;\n    obj = JS_ToObject(ctx, obj1);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    p = JS_VALUE_GET_OBJ(obj);\n    if (JS_GetOwnPropertyNamesInternal(ctx, &atoms, &len, p, flags & ~JS_GPN_ENUM_ONLY))\n        goto exception;\n    r = JS_NewArray(ctx);\n    if (JS_IsException(r))\n        goto exception;\n    for(j = i = 0; i < len; i++) {\n        JSAtom atom = atoms[i].atom;\n        if (flags & JS_GPN_ENUM_ONLY) {\n            JSPropertyDescriptor desc;\n            int res;\n\n            /* Check if property is still enumerable */\n            res = JS_GetOwnPropertyInternal(ctx, &desc, p, atom);\n            if (res < 0)\n                goto exception;\n            if (!res)\n                continue;\n            js_free_desc(ctx, &desc);\n            if (!(desc.flags & JS_PROP_ENUMERABLE))\n                continue;\n        }\n        switch(kind) {\n        default:\n        case JS_ITERATOR_KIND_KEY:\n            val = JS_AtomToValue(ctx, atom);\n            if (JS_IsException(val))\n                goto exception;\n            break;\n        case JS_ITERATOR_KIND_VALUE:\n            val = JS_GetProperty(ctx, obj, atom);\n            if (JS_IsException(val))\n                goto exception;\n            break;\n        case JS_ITERATOR_KIND_KEY_AND_VALUE:\n            val = JS_NewArray(ctx);\n            if (JS_IsException(val))\n                goto exception;\n            key = JS_AtomToValue(ctx, atom);\n            if (JS_IsException(key))\n                goto exception1;\n            if (JS_CreateDataPropertyUint32(ctx, val, 0, key, JS_PROP_THROW) < 0)\n                goto exception1;\n            value = JS_GetProperty(ctx, obj, atom);\n            if (JS_IsException(value))\n                goto exception1;\n            if (JS_CreateDataPropertyUint32(ctx, val, 1, value, JS_PROP_THROW) < 0)\n                goto exception1;\n            break;\n        }\n        if (JS_CreateDataPropertyUint32(ctx, r, j++, val, 0) < 0)\n            goto exception;\n    }\n    goto done;\n\nexception1:\n    JS_FreeValue(ctx, val);\nexception:\n    JS_FreeValue(ctx, r);\n    r = JS_EXCEPTION;\ndone:\n    js_free_prop_enum(ctx, atoms, len);\n    JS_FreeValue(ctx, obj);\n    return r;\n}\n\nstatic JSValue js_object_getOwnPropertyNames(JSContext *ctx, JSValueConst this_val,\n                                             int argc, JSValueConst *argv)\n{\n    return JS_GetOwnPropertyNames2(ctx, argv[0],\n                                   JS_GPN_STRING_MASK, JS_ITERATOR_KIND_KEY);\n}\n\nstatic JSValue js_object_getOwnPropertySymbols(JSContext *ctx, JSValueConst this_val,\n                                             int argc, JSValueConst *argv)\n{\n    return JS_GetOwnPropertyNames2(ctx, argv[0],\n                                   JS_GPN_SYMBOL_MASK, JS_ITERATOR_KIND_KEY);\n}\n\nstatic JSValue js_object_keys(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int kind)\n{\n    return JS_GetOwnPropertyNames2(ctx, argv[0],\n                                   JS_GPN_ENUM_ONLY | JS_GPN_STRING_MASK, kind);\n}\n\nstatic JSValue js_object_isExtensible(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv, int reflect)\n{\n    JSValueConst obj;\n    int ret;\n\n    obj = argv[0];\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) {\n        if (reflect)\n            return JS_ThrowTypeErrorNotAnObject(ctx);\n        else\n            return JS_FALSE;\n    }\n    ret = JS_IsExtensible(ctx, obj);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_object_preventExtensions(JSContext *ctx, JSValueConst this_val,\n                                           int argc, JSValueConst *argv, int reflect)\n{\n    JSValueConst obj;\n    int ret;\n\n    obj = argv[0];\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) {\n        if (reflect)\n            return JS_ThrowTypeErrorNotAnObject(ctx);\n        else\n            return JS_DupValue(ctx, obj);\n    }\n    ret = JS_PreventExtensions(ctx, obj);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    if (reflect) {\n        return JS_NewBool(ctx, ret);\n    } else {\n        if (!ret)\n            return JS_ThrowTypeError(ctx, \"proxy preventExtensions handler returned false\");\n        return JS_DupValue(ctx, obj);\n    }\n}\n\nstatic JSValue js_object_hasOwnProperty(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv)\n{\n    JSValue obj;\n    JSAtom atom;\n    JSObject *p;\n    BOOL ret;\n\n    atom = JS_ValueToAtom(ctx, argv[0]); /* must be done first */\n    if (unlikely(atom == JS_ATOM_NULL))\n        return JS_EXCEPTION;\n    obj = JS_ToObject(ctx, this_val);\n    if (JS_IsException(obj)) {\n        JS_FreeAtom(ctx, atom);\n        return obj;\n    }\n    p = JS_VALUE_GET_OBJ(obj);\n    ret = JS_GetOwnPropertyInternal(ctx, NULL, p, atom);\n    JS_FreeAtom(ctx, atom);\n    JS_FreeValue(ctx, obj);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_object_valueOf(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    return JS_ToObject(ctx, this_val);\n}\n\nstatic JSValue js_object_toString(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    JSValue obj, tag;\n    int is_array;\n    JSAtom atom;\n    JSObject *p;\n\n    if (JS_IsNull(this_val)) {\n        tag = JS_NewString(ctx, \"Null\");\n    } else if (JS_IsUndefined(this_val)) {\n        tag = JS_NewString(ctx, \"Undefined\");\n    } else {\n        obj = JS_ToObject(ctx, this_val);\n        if (JS_IsException(obj))\n            return obj;\n        is_array = JS_IsArray(ctx, obj);\n        if (is_array < 0) {\n            JS_FreeValue(ctx, obj);\n            return JS_EXCEPTION;\n        }\n        if (is_array) {\n            atom = JS_ATOM_Array;\n        } else if (JS_IsFunction(ctx, obj)) {\n            atom = JS_ATOM_Function;\n        } else {\n            p = JS_VALUE_GET_OBJ(obj);\n            switch(p->class_id) {\n            case JS_CLASS_STRING:\n            case JS_CLASS_ARGUMENTS:\n            case JS_CLASS_MAPPED_ARGUMENTS:\n            case JS_CLASS_ERROR:\n            case JS_CLASS_BOOLEAN:\n            case JS_CLASS_NUMBER:\n            case JS_CLASS_DATE:\n            case JS_CLASS_REGEXP:\n                atom = ctx->rt->class_array[p->class_id].class_name;\n                break;\n            default:\n                atom = JS_ATOM_Object;\n                break;\n            }\n        }\n        tag = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_toStringTag);\n        JS_FreeValue(ctx, obj);\n        if (JS_IsException(tag))\n            return JS_EXCEPTION;\n        if (!JS_IsString(tag)) {\n            JS_FreeValue(ctx, tag);\n            tag = JS_AtomToString(ctx, atom);\n        }\n    }\n    return JS_ConcatString3(ctx, \"[object \", tag, \"]\");\n}\n\nstatic JSValue js_object_toLocaleString(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv)\n{\n    return JS_Invoke(ctx, this_val, JS_ATOM_toString, 0, NULL);\n}\n\nstatic JSValue js_object_assign(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    // Object.assign(obj, source1)\n    JSValue obj, s;\n    int i;\n\n    s = JS_UNDEFINED;\n    obj = JS_ToObject(ctx, argv[0]);\n    if (JS_IsException(obj))\n        goto exception;\n    for (i = 1; i < argc; i++) {\n        if (!JS_IsNull(argv[i]) && !JS_IsUndefined(argv[i])) {\n            s = JS_ToObject(ctx, argv[i]);\n            if (JS_IsException(s))\n                goto exception;\n            if (JS_CopyDataProperties(ctx, obj, s, JS_UNDEFINED, TRUE))\n                goto exception;\n            JS_FreeValue(ctx, s);\n        }\n    }\n    return obj;\nexception:\n    JS_FreeValue(ctx, obj);\n    JS_FreeValue(ctx, s);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_object_seal(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int freeze_flag)\n{\n    JSValueConst obj = argv[0];\n    JSObject *p;\n    JSPropertyEnum *props;\n    uint32_t len, i;\n    int flags, desc_flags, res;\n\n    if (!JS_IsObject(obj))\n        return JS_DupValue(ctx, obj);\n\n    res = JS_PreventExtensions(ctx, obj);\n    if (res < 0)\n        return JS_EXCEPTION;\n    if (!res) {\n        return JS_ThrowTypeError(ctx, \"proxy preventExtensions handler returned false\");\n    }\n    \n    p = JS_VALUE_GET_OBJ(obj);\n    flags = JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK;\n    if (JS_GetOwnPropertyNamesInternal(ctx, &props, &len, p, flags))\n        return JS_EXCEPTION;\n\n    for(i = 0; i < len; i++) {\n        JSPropertyDescriptor desc;\n        JSAtom prop = props[i].atom;\n\n        desc_flags = JS_PROP_THROW | JS_PROP_HAS_CONFIGURABLE;\n        if (freeze_flag) {\n            res = JS_GetOwnPropertyInternal(ctx, &desc, p, prop);\n            if (res < 0)\n                goto exception;\n            if (res) {\n                if (desc.flags & JS_PROP_WRITABLE)\n                    desc_flags |= JS_PROP_HAS_WRITABLE;\n                js_free_desc(ctx, &desc);\n            }\n        }\n        if (JS_DefineProperty(ctx, obj, prop, JS_UNDEFINED,\n                              JS_UNDEFINED, JS_UNDEFINED, desc_flags) < 0)\n            goto exception;\n    }\n    js_free_prop_enum(ctx, props, len);\n    return JS_DupValue(ctx, obj);\n\n exception:\n    js_free_prop_enum(ctx, props, len);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_object_isSealed(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv, int is_frozen)\n{\n    JSValueConst obj = argv[0];\n    JSObject *p;\n    JSPropertyEnum *props;\n    uint32_t len, i;\n    int flags, res;\n    \n    if (!JS_IsObject(obj))\n        return JS_TRUE;\n\n    p = JS_VALUE_GET_OBJ(obj);\n    flags = JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK;\n    if (JS_GetOwnPropertyNamesInternal(ctx, &props, &len, p, flags))\n        return JS_EXCEPTION;\n\n    for(i = 0; i < len; i++) {\n        JSPropertyDescriptor desc;\n        JSAtom prop = props[i].atom;\n\n        res = JS_GetOwnPropertyInternal(ctx, &desc, p, prop);\n        if (res < 0)\n            goto exception;\n        if (res) {\n            js_free_desc(ctx, &desc);\n            if ((desc.flags & JS_PROP_CONFIGURABLE)\n            ||  (is_frozen && (desc.flags & JS_PROP_WRITABLE))) {\n                res = FALSE;\n                goto done;\n            }\n        }\n    }\n    res = JS_IsExtensible(ctx, obj);\n    if (res < 0)\n        return JS_EXCEPTION;\n    res ^= 1;\ndone:        \n    js_free_prop_enum(ctx, props, len);\n    return JS_NewBool(ctx, res);\n\nexception:\n    js_free_prop_enum(ctx, props, len);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_object_fromEntries(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue obj, iter, next_method = JS_UNDEFINED;\n    JSValueConst iterable;\n    BOOL done;\n\n    /*  RequireObjectCoercible() not necessary because it is tested in\n        JS_GetIterator() by JS_GetProperty() */\n    iterable = argv[0];\n\n    obj = JS_NewObject(ctx);\n    if (JS_IsException(obj))\n        return obj;\n    \n    iter = JS_GetIterator(ctx, iterable, FALSE);\n    if (JS_IsException(iter))\n        goto fail;\n    next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);\n    if (JS_IsException(next_method))\n        goto fail;\n    \n    for(;;) {\n        JSValue key, value, item;\n        item = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);\n        if (JS_IsException(item))\n            goto fail;\n        if (done) {\n            JS_FreeValue(ctx, item);\n            break;\n        }\n        \n        key = JS_UNDEFINED;\n        value = JS_UNDEFINED;\n        if (!JS_IsObject(item)) {\n            JS_ThrowTypeErrorNotAnObject(ctx);\n            goto fail1;\n        }\n        key = JS_GetPropertyUint32(ctx, item, 0);\n        if (JS_IsException(key))\n            goto fail1;\n        value = JS_GetPropertyUint32(ctx, item, 1);\n        if (JS_IsException(value)) {\n            JS_FreeValue(ctx, key);\n            goto fail1;\n        }\n        if (JS_DefinePropertyValueValue(ctx, obj, key, value,\n                                        JS_PROP_C_W_E | JS_PROP_THROW) < 0) {\n        fail1:\n            JS_FreeValue(ctx, item);\n            goto fail;\n        }\n        JS_FreeValue(ctx, item);\n    }\n    JS_FreeValue(ctx, next_method);\n    JS_FreeValue(ctx, iter);\n    return obj;\n fail:\n    if (JS_IsObject(iter)) {\n        /* close the iterator object, preserving pending exception */\n        JS_IteratorClose(ctx, iter, TRUE);\n    }\n    JS_FreeValue(ctx, next_method);\n    JS_FreeValue(ctx, iter);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\n#if 0\n/* Note: corresponds to ECMA spec: CreateDataPropertyOrThrow() */\nstatic JSValue js_object___setOwnProperty(JSContext *ctx, JSValueConst this_val,\n                                          int argc, JSValueConst *argv)\n{\n    int ret;\n    ret = JS_DefinePropertyValueValue(ctx, argv[0], JS_DupValue(ctx, argv[1]),\n                                      JS_DupValue(ctx, argv[2]),\n                                      JS_PROP_C_W_E | JS_PROP_THROW);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_object___toObject(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    return JS_ToObject(ctx, argv[0]);\n}\n\nstatic JSValue js_object___toPrimitive(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    int hint = HINT_NONE;\n\n    if (JS_VALUE_GET_TAG(argv[1]) == JS_TAG_INT)\n        hint = JS_VALUE_GET_INT(argv[1]);\n\n    return JS_ToPrimitive(ctx, argv[0], hint);\n}\n#endif\n\n/* return an empty string if not an object */\nstatic JSValue js_object___getClass(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSAtom atom;\n    JSObject *p;\n    uint32_t tag;\n    int class_id;\n\n    tag = JS_VALUE_GET_NORM_TAG(argv[0]);\n    if (tag == JS_TAG_OBJECT) {\n        p = JS_VALUE_GET_OBJ(argv[0]);\n        class_id = p->class_id;\n        if (class_id == JS_CLASS_PROXY && JS_IsFunction(ctx, argv[0]))\n            class_id = JS_CLASS_BYTECODE_FUNCTION;\n        atom = ctx->rt->class_array[class_id].class_name;\n    } else {\n        atom = JS_ATOM_empty_string;\n    }\n    return JS_AtomToString(ctx, atom);\n}\n\nstatic JSValue js_object_is(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv)\n{\n    return JS_NewBool(ctx, js_same_value(ctx, argv[0], argv[1]));\n}\n\n#if 0\nstatic JSValue js_object___getObjectData(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    return JS_GetObjectData(ctx, argv[0]);\n}\n\nstatic JSValue js_object___setObjectData(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    if (JS_SetObjectData(ctx, argv[0], JS_DupValue(ctx, argv[1])))\n        return JS_EXCEPTION;\n    return JS_DupValue(ctx, argv[1]);\n}\n\nstatic JSValue js_object___toPropertyKey(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    return JS_ToPropertyKey(ctx, argv[0]);\n}\n\nstatic JSValue js_object___isObject(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    return JS_NewBool(ctx, JS_IsObject(argv[0]));\n}\n\nstatic JSValue js_object___isSameValueZero(JSContext *ctx, JSValueConst this_val,\n                                           int argc, JSValueConst *argv)\n{\n    return JS_NewBool(ctx, js_same_value_zero(ctx, argv[0], argv[1]));\n}\n\nstatic JSValue js_object___isConstructor(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    return JS_NewBool(ctx, JS_IsConstructor(ctx, argv[0]));\n}\n#endif\n\nstatic JSValue JS_SpeciesConstructor(JSContext *ctx, JSValueConst obj,\n                                     JSValueConst defaultConstructor)\n{\n    JSValue ctor, species;\n\n    if (!JS_IsObject(obj))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    ctor = JS_GetProperty(ctx, obj, JS_ATOM_constructor);\n    if (JS_IsException(ctor))\n        return ctor;\n    if (JS_IsUndefined(ctor))\n        return JS_DupValue(ctx, defaultConstructor);\n    if (!JS_IsObject(ctor)) {\n        JS_FreeValue(ctx, ctor);\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    }\n    species = JS_GetProperty(ctx, ctor, JS_ATOM_Symbol_species);\n    JS_FreeValue(ctx, ctor);\n    if (JS_IsException(species))\n        return species;\n    if (JS_IsUndefined(species) || JS_IsNull(species))\n        return JS_DupValue(ctx, defaultConstructor);\n    if (!JS_IsConstructor(ctx, species)) {\n        JS_FreeValue(ctx, species);\n        return JS_ThrowTypeError(ctx, \"not a constructor\");\n    }\n    return species;\n}\n\n#if 0\nstatic JSValue js_object___speciesConstructor(JSContext *ctx, JSValueConst this_val,\n                                              int argc, JSValueConst *argv)\n{\n    return JS_SpeciesConstructor(ctx, argv[0], argv[1]);\n}\n#endif\n\nstatic JSValue js_object_get___proto__(JSContext *ctx, JSValueConst this_val)\n{\n    JSValue val, ret;\n\n    val = JS_ToObject(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    ret = JS_GetPrototype(ctx, val);\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nstatic JSValue js_object_set___proto__(JSContext *ctx, JSValueConst this_val,\n                                       JSValueConst proto)\n{\n    if (JS_IsUndefined(this_val) || JS_IsNull(this_val))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    if (!JS_IsObject(proto) && !JS_IsNull(proto))\n        return JS_UNDEFINED;\n    if (JS_SetPrototypeInternal(ctx, this_val, proto, TRUE) < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_UNDEFINED;\n}\n\nstatic JSValue js_object_isPrototypeOf(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    JSValue obj, v1;\n    JSValueConst v;\n    int res;\n\n    v = argv[0];\n    if (!JS_IsObject(v))\n        return JS_FALSE;\n    obj = JS_ToObject(ctx, this_val);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    v1 = JS_DupValue(ctx, v);\n    for(;;) {\n        v1 = JS_GetPrototypeFree(ctx, v1);\n        if (JS_IsException(v1))\n            goto exception;\n        if (JS_IsNull(v1)) {\n            res = FALSE;\n            break;\n        }\n        if (JS_VALUE_GET_OBJ(obj) == JS_VALUE_GET_OBJ(v1)) {\n            res = TRUE;\n            break;\n        }\n        /* avoid infinite loop (possible with proxies) */\n        if (js_poll_interrupts(ctx))\n            goto exception;\n    }\n    JS_FreeValue(ctx, v1);\n    JS_FreeValue(ctx, obj);\n    return JS_NewBool(ctx, res);\n\nexception:\n    JS_FreeValue(ctx, v1);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_object_propertyIsEnumerable(JSContext *ctx, JSValueConst this_val,\n                                              int argc, JSValueConst *argv)\n{\n    JSValue obj, res = JS_EXCEPTION;\n    JSAtom prop = JS_ATOM_NULL;\n    JSPropertyDescriptor desc;\n    int has_prop;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (JS_IsException(obj))\n        goto exception;\n    prop = JS_ValueToAtom(ctx, argv[0]);\n    if (unlikely(prop == JS_ATOM_NULL))\n        goto exception;\n\n    has_prop = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(obj), prop);\n    if (has_prop < 0)\n        goto exception;\n    if (has_prop) {\n        res = JS_NewBool(ctx, (desc.flags & JS_PROP_ENUMERABLE) != 0);\n        js_free_desc(ctx, &desc);\n    } else {\n        res = JS_FALSE;\n    }\n\nexception:\n    JS_FreeAtom(ctx, prop);\n    JS_FreeValue(ctx, obj);\n    return res;\n}\n\nstatic JSValue js_object___lookupGetter__(JSContext *ctx, JSValueConst this_val,\n                                          int argc, JSValueConst *argv, int setter)\n{\n    JSValue obj, res = JS_EXCEPTION;\n    JSAtom prop = JS_ATOM_NULL;\n    JSPropertyDescriptor desc;\n    int has_prop;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (JS_IsException(obj))\n        goto exception;\n    prop = JS_ValueToAtom(ctx, argv[0]);\n    if (unlikely(prop == JS_ATOM_NULL))\n        goto exception;\n\n    for (;;) {\n        has_prop = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(obj), prop);\n        if (has_prop < 0)\n            goto exception;\n        if (has_prop) {\n            if (desc.flags & JS_PROP_GETSET)\n                res = JS_DupValue(ctx, setter ? desc.setter : desc.getter);\n            else\n                res = JS_UNDEFINED;\n            js_free_desc(ctx, &desc);\n            break;\n        }\n        obj = JS_GetPrototypeFree(ctx, obj);\n        if (JS_IsException(obj))\n            goto exception;\n        if (JS_IsNull(obj)) {\n            res = JS_UNDEFINED;\n            break;\n        }\n        /* avoid infinite loop (possible with proxies) */\n        if (js_poll_interrupts(ctx))\n            goto exception;\n    }\n\nexception:\n    JS_FreeAtom(ctx, prop);\n    JS_FreeValue(ctx, obj);\n    return res;\n}\n\nstatic const JSCFunctionListEntry js_object_funcs[] = {\n    JS_CFUNC_DEF(\"create\", 2, js_object_create ),\n    JS_CFUNC_MAGIC_DEF(\"getPrototypeOf\", 1, js_object_getPrototypeOf, 0 ),\n    JS_CFUNC_DEF(\"setPrototypeOf\", 2, js_object_setPrototypeOf ),\n    JS_CFUNC_MAGIC_DEF(\"defineProperty\", 3, js_object_defineProperty, 0 ),\n    JS_CFUNC_DEF(\"defineProperties\", 2, js_object_defineProperties ),\n    JS_CFUNC_DEF(\"getOwnPropertyNames\", 1, js_object_getOwnPropertyNames ),\n    JS_CFUNC_DEF(\"getOwnPropertySymbols\", 1, js_object_getOwnPropertySymbols ),\n    JS_CFUNC_MAGIC_DEF(\"keys\", 1, js_object_keys, JS_ITERATOR_KIND_KEY ),\n    JS_CFUNC_MAGIC_DEF(\"values\", 1, js_object_keys, JS_ITERATOR_KIND_VALUE ),\n    JS_CFUNC_MAGIC_DEF(\"entries\", 1, js_object_keys, JS_ITERATOR_KIND_KEY_AND_VALUE ),\n    JS_CFUNC_MAGIC_DEF(\"isExtensible\", 1, js_object_isExtensible, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"preventExtensions\", 1, js_object_preventExtensions, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"getOwnPropertyDescriptor\", 2, js_object_getOwnPropertyDescriptor, 0 ),\n    JS_CFUNC_DEF(\"getOwnPropertyDescriptors\", 1, js_object_getOwnPropertyDescriptors ),\n    JS_CFUNC_DEF(\"is\", 2, js_object_is ),\n    JS_CFUNC_DEF(\"assign\", 2, js_object_assign ),\n    JS_CFUNC_MAGIC_DEF(\"seal\", 1, js_object_seal, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"freeze\", 1, js_object_seal, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"isSealed\", 1, js_object_isSealed, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"isFrozen\", 1, js_object_isSealed, 1 ),\n    JS_CFUNC_DEF(\"__getClass\", 1, js_object___getClass ),\n    //JS_CFUNC_DEF(\"__isObject\", 1, js_object___isObject ),\n    //JS_CFUNC_DEF(\"__isConstructor\", 1, js_object___isConstructor ),\n    //JS_CFUNC_DEF(\"__toObject\", 1, js_object___toObject ),\n    //JS_CFUNC_DEF(\"__setOwnProperty\", 3, js_object___setOwnProperty ),\n    //JS_CFUNC_DEF(\"__toPrimitive\", 2, js_object___toPrimitive ),\n    //JS_CFUNC_DEF(\"__toPropertyKey\", 1, js_object___toPropertyKey ),\n    //JS_CFUNC_DEF(\"__speciesConstructor\", 2, js_object___speciesConstructor ),\n    //JS_CFUNC_DEF(\"__isSameValueZero\", 2, js_object___isSameValueZero ),\n    //JS_CFUNC_DEF(\"__getObjectData\", 1, js_object___getObjectData ),\n    //JS_CFUNC_DEF(\"__setObjectData\", 2, js_object___setObjectData ),\n    JS_CFUNC_DEF(\"fromEntries\", 1, js_object_fromEntries ),\n};\n\nstatic const JSCFunctionListEntry js_object_proto_funcs[] = {\n    JS_CFUNC_DEF(\"toString\", 0, js_object_toString ),\n    JS_CFUNC_DEF(\"toLocaleString\", 0, js_object_toLocaleString ),\n    JS_CFUNC_DEF(\"valueOf\", 0, js_object_valueOf ),\n    JS_CFUNC_DEF(\"hasOwnProperty\", 1, js_object_hasOwnProperty ),\n    JS_CFUNC_DEF(\"isPrototypeOf\", 1, js_object_isPrototypeOf ),\n    JS_CFUNC_DEF(\"propertyIsEnumerable\", 1, js_object_propertyIsEnumerable ),\n    JS_CGETSET_DEF(\"__proto__\", js_object_get___proto__, js_object_set___proto__ ),\n    JS_CFUNC_MAGIC_DEF(\"__defineGetter__\", 2, js_object___defineGetter__, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"__defineSetter__\", 2, js_object___defineGetter__, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"__lookupGetter__\", 1, js_object___lookupGetter__, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"__lookupSetter__\", 1, js_object___lookupGetter__, 1 ),\n};\n\n/* Function class */\n\nstatic JSValue js_function_proto(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    return JS_UNDEFINED;\n}\n\n/* XXX: add a specific eval mode so that Function(\"}), ({\") is rejected */\nstatic JSValue js_function_constructor(JSContext *ctx, JSValueConst new_target,\n                                       int argc, JSValueConst *argv, int magic)\n{\n    JSFunctionKindEnum func_kind = magic;\n    int i, n, ret;\n    JSValue s, proto, obj = JS_UNDEFINED;\n    StringBuffer b_s, *b = &b_s;\n\n    string_buffer_init(ctx, b, 0);\n    string_buffer_putc8(b, '(');\n    \n    if (func_kind == JS_FUNC_ASYNC || func_kind == JS_FUNC_ASYNC_GENERATOR) {\n        string_buffer_puts8(b, \"async \");\n    }\n    string_buffer_puts8(b, \"function\");\n\n    if (func_kind == JS_FUNC_GENERATOR || func_kind == JS_FUNC_ASYNC_GENERATOR) {\n        string_buffer_putc8(b, '*');\n    }\n    string_buffer_puts8(b, \" anonymous(\");\n\n    n = argc - 1;\n    for(i = 0; i < n; i++) {\n        if (i != 0) {\n            string_buffer_putc8(b, ',');\n        }\n        if (string_buffer_concat_value(b, argv[i]))\n            goto fail;\n    }\n    string_buffer_puts8(b, \"\\n) {\\n\");\n    if (n >= 0) {\n        if (string_buffer_concat_value(b, argv[n]))\n            goto fail;\n    }\n    string_buffer_puts8(b, \"\\n})\");\n    s = string_buffer_end(b);\n    if (JS_IsException(s))\n        goto fail1;\n\n    obj = JS_EvalObject(ctx, ctx->global_obj, s, JS_EVAL_TYPE_INDIRECT, -1);\n    JS_FreeValue(ctx, s);\n    if (JS_IsException(obj))\n        goto fail1;\n    if (!JS_IsUndefined(new_target)) {\n        /* set the prototype */\n        proto = JS_GetProperty(ctx, new_target, JS_ATOM_prototype);\n        if (JS_IsException(proto))\n            goto fail1;\n        if (!JS_IsObject(proto)) {\n            JSContext *realm;\n            JS_FreeValue(ctx, proto);\n            realm = JS_GetFunctionRealm(ctx, new_target);\n            if (!realm)\n                goto fail1;\n            proto = JS_DupValue(ctx, realm->class_proto[func_kind_to_class_id[func_kind]]);\n        }\n        ret = JS_SetPrototypeInternal(ctx, obj, proto, TRUE);\n        JS_FreeValue(ctx, proto);\n        if (ret < 0)\n            goto fail1;\n    }\n    return obj;\n\n fail:\n    string_buffer_free(b);\n fail1:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic __exception int js_get_length32(JSContext *ctx, uint32_t *pres,\n                                       JSValueConst obj)\n{\n    JSValue len_val;\n    len_val = JS_GetProperty(ctx, obj, JS_ATOM_length);\n    if (JS_IsException(len_val)) {\n        *pres = 0;\n        return -1;\n    }\n    return JS_ToUint32Free(ctx, pres, len_val);\n}\n\nstatic __exception int js_get_length64(JSContext *ctx, int64_t *pres,\n                                       JSValueConst obj)\n{\n    JSValue len_val;\n    len_val = JS_GetProperty(ctx, obj, JS_ATOM_length);\n    if (JS_IsException(len_val)) {\n        *pres = 0;\n        return -1;\n    }\n    return JS_ToLengthFree(ctx, pres, len_val);\n}\n\nstatic void free_arg_list(JSContext *ctx, JSValue *tab, uint32_t len)\n{\n    uint32_t i;\n    for(i = 0; i < len; i++) {\n        JS_FreeValue(ctx, tab[i]);\n    }\n    js_free(ctx, tab);\n}\n\n/* XXX: should use ValueArray */\nstatic JSValue *build_arg_list(JSContext *ctx, uint32_t *plen,\n                               JSValueConst array_arg)\n{\n    uint32_t len, i;\n    JSValue *tab, ret;\n    JSObject *p;\n\n    if (JS_VALUE_GET_TAG(array_arg) != JS_TAG_OBJECT) {\n        JS_ThrowTypeError(ctx, \"not a object\");\n        return NULL;\n    }\n    if (js_get_length32(ctx, &len, array_arg))\n        return NULL;\n    if (len > JS_MAX_LOCAL_VARS) {\n        JS_ThrowInternalError(ctx, \"too many arguments\");\n        return NULL;\n    }\n    /* avoid allocating 0 bytes */\n    tab = js_mallocz(ctx, sizeof(tab[0]) * max_uint32(1, len));\n    if (!tab)\n        return NULL;\n    p = JS_VALUE_GET_OBJ(array_arg);\n    if ((p->class_id == JS_CLASS_ARRAY || p->class_id == JS_CLASS_ARGUMENTS) &&\n        p->fast_array &&\n        len == p->u.array.count) {\n        for(i = 0; i < len; i++) {\n            tab[i] = JS_DupValue(ctx, p->u.array.u.values[i]);\n        }\n    } else {\n        for(i = 0; i < len; i++) {\n            ret = JS_GetPropertyUint32(ctx, array_arg, i);\n            if (JS_IsException(ret)) {\n                free_arg_list(ctx, tab, i);\n                return NULL;\n            }\n            tab[i] = ret;\n        }\n    }\n    *plen = len;\n    return tab;\n}\n\n/* magic value: 0 = normal apply, 1 = apply for constructor, 2 =\n   Reflect.apply */\nstatic JSValue js_function_apply(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv, int magic)\n{\n    JSValueConst this_arg, array_arg;\n    uint32_t len;\n    JSValue *tab, ret;\n\n    if (check_function(ctx, this_val))\n        return JS_EXCEPTION;\n    this_arg = argv[0];\n    array_arg = argv[1];\n    if ((JS_VALUE_GET_TAG(array_arg) == JS_TAG_UNDEFINED ||\n         JS_VALUE_GET_TAG(array_arg) == JS_TAG_NULL) && magic != 2) {\n        return JS_Call(ctx, this_val, this_arg, 0, NULL);\n    }\n    tab = build_arg_list(ctx, &len, array_arg);\n    if (!tab)\n        return JS_EXCEPTION;\n    if (magic & 1) {\n        ret = JS_CallConstructor2(ctx, this_val, this_arg, len, (JSValueConst *)tab);\n    } else {\n        ret = JS_Call(ctx, this_val, this_arg, len, (JSValueConst *)tab);\n    }\n    free_arg_list(ctx, tab, len);\n    return ret;\n}\n\nstatic JSValue js_function_call(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    if (argc <= 0) {\n        return JS_Call(ctx, this_val, JS_UNDEFINED, 0, NULL);\n    } else {\n        return JS_Call(ctx, this_val, argv[0], argc - 1, argv + 1);\n    }\n}\n\nstatic JSValue js_function_bind(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSBoundFunction *bf;\n    JSValue func_obj, name1, len_val;\n    JSObject *p;\n    int arg_count, i, ret;\n\n    if (check_function(ctx, this_val))\n        return JS_EXCEPTION;\n\n    func_obj = JS_NewObjectProtoClass(ctx, ctx->function_proto,\n                                 JS_CLASS_BOUND_FUNCTION);\n    if (JS_IsException(func_obj))\n        return JS_EXCEPTION;\n    p = JS_VALUE_GET_OBJ(func_obj);\n    p->is_constructor = JS_IsConstructor(ctx, this_val);\n    arg_count = max_int(0, argc - 1);\n    bf = js_malloc(ctx, sizeof(*bf) + arg_count * sizeof(JSValue));\n    if (!bf)\n        goto exception;\n    bf->func_obj = JS_DupValue(ctx, this_val);\n    bf->this_val = JS_DupValue(ctx, argv[0]);\n    bf->argc = arg_count;\n    for(i = 0; i < arg_count; i++) {\n        bf->argv[i] = JS_DupValue(ctx, argv[i + 1]);\n    }\n    p->u.bound_function = bf;\n\n    /* XXX: the spec could be simpler by only using GetOwnProperty */\n    ret = JS_GetOwnProperty(ctx, NULL, this_val, JS_ATOM_length);\n    if (ret < 0)\n        goto exception;\n    if (!ret) {\n        len_val = JS_NewInt32(ctx, 0);\n    } else {\n        len_val = JS_GetProperty(ctx, this_val, JS_ATOM_length);\n        if (JS_IsException(len_val))\n            goto exception;\n        if (JS_VALUE_GET_TAG(len_val) == JS_TAG_INT) {\n            /* most common case */\n            int len1 = JS_VALUE_GET_INT(len_val);\n            if (len1 <= arg_count)\n                len1 = 0;\n            else\n                len1 -= arg_count;\n            len_val = JS_NewInt32(ctx, len1);\n        } else if (JS_VALUE_GET_NORM_TAG(len_val) == JS_TAG_FLOAT64) {\n            double d = JS_VALUE_GET_FLOAT64(len_val);\n            if (isnan(d)) {\n                d = 0.0;\n            } else {\n                d = trunc(d);\n                if (d <= (double)arg_count)\n                    d = 0.0;\n                else\n                    d -= (double)arg_count; /* also converts -0 to +0 */\n            }\n            len_val = JS_NewFloat64(ctx, d);\n        } else {\n            JS_FreeValue(ctx, len_val);\n            len_val = JS_NewInt32(ctx, 0);\n        }\n    }\n    JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_length,\n                           len_val, JS_PROP_CONFIGURABLE);\n\n    name1 = JS_GetProperty(ctx, this_val, JS_ATOM_name);\n    if (JS_IsException(name1))\n        goto exception;\n    if (!JS_IsString(name1)) {\n        JS_FreeValue(ctx, name1);\n        name1 = JS_AtomToString(ctx, JS_ATOM_empty_string);\n    }\n    name1 = JS_ConcatString3(ctx, \"bound \", name1, \"\");\n    if (JS_IsException(name1))\n        goto exception;\n    JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_name, name1,\n                           JS_PROP_CONFIGURABLE);\n    return func_obj;\n exception:\n    JS_FreeValue(ctx, func_obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_function_toString(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSObject *p;\n    JSFunctionKindEnum func_kind = JS_FUNC_NORMAL;\n\n    if (check_function(ctx, this_val))\n        return JS_EXCEPTION;\n\n    p = JS_VALUE_GET_OBJ(this_val);\n    if (js_class_has_bytecode(p->class_id)) {\n        JSFunctionBytecode *b = p->u.func.function_bytecode;\n        if (b->has_debug && b->debug.source) {\n            return JS_NewStringLen(ctx, b->debug.source, b->debug.source_len);\n        }\n        func_kind = b->func_kind;\n    }\n    {\n        JSValue name;\n        const char *pref, *suff;\n\n        switch(func_kind) {\n        default:\n        case JS_FUNC_NORMAL:\n            pref = \"function \";\n            break;\n        case JS_FUNC_GENERATOR:\n            pref = \"function *\";\n            break;\n        case JS_FUNC_ASYNC:\n            pref = \"async function \";\n            break;\n        case JS_FUNC_ASYNC_GENERATOR:\n            pref = \"async function *\";\n            break;\n        }\n        suff = \"() {\\n    [native code]\\n}\";\n        name = JS_GetProperty(ctx, this_val, JS_ATOM_name);\n        if (JS_IsUndefined(name))\n            name = JS_AtomToString(ctx, JS_ATOM_empty_string);\n        return JS_ConcatString3(ctx, pref, name, suff);\n    }\n}\n\nstatic JSValue js_function_hasInstance(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    int ret;\n    ret = JS_OrdinaryIsInstanceOf(ctx, argv[0], this_val);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic const JSCFunctionListEntry js_function_proto_funcs[] = {\n    JS_CFUNC_DEF(\"call\", 1, js_function_call ),\n    JS_CFUNC_MAGIC_DEF(\"apply\", 2, js_function_apply, 0 ),\n    JS_CFUNC_DEF(\"bind\", 1, js_function_bind ),\n    JS_CFUNC_DEF(\"toString\", 0, js_function_toString ),\n    JS_CFUNC_DEF(\"[Symbol.hasInstance]\", 1, js_function_hasInstance ),\n    JS_CGETSET_DEF(\"fileName\", js_function_proto_fileName, NULL ),\n    JS_CGETSET_DEF(\"lineNumber\", js_function_proto_lineNumber, NULL ),\n};\n\n/* Error class */\n\nstatic JSValue iterator_to_array(JSContext *ctx, JSValueConst items)\n{\n    JSValue iter, next_method = JS_UNDEFINED;\n    JSValue v, r = JS_UNDEFINED;\n    int64_t k;\n    BOOL done;\n    \n    iter = JS_GetIterator(ctx, items, FALSE);\n    if (JS_IsException(iter))\n        goto exception;\n    next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);\n    if (JS_IsException(next_method))\n        goto exception;\n    r = JS_NewArray(ctx);\n    if (JS_IsException(r))\n        goto exception;\n    for (k = 0;; k++) {\n        v = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);\n        if (JS_IsException(v))\n            goto exception_close;\n        if (done)\n            break;\n        if (JS_DefinePropertyValueInt64(ctx, r, k, v,\n                                        JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n            goto exception_close;\n    }\n done:\n    JS_FreeValue(ctx, next_method);\n    JS_FreeValue(ctx, iter);\n    return r;\n exception_close:\n    JS_IteratorClose(ctx, iter, TRUE);\n exception:\n    JS_FreeValue(ctx, r);\n    r = JS_EXCEPTION;\n    goto done;\n}\n\nstatic JSValue js_error_constructor(JSContext *ctx, JSValueConst new_target,\n                                    int argc, JSValueConst *argv, int magic)\n{\n    JSValue obj, msg, proto;\n    JSValueConst message;\n\n    if (JS_IsUndefined(new_target))\n        new_target = JS_GetActiveFunction(ctx);\n    proto = JS_GetProperty(ctx, new_target, JS_ATOM_prototype);\n    if (JS_IsException(proto))\n        return proto;\n    if (!JS_IsObject(proto)) {\n        JSContext *realm;\n        JSValueConst proto1;\n        \n        JS_FreeValue(ctx, proto);\n        realm = JS_GetFunctionRealm(ctx, new_target);\n        if (!realm)\n            return JS_EXCEPTION;\n        if (magic < 0) {\n            proto1 = realm->class_proto[JS_CLASS_ERROR];\n        } else {\n            proto1 = realm->native_error_proto[magic];\n        }\n        proto = JS_DupValue(ctx, proto1);\n    }\n    obj = JS_NewObjectProtoClass(ctx, proto, JS_CLASS_ERROR);\n    JS_FreeValue(ctx, proto);\n    if (JS_IsException(obj))\n        return obj;\n    if (magic == JS_AGGREGATE_ERROR) {\n        message = argv[1];\n    } else {\n        message = argv[0];\n    }\n\n    if (!JS_IsUndefined(message)) {\n        msg = JS_ToString(ctx, message);\n        if (unlikely(JS_IsException(msg)))\n            goto exception;\n        JS_DefinePropertyValue(ctx, obj, JS_ATOM_message, msg,\n                               JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    }\n\n    if (magic == JS_AGGREGATE_ERROR) {\n        JSValue error_list = iterator_to_array(ctx, argv[0]);\n        if (JS_IsException(error_list))\n            goto exception;\n        JS_DefinePropertyValue(ctx, obj, JS_ATOM_errors, error_list,\n                               JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    }\n\n    /* skip the Error() function in the backtrace */\n    build_backtrace(ctx, obj, NULL, 0, JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL);\n    return obj;\n exception:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_error_toString(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValue name, msg;\n\n    if (!JS_IsObject(this_val))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    name = JS_GetProperty(ctx, this_val, JS_ATOM_name);\n    if (JS_IsUndefined(name))\n        name = JS_AtomToString(ctx, JS_ATOM_Error);\n    else\n        name = JS_ToStringFree(ctx, name);\n    if (JS_IsException(name))\n        return JS_EXCEPTION;\n\n    msg = JS_GetProperty(ctx, this_val, JS_ATOM_message);\n    if (JS_IsUndefined(msg))\n        msg = JS_AtomToString(ctx, JS_ATOM_empty_string);\n    else\n        msg = JS_ToStringFree(ctx, msg);\n    if (JS_IsException(msg)) {\n        JS_FreeValue(ctx, name);\n        return JS_EXCEPTION;\n    }\n    if (!JS_IsEmptyString(name) && !JS_IsEmptyString(msg))\n        name = JS_ConcatString3(ctx, \"\", name, \": \");\n    return JS_ConcatString(ctx, name, msg);\n}\n\nstatic const JSCFunctionListEntry js_error_proto_funcs[] = {\n    JS_CFUNC_DEF(\"toString\", 0, js_error_toString ),\n    JS_PROP_STRING_DEF(\"name\", \"Error\", JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),\n    JS_PROP_STRING_DEF(\"message\", \"\", JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),\n};\n\n/* AggregateError */\n\n/* used by C code. */\nstatic JSValue js_aggregate_error_constructor(JSContext *ctx,\n                                              JSValueConst errors)\n{\n    JSValue obj;\n    \n    obj = JS_NewObjectProtoClass(ctx,\n                                 ctx->native_error_proto[JS_AGGREGATE_ERROR],\n                                 JS_CLASS_ERROR);\n    if (JS_IsException(obj))\n        return obj;\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_errors, JS_DupValue(ctx, errors),\n                           JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    return obj;\n}\n\n/* Array */\n\nstatic int JS_CopySubArray(JSContext *ctx,\n                           JSValueConst obj, int64_t to_pos,\n                           int64_t from_pos, int64_t count, int dir)\n{\n    int64_t i, from, to;\n    JSValue val;\n    int fromPresent;\n\n    /* XXX: should special case fast arrays */\n    for (i = 0; i < count; i++) {\n        if (dir < 0) {\n            from = from_pos + count - i - 1;\n            to = to_pos + count - i - 1;\n        } else {\n            from = from_pos + i;\n            to = to_pos + i;\n        }\n        fromPresent = JS_TryGetPropertyInt64(ctx, obj, from, &val);\n        if (fromPresent < 0)\n            goto exception;\n\n        if (fromPresent) {\n            if (JS_SetPropertyInt64(ctx, obj, to, val) < 0)\n                goto exception;\n        } else {\n            if (JS_DeletePropertyInt64(ctx, obj, to, JS_PROP_THROW) < 0)\n                goto exception;\n        }\n    }\n    return 0;\n\n exception:\n    return -1;\n}\n\nstatic JSValue js_array_constructor(JSContext *ctx, JSValueConst new_target,\n                                    int argc, JSValueConst *argv)\n{\n    JSValue obj;\n    int i;\n\n    obj = js_create_from_ctor(ctx, new_target, JS_CLASS_ARRAY);\n    if (JS_IsException(obj))\n        return obj;\n    if (argc == 1 && JS_IsNumber(argv[0])) {\n        uint32_t len;\n        if (JS_ToArrayLengthFree(ctx, &len, JS_DupValue(ctx, argv[0]), TRUE))\n            goto fail;\n        if (JS_SetProperty(ctx, obj, JS_ATOM_length, JS_NewUint32(ctx, len)) < 0)\n            goto fail;\n    } else {\n        for(i = 0; i < argc; i++) {\n            if (JS_SetPropertyUint32(ctx, obj, i, JS_DupValue(ctx, argv[i])) < 0)\n                goto fail;\n        }\n    }\n    return obj;\nfail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_from(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    // from(items, mapfn = void 0, this_arg = void 0)\n    JSValueConst items = argv[0], mapfn, this_arg;\n    JSValueConst args[2];\n    JSValue stack[2];\n    JSValue iter, r, v, v2, arrayLike;\n    int64_t k, len;\n    int done, mapping;\n\n    mapping = FALSE;\n    mapfn = JS_UNDEFINED;\n    this_arg = JS_UNDEFINED;\n    r = JS_UNDEFINED;\n    arrayLike = JS_UNDEFINED;\n    stack[0] = JS_UNDEFINED;\n    stack[1] = JS_UNDEFINED;\n\n    if (argc > 1) {\n        mapfn = argv[1];\n        if (!JS_IsUndefined(mapfn)) {\n            if (check_function(ctx, mapfn))\n                goto exception;\n            mapping = 1;\n            if (argc > 2)\n                this_arg = argv[2];\n        }\n    }\n    iter = JS_GetProperty(ctx, items, JS_ATOM_Symbol_iterator);\n    if (JS_IsException(iter))\n        goto exception;\n    if (!JS_IsUndefined(iter)) {\n        JS_FreeValue(ctx, iter);\n        if (JS_IsConstructor(ctx, this_val))\n            r = JS_CallConstructor(ctx, this_val, 0, NULL);\n        else\n            r = JS_NewArray(ctx);\n        if (JS_IsException(r))\n            goto exception;\n        stack[0] = JS_DupValue(ctx, items);\n        if (js_for_of_start(ctx, &stack[1], FALSE))\n            goto exception;\n        for (k = 0;; k++) {\n            v = JS_IteratorNext(ctx, stack[0], stack[1], 0, NULL, &done);\n            if (JS_IsException(v))\n                goto exception_close;\n            if (done)\n                break;\n            if (mapping) {\n                args[0] = v;\n                args[1] = JS_NewInt32(ctx, k);\n                v2 = JS_Call(ctx, mapfn, this_arg, 2, args);\n                JS_FreeValue(ctx, v);\n                v = v2;\n                if (JS_IsException(v))\n                    goto exception_close;\n            }\n            if (JS_DefinePropertyValueInt64(ctx, r, k, v,\n                                            JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                goto exception_close;\n        }\n    } else {\n        arrayLike = JS_ToObject(ctx, items);\n        if (JS_IsException(arrayLike))\n            goto exception;\n        if (js_get_length64(ctx, &len, arrayLike) < 0)\n            goto exception;\n        v = JS_NewInt64(ctx, len);\n        args[0] = v;\n        if (JS_IsConstructor(ctx, this_val)) {\n            r = JS_CallConstructor(ctx, this_val, 1, args);\n        } else {\n            r = js_array_constructor(ctx, JS_UNDEFINED, 1, args);\n        }\n        JS_FreeValue(ctx, v);\n        if (JS_IsException(r))\n            goto exception;\n        for(k = 0; k < len; k++) {\n            v = JS_GetPropertyInt64(ctx, arrayLike, k);\n            if (JS_IsException(v))\n                goto exception;\n            if (mapping) {\n                args[0] = v;\n                args[1] = JS_NewInt32(ctx, k);\n                v2 = JS_Call(ctx, mapfn, this_arg, 2, args);\n                JS_FreeValue(ctx, v);\n                v = v2;\n                if (JS_IsException(v))\n                    goto exception;\n            }\n            if (JS_DefinePropertyValueInt64(ctx, r, k, v,\n                                            JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                goto exception;\n        }\n    }\n    if (JS_SetProperty(ctx, r, JS_ATOM_length, JS_NewUint32(ctx, k)) < 0)\n        goto exception;\n    goto done;\n\n exception_close:\n    if (!JS_IsUndefined(stack[0]))\n        JS_IteratorClose(ctx, stack[0], TRUE);\n exception:\n    JS_FreeValue(ctx, r);\n    r = JS_EXCEPTION;\n done:\n    JS_FreeValue(ctx, arrayLike);\n    JS_FreeValue(ctx, stack[0]);\n    JS_FreeValue(ctx, stack[1]);\n    return r;\n}\n\nstatic JSValue js_array_of(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    JSValue obj, args[1];\n    int i;\n\n    if (JS_IsConstructor(ctx, this_val)) {\n        args[0] = JS_NewInt32(ctx, argc);\n        obj = JS_CallConstructor(ctx, this_val, 1, (JSValueConst *)args);\n    } else {\n        obj = JS_NewArray(ctx);\n    }\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    for(i = 0; i < argc; i++) {\n        if (JS_CreateDataPropertyUint32(ctx, obj, i, JS_DupValue(ctx, argv[i]),\n                                        JS_PROP_THROW) < 0) {\n            goto fail;\n        }\n    }\n    if (JS_SetProperty(ctx, obj, JS_ATOM_length, JS_NewUint32(ctx, argc)) < 0) {\n    fail:\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    return obj;\n}\n\nstatic JSValue js_array_isArray(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    int ret;\n    ret = JS_IsArray(ctx, argv[0]);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_get_this(JSContext *ctx,\n                           JSValueConst this_val)\n{\n    return JS_DupValue(ctx, this_val);\n}\n\nstatic JSValue JS_ArraySpeciesCreate(JSContext *ctx, JSValueConst obj,\n                                     JSValueConst len_val)\n{\n    JSValue ctor, ret, species;\n    int res;\n    JSContext *realm;\n    \n    res = JS_IsArray(ctx, obj);\n    if (res < 0)\n        return JS_EXCEPTION;\n    if (!res)\n        return js_array_constructor(ctx, JS_UNDEFINED, 1, &len_val);\n    ctor = JS_GetProperty(ctx, obj, JS_ATOM_constructor);\n    if (JS_IsException(ctor))\n        return ctor;\n    if (JS_IsConstructor(ctx, ctor)) {\n        /* legacy web compatibility */\n        realm = JS_GetFunctionRealm(ctx, ctor);\n        if (!realm) {\n            JS_FreeValue(ctx, ctor);\n            return JS_EXCEPTION;\n        }\n        if (realm != ctx &&\n            js_same_value(ctx, ctor, realm->array_ctor)) {\n            JS_FreeValue(ctx, ctor);\n            ctor = JS_UNDEFINED;\n        }\n    }\n    if (JS_IsObject(ctor)) {\n        species = JS_GetProperty(ctx, ctor, JS_ATOM_Symbol_species);\n        JS_FreeValue(ctx, ctor);\n        if (JS_IsException(species))\n            return species;\n        ctor = species;\n        if (JS_IsNull(ctor))\n            ctor = JS_UNDEFINED;\n    }\n    if (JS_IsUndefined(ctor)) {\n        return js_array_constructor(ctx, JS_UNDEFINED, 1, &len_val);\n    } else {\n        ret = JS_CallConstructor(ctx, ctor, 1, &len_val);\n        JS_FreeValue(ctx, ctor);\n        return ret;\n    }\n}\n\nstatic const JSCFunctionListEntry js_array_funcs[] = {\n    JS_CFUNC_DEF(\"isArray\", 1, js_array_isArray ),\n    JS_CFUNC_DEF(\"from\", 1, js_array_from ),\n    JS_CFUNC_DEF(\"of\", 0, js_array_of ),\n    JS_CGETSET_DEF(\"[Symbol.species]\", js_get_this, NULL ),\n};\n\nstatic int JS_isConcatSpreadable(JSContext *ctx, JSValueConst obj)\n{\n    JSValue val;\n\n    if (!JS_IsObject(obj))\n        return FALSE;\n    val = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_isConcatSpreadable);\n    if (JS_IsException(val))\n        return -1;\n    if (!JS_IsUndefined(val))\n        return JS_ToBoolFree(ctx, val);\n    return JS_IsArray(ctx, obj);\n}\n\nstatic JSValue js_array_concat(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    JSValue obj, arr, val;\n    JSValueConst e;\n    int64_t len, k, n;\n    int i, res;\n\n    arr = JS_UNDEFINED;\n    obj = JS_ToObject(ctx, this_val);\n    if (JS_IsException(obj))\n        goto exception;\n\n    arr = JS_ArraySpeciesCreate(ctx, obj, JS_NewInt32(ctx, 0));\n    if (JS_IsException(arr))\n        goto exception;\n    n = 0;\n    for (i = -1; i < argc; i++) {\n        if (i < 0)\n            e = obj;\n        else\n            e = argv[i];\n\n        res = JS_isConcatSpreadable(ctx, e);\n        if (res < 0)\n            goto exception;\n        if (res) {\n            if (js_get_length64(ctx, &len, e))\n                goto exception;\n            if (n + len > MAX_SAFE_INTEGER) {\n                JS_ThrowTypeError(ctx, \"Array loo long\");\n                goto exception;\n            }\n            for (k = 0; k < len; k++, n++) {\n                res = JS_TryGetPropertyInt64(ctx, e, k, &val);\n                if (res < 0)\n                    goto exception;\n                if (res) {\n                    if (JS_DefinePropertyValueInt64(ctx, arr, n, val,\n                                                    JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                        goto exception;\n                }\n            }\n        } else {\n            if (n >= MAX_SAFE_INTEGER) {\n                JS_ThrowTypeError(ctx, \"Array loo long\");\n                goto exception;\n            }\n            if (JS_DefinePropertyValueInt64(ctx, arr, n, JS_DupValue(ctx, e),\n                                            JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                goto exception;\n            n++;\n        }\n    }\n    if (JS_SetProperty(ctx, arr, JS_ATOM_length, JS_NewInt64(ctx, n)) < 0)\n        goto exception;\n\n    JS_FreeValue(ctx, obj);\n    return arr;\n\nexception:\n    JS_FreeValue(ctx, arr);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\n#define special_every    0\n#define special_some     1\n#define special_forEach  2\n#define special_map      3\n#define special_filter   4\n#define special_TA       8\n\nstatic int js_typed_array_get_length_internal(JSContext *ctx, JSValueConst obj);\n\nstatic JSValue js_typed_array___speciesCreate(JSContext *ctx,\n                                              JSValueConst this_val,\n                                              int argc, JSValueConst *argv);\n\nstatic JSValue js_array_every(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int special)\n{\n    JSValue obj, val, index_val, res, ret;\n    JSValueConst args[3];\n    JSValueConst func, this_arg;\n    int64_t len, k, n;\n    int present;\n\n    ret = JS_UNDEFINED;\n    val = JS_UNDEFINED;\n    if (special & special_TA) {\n        obj = JS_DupValue(ctx, this_val);\n        len = js_typed_array_get_length_internal(ctx, obj);\n        if (len < 0)\n            goto exception;\n    } else {\n        obj = JS_ToObject(ctx, this_val);\n        if (js_get_length64(ctx, &len, obj))\n            goto exception;\n    }\n    func = argv[0];\n    this_arg = JS_UNDEFINED;\n    if (argc > 1)\n        this_arg = argv[1];\n        \n    if (check_function(ctx, func))\n        goto exception;\n\n    switch (special) {\n    case special_every:\n    case special_every | special_TA:\n        ret = JS_TRUE;\n        break;\n    case special_some:\n    case special_some | special_TA:\n        ret = JS_FALSE;\n        break;\n    case special_map:\n        /* XXX: JS_ArraySpeciesCreate should take int64_t */\n        ret = JS_ArraySpeciesCreate(ctx, obj, JS_NewInt64(ctx, len));\n        if (JS_IsException(ret))\n            goto exception;\n        break;\n    case special_filter:\n        ret = JS_ArraySpeciesCreate(ctx, obj, JS_NewInt32(ctx, 0));\n        if (JS_IsException(ret))\n            goto exception;\n        break;\n    case special_map | special_TA:\n        args[0] = obj;\n        args[1] = JS_NewInt32(ctx, len);\n        ret = js_typed_array___speciesCreate(ctx, JS_UNDEFINED, 2, args);\n        if (JS_IsException(ret))\n            goto exception;\n        break;\n    case special_filter | special_TA:\n        ret = JS_NewArray(ctx);\n        if (JS_IsException(ret))\n            goto exception;\n        break;\n    }\n    n = 0;\n\n    for(k = 0; k < len; k++) {\n        if (special & special_TA) {\n            val = JS_GetPropertyInt64(ctx, obj, k);\n            if (JS_IsException(val))\n                goto exception;\n            present = TRUE;\n        } else {\n            present = JS_TryGetPropertyInt64(ctx, obj, k, &val);\n            if (present < 0)\n                goto exception;\n        }\n        if (present) {\n            index_val = JS_NewInt64(ctx, k);\n            if (JS_IsException(index_val))\n                goto exception;\n            args[0] = val;\n            args[1] = index_val;\n            args[2] = obj;\n            res = JS_Call(ctx, func, this_arg, 3, args);\n            JS_FreeValue(ctx, index_val);\n            if (JS_IsException(res))\n                goto exception;\n            switch (special) {\n            case special_every:\n            case special_every | special_TA:\n                if (!JS_ToBoolFree(ctx, res)) {\n                    ret = JS_FALSE;\n                    goto done;\n                }\n                break;\n            case special_some:\n            case special_some | special_TA:\n                if (JS_ToBoolFree(ctx, res)) {\n                    ret = JS_TRUE;\n                    goto done;\n                }\n                break;\n            case special_map:\n                if (JS_DefinePropertyValueInt64(ctx, ret, k, res,\n                                                JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                    goto exception;\n                break;\n            case special_map | special_TA:\n                if (JS_SetPropertyValue(ctx, ret, JS_NewInt32(ctx, k), res, JS_PROP_THROW) < 0)\n                    goto exception;\n                break;\n            case special_filter:\n            case special_filter | special_TA:\n                if (JS_ToBoolFree(ctx, res)) {\n                    if (JS_DefinePropertyValueInt64(ctx, ret, n++, JS_DupValue(ctx, val),\n                                                    JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                        goto exception;\n                }\n                break;\n            default:\n                JS_FreeValue(ctx, res);\n                break;\n            }\n            JS_FreeValue(ctx, val);\n            val = JS_UNDEFINED;\n        }\n    }\ndone:\n    if (special == (special_filter | special_TA)) {\n        JSValue arr;\n        args[0] = obj;\n        args[1] = JS_NewInt32(ctx, n);\n        arr = js_typed_array___speciesCreate(ctx, JS_UNDEFINED, 2, args);\n        if (JS_IsException(arr))\n            goto exception;\n        args[0] = ret;\n        res = JS_Invoke(ctx, arr, JS_ATOM_set, 1, args);\n        if (check_exception_free(ctx, res))\n            goto exception;\n        JS_FreeValue(ctx, ret);\n        ret = arr;\n    }\n    JS_FreeValue(ctx, val);\n    JS_FreeValue(ctx, obj);\n    return ret;\n\nexception:\n    JS_FreeValue(ctx, ret);\n    JS_FreeValue(ctx, val);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\n#define special_reduce       0\n#define special_reduceRight  1\n\nstatic JSValue js_array_reduce(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv, int special)\n{\n    JSValue obj, val, index_val, acc, acc1;\n    JSValueConst args[4];\n    JSValueConst func;\n    int64_t len, k, k1;\n    int present;\n\n    acc = JS_UNDEFINED;\n    val = JS_UNDEFINED;\n    if (special & special_TA) {\n        obj = JS_DupValue(ctx, this_val);\n        len = js_typed_array_get_length_internal(ctx, obj);\n        if (len < 0)\n            goto exception;\n    } else {\n        obj = JS_ToObject(ctx, this_val);\n        if (js_get_length64(ctx, &len, obj))\n            goto exception;\n    }\n    func = argv[0];\n\n    if (check_function(ctx, func))\n        goto exception;\n\n    k = 0;\n    if (argc > 1) {\n        acc = JS_DupValue(ctx, argv[1]);\n    } else {\n        for(;;) {\n            if (k >= len) {\n                JS_ThrowTypeError(ctx, \"empty array\");\n                goto exception;\n            }\n            k1 = (special & special_reduceRight) ? len - k - 1 : k;\n            k++;\n            if (special & special_TA) {\n                acc = JS_GetPropertyInt64(ctx, obj, k1);\n                if (JS_IsException(acc))\n                    goto exception;\n                break;\n            } else {\n                present = JS_TryGetPropertyInt64(ctx, obj, k1, &acc);\n                if (present < 0)\n                    goto exception;\n                if (present)\n                    break;\n            }\n        }\n    }\n    for (; k < len; k++) {\n        k1 = (special & special_reduceRight) ? len - k - 1 : k;\n        if (special & special_TA) {\n            val = JS_GetPropertyInt64(ctx, obj, k1);\n            if (JS_IsException(val))\n                goto exception;\n            present = TRUE;\n        } else {\n            present = JS_TryGetPropertyInt64(ctx, obj, k1, &val);\n            if (present < 0)\n                goto exception;\n        }\n        if (present) {\n            index_val = JS_NewInt64(ctx, k1);\n            if (JS_IsException(index_val))\n                goto exception;\n            args[0] = acc;\n            args[1] = val;\n            args[2] = index_val;\n            args[3] = obj;\n            acc1 = JS_Call(ctx, func, JS_UNDEFINED, 4, args);\n            JS_FreeValue(ctx, index_val);\n            JS_FreeValue(ctx, val);\n            val = JS_UNDEFINED;\n            if (JS_IsException(acc1))\n                goto exception;\n            JS_FreeValue(ctx, acc);\n            acc = acc1;\n        }\n    }\n    JS_FreeValue(ctx, obj);\n    return acc;\n\nexception:\n    JS_FreeValue(ctx, acc);\n    JS_FreeValue(ctx, val);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_fill(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    JSValue obj;\n    int64_t len, start, end;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    start = 0;\n    if (argc > 1 && !JS_IsUndefined(argv[1])) {\n        if (JS_ToInt64Clamp(ctx, &start, argv[1], 0, len, len))\n            goto exception;\n    }\n\n    end = len;\n    if (argc > 2 && !JS_IsUndefined(argv[2])) {\n        if (JS_ToInt64Clamp(ctx, &end, argv[2], 0, len, len))\n            goto exception;\n    }\n\n    /* XXX: should special case fast arrays */\n    while (start < end) {\n        if (JS_SetPropertyInt64(ctx, obj, start,\n                                JS_DupValue(ctx, argv[0])) < 0)\n            goto exception;\n        start++;\n    }\n    return obj;\n\n exception:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_includes(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValue obj, val;\n    int64_t len, n, res;\n    JSValue *arrp;\n    uint32_t count;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    res = FALSE;\n    if (len > 0) {\n        n = 0;\n        if (argc > 1) {\n            if (JS_ToInt64Clamp(ctx, &n, argv[1], 0, len, len))\n                goto exception;\n        }\n        if (js_get_fast_array(ctx, obj, &arrp, &count)) {\n            for (; n < count; n++) {\n                if (js_strict_eq2(ctx, JS_DupValue(ctx, argv[0]),\n                                  JS_DupValue(ctx, arrp[n]),\n                                  JS_EQ_SAME_VALUE_ZERO)) {\n                    res = TRUE;\n                    goto done;\n                }\n            }\n        }\n        for (; n < len; n++) {\n            val = JS_GetPropertyInt64(ctx, obj, n);\n            if (JS_IsException(val))\n                goto exception;\n            if (js_strict_eq2(ctx, JS_DupValue(ctx, argv[0]), val,\n                              JS_EQ_SAME_VALUE_ZERO)) {\n                res = TRUE;\n                break;\n            }\n        }\n    }\n done:\n    JS_FreeValue(ctx, obj);\n    return JS_NewBool(ctx, res);\n\n exception:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_indexOf(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValue obj, val;\n    int64_t len, n, res;\n    JSValue *arrp;\n    uint32_t count;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    res = -1;\n    if (len > 0) {\n        n = 0;\n        if (argc > 1) {\n            if (JS_ToInt64Clamp(ctx, &n, argv[1], 0, len, len))\n                goto exception;\n        }\n        if (js_get_fast_array(ctx, obj, &arrp, &count)) {\n            for (; n < count; n++) {\n                if (js_strict_eq2(ctx, JS_DupValue(ctx, argv[0]),\n                                  JS_DupValue(ctx, arrp[n]), JS_EQ_STRICT)) {\n                    res = n;\n                    goto done;\n                }\n            }\n        }\n        for (; n < len; n++) {\n            int present = JS_TryGetPropertyInt64(ctx, obj, n, &val);\n            if (present < 0)\n                goto exception;\n            if (present) {\n                if (js_strict_eq2(ctx, JS_DupValue(ctx, argv[0]), val, JS_EQ_STRICT)) {\n                    res = n;\n                    break;\n                }\n            }\n        }\n    }\n done:\n    JS_FreeValue(ctx, obj);\n    return JS_NewInt64(ctx, res);\n\n exception:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_lastIndexOf(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSValue obj, val;\n    int64_t len, n, res;\n    int present;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    res = -1;\n    if (len > 0) {\n        n = len - 1;\n        if (argc > 1) {\n            if (JS_ToInt64Clamp(ctx, &n, argv[1], -1, len - 1, len))\n                goto exception;\n        }\n        /* XXX: should special case fast arrays */\n        for (; n >= 0; n--) {\n            present = JS_TryGetPropertyInt64(ctx, obj, n, &val);\n            if (present < 0)\n                goto exception;\n            if (present) {\n                if (js_strict_eq2(ctx, JS_DupValue(ctx, argv[0]), val, JS_EQ_STRICT)) {\n                    res = n;\n                    break;\n                }\n            }\n        }\n    }\n    JS_FreeValue(ctx, obj);\n    return JS_NewInt64(ctx, res);\n\n exception:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_find(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv, int findIndex)\n{\n    JSValueConst func, this_arg;\n    JSValueConst args[3];\n    JSValue obj, val, index_val, res;\n    int64_t len, k;\n\n    index_val = JS_UNDEFINED;\n    val = JS_UNDEFINED;\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    func = argv[0];\n    if (check_function(ctx, func))\n        goto exception;\n\n    this_arg = JS_UNDEFINED;\n    if (argc > 1)\n        this_arg = argv[1];\n\n    for(k = 0; k < len; k++) {\n        index_val = JS_NewInt64(ctx, k);\n        if (JS_IsException(index_val))\n            goto exception;\n        val = JS_GetPropertyValue(ctx, obj, index_val);\n        if (JS_IsException(val))\n            goto exception;\n        args[0] = val;\n        args[1] = index_val;\n        args[2] = this_val;\n        res = JS_Call(ctx, func, this_arg, 3, args);\n        if (JS_IsException(res))\n            goto exception;\n        if (JS_ToBoolFree(ctx, res)) {\n            if (findIndex) {\n                JS_FreeValue(ctx, val);\n                JS_FreeValue(ctx, obj);\n                return index_val;\n            } else {\n                JS_FreeValue(ctx, index_val);\n                JS_FreeValue(ctx, obj);\n                return val;\n            }\n        }\n        JS_FreeValue(ctx, val);\n        JS_FreeValue(ctx, index_val);\n    }\n    JS_FreeValue(ctx, obj);\n    if (findIndex)\n        return JS_NewInt32(ctx, -1);\n    else\n        return JS_UNDEFINED;\n\nexception:\n    JS_FreeValue(ctx, index_val);\n    JS_FreeValue(ctx, val);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_toString(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValue obj, method, ret;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    method = JS_GetProperty(ctx, obj, JS_ATOM_join);\n    if (JS_IsException(method)) {\n        ret = JS_EXCEPTION;\n    } else\n    if (!JS_IsFunction(ctx, method)) {\n        /* Use intrinsic Object.prototype.toString */\n        JS_FreeValue(ctx, method);\n        ret = js_object_toString(ctx, obj, 0, NULL);\n    } else {\n        ret = JS_CallFree(ctx, method, obj, 0, NULL);\n    }\n    JS_FreeValue(ctx, obj);\n    return ret;\n}\n\nstatic JSValue js_array_join(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv, int toLocaleString)\n{\n    JSValue obj, sep = JS_UNDEFINED, el;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p = NULL;\n    int64_t i, n;\n    int c;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &n, obj))\n        goto exception;\n\n    c = ',';    /* default separator */\n    if (!toLocaleString && argc > 0 && !JS_IsUndefined(argv[0])) {\n        sep = JS_ToString(ctx, argv[0]);\n        if (JS_IsException(sep))\n            goto exception;\n        p = JS_VALUE_GET_STRING(sep);\n        if (p->len == 1 && !p->is_wide_char)\n            c = p->u.str8[0];\n        else\n            c = -1;\n    }\n    string_buffer_init(ctx, b, 0);\n\n    for(i = 0; i < n; i++) {\n        if (i > 0) {\n            if (c >= 0) {\n                string_buffer_putc8(b, c);\n            } else {\n                string_buffer_concat(b, p, 0, p->len);\n            }\n        }\n        el = JS_GetPropertyUint32(ctx, obj, i);\n        if (JS_IsException(el))\n            goto fail;\n        if (!JS_IsNull(el) && !JS_IsUndefined(el)) {\n            if (toLocaleString) {\n                el = JS_ToLocaleStringFree(ctx, el);\n            }\n            if (string_buffer_concat_value_free(b, el))\n                goto fail;\n        }\n    }\n    JS_FreeValue(ctx, sep);\n    JS_FreeValue(ctx, obj);\n    return string_buffer_end(b);\n\nfail:\n    string_buffer_free(b);\n    JS_FreeValue(ctx, sep);\nexception:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_pop(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv, int shift)\n{\n    JSValue obj, res = JS_UNDEFINED;\n    int64_t len, newLen;\n    JSValue *arrp;\n    uint32_t count32;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n    newLen = 0;\n    if (len > 0) {\n        newLen = len - 1;\n        /* Special case fast arrays */\n        if (js_get_fast_array(ctx, obj, &arrp, &count32) && count32 == len) {\n            JSObject *p = JS_VALUE_GET_OBJ(obj);\n            if (shift) {\n                res = arrp[0];\n                memmove(arrp, arrp + 1, (count32 - 1) * sizeof(*arrp));\n                p->u.array.count--;\n            } else {\n                res = arrp[count32 - 1];\n                p->u.array.count--;\n            }\n        } else {\n            if (shift) {\n                res = JS_GetPropertyInt64(ctx, obj, 0);\n                if (JS_IsException(res))\n                    goto exception;\n                if (JS_CopySubArray(ctx, obj, 0, 1, len - 1, +1))\n                    goto exception;\n            } else {\n                res = JS_GetPropertyInt64(ctx, obj, newLen);\n                if (JS_IsException(res))\n                    goto exception;\n            }\n            if (JS_DeletePropertyInt64(ctx, obj, newLen, JS_PROP_THROW) < 0)\n                goto exception;\n        }\n    }\n    if (JS_SetProperty(ctx, obj, JS_ATOM_length, JS_NewInt64(ctx, newLen)) < 0)\n        goto exception;\n\n    JS_FreeValue(ctx, obj);\n    return res;\n\n exception:\n    JS_FreeValue(ctx, res);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_push(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv, int unshift)\n{\n    JSValue obj;\n    int i;\n    int64_t len, from, newLen;\n\n    obj = JS_ToObject(ctx, this_val);\n\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(obj);\n        if (p->class_id != JS_CLASS_ARRAY ||\n            !p->fast_array || !p->extensible)\n            goto generic_case;\n        /* length must be writable */\n        if (unlikely(!(get_shape_prop(p->shape)->flags & JS_PROP_WRITABLE)))\n            goto generic_case;\n        /* check the length */\n        if (unlikely(JS_VALUE_GET_TAG(p->prop[0].u.value) != JS_TAG_INT))\n            goto generic_case;\n        len = JS_VALUE_GET_INT(p->prop[0].u.value);\n        /* we don't support holes */\n        if (unlikely(len != p->u.array.count))\n            goto generic_case;\n        newLen = len + argc;\n        if (unlikely(newLen > INT32_MAX))\n            goto generic_case;\n        if (newLen > p->u.array.u1.size) {\n            if (expand_fast_array(ctx, p, newLen))\n                goto exception;\n        }\n        if (unshift && argc > 0) {\n            memmove(p->u.array.u.values + argc, p->u.array.u.values,\n                    len * sizeof(p->u.array.u.values[0]));\n            from = 0;\n        } else {\n            from = len;\n        }\n        for(i = 0; i < argc; i++) {\n            p->u.array.u.values[from + i] = JS_DupValue(ctx, argv[i]);\n        }\n        p->u.array.count = newLen;\n        p->prop[0].u.value = JS_NewInt32(ctx, newLen);\n    } else {\n    generic_case:\n        if (js_get_length64(ctx, &len, obj))\n            goto exception;\n        newLen = len + argc;\n        if (newLen > MAX_SAFE_INTEGER) {\n            JS_ThrowTypeError(ctx, \"Array loo long\");\n            goto exception;\n        }\n        from = len;\n        if (unshift && argc > 0) {\n            if (JS_CopySubArray(ctx, obj, argc, 0, len, -1))\n                goto exception;\n            from = 0;\n        }\n        for(i = 0; i < argc; i++) {\n            if (JS_SetPropertyInt64(ctx, obj, from + i,\n                                    JS_DupValue(ctx, argv[i])) < 0)\n                goto exception;\n        }\n        if (JS_SetProperty(ctx, obj, JS_ATOM_length, JS_NewInt64(ctx, newLen)) < 0)\n            goto exception;\n    }\n    JS_FreeValue(ctx, obj);\n    return JS_NewInt64(ctx, newLen);\n\n exception:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_reverse(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValue obj, lval, hval;\n    JSValue *arrp;\n    int64_t len, l, h;\n    int l_present, h_present;\n    uint32_t count32;\n\n    lval = JS_UNDEFINED;\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    /* Special case fast arrays */\n    if (js_get_fast_array(ctx, obj, &arrp, &count32) && count32 == len) {\n        uint32_t ll, hh;\n\n        if (count32 > 1) {\n            for (ll = 0, hh = count32 - 1; ll < hh; ll++, hh--) {\n                lval = arrp[ll];\n                arrp[ll] = arrp[hh];\n                arrp[hh] = lval;\n            }\n        }\n        return obj;\n    }\n\n    for (l = 0, h = len - 1; l < h; l++, h--) {\n        l_present = JS_TryGetPropertyInt64(ctx, obj, l, &lval);\n        if (l_present < 0)\n            goto exception;\n        h_present = JS_TryGetPropertyInt64(ctx, obj, h, &hval);\n        if (h_present < 0)\n            goto exception;\n        if (h_present) {\n            if (JS_SetPropertyInt64(ctx, obj, l, hval) < 0)\n                goto exception;\n\n            if (l_present) {\n                if (JS_SetPropertyInt64(ctx, obj, h, lval) < 0) {\n                    lval = JS_UNDEFINED;\n                    goto exception;\n                }\n                lval = JS_UNDEFINED;\n            } else {\n                if (JS_DeletePropertyInt64(ctx, obj, h, JS_PROP_THROW) < 0)\n                    goto exception;\n            }\n        } else {\n            if (l_present) {\n                if (JS_DeletePropertyInt64(ctx, obj, l, JS_PROP_THROW) < 0)\n                    goto exception;\n                if (JS_SetPropertyInt64(ctx, obj, h, lval) < 0) {\n                    lval = JS_UNDEFINED;\n                    goto exception;\n                }\n                lval = JS_UNDEFINED;\n            }\n        }\n    }\n    return obj;\n\n exception:\n    JS_FreeValue(ctx, lval);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_slice(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int splice)\n{\n    JSValue obj, arr, val, len_val;\n    int64_t len, start, k, final, n, count, del_count, new_len;\n    int kPresent;\n    JSValue *arrp;\n    uint32_t count32, i, item_count;\n\n    arr = JS_UNDEFINED;\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    if (JS_ToInt64Clamp(ctx, &start, argv[0], 0, len, len))\n        goto exception;\n\n    if (splice) {\n        if (argc == 0) {\n            item_count = 0;\n            del_count = 0;\n        } else\n        if (argc == 1) {\n            item_count = 0;\n            del_count = len - start;\n        } else {\n            item_count = argc - 2;\n            if (JS_ToInt64Clamp(ctx, &del_count, argv[1], 0, len - start, 0))\n                goto exception;\n        }\n        if (len + item_count - del_count > MAX_SAFE_INTEGER) {\n            JS_ThrowTypeError(ctx, \"Array loo long\");\n            goto exception;\n        }\n        count = del_count;\n    } else {\n        item_count = 0; /* avoid warning */\n        final = len;\n        if (!JS_IsUndefined(argv[1])) {\n            if (JS_ToInt64Clamp(ctx, &final, argv[1], 0, len, len))\n                goto exception;\n        }\n        count = max_int64(final - start, 0);\n    }\n    len_val = JS_NewInt64(ctx, count);\n    arr = JS_ArraySpeciesCreate(ctx, obj, len_val);\n    JS_FreeValue(ctx, len_val);\n    if (JS_IsException(arr))\n        goto exception;\n\n    k = start;\n    final = start + count;\n    n = 0;\n    /* The fast array test on arr ensures that\n       JS_CreateDataPropertyUint32() won't modify obj in case arr is\n       an exotic object */\n    /* Special case fast arrays */\n    if (js_get_fast_array(ctx, obj, &arrp, &count32) &&\n        js_is_fast_array(ctx, arr)) {\n        /* XXX: should share code with fast array constructor */\n        for (; k < final && k < count32; k++, n++) {\n            if (JS_CreateDataPropertyUint32(ctx, arr, n, JS_DupValue(ctx, arrp[k]), JS_PROP_THROW) < 0)\n                goto exception;\n        }\n    }\n    /* Copy the remaining elements if any (handle case of inherited properties) */\n    for (; k < final; k++, n++) {\n        kPresent = JS_TryGetPropertyInt64(ctx, obj, k, &val);\n        if (kPresent < 0)\n            goto exception;\n        if (kPresent) {\n            if (JS_CreateDataPropertyUint32(ctx, arr, n, val, JS_PROP_THROW) < 0)\n                goto exception;\n        }\n    }\n    if (JS_SetProperty(ctx, arr, JS_ATOM_length, JS_NewInt64(ctx, n)) < 0)\n        goto exception;\n\n    if (splice) {\n        new_len = len + item_count - del_count;\n        if (item_count != del_count) {\n            if (JS_CopySubArray(ctx, obj, start + item_count,\n                                start + del_count, len - (start + del_count),\n                                item_count <= del_count ? +1 : -1) < 0)\n                goto exception;\n\n            for (k = len; k-- > new_len; ) {\n                if (JS_DeletePropertyInt64(ctx, obj, k, JS_PROP_THROW) < 0)\n                    goto exception;\n            }\n        }\n        for (i = 0; i < item_count; i++) {\n            if (JS_SetPropertyInt64(ctx, obj, start + i, JS_DupValue(ctx, argv[i + 2])) < 0)\n                goto exception;\n        }\n        if (JS_SetProperty(ctx, obj, JS_ATOM_length, JS_NewInt64(ctx, new_len)) < 0)\n            goto exception;\n    }\n    JS_FreeValue(ctx, obj);\n    return arr;\n\n exception:\n    JS_FreeValue(ctx, obj);\n    JS_FreeValue(ctx, arr);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_copyWithin(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    JSValue obj;\n    int64_t len, from, to, final, count;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    if (JS_ToInt64Clamp(ctx, &to, argv[0], 0, len, len))\n        goto exception;\n\n    if (JS_ToInt64Clamp(ctx, &from, argv[1], 0, len, len))\n        goto exception;\n\n    final = len;\n    if (argc > 2 && !JS_IsUndefined(argv[2])) {\n        if (JS_ToInt64Clamp(ctx, &final, argv[2], 0, len, len))\n            goto exception;\n    }\n\n    count = min_int64(final - from, len - to);\n\n    if (JS_CopySubArray(ctx, obj, to, from, count,\n                        (from < to && to < from + count) ? -1 : +1))\n        goto exception;\n\n    return obj;\n\n exception:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic int64_t JS_FlattenIntoArray(JSContext *ctx, JSValueConst target,\n                                   JSValueConst source, int64_t sourceLen,\n                                   int64_t targetIndex, int depth,\n                                   JSValueConst mapperFunction,\n                                   JSValueConst thisArg)\n{\n    JSValue element;\n    int64_t sourceIndex, elementLen;\n    int present, is_array;\n\n    if (js_check_stack_overflow(ctx->rt, 0)) {\n        JS_ThrowStackOverflow(ctx);\n        return -1;\n    }\n\n    for (sourceIndex = 0; sourceIndex < sourceLen; sourceIndex++) {\n        present = JS_TryGetPropertyInt64(ctx, source, sourceIndex, &element);\n        if (present < 0)\n            return -1;\n        if (!present)\n            continue;\n        if (!JS_IsUndefined(mapperFunction)) {\n            JSValueConst args[3] = { element, JS_NewInt64(ctx, sourceIndex), source };\n            element = JS_Call(ctx, mapperFunction, thisArg, 3, args);\n            JS_FreeValue(ctx, (JSValue)args[0]);\n            JS_FreeValue(ctx, (JSValue)args[1]);\n            if (JS_IsException(element))\n                return -1;\n        }\n        if (depth > 0) {\n            is_array = JS_IsArray(ctx, element);\n            if (is_array < 0)\n                goto fail;\n            if (is_array) {\n                if (js_get_length64(ctx, &elementLen, element) < 0)\n                    goto fail;\n                targetIndex = JS_FlattenIntoArray(ctx, target, element,\n                                                  elementLen, targetIndex,\n                                                  depth - 1,\n                                                  JS_UNDEFINED, JS_UNDEFINED);\n                if (targetIndex < 0)\n                    goto fail;\n                JS_FreeValue(ctx, element);\n                continue;\n            }\n        }\n        if (targetIndex >= MAX_SAFE_INTEGER) {\n            JS_ThrowTypeError(ctx, \"Array too long\");\n            goto fail;\n        }\n        if (JS_DefinePropertyValueInt64(ctx, target, targetIndex, element,\n                                        JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n            return -1;\n        targetIndex++;\n    }\n    return targetIndex;\n\nfail:\n    JS_FreeValue(ctx, element);\n    return -1;\n}\n\nstatic JSValue js_array_flatten(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv, int map)\n{\n    JSValue obj, arr;\n    JSValueConst mapperFunction, thisArg;\n    int64_t sourceLen;\n    int depthNum;\n\n    arr = JS_UNDEFINED;\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &sourceLen, obj))\n        goto exception;\n\n    depthNum = 1;\n    mapperFunction = JS_UNDEFINED;\n    thisArg = JS_UNDEFINED;\n    if (map) {\n        mapperFunction = argv[0];\n        if (argc > 1) {\n            thisArg = argv[1];\n        }\n        if (check_function(ctx, mapperFunction))\n            goto exception;\n    } else {\n        if (argc > 0 && !JS_IsUndefined(argv[0])) {\n            if (JS_ToInt32Sat(ctx, &depthNum, argv[0]) < 0)\n                goto exception;\n        }\n    }\n    arr = JS_ArraySpeciesCreate(ctx, obj, JS_NewInt32(ctx, 0));\n    if (JS_IsException(arr))\n        goto exception;\n    if (JS_FlattenIntoArray(ctx, arr, obj, sourceLen, 0, depthNum,\n                            mapperFunction, thisArg) < 0)\n        goto exception;\n    JS_FreeValue(ctx, obj);\n    return arr;\n\nexception:\n    JS_FreeValue(ctx, obj);\n    JS_FreeValue(ctx, arr);\n    return JS_EXCEPTION;\n}\n\n/* Array sort */\n\ntypedef struct ValueSlot {\n    JSValue val;\n    JSString *str;\n    int64_t pos;\n} ValueSlot;\n\nstruct array_sort_context {\n    JSContext *ctx;\n    int exception;\n    int has_method;\n    JSValueConst method;\n};\n\nstatic int js_array_cmp_generic(const void *a, const void *b, void *opaque) {\n    struct array_sort_context *psc = opaque;\n    JSContext *ctx = psc->ctx;\n    JSValueConst argv[2];\n    JSValue res;\n    ValueSlot *ap = (ValueSlot *)(void *)a;\n    ValueSlot *bp = (ValueSlot *)(void *)b;\n    int cmp;\n\n    if (psc->exception)\n        return 0;\n\n    if (psc->has_method) {\n        /* custom sort function is specified as returning 0 for identical\n         * objects: avoid method call overhead.\n         */\n        if (!memcmp(&ap->val, &bp->val, sizeof(ap->val)))\n            goto cmp_same;\n        argv[0] = ap->val;\n        argv[1] = bp->val;\n        res = JS_Call(ctx, psc->method, JS_UNDEFINED, 2, argv);\n        if (JS_IsException(res))\n            goto exception;\n        if (JS_VALUE_GET_TAG(res) == JS_TAG_INT) {\n            int val = JS_VALUE_GET_INT(res);\n            cmp = (val > 0) - (val < 0);\n        } else {\n            double val;\n            if (JS_ToFloat64Free(ctx, &val, res) < 0)\n                goto exception;\n            cmp = (val > 0) - (val < 0);\n        }\n    } else {\n        /* Not supposed to bypass ToString even for identical objects as\n         * tested in test262/test/built-ins/Array/prototype/sort/bug_596_1.js\n         */\n        if (!ap->str) {\n            JSValue str = JS_ToString(ctx, ap->val);\n            if (JS_IsException(str))\n                goto exception;\n            ap->str = JS_VALUE_GET_STRING(str);\n        }\n        if (!bp->str) {\n            JSValue str = JS_ToString(ctx, bp->val);\n            if (JS_IsException(str))\n                goto exception;\n            bp->str = JS_VALUE_GET_STRING(str);\n        }\n        cmp = js_string_compare(ctx, ap->str, bp->str);\n    }\n    if (cmp != 0)\n        return cmp;\ncmp_same:\n    /* make sort stable: compare array offsets */\n    return (ap->pos > bp->pos) - (ap->pos < bp->pos);\n\nexception:\n    psc->exception = 1;\n    return 0;\n}\n\nstatic JSValue js_array_sort(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    struct array_sort_context asc = { ctx, 0, 0, argv[0] };\n    JSValue obj = JS_UNDEFINED;\n    ValueSlot *array = NULL;\n    size_t array_size = 0, pos = 0, n = 0;\n    int64_t i, len, undefined_count = 0;\n    int present;\n\n    if (!JS_IsUndefined(asc.method)) {\n        if (check_function(ctx, asc.method))\n            goto exception;\n        asc.has_method = 1;\n    }\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    /* XXX: should special case fast arrays */\n    for (i = 0; i < len; i++) {\n        if (pos >= array_size) {\n            size_t new_size, slack;\n            ValueSlot *new_array;\n            new_size = (array_size + (array_size >> 1) + 31) & ~15;\n            new_array = js_realloc2(ctx, array, new_size * sizeof(*array), &slack);\n            if (new_array == NULL)\n                goto exception;\n            new_size += slack / sizeof(*new_array);\n            array = new_array;\n            array_size = new_size;\n        }\n        present = JS_TryGetPropertyInt64(ctx, obj, i, &array[pos].val);\n        if (present < 0)\n            goto exception;\n        if (present == 0)\n            continue;\n        if (JS_IsUndefined(array[pos].val)) {\n            undefined_count++;\n            continue;\n        }\n        array[pos].str = NULL;\n        array[pos].pos = i;\n        pos++;\n    }\n    rqsort(array, pos, sizeof(*array), js_array_cmp_generic, &asc);\n    if (asc.exception)\n        goto exception;\n\n    /* XXX: should special case fast arrays */\n    while (n < pos) {\n        if (array[n].str)\n            JS_FreeValue(ctx, JS_MKPTR(JS_TAG_STRING, array[n].str));\n        if (array[n].pos == n) {\n            JS_FreeValue(ctx, array[n].val);\n        } else {\n            if (JS_SetPropertyInt64(ctx, obj, n, array[n].val) < 0) {\n                n++;\n                goto exception;\n            }\n        }\n        n++;\n    }\n    js_free(ctx, array);\n    for (i = n; undefined_count-- > 0; i++) {\n        if (JS_SetPropertyInt64(ctx, obj, i, JS_UNDEFINED) < 0)\n            goto fail;\n    }\n    for (; i < len; i++) {\n        if (JS_DeletePropertyInt64(ctx, obj, i, JS_PROP_THROW) < 0)\n            goto fail;\n    }\n    return obj;\n\nexception:\n    for (; n < pos; n++) {\n        JS_FreeValue(ctx, array[n].val);\n        if (array[n].str)\n            JS_FreeValue(ctx, JS_MKPTR(JS_TAG_STRING, array[n].str));\n    }\n    js_free(ctx, array);\nfail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\ntypedef struct JSArrayIteratorData {\n    JSValue obj;\n    JSIteratorKindEnum kind;\n    uint32_t idx;\n} JSArrayIteratorData;\n\nstatic void js_array_iterator_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSArrayIteratorData *it = p->u.array_iterator_data;\n    if (it) {\n        JS_FreeValueRT(rt, it->obj);\n        js_free_rt(rt, it);\n    }\n}\n\nstatic void js_array_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                   JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSArrayIteratorData *it = p->u.array_iterator_data;\n    if (it) {\n        JS_MarkValue(rt, it->obj, mark_func);\n    }\n}\n\nstatic JSValue js_create_array(JSContext *ctx, int len, JSValueConst *tab)\n{\n    JSValue obj;\n    int i;\n\n    obj = JS_NewArray(ctx);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    for(i = 0; i < len; i++) {\n        if (JS_CreateDataPropertyUint32(ctx, obj, i, JS_DupValue(ctx, tab[i]), 0) < 0) {\n            JS_FreeValue(ctx, obj);\n            return JS_EXCEPTION;\n        }\n    }\n    return obj;\n}\n\nstatic JSValue js_create_array_iterator(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv, int magic)\n{\n    JSValue enum_obj, arr;\n    JSArrayIteratorData *it;\n    JSIteratorKindEnum kind;\n    int class_id;\n\n    kind = magic & 3;\n    if (magic & 4) {\n        /* string iterator case */\n        arr = JS_ToStringCheckObject(ctx, this_val);\n        class_id = JS_CLASS_STRING_ITERATOR;\n    } else {\n        arr = JS_ToObject(ctx, this_val);\n        class_id = JS_CLASS_ARRAY_ITERATOR;\n    }\n    if (JS_IsException(arr))\n        goto fail;\n    enum_obj = JS_NewObjectClass(ctx, class_id);\n    if (JS_IsException(enum_obj))\n        goto fail;\n    it = js_malloc(ctx, sizeof(*it));\n    if (!it)\n        goto fail1;\n    it->obj = arr;\n    it->kind = kind;\n    it->idx = 0;\n    JS_SetOpaque(enum_obj, it);\n    return enum_obj;\n fail1:\n    JS_FreeValue(ctx, enum_obj);\n fail:\n    JS_FreeValue(ctx, arr);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_iterator_next(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv,\n                                      BOOL *pdone, int magic)\n{\n    JSArrayIteratorData *it;\n    uint32_t len, idx;\n    JSValue val, obj;\n    JSObject *p;\n\n    it = JS_GetOpaque2(ctx, this_val, JS_CLASS_ARRAY_ITERATOR);\n    if (!it)\n        goto fail1;\n    if (JS_IsUndefined(it->obj))\n        goto done;\n    p = JS_VALUE_GET_OBJ(it->obj);\n    if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n        p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n        if (typed_array_is_detached(ctx, p)) {\n            JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n            goto fail1;\n        }\n        len = p->u.array.count;\n    } else {\n        if (js_get_length32(ctx, &len, it->obj)) {\n        fail1:\n            *pdone = FALSE;\n            return JS_EXCEPTION;\n        }\n    }\n    idx = it->idx;\n    if (idx >= len) {\n        JS_FreeValue(ctx, it->obj);\n        it->obj = JS_UNDEFINED;\n    done:\n        *pdone = TRUE;\n        return JS_UNDEFINED;\n    }\n    it->idx = idx + 1;\n    *pdone = FALSE;\n    if (it->kind == JS_ITERATOR_KIND_KEY) {\n        return JS_NewUint32(ctx, idx);\n    } else {\n        val = JS_GetPropertyUint32(ctx, it->obj, idx);\n        if (JS_IsException(val))\n            return JS_EXCEPTION;\n        if (it->kind == JS_ITERATOR_KIND_VALUE) {\n            return val;\n        } else {\n            JSValueConst args[2];\n            JSValue num;\n            num = JS_NewUint32(ctx, idx);\n            args[0] = num;\n            args[1] = val;\n            obj = js_create_array(ctx, 2, args);\n            JS_FreeValue(ctx, val);\n            JS_FreeValue(ctx, num);\n            return obj;\n        }\n    }\n}\n\nstatic JSValue js_iterator_proto_iterator(JSContext *ctx, JSValueConst this_val,\n                                          int argc, JSValueConst *argv)\n{\n    return JS_DupValue(ctx, this_val);\n}\n\nstatic const JSCFunctionListEntry js_iterator_proto_funcs[] = {\n    JS_CFUNC_DEF(\"[Symbol.iterator]\", 0, js_iterator_proto_iterator ),\n};\n\nstatic const JSCFunctionListEntry js_array_proto_funcs[] = {\n    JS_CFUNC_DEF(\"concat\", 1, js_array_concat ),\n    JS_CFUNC_MAGIC_DEF(\"every\", 1, js_array_every, special_every ),\n    JS_CFUNC_MAGIC_DEF(\"some\", 1, js_array_every, special_some ),\n    JS_CFUNC_MAGIC_DEF(\"forEach\", 1, js_array_every, special_forEach ),\n    JS_CFUNC_MAGIC_DEF(\"map\", 1, js_array_every, special_map ),\n    JS_CFUNC_MAGIC_DEF(\"filter\", 1, js_array_every, special_filter ),\n    JS_CFUNC_MAGIC_DEF(\"reduce\", 1, js_array_reduce, special_reduce ),\n    JS_CFUNC_MAGIC_DEF(\"reduceRight\", 1, js_array_reduce, special_reduceRight ),\n    JS_CFUNC_DEF(\"fill\", 1, js_array_fill ),\n    JS_CFUNC_MAGIC_DEF(\"find\", 1, js_array_find, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"findIndex\", 1, js_array_find, 1 ),\n    JS_CFUNC_DEF(\"indexOf\", 1, js_array_indexOf ),\n    JS_CFUNC_DEF(\"lastIndexOf\", 1, js_array_lastIndexOf ),\n    JS_CFUNC_DEF(\"includes\", 1, js_array_includes ),\n    JS_CFUNC_MAGIC_DEF(\"join\", 1, js_array_join, 0 ),\n    JS_CFUNC_DEF(\"toString\", 0, js_array_toString ),\n    JS_CFUNC_MAGIC_DEF(\"toLocaleString\", 0, js_array_join, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"pop\", 0, js_array_pop, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"push\", 1, js_array_push, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"shift\", 0, js_array_pop, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"unshift\", 1, js_array_push, 1 ),\n    JS_CFUNC_DEF(\"reverse\", 0, js_array_reverse ),\n    JS_CFUNC_DEF(\"sort\", 1, js_array_sort ),\n    JS_CFUNC_MAGIC_DEF(\"slice\", 2, js_array_slice, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"splice\", 2, js_array_slice, 1 ),\n    JS_CFUNC_DEF(\"copyWithin\", 2, js_array_copyWithin ),\n    JS_CFUNC_MAGIC_DEF(\"flatMap\", 1, js_array_flatten, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"flat\", 0, js_array_flatten, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"values\", 0, js_create_array_iterator, JS_ITERATOR_KIND_VALUE ),\n    JS_ALIAS_DEF(\"[Symbol.iterator]\", \"values\" ),\n    JS_CFUNC_MAGIC_DEF(\"keys\", 0, js_create_array_iterator, JS_ITERATOR_KIND_KEY ),\n    JS_CFUNC_MAGIC_DEF(\"entries\", 0, js_create_array_iterator, JS_ITERATOR_KIND_KEY_AND_VALUE ),\n};\n\nstatic const JSCFunctionListEntry js_array_iterator_proto_funcs[] = {\n    JS_ITERATOR_NEXT_DEF(\"next\", 0, js_array_iterator_next, 0 ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Array Iterator\", JS_PROP_CONFIGURABLE ),\n};\n\n/* Number */\n\nstatic JSValue js_number_constructor(JSContext *ctx, JSValueConst new_target,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue val, obj;\n    if (argc == 0) {\n        val = JS_NewInt32(ctx, 0);\n    } else {\n        val = JS_ToNumeric(ctx, argv[0]);\n        if (JS_IsException(val))\n            return val;\n        switch(JS_VALUE_GET_TAG(val)) {\n#ifdef CONFIG_BIGNUM\n        case JS_TAG_BIG_INT:\n        case JS_TAG_BIG_FLOAT:\n            {\n                JSBigFloat *p = JS_VALUE_GET_PTR(val);\n                double d;\n                bf_get_float64(&p->num, &d, BF_RNDN);\n                JS_FreeValue(ctx, val);\n                val = __JS_NewFloat64(ctx, d);\n            }\n            break;\n        case JS_TAG_BIG_DECIMAL:\n            val = JS_ToStringFree(ctx, val);\n            if (JS_IsException(val))\n                return val;\n            val = JS_ToNumberFree(ctx, val);\n            if (JS_IsException(val))\n                return val;\n            break;\n#endif\n        default:\n            break;\n        }\n    }\n    if (!JS_IsUndefined(new_target)) {\n        obj = js_create_from_ctor(ctx, new_target, JS_CLASS_NUMBER);\n        if (!JS_IsException(obj))\n            JS_SetObjectData(ctx, obj, val);\n        return obj;\n    } else {\n        return val;\n    }\n}\n\n#if 0\nstatic JSValue js_number___toInteger(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    return JS_ToIntegerFree(ctx, JS_DupValue(ctx, argv[0]));\n}\n\nstatic JSValue js_number___toLength(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    int64_t v;\n    if (JS_ToLengthFree(ctx, &v, JS_DupValue(ctx, argv[0])))\n        return JS_EXCEPTION;\n    return JS_NewInt64(ctx, v);\n}\n#endif\n\nstatic JSValue js_number_isNaN(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    if (!JS_IsNumber(argv[0]))\n        return JS_FALSE;\n    return js_global_isNaN(ctx, this_val, argc, argv);\n}\n\nstatic JSValue js_number_isFinite(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    if (!JS_IsNumber(argv[0]))\n        return JS_FALSE;\n    return js_global_isFinite(ctx, this_val, argc, argv);\n}\n\nstatic JSValue js_number_isInteger(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    int ret;\n    ret = JS_NumberIsInteger(ctx, argv[0]);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_number_isSafeInteger(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    double d;\n    if (!JS_IsNumber(argv[0]))\n        return JS_FALSE;\n    if (unlikely(JS_ToFloat64(ctx, &d, argv[0])))\n        return JS_EXCEPTION;\n    return JS_NewBool(ctx, is_safe_integer(d));\n}\n\nstatic const JSCFunctionListEntry js_number_funcs[] = {\n    /* global ParseInt and parseFloat should be defined already or delayed */\n    JS_ALIAS_BASE_DEF(\"parseInt\", \"parseInt\", 0 ),\n    JS_ALIAS_BASE_DEF(\"parseFloat\", \"parseFloat\", 0 ),\n    JS_CFUNC_DEF(\"isNaN\", 1, js_number_isNaN ),\n    JS_CFUNC_DEF(\"isFinite\", 1, js_number_isFinite ),\n    JS_CFUNC_DEF(\"isInteger\", 1, js_number_isInteger ),\n    JS_CFUNC_DEF(\"isSafeInteger\", 1, js_number_isSafeInteger ),\n    JS_PROP_DOUBLE_DEF(\"MAX_VALUE\", 1.7976931348623157e+308, 0 ),\n    JS_PROP_DOUBLE_DEF(\"MIN_VALUE\", 5e-324, 0 ),\n    JS_PROP_DOUBLE_DEF(\"NaN\", NAN, 0 ),\n    JS_PROP_DOUBLE_DEF(\"NEGATIVE_INFINITY\", -INFINITY, 0 ),\n    JS_PROP_DOUBLE_DEF(\"POSITIVE_INFINITY\", INFINITY, 0 ),\n    JS_PROP_DOUBLE_DEF(\"EPSILON\", 2.220446049250313e-16, 0 ), /* ES6 */\n    JS_PROP_DOUBLE_DEF(\"MAX_SAFE_INTEGER\", 9007199254740991.0, 0 ), /* ES6 */\n    JS_PROP_DOUBLE_DEF(\"MIN_SAFE_INTEGER\", -9007199254740991.0, 0 ), /* ES6 */\n    //JS_CFUNC_DEF(\"__toInteger\", 1, js_number___toInteger ),\n    //JS_CFUNC_DEF(\"__toLength\", 1, js_number___toLength ),\n};\n\nstatic JSValue js_thisNumberValue(JSContext *ctx, JSValueConst this_val)\n{\n    if (JS_IsNumber(this_val))\n        return JS_DupValue(ctx, this_val);\n\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_NUMBER) {\n            if (JS_IsNumber(p->u.object_data))\n                return JS_DupValue(ctx, p->u.object_data);\n        }\n    }\n    return JS_ThrowTypeError(ctx, \"not a number\");\n}\n\nstatic JSValue js_number_valueOf(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    return js_thisNumberValue(ctx, this_val);\n}\n\nstatic int js_get_radix(JSContext *ctx, JSValueConst val)\n{\n    int radix;\n    if (JS_ToInt32Sat(ctx, &radix, val))\n        return -1;\n    if (radix < 2 || radix > 36) {\n        JS_ThrowRangeError(ctx, \"radix must be between 2 and 36\");\n        return -1;\n    }\n    return radix;\n}\n\nstatic JSValue js_number_toString(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv, int magic)\n{\n    JSValue val;\n    int base;\n    double d;\n\n    val = js_thisNumberValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (magic || JS_IsUndefined(argv[0])) {\n        base = 10;\n    } else {\n        base = js_get_radix(ctx, argv[0]);\n        if (base < 0)\n            goto fail;\n    }\n    if (JS_ToFloat64Free(ctx, &d, val))\n        return JS_EXCEPTION;\n    return js_dtoa(ctx, d, base, 0, JS_DTOA_VAR_FORMAT);\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_number_toFixed(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValue val;\n    int f;\n    double d;\n\n    val = js_thisNumberValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_ToFloat64Free(ctx, &d, val))\n        return JS_EXCEPTION;\n    if (JS_ToInt32Sat(ctx, &f, argv[0]))\n        return JS_EXCEPTION;\n    if (f < 0 || f > 100)\n        return JS_ThrowRangeError(ctx, \"invalid number of digits\");\n    if (fabs(d) >= 1e21) {\n        return JS_ToStringFree(ctx, __JS_NewFloat64(ctx, d));\n    } else {\n        return js_dtoa(ctx, d, 10, f, JS_DTOA_FRAC_FORMAT);\n    }\n}\n\nstatic JSValue js_number_toExponential(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    JSValue val;\n    int f, flags;\n    double d;\n\n    val = js_thisNumberValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_ToFloat64Free(ctx, &d, val))\n        return JS_EXCEPTION;\n    if (JS_ToInt32Sat(ctx, &f, argv[0]))\n        return JS_EXCEPTION;\n    if (!isfinite(d)) {\n        return JS_ToStringFree(ctx,  __JS_NewFloat64(ctx, d));\n    }\n    if (JS_IsUndefined(argv[0])) {\n        flags = 0;\n        f = 0;\n    } else {\n        if (f < 0 || f > 100)\n            return JS_ThrowRangeError(ctx, \"invalid number of digits\");\n        f++;\n        flags = JS_DTOA_FIXED_FORMAT;\n    }\n    return js_dtoa(ctx, d, 10, f, flags | JS_DTOA_FORCE_EXP);\n}\n\nstatic JSValue js_number_toPrecision(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue val;\n    int p;\n    double d;\n\n    val = js_thisNumberValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_ToFloat64Free(ctx, &d, val))\n        return JS_EXCEPTION;\n    if (JS_IsUndefined(argv[0]))\n        goto to_string;\n    if (JS_ToInt32Sat(ctx, &p, argv[0]))\n        return JS_EXCEPTION;\n    if (!isfinite(d)) {\n    to_string:\n        return JS_ToStringFree(ctx,  __JS_NewFloat64(ctx, d));\n    }\n    if (p < 1 || p > 100)\n        return JS_ThrowRangeError(ctx, \"invalid number of digits\");\n    return js_dtoa(ctx, d, 10, p, JS_DTOA_FIXED_FORMAT);\n}\n\nstatic const JSCFunctionListEntry js_number_proto_funcs[] = {\n    JS_CFUNC_DEF(\"toExponential\", 1, js_number_toExponential ),\n    JS_CFUNC_DEF(\"toFixed\", 1, js_number_toFixed ),\n    JS_CFUNC_DEF(\"toPrecision\", 1, js_number_toPrecision ),\n    JS_CFUNC_MAGIC_DEF(\"toString\", 1, js_number_toString, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"toLocaleString\", 0, js_number_toString, 1 ),\n    JS_CFUNC_DEF(\"valueOf\", 0, js_number_valueOf ),\n};\n\nstatic JSValue js_parseInt(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    const char *str, *p;\n    int radix, flags;\n    JSValue ret;\n\n    str = JS_ToCString(ctx, argv[0]);\n    if (!str)\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &radix, argv[1])) {\n        JS_FreeCString(ctx, str);\n        return JS_EXCEPTION;\n    }\n    if (radix != 0 && (radix < 2 || radix > 36)) {\n        ret = JS_NAN;\n    } else {\n        p = str;\n        p += skip_spaces(p);\n        flags = ATOD_INT_ONLY | ATOD_ACCEPT_PREFIX_AFTER_SIGN;\n        ret = js_atof(ctx, p, NULL, radix, flags);\n    }\n    JS_FreeCString(ctx, str);\n    return ret;\n}\n\nstatic JSValue js_parseFloat(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    const char *str, *p;\n    JSValue ret;\n\n    str = JS_ToCString(ctx, argv[0]);\n    if (!str)\n        return JS_EXCEPTION;\n    p = str;\n    p += skip_spaces(p);\n    ret = js_atof(ctx, p, NULL, 10, 0);\n    JS_FreeCString(ctx, str);\n    return ret;\n}\n\n/* Boolean */\nstatic JSValue js_boolean_constructor(JSContext *ctx, JSValueConst new_target,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue val, obj;\n    val = JS_NewBool(ctx, JS_ToBool(ctx, argv[0]));\n    if (!JS_IsUndefined(new_target)) {\n        obj = js_create_from_ctor(ctx, new_target, JS_CLASS_BOOLEAN);\n        if (!JS_IsException(obj))\n            JS_SetObjectData(ctx, obj, val);\n        return obj;\n    } else {\n        return val;\n    }\n}\n\nstatic JSValue js_thisBooleanValue(JSContext *ctx, JSValueConst this_val)\n{\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_BOOL)\n        return JS_DupValue(ctx, this_val);\n\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_BOOLEAN) {\n            if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_BOOL)\n                return p->u.object_data;\n        }\n    }\n    return JS_ThrowTypeError(ctx, \"not a boolean\");\n}\n\nstatic JSValue js_boolean_toString(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    JSValue val = js_thisBooleanValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    return JS_AtomToString(ctx, JS_VALUE_GET_BOOL(val) ?\n                       JS_ATOM_true : JS_ATOM_false);\n}\n\nstatic JSValue js_boolean_valueOf(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    return js_thisBooleanValue(ctx, this_val);\n}\n\nstatic const JSCFunctionListEntry js_boolean_proto_funcs[] = {\n    JS_CFUNC_DEF(\"toString\", 0, js_boolean_toString ),\n    JS_CFUNC_DEF(\"valueOf\", 0, js_boolean_valueOf ),\n};\n\n/* String */\n\nstatic int js_string_get_own_property(JSContext *ctx,\n                                      JSPropertyDescriptor *desc,\n                                      JSValueConst obj, JSAtom prop)\n{\n    JSObject *p;\n    JSString *p1;\n    uint32_t idx, ch;\n\n    /* This is a class exotic method: obj class_id is JS_CLASS_STRING */\n    if (__JS_AtomIsTaggedInt(prop)) {\n        p = JS_VALUE_GET_OBJ(obj);\n        if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_STRING) {\n            p1 = JS_VALUE_GET_STRING(p->u.object_data);\n            idx = __JS_AtomToUInt32(prop);\n            if (idx < p1->len) {\n                if (desc) {\n                    if (p1->is_wide_char)\n                        ch = p1->u.str16[idx];\n                    else\n                        ch = p1->u.str8[idx];\n                    desc->flags = JS_PROP_ENUMERABLE;\n                    desc->value = js_new_string_char(ctx, ch);\n                    desc->getter = JS_UNDEFINED;\n                    desc->setter = JS_UNDEFINED;\n                }\n                return TRUE;\n            }\n        }\n    }\n    return FALSE;\n}\n\nstatic int js_string_define_own_property(JSContext *ctx,\n                                         JSValueConst this_obj,\n                                         JSAtom prop, JSValueConst val,\n                                         JSValueConst getter,\n                                         JSValueConst setter, int flags)\n{\n    uint32_t idx;\n    JSObject *p;\n    JSString *p1, *p2;\n    \n    if (__JS_AtomIsTaggedInt(prop)) {\n        idx = __JS_AtomToUInt32(prop);\n        p = JS_VALUE_GET_OBJ(this_obj);\n        if (JS_VALUE_GET_TAG(p->u.object_data) != JS_TAG_STRING)\n            goto def;\n        p1 = JS_VALUE_GET_STRING(p->u.object_data);\n        if (idx >= p1->len)\n            goto def;\n        if (!check_define_prop_flags(JS_PROP_ENUMERABLE, flags))\n            goto fail;\n        /* check that the same value is configured */\n        if (flags & JS_PROP_HAS_VALUE) {\n            if (JS_VALUE_GET_TAG(val) != JS_TAG_STRING)\n                goto fail;\n            p2 = JS_VALUE_GET_STRING(val);\n            if (p2->len != 1)\n                goto fail;\n            if (string_get(p1, idx) != string_get(p2, 0)) {\n            fail:\n                return JS_ThrowTypeErrorOrFalse(ctx, flags, \"property is not configurable\");\n            }\n        }\n        return TRUE;\n    } else {\n    def:\n        return JS_DefineProperty(ctx, this_obj, prop, val, getter, setter,\n                                 flags | JS_PROP_NO_EXOTIC);\n    }\n}\n\nstatic int js_string_delete_property(JSContext *ctx,\n                                     JSValueConst obj, JSAtom prop)\n{\n    uint32_t idx;\n\n    if (__JS_AtomIsTaggedInt(prop)) {\n        idx = __JS_AtomToUInt32(prop);\n        if (idx < js_string_obj_get_length(ctx, obj)) {\n            return FALSE;\n        }\n    }\n    return TRUE;\n}\n\nstatic const JSClassExoticMethods js_string_exotic_methods = {\n    .get_own_property = js_string_get_own_property,\n    .define_own_property = js_string_define_own_property,\n    .delete_property = js_string_delete_property,\n};\n\nstatic JSValue js_string_constructor(JSContext *ctx, JSValueConst new_target,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue val, obj;\n    if (argc == 0) {\n        val = JS_AtomToString(ctx, JS_ATOM_empty_string);\n    } else {\n        if (JS_IsUndefined(new_target) && JS_IsSymbol(argv[0])) {\n            JSAtomStruct *p = JS_VALUE_GET_PTR(argv[0]);\n            val = JS_ConcatString3(ctx, \"Symbol(\", JS_AtomToString(ctx, js_get_atom_index(ctx->rt, p)), \")\");\n        } else {\n            val = JS_ToString(ctx, argv[0]);\n        }\n        if (JS_IsException(val))\n            return val;\n    }\n    if (!JS_IsUndefined(new_target)) {\n        JSString *p1 = JS_VALUE_GET_STRING(val);\n\n        obj = js_create_from_ctor(ctx, new_target, JS_CLASS_STRING);\n        if (!JS_IsException(obj)) {\n            JS_SetObjectData(ctx, obj, val);\n            JS_DefinePropertyValue(ctx, obj, JS_ATOM_length, JS_NewInt32(ctx, p1->len), 0);\n        }\n        return obj;\n    } else {\n        return val;\n    }\n}\n\nstatic JSValue js_thisStringValue(JSContext *ctx, JSValueConst this_val)\n{\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_STRING)\n        return JS_DupValue(ctx, this_val);\n\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_STRING) {\n            if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_STRING)\n                return JS_DupValue(ctx, p->u.object_data);\n        }\n    }\n    return JS_ThrowTypeError(ctx, \"not a string\");\n}\n\nstatic JSValue js_string_fromCharCode(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv)\n{\n    int i;\n    StringBuffer b_s, *b = &b_s;\n\n    string_buffer_init(ctx, b, argc);\n\n    for(i = 0; i < argc; i++) {\n        int32_t c;\n        if (JS_ToInt32(ctx, &c, argv[i]) || string_buffer_putc16(b, c & 0xffff)) {\n            string_buffer_free(b);\n            return JS_EXCEPTION;\n        }\n    }\n    return string_buffer_end(b);\n}\n\nstatic JSValue js_string_fromCodePoint(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    double d;\n    int i, c;\n    StringBuffer b_s, *b = &b_s;\n\n    /* XXX: could pre-compute string length if all arguments are JS_TAG_INT */\n\n    if (string_buffer_init(ctx, b, argc))\n        goto fail;\n    for(i = 0; i < argc; i++) {\n        if (JS_VALUE_GET_TAG(argv[i]) == JS_TAG_INT) {\n            c = JS_VALUE_GET_INT(argv[i]);\n            if (c < 0 || c > 0x10ffff)\n                goto range_error;\n        } else {\n            if (JS_ToFloat64(ctx, &d, argv[i]))\n                goto fail;\n            if (d < 0 || d > 0x10ffff || (c = (int)d) != d)\n                goto range_error;\n        }\n        if (string_buffer_putc(b, c))\n            goto fail;\n    }\n    return string_buffer_end(b);\n\n range_error:\n    JS_ThrowRangeError(ctx, \"invalid code point\");\n fail:\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_string_raw(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    // raw(temp,...a)\n    JSValue cooked, val, raw;\n    StringBuffer b_s, *b = &b_s;\n    int64_t i, n;\n\n    string_buffer_init(ctx, b, 0);\n    raw = JS_UNDEFINED;\n    cooked = JS_ToObject(ctx, argv[0]);\n    if (JS_IsException(cooked))\n        goto exception;\n    raw = JS_ToObjectFree(ctx, JS_GetProperty(ctx, cooked, JS_ATOM_raw));\n    if (JS_IsException(raw))\n        goto exception;\n    if (js_get_length64(ctx, &n, raw) < 0)\n        goto exception;\n        \n    for (i = 0; i < n; i++) {\n        val = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, raw, i));\n        if (JS_IsException(val))\n            goto exception;\n        string_buffer_concat_value_free(b, val);\n        if (i < n - 1 && i + 1 < argc) {\n            if (string_buffer_concat_value(b, argv[i + 1]))\n                goto exception;\n        }\n    }\n    JS_FreeValue(ctx, cooked);\n    JS_FreeValue(ctx, raw);\n    return string_buffer_end(b);\n\nexception:\n    JS_FreeValue(ctx, cooked);\n    JS_FreeValue(ctx, raw);\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\n/* only used in test262 */\nJSValue js_string_codePointRange(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    uint32_t start, end, i, n;\n    StringBuffer b_s, *b = &b_s;\n\n    if (JS_ToUint32(ctx, &start, argv[0]) ||\n        JS_ToUint32(ctx, &end, argv[1]))\n        return JS_EXCEPTION;\n    end = min_uint32(end, 0x10ffff + 1);\n\n    if (start > end) {\n        start = end;\n    }\n    n = end - start;\n    if (end > 0x10000) {\n        n += end - max_uint32(start, 0x10000);\n    }\n    if (string_buffer_init2(ctx, b, n, end >= 0x100))\n        return JS_EXCEPTION;\n    for(i = start; i < end; i++) {\n        string_buffer_putc(b, i);\n    }\n    return string_buffer_end(b);\n}\n\n#if 0\nstatic JSValue js_string___isSpace(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    int c;\n    if (JS_ToInt32(ctx, &c, argv[0]))\n        return JS_EXCEPTION;\n    return JS_NewBool(ctx, lre_is_space(c));\n}\n#endif\n\nstatic JSValue js_string_charCodeAt(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    JSString *p;\n    int idx, c;\n\n    val = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    p = JS_VALUE_GET_STRING(val);\n    if (JS_ToInt32Sat(ctx, &idx, argv[0])) {\n        JS_FreeValue(ctx, val);\n        return JS_EXCEPTION;\n    }\n    if (idx < 0 || idx >= p->len) {\n        ret = JS_NAN;\n    } else {\n        if (p->is_wide_char)\n            c = p->u.str16[idx];\n        else\n            c = p->u.str8[idx];\n        ret = JS_NewInt32(ctx, c);\n    }\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nstatic JSValue js_string_charAt(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    JSString *p;\n    int idx, c;\n\n    val = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    p = JS_VALUE_GET_STRING(val);\n    if (JS_ToInt32Sat(ctx, &idx, argv[0])) {\n        JS_FreeValue(ctx, val);\n        return JS_EXCEPTION;\n    }\n    if (idx < 0 || idx >= p->len) {\n        ret = js_new_string8(ctx, NULL, 0);\n    } else {\n        if (p->is_wide_char)\n            c = p->u.str16[idx];\n        else\n            c = p->u.str8[idx];\n        ret = js_new_string_char(ctx, c);\n    }\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nstatic JSValue js_string_codePointAt(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    JSString *p;\n    int idx, c;\n\n    val = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    p = JS_VALUE_GET_STRING(val);\n    if (JS_ToInt32Sat(ctx, &idx, argv[0])) {\n        JS_FreeValue(ctx, val);\n        return JS_EXCEPTION;\n    }\n    if (idx < 0 || idx >= p->len) {\n        ret = JS_UNDEFINED;\n    } else {\n        c = string_getc(p, &idx);\n        ret = JS_NewInt32(ctx, c);\n    }\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nstatic JSValue js_string_concat(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValue r;\n    int i;\n\n    /* XXX: Use more efficient method */\n    /* XXX: This method is OK if r has a single refcount */\n    /* XXX: should use string_buffer? */\n    r = JS_ToStringCheckObject(ctx, this_val);\n    for (i = 0; i < argc; i++) {\n        if (JS_IsException(r))\n            break;\n        r = JS_ConcatString(ctx, r, JS_DupValue(ctx, argv[i]));\n    }\n    return r;\n}\n\nstatic int string_cmp(JSString *p1, JSString *p2, int x1, int x2, int len)\n{\n    int i, c1, c2;\n    for (i = 0; i < len; i++) {\n        if ((c1 = string_get(p1, x1 + i)) != (c2 = string_get(p2, x2 + i)))\n            return c1 - c2;\n    }\n    return 0;\n}\n\nstatic int string_indexof_char(JSString *p, int c, int from)\n{\n    /* assuming 0 <= from <= p->len */\n    int i, len = p->len;\n    if (p->is_wide_char) {\n        for (i = from; i < len; i++) {\n            if (p->u.str16[i] == c)\n                return i;\n        }\n    } else {\n        if ((c & ~0xff) == 0) {\n            for (i = from; i < len; i++) {\n                if (p->u.str8[i] == (uint8_t)c)\n                    return i;\n            }\n        }\n    }\n    return -1;\n}\n\nstatic int string_indexof(JSString *p1, JSString *p2, int from)\n{\n    /* assuming 0 <= from <= p1->len */\n    int c, i, j, len1 = p1->len, len2 = p2->len;\n    if (len2 == 0)\n        return from;\n    for (i = from, c = string_get(p2, 0); i + len2 <= len1; i = j + 1) {\n        j = string_indexof_char(p1, c, i);\n        if (j < 0 || j + len2 > len1)\n            break;\n        if (!string_cmp(p1, p2, j + 1, 1, len2 - 1))\n            return j;\n    }\n    return -1;\n}\n\nstatic int64_t string_advance_index(JSString *p, int64_t index, BOOL unicode)\n{\n    if (!unicode || index >= p->len || !p->is_wide_char) {\n        index++;\n    } else {\n        int index32 = (int)index;\n        string_getc(p, &index32);\n        index = index32;\n    }\n    return index;\n}\n\nstatic JSValue js_string_indexOf(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv, int lastIndexOf)\n{\n    JSValue str, v;\n    int i, len, v_len, pos, start, stop, ret, inc;\n    JSString *p;\n    JSString *p1;\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        return str;\n    v = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(v))\n        goto fail;\n    p = JS_VALUE_GET_STRING(str);\n    p1 = JS_VALUE_GET_STRING(v);\n    len = p->len;\n    v_len = p1->len;\n    if (lastIndexOf) {\n        pos = len - v_len;\n        if (argc > 1) {\n            double d;\n            if (JS_ToFloat64(ctx, &d, argv[1]))\n                goto fail;\n            if (!isnan(d)) {\n                if (d <= 0)\n                    pos = 0;\n                else if (d < pos)\n                    pos = d;\n            }\n        }\n        start = pos;\n        stop = 0;\n        inc = -1;\n    } else {\n        pos = 0;\n        if (argc > 1) {\n            if (JS_ToInt32Clamp(ctx, &pos, argv[1], 0, len, 0))\n                goto fail;\n        }\n        start = pos;\n        stop = len - v_len;\n        inc = 1;\n    }\n    ret = -1;\n    if (len >= v_len && inc * (stop - start) >= 0) {\n        for (i = start;; i += inc) {\n            if (!string_cmp(p, p1, i, 0, v_len)) {\n                ret = i;\n                break;\n            }\n            if (i == stop)\n                break;\n        }\n    }\n    JS_FreeValue(ctx, str);\n    JS_FreeValue(ctx, v);\n    return JS_NewInt32(ctx, ret);\n\nfail:\n    JS_FreeValue(ctx, str);\n    JS_FreeValue(ctx, v);\n    return JS_EXCEPTION;\n}\n\n/* return < 0 if exception or TRUE/FALSE */\nstatic int js_is_regexp(JSContext *ctx, JSValueConst obj);\n\nstatic JSValue js_string_includes(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv, int magic)\n{\n    JSValue str, v = JS_UNDEFINED;\n    int i, len, v_len, pos, start, stop, ret;\n    JSString *p;\n    JSString *p1;\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        return str;\n    ret = js_is_regexp(ctx, argv[0]);\n    if (ret) {\n        if (ret > 0)\n            JS_ThrowTypeError(ctx, \"regex not supported\");\n        goto fail;\n    }\n    v = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(v))\n        goto fail;\n    p = JS_VALUE_GET_STRING(str);\n    p1 = JS_VALUE_GET_STRING(v);\n    len = p->len;\n    v_len = p1->len;\n    pos = (magic == 2) ? len : 0;\n    if (argc > 1 && !JS_IsUndefined(argv[1])) {\n        if (JS_ToInt32Clamp(ctx, &pos, argv[1], 0, len, 0))\n            goto fail;\n    }\n    len -= v_len;\n    ret = 0;\n    if (magic == 0) {\n        start = pos;\n        stop = len;\n    } else {\n        if (magic == 1) {\n            if (pos > len)\n                goto done;\n        } else {\n            pos -= v_len;\n        }\n        start = stop = pos;\n    }\n    if (start >= 0 && start <= stop) {\n        for (i = start;; i++) {\n            if (!string_cmp(p, p1, i, 0, v_len)) {\n                ret = 1;\n                break;\n            }\n            if (i == stop)\n                break;\n        }\n    }\n done:\n    JS_FreeValue(ctx, str);\n    JS_FreeValue(ctx, v);\n    return JS_NewBool(ctx, ret);\n\nfail:\n    JS_FreeValue(ctx, str);\n    JS_FreeValue(ctx, v);\n    return JS_EXCEPTION;\n}\n\nstatic int check_regexp_g_flag(JSContext *ctx, JSValueConst regexp)\n{\n    int ret;\n    JSValue flags;\n    \n    ret = js_is_regexp(ctx, regexp);\n    if (ret < 0)\n        return -1;\n    if (ret) {\n        flags = JS_GetProperty(ctx, regexp, JS_ATOM_flags);\n        if (JS_IsException(flags))\n            return -1;\n        if (JS_IsUndefined(flags) || JS_IsNull(flags)) {\n            JS_ThrowTypeError(ctx, \"cannot convert to object\");\n            return -1;\n        }\n        flags = JS_ToStringFree(ctx, flags);\n        if (JS_IsException(flags))\n            return -1;\n        ret = string_indexof_char(JS_VALUE_GET_STRING(flags), 'g', 0);\n        JS_FreeValue(ctx, flags);\n        if (ret < 0) {\n            JS_ThrowTypeError(ctx, \"regexp must have the 'g' flag\");\n            return -1;\n        }\n    }\n    return 0;\n}\n\nstatic JSValue js_string_match(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv, int atom)\n{\n    // match(rx), search(rx), matchAll(rx)\n    // atom is JS_ATOM_Symbol_match, JS_ATOM_Symbol_search, or JS_ATOM_Symbol_matchAll\n    JSValueConst O = this_val, regexp = argv[0], args[2];\n    JSValue matcher, S, rx, result, str;\n    int args_len;\n\n    if (JS_IsUndefined(O) || JS_IsNull(O))\n        return JS_ThrowTypeError(ctx, \"cannot convert to object\");\n\n    if (!JS_IsUndefined(regexp) && !JS_IsNull(regexp)) {\n        matcher = JS_GetProperty(ctx, regexp, atom);\n        if (JS_IsException(matcher))\n            return JS_EXCEPTION;\n        if (atom == JS_ATOM_Symbol_matchAll) {\n            if (check_regexp_g_flag(ctx, regexp) < 0) {\n                JS_FreeValue(ctx, matcher);\n                return JS_EXCEPTION;\n            }\n        }\n        if (!JS_IsUndefined(matcher) && !JS_IsNull(matcher)) {\n            return JS_CallFree(ctx, matcher, regexp, 1, &O);\n        }\n    }\n    S = JS_ToString(ctx, O);\n    if (JS_IsException(S))\n        return JS_EXCEPTION;\n    args_len = 1;\n    args[0] = regexp;\n    str = JS_UNDEFINED;\n    if (atom == JS_ATOM_Symbol_matchAll) {\n        str = JS_NewString(ctx, \"g\");\n        if (JS_IsException(str))\n            goto fail;\n        args[args_len++] = (JSValueConst)str;\n    }\n    rx = JS_CallConstructor(ctx, ctx->regexp_ctor, args_len, args);\n    JS_FreeValue(ctx, str);\n    if (JS_IsException(rx)) {\n    fail:\n        JS_FreeValue(ctx, S);\n        return JS_EXCEPTION;\n    }\n    result = JS_InvokeFree(ctx, rx, atom, 1, (JSValueConst *)&S);\n    JS_FreeValue(ctx, S);\n    return result;\n}\n\nstatic JSValue js_string___GetSubstitution(JSContext *ctx, JSValueConst this_val,\n                                           int argc, JSValueConst *argv)\n{\n    // GetSubstitution(matched, str, position, captures, namedCaptures, rep)\n    JSValueConst matched, str, captures, namedCaptures, rep;\n    JSValue capture, name, s;\n    uint32_t position, len, matched_len, captures_len;\n    int i, j, j0, k, k1;\n    int c, c1;\n    StringBuffer b_s, *b = &b_s;\n    JSString *sp, *rp;\n\n    matched = argv[0];\n    str = argv[1];\n    captures = argv[3];\n    namedCaptures = argv[4];\n    rep = argv[5];\n\n    if (!JS_IsString(rep) || !JS_IsString(str))\n        return JS_ThrowTypeError(ctx, \"not a string\");\n\n    sp = JS_VALUE_GET_STRING(str);\n    rp = JS_VALUE_GET_STRING(rep);\n\n    string_buffer_init(ctx, b, 0);\n\n    captures_len = 0;\n    if (!JS_IsUndefined(captures)) {\n        if (js_get_length32(ctx, &captures_len, captures))\n            goto exception;\n    }\n    if (js_get_length32(ctx, &matched_len, matched))\n        goto exception;\n    if (JS_ToUint32(ctx, &position, argv[2]) < 0)\n        goto exception;\n\n    len = rp->len;\n    i = 0;\n    for(;;) {\n        j = string_indexof_char(rp, '$', i);\n        if (j < 0 || j + 1 >= len)\n            break;\n        string_buffer_concat(b, rp, i, j);\n        j0 = j++;\n        c = string_get(rp, j++);\n        if (c == '$') {\n            string_buffer_putc8(b, '$');\n        } else if (c == '&') {\n            if (string_buffer_concat_value(b, matched))\n                goto exception;\n        } else if (c == '`') {\n            string_buffer_concat(b, sp, 0, position);\n        } else if (c == '\\'') {\n            string_buffer_concat(b, sp, position + matched_len, sp->len);\n        } else if (c >= '0' && c <= '9') {\n            k = c - '0';\n            if (j < len) {\n                c1 = string_get(rp, j);\n                if (c1 >= '0' && c1 <= '9') {\n                    /* This behavior is specified in ES6 and refined in ECMA 2019 */\n                    /* ECMA 2019 does not have the extra test, but\n                       Test262 S15.5.4.11_A3_T1..3 require this behavior */\n                    k1 = k * 10 + c1 - '0';\n                    if (k1 >= 1 && k1 < captures_len) {\n                        k = k1;\n                        j++;\n                    }\n                }\n            }\n            if (k >= 1 && k < captures_len) {\n                s = JS_GetPropertyInt64(ctx, captures, k);\n                if (JS_IsException(s))\n                    goto exception;\n                if (!JS_IsUndefined(s)) {\n                    if (string_buffer_concat_value_free(b, s))\n                        goto exception;\n                }\n            } else {\n                goto norep;\n            }\n        } else if (c == '<' && !JS_IsUndefined(namedCaptures)) {\n            k = string_indexof_char(rp, '>', j);\n            if (k < 0)\n                goto norep;\n            name = js_sub_string(ctx, rp, j, k);\n            if (JS_IsException(name))\n                goto exception;\n            capture = JS_GetPropertyValue(ctx, namedCaptures, name);\n            if (JS_IsException(capture))\n                goto exception;\n            if (!JS_IsUndefined(capture)) {\n                if (string_buffer_concat_value_free(b, capture))\n                    goto exception;\n            }\n            j = k + 1;\n        } else {\n        norep:\n            string_buffer_concat(b, rp, j0, j);\n        }\n        i = j;\n    }\n    string_buffer_concat(b, rp, i, rp->len);\n    return string_buffer_end(b);\nexception:\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_string_replace(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv,\n                                 int is_replaceAll)\n{\n    // replace(rx, rep)\n    JSValueConst O = this_val, searchValue = argv[0], replaceValue = argv[1];\n    JSValueConst args[6];\n    JSValue str, search_str, replaceValue_str, repl_str;\n    JSString *sp, *searchp;\n    StringBuffer b_s, *b = &b_s;\n    int pos, functionalReplace, endOfLastMatch;\n    BOOL is_first;\n\n    if (JS_IsUndefined(O) || JS_IsNull(O))\n        return JS_ThrowTypeError(ctx, \"cannot convert to object\");\n\n    search_str = JS_UNDEFINED;\n    replaceValue_str = JS_UNDEFINED;\n    repl_str = JS_UNDEFINED;\n\n    if (!JS_IsUndefined(searchValue) && !JS_IsNull(searchValue)) {\n        JSValue replacer;\n        if (is_replaceAll) {\n            if (check_regexp_g_flag(ctx, searchValue) < 0)\n                return JS_EXCEPTION;\n        }\n        replacer = JS_GetProperty(ctx, searchValue, JS_ATOM_Symbol_replace);\n        if (JS_IsException(replacer))\n            return JS_EXCEPTION;\n        if (!JS_IsUndefined(replacer) && !JS_IsNull(replacer)) {\n            args[0] = O;\n            args[1] = replaceValue;\n            return JS_CallFree(ctx, replacer, searchValue, 2, args);\n        }\n    }\n    string_buffer_init(ctx, b, 0);\n\n    str = JS_ToString(ctx, O);\n    if (JS_IsException(str))\n        goto exception;\n    search_str = JS_ToString(ctx, searchValue);\n    if (JS_IsException(search_str))\n        goto exception;\n    functionalReplace = JS_IsFunction(ctx, replaceValue);\n    if (!functionalReplace) {\n        replaceValue_str = JS_ToString(ctx, replaceValue);\n        if (JS_IsException(replaceValue_str))\n            goto exception;\n    }\n\n    sp = JS_VALUE_GET_STRING(str);\n    searchp = JS_VALUE_GET_STRING(search_str);\n    endOfLastMatch = 0;\n    is_first = TRUE;\n    for(;;) {\n        if (unlikely(searchp->len == 0)) {\n            if (is_first)\n                pos = 0;\n            else if (endOfLastMatch >= sp->len)\n                pos = -1;\n            else\n                pos = endOfLastMatch + 1;\n        } else {\n            pos = string_indexof(sp, searchp, endOfLastMatch);\n        }\n        if (pos < 0) {\n            if (is_first) {\n                string_buffer_free(b);\n                JS_FreeValue(ctx, search_str);\n                JS_FreeValue(ctx, replaceValue_str);\n                return str;\n            } else {\n                break;\n            }\n        }\n        if (functionalReplace) {\n            args[0] = search_str;\n            args[1] = JS_NewInt32(ctx, pos);\n            args[2] = str;\n            repl_str = JS_ToStringFree(ctx, JS_Call(ctx, replaceValue, JS_UNDEFINED, 3, args));\n        } else {\n            args[0] = search_str;\n            args[1] = str;\n            args[2] = JS_NewInt32(ctx, pos);\n            args[3] = JS_UNDEFINED;\n            args[4] = JS_UNDEFINED;\n            args[5] = replaceValue_str;\n            repl_str = js_string___GetSubstitution(ctx, JS_UNDEFINED, 6, args);\n        }\n        if (JS_IsException(repl_str))\n            goto exception;\n        \n        string_buffer_concat(b, sp, endOfLastMatch, pos);\n        string_buffer_concat_value_free(b, repl_str);\n        endOfLastMatch = pos + searchp->len;\n        is_first = FALSE;\n        if (!is_replaceAll)\n            break;\n    }\n    string_buffer_concat(b, sp, endOfLastMatch, sp->len);\n    JS_FreeValue(ctx, search_str);\n    JS_FreeValue(ctx, replaceValue_str);\n    JS_FreeValue(ctx, str);\n    return string_buffer_end(b);\n\nexception:\n    string_buffer_free(b);\n    JS_FreeValue(ctx, search_str);\n    JS_FreeValue(ctx, replaceValue_str);\n    JS_FreeValue(ctx, str);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_string_split(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    // split(sep, limit)\n    JSValueConst O = this_val, separator = argv[0], limit = argv[1];\n    JSValueConst args[2];\n    JSValue S, A, R, T;\n    uint32_t lim, lengthA;\n    int64_t p, q, s, r, e;\n    JSString *sp, *rp;\n\n    if (JS_IsUndefined(O) || JS_IsNull(O))\n        return JS_ThrowTypeError(ctx, \"cannot convert to object\");\n\n    S = JS_UNDEFINED;\n    A = JS_UNDEFINED;\n    R = JS_UNDEFINED;\n\n    if (!JS_IsUndefined(separator) && !JS_IsNull(separator)) {\n        JSValue splitter;\n        splitter = JS_GetProperty(ctx, separator, JS_ATOM_Symbol_split);\n        if (JS_IsException(splitter))\n            return JS_EXCEPTION;\n        if (!JS_IsUndefined(splitter) && !JS_IsNull(splitter)) {\n            args[0] = O;\n            args[1] = limit;\n            return JS_CallFree(ctx, splitter, separator, 2, args);\n        }\n    }\n    S = JS_ToString(ctx, O);\n    if (JS_IsException(S))\n        goto exception;\n    A = JS_NewArray(ctx);\n    if (JS_IsException(A))\n        goto exception;\n    lengthA = 0;\n    if (JS_IsUndefined(limit)) {\n        lim = 0xffffffff;\n    } else {\n        if (JS_ToUint32(ctx, &lim, limit) < 0)\n            goto exception;\n    }\n    sp = JS_VALUE_GET_STRING(S);\n    s = sp->len;\n    R = JS_ToString(ctx, separator);\n    if (JS_IsException(R))\n        goto exception;\n    rp = JS_VALUE_GET_STRING(R);\n    r = rp->len;\n    p = 0;\n    if (lim == 0)\n        goto done;\n    if (JS_IsUndefined(separator))\n        goto add_tail;\n    if (s == 0) {\n        if (r != 0)\n            goto add_tail;\n        goto done;\n    }\n    q = p;\n    for (q = p; (q += !r) <= s - r - !r; q = p = e + r) {\n        e = string_indexof(sp, rp, q);\n        if (e < 0)\n            break;\n        T = js_sub_string(ctx, sp, p, e);\n        if (JS_IsException(T))\n            goto exception;\n        if (JS_CreateDataPropertyUint32(ctx, A, lengthA++, T, 0) < 0)\n            goto exception;\n        if (lengthA == lim)\n            goto done;\n    }\nadd_tail:\n    T = js_sub_string(ctx, sp, p, s);\n    if (JS_IsException(T))\n        goto exception;\n    if (JS_CreateDataPropertyUint32(ctx, A, lengthA++, T,0 ) < 0)\n        goto exception;\ndone:\n    JS_FreeValue(ctx, S);\n    JS_FreeValue(ctx, R);\n    return A;\n\nexception:\n    JS_FreeValue(ctx, A);\n    JS_FreeValue(ctx, S);\n    JS_FreeValue(ctx, R);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_string_substring(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    JSValue str, ret;\n    int a, b, start, end;\n    JSString *p;\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        return str;\n    p = JS_VALUE_GET_STRING(str);\n    if (JS_ToInt32Clamp(ctx, &a, argv[0], 0, p->len, 0)) {\n        JS_FreeValue(ctx, str);\n        return JS_EXCEPTION;\n    }\n    b = p->len;\n    if (!JS_IsUndefined(argv[1])) {\n        if (JS_ToInt32Clamp(ctx, &b, argv[1], 0, p->len, 0)) {\n            JS_FreeValue(ctx, str);\n            return JS_EXCEPTION;\n        }\n    }\n    if (a < b) {\n        start = a;\n        end = b;\n    } else {\n        start = b;\n        end = a;\n    }\n    ret = js_sub_string(ctx, p, start, end);\n    JS_FreeValue(ctx, str);\n    return ret;\n}\n\nstatic JSValue js_string_substr(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValue str, ret;\n    int a, len, n;\n    JSString *p;\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        return str;\n    p = JS_VALUE_GET_STRING(str);\n    len = p->len;\n    if (JS_ToInt32Clamp(ctx, &a, argv[0], 0, len, len)) {\n        JS_FreeValue(ctx, str);\n        return JS_EXCEPTION;\n    }\n    n = len - a;\n    if (!JS_IsUndefined(argv[1])) {\n        if (JS_ToInt32Clamp(ctx, &n, argv[1], 0, len - a, 0)) {\n            JS_FreeValue(ctx, str);\n            return JS_EXCEPTION;\n        }\n    }\n    ret = js_sub_string(ctx, p, a, a + n);\n    JS_FreeValue(ctx, str);\n    return ret;\n}\n\nstatic JSValue js_string_slice(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    JSValue str, ret;\n    int len, start, end;\n    JSString *p;\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        return str;\n    p = JS_VALUE_GET_STRING(str);\n    len = p->len;\n    if (JS_ToInt32Clamp(ctx, &start, argv[0], 0, len, len)) {\n        JS_FreeValue(ctx, str);\n        return JS_EXCEPTION;\n    }\n    end = len;\n    if (!JS_IsUndefined(argv[1])) {\n        if (JS_ToInt32Clamp(ctx, &end, argv[1], 0, len, len)) {\n            JS_FreeValue(ctx, str);\n            return JS_EXCEPTION;\n        }\n    }\n    ret = js_sub_string(ctx, p, start, max_int(end, start));\n    JS_FreeValue(ctx, str);\n    return ret;\n}\n\nstatic JSValue js_string_pad(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv, int padEnd)\n{\n    JSValue str, v = JS_UNDEFINED;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p, *p1 = NULL;\n    int n, len, c = ' ';\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        goto fail1;\n    if (JS_ToInt32Sat(ctx, &n, argv[0]))\n        goto fail2;\n    p = JS_VALUE_GET_STRING(str);\n    len = p->len;\n    if (len >= n)\n        return str;\n    if (argc > 1 && !JS_IsUndefined(argv[1])) {\n        v = JS_ToString(ctx, argv[1]);\n        if (JS_IsException(v))\n            goto fail2;\n        p1 = JS_VALUE_GET_STRING(v);\n        if (p1->len == 0) {\n            JS_FreeValue(ctx, v);\n            return str;\n        }\n        if (p1->len == 1) {\n            c = string_get(p1, 0);\n            p1 = NULL;\n        }\n    }\n    if (n > JS_STRING_LEN_MAX) {\n        JS_ThrowInternalError(ctx, \"string too long\");\n        goto fail2;\n    }\n    if (string_buffer_init(ctx, b, n))\n        goto fail3;\n    n -= len;\n    if (padEnd) {\n        if (string_buffer_concat(b, p, 0, len))\n            goto fail;\n    }\n    if (p1) {\n        while (n > 0) {\n            int chunk = min_int(n, p1->len);\n            if (string_buffer_concat(b, p1, 0, chunk))\n                goto fail;\n            n -= chunk;\n        }\n    } else {\n        if (string_buffer_fill(b, c, n))\n            goto fail;\n    }\n    if (!padEnd) {\n        if (string_buffer_concat(b, p, 0, len))\n            goto fail;\n    }\n    JS_FreeValue(ctx, v);\n    JS_FreeValue(ctx, str);\n    return string_buffer_end(b);\n\nfail:\n    string_buffer_free(b);\nfail3:\n    JS_FreeValue(ctx, v);\nfail2:\n    JS_FreeValue(ctx, str);\nfail1:\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_string_repeat(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValue str;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p;\n    int64_t val;\n    int n, len;\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        goto fail;\n    if (JS_ToInt64Sat(ctx, &val, argv[0]))\n        goto fail;\n    if (val < 0 || val > 2147483647) {\n        JS_ThrowRangeError(ctx, \"invalid repeat count\");\n        goto fail;\n    }\n    n = val;\n    p = JS_VALUE_GET_STRING(str);\n    len = p->len;\n    if (len == 0 || n == 1)\n        return str;\n    if (val * len > JS_STRING_LEN_MAX) {\n        JS_ThrowInternalError(ctx, \"string too long\");\n        goto fail;\n    }\n    if (string_buffer_init2(ctx, b, n * len, p->is_wide_char))\n        goto fail;\n    if (len == 1) {\n        string_buffer_fill(b, string_get(p, 0), n);\n    } else {\n        while (n-- > 0) {\n            string_buffer_concat(b, p, 0, len);\n        }\n    }\n    JS_FreeValue(ctx, str);\n    return string_buffer_end(b);\n\nfail:\n    JS_FreeValue(ctx, str);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_string_trim(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int magic)\n{\n    JSValue str, ret;\n    int a, b, len;\n    JSString *p;\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        return str;\n    p = JS_VALUE_GET_STRING(str);\n    a = 0;\n    b = len = p->len;\n    if (magic & 1) {\n        while (a < len && lre_is_space(string_get(p, a)))\n            a++;\n    }\n    if (magic & 2) {\n        while (b > a && lre_is_space(string_get(p, b - 1)))\n            b--;\n    }\n    ret = js_sub_string(ctx, p, a, b);\n    JS_FreeValue(ctx, str);\n    return ret;\n}\n\nstatic JSValue js_string___quote(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    return JS_ToQuotedString(ctx, this_val);\n}\n\n/* return 0 if before the first char */\nstatic int string_prevc(JSString *p, int *pidx)\n{\n    int idx, c, c1;\n\n    idx = *pidx;\n    if (idx <= 0)\n        return 0;\n    idx--;\n    if (p->is_wide_char) {\n        c = p->u.str16[idx];\n        if (c >= 0xdc00 && c < 0xe000 && idx > 0) {\n            c1 = p->u.str16[idx - 1];\n            if (c1 >= 0xd800 && c1 <= 0xdc00) {\n                c = (((c1 & 0x3ff) << 10) | (c & 0x3ff)) + 0x10000;\n                idx--;\n            }\n        }\n    } else {\n        c = p->u.str8[idx];\n    }\n    *pidx = idx;\n    return c;\n}\n\nstatic BOOL test_final_sigma(JSString *p, int sigma_pos)\n{\n    int k, c1;\n\n    /* before C: skip case ignorable chars and check there is\n       a cased letter */\n    k = sigma_pos;\n    for(;;) {\n        c1 = string_prevc(p, &k);\n        if (!lre_is_case_ignorable(c1))\n            break;\n    }\n    if (!lre_is_cased(c1))\n        return FALSE;\n\n    /* after C: skip case ignorable chars and check there is\n       no cased letter */\n    k = sigma_pos + 1;\n    for(;;) {\n        if (k >= p->len)\n            return TRUE;\n        c1 = string_getc(p, &k);\n        if (!lre_is_case_ignorable(c1))\n            break;\n    }\n    return !lre_is_cased(c1);\n}\n\nstatic JSValue js_string_localeCompare(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    JSValue a, b;\n    int cmp;\n\n    a = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(a))\n        return JS_EXCEPTION;\n    b = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(b)) {\n        JS_FreeValue(ctx, a);\n        return JS_EXCEPTION;\n    }\n    cmp = js_string_compare(ctx, JS_VALUE_GET_STRING(a), JS_VALUE_GET_STRING(b));\n    JS_FreeValue(ctx, a);\n    JS_FreeValue(ctx, b);\n    return JS_NewInt32(ctx, cmp);\n}\n\nstatic JSValue js_string_toLowerCase(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv, int to_lower)\n{\n    JSValue val;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p;\n    int i, c, j, l;\n    uint32_t res[LRE_CC_RES_LEN_MAX];\n\n    val = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    p = JS_VALUE_GET_STRING(val);\n    if (p->len == 0)\n        return val;\n    if (string_buffer_init(ctx, b, p->len))\n        goto fail;\n    for(i = 0; i < p->len;) {\n        c = string_getc(p, &i);\n        if (c == 0x3a3 && to_lower && test_final_sigma(p, i - 1)) {\n            res[0] = 0x3c2; /* final sigma */\n            l = 1;\n        } else {\n            l = lre_case_conv(res, c, to_lower);\n        }\n        for(j = 0; j < l; j++) {\n            if (string_buffer_putc(b, res[j]))\n                goto fail;\n        }\n    }\n    JS_FreeValue(ctx, val);\n    return string_buffer_end(b);\n fail:\n    JS_FreeValue(ctx, val);\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\n#ifdef CONFIG_ALL_UNICODE\n\n/* return (-1, NULL) if exception, otherwise (len, buf) */\nstatic int JS_ToUTF32String(JSContext *ctx, uint32_t **pbuf, JSValueConst val1)\n{\n    JSValue val;\n    JSString *p;\n    uint32_t *buf;\n    int i, j, len;\n\n    val = JS_ToString(ctx, val1);\n    if (JS_IsException(val))\n        return -1;\n    p = JS_VALUE_GET_STRING(val);\n    len = p->len;\n    /* UTF32 buffer length is len minus the number of correct surrogates pairs */\n    buf = js_malloc(ctx, sizeof(buf[0]) * max_int(len, 1));\n    if (!buf) {\n        JS_FreeValue(ctx, val);\n        goto fail;\n    }\n    for(i = j = 0; i < len;)\n        buf[j++] = string_getc(p, &i);\n    JS_FreeValue(ctx, val);\n    *pbuf = buf;\n    return j;\n fail:\n    *pbuf = NULL;\n    return -1;\n}\n\nstatic JSValue JS_NewUTF32String(JSContext *ctx, const uint32_t *buf, int len)\n{\n    int i;\n    StringBuffer b_s, *b = &b_s;\n    if (string_buffer_init(ctx, b, len))\n        return JS_EXCEPTION;\n    for(i = 0; i < len; i++) {\n        if (string_buffer_putc(b, buf[i]))\n            goto fail;\n    }\n    return string_buffer_end(b);\n fail:\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_string_normalize(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    const char *form, *p;\n    size_t form_len;\n    int is_compat, buf_len, out_len;\n    UnicodeNormalizationEnum n_type;\n    JSValue val;\n    uint32_t *buf, *out_buf;\n\n    val = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    buf_len = JS_ToUTF32String(ctx, &buf, val);\n    JS_FreeValue(ctx, val);\n    if (buf_len < 0)\n        return JS_EXCEPTION;\n\n    if (argc == 0 || JS_IsUndefined(argv[0])) {\n        n_type = UNICODE_NFC;\n    } else {\n        form = JS_ToCStringLen(ctx, &form_len, argv[0]);\n        if (!form)\n            goto fail1;\n        p = form;\n        if (p[0] != 'N' || p[1] != 'F')\n            goto bad_form;\n        p += 2;\n        is_compat = FALSE;\n        if (*p == 'K') {\n            is_compat = TRUE;\n            p++;\n        }\n        if (*p == 'C' || *p == 'D') {\n            n_type = UNICODE_NFC + is_compat * 2 + (*p - 'C');\n            if ((p + 1 - form) != form_len)\n                goto bad_form;\n        } else {\n        bad_form:\n            JS_FreeCString(ctx, form);\n            JS_ThrowRangeError(ctx, \"bad normalization form\");\n        fail1:\n            js_free(ctx, buf);\n            return JS_EXCEPTION;\n        }\n        JS_FreeCString(ctx, form);\n    }\n\n    out_len = unicode_normalize(&out_buf, buf, buf_len, n_type,\n                                ctx->rt, (DynBufReallocFunc *)js_realloc_rt);\n    js_free(ctx, buf);\n    if (out_len < 0)\n        return JS_EXCEPTION;\n    val = JS_NewUTF32String(ctx, out_buf, out_len);\n    js_free(ctx, out_buf);\n    return val;\n}\n#endif /* CONFIG_ALL_UNICODE */\n\n/* also used for String.prototype.valueOf */\nstatic JSValue js_string_toString(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    return js_thisStringValue(ctx, this_val);\n}\n\n#if 0\nstatic JSValue js_string___toStringCheckObject(JSContext *ctx, JSValueConst this_val,\n                                               int argc, JSValueConst *argv)\n{\n    return JS_ToStringCheckObject(ctx, argv[0]);\n}\n\nstatic JSValue js_string___toString(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    return JS_ToString(ctx, argv[0]);\n}\n\nstatic JSValue js_string___advanceStringIndex(JSContext *ctx, JSValueConst\n                                              this_val,\n                                              int argc, JSValueConst *argv)\n{\n    JSValue str;\n    int idx;\n    BOOL is_unicode;\n    JSString *p;\n\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        return str;\n    if (JS_ToInt32Sat(ctx, &idx, argv[1])) {\n        JS_FreeValue(ctx, str);\n        return JS_EXCEPTION;\n    }\n    is_unicode = JS_ToBool(ctx, argv[2]);\n    p = JS_VALUE_GET_STRING(str);\n    if (!is_unicode || (unsigned)idx >= p->len || !p->is_wide_char) {\n        idx++;\n    } else {\n        string_getc(p, &idx);\n    }\n    JS_FreeValue(ctx, str);\n    return JS_NewInt32(ctx, idx);\n}\n#endif\n\n/* String Iterator */\n\nstatic JSValue js_string_iterator_next(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv,\n                                       BOOL *pdone, int magic)\n{\n    JSArrayIteratorData *it;\n    uint32_t idx, c, start;\n    JSString *p;\n\n    it = JS_GetOpaque2(ctx, this_val, JS_CLASS_STRING_ITERATOR);\n    if (!it) {\n        *pdone = FALSE;\n        return JS_EXCEPTION;\n    }\n    if (JS_IsUndefined(it->obj))\n        goto done;\n    p = JS_VALUE_GET_STRING(it->obj);\n    idx = it->idx;\n    if (idx >= p->len) {\n        JS_FreeValue(ctx, it->obj);\n        it->obj = JS_UNDEFINED;\n    done:\n        *pdone = TRUE;\n        return JS_UNDEFINED;\n    }\n\n    start = idx;\n    c = string_getc(p, (int *)&idx);\n    it->idx = idx;\n    *pdone = FALSE;\n    if (c <= 0xffff) {\n        return js_new_string_char(ctx, c);\n    } else {\n        return js_new_string16(ctx, p->u.str16 + start, 2);\n    }\n}\n\n/* ES6 Annex B 2.3.2 etc. */\nenum {\n    magic_string_anchor,\n    magic_string_big,\n    magic_string_blink,\n    magic_string_bold,\n    magic_string_fixed,\n    magic_string_fontcolor,\n    magic_string_fontsize,\n    magic_string_italics,\n    magic_string_link,\n    magic_string_small,\n    magic_string_strike,\n    magic_string_sub,\n    magic_string_sup,\n};\n\nstatic JSValue js_string_CreateHTML(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv, int magic)\n{\n    JSValue str;\n    const JSString *p;\n    StringBuffer b_s, *b = &b_s;\n    static struct { const char *tag, *attr; } const defs[] = {\n        { \"a\", \"name\" }, { \"big\", NULL }, { \"blink\", NULL }, { \"b\", NULL },\n        { \"tt\", NULL }, { \"font\", \"color\" }, { \"font\", \"size\" }, { \"i\", NULL },\n        { \"a\", \"href\" }, { \"small\", NULL }, { \"strike\", NULL }, \n        { \"sub\", NULL }, { \"sup\", NULL },\n    };\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        return JS_EXCEPTION;\n    string_buffer_init(ctx, b, 7);\n    string_buffer_putc8(b, '<');\n    string_buffer_puts8(b, defs[magic].tag);\n    if (defs[magic].attr) {\n        // r += \" \" + attr + \"=\\\"\" + value + \"\\\"\";\n        JSValue value;\n        int i;\n\n        string_buffer_putc8(b, ' ');\n        string_buffer_puts8(b, defs[magic].attr);\n        string_buffer_puts8(b, \"=\\\"\");\n        value = JS_ToStringCheckObject(ctx, argv[0]);\n        if (JS_IsException(value)) {\n            JS_FreeValue(ctx, str);\n            string_buffer_free(b);\n            return JS_EXCEPTION;\n        }\n        p = JS_VALUE_GET_STRING(value);\n        for (i = 0; i < p->len; i++) {\n            int c = string_get(p, i);\n            if (c == '\"') {\n                string_buffer_puts8(b, \"&quot;\");\n            } else {\n                string_buffer_putc16(b, c);\n            }\n        }\n        JS_FreeValue(ctx, value);\n        string_buffer_putc8(b, '\\\"');\n    }\n    // return r + \">\" + str + \"</\" + tag + \">\";\n    string_buffer_putc8(b, '>');\n    string_buffer_concat_value_free(b, str);\n    string_buffer_puts8(b, \"</\");\n    string_buffer_puts8(b, defs[magic].tag);\n    string_buffer_putc8(b, '>');\n    return string_buffer_end(b);\n}\n\nstatic const JSCFunctionListEntry js_string_funcs[] = {\n    JS_CFUNC_DEF(\"fromCharCode\", 1, js_string_fromCharCode ),\n    JS_CFUNC_DEF(\"fromCodePoint\", 1, js_string_fromCodePoint ),\n    JS_CFUNC_DEF(\"raw\", 1, js_string_raw ),\n    //JS_CFUNC_DEF(\"__toString\", 1, js_string___toString ),\n    //JS_CFUNC_DEF(\"__isSpace\", 1, js_string___isSpace ),\n    //JS_CFUNC_DEF(\"__toStringCheckObject\", 1, js_string___toStringCheckObject ),\n    //JS_CFUNC_DEF(\"__advanceStringIndex\", 3, js_string___advanceStringIndex ),\n    //JS_CFUNC_DEF(\"__GetSubstitution\", 6, js_string___GetSubstitution ),\n};\n\nstatic const JSCFunctionListEntry js_string_proto_funcs[] = {\n    JS_PROP_INT32_DEF(\"length\", 0, JS_PROP_CONFIGURABLE ),\n    JS_CFUNC_DEF(\"charCodeAt\", 1, js_string_charCodeAt ),\n    JS_CFUNC_DEF(\"charAt\", 1, js_string_charAt ),\n    JS_CFUNC_DEF(\"concat\", 1, js_string_concat ),\n    JS_CFUNC_DEF(\"codePointAt\", 1, js_string_codePointAt ),\n    JS_CFUNC_MAGIC_DEF(\"indexOf\", 1, js_string_indexOf, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"lastIndexOf\", 1, js_string_indexOf, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"includes\", 1, js_string_includes, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"endsWith\", 1, js_string_includes, 2 ),\n    JS_CFUNC_MAGIC_DEF(\"startsWith\", 1, js_string_includes, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"match\", 1, js_string_match, JS_ATOM_Symbol_match ),\n    JS_CFUNC_MAGIC_DEF(\"matchAll\", 1, js_string_match, JS_ATOM_Symbol_matchAll ),\n    JS_CFUNC_MAGIC_DEF(\"search\", 1, js_string_match, JS_ATOM_Symbol_search ),\n    JS_CFUNC_DEF(\"split\", 2, js_string_split ),\n    JS_CFUNC_DEF(\"substring\", 2, js_string_substring ),\n    JS_CFUNC_DEF(\"substr\", 2, js_string_substr ),\n    JS_CFUNC_DEF(\"slice\", 2, js_string_slice ),\n    JS_CFUNC_DEF(\"repeat\", 1, js_string_repeat ),\n    JS_CFUNC_MAGIC_DEF(\"replace\", 2, js_string_replace, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"replaceAll\", 2, js_string_replace, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"padEnd\", 1, js_string_pad, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"padStart\", 1, js_string_pad, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"trim\", 0, js_string_trim, 3 ),\n    JS_CFUNC_MAGIC_DEF(\"trimEnd\", 0, js_string_trim, 2 ),\n    JS_ALIAS_DEF(\"trimRight\", \"trimEnd\" ),\n    JS_CFUNC_MAGIC_DEF(\"trimStart\", 0, js_string_trim, 1 ),\n    JS_ALIAS_DEF(\"trimLeft\", \"trimStart\" ),\n    JS_CFUNC_DEF(\"toString\", 0, js_string_toString ),\n    JS_CFUNC_DEF(\"valueOf\", 0, js_string_toString ),\n    JS_CFUNC_DEF(\"__quote\", 1, js_string___quote ),\n    JS_CFUNC_DEF(\"localeCompare\", 1, js_string_localeCompare ),\n    JS_CFUNC_MAGIC_DEF(\"toLowerCase\", 0, js_string_toLowerCase, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"toUpperCase\", 0, js_string_toLowerCase, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"toLocaleLowerCase\", 0, js_string_toLowerCase, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"toLocaleUpperCase\", 0, js_string_toLowerCase, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"[Symbol.iterator]\", 0, js_create_array_iterator, JS_ITERATOR_KIND_VALUE | 4 ),\n    /* ES6 Annex B 2.3.2 etc. */\n    JS_CFUNC_MAGIC_DEF(\"anchor\", 1, js_string_CreateHTML, magic_string_anchor ),\n    JS_CFUNC_MAGIC_DEF(\"big\", 0, js_string_CreateHTML, magic_string_big ),\n    JS_CFUNC_MAGIC_DEF(\"blink\", 0, js_string_CreateHTML, magic_string_blink ),\n    JS_CFUNC_MAGIC_DEF(\"bold\", 0, js_string_CreateHTML, magic_string_bold ),\n    JS_CFUNC_MAGIC_DEF(\"fixed\", 0, js_string_CreateHTML, magic_string_fixed ),\n    JS_CFUNC_MAGIC_DEF(\"fontcolor\", 1, js_string_CreateHTML, magic_string_fontcolor ),\n    JS_CFUNC_MAGIC_DEF(\"fontsize\", 1, js_string_CreateHTML, magic_string_fontsize ),\n    JS_CFUNC_MAGIC_DEF(\"italics\", 0, js_string_CreateHTML, magic_string_italics ),\n    JS_CFUNC_MAGIC_DEF(\"link\", 1, js_string_CreateHTML, magic_string_link ),\n    JS_CFUNC_MAGIC_DEF(\"small\", 0, js_string_CreateHTML, magic_string_small ),\n    JS_CFUNC_MAGIC_DEF(\"strike\", 0, js_string_CreateHTML, magic_string_strike ),\n    JS_CFUNC_MAGIC_DEF(\"sub\", 0, js_string_CreateHTML, magic_string_sub ),\n    JS_CFUNC_MAGIC_DEF(\"sup\", 0, js_string_CreateHTML, magic_string_sup ),\n};\n\nstatic const JSCFunctionListEntry js_string_iterator_proto_funcs[] = {\n    JS_ITERATOR_NEXT_DEF(\"next\", 0, js_string_iterator_next, 0 ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"String Iterator\", JS_PROP_CONFIGURABLE ),\n};\n\n#ifdef CONFIG_ALL_UNICODE\nstatic const JSCFunctionListEntry js_string_proto_normalize[] = {\n    JS_CFUNC_DEF(\"normalize\", 0, js_string_normalize ),\n};\n#endif\n\nvoid JS_AddIntrinsicStringNormalize(JSContext *ctx)\n{\n#ifdef CONFIG_ALL_UNICODE\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_STRING], js_string_proto_normalize,\n                               countof(js_string_proto_normalize));\n#endif\n}\n\n/* Math */\n\n/* precondition: a and b are not NaN */\nstatic double js_fmin(double a, double b)\n{\n    if (a == 0 && b == 0) {\n        JSFloat64Union a1, b1;\n        a1.d = a;\n        b1.d = b;\n        a1.u64 |= b1.u64;\n        return a1.d;\n    } else {\n        return fmin(a, b);\n    }\n}\n\n/* precondition: a and b are not NaN */\nstatic double js_fmax(double a, double b)\n{\n    if (a == 0 && b == 0) {\n        JSFloat64Union a1, b1;\n        a1.d = a;\n        b1.d = b;\n        a1.u64 &= b1.u64;\n        return a1.d;\n    } else {\n        return fmax(a, b);\n    }\n}\n\nstatic JSValue js_math_min_max(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv, int magic)\n{\n    BOOL is_max = magic;\n    double r, a;\n    int i;\n    uint32_t tag;\n\n    if (unlikely(argc == 0)) {\n        return __JS_NewFloat64(ctx, is_max ? -1.0 / 0.0 : 1.0 / 0.0);\n    }\n\n    tag = JS_VALUE_GET_TAG(argv[0]);\n    if (tag == JS_TAG_INT) {\n        int a1, r1 = JS_VALUE_GET_INT(argv[0]);\n        for(i = 1; i < argc; i++) {\n            tag = JS_VALUE_GET_TAG(argv[i]);\n            if (tag != JS_TAG_INT) {\n                r = r1;\n                goto generic_case;\n            }\n            a1 = JS_VALUE_GET_INT(argv[i]);\n            if (is_max)\n                r1 = max_int(r1, a1);\n            else\n                r1 = min_int(r1, a1);\n\n        }\n        return JS_NewInt32(ctx, r1);\n    } else {\n        if (JS_ToFloat64(ctx, &r, argv[0]))\n            return JS_EXCEPTION;\n        i = 1;\n    generic_case:\n        while (i < argc) {\n            if (JS_ToFloat64(ctx, &a, argv[i]))\n                return JS_EXCEPTION;\n            if (!isnan(r)) {\n                if (isnan(a)) {\n                    r = a;\n                } else {\n                    if (is_max)\n                        r = js_fmax(r, a);\n                    else\n                        r = js_fmin(r, a);\n                }\n            }\n            i++;\n        }\n        return JS_NewFloat64(ctx, r);\n    }\n}\n\nstatic double js_math_sign(double a)\n{\n    if (isnan(a) || a == 0.0)\n        return a;\n    if (a < 0)\n        return -1;\n    else\n        return 1;\n}\n\nstatic double js_math_round(double a)\n{\n    JSFloat64Union u;\n    uint64_t frac_mask, one;\n    unsigned int e, s;\n\n    u.d = a;\n    e = (u.u64 >> 52) & 0x7ff;\n    if (e < 1023) {\n        /* abs(a) < 1 */\n        if (e == (1023 - 1) && u.u64 != 0xbfe0000000000000) {\n            /* abs(a) > 0.5 or a = 0.5: return +/-1.0 */\n            u.u64 = (u.u64 & ((uint64_t)1 << 63)) | ((uint64_t)1023 << 52);\n        } else {\n            /* return +/-0.0 */\n            u.u64 &= (uint64_t)1 << 63;\n        }\n    } else if (e < (1023 + 52)) {\n        s = u.u64 >> 63;\n        one = (uint64_t)1 << (52 - (e - 1023));\n        frac_mask = one - 1;\n        u.u64 += (one >> 1) - s;\n        u.u64 &= ~frac_mask; /* truncate to an integer */\n    }\n    /* otherwise: abs(a) >= 2^52, or NaN, +/-Infinity: no change */\n    return u.d;\n}\n\nstatic JSValue js_math_hypot(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    double r, a;\n    int i;\n\n    r = 0;\n    if (argc > 0) {\n        if (JS_ToFloat64(ctx, &r, argv[0]))\n            return JS_EXCEPTION;\n        if (argc == 1) {\n            r = fabs(r);\n        } else {\n            /* use the built-in function to minimize precision loss */\n            for (i = 1; i < argc; i++) {\n                if (JS_ToFloat64(ctx, &a, argv[i]))\n                    return JS_EXCEPTION;\n                r = hypot(r, a);\n            }\n        }\n    }\n    return JS_NewFloat64(ctx, r);\n}\n\nstatic double js_math_fround(double a)\n{\n    return (float)a;\n}\n\nstatic JSValue js_math_imul(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv)\n{\n    int a, b;\n\n    if (JS_ToInt32(ctx, &a, argv[0]))\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &b, argv[1]))\n        return JS_EXCEPTION;\n    /* purposely ignoring overflow */\n    return JS_NewInt32(ctx, a * b);\n}\n\nstatic JSValue js_math_clz32(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    uint32_t a, r;\n\n    if (JS_ToUint32(ctx, &a, argv[0]))\n        return JS_EXCEPTION;\n    if (a == 0)\n        r = 32;\n    else\n        r = clz32(a);\n    return JS_NewInt32(ctx, r);\n}\n\n/* xorshift* random number generator by Marsaglia */\nstatic uint64_t xorshift64star(uint64_t *pstate)\n{\n    uint64_t x;\n    x = *pstate;\n    x ^= x >> 12;\n    x ^= x << 25;\n    x ^= x >> 27;\n    *pstate = x;\n    return x * 0x2545F4914F6CDD1D;\n}\n\nstatic void js_random_init(JSContext *ctx)\n{\n    struct timeval tv;\n    gettimeofday(&tv, NULL);\n    ctx->random_state = ((int64_t)tv.tv_sec * 1000000) + tv.tv_usec;\n    /* the state must be non zero */\n    if (ctx->random_state == 0)\n        ctx->random_state = 1;\n}\n\nstatic JSValue js_math_random(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    JSFloat64Union u;\n    uint64_t v;\n\n    v = xorshift64star(&ctx->random_state);\n    /* 1.0 <= u.d < 2 */\n    u.u64 = ((uint64_t)0x3ff << 52) | (v >> 12);\n    return __JS_NewFloat64(ctx, u.d - 1.0);\n}\n\nstatic const JSCFunctionListEntry js_math_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"min\", 2, js_math_min_max, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"max\", 2, js_math_min_max, 1 ),\n    JS_CFUNC_SPECIAL_DEF(\"abs\", 1, f_f, fabs ),\n    JS_CFUNC_SPECIAL_DEF(\"floor\", 1, f_f, floor ),\n    JS_CFUNC_SPECIAL_DEF(\"ceil\", 1, f_f, ceil ),\n    JS_CFUNC_SPECIAL_DEF(\"round\", 1, f_f, js_math_round ),\n    JS_CFUNC_SPECIAL_DEF(\"sqrt\", 1, f_f, sqrt ),\n\n    JS_CFUNC_SPECIAL_DEF(\"acos\", 1, f_f, acos ),\n    JS_CFUNC_SPECIAL_DEF(\"asin\", 1, f_f, asin ),\n    JS_CFUNC_SPECIAL_DEF(\"atan\", 1, f_f, atan ),\n    JS_CFUNC_SPECIAL_DEF(\"atan2\", 2, f_f_f, atan2 ),\n    JS_CFUNC_SPECIAL_DEF(\"cos\", 1, f_f, cos ),\n    JS_CFUNC_SPECIAL_DEF(\"exp\", 1, f_f, exp ),\n    JS_CFUNC_SPECIAL_DEF(\"log\", 1, f_f, log ),\n    JS_CFUNC_SPECIAL_DEF(\"pow\", 2, f_f_f, js_pow ),\n    JS_CFUNC_SPECIAL_DEF(\"sin\", 1, f_f, sin ),\n    JS_CFUNC_SPECIAL_DEF(\"tan\", 1, f_f, tan ),\n    /* ES6 */\n    JS_CFUNC_SPECIAL_DEF(\"trunc\", 1, f_f, trunc ),\n    JS_CFUNC_SPECIAL_DEF(\"sign\", 1, f_f, js_math_sign ),\n    JS_CFUNC_SPECIAL_DEF(\"cosh\", 1, f_f, cosh ),\n    JS_CFUNC_SPECIAL_DEF(\"sinh\", 1, f_f, sinh ),\n    JS_CFUNC_SPECIAL_DEF(\"tanh\", 1, f_f, tanh ),\n    JS_CFUNC_SPECIAL_DEF(\"acosh\", 1, f_f, acosh ),\n    JS_CFUNC_SPECIAL_DEF(\"asinh\", 1, f_f, asinh ),\n    JS_CFUNC_SPECIAL_DEF(\"atanh\", 1, f_f, atanh ),\n    JS_CFUNC_SPECIAL_DEF(\"expm1\", 1, f_f, expm1 ),\n    JS_CFUNC_SPECIAL_DEF(\"log1p\", 1, f_f, log1p ),\n#if defined(__ANDROID__)\n    JS_CFUNC_SPECIAL_DEF(\"log2\", 1, f_f, __log2 ),\n#else \n    JS_CFUNC_SPECIAL_DEF(\"log2\", 1, f_f, log2 ),\n#endif\n    JS_CFUNC_SPECIAL_DEF(\"log10\", 1, f_f, log10 ),\n    JS_CFUNC_SPECIAL_DEF(\"cbrt\", 1, f_f, cbrt ),\n    JS_CFUNC_DEF(\"hypot\", 2, js_math_hypot ),\n    JS_CFUNC_DEF(\"random\", 0, js_math_random ),\n    JS_CFUNC_SPECIAL_DEF(\"fround\", 1, f_f, js_math_fround ),\n    JS_CFUNC_DEF(\"imul\", 2, js_math_imul ),\n    JS_CFUNC_DEF(\"clz32\", 1, js_math_clz32 ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Math\", JS_PROP_CONFIGURABLE ),\n    JS_PROP_DOUBLE_DEF(\"E\", 2.718281828459045, 0 ),\n    JS_PROP_DOUBLE_DEF(\"LN10\", 2.302585092994046, 0 ),\n    JS_PROP_DOUBLE_DEF(\"LN2\", 0.6931471805599453, 0 ),\n    JS_PROP_DOUBLE_DEF(\"LOG2E\", 1.4426950408889634, 0 ),\n    JS_PROP_DOUBLE_DEF(\"LOG10E\", 0.4342944819032518, 0 ),\n    JS_PROP_DOUBLE_DEF(\"PI\", 3.141592653589793, 0 ),\n    JS_PROP_DOUBLE_DEF(\"SQRT1_2\", 0.7071067811865476, 0 ),\n    JS_PROP_DOUBLE_DEF(\"SQRT2\", 1.4142135623730951, 0 ),\n};\n\nstatic const JSCFunctionListEntry js_math_obj[] = {\n    JS_OBJECT_DEF(\"Math\", js_math_funcs, countof(js_math_funcs), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),\n};\n\n/* Date */\n\n#if 0\n/* OS dependent: return the UTC time in ms since 1970. */\nstatic JSValue js___date_now(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    int64_t d;\n    struct timeval tv;\n    gettimeofday(&tv, NULL);\n    d = (int64_t)tv.tv_sec * 1000 + (tv.tv_usec / 1000);\n    return JS_NewInt64(ctx, d);\n}\n#endif\n\n/* OS dependent: return the UTC time in microseconds since 1970. */\nstatic JSValue js___date_clock(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    int64_t d;\n    struct timeval tv;\n    gettimeofday(&tv, NULL);\n    d = (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;\n    return JS_NewInt64(ctx, d);\n}\n\n/* OS dependent. d = argv[0] is in ms from 1970. Return the difference\n   between UTC time and local time 'd' in minutes */\nstatic int getTimezoneOffset(int64_t time) {\n#if defined(_WIN32)\n    /* XXX: TODO */\n    return 0;\n#else\n    time_t ti;\n    struct tm tm;\n\n    time /= 1000; /* convert to seconds */\n    if (sizeof(time_t) == 4) {\n        /* on 32-bit systems, we need to clamp the time value to the\n           range of `time_t`. This is better than truncating values to\n           32 bits and hopefully provides the same result as 64-bit\n           implementation of localtime_r.\n         */\n        if ((time_t)-1 < 0) {\n            if (time < INT32_MIN) {\n                time = INT32_MIN;\n            } else if (time > INT32_MAX) {\n                time = INT32_MAX;\n            }\n        } else {\n            if (time < 0) {\n                time = 0;\n            } else if (time > UINT32_MAX) {\n                time = UINT32_MAX;\n            }\n        }\n    }\n    ti = time;\n    localtime_r(&ti, &tm);\n    return -tm.tm_gmtoff / 60;\n#endif\n}\n\n#if 0\nstatic JSValue js___date_getTimezoneOffset(JSContext *ctx, JSValueConst this_val,\n                                           int argc, JSValueConst *argv)\n{\n    double dd;\n\n    if (JS_ToFloat64(ctx, &dd, argv[0]))\n        return JS_EXCEPTION;\n    if (isnan(dd))\n        return __JS_NewFloat64(ctx, dd);\n    else\n        return JS_NewInt32(ctx, getTimezoneOffset((int64_t)dd));\n}\n\nstatic JSValue js_get_prototype_from_ctor(JSContext *ctx, JSValueConst ctor,\n                                          JSValueConst def_proto)\n{\n    JSValue proto;\n    proto = JS_GetProperty(ctx, ctor, JS_ATOM_prototype);\n    if (JS_IsException(proto))\n        return proto;\n    if (!JS_IsObject(proto)) {\n        JS_FreeValue(ctx, proto);\n        proto = JS_DupValue(ctx, def_proto);\n    }\n    return proto;\n}\n\n/* create a new date object */\nstatic JSValue js___date_create(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValue obj, proto;\n    proto = js_get_prototype_from_ctor(ctx, argv[0], argv[1]);\n    if (JS_IsException(proto))\n        return proto;\n    obj = JS_NewObjectProtoClass(ctx, proto, JS_CLASS_DATE);\n    JS_FreeValue(ctx, proto);\n    if (!JS_IsException(obj))\n        JS_SetObjectData(ctx, obj, JS_DupValue(ctx, argv[2]));\n    return obj;\n}\n#endif\n\n/* RegExp */\n\nstatic void js_regexp_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSRegExp *re = &p->u.regexp;\n    JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_STRING, re->bytecode));\n    JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_STRING, re->pattern));\n}\n\n/* create a string containing the RegExp bytecode */\nstatic JSValue js_compile_regexp(JSContext *ctx, JSValueConst pattern,\n                                 JSValueConst flags)\n{\n    const char *str;\n    int re_flags, mask;\n    uint8_t *re_bytecode_buf;\n    size_t i, len;\n    int re_bytecode_len;\n    JSValue ret;\n    char error_msg[64];\n\n    re_flags = 0;\n    if (!JS_IsUndefined(flags)) {\n        str = JS_ToCStringLen(ctx, &len, flags);\n        if (!str)\n            return JS_EXCEPTION;\n        /* XXX: re_flags = LRE_FLAG_OCTAL unless strict mode? */\n        for (i = 0; i < len; i++) {\n            switch(str[i]) {\n            case 'g':\n                mask = LRE_FLAG_GLOBAL;\n                break;\n            case 'i':\n                mask = LRE_FLAG_IGNORECASE;\n                break;\n            case 'm':\n                mask = LRE_FLAG_MULTILINE;\n                break;\n            case 's':\n                mask = LRE_FLAG_DOTALL;\n                break;\n            case 'u':\n                mask = LRE_FLAG_UTF16;\n                break;\n            case 'y':\n                mask = LRE_FLAG_STICKY;\n                break;\n            default:\n                goto bad_flags;\n            }\n            if ((re_flags & mask) != 0) {\n            bad_flags:\n                JS_FreeCString(ctx, str);\n                return JS_ThrowSyntaxError(ctx, \"invalid regular expression flags\");\n            }\n            re_flags |= mask;\n        }\n        JS_FreeCString(ctx, str);\n    }\n\n    str = JS_ToCStringLen2(ctx, &len, pattern, !(re_flags & LRE_FLAG_UTF16));\n    if (!str)\n        return JS_EXCEPTION;\n    re_bytecode_buf = lre_compile(&re_bytecode_len, error_msg,\n                                  sizeof(error_msg), str, len, re_flags, ctx);\n    JS_FreeCString(ctx, str);\n    if (!re_bytecode_buf) {\n        JS_ThrowSyntaxError(ctx, \"%s\", error_msg);\n        return JS_EXCEPTION;\n    }\n\n    ret = js_new_string8(ctx, re_bytecode_buf, re_bytecode_len);\n    js_free(ctx, re_bytecode_buf);\n    return ret;\n}\n\n/* create a RegExp object from a string containing the RegExp bytecode\n   and the source pattern */\nstatic JSValue js_regexp_constructor_internal(JSContext *ctx, JSValueConst ctor,\n                                              JSValue pattern, JSValue bc)\n{\n    JSValue obj;\n    JSObject *p;\n    JSRegExp *re;\n\n    /* sanity check */\n    if (JS_VALUE_GET_TAG(bc) != JS_TAG_STRING ||\n        JS_VALUE_GET_TAG(pattern) != JS_TAG_STRING) {\n        JS_ThrowTypeError(ctx, \"string expected\");\n    fail:\n        JS_FreeValue(ctx, bc);\n        JS_FreeValue(ctx, pattern);\n        return JS_EXCEPTION;\n    }\n\n    obj = js_create_from_ctor(ctx, ctor, JS_CLASS_REGEXP);\n    if (JS_IsException(obj))\n        goto fail;\n    p = JS_VALUE_GET_OBJ(obj);\n    re = &p->u.regexp;\n    re->pattern = JS_VALUE_GET_STRING(pattern);\n    re->bytecode = JS_VALUE_GET_STRING(bc);\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_lastIndex, JS_NewInt32(ctx, 0),\n                           JS_PROP_WRITABLE);\n    return obj;\n}\n\nstatic JSRegExp *js_get_regexp(JSContext *ctx, JSValueConst obj, BOOL throw_error)\n{\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(obj);\n        if (p->class_id == JS_CLASS_REGEXP)\n            return &p->u.regexp;\n    }\n    if (throw_error) {\n        JS_ThrowTypeErrorInvalidClass(ctx, JS_CLASS_REGEXP);\n    }\n    return NULL;\n}\n\n/* return < 0 if exception or TRUE/FALSE */\nstatic int js_is_regexp(JSContext *ctx, JSValueConst obj)\n{\n    JSValue m;\n\n    if (!JS_IsObject(obj))\n        return FALSE;\n    m = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_match);\n    if (JS_IsException(m))\n        return -1;\n    if (!JS_IsUndefined(m))\n        return JS_ToBoolFree(ctx, m);\n    return js_get_regexp(ctx, obj, FALSE) != NULL;\n}\n\nstatic JSValue js_regexp_constructor(JSContext *ctx, JSValueConst new_target,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue pattern, flags, bc, val;\n    JSValueConst pat, flags1;\n    JSRegExp *re;\n    int pat_is_regexp;\n\n    pat = argv[0];\n    flags1 = argv[1];\n    pat_is_regexp = js_is_regexp(ctx, pat);\n    if (pat_is_regexp < 0)\n        return JS_EXCEPTION;\n    if (JS_IsUndefined(new_target)) {\n        /* called as a function */\n        new_target = JS_GetActiveFunction(ctx);\n        if (pat_is_regexp && JS_IsUndefined(flags1)) {\n            JSValue ctor;\n            BOOL res;\n            ctor = JS_GetProperty(ctx, pat, JS_ATOM_constructor);\n            if (JS_IsException(ctor))\n                return ctor;\n            res = js_same_value(ctx, ctor, new_target);\n            JS_FreeValue(ctx, ctor);\n            if (res)\n                return JS_DupValue(ctx, pat);\n        }\n    }\n    re = js_get_regexp(ctx, pat, FALSE);\n    if (re) {\n        pattern = JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, re->pattern));\n        if (JS_IsUndefined(flags1)) {\n            bc = JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, re->bytecode));\n            goto no_compilation;\n        } else {\n            flags = JS_ToString(ctx, flags1);\n            if (JS_IsException(flags))\n                goto fail;\n        }\n    } else {\n        flags = JS_UNDEFINED;\n        if (pat_is_regexp) {\n            pattern = JS_GetProperty(ctx, pat, JS_ATOM_source);\n            if (JS_IsException(pattern))\n                goto fail;\n            if (JS_IsUndefined(flags1)) {\n                flags = JS_GetProperty(ctx, pat, JS_ATOM_flags);\n                if (JS_IsException(flags))\n                    goto fail;\n            } else {\n                flags = JS_DupValue(ctx, flags1);\n            }\n        } else {\n            pattern = JS_DupValue(ctx, pat);\n            flags = JS_DupValue(ctx, flags1);\n        }\n        if (JS_IsUndefined(pattern)) {\n            pattern = JS_AtomToString(ctx, JS_ATOM_empty_string);\n        } else {\n            val = pattern;\n            pattern = JS_ToString(ctx, val);\n            JS_FreeValue(ctx, val);\n            if (JS_IsException(pattern))\n                goto fail;\n        }\n    }\n    bc = js_compile_regexp(ctx, pattern, flags);\n    if (JS_IsException(bc))\n        goto fail;\n    JS_FreeValue(ctx, flags);\n no_compilation:\n    return js_regexp_constructor_internal(ctx, new_target, pattern, bc);\n fail:\n    JS_FreeValue(ctx, pattern);\n    JS_FreeValue(ctx, flags);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_regexp_compile(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSRegExp *re1, *re;\n    JSValueConst pattern1, flags1;\n    JSValue bc, pattern;\n\n    re = js_get_regexp(ctx, this_val, TRUE);\n    if (!re)\n        return JS_EXCEPTION;\n    pattern1 = argv[0];\n    flags1 = argv[1];\n    re1 = js_get_regexp(ctx, pattern1, FALSE);\n    if (re1) {\n        if (!JS_IsUndefined(flags1))\n            return JS_ThrowTypeError(ctx, \"flags must be undefined\");\n        pattern = JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, re1->pattern));\n        bc = JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, re1->bytecode));\n    } else {\n        bc = JS_UNDEFINED;\n        if (JS_IsUndefined(pattern1))\n            pattern = JS_AtomToString(ctx, JS_ATOM_empty_string);\n        else\n            pattern = JS_ToString(ctx, pattern1);\n        if (JS_IsException(pattern))\n            goto fail;\n        bc = js_compile_regexp(ctx, pattern, flags1);\n        if (JS_IsException(bc))\n            goto fail;\n    }\n    JS_FreeValue(ctx, JS_MKPTR(JS_TAG_STRING, re->pattern));\n    JS_FreeValue(ctx, JS_MKPTR(JS_TAG_STRING, re->bytecode));\n    re->pattern = JS_VALUE_GET_STRING(pattern);\n    re->bytecode = JS_VALUE_GET_STRING(bc);\n    if (JS_SetProperty(ctx, this_val, JS_ATOM_lastIndex,\n                       JS_NewInt32(ctx, 0)) < 0)\n        return JS_EXCEPTION;\n    return JS_DupValue(ctx, this_val);\n fail:\n    JS_FreeValue(ctx, pattern);\n    JS_FreeValue(ctx, bc);\n    return JS_EXCEPTION;\n}\n\n#if 0\nstatic JSValue js_regexp_get___source(JSContext *ctx, JSValueConst this_val)\n{\n    JSRegExp *re = js_get_regexp(ctx, this_val, TRUE);\n    if (!re)\n        return JS_EXCEPTION;\n    return JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, re->pattern));\n}\n\nstatic JSValue js_regexp_get___flags(JSContext *ctx, JSValueConst this_val)\n{\n    JSRegExp *re = js_get_regexp(ctx, this_val, TRUE);\n    int flags;\n\n    if (!re)\n        return JS_EXCEPTION;\n    flags = lre_get_flags(re->bytecode->u.str8);\n    return JS_NewInt32(ctx, flags);\n}\n#endif\n\nstatic JSValue js_regexp_get_source(JSContext *ctx, JSValueConst this_val)\n{\n    JSRegExp *re;\n    JSString *p;\n    StringBuffer b_s, *b = &b_s;\n    int i, n, c, c2, bra;\n\n    if (JS_VALUE_GET_TAG(this_val) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    if (js_same_value(ctx, this_val, ctx->class_proto[JS_CLASS_REGEXP]))\n        goto empty_regex;\n\n    re = js_get_regexp(ctx, this_val, TRUE);\n    if (!re)\n        return JS_EXCEPTION;\n\n    p = re->pattern;\n\n    if (p->len == 0) {\n    empty_regex:\n        return JS_NewString(ctx, \"(?:)\");\n    }    \n    string_buffer_init2(ctx, b, p->len, p->is_wide_char);\n\n    /* Escape '/' and newline sequences as needed */\n    bra = 0;\n    for (i = 0, n = p->len; i < n;) {\n        c2 = -1;\n        switch (c = string_get(p, i++)) {\n        case '\\\\':\n            if (i < n)\n                c2 = string_get(p, i++);\n            break;\n        case ']':\n            bra = 0;\n            break;\n        case '[':\n            if (!bra) {\n                if (i < n && string_get(p, i) == ']')\n                    c2 = string_get(p, i++);\n                bra = 1;\n            }\n            break;\n        case '\\n':\n            c = '\\\\';\n            c2 = 'n';\n            break;\n        case '\\r':\n            c = '\\\\';\n            c2 = 'r';\n            break;\n        case '/':\n            if (!bra) {\n                c = '\\\\';\n                c2 = '/';\n            }\n            break;\n        }\n        string_buffer_putc16(b, c);\n        if (c2 >= 0)\n            string_buffer_putc16(b, c2);\n    }\n    return string_buffer_end(b);\n}\n\nstatic JSValue js_regexp_get_flag(JSContext *ctx, JSValueConst this_val, int mask)\n{\n    JSRegExp *re;\n    int flags;\n\n    if (JS_VALUE_GET_TAG(this_val) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    re = js_get_regexp(ctx, this_val, FALSE);\n    if (!re) {\n        if (js_same_value(ctx, this_val, ctx->class_proto[JS_CLASS_REGEXP]))\n            return JS_UNDEFINED;\n        else\n            return JS_ThrowTypeErrorInvalidClass(ctx, JS_CLASS_REGEXP);\n    }\n    \n    flags = lre_get_flags(re->bytecode->u.str8);\n    return JS_NewBool(ctx, (flags & mask) != 0);\n}\n\nstatic JSValue js_regexp_get_flags(JSContext *ctx, JSValueConst this_val)\n{\n    char str[8], *p = str;\n    int res;\n\n    if (JS_VALUE_GET_TAG(this_val) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    res = JS_ToBoolFree(ctx, JS_GetProperty(ctx, this_val, JS_ATOM_global));\n    if (res < 0)\n        goto exception;\n    if (res)\n        *p++ = 'g';\n    res = JS_ToBoolFree(ctx, JS_GetPropertyStr(ctx, this_val, \"ignoreCase\"));\n    if (res < 0)\n        goto exception;\n    if (res)\n        *p++ = 'i';\n    res = JS_ToBoolFree(ctx, JS_GetPropertyStr(ctx, this_val, \"multiline\"));\n    if (res < 0)\n        goto exception;\n    if (res)\n        *p++ = 'm';\n    res = JS_ToBoolFree(ctx, JS_GetPropertyStr(ctx, this_val, \"dotAll\"));\n    if (res < 0)\n        goto exception;\n    if (res)\n        *p++ = 's';\n    res = JS_ToBoolFree(ctx, JS_GetProperty(ctx, this_val, JS_ATOM_unicode));\n    if (res < 0)\n        goto exception;\n    if (res)\n        *p++ = 'u';\n    res = JS_ToBoolFree(ctx, JS_GetPropertyStr(ctx, this_val, \"sticky\"));\n    if (res < 0)\n        goto exception;\n    if (res)\n        *p++ = 'y';\n    return JS_NewStringLen(ctx, str, p - str);\n\nexception:\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_regexp_toString(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    JSValue pattern, flags;\n    StringBuffer b_s, *b = &b_s;\n\n    if (!JS_IsObject(this_val))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    string_buffer_init(ctx, b, 0);\n    string_buffer_putc8(b, '/');\n    pattern = JS_GetProperty(ctx, this_val, JS_ATOM_source);\n    if (string_buffer_concat_value_free(b, pattern))\n        goto fail;\n    string_buffer_putc8(b, '/');\n    flags = JS_GetProperty(ctx, this_val, JS_ATOM_flags);\n    if (string_buffer_concat_value_free(b, flags))\n        goto fail;\n    return string_buffer_end(b);\n\nfail:\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nBOOL lre_check_stack_overflow(void *opaque, size_t alloca_size)\n{\n    JSContext *ctx = opaque;\n    return js_check_stack_overflow(ctx->rt, alloca_size);\n}\n\nvoid *lre_realloc(void *opaque, void *ptr, size_t size)\n{\n    JSContext *ctx = opaque;\n    /* No JS exception is raised here */\n    return js_realloc_rt(ctx->rt, ptr, size);\n}\n\nstatic JSValue js_regexp_exec(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    JSRegExp *re = js_get_regexp(ctx, this_val, TRUE);\n    JSString *str;\n    JSValue str_val, obj, val, groups = JS_UNDEFINED;\n    uint8_t *re_bytecode;\n    int ret;\n    uint8_t **capture, *str_buf;\n    int capture_count, shift, i, re_flags;\n    int64_t last_index;\n    const char *group_name_ptr;\n\n    if (!re)\n        return JS_EXCEPTION;\n    str_val = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str_val))\n        return str_val;\n    val = JS_GetProperty(ctx, this_val, JS_ATOM_lastIndex);\n    if (JS_IsException(val) ||\n        JS_ToLengthFree(ctx, &last_index, val)) {\n        JS_FreeValue(ctx, str_val);\n        return JS_EXCEPTION;\n    }\n    re_bytecode = re->bytecode->u.str8;\n    re_flags = lre_get_flags(re_bytecode);\n    if ((re_flags & (LRE_FLAG_GLOBAL | LRE_FLAG_STICKY)) == 0) {\n        last_index = 0;\n    }\n    str = JS_VALUE_GET_STRING(str_val);\n    capture_count = lre_get_capture_count(re_bytecode);\n    capture = NULL;\n    if (capture_count > 0) {\n        capture = js_malloc(ctx, sizeof(capture[0]) * capture_count * 2);\n        if (!capture) {\n            JS_FreeValue(ctx, str_val);\n            return JS_EXCEPTION;\n        }\n    }\n    shift = str->is_wide_char;\n    str_buf = str->u.str8;\n    if (last_index > str->len) {\n        ret = 2;\n    } else {\n        ret = lre_exec(capture, re_bytecode,\n                       str_buf, last_index, str->len,\n                       shift, ctx);\n    }\n    obj = JS_NULL;\n    if (ret != 1) {\n        if (ret >= 0) {\n            if (ret == 2 || (re_flags & (LRE_FLAG_GLOBAL | LRE_FLAG_STICKY))) {\n                if (JS_SetProperty(ctx, this_val, JS_ATOM_lastIndex,\n                                   JS_NewInt32(ctx, 0)) < 0)\n                    goto fail;\n            }\n        } else {\n            JS_ThrowInternalError(ctx, \"out of memory in regexp execution\");\n            goto fail;\n        }\n        JS_FreeValue(ctx, str_val);\n    } else {\n        int prop_flags;\n        if (re_flags & (LRE_FLAG_GLOBAL | LRE_FLAG_STICKY)) {\n            if (JS_SetProperty(ctx, this_val, JS_ATOM_lastIndex,\n                               JS_NewInt32(ctx, (capture[1] - str_buf) >> shift)) < 0)\n                goto fail;\n        }\n        obj = JS_NewArray(ctx);\n        if (JS_IsException(obj))\n            goto fail;\n        prop_flags = JS_PROP_C_W_E | JS_PROP_THROW;\n        group_name_ptr = lre_get_groupnames(re_bytecode);\n        if (group_name_ptr) {\n            groups = JS_NewObjectProto(ctx, JS_NULL);\n            if (JS_IsException(groups))\n                goto fail;\n        }\n\n        for(i = 0; i < capture_count; i++) {\n            int start, end;\n            JSValue val;\n            if (capture[2 * i] == NULL ||\n                capture[2 * i + 1] == NULL) {\n                val = JS_UNDEFINED;\n            } else {\n                start = (capture[2 * i] - str_buf) >> shift;\n                end = (capture[2 * i + 1] - str_buf) >> shift;\n                val = js_sub_string(ctx, str, start, end);\n                if (JS_IsException(val))\n                    goto fail;\n            }\n            if (group_name_ptr && i > 0) {\n                if (*group_name_ptr) {\n                    if (JS_DefinePropertyValueStr(ctx, groups, group_name_ptr,\n                                                  JS_DupValue(ctx, val),\n                                                  prop_flags) < 0) {\n                        JS_FreeValue(ctx, val);\n                        goto fail;\n                    }\n                }\n                group_name_ptr += strlen(group_name_ptr) + 1;\n            }\n            if (JS_DefinePropertyValueUint32(ctx, obj, i, val, prop_flags) < 0)\n                goto fail;\n        }\n        if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_groups,\n                                   groups, prop_flags) < 0)\n            goto fail;\n        if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_index,\n                                   JS_NewInt32(ctx, (capture[0] - str_buf) >> shift), prop_flags) < 0)\n            goto fail;\n        if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_input, str_val, prop_flags) < 0)\n            goto fail1;\n    }\n    js_free(ctx, capture);\n    return obj;\nfail:\n    JS_FreeValue(ctx, groups);\n    JS_FreeValue(ctx, str_val);\nfail1:\n    JS_FreeValue(ctx, obj);\n    js_free(ctx, capture);\n    return JS_EXCEPTION;\n}\n\n/* delete portions of a string that match a given regex */\nstatic JSValue JS_RegExpDelete(JSContext *ctx, JSValueConst this_val, JSValueConst arg)\n{\n    JSRegExp *re = js_get_regexp(ctx, this_val, TRUE);\n    JSString *str;\n    JSValue str_val, val;\n    uint8_t *re_bytecode;\n    int ret;\n    uint8_t **capture, *str_buf;\n    int capture_count, shift, re_flags;\n    int next_src_pos, start, end;\n    int64_t last_index;\n    StringBuffer b_s, *b = &b_s;\n\n    if (!re)\n        return JS_EXCEPTION;\n\n    string_buffer_init(ctx, b, 0);\n\n    capture = NULL;\n    str_val = JS_ToString(ctx, arg);\n    if (JS_IsException(str_val))\n        goto fail;\n    str = JS_VALUE_GET_STRING(str_val);\n    re_bytecode = re->bytecode->u.str8;\n    re_flags = lre_get_flags(re_bytecode);\n    if ((re_flags & (LRE_FLAG_GLOBAL | LRE_FLAG_STICKY)) == 0) {\n        last_index = 0;\n    } else {\n        val = JS_GetProperty(ctx, this_val, JS_ATOM_lastIndex);\n        if (JS_IsException(val) || JS_ToLengthFree(ctx, &last_index, val))\n            goto fail;\n    }\n    capture_count = lre_get_capture_count(re_bytecode);\n    if (capture_count > 0) {\n        capture = js_malloc(ctx, sizeof(capture[0]) * capture_count * 2);\n        if (!capture)\n            goto fail;\n    }\n    shift = str->is_wide_char;\n    str_buf = str->u.str8;\n    next_src_pos = 0;\n    for (;;) {\n        if (last_index > str->len)\n            break;\n\n        ret = lre_exec(capture, re_bytecode,\n                       str_buf, last_index, str->len, shift, ctx);\n        if (ret != 1) {\n            if (ret >= 0) {\n                if (ret == 2 || (re_flags & (LRE_FLAG_GLOBAL | LRE_FLAG_STICKY))) {\n                    if (JS_SetProperty(ctx, this_val, JS_ATOM_lastIndex,\n                                       JS_NewInt32(ctx, 0)) < 0)\n                        goto fail;\n                }\n            } else {\n                JS_ThrowInternalError(ctx, \"out of memory in regexp execution\");\n                goto fail;\n            }\n            break;\n        }\n        start = (capture[0] - str_buf) >> shift;\n        end = (capture[1] - str_buf) >> shift;\n        last_index = end;\n        if (next_src_pos < start) {\n            if (string_buffer_concat(b, str, next_src_pos, start))\n                goto fail;\n        }\n        next_src_pos = end;\n        if (!(re_flags & LRE_FLAG_GLOBAL)) {\n            if (JS_SetProperty(ctx, this_val, JS_ATOM_lastIndex,\n                               JS_NewInt32(ctx, end)) < 0)\n                goto fail;\n            break;\n        }\n        if (end == start) {\n            if (!(re_flags & LRE_FLAG_UTF16) || (unsigned)end >= str->len || !str->is_wide_char) {\n                end++;\n            } else {\n                string_getc(str, &end);\n            }\n        }\n        last_index = end;\n    }\n    if (string_buffer_concat(b, str, next_src_pos, str->len))\n        goto fail;\n    JS_FreeValue(ctx, str_val);\n    js_free(ctx, capture);\n    return string_buffer_end(b);\nfail:\n    JS_FreeValue(ctx, str_val);\n    js_free(ctx, capture);\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_RegExpExec(JSContext *ctx, JSValueConst r, JSValueConst s)\n{\n    JSValue method, ret;\n\n    method = JS_GetProperty(ctx, r, JS_ATOM_exec);\n    if (JS_IsException(method))\n        return method;\n    if (JS_IsFunction(ctx, method)) {\n        ret = JS_CallFree(ctx, method, r, 1, &s);\n        if (JS_IsException(ret))\n            return ret;\n        if (!JS_IsObject(ret) && !JS_IsNull(ret)) {\n            JS_FreeValue(ctx, ret);\n            return JS_ThrowTypeError(ctx, \"RegExp exec method must return an object or null\");\n        }\n        return ret;\n    }\n    JS_FreeValue(ctx, method);\n    return js_regexp_exec(ctx, r, 1, &s);\n}\n\n#if 0\nstatic JSValue js_regexp___RegExpExec(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv)\n{\n    return JS_RegExpExec(ctx, argv[0], argv[1]);\n}\nstatic JSValue js_regexp___RegExpDelete(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv)\n{\n    return JS_RegExpDelete(ctx, argv[0], argv[1]);\n}\n#endif\n\nstatic JSValue js_regexp_test(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    JSValue val;\n    BOOL ret;\n\n    val = JS_RegExpExec(ctx, this_val, argv[0]);\n    if (JS_IsException(val))\n        return JS_EXCEPTION;\n    ret = !JS_IsNull(val);\n    JS_FreeValue(ctx, val);\n    return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_regexp_Symbol_match(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv)\n{\n    // [Symbol.match](str)\n    JSValueConst rx = this_val;\n    JSValue A, S, result, matchStr;\n    int global, n, fullUnicode, isEmpty;\n    JSString *p;\n\n    if (!JS_IsObject(rx))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    A = JS_UNDEFINED;\n    result = JS_UNDEFINED;\n    matchStr = JS_UNDEFINED;\n    S = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(S))\n        goto exception;\n\n    global = JS_ToBoolFree(ctx, JS_GetProperty(ctx, rx, JS_ATOM_global));\n    if (global < 0)\n        goto exception;\n\n    if (!global) {\n        A = JS_RegExpExec(ctx, rx, S);\n    } else {\n        fullUnicode = JS_ToBoolFree(ctx, JS_GetProperty(ctx, rx, JS_ATOM_unicode));\n        if (fullUnicode < 0)\n            goto exception;\n\n        if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, JS_NewInt32(ctx, 0)) < 0)\n            goto exception;\n        A = JS_NewArray(ctx);\n        if (JS_IsException(A))\n            goto exception;\n        n = 0;\n        for(;;) {\n            JS_FreeValue(ctx, result);\n            result = JS_RegExpExec(ctx, rx, S);\n            if (JS_IsException(result))\n                goto exception;\n            if (JS_IsNull(result))\n                break;\n            matchStr = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, result, 0));\n            if (JS_IsException(matchStr))\n                goto exception;\n            isEmpty = JS_IsEmptyString(matchStr);\n            if (JS_SetPropertyInt64(ctx, A, n++, matchStr) < 0)\n                goto exception;\n            if (isEmpty) {\n                int64_t thisIndex, nextIndex;\n                if (JS_ToLengthFree(ctx, &thisIndex,\n                                    JS_GetProperty(ctx, rx, JS_ATOM_lastIndex)) < 0)\n                    goto exception;\n                p = JS_VALUE_GET_STRING(S);\n                nextIndex = string_advance_index(p, thisIndex, fullUnicode);\n                if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, JS_NewInt64(ctx, nextIndex)) < 0)\n                    goto exception;\n            }\n        }\n        if (n == 0) {\n            JS_FreeValue(ctx, A);\n            A = JS_NULL;\n        }\n    }\n    JS_FreeValue(ctx, result);\n    JS_FreeValue(ctx, S);\n    return A;\n\nexception:\n    JS_FreeValue(ctx, A);\n    JS_FreeValue(ctx, result);\n    JS_FreeValue(ctx, S);\n    return JS_EXCEPTION;\n}\n\ntypedef struct JSRegExpStringIteratorData {\n    JSValue iterating_regexp;\n    JSValue iterated_string;\n    BOOL global;\n    BOOL unicode;\n    BOOL done;\n} JSRegExpStringIteratorData;\n\nstatic void js_regexp_string_iterator_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSRegExpStringIteratorData *it = p->u.regexp_string_iterator_data;\n    if (it) {\n        JS_FreeValueRT(rt, it->iterating_regexp);\n        JS_FreeValueRT(rt, it->iterated_string);\n        js_free_rt(rt, it);\n    }\n}\n\nstatic void js_regexp_string_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                           JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSRegExpStringIteratorData *it = p->u.regexp_string_iterator_data;\n    if (it) {\n        JS_MarkValue(rt, it->iterating_regexp, mark_func);\n        JS_MarkValue(rt, it->iterated_string, mark_func);\n    }\n}\n\nstatic JSValue js_regexp_string_iterator_next(JSContext *ctx,\n                                              JSValueConst this_val,\n                                              int argc, JSValueConst *argv,\n                                              BOOL *pdone, int magic)\n{\n    JSRegExpStringIteratorData *it;\n    JSValueConst R, S;\n    JSValue matchStr = JS_UNDEFINED, match = JS_UNDEFINED;\n    JSString *sp;\n\n    it = JS_GetOpaque2(ctx, this_val, JS_CLASS_REGEXP_STRING_ITERATOR);\n    if (!it)\n        goto exception;\n    if (it->done) {\n        *pdone = TRUE;\n        return JS_UNDEFINED;\n    }\n    R = it->iterating_regexp;\n    S = it->iterated_string;\n    match = JS_RegExpExec(ctx, R, S);\n    if (JS_IsException(match))\n        goto exception;\n    if (JS_IsNull(match)) {\n        it->done = TRUE;\n        *pdone = TRUE;\n        return JS_UNDEFINED;\n    } else if (it->global) {\n        matchStr = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, match, 0));\n        if (JS_IsException(matchStr))\n            goto exception;\n        if (JS_IsEmptyString(matchStr)) {\n            int64_t thisIndex, nextIndex;\n            if (JS_ToLengthFree(ctx, &thisIndex,\n                                JS_GetProperty(ctx, R, JS_ATOM_lastIndex)) < 0)\n                goto exception;\n            sp = JS_VALUE_GET_STRING(S);\n            nextIndex = string_advance_index(sp, thisIndex, it->unicode);\n            if (JS_SetProperty(ctx, R, JS_ATOM_lastIndex,\n                               JS_NewInt64(ctx, nextIndex)) < 0)\n                goto exception;\n        }\n        JS_FreeValue(ctx, matchStr);\n    } else {\n        it->done = TRUE;\n    }\n    *pdone = FALSE;\n    return match;\n exception:\n    JS_FreeValue(ctx, match);\n    JS_FreeValue(ctx, matchStr);\n    *pdone = FALSE;\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_regexp_Symbol_matchAll(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    // [Symbol.matchAll](str)\n    JSValueConst R = this_val;\n    JSValue S, C, flags, matcher, iter;\n    JSValueConst args[2];\n    JSString *strp;\n    int64_t lastIndex;\n    JSRegExpStringIteratorData *it;\n    \n    if (!JS_IsObject(R))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    C = JS_UNDEFINED;\n    flags = JS_UNDEFINED;\n    matcher = JS_UNDEFINED;\n    iter = JS_UNDEFINED;\n    \n    S = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(S))\n        goto exception;\n    C = JS_SpeciesConstructor(ctx, R, ctx->regexp_ctor);\n    if (JS_IsException(C))\n        goto exception;\n    flags = JS_ToStringFree(ctx, JS_GetProperty(ctx, R, JS_ATOM_flags));\n    if (JS_IsException(flags))\n        goto exception;\n    args[0] = R;\n    args[1] = flags;\n    matcher = JS_CallConstructor(ctx, C, 2, args);\n    if (JS_IsException(matcher))\n        goto exception;\n    if (JS_ToLengthFree(ctx, &lastIndex,\n                        JS_GetProperty(ctx, R, JS_ATOM_lastIndex)))\n        goto exception;\n    if (JS_SetProperty(ctx, matcher, JS_ATOM_lastIndex,\n                       JS_NewInt64(ctx, lastIndex)) < 0)\n        goto exception;\n    \n    iter = JS_NewObjectClass(ctx, JS_CLASS_REGEXP_STRING_ITERATOR);\n    if (JS_IsException(iter))\n        goto exception;\n    it = js_malloc(ctx, sizeof(*it));\n    if (!it)\n        goto exception;\n    it->iterating_regexp = matcher;\n    it->iterated_string = S;\n    strp = JS_VALUE_GET_STRING(flags);\n    it->global = string_indexof_char(strp, 'g', 0) >= 0;\n    it->unicode = string_indexof_char(strp, 'u', 0) >= 0;\n    it->done = FALSE;\n    JS_SetOpaque(iter, it);\n\n    JS_FreeValue(ctx, C);\n    JS_FreeValue(ctx, flags);\n    return iter;\n exception:\n    JS_FreeValue(ctx, S);\n    JS_FreeValue(ctx, C);\n    JS_FreeValue(ctx, flags);\n    JS_FreeValue(ctx, matcher);\n    JS_FreeValue(ctx, iter);\n    return JS_EXCEPTION;\n}\n\ntypedef struct ValueBuffer {\n    JSContext *ctx;\n    JSValue *arr;\n    JSValue def[4];\n    int len;\n    int size;\n    int error_status;\n} ValueBuffer;\n\nstatic int value_buffer_init(JSContext *ctx, ValueBuffer *b)\n{\n    b->ctx = ctx;\n    b->len = 0;\n    b->size = 4;\n    b->error_status = 0;\n    b->arr = b->def;\n    return 0;\n}\n\nstatic void value_buffer_free(ValueBuffer *b)\n{\n    while (b->len > 0)\n        JS_FreeValue(b->ctx, b->arr[--b->len]);\n    if (b->arr != b->def)\n        js_free(b->ctx, b->arr);\n    b->arr = b->def;\n    b->size = 4;\n}\n\nstatic int value_buffer_append(ValueBuffer *b, JSValue val)\n{\n    if (b->error_status)\n        return -1;\n\n    if (b->len >= b->size) {\n        int new_size = (b->len + (b->len >> 1) + 31) & ~16;\n        size_t slack;\n        JSValue *new_arr;\n\n        if (b->arr == b->def) {\n            new_arr = js_realloc2(b->ctx, NULL, sizeof(*b->arr) * new_size, &slack);\n            if (new_arr)\n                memcpy(new_arr, b->def, sizeof b->def);\n        } else {\n            new_arr = js_realloc2(b->ctx, b->arr, sizeof(*b->arr) * new_size, &slack);\n        }\n        if (!new_arr) {\n            value_buffer_free(b);\n            JS_FreeValue(b->ctx, val);\n            b->error_status = -1;\n            return -1;\n        }\n        new_size += slack / sizeof(*new_arr);\n        b->arr = new_arr;\n        b->size = new_size;\n    }\n    b->arr[b->len++] = val;\n    return 0;\n}\n\nstatic int js_is_standard_regexp(JSContext *ctx, JSValueConst rx)\n{\n    JSValue val;\n    int res;\n\n    val = JS_GetProperty(ctx, rx, JS_ATOM_constructor);\n    if (JS_IsException(val))\n        return -1;\n    // rx.constructor === RegExp\n    res = js_same_value(ctx, val, ctx->regexp_ctor);\n    JS_FreeValue(ctx, val);\n    if (res) {\n        val = JS_GetProperty(ctx, rx, JS_ATOM_exec);\n        if (JS_IsException(val))\n            return -1;\n        // rx.exec === RE_exec\n        res = JS_IsCFunction(ctx, val, js_regexp_exec, 0);\n        JS_FreeValue(ctx, val);\n    }\n    return res;\n}\n\nstatic JSValue js_regexp_Symbol_replace(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv)\n{\n    // [Symbol.replace](str, rep)\n    JSValueConst rx = this_val, rep = argv[1];\n    JSValueConst args[6];\n    JSValue str, rep_val, matched, tab, rep_str, namedCaptures, res;\n    JSString *sp, *rp;\n    StringBuffer b_s, *b = &b_s;\n    ValueBuffer v_b, *results = &v_b;\n    int nextSourcePosition, n, j, functionalReplace, is_global, fullUnicode;\n    uint32_t nCaptures;\n    int64_t position;\n\n    if (!JS_IsObject(rx))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    string_buffer_init(ctx, b, 0);\n    value_buffer_init(ctx, results);\n\n    rep_val = JS_UNDEFINED;\n    matched = JS_UNDEFINED;\n    tab = JS_UNDEFINED;\n    rep_str = JS_UNDEFINED;\n    namedCaptures = JS_UNDEFINED;\n\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        goto exception;\n        \n    sp = JS_VALUE_GET_STRING(str);\n    rp = NULL;\n    functionalReplace = JS_IsFunction(ctx, rep);\n    if (!functionalReplace) {\n        rep_val = JS_ToString(ctx, rep);\n        if (JS_IsException(rep_val))\n            goto exception;\n        rp = JS_VALUE_GET_STRING(rep_val);\n    }\n    fullUnicode = 0;\n    is_global = JS_ToBoolFree(ctx, JS_GetProperty(ctx, rx, JS_ATOM_global));\n    if (is_global < 0)\n        goto exception;\n    if (is_global) {\n        fullUnicode = JS_ToBoolFree(ctx, JS_GetProperty(ctx, rx, JS_ATOM_unicode));\n        if (fullUnicode < 0)\n            goto exception;\n        if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, JS_NewInt32(ctx, 0)) < 0)\n            goto exception;\n    }\n\n    if (rp && rp->len == 0 && is_global && js_is_standard_regexp(ctx, rx)) {\n        /* use faster version for simple cases */\n        res = JS_RegExpDelete(ctx, rx, str);\n        goto done;\n    }\n    for(;;) {\n        JSValue result;\n        result = JS_RegExpExec(ctx, rx, str);\n        if (JS_IsException(result))\n            goto exception;\n        if (JS_IsNull(result))\n            break;\n        if (value_buffer_append(results, result) < 0)\n            goto exception;\n        if (!is_global)\n            break;\n        JS_FreeValue(ctx, matched);\n        matched = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, result, 0));\n        if (JS_IsException(matched))\n            goto exception;\n        if (JS_IsEmptyString(matched)) {\n            /* always advance of at least one char */\n            int64_t thisIndex, nextIndex;\n            if (JS_ToLengthFree(ctx, &thisIndex, JS_GetProperty(ctx, rx, JS_ATOM_lastIndex)) < 0)\n                goto exception;\n            nextIndex = string_advance_index(sp, thisIndex, fullUnicode);\n            if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, JS_NewInt64(ctx, nextIndex)) < 0)\n                goto exception;\n        }\n    }\n    nextSourcePosition = 0;\n    for(j = 0; j < results->len; j++) {\n        JSValueConst result;\n        result = results->arr[j];\n        if (js_get_length32(ctx, &nCaptures, result) < 0)\n            goto exception;\n        JS_FreeValue(ctx, matched);\n        matched = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, result, 0));\n        if (JS_IsException(matched))\n            goto exception;\n        if (JS_ToLengthFree(ctx, &position, JS_GetProperty(ctx, result, JS_ATOM_index)))\n            goto exception;\n        if (position > sp->len)\n            position = sp->len;\n        else if (position < 0)\n            position = 0;\n        /* ignore substition if going backward (can happen\n           with custom regexp object) */\n        JS_FreeValue(ctx, tab);\n        tab = JS_NewArray(ctx);\n        if (JS_IsException(tab))\n            goto exception;\n        if (JS_DefinePropertyValueInt64(ctx, tab, 0, JS_DupValue(ctx, matched),\n                                        JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n            goto exception;\n        for(n = 1; n < nCaptures; n++) {\n            JSValue capN;\n            capN = JS_GetPropertyInt64(ctx, result, n);\n            if (JS_IsException(capN))\n                goto exception;\n            if (!JS_IsUndefined(capN)) {\n                capN = JS_ToStringFree(ctx, capN);\n                if (JS_IsException(capN))\n                    goto exception;\n            }\n            if (JS_DefinePropertyValueInt64(ctx, tab, n, capN,\n                                            JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                goto exception;\n        }\n        JS_FreeValue(ctx, namedCaptures);\n        namedCaptures = JS_GetProperty(ctx, result, JS_ATOM_groups);\n        if (JS_IsException(namedCaptures))\n            goto exception;\n        if (functionalReplace) {\n            if (JS_DefinePropertyValueInt64(ctx, tab, n++, JS_NewInt32(ctx, position), JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                goto exception;\n            if (JS_DefinePropertyValueInt64(ctx, tab, n++, JS_DupValue(ctx, str), JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                goto exception;\n            if (!JS_IsUndefined(namedCaptures)) {\n                if (JS_DefinePropertyValueInt64(ctx, tab, n++, JS_DupValue(ctx, namedCaptures), JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                    goto exception;\n            }\n            args[0] = JS_UNDEFINED;\n            args[1] = tab;\n            JS_FreeValue(ctx, rep_str);\n            rep_str = JS_ToStringFree(ctx, js_function_apply(ctx, rep, 2, args, 0));\n        } else {\n            JSValue namedCaptures1;\n            if (!JS_IsUndefined(namedCaptures)) {\n                namedCaptures1 = JS_ToObject(ctx, namedCaptures);\n                if (JS_IsException(namedCaptures1))\n                    goto exception;\n            } else {\n                namedCaptures1 = JS_UNDEFINED;\n            }\n            args[0] = matched;\n            args[1] = str;\n            args[2] = JS_NewInt32(ctx, position);\n            args[3] = tab;\n            args[4] = namedCaptures1;\n            args[5] = rep_val;\n            JS_FreeValue(ctx, rep_str);\n            rep_str = js_string___GetSubstitution(ctx, JS_UNDEFINED, 6, args);\n            JS_FreeValue(ctx, namedCaptures1);\n        }\n        if (JS_IsException(rep_str))\n            goto exception;\n        if (position >= nextSourcePosition) {\n            string_buffer_concat(b, sp, nextSourcePosition, position);\n            string_buffer_concat_value(b, rep_str);\n            nextSourcePosition = position + JS_VALUE_GET_STRING(matched)->len;\n        }\n    }\n    string_buffer_concat(b, sp, nextSourcePosition, sp->len);\n    res = string_buffer_end(b);\n    goto done1;\n\nexception:\n    res = JS_EXCEPTION;\ndone:\n    string_buffer_free(b);\ndone1:\n    value_buffer_free(results);\n    JS_FreeValue(ctx, rep_val);\n    JS_FreeValue(ctx, matched);\n    JS_FreeValue(ctx, tab);\n    JS_FreeValue(ctx, rep_str);\n    JS_FreeValue(ctx, namedCaptures);\n    JS_FreeValue(ctx, str);\n    return res;\n}\n\nstatic JSValue js_regexp_Symbol_search(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    JSValueConst rx = this_val;\n    JSValue str, previousLastIndex, currentLastIndex, result, index;\n\n    if (!JS_IsObject(rx))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    result = JS_UNDEFINED;\n    currentLastIndex = JS_UNDEFINED;\n    previousLastIndex = JS_UNDEFINED;\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        goto exception;\n\n    previousLastIndex = JS_GetProperty(ctx, rx, JS_ATOM_lastIndex);\n    if (JS_IsException(previousLastIndex))\n        goto exception;\n\n    if (!js_same_value(ctx, previousLastIndex, JS_NewInt32(ctx, 0))) {\n        if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, JS_NewInt32(ctx, 0)) < 0) {\n            goto exception;\n        }\n    }\n    result = JS_RegExpExec(ctx, rx, str);\n    if (JS_IsException(result))\n        goto exception;\n    currentLastIndex = JS_GetProperty(ctx, rx, JS_ATOM_lastIndex);\n    if (JS_IsException(currentLastIndex))\n        goto exception;\n    if (js_same_value(ctx, currentLastIndex, previousLastIndex)) {\n        JS_FreeValue(ctx, previousLastIndex);\n    } else {\n        if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, previousLastIndex) < 0) {\n            previousLastIndex = JS_UNDEFINED;\n            goto exception;\n        }\n    }\n    JS_FreeValue(ctx, str);\n    JS_FreeValue(ctx, currentLastIndex);\n\n    if (JS_IsNull(result)) {\n        return JS_NewInt32(ctx, -1);\n    } else {\n        index = JS_GetProperty(ctx, result, JS_ATOM_index);\n        JS_FreeValue(ctx, result);\n        return index;\n    }\n\nexception:\n    JS_FreeValue(ctx, result);\n    JS_FreeValue(ctx, str);\n    JS_FreeValue(ctx, currentLastIndex);\n    JS_FreeValue(ctx, previousLastIndex);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_regexp_Symbol_split(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    // [Symbol.split](str, limit)\n    JSValueConst rx = this_val;\n    JSValueConst args[2];\n    JSValue str, ctor, splitter, A, flags, z, sub;\n    JSString *strp;\n    uint32_t lim, size, p, q;\n    int unicodeMatching;\n    int64_t lengthA, e, numberOfCaptures, i;\n\n    if (!JS_IsObject(rx))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    ctor = JS_UNDEFINED;\n    splitter = JS_UNDEFINED;\n    A = JS_UNDEFINED;\n    flags = JS_UNDEFINED;\n    z = JS_UNDEFINED;\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        goto exception;\n    ctor = JS_SpeciesConstructor(ctx, rx, ctx->regexp_ctor);\n    if (JS_IsException(ctor))\n        goto exception;\n    flags = JS_ToStringFree(ctx, JS_GetProperty(ctx, rx, JS_ATOM_flags));\n    if (JS_IsException(flags))\n        goto exception;\n    strp = JS_VALUE_GET_STRING(flags);\n    unicodeMatching = string_indexof_char(strp, 'u', 0) >= 0;\n    if (string_indexof_char(strp, 'y', 0) < 0) {\n        flags = JS_ConcatString3(ctx, \"\", flags, \"y\");\n        if (JS_IsException(flags))\n            goto exception;\n    }\n    args[0] = rx;\n    args[1] = flags;\n    splitter = JS_CallConstructor(ctx, ctor, 2, args);\n    if (JS_IsException(splitter))\n        goto exception;\n    A = JS_NewArray(ctx);\n    if (JS_IsException(A))\n        goto exception;\n    lengthA = 0;\n    if (JS_IsUndefined(argv[1])) {\n        lim = 0xffffffff;\n    } else {\n        if (JS_ToUint32(ctx, &lim, argv[1]) < 0)\n            goto exception;\n        if (lim == 0)\n            goto done;\n    }\n    strp = JS_VALUE_GET_STRING(str);\n    p = q = 0;\n    size = strp->len;\n    if (size == 0) {\n        z = JS_RegExpExec(ctx, splitter, str);\n        if (JS_IsException(z))\n            goto exception;\n        if (JS_IsNull(z))\n            goto add_tail;\n        goto done;\n    }\n    while (q < size) {\n        if (JS_SetProperty(ctx, splitter, JS_ATOM_lastIndex, JS_NewInt32(ctx, q)) < 0)\n            goto exception;\n        JS_FreeValue(ctx, z);    \n        z = JS_RegExpExec(ctx, splitter, str);\n        if (JS_IsException(z))\n            goto exception;\n        if (JS_IsNull(z)) {\n            q = string_advance_index(strp, q, unicodeMatching);\n        } else {\n            if (JS_ToLengthFree(ctx, &e, JS_GetProperty(ctx, splitter, JS_ATOM_lastIndex)))\n                goto exception;\n            if (e > size)\n                e = size;\n            if (e == p) {\n                q = string_advance_index(strp, q, unicodeMatching);\n            } else {\n                sub = js_sub_string(ctx, strp, p, q);\n                if (JS_IsException(sub))\n                    goto exception;\n                if (JS_DefinePropertyValueInt64(ctx, A, lengthA++, sub,\n                                                JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                    goto exception;\n                if (lengthA == lim)\n                    goto done;\n                p = e;\n                if (js_get_length64(ctx, &numberOfCaptures, z))\n                    goto exception;\n                for(i = 1; i < numberOfCaptures; i++) {\n                    sub = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, z, i));\n                    if (JS_IsException(sub))\n                        goto exception;\n                    if (JS_DefinePropertyValueInt64(ctx, A, lengthA++, sub, JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                        goto exception;\n                    if (lengthA == lim)\n                        goto done;\n                }\n                q = p;\n            }\n        }\n    }\nadd_tail:\n    if (p > size)\n        p = size;\n    sub = js_sub_string(ctx, strp, p, size);\n    if (JS_IsException(sub))\n        goto exception;\n    if (JS_DefinePropertyValueInt64(ctx, A, lengthA++, sub, JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n        goto exception;\n    goto done;\nexception:\n    JS_FreeValue(ctx, A);\n    A = JS_EXCEPTION;\ndone:\n    JS_FreeValue(ctx, str);\n    JS_FreeValue(ctx, ctor);\n    JS_FreeValue(ctx, splitter);\n    JS_FreeValue(ctx, flags);\n    JS_FreeValue(ctx, z);    \n    return A;\n}\n\nstatic const JSCFunctionListEntry js_regexp_funcs[] = {\n    JS_CGETSET_DEF(\"[Symbol.species]\", js_get_this, NULL ),\n    //JS_CFUNC_DEF(\"__RegExpExec\", 2, js_regexp___RegExpExec ),\n    //JS_CFUNC_DEF(\"__RegExpDelete\", 2, js_regexp___RegExpDelete ),\n};\n\nstatic const JSCFunctionListEntry js_regexp_proto_funcs[] = {\n    JS_CGETSET_DEF(\"flags\", js_regexp_get_flags, NULL ),\n    JS_CGETSET_DEF(\"source\", js_regexp_get_source, NULL ),\n    JS_CGETSET_MAGIC_DEF(\"global\", js_regexp_get_flag, NULL, 1 ),\n    JS_CGETSET_MAGIC_DEF(\"ignoreCase\", js_regexp_get_flag, NULL, 2 ),\n    JS_CGETSET_MAGIC_DEF(\"multiline\", js_regexp_get_flag, NULL, 4 ),\n    JS_CGETSET_MAGIC_DEF(\"dotAll\", js_regexp_get_flag, NULL, 8 ),\n    JS_CGETSET_MAGIC_DEF(\"unicode\", js_regexp_get_flag, NULL, 16 ),\n    JS_CGETSET_MAGIC_DEF(\"sticky\", js_regexp_get_flag, NULL, 32 ),\n    JS_CFUNC_DEF(\"exec\", 1, js_regexp_exec ),\n    JS_CFUNC_DEF(\"compile\", 2, js_regexp_compile ),\n    JS_CFUNC_DEF(\"test\", 1, js_regexp_test ),\n    JS_CFUNC_DEF(\"toString\", 0, js_regexp_toString ),\n    JS_CFUNC_DEF(\"[Symbol.replace]\", 2, js_regexp_Symbol_replace ),\n    JS_CFUNC_DEF(\"[Symbol.match]\", 1, js_regexp_Symbol_match ),\n    JS_CFUNC_DEF(\"[Symbol.matchAll]\", 1, js_regexp_Symbol_matchAll ),\n    JS_CFUNC_DEF(\"[Symbol.search]\", 1, js_regexp_Symbol_search ),\n    JS_CFUNC_DEF(\"[Symbol.split]\", 2, js_regexp_Symbol_split ),\n    //JS_CGETSET_DEF(\"__source\", js_regexp_get___source, NULL ),\n    //JS_CGETSET_DEF(\"__flags\", js_regexp_get___flags, NULL ),\n};\n\nstatic const JSCFunctionListEntry js_regexp_string_iterator_proto_funcs[] = {\n    JS_ITERATOR_NEXT_DEF(\"next\", 0, js_regexp_string_iterator_next, 0 ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"RegExp String Iterator\", JS_PROP_CONFIGURABLE ),\n};\n\nvoid JS_AddIntrinsicRegExpCompiler(JSContext *ctx)\n{\n    ctx->compile_regexp = js_compile_regexp;\n}\n\nvoid JS_AddIntrinsicRegExp(JSContext *ctx)\n{\n    JSValueConst obj;\n\n    JS_AddIntrinsicRegExpCompiler(ctx);\n\n    ctx->class_proto[JS_CLASS_REGEXP] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_REGEXP], js_regexp_proto_funcs,\n                               countof(js_regexp_proto_funcs));\n    obj = JS_NewGlobalCConstructor(ctx, \"RegExp\", js_regexp_constructor, 2,\n                                   ctx->class_proto[JS_CLASS_REGEXP]);\n    ctx->regexp_ctor = JS_DupValue(ctx, obj);\n    JS_SetPropertyFunctionList(ctx, obj, js_regexp_funcs, countof(js_regexp_funcs));\n\n    ctx->class_proto[JS_CLASS_REGEXP_STRING_ITERATOR] =\n        JS_NewObjectProto(ctx, ctx->iterator_proto);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_REGEXP_STRING_ITERATOR],\n                               js_regexp_string_iterator_proto_funcs,\n                               countof(js_regexp_string_iterator_proto_funcs));\n}\n\n/* JSON */\n\nstatic int json_parse_expect(JSParseState *s, int tok)\n{\n    if (s->token.val != tok) {\n        /* XXX: dump token correctly in all cases */\n        return js_parse_error(s, \"expecting '%c'\", tok);\n    }\n    return json_next_token(s);\n}\n\nstatic JSValue json_parse_value(JSParseState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSValue val = JS_NULL;\n    int ret;\n\n    switch(s->token.val) {\n    case '{':\n        {\n            JSValue prop_val;\n            JSAtom prop_name;\n            \n            if (json_next_token(s))\n                goto fail;\n            val = JS_NewObject(ctx);\n            if (JS_IsException(val))\n                goto fail;\n            if (s->token.val != '}') {\n                for(;;) {\n                    if (s->token.val == TOK_STRING) {\n                        prop_name = JS_ValueToAtom(ctx, s->token.u.str.str);\n                        if (prop_name == JS_ATOM_NULL)\n                            goto fail;\n                    } else if (s->ext_json && s->token.val == TOK_IDENT) {\n                        prop_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n                    } else {\n                        js_parse_error(s, \"expecting property name\");\n                        goto fail;\n                    }\n                    if (json_next_token(s))\n                        goto fail1;\n                    if (json_parse_expect(s, ':'))\n                        goto fail1;\n                    prop_val = json_parse_value(s);\n                    if (JS_IsException(prop_val)) {\n                    fail1:\n                        JS_FreeAtom(ctx, prop_name);\n                        goto fail;\n                    }\n                    ret = JS_DefinePropertyValue(ctx, val, prop_name,\n                                                 prop_val, JS_PROP_C_W_E);\n                    JS_FreeAtom(ctx, prop_name);\n                    if (ret < 0)\n                        goto fail;\n\n                    if (s->token.val != ',')\n                        break;\n                    if (json_next_token(s))\n                        goto fail;\n                    if (s->ext_json && s->token.val == '}')\n                        break;\n                }\n            }\n            if (json_parse_expect(s, '}'))\n                goto fail;\n        }\n        break;\n    case '[':\n        {\n            JSValue el;\n            uint32_t idx;\n\n            if (json_next_token(s))\n                goto fail;\n            val = JS_NewArray(ctx);\n            if (JS_IsException(val))\n                goto fail;\n            if (s->token.val != ']') {\n                idx = 0;\n                for(;;) {\n                    el = json_parse_value(s);\n                    if (JS_IsException(el))\n                        goto fail;\n                    ret = JS_DefinePropertyValueUint32(ctx, val, idx, el, JS_PROP_C_W_E);\n                    if (ret < 0)\n                        goto fail;\n                    if (s->token.val != ',')\n                        break;\n                    if (json_next_token(s))\n                        goto fail;\n                    idx++;\n                    if (s->ext_json && s->token.val == ']')\n                        break;\n                }\n            }\n            if (json_parse_expect(s, ']'))\n                goto fail;\n        }\n        break;\n    case TOK_STRING:\n        val = JS_DupValue(ctx, s->token.u.str.str);\n        if (json_next_token(s))\n            goto fail;\n        break;\n    case TOK_NUMBER:\n        val = s->token.u.num.val;\n        if (json_next_token(s))\n            goto fail;\n        break;\n    case TOK_IDENT:\n        if (s->token.u.ident.atom == JS_ATOM_false ||\n            s->token.u.ident.atom == JS_ATOM_true) {\n            val = JS_NewBool(ctx, (s->token.u.ident.atom == JS_ATOM_true));\n        } else if (s->token.u.ident.atom == JS_ATOM_null) {\n            val = JS_NULL;\n        } else {\n            goto def_token;\n        }\n        if (json_next_token(s))\n            goto fail;\n        break;\n    default:\n    def_token:\n        if (s->token.val == TOK_EOF) {\n            js_parse_error(s, \"unexpected end of input\");\n        } else {\n            js_parse_error(s, \"unexpected token: '%.*s'\",\n                           (int)(s->buf_ptr - s->token.ptr), s->token.ptr);\n        }\n        goto fail;\n    }\n    return val;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nJSValue JS_ParseJSON2(JSContext *ctx, const char *buf, size_t buf_len,\n                      const char *filename, int flags)\n{\n    JSParseState s1, *s = &s1;\n    JSValue val = JS_UNDEFINED;\n\n    js_parse_init(ctx, s, buf, buf_len, filename);\n    s->ext_json = ((flags & JS_PARSE_JSON_EXT) != 0);\n    if (json_next_token(s))\n        goto fail;\n    val = json_parse_value(s);\n    if (JS_IsException(val))\n        goto fail;\n    if (s->token.val != TOK_EOF) {\n        if (js_parse_error(s, \"unexpected data at the end\"))\n            goto fail;\n    }\n    return val;\n fail:\n    JS_FreeValue(ctx, val);\n    free_token(s, &s->token);\n    return JS_EXCEPTION;\n}\n\nJSValue JS_ParseJSON(JSContext *ctx, const char *buf, size_t buf_len,\n                     const char *filename)\n{\n    return JS_ParseJSON2(ctx, buf, buf_len, filename, 0); \n}\n\nstatic JSValue internalize_json_property(JSContext *ctx, JSValueConst holder,\n                                         JSAtom name, JSValueConst reviver)\n{\n    JSValue val, new_el, name_val, res;\n    JSValueConst args[2];\n    int ret, is_array;\n    uint32_t i, len = 0;\n    JSAtom prop;\n    JSPropertyEnum *atoms = NULL;\n\n    if (js_check_stack_overflow(ctx->rt, 0)) {\n        return JS_ThrowStackOverflow(ctx);\n    }\n\n    val = JS_GetProperty(ctx, holder, name);\n    if (JS_IsException(val))\n        return val;\n    if (JS_IsObject(val)) {\n        is_array = JS_IsArray(ctx, val);\n        if (is_array < 0)\n            goto fail;\n        if (is_array) {\n            if (js_get_length32(ctx, &len, val))\n                goto fail;\n        } else {\n            ret = JS_GetOwnPropertyNamesInternal(ctx, &atoms, &len, JS_VALUE_GET_OBJ(val), JS_GPN_ENUM_ONLY | JS_GPN_STRING_MASK);\n            if (ret < 0)\n                goto fail;\n        }\n        for(i = 0; i < len; i++) {\n            if (is_array) {\n                prop = JS_NewAtomUInt32(ctx, i);\n                if (prop == JS_ATOM_NULL)\n                    goto fail;\n            } else {\n                prop = JS_DupAtom(ctx, atoms[i].atom);\n            }\n            new_el = internalize_json_property(ctx, val, prop, reviver);\n            if (JS_IsException(new_el)) {\n                JS_FreeAtom(ctx, prop);\n                goto fail;\n            }\n            if (JS_IsUndefined(new_el)) {\n                ret = JS_DeleteProperty(ctx, val, prop, 0);\n            } else {\n                ret = JS_DefinePropertyValue(ctx, val, prop, new_el, JS_PROP_C_W_E);\n            }\n            JS_FreeAtom(ctx, prop);\n            if (ret < 0)\n                goto fail;\n        }\n    }\n    js_free_prop_enum(ctx, atoms, len);\n    atoms = NULL;\n    name_val = JS_AtomToValue(ctx, name);\n    if (JS_IsException(name_val))\n        goto fail;\n    args[0] = name_val;\n    args[1] = val;\n    res = JS_Call(ctx, reviver, holder, 2, args);\n    JS_FreeValue(ctx, name_val);\n    JS_FreeValue(ctx, val);\n    return res;\n fail:\n    js_free_prop_enum(ctx, atoms, len);\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_json_parse(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    JSValue obj, root;\n    JSValueConst reviver;\n    const char *str;\n    size_t len;\n\n    str = JS_ToCStringLen(ctx, &len, argv[0]);\n    if (!str)\n        return JS_EXCEPTION;\n    obj = JS_ParseJSON(ctx, str, len, \"<input>\");\n    JS_FreeCString(ctx, str);\n    if (JS_IsException(obj))\n        return obj;\n    if (argc > 1 && JS_IsFunction(ctx, argv[1])) {\n        reviver = argv[1];\n        root = JS_NewObject(ctx);\n        if (JS_IsException(root)) {\n            JS_FreeValue(ctx, obj);\n            return JS_EXCEPTION;\n        }\n        if (JS_DefinePropertyValue(ctx, root, JS_ATOM_empty_string, obj,\n                                   JS_PROP_C_W_E) < 0) {\n            JS_FreeValue(ctx, root);\n            return JS_EXCEPTION;\n        }\n        obj = internalize_json_property(ctx, root, JS_ATOM_empty_string,\n                                        reviver);\n        JS_FreeValue(ctx, root);\n    }\n    return obj;\n}\n\ntypedef struct JSONStringifyContext {\n    JSValueConst replacer_func;\n    JSValue stack;\n    JSValue property_list;\n    JSValue gap;\n    JSValue empty;\n    StringBuffer *b;\n} JSONStringifyContext;\n\nstatic JSValue JS_ToQuotedStringFree(JSContext *ctx, JSValue val) {\n    JSValue r = JS_ToQuotedString(ctx, val);\n    JS_FreeValue(ctx, val);\n    return r;\n}\n\nstatic JSValue js_json_check(JSContext *ctx, JSONStringifyContext *jsc,\n                             JSValueConst holder, JSValue val, JSValueConst key)\n{\n    JSValue v;\n    JSValueConst args[2];\n\n    if (JS_IsObject(val)\n#ifdef CONFIG_BIGNUM\n    ||  JS_IsBigInt(ctx, val)   /* XXX: probably useless */\n#endif\n        ) {\n            JSValue f = JS_GetProperty(ctx, val, JS_ATOM_toJSON);\n            if (JS_IsException(f))\n                goto exception;\n            if (JS_IsFunction(ctx, f)) {\n                v = JS_CallFree(ctx, f, val, 1, &key);\n                JS_FreeValue(ctx, val);\n                val = v;\n                if (JS_IsException(val))\n                    goto exception;\n            } else {\n                JS_FreeValue(ctx, f);\n            }\n        }\n\n    if (!JS_IsUndefined(jsc->replacer_func)) {\n        args[0] = key;\n        args[1] = val;\n        v = JS_Call(ctx, jsc->replacer_func, holder, 2, args);\n        JS_FreeValue(ctx, val);\n        val = v;\n        if (JS_IsException(val))\n            goto exception;\n    }\n\n    switch (JS_VALUE_GET_NORM_TAG(val)) {\n    case JS_TAG_OBJECT:\n        if (JS_IsFunction(ctx, val))\n            break;\n    case JS_TAG_STRING:\n    case JS_TAG_INT:\n    case JS_TAG_FLOAT64:\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_FLOAT:\n#endif\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n#endif\n    case JS_TAG_EXCEPTION:\n        return val;\n    default:\n        break;\n    }\n    JS_FreeValue(ctx, val);\n    return JS_UNDEFINED;\n\nexception:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic int js_json_to_str(JSContext *ctx, JSONStringifyContext *jsc,\n                          JSValueConst holder, JSValue val,\n                          JSValueConst indent)\n{\n    JSValue indent1, sep, sep1, tab, v, prop;\n    JSObject *p;\n    int64_t i, len;\n    int cl, ret;\n    BOOL has_content;\n    \n    indent1 = JS_UNDEFINED;\n    sep = JS_UNDEFINED;\n    sep1 = JS_UNDEFINED;\n    tab = JS_UNDEFINED;\n    prop = JS_UNDEFINED;\n\n    switch (JS_VALUE_GET_NORM_TAG(val)) {\n    case JS_TAG_OBJECT:\n        p = JS_VALUE_GET_OBJ(val);\n        cl = p->class_id;\n        if (cl == JS_CLASS_STRING) {\n            val = JS_ToStringFree(ctx, val);\n            if (JS_IsException(val))\n                goto exception;\n            val = JS_ToQuotedStringFree(ctx, val);\n            if (JS_IsException(val))\n                goto exception;\n            return string_buffer_concat_value_free(jsc->b, val);\n        } else if (cl == JS_CLASS_NUMBER) {\n            val = JS_ToNumberFree(ctx, val);\n            if (JS_IsException(val))\n                goto exception;\n            return string_buffer_concat_value_free(jsc->b, val);\n        } else if (cl == JS_CLASS_BOOLEAN) {\n            ret = string_buffer_concat_value(jsc->b, p->u.object_data);\n            JS_FreeValue(ctx, val);\n            return ret;\n        }\n#ifdef CONFIG_BIGNUM\n        else if (cl == JS_CLASS_BIG_FLOAT) {\n            return string_buffer_concat_value_free(jsc->b, val);\n        } else if (cl == JS_CLASS_BIG_INT) {\n            JS_ThrowTypeError(ctx, \"bigint are forbidden in JSON.stringify\");\n            goto exception;\n        }\n#endif\n        v = js_array_includes(ctx, jsc->stack, 1, (JSValueConst *)&val);\n        if (JS_IsException(v))\n            goto exception;\n        if (JS_ToBoolFree(ctx, v)) {\n            JS_ThrowTypeError(ctx, \"circular reference\");\n            goto exception;\n        }\n        indent1 = JS_ConcatString(ctx, JS_DupValue(ctx, indent), JS_DupValue(ctx, jsc->gap));\n        if (JS_IsException(indent1))\n            goto exception;\n        if (!JS_IsEmptyString(jsc->gap)) {\n            sep = JS_ConcatString3(ctx, \"\\n\", JS_DupValue(ctx, indent1), \"\");\n            if (JS_IsException(sep))\n                goto exception;\n            sep1 = JS_NewString(ctx, \" \");\n            if (JS_IsException(sep1))\n                goto exception;\n        } else {\n            sep = JS_DupValue(ctx, jsc->empty);\n            sep1 = JS_DupValue(ctx, jsc->empty);\n        }\n        v = js_array_push(ctx, jsc->stack, 1, (JSValueConst *)&val, 0);\n        if (check_exception_free(ctx, v))\n            goto exception;\n        ret = JS_IsArray(ctx, val);\n        if (ret < 0)\n            goto exception;\n        if (ret) {\n            if (js_get_length64(ctx, &len, val))\n                goto exception;\n            string_buffer_putc8(jsc->b, '[');\n            for(i = 0; i < len; i++) {\n                if (i > 0)\n                    string_buffer_putc8(jsc->b, ',');\n                string_buffer_concat_value(jsc->b, sep);\n                v = JS_GetPropertyInt64(ctx, val, i);\n                if (JS_IsException(v))\n                    goto exception;\n                /* XXX: could do this string conversion only when needed */\n                prop = JS_ToStringFree(ctx, JS_NewInt64(ctx, i));\n                if (JS_IsException(prop))\n                    goto exception;\n                v = js_json_check(ctx, jsc, val, v, prop);\n                JS_FreeValue(ctx, prop);\n                prop = JS_UNDEFINED;\n                if (JS_IsException(v))\n                    goto exception;\n                if (JS_IsUndefined(v))\n                    v = JS_NULL;\n                if (js_json_to_str(ctx, jsc, val, v, indent1))\n                    goto exception;\n            }\n            if (len > 0 && !JS_IsEmptyString(jsc->gap)) {\n                string_buffer_putc8(jsc->b, '\\n');\n                string_buffer_concat_value(jsc->b, indent);\n            }\n            string_buffer_putc8(jsc->b, ']');\n        } else {\n            if (!JS_IsUndefined(jsc->property_list))\n                tab = JS_DupValue(ctx, jsc->property_list);\n            else\n                tab = js_object_keys(ctx, JS_UNDEFINED, 1, (JSValueConst *)&val, JS_ITERATOR_KIND_KEY);\n            if (JS_IsException(tab))\n                goto exception;\n            if (js_get_length64(ctx, &len, tab))\n                goto exception;\n            string_buffer_putc8(jsc->b, '{');\n            has_content = FALSE;\n            for(i = 0; i < len; i++) {\n                JS_FreeValue(ctx, prop);\n                prop = JS_GetPropertyInt64(ctx, tab, i);\n                if (JS_IsException(prop))\n                    goto exception;\n                v = JS_GetPropertyValue(ctx, val, JS_DupValue(ctx, prop));\n                if (JS_IsException(v))\n                    goto exception;\n                v = js_json_check(ctx, jsc, val, v, prop);\n                if (JS_IsException(v))\n                    goto exception;\n                if (!JS_IsUndefined(v)) {\n                    if (has_content)\n                        string_buffer_putc8(jsc->b, ',');\n                    prop = JS_ToQuotedStringFree(ctx, prop);\n                    if (JS_IsException(prop)) {\n                        JS_FreeValue(ctx, v);\n                        goto exception;\n                    }\n                    string_buffer_concat_value(jsc->b, sep);\n                    string_buffer_concat_value(jsc->b, prop);\n                    string_buffer_putc8(jsc->b, ':');\n                    string_buffer_concat_value(jsc->b, sep1);\n                    if (js_json_to_str(ctx, jsc, val, v, indent1))\n                        goto exception;\n                    has_content = TRUE;\n                }\n            }\n            if (has_content && JS_VALUE_GET_STRING(jsc->gap)->len != 0) {\n                string_buffer_putc8(jsc->b, '\\n');\n                string_buffer_concat_value(jsc->b, indent);\n            }\n            string_buffer_putc8(jsc->b, '}');\n        }\n        if (check_exception_free(ctx, js_array_pop(ctx, jsc->stack, 0, NULL, 0)))\n            goto exception;\n        JS_FreeValue(ctx, val);\n        JS_FreeValue(ctx, tab);\n        JS_FreeValue(ctx, sep);\n        JS_FreeValue(ctx, sep1);\n        JS_FreeValue(ctx, indent1);\n        JS_FreeValue(ctx, prop);\n        return 0;\n    case JS_TAG_STRING:\n        val = JS_ToQuotedStringFree(ctx, val);\n        if (JS_IsException(val))\n            goto exception;\n        goto concat_value;\n    case JS_TAG_FLOAT64:\n        if (!isfinite(JS_VALUE_GET_FLOAT64(val))) {\n            val = JS_NULL;\n        }\n        goto concat_value;\n    case JS_TAG_INT:\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_FLOAT:\n#endif\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n    concat_value:\n        return string_buffer_concat_value_free(jsc->b, val);\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n        JS_ThrowTypeError(ctx, \"bigint are forbidden in JSON.stringify\");\n        goto exception;\n#endif\n    default:\n        JS_FreeValue(ctx, val);\n        return 0;\n    }\n    \nexception:\n    JS_FreeValue(ctx, val);\n    JS_FreeValue(ctx, tab);\n    JS_FreeValue(ctx, sep);\n    JS_FreeValue(ctx, sep1);\n    JS_FreeValue(ctx, indent1);\n    JS_FreeValue(ctx, prop);\n    return -1;\n}\n\nJSValue JS_JSONStringify(JSContext *ctx, JSValueConst obj,\n                         JSValueConst replacer, JSValueConst space0)\n{\n    StringBuffer b_s;\n    JSONStringifyContext jsc_s, *jsc = &jsc_s;\n    JSValue val, v, space, ret, wrapper;\n    int res;\n    int64_t i, j, n;\n\n    jsc->replacer_func = JS_UNDEFINED;\n    jsc->stack = JS_UNDEFINED;\n    jsc->property_list = JS_UNDEFINED;\n    jsc->gap = JS_UNDEFINED;\n    jsc->b = &b_s;\n    jsc->empty = JS_AtomToString(ctx, JS_ATOM_empty_string);\n    ret = JS_UNDEFINED;\n    wrapper = JS_UNDEFINED;\n\n    string_buffer_init(ctx, jsc->b, 0);\n    jsc->stack = JS_NewArray(ctx);\n    if (JS_IsException(jsc->stack))\n        goto exception;\n    if (JS_IsFunction(ctx, replacer)) {\n        jsc->replacer_func = replacer;\n    } else {\n        res = JS_IsArray(ctx, replacer);\n        if (res < 0)\n            goto exception;\n        if (res) {\n            /* XXX: enumeration is not fully correct */\n            jsc->property_list = JS_NewArray(ctx);\n            if (JS_IsException(jsc->property_list))\n                goto exception;\n            if (js_get_length64(ctx, &n, replacer))\n                goto exception;\n            for (i = j = 0; i < n; i++) {\n                JSValue present;\n                v = JS_GetPropertyInt64(ctx, replacer, i);\n                if (JS_IsException(v))\n                    goto exception;\n                if (JS_IsObject(v)) {\n                    JSObject *p = JS_VALUE_GET_OBJ(v);\n                    if (p->class_id == JS_CLASS_STRING ||\n                        p->class_id == JS_CLASS_NUMBER) {\n                        v = JS_ToStringFree(ctx, v);\n                        if (JS_IsException(v))\n                            goto exception;\n                    } else {\n                        JS_FreeValue(ctx, v);\n                        continue;\n                    }\n                } else if (JS_IsNumber(v)) {\n                    v = JS_ToStringFree(ctx, v);\n                    if (JS_IsException(v))\n                        goto exception;\n                } else if (!JS_IsString(v)) {\n                    JS_FreeValue(ctx, v);\n                    continue;\n                }\n                present = js_array_includes(ctx, jsc->property_list,\n                                            1, (JSValueConst *)&v);\n                if (JS_IsException(present)) {\n                    JS_FreeValue(ctx, v);\n                    goto exception;\n                }\n                if (!JS_ToBoolFree(ctx, present)) {\n                    JS_SetPropertyInt64(ctx, jsc->property_list, j++, v);\n                } else {\n                    JS_FreeValue(ctx, v);\n                }\n            }\n        }\n    }\n    space = JS_DupValue(ctx, space0);\n    if (JS_IsObject(space)) {\n        JSObject *p = JS_VALUE_GET_OBJ(space);\n        if (p->class_id == JS_CLASS_NUMBER) {\n            space = JS_ToNumberFree(ctx, space);\n        } else if (p->class_id == JS_CLASS_STRING) {\n            space = JS_ToStringFree(ctx, space);\n        }\n        if (JS_IsException(space)) {\n            JS_FreeValue(ctx, space);\n            goto exception;\n        }\n    }\n    if (JS_IsNumber(space)) {\n        int n;\n        if (JS_ToInt32Clamp(ctx, &n, space, 0, 10, 0))\n            goto exception;\n        jsc->gap = JS_NewStringLen(ctx, \"          \", n);\n    } else if (JS_IsString(space)) {\n        JSString *p = JS_VALUE_GET_STRING(space);\n        jsc->gap = js_sub_string(ctx, p, 0, min_int(p->len, 10));\n    } else {\n        jsc->gap = JS_DupValue(ctx, jsc->empty);\n    }\n    JS_FreeValue(ctx, space);\n    if (JS_IsException(jsc->gap))\n        goto exception;\n    wrapper = JS_NewObject(ctx);\n    if (JS_IsException(wrapper))\n        goto exception;\n    if (JS_DefinePropertyValue(ctx, wrapper, JS_ATOM_empty_string,\n                               JS_DupValue(ctx, obj), JS_PROP_C_W_E) < 0)\n        goto exception;\n    val = JS_DupValue(ctx, obj);\n                           \n    val = js_json_check(ctx, jsc, wrapper, val, jsc->empty);\n    if (JS_IsException(val))\n        goto exception;\n    if (JS_IsUndefined(val)) {\n        ret = JS_UNDEFINED;\n        goto done1;\n    }\n    if (js_json_to_str(ctx, jsc, wrapper, val, jsc->empty))\n        goto exception;\n\n    ret = string_buffer_end(jsc->b);\n    goto done;\n\nexception:\n    ret = JS_EXCEPTION;\ndone1:\n    string_buffer_free(jsc->b);\ndone:\n    JS_FreeValue(ctx, wrapper);\n    JS_FreeValue(ctx, jsc->empty);\n    JS_FreeValue(ctx, jsc->gap);\n    JS_FreeValue(ctx, jsc->property_list);\n    JS_FreeValue(ctx, jsc->stack);\n    return ret;\n}\n\nstatic JSValue js_json_stringify(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    // stringify(val, replacer, space)\n    return JS_JSONStringify(ctx, argv[0], argv[1], argv[2]);\n}\n\nstatic const JSCFunctionListEntry js_json_funcs[] = {\n    JS_CFUNC_DEF(\"parse\", 2, js_json_parse ),\n    JS_CFUNC_DEF(\"stringify\", 3, js_json_stringify ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"JSON\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_json_obj[] = {\n    JS_OBJECT_DEF(\"JSON\", js_json_funcs, countof(js_json_funcs), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),\n};\n\nvoid JS_AddIntrinsicJSON(JSContext *ctx)\n{\n    /* add JSON as autoinit object */\n    JS_SetPropertyFunctionList(ctx, ctx->global_obj, js_json_obj, countof(js_json_obj));\n}\n\n/* Reflect */\n\nstatic JSValue js_reflect_apply(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    return js_function_apply(ctx, argv[0], max_int(0, argc - 1), argv + 1, 2);\n}\n\nstatic JSValue js_reflect_construct(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSValueConst func, array_arg, new_target;\n    JSValue *tab, ret;\n    uint32_t len;\n\n    func = argv[0];\n    array_arg = argv[1];\n    if (argc > 2) {\n        new_target = argv[2];\n        if (!JS_IsConstructor(ctx, new_target))\n            return JS_ThrowTypeError(ctx, \"not a constructor\");\n    } else {\n        new_target = func;\n    }\n    tab = build_arg_list(ctx, &len, array_arg);\n    if (!tab)\n        return JS_EXCEPTION;\n    ret = JS_CallConstructor2(ctx, func, new_target, len, (JSValueConst *)tab);\n    free_arg_list(ctx, tab, len);\n    return ret;\n}\n\nstatic JSValue js_reflect_deleteProperty(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    JSValueConst obj;\n    JSAtom atom;\n    int ret;\n\n    obj = argv[0];\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    atom = JS_ValueToAtom(ctx, argv[1]);\n    if (unlikely(atom == JS_ATOM_NULL))\n        return JS_EXCEPTION;\n    ret = JS_DeleteProperty(ctx, obj, atom, 0);\n    JS_FreeAtom(ctx, atom);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_reflect_get(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    JSValueConst obj, prop, receiver;\n    JSAtom atom;\n    JSValue ret;\n\n    obj = argv[0];\n    prop = argv[1];\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    if (argc > 2)\n        receiver = argv[2];\n    else\n        receiver = obj;\n    atom = JS_ValueToAtom(ctx, prop);\n    if (unlikely(atom == JS_ATOM_NULL))\n        return JS_EXCEPTION;\n    ret = JS_GetPropertyInternal(ctx, obj, atom, receiver, FALSE);\n    JS_FreeAtom(ctx, atom);\n    return ret;\n}\n\nstatic JSValue js_reflect_has(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    JSValueConst obj, prop;\n    JSAtom atom;\n    int ret;\n\n    obj = argv[0];\n    prop = argv[1];\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    atom = JS_ValueToAtom(ctx, prop);\n    if (unlikely(atom == JS_ATOM_NULL))\n        return JS_EXCEPTION;\n    ret = JS_HasProperty(ctx, obj, atom);\n    JS_FreeAtom(ctx, atom);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_reflect_set(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    JSValueConst obj, prop, val, receiver;\n    int ret;\n    JSAtom atom;\n\n    obj = argv[0];\n    prop = argv[1];\n    val = argv[2];\n    if (argc > 3)\n        receiver = argv[3];\n    else\n        receiver = obj;\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    atom = JS_ValueToAtom(ctx, prop);\n    if (unlikely(atom == JS_ATOM_NULL))\n        return JS_EXCEPTION;\n    ret = JS_SetPropertyGeneric(ctx, obj, atom,\n                                JS_DupValue(ctx, val), receiver, 0);\n    JS_FreeAtom(ctx, atom);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_reflect_setPrototypeOf(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    int ret;\n    ret = JS_SetPrototypeInternal(ctx, argv[0], argv[1], FALSE);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_reflect_ownKeys(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    if (JS_VALUE_GET_TAG(argv[0]) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    return JS_GetOwnPropertyNames2(ctx, argv[0],\n                                   JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK,\n                                   JS_ITERATOR_KIND_KEY);\n}\n\nstatic const JSCFunctionListEntry js_reflect_funcs[] = {\n    JS_CFUNC_DEF(\"apply\", 3, js_reflect_apply ),\n    JS_CFUNC_DEF(\"construct\", 2, js_reflect_construct ),\n    JS_CFUNC_MAGIC_DEF(\"defineProperty\", 3, js_object_defineProperty, 1 ),\n    JS_CFUNC_DEF(\"deleteProperty\", 2, js_reflect_deleteProperty ),\n    JS_CFUNC_DEF(\"get\", 2, js_reflect_get ),\n    JS_CFUNC_MAGIC_DEF(\"getOwnPropertyDescriptor\", 2, js_object_getOwnPropertyDescriptor, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"getPrototypeOf\", 1, js_object_getPrototypeOf, 1 ),\n    JS_CFUNC_DEF(\"has\", 2, js_reflect_has ),\n    JS_CFUNC_MAGIC_DEF(\"isExtensible\", 1, js_object_isExtensible, 1 ),\n    JS_CFUNC_DEF(\"ownKeys\", 1, js_reflect_ownKeys ),\n    JS_CFUNC_MAGIC_DEF(\"preventExtensions\", 1, js_object_preventExtensions, 1 ),\n    JS_CFUNC_DEF(\"set\", 3, js_reflect_set ),\n    JS_CFUNC_DEF(\"setPrototypeOf\", 2, js_reflect_setPrototypeOf ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Reflect\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_reflect_obj[] = {\n    JS_OBJECT_DEF(\"Reflect\", js_reflect_funcs, countof(js_reflect_funcs), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),\n};\n\n/* Proxy */\n\nstatic void js_proxy_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSProxyData *s = JS_GetOpaque(val, JS_CLASS_PROXY);\n    if (s) {\n        JS_FreeValueRT(rt, s->target);\n        JS_FreeValueRT(rt, s->handler);\n        js_free_rt(rt, s);\n    }\n}\n\nstatic void js_proxy_mark(JSRuntime *rt, JSValueConst val,\n                          JS_MarkFunc *mark_func)\n{\n    JSProxyData *s = JS_GetOpaque(val, JS_CLASS_PROXY);\n    if (s) {\n        JS_MarkValue(rt, s->target, mark_func);\n        JS_MarkValue(rt, s->handler, mark_func);\n    }\n}\n\nstatic JSValue JS_ThrowTypeErrorRevokedProxy(JSContext *ctx)\n{\n    return JS_ThrowTypeError(ctx, \"revoked proxy\");\n}\n\nstatic JSProxyData *get_proxy_method(JSContext *ctx, JSValue *pmethod,\n                                     JSValueConst obj, JSAtom name)\n{\n    JSProxyData *s = JS_GetOpaque(obj, JS_CLASS_PROXY);\n    JSValue method;\n\n    /* safer to test recursion in all proxy methods */\n    if (js_check_stack_overflow(ctx->rt, 0)) {\n        JS_ThrowStackOverflow(ctx);\n        return NULL;\n    }\n    \n    /* 's' should never be NULL */\n    if (s->is_revoked) {\n        JS_ThrowTypeErrorRevokedProxy(ctx);\n        return NULL;\n    }\n    method = JS_GetProperty(ctx, s->handler, name);\n    if (JS_IsException(method))\n        return NULL;\n    if (JS_IsNull(method))\n        method = JS_UNDEFINED;\n    *pmethod = method;\n    return s;\n}\n\nstatic JSValue js_proxy_getPrototypeOf(JSContext *ctx, JSValueConst obj)\n{\n    JSProxyData *s;\n    JSValue method, ret, proto1;\n    int res;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_getPrototypeOf);\n    if (!s)\n        return JS_EXCEPTION;\n    if (JS_IsUndefined(method))\n        return JS_GetPrototype(ctx, s->target);\n    ret = JS_CallFree(ctx, method, s->handler, 1, (JSValueConst *)&s->target);\n    if (JS_IsException(ret))\n        return ret;\n    if (JS_VALUE_GET_TAG(ret) != JS_TAG_NULL &&\n        JS_VALUE_GET_TAG(ret) != JS_TAG_OBJECT) {\n        goto fail;\n    }\n    res = JS_IsExtensible(ctx, s->target);\n    if (res < 0) {\n        JS_FreeValue(ctx, ret);\n        return JS_EXCEPTION;\n    }\n    if (!res) {\n        /* check invariant */\n        proto1 = JS_GetPrototype(ctx, s->target);\n        if (JS_IsException(proto1)) {\n            JS_FreeValue(ctx, ret);\n            return JS_EXCEPTION;\n        }\n        if (JS_VALUE_GET_OBJ(proto1) != JS_VALUE_GET_OBJ(ret)) {\n            JS_FreeValue(ctx, proto1);\n        fail:\n            JS_FreeValue(ctx, ret);\n            return JS_ThrowTypeError(ctx, \"proxy: inconsistent prototype\");\n        }\n        JS_FreeValue(ctx, proto1);\n    }\n    return ret;\n}\n\nstatic int js_proxy_setPrototypeOf(JSContext *ctx, JSValueConst obj,\n                                   JSValueConst proto_val, BOOL throw_flag)\n{\n    JSProxyData *s;\n    JSValue method, ret, proto1;\n    JSValueConst args[2];\n    BOOL res;\n    int res2;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_setPrototypeOf);\n    if (!s)\n        return -1;\n    if (JS_IsUndefined(method))\n        return JS_SetPrototypeInternal(ctx, s->target, proto_val, throw_flag);\n    args[0] = s->target;\n    args[1] = proto_val;\n    ret = JS_CallFree(ctx, method, s->handler, 2, args);\n    if (JS_IsException(ret))\n        return -1;\n    res = JS_ToBoolFree(ctx, ret);\n    if (!res) {\n        if (throw_flag) {\n            JS_ThrowTypeError(ctx, \"proxy: bad prototype\");\n            return -1;\n        } else {\n            return FALSE;\n        }\n    }\n    res2 = JS_IsExtensible(ctx, s->target);\n    if (res2 < 0)\n        return -1;\n    if (!res2) {\n        proto1 = JS_GetPrototype(ctx, s->target);\n        if (JS_IsException(proto1))\n            return -1;\n        if (JS_VALUE_GET_OBJ(proto_val) != JS_VALUE_GET_OBJ(proto1)) {\n            JS_FreeValue(ctx, proto1);\n            JS_ThrowTypeError(ctx, \"proxy: inconsistent prototype\");\n            return -1;\n        }\n        JS_FreeValue(ctx, proto1);\n    }\n    return TRUE;\n}\n\nstatic int js_proxy_isExtensible(JSContext *ctx, JSValueConst obj)\n{\n    JSProxyData *s;\n    JSValue method, ret;\n    BOOL res;\n    int res2;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_isExtensible);\n    if (!s)\n        return -1;\n    if (JS_IsUndefined(method))\n        return JS_IsExtensible(ctx, s->target);\n    ret = JS_CallFree(ctx, method, s->handler, 1, (JSValueConst *)&s->target);\n    if (JS_IsException(ret))\n        return -1;\n    res = JS_ToBoolFree(ctx, ret);\n    res2 = JS_IsExtensible(ctx, s->target);\n    if (res2 < 0)\n        return res2;\n    if (res != res2) {\n        JS_ThrowTypeError(ctx, \"proxy: inconsistent isExtensible\");\n        return -1;\n    }\n    return res;\n}\n\nstatic int js_proxy_preventExtensions(JSContext *ctx, JSValueConst obj)\n{\n    JSProxyData *s;\n    JSValue method, ret;\n    BOOL res;\n    int res2;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_preventExtensions);\n    if (!s)\n        return -1;\n    if (JS_IsUndefined(method))\n        return JS_PreventExtensions(ctx, s->target);\n    ret = JS_CallFree(ctx, method, s->handler, 1, (JSValueConst *)&s->target);\n    if (JS_IsException(ret))\n        return -1;\n    res = JS_ToBoolFree(ctx, ret);\n    if (res) {\n        res2 = JS_IsExtensible(ctx, s->target);\n        if (res2 < 0)\n            return res2;\n        if (res2) {\n            JS_ThrowTypeError(ctx, \"proxy: inconsistent preventExtensions\");\n            return -1;\n        }\n    }\n    return res;\n}\n\nstatic int js_proxy_has(JSContext *ctx, JSValueConst obj, JSAtom atom)\n{\n    JSProxyData *s;\n    JSValue method, ret1, atom_val;\n    int ret, res;\n    JSObject *p;\n    JSValueConst args[2];\n    BOOL res2;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_has);\n    if (!s)\n        return -1;\n    if (JS_IsUndefined(method))\n        return JS_HasProperty(ctx, s->target, atom);\n    atom_val = JS_AtomToValue(ctx, atom);\n    if (JS_IsException(atom_val)) {\n        JS_FreeValue(ctx, method);\n        return -1;\n    }\n    args[0] = s->target;\n    args[1] = atom_val;\n    ret1 = JS_CallFree(ctx, method, s->handler, 2, args);\n    JS_FreeValue(ctx, atom_val);\n    if (JS_IsException(ret1))\n        return -1;\n    ret = JS_ToBoolFree(ctx, ret1);\n    if (!ret) {\n        JSPropertyDescriptor desc;\n        p = JS_VALUE_GET_OBJ(s->target);\n        res = JS_GetOwnPropertyInternal(ctx, &desc, p, atom);\n        if (res < 0)\n            return -1;\n        if (res) {\n            res2 = !(desc.flags & JS_PROP_CONFIGURABLE);\n            js_free_desc(ctx, &desc);\n            if (res2 || !p->extensible) {\n                JS_ThrowTypeError(ctx, \"proxy: inconsistent has\");\n                return -1;\n            }\n        }\n    }\n    return ret;\n}\n\nstatic JSValue js_proxy_get(JSContext *ctx, JSValueConst obj, JSAtom atom,\n                            JSValueConst receiver)\n{\n    JSProxyData *s;\n    JSValue method, ret, atom_val;\n    int res;\n    JSValueConst args[3];\n    JSPropertyDescriptor desc;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_get);\n    if (!s)\n        return JS_EXCEPTION;\n    /* Note: recursion is possible thru the prototype of s->target */\n    if (JS_IsUndefined(method))\n        return JS_GetPropertyInternal(ctx, s->target, atom, receiver, FALSE);\n    atom_val = JS_AtomToValue(ctx, atom);\n    if (JS_IsException(atom_val)) {\n        JS_FreeValue(ctx, method);\n        return JS_EXCEPTION;\n    }\n    args[0] = s->target;\n    args[1] = atom_val;\n    args[2] = receiver;\n    ret = JS_CallFree(ctx, method, s->handler, 3, args);\n    JS_FreeValue(ctx, atom_val);\n    if (JS_IsException(ret))\n        return JS_EXCEPTION;\n    res = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(s->target), atom);\n    if (res < 0)\n        return JS_EXCEPTION;\n    if (res) {\n        if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) == 0) {\n            if (!js_same_value(ctx, desc.value, ret)) {\n                goto fail;\n            }\n        } else if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE)) == JS_PROP_GETSET) {\n            if (JS_IsUndefined(desc.getter) && !JS_IsUndefined(ret)) {\n            fail:\n                js_free_desc(ctx, &desc);\n                JS_FreeValue(ctx, ret);\n                return JS_ThrowTypeError(ctx, \"proxy: inconsistent get\");\n            }\n        }\n        js_free_desc(ctx, &desc);\n    }\n    return ret;\n}\n\nstatic int js_proxy_set(JSContext *ctx, JSValueConst obj, JSAtom atom,\n                        JSValueConst value, JSValueConst receiver, int flags)\n{\n    JSProxyData *s;\n    JSValue method, ret1, atom_val;\n    int ret, res;\n    JSValueConst args[4];\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_set);\n    if (!s)\n        return -1;\n    if (JS_IsUndefined(method)) {\n        return JS_SetPropertyGeneric(ctx, s->target, atom,\n                                     JS_DupValue(ctx, value), receiver,\n                                     flags);\n    }\n    atom_val = JS_AtomToValue(ctx, atom);\n    if (JS_IsException(atom_val)) {\n        JS_FreeValue(ctx, method);\n        return -1;\n    }\n    args[0] = s->target;\n    args[1] = atom_val;\n    args[2] = value;\n    args[3] = receiver;\n    ret1 = JS_CallFree(ctx, method, s->handler, 4, args);\n    JS_FreeValue(ctx, atom_val);\n    if (JS_IsException(ret1))\n        return -1;\n    ret = JS_ToBoolFree(ctx, ret1);\n    if (ret) {\n        JSPropertyDescriptor desc;\n        res = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(s->target), atom);\n        if (res < 0)\n            return -1;\n        if (res) {\n            if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) == 0) {\n                if (!js_same_value(ctx, desc.value, value)) {\n                    goto fail;\n                }\n            } else if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE)) == JS_PROP_GETSET && JS_IsUndefined(desc.setter)) {\n                fail:\n                    js_free_desc(ctx, &desc);\n                    JS_ThrowTypeError(ctx, \"proxy: inconsistent set\");\n                    return -1;\n            }\n            js_free_desc(ctx, &desc);\n        }\n    } else {\n        if ((flags & JS_PROP_THROW) ||\n            ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) {\n            JS_ThrowTypeError(ctx, \"proxy: cannot set property\");\n            return -1;\n        }\n    }\n    return ret;\n}\n\nstatic JSValue js_create_desc(JSContext *ctx, JSValueConst val,\n                              JSValueConst getter, JSValueConst setter,\n                              int flags)\n{\n    JSValue ret;\n    ret = JS_NewObject(ctx);\n    if (JS_IsException(ret))\n        return ret;\n    if (flags & JS_PROP_HAS_GET) {\n        JS_DefinePropertyValue(ctx, ret, JS_ATOM_get, JS_DupValue(ctx, getter),\n                               JS_PROP_C_W_E);\n    }\n    if (flags & JS_PROP_HAS_SET) {\n        JS_DefinePropertyValue(ctx, ret, JS_ATOM_set, JS_DupValue(ctx, setter),\n                               JS_PROP_C_W_E);\n    }\n    if (flags & JS_PROP_HAS_VALUE) {\n        JS_DefinePropertyValue(ctx, ret, JS_ATOM_value, JS_DupValue(ctx, val),\n                               JS_PROP_C_W_E);\n    }\n    if (flags & JS_PROP_HAS_WRITABLE) {\n        JS_DefinePropertyValue(ctx, ret, JS_ATOM_writable,\n                               JS_NewBool(ctx, (flags & JS_PROP_WRITABLE) != 0),\n                               JS_PROP_C_W_E);\n    }\n    if (flags & JS_PROP_HAS_ENUMERABLE) {\n        JS_DefinePropertyValue(ctx, ret, JS_ATOM_enumerable,\n                               JS_NewBool(ctx, (flags & JS_PROP_ENUMERABLE) != 0),\n                               JS_PROP_C_W_E);\n    }\n    if (flags & JS_PROP_HAS_CONFIGURABLE) {\n        JS_DefinePropertyValue(ctx, ret, JS_ATOM_configurable,\n                               JS_NewBool(ctx, (flags & JS_PROP_CONFIGURABLE) != 0),\n                               JS_PROP_C_W_E);\n    }\n    return ret;\n}\n\nstatic int js_proxy_get_own_property(JSContext *ctx, JSPropertyDescriptor *pdesc,\n                                     JSValueConst obj, JSAtom prop)\n{\n    JSProxyData *s;\n    JSValue method, trap_result_obj, prop_val;\n    int res, target_desc_ret, ret;\n    JSObject *p;\n    JSValueConst args[2];\n    JSPropertyDescriptor result_desc, target_desc;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_getOwnPropertyDescriptor);\n    if (!s)\n        return -1;\n    p = JS_VALUE_GET_OBJ(s->target);\n    if (JS_IsUndefined(method)) {\n        return JS_GetOwnPropertyInternal(ctx, pdesc, p, prop);\n    }\n    prop_val = JS_AtomToValue(ctx, prop);\n    if (JS_IsException(prop_val)) {\n        JS_FreeValue(ctx, method);\n        return -1;\n    }\n    args[0] = s->target;\n    args[1] = prop_val;\n    trap_result_obj = JS_CallFree(ctx, method, s->handler, 2, args);\n    JS_FreeValue(ctx, prop_val);\n    if (JS_IsException(trap_result_obj))\n        return -1;\n    if (!JS_IsObject(trap_result_obj) && !JS_IsUndefined(trap_result_obj)) {\n        JS_FreeValue(ctx, trap_result_obj);\n        goto fail;\n    }\n    target_desc_ret = JS_GetOwnPropertyInternal(ctx, &target_desc, p, prop);\n    if (target_desc_ret < 0) {\n        JS_FreeValue(ctx, trap_result_obj);\n        return -1;\n    }\n    if (target_desc_ret)\n        js_free_desc(ctx, &target_desc);\n    if (JS_IsUndefined(trap_result_obj)) {\n        if (target_desc_ret) {\n            if (!(target_desc.flags & JS_PROP_CONFIGURABLE) || !p->extensible)\n                goto fail;\n        }\n        ret = FALSE;\n    } else {\n        int flags1, extensible_target;\n        extensible_target = JS_IsExtensible(ctx, s->target);\n        if (extensible_target < 0) {\n            JS_FreeValue(ctx, trap_result_obj);\n            return -1;\n        }\n        res = js_obj_to_desc(ctx, &result_desc, trap_result_obj);\n        JS_FreeValue(ctx, trap_result_obj);\n        if (res < 0)\n            return -1;\n        \n        if (target_desc_ret) {\n            /* convert result_desc.flags to defineProperty flags */\n            flags1 = result_desc.flags | JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_ENUMERABLE;\n            if (result_desc.flags & JS_PROP_GETSET)\n                flags1 |= JS_PROP_HAS_GET | JS_PROP_HAS_SET;\n            else\n                flags1 |= JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE;\n            /* XXX: not complete check: need to compare value &\n               getter/setter as in defineproperty */\n            if (!check_define_prop_flags(target_desc.flags, flags1))\n                goto fail1;\n        } else {\n            if (!extensible_target)\n                goto fail1;\n        }\n        if (!(result_desc.flags & JS_PROP_CONFIGURABLE)) {\n            if (!target_desc_ret || (target_desc.flags & JS_PROP_CONFIGURABLE))\n                goto fail1;\n            if ((result_desc.flags &\n                 (JS_PROP_GETSET | JS_PROP_WRITABLE)) == 0 &&\n                target_desc_ret &&\n                (target_desc.flags & JS_PROP_WRITABLE) != 0) {\n                /* proxy-missing-checks */\n            fail1:\n                js_free_desc(ctx, &result_desc);\n            fail:\n                JS_ThrowTypeError(ctx, \"proxy: inconsistent getOwnPropertyDescriptor\");\n                return -1;\n            }\n        }\n        ret = TRUE;\n        if (pdesc) {\n            *pdesc = result_desc;\n        } else {\n            js_free_desc(ctx, &result_desc);\n        }\n    }\n    return ret;\n}\n\nstatic int js_proxy_define_own_property(JSContext *ctx, JSValueConst obj,\n                                        JSAtom prop, JSValueConst val,\n                                        JSValueConst getter, JSValueConst setter,\n                                        int flags)\n{\n    JSProxyData *s;\n    JSValue method, ret1, prop_val, desc_val;\n    int res, ret;\n    JSObject *p;\n    JSValueConst args[3];\n    JSPropertyDescriptor desc;\n    BOOL setting_not_configurable;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_defineProperty);\n    if (!s)\n        return -1;\n    if (JS_IsUndefined(method)) {\n        return JS_DefineProperty(ctx, s->target, prop, val, getter, setter, flags);\n    }\n    prop_val = JS_AtomToValue(ctx, prop);\n    if (JS_IsException(prop_val)) {\n        JS_FreeValue(ctx, method);\n        return -1;\n    }\n    desc_val = js_create_desc(ctx, val, getter, setter, flags);\n    if (JS_IsException(desc_val)) {\n        JS_FreeValue(ctx, prop_val);\n        JS_FreeValue(ctx, method);\n        return -1;\n    }\n    args[0] = s->target;\n    args[1] = prop_val;\n    args[2] = desc_val;\n    ret1 = JS_CallFree(ctx, method, s->handler, 3, args);\n    JS_FreeValue(ctx, prop_val);\n    JS_FreeValue(ctx, desc_val);\n    if (JS_IsException(ret1))\n        return -1;\n    ret = JS_ToBoolFree(ctx, ret1);\n    if (!ret) {\n        if (flags & JS_PROP_THROW) {\n            JS_ThrowTypeError(ctx, \"proxy: defineProperty exception\");\n            return -1;\n        } else {\n            return 0;\n        }\n    }\n    p = JS_VALUE_GET_OBJ(s->target);\n    res = JS_GetOwnPropertyInternal(ctx, &desc, p, prop);\n    if (res < 0)\n        return -1;\n    setting_not_configurable = ((flags & (JS_PROP_HAS_CONFIGURABLE |\n                                          JS_PROP_CONFIGURABLE)) ==\n                                JS_PROP_HAS_CONFIGURABLE);\n    if (!res) {\n        if (!p->extensible || setting_not_configurable)\n            goto fail;\n    } else {\n        if (!check_define_prop_flags(desc.flags, flags) ||\n            ((desc.flags & JS_PROP_CONFIGURABLE) && setting_not_configurable)) {\n            goto fail1;\n        }\n        if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {\n            if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE)) ==\n                JS_PROP_GETSET) {\n                if ((flags & JS_PROP_HAS_GET) &&\n                    !js_same_value(ctx, getter, desc.getter)) {\n                    goto fail1;\n                }\n                if ((flags & JS_PROP_HAS_SET) &&\n                    !js_same_value(ctx, setter, desc.setter)) {\n                    goto fail1;\n                }\n            }\n        } else if (flags & JS_PROP_HAS_VALUE) {\n            if ((desc.flags & (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) ==\n                JS_PROP_WRITABLE && !(flags & JS_PROP_WRITABLE)) {\n                /* missing-proxy-check feature */\n                goto fail1;\n            } else if ((desc.flags & (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) == 0 &&\n                !js_same_value(ctx, val, desc.value)) {\n                goto fail1;\n            }\n        }\n        if (flags & JS_PROP_HAS_WRITABLE) {\n            if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE |\n                               JS_PROP_WRITABLE)) == JS_PROP_WRITABLE) {\n                /* proxy-missing-checks */\n            fail1:\n                js_free_desc(ctx, &desc);\n            fail:\n                JS_ThrowTypeError(ctx, \"proxy: inconsistent defineProperty\");\n                return -1;\n            }\n        }\n        js_free_desc(ctx, &desc);\n    }\n    return 1;\n}\n\nstatic int js_proxy_delete_property(JSContext *ctx, JSValueConst obj,\n                                    JSAtom atom)\n{\n    JSProxyData *s;\n    JSValue method, ret, atom_val;\n    int res, res2, is_extensible;\n    JSValueConst args[2];\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_deleteProperty);\n    if (!s)\n        return -1;\n    if (JS_IsUndefined(method)) {\n        return JS_DeleteProperty(ctx, s->target, atom, 0);\n    }\n    atom_val = JS_AtomToValue(ctx, atom);;\n    if (JS_IsException(atom_val)) {\n        JS_FreeValue(ctx, method);\n        return -1;\n    }\n    args[0] = s->target;\n    args[1] = atom_val;\n    ret = JS_CallFree(ctx, method, s->handler, 2, args);\n    JS_FreeValue(ctx, atom_val);\n    if (JS_IsException(ret))\n        return -1;\n    res = JS_ToBoolFree(ctx, ret);\n    if (res) {\n        JSPropertyDescriptor desc;\n        res2 = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(s->target), atom);\n        if (res2 < 0)\n            return -1;\n        if (res2) {\n            if (!(desc.flags & JS_PROP_CONFIGURABLE))\n                goto fail;\n            is_extensible = JS_IsExtensible(ctx, s->target);\n            if (is_extensible < 0)\n                goto fail1;\n            if (!is_extensible) {\n                /* proxy-missing-checks */\n            fail:\n                JS_ThrowTypeError(ctx, \"proxy: inconsistent deleteProperty\");\n            fail1:\n                js_free_desc(ctx, &desc);\n                return -1;\n            }\n            js_free_desc(ctx, &desc);\n        }\n    }\n    return res;\n}\n\n/* return the index of the property or -1 if not found */\nstatic int find_prop_key(const JSPropertyEnum *tab, int n, JSAtom atom)\n{\n    int i;\n    for(i = 0; i < n; i++) {\n        if (tab[i].atom == atom)\n            return i;\n    }\n    return -1;\n}\n\nstatic int js_proxy_get_own_property_names(JSContext *ctx,\n                                           JSPropertyEnum **ptab,\n                                           uint32_t *plen,\n                                           JSValueConst obj)\n{\n    JSProxyData *s;\n    JSValue method, prop_array, val;\n    uint32_t len, i, len2;\n    JSPropertyEnum *tab, *tab2;\n    JSAtom atom;\n    JSPropertyDescriptor desc;\n    int res, is_extensible, idx;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_ownKeys);\n    if (!s)\n        return -1;\n    if (JS_IsUndefined(method)) {\n        return JS_GetOwnPropertyNamesInternal(ctx, ptab, plen,\n                                      JS_VALUE_GET_OBJ(s->target),\n                                      JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK);\n    }\n    prop_array = JS_CallFree(ctx, method, s->handler, 1, (JSValueConst *)&s->target);\n    if (JS_IsException(prop_array))\n        return -1;\n    tab = NULL;\n    len = 0;\n    tab2 = NULL;\n    len2 = 0;\n    if (js_get_length32(ctx, &len, prop_array))\n        goto fail;\n    if (len > 0) {\n        tab = js_mallocz(ctx, sizeof(tab[0]) * len);\n        if (!tab)\n            goto fail;\n    }\n    for(i = 0; i < len; i++) {\n        val = JS_GetPropertyUint32(ctx, prop_array, i);\n        if (JS_IsException(val))\n            goto fail;\n        if (!JS_IsString(val) && !JS_IsSymbol(val)) {\n            JS_FreeValue(ctx, val);\n            JS_ThrowTypeError(ctx, \"proxy: properties must be strings or symbols\");\n            goto fail;\n        }\n        atom = JS_ValueToAtom(ctx, val);\n        JS_FreeValue(ctx, val);\n        if (atom == JS_ATOM_NULL)\n            goto fail;\n        tab[i].atom = atom;\n        tab[i].is_enumerable = FALSE; /* XXX: redundant? */\n    }\n\n    /* check duplicate properties (XXX: inefficient, could store the\n     * properties an a temporary object to use the hash) */\n    for(i = 1; i < len; i++) {\n        if (find_prop_key(tab, i, tab[i].atom) >= 0) {\n            JS_ThrowTypeError(ctx, \"proxy: duplicate property\");\n            goto fail;\n        }\n    }\n\n    is_extensible = JS_IsExtensible(ctx, s->target);\n    if (is_extensible < 0)\n        goto fail;\n\n    /* check if there are non configurable properties */\n    if (s->is_revoked) {\n        JS_ThrowTypeErrorRevokedProxy(ctx);\n        goto fail;\n    }\n    if (JS_GetOwnPropertyNamesInternal(ctx, &tab2, &len2, JS_VALUE_GET_OBJ(s->target),\n                               JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK))\n        goto fail;\n    for(i = 0; i < len2; i++) {\n        if (s->is_revoked) {\n            JS_ThrowTypeErrorRevokedProxy(ctx);\n            goto fail;\n        }\n        res = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(s->target),\n                                tab2[i].atom);\n        if (res < 0)\n            goto fail;\n        if (res) {  /* safety, property should be found */\n            js_free_desc(ctx, &desc);\n            if (!(desc.flags & JS_PROP_CONFIGURABLE) || !is_extensible) {\n                idx = find_prop_key(tab, len, tab2[i].atom);\n                if (idx < 0) {\n                    JS_ThrowTypeError(ctx, \"proxy: target property must be present in proxy ownKeys\");\n                    goto fail;\n                }\n                /* mark the property as found */\n                if (!is_extensible)\n                    tab[idx].is_enumerable = TRUE;\n            }\n        }\n    }\n    if (!is_extensible) {\n        /* check that all property in 'tab' were checked */\n        for(i = 0; i < len; i++) {\n            if (!tab[i].is_enumerable) {\n                JS_ThrowTypeError(ctx, \"proxy: property not present in target were returned by non extensible proxy\");\n                goto fail;\n            }\n        }\n    }\n\n    js_free_prop_enum(ctx, tab2, len2);\n    JS_FreeValue(ctx, prop_array);\n    *ptab = tab;\n    *plen = len;\n    return 0;\n fail:\n    js_free_prop_enum(ctx, tab2, len2);\n    js_free_prop_enum(ctx, tab, len);\n    JS_FreeValue(ctx, prop_array);\n    return -1;\n}\n\nstatic JSValue js_proxy_call_constructor(JSContext *ctx, JSValueConst func_obj,\n                                         JSValueConst new_target,\n                                         int argc, JSValueConst *argv)\n{\n    JSProxyData *s;\n    JSValue method, arg_array, ret;\n    JSValueConst args[3];\n\n    s = get_proxy_method(ctx, &method, func_obj, JS_ATOM_construct);\n    if (!s)\n        return JS_EXCEPTION;\n    if (!JS_IsConstructor(ctx, s->target))\n        return JS_ThrowTypeError(ctx, \"not a constructor\");\n    if (JS_IsUndefined(method))\n        return JS_CallConstructor2(ctx, s->target, new_target, argc, argv);\n    arg_array = js_create_array(ctx, argc, argv);\n    if (JS_IsException(arg_array)) {\n        ret = JS_EXCEPTION;\n        goto fail;\n    }\n    args[0] = s->target;\n    args[1] = arg_array;\n    args[2] = new_target;\n    ret = JS_Call(ctx, method, s->handler, 3, args);\n    if (!JS_IsException(ret) && JS_VALUE_GET_TAG(ret) != JS_TAG_OBJECT) {\n        JS_FreeValue(ctx, ret);\n        ret = JS_ThrowTypeErrorNotAnObject(ctx);\n    }\n fail:\n    JS_FreeValue(ctx, method);\n    JS_FreeValue(ctx, arg_array);\n    return ret;\n}\n\nstatic JSValue js_proxy_call(JSContext *ctx, JSValueConst func_obj,\n                             JSValueConst this_obj,\n                             int argc, JSValueConst *argv, int flags)\n{\n    JSProxyData *s;\n    JSValue method, arg_array, ret;\n    JSValueConst args[3];\n\n    if (flags & JS_CALL_FLAG_CONSTRUCTOR)\n        return js_proxy_call_constructor(ctx, func_obj, this_obj, argc, argv);\n    \n    s = get_proxy_method(ctx, &method, func_obj, JS_ATOM_apply);\n    if (!s)\n        return JS_EXCEPTION;\n    if (!s->is_func) {\n        JS_FreeValue(ctx, method);\n        return JS_ThrowTypeError(ctx, \"not a function\");\n    }\n    if (JS_IsUndefined(method))\n        return JS_Call(ctx, s->target, this_obj, argc, argv);\n    arg_array = js_create_array(ctx, argc, argv);\n    if (JS_IsException(arg_array)) {\n        ret = JS_EXCEPTION;\n        goto fail;\n    }\n    args[0] = s->target;\n    args[1] = this_obj;\n    args[2] = arg_array;\n    ret = JS_Call(ctx, method, s->handler, 3, args);\n fail:\n    JS_FreeValue(ctx, method);\n    JS_FreeValue(ctx, arg_array);\n    return ret;\n}\n\nstatic int js_proxy_isArray(JSContext *ctx, JSValueConst obj)\n{\n    JSProxyData *s = JS_GetOpaque(obj, JS_CLASS_PROXY);\n    if (!s)\n        return FALSE;\n    if (s->is_revoked) {\n        JS_ThrowTypeErrorRevokedProxy(ctx);\n        return -1;\n    }\n    return JS_IsArray(ctx, s->target);\n}\n\nstatic const JSClassExoticMethods js_proxy_exotic_methods = {\n    .get_own_property = js_proxy_get_own_property,\n    .define_own_property = js_proxy_define_own_property,\n    .delete_property = js_proxy_delete_property,\n    .get_own_property_names = js_proxy_get_own_property_names,\n    .has_property = js_proxy_has,\n    .get_property = js_proxy_get,\n    .set_property = js_proxy_set,\n};\n\nstatic JSValue js_proxy_constructor(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSValueConst target, handler;\n    JSValue obj;\n    JSProxyData *s;\n\n    target = argv[0];\n    handler = argv[1];\n    if (JS_VALUE_GET_TAG(target) != JS_TAG_OBJECT ||\n        JS_VALUE_GET_TAG(handler) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    obj = JS_NewObjectProtoClass(ctx, JS_NULL, JS_CLASS_PROXY);\n    if (JS_IsException(obj))\n        return obj;\n    s = js_malloc(ctx, sizeof(JSProxyData));\n    if (!s) {\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    s->target = JS_DupValue(ctx, target);\n    s->handler = JS_DupValue(ctx, handler);\n    s->is_func = JS_IsFunction(ctx, target);\n    s->is_revoked = FALSE;\n    JS_SetOpaque(obj, s);\n    JS_SetConstructorBit(ctx, obj, JS_IsConstructor(ctx, target));\n    return obj;\n}\n\nstatic JSValue js_proxy_revoke(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv, int magic,\n                               JSValue *func_data)\n{\n    JSProxyData *s = JS_GetOpaque(func_data[0], JS_CLASS_PROXY);\n    if (s) {\n        /* We do not free the handler and target in case they are\n           referenced as constants in the C call stack */\n        s->is_revoked = TRUE;\n        JS_FreeValue(ctx, func_data[0]);\n        func_data[0] = JS_NULL;\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_proxy_revoke_constructor(JSContext *ctx,\n                                           JSValueConst proxy_obj)\n{\n    return JS_NewCFunctionData(ctx, js_proxy_revoke, 0, 0, 1, &proxy_obj);\n}\n\nstatic JSValue js_proxy_revocable(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValue proxy_obj, revoke_obj = JS_UNDEFINED, obj;\n\n    proxy_obj = js_proxy_constructor(ctx, JS_UNDEFINED, argc, argv);\n    if (JS_IsException(proxy_obj))\n        goto fail;\n    revoke_obj = js_proxy_revoke_constructor(ctx, proxy_obj);\n    if (JS_IsException(revoke_obj))\n        goto fail;\n    obj = JS_NewObject(ctx);\n    if (JS_IsException(obj))\n        goto fail;\n    // XXX: exceptions?\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_proxy, proxy_obj, JS_PROP_C_W_E);\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_revoke, revoke_obj, JS_PROP_C_W_E);\n    return obj;\n fail:\n    JS_FreeValue(ctx, proxy_obj);\n    JS_FreeValue(ctx, revoke_obj);\n    return JS_EXCEPTION;\n}\n\nstatic const JSCFunctionListEntry js_proxy_funcs[] = {\n    JS_CFUNC_DEF(\"revocable\", 2, js_proxy_revocable ),\n};\n\nstatic const JSClassShortDef js_proxy_class_def[] = {\n    { JS_ATOM_Object, js_proxy_finalizer, js_proxy_mark }, /* JS_CLASS_PROXY */\n};\n\nvoid JS_AddIntrinsicProxy(JSContext *ctx)\n{\n    JSRuntime *rt = ctx->rt;\n    JSValue obj1;\n\n    if (!JS_IsRegisteredClass(rt, JS_CLASS_PROXY)) {\n        init_class_range(rt, js_proxy_class_def, JS_CLASS_PROXY,\n                         countof(js_proxy_class_def));\n        rt->class_array[JS_CLASS_PROXY].exotic = &js_proxy_exotic_methods;\n        rt->class_array[JS_CLASS_PROXY].call = js_proxy_call;\n    }\n\n    obj1 = JS_NewCFunction2(ctx, js_proxy_constructor, \"Proxy\", 2,\n                            JS_CFUNC_constructor, 0);\n    JS_SetConstructorBit(ctx, obj1, TRUE);\n    JS_SetPropertyFunctionList(ctx, obj1, js_proxy_funcs,\n                               countof(js_proxy_funcs));\n    JS_DefinePropertyValueStr(ctx, ctx->global_obj, \"Proxy\",\n                              obj1, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n}\n\n/* Symbol */\n\nstatic JSValue js_symbol_constructor(JSContext *ctx, JSValueConst new_target,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue str;\n    JSString *p;\n\n    if (!JS_IsUndefined(new_target))\n        return JS_ThrowTypeError(ctx, \"not a constructor\");\n    if (argc == 0 || JS_IsUndefined(argv[0])) {\n        p = NULL;\n    } else {\n        str = JS_ToString(ctx, argv[0]);\n        if (JS_IsException(str))\n            return JS_EXCEPTION;\n        p = JS_VALUE_GET_STRING(str);\n    }\n    return JS_NewSymbol(ctx, p, JS_ATOM_TYPE_SYMBOL);\n}\n\nstatic JSValue js_thisSymbolValue(JSContext *ctx, JSValueConst this_val)\n{\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_SYMBOL)\n        return JS_DupValue(ctx, this_val);\n\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_SYMBOL) {\n            if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_SYMBOL)\n                return JS_DupValue(ctx, p->u.object_data);\n        }\n    }\n    return JS_ThrowTypeError(ctx, \"not a symbol\");\n}\n\nstatic JSValue js_symbol_toString(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    val = js_thisSymbolValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    /* XXX: use JS_ToStringInternal() with a flags */\n    ret = js_string_constructor(ctx, JS_UNDEFINED, 1, (JSValueConst *)&val);\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nstatic JSValue js_symbol_valueOf(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    return js_thisSymbolValue(ctx, this_val);\n}\n\nstatic JSValue js_symbol_get_description(JSContext *ctx, JSValueConst this_val)\n{\n    JSValue val, ret;\n    JSAtomStruct *p;\n\n    val = js_thisSymbolValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    p = JS_VALUE_GET_PTR(val);\n    if (p->len == 0 && p->is_wide_char != 0) {\n        ret = JS_UNDEFINED;\n    } else {\n        ret = JS_AtomToString(ctx, js_get_atom_index(ctx->rt, p));\n    }\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nstatic const JSCFunctionListEntry js_symbol_proto_funcs[] = {\n    JS_CFUNC_DEF(\"toString\", 0, js_symbol_toString ),\n    JS_CFUNC_DEF(\"valueOf\", 0, js_symbol_valueOf ),\n    // XXX: should have writable: false\n    JS_CFUNC_DEF(\"[Symbol.toPrimitive]\", 1, js_symbol_valueOf ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Symbol\", JS_PROP_CONFIGURABLE ),\n    JS_CGETSET_DEF(\"description\", js_symbol_get_description, NULL ),\n};\n\nstatic JSValue js_symbol_for(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    JSValue str;\n\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        return JS_EXCEPTION;\n    return JS_NewSymbol(ctx, JS_VALUE_GET_STRING(str), JS_ATOM_TYPE_GLOBAL_SYMBOL);\n}\n\nstatic JSValue js_symbol_keyFor(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSAtomStruct *p;\n\n    if (!JS_IsSymbol(argv[0]))\n        return JS_ThrowTypeError(ctx, \"not a symbol\");\n    p = JS_VALUE_GET_PTR(argv[0]);\n    if (p->atom_type != JS_ATOM_TYPE_GLOBAL_SYMBOL)\n        return JS_UNDEFINED;\n    return JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, p));\n}\n\nstatic const JSCFunctionListEntry js_symbol_funcs[] = {\n    JS_CFUNC_DEF(\"for\", 1, js_symbol_for ),\n    JS_CFUNC_DEF(\"keyFor\", 1, js_symbol_keyFor ),\n};\n\n/* Set/Map/WeakSet/WeakMap */\n\ntypedef struct JSMapRecord {\n    int ref_count; /* used during enumeration to avoid freeing the record */\n    BOOL empty; /* TRUE if the record is deleted */\n    struct JSMapState *map;\n    struct JSMapRecord *next_weak_ref;\n    struct list_head link;\n    struct list_head hash_link;\n    JSValue key;\n    JSValue value;\n} JSMapRecord;\n\ntypedef struct JSMapState {\n    BOOL is_weak; /* TRUE if WeakSet/WeakMap */\n    struct list_head records; /* list of JSMapRecord.link */\n    uint32_t record_count;\n    struct list_head *hash_table;\n    uint32_t hash_size; /* must be a power of two */\n    uint32_t record_count_threshold; /* count at which a hash table\n                                        resize is needed */\n} JSMapState;\n\n#define MAGIC_SET (1 << 0)\n#define MAGIC_WEAK (1 << 1)\n\nstatic JSValue js_map_constructor(JSContext *ctx, JSValueConst new_target,\n                                  int argc, JSValueConst *argv, int magic)\n{\n    JSMapState *s;\n    JSValue obj, adder = JS_UNDEFINED, iter = JS_UNDEFINED, next_method = JS_UNDEFINED;\n    JSValueConst arr;\n    BOOL is_set, is_weak;\n\n    is_set = magic & MAGIC_SET;\n    is_weak = ((magic & MAGIC_WEAK) != 0);\n    obj = js_create_from_ctor(ctx, new_target, JS_CLASS_MAP + magic);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s)\n        goto fail;\n    init_list_head(&s->records);\n    s->is_weak = is_weak;\n    JS_SetOpaque(obj, s);\n    s->hash_size = 1;\n    s->hash_table = js_malloc(ctx, sizeof(s->hash_table[0]) * s->hash_size);\n    if (!s->hash_table)\n        goto fail;\n    init_list_head(&s->hash_table[0]);\n    s->record_count_threshold = 4;\n\n    arr = JS_UNDEFINED;\n    if (argc > 0)\n        arr = argv[0];\n    if (!JS_IsUndefined(arr) && !JS_IsNull(arr)) {\n        JSValue item, ret;\n        BOOL done;\n\n        adder = JS_GetProperty(ctx, obj, is_set ? JS_ATOM_add : JS_ATOM_set);\n        if (JS_IsException(adder))\n            goto fail;\n        if (!JS_IsFunction(ctx, adder)) {\n            JS_ThrowTypeError(ctx, \"set/add is not a function\");\n            goto fail;\n        }\n\n        iter = JS_GetIterator(ctx, arr, FALSE);\n        if (JS_IsException(iter))\n            goto fail;\n        next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);\n        if (JS_IsException(next_method))\n            goto fail;\n\n        for(;;) {\n            item = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);\n            if (JS_IsException(item))\n                goto fail;\n            if (done) {\n                JS_FreeValue(ctx, item);\n                break;\n            }\n            if (is_set) {\n                ret = JS_Call(ctx, adder, obj, 1, (JSValueConst *)&item);\n                if (JS_IsException(ret)) {\n                    JS_FreeValue(ctx, item);\n                    goto fail;\n                }\n            } else {\n                JSValue key, value;\n                JSValueConst args[2];\n                key = JS_UNDEFINED;\n                value = JS_UNDEFINED;\n                if (!JS_IsObject(item)) {\n                    JS_ThrowTypeErrorNotAnObject(ctx);\n                    goto fail1;\n                }\n                key = JS_GetPropertyUint32(ctx, item, 0);\n                if (JS_IsException(key))\n                    goto fail1;\n                value = JS_GetPropertyUint32(ctx, item, 1);\n                if (JS_IsException(value))\n                    goto fail1;\n                args[0] = key;\n                args[1] = value;\n                ret = JS_Call(ctx, adder, obj, 2, args);\n                if (JS_IsException(ret)) {\n                fail1:\n                    JS_FreeValue(ctx, item);\n                    JS_FreeValue(ctx, key);\n                    JS_FreeValue(ctx, value);\n                    goto fail;\n                }\n                JS_FreeValue(ctx, key);\n                JS_FreeValue(ctx, value);\n            }\n            JS_FreeValue(ctx, ret);\n            JS_FreeValue(ctx, item);\n        }\n        JS_FreeValue(ctx, next_method);\n        JS_FreeValue(ctx, iter);\n        JS_FreeValue(ctx, adder);\n    }\n    return obj;\n fail:\n    if (JS_IsObject(iter)) {\n        /* close the iterator object, preserving pending exception */\n        JS_IteratorClose(ctx, iter, TRUE);\n    }\n    JS_FreeValue(ctx, next_method);\n    JS_FreeValue(ctx, iter);\n    JS_FreeValue(ctx, adder);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\n/* XXX: could normalize strings to speed up comparison */\nstatic JSValueConst map_normalize_key(JSContext *ctx, JSValueConst key)\n{\n    uint32_t tag = JS_VALUE_GET_TAG(key);\n    /* convert -0.0 to +0.0 */\n    if (JS_TAG_IS_FLOAT64(tag) && JS_VALUE_GET_FLOAT64(key) == 0.0) {\n        key = JS_NewInt32(ctx, 0);\n    }\n    return key;\n}\n\n/* XXX: better hash ? */\nstatic uint32_t map_hash_key(JSContext *ctx, JSValueConst key)\n{\n    uint32_t tag = JS_VALUE_GET_NORM_TAG(key);\n    uint32_t h;\n    double d;\n    JSFloat64Union u;\n\n    switch(tag) {\n    case JS_TAG_BOOL:\n        h = JS_VALUE_GET_INT(key);\n        break;\n    case JS_TAG_STRING:\n        h = hash_string(JS_VALUE_GET_STRING(key), 0);\n        break;\n    case JS_TAG_OBJECT:\n    case JS_TAG_SYMBOL:\n        h = (uintptr_t)JS_VALUE_GET_PTR(key) * 3163;\n        break;\n    case JS_TAG_INT:\n        d = JS_VALUE_GET_INT(key) * 3163;\n        goto hash_float64;\n    case JS_TAG_FLOAT64:\n        d = JS_VALUE_GET_FLOAT64(key);\n        /* normalize the NaN */\n        if (isnan(d))\n            d = JS_FLOAT64_NAN;\n    hash_float64:\n        u.d = d;\n        h = (u.u32[0] ^ u.u32[1]) * 3163;\n        break;\n    default:\n        h = 0; /* XXX: bignum support */\n        break;\n    }\n    h ^= tag;\n    return h;\n}\n\nstatic JSMapRecord *map_find_record(JSContext *ctx, JSMapState *s,\n                                    JSValueConst key)\n{\n    struct list_head *el;\n    JSMapRecord *mr;\n    uint32_t h;\n    h = map_hash_key(ctx, key) & (s->hash_size - 1);\n    list_for_each(el, &s->hash_table[h]) {\n        mr = list_entry(el, JSMapRecord, hash_link);\n        if (js_same_value_zero(ctx, mr->key, key))\n            return mr;\n    }\n    return NULL;\n}\n\nstatic void map_hash_resize(JSContext *ctx, JSMapState *s)\n{\n    uint32_t new_hash_size, i, h;\n    size_t slack;\n    struct list_head *new_hash_table, *el;\n    JSMapRecord *mr;\n\n    /* XXX: no reporting of memory allocation failure */\n    if (s->hash_size == 1)\n        new_hash_size = 4;\n    else\n        new_hash_size = s->hash_size * 2;\n    new_hash_table = js_realloc2(ctx, s->hash_table,\n                                 sizeof(new_hash_table[0]) * new_hash_size, &slack);\n    if (!new_hash_table)\n        return;\n    new_hash_size += slack / sizeof(*new_hash_table);\n\n    for(i = 0; i < new_hash_size; i++)\n        init_list_head(&new_hash_table[i]);\n\n    list_for_each(el, &s->records) {\n        mr = list_entry(el, JSMapRecord, link);\n        if (!mr->empty) {\n            h = map_hash_key(ctx, mr->key) & (new_hash_size - 1);\n            list_add_tail(&mr->hash_link, &new_hash_table[h]);\n        }\n    }\n    s->hash_table = new_hash_table;\n    s->hash_size = new_hash_size;\n    s->record_count_threshold = new_hash_size * 2;\n}\n\nstatic JSMapRecord *map_add_record(JSContext *ctx, JSMapState *s,\n                                   JSValueConst key)\n{\n    uint32_t h;\n    JSMapRecord *mr;\n\n    mr = js_malloc(ctx, sizeof(*mr));\n    if (!mr)\n        return NULL;\n    mr->ref_count = 1;\n    mr->map = s;\n    mr->empty = FALSE;\n    if (s->is_weak) {\n        JSObject *p = JS_VALUE_GET_OBJ(key);\n        /* Add the weak reference */\n        mr->next_weak_ref = p->first_weak_ref;\n        p->first_weak_ref = mr;\n    } else {\n        JS_DupValue(ctx, key);\n    }\n    mr->key = (JSValue)key;\n    h = map_hash_key(ctx, key) & (s->hash_size - 1);\n    list_add_tail(&mr->hash_link, &s->hash_table[h]);\n    list_add_tail(&mr->link, &s->records);\n    s->record_count++;\n    if (s->record_count >= s->record_count_threshold) {\n        map_hash_resize(ctx, s);\n    }\n    return mr;\n}\n\n/* Remove the weak reference from the object weak\n   reference list. we don't use a doubly linked list to\n   save space, assuming a given object has few weak\n       references to it */\nstatic void delete_weak_ref(JSRuntime *rt, JSMapRecord *mr)\n{\n    JSMapRecord **pmr, *mr1;\n    JSObject *p;\n\n    p = JS_VALUE_GET_OBJ(mr->key);\n    pmr = &p->first_weak_ref;\n    for(;;) {\n        mr1 = *pmr;\n        assert(mr1 != NULL);\n        if (mr1 == mr)\n            break;\n        pmr = &mr1->next_weak_ref;\n    }\n    *pmr = mr1->next_weak_ref;\n}\n\nstatic void map_delete_record(JSRuntime *rt, JSMapState *s, JSMapRecord *mr)\n{\n    if (mr->empty)\n        return;\n    list_del(&mr->hash_link);\n    if (s->is_weak) {\n        delete_weak_ref(rt, mr);\n    } else {\n        JS_FreeValueRT(rt, mr->key);\n    }\n    JS_FreeValueRT(rt, mr->value);\n    if (--mr->ref_count == 0) {\n        list_del(&mr->link);\n        js_free_rt(rt, mr);\n    } else {\n        /* keep a zombie record for iterators */\n        mr->empty = TRUE;\n        mr->key = JS_UNDEFINED;\n        mr->value = JS_UNDEFINED;\n    }\n    s->record_count--;\n}\n\nstatic void map_decref_record(JSRuntime *rt, JSMapRecord *mr)\n{\n    if (--mr->ref_count == 0) {\n        /* the record can be safely removed */\n        assert(mr->empty);\n        list_del(&mr->link);\n        js_free_rt(rt, mr);\n    }\n}\n\nstatic void reset_weak_ref(JSRuntime *rt, JSObject *p)\n{\n    JSMapRecord *mr, *mr_next;\n    JSMapState *s;\n    \n    /* first pass to remove the records from the WeakMap/WeakSet\n       lists */\n    for(mr = p->first_weak_ref; mr != NULL; mr = mr->next_weak_ref) {\n        s = mr->map;\n        assert(s->is_weak);\n        assert(!mr->empty); /* no iterator on WeakMap/WeakSet */\n        list_del(&mr->hash_link);\n        list_del(&mr->link);\n    }\n    \n    /* second pass to free the values to avoid modifying the weak\n       reference list while traversing it. */\n    for(mr = p->first_weak_ref; mr != NULL; mr = mr_next) {\n        mr_next = mr->next_weak_ref;\n        JS_FreeValueRT(rt, mr->value);\n        js_free_rt(rt, mr);\n    }\n\n    p->first_weak_ref = NULL; /* fail safe */\n}\n\nstatic JSValue js_map_set(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv, int magic)\n{\n    JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);\n    JSMapRecord *mr;\n    JSValueConst key, value;\n\n    if (!s)\n        return JS_EXCEPTION;\n    key = map_normalize_key(ctx, argv[0]);\n    if (s->is_weak && !JS_IsObject(key))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    if (magic & MAGIC_SET)\n        value = JS_UNDEFINED;\n    else\n        value = argv[1];\n    mr = map_find_record(ctx, s, key);\n    if (mr) {\n        JS_FreeValue(ctx, mr->value);\n    } else {\n        mr = map_add_record(ctx, s, key);\n        if (!mr)\n            return JS_EXCEPTION;\n    }\n    mr->value = JS_DupValue(ctx, value);\n    return JS_DupValue(ctx, this_val);\n}\n\nstatic JSValue js_map_get(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv, int magic)\n{\n    JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);\n    JSMapRecord *mr;\n    JSValueConst key;\n\n    if (!s)\n        return JS_EXCEPTION;\n    key = map_normalize_key(ctx, argv[0]);\n    mr = map_find_record(ctx, s, key);\n    if (!mr)\n        return JS_UNDEFINED;\n    else\n        return JS_DupValue(ctx, mr->value);\n}\n\nstatic JSValue js_map_has(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv, int magic)\n{\n    JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);\n    JSMapRecord *mr;\n    JSValueConst key;\n\n    if (!s)\n        return JS_EXCEPTION;\n    key = map_normalize_key(ctx, argv[0]);\n    mr = map_find_record(ctx, s, key);\n    return JS_NewBool(ctx, (mr != NULL));\n}\n\nstatic JSValue js_map_delete(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv, int magic)\n{\n    JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);\n    JSMapRecord *mr;\n    JSValueConst key;\n\n    if (!s)\n        return JS_EXCEPTION;\n    key = map_normalize_key(ctx, argv[0]);\n    mr = map_find_record(ctx, s, key);\n    if (!mr)\n        return JS_FALSE;\n    map_delete_record(ctx->rt, s, mr);\n    return JS_TRUE;\n}\n\nstatic JSValue js_map_clear(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv, int magic)\n{\n    JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);\n    struct list_head *el, *el1;\n    JSMapRecord *mr;\n\n    if (!s)\n        return JS_EXCEPTION;\n    list_for_each_safe(el, el1, &s->records) {\n        mr = list_entry(el, JSMapRecord, link);\n        map_delete_record(ctx->rt, s, mr);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_map_get_size(JSContext *ctx, JSValueConst this_val, int magic)\n{\n    JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);\n    if (!s)\n        return JS_EXCEPTION;\n    return JS_NewUint32(ctx, s->record_count);\n}\n\nstatic JSValue js_map_forEach(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int magic)\n{\n    JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);\n    JSValueConst func, this_arg;\n    JSValue ret, args[3];\n    struct list_head *el;\n    JSMapRecord *mr;\n\n    if (!s)\n        return JS_EXCEPTION;\n    func = argv[0];\n    if (argc > 1)\n        this_arg = argv[1];\n    else\n        this_arg = JS_UNDEFINED;\n    if (check_function(ctx, func))\n        return JS_EXCEPTION;\n    /* Note: the list can be modified while traversing it, but the\n       current element is locked */\n    el = s->records.next;\n    while (el != &s->records) {\n        mr = list_entry(el, JSMapRecord, link);\n        if (!mr->empty) {\n            mr->ref_count++;\n            /* must duplicate in case the record is deleted */\n            args[1] = JS_DupValue(ctx, mr->key);\n            if (magic)\n                args[0] = args[1];\n            else\n                args[0] = JS_DupValue(ctx, mr->value);\n            args[2] = (JSValue)this_val;\n            ret = JS_Call(ctx, func, this_arg, 3, (JSValueConst *)args);\n            JS_FreeValue(ctx, args[0]);\n            if (!magic)\n                JS_FreeValue(ctx, args[1]);\n            el = el->next;\n            map_decref_record(ctx->rt, mr);\n            if (JS_IsException(ret))\n                return ret;\n            JS_FreeValue(ctx, ret);\n        } else {\n            el = el->next;\n        }\n    }\n    return JS_UNDEFINED;\n}\n\nstatic void js_map_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p;\n    JSMapState *s;\n    struct list_head *el, *el1;\n    JSMapRecord *mr;\n\n    p = JS_VALUE_GET_OBJ(val);\n    s = p->u.map_state;\n    if (s) {\n        /* if the object is deleted we are sure that no iterator is\n           using it */\n        list_for_each_safe(el, el1, &s->records) {\n            mr = list_entry(el, JSMapRecord, link);\n            if (!mr->empty) {\n                if (s->is_weak)\n                    delete_weak_ref(rt, mr);\n                else\n                    JS_FreeValueRT(rt, mr->key);\n                JS_FreeValueRT(rt, mr->value);\n            }\n            js_free_rt(rt, mr);\n        }\n        js_free_rt(rt, s->hash_table);\n        js_free_rt(rt, s);\n    }\n}\n\nstatic void js_map_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSMapState *s;\n    struct list_head *el;\n    JSMapRecord *mr;\n\n    s = p->u.map_state;\n    if (s) {\n        list_for_each(el, &s->records) {\n            mr = list_entry(el, JSMapRecord, link);\n            if (!s->is_weak)\n                JS_MarkValue(rt, mr->key, mark_func);\n            JS_MarkValue(rt, mr->value, mark_func);\n        }\n    }\n}\n\n/* Map Iterator */\n\ntypedef struct JSMapIteratorData {\n    JSValue obj;\n    JSIteratorKindEnum kind;\n    JSMapRecord *cur_record;\n} JSMapIteratorData;\n\nstatic void js_map_iterator_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p;\n    JSMapIteratorData *it;\n\n    p = JS_VALUE_GET_OBJ(val);\n    it = p->u.map_iterator_data;\n    if (it) {\n        /* During the GC sweep phase the Map finalizer may be\n           called before the Map iterator finalizer */\n        if (JS_IsLiveObject(rt, it->obj) && it->cur_record) {\n            map_decref_record(rt, it->cur_record);\n        }\n        JS_FreeValueRT(rt, it->obj);\n        js_free_rt(rt, it);\n    }\n}\n\nstatic void js_map_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                 JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSMapIteratorData *it;\n    it = p->u.map_iterator_data;\n    if (it) {\n        /* the record is already marked by the object */\n        JS_MarkValue(rt, it->obj, mark_func);\n    }\n}\n\nstatic JSValue js_create_map_iterator(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv, int magic)\n{\n    JSIteratorKindEnum kind;\n    JSMapState *s;\n    JSMapIteratorData *it;\n    JSValue enum_obj;\n\n    kind = magic >> 2;\n    magic &= 3;\n    s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);\n    if (!s)\n        return JS_EXCEPTION;\n    enum_obj = JS_NewObjectClass(ctx, JS_CLASS_MAP_ITERATOR + magic);\n    if (JS_IsException(enum_obj))\n        goto fail;\n    it = js_malloc(ctx, sizeof(*it));\n    if (!it) {\n        JS_FreeValue(ctx, enum_obj);\n        goto fail;\n    }\n    it->obj = JS_DupValue(ctx, this_val);\n    it->kind = kind;\n    it->cur_record = NULL;\n    JS_SetOpaque(enum_obj, it);\n    return enum_obj;\n fail:\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_map_iterator_next(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv,\n                                    BOOL *pdone, int magic)\n{\n    JSMapIteratorData *it;\n    JSMapState *s;\n    JSMapRecord *mr;\n    struct list_head *el;\n\n    it = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP_ITERATOR + magic);\n    if (!it) {\n        *pdone = FALSE;\n        return JS_EXCEPTION;\n    }\n    if (JS_IsUndefined(it->obj))\n        goto done;\n    s = JS_GetOpaque(it->obj, JS_CLASS_MAP + magic);\n    assert(s != NULL);\n    if (!it->cur_record) {\n        el = s->records.next;\n    } else {\n        mr = it->cur_record;\n        el = mr->link.next;\n        map_decref_record(ctx->rt, mr); /* the record can be freed here */\n    }\n    for(;;) {\n        if (el == &s->records) {\n            /* no more record  */\n            it->cur_record = NULL;\n            JS_FreeValue(ctx, it->obj);\n            it->obj = JS_UNDEFINED;\n        done:\n            /* end of enumeration */\n            *pdone = TRUE;\n            return JS_UNDEFINED;\n        }\n        mr = list_entry(el, JSMapRecord, link);\n        if (!mr->empty)\n            break;\n        /* get the next record */\n        el = mr->link.next;\n    }\n\n    /* lock the record so that it won't be freed */\n    mr->ref_count++;\n    it->cur_record = mr;\n    *pdone = FALSE;\n\n    if (it->kind == JS_ITERATOR_KIND_KEY) {\n        return JS_DupValue(ctx, mr->key);\n    } else {\n        JSValueConst args[2];\n        args[0] = mr->key;\n        if (magic)\n            args[1] = mr->key;\n        else\n            args[1] = mr->value;\n        if (it->kind == JS_ITERATOR_KIND_VALUE) {\n            return JS_DupValue(ctx, args[1]);\n        } else {\n            return js_create_array(ctx, 2, args);\n        }\n    }\n}\n\nstatic const JSCFunctionListEntry js_map_funcs[] = {\n    JS_CGETSET_DEF(\"[Symbol.species]\", js_get_this, NULL ),\n};\n\nstatic const JSCFunctionListEntry js_map_proto_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"set\", 2, js_map_set, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"get\", 1, js_map_get, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"has\", 1, js_map_has, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"delete\", 1, js_map_delete, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"clear\", 0, js_map_clear, 0 ),\n    JS_CGETSET_MAGIC_DEF(\"size\", js_map_get_size, NULL, 0),\n    JS_CFUNC_MAGIC_DEF(\"forEach\", 1, js_map_forEach, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"values\", 0, js_create_map_iterator, (JS_ITERATOR_KIND_VALUE << 2) | 0 ),\n    JS_CFUNC_MAGIC_DEF(\"keys\", 0, js_create_map_iterator, (JS_ITERATOR_KIND_KEY << 2) | 0 ),\n    JS_CFUNC_MAGIC_DEF(\"entries\", 0, js_create_map_iterator, (JS_ITERATOR_KIND_KEY_AND_VALUE << 2) | 0 ),\n    JS_ALIAS_DEF(\"[Symbol.iterator]\", \"entries\" ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Map\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_map_iterator_proto_funcs[] = {\n    JS_ITERATOR_NEXT_DEF(\"next\", 0, js_map_iterator_next, 0 ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Map Iterator\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_set_proto_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"add\", 1, js_map_set, MAGIC_SET ),\n    JS_CFUNC_MAGIC_DEF(\"has\", 1, js_map_has, MAGIC_SET ),\n    JS_CFUNC_MAGIC_DEF(\"delete\", 1, js_map_delete, MAGIC_SET ),\n    JS_CFUNC_MAGIC_DEF(\"clear\", 0, js_map_clear, MAGIC_SET ),\n    JS_CGETSET_MAGIC_DEF(\"size\", js_map_get_size, NULL, MAGIC_SET ),\n    JS_CFUNC_MAGIC_DEF(\"forEach\", 1, js_map_forEach, MAGIC_SET ),\n    JS_CFUNC_MAGIC_DEF(\"values\", 0, js_create_map_iterator, (JS_ITERATOR_KIND_KEY << 2) | MAGIC_SET ),\n    JS_ALIAS_DEF(\"keys\", \"values\" ),\n    JS_ALIAS_DEF(\"[Symbol.iterator]\", \"values\" ),\n    JS_CFUNC_MAGIC_DEF(\"entries\", 0, js_create_map_iterator, (JS_ITERATOR_KIND_KEY_AND_VALUE << 2) | MAGIC_SET ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Set\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_set_iterator_proto_funcs[] = {\n    JS_ITERATOR_NEXT_DEF(\"next\", 0, js_map_iterator_next, MAGIC_SET ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Set Iterator\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_weak_map_proto_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"set\", 2, js_map_set, MAGIC_WEAK ),\n    JS_CFUNC_MAGIC_DEF(\"get\", 1, js_map_get, MAGIC_WEAK ),\n    JS_CFUNC_MAGIC_DEF(\"has\", 1, js_map_has, MAGIC_WEAK ),\n    JS_CFUNC_MAGIC_DEF(\"delete\", 1, js_map_delete, MAGIC_WEAK ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"WeakMap\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_weak_set_proto_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"add\", 1, js_map_set, MAGIC_SET | MAGIC_WEAK ),\n    JS_CFUNC_MAGIC_DEF(\"has\", 1, js_map_has, MAGIC_SET | MAGIC_WEAK ),\n    JS_CFUNC_MAGIC_DEF(\"delete\", 1, js_map_delete, MAGIC_SET | MAGIC_WEAK ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"WeakSet\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry * const js_map_proto_funcs_ptr[6] = {\n    js_map_proto_funcs,\n    js_set_proto_funcs,\n    js_weak_map_proto_funcs,\n    js_weak_set_proto_funcs,\n    js_map_iterator_proto_funcs,\n    js_set_iterator_proto_funcs,\n};\n\nstatic const uint8_t js_map_proto_funcs_count[6] = {\n    countof(js_map_proto_funcs),\n    countof(js_set_proto_funcs),\n    countof(js_weak_map_proto_funcs),\n    countof(js_weak_set_proto_funcs),\n    countof(js_map_iterator_proto_funcs),\n    countof(js_set_iterator_proto_funcs),\n};\n\nvoid JS_AddIntrinsicMapSet(JSContext *ctx)\n{\n    int i;\n    JSValue obj1;\n    char buf[ATOM_GET_STR_BUF_SIZE];\n\n    for(i = 0; i < 4; i++) {\n        const char *name = JS_AtomGetStr(ctx, buf, sizeof(buf),\n                                         JS_ATOM_Map + i);\n        ctx->class_proto[JS_CLASS_MAP + i] = JS_NewObject(ctx);\n        JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_MAP + i],\n                                   js_map_proto_funcs_ptr[i],\n                                   js_map_proto_funcs_count[i]);\n        obj1 = JS_NewCFunctionMagic(ctx, js_map_constructor, name, 0,\n                                    JS_CFUNC_constructor_magic, i);\n        if (i < 2) {\n            JS_SetPropertyFunctionList(ctx, obj1, js_map_funcs,\n                                       countof(js_map_funcs));\n        }\n        JS_NewGlobalCConstructor2(ctx, obj1, name, ctx->class_proto[JS_CLASS_MAP + i]);\n    }\n\n    for(i = 0; i < 2; i++) {\n        ctx->class_proto[JS_CLASS_MAP_ITERATOR + i] =\n            JS_NewObjectProto(ctx, ctx->iterator_proto);\n        JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_MAP_ITERATOR + i],\n                                   js_map_proto_funcs_ptr[i + 4],\n                                   js_map_proto_funcs_count[i + 4]);\n    }\n}\n\n/* Generator */\nstatic const JSCFunctionListEntry js_generator_function_proto_funcs[] = {\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"GeneratorFunction\", JS_PROP_CONFIGURABLE),\n};\n\nstatic const JSCFunctionListEntry js_generator_proto_funcs[] = {\n    JS_ITERATOR_NEXT_DEF(\"next\", 1, js_generator_next, GEN_MAGIC_NEXT ),\n    JS_ITERATOR_NEXT_DEF(\"return\", 1, js_generator_next, GEN_MAGIC_RETURN ),\n    JS_ITERATOR_NEXT_DEF(\"throw\", 1, js_generator_next, GEN_MAGIC_THROW ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Generator\", JS_PROP_CONFIGURABLE),\n};\n\n/* Promise */\n\ntypedef enum JSPromiseStateEnum {\n    JS_PROMISE_PENDING,\n    JS_PROMISE_FULFILLED,\n    JS_PROMISE_REJECTED,\n} JSPromiseStateEnum;\n\ntypedef struct JSPromiseData {\n    JSPromiseStateEnum promise_state;\n    /* 0=fulfill, 1=reject, list of JSPromiseReactionData.link */\n    struct list_head promise_reactions[2];\n    BOOL is_handled; /* Note: only useful to debug */\n    JSValue promise_result;\n} JSPromiseData;\n\ntypedef struct JSPromiseFunctionDataResolved {\n    int ref_count;\n    BOOL already_resolved;\n} JSPromiseFunctionDataResolved;\n\ntypedef struct JSPromiseFunctionData {\n    JSValue promise;\n    JSPromiseFunctionDataResolved *presolved;\n} JSPromiseFunctionData;\n\ntypedef struct JSPromiseReactionData {\n    struct list_head link; /* not used in promise_reaction_job */\n    JSValue resolving_funcs[2];\n    JSValue handler;\n} JSPromiseReactionData;\n\nstatic int js_create_resolving_functions(JSContext *ctx, JSValue *args,\n                                         JSValueConst promise);\n\nstatic void promise_reaction_data_free(JSRuntime *rt,\n                                       JSPromiseReactionData *rd)\n{\n    JS_FreeValueRT(rt, rd->resolving_funcs[0]);\n    JS_FreeValueRT(rt, rd->resolving_funcs[1]);\n    JS_FreeValueRT(rt, rd->handler);\n    js_free_rt(rt, rd);\n}\n\nstatic JSValue promise_reaction_job(JSContext *ctx, int argc,\n                                    JSValueConst *argv)\n{\n    JSValueConst handler, arg, func;\n    JSValue res, res2;\n    BOOL is_reject;\n\n    assert(argc == 5);\n    handler = argv[2];\n    is_reject = JS_ToBool(ctx, argv[3]);\n    arg = argv[4];\n#ifdef DUMP_PROMISE\n    printf(\"promise_reaction_job: is_reject=%d\\n\", is_reject);\n#endif\n\n    if (JS_IsUndefined(handler)) {\n        if (is_reject) {\n            res = JS_Throw(ctx, JS_DupValue(ctx, arg));\n        } else {\n            res = JS_DupValue(ctx, arg);\n        }\n    } else {\n        res = JS_Call(ctx, handler, JS_UNDEFINED, 1, &arg);\n    }\n    is_reject = JS_IsException(res);\n    if (is_reject)\n        res = JS_GetException(ctx);\n    func = argv[is_reject];\n    /* as an extension, we support undefined as value to avoid\n       creating a dummy promise in the 'await' implementation of async\n       functions */\n    if (!JS_IsUndefined(func)) {\n        res2 = JS_Call(ctx, func, JS_UNDEFINED,\n                       1, (JSValueConst *)&res);\n    } else {\n        res2 = JS_UNDEFINED;\n    }\n    JS_FreeValue(ctx, res);\n\n    return res2;\n}\n\nvoid JS_SetHostPromiseRejectionTracker(JSRuntime *rt,\n                                       JSHostPromiseRejectionTracker *cb,\n                                       void *opaque)\n{\n    rt->host_promise_rejection_tracker = cb;\n    rt->host_promise_rejection_tracker_opaque = opaque;\n}\n\nstatic void fulfill_or_reject_promise(JSContext *ctx, JSValueConst promise,\n                                      JSValueConst value, BOOL is_reject)\n{\n    JSPromiseData *s = JS_GetOpaque(promise, JS_CLASS_PROMISE);\n    struct list_head *el, *el1;\n    JSPromiseReactionData *rd;\n    JSValueConst args[5];\n\n    if (!s || s->promise_state != JS_PROMISE_PENDING)\n        return; /* should never happen */\n    set_value(ctx, &s->promise_result, JS_DupValue(ctx, value));\n    s->promise_state = JS_PROMISE_FULFILLED + is_reject;\n#ifdef DUMP_PROMISE\n    printf(\"fulfill_or_reject_promise: is_reject=%d\\n\", is_reject);\n#endif\n    if (s->promise_state == JS_PROMISE_REJECTED && !s->is_handled) {\n        JSRuntime *rt = ctx->rt;\n        if (rt->host_promise_rejection_tracker) {\n            rt->host_promise_rejection_tracker(ctx, promise, value, FALSE,\n                                               rt->host_promise_rejection_tracker_opaque);\n        }\n    }\n\n    list_for_each_safe(el, el1, &s->promise_reactions[is_reject]) {\n        rd = list_entry(el, JSPromiseReactionData, link);\n        args[0] = rd->resolving_funcs[0];\n        args[1] = rd->resolving_funcs[1];\n        args[2] = rd->handler;\n        args[3] = JS_NewBool(ctx, is_reject);\n        args[4] = value;\n        JS_EnqueueJob(ctx, promise_reaction_job, 5, args);\n        list_del(&rd->link);\n        promise_reaction_data_free(ctx->rt, rd);\n    }\n\n    list_for_each_safe(el, el1, &s->promise_reactions[1 - is_reject]) {\n        rd = list_entry(el, JSPromiseReactionData, link);\n        list_del(&rd->link);\n        promise_reaction_data_free(ctx->rt, rd);\n    }\n}\n\nstatic void reject_promise(JSContext *ctx, JSValueConst promise,\n                           JSValueConst value)\n{\n    fulfill_or_reject_promise(ctx, promise, value, TRUE);\n}\n\nstatic JSValue js_promise_resolve_thenable_job(JSContext *ctx,\n                                               int argc, JSValueConst *argv)\n{\n    JSValueConst promise, thenable, then;\n    JSValue args[2], res;\n\n#ifdef DUMP_PROMISE\n    printf(\"js_promise_resolve_thenable_job\\n\");\n#endif\n    assert(argc == 3);\n    promise = argv[0];\n    thenable = argv[1];\n    then = argv[2];\n    if (js_create_resolving_functions(ctx, args, promise) < 0)\n        return JS_EXCEPTION;\n    res = JS_Call(ctx, then, thenable, 2, (JSValueConst *)args);\n    if (JS_IsException(res)) {\n        JSValue error = JS_GetException(ctx);\n        res = JS_Call(ctx, args[1], JS_UNDEFINED, 1, (JSValueConst *)&error);\n        JS_FreeValue(ctx, error);\n    }\n    JS_FreeValue(ctx, args[0]);\n    JS_FreeValue(ctx, args[1]);\n    return res;\n}\n\nstatic void js_promise_resolve_function_free_resolved(JSRuntime *rt,\n                                                      JSPromiseFunctionDataResolved *sr)\n{\n    if (--sr->ref_count == 0) {\n        js_free_rt(rt, sr);\n    }\n}\n\nstatic int js_create_resolving_functions(JSContext *ctx,\n                                         JSValue *resolving_funcs,\n                                         JSValueConst promise)\n\n{\n    JSValue obj;\n    JSPromiseFunctionData *s;\n    JSPromiseFunctionDataResolved *sr;\n    int i, ret;\n\n    sr = js_malloc(ctx, sizeof(*sr));\n    if (!sr)\n        return -1;\n    sr->ref_count = 1;\n    sr->already_resolved = FALSE; /* must be shared between the two functions */\n    ret = 0;\n    for(i = 0; i < 2; i++) {\n        obj = JS_NewObjectProtoClass(ctx, ctx->function_proto,\n                                     JS_CLASS_PROMISE_RESOLVE_FUNCTION + i);\n        if (JS_IsException(obj))\n            goto fail;\n        s = js_malloc(ctx, sizeof(*s));\n        if (!s) {\n            JS_FreeValue(ctx, obj);\n        fail:\n\n            if (i != 0)\n                JS_FreeValue(ctx, resolving_funcs[0]);\n            ret = -1;\n            break;\n        }\n        sr->ref_count++;\n        s->presolved = sr;\n        s->promise = JS_DupValue(ctx, promise);\n        JS_SetOpaque(obj, s);\n        js_function_set_properties(ctx, obj, JS_ATOM_empty_string, 1);\n        resolving_funcs[i] = obj;\n    }\n    js_promise_resolve_function_free_resolved(ctx->rt, sr);\n    return ret;\n}\n\nstatic void js_promise_resolve_function_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSPromiseFunctionData *s = JS_VALUE_GET_OBJ(val)->u.promise_function_data;\n    if (s) {\n        js_promise_resolve_function_free_resolved(rt, s->presolved);\n        JS_FreeValueRT(rt, s->promise);\n        js_free_rt(rt, s);\n    }\n}\n\nstatic void js_promise_resolve_function_mark(JSRuntime *rt, JSValueConst val,\n                                             JS_MarkFunc *mark_func)\n{\n    JSPromiseFunctionData *s = JS_VALUE_GET_OBJ(val)->u.promise_function_data;\n    if (s) {\n        JS_MarkValue(rt, s->promise, mark_func);\n    }\n}\n\nstatic JSValue js_promise_resolve_function_call(JSContext *ctx,\n                                                JSValueConst func_obj,\n                                                JSValueConst this_val,\n                                                int argc, JSValueConst *argv,\n                                                int flags)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(func_obj);\n    JSPromiseFunctionData *s;\n    JSValueConst resolution, args[3];\n    JSValue then;\n    BOOL is_reject;\n\n    s = p->u.promise_function_data;\n    if (!s || s->presolved->already_resolved)\n        return JS_UNDEFINED;\n    s->presolved->already_resolved = TRUE;\n    is_reject = p->class_id - JS_CLASS_PROMISE_RESOLVE_FUNCTION;\n    if (argc > 0)\n        resolution = argv[0];\n    else\n        resolution = JS_UNDEFINED;\n#ifdef DUMP_PROMISE\n    printf(\"js_promise_resolving_function_call: is_reject=%d resolution=\", is_reject);\n    JS_DumpValue(ctx, resolution);\n    printf(\"\\n\");\n#endif\n    if (is_reject || !JS_IsObject(resolution)) {\n        goto done;\n    } else if (js_same_value(ctx, resolution, s->promise)) {\n        JS_ThrowTypeError(ctx, \"promise self resolution\");\n        goto fail_reject;\n    }\n    then = JS_GetProperty(ctx, resolution, JS_ATOM_then);\n    if (JS_IsException(then)) {\n        JSValue error;\n    fail_reject:\n        error = JS_GetException(ctx);\n        reject_promise(ctx, s->promise, error);\n        JS_FreeValue(ctx, error);\n    } else if (!JS_IsFunction(ctx, then)) {\n        JS_FreeValue(ctx, then);\n    done:\n        fulfill_or_reject_promise(ctx, s->promise, resolution, is_reject);\n    } else {\n        args[0] = s->promise;\n        args[1] = resolution;\n        args[2] = then;\n        JS_EnqueueJob(ctx, js_promise_resolve_thenable_job, 3, args);\n        JS_FreeValue(ctx, then);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic void js_promise_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSPromiseData *s = JS_GetOpaque(val, JS_CLASS_PROMISE);\n    struct list_head *el, *el1;\n    int i;\n\n    if (!s)\n        return;\n    for(i = 0; i < 2; i++) {\n        list_for_each_safe(el, el1, &s->promise_reactions[i]) {\n            JSPromiseReactionData *rd =\n                list_entry(el, JSPromiseReactionData, link);\n            promise_reaction_data_free(rt, rd);\n        }\n    }\n    JS_FreeValueRT(rt, s->promise_result);\n    js_free_rt(rt, s);\n}\n\nstatic void js_promise_mark(JSRuntime *rt, JSValueConst val,\n                            JS_MarkFunc *mark_func)\n{\n    JSPromiseData *s = JS_GetOpaque(val, JS_CLASS_PROMISE);\n    struct list_head *el;\n    int i;\n\n    if (!s)\n        return;\n    for(i = 0; i < 2; i++) {\n        list_for_each(el, &s->promise_reactions[i]) {\n            JSPromiseReactionData *rd =\n                list_entry(el, JSPromiseReactionData, link);\n            JS_MarkValue(rt, rd->resolving_funcs[0], mark_func);\n            JS_MarkValue(rt, rd->resolving_funcs[1], mark_func);\n            JS_MarkValue(rt, rd->handler, mark_func);\n        }\n    }\n    JS_MarkValue(rt, s->promise_result, mark_func);\n}\n\nstatic JSValue js_promise_constructor(JSContext *ctx, JSValueConst new_target,\n                                      int argc, JSValueConst *argv)\n{\n    JSValueConst executor;\n    JSValue obj;\n    JSPromiseData *s;\n    JSValue args[2], ret;\n    int i;\n\n    executor = argv[0];\n    if (check_function(ctx, executor))\n        return JS_EXCEPTION;\n    obj = js_create_from_ctor(ctx, new_target, JS_CLASS_PROMISE);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s)\n        goto fail;\n    s->promise_state = JS_PROMISE_PENDING;\n    s->is_handled = FALSE;\n    for(i = 0; i < 2; i++)\n        init_list_head(&s->promise_reactions[i]);\n    s->promise_result = JS_UNDEFINED;\n    JS_SetOpaque(obj, s);\n    if (js_create_resolving_functions(ctx, args, obj))\n        goto fail;\n    ret = JS_Call(ctx, executor, JS_UNDEFINED, 2, (JSValueConst *)args);\n    if (JS_IsException(ret)) {\n        JSValue ret2, error;\n        error = JS_GetException(ctx);\n        ret2 = JS_Call(ctx, args[1], JS_UNDEFINED, 1, (JSValueConst *)&error);\n        JS_FreeValue(ctx, error);\n        if (JS_IsException(ret2))\n            goto fail1;\n        JS_FreeValue(ctx, ret2);\n    }\n    JS_FreeValue(ctx, ret);\n    JS_FreeValue(ctx, args[0]);\n    JS_FreeValue(ctx, args[1]);\n    return obj;\n fail1:\n    JS_FreeValue(ctx, args[0]);\n    JS_FreeValue(ctx, args[1]);\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_promise_executor(JSContext *ctx,\n                                   JSValueConst this_val,\n                                   int argc, JSValueConst *argv,\n                                   int magic, JSValue *func_data)\n{\n    int i;\n\n    for(i = 0; i < 2; i++) {\n        if (!JS_IsUndefined(func_data[i]))\n            return JS_ThrowTypeError(ctx, \"resolving function already set\");\n        func_data[i] = JS_DupValue(ctx, argv[i]);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_promise_executor_new(JSContext *ctx)\n{\n    JSValueConst func_data[2];\n\n    func_data[0] = JS_UNDEFINED;\n    func_data[1] = JS_UNDEFINED;\n    return JS_NewCFunctionData(ctx, js_promise_executor, 2,\n                               0, 2, func_data);\n}\n\nstatic JSValue js_new_promise_capability(JSContext *ctx,\n                                         JSValue *resolving_funcs,\n                                         JSValueConst ctor)\n{\n    JSValue executor, result_promise;\n    JSCFunctionDataRecord *s;\n    int i;\n\n    executor = js_promise_executor_new(ctx);\n    if (JS_IsException(executor))\n        return executor;\n\n    if (JS_IsUndefined(ctor)) {\n        result_promise = js_promise_constructor(ctx, ctor, 1,\n                                                (JSValueConst *)&executor);\n    } else {\n        result_promise = JS_CallConstructor(ctx, ctor, 1,\n                                            (JSValueConst *)&executor);\n    }\n    if (JS_IsException(result_promise))\n        goto fail;\n    s = JS_GetOpaque(executor, JS_CLASS_C_FUNCTION_DATA);\n    for(i = 0; i < 2; i++) {\n        if (check_function(ctx, s->data[i]))\n            goto fail;\n    }\n    for(i = 0; i < 2; i++)\n        resolving_funcs[i] = JS_DupValue(ctx, s->data[i]);\n    JS_FreeValue(ctx, executor);\n    return result_promise;\n fail:\n    JS_FreeValue(ctx, executor);\n    JS_FreeValue(ctx, result_promise);\n    return JS_EXCEPTION;\n}\n\nJSValue JS_NewPromiseCapability(JSContext *ctx, JSValue *resolving_funcs)\n{\n    return js_new_promise_capability(ctx, resolving_funcs, JS_UNDEFINED);\n}\n\nstatic JSValue js_promise_resolve(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv, int magic)\n{\n    JSValue result_promise, resolving_funcs[2], ret;\n    BOOL is_reject = magic;\n\n    if (!JS_IsObject(this_val))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    if (!is_reject && JS_GetOpaque(argv[0], JS_CLASS_PROMISE)) {\n        JSValue ctor;\n        BOOL is_same;\n        ctor = JS_GetProperty(ctx, argv[0], JS_ATOM_constructor);\n        if (JS_IsException(ctor))\n            return ctor;\n        is_same = js_same_value(ctx, ctor, this_val);\n        JS_FreeValue(ctx, ctor);\n        if (is_same)\n            return JS_DupValue(ctx, argv[0]);\n    }\n    result_promise = js_new_promise_capability(ctx, resolving_funcs, this_val);\n    if (JS_IsException(result_promise))\n        return result_promise;\n    ret = JS_Call(ctx, resolving_funcs[is_reject], JS_UNDEFINED, 1, argv);\n    JS_FreeValue(ctx, resolving_funcs[0]);\n    JS_FreeValue(ctx, resolving_funcs[1]);\n    if (JS_IsException(ret)) {\n        JS_FreeValue(ctx, result_promise);\n        return ret;\n    }\n    JS_FreeValue(ctx, ret);\n    return result_promise;\n}\n\n#if 0\nstatic JSValue js_promise___newPromiseCapability(JSContext *ctx,\n                                                 JSValueConst this_val,\n                                                 int argc, JSValueConst *argv)\n{\n    JSValue result_promise, resolving_funcs[2], obj;\n    JSValueConst ctor;\n    ctor = argv[0];\n    if (!JS_IsObject(ctor))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    result_promise = js_new_promise_capability(ctx, resolving_funcs, ctor);\n    if (JS_IsException(result_promise))\n        return result_promise;\n    obj = JS_NewObject(ctx);\n    if (JS_IsException(obj)) {\n        JS_FreeValue(ctx, resolving_funcs[0]);\n        JS_FreeValue(ctx, resolving_funcs[1]);\n        JS_FreeValue(ctx, result_promise);\n        return JS_EXCEPTION;\n    }\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_promise, result_promise, JS_PROP_C_W_E);\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_resolve, resolving_funcs[0], JS_PROP_C_W_E);\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_reject, resolving_funcs[1], JS_PROP_C_W_E);\n    return obj;\n}\n#endif\n\nstatic __exception int remainingElementsCount_add(JSContext *ctx,\n                                                  JSValueConst resolve_element_env,\n                                                  int addend)\n{\n    JSValue val;\n    int remainingElementsCount;\n\n    val = JS_GetPropertyUint32(ctx, resolve_element_env, 0);\n    if (JS_IsException(val))\n        return -1;\n    if (JS_ToInt32Free(ctx, &remainingElementsCount, val))\n        return -1;\n    remainingElementsCount += addend;\n    if (JS_SetPropertyUint32(ctx, resolve_element_env, 0,\n                             JS_NewInt32(ctx, remainingElementsCount)) < 0)\n        return -1;\n    return (remainingElementsCount == 0);\n}\n\n#define PROMISE_MAGIC_all        0\n#define PROMISE_MAGIC_allSettled 1\n#define PROMISE_MAGIC_any        2\n\nstatic JSValue js_promise_all_resolve_element(JSContext *ctx,\n                                              JSValueConst this_val,\n                                              int argc, JSValueConst *argv,\n                                              int magic,\n                                              JSValue *func_data)\n{\n    int resolve_type = magic & 3;\n    int is_reject = magic & 4;\n    BOOL alreadyCalled = JS_ToBool(ctx, func_data[0]);\n    JSValueConst values = func_data[2];\n    JSValueConst resolve = func_data[3];\n    JSValueConst resolve_element_env = func_data[4];\n    JSValue ret, obj;\n    int is_zero, index;\n    \n    if (JS_ToInt32(ctx, &index, func_data[1]))\n        return JS_EXCEPTION;\n    if (alreadyCalled)\n        return JS_UNDEFINED;\n    func_data[0] = JS_NewBool(ctx, TRUE);\n\n    if (resolve_type == PROMISE_MAGIC_allSettled) {\n        JSValue str;\n        \n        obj = JS_NewObject(ctx);\n        if (JS_IsException(obj))\n            return JS_EXCEPTION;\n        str = JS_NewString(ctx, is_reject ? \"rejected\" : \"fulfilled\");\n        if (JS_IsException(str))\n            goto fail1;\n        if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_status,\n                                   str,\n                                   JS_PROP_C_W_E) < 0)\n            goto fail1;\n        if (JS_DefinePropertyValue(ctx, obj,\n                                   is_reject ? JS_ATOM_reason : JS_ATOM_value,\n                                   JS_DupValue(ctx, argv[0]),\n                                   JS_PROP_C_W_E) < 0) {\n        fail1:\n            JS_FreeValue(ctx, obj);\n            return JS_EXCEPTION;\n        }\n    } else {\n        obj = JS_DupValue(ctx, argv[0]);\n    }\n    if (JS_DefinePropertyValueUint32(ctx, values, index,\n                                     obj, JS_PROP_C_W_E) < 0)\n        return JS_EXCEPTION;\n    \n    is_zero = remainingElementsCount_add(ctx, resolve_element_env, -1);\n    if (is_zero < 0)\n        return JS_EXCEPTION;\n    if (is_zero) {\n        if (resolve_type == PROMISE_MAGIC_any) {\n            JSValue error;\n            error = js_aggregate_error_constructor(ctx, values);\n            if (JS_IsException(error))\n                return JS_EXCEPTION;\n            ret = JS_Call(ctx, resolve, JS_UNDEFINED, 1, (JSValueConst *)&error);\n            JS_FreeValue(ctx, error);\n        } else {\n            ret = JS_Call(ctx, resolve, JS_UNDEFINED, 1, (JSValueConst *)&values);\n        }\n        if (JS_IsException(ret))\n            return ret;\n        JS_FreeValue(ctx, ret);\n    }\n    return JS_UNDEFINED;\n}\n\n/* magic = 0: Promise.all 1: Promise.allSettled */\nstatic JSValue js_promise_all(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int magic)\n{\n    JSValue result_promise, resolving_funcs[2], item, next_promise, ret;\n    JSValue next_method = JS_UNDEFINED, values = JS_UNDEFINED;\n    JSValue resolve_element_env = JS_UNDEFINED, resolve_element, reject_element;\n    JSValue promise_resolve = JS_UNDEFINED, iter = JS_UNDEFINED;\n    JSValueConst then_args[2], resolve_element_data[5];\n    BOOL done;\n    int index, is_zero, is_promise_any = (magic == PROMISE_MAGIC_any);\n    \n    if (!JS_IsObject(this_val))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    result_promise = js_new_promise_capability(ctx, resolving_funcs, this_val);\n    if (JS_IsException(result_promise))\n        return result_promise;\n    promise_resolve = JS_GetProperty(ctx, this_val, JS_ATOM_resolve);\n    if (JS_IsException(promise_resolve) ||\n        check_function(ctx, promise_resolve))\n        goto fail_reject;\n    iter = JS_GetIterator(ctx, argv[0], FALSE);\n    if (JS_IsException(iter)) {\n        JSValue error;\n    fail_reject:\n        error = JS_GetException(ctx);\n        ret = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED, 1,\n                       (JSValueConst *)&error);\n        JS_FreeValue(ctx, error);\n        if (JS_IsException(ret))\n            goto fail;\n        JS_FreeValue(ctx, ret);\n    } else {\n        next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);\n        if (JS_IsException(next_method))\n            goto fail_reject;\n        values = JS_NewArray(ctx);\n        if (JS_IsException(values))\n            goto fail_reject;\n        resolve_element_env = JS_NewArray(ctx);\n        if (JS_IsException(resolve_element_env))\n            goto fail_reject;\n        /* remainingElementsCount field */\n        if (JS_DefinePropertyValueUint32(ctx, resolve_element_env, 0,\n                                         JS_NewInt32(ctx, 1),\n                                         JS_PROP_CONFIGURABLE | JS_PROP_ENUMERABLE | JS_PROP_WRITABLE) < 0)\n            goto fail_reject;\n        \n        index = 0;\n        for(;;) {\n            /* XXX: conformance: should close the iterator if error on 'done'\n               access, but not on 'value' access */\n            item = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);\n            if (JS_IsException(item))\n                goto fail_reject;\n            if (done)\n                break;\n            next_promise = JS_Call(ctx, promise_resolve, \n                                   this_val, 1, (JSValueConst *)&item);\n            JS_FreeValue(ctx, item);\n            if (JS_IsException(next_promise)) {\n            fail_reject1:\n                JS_IteratorClose(ctx, iter, TRUE);\n                goto fail_reject;\n            }\n            resolve_element_data[0] = JS_NewBool(ctx, FALSE);\n            resolve_element_data[1] = (JSValueConst)JS_NewInt32(ctx, index);\n            resolve_element_data[2] = values;\n            resolve_element_data[3] = resolving_funcs[is_promise_any];\n            resolve_element_data[4] = resolve_element_env;\n            resolve_element =\n                JS_NewCFunctionData(ctx, js_promise_all_resolve_element, 1,\n                                    magic, 5, resolve_element_data);\n            if (JS_IsException(resolve_element)) {\n                JS_FreeValue(ctx, next_promise);\n                goto fail_reject1;\n            }\n            \n            if (magic == PROMISE_MAGIC_allSettled) {\n                reject_element =\n                    JS_NewCFunctionData(ctx, js_promise_all_resolve_element, 1,\n                                        magic | 4, 5, resolve_element_data);\n                if (JS_IsException(reject_element)) {\n                    JS_FreeValue(ctx, next_promise);\n                    goto fail_reject1;\n                }\n            } else if (magic == PROMISE_MAGIC_any) {\n                if (JS_DefinePropertyValueUint32(ctx, values, index,\n                                                 JS_UNDEFINED, JS_PROP_C_W_E) < 0)\n                    goto fail_reject1;\n                reject_element = resolve_element;\n                resolve_element = JS_DupValue(ctx, resolving_funcs[0]);\n            } else {\n                reject_element = JS_DupValue(ctx, resolving_funcs[1]);\n            }\n\n            if (remainingElementsCount_add(ctx, resolve_element_env, 1) < 0) {\n                JS_FreeValue(ctx, next_promise);\n                JS_FreeValue(ctx, resolve_element);\n                JS_FreeValue(ctx, reject_element);\n                goto fail_reject1;\n            }\n\n            then_args[0] = resolve_element;\n            then_args[1] = reject_element;\n            ret = JS_InvokeFree(ctx, next_promise, JS_ATOM_then, 2, then_args);\n            JS_FreeValue(ctx, resolve_element);\n            JS_FreeValue(ctx, reject_element);\n            if (check_exception_free(ctx, ret))\n                goto fail_reject1;\n            index++;\n        }\n\n        is_zero = remainingElementsCount_add(ctx, resolve_element_env, -1);\n        if (is_zero < 0)\n            goto fail_reject;\n        if (is_zero) {\n            if (magic == PROMISE_MAGIC_any) {\n                JSValue error;\n                error = js_aggregate_error_constructor(ctx, values);\n                if (JS_IsException(error))\n                    goto fail_reject;\n                JS_FreeValue(ctx, values);\n                values = error;\n            }\n            ret = JS_Call(ctx, resolving_funcs[is_promise_any], JS_UNDEFINED,\n                          1, (JSValueConst *)&values);\n            if (check_exception_free(ctx, ret))\n                goto fail_reject;\n        }\n    }\n done:\n    JS_FreeValue(ctx, promise_resolve);\n    JS_FreeValue(ctx, resolve_element_env);\n    JS_FreeValue(ctx, values);\n    JS_FreeValue(ctx, next_method);\n    JS_FreeValue(ctx, iter);\n    JS_FreeValue(ctx, resolving_funcs[0]);\n    JS_FreeValue(ctx, resolving_funcs[1]);\n    return result_promise;\n fail:\n    JS_FreeValue(ctx, result_promise);\n    result_promise = JS_EXCEPTION;\n    goto done;\n}\n\nstatic JSValue js_promise_race(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    JSValue result_promise, resolving_funcs[2], item, next_promise, ret;\n    JSValue next_method = JS_UNDEFINED, iter = JS_UNDEFINED;\n    JSValue promise_resolve = JS_UNDEFINED;\n    BOOL done;\n\n    if (!JS_IsObject(this_val))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    result_promise = js_new_promise_capability(ctx, resolving_funcs, this_val);\n    if (JS_IsException(result_promise))\n        return result_promise;\n    promise_resolve = JS_GetProperty(ctx, this_val, JS_ATOM_resolve);\n    if (JS_IsException(promise_resolve) ||\n        check_function(ctx, promise_resolve))\n        goto fail_reject;\n    iter = JS_GetIterator(ctx, argv[0], FALSE);\n    if (JS_IsException(iter)) {\n        JSValue error;\n    fail_reject:\n        error = JS_GetException(ctx);\n        ret = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED, 1,\n                       (JSValueConst *)&error);\n        JS_FreeValue(ctx, error);\n        if (JS_IsException(ret))\n            goto fail;\n        JS_FreeValue(ctx, ret);\n    } else {\n        next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);\n        if (JS_IsException(next_method))\n            goto fail_reject;\n\n        for(;;) {\n            /* XXX: conformance: should close the iterator if error on 'done'\n               access, but not on 'value' access */\n            item = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);\n            if (JS_IsException(item))\n                goto fail_reject;\n            if (done)\n                break;\n            next_promise = JS_Call(ctx, promise_resolve,\n                                   this_val, 1, (JSValueConst *)&item);\n            JS_FreeValue(ctx, item);\n            if (JS_IsException(next_promise)) {\n            fail_reject1:\n                JS_IteratorClose(ctx, iter, TRUE);\n                goto fail_reject;\n            }\n            ret = JS_InvokeFree(ctx, next_promise, JS_ATOM_then, 2,\n                                (JSValueConst *)resolving_funcs);\n            if (check_exception_free(ctx, ret))\n                goto fail_reject1;\n        }\n    }\n done:\n    JS_FreeValue(ctx, promise_resolve);\n    JS_FreeValue(ctx, next_method);\n    JS_FreeValue(ctx, iter);\n    JS_FreeValue(ctx, resolving_funcs[0]);\n    JS_FreeValue(ctx, resolving_funcs[1]);\n    return result_promise;\n fail:\n    //JS_FreeValue(ctx, next_method); // why not???\n    JS_FreeValue(ctx, result_promise);\n    result_promise = JS_EXCEPTION;\n    goto done;\n}\n\nstatic __exception int perform_promise_then(JSContext *ctx,\n                                            JSValueConst promise,\n                                            JSValueConst *resolve_reject,\n                                            JSValueConst *cap_resolving_funcs)\n{\n    JSPromiseData *s = JS_GetOpaque(promise, JS_CLASS_PROMISE);\n    JSPromiseReactionData *rd_array[2], *rd;\n    int i, j;\n\n    rd_array[0] = NULL;\n    rd_array[1] = NULL;\n    for(i = 0; i < 2; i++) {\n        JSValueConst handler;\n        rd = js_mallocz(ctx, sizeof(*rd));\n        if (!rd) {\n            if (i == 1)\n                promise_reaction_data_free(ctx->rt, rd_array[0]);\n            return -1;\n        }\n        for(j = 0; j < 2; j++)\n            rd->resolving_funcs[j] = JS_DupValue(ctx, cap_resolving_funcs[j]);\n        handler = resolve_reject[i];\n        if (!JS_IsFunction(ctx, handler))\n            handler = JS_UNDEFINED;\n        rd->handler = JS_DupValue(ctx, handler);\n        rd_array[i] = rd;\n    }\n\n    if (s->promise_state == JS_PROMISE_PENDING) {\n        for(i = 0; i < 2; i++)\n            list_add_tail(&rd_array[i]->link, &s->promise_reactions[i]);\n    } else {\n        JSValueConst args[5];\n        if (s->promise_state == JS_PROMISE_REJECTED && !s->is_handled) {\n            JSRuntime *rt = ctx->rt;\n            if (rt->host_promise_rejection_tracker) {\n                rt->host_promise_rejection_tracker(ctx, promise, s->promise_result,\n                                                   TRUE, rt->host_promise_rejection_tracker_opaque);\n            }\n        }\n        i = s->promise_state - JS_PROMISE_FULFILLED;\n        rd = rd_array[i];\n        args[0] = rd->resolving_funcs[0];\n        args[1] = rd->resolving_funcs[1];\n        args[2] = rd->handler;\n        args[3] = JS_NewBool(ctx, i);\n        args[4] = s->promise_result;\n        JS_EnqueueJob(ctx, promise_reaction_job, 5, args);\n        for(i = 0; i < 2; i++)\n            promise_reaction_data_free(ctx->rt, rd_array[i]);\n    }\n    s->is_handled = TRUE;\n    return 0;\n}\n\nstatic JSValue js_promise_then(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    JSValue ctor, result_promise, resolving_funcs[2];\n    JSPromiseData *s;\n    int i, ret;\n\n    s = JS_GetOpaque2(ctx, this_val, JS_CLASS_PROMISE);\n    if (!s)\n        return JS_EXCEPTION;\n\n    ctor = JS_SpeciesConstructor(ctx, this_val, JS_UNDEFINED);\n    if (JS_IsException(ctor))\n        return ctor;\n    result_promise = js_new_promise_capability(ctx, resolving_funcs, ctor);\n    JS_FreeValue(ctx, ctor);\n    if (JS_IsException(result_promise))\n        return result_promise;\n    ret = perform_promise_then(ctx, this_val, argv,\n                               (JSValueConst *)resolving_funcs);\n    for(i = 0; i < 2; i++)\n        JS_FreeValue(ctx, resolving_funcs[i]);\n    if (ret) {\n        JS_FreeValue(ctx, result_promise);\n        return JS_EXCEPTION;\n    }\n    return result_promise;\n}\n\nstatic JSValue js_promise_catch(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValueConst args[2];\n    args[0] = JS_UNDEFINED;\n    args[1] = argv[0];\n    return JS_Invoke(ctx, this_val, JS_ATOM_then, 2, args);\n}\n\nstatic JSValue js_promise_finally_value_thunk(JSContext *ctx, JSValueConst this_val,\n                                              int argc, JSValueConst *argv,\n                                              int magic, JSValue *func_data)\n{\n    return JS_DupValue(ctx, func_data[0]);\n}\n\nstatic JSValue js_promise_finally_thrower(JSContext *ctx, JSValueConst this_val,\n                                          int argc, JSValueConst *argv,\n                                          int magic, JSValue *func_data)\n{\n    return JS_Throw(ctx, JS_DupValue(ctx, func_data[0]));\n}\n\nstatic JSValue js_promise_then_finally_func(JSContext *ctx, JSValueConst this_val,\n                                            int argc, JSValueConst *argv,\n                                            int magic, JSValue *func_data)\n{\n    JSValueConst ctor = func_data[0];\n    JSValueConst onFinally = func_data[1];\n    JSValue res, promise, ret, then_func;\n\n    res = JS_Call(ctx, onFinally, JS_UNDEFINED, 0, NULL);\n    if (JS_IsException(res))\n        return res;\n    promise = js_promise_resolve(ctx, ctor, 1, (JSValueConst *)&res, 0);\n    JS_FreeValue(ctx, res);\n    if (JS_IsException(promise))\n        return promise;\n    if (magic == 0) {\n        then_func = JS_NewCFunctionData(ctx, js_promise_finally_value_thunk, 0,\n                                        0, 1, argv);\n    } else {\n        then_func = JS_NewCFunctionData(ctx, js_promise_finally_thrower, 0,\n                                        0, 1, argv);\n    }\n    if (JS_IsException(then_func)) {\n        JS_FreeValue(ctx, promise);\n        return then_func;\n    }\n    ret = JS_InvokeFree(ctx, promise, JS_ATOM_then, 1, (JSValueConst *)&then_func);\n    JS_FreeValue(ctx, then_func);\n    return ret;\n}\n\nstatic JSValue js_promise_finally(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    JSValueConst onFinally = argv[0];\n    JSValue ctor, ret;\n    JSValue then_funcs[2];\n    JSValueConst func_data[2];\n    int i;\n\n    ctor = JS_SpeciesConstructor(ctx, this_val, JS_UNDEFINED);\n    if (JS_IsException(ctor))\n        return ctor;\n    if (!JS_IsFunction(ctx, onFinally)) {\n        then_funcs[0] = JS_DupValue(ctx, onFinally);\n        then_funcs[1] = JS_DupValue(ctx, onFinally);\n    } else {\n        func_data[0] = ctor;\n        func_data[1] = onFinally;\n        for(i = 0; i < 2; i++) {\n            then_funcs[i] = JS_NewCFunctionData(ctx, js_promise_then_finally_func, 1, i, 2, func_data);\n            if (JS_IsException(then_funcs[i])) {\n                if (i == 1)\n                    JS_FreeValue(ctx, then_funcs[0]);\n                JS_FreeValue(ctx, ctor);\n                return JS_EXCEPTION;\n            }\n        }\n    }\n    JS_FreeValue(ctx, ctor);\n    ret = JS_Invoke(ctx, this_val, JS_ATOM_then, 2, (JSValueConst *)then_funcs);\n    JS_FreeValue(ctx, then_funcs[0]);\n    JS_FreeValue(ctx, then_funcs[1]);\n    return ret;\n}\n\nstatic const JSCFunctionListEntry js_promise_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"resolve\", 1, js_promise_resolve, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"reject\", 1, js_promise_resolve, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"all\", 1, js_promise_all, PROMISE_MAGIC_all ),\n    JS_CFUNC_MAGIC_DEF(\"allSettled\", 1, js_promise_all, PROMISE_MAGIC_allSettled ),\n    JS_CFUNC_MAGIC_DEF(\"any\", 1, js_promise_all, PROMISE_MAGIC_any ),\n    JS_CFUNC_DEF(\"race\", 1, js_promise_race ),\n    //JS_CFUNC_DEF(\"__newPromiseCapability\", 1, js_promise___newPromiseCapability ),\n    JS_CGETSET_DEF(\"[Symbol.species]\", js_get_this, NULL),\n};\n\nstatic const JSCFunctionListEntry js_promise_proto_funcs[] = {\n    JS_CFUNC_DEF(\"then\", 2, js_promise_then ),\n    JS_CFUNC_DEF(\"catch\", 1, js_promise_catch ),\n    JS_CFUNC_DEF(\"finally\", 1, js_promise_finally ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Promise\", JS_PROP_CONFIGURABLE ),\n};\n\n/* AsyncFunction */\nstatic const JSCFunctionListEntry js_async_function_proto_funcs[] = {\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"AsyncFunction\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic JSValue js_async_from_sync_iterator_unwrap(JSContext *ctx,\n                                                  JSValueConst this_val,\n                                                  int argc, JSValueConst *argv,\n                                                  int magic, JSValue *func_data)\n{\n    return js_create_iterator_result(ctx, JS_DupValue(ctx, argv[0]),\n                                     JS_ToBool(ctx, func_data[0]));\n}\n\nstatic JSValue js_async_from_sync_iterator_unwrap_func_create(JSContext *ctx,\n                                                              BOOL done)\n{\n    JSValueConst func_data[1];\n\n    func_data[0] = (JSValueConst)JS_NewBool(ctx, done);\n    return JS_NewCFunctionData(ctx, js_async_from_sync_iterator_unwrap,\n                               1, 0, 1, func_data);\n}\n\n/* AsyncIteratorPrototype */\n\nstatic const JSCFunctionListEntry js_async_iterator_proto_funcs[] = {\n    JS_CFUNC_DEF(\"[Symbol.asyncIterator]\", 0, js_iterator_proto_iterator ),\n};\n\n/* AsyncFromSyncIteratorPrototype */\n\ntypedef struct JSAsyncFromSyncIteratorData {\n    JSValue sync_iter;\n    JSValue next_method;\n} JSAsyncFromSyncIteratorData;\n\nstatic void js_async_from_sync_iterator_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSAsyncFromSyncIteratorData *s =\n        JS_GetOpaque(val, JS_CLASS_ASYNC_FROM_SYNC_ITERATOR);\n    if (s) {\n        JS_FreeValueRT(rt, s->sync_iter);\n        JS_FreeValueRT(rt, s->next_method);\n        js_free_rt(rt, s);\n    }\n}\n\nstatic void js_async_from_sync_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                             JS_MarkFunc *mark_func)\n{\n    JSAsyncFromSyncIteratorData *s =\n        JS_GetOpaque(val, JS_CLASS_ASYNC_FROM_SYNC_ITERATOR);\n    if (s) {\n        JS_MarkValue(rt, s->sync_iter, mark_func);\n        JS_MarkValue(rt, s->next_method, mark_func);\n    }\n}\n\nstatic JSValue JS_CreateAsyncFromSyncIterator(JSContext *ctx,\n                                              JSValueConst sync_iter)\n{\n    JSValue async_iter, next_method;\n    JSAsyncFromSyncIteratorData *s;\n\n    next_method = JS_GetProperty(ctx, sync_iter, JS_ATOM_next);\n    if (JS_IsException(next_method))\n        return JS_EXCEPTION;\n    async_iter = JS_NewObjectClass(ctx, JS_CLASS_ASYNC_FROM_SYNC_ITERATOR);\n    if (JS_IsException(async_iter)) {\n        JS_FreeValue(ctx, next_method);\n        return async_iter;\n    }\n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s) {\n        JS_FreeValue(ctx, async_iter);\n        JS_FreeValue(ctx, next_method);\n        return JS_EXCEPTION;\n    }\n    s->sync_iter = JS_DupValue(ctx, sync_iter);\n    s->next_method = next_method;\n    JS_SetOpaque(async_iter, s);\n    return async_iter;\n}\n\nstatic JSValue js_async_from_sync_iterator_next(JSContext *ctx, JSValueConst this_val,\n                                                int argc, JSValueConst *argv,\n                                                int magic)\n{\n    JSValue promise, resolving_funcs[2], value, err, method;\n    JSAsyncFromSyncIteratorData *s;\n    int done;\n    int is_reject;\n\n    promise = JS_NewPromiseCapability(ctx, resolving_funcs);\n    if (JS_IsException(promise))\n        return JS_EXCEPTION;\n    s = JS_GetOpaque(this_val, JS_CLASS_ASYNC_FROM_SYNC_ITERATOR);\n    if (!s) {\n        JS_ThrowTypeError(ctx, \"not an Async-from-Sync Iterator\");\n        goto reject;\n    }\n\n    if (magic == GEN_MAGIC_NEXT) {\n        method = JS_DupValue(ctx, s->next_method);\n    } else {\n        method = JS_GetProperty(ctx, s->sync_iter,\n                                magic == GEN_MAGIC_RETURN ? JS_ATOM_return :\n                                JS_ATOM_throw);\n        if (JS_IsException(method))\n            goto reject;\n        if (JS_IsUndefined(method) || JS_IsNull(method)) {\n            if (magic == GEN_MAGIC_RETURN) {\n                err = js_create_iterator_result(ctx, JS_DupValue(ctx, argv[0]), TRUE);\n                is_reject = 0;\n            } else {\n                err = JS_DupValue(ctx, argv[0]);\n                is_reject = 1;\n            }\n            goto done_resolve;\n        }\n    }\n    value = JS_IteratorNext2(ctx, s->sync_iter, method,\n                             argc >= 1 ? 1 : 0, argv, &done);\n    JS_FreeValue(ctx, method);\n    if (JS_IsException(value))\n        goto reject;\n    if (done == 2) {\n        JSValue obj = value;\n        value = JS_IteratorGetCompleteValue(ctx, obj, &done);\n        JS_FreeValue(ctx, obj);\n        if (JS_IsException(value))\n            goto reject;\n    }\n\n    if (JS_IsException(value)) {\n        JSValue res2;\n    reject:\n        err = JS_GetException(ctx);\n        is_reject = 1;\n    done_resolve:\n        res2 = JS_Call(ctx, resolving_funcs[is_reject], JS_UNDEFINED,\n                       1, (JSValueConst *)&err);\n        JS_FreeValue(ctx, err);\n        JS_FreeValue(ctx, res2);\n        JS_FreeValue(ctx, resolving_funcs[0]);\n        JS_FreeValue(ctx, resolving_funcs[1]);\n        return promise;\n    }\n    {\n        JSValue value_wrapper_promise, resolve_reject[2];\n        int res;\n\n        value_wrapper_promise = js_promise_resolve(ctx, ctx->promise_ctor,\n                                                   1, (JSValueConst *)&value, 0);\n        if (JS_IsException(value_wrapper_promise)) {\n            JS_FreeValue(ctx, value);\n            goto reject;\n        }\n\n        resolve_reject[0] =\n            js_async_from_sync_iterator_unwrap_func_create(ctx, done);\n        if (JS_IsException(resolve_reject[0])) {\n            JS_FreeValue(ctx, value_wrapper_promise);\n            goto fail;\n        }\n        JS_FreeValue(ctx, value);\n        resolve_reject[1] = JS_UNDEFINED;\n\n        res = perform_promise_then(ctx, value_wrapper_promise,\n                                   (JSValueConst *)resolve_reject,\n                                   (JSValueConst *)resolving_funcs);\n        JS_FreeValue(ctx, resolve_reject[0]);\n        JS_FreeValue(ctx, value_wrapper_promise);\n        JS_FreeValue(ctx, resolving_funcs[0]);\n        JS_FreeValue(ctx, resolving_funcs[1]);\n        if (res) {\n            JS_FreeValue(ctx, promise);\n            return JS_EXCEPTION;\n        }\n    }\n    return promise;\n fail:\n    JS_FreeValue(ctx, value);\n    JS_FreeValue(ctx, resolving_funcs[0]);\n    JS_FreeValue(ctx, resolving_funcs[1]);\n    JS_FreeValue(ctx, promise);\n    return JS_EXCEPTION;\n}\n\nstatic const JSCFunctionListEntry js_async_from_sync_iterator_proto_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"next\", 1, js_async_from_sync_iterator_next, GEN_MAGIC_NEXT ),\n    JS_CFUNC_MAGIC_DEF(\"return\", 1, js_async_from_sync_iterator_next, GEN_MAGIC_RETURN ),\n    JS_CFUNC_MAGIC_DEF(\"throw\", 1, js_async_from_sync_iterator_next, GEN_MAGIC_THROW ),\n};\n\n/* AsyncGeneratorFunction */\n\nstatic const JSCFunctionListEntry js_async_generator_function_proto_funcs[] = {\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"AsyncGeneratorFunction\", JS_PROP_CONFIGURABLE ),\n};\n\n/* AsyncGenerator prototype */\n\nstatic const JSCFunctionListEntry js_async_generator_proto_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"next\", 1, js_async_generator_next, GEN_MAGIC_NEXT ),\n    JS_CFUNC_MAGIC_DEF(\"return\", 1, js_async_generator_next, GEN_MAGIC_RETURN ),\n    JS_CFUNC_MAGIC_DEF(\"throw\", 1, js_async_generator_next, GEN_MAGIC_THROW ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"AsyncGenerator\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic JSClassShortDef const js_async_class_def[] = {\n    { JS_ATOM_Promise, js_promise_finalizer, js_promise_mark },                      /* JS_CLASS_PROMISE */\n    { JS_ATOM_PromiseResolveFunction, js_promise_resolve_function_finalizer, js_promise_resolve_function_mark }, /* JS_CLASS_PROMISE_RESOLVE_FUNCTION */\n    { JS_ATOM_PromiseRejectFunction, js_promise_resolve_function_finalizer, js_promise_resolve_function_mark }, /* JS_CLASS_PROMISE_REJECT_FUNCTION */\n    { JS_ATOM_AsyncFunction, js_bytecode_function_finalizer, js_bytecode_function_mark },  /* JS_CLASS_ASYNC_FUNCTION */\n    { JS_ATOM_AsyncFunctionResolve, js_async_function_resolve_finalizer, js_async_function_resolve_mark }, /* JS_CLASS_ASYNC_FUNCTION_RESOLVE */\n    { JS_ATOM_AsyncFunctionReject, js_async_function_resolve_finalizer, js_async_function_resolve_mark }, /* JS_CLASS_ASYNC_FUNCTION_REJECT */\n    { JS_ATOM_empty_string, js_async_from_sync_iterator_finalizer, js_async_from_sync_iterator_mark }, /* JS_CLASS_ASYNC_FROM_SYNC_ITERATOR */\n    { JS_ATOM_AsyncGeneratorFunction, js_bytecode_function_finalizer, js_bytecode_function_mark },  /* JS_CLASS_ASYNC_GENERATOR_FUNCTION */\n    { JS_ATOM_AsyncGenerator, js_async_generator_finalizer, js_async_generator_mark },  /* JS_CLASS_ASYNC_GENERATOR */\n};\n\nvoid JS_AddIntrinsicPromise(JSContext *ctx)\n{\n    JSRuntime *rt = ctx->rt;\n    JSValue obj1;\n\n    if (!JS_IsRegisteredClass(rt, JS_CLASS_PROMISE)) {\n        init_class_range(rt, js_async_class_def, JS_CLASS_PROMISE,\n                         countof(js_async_class_def));\n        rt->class_array[JS_CLASS_PROMISE_RESOLVE_FUNCTION].call = js_promise_resolve_function_call;\n        rt->class_array[JS_CLASS_PROMISE_REJECT_FUNCTION].call = js_promise_resolve_function_call;\n        rt->class_array[JS_CLASS_ASYNC_FUNCTION].call = js_async_function_call;\n        rt->class_array[JS_CLASS_ASYNC_FUNCTION_RESOLVE].call = js_async_function_resolve_call;\n        rt->class_array[JS_CLASS_ASYNC_FUNCTION_REJECT].call = js_async_function_resolve_call;\n        rt->class_array[JS_CLASS_ASYNC_GENERATOR_FUNCTION].call = js_async_generator_function_call;\n    }\n\n    /* Promise */\n    ctx->class_proto[JS_CLASS_PROMISE] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_PROMISE],\n                               js_promise_proto_funcs,\n                               countof(js_promise_proto_funcs));\n    obj1 = JS_NewCFunction2(ctx, js_promise_constructor, \"Promise\", 1,\n                            JS_CFUNC_constructor, 0);\n    ctx->promise_ctor = JS_DupValue(ctx, obj1);\n    JS_SetPropertyFunctionList(ctx, obj1,\n                               js_promise_funcs,\n                               countof(js_promise_funcs));\n    JS_NewGlobalCConstructor2(ctx, obj1, \"Promise\",\n                              ctx->class_proto[JS_CLASS_PROMISE]);\n\n    /* AsyncFunction */\n    ctx->class_proto[JS_CLASS_ASYNC_FUNCTION] = JS_NewObjectProto(ctx, ctx->function_proto);\n    obj1 = JS_NewCFunction3(ctx, (JSCFunction *)js_function_constructor,\n                            \"AsyncFunction\", 1,\n                            JS_CFUNC_constructor_or_func_magic, JS_FUNC_ASYNC,\n                            ctx->function_ctor);\n    JS_SetPropertyFunctionList(ctx,\n                               ctx->class_proto[JS_CLASS_ASYNC_FUNCTION],\n                               js_async_function_proto_funcs,\n                               countof(js_async_function_proto_funcs));\n    JS_SetConstructor2(ctx, obj1, ctx->class_proto[JS_CLASS_ASYNC_FUNCTION],\n                       0, JS_PROP_CONFIGURABLE);\n    JS_FreeValue(ctx, obj1);\n\n    /* AsyncIteratorPrototype */\n    ctx->async_iterator_proto = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->async_iterator_proto,\n                               js_async_iterator_proto_funcs,\n                               countof(js_async_iterator_proto_funcs));\n\n    /* AsyncFromSyncIteratorPrototype */\n    ctx->class_proto[JS_CLASS_ASYNC_FROM_SYNC_ITERATOR] =\n        JS_NewObjectProto(ctx, ctx->async_iterator_proto);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ASYNC_FROM_SYNC_ITERATOR],\n                               js_async_from_sync_iterator_proto_funcs,\n                               countof(js_async_from_sync_iterator_proto_funcs));\n\n    /* AsyncGeneratorPrototype */\n    ctx->class_proto[JS_CLASS_ASYNC_GENERATOR] =\n        JS_NewObjectProto(ctx, ctx->async_iterator_proto);\n    JS_SetPropertyFunctionList(ctx,\n                               ctx->class_proto[JS_CLASS_ASYNC_GENERATOR],\n                               js_async_generator_proto_funcs,\n                               countof(js_async_generator_proto_funcs));\n\n    /* AsyncGeneratorFunction */\n    ctx->class_proto[JS_CLASS_ASYNC_GENERATOR_FUNCTION] =\n        JS_NewObjectProto(ctx, ctx->function_proto);\n    obj1 = JS_NewCFunction3(ctx, (JSCFunction *)js_function_constructor,\n                            \"AsyncGeneratorFunction\", 1,\n                            JS_CFUNC_constructor_or_func_magic,\n                            JS_FUNC_ASYNC_GENERATOR,\n                            ctx->function_ctor);\n    JS_SetPropertyFunctionList(ctx,\n                               ctx->class_proto[JS_CLASS_ASYNC_GENERATOR_FUNCTION],\n                               js_async_generator_function_proto_funcs,\n                               countof(js_async_generator_function_proto_funcs));\n    JS_SetConstructor2(ctx, ctx->class_proto[JS_CLASS_ASYNC_GENERATOR_FUNCTION],\n                       ctx->class_proto[JS_CLASS_ASYNC_GENERATOR],\n                       JS_PROP_CONFIGURABLE, JS_PROP_CONFIGURABLE);\n    JS_SetConstructor2(ctx, obj1, ctx->class_proto[JS_CLASS_ASYNC_GENERATOR_FUNCTION],\n                       0, JS_PROP_CONFIGURABLE);\n    JS_FreeValue(ctx, obj1);\n}\n\n/* URI handling */\n\nstatic int string_get_hex(JSString *p, int k, int n) {\n    int c = 0, h;\n    while (n-- > 0) {\n        if ((h = from_hex(string_get(p, k++))) < 0)\n            return -1;\n        c = (c << 4) | h;\n    }\n    return c;\n}\n\nstatic int isURIReserved(int c) {\n    return c < 0x100 && memchr(\";/?:@&=+$,#\", c, sizeof(\";/?:@&=+$,#\") - 1) != NULL;\n}\n\nstatic int __attribute__((format(printf, 2, 3))) js_throw_URIError(JSContext *ctx, const char *fmt, ...)\n{\n    va_list ap;\n\n    va_start(ap, fmt);\n    JS_ThrowError(ctx, JS_URI_ERROR, fmt, ap);\n    va_end(ap);\n    return -1;\n}\n\nstatic int hex_decode(JSContext *ctx, JSString *p, int k) {\n    int c;\n\n    if (k >= p->len || string_get(p, k) != '%')\n        return js_throw_URIError(ctx, \"expecting %%\");\n    if (k + 2 >= p->len || (c = string_get_hex(p, k + 1, 2)) < 0)\n        return js_throw_URIError(ctx, \"expecting hex digit\");\n\n    return c;\n}\n\nstatic JSValue js_global_decodeURI(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv, int isComponent)\n{\n    JSValue str;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p;\n    int k, c, c1, n, c_min;\n\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        return str;\n\n    string_buffer_init(ctx, b, 0);\n\n    p = JS_VALUE_GET_STRING(str);\n    for (k = 0; k < p->len;) {\n        c = string_get(p, k);\n        if (c == '%') {\n            c = hex_decode(ctx, p, k);\n            if (c < 0)\n                goto fail;\n            k += 3;\n            if (c < 0x80) {\n                if (!isComponent && isURIReserved(c)) {\n                    c = '%';\n                    k -= 2;\n                }\n            } else {\n                /* Decode URI-encoded UTF-8 sequence */\n                if (c >= 0xc0 && c <= 0xdf) {\n                    n = 1;\n                    c_min = 0x80;\n                    c &= 0x1f;\n                } else if (c >= 0xe0 && c <= 0xef) {\n                    n = 2;\n                    c_min = 0x800;\n                    c &= 0xf;\n                } else if (c >= 0xf0 && c <= 0xf7) {\n                    n = 3;\n                    c_min = 0x10000;\n                    c &= 0x7;\n                } else {\n                    n = 0;\n                    c_min = 1;\n                    c = 0;\n                }\n                while (n-- > 0) {\n                    c1 = hex_decode(ctx, p, k);\n                    if (c1 < 0)\n                        goto fail;\n                    k += 3;\n                    if ((c1 & 0xc0) != 0x80) {\n                        c = 0;\n                        break;\n                    }\n                    c = (c << 6) | (c1 & 0x3f);\n                }\n                if (c < c_min || c > 0x10FFFF ||\n                    (c >= 0xd800 && c < 0xe000)) {\n                    js_throw_URIError(ctx, \"malformed UTF-8\");\n                    goto fail;\n                }\n            }\n        } else {\n            k++;\n        }\n        string_buffer_putc(b, c);\n    }\n    JS_FreeValue(ctx, str);\n    return string_buffer_end(b);\n\nfail:\n    JS_FreeValue(ctx, str);\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nstatic int isUnescaped(int c) {\n    static char const unescaped_chars[] =\n        \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n        \"abcdefghijklmnopqrstuvwxyz\"\n        \"0123456789\"\n        \"@*_+-./\";\n    return c < 0x100 &&\n        memchr(unescaped_chars, c, sizeof(unescaped_chars) - 1);\n}\n\nstatic int isURIUnescaped(int c, int isComponent) {\n    return c < 0x100 &&\n        ((c >= 0x61 && c <= 0x7a) ||\n         (c >= 0x41 && c <= 0x5a) ||\n         (c >= 0x30 && c <= 0x39) ||\n         memchr(\"-_.!~*'()\", c, sizeof(\"-_.!~*'()\") - 1) != NULL ||\n         (!isComponent && isURIReserved(c)));\n}\n\nstatic int encodeURI_hex(StringBuffer *b, int c) {\n    uint8_t buf[6];\n    int n = 0;\n    const char *hex = \"0123456789ABCDEF\";\n\n    buf[n++] = '%';\n    if (c >= 256) {\n        buf[n++] = 'u';\n        buf[n++] = hex[(c >> 12) & 15];\n        buf[n++] = hex[(c >>  8) & 15];\n    }\n    buf[n++] = hex[(c >> 4) & 15];\n    buf[n++] = hex[(c >> 0) & 15];\n    return string_buffer_write8(b, buf, n);\n}\n\nstatic JSValue js_global_encodeURI(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv,\n                                   int isComponent)\n{\n    JSValue str;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p;\n    int k, c, c1;\n\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        return str;\n\n    p = JS_VALUE_GET_STRING(str);\n    string_buffer_init(ctx, b, p->len);\n    for (k = 0; k < p->len;) {\n        c = string_get(p, k);\n        k++;\n        if (isURIUnescaped(c, isComponent)) {\n            string_buffer_putc16(b, c);\n        } else {\n            if (c >= 0xdc00 && c <= 0xdfff) {\n                js_throw_URIError(ctx, \"invalid character\");\n                goto fail;\n            } else if (c >= 0xd800 && c <= 0xdbff) {\n                if (k >= p->len) {\n                    js_throw_URIError(ctx, \"expecting surrogate pair\");\n                    goto fail;\n                }\n                c1 = string_get(p, k);\n                k++;\n                if (c1 < 0xdc00 || c1 > 0xdfff) {\n                    js_throw_URIError(ctx, \"expecting surrogate pair\");\n                    goto fail;\n                }\n                c = (((c & 0x3ff) << 10) | (c1 & 0x3ff)) + 0x10000;\n            }\n            if (c < 0x80) {\n                encodeURI_hex(b, c);\n            } else {\n                /* XXX: use C UTF-8 conversion ? */\n                if (c < 0x800) {\n                    encodeURI_hex(b, (c >> 6) | 0xc0);\n                } else {\n                    if (c < 0x10000) {\n                        encodeURI_hex(b, (c >> 12) | 0xe0);\n                    } else {\n                        encodeURI_hex(b, (c >> 18) | 0xf0);\n                        encodeURI_hex(b, ((c >> 12) & 0x3f) | 0x80);\n                    }\n                    encodeURI_hex(b, ((c >> 6) & 0x3f) | 0x80);\n                }\n                encodeURI_hex(b, (c & 0x3f) | 0x80);\n            }\n        }\n    }\n    JS_FreeValue(ctx, str);\n    return string_buffer_end(b);\n\nfail:\n    JS_FreeValue(ctx, str);\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_global_escape(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValue str;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p;\n    int i, len, c;\n\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        return str;\n\n    p = JS_VALUE_GET_STRING(str);\n    string_buffer_init(ctx, b, p->len);\n    for (i = 0, len = p->len; i < len; i++) {\n        c = string_get(p, i);\n        if (isUnescaped(c)) {\n            string_buffer_putc16(b, c);\n        } else {\n            encodeURI_hex(b, c);\n        }\n    }\n    JS_FreeValue(ctx, str);\n    return string_buffer_end(b);\n}\n\nstatic JSValue js_global_unescape(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    JSValue str;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p;\n    int i, len, c, n;\n\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        return str;\n\n    string_buffer_init(ctx, b, 0);\n    p = JS_VALUE_GET_STRING(str);\n    for (i = 0, len = p->len; i < len; i++) {\n        c = string_get(p, i);\n        if (c == '%') {\n            if (i + 6 <= len\n            &&  string_get(p, i + 1) == 'u'\n            &&  (n = string_get_hex(p, i + 2, 4)) >= 0) {\n                c = n;\n                i += 6 - 1;\n            } else\n            if (i + 3 <= len\n            &&  (n = string_get_hex(p, i + 1, 2)) >= 0) {\n                c = n;\n                i += 3 - 1;\n            }\n        }\n        string_buffer_putc16(b, c);\n    }\n    JS_FreeValue(ctx, str);\n    return string_buffer_end(b);\n}\n\n/* global object */\n\nstatic const JSCFunctionListEntry js_global_funcs[] = {\n    JS_CFUNC_DEF(\"parseInt\", 2, js_parseInt ),\n    JS_CFUNC_DEF(\"parseFloat\", 1, js_parseFloat ),\n    JS_CFUNC_DEF(\"isNaN\", 1, js_global_isNaN ),\n    JS_CFUNC_DEF(\"isFinite\", 1, js_global_isFinite ),\n\n    JS_CFUNC_MAGIC_DEF(\"decodeURI\", 1, js_global_decodeURI, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"decodeURIComponent\", 1, js_global_decodeURI, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"encodeURI\", 1, js_global_encodeURI, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"encodeURIComponent\", 1, js_global_encodeURI, 1 ),\n    JS_CFUNC_DEF(\"escape\", 1, js_global_escape ),\n    JS_CFUNC_DEF(\"unescape\", 1, js_global_unescape ),\n    JS_PROP_DOUBLE_DEF(\"Infinity\", 1.0 / 0.0, 0 ),\n    JS_PROP_DOUBLE_DEF(\"NaN\", NAN, 0 ),\n    JS_PROP_UNDEFINED_DEF(\"undefined\", 0 ),\n\n    /* for the 'Date' implementation */\n    JS_CFUNC_DEF(\"__date_clock\", 0, js___date_clock ),\n    //JS_CFUNC_DEF(\"__date_now\", 0, js___date_now ),\n    //JS_CFUNC_DEF(\"__date_getTimezoneOffset\", 1, js___date_getTimezoneOffset ),\n    //JS_CFUNC_DEF(\"__date_create\", 3, js___date_create ),\n};\n\n/* Date */\n\nstatic int64_t math_mod(int64_t a, int64_t b) {\n    /* return positive modulo */\n    int64_t m = a % b;\n    return m + (m < 0) * b;\n}\n\nstatic int64_t floor_div(int64_t a, int64_t b) {\n    /* integer division rounding toward -Infinity */\n    int64_t m = a % b;\n    return (a - (m + (m < 0) * b)) / b;\n}\n\nstatic JSValue js_Date_parse(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv);\n\nstatic __exception int JS_ThisTimeValue(JSContext *ctx, double *valp, JSValueConst this_val)\n{\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_DATE && JS_IsNumber(p->u.object_data))\n            return JS_ToFloat64(ctx, valp, p->u.object_data);\n    }\n    JS_ThrowTypeError(ctx, \"not a Date object\");\n    return -1;\n}\n\nstatic JSValue JS_SetThisTimeValue(JSContext *ctx, JSValueConst this_val, double v)\n{\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_DATE) {\n            JS_FreeValue(ctx, p->u.object_data);\n            p->u.object_data = JS_NewFloat64(ctx, v);\n            return JS_DupValue(ctx, p->u.object_data);\n        }\n    }\n    return JS_ThrowTypeError(ctx, \"not a Date object\");\n}\n\nstatic int64_t days_from_year(int64_t y) {\n    return 365 * (y - 1970) + floor_div(y - 1969, 4) -\n        floor_div(y - 1901, 100) + floor_div(y - 1601, 400);\n}\n\nstatic int64_t days_in_year(int64_t y) {\n    return 365 + !(y % 4) - !(y % 100) + !(y % 400);\n}\n\n/* return the year, update days */\nstatic int64_t year_from_days(int64_t *days) {\n    int64_t y, d1, nd, d = *days;\n    y = floor_div(d * 10000, 3652425) + 1970;\n    /* the initial approximation is very good, so only a few\n       iterations are necessary */\n    for(;;) {\n        d1 = d - days_from_year(y);\n        if (d1 < 0) {\n            y--;\n            d1 += days_in_year(y);\n        } else {\n            nd = days_in_year(y);\n            if (d1 < nd)\n                break;\n            d1 -= nd;\n            y++;\n        }\n    }\n    *days = d1;\n    return y;\n}\n\nstatic int const month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\nstatic char const month_names[] = \"JanFebMarAprMayJunJulAugSepOctNovDec\";\nstatic char const day_names[] = \"SunMonTueWedThuFriSat\";\n\nstatic __exception int get_date_fields(JSContext *ctx, JSValueConst obj,\n                                       double fields[9], int is_local, int force)\n{\n    double dval;\n    int64_t d, days, wd, y, i, md, h, m, s, ms, tz = 0;\n\n    if (JS_ThisTimeValue(ctx, &dval, obj))\n        return -1;\n\n    if (isnan(dval)) {\n        if (!force)\n            return FALSE; /* NaN */\n        d = 0;        /* initialize all fields to 0 */\n    } else {\n        d = dval;\n        if (is_local) {\n            tz = -getTimezoneOffset(d);\n            d += tz * 60000;\n        }\n    }\n\n    /* result is >= 0, we can use % */\n    h = math_mod(d, 86400000);\n    days = (d - h) / 86400000;\n    ms = h % 1000;\n    h = (h - ms) / 1000;\n    s = h % 60;\n    h = (h - s) / 60;\n    m = h % 60;\n    h = (h - m) / 60;\n    wd = math_mod(days + 4, 7); /* week day */\n    y = year_from_days(&days);\n\n    for(i = 0; i < 11; i++) {\n        md = month_days[i];\n        if (i == 1)\n            md += days_in_year(y) - 365;\n        if (days < md)\n            break;\n        days -= md;\n    }\n    fields[0] = y;\n    fields[1] = i;\n    fields[2] = days + 1;\n    fields[3] = h;\n    fields[4] = m;\n    fields[5] = s;\n    fields[6] = ms;\n    fields[7] = wd;\n    fields[8] = tz;\n    return TRUE;\n}\n\nstatic double time_clip(double t) {\n    if (t >= -8.64e15 && t <= 8.64e15)\n        return trunc(t) + 0.0;  /* convert -0 to +0 */\n    else\n        return NAN;\n}\n\n/* The spec mandates the use of 'double' and it fixes the order\n   of the operations */\nstatic double set_date_fields(double fields[], int is_local) {\n    int64_t y;\n    double days, d, h, m1;\n    int i, m, md;\n    \n    m1 = fields[1];\n    m = fmod(m1, 12);\n    if (m < 0)\n        m += 12;\n    y = (int64_t)(fields[0] + floor(m1 / 12));\n    days = days_from_year(y);\n\n    for(i = 0; i < m; i++) {\n        md = month_days[i];\n        if (i == 1)\n            md += days_in_year(y) - 365;\n        days += md;\n    }\n    days += fields[2] - 1;\n    h = fields[3] * 3600000 + fields[4] * 60000 + \n        fields[5] * 1000 + fields[6];\n    d = days * 86400000 + h;\n    if (is_local)\n        d += getTimezoneOffset(d) * 60000;\n    return time_clip(d);\n}\n\nstatic JSValue get_date_field(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int magic)\n{\n    // get_date_field(obj, n, is_local)\n    double fields[9];\n    int res, n, is_local;\n\n    is_local = magic & 0x0F;\n    n = (magic >> 4) & 0x0F;\n    res = get_date_fields(ctx, this_val, fields, is_local, 0);\n    if (res < 0)\n        return JS_EXCEPTION;\n    if (!res)\n        return JS_NAN;\n\n    if (magic & 0x100) {    // getYear\n        fields[0] -= 1900;\n    }\n    return JS_NewFloat64(ctx, fields[n]);\n}\n\nstatic JSValue set_date_field(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int magic)\n{\n    // _field(obj, first_field, end_field, args, is_local)\n    double fields[9];\n    int res, first_field, end_field, is_local, i, n;\n    double d, a;\n\n    d = NAN;\n    first_field = (magic >> 8) & 0x0F;\n    end_field = (magic >> 4) & 0x0F;\n    is_local = magic & 0x0F;\n\n    res = get_date_fields(ctx, this_val, fields, is_local, first_field == 0);\n    if (res < 0)\n        return JS_EXCEPTION;\n    if (res && argc > 0) {\n        n = end_field - first_field;\n        if (argc < n)\n            n = argc;\n        for(i = 0; i < n; i++) {\n            if (JS_ToFloat64(ctx, &a, argv[i]))\n                return JS_EXCEPTION;\n            if (!isfinite(a))\n                goto done;\n            fields[first_field + i] = trunc(a);\n        }\n        d = set_date_fields(fields, is_local);\n    }\ndone:\n    return JS_SetThisTimeValue(ctx, this_val, d);\n}\n\n/* fmt:\n   0: toUTCString: \"Tue, 02 Jan 2018 23:04:46 GMT\"\n   1: toString: \"Wed Jan 03 2018 00:05:22 GMT+0100 (CET)\"\n   2: toISOString: \"2018-01-02T23:02:56.927Z\"\n   3: toLocaleString: \"1/2/2018, 11:40:40 PM\"\n   part: 1=date, 2=time 3=all\n   XXX: should use a variant of strftime().\n */\nstatic JSValue get_date_string(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv, int magic)\n{\n    // _string(obj, fmt, part)\n    char buf[64];\n    double fields[9];\n    int res, fmt, part, pos;\n    int y, mon, d, h, m, s, ms, wd, tz;\n\n    fmt = (magic >> 4) & 0x0F;\n    part = magic & 0x0F;\n\n    res = get_date_fields(ctx, this_val, fields, fmt & 1, 0);\n    if (res < 0)\n        return JS_EXCEPTION;\n    if (!res) {\n        if (fmt == 2)\n            return JS_ThrowRangeError(ctx, \"Date value is NaN\");\n        else\n            return JS_NewString(ctx, \"Invalid Date\");\n    }\n\n    y = fields[0];\n    mon = fields[1];\n    d = fields[2];\n    h = fields[3];\n    m = fields[4];\n    s = fields[5];\n    ms = fields[6];\n    wd = fields[7];\n    tz = fields[8];\n\n    pos = 0;\n\n    if (part & 1) { /* date part */\n        switch(fmt) {\n        case 0:\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"%.3s, %02d %.3s %0*d \",\n                            day_names + wd * 3, d,\n                            month_names + mon * 3, 4 + (y < 0), y);\n            break;\n        case 1:\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"%.3s %.3s %02d %0*d\",\n                            day_names + wd * 3,\n                            month_names + mon * 3, d, 4 + (y < 0), y);\n            if (part == 3) {\n                buf[pos++] = ' ';\n            }\n            break;\n        case 2:\n            if (y >= 0 && y <= 9999) {\n                pos += snprintf(buf + pos, sizeof(buf) - pos,\n                                \"%04d\", y);\n            } else {\n                pos += snprintf(buf + pos, sizeof(buf) - pos,\n                                \"%+07d\", y);\n            }\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"-%02d-%02dT\", mon + 1, d);\n            break;\n        case 3:\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"%02d/%02d/%0*d\", mon + 1, d, 4 + (y < 0), y);\n            if (part == 3) {\n                buf[pos++] = ',';\n                buf[pos++] = ' ';\n            }\n            break;\n        }\n    }\n    if (part & 2) { /* time part */\n        switch(fmt) {\n        case 0:\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"%02d:%02d:%02d GMT\", h, m, s);\n            break;\n        case 1:\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"%02d:%02d:%02d GMT\", h, m, s);\n            if (tz < 0) {\n                buf[pos++] = '-';\n                tz = -tz;\n            } else {\n                buf[pos++] = '+';\n            }\n            /* tz is >= 0, can use % */\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"%02d%02d\", tz / 60, tz % 60);\n            /* XXX: tack the time zone code? */\n            break;\n        case 2:\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"%02d:%02d:%02d.%03dZ\", h, m, s, ms);\n            break;\n        case 3:\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"%02d:%02d:%02d %cM\", (h + 1) % 12 - 1, m, s,\n                            (h < 12) ? 'A' : 'P');\n            break;\n        }\n    }\n    return JS_NewStringLen(ctx, buf, pos);\n}\n\n/* OS dependent: return the UTC time in ms since 1970. */\nstatic int64_t date_now(void) {\n    struct timeval tv;\n    gettimeofday(&tv, NULL);\n    return (int64_t)tv.tv_sec * 1000 + (tv.tv_usec / 1000);\n}\n\nstatic JSValue js_date_constructor(JSContext *ctx, JSValueConst new_target,\n                                   int argc, JSValueConst *argv)\n{\n    // Date(y, mon, d, h, m, s, ms)\n    JSValue rv;\n    int i, n;\n    double a, val;\n\n    if (JS_IsUndefined(new_target)) {\n        /* invoked as function */\n        argc = 0;\n    }\n    n = argc;\n    if (n == 0) {\n        val = date_now();\n    } else if (n == 1) {\n        JSValue v, dv;\n        if (JS_VALUE_GET_TAG(argv[0]) == JS_TAG_OBJECT) {\n            JSObject *p = JS_VALUE_GET_OBJ(argv[0]);\n            if (p->class_id == JS_CLASS_DATE && JS_IsNumber(p->u.object_data)) {\n                if (JS_ToFloat64(ctx, &val, p->u.object_data))\n                    return JS_EXCEPTION;\n                val = time_clip(val);\n                goto has_val;\n            }\n        }\n        v = JS_ToPrimitive(ctx, argv[0], HINT_NONE);\n        if (JS_IsString(v)) {\n            dv = js_Date_parse(ctx, JS_UNDEFINED, 1, (JSValueConst *)&v);\n            JS_FreeValue(ctx, v);\n            if (JS_IsException(dv))\n                return JS_EXCEPTION;\n            if (JS_ToFloat64Free(ctx, &val, dv))\n                return JS_EXCEPTION;\n        } else {\n            if (JS_ToFloat64Free(ctx, &val, v))\n                return JS_EXCEPTION;\n        }\n        val = time_clip(val);\n    } else {\n        double fields[] = { 0, 0, 1, 0, 0, 0, 0 };\n        if (n > 7)\n            n = 7;\n        for(i = 0; i < n; i++) {\n            if (JS_ToFloat64(ctx, &a, argv[i]))\n                return JS_EXCEPTION;\n            if (!isfinite(a))\n                break;\n            fields[i] = trunc(a);\n            if (i == 0 && fields[0] >= 0 && fields[0] < 100)\n                fields[0] += 1900;\n        }\n        val = (i == n) ? set_date_fields(fields, 1) : NAN;\n    }\nhas_val:\n#if 0\n    JSValueConst args[3];\n    args[0] = new_target;\n    args[1] = ctx->class_proto[JS_CLASS_DATE];\n    args[2] = JS_NewFloat64(ctx, val);\n    rv = js___date_create(ctx, JS_UNDEFINED, 3, args);\n#else\n    rv = js_create_from_ctor(ctx, new_target, JS_CLASS_DATE);\n    if (!JS_IsException(rv))\n        JS_SetObjectData(ctx, rv, JS_NewFloat64(ctx, val));\n#endif\n    if (!JS_IsException(rv) && JS_IsUndefined(new_target)) {\n        /* invoked as a function, return (new Date()).toString(); */\n        JSValue s;\n        s = get_date_string(ctx, rv, 0, NULL, 0x13);\n        JS_FreeValue(ctx, rv);\n        rv = s;\n    }\n    return rv;\n}\n\nstatic JSValue js_Date_UTC(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    // UTC(y, mon, d, h, m, s, ms)\n    double fields[] = { 0, 0, 1, 0, 0, 0, 0 };\n    int i, n;\n    double a;\n\n    n = argc;\n    if (n == 0)\n        return JS_NAN;\n    if (n > 7)\n        n = 7;\n    for(i = 0; i < n; i++) {\n        if (JS_ToFloat64(ctx, &a, argv[i]))\n            return JS_EXCEPTION;\n        if (!isfinite(a))\n            return JS_NAN;\n        fields[i] = trunc(a);\n        if (i == 0 && fields[0] >= 0 && fields[0] < 100)\n            fields[0] += 1900;\n    }\n    return JS_NewFloat64(ctx, set_date_fields(fields, 0));\n}\n\nstatic void string_skip_spaces(JSString *sp, int *pp) {\n    while (*pp < sp->len && string_get(sp, *pp) == ' ')\n        *pp += 1;\n}\n\nstatic void string_skip_non_spaces(JSString *sp, int *pp) {\n    while (*pp < sp->len && string_get(sp, *pp) != ' ')\n        *pp += 1;\n}\n\n/* parse a numeric field with an optional sign if accept_sign is TRUE */\nstatic int string_get_digits(JSString *sp, int *pp, int64_t *pval) {\n    int64_t v = 0;\n    int c, p = *pp, p_start;\n    \n    if (p >= sp->len)\n        return -1;\n    p_start = p;\n    while (p < sp->len) {\n        c = string_get(sp, p);\n        if (!(c >= '0' && c <= '9')) {\n            if (p == p_start)\n                return -1;\n            else\n                break;\n        }\n        v = v * 10 + c - '0';\n        p++;\n    }\n    *pval = v;\n    *pp = p;\n    return 0;\n}\n\nstatic int string_get_signed_digits(JSString *sp, int *pp, int64_t *pval) {\n    int res, sgn, p = *pp;\n    \n    if (p >= sp->len)\n        return -1;\n\n    sgn = string_get(sp, p);\n    if (sgn == '-' || sgn == '+')\n        p++;\n \n    res = string_get_digits(sp, &p, pval);\n    if (res == 0 && sgn == '-')\n        *pval = -*pval;\n    *pp = p;\n    return res;\n}\n\n/* parse a fixed width numeric field */\nstatic int string_get_fixed_width_digits(JSString *sp, int *pp, int n, int64_t *pval) {\n    int64_t v = 0;\n    int i, c, p = *pp;\n\n    for(i = 0; i < n; i++) {\n        if (p >= sp->len)\n            return -1;\n        c = string_get(sp, p);\n        if (!(c >= '0' && c <= '9'))\n            return -1;\n        v = v * 10 + c - '0';\n        p++;\n    }\n    *pval = v;\n    *pp = p;\n    return 0;\n}\n\nstatic int string_get_milliseconds(JSString *sp, int *pp, int64_t *pval) {\n    /* parse milliseconds as a fractional part, round to nearest */\n    /* XXX: the spec does not indicate which rounding should be used */\n    int mul = 1000, ms = 0, p = *pp, c, p_start;\n    if (p >= sp->len)\n        return -1;\n    p_start = p;\n    while (p < sp->len) {\n        c = string_get(sp, p);\n        if (!(c >= '0' && c <= '9')) {\n            if (p == p_start)\n                return -1;\n            else\n                break;\n        }\n        if (mul == 1 && c >= '5')\n            ms += 1;\n        ms += (c - '0') * (mul /= 10);\n        p++;\n    }\n    *pval = ms;\n    *pp = p;\n    return 0;\n}\n\n\nstatic int find_abbrev(JSString *sp, int p, const char *list, int count) {\n    int n, i;\n\n    if (p + 3 <= sp->len) {\n        for (n = 0; n < count; n++) {\n            for (i = 0; i < 3; i++) {\n                if (string_get(sp, p + i) != month_names[n * 3 + i])\n                    goto next;\n            }\n            return n;\n        next:;\n        }\n    }\n    return -1;\n}\n\nstatic int string_get_month(JSString *sp, int *pp, int64_t *pval) {\n    int n;\n\n    string_skip_spaces(sp, pp);\n    n = find_abbrev(sp, *pp, month_names, 12);\n    if (n < 0)\n        return -1;\n\n    *pval = n;\n    *pp += 3;\n    return 0;\n}\n\nstatic JSValue js_Date_parse(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    // parse(s)\n    JSValue s, rv;\n    int64_t fields[] = { 0, 1, 1, 0, 0, 0, 0 };\n    double fields1[7];\n    int64_t tz, hh, mm;\n    double d;\n    int p, i, c, sgn, l;\n    JSString *sp;\n    BOOL is_local;\n    \n    rv = JS_NAN;\n\n    s = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(s))\n        return JS_EXCEPTION;\n    \n    sp = JS_VALUE_GET_STRING(s);\n    p = 0;\n    if (p < sp->len && (((c = string_get(sp, p)) >= '0' && c <= '9') || c == '+' || c == '-')) {\n        /* ISO format */\n        /* year field can be negative */\n        if (string_get_signed_digits(sp, &p, &fields[0]))\n            goto done;\n\n        for (i = 1; i < 7; i++) {\n            if (p >= sp->len)\n                break;\n            switch(i) {\n            case 1:\n            case 2:\n                c = '-';\n                break;\n            case 3:\n                c = 'T';\n                break;\n            case 4:\n            case 5:\n                c = ':';\n                break;\n            case 6:\n                c = '.';\n                break;\n            }\n            if (string_get(sp, p) != c)\n                break;\n            p++;\n            if (i == 6) {\n                if (string_get_milliseconds(sp, &p, &fields[i]))\n                    goto done;\n            } else {\n                if (string_get_digits(sp, &p, &fields[i]))\n                    goto done;\n            }\n        }\n        /* no time: UTC by default */\n        is_local = (i > 3);\n        fields[1] -= 1;\n\n        /* parse the time zone offset if present: [+-]HH:mm or [+-]HHmm */\n        tz = 0;\n        if (p < sp->len) {\n            sgn = string_get(sp, p);\n            if (sgn == '+' || sgn == '-') {\n                p++;\n                l = sp->len - p;\n                if (l != 4 && l != 5)\n                    goto done;\n                if (string_get_fixed_width_digits(sp, &p, 2, &hh))\n                    goto done;\n                if (l == 5) {\n                    if (string_get(sp, p) != ':')\n                        goto done;\n                    p++;\n                }\n                if (string_get_fixed_width_digits(sp, &p, 2, &mm))\n                    goto done;\n                tz = hh * 60 + mm;\n                if (sgn == '-')\n                    tz = -tz;\n                is_local = FALSE;\n            } else if (sgn == 'Z') {\n                p++;\n                is_local = FALSE;\n            } else {\n                goto done;\n            }\n            /* error if extraneous characters */\n            if (p != sp->len)\n                goto done;\n        }\n    } else {\n        /* toString or toUTCString format */\n        /* skip the day of the week */\n        string_skip_non_spaces(sp, &p);\n        string_skip_spaces(sp, &p);\n        if (p >= sp->len)\n            goto done;\n        c = string_get(sp, p);\n        if (c >= '0' && c <= '9') {\n            /* day of month first */\n            if (string_get_digits(sp, &p, &fields[2]))\n                goto done;\n            if (string_get_month(sp, &p, &fields[1]))\n                goto done;\n        } else {\n            /* month first */\n            if (string_get_month(sp, &p, &fields[1]))\n                goto done;\n            string_skip_spaces(sp, &p);\n            if (string_get_digits(sp, &p, &fields[2]))\n                goto done;\n        }\n        /* year */\n        string_skip_spaces(sp, &p);\n        if (string_get_signed_digits(sp, &p, &fields[0]))\n            goto done;\n\n        /* hour, min, seconds */\n        string_skip_spaces(sp, &p);\n        for(i = 0; i < 3; i++) {\n            if (i == 1 || i == 2) {\n                if (p >= sp->len)\n                    goto done;\n                if (string_get(sp, p) != ':')\n                    goto done;\n                p++;\n            }\n            if (string_get_digits(sp, &p, &fields[3 + i]))\n                goto done;\n        }\n        // XXX: parse optional milliseconds?\n\n        /* parse the time zone offset if present: [+-]HHmm */\n        is_local = FALSE;\n        tz = 0;\n        for (tz = 0; p < sp->len; p++) {\n            sgn = string_get(sp, p);\n            if (sgn == '+' || sgn == '-') {\n                p++;\n                if (string_get_fixed_width_digits(sp, &p, 2, &hh))\n                    goto done;\n                if (string_get_fixed_width_digits(sp, &p, 2, &mm))\n                    goto done;\n                tz = hh * 60 + mm;\n                if (sgn == '-')\n                    tz = -tz;\n                break;\n            }\n        }\n    }\n    for(i = 0; i < 7; i++)\n        fields1[i] = fields[i];\n    d = set_date_fields(fields1, is_local) - tz * 60000;\n    rv = JS_NewFloat64(ctx, d);\n\ndone:\n    JS_FreeValue(ctx, s);\n    return rv;\n}\n\nstatic JSValue js_Date_now(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    // now()\n    return JS_NewInt64(ctx, date_now());\n}\n\nstatic JSValue js_date_Symbol_toPrimitive(JSContext *ctx, JSValueConst this_val,\n                                          int argc, JSValueConst *argv)\n{\n    // Symbol_toPrimitive(hint)\n    JSValueConst obj = this_val;\n    JSAtom hint = JS_ATOM_NULL;\n    int hint_num;\n\n    if (!JS_IsObject(obj))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    if (JS_IsString(argv[0])) {\n        hint = JS_ValueToAtom(ctx, argv[0]);\n        if (hint == JS_ATOM_NULL)\n            return JS_EXCEPTION;\n        JS_FreeAtom(ctx, hint);\n    }\n    switch (hint) {\n    case JS_ATOM_number:\n#ifdef CONFIG_BIGNUM\n    case JS_ATOM_integer:\n#endif\n        hint_num = HINT_NUMBER;\n        break;\n    case JS_ATOM_string:\n    case JS_ATOM_default:\n        hint_num = HINT_STRING;\n        break;\n    default:\n        return JS_ThrowTypeError(ctx, \"invalid hint\");\n    }\n    return JS_ToPrimitive(ctx, obj, hint_num | HINT_FORCE_ORDINARY);\n}\n\nstatic JSValue js_date_getTimezoneOffset(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    // getTimezoneOffset()\n    double v;\n\n    if (JS_ThisTimeValue(ctx, &v, this_val))\n        return JS_EXCEPTION;\n    if (isnan(v))\n        return JS_NAN;\n    else\n        return JS_NewInt64(ctx, getTimezoneOffset((int64_t)trunc(v)));\n}\n\nstatic JSValue js_date_getTime(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    // getTime()\n    double v;\n\n    if (JS_ThisTimeValue(ctx, &v, this_val))\n        return JS_EXCEPTION;\n    return JS_NewFloat64(ctx, v);\n}\n\nstatic JSValue js_date_setTime(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    // setTime(v)\n    double v;\n\n    if (JS_ThisTimeValue(ctx, &v, this_val) || JS_ToFloat64(ctx, &v, argv[0]))\n        return JS_EXCEPTION;\n    return JS_SetThisTimeValue(ctx, this_val, time_clip(v));\n}\n\nstatic JSValue js_date_setYear(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    // setYear(y)\n    double y;\n    JSValueConst args[1];\n\n    if (JS_ThisTimeValue(ctx, &y, this_val) || JS_ToFloat64(ctx, &y, argv[0]))\n        return JS_EXCEPTION;\n    y = +y;\n    if (isfinite(y)) {\n        y = trunc(y);\n        if (y >= 0 && y < 100)\n            y += 1900;\n    }\n    args[0] = JS_NewFloat64(ctx, y);\n    return set_date_field(ctx, this_val, 1, args, 0x011);\n}\n\nstatic JSValue js_date_toJSON(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    // toJSON(key)\n    JSValue obj, tv, method, rv;\n    double d;\n\n    rv = JS_EXCEPTION;\n    tv = JS_UNDEFINED;\n\n    obj = JS_ToObject(ctx, this_val);\n    tv = JS_ToPrimitive(ctx, obj, HINT_NUMBER);\n    if (JS_IsException(tv))\n        goto exception;\n    if (JS_IsNumber(tv)) {\n        if (JS_ToFloat64(ctx, &d, tv) < 0)\n            goto exception;\n        if (!isfinite(d)) {\n            rv = JS_NULL;\n            goto done;\n        }\n    }\n    method = JS_GetPropertyStr(ctx, obj, \"toISOString\");\n    if (JS_IsException(method))\n        goto exception;\n    if (!JS_IsFunction(ctx, method)) {\n        JS_ThrowTypeError(ctx, \"object needs toISOString method\");\n        JS_FreeValue(ctx, method);\n        goto exception;\n    }\n    rv = JS_CallFree(ctx, method, obj, 0, NULL);\nexception:\ndone:\n    JS_FreeValue(ctx, obj);\n    JS_FreeValue(ctx, tv);\n    return rv;\n}\n\nstatic const JSCFunctionListEntry js_date_funcs[] = {\n    JS_CFUNC_DEF(\"now\", 0, js_Date_now ),\n    JS_CFUNC_DEF(\"parse\", 1, js_Date_parse ),\n    JS_CFUNC_DEF(\"UTC\", 7, js_Date_UTC ),\n};\n\nstatic const JSCFunctionListEntry js_date_proto_funcs[] = {\n    JS_CFUNC_DEF(\"valueOf\", 0, js_date_getTime ),\n    JS_CFUNC_MAGIC_DEF(\"toString\", 0, get_date_string, 0x13 ),\n    JS_CFUNC_DEF(\"[Symbol.toPrimitive]\", 1, js_date_Symbol_toPrimitive ),\n    JS_CFUNC_MAGIC_DEF(\"toUTCString\", 0, get_date_string, 0x03 ),\n    JS_ALIAS_DEF(\"toGMTString\", \"toUTCString\" ),\n    JS_CFUNC_MAGIC_DEF(\"toISOString\", 0, get_date_string, 0x23 ),\n    JS_CFUNC_MAGIC_DEF(\"toDateString\", 0, get_date_string, 0x11 ),\n    JS_CFUNC_MAGIC_DEF(\"toTimeString\", 0, get_date_string, 0x12 ),\n    JS_CFUNC_MAGIC_DEF(\"toLocaleString\", 0, get_date_string, 0x33 ),\n    JS_CFUNC_MAGIC_DEF(\"toLocaleDateString\", 0, get_date_string, 0x31 ),\n    JS_CFUNC_MAGIC_DEF(\"toLocaleTimeString\", 0, get_date_string, 0x32 ),\n    JS_CFUNC_DEF(\"getTimezoneOffset\", 0, js_date_getTimezoneOffset ),\n    JS_CFUNC_DEF(\"getTime\", 0, js_date_getTime ),\n    JS_CFUNC_MAGIC_DEF(\"getYear\", 0, get_date_field, 0x101 ),\n    JS_CFUNC_MAGIC_DEF(\"getFullYear\", 0, get_date_field, 0x01 ),\n    JS_CFUNC_MAGIC_DEF(\"getUTCFullYear\", 0, get_date_field, 0x00 ),\n    JS_CFUNC_MAGIC_DEF(\"getMonth\", 0, get_date_field, 0x11 ),\n    JS_CFUNC_MAGIC_DEF(\"getUTCMonth\", 0, get_date_field, 0x10 ),\n    JS_CFUNC_MAGIC_DEF(\"getDate\", 0, get_date_field, 0x21 ),\n    JS_CFUNC_MAGIC_DEF(\"getUTCDate\", 0, get_date_field, 0x20 ),\n    JS_CFUNC_MAGIC_DEF(\"getHours\", 0, get_date_field, 0x31 ),\n    JS_CFUNC_MAGIC_DEF(\"getUTCHours\", 0, get_date_field, 0x30 ),\n    JS_CFUNC_MAGIC_DEF(\"getMinutes\", 0, get_date_field, 0x41 ),\n    JS_CFUNC_MAGIC_DEF(\"getUTCMinutes\", 0, get_date_field, 0x40 ),\n    JS_CFUNC_MAGIC_DEF(\"getSeconds\", 0, get_date_field, 0x51 ),\n    JS_CFUNC_MAGIC_DEF(\"getUTCSeconds\", 0, get_date_field, 0x50 ),\n    JS_CFUNC_MAGIC_DEF(\"getMilliseconds\", 0, get_date_field, 0x61 ),\n    JS_CFUNC_MAGIC_DEF(\"getUTCMilliseconds\", 0, get_date_field, 0x60 ),\n    JS_CFUNC_MAGIC_DEF(\"getDay\", 0, get_date_field, 0x71 ),\n    JS_CFUNC_MAGIC_DEF(\"getUTCDay\", 0, get_date_field, 0x70 ),\n    JS_CFUNC_DEF(\"setTime\", 1, js_date_setTime ),\n    JS_CFUNC_MAGIC_DEF(\"setMilliseconds\", 1, set_date_field, 0x671 ),\n    JS_CFUNC_MAGIC_DEF(\"setUTCMilliseconds\", 1, set_date_field, 0x670 ),\n    JS_CFUNC_MAGIC_DEF(\"setSeconds\", 2, set_date_field, 0x571 ),\n    JS_CFUNC_MAGIC_DEF(\"setUTCSeconds\", 2, set_date_field, 0x570 ),\n    JS_CFUNC_MAGIC_DEF(\"setMinutes\", 3, set_date_field, 0x471 ),\n    JS_CFUNC_MAGIC_DEF(\"setUTCMinutes\", 3, set_date_field, 0x470 ),\n    JS_CFUNC_MAGIC_DEF(\"setHours\", 4, set_date_field, 0x371 ),\n    JS_CFUNC_MAGIC_DEF(\"setUTCHours\", 4, set_date_field, 0x370 ),\n    JS_CFUNC_MAGIC_DEF(\"setDate\", 1, set_date_field, 0x231 ),\n    JS_CFUNC_MAGIC_DEF(\"setUTCDate\", 1, set_date_field, 0x230 ),\n    JS_CFUNC_MAGIC_DEF(\"setMonth\", 2, set_date_field, 0x131 ),\n    JS_CFUNC_MAGIC_DEF(\"setUTCMonth\", 2, set_date_field, 0x130 ),\n    JS_CFUNC_DEF(\"setYear\", 1, js_date_setYear ),\n    JS_CFUNC_MAGIC_DEF(\"setFullYear\", 3, set_date_field, 0x031 ),\n    JS_CFUNC_MAGIC_DEF(\"setUTCFullYear\", 3, set_date_field, 0x030 ),\n    JS_CFUNC_DEF(\"toJSON\", 1, js_date_toJSON ),\n};\n\nvoid JS_AddIntrinsicDate(JSContext *ctx)\n{\n    JSValueConst obj;\n\n    /* Date */\n    ctx->class_proto[JS_CLASS_DATE] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_DATE], js_date_proto_funcs,\n                               countof(js_date_proto_funcs));\n    obj = JS_NewGlobalCConstructor(ctx, \"Date\", js_date_constructor, 7,\n                                   ctx->class_proto[JS_CLASS_DATE]);\n    JS_SetPropertyFunctionList(ctx, obj, js_date_funcs, countof(js_date_funcs));\n}\n\n/* eval */\n\nvoid JS_AddIntrinsicEval(JSContext *ctx)\n{\n    ctx->eval_internal = __JS_EvalInternal;\n}\n\n#ifdef CONFIG_BIGNUM\n\n/* Operators */\n\nstatic void js_operator_set_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSOperatorSetData *opset = JS_GetOpaque(val, JS_CLASS_OPERATOR_SET);\n    int i, j;\n    JSBinaryOperatorDefEntry *ent;\n    \n    if (opset) {\n        for(i = 0; i < JS_OVOP_COUNT; i++) {\n            if (opset->self_ops[i])\n                JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, opset->self_ops[i]));\n        }\n        for(j = 0; j < opset->left.count; j++) {\n            ent = &opset->left.tab[j];\n            for(i = 0; i < JS_OVOP_BINARY_COUNT; i++) {\n                if (ent->ops[i])\n                    JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, ent->ops[i]));\n            }\n        }\n        js_free_rt(rt, opset->left.tab);\n        for(j = 0; j < opset->right.count; j++) {\n            ent = &opset->right.tab[j];\n            for(i = 0; i < JS_OVOP_BINARY_COUNT; i++) {\n                if (ent->ops[i])\n                    JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, ent->ops[i]));\n            }\n        }\n        js_free_rt(rt, opset->right.tab);\n        js_free_rt(rt, opset);\n    }\n}\n\nstatic void js_operator_set_mark(JSRuntime *rt, JSValueConst val,\n                                 JS_MarkFunc *mark_func)\n{\n    JSOperatorSetData *opset = JS_GetOpaque(val, JS_CLASS_OPERATOR_SET);\n    int i, j;\n    JSBinaryOperatorDefEntry *ent;\n    \n    if (opset) {\n        for(i = 0; i < JS_OVOP_COUNT; i++) {\n            if (opset->self_ops[i])\n                JS_MarkValue(rt, JS_MKPTR(JS_TAG_OBJECT, opset->self_ops[i]),\n                             mark_func);\n        }\n        for(j = 0; j < opset->left.count; j++) {\n            ent = &opset->left.tab[j];\n            for(i = 0; i < JS_OVOP_BINARY_COUNT; i++) {\n                if (ent->ops[i])\n                    JS_MarkValue(rt, JS_MKPTR(JS_TAG_OBJECT, ent->ops[i]),\n                                 mark_func);\n            }\n        }\n        for(j = 0; j < opset->right.count; j++) {\n            ent = &opset->right.tab[j];\n            for(i = 0; i < JS_OVOP_BINARY_COUNT; i++) {\n                if (ent->ops[i])\n                    JS_MarkValue(rt, JS_MKPTR(JS_TAG_OBJECT, ent->ops[i]),\n                                 mark_func);\n            }\n        }\n    }\n}\n\n\n/* create an OperatorSet object */\nstatic JSValue js_operators_create_internal(JSContext *ctx,\n                                            int argc, JSValueConst *argv,\n                                            BOOL is_primitive)\n{\n    JSValue opset_obj, prop, obj;\n    JSOperatorSetData *opset, *opset1;\n    JSBinaryOperatorDef *def;\n    JSValueConst arg;\n    int i, j;\n    JSBinaryOperatorDefEntry *new_tab;\n    JSBinaryOperatorDefEntry *ent;\n    uint32_t op_count;\n\n    if (ctx->rt->operator_count == UINT32_MAX) {\n        return JS_ThrowTypeError(ctx, \"too many operators\");\n    }\n    opset_obj = JS_NewObjectProtoClass(ctx, JS_NULL, JS_CLASS_OPERATOR_SET);\n    if (JS_IsException(opset_obj))\n        goto fail;\n    opset = js_mallocz(ctx, sizeof(*opset));\n    if (!opset)\n        goto fail;\n    JS_SetOpaque(opset_obj, opset);\n    if (argc >= 1) {\n        arg = argv[0];\n        /* self operators */\n        for(i = 0; i < JS_OVOP_COUNT; i++) {\n            prop = JS_GetPropertyStr(ctx, arg, js_overloadable_operator_names[i]);\n            if (JS_IsException(prop))\n                goto fail;\n            if (!JS_IsUndefined(prop)) {\n                if (check_function(ctx, prop)) {\n                    JS_FreeValue(ctx, prop);\n                    goto fail;\n                }\n                opset->self_ops[i] = JS_VALUE_GET_OBJ(prop);\n            }\n        }\n    }\n    /* left & right operators */\n    for(j = 1; j < argc; j++) {\n        arg = argv[j];\n        prop = JS_GetPropertyStr(ctx, arg, \"left\");\n        if (JS_IsException(prop))\n            goto fail;\n        def = &opset->right;\n        if (JS_IsUndefined(prop)) {\n            prop = JS_GetPropertyStr(ctx, arg, \"right\");\n            if (JS_IsException(prop))\n                goto fail;\n            if (JS_IsUndefined(prop)) {\n                JS_ThrowTypeError(ctx, \"left or right property must be present\");\n                goto fail;\n            }\n            def = &opset->left;\n        }\n        /* get the operator set */\n        obj = JS_GetProperty(ctx, prop, JS_ATOM_prototype);\n        JS_FreeValue(ctx, prop);\n        if (JS_IsException(obj))\n            goto fail;\n        prop = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_operatorSet);\n        JS_FreeValue(ctx, obj);\n        if (JS_IsException(prop))\n            goto fail;\n        opset1 = JS_GetOpaque2(ctx, prop, JS_CLASS_OPERATOR_SET);\n        if (!opset1) {\n            JS_FreeValue(ctx, prop);\n            goto fail;\n        }\n        op_count = opset1->operator_counter;\n        JS_FreeValue(ctx, prop);\n        \n        /* we assume there are few entries */\n        new_tab = js_realloc(ctx, def->tab,\n                             (def->count + 1) * sizeof(def->tab[0]));\n        if (!new_tab)\n            goto fail;\n        def->tab = new_tab;\n        def->count++;\n        ent = def->tab + def->count - 1;\n        memset(ent, 0, sizeof(def->tab[0]));\n        ent->operator_index = op_count;\n        \n        for(i = 0; i < JS_OVOP_BINARY_COUNT; i++) {\n            prop = JS_GetPropertyStr(ctx, arg,\n                                     js_overloadable_operator_names[i]);\n            if (JS_IsException(prop))\n                goto fail;\n            if (!JS_IsUndefined(prop)) {\n                if (check_function(ctx, prop)) {\n                    JS_FreeValue(ctx, prop);\n                    goto fail;\n                }\n                ent->ops[i] = JS_VALUE_GET_OBJ(prop);\n            }\n        }\n    }\n    opset->is_primitive = is_primitive;\n    opset->operator_counter = ctx->rt->operator_count++;\n    return opset_obj;\n fail:\n    JS_FreeValue(ctx, opset_obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_operators_create(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    return js_operators_create_internal(ctx, argc, argv, FALSE);\n}\n\nstatic JSValue js_operators_updateBigIntOperators(JSContext *ctx, JSValueConst this_val,\n                                                  int argc, JSValueConst *argv)\n{\n    JSValue opset_obj, prop;\n    JSOperatorSetData *opset;\n    const JSOverloadableOperatorEnum ops[2] = { JS_OVOP_DIV, JS_OVOP_POW };\n    JSOverloadableOperatorEnum op;\n    int i;\n    \n    opset_obj = JS_GetProperty(ctx, ctx->class_proto[JS_CLASS_BIG_INT],\n                               JS_ATOM_Symbol_operatorSet);\n    if (JS_IsException(opset_obj))\n        goto fail;\n    opset = JS_GetOpaque2(ctx, opset_obj, JS_CLASS_OPERATOR_SET);\n    if (!opset)\n        goto fail;\n    for(i = 0; i < countof(ops); i++) {\n        op = ops[i];\n        prop = JS_GetPropertyStr(ctx, argv[0],\n                                 js_overloadable_operator_names[op]);\n        if (JS_IsException(prop))\n            goto fail;\n        if (!JS_IsUndefined(prop)) {\n            if (!JS_IsNull(prop) && check_function(ctx, prop)) {\n                JS_FreeValue(ctx, prop);\n                goto fail;\n            }\n            if (opset->self_ops[op])\n                JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, opset->self_ops[op]));\n            if (JS_IsNull(prop)) {\n                opset->self_ops[op] = NULL;\n            } else {\n                opset->self_ops[op] = JS_VALUE_GET_PTR(prop);\n            }\n        }\n    }\n    JS_FreeValue(ctx, opset_obj);\n    return JS_UNDEFINED;\n fail:\n    JS_FreeValue(ctx, opset_obj);\n    return JS_EXCEPTION;\n}\n\nstatic int js_operators_set_default(JSContext *ctx, JSValueConst obj)\n{\n    JSValue opset_obj;\n\n    if (!JS_IsObject(obj)) /* in case the prototype is not defined */\n        return 0;\n    opset_obj = js_operators_create_internal(ctx, 0, NULL, TRUE);\n    if (JS_IsException(opset_obj))\n        return -1;\n    /* cannot be modified by the user */\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_Symbol_operatorSet,\n                           opset_obj, 0);\n    return 0;\n}\n\nstatic JSValue js_dummy_operators_ctor(JSContext *ctx, JSValueConst new_target,\n                                       int argc, JSValueConst *argv)\n{\n    return js_create_from_ctor(ctx, new_target, JS_CLASS_OBJECT);\n}\n\nstatic JSValue js_global_operators(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    JSValue func_obj, proto, opset_obj;\n\n    func_obj = JS_UNDEFINED;\n    proto = JS_NewObject(ctx);\n    if (JS_IsException(proto))\n        return JS_EXCEPTION;\n    opset_obj = js_operators_create_internal(ctx, argc, argv, FALSE);\n    if (JS_IsException(opset_obj))\n        goto fail;\n    JS_DefinePropertyValue(ctx, proto, JS_ATOM_Symbol_operatorSet,\n                           opset_obj, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    func_obj = JS_NewCFunction2(ctx, js_dummy_operators_ctor, \"Operators\",\n                                0, JS_CFUNC_constructor, 0);\n    if (JS_IsException(func_obj))\n        goto fail;\n    JS_SetConstructor2(ctx, func_obj, proto,\n                       0, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    JS_FreeValue(ctx, proto);\n    return func_obj;\n fail:\n    JS_FreeValue(ctx, proto);\n    JS_FreeValue(ctx, func_obj);\n    return JS_EXCEPTION;\n}\n\nstatic const JSCFunctionListEntry js_operators_funcs[] = {\n    JS_CFUNC_DEF(\"create\", 1, js_operators_create ),\n    JS_CFUNC_DEF(\"updateBigIntOperators\", 2, js_operators_updateBigIntOperators ),\n};\n\n/* must be called after all overloadable base types are initialized */\nvoid JS_AddIntrinsicOperators(JSContext *ctx)\n{\n    JSValue obj;\n\n    ctx->allow_operator_overloading = TRUE;\n    obj = JS_NewCFunction(ctx, js_global_operators, \"Operators\", 1);\n    JS_SetPropertyFunctionList(ctx, obj,\n                               js_operators_funcs,\n                               countof(js_operators_funcs));\n    JS_DefinePropertyValue(ctx, ctx->global_obj, JS_ATOM_Operators,\n                           obj,\n                           JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    /* add default operatorSets */\n    js_operators_set_default(ctx, ctx->class_proto[JS_CLASS_BOOLEAN]);\n    js_operators_set_default(ctx, ctx->class_proto[JS_CLASS_NUMBER]);\n    js_operators_set_default(ctx, ctx->class_proto[JS_CLASS_STRING]);\n    js_operators_set_default(ctx, ctx->class_proto[JS_CLASS_BIG_INT]);\n    js_operators_set_default(ctx, ctx->class_proto[JS_CLASS_BIG_FLOAT]);\n    js_operators_set_default(ctx, ctx->class_proto[JS_CLASS_BIG_DECIMAL]);\n}\n\n/* BigInt */\n\nstatic JSValue JS_ToBigIntCtorFree(JSContext *ctx, JSValue val)\n{\n    uint32_t tag;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n        val = JS_NewBigInt64(ctx, JS_VALUE_GET_INT(val));\n        break;\n    case JS_TAG_BIG_INT:\n        break;\n    case JS_TAG_FLOAT64:\n    case JS_TAG_BIG_FLOAT:\n        {\n            bf_t *a, a_s;\n            \n            a = JS_ToBigFloat(ctx, &a_s, val);\n            if (!bf_is_finite(a)) {\n                JS_FreeValue(ctx, val);\n                val = JS_ThrowRangeError(ctx, \"cannot convert NaN or Infinity to bigint\");\n            } else {\n                JSValue val1 = JS_NewBigInt(ctx);\n                bf_t *r;\n                int ret;\n                if (JS_IsException(val1)) {\n                    JS_FreeValue(ctx, val);\n                    return JS_EXCEPTION;\n                }\n                r = JS_GetBigInt(val1);\n                ret = bf_set(r, a);\n                ret |= bf_rint(r, BF_RNDZ);\n                JS_FreeValue(ctx, val);\n                if (ret & BF_ST_MEM_ERROR) {\n                    JS_FreeValue(ctx, val1);\n                    val = JS_ThrowOutOfMemory(ctx);\n                } else if (ret & BF_ST_INEXACT) {\n                    JS_FreeValue(ctx, val1);\n                    val = JS_ThrowRangeError(ctx, \"cannot convert to bigint: not an integer\");\n                } else {\n                    val = JS_CompactBigInt(ctx, val1);\n                }\n            }\n            if (a == &a_s)\n                bf_delete(a);\n        }\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        val = JS_ToStringFree(ctx, val);\n         if (JS_IsException(val))\n            break;\n        goto redo;\n    case JS_TAG_STRING:\n        val = JS_StringToBigIntErr(ctx, val);\n        break;\n    case JS_TAG_OBJECT:\n        val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER);\n        if (JS_IsException(val))\n            break;\n        goto redo;\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n    default:\n        JS_FreeValue(ctx, val);\n        return JS_ThrowTypeError(ctx, \"cannot convert to bigint\");\n    }\n    return val;\n}\n\nstatic JSValue js_bigint_constructor(JSContext *ctx,\n                                     JSValueConst new_target,\n                                     int argc, JSValueConst *argv)\n{\n    if (!JS_IsUndefined(new_target))\n        return JS_ThrowTypeError(ctx, \"not a constructor\");\n    return JS_ToBigIntCtorFree(ctx, JS_DupValue(ctx, argv[0]));\n}\n\nstatic JSValue js_thisBigIntValue(JSContext *ctx, JSValueConst this_val)\n{\n    if (JS_IsBigInt(ctx, this_val))\n        return JS_DupValue(ctx, this_val);\n\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_BIG_INT) {\n            if (JS_IsBigInt(ctx, p->u.object_data))\n                return JS_DupValue(ctx, p->u.object_data);\n        }\n    }\n    return JS_ThrowTypeError(ctx, \"not a bigint\");\n}\n\nstatic JSValue js_bigint_toString(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    JSValue val;\n    int base;\n    JSValue ret;\n\n    val = js_thisBigIntValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (argc == 0 || JS_IsUndefined(argv[0])) {\n        base = 10;\n    } else {\n        base = js_get_radix(ctx, argv[0]);\n        if (base < 0)\n            goto fail;\n    }\n    ret = js_bigint_to_string1(ctx, val, base);\n    JS_FreeValue(ctx, val);\n    return ret;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_bigint_valueOf(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    return js_thisBigIntValue(ctx, this_val);\n}\n\nstatic JSValue js_bigint_div(JSContext *ctx,\n                              JSValueConst this_val,\n                              int argc, JSValueConst *argv, int magic)\n{\n    bf_t a_s, b_s, *a, *b, *r, *q;\n    int status;\n    JSValue q_val, r_val;\n    \n    q_val = JS_NewBigInt(ctx);\n    if (JS_IsException(q_val))\n        return JS_EXCEPTION;\n    r_val = JS_NewBigInt(ctx);\n    if (JS_IsException(r_val))\n        goto fail;\n    b = NULL;\n    a = JS_ToBigInt(ctx, &a_s, argv[0]);\n    if (!a)\n        goto fail;\n    b = JS_ToBigInt(ctx, &b_s, argv[1]);\n    if (!b) {\n        JS_FreeBigInt(ctx, a, &a_s);\n        goto fail;\n    }\n    q = JS_GetBigInt(q_val);\n    r = JS_GetBigInt(r_val);\n    status = bf_divrem(q, r, a, b, BF_PREC_INF, BF_RNDZ, magic & 0xf);\n    JS_FreeBigInt(ctx, a, &a_s);\n    JS_FreeBigInt(ctx, b, &b_s);\n    if (unlikely(status)) {\n        throw_bf_exception(ctx, status);\n        goto fail;\n    }\n    q_val = JS_CompactBigInt(ctx, q_val);\n    if (magic & 0x10) {\n        JSValue ret;\n        ret = JS_NewArray(ctx);\n        if (JS_IsException(ret))\n            goto fail;\n        JS_SetPropertyUint32(ctx, ret, 0, q_val);\n        JS_SetPropertyUint32(ctx, ret, 1, JS_CompactBigInt(ctx, r_val));\n        return ret;\n    } else {\n        JS_FreeValue(ctx, r_val);\n        return q_val;\n    }\n fail:\n    JS_FreeValue(ctx, q_val);\n    JS_FreeValue(ctx, r_val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_bigint_sqrt(JSContext *ctx,\n                               JSValueConst this_val,\n                               int argc, JSValueConst *argv, int magic)\n{\n    bf_t a_s, *a, *r, *rem;\n    int status;\n    JSValue r_val, rem_val;\n    \n    r_val = JS_NewBigInt(ctx);\n    if (JS_IsException(r_val))\n        return JS_EXCEPTION;\n    rem_val = JS_NewBigInt(ctx);\n    if (JS_IsException(rem_val))\n        return JS_EXCEPTION;\n    r = JS_GetBigInt(r_val);\n    rem = JS_GetBigInt(rem_val);\n\n    a = JS_ToBigInt(ctx, &a_s, argv[0]);\n    if (!a)\n        goto fail;\n    status = bf_sqrtrem(r, rem, a);\n    JS_FreeBigInt(ctx, a, &a_s);\n    if (unlikely(status & ~BF_ST_INEXACT)) {\n        throw_bf_exception(ctx, status);\n        goto fail;\n    }\n    r_val = JS_CompactBigInt(ctx, r_val);\n    if (magic) {\n        JSValue ret;\n        ret = JS_NewArray(ctx);\n        if (JS_IsException(ret))\n            goto fail;\n        JS_SetPropertyUint32(ctx, ret, 0, r_val);\n        JS_SetPropertyUint32(ctx, ret, 1, JS_CompactBigInt(ctx, rem_val));\n        return ret;\n    } else {\n        JS_FreeValue(ctx, rem_val);\n        return r_val;\n    }\n fail:\n    JS_FreeValue(ctx, r_val);\n    JS_FreeValue(ctx, rem_val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_bigint_op1(JSContext *ctx,\n                              JSValueConst this_val,\n                              int argc, JSValueConst *argv,\n                              int magic)\n{\n    bf_t a_s, *a;\n    int64_t res;\n\n    a = JS_ToBigInt(ctx, &a_s, argv[0]);\n    if (!a)\n        return JS_EXCEPTION;\n    switch(magic) {\n    case 0: /* floorLog2 */\n        if (a->sign || a->expn <= 0) {\n            res = -1;\n        } else {\n            res = a->expn - 1;\n        }\n        break;\n    case 1: /* ctz */\n        if (bf_is_zero(a)) {\n            res = -1;\n        } else {\n            res = bf_get_exp_min(a);\n        }\n        break;\n    default:\n        abort();\n    }\n    JS_FreeBigInt(ctx, a, &a_s);\n    return JS_NewBigInt64(ctx, res);\n}\n\nstatic JSValue js_bigint_asUintN(JSContext *ctx,\n                                  JSValueConst this_val,\n                                  int argc, JSValueConst *argv, int asIntN)\n{\n    uint64_t bits;\n    bf_t a_s, *a = &a_s, *r, mask_s, *mask = &mask_s;\n    JSValue res;\n    \n    if (JS_ToIndex(ctx, &bits, argv[0]))\n        return JS_EXCEPTION;\n    res = JS_NewBigInt(ctx);\n    if (JS_IsException(res))\n        return JS_EXCEPTION;\n    r = JS_GetBigInt(res);\n    a = JS_ToBigInt(ctx, &a_s, argv[1]);\n    if (!a) {\n        JS_FreeValue(ctx, res);\n        return JS_EXCEPTION;\n    }\n    /* XXX: optimize */\n    r = JS_GetBigInt(res);\n    bf_init(ctx->bf_ctx, mask);\n    bf_set_ui(mask, 1);\n    bf_mul_2exp(mask, bits, BF_PREC_INF, BF_RNDZ);\n    bf_add_si(mask, mask, -1, BF_PREC_INF, BF_RNDZ);\n    bf_logic_and(r, a, mask);\n    if (asIntN && bits != 0) {\n        bf_set_ui(mask, 1);\n        bf_mul_2exp(mask, bits - 1, BF_PREC_INF, BF_RNDZ);\n        if (bf_cmpu(r, mask) >= 0) {\n            bf_set_ui(mask, 1);\n            bf_mul_2exp(mask, bits, BF_PREC_INF, BF_RNDZ);\n            bf_sub(r, r, mask, BF_PREC_INF, BF_RNDZ);\n        }\n    }\n    bf_delete(mask);\n    JS_FreeBigInt(ctx, a, &a_s);\n    return JS_CompactBigInt(ctx, res);\n}\n\nstatic const JSCFunctionListEntry js_bigint_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"asUintN\", 2, js_bigint_asUintN, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"asIntN\", 2, js_bigint_asUintN, 1 ),\n    /* QuickJS extensions */\n    JS_CFUNC_MAGIC_DEF(\"tdiv\", 2, js_bigint_div, BF_RNDZ ),\n    JS_CFUNC_MAGIC_DEF(\"fdiv\", 2, js_bigint_div, BF_RNDD ),\n    JS_CFUNC_MAGIC_DEF(\"cdiv\", 2, js_bigint_div, BF_RNDU ),\n    JS_CFUNC_MAGIC_DEF(\"ediv\", 2, js_bigint_div, BF_DIVREM_EUCLIDIAN ),\n    JS_CFUNC_MAGIC_DEF(\"tdivrem\", 2, js_bigint_div, BF_RNDZ | 0x10 ),\n    JS_CFUNC_MAGIC_DEF(\"fdivrem\", 2, js_bigint_div, BF_RNDD | 0x10 ),\n    JS_CFUNC_MAGIC_DEF(\"cdivrem\", 2, js_bigint_div, BF_RNDU | 0x10 ),\n    JS_CFUNC_MAGIC_DEF(\"edivrem\", 2, js_bigint_div, BF_DIVREM_EUCLIDIAN | 0x10 ),\n    JS_CFUNC_MAGIC_DEF(\"sqrt\", 1, js_bigint_sqrt, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"sqrtrem\", 1, js_bigint_sqrt, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"floorLog2\", 1, js_bigint_op1, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"ctz\", 1, js_bigint_op1, 1 ),\n};\n\nstatic const JSCFunctionListEntry js_bigint_proto_funcs[] = {\n    JS_CFUNC_DEF(\"toString\", 0, js_bigint_toString ),\n    JS_CFUNC_DEF(\"valueOf\", 0, js_bigint_valueOf ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"BigInt\", JS_PROP_CONFIGURABLE ),\n};\n\nvoid JS_AddIntrinsicBigInt(JSContext *ctx)\n{\n    JSRuntime *rt = ctx->rt;\n    JSValueConst obj1;\n\n    rt->bigint_ops.to_string = js_bigint_to_string;\n    rt->bigint_ops.from_string = js_string_to_bigint;\n    rt->bigint_ops.unary_arith = js_unary_arith_bigint;\n    rt->bigint_ops.binary_arith = js_binary_arith_bigint;\n    rt->bigint_ops.compare = js_compare_bigfloat;\n    \n    ctx->class_proto[JS_CLASS_BIG_INT] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_BIG_INT],\n                               js_bigint_proto_funcs,\n                               countof(js_bigint_proto_funcs));\n    obj1 = JS_NewGlobalCConstructor(ctx, \"BigInt\", js_bigint_constructor, 1,\n                                    ctx->class_proto[JS_CLASS_BIG_INT]);\n    JS_SetPropertyFunctionList(ctx, obj1, js_bigint_funcs,\n                               countof(js_bigint_funcs));\n}\n\n/* BigFloat */\n\nstatic JSValue js_thisBigFloatValue(JSContext *ctx, JSValueConst this_val)\n{\n    if (JS_IsBigFloat(this_val))\n        return JS_DupValue(ctx, this_val);\n\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_BIG_FLOAT) {\n            if (JS_IsBigFloat(p->u.object_data))\n                return JS_DupValue(ctx, p->u.object_data);\n        }\n    }\n    return JS_ThrowTypeError(ctx, \"not a bigfloat\");\n}\n\nstatic JSValue js_bigfloat_toString(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSValue val;\n    int base;\n    JSValue ret;\n\n    val = js_thisBigFloatValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (argc == 0 || JS_IsUndefined(argv[0])) {\n        base = 10;\n    } else {\n        base = js_get_radix(ctx, argv[0]);\n        if (base < 0)\n            goto fail;\n    }\n    ret = js_ftoa(ctx, val, base, 0, BF_RNDN | BF_FTOA_FORMAT_FREE_MIN);\n    JS_FreeValue(ctx, val);\n    return ret;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_bigfloat_valueOf(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    return js_thisBigFloatValue(ctx, this_val);\n}\n\nstatic int bigfloat_get_rnd_mode(JSContext *ctx, JSValueConst val)\n{\n    int rnd_mode;\n    if (JS_ToInt32Sat(ctx, &rnd_mode, val))\n        return -1;\n    if (rnd_mode < BF_RNDN || rnd_mode > BF_RNDF) {\n        JS_ThrowRangeError(ctx, \"invalid rounding mode\");\n        return -1;\n    }\n    return rnd_mode;\n}\n\nstatic JSValue js_bigfloat_toFixed(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    int64_t f;\n    int rnd_mode, radix;\n\n    val = js_thisBigFloatValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_ToInt64Sat(ctx, &f, argv[0]))\n        goto fail;\n    if (f < 0 || f > BF_PREC_MAX) {\n        JS_ThrowRangeError(ctx, \"invalid number of digits\");\n        goto fail;\n    }\n    rnd_mode = BF_RNDNA;\n    radix = 10;\n    /* XXX: swap parameter order for rounding mode and radix */\n    if (argc > 1) {\n        rnd_mode = bigfloat_get_rnd_mode(ctx, argv[1]);\n        if (rnd_mode < 0)\n            goto fail;\n    }\n    if (argc > 2) {\n        radix = js_get_radix(ctx, argv[2]);\n        if (radix < 0)\n            goto fail;\n    }\n    ret = js_ftoa(ctx, val, radix, f, rnd_mode | BF_FTOA_FORMAT_FRAC);\n    JS_FreeValue(ctx, val);\n    return ret;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic BOOL js_bigfloat_is_finite(JSContext *ctx, JSValueConst val)\n{\n    BOOL res;\n    uint32_t tag;\n\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            res = bf_is_finite(&p->num);\n        }\n        break;\n    default:\n        res = FALSE;\n        break;\n    }\n    return res;\n}\n\nstatic JSValue js_bigfloat_toExponential(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    int64_t f;\n    int rnd_mode, radix;\n\n    val = js_thisBigFloatValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_ToInt64Sat(ctx, &f, argv[0]))\n        goto fail;\n    if (!js_bigfloat_is_finite(ctx, val)) {\n        ret = JS_ToString(ctx, val);\n    } else if (JS_IsUndefined(argv[0])) {\n        ret = js_ftoa(ctx, val, 10, 0,\n                      BF_RNDN | BF_FTOA_FORMAT_FREE_MIN | BF_FTOA_FORCE_EXP);\n    } else {\n        if (f < 0 || f > BF_PREC_MAX) {\n            JS_ThrowRangeError(ctx, \"invalid number of digits\");\n            goto fail;\n        }\n        rnd_mode = BF_RNDNA;\n        radix = 10;\n        if (argc > 1) {\n            rnd_mode = bigfloat_get_rnd_mode(ctx, argv[1]);\n            if (rnd_mode < 0)\n                goto fail;\n        }\n        if (argc > 2) {\n            radix = js_get_radix(ctx, argv[2]);\n            if (radix < 0)\n                goto fail;\n        }\n        ret = js_ftoa(ctx, val, radix, f + 1,\n                      rnd_mode | BF_FTOA_FORMAT_FIXED | BF_FTOA_FORCE_EXP);\n    }\n    JS_FreeValue(ctx, val);\n    return ret;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_bigfloat_toPrecision(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    int64_t p;\n    int rnd_mode, radix;\n\n    val = js_thisBigFloatValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_IsUndefined(argv[0]))\n        goto to_string;\n    if (JS_ToInt64Sat(ctx, &p, argv[0]))\n        goto fail;\n    if (!js_bigfloat_is_finite(ctx, val)) {\n    to_string:\n        ret = JS_ToString(ctx, this_val);\n    } else {\n        if (p < 1 || p > BF_PREC_MAX) {\n            JS_ThrowRangeError(ctx, \"invalid number of digits\");\n            goto fail;\n        }\n        rnd_mode = BF_RNDNA;\n        radix = 10;\n        if (argc > 1) {\n            rnd_mode = bigfloat_get_rnd_mode(ctx, argv[1]);\n            if (rnd_mode < 0)\n                goto fail;\n        }\n        if (argc > 2) {\n            radix = js_get_radix(ctx, argv[2]);\n            if (radix < 0)\n                goto fail;\n        }\n        ret = js_ftoa(ctx, val, radix, p, rnd_mode | BF_FTOA_FORMAT_FIXED);\n    }\n    JS_FreeValue(ctx, val);\n    return ret;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic const JSCFunctionListEntry js_bigfloat_proto_funcs[] = {\n    JS_CFUNC_DEF(\"toString\", 0, js_bigfloat_toString ),\n    JS_CFUNC_DEF(\"valueOf\", 0, js_bigfloat_valueOf ),\n    JS_CFUNC_DEF(\"toPrecision\", 1, js_bigfloat_toPrecision ),\n    JS_CFUNC_DEF(\"toFixed\", 1, js_bigfloat_toFixed ),\n    JS_CFUNC_DEF(\"toExponential\", 1, js_bigfloat_toExponential ),\n};\n\nstatic JSValue js_bigfloat_constructor(JSContext *ctx,\n                                       JSValueConst new_target,\n                                       int argc, JSValueConst *argv)\n{\n    JSValue val;\n    if (!JS_IsUndefined(new_target))\n        return JS_ThrowTypeError(ctx, \"not a constructor\");\n    if (argc == 0) {\n        bf_t *r;\n        val = JS_NewBigFloat(ctx);\n        if (JS_IsException(val))\n            return val;\n        r = JS_GetBigFloat(val);\n        bf_set_zero(r, 0);\n    } else {\n        val = JS_DupValue(ctx, argv[0]);\n    redo:\n        switch(JS_VALUE_GET_NORM_TAG(val)) {\n        case JS_TAG_BIG_FLOAT:\n            break;\n        case JS_TAG_FLOAT64:\n            {\n                bf_t *r;\n                double d = JS_VALUE_GET_FLOAT64(val);\n                val = JS_NewBigFloat(ctx);\n                if (JS_IsException(val))\n                    break;\n                r = JS_GetBigFloat(val);\n                if (bf_set_float64(r, d))\n                    goto fail;\n            }\n            break;\n        case JS_TAG_INT:\n            {\n                bf_t *r;\n                int32_t v = JS_VALUE_GET_INT(val);\n                val = JS_NewBigFloat(ctx);\n                if (JS_IsException(val))\n                    break;\n                r = JS_GetBigFloat(val);\n                if (bf_set_si(r, v))\n                    goto fail;\n            }\n            break;\n        case JS_TAG_BIG_INT:\n            /* We keep the full precision of the integer */\n            {\n                JSBigFloat *p = JS_VALUE_GET_PTR(val);\n                val = JS_MKPTR(JS_TAG_BIG_FLOAT, p);\n            }\n            break;\n        case JS_TAG_BIG_DECIMAL:\n            val = JS_ToStringFree(ctx, val);\n            if (JS_IsException(val))\n                break;\n            goto redo;\n        case JS_TAG_STRING:\n            {\n                const char *str, *p;\n                size_t len;\n                int err;\n\n                str = JS_ToCStringLen(ctx, &len, val);\n                JS_FreeValue(ctx, val);\n                if (!str)\n                    return JS_EXCEPTION;\n                p = str;\n                p += skip_spaces(p);\n                if ((p - str) == len) {\n                    bf_t *r;\n                    val = JS_NewBigFloat(ctx);\n                    if (JS_IsException(val))\n                        break;\n                    r = JS_GetBigFloat(val);\n                    bf_set_zero(r, 0);\n                    err = 0;\n                } else {\n                    val = js_atof(ctx, p, &p, 0, ATOD_ACCEPT_BIN_OCT |\n                                  ATOD_TYPE_BIG_FLOAT |\n                                  ATOD_ACCEPT_PREFIX_AFTER_SIGN);\n                    if (JS_IsException(val)) {\n                        JS_FreeCString(ctx, str);\n                        return JS_EXCEPTION;\n                    }\n                    p += skip_spaces(p);\n                    err = ((p - str) != len);\n                }\n                JS_FreeCString(ctx, str);\n                if (err) {\n                    JS_FreeValue(ctx, val);\n                    return JS_ThrowSyntaxError(ctx, \"invalid bigfloat literal\");\n                }\n            }\n            break;\n        case JS_TAG_OBJECT:\n            val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER);\n            if (JS_IsException(val))\n                break;\n            goto redo;\n        case JS_TAG_NULL:\n        case JS_TAG_UNDEFINED:\n        default:\n            JS_FreeValue(ctx, val);\n            return JS_ThrowTypeError(ctx, \"cannot convert to bigfloat\");\n        }\n    }\n    return val;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_bigfloat_get_const(JSContext *ctx,\n                                     JSValueConst this_val, int magic)\n{\n    bf_t *r;\n    JSValue val;\n    val = JS_NewBigFloat(ctx);\n    if (JS_IsException(val))\n        return val;\n    r = JS_GetBigFloat(val);\n    switch(magic) {\n    case 0: /* PI */\n        bf_const_pi(r, ctx->fp_env.prec, ctx->fp_env.flags);\n        break;\n    case 1: /* LN2 */\n        bf_const_log2(r, ctx->fp_env.prec, ctx->fp_env.flags);\n        break;\n    case 2: /* MIN_VALUE */\n    case 3: /* MAX_VALUE */\n        {\n            slimb_t e_range, e;\n            e_range = (limb_t)1 << (bf_get_exp_bits(ctx->fp_env.flags) - 1);\n            bf_set_ui(r, 1);\n            if (magic == 2) {\n                e = -e_range + 2;\n                if (ctx->fp_env.flags & BF_FLAG_SUBNORMAL)\n                    e -= ctx->fp_env.prec - 1;\n                bf_mul_2exp(r, e, ctx->fp_env.prec, ctx->fp_env.flags);\n            } else {\n                bf_mul_2exp(r, ctx->fp_env.prec, ctx->fp_env.prec,\n                            ctx->fp_env.flags);\n                bf_add_si(r, r, -1, ctx->fp_env.prec, ctx->fp_env.flags);\n                bf_mul_2exp(r, e_range - ctx->fp_env.prec, ctx->fp_env.prec,\n                            ctx->fp_env.flags);\n            }\n        }\n        break;\n    case 4: /* EPSILON */\n        bf_set_ui(r, 1);\n        bf_mul_2exp(r, 1 - ctx->fp_env.prec,\n                    ctx->fp_env.prec, ctx->fp_env.flags);\n        break;\n    default:\n        abort();\n    }\n    return val;\n}\n\nstatic JSValue js_bigfloat_parseFloat(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv)\n{\n    bf_t *a;\n    const char *str;\n    JSValue ret;\n    int radix;\n    JSFloatEnv *fe;\n\n    str = JS_ToCString(ctx, argv[0]);\n    if (!str)\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &radix, argv[1])) {\n    fail:\n        JS_FreeCString(ctx, str);\n        return JS_EXCEPTION;\n    }\n    if (radix != 0 && (radix < 2 || radix > 36)) {\n        JS_ThrowRangeError(ctx, \"radix must be between 2 and 36\");\n        goto fail;\n    }\n    fe = &ctx->fp_env;\n    if (argc > 2) {\n        fe = JS_GetOpaque2(ctx, argv[2], JS_CLASS_FLOAT_ENV);\n        if (!fe)\n            goto fail;\n    }\n    ret = JS_NewBigFloat(ctx);\n    if (JS_IsException(ret))\n        goto done;\n    a = JS_GetBigFloat(ret);\n    /* XXX: use js_atof() */\n    bf_atof(a, str, NULL, radix, fe->prec, fe->flags);\n done:\n    JS_FreeCString(ctx, str);\n    return ret;\n}\n\nstatic JSValue js_bigfloat_isFinite(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSValueConst val = argv[0];\n    JSBigFloat *p;\n    \n    if (JS_VALUE_GET_NORM_TAG(val) != JS_TAG_BIG_FLOAT)\n        return JS_FALSE;\n    p = JS_VALUE_GET_PTR(val);\n    return JS_NewBool(ctx, bf_is_finite(&p->num));\n}\n\nstatic JSValue js_bigfloat_isNaN(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValueConst val = argv[0];\n    JSBigFloat *p;\n    \n    if (JS_VALUE_GET_NORM_TAG(val) != JS_TAG_BIG_FLOAT)\n        return JS_FALSE;\n    p = JS_VALUE_GET_PTR(val);\n    return JS_NewBool(ctx, bf_is_nan(&p->num));\n}\n\nenum {\n    MATH_OP_ABS,\n    MATH_OP_FLOOR,\n    MATH_OP_CEIL,\n    MATH_OP_ROUND,\n    MATH_OP_TRUNC,\n    MATH_OP_SQRT,\n    MATH_OP_FPROUND,\n    MATH_OP_ACOS,\n    MATH_OP_ASIN,\n    MATH_OP_ATAN,\n    MATH_OP_ATAN2,\n    MATH_OP_COS,\n    MATH_OP_EXP,\n    MATH_OP_LOG,\n    MATH_OP_POW,\n    MATH_OP_SIN,\n    MATH_OP_TAN,\n    MATH_OP_FMOD,\n    MATH_OP_REM,\n    MATH_OP_SIGN,\n\n    MATH_OP_ADD,\n    MATH_OP_SUB,\n    MATH_OP_MUL,\n    MATH_OP_DIV,\n};\n\nstatic JSValue js_bigfloat_fop(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv, int magic)\n{\n    bf_t a_s, *a, *r;\n    JSFloatEnv *fe;\n    int rnd_mode;\n    JSValue op1, res;\n\n    op1 = JS_ToNumeric(ctx, argv[0]);\n    if (JS_IsException(op1))\n        return op1;\n    a = JS_ToBigFloat(ctx, &a_s, op1);\n    fe = &ctx->fp_env;\n    if (argc > 1) {\n        fe = JS_GetOpaque2(ctx, argv[1], JS_CLASS_FLOAT_ENV);\n        if (!fe)\n            goto fail;\n    }\n    res = JS_NewBigFloat(ctx);\n    if (JS_IsException(res)) {\n    fail:\n        if (a == &a_s)\n            bf_delete(a);\n        JS_FreeValue(ctx, op1);\n        return JS_EXCEPTION;\n    }\n    r = JS_GetBigFloat(res);\n    switch (magic) {\n    case MATH_OP_ABS:\n        bf_set(r, a);\n        r->sign = 0;\n        break;\n    case MATH_OP_FLOOR:\n        rnd_mode = BF_RNDD;\n        goto rint;\n    case MATH_OP_CEIL:\n        rnd_mode = BF_RNDU;\n        goto rint;\n    case MATH_OP_ROUND:\n        rnd_mode = BF_RNDNA;\n        goto rint;\n    case MATH_OP_TRUNC:\n        rnd_mode = BF_RNDZ;\n    rint:\n        bf_set(r, a);\n        fe->status |= bf_rint(r, rnd_mode);\n        break;\n    case MATH_OP_SQRT:\n        fe->status |= bf_sqrt(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_FPROUND:\n        bf_set(r, a);\n        fe->status |= bf_round(r, fe->prec, fe->flags);\n        break;\n    case MATH_OP_ACOS:\n        fe->status |= bf_acos(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_ASIN:\n        fe->status |= bf_asin(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_ATAN:\n        fe->status |= bf_atan(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_COS:\n        fe->status |= bf_cos(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_EXP:\n        fe->status |= bf_exp(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_LOG:\n        fe->status |= bf_log(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_SIN:\n        fe->status |= bf_sin(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_TAN:\n        fe->status |= bf_tan(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_SIGN:\n        if (bf_is_nan(a) || bf_is_zero(a)) {\n            bf_set(r, a);\n        } else {\n            bf_set_si(r, 1 - 2 * a->sign);\n        }\n        break;\n    default:\n        abort();\n    }\n    if (a == &a_s)\n        bf_delete(a);\n    JS_FreeValue(ctx, op1);\n    return res;\n}\n\nstatic JSValue js_bigfloat_fop2(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv, int magic)\n{\n    bf_t a_s, *a, b_s, *b, r_s, *r = &r_s;\n    JSFloatEnv *fe;\n    JSValue op1, op2, res;\n\n    op1 = JS_ToNumeric(ctx, argv[0]);\n    if (JS_IsException(op1))\n        return op1;\n    op2 = JS_ToNumeric(ctx, argv[1]);\n    if (JS_IsException(op2)) {\n        JS_FreeValue(ctx, op1);\n        return op2;\n    }\n    a = JS_ToBigFloat(ctx, &a_s, op1);\n    b = JS_ToBigFloat(ctx, &b_s, op2);\n    fe = &ctx->fp_env;\n    if (argc > 2) {\n        fe = JS_GetOpaque2(ctx, argv[2], JS_CLASS_FLOAT_ENV);\n        if (!fe)\n            goto fail;\n    }\n    res = JS_NewBigFloat(ctx);\n    if (JS_IsException(res)) {\n    fail:\n        if (a == &a_s)\n            bf_delete(a);\n        if (b == &b_s)\n            bf_delete(b);\n        JS_FreeValue(ctx, op1);\n        JS_FreeValue(ctx, op2);\n        return JS_EXCEPTION;\n    }\n    r = JS_GetBigFloat(res);\n    switch (magic) {\n    case MATH_OP_ATAN2:\n        fe->status |= bf_atan2(r, a, b, fe->prec, fe->flags);\n        break;\n    case MATH_OP_POW:\n        fe->status |= bf_pow(r, a, b, fe->prec, fe->flags | BF_POW_JS_QUIRKS);\n        break;\n    case MATH_OP_FMOD:\n        fe->status |= bf_rem(r, a, b, fe->prec, fe->flags, BF_RNDZ);\n        break;\n    case MATH_OP_REM:\n        fe->status |= bf_rem(r, a, b, fe->prec, fe->flags, BF_RNDN);\n        break;\n    case MATH_OP_ADD:\n        fe->status |= bf_add(r, a, b, fe->prec, fe->flags);\n        break;\n    case MATH_OP_SUB:\n        fe->status |= bf_sub(r, a, b, fe->prec, fe->flags);\n        break;\n    case MATH_OP_MUL:\n        fe->status |= bf_mul(r, a, b, fe->prec, fe->flags);\n        break;\n    case MATH_OP_DIV:\n        fe->status |= bf_div(r, a, b, fe->prec, fe->flags);\n        break;\n    default:\n        abort();\n    }\n    if (a == &a_s)\n        bf_delete(a);\n    if (b == &b_s)\n        bf_delete(b);\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    return res;\n}\n\nstatic const JSCFunctionListEntry js_bigfloat_funcs[] = {\n    JS_CGETSET_MAGIC_DEF(\"PI\", js_bigfloat_get_const, NULL, 0 ),\n    JS_CGETSET_MAGIC_DEF(\"LN2\", js_bigfloat_get_const, NULL, 1 ),\n    JS_CGETSET_MAGIC_DEF(\"MIN_VALUE\", js_bigfloat_get_const, NULL, 2 ),\n    JS_CGETSET_MAGIC_DEF(\"MAX_VALUE\", js_bigfloat_get_const, NULL, 3 ),\n    JS_CGETSET_MAGIC_DEF(\"EPSILON\", js_bigfloat_get_const, NULL, 4 ),\n    JS_CFUNC_DEF(\"parseFloat\", 1, js_bigfloat_parseFloat ),\n    JS_CFUNC_DEF(\"isFinite\", 1, js_bigfloat_isFinite ),\n    JS_CFUNC_DEF(\"isNaN\", 1, js_bigfloat_isNaN ),\n    JS_CFUNC_MAGIC_DEF(\"abs\", 1, js_bigfloat_fop, MATH_OP_ABS ),\n    JS_CFUNC_MAGIC_DEF(\"fpRound\", 1, js_bigfloat_fop, MATH_OP_FPROUND ),\n    JS_CFUNC_MAGIC_DEF(\"floor\", 1, js_bigfloat_fop, MATH_OP_FLOOR ),\n    JS_CFUNC_MAGIC_DEF(\"ceil\", 1, js_bigfloat_fop, MATH_OP_CEIL ),\n    JS_CFUNC_MAGIC_DEF(\"round\", 1, js_bigfloat_fop, MATH_OP_ROUND ),\n    JS_CFUNC_MAGIC_DEF(\"trunc\", 1, js_bigfloat_fop, MATH_OP_TRUNC ),\n    JS_CFUNC_MAGIC_DEF(\"sqrt\", 1, js_bigfloat_fop, MATH_OP_SQRT ),\n    JS_CFUNC_MAGIC_DEF(\"acos\", 1, js_bigfloat_fop, MATH_OP_ACOS ),\n    JS_CFUNC_MAGIC_DEF(\"asin\", 1, js_bigfloat_fop, MATH_OP_ASIN ),\n    JS_CFUNC_MAGIC_DEF(\"atan\", 1, js_bigfloat_fop, MATH_OP_ATAN ),\n    JS_CFUNC_MAGIC_DEF(\"atan2\", 2, js_bigfloat_fop2, MATH_OP_ATAN2 ),\n    JS_CFUNC_MAGIC_DEF(\"cos\", 1, js_bigfloat_fop, MATH_OP_COS ),\n    JS_CFUNC_MAGIC_DEF(\"exp\", 1, js_bigfloat_fop, MATH_OP_EXP ),\n    JS_CFUNC_MAGIC_DEF(\"log\", 1, js_bigfloat_fop, MATH_OP_LOG ),\n    JS_CFUNC_MAGIC_DEF(\"pow\", 2, js_bigfloat_fop2, MATH_OP_POW ),\n    JS_CFUNC_MAGIC_DEF(\"sin\", 1, js_bigfloat_fop, MATH_OP_SIN ),\n    JS_CFUNC_MAGIC_DEF(\"tan\", 1, js_bigfloat_fop, MATH_OP_TAN ),\n    JS_CFUNC_MAGIC_DEF(\"sign\", 1, js_bigfloat_fop, MATH_OP_SIGN ),\n    JS_CFUNC_MAGIC_DEF(\"add\", 2, js_bigfloat_fop2, MATH_OP_ADD ),\n    JS_CFUNC_MAGIC_DEF(\"sub\", 2, js_bigfloat_fop2, MATH_OP_SUB ),\n    JS_CFUNC_MAGIC_DEF(\"mul\", 2, js_bigfloat_fop2, MATH_OP_MUL ),\n    JS_CFUNC_MAGIC_DEF(\"div\", 2, js_bigfloat_fop2, MATH_OP_DIV ),\n    JS_CFUNC_MAGIC_DEF(\"fmod\", 2, js_bigfloat_fop2, MATH_OP_FMOD ),\n    JS_CFUNC_MAGIC_DEF(\"remainder\", 2, js_bigfloat_fop2, MATH_OP_REM ),\n};\n\n/* FloatEnv */\n\nstatic JSValue js_float_env_constructor(JSContext *ctx,\n                                        JSValueConst new_target,\n                                        int argc, JSValueConst *argv)\n{\n    JSValue obj;\n    JSFloatEnv *fe;\n    int64_t prec;\n    int flags, rndmode;\n\n    prec = ctx->fp_env.prec;\n    flags = ctx->fp_env.flags;\n    if (!JS_IsUndefined(argv[0])) {\n        if (JS_ToInt64Sat(ctx, &prec, argv[0]))\n            return JS_EXCEPTION;\n        if (prec < BF_PREC_MIN || prec > BF_PREC_MAX)\n            return JS_ThrowRangeError(ctx, \"invalid precision\");\n        flags = BF_RNDN; /* RNDN, max exponent size, no subnormal */\n        if (argc > 1 && !JS_IsUndefined(argv[1])) {\n            if (JS_ToInt32Sat(ctx, &rndmode, argv[1]))\n                return JS_EXCEPTION;\n            if (rndmode < BF_RNDN || rndmode > BF_RNDF)\n                return JS_ThrowRangeError(ctx, \"invalid rounding mode\");\n            flags = rndmode;\n        }\n    }\n\n    obj = JS_NewObjectClass(ctx, JS_CLASS_FLOAT_ENV);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    fe = js_malloc(ctx, sizeof(*fe));\n    if (!fe)\n        return JS_EXCEPTION;\n    fe->prec = prec;\n    fe->flags = flags;\n    fe->status = 0;\n    JS_SetOpaque(obj, fe);\n    return obj;\n}\n\nstatic void js_float_env_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSFloatEnv *fe = JS_GetOpaque(val, JS_CLASS_FLOAT_ENV);\n    js_free_rt(rt, fe);\n}\n\nstatic JSValue js_float_env_get_prec(JSContext *ctx, JSValueConst this_val)\n{\n    return JS_NewInt64(ctx, ctx->fp_env.prec);\n}\n\nstatic JSValue js_float_env_get_expBits(JSContext *ctx, JSValueConst this_val)\n{\n    return JS_NewInt32(ctx, bf_get_exp_bits(ctx->fp_env.flags));\n}\n\nstatic JSValue js_float_env_setPrec(JSContext *ctx,\n                                    JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSValueConst func;\n    int exp_bits, flags, saved_flags;\n    JSValue ret;\n    limb_t saved_prec;\n    int64_t prec;\n\n    func = argv[0];\n    if (JS_ToInt64Sat(ctx, &prec, argv[1]))\n        return JS_EXCEPTION;\n    if (prec < BF_PREC_MIN || prec > BF_PREC_MAX)\n        return JS_ThrowRangeError(ctx, \"invalid precision\");\n    exp_bits = BF_EXP_BITS_MAX;\n\n    if (argc > 2 && !JS_IsUndefined(argv[2])) {\n        if (JS_ToInt32Sat(ctx, &exp_bits, argv[2]))\n            return JS_EXCEPTION;\n        if (exp_bits < BF_EXP_BITS_MIN || exp_bits > BF_EXP_BITS_MAX)\n            return JS_ThrowRangeError(ctx, \"invalid number of exponent bits\");\n    }\n\n    flags = BF_RNDN | BF_FLAG_SUBNORMAL | bf_set_exp_bits(exp_bits);\n\n    saved_prec = ctx->fp_env.prec;\n    saved_flags = ctx->fp_env.flags;\n\n    ctx->fp_env.prec = prec;\n    ctx->fp_env.flags = flags;\n\n    ret = JS_Call(ctx, func, JS_UNDEFINED, 0, NULL);\n    /* always restore the floating point precision */\n    ctx->fp_env.prec = saved_prec;\n    ctx->fp_env.flags = saved_flags;\n    return ret;\n}\n\n#define FE_PREC      (-1)\n#define FE_EXP       (-2)\n#define FE_RNDMODE   (-3)\n#define FE_SUBNORMAL (-4)\n\nstatic JSValue js_float_env_proto_get_status(JSContext *ctx, JSValueConst this_val, int magic)\n{\n    JSFloatEnv *fe;\n    fe = JS_GetOpaque2(ctx, this_val, JS_CLASS_FLOAT_ENV);\n    if (!fe)\n        return JS_EXCEPTION;\n    switch(magic) {\n    case FE_PREC:\n        return JS_NewInt64(ctx, fe->prec);\n    case FE_EXP:\n        return JS_NewInt32(ctx, bf_get_exp_bits(fe->flags));\n    case FE_RNDMODE:\n        return JS_NewInt32(ctx, fe->flags & BF_RND_MASK);\n    case FE_SUBNORMAL:\n        return JS_NewBool(ctx, (fe->flags & BF_FLAG_SUBNORMAL) != 0);\n    default:\n        return JS_NewBool(ctx, (fe->status & magic) != 0);\n    }\n}\n\nstatic JSValue js_float_env_proto_set_status(JSContext *ctx, JSValueConst this_val, JSValueConst val, int magic)\n{\n    JSFloatEnv *fe;\n    int b;\n    int64_t prec;\n\n    fe = JS_GetOpaque2(ctx, this_val, JS_CLASS_FLOAT_ENV);\n    if (!fe)\n        return JS_EXCEPTION;\n    switch(magic) {\n    case FE_PREC:\n        if (JS_ToInt64Sat(ctx, &prec, val))\n            return JS_EXCEPTION;\n        if (prec < BF_PREC_MIN || prec > BF_PREC_MAX)\n            return JS_ThrowRangeError(ctx, \"invalid precision\");\n        fe->prec = prec;\n        break;\n    case FE_EXP:\n        if (JS_ToInt32Sat(ctx, &b, val))\n            return JS_EXCEPTION;\n        if (b < BF_EXP_BITS_MIN || b > BF_EXP_BITS_MAX)\n            return JS_ThrowRangeError(ctx, \"invalid number of exponent bits\");\n        fe->flags = (fe->flags & ~(BF_EXP_BITS_MASK << BF_EXP_BITS_SHIFT)) |\n            bf_set_exp_bits(b);\n        break;\n    case FE_RNDMODE:\n        b = bigfloat_get_rnd_mode(ctx, val);\n        if (b < 0)\n            return JS_EXCEPTION;\n        fe->flags = (fe->flags & ~BF_RND_MASK) | b;\n        break;\n    case FE_SUBNORMAL:\n        b = JS_ToBool(ctx, val);\n        fe->flags = (fe->flags & ~BF_FLAG_SUBNORMAL) | (b ? BF_FLAG_SUBNORMAL: 0);\n        break;\n    default:\n        b = JS_ToBool(ctx, val);\n        fe->status = (fe->status & ~magic) & ((-b) & magic);\n        break;\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_float_env_clearStatus(JSContext *ctx,\n                                        JSValueConst this_val,\n                                        int argc, JSValueConst *argv)\n{\n    JSFloatEnv *fe = JS_GetOpaque2(ctx, this_val, JS_CLASS_FLOAT_ENV);\n    if (!fe)\n        return JS_EXCEPTION;\n    fe->status = 0;\n    return JS_UNDEFINED;\n}\n\nstatic const JSCFunctionListEntry js_float_env_funcs[] = {\n    JS_CGETSET_DEF(\"prec\", js_float_env_get_prec, NULL ),\n    JS_CGETSET_DEF(\"expBits\", js_float_env_get_expBits, NULL ),\n    JS_CFUNC_DEF(\"setPrec\", 2, js_float_env_setPrec ),\n    JS_PROP_INT32_DEF(\"RNDN\", BF_RNDN, 0 ),\n    JS_PROP_INT32_DEF(\"RNDZ\", BF_RNDZ, 0 ),\n    JS_PROP_INT32_DEF(\"RNDU\", BF_RNDU, 0 ),\n    JS_PROP_INT32_DEF(\"RNDD\", BF_RNDD, 0 ),\n    JS_PROP_INT32_DEF(\"RNDNA\", BF_RNDNA, 0 ),\n    JS_PROP_INT32_DEF(\"RNDA\", BF_RNDA, 0 ),\n    JS_PROP_INT32_DEF(\"RNDF\", BF_RNDF, 0 ),\n    JS_PROP_INT32_DEF(\"precMin\", BF_PREC_MIN, 0 ),\n    JS_PROP_INT64_DEF(\"precMax\", BF_PREC_MAX, 0 ),\n    JS_PROP_INT32_DEF(\"expBitsMin\", BF_EXP_BITS_MIN, 0 ),\n    JS_PROP_INT32_DEF(\"expBitsMax\", BF_EXP_BITS_MAX, 0 ),\n};\n\nstatic const JSCFunctionListEntry js_float_env_proto_funcs[] = {\n    JS_CGETSET_MAGIC_DEF(\"prec\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, FE_PREC ),\n    JS_CGETSET_MAGIC_DEF(\"expBits\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, FE_EXP ),\n    JS_CGETSET_MAGIC_DEF(\"rndMode\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, FE_RNDMODE ),\n    JS_CGETSET_MAGIC_DEF(\"subnormal\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, FE_SUBNORMAL ),\n    JS_CGETSET_MAGIC_DEF(\"invalidOperation\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, BF_ST_INVALID_OP ),\n    JS_CGETSET_MAGIC_DEF(\"divideByZero\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, BF_ST_DIVIDE_ZERO ),\n    JS_CGETSET_MAGIC_DEF(\"overflow\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, BF_ST_OVERFLOW ),\n    JS_CGETSET_MAGIC_DEF(\"underflow\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, BF_ST_UNDERFLOW ),\n    JS_CGETSET_MAGIC_DEF(\"inexact\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, BF_ST_INEXACT ),\n    JS_CFUNC_DEF(\"clearStatus\", 0, js_float_env_clearStatus ),\n};\n\nvoid JS_AddIntrinsicBigFloat(JSContext *ctx)\n{\n    JSRuntime *rt = ctx->rt;\n    JSValueConst obj1;\n    \n    rt->bigfloat_ops.to_string = js_bigfloat_to_string;\n    rt->bigfloat_ops.from_string = js_string_to_bigfloat;\n    rt->bigfloat_ops.unary_arith = js_unary_arith_bigfloat;\n    rt->bigfloat_ops.binary_arith = js_binary_arith_bigfloat;\n    rt->bigfloat_ops.compare = js_compare_bigfloat;\n    rt->bigfloat_ops.mul_pow10_to_float64 = js_mul_pow10_to_float64;\n    rt->bigfloat_ops.mul_pow10 = js_mul_pow10;\n    \n    ctx->class_proto[JS_CLASS_BIG_FLOAT] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_BIG_FLOAT],\n                               js_bigfloat_proto_funcs,\n                               countof(js_bigfloat_proto_funcs));\n    obj1 = JS_NewGlobalCConstructor(ctx, \"BigFloat\", js_bigfloat_constructor, 1,\n                                    ctx->class_proto[JS_CLASS_BIG_FLOAT]);\n    JS_SetPropertyFunctionList(ctx, obj1, js_bigfloat_funcs,\n                               countof(js_bigfloat_funcs));\n\n    ctx->class_proto[JS_CLASS_FLOAT_ENV] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_FLOAT_ENV],\n                               js_float_env_proto_funcs,\n                               countof(js_float_env_proto_funcs));\n    obj1 = JS_NewGlobalCConstructorOnly(ctx, \"BigFloatEnv\",\n                                        js_float_env_constructor, 1,\n                                        ctx->class_proto[JS_CLASS_FLOAT_ENV]);\n    JS_SetPropertyFunctionList(ctx, obj1, js_float_env_funcs,\n                               countof(js_float_env_funcs));\n}\n\n/* BigDecimal */\n\nstatic JSValue JS_ToBigDecimalFree(JSContext *ctx, JSValue val,\n                                   BOOL allow_null_or_undefined)\n{\n redo:\n    switch(JS_VALUE_GET_NORM_TAG(val)) {\n    case JS_TAG_BIG_DECIMAL:\n        break;\n    case JS_TAG_NULL:\n        if (!allow_null_or_undefined)\n            goto fail;\n        /* fall thru */\n    case JS_TAG_BOOL:\n    case JS_TAG_INT:\n        {\n            bfdec_t *r;\n            int32_t v = JS_VALUE_GET_INT(val);\n\n            val = JS_NewBigDecimal(ctx);\n            if (JS_IsException(val))\n                break;\n            r = JS_GetBigDecimal(val);\n            if (bfdec_set_si(r, v)) {\n                JS_FreeValue(ctx, val);\n                val = JS_EXCEPTION;\n                break;\n            }\n        }\n        break;\n    case JS_TAG_FLOAT64:\n    case JS_TAG_BIG_INT:\n    case JS_TAG_BIG_FLOAT:\n        val = JS_ToStringFree(ctx, val);\n        if (JS_IsException(val))\n            break;\n        goto redo;\n    case JS_TAG_STRING:\n        {\n            const char *str, *p;\n            size_t len;\n            int err;\n\n            str = JS_ToCStringLen(ctx, &len, val);\n            JS_FreeValue(ctx, val);\n            if (!str)\n                return JS_EXCEPTION;\n            p = str;\n            p += skip_spaces(p);\n            if ((p - str) == len) {\n                bfdec_t *r;\n                val = JS_NewBigDecimal(ctx);\n                if (JS_IsException(val))\n                    break;\n                r = JS_GetBigDecimal(val);\n                bfdec_set_zero(r, 0);\n                err = 0;\n            } else {\n                val = js_atof(ctx, p, &p, 0, ATOD_TYPE_BIG_DECIMAL);\n                if (JS_IsException(val)) {\n                    JS_FreeCString(ctx, str);\n                    return JS_EXCEPTION;\n                }\n                p += skip_spaces(p);\n                err = ((p - str) != len);\n            }\n            JS_FreeCString(ctx, str);\n            if (err) {\n                JS_FreeValue(ctx, val);\n                return JS_ThrowSyntaxError(ctx, \"invalid bigdecimal literal\");\n            }\n        }\n        break;\n    case JS_TAG_OBJECT:\n        val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER);\n        if (JS_IsException(val))\n            break;\n        goto redo;\n    case JS_TAG_UNDEFINED:\n        {\n            bfdec_t *r;\n            if (!allow_null_or_undefined)\n                goto fail;\n            val = JS_NewBigDecimal(ctx);\n            if (JS_IsException(val))\n                break;\n            r = JS_GetBigDecimal(val);\n            bfdec_set_nan(r);\n        }\n        break;\n    default:\n    fail:\n        JS_FreeValue(ctx, val);\n        return JS_ThrowTypeError(ctx, \"cannot convert to bigdecimal\");\n    }\n    return val;\n}\n\nstatic JSValue js_bigdecimal_constructor(JSContext *ctx,\n                                         JSValueConst new_target,\n                                         int argc, JSValueConst *argv)\n{\n    JSValue val;\n    if (!JS_IsUndefined(new_target))\n        return JS_ThrowTypeError(ctx, \"not a constructor\");\n    if (argc == 0) {\n        bfdec_t *r;\n        val = JS_NewBigDecimal(ctx);\n        if (JS_IsException(val))\n            return val;\n        r = JS_GetBigDecimal(val);\n        bfdec_set_zero(r, 0);\n    } else {\n        val = JS_ToBigDecimalFree(ctx, JS_DupValue(ctx, argv[0]), FALSE);\n    }\n    return val;\n}\n\nstatic JSValue js_thisBigDecimalValue(JSContext *ctx, JSValueConst this_val)\n{\n    if (JS_IsBigDecimal(this_val))\n        return JS_DupValue(ctx, this_val);\n\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_BIG_DECIMAL) {\n            if (JS_IsBigDecimal(p->u.object_data))\n                return JS_DupValue(ctx, p->u.object_data);\n        }\n    }\n    return JS_ThrowTypeError(ctx, \"not a bigdecimal\");\n}\n\nstatic JSValue js_bigdecimal_toString(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv)\n{\n    JSValue val;\n\n    val = js_thisBigDecimalValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    return JS_ToStringFree(ctx, val);\n}\n\nstatic JSValue js_bigdecimal_valueOf(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    return js_thisBigDecimalValue(ctx, this_val);\n}\n\nstatic int js_bigdecimal_get_rnd_mode(JSContext *ctx, JSValueConst obj)\n{\n    const char *str;\n    size_t size;\n    int rnd_mode;\n    \n    str = JS_ToCStringLen(ctx, &size, obj);\n    if (!str)\n        return -1;\n    if (strlen(str) != size)\n        goto invalid_rounding_mode;\n    if (!strcmp(str, \"floor\")) {\n        rnd_mode = BF_RNDD;\n    } else if (!strcmp(str, \"ceiling\")) {\n        rnd_mode = BF_RNDU;\n    } else if (!strcmp(str, \"down\")) {\n        rnd_mode = BF_RNDZ;\n    } else if (!strcmp(str, \"up\")) {\n        rnd_mode = BF_RNDA;\n    } else if (!strcmp(str, \"half-even\")) {\n        rnd_mode = BF_RNDN;\n    } else if (!strcmp(str, \"half-up\")) {\n        rnd_mode = BF_RNDNA;\n    } else {\n    invalid_rounding_mode:\n        JS_FreeCString(ctx, str);\n        JS_ThrowTypeError(ctx, \"invalid rounding mode\");\n        return -1;\n    }\n    JS_FreeCString(ctx, str);\n    return rnd_mode;\n}\n\ntypedef struct {\n    int64_t prec;\n    bf_flags_t flags;\n} BigDecimalEnv;\n\nstatic int js_bigdecimal_get_env(JSContext *ctx, BigDecimalEnv *fe,\n                                 JSValueConst obj)\n{\n    JSValue prop;\n    int64_t val;\n    BOOL has_prec;\n    int rnd_mode;\n    \n    if (!JS_IsObject(obj)) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        return -1;\n    }\n    prop = JS_GetProperty(ctx, obj, JS_ATOM_roundingMode);\n    if (JS_IsException(prop))\n        return -1;\n    rnd_mode = js_bigdecimal_get_rnd_mode(ctx, prop);\n    JS_FreeValue(ctx, prop);\n    if (rnd_mode < 0)\n        return -1;\n    fe->flags = rnd_mode;\n    \n    prop = JS_GetProperty(ctx, obj, JS_ATOM_maximumSignificantDigits);\n    if (JS_IsException(prop))\n        return -1;\n    has_prec = FALSE;\n    if (!JS_IsUndefined(prop)) {\n        if (JS_ToInt64SatFree(ctx, &val, prop))\n            return -1;\n        if (val < 1 || val > BF_PREC_MAX)\n            goto invalid_precision;\n        fe->prec = val;\n        has_prec = TRUE;\n    }\n\n    prop = JS_GetProperty(ctx, obj, JS_ATOM_maximumFractionDigits);\n    if (JS_IsException(prop))\n        return -1;\n    if (!JS_IsUndefined(prop)) {\n        if (has_prec) {\n            JS_FreeValue(ctx, prop);\n            JS_ThrowTypeError(ctx, \"cannot provide both maximumSignificantDigits and maximumFractionDigits\");\n            return -1;\n        }\n        if (JS_ToInt64SatFree(ctx, &val, prop))\n            return -1;\n        if (val < 0 || val > BF_PREC_MAX) {\n        invalid_precision:\n            JS_ThrowTypeError(ctx, \"invalid precision\");\n            return -1;\n        }\n        fe->prec = val;\n        fe->flags |= BF_FLAG_RADPNT_PREC;\n        has_prec = TRUE;\n    }\n    if (!has_prec) {\n        JS_ThrowTypeError(ctx, \"precision must be present\");\n        return -1;\n    }\n    return 0;\n}\n\n\nstatic JSValue js_bigdecimal_fop(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv, int magic)\n{\n    bfdec_t *a, *b, r_s, *r = &r_s;\n    JSValue op1, op2, res;\n    BigDecimalEnv fe_s, *fe = &fe_s;\n    int op_count, ret;\n\n    if (magic == MATH_OP_SQRT ||\n        magic == MATH_OP_ROUND)\n        op_count = 1;\n    else\n        op_count = 2;\n    \n    op1 = JS_ToNumeric(ctx, argv[0]);\n    if (JS_IsException(op1))\n        return op1;\n    a = JS_ToBigDecimal(ctx, op1);\n    if (!a) {\n        JS_FreeValue(ctx, op1);\n        return JS_EXCEPTION;\n    }\n    if (op_count >= 2) {\n        op2 = JS_ToNumeric(ctx, argv[1]);\n        if (JS_IsException(op2)) {\n            JS_FreeValue(ctx, op1);\n            return op2;\n        }\n        b = JS_ToBigDecimal(ctx, op2);\n        if (!b)\n            goto fail;\n    } else {\n        op2 = JS_UNDEFINED;\n        b = NULL;\n    }\n    fe->flags = BF_RNDZ;\n    fe->prec = BF_PREC_INF;\n    if (op_count < argc) {\n        if (js_bigdecimal_get_env(ctx, fe, argv[op_count]))\n            goto fail;\n    }\n\n    res = JS_NewBigDecimal(ctx);\n    if (JS_IsException(res)) {\n    fail:\n        JS_FreeValue(ctx, op1);\n        JS_FreeValue(ctx, op2);\n        return JS_EXCEPTION;\n    }\n    r = JS_GetBigDecimal(res);\n    switch (magic) {\n    case MATH_OP_ADD:\n        ret = bfdec_add(r, a, b, fe->prec, fe->flags);\n        break;\n    case MATH_OP_SUB:\n        ret = bfdec_sub(r, a, b, fe->prec, fe->flags);\n        break;\n    case MATH_OP_MUL:\n        ret = bfdec_mul(r, a, b, fe->prec, fe->flags);\n        break;\n    case MATH_OP_DIV:\n        ret = bfdec_div(r, a, b, fe->prec, fe->flags);\n        break;\n    case MATH_OP_FMOD:\n        ret = bfdec_rem(r, a, b, fe->prec, fe->flags, BF_RNDZ);\n        break;\n    case MATH_OP_SQRT:\n        ret = bfdec_sqrt(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_ROUND:\n        ret = bfdec_set(r, a);\n        if (!(ret & BF_ST_MEM_ERROR))\n            ret = bfdec_round(r, fe->prec, fe->flags);\n        break;\n    default:\n        abort();\n    }\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    ret &= BF_ST_MEM_ERROR | BF_ST_DIVIDE_ZERO | BF_ST_INVALID_OP |\n        BF_ST_OVERFLOW;\n    if (ret != 0) {\n        JS_FreeValue(ctx, res);\n        return throw_bf_exception(ctx, ret);\n    } else {\n        return res;\n    }\n}\n\nstatic JSValue js_bigdecimal_toFixed(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    int64_t f;\n    int rnd_mode;\n\n    val = js_thisBigDecimalValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_ToInt64Sat(ctx, &f, argv[0]))\n        goto fail;\n    if (f < 0 || f > BF_PREC_MAX) {\n        JS_ThrowRangeError(ctx, \"invalid number of digits\");\n        goto fail;\n    }\n    rnd_mode = BF_RNDNA;\n    if (argc > 1) {\n        rnd_mode = js_bigdecimal_get_rnd_mode(ctx, argv[1]);\n        if (rnd_mode < 0)\n            goto fail;\n    }\n    ret = js_bigdecimal_to_string1(ctx, val, f, rnd_mode | BF_FTOA_FORMAT_FRAC);\n    JS_FreeValue(ctx, val);\n    return ret;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_bigdecimal_toExponential(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    int64_t f;\n    int rnd_mode;\n\n    val = js_thisBigDecimalValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_ToInt64Sat(ctx, &f, argv[0]))\n        goto fail;\n    if (JS_IsUndefined(argv[0])) {\n        ret = js_bigdecimal_to_string1(ctx, val, 0,\n                  BF_RNDN | BF_FTOA_FORMAT_FREE_MIN | BF_FTOA_FORCE_EXP);\n    } else {\n        if (f < 0 || f > BF_PREC_MAX) {\n            JS_ThrowRangeError(ctx, \"invalid number of digits\");\n            goto fail;\n        }\n        rnd_mode = BF_RNDNA;\n        if (argc > 1) {\n            rnd_mode = js_bigdecimal_get_rnd_mode(ctx, argv[1]);\n            if (rnd_mode < 0)\n                goto fail;\n        }\n        ret = js_bigdecimal_to_string1(ctx, val, f + 1,\n                      rnd_mode | BF_FTOA_FORMAT_FIXED | BF_FTOA_FORCE_EXP);\n    }\n    JS_FreeValue(ctx, val);\n    return ret;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_bigdecimal_toPrecision(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    int64_t p;\n    int rnd_mode;\n\n    val = js_thisBigDecimalValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_IsUndefined(argv[0])) {\n        return JS_ToStringFree(ctx, val);\n    }\n    if (JS_ToInt64Sat(ctx, &p, argv[0]))\n        goto fail;\n    if (p < 1 || p > BF_PREC_MAX) {\n        JS_ThrowRangeError(ctx, \"invalid number of digits\");\n        goto fail;\n    }\n    rnd_mode = BF_RNDNA;\n    if (argc > 1) {\n        rnd_mode = js_bigdecimal_get_rnd_mode(ctx, argv[1]);\n        if (rnd_mode < 0)\n            goto fail;\n    }\n    ret = js_bigdecimal_to_string1(ctx, val, p,\n                                   rnd_mode | BF_FTOA_FORMAT_FIXED);\n    JS_FreeValue(ctx, val);\n    return ret;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic const JSCFunctionListEntry js_bigdecimal_proto_funcs[] = {\n    JS_CFUNC_DEF(\"toString\", 0, js_bigdecimal_toString ),\n    JS_CFUNC_DEF(\"valueOf\", 0, js_bigdecimal_valueOf ),\n    JS_CFUNC_DEF(\"toPrecision\", 1, js_bigdecimal_toPrecision ),\n    JS_CFUNC_DEF(\"toFixed\", 1, js_bigdecimal_toFixed ),\n    JS_CFUNC_DEF(\"toExponential\", 1, js_bigdecimal_toExponential ),\n};\n\nstatic const JSCFunctionListEntry js_bigdecimal_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"add\", 2, js_bigdecimal_fop, MATH_OP_ADD ),\n    JS_CFUNC_MAGIC_DEF(\"sub\", 2, js_bigdecimal_fop, MATH_OP_SUB ),\n    JS_CFUNC_MAGIC_DEF(\"mul\", 2, js_bigdecimal_fop, MATH_OP_MUL ),\n    JS_CFUNC_MAGIC_DEF(\"div\", 2, js_bigdecimal_fop, MATH_OP_DIV ),\n    JS_CFUNC_MAGIC_DEF(\"mod\", 2, js_bigdecimal_fop, MATH_OP_FMOD ),\n    JS_CFUNC_MAGIC_DEF(\"round\", 1, js_bigdecimal_fop, MATH_OP_ROUND ),\n    JS_CFUNC_MAGIC_DEF(\"sqrt\", 1, js_bigdecimal_fop, MATH_OP_SQRT ),\n};\n\nvoid JS_AddIntrinsicBigDecimal(JSContext *ctx)\n{\n    JSRuntime *rt = ctx->rt;\n    JSValueConst obj1;\n\n    rt->bigdecimal_ops.to_string = js_bigdecimal_to_string;\n    rt->bigdecimal_ops.from_string = js_string_to_bigdecimal;\n    rt->bigdecimal_ops.unary_arith = js_unary_arith_bigdecimal;\n    rt->bigdecimal_ops.binary_arith = js_binary_arith_bigdecimal;\n    rt->bigdecimal_ops.compare = js_compare_bigdecimal;\n\n    ctx->class_proto[JS_CLASS_BIG_DECIMAL] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_BIG_DECIMAL],\n                               js_bigdecimal_proto_funcs,\n                               countof(js_bigdecimal_proto_funcs));\n    obj1 = JS_NewGlobalCConstructor(ctx, \"BigDecimal\",\n                                    js_bigdecimal_constructor, 1,\n                                    ctx->class_proto[JS_CLASS_BIG_DECIMAL]);\n    JS_SetPropertyFunctionList(ctx, obj1, js_bigdecimal_funcs,\n                               countof(js_bigdecimal_funcs));\n}\n\nvoid JS_EnableBignumExt(JSContext *ctx, BOOL enable)\n{\n    ctx->bignum_ext = enable;\n}\n\n#endif /* CONFIG_BIGNUM */\n\nstatic const char * const native_error_name[JS_NATIVE_ERROR_COUNT] = {\n    \"EvalError\", \"RangeError\", \"ReferenceError\",\n    \"SyntaxError\", \"TypeError\", \"URIError\",\n    \"InternalError\", \"AggregateError\",\n};\n\n/* Minimum amount of objects to be able to compile code and display\n   error messages. No JSAtom should be allocated by this function. */\nstatic void JS_AddIntrinsicBasicObjects(JSContext *ctx)\n{\n    JSValue proto;\n    int i;\n\n    ctx->class_proto[JS_CLASS_OBJECT] = JS_NewObjectProto(ctx, JS_NULL);\n    ctx->function_proto = JS_NewCFunction3(ctx, js_function_proto, \"\", 0,\n                                           JS_CFUNC_generic, 0,\n                                           ctx->class_proto[JS_CLASS_OBJECT]);\n    ctx->class_proto[JS_CLASS_BYTECODE_FUNCTION] = JS_DupValue(ctx, ctx->function_proto);\n    ctx->class_proto[JS_CLASS_ERROR] = JS_NewObject(ctx);\n#if 0\n    /* these are auto-initialized from js_error_proto_funcs,\n       but delaying might be a problem */\n    JS_DefinePropertyValue(ctx, ctx->class_proto[JS_CLASS_ERROR], JS_ATOM_name,\n                           JS_AtomToString(ctx, JS_ATOM_Error),\n                           JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    JS_DefinePropertyValue(ctx, ctx->class_proto[JS_CLASS_ERROR], JS_ATOM_message,\n                           JS_AtomToString(ctx, JS_ATOM_empty_string),\n                           JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n#endif\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ERROR],\n                               js_error_proto_funcs,\n                               countof(js_error_proto_funcs));\n\n    for(i = 0; i < JS_NATIVE_ERROR_COUNT; i++) {\n        proto = JS_NewObjectProto(ctx, ctx->class_proto[JS_CLASS_ERROR]);\n        JS_DefinePropertyValue(ctx, proto, JS_ATOM_name,\n                               JS_NewAtomString(ctx, native_error_name[i]),\n                               JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n        JS_DefinePropertyValue(ctx, proto, JS_ATOM_message,\n                               JS_AtomToString(ctx, JS_ATOM_empty_string),\n                               JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n        ctx->native_error_proto[i] = proto;\n    }\n\n    /* the array prototype is an array */\n    ctx->class_proto[JS_CLASS_ARRAY] =\n        JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],\n                               JS_CLASS_ARRAY);\n\n    ctx->array_shape = js_new_shape2(ctx, get_proto_obj(ctx->class_proto[JS_CLASS_ARRAY]),\n                                     JS_PROP_INITIAL_HASH_SIZE, 1);\n    add_shape_property(ctx, &ctx->array_shape, NULL,\n                       JS_ATOM_length, JS_PROP_WRITABLE | JS_PROP_LENGTH);\n\n    /* XXX: could test it on first context creation to ensure that no\n       new atoms are created in JS_AddIntrinsicBasicObjects(). It is\n       necessary to avoid useless renumbering of atoms after\n       JS_EvalBinary() if it is done just after\n       JS_AddIntrinsicBasicObjects(). */\n    //    assert(ctx->rt->atom_count == JS_ATOM_END);\n}\n\nvoid JS_AddIntrinsicBaseObjects(JSContext *ctx)\n{\n    int i;\n    JSValueConst obj, number_obj;\n    JSValue obj1;\n\n    ctx->throw_type_error = JS_NewCFunction(ctx, js_throw_type_error, NULL, 0);\n\n    /* add caller and arguments properties to throw a TypeError */\n    obj1 = JS_NewCFunction(ctx, js_function_proto_caller, NULL, 0);\n    JS_DefineProperty(ctx, ctx->function_proto, JS_ATOM_caller, JS_UNDEFINED,\n                      obj1, ctx->throw_type_error,\n                      JS_PROP_HAS_GET | JS_PROP_HAS_SET |\n                      JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE);\n    JS_DefineProperty(ctx, ctx->function_proto, JS_ATOM_arguments, JS_UNDEFINED,\n                      obj1, ctx->throw_type_error,\n                      JS_PROP_HAS_GET | JS_PROP_HAS_SET |\n                      JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE);\n    JS_FreeValue(ctx, obj1);\n    JS_FreeValue(ctx, js_object_seal(ctx, JS_UNDEFINED, 1, (JSValueConst *)&ctx->throw_type_error, 1));\n\n    ctx->global_obj = JS_NewObject(ctx);\n    ctx->global_var_obj = JS_NewObjectProto(ctx, JS_NULL);\n\n    /* Object */\n    obj = JS_NewGlobalCConstructor(ctx, \"Object\", js_object_constructor, 1,\n                                   ctx->class_proto[JS_CLASS_OBJECT]);\n    JS_SetPropertyFunctionList(ctx, obj, js_object_funcs, countof(js_object_funcs));\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_OBJECT],\n                               js_object_proto_funcs, countof(js_object_proto_funcs));\n\n    /* Function */\n    JS_SetPropertyFunctionList(ctx, ctx->function_proto, js_function_proto_funcs, countof(js_function_proto_funcs));\n    ctx->function_ctor = JS_NewCFunctionMagic(ctx, js_function_constructor,\n                                              \"Function\", 1, JS_CFUNC_constructor_or_func_magic,\n                                              JS_FUNC_NORMAL);\n    JS_NewGlobalCConstructor2(ctx, JS_DupValue(ctx, ctx->function_ctor), \"Function\",\n                              ctx->function_proto);\n\n    /* Error */\n    obj1 = JS_NewCFunctionMagic(ctx, js_error_constructor,\n                                \"Error\", 1, JS_CFUNC_constructor_or_func_magic, -1);\n    JS_NewGlobalCConstructor2(ctx, obj1,\n                              \"Error\", ctx->class_proto[JS_CLASS_ERROR]);\n\n    for(i = 0; i < JS_NATIVE_ERROR_COUNT; i++) {\n        JSValue func_obj;\n        int n_args;\n        n_args = 1 + (i == JS_AGGREGATE_ERROR);\n        func_obj = JS_NewCFunction3(ctx, (JSCFunction *)js_error_constructor,\n                                    native_error_name[i], n_args,\n                                    JS_CFUNC_constructor_or_func_magic, i, obj1);\n        JS_NewGlobalCConstructor2(ctx, func_obj, native_error_name[i],\n                                  ctx->native_error_proto[i]);\n    }\n\n    /* Iterator prototype */\n    ctx->iterator_proto = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->iterator_proto,\n                               js_iterator_proto_funcs,\n                               countof(js_iterator_proto_funcs));\n\n    /* Array */\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ARRAY],\n                               js_array_proto_funcs,\n                               countof(js_array_proto_funcs));\n\n    obj = JS_NewGlobalCConstructor(ctx, \"Array\", js_array_constructor, 1,\n                                   ctx->class_proto[JS_CLASS_ARRAY]);\n    ctx->array_ctor = JS_DupValue(ctx, obj);\n    JS_SetPropertyFunctionList(ctx, obj, js_array_funcs,\n                               countof(js_array_funcs));\n\n    /* XXX: create auto_initializer */\n    {\n        /* initialize Array.prototype[Symbol.unscopables] */\n        char const unscopables[] = \"copyWithin\" \"\\0\" \"entries\" \"\\0\" \"fill\" \"\\0\" \"find\" \"\\0\"\n            \"findIndex\" \"\\0\" \"flat\" \"\\0\" \"flatMap\" \"\\0\" \"includes\" \"\\0\" \"keys\" \"\\0\" \"values\" \"\\0\";\n        const char *p = unscopables;\n        obj1 = JS_NewObjectProto(ctx, JS_NULL);\n        for(p = unscopables; *p; p += strlen(p) + 1) {\n            JS_DefinePropertyValueStr(ctx, obj1, p, JS_TRUE, JS_PROP_C_W_E);\n        }\n        JS_DefinePropertyValue(ctx, ctx->class_proto[JS_CLASS_ARRAY],\n                               JS_ATOM_Symbol_unscopables, obj1,\n                               JS_PROP_CONFIGURABLE);\n    }\n\n    /* needed to initialize arguments[Symbol.iterator] */\n    ctx->array_proto_values =\n        JS_GetProperty(ctx, ctx->class_proto[JS_CLASS_ARRAY], JS_ATOM_values);\n\n    ctx->class_proto[JS_CLASS_ARRAY_ITERATOR] = JS_NewObjectProto(ctx, ctx->iterator_proto);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ARRAY_ITERATOR],\n                               js_array_iterator_proto_funcs,\n                               countof(js_array_iterator_proto_funcs));\n\n    /* parseFloat and parseInteger must be defined before Number\n       because of the Number.parseFloat and Number.parseInteger\n       aliases */\n    JS_SetPropertyFunctionList(ctx, ctx->global_obj, js_global_funcs,\n                               countof(js_global_funcs));\n\n    /* Number */\n    ctx->class_proto[JS_CLASS_NUMBER] = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],\n                                                               JS_CLASS_NUMBER);\n    JS_SetObjectData(ctx, ctx->class_proto[JS_CLASS_NUMBER], JS_NewInt32(ctx, 0));\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_NUMBER],\n                               js_number_proto_funcs,\n                               countof(js_number_proto_funcs));\n    number_obj = JS_NewGlobalCConstructor(ctx, \"Number\", js_number_constructor, 1,\n                                          ctx->class_proto[JS_CLASS_NUMBER]);\n    JS_SetPropertyFunctionList(ctx, number_obj, js_number_funcs, countof(js_number_funcs));\n\n    /* Boolean */\n    ctx->class_proto[JS_CLASS_BOOLEAN] = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],\n                                                                JS_CLASS_BOOLEAN);\n    JS_SetObjectData(ctx, ctx->class_proto[JS_CLASS_BOOLEAN], JS_NewBool(ctx, FALSE));\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_BOOLEAN], js_boolean_proto_funcs,\n                               countof(js_boolean_proto_funcs));\n    JS_NewGlobalCConstructor(ctx, \"Boolean\", js_boolean_constructor, 1,\n                             ctx->class_proto[JS_CLASS_BOOLEAN]);\n\n    /* String */\n    ctx->class_proto[JS_CLASS_STRING] = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],\n                                                               JS_CLASS_STRING);\n    JS_SetObjectData(ctx, ctx->class_proto[JS_CLASS_STRING], JS_AtomToString(ctx, JS_ATOM_empty_string));\n    obj = JS_NewGlobalCConstructor(ctx, \"String\", js_string_constructor, 1,\n                                   ctx->class_proto[JS_CLASS_STRING]);\n    JS_SetPropertyFunctionList(ctx, obj, js_string_funcs,\n                               countof(js_string_funcs));\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_STRING], js_string_proto_funcs,\n                               countof(js_string_proto_funcs));\n\n    ctx->class_proto[JS_CLASS_STRING_ITERATOR] = JS_NewObjectProto(ctx, ctx->iterator_proto);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_STRING_ITERATOR],\n                               js_string_iterator_proto_funcs,\n                               countof(js_string_iterator_proto_funcs));\n\n    /* Math: create as autoinit object */\n    js_random_init(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->global_obj, js_math_obj, countof(js_math_obj));\n\n    /* ES6 Reflect: create as autoinit object */\n    JS_SetPropertyFunctionList(ctx, ctx->global_obj, js_reflect_obj, countof(js_reflect_obj));\n\n    /* ES6 Symbol */\n    ctx->class_proto[JS_CLASS_SYMBOL] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_SYMBOL], js_symbol_proto_funcs,\n                               countof(js_symbol_proto_funcs));\n    obj = JS_NewGlobalCConstructor(ctx, \"Symbol\", js_symbol_constructor, 0,\n                                   ctx->class_proto[JS_CLASS_SYMBOL]);\n    JS_SetPropertyFunctionList(ctx, obj, js_symbol_funcs,\n                               countof(js_symbol_funcs));\n    for(i = JS_ATOM_Symbol_toPrimitive; i < JS_ATOM_END; i++) {\n        char buf[ATOM_GET_STR_BUF_SIZE];\n        const char *str, *p;\n        str = JS_AtomGetStr(ctx, buf, sizeof(buf), i);\n        /* skip \"Symbol.\" */\n        p = strchr(str, '.');\n        if (p)\n            str = p + 1;\n        JS_DefinePropertyValueStr(ctx, obj, str, JS_AtomToValue(ctx, i), 0);\n    }\n\n    /* ES6 Generator */\n    ctx->class_proto[JS_CLASS_GENERATOR] = JS_NewObjectProto(ctx, ctx->iterator_proto);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_GENERATOR],\n                               js_generator_proto_funcs,\n                               countof(js_generator_proto_funcs));\n\n    ctx->class_proto[JS_CLASS_GENERATOR_FUNCTION] = JS_NewObjectProto(ctx, ctx->function_proto);\n    obj1 = JS_NewCFunctionMagic(ctx, js_function_constructor,\n                                \"GeneratorFunction\", 1,\n                                JS_CFUNC_constructor_or_func_magic, JS_FUNC_GENERATOR);\n    JS_SetPropertyFunctionList(ctx,\n                               ctx->class_proto[JS_CLASS_GENERATOR_FUNCTION],\n                               js_generator_function_proto_funcs,\n                               countof(js_generator_function_proto_funcs));\n    JS_SetConstructor2(ctx, ctx->class_proto[JS_CLASS_GENERATOR_FUNCTION],\n                       ctx->class_proto[JS_CLASS_GENERATOR],\n                       JS_PROP_CONFIGURABLE, JS_PROP_CONFIGURABLE);\n    JS_SetConstructor2(ctx, obj1, ctx->class_proto[JS_CLASS_GENERATOR_FUNCTION],\n                       0, JS_PROP_CONFIGURABLE);\n    JS_FreeValue(ctx, obj1);\n\n    /* global properties */\n    ctx->eval_obj = JS_NewCFunction(ctx, js_global_eval, \"eval\", 1);\n    JS_DefinePropertyValue(ctx, ctx->global_obj, JS_ATOM_eval,\n                           JS_DupValue(ctx, ctx->eval_obj),\n                           JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n\n    JS_DefinePropertyValue(ctx, ctx->global_obj, JS_ATOM_globalThis,\n                           JS_DupValue(ctx, ctx->global_obj),\n                           JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE);\n}\n\n/* Typed Arrays */\n\nstatic uint8_t const typed_array_size_log2[JS_TYPED_ARRAY_COUNT] = {\n    0, 0, 0, 1, 1, 2, 2,\n#ifdef CONFIG_BIGNUM\n    3, 3, /* BigInt64Array, BigUint64Array */\n#endif\n    2, 3\n};\n\nstatic JSValue js_array_buffer_constructor3(JSContext *ctx,\n                                            JSValueConst new_target,\n                                            uint64_t len, JSClassID class_id,\n                                            uint8_t *buf,\n                                            JSFreeArrayBufferDataFunc *free_func,\n                                            void *opaque, BOOL alloc_flag)\n{\n    JSRuntime *rt = ctx->rt;\n    JSValue obj;\n    JSArrayBuffer *abuf = NULL;\n\n    obj = js_create_from_ctor(ctx, new_target, class_id);\n    if (JS_IsException(obj))\n        return obj;\n    /* XXX: we are currently limited to 2 GB */\n    if (len > INT32_MAX) {\n        JS_ThrowRangeError(ctx, \"invalid array buffer length\");\n        goto fail;\n    }\n    abuf = js_malloc(ctx, sizeof(*abuf));\n    if (!abuf)\n        goto fail;\n    abuf->byte_length = len;\n    if (alloc_flag) {\n        if (class_id == JS_CLASS_SHARED_ARRAY_BUFFER &&\n            rt->sab_funcs.sab_alloc) {\n            abuf->data = rt->sab_funcs.sab_alloc(rt->sab_funcs.sab_opaque,\n                                                 max_int(len, 1));\n            if (!abuf->data)\n                goto fail;\n            memset(abuf->data, 0, len);\n        } else {\n            /* the allocation must be done after the object creation */\n            abuf->data = js_mallocz(ctx, max_int(len, 1));\n            if (!abuf->data)\n                goto fail;\n        }\n    } else {\n        if (class_id == JS_CLASS_SHARED_ARRAY_BUFFER &&\n            rt->sab_funcs.sab_dup) {\n            rt->sab_funcs.sab_dup(rt->sab_funcs.sab_opaque, buf);\n        }\n        abuf->data = buf;\n    }\n    init_list_head(&abuf->array_list);\n    abuf->detached = FALSE;\n    abuf->shared = (class_id == JS_CLASS_SHARED_ARRAY_BUFFER);\n    abuf->opaque = opaque;\n    abuf->free_func = free_func;\n    if (alloc_flag && buf)\n        memcpy(abuf->data, buf, len);\n    JS_SetOpaque(obj, abuf);\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    js_free(ctx, abuf);\n    return JS_EXCEPTION;\n}\n\nstatic void js_array_buffer_free(JSRuntime *rt, void *opaque, void *ptr)\n{\n    js_free_rt(rt, ptr);\n}\n\nstatic JSValue js_array_buffer_constructor2(JSContext *ctx,\n                                            JSValueConst new_target,\n                                            uint64_t len, JSClassID class_id)\n{\n    return js_array_buffer_constructor3(ctx, new_target, len, class_id,\n                                        NULL, js_array_buffer_free, NULL,\n                                        TRUE);\n}\n\nstatic JSValue js_array_buffer_constructor1(JSContext *ctx,\n                                            JSValueConst new_target,\n                                            uint64_t len)\n{\n    return js_array_buffer_constructor2(ctx, new_target, len,\n                                        JS_CLASS_ARRAY_BUFFER);\n}\n\nJSValue JS_NewArrayBuffer(JSContext *ctx, uint8_t *buf, size_t len,\n                          JSFreeArrayBufferDataFunc *free_func, void *opaque,\n                          BOOL is_shared)\n{\n    return js_array_buffer_constructor3(ctx, JS_UNDEFINED, len,\n                                        is_shared ? JS_CLASS_SHARED_ARRAY_BUFFER : JS_CLASS_ARRAY_BUFFER,\n                                        buf, free_func, opaque, FALSE);\n}\n\n/* create a new ArrayBuffer of length 'len' and copy 'buf' to it */\nJSValue JS_NewArrayBufferCopy(JSContext *ctx, const uint8_t *buf, size_t len)\n{\n    return js_array_buffer_constructor3(ctx, JS_UNDEFINED, len,\n                                        JS_CLASS_ARRAY_BUFFER,\n                                        (uint8_t *)buf,\n                                        js_array_buffer_free, NULL,\n                                        TRUE);\n}\n\nstatic JSValue js_array_buffer_constructor(JSContext *ctx,\n                                           JSValueConst new_target,\n                                           int argc, JSValueConst *argv)\n{\n    uint64_t len;\n    if (JS_ToIndex(ctx, &len, argv[0]))\n        return JS_EXCEPTION;\n    return js_array_buffer_constructor1(ctx, new_target, len);\n}\n\nstatic JSValue js_shared_array_buffer_constructor(JSContext *ctx,\n                                                  JSValueConst new_target,\n                                                  int argc, JSValueConst *argv)\n{\n    uint64_t len;\n    if (JS_ToIndex(ctx, &len, argv[0]))\n        return JS_EXCEPTION;\n    return js_array_buffer_constructor2(ctx, new_target, len,\n                                        JS_CLASS_SHARED_ARRAY_BUFFER);\n}\n\n/* also used for SharedArrayBuffer */\nstatic void js_array_buffer_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSArrayBuffer *abuf = p->u.array_buffer;\n    if (abuf) {\n        /* The ArrayBuffer finalizer may be called before the typed\n           array finalizers using it, so abuf->array_list is not\n           necessarily empty. */\n        // assert(list_empty(&abuf->array_list));\n        if (abuf->shared && rt->sab_funcs.sab_free) {\n            rt->sab_funcs.sab_free(rt->sab_funcs.sab_opaque, abuf->data);\n        } else {\n            if (abuf->free_func)\n                abuf->free_func(rt, abuf->opaque, abuf->data);\n        }\n        js_free_rt(rt, abuf);\n    }\n}\n\nstatic JSValue js_array_buffer_isView(JSContext *ctx,\n                                      JSValueConst this_val,\n                                      int argc, JSValueConst *argv)\n{\n    JSObject *p;\n    BOOL res;\n    res = FALSE;\n    if (JS_VALUE_GET_TAG(argv[0]) == JS_TAG_OBJECT) {\n        p = JS_VALUE_GET_OBJ(argv[0]);\n        if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n            p->class_id <= JS_CLASS_DATAVIEW) {\n            res = TRUE;\n        }\n    }\n    return JS_NewBool(ctx, res);\n}\n\nstatic const JSCFunctionListEntry js_array_buffer_funcs[] = {\n    JS_CFUNC_DEF(\"isView\", 1, js_array_buffer_isView ),\n    JS_CGETSET_DEF(\"[Symbol.species]\", js_get_this, NULL ),\n};\n\nstatic JSValue JS_ThrowTypeErrorDetachedArrayBuffer(JSContext *ctx)\n{\n    return JS_ThrowTypeError(ctx, \"ArrayBuffer is detached\");\n}\n\nstatic JSValue js_array_buffer_get_byteLength(JSContext *ctx,\n                                              JSValueConst this_val,\n                                              int class_id)\n{\n    JSArrayBuffer *abuf = JS_GetOpaque2(ctx, this_val, class_id);\n    if (!abuf)\n        return JS_EXCEPTION;\n    /* return 0 if detached */\n    return JS_NewUint32(ctx, abuf->byte_length);\n}\n\nvoid JS_DetachArrayBuffer(JSContext *ctx, JSValueConst obj)\n{\n    JSArrayBuffer *abuf = JS_GetOpaque(obj, JS_CLASS_ARRAY_BUFFER);\n    struct list_head *el;\n\n    if (!abuf || abuf->detached)\n        return;\n    if (abuf->free_func)\n        abuf->free_func(ctx->rt, abuf->opaque, abuf->data);\n    abuf->data = NULL;\n    abuf->byte_length = 0;\n    abuf->detached = TRUE;\n\n    list_for_each(el, &abuf->array_list) {\n        JSTypedArray *ta;\n        JSObject *p;\n\n        ta = list_entry(el, JSTypedArray, link);\n        p = ta->obj;\n        /* Note: the typed array length and offset fields are not modified */\n        if (p->class_id != JS_CLASS_DATAVIEW) {\n            p->u.array.count = 0;\n            p->u.array.u.ptr = NULL;\n        }\n    }\n}\n\n/* get an ArrayBuffer or SharedArrayBuffer */\nstatic JSArrayBuffer *js_get_array_buffer(JSContext *ctx, JSValueConst obj)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        goto fail;\n    p = JS_VALUE_GET_OBJ(obj);\n    if (p->class_id != JS_CLASS_ARRAY_BUFFER &&\n        p->class_id != JS_CLASS_SHARED_ARRAY_BUFFER) {\n    fail:\n        JS_ThrowTypeErrorInvalidClass(ctx, JS_CLASS_ARRAY_BUFFER);\n        return NULL;\n    }\n    return p->u.array_buffer;\n}\n\n/* return NULL if exception. WARNING: any JS call can detach the\n   buffer and render the returned pointer invalid */\nuint8_t *JS_GetArrayBuffer(JSContext *ctx, size_t *psize, JSValueConst obj)\n{\n    JSArrayBuffer *abuf = js_get_array_buffer(ctx, obj);\n    if (!abuf)\n        goto fail;\n    if (abuf->detached) {\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        goto fail;\n    }\n    *psize = abuf->byte_length;\n    return abuf->data;\n fail:\n    *psize = 0;\n    return NULL;\n}\n\nstatic JSValue js_array_buffer_slice(JSContext *ctx,\n                                     JSValueConst this_val,\n                                     int argc, JSValueConst *argv, int class_id)\n{\n    JSArrayBuffer *abuf, *new_abuf;\n    int64_t len, start, end, new_len;\n    JSValue ctor, new_obj;\n\n    abuf = JS_GetOpaque2(ctx, this_val, class_id);\n    if (!abuf)\n        return JS_EXCEPTION;\n    if (abuf->detached)\n        return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n    len = abuf->byte_length;\n\n    if (JS_ToInt64Clamp(ctx, &start, argv[0], 0, len, len))\n        return JS_EXCEPTION;\n\n    end = len;\n    if (!JS_IsUndefined(argv[1])) {\n        if (JS_ToInt64Clamp(ctx, &end, argv[1], 0, len, len))\n            return JS_EXCEPTION;\n    }\n    new_len = max_int64(end - start, 0);\n    ctor = JS_SpeciesConstructor(ctx, this_val, JS_UNDEFINED);\n    if (JS_IsException(ctor))\n        return ctor;\n    if (JS_IsUndefined(ctor)) {\n        new_obj = js_array_buffer_constructor2(ctx, JS_UNDEFINED, new_len,\n                                               class_id);\n    } else {\n        JSValue args[1];\n        args[0] = JS_NewInt64(ctx, new_len);\n        new_obj = JS_CallConstructor(ctx, ctor, 1, (JSValueConst *)args);\n        JS_FreeValue(ctx, ctor);\n        JS_FreeValue(ctx, args[0]);\n    }\n    if (JS_IsException(new_obj))\n        return new_obj;\n    new_abuf = JS_GetOpaque2(ctx, new_obj, class_id);\n    if (!new_abuf)\n        goto fail;\n    if (js_same_value(ctx, new_obj, this_val)) {\n        JS_ThrowTypeError(ctx, \"cannot use identical ArrayBuffer\");\n        goto fail;\n    }\n    if (new_abuf->detached) {\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        goto fail;\n    }\n    if (new_abuf->byte_length < new_len) {\n        JS_ThrowTypeError(ctx, \"new ArrayBuffer is too small\");\n        goto fail;\n    }\n    /* must test again because of side effects */\n    if (abuf->detached) {\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        goto fail;\n    }\n    memcpy(new_abuf->data, abuf->data + start, new_len);\n    return new_obj;\n fail:\n    JS_FreeValue(ctx, new_obj);\n    return JS_EXCEPTION;\n}\n\nstatic const JSCFunctionListEntry js_array_buffer_proto_funcs[] = {\n    JS_CGETSET_MAGIC_DEF(\"byteLength\", js_array_buffer_get_byteLength, NULL, JS_CLASS_ARRAY_BUFFER ),\n    JS_CFUNC_MAGIC_DEF(\"slice\", 2, js_array_buffer_slice, JS_CLASS_ARRAY_BUFFER ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"ArrayBuffer\", JS_PROP_CONFIGURABLE ),\n};\n\n/* SharedArrayBuffer */\n\nstatic const JSCFunctionListEntry js_shared_array_buffer_funcs[] = {\n    JS_CGETSET_DEF(\"[Symbol.species]\", js_get_this, NULL ),\n};\n\nstatic const JSCFunctionListEntry js_shared_array_buffer_proto_funcs[] = {\n    JS_CGETSET_MAGIC_DEF(\"byteLength\", js_array_buffer_get_byteLength, NULL, JS_CLASS_SHARED_ARRAY_BUFFER ),\n    JS_CFUNC_MAGIC_DEF(\"slice\", 2, js_array_buffer_slice, JS_CLASS_SHARED_ARRAY_BUFFER ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"SharedArrayBuffer\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic JSObject *get_typed_array(JSContext *ctx,\n                                 JSValueConst this_val,\n                                 int is_dataview)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(this_val) != JS_TAG_OBJECT)\n        goto fail;\n    p = JS_VALUE_GET_OBJ(this_val);\n    if (is_dataview) {\n        if (p->class_id != JS_CLASS_DATAVIEW)\n            goto fail;\n    } else {\n        if (!(p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n              p->class_id <= JS_CLASS_FLOAT64_ARRAY)) {\n        fail:\n            JS_ThrowTypeError(ctx, \"not a %s\", is_dataview ? \"DataView\" : \"TypedArray\");\n            return NULL;\n        }\n    }\n    return p;\n}\n\n/* WARNING: 'p' must be a typed array */\nstatic BOOL typed_array_is_detached(JSContext *ctx, JSObject *p)\n{\n    JSTypedArray *ta = p->u.typed_array;\n    JSArrayBuffer *abuf = ta->buffer->u.array_buffer;\n    /* XXX: could simplify test by ensuring that\n       p->u.array.u.ptr is NULL iff it is detached */\n    return abuf->detached;\n}\n\n/* WARNING: 'p' must be a typed array. Works even if the array buffer\n   is detached */\nstatic uint32_t typed_array_get_length(JSContext *ctx, JSObject *p)\n{\n    JSTypedArray *ta = p->u.typed_array;\n    int size_log2 = typed_array_size_log2(p->class_id);\n    return ta->length >> size_log2;\n}\n\nstatic int validate_typed_array(JSContext *ctx, JSValueConst this_val)\n{\n    JSObject *p;\n    p = get_typed_array(ctx, this_val, 0);\n    if (!p)\n        return -1;\n    if (typed_array_is_detached(ctx, p)) {\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        return -1;\n    }\n    return 0;\n}\n\nstatic JSValue js_typed_array_get_length(JSContext *ctx,\n                                         JSValueConst this_val)\n{\n    JSObject *p;\n    p = get_typed_array(ctx, this_val, 0);\n    if (!p)\n        return JS_EXCEPTION;\n    return JS_NewInt32(ctx, p->u.array.count);\n}\n\nstatic JSValue js_typed_array_get_buffer(JSContext *ctx,\n                                         JSValueConst this_val, int is_dataview)\n{\n    JSObject *p;\n    JSTypedArray *ta;\n    p = get_typed_array(ctx, this_val, is_dataview);\n    if (!p)\n        return JS_EXCEPTION;\n    ta = p->u.typed_array;\n    return JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, ta->buffer));\n}\n\nstatic JSValue js_typed_array_get_byteLength(JSContext *ctx,\n                                             JSValueConst this_val,\n                                             int is_dataview)\n{\n    JSObject *p;\n    JSTypedArray *ta;\n    p = get_typed_array(ctx, this_val, is_dataview);\n    if (!p)\n        return JS_EXCEPTION;\n    if (typed_array_is_detached(ctx, p)) {\n        if (is_dataview) {\n            return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        } else {\n            return JS_NewInt32(ctx, 0);\n        }\n    }\n    ta = p->u.typed_array;\n    return JS_NewInt32(ctx, ta->length);\n}\n\nstatic JSValue js_typed_array_get_byteOffset(JSContext *ctx,\n                                             JSValueConst this_val,\n                                             int is_dataview)\n{\n    JSObject *p;\n    JSTypedArray *ta;\n    p = get_typed_array(ctx, this_val, is_dataview);\n    if (!p)\n        return JS_EXCEPTION;\n    if (typed_array_is_detached(ctx, p)) {\n        if (is_dataview) {\n            return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        } else {\n            return JS_NewInt32(ctx, 0);\n        }\n    }\n    ta = p->u.typed_array;\n    return JS_NewInt32(ctx, ta->offset);\n}\n\n/* Return the buffer associated to the typed array or an exception if\n   it is not a typed array or if the buffer is detached. pbyte_offset,\n   pbyte_length or pbytes_per_element can be NULL. */\nJSValue JS_GetTypedArrayBuffer(JSContext *ctx, JSValueConst obj,\n                               size_t *pbyte_offset,\n                               size_t *pbyte_length,\n                               size_t *pbytes_per_element)\n{\n    JSObject *p;\n    JSTypedArray *ta;\n    p = get_typed_array(ctx, obj, FALSE);\n    if (!p)\n        return JS_EXCEPTION;\n    if (typed_array_is_detached(ctx, p))\n        return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n    ta = p->u.typed_array;\n    if (pbyte_offset)\n        *pbyte_offset = ta->offset;\n    if (pbyte_length)\n        *pbyte_length = ta->length;\n    if (pbytes_per_element) {\n        *pbytes_per_element = 1 << typed_array_size_log2(p->class_id);\n    }\n    return JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, ta->buffer));\n}\n                               \nstatic JSValue js_typed_array_get_toStringTag(JSContext *ctx,\n                                              JSValueConst this_val)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(this_val) != JS_TAG_OBJECT)\n        return JS_UNDEFINED;\n    p = JS_VALUE_GET_OBJ(this_val);\n    if (!(p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n          p->class_id <= JS_CLASS_FLOAT64_ARRAY))\n        return JS_UNDEFINED;\n    return JS_AtomToString(ctx, ctx->rt->class_array[p->class_id].class_name);\n}\n\nstatic JSValue js_typed_array_set_internal(JSContext *ctx,\n                                           JSValueConst dst,\n                                           JSValueConst src,\n                                           JSValueConst off)\n{\n    JSObject *p;\n    JSObject *src_p;\n    uint32_t i;\n    int64_t src_len, offset;\n    JSValue val, src_obj = JS_UNDEFINED;\n\n    p = get_typed_array(ctx, dst, 0);\n    if (!p)\n        goto fail;\n    if (JS_ToInt64Sat(ctx, &offset, off))\n        goto fail;\n    if (offset < 0)\n        goto range_error;\n    if (typed_array_is_detached(ctx, p)) {\n    detached:\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        goto fail;\n    }\n    src_obj = JS_ToObject(ctx, src);\n    if (JS_IsException(src_obj))\n        goto fail;\n    src_p = JS_VALUE_GET_OBJ(src_obj);\n    if (src_p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n        src_p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n        JSTypedArray *dest_ta = p->u.typed_array;\n        JSArrayBuffer *dest_abuf = dest_ta->buffer->u.array_buffer;\n        JSTypedArray *src_ta = src_p->u.typed_array;\n        JSArrayBuffer *src_abuf = src_ta->buffer->u.array_buffer;\n        int shift = typed_array_size_log2(p->class_id);\n\n        if (src_abuf->detached)\n            goto detached;\n\n        src_len = src_p->u.array.count;\n        if (offset > (int64_t)(p->u.array.count - src_len))\n            goto range_error;\n\n        /* copying between typed objects */\n        if (src_p->class_id == p->class_id) {\n            /* same type, use memmove */\n            memmove(dest_abuf->data + dest_ta->offset + (offset << shift),\n                    src_abuf->data + src_ta->offset, src_len << shift);\n            goto done;\n        }\n        if (dest_abuf->data == src_abuf->data) {\n            /* copying between the same buffer using different types of mappings\n               would require a temporary buffer */\n        }\n        /* otherwise, default behavior is slow but correct */\n    } else {\n        if (js_get_length64(ctx, &src_len, src_obj))\n            goto fail;\n        if (offset > (int64_t)(p->u.array.count - src_len)) {\n        range_error:\n            JS_ThrowRangeError(ctx, \"invalid array length\");\n            goto fail;\n        }\n    }\n    for(i = 0; i < src_len; i++) {\n        val = JS_GetPropertyUint32(ctx, src_obj, i);\n        if (JS_IsException(val))\n            goto fail;\n        if (JS_SetPropertyUint32(ctx, dst, offset + i, val) < 0)\n            goto fail;\n    }\ndone:\n    JS_FreeValue(ctx, src_obj);\n    return JS_UNDEFINED;\nfail:\n    JS_FreeValue(ctx, src_obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_typed_array_set(JSContext *ctx,\n                                  JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    JSValueConst offset = JS_UNDEFINED;\n    if (argc > 1) {\n        offset = argv[1];\n    }\n    return js_typed_array_set_internal(ctx, this_val, argv[0], offset);\n}\n\nstatic JSValue js_create_typed_array_iterator(JSContext *ctx, JSValueConst this_val,\n                                              int argc, JSValueConst *argv, int magic)\n{\n    if (validate_typed_array(ctx, this_val))\n        return JS_EXCEPTION;\n    return js_create_array_iterator(ctx, this_val, argc, argv, magic);\n}\n\n/* return < 0 if exception */\nstatic int js_typed_array_get_length_internal(JSContext *ctx,\n                                              JSValueConst obj)\n{\n    JSObject *p;\n    p = get_typed_array(ctx, obj, 0);\n    if (!p)\n        return -1;\n    if (typed_array_is_detached(ctx, p)) {\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        return -1;\n    }\n    return p->u.array.count;\n}\n\n#if 0\n/* validate a typed array and return its length */\nstatic JSValue js_typed_array___getLength(JSContext *ctx,\n                                          JSValueConst this_val,\n                                          int argc, JSValueConst *argv)\n{\n    BOOL ignore_detached = JS_ToBool(ctx, argv[1]);\n\n    if (ignore_detached) {\n        return js_typed_array_get_length(ctx, argv[0]);\n    } else {\n        int len;\n        len = js_typed_array_get_length_internal(ctx, argv[0]);\n        if (len < 0)\n            return JS_EXCEPTION;\n        return JS_NewInt32(ctx, len);\n    }\n}\n#endif\n\nstatic JSValue js_typed_array_create(JSContext *ctx, JSValueConst ctor,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue ret;\n    int new_len;\n    int64_t len;\n\n    ret = JS_CallConstructor(ctx, ctor, argc, argv);\n    if (JS_IsException(ret))\n        return ret;\n    /* validate the typed array */\n    new_len = js_typed_array_get_length_internal(ctx, ret);\n    if (new_len < 0)\n        goto fail;\n    if (argc == 1) {\n        /* ensure that it is large enough */\n        if (JS_ToLengthFree(ctx, &len, JS_DupValue(ctx, argv[0])))\n            goto fail;\n        if (new_len < len) {\n            JS_ThrowTypeError(ctx, \"TypedArray length is too small\");\n        fail:\n            JS_FreeValue(ctx, ret);\n            return JS_EXCEPTION;\n        }\n    }\n    return ret;\n}\n\n#if 0\nstatic JSValue js_typed_array___create(JSContext *ctx,\n                                       JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    return js_typed_array_create(ctx, argv[0], max_int(argc - 1, 0), argv + 1);\n}\n#endif\n\nstatic JSValue js_typed_array___speciesCreate(JSContext *ctx,\n                                              JSValueConst this_val,\n                                              int argc, JSValueConst *argv)\n{\n    JSValueConst obj;\n    JSObject *p;\n    JSValue ctor, ret;\n    int argc1;\n\n    obj = argv[0];\n    p = get_typed_array(ctx, obj, 0);\n    if (!p)\n        return JS_EXCEPTION;\n    ctor = JS_SpeciesConstructor(ctx, obj, JS_UNDEFINED);\n    if (JS_IsException(ctor))\n        return ctor;\n    argc1 = max_int(argc - 1, 0);\n    if (JS_IsUndefined(ctor)) {\n        ret = js_typed_array_constructor(ctx, JS_UNDEFINED, argc1, argv + 1,\n                                         p->class_id);\n    } else {\n        ret = js_typed_array_create(ctx, ctor, argc1, argv + 1);\n        JS_FreeValue(ctx, ctor);\n    }\n    return ret;\n}\n\nstatic JSValue js_typed_array_from(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    // from(items, mapfn = void 0, this_arg = void 0)\n    JSValueConst items = argv[0], mapfn, this_arg;\n    JSValueConst args[2];\n    JSValue stack[2];\n    JSValue iter, arr, r, v, v2;\n    int64_t k, len;\n    int done, mapping;\n\n    mapping = FALSE;\n    mapfn = JS_UNDEFINED;\n    this_arg = JS_UNDEFINED;\n    r = JS_UNDEFINED;\n    arr = JS_UNDEFINED;\n    stack[0] = JS_UNDEFINED;\n    stack[1] = JS_UNDEFINED;\n\n    if (argc > 1) {\n        mapfn = argv[1];\n        if (!JS_IsUndefined(mapfn)) {\n            if (check_function(ctx, mapfn))\n                goto exception;\n            mapping = 1;\n            if (argc > 2)\n                this_arg = argv[2];\n        }\n    }\n    iter = JS_GetProperty(ctx, items, JS_ATOM_Symbol_iterator);\n    if (JS_IsException(iter))\n        goto exception;\n    if (!JS_IsUndefined(iter)) {\n        JS_FreeValue(ctx, iter);\n        arr = JS_NewArray(ctx);\n        if (JS_IsException(arr))\n            goto exception;\n        stack[0] = JS_DupValue(ctx, items);\n        if (js_for_of_start(ctx, &stack[1], FALSE))\n            goto exception;\n        for (k = 0;; k++) {\n            v = JS_IteratorNext(ctx, stack[0], stack[1], 0, NULL, &done);\n            if (JS_IsException(v))\n                goto exception_close;\n            if (done)\n                break;\n            if (JS_DefinePropertyValueInt64(ctx, arr, k, v, JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                goto exception_close;\n        }\n    } else {\n        arr = JS_ToObject(ctx, items);\n        if (JS_IsException(arr))\n            goto exception;\n    }\n    if (js_get_length64(ctx, &len, arr) < 0)\n        goto exception;\n    v = JS_NewInt64(ctx, len);\n    args[0] = v;\n    r = js_typed_array_create(ctx, this_val, 1, args);\n    JS_FreeValue(ctx, v);\n    if (JS_IsException(r))\n        goto exception;\n    for(k = 0; k < len; k++) {\n        v = JS_GetPropertyInt64(ctx, arr, k);\n        if (JS_IsException(v))\n            goto exception;\n        if (mapping) {\n            args[0] = v;\n            args[1] = JS_NewInt32(ctx, k);\n            v2 = JS_Call(ctx, mapfn, this_arg, 2, args);\n            JS_FreeValue(ctx, v);\n            v = v2;\n            if (JS_IsException(v))\n                goto exception;\n        }\n        if (JS_SetPropertyInt64(ctx, r, k, v) < 0)\n            goto exception;\n    }\n    goto done;\n\n exception_close:\n    if (!JS_IsUndefined(stack[0]))\n        JS_IteratorClose(ctx, stack[0], TRUE);\n exception:\n    JS_FreeValue(ctx, r);\n    r = JS_EXCEPTION;\n done:\n    JS_FreeValue(ctx, arr);\n    JS_FreeValue(ctx, stack[0]);\n    JS_FreeValue(ctx, stack[1]);\n    return r;\n}\n\nstatic JSValue js_typed_array_of(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValue obj;\n    JSValueConst args[1];\n    int i;\n\n    args[0] = JS_NewInt32(ctx, argc);\n    obj = js_typed_array_create(ctx, this_val, 1, args);\n    if (JS_IsException(obj))\n        return obj;\n\n    for(i = 0; i < argc; i++) {\n        if (JS_SetPropertyUint32(ctx, obj, i, JS_DupValue(ctx, argv[i])) < 0) {\n            JS_FreeValue(ctx, obj);\n            return JS_EXCEPTION;\n        }\n    }\n    return obj;\n}\n\nstatic JSValue js_typed_array_copyWithin(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    JSObject *p;\n    int len, to, from, final, count, shift;\n\n    len = js_typed_array_get_length_internal(ctx, this_val);\n    if (len < 0)\n        return JS_EXCEPTION;\n\n    if (JS_ToInt32Clamp(ctx, &to, argv[0], 0, len, len))\n        return JS_EXCEPTION;\n\n    if (JS_ToInt32Clamp(ctx, &from, argv[1], 0, len, len))\n        return JS_EXCEPTION;\n\n    final = len;\n    if (argc > 2 && !JS_IsUndefined(argv[2])) {\n        if (JS_ToInt32Clamp(ctx, &final, argv[2], 0, len, len))\n            return JS_EXCEPTION;\n    }\n\n    count = min_int(final - from, len - to);\n    if (count > 0) {\n        p = JS_VALUE_GET_OBJ(this_val);\n        if (typed_array_is_detached(ctx, p))\n            return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        shift = typed_array_size_log2(p->class_id);\n        memmove(p->u.array.u.uint8_ptr + (to << shift),\n                p->u.array.u.uint8_ptr + (from << shift),\n                count << shift);\n    }\n    return JS_DupValue(ctx, this_val);\n}\n\nstatic JSValue js_typed_array_fill(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    JSObject *p;\n    int len, k, final, shift;\n    uint64_t v64;\n\n    len = js_typed_array_get_length_internal(ctx, this_val);\n    if (len < 0)\n        return JS_EXCEPTION;\n    p = JS_VALUE_GET_OBJ(this_val);\n\n    if (p->class_id == JS_CLASS_UINT8C_ARRAY) {\n        int32_t v;\n        if (JS_ToUint8ClampFree(ctx, &v, JS_DupValue(ctx, argv[0])))\n            return JS_EXCEPTION;\n        v64 = v;\n    } else if (p->class_id <= JS_CLASS_UINT32_ARRAY) {\n        uint32_t v;\n        if (JS_ToUint32(ctx, &v, argv[0]))\n            return JS_EXCEPTION;\n        v64 = v;\n    } else\n#ifdef CONFIG_BIGNUM\n    if (p->class_id <= JS_CLASS_BIG_UINT64_ARRAY) {\n        if (JS_ToBigInt64(ctx, (int64_t *)&v64, argv[0]))\n            return JS_EXCEPTION;\n    } else\n#endif\n    {\n        double d;\n        if (JS_ToFloat64(ctx, &d, argv[0]))\n            return JS_EXCEPTION;\n        if (p->class_id == JS_CLASS_FLOAT32_ARRAY) {\n            union {\n                float f;\n                uint32_t u32;\n            } u;\n            u.f = d;\n            v64 = u.u32;\n        } else {\n            JSFloat64Union u;\n            u.d = d;\n            v64 = u.u64;\n        }\n    }\n\n    k = 0;\n    if (argc > 1) {\n        if (JS_ToInt32Clamp(ctx, &k, argv[1], 0, len, len))\n            return JS_EXCEPTION;\n    }\n\n    final = len;\n    if (argc > 2 && !JS_IsUndefined(argv[2])) {\n        if (JS_ToInt32Clamp(ctx, &final, argv[2], 0, len, len))\n            return JS_EXCEPTION;\n    }\n\n    if (typed_array_is_detached(ctx, p))\n        return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n    \n    shift = typed_array_size_log2(p->class_id);\n    switch(shift) {\n    case 0:\n        if (k < final) {\n            memset(p->u.array.u.uint8_ptr + k, v64, final - k);\n        }\n        break;\n    case 1:\n        for(; k < final; k++) {\n            p->u.array.u.uint16_ptr[k] = v64;\n        }\n        break;\n    case 2:\n        for(; k < final; k++) {\n            p->u.array.u.uint32_ptr[k] = v64;\n        }\n        break;\n    case 3:\n        for(; k < final; k++) {\n            p->u.array.u.uint64_ptr[k] = v64;\n        }\n        break;\n    default:\n        abort();\n    }\n    return JS_DupValue(ctx, this_val);\n}\n\nstatic JSValue js_typed_array_find(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv, int findIndex)\n{\n    JSValueConst func, this_arg;\n    JSValueConst args[3];\n    JSValue val, index_val, res;\n    int len, k;\n\n    val = JS_UNDEFINED;\n    len = js_typed_array_get_length_internal(ctx, this_val);\n    if (len < 0)\n        goto exception;\n\n    func = argv[0];\n    if (check_function(ctx, func))\n        goto exception;\n\n    this_arg = JS_UNDEFINED;\n    if (argc > 1)\n        this_arg = argv[1];\n\n    for(k = 0; k < len; k++) {\n        index_val = JS_NewInt32(ctx, k);\n        val = JS_GetPropertyValue(ctx, this_val, index_val);\n        if (JS_IsException(val))\n            goto exception;\n        args[0] = val;\n        args[1] = index_val;\n        args[2] = this_val;\n        res = JS_Call(ctx, func, this_arg, 3, args);\n        if (JS_IsException(res))\n            goto exception;\n        if (JS_ToBoolFree(ctx, res)) {\n            if (findIndex) {\n                JS_FreeValue(ctx, val);\n                return index_val;\n            } else {\n                return val;\n            }\n        }\n        JS_FreeValue(ctx, val);\n    }\n    if (findIndex)\n        return JS_NewInt32(ctx, -1);\n    else\n        return JS_UNDEFINED;\n\nexception:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\n#define special_indexOf 0\n#define special_lastIndexOf 1\n#define special_includes -1\n\nstatic JSValue js_typed_array_indexOf(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv, int special)\n{\n    JSObject *p;\n    int len, tag, is_int, is_bigint, k, stop, inc, res = -1;\n    int64_t v64;\n    double d;\n    float f;\n\n    len = js_typed_array_get_length_internal(ctx, this_val);\n    if (len < 0)\n        goto exception;\n    if (len == 0)\n        goto done;\n\n    if (special == special_lastIndexOf) {\n        k = len - 1;\n        if (argc > 1) {\n            if (JS_ToFloat64(ctx, &d, argv[1]))\n                goto exception;\n            if (isnan(d)) {\n                k = 0;\n            } else {\n                if (d >= 0) {\n                    if (d < k) {\n                        k = d;\n                    }\n                } else {\n                    d += len;\n                    if (d < 0)\n                        goto done;\n                    k = d;\n                }\n            }\n        }\n        stop = -1;\n        inc = -1;\n    } else {\n        k = 0;\n        if (argc > 1) {\n            if (JS_ToInt32Clamp(ctx, &k, argv[1], 0, len, len))\n                goto exception;\n        }\n        stop = len;\n        inc = 1;\n    }\n\n    p = JS_VALUE_GET_OBJ(this_val);\n    /* if the array was detached, no need to go further (but no\n       exception is raised) */\n    if (typed_array_is_detached(ctx, p)) {\n        /* \"includes\" scans all the properties, so \"undefined\" can match */\n        if (special == special_includes && JS_IsUndefined(argv[0]) && len > 0)\n            res = 0;\n        goto done;\n    }\n    \n    is_bigint = 0;\n    is_int = 0; /* avoid warning */\n    v64 = 0; /* avoid warning */\n    tag = JS_VALUE_GET_NORM_TAG(argv[0]);\n    if (tag == JS_TAG_INT) {\n        is_int = 1;\n        v64 = JS_VALUE_GET_INT(argv[0]);\n        d = v64;\n    } else\n    if (tag == JS_TAG_FLOAT64) {\n        d = JS_VALUE_GET_FLOAT64(argv[0]);\n        v64 = d;\n        is_int = (v64 == d);\n    } else\n#ifdef CONFIG_BIGNUM\n    if (tag == JS_TAG_BIG_INT) {\n        JSBigFloat *p1 = JS_VALUE_GET_PTR(argv[0]);\n        \n        if (p->class_id == JS_CLASS_BIG_INT64_ARRAY) {\n            if (bf_get_int64(&v64, &p1->num, 0) != 0)\n                goto done;\n        } else if (p->class_id == JS_CLASS_BIG_UINT64_ARRAY) {\n            if (bf_get_uint64((uint64_t *)&v64, &p1->num) != 0)\n                goto done;\n        } else {\n            goto done;\n        }\n        d = 0;\n        is_bigint = 1;\n    } else\n#endif\n    {\n        goto done;\n    }\n\n    switch (p->class_id) {\n    case JS_CLASS_INT8_ARRAY:\n        if (is_int && (int8_t)v64 == v64)\n            goto scan8;\n        break;\n    case JS_CLASS_UINT8C_ARRAY:\n    case JS_CLASS_UINT8_ARRAY:\n        if (is_int && (uint8_t)v64 == v64) {\n            const uint8_t *pv, *pp;\n            uint16_t v;\n        scan8:\n            pv = p->u.array.u.uint8_ptr;\n            v = v64;\n            if (inc > 0) {\n                pp = memchr(pv + k, v, len - k);\n                if (pp)\n                    res = pp - pv;\n            } else {\n                for (; k != stop; k += inc) {\n                    if (pv[k] == v) {\n                        res = k;\n                        break;\n                    }\n                }\n            }\n        }\n        break;\n    case JS_CLASS_INT16_ARRAY:\n        if (is_int && (int16_t)v64 == v64)\n            goto scan16;\n        break;\n    case JS_CLASS_UINT16_ARRAY:\n        if (is_int && (uint16_t)v64 == v64) {\n            const uint16_t *pv;\n            uint16_t v;\n        scan16:\n            pv = p->u.array.u.uint16_ptr;\n            v = v64;\n            for (; k != stop; k += inc) {\n                if (pv[k] == v) {\n                    res = k;\n                    break;\n                }\n            }\n        }\n        break;\n    case JS_CLASS_INT32_ARRAY:\n        if (is_int && (int32_t)v64 == v64)\n            goto scan32;\n        break;\n    case JS_CLASS_UINT32_ARRAY:\n        if (is_int && (uint32_t)v64 == v64) {\n            const uint32_t *pv;\n            uint32_t v;\n        scan32:\n            pv = p->u.array.u.uint32_ptr;\n            v = v64;\n            for (; k != stop; k += inc) {\n                if (pv[k] == v) {\n                    res = k;\n                    break;\n                }\n            }\n        }\n        break;\n    case JS_CLASS_FLOAT32_ARRAY:\n        if (is_bigint)\n            break;\n        if (isnan(d)) {\n            const float *pv = p->u.array.u.float_ptr;\n            /* special case: indexOf returns -1, includes finds NaN */\n            if (special != special_includes)\n                goto done;\n            for (; k != stop; k += inc) {\n                if (isnan(pv[k])) {\n                    res = k;\n                    break;\n                }\n            }\n        } else if ((f = (float)d) == d) {\n            const float *pv = p->u.array.u.float_ptr;\n            for (; k != stop; k += inc) {\n                if (pv[k] == f) {\n                    res = k;\n                    break;\n                }\n            }\n        }\n        break;\n    case JS_CLASS_FLOAT64_ARRAY:\n        if (is_bigint)\n            break;\n        if (isnan(d)) {\n            const double *pv = p->u.array.u.double_ptr;\n            /* special case: indexOf returns -1, includes finds NaN */\n            if (special != special_includes)\n                goto done;\n            for (; k != stop; k += inc) {\n                if (isnan(pv[k])) {\n                    res = k;\n                    break;\n                }\n            }\n        } else {\n            const double *pv = p->u.array.u.double_ptr;\n            for (; k != stop; k += inc) {\n                if (pv[k] == d) {\n                    res = k;\n                    break;\n                }\n            }\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_CLASS_BIG_INT64_ARRAY:\n        if (is_bigint || (is_math_mode(ctx) && is_int &&\n                          v64 >= -MAX_SAFE_INTEGER &&\n                          v64 <= MAX_SAFE_INTEGER)) {\n            goto scan64;\n        }\n        break;\n    case JS_CLASS_BIG_UINT64_ARRAY:\n        if (is_bigint || (is_math_mode(ctx) && is_int &&\n                          v64 >= 0 && v64 <= MAX_SAFE_INTEGER)) {\n            const uint64_t *pv;\n            uint64_t v;\n        scan64:\n            pv = p->u.array.u.uint64_ptr;\n            v = v64;\n            for (; k != stop; k += inc) {\n                if (pv[k] == v) {\n                    res = k;\n                    break;\n                }\n            }\n        }\n        break;\n#endif\n    }\n\ndone:\n    if (special == special_includes)\n        return JS_NewBool(ctx, res >= 0);\n    else\n        return JS_NewInt32(ctx, res);\n\nexception:\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_typed_array_join(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv, int toLocaleString)\n{\n    JSValue sep = JS_UNDEFINED, el;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p = NULL;\n    int i, n;\n    int c;\n\n    n = js_typed_array_get_length_internal(ctx, this_val);\n    if (n < 0)\n        goto exception;\n\n    c = ',';    /* default separator */\n    if (!toLocaleString && argc > 0 && !JS_IsUndefined(argv[0])) {\n        sep = JS_ToString(ctx, argv[0]);\n        if (JS_IsException(sep))\n            goto exception;\n        p = JS_VALUE_GET_STRING(sep);\n        if (p->len == 1 && !p->is_wide_char)\n            c = p->u.str8[0];\n        else\n            c = -1;\n    }\n    string_buffer_init(ctx, b, 0);\n\n    /* XXX: optimize with direct access */\n    for(i = 0; i < n; i++) {\n        if (i > 0) {\n            if (c >= 0) {\n                if (string_buffer_putc8(b, c))\n                    goto fail;\n            } else {\n                if (string_buffer_concat(b, p, 0, p->len))\n                    goto fail;\n            }\n        }\n        el = JS_GetPropertyUint32(ctx, this_val, i);\n        /* Can return undefined for example if the typed array is detached */\n        if (!JS_IsNull(el) && !JS_IsUndefined(el)) {\n            if (JS_IsException(el))\n                goto fail;\n            if (toLocaleString) {\n                el = JS_ToLocaleStringFree(ctx, el);\n            }\n            if (string_buffer_concat_value_free(b, el))\n                goto fail;\n        }\n    }\n    JS_FreeValue(ctx, sep);\n    return string_buffer_end(b);\n\nfail:\n    string_buffer_free(b);\n    JS_FreeValue(ctx, sep);\nexception:\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_typed_array_reverse(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv)\n{\n    JSObject *p;\n    int len;\n\n    len = js_typed_array_get_length_internal(ctx, this_val);\n    if (len < 0)\n        return JS_EXCEPTION;\n    if (len > 0) {\n        p = JS_VALUE_GET_OBJ(this_val);\n        switch (typed_array_size_log2(p->class_id)) {\n        case 0:\n            {\n                uint8_t *p1 = p->u.array.u.uint8_ptr;\n                uint8_t *p2 = p1 + len - 1;\n                while (p1 < p2) {\n                    uint8_t v = *p1;\n                    *p1++ = *p2;\n                    *p2-- = v;\n                }\n            }\n            break;\n        case 1:\n            {\n                uint16_t *p1 = p->u.array.u.uint16_ptr;\n                uint16_t *p2 = p1 + len - 1;\n                while (p1 < p2) {\n                    uint16_t v = *p1;\n                    *p1++ = *p2;\n                    *p2-- = v;\n                }\n            }\n            break;\n        case 2:\n            {\n                uint32_t *p1 = p->u.array.u.uint32_ptr;\n                uint32_t *p2 = p1 + len - 1;\n                while (p1 < p2) {\n                    uint32_t v = *p1;\n                    *p1++ = *p2;\n                    *p2-- = v;\n                }\n            }\n            break;\n        case 3:\n            {\n                uint64_t *p1 = p->u.array.u.uint64_ptr;\n                uint64_t *p2 = p1 + len - 1;\n                while (p1 < p2) {\n                    uint64_t v = *p1;\n                    *p1++ = *p2;\n                    *p2-- = v;\n                }\n            }\n            break;\n        default:\n            abort();\n        }\n    }\n    return JS_DupValue(ctx, this_val);\n}\n\nstatic JSValue js_typed_array_slice(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSValueConst args[2];\n    JSValue arr, val;\n    JSObject *p, *p1;\n    int n, len, start, final, count, shift;\n\n    arr = JS_UNDEFINED;\n    len = js_typed_array_get_length_internal(ctx, this_val);\n    if (len < 0)\n        goto exception;\n\n    if (JS_ToInt32Clamp(ctx, &start, argv[0], 0, len, len))\n        goto exception;\n    final = len;\n    if (!JS_IsUndefined(argv[1])) {\n        if (JS_ToInt32Clamp(ctx, &final, argv[1], 0, len, len))\n            goto exception;\n    }\n    count = max_int(final - start, 0);\n\n    p = get_typed_array(ctx, this_val, 0);\n    if (p == NULL)\n        goto exception;\n    shift = typed_array_size_log2(p->class_id);\n\n    args[0] = this_val;\n    args[1] = JS_NewInt32(ctx, count);\n    arr = js_typed_array___speciesCreate(ctx, JS_UNDEFINED, 2, args);\n    if (JS_IsException(arr))\n        goto exception;\n\n    if (count > 0) {\n        if (validate_typed_array(ctx, this_val)\n        ||  validate_typed_array(ctx, arr))\n            goto exception;\n\n        p1 = get_typed_array(ctx, arr, 0);\n        if (p1 != NULL && p->class_id == p1->class_id &&\n            typed_array_get_length(ctx, p1) >= count &&\n            typed_array_get_length(ctx, p) >= start + count) {\n            memcpy(p1->u.array.u.uint8_ptr,\n                   p->u.array.u.uint8_ptr + (start << shift),\n                   count << shift);\n        } else {\n            for (n = 0; n < count; n++) {\n                val = JS_GetPropertyValue(ctx, this_val, JS_NewInt32(ctx, start + n));\n                if (JS_IsException(val))\n                    goto exception;\n                if (JS_SetPropertyValue(ctx, arr, JS_NewInt32(ctx, n), val,\n                                        JS_PROP_THROW) < 0)\n                    goto exception;\n            }\n        }\n    }\n    return arr;\n\n exception:\n    JS_FreeValue(ctx, arr);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_typed_array_subarray(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    JSValueConst args[4];\n    JSValue arr, byteOffset, ta_buffer;\n    JSObject *p;\n    int len, start, final, count, shift, offset;\n\n    p = get_typed_array(ctx, this_val, 0);\n    if (!p)\n        goto exception;\n    len = p->u.array.count;\n    if (JS_ToInt32Clamp(ctx, &start, argv[0], 0, len, len))\n        goto exception;\n\n    final = len;\n    if (!JS_IsUndefined(argv[1])) {\n        if (JS_ToInt32Clamp(ctx, &final, argv[1], 0, len, len))\n            goto exception;\n    }\n    count = max_int(final - start, 0);\n    byteOffset = js_typed_array_get_byteOffset(ctx, this_val, 0);\n    if (JS_IsException(byteOffset))\n        goto exception;\n    shift = typed_array_size_log2(p->class_id);\n    offset = JS_VALUE_GET_INT(byteOffset) + (start << shift);\n    JS_FreeValue(ctx, byteOffset);\n    ta_buffer = js_typed_array_get_buffer(ctx, this_val, 0);\n    if (JS_IsException(ta_buffer))\n        goto exception;\n    args[0] = this_val;\n    args[1] = ta_buffer;\n    args[2] = JS_NewInt32(ctx, offset);\n    args[3] = JS_NewInt32(ctx, count);\n    arr = js_typed_array___speciesCreate(ctx, JS_UNDEFINED, 4, args);\n    JS_FreeValue(ctx, ta_buffer);\n    return arr;\n\n exception:\n    return JS_EXCEPTION;\n}\n\n/* TypedArray.prototype.sort */\n\nstatic int js_cmp_doubles(double x, double y)\n{\n    if (isnan(x))    return isnan(y) ? 0 : +1;\n    if (isnan(y))    return -1;\n    if (x < y)       return -1;\n    if (x > y)       return 1;\n    if (x != 0)      return 0;\n    if (signbit(x))  return signbit(y) ? 0 : -1;\n    else             return signbit(y) ? 1 : 0;\n}\n\nstatic int js_TA_cmp_int8(const void *a, const void *b, void *opaque) {\n    return *(const int8_t *)a - *(const int8_t *)b;\n}\n\nstatic int js_TA_cmp_uint8(const void *a, const void *b, void *opaque) {\n    return *(const uint8_t *)a - *(const uint8_t *)b;\n}\n\nstatic int js_TA_cmp_int16(const void *a, const void *b, void *opaque) {\n    return *(const int16_t *)a - *(const int16_t *)b;\n}\n\nstatic int js_TA_cmp_uint16(const void *a, const void *b, void *opaque) {\n    return *(const uint16_t *)a - *(const uint16_t *)b;\n}\n\nstatic int js_TA_cmp_int32(const void *a, const void *b, void *opaque) {\n    int32_t x = *(const int32_t *)a;\n    int32_t y = *(const int32_t *)b;\n    return (y < x) - (y > x);\n}\n\nstatic int js_TA_cmp_uint32(const void *a, const void *b, void *opaque) {\n    uint32_t x = *(const uint32_t *)a;\n    uint32_t y = *(const uint32_t *)b;\n    return (y < x) - (y > x);\n}\n\n#ifdef CONFIG_BIGNUM\nstatic int js_TA_cmp_int64(const void *a, const void *b, void *opaque) {\n    int64_t x = *(const int64_t *)a;\n    int64_t y = *(const int64_t *)b;\n    return (y < x) - (y > x);\n}\n\nstatic int js_TA_cmp_uint64(const void *a, const void *b, void *opaque) {\n    uint64_t x = *(const uint64_t *)a;\n    uint64_t y = *(const uint64_t *)b;\n    return (y < x) - (y > x);\n}\n#endif\n\nstatic int js_TA_cmp_float32(const void *a, const void *b, void *opaque) {\n    return js_cmp_doubles(*(const float *)a, *(const float *)b);\n}\n\nstatic int js_TA_cmp_float64(const void *a, const void *b, void *opaque) {\n    return js_cmp_doubles(*(const double *)a, *(const double *)b);\n}\n\nstatic JSValue js_TA_get_int8(JSContext *ctx, const void *a) {\n    return JS_NewInt32(ctx, *(const int8_t *)a);\n}\n\nstatic JSValue js_TA_get_uint8(JSContext *ctx, const void *a) {\n    return JS_NewInt32(ctx, *(const uint8_t *)a);\n}\n\nstatic JSValue js_TA_get_int16(JSContext *ctx, const void *a) {\n    return JS_NewInt32(ctx, *(const int16_t *)a);\n}\n\nstatic JSValue js_TA_get_uint16(JSContext *ctx, const void *a) {\n    return JS_NewInt32(ctx, *(const uint16_t *)a);\n}\n\nstatic JSValue js_TA_get_int32(JSContext *ctx, const void *a) {\n    return JS_NewInt32(ctx, *(const int32_t *)a);\n}\n\nstatic JSValue js_TA_get_uint32(JSContext *ctx, const void *a) {\n    return JS_NewUint32(ctx, *(const uint32_t *)a);\n}\n\n#ifdef CONFIG_BIGNUM\nstatic JSValue js_TA_get_int64(JSContext *ctx, const void *a) {\n    return JS_NewBigInt64(ctx, *(int64_t *)a);\n}\n\nstatic JSValue js_TA_get_uint64(JSContext *ctx, const void *a) {\n    return JS_NewBigUint64(ctx, *(uint64_t *)a);\n}\n#endif\n\nstatic JSValue js_TA_get_float32(JSContext *ctx, const void *a) {\n    return __JS_NewFloat64(ctx, *(const float *)a);\n}\n\nstatic JSValue js_TA_get_float64(JSContext *ctx, const void *a) {\n    return __JS_NewFloat64(ctx, *(const double *)a);\n}\n\nstruct TA_sort_context {\n    JSContext *ctx;\n    int exception;\n    JSValueConst arr;\n    JSValueConst cmp;\n    JSValue (*getfun)(JSContext *ctx, const void *a);\n    uint8_t *array_ptr; /* cannot change unless the array is detached */\n    int elt_size;\n};\n\nstatic int js_TA_cmp_generic(const void *a, const void *b, void *opaque) {\n    struct TA_sort_context *psc = opaque;\n    JSContext *ctx = psc->ctx;\n    uint32_t a_idx, b_idx;\n    JSValueConst argv[2];\n    JSValue res;\n    int cmp;\n\n    cmp = 0;\n    if (!psc->exception) {\n        a_idx = *(uint32_t *)a;\n        b_idx = *(uint32_t *)b;\n        argv[0] = psc->getfun(ctx, psc->array_ptr +\n                              a_idx * (size_t)psc->elt_size);\n        argv[1] = psc->getfun(ctx, psc->array_ptr +\n                              b_idx * (size_t)(psc->elt_size));\n        res = JS_Call(ctx, psc->cmp, JS_UNDEFINED, 2, argv);\n        if (JS_IsException(res)) {\n            psc->exception = 1;\n            goto done;\n        }\n        if (JS_VALUE_GET_TAG(res) == JS_TAG_INT) {\n            int val = JS_VALUE_GET_INT(res);\n            cmp = (val > 0) - (val < 0);\n        } else {\n            double val;\n            if (JS_ToFloat64Free(ctx, &val, res) < 0) {\n                psc->exception = 1;\n                goto done;\n            } else {\n                cmp = (val > 0) - (val < 0);\n            }\n        }\n        if (cmp == 0) {\n            /* make sort stable: compare array offsets */\n            cmp = (a_idx > b_idx) - (a_idx < b_idx);\n        }\n        if (validate_typed_array(ctx, psc->arr) < 0) {\n            psc->exception = 1;\n        }\n    done:\n        JS_FreeValue(ctx, (JSValue)argv[0]);\n        JS_FreeValue(ctx, (JSValue)argv[1]);\n    }\n    return cmp;\n}\n\nstatic JSValue js_typed_array_sort(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    JSObject *p;\n    int len;\n    size_t elt_size;\n    struct TA_sort_context tsc;\n    void *array_ptr;\n    int (*cmpfun)(const void *a, const void *b, void *opaque);\n\n    tsc.ctx = ctx;\n    tsc.exception = 0;\n    tsc.arr = this_val;\n    tsc.cmp = argv[0];\n\n    len = js_typed_array_get_length_internal(ctx, this_val);\n    if (len < 0)\n        return JS_EXCEPTION;\n    if (!JS_IsUndefined(tsc.cmp) && check_function(ctx, tsc.cmp))\n        return JS_EXCEPTION;\n\n    if (len > 1) {\n        p = JS_VALUE_GET_OBJ(this_val);\n        switch (p->class_id) {\n        case JS_CLASS_INT8_ARRAY:\n            tsc.getfun = js_TA_get_int8;\n            cmpfun = js_TA_cmp_int8;\n            break;\n        case JS_CLASS_UINT8C_ARRAY:\n        case JS_CLASS_UINT8_ARRAY:\n            tsc.getfun = js_TA_get_uint8;\n            cmpfun = js_TA_cmp_uint8;\n            break;\n        case JS_CLASS_INT16_ARRAY:\n            tsc.getfun = js_TA_get_int16;\n            cmpfun = js_TA_cmp_int16;\n            break;\n        case JS_CLASS_UINT16_ARRAY:\n            tsc.getfun = js_TA_get_uint16;\n            cmpfun = js_TA_cmp_uint16;\n            break;\n        case JS_CLASS_INT32_ARRAY:\n            tsc.getfun = js_TA_get_int32;\n            cmpfun = js_TA_cmp_int32;\n            break;\n        case JS_CLASS_UINT32_ARRAY:\n            tsc.getfun = js_TA_get_uint32;\n            cmpfun = js_TA_cmp_uint32;\n            break;\n#ifdef CONFIG_BIGNUM\n        case JS_CLASS_BIG_INT64_ARRAY:\n            tsc.getfun = js_TA_get_int64;\n            cmpfun = js_TA_cmp_int64;\n            break;\n        case JS_CLASS_BIG_UINT64_ARRAY:\n            tsc.getfun = js_TA_get_uint64;\n            cmpfun = js_TA_cmp_uint64;\n            break;\n#endif\n        case JS_CLASS_FLOAT32_ARRAY:\n            tsc.getfun = js_TA_get_float32;\n            cmpfun = js_TA_cmp_float32;\n            break;\n        case JS_CLASS_FLOAT64_ARRAY:\n            tsc.getfun = js_TA_get_float64;\n            cmpfun = js_TA_cmp_float64;\n            break;\n        default:\n            abort();\n        }\n        array_ptr = p->u.array.u.ptr;\n        elt_size = 1 << typed_array_size_log2(p->class_id);\n        if (!JS_IsUndefined(tsc.cmp)) {\n            uint32_t *array_idx;\n            void *array_tmp;\n            size_t i, j;\n            \n            /* XXX: a stable sort would use less memory */\n            array_idx = js_malloc(ctx, len * sizeof(array_idx[0]));\n            if (!array_idx)\n                return JS_EXCEPTION;\n            for(i = 0; i < len; i++)\n                array_idx[i] = i;\n            tsc.array_ptr = array_ptr;\n            tsc.elt_size = elt_size;\n            rqsort(array_idx, len, sizeof(array_idx[0]),\n                   js_TA_cmp_generic, &tsc);\n            if (tsc.exception)\n                goto fail;\n            array_tmp = js_malloc(ctx, len * elt_size);\n            if (!array_tmp) {\n            fail:\n                js_free(ctx, array_idx);\n                return JS_EXCEPTION;\n            }\n            memcpy(array_tmp, array_ptr, len * elt_size);\n            switch(elt_size) {\n            case 1:\n                for(i = 0; i < len; i++) {\n                    j = array_idx[i];\n                    ((uint8_t *)array_ptr)[i] = ((uint8_t *)array_tmp)[j];\n                }\n                break;\n            case 2:\n                for(i = 0; i < len; i++) {\n                    j = array_idx[i];\n                    ((uint16_t *)array_ptr)[i] = ((uint16_t *)array_tmp)[j];\n                }\n                break;\n            case 4:\n                for(i = 0; i < len; i++) {\n                    j = array_idx[i];\n                    ((uint32_t *)array_ptr)[i] = ((uint32_t *)array_tmp)[j];\n                }\n                break;\n            case 8:\n                for(i = 0; i < len; i++) {\n                    j = array_idx[i];\n                    ((uint64_t *)array_ptr)[i] = ((uint64_t *)array_tmp)[j];\n                }\n                break;\n            default:\n                abort();\n            }\n            js_free(ctx, array_tmp);\n            js_free(ctx, array_idx);\n        } else {\n            rqsort(array_ptr, len, elt_size, cmpfun, &tsc);\n            if (tsc.exception)\n                return JS_EXCEPTION;\n        }\n    }\n    return JS_DupValue(ctx, this_val);\n}\n\nstatic const JSCFunctionListEntry js_typed_array_base_funcs[] = {\n    JS_CFUNC_DEF(\"from\", 1, js_typed_array_from ),\n    JS_CFUNC_DEF(\"of\", 0, js_typed_array_of ),\n    JS_CGETSET_DEF(\"[Symbol.species]\", js_get_this, NULL ),\n    //JS_CFUNC_DEF(\"__getLength\", 2, js_typed_array___getLength ),\n    //JS_CFUNC_DEF(\"__create\", 2, js_typed_array___create ),\n    //JS_CFUNC_DEF(\"__speciesCreate\", 2, js_typed_array___speciesCreate ),\n};\n\nstatic const JSCFunctionListEntry js_typed_array_base_proto_funcs[] = {\n    JS_CGETSET_DEF(\"length\", js_typed_array_get_length, NULL ),\n    JS_CGETSET_MAGIC_DEF(\"buffer\", js_typed_array_get_buffer, NULL, 0 ),\n    JS_CGETSET_MAGIC_DEF(\"byteLength\", js_typed_array_get_byteLength, NULL, 0 ),\n    JS_CGETSET_MAGIC_DEF(\"byteOffset\", js_typed_array_get_byteOffset, NULL, 0 ),\n    JS_CFUNC_DEF(\"set\", 1, js_typed_array_set ),\n    JS_CFUNC_MAGIC_DEF(\"values\", 0, js_create_typed_array_iterator, JS_ITERATOR_KIND_VALUE ),\n    JS_ALIAS_DEF(\"[Symbol.iterator]\", \"values\" ),\n    JS_CFUNC_MAGIC_DEF(\"keys\", 0, js_create_typed_array_iterator, JS_ITERATOR_KIND_KEY ),\n    JS_CFUNC_MAGIC_DEF(\"entries\", 0, js_create_typed_array_iterator, JS_ITERATOR_KIND_KEY_AND_VALUE ),\n    JS_CGETSET_DEF(\"[Symbol.toStringTag]\", js_typed_array_get_toStringTag, NULL ),\n    JS_CFUNC_DEF(\"copyWithin\", 2, js_typed_array_copyWithin ),\n    JS_CFUNC_MAGIC_DEF(\"every\", 1, js_array_every, special_every | special_TA ),\n    JS_CFUNC_MAGIC_DEF(\"some\", 1, js_array_every, special_some | special_TA ),\n    JS_CFUNC_MAGIC_DEF(\"forEach\", 1, js_array_every, special_forEach | special_TA ),\n    JS_CFUNC_MAGIC_DEF(\"map\", 1, js_array_every, special_map | special_TA ),\n    JS_CFUNC_MAGIC_DEF(\"filter\", 1, js_array_every, special_filter | special_TA ),\n    JS_CFUNC_MAGIC_DEF(\"reduce\", 1, js_array_reduce, special_reduce | special_TA ),\n    JS_CFUNC_MAGIC_DEF(\"reduceRight\", 1, js_array_reduce, special_reduceRight | special_TA ),\n    JS_CFUNC_DEF(\"fill\", 1, js_typed_array_fill ),\n    JS_CFUNC_MAGIC_DEF(\"find\", 1, js_typed_array_find, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"findIndex\", 1, js_typed_array_find, 1 ),\n    JS_CFUNC_DEF(\"reverse\", 0, js_typed_array_reverse ),\n    JS_CFUNC_DEF(\"slice\", 2, js_typed_array_slice ),\n    JS_CFUNC_DEF(\"subarray\", 2, js_typed_array_subarray ),\n    JS_CFUNC_DEF(\"sort\", 1, js_typed_array_sort ),\n    JS_CFUNC_MAGIC_DEF(\"join\", 1, js_typed_array_join, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"toLocaleString\", 0, js_typed_array_join, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"indexOf\", 1, js_typed_array_indexOf, special_indexOf ),\n    JS_CFUNC_MAGIC_DEF(\"lastIndexOf\", 1, js_typed_array_indexOf, special_lastIndexOf ),\n    JS_CFUNC_MAGIC_DEF(\"includes\", 1, js_typed_array_indexOf, special_includes ),\n    //JS_ALIAS_BASE_DEF(\"toString\", \"toString\", 2 /* Array.prototype. */), @@@\n};\n\nstatic JSValue js_typed_array_base_constructor(JSContext *ctx,\n                                               JSValueConst this_val,\n                                               int argc, JSValueConst *argv)\n{\n    return JS_ThrowTypeError(ctx, \"cannot be called\");\n}\n\n/* 'obj' must be an allocated typed array object */\nstatic int typed_array_init(JSContext *ctx, JSValueConst obj,\n                            JSValue buffer, uint64_t offset, uint64_t len)\n{\n    JSTypedArray *ta;\n    JSObject *p, *pbuffer;\n    JSArrayBuffer *abuf;\n    int size_log2;\n\n    p = JS_VALUE_GET_OBJ(obj);\n    size_log2 = typed_array_size_log2(p->class_id);\n    ta = js_malloc(ctx, sizeof(*ta));\n    if (!ta) {\n        JS_FreeValue(ctx, buffer);\n        return -1;\n    }\n    pbuffer = JS_VALUE_GET_OBJ(buffer);\n    abuf = pbuffer->u.array_buffer;\n    ta->obj = p;\n    ta->buffer = pbuffer;\n    ta->offset = offset;\n    ta->length = len << size_log2;\n    list_add_tail(&ta->link, &abuf->array_list);\n    p->u.typed_array = ta;\n    p->u.array.count = len;\n    p->u.array.u.ptr = abuf->data + offset;\n    return 0;\n}\n\n\nstatic JSValue js_array_from_iterator(JSContext *ctx, uint32_t *plen,\n                                      JSValueConst obj, JSValueConst method)\n{\n    JSValue arr, iter, next_method = JS_UNDEFINED, val;\n    BOOL done;\n    uint32_t k;\n\n    *plen = 0;\n    arr = JS_NewArray(ctx);\n    if (JS_IsException(arr))\n        return arr;\n    iter = JS_GetIterator2(ctx, obj, method);\n    if (JS_IsException(iter))\n        goto fail;\n    next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);\n    if (JS_IsException(next_method))\n        goto fail;\n    k = 0;\n    for(;;) {\n        val = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);\n        if (JS_IsException(val))\n            goto fail;\n        if (done) {\n            JS_FreeValue(ctx, val);\n            break;\n        }\n        if (JS_CreateDataPropertyUint32(ctx, arr, k, val, JS_PROP_THROW) < 0)\n            goto fail;\n        k++;\n    }\n    JS_FreeValue(ctx, next_method);\n    JS_FreeValue(ctx, iter);\n    *plen = k;\n    return arr;\n fail:\n    JS_FreeValue(ctx, next_method);\n    JS_FreeValue(ctx, iter);\n    JS_FreeValue(ctx, arr);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_typed_array_constructor_obj(JSContext *ctx,\n                                              JSValueConst new_target,\n                                              JSValueConst obj,\n                                              int classid)\n{\n    JSValue iter, ret, arr = JS_UNDEFINED, val, buffer;\n    uint32_t i;\n    int size_log2;\n    int64_t len;\n\n    size_log2 = typed_array_size_log2(classid);\n    ret = js_create_from_ctor(ctx, new_target, classid);\n    if (JS_IsException(ret))\n        return JS_EXCEPTION;\n\n    iter = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_iterator);\n    if (JS_IsException(iter))\n        goto fail;\n    if (!JS_IsUndefined(iter) && !JS_IsNull(iter)) {\n        uint32_t len1;\n        arr = js_array_from_iterator(ctx, &len1, obj, iter);\n        JS_FreeValue(ctx, iter);\n        if (JS_IsException(arr))\n            goto fail;\n        len = len1;\n    } else {\n        if (js_get_length64(ctx, &len, obj))\n            goto fail;\n        arr = JS_DupValue(ctx, obj);\n    }\n\n    buffer = js_array_buffer_constructor1(ctx, JS_UNDEFINED,\n                                          len << size_log2);\n    if (JS_IsException(buffer))\n        goto fail;\n    if (typed_array_init(ctx, ret, buffer, 0, len))\n        goto fail;\n\n    for(i = 0; i < len; i++) {\n        val = JS_GetPropertyUint32(ctx, arr, i);\n        if (JS_IsException(val))\n            goto fail;\n        if (JS_SetPropertyUint32(ctx, ret, i, val) < 0)\n            goto fail;\n    }\n    JS_FreeValue(ctx, arr);\n    return ret;\n fail:\n    JS_FreeValue(ctx, arr);\n    JS_FreeValue(ctx, ret);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_typed_array_constructor_ta(JSContext *ctx,\n                                             JSValueConst new_target,\n                                             JSValueConst src_obj,\n                                             int classid)\n{\n    JSObject *p, *src_buffer;\n    JSTypedArray *ta;\n    JSValue ctor, obj, buffer;\n    uint32_t len, i;\n    int size_log2;\n    JSArrayBuffer *src_abuf, *abuf;\n\n    obj = js_create_from_ctor(ctx, new_target, classid);\n    if (JS_IsException(obj))\n        return obj;\n    p = JS_VALUE_GET_OBJ(src_obj);\n    if (typed_array_is_detached(ctx, p)) {\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        goto fail;\n    }\n    ta = p->u.typed_array;\n    len = p->u.array.count;\n    src_buffer = ta->buffer;\n    src_abuf = src_buffer->u.array_buffer;\n    if (!src_abuf->shared) {\n        ctor = JS_SpeciesConstructor(ctx, JS_MKPTR(JS_TAG_OBJECT, src_buffer),\n                                     JS_UNDEFINED);\n        if (JS_IsException(ctor))\n            goto fail;\n    } else {\n        /* force ArrayBuffer default constructor */\n        ctor = JS_UNDEFINED;\n    }\n    size_log2 = typed_array_size_log2(classid);\n    buffer = js_array_buffer_constructor1(ctx, ctor,\n                                          (uint64_t)len << size_log2);\n    JS_FreeValue(ctx, ctor);\n    if (JS_IsException(buffer))\n        goto fail;\n    /* necessary because it could have been detached */\n    if (typed_array_is_detached(ctx, p)) {\n        JS_FreeValue(ctx, buffer);\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        goto fail;\n    }\n    abuf = JS_GetOpaque(buffer, JS_CLASS_ARRAY_BUFFER);\n    if (typed_array_init(ctx, obj, buffer, 0, len))\n        goto fail;\n    if (p->class_id == classid) {\n        /* same type: copy the content */\n        memcpy(abuf->data, src_abuf->data + ta->offset, abuf->byte_length);\n    } else {\n        for(i = 0; i < len; i++) {\n            JSValue val;\n            val = JS_GetPropertyUint32(ctx, src_obj, i);\n            if (JS_IsException(val))\n                goto fail;\n            if (JS_SetPropertyUint32(ctx, obj, i, val) < 0)\n                goto fail;\n        }\n    }\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_typed_array_constructor(JSContext *ctx,\n                                          JSValueConst new_target,\n                                          int argc, JSValueConst *argv,\n                                          int classid)\n{\n    JSValue buffer, obj;\n    JSArrayBuffer *abuf;\n    int size_log2;\n    uint64_t len, offset;\n\n    size_log2 = typed_array_size_log2(classid);\n    if (JS_VALUE_GET_TAG(argv[0]) != JS_TAG_OBJECT) {\n        if (JS_ToIndex(ctx, &len, argv[0]))\n            return JS_EXCEPTION;\n        buffer = js_array_buffer_constructor1(ctx, JS_UNDEFINED,\n                                              len << size_log2);\n        if (JS_IsException(buffer))\n            return JS_EXCEPTION;\n        offset = 0;\n    } else {\n        JSObject *p = JS_VALUE_GET_OBJ(argv[0]);\n        if (p->class_id == JS_CLASS_ARRAY_BUFFER ||\n            p->class_id == JS_CLASS_SHARED_ARRAY_BUFFER) {\n            abuf = p->u.array_buffer;\n            if (JS_ToIndex(ctx, &offset, argv[1]))\n                return JS_EXCEPTION;\n            if (abuf->detached)\n                return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n            if ((offset & ((1 << size_log2) - 1)) != 0 ||\n                offset > abuf->byte_length)\n                return JS_ThrowRangeError(ctx, \"invalid offset\");\n            if (JS_IsUndefined(argv[2])) {\n                if ((abuf->byte_length & ((1 << size_log2) - 1)) != 0)\n                    goto invalid_length;\n                len = (abuf->byte_length - offset) >> size_log2;\n            } else {\n                if (JS_ToIndex(ctx, &len, argv[2]))\n                    return JS_EXCEPTION;\n                if (abuf->detached)\n                    return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n                if ((offset + (len << size_log2)) > abuf->byte_length) {\n                invalid_length:\n                    return JS_ThrowRangeError(ctx, \"invalid length\");\n                }\n            }\n            buffer = JS_DupValue(ctx, argv[0]);\n        } else {\n            if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n                p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n                return js_typed_array_constructor_ta(ctx, new_target, argv[0], classid);\n            } else {\n                return js_typed_array_constructor_obj(ctx, new_target, argv[0], classid);\n            }\n        }\n    }\n\n    obj = js_create_from_ctor(ctx, new_target, classid);\n    if (JS_IsException(obj)) {\n        JS_FreeValue(ctx, buffer);\n        return JS_EXCEPTION;\n    }\n    if (typed_array_init(ctx, obj, buffer, offset, len)) {\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    return obj;\n}\n\nstatic void js_typed_array_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSTypedArray *ta = p->u.typed_array;\n    if (ta) {\n        /* during the GC the finalizers are called in an arbitrary\n           order so the ArrayBuffer finalizer may have been called */\n        if (JS_IsLiveObject(rt, JS_MKPTR(JS_TAG_OBJECT, ta->buffer))) {\n            list_del(&ta->link);\n        }\n        JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, ta->buffer));\n        js_free_rt(rt, ta);\n    }\n}\n\nstatic void js_typed_array_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSTypedArray *ta = p->u.typed_array;\n    if (ta) {\n        JS_MarkValue(rt, JS_MKPTR(JS_TAG_OBJECT, ta->buffer), mark_func);\n    }\n}\n\nstatic JSValue js_dataview_constructor(JSContext *ctx,\n                                       JSValueConst new_target,\n                                       int argc, JSValueConst *argv)\n{\n    JSArrayBuffer *abuf;\n    uint64_t offset;\n    uint32_t len;\n    JSValueConst buffer;\n    JSValue obj;\n    JSTypedArray *ta;\n    JSObject *p;\n\n    buffer = argv[0];\n    abuf = js_get_array_buffer(ctx, buffer);\n    if (!abuf)\n        return JS_EXCEPTION;\n    offset = 0;\n    if (argc > 1) {\n        if (JS_ToIndex(ctx, &offset, argv[1]))\n            return JS_EXCEPTION;\n    }\n    if (abuf->detached)\n        return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n    if (offset > abuf->byte_length)\n        return JS_ThrowRangeError(ctx, \"invalid byteOffset\");\n    len = abuf->byte_length - offset;\n    if (argc > 2 && !JS_IsUndefined(argv[2])) {\n        uint64_t l;\n        if (JS_ToIndex(ctx, &l, argv[2]))\n            return JS_EXCEPTION;\n        if (l > len)\n            return JS_ThrowRangeError(ctx, \"invalid byteLength\");\n        len = l;\n    }\n\n    obj = js_create_from_ctor(ctx, new_target, JS_CLASS_DATAVIEW);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    if (abuf->detached) {\n        /* could have been detached in js_create_from_ctor() */\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        goto fail;\n    }\n    ta = js_malloc(ctx, sizeof(*ta));\n    if (!ta) {\n    fail:\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    p = JS_VALUE_GET_OBJ(obj);\n    ta->obj = p;\n    ta->buffer = JS_VALUE_GET_OBJ(JS_DupValue(ctx, buffer));\n    ta->offset = offset;\n    ta->length = len;\n    list_add_tail(&ta->link, &abuf->array_list);\n    p->u.typed_array = ta;\n    return obj;\n}\n\nstatic JSValue js_dataview_getValue(JSContext *ctx,\n                                    JSValueConst this_obj,\n                                    int argc, JSValueConst *argv, int class_id)\n{\n    JSTypedArray *ta;\n    JSArrayBuffer *abuf;\n    int is_swap, size;\n    uint8_t *ptr;\n    uint32_t v;\n    uint64_t pos;\n\n    ta = JS_GetOpaque2(ctx, this_obj, JS_CLASS_DATAVIEW);\n    if (!ta)\n        return JS_EXCEPTION;\n    size = 1 << typed_array_size_log2(class_id);\n    if (JS_ToIndex(ctx, &pos, argv[0]))\n        return JS_EXCEPTION;\n    is_swap = FALSE;\n    if (argc > 1)\n        is_swap = JS_ToBool(ctx, argv[1]);\n#ifndef WORDS_BIGENDIAN\n    is_swap ^= 1;\n#endif\n    abuf = ta->buffer->u.array_buffer;\n    if (abuf->detached)\n        return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n    if ((pos + size) > ta->length)\n        return JS_ThrowRangeError(ctx, \"out of bound\");\n    ptr = abuf->data + ta->offset + pos;\n\n    switch(class_id) {\n    case JS_CLASS_INT8_ARRAY:\n        return JS_NewInt32(ctx, *(int8_t *)ptr);\n    case JS_CLASS_UINT8_ARRAY:\n        return JS_NewInt32(ctx, *(uint8_t *)ptr);\n    case JS_CLASS_INT16_ARRAY:\n        v = get_u16(ptr);\n        if (is_swap)\n            v = bswap16(v);\n        return JS_NewInt32(ctx, (int16_t)v);\n    case JS_CLASS_UINT16_ARRAY:\n        v = get_u16(ptr);\n        if (is_swap)\n            v = bswap16(v);\n        return JS_NewInt32(ctx, v);\n    case JS_CLASS_INT32_ARRAY:\n        v = get_u32(ptr);\n        if (is_swap)\n            v = bswap32(v);\n        return JS_NewInt32(ctx, v);\n    case JS_CLASS_UINT32_ARRAY:\n        v = get_u32(ptr);\n        if (is_swap)\n            v = bswap32(v);\n        return JS_NewUint32(ctx, v);\n#ifdef CONFIG_BIGNUM\n    case JS_CLASS_BIG_INT64_ARRAY:\n        {\n            uint64_t v;\n            v = get_u64(ptr);\n            if (is_swap)\n                v = bswap64(v);\n            return JS_NewBigInt64(ctx, v);\n        }\n        break;\n    case JS_CLASS_BIG_UINT64_ARRAY:\n        {\n            uint64_t v;\n            v = get_u64(ptr);\n            if (is_swap)\n                v = bswap64(v);\n            return JS_NewBigUint64(ctx, v);\n        }\n        break;\n#endif\n    case JS_CLASS_FLOAT32_ARRAY:\n        {\n            union {\n                float f;\n                uint32_t i;\n            } u;\n            v = get_u32(ptr);\n            if (is_swap)\n                v = bswap32(v);\n            u.i = v;\n            return __JS_NewFloat64(ctx, u.f);\n        }\n    case JS_CLASS_FLOAT64_ARRAY:\n        {\n            union {\n                double f;\n                uint64_t i;\n            } u;\n            u.i = get_u64(ptr);\n            if (is_swap)\n                u.i = bswap64(u.i);\n            return __JS_NewFloat64(ctx, u.f);\n        }\n    default:\n        abort();\n    }\n}\n\nstatic JSValue js_dataview_setValue(JSContext *ctx,\n                                    JSValueConst this_obj,\n                                    int argc, JSValueConst *argv, int class_id)\n{\n    JSTypedArray *ta;\n    JSArrayBuffer *abuf;\n    int is_swap, size;\n    uint8_t *ptr;\n    uint64_t v64;\n    uint32_t v;\n    uint64_t pos;\n    JSValueConst val;\n\n    ta = JS_GetOpaque2(ctx, this_obj, JS_CLASS_DATAVIEW);\n    if (!ta)\n        return JS_EXCEPTION;\n    size = 1 << typed_array_size_log2(class_id);\n    if (JS_ToIndex(ctx, &pos, argv[0]))\n        return JS_EXCEPTION;\n    val = argv[1];\n    v = 0; /* avoid warning */\n    v64 = 0; /* avoid warning */\n    if (class_id <= JS_CLASS_UINT32_ARRAY) {\n        if (JS_ToUint32(ctx, &v, val))\n            return JS_EXCEPTION;\n    } else\n#ifdef CONFIG_BIGNUM\n    if (class_id <= JS_CLASS_BIG_UINT64_ARRAY) {\n        if (JS_ToBigInt64(ctx, (int64_t *)&v64, val))\n            return JS_EXCEPTION;\n    } else\n#endif\n    {\n        double d;\n        if (JS_ToFloat64(ctx, &d, val))\n            return JS_EXCEPTION;\n        if (class_id == JS_CLASS_FLOAT32_ARRAY) {\n            union {\n                float f;\n                uint32_t i;\n            } u;\n            u.f = d;\n            v = u.i;\n        } else {\n            JSFloat64Union u;\n            u.d = d;\n            v64 = u.u64;\n        }\n    }\n    is_swap = FALSE;\n    if (argc > 2)\n        is_swap = JS_ToBool(ctx, argv[2]);\n#ifndef WORDS_BIGENDIAN\n    is_swap ^= 1;\n#endif\n    abuf = ta->buffer->u.array_buffer;\n    if (abuf->detached)\n        return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n    if ((pos + size) > ta->length)\n        return JS_ThrowRangeError(ctx, \"out of bound\");\n    ptr = abuf->data + ta->offset + pos;\n\n    switch(class_id) {\n    case JS_CLASS_INT8_ARRAY:\n    case JS_CLASS_UINT8_ARRAY:\n        *ptr = v;\n        break;\n    case JS_CLASS_INT16_ARRAY:\n    case JS_CLASS_UINT16_ARRAY:\n        if (is_swap)\n            v = bswap16(v);\n        put_u16(ptr, v);\n        break;\n    case JS_CLASS_INT32_ARRAY:\n    case JS_CLASS_UINT32_ARRAY:\n    case JS_CLASS_FLOAT32_ARRAY:\n        if (is_swap)\n            v = bswap32(v);\n        put_u32(ptr, v);\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_CLASS_BIG_INT64_ARRAY:\n    case JS_CLASS_BIG_UINT64_ARRAY:\n#endif\n    case JS_CLASS_FLOAT64_ARRAY:\n        if (is_swap)\n            v64 = bswap64(v64);\n        put_u64(ptr, v64);\n        break;\n    default:\n        abort();\n    }\n    return JS_UNDEFINED;\n}\n\nstatic const JSCFunctionListEntry js_dataview_proto_funcs[] = {\n    JS_CGETSET_MAGIC_DEF(\"buffer\", js_typed_array_get_buffer, NULL, 1 ),\n    JS_CGETSET_MAGIC_DEF(\"byteLength\", js_typed_array_get_byteLength, NULL, 1 ),\n    JS_CGETSET_MAGIC_DEF(\"byteOffset\", js_typed_array_get_byteOffset, NULL, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"getInt8\", 1, js_dataview_getValue, JS_CLASS_INT8_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"getUint8\", 1, js_dataview_getValue, JS_CLASS_UINT8_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"getInt16\", 1, js_dataview_getValue, JS_CLASS_INT16_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"getUint16\", 1, js_dataview_getValue, JS_CLASS_UINT16_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"getInt32\", 1, js_dataview_getValue, JS_CLASS_INT32_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"getUint32\", 1, js_dataview_getValue, JS_CLASS_UINT32_ARRAY ),\n#ifdef CONFIG_BIGNUM\n    JS_CFUNC_MAGIC_DEF(\"getBigInt64\", 1, js_dataview_getValue, JS_CLASS_BIG_INT64_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"getBigUint64\", 1, js_dataview_getValue, JS_CLASS_BIG_UINT64_ARRAY ),\n#endif\n    JS_CFUNC_MAGIC_DEF(\"getFloat32\", 1, js_dataview_getValue, JS_CLASS_FLOAT32_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"getFloat64\", 1, js_dataview_getValue, JS_CLASS_FLOAT64_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"setInt8\", 2, js_dataview_setValue, JS_CLASS_INT8_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"setUint8\", 2, js_dataview_setValue, JS_CLASS_UINT8_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"setInt16\", 2, js_dataview_setValue, JS_CLASS_INT16_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"setUint16\", 2, js_dataview_setValue, JS_CLASS_UINT16_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"setInt32\", 2, js_dataview_setValue, JS_CLASS_INT32_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"setUint32\", 2, js_dataview_setValue, JS_CLASS_UINT32_ARRAY ),\n#ifdef CONFIG_BIGNUM\n    JS_CFUNC_MAGIC_DEF(\"setBigInt64\", 2, js_dataview_setValue, JS_CLASS_BIG_INT64_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"setBigUint64\", 2, js_dataview_setValue, JS_CLASS_BIG_UINT64_ARRAY ),\n#endif\n    JS_CFUNC_MAGIC_DEF(\"setFloat32\", 2, js_dataview_setValue, JS_CLASS_FLOAT32_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"setFloat64\", 2, js_dataview_setValue, JS_CLASS_FLOAT64_ARRAY ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"DataView\", JS_PROP_CONFIGURABLE ),\n};\n\n/* Atomics */\n#ifdef CONFIG_ATOMICS\n\ntypedef enum AtomicsOpEnum {\n    ATOMICS_OP_ADD,\n    ATOMICS_OP_AND,\n    ATOMICS_OP_OR,\n    ATOMICS_OP_SUB,\n    ATOMICS_OP_XOR,\n    ATOMICS_OP_EXCHANGE,\n    ATOMICS_OP_COMPARE_EXCHANGE,\n    ATOMICS_OP_LOAD,\n} AtomicsOpEnum;\n\nstatic void *js_atomics_get_ptr(JSContext *ctx,\n                                JSArrayBuffer **pabuf,\n                                int *psize_log2, JSClassID *pclass_id,\n                                JSValueConst obj, JSValueConst idx_val,\n                                int is_waitable)\n{\n    JSObject *p;\n    JSTypedArray *ta;\n    JSArrayBuffer *abuf;\n    void *ptr;\n    uint64_t idx;\n    BOOL err;\n    int size_log2;\n\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        goto fail;\n    p = JS_VALUE_GET_OBJ(obj);\n#ifdef CONFIG_BIGNUM\n    if (is_waitable)\n        err = (p->class_id != JS_CLASS_INT32_ARRAY &&\n               p->class_id != JS_CLASS_BIG_INT64_ARRAY);\n    else\n        err = !(p->class_id >= JS_CLASS_INT8_ARRAY &&\n                p->class_id <= JS_CLASS_BIG_UINT64_ARRAY);\n#else\n    if (is_waitable)\n        err = (p->class_id != JS_CLASS_INT32_ARRAY);\n    else\n        err = !(p->class_id >= JS_CLASS_INT8_ARRAY &&\n                p->class_id <= JS_CLASS_UINT32_ARRAY);\n#endif\n    if (err) {\n    fail:\n        JS_ThrowTypeError(ctx, \"integer TypedArray expected\");\n        return NULL;\n    }\n    ta = p->u.typed_array;\n    abuf = ta->buffer->u.array_buffer;\n    if (!abuf->shared) {\n        if (is_waitable == 2) {\n            JS_ThrowTypeError(ctx, \"not a SharedArrayBuffer TypedArray\");\n            return NULL;\n        }\n        if (abuf->detached) {\n            JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n            return NULL;\n        }\n    }\n    if (JS_ToIndex(ctx, &idx, idx_val)) {\n        return NULL;\n    }\n    /* if the array buffer is detached, p->u.array.count = 0 */\n    if (idx >= p->u.array.count) {\n        JS_ThrowRangeError(ctx, \"out-of-bound access\");\n        return NULL;\n    }\n    size_log2 = typed_array_size_log2(p->class_id);\n    ptr = p->u.array.u.uint8_ptr + ((uintptr_t)idx << size_log2);\n    if (pabuf)\n        *pabuf = abuf;\n    if (psize_log2)\n        *psize_log2 = size_log2;\n    if (pclass_id)\n        *pclass_id = p->class_id;\n    return ptr;\n}\n\nstatic JSValue js_atomics_op(JSContext *ctx,\n                             JSValueConst this_obj,\n                             int argc, JSValueConst *argv, int op)\n{\n    int size_log2;\n#ifdef CONFIG_BIGNUM\n    uint64_t v, a, rep_val;\n#else\n    uint32_t v, a, rep_val;\n#endif\n    void *ptr;\n    JSValue ret;\n    JSClassID class_id;\n    JSArrayBuffer *abuf;\n\n    ptr = js_atomics_get_ptr(ctx, &abuf, &size_log2, &class_id,\n                             argv[0], argv[1], 0);\n    if (!ptr)\n        return JS_EXCEPTION;\n    rep_val = 0;\n    if (op == ATOMICS_OP_LOAD) {\n        v = 0;\n    } else {\n#ifdef CONFIG_BIGNUM\n        if (size_log2 == 3) {\n            int64_t v64;\n            if (JS_ToBigInt64(ctx, &v64, argv[2]))\n                return JS_EXCEPTION;\n            v = v64;\n            if (op == ATOMICS_OP_COMPARE_EXCHANGE) {\n                if (JS_ToBigInt64(ctx, &v64, argv[3]))\n                    return JS_EXCEPTION;\n                rep_val = v64;\n            }\n        } else\n#endif\n        {\n                uint32_t v32;\n                if (JS_ToUint32(ctx, &v32, argv[2]))\n                    return JS_EXCEPTION;\n                v = v32;\n                if (op == ATOMICS_OP_COMPARE_EXCHANGE) {\n                    if (JS_ToUint32(ctx, &v32, argv[3]))\n                        return JS_EXCEPTION;\n                    rep_val = v32;\n                }\n        }\n        if (abuf->detached)\n            return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n   }\n\n   switch(op | (size_log2 << 3)) {\n            \n#ifdef CONFIG_BIGNUM\n#define OP(op_name, func_name)                          \\\n    case ATOMICS_OP_ ## op_name | (0 << 3):             \\\n       a = func_name((_Atomic(uint8_t) *)ptr, v);       \\\n       break;                                           \\\n    case ATOMICS_OP_ ## op_name | (1 << 3):             \\\n        a = func_name((_Atomic(uint16_t) *)ptr, v);     \\\n        break;                                          \\\n    case ATOMICS_OP_ ## op_name | (2 << 3):             \\\n        a = func_name((_Atomic(uint32_t) *)ptr, v);     \\\n        break;                                          \\\n    case ATOMICS_OP_ ## op_name | (3 << 3):             \\\n        a = func_name((_Atomic(uint64_t) *)ptr, v);     \\\n        break;\n#else\n#define OP(op_name, func_name)                          \\\n    case ATOMICS_OP_ ## op_name | (0 << 3):             \\\n       a = func_name((_Atomic(uint8_t) *)ptr, v);       \\\n       break;                                           \\\n    case ATOMICS_OP_ ## op_name | (1 << 3):             \\\n        a = func_name((_Atomic(uint16_t) *)ptr, v);     \\\n        break;                                          \\\n    case ATOMICS_OP_ ## op_name | (2 << 3):             \\\n        a = func_name((_Atomic(uint32_t) *)ptr, v);     \\\n        break;\n#endif\n        OP(ADD, atomic_fetch_add)\n        OP(AND, atomic_fetch_and)\n        OP(OR, atomic_fetch_or)\n        OP(SUB, atomic_fetch_sub)\n        OP(XOR, atomic_fetch_xor)\n        OP(EXCHANGE, atomic_exchange)\n#undef OP\n\n    case ATOMICS_OP_LOAD | (0 << 3):\n        a = atomic_load((_Atomic(uint8_t) *)ptr);\n        break;\n    case ATOMICS_OP_LOAD | (1 << 3):\n        a = atomic_load((_Atomic(uint16_t) *)ptr);\n        break;\n    case ATOMICS_OP_LOAD | (2 << 3):\n        a = atomic_load((_Atomic(uint32_t) *)ptr);\n        break;\n#ifdef CONFIG_BIGNUM\n    case ATOMICS_OP_LOAD | (3 << 3):\n        a = atomic_load((_Atomic(uint64_t) *)ptr);\n        break;\n#endif\n        \n    case ATOMICS_OP_COMPARE_EXCHANGE | (0 << 3):\n        {\n            uint8_t v1 = v;\n            atomic_compare_exchange_strong((_Atomic(uint8_t) *)ptr, &v1, rep_val);\n            a = v1;\n        }\n        break;\n    case ATOMICS_OP_COMPARE_EXCHANGE | (1 << 3):\n        {\n            uint16_t v1 = v;\n            atomic_compare_exchange_strong((_Atomic(uint16_t) *)ptr, &v1, rep_val);\n            a = v1;\n        }\n        break;\n    case ATOMICS_OP_COMPARE_EXCHANGE | (2 << 3):\n        {\n            uint32_t v1 = v;\n            atomic_compare_exchange_strong((_Atomic(uint32_t) *)ptr, &v1, rep_val);\n            a = v1;\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case ATOMICS_OP_COMPARE_EXCHANGE | (3 << 3):\n        {\n            uint64_t v1 = v;\n            atomic_compare_exchange_strong((_Atomic(uint64_t) *)ptr, &v1, rep_val);\n            a = v1;\n        }\n        break;\n#endif\n    default:\n        abort();\n    }\n\n    switch(class_id) {\n    case JS_CLASS_INT8_ARRAY:\n        a = (int8_t)a;\n        goto done;\n    case JS_CLASS_UINT8_ARRAY:\n        a = (uint8_t)a;\n        goto done;\n    case JS_CLASS_INT16_ARRAY:\n        a = (int16_t)a;\n        goto done;\n    case JS_CLASS_UINT16_ARRAY:\n        a = (uint16_t)a;\n        goto done;\n    case JS_CLASS_INT32_ARRAY:\n    done:\n        ret = JS_NewInt32(ctx, a);\n        break;\n    case JS_CLASS_UINT32_ARRAY:\n        ret = JS_NewUint32(ctx, a);\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_CLASS_BIG_INT64_ARRAY:\n        ret = JS_NewBigInt64(ctx, a);\n        break;\n    case JS_CLASS_BIG_UINT64_ARRAY:\n        ret = JS_NewBigUint64(ctx, a);\n        break;\n#endif\n    default:\n        abort();\n    }\n    return ret;\n}\n\nstatic JSValue js_atomics_store(JSContext *ctx,\n                                JSValueConst this_obj,\n                                int argc, JSValueConst *argv)\n{\n    int size_log2;\n    void *ptr;\n    JSValue ret;\n    JSArrayBuffer *abuf;\n\n    ptr = js_atomics_get_ptr(ctx, &abuf, &size_log2, NULL,\n                             argv[0], argv[1], 0);\n    if (!ptr)\n        return JS_EXCEPTION;\n#ifdef CONFIG_BIGNUM\n    if (size_log2 == 3) {\n        int64_t v64;\n        ret = JS_ToBigIntValueFree(ctx, JS_DupValue(ctx, argv[2]));\n        if (JS_IsException(ret))\n            return ret;\n        if (JS_ToBigInt64(ctx, &v64, ret)) {\n            JS_FreeValue(ctx, ret);\n            return JS_EXCEPTION;\n        }\n        if (abuf->detached)\n            return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        atomic_store((_Atomic(uint64_t) *)ptr, v64);\n    } else\n#endif\n    {\n        uint32_t v;\n        /* XXX: spec, would be simpler to return the written value */\n        ret = JS_ToIntegerFree(ctx, JS_DupValue(ctx, argv[2]));\n        if (JS_IsException(ret))\n            return ret;\n        if (JS_ToUint32(ctx, &v, ret)) {\n            JS_FreeValue(ctx, ret);\n            return JS_EXCEPTION;\n        }\n        if (abuf->detached)\n            return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        switch(size_log2) {\n        case 0:\n            atomic_store((_Atomic(uint8_t) *)ptr, v);\n            break;\n        case 1:\n            atomic_store((_Atomic(uint16_t) *)ptr, v);\n            break;\n        case 2:\n            atomic_store((_Atomic(uint32_t) *)ptr, v);\n            break;\n        default:\n            abort();\n        }\n    }\n    return ret;\n}\n\nstatic JSValue js_atomics_isLockFree(JSContext *ctx,\n                                     JSValueConst this_obj,\n                                     int argc, JSValueConst *argv)\n{\n    int v, ret;\n    if (JS_ToInt32Sat(ctx, &v, argv[0]))\n        return JS_EXCEPTION;\n    ret = (v == 1 || v == 2 || v == 4\n#ifdef CONFIG_BIGNUM\n           || v == 8\n#endif\n           );\n    return JS_NewBool(ctx, ret);\n}\n\ntypedef struct JSAtomicsWaiter {\n    struct list_head link;\n    BOOL linked;\n    pthread_cond_t cond;\n    int32_t *ptr;\n} JSAtomicsWaiter;\n\nstatic pthread_mutex_t js_atomics_mutex = PTHREAD_MUTEX_INITIALIZER;\nstatic struct list_head js_atomics_waiter_list =\n    LIST_HEAD_INIT(js_atomics_waiter_list);\n\nstatic JSValue js_atomics_wait(JSContext *ctx,\n                               JSValueConst this_obj,\n                               int argc, JSValueConst *argv)\n{\n    int64_t v;\n    int32_t v32;\n    void *ptr;\n    int64_t timeout;\n    struct timespec ts;\n    JSAtomicsWaiter waiter_s, *waiter;\n    int ret, size_log2, res;\n    double d;\n\n    ptr = js_atomics_get_ptr(ctx, NULL, &size_log2, NULL,\n                             argv[0], argv[1], 2);\n    if (!ptr)\n        return JS_EXCEPTION;\n#ifdef CONFIG_BIGNUM\n    if (size_log2 == 3) {\n        if (JS_ToBigInt64(ctx, &v, argv[2]))\n            return JS_EXCEPTION;\n    } else\n#endif\n    {        \n        if (JS_ToInt32(ctx, &v32, argv[2]))\n            return JS_EXCEPTION;\n        v = v32;\n    }\n    if (JS_ToFloat64(ctx, &d, argv[3]))\n        return JS_EXCEPTION;\n    if (isnan(d) || d > INT64_MAX)\n        timeout = INT64_MAX;\n    else if (d < 0)\n        timeout = 0;\n    else\n        timeout = (int64_t)d;\n    if (!ctx->rt->can_block)\n        return JS_ThrowTypeError(ctx, \"cannot block in this thread\");\n\n    /* XXX: inefficient if large number of waiters, should hash on\n       'ptr' value */\n    /* XXX: use Linux futexes when available ? */\n    pthread_mutex_lock(&js_atomics_mutex);\n    if (size_log2 == 3) {\n        res = *(int64_t *)ptr != v;\n    } else {\n        res = *(int32_t *)ptr != v;\n    }\n    if (res) {\n        pthread_mutex_unlock(&js_atomics_mutex);\n        return JS_AtomToString(ctx, JS_ATOM_not_equal);\n    }\n\n    waiter = &waiter_s;\n    waiter->ptr = ptr;\n    pthread_cond_init(&waiter->cond, NULL);\n    waiter->linked = TRUE;\n    list_add_tail(&waiter->link, &js_atomics_waiter_list);\n\n    if (timeout == INT64_MAX) {\n        pthread_cond_wait(&waiter->cond, &js_atomics_mutex);\n        ret = 0;\n    } else {\n        /* XXX: use clock monotonic */\n        clock_gettime(CLOCK_REALTIME, &ts);\n        ts.tv_sec += timeout / 1000;\n        ts.tv_nsec += (timeout % 1000) * 1000000;\n        if (ts.tv_nsec >= 1000000000) {\n            ts.tv_nsec -= 1000000000;\n            ts.tv_sec++;\n        }\n        ret = pthread_cond_timedwait(&waiter->cond, &js_atomics_mutex,\n                                     &ts);\n    }\n    if (waiter->linked)\n        list_del(&waiter->link);\n    pthread_mutex_unlock(&js_atomics_mutex);\n    pthread_cond_destroy(&waiter->cond);\n    if (ret == ETIMEDOUT) {\n        return JS_AtomToString(ctx, JS_ATOM_timed_out);\n    } else {\n        return JS_AtomToString(ctx, JS_ATOM_ok);\n    }\n}\n\nstatic JSValue js_atomics_notify(JSContext *ctx,\n                                 JSValueConst this_obj,\n                                 int argc, JSValueConst *argv)\n{\n    struct list_head *el, *el1, waiter_list;\n    int32_t count, n;\n    void *ptr;\n    JSAtomicsWaiter *waiter;\n    JSArrayBuffer *abuf;\n\n    ptr = js_atomics_get_ptr(ctx, &abuf, NULL, NULL, argv[0], argv[1], 1);\n    if (!ptr)\n        return JS_EXCEPTION;\n\n    if (JS_IsUndefined(argv[2])) {\n        count = INT32_MAX;\n    } else {\n        if (JS_ToInt32Clamp(ctx, &count, argv[2], 0, INT32_MAX, 0))\n            return JS_EXCEPTION;\n    }\n    if (abuf->detached)\n        return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n\n    n = 0;\n    if (abuf->shared && count > 0) {\n        pthread_mutex_lock(&js_atomics_mutex);\n        init_list_head(&waiter_list);\n        list_for_each_safe(el, el1, &js_atomics_waiter_list) {\n            waiter = list_entry(el, JSAtomicsWaiter, link);\n            if (waiter->ptr == ptr) {\n                list_del(&waiter->link);\n                waiter->linked = FALSE;\n                list_add_tail(&waiter->link, &waiter_list);\n                n++;\n                if (n >= count)\n                    break;\n            }\n        }\n        list_for_each(el, &waiter_list) {\n            waiter = list_entry(el, JSAtomicsWaiter, link);\n            pthread_cond_signal(&waiter->cond);\n        }\n        pthread_mutex_unlock(&js_atomics_mutex);\n    }\n    return JS_NewInt32(ctx, n);\n}\n\nstatic const JSCFunctionListEntry js_atomics_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"add\", 3, js_atomics_op, ATOMICS_OP_ADD ),\n    JS_CFUNC_MAGIC_DEF(\"and\", 3, js_atomics_op, ATOMICS_OP_AND ),\n    JS_CFUNC_MAGIC_DEF(\"or\", 3, js_atomics_op, ATOMICS_OP_OR ),\n    JS_CFUNC_MAGIC_DEF(\"sub\", 3, js_atomics_op, ATOMICS_OP_SUB ),\n    JS_CFUNC_MAGIC_DEF(\"xor\", 3, js_atomics_op, ATOMICS_OP_XOR ),\n    JS_CFUNC_MAGIC_DEF(\"exchange\", 3, js_atomics_op, ATOMICS_OP_EXCHANGE ),\n    JS_CFUNC_MAGIC_DEF(\"compareExchange\", 4, js_atomics_op, ATOMICS_OP_COMPARE_EXCHANGE ),\n    JS_CFUNC_MAGIC_DEF(\"load\", 2, js_atomics_op, ATOMICS_OP_LOAD ),\n    JS_CFUNC_DEF(\"store\", 3, js_atomics_store ),\n    JS_CFUNC_DEF(\"isLockFree\", 1, js_atomics_isLockFree ),\n    JS_CFUNC_DEF(\"wait\", 4, js_atomics_wait ),\n    JS_CFUNC_DEF(\"notify\", 3, js_atomics_notify ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Atomics\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_atomics_obj[] = {\n    JS_OBJECT_DEF(\"Atomics\", js_atomics_funcs, countof(js_atomics_funcs), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),\n};\n\nvoid JS_AddIntrinsicAtomics(JSContext *ctx)\n{\n    /* add Atomics as autoinit object */\n    JS_SetPropertyFunctionList(ctx, ctx->global_obj, js_atomics_obj, countof(js_atomics_obj));\n}\n\n#endif /* CONFIG_ATOMICS */\n\nvoid JS_AddIntrinsicTypedArrays(JSContext *ctx)\n{\n    JSValue typed_array_base_proto, typed_array_base_func;\n    JSValueConst array_buffer_func, shared_array_buffer_func;\n    int i;\n\n    ctx->class_proto[JS_CLASS_ARRAY_BUFFER] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ARRAY_BUFFER],\n                               js_array_buffer_proto_funcs,\n                               countof(js_array_buffer_proto_funcs));\n\n    array_buffer_func = JS_NewGlobalCConstructorOnly(ctx, \"ArrayBuffer\",\n                                                 js_array_buffer_constructor, 1,\n                                                 ctx->class_proto[JS_CLASS_ARRAY_BUFFER]);\n    JS_SetPropertyFunctionList(ctx, array_buffer_func,\n                               js_array_buffer_funcs,\n                               countof(js_array_buffer_funcs));\n\n    ctx->class_proto[JS_CLASS_SHARED_ARRAY_BUFFER] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_SHARED_ARRAY_BUFFER],\n                               js_shared_array_buffer_proto_funcs,\n                               countof(js_shared_array_buffer_proto_funcs));\n\n    shared_array_buffer_func = JS_NewGlobalCConstructorOnly(ctx, \"SharedArrayBuffer\",\n                                                 js_shared_array_buffer_constructor, 1,\n                                                 ctx->class_proto[JS_CLASS_SHARED_ARRAY_BUFFER]);\n    JS_SetPropertyFunctionList(ctx, shared_array_buffer_func,\n                               js_shared_array_buffer_funcs,\n                               countof(js_shared_array_buffer_funcs));\n\n    typed_array_base_proto = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, typed_array_base_proto,\n                               js_typed_array_base_proto_funcs,\n                               countof(js_typed_array_base_proto_funcs));\n\n    /* TypedArray.prototype.toString must be the same object as Array.prototype.toString */\n    JSValue obj = JS_GetProperty(ctx, ctx->class_proto[JS_CLASS_ARRAY], JS_ATOM_toString);\n    /* XXX: should use alias method in JSCFunctionListEntry */ //@@@\n    JS_DefinePropertyValue(ctx, typed_array_base_proto, JS_ATOM_toString, obj,\n                           JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n\n    typed_array_base_func = JS_NewCFunction(ctx, js_typed_array_base_constructor,\n                                            \"TypedArray\", 0);\n    JS_SetPropertyFunctionList(ctx, typed_array_base_func,\n                               js_typed_array_base_funcs,\n                               countof(js_typed_array_base_funcs));\n    JS_SetConstructor(ctx, typed_array_base_func, typed_array_base_proto);\n\n    for(i = JS_CLASS_UINT8C_ARRAY; i < JS_CLASS_UINT8C_ARRAY + JS_TYPED_ARRAY_COUNT; i++) {\n        JSValue func_obj;\n        char buf[ATOM_GET_STR_BUF_SIZE];\n        const char *name;\n\n        ctx->class_proto[i] = JS_NewObjectProto(ctx, typed_array_base_proto);\n        JS_DefinePropertyValueStr(ctx, ctx->class_proto[i],\n                                  \"BYTES_PER_ELEMENT\",\n                                  JS_NewInt32(ctx, 1 << typed_array_size_log2(i)),\n                                  0);\n        name = JS_AtomGetStr(ctx, buf, sizeof(buf),\n                             JS_ATOM_Uint8ClampedArray + i - JS_CLASS_UINT8C_ARRAY);\n        func_obj = JS_NewCFunction3(ctx, (JSCFunction *)js_typed_array_constructor,\n                                    name, 3, JS_CFUNC_constructor_magic, i,\n                                    typed_array_base_func);\n        JS_NewGlobalCConstructor2(ctx, func_obj, name, ctx->class_proto[i]);\n        JS_DefinePropertyValueStr(ctx, func_obj,\n                                  \"BYTES_PER_ELEMENT\",\n                                  JS_NewInt32(ctx, 1 << typed_array_size_log2(i)),\n                                  0);\n    }\n    JS_FreeValue(ctx, typed_array_base_proto);\n    JS_FreeValue(ctx, typed_array_base_func);\n\n    /* DataView */\n    ctx->class_proto[JS_CLASS_DATAVIEW] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_DATAVIEW],\n                               js_dataview_proto_funcs,\n                               countof(js_dataview_proto_funcs));\n    JS_NewGlobalCConstructorOnly(ctx, \"DataView\",\n                                 js_dataview_constructor, 1,\n                                 ctx->class_proto[JS_CLASS_DATAVIEW]);\n    /* Atomics */\n#ifdef CONFIG_ATOMICS\n    JS_AddIntrinsicAtomics(ctx);\n#endif\n}\n\nstatic JSValue JSB_ThrowError2(JSContext *ctx, JSErrorEnum error_num,\n                              const char *buf, size_t buf_len, BOOL add_backtrace)\n{\n    JSValue obj, ret;\n\n    obj = JS_NewObjectProtoClass(ctx, ctx->native_error_proto[error_num],\n                                 JS_CLASS_ERROR);\n    if (unlikely(JS_IsException(obj))) {\n        /* out of memory: throw JS_NULL to avoid recursing */\n        obj = JS_NULL;\n    } else {\n        JS_DefinePropertyValue(ctx, obj, JS_ATOM_message,\n                               JS_NewStringLen(ctx, buf, buf_len),\n                               JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    }\n    if (add_backtrace) {\n        build_backtrace(ctx, obj, NULL, 0, 0);\n    }\n    ret = JS_Throw(ctx, obj);\n    return ret;\n}\n\nJSValue JSB_ThrowError(JSContext *ctx, const char *buf, size_t buf_len)\n{\n    JSRuntime *rt = ctx->rt;\n    JSStackFrame *sf;\n    BOOL add_backtrace;\n\n    /* the backtrace is added later if called from a bytecode function */\n    sf = rt->current_stack_frame;\n    add_backtrace = !rt->in_out_of_memory &&\n        (!sf || (JS_GetFunctionBytecode(sf->cur_func) == NULL));\n    return JSB_ThrowError2(ctx, JS_INTERNAL_ERROR, buf, buf_len, add_backtrace);\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/quickjs.h",
    "content": "/*\n * QuickJS Javascript Engine\n *\n * Copyright (c) 2017-2021 Fabrice Bellard\n * Copyright (c) 2017-2021 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#ifndef QUICKJS_H\n#define QUICKJS_H\n\n#include <stdio.h>\n#include <stdint.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if defined(__GNUC__) || defined(__clang__)\n#define js_likely(x)          __builtin_expect(!!(x), 1)\n#define js_unlikely(x)        __builtin_expect(!!(x), 0)\n#define js_force_inline       inline __attribute__((always_inline))\n#define __js_printf_like(f, a)   __attribute__((format(printf, f, a)))\n#else\n#define js_likely(x)     (x)\n#define js_unlikely(x)   (x)\n#define js_force_inline  inline\n#define __js_printf_like(a, b)\n#endif\n\n#define JS_BOOL int\n\ntypedef struct JSRuntime JSRuntime;\ntypedef struct JSContext JSContext;\ntypedef struct JSObject JSObject;\ntypedef struct JSClass JSClass;\ntypedef uint32_t JSClassID;\ntypedef uint32_t JSAtom;\n\n#if INTPTR_MAX >= INT64_MAX\n#define JS_PTR64\n#define JS_PTR64_DEF(a) a\n#else\n#define JS_PTR64_DEF(a)\n#endif\n\n#ifndef JS_PTR64\n// #define JS_NAN_BOXING\n#endif\n\nenum {\n    /* all tags with a reference count are negative */\n    JS_TAG_FIRST       = -11, /* first negative tag */\n    JS_TAG_BIG_DECIMAL = -11,\n    JS_TAG_BIG_INT     = -10,\n    JS_TAG_BIG_FLOAT   = -9,\n    JS_TAG_SYMBOL      = -8,\n    JS_TAG_STRING      = -7,\n    JS_TAG_MODULE      = -3, /* used internally */\n    JS_TAG_FUNCTION_BYTECODE = -2, /* used internally */\n    JS_TAG_OBJECT      = -1,\n\n    JS_TAG_INT         = 0,\n    JS_TAG_BOOL        = 1,\n    JS_TAG_NULL        = 2,\n    JS_TAG_UNDEFINED   = 3,\n    JS_TAG_UNINITIALIZED = 4,\n    JS_TAG_CATCH_OFFSET = 5,\n    JS_TAG_EXCEPTION   = 6,\n    JS_TAG_FLOAT64     = 7,\n    /* any larger tag is FLOAT64 if JS_NAN_BOXING */\n};\n\ntypedef struct JSRefCountHeader {\n    int ref_count;\n} JSRefCountHeader;\n\n#define JS_FLOAT64_NAN NAN\n\n#ifdef CONFIG_CHECK_JSVALUE\n/* JSValue consistency : it is not possible to run the code in this\n   mode, but it is useful to detect simple reference counting\n   errors. It would be interesting to modify a static C analyzer to\n   handle specific annotations (clang has such annotations but only\n   for objective C) */\ntypedef struct __JSValue *JSValue;\ntypedef const struct __JSValue *JSValueConst;\n\n#define JS_VALUE_GET_TAG(v) (int)((uintptr_t)(v) & 0xf)\n/* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */\n#define JS_VALUE_GET_NORM_TAG(v) JS_VALUE_GET_TAG(v)\n#define JS_VALUE_GET_INT(v) (int)((intptr_t)(v) >> 4)\n#define JS_VALUE_GET_BOOL(v) JS_VALUE_GET_INT(v)\n#define JS_VALUE_GET_FLOAT64(v) (double)JS_VALUE_GET_INT(v)\n#define JS_VALUE_GET_PTR(v) (void *)((intptr_t)(v) & ~0xf)\n\n#define JS_MKVAL(tag, val) (JSValue)(intptr_t)(((val) << 4) | (tag))\n#define JS_MKPTR(tag, p) (JSValue)((intptr_t)(p) | (tag))\n\n#define JS_TAG_IS_FLOAT64(tag) ((unsigned)(tag) == JS_TAG_FLOAT64)\n\n#define JS_NAN JS_MKVAL(JS_TAG_FLOAT64, 1)\n\nstatic inline JSValue __JS_NewFloat64(JSContext *ctx, double d)\n{\n    return JS_MKVAL(JS_TAG_FLOAT64, (int)d);\n}\n\nstatic inline JS_BOOL JS_VALUE_IS_NAN(JSValue v)\n{\n    return 0;\n}\n    \n#elif defined(JS_NAN_BOXING)\n\ntypedef uint64_t JSValue;\n\n#define JSValueConst JSValue\n\n#define JS_VALUE_GET_TAG(v) (int)((v) >> 32)\n#define JS_VALUE_GET_INT(v) (int)(v)\n#define JS_VALUE_GET_BOOL(v) (int)(v)\n#define JS_VALUE_GET_PTR(v) (void *)(intptr_t)(v)\n\n#define JS_MKVAL(tag, val) (((uint64_t)(tag) << 32) | (uint32_t)(val))\n#define JS_MKPTR(tag, ptr) (((uint64_t)(tag) << 32) | (uintptr_t)(ptr))\n\n#define JS_FLOAT64_TAG_ADDEND (0x7ff80000 - JS_TAG_FIRST + 1) /* quiet NaN encoding */\n\nstatic inline double JS_VALUE_GET_FLOAT64(JSValue v)\n{\n    union {\n        JSValue v;\n        double d;\n    } u;\n    u.v = v;\n    u.v += (uint64_t)JS_FLOAT64_TAG_ADDEND << 32;\n    return u.d;\n}\n\n#define JS_NAN (0x7ff8000000000000 - ((uint64_t)JS_FLOAT64_TAG_ADDEND << 32))\n\nstatic inline JSValue __JS_NewFloat64(JSContext *ctx, double d)\n{\n    union {\n        double d;\n        uint64_t u64;\n    } u;\n    JSValue v;\n    u.d = d;\n    /* normalize NaN */\n    if (js_unlikely((u.u64 & 0x7fffffffffffffff) > 0x7ff0000000000000))\n        v = JS_NAN;\n    else\n        v = u.u64 - ((uint64_t)JS_FLOAT64_TAG_ADDEND << 32);\n    return v;\n}\n\n#define JS_TAG_IS_FLOAT64(tag) ((unsigned)((tag) - JS_TAG_FIRST) >= (JS_TAG_FLOAT64 - JS_TAG_FIRST))\n\n/* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */\nstatic inline int JS_VALUE_GET_NORM_TAG(JSValue v)\n{\n    uint32_t tag;\n    tag = JS_VALUE_GET_TAG(v);\n    if (JS_TAG_IS_FLOAT64(tag))\n        return JS_TAG_FLOAT64;\n    else\n        return tag;\n}\n\nstatic inline JS_BOOL JS_VALUE_IS_NAN(JSValue v)\n{\n    uint32_t tag;\n    tag = JS_VALUE_GET_TAG(v);\n    return tag == (JS_NAN >> 32);\n}\n    \n#else /* !JS_NAN_BOXING */\n\ntypedef union JSValueUnion {\n    int32_t int32;\n    double float64;\n    void *ptr;\n} JSValueUnion;\n\ntypedef struct JSValue {\n    JSValueUnion u;\n    int64_t tag;\n} JSValue;\n\n#define JSValueConst JSValue\n\n#define JS_VALUE_GET_TAG(v) ((int32_t)(v).tag)\n/* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */\n#define JS_VALUE_GET_NORM_TAG(v) JS_VALUE_GET_TAG(v)\n#define JS_VALUE_GET_INT(v) ((v).u.int32)\n#define JS_VALUE_GET_BOOL(v) ((v).u.int32)\n#define JS_VALUE_GET_FLOAT64(v) ((v).u.float64)\n#define JS_VALUE_GET_PTR(v) ((v).u.ptr)\n\n#define JS_MKVAL(tag, val) (JSValue){ (JSValueUnion){ .int32 = val }, tag }\n#define JS_MKPTR(tag, p) (JSValue){ (JSValueUnion){ .ptr = p }, tag }\n\n#define JS_TAG_IS_FLOAT64(tag) ((unsigned)(tag) == JS_TAG_FLOAT64)\n\n#define JS_NAN (JSValue){ .u.float64 = JS_FLOAT64_NAN, JS_TAG_FLOAT64 }\n\nstatic inline JSValue __JS_NewFloat64(JSContext *ctx, double d)\n{\n    JSValue v;\n    v.tag = JS_TAG_FLOAT64;\n    v.u.float64 = d;\n    return v;\n}\n\nstatic inline JS_BOOL JS_VALUE_IS_NAN(JSValue v)\n{\n    union {\n        double d;\n        uint64_t u64;\n    } u;\n    if (v.tag != JS_TAG_FLOAT64)\n        return 0;\n    u.d = v.u.float64;\n    return (u.u64 & 0x7fffffffffffffff) > 0x7ff0000000000000;\n}\n\n#endif /* !JS_NAN_BOXING */\n\n#define JS_VALUE_IS_BOTH_INT(v1, v2) ((JS_VALUE_GET_TAG(v1) | JS_VALUE_GET_TAG(v2)) == 0)\n#define JS_VALUE_IS_BOTH_FLOAT(v1, v2) (JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(v1)) && JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(v2)))\n\n#define JS_VALUE_GET_OBJ(v) ((JSObject *)JS_VALUE_GET_PTR(v))\n#define JS_VALUE_GET_STRING(v) ((JSString *)JS_VALUE_GET_PTR(v))\n#define JS_VALUE_HAS_REF_COUNT(v) ((unsigned)JS_VALUE_GET_TAG(v) >= (unsigned)JS_TAG_FIRST)\n\n/* special values */\n#define JS_NULL      JS_MKVAL(JS_TAG_NULL, 0)\n#define JS_UNDEFINED JS_MKVAL(JS_TAG_UNDEFINED, 0)\n#define JS_FALSE     JS_MKVAL(JS_TAG_BOOL, 0)\n#define JS_TRUE      JS_MKVAL(JS_TAG_BOOL, 1)\n#define JS_EXCEPTION JS_MKVAL(JS_TAG_EXCEPTION, 0)\n#define JS_UNINITIALIZED JS_MKVAL(JS_TAG_UNINITIALIZED, 0)\n\n/* flags for object properties */\n#define JS_PROP_CONFIGURABLE  (1 << 0)\n#define JS_PROP_WRITABLE      (1 << 1)\n#define JS_PROP_ENUMERABLE    (1 << 2)\n#define JS_PROP_C_W_E         (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE | JS_PROP_ENUMERABLE)\n#define JS_PROP_LENGTH        (1 << 3) /* used internally in Arrays */\n#define JS_PROP_TMASK         (3 << 4) /* mask for NORMAL, GETSET, VARREF, AUTOINIT */\n#define JS_PROP_NORMAL         (0 << 4)\n#define JS_PROP_GETSET         (1 << 4)\n#define JS_PROP_VARREF         (2 << 4) /* used internally */\n#define JS_PROP_AUTOINIT       (3 << 4) /* used internally */\n\n/* flags for JS_DefineProperty */\n#define JS_PROP_HAS_SHIFT        8\n#define JS_PROP_HAS_CONFIGURABLE (1 << 8)\n#define JS_PROP_HAS_WRITABLE     (1 << 9)\n#define JS_PROP_HAS_ENUMERABLE   (1 << 10)\n#define JS_PROP_HAS_GET          (1 << 11)\n#define JS_PROP_HAS_SET          (1 << 12)\n#define JS_PROP_HAS_VALUE        (1 << 13)\n\n/* throw an exception if false would be returned\n   (JS_DefineProperty/JS_SetProperty) */\n#define JS_PROP_THROW            (1 << 14)\n/* throw an exception if false would be returned in strict mode\n   (JS_SetProperty) */\n#define JS_PROP_THROW_STRICT     (1 << 15)\n\n#define JS_PROP_NO_ADD           (1 << 16) /* internal use */\n#define JS_PROP_NO_EXOTIC        (1 << 17) /* internal use */\n\n#define JS_DEFAULT_STACK_SIZE (256 * 1024)\n\n/* JS_Eval() flags */\n#define JS_EVAL_TYPE_GLOBAL   (0 << 0) /* global code (default) */\n#define JS_EVAL_TYPE_MODULE   (1 << 0) /* module code */\n#define JS_EVAL_TYPE_DIRECT   (2 << 0) /* direct call (internal use) */\n#define JS_EVAL_TYPE_INDIRECT (3 << 0) /* indirect call (internal use) */\n#define JS_EVAL_TYPE_MASK     (3 << 0)\n\n#define JS_EVAL_FLAG_STRICT   (1 << 3) /* force 'strict' mode */\n#define JS_EVAL_FLAG_STRIP    (1 << 4) /* force 'strip' mode */\n/* compile but do not run. The result is an object with a\n   JS_TAG_FUNCTION_BYTECODE or JS_TAG_MODULE tag. It can be executed\n   with JS_EvalFunction(). */\n#define JS_EVAL_FLAG_COMPILE_ONLY (1 << 5)\n/* don't include the stack frames before this eval in the Error() backtraces */\n#define JS_EVAL_FLAG_BACKTRACE_BARRIER (1 << 6)\n\ntypedef JSValue JSCFunction(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv);\ntypedef JSValue JSCFunctionMagic(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic);\ntypedef JSValue JSCFunctionData(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, JSValue *func_data);\n\ntypedef struct JSMallocState {\n    size_t malloc_count;\n    size_t malloc_size;\n    size_t malloc_limit;\n    void *opaque; /* user opaque */\n} JSMallocState;\n\ntypedef struct JSMallocFunctions {\n    void *(*js_malloc)(JSMallocState *s, size_t size);\n    void (*js_free)(JSMallocState *s, void *ptr);\n    void *(*js_realloc)(JSMallocState *s, void *ptr, size_t size);\n    size_t (*js_malloc_usable_size)(const void *ptr);\n} JSMallocFunctions;\n\ntypedef struct JSGCObjectHeader JSGCObjectHeader;\n\nJSRuntime *JS_NewRuntime(void);\n/* info lifetime must exceed that of rt */\nvoid JS_SetRuntimeInfo(JSRuntime *rt, const char *info);\nvoid JS_SetMemoryLimit(JSRuntime *rt, size_t limit);\nvoid JS_SetGCThreshold(JSRuntime *rt, size_t gc_threshold);\n/* use 0 to disable maximum stack size check */\nvoid JS_SetMaxStackSize(JSRuntime *rt, size_t stack_size);\n/* should be called when changing thread to update the stack top value\n   used to check stack overflow. */\nvoid JS_UpdateStackTop(JSRuntime *rt);\nJSRuntime *JS_NewRuntime2(const JSMallocFunctions *mf, void *opaque);\nint JS_FreeRuntime(JSRuntime *rt);\nvoid *JS_GetRuntimeOpaque(JSRuntime *rt);\nvoid JS_SetRuntimeOpaque(JSRuntime *rt, void *opaque);\ntypedef void JS_MarkFunc(JSRuntime *rt, JSGCObjectHeader *gp);\nvoid JS_MarkValue(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func);\nvoid JS_RunGC(JSRuntime *rt);\nJS_BOOL JS_IsLiveObject(JSRuntime *rt, JSValueConst obj);\n\nJSContext *JS_NewContext(JSRuntime *rt);\nvoid JS_FreeContext(JSContext *s);\nJSContext *JS_DupContext(JSContext *ctx);\nvoid *JS_GetContextOpaque(JSContext *ctx);\nvoid JS_SetContextOpaque(JSContext *ctx, void *opaque);\nJSRuntime *JS_GetRuntime(JSContext *ctx);\nvoid JS_SetClassProto(JSContext *ctx, JSClassID class_id, JSValue obj);\nJSValue JS_GetClassProto(JSContext *ctx, JSClassID class_id);\n\n/* the following functions are used to select the intrinsic object to\n   save memory */\nJSContext *JS_NewContextRaw(JSRuntime *rt);\nvoid JS_AddIntrinsicBaseObjects(JSContext *ctx);\nvoid JS_AddIntrinsicDate(JSContext *ctx);\nvoid JS_AddIntrinsicEval(JSContext *ctx);\nvoid JS_AddIntrinsicStringNormalize(JSContext *ctx);\nvoid JS_AddIntrinsicRegExpCompiler(JSContext *ctx);\nvoid JS_AddIntrinsicRegExp(JSContext *ctx);\nvoid JS_AddIntrinsicJSON(JSContext *ctx);\nvoid JS_AddIntrinsicProxy(JSContext *ctx);\nvoid JS_AddIntrinsicMapSet(JSContext *ctx);\nvoid JS_AddIntrinsicTypedArrays(JSContext *ctx);\nvoid JS_AddIntrinsicPromise(JSContext *ctx);\nvoid JS_AddIntrinsicBigInt(JSContext *ctx);\nvoid JS_AddIntrinsicBigFloat(JSContext *ctx);\nvoid JS_AddIntrinsicBigDecimal(JSContext *ctx);\n/* enable operator overloading */\nvoid JS_AddIntrinsicOperators(JSContext *ctx);\n/* enable \"use math\" */\nvoid JS_EnableBignumExt(JSContext *ctx, JS_BOOL enable);\n\nJSValue js_string_codePointRange(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv);\n\nvoid *js_malloc_rt(JSRuntime *rt, size_t size);\nvoid js_free_rt(JSRuntime *rt, void *ptr);\nvoid *js_realloc_rt(JSRuntime *rt, void *ptr, size_t size);\nsize_t js_malloc_usable_size_rt(JSRuntime *rt, const void *ptr);\nvoid *js_mallocz_rt(JSRuntime *rt, size_t size);\n\nvoid *js_malloc(JSContext *ctx, size_t size);\nvoid js_free(JSContext *ctx, void *ptr);\nvoid *js_realloc(JSContext *ctx, void *ptr, size_t size);\nsize_t js_malloc_usable_size(JSContext *ctx, const void *ptr);\nvoid *js_realloc2(JSContext *ctx, void *ptr, size_t size, size_t *pslack);\nvoid *js_mallocz(JSContext *ctx, size_t size);\nchar *js_strdup(JSContext *ctx, const char *str);\nchar *js_strndup(JSContext *ctx, const char *s, size_t n);\n\ntypedef struct JSMemoryUsage {\n    int64_t malloc_size, malloc_limit, memory_used_size;\n    int64_t malloc_count;\n    int64_t memory_used_count;\n    int64_t atom_count, atom_size;\n    int64_t str_count, str_size;\n    int64_t obj_count, obj_size;\n    int64_t prop_count, prop_size;\n    int64_t shape_count, shape_size;\n    int64_t js_func_count, js_func_size, js_func_code_size;\n    int64_t js_func_pc2line_count, js_func_pc2line_size;\n    int64_t c_func_count, array_count;\n    int64_t fast_array_count, fast_array_elements;\n    int64_t binary_object_count, binary_object_size;\n} JSMemoryUsage;\n\nvoid JS_ComputeMemoryUsage(JSRuntime *rt, JSMemoryUsage *s);\nvoid JS_DumpMemoryUsage(FILE *fp, const JSMemoryUsage *s, JSRuntime *rt);\n\n/* atom support */\n#define JS_ATOM_NULL 0\n\nJSAtom JS_NewAtomLen(JSContext *ctx, const char *str, size_t len);\nJSAtom JS_NewAtom(JSContext *ctx, const char *str);\nJSAtom JS_NewAtomUInt32(JSContext *ctx, uint32_t n);\nJSAtom JS_DupAtom(JSContext *ctx, JSAtom v);\nvoid JS_FreeAtom(JSContext *ctx, JSAtom v);\nvoid JS_FreeAtomRT(JSRuntime *rt, JSAtom v);\nJSValue JS_AtomToValue(JSContext *ctx, JSAtom atom);\nJSValue JS_AtomToString(JSContext *ctx, JSAtom atom);\nconst char *JS_AtomToCString(JSContext *ctx, JSAtom atom);\nJSAtom JS_ValueToAtom(JSContext *ctx, JSValueConst val);\n\n/* object class support */\n\ntypedef struct JSPropertyEnum {\n    JS_BOOL is_enumerable;\n    JSAtom atom;\n} JSPropertyEnum;\n\ntypedef struct JSPropertyDescriptor {\n    int flags;\n    JSValue value;\n    JSValue getter;\n    JSValue setter;\n} JSPropertyDescriptor;\n\ntypedef struct JSClassExoticMethods {\n    /* Return -1 if exception (can only happen in case of Proxy object),\n       FALSE if the property does not exists, TRUE if it exists. If 1 is\n       returned, the property descriptor 'desc' is filled if != NULL. */\n    int (*get_own_property)(JSContext *ctx, JSPropertyDescriptor *desc,\n                             JSValueConst obj, JSAtom prop);\n    /* '*ptab' should hold the '*plen' property keys. Return 0 if OK,\n       -1 if exception. The 'is_enumerable' field is ignored.\n    */\n    int (*get_own_property_names)(JSContext *ctx, JSPropertyEnum **ptab,\n                                  uint32_t *plen,\n                                  JSValueConst obj);\n    /* return < 0 if exception, or TRUE/FALSE */\n    int (*delete_property)(JSContext *ctx, JSValueConst obj, JSAtom prop);\n    /* return < 0 if exception or TRUE/FALSE */\n    int (*define_own_property)(JSContext *ctx, JSValueConst this_obj,\n                               JSAtom prop, JSValueConst val,\n                               JSValueConst getter, JSValueConst setter,\n                               int flags);\n    /* The following methods can be emulated with the previous ones,\n       so they are usually not needed */\n    /* return < 0 if exception or TRUE/FALSE */\n    int (*has_property)(JSContext *ctx, JSValueConst obj, JSAtom atom);\n    JSValue (*get_property)(JSContext *ctx, JSValueConst obj, JSAtom atom,\n                            JSValueConst receiver);\n    /* return < 0 if exception or TRUE/FALSE */\n    int (*set_property)(JSContext *ctx, JSValueConst obj, JSAtom atom,\n                        JSValueConst value, JSValueConst receiver, int flags);\n} JSClassExoticMethods;\n\ntypedef void JSClassFinalizer(JSRuntime *rt, JSValue val);\ntypedef void JSClassGCMark(JSRuntime *rt, JSValueConst val,\n                           JS_MarkFunc *mark_func);\n#define JS_CALL_FLAG_CONSTRUCTOR (1 << 0)\ntypedef JSValue JSClassCall(JSContext *ctx, JSValueConst func_obj,\n                            JSValueConst this_val, int argc, JSValueConst *argv,\n                            int flags);\n\ntypedef struct JSClassDef {\n    const char *class_name;\n    JSClassFinalizer *finalizer;\n    JSClassGCMark *gc_mark;\n    /* if call != NULL, the object is a function. If (flags &\n       JS_CALL_FLAG_CONSTRUCTOR) != 0, the function is called as a\n       constructor. In this case, 'this_val' is new.target. A\n       constructor call only happens if the object constructor bit is\n       set (see JS_SetConstructorBit()). */\n    JSClassCall *call;\n    /* XXX: suppress this indirection ? It is here only to save memory\n       because only a few classes need these methods */\n    JSClassExoticMethods *exotic;\n} JSClassDef;\n\nJSClassID JS_NewClassID(JSClassID *pclass_id);\nint JS_NewClass(JSRuntime *rt, JSClassID class_id, const JSClassDef *class_def);\nint JS_IsRegisteredClass(JSRuntime *rt, JSClassID class_id);\n\n/* value handling */\n\nstatic js_force_inline JSValue JS_NewBool(JSContext *ctx, JS_BOOL val)\n{\n    return JS_MKVAL(JS_TAG_BOOL, (val != 0));\n}\n\nstatic js_force_inline JSValue JS_NewInt32(JSContext *ctx, int32_t val)\n{\n    return JS_MKVAL(JS_TAG_INT, val);\n}\n\nstatic js_force_inline JSValue JS_NewCatchOffset(JSContext *ctx, int32_t val)\n{\n    return JS_MKVAL(JS_TAG_CATCH_OFFSET, val);\n}\n\nstatic js_force_inline JSValue JS_NewInt64(JSContext *ctx, int64_t val)\n{\n    JSValue v;\n    if (val == (int32_t)val) {\n        v = JS_NewInt32(ctx, val);\n    } else {\n        v = __JS_NewFloat64(ctx, val);\n    }\n    return v;\n}\n\nstatic js_force_inline JSValue JS_NewUint32(JSContext *ctx, uint32_t val)\n{\n    JSValue v;\n    if (val <= 0x7fffffff) {\n        v = JS_NewInt32(ctx, val);\n    } else {\n        v = __JS_NewFloat64(ctx, val);\n    }\n    return v;\n}\n\nJSValue JS_NewBigInt64(JSContext *ctx, int64_t v);\nJSValue JS_NewBigUint64(JSContext *ctx, uint64_t v);\n\nstatic js_force_inline JSValue JS_NewFloat64(JSContext *ctx, double d)\n{\n    JSValue v;\n    int32_t val;\n    union {\n        double d;\n        uint64_t u;\n    } u, t;\n    u.d = d;\n    val = (int32_t)d;\n    t.d = val;\n    /* -0 cannot be represented as integer, so we compare the bit\n        representation */\n    if (u.u == t.u) {\n        v = JS_MKVAL(JS_TAG_INT, val);\n    } else {\n        v = __JS_NewFloat64(ctx, d);\n    }\n    return v;\n}\n\nstatic inline JS_BOOL JS_IsNumber(JSValueConst v)\n{\n    int tag = JS_VALUE_GET_TAG(v);\n    return tag == JS_TAG_INT || JS_TAG_IS_FLOAT64(tag);\n}\n\nstatic inline JS_BOOL JS_IsBigInt(JSContext *ctx, JSValueConst v)\n{\n    int tag = JS_VALUE_GET_TAG(v);\n    return tag == JS_TAG_BIG_INT;\n}\n\nstatic inline JS_BOOL JS_IsBigFloat(JSValueConst v)\n{\n    int tag = JS_VALUE_GET_TAG(v);\n    return tag == JS_TAG_BIG_FLOAT;\n}\n\nstatic inline JS_BOOL JS_IsBigDecimal(JSValueConst v)\n{\n    int tag = JS_VALUE_GET_TAG(v);\n    return tag == JS_TAG_BIG_DECIMAL;\n}\n\nstatic inline JS_BOOL JS_IsBool(JSValueConst v)\n{\n    return JS_VALUE_GET_TAG(v) == JS_TAG_BOOL;\n}\n\nstatic inline JS_BOOL JS_IsNull(JSValueConst v)\n{\n    return JS_VALUE_GET_TAG(v) == JS_TAG_NULL;\n}\n\nstatic inline JS_BOOL JS_IsUndefined(JSValueConst v)\n{\n    return JS_VALUE_GET_TAG(v) == JS_TAG_UNDEFINED;\n}\n\nstatic inline JS_BOOL JS_IsException(JSValueConst v)\n{\n    return js_unlikely(JS_VALUE_GET_TAG(v) == JS_TAG_EXCEPTION);\n}\n\nstatic inline JS_BOOL JS_IsUninitialized(JSValueConst v)\n{\n    return js_unlikely(JS_VALUE_GET_TAG(v) == JS_TAG_UNINITIALIZED);\n}\n\nstatic inline JS_BOOL JS_IsString(JSValueConst v)\n{\n    return JS_VALUE_GET_TAG(v) == JS_TAG_STRING;\n}\n\nstatic inline JS_BOOL JS_IsSymbol(JSValueConst v)\n{\n    return JS_VALUE_GET_TAG(v) == JS_TAG_SYMBOL;\n}\n\nstatic inline JS_BOOL JS_IsObject(JSValueConst v)\n{\n    return JS_VALUE_GET_TAG(v) == JS_TAG_OBJECT;\n}\n\nJSValue JS_Throw(JSContext *ctx, JSValue obj);\nJSValue JS_GetException(JSContext *ctx);\nJS_BOOL JS_IsError(JSContext *ctx, JSValueConst val);\nvoid JS_ResetUncatchableError(JSContext *ctx);\nJSValue JS_NewError(JSContext *ctx);\nJSValue __js_printf_like(2, 3) JS_ThrowSyntaxError(JSContext *ctx, const char *fmt, ...);\nJSValue __js_printf_like(2, 3) JS_ThrowTypeError(JSContext *ctx, const char *fmt, ...);\nJSValue __js_printf_like(2, 3) JS_ThrowReferenceError(JSContext *ctx, const char *fmt, ...);\nJSValue __js_printf_like(2, 3) JS_ThrowRangeError(JSContext *ctx, const char *fmt, ...);\nJSValue __js_printf_like(2, 3) JS_ThrowInternalError(JSContext *ctx, const char *fmt, ...);\nJSValue JS_ThrowOutOfMemory(JSContext *ctx);\n\nvoid __JS_FreeValue(JSContext *ctx, JSValue v);\nstatic inline void JS_FreeValue(JSContext *ctx, JSValue v)\n{\n    if (JS_VALUE_HAS_REF_COUNT(v)) {\n        JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v);\n        if (--p->ref_count <= 0) {\n            __JS_FreeValue(ctx, v);\n        }\n    }\n}\nvoid __JS_FreeValueRT(JSRuntime *rt, JSValue v);\nstatic inline void JS_FreeValueRT(JSRuntime *rt, JSValue v)\n{\n    if (JS_VALUE_HAS_REF_COUNT(v)) {\n        JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v);\n        if (--p->ref_count <= 0) {\n            __JS_FreeValueRT(rt, v);\n        }\n    }\n}\n\nstatic inline JSValue JS_DupValue(JSContext *ctx, JSValueConst v)\n{\n    if (JS_VALUE_HAS_REF_COUNT(v)) {\n        JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v);\n        p->ref_count++;\n    }\n    return (JSValue)v;\n}\n\nstatic inline JSValue JS_DupValueRT(JSRuntime *rt, JSValueConst v)\n{\n    if (JS_VALUE_HAS_REF_COUNT(v)) {\n        JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v);\n        p->ref_count++;\n    }\n    return (JSValue)v;\n}\n\nint JS_ToBool(JSContext *ctx, JSValueConst val); /* return -1 for JS_EXCEPTION */\nint JS_ToInt32(JSContext *ctx, int32_t *pres, JSValueConst val);\nstatic inline int JS_ToUint32(JSContext *ctx, uint32_t *pres, JSValueConst val)\n{\n    return JS_ToInt32(ctx, (int32_t*)pres, val);\n}\nint JS_ToInt64(JSContext *ctx, int64_t *pres, JSValueConst val);\nint JS_ToIndex(JSContext *ctx, uint64_t *plen, JSValueConst val);\nint JS_ToFloat64(JSContext *ctx, double *pres, JSValueConst val);\n/* return an exception if 'val' is a Number */\nint JS_ToBigInt64(JSContext *ctx, int64_t *pres, JSValueConst val);\n/* same as JS_ToInt64() but allow BigInt */\nint JS_ToInt64Ext(JSContext *ctx, int64_t *pres, JSValueConst val);\n\nJSValue JS_NewStringLen(JSContext *ctx, const char *str1, size_t len1);\nJSValue JS_NewString(JSContext *ctx, const char *str);\nJSValue JS_NewAtomString(JSContext *ctx, const char *str);\nJSValue JS_ToString(JSContext *ctx, JSValueConst val);\nJSValue JS_ToPropertyKey(JSContext *ctx, JSValueConst val);\nconst char *JS_ToCStringLen2(JSContext *ctx, size_t *plen, JSValueConst val1, JS_BOOL cesu8);\nstatic inline const char *JS_ToCStringLen(JSContext *ctx, size_t *plen, JSValueConst val1)\n{\n    return JS_ToCStringLen2(ctx, plen, val1, 0);\n}\nstatic inline const char *JS_ToCString(JSContext *ctx, JSValueConst val1)\n{\n    return JS_ToCStringLen2(ctx, NULL, val1, 0);\n}\nvoid JS_FreeCString(JSContext *ctx, const char *ptr);\n\nJSValue JS_NewObjectProtoClass(JSContext *ctx, JSValueConst proto, JSClassID class_id);\nJSValue JS_NewObjectClass(JSContext *ctx, int class_id);\nJSValue JS_NewObjectProto(JSContext *ctx, JSValueConst proto);\nJSValue JS_NewObject(JSContext *ctx);\n\nJS_BOOL JS_IsFunction(JSContext* ctx, JSValueConst val);\nJS_BOOL JS_IsConstructor(JSContext* ctx, JSValueConst val);\nJS_BOOL JS_SetConstructorBit(JSContext *ctx, JSValueConst func_obj, JS_BOOL val);\n\nJSValue JS_NewArray(JSContext *ctx);\nint JS_IsArray(JSContext *ctx, JSValueConst val);\n\nJSValue JS_GetPropertyInternal(JSContext *ctx, JSValueConst obj,\n                               JSAtom prop, JSValueConst receiver,\n                               JS_BOOL throw_ref_error);\nstatic js_force_inline JSValue JS_GetProperty(JSContext *ctx, JSValueConst this_obj,\n                                              JSAtom prop)\n{\n    return JS_GetPropertyInternal(ctx, this_obj, prop, this_obj, 0);\n}\nJSValue JS_GetPropertyStr(JSContext *ctx, JSValueConst this_obj,\n                          const char *prop);\nJSValue JS_GetPropertyUint32(JSContext *ctx, JSValueConst this_obj,\n                             uint32_t idx);\n\nint JS_SetPropertyInternal(JSContext *ctx, JSValueConst this_obj,\n                           JSAtom prop, JSValue val,\n                           int flags);\nstatic inline int JS_SetProperty(JSContext *ctx, JSValueConst this_obj,\n                                 JSAtom prop, JSValue val)\n{\n    return JS_SetPropertyInternal(ctx, this_obj, prop, val, JS_PROP_THROW);\n}\nint JS_SetPropertyUint32(JSContext *ctx, JSValueConst this_obj,\n                         uint32_t idx, JSValue val);\nint JS_SetPropertyInt64(JSContext *ctx, JSValueConst this_obj,\n                        int64_t idx, JSValue val);\nint JS_SetPropertyStr(JSContext *ctx, JSValueConst this_obj,\n                      const char *prop, JSValue val);\nint JS_HasProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop);\nint JS_IsExtensible(JSContext *ctx, JSValueConst obj);\nint JS_PreventExtensions(JSContext *ctx, JSValueConst obj);\nint JS_DeleteProperty(JSContext *ctx, JSValueConst obj, JSAtom prop, int flags);\nint JS_SetPrototype(JSContext *ctx, JSValueConst obj, JSValueConst proto_val);\nJSValue JS_GetPrototype(JSContext *ctx, JSValueConst val);\n\n#define JS_GPN_STRING_MASK  (1 << 0)\n#define JS_GPN_SYMBOL_MASK  (1 << 1)\n#define JS_GPN_PRIVATE_MASK (1 << 2)\n/* only include the enumerable properties */\n#define JS_GPN_ENUM_ONLY    (1 << 4)\n/* set theJSPropertyEnum.is_enumerable field */\n#define JS_GPN_SET_ENUM     (1 << 5)\n\nint JS_GetOwnPropertyNames(JSContext *ctx, JSPropertyEnum **ptab,\n                           uint32_t *plen, JSValueConst obj, int flags);\nint JS_GetOwnProperty(JSContext *ctx, JSPropertyDescriptor *desc,\n                      JSValueConst obj, JSAtom prop);\n\nJSValue JS_Call(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj,\n                int argc, JSValueConst *argv);\nJSValue JS_Invoke(JSContext *ctx, JSValueConst this_val, JSAtom atom,\n                  int argc, JSValueConst *argv);\nJSValue JS_CallConstructor(JSContext *ctx, JSValueConst func_obj,\n                           int argc, JSValueConst *argv);\nJSValue JS_CallConstructor2(JSContext *ctx, JSValueConst func_obj,\n                            JSValueConst new_target,\n                            int argc, JSValueConst *argv);\nJS_BOOL JS_DetectModule(const char *input, size_t input_len);\n/* 'input' must be zero terminated i.e. input[input_len] = '\\0'. */\nJSValue JS_Eval(JSContext *ctx, const char *input, size_t input_len,\n                const char *filename, int eval_flags);\n/* same as JS_Eval() but with an explicit 'this_obj' parameter */\nJSValue JS_EvalThis(JSContext *ctx, JSValueConst this_obj,\n                    const char *input, size_t input_len,\n                    const char *filename, int eval_flags);\nJSValue JS_GetGlobalObject(JSContext *ctx);\nint JS_IsInstanceOf(JSContext *ctx, JSValueConst val, JSValueConst obj);\nint JS_DefineProperty(JSContext *ctx, JSValueConst this_obj,\n                      JSAtom prop, JSValueConst val,\n                      JSValueConst getter, JSValueConst setter, int flags);\nint JS_DefinePropertyValue(JSContext *ctx, JSValueConst this_obj,\n                           JSAtom prop, JSValue val, int flags);\nint JS_DefinePropertyValueUint32(JSContext *ctx, JSValueConst this_obj,\n                                 uint32_t idx, JSValue val, int flags);\nint JS_DefinePropertyValueStr(JSContext *ctx, JSValueConst this_obj,\n                              const char *prop, JSValue val, int flags);\nint JS_DefinePropertyGetSet(JSContext *ctx, JSValueConst this_obj,\n                            JSAtom prop, JSValue getter, JSValue setter,\n                            int flags);\nvoid JS_SetOpaque(JSValue obj, void *opaque);\nvoid *JS_GetOpaque(JSValueConst obj, JSClassID class_id);\nvoid *JS_GetOpaque2(JSContext *ctx, JSValueConst obj, JSClassID class_id);\n\n/* 'buf' must be zero terminated i.e. buf[buf_len] = '\\0'. */\nJSValue JS_ParseJSON(JSContext *ctx, const char *buf, size_t buf_len,\n                     const char *filename);\n#define JS_PARSE_JSON_EXT (1 << 0) /* allow extended JSON */\nJSValue JS_ParseJSON2(JSContext *ctx, const char *buf, size_t buf_len,\n                      const char *filename, int flags);\nJSValue JS_JSONStringify(JSContext *ctx, JSValueConst obj,\n                         JSValueConst replacer, JSValueConst space0);\n\ntypedef void JSFreeArrayBufferDataFunc(JSRuntime *rt, void *opaque, void *ptr);\nJSValue JS_NewArrayBuffer(JSContext *ctx, uint8_t *buf, size_t len,\n                          JSFreeArrayBufferDataFunc *free_func, void *opaque,\n                          JS_BOOL is_shared);\nJSValue JS_NewArrayBufferCopy(JSContext *ctx, const uint8_t *buf, size_t len);\nvoid JS_DetachArrayBuffer(JSContext *ctx, JSValueConst obj);\nuint8_t *JS_GetArrayBuffer(JSContext *ctx, size_t *psize, JSValueConst obj);\nJSValue JS_GetTypedArrayBuffer(JSContext *ctx, JSValueConst obj,\n                               size_t *pbyte_offset,\n                               size_t *pbyte_length,\n                               size_t *pbytes_per_element);\ntypedef struct {\n    void *(*sab_alloc)(void *opaque, size_t size);\n    void (*sab_free)(void *opaque, void *ptr);\n    void (*sab_dup)(void *opaque, void *ptr);\n    void *sab_opaque;\n} JSSharedArrayBufferFunctions;\nvoid JS_SetSharedArrayBufferFunctions(JSRuntime *rt,\n                                      const JSSharedArrayBufferFunctions *sf);\n\nJSValue JS_NewPromiseCapability(JSContext *ctx, JSValue *resolving_funcs);\n\n/* is_handled = TRUE means that the rejection is handled */\ntypedef void JSHostPromiseRejectionTracker(JSContext *ctx, JSValueConst promise,\n                                           JSValueConst reason,\n                                           JS_BOOL is_handled, void *opaque);\nvoid JS_SetHostPromiseRejectionTracker(JSRuntime *rt, JSHostPromiseRejectionTracker *cb, void *opaque);\n\n/* return != 0 if the JS code needs to be interrupted */\ntypedef int JSInterruptHandler(JSRuntime *rt, void *opaque);\nvoid JS_SetInterruptHandler(JSRuntime *rt, JSInterruptHandler *cb, void *opaque);\n/* if can_block is TRUE, Atomics.wait() can be used */\nvoid JS_SetCanBlock(JSRuntime *rt, JS_BOOL can_block);\n/* set the [IsHTMLDDA] internal slot */\nvoid JS_SetIsHTMLDDA(JSContext *ctx, JSValueConst obj);\n\ntypedef struct JSModuleDef JSModuleDef;\n\n/* return the module specifier (allocated with js_malloc()) or NULL if\n   exception */\ntypedef char *JSModuleNormalizeFunc(JSContext *ctx,\n                                    const char *module_base_name,\n                                    const char *module_name, void *opaque);\ntypedef JSModuleDef *JSModuleLoaderFunc(JSContext *ctx,\n                                        const char *module_name, void *opaque);\n\n/* module_normalize = NULL is allowed and invokes the default module\n   filename normalizer */\nvoid JS_SetModuleLoaderFunc(JSRuntime *rt,\n                            JSModuleNormalizeFunc *module_normalize,\n                            JSModuleLoaderFunc *module_loader, void *opaque);\n/* return the import.meta object of a module */\nJSValue JS_GetImportMeta(JSContext *ctx, JSModuleDef *m);\nJSAtom JS_GetModuleName(JSContext *ctx, JSModuleDef *m);\n\n/* JS Job support */\n\ntypedef JSValue JSJobFunc(JSContext *ctx, int argc, JSValueConst *argv);\nint JS_EnqueueJob(JSContext *ctx, JSJobFunc *job_func, int argc, JSValueConst *argv);\n\nJS_BOOL JS_IsJobPending(JSRuntime *rt);\nint JS_ExecutePendingJob(JSRuntime *rt, JSContext **pctx);\n\n/* Object Writer/Reader (currently only used to handle precompiled code) */\n#define JS_WRITE_OBJ_BYTECODE  (1 << 0) /* allow function/module */\n#define JS_WRITE_OBJ_BSWAP     (1 << 1) /* byte swapped output */\n#define JS_WRITE_OBJ_SAB       (1 << 2) /* allow SharedArrayBuffer */\n#define JS_WRITE_OBJ_REFERENCE (1 << 3) /* allow object references to\n                                           encode arbitrary object\n                                           graph */\nuint8_t *JS_WriteObject(JSContext *ctx, size_t *psize, JSValueConst obj,\n                        int flags);\nuint8_t *JS_WriteObject2(JSContext *ctx, size_t *psize, JSValueConst obj,\n                         int flags, uint8_t ***psab_tab, size_t *psab_tab_len);\n\n#define JS_READ_OBJ_BYTECODE  (1 << 0) /* allow function/module */\n#define JS_READ_OBJ_ROM_DATA  (1 << 1) /* avoid duplicating 'buf' data */\n#define JS_READ_OBJ_SAB       (1 << 2) /* allow SharedArrayBuffer */\n#define JS_READ_OBJ_REFERENCE (1 << 3) /* allow object references */\nJSValue JS_ReadObject(JSContext *ctx, const uint8_t *buf, size_t buf_len,\n                      int flags);\n/* instantiate and evaluate a bytecode function. Only used when\n   reading a script or module with JS_ReadObject() */\nJSValue JS_EvalFunction(JSContext *ctx, JSValue fun_obj);\n/* load the dependencies of the module 'obj'. Useful when JS_ReadObject()\n   returns a module. */\nint JS_ResolveModule(JSContext *ctx, JSValueConst obj);\n\n/* only exported for os.Worker() */\nJSAtom JS_GetScriptOrModuleName(JSContext *ctx, int n_stack_levels);\n/* only exported for os.Worker() */\nJSModuleDef *JS_RunModule(JSContext *ctx, const char *basename,\n                          const char *filename);\n\n/* C function definition */\ntypedef enum JSCFunctionEnum {  /* XXX: should rename for namespace isolation */\n    JS_CFUNC_generic,\n    JS_CFUNC_generic_magic,\n    JS_CFUNC_constructor,\n    JS_CFUNC_constructor_magic,\n    JS_CFUNC_constructor_or_func,\n    JS_CFUNC_constructor_or_func_magic,\n    JS_CFUNC_f_f,\n    JS_CFUNC_f_f_f,\n    JS_CFUNC_getter,\n    JS_CFUNC_setter,\n    JS_CFUNC_getter_magic,\n    JS_CFUNC_setter_magic,\n    JS_CFUNC_iterator_next,\n} JSCFunctionEnum;\n\ntypedef union JSCFunctionType {\n    JSCFunction *generic;\n    JSValue (*generic_magic)(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic);\n    JSCFunction *constructor;\n    JSValue (*constructor_magic)(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv, int magic);\n    JSCFunction *constructor_or_func;\n    double (*f_f)(double);\n    double (*f_f_f)(double, double);\n    JSValue (*getter)(JSContext *ctx, JSValueConst this_val);\n    JSValue (*setter)(JSContext *ctx, JSValueConst this_val, JSValueConst val);\n    JSValue (*getter_magic)(JSContext *ctx, JSValueConst this_val, int magic);\n    JSValue (*setter_magic)(JSContext *ctx, JSValueConst this_val, JSValueConst val, int magic);\n    JSValue (*iterator_next)(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv, int *pdone, int magic);\n} JSCFunctionType;\n\nJSValue JS_NewCFunction2(JSContext *ctx, JSCFunction *func,\n                         const char *name,\n                         int length, JSCFunctionEnum cproto, int magic);\nJSValue JS_NewCFunctionData(JSContext *ctx, JSCFunctionData *func,\n                            int length, int magic, int data_len,\n                            JSValueConst *data);\n\nstatic inline JSValue JS_NewCFunction(JSContext *ctx, JSCFunction *func, const char *name,\n                                      int length)\n{\n    return JS_NewCFunction2(ctx, func, name, length, JS_CFUNC_generic, 0);\n}\n\nstatic inline JSValue JS_NewCFunctionMagic(JSContext *ctx, JSCFunctionMagic *func,\n                                           const char *name,\n                                           int length, JSCFunctionEnum cproto, int magic)\n{\n    return JS_NewCFunction2(ctx, (JSCFunction *)func, name, length, cproto, magic);\n}\nvoid JS_SetConstructor(JSContext *ctx, JSValueConst func_obj, \n                       JSValueConst proto);\n\n/* C property definition */\n\ntypedef struct JSCFunctionListEntry {\n    const char *name;\n    uint8_t prop_flags;\n    uint8_t def_type;\n    int16_t magic;\n    union {\n        struct {\n            uint8_t length; /* XXX: should move outside union */\n            uint8_t cproto; /* XXX: should move outside union */\n            JSCFunctionType cfunc;\n        } func;\n        struct {\n            JSCFunctionType get;\n            JSCFunctionType set;\n        } getset;\n        struct {\n            const char *name;\n            int base;\n        } alias;\n        struct {\n            const struct JSCFunctionListEntry *tab;\n            int len;\n        } prop_list;\n        const char *str;\n        int32_t i32;\n        int64_t i64;\n        double f64;\n    } u;\n} JSCFunctionListEntry;\n\n#define JS_DEF_CFUNC          0\n#define JS_DEF_CGETSET        1\n#define JS_DEF_CGETSET_MAGIC  2\n#define JS_DEF_PROP_STRING    3\n#define JS_DEF_PROP_INT32     4\n#define JS_DEF_PROP_INT64     5\n#define JS_DEF_PROP_DOUBLE    6\n#define JS_DEF_PROP_UNDEFINED 7\n#define JS_DEF_OBJECT         8\n#define JS_DEF_ALIAS          9\n\n/* Note: c++ does not like nested designators */\n#define JS_CFUNC_DEF(name, length, func1) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, 0, .u = { .func = { length, JS_CFUNC_generic, { .generic = func1 } } } }\n#define JS_CFUNC_MAGIC_DEF(name, length, func1, magic) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, magic, .u = { .func = { length, JS_CFUNC_generic_magic, { .generic_magic = func1 } } } }\n#define JS_CFUNC_SPECIAL_DEF(name, length, cproto, func1) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, 0, .u = { .func = { length, JS_CFUNC_ ## cproto, { .cproto = func1 } } } }\n#define JS_ITERATOR_NEXT_DEF(name, length, func1, magic) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, magic, .u = { .func = { length, JS_CFUNC_iterator_next, { .iterator_next = func1 } } } }\n#define JS_CGETSET_DEF(name, fgetter, fsetter) { name, JS_PROP_CONFIGURABLE, JS_DEF_CGETSET, 0, .u = { .getset = { .get = { .getter = fgetter }, .set = { .setter = fsetter } } } }\n#define JS_CGETSET_MAGIC_DEF(name, fgetter, fsetter, magic) { name, JS_PROP_CONFIGURABLE, JS_DEF_CGETSET_MAGIC, magic, .u = { .getset = { .get = { .getter_magic = fgetter }, .set = { .setter_magic = fsetter } } } }\n#define JS_PROP_STRING_DEF(name, cstr, prop_flags) { name, prop_flags, JS_DEF_PROP_STRING, 0, .u = { .str = cstr } }\n#define JS_PROP_INT32_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_INT32, 0, .u = { .i32 = val } }\n#define JS_PROP_INT64_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_INT64, 0, .u = { .i64 = val } }\n#define JS_PROP_DOUBLE_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_DOUBLE, 0, .u = { .f64 = val } }\n#define JS_PROP_UNDEFINED_DEF(name, prop_flags) { name, prop_flags, JS_DEF_PROP_UNDEFINED, 0, .u = { .i32 = 0 } }\n#define JS_OBJECT_DEF(name, tab, len, prop_flags) { name, prop_flags, JS_DEF_OBJECT, 0, .u = { .prop_list = { tab, len } } }\n#define JS_ALIAS_DEF(name, from) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_ALIAS, 0, .u = { .alias = { from, -1 } } }\n#define JS_ALIAS_BASE_DEF(name, from, base) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_ALIAS, 0, .u = { .alias = { from, base } } }\n\nvoid JS_SetPropertyFunctionList(JSContext *ctx, JSValueConst obj,\n                                const JSCFunctionListEntry *tab,\n                                int len);\n\n/* C module definition */\n\ntypedef int JSModuleInitFunc(JSContext *ctx, JSModuleDef *m);\n\nJSModuleDef *JS_NewCModule(JSContext *ctx, const char *name_str,\n                           JSModuleInitFunc *func);\n/* can only be called before the module is instantiated */\nint JS_AddModuleExport(JSContext *ctx, JSModuleDef *m, const char *name_str);\nint JS_AddModuleExportList(JSContext *ctx, JSModuleDef *m,\n                           const JSCFunctionListEntry *tab, int len);\n/* can only be called after the module is instantiated */\nint JS_SetModuleExport(JSContext *ctx, JSModuleDef *m, const char *export_name,\n                       JSValue val);\nint JS_SetModuleExportList(JSContext *ctx, JSModuleDef *m,\n                           const JSCFunctionListEntry *tab, int len);\n\n#undef js_unlikely\n#undef js_force_inline\n\n#ifdef __cplusplus\n} /* extern \"C\" { */\n#endif\n\n#endif /* QUICKJS_H */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/readme.txt",
    "content": "The main documentation is in doc/quickjs.pdf or doc/quickjs.html.\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/release.sh",
    "content": "#!/bin/sh\n# Release the QuickJS source code\n\nset -e\n\nversion=`cat VERSION`\n\nif [ \"$1\" = \"-h\" ] ; then\n    echo \"release.sh [release_list]\"\n    echo \"\"\n    echo \"release_list: extras binary win_binary quickjs\"\n    \n    exit 1\nfi\n\nrelease_list=\"extras binary win_binary quickjs\"\n\nif [ \"$1\" != \"\" ] ; then\n    release_list=\"$1\"\nfi\n\n#################################################\"\n# extras\n\nif echo $release_list | grep -w -q extras ; then\n\nd=\"quickjs-${version}\"\nname=\"quickjs-extras-${version}\"\noutdir=\"/tmp/${d}\"\n\nrm -rf $outdir\nmkdir -p $outdir $outdir/unicode $outdir/tests \n\ncp unicode/* $outdir/unicode\ncp -a tests/bench-v8 $outdir/tests\n\n( cd /tmp && tar Jcvf /tmp/${name}.tar.xz ${d} )\n\nfi\n\n#################################################\"\n# Windows binary release\n\nif echo $release_list | grep -w -q win_binary ; then\n\n# win64\n\ndlldir=/usr/x86_64-w64-mingw32/sys-root/mingw/bin\ncross_prefix=\"x86_64-w64-mingw32-\"\nd=\"quickjs-win-x86_64-${version}\"\noutdir=\"/tmp/${d}\"\n\nrm -rf $outdir\nmkdir -p $outdir\n\nmake CONFIG_WIN32=y qjs.exe\ncp qjs.exe $outdir\n${cross_prefix}strip $outdir/qjs.exe\ncp $dlldir/libwinpthread-1.dll $outdir\n\n( cd /tmp/$d && rm -f ../${d}.zip && zip -r ../${d}.zip . )\n\nmake CONFIG_WIN32=y clean\n\n# win32\n\ndlldir=/usr/i686-w64-mingw32/sys-root/mingw/bin\ncross_prefix=\"i686-w64-mingw32-\"\nd=\"quickjs-win-i686-${version}\"\noutdir=\"/tmp/${d}\"\n\nrm -rf $outdir\nmkdir -p $outdir\n\nmake clean\nmake CONFIG_WIN32=y clean\n\nmake CONFIG_WIN32=y CONFIG_M32=y qjs.exe\ncp qjs.exe $outdir\n${cross_prefix}strip $outdir/qjs.exe\ncp $dlldir/libwinpthread-1.dll $outdir\n\n( cd /tmp/$d && rm -f ../${d}.zip && zip -r ../${d}.zip . )\n\nfi\n    \n#################################################\"\n# Linux binary release\n\nif echo $release_list | grep -w -q binary ; then\n\nmake clean\nmake CONFIG_WIN32=y clean\nmake -j4 qjs run-test262\nmake -j4 CONFIG_M32=y qjs32 run-test262-32\nstrip qjs run-test262 qjs32 run-test262-32\n\nd=\"quickjs-linux-x86_64-${version}\"\noutdir=\"/tmp/${d}\"\n\nrm -rf $outdir\nmkdir -p $outdir\n\ncp qjs run-test262 $outdir\n\n( cd /tmp/$d && rm -f ../${d}.zip && zip -r ../${d}.zip . )\n\nd=\"quickjs-linux-i686-${version}\"\noutdir=\"/tmp/${d}\"\n\nrm -rf $outdir\nmkdir -p $outdir\n\ncp qjs32 $outdir/qjs\ncp run-test262-32 $outdir/run-test262\n\n( cd /tmp/$d && rm -f ../${d}.zip && zip -r ../${d}.zip . )\n\nfi\n\n#################################################\"\n# quickjs\n\nif echo $release_list | grep -w -q quickjs ; then\n\nmake build_doc\n\nd=\"quickjs-${version}\"\noutdir=\"/tmp/${d}\"\n\nrm -rf $outdir\nmkdir -p $outdir $outdir/doc $outdir/tests $outdir/examples\n\ncp Makefile VERSION TODO Changelog readme.txt LICENSE \\\n   release.sh unicode_download.sh \\\n   qjs.c qjsc.c qjscalc.js repl.js \\\n   quickjs.c quickjs.h quickjs-atom.h \\\n   quickjs-libc.c quickjs-libc.h quickjs-opcode.h \\\n   cutils.c cutils.h list.h \\\n   libregexp.c libregexp.h libregexp-opcode.h \\\n   libunicode.c libunicode.h libunicode-table.h \\\n   libbf.c libbf.h \\\n   unicode_gen.c unicode_gen_def.h \\\n   run-test262.c test262o.conf test262.conf \\\n   test262o_errors.txt test262_errors.txt \\\n   $outdir\n\ncp tests/*.js tests/*.patch tests/bjson.c $outdir/tests\n\ncp examples/*.js examples/*.c $outdir/examples\n\ncp doc/quickjs.texi doc/quickjs.pdf doc/quickjs.html \\\n   doc/jsbignum.texi doc/jsbignum.html doc/jsbignum.pdf \\\n   $outdir/doc \n\n( cd /tmp && tar Jcvf /tmp/${d}.tar.xz ${d} )\n\nfi\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/repl.js",
    "content": "/*\n * QuickJS Read Eval Print Loop\n * \n * Copyright (c) 2017-2020 Fabrice Bellard\n * Copyright (c) 2017-2020 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\"use strip\";\n\nimport * as std from \"std\";\nimport * as os from \"os\";\n\n(function(g) {\n    /* add 'os' and 'std' bindings */\n    g.os = os;\n    g.std = std;\n    \n    /* close global objects */\n    var Object = g.Object;\n    var String = g.String;\n    var Array = g.Array;\n    var Date = g.Date;\n    var Math = g.Math;\n    var isFinite = g.isFinite;\n    var parseFloat = g.parseFloat;\n\n    /* XXX: use preprocessor ? */\n    var config_numcalc = (typeof os.open === \"undefined\");\n    var has_jscalc = (typeof Fraction === \"function\");\n    var has_bignum = (typeof BigFloat === \"function\");\n    \n    var colors = {\n        none:    \"\\x1b[0m\",\n        black:   \"\\x1b[30m\",\n        red:     \"\\x1b[31m\",\n        green:   \"\\x1b[32m\",\n        yellow:  \"\\x1b[33m\",\n        blue:    \"\\x1b[34m\",\n        magenta: \"\\x1b[35m\",\n        cyan:    \"\\x1b[36m\",\n        white:   \"\\x1b[37m\",\n        gray:    \"\\x1b[30;1m\",\n        grey:    \"\\x1b[30;1m\",\n        bright_red:     \"\\x1b[31;1m\",\n        bright_green:   \"\\x1b[32;1m\",\n        bright_yellow:  \"\\x1b[33;1m\",\n        bright_blue:    \"\\x1b[34;1m\",\n        bright_magenta: \"\\x1b[35;1m\",\n        bright_cyan:    \"\\x1b[36;1m\",\n        bright_white:   \"\\x1b[37;1m\",\n    };\n\n    var styles;\n    if (config_numcalc) {\n        styles = {\n            'default':    'black',\n            'comment':    'white',\n            'string':     'green',\n            'regex':      'cyan',\n            'number':     'green',\n            'keyword':    'blue',\n            'function':   'gray',\n            'type':       'bright_magenta',\n            'identifier': 'yellow',\n            'error':      'bright_red',\n            'result':     'black',\n            'error_msg':  'bright_red',\n        };\n    } else {\n        styles = {\n            'default':    'bright_green',\n            'comment':    'white',\n            'string':     'bright_cyan',\n            'regex':      'cyan',\n            'number':     'green',\n            'keyword':    'bright_white',\n            'function':   'bright_yellow',\n            'type':       'bright_magenta',\n            'identifier': 'bright_green',\n            'error':      'red',\n            'result':     'bright_white',\n            'error_msg':  'bright_red',\n        };\n    }\n\n    var history = [];\n    var clip_board = \"\";\n    var prec;\n    var expBits;\n    var log2_10;\n    \n    var pstate = \"\";\n    var prompt = \"\";\n    var plen = 0;\n    var ps1;\n    if (config_numcalc)\n        ps1 = \"> \";\n    else\n        ps1 = \"qjs > \";\n    var ps2 = \"  ... \";\n    var utf8 = true;\n    var show_time = false;\n    var show_colors = true;\n    var eval_time = 0;\n    \n    var mexpr = \"\";\n    var level = 0;\n    var cmd = \"\";\n    var cursor_pos = 0;\n    var last_cmd = \"\";\n    var last_cursor_pos = 0;\n    var history_index;\n    var this_fun, last_fun;\n    var quote_flag = false;\n\n    var utf8_state = 0;\n    var utf8_val = 0;\n\n    var term_fd;\n    var term_read_buf;\n    var term_width;\n    /* current X position of the cursor in the terminal */\n    var term_cursor_x = 0; \n    \n    function termInit() {\n        var tab;\n        term_fd = std.in.fileno();\n        \n        /* get the terminal size */\n        term_width = 80;\n        if (os.isatty(term_fd)) {\n            if (os.ttyGetWinSize) {\n                tab = os.ttyGetWinSize(term_fd);\n                if (tab)\n                    term_width = tab[0];\n            }\n            if (os.ttySetRaw) {\n                /* set the TTY to raw mode */\n                os.ttySetRaw(term_fd);\n            }\n        }\n\n        /* install a Ctrl-C signal handler */\n        os.signal(os.SIGINT, sigint_handler);\n\n        /* install a handler to read stdin */\n        term_read_buf = new Uint8Array(64);\n        os.setReadHandler(term_fd, term_read_handler);\n    }\n\n    function sigint_handler() {\n        /* send Ctrl-C to readline */\n        handle_byte(3);\n    }\n    \n    function term_read_handler() {\n        var l, i;\n        l = os.read(term_fd, term_read_buf.buffer, 0, term_read_buf.length);\n        for(i = 0; i < l; i++)\n            handle_byte(term_read_buf[i]);\n    }\n    \n    function handle_byte(c) {\n        if (!utf8) {\n            handle_char(c);\n        } else if (utf8_state !== 0 && (c >= 0x80 && c < 0xc0)) {\n            utf8_val = (utf8_val << 6) | (c & 0x3F);\n            utf8_state--;\n            if (utf8_state === 0) {\n                handle_char(utf8_val);\n            }\n        } else if (c >= 0xc0 && c < 0xf8) {\n            utf8_state = 1 + (c >= 0xe0) + (c >= 0xf0);\n            utf8_val = c & ((1 << (6 - utf8_state)) - 1);\n        } else {\n            utf8_state = 0;\n            handle_char(c);\n        }\n    }\n    \n    function is_alpha(c) {\n        return typeof c === \"string\" &&\n            ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'));\n    }\n    \n    function is_digit(c) {\n        return typeof c === \"string\" && (c >= '0' && c <= '9');\n    }\n\n    function is_word(c) {\n        return typeof c === \"string\" &&\n            (is_alpha(c) || is_digit(c) || c == '_' || c == '$');\n    }\n\n    function ucs_length(str) {\n        var len, c, i, str_len = str.length;\n        len = 0;\n        /* we never count the trailing surrogate to have the\n         following property: ucs_length(str) =\n         ucs_length(str.substring(0, a)) + ucs_length(str.substring(a,\n         str.length)) for 0 <= a <= str.length */\n        for(i = 0; i < str_len; i++) {\n            c = str.charCodeAt(i);\n            if (c < 0xdc00 || c >= 0xe000)\n                len++;\n        }\n        return len;\n    }\n\n    function is_trailing_surrogate(c)  {\n        var d;\n        if (typeof c !== \"string\")\n            return false;\n        d = c.codePointAt(0); /* can be NaN if empty string */\n        return d >= 0xdc00 && d < 0xe000;\n    }\n    \n    function is_balanced(a, b) {\n        switch (a + b) {\n        case \"()\":\n        case \"[]\":\n        case \"{}\":\n            return true;\n        }\n        return false;\n    }\n\n    function print_color_text(str, start, style_names) {\n        var i, j;\n        for (j = start; j < str.length;) {\n            var style = style_names[i = j];\n            while (++j < str.length && style_names[j] == style)\n                continue;\n            std.puts(colors[styles[style] || 'default']);\n            std.puts(str.substring(i, j));\n            std.puts(colors['none']);\n        }\n    }\n\n    function print_csi(n, code) {\n        std.puts(\"\\x1b[\" + ((n != 1) ? n : \"\") + code);\n    }\n\n    /* XXX: handle double-width characters */\n    function move_cursor(delta) {\n        var i, l;\n        if (delta > 0) {\n            while (delta != 0) {\n                if (term_cursor_x == (term_width - 1)) {\n                    std.puts(\"\\n\"); /* translated to CRLF */\n                    term_cursor_x = 0;\n                    delta--;\n                } else {\n                    l = Math.min(term_width - 1 - term_cursor_x, delta);\n                    print_csi(l, \"C\"); /* right */\n                    delta -= l; \n                    term_cursor_x += l;\n                }\n            }\n        } else {\n            delta = -delta;\n            while (delta != 0) {\n                if (term_cursor_x == 0) {\n                    print_csi(1, \"A\"); /* up */\n                    print_csi(term_width - 1, \"C\"); /* right */\n                    delta--;\n                    term_cursor_x = term_width - 1;\n                } else {\n                    l = Math.min(delta, term_cursor_x);\n                    print_csi(l, \"D\"); /* left */\n                    delta -= l;\n                    term_cursor_x -= l;\n                }\n            }\n        }\n    }\n\n    function update() {\n        var i, cmd_len;\n        /* cursor_pos is the position in 16 bit characters inside the\n           UTF-16 string 'cmd' */\n        if (cmd != last_cmd) {\n            if (!show_colors && last_cmd.substring(0, last_cursor_pos) == cmd.substring(0, last_cursor_pos)) {\n                /* optimize common case */\n                std.puts(cmd.substring(last_cursor_pos));\n            } else {\n                /* goto the start of the line */\n                move_cursor(-ucs_length(last_cmd.substring(0, last_cursor_pos)));\n                if (show_colors) {\n                    var str = mexpr ? mexpr + '\\n' + cmd : cmd;\n                    var start = str.length - cmd.length;\n                    var colorstate = colorize_js(str);\n                    print_color_text(str, start, colorstate[2]);\n                } else {\n                    std.puts(cmd);\n                }\n            }\n            term_cursor_x = (term_cursor_x + ucs_length(cmd)) % term_width;\n            if (term_cursor_x == 0) {\n                /* show the cursor on the next line */\n                std.puts(\" \\x08\");\n            }\n            /* remove the trailing characters */\n            std.puts(\"\\x1b[J\");\n            last_cmd = cmd;\n            last_cursor_pos = cmd.length;\n        }\n        if (cursor_pos > last_cursor_pos) {\n            move_cursor(ucs_length(cmd.substring(last_cursor_pos, cursor_pos)));\n        } else if (cursor_pos < last_cursor_pos) {\n            move_cursor(-ucs_length(cmd.substring(cursor_pos, last_cursor_pos)));\n        }\n        last_cursor_pos = cursor_pos;\n        std.out.flush();\n    }\n\n    /* editing commands */\n    function insert(str) {\n        if (str) {\n            cmd = cmd.substring(0, cursor_pos) + str + cmd.substring(cursor_pos);\n            cursor_pos += str.length;\n        }\n    }\n\n    function quoted_insert() {\n        quote_flag = true;\n    }\n\n    function abort() {\n        cmd = \"\";\n        cursor_pos = 0;\n        return -2;\n    }\n\n    function alert() {\n    }\n\n    function beginning_of_line() {\n        cursor_pos = 0;\n    }\n\n    function end_of_line() {\n        cursor_pos = cmd.length;\n    }\n\n    function forward_char() {\n        if (cursor_pos < cmd.length) {\n            cursor_pos++;\n            while (is_trailing_surrogate(cmd.charAt(cursor_pos)))\n                cursor_pos++;\n        }\n    }\n\n    function backward_char() {\n        if (cursor_pos > 0) {\n            cursor_pos--;\n            while (is_trailing_surrogate(cmd.charAt(cursor_pos)))\n                cursor_pos--;\n        }\n    }\n\n    function skip_word_forward(pos) {\n        while (pos < cmd.length && !is_word(cmd.charAt(pos)))\n            pos++;\n        while (pos < cmd.length && is_word(cmd.charAt(pos)))\n            pos++;\n        return pos;\n    }\n\n    function skip_word_backward(pos) {\n        while (pos > 0 && !is_word(cmd.charAt(pos - 1)))\n            pos--;\n        while (pos > 0 && is_word(cmd.charAt(pos - 1)))\n            pos--;\n        return pos;\n    }\n\n    function forward_word() {\n        cursor_pos = skip_word_forward(cursor_pos);\n    }\n\n    function backward_word() {\n        cursor_pos = skip_word_backward(cursor_pos);\n    }        \n\n    function accept_line() {\n        std.puts(\"\\n\");\n        history_add(cmd);\n        return -1;\n    }\n\n    function history_add(str) {\n        if (str) {\n            history.push(str);\n        }\n        history_index = history.length;\n    }\n\n    function previous_history() {\n        if (history_index > 0) {\n            if (history_index == history.length) {\n                history.push(cmd);\n            }\n            history_index--;\n            cmd = history[history_index];\n            cursor_pos = cmd.length;\n        }\n    }\n\n    function next_history() {\n        if (history_index < history.length - 1) {\n            history_index++;\n            cmd = history[history_index];\n            cursor_pos = cmd.length;\n        }\n    }\n\n    function history_search(dir) {\n        var pos = cursor_pos;\n        for (var i = 1; i <= history.length; i++) {\n            var index = (history.length + i * dir + history_index) % history.length;\n            if (history[index].substring(0, pos) == cmd.substring(0, pos)) {\n                history_index = index;\n                cmd = history[index];\n                return;\n            }\n        }\n    }\n\n    function history_search_backward() {\n        return history_search(-1);\n    }\n\n    function history_search_forward() {\n        return history_search(1);\n    }\n\n    function delete_char_dir(dir) {\n        var start, end;\n\n        start = cursor_pos;\n        if (dir < 0) {\n            start--;\n            while (is_trailing_surrogate(cmd.charAt(start)))\n                start--;\n        }\n        end = start + 1;\n        while (is_trailing_surrogate(cmd.charAt(end)))\n            end++;\n\n        if (start >= 0 && start < cmd.length) {\n            if (last_fun === kill_region) {\n                kill_region(start, end, dir);\n            } else {\n                cmd = cmd.substring(0, start) + cmd.substring(end);\n                cursor_pos = start;\n            }\n        }\n    }\n\n    function delete_char() {\n        delete_char_dir(1);\n    }\n\n    function control_d() {\n        if (cmd.length == 0) {\n            std.puts(\"\\n\");\n            return -3; /* exit read eval print loop */\n        } else {\n            delete_char_dir(1);\n        }\n    }\n\n    function backward_delete_char() {\n        delete_char_dir(-1);\n    }\n\n    function transpose_chars() {\n        var pos = cursor_pos;\n        if (cmd.length > 1 && pos > 0) {\n            if (pos == cmd.length)\n                pos--;\n            cmd = cmd.substring(0, pos - 1) + cmd.substring(pos, pos + 1) +\n                cmd.substring(pos - 1, pos) + cmd.substring(pos + 1);\n            cursor_pos = pos + 1;\n        }\n    }\n\n    function transpose_words() {\n        var p1 = skip_word_backward(cursor_pos);\n        var p2 = skip_word_forward(p1);\n        var p4 = skip_word_forward(cursor_pos);\n        var p3 = skip_word_backward(p4);\n\n        if (p1 < p2 && p2 <= cursor_pos && cursor_pos <= p3 && p3 < p4) {\n            cmd = cmd.substring(0, p1) + cmd.substring(p3, p4) +\n            cmd.substring(p2, p3) + cmd.substring(p1, p2);\n            cursor_pos = p4;\n        }\n    }\n\n    function upcase_word() {\n        var end = skip_word_forward(cursor_pos);\n        cmd = cmd.substring(0, cursor_pos) +\n            cmd.substring(cursor_pos, end).toUpperCase() +\n            cmd.substring(end);\n    }\n\n    function downcase_word() {\n        var end = skip_word_forward(cursor_pos);\n        cmd = cmd.substring(0, cursor_pos) +\n            cmd.substring(cursor_pos, end).toLowerCase() +\n            cmd.substring(end);\n    }\n\n    function kill_region(start, end, dir) {\n        var s = cmd.substring(start, end);\n        if (last_fun !== kill_region)\n            clip_board = s;\n        else if (dir < 0)\n            clip_board = s + clip_board;\n        else\n            clip_board = clip_board + s;\n\n        cmd = cmd.substring(0, start) + cmd.substring(end);\n        if (cursor_pos > end)\n            cursor_pos -= end - start;\n        else if (cursor_pos > start)\n            cursor_pos = start;\n        this_fun = kill_region;\n    }\n\n    function kill_line() {\n        kill_region(cursor_pos, cmd.length, 1);\n    }\n\n    function backward_kill_line() {\n        kill_region(0, cursor_pos, -1);\n    }\n\n    function kill_word() {\n        kill_region(cursor_pos, skip_word_forward(cursor_pos), 1);\n    }\n\n    function backward_kill_word() {\n        kill_region(skip_word_backward(cursor_pos), cursor_pos, -1);\n    }\n\n    function yank() {\n        insert(clip_board);\n    }\n\n    function control_c() {\n        if (last_fun === control_c) {\n            std.puts(\"\\n\");\n            std.exit(0);\n        } else {\n            std.puts(\"\\n(Press Ctrl-C again to quit)\\n\");\n            readline_print_prompt();\n        }\n    }\n    \n    function reset() {\n        cmd = \"\";\n        cursor_pos = 0;\n    }\n\n    function get_context_word(line, pos) {\n        var s = \"\";\n        while (pos > 0 && is_word(line[pos - 1])) {\n            pos--;\n            s = line[pos] + s;\n        }\n        return s;\n    }\n    function get_context_object(line, pos) {\n        var obj, base, c;\n        if (pos <= 0 || \" ~!%^&*(-+={[|:;,<>?/\".indexOf(line[pos - 1]) >= 0)\n            return g;\n        if (pos >= 2 && line[pos - 1] === \".\") {\n            pos--;\n            obj = {};\n            switch (c = line[pos - 1]) {\n            case '\\'':\n            case '\\\"':\n                return \"a\";\n            case ']':\n                return [];\n            case '}':\n                return {};\n            case '/':\n                return / /;\n            default:\n                if (is_word(c)) {\n                    base = get_context_word(line, pos);\n                    if ([\"true\", \"false\", \"null\", \"this\"].includes(base) || !isNaN(+base))\n                        return eval(base);\n                    obj = get_context_object(line, pos - base.length);\n                    if (obj === null || obj === void 0)\n                        return obj;\n                    if (obj === g && obj[base] === void 0)\n                        return eval(base);\n                    else\n                        return obj[base];\n                }\n                return {};\n            }\n        }\n        return void 0;\n    }\n\n    function get_completions(line, pos) {\n        var s, obj, ctx_obj, r, i, j, paren;\n\n        s = get_context_word(line, pos);\n        ctx_obj = get_context_object(line, pos - s.length);\n        r = [];\n        /* enumerate properties from object and its prototype chain,\n           add non-numeric regular properties with s as e prefix\n         */\n        for (i = 0, obj = ctx_obj; i < 10 && obj !== null && obj !== void 0; i++) {\n            var props = Object.getOwnPropertyNames(obj);\n            /* add non-numeric regular properties */\n            for (j = 0; j < props.length; j++) {\n                var prop = props[j];\n                if (typeof prop == \"string\" && \"\"+(+prop) != prop && prop.startsWith(s))\n                    r.push(prop);\n            }\n            obj = Object.getPrototypeOf(obj);\n        }\n        if (r.length > 1) {\n            /* sort list with internal names last and remove duplicates */\n            function symcmp(a, b) {\n                if (a[0] != b[0]) {\n                    if (a[0] == '_')\n                        return 1;\n                    if (b[0] == '_')\n                        return -1;\n                }\n                if (a < b)\n                    return -1;\n                if (a > b)\n                    return +1;\n                return 0;\n            }\n            r.sort(symcmp);\n            for(i = j = 1; i < r.length; i++) {\n                if (r[i] != r[i - 1])\n                    r[j++] = r[i];\n            }\n            r.length = j;\n        }\n        /* 'tab' = list of completions, 'pos' = cursor position inside\n           the completions */\n        return { tab: r, pos: s.length, ctx: ctx_obj };\n    }\n\n    function completion() {\n        var tab, res, s, i, j, len, t, max_width, col, n_cols, row, n_rows;\n        res = get_completions(cmd, cursor_pos);\n        tab = res.tab;\n        if (tab.length === 0)\n            return;\n        s = tab[0];\n        len = s.length;\n        /* add the chars which are identical in all the completions */\n        for(i = 1; i < tab.length; i++) {\n            t = tab[i];\n            for(j = 0; j < len; j++) {\n                if (t[j] !== s[j]) {\n                    len = j;\n                    break;\n                }\n            }\n        }\n        for(i = res.pos; i < len; i++) {\n            insert(s[i]);\n        }\n        if (last_fun === completion && tab.length == 1) {\n            /* append parentheses to function names */\n            var m = res.ctx[tab[0]];\n            if (typeof m == \"function\") {\n                insert('(');\n                if (m.length == 0)\n                    insert(')');\n            } else if (typeof m == \"object\") {\n                insert('.');\n            }\n        }\n        /* show the possible completions */\n        if (last_fun === completion && tab.length >= 2) {\n            max_width = 0;\n            for(i = 0; i < tab.length; i++)\n                max_width = Math.max(max_width, tab[i].length);\n            max_width += 2;\n            n_cols = Math.max(1, Math.floor((term_width + 1) / max_width));\n            n_rows = Math.ceil(tab.length / n_cols);\n            std.puts(\"\\n\");\n            /* display the sorted list column-wise */\n            for (row = 0; row < n_rows; row++) {\n                for (col = 0; col < n_cols; col++) {\n                    i = col * n_rows + row;\n                    if (i >= tab.length)\n                        break;\n                    s = tab[i];\n                    if (col != n_cols - 1)\n                        s = s.padEnd(max_width);\n                    std.puts(s);\n                }\n                std.puts(\"\\n\");\n            }\n            /* show a new prompt */\n            readline_print_prompt();\n        }\n    }\n    \n    var commands = {        /* command table */\n        \"\\x01\":     beginning_of_line,      /* ^A - bol */\n        \"\\x02\":     backward_char,          /* ^B - backward-char */\n        \"\\x03\":     control_c,              /* ^C - abort */\n        \"\\x04\":     control_d,              /* ^D - delete-char or exit */\n        \"\\x05\":     end_of_line,            /* ^E - eol */\n        \"\\x06\":     forward_char,           /* ^F - forward-char */\n        \"\\x07\":     abort,                  /* ^G - bell */\n        \"\\x08\":     backward_delete_char,   /* ^H - backspace */\n        \"\\x09\":     completion,             /* ^I - history-search-backward */\n        \"\\x0a\":     accept_line,            /* ^J - newline */\n        \"\\x0b\":     kill_line,              /* ^K - delete to end of line */\n        \"\\x0d\":     accept_line,            /* ^M - enter */\n        \"\\x0e\":     next_history,           /* ^N - down */\n        \"\\x10\":     previous_history,       /* ^P - up */\n        \"\\x11\":     quoted_insert,          /* ^Q - quoted-insert */\n        \"\\x12\":     alert,                  /* ^R - reverse-search */\n        \"\\x13\":     alert,                  /* ^S - search */\n        \"\\x14\":     transpose_chars,        /* ^T - transpose */\n        \"\\x18\":     reset,                  /* ^X - cancel */\n        \"\\x19\":     yank,                   /* ^Y - yank */\n        \"\\x1bOA\":   previous_history,       /* ^[OA - up */\n        \"\\x1bOB\":   next_history,           /* ^[OB - down */\n        \"\\x1bOC\":   forward_char,           /* ^[OC - right */\n        \"\\x1bOD\":   backward_char,          /* ^[OD - left */\n        \"\\x1bOF\":   forward_word,           /* ^[OF - ctrl-right */\n        \"\\x1bOH\":   backward_word,          /* ^[OH - ctrl-left */\n        \"\\x1b[1;5C\": forward_word,          /* ^[[1;5C - ctrl-right */\n        \"\\x1b[1;5D\": backward_word,         /* ^[[1;5D - ctrl-left */\n        \"\\x1b[1~\":  beginning_of_line,      /* ^[[1~ - bol */\n        \"\\x1b[3~\":  delete_char,            /* ^[[3~ - delete */\n        \"\\x1b[4~\":  end_of_line,            /* ^[[4~ - eol */\n        \"\\x1b[5~\":  history_search_backward,/* ^[[5~ - page up */\n        \"\\x1b[6~\":  history_search_forward, /* ^[[5~ - page down */\n        \"\\x1b[A\":   previous_history,       /* ^[[A - up */\n        \"\\x1b[B\":   next_history,           /* ^[[B - down */\n        \"\\x1b[C\":   forward_char,           /* ^[[C - right */\n        \"\\x1b[D\":   backward_char,          /* ^[[D - left */\n        \"\\x1b[F\":   end_of_line,            /* ^[[F - end */\n        \"\\x1b[H\":   beginning_of_line,      /* ^[[H - home */\n        \"\\x1b\\x7f\": backward_kill_word,     /* M-C-? - backward_kill_word */\n        \"\\x1bb\":    backward_word,          /* M-b - backward_word */\n        \"\\x1bd\":    kill_word,              /* M-d - kill_word */\n        \"\\x1bf\":    forward_word,           /* M-f - backward_word */\n        \"\\x1bk\":    backward_kill_line,     /* M-k - backward_kill_line */\n        \"\\x1bl\":    downcase_word,          /* M-l - downcase_word */\n        \"\\x1bt\":    transpose_words,        /* M-t - transpose_words */\n        \"\\x1bu\":    upcase_word,            /* M-u - upcase_word */\n        \"\\x7f\":     backward_delete_char,   /* ^? - delete */\n    };\n\n    function dupstr(str, count) {\n        var res = \"\";\n        while (count-- > 0)\n            res += str;\n        return res;\n    }\n\n    var readline_keys;\n    var readline_state;\n    var readline_cb;\n\n    function readline_print_prompt()\n    {\n        std.puts(prompt);\n        term_cursor_x = ucs_length(prompt) % term_width;\n        last_cmd = \"\";\n        last_cursor_pos = 0;\n    }\n\n    function readline_start(defstr, cb) {\n        cmd = defstr || \"\";\n        cursor_pos = cmd.length;\n        history_index = history.length;\n        readline_cb = cb;\n        \n        prompt = pstate;\n    \n        if (mexpr) {\n            prompt += dupstr(\" \", plen - prompt.length);\n            prompt += ps2;\n        } else {\n            if (show_time) {\n                var t = Math.round(eval_time) + \" \";\n                eval_time = 0;\n                t = dupstr(\"0\", 5 - t.length) + t;\n                prompt += t.substring(0, t.length - 4) + \".\" + t.substring(t.length - 4);\n            }\n            plen = prompt.length;\n            prompt += ps1;\n        }\n        readline_print_prompt();\n        update();\n        readline_state = 0;\n    }\n\n    function handle_char(c1) {\n        var c;\n        c = String.fromCodePoint(c1);\n        switch(readline_state) {\n        case 0:\n            if (c == '\\x1b') {  /* '^[' - ESC */\n                readline_keys = c;\n                readline_state = 1;\n            } else {\n                handle_key(c);\n            }\n            break;\n        case 1: /* '^[ */\n            readline_keys += c;\n            if (c == '[') {\n                readline_state = 2;\n            } else if (c == 'O') {\n                readline_state = 3;\n            } else {\n                handle_key(readline_keys);\n                readline_state = 0;\n            }\n            break;\n        case 2: /* '^[[' - CSI */\n            readline_keys += c;\n            if (!(c == ';' || (c >= '0' && c <= '9'))) {\n                handle_key(readline_keys);\n                readline_state = 0;\n            }\n            break;\n        case 3: /* '^[O' - ESC2 */\n            readline_keys += c;\n            handle_key(readline_keys);\n            readline_state = 0;\n            break;\n        }\n    }\n\n    function handle_key(keys) {\n        var fun;\n\n        if (quote_flag) {\n            if (ucs_length(keys) === 1)\n                insert(keys);\n            quote_flag = false;\n        } else if (fun = commands[keys]) {\n            this_fun = fun;\n            switch (fun(keys)) {\n            case -1:\n                readline_cb(cmd);\n                return;\n            case -2:\n                readline_cb(null);\n                return;\n            case -3:\n                /* uninstall a Ctrl-C signal handler */\n                os.signal(os.SIGINT, null);\n                /* uninstall the stdin read handler */\n                os.setReadHandler(term_fd, null);\n                return;\n            }\n            last_fun = this_fun;\n        } else if (ucs_length(keys) === 1 && keys >= ' ') {\n            insert(keys);\n            last_fun = insert;\n        } else {\n            alert(); /* beep! */\n        }\n        \n        cursor_pos = (cursor_pos < 0) ? 0 :\n            (cursor_pos > cmd.length) ? cmd.length : cursor_pos;\n        update();\n    }\n\n    var hex_mode = false;\n    var eval_mode = \"std\";\n\n    function number_to_string(a, radix) {\n        var s;\n        if (!isFinite(a)) {\n            /* NaN, Infinite */\n            return a.toString();\n        } else {\n            if (a == 0) {\n                if (1 / a < 0)\n                    s = \"-0\";\n                else\n                    s = \"0\";\n            } else {\n                if (radix == 16 && a === Math.floor(a)) {\n                    var s;\n                    if (a < 0) {\n                        a = -a;\n                        s = \"-\";\n                    } else {\n                        s = \"\";\n                    }\n                    s += \"0x\" + a.toString(16);\n                } else {\n                    s = a.toString();\n                }\n            }\n            return s;\n        }\n    }\n\n    function bigfloat_to_string(a, radix) {\n        var s;\n        if (!BigFloat.isFinite(a)) {\n            /* NaN, Infinite */\n            if (eval_mode !== \"math\") {\n                return \"BigFloat(\" + a.toString() + \")\";\n            } else {\n                return a.toString();\n            }\n        } else {\n            if (a == 0) {\n                if (1 / a < 0)\n                    s = \"-0\";\n                else\n                    s = \"0\";\n            } else {\n                if (radix == 16) {\n                    var s;\n                    if (a < 0) {\n                        a = -a;\n                        s = \"-\";\n                    } else {\n                        s = \"\";\n                    }\n                    s += \"0x\" + a.toString(16);\n                } else {\n                    s = a.toString();\n                }\n            }\n            if (typeof a === \"bigfloat\" && eval_mode !== \"math\") {\n                s += \"l\";\n            } else if (eval_mode !== \"std\" && s.indexOf(\".\") < 0 &&\n                ((radix == 16 && s.indexOf(\"p\") < 0) ||\n                 (radix == 10 && s.indexOf(\"e\") < 0))) {\n                /* add a decimal point so that the floating point type\n                   is visible */\n                s += \".0\";\n            }\n            return s;\n        }\n    }\n\n    function bigint_to_string(a, radix) {\n        var s;\n        if (radix == 16) {\n            var s;\n            if (a < 0) {\n                a = -a;\n                s = \"-\";\n            } else {\n                s = \"\";\n            }\n            s += \"0x\" + a.toString(16);\n        } else {\n            s = a.toString();\n        }\n        if (eval_mode === \"std\")\n            s += \"n\";\n        return s;\n    }\n    \n    function print(a) {\n        var stack = [];\n\n        function print_rec(a) {\n            var n, i, keys, key, type, s;\n            \n            type = typeof(a);\n            if (type === \"object\") {\n                if (a === null) {\n                    std.puts(a);\n                } else if (stack.indexOf(a) >= 0) {\n                    std.puts(\"[circular]\");\n                } else if (has_jscalc && (a instanceof Fraction ||\n                                        a instanceof Complex ||\n                                        a instanceof Mod ||\n                                        a instanceof Polynomial ||\n                                        a instanceof PolyMod ||\n                                        a instanceof RationalFunction ||\n                                        a instanceof Series)) {\n                    std.puts(a.toString());\n                } else {\n                    stack.push(a);\n                    if (Array.isArray(a)) {\n                        n = a.length;\n                        std.puts(\"[ \");\n                        for(i = 0; i < n; i++) {\n                            if (i !== 0)\n                                std.puts(\", \");\n                            if (i in a) {\n                                print_rec(a[i]);\n                            } else {\n                                std.puts(\"<empty>\");\n                            }\n                            if (i > 20) {\n                                std.puts(\"...\");\n                                break;\n                            }\n                        }\n                        std.puts(\" ]\");\n                    } else if (Object.__getClass(a) === \"RegExp\") {\n                        std.puts(a.toString());\n                    } else {\n                        keys = Object.keys(a);\n                        n = keys.length;\n                        std.puts(\"{ \");\n                        for(i = 0; i < n; i++) {\n                            if (i !== 0)\n                                std.puts(\", \");\n                            key = keys[i];\n                            std.puts(key, \": \");\n                            print_rec(a[key]);\n                        }\n                        std.puts(\" }\");\n                    }\n                    stack.pop(a);\n                }\n            } else if (type === \"string\") {\n                s = a.__quote();\n                if (s.length > 79)\n                    s = s.substring(0, 75) + \"...\\\"\";\n                std.puts(s);\n            } else if (type === \"number\") {\n                std.puts(number_to_string(a, hex_mode ? 16 : 10));\n            } else if (type === \"bigint\") {\n                std.puts(bigint_to_string(a, hex_mode ? 16 : 10));\n            } else if (type === \"bigfloat\") {\n                std.puts(bigfloat_to_string(a, hex_mode ? 16 : 10));\n            } else if (type === \"bigdecimal\") {\n                std.puts(a.toString() + \"m\");\n            } else if (type === \"symbol\") {\n                std.puts(String(a));\n            } else if (type === \"function\") {\n                std.puts(\"function \" + a.name + \"()\");\n            } else {\n                std.puts(a);\n            }\n        }\n        print_rec(a);\n    }\n    \n    function extract_directive(a) {\n        var pos;\n        if (a[0] !== '\\\\')\n            return \"\";\n        for (pos = 1; pos < a.length; pos++) {\n            if (!is_alpha(a[pos]))\n                break;\n        }\n        return a.substring(1, pos);\n    }\n\n    /* return true if the string after cmd can be evaluted as JS */\n    function handle_directive(cmd, expr) {\n        var param, prec1, expBits1;\n        \n        if (cmd === \"h\" || cmd === \"?\" || cmd == \"help\") {\n            help();\n        } else if (cmd === \"load\") {\n            var filename = expr.substring(cmd.length + 1).trim();\n            if (filename.lastIndexOf(\".\") <= filename.lastIndexOf(\"/\"))\n                filename += \".js\";\n            std.loadScript(filename);\n            return false;\n        } else if (cmd === \"x\") {\n            hex_mode = true;\n        } else if (cmd === \"d\") {\n            hex_mode = false;\n        } else if (cmd === \"t\") {\n            show_time = !show_time;\n        } else if (has_bignum && cmd === \"p\") {\n            param = expr.substring(cmd.length + 1).trim().split(\" \");\n            if (param.length === 1 && param[0] === \"\") {\n                std.puts(\"BigFloat precision=\" + prec + \" bits (~\" +\n                          Math.floor(prec / log2_10) +\n                          \" digits), exponent size=\" + expBits + \" bits\\n\");\n            } else if (param[0] === \"f16\") {\n                prec = 11;\n                expBits = 5;\n            } else if (param[0] === \"f32\") {\n                prec = 24;\n                expBits = 8;\n            } else if (param[0] === \"f64\") {\n                prec = 53;\n                expBits = 11;\n            } else if (param[0] === \"f128\") {\n                prec = 113;\n                expBits = 15;\n            } else {\n                prec1 = parseInt(param[0]);\n                if (param.length >= 2)\n                    expBits1 = parseInt(param[1]);\n                else\n                    expBits1 = BigFloatEnv.expBitsMax;\n                if (Number.isNaN(prec1) ||\n                    prec1 < BigFloatEnv.precMin ||\n                    prec1 > BigFloatEnv.precMax) {\n                    std.puts(\"Invalid precision\\n\");\n                    return false;\n                }\n                if (Number.isNaN(expBits1) ||\n                    expBits1 < BigFloatEnv.expBitsMin ||\n                    expBits1 > BigFloatEnv.expBitsMax) {\n                    std.puts(\"Invalid exponent bits\\n\");\n                    return false;\n                }\n                prec = prec1;\n                expBits = expBits1;\n            }\n            return false;\n        } else if (has_bignum && cmd === \"digits\") {\n            param = expr.substring(cmd.length + 1).trim();\n            prec1 = Math.ceil(parseFloat(param) * log2_10);\n            if (prec1 < BigFloatEnv.precMin ||\n                prec1 > BigFloatEnv.precMax) {\n                std.puts(\"Invalid precision\\n\");\n                return false;\n            }\n            prec = prec1;\n            expBits = BigFloatEnv.expBitsMax;\n            return false;\n        } else if (has_bignum && cmd === \"mode\") {\n            param = expr.substring(cmd.length + 1).trim();\n            if (param === \"\") {\n                std.puts(\"Running mode=\" + eval_mode + \"\\n\");\n            } else if (param === \"std\" || param === \"math\") {\n                eval_mode = param;\n            } else {\n                std.puts(\"Invalid mode\\n\");\n            }\n            return false;\n        } else if (cmd === \"clear\") {\n            std.puts(\"\\x1b[H\\x1b[J\");\n        } else if (cmd === \"q\") {\n            std.exit(0);\n        } else if (has_jscalc && cmd === \"a\") {\n            algebraicMode = true;\n        } else if (has_jscalc && cmd === \"n\") {\n            algebraicMode = false;\n        } else {\n            std.puts(\"Unknown directive: \" + cmd + \"\\n\");\n            return false;\n        }\n        return true;\n    }\n\n    if (config_numcalc) {\n        /* called by the GUI */\n        g.execCmd = function (cmd) {\n            switch(cmd) {\n            case \"dec\":\n                hex_mode = false;\n                break;\n            case \"hex\":\n                hex_mode = true;\n                break;\n            case \"num\":\n                algebraicMode = false;\n                break;\n            case \"alg\":\n                algebraicMode = true;\n                break;\n            }\n        }\n    }\n    \n    function help() {\n        function sel(n) {\n            return n ? \"*\": \" \";\n        }\n        std.puts(\"\\\\h          this help\\n\" +\n                 \"\\\\x         \" + sel(hex_mode) + \"hexadecimal number display\\n\" +\n                 \"\\\\d         \" + sel(!hex_mode) + \"decimal number display\\n\" +\n                 \"\\\\t         \" + sel(show_time) + \"toggle timing display\\n\" +\n                  \"\\\\clear      clear the terminal\\n\");\n        if (has_jscalc) {\n            std.puts(\"\\\\a         \" + sel(algebraicMode) + \"algebraic mode\\n\" +\n                     \"\\\\n         \" + sel(!algebraicMode) + \"numeric mode\\n\");\n        }\n        if (has_bignum) {\n            std.puts(\"\\\\p [m [e]]  set the BigFloat precision to 'm' bits\\n\" +\n                     \"\\\\digits n   set the BigFloat precision to 'ceil(n*log2(10))' bits\\n\");\n            if (!has_jscalc) {\n                std.puts(\"\\\\mode [std|math] change the running mode (current = \" + eval_mode + \")\\n\");\n            }\n        }\n        if (!config_numcalc) {\n            std.puts(\"\\\\q          exit\\n\");\n        }\n    }\n\n    function eval_and_print(expr) {\n        var result;\n        \n        try {\n            if (eval_mode === \"math\")\n                expr = '\"use math\"; void 0;' + expr;\n            var now = (new Date).getTime();\n            /* eval as a script */\n            result = std.evalScript(expr, { backtrace_barrier: true });\n            eval_time = (new Date).getTime() - now;\n            std.puts(colors[styles.result]);\n            print(result);\n            std.puts(\"\\n\");\n            std.puts(colors.none);\n            /* set the last result */\n            g._ = result;\n        } catch (error) {\n            std.puts(colors[styles.error_msg]);\n            if (error instanceof Error) {\n                console.log(error);\n                if (error.stack) {\n                    std.puts(error.stack);\n                }\n            } else {\n                std.puts(\"Throw: \");\n                console.log(error);\n            }\n            std.puts(colors.none);\n        }\n    }\n\n    function cmd_start() {\n        if (!config_numcalc) {\n            if (has_jscalc)\n                std.puts('QJSCalc - Type \"\\\\h\" for help\\n');\n            else\n                std.puts('QuickJS - Type \"\\\\h\" for help\\n');\n        }\n        if (has_bignum) {\n            log2_10 = Math.log(10) / Math.log(2);\n            prec = 113;\n            expBits = 15;\n            if (has_jscalc) {\n                eval_mode = \"math\";\n                /* XXX: numeric mode should always be the default ? */\n                g.algebraicMode = config_numcalc;\n            }\n        }\n\n        cmd_readline_start();\n    }\n\n    function cmd_readline_start() {\n        readline_start(dupstr(\"    \", level), readline_handle_cmd);\n    }\n    \n    function readline_handle_cmd(expr) {\n        handle_cmd(expr);\n        cmd_readline_start();\n    }\n\n    function handle_cmd(expr) {\n        var colorstate, cmd;\n        \n        if (expr === null) {\n            expr = \"\";\n            return;\n        }\n        if (expr === \"?\") {\n            help();\n            return;\n        }\n        cmd = extract_directive(expr);\n        if (cmd.length > 0) {\n            if (!handle_directive(cmd, expr))\n                return;\n            expr = expr.substring(cmd.length + 1);\n        }\n        if (expr === \"\")\n            return;\n        \n        if (mexpr)\n            expr = mexpr + '\\n' + expr;\n        colorstate = colorize_js(expr);\n        pstate = colorstate[0];\n        level = colorstate[1];\n        if (pstate) {\n            mexpr = expr;\n            return;\n        }\n        mexpr = \"\";\n        \n        if (has_bignum) {\n            BigFloatEnv.setPrec(eval_and_print.bind(null, expr),\n                                prec, expBits);\n        } else {\n            eval_and_print(expr);\n        }\n        level = 0;\n        \n        /* run the garbage collector after each command */\n        std.gc();\n    }\n\n    function colorize_js(str) {\n        var i, c, start, n = str.length;\n        var style, state = \"\", level = 0;\n        var primary, can_regex = 1;\n        var r = [];\n\n        function push_state(c) { state += c; }\n        function last_state(c) { return state.substring(state.length - 1); }\n        function pop_state(c) {\n            var c = last_state();\n            state = state.substring(0, state.length - 1);\n            return c;\n        }\n\n        function parse_block_comment() {\n            style = 'comment';\n            push_state('/');\n            for (i++; i < n - 1; i++) {\n                if (str[i] == '*' && str[i + 1] == '/') {\n                    i += 2;\n                    pop_state('/');\n                    break;\n                }\n            }\n        }\n\n        function parse_line_comment() {\n            style = 'comment';\n            for (i++; i < n; i++) {\n                if (str[i] == '\\n') {\n                    break;\n                }\n            }\n        }\n\n        function parse_string(delim) {\n            style = 'string';\n            push_state(delim);\n            while (i < n) {\n                c = str[i++];\n                if (c == '\\n') {\n                    style = 'error';\n                    continue;\n                }\n                if (c == '\\\\') {\n                    if (i >= n)\n                        break;\n                    i++;\n                } else\n                if (c == delim) {\n                    pop_state();\n                    break;\n                }\n            }\n        }\n\n        function parse_regex() {\n            style = 'regex';\n            push_state('/');\n            while (i < n) {\n                c = str[i++];\n                if (c == '\\n') {\n                    style = 'error';\n                    continue;\n                }\n                if (c == '\\\\') {\n                    if (i < n) {\n                        i++;\n                    }\n                    continue;\n                }\n                if (last_state() == '[') {\n                    if (c == ']') {\n                        pop_state()\n                    }\n                    // ECMA 5: ignore '/' inside char classes\n                    continue;\n                }\n                if (c == '[') {\n                    push_state('[');\n                    if (str[i] == '[' || str[i] == ']')\n                        i++;\n                    continue;\n                }\n                if (c == '/') {\n                    pop_state();\n                    while (i < n && is_word(str[i]))\n                        i++;\n                    break;\n                }\n            }\n        }\n\n        function parse_number() {\n            style = 'number';\n            while (i < n && (is_word(str[i]) || (str[i] == '.' && (i == n - 1 || str[i + 1] != '.')))) {\n                i++;\n            }\n        }\n\n        var js_keywords = \"|\" +\n            \"break|case|catch|continue|debugger|default|delete|do|\" +\n            \"else|finally|for|function|if|in|instanceof|new|\" +\n            \"return|switch|this|throw|try|typeof|while|with|\" +\n            \"class|const|enum|import|export|extends|super|\" +\n            \"implements|interface|let|package|private|protected|\" +\n            \"public|static|yield|\" +\n            \"undefined|null|true|false|Infinity|NaN|\" +\n            \"eval|arguments|\" +\n            \"await|\";\n\n        var js_no_regex = \"|this|super|undefined|null|true|false|Infinity|NaN|arguments|\";\n        var js_types = \"|void|var|\";\n\n        function parse_identifier() {\n            can_regex = 1;\n\n            while (i < n && is_word(str[i]))\n                i++;\n\n            var w = '|' + str.substring(start, i) + '|';\n\n            if (js_keywords.indexOf(w) >= 0) {\n                style = 'keyword';\n                if (js_no_regex.indexOf(w) >= 0)\n                    can_regex = 0;\n                return;\n            }\n\n            var i1 = i;\n            while (i1 < n && str[i1] == ' ')\n                i1++;\n\n            if (i1 < n && str[i1] == '(') {\n                style = 'function';\n                return;\n            }\n\n            if (js_types.indexOf(w) >= 0) {\n                style = 'type';\n                return;\n            }\n\n            style = 'identifier';\n            can_regex = 0;\n        }\n\n        function set_style(from, to) {\n            while (r.length < from)\n                r.push('default');\n            while (r.length < to)\n                r.push(style);\n        }\n\n        for (i = 0; i < n;) {\n            style = null;\n            start = i;\n            switch (c = str[i++]) {\n            case ' ':\n            case '\\t':\n            case '\\r':\n            case '\\n':\n                continue;\n            case '+':\n            case '-':\n                if (i < n && str[i] == c) {\n                    i++;\n                    continue;\n                }\n                can_regex = 1;\n                continue;\n            case '/':\n                if (i < n && str[i] == '*') { // block comment\n                    parse_block_comment();\n                    break;\n                }\n                if (i < n && str[i] == '/') { // line comment\n                    parse_line_comment();\n                    break;\n                }\n                if (can_regex) {\n                    parse_regex();\n                    can_regex = 0;\n                    break;\n                }\n                can_regex = 1;\n                continue;\n            case '\\'':\n            case '\\\"':\n            case '`':\n                parse_string(c);\n                can_regex = 0;\n                break;\n            case '(':\n            case '[':\n            case '{':\n                can_regex = 1;\n                level++;\n                push_state(c);\n                continue;\n            case ')':\n            case ']':\n            case '}':\n                can_regex = 0;\n                if (level > 0 && is_balanced(last_state(), c)) {\n                    level--;\n                    pop_state();\n                    continue;\n                }\n                style = 'error';\n                break;\n            default:\n                if (is_digit(c)) {\n                    parse_number();\n                    can_regex = 0;\n                    break;\n                }\n                if (is_word(c) || c == '$') {\n                    parse_identifier();\n                    break;\n                }\n                can_regex = 1;\n                continue;\n            }\n            if (style)\n                set_style(start, i);\n        }\n        set_style(n, n);\n        return [ state, level, r ];\n    }\n\n    termInit();\n    \n    cmd_start();\n\n})(globalThis);\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/run-test262.c",
    "content": "/*\n * ECMA Test 262 Runner for QuickJS\n * \n * Copyright (c) 2017-2021 Fabrice Bellard\n * Copyright (c) 2017-2021 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <inttypes.h>\n#include <string.h>\n#include <assert.h>\n#include <ctype.h>\n#include <unistd.h>\n#include <errno.h>\n#include <time.h>\n#include <dirent.h>\n#include <ftw.h>\n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"quickjs-libc.h\"\n\n/* enable test262 thread support to test SharedArrayBuffer and Atomics */\n#define CONFIG_AGENT\n\n#define CMD_NAME \"run-test262\"\n\ntypedef struct namelist_t {\n    char **array;\n    int count;\n    int size;\n    unsigned int sorted : 1;\n} namelist_t;\n\nnamelist_t test_list;\nnamelist_t exclude_list;\nnamelist_t exclude_dir_list;\n\nFILE *outfile;\nenum test_mode_t {\n    TEST_DEFAULT_NOSTRICT, /* run tests as nostrict unless test is flagged as strictonly */\n    TEST_DEFAULT_STRICT,   /* run tests as strict unless test is flagged as nostrict */\n    TEST_NOSTRICT,         /* run tests as nostrict, skip strictonly tests */\n    TEST_STRICT,           /* run tests as strict, skip nostrict tests */\n    TEST_ALL,              /* run tests in both strict and nostrict, unless restricted by spec */\n} test_mode = TEST_DEFAULT_NOSTRICT;\nint skip_async;\nint skip_module;\nint new_style;\nint dump_memory;\nint stats_count;\nJSMemoryUsage stats_all, stats_avg, stats_min, stats_max;\nchar *stats_min_filename;\nchar *stats_max_filename;\nint verbose;\nchar *harness_dir;\nchar *harness_exclude;\nchar *harness_features;\nchar *harness_skip_features;\nchar *error_filename;\nchar *error_file;\nFILE *error_out;\nchar *report_filename;\nint update_errors;\nint test_count, test_failed, test_index, test_skipped, test_excluded;\nint new_errors, changed_errors, fixed_errors;\nint async_done;\n\nvoid warning(const char *, ...) __attribute__((__format__(__printf__, 1, 2)));\nvoid fatal(int, const char *, ...) __attribute__((__format__(__printf__, 2, 3)));\n\nvoid warning(const char *fmt, ...)\n{\n    va_list ap;\n\n    fflush(stdout);\n    fprintf(stderr, \"%s: \", CMD_NAME);\n    va_start(ap, fmt);\n    vfprintf(stderr, fmt, ap);\n    va_end(ap);\n    fputc('\\n', stderr);\n}\n\nvoid fatal(int errcode, const char *fmt, ...)\n{\n    va_list ap;\n\n    fflush(stdout);\n    fprintf(stderr, \"%s: \", CMD_NAME);\n    va_start(ap, fmt);\n    vfprintf(stderr, fmt, ap);\n    va_end(ap);\n    fputc('\\n', stderr);\n\n    exit(errcode);\n}\n\nvoid perror_exit(int errcode, const char *s)\n{\n    fflush(stdout);\n    fprintf(stderr, \"%s: \", CMD_NAME);\n    perror(s);\n    exit(errcode);\n}\n\nchar *strdup_len(const char *str, int len)\n{\n    char *p = malloc(len + 1);\n    memcpy(p, str, len);\n    p[len] = '\\0';\n    return p;\n}\n\nstatic inline int str_equal(const char *a, const char *b) {\n    return !strcmp(a, b);\n}\n\nchar *str_append(char **pp, const char *sep, const char *str) {\n    char *res, *p;\n    size_t len = 0;\n    p = *pp;\n    if (p) {\n        len = strlen(p) + strlen(sep);\n    }\n    res = malloc(len + strlen(str) + 1);\n    if (p) {\n        strcpy(res, p);\n        strcat(res, sep);\n    }\n    strcpy(res + len, str);\n    free(p);\n    return *pp = res;\n}\n\nchar *str_strip(char *p)\n{\n    size_t len = strlen(p);\n    while (len > 0 && isspace((unsigned char)p[len - 1]))\n        p[--len] = '\\0';\n    while (isspace((unsigned char)*p))\n        p++;\n    return p;\n}\n\nint has_prefix(const char *str, const char *prefix)\n{\n    return !strncmp(str, prefix, strlen(prefix));\n}\n\nchar *skip_prefix(const char *str, const char *prefix)\n{\n    int i;\n    for (i = 0;; i++) {\n        if (prefix[i] == '\\0') {  /* skip the prefix */\n            str += i;\n            break;\n        }\n        if (str[i] != prefix[i])\n            break;\n    }\n    return (char *)str;\n}\n\nchar *get_basename(const char *filename)\n{\n    char *p;\n\n    p = strrchr(filename, '/');\n    if (!p)\n        return NULL;\n    return strdup_len(filename, p - filename);\n}\n\nchar *compose_path(const char *path, const char *name)\n{\n    int path_len, name_len;\n    char *d, *q;\n\n    if (!path || path[0] == '\\0' || *name == '/') {\n        d = strdup(name);\n    } else {\n        path_len = strlen(path);\n        name_len = strlen(name);\n        d = malloc(path_len + 1 + name_len + 1);\n        if (d) {\n            q = d;\n            memcpy(q, path, path_len);\n            q += path_len;\n            if (path[path_len - 1] != '/')\n                *q++ = '/';\n            memcpy(q, name, name_len + 1);\n        }\n    }\n    return d;\n}\n\nint namelist_cmp(const char *a, const char *b)\n{\n    /* compare strings in modified lexicographical order */\n    for (;;) {\n        int ca = (unsigned char)*a++;\n        int cb = (unsigned char)*b++;\n        if (isdigit(ca) && isdigit(cb)) {\n            int na = ca - '0';\n            int nb = cb - '0';\n            while (isdigit(ca = (unsigned char)*a++))\n                na = na * 10 + ca - '0';\n            while (isdigit(cb = (unsigned char)*b++))\n                nb = nb * 10 + cb - '0';\n            if (na < nb)\n                return -1;\n            if (na > nb)\n                return +1;\n        }\n        if (ca < cb)\n            return -1;\n        if (ca > cb)\n            return +1;\n        if (ca == '\\0')\n            return 0;\n    }\n}\n\nint namelist_cmp_indirect(const void *a, const void *b)\n{\n    return namelist_cmp(*(const char **)a, *(const char **)b);\n}\n\nvoid namelist_sort(namelist_t *lp)\n{\n    int i, count;\n    if (lp->count > 1) {\n        qsort(lp->array, lp->count, sizeof(*lp->array), namelist_cmp_indirect);\n        /* remove duplicates */\n        for (count = i = 1; i < lp->count; i++) {\n            if (namelist_cmp(lp->array[count - 1], lp->array[i]) == 0) {\n                free(lp->array[i]);\n            } else {\n                lp->array[count++] = lp->array[i];\n            }\n        }\n        lp->count = count;\n    }\n    lp->sorted = 1;\n}\n\nint namelist_find(namelist_t *lp, const char *name)\n{\n    int a, b, m, cmp;\n\n    if (!lp->sorted) {\n        namelist_sort(lp);\n    }\n    for (a = 0, b = lp->count; a < b;) {\n        m = a + (b - a) / 2;\n        cmp = namelist_cmp(lp->array[m], name);\n        if (cmp < 0)\n            a = m + 1;\n        else if (cmp > 0)\n            b = m;\n        else\n            return m;\n    }\n    return -1;\n}\n\nvoid namelist_add(namelist_t *lp, const char *base, const char *name)\n{\n    char *s;\n\n    s = compose_path(base, name);\n    if (!s)\n        goto fail;\n    if (lp->count == lp->size) {\n        size_t newsize = lp->size + (lp->size >> 1) + 4;\n        char **a = realloc(lp->array, sizeof(lp->array[0]) * newsize);\n        if (!a)\n            goto fail;\n        lp->array = a;\n        lp->size = newsize;\n    }\n    lp->array[lp->count] = s;\n    lp->count++;\n    return;\nfail:\n    fatal(1, \"allocation failure\\n\");\n}\n\nvoid namelist_load(namelist_t *lp, const char *filename)\n{\n    char buf[1024];\n    char *base_name;\n    FILE *f;\n\n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror_exit(1, filename);\n    }\n    base_name = get_basename(filename);\n\n    while (fgets(buf, sizeof(buf), f) != NULL) {\n        char *p = str_strip(buf);\n        if (*p == '#' || *p == ';' || *p == '\\0')\n            continue;  /* line comment */\n        \n        namelist_add(lp, base_name, p);\n    }\n    free(base_name);\n    fclose(f);\n}\n\nvoid namelist_add_from_error_file(namelist_t *lp, const char *file)\n{\n    const char *p, *p0;\n    char *pp;\n\n    for (p = file; (p = strstr(p, \".js:\")) != NULL; p++) {\n        for (p0 = p; p0 > file && p0[-1] != '\\n'; p0--)\n            continue;\n        pp = strdup_len(p0, p + 3 - p0);\n        namelist_add(lp, NULL, pp);\n        free(pp);\n    }\n}\n\nvoid namelist_free(namelist_t *lp)\n{\n    while (lp->count > 0) {\n        free(lp->array[--lp->count]);\n    }\n    free(lp->array);\n    lp->array = NULL;\n    lp->size = 0;\n}\n\nstatic int add_test_file(const char *filename, const struct stat *ptr, int flag)\n{\n    namelist_t *lp = &test_list;\n    if (has_suffix(filename, \".js\") && !has_suffix(filename, \"_FIXTURE.js\"))\n        namelist_add(lp, NULL, filename);\n    return 0;\n}\n\n/* find js files from the directory tree and sort the list */\nstatic void enumerate_tests(const char *path)\n{\n    namelist_t *lp = &test_list;\n    int start = lp->count;\n    ftw(path, add_test_file, 100);\n    qsort(lp->array + start, lp->count - start, sizeof(*lp->array),\n          namelist_cmp_indirect);\n}\n\nstatic JSValue js_print(JSContext *ctx, JSValueConst this_val,\n                        int argc, JSValueConst *argv)\n{\n    int i;\n    const char *str;\n\n    if (outfile) {\n        for (i = 0; i < argc; i++) {\n            if (i != 0)\n                fputc(' ', outfile);\n            str = JS_ToCString(ctx, argv[i]);\n            if (!str)\n                return JS_EXCEPTION;\n            if (!strcmp(str, \"Test262:AsyncTestComplete\")) {\n                async_done++;\n            } else if (strstart(str, \"Test262:AsyncTestFailure\", NULL)) {\n                async_done = 2; /* force an error */\n            }\n            fputs(str, outfile);\n            JS_FreeCString(ctx, str);\n        }\n        fputc('\\n', outfile);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_detachArrayBuffer(JSContext *ctx, JSValue this_val,\n                                    int argc, JSValue *argv)\n{\n    JS_DetachArrayBuffer(ctx, argv[0]);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_evalScript(JSContext *ctx, JSValue this_val,\n                             int argc, JSValue *argv)\n{\n    const char *str;\n    size_t len;\n    JSValue ret;\n    str = JS_ToCStringLen(ctx, &len, argv[0]);\n    if (!str)\n        return JS_EXCEPTION;\n    ret = JS_Eval(ctx, str, len, \"<evalScript>\", JS_EVAL_TYPE_GLOBAL);\n    JS_FreeCString(ctx, str);\n    return ret;\n}\n\n#ifdef CONFIG_AGENT\n\n#include <pthread.h>\n\ntypedef struct {\n    struct list_head link;\n    pthread_t tid;\n    char *script;\n    JSValue broadcast_func;\n    BOOL broadcast_pending;\n    JSValue broadcast_sab; /* in the main context */\n    uint8_t *broadcast_sab_buf;\n    size_t broadcast_sab_size;\n    int32_t broadcast_val;\n} Test262Agent;\n\ntypedef struct {\n    struct list_head link;\n    char *str;\n} AgentReport;\n\nstatic JSValue add_helpers1(JSContext *ctx);\nstatic void add_helpers(JSContext *ctx);\n\nstatic pthread_mutex_t agent_mutex = PTHREAD_MUTEX_INITIALIZER;\nstatic pthread_cond_t agent_cond = PTHREAD_COND_INITIALIZER;\n/* list of Test262Agent.link */\nstatic struct list_head agent_list = LIST_HEAD_INIT(agent_list);\n\nstatic pthread_mutex_t report_mutex = PTHREAD_MUTEX_INITIALIZER;\n/* list of AgentReport.link */\nstatic struct list_head report_list = LIST_HEAD_INIT(report_list);\n\nstatic void *agent_start(void *arg)\n{\n    Test262Agent *agent = arg;\n    JSRuntime *rt;\n    JSContext *ctx;\n    JSValue ret_val;\n    int ret;\n    \n    rt = JS_NewRuntime();\n    if (rt == NULL) {\n        fatal(1, \"JS_NewRuntime failure\");\n    }        \n    ctx = JS_NewContext(rt);\n    if (ctx == NULL) {\n        JS_FreeRuntime(rt);\n        fatal(1, \"JS_NewContext failure\");\n    }\n    JS_SetContextOpaque(ctx, agent);\n    JS_SetRuntimeInfo(rt, \"agent\");\n    JS_SetCanBlock(rt, TRUE);\n    \n    add_helpers(ctx);\n    ret_val = JS_Eval(ctx, agent->script, strlen(agent->script),\n                      \"<evalScript>\", JS_EVAL_TYPE_GLOBAL);\n    free(agent->script);\n    agent->script = NULL;\n    if (JS_IsException(ret_val))\n        js_std_dump_error(ctx);\n    JS_FreeValue(ctx, ret_val);\n    \n    for(;;) {\n        JSContext *ctx1;\n        ret = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1);\n        if (ret < 0) {\n            js_std_dump_error(ctx);\n            break;\n        } else if (ret == 0) {\n            if (JS_IsUndefined(agent->broadcast_func)) {\n                break;\n            } else {\n                JSValue args[2];\n                \n                pthread_mutex_lock(&agent_mutex);\n                while (!agent->broadcast_pending) {\n                    pthread_cond_wait(&agent_cond, &agent_mutex);\n                }\n                \n                agent->broadcast_pending = FALSE;\n                pthread_cond_signal(&agent_cond);\n\n                pthread_mutex_unlock(&agent_mutex);\n\n                args[0] = JS_NewArrayBuffer(ctx, agent->broadcast_sab_buf,\n                                            agent->broadcast_sab_size,\n                                            NULL, NULL, TRUE);\n                args[1] = JS_NewInt32(ctx, agent->broadcast_val);\n                ret_val = JS_Call(ctx, agent->broadcast_func, JS_UNDEFINED,\n                                  2, (JSValueConst *)args);\n                JS_FreeValue(ctx, args[0]);\n                JS_FreeValue(ctx, args[1]);\n                if (JS_IsException(ret_val))\n                    js_std_dump_error(ctx);\n                JS_FreeValue(ctx, ret_val);\n                JS_FreeValue(ctx, agent->broadcast_func);\n                agent->broadcast_func = JS_UNDEFINED;\n            }\n        }\n    }\n    JS_FreeValue(ctx, agent->broadcast_func);\n\n    JS_FreeContext(ctx);\n    JS_FreeRuntime(rt);\n    return NULL;\n}\n\nstatic JSValue js_agent_start(JSContext *ctx, JSValue this_val,\n                              int argc, JSValue *argv)\n{\n    const char *script;\n    Test262Agent *agent;\n\n    if (JS_GetContextOpaque(ctx) != NULL)\n        return JS_ThrowTypeError(ctx, \"cannot be called inside an agent\");\n    \n    script = JS_ToCString(ctx, argv[0]);\n    if (!script)\n        return JS_EXCEPTION;\n    agent = malloc(sizeof(*agent));\n    memset(agent, 0, sizeof(*agent));\n    agent->broadcast_func = JS_UNDEFINED;\n    agent->broadcast_sab = JS_UNDEFINED;\n    agent->script = strdup(script);\n    JS_FreeCString(ctx, script);\n    list_add_tail(&agent->link, &agent_list);\n    pthread_create(&agent->tid, NULL, agent_start, agent);\n    return JS_UNDEFINED;\n}\n\nstatic void js_agent_free(JSContext *ctx)\n{\n    struct list_head *el, *el1;\n    Test262Agent *agent;\n    \n    list_for_each_safe(el, el1, &agent_list) {\n        agent = list_entry(el, Test262Agent, link);\n        pthread_join(agent->tid, NULL);\n        JS_FreeValue(ctx, agent->broadcast_sab);\n        list_del(&agent->link);\n        free(agent);\n    }\n}\n \nstatic JSValue js_agent_leaving(JSContext *ctx, JSValue this_val,\n                                int argc, JSValue *argv)\n{\n    Test262Agent *agent = JS_GetContextOpaque(ctx);\n    if (!agent)\n        return JS_ThrowTypeError(ctx, \"must be called inside an agent\");\n    /* nothing to do */\n    return JS_UNDEFINED;\n}\n\nstatic BOOL is_broadcast_pending(void)\n{\n    struct list_head *el;\n    Test262Agent *agent;\n    list_for_each(el, &agent_list) {\n        agent = list_entry(el, Test262Agent, link);\n        if (agent->broadcast_pending)\n            return TRUE;\n    }\n    return FALSE;\n}\n\nstatic JSValue js_agent_broadcast(JSContext *ctx, JSValue this_val,\n                                  int argc, JSValue *argv)\n{\n    JSValueConst sab = argv[0];\n    struct list_head *el;\n    Test262Agent *agent;\n    uint8_t *buf;\n    size_t buf_size;\n    int32_t val;\n    \n    if (JS_GetContextOpaque(ctx) != NULL)\n        return JS_ThrowTypeError(ctx, \"cannot be called inside an agent\");\n    \n    buf = JS_GetArrayBuffer(ctx, &buf_size, sab);\n    if (!buf)\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &val, argv[1]))\n        return JS_EXCEPTION;\n    \n    /* broadcast the values and wait until all agents have started\n       calling their callbacks */\n    pthread_mutex_lock(&agent_mutex);\n    list_for_each(el, &agent_list) {\n        agent = list_entry(el, Test262Agent, link);\n        agent->broadcast_pending = TRUE;\n        /* the shared array buffer is used by the thread, so increment\n           its refcount */\n        agent->broadcast_sab = JS_DupValue(ctx, sab);\n        agent->broadcast_sab_buf = buf;\n        agent->broadcast_sab_size = buf_size;\n        agent->broadcast_val = val;\n    }\n    pthread_cond_broadcast(&agent_cond);\n\n    while (is_broadcast_pending()) {\n        pthread_cond_wait(&agent_cond, &agent_mutex);\n    }\n    pthread_mutex_unlock(&agent_mutex);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_agent_receiveBroadcast(JSContext *ctx, JSValue this_val,\n                                         int argc, JSValue *argv)\n{\n    Test262Agent *agent = JS_GetContextOpaque(ctx);\n    if (!agent)\n        return JS_ThrowTypeError(ctx, \"must be called inside an agent\");\n    if (!JS_IsFunction(ctx, argv[0]))\n        return JS_ThrowTypeError(ctx, \"expecting function\");\n    JS_FreeValue(ctx, agent->broadcast_func);\n    agent->broadcast_func = JS_DupValue(ctx, argv[0]);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_agent_sleep(JSContext *ctx, JSValue this_val,\n                              int argc, JSValue *argv)\n{\n    uint32_t duration;\n    if (JS_ToUint32(ctx, &duration, argv[0]))\n        return JS_EXCEPTION;\n    usleep(duration * 1000);\n    return JS_UNDEFINED;\n}\n\nstatic int64_t get_clock_ms(void)\n{\n    struct timespec ts;\n    clock_gettime(CLOCK_MONOTONIC, &ts);\n    return (uint64_t)ts.tv_sec * 1000 + (ts.tv_nsec / 1000000);\n}\n\nstatic JSValue js_agent_monotonicNow(JSContext *ctx, JSValue this_val,\n                                     int argc, JSValue *argv)\n{\n    return JS_NewInt64(ctx, get_clock_ms());\n}\n\nstatic JSValue js_agent_getReport(JSContext *ctx, JSValue this_val,\n                                  int argc, JSValue *argv)\n{\n    AgentReport *rep;\n    JSValue ret;\n\n    pthread_mutex_lock(&report_mutex);\n    if (list_empty(&report_list)) {\n        rep = NULL;\n    } else {\n        rep = list_entry(report_list.next, AgentReport, link);\n        list_del(&rep->link);\n    }\n    pthread_mutex_unlock(&report_mutex);\n    if (rep) {\n        ret = JS_NewString(ctx, rep->str);\n        free(rep->str);\n        free(rep);\n    } else {\n        ret = JS_NULL;\n    }\n    return ret;\n}\n\nstatic JSValue js_agent_report(JSContext *ctx, JSValue this_val,\n                               int argc, JSValue *argv)\n{\n    const char *str;\n    AgentReport *rep;\n\n    str = JS_ToCString(ctx, argv[0]);\n    if (!str)\n        return JS_EXCEPTION;\n    rep = malloc(sizeof(*rep));\n    rep->str = strdup(str);\n    JS_FreeCString(ctx, str);\n    \n    pthread_mutex_lock(&report_mutex);\n    list_add_tail(&rep->link, &report_list);\n    pthread_mutex_unlock(&report_mutex);\n    return JS_UNDEFINED;\n}\n\nstatic const JSCFunctionListEntry js_agent_funcs[] = {\n    /* only in main */\n    JS_CFUNC_DEF(\"start\", 1, js_agent_start ),\n    JS_CFUNC_DEF(\"getReport\", 0, js_agent_getReport ),\n    JS_CFUNC_DEF(\"broadcast\", 2, js_agent_broadcast ),\n    /* only in agent */\n    JS_CFUNC_DEF(\"report\", 1, js_agent_report ),\n    JS_CFUNC_DEF(\"leaving\", 0, js_agent_leaving ),\n    JS_CFUNC_DEF(\"receiveBroadcast\", 1, js_agent_receiveBroadcast ),\n    /* in both */\n    JS_CFUNC_DEF(\"sleep\", 1, js_agent_sleep ),\n    JS_CFUNC_DEF(\"monotonicNow\", 0, js_agent_monotonicNow ),\n};\n    \nstatic JSValue js_new_agent(JSContext *ctx)\n{\n    JSValue agent;\n    agent = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, agent, js_agent_funcs,\n                               countof(js_agent_funcs));\n    return agent;\n}\n#endif\n\nstatic JSValue js_createRealm(JSContext *ctx, JSValue this_val,\n                              int argc, JSValue *argv)\n{\n    JSContext *ctx1;\n    JSValue ret;\n    \n    ctx1 = JS_NewContext(JS_GetRuntime(ctx));\n    if (!ctx1)\n        return JS_ThrowOutOfMemory(ctx);\n    ret = add_helpers1(ctx1);\n    /* ctx1 has a refcount so it stays alive */\n    JS_FreeContext(ctx1);\n    return ret;\n}\n\nstatic JSValue js_IsHTMLDDA(JSContext *ctx, JSValue this_val,\n                            int argc, JSValue *argv)\n{\n    return JS_NULL;\n}\n\nstatic JSValue add_helpers1(JSContext *ctx)\n{\n    JSValue global_obj;\n    JSValue obj262, obj;\n    \n    global_obj = JS_GetGlobalObject(ctx);\n\n    JS_SetPropertyStr(ctx, global_obj, \"print\",\n                      JS_NewCFunction(ctx, js_print, \"print\", 1));\n\n    /* $262 special object used by the tests */\n    obj262 = JS_NewObject(ctx);\n    JS_SetPropertyStr(ctx, obj262, \"detachArrayBuffer\",\n                      JS_NewCFunction(ctx, js_detachArrayBuffer,\n                                      \"detachArrayBuffer\", 1));\n    JS_SetPropertyStr(ctx, obj262, \"evalScript\",\n                      JS_NewCFunction(ctx, js_evalScript,\n                                      \"evalScript\", 1));\n    JS_SetPropertyStr(ctx, obj262, \"codePointRange\",\n                      JS_NewCFunction(ctx, js_string_codePointRange,\n                                      \"codePointRange\", 2));\n#ifdef CONFIG_AGENT\n    JS_SetPropertyStr(ctx, obj262, \"agent\", js_new_agent(ctx));\n#endif\n\n    JS_SetPropertyStr(ctx, obj262, \"global\",\n                      JS_DupValue(ctx, global_obj));\n    JS_SetPropertyStr(ctx, obj262, \"createRealm\",\n                      JS_NewCFunction(ctx, js_createRealm,\n                                      \"createRealm\", 0));\n    obj = JS_NewCFunction(ctx, js_IsHTMLDDA, \"IsHTMLDDA\", 0);\n    JS_SetIsHTMLDDA(ctx, obj);\n    JS_SetPropertyStr(ctx, obj262, \"IsHTMLDDA\", obj);\n\n    JS_SetPropertyStr(ctx, global_obj, \"$262\", JS_DupValue(ctx, obj262));\n    \n    JS_FreeValue(ctx, global_obj);\n    return obj262;\n}\n\nstatic void add_helpers(JSContext *ctx)\n{\n    JS_FreeValue(ctx, add_helpers1(ctx));\n}\n\nstatic char *load_file(const char *filename, size_t *lenp)\n{\n    char *buf;\n    size_t buf_len;\n    buf = (char *)js_load_file(NULL, &buf_len, filename);\n    if (!buf)\n        perror_exit(1, filename);\n    if (lenp)\n        *lenp = buf_len;\n    return buf;\n}\n\nstatic JSModuleDef *js_module_loader_test(JSContext *ctx,\n                                          const char *module_name, void *opaque)\n{\n    size_t buf_len;\n    uint8_t *buf;\n    JSModuleDef *m;\n    JSValue func_val;\n    \n    buf = js_load_file(ctx, &buf_len, module_name);\n    if (!buf) {\n        JS_ThrowReferenceError(ctx, \"could not load module filename '%s'\",\n                               module_name);\n        return NULL;\n    }\n    \n    /* compile the module */\n    func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name,\n                       JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);\n    js_free(ctx, buf);\n    if (JS_IsException(func_val))\n        return NULL;\n    /* the module is already referenced, so we must free it */\n    m = JS_VALUE_GET_PTR(func_val);\n    JS_FreeValue(ctx, func_val);\n    return m;\n}\n\nint is_line_sep(char c)\n{\n    return (c == '\\0' || c == '\\n' || c == '\\r');\n}\n\nchar *find_line(const char *str, const char *line)\n{\n    if (str) {\n        const char *p;\n        int len = strlen(line);\n        for (p = str; (p = strstr(p, line)) != NULL; p += len + 1) {\n            if ((p == str || is_line_sep(p[-1])) && is_line_sep(p[len]))\n                return (char *)p;\n        }\n    }\n    return NULL;\n}\n\nint is_word_sep(char c)\n{\n    return (c == '\\0' || isspace((unsigned char)c) || c == ',');\n}\n\nchar *find_word(const char *str, const char *word)\n{\n    const char *p;\n    int len = strlen(word);\n    if (str && len) {\n        for (p = str; (p = strstr(p, word)) != NULL; p += len) {\n            if ((p == str || is_word_sep(p[-1])) && is_word_sep(p[len]))\n                return (char *)p;\n        }\n    }\n    return NULL;\n}\n\n/* handle exclude directories */\nvoid update_exclude_dirs(void)\n{\n    namelist_t *lp = &test_list;\n    namelist_t *ep = &exclude_list;\n    namelist_t *dp = &exclude_dir_list;\n    char *name;\n    int i, j, count;\n\n    /* split directpries from exclude_list */\n    for (count = i = 0; i < ep->count; i++) {\n        name = ep->array[i];\n        if (has_suffix(name, \"/\")) {\n            namelist_add(dp, NULL, name);\n            free(name);\n        } else {\n            ep->array[count++] = name;\n        }\n    }\n    ep->count = count;\n\n    namelist_sort(dp);\n\n    /* filter out excluded directories */\n    for (count = i = 0; i < lp->count; i++) {\n        name = lp->array[i];\n        for (j = 0; j < dp->count; j++) {\n            if (has_prefix(name, dp->array[j])) {\n                test_excluded++;\n                free(name);\n                name = NULL;\n                break;\n            }\n        }\n        if (name) {\n            lp->array[count++] = name;\n        }\n    }\n    lp->count = count;\n}\n\nvoid load_config(const char *filename)\n{\n    char buf[1024];\n    FILE *f;\n    char *base_name;\n    enum {\n        SECTION_NONE = 0,\n        SECTION_CONFIG,\n        SECTION_EXCLUDE,\n        SECTION_FEATURES,\n        SECTION_TESTS,\n    } section = SECTION_NONE;\n    int lineno = 0;\n\n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror_exit(1, filename);\n    }\n    base_name = get_basename(filename);\n    \n    while (fgets(buf, sizeof(buf), f) != NULL) {\n        char *p, *q;\n        lineno++;\n        p = str_strip(buf);\n        if (*p == '#' || *p == ';' || *p == '\\0')\n            continue;  /* line comment */\n        \n        if (*p == \"[]\"[0]) {\n            /* new section */\n            p++;\n            p[strcspn(p, \"]\")] = '\\0';\n            if (str_equal(p, \"config\"))\n                section = SECTION_CONFIG;\n            else if (str_equal(p, \"exclude\"))\n                section = SECTION_EXCLUDE;\n            else if (str_equal(p, \"features\"))\n                section = SECTION_FEATURES;\n            else if (str_equal(p, \"tests\"))\n                section = SECTION_TESTS;\n            else\n                section = SECTION_NONE;\n            continue;\n        }\n        q = strchr(p, '=');\n        if (q) {\n            /* setting: name=value */\n            *q++ = '\\0';\n            q = str_strip(q);\n        }\n        switch (section) {\n        case SECTION_CONFIG:\n            if (!q) {\n                printf(\"%s:%d: syntax error\\n\", filename, lineno);\n                continue;\n            }\n            if (str_equal(p, \"style\")) {\n                new_style = str_equal(q, \"new\");\n                continue;\n            }\n            if (str_equal(p, \"testdir\")) {\n                char *testdir = compose_path(base_name, q);\n                enumerate_tests(testdir);\n                free(testdir);\n                continue;\n            }\n            if (str_equal(p, \"harnessdir\")) {\n                harness_dir = compose_path(base_name, q);\n                continue;\n            }\n            if (str_equal(p, \"harnessexclude\")) {\n                str_append(&harness_exclude, \" \", q);\n                continue;\n            }\n            if (str_equal(p, \"features\")) {\n                str_append(&harness_features, \" \", q);\n                continue;\n            }\n            if (str_equal(p, \"skip-features\")) {\n                str_append(&harness_skip_features, \" \", q);\n                continue;\n            }\n            if (str_equal(p, \"mode\")) {\n                if (str_equal(q, \"default\") || str_equal(q, \"default-nostrict\"))\n                    test_mode = TEST_DEFAULT_NOSTRICT;\n                else if (str_equal(q, \"default-strict\"))\n                    test_mode = TEST_DEFAULT_STRICT;\n                else if (str_equal(q, \"nostrict\"))\n                    test_mode = TEST_NOSTRICT;\n                else if (str_equal(q, \"strict\"))\n                    test_mode = TEST_STRICT;\n                else if (str_equal(q, \"all\") || str_equal(q, \"both\"))\n                    test_mode = TEST_ALL;\n                else \n                    fatal(2, \"unknown test mode: %s\", q);\n                continue;\n            }\n            if (str_equal(p, \"strict\")) {\n                if (str_equal(q, \"skip\") || str_equal(q, \"no\"))\n                    test_mode = TEST_NOSTRICT;\n                continue;\n            }\n            if (str_equal(p, \"nostrict\")) {\n                if (str_equal(q, \"skip\") || str_equal(q, \"no\"))\n                    test_mode = TEST_STRICT;\n                continue;\n            }\n            if (str_equal(p, \"async\")) {\n                skip_async = !str_equal(q, \"yes\");\n                continue;\n            }\n            if (str_equal(p, \"module\")) {\n                skip_module = !str_equal(q, \"yes\");\n                continue;\n            }\n            if (str_equal(p, \"verbose\")) {\n                verbose = str_equal(q, \"yes\");\n                continue;\n            }\n            if (str_equal(p, \"errorfile\")) {\n                error_filename = compose_path(base_name, q);\n                continue;\n            }\n            if (str_equal(p, \"excludefile\")) {\n                char *path = compose_path(base_name, q);\n                namelist_load(&exclude_list, path);\n                free(path);\n                continue;\n            }\n            if (str_equal(p, \"reportfile\")) {\n                report_filename = compose_path(base_name, q);\n                continue;\n            }\n        case SECTION_EXCLUDE:\n            namelist_add(&exclude_list, base_name, p);\n            break;\n        case SECTION_FEATURES:\n            if (!q || str_equal(q, \"yes\"))\n                str_append(&harness_features, \" \", p);\n            else\n                str_append(&harness_skip_features, \" \", p);\n            break;\n        case SECTION_TESTS:\n            namelist_add(&test_list, base_name, p);\n            break;\n        default:\n            /* ignore settings in other sections */\n            break;\n        }\n    }\n    fclose(f);\n    free(base_name);\n}\n\nchar *find_error(const char *filename, int *pline, int is_strict)\n{\n    if (error_file) {\n        size_t len = strlen(filename);\n        const char *p, *q, *r;\n        int line;\n\n        for (p = error_file; (p = strstr(p, filename)) != NULL; p += len) {\n            if ((p == error_file || p[-1] == '\\n' || p[-1] == '(') && p[len] == ':') {\n                q = p + len;\n                line = 1;\n                if (*q == ':') {\n                    line = strtol(q + 1, (char**)&q, 10);\n                    if (*q == ':')\n                        q++;\n                }\n                while (*q == ' ') {\n                    q++;\n                }\n                /* check strict mode indicator */\n                if (!strstart(q, \"strict mode: \", &q) != !is_strict)\n                    continue;\n                r = q = skip_prefix(q, \"unexpected error: \");\n                r += strcspn(r, \"\\n\");\n                while (r[0] == '\\n' && r[1] && strncmp(r + 1, filename, 8)) {\n                    r++;\n                    r += strcspn(r, \"\\n\");\n                }\n                if (pline)\n                    *pline = line;\n                return strdup_len(q, r - q);\n            }\n        }\n    }\n    return NULL;\n}\n\nint skip_comments(const char *str, int line, int *pline)\n{\n    const char *p;\n    int c;\n\n    p = str;\n    while ((c = (unsigned char)*p++) != '\\0') {\n        if (isspace(c)) {\n            if (c == '\\n')\n                line++;\n            continue;\n        }\n        if (c == '/' && *p == '/') {\n            while (*++p && *p != '\\n')\n                continue;\n            continue;\n        }\n        if (c == '/' && *p == '*') {\n            for (p += 1; *p; p++) {\n                if (*p == '\\n') {\n                    line++;\n                    continue;\n                }\n                if (*p == '*' && p[1] == '/') {\n                    p += 2;\n                    break;\n                }\n            }\n            continue;\n        }\n        break;\n    }\n    if (pline)\n        *pline = line;\n\n    return p - str;\n}\n\nint longest_match(const char *str, const char *find, int pos, int *ppos, int line, int *pline)\n{\n    int len, maxlen;\n\n    maxlen = 0;\n    \n    if (*find) {\n        const char *p;\n        for (p = str + pos; *p; p++) {\n            if (*p == *find) {\n                for (len = 1; p[len] && p[len] == find[len]; len++)\n                    continue;\n                if (len > maxlen) {\n                    maxlen = len;\n                    if (ppos)\n                        *ppos = p - str;\n                    if (pline)\n                        *pline = line;\n                    if (!find[len])\n                        break;\n                }\n            }\n            if (*p == '\\n')\n                line++;\n        }\n    }\n    return maxlen;\n}\n\nstatic int eval_buf(JSContext *ctx, const char *buf, size_t buf_len,\n                    const char *filename, int is_test, int is_negative,\n                    const char *error_type, FILE *outfile, int eval_flags,\n                    int is_async)\n{\n    JSValue res_val, exception_val;\n    int ret, error_line, pos, pos_line;\n    BOOL is_error, has_error_line;\n    const char *error_name;\n    \n    pos = skip_comments(buf, 1, &pos_line);\n    error_line = pos_line;\n    has_error_line = FALSE;\n    exception_val = JS_UNDEFINED;\n    error_name = NULL;\n\n    async_done = 0; /* counter of \"Test262:AsyncTestComplete\" messages */\n\n    res_val = JS_Eval(ctx, buf, buf_len, filename, eval_flags);\n\n    if (is_async && !JS_IsException(res_val)) {\n        JS_FreeValue(ctx, res_val);\n        for(;;) {\n            JSContext *ctx1;\n            ret = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1);\n            if (ret < 0) {\n                res_val = JS_EXCEPTION;\n                break;\n            } else if (ret == 0) {\n                /* test if the test called $DONE() once */\n                if (async_done != 1) {\n                    res_val = JS_ThrowTypeError(ctx, \"$DONE() not called\");\n                } else {\n                    res_val = JS_UNDEFINED;\n                }\n                break;\n            }\n        }\n    }\n\n    if (JS_IsException(res_val)) {\n        exception_val = JS_GetException(ctx);\n        is_error = JS_IsError(ctx, exception_val);\n        /* XXX: should get the filename and line number */\n        if (outfile) {\n            if (!is_error)\n                fprintf(outfile, \"%sThrow: \", (eval_flags & JS_EVAL_FLAG_STRICT) ?\n                        \"strict mode: \" : \"\");\n            js_print(ctx, JS_NULL, 1, &exception_val);\n        }\n        if (is_error) {\n            JSValue name, stack;\n            const char *stack_str;\n        \n            name = JS_GetPropertyStr(ctx, exception_val, \"name\");\n            error_name = JS_ToCString(ctx, name);\n            stack = JS_GetPropertyStr(ctx, exception_val, \"stack\");\n            if (!JS_IsUndefined(stack)) {\n                stack_str = JS_ToCString(ctx, stack);\n                if (stack_str) {\n                    const char *p;\n                    int len;\n                    \n                    if (outfile)\n                        fprintf(outfile, \"%s\", stack_str);\n                    \n                    len = strlen(filename);\n                    p = strstr(stack_str, filename);\n                    if (p != NULL && p[len] == ':') {\n                        error_line = atoi(p + len + 1);\n                        has_error_line = TRUE;\n                    }\n                    JS_FreeCString(ctx, stack_str);\n                }\n            }\n            JS_FreeValue(ctx, stack);\n            JS_FreeValue(ctx, name);\n        }\n        if (is_negative) {\n            ret = 0;\n            if (error_type) {\n                char *error_class;\n                const char *msg;\n            \n                msg = JS_ToCString(ctx, exception_val);\n                error_class = strdup_len(msg, strcspn(msg, \":\"));\n                if (!str_equal(error_class, error_type))\n                    ret = -1;\n                free(error_class);\n                JS_FreeCString(ctx, msg);\n            }\n        } else {\n            ret = -1;\n        }\n    } else {\n        if (is_negative)\n            ret = -1;\n        else\n            ret = 0;\n    }\n\n    if (verbose && is_test) {\n        JSValue msg_val = JS_UNDEFINED;\n        const char *msg = NULL;\n        int s_line;\n        char *s = find_error(filename, &s_line, eval_flags & JS_EVAL_FLAG_STRICT);\n        const char *strict_mode = (eval_flags & JS_EVAL_FLAG_STRICT) ? \"strict mode: \" : \"\";\n\n        if (!JS_IsUndefined(exception_val)) {\n            msg_val = JS_ToString(ctx, exception_val);\n            msg = JS_ToCString(ctx, msg_val);\n        }\n        if (is_negative) {  // expect error\n            if (ret == 0) {\n                if (msg && s &&\n                    (str_equal(s, \"expected error\") ||\n                     strstart(s, \"unexpected error type:\", NULL) ||\n                     str_equal(s, msg))) {     // did not have error yet\n                    if (!has_error_line) {\n                        longest_match(buf, msg, pos, &pos, pos_line, &error_line);\n                    }\n                    printf(\"%s:%d: %sOK, now has error %s\\n\",\n                           filename, error_line, strict_mode, msg);\n                    fixed_errors++;\n                }\n            } else {\n                if (!s) {   // not yet reported\n                    if (msg) {\n                        fprintf(error_out, \"%s:%d: %sunexpected error type: %s\\n\",\n                                filename, error_line, strict_mode, msg);\n                    } else {\n                        fprintf(error_out, \"%s:%d: %sexpected error\\n\",\n                                filename, error_line, strict_mode);\n                    }\n                    new_errors++;\n                }\n            }\n        } else {            // should not have error\n            if (msg) {\n                if (!s || !str_equal(s, msg)) {\n                    if (!has_error_line) {\n                        char *p = skip_prefix(msg, \"Test262 Error: \");\n                        if (strstr(p, \"Test case returned non-true value!\")) {\n                            longest_match(buf, \"runTestCase\", pos, &pos, pos_line, &error_line);\n                        } else {\n                            longest_match(buf, p, pos, &pos, pos_line, &error_line);\n                        }\n                    }\n                    fprintf(error_out, \"%s:%d: %s%s%s\\n\", filename, error_line, strict_mode,\n                            error_file ? \"unexpected error: \" : \"\", msg);\n\n                    if (s && (!str_equal(s, msg) || error_line != s_line)) {\n                        printf(\"%s:%d: %sprevious error: %s\\n\", filename, s_line, strict_mode, s);\n                        changed_errors++;\n                    } else {\n                        new_errors++;\n                    }\n                }\n            } else {\n                if (s) {\n                    printf(\"%s:%d: %sOK, fixed error: %s\\n\", filename, s_line, strict_mode, s);\n                    fixed_errors++;\n                }\n            }\n        }\n        JS_FreeValue(ctx, msg_val);\n        JS_FreeCString(ctx, msg);\n        free(s);\n    }\n    JS_FreeCString(ctx, error_name);\n    JS_FreeValue(ctx, exception_val);\n    JS_FreeValue(ctx, res_val);\n    return ret;\n}\n\nstatic int eval_file(JSContext *ctx, const char *base, const char *p,\n                     int eval_flags)\n{\n    char *buf;\n    size_t buf_len;\n    char *filename = compose_path(base, p);\n\n    buf = load_file(filename, &buf_len);\n    if (!buf) {\n        warning(\"cannot load %s\", filename);\n        goto fail;\n    }\n    if (eval_buf(ctx, buf, buf_len, filename, FALSE, FALSE, NULL, stderr,\n                 eval_flags, FALSE)) {\n        warning(\"error evaluating %s\", filename);\n        goto fail;\n    }\n    free(buf);\n    free(filename);\n    return 0;\n\nfail:\n    free(buf);\n    free(filename);\n    return 1;\n}\n\nchar *extract_desc(const char *buf, char style)\n{\n    const char *p, *desc_start;\n    char *desc;\n    int len;\n    \n    p = buf;\n    while (*p != '\\0') {\n        if (p[0] == '/' && p[1] == '*' && p[2] == style && p[3] != '/') {\n            p += 3;\n            desc_start = p;\n            while (*p != '\\0' && (p[0] != '*' || p[1] != '/'))\n                p++;\n            if (*p == '\\0') {\n                warning(\"Expecting end of desc comment\");\n                return NULL;\n            }\n            len = p - desc_start;\n            desc = malloc(len + 1);\n            memcpy(desc, desc_start, len);\n            desc[len] = '\\0';\n            return desc;\n        } else {\n            p++;\n        }\n    }\n    return NULL;\n}\n\nstatic char *find_tag(char *desc, const char *tag, int *state)\n{\n    char *p;\n    p = strstr(desc, tag);\n    if (p) {\n        p += strlen(tag);\n        *state = 0;\n    }\n    return p;\n}\n\nstatic char *get_option(char **pp, int *state)\n{\n    char *p, *p0, *option = NULL;\n    if (*pp) {\n        for (p = *pp;; p++) {\n            switch (*p) {\n            case '[':\n                *state += 1;\n                continue;\n            case ']':\n                *state -= 1;\n                if (*state > 0)\n                    continue;\n                p = NULL;\n                break;\n            case ' ':\n            case '\\t':\n            case '\\r':\n            case ',':\n            case '-':\n                continue;\n            case '\\n':\n                if (*state > 0 || p[1] == ' ')\n                    continue;\n                p = NULL;\n                break;\n            case '\\0':\n                p = NULL;\n                break;\n            default:\n                p0 = p;\n                p += strcspn(p0, \" \\t\\r\\n,]\");\n                option = strdup_len(p0, p - p0);\n                break;\n            }\n            break;\n        }\n        *pp = p;\n    }\n    return option;\n}\n\nvoid update_stats(JSRuntime *rt, const char *filename) {\n    JSMemoryUsage stats;\n    JS_ComputeMemoryUsage(rt, &stats);\n    if (stats_count++ == 0) {\n        stats_avg = stats_all = stats_min = stats_max = stats;\n        stats_min_filename = strdup(filename);\n        stats_max_filename = strdup(filename);\n    } else {\n        if (stats_max.malloc_size < stats.malloc_size) {\n            stats_max = stats;\n            free(stats_max_filename);\n            stats_max_filename = strdup(filename);\n        }\n        if (stats_min.malloc_size > stats.malloc_size) {\n            stats_min = stats;\n            free(stats_min_filename);\n            stats_min_filename = strdup(filename);\n        }\n\n#define update(f)  stats_avg.f = (stats_all.f += stats.f) / stats_count\n        update(malloc_count);\n        update(malloc_size);\n        update(memory_used_count);\n        update(memory_used_size);\n        update(atom_count);\n        update(atom_size);\n        update(str_count);\n        update(str_size);\n        update(obj_count);\n        update(obj_size);\n        update(prop_count);\n        update(prop_size);\n        update(shape_count);\n        update(shape_size);\n        update(js_func_count);\n        update(js_func_size);\n        update(js_func_code_size);\n        update(js_func_pc2line_count);\n        update(js_func_pc2line_size);\n        update(c_func_count);\n        update(array_count);\n        update(fast_array_count);\n        update(fast_array_elements);\n    }\n#undef update\n}\n\nint run_test_buf(const char *filename, char *harness, namelist_t *ip,\n                 char *buf, size_t buf_len, const char* error_type,\n                 int eval_flags, BOOL is_negative, BOOL is_async,\n                 BOOL can_block)\n{\n    JSRuntime *rt;\n    JSContext *ctx;\n    int i, ret;\n        \n    rt = JS_NewRuntime();\n    if (rt == NULL) {\n        fatal(1, \"JS_NewRuntime failure\");\n    }        \n    ctx = JS_NewContext(rt);\n    if (ctx == NULL) {\n        JS_FreeRuntime(rt);\n        fatal(1, \"JS_NewContext failure\");\n    }\n    JS_SetRuntimeInfo(rt, filename);\n\n    JS_SetCanBlock(rt, can_block);\n    \n    /* loader for ES6 modules */\n    JS_SetModuleLoaderFunc(rt, NULL, js_module_loader_test, NULL);\n        \n    add_helpers(ctx);\n\n    for (i = 0; i < ip->count; i++) {\n        if (eval_file(ctx, harness, ip->array[i],\n                      JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_STRIP)) {\n            fatal(1, \"error including %s for %s\", ip->array[i], filename);\n        }\n    }\n\n    ret = eval_buf(ctx, buf, buf_len, filename, TRUE, is_negative,\n                   error_type, outfile, eval_flags, is_async);\n    ret = (ret != 0);\n        \n    if (dump_memory) {\n        update_stats(rt, filename);\n    }\n#ifdef CONFIG_AGENT\n    js_agent_free(ctx);\n#endif\n    JS_FreeContext(ctx);\n    JS_FreeRuntime(rt);\n\n    test_count++;\n    if (ret) {\n        test_failed++;\n        if (outfile) {\n            /* do not output a failure number to minimize diff */\n            fprintf(outfile, \"  FAILED\\n\");\n        }\n    }\n    return ret;\n}\n\nint run_test(const char *filename, int index)\n{\n    char harnessbuf[1024];\n    char *harness;\n    char *buf;\n    size_t buf_len;\n    char *desc, *p;\n    char *error_type;\n    int ret, eval_flags, use_strict, use_nostrict;\n    BOOL is_negative, is_nostrict, is_onlystrict, is_async, is_module, skip;\n    BOOL can_block;\n    namelist_t include_list = { 0 }, *ip = &include_list;\n    \n    is_nostrict = is_onlystrict = is_negative = is_async = is_module = skip = FALSE;\n    can_block = TRUE;\n    error_type = NULL;\n    buf = load_file(filename, &buf_len);\n\n    harness = harness_dir;\n\n    if (new_style) {\n        if (!harness) {\n            p = strstr(filename, \"test/\");\n            if (p) {\n                snprintf(harnessbuf, sizeof(harnessbuf), \"%.*s%s\",\n                         (int)(p - filename), filename, \"harness\");\n            }\n            harness = harnessbuf;\n        }\n        namelist_add(ip, NULL, \"sta.js\");\n        namelist_add(ip, NULL, \"assert.js\");\n        /* extract the YAML frontmatter */\n        desc = extract_desc(buf, '-');\n        if (desc) {\n            char *ifile, *option;\n            int state;\n            p = find_tag(desc, \"includes:\", &state);\n            if (p) {\n                while ((ifile = get_option(&p, &state)) != NULL) {\n                    // skip unsupported harness files\n                    if (find_word(harness_exclude, ifile)) {\n                        skip |= 1;\n                    } else {\n                        namelist_add(ip, NULL, ifile);\n                    }\n                    free(ifile);\n                }\n            }\n            p = find_tag(desc, \"flags:\", &state);\n            if (p) {\n                while ((option = get_option(&p, &state)) != NULL) {\n                    if (str_equal(option, \"noStrict\") ||\n                        str_equal(option, \"raw\")) {\n                        is_nostrict = TRUE;\n                        skip |= (test_mode == TEST_STRICT);\n                    }\n                    else if (str_equal(option, \"onlyStrict\")) {\n                        is_onlystrict = TRUE;\n                        skip |= (test_mode == TEST_NOSTRICT);\n                    }\n                    else if (str_equal(option, \"async\")) {\n                        is_async = TRUE;\n                        skip |= skip_async;\n                    }\n                    else if (str_equal(option, \"module\")) {\n                        is_module = TRUE;\n                        skip |= skip_module;\n                    }\n                    else if (str_equal(option, \"CanBlockIsFalse\")) {\n                        can_block = FALSE;\n                    }\n                    free(option);\n                }\n            }\n            p = find_tag(desc, \"negative:\", &state);\n            if (p) {\n                /* XXX: should extract the phase */\n                char *q = find_tag(p, \"type:\", &state);\n                if (q) {\n                    while (isspace(*q))\n                        q++;\n                    error_type = strdup_len(q, strcspn(q, \" \\n\"));\n                }\n                is_negative = TRUE;\n            }\n            p = find_tag(desc, \"features:\", &state);\n            if (p) {\n                while ((option = get_option(&p, &state)) != NULL) {\n                    if (find_word(harness_features, option)) {\n                        /* feature is enabled */\n                    } else if (find_word(harness_skip_features, option)) {\n                        /* skip disabled feature */\n                        skip |= 1;\n                    } else {\n                        /* feature is not listed: skip and warn */\n                        printf(\"%s:%d: unknown feature: %s\\n\", filename, 1, option);\n                        skip |= 1;\n                    }\n                    free(option);\n                }\n            }\n            free(desc);\n        }\n        if (is_async)\n            namelist_add(ip, NULL, \"doneprintHandle.js\");\n    } else {\n        char *ifile;\n\n        if (!harness) {\n            p = strstr(filename, \"test/\");\n            if (p) {\n                snprintf(harnessbuf, sizeof(harnessbuf), \"%.*s%s\",\n                         (int)(p - filename), filename, \"test/harness\");\n            }\n            harness = harnessbuf;\n        }\n\n        namelist_add(ip, NULL, \"sta.js\");\n\n        /* include extra harness files */\n        for (p = buf; (p = strstr(p, \"$INCLUDE(\\\"\")) != NULL; p++) {\n            p += 10;\n            ifile = strdup_len(p, strcspn(p, \"\\\"\"));\n            // skip unsupported harness files\n            if (find_word(harness_exclude, ifile)) {\n                skip |= 1;\n            } else {\n                namelist_add(ip, NULL, ifile);\n            }\n            free(ifile);\n        }\n\n        /* locate the old style configuration comment */\n        desc = extract_desc(buf, '*');\n        if (desc) {\n            if (strstr(desc, \"@noStrict\")) {\n                is_nostrict = TRUE;\n                skip |= (test_mode == TEST_STRICT);\n            }\n            if (strstr(desc, \"@onlyStrict\")) {\n                is_onlystrict = TRUE;\n                skip |= (test_mode == TEST_NOSTRICT);\n            }\n            if (strstr(desc, \"@negative\")) {\n                /* XXX: should extract the regex to check error type */\n                is_negative = TRUE;\n            }\n            free(desc);\n        }\n    }\n\n    if (outfile && index >= 0) {\n        fprintf(outfile, \"%d: %s%s%s%s%s%s%s\\n\", index, filename,\n                is_nostrict ? \"  @noStrict\" : \"\",\n                is_onlystrict ? \"  @onlyStrict\" : \"\",\n                is_async ? \"  async\" : \"\",\n                is_module ? \"  module\" : \"\",\n                is_negative ? \"  @negative\" : \"\",\n                skip ? \"  SKIPPED\" : \"\");\n        fflush(outfile);\n    }\n\n    use_strict = use_nostrict = 0;\n    /* XXX: should remove 'test_mode' or simplify it just to force\n       strict or non strict mode for single file tests */\n    switch (test_mode) {\n    case TEST_DEFAULT_NOSTRICT:\n        if (is_onlystrict)\n            use_strict = 1;\n        else\n            use_nostrict = 1;\n        break;\n    case TEST_DEFAULT_STRICT:\n        if (is_nostrict)\n            use_nostrict = 1;\n        else\n            use_strict = 1;\n        break;\n    case TEST_NOSTRICT:\n        if (!is_onlystrict)\n            use_nostrict = 1;\n        break;\n    case TEST_STRICT:\n        if (!is_nostrict)\n            use_strict = 1;\n        break;\n    case TEST_ALL:\n        if (is_module) {\n            use_nostrict = 1;\n        } else {\n            if (!is_nostrict)\n                use_strict = 1;\n            if (!is_onlystrict)\n                use_nostrict = 1;\n        }\n        break;\n    }\n\n    if (skip || use_strict + use_nostrict == 0) {\n        test_skipped++;\n        ret = -2;\n    } else {\n        clock_t clocks;\n\n        if (is_module) {\n            eval_flags = JS_EVAL_TYPE_MODULE;\n        } else {\n            eval_flags = JS_EVAL_TYPE_GLOBAL;\n        }\n        clocks = clock();\n        ret = 0;\n        if (use_nostrict) {\n            ret = run_test_buf(filename, harness, ip, buf, buf_len,\n                               error_type, eval_flags, is_negative, is_async,\n                               can_block);\n        }\n        if (use_strict) {\n            ret |= run_test_buf(filename, harness, ip, buf, buf_len,\n                                error_type, eval_flags | JS_EVAL_FLAG_STRICT,\n                                is_negative, is_async, can_block);\n        }\n        clocks = clock() - clocks;\n        if (outfile && index >= 0 && clocks >= CLOCKS_PER_SEC / 10) {\n            /* output timings for tests that take more than 100 ms */\n            fprintf(outfile, \" time: %d ms\\n\", (int)(clocks * 1000LL / CLOCKS_PER_SEC));\n        }\n    }\n    namelist_free(&include_list);\n    free(error_type);\n    free(buf);\n\n    return ret;\n}\n\n/* run a test when called by test262-harness+eshost */\nint run_test262_harness_test(const char *filename, BOOL is_module)\n{\n    JSRuntime *rt;\n    JSContext *ctx;\n    char *buf;\n    size_t buf_len;\n    int eval_flags, ret_code, ret;\n    JSValue res_val;\n    BOOL can_block;\n    \n    outfile = stdout; /* for js_print */\n\n    rt = JS_NewRuntime();\n    if (rt == NULL) {\n        fatal(1, \"JS_NewRuntime failure\");\n    }        \n    ctx = JS_NewContext(rt);\n    if (ctx == NULL) {\n        JS_FreeRuntime(rt);\n        fatal(1, \"JS_NewContext failure\");\n    }\n    JS_SetRuntimeInfo(rt, filename);\n\n    can_block = TRUE;\n    JS_SetCanBlock(rt, can_block);\n    \n    /* loader for ES6 modules */\n    JS_SetModuleLoaderFunc(rt, NULL, js_module_loader_test, NULL);\n        \n    add_helpers(ctx);\n\n    buf = load_file(filename, &buf_len);\n\n    if (is_module) {\n      eval_flags = JS_EVAL_TYPE_MODULE;\n    } else {\n      eval_flags = JS_EVAL_TYPE_GLOBAL;\n    }\n    res_val = JS_Eval(ctx, buf, buf_len, filename, eval_flags);\n    ret_code = 0;\n    if (JS_IsException(res_val)) {\n       js_std_dump_error(ctx);\n       ret_code = 1;\n    } else {\n        JS_FreeValue(ctx, res_val);\n        for(;;) {\n            JSContext *ctx1;\n            ret = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1);\n            if (ret < 0) {\n\t      js_std_dump_error(ctx1);\n\t      ret_code = 1;\n            } else if (ret == 0) {\n\t      break;\n            }\n        }\n    }\n    free(buf);\n#ifdef CONFIG_AGENT\n    js_agent_free(ctx);\n#endif\n    JS_FreeContext(ctx);\n    JS_FreeRuntime(rt);\n    return ret_code;\n}\n\nclock_t last_clock;\n\nvoid show_progress(int force) {\n    clock_t t = clock();\n    if (force || !last_clock || (t - last_clock) > CLOCKS_PER_SEC / 20) {\n        last_clock = t;\n        /* output progress indicator: erase end of line and return to col 0 */\n        fprintf(stderr, \"%d/%d/%d\\033[K\\r\",\n                test_failed, test_count, test_skipped);\n        fflush(stderr);\n    }\n}\n\nstatic int slow_test_threshold;\n\nvoid run_test_dir_list(namelist_t *lp, int start_index, int stop_index)\n{\n    int i;\n\n    namelist_sort(lp);\n    for (i = 0; i < lp->count; i++) {\n        const char *p = lp->array[i];\n        if (namelist_find(&exclude_list, p) >= 0) {\n            test_excluded++;\n        } else if (test_index < start_index) {\n            test_skipped++;\n        } else if (stop_index >= 0 && test_index > stop_index) {\n            test_skipped++;\n        } else {\n            int ti;\n            if (slow_test_threshold != 0) {\n                ti = get_clock_ms();\n            } else {\n                ti = 0;\n            }\n            run_test(p, test_index);\n            if (slow_test_threshold != 0) {\n                ti = get_clock_ms() - ti;\n                if (ti >= slow_test_threshold)\n                    fprintf(stderr, \"\\n%s (%d ms)\\n\", p, ti);\n            }\n            show_progress(FALSE);\n        }\n        test_index++;\n    }\n    show_progress(TRUE);\n}\n\nvoid help(void)\n{\n    printf(\"run-test262 version \" CONFIG_VERSION \"\\n\"\n           \"usage: run-test262 [options] {-f file ... | [dir_list] [index range]}\\n\"\n           \"-h             help\\n\"\n           \"-a             run tests in strict and nostrict modes\\n\"\n           \"-m             print memory usage summary\\n\"\n           \"-n             use new style harness\\n\"\n           \"-N             run test prepared by test262-harness+eshost\\n\"\n           \"-s             run tests in strict mode, skip @nostrict tests\\n\"\n           \"-E             only run tests from the error file\\n\"\n           \"-u             update error file\\n\"\n           \"-v             verbose: output error messages\\n\"\n           \"-T duration    display tests taking more than 'duration' ms\\n\"\n           \"-c file        read configuration from 'file'\\n\"\n           \"-d dir         run all test files in directory tree 'dir'\\n\"\n           \"-e file        load the known errors from 'file'\\n\"\n           \"-f file        execute single test from 'file'\\n\"\n           \"-r file        set the report file name (default=none)\\n\"\n           \"-x file        exclude tests listed in 'file'\\n\");\n    exit(1);\n}\n\nchar *get_opt_arg(const char *option, char *arg)\n{\n    if (!arg) {\n        fatal(2, \"missing argument for option %s\", option);\n    }\n    return arg;\n}\n\nint main(int argc, char **argv)\n{\n    int optind, start_index, stop_index;\n    BOOL is_dir_list;\n    BOOL only_check_errors = FALSE;\n    const char *filename;\n    BOOL is_test262_harness = FALSE;\n    BOOL is_module = FALSE;\n\n#if !defined(_WIN32)\n    /* Date tests assume California local time */\n    setenv(\"TZ\", \"America/Los_Angeles\", 1);\n#endif\n\n    /* cannot use getopt because we want to pass the command line to\n       the script */\n    optind = 1;\n    is_dir_list = TRUE;\n    while (optind < argc) {\n        char *arg = argv[optind];\n        if (*arg != '-')\n            break;\n        optind++;\n        if (str_equal(arg, \"-h\")) {\n            help();\n        } else if (str_equal(arg, \"-m\")) {\n            dump_memory++;\n        } else if (str_equal(arg, \"-n\")) {\n            new_style++;\n        } else if (str_equal(arg, \"-s\")) {\n            test_mode = TEST_STRICT;\n        } else if (str_equal(arg, \"-a\")) {\n            test_mode = TEST_ALL;\n        } else if (str_equal(arg, \"-u\")) {\n            update_errors++;\n        } else if (str_equal(arg, \"-v\")) {\n            verbose++;\n        } else if (str_equal(arg, \"-c\")) {\n            load_config(get_opt_arg(arg, argv[optind++]));\n        } else if (str_equal(arg, \"-d\")) {\n            enumerate_tests(get_opt_arg(arg, argv[optind++]));\n        } else if (str_equal(arg, \"-e\")) {\n            error_filename = get_opt_arg(arg, argv[optind++]);\n        } else if (str_equal(arg, \"-x\")) {\n            namelist_load(&exclude_list, get_opt_arg(arg, argv[optind++]));\n        } else if (str_equal(arg, \"-f\")) {\n            is_dir_list = FALSE;\n        } else if (str_equal(arg, \"-r\")) {\n            report_filename = get_opt_arg(arg, argv[optind++]);\n        } else if (str_equal(arg, \"-E\")) {\n            only_check_errors = TRUE;\n        } else if (str_equal(arg, \"-T\")) {\n            slow_test_threshold = atoi(get_opt_arg(arg, argv[optind++]));\n        } else if (str_equal(arg, \"-N\")) {\n            is_test262_harness = TRUE;\n        } else if (str_equal(arg, \"--module\")) {\n            is_module = TRUE;\n        } else {\n            fatal(1, \"unknown option: %s\", arg);\n            break;\n        }\n    }\n    \n    if (optind >= argc && !test_list.count)\n        help();\n\n    if (is_test262_harness) {\n        return run_test262_harness_test(argv[optind], is_module);\n    }\n\t\t\t       \n    error_out = stdout;\n    if (error_filename) {\n        error_file = load_file(error_filename, NULL);\n        if (only_check_errors && error_file) {\n            namelist_free(&test_list);\n            namelist_add_from_error_file(&test_list, error_file);\n        }\n        if (update_errors) {\n            free(error_file);\n            error_file = NULL;\n            error_out = fopen(error_filename, \"w\");\n            if (!error_out) {\n                perror_exit(1, error_filename);\n            }\n        }\n    }\n\n    update_exclude_dirs();\n\n    if (is_dir_list) {\n        if (optind < argc && !isdigit(argv[optind][0])) {\n            filename = argv[optind++];\n            namelist_load(&test_list, filename);\n        }\n        start_index = 0;\n        stop_index = -1;\n        if (optind < argc) {\n            start_index = atoi(argv[optind++]);\n            if (optind < argc) {\n                stop_index = atoi(argv[optind++]);\n            }\n        }\n        if (!report_filename || str_equal(report_filename, \"none\")) {\n            outfile = NULL;\n        } else if (str_equal(report_filename, \"-\")) {\n            outfile = stdout;\n        } else {\n            outfile = fopen(report_filename, \"wb\");\n            if (!outfile) {\n                perror_exit(1, report_filename);\n            }\n        }\n        run_test_dir_list(&test_list, start_index, stop_index);\n\n        if (outfile && outfile != stdout) {\n            fclose(outfile);\n            outfile = NULL;\n        }\n    } else {\n        outfile = stdout;\n        while (optind < argc) {\n            run_test(argv[optind++], -1);\n        }\n    }\n\n    if (dump_memory) {\n        if (dump_memory > 1 && stats_count > 1) {\n            printf(\"\\nMininum memory statistics for %s:\\n\\n\", stats_min_filename);\n            JS_DumpMemoryUsage(stdout, &stats_min, NULL);\n            printf(\"\\nMaximum memory statistics for %s:\\n\\n\", stats_max_filename);\n            JS_DumpMemoryUsage(stdout, &stats_max, NULL);\n        }\n        printf(\"\\nAverage memory statistics for %d tests:\\n\\n\", stats_count);\n        JS_DumpMemoryUsage(stdout, &stats_avg, NULL);\n        printf(\"\\n\");\n    }\n\n    if (is_dir_list) {\n        fprintf(stderr, \"Result: %d/%d error%s\",\n                test_failed, test_count, test_count != 1 ? \"s\" : \"\");\n        if (test_excluded)\n            fprintf(stderr, \", %d excluded\", test_excluded);\n        if (test_skipped)\n            fprintf(stderr, \", %d skipped\", test_skipped);\n        if (error_file) {\n            if (new_errors)\n                fprintf(stderr, \", %d new\", new_errors);\n            if (changed_errors)\n                fprintf(stderr, \", %d changed\", changed_errors);\n            if (fixed_errors)\n                fprintf(stderr, \", %d fixed\", fixed_errors);\n        }\n        fprintf(stderr, \"\\n\");\n    }\n\n    if (error_out && error_out != stdout) {\n        fclose(error_out);\n        error_out = NULL;\n    }\n\n    namelist_free(&test_list);\n    namelist_free(&exclude_list);\n    namelist_free(&exclude_dir_list);\n    free(harness_dir);\n    free(harness_features);\n    free(harness_exclude);\n    free(error_file);\n\n    return 0;\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/test262.conf",
    "content": "[config]\n# general settings for test262 ES6 version\n\n# framework style: old, new\nstyle=new\n\n# handle tests tagged as [noStrict]: yes, no, skip\nnostrict=yes\n\n# handle tests tagged as [strictOnly]: yes, no, skip\nstrict=yes\n\n# test mode: default, default-nostrict, default-strict, strict, nostrict, both, all\nmode=default\n\n# handle tests flagged as [async]: yes, no, skip\n# for these, load 'harness/doneprintHandle.js' prior to test\n# and expect `print('Test262:AsyncTestComplete')` to be called for \n# successful termination\nasync=yes\n\n# handle tests flagged as [module]: yes, no, skip\nmodule=yes\n\n# output error messages: yes, no\nverbose=yes\n\n# load harness files from this directory\nharnessdir=test262/harness\n\n# names of harness include files to skip\n#harnessexclude=\n\n# name of the error file for known errors\nerrorfile=test262_errors.txt\n\n# exclude tests enumerated in this file (see also [exclude] section)\n#excludefile=test262_exclude.txt\n\n# report test results to this file\nreportfile=test262_report.txt\n\n# enumerate tests from this directory\ntestdir=test262/test\n\n[features]\n# Standard language features and proposed extensions\n# list the features that are included\n# skipped features are tagged as such to avoid warnings\n\nAggregateError\nalign-detached-buffer-semantics-with-web-reality\narbitrary-module-namespace-names=skip\nArray.prototype.at=skip\nArray.prototype.flat\nArray.prototype.flatMap\nArray.prototype.flatten\nArray.prototype.values\nArrayBuffer\narrow-function\nasync-functions\nasync-iteration\nAtomics\nAtomics.waitAsync=skip\nBigInt\ncaller\nclass\nclass-fields-private\nclass-fields-public\nclass-methods-private\nclass-static-fields-public\nclass-static-fields-private\nclass-static-methods-private\ncleanupSome=skip\ncoalesce-expression\ncomputed-property-names\nconst\ncross-realm\nDataView\nDataView.prototype.getFloat32\nDataView.prototype.getFloat64\nDataView.prototype.getInt16\nDataView.prototype.getInt32\nDataView.prototype.getInt8\nDataView.prototype.getUint16\nDataView.prototype.getUint32\nDataView.prototype.setUint8\ndefault-parameters\ndestructuring-assignment\ndestructuring-binding\ndynamic-import\nexport-star-as-namespace-from-module\nFinalizationGroup=skip\nFinalizationRegistry=skip\nFinalizationRegistry.prototype.cleanupSome=skip\nFloat32Array\nFloat64Array\nfor-in-order\nfor-of\ngenerators\nglobalThis\nhashbang\nhost-gc-required=skip\nimport.meta\nInt16Array\nInt32Array\nInt8Array\nIsHTMLDDA\njson-superset\nlegacy-regexp=skip\nlet\nlogical-assignment-operators\nMap\nnew.target\nnumeric-separator-literal\nobject-rest\nobject-spread\nObject.fromEntries\nObject.is\noptional-catch-binding\noptional-chaining\nPromise\nPromise.allSettled\nPromise.any\nPromise.prototype.finally\nProxy\nproxy-missing-checks\nReflect\nReflect.construct\nReflect.set\nReflect.setPrototypeOf\nregexp-dotall\nregexp-lookbehind\nregexp-match-indices=skip\nregexp-named-groups\nregexp-unicode-property-escapes\nrest-parameters\nSet\nSharedArrayBuffer\nstring-trimming\nString.fromCodePoint\nString.prototype.endsWith\nString.prototype.includes\nString.prototype.at=skip\nString.prototype.matchAll\nString.prototype.replaceAll\nString.prototype.trimEnd\nString.prototype.trimStart\nsuper\nSymbol\nSymbol.asyncIterator\nSymbol.hasInstance\nSymbol.isConcatSpreadable\nSymbol.iterator\nSymbol.match\nSymbol.matchAll\nSymbol.prototype.description\nSymbol.replace\nSymbol.search\nSymbol.species\nSymbol.split\nSymbol.toPrimitive\nSymbol.toStringTag\nSymbol.unscopables\ntail-call-optimization=skip\ntemplate\ntop-level-await=skip\nTypedArray\nTypedArray.prototype.at=skip\nu180e\nUint16Array\nUint32Array\nUint8Array\nUint8ClampedArray\nWeakMap\nWeakRef=skip\nWeakSet\nwell-formed-json-stringify\n__getter__\n__proto__\n__setter__\n\n[exclude]\n# list excluded tests and directories here\n\n# intl not supported\ntest262/test/intl402/\n\n# incompatible with the \"caller\" feature\ntest262/test/built-ins/Function/prototype/restricted-property-caller.js\ntest262/test/built-ins/Function/prototype/restricted-property-arguments.js\ntest262/test/built-ins/ThrowTypeError/unique-per-realm-function-proto.js\n\n# slow tests\n#test262/test/built-ins/RegExp/CharacterClassEscapes/\n#test262/test/built-ins/RegExp/property-escapes/\n\n[tests]\n# list test files or use config.testdir\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/test262_errors.txt",
    "content": "test262/test/built-ins/Function/internals/Construct/derived-this-uninitialized-realm.js:20: Test262Error: Expected a ReferenceError but got a ReferenceError\ntest262/test/built-ins/Function/internals/Construct/derived-this-uninitialized-realm.js:20: strict mode: Test262Error: Expected a ReferenceError but got a ReferenceError\ntest262/test/built-ins/RegExp/named-groups/non-unicode-property-names-valid.js:46: SyntaxError: invalid group name\ntest262/test/built-ins/RegExp/named-groups/non-unicode-property-names-valid.js:46: strict mode: SyntaxError: invalid group name\ntest262/test/built-ins/TypedArrayConstructors/internals/DefineOwnProperty/BigInt/detached-buffer.js:46: Test262Error:  (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/DefineOwnProperty/BigInt/detached-buffer.js:46: strict mode: Test262Error:  (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/DefineOwnProperty/detached-buffer.js:47: Test262Error:  (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/DefineOwnProperty/detached-buffer.js:47: strict mode: Test262Error:  (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/detached-buffer-realm.js:37: strict mode: TypeError: out-of-bound numeric index (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/detached-buffer.js:34: TypeError: cannot convert bigint to number (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/detached-buffer.js:32: strict mode: TypeError: out-of-bound numeric index (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/key-is-minus-zero.js:20: Test262Error: Reflect.set(\"new TA([42n])\", \"-0\", 1n) must return true Expected SameValue(«false», «true») to be true (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/key-is-minus-zero.js:20: strict mode: Test262Error: Reflect.set(\"new TA([42n])\", \"-0\", 1n) must return true Expected SameValue(«false», «true») to be true (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/key-is-not-integer.js:21: Test262Error: Reflect.set(\"new TA([42n])\", \"1.1\", 1n) must return true Expected SameValue(«false», «true») to be true (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/key-is-not-integer.js:21: strict mode: Test262Error: Reflect.set(\"new TA([42n])\", \"1.1\", 1n) must return true Expected SameValue(«false», «true») to be true (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/key-is-out-of-bounds.js:27: Test262Error: Reflect.set(\"new TA([42n])\", \"-1\", 1n) must return false Expected SameValue(«false», «true») to be true (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/key-is-out-of-bounds.js:27: strict mode: Test262Error: Reflect.set(\"new TA([42n])\", \"-1\", 1n) must return false Expected SameValue(«false», «true») to be true (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/tonumber-value-detached-buffer.js:24: Test262Error: Expected SameValue(«false», «true») to be true (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/tonumber-value-detached-buffer.js:24: strict mode: Test262Error: Expected SameValue(«false», «true») to be true (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/detached-buffer-realm.js:37: strict mode: TypeError: out-of-bound numeric index (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/detached-buffer.js:32: strict mode: TypeError: out-of-bound numeric index (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/key-is-minus-zero.js:22: Test262Error: Reflect.set(sample, \"-0\", 1) must return true Expected SameValue(«false», «true») to be true (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/key-is-minus-zero.js:22: strict mode: Test262Error: Reflect.set(sample, \"-0\", 1) must return true Expected SameValue(«false», «true») to be true (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/key-is-not-integer.js:22: Test262Error: Reflect.set(sample, \"1.1\", 1) must return true Expected SameValue(«false», «true») to be true (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/key-is-not-integer.js:22: strict mode: Test262Error: Reflect.set(sample, \"1.1\", 1) must return true Expected SameValue(«false», «true») to be true (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/key-is-out-of-bounds.js:22: Test262Error: Reflect.set(sample, \"-1\", 1) must return true Expected SameValue(«false», «true») to be true (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/key-is-out-of-bounds.js:22: strict mode: Test262Error: Reflect.set(sample, \"-1\", 1) must return true Expected SameValue(«false», «true») to be true (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/tonumber-value-detached-buffer.js:39: Test262Error: Expected SameValue(«false», «true») to be true (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/tonumber-value-detached-buffer.js:39: strict mode: Test262Error: Expected SameValue(«false», «true») to be true (Testing with Float64Array.)\ntest262/test/language/expressions/dynamic-import/usage-from-eval.js:26: TypeError: $DONE() not called\ntest262/test/language/expressions/dynamic-import/usage-from-eval.js:26: strict mode: TypeError: $DONE() not called\ntest262/test/language/expressions/optional-chaining/optional-call-preserves-this.js:21: TypeError: cannot read property 'c' of undefined\ntest262/test/language/expressions/optional-chaining/optional-call-preserves-this.js:15: strict mode: TypeError: cannot read property '_b' of undefined\ntest262/test/language/statements/for-of/head-lhs-async-invalid.js:14: unexpected error type: Test262: This statement should not be evaluated.\ntest262/test/language/statements/for-of/head-lhs-async-invalid.js:14: strict mode: unexpected error type: Test262: This statement should not be evaluated.\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/test262o.conf",
    "content": "[config]\n# general settings for test262 ES5 version\n\n# framework style: old, new\nstyle=old\n\n# handle tests tagged as @noStrict: yes, no, skip\nnostrict=yes\n\n# handle tests tagged as @strictOnly: yes, no, skip\nstrict=yes\n\n# test mode: default, default-nostrict, default-strict, strict, nostrict, both, all\nmode=default\n\n# output error messages: yes, no\nverbose=yes\n\n# load harness files this directory\nharnessdir=test262o/test/harness\n\n# name of the error file for known errors\nerrorfile=test262o_errors.txt\n\n# exclude tests enumerated in this file\n#excludefile=test262o_excluded.txt\n\n# report test results to this file\nreportfile=test262o_report.txt\n\n# enumerate tests from this directory\ntestdir=test262o/test/suite\n\n[exclude]\n# list excluded tests and directories here\n\n# intl not supported\ntest262o/test/suite/intl402/\n\n# ES6 != ES5: block scoped function definitions allowed in strict mode\ntest262o/test/suite/bestPractice/Sbp_A1_T1.js\ntest262o/test/suite/bestPractice/Sbp_A2_T1.js\ntest262o/test/suite/bestPractice/Sbp_A2_T2.js\ntest262o/test/suite/bestPractice/Sbp_A3_T1.js\ntest262o/test/suite/bestPractice/Sbp_A3_T2.js\ntest262o/test/suite/bestPractice/Sbp_A4_T1.js\ntest262o/test/suite/bestPractice/Sbp_A4_T2.js\ntest262o/test/suite/bestPractice/Sbp_A5_T2.js\n\n# ES6 != ES5: `y={x};` is shorthand for `y={x:x}`\ntest262o/test/suite/ch12/12.1/S12.1_A4_T2.js\ntest262o/test/suite/ch12/12.6/12.6.4/S12.6.4_A15.js\n\n# ES6 != ES5: function length property is configurable\ntest262o/test/suite/ch11/11.4/11.4.1/11.4.1-5-a-28-s.js\ntest262o/test/suite/ch13/13.2/13.2-15-1.js\ntest262o/test/suite/ch15/15.1/15.1.2/15.1.2.1/S15.1.2.1_A4.2.js\ntest262o/test/suite/ch15/15.1/15.1.2/15.1.2.2/S15.1.2.2_A9.2.js\ntest262o/test/suite/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A7.2.js\ntest262o/test/suite/ch15/15.1/15.1.2/15.1.2.4/S15.1.2.4_A2.2.js\ntest262o/test/suite/ch15/15.1/15.1.2/15.1.2.5/S15.1.2.5_A2.2.js\ntest262o/test/suite/ch15/15.1/15.1.3/15.1.3.1/S15.1.3.1_A5.2.js\ntest262o/test/suite/ch15/15.1/15.1.3/15.1.3.2/S15.1.3.2_A5.2.js\ntest262o/test/suite/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A5.2.js\ntest262o/test/suite/ch15/15.1/15.1.3/15.1.3.4/S15.1.3.4_A5.2.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-186.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-187.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-191.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-194.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-201.js\ntest262o/test/suite/ch15/15.2/15.2.4/15.2.4.2/S15.2.4.2_A9.js\ntest262o/test/suite/ch15/15.2/15.2.4/15.2.4.3/S15.2.4.3_A9.js\ntest262o/test/suite/ch15/15.2/15.2.4/15.2.4.4/S15.2.4.4_A9.js\ntest262o/test/suite/ch15/15.2/15.2.4/15.2.4.5/S15.2.4.5_A9.js\ntest262o/test/suite/ch15/15.2/15.2.4/15.2.4.6/S15.2.4.6_A9.js\ntest262o/test/suite/ch15/15.2/15.2.4/15.2.4.7/S15.2.4.7_A9.js\ntest262o/test/suite/ch15/15.3/15.3.3/15.3.3.2/15.3.3.2-1.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.2/S15.3.4.2_A9.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A9.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A9.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-15-2.js\ntest262o/test/suite/ch15/15.3/15.3.5/S15.3.5.1_A2_T1.js\ntest262o/test/suite/ch15/15.3/15.3.5/S15.3.5.1_A2_T2.js\ntest262o/test/suite/ch15/15.3/15.3.5/S15.3.5.1_A2_T3.js\ntest262o/test/suite/ch15/15.4/15.4.3/S15.4.3_A2.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.2/S15.4.4.2_A4.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.3/S15.4.4.3_A4.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.4/S15.4.4.4_A4.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.5/S15.4.4.5_A6.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.6/S15.4.4.6_A5.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.7/S15.4.4.7_A6.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.8/S15.4.4.8_A5.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.9/S15.4.4.9_A5.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.10/S15.4.4.10_A5.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.11/S15.4.4.11_A7.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A5.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.13/S15.4.4.13_A5.2.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.4/S15.5.4.4_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.5/S15.5.4.5_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.6/S15.5.4.6_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.8/S15.5.4.8_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.9/S15.5.4.9_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.11/S15.5.4.11_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.12/S15.5.4.12_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.14/S15.5.4.14_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.16/S15.5.4.16_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.17/S15.5.4.17_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.18/S15.5.4.18_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.19/S15.5.4.19_A9.js\ntest262o/test/suite/ch15/15.9/15.9.4/15.9.4.2/S15.9.4.2_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.4/15.9.4.3/S15.9.4.3_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.1/S15.9.5.1_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.2/S15.9.5.2_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.3/S15.9.5.3_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.4/S15.9.5.4_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.5/S15.9.5.5_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.6/S15.9.5.6_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.7/S15.9.5.7_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.8/S15.9.5.8_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.9/S15.9.5.9_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.10/S15.9.5.10_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.11/S15.9.5.11_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.12/S15.9.5.12_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.13/S15.9.5.13_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.14/S15.9.5.14_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.15/S15.9.5.15_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.16/S15.9.5.16_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.17/S15.9.5.17_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.18/S15.9.5.18_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.19/S15.9.5.19_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.20/S15.9.5.20_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.21/S15.9.5.21_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.22/S15.9.5.22_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.23/S15.9.5.23_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.24/S15.9.5.24_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.25/S15.9.5.25_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.26/S15.9.5.26_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.27/S15.9.5.27_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.28/S15.9.5.28_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.29/S15.9.5.29_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.30/S15.9.5.30_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.31/S15.9.5.31_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.32/S15.9.5.32_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.33/S15.9.5.33_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.34/S15.9.5.34_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.35/S15.9.5.35_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.36/S15.9.5.36_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.37/S15.9.5.37_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.38/S15.9.5.38_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.39/S15.9.5.39_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.40/S15.9.5.40_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.41/S15.9.5.41_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.42/S15.9.5.42_A3_T2.js\ntest262o/test/suite/ch15/15.10/15.10.6/15.10.6.2/S15.10.6.2_A9.js\ntest262o/test/suite/ch15/15.10/15.10.6/15.10.6.3/S15.10.6.3_A9.js\ntest262o/test/suite/ch15/15.10/15.10.6/15.10.6.4/S15.10.6.4_A9.js\n\n# ES6 != ES5: object literals may have duplicates\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5-4-4-a-1-s.js\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5_4-4-b-1.js\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5_4-4-b-2.js\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5_4-4-c-1.js\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5_4-4-c-2.js\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5_4-4-d-1.js\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5_4-4-d-2.js\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5_4-4-d-3.js\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5_4-4-d-4.js\n\n# ES6 != ES5: Date.prototype is no longer an instance of Date\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.40/15.9.5.40_1.js\n\n# ES6 != ES5: Object.getPrototypeOf converts argument to object\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-1-3.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-1-4.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-1.js\n\n# ES6 != ES5: Object.getPrototypeOf(NativeError)\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-12.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-13.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-14.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-15.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-16.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-17.js\n\n# ES6 != ES5: Object.getOwnPropertyDescriptor converts argument to object\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-1-3.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-1-4.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-1.js\n\n# ES6 != ES5: Object.getOwnPropertyNames converts argument to object\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.4/15.2.3.4-1-4.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.4/15.2.3.4-1-5.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.4/15.2.3.4-1.js\n\n# ES6 != ES5: Object.seal accepts all types\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.8/15.2.3.8-1-1.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.8/15.2.3.8-1-2.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.8/15.2.3.8-1-3.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.8/15.2.3.8-1-4.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.8/15.2.3.8-1.js\n\n# ES6 != ES5: Object.freeze accepts all types\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.9/15.2.3.9-1-1.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.9/15.2.3.9-1-2.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.9/15.2.3.9-1-3.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.9/15.2.3.9-1-4.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.9/15.2.3.9-1.js\n\n# ES6 != ES5: Object.preventExtensions accepts all types\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.10/15.2.3.10-1-1.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.10/15.2.3.10-1-2.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.10/15.2.3.10-1-3.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.10/15.2.3.10-1-4.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.10/15.2.3.10-1.js\n\n# ES6 != ES5: Object.isSealed accepts all types\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-1.js\n\n# ES6 != ES5: Object.isFrozen accepts all types\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.12/15.2.3.12-1-1.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.12/15.2.3.12-1-2.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.12/15.2.3.12-1-3.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.12/15.2.3.12-1-4.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.12/15.2.3.12-1.js\n\n# ES6 != ES5: Object.isExtensible accepts all types\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-1-1.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-1-2.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-1-3.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-1-4.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-1.js\n\n# ES6 != ES5: Object.keys converts argument to object\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.14/15.2.3.14-1-1.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.14/15.2.3.14-1-2.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.14/15.2.3.14-1-3.js\n\n# ES6 != ES5: source and other properties of RegExp.prototype are not own properties\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-212.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-213.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-214.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-215.js\n\n# ES6 != ES5: String numeric object properties are enumerated first\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.4/15.2.3.4-4-44.js\n\n# ES6: new RegExp(regex, flags) is valid\ntest262o/test/suite/ch15/15.10/15.10.3/S15.10.3.1_A2_T1.js\ntest262o/test/suite/ch15/15.10/15.10.3/S15.10.3.1_A2_T2.js\ntest262o/test/suite/ch15/15.10/15.10.4/15.10.4.1/15.10.4.1-1.js\ntest262o/test/suite/ch15/15.10/15.10.4/S15.10.4.1_A2_T1.js\ntest262o/test/suite/ch15/15.10/15.10.4/S15.10.4.1_A2_T2.js\n\n# ES6 != ES5: RegExp.prototype.test behavior\ntest262o/test/suite/ch15/15.10/15.10.6/15.10.6.2/S15.10.6.2_A5_T3.js\n\n# ES6 != ES5: source, global, ignoreCase, multiline, lastIndex are not data properties\n# of RegExp objects and RegExp.prototype is not a RegExp object\ntest262o/test/suite/ch15/15.10/15.10.6/15.10.6.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.1/15.10.7.1-1.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.1/15.10.7.1-2.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.1/S15.10.7.1_A8.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.1/S15.10.7.1_A9.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.1/S15.10.7.1_A10.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.2/15.10.7.2-1.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.2/15.10.7.2-2.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.2/S15.10.7.2_A8.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.2/S15.10.7.2_A9.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.2/S15.10.7.2_A10.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.3/15.10.7.3-1.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.3/15.10.7.3-2.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.3/S15.10.7.3_A8.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.3/S15.10.7.3_A9.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.3/S15.10.7.3_A10.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.4/15.10.7.4-1.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.4/15.10.7.4-2.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.4/S15.10.7.4_A8.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.4/S15.10.7.4_A9.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.4/S15.10.7.4_A10.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.5/15.10.7.5-1.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.5/15.10.7.5-2.js\n\n# ES6 != ES5: Error.prototype is a normal object\ntest262o/test/suite/ch15/15.11/15.11.4/S15.11.4_A2.js\n\n# ES6 different ToLength() semantics\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.5/S15.4.4.5_A4_T3.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.6/S15.4.4.6_A2_T2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.6/S15.4.4.6_A3_T1.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.6/S15.4.4.6_A3_T2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.6/S15.4.4.6_A3_T3.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.7/S15.4.4.7_A2_T2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.7/S15.4.4.7_A4_T1.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.7/S15.4.4.7_A4_T3.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.8/S15.4.4.8_A3_T3.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.9/S15.4.4.9_A3_T3.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.10/S15.4.4.10_A3_T1.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.10/S15.4.4.10_A3_T2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.10/S15.4.4.10_A3_T3.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.11/S15.4.4.11_A4_T3.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A3_T1.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A3_T3.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.13/S15.4.4.13_A3_T2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-8.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-14.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-25.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-28.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-29.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.15/15.4.4.15-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.15/15.4.4.15-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.15/15.4.4.15-3-25.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.15/15.4.4.15-3-28.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-8.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-14.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-25.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-29.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-3-8.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-3-14.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-3-25.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-3-28.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-3-29.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-25.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-3-8.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-3-14.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-3-25.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-3-28.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-3-29.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.20/15.4.4.20-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.20/15.4.4.20-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.20/15.4.4.20-3-25.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-25.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.22/15.4.4.22-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.22/15.4.4.22-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.22/15.4.4.22-3-25.js\n\n# ES6 different ToLength() semantics causes near infinite runtime\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.15/15.4.4.15-3-14.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-14.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.20/15.4.4.20-3-14.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-14.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.22/15.4.4.22-3-14.js\n\n# ES6 arguments/caller changes\ntest262o/test/suite/ch10/10.6/10.6-13-b-1-s.js\ntest262o/test/suite/ch10/10.6/10.6-13-b-2-s.js\ntest262o/test/suite/ch10/10.6/10.6-13-b-3-s.js\ntest262o/test/suite/ch10/10.6/10.6-14-1-s.js\ntest262o/test/suite/ch10/10.6/10.6-14-b-1-s.js\ntest262o/test/suite/ch10/10.6/10.6-14-b-4-s.js\ntest262o/test/suite/ch13/13.2/13.2-29-s.js\ntest262o/test/suite/ch13/13.2/13.2-30-s.js\ntest262o/test/suite/ch13/13.2/13.2-31-s.js\ntest262o/test/suite/ch13/13.2/13.2-32-s.js\ntest262o/test/suite/ch13/13.2/13.2-33-s.js\ntest262o/test/suite/ch13/13.2/13.2-34-s.js\ntest262o/test/suite/ch13/13.2/13.2-35-s.js\ntest262o/test/suite/ch13/13.2/13.2-36-s.js\ntest262o/test/suite/ch13/13.2/S13.2.3_A1.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-20-1.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-20-4.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-20-5.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-21-1.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-21-4.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-21-5.js\n\n# u180e is no longer considered as a space\ntest262o/test/suite/ch09/9.3/9.3.1/S9.3.1_A2.js\ntest262o/test/suite/ch09/9.3/9.3.1/S9.3.1_A3_T1.js\ntest262o/test/suite/ch09/9.3/9.3.1/S9.3.1_A3_T2.js\ntest262o/test/suite/ch15/15.1/15.1.2/15.1.2.2/S15.1.2.2_A2_T10.js\ntest262o/test/suite/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A2_T10.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.20/15.5.4.20-3-2.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.20/15.5.4.20-3-3.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.20/15.5.4.20-3-4.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.20/15.5.4.20-3-5.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.20/15.5.4.20-3-6.js\ntest262o/test/suite/ch15/15.10/15.10.2/15.10.2.12/S15.10.2.12_A1_T1.js\ntest262o/test/suite/ch15/15.10/15.10.2/15.10.2.12/S15.10.2.12_A2_T1.js\n\n# E6 eval return value is different\ntest262o/test/suite/ch12/12.6/12.6.3/S12.6.3_A9.js\ntest262o/test/suite/ch12/12.6/12.6.3/S12.6.3_A9.1.js\n\n# ECMA 2019 optional-catch-binding feature allows try{}catch{}\ntest262o/test/suite/ch12/12.14/S12.14_A16_T4.js\n\n# Syntax error instead of ReferenceError in ES2020\ntest262o/test/suite/ch11/11.13/11.13.1/11.13.1-1-1.js\ntest262o/test/suite/ch11/11.13/11.13.1/11.13.1-1-2.js\ntest262o/test/suite/ch11/11.13/11.13.1/11.13.1-1-3.js\ntest262o/test/suite/ch11/11.13/11.13.1/11.13.1-1-4.js\n\n[tests]\n# list test files or use config.testdir\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/test262o_errors.txt",
    "content": ""
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/tests/bjson.c",
    "content": "/*\n * QuickJS: binary JSON module (test only)\n * \n * Copyright (c) 2017-2019 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \"../quickjs-libc.h\"\n#include \"../cutils.h\"\n\nstatic JSValue js_bjson_read(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    uint8_t *buf;\n    uint64_t pos, len;\n    JSValue obj;\n    size_t size;\n    int flags;\n    \n    if (JS_ToIndex(ctx, &pos, argv[1]))\n        return JS_EXCEPTION;\n    if (JS_ToIndex(ctx, &len, argv[2]))\n        return JS_EXCEPTION;\n    buf = JS_GetArrayBuffer(ctx, &size, argv[0]);\n    if (!buf)\n        return JS_EXCEPTION;\n    if (pos + len > size)\n        return JS_ThrowRangeError(ctx, \"array buffer overflow\");\n    flags = 0;\n    if (JS_ToBool(ctx, argv[3]))\n        flags |= JS_READ_OBJ_REFERENCE;\n    obj = JS_ReadObject(ctx, buf + pos, len, flags);\n    return obj;\n}\n\nstatic JSValue js_bjson_write(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    size_t len;\n    uint8_t *buf;\n    JSValue array;\n    int flags;\n    \n    flags = 0;\n    if (JS_ToBool(ctx, argv[1]))\n        flags |= JS_WRITE_OBJ_REFERENCE;\n    buf = JS_WriteObject(ctx, &len, argv[0], flags);\n    if (!buf)\n        return JS_EXCEPTION;\n    array = JS_NewArrayBufferCopy(ctx, buf, len);\n    js_free(ctx, buf);\n    return array;\n}\n\nstatic const JSCFunctionListEntry js_bjson_funcs[] = {\n    JS_CFUNC_DEF(\"read\", 4, js_bjson_read ),\n    JS_CFUNC_DEF(\"write\", 2, js_bjson_write ),\n};\n\nstatic int js_bjson_init(JSContext *ctx, JSModuleDef *m)\n{\n    return JS_SetModuleExportList(ctx, m, js_bjson_funcs,\n                                  countof(js_bjson_funcs));\n}\n\n#ifdef JS_SHARED_LIBRARY\n#define JS_INIT_MODULE js_init_module\n#else\n#define JS_INIT_MODULE js_init_module_bjson\n#endif\n\nJSModuleDef *JS_INIT_MODULE(JSContext *ctx, const char *module_name)\n{\n    JSModuleDef *m;\n    m = JS_NewCModule(ctx, module_name, js_bjson_init);\n    if (!m)\n        return NULL;\n    JS_AddModuleExportList(ctx, m, js_bjson_funcs, countof(js_bjson_funcs));\n    return m;\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/tests/microbench.js",
    "content": "/*\n * Javascript Micro benchmark\n *\n * Copyright (c) 2017-2019 Fabrice Bellard\n * Copyright (c) 2017-2019 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\nimport * as std from \"std\";\n\nfunction pad(str, n) {\n    str += \"\";\n    while (str.length < n)\n        str += \" \";\n    return str;\n}\n\nfunction pad_left(str, n) {\n    str += \"\";\n    while (str.length < n)\n        str = \" \" + str;\n    return str;\n}\n\nfunction pad_center(str, n) {\n    str += \"\";\n    while (str.length < n) {\n        if ((n - str.length) & 1)\n            str = str + \" \";\n        else\n            str = \" \" + str;\n    }\n    return str;\n}\n\nfunction toPrec(n, prec) {\n    var i, s;\n    for (i = 0; i < prec; i++)\n        n *= 10;\n    s = \"\" + Math.round(n);\n    for (i = s.length - prec; i <= 0; i++)\n        s = \"0\" + s;\n    if (prec > 0)\n        s = s.substring(0, i) + \".\" + s.substring(i);\n    return s;\n}\n                \nvar ref_data;\nvar log_data;\n\nvar heads  = [ \"TEST\", \"N\", \"TIME (ns)\", \"REF (ns)\", \"SCORE (%)\" ];\nvar widths = [    22,   10,          9,     9,       9 ];\nvar precs  = [     0,   0,           2,     2,       2 ];\nvar total  = [     0,   0,           0,     0,       0 ];\nvar total_score = 0;\nvar total_scale = 0;\n\nif (typeof console == \"undefined\") {\n    var console = { log: print };\n}\n\nfunction log_line() {\n    var i, n, s, a;\n    s = \"\";\n    for (i = 0, n = arguments.length; i < n; i++) {\n        if (i > 0)\n            s += \" \";\n        a = arguments[i];\n        if (typeof a == \"number\") {\n            total[i] += a;\n            a = toPrec(a, precs[i]);\n            s += pad_left(a, widths[i]);\n        } else {\n            s += pad_left(a, widths[i]);\n        }\n    }\n    console.log(s);\n}\n\nvar clocks_per_sec = 1000000;\nvar max_iterations = 100;\nvar clock_threshold = 2000;  /* favoring short measuring spans */\nvar min_n_argument = 1;\nvar get_clock;\n\nif (typeof globalThis.__date_clock != \"function\") {\n    console.log(\"using fallback millisecond clock\");\n    clocks_per_sec = 1000;\n    max_iterations = 10;\n    clock_threshold = 100;\n    get_clock = Date.now;\n} else {\n    get_clock = globalThis.__date_clock;\n}\n\nfunction log_one(text, n, ti) {\n    var ref;\n\n    if (ref_data)\n        ref = ref_data[text];\n    else\n        ref = null;\n\n    ti = Math.round(ti * 100) / 100;\n    log_data[text] = ti;\n    if (typeof ref === \"number\") {\n        log_line(text, n, ti, ref, ti * 100 / ref);\n        total_score += ti * 100 / ref;\n        total_scale += 100;\n    } else {\n        log_line(text, n, ti);\n        total_score += 100;\n        total_scale += 100;\n    }\n}\n\nfunction bench(f, text)\n{\n    var i, j, n, t, t1, ti, nb_its, ref, ti_n, ti_n1, min_ti;\n\n    nb_its = n = 1;\n    if (f.bench) {\n        ti_n = f(text);\n    } else {\n        ti_n = 1000000000;\n        min_ti = clock_threshold / 10;\n        for(i = 0; i < 30; i++) {\n            ti = 1000000000;\n            for (j = 0; j < max_iterations; j++) {\n                t = get_clock();\n                while ((t1 = get_clock()) == t)\n                    continue;\n                nb_its = f(n);\n                if (nb_its < 0)\n                    return; // test failure\n                t1 = get_clock() - t1;\n                if (ti > t1)\n                    ti = t1;\n            }\n            if (ti >= min_ti) {\n                ti_n1 = ti / nb_its;\n                if (ti_n > ti_n1)\n                    ti_n = ti_n1;\n            }\n            if (ti >= clock_threshold && n >= min_n_argument)\n                break;\n\n            n = n * [ 2, 2.5, 2 ][i % 3];\n        }\n        // to use only the best timing from the last loop, uncomment below\n        //ti_n = ti / nb_its;\n    }\n    /* nano seconds per iteration */\n    log_one(text, n, ti_n * 1e9 / clocks_per_sec);\n}\n\nvar global_res; /* to be sure the code is not optimized */\n\nfunction empty_loop(n) {\n    var j;\n    for(j = 0; j < n; j++) {\n    }\n    return n;\n}\n\nfunction date_now(n) {\n    var j;\n    for(j = 0; j < n; j++) {\n        Date.now();\n    }\n    return n;\n}\n\nfunction prop_read(n)\n{\n    var obj, sum, j;\n    obj = {a: 1, b: 2, c:3, d:4 };\n    sum = 0;\n    for(j = 0; j < n; j++) {\n        sum += obj.a;\n        sum += obj.b;\n        sum += obj.c;\n        sum += obj.d;\n    }\n    global_res = sum;\n    return n * 4;\n}\n\nfunction prop_write(n)\n{\n    var obj, j;\n    obj = {a: 1, b: 2, c:3, d:4 };\n    for(j = 0; j < n; j++) {\n        obj.a = j;\n        obj.b = j;\n        obj.c = j;\n        obj.d = j;\n    }\n    return n * 4;\n}\n\nfunction prop_create(n)\n{\n    var obj, j;\n    for(j = 0; j < n; j++) {\n        obj = new Object();\n        obj.a = 1;\n        obj.b = 2;\n        obj.c = 3;\n        obj.d = 4;\n    }\n    return n * 4;\n}\n\nfunction prop_delete(n)\n{\n    var obj, j;\n    obj = {};\n    for(j = 0; j < n; j++) {\n        obj[j] = 1;\n    }\n    for(j = 0; j < n; j++) {\n        delete obj[j];\n    }\n    return n;\n}\n\nfunction array_read(n)\n{\n    var tab, len, sum, i, j;\n    tab = [];\n    len = 10;\n    for(i = 0; i < len; i++)\n        tab[i] = i;\n    sum = 0;\n    for(j = 0; j < n; j++) {\n        sum += tab[0];\n        sum += tab[1];\n        sum += tab[2];\n        sum += tab[3];\n        sum += tab[4];\n        sum += tab[5];\n        sum += tab[6];\n        sum += tab[7];\n        sum += tab[8];\n        sum += tab[9];\n    }\n    global_res = sum;\n    return len * n;\n}\n\nfunction array_write(n)\n{\n    var tab, len, i, j;\n    tab = [];\n    len = 10;\n    for(i = 0; i < len; i++)\n        tab[i] = i;\n    for(j = 0; j < n; j++) {\n        tab[0] = j;\n        tab[1] = j;\n        tab[2] = j;\n        tab[3] = j;\n        tab[4] = j;\n        tab[5] = j;\n        tab[6] = j;\n        tab[7] = j;\n        tab[8] = j;\n        tab[9] = j;\n    }\n    return len * n;\n}\n\nfunction array_prop_create(n)\n{\n    var tab, i, j, len;\n    len = 1000;\n    for(j = 0; j < n; j++) {\n        tab = [];\n        for(i = 0; i < len; i++)\n            tab[i] = i;\n    }\n    return len * n;\n}\n\nfunction array_length_decr(n)\n{\n    var tab, i, j, len;\n    len = 1000;\n    tab = [];\n    for(i = 0; i < len; i++)\n        tab[i] = i;\n    for(j = 0; j < n; j++) {\n        for(i = len - 1; i >= 0; i--)\n            tab.length = i;\n    }\n    return len * n;\n}\n\nfunction array_hole_length_decr(n)\n{\n    var tab, i, j, len;\n    len = 1000;\n    tab = [];\n    for(i = 0; i < len; i++) {\n        if (i != 3)\n            tab[i] = i;\n    }\n    for(j = 0; j < n; j++) {\n        for(i = len - 1; i >= 0; i--)\n            tab.length = i;\n    }\n    return len * n;\n}\n\nfunction array_push(n)\n{\n    var tab, i, j, len;\n    len = 500;\n    for(j = 0; j < n; j++) {\n        tab = [];\n        for(i = 0; i < len; i++)\n            tab.push(i);\n    }\n    return len * n;\n}\n\nfunction array_pop(n)\n{\n    var tab, i, j, len, sum;\n    len = 500;\n    for(j = 0; j < n; j++) {\n        tab = [];\n        for(i = 0; i < len; i++)\n            tab[i] = i;\n        sum = 0;\n        for(i = 0; i < len; i++)\n            sum += tab.pop();\n        global_res = sum;\n    }\n    return len * n;\n}\n\nfunction typed_array_read(n)\n{\n    var tab, len, sum, i, j;\n    len = 10;\n    tab = new Int32Array(len);\n    for(i = 0; i < len; i++)\n        tab[i] = i;\n    sum = 0;\n    for(j = 0; j < n; j++) {\n        sum += tab[0];\n        sum += tab[1];\n        sum += tab[2];\n        sum += tab[3];\n        sum += tab[4];\n        sum += tab[5];\n        sum += tab[6];\n        sum += tab[7];\n        sum += tab[8];\n        sum += tab[9];\n    }\n    global_res = sum;\n    return len * n;\n}\n\nfunction typed_array_write(n)\n{\n    var tab, len, i, j;\n    len = 10;\n    tab = new Int32Array(len);\n    for(i = 0; i < len; i++)\n        tab[i] = i;\n    for(j = 0; j < n; j++) {\n        tab[0] = j;\n        tab[1] = j;\n        tab[2] = j;\n        tab[3] = j;\n        tab[4] = j;\n        tab[5] = j;\n        tab[6] = j;\n        tab[7] = j;\n        tab[8] = j;\n        tab[9] = j;\n    }\n    return len * n;\n}\n\nvar global_var0;\n\nfunction global_read(n)\n{\n    var sum, j;\n    global_var0 = 0;\n    sum = 0;\n    for(j = 0; j < n; j++) {\n        sum += global_var0;\n        sum += global_var0;\n        sum += global_var0;\n        sum += global_var0;\n    }\n    global_res = sum;\n    return n * 4;\n}\n\nvar global_write =\n    (1, eval)(`(function global_write(n)\n           {\n               var j;\n               for(j = 0; j < n; j++) {\n                   global_var0 = j;\n                   global_var0 = j;\n                   global_var0 = j;\n                   global_var0 = j;\n               }\n               return n * 4;\n           })`);\n\nfunction global_write_strict(n)\n{\n    var j;\n    for(j = 0; j < n; j++) {\n        global_var0 = j;\n        global_var0 = j;\n        global_var0 = j;\n        global_var0 = j;\n    }\n    return n * 4;\n}\n\nfunction local_destruct(n)\n{\n    var j, v1, v2, v3, v4;\n    var array = [ 1, 2, 3, 4, 5];\n    var o = { a:1, b:2, c:3, d:4 };\n    var a, b, c, d;\n    for(j = 0; j < n; j++) {\n        [ v1, v2,, v3, ...v4] = array;\n        ({ a, b, c, d } = o);\n        ({ a: a, b: b, c: c, d: d } = o);\n    }\n    return n * 12;\n}\n\nvar global_v1, global_v2, global_v3, global_v4;\nvar global_a, global_b, global_c, global_d;\n\nvar global_destruct =\n    (1, eval)(`(function global_destruct(n)\n           {\n               var j, v1, v2, v3, v4;\n               var array = [ 1, 2, 3, 4, 5 ];\n               var o = { a:1, b:2, c:3, d:4 };\n               var a, b, c, d;\n               for(j = 0; j < n; j++) {\n                   [ global_v1, global_v2,, global_v3, ...global_v4] = array;\n                   ({ a: global_a, b: global_b, c: global_c, d: global_d } = o);\n               }\n               return n * 8;\n          })`);\n\nfunction global_destruct_strict(n)\n{\n    var j, v1, v2, v3, v4;\n    var array = [ 1, 2, 3, 4, 5 ];\n    var o = { a:1, b:2, c:3, d:4 };\n    var a, b, c, d;\n    for(j = 0; j < n; j++) {\n        [ global_v1, global_v2,, global_v3, ...global_v4] = array;\n        ({ a: global_a, b: global_b, c: global_c, d: global_d } = o);\n    }\n    return n * 8;\n}\n\nfunction func_call(n)\n{\n    function f(a)\n    {\n        return 1;\n    }\n\n    var j, sum;\n    sum = 0;\n    for(j = 0; j < n; j++) {\n        sum += f(j);\n        sum += f(j);\n        sum += f(j);\n        sum += f(j);\n    }\n    global_res = sum;\n    return n * 4;\n}\n\nfunction closure_var(n)\n{\n    function f(a)\n    {\n        sum++;\n    }\n\n    var j, sum;\n    sum = 0;\n    for(j = 0; j < n; j++) {\n        f(j);\n        f(j);\n        f(j);\n        f(j);\n    }\n    global_res = sum;\n    return n * 4;\n}\n\nfunction int_arith(n)\n{\n    var i, j, sum;\n    global_res = 0;\n    for(j = 0; j < n; j++) {\n        sum = 0;\n        for(i = 0; i < 1000; i++) {\n            sum += i * i;\n        }\n        global_res += sum;\n    }\n    return n * 1000;\n}\n\nfunction float_arith(n)\n{\n    var i, j, sum, a, incr, a0;\n    global_res = 0;\n    a0 = 0.1;\n    incr = 1.1;\n    for(j = 0; j < n; j++) {\n        sum = 0;\n        a = a0;\n        for(i = 0; i < 1000; i++) {\n            sum += a * a;\n            a += incr;\n        }\n        global_res += sum;\n    }\n    return n * 1000;\n}\n\nfunction bigfloat_arith(n)\n{\n    var i, j, sum, a, incr, a0;\n    global_res = 0;\n    a0 = BigFloat(\"0.1\");\n    incr = BigFloat(\"1.1\");\n    for(j = 0; j < n; j++) {\n        sum = 0;\n        a = a0;\n        for(i = 0; i < 1000; i++) {\n            sum += a * a;\n            a += incr;\n        }\n        global_res += sum;\n    }\n    return n * 1000;\n}\n\nfunction float256_arith(n)\n{\n    return BigFloatEnv.setPrec(bigfloat_arith.bind(null, n), 237, 19);\n}\n\nfunction bigint_arith(n, bits)\n{\n    var i, j, sum, a, incr, a0, sum0;\n    sum0 = global_res = BigInt(0);\n    a0 = BigInt(1) << BigInt(Math.floor((bits - 10) * 0.5));\n    incr = BigInt(1);\n    for(j = 0; j < n; j++) {\n        sum = sum0;\n        a = a0;\n        for(i = 0; i < 1000; i++) {\n            sum += a * a;\n            a += incr;\n        }\n        global_res += sum;\n    }\n    return n * 1000;\n}\n\nfunction bigint64_arith(n)\n{\n    return bigint_arith(n, 64);\n}\n\nfunction bigint256_arith(n)\n{\n    return bigint_arith(n, 256);\n}\n\nfunction set_collection_add(n)\n{\n    var s, i, j, len = 100;\n    s = new Set();\n    for(j = 0; j < n; j++) {\n        for(i = 0; i < len; i++) {\n            s.add(String(i), i);\n        }\n        for(i = 0; i < len; i++) {\n            if (!s.has(String(i)))\n                throw Error(\"bug in Set\");\n        }\n    }\n    return n * len;\n}\n\nfunction array_for(n)\n{\n    var r, i, j, sum;\n    r = [];\n    for(i = 0; i < 100; i++)\n        r[i] = i;\n    for(j = 0; j < n; j++) {\n        sum = 0;\n        for(i = 0; i < 100; i++) {\n            sum += r[i];\n        }\n        global_res = sum;\n    }\n    return n * 100;\n}\n\nfunction array_for_in(n)\n{\n    var r, i, j, sum;\n    r = [];\n    for(i = 0; i < 100; i++)\n        r[i] = i;\n    for(j = 0; j < n; j++) {\n        sum = 0;\n        for(i in r) {\n            sum += r[i];\n        }\n        global_res = sum;\n    }\n    return n * 100;\n}\n\nfunction array_for_of(n)\n{\n    var r, i, j, sum;\n    r = [];\n    for(i = 0; i < 100; i++)\n        r[i] = i;\n    for(j = 0; j < n; j++) {\n        sum = 0;\n        for(i of r) {\n            sum += i;\n        }\n        global_res = sum;\n    }\n    return n * 100;\n}\n\nfunction math_min(n)\n{\n    var i, j, r;\n    r = 0;\n    for(j = 0; j < n; j++) {\n        for(i = 0; i < 1000; i++)\n            r = Math.min(i, 500);\n        global_res = r;\n    }\n    return n * 1000;\n}\n\n/* incremental string contruction as local var */\nfunction string_build1(n)\n{\n    var i, j, r;\n    r = \"\";\n    for(j = 0; j < n; j++) {\n        for(i = 0; i < 100; i++)\n            r += \"x\";\n        global_res = r;\n    }\n    return n * 100;\n}\n\n/* incremental string contruction as arg */\nfunction string_build2(n, r)\n{\n    var i, j;\n    r = \"\";\n    for(j = 0; j < n; j++) {\n        for(i = 0; i < 100; i++)\n            r += \"x\";\n        global_res = r;\n    }\n    return n * 100;\n}\n\n/* incremental string contruction by prepending */\nfunction string_build3(n, r)\n{\n    var i, j;\n    r = \"\";\n    for(j = 0; j < n; j++) {\n        for(i = 0; i < 100; i++)\n            r = \"x\" + r;\n        global_res = r;\n    }\n    return n * 100;\n}\n\n/* incremental string contruction with multiple reference */\nfunction string_build4(n)\n{\n    var i, j, r, s;\n    r = \"\";\n    for(j = 0; j < n; j++) {\n        for(i = 0; i < 100; i++) {\n            s = r;\n            r += \"x\";\n        }\n        global_res = r;\n    }\n    return n * 100;\n}\n\n/* sort bench */\n\nfunction sort_bench(text) {\n    function random(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[(Math.random() * n) >> 0];\n    }\n    function random8(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[(Math.random() * 256) >> 0];\n    }\n    function random1(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[(Math.random() * 2) >> 0];\n    }\n    function hill(arr, n, def) {\n        var mid = n >> 1;\n        for (var i = 0; i < mid; i++)\n            arr[i] = def[i];\n        for (var i = mid; i < n; i++)\n            arr[i] = def[n - i];\n    }\n    function comb(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[(i & 1) * i];\n    }\n    function crisscross(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[(i & 1) ? n - i : i];\n    }\n    function zero(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[0];\n    }\n    function increasing(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[i];\n    }\n    function decreasing(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[n - 1 - i];\n    }\n    function alternate(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[i ^ 1];\n    }\n    function jigsaw(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[i % (n >> 4)];\n    }\n    function incbutone(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[i];\n        if (n > 0)\n            arr[n >> 2] = def[n];\n    }\n    function incbutfirst(arr, n, def) {\n        if (n > 0)\n            arr[0] = def[n];\n        for (var i = 1; i < n; i++)\n            arr[i] = def[i];\n    }\n    function incbutlast(arr, n, def) {\n        for (var i = 0; i < n - 1; i++)\n            arr[i] = def[i + 1];\n        if (n > 0)\n            arr[n - 1] = def[0];\n    }\n\n    var sort_cases = [ random, random8, random1, jigsaw, hill, comb,\n                      crisscross, zero, increasing, decreasing, alternate,\n                      incbutone, incbutlast, incbutfirst ];\n\n    var n = sort_bench.array_size || 10000;\n    var array_type = sort_bench.array_type || Array;\n    var def, arr;\n    var i, j, x, y;\n    var total = 0;\n\n    var save_total_score = total_score;\n    var save_total_scale = total_scale;\n\n    // initialize default sorted array (n + 1 elements)\n    def = new array_type(n + 1);\n    if (array_type == Array) {\n        for (i = 0; i <= n; i++) {\n            def[i] = i + \"\";\n        }\n    } else {\n        for (i = 0; i <= n; i++) {\n            def[i] = i;\n        }\n    }\n    def.sort();\n    for (var f of sort_cases) {\n        var ti = 0, tx = 0;\n        for (j = 0; j < 100; j++) {\n            arr = new array_type(n);\n            f(arr, n, def);\n            var t1 = get_clock();\n            arr.sort();\n            t1 = get_clock() - t1;\n            tx += t1;\n            if (!ti || ti > t1)\n                ti = t1;\n            if (tx >= clocks_per_sec)\n                break;\n        }\n        total += ti;\n\n        i = 0;\n        x = arr[0];\n        if (x !== void 0) {\n            for (i = 1; i < n; i++) {\n                y = arr[i];\n                if (y === void 0)\n                    break;\n                if (x > y)\n                    break;\n                x = y;\n            }\n        }\n        while (i < n && arr[i] === void 0)\n            i++;\n        if (i < n) {\n            console.log(\"sort_bench: out of order error for \" + f.name +\n                        \" at offset \" + (i - 1) +\n                        \": \" + arr[i - 1] + \" > \" + arr[i]);\n        }\n        if (sort_bench.verbose)\n            log_one(\"sort_\" + f.name, n, ti, n * 100);\n    }\n    total_score = save_total_score;\n    total_scale = save_total_scale;\n    return total / n / 1000;\n}\nsort_bench.bench = true;\nsort_bench.verbose = false;\n\nfunction int_to_string(n)\n{\n    var s, r, j;\n    r = 0;\n    for(j = 0; j < n; j++) {\n        s = (j + 1).toString();\n    }\n    return n;\n}\n\nfunction float_to_string(n)\n{\n    var s, r, j;\n    r = 0;\n    for(j = 0; j < n; j++) {\n        s = (j + 0.1).toString();\n    }\n    return n;\n}\n\nfunction string_to_int(n)\n{\n    var s, r, j;\n    r = 0;\n    s = \"12345\";\n    r = 0;\n    for(j = 0; j < n; j++) {\n        r += (s | 0);\n    }\n    global_res = r;\n    return n;\n}\n\nfunction string_to_float(n)\n{\n    var s, r, j;\n    r = 0;\n    s = \"12345.6\";\n    r = 0;\n    for(j = 0; j < n; j++) {\n        r -= s;\n    }\n    global_res = r;\n    return n;\n}\n\nfunction load_result(filename)\n{\n    var f, str, res;\n    if (typeof std === \"undefined\")\n        return null;\n    f = std.open(filename, \"r\");\n    if (!f)\n        return null;\n    str = f.readAsString();\n    res = JSON.parse(str);\n    f.close();\n    return res;\n}\n\nfunction save_result(filename, obj)\n{\n    var f;\n    if (typeof std === \"undefined\")\n        return;\n    f = std.open(filename, \"w\");\n    f.puts(JSON.stringify(obj, null, 2));\n    f.puts(\"\\n\");\n    f.close();\n}\n\nfunction main(argc, argv, g)\n{\n    var test_list = [\n        empty_loop,\n        date_now,\n        prop_read,\n        prop_write,\n        prop_create,\n        prop_delete,\n        array_read,\n        array_write,\n        array_prop_create,\n        array_length_decr,\n        array_hole_length_decr,\n        array_push,\n        array_pop,\n        typed_array_read,\n        typed_array_write,\n        global_read,\n        global_write,\n        global_write_strict,\n        local_destruct,\n        global_destruct,\n        global_destruct_strict,\n        func_call,\n        closure_var,\n        int_arith,\n        float_arith,\n        set_collection_add,\n        array_for,\n        array_for_in,\n        array_for_of,\n        math_min,\n        string_build1,\n        string_build2,\n        //string_build3,\n        //string_build4,\n        sort_bench,\n        int_to_string,\n        float_to_string,\n        string_to_int,\n        string_to_float,\n    ];\n    var tests = [];\n    var i, j, n, f, name;\n    \n    if (typeof BigInt == \"function\") {\n        /* BigInt test */\n        test_list.push(bigint64_arith);\n        test_list.push(bigint256_arith);\n    }\n    if (typeof BigFloat == \"function\") {\n        /* BigFloat test */\n        test_list.push(float256_arith);\n    }\n    \n    for (i = 1; i < argc;) {\n        name = argv[i++];\n        if (name == \"-a\") {\n            sort_bench.verbose = true;\n            continue;\n        }\n        if (name == \"-t\") {\n            name = argv[i++];\n            sort_bench.array_type = g[name];\n            if (typeof sort_bench.array_type != \"function\") {\n                console.log(\"unknown array type: \" + name);\n                return 1;\n            }\n            continue;\n        }\n        if (name == \"-n\") {\n            sort_bench.array_size = +argv[i++];\n            continue;\n        }\n        for (j = 0; j < test_list.length; j++) {\n            f = test_list[j];\n            if (name === f.name) {\n                tests.push(f);\n                break;\n            }\n        }\n        if (j == test_list.length) {\n            console.log(\"unknown benchmark: \" + name);\n            return 1;\n        }\n    }\n    if (tests.length == 0)\n        tests = test_list;\n\n    ref_data = load_result(\"microbench.txt\");\n    log_data = {};\n    log_line.apply(null, heads);\n    n = 0;\n\n    for(i = 0; i < tests.length; i++) {\n        f = tests[i];\n        bench(f, f.name, ref_data, log_data);\n        if (ref_data && ref_data[f.name])\n            n++;\n    }\n    if (ref_data)\n        log_line(\"total\", \"\", total[2], total[3], total_score * 100 / total_scale);\n    else\n        log_line(\"total\", \"\", total[2]);\n        \n    if (tests == test_list)\n        save_result(\"microbench-new.txt\", log_data);\n}\n\nif (!scriptArgs)\n    scriptArgs = [];\nmain(scriptArgs.length, scriptArgs, this);\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/tests/test262.patch",
    "content": "diff --git a/harness/atomicsHelper.js b/harness/atomicsHelper.js\nindex 9c1217351e..3c24755558 100644\n--- a/harness/atomicsHelper.js\n+++ b/harness/atomicsHelper.js\n@@ -227,10 +227,14 @@ $262.agent.waitUntil = function(typedArray, index, expected) {\n  *   }\n  */\n $262.agent.timeouts = {\n-  yield: 100,\n-  small: 200,\n-  long: 1000,\n-  huge: 10000,\n+//  yield: 100,\n+//  small: 200,\n+//  long: 1000,\n+//  huge: 10000,\n+  yield: 20,\n+  small: 20,\n+  long: 100,\n+  huge: 1000,\n };\n \n /**\ndiff --git a/harness/regExpUtils.js b/harness/regExpUtils.js\nindex be7039fda0..7b38abf8df 100644\n--- a/harness/regExpUtils.js\n+++ b/harness/regExpUtils.js\n@@ -6,24 +6,27 @@ description: |\n defines: [buildString, testPropertyEscapes, matchValidator]\n ---*/\n \n+if ($262 && typeof $262.codePointRange === \"function\") {\n+    /* use C function to build the codePointRange (much faster with\n+       slow JS engines) */\n+    codePointRange = $262.codePointRange;\n+} else {\n+    codePointRange = function codePointRange(start, end) {\n+        const codePoints = [];\n+        let length = 0;\n+        for (codePoint = start; codePoint < end; codePoint++) {\n+            codePoints[length++] = codePoint;\n+        }\n+        return String.fromCodePoint.apply(null, codePoints);\n+    }\n+}\n+\n function buildString({ loneCodePoints, ranges }) {\n-  const CHUNK_SIZE = 10000;\n-  let result = Reflect.apply(String.fromCodePoint, null, loneCodePoints);\n-  for (let i = 0; i < ranges.length; i++) {\n-    const range = ranges[i];\n-    const start = range[0];\n-    const end = range[1];\n-    const codePoints = [];\n-    for (let length = 0, codePoint = start; codePoint <= end; codePoint++) {\n-      codePoints[length++] = codePoint;\n-      if (length === CHUNK_SIZE) {\n-        result += Reflect.apply(String.fromCodePoint, null, codePoints);\n-        codePoints.length = length = 0;\n-      }\n+    let result = String.fromCodePoint.apply(null, loneCodePoints);\n+    for (const [start, end] of ranges) {\n+        result += codePointRange(start, end + 1);\n     }\n-    result += Reflect.apply(String.fromCodePoint, null, codePoints);\n-  }\n-  return result;\n+    return result;\n }\n \n function testPropertyEscapes(regex, string, expression) {\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/tests/test_bignum.js",
    "content": "\"use strict\";\n\nfunction assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\nfunction assertThrows(err, func)\n{\n    var ex;\n    ex = false;\n    try {\n        func();\n    } catch(e) {\n        ex = true;\n        assert(e instanceof err);\n    }\n    assert(ex, true, \"exception expected\");\n}\n\n// load more elaborate version of assert if available\ntry { __loadScript(\"test_assert.js\"); } catch(e) {}\n\n/*----------------*/\n\nfunction bigint_pow(a, n)\n{\n    var r, i;\n    r = 1n;\n    for(i = 0n; i < n; i++)\n        r *= a;\n    return r;\n}\n\n/* a must be < b */\nfunction test_less(a, b)\n{\n    assert(a < b);\n    assert(!(b < a));\n    assert(a <= b);\n    assert(!(b <= a));\n    assert(b > a);\n    assert(!(a > b));\n    assert(b >= a);\n    assert(!(a >= b));\n    assert(a != b);\n    assert(!(a == b));\n}\n\n/* a must be numerically equal to b */\nfunction test_eq(a, b)\n{\n    assert(a == b);\n    assert(b == a);\n    assert(!(a != b));\n    assert(!(b != a));\n    assert(a <= b);\n    assert(b <= a);\n    assert(!(a < b));\n    assert(a >= b);\n    assert(b >= a);\n    assert(!(a > b));\n}\n\nfunction test_bigint1()\n{\n    var a, r;\n\n    test_less(2n, 3n);\n    test_eq(3n, 3n);\n\n    test_less(2, 3n);\n    test_eq(3, 3n);\n\n    test_less(2.1, 3n);\n    test_eq(Math.sqrt(4), 2n);\n\n    a = bigint_pow(3n, 100n);\n    assert((a - 1n) != a);\n    assert(a == 515377520732011331036461129765621272702107522001n);\n    assert(a == 0x5a4653ca673768565b41f775d6947d55cf3813d1n);\n\n    r = 1n << 31n;\n    assert(r, 2147483648n, \"1 << 31n === 2147483648n\");\n    \n    r = 1n << 32n;\n    assert(r, 4294967296n, \"1 << 32n === 4294967296n\");\n}\n\nfunction test_bigint2()\n{\n    assert(BigInt(\"\"), 0n);\n    assert(BigInt(\"  123\"), 123n);\n    assert(BigInt(\"  123   \"), 123n);\n    assertThrows(SyntaxError, () => { BigInt(\"+\") } );\n    assertThrows(SyntaxError, () => { BigInt(\"-\") } );\n    assertThrows(SyntaxError, () => { BigInt(\"\\x00a\") } );\n    assertThrows(SyntaxError, () => { BigInt(\"  123  r\") } );\n}\n\nfunction test_divrem(div1, a, b, q)\n{\n    var div, divrem, t;\n    div = BigInt[div1];\n    divrem = BigInt[div1 + \"rem\"];\n    assert(div(a, b) == q);\n    t = divrem(a, b);\n    assert(t[0] == q);\n    assert(a == b * q + t[1]);\n}\n\nfunction test_idiv1(div, a, b, r)\n{\n    test_divrem(div, a, b, r[0]);\n    test_divrem(div, -a, b, r[1]);\n    test_divrem(div, a, -b, r[2]);\n    test_divrem(div, -a, -b, r[3]);\n}\n\n/* QuickJS BigInt extensions */\nfunction test_bigint_ext()\n{\n    var r;\n    assert(BigInt.floorLog2(0n) === -1n);\n    assert(BigInt.floorLog2(7n) === 2n);\n\n    assert(BigInt.sqrt(0xffffffc000000000000000n) === 17592185913343n);\n    r = BigInt.sqrtrem(0xffffffc000000000000000n);\n    assert(r[0] === 17592185913343n);\n    assert(r[1] === 35167191957503n);\n\n    test_idiv1(\"tdiv\", 3n, 2n, [1n, -1n, -1n, 1n]);\n    test_idiv1(\"fdiv\", 3n, 2n, [1n, -2n, -2n, 1n]);\n    test_idiv1(\"cdiv\", 3n, 2n, [2n, -1n, -1n, 2n]);\n    test_idiv1(\"ediv\", 3n, 2n, [1n, -2n, -1n, 2n]);\n}\n\nfunction test_bigfloat()\n{\n    var e, a, b, sqrt2;\n    \n    assert(typeof 1n === \"bigint\");\n    assert(typeof 1l === \"bigfloat\");\n    assert(1 == 1.0l);\n    assert(1 !== 1.0l);\n\n    test_less(2l, 3l);\n    test_eq(3l, 3l);\n\n    test_less(2, 3l);\n    test_eq(3, 3l);\n\n    test_less(2.1, 3l);\n    test_eq(Math.sqrt(9), 3l);\n    \n    test_less(2n, 3l);\n    test_eq(3n, 3l);\n\n    e = new BigFloatEnv(128);\n    assert(e.prec == 128);\n    a = BigFloat.sqrt(2l, e);\n    assert(a === BigFloat.parseFloat(\"0x1.6a09e667f3bcc908b2fb1366ea957d3e\", 0, e));\n    assert(e.inexact === true);\n    assert(BigFloat.fpRound(a) == 0x1.6a09e667f3bcc908b2fb1366ea95l);\n    \n    b = BigFloatEnv.setPrec(BigFloat.sqrt.bind(null, 2), 128);\n    assert(a === b);\n\n    assert(BigFloat.isNaN(BigFloat(NaN)));\n    assert(BigFloat.isFinite(1l));\n    assert(!BigFloat.isFinite(1l/0l));\n\n    assert(BigFloat.abs(-3l) === 3l);\n    assert(BigFloat.sign(-3l) === -1l);\n\n    assert(BigFloat.exp(0.2l) === 1.2214027581601698339210719946396742l);\n    assert(BigFloat.log(3l) === 1.0986122886681096913952452369225256l);\n    assert(BigFloat.pow(2.1l, 1.6l) === 3.277561666451861947162828744873745l);\n    \n    assert(BigFloat.sin(-1l) === -0.841470984807896506652502321630299l);\n    assert(BigFloat.cos(1l) === 0.5403023058681397174009366074429766l);\n    assert(BigFloat.tan(0.1l) === 0.10033467208545054505808004578111154l);\n\n    assert(BigFloat.asin(0.3l) === 0.30469265401539750797200296122752915l);\n    assert(BigFloat.acos(0.4l) === 1.1592794807274085998465837940224159l);\n    assert(BigFloat.atan(0.7l) === 0.610725964389208616543758876490236l);\n    assert(BigFloat.atan2(7.1l, -5.1l) === 2.1937053809751415549388104628759813l);\n\n    assert(BigFloat.floor(2.5l) === 2l);\n    assert(BigFloat.ceil(2.5l) === 3l);\n    assert(BigFloat.trunc(-2.5l) === -2l);\n    assert(BigFloat.round(2.5l) === 3l);\n\n    assert(BigFloat.fmod(3l,2l) === 1l);\n    assert(BigFloat.remainder(3l,2l) === -1l);\n\n    /* string conversion */\n    assert((1234.125l).toString(), \"1234.125\");\n    assert((1234.125l).toFixed(2), \"1234.13\");\n    assert((1234.125l).toFixed(2, \"down\"), \"1234.12\");\n    assert((1234.125l).toExponential(), \"1.234125e+3\");\n    assert((1234.125l).toExponential(5), \"1.23413e+3\");\n    assert((1234.125l).toExponential(5, BigFloatEnv.RNDZ), \"1.23412e+3\");\n    assert((1234.125l).toPrecision(6), \"1234.13\");\n    assert((1234.125l).toPrecision(6, BigFloatEnv.RNDZ), \"1234.12\");\n\n    /* string conversion with binary base */\n    assert((0x123.438l).toString(16), \"123.438\");\n    assert((0x323.438l).toString(16), \"323.438\");\n    assert((0x723.438l).toString(16), \"723.438\");\n    assert((0xf23.438l).toString(16), \"f23.438\");\n    assert((0x123.438l).toFixed(2, BigFloatEnv.RNDNA, 16), \"123.44\");\n    assert((0x323.438l).toFixed(2, BigFloatEnv.RNDNA, 16), \"323.44\");\n    assert((0x723.438l).toFixed(2, BigFloatEnv.RNDNA, 16), \"723.44\");\n    assert((0xf23.438l).toFixed(2, BigFloatEnv.RNDNA, 16), \"f23.44\");\n    assert((0x0.0000438l).toFixed(6, BigFloatEnv.RNDNA, 16), \"0.000044\");\n    assert((0x1230000000l).toFixed(1, BigFloatEnv.RNDNA, 16), \"1230000000.0\");\n    assert((0x123.438l).toPrecision(5, BigFloatEnv.RNDNA, 16), \"123.44\");\n    assert((0x123.438l).toPrecision(5, BigFloatEnv.RNDZ, 16), \"123.43\");\n    assert((0x323.438l).toPrecision(5, BigFloatEnv.RNDNA, 16), \"323.44\");\n    assert((0x723.438l).toPrecision(5, BigFloatEnv.RNDNA, 16), \"723.44\");\n    assert((-0xf23.438l).toPrecision(5, BigFloatEnv.RNDD, 16), \"-f23.44\");\n    assert((0x123.438l).toExponential(4, BigFloatEnv.RNDNA, 16), \"1.2344p+8\");\n}\n\nfunction test_bigdecimal()\n{\n    assert(1m === 1m);\n    assert(1m !== 2m);\n    test_less(1m, 2m);\n    test_eq(2m, 2m);\n    \n    test_less(1, 2m);\n    test_eq(2, 2m);\n\n    test_less(1.1, 2m);\n    test_eq(Math.sqrt(4), 2m);\n    \n    test_less(2n, 3m);\n    test_eq(3n, 3m);\n    \n    assert(BigDecimal(\"1234.1\") === 1234.1m);\n    assert(BigDecimal(\"    1234.1\") === 1234.1m);\n    assert(BigDecimal(\"    1234.1  \") === 1234.1m);\n\n    assert(BigDecimal(0.1) === 0.1m);\n    assert(BigDecimal(123) === 123m);\n    assert(BigDecimal(true) === 1m);\n\n    assert(123m + 1m === 124m);\n    assert(123m - 1m === 122m);\n\n    assert(3.2m * 3m === 9.6m);\n    assert(10m / 2m === 5m);\n    assertThrows(RangeError, () => { 10m / 3m } );\n\n    assert(10m % 3m === 1m);\n    assert(-10m % 3m === -1m);\n\n    assert(1234.5m ** 3m === 1881365963.625m);\n    assertThrows(RangeError, () => { 2m ** 3.1m } );\n    assertThrows(RangeError, () => { 2m ** -3m } );\n    \n    assert(BigDecimal.sqrt(2m,\n                       { roundingMode: \"half-even\",\n                         maximumSignificantDigits: 4 }) === 1.414m);\n    assert(BigDecimal.sqrt(101m,\n                       { roundingMode: \"half-even\",\n                         maximumFractionDigits: 3 }) === 10.050m);\n    assert(BigDecimal.sqrt(0.002m,\n                       { roundingMode: \"half-even\",\n                         maximumFractionDigits: 3 }) === 0.045m);\n    \n    assert(BigDecimal.round(3.14159m,\n                       { roundingMode: \"half-even\",\n                         maximumFractionDigits: 3 }) === 3.142m);\n\n    assert(BigDecimal.add(3.14159m, 0.31212m,\n                          { roundingMode: \"half-even\",\n                            maximumFractionDigits: 2 }) === 3.45m);\n    assert(BigDecimal.sub(3.14159m, 0.31212m,\n                          { roundingMode: \"down\",\n                            maximumFractionDigits: 2 }) === 2.82m);\n    assert(BigDecimal.mul(3.14159m, 0.31212m,\n                          { roundingMode: \"half-even\",\n                            maximumFractionDigits: 3 }) === 0.981m);\n    assert(BigDecimal.mod(3.14159m, 0.31211m,\n                          { roundingMode: \"half-even\",\n                            maximumFractionDigits: 4 }) === 0.0205m);\n    assert(BigDecimal.div(20m, 3m,\n                       { roundingMode: \"half-even\",\n                         maximumSignificantDigits: 3 }) === 6.67m);\n    assert(BigDecimal.div(20m, 3m,\n                       { roundingMode: \"half-even\",\n                         maximumFractionDigits: 50 }) ===\n           6.66666666666666666666666666666666666666666666666667m);\n\n    /* string conversion */\n    assert((1234.125m).toString(), \"1234.125\");\n    assert((1234.125m).toFixed(2), \"1234.13\");\n    assert((1234.125m).toFixed(2, \"down\"), \"1234.12\");\n    assert((1234.125m).toExponential(), \"1.234125e+3\");\n    assert((1234.125m).toExponential(5), \"1.23413e+3\");\n    assert((1234.125m).toExponential(5, \"down\"), \"1.23412e+3\");\n    assert((1234.125m).toPrecision(6), \"1234.13\");\n    assert((1234.125m).toPrecision(6, \"down\"), \"1234.12\");\n    assert((-1234.125m).toPrecision(6, \"floor\"), \"-1234.13\");\n}\n\ntest_bigint1();\ntest_bigint2();\ntest_bigint_ext();\ntest_bigfloat();\ntest_bigdecimal();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/tests/test_bjson.js",
    "content": "import * as bjson from \"./bjson.so\";\n\nfunction assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\nfunction toHex(a)\n{\n    var i, s = \"\", tab, v;\n    tab = new Uint8Array(a);\n    for(i = 0; i < tab.length; i++) {\n        v = tab[i].toString(16);\n        if (v.length < 2)\n            v = \"0\" + v;\n        if (i !== 0)\n            s += \" \";\n        s += v;\n    }\n    return s;\n}\n\nfunction isArrayLike(a)\n{\n    return Array.isArray(a) || \n        (a instanceof Uint8ClampedArray) ||\n        (a instanceof Uint8Array) ||\n        (a instanceof Uint16Array) ||\n        (a instanceof Uint32Array) ||\n        (a instanceof Int8Array) ||\n        (a instanceof Int16Array) ||\n        (a instanceof Int32Array) ||\n        (a instanceof Float32Array) ||\n        (a instanceof Float64Array);\n}\n\nfunction toStr(a)\n{\n    var s, i, props, prop;\n\n    switch(typeof(a)) {\n    case \"object\":\n        if (a === null)\n            return \"null\";\n        if (a instanceof Date) {\n            s = \"Date(\" + toStr(a.valueOf()) + \")\";\n        } else if (a instanceof Number) {\n            s = \"Number(\" + toStr(a.valueOf()) + \")\";\n        } else if (a instanceof String) {\n            s = \"String(\" + toStr(a.valueOf()) + \")\";\n        } else if (a instanceof Boolean) {\n            s = \"Boolean(\" + toStr(a.valueOf()) + \")\";\n        } else if (isArrayLike(a)) {\n            s = \"[\";\n            for(i = 0; i < a.length; i++) {\n                if (i != 0)\n                    s += \",\";\n                s += toStr(a[i]);\n            }\n            s += \"]\";\n        } else {\n            props = Object.keys(a);\n            s = \"{\";\n            for(i = 0; i < props.length; i++) {\n                if (i != 0)\n                    s += \",\";\n                prop = props[i];\n                s += prop + \":\" + toStr(a[prop]);\n            }\n            s += \"}\";\n        }\n        return s;\n    case \"undefined\":\n        return \"undefined\";\n    case \"string\":\n        return a.__quote();\n    case \"number\":\n    case \"bigfloat\":\n        if (a == 0 && 1 / a < 0)\n            return \"-0\";\n        else\n            return a.toString();\n        break;\n    default:\n        return a.toString();\n    }\n}\n\nfunction bjson_test(a)\n{\n    var buf, r, a_str, r_str;\n    a_str = toStr(a);\n    buf = bjson.write(a);\n    if (0) {\n        print(a_str, \"->\", toHex(buf));\n    }\n    r = bjson.read(buf, 0, buf.byteLength);\n    r_str = toStr(r);\n    if (a_str != r_str) {\n        print(a_str);\n        print(r_str);\n        assert(false);\n    }\n}\n\n/* test multiple references to an object including circular\n   references */\nfunction bjson_test_reference()\n{\n    var array, buf, i, n, array_buffer;\n    n = 16;\n    array = [];\n    for(i = 0; i < n; i++)\n        array[i] = {};\n    array_buffer = new ArrayBuffer(n);\n    for(i = 0; i < n; i++) {\n        array[i].next = array[(i + 1) % n];\n        array[i].idx = i;\n        array[i].typed_array = new Uint8Array(array_buffer, i, 1);\n    }\n    buf = bjson.write(array, true);\n\n    array = bjson.read(buf, 0, buf.byteLength, true);\n\n    /* check the result */\n    for(i = 0; i < n; i++) {\n        assert(array[i].next, array[(i + 1) % n]);\n        assert(array[i].idx, i);\n        assert(array[i].typed_array.buffer, array_buffer);\n        assert(array[i].typed_array.length, 1);\n        assert(array[i].typed_array.byteOffset, i);\n    }\n}\n\nfunction bjson_test_all()\n{\n    var obj;\n    \n    bjson_test({x:1, y:2, if:3});\n    bjson_test([1, 2, 3]);\n    bjson_test([1.0, \"aa\", true, false, undefined, null, NaN, -Infinity, -0.0]);\n    if (typeof BigInt !== \"undefined\") {\n        bjson_test([BigInt(\"1\"), -BigInt(\"0x123456789\"),\n               BigInt(\"0x123456789abcdef123456789abcdef\")]);\n    }\n    if (typeof BigFloat !== \"undefined\") {\n        BigFloatEnv.setPrec(function () {\n            bjson_test([BigFloat(\"0.1\"), BigFloat(\"-1e30\"), BigFloat(\"0\"),\n                   BigFloat(\"-0\"), BigFloat(\"Infinity\"), BigFloat(\"-Infinity\"),\n                   0.0 / BigFloat(\"0\"), BigFloat.MAX_VALUE,\n                   BigFloat.MIN_VALUE]);\n        }, 113, 15);\n    }\n    if (typeof BigDecimal !== \"undefined\") {\n        bjson_test([BigDecimal(\"0\"),\n                    BigDecimal(\"0.8\"), BigDecimal(\"123321312321321e100\"),\n                    BigDecimal(\"-1233213123213214332333223332e100\"),\n                    BigDecimal(\"1.233e-1000\")]);\n    }\n\n    bjson_test([new Date(1234), new String(\"abc\"), new Number(-12.1), new Boolean(true)]);\n\n    bjson_test(new Int32Array([123123, 222111, -32222]));\n    bjson_test(new Float64Array([123123, 222111.5]));\n    \n    /* tested with a circular reference */\n    obj = {};\n    obj.x = obj;\n    try {\n        bjson.write(obj);\n        assert(false);\n    } catch(e) {\n        assert(e instanceof TypeError);\n    }\n\n    bjson_test_reference();\n}\n\nbjson_test_all();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/tests/test_builtin.js",
    "content": "\"use strict\";\n\nfunction assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\nfunction assert_throws(expected_error, func)\n{\n    var err = false;\n    try {\n        func();\n    } catch(e) {\n        err = true;\n        if (!(e instanceof expected_error)) {\n            throw Error(\"unexpected exception type\");\n        }\n    }\n    if (!err) {\n        throw Error(\"expected exception\");\n    }\n}\n\n// load more elaborate version of assert if available\ntry { __loadScript(\"test_assert.js\"); } catch(e) {}\n\n/*----------------*/\n\nfunction my_func(a, b)\n{\n    return a + b;\n}\n\nfunction test_function()\n{\n    function f(a, b) {\n        var i, tab = [];\n        tab.push(this);\n        for(i = 0; i < arguments.length; i++)\n            tab.push(arguments[i]);\n        return tab;\n    }\n    function constructor1(a) {\n        this.x = a;\n    }\n\n    var r, g;\n    \n    r = my_func.call(null, 1, 2);\n    assert(r, 3, \"call\");\n\n    r = my_func.apply(null, [1, 2]);\n    assert(r, 3, \"apply\");\n\n    r = (function () { return 1; }).apply(null, undefined);\n    assert(r, 1);\n\n    assert_throws(TypeError, (function() {\n        Reflect.apply((function () { return 1; }), null, undefined);\n    }));\n    \n    r = new Function(\"a\", \"b\", \"return a + b;\");\n    assert(r(2,3), 5, \"function\");\n    \n    g = f.bind(1, 2);\n    assert(g.length, 1);\n    assert(g.name, \"bound f\");\n    assert(g(3), [1,2,3]);\n\n    g = constructor1.bind(null, 1);\n    r = new g();\n    assert(r.x, 1);\n}\n\nfunction test()\n{\n    var r, a, b, c, err;\n\n    r = Error(\"hello\");\n    assert(r.message, \"hello\", \"Error\");\n\n    a = new Object();\n    a.x = 1;\n    assert(a.x, 1, \"Object\");\n\n    assert(Object.getPrototypeOf(a), Object.prototype, \"getPrototypeOf\");\n    Object.defineProperty(a, \"y\", { value: 3, writable: true, configurable: true, enumerable: true });\n    assert(a.y, 3, \"defineProperty\");\n\n    Object.defineProperty(a, \"z\", { get: function () { return 4; }, set: function(val) { this.z_val = val; }, configurable: true, enumerable: true });\n    assert(a.z, 4, \"get\");\n    a.z = 5;\n    assert(a.z_val, 5, \"set\");\n    \n    a = { get z() { return 4; }, set z(val) { this.z_val = val; } };\n    assert(a.z, 4, \"get\");\n    a.z = 5;\n    assert(a.z_val, 5, \"set\");\n\n    b = Object.create(a);\n    assert(Object.getPrototypeOf(b), a, \"create\");\n    c = {u:2};\n    /* XXX: refcount bug in 'b' instead of 'a' */\n    Object.setPrototypeOf(a, c);\n    assert(Object.getPrototypeOf(a), c, \"setPrototypeOf\");\n\n    a = {};\n    assert(a.toString(), \"[object Object]\", \"toString\");\n\n    a = {x:1};\n    assert(Object.isExtensible(a), true, \"extensible\");\n    Object.preventExtensions(a);\n\n    err = false;\n    try {\n        a.y = 2;\n    } catch(e) {\n        err = true;\n    }\n    assert(Object.isExtensible(a), false, \"extensible\");\n    assert(typeof a.y, \"undefined\", \"extensible\");\n    assert(err, true, \"extensible\");\n}\n\nfunction test_enum()\n{\n    var a, tab;\n    a = {x:1,\n         \"18014398509481984\": 1,\n         \"9007199254740992\": 1,\n         \"9007199254740991\": 1,\n         \"4294967296\": 1,\n         \"4294967295\": 1,\n         y:1,\n         \"4294967294\": 1,\n         \"1\": 2};\n    tab = Object.keys(a);\n//    console.log(\"tab=\" + tab.toString());\n    assert(tab, [\"1\",\"4294967294\",\"x\",\"18014398509481984\",\"9007199254740992\",\"9007199254740991\",\"4294967296\",\"4294967295\",\"y\"], \"keys\");\n}\n\nfunction test_array()\n{\n    var a, err;\n\n    a = [1, 2, 3];\n    assert(a.length, 3, \"array\");\n    assert(a[2], 3, \"array1\");\n\n    a = new Array(10);\n    assert(a.length, 10, \"array2\");\n\n    a = new Array(1, 2);\n    assert(a.length === 2 && a[0] === 1 && a[1] === 2, true, \"array3\");\n\n    a = [1, 2, 3];\n    a.length = 2;\n    assert(a.length === 2 && a[0] === 1 && a[1] === 2, true, \"array4\");\n\n    a = [];\n    a[1] = 10;\n    a[4] = 3;\n    assert(a.length, 5);\n\n    a = [1,2];\n    a.length = 5;\n    a[4] = 1;\n    a.length = 4;\n    assert(a[4] !== 1, true, \"array5\");\n\n    a = [1,2];\n    a.push(3,4);\n    assert(a.join(), \"1,2,3,4\", \"join\");\n\n    a = [1,2,3,4,5];\n    Object.defineProperty(a, \"3\", { configurable: false });\n    err = false;\n    try {\n        a.length = 2;\n    } catch(e) {\n        err = true;\n    }\n    assert(err && a.toString() === \"1,2,3,4\");\n}\n\nfunction test_string()\n{\n    var a;\n    a = String(\"abc\");\n    assert(a.length, 3, \"string\");\n    assert(a[1], \"b\", \"string\");\n    assert(a.charCodeAt(1), 0x62, \"string\");\n    assert(String.fromCharCode(65), \"A\", \"string\");\n    assert(String.fromCharCode.apply(null, [65, 66, 67]), \"ABC\", \"string\");\n    assert(a.charAt(1), \"b\");\n    assert(a.charAt(-1), \"\");\n    assert(a.charAt(3), \"\");\n    \n    a = \"abcd\";\n    assert(a.substring(1, 3), \"bc\", \"substring\");\n    a = String.fromCharCode(0x20ac);\n    assert(a.charCodeAt(0), 0x20ac, \"unicode\");\n    assert(a, \"€\", \"unicode\");\n    assert(a, \"\\u20ac\", \"unicode\");\n    assert(a, \"\\u{20ac}\", \"unicode\");\n    assert(\"a\", \"\\x61\", \"unicode\");\n        \n    a = \"\\u{10ffff}\";\n    assert(a.length, 2, \"unicode\");\n    assert(a, \"\\u{dbff}\\u{dfff}\", \"unicode\");\n    assert(a.codePointAt(0), 0x10ffff);\n    assert(String.fromCodePoint(0x10ffff), a);\n\n    assert(\"a\".concat(\"b\", \"c\"), \"abc\");\n\n    assert(\"abcabc\".indexOf(\"cab\"), 2);\n    assert(\"abcabc\".indexOf(\"cab2\"), -1);\n    assert(\"abc\".indexOf(\"c\"), 2);\n\n    assert(\"aaa\".indexOf(\"a\"), 0);\n    assert(\"aaa\".indexOf(\"a\", NaN), 0);\n    assert(\"aaa\".indexOf(\"a\", -Infinity), 0);\n    assert(\"aaa\".indexOf(\"a\", -1), 0);\n    assert(\"aaa\".indexOf(\"a\", -0), 0);\n    assert(\"aaa\".indexOf(\"a\", 0), 0);\n    assert(\"aaa\".indexOf(\"a\", 1), 1);\n    assert(\"aaa\".indexOf(\"a\", 2), 2);\n    assert(\"aaa\".indexOf(\"a\", 3), -1);\n    assert(\"aaa\".indexOf(\"a\", 4), -1);\n    assert(\"aaa\".indexOf(\"a\", Infinity), -1);\n\n    assert(\"aaa\".indexOf(\"\"), 0);\n    assert(\"aaa\".indexOf(\"\", NaN), 0);\n    assert(\"aaa\".indexOf(\"\", -Infinity), 0);\n    assert(\"aaa\".indexOf(\"\", -1), 0);\n    assert(\"aaa\".indexOf(\"\", -0), 0);\n    assert(\"aaa\".indexOf(\"\", 0), 0);\n    assert(\"aaa\".indexOf(\"\", 1), 1);\n    assert(\"aaa\".indexOf(\"\", 2), 2);\n    assert(\"aaa\".indexOf(\"\", 3), 3);\n    assert(\"aaa\".indexOf(\"\", 4), 3);\n    assert(\"aaa\".indexOf(\"\", Infinity), 3);\n\n    assert(\"aaa\".lastIndexOf(\"a\"), 2);\n    assert(\"aaa\".lastIndexOf(\"a\", NaN), 2);\n    assert(\"aaa\".lastIndexOf(\"a\", -Infinity), 0);\n    assert(\"aaa\".lastIndexOf(\"a\", -1), 0);\n    assert(\"aaa\".lastIndexOf(\"a\", -0), 0);\n    assert(\"aaa\".lastIndexOf(\"a\", 0), 0);\n    assert(\"aaa\".lastIndexOf(\"a\", 1), 1);\n    assert(\"aaa\".lastIndexOf(\"a\", 2), 2);\n    assert(\"aaa\".lastIndexOf(\"a\", 3), 2);\n    assert(\"aaa\".lastIndexOf(\"a\", 4), 2);\n    assert(\"aaa\".lastIndexOf(\"a\", Infinity), 2);\n\n    assert(\"aaa\".lastIndexOf(\"\"), 3);\n    assert(\"aaa\".lastIndexOf(\"\", NaN), 3);\n    assert(\"aaa\".lastIndexOf(\"\", -Infinity), 0);\n    assert(\"aaa\".lastIndexOf(\"\", -1), 0);\n    assert(\"aaa\".lastIndexOf(\"\", -0), 0);\n    assert(\"aaa\".lastIndexOf(\"\", 0), 0);\n    assert(\"aaa\".lastIndexOf(\"\", 1), 1);\n    assert(\"aaa\".lastIndexOf(\"\", 2), 2);\n    assert(\"aaa\".lastIndexOf(\"\", 3), 3);\n    assert(\"aaa\".lastIndexOf(\"\", 4), 3);\n    assert(\"aaa\".lastIndexOf(\"\", Infinity), 3);\n\n    assert(\"a,b,c\".split(\",\"), [\"a\",\"b\",\"c\"]);\n    assert(\",b,c\".split(\",\"), [\"\",\"b\",\"c\"]);\n    assert(\"a,b,\".split(\",\"), [\"a\",\"b\",\"\"]);\n\n    assert(\"aaaa\".split(), [ \"aaaa\" ]);\n    assert(\"aaaa\".split(undefined, 0), [ ]);\n    assert(\"aaaa\".split(\"\"), [ \"a\", \"a\", \"a\", \"a\" ]);\n    assert(\"aaaa\".split(\"\", 0), [ ]);\n    assert(\"aaaa\".split(\"\", 1), [ \"a\" ]);\n    assert(\"aaaa\".split(\"\", 2), [ \"a\", \"a\" ]);\n    assert(\"aaaa\".split(\"a\"), [ \"\", \"\", \"\", \"\", \"\" ]);\n    assert(\"aaaa\".split(\"a\", 2), [ \"\", \"\" ]);\n    assert(\"aaaa\".split(\"aa\"), [ \"\", \"\", \"\" ]);\n    assert(\"aaaa\".split(\"aa\", 0), [ ]);\n    assert(\"aaaa\".split(\"aa\", 1), [ \"\" ]);\n    assert(\"aaaa\".split(\"aa\", 2), [ \"\", \"\" ]);\n    assert(\"aaaa\".split(\"aaa\"), [ \"\", \"a\" ]);\n    assert(\"aaaa\".split(\"aaaa\"), [ \"\", \"\" ]);\n    assert(\"aaaa\".split(\"aaaaa\"), [ \"aaaa\" ]);\n    assert(\"aaaa\".split(\"aaaaa\", 0), [  ]);\n    assert(\"aaaa\".split(\"aaaaa\", 1), [ \"aaaa\" ]);\n\n    assert(eval('\"\\0\"'), \"\\0\");\n\n    assert(\"abc\".padStart(Infinity, \"\"), \"abc\");\n}\n\nfunction test_math()\n{\n    var a;\n    a = 1.4;\n    assert(Math.floor(a), 1);\n    assert(Math.ceil(a), 2);\n    assert(Math.imul(0x12345678, 123), -1088058456);\n    assert(Math.fround(0.1), 0.10000000149011612);\n    assert(Math.hypot() == 0);\n    assert(Math.hypot(-2) == 2);\n    assert(Math.hypot(3, 4) == 5);\n    assert(Math.abs(Math.hypot(3, 4, 5) - 7.0710678118654755) <= 1e-15);\n}\n\nfunction test_number()\n{\n    assert(parseInt(\"123\"), 123);\n    assert(parseInt(\"  123r\"), 123);\n    assert(parseInt(\"0x123\"), 0x123);\n    assert(parseInt(\"0o123\"), 0);\n    assert(+\"  123   \", 123);\n    assert(+\"0b111\", 7);\n    assert(+\"0o123\", 83);\n    assert(parseFloat(\"0x1234\"), 0);\n    assert(parseFloat(\"Infinity\"), Infinity);\n    assert(parseFloat(\"-Infinity\"), -Infinity);\n    assert(parseFloat(\"123.2\"), 123.2);\n    assert(parseFloat(\"123.2e3\"), 123200);\n    assert(Number.isNaN(Number(\"+\")));\n    assert(Number.isNaN(Number(\"-\")));\n    assert(Number.isNaN(Number(\"\\x00a\")));\n\n    assert((25).toExponential(0), \"3e+1\");\n    assert((-25).toExponential(0), \"-3e+1\");\n    assert((2.5).toPrecision(1), \"3\");\n    assert((-2.5).toPrecision(1), \"-3\");\n    assert((1.125).toFixed(2), \"1.13\");\n    assert((-1.125).toFixed(2), \"-1.13\");\n}\n\nfunction test_eval2()\n{\n    var g_call_count = 0;\n    /* force non strict mode for f1 and f2 */\n    var f1 = new Function(\"eval\", \"eval(1, 2)\");\n    var f2 = new Function(\"eval\", \"eval(...[1, 2])\");\n    function g(a, b) {\n        assert(a, 1);\n        assert(b, 2);\n        g_call_count++;\n    }\n    f1(g);\n    f2(g);\n    assert(g_call_count, 2);\n}\n\nfunction test_eval()\n{\n    function f(b) {\n        var x = 1;\n        return eval(b);\n    }\n    var r, a;\n\n    r = eval(\"1+1;\");\n    assert(r, 2, \"eval\");\n\n    r = eval(\"var my_var=2; my_var;\");\n    assert(r, 2, \"eval\");\n    assert(typeof my_var, \"undefined\");\n\n    assert(eval(\"if (1) 2; else 3;\"), 2);\n    assert(eval(\"if (0) 2; else 3;\"), 3);\n\n    assert(f.call(1, \"this\"), 1);\n    \n    a = 2;\n    assert(eval(\"a\"), 2);\n\n    eval(\"a = 3\");\n    assert(a, 3);\n\n    assert(f(\"arguments.length\", 1), 2);\n    assert(f(\"arguments[1]\", 1), 1);\n\n    a = 4;\n    assert(f(\"a\"), 4);\n    f(\"a=3\");\n    assert(a, 3);\n\n    test_eval2();\n}\n\nfunction test_typed_array()\n{\n    var buffer, a, i, str;\n\n    a = new Uint8Array(4);\n    assert(a.length, 4);\n    for(i = 0; i < a.length; i++)\n        a[i] = i;\n    assert(a.join(\",\"), \"0,1,2,3\");\n    a[0] = -1;\n    assert(a[0], 255);\n\n    a = new Int8Array(3);\n    a[0] = 255;\n    assert(a[0], -1);\n\n    a = new Int32Array(3);\n    a[0] = Math.pow(2, 32) - 1;\n    assert(a[0], -1);\n    assert(a.BYTES_PER_ELEMENT, 4);\n\n    a = new Uint8ClampedArray(4);\n    a[0] = -100;\n    a[1] = 1.5;\n    a[2] = 0.5;\n    a[3] = 1233.5;\n    assert(a.toString(), \"0,2,0,255\");\n    \n    buffer = new ArrayBuffer(16);\n    assert(buffer.byteLength, 16);\n    a = new Uint32Array(buffer, 12, 1);\n    assert(a.length, 1);\n    a[0] = -1;\n\n    a = new Uint16Array(buffer, 2);\n    a[0] = -1;\n\n    a = new Float32Array(buffer, 8, 1);\n    a[0] = 1;\n    \n    a = new Uint8Array(buffer);\n\n    str = a.toString();\n    /* test little and big endian cases */\n    if (str !== \"0,0,255,255,0,0,0,0,0,0,128,63,255,255,255,255\" &&\n        str !== \"0,0,255,255,0,0,0,0,63,128,0,0,255,255,255,255\") {\n        assert(false);\n    }\n\n    assert(a.buffer, buffer);\n\n    a = new Uint8Array([1, 2, 3, 4]);\n    assert(a.toString(), \"1,2,3,4\");\n    a.set([10, 11], 2);\n    assert(a.toString(), \"1,2,10,11\");\n}\n\nfunction test_json()\n{\n    var a, s;\n    s = '{\"x\":1,\"y\":true,\"z\":null,\"a\":[1,2,3],\"s\":\"str\"}';\n    a = JSON.parse(s);\n    assert(a.x, 1);\n    assert(a.y, true);\n    assert(a.z, null);\n    assert(JSON.stringify(a), s);\n\n    /* indentation test */\n    assert(JSON.stringify([[{x:1,y:{},z:[]},2,3]],undefined,1),\n`[\n [\n  {\n   \"x\": 1,\n   \"y\": {},\n   \"z\": []\n  },\n  2,\n  3\n ]\n]`);\n}\n\nfunction test_date()\n{\n    var d = new Date(1506098258091), a, s;\n    assert(d.toISOString(), \"2017-09-22T16:37:38.091Z\");\n    d.setUTCHours(18, 10, 11);\n    assert(d.toISOString(), \"2017-09-22T18:10:11.091Z\");\n    a = Date.parse(d.toISOString());\n    assert((new Date(a)).toISOString(), d.toISOString());\n    s = new Date(\"2020-01-01T01:01:01.1Z\").toISOString();\n    assert(s ==  \"2020-01-01T01:01:01.100Z\");\n    s = new Date(\"2020-01-01T01:01:01.12Z\").toISOString();\n    assert(s ==  \"2020-01-01T01:01:01.120Z\");\n    s = new Date(\"2020-01-01T01:01:01.123Z\").toISOString();\n    assert(s ==  \"2020-01-01T01:01:01.123Z\");\n    s = new Date(\"2020-01-01T01:01:01.1234Z\").toISOString();\n    assert(s ==  \"2020-01-01T01:01:01.123Z\");\n    s = new Date(\"2020-01-01T01:01:01.12345Z\").toISOString();\n    assert(s ==  \"2020-01-01T01:01:01.123Z\");\n    s = new Date(\"2020-01-01T01:01:01.1235Z\").toISOString();\n    assert(s ==  \"2020-01-01T01:01:01.124Z\");\n    s = new Date(\"2020-01-01T01:01:01.9999Z\").toISOString();\n    assert(s ==  \"2020-01-01T01:01:02.000Z\");\n}\n\nfunction test_regexp()\n{\n    var a, str;\n    str = \"abbbbbc\";\n    a = /(b+)c/.exec(str);\n    assert(a[0], \"bbbbbc\");\n    assert(a[1], \"bbbbb\");\n    assert(a.index, 1);\n    assert(a.input, str);\n    a = /(b+)c/.test(str);\n    assert(a, true);\n    assert(/\\x61/.exec(\"a\")[0], \"a\");\n    assert(/\\u0061/.exec(\"a\")[0], \"a\");\n    assert(/\\ca/.exec(\"\\x01\")[0], \"\\x01\");\n    assert(/\\\\a/.exec(\"\\\\a\")[0], \"\\\\a\");\n    assert(/\\c0/.exec(\"\\\\c0\")[0], \"\\\\c0\");\n\n    a = /(\\.(?=com|org)|\\/)/.exec(\"ah.com\");\n    assert(a.index === 2 && a[0] === \".\");\n\n    a = /(\\.(?!com|org)|\\/)/.exec(\"ah.com\");\n    assert(a, null);\n    \n    a = /(?=(a+))/.exec(\"baaabac\");\n    assert(a.index === 1 && a[0] === \"\" && a[1] === \"aaa\");\n\n    a = /(z)((a+)?(b+)?(c))*/.exec(\"zaacbbbcac\");\n    assert(a, [\"zaacbbbcac\",\"z\",\"ac\",\"a\",,\"c\"]);\n\n    a = eval(\"/\\0a/\");\n    assert(a.toString(), \"/\\0a/\");\n    assert(a.exec(\"\\0a\")[0], \"\\0a\");\n\n    assert(/{1a}/.toString(), \"/{1a}/\");\n    a = /a{1+/.exec(\"a{11\");\n    assert(a, [\"a{11\"] );\n}\n\nfunction test_symbol()\n{\n    var a, b, obj, c;\n    a = Symbol(\"abc\");\n    obj = {};\n    obj[a] = 2;\n    assert(obj[a], 2);\n    assert(typeof obj[\"abc\"], \"undefined\");\n    assert(String(a), \"Symbol(abc)\");\n    b = Symbol(\"abc\");\n    assert(a == a);\n    assert(a === a);\n    assert(a != b);\n    assert(a !== b);\n\n    b = Symbol.for(\"abc\");\n    c = Symbol.for(\"abc\");\n    assert(b === c);\n    assert(b !== a);\n\n    assert(Symbol.keyFor(b), \"abc\");\n    assert(Symbol.keyFor(a), undefined);\n\n    a = Symbol(\"aaa\");\n    assert(a.valueOf(), a);\n    assert(a.toString(), \"Symbol(aaa)\");\n\n    b = Object(a);\n    assert(b.valueOf(), a);\n    assert(b.toString(), \"Symbol(aaa)\");\n}\n\nfunction test_map()\n{\n    var a, i, n, tab, o, v;\n    n = 1000;\n    a = new Map();\n    tab = [];\n    for(i = 0; i < n; i++) {\n        v = { };\n        o = { id: i };\n        tab[i] = [o, v];\n        a.set(o, v);\n    }\n\n    assert(a.size, n);\n    for(i = 0; i < n; i++) {\n        assert(a.get(tab[i][0]), tab[i][1]);\n    }\n\n    i = 0;\n    a.forEach(function (v, o) { \n        assert(o, tab[i++][0]);\n        assert(a.has(o));\n        assert(a.delete(o));\n        assert(!a.has(o));\n    });\n\n    assert(a.size, 0);\n}\n\nfunction test_weak_map()\n{\n    var a, i, n, tab, o, v, n2;\n    a = new WeakMap();\n    n = 10;\n    tab = [];\n    for(i = 0; i < n; i++) {\n        v = { };\n        o = { id: i };\n        tab[i] = [o, v];\n        a.set(o, v);\n    }\n    o = null;\n    \n    n2 = n >> 1;\n    for(i = 0; i < n2; i++) {\n        a.delete(tab[i][0]);\n    }\n    for(i = n2; i < n; i++) {\n        tab[i][0] = null; /* should remove the object from the WeakMap too */\n    }\n    /* the WeakMap should be empty here */\n}\n\nfunction test_generator()\n{\n    function *f() {\n        var ret;\n        yield 1;\n        ret = yield 2;\n        assert(ret, \"next_arg\");\n        return 3;\n    }\n    function *f2() {\n        yield 1;\n        yield 2;\n        return \"ret_val\";\n    }\n    function *f1() {\n        var ret = yield *f2();\n        assert(ret, \"ret_val\");\n        return 3;\n    }\n    var g, v;\n    g = f();\n    v = g.next();\n    assert(v.value === 1 && v.done === false);\n    v = g.next();\n    assert(v.value === 2 && v.done === false);\n    v = g.next(\"next_arg\");\n    assert(v.value === 3 && v.done === true);\n    v = g.next();\n    assert(v.value === undefined && v.done === true);\n\n    g = f1();\n    v = g.next();\n    assert(v.value === 1 && v.done === false);\n    v = g.next();\n    assert(v.value === 2 && v.done === false);\n    v = g.next();\n    assert(v.value === 3 && v.done === true);\n    v = g.next();\n    assert(v.value === undefined && v.done === true);\n}\n\ntest();\ntest_function();\ntest_enum();\ntest_array();\ntest_string();\ntest_math();\ntest_number();\ntest_eval();\ntest_typed_array();\ntest_json();\ntest_date();\ntest_regexp();\ntest_symbol();\ntest_map();\ntest_weak_map();\ntest_generator();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/tests/test_closure.js",
    "content": "function assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\n// load more elaborate version of assert if available\ntry { __loadScript(\"test_assert.js\"); } catch(e) {}\n\n/*----------------*/\n\nvar log_str = \"\";\n\nfunction log(str)\n{\n    log_str += str + \",\";\n}\n\nfunction f(a, b, c)\n{\n    var x = 10;\n    log(\"a=\"+a);\n    function g(d) {\n        function h() {\n            log(\"d=\" + d);\n            log(\"x=\" + x);\n        }\n        log(\"b=\" + b);\n        log(\"c=\" + c);\n        h();\n    }\n    g(4);\n    return g;\n}\n\nvar g1 = f(1, 2, 3);\ng1(5);\n\nassert(log_str, \"a=1,b=2,c=3,d=4,x=10,b=2,c=3,d=5,x=10,\", \"closure1\");\n\nfunction test_closure1()\n{\n    function f2()\n    {\n        var val = 1;\n        \n        function set(a) {\n            val = a;\n        }\n        function get(a) {\n            return val;\n        }\n        return { \"set\": set, \"get\": get };\n    }\n    \n    var obj = f2();\n    obj.set(10);\n    var r;\n    r = obj.get();\n    assert(r, 10, \"closure2\");\n}\n\nfunction test_closure2()\n{\n    var expr_func = function myfunc1(n) {\n        function myfunc2(n) {\n            return myfunc1(n - 1);\n        }\n        if (n == 0)\n            return 0;\n        else\n            return myfunc2(n);\n    };\n    var r;\n    r = expr_func(1);\n    assert(r, 0, \"expr_func\");\n}\n\nfunction test_closure3()\n{\n    function fib(n)\n    {\n        if (n <= 0)\n            return 0;\n        else if (n == 1)\n            return 1;\n        else\n            return fib(n - 1) + fib(n - 2);\n    }\n\n    var fib_func = function fib1(n)\n    {\n        if (n <= 0)\n            return 0;\n        else if (n == 1)\n            return 1;\n        else\n            return fib1(n - 1) + fib1(n - 2);\n    };\n\n    assert(fib(6), 8, \"fib\");\n    assert(fib_func(6), 8, \"fib_func\");\n}\n\nfunction test_arrow_function()\n{\n    \"use strict\";\n\n    function f1() {\n        return (() => arguments)();\n    }\n    function f2() {\n        return (() => this)();\n    }\n    function f3() {\n        return (() => eval(\"this\"))();\n    }\n    function f4() {\n        return (() => eval(\"new.target\"))();\n    }\n    var a;\n\n    a = f1(1, 2);\n    assert(a.length, 2);\n    assert(a[0] === 1 && a[1] === 2);\n\n    assert(f2.call(\"this_val\") === \"this_val\");\n    assert(f3.call(\"this_val\") === \"this_val\");\n    assert(new f4() === f4);\n\n    var o1 = { f() { return this; } };\n    var o2 = { f() {\n        return (() => eval(\"super.f()\"))();\n    } };\n    o2.__proto__ = o1;\n\n    assert(o2.f() === o2);\n}\n\nfunction test_with()\n{\n    var o1 = { x: \"o1\", y: \"o1\" };\n    var x = \"local\";\n    eval('var z=\"var_obj\";');\n    assert(z === \"var_obj\");\n    with (o1) {\n        assert(x === \"o1\");\n        assert(eval(\"x\") === \"o1\");\n        var f = function () {\n            o2 = { x: \"o2\" };\n            with (o2) {\n                assert(x === \"o2\");\n                assert(y === \"o1\");\n                assert(z === \"var_obj\");\n                assert(eval(\"x\") === \"o2\");\n                assert(eval(\"y\") === \"o1\");\n                assert(eval(\"z\") === \"var_obj\");\n                assert(eval('eval(\"x\")') === \"o2\");\n            }\n        };\n        f();\n    }\n}\n\nfunction test_eval_closure()\n{\n    var tab;\n\n    tab = [];\n    for(let i = 0; i < 3; i++) {\n        eval(\"tab.push(function g1() { return i; })\");\n    }\n    for(let i = 0; i < 3; i++) {\n        assert(tab[i]() === i);\n    }\n\n    tab = [];\n    for(let i = 0; i < 3; i++) {\n        let f = function f() {\n            eval(\"tab.push(function g2() { return i; })\");\n        };\n        f();\n    }\n    for(let i = 0; i < 3; i++) {\n        assert(tab[i]() === i);\n    }\n}\n\nfunction test_eval_const()\n{\n    const a = 1;\n    var success = false;\n    var f = function () {\n        eval(\"a = 1\");\n    };\n    try {\n        f();\n    } catch(e) {\n        success = (e instanceof TypeError);\n    }\n    assert(success);\n}\n\ntest_closure1();\ntest_closure2();\ntest_closure3();\ntest_arrow_function();\ntest_with();\ntest_eval_closure();\ntest_eval_const();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/tests/test_language.js",
    "content": "function assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\nfunction assert_throws(expected_error, func)\n{\n    var err = false;\n    try {\n        func();\n    } catch(e) {\n        err = true;\n        if (!(e instanceof expected_error)) {\n            throw Error(\"unexpected exception type\");\n        }\n    }\n    if (!err) {\n        throw Error(\"expected exception\");\n    }\n}\n\n// load more elaborate version of assert if available\ntry { __loadScript(\"test_assert.js\"); } catch(e) {}\n\n/*----------------*/\n\nfunction test_op1()\n{\n    var r, a;\n    r = 1 + 2;\n    assert(r, 3, \"1 + 2 === 3\");\n\n    r = 1 - 2;\n    assert(r, -1, \"1 - 2 === -1\");\n\n    r = -1;\n    assert(r, -1, \"-1 === -1\");\n\n    r = +2;\n    assert(r, 2, \"+2 === 2\");\n\n    r = 2 * 3;\n    assert(r, 6, \"2 * 3 === 6\");\n\n    r = 4 / 2;\n    assert(r, 2, \"4 / 2 === 2\");\n\n    r = 4 % 3;\n    assert(r, 1, \"4 % 3 === 3\");\n\n    r = 4 << 2;\n    assert(r, 16, \"4 << 2 === 16\");\n\n    r = 1 << 0;\n    assert(r, 1, \"1 << 0 === 1\");\n\n    r = 1 << 31;\n    assert(r, -2147483648, \"1 << 31 === -2147483648\");\n    \n    r = 1 << 32;\n    assert(r, 1, \"1 << 32 === 1\");\n    \n    r = (1 << 31) < 0;\n    assert(r, true, \"(1 << 31) < 0 === true\");\n\n    r = -4 >> 1;\n    assert(r, -2, \"-4 >> 1 === -2\");\n\n    r = -4 >>> 1;\n    assert(r, 0x7ffffffe, \"-4 >>> 1 === 0x7ffffffe\");\n\n    r = 1 & 1;\n    assert(r, 1, \"1 & 1 === 1\");\n\n    r = 0 | 1;\n    assert(r, 1, \"0 | 1 === 1\");\n\n    r = 1 ^ 1;\n    assert(r, 0, \"1 ^ 1 === 0\");\n\n    r = ~1;\n    assert(r, -2, \"~1 === -2\");\n\n    r = !1;\n    assert(r, false, \"!1 === false\");\n\n    assert((1 < 2), true, \"(1 < 2) === true\");\n\n    assert((2 > 1), true, \"(2 > 1) === true\");\n\n    assert(('b' > 'a'), true, \"('b' > 'a') === true\");\n\n    assert(2 ** 8, 256, \"2 ** 8 === 256\");\n}\n\nfunction test_cvt()\n{\n    assert((NaN | 0) === 0);\n    assert((Infinity | 0) === 0);\n    assert(((-Infinity) | 0) === 0);\n    assert((\"12345\" | 0) === 12345);\n    assert((\"0x12345\" | 0) === 0x12345);\n    assert(((4294967296 * 3 - 4) | 0) === -4);\n    \n    assert((\"12345\" >>> 0) === 12345);\n    assert((\"0x12345\" >>> 0) === 0x12345);\n    assert((NaN >>> 0) === 0);\n    assert((Infinity >>> 0) === 0);\n    assert(((-Infinity) >>> 0) === 0);\n    assert(((4294967296 * 3 - 4) >>> 0) === (4294967296 - 4));\n}\n\nfunction test_eq()\n{\n    assert(null == undefined);\n    assert(undefined == null);\n    assert(true == 1);\n    assert(0 == false);\n    assert(\"\" == 0);\n    assert(\"123\" == 123);\n    assert(\"122\" != 123);\n    assert((new Number(1)) == 1);\n    assert(2 == (new Number(2)));\n    assert((new String(\"abc\")) == \"abc\");\n    assert({} != \"abc\");\n}\n\nfunction test_inc_dec()\n{\n    var a, r;\n    \n    a = 1;\n    r = a++;\n    assert(r === 1 && a === 2, true, \"++\");\n\n    a = 1;\n    r = ++a;\n    assert(r === 2 && a === 2, true, \"++\");\n\n    a = 1;\n    r = a--;\n    assert(r === 1 && a === 0, true, \"--\");\n\n    a = 1;\n    r = --a;\n    assert(r === 0 && a === 0, true, \"--\");\n\n    a = {x:true};\n    a.x++;\n    assert(a.x, 2, \"++\");\n\n    a = {x:true};\n    a.x--;\n    assert(a.x, 0, \"--\");\n\n    a = [true];\n    a[0]++;\n    assert(a[0], 2, \"++\");\n    \n    a = {x:true};\n    r = a.x++;\n    assert(r === 1 && a.x === 2, true, \"++\");\n    \n    a = {x:true};\n    r = a.x--;\n    assert(r === 1 && a.x === 0, true, \"--\");\n    \n    a = [true];\n    r = a[0]++;\n    assert(r === 1 && a[0] === 2, true, \"++\");\n    \n    a = [true];\n    r = a[0]--;\n    assert(r === 1 && a[0] === 0, true, \"--\");\n}\n\nfunction F(x)\n{\n    this.x = x;\n}\n\nfunction test_op2()\n{\n    var a, b;\n    a = new Object;\n    a.x = 1;\n    assert(a.x, 1, \"new\");\n    b = new F(2);\n    assert(b.x, 2, \"new\");\n\n    a = {x : 2};\n    assert((\"x\" in a), true, \"in\");\n    assert((\"y\" in a), false, \"in\");\n\n    a = {};\n    assert((a instanceof Object), true, \"instanceof\");\n    assert((a instanceof String), false, \"instanceof\");\n\n    assert((typeof 1), \"number\", \"typeof\");\n    assert((typeof Object), \"function\", \"typeof\");\n    assert((typeof null), \"object\", \"typeof\");\n    assert((typeof unknown_var), \"undefined\", \"typeof\");\n    \n    a = {x: 1, if: 2, async: 3};\n    assert(a.if === 2);\n    assert(a.async === 3);\n}\n\nfunction test_delete()\n{\n    var a, err;\n\n    a = {x: 1, y: 1};\n    assert((delete a.x), true, \"delete\");\n    assert((\"x\" in a), false, \"delete\");\n    \n    /* the following are not tested by test262 */\n    assert(delete \"abc\"[100], true);\n\n    err = false;\n    try {\n        delete null.a;\n    } catch(e) {\n        err = (e instanceof TypeError);\n    }\n    assert(err, true, \"delete\");\n\n    err = false;\n    try {\n        a = { f() { delete super.a; } };\n        a.f();\n    } catch(e) {\n        err = (e instanceof ReferenceError);\n    }\n    assert(err, true, \"delete\");\n}\n\nfunction test_prototype()\n{\n    var f = function f() { };\n    assert(f.prototype.constructor, f, \"prototype\");\n\n    var g = function g() { };\n    /* QuickJS bug */\n    Object.defineProperty(g, \"prototype\", { writable: false });\n    assert(g.prototype.constructor, g, \"prototype\");\n}\n\nfunction test_arguments()\n{\n    function f2() {\n        assert(arguments.length, 2, \"arguments\");\n        assert(arguments[0], 1, \"arguments\");\n        assert(arguments[1], 3, \"arguments\");\n    }\n    f2(1, 3);\n}\n\nfunction test_class()\n{\n    var o;\n    class C {\n        constructor() {\n            this.x = 10;\n        }\n        f() {\n            return 1;\n        }\n        static F() {\n            return -1;\n        }\n        get y() {\n            return 12;\n        }\n    };\n    class D extends C {\n        constructor() {\n            super();\n            this.z = 20;\n        }\n        g() {\n            return 2;\n        }\n        static G() {\n            return -2;\n        }\n        h() {\n            return super.f();\n        }\n        static H() {\n            return super[\"F\"]();\n        }\n    }\n\n    assert(C.F() === -1);\n    assert(Object.getOwnPropertyDescriptor(C.prototype, \"y\").get.name === \"get y\");\n\n    o = new C();\n    assert(o.f() === 1);\n    assert(o.x === 10);\n    \n    assert(D.F() === -1);\n    assert(D.G() === -2);\n    assert(D.H() === -1);\n\n    o = new D();\n    assert(o.f() === 1);\n    assert(o.g() === 2);\n    assert(o.x === 10);\n    assert(o.z === 20);\n    assert(o.h() === 1);\n\n    /* test class name scope */\n    var E1 = class E { static F() { return E; } };\n    assert(E1 === E1.F());\n};\n\nfunction test_template()\n{\n    var a, b;\n    b = 123;\n    a = `abc${b}d`;\n    assert(a, \"abc123d\");\n\n    a = String.raw `abc${b}d`;\n    assert(a, \"abc123d\");\n\n    a = \"aaa\";\n    b = \"bbb\";\n    assert(`aaa${a, b}ccc`, \"aaabbbccc\");\n}\n\nfunction test_template_skip()\n{\n    var a = \"Bar\";\n    var { b = `${a + `a${a}` }baz` } = {};\n    assert(b, \"BaraBarbaz\");\n}\n\nfunction test_object_literal()\n{\n    var x = 0, get = 1, set = 2; async = 3;\n    a = { get: 2, set: 3, async: 4 };\n    assert(JSON.stringify(a), '{\"get\":2,\"set\":3,\"async\":4}');\n\n    a = { x, get, set, async };\n    assert(JSON.stringify(a), '{\"x\":0,\"get\":1,\"set\":2,\"async\":3}');\n}\n\nfunction test_regexp_skip()\n{\n    var a, b;\n    [a, b = /abc\\(/] = [1];\n    assert(a === 1);\n    \n    [a, b =/abc\\(/] = [2];\n    assert(a === 2);\n}\n\nfunction test_labels()\n{\n    do x: { break x; } while(0);\n    if (1)\n        x: { break x; }\n    else\n        x: { break x; }\n    with ({}) x: { break x; };\n    while (0) x: { break x; };\n}\n\nfunction test_destructuring()\n{\n    function * g () { return 0; };\n    var [x] = g();\n    assert(x, void 0);\n}\n\nfunction test_spread()\n{\n    var x;\n    x = [1, 2, ...[3, 4]];\n    assert(x.toString(), \"1,2,3,4\");\n\n    x = [ ...[ , ] ];\n    assert(Object.getOwnPropertyNames(x).toString(), \"0,length\");\n}\n\nfunction test_function_length()\n{\n    assert( ((a, b = 1, c) => {}).length, 1);\n    assert( (([a,b]) => {}).length, 1);\n    assert( (({a,b}) => {}).length, 1);\n    assert( ((c, [a,b] = 1, d) => {}).length, 1);\n}\n\nfunction test_argument_scope()\n{\n    var f;\n    var c = \"global\";\n    \n    f = function(a = eval(\"var arguments\")) {};\n    assert_throws(SyntaxError, f);\n\n    f = function(a = eval(\"1\"), b = arguments[0]) { return b; };\n    assert(f(12), 12);\n\n    f = function(a, b = arguments[0]) { return b; };\n    assert(f(12), 12);\n\n    f = function(a, b = () => arguments) { return b; };\n    assert(f(12)()[0], 12);\n\n    f = function(a = eval(\"1\"), b = () => arguments) { return b; };\n    assert(f(12)()[0], 12);\n\n    (function() {\n        \"use strict\";\n        f = function(a = this) { return a; };\n        assert(f.call(123), 123);\n\n        f = function f(a = f) { return a; };\n        assert(f(), f);\n\n        f = function f(a = eval(\"f\")) { return a; };\n        assert(f(), f);\n    })();\n\n    f = (a = eval(\"var c = 1\"), probe = () => c) => {\n        var c = 2;\n        assert(c, 2);\n        assert(probe(), 1);\n    }\n    f();\n\n    f = (a = eval(\"var arguments = 1\"), probe = () => arguments) => {\n        var arguments = 2;\n        assert(arguments, 2);\n        assert(probe(), 1);\n    }\n    f();\n\n    f = function f(a = eval(\"var c = 1\"), b = c, probe = () => c) {\n        assert(b, 1);\n        assert(c, 1);\n        assert(probe(), 1)\n    }\n    f();\n\n    assert(c, \"global\");\n    f = function f(a, b = c, probe = () => c) {\n        eval(\"var c = 1\");\n        assert(c, 1);\n        assert(b, \"global\");\n        assert(probe(), \"global\")\n    }\n    f();\n    assert(c, \"global\");\n\n    f = function f(a = eval(\"var c = 1\"), probe = (d = eval(\"c\")) => d) {\n        assert(probe(), 1)\n    }\n    f();\n}\n\nfunction test_function_expr_name()\n{\n    var f;\n\n    /* non strict mode test : assignment to the function name silently\n       fails */\n    \n    f = function myfunc() {\n        myfunc = 1;\n        return myfunc;\n    };\n    assert(f(), f);\n\n    f = function myfunc() {\n        myfunc = 1;\n        (() => {\n            myfunc = 1;\n        })();\n        return myfunc;\n    };\n    assert(f(), f);\n\n    f = function myfunc() {\n        eval(\"myfunc = 1\");\n        return myfunc;\n    };\n    assert(f(), f);\n    \n    /* strict mode test : assignment to the function name raises a\n       TypeError exception */\n\n    f = function myfunc() {\n        \"use strict\";\n        myfunc = 1;\n    };\n    assert_throws(TypeError, f);\n\n    f = function myfunc() {\n        \"use strict\";\n        (() => {\n            myfunc = 1;\n        })();\n    };\n    assert_throws(TypeError, f);\n\n    f = function myfunc() {\n        \"use strict\";\n        eval(\"myfunc = 1\");\n    };\n    assert_throws(TypeError, f);\n}\n\ntest_op1();\ntest_cvt();\ntest_eq();\ntest_inc_dec();\ntest_op2();\ntest_delete();\ntest_prototype();\ntest_arguments();\ntest_class();\ntest_template();\ntest_template_skip();\ntest_object_literal();\ntest_regexp_skip();\ntest_labels();\ntest_destructuring();\ntest_spread();\ntest_function_length();\ntest_argument_scope();\ntest_function_expr_name();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/tests/test_loop.js",
    "content": "function assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\n// load more elaborate version of assert if available\ntry { __loadScript(\"test_assert.js\"); } catch(e) {}\n\n/*----------------*/\n\nfunction test_while()\n{\n    var i, c;\n    i = 0;\n    c = 0;\n    while (i < 3) {\n        c++;\n        i++;\n    }\n    assert(c === 3);\n}\n\nfunction test_while_break()\n{\n    var i, c;\n    i = 0;\n    c = 0;\n    while (i < 3) {\n        c++;\n        if (i == 1)\n            break;\n        i++;\n    }\n    assert(c === 2 && i === 1);\n}\n\nfunction test_do_while()\n{\n    var i, c;\n    i = 0;\n    c = 0;\n    do {\n        c++;\n        i++;\n    } while (i < 3);\n    assert(c === 3 && i === 3);\n}\n\nfunction test_for()\n{\n    var i, c;\n    c = 0;\n    for(i = 0; i < 3; i++) {\n        c++;\n    }\n    assert(c === 3 && i === 3);\n\n    c = 0;\n    for(var j = 0; j < 3; j++) {\n        c++;\n    }\n    assert(c === 3 && j === 3);\n}\n\nfunction test_for_in()\n{\n    var i, tab, a, b;\n\n    tab = [];\n    for(i in {x:1, y: 2}) {\n        tab.push(i);\n    }\n    assert(tab.toString(), \"x,y\", \"for_in\");\n\n    /* prototype chain test */\n    a = {x:2, y: 2, \"1\": 3};\n    b = {\"4\" : 3 };\n    Object.setPrototypeOf(a, b);\n    tab = [];\n    for(i in a) {\n        tab.push(i);\n    }\n    assert(tab.toString(), \"1,x,y,4\", \"for_in\");\n\n    /* non enumerable properties hide enumerables ones in the\n       prototype chain */\n    a = {y: 2, \"1\": 3};\n    Object.defineProperty(a, \"x\", { value: 1 });\n    b = {\"x\" : 3 };\n    Object.setPrototypeOf(a, b);\n    tab = [];\n    for(i in a) {\n        tab.push(i);\n    }\n    assert(tab.toString(), \"1,y\", \"for_in\");\n\n    /* array optimization */\n    a = [];\n    for(i = 0; i < 10; i++)\n        a.push(i);\n    tab = [];\n    for(i in a) {\n        tab.push(i);\n    }\n    assert(tab.toString(), \"0,1,2,3,4,5,6,7,8,9\", \"for_in\");\n\n    /* iterate with a field */\n    a={x:0};\n    tab = [];\n    for(a.x in {x:1, y: 2}) {\n        tab.push(a.x);\n    }\n    assert(tab.toString(), \"x,y\", \"for_in\");\n\n    /* iterate with a variable field */\n    a=[0];\n    tab = [];\n    for(a[0] in {x:1, y: 2}) {\n        tab.push(a[0]);\n    }\n    assert(tab.toString(), \"x,y\", \"for_in\");\n\n    /* variable definition in the for in */\n    tab = [];\n    for(var j in {x:1, y: 2}) {\n        tab.push(j);\n    }\n    assert(tab.toString(), \"x,y\", \"for_in\");\n\n    /* variable assigment in the for in */\n    tab = [];\n    for(var k = 2 in {x:1, y: 2}) {\n        tab.push(k);\n    }\n    assert(tab.toString(), \"x,y\", \"for_in\");\n}\n\nfunction test_for_in2()\n{\n    var i;\n    tab = [];\n    for(i in {x:1, y: 2, z:3}) {\n        if (i === \"y\")\n            continue;\n        tab.push(i);\n    }\n    assert(tab.toString() == \"x,z\");\n\n    tab = [];\n    for(i in {x:1, y: 2, z:3}) {\n        if (i === \"z\")\n            break;\n        tab.push(i);\n    }\n    assert(tab.toString() == \"x,y\");\n}\n\nfunction test_for_break()\n{\n    var i, c;\n    c = 0;\n    L1: for(i = 0; i < 3; i++) {\n        c++;\n        if (i == 0)\n            continue;\n        while (1) {\n            break L1;\n        }\n    }\n    assert(c === 2 && i === 1);\n}\n\nfunction test_switch1()\n{\n    var i, a, s;\n    s = \"\";\n    for(i = 0; i < 3; i++) {\n        a = \"?\";\n        switch(i) {\n        case 0:\n            a = \"a\";\n            break;\n        case 1:\n            a = \"b\";\n            break;\n        default:\n            a = \"c\";\n            break;\n        }\n        s += a;\n    }\n    assert(s === \"abc\" && i === 3);\n}\n\nfunction test_switch2()\n{\n    var i, a, s;\n    s = \"\";\n    for(i = 0; i < 4; i++) {\n        a = \"?\";\n        switch(i) {\n        case 0:\n            a = \"a\";\n            break;\n        case 1:\n            a = \"b\";\n            break;\n        case 2:\n            continue;\n        default:\n            a = \"\" + i;\n            break;\n        }\n        s += a;\n    }\n    assert(s === \"ab3\" && i === 4);\n}\n\nfunction test_try_catch1()\n{\n    try {\n        throw \"hello\";\n    } catch (e) {\n        assert(e, \"hello\", \"catch\");\n        return;\n    }\n    assert(false, \"catch\");\n}\n\nfunction test_try_catch2()\n{\n    var a;\n    try {\n        a = 1;\n    } catch (e) {\n        a = 2;\n    }\n    assert(a, 1, \"catch\");\n}\n\nfunction test_try_catch3()\n{\n    var s;\n    s = \"\";\n    try {\n        s += \"t\";\n    } catch (e) {\n        s += \"c\";\n    } finally {\n        s += \"f\";\n    }\n    assert(s, \"tf\", \"catch\");\n}\n\nfunction test_try_catch4()\n{\n    var s;\n    s = \"\";\n    try {\n        s += \"t\";\n        throw \"c\";\n    } catch (e) {\n        s += e;\n    } finally {\n        s += \"f\";\n    }\n    assert(s, \"tcf\", \"catch\");\n}\n\nfunction test_try_catch5()\n{\n    var s;\n    s = \"\";\n    for(;;) {\n        try {\n            s += \"t\";\n            break;\n            s += \"b\";\n        } finally {\n            s += \"f\";\n        }\n    }\n    assert(s, \"tf\", \"catch\");\n}\n\nfunction test_try_catch6()\n{\n    function f() {\n        try {\n            s += 't';\n            return 1;\n        } finally {\n            s += \"f\";\n        }\n    }\n    var s = \"\";\n    assert(f() === 1);\n    assert(s, \"tf\", \"catch6\");\n}\n\nfunction test_try_catch7()\n{\n    var s;\n    s = \"\";\n\n    try {\n        try {\n            s += \"t\";\n            throw \"a\";\n        } finally {\n            s += \"f\";\n        }\n    } catch(e) {\n        s += e;\n    } finally {\n        s += \"g\";\n    }\n    assert(s, \"tfag\", \"catch\");\n}\n\nfunction test_try_catch8()\n{\n    var i, s;\n    \n    s = \"\";\n    for(var i in {x:1, y:2}) {\n        try {\n            s += i;\n            throw \"a\";\n        } catch (e) {\n            s += e;\n        } finally {\n            s += \"f\";\n        }\n    }\n    assert(s === \"xafyaf\");\n}\n\ntest_while();\ntest_while_break();\ntest_do_while();\ntest_for();\ntest_for_break();\ntest_switch1();\ntest_switch2();\ntest_for_in();\ntest_for_in2();\n\ntest_try_catch1();\ntest_try_catch2();\ntest_try_catch3();\ntest_try_catch4();\ntest_try_catch5();\ntest_try_catch6();\ntest_try_catch7();\ntest_try_catch8();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/tests/test_op_overloading.js",
    "content": "\"use strict\";\n\nfunction assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\n/* operators overloading with Operators.create() */\nfunction test_operators_create() {\n    class Vec2\n    {\n        constructor(x, y) {\n            this.x = x;\n            this.y = y;\n        }\n        static mul_scalar(p1, a) {\n            var r = new Vec2();\n            r.x = p1.x * a;\n            r.y = p1.y * a;\n            return r;\n        }\n        toString() {\n            return \"Vec2(\" + this.x + \",\" + this.y + \")\";\n        }\n    }\n    \n    Vec2.prototype[Symbol.operatorSet] = Operators.create(\n    {\n        \"+\"(p1, p2) {\n            var r = new Vec2();\n            r.x = p1.x + p2.x;\n            r.y = p1.y + p2.y;\n            return r;\n        },\n        \"-\"(p1, p2) {\n            var r = new Vec2();\n            r.x = p1.x - p2.x;\n            r.y = p1.y - p2.y;\n            return r;\n        },\n        \"==\"(a, b) {\n            return a.x == b.x && a.y == b.y;\n        },\n        \"<\"(a, b) {\n            var r;\n            /* lexicographic order */\n            if (a.x == b.x)\n                r = (a.y < b.y);\n            else\n                r = (a.x < b.x);\n            return r;\n        },\n        \"++\"(a) {\n            var r = new Vec2();\n            r.x = a.x + 1;\n            r.y = a.y + 1;\n            return r;\n        }\n    },\n    {\n        left: Number,\n        \"*\"(a, b) {\n            return Vec2.mul_scalar(b, a);\n        }\n    },\n    {\n        right: Number,\n        \"*\"(a, b) {\n            return Vec2.mul_scalar(a, b);\n        }\n    });\n\n    var a = new Vec2(1, 2);\n    var b = new Vec2(3, 4);\n    var r;\n\n    r = a * 2 + 3 * b;\n    assert(r.x === 11 && r.y === 16);\n    assert(a == a, true);\n    assert(a == b, false);\n    assert(a != a, false);\n    assert(a < b, true);\n    assert(a <= b, true);\n    assert(b < a, false);\n    assert(b <= a, false);\n    assert(a <= a, true);\n    assert(a >= a, true);\n    a++;\n    assert(a.x === 2 && a.y === 3);\n    r = ++a;\n    assert(a.x === 3 && a.y === 4);\n    assert(r === a);\n}\n\n/* operators overloading thru inheritance */\nfunction test_operators()\n{\n    var Vec2;\n\n    function mul_scalar(p1, a) {\n        var r = new Vec2();\n        r.x = p1.x * a;\n        r.y = p1.y * a;\n        return r;\n    }\n\n    var vec2_ops = Operators({\n        \"+\"(p1, p2) {\n            var r = new Vec2();\n            r.x = p1.x + p2.x;\n            r.y = p1.y + p2.y;\n            return r;\n        },\n        \"-\"(p1, p2) {\n            var r = new Vec2();\n            r.x = p1.x - p2.x;\n            r.y = p1.y - p2.y;\n            return r;\n        },\n        \"==\"(a, b) {\n            return a.x == b.x && a.y == b.y;\n        },\n        \"<\"(a, b) {\n            var r;\n            /* lexicographic order */\n            if (a.x == b.x)\n                r = (a.y < b.y);\n            else\n                r = (a.x < b.x);\n            return r;\n        },\n        \"++\"(a) {\n            var r = new Vec2();\n            r.x = a.x + 1;\n            r.y = a.y + 1;\n            return r;\n        }\n    },\n    {\n        left: Number,\n        \"*\"(a, b) {\n            return mul_scalar(b, a);\n        }\n    },\n    {\n        right: Number,\n        \"*\"(a, b) {\n            return mul_scalar(a, b);\n        }\n    });\n\n    Vec2 = class Vec2 extends vec2_ops\n    {\n        constructor(x, y) {\n            super();\n            this.x = x;\n            this.y = y;\n        }\n        toString() {\n            return \"Vec2(\" + this.x + \",\" + this.y + \")\";\n        }\n    }\n    \n    var a = new Vec2(1, 2);\n    var b = new Vec2(3, 4);\n    var r;\n\n    r = a * 2 + 3 * b;\n    assert(r.x === 11 && r.y === 16);\n    assert(a == a, true);\n    assert(a == b, false);\n    assert(a != a, false);\n    assert(a < b, true);\n    assert(a <= b, true);\n    assert(b < a, false);\n    assert(b <= a, false);\n    assert(a <= a, true);\n    assert(a >= a, true);\n    a++;\n    assert(a.x === 2 && a.y === 3);\n    r = ++a;\n    assert(a.x === 3 && a.y === 4);\n    assert(r === a);\n}\n\nfunction test_default_op()\n{\n    assert(Object(1) + 2, 3);\n    assert(Object(1) + true, 2);\n    assert(-Object(1), -1);\n}\n\ntest_operators_create();\ntest_operators();\ntest_default_op();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/tests/test_qjscalc.js",
    "content": "\"use math\";\n\"use strict\";\n\nfunction assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\nfunction assertThrows(err, func)\n{\n    var ex;\n    ex = false;\n    try {\n        func();\n    } catch(e) {\n        ex = true;\n        assert(e instanceof err);\n    }\n    assert(ex, true, \"exception expected\");\n}\n\n// load more elaborate version of assert if available\ntry { __loadScript(\"test_assert.js\"); } catch(e) {}\n\n/*----------------*/\n\nfunction pow(a, n)\n{\n    var r, i;\n    r = 1;\n    for(i = 0; i < n; i++)\n        r *= a;\n    return r;\n}\n\nfunction test_integer()\n{\n    var a, r;\n    a = pow(3, 100);\n    assert((a - 1) != a);\n    assert(a == 515377520732011331036461129765621272702107522001);\n    assert(a == 0x5a4653ca673768565b41f775d6947d55cf3813d1);\n    assert(Integer.isInteger(1) === true);\n    assert(Integer.isInteger(1.0) === false);\n\n    assert(Integer.floorLog2(0) === -1);\n    assert(Integer.floorLog2(7) === 2);\n\n    r = 1 << 31;\n    assert(r, 2147483648, \"1 << 31 === 2147483648\");\n    \n    r = 1 << 32;\n    assert(r, 4294967296, \"1 << 32 === 4294967296\");\n    \n    r = (1 << 31) < 0;\n    assert(r, false, \"(1 << 31) < 0 === false\");\n\n    assert(typeof 1 === \"number\");\n    assert(typeof 9007199254740991 === \"number\");\n    assert(typeof 9007199254740992 === \"bigint\");\n}\n\nfunction test_float()\n{\n    assert(typeof 1.0 === \"bigfloat\");\n    assert(1 == 1.0);\n    assert(1 !== 1.0);\n}\n\n/* jscalc tests */\n\nfunction test_modulo()\n{\n    var i, p, a, b;\n\n    /* Euclidian modulo operator */\n    assert((-3) % 2 == 1);\n    assert(3 % (-2) == 1);\n\n    p = 101;\n    for(i = 1; i < p; i++) {\n        a = Integer.invmod(i, p);\n        assert(a >= 0 && a < p);\n        assert((i * a) % p == 1);\n    }\n\n    assert(Integer.isPrime(2^107-1));\n    assert(!Integer.isPrime((2^107-1) * (2^89-1)));\n    a = Integer.factor((2^89-1)*2^3*11*13^2*1009);\n    assert(a == [ 2,2,2,11,13,13,1009,618970019642690137449562111 ]);\n}\n\nfunction test_fraction()\n{\n    assert((1/3 + 1).toString(), \"4/3\")\n    assert((2/3)^30, 1073741824/205891132094649);\n    assert(1/3 < 2/3);\n    assert(1/3 < 1);\n    assert(1/3 == 1.0/3);\n    assert(1.0/3 < 2/3);\n}\n\nfunction test_mod()\n{\n    var a, b, p;\n    \n    a = Mod(3, 101);\n    b = Mod(-1, 101);\n    assert((a + b) == Mod(2, 101));\n    assert(a ^ 100 == Mod(1, 101));\n\n    p = 2 ^ 607 - 1; /* mersenne prime */\n    a = Mod(3, p) ^ (p - 1);\n    assert(a == Mod(1, p));\n}\n\nfunction test_polynomial()\n{\n    var a, b, q, r, t, i;\n    a = (1 + X) ^ 4;\n    assert(a == X^4+4*X^3+6*X^2+4*X+1);\n    \n    r = (1 + X);\n    q = (1+X+X^2);\n    b = (1 - X^2);\n    a = q * b + r;\n    t = Polynomial.divrem(a, b);\n    assert(t[0] == q);\n    assert(t[1] == r);\n\n    a = 1 + 2*X + 3*X^2;\n    assert(a.apply(0.1) == 1.23);\n\n    a = 1-2*X^2+2*X^3;\n    assert(deriv(a) == (6*X^2-4*X));\n    assert(deriv(integ(a)) == a);\n\n    a = (X-1)*(X-2)*(X-3)*(X-4)*(X-0.1);\n    r = polroots(a);\n    for(i = 0; i < r.length; i++) {\n        b = abs(a.apply(r[i]));\n        assert(b <= 1e-13);\n    }\n}\n\nfunction test_poly_mod()\n{\n    var a, p;\n\n    /* modulo using polynomials */\n    p = X^2 + X + 1;\n    a = PolyMod(3+X, p) ^ 10;\n    assert(a == PolyMod(-3725*X-18357, p));\n\n    a = PolyMod(1/X, 1+X^2);\n    assert(a == PolyMod(-X, X^2+1));\n}\n\nfunction test_rfunc()\n{\n    var a;\n    a = (X+1)/((X+1)*(X-1));\n    assert(a == 1/(X-1));\n    a = (X + 2) / (X - 2);\n    assert(a.apply(1/3) == -7/5);\n\n    assert(deriv((X^2-X+1)/(X-1)) == (X^2-2*X)/(X^2-2*X+1));\n}\n\nfunction test_series()\n{\n    var a, b;\n    a = 1+X+O(X^5);\n    b = a.inverse();\n    assert(b == 1-X+X^2-X^3+X^4+O(X^5));\n    assert(deriv(b) == -1+2*X-3*X^2+4*X^3+O(X^4));\n    assert(deriv(integ(b)) == b);\n\n    a = Series(1/(1-X), 5);\n    assert(a == 1+X+X^2+X^3+X^4+O(X^5));\n    b = a.apply(0.1);\n    assert(b == 1.1111);\n\n    assert(exp(3*X^2+O(X^10)) == 1+3*X^2+9/2*X^4+9/2*X^6+27/8*X^8+O(X^10));\n    assert(sin(X+O(X^6)) == X-1/6*X^3+1/120*X^5+O(X^6));\n    assert(cos(X+O(X^6)) == 1-1/2*X^2+1/24*X^4+O(X^6));\n    assert(tan(X+O(X^8)) == X+1/3*X^3+2/15*X^5+17/315*X^7+O(X^8));\n        assert((1+X+O(X^6))^(2+X) == 1+2*X+2*X^2+3/2*X^3+5/6*X^4+5/12*X^5+O(X^6));\n}\n\nfunction test_matrix()\n{\n    var a, b, r;\n    a = [[1, 2],[3, 4]];\n    b = [3, 4];\n    r = a * b;\n    assert(r == [11, 25]);\n    r = (a^-1) * 2;\n    assert(r == [[-4, 2],[3, -1]]);\n\n    assert(norm2([1,2,3]) == 14);\n\n    assert(diag([1,2,3]) == [ [ 1, 0, 0 ], [ 0, 2, 0 ], [ 0, 0, 3 ] ]);\n    assert(trans(a) == [ [ 1, 3 ], [ 2, 4 ] ]);\n    assert(trans([1,2,3]) == [[1,2,3]]);\n    assert(trace(a) == 5);\n\n    assert(charpoly(Matrix.hilbert(4)) == X^4-176/105*X^3+3341/12600*X^2-41/23625*X+1/6048000);\n    assert(det(Matrix.hilbert(4)) == 1/6048000);\n\n    a = [[1,2,1],[-2,-3,1],[3,5,0]];\n    assert(rank(a) == 2);\n    assert(ker(a) == [ [ 5 ], [ -3 ], [ 1 ] ]);\n\n    assert(dp([1, 2, 3], [3, -4, -7]) === -26);\n    assert(cp([1, 2, 3], [3, -4, -7]) == [ -2, 16, -10 ]);\n}\n\nfunction assert_eq(a, ref)\n{\n    assert(abs(a / ref - 1.0) <= 1e-15);\n}\n\nfunction test_trig()\n{\n    assert_eq(sin(1/2), 0.479425538604203);\n    assert_eq(sin(2+3*I), 9.154499146911428-4.168906959966565*I);\n    assert_eq(cos(2+3*I), -4.189625690968807-9.109227893755337*I);\n    assert_eq((2+0.5*I)^(1.1-0.5*I), 2.494363021357619-0.23076804554558092*I);\n    assert_eq(sqrt(2*I), 1 + I);\n}\n\ntest_integer();\ntest_float();\n\ntest_modulo();\ntest_fraction();\ntest_mod();\ntest_polynomial();\ntest_poly_mod();\ntest_rfunc();\ntest_series();\ntest_matrix();\ntest_trig();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/tests/test_std.js",
    "content": "import * as std from \"std\";\nimport * as os from \"os\";\n\nfunction assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\n// load more elaborate version of assert if available\ntry { std.loadScript(\"test_assert.js\"); } catch(e) {}\n\n/*----------------*/\n\nfunction test_printf()\n{\n    assert(std.sprintf(\"a=%d s=%s\", 123, \"abc\"), \"a=123 s=abc\");\n    assert(std.sprintf(\"%010d\", 123), \"0000000123\");\n    assert(std.sprintf(\"%x\", -2), \"fffffffe\");\n    assert(std.sprintf(\"%lx\", -2), \"fffffffffffffffe\");\n    assert(std.sprintf(\"%10.1f\", 2.1), \"       2.1\");\n    assert(std.sprintf(\"%*.*f\", 10, 2, -2.13), \"     -2.13\");\n    assert(std.sprintf(\"%#lx\", 0x7fffffffffffffffn), \"0x7fffffffffffffff\");\n}\n\nfunction test_file1()\n{\n    var f, len, str, size, buf, ret, i, str1;\n\n    f = std.tmpfile();\n    str = \"hello world\\n\";\n    f.puts(str);\n\n    f.seek(0, std.SEEK_SET);\n    str1 = f.readAsString();\n    assert(str1 === str);\n    \n    f.seek(0, std.SEEK_END);\n    size = f.tell();\n    assert(size === str.length);\n\n    f.seek(0, std.SEEK_SET);\n\n    buf = new Uint8Array(size);\n    ret = f.read(buf.buffer, 0, size);\n    assert(ret === size);\n    for(i = 0; i < size; i++)\n        assert(buf[i] === str.charCodeAt(i));\n\n    f.close();\n}\n\nfunction test_file2()\n{\n    var f, str, i, size;\n    f = std.tmpfile();\n    str = \"hello world\\n\";\n    size = str.length;\n    for(i = 0; i < size; i++)\n        f.putByte(str.charCodeAt(i));\n    f.seek(0, std.SEEK_SET);\n    for(i = 0; i < size; i++) {\n        assert(str.charCodeAt(i) === f.getByte());\n    }\n    assert(f.getByte() === -1);\n    f.close();\n}\n\nfunction test_getline()\n{\n    var f, line, line_count, lines, i;\n    \n    lines = [\"hello world\", \"line 1\", \"line 2\" ];\n    f = std.tmpfile();\n    for(i = 0; i < lines.length; i++) {\n        f.puts(lines[i], \"\\n\");\n    }\n\n    f.seek(0, std.SEEK_SET);\n    assert(!f.eof());\n    line_count = 0;\n    for(;;) {\n        line = f.getline();\n        if (line === null)\n            break;\n        assert(line == lines[line_count]);\n        line_count++;\n    }\n    assert(f.eof());\n    assert(line_count === lines.length);\n\n    f.close();\n}\n \nfunction test_popen()\n{\n    var str, f, fname = \"tmp_file.txt\";\n    var content = \"hello world\";\n\n    f = std.open(fname, \"w\");\n    f.puts(content);\n    f.close();\n\n    /* test loadFile */\n    assert(std.loadFile(fname), content);\n    \n    /* execute the 'cat' shell command */\n    f = std.popen(\"cat \" + fname, \"r\");\n    str = f.readAsString();\n    f.close();\n\n    assert(str, content);\n\n    os.remove(fname);\n}\n\nfunction test_ext_json()\n{\n    var expected, input, obj;\n    expected = '{\"x\":false,\"y\":true,\"z2\":null,\"a\":[1,8,160],\"s\":\"str\"}';\n    input = `{ \"x\":false, /*comments are allowed */\n               \"y\":true,  // also a comment\n               z2:null, // unquoted property names\n               \"a\":[+1,0o10,0xa0,], // plus prefix, octal, hexadecimal\n               \"s\":\"str\",} // trailing comma in objects and arrays\n            `;\n    obj = std.parseExtJSON(input);\n    assert(JSON.stringify(obj), expected);\n}\n\nfunction test_os()\n{\n    var fd, fpath, fname, fdir, buf, buf2, i, files, err, fdate, st, link_path;\n\n    assert(os.isatty(0));\n\n    fdir = \"test_tmp_dir\";\n    fname = \"tmp_file.txt\";\n    fpath = fdir + \"/\" + fname;\n    link_path = fdir + \"/test_link\";\n    \n    os.remove(link_path);\n    os.remove(fpath);\n    os.remove(fdir);\n\n    err = os.mkdir(fdir, 0o755);\n    assert(err === 0);\n    \n    fd = os.open(fpath, os.O_RDWR | os.O_CREAT | os.O_TRUNC);\n    assert(fd >= 0);\n    \n    buf = new Uint8Array(10);\n    for(i = 0; i < buf.length; i++)\n        buf[i] = i;\n    assert(os.write(fd, buf.buffer, 0, buf.length) === buf.length);\n\n    assert(os.seek(fd, 0, std.SEEK_SET) === 0);\n    buf2 = new Uint8Array(buf.length);\n    assert(os.read(fd, buf2.buffer, 0, buf2.length) === buf2.length);\n    \n    for(i = 0; i < buf.length; i++)\n        assert(buf[i] == buf2[i]);\n    \n    if (typeof BigInt !== \"undefined\") {\n        assert(os.seek(fd, BigInt(6), std.SEEK_SET), BigInt(6));\n        assert(os.read(fd, buf2.buffer, 0, 1) === 1);\n        assert(buf[6] == buf2[0]);\n    }\n    \n    assert(os.close(fd) === 0);\n\n    [files, err] = os.readdir(fdir);\n    assert(err, 0);\n    assert(files.indexOf(fname) >= 0);\n\n    fdate = 10000;\n\n    err = os.utimes(fpath, fdate, fdate);\n    assert(err, 0);\n    \n    [st, err] = os.stat(fpath);\n    assert(err, 0);\n    assert(st.mode & os.S_IFMT, os.S_IFREG);\n    assert(st.mtime, fdate);\n\n    err = os.symlink(fname, link_path);\n    assert(err === 0);\n    \n    [st, err] = os.lstat(link_path);\n    assert(err, 0);\n    assert(st.mode & os.S_IFMT, os.S_IFLNK);\n\n    [buf, err] = os.readlink(link_path);\n    assert(err, 0);\n    assert(buf, fname);\n    \n    assert(os.remove(link_path) === 0);\n\n    [buf, err] = os.getcwd();\n    assert(err, 0);\n\n    [buf2, err] = os.realpath(\".\");\n    assert(err, 0);\n\n    assert(buf, buf2);\n    \n    assert(os.remove(fpath) === 0);\n\n    fd = os.open(fpath, os.O_RDONLY);\n    assert(fd < 0);\n\n    assert(os.remove(fdir) === 0);\n}\n\nfunction test_os_exec()\n{\n    var ret, fds, pid, f, status;\n\n    ret = os.exec([\"true\"]);\n    assert(ret, 0);\n\n    ret = os.exec([\"/bin/sh\", \"-c\", \"exit 1\"], { usePath: false });\n    assert(ret, 1);\n    \n    fds = os.pipe();\n    pid = os.exec([\"sh\", \"-c\", \"echo $FOO\"], {\n        stdout: fds[1],\n        block: false,\n        env: { FOO: \"hello\" },\n    } );\n    assert(pid >= 0);\n    os.close(fds[1]); /* close the write end (as it is only in the child)  */\n    f = std.fdopen(fds[0], \"r\");\n    assert(f.getline(), \"hello\");\n    assert(f.getline(), null);\n    f.close();\n    [ret, status] = os.waitpid(pid, 0);\n    assert(ret, pid);\n    assert(status & 0x7f, 0); /* exited */\n    assert(status >> 8, 0); /* exit code */\n\n    pid = os.exec([\"cat\"], { block: false } );\n    assert(pid >= 0);\n    os.kill(pid, os.SIGQUIT);\n    [ret, status] = os.waitpid(pid, 0);\n    assert(ret, pid);\n    assert(status & 0x7f, os.SIGQUIT);\n}\n\nfunction test_timer()\n{\n    var th, i;\n\n    /* just test that a timer can be inserted and removed */\n    th = [];\n    for(i = 0; i < 3; i++)\n        th[i] = os.setTimeout(function () { }, 1000);\n    for(i = 0; i < 3; i++)\n        os.clearTimeout(th[i]);\n}\n\ntest_printf();\ntest_file1();\ntest_file2();\ntest_getline();\ntest_popen();\ntest_os();\ntest_os_exec();\ntest_timer();\ntest_ext_json();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/tests/test_worker.js",
    "content": "/* os.Worker API test */\nimport * as std from \"std\";\nimport * as os from \"os\";\n\nfunction assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\nvar worker;\n\nfunction test_worker()\n{\n    var counter;\n\n    worker = new os.Worker(\"./test_worker_module.js\");\n\n    counter = 0;\n    worker.onmessage = function (e) {\n        var ev = e.data;\n//        print(\"recv\", JSON.stringify(ev));\n        switch(ev.type) {\n        case \"num\":\n            assert(ev.num, counter);\n            counter++;\n            if (counter == 10) {\n                /* test SharedArrayBuffer modification */\n                let sab = new SharedArrayBuffer(10);\n                let buf = new Uint8Array(sab);\n                worker.postMessage({ type: \"sab\", buf: buf });\n            }\n            break;\n        case \"sab_done\":\n            {\n                let buf = ev.buf;\n                /* check that the SharedArrayBuffer was modified */\n                assert(buf[2], 10);\n                worker.postMessage({ type: \"abort\" });\n            }\n            break;\n        case \"done\":\n            /* terminate */\n            worker.onmessage = null;\n            break;\n        }\n    };\n}\n\n\ntest_worker();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/tests/test_worker_module.js",
    "content": "/* Worker code for test_worker.js */\nimport * as std from \"std\";\nimport * as os from \"os\";\n\nvar parent = os.Worker.parent;\n\nfunction handle_msg(e) {\n    var ev = e.data;\n    //          print(\"child_recv\", JSON.stringify(ev));\n    switch(ev.type) {\n    case \"abort\":\n        parent.postMessage({ type: \"done\" });\n        break;\n    case \"sab\":\n        /* modify the SharedArrayBuffer */\n        ev.buf[2] = 10;\n        parent.postMessage({ type: \"sab_done\", buf: ev.buf });\n        break;\n    }\n}\n\nfunction worker_main() {\n    var i;\n    \n    parent.onmessage = handle_msg;\n    for(i = 0; i < 10; i++) {\n        parent.postMessage({ type: \"num\", num: i }); \n    }\n}\n\nworker_main();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/unicode_download.sh",
    "content": "#!/bin/sh\nset -e\n\nurl=\"ftp://ftp.unicode.org/Public/13.0.0/ucd\"\nemoji_url=\"${url}/emoji/emoji-data.txt\"\n\nfiles=\"CaseFolding.txt DerivedNormalizationProps.txt PropList.txt \\\nSpecialCasing.txt CompositionExclusions.txt ScriptExtensions.txt \\\nUnicodeData.txt DerivedCoreProperties.txt NormalizationTest.txt Scripts.txt \\\nPropertyValueAliases.txt\"\n\nmkdir -p unicode\n\n#for f in $files; do\n#    g=\"${url}/${f}\"\n#    wget $g -O unicode/$f\n#done\n    \nwget $emoji_url -O unicode/emoji-data.txt\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/unicode_gen.c",
    "content": "/*\n * Generation of Unicode tables\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n * Copyright (c) 2017-2018 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <inttypes.h>\n#include <string.h>\n#include <assert.h>\n#include <ctype.h>\n#include <time.h>\n\n#include \"cutils.h\"\n\n/* define it to be able to test unicode.c */\n//#define USE_TEST\n/* profile tests */\n//#define PROFILE\n\n//#define DUMP_CASE_CONV_TABLE\n//#define DUMP_TABLE_SIZE\n//#define DUMP_CC_TABLE\n//#define DUMP_DECOMP_TABLE\n\n/* Ideas:\n   - Generalize run length encoding + index for all tables\n   - remove redundant tables for ID_start, ID_continue, Case_Ignorable, Cased\n\n   Case conversion:\n   - use a single entry for consecutive U/LF runs\n   - allow EXT runs of length > 1\n\n   Decomposition:\n   - Greek lower case (+1f10/1f10) ?\n   - allow holes in B runs\n   - suppress more upper / lower case redundancy\n*/\n\n#ifdef USE_TEST\n#include \"libunicode.c\"\n#endif\n\n#define CHARCODE_MAX 0x10ffff\n#define CC_LEN_MAX 3\n\nvoid *mallocz(size_t size)\n{\n    void *ptr;\n    ptr = malloc(size);\n    memset(ptr, 0, size);\n    return ptr;\n}\n\nconst char *get_field(const char *p, int n)\n{\n    int i;\n    for(i = 0; i < n; i++) {\n        while (*p != ';' && *p != '\\0')\n            p++;\n        if (*p == '\\0')\n            return NULL;\n        p++;\n    }\n    return p;\n}\n\nconst char *get_field_buf(char *buf, size_t buf_size, const char *p, int n)\n{\n    char *q;\n    p = get_field(p, n);\n    q = buf;\n    while (*p != ';' && *p != '\\0') {\n        if ((q - buf) < buf_size - 1)\n            *q++ = *p;\n        p++;\n    }\n    *q = '\\0';\n    return buf;\n}\n\nvoid add_char(int **pbuf, int *psize, int *plen, int c)\n{\n    int len, size, *buf;\n    buf = *pbuf;\n    size = *psize;\n    len = *plen;\n    if (len >= size) {\n        size = *psize;\n        size = max_int(len + 1, size * 3 / 2);\n        buf = realloc(buf, sizeof(buf[0]) * size);\n        *pbuf = buf;\n        *psize = size;\n    }\n    buf[len++] = c;\n    *plen = len;\n}\n\nint *get_field_str(int *plen, const char *str, int n)\n{\n    const char *p;\n    int *buf, len, size;\n    p = get_field(str, n);\n    if (!p) {\n        *plen = 0;\n        return NULL;\n    }\n    len = 0;\n    size = 0;\n    buf = NULL;\n    for(;;) {\n        while (isspace(*p))\n            p++;\n        if (!isxdigit(*p))\n            break;\n        add_char(&buf, &size, &len, strtoul(p, (char **)&p, 16));\n    }\n    *plen = len;\n    return buf;\n}\n\nchar *get_line(char *buf, int buf_size, FILE *f)\n{\n    int len;\n    if (!fgets(buf, buf_size, f))\n        return NULL;\n    len = strlen(buf);\n    if (len > 0 && buf[len - 1] == '\\n')\n        buf[len - 1] = '\\0';\n    return buf;\n}\n\n#define UNICODE_GENERAL_CATEGORY\n\ntypedef enum {\n#define DEF(id, str) GCAT_ ## id,\n#include \"unicode_gen_def.h\"\n#undef DEF\n    GCAT_COUNT,\n} UnicodeGCEnum1;\n\nstatic const char *unicode_gc_name[] = {\n#define DEF(id, str) #id,\n#include \"unicode_gen_def.h\"\n#undef DEF\n};\n\nstatic const char *unicode_gc_short_name[] = {\n#define DEF(id, str) str,\n#include \"unicode_gen_def.h\"\n#undef DEF\n};\n\n#undef UNICODE_GENERAL_CATEGORY\n\n#define UNICODE_SCRIPT\n\ntypedef enum {\n#define DEF(id, str) SCRIPT_ ## id,\n#include \"unicode_gen_def.h\"\n#undef DEF\n    SCRIPT_COUNT,\n} UnicodeScriptEnum1;\n\nstatic const char *unicode_script_name[] = {\n#define DEF(id, str) #id,\n#include \"unicode_gen_def.h\"\n#undef DEF\n};\n\nconst char *unicode_script_short_name[] = {\n#define DEF(id, str) str,\n#include \"unicode_gen_def.h\"\n#undef DEF\n};\n\n#undef UNICODE_SCRIPT\n\n#define UNICODE_PROP_LIST\n\ntypedef enum {\n#define DEF(id, str) PROP_ ## id,\n#include \"unicode_gen_def.h\"\n#undef DEF\n    PROP_COUNT,\n} UnicodePropEnum1;\n\nstatic const char *unicode_prop_name[] = {\n#define DEF(id, str) #id,\n#include \"unicode_gen_def.h\"\n#undef DEF\n};\n\nstatic const char *unicode_prop_short_name[] = {\n#define DEF(id, str) str,\n#include \"unicode_gen_def.h\"\n#undef DEF\n};\n\n#undef UNICODE_SPROP_LIST\n\ntypedef struct {\n    /* case conv */\n    uint8_t u_len;\n    uint8_t l_len;\n    int u_data[CC_LEN_MAX];\n    int l_data[CC_LEN_MAX];\n    int f_code;\n\n    uint8_t combining_class;\n    uint8_t is_compat:1;\n    uint8_t is_excluded:1;\n    uint8_t general_category;\n    uint8_t script;\n    uint8_t script_ext_len;\n    uint8_t *script_ext;\n    uint32_t prop_bitmap_tab[3];\n    /* decomposition */\n    int decomp_len;\n    int *decomp_data;\n} CCInfo;\n\nCCInfo *unicode_db;\n\nint find_name(const char **tab, int tab_len, const char *name)\n{\n    int i, len, name_len;\n    const char *p, *r;\n\n    name_len = strlen(name);\n    for(i = 0; i < tab_len; i++) {\n        p = tab[i];\n        for(;;) {\n            r = strchr(p, ',');\n            if (!r)\n                len = strlen(p);\n            else\n                len = r - p;\n            if (len == name_len && memcmp(p, name, len) == 0)\n                return i;\n            if (!r)\n                break;\n            p = r + 1;\n        }\n    }\n    return -1;\n}\n\nstatic int get_prop(uint32_t c, int prop_idx)\n{\n    return (unicode_db[c].prop_bitmap_tab[prop_idx >> 5] >> (prop_idx & 0x1f)) & 1;\n}\n\nstatic void set_prop(uint32_t c, int prop_idx, int val)\n{\n    uint32_t mask;\n    mask = 1U << (prop_idx & 0x1f);\n    if (val)\n        unicode_db[c].prop_bitmap_tab[prop_idx >> 5] |= mask;\n    else\n        unicode_db[c].prop_bitmap_tab[prop_idx >> 5]  &= ~mask;\n}\n\nvoid parse_unicode_data(const char *filename)\n{\n    FILE *f;\n    char line[1024];\n    char buf1[256];\n    const char *p;\n    int code, lc, uc, last_code;\n    CCInfo *ci, *tab = unicode_db;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    last_code = 0;\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#')\n            continue;\n\n        p = get_field(line, 0);\n        if (!p)\n            continue;\n        code = strtoul(p, NULL, 16);\n        lc = 0;\n        uc = 0;\n        \n        p = get_field(line, 12);\n        if (p && *p != ';') {\n            uc = strtoul(p, NULL, 16);\n        }\n\n        p = get_field(line, 13);\n        if (p && *p != ';') {\n            lc = strtoul(p, NULL, 16);\n        }\n        ci = &tab[code];\n        if (uc > 0 || lc > 0) {\n            assert(code <= CHARCODE_MAX);\n            if (uc > 0) {\n                assert(ci->u_len == 0);\n                ci->u_len = 1;\n                ci->u_data[0] = uc;\n            }\n            if (lc > 0) {\n                assert(ci->l_len == 0);\n                ci->l_len = 1;\n                ci->l_data[0] = lc;\n            }\n        }\n\n        {\n            int i;\n            get_field_buf(buf1, sizeof(buf1), line, 2);\n            i = find_name(unicode_gc_name, countof(unicode_gc_name), buf1);\n            if (i < 0) {\n                fprintf(stderr, \"General category '%s' not found\\n\",\n                        buf1);\n                exit(1);\n            }\n            ci->general_category = i;\n        }\n        \n        p = get_field(line, 3);\n        if (p && *p != ';' && *p != '\\0') {\n            int cc;\n            cc = strtoul(p, NULL, 0);\n            if (cc != 0) {\n                assert(code <= CHARCODE_MAX);\n                ci->combining_class = cc;\n                //                printf(\"%05x: %d\\n\", code, ci->combining_class);\n            }\n        }\n\n        p = get_field(line, 5);\n        if (p && *p != ';' && *p != '\\0') {\n            int size;\n            assert(code <= CHARCODE_MAX);\n            ci->is_compat = 0;\n            if (*p == '<') {\n                while (*p != '\\0' && *p != '>')\n                    p++;\n                if (*p == '>')\n                    p++;\n                ci->is_compat = 1;\n            }\n            size = 0;\n            for(;;) {\n                while (isspace(*p))\n                    p++;\n                if (!isxdigit(*p))\n                    break;\n                add_char(&ci->decomp_data, &size, &ci->decomp_len, strtoul(p, (char **)&p, 16));\n            }\n#if 0\n            {\n                int i;\n                static int count, d_count;\n\n                printf(\"%05x: %c\", code, ci->is_compat ? 'C': ' ');\n                for(i = 0; i < ci->decomp_len; i++)\n                    printf(\" %05x\", ci->decomp_data[i]);\n                printf(\"\\n\");\n                count++;\n                d_count += ci->decomp_len;\n                //                printf(\"%d %d\\n\", count, d_count);\n            }\n#endif\n        }\n\n        p = get_field(line, 9);\n        if (p && *p == 'Y') {\n            set_prop(code, PROP_Bidi_Mirrored, 1);\n        }\n        \n        /* handle ranges */\n        get_field_buf(buf1, sizeof(buf1), line, 1);\n        if (strstr(buf1, \" Last>\")) {\n            int i;\n            //            printf(\"range: 0x%x-%0x\\n\", last_code, code);\n            assert(ci->decomp_len == 0);\n            assert(ci->script_ext_len == 0);\n            for(i = last_code + 1; i < code; i++) {\n                unicode_db[i] = *ci;\n            }\n        }\n        last_code = code;\n    }\n        \n    fclose(f);\n}\n\nvoid parse_special_casing(CCInfo *tab, const char *filename)\n{\n    FILE *f;\n    char line[1024];\n    const char *p;\n    int code;\n    CCInfo *ci;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#')\n            continue;\n\n        p = get_field(line, 0);\n        if (!p)\n            continue;\n        code = strtoul(p, NULL, 16);\n        assert(code <= CHARCODE_MAX);\n        ci = &tab[code];\n\n        p = get_field(line, 4);\n        if (p) {\n            /* locale dependent casing */\n            while (isspace(*p))\n                p++;\n            if (*p != '#' && *p != '\\0')\n                continue;\n        }\n            \n        \n        p = get_field(line, 1);\n        if (p && *p != ';') {\n            ci->l_len = 0;\n            for(;;) {\n                while (isspace(*p))\n                    p++;\n                if (*p == ';')\n                    break;\n                assert(ci->l_len < CC_LEN_MAX);\n                ci->l_data[ci->l_len++] = strtoul(p, (char **)&p, 16);\n            }\n\n            if (ci->l_len == 1 && ci->l_data[0] == code)\n                ci->l_len = 0;\n        }\n\n        p = get_field(line, 3);\n        if (p && *p != ';') {\n            ci->u_len = 0;\n            for(;;) {\n                while (isspace(*p))\n                    p++;\n                if (*p == ';')\n                    break;\n                assert(ci->u_len < CC_LEN_MAX);\n                ci->u_data[ci->u_len++] = strtoul(p, (char **)&p, 16);\n            }\n\n            if (ci->u_len == 1 && ci->u_data[0] == code)\n                ci->u_len = 0;\n        }\n    }\n        \n    fclose(f);\n}\n\nvoid parse_case_folding(CCInfo *tab, const char *filename)\n{\n    FILE *f;\n    char line[1024];\n    const char *p;\n    int code;\n    CCInfo *ci;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#')\n            continue;\n\n        p = get_field(line, 0);\n        if (!p)\n            continue;\n        code = strtoul(p, NULL, 16);\n        assert(code <= CHARCODE_MAX);\n        ci = &tab[code];\n\n        p = get_field(line, 1);\n        if (!p)\n            continue;\n        /* locale dependent casing */\n        while (isspace(*p))\n            p++;\n        if (*p != 'C' && *p != 'S')\n            continue;\n        \n        p = get_field(line, 2);\n        assert(p != 0);\n        assert(ci->f_code == 0);\n        ci->f_code = strtoul(p, NULL, 16);\n        assert(ci->f_code != 0 && ci->f_code != code);\n    }\n        \n    fclose(f);\n}\n\nvoid parse_composition_exclusions(const char *filename)\n{\n    FILE *f;\n    char line[4096], *p;\n    uint32_t c0;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#' || *p == '@' || *p == '\\0')\n            continue;\n        c0 = strtoul(p, (char **)&p, 16);\n        assert(c0 > 0 && c0 <= CHARCODE_MAX);\n        unicode_db[c0].is_excluded = TRUE;\n    }\n    fclose(f);\n}\n\nvoid parse_derived_core_properties(const char *filename)\n{\n    FILE *f;\n    char line[4096], *p, buf[256], *q;\n    uint32_t c0, c1, c;\n    int i;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#' || *p == '@' || *p == '\\0')\n            continue;\n        c0 = strtoul(p, (char **)&p, 16);\n        if (*p == '.' && p[1] == '.') {\n            p += 2;\n            c1 = strtoul(p, (char **)&p, 16);\n        } else {\n            c1 = c0;\n        }\n        assert(c1 <= CHARCODE_MAX);\n        p += strspn(p, \" \\t\");\n        if (*p == ';') {\n            p++;\n            p += strspn(p, \" \\t\");\n            q = buf;\n            while (*p != '\\0' && *p != ' ' && *p != '#' && *p != '\\t') {\n                if ((q - buf) < sizeof(buf) - 1)\n                    *q++ = *p;\n                p++;\n            }\n            *q = '\\0';\n            i = find_name(unicode_prop_name,\n                          countof(unicode_prop_name), buf);\n            if (i < 0) {\n                if (!strcmp(buf, \"Grapheme_Link\"))\n                    goto next;\n                fprintf(stderr, \"Property not found: %s\\n\", buf);\n                exit(1);\n            }\n            for(c = c0; c <= c1; c++) {\n                set_prop(c, i, 1);\n            }\nnext: ;\n        }\n    }\n    fclose(f);\n}\n\nvoid parse_derived_norm_properties(const char *filename)\n{\n    FILE *f;\n    char line[4096], *p, buf[256], *q;\n    uint32_t c0, c1, c;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#' || *p == '@' || *p == '\\0')\n            continue;\n        c0 = strtoul(p, (char **)&p, 16);\n        if (*p == '.' && p[1] == '.') {\n            p += 2;\n            c1 = strtoul(p, (char **)&p, 16);\n        } else {\n            c1 = c0;\n        }\n        assert(c1 <= CHARCODE_MAX);\n        p += strspn(p, \" \\t\");\n        if (*p == ';') {\n            p++;\n            p += strspn(p, \" \\t\");\n            q = buf;\n            while (*p != '\\0' && *p != ' ' && *p != '#' && *p != '\\t') {\n                if ((q - buf) < sizeof(buf) - 1)\n                    *q++ = *p;\n                p++;\n            }\n            *q = '\\0';\n            if (!strcmp(buf, \"Changes_When_NFKC_Casefolded\")) {\n                for(c = c0; c <= c1; c++) {\n                    set_prop(c, PROP_Changes_When_NFKC_Casefolded, 1);\n                }\n            }\n        }\n    }\n    fclose(f);\n}\n\nvoid parse_prop_list(const char *filename)\n{\n    FILE *f;\n    char line[4096], *p, buf[256], *q;\n    uint32_t c0, c1, c;\n    int i;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#' || *p == '@' || *p == '\\0')\n            continue;\n        c0 = strtoul(p, (char **)&p, 16);\n        if (*p == '.' && p[1] == '.') {\n            p += 2;\n            c1 = strtoul(p, (char **)&p, 16);\n        } else {\n            c1 = c0;\n        }\n        assert(c1 <= CHARCODE_MAX);\n        p += strspn(p, \" \\t\");\n        if (*p == ';') {\n            p++;\n            p += strspn(p, \" \\t\");\n            q = buf;\n            while (*p != '\\0' && *p != ' ' && *p != '#' && *p != '\\t') {\n                if ((q - buf) < sizeof(buf) - 1)\n                    *q++ = *p;\n                p++;\n            }\n            *q = '\\0';\n            i = find_name(unicode_prop_name,\n                          countof(unicode_prop_name), buf);\n            if (i < 0) {\n                fprintf(stderr, \"Property not found: %s\\n\", buf);\n                exit(1);\n            }\n            for(c = c0; c <= c1; c++) {\n                set_prop(c, i, 1);\n            }\n        }\n    }\n    fclose(f);\n}\n\nvoid parse_scripts(const char *filename)\n{\n    FILE *f;\n    char line[4096], *p, buf[256], *q;\n    uint32_t c0, c1, c;\n    int i;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#' || *p == '@' || *p == '\\0')\n            continue;\n        c0 = strtoul(p, (char **)&p, 16);\n        if (*p == '.' && p[1] == '.') {\n            p += 2;\n            c1 = strtoul(p, (char **)&p, 16);\n        } else {\n            c1 = c0;\n        }\n        assert(c1 <= CHARCODE_MAX);\n        p += strspn(p, \" \\t\");\n        if (*p == ';') {\n            p++;\n            p += strspn(p, \" \\t\");\n            q = buf;\n            while (*p != '\\0' && *p != ' ' && *p != '#' && *p != '\\t') {\n                if ((q - buf) < sizeof(buf) - 1)\n                    *q++ = *p;\n                p++;\n            }\n            *q = '\\0';\n            i = find_name(unicode_script_name,\n                          countof(unicode_script_name), buf);\n            if (i < 0) {\n                fprintf(stderr, \"Unknown script: '%s'\\n\", buf);\n                exit(1);\n            }\n            for(c = c0; c <= c1; c++)\n                unicode_db[c].script = i;\n        }\n    }\n    fclose(f);\n}\n\nvoid parse_script_extensions(const char *filename)\n{\n    FILE *f;\n    char line[4096], *p, buf[256], *q;\n    uint32_t c0, c1, c;\n    int i;\n    uint8_t script_ext[255];\n    int script_ext_len;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#' || *p == '@' || *p == '\\0')\n            continue;\n        c0 = strtoul(p, (char **)&p, 16);\n        if (*p == '.' && p[1] == '.') {\n            p += 2;\n            c1 = strtoul(p, (char **)&p, 16);\n        } else {\n            c1 = c0;\n        }\n        assert(c1 <= CHARCODE_MAX);\n        p += strspn(p, \" \\t\");\n        script_ext_len = 0;\n        if (*p == ';') {\n            p++;\n            for(;;) {\n                p += strspn(p, \" \\t\");\n                q = buf;\n                while (*p != '\\0' && *p != ' ' && *p != '#' && *p != '\\t') {\n                    if ((q - buf) < sizeof(buf) - 1)\n                        *q++ = *p;\n                    p++;\n                }\n                *q = '\\0';\n                if (buf[0] == '\\0')\n                    break;\n                i = find_name(unicode_script_short_name,\n                              countof(unicode_script_short_name), buf);\n                if (i < 0) {\n                    fprintf(stderr, \"Script not found: %s\\n\", buf);\n                    exit(1);\n                }\n                assert(script_ext_len < sizeof(script_ext));\n                script_ext[script_ext_len++] = i;\n            }\n            for(c = c0; c <= c1; c++) {\n                CCInfo *ci = &unicode_db[c];\n                ci->script_ext_len = script_ext_len;\n                ci->script_ext = malloc(sizeof(ci->script_ext[0]) * script_ext_len);\n                for(i = 0; i < script_ext_len; i++)\n                    ci->script_ext[i] = script_ext[i];\n            }\n        }\n    }\n    fclose(f);\n}\n\nvoid dump_cc_info(CCInfo *ci, int i)\n{\n    int j;\n    printf(\"%05x:\", i);\n    if (ci->u_len != 0) {\n        printf(\" U:\");\n        for(j = 0; j < ci->u_len; j++)\n            printf(\" %05x\", ci->u_data[j]);\n    }\n    if (ci->l_len != 0) {\n        printf(\" L:\");\n        for(j = 0; j < ci->l_len; j++)\n            printf(\" %05x\", ci->l_data[j]);\n    }\n    if (ci->f_code != 0) {\n        printf(\" F: %05x\", ci->f_code);\n    }\n    printf(\"\\n\");\n}\n\nvoid dump_data(CCInfo *tab)\n{\n    int i;\n    CCInfo *ci;\n    for(i = 0; i <= CHARCODE_MAX; i++) {\n        ci = &tab[i];\n        if (ci->u_len != 0 || ci->l_len != 0 || ci->f_code != 0) {\n            dump_cc_info(ci, i);\n        }\n    }\n}\n\nBOOL is_complicated_case(const CCInfo *ci)\n{\n    return (ci->u_len > 1 || ci->l_len > 1 ||\n            (ci->u_len > 0 && ci->l_len > 0) ||\n            (ci->f_code != 0) != ci->l_len ||\n            (ci->f_code != 0 && ci->l_data[0] != ci->f_code));\n}\n\n#ifndef USE_TEST\nenum {\n    RUN_TYPE_U,\n    RUN_TYPE_L,\n    RUN_TYPE_UF,\n    RUN_TYPE_LF,\n    RUN_TYPE_UL,\n    RUN_TYPE_LSU,\n    RUN_TYPE_U2L_399_EXT2,\n    RUN_TYPE_UF_D20,\n    RUN_TYPE_UF_D1_EXT,\n    RUN_TYPE_U_EXT,\n    RUN_TYPE_LF_EXT,\n    RUN_TYPE_U_EXT2,\n    RUN_TYPE_L_EXT2,\n    RUN_TYPE_U_EXT3,\n};\n#endif\n\nconst char *run_type_str[] = {\n    \"U\",\n    \"L\",\n    \"UF\",\n    \"LF\",\n    \"UL\",\n    \"LSU\",\n    \"U2L_399_EXT2\",\n    \"UF_D20\",\n    \"UF_D1_EXT\",\n    \"U_EXT\",\n    \"LF_EXT\",\n    \"U_EXT2\",\n    \"L_EXT2\",\n    \"U_EXT3\",\n};\n\ntypedef struct {\n    int code;\n    int len;\n    int type;\n    int data;\n    int ext_len;\n    int ext_data[3];\n    int data_index; /* 'data' coming from the table */\n} TableEntry;\n\n/* code (17), len (7), type (4) */\n\nvoid find_run_type(TableEntry *te, CCInfo *tab, int code)\n{\n    int is_lower, len;\n    CCInfo *ci, *ci1, *ci2;\n\n    ci = &tab[code];\n    ci1 = &tab[code + 1];\n    ci2 = &tab[code + 2];\n    te->code = code;\n    \n    if (ci->l_len == 1 && ci->l_data[0] == code + 2 &&\n        ci->f_code == ci->l_data[0] &&\n        ci->u_len == 0 &&\n\n        ci1->l_len == 1 && ci1->l_data[0] == code + 2 &&\n        ci1->f_code == ci1->l_data[0] &&\n        ci1->u_len == 1 && ci1->u_data[0] == code &&\n\n        ci2->l_len == 0 &&\n        ci2->f_code == 0 &&\n        ci2->u_len == 1 && ci2->u_data[0] == code) {\n        te->len = 3;\n        te->data = 0;\n        te->type = RUN_TYPE_LSU;\n        return;\n    }\n\n    if (is_complicated_case(ci)) {\n        len = 1;\n        while (code + len <= CHARCODE_MAX) {\n            ci1 = &tab[code + len];\n            if (ci1->u_len != 1 ||\n                ci1->u_data[0] != ci->u_data[0] + len ||\n                ci1->l_len != 0 ||\n                ci1->f_code != ci1->u_data[0])\n                break;\n            len++;\n        }\n        if (len > 1) {\n            te->len = len;\n            te->type = RUN_TYPE_UF;\n            te->data = ci->u_data[0];\n            return;\n        }\n\n        if (ci->u_len == 2 && ci->u_data[1] == 0x399 &&\n            ci->f_code == 0 && ci->l_len == 0) {\n            len = 1;\n            while (code + len <= CHARCODE_MAX) {\n                ci1 = &tab[code + len];\n                if (!(ci1->u_len == 2 &&\n                    ci1->u_data[1] == 0x399 &&\n                      ci1->u_data[0] == ci->u_data[0] + len &&\n                      ci1->f_code == 0 &&\n                      ci1->l_len == 0))\n                    break;\n                len++;\n            }\n            te->len = len;\n            te->type = RUN_TYPE_U_EXT2;\n            te->ext_data[0] = ci->u_data[0];\n            te->ext_data[1] = ci->u_data[1];\n            te->ext_len = 2;\n            return;\n        }\n\n        if (ci->u_len == 2 && ci->u_data[1] == 0x399 &&\n            ci->l_len == 1 && ci->f_code == ci->l_data[0]) {\n            len = 1;\n            while (code + len <= CHARCODE_MAX) {\n                ci1 = &tab[code + len];\n                if (!(ci1->u_len == 2 &&\n                      ci1->u_data[1] == 0x399 &&\n                      ci1->u_data[0] == ci->u_data[0] + len &&\n                      ci1->l_len == 1 &&\n                      ci1->l_data[0] == ci->l_data[0] + len &&\n                      ci1->f_code == ci1->l_data[0]))\n                    break;\n                len++;\n            }\n            te->len = len;\n            te->type = RUN_TYPE_U2L_399_EXT2;\n            te->ext_data[0] = ci->u_data[0];\n            te->ext_data[1] = ci->l_data[0];\n            te->ext_len = 2;\n            return;\n        }\n\n        if (ci->l_len == 1 && ci->u_len == 0 && ci->f_code == 0) {\n            len = 1;\n            while (code + len <= CHARCODE_MAX) {\n                ci1 = &tab[code + len];\n                if (!(ci1->l_len == 1 &&\n                      ci1->l_data[0] == ci->l_data[0] + len &&\n                      ci1->u_len == 0 && ci1->f_code == 0))\n                    break;\n                len++;\n            }\n            te->len = len;\n            te->type = RUN_TYPE_L;\n            te->data = ci->l_data[0];\n            return;\n        }\n\n        if (ci->l_len == 0 &&\n            ci->u_len == 1 &&\n            ci->u_data[0] < 0x1000 &&\n            ci->f_code == ci->u_data[0] + 0x20) {\n            te->len = 1;\n            te->type = RUN_TYPE_UF_D20;\n            te->data = ci->u_data[0];\n        } else if (ci->l_len == 0 &&\n            ci->u_len == 1 &&\n            ci->f_code == ci->u_data[0] + 1) {\n            te->len = 1;\n            te->type = RUN_TYPE_UF_D1_EXT;\n            te->ext_data[0] = ci->u_data[0];\n            te->ext_len = 1;\n        } else if (ci->l_len == 2 && ci->u_len == 0 && ci->f_code == 0) {\n            te->len = 1;\n            te->type = RUN_TYPE_L_EXT2;\n            te->ext_data[0] = ci->l_data[0];\n            te->ext_data[1] = ci->l_data[1];\n            te->ext_len = 2;\n        } else if (ci->u_len == 2 && ci->l_len == 0 && ci->f_code == 0) {\n            te->len = 1;\n            te->type = RUN_TYPE_U_EXT2;\n            te->ext_data[0] = ci->u_data[0];\n            te->ext_data[1] = ci->u_data[1];\n            te->ext_len = 2;\n        } else if (ci->u_len == 3 && ci->l_len == 0 && ci->f_code == 0) {\n            te->len = 1;\n            te->type = RUN_TYPE_U_EXT3;\n            te->ext_data[0] = ci->u_data[0];\n            te->ext_data[1] = ci->u_data[1];\n            te->ext_data[2] = ci->u_data[2];\n            te->ext_len = 3;\n        } else {\n            printf(\"unsupported encoding case:\\n\");\n            dump_cc_info(ci, code);\n            abort();\n        }\n    } else {\n        /* look for a run of identical conversions */\n        len = 0;\n        for(;;) {\n            if (code >= CHARCODE_MAX || len >= 126)\n                break;\n            ci = &tab[code + len];\n            ci1 = &tab[code + len + 1];\n            if (is_complicated_case(ci) || is_complicated_case(ci1)) {\n                break;\n            }\n            if (ci->l_len != 1 || ci->l_data[0] != code + len + 1)\n                break;\n            if (ci1->u_len != 1 || ci1->u_data[0] != code + len)\n                break;\n            len += 2;\n        }\n        if (len > 0) {\n            te->len = len;\n            te->type = RUN_TYPE_UL;\n            te->data = 0;\n            return;\n        }\n        \n        ci = &tab[code];\n        is_lower = ci->l_len > 0;\n        len = 1;\n        while (code + len <= CHARCODE_MAX) {\n            ci1 = &tab[code + len];\n            if (is_complicated_case(ci1))\n                break;\n            if (is_lower) {\n                if (ci1->l_len != 1 ||\n                    ci1->l_data[0] != ci->l_data[0] + len)\n                    break;\n            } else {\n                if (ci1->u_len != 1 ||\n                    ci1->u_data[0] != ci->u_data[0] + len)\n                    break;\n            }\n            len++;\n        }\n        te->len = len;\n        if (is_lower) {\n            te->type = RUN_TYPE_LF;\n            te->data = ci->l_data[0];\n        } else {\n            te->type = RUN_TYPE_U;\n            te->data = ci->u_data[0];\n        }\n    }\n}\n\nTableEntry conv_table[1000];\nint conv_table_len;\nint ext_data[1000];\nint ext_data_len;\n\nvoid dump_case_conv_table1(void)\n{\n    int i, j;\n    const TableEntry *te;\n\n    for(i = 0; i < conv_table_len; i++) {\n        te = &conv_table[i];\n        printf(\"%05x %02x %-10s %05x\",\n               te->code, te->len, run_type_str[te->type], te->data);\n        for(j = 0; j < te->ext_len; j++) {\n            printf(\" %05x\", te->ext_data[j]);\n        }\n        printf(\"\\n\");\n    }\n    printf(\"table_len=%d ext_len=%d\\n\", conv_table_len, ext_data_len);\n}\n\nint find_data_index(const TableEntry *conv_table, int len, int data)\n{\n    int i;\n    const TableEntry *te;\n    for(i = 0; i < len; i++) {\n        te = &conv_table[i];\n        if (te->code == data)\n            return i;\n    }\n    return -1;\n}\n\nint find_ext_data_index(int data)\n{\n    int i;\n    for(i = 0; i < ext_data_len; i++) {\n        if (ext_data[i] == data)\n            return i;\n    }\n    assert(ext_data_len < countof(ext_data));\n    ext_data[ext_data_len++] = data;\n    return ext_data_len - 1;\n}\n\nvoid build_conv_table(CCInfo *tab)\n{\n    int code, i, j;\n    CCInfo *ci;\n    TableEntry *te;\n                          \n    te = conv_table;\n    for(code = 0; code <= CHARCODE_MAX; code++) {\n        ci = &tab[code];\n        if (ci->u_len == 0 && ci->l_len == 0 && ci->f_code == 0)\n            continue;\n        assert(te - conv_table < countof(conv_table));\n        find_run_type(te, tab, code);\n#if 0\n        if (te->type == RUN_TYPE_TODO) {\n            printf(\"TODO: \");\n            dump_cc_info(ci, code);\n        }\n#endif\n        assert(te->len <= 127);\n        code += te->len - 1;\n        te++;\n    }\n    conv_table_len = te - conv_table;\n\n    /* find the data index */\n    for(i = 0; i < conv_table_len; i++) {\n        int data_index;\n        te = &conv_table[i];\n        \n        switch(te->type) {\n        case RUN_TYPE_U:\n        case RUN_TYPE_L:\n        case RUN_TYPE_UF:\n        case RUN_TYPE_LF:\n            data_index = find_data_index(conv_table, conv_table_len, te->data);\n            if (data_index < 0) {\n                switch(te->type) {\n                case RUN_TYPE_U:\n                    te->type = RUN_TYPE_U_EXT;\n                    te->ext_len = 1;\n                    te->ext_data[0] = te->data;\n                    break;\n                case RUN_TYPE_LF:\n                    te->type = RUN_TYPE_LF_EXT;\n                    te->ext_len = 1;\n                    te->ext_data[0] = te->data;\n                    break;\n                default:\n                    printf(\"%05x: index not found\\n\", te->code);\n                    exit(1);\n                }\n            } else {\n                te->data_index = data_index;\n            }\n            break;\n        case RUN_TYPE_UF_D20:\n            te->data_index = te->data;\n            break;\n        }\n    }\n\n    /* find the data index for ext_data */\n    for(i = 0; i < conv_table_len; i++) {\n        te = &conv_table[i];\n        if (te->type == RUN_TYPE_U_EXT3) {\n            int p, v;\n            v = 0;\n            for(j = 0; j < 3; j++) {\n                p = find_ext_data_index(te->ext_data[j]);\n                assert(p < 16);\n                v = (v << 4) | p;\n            }\n            te->data_index = v;\n        }\n    }\n\n    for(i = 0; i < conv_table_len; i++) {\n        te = &conv_table[i];\n        if (te->type == RUN_TYPE_L_EXT2 ||\n            te->type == RUN_TYPE_U_EXT2 ||\n            te->type == RUN_TYPE_U2L_399_EXT2) {\n            int p, v;\n            v = 0;\n            for(j = 0; j < 2; j++) {\n                p = find_ext_data_index(te->ext_data[j]);\n                assert(p < 64);\n                v = (v << 6) | p;\n            }\n            te->data_index = v;\n        }\n    }\n\n    for(i = 0; i < conv_table_len; i++) {\n        te = &conv_table[i];\n        if (te->type == RUN_TYPE_UF_D1_EXT ||\n            te->type == RUN_TYPE_U_EXT ||\n            te->type == RUN_TYPE_LF_EXT) {\n            te->data_index = find_ext_data_index(te->ext_data[0]);\n        }\n    }\n#ifdef DUMP_CASE_CONV_TABLE\n    dump_case_conv_table1();\n#endif\n}\n\nvoid dump_case_conv_table(FILE *f)\n{\n    int i;\n    uint32_t v;\n    const TableEntry *te;\n\n    fprintf(f, \"static const uint32_t case_conv_table1[%u] = {\", conv_table_len);\n    for(i = 0; i < conv_table_len; i++) {\n        if (i % 4 == 0)\n            fprintf(f, \"\\n   \");\n        te = &conv_table[i];\n        v = te->code << (32 - 17);\n        v |= te->len << (32 - 17 - 7);\n        v |= te->type << (32 - 17 - 7 - 4);\n        v |= te->data_index >> 8;\n        fprintf(f, \" 0x%08x,\", v);\n    }\n    fprintf(f, \"\\n};\\n\\n\");\n\n    fprintf(f, \"static const uint8_t case_conv_table2[%u] = {\", conv_table_len);\n    for(i = 0; i < conv_table_len; i++) {\n        if (i % 8 == 0)\n            fprintf(f, \"\\n   \");\n        te = &conv_table[i];\n        fprintf(f, \" 0x%02x,\", te->data_index & 0xff);\n    }\n    fprintf(f, \"\\n};\\n\\n\");\n\n    fprintf(f, \"static const uint16_t case_conv_ext[%u] = {\", ext_data_len);\n    for(i = 0; i < ext_data_len; i++) {\n        if (i % 8 == 0)\n            fprintf(f, \"\\n   \");\n        fprintf(f, \" 0x%04x,\", ext_data[i]);\n    }\n    fprintf(f, \"\\n};\\n\\n\");\n}\n\nint tabcmp(const int *tab1, const int *tab2, int n)\n{\n    int i;\n    for(i = 0; i < n; i++) {\n        if (tab1[i] != tab2[i])\n            return -1;\n    }\n    return 0;\n}\n\nvoid dump_str(const char *str, const int *buf, int len)\n{\n    int i;\n    printf(\"%s=\", str);\n    for(i = 0; i < len; i++)\n        printf(\" %05x\", buf[i]);\n    printf(\"\\n\");\n}\n\nvoid compute_internal_props(void)\n{\n    int i;\n    BOOL has_ul;\n\n    for(i = 0; i <= CHARCODE_MAX; i++) {\n        CCInfo *ci = &unicode_db[i];\n        has_ul = (ci->u_len != 0 || ci->l_len != 0 || ci->f_code != 0);\n        if (has_ul) {\n            assert(get_prop(i, PROP_Cased));\n        } else {\n            set_prop(i, PROP_Cased1, get_prop(i, PROP_Cased));\n        }\n        set_prop(i, PROP_ID_Continue1,\n                 get_prop(i, PROP_ID_Continue) & (get_prop(i, PROP_ID_Start) ^ 1));\n        set_prop(i, PROP_XID_Start1,\n                 get_prop(i, PROP_ID_Start) ^ get_prop(i, PROP_XID_Start));\n        set_prop(i, PROP_XID_Continue1,\n                 get_prop(i, PROP_ID_Continue) ^ get_prop(i, PROP_XID_Continue));\n        set_prop(i, PROP_Changes_When_Titlecased1,\n                 get_prop(i, PROP_Changes_When_Titlecased) ^ (ci->u_len != 0));\n        set_prop(i, PROP_Changes_When_Casefolded1,\n                 get_prop(i, PROP_Changes_When_Casefolded) ^ (ci->f_code != 0));\n        /* XXX: reduce table size (438 bytes) */\n        set_prop(i, PROP_Changes_When_NFKC_Casefolded1,\n                 get_prop(i, PROP_Changes_When_NFKC_Casefolded) ^ (ci->f_code != 0));\n#if 0\n        /* TEST */\n#define M(x) (1U << GCAT_ ## x)\n        {\n            int b;\n            b = ((M(Mn) | M(Cf) | M(Lm) | M(Sk)) >>\n                 unicode_db[i].general_category) & 1;\n            set_prop(i, PROP_Cased1,\n                     get_prop(i, PROP_Case_Ignorable) ^ b);\n        }\n#undef M\n#endif\n    }\n}\n\nvoid dump_byte_table(FILE *f, const char *cname, const uint8_t *tab, int len)\n{\n    int i;\n    fprintf(f, \"static const uint8_t %s[%d] = {\", cname, len);\n    for(i = 0; i < len; i++) {\n        if (i % 8 == 0)\n            fprintf(f, \"\\n   \");\n        fprintf(f, \" 0x%02x,\", tab[i]);\n    }\n    fprintf(f, \"\\n};\\n\\n\");\n}\n\n#define PROP_BLOCK_LEN 32\n\nvoid build_prop_table(FILE *f, int prop_index, BOOL add_index)\n{\n    int i, j, n, v, offset, code;\n    DynBuf dbuf_s, *dbuf = &dbuf_s;\n    DynBuf dbuf1_s, *dbuf1 = &dbuf1_s;\n    DynBuf dbuf2_s, *dbuf2 = &dbuf2_s;\n    const uint32_t *buf;\n    int buf_len, block_end_pos, bit;\n    char cname[128];\n    \n    dbuf_init(dbuf1);\n\n    for(i = 0; i <= CHARCODE_MAX;) {\n        v = get_prop(i, prop_index);\n        j = i + 1;\n        while (j <= CHARCODE_MAX && get_prop(j, prop_index) == v) {\n            j++;\n        }\n        n = j - i;\n        if (j == (CHARCODE_MAX + 1) && v == 0)\n            break; /* no need to encode last zero run */\n        //printf(\"%05x: %d %d\\n\", i, n, v);\n        dbuf_put_u32(dbuf1, n - 1);\n        i += n;\n    }\n    \n    dbuf_init(dbuf);\n    dbuf_init(dbuf2);\n    buf = (uint32_t *)dbuf1->buf;\n    buf_len = dbuf1->size / sizeof(buf[0]);\n    \n    /* the first value is assumed to be 0 */\n    assert(get_prop(0, prop_index) == 0);\n    \n    block_end_pos = PROP_BLOCK_LEN;\n    i = 0;\n    code = 0;\n    bit = 0;\n    while (i < buf_len) {\n        if (add_index && dbuf->size >= block_end_pos && bit == 0) {\n            offset = (dbuf->size - block_end_pos);\n            /* XXX: offset could be larger in case of runs of small\n               lengths. Could add code to change the encoding to\n               prevent it at the expense of one byte loss */\n            assert(offset <= 7);\n            v = code | (offset << 21);\n            dbuf_putc(dbuf2, v);\n            dbuf_putc(dbuf2, v >> 8);\n            dbuf_putc(dbuf2, v >> 16);\n            block_end_pos += PROP_BLOCK_LEN;\n        }\n\n        v = buf[i];\n        code += v + 1;\n        bit ^= 1;\n        if (v < 8 && (i + 1) < buf_len && buf[i + 1] < 8) {\n            code += buf[i + 1] + 1;\n            bit ^= 1;\n            dbuf_putc(dbuf, (v << 3) | buf[i + 1]);\n            i += 2;\n        } else if (v < 128) {\n            dbuf_putc(dbuf, 0x80 + v);\n            i++;\n        } else if (v < (1 << 13)) {\n            dbuf_putc(dbuf, 0x40 + (v >> 8));\n            dbuf_putc(dbuf, v);\n            i++;\n        } else {\n            assert(v < (1 << 21));\n            dbuf_putc(dbuf, 0x60 + (v >> 16));\n            dbuf_putc(dbuf, v >> 8);\n            dbuf_putc(dbuf, v);\n            i++;\n        }\n    }\n\n    if (add_index) {\n        /* last index entry */\n        v = code;\n        dbuf_putc(dbuf2, v);\n        dbuf_putc(dbuf2, v >> 8);\n        dbuf_putc(dbuf2, v >> 16);\n    }\n\n#ifdef DUMP_TABLE_SIZE\n    printf(\"prop %s: length=%d bytes\\n\", unicode_prop_name[prop_index],\n           (int)(dbuf->size + dbuf2->size));\n#endif\n    snprintf(cname, sizeof(cname), \"unicode_prop_%s_table\", unicode_prop_name[prop_index]);\n    dump_byte_table(f, cname, dbuf->buf, dbuf->size);\n    if (add_index) {\n        snprintf(cname, sizeof(cname), \"unicode_prop_%s_index\", unicode_prop_name[prop_index]);\n        dump_byte_table(f, cname, dbuf2->buf, dbuf2->size);\n    }\n    \n    dbuf_free(dbuf);\n    dbuf_free(dbuf1);\n    dbuf_free(dbuf2);\n}\n\nvoid build_flags_tables(FILE *f)\n{\n    build_prop_table(f, PROP_Cased1, TRUE);\n    build_prop_table(f, PROP_Case_Ignorable, TRUE);\n    build_prop_table(f, PROP_ID_Start, TRUE);\n    build_prop_table(f, PROP_ID_Continue1, TRUE);\n}\n\nvoid dump_name_table(FILE *f, const char *cname, const char **tab_name, int len,\n                     const char **tab_short_name)\n{\n    int i, w, maxw;\n\n    maxw = 0;\n    for(i = 0; i < len; i++) {\n        w = strlen(tab_name[i]);\n        if (tab_short_name[i][0] != '\\0') {\n            w += 1 + strlen(tab_short_name[i]);\n        }\n        if (maxw < w)\n            maxw = w;\n    }\n\n    /* generate a sequence of strings terminated by an empty string */\n    fprintf(f, \"static const char %s[] =\\n\", cname);\n    for(i = 0; i < len; i++) {\n        fprintf(f, \"    \\\"\");\n        w = fprintf(f, \"%s\", tab_name[i]);\n        if (tab_short_name[i][0] != '\\0') {\n            w += fprintf(f, \",%s\", tab_short_name[i]);\n        }\n        fprintf(f, \"\\\"%*s\\\"\\\\0\\\"\\n\", 1 + maxw - w, \"\");\n    }\n    fprintf(f, \";\\n\\n\");\n}\n\nvoid build_general_category_table(FILE *f)\n{\n    int i, v, j, n, n1;\n    DynBuf dbuf_s, *dbuf = &dbuf_s;\n    int cw_count, cw_len_count[4], cw_start;\n\n    fprintf(f, \"typedef enum {\\n\");\n    for(i = 0; i < GCAT_COUNT; i++)\n        fprintf(f, \"    UNICODE_GC_%s,\\n\", unicode_gc_name[i]);\n    fprintf(f, \"    UNICODE_GC_COUNT,\\n\");\n    fprintf(f, \"} UnicodeGCEnum;\\n\\n\");\n\n    dump_name_table(f, \"unicode_gc_name_table\",\n                    unicode_gc_name, GCAT_COUNT,\n                    unicode_gc_short_name);\n\n\n    dbuf_init(dbuf);\n    cw_count = 0;\n    for(i = 0; i < 4; i++)\n        cw_len_count[i] = 0;\n    for(i = 0; i <= CHARCODE_MAX;) {\n        v = unicode_db[i].general_category;\n        j = i + 1;\n        while (j <= CHARCODE_MAX && unicode_db[j].general_category == v)\n            j++;\n        n = j - i;\n        /* compress Lu/Ll runs */\n        if (v == GCAT_Lu) {\n            n1 = 1;\n            while ((i + n1) <= CHARCODE_MAX && unicode_db[i + n1].general_category == (v + (n1 & 1))) {\n                n1++;\n            }\n            if (n1 > n) {\n                v = 31;\n                n = n1;\n            }\n        }\n        //        printf(\"%05x %05x %d\\n\", i, n, v);\n        cw_count++;\n        n--;\n        cw_start = dbuf->size;\n        if (n < 7) {\n            dbuf_putc(dbuf, (n << 5) | v);\n        } else if (n < 7 + 128) {\n            n1 = n - 7;\n            assert(n1 < 128);\n            dbuf_putc(dbuf, (0xf << 5) | v);\n            dbuf_putc(dbuf, n1);\n        } else if (n < 7 + 128 + (1 << 14)) {\n            n1 = n - (7 + 128);\n            assert(n1 < (1 << 14));\n            dbuf_putc(dbuf, (0xf << 5) | v);\n            dbuf_putc(dbuf, (n1 >> 8) + 128);\n            dbuf_putc(dbuf, n1);\n        } else {\n            n1 = n - (7 + 128 + (1 << 14));\n            assert(n1 < (1 << 22));\n            dbuf_putc(dbuf, (0xf << 5) | v);\n            dbuf_putc(dbuf, (n1 >> 16) + 128 + 64);\n            dbuf_putc(dbuf, n1 >> 8);\n            dbuf_putc(dbuf, n1);\n        }\n        cw_len_count[dbuf->size - cw_start - 1]++;\n        i += n + 1;\n    }\n#ifdef DUMP_TABLE_SIZE\n    printf(\"general category: %d entries [\",\n           cw_count);\n    for(i = 0; i < 4; i++)\n        printf(\" %d\", cw_len_count[i]);\n    printf(\" ], length=%d bytes\\n\", (int)dbuf->size);\n#endif\n    \n    dump_byte_table(f, \"unicode_gc_table\", dbuf->buf, dbuf->size);\n\n    dbuf_free(dbuf);\n}\n\nvoid build_script_table(FILE *f)\n{\n    int i, v, j, n, n1, type;\n    DynBuf dbuf_s, *dbuf = &dbuf_s;\n    int cw_count, cw_len_count[4], cw_start;\n\n    fprintf(f, \"typedef enum {\\n\");\n    for(i = 0; i < SCRIPT_COUNT; i++)\n        fprintf(f, \"    UNICODE_SCRIPT_%s,\\n\", unicode_script_name[i]);\n    fprintf(f, \"    UNICODE_SCRIPT_COUNT,\\n\");\n    fprintf(f, \"} UnicodeScriptEnum;\\n\\n\");\n\n    i = 1;\n    dump_name_table(f, \"unicode_script_name_table\",\n                    unicode_script_name + i, SCRIPT_COUNT - i,\n                    unicode_script_short_name + i);\n\n    dbuf_init(dbuf);\n    cw_count = 0;\n    for(i = 0; i < 4; i++)\n        cw_len_count[i] = 0;\n    for(i = 0; i <= CHARCODE_MAX;) {\n        v = unicode_db[i].script;\n        j = i + 1;\n        while (j <= CHARCODE_MAX && unicode_db[j].script == v)\n            j++;\n        n = j - i;\n        if (v == 0 && j == (CHARCODE_MAX + 1))\n            break;\n        //        printf(\"%05x %05x %d\\n\", i, n, v);\n        cw_count++;\n        n--;\n        cw_start = dbuf->size;\n        if (v == 0)\n            type = 0;\n        else\n            type = 1;\n        if (n < 96) {\n            dbuf_putc(dbuf, n | (type << 7));\n        } else if (n < 96 + (1 << 12)) {\n            n1 = n - 96;\n            assert(n1 < (1 << 12));\n            dbuf_putc(dbuf, ((n1 >> 8) + 96) | (type << 7));\n            dbuf_putc(dbuf, n1);\n        } else {\n            n1 = n - (96 + (1 << 12));\n            assert(n1 < (1 << 20));\n            dbuf_putc(dbuf, ((n1 >> 16) + 112) | (type << 7));\n            dbuf_putc(dbuf, n1 >> 8);\n            dbuf_putc(dbuf, n1);\n        }\n        if (type != 0)\n            dbuf_putc(dbuf, v);\n\n        cw_len_count[dbuf->size - cw_start - 1]++;\n        i += n + 1;\n    }\n#if defined(DUMP_TABLE_SIZE)\n    printf(\"script: %d entries [\",\n           cw_count);\n    for(i = 0; i < 4; i++)\n        printf(\" %d\", cw_len_count[i]);\n    printf(\" ], length=%d bytes\\n\", (int)dbuf->size);\n#endif\n    \n    dump_byte_table(f, \"unicode_script_table\", dbuf->buf, dbuf->size);\n\n    dbuf_free(dbuf);\n}\n\nvoid build_script_ext_table(FILE *f)\n{\n    int i, j, n, n1, script_ext_len;\n    DynBuf dbuf_s, *dbuf = &dbuf_s;\n    int cw_count;\n\n    dbuf_init(dbuf);\n    cw_count = 0;\n    for(i = 0; i <= CHARCODE_MAX;) {\n        script_ext_len = unicode_db[i].script_ext_len;\n        j = i + 1;\n        while (j <= CHARCODE_MAX &&\n               unicode_db[j].script_ext_len == script_ext_len &&\n               !memcmp(unicode_db[j].script_ext, unicode_db[i].script_ext,\n                       script_ext_len)) {\n            j++;\n        }\n        n = j - i;\n        cw_count++;\n        n--;\n        if (n < 128) {\n            dbuf_putc(dbuf, n);\n        } else if (n < 128 + (1 << 14)) {\n            n1 = n - 128;\n            assert(n1 < (1 << 14));\n            dbuf_putc(dbuf, (n1 >> 8) + 128);\n            dbuf_putc(dbuf, n1);\n        } else {\n            n1 = n - (128 + (1 << 14));\n            assert(n1 < (1 << 22));\n            dbuf_putc(dbuf, (n1 >> 16) + 128 + 64);\n            dbuf_putc(dbuf, n1 >> 8);\n            dbuf_putc(dbuf, n1);\n        }\n        dbuf_putc(dbuf, script_ext_len);\n        for(j = 0; j < script_ext_len; j++)\n            dbuf_putc(dbuf, unicode_db[i].script_ext[j]);\n        i += n + 1;\n    }\n#ifdef DUMP_TABLE_SIZE\n    printf(\"script_ext: %d entries\",\n           cw_count);\n    printf(\", length=%d bytes\\n\", (int)dbuf->size);\n#endif\n    \n    dump_byte_table(f, \"unicode_script_ext_table\", dbuf->buf, dbuf->size);\n\n    dbuf_free(dbuf);\n}\n\n/* the following properties are synthetized so no table is necessary */\n#define PROP_TABLE_COUNT PROP_ASCII\n\nvoid build_prop_list_table(FILE *f)\n{\n    int i;\n    \n    for(i = 0; i < PROP_TABLE_COUNT; i++) {\n        if (i == PROP_ID_Start ||\n            i == PROP_Case_Ignorable ||\n            i == PROP_ID_Continue1) {\n            /* already generated */\n        } else {\n            build_prop_table(f, i, FALSE);\n        }\n    }\n    \n    fprintf(f, \"typedef enum {\\n\");\n    for(i = 0; i < PROP_COUNT; i++)\n        fprintf(f, \"    UNICODE_PROP_%s,\\n\", unicode_prop_name[i]);\n    fprintf(f, \"    UNICODE_PROP_COUNT,\\n\");\n    fprintf(f, \"} UnicodePropertyEnum;\\n\\n\");\n\n    i = PROP_ASCII_Hex_Digit;\n    dump_name_table(f, \"unicode_prop_name_table\",\n                    unicode_prop_name + i, PROP_XID_Start - i + 1,\n                    unicode_prop_short_name + i);\n\n    fprintf(f, \"static const uint8_t * const unicode_prop_table[] = {\\n\");\n    for(i = 0; i < PROP_TABLE_COUNT; i++) {\n        fprintf(f, \"    unicode_prop_%s_table,\\n\", unicode_prop_name[i]);\n    }\n    fprintf(f, \"};\\n\\n\");\n\n    fprintf(f, \"static const uint16_t unicode_prop_len_table[] = {\\n\");\n    for(i = 0; i < PROP_TABLE_COUNT; i++) {\n        fprintf(f, \"    countof(unicode_prop_%s_table),\\n\", unicode_prop_name[i]);\n    }\n    fprintf(f, \"};\\n\\n\");\n}\n\n#ifdef USE_TEST\nint check_conv(uint32_t *res, uint32_t c, int conv_type)\n{\n    return lre_case_conv(res, c, conv_type);\n}\n\nvoid check_case_conv(void)\n{\n    CCInfo *tab = unicode_db;\n    uint32_t res[3];\n    int l, error;\n    CCInfo ci_s, *ci1, *ci = &ci_s;\n    int code;\n    \n    for(code = 0; code <= CHARCODE_MAX; code++) {\n        ci1 = &tab[code];\n        *ci = *ci1;\n        if (ci->l_len == 0) {\n            ci->l_len = 1;\n            ci->l_data[0] = code;\n        }\n        if (ci->u_len == 0) {\n            ci->u_len = 1;\n            ci->u_data[0] = code;\n        }\n        if (ci->f_code == 0)\n            ci->f_code = code;\n\n        error = 0;\n        l = check_conv(res, code, 0);\n        if (l != ci->u_len || tabcmp((int *)res, ci->u_data, l)) {\n            printf(\"ERROR: L\\n\");\n            error++;\n        }\n        l = check_conv(res, code, 1);\n        if (l != ci->l_len || tabcmp((int *)res, ci->l_data, l)) {\n            printf(\"ERROR: U\\n\");\n            error++;\n        }\n        l = check_conv(res, code, 2);\n        if (l != 1 || res[0] != ci->f_code) {\n            printf(\"ERROR: F\\n\");\n            error++;\n        }\n        if (error) {\n            dump_cc_info(ci, code);\n            exit(1);\n        }\n    }\n}\n\n#ifdef PROFILE\nstatic int64_t get_time_ns(void)\n{\n    struct timespec ts;\n    clock_gettime(CLOCK_MONOTONIC, &ts);\n    return (int64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;\n}\n#endif\n\n\nvoid check_flags(void)\n{\n    int c;\n    BOOL flag_ref, flag;\n    for(c = 0; c <= CHARCODE_MAX; c++) {\n        flag_ref = get_prop(c, PROP_Cased);\n        flag = lre_is_cased(c);\n        if (flag != flag_ref) {\n            printf(\"ERROR: c=%05x cased=%d ref=%d\\n\",\n                   c, flag, flag_ref);\n            exit(1);\n        }\n\n        flag_ref = get_prop(c, PROP_Case_Ignorable);\n        flag = lre_is_case_ignorable(c);\n        if (flag != flag_ref) {\n            printf(\"ERROR: c=%05x case_ignorable=%d ref=%d\\n\",\n                   c, flag, flag_ref);\n            exit(1);\n        }\n\n        flag_ref = get_prop(c, PROP_ID_Start);\n        flag = lre_is_id_start(c);\n        if (flag != flag_ref) {\n            printf(\"ERROR: c=%05x id_start=%d ref=%d\\n\",\n                   c, flag, flag_ref);\n            exit(1);\n        }\n\n        flag_ref = get_prop(c, PROP_ID_Continue);\n        flag = lre_is_id_continue(c);\n        if (flag != flag_ref) {\n            printf(\"ERROR: c=%05x id_cont=%d ref=%d\\n\",\n                   c, flag, flag_ref);\n            exit(1);\n        }\n    }\n#ifdef PROFILE\n    {\n        int64_t ti, count;\n        ti = get_time_ns();\n        count = 0;\n        for(c = 0x20; c <= 0xffff; c++) {\n            flag_ref = get_prop(c, PROP_ID_Start);\n            flag = lre_is_id_start(c);\n            assert(flag == flag_ref);\n            count++;\n        }\n        ti = get_time_ns() - ti;\n        printf(\"flags time=%0.1f ns/char\\n\",\n               (double)ti / count);\n    }\n#endif\n}\n\n#endif\n\n#define CC_BLOCK_LEN 32\n\nvoid build_cc_table(FILE *f)\n{\n    int i, cc, n, cc_table_len, type, n1;\n    DynBuf dbuf_s, *dbuf = &dbuf_s;\n    DynBuf dbuf1_s, *dbuf1 = &dbuf1_s;\n    int cw_len_tab[3], cw_start, block_end_pos;\n    uint32_t v;\n    \n    dbuf_init(dbuf);\n    dbuf_init(dbuf1);\n    cc_table_len = 0;\n    for(i = 0; i < countof(cw_len_tab); i++)\n        cw_len_tab[i] = 0;\n    block_end_pos = CC_BLOCK_LEN;\n    for(i = 0; i <= CHARCODE_MAX;) {\n        cc = unicode_db[i].combining_class;\n        assert(cc <= 255);\n        /* check increasing values */\n        n = 1;\n        while ((i + n) <= CHARCODE_MAX &&\n               unicode_db[i + n].combining_class == (cc + n))\n            n++;\n        if (n >= 2) {\n            type = 1;\n        } else {\n            type = 0;\n            n = 1;\n            while ((i + n) <= CHARCODE_MAX &&\n                   unicode_db[i + n].combining_class == cc)\n                n++;\n        }\n        /* no need to encode the last run */\n        if (cc == 0 && (i + n - 1) == CHARCODE_MAX)\n            break;\n#ifdef DUMP_CC_TABLE\n        printf(\"%05x %6d %d %d\\n\", i, n, type, cc);\n#endif\n        if (type == 0) {\n            if (cc == 0)\n                type = 2;\n            else if (cc == 230)\n                type = 3;\n        }\n        n1 = n - 1;\n\n        /* add an entry to the index if necessary */\n        if (dbuf->size >= block_end_pos) {\n            v = i | ((dbuf->size - block_end_pos) << 21);\n            dbuf_putc(dbuf1, v);\n            dbuf_putc(dbuf1, v >> 8);\n            dbuf_putc(dbuf1, v >> 16);\n            block_end_pos += CC_BLOCK_LEN;\n        }\n        cw_start = dbuf->size;\n        if (n1 < 48) {\n            dbuf_putc(dbuf, n1 | (type << 6));\n        } else if (n1 < 48 + (1 << 11)) {\n            n1 -= 48;\n            dbuf_putc(dbuf, ((n1 >> 8) + 48) | (type << 6));\n            dbuf_putc(dbuf, n1);\n        } else {\n            n1 -= 48 + (1 << 11);\n            assert(n1 < (1 << 20));\n            dbuf_putc(dbuf, ((n1 >> 16) + 56) | (type << 6));\n            dbuf_putc(dbuf, n1 >> 8);\n            dbuf_putc(dbuf, n1);\n        }\n        cw_len_tab[dbuf->size - cw_start - 1]++;\n        if (type == 0 || type == 1)\n            dbuf_putc(dbuf, cc);\n        cc_table_len++;\n        i += n;\n    }\n\n    /* last index entry */\n    v = i;\n    dbuf_putc(dbuf1, v);\n    dbuf_putc(dbuf1, v >> 8);\n    dbuf_putc(dbuf1, v >> 16);\n    \n    dump_byte_table(f, \"unicode_cc_table\", dbuf->buf, dbuf->size);\n    dump_byte_table(f, \"unicode_cc_index\", dbuf1->buf, dbuf1->size);\n\n#if defined(DUMP_CC_TABLE) || defined(DUMP_TABLE_SIZE)\n    printf(\"CC table: size=%d (%d entries) [\",\n           (int)(dbuf->size + dbuf1->size),\n           cc_table_len);\n    for(i = 0; i < countof(cw_len_tab); i++)\n        printf(\" %d\", cw_len_tab[i]);\n    printf(\" ]\\n\");\n#endif\n    dbuf_free(dbuf);\n    dbuf_free(dbuf1);\n}\n\n/* maximum length of decomposition: 18 chars (1), then 8 */\n#ifndef USE_TEST\ntypedef enum {\n    DECOMP_TYPE_C1, /* 16 bit char */\n    DECOMP_TYPE_L1, /* 16 bit char table */\n    DECOMP_TYPE_L2,\n    DECOMP_TYPE_L3,\n    DECOMP_TYPE_L4,\n    DECOMP_TYPE_L5, /* XXX: not used */\n    DECOMP_TYPE_L6, /* XXX: could remove */\n    DECOMP_TYPE_L7, /* XXX: could remove */\n    DECOMP_TYPE_LL1, /* 18 bit char table */\n    DECOMP_TYPE_LL2,\n    DECOMP_TYPE_S1, /* 8 bit char table */\n    DECOMP_TYPE_S2,\n    DECOMP_TYPE_S3,\n    DECOMP_TYPE_S4,\n    DECOMP_TYPE_S5,\n    DECOMP_TYPE_I1, /* increment 16 bit char value */\n    DECOMP_TYPE_I2_0,\n    DECOMP_TYPE_I2_1,\n    DECOMP_TYPE_I3_1,\n    DECOMP_TYPE_I3_2,\n    DECOMP_TYPE_I4_1,\n    DECOMP_TYPE_I4_2,\n    DECOMP_TYPE_B1, /* 16 bit base + 8 bit offset */\n    DECOMP_TYPE_B2,\n    DECOMP_TYPE_B3,\n    DECOMP_TYPE_B4,\n    DECOMP_TYPE_B5,\n    DECOMP_TYPE_B6,\n    DECOMP_TYPE_B7,\n    DECOMP_TYPE_B8,\n    DECOMP_TYPE_B18,\n    DECOMP_TYPE_LS2,\n    DECOMP_TYPE_PAT3,\n    DECOMP_TYPE_S2_UL,\n    DECOMP_TYPE_LS2_UL,\n} DecompTypeEnum;\n#endif\n\nconst char *decomp_type_str[] = {\n    \"C1\",\n    \"L1\",\n    \"L2\",\n    \"L3\",\n    \"L4\",\n    \"L5\",\n    \"L6\",\n    \"L7\",\n    \"LL1\",\n    \"LL2\",\n    \"S1\",\n    \"S2\",\n    \"S3\",\n    \"S4\",\n    \"S5\",\n    \"I1\",\n    \"I2_0\",\n    \"I2_1\",\n    \"I3_1\",\n    \"I3_2\",\n    \"I4_1\",\n    \"I4_2\",\n    \"B1\",\n    \"B2\",\n    \"B3\",\n    \"B4\",\n    \"B5\",\n    \"B6\",\n    \"B7\",\n    \"B8\",\n    \"B18\",\n    \"LS2\",\n    \"PAT3\",\n    \"S2_UL\",\n    \"LS2_UL\",\n};\n\nconst int decomp_incr_tab[4][4] = {\n    { DECOMP_TYPE_I1, 0, -1 },\n    { DECOMP_TYPE_I2_0, 0, 1, -1 },\n    { DECOMP_TYPE_I3_1, 1, 2, -1 },\n    { DECOMP_TYPE_I4_1, 1, 2, -1 },\n};\n\n/*\n  entry size:\n  type   bits\n  code   18 \n  len    7\n  compat 1\n  type   5\n  index  16\n  total  47\n*/\n\ntypedef struct {\n    int code;\n    uint8_t len;\n    uint8_t type;\n    uint8_t c_len;\n    uint16_t c_min;\n    uint16_t data_index;\n    int cost; /* size in bytes from this entry to the end */\n} DecompEntry;\n\nint get_decomp_run_size(const DecompEntry *de)\n{\n    int s;\n    s = 6;\n    if (de->type <= DECOMP_TYPE_C1) {\n        /* nothing more */\n    } else if (de->type <= DECOMP_TYPE_L7) {\n        s += de->len * de->c_len * 2;\n    } else if (de->type <= DECOMP_TYPE_LL2) {\n        /* 18 bits per char */\n        s += (de->len * de->c_len * 18 + 7) / 8;\n    } else if (de->type <= DECOMP_TYPE_S5) {\n        s += de->len * de->c_len;\n    } else if (de->type <= DECOMP_TYPE_I4_2) {\n        s += de->c_len * 2;\n    } else if (de->type <= DECOMP_TYPE_B18) {\n        s += 2 + de->len * de->c_len;\n    } else if (de->type <= DECOMP_TYPE_LS2) {\n        s += de->len * 3;\n    } else if (de->type <= DECOMP_TYPE_PAT3) {\n        s += 4 + de->len * 2;\n    } else if (de->type <= DECOMP_TYPE_S2_UL) {\n        s += de->len;\n    } else if (de->type <= DECOMP_TYPE_LS2_UL) {\n        s += (de->len / 2) * 3;\n    } else {\n        abort();\n    }\n    return s;\n}\n\nstatic const uint16_t unicode_short_table[2] = { 0x2044, 0x2215 };\n\n/* return -1 if not found */\nint get_short_code(int c)\n{\n    int i;\n    if (c < 0x80) {\n        return c;\n    } else if (c >= 0x300 && c < 0x350) {\n        return c - 0x300 + 0x80;\n    } else {\n        for(i = 0; i < countof(unicode_short_table); i++) {\n            if (c == unicode_short_table[i])\n                return i + 0x80 + 0x50;\n        }\n        return -1;\n    }\n}\n\nstatic BOOL is_short(int code)\n{\n    return get_short_code(code) >= 0;\n}\n\nstatic BOOL is_short_tab(const int *tab, int len)\n{\n    int i;\n    for(i = 0; i < len; i++) {\n        if (!is_short(tab[i]))\n            return FALSE;\n    }\n    return TRUE;\n}\n\nstatic BOOL is_16bit(const int *tab, int len)\n{\n    int i;\n    for(i = 0; i < len; i++) {\n        if (tab[i] > 0xffff)\n            return FALSE;\n    }\n    return TRUE;\n}\n\nstatic uint32_t to_lower_simple(uint32_t c)\n{\n    /* Latin1 and Cyrillic */\n    if (c < 0x100 || (c >= 0x410 && c <= 0x42f))\n        c += 0x20;\n    else\n        c++;\n    return c;\n}\n\n/* select best encoding with dynamic programming */\nvoid find_decomp_run(DecompEntry *tab_de, int i)\n{\n    DecompEntry de_s, *de = &de_s;\n    CCInfo *ci, *ci1, *ci2;\n    int l, j, n, len_max;\n    \n    ci = &unicode_db[i];\n    l = ci->decomp_len;\n    if (l == 0) {\n        tab_de[i].cost = tab_de[i + 1].cost;\n        return;\n    }\n\n    /* the offset for the compose table has only 6 bits, so we must\n       limit if it can be used by the compose table */\n    if (!ci->is_compat && !ci->is_excluded && l == 2)\n        len_max = 64; \n    else\n        len_max = 127;\n    \n    tab_de[i].cost = 0x7fffffff;\n    \n    if (!is_16bit(ci->decomp_data, l)) {\n        assert(l <= 2);\n\n        n = 1;\n        for(;;) {\n            de->code = i;\n            de->len = n;\n            de->type = DECOMP_TYPE_LL1 + l - 1;\n            de->c_len = l;\n            de->cost = get_decomp_run_size(de) + tab_de[i + n].cost;\n            if (de->cost < tab_de[i].cost) {\n                tab_de[i] = *de;\n            }\n            if (!((i + n) <= CHARCODE_MAX && n < len_max))\n                break;\n            ci1 = &unicode_db[i + n];\n            /* Note: we accept a hole */\n            if (!(ci1->decomp_len == 0 ||\n                  (ci1->decomp_len == l &&\n                   ci1->is_compat == ci->is_compat)))\n                break;\n            n++;\n        }\n        return;\n    }\n\n    if (l <= 7) {\n        n = 1;\n        for(;;) {\n            de->code = i;\n            de->len = n;\n            if (l == 1 && n == 1) {\n                de->type = DECOMP_TYPE_C1;\n            } else {\n                assert(l <= 8);\n                de->type = DECOMP_TYPE_L1 + l - 1;\n            }\n            de->c_len = l;\n            de->cost = get_decomp_run_size(de) + tab_de[i + n].cost;\n            if (de->cost < tab_de[i].cost) {\n                tab_de[i] = *de;\n            }\n            \n            if (!((i + n) <= CHARCODE_MAX && n < len_max))\n                break;\n            ci1 = &unicode_db[i + n];\n            /* Note: we accept a hole */\n            if (!(ci1->decomp_len == 0 ||\n                  (ci1->decomp_len == l &&\n                   ci1->is_compat == ci->is_compat &&\n                   is_16bit(ci1->decomp_data, l))))\n                break;\n            n++;\n        }\n    }\n    \n    if (l <= 8 || l == 18) {\n        int c_min, c_max, c;\n        c_min = c_max = -1;\n        n = 1;\n        for(;;) {\n            ci1 = &unicode_db[i + n - 1];\n            for(j = 0; j < l; j++) {\n                c = ci1->decomp_data[j];\n                if (c == 0x20) {\n                    /* we accept space for Arabic */\n                } else if (c_min == -1) {\n                    c_min = c_max = c;\n                } else {\n                    c_min = min_int(c_min, c);\n                    c_max = max_int(c_max, c);\n                }\n            }\n            if ((c_max - c_min) > 254)\n                break;\n            de->code = i;\n            de->len = n;\n            if (l == 18)\n                de->type = DECOMP_TYPE_B18;\n            else\n                de->type = DECOMP_TYPE_B1 + l - 1;\n            de->c_len = l;\n            de->c_min = c_min;\n            de->cost = get_decomp_run_size(de) + tab_de[i + n].cost;\n            if (de->cost < tab_de[i].cost) {\n                tab_de[i] = *de;\n            }\n            if (!((i + n) <= CHARCODE_MAX && n < len_max))\n                break;\n            ci1 = &unicode_db[i + n];\n            if (!(ci1->decomp_len == l &&\n                  ci1->is_compat == ci->is_compat))\n                break;\n            n++;\n        }\n    }\n\n    /* find an ascii run */\n    if (l <= 5 && is_short_tab(ci->decomp_data, l)) {\n        n = 1;\n        for(;;) {\n            de->code = i;\n            de->len = n;\n            de->type = DECOMP_TYPE_S1 + l - 1;\n            de->c_len = l;\n            de->cost = get_decomp_run_size(de) + tab_de[i + n].cost;\n            if (de->cost < tab_de[i].cost) {\n                tab_de[i] = *de;\n            }\n\n            if (!((i + n) <= CHARCODE_MAX && n < len_max))\n                break;\n            ci1 = &unicode_db[i + n];\n            /* Note: we accept a hole */\n            if (!(ci1->decomp_len == 0 ||\n                  (ci1->decomp_len == l &&\n                   ci1->is_compat == ci->is_compat &&\n                   is_short_tab(ci1->decomp_data, l))))\n                break;\n            n++;\n        }\n    }\n\n    /* check if a single char is increasing */\n    if (l <= 4) {\n        int idx1, idx;\n        \n        for(idx1 = 1; (idx = decomp_incr_tab[l - 1][idx1]) >= 0; idx1++) {\n            n = 1;\n            for(;;) {\n                de->code = i;\n                de->len = n;\n                de->type = decomp_incr_tab[l - 1][0] + idx1 - 1;\n                de->c_len = l;\n                de->cost = get_decomp_run_size(de) + tab_de[i + n].cost;\n                if (de->cost < tab_de[i].cost) {\n                    tab_de[i] = *de;\n                }\n\n                if (!((i + n) <= CHARCODE_MAX && n < len_max))\n                    break;\n                ci1 = &unicode_db[i + n];\n                if (!(ci1->decomp_len == l &&\n                      ci1->is_compat == ci->is_compat))\n                    goto next1;\n                for(j = 0; j < l; j++) {\n                    if (j == idx) {\n                        if (ci1->decomp_data[j] != ci->decomp_data[j] + n)\n                            goto next1;\n                    } else {\n                        if (ci1->decomp_data[j] != ci->decomp_data[j])\n                            goto next1;\n                    }\n                }\n                n++;\n            }\n        next1: ;\n        }\n    }\n\n    if (l == 3) {\n        n = 1;\n        for(;;) {\n            de->code = i;\n            de->len = n;\n            de->type = DECOMP_TYPE_PAT3;\n            de->c_len = l;\n            de->cost = get_decomp_run_size(de) + tab_de[i + n].cost;\n            if (de->cost < tab_de[i].cost) {\n                tab_de[i] = *de;\n            }\n            if (!((i + n) <= CHARCODE_MAX && n < len_max))\n                break;\n            ci1 = &unicode_db[i + n];\n            if (!(ci1->decomp_len == l &&\n                  ci1->is_compat == ci->is_compat &&\n                  ci1->decomp_data[1] <= 0xffff &&\n                  ci1->decomp_data[0] == ci->decomp_data[0] &&\n                  ci1->decomp_data[l - 1] == ci->decomp_data[l - 1]))\n                break;\n            n++;\n        }\n    }\n\n    if (l == 2 && is_short(ci->decomp_data[1])) {\n        n = 1;\n        for(;;) {\n            de->code = i;\n            de->len = n;\n            de->type = DECOMP_TYPE_LS2;\n            de->c_len = l;\n            de->cost = get_decomp_run_size(de) + tab_de[i + n].cost;\n            if (de->cost < tab_de[i].cost) {\n                tab_de[i] = *de;\n            }\n            if (!((i + n) <= CHARCODE_MAX && n < len_max))\n                break;\n            ci1 = &unicode_db[i + n];\n            if (!(ci1->decomp_len == 0 ||\n                  (ci1->decomp_len == l &&\n                   ci1->is_compat == ci->is_compat &&\n                   ci1->decomp_data[0] <= 0xffff &&\n                   is_short(ci1->decomp_data[1]))))\n                break;\n            n++;\n        }\n    }\n\n    if (l == 2) {\n        BOOL is_16bit;\n        \n        n = 0;\n        is_16bit = FALSE;\n        for(;;) {\n            if (!((i + n + 1) <= CHARCODE_MAX && n + 2 <= len_max))\n                break;\n            ci1 = &unicode_db[i + n];\n            if (!(ci1->decomp_len == l &&\n                  ci1->is_compat == ci->is_compat &&\n                  is_short(ci1->decomp_data[1])))\n                break;\n            if (!is_16bit && !is_short(ci1->decomp_data[0]))\n                is_16bit = TRUE;\n            ci2 = &unicode_db[i + n + 1];\n            if (!(ci2->decomp_len == l &&\n                  ci2->is_compat == ci->is_compat &&\n                  ci2->decomp_data[0] == to_lower_simple(ci1->decomp_data[0])  &&\n                  ci2->decomp_data[1] == ci1->decomp_data[1]))\n                break;\n            n += 2;\n            de->code = i;\n            de->len = n;\n            de->type = DECOMP_TYPE_S2_UL + is_16bit;\n            de->c_len = l;\n            de->cost = get_decomp_run_size(de) + tab_de[i + n].cost;\n            if (de->cost < tab_de[i].cost) {\n                tab_de[i] = *de;\n            }\n        }\n    }\n}\n\nvoid put16(uint8_t *data_buf, int *pidx, uint16_t c)\n{\n    int idx;\n    idx = *pidx;\n    data_buf[idx++] = c;\n    data_buf[idx++] = c >> 8;\n    *pidx = idx;\n}\n\nvoid add_decomp_data(uint8_t *data_buf, int *pidx, DecompEntry *de)\n{\n    int i, j, idx, c;\n    CCInfo *ci;\n    \n    idx = *pidx;\n    de->data_index = idx;\n    if (de->type <= DECOMP_TYPE_C1) {\n        ci = &unicode_db[de->code];\n        assert(ci->decomp_len == 1);\n        de->data_index = ci->decomp_data[0];\n    } else if (de->type <= DECOMP_TYPE_L7) {\n        for(i = 0; i < de->len; i++) {\n            ci = &unicode_db[de->code + i];\n            for(j = 0; j < de->c_len; j++) {\n                if (ci->decomp_len == 0)\n                    c = 0;\n                else\n                    c = ci->decomp_data[j];\n                put16(data_buf, &idx,  c);\n            }\n        }\n    } else if (de->type <= DECOMP_TYPE_LL2) {\n        int n, p, k;\n        n = (de->len * de->c_len * 18 + 7) / 8;\n        p = de->len * de->c_len * 2;\n        memset(data_buf + idx, 0, n);\n        k = 0;\n        for(i = 0; i < de->len; i++) {\n            ci = &unicode_db[de->code + i];\n            for(j = 0; j < de->c_len; j++) {\n                if (ci->decomp_len == 0)\n                    c = 0;\n                else\n                    c = ci->decomp_data[j];\n                data_buf[idx + k * 2] = c;\n                data_buf[idx + k * 2 + 1] = c >> 8;\n                data_buf[idx + p + (k / 4)] |= (c >> 16) << ((k % 4) * 2);\n                k++;\n            }\n        }\n        idx += n;\n    } else if (de->type <= DECOMP_TYPE_S5) {\n        for(i = 0; i < de->len; i++) {\n            ci = &unicode_db[de->code + i];\n            for(j = 0; j < de->c_len; j++) {\n                if (ci->decomp_len == 0)\n                    c = 0;\n                else\n                    c = ci->decomp_data[j];\n                c = get_short_code(c);\n                assert(c >= 0);\n                data_buf[idx++] = c;\n            }\n        }\n    } else if (de->type <= DECOMP_TYPE_I4_2) {\n        ci = &unicode_db[de->code];\n        assert(ci->decomp_len == de->c_len);\n        for(j = 0; j < de->c_len; j++)\n            put16(data_buf, &idx, ci->decomp_data[j]);\n    } else if (de->type <= DECOMP_TYPE_B18) {\n        c = de->c_min;\n        data_buf[idx++] = c;\n        data_buf[idx++] = c >> 8;\n        for(i = 0; i < de->len; i++) {\n            ci = &unicode_db[de->code + i];\n            for(j = 0; j < de->c_len; j++) {\n                assert(ci->decomp_len == de->c_len);\n                c = ci->decomp_data[j];\n                if (c == 0x20) {\n                    c = 0xff;\n                } else {\n                    c -= de->c_min;\n                    assert((uint32_t)c <= 254);\n                }\n                data_buf[idx++] = c;\n            }\n        }\n    } else if (de->type <= DECOMP_TYPE_LS2) {\n        assert(de->c_len == 2);\n        for(i = 0; i < de->len; i++) {\n            ci = &unicode_db[de->code + i];\n            if (ci->decomp_len == 0)\n                c = 0;\n            else\n                c = ci->decomp_data[0];\n            put16(data_buf, &idx,  c);\n\n            if (ci->decomp_len == 0)\n                c = 0;\n            else\n                c = ci->decomp_data[1];\n            c = get_short_code(c);\n            assert(c >= 0);\n            data_buf[idx++] = c;\n        }\n    } else if (de->type <= DECOMP_TYPE_PAT3) {\n        ci = &unicode_db[de->code];\n        assert(ci->decomp_len == 3);\n        put16(data_buf, &idx,  ci->decomp_data[0]);\n        put16(data_buf, &idx,  ci->decomp_data[2]);\n        for(i = 0; i < de->len; i++) {\n            ci = &unicode_db[de->code + i];\n            assert(ci->decomp_len == 3);\n            put16(data_buf, &idx,  ci->decomp_data[1]);\n        }\n    } else if (de->type <= DECOMP_TYPE_S2_UL) {\n        for(i = 0; i < de->len; i += 2) {\n            ci = &unicode_db[de->code + i];\n            c = ci->decomp_data[0];\n            c = get_short_code(c);\n            assert(c >= 0);\n            data_buf[idx++] = c;\n            c = ci->decomp_data[1];\n            c = get_short_code(c);\n            assert(c >= 0);\n            data_buf[idx++] = c;\n        }\n    } else if (de->type <= DECOMP_TYPE_LS2_UL) {\n        for(i = 0; i < de->len; i += 2) {\n            ci = &unicode_db[de->code + i];\n            c = ci->decomp_data[0];\n            put16(data_buf, &idx,  c);\n            c = ci->decomp_data[1];\n            c = get_short_code(c);\n            assert(c >= 0);\n            data_buf[idx++] = c;\n        }\n    } else {\n        abort();\n    }\n    *pidx = idx;\n}\n\n#if 0\nvoid dump_large_char(void)\n{\n    int i, j;\n    for(i = 0; i <= CHARCODE_MAX; i++) {\n        CCInfo *ci = &unicode_db[i];\n        for(j = 0; j < ci->decomp_len; j++) {\n            if (ci->decomp_data[j] > 0xffff)\n                printf(\"%05x\\n\", ci->decomp_data[j]);\n        }\n    }\n}\n#endif\n\nvoid build_compose_table(FILE *f, const DecompEntry *tab_de);\n\nvoid build_decompose_table(FILE *f)\n{\n    int i, array_len, code_max, data_len, count;\n    DecompEntry *tab_de, de_s, *de = &de_s;\n    uint8_t *data_buf;\n    \n    code_max = CHARCODE_MAX;\n    \n    tab_de = mallocz((code_max + 2) * sizeof(*tab_de));\n\n    for(i = code_max; i >= 0; i--) {\n        find_decomp_run(tab_de, i);\n    }\n\n    /* build the data buffer */\n    data_buf = malloc(100000);\n    data_len = 0;\n    array_len = 0;\n    for(i = 0; i <= code_max; i++) {\n        de = &tab_de[i];\n        if (de->len != 0) {\n            add_decomp_data(data_buf, &data_len, de);\n            i += de->len - 1;\n            array_len++;\n        }\n    }\n\n#ifdef DUMP_DECOMP_TABLE\n    /* dump */\n    {\n        int size, size1;\n        \n        printf(\"START LEN   TYPE  L C SIZE\\n\");\n        size = 0;\n        for(i = 0; i <= code_max; i++) {\n            de = &tab_de[i];\n            if (de->len != 0) {\n                size1 = get_decomp_run_size(de);\n                printf(\"%05x %3d %6s %2d %1d %4d\\n\", i, de->len,\n                       decomp_type_str[de->type], de->c_len,\n                       unicode_db[i].is_compat, size1);\n                i += de->len - 1;\n                size += size1;\n            }\n        }\n        \n        printf(\"array_len=%d estimated size=%d bytes actual=%d bytes\\n\",\n               array_len, size, array_len * 6 + data_len);\n    }\n#endif\n\n    fprintf(f, \"static const uint32_t unicode_decomp_table1[%u] = {\",\n            array_len);\n    count = 0;\n    for(i = 0; i <= code_max; i++) {\n        de = &tab_de[i];\n        if (de->len != 0) {\n            uint32_t v;\n            if (count++ % 4 == 0)\n                fprintf(f, \"\\n   \");\n            v = (de->code << (32 - 18)) |\n                (de->len << (32 - 18 - 7)) |\n                (de->type << (32 - 18 - 7 - 6)) |\n                unicode_db[de->code].is_compat;\n            fprintf(f, \" 0x%08x,\", v);\n            i += de->len - 1;\n        }\n    }\n    fprintf(f, \"\\n};\\n\\n\");\n\n    fprintf(f, \"static const uint16_t unicode_decomp_table2[%u] = {\",\n            array_len);\n    count = 0;\n    for(i = 0; i <= code_max; i++) {\n        de = &tab_de[i];\n        if (de->len != 0) {\n            if (count++ % 8 == 0)\n                fprintf(f, \"\\n   \");\n            fprintf(f, \" 0x%04x,\", de->data_index);\n            i += de->len - 1;\n        }\n    }\n    fprintf(f, \"\\n};\\n\\n\");\n    \n    fprintf(f, \"static const uint8_t unicode_decomp_data[%u] = {\",\n            data_len);\n    for(i = 0; i < data_len; i++) {\n        if (i % 8 == 0)\n            fprintf(f, \"\\n   \");\n        fprintf(f, \" 0x%02x,\", data_buf[i]);\n    }\n    fprintf(f, \"\\n};\\n\\n\");\n\n    build_compose_table(f, tab_de);\n\n    free(data_buf);\n    \n    free(tab_de);\n}\n\ntypedef struct {\n    uint32_t c[2];\n    uint32_t p;\n} ComposeEntry;\n\n#define COMPOSE_LEN_MAX 10000\n\nstatic int ce_cmp(const void *p1, const void *p2)\n{\n    const ComposeEntry *ce1 = p1;\n    const ComposeEntry *ce2 = p2;\n    int i;\n\n    for(i = 0; i < 2; i++) {\n        if (ce1->c[i] < ce2->c[i])\n            return -1;\n        else if (ce1->c[i] > ce2->c[i])\n            return 1;\n    }\n    return 0;\n}\n\n\nstatic int get_decomp_pos(const DecompEntry *tab_de, int c)\n{\n    int i, v, k;\n    const DecompEntry *de;\n    \n    k = 0;\n    for(i = 0; i <= CHARCODE_MAX; i++) {\n        de = &tab_de[i];\n        if (de->len != 0) {\n            if (c >= de->code && c < de->code + de->len) {\n                v = c - de->code;\n                assert(v < 64);\n                v |= k << 6;\n                assert(v < 65536);\n                return v;\n            }\n            i += de->len - 1;\n            k++;\n        }\n    }\n    return -1;\n}\n\nvoid build_compose_table(FILE *f, const DecompEntry *tab_de)\n{\n    int i, v, tab_ce_len;\n    ComposeEntry *ce, *tab_ce;\n    \n    tab_ce = malloc(sizeof(*tab_ce) * COMPOSE_LEN_MAX);\n    tab_ce_len = 0;\n    for(i = 0; i <= CHARCODE_MAX; i++) {\n        CCInfo *ci = &unicode_db[i];\n        if (ci->decomp_len == 2 && !ci->is_compat &&\n            !ci->is_excluded) {\n            assert(tab_ce_len < COMPOSE_LEN_MAX); \n            ce = &tab_ce[tab_ce_len++];\n            ce->c[0] = ci->decomp_data[0];\n            ce->c[1] = ci->decomp_data[1];\n            ce->p = i;\n        }\n    }\n    qsort(tab_ce, tab_ce_len, sizeof(*tab_ce), ce_cmp);\n\n#if 0\n    {\n        printf(\"tab_ce_len=%d\\n\", tab_ce_len);\n        for(i = 0; i < tab_ce_len; i++) {\n            ce = &tab_ce[i];\n            printf(\"%05x %05x %05x\\n\", ce->c[0], ce->c[1], ce->p);\n        }\n    }\n#endif\n    \n    fprintf(f, \"static const uint16_t unicode_comp_table[%u] = {\",\n            tab_ce_len);\n    for(i = 0; i < tab_ce_len; i++) {\n        if (i % 8 == 0)\n            fprintf(f, \"\\n   \");\n        v = get_decomp_pos(tab_de, tab_ce[i].p);\n        if (v < 0) {\n            printf(\"ERROR: entry for c=%04x not found\\n\",\n                   tab_ce[i].p);\n            exit(1);\n        }\n        fprintf(f, \" 0x%04x,\", v);\n    }\n    fprintf(f, \"\\n};\\n\\n\");\n    \n    free(tab_ce);\n}\n\n#ifdef USE_TEST\nvoid check_decompose_table(void)\n{\n    int c;\n    CCInfo *ci;\n    int res[UNICODE_DECOMP_LEN_MAX], *ref;\n    int len, ref_len, is_compat;\n\n    for(is_compat = 0; is_compat <= 1; is_compat++) {\n        for(c = 0; c < CHARCODE_MAX; c++) {\n            ci = &unicode_db[c];\n            ref_len = ci->decomp_len;\n            ref = ci->decomp_data;\n            if (!is_compat && ci->is_compat) {\n                ref_len = 0;\n            }\n            len = unicode_decomp_char((uint32_t *)res, c, is_compat);\n            if (len != ref_len ||\n                tabcmp(res, ref, ref_len) != 0) {\n                printf(\"ERROR c=%05x compat=%d\\n\", c, is_compat);\n                dump_str(\"res\", res, len);\n                dump_str(\"ref\", ref, ref_len);\n                exit(1);\n            }\n        }\n    }\n}\n\nvoid check_compose_table(void)\n{\n    int i, p;\n    /* XXX: we don't test all the cases */\n\n    for(i = 0; i <= CHARCODE_MAX; i++) {\n        CCInfo *ci = &unicode_db[i];\n        if (ci->decomp_len == 2 && !ci->is_compat &&\n            !ci->is_excluded) {\n            p = unicode_compose_pair(ci->decomp_data[0], ci->decomp_data[1]);\n            if (p != i) {\n                printf(\"ERROR compose: c=%05x %05x -> %05x ref=%05x\\n\",\n                       ci->decomp_data[0], ci->decomp_data[1], p, i);\n                exit(1);\n            }\n        }\n    }\n    \n\n\n}\n\n#endif\n\n\n\n#ifdef USE_TEST\n\nvoid check_str(const char *msg, int num, const int *in_buf, int in_len,\n               const int *buf1, int len1,\n               const int *buf2, int len2)\n{\n    if (len1 != len2 || tabcmp(buf1, buf2, len1) != 0) {\n        printf(\"%d: ERROR %s:\\n\", num, msg);\n        dump_str(\" in\", in_buf, in_len);\n        dump_str(\"res\", buf1, len1);\n        dump_str(\"ref\", buf2, len2);\n        exit(1);\n    }\n}\n\nvoid check_cc_table(void)\n{\n    int cc, cc_ref, c;\n\n    for(c = 0; c <= CHARCODE_MAX; c++) {\n        cc_ref = unicode_db[c].combining_class;\n        cc = unicode_get_cc(c);\n        if (cc != cc_ref) {\n            printf(\"ERROR: c=%04x cc=%d cc_ref=%d\\n\",\n                   c, cc, cc_ref);\n            exit(1);\n        }\n    }\n#ifdef PROFILE\n    {\n        int64_t ti, count;\n    \n        ti = get_time_ns();\n        count = 0;\n        /* only do it on meaningful chars */\n        for(c = 0x20; c <= 0xffff; c++) {\n            cc_ref = unicode_db[c].combining_class;\n            cc = unicode_get_cc(c);\n            count++;\n        }\n        ti = get_time_ns() - ti;\n        printf(\"cc time=%0.1f ns/char\\n\",\n               (double)ti / count);\n    }\n#endif\n}\n\nvoid normalization_test(const char *filename)\n{\n    FILE *f;\n    char line[4096], *p;\n    int *in_str, *nfc_str, *nfd_str, *nfkc_str, *nfkd_str;\n    int in_len, nfc_len, nfd_len, nfkc_len, nfkd_len;\n    int *buf, buf_len, pos;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n    pos = 0;\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        pos++;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#' || *p == '@')\n            continue;\n        in_str = get_field_str(&in_len, p, 0);\n        nfc_str = get_field_str(&nfc_len, p, 1);\n        nfd_str = get_field_str(&nfd_len, p, 2);\n        nfkc_str = get_field_str(&nfkc_len, p, 3);\n        nfkd_str = get_field_str(&nfkd_len, p, 4);\n\n        //        dump_str(\"in\", in_str, in_len);\n\n        buf_len = unicode_normalize((uint32_t **)&buf, (uint32_t *)in_str, in_len, UNICODE_NFD, NULL, NULL);\n        check_str(\"nfd\", pos, in_str, in_len, buf, buf_len, nfd_str, nfd_len);\n        free(buf);\n\n        buf_len = unicode_normalize((uint32_t **)&buf, (uint32_t *)in_str, in_len, UNICODE_NFKD, NULL, NULL);\n        check_str(\"nfkd\", pos, in_str, in_len, buf, buf_len, nfkd_str, nfkd_len);\n        free(buf);\n        \n        buf_len = unicode_normalize((uint32_t **)&buf, (uint32_t *)in_str, in_len, UNICODE_NFC, NULL, NULL);\n        check_str(\"nfc\", pos, in_str, in_len, buf, buf_len, nfc_str, nfc_len);\n        free(buf);\n\n        buf_len = unicode_normalize((uint32_t **)&buf, (uint32_t *)in_str, in_len, UNICODE_NFKC, NULL, NULL);\n        check_str(\"nfkc\", pos, in_str, in_len, buf, buf_len, nfkc_str, nfkc_len);\n        free(buf);\n\n        free(in_str);\n        free(nfc_str);\n        free(nfd_str);\n        free(nfkc_str);\n        free(nfkd_str);\n    }\n    fclose(f);\n}\n#endif\n\nint main(int argc, char **argv)\n{\n    const char *unicode_db_path, *outfilename;\n    char filename[1024];\n    \n    if (argc < 2) {\n        printf(\"usage: %s unicode_db_path [output_file]\\n\"\n               \"\\n\"\n               \"If no output_file is given, a self test is done using the current unicode library\\n\",\n               argv[0]);\n        exit(1);\n    }\n    unicode_db_path = argv[1];\n    outfilename = NULL;\n    if (argc >= 3)\n        outfilename = argv[2];\n\n    unicode_db = mallocz(sizeof(unicode_db[0]) * (CHARCODE_MAX + 1));\n\n    snprintf(filename, sizeof(filename), \"%s/UnicodeData.txt\", unicode_db_path);\n\n    parse_unicode_data(filename);\n\n    snprintf(filename, sizeof(filename), \"%s/SpecialCasing.txt\", unicode_db_path);\n    parse_special_casing(unicode_db, filename);\n    \n    snprintf(filename, sizeof(filename), \"%s/CaseFolding.txt\", unicode_db_path);\n    parse_case_folding(unicode_db, filename);\n\n    snprintf(filename, sizeof(filename), \"%s/CompositionExclusions.txt\", unicode_db_path);\n    parse_composition_exclusions(filename);\n    \n    snprintf(filename, sizeof(filename), \"%s/DerivedCoreProperties.txt\", unicode_db_path);\n    parse_derived_core_properties(filename);\n\n    snprintf(filename, sizeof(filename), \"%s/DerivedNormalizationProps.txt\", unicode_db_path);\n    parse_derived_norm_properties(filename);\n\n    snprintf(filename, sizeof(filename), \"%s/PropList.txt\", unicode_db_path);\n    parse_prop_list(filename);\n\n    snprintf(filename, sizeof(filename), \"%s/Scripts.txt\", unicode_db_path);\n    parse_scripts(filename);\n\n    snprintf(filename, sizeof(filename), \"%s/ScriptExtensions.txt\",\n             unicode_db_path);\n    parse_script_extensions(filename);\n                        \n    snprintf(filename, sizeof(filename), \"%s/emoji-data.txt\",\n             unicode_db_path);\n    parse_prop_list(filename);\n\n    //    dump_data(unicode_db);\n\n    build_conv_table(unicode_db);\n    \n    //    dump_table();\n\n    if (!outfilename) {\n#ifdef USE_TEST\n        check_case_conv();\n        check_flags();\n        check_decompose_table();\n        check_compose_table();\n        check_cc_table();\n        snprintf(filename, sizeof(filename), \"%s/NormalizationTest.txt\", unicode_db_path);\n        normalization_test(filename);\n#else\n        fprintf(stderr, \"Tests are not compiled\\n\");\n        exit(1);\n#endif\n    } else\n    {\n        FILE *fo = fopen(outfilename, \"wb\");\n        \n        if (!fo) {\n            perror(outfilename);\n            exit(1);\n        }\n        fprintf(fo,\n                \"/* Compressed unicode tables */\\n\"\n                \"/* Automatically generated file - do not edit */\\n\"\n                \"\\n\"\n                \"#include <stdint.h>\\n\"\n                \"\\n\");\n        dump_case_conv_table(fo);\n        compute_internal_props();\n        build_flags_tables(fo);\n        fprintf(fo, \"#ifdef CONFIG_ALL_UNICODE\\n\\n\");\n        build_cc_table(fo);\n        build_decompose_table(fo);\n        build_general_category_table(fo);\n        build_script_table(fo);\n        build_script_ext_table(fo);\n        build_prop_list_table(fo);\n        fprintf(fo, \"#endif /* CONFIG_ALL_UNICODE */\\n\");\n        fclose(fo);\n    }\n    return 0;\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-latest/unicode_gen_def.h",
    "content": "#ifdef UNICODE_GENERAL_CATEGORY\nDEF(Cn, \"Unassigned\") /* must be zero */\nDEF(Lu, \"Uppercase_Letter\")\nDEF(Ll, \"Lowercase_Letter\")\nDEF(Lt, \"Titlecase_Letter\")\nDEF(Lm, \"Modifier_Letter\")\nDEF(Lo, \"Other_Letter\")\nDEF(Mn, \"Nonspacing_Mark\")\nDEF(Mc, \"Spacing_Mark\")\nDEF(Me, \"Enclosing_Mark\")\nDEF(Nd, \"Decimal_Number,digit\")\nDEF(Nl, \"Letter_Number\")\nDEF(No, \"Other_Number\")\nDEF(Sm, \"Math_Symbol\")\nDEF(Sc, \"Currency_Symbol\")\nDEF(Sk, \"Modifier_Symbol\")\nDEF(So, \"Other_Symbol\")\nDEF(Pc, \"Connector_Punctuation\")\nDEF(Pd, \"Dash_Punctuation\")\nDEF(Ps, \"Open_Punctuation\")\nDEF(Pe, \"Close_Punctuation\")\nDEF(Pi, \"Initial_Punctuation\")\nDEF(Pf, \"Final_Punctuation\")\nDEF(Po, \"Other_Punctuation\")\nDEF(Zs, \"Space_Separator\")\nDEF(Zl, \"Line_Separator\")\nDEF(Zp, \"Paragraph_Separator\")\nDEF(Cc, \"Control,cntrl\")\nDEF(Cf, \"Format\")\nDEF(Cs, \"Surrogate\")\nDEF(Co, \"Private_Use\")\n/* synthetic properties */\nDEF(LC, \"Cased_Letter\")\nDEF(L, \"Letter\")\nDEF(M, \"Mark,Combining_Mark\")\nDEF(N, \"Number\")\nDEF(S, \"Symbol\")\nDEF(P, \"Punctuation,punct\")\nDEF(Z, \"Separator\")\nDEF(C, \"Other\")\n#endif\n\n#ifdef UNICODE_SCRIPT\n/* scripts aliases names in PropertyValueAliases.txt */\nDEF(Unknown, \"Zzzz\")\nDEF(Adlam, \"Adlm\")\nDEF(Ahom, \"Ahom\")\nDEF(Anatolian_Hieroglyphs, \"Hluw\")\nDEF(Arabic, \"Arab\")\nDEF(Armenian, \"Armn\")\nDEF(Avestan, \"Avst\")\nDEF(Balinese, \"Bali\")\nDEF(Bamum, \"Bamu\")\nDEF(Bassa_Vah, \"Bass\")\nDEF(Batak, \"Batk\")\nDEF(Bengali, \"Beng\")\nDEF(Bhaiksuki, \"Bhks\")\nDEF(Bopomofo, \"Bopo\")\nDEF(Brahmi, \"Brah\")\nDEF(Braille, \"Brai\")\nDEF(Buginese, \"Bugi\")\nDEF(Buhid, \"Buhd\")\nDEF(Canadian_Aboriginal, \"Cans\")\nDEF(Carian, \"Cari\")\nDEF(Caucasian_Albanian, \"Aghb\")\nDEF(Chakma, \"Cakm\")\nDEF(Cham, \"Cham\")\nDEF(Cherokee, \"Cher\")\nDEF(Chorasmian, \"Chrs\")\nDEF(Common, \"Zyyy\")\nDEF(Coptic, \"Copt,Qaac\")\nDEF(Cuneiform, \"Xsux\")\nDEF(Cypriot, \"Cprt\")\nDEF(Cyrillic, \"Cyrl\")\nDEF(Deseret, \"Dsrt\")\nDEF(Devanagari, \"Deva\")\nDEF(Dives_Akuru, \"Diak\")\nDEF(Dogra, \"Dogr\")\nDEF(Duployan, \"Dupl\")\nDEF(Egyptian_Hieroglyphs, \"Egyp\")\nDEF(Elbasan, \"Elba\")\nDEF(Elymaic, \"Elym\")\nDEF(Ethiopic, \"Ethi\")\nDEF(Georgian, \"Geor\")\nDEF(Glagolitic, \"Glag\")\nDEF(Gothic, \"Goth\")\nDEF(Grantha, \"Gran\")\nDEF(Greek, \"Grek\")\nDEF(Gujarati, \"Gujr\")\nDEF(Gunjala_Gondi, \"Gong\")\nDEF(Gurmukhi, \"Guru\")\nDEF(Han, \"Hani\")\nDEF(Hangul, \"Hang\")\nDEF(Hanifi_Rohingya, \"Rohg\")\nDEF(Hanunoo, \"Hano\")\nDEF(Hatran, \"Hatr\")\nDEF(Hebrew, \"Hebr\")\nDEF(Hiragana, \"Hira\")\nDEF(Imperial_Aramaic, \"Armi\")\nDEF(Inherited, \"Zinh,Qaai\")\nDEF(Inscriptional_Pahlavi, \"Phli\")\nDEF(Inscriptional_Parthian, \"Prti\")\nDEF(Javanese, \"Java\")\nDEF(Kaithi, \"Kthi\")\nDEF(Kannada, \"Knda\")\nDEF(Katakana, \"Kana\")\nDEF(Kayah_Li, \"Kali\")\nDEF(Kharoshthi, \"Khar\")\nDEF(Khmer, \"Khmr\")\nDEF(Khojki, \"Khoj\")\nDEF(Khitan_Small_Script, \"Kits\")\nDEF(Khudawadi, \"Sind\")\nDEF(Lao, \"Laoo\")\nDEF(Latin, \"Latn\")\nDEF(Lepcha, \"Lepc\")\nDEF(Limbu, \"Limb\")\nDEF(Linear_A, \"Lina\")\nDEF(Linear_B, \"Linb\")\nDEF(Lisu, \"Lisu\")\nDEF(Lycian, \"Lyci\")\nDEF(Lydian, \"Lydi\")\nDEF(Makasar, \"Maka\")\nDEF(Mahajani, \"Mahj\")\nDEF(Malayalam, \"Mlym\")\nDEF(Mandaic, \"Mand\")\nDEF(Manichaean, \"Mani\")\nDEF(Marchen, \"Marc\")\nDEF(Masaram_Gondi, \"Gonm\")\nDEF(Medefaidrin, \"Medf\")\nDEF(Meetei_Mayek, \"Mtei\")\nDEF(Mende_Kikakui, \"Mend\")\nDEF(Meroitic_Cursive, \"Merc\")\nDEF(Meroitic_Hieroglyphs, \"Mero\")\nDEF(Miao, \"Plrd\")\nDEF(Modi, \"Modi\")\nDEF(Mongolian, \"Mong\")\nDEF(Mro, \"Mroo\")\nDEF(Multani, \"Mult\")\nDEF(Myanmar, \"Mymr\")\nDEF(Nabataean, \"Nbat\")\nDEF(Nandinagari, \"Nand\")\nDEF(New_Tai_Lue, \"Talu\")\nDEF(Newa, \"Newa\")\nDEF(Nko, \"Nkoo\")\nDEF(Nushu, \"Nshu\")\nDEF(Nyiakeng_Puachue_Hmong, \"Hmnp\")\nDEF(Ogham, \"Ogam\")\nDEF(Ol_Chiki, \"Olck\")\nDEF(Old_Hungarian, \"Hung\")\nDEF(Old_Italic, \"Ital\")\nDEF(Old_North_Arabian, \"Narb\")\nDEF(Old_Permic, \"Perm\")\nDEF(Old_Persian, \"Xpeo\")\nDEF(Old_Sogdian, \"Sogo\")\nDEF(Old_South_Arabian, \"Sarb\")\nDEF(Old_Turkic, \"Orkh\")\nDEF(Oriya, \"Orya\")\nDEF(Osage, \"Osge\")\nDEF(Osmanya, \"Osma\")\nDEF(Pahawh_Hmong, \"Hmng\")\nDEF(Palmyrene, \"Palm\")\nDEF(Pau_Cin_Hau, \"Pauc\")\nDEF(Phags_Pa, \"Phag\")\nDEF(Phoenician, \"Phnx\")\nDEF(Psalter_Pahlavi, \"Phlp\")\nDEF(Rejang, \"Rjng\")\nDEF(Runic, \"Runr\")\nDEF(Samaritan, \"Samr\")\nDEF(Saurashtra, \"Saur\")\nDEF(Sharada, \"Shrd\")\nDEF(Shavian, \"Shaw\")\nDEF(Siddham, \"Sidd\")\nDEF(SignWriting, \"Sgnw\")\nDEF(Sinhala, \"Sinh\")\nDEF(Sogdian, \"Sogd\")\nDEF(Sora_Sompeng, \"Sora\")\nDEF(Soyombo, \"Soyo\")\nDEF(Sundanese, \"Sund\")\nDEF(Syloti_Nagri, \"Sylo\")\nDEF(Syriac, \"Syrc\")\nDEF(Tagalog, \"Tglg\")\nDEF(Tagbanwa, \"Tagb\")\nDEF(Tai_Le, \"Tale\")\nDEF(Tai_Tham, \"Lana\")\nDEF(Tai_Viet, \"Tavt\")\nDEF(Takri, \"Takr\")\nDEF(Tamil, \"Taml\")\nDEF(Tangut, \"Tang\")\nDEF(Telugu, \"Telu\")\nDEF(Thaana, \"Thaa\")\nDEF(Thai, \"Thai\")\nDEF(Tibetan, \"Tibt\")\nDEF(Tifinagh, \"Tfng\")\nDEF(Tirhuta, \"Tirh\")\nDEF(Ugaritic, \"Ugar\")\nDEF(Vai, \"Vaii\")\nDEF(Wancho, \"Wcho\")\nDEF(Warang_Citi, \"Wara\")\nDEF(Yezidi, \"Yezi\")\nDEF(Yi, \"Yiii\")\nDEF(Zanabazar_Square, \"Zanb\")\n#endif\n\n#ifdef UNICODE_PROP_LIST\n/* Prop list not exported to regexp */\nDEF(Hyphen, \"\")\nDEF(Other_Math, \"\")\nDEF(Other_Alphabetic, \"\")\nDEF(Other_Lowercase, \"\")\nDEF(Other_Uppercase, \"\")\nDEF(Other_Grapheme_Extend, \"\")\nDEF(Other_Default_Ignorable_Code_Point, \"\")\nDEF(Other_ID_Start, \"\")\nDEF(Other_ID_Continue, \"\")\nDEF(Prepended_Concatenation_Mark, \"\")\n/* additional computed properties for smaller tables */\nDEF(ID_Continue1, \"\")\nDEF(XID_Start1, \"\")\nDEF(XID_Continue1, \"\")\nDEF(Changes_When_Titlecased1, \"\")\nDEF(Changes_When_Casefolded1, \"\")\nDEF(Changes_When_NFKC_Casefolded1, \"\")\n\n/* Prop list exported to JS */\nDEF(ASCII_Hex_Digit, \"AHex\")\nDEF(Bidi_Control, \"Bidi_C\")\nDEF(Dash, \"\")\nDEF(Deprecated, \"Dep\")\nDEF(Diacritic, \"Dia\")\nDEF(Extender, \"Ext\")\nDEF(Hex_Digit, \"Hex\")\nDEF(IDS_Binary_Operator, \"IDSB\")\nDEF(IDS_Trinary_Operator, \"IDST\")\nDEF(Ideographic, \"Ideo\")\nDEF(Join_Control, \"Join_C\")\nDEF(Logical_Order_Exception, \"LOE\")\nDEF(Noncharacter_Code_Point, \"NChar\")\nDEF(Pattern_Syntax, \"Pat_Syn\")\nDEF(Pattern_White_Space, \"Pat_WS\")\nDEF(Quotation_Mark, \"QMark\")\nDEF(Radical, \"\")\nDEF(Regional_Indicator, \"RI\")\nDEF(Sentence_Terminal, \"STerm\")\nDEF(Soft_Dotted, \"SD\")\nDEF(Terminal_Punctuation, \"Term\")\nDEF(Unified_Ideograph, \"UIdeo\")\nDEF(Variation_Selector, \"VS\")\nDEF(White_Space, \"space\")\nDEF(Bidi_Mirrored, \"Bidi_M\")\nDEF(Emoji, \"\")\nDEF(Emoji_Component, \"EComp\")\nDEF(Emoji_Modifier, \"EMod\")\nDEF(Emoji_Modifier_Base, \"EBase\")\nDEF(Emoji_Presentation, \"EPres\")\nDEF(Extended_Pictographic, \"ExtPict\")\nDEF(Default_Ignorable_Code_Point, \"DI\")\nDEF(ID_Start, \"IDS\")\nDEF(Case_Ignorable, \"CI\")\n\n/* other binary properties */\nDEF(ASCII,\"\")\nDEF(Alphabetic, \"Alpha\")\nDEF(Any, \"\")\nDEF(Assigned,\"\")\nDEF(Cased, \"\")\nDEF(Changes_When_Casefolded, \"CWCF\")\nDEF(Changes_When_Casemapped, \"CWCM\")\nDEF(Changes_When_Lowercased, \"CWL\")\nDEF(Changes_When_NFKC_Casefolded, \"CWKCF\")\nDEF(Changes_When_Titlecased, \"CWT\")\nDEF(Changes_When_Uppercased, \"CWU\")\nDEF(Grapheme_Base, \"Gr_Base\")\nDEF(Grapheme_Extend, \"Gr_Ext\")\nDEF(ID_Continue, \"IDC\")\nDEF(Lowercase, \"Lower\")\nDEF(Math, \"\")\nDEF(Uppercase, \"Upper\")\nDEF(XID_Continue, \"XIDC\")\nDEF(XID_Start, \"XIDS\")\n\n/* internal tables with index */\nDEF(Cased1, \"\")\n\n#endif\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/Changelog",
    "content": "2021-03-27:\n\n- faster Array.prototype.push and Array.prototype.unshift\n- added JS_UpdateStackTop()\n- fixed Windows console\n- misc bug fixes\n\n2020-11-08:\n\n- improved function parameter initializers\n- added std.setenv(), std.unsetenv() and std.getenviron()\n- added JS_EvalThis()\n- misc bug fixes\n\n2020-09-06:\n\n- added logical assignment operators\n- added IsHTMLDDA support\n- faster for-of loops\n- os.Worker now takes a module filename as parameter\n- qjsc: added -D option to compile dynamically loaded modules or workers\n- misc bug fixes\n\n2020-07-05:\n\n- modified JS_GetPrototype() to return a live value\n- REPL: support unicode characters larger than 16 bits\n- added os.Worker\n- improved object serialization\n- added std.parseExtJSON\n- misc bug fixes\n\n2020-04-12:\n\n- added cross realm support\n- added AggregateError and Promise.any\n- added env, uid and gid options in os.exec()\n- misc bug fixes\n\n2020-03-16:\n\n- reworked error handling in std and os libraries: suppressed I/O\n  exceptions in std FILE functions and return a positive errno value\n  when it is explicit\n- output exception messages to stderr\n- added std.loadFile(), std.strerror(), std.FILE.prototype.tello()\n- added JS_GetRuntimeOpaque(), JS_SetRuntimeOpaque(), JS_NewUint32()\n- updated to Unicode 13.0.0\n- misc bug fixes\n\n2020-01-19:\n\n- keep CONFIG_BIGNUM in the makefile\n- added os.chdir()\n- qjs: added -I option\n- more memory checks in the bignum operations\n- modified operator overloading semantics to be closer to the TC39\n  proposal\n- suppressed \"use bigint\" mode. Simplified \"use math\" mode\n- BigDecimal: changed suffix from 'd' to 'm'\n- misc bug fixes\n\n2020-01-05:\n\n- always compile the bignum code. Added '--bignum' option to qjs.\n- added BigDecimal\n- added String.prototype.replaceAll\n- misc bug fixes\n\n2019-12-21:\n\n- added nullish coalescing operator (ES2020)\n- added optional chaining (ES2020)\n- removed recursions in garbage collector\n- test stack overflow in the parser\n- improved backtrace logic\n- added JS_SetHostPromiseRejectionTracker()\n- allow exotic constructors\n- improved c++ compatibility\n- misc bug fixes\n\n2019-10-27:\n\n- added example of C class in a module (examples/test_point.js)\n- added JS_GetTypedArrayBuffer()\n- misc bug fixes\n\n2019-09-18:\n\n- added os.exec and other system calls\n- exported JS_ValueToAtom()\n- qjsc: added 'qjsc_' prefix to the generated C identifiers\n- added cross-compilation support\n- misc bug fixes\n\n2019-09-01:\n\n- added globalThis\n- documented JS_EVAL_FLAG_COMPILE_ONLY\n- added import.meta.url and import.meta.main\n- added 'debugger' statement\n- misc bug fixes\n\n2019-08-18:\n\n- added os.realpath, os.getcwd, os.mkdir, os.stat, os.lstat,\n  os.readlink, os.readdir, os.utimes, std.popen\n- module autodetection\n- added import.meta\n- misc bug fixes\n\n2019-08-10:\n\n- added public class fields and private class fields, methods and\n  accessors (TC39 proposal)\n- changed JS_ToCStringLen() prototype\n- qjsc: handle '-' in module names and modules with the same filename\n- added std.urlGet\n- exported JS_GetOwnPropertyNames() and JS_GetOwnProperty()\n- exported some bigint C functions\n- added support for eshost in run-test262\n- misc bug fixes\n\n2019-07-28:\n\n- added dynamic import\n- added Promise.allSettled\n- added String.prototype.matchAll\n- added Object.fromEntries\n- reduced number of ticks in await\n- added BigInt support in Atomics\n- exported JS_NewPromiseCapability()\n- misc async function and async generator fixes\n- enabled hashbang support by default\n\n2019-07-21:\n\n- updated test262 tests\n- updated to Unicode version 12.1.0\n- fixed missing Date object in qjsc\n- fixed multi-context creation\n- misc ES2020 related fixes\n- simplified power and division operators in bignum extension\n- fixed several crash conditions\n\n2019-07-09:\n\n- first public release\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/LICENSE",
    "content": "QuickJS Javascript Engine\n \nCopyright (c) 2017-2021 Fabrice Bellard\nCopyright (c) 2017-2021 Charlie Gordon\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/Makefile",
    "content": "#\n# QuickJS Javascript Engine\n# \n# Copyright (c) 2017-2021 Fabrice Bellard\n# Copyright (c) 2017-2021 Charlie Gordon\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nifeq ($(shell uname -s),Darwin)\nCONFIG_DARWIN=y\nendif\n# Windows cross compilation from Linux\n#CONFIG_WIN32=y\n# use link time optimization (smaller and faster executables but slower build)\nCONFIG_LTO=y\n# consider warnings as errors (for development)\n#CONFIG_WERROR=y\n# force 32 bit build for some utilities\n#CONFIG_M32=y\n\nifdef CONFIG_DARWIN\n# use clang instead of gcc\nCONFIG_CLANG=y\nCONFIG_DEFAULT_AR=y\nendif\n\n# installation directory\nprefix=/usr/local\n\n# use the gprof profiler\n#CONFIG_PROFILE=y\n# use address sanitizer\n#CONFIG_ASAN=y\n# include the code for BigInt/BigFloat/BigDecimal and math mode\nCONFIG_BIGNUM=y\n\nOBJDIR=.obj\n\nifdef CONFIG_WIN32\n  ifdef CONFIG_M32\n    CROSS_PREFIX=i686-w64-mingw32-\n  else\n    CROSS_PREFIX=x86_64-w64-mingw32-\n  endif\n  EXE=.exe\nelse\n  CROSS_PREFIX=\n  EXE=\nendif\nifdef CONFIG_CLANG\n  HOST_CC=clang\n  CC=$(CROSS_PREFIX)clang\n  CFLAGS=-g -Wall -MMD -MF $(OBJDIR)/$(@F).d\n  CFLAGS += -Wextra\n  CFLAGS += -Wno-sign-compare\n  CFLAGS += -Wno-missing-field-initializers\n  CFLAGS += -Wundef -Wuninitialized\n  CFLAGS += -Wunused -Wno-unused-parameter\n  CFLAGS += -Wwrite-strings\n  CFLAGS += -Wchar-subscripts -funsigned-char\n  CFLAGS += -MMD -MF $(OBJDIR)/$(@F).d\n  ifdef CONFIG_DEFAULT_AR\n    AR=$(CROSS_PREFIX)ar\n  else\n    ifdef CONFIG_LTO\n      AR=$(CROSS_PREFIX)llvm-ar\n    else\n      AR=$(CROSS_PREFIX)ar\n    endif\n  endif\nelse\n  HOST_CC=gcc\n  CC=$(CROSS_PREFIX)gcc\n  CFLAGS=-g -Wall -MMD -MF $(OBJDIR)/$(@F).d\n  CFLAGS += -Wno-array-bounds -Wno-format-truncation\n  ifdef CONFIG_LTO\n    AR=$(CROSS_PREFIX)gcc-ar\n  else\n    AR=$(CROSS_PREFIX)ar\n  endif\nendif\nSTRIP=$(CROSS_PREFIX)strip\nifdef CONFIG_WERROR\nCFLAGS+=-Werror\nendif\nDEFINES:=-D_GNU_SOURCE -DCONFIG_VERSION=\\\"$(shell cat VERSION)\\\"\nifdef CONFIG_BIGNUM\nDEFINES+=-DCONFIG_BIGNUM\nendif\nifdef CONFIG_WIN32\nDEFINES+=-D__USE_MINGW_ANSI_STDIO # for standard snprintf behavior\nendif\n\nCFLAGS+=$(DEFINES)\nCFLAGS_DEBUG=$(CFLAGS) -O0\nCFLAGS_SMALL=$(CFLAGS) -Os\nCFLAGS_OPT=$(CFLAGS) -O2\nCFLAGS_NOLTO:=$(CFLAGS_OPT)\nLDFLAGS=-g\nifdef CONFIG_LTO\nCFLAGS_SMALL+=-flto\nCFLAGS_OPT+=-flto\nLDFLAGS+=-flto\nendif\nifdef CONFIG_PROFILE\nCFLAGS+=-p\nLDFLAGS+=-p\nendif\nifdef CONFIG_ASAN\nCFLAGS+=-fsanitize=address -fno-omit-frame-pointer\nLDFLAGS+=-fsanitize=address -fno-omit-frame-pointer\nendif\nifdef CONFIG_WIN32\nLDEXPORT=\nelse\nLDEXPORT=-rdynamic\nendif\n\nPROGS=qjs$(EXE) qjsc$(EXE) run-test262\nifneq ($(CROSS_PREFIX),)\nQJSC_CC=gcc\nQJSC=./host-qjsc\nPROGS+=$(QJSC)\nelse\nQJSC_CC=$(CC)\nQJSC=./qjsc$(EXE)\nendif\nifndef CONFIG_WIN32\nPROGS+=qjscalc\nendif\nifdef CONFIG_M32\nPROGS+=qjs32 qjs32_s\nendif\nPROGS+=libquickjs.a\nifdef CONFIG_LTO\nPROGS+=libquickjs.lto.a\nendif\n\n# examples\nifeq ($(CROSS_PREFIX),)\nifdef CONFIG_ASAN\nPROGS+=\nelse\nPROGS+=examples/hello examples/hello_module examples/test_fib\nifndef CONFIG_DARWIN\nPROGS+=examples/fib.so examples/point.so\nendif\nendif\nendif\n\nall: $(OBJDIR) $(OBJDIR)/quickjs.check.o $(OBJDIR)/qjs.check.o $(PROGS)\n\nQJS_LIB_OBJS=$(OBJDIR)/quickjs.o $(OBJDIR)/libregexp.o $(OBJDIR)/libunicode.o $(OBJDIR)/cutils.o $(OBJDIR)/quickjs-libc.o\n\nQJS_OBJS=$(OBJDIR)/qjs.o $(OBJDIR)/repl.o $(QJS_LIB_OBJS)\nifdef CONFIG_BIGNUM\nQJS_LIB_OBJS+=$(OBJDIR)/libbf.o \nQJS_OBJS+=$(OBJDIR)/qjscalc.o\nendif\n\nHOST_LIBS=-lm -ldl -lpthread\nLIBS=-lm\nifndef CONFIG_WIN32\nLIBS+=-ldl -lpthread\nendif\nLIBS+=$(EXTRA_LIBS)\n\n$(OBJDIR):\n\tmkdir -p $(OBJDIR) $(OBJDIR)/examples $(OBJDIR)/tests\n\nqjs$(EXE): $(QJS_OBJS)\n\t$(CC) $(LDFLAGS) $(LDEXPORT) -o $@ $^ $(LIBS)\n\nqjs-debug$(EXE): $(patsubst %.o, %.debug.o, $(QJS_OBJS))\n\t$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)\n\nqjsc$(EXE): $(OBJDIR)/qjsc.o $(QJS_LIB_OBJS)\n\t$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)\n\nifneq ($(CROSS_PREFIX),)\n\n$(QJSC): $(OBJDIR)/qjsc.host.o \\\n    $(patsubst %.o, %.host.o, $(QJS_LIB_OBJS))\n\t$(HOST_CC) $(LDFLAGS) -o $@ $^ $(HOST_LIBS)\n\nendif #CROSS_PREFIX\n\nQJSC_DEFINES:=-DCONFIG_CC=\\\"$(QJSC_CC)\\\" -DCONFIG_PREFIX=\\\"$(prefix)\\\"\nifdef CONFIG_LTO\nQJSC_DEFINES+=-DCONFIG_LTO\nendif\nQJSC_HOST_DEFINES:=-DCONFIG_CC=\\\"$(HOST_CC)\\\" -DCONFIG_PREFIX=\\\"$(prefix)\\\"\n\n$(OBJDIR)/qjsc.o: CFLAGS+=$(QJSC_DEFINES)\n$(OBJDIR)/qjsc.host.o: CFLAGS+=$(QJSC_HOST_DEFINES)\n\nqjs32: $(patsubst %.o, %.m32.o, $(QJS_OBJS))\n\t$(CC) -m32 $(LDFLAGS) $(LDEXPORT) -o $@ $^ $(LIBS)\n\nqjs32_s: $(patsubst %.o, %.m32s.o, $(QJS_OBJS))\n\t$(CC) -m32 $(LDFLAGS) -o $@ $^ $(LIBS)\n\t@size $@\n\nqjscalc: qjs\n\tln -sf $< $@\n\nifdef CONFIG_LTO\nLTOEXT=.lto\nelse\nLTOEXT=\nendif\n\nlibquickjs$(LTOEXT).a: $(QJS_LIB_OBJS)\n\t$(AR) rcs $@ $^\n\nifdef CONFIG_LTO\nlibquickjs.a: $(patsubst %.o, %.nolto.o, $(QJS_LIB_OBJS))\n\t$(AR) rcs $@ $^\nendif # CONFIG_LTO\n\nrepl.c: $(QJSC) repl.js\n\t$(QJSC) -c -o $@ -m repl.js\n\nqjscalc.c: $(QJSC) qjscalc.js\n\t$(QJSC) -fbignum -c -o $@ qjscalc.js\n\nifneq ($(wildcard unicode/UnicodeData.txt),)\n$(OBJDIR)/libunicode.o $(OBJDIR)/libunicode.m32.o $(OBJDIR)/libunicode.m32s.o \\\n    $(OBJDIR)/libunicode.nolto.o: libunicode-table.h\n\nlibunicode-table.h: unicode_gen\n\t./unicode_gen unicode $@\nendif\n\nrun-test262: $(OBJDIR)/run-test262.o $(QJS_LIB_OBJS)\n\t$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)\n\nrun-test262-debug: $(patsubst %.o, %.debug.o, $(OBJDIR)/run-test262.o $(QJS_LIB_OBJS))\n\t$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)\n\nrun-test262-32: $(patsubst %.o, %.m32.o, $(OBJDIR)/run-test262.o $(QJS_LIB_OBJS))\n\t$(CC) -m32 $(LDFLAGS) -o $@ $^ $(LIBS)\n\n# object suffix order: nolto, [m32|m32s]\n\n$(OBJDIR)/%.o: %.c | $(OBJDIR)\n\t$(CC) $(CFLAGS_OPT) -c -o $@ $<\n\n$(OBJDIR)/%.host.o: %.c | $(OBJDIR)\n\t$(HOST_CC) $(CFLAGS_OPT) -c -o $@ $<\n\n$(OBJDIR)/%.pic.o: %.c | $(OBJDIR)\n\t$(CC) $(CFLAGS_OPT) -fPIC -DJS_SHARED_LIBRARY -c -o $@ $<\n\n$(OBJDIR)/%.nolto.o: %.c | $(OBJDIR)\n\t$(CC) $(CFLAGS_NOLTO) -c -o $@ $<\n\n$(OBJDIR)/%.m32.o: %.c | $(OBJDIR)\n\t$(CC) -m32 $(CFLAGS_OPT) -c -o $@ $<\n\n$(OBJDIR)/%.m32s.o: %.c | $(OBJDIR)\n\t$(CC) -m32 $(CFLAGS_SMALL) -c -o $@ $<\n\n$(OBJDIR)/%.debug.o: %.c | $(OBJDIR)\n\t$(CC) $(CFLAGS_DEBUG) -c -o $@ $<\n\n$(OBJDIR)/%.check.o: %.c | $(OBJDIR)\n\t$(CC) $(CFLAGS) -DCONFIG_CHECK_JSVALUE -c -o $@ $<\n\nregexp_test: libregexp.c libunicode.c cutils.c\n\t$(CC) $(LDFLAGS) $(CFLAGS) -DTEST -o $@ libregexp.c libunicode.c cutils.c $(LIBS)\n\nunicode_gen: $(OBJDIR)/unicode_gen.host.o $(OBJDIR)/cutils.host.o libunicode.c unicode_gen_def.h\n\t$(HOST_CC) $(LDFLAGS) $(CFLAGS) -o $@ $(OBJDIR)/unicode_gen.host.o $(OBJDIR)/cutils.host.o\n\nclean:\n\trm -f repl.c qjscalc.c out.c\n\trm -f *.a *.o *.d *~ unicode_gen regexp_test $(PROGS)\n\trm -f hello.c test_fib.c\n\trm -f examples/*.so tests/*.so\n\trm -rf $(OBJDIR)/ *.dSYM/ qjs-debug\n\trm -rf run-test262-debug run-test262-32\n\ninstall: all\n\tmkdir -p \"$(DESTDIR)$(prefix)/bin\"\n\t$(STRIP) qjs qjsc\n\tinstall -m755 qjs qjsc \"$(DESTDIR)$(prefix)/bin\"\n\tln -sf qjs \"$(DESTDIR)$(prefix)/bin/qjscalc\"\n\tmkdir -p \"$(DESTDIR)$(prefix)/lib/quickjs\"\n\tinstall -m644 libquickjs.a \"$(DESTDIR)$(prefix)/lib/quickjs\"\nifdef CONFIG_LTO\n\tinstall -m644 libquickjs.lto.a \"$(DESTDIR)$(prefix)/lib/quickjs\"\nendif\n\tmkdir -p \"$(DESTDIR)$(prefix)/include/quickjs\"\n\tinstall -m644 quickjs.h quickjs-libc.h \"$(DESTDIR)$(prefix)/include/quickjs\"\n\n###############################################################################\n# examples\n\n# example of static JS compilation\nHELLO_SRCS=examples/hello.js\nHELLO_OPTS=-fno-string-normalize -fno-map -fno-promise -fno-typedarray \\\n           -fno-typedarray -fno-regexp -fno-json -fno-eval -fno-proxy \\\n           -fno-date -fno-module-loader\nifdef CONFIG_BIGNUM\nHELLO_OPTS+=-fno-bigint\nendif\n\nhello.c: $(QJSC) $(HELLO_SRCS)\n\t$(QJSC) -e $(HELLO_OPTS) -o $@ $(HELLO_SRCS)\n\nifdef CONFIG_M32\nexamples/hello: $(OBJDIR)/hello.m32s.o $(patsubst %.o, %.m32s.o, $(QJS_LIB_OBJS))\n\t$(CC) -m32 $(LDFLAGS) -o $@ $^ $(LIBS)\nelse\nexamples/hello: $(OBJDIR)/hello.o $(QJS_LIB_OBJS)\n\t$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)\nendif\n\n# example of static JS compilation with modules\nHELLO_MODULE_SRCS=examples/hello_module.js\nHELLO_MODULE_OPTS=-fno-string-normalize -fno-map -fno-promise -fno-typedarray \\\n           -fno-typedarray -fno-regexp -fno-json -fno-eval -fno-proxy \\\n           -fno-date -m\nexamples/hello_module: $(QJSC) libquickjs$(LTOEXT).a $(HELLO_MODULE_SRCS)\n\t$(QJSC) $(HELLO_MODULE_OPTS) -o $@ $(HELLO_MODULE_SRCS)\n\n# use of an external C module (static compilation)\n\ntest_fib.c: $(QJSC) examples/test_fib.js\n\t$(QJSC) -e -M examples/fib.so,fib -m -o $@ examples/test_fib.js\n\nexamples/test_fib: $(OBJDIR)/test_fib.o $(OBJDIR)/examples/fib.o libquickjs$(LTOEXT).a\n\t$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)\n\nexamples/fib.so: $(OBJDIR)/examples/fib.pic.o\n\t$(CC) $(LDFLAGS) -shared -o $@ $^\n\nexamples/point.so: $(OBJDIR)/examples/point.pic.o\n\t$(CC) $(LDFLAGS) -shared -o $@ $^\n\n###############################################################################\n# documentation\n\nDOCS=doc/quickjs.pdf doc/quickjs.html doc/jsbignum.pdf doc/jsbignum.html \n\nbuild_doc: $(DOCS)\n\nclean_doc: \n\trm -f $(DOCS)\n\ndoc/%.pdf: doc/%.texi\n\ttexi2pdf --clean -o $@ -q $<\n\ndoc/%.html.pre: doc/%.texi\n\tmakeinfo --html --no-headers --no-split --number-sections -o $@ $<\n\ndoc/%.html: doc/%.html.pre\n\tsed -e 's|</style>|</style>\\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">|' < $< > $@\n\n###############################################################################\n# tests\n\nifndef CONFIG_DARWIN\ntest: tests/bjson.so examples/point.so\nendif\nifdef CONFIG_M32\ntest: qjs32\nendif\n\ntest: qjs\n\t./qjs tests/test_closure.js\n\t./qjs tests/test_language.js\n\t./qjs tests/test_builtin.js\n\t./qjs tests/test_loop.js\n\t./qjs tests/test_std.js\n\t./qjs tests/test_worker.js\nifndef CONFIG_DARWIN\nifdef CONFIG_BIGNUM\n\t./qjs --bignum tests/test_bjson.js\nelse\n\t./qjs tests/test_bjson.js\nendif\n\t./qjs examples/test_point.js\nendif\nifdef CONFIG_BIGNUM\n\t./qjs --bignum tests/test_op_overloading.js\n\t./qjs --bignum tests/test_bignum.js\n\t./qjs --qjscalc tests/test_qjscalc.js\nendif\nifdef CONFIG_M32\n\t./qjs32 tests/test_closure.js\n\t./qjs32 tests/test_language.js\n\t./qjs32 tests/test_builtin.js\n\t./qjs32 tests/test_loop.js\n\t./qjs32 tests/test_std.js\n\t./qjs32 tests/test_worker.js\nifdef CONFIG_BIGNUM\n\t./qjs32 --bignum tests/test_op_overloading.js\n\t./qjs32 --bignum tests/test_bignum.js\n\t./qjs32 --qjscalc tests/test_qjscalc.js\nendif\nendif\n\nstats: qjs qjs32\n\t./qjs -qd\n\t./qjs32 -qd\n\nmicrobench: qjs\n\t./qjs tests/microbench.js\n\nmicrobench-32: qjs32\n\t./qjs32 tests/microbench.js\n\n# ES5 tests (obsolete)\ntest2o: run-test262\n\ttime ./run-test262 -m -c test262o.conf\n\ntest2o-32: run-test262-32\n\ttime ./run-test262-32 -m -c test262o.conf\n\ntest2o-update: run-test262\n\t./run-test262 -u -c test262o.conf\n\n# Test262 tests\ntest2-default: run-test262\n\ttime ./run-test262 -m -c test262.conf\n\ntest2: run-test262\n\ttime ./run-test262 -m -c test262.conf -a\n\ntest2-32: run-test262-32\n\ttime ./run-test262-32 -m -c test262.conf -a\n\ntest2-update: run-test262\n\t./run-test262 -u -c test262.conf -a\n\ntest2-check: run-test262\n\ttime ./run-test262 -m -c test262.conf -E -a\n\ntestall: all test microbench test2o test2\n\ntestall-32: all test-32 microbench-32 test2o-32 test2-32\n\ntestall-complete: testall testall-32\n\nbench-v8: qjs\n\tmake -C tests/bench-v8\n\t./qjs -d tests/bench-v8/combined.js\n\ntests/bjson.so: $(OBJDIR)/tests/bjson.pic.o\n\t$(CC) $(LDFLAGS) -shared -o $@ $^ $(LIBS)\n\n-include $(wildcard $(OBJDIR)/*.d)\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/TODO",
    "content": "Bugs:\n- modules: better error handling with cyclic module references\n\nMisc ideas:\n- use custom printf to avoid compatibility issues with floating point numbers\n- consistent naming for preprocessor defines\n- unify coding style and naming conventions\n- use names from the ECMA spec in library implementation\n- use byte code emitters with typed arguments (for clarity)\n- use 2 bytecode DynBufs in JSFunctionDef, one for reading, one for writing\n  and use the same wrappers in all phases\n- use more generic method for line numbers in resolve_variables and resolve_labels\n- use custom timezone support to avoid C library compatibility issues\n\nMemory:\n- use memory pools for objects, etc?\n- test border cases for max number of atoms, object properties, string length\n- add emergency malloc mode for out of memory exceptions.\n- test all DynBuf memory errors\n- test all js_realloc memory errors\n- improve JS_ComputeMemoryUsage() with more info\n\nBuilt-in standard library:\n- BSD sockets\n- modules: use realpath in module name normalizer and put it in quickjs-libc\n- modules: if no \".\", use a well known module loading path ?\n- get rid of __loadScript, use more common name\n\nREPL:\n- debugger\n- readline: support MS Windows terminal\n- readline: handle dynamic terminal resizing\n- readline: handle double width unicode characters\n- multiline editing\n- runtime object and function inspectors\n- interactive object browser\n- use more generic approach to display evaluation results\n- improve directive handling: dispatch, colorize, completion...\n- save history\n- close all predefined methods in repl.js and jscalc.js\n\nOptimization ideas:\n- 64-bit atoms in 64-bit mode ?\n- 64-bit small bigint in 64-bit mode ?\n- reuse stack slots for disjoint scopes, if strip\n- add heuristic to avoid some cycles in closures\n- small String (0-2 charcodes) with immediate storage\n- perform static string concatenation at compile time\n- optimize string concatenation with ropes or miniropes?\n- add implicit numeric strings for Uint32 numbers?\n- optimize `s += a + b`, `s += a.b` and similar simple expressions\n- ensure string canonical representation and optimise comparisons and hashes?\n- remove JSObject.first_weak_ref, use bit+context based hashed array for weak references\n- property access optimization on the global object, functions,\n  prototypes and special non extensible objects.\n- create object literals with the correct length by backpatching length argument\n- remove redundant set_loc_uninitialized/check_uninitialized opcodes\n- peephole optim: push_atom_value, to_propkey -> push_atom_value\n- peephole optim: put_loc x, get_loc_check x -> set_loc x\n- convert slow array to fast array when all properties != length are numeric\n- optimize destructuring assignments for global and local variables\n- implement some form of tail-call-optimization\n- optimize OP_apply\n- optimize f(...b)\n\nTest262o:   0/11262 errors, 463 excluded\nTest262o commit: 7da91bceb9ce7613f87db47ddd1292a2dda58b42 (es5-tests branch)\n\nResult: 35/75280 errors, 909 excluded, 585 skipped\nTest262 commit: 31126581e7290f9233c29cefd93f66c6ac78f1c9\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/VERSION",
    "content": "2021-03-27\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/cutils.c",
    "content": "/*\n * C utilities\n * \n * Copyright (c) 2017 Fabrice Bellard\n * Copyright (c) 2018 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <string.h>\n\n#include \"cutils.h\"\n\n#ifdef _MSC_VER\n\n // From: https://stackoverflow.com/a/26085827\nint gettimeofday(struct timeval* tp, struct timezone* tzp)\n{\n    static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL);\n\n    SYSTEMTIME  system_time;\n    FILETIME    file_time;\n    uint64_t    time;\n\n    GetSystemTime(&system_time);\n    SystemTimeToFileTime(&system_time, &file_time);\n    time = ((uint64_t)file_time.dwLowDateTime);\n    time += ((uint64_t)file_time.dwHighDateTime) << 32;\n\n    tp->tv_sec = (long)((time - EPOCH) / 10000000L);\n    tp->tv_usec = (long)(system_time.wMilliseconds * 1000);\n\n    return 0;\n}\n#endif\n\nvoid pstrcpy(char *buf, int buf_size, const char *str)\n{\n    int c;\n    char *q = buf;\n\n    if (buf_size <= 0)\n        return;\n\n    for(;;) {\n        c = *str++;\n        if (c == 0 || q >= buf + buf_size - 1)\n            break;\n        *q++ = c;\n    }\n    *q = '\\0';\n}\n\n/* strcat and truncate. */\nchar *pstrcat(char *buf, int buf_size, const char *s)\n{\n    int len;\n    len = strlen(buf);\n    if (len < buf_size)\n        pstrcpy(buf + len, buf_size - len, s);\n    return buf;\n}\n\nint strstart(const char *str, const char *val, const char **ptr)\n{\n    const char *p, *q;\n    p = str;\n    q = val;\n    while (*q != '\\0') {\n        if (*p != *q)\n            return 0;\n        p++;\n        q++;\n    }\n    if (ptr)\n        *ptr = p;\n    return 1;\n}\n\nint has_suffix(const char *str, const char *suffix)\n{\n    size_t len = strlen(str);\n    size_t slen = strlen(suffix);\n    return (len >= slen && !memcmp(str + len - slen, suffix, slen));\n}\n\n/* Dynamic buffer package */\n\nstatic void *dbuf_default_realloc(void *opaque, void *ptr, size_t size)\n{\n    return realloc(ptr, size);\n}\n\nvoid dbuf_init2(DynBuf *s, void *opaque, DynBufReallocFunc *realloc_func)\n{\n    memset(s, 0, sizeof(*s));\n    if (!realloc_func)\n        realloc_func = dbuf_default_realloc;\n    s->opaque = opaque;\n    s->realloc_func = realloc_func;\n}\n\nvoid dbuf_init(DynBuf *s)\n{\n    dbuf_init2(s, NULL, NULL);\n}\n\n/* return < 0 if error */\nint dbuf_realloc(DynBuf *s, size_t new_size)\n{\n    size_t size;\n    uint8_t *new_buf;\n    if (new_size > s->allocated_size) {\n        if (s->error)\n            return -1;\n        size = s->allocated_size * 3 / 2;\n        if (size > new_size)\n            new_size = size;\n        new_buf = s->realloc_func(s->opaque, s->buf, new_size);\n        if (!new_buf) {\n            s->error = TRUE;\n            return -1;\n        }\n        s->buf = new_buf;\n        s->allocated_size = new_size;\n    }\n    return 0;\n}\n\nint dbuf_write(DynBuf *s, size_t offset, const uint8_t *data, size_t len)\n{\n    size_t end;\n    end = offset + len;\n    if (dbuf_realloc(s, end))\n        return -1;\n    memcpy(s->buf + offset, data, len);\n    if (end > s->size)\n        s->size = end;\n    return 0;\n}\n\nint dbuf_put(DynBuf *s, const uint8_t *data, size_t len)\n{\n    if (unlikely((s->size + len) > s->allocated_size)) {\n        if (dbuf_realloc(s, s->size + len))\n            return -1;\n    }\n    memcpy(s->buf + s->size, data, len);\n    s->size += len;\n    return 0;\n}\n\nint dbuf_put_self(DynBuf *s, size_t offset, size_t len)\n{\n    if (unlikely((s->size + len) > s->allocated_size)) {\n        if (dbuf_realloc(s, s->size + len))\n            return -1;\n    }\n    memcpy(s->buf + s->size, s->buf + offset, len);\n    s->size += len;\n    return 0;\n}\n\nint dbuf_putc(DynBuf *s, uint8_t c)\n{\n    return dbuf_put(s, &c, 1);\n}\n\nint dbuf_putstr(DynBuf *s, const char *str)\n{\n    return dbuf_put(s, (const uint8_t *)str, strlen(str));\n}\n\nint __attribute__((format(printf, 2, 3))) dbuf_printf(DynBuf *s,\n                                                      const char *fmt, ...)\n{\n    va_list ap;\n    char buf[128];\n    int len;\n    \n    va_start(ap, fmt);\n    len = vsnprintf(buf, sizeof(buf), fmt, ap);\n    va_end(ap);\n    if (len < sizeof(buf)) {\n        /* fast case */\n        return dbuf_put(s, (uint8_t *)buf, len);\n    } else {\n        if (dbuf_realloc(s, s->size + len + 1))\n            return -1;\n        va_start(ap, fmt);\n        vsnprintf((char *)(s->buf + s->size), s->allocated_size - s->size,\n                  fmt, ap);\n        va_end(ap);\n        s->size += len;\n    }\n    return 0;\n}\n\nvoid dbuf_free(DynBuf *s)\n{\n    /* we test s->buf as a fail safe to avoid crashing if dbuf_free()\n       is called twice */\n    if (s->buf) {\n        s->realloc_func(s->opaque, s->buf, 0);\n    }\n    memset(s, 0, sizeof(*s));\n}\n\n/* Note: at most 31 bits are encoded. At most UTF8_CHAR_LEN_MAX bytes\n   are output. */\nint unicode_to_utf8(uint8_t *buf, unsigned int c)\n{\n    uint8_t *q = buf;\n\n    if (c < 0x80) {\n        *q++ = c;\n    } else {\n        if (c < 0x800) {\n            *q++ = (c >> 6) | 0xc0;\n        } else {\n            if (c < 0x10000) {\n                *q++ = (c >> 12) | 0xe0;\n            } else {\n                if (c < 0x00200000) {\n                    *q++ = (c >> 18) | 0xf0;\n                } else {\n                    if (c < 0x04000000) {\n                        *q++ = (c >> 24) | 0xf8;\n                    } else if (c < 0x80000000) {\n                        *q++ = (c >> 30) | 0xfc;\n                        *q++ = ((c >> 24) & 0x3f) | 0x80;\n                    } else {\n                        return 0;\n                    }\n                    *q++ = ((c >> 18) & 0x3f) | 0x80;\n                }\n                *q++ = ((c >> 12) & 0x3f) | 0x80;\n            }\n            *q++ = ((c >> 6) & 0x3f) | 0x80;\n        }\n        *q++ = (c & 0x3f) | 0x80;\n    }\n    return q - buf;\n}\n\nstatic const unsigned int utf8_min_code[5] = {\n    0x80, 0x800, 0x10000, 0x00200000, 0x04000000,\n};\n\nstatic const unsigned char utf8_first_code_mask[5] = {\n    0x1f, 0xf, 0x7, 0x3, 0x1,\n};\n\n/* return -1 if error. *pp is not updated in this case. max_len must\n   be >= 1. The maximum length for a UTF8 byte sequence is 6 bytes. */\nint unicode_from_utf8(const uint8_t *p, int max_len, const uint8_t **pp)\n{\n    int l, c, b, i;\n\n    c = *p++;\n    if (c < 0x80) {\n        *pp = p;\n        return c;\n    }\n    switch(c) {\n    case 0xc0: case 0xc1: case 0xc2: case 0xc3:\n    case 0xc4: case 0xc5: case 0xc6: case 0xc7:\n    case 0xc8: case 0xc9: case 0xca: case 0xcb:\n    case 0xcc: case 0xcd: case 0xce: case 0xcf:\n    case 0xd0: case 0xd1: case 0xd2: case 0xd3:\n    case 0xd4: case 0xd5: case 0xd6: case 0xd7:\n    case 0xd8: case 0xd9: case 0xda: case 0xdb:\n    case 0xdc: case 0xdd: case 0xde: case 0xdf:\n        l = 1;\n        break;\n    case 0xe0: case 0xe1: case 0xe2: case 0xe3:\n    case 0xe4: case 0xe5: case 0xe6: case 0xe7:\n    case 0xe8: case 0xe9: case 0xea: case 0xeb:\n    case 0xec: case 0xed: case 0xee: case 0xef:\n        l = 2;\n        break;\n    case 0xf0: case 0xf1: case 0xf2: case 0xf3:\n    case 0xf4: case 0xf5: case 0xf6: case 0xf7:\n        l = 3;\n        break;\n    case 0xf8: case 0xf9: case 0xfa: case 0xfb:\n        l = 4;\n        break;\n    case 0xfc: case 0xfd:\n        l = 5;\n        break;\n    default:\n        return -1;\n    }\n    /* check that we have enough characters */\n    if (l > (max_len - 1))\n        return -1;\n    c &= utf8_first_code_mask[l - 1];\n    for(i = 0; i < l; i++) {\n        b = *p++;\n        if (b < 0x80 || b >= 0xc0)\n            return -1;\n        c = (c << 6) | (b & 0x3f);\n    }\n    if (c < utf8_min_code[l - 1])\n        return -1;\n    *pp = p;\n    return c;\n}\n\n#if 0\n\n#if defined(EMSCRIPTEN) || defined(__ANDROID__)\n\nstatic void *rqsort_arg;\nstatic int (*rqsort_cmp)(const void *, const void *, void *);\n\nstatic int rqsort_cmp2(const void *p1, const void *p2)\n{\n    return rqsort_cmp(p1, p2, rqsort_arg);\n}\n\n/* not reentrant, but not needed with emscripten */\nvoid rqsort(void *base, size_t nmemb, size_t size,\n            int (*cmp)(const void *, const void *, void *),\n            void *arg)\n{\n    rqsort_arg = arg;\n    rqsort_cmp = cmp;\n    qsort(base, nmemb, size, rqsort_cmp2);\n}\n\n#endif\n\n#else\n\ntypedef void (*exchange_f)(void *a, void *b, size_t size);\ntypedef int (*cmp_f)(const void *, const void *, void *opaque);\n\nstatic void exchange_bytes(void *a, void *b, size_t size) {\n    uint8_t *ap = (uint8_t *)a;\n    uint8_t *bp = (uint8_t *)b;\n\n    while (size-- != 0) {\n        uint8_t t = *ap;\n        *ap++ = *bp;\n        *bp++ = t;\n    }\n}\n\nstatic void exchange_one_byte(void *a, void *b, size_t size) {\n    uint8_t *ap = (uint8_t *)a;\n    uint8_t *bp = (uint8_t *)b;\n    uint8_t t = *ap;\n    *ap = *bp;\n    *bp = t;\n}\n\nstatic void exchange_int16s(void *a, void *b, size_t size) {\n    uint16_t *ap = (uint16_t *)a;\n    uint16_t *bp = (uint16_t *)b;\n\n    for (size /= sizeof(uint16_t); size-- != 0;) {\n        uint16_t t = *ap;\n        *ap++ = *bp;\n        *bp++ = t;\n    }\n}\n\nstatic void exchange_one_int16(void *a, void *b, size_t size) {\n    uint16_t *ap = (uint16_t *)a;\n    uint16_t *bp = (uint16_t *)b;\n    uint16_t t = *ap;\n    *ap = *bp;\n    *bp = t;\n}\n\nstatic void exchange_int32s(void *a, void *b, size_t size) {\n    uint32_t *ap = (uint32_t *)a;\n    uint32_t *bp = (uint32_t *)b;\n\n    for (size /= sizeof(uint32_t); size-- != 0;) {\n        uint32_t t = *ap;\n        *ap++ = *bp;\n        *bp++ = t;\n    }\n}\n\nstatic void exchange_one_int32(void *a, void *b, size_t size) {\n    uint32_t *ap = (uint32_t *)a;\n    uint32_t *bp = (uint32_t *)b;\n    uint32_t t = *ap;\n    *ap = *bp;\n    *bp = t;\n}\n\nstatic void exchange_int64s(void *a, void *b, size_t size) {\n    uint64_t *ap = (uint64_t *)a;\n    uint64_t *bp = (uint64_t *)b;\n\n    for (size /= sizeof(uint64_t); size-- != 0;) {\n        uint64_t t = *ap;\n        *ap++ = *bp;\n        *bp++ = t;\n    }\n}\n\nstatic void exchange_one_int64(void *a, void *b, size_t size) {\n    uint64_t *ap = (uint64_t *)a;\n    uint64_t *bp = (uint64_t *)b;\n    uint64_t t = *ap;\n    *ap = *bp;\n    *bp = t;\n}\n\nstatic void exchange_int128s(void *a, void *b, size_t size) {\n    uint64_t *ap = (uint64_t *)a;\n    uint64_t *bp = (uint64_t *)b;\n\n    for (size /= sizeof(uint64_t) * 2; size-- != 0; ap += 2, bp += 2) {\n        uint64_t t = ap[0];\n        uint64_t u = ap[1];\n        ap[0] = bp[0];\n        ap[1] = bp[1];\n        bp[0] = t;\n        bp[1] = u;\n    }\n}\n\nstatic void exchange_one_int128(void *a, void *b, size_t size) {\n    uint64_t *ap = (uint64_t *)a;\n    uint64_t *bp = (uint64_t *)b;\n    uint64_t t = ap[0];\n    uint64_t u = ap[1];\n    ap[0] = bp[0];\n    ap[1] = bp[1];\n    bp[0] = t;\n    bp[1] = u;\n}\n\nstatic inline exchange_f exchange_func(const void *base, size_t size) {\n    switch (((uintptr_t)base | (uintptr_t)size) & 15) {\n    case 0:\n        if (size == sizeof(uint64_t) * 2)\n            return exchange_one_int128;\n        else\n            return exchange_int128s;\n    case 8:\n        if (size == sizeof(uint64_t))\n            return exchange_one_int64;\n        else\n            return exchange_int64s;\n    case 4:\n    case 12:\n        if (size == sizeof(uint32_t))\n            return exchange_one_int32;\n        else\n            return exchange_int32s;\n    case 2:\n    case 6:\n    case 10:\n    case 14:\n        if (size == sizeof(uint16_t))\n            return exchange_one_int16;\n        else\n            return exchange_int16s;\n    default:\n        if (size == 1)\n            return exchange_one_byte;\n        else\n            return exchange_bytes;\n    }\n}\n\nstatic void heapsortx(void *base, size_t nmemb, size_t size, cmp_f cmp, void *opaque)\n{\n    uint8_t *basep = (uint8_t *)base;\n    size_t i, n, c, r;\n    exchange_f swap = exchange_func(base, size);\n\n    if (nmemb > 1) {\n        i = (nmemb / 2) * size;\n        n = nmemb * size;\n\n        while (i > 0) {\n            i -= size;\n            for (r = i; (c = r * 2 + size) < n; r = c) {\n                if (c < n - size && cmp(basep + c, basep + c + size, opaque) <= 0)\n                    c += size;\n                if (cmp(basep + r, basep + c, opaque) > 0)\n                    break;\n                swap(basep + r, basep + c, size);\n            }\n        }\n        for (i = n - size; i > 0; i -= size) {\n            swap(basep, basep + i, size);\n\n            for (r = 0; (c = r * 2 + size) < i; r = c) {\n                if (c < i - size && cmp(basep + c, basep + c + size, opaque) <= 0)\n                    c += size;\n                if (cmp(basep + r, basep + c, opaque) > 0)\n                    break;\n                swap(basep + r, basep + c, size);\n            }\n        }\n    }\n}\n\nstatic inline void *med3(void *a, void *b, void *c, cmp_f cmp, void *opaque)\n{\n    return cmp(a, b, opaque) < 0 ?\n        (cmp(b, c, opaque) < 0 ? b : (cmp(a, c, opaque) < 0 ? c : a )) :\n        (cmp(b, c, opaque) > 0 ? b : (cmp(a, c, opaque) < 0 ? a : c ));\n}\n\n/* pointer based version with local stack and insertion sort threshhold */\nvoid rqsort(void *base, size_t nmemb, size_t size, cmp_f cmp, void *opaque)\n{\n    struct { uint8_t *base; size_t count; int depth; } stack[50], *sp = stack;\n    uint8_t *ptr, *pi, *pj, *plt, *pgt, *top, *m;\n    size_t m4, i, lt, gt, span, span2;\n    int c, depth;\n    exchange_f swap = exchange_func(base, size);\n    exchange_f swap_block = exchange_func(base, size | 128);\n\n    if (nmemb < 2 || size <= 0)\n        return;\n\n    sp->base = (uint8_t *)base;\n    sp->count = nmemb;\n    sp->depth = 0;\n    sp++;\n\n    while (sp > stack) {\n        sp--;\n        ptr = sp->base;\n        nmemb = sp->count;\n        depth = sp->depth;\n\n        while (nmemb > 6) {\n            if (++depth > 50) {\n                /* depth check to ensure worst case logarithmic time */\n                heapsortx(ptr, nmemb, size, cmp, opaque);\n                nmemb = 0;\n                break;\n            }\n            /* select median of 3 from 1/4, 1/2, 3/4 positions */\n            /* should use median of 5 or 9? */\n            m4 = (nmemb >> 2) * size;\n            m = med3(ptr + m4, ptr + 2 * m4, ptr + 3 * m4, cmp, opaque);\n            swap(ptr, m, size);  /* move the pivot to the start or the array */\n            i = lt = 1;\n            pi = plt = ptr + size;\n            gt = nmemb;\n            pj = pgt = top = ptr + nmemb * size;\n            for (;;) {\n                while (pi < pj && (c = cmp(ptr, pi, opaque)) >= 0) {\n                    if (c == 0) {\n                        swap(plt, pi, size);\n                        lt++;\n                        plt += size;\n                    }\n                    i++;\n                    pi += size;\n                }\n                while (pi < (pj -= size) && (c = cmp(ptr, pj, opaque)) <= 0) {\n                    if (c == 0) {\n                        gt--;\n                        pgt -= size;\n                        swap(pgt, pj, size);\n                    }\n                }\n                if (pi >= pj)\n                    break;\n                swap(pi, pj, size);\n                i++;\n                pi += size;\n            }\n            /* array has 4 parts:\n             * from 0 to lt excluded: elements identical to pivot\n             * from lt to pi excluded: elements smaller than pivot\n             * from pi to gt excluded: elements greater than pivot\n             * from gt to n excluded: elements identical to pivot\n             */\n            /* move elements identical to pivot in the middle of the array: */\n            /* swap values in ranges [0..lt[ and [i-lt..i[\n               swapping the smallest span between lt and i-lt is sufficient\n             */\n            span = plt - ptr;\n            span2 = pi - plt;\n            lt = i - lt;\n            if (span > span2)\n                span = span2;\n            swap_block(ptr, pi - span, span);\n            /* swap values in ranges [gt..top[ and [i..top-(top-gt)[\n               swapping the smallest span between top-gt and gt-i is sufficient\n             */\n            span = top - pgt;\n            span2 = pgt - pi;\n            pgt = top - span2;\n            gt = nmemb - (gt - i);\n            if (span > span2)\n                span = span2;\n            swap_block(pi, top - span, span);\n\n            /* now array has 3 parts:\n             * from 0 to lt excluded: elements smaller than pivot\n             * from lt to gt excluded: elements identical to pivot\n             * from gt to n excluded: elements greater than pivot\n             */\n            /* stack the larger segment and keep processing the smaller one\n               to minimize stack use for pathological distributions */\n            if (lt > nmemb - gt) {\n                sp->base = ptr;\n                sp->count = lt;\n                sp->depth = depth;\n                sp++;\n                ptr = pgt;\n                nmemb -= gt;\n            } else {\n                sp->base = pgt;\n                sp->count = nmemb - gt;\n                sp->depth = depth;\n                sp++;\n                nmemb = lt;\n            }\n        }\n        /* Use insertion sort for small fragments */\n        for (pi = ptr + size, top = ptr + nmemb * size; pi < top; pi += size) {\n            for (pj = pi; pj > ptr && cmp(pj - size, pj, opaque) > 0; pj -= size)\n                swap(pj, pj - size, size);\n        }\n    }\n}\n\n#endif\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/cutils.h",
    "content": "/*\n * C utilities\n * \n * Copyright (c) 2017 Fabrice Bellard\n * Copyright (c) 2018 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#ifndef CUTILS_H\n#define CUTILS_H\n\n#include <stdlib.h>\n#include <inttypes.h>\n\n#ifdef _MSC_VER\n\ntypedef struct timeval {\n    long    tv_sec;         /* seconds */\n    long    tv_usec;        /* microseconds */\n} timeval;\n\n#include <time.h>\n#include <windows.h>\n#include <intrin.h>\n#ifndef alloca\n#define alloca(s) _alloca(s)\n#endif\nint gettimeofday(struct timeval* tp, struct timezone* tzp);\n#else \n#include <sys/time.h>\n#endif\n\n/* set if CPU is big endian */\n#undef WORDS_BIGENDIAN\n\n#ifdef _MSC_VER\n#define likely(x)       (x)\n#define unlikely(x)     (x)\n#define force_inline __forceinline\n#define no_inline \n#define __maybe_unused \n#define __attribute__(x)\ntypedef intptr_t ssize_t;\n#else \n#define likely(x)       __builtin_expect(!!(x), 1)\n#define unlikely(x)     __builtin_expect(!!(x), 0)\n#define force_inline inline __attribute__((always_inline))\n#define no_inline __attribute__((noinline))\n#define __maybe_unused __attribute__((unused))\n#endif\n\n#define xglue(x, y) x ## y\n#define glue(x, y) xglue(x, y)\n#define stringify(s)    tostring(s)\n#define tostring(s)     #s\n\n#ifndef offsetof\n#define offsetof(type, field) ((size_t) &((type *)0)->field)\n#endif\n#ifndef countof\n#define countof(x) (sizeof(x) / sizeof((x)[0]))\n#endif\n\ntypedef int BOOL;\n\n#ifndef FALSE\nenum {\n    FALSE = 0,\n    TRUE = 1,\n};\n#endif\n\nvoid pstrcpy(char *buf, int buf_size, const char *str);\nchar *pstrcat(char *buf, int buf_size, const char *s);\nint strstart(const char *str, const char *val, const char **ptr);\nint has_suffix(const char *str, const char *suffix);\n\nstatic inline int max_int(int a, int b)\n{\n    if (a > b)\n        return a;\n    else\n        return b;\n}\n\nstatic inline int min_int(int a, int b)\n{\n    if (a < b)\n        return a;\n    else\n        return b;\n}\n\nstatic inline uint32_t max_uint32(uint32_t a, uint32_t b)\n{\n    if (a > b)\n        return a;\n    else\n        return b;\n}\n\nstatic inline uint32_t min_uint32(uint32_t a, uint32_t b)\n{\n    if (a < b)\n        return a;\n    else\n        return b;\n}\n\nstatic inline int64_t max_int64(int64_t a, int64_t b)\n{\n    if (a > b)\n        return a;\n    else\n        return b;\n}\n\nstatic inline int64_t min_int64(int64_t a, int64_t b)\n{\n    if (a < b)\n        return a;\n    else\n        return b;\n}\n\n/* WARNING: undefined if a = 0 */\nstatic inline int clz32(unsigned int a)\n{\n#ifdef _MSC_VER\n    unsigned long idx;\n    _BitScanReverse(&idx, a);\n    return 31 ^ idx;\n#else\n    return __builtin_clz(a);\n#endif\n}\n\n/* WARNING: undefined if a = 0 */\nstatic inline int clz64(uint64_t a)\n{\n#ifdef _MSC_VER\n    unsigned long where;\n    // BitScanReverse scans from MSB to LSB for first set bit.\n    // Returns 0 if no set bit is found.\n#if INTPTR_MAX >= INT64_MAX // 64-bit\n    if (_BitScanReverse64(&where, a))\n        return (int)(63 - where);\n#else\n  // Scan the high 32 bits.\n    if (_BitScanReverse(&where, (uint32_t)(a >> 32)))\n        return (int)(63 - (where + 32)); // Create a bit offset from the MSB.\n      // Scan the low 32 bits.\n    if (_BitScanReverse(&where, (uint32_t)(a)))\n        return (int)(63 - where);\n#endif\n    return 64; // Undefined Behavior.\n#else\n    return __builtin_clzll(a);\n#endif\n}\n\n/* WARNING: undefined if a = 0 */\nstatic inline int ctz32(unsigned int a)\n{\n#ifdef _MSC_VER\n    unsigned long idx;\n    _BitScanForward(&idx, a);\n    return 31 ^ idx;\n#else\n    return __builtin_ctz(a);\n#endif\n}\n\n/* WARNING: undefined if a = 0 */\nstatic inline int ctz64(uint64_t a)\n{\n#ifdef _MSC_VER\n    unsigned long where;\n    // Search from LSB to MSB for first set bit.\n    // Returns zero if no set bit is found.\n#if INTPTR_MAX >= INT64_MAX // 64-bit\n    if (_BitScanForward64(&where, a))\n        return (int)(where);\n#else\n  // Win32 doesn't have _BitScanForward64 so emulate it with two 32 bit calls.\n  // Scan the Low Word.\n    if (_BitScanForward(&where, (uint32_t)(a)))\n        return (int)(where);\n    // Scan the High Word.\n    if (_BitScanForward(&where, (uint32_t)(a >> 32)))\n        return (int)(where + 32); // Create a bit offset from the LSB.\n#endif\n    return 64;\n#else\n    return __builtin_ctzll(a);\n#endif\n}\n\nstruct __attribute__((packed)) packed_u64 {\n    uint64_t v;\n};\n\nstruct __attribute__((packed)) packed_u32 {\n    uint32_t v;\n};\n\nstruct __attribute__((packed)) packed_u16 {\n    uint16_t v;\n};\n\nstatic inline uint64_t get_u64(const uint8_t *tab)\n{\n    return ((const struct packed_u64 *)tab)->v;\n}\n\nstatic inline int64_t get_i64(const uint8_t *tab)\n{\n    return (int64_t)((const struct packed_u64 *)tab)->v;\n}\n\nstatic inline void put_u64(uint8_t *tab, uint64_t val)\n{\n    ((struct packed_u64 *)tab)->v = val;\n}\n\nstatic inline uint32_t get_u32(const uint8_t *tab)\n{\n    return ((const struct packed_u32 *)tab)->v;\n}\n\nstatic inline int32_t get_i32(const uint8_t *tab)\n{\n    return (int32_t)((const struct packed_u32 *)tab)->v;\n}\n\nstatic inline void put_u32(uint8_t *tab, uint32_t val)\n{\n    ((struct packed_u32 *)tab)->v = val;\n}\n\nstatic inline uint32_t get_u16(const uint8_t *tab)\n{\n    return ((const struct packed_u16 *)tab)->v;\n}\n\nstatic inline int32_t get_i16(const uint8_t *tab)\n{\n    return (int16_t)((const struct packed_u16 *)tab)->v;\n}\n\nstatic inline void put_u16(uint8_t *tab, uint16_t val)\n{\n    ((struct packed_u16 *)tab)->v = val;\n}\n\nstatic inline uint32_t get_u8(const uint8_t *tab)\n{\n    return *tab;\n}\n\nstatic inline int32_t get_i8(const uint8_t *tab)\n{\n    return (int8_t)*tab;\n}\n\nstatic inline void put_u8(uint8_t *tab, uint8_t val)\n{\n    *tab = val;\n}\n\nstatic inline uint16_t bswap16(uint16_t x)\n{\n    return (x >> 8) | (x << 8);\n}\n\nstatic inline uint32_t bswap32(uint32_t v)\n{\n    return ((v & 0xff000000) >> 24) | ((v & 0x00ff0000) >>  8) |\n        ((v & 0x0000ff00) <<  8) | ((v & 0x000000ff) << 24);\n}\n\nstatic inline uint64_t bswap64(uint64_t v)\n{\n    return ((v & ((uint64_t)0xff << (7 * 8))) >> (7 * 8)) | \n        ((v & ((uint64_t)0xff << (6 * 8))) >> (5 * 8)) | \n        ((v & ((uint64_t)0xff << (5 * 8))) >> (3 * 8)) | \n        ((v & ((uint64_t)0xff << (4 * 8))) >> (1 * 8)) | \n        ((v & ((uint64_t)0xff << (3 * 8))) << (1 * 8)) | \n        ((v & ((uint64_t)0xff << (2 * 8))) << (3 * 8)) | \n        ((v & ((uint64_t)0xff << (1 * 8))) << (5 * 8)) | \n        ((v & ((uint64_t)0xff << (0 * 8))) << (7 * 8));\n}\n\n/* XXX: should take an extra argument to pass slack information to the caller */\ntypedef void *DynBufReallocFunc(void *opaque, void *ptr, size_t size);\n\ntypedef struct DynBuf {\n    uint8_t *buf;\n    size_t size;\n    size_t allocated_size;\n    BOOL error; /* true if a memory allocation error occurred */\n    DynBufReallocFunc *realloc_func;\n    void *opaque; /* for realloc_func */\n} DynBuf;\n\nvoid dbuf_init(DynBuf *s);\nvoid dbuf_init2(DynBuf *s, void *opaque, DynBufReallocFunc *realloc_func);\nint dbuf_realloc(DynBuf *s, size_t new_size);\nint dbuf_write(DynBuf *s, size_t offset, const uint8_t *data, size_t len);\nint dbuf_put(DynBuf *s, const uint8_t *data, size_t len);\nint dbuf_put_self(DynBuf *s, size_t offset, size_t len);\nint dbuf_putc(DynBuf *s, uint8_t c);\nint dbuf_putstr(DynBuf *s, const char *str);\nstatic inline int dbuf_put_u16(DynBuf *s, uint16_t val)\n{\n    return dbuf_put(s, (uint8_t *)&val, 2);\n}\nstatic inline int dbuf_put_u32(DynBuf *s, uint32_t val)\n{\n    return dbuf_put(s, (uint8_t *)&val, 4);\n}\nstatic inline int dbuf_put_u64(DynBuf *s, uint64_t val)\n{\n    return dbuf_put(s, (uint8_t *)&val, 8);\n}\nint __attribute__((format(printf, 2, 3))) dbuf_printf(DynBuf *s,\n                                                      const char *fmt, ...);\nvoid dbuf_free(DynBuf *s);\nstatic inline BOOL dbuf_error(DynBuf *s) {\n    return s->error;\n}\nstatic inline void dbuf_set_error(DynBuf *s)\n{\n    s->error = TRUE;\n}\n\n#define UTF8_CHAR_LEN_MAX 6\n\nint unicode_to_utf8(uint8_t *buf, unsigned int c);\nint unicode_from_utf8(const uint8_t *p, int max_len, const uint8_t **pp);\n\nstatic inline int from_hex(int c)\n{\n    if (c >= '0' && c <= '9')\n        return c - '0';\n    else if (c >= 'A' && c <= 'F')\n        return c - 'A' + 10;\n    else if (c >= 'a' && c <= 'f')\n        return c - 'a' + 10;\n    else\n        return -1;\n}\n\nvoid rqsort(void *base, size_t nmemb, size_t size,\n            int (*cmp)(const void *, const void *, void *),\n            void *arg);\n\n#endif  /* CUTILS_H */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/doc/jsbignum.html",
    "content": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n<!-- Created by GNU Texinfo 6.1, http://www.gnu.org/software/texinfo/ -->\n<head>\n<title>Javascript Bignum Extensions</title>\n\n<meta name=\"description\" content=\"Javascript Bignum Extensions\">\n<meta name=\"keywords\" content=\"Javascript Bignum Extensions\">\n<meta name=\"resource-type\" content=\"document\">\n<meta name=\"distribution\" content=\"global\">\n<meta name=\"Generator\" content=\"makeinfo\">\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<link href=\"#SEC_Contents\" rel=\"contents\" title=\"Table of Contents\">\n<style type=\"text/css\">\n<!--\na.summary-letter {text-decoration: none}\nblockquote.indentedblock {margin-right: 0em}\nblockquote.smallindentedblock {margin-right: 0em; font-size: smaller}\nblockquote.smallquotation {font-size: smaller}\ndiv.display {margin-left: 3.2em}\ndiv.example {margin-left: 3.2em}\ndiv.lisp {margin-left: 3.2em}\ndiv.smalldisplay {margin-left: 3.2em}\ndiv.smallexample {margin-left: 3.2em}\ndiv.smalllisp {margin-left: 3.2em}\nkbd {font-style: oblique}\npre.display {font-family: inherit}\npre.format {font-family: inherit}\npre.menu-comment {font-family: serif}\npre.menu-preformatted {font-family: serif}\npre.smalldisplay {font-family: inherit; font-size: smaller}\npre.smallexample {font-size: smaller}\npre.smallformat {font-family: inherit; font-size: smaller}\npre.smalllisp {font-size: smaller}\nspan.nolinebreak {white-space: nowrap}\nspan.roman {font-family: initial; font-weight: normal}\nspan.sansserif {font-family: sans-serif; font-weight: normal}\nul.no-bullet {list-style: none}\n-->\n</style>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n\n\n</head>\n\n<body lang=\"en\">\n<h1 class=\"settitle\" align=\"center\">Javascript Bignum Extensions</h1>\n\n<a name=\"SEC_Contents\"></a>\n<h2 class=\"contents-heading\">Table of Contents</h2>\n\n<div class=\"contents\">\n<ul class=\"no-bullet\">\n<li><a name=\"toc-Introduction\" href=\"#Introduction\">1 Introduction</a></li>\n<li><a name=\"toc-Operator-overloading\" href=\"#Operator-overloading\">2 Operator overloading</a></li>\n<li><a name=\"toc-BigInt-extensions\" href=\"#BigInt-extensions\">3 BigInt extensions</a></li>\n<li><a name=\"toc-BigFloat\" href=\"#BigFloat\">4 BigFloat</a>\n<ul class=\"no-bullet\">\n  <li><a name=\"toc-Introduction-1\" href=\"#Introduction-1\">4.1 Introduction</a></li>\n  <li><a name=\"toc-Floating-point-rounding\" href=\"#Floating-point-rounding\">4.2 Floating point rounding</a></li>\n  <li><a name=\"toc-Operators\" href=\"#Operators\">4.3 Operators</a></li>\n  <li><a name=\"toc-BigFloat-literals\" href=\"#BigFloat-literals\">4.4 BigFloat literals</a></li>\n  <li><a name=\"toc-Builtin-Object-changes\" href=\"#Builtin-Object-changes\">4.5 Builtin Object changes</a>\n  <ul class=\"no-bullet\">\n    <li><a name=\"toc-BigFloat-function\" href=\"#BigFloat-function\">4.5.1 <code>BigFloat</code> function</a></li>\n    <li><a name=\"toc-BigFloat_002eprototype\" href=\"#BigFloat_002eprototype\">4.5.2 <code>BigFloat.prototype</code></a></li>\n    <li><a name=\"toc-BigFloatEnv-constructor\" href=\"#BigFloatEnv-constructor\">4.5.3 <code>BigFloatEnv</code> constructor</a></li>\n  </ul></li>\n</ul></li>\n<li><a name=\"toc-BigDecimal\" href=\"#BigDecimal\">5 BigDecimal</a>\n<ul class=\"no-bullet\">\n  <li><a name=\"toc-Operators-1\" href=\"#Operators-1\">5.1 Operators</a></li>\n  <li><a name=\"toc-BigDecimal-literals\" href=\"#BigDecimal-literals\">5.2 BigDecimal literals</a></li>\n  <li><a name=\"toc-Builtin-Object-changes-1\" href=\"#Builtin-Object-changes-1\">5.3 Builtin Object changes</a>\n  <ul class=\"no-bullet\">\n    <li><a name=\"toc-The-BigDecimal-function_002e\" href=\"#The-BigDecimal-function_002e\">5.3.1 The <code>BigDecimal</code> function.</a></li>\n    <li><a name=\"toc-Properties-of-the-BigDecimal-object\" href=\"#Properties-of-the-BigDecimal-object\">5.3.2 Properties of the <code>BigDecimal</code> object</a></li>\n    <li><a name=\"toc-Properties-of-the-BigDecimal_002eprototype-object\" href=\"#Properties-of-the-BigDecimal_002eprototype-object\">5.3.3 Properties of the <code>BigDecimal.prototype</code> object</a></li>\n  </ul></li>\n</ul></li>\n<li><a name=\"toc-Math-mode\" href=\"#Math-mode\">6 Math mode</a></li>\n\n</ul>\n</div>\n\n\n<a name=\"Introduction\"></a>\n<h2 class=\"chapter\">1 Introduction</h2>\n\n<p>The Bignum extensions add the following features to the Javascript\nlanguage while being 100% backward compatible:\n</p>\n<ul>\n<li> Operator overloading with a dispatch logic inspired from the proposal available at <a href=\"https://github.com/tc39/proposal-operator-overloading/\">https://github.com/tc39/proposal-operator-overloading/</a>.\n\n</li><li> Arbitrarily large floating point numbers (<code>BigFloat</code>) in base 2 using the IEEE 754 semantics.\n\n</li><li> Arbitrarily large floating point numbers (<code>BigDecimal</code>) in base 10 based on the proposal available at\n<a href=\"https://github.com/littledan/proposal-bigdecimal\">https://github.com/littledan/proposal-bigdecimal</a>.\n\n</li><li> <code>math</code> mode: arbitrarily large integers and floating point numbers are available by default. The integer division and power can be overloaded for example to return a fraction. The modulo operator (<code>%</code>) is defined as the Euclidian\nremainder. <code>^</code> is an alias to the power operator\n(<code>**</code>). <code>^^</code> is used as the exclusive or operator.\n\n</li></ul>\n\n<p>The extensions are independent from each other except the <code>math</code>\nmode which relies on BigFloat and operator overloading.\n</p>\n<a name=\"Operator-overloading\"></a>\n<h2 class=\"chapter\">2 Operator overloading</h2>\n\n<p>Operator overloading is inspired from the proposal available at\n<a href=\"https://github.com/tc39/proposal-operator-overloading/\">https://github.com/tc39/proposal-operator-overloading/</a>. It\nimplements the same dispatch logic but finds the operator sets by\nlooking at the <code>Symbol.operatorSet</code> property in the objects. The\nchanges were done in order to simplify the implementation.\n</p>\n<p>More precisely, the following modifications were made:\n</p>\n<ul>\n<li> <code>with operators from</code> is not supported. Operator overloading is always enabled.\n\n</li><li> The dispatch is not based on a static <code>[[OperatorSet]]</code> field in all instances. Instead, a dynamic lookup of the <code>Symbol.operatorSet</code> property is done. This property is typically added in the prototype of each object.\n\n</li><li> <code>Operators.create(...dictionaries)</code> is used to create a new OperatorSet object. The <code>Operators</code> function is supported as an helper to be closer to the TC39 proposal.\n\n</li><li> <code>[]</code> cannot be overloaded.\n\n</li><li> In math mode, the BigInt division and power operators can be overloaded with <code>Operators.updateBigIntOperators(dictionary)</code>.\n\n</li></ul>\n\n<a name=\"BigInt-extensions\"></a>\n<h2 class=\"chapter\">3 BigInt extensions</h2>\n\n<p>A few properties are added to the BigInt object:\n</p>\n<dl compact=\"compact\">\n<dt><code>tdiv(a, b)</code></dt>\n<dd><p>Return <em>trunc(a/b)</em>. <code>b = 0</code> raises a RangeError\nexception.\n</p>\n</dd>\n<dt><code>fdiv(a, b)</code></dt>\n<dd><p>Return <em>\\lfloor a/b \\rfloor</em>. <code>b = 0</code> raises a RangeError\nexception.\n</p>\n</dd>\n<dt><code>cdiv(a, b)</code></dt>\n<dd><p>Return <em>\\lceil a/b \\rceil</em>. <code>b = 0</code> raises a RangeError\nexception.\n</p>\n</dd>\n<dt><code>ediv(a, b)</code></dt>\n<dd><p>Return <em>sgn(b) \\lfloor a/{|b|} \\rfloor</em> (Euclidian\ndivision). <code>b = 0</code> raises a RangeError exception.\n</p>\n</dd>\n<dt><code>tdivrem(a, b)</code></dt>\n<dt><code>fdivrem(a, b)</code></dt>\n<dt><code>cdivrem(a, b)</code></dt>\n<dt><code>edivrem(a, b)</code></dt>\n<dd><p>Return an array of two elements. The first element is the quotient,\nthe second is the remainder. The same rounding is done as the\ncorresponding division operation.\n</p>\n</dd>\n<dt><code>sqrt(a)</code></dt>\n<dd><p>Return <em>\\lfloor \\sqrt(a) \\rfloor</em>. A RangeError exception is\nraised if <em>a &lt; 0</em>.\n</p>\n</dd>\n<dt><code>sqrtrem(a)</code></dt>\n<dd><p>Return an array of two elements. The first element is <em>\\lfloor\n\\sqrt{a} \\rfloor</em>. The second element is <em>a-\\lfloor \\sqrt{a}\n\\rfloor^2</em>. A RangeError exception is raised if <em>a &lt; 0</em>.\n</p>\n</dd>\n<dt><code>floorLog2(a)</code></dt>\n<dd><p>Return -1 if <em>a \\leq 0</em> otherwise return <em>\\lfloor \\log2(a) \\rfloor</em>.\n</p>\n</dd>\n<dt><code>ctz(a)</code></dt>\n<dd><p>Return the number of trailing zeros in the two&rsquo;s complement binary representation of a. Return -1 if <em>a=0</em>.\n</p>\n</dd>\n</dl>\n\n<a name=\"BigFloat\"></a>\n<h2 class=\"chapter\">4 BigFloat</h2>\n\n<a name=\"Introduction-1\"></a>\n<h3 class=\"section\">4.1 Introduction</h3>\n\n<p>This extension adds the <code>BigFloat</code> primitive type. The\n<code>BigFloat</code> type represents floating point numbers in base 2\nwith the IEEE 754 semantics. A floating\npoint number is represented as a sign, mantissa and exponent. The\nspecial values <code>NaN</code>, <code>+/-Infinity</code>, <code>+0</code> and <code>-0</code>\nare supported. The mantissa and exponent can have any bit length with\nan implementation specific minimum and maximum.\n</p>\n<a name=\"Floating-point-rounding\"></a>\n<h3 class=\"section\">4.2 Floating point rounding</h3>\n\n<p>Each floating point operation operates with infinite precision and\nthen rounds the result according to the specified floating point\nenvironment (<code>BigFloatEnv</code> object). The status flags of the\nenvironment are also set according to the result of the operation.\n</p>\n<p>If no floating point environment is provided, the global floating\npoint environment is used.\n</p>\n<p>The rounding mode of the global floating point environment is always\n<code>RNDN</code> (&ldquo;round to nearest with ties to even&rdquo;)<a name=\"DOCF1\" href=\"#FOOT1\"><sup>1</sup></a>. The status flags of the global environment cannot be\nread<a name=\"DOCF2\" href=\"#FOOT2\"><sup>2</sup></a>. The precision of the global environment is\n<code>BigFloatEnv.prec</code>. The number of exponent bits of the global\nenvironment is <code>BigFloatEnv.expBits</code>. The global environment\nsubnormal flag is set to <code>true</code>.\n</p>\n<p>For example, <code>prec = 53</code> and <code> expBits = 11</code> exactly give\nthe same precision as the IEEE 754 64 bit floating point format. The\ndefault precision is <code>prec = 113</code> and <code> expBits = 15</code> (IEEE\n754 128 bit floating point format).\n</p>\n<p>The global floating point environment can only be modified temporarily\nwhen calling a function (see <code>BigFloatEnv.setPrec</code>). Hence a\nfunction can change the global floating point environment for its\ncallees but not for its caller.\n</p>\n<a name=\"Operators\"></a>\n<h3 class=\"section\">4.3 Operators</h3>\n\n<p>The builtin operators are extended so that a BigFloat is returned if\nat least one operand is a BigFloat. The computations are always done\nwith infinite precision and rounded according to the global floating\npoint environment.\n</p>\n<p><code>typeof</code> applied on a <code>BigFloat</code> returns <code>bigfloat</code>.\n</p>\n<p>BigFloat can be compared with all the other numeric types and the\nresult follows the expected mathematical relations.\n</p>\n<p>However, since BigFloat and Number are different types they are never\nequal when using the strict comparison operators (e.g. <code>0.0 ===\n0.0l</code> is false).\n</p>\n<a name=\"BigFloat-literals\"></a>\n<h3 class=\"section\">4.4 BigFloat literals</h3>\n\n<p>BigFloat literals are floating point numbers with a trailing <code>l</code>\nsuffix. BigFloat literals have an infinite precision. They are rounded\naccording to the global floating point environment when they are\nevaluated.<a name=\"DOCF3\" href=\"#FOOT3\"><sup>3</sup></a>\n</p>\n<a name=\"Builtin-Object-changes\"></a>\n<h3 class=\"section\">4.5 Builtin Object changes</h3>\n\n<a name=\"BigFloat-function\"></a>\n<h4 class=\"subsection\">4.5.1 <code>BigFloat</code> function</h4>\n\n<p>The <code>BigFloat</code> function cannot be invoked as a constructor. When\ninvoked as a function: the parameter is converted to a primitive\ntype. If the result is a numeric type, it is converted to BigFloat\nwithout rounding. If the result is a string, it is converted to\nBigFloat using the precision of the global floating point environment.\n</p>\n<p><code>BigFloat</code> properties:\n</p>\n<dl compact=\"compact\">\n<dt><code>LN2</code></dt>\n<dt><code>PI</code></dt>\n<dd><p>Getter. Return the value of the corresponding mathematical constant\nrounded to nearest, ties to even with the current global\nprecision. The constant values are cached for small precisions.\n</p>\n</dd>\n<dt><code>MIN_VALUE</code></dt>\n<dt><code>MAX_VALUE</code></dt>\n<dt><code>EPSILON</code></dt>\n<dd><p>Getter. Return the minimum, maximum and epsilon <code>BigFloat</code> values\n(same definition as the corresponding <code>Number</code> constants).\n</p>\n</dd>\n<dt><code>fpRound(a[, e])</code></dt>\n<dd><p>Round the floating point number <code>a</code> according to the floating\npoint environment <code>e</code> or the global environment if <code>e</code> is\nundefined.\n</p>\n</dd>\n<dt><code>parseFloat(a[, radix[, e]])</code></dt>\n<dd><p>Parse the string <code>a</code> as a floating point number in radix\n<code>radix</code>. The radix is 0 (default) or from 2 to 36. The radix 0\nmeans radix 10 unless there is a hexadecimal or binary prefix. The\nresult is rounded according to the floating point environment <code>e</code>\nor the global environment if <code>e</code> is undefined.\n</p>\n</dd>\n<dt><code>isFinite(a)</code></dt>\n<dd><p>Return true if <code>a</code> is a finite bigfloat.\n</p>\n</dd>\n<dt><code>isNaN(a)</code></dt>\n<dd><p>Return true if <code>a</code> is a NaN bigfloat.\n</p>\n</dd>\n<dt><code>add(a, b[, e])</code></dt>\n<dt><code>sub(a, b[, e])</code></dt>\n<dt><code>mul(a, b[, e])</code></dt>\n<dt><code>div(a, b[, e])</code></dt>\n<dd><p>Perform the specified floating point operation and round the floating\npoint number <code>a</code> according to the floating point environment\n<code>e</code> or the global environment if <code>e</code> is undefined. If\n<code>e</code> is specified, the floating point status flags are updated.\n</p>\n</dd>\n<dt><code>floor(x)</code></dt>\n<dt><code>ceil(x)</code></dt>\n<dt><code>round(x)</code></dt>\n<dt><code>trunc(x)</code></dt>\n<dd><p>Round to an integer. No additional rounding is performed.\n</p>\n</dd>\n<dt><code>abs(x)</code></dt>\n<dd><p>Return the absolute value of x. No additional rounding is performed.\n</p>\n</dd>\n<dt><code>fmod(x, y[, e])</code></dt>\n<dt><code>remainder(x, y[, e])</code></dt>\n<dd><p>Floating point remainder. The quotient is truncated to zero (fmod) or\nto the nearest integer with ties to even (remainder). <code>e</code> is an\noptional floating point environment.\n</p>\n</dd>\n<dt><code>sqrt(x[, e])</code></dt>\n<dd><p>Square root. Return a rounded floating point number. <code>e</code> is an\noptional floating point environment.\n</p>\n</dd>\n<dt><code>sin(x[, e])</code></dt>\n<dt><code>cos(x[, e])</code></dt>\n<dt><code>tan(x[, e])</code></dt>\n<dt><code>asin(x[, e])</code></dt>\n<dt><code>acos(x[, e])</code></dt>\n<dt><code>atan(x[, e])</code></dt>\n<dt><code>atan2(x, y[, e])</code></dt>\n<dt><code>exp(x[, e])</code></dt>\n<dt><code>log(x[, e])</code></dt>\n<dt><code>pow(x, y[, e])</code></dt>\n<dd><p>Transcendental operations. Return a rounded floating point\nnumber. <code>e</code> is an optional floating point environment.\n</p>\n</dd>\n</dl>\n\n<a name=\"BigFloat_002eprototype\"></a>\n<h4 class=\"subsection\">4.5.2 <code>BigFloat.prototype</code></h4>\n\n<p>The following properties are modified:\n</p>\n<dl compact=\"compact\">\n<dt><code>valueOf()</code></dt>\n<dd><p>Return the bigfloat primitive value corresponding to <code>this</code>.\n</p>\n</dd>\n<dt><code>toString(radix)</code></dt>\n<dd>\n<p>For floating point numbers:\n</p>\n<ul>\n<li> If the radix is a power of two, the conversion is done with infinite\nprecision.\n</li><li> Otherwise, the number is rounded to nearest with ties to even using\nthe global precision. It is then converted to string using the minimum\nnumber of digits so that its conversion back to a floating point using\nthe global precision and round to nearest gives the same number. \n\n</li></ul>\n\n<p>The exponent letter is <code>e</code> for base 10, <code>p</code> for bases 2, 8,\n16 with a binary exponent and <code>@</code> for the other bases.\n</p>\n</dd>\n<dt><code>toPrecision(p, rnd_mode = BigFloatEnv.RNDNA, radix = 10)</code></dt>\n<dt><code>toFixed(p, rnd_mode = BigFloatEnv.RNDNA, radix = 10)</code></dt>\n<dt><code>toExponential(p, rnd_mode = BigFloatEnv.RNDNA, radix = 10)</code></dt>\n<dd><p>Same semantics as the corresponding <code>Number</code> functions with\nBigFloats. There is no limit on the accepted precision <code>p</code>. The\nrounding mode and radix can be optionally specified. The radix must be\nbetween 2 and 36.\n</p>\n</dd>\n</dl>\n\n<a name=\"BigFloatEnv-constructor\"></a>\n<h4 class=\"subsection\">4.5.3 <code>BigFloatEnv</code> constructor</h4>\n\n<p>The <code>BigFloatEnv([p, [,rndMode]]</code> constructor cannot be invoked as a\nfunction. The floating point environment contains:\n</p>\n<ul>\n<li> the mantissa precision in bits\n\n</li><li> the exponent size in bits assuming an IEEE 754 representation;\n\n</li><li> the subnormal flag (if true, subnormal floating point numbers can\nbe generated by the floating point operations).\n\n</li><li> the rounding mode\n\n</li><li> the floating point status. The status flags can only be set by the floating point operations. They can be reset with <code>BigFloatEnv.prototype.clearStatus()</code> or with the various status flag setters.\n\n</li></ul>\n\n<p><code>new BigFloatEnv([p, [,rndMode]]</code> creates a new floating point\nenvironment. The status flags are reset. If no parameter is given the\nprecision, exponent bits and subnormal flags are copied from the\nglobal floating point environment. Otherwise, the precision is set to\n<code>p</code>, the number of exponent bits is set to <code>expBitsMax</code> and the\nsubnormal flags is set to <code>false</code>. If <code>rndMode</code> is\n<code>undefined</code>, the rounding mode is set to <code>RNDN</code>.\n</p>\n<p><code>BigFloatEnv</code> properties:\n</p>\n<dl compact=\"compact\">\n<dt><code>prec</code></dt>\n<dd><p>Getter. Return the precision in bits of the global floating point\nenvironment. The initial value is <code>113</code>.\n</p>\n</dd>\n<dt><code>expBits</code></dt>\n<dd><p>Getter. Return the exponent size in bits of the global floating point\nenvironment assuming an IEEE 754 representation. The initial value is\n<code>15</code>.\n</p>\n</dd>\n<dt><code>setPrec(f, p[, e])</code></dt>\n<dd><p>Set the precision of the global floating point environment to <code>p</code>\nand the exponent size to <code>e</code> then call the function\n<code>f</code>. Then the Float precision and exponent size are reset to\ntheir precious value and the return value of <code>f</code> is returned (or\nan exception is raised if <code>f</code> raised an exception). If <code>e</code>\nis <code>undefined</code> it is set to <code>BigFloatEnv.expBitsMax</code>.\n</p>\n</dd>\n<dt><code>precMin</code></dt>\n<dd><p>Read-only integer. Return the minimum allowed precision. Must be at least 2.\n</p>\n</dd>\n<dt><code>precMax</code></dt>\n<dd><p>Read-only integer. Return the maximum allowed precision. Must be at least 113.\n</p>\n</dd>\n<dt><code>expBitsMin</code></dt>\n<dd><p>Read-only integer. Return the minimum allowed exponent size in\nbits. Must be at least 3.\n</p>\n</dd>\n<dt><code>expBitsMax</code></dt>\n<dd><p>Read-only integer. Return the maximum allowed exponent size in\nbits. Must be at least 15.\n</p>\n</dd>\n<dt><code>RNDN</code></dt>\n<dd><p>Read-only integer. Round to nearest, with ties to even rounding mode.\n</p>\n</dd>\n<dt><code>RNDZ</code></dt>\n<dd><p>Read-only integer. Round to zero rounding mode.\n</p>\n</dd>\n<dt><code>RNDD</code></dt>\n<dd><p>Read-only integer. Round to -Infinity rounding mode.\n</p>\n</dd>\n<dt><code>RNDU</code></dt>\n<dd><p>Read-only integer. Round to +Infinity rounding mode.\n</p>\n</dd>\n<dt><code>RNDNA</code></dt>\n<dd><p>Read-only integer. Round to nearest, with ties away from zero rounding mode.\n</p>\n</dd>\n<dt><code>RNDA</code></dt>\n<dd><p>Read-only integer. Round away from zero rounding mode.\n</p>\n</dd>\n<dt><code>RNDF<a name=\"DOCF4\" href=\"#FOOT4\"><sup>4</sup></a></code></dt>\n<dd><p>Read-only integer. Faithful rounding mode. The result is\nnon-deterministically rounded to -Infinity or +Infinity. This rounding\nmode usually gives a faster and deterministic running time for the\nfloating point operations.\n</p>\n</dd>\n</dl>\n\n<p><code>BigFloatEnv.prototype</code> properties:\n</p>\n<dl compact=\"compact\">\n<dt><code>prec</code></dt>\n<dd><p>Getter and setter (Integer). Return or set the precision in bits.\n</p>\n</dd>\n<dt><code>expBits</code></dt>\n<dd><p>Getter and setter (Integer). Return or set the exponent size in bits\nassuming an IEEE 754 representation.\n</p>\n</dd>\n<dt><code>rndMode</code></dt>\n<dd><p>Getter and setter (Integer). Return or set the rounding mode.\n</p>\n</dd>\n<dt><code>subnormal</code></dt>\n<dd><p>Getter and setter (Boolean). subnormal flag. It is false when\n<code>expBits = expBitsMax</code>.\n</p>\n</dd>\n<dt><code>clearStatus()</code></dt>\n<dd><p>Clear the status flags.\n</p>\n</dd>\n<dt><code>invalidOperation</code></dt>\n<dt><code>divideByZero</code></dt>\n<dt><code>overflow</code></dt>\n<dt><code>underflow</code></dt>\n<dt><code>inexact</code></dt>\n<dd><p>Getter and setter (Boolean). Status flags.\n</p>\n</dd>\n</dl>\n\n<a name=\"BigDecimal\"></a>\n<h2 class=\"chapter\">5 BigDecimal</h2>\n\n<p>This extension adds the <code>BigDecimal</code> primitive type. The\n<code>BigDecimal</code> type represents floating point numbers in base\n10. It is inspired from the proposal available at\n<a href=\"https://github.com/littledan/proposal-bigdecimal\">https://github.com/littledan/proposal-bigdecimal</a>.\n</p>\n<p>The <code>BigDecimal</code> floating point numbers are always normalized and\nfinite. There is no concept of <code>-0</code>, <code>Infinity</code> or\n<code>NaN</code>. By default, all the computations are done with infinite\nprecision.\n</p>\n<a name=\"Operators-1\"></a>\n<h3 class=\"section\">5.1 Operators</h3>\n\n<p>The following builtin operators support BigDecimal:\n</p>\n<dl compact=\"compact\">\n<dt><code>+</code></dt>\n<dt><code>-</code></dt>\n<dt><code>*</code></dt>\n<dd><p>Both operands must be BigDecimal. The result is computed with infinite\nprecision.\n</p></dd>\n<dt><code>%</code></dt>\n<dd><p>Both operands must be BigDecimal. The result is computed with infinite\nprecision. A range error is throws in case of division by zero.\n</p>\n</dd>\n<dt><code>/</code></dt>\n<dd><p>Both operands must be BigDecimal. A range error is throws in case of\ndivision by zero or if the result cannot be represented with infinite\nprecision (use <code>BigDecimal.div</code> to specify the rounding).\n</p>\n</dd>\n<dt><code>**</code></dt>\n<dd><p>Both operands must be BigDecimal. The exponent must be a positive\ninteger. The result is computed with infinite precision.\n</p>\n</dd>\n<dt><code>===</code></dt>\n<dd><p>When one of the operand is a BigDecimal, return true if both operands\nare a BigDecimal and if they are equal.\n</p>\n</dd>\n<dt><code>==</code></dt>\n<dt><code>!=</code></dt>\n<dt><code>&lt;=</code></dt>\n<dt><code>&gt;=</code></dt>\n<dt><code>&lt;</code></dt>\n<dt><code>&gt;</code></dt>\n<dd>\n<p>Numerical comparison. When one of the operand is not a BigDecimal, it is\nconverted to BigDecimal by using ToString(). Hence comparisons between\nNumber and BigDecimal do not use the exact mathematical value of the\nNumber value.\n</p>\n</dd>\n</dl>\n\n<a name=\"BigDecimal-literals\"></a>\n<h3 class=\"section\">5.2 BigDecimal literals</h3>\n\n<p>BigDecimal literals are decimal floating point numbers with a trailing\n<code>m</code> suffix.\n</p>\n<a name=\"Builtin-Object-changes-1\"></a>\n<h3 class=\"section\">5.3 Builtin Object changes</h3>\n\n<a name=\"The-BigDecimal-function_002e\"></a>\n<h4 class=\"subsection\">5.3.1 The <code>BigDecimal</code> function.</h4>\n\n<p>It returns <code>0m</code> if no parameter is provided. Otherwise the first\nparameter is converted to a bigdecimal by using ToString(). Hence\nNumber values are not converted to their exact numerical value as\nBigDecimal.\n</p>\n<a name=\"Properties-of-the-BigDecimal-object\"></a>\n<h4 class=\"subsection\">5.3.2 Properties of the <code>BigDecimal</code> object</h4>\n\n<dl compact=\"compact\">\n<dt><code>add(a, b[, e])</code></dt>\n<dt><code>sub(a, b[, e])</code></dt>\n<dt><code>mul(a, b[, e])</code></dt>\n<dt><code>div(a, b[, e])</code></dt>\n<dt><code>mod(a, b[, e])</code></dt>\n<dt><code>sqrt(a, e)</code></dt>\n<dt><code>round(a, e)</code></dt>\n<dd><p>Perform the specified floating point operation and round the floating\npoint result according to the rounding object <code>e</code>. If the\nrounding object is not present, the operation is executed with\ninfinite precision.\n</p>\n<p>For <code>div</code>, a <code>RangeError</code> exception is thrown in case of\ndivision by zero or if the result cannot be represented with infinite\nprecision if no rounding object is present.\n</p>\n<p>For <code>sqrt</code>, a range error is thrown if <code>a</code> is less than\nzero.\n</p>\n<p>The rounding object must contain the following properties:\n<code>roundingMode</code> is a string specifying the rounding mode\n(<code>&quot;floor&quot;</code>, <code>&quot;ceiling&quot;</code>, <code>&quot;down&quot;</code>, <code>&quot;up&quot;</code>,\n<code>&quot;half-even&quot;</code>, <code>&quot;half-up&quot;</code>). Either\n<code>maximumSignificantDigits</code> or <code>maximumFractionDigits</code> must\nbe present to specify respectively the number of significant digits\n(must be &gt;= 1) or the number of digits after the decimal point (must\nbe &gt;= 0).\n</p>\n</dd>\n</dl>\n\n<a name=\"Properties-of-the-BigDecimal_002eprototype-object\"></a>\n<h4 class=\"subsection\">5.3.3 Properties of the <code>BigDecimal.prototype</code> object</h4>\n\n<dl compact=\"compact\">\n<dt><code>valueOf()</code></dt>\n<dd><p>Return the bigdecimal primitive value corresponding to <code>this</code>.\n</p>\n</dd>\n<dt><code>toString()</code></dt>\n<dd><p>Convert <code>this</code> to a string with infinite precision in base 10.\n</p>\n</dd>\n<dt><code>toPrecision(p, rnd_mode = &quot;half-up&quot;)</code></dt>\n<dt><code>toFixed(p, rnd_mode = &quot;half-up&quot;)</code></dt>\n<dt><code>toExponential(p, rnd_mode = &quot;half-up&quot;)</code></dt>\n<dd><p>Convert the BigDecimal <code>this</code> to string with the specified\nprecision <code>p</code>. There is no limit on the accepted precision\n<code>p</code>. The rounding mode can be optionally\nspecified. <code>toPrecision</code> outputs either in decimal fixed notation\nor in decimal exponential notation with a <code>p</code> digits of\nprecision.  <code>toExponential</code> outputs in decimal exponential\nnotation with <code>p</code> digits after the decimal point. <code>toFixed</code>\noutputs in decimal notation with <code>p</code> digits after the decimal\npoint.\n</p>\n</dd>\n</dl>\n\n<a name=\"Math-mode\"></a>\n<h2 class=\"chapter\">6 Math mode</h2>\n\n<p>A new <em>math mode</em> is enabled with the <code>&quot;use math&quot;</code>\ndirective. It propagates the same way as the <em>strict mode</em>. It is\ndesigned so that arbitrarily large integers and floating point numbers\nare available by default. In order to minimize the number of changes\nin the Javascript semantics, integers are represented either as Number\nor BigInt depending on their magnitude. Floating point numbers are\nalways represented as BigFloat.\n</p>\n<p>The following changes are made to the Javascript semantics:\n</p>\n<ul>\n<li> Floating point literals (i.e. number with a decimal point or an exponent) are <code>BigFloat</code> by default (i.e. a <code>l</code> suffix is implied). Hence <code>typeof 1.0 === &quot;bigfloat&quot;</code>.\n\n</li><li> Integer literals (i.e. numbers without a decimal point or an exponent) with or without the <code>n</code> suffix are <code>BigInt</code> if their value cannot be represented as a safe integer. A safe integer is defined as a integer whose absolute value is smaller or equal to <code>2**53-1</code>. Hence <code>typeof 1 === &quot;number &quot;</code>, <code>typeof 1n === &quot;number&quot;</code> but <code>typeof 9007199254740992 === &quot;bigint&quot; </code>.\n\n</li><li> All the bigint builtin operators and functions are modified so that their result is returned as a Number if it is a safe integer. Otherwise the result stays a BigInt.\n\n</li><li> The builtin operators are modified so that they return an exact result (which can be a BigInt) if their operands are safe integers. Operands between Number and BigInt are accepted provided the Number operand is a safe integer. The integer power with a negative exponent returns a BigFloat as result. The integer division returns a BigFloat as result.\n\n</li><li> The <code>^</code> operator is an alias to the power operator (<code>**</code>).\n\n</li><li> The power operator (both <code>^</code> and <code>**</code>) grammar is modified so that <code>-2^2</code> is allowed and yields <code>-4</code>.\n\n</li><li> The logical xor operator is still available with the <code>^^</code> operator.\n\n</li><li> The modulo operator (<code>%</code>) returns the Euclidian remainder (always positive) instead of the truncated remainder.\n\n</li><li> The integer division operator can be overloaded with <code>Operators.updateBigIntOperators(dictionary)</code>.\n\n</li><li> The integer power operator with a non zero negative exponent can be overloaded with <code>Operators.updateBigIntOperators(dictionary)</code>.\n\n</li></ul>\n\n<div class=\"footnote\">\n<hr>\n<h4 class=\"footnotes-heading\">Footnotes</h4>\n\n<h3><a name=\"FOOT1\" href=\"#DOCF1\">(1)</a></h3>\n<p>The\nrationale is that the rounding mode changes must always be\nexplicit.</p>\n<h3><a name=\"FOOT2\" href=\"#DOCF2\">(2)</a></h3>\n<p>The rationale is to avoid side effects for the built-in\noperators.</p>\n<h3><a name=\"FOOT3\" href=\"#DOCF3\">(3)</a></h3>\n<p>Base 10 floating point literals cannot usually be\nexactly represented as base 2 floating point number. In order to\nensure that the literal is represented accurately with the current\nprecision, it must be evaluated at runtime.</p>\n<h3><a name=\"FOOT4\" href=\"#DOCF4\">(4)</a></h3>\n<p>Could be removed in case a deterministic behavior for floating point operations is required.</p>\n</div>\n<hr>\n\n\n\n</body>\n</html>\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/doc/jsbignum.texi",
    "content": "\\input texinfo\n\n@iftex\n@afourpaper\n@headings double\n@end iftex\n\n@titlepage\n@afourpaper\n@sp 7\n@center @titlefont{Javascript Bignum Extensions}\n@sp 3\n@center Version 2020-01-11\n@sp 3\n@center Author: Fabrice Bellard\n@end titlepage\n\n@setfilename jsbignum.info\n@settitle Javascript Bignum Extensions\n\n@contents\n\n@chapter Introduction\n\nThe Bignum extensions add the following features to the Javascript\nlanguage while being 100% backward compatible:\n\n@itemize\n\n@item Operator overloading with a dispatch logic inspired from the proposal available at @url{https://github.com/tc39/proposal-operator-overloading/}.\n\n@item Arbitrarily large floating point numbers (@code{BigFloat}) in base 2 using the IEEE 754 semantics.\n\n@item Arbitrarily large floating point numbers (@code{BigDecimal}) in base 10 based on the proposal available at\n@url{https://github.com/littledan/proposal-bigdecimal}.\n\n@item @code{math} mode: arbitrarily large integers and floating point numbers are available by default. The integer division and power can be overloaded for example to return a fraction. The modulo operator (@code{%}) is defined as the Euclidian\nremainder. @code{^} is an alias to the power operator\n(@code{**}). @code{^^} is used as the exclusive or operator.\n\n@end itemize\n\nThe extensions are independent from each other except the @code{math}\nmode which relies on BigFloat and operator overloading.\n\n@chapter Operator overloading\n\nOperator overloading is inspired from the proposal available at\n@url{https://github.com/tc39/proposal-operator-overloading/}. It\nimplements the same dispatch logic but finds the operator sets by\nlooking at the @code{Symbol.operatorSet} property in the objects. The\nchanges were done in order to simplify the implementation.\n\nMore precisely, the following modifications were made:\n\n@itemize\n\n@item @code{with operators from} is not supported. Operator overloading is always enabled.\n\n@item The dispatch is not based on a static @code{[[OperatorSet]]} field in all instances. Instead, a dynamic lookup of the @code{Symbol.operatorSet} property is done. This property is typically added in the prototype of each object.\n\n@item @code{Operators.create(...dictionaries)} is used to create a new OperatorSet object. The @code{Operators} function is supported as an helper to be closer to the TC39 proposal.\n\n@item @code{[]} cannot be overloaded.\n\n@item In math mode, the BigInt division and power operators can be overloaded with @code{Operators.updateBigIntOperators(dictionary)}.\n\n@end itemize\n\n@chapter BigInt extensions\n\nA few properties are added to the BigInt object:\n\n@table @code\n\n@item tdiv(a, b)\nReturn @math{trunc(a/b)}. @code{b = 0} raises a RangeError\nexception.\n\n@item fdiv(a, b)\nReturn @math{\\lfloor a/b \\rfloor}. @code{b = 0} raises a RangeError\nexception.\n\n@item cdiv(a, b)\nReturn @math{\\lceil a/b \\rceil}. @code{b = 0} raises a RangeError\nexception.\n\n@item ediv(a, b)\nReturn @math{sgn(b) \\lfloor a/{|b|} \\rfloor} (Euclidian\ndivision). @code{b = 0} raises a RangeError exception.\n\n@item tdivrem(a, b)\n@item fdivrem(a, b)\n@item cdivrem(a, b)\n@item edivrem(a, b)\nReturn an array of two elements. The first element is the quotient,\nthe second is the remainder. The same rounding is done as the\ncorresponding division operation.\n\n@item sqrt(a)\nReturn @math{\\lfloor \\sqrt(a) \\rfloor}. A RangeError exception is\nraised if @math{a < 0}.\n\n@item sqrtrem(a)\nReturn an array of two elements. The first element is @math{\\lfloor\n\\sqrt{a} \\rfloor}. The second element is @math{a-\\lfloor \\sqrt{a}\n\\rfloor^2}. A RangeError exception is raised if @math{a < 0}.\n\n@item floorLog2(a)\nReturn -1 if @math{a \\leq 0} otherwise return @math{\\lfloor \\log2(a) \\rfloor}.\n\n@item ctz(a)\nReturn the number of trailing zeros in the two's complement binary representation of a. Return -1 if @math{a=0}.\n\n@end table\n\n@chapter BigFloat\n\n@section Introduction\n\nThis extension adds the @code{BigFloat} primitive type. The\n@code{BigFloat} type represents floating point numbers in base 2\nwith the IEEE 754 semantics. A floating\npoint number is represented as a sign, mantissa and exponent. The\nspecial values @code{NaN}, @code{+/-Infinity}, @code{+0} and @code{-0}\nare supported. The mantissa and exponent can have any bit length with\nan implementation specific minimum and maximum.\n\n@section Floating point rounding\n\nEach floating point operation operates with infinite precision and\nthen rounds the result according to the specified floating point\nenvironment (@code{BigFloatEnv} object). The status flags of the\nenvironment are also set according to the result of the operation.\n\nIf no floating point environment is provided, the global floating\npoint environment is used.\n\nThe rounding mode of the global floating point environment is always\n@code{RNDN} (``round to nearest with ties to even'')@footnote{The\nrationale is that the rounding mode changes must always be\nexplicit.}. The status flags of the global environment cannot be\nread@footnote{The rationale is to avoid side effects for the built-in\noperators.}. The precision of the global environment is\n@code{BigFloatEnv.prec}. The number of exponent bits of the global\nenvironment is @code{BigFloatEnv.expBits}. The global environment\nsubnormal flag is set to @code{true}.\n\nFor example, @code{prec = 53} and @code{ expBits = 11} exactly give\nthe same precision as the IEEE 754 64 bit floating point format. The\ndefault precision is @code{prec = 113} and @code{ expBits = 15} (IEEE\n754 128 bit floating point format).\n\nThe global floating point environment can only be modified temporarily\nwhen calling a function (see @code{BigFloatEnv.setPrec}). Hence a\nfunction can change the global floating point environment for its\ncallees but not for its caller.\n\n@section Operators\n\nThe builtin operators are extended so that a BigFloat is returned if\nat least one operand is a BigFloat. The computations are always done\nwith infinite precision and rounded according to the global floating\npoint environment.\n\n@code{typeof} applied on a @code{BigFloat} returns @code{bigfloat}.\n\nBigFloat can be compared with all the other numeric types and the\nresult follows the expected mathematical relations.\n\nHowever, since BigFloat and Number are different types they are never\nequal when using the strict comparison operators (e.g. @code{0.0 ===\n0.0l} is false).\n\n@section BigFloat literals\n\nBigFloat literals are floating point numbers with a trailing @code{l}\nsuffix. BigFloat literals have an infinite precision. They are rounded\naccording to the global floating point environment when they are\nevaluated.@footnote{Base 10 floating point literals cannot usually be\nexactly represented as base 2 floating point number. In order to\nensure that the literal is represented accurately with the current\nprecision, it must be evaluated at runtime.}\n\n@section Builtin Object changes\n\n@subsection @code{BigFloat} function\n\nThe @code{BigFloat} function cannot be invoked as a constructor. When\ninvoked as a function: the parameter is converted to a primitive\ntype. If the result is a numeric type, it is converted to BigFloat\nwithout rounding. If the result is a string, it is converted to\nBigFloat using the precision of the global floating point environment.\n\n@code{BigFloat} properties:\n\n@table @code\n\n@item LN2\n@item PI\nGetter. Return the value of the corresponding mathematical constant\nrounded to nearest, ties to even with the current global\nprecision. The constant values are cached for small precisions.\n\n@item MIN_VALUE\n@item MAX_VALUE\n@item EPSILON\nGetter. Return the minimum, maximum and epsilon @code{BigFloat} values\n(same definition as the corresponding @code{Number} constants).\n\n@item fpRound(a[, e])\nRound the floating point number @code{a} according to the floating\npoint environment @code{e} or the global environment if @code{e} is\nundefined.\n\n@item parseFloat(a[, radix[, e]])\nParse the string @code{a} as a floating point number in radix\n@code{radix}. The radix is 0 (default) or from 2 to 36. The radix 0\nmeans radix 10 unless there is a hexadecimal or binary prefix. The\nresult is rounded according to the floating point environment @code{e}\nor the global environment if @code{e} is undefined.\n\n@item isFinite(a)\nReturn true if @code{a} is a finite bigfloat.\n\n@item isNaN(a)\nReturn true if @code{a} is a NaN bigfloat.\n\n@item add(a, b[, e])\n@item sub(a, b[, e])\n@item mul(a, b[, e])\n@item div(a, b[, e])\nPerform the specified floating point operation and round the floating\npoint number @code{a} according to the floating point environment\n@code{e} or the global environment if @code{e} is undefined. If\n@code{e} is specified, the floating point status flags are updated.\n\n@item floor(x)\n@item ceil(x)\n@item round(x)\n@item trunc(x)\nRound to an integer. No additional rounding is performed.\n\n@item abs(x)\nReturn the absolute value of x. No additional rounding is performed.\n\n@item fmod(x, y[, e])\n@item remainder(x, y[, e])\nFloating point remainder. The quotient is truncated to zero (fmod) or\nto the nearest integer with ties to even (remainder). @code{e} is an\noptional floating point environment.\n\n@item sqrt(x[, e])\nSquare root. Return a rounded floating point number. @code{e} is an\noptional floating point environment.\n\n@item sin(x[, e])\n@item cos(x[, e])\n@item tan(x[, e])\n@item asin(x[, e])\n@item acos(x[, e])\n@item atan(x[, e])\n@item atan2(x, y[, e])\n@item exp(x[, e])\n@item log(x[, e])\n@item pow(x, y[, e])\nTranscendental operations. Return a rounded floating point\nnumber. @code{e} is an optional floating point environment.\n\n@end table\n\n@subsection @code{BigFloat.prototype}\n\nThe following properties are modified:\n\n@table @code\n@item valueOf()\nReturn the bigfloat primitive value corresponding to @code{this}.\n\n@item toString(radix)\n\nFor floating point numbers:\n\n@itemize\n@item\nIf the radix is a power of two, the conversion is done with infinite\nprecision.\n@item\nOtherwise, the number is rounded to nearest with ties to even using\nthe global precision. It is then converted to string using the minimum\nnumber of digits so that its conversion back to a floating point using\nthe global precision and round to nearest gives the same number. \n\n@end itemize\n\nThe exponent letter is @code{e} for base 10, @code{p} for bases 2, 8,\n16 with a binary exponent and @code{@@} for the other bases.\n\n@item toPrecision(p, rnd_mode = BigFloatEnv.RNDNA, radix = 10)\n@item toFixed(p, rnd_mode = BigFloatEnv.RNDNA, radix = 10)\n@item toExponential(p, rnd_mode = BigFloatEnv.RNDNA, radix = 10)\nSame semantics as the corresponding @code{Number} functions with\nBigFloats. There is no limit on the accepted precision @code{p}. The\nrounding mode and radix can be optionally specified. The radix must be\nbetween 2 and 36.\n\n@end table\n\n@subsection @code{BigFloatEnv} constructor\n\nThe @code{BigFloatEnv([p, [,rndMode]]} constructor cannot be invoked as a\nfunction. The floating point environment contains:\n\n@itemize\n@item the mantissa precision in bits\n\n@item the exponent size in bits assuming an IEEE 754 representation;\n\n@item the subnormal flag (if true, subnormal floating point numbers can\nbe generated by the floating point operations).\n\n@item the rounding mode\n\n@item the floating point status. The status flags can only be set by the floating point operations. They can be reset with @code{BigFloatEnv.prototype.clearStatus()} or with the various status flag setters.\n\n@end itemize\n\n@code{new BigFloatEnv([p, [,rndMode]]} creates a new floating point\nenvironment. The status flags are reset. If no parameter is given the\nprecision, exponent bits and subnormal flags are copied from the\nglobal floating point environment. Otherwise, the precision is set to\n@code{p}, the number of exponent bits is set to @code{expBitsMax} and the\nsubnormal flags is set to @code{false}. If @code{rndMode} is\n@code{undefined}, the rounding mode is set to @code{RNDN}.\n\n@code{BigFloatEnv} properties:\n\n@table @code\n\n@item prec\nGetter. Return the precision in bits of the global floating point\nenvironment. The initial value is @code{113}.\n\n@item expBits\nGetter. Return the exponent size in bits of the global floating point\nenvironment assuming an IEEE 754 representation. The initial value is\n@code{15}.\n\n@item setPrec(f, p[, e])\nSet the precision of the global floating point environment to @code{p}\nand the exponent size to @code{e} then call the function\n@code{f}. Then the Float precision and exponent size are reset to\ntheir precious value and the return value of @code{f} is returned (or\nan exception is raised if @code{f} raised an exception). If @code{e}\nis @code{undefined} it is set to @code{BigFloatEnv.expBitsMax}.\n\n@item precMin\nRead-only integer. Return the minimum allowed precision. Must be at least 2.\n\n@item precMax\nRead-only integer. Return the maximum allowed precision. Must be at least 113.\n\n@item expBitsMin\nRead-only integer. Return the minimum allowed exponent size in\nbits. Must be at least 3.\n\n@item expBitsMax\nRead-only integer. Return the maximum allowed exponent size in\nbits. Must be at least 15.\n\n@item RNDN\nRead-only integer. Round to nearest, with ties to even rounding mode.\n\n@item RNDZ\nRead-only integer. Round to zero rounding mode.\n\n@item RNDD\nRead-only integer. Round to -Infinity rounding mode.\n\n@item RNDU\nRead-only integer. Round to +Infinity rounding mode.\n\n@item RNDNA\nRead-only integer. Round to nearest, with ties away from zero rounding mode.\n\n@item RNDA\nRead-only integer. Round away from zero rounding mode.\n\n@item RNDF@footnote{Could be removed in case a deterministic behavior for floating point operations is required.}\nRead-only integer. Faithful rounding mode. The result is\nnon-deterministically rounded to -Infinity or +Infinity. This rounding\nmode usually gives a faster and deterministic running time for the\nfloating point operations.\n\n@end table\n\n@code{BigFloatEnv.prototype} properties:\n\n@table @code\n\n@item prec\nGetter and setter (Integer). Return or set the precision in bits.\n\n@item expBits\nGetter and setter (Integer). Return or set the exponent size in bits\nassuming an IEEE 754 representation.\n\n@item rndMode\nGetter and setter (Integer). Return or set the rounding mode.\n\n@item subnormal\nGetter and setter (Boolean). subnormal flag. It is false when\n@code{expBits = expBitsMax}.\n\n@item clearStatus()\nClear the status flags.\n\n@item invalidOperation\n@item divideByZero\n@item overflow\n@item underflow\n@item inexact\nGetter and setter (Boolean). Status flags.\n\n@end table\n\n@chapter BigDecimal\n\nThis extension adds the @code{BigDecimal} primitive type. The\n@code{BigDecimal} type represents floating point numbers in base\n10. It is inspired from the proposal available at\n@url{https://github.com/littledan/proposal-bigdecimal}.\n\nThe @code{BigDecimal} floating point numbers are always normalized and\nfinite. There is no concept of @code{-0}, @code{Infinity} or\n@code{NaN}. By default, all the computations are done with infinite\nprecision.\n\n@section Operators\n\nThe following builtin operators support BigDecimal:\n\n@table @code\n\n@item +\n@item -\n@item *\nBoth operands must be BigDecimal. The result is computed with infinite\nprecision.\n@item %\nBoth operands must be BigDecimal. The result is computed with infinite\nprecision. A range error is throws in case of division by zero.\n\n@item /\nBoth operands must be BigDecimal. A range error is throws in case of\ndivision by zero or if the result cannot be represented with infinite\nprecision (use @code{BigDecimal.div} to specify the rounding).\n\n@item **\nBoth operands must be BigDecimal. The exponent must be a positive\ninteger. The result is computed with infinite precision.\n\n@item ===\nWhen one of the operand is a BigDecimal, return true if both operands\nare a BigDecimal and if they are equal.\n\n@item ==\n@item !=\n@item <=\n@item >=\n@item <\n@item >\n\nNumerical comparison. When one of the operand is not a BigDecimal, it is\nconverted to BigDecimal by using ToString(). Hence comparisons between\nNumber and BigDecimal do not use the exact mathematical value of the\nNumber value.\n\n@end table\n\n@section BigDecimal literals\n\nBigDecimal literals are decimal floating point numbers with a trailing\n@code{m} suffix.\n\n@section Builtin Object changes\n\n@subsection The @code{BigDecimal} function.\n\nIt returns @code{0m} if no parameter is provided. Otherwise the first\nparameter is converted to a bigdecimal by using ToString(). Hence\nNumber values are not converted to their exact numerical value as\nBigDecimal.\n\n@subsection Properties of the @code{BigDecimal} object\n\n@table @code\n\n@item add(a, b[, e])\n@item sub(a, b[, e])\n@item mul(a, b[, e])\n@item div(a, b[, e])\n@item mod(a, b[, e])\n@item sqrt(a, e)\n@item round(a, e)\nPerform the specified floating point operation and round the floating\npoint result according to the rounding object @code{e}. If the\nrounding object is not present, the operation is executed with\ninfinite precision.\n\nFor @code{div}, a @code{RangeError} exception is thrown in case of\ndivision by zero or if the result cannot be represented with infinite\nprecision if no rounding object is present.\n\nFor @code{sqrt}, a range error is thrown if @code{a} is less than\nzero.\n\nThe rounding object must contain the following properties:\n@code{roundingMode} is a string specifying the rounding mode\n(@code{\"floor\"}, @code{\"ceiling\"}, @code{\"down\"}, @code{\"up\"},\n@code{\"half-even\"}, @code{\"half-up\"}). Either\n@code{maximumSignificantDigits} or @code{maximumFractionDigits} must\nbe present to specify respectively the number of significant digits\n(must be >= 1) or the number of digits after the decimal point (must\nbe >= 0).\n\n@end table\n\n@subsection Properties of the @code{BigDecimal.prototype} object\n\n@table @code\n@item valueOf()\nReturn the bigdecimal primitive value corresponding to @code{this}.\n\n@item toString()\nConvert @code{this} to a string with infinite precision in base 10.\n\n@item toPrecision(p, rnd_mode = \"half-up\")\n@item toFixed(p, rnd_mode = \"half-up\")\n@item toExponential(p, rnd_mode = \"half-up\")\nConvert the BigDecimal @code{this} to string with the specified\nprecision @code{p}. There is no limit on the accepted precision\n@code{p}. The rounding mode can be optionally\nspecified. @code{toPrecision} outputs either in decimal fixed notation\nor in decimal exponential notation with a @code{p} digits of\nprecision.  @code{toExponential} outputs in decimal exponential\nnotation with @code{p} digits after the decimal point. @code{toFixed}\noutputs in decimal notation with @code{p} digits after the decimal\npoint.\n\n@end table\n\n@chapter Math mode\n\nA new @emph{math mode} is enabled with the @code{\"use math\"}\ndirective. It propagates the same way as the @emph{strict mode}. It is\ndesigned so that arbitrarily large integers and floating point numbers\nare available by default. In order to minimize the number of changes\nin the Javascript semantics, integers are represented either as Number\nor BigInt depending on their magnitude. Floating point numbers are\nalways represented as BigFloat.\n\nThe following changes are made to the Javascript semantics:\n\n@itemize\n\n@item Floating point literals (i.e. number with a decimal point or an exponent) are @code{BigFloat} by default (i.e. a @code{l} suffix is implied). Hence @code{typeof 1.0 === \"bigfloat\"}.\n\n@item Integer literals (i.e. numbers without a decimal point or an exponent) with or without the @code{n} suffix are @code{BigInt} if their value cannot be represented as a safe integer. A safe integer is defined as a integer whose absolute value is smaller or equal to @code{2**53-1}. Hence @code{typeof 1 === \"number \"}, @code{typeof 1n === \"number\"} but @code{typeof 9007199254740992 === \"bigint\" }.\n\n@item All the bigint builtin operators and functions are modified so that their result is returned as a Number if it is a safe integer. Otherwise the result stays a BigInt.\n\n@item The builtin operators are modified so that they return an exact result (which can be a BigInt) if their operands are safe integers. Operands between Number and BigInt are accepted provided the Number operand is a safe integer. The integer power with a negative exponent returns a BigFloat as result. The integer division returns a BigFloat as result.\n\n@item The @code{^} operator is an alias to the power operator (@code{**}).\n\n@item The power operator (both @code{^} and @code{**}) grammar is modified so that @code{-2^2} is allowed and yields @code{-4}.\n\n@item The logical xor operator is still available with the @code{^^} operator.\n\n@item The modulo operator (@code{%}) returns the Euclidian remainder (always positive) instead of the truncated remainder.\n\n@item The integer division operator can be overloaded with @code{Operators.updateBigIntOperators(dictionary)}.\n\n@item The integer power operator with a non zero negative exponent can be overloaded with @code{Operators.updateBigIntOperators(dictionary)}.\n\n@end itemize\n\n@bye\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/doc/quickjs.html",
    "content": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n<!-- Created by GNU Texinfo 6.1, http://www.gnu.org/software/texinfo/ -->\n<head>\n<title>QuickJS Javascript Engine</title>\n\n<meta name=\"description\" content=\"QuickJS Javascript Engine\">\n<meta name=\"keywords\" content=\"QuickJS Javascript Engine\">\n<meta name=\"resource-type\" content=\"document\">\n<meta name=\"distribution\" content=\"global\">\n<meta name=\"Generator\" content=\"makeinfo\">\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<link href=\"#SEC_Contents\" rel=\"contents\" title=\"Table of Contents\">\n<style type=\"text/css\">\n<!--\na.summary-letter {text-decoration: none}\nblockquote.indentedblock {margin-right: 0em}\nblockquote.smallindentedblock {margin-right: 0em; font-size: smaller}\nblockquote.smallquotation {font-size: smaller}\ndiv.display {margin-left: 3.2em}\ndiv.example {margin-left: 3.2em}\ndiv.lisp {margin-left: 3.2em}\ndiv.smalldisplay {margin-left: 3.2em}\ndiv.smallexample {margin-left: 3.2em}\ndiv.smalllisp {margin-left: 3.2em}\nkbd {font-style: oblique}\npre.display {font-family: inherit}\npre.format {font-family: inherit}\npre.menu-comment {font-family: serif}\npre.menu-preformatted {font-family: serif}\npre.smalldisplay {font-family: inherit; font-size: smaller}\npre.smallexample {font-size: smaller}\npre.smallformat {font-family: inherit; font-size: smaller}\npre.smalllisp {font-size: smaller}\nspan.nolinebreak {white-space: nowrap}\nspan.roman {font-family: initial; font-weight: normal}\nspan.sansserif {font-family: sans-serif; font-weight: normal}\nul.no-bullet {list-style: none}\n-->\n</style>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n\n\n</head>\n\n<body lang=\"en\">\n<h1 class=\"settitle\" align=\"center\">QuickJS Javascript Engine</h1>\n\n<a name=\"SEC_Contents\"></a>\n<h2 class=\"contents-heading\">Table of Contents</h2>\n\n<div class=\"contents\">\n<ul class=\"no-bullet\">\n<li><a name=\"toc-Introduction\" href=\"#Introduction\">1 Introduction</a>\n<ul class=\"no-bullet\">\n  <li><a name=\"toc-Main-Features\" href=\"#Main-Features\">1.1 Main Features</a></li>\n</ul></li>\n<li><a name=\"toc-Usage\" href=\"#Usage\">2 Usage</a>\n<ul class=\"no-bullet\">\n  <li><a name=\"toc-Installation\" href=\"#Installation\">2.1 Installation</a></li>\n  <li><a name=\"toc-Quick-start\" href=\"#Quick-start\">2.2 Quick start</a></li>\n  <li><a name=\"toc-Command-line-options\" href=\"#Command-line-options\">2.3 Command line options</a>\n  <ul class=\"no-bullet\">\n    <li><a name=\"toc-qjs-interpreter\" href=\"#qjs-interpreter\">2.3.1 <code>qjs</code> interpreter</a></li>\n    <li><a name=\"toc-qjsc-compiler\" href=\"#qjsc-compiler\">2.3.2 <code>qjsc</code> compiler</a></li>\n  </ul></li>\n  <li><a name=\"toc-qjscalc-application\" href=\"#qjscalc-application\">2.4 <code>qjscalc</code> application</a></li>\n  <li><a name=\"toc-Built_002din-tests\" href=\"#Built_002din-tests\">2.5 Built-in tests</a></li>\n  <li><a name=\"toc-Test262-_0028ECMAScript-Test-Suite_0029\" href=\"#Test262-_0028ECMAScript-Test-Suite_0029\">2.6 Test262 (ECMAScript Test Suite)</a></li>\n</ul></li>\n<li><a name=\"toc-Specifications\" href=\"#Specifications\">3 Specifications</a>\n<ul class=\"no-bullet\">\n  <li><a name=\"toc-Language-support\" href=\"#Language-support\">3.1 Language support</a>\n  <ul class=\"no-bullet\">\n    <li><a name=\"toc-ES2020-support\" href=\"#ES2020-support\">3.1.1 ES2020 support</a></li>\n    <li><a name=\"toc-ECMA402\" href=\"#ECMA402\">3.1.2 ECMA402</a></li>\n    <li><a name=\"toc-Extensions\" href=\"#Extensions\">3.1.3 Extensions</a></li>\n    <li><a name=\"toc-Mathematical-extensions\" href=\"#Mathematical-extensions\">3.1.4 Mathematical extensions</a></li>\n  </ul></li>\n  <li><a name=\"toc-Modules\" href=\"#Modules\">3.2 Modules</a></li>\n  <li><a name=\"toc-Standard-library\" href=\"#Standard-library\">3.3 Standard library</a>\n  <ul class=\"no-bullet\">\n    <li><a name=\"toc-Global-objects\" href=\"#Global-objects\">3.3.1 Global objects</a></li>\n    <li><a name=\"toc-std-module\" href=\"#std-module\">3.3.2 <code>std</code> module</a></li>\n    <li><a name=\"toc-os-module\" href=\"#os-module\">3.3.3 <code>os</code> module</a></li>\n  </ul></li>\n  <li><a name=\"toc-QuickJS-C-API\" href=\"#QuickJS-C-API\">3.4 QuickJS C API</a>\n  <ul class=\"no-bullet\">\n    <li><a name=\"toc-Runtime-and-contexts\" href=\"#Runtime-and-contexts\">3.4.1 Runtime and contexts</a></li>\n    <li><a name=\"toc-JSValue\" href=\"#JSValue\">3.4.2 JSValue</a></li>\n    <li><a name=\"toc-C-functions\" href=\"#C-functions\">3.4.3 C functions</a></li>\n    <li><a name=\"toc-Exceptions\" href=\"#Exceptions\">3.4.4 Exceptions</a></li>\n    <li><a name=\"toc-Script-evaluation\" href=\"#Script-evaluation\">3.4.5 Script evaluation</a></li>\n    <li><a name=\"toc-JS-Classes\" href=\"#JS-Classes\">3.4.6 JS Classes</a></li>\n    <li><a name=\"toc-C-Modules\" href=\"#C-Modules\">3.4.7 C Modules</a></li>\n    <li><a name=\"toc-Memory-handling\" href=\"#Memory-handling\">3.4.8 Memory handling</a></li>\n    <li><a name=\"toc-Execution-timeout-and-interrupts\" href=\"#Execution-timeout-and-interrupts\">3.4.9 Execution timeout and interrupts</a></li>\n  </ul></li>\n</ul></li>\n<li><a name=\"toc-Internals\" href=\"#Internals\">4 Internals</a>\n<ul class=\"no-bullet\">\n  <li><a name=\"toc-Bytecode\" href=\"#Bytecode\">4.1 Bytecode</a></li>\n  <li><a name=\"toc-Executable-generation\" href=\"#Executable-generation\">4.2 Executable generation</a>\n  <ul class=\"no-bullet\">\n    <li><a name=\"toc-qjsc-compiler-1\" href=\"#qjsc-compiler-1\">4.2.1 <code>qjsc</code> compiler</a></li>\n    <li><a name=\"toc-Binary-JSON\" href=\"#Binary-JSON\">4.2.2 Binary JSON</a></li>\n  </ul></li>\n  <li><a name=\"toc-Runtime\" href=\"#Runtime\">4.3 Runtime</a>\n  <ul class=\"no-bullet\">\n    <li><a name=\"toc-Strings\" href=\"#Strings\">4.3.1 Strings</a></li>\n    <li><a name=\"toc-Objects\" href=\"#Objects\">4.3.2 Objects</a></li>\n    <li><a name=\"toc-Atoms\" href=\"#Atoms\">4.3.3 Atoms</a></li>\n    <li><a name=\"toc-Numbers\" href=\"#Numbers\">4.3.4 Numbers</a></li>\n    <li><a name=\"toc-Garbage-collection\" href=\"#Garbage-collection\">4.3.5 Garbage collection</a></li>\n    <li><a name=\"toc-JSValue-1\" href=\"#JSValue-1\">4.3.6 JSValue</a></li>\n    <li><a name=\"toc-Function-call\" href=\"#Function-call\">4.3.7 Function call</a></li>\n  </ul></li>\n  <li><a name=\"toc-RegExp\" href=\"#RegExp\">4.4 RegExp</a></li>\n  <li><a name=\"toc-Unicode\" href=\"#Unicode\">4.5 Unicode</a></li>\n  <li><a name=\"toc-BigInt_002c-BigFloat_002c-BigDecimal\" href=\"#BigInt_002c-BigFloat_002c-BigDecimal\">4.6 BigInt, BigFloat, BigDecimal</a></li>\n</ul></li>\n<li><a name=\"toc-License\" href=\"#License\">5 License</a></li>\n\n</ul>\n</div>\n\n\n<a name=\"Introduction\"></a>\n<h2 class=\"chapter\">1 Introduction</h2>\n\n<p>QuickJS is a small and embeddable Javascript engine. It supports the\nES2020 specification\n<a name=\"DOCF1\" href=\"#FOOT1\"><sup>1</sup></a>\nincluding modules, asynchronous generators, proxies and BigInt.\n</p>\n<p>It supports mathematical extensions such as big decimal float float\nnumbers (BigDecimal), big binary floating point numbers (BigFloat),\nand operator overloading.\n</p>\n<a name=\"Main-Features\"></a>\n<h3 class=\"section\">1.1 Main Features</h3>\n\n<ul>\n<li> Small and easily embeddable: just a few C files, no external dependency, 210 KiB of x86 code for a simple &ldquo;hello world&rdquo; program.\n\n</li><li> Fast interpreter with very low startup time: runs the 69000 tests of the ECMAScript Test Suite<a name=\"DOCF2\" href=\"#FOOT2\"><sup>2</sup></a> in about 95 seconds on a single core of a desktop PC. The complete life cycle of a runtime instance completes in less than 300 microseconds.\n\n</li><li> Almost complete ES2020 support including modules, asynchronous\ngenerators and full Annex B support (legacy web compatibility). Many\nfeatures from the upcoming ES2021 specification\n<a name=\"DOCF3\" href=\"#FOOT3\"><sup>3</sup></a> are also supported.\n\n</li><li> Passes nearly 100% of the ECMAScript Test Suite tests when selecting the ES2020 features.\n\n</li><li> Compile Javascript sources to executables with no external dependency.\n\n</li><li> Garbage collection using reference counting (to reduce memory usage and have deterministic behavior) with cycle removal.\n\n</li><li> Mathematical extensions: BigDecimal, BigFloat, operator overloading, bigint mode, math mode.\n\n</li><li> Command line interpreter with contextual colorization and completion implemented in Javascript.\n\n</li><li> Small built-in standard library with C library wrappers.\n\n</li></ul>\n\n<a name=\"Usage\"></a>\n<h2 class=\"chapter\">2 Usage</h2>\n\n<a name=\"Installation\"></a>\n<h3 class=\"section\">2.1 Installation</h3>\n\n<p>A Makefile is provided to compile the engine on Linux or MacOS/X.  A\npreliminary Windows support is available thru cross compilation on a\nLinux host with the MingGW tools.\n</p>\n<p>Edit the top of the <code>Makefile</code> if you wish to select specific\noptions then run <code>make</code>.\n</p>\n<p>You can type <code>make install</code> as root if you wish to install the binaries and support files to\n<code>/usr/local</code> (this is not necessary to use QuickJS).\n</p>\n<a name=\"Quick-start\"></a>\n<h3 class=\"section\">2.2 Quick start</h3>\n\n<p><code>qjs</code> is the command line interpreter (Read-Eval-Print Loop). You can pass\nJavascript files and/or expressions as arguments to execute them:\n</p>\n<div class=\"example\">\n<pre class=\"example\">./qjs examples/hello.js\n</pre></div>\n\n<p><code>qjsc</code> is the command line compiler:\n</p>\n<div class=\"example\">\n<pre class=\"example\">./qjsc -o hello examples/hello.js\n./hello\n</pre></div>\n\n<p>generates a <code>hello</code> executable with no external dependency.\n</p>\n<a name=\"Command-line-options\"></a>\n<h3 class=\"section\">2.3 Command line options</h3>\n\n<a name=\"qjs-interpreter\"></a>\n<h4 class=\"subsection\">2.3.1 <code>qjs</code> interpreter</h4>\n\n<pre class=\"verbatim\">usage: qjs [options] [file [args]]\n</pre>\n<p>Options are:\n</p><dl compact=\"compact\">\n<dt><code>-h</code></dt>\n<dt><code>--help</code></dt>\n<dd><p>List options.\n</p>\n</dd>\n<dt><code>-e <code>EXPR</code></code></dt>\n<dt><code>--eval <code>EXPR</code></code></dt>\n<dd><p>Evaluate EXPR.\n</p>\n</dd>\n<dt><code>-i</code></dt>\n<dt><code>--interactive</code></dt>\n<dd><p>Go to interactive mode (it is not the default when files are provided on the command line).\n</p>\n</dd>\n<dt><code>-m</code></dt>\n<dt><code>--module</code></dt>\n<dd><p>Load as ES6 module (default=autodetect). A module is autodetected if\nthe filename extension is <code>.mjs</code> or if the first keyword of the\nsource is <code>import</code>.\n</p>\n</dd>\n<dt><code>--script</code></dt>\n<dd><p>Load as ES6 script (default=autodetect).\n</p>\n</dd>\n<dt><code>--bignum</code></dt>\n<dd><p>Enable the bignum extensions: BigDecimal object, BigFloat object and\nthe <code>&quot;use math&quot;</code> directive.\n</p>\n</dd>\n<dt><code>-I file</code></dt>\n<dt><code>--include file</code></dt>\n<dd><p>Include an additional file.\n</p>\n</dd>\n</dl>\n\n<p>Advanced options are:\n</p>\n<dl compact=\"compact\">\n<dt><code>--std</code></dt>\n<dd><p>Make the <code>std</code> and <code>os</code> modules available to the loaded\nscript even if it is not a module.\n</p>\n</dd>\n<dt><code>-d</code></dt>\n<dt><code>--dump</code></dt>\n<dd><p>Dump the memory usage stats.\n</p>\n</dd>\n<dt><code>-q</code></dt>\n<dt><code>--quit</code></dt>\n<dd><p>just instantiate the interpreter and quit.\n</p>\n</dd>\n</dl>\n\n<a name=\"qjsc-compiler\"></a>\n<h4 class=\"subsection\">2.3.2 <code>qjsc</code> compiler</h4>\n\n<pre class=\"verbatim\">usage: qjsc [options] [files]\n</pre>\n<p>Options are:\n</p><dl compact=\"compact\">\n<dt><code>-c</code></dt>\n<dd><p>Only output bytecode in a C file. The default is to output an executable file.\n</p></dd>\n<dt><code>-e</code></dt>\n<dd><p>Output <code>main()</code> and bytecode in a C file. The default is to output an\nexecutable file.\n</p></dd>\n<dt><code>-o output</code></dt>\n<dd><p>Set the output filename (default = <samp>out.c</samp> or <samp>a.out</samp>).\n</p>\n</dd>\n<dt><code>-N cname</code></dt>\n<dd><p>Set the C name of the generated data.\n</p>\n</dd>\n<dt><code>-m</code></dt>\n<dd><p>Compile as Javascript module (default=autodetect).\n</p>\n</dd>\n<dt><code>-D module_name</code></dt>\n<dd><p>Compile a dynamically loaded module and its dependencies. This option\nis needed when your code uses the <code>import</code> keyword or the\n<code>os.Worker</code> constructor because the compiler cannot statically\nfind the name of the dynamically loaded modules.\n</p>\n</dd>\n<dt><code>-M module_name[,cname]</code></dt>\n<dd><p>Add initialization code for an external C module. See the\n<code>c_module</code> example.\n</p>\n</dd>\n<dt><code>-x</code></dt>\n<dd><p>Byte swapped output (only used for cross compilation).\n</p>\n</dd>\n<dt><code>-flto</code></dt>\n<dd><p>Use link time optimization. The compilation is slower but the\nexecutable is smaller and faster. This option is automatically set\nwhen the <code>-fno-x</code> options are used.\n</p>\n</dd>\n<dt><code>-fno-[eval|string-normalize|regexp|json|proxy|map|typedarray|promise|bigint]</code></dt>\n<dd><p>Disable selected language features to produce a smaller executable file.\n</p>\n</dd>\n<dt><code>-fbignum</code></dt>\n<dd><p>Enable the bignum extensions: BigDecimal object, BigFloat object and\nthe <code>&quot;use math&quot;</code> directive.\n</p>\n</dd>\n</dl>\n\n<a name=\"qjscalc-application\"></a>\n<h3 class=\"section\">2.4 <code>qjscalc</code> application</h3>\n\n<p>The <code>qjscalc</code> application is a superset of the <code>qjs</code>\ncommand line interpreter implementing a Javascript calculator with\narbitrarily large integer and floating point numbers, fractions,\ncomplex numbers, polynomials and matrices. The source code is in\n<samp>qjscalc.js</samp>. More documentation and a web version are available at\n<a href=\"http://numcalc.com\">http://numcalc.com</a>.\n</p>\n<a name=\"Built_002din-tests\"></a>\n<h3 class=\"section\">2.5 Built-in tests</h3>\n\n<p>Run <code>make test</code> to run the few built-in tests included in the\nQuickJS archive.\n</p>\n<a name=\"Test262-_0028ECMAScript-Test-Suite_0029\"></a>\n<h3 class=\"section\">2.6 Test262 (ECMAScript Test Suite)</h3>\n\n<p>A test262 runner is included in the QuickJS archive. The test262 tests\ncan be installed in the QuickJS source directory with:\n</p>\n<div class=\"example\">\n<pre class=\"example\">git clone https://github.com/tc39/test262.git test262\ncd test262\npatch -p1 &lt; ../tests/test262.patch\ncd ..\n</pre></div>\n\n<p>The patch adds the implementation specific <code>harness</code> functions\nand optimizes the inefficient RegExp character classes and Unicode\nproperty escapes tests (the tests themselves are not modified, only a\nslow string initialization function is optimized).\n</p>\n<p>The tests can be run with\n</p><div class=\"example\">\n<pre class=\"example\">make test2\n</pre></div>\n\n<p>The configuration files <code>test262.conf</code>\n(resp. <code>test262o.conf</code> for the old ES5.1 tests<a name=\"DOCF4\" href=\"#FOOT4\"><sup>4</sup></a>))\ncontain the options to run the various tests. Tests can be excluded\nbased on features or filename.\n</p>\n<p>The file <code>test262_errors.txt</code> contains the current list of\nerrors. The runner displays a message when a new error appears or when\nan existing error is corrected or modified. Use the <code>-u</code> option\nto update the current list of errors (or <code>make test2-update</code>).\n</p>\n<p>The file <code>test262_report.txt</code> contains the logs of all the\ntests. It is useful to have a clearer analysis of a particular\nerror. In case of crash, the last line corresponds to the failing\ntest.\n</p>\n<p>Use the syntax <code>./run-test262 -c test262.conf -f filename.js</code> to\nrun a single test. Use the syntax <code>./run-test262 -c test262.conf\nN</code> to start testing at test number <code>N</code>.\n</p>\n<p>For more information, run <code>./run-test262</code> to see the command line\noptions of the test262 runner.\n</p>\n<p><code>run-test262</code> accepts the <code>-N</code> option to be invoked from\n<code>test262-harness</code><a name=\"DOCF5\" href=\"#FOOT5\"><sup>5</sup></a>\nthru <code>eshost</code>. Unless you want to compare QuickJS with other\nengines under the same conditions, we do not recommend to run the\ntests this way as it is much slower (typically half an hour instead of\nabout 100 seconds).\n</p>\n<a name=\"Specifications\"></a>\n<h2 class=\"chapter\">3 Specifications</h2>\n\n<a name=\"Language-support\"></a>\n<h3 class=\"section\">3.1 Language support</h3>\n\n<a name=\"ES2020-support\"></a>\n<h4 class=\"subsection\">3.1.1 ES2020 support</h4>\n\n<p>The ES2020 specification is almost fully supported including the Annex\nB (legacy web compatibility) and the Unicode related features.\n</p>\n<p>The following features are not supported yet:\n</p>\n<ul>\n<li> Tail calls<a name=\"DOCF6\" href=\"#FOOT6\"><sup>6</sup></a>\n\n</li></ul>\n\n<a name=\"ECMA402\"></a>\n<h4 class=\"subsection\">3.1.2 ECMA402</h4>\n\n<p>ECMA402 (Internationalization API) is not supported.\n</p>\n<a name=\"Extensions\"></a>\n<h4 class=\"subsection\">3.1.3 Extensions</h4>\n\n<ul>\n<li> The directive <code>&quot;use strip&quot;</code> indicates that the debug information (including the source code of the functions) should not be retained to save memory. As <code>&quot;use strict&quot;</code>, the directive can be global to a script or local to a function.\n\n</li><li> The first line of a script beginning with <code>#!</code> is ignored.\n\n</li></ul>\n\n<a name=\"Mathematical-extensions\"></a>\n<h4 class=\"subsection\">3.1.4 Mathematical extensions</h4>\n\n<p>The mathematical extensions are fully backward compatible with\nstandard Javascript. See <code>jsbignum.pdf</code> for more information.\n</p>\n<ul>\n<li> <code>BigDecimal</code> support: arbitrary large floating point numbers in base 10.\n\n</li><li> <code>BigFloat</code> support: arbitrary large floating point numbers in base 2.\n\n</li><li> Operator overloading.\n\n</li><li> The directive <code>&quot;use bigint&quot;</code> enables the bigint mode where integers are <code>BigInt</code> by default.\n\n</li><li> The directive <code>&quot;use math&quot;</code> enables the math mode where the division and power operators on integers produce fractions. Floating point literals are <code>BigFloat</code> by default and integers are <code>BigInt</code> by default.\n\n</li></ul>\n\n<a name=\"Modules\"></a>\n<h3 class=\"section\">3.2 Modules</h3>\n\n<p>ES6 modules are fully supported. The default name resolution is the\nfollowing:\n</p>\n<ul>\n<li> Module names with a leading <code>.</code> or <code>..</code> are relative\nto the current module path.\n\n</li><li> Module names without a leading <code>.</code> or <code>..</code> are system\nmodules, such as <code>std</code> or <code>os</code>.\n\n</li><li> Module names ending with <code>.so</code> are native modules using the\nQuickJS C API.\n\n</li></ul>\n\n<a name=\"Standard-library\"></a>\n<h3 class=\"section\">3.3 Standard library</h3>\n\n<p>The standard library is included by default in the command line\ninterpreter. It contains the two modules <code>std</code> and <code>os</code> and\na few global objects.\n</p>\n<a name=\"Global-objects\"></a>\n<h4 class=\"subsection\">3.3.1 Global objects</h4>\n\n<dl compact=\"compact\">\n<dt><code>scriptArgs</code></dt>\n<dd><p>Provides the command line arguments. The first argument is the script name.\n</p></dd>\n<dt><code>print(...args)</code></dt>\n<dd><p>Print the arguments separated by spaces and a trailing newline.\n</p></dd>\n<dt><code>console.log(...args)</code></dt>\n<dd><p>Same as print().\n</p>\n</dd>\n</dl>\n\n<a name=\"std-module\"></a>\n<h4 class=\"subsection\">3.3.2 <code>std</code> module</h4>\n\n<p>The <code>std</code> module provides wrappers to the libc <samp>stdlib.h</samp>\nand <samp>stdio.h</samp> and a few other utilities.\n</p>\n<p>Available exports:\n</p>\n<dl compact=\"compact\">\n<dt><code>exit(n)</code></dt>\n<dd><p>Exit the process.\n</p>\n</dd>\n<dt><code>evalScript(str, options = undefined)</code></dt>\n<dd><p>Evaluate the string <code>str</code> as a script (global\neval). <code>options</code> is an optional object containing the following\noptional properties:\n</p>\n<dl compact=\"compact\">\n<dt><code>backtrace_barrier</code></dt>\n<dd><p>Boolean (default = false). If true, error backtraces do not list the\n  stack frames below the evalScript.\n  </p></dd>\n</dl>\n\n</dd>\n<dt><code>loadScript(filename)</code></dt>\n<dd><p>Evaluate the file <code>filename</code> as a script (global eval).\n</p>\n</dd>\n<dt><code>loadFile(filename)</code></dt>\n<dd><p>Load the file <code>filename</code> and return it as a string assuming UTF-8\nencoding. Return <code>null</code> in case of I/O error.\n</p>\n</dd>\n<dt><code>open(filename, flags, errorObj = undefined)</code></dt>\n<dd><p>Open a file (wrapper to the libc <code>fopen()</code>). Return the FILE\nobject or <code>null</code> in case of I/O error. If <code>errorObj</code> is not\nundefined, set its <code>errno</code> property to the error code or to 0 if\nno error occured.\n</p>\n</dd>\n<dt><code>popen(command, flags, errorObj = undefined)</code></dt>\n<dd><p>Open a process by creating a pipe (wrapper to the libc\n<code>popen()</code>). Return the FILE\nobject or <code>null</code> in case of I/O error. If <code>errorObj</code> is not\nundefined, set its <code>errno</code> property to the error code or to 0 if\nno error occured.\n</p>\n</dd>\n<dt><code>fdopen(fd, flags, errorObj = undefined)</code></dt>\n<dd><p>Open a file from a file handle (wrapper to the libc\n<code>fdopen()</code>). Return the FILE\nobject or <code>null</code> in case of I/O error. If <code>errorObj</code> is not\nundefined, set its <code>errno</code> property to the error code or to 0 if\nno error occured.\n</p>\n</dd>\n<dt><code>tmpfile(errorObj = undefined)</code></dt>\n<dd><p>Open a temporary file. Return the FILE\nobject or <code>null</code> in case of I/O error. If <code>errorObj</code> is not\nundefined, set its <code>errno</code> property to the error code or to 0 if\nno error occured.\n</p>\n</dd>\n<dt><code>puts(str)</code></dt>\n<dd><p>Equivalent to <code>std.out.puts(str)</code>.\n</p>\n</dd>\n<dt><code>printf(fmt, ...args)</code></dt>\n<dd><p>Equivalent to <code>std.out.printf(fmt, ...args)</code>.\n</p>\n</dd>\n<dt><code>sprintf(fmt, ...args)</code></dt>\n<dd><p>Equivalent to the libc sprintf().\n</p>\n</dd>\n<dt><code>in</code></dt>\n<dt><code>out</code></dt>\n<dt><code>err</code></dt>\n<dd><p>Wrappers to the libc file <code>stdin</code>, <code>stdout</code>, <code>stderr</code>.\n</p>\n</dd>\n<dt><code>SEEK_SET</code></dt>\n<dt><code>SEEK_CUR</code></dt>\n<dt><code>SEEK_END</code></dt>\n<dd><p>Constants for seek().\n</p>\n</dd>\n<dt><code>Error</code></dt>\n<dd>\n<p>Enumeration object containing the integer value of common errors\n(additional error codes may be defined):\n</p>\n<dl compact=\"compact\">\n<dt><code>EINVAL</code></dt>\n<dt><code>EIO</code></dt>\n<dt><code>EACCES</code></dt>\n<dt><code>EEXIST</code></dt>\n<dt><code>ENOSPC</code></dt>\n<dt><code>ENOSYS</code></dt>\n<dt><code>EBUSY</code></dt>\n<dt><code>ENOENT</code></dt>\n<dt><code>EPERM</code></dt>\n<dt><code>EPIPE</code></dt>\n</dl>\n\n</dd>\n<dt><code>strerror(errno)</code></dt>\n<dd><p>Return a string that describes the error <code>errno</code>.\n</p>\n</dd>\n<dt><code>gc()</code></dt>\n<dd><p>Manually invoke the cycle removal algorithm. The cycle removal\nalgorithm is automatically started when needed, so this function is\nuseful in case of specific memory constraints or for testing.\n</p>\n</dd>\n<dt><code>getenv(name)</code></dt>\n<dd><p>Return the value of the environment variable <code>name</code> or\n<code>undefined</code> if it is not defined.\n</p>\n</dd>\n<dt><code>setenv(name, value)</code></dt>\n<dd><p>Set the value of the environment variable <code>name</code> to the string\n<code>value</code>.\n</p>\n</dd>\n<dt><code>unsetenv(name)</code></dt>\n<dd><p>Delete the environment variable <code>name</code>.\n</p>\n</dd>\n<dt><code>getenviron()</code></dt>\n<dd><p>Return an object containing the environment variables as key-value pairs.\n</p>\n</dd>\n<dt><code>urlGet(url, options = undefined)</code></dt>\n<dd>\n<p>Download <code>url</code> using the <samp>curl</samp> command line\nutility. <code>options</code> is an optional object containing the following\noptional properties:\n</p>\n<dl compact=\"compact\">\n<dt><code>binary</code></dt>\n<dd><p>Boolean (default = false). If true, the response is an ArrayBuffer\n  instead of a string. When a string is returned, the data is assumed\n  to be UTF-8 encoded.\n</p>\n</dd>\n<dt><code>full</code></dt>\n<dd>  \n<p>Boolean (default = false). If true, return the an object contains\n  the properties <code>response</code> (response content),\n  <code>responseHeaders</code> (headers separated by CRLF), <code>status</code>\n  (status code). <code>response</code> is <code>null</code> is case of protocol or\n  network error. If <code>full</code> is false, only the response is\n  returned if the status is between 200 and 299. Otherwise <code>null</code>\n  is returned.\n</p>\n</dd>\n</dl>\n\n</dd>\n<dt><code>parseExtJSON(str)</code></dt>\n<dd>\n<p>Parse <code>str</code> using a superset of <code>JSON.parse</code>. The\n  following extensions are accepted:\n</p>\n<ul>\n<li> Single line and multiline comments\n  </li><li> unquoted properties (ASCII-only Javascript identifiers)\n  </li><li> trailing comma in array and object definitions\n  </li><li> single quoted strings\n  </li><li> <code>\\f</code> and <code>\\v</code> are accepted as space characters\n  </li><li> leading plus in numbers\n  </li><li> octal (<code>0o</code> prefix) and hexadecimal (<code>0x</code> prefix) numbers\n  </li></ul>\n</dd>\n</dl>\n\n<p>FILE prototype:\n</p>\n<dl compact=\"compact\">\n<dt><code>close()</code></dt>\n<dd><p>Close the file. Return 0 if OK or <code>-errno</code> in case of I/O error.\n</p></dd>\n<dt><code>puts(str)</code></dt>\n<dd><p>Outputs the string with the UTF-8 encoding.\n</p></dd>\n<dt><code>printf(fmt, ...args)</code></dt>\n<dd><p>Formatted printf.\n</p>\n<p>The same formats as the standard C library <code>printf</code> are\nsupported. Integer format types (e.g. <code>%d</code>) truncate the Numbers\nor BigInts to 32 bits. Use the <code>l</code> modifier (e.g. <code>%ld</code>) to\ntruncate to 64 bits.\n</p>\n</dd>\n<dt><code>flush()</code></dt>\n<dd><p>Flush the buffered file.\n</p></dd>\n<dt><code>seek(offset, whence)</code></dt>\n<dd><p>Seek to a give file position (whence is\n<code>std.SEEK_*</code>). <code>offset</code> can be a number or a bigint. Return\n0 if OK or <code>-errno</code> in case of I/O error.\n</p></dd>\n<dt><code>tell()</code></dt>\n<dd><p>Return the current file position.\n</p></dd>\n<dt><code>tello()</code></dt>\n<dd><p>Return the current file position as a bigint.\n</p></dd>\n<dt><code>eof()</code></dt>\n<dd><p>Return true if end of file.\n</p></dd>\n<dt><code>fileno()</code></dt>\n<dd><p>Return the associated OS handle.\n</p></dd>\n<dt><code>error()</code></dt>\n<dd><p>Return true if there was an error.\n</p></dd>\n<dt><code>clearerr()</code></dt>\n<dd><p>Clear the error indication.\n</p>\n</dd>\n<dt><code>read(buffer, position, length)</code></dt>\n<dd><p>Read <code>length</code> bytes from the file to the ArrayBuffer <code>buffer</code> at byte\nposition <code>position</code> (wrapper to the libc <code>fread</code>).\n</p>\n</dd>\n<dt><code>write(buffer, position, length)</code></dt>\n<dd><p>Write <code>length</code> bytes to the file from the ArrayBuffer <code>buffer</code> at byte\nposition <code>position</code> (wrapper to the libc <code>fwrite</code>).\n</p>\n</dd>\n<dt><code>getline()</code></dt>\n<dd><p>Return the next line from the file, assuming UTF-8 encoding, excluding\nthe trailing line feed.\n</p>\n</dd>\n<dt><code>readAsString(max_size = undefined)</code></dt>\n<dd><p>Read <code>max_size</code> bytes from the file and return them as a string\nassuming UTF-8 encoding. If <code>max_size</code> is not present, the file\nis read up its end.\n</p>\n</dd>\n<dt><code>getByte()</code></dt>\n<dd><p>Return the next byte from the file. Return -1 if the end of file is reached.\n</p>\n</dd>\n<dt><code>putByte(c)</code></dt>\n<dd><p>Write one byte to the file.\n</p></dd>\n</dl>\n\n<a name=\"os-module\"></a>\n<h4 class=\"subsection\">3.3.3 <code>os</code> module</h4>\n\n<p>The <code>os</code> module provides Operating System specific functions:\n</p>\n<ul>\n<li> low level file access\n</li><li> signals\n</li><li> timers\n</li><li> asynchronous I/O\n</li><li> workers (threads)\n</li></ul>\n\n<p>The OS functions usually return 0 if OK or an OS specific negative\nerror code.\n</p>\n<p>Available exports:\n</p>\n<dl compact=\"compact\">\n<dt><code>open(filename, flags, mode = 0o666)</code></dt>\n<dd><p>Open a file. Return a handle or &lt; 0 if error.\n</p>\n</dd>\n<dt><code>O_RDONLY</code></dt>\n<dt><code>O_WRONLY</code></dt>\n<dt><code>O_RDWR</code></dt>\n<dt><code>O_APPEND</code></dt>\n<dt><code>O_CREAT</code></dt>\n<dt><code>O_EXCL</code></dt>\n<dt><code>O_TRUNC</code></dt>\n<dd><p>POSIX open flags.\n</p>\n</dd>\n<dt><code>O_TEXT</code></dt>\n<dd><p>(Windows specific). Open the file in text mode. The default is binary mode.\n</p>\n</dd>\n<dt><code>close(fd)</code></dt>\n<dd><p>Close the file handle <code>fd</code>.\n</p>\n</dd>\n<dt><code>seek(fd, offset, whence)</code></dt>\n<dd><p>Seek in the file. Use <code>std.SEEK_*</code> for\n<code>whence</code>. <code>offset</code> is either a number or a bigint. If\n<code>offset</code> is a bigint, a bigint is returned too.\n</p>\n</dd>\n<dt><code>read(fd, buffer, offset, length)</code></dt>\n<dd><p>Read <code>length</code> bytes from the file handle <code>fd</code> to the\nArrayBuffer <code>buffer</code> at byte position <code>offset</code>.\nReturn the number of read bytes or &lt; 0 if error.\n</p>\n</dd>\n<dt><code>write(fd, buffer, offset, length)</code></dt>\n<dd><p>Write <code>length</code> bytes to the file handle <code>fd</code> from the\nArrayBuffer <code>buffer</code> at byte position <code>offset</code>.\nReturn the number of written bytes or &lt; 0 if error.\n</p>\n</dd>\n<dt><code>isatty(fd)</code></dt>\n<dd><p>Return <code>true</code> is <code>fd</code> is a TTY (terminal) handle.\n</p>\n</dd>\n<dt><code>ttyGetWinSize(fd)</code></dt>\n<dd><p>Return the TTY size as <code>[width, height]</code> or <code>null</code> if not available.\n</p>\n</dd>\n<dt><code>ttySetRaw(fd)</code></dt>\n<dd><p>Set the TTY in raw mode.\n</p>\n</dd>\n<dt><code>remove(filename)</code></dt>\n<dd><p>Remove a file. Return 0 if OK or <code>-errno</code>.\n</p>\n</dd>\n<dt><code>rename(oldname, newname)</code></dt>\n<dd><p>Rename a file. Return 0 if OK or <code>-errno</code>.\n</p>\n</dd>\n<dt><code>realpath(path)</code></dt>\n<dd><p>Return <code>[str, err]</code> where <code>str</code> is the canonicalized absolute\npathname of <code>path</code> and <code>err</code> the error code.\n</p>\n</dd>\n<dt><code>getcwd()</code></dt>\n<dd><p>Return <code>[str, err]</code> where <code>str</code> is the current working directory\nand <code>err</code> the error code.\n</p>\n</dd>\n<dt><code>chdir(path)</code></dt>\n<dd><p>Change the current directory. Return 0 if OK or <code>-errno</code>.\n</p>\n</dd>\n<dt><code>mkdir(path, mode = 0o777)</code></dt>\n<dd><p>Create a directory at <code>path</code>. Return 0 if OK or <code>-errno</code>.\n</p>\n</dd>\n<dt><code>stat(path)</code></dt>\n<dt><code>lstat(path)</code></dt>\n<dd>\n<p>Return <code>[obj, err]</code> where <code>obj</code> is an object containing the\nfile status of <code>path</code>. <code>err</code> is the error code. The\nfollowing fields are defined in <code>obj</code>: dev, ino, mode, nlink,\nuid, gid, rdev, size, blocks, atime, mtime, ctime. The times are\nspecified in milliseconds since 1970. <code>lstat()</code> is the same as\n<code>stat()</code> excepts that it returns information about the link\nitself.\n</p>\n</dd>\n<dt><code>S_IFMT</code></dt>\n<dt><code>S_IFIFO</code></dt>\n<dt><code>S_IFCHR</code></dt>\n<dt><code>S_IFDIR</code></dt>\n<dt><code>S_IFBLK</code></dt>\n<dt><code>S_IFREG</code></dt>\n<dt><code>S_IFSOCK</code></dt>\n<dt><code>S_IFLNK</code></dt>\n<dt><code>S_ISGID</code></dt>\n<dt><code>S_ISUID</code></dt>\n<dd><p>Constants to interpret the <code>mode</code> property returned by\n<code>stat()</code>. They have the same value as in the C system header\n<samp>sys/stat.h</samp>.\n</p>\n</dd>\n<dt><code>utimes(path, atime, mtime)</code></dt>\n<dd><p>Change the access and modification times of the file <code>path</code>. The\ntimes are specified in milliseconds since 1970. Return 0 if OK or <code>-errno</code>.\n</p>\n</dd>\n<dt><code>symlink(target, linkpath)</code></dt>\n<dd><p>Create a link at <code>linkpath</code> containing the string <code>target</code>. Return 0 if OK or <code>-errno</code>.\n</p>\n</dd>\n<dt><code>readlink(path)</code></dt>\n<dd><p>Return <code>[str, err]</code> where <code>str</code> is the link target and <code>err</code>\nthe error code.\n</p>\n</dd>\n<dt><code>readdir(path)</code></dt>\n<dd><p>Return <code>[array, err]</code> where <code>array</code> is an array of strings\ncontaining the filenames of the directory <code>path</code>. <code>err</code> is\nthe error code.\n</p>\n</dd>\n<dt><code>setReadHandler(fd, func)</code></dt>\n<dd><p>Add a read handler to the file handle <code>fd</code>. <code>func</code> is called\neach time there is data pending for <code>fd</code>. A single read handler\nper file handle is supported. Use <code>func = null</code> to remove the\nhandler.\n</p>\n</dd>\n<dt><code>setWriteHandler(fd, func)</code></dt>\n<dd><p>Add a write handler to the file handle <code>fd</code>. <code>func</code> is\ncalled each time data can be written to <code>fd</code>. A single write\nhandler per file handle is supported. Use <code>func = null</code> to remove\nthe handler.\n</p>\n</dd>\n<dt><code>signal(signal, func)</code></dt>\n<dd><p>Call the function <code>func</code> when the signal <code>signal</code>\nhappens. Only a single handler per signal number is supported. Use\n<code>null</code> to set the default handler or <code>undefined</code> to ignore\nthe signal. Signal handlers can only be defined in the main thread.\n</p>\n</dd>\n<dt><code>SIGINT</code></dt>\n<dt><code>SIGABRT</code></dt>\n<dt><code>SIGFPE</code></dt>\n<dt><code>SIGILL</code></dt>\n<dt><code>SIGSEGV</code></dt>\n<dt><code>SIGTERM</code></dt>\n<dd><p>POSIX signal numbers.\n</p>\n</dd>\n<dt><code>kill(pid, sig)</code></dt>\n<dd><p>Send the signal <code>sig</code> to the process <code>pid</code>.\n</p>\n</dd>\n<dt><code>exec(args[, options])</code></dt>\n<dd><p>Execute a process with the arguments <code>args</code>. <code>options</code> is an\nobject containing optional parameters:\n</p>\n<dl compact=\"compact\">\n<dt><code>block</code></dt>\n<dd><p>Boolean (default = true). If true, wait until the process is\n  terminated. In this case, <code>exec</code> return the exit code if positive\n  or the negated signal number if the process was interrupted by a\n  signal. If false, do not block and return the process id of the child.\n</p>  \n</dd>\n<dt><code>usePath</code></dt>\n<dd><p>Boolean (default = true). If true, the file is searched in the\n  <code>PATH</code> environment variable.\n</p>\n</dd>\n<dt><code>file</code></dt>\n<dd><p>String (default = <code>args[0]</code>). Set the file to be executed.\n</p>\n</dd>\n<dt><code>cwd</code></dt>\n<dd><p>String. If present, set the working directory of the new process.\n</p>\n</dd>\n<dt><code>stdin</code></dt>\n<dt><code>stdout</code></dt>\n<dt><code>stderr</code></dt>\n<dd><p>If present, set the handle in the child for stdin, stdout or stderr.\n</p>\n</dd>\n<dt><code>env</code></dt>\n<dd><p>Object. If present, set the process environment from the object\n  key-value pairs. Otherwise use the same environment as the current\n  process.\n</p>\n</dd>\n<dt><code>uid</code></dt>\n<dd><p>Integer. If present, the process uid with <code>setuid</code>.\n</p>\n</dd>\n<dt><code>gid</code></dt>\n<dd><p>Integer. If present, the process gid with <code>setgid</code>.\n</p>\n</dd>\n</dl>\n\n</dd>\n<dt><code>waitpid(pid, options)</code></dt>\n<dd><p><code>waitpid</code> Unix system call. Return the array <code>[ret,\nstatus]</code>. <code>ret</code> contains <code>-errno</code> in case of error.\n</p>\n</dd>\n<dt><code>WNOHANG</code></dt>\n<dd><p>Constant for the <code>options</code> argument of <code>waitpid</code>.\n</p>\n</dd>\n<dt><code>dup(fd)</code></dt>\n<dd><p><code>dup</code> Unix system call.\n</p>\n</dd>\n<dt><code>dup2(oldfd, newfd)</code></dt>\n<dd><p><code>dup2</code> Unix system call.\n</p>\n</dd>\n<dt><code>pipe()</code></dt>\n<dd><p><code>pipe</code> Unix system call. Return two handles as <code>[read_fd,\nwrite_fd]</code> or null in case of error.\n</p>\n</dd>\n<dt><code>sleep(delay_ms)</code></dt>\n<dd><p>Sleep during <code>delay_ms</code> milliseconds.\n</p>\n</dd>\n<dt><code>setTimeout(func, delay)</code></dt>\n<dd><p>Call the function <code>func</code> after <code>delay</code> ms. Return a handle\nto the timer.\n</p>\n</dd>\n<dt><code>clearTimeout(handle)</code></dt>\n<dd><p>Cancel a timer.\n</p>\n</dd>\n<dt><code>platform</code></dt>\n<dd><p>Return a string representing the platform: <code>&quot;linux&quot;</code>, <code>&quot;darwin&quot;</code>,\n<code>&quot;win32&quot;</code> or <code>&quot;js&quot;</code>.\n</p>\n</dd>\n<dt><code>Worker(module_filename)</code></dt>\n<dd><p>Constructor to create a new thread (worker) with an API close to the\n<code>WebWorkers</code>. <code>module_filename</code> is a string specifying the\nmodule filename which is executed in the newly created thread. As for\ndynamically imported module, it is relative to the current script or\nmodule path. Threads normally don&rsquo;t share any data and communicate\nbetween each other with messages. Nested workers are not supported. An\nexample is available in <samp>tests/test_worker.js</samp>.\n</p>\n<p>The worker class has the following static properties:\n</p>\n<dl compact=\"compact\">\n<dt><code>parent</code></dt>\n<dd><p>In the created worker, <code>Worker.parent</code> represents the parent\n  worker and is used to send or receive messages.\n  </p></dd>\n</dl>\n\n<p>The worker instances have the following properties:\n</p>\n<dl compact=\"compact\">\n<dt><code>postMessage(msg)</code></dt>\n<dd>  \n<p>Send a message to the corresponding worker. <code>msg</code> is cloned in\n  the destination worker using an algorithm similar to the <code>HTML</code>\n  structured clone algorithm. <code>SharedArrayBuffer</code> are shared\n  between workers.\n</p>\n<p>Current limitations: <code>Map</code> and <code>Set</code> are not supported\n  yet.\n</p>\n</dd>\n<dt><code>onmessage</code></dt>\n<dd>\n<p>Getter and setter. Set a function which is called each time a\n  message is received. The function is called with a single\n  argument. It is an object with a <code>data</code> property containing the\n  received message. The thread is not terminated if there is at least\n  one non <code>null</code> <code>onmessage</code> handler.\n</p>\n</dd>\n</dl>\n\n</dd>\n</dl>\n\n<a name=\"QuickJS-C-API\"></a>\n<h3 class=\"section\">3.4 QuickJS C API</h3>\n\n<p>The C API was designed to be simple and efficient. The C API is\ndefined in the header <code>quickjs.h</code>.\n</p>\n<a name=\"Runtime-and-contexts\"></a>\n<h4 class=\"subsection\">3.4.1 Runtime and contexts</h4>\n\n<p><code>JSRuntime</code> represents a Javascript runtime corresponding to an\nobject heap. Several runtimes can exist at the same time but they\ncannot exchange objects. Inside a given runtime, no multi-threading is\nsupported.\n</p>\n<p><code>JSContext</code> represents a Javascript context (or Realm). Each\nJSContext has its own global objects and system objects. There can be\nseveral JSContexts per JSRuntime and they can share objects, similar\nto frames of the same origin sharing Javascript objects in a\nweb browser.\n</p>\n<a name=\"JSValue\"></a>\n<h4 class=\"subsection\">3.4.2 JSValue</h4>\n\n<p><code>JSValue</code> represents a Javascript value which can be a primitive\ntype or an object. Reference counting is used, so it is important to\nexplicitly duplicate (<code>JS_DupValue()</code>, increment the reference\ncount) or free (<code>JS_FreeValue()</code>, decrement the reference count)\nJSValues.\n</p>\n<a name=\"C-functions\"></a>\n<h4 class=\"subsection\">3.4.3 C functions</h4>\n\n<p>C functions can be created with\n<code>JS_NewCFunction()</code>. <code>JS_SetPropertyFunctionList()</code> is a\nshortcut to easily add functions, setters and getters properties to a\ngiven object.\n</p>\n<p>Unlike other embedded Javascript engines, there is no implicit stack,\nso C functions get their parameters as normal C parameters. As a\ngeneral rule, C functions take constant <code>JSValue</code>s as parameters\n(so they don&rsquo;t need to free them) and return a newly allocated (=live)\n<code>JSValue</code>.\n</p>\n<a name=\"Exceptions\"></a>\n<h4 class=\"subsection\">3.4.4 Exceptions</h4>\n\n<p>Exceptions: most C functions can return a Javascript exception. It\nmust be explicitly tested and handled by the C code. The specific\n<code>JSValue</code> <code>JS_EXCEPTION</code> indicates that an exception\noccurred. The actual exception object is stored in the\n<code>JSContext</code> and can be retrieved with <code>JS_GetException()</code>.\n</p>\n<a name=\"Script-evaluation\"></a>\n<h4 class=\"subsection\">3.4.5 Script evaluation</h4>\n\n<p>Use <code>JS_Eval()</code> to evaluate a script or module source.\n</p>\n<p>If the script or module was compiled to bytecode with <code>qjsc</code>, it\ncan be evaluated by calling <code>js_std_eval_binary()</code>. The advantage\nis that no compilation is needed so it is faster and smaller because\nthe compiler can be removed from the executable if no <code>eval</code> is\nrequired.\n</p>\n<p>Note: the bytecode format is linked to a given QuickJS\nversion. Moreover, no security check is done before its\nexecution. Hence the bytecode should not be loaded from untrusted\nsources. That&rsquo;s why there is no option to output the bytecode to a\nbinary file in <code>qjsc</code>.\n</p>\n<a name=\"JS-Classes\"></a>\n<h4 class=\"subsection\">3.4.6 JS Classes</h4>\n\n<p>C opaque data can be attached to a Javascript object. The type of the\nC opaque data is determined with the class ID (<code>JSClassID</code>) of\nthe object. Hence the first step is to register a new class ID and JS\nclass (<code>JS_NewClassID()</code>, <code>JS_NewClass()</code>). Then you can\ncreate objects of this class with <code>JS_NewObjectClass()</code> and get or\nset the C opaque point with\n<code>JS_GetOpaque()</code>/<code>JS_SetOpaque()</code>.\n</p>\n<p>When defining a new JS class, it is possible to declare a finalizer\nwhich is called when the object is destroyed. The finalizer should be\nused to release C resources. It is invalid to execute JS code from\nit. A <code>gc_mark</code> method can be provided so that the cycle removal\nalgorithm can find the other objects referenced by this object. Other\nmethods are available to define exotic object behaviors.\n</p>\n<p>The Class ID are globally allocated (i.e. for all runtimes). The\nJSClass are allocated per <code>JSRuntime</code>. <code>JS_SetClassProto()</code>\nis used to define a prototype for a given class in a given\nJSContext. <code>JS_NewObjectClass()</code> sets this prototype in the\ncreated object.\n</p>\n<p>Examples are available in <samp>quickjs-libc.c</samp>.\n</p>\n<a name=\"C-Modules\"></a>\n<h4 class=\"subsection\">3.4.7 C Modules</h4>\n\n<p>Native ES6 modules are supported and can be dynamically or statically\nlinked. Look at the <samp>test_bjson</samp> and <samp>bjson.so</samp>\nexamples. The standard library <samp>quickjs-libc.c</samp> is also a good example\nof a native module.\n</p>\n<a name=\"Memory-handling\"></a>\n<h4 class=\"subsection\">3.4.8 Memory handling</h4>\n\n<p>Use <code>JS_SetMemoryLimit()</code> to set a global memory allocation limit\nto a given JSRuntime.\n</p>\n<p>Custom memory allocation functions can be provided with\n<code>JS_NewRuntime2()</code>.\n</p>\n<p>The maximum system stack size can be set with <code>JS_SetMaxStackSize()</code>.\n</p>\n<a name=\"Execution-timeout-and-interrupts\"></a>\n<h4 class=\"subsection\">3.4.9 Execution timeout and interrupts</h4>\n\n<p>Use <code>JS_SetInterruptHandler()</code> to set a callback which is\nregularly called by the engine when it is executing code. This\ncallback can be used to implement an execution timeout.\n</p>\n<p>It is used by the command line interpreter to implement a\n<code>Ctrl-C</code> handler.\n</p>\n<a name=\"Internals\"></a>\n<h2 class=\"chapter\">4 Internals</h2>\n\n<a name=\"Bytecode\"></a>\n<h3 class=\"section\">4.1 Bytecode</h3>\n\n<p>The compiler generates bytecode directly with no intermediate\nrepresentation such as a parse tree, hence it is very fast. Several\noptimizations passes are done over the generated bytecode.\n</p>\n<p>A stack-based bytecode was chosen because it is simple and generates \ncompact code.\n</p>\n<p>For each function, the maximum stack size is computed at compile time so that\nno runtime stack overflow tests are needed.\n</p>\n<p>A separate compressed line number table is maintained for the debug\ninformation.\n</p>\n<p>Access to closure variables is optimized and is almost as fast as local\nvariables.\n</p>\n<p>Direct <code>eval</code> in strict mode is optimized.\n</p>\n<a name=\"Executable-generation\"></a>\n<h3 class=\"section\">4.2 Executable generation</h3>\n\n<a name=\"qjsc-compiler-1\"></a>\n<h4 class=\"subsection\">4.2.1 <code>qjsc</code> compiler</h4>\n\n<p>The <code>qjsc</code> compiler generates C sources from Javascript files. By\ndefault the C sources are compiled with the system compiler\n(<code>gcc</code> or <code>clang</code>).\n</p>\n<p>The generated C source contains the bytecode of the compiled functions\nor modules. If a full complete executable is needed, it also\ncontains a <code>main()</code> function with the necessary C code to initialize the\nJavascript engine and to load and execute the compiled functions and\nmodules.\n</p>\n<p>Javascript code can be mixed with C modules.\n</p>\n<p>In order to have smaller executables, specific Javascript features can\nbe disabled, in particular <code>eval</code> or the regular expressions. The\ncode removal relies on the Link Time Optimization of the system\ncompiler.\n</p>\n<a name=\"Binary-JSON\"></a>\n<h4 class=\"subsection\">4.2.2 Binary JSON</h4>\n\n<p><code>qjsc</code> works by compiling scripts or modules and then serializing\nthem to a binary format. A subset of this format (without functions or\nmodules) can be used as binary JSON. The example <samp>test_bjson.js</samp>\nshows how to use it.\n</p>\n<p>Warning: the binary JSON format may change without notice, so it\nshould not be used to store persistent data. The <samp>test_bjson.js</samp>\nexample is only used to test the binary object format functions.\n</p>\n<a name=\"Runtime\"></a>\n<h3 class=\"section\">4.3 Runtime</h3>\n\n<a name=\"Strings\"></a>\n<h4 class=\"subsection\">4.3.1 Strings</h4>\n\n<p>Strings are stored either as an 8 bit or a 16 bit array of\ncharacters. Hence random access to characters is always fast.\n</p>\n<p>The C API provides functions to convert Javascript Strings to C UTF-8 encoded\nstrings. The most common case where the Javascript string contains\nonly ASCII characters involves no copying.\n</p>\n<a name=\"Objects\"></a>\n<h4 class=\"subsection\">4.3.2 Objects</h4>\n\n<p>The object shapes (object prototype, property names and flags) are shared\nbetween objects to save memory.\n</p>\n<p>Arrays with no holes (except at the end of the array) are optimized.\n</p>\n<p>TypedArray accesses are optimized.\n</p>\n<a name=\"Atoms\"></a>\n<h4 class=\"subsection\">4.3.3 Atoms</h4>\n\n<p>Object property names and some strings are stored as Atoms (unique\nstrings) to save memory and allow fast comparison. Atoms are\nrepresented as a 32 bit integer. Half of the atom range is reserved for\nimmediate integer literals from <em>0</em> to <em>2^{31}-1</em>.\n</p>\n<a name=\"Numbers\"></a>\n<h4 class=\"subsection\">4.3.4 Numbers</h4>\n\n<p>Numbers are represented either as 32-bit signed integers or 64-bit IEEE-754\nfloating point values. Most operations have fast paths for the 32-bit\ninteger case.\n</p>\n<a name=\"Garbage-collection\"></a>\n<h4 class=\"subsection\">4.3.5 Garbage collection</h4>\n\n<p>Reference counting is used to free objects automatically and\ndeterministically. A separate cycle removal pass is done when the allocated\nmemory becomes too large. The cycle removal algorithm only uses the\nreference counts and the object content, so no explicit garbage\ncollection roots need to be manipulated in the C code.\n</p>\n<a name=\"JSValue-1\"></a>\n<h4 class=\"subsection\">4.3.6 JSValue</h4>\n\n<p>It is a Javascript value which can be a primitive type (such as\nNumber, String, ...) or an Object. NaN boxing is used in the 32-bit version\nto store 64-bit floating point numbers. The representation is\noptimized so that 32-bit integers and reference counted values can be\nefficiently tested.\n</p>\n<p>In 64-bit code, JSValue are 128-bit large and no NaN boxing is used. The\nrationale is that in 64-bit code memory usage is less critical.\n</p>\n<p>In both cases (32 or 64 bits), JSValue exactly fits two CPU registers,\nso it can be efficiently returned by C functions.\n</p>\n<a name=\"Function-call\"></a>\n<h4 class=\"subsection\">4.3.7 Function call</h4>\n\n<p>The engine is optimized so that function calls are fast. The system\nstack holds the Javascript parameters and local variables.\n</p>\n<a name=\"RegExp\"></a>\n<h3 class=\"section\">4.4 RegExp</h3>\n\n<p>A specific regular expression engine was developed. It is both small\nand efficient and supports all the ES2020 features including the\nUnicode properties. As the Javascript compiler, it directly generates\nbytecode without a parse tree.\n</p>\n<p>Backtracking with an explicit stack is used so that there is no\nrecursion on the system stack. Simple quantifiers are specifically\noptimized to avoid recursions.\n</p>\n<p>Infinite recursions coming from quantifiers with empty terms are\navoided.\n</p>\n<p>The full regexp library weights about 15 KiB (x86 code), excluding the\nUnicode library.\n</p>\n<a name=\"Unicode\"></a>\n<h3 class=\"section\">4.5 Unicode</h3>\n\n<p>A specific Unicode library was developed so that there is no\ndependency on an external large Unicode library such as ICU. All the\nUnicode tables are compressed while keeping a reasonable access\nspeed.\n</p>\n<p>The library supports case conversion, Unicode normalization, Unicode\nscript queries, Unicode general category queries and all Unicode\nbinary properties.\n</p>\n<p>The full Unicode library weights about 45 KiB (x86 code).\n</p>\n<a name=\"BigInt_002c-BigFloat_002c-BigDecimal\"></a>\n<h3 class=\"section\">4.6 BigInt, BigFloat, BigDecimal</h3>\n\n<p>BigInt, BigFloat and BigDecimal are implemented with the <code>libbf</code>\nlibrary<a name=\"DOCF7\" href=\"#FOOT7\"><sup>7</sup></a>. It weights about 90\nKiB (x86 code) and provides arbitrary precision IEEE 754 floating\npoint operations and transcendental functions with exact rounding.\n</p>\n<a name=\"License\"></a>\n<h2 class=\"chapter\">5 License</h2>\n\n<p>QuickJS is released under the MIT license.\n</p>\n<p>Unless otherwise specified, the QuickJS sources are copyright Fabrice\nBellard and Charlie Gordon.\n</p>\n<div class=\"footnote\">\n<hr>\n<h4 class=\"footnotes-heading\">Footnotes</h4>\n\n<h3><a name=\"FOOT1\" href=\"#DOCF1\">(1)</a></h3>\n<p><a href=\"https://tc39.es/ecma262/\">https://tc39.es/ecma262/</a></p>\n<h3><a name=\"FOOT2\" href=\"#DOCF2\">(2)</a></h3>\n<p><a href=\"https://github.com/tc39/test262\">https://github.com/tc39/test262</a></p>\n<h3><a name=\"FOOT3\" href=\"#DOCF3\">(3)</a></h3>\n<p><a href=\"https://tc39.github.io/ecma262/\">https://tc39.github.io/ecma262/</a></p>\n<h3><a name=\"FOOT4\" href=\"#DOCF4\">(4)</a></h3>\n<p>The old\nES5.1 tests can be extracted with <code>git clone --single-branch\n--branch es5-tests https://github.com/tc39/test262.git test262o</code></p>\n<h3><a name=\"FOOT5\" href=\"#DOCF5\">(5)</a></h3>\n<p><a href=\"https://github.com/bterlson/test262-harness\">https://github.com/bterlson/test262-harness</a></p>\n<h3><a name=\"FOOT6\" href=\"#DOCF6\">(6)</a></h3>\n<p>We believe the current specification of tails calls is too complicated and presents limited practical interests.</p>\n<h3><a name=\"FOOT7\" href=\"#DOCF7\">(7)</a></h3>\n<p><a href=\"https://bellard.org/libbf\">https://bellard.org/libbf</a></p>\n</div>\n<hr>\n\n\n\n</body>\n</html>\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/doc/quickjs.texi",
    "content": "\\input texinfo\n\n@iftex\n@afourpaper\n@headings double\n@end iftex\n\n@titlepage\n@afourpaper\n@sp 7\n@center @titlefont{QuickJS Javascript Engine}\n@sp 3\n@end titlepage\n\n@setfilename spec.info\n@settitle QuickJS Javascript Engine\n\n@contents\n\n@chapter Introduction\n\nQuickJS is a small and embeddable Javascript engine. It supports the\nES2020 specification\n@footnote{@url{https://tc39.es/ecma262/}}\nincluding modules, asynchronous generators, proxies and BigInt.\n\nIt supports mathematical extensions such as big decimal float float\nnumbers (BigDecimal), big binary floating point numbers (BigFloat),\nand operator overloading.\n\n@section Main Features\n\n@itemize\n\n@item Small and easily embeddable: just a few C files, no external dependency, 210 KiB of x86 code for a simple ``hello world'' program.\n\n@item Fast interpreter with very low startup time: runs the 69000 tests of the ECMAScript Test Suite@footnote{@url{https://github.com/tc39/test262}} in about 95 seconds on a single core of a desktop PC. The complete life cycle of a runtime instance completes in less than 300 microseconds.\n\n@item Almost complete ES2020 support including modules, asynchronous\ngenerators and full Annex B support (legacy web compatibility). Many\nfeatures from the upcoming ES2021 specification\n@footnote{@url{https://tc39.github.io/ecma262/}} are also supported.\n\n@item Passes nearly 100% of the ECMAScript Test Suite tests when selecting the ES2020 features.\n\n@item Compile Javascript sources to executables with no external dependency.\n\n@item Garbage collection using reference counting (to reduce memory usage and have deterministic behavior) with cycle removal.\n\n@item Mathematical extensions: BigDecimal, BigFloat, operator overloading, bigint mode, math mode.\n\n@item Command line interpreter with contextual colorization and completion implemented in Javascript.\n\n@item Small built-in standard library with C library wrappers.\n\n@end itemize\n\n@chapter Usage\n\n@section Installation\n\nA Makefile is provided to compile the engine on Linux or MacOS/X.  A\npreliminary Windows support is available thru cross compilation on a\nLinux host with the MingGW tools.\n\nEdit the top of the @code{Makefile} if you wish to select specific\noptions then run @code{make}.\n\nYou can type @code{make install} as root if you wish to install the binaries and support files to\n@code{/usr/local} (this is not necessary to use QuickJS).\n\n@section Quick start\n\n@code{qjs} is the command line interpreter (Read-Eval-Print Loop). You can pass\nJavascript files and/or expressions as arguments to execute them:\n\n@example\n./qjs examples/hello.js\n@end example\n\n@code{qjsc} is the command line compiler:\n\n@example\n./qjsc -o hello examples/hello.js\n./hello\n@end example\n\ngenerates a @code{hello} executable with no external dependency.\n\n@section Command line options\n\n@subsection @code{qjs} interpreter\n\n@verbatim\nusage: qjs [options] [file [args]]\n@end verbatim\n\nOptions are:\n@table @code\n@item -h\n@item --help\nList options.\n\n@item -e @code{EXPR}\n@item --eval @code{EXPR}\nEvaluate EXPR.\n\n@item -i\n@item --interactive\nGo to interactive mode (it is not the default when files are provided on the command line).\n\n@item -m\n@item --module\nLoad as ES6 module (default=autodetect). A module is autodetected if\nthe filename extension is @code{.mjs} or if the first keyword of the\nsource is @code{import}.\n\n@item --script\nLoad as ES6 script (default=autodetect).\n\n@item --bignum\nEnable the bignum extensions: BigDecimal object, BigFloat object and\nthe @code{\"use math\"} directive.\n\n@item -I file\n@item --include file\nInclude an additional file.\n\n@end table\n\nAdvanced options are:\n\n@table @code\n@item --std\nMake the @code{std} and @code{os} modules available to the loaded\nscript even if it is not a module.\n\n@item -d\n@item --dump\nDump the memory usage stats.\n\n@item -q\n@item --quit\njust instantiate the interpreter and quit.\n\n@end table\n\n@subsection @code{qjsc} compiler\n\n@verbatim\nusage: qjsc [options] [files]\n@end verbatim\n\nOptions are:\n@table @code\n@item -c\nOnly output bytecode in a C file. The default is to output an executable file.\n@item -e \nOutput @code{main()} and bytecode in a C file. The default is to output an\nexecutable file.\n@item -o output\nSet the output filename (default = @file{out.c} or @file{a.out}).\n\n@item -N cname\nSet the C name of the generated data.\n\n@item -m\nCompile as Javascript module (default=autodetect).\n\n@item -D module_name\nCompile a dynamically loaded module and its dependencies. This option\nis needed when your code uses the @code{import} keyword or the\n@code{os.Worker} constructor because the compiler cannot statically\nfind the name of the dynamically loaded modules.\n\n@item -M module_name[,cname]\nAdd initialization code for an external C module. See the\n@code{c_module} example.\n\n@item -x\nByte swapped output (only used for cross compilation).\n\n@item -flto\nUse link time optimization. The compilation is slower but the\nexecutable is smaller and faster. This option is automatically set\nwhen the @code{-fno-x} options are used.\n\n@item -fno-[eval|string-normalize|regexp|json|proxy|map|typedarray|promise|bigint]\nDisable selected language features to produce a smaller executable file.\n\n@item -fbignum\nEnable the bignum extensions: BigDecimal object, BigFloat object and\nthe @code{\"use math\"} directive.\n\n@end table\n\n@section @code{qjscalc} application\n\nThe @code{qjscalc} application is a superset of the @code{qjs}\ncommand line interpreter implementing a Javascript calculator with\narbitrarily large integer and floating point numbers, fractions,\ncomplex numbers, polynomials and matrices. The source code is in\n@file{qjscalc.js}. More documentation and a web version are available at\n@url{http://numcalc.com}.\n\n@section Built-in tests\n\nRun @code{make test} to run the few built-in tests included in the\nQuickJS archive.\n\n@section Test262 (ECMAScript Test Suite)\n\nA test262 runner is included in the QuickJS archive. The test262 tests\ncan be installed in the QuickJS source directory with:\n\n@example\ngit clone https://github.com/tc39/test262.git test262\ncd test262\npatch -p1 < ../tests/test262.patch\ncd ..\n@end example\n\nThe patch adds the implementation specific @code{harness} functions\nand optimizes the inefficient RegExp character classes and Unicode\nproperty escapes tests (the tests themselves are not modified, only a\nslow string initialization function is optimized).\n\nThe tests can be run with\n@example\nmake test2\n@end example\n\nThe configuration files @code{test262.conf}\n(resp. @code{test262o.conf} for the old ES5.1 tests@footnote{The old\nES5.1 tests can be extracted with @code{git clone --single-branch\n--branch es5-tests https://github.com/tc39/test262.git test262o}}))\ncontain the options to run the various tests. Tests can be excluded\nbased on features or filename.\n\nThe file @code{test262_errors.txt} contains the current list of\nerrors. The runner displays a message when a new error appears or when\nan existing error is corrected or modified. Use the @code{-u} option\nto update the current list of errors (or @code{make test2-update}).\n\nThe file @code{test262_report.txt} contains the logs of all the\ntests. It is useful to have a clearer analysis of a particular\nerror. In case of crash, the last line corresponds to the failing\ntest.\n\nUse the syntax @code{./run-test262 -c test262.conf -f filename.js} to\nrun a single test. Use the syntax @code{./run-test262 -c test262.conf\nN} to start testing at test number @code{N}.\n\nFor more information, run @code{./run-test262} to see the command line\noptions of the test262 runner.\n\n@code{run-test262} accepts the @code{-N} option to be invoked from\n@code{test262-harness}@footnote{@url{https://github.com/bterlson/test262-harness}}\nthru @code{eshost}. Unless you want to compare QuickJS with other\nengines under the same conditions, we do not recommend to run the\ntests this way as it is much slower (typically half an hour instead of\nabout 100 seconds).\n\n@chapter Specifications\n\n@section Language support\n\n@subsection ES2020 support\n\nThe ES2020 specification is almost fully supported including the Annex\nB (legacy web compatibility) and the Unicode related features.\n\nThe following features are not supported yet:\n\n@itemize\n\n@item Tail calls@footnote{We believe the current specification of tails calls is too complicated and presents limited practical interests.}\n\n@end itemize\n\n@subsection ECMA402\n\nECMA402 (Internationalization API) is not supported.\n\n@subsection Extensions\n\n@itemize\n\n@item The directive @code{\"use strip\"} indicates that the debug information (including the source code of the functions) should not be retained to save memory. As @code{\"use strict\"}, the directive can be global to a script or local to a function.\n\n@item The first line of a script beginning with @code{#!} is ignored.\n\n@end itemize\n\n@subsection Mathematical extensions\n\nThe mathematical extensions are fully backward compatible with\nstandard Javascript. See @code{jsbignum.pdf} for more information.\n\n@itemize\n\n@item @code{BigDecimal} support: arbitrary large floating point numbers in base 10.\n\n@item @code{BigFloat} support: arbitrary large floating point numbers in base 2.\n\n@item Operator overloading.\n\n@item The directive @code{\"use bigint\"} enables the bigint mode where integers are @code{BigInt} by default.\n\n@item The directive @code{\"use math\"} enables the math mode where the division and power operators on integers produce fractions. Floating point literals are @code{BigFloat} by default and integers are @code{BigInt} by default.\n\n@end itemize\n\n@section Modules\n\nES6 modules are fully supported. The default name resolution is the\nfollowing:\n\n@itemize\n\n@item Module names with a leading @code{.} or @code{..} are relative\nto the current module path.\n\n@item Module names without a leading @code{.} or @code{..} are system\nmodules, such as @code{std} or @code{os}.\n\n@item Module names ending with @code{.so} are native modules using the\nQuickJS C API.\n\n@end itemize\n\n@section Standard library\n\nThe standard library is included by default in the command line\ninterpreter. It contains the two modules @code{std} and @code{os} and\na few global objects.\n\n@subsection Global objects\n\n@table @code\n@item scriptArgs\nProvides the command line arguments. The first argument is the script name.\n@item print(...args)\nPrint the arguments separated by spaces and a trailing newline.\n@item console.log(...args)\nSame as print().\n\n@end table\n\n@subsection @code{std} module\n\nThe @code{std} module provides wrappers to the libc @file{stdlib.h}\nand @file{stdio.h} and a few other utilities.\n\nAvailable exports:\n\n@table @code\n\n@item exit(n)\nExit the process.\n\n@item evalScript(str, options = undefined)\nEvaluate the string @code{str} as a script (global\neval). @code{options} is an optional object containing the following\noptional properties:\n\n  @table @code\n  @item backtrace_barrier\n  Boolean (default = false). If true, error backtraces do not list the\n  stack frames below the evalScript.\n  @end table\n\n@item loadScript(filename)\nEvaluate the file @code{filename} as a script (global eval).\n\n@item loadFile(filename)\nLoad the file @code{filename} and return it as a string assuming UTF-8\nencoding. Return @code{null} in case of I/O error.\n\n@item open(filename, flags, errorObj = undefined)\nOpen a file (wrapper to the libc @code{fopen()}). Return the FILE\nobject or @code{null} in case of I/O error. If @code{errorObj} is not\nundefined, set its @code{errno} property to the error code or to 0 if\nno error occured.\n\n@item popen(command, flags, errorObj = undefined)\nOpen a process by creating a pipe (wrapper to the libc\n@code{popen()}). Return the FILE\nobject or @code{null} in case of I/O error. If @code{errorObj} is not\nundefined, set its @code{errno} property to the error code or to 0 if\nno error occured.\n\n@item fdopen(fd, flags, errorObj = undefined)\nOpen a file from a file handle (wrapper to the libc\n@code{fdopen()}). Return the FILE\nobject or @code{null} in case of I/O error. If @code{errorObj} is not\nundefined, set its @code{errno} property to the error code or to 0 if\nno error occured.\n\n@item tmpfile(errorObj = undefined)\nOpen a temporary file. Return the FILE\nobject or @code{null} in case of I/O error. If @code{errorObj} is not\nundefined, set its @code{errno} property to the error code or to 0 if\nno error occured.\n\n@item puts(str)\nEquivalent to @code{std.out.puts(str)}.\n\n@item printf(fmt, ...args)\nEquivalent to @code{std.out.printf(fmt, ...args)}.\n\n@item sprintf(fmt, ...args)\nEquivalent to the libc sprintf().\n\n@item in\n@item out\n@item err\nWrappers to the libc file @code{stdin}, @code{stdout}, @code{stderr}.\n\n@item SEEK_SET\n@item SEEK_CUR\n@item SEEK_END\nConstants for seek().\n\n@item Error\n\nEnumeration object containing the integer value of common errors\n(additional error codes may be defined):\n\n  @table @code\n  @item EINVAL\n  @item EIO\n  @item EACCES\n  @item EEXIST\n  @item ENOSPC\n  @item ENOSYS\n  @item EBUSY\n  @item ENOENT\n  @item EPERM\n  @item EPIPE\n  @end table\n\n@item strerror(errno)\nReturn a string that describes the error @code{errno}.\n\n@item gc()\nManually invoke the cycle removal algorithm. The cycle removal\nalgorithm is automatically started when needed, so this function is\nuseful in case of specific memory constraints or for testing.\n\n@item getenv(name)\nReturn the value of the environment variable @code{name} or\n@code{undefined} if it is not defined.\n\n@item setenv(name, value)\nSet the value of the environment variable @code{name} to the string\n@code{value}.\n\n@item unsetenv(name)\nDelete the environment variable @code{name}.\n\n@item getenviron()\nReturn an object containing the environment variables as key-value pairs.\n\n@item urlGet(url, options = undefined)\n\nDownload @code{url} using the @file{curl} command line\nutility. @code{options} is an optional object containing the following\noptional properties:\n\n  @table @code\n  @item binary\n  Boolean (default = false). If true, the response is an ArrayBuffer\n  instead of a string. When a string is returned, the data is assumed\n  to be UTF-8 encoded.\n\n  @item full\n  \n  Boolean (default = false). If true, return the an object contains\n  the properties @code{response} (response content),\n  @code{responseHeaders} (headers separated by CRLF), @code{status}\n  (status code). @code{response} is @code{null} is case of protocol or\n  network error. If @code{full} is false, only the response is\n  returned if the status is between 200 and 299. Otherwise @code{null}\n  is returned.\n\n  @end table\n\n@item parseExtJSON(str)\n\n  Parse @code{str} using a superset of @code{JSON.parse}. The\n  following extensions are accepted:\n\n  @itemize\n  @item Single line and multiline comments\n  @item unquoted properties (ASCII-only Javascript identifiers)\n  @item trailing comma in array and object definitions\n  @item single quoted strings\n  @item @code{\\f} and @code{\\v} are accepted as space characters\n  @item leading plus in numbers\n  @item octal (@code{0o} prefix) and hexadecimal (@code{0x} prefix) numbers\n  @end itemize\n@end table\n\nFILE prototype:\n\n@table @code\n@item close()\nClose the file. Return 0 if OK or @code{-errno} in case of I/O error.\n@item puts(str)\nOutputs the string with the UTF-8 encoding.\n@item printf(fmt, ...args)\nFormatted printf.\n\nThe same formats as the standard C library @code{printf} are\nsupported. Integer format types (e.g. @code{%d}) truncate the Numbers\nor BigInts to 32 bits. Use the @code{l} modifier (e.g. @code{%ld}) to\ntruncate to 64 bits.\n\n@item flush()\nFlush the buffered file.\n@item seek(offset, whence)\nSeek to a give file position (whence is\n@code{std.SEEK_*}). @code{offset} can be a number or a bigint. Return\n0 if OK or @code{-errno} in case of I/O error.\n@item tell()\nReturn the current file position.\n@item tello()\nReturn the current file position as a bigint.\n@item eof()\nReturn true if end of file.\n@item fileno()\nReturn the associated OS handle.\n@item error()\nReturn true if there was an error.\n@item clearerr()\nClear the error indication.\n\n@item read(buffer, position, length)\nRead @code{length} bytes from the file to the ArrayBuffer @code{buffer} at byte\nposition @code{position} (wrapper to the libc @code{fread}).\n\n@item write(buffer, position, length)\nWrite @code{length} bytes to the file from the ArrayBuffer @code{buffer} at byte\nposition @code{position} (wrapper to the libc @code{fwrite}).\n\n@item getline()\nReturn the next line from the file, assuming UTF-8 encoding, excluding\nthe trailing line feed.\n\n@item readAsString(max_size = undefined)\nRead @code{max_size} bytes from the file and return them as a string\nassuming UTF-8 encoding. If @code{max_size} is not present, the file\nis read up its end.\n\n@item getByte()\nReturn the next byte from the file. Return -1 if the end of file is reached.\n\n@item putByte(c)\nWrite one byte to the file.\n@end table\n\n@subsection @code{os} module\n\nThe @code{os} module provides Operating System specific functions:\n\n@itemize\n@item low level file access\n@item signals\n@item timers\n@item asynchronous I/O\n@item workers (threads)\n@end itemize\n\nThe OS functions usually return 0 if OK or an OS specific negative\nerror code.\n\nAvailable exports:\n\n@table @code\n@item open(filename, flags, mode = 0o666)\nOpen a file. Return a handle or < 0 if error.\n\n@item O_RDONLY\n@item O_WRONLY        \n@item O_RDWR\n@item O_APPEND\n@item O_CREAT\n@item O_EXCL\n@item O_TRUNC\nPOSIX open flags.\n\n@item O_TEXT\n(Windows specific). Open the file in text mode. The default is binary mode.\n\n@item close(fd)\nClose the file handle @code{fd}.\n\n@item seek(fd, offset, whence)\nSeek in the file. Use @code{std.SEEK_*} for\n@code{whence}. @code{offset} is either a number or a bigint. If\n@code{offset} is a bigint, a bigint is returned too.\n\n@item read(fd, buffer, offset, length)\nRead @code{length} bytes from the file handle @code{fd} to the\nArrayBuffer @code{buffer} at byte position @code{offset}.\nReturn the number of read bytes or < 0 if error.\n\n@item write(fd, buffer, offset, length)\nWrite @code{length} bytes to the file handle @code{fd} from the\nArrayBuffer @code{buffer} at byte position @code{offset}.\nReturn the number of written bytes or < 0 if error.\n\n@item isatty(fd)\nReturn @code{true} is @code{fd} is a TTY (terminal) handle.\n\n@item ttyGetWinSize(fd)\nReturn the TTY size as @code{[width, height]} or @code{null} if not available.\n\n@item ttySetRaw(fd)\nSet the TTY in raw mode.\n\n@item remove(filename)\nRemove a file. Return 0 if OK or @code{-errno}.\n\n@item rename(oldname, newname)\nRename a file. Return 0 if OK or @code{-errno}.\n\n@item realpath(path)\nReturn @code{[str, err]} where @code{str} is the canonicalized absolute\npathname of @code{path} and @code{err} the error code.\n\n@item getcwd()\nReturn @code{[str, err]} where @code{str} is the current working directory\nand @code{err} the error code.\n\n@item chdir(path)\nChange the current directory. Return 0 if OK or @code{-errno}.\n\n@item mkdir(path, mode = 0o777)\nCreate a directory at @code{path}. Return 0 if OK or @code{-errno}.\n\n@item stat(path)\n@item lstat(path)\n\nReturn @code{[obj, err]} where @code{obj} is an object containing the\nfile status of @code{path}. @code{err} is the error code. The\nfollowing fields are defined in @code{obj}: dev, ino, mode, nlink,\nuid, gid, rdev, size, blocks, atime, mtime, ctime. The times are\nspecified in milliseconds since 1970. @code{lstat()} is the same as\n@code{stat()} excepts that it returns information about the link\nitself.\n\n@item S_IFMT\n@item S_IFIFO\n@item S_IFCHR\n@item S_IFDIR\n@item S_IFBLK\n@item S_IFREG\n@item S_IFSOCK\n@item S_IFLNK\n@item S_ISGID\n@item S_ISUID\nConstants to interpret the @code{mode} property returned by\n@code{stat()}. They have the same value as in the C system header\n@file{sys/stat.h}.\n\n@item utimes(path, atime, mtime)\nChange the access and modification times of the file @code{path}. The\ntimes are specified in milliseconds since 1970. Return 0 if OK or @code{-errno}.\n\n@item symlink(target, linkpath)\nCreate a link at @code{linkpath} containing the string @code{target}. Return 0 if OK or @code{-errno}.\n\n@item readlink(path)\nReturn @code{[str, err]} where @code{str} is the link target and @code{err}\nthe error code.\n\n@item readdir(path)\nReturn @code{[array, err]} where @code{array} is an array of strings\ncontaining the filenames of the directory @code{path}. @code{err} is\nthe error code.\n\n@item setReadHandler(fd, func)\nAdd a read handler to the file handle @code{fd}. @code{func} is called\neach time there is data pending for @code{fd}. A single read handler\nper file handle is supported. Use @code{func = null} to remove the\nhandler.\n\n@item setWriteHandler(fd, func)\nAdd a write handler to the file handle @code{fd}. @code{func} is\ncalled each time data can be written to @code{fd}. A single write\nhandler per file handle is supported. Use @code{func = null} to remove\nthe handler.\n\n@item signal(signal, func)\nCall the function @code{func} when the signal @code{signal}\nhappens. Only a single handler per signal number is supported. Use\n@code{null} to set the default handler or @code{undefined} to ignore\nthe signal. Signal handlers can only be defined in the main thread.\n\n@item SIGINT\n@item SIGABRT\n@item SIGFPE\n@item SIGILL\n@item SIGSEGV\n@item SIGTERM\nPOSIX signal numbers.\n\n@item kill(pid, sig)\nSend the signal @code{sig} to the process @code{pid}.\n\n@item exec(args[, options])\nExecute a process with the arguments @code{args}. @code{options} is an\nobject containing optional parameters:\n\n  @table @code\n  @item block\n  Boolean (default = true). If true, wait until the process is\n  terminated. In this case, @code{exec} return the exit code if positive\n  or the negated signal number if the process was interrupted by a\n  signal. If false, do not block and return the process id of the child.\n  \n  @item usePath\n  Boolean (default = true). If true, the file is searched in the\n  @code{PATH} environment variable.\n\n  @item file\n  String (default = @code{args[0]}). Set the file to be executed.\n\n  @item cwd\n  String. If present, set the working directory of the new process.\n\n  @item stdin\n  @item stdout\n  @item stderr\n  If present, set the handle in the child for stdin, stdout or stderr.\n\n  @item env\n  Object. If present, set the process environment from the object\n  key-value pairs. Otherwise use the same environment as the current\n  process.\n\n  @item uid\n  Integer. If present, the process uid with @code{setuid}.\n\n  @item gid \n  Integer. If present, the process gid with @code{setgid}.\n\n  @end table\n\n@item waitpid(pid, options)\n@code{waitpid} Unix system call. Return the array @code{[ret,\nstatus]}. @code{ret} contains @code{-errno} in case of error.\n\n@item WNOHANG\nConstant for the @code{options} argument of @code{waitpid}.\n\n@item dup(fd)\n@code{dup} Unix system call.\n\n@item dup2(oldfd, newfd)\n@code{dup2} Unix system call.\n\n@item pipe()\n@code{pipe} Unix system call. Return two handles as @code{[read_fd,\nwrite_fd]} or null in case of error.\n\n@item sleep(delay_ms)\nSleep during @code{delay_ms} milliseconds.\n\n@item setTimeout(func, delay)\nCall the function @code{func} after @code{delay} ms. Return a handle\nto the timer.\n\n@item clearTimeout(handle)\nCancel a timer.\n\n@item platform\nReturn a string representing the platform: @code{\"linux\"}, @code{\"darwin\"},\n@code{\"win32\"} or @code{\"js\"}.\n\n@item Worker(module_filename)\nConstructor to create a new thread (worker) with an API close to the\n@code{WebWorkers}. @code{module_filename} is a string specifying the\nmodule filename which is executed in the newly created thread. As for\ndynamically imported module, it is relative to the current script or\nmodule path. Threads normally don't share any data and communicate\nbetween each other with messages. Nested workers are not supported. An\nexample is available in @file{tests/test_worker.js}.\n\nThe worker class has the following static properties:\n\n  @table @code\n  @item parent\n  In the created worker, @code{Worker.parent} represents the parent\n  worker and is used to send or receive messages.\n  @end table\n\nThe worker instances have the following properties:\n\n  @table @code\n  @item postMessage(msg)\n  \n  Send a message to the corresponding worker. @code{msg} is cloned in\n  the destination worker using an algorithm similar to the @code{HTML}\n  structured clone algorithm. @code{SharedArrayBuffer} are shared\n  between workers.\n\n  Current limitations: @code{Map} and @code{Set} are not supported\n  yet.\n\n  @item onmessage\n\n  Getter and setter. Set a function which is called each time a\n  message is received. The function is called with a single\n  argument. It is an object with a @code{data} property containing the\n  received message. The thread is not terminated if there is at least\n  one non @code{null} @code{onmessage} handler.\n\n  @end table\n\n@end table\n\n@section QuickJS C API\n\nThe C API was designed to be simple and efficient. The C API is\ndefined in the header @code{quickjs.h}.\n\n@subsection Runtime and contexts\n\n@code{JSRuntime} represents a Javascript runtime corresponding to an\nobject heap. Several runtimes can exist at the same time but they\ncannot exchange objects. Inside a given runtime, no multi-threading is\nsupported.\n\n@code{JSContext} represents a Javascript context (or Realm). Each\nJSContext has its own global objects and system objects. There can be\nseveral JSContexts per JSRuntime and they can share objects, similar\nto frames of the same origin sharing Javascript objects in a\nweb browser.\n\n@subsection JSValue\n\n@code{JSValue} represents a Javascript value which can be a primitive\ntype or an object. Reference counting is used, so it is important to\nexplicitly duplicate (@code{JS_DupValue()}, increment the reference\ncount) or free (@code{JS_FreeValue()}, decrement the reference count)\nJSValues.\n\n@subsection C functions\n\nC functions can be created with\n@code{JS_NewCFunction()}. @code{JS_SetPropertyFunctionList()} is a\nshortcut to easily add functions, setters and getters properties to a\ngiven object.\n\nUnlike other embedded Javascript engines, there is no implicit stack,\nso C functions get their parameters as normal C parameters. As a\ngeneral rule, C functions take constant @code{JSValue}s as parameters\n(so they don't need to free them) and return a newly allocated (=live)\n@code{JSValue}.\n\n@subsection Exceptions\n\nExceptions: most C functions can return a Javascript exception. It\nmust be explicitly tested and handled by the C code. The specific\n@code{JSValue} @code{JS_EXCEPTION} indicates that an exception\noccurred. The actual exception object is stored in the\n@code{JSContext} and can be retrieved with @code{JS_GetException()}.\n\n@subsection Script evaluation\n\nUse @code{JS_Eval()} to evaluate a script or module source.\n\nIf the script or module was compiled to bytecode with @code{qjsc}, it\ncan be evaluated by calling @code{js_std_eval_binary()}. The advantage\nis that no compilation is needed so it is faster and smaller because\nthe compiler can be removed from the executable if no @code{eval} is\nrequired.\n\nNote: the bytecode format is linked to a given QuickJS\nversion. Moreover, no security check is done before its\nexecution. Hence the bytecode should not be loaded from untrusted\nsources. That's why there is no option to output the bytecode to a\nbinary file in @code{qjsc}.\n\n@subsection JS Classes\n\nC opaque data can be attached to a Javascript object. The type of the\nC opaque data is determined with the class ID (@code{JSClassID}) of\nthe object. Hence the first step is to register a new class ID and JS\nclass (@code{JS_NewClassID()}, @code{JS_NewClass()}). Then you can\ncreate objects of this class with @code{JS_NewObjectClass()} and get or\nset the C opaque point with\n@code{JS_GetOpaque()}/@code{JS_SetOpaque()}.\n\nWhen defining a new JS class, it is possible to declare a finalizer\nwhich is called when the object is destroyed. The finalizer should be\nused to release C resources. It is invalid to execute JS code from\nit. A @code{gc_mark} method can be provided so that the cycle removal\nalgorithm can find the other objects referenced by this object. Other\nmethods are available to define exotic object behaviors.\n\nThe Class ID are globally allocated (i.e. for all runtimes). The\nJSClass are allocated per @code{JSRuntime}. @code{JS_SetClassProto()}\nis used to define a prototype for a given class in a given\nJSContext. @code{JS_NewObjectClass()} sets this prototype in the\ncreated object.\n\nExamples are available in @file{quickjs-libc.c}.\n\n@subsection C Modules\n\nNative ES6 modules are supported and can be dynamically or statically\nlinked. Look at the @file{test_bjson} and @file{bjson.so}\nexamples. The standard library @file{quickjs-libc.c} is also a good example\nof a native module.\n\n@subsection Memory handling\n\nUse @code{JS_SetMemoryLimit()} to set a global memory allocation limit\nto a given JSRuntime.\n\nCustom memory allocation functions can be provided with\n@code{JS_NewRuntime2()}.\n\nThe maximum system stack size can be set with @code{JS_SetMaxStackSize()}.\n\n@subsection Execution timeout and interrupts\n\nUse @code{JS_SetInterruptHandler()} to set a callback which is\nregularly called by the engine when it is executing code. This\ncallback can be used to implement an execution timeout.\n\nIt is used by the command line interpreter to implement a\n@code{Ctrl-C} handler.\n\n@chapter Internals\n\n@section Bytecode\n\nThe compiler generates bytecode directly with no intermediate\nrepresentation such as a parse tree, hence it is very fast. Several\noptimizations passes are done over the generated bytecode.\n\nA stack-based bytecode was chosen because it is simple and generates \ncompact code.\n\nFor each function, the maximum stack size is computed at compile time so that\nno runtime stack overflow tests are needed.\n\nA separate compressed line number table is maintained for the debug\ninformation.\n\nAccess to closure variables is optimized and is almost as fast as local\nvariables.\n\nDirect @code{eval} in strict mode is optimized.\n\n@section Executable generation\n\n@subsection @code{qjsc} compiler\n\nThe @code{qjsc} compiler generates C sources from Javascript files. By\ndefault the C sources are compiled with the system compiler\n(@code{gcc} or @code{clang}).\n\nThe generated C source contains the bytecode of the compiled functions\nor modules. If a full complete executable is needed, it also\ncontains a @code{main()} function with the necessary C code to initialize the\nJavascript engine and to load and execute the compiled functions and\nmodules.\n\nJavascript code can be mixed with C modules.\n\nIn order to have smaller executables, specific Javascript features can\nbe disabled, in particular @code{eval} or the regular expressions. The\ncode removal relies on the Link Time Optimization of the system\ncompiler.\n\n@subsection Binary JSON\n\n@code{qjsc} works by compiling scripts or modules and then serializing\nthem to a binary format. A subset of this format (without functions or\nmodules) can be used as binary JSON. The example @file{test_bjson.js}\nshows how to use it.\n\nWarning: the binary JSON format may change without notice, so it\nshould not be used to store persistent data. The @file{test_bjson.js}\nexample is only used to test the binary object format functions.\n\n@section Runtime\n\n@subsection Strings\n\nStrings are stored either as an 8 bit or a 16 bit array of\ncharacters. Hence random access to characters is always fast.\n\nThe C API provides functions to convert Javascript Strings to C UTF-8 encoded\nstrings. The most common case where the Javascript string contains\nonly ASCII characters involves no copying.\n\n@subsection Objects\n\nThe object shapes (object prototype, property names and flags) are shared\nbetween objects to save memory.\n\nArrays with no holes (except at the end of the array) are optimized.\n\nTypedArray accesses are optimized.\n\n@subsection Atoms\n\nObject property names and some strings are stored as Atoms (unique\nstrings) to save memory and allow fast comparison. Atoms are\nrepresented as a 32 bit integer. Half of the atom range is reserved for\nimmediate integer literals from @math{0} to @math{2^{31}-1}.\n\n@subsection Numbers\n\nNumbers are represented either as 32-bit signed integers or 64-bit IEEE-754\nfloating point values. Most operations have fast paths for the 32-bit\ninteger case.\n\n@subsection Garbage collection\n\nReference counting is used to free objects automatically and\ndeterministically. A separate cycle removal pass is done when the allocated\nmemory becomes too large. The cycle removal algorithm only uses the\nreference counts and the object content, so no explicit garbage\ncollection roots need to be manipulated in the C code.\n\n@subsection JSValue\n\nIt is a Javascript value which can be a primitive type (such as\nNumber, String, ...) or an Object. NaN boxing is used in the 32-bit version\nto store 64-bit floating point numbers. The representation is\noptimized so that 32-bit integers and reference counted values can be\nefficiently tested.\n\nIn 64-bit code, JSValue are 128-bit large and no NaN boxing is used. The\nrationale is that in 64-bit code memory usage is less critical.\n\nIn both cases (32 or 64 bits), JSValue exactly fits two CPU registers,\nso it can be efficiently returned by C functions.\n\n@subsection Function call\n\nThe engine is optimized so that function calls are fast. The system\nstack holds the Javascript parameters and local variables.\n\n@section RegExp\n\nA specific regular expression engine was developed. It is both small\nand efficient and supports all the ES2020 features including the\nUnicode properties. As the Javascript compiler, it directly generates\nbytecode without a parse tree.\n\nBacktracking with an explicit stack is used so that there is no\nrecursion on the system stack. Simple quantifiers are specifically\noptimized to avoid recursions.\n\nInfinite recursions coming from quantifiers with empty terms are\navoided.\n\nThe full regexp library weights about 15 KiB (x86 code), excluding the\nUnicode library.\n\n@section Unicode\n\nA specific Unicode library was developed so that there is no\ndependency on an external large Unicode library such as ICU. All the\nUnicode tables are compressed while keeping a reasonable access\nspeed.\n\nThe library supports case conversion, Unicode normalization, Unicode\nscript queries, Unicode general category queries and all Unicode\nbinary properties.\n\nThe full Unicode library weights about 45 KiB (x86 code).\n\n@section BigInt, BigFloat, BigDecimal\n\nBigInt, BigFloat and BigDecimal are implemented with the @code{libbf}\nlibrary@footnote{@url{https://bellard.org/libbf}}. It weights about 90\nKiB (x86 code) and provides arbitrary precision IEEE 754 floating\npoint operations and transcendental functions with exact rounding.\n\n@chapter License\n\nQuickJS is released under the MIT license.\n\nUnless otherwise specified, the QuickJS sources are copyright Fabrice\nBellard and Charlie Gordon.\n\n@bye\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/examples/fib.c",
    "content": "/*\n * QuickJS: Example of C module\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \"../quickjs.h\"\n\n#define countof(x) (sizeof(x) / sizeof((x)[0]))\n\nstatic int fib(int n)\n{\n    if (n <= 0)\n        return 0;\n    else if (n == 1)\n        return 1;\n    else\n        return fib(n - 1) + fib(n - 2);\n}\n\nstatic JSValue js_fib(JSContext *ctx, JSValueConst this_val,\n                      int argc, JSValueConst *argv)\n{\n    int n, res;\n    if (JS_ToInt32(ctx, &n, argv[0]))\n        return JS_EXCEPTION;\n    res = fib(n);\n    return JS_NewInt32(ctx, res);\n}\n\nstatic const JSCFunctionListEntry js_fib_funcs[] = {\n    JS_CFUNC_DEF(\"fib\", 1, js_fib ),\n};\n\nstatic int js_fib_init(JSContext *ctx, JSModuleDef *m)\n{\n    return JS_SetModuleExportList(ctx, m, js_fib_funcs,\n                                  countof(js_fib_funcs));\n}\n\n#ifdef JS_SHARED_LIBRARY\n#define JS_INIT_MODULE js_init_module\n#else\n#define JS_INIT_MODULE js_init_module_fib\n#endif\n\nJSModuleDef *JS_INIT_MODULE(JSContext *ctx, const char *module_name)\n{\n    JSModuleDef *m;\n    m = JS_NewCModule(ctx, module_name, js_fib_init);\n    if (!m)\n        return NULL;\n    JS_AddModuleExportList(ctx, m, js_fib_funcs, countof(js_fib_funcs));\n    return m;\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/examples/fib_module.js",
    "content": "/* fib module */\nexport function fib(n)\n{\n    if (n <= 0)\n        return 0;\n    else if (n == 1)\n        return 1;\n    else\n        return fib(n - 1) + fib(n - 2);\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/examples/hello.js",
    "content": "console.log(\"Hello World\");\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/examples/hello_module.js",
    "content": "/* example of JS module */\n\nimport { fib } from \"./fib_module.js\";\n\nconsole.log(\"Hello World\");\nconsole.log(\"fib(10)=\", fib(10));\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/examples/pi_bigdecimal.js",
    "content": "/*\n * PI computation in Javascript using the QuickJS bigdecimal type\n * (decimal floating point)\n */\n\"use strict\";\n\n/* compute PI with a precision of 'prec' digits */\nfunction calc_pi(prec) {\n    const CHUD_A = 13591409m;\n    const CHUD_B = 545140134m;\n    const CHUD_C = 640320m;\n    const CHUD_C3 = 10939058860032000m; /* C^3/24 */\n    const CHUD_DIGITS_PER_TERM = 14.18164746272548; /* log10(C/12)*3 */\n    \n    /* return [P, Q, G] */\n    function chud_bs(a, b, need_G) {\n        var c, P, Q, G, P1, Q1, G1, P2, Q2, G2, b1;\n        if (a == (b - 1n)) {\n            b1 = BigDecimal(b);\n            G = (2m * b1 - 1m) * (6m * b1 - 1m) * (6m * b1 - 5m);\n            P = G * (CHUD_B * b1 + CHUD_A);\n            if (b & 1n)\n                P = -P;\n            G = G;\n            Q = b1 * b1 * b1 * CHUD_C3;\n        } else {\n            c = (a + b) >> 1n;\n            [P1, Q1, G1] = chud_bs(a, c, true);\n            [P2, Q2, G2] = chud_bs(c, b, need_G);\n            P = P1 * Q2 + P2 * G1;\n            Q = Q1 * Q2;\n            if (need_G)\n                G = G1 * G2;\n            else\n                G = 0m;\n        }\n        return [P, Q, G];\n    }\n\n    var n, P, Q, G;\n    /* number of serie terms */\n    n = BigInt(Math.ceil(prec / CHUD_DIGITS_PER_TERM)) + 10n;\n    [P, Q, G] = chud_bs(0n, n, false);\n    Q = BigDecimal.div(Q, (P + Q * CHUD_A),\n                       { roundingMode: \"half-even\",\n                         maximumSignificantDigits: prec });\n    G = (CHUD_C / 12m) * BigDecimal.sqrt(CHUD_C,\n                                         { roundingMode: \"half-even\",\n                                           maximumSignificantDigits: prec });\n    return Q * G;\n}\n\n(function() {\n    var r, n_digits, n_bits;\n    if (typeof scriptArgs != \"undefined\") {\n        if (scriptArgs.length < 2) {\n            print(\"usage: pi n_digits\");\n            return;\n        }\n        n_digits = scriptArgs[1] | 0;\n    } else {\n        n_digits = 1000;\n    }\n    /* we add more digits to reduce the probability of bad rounding for\n       the last digits */\n    r = calc_pi(n_digits + 20);\n    print(r.toFixed(n_digits, \"down\"));\n})();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/examples/pi_bigfloat.js",
    "content": "/*\n * PI computation in Javascript using the QuickJS bigfloat type\n * (binary floating point)\n */\n\"use strict\";\n\n/* compute PI with a precision of 'prec' bits */\nfunction calc_pi() {\n    const CHUD_A = 13591409n;\n    const CHUD_B = 545140134n;\n    const CHUD_C = 640320n;\n    const CHUD_C3 = 10939058860032000n; /* C^3/24 */\n    const CHUD_BITS_PER_TERM = 47.11041313821584202247; /* log2(C/12)*3 */\n    \n    /* return [P, Q, G] */\n    function chud_bs(a, b, need_G) {\n        var c, P, Q, G, P1, Q1, G1, P2, Q2, G2;\n        if (a == (b - 1n)) {\n            G = (2n * b - 1n) * (6n * b - 1n) * (6n * b - 5n);\n            P = BigFloat(G * (CHUD_B * b + CHUD_A));\n            if (b & 1n)\n                P = -P;\n            G = BigFloat(G);\n            Q = BigFloat(b * b * b * CHUD_C3);\n        } else {\n            c = (a + b) >> 1n;\n            [P1, Q1, G1] = chud_bs(a, c, true);\n            [P2, Q2, G2] = chud_bs(c, b, need_G);\n            P = P1 * Q2 + P2 * G1;\n            Q = Q1 * Q2;\n            if (need_G)\n                G = G1 * G2;\n            else\n                G = 0l;\n        }\n        return [P, Q, G];\n    }\n\n    var n, P, Q, G;\n    /* number of serie terms */\n    n = BigInt(Math.ceil(BigFloatEnv.prec / CHUD_BITS_PER_TERM)) + 10n;\n    [P, Q, G] = chud_bs(0n, n, false);\n    Q = Q / (P + Q * BigFloat(CHUD_A));\n    G = BigFloat((CHUD_C / 12n)) * BigFloat.sqrt(BigFloat(CHUD_C));\n    return Q * G;\n}\n\n(function() {\n    var r, n_digits, n_bits;\n    if (typeof scriptArgs != \"undefined\") {\n        if (scriptArgs.length < 2) {\n            print(\"usage: pi n_digits\");\n            return;\n        }\n        n_digits = scriptArgs[1];\n    } else {\n        n_digits = 1000;\n    }\n    n_bits = Math.ceil(n_digits * Math.log2(10));\n    /* we add more bits to reduce the probability of bad rounding for\n       the last digits */\n    BigFloatEnv.setPrec( () => {\n        r = calc_pi();\n        print(r.toFixed(n_digits, BigFloatEnv.RNDZ));\n    }, n_bits + 32);\n})();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/examples/pi_bigint.js",
    "content": "/*\n * PI computation in Javascript using the BigInt type\n */\n\"use strict\";\n\n/* return floor(log2(a)) for a > 0 and 0 for a = 0 */\nfunction floor_log2(a)\n{\n    var k_max, a1, k, i;\n    k_max = 0n;\n    while ((a >> (2n ** k_max)) != 0n) {\n        k_max++;\n    }\n    k = 0n;\n    a1 = a;\n    for(i = k_max - 1n; i >= 0n; i--) {\n        a1 = a >> (2n ** i);\n        if (a1 != 0n) {\n            a = a1;\n            k |= (1n << i);\n        }\n    }\n    return k;\n}\n\n/* return ceil(log2(a)) for a > 0 */\nfunction ceil_log2(a)\n{\n    return floor_log2(a - 1n) + 1n;\n}\n\n/* return floor(sqrt(a)) (not efficient but simple) */\nfunction int_sqrt(a)\n{\n    var l, u, s;\n    if (a == 0n)\n        return a;\n    l = ceil_log2(a);\n    u = 1n << ((l + 1n) / 2n);\n    /* u >= floor(sqrt(a)) */\n    for(;;) {\n        s = u;\n        u = ((a / s) + s) / 2n;\n        if (u >= s)\n            break;\n    }\n    return s;\n}\n\n/* return pi * 2**prec */\nfunction calc_pi(prec) {\n    const CHUD_A = 13591409n;\n    const CHUD_B = 545140134n;\n    const CHUD_C = 640320n;\n    const CHUD_C3 = 10939058860032000n; /* C^3/24 */\n    const CHUD_BITS_PER_TERM = 47.11041313821584202247; /* log2(C/12)*3 */\n    \n    /* return [P, Q, G] */\n    function chud_bs(a, b, need_G) {\n        var c, P, Q, G, P1, Q1, G1, P2, Q2, G2;\n        if (a == (b - 1n)) {\n            G = (2n * b - 1n) * (6n * b - 1n) * (6n * b - 5n);\n            P = G * (CHUD_B * b + CHUD_A);\n            if (b & 1n)\n                P = -P;\n            Q = b * b * b * CHUD_C3;\n        } else {\n            c = (a + b) >> 1n;\n            [P1, Q1, G1] = chud_bs(a, c, true);\n            [P2, Q2, G2] = chud_bs(c, b, need_G);\n            P = P1 * Q2 + P2 * G1;\n            Q = Q1 * Q2;\n            if (need_G)\n                G = G1 * G2;\n            else\n                G = 0n;\n        }\n        return [P, Q, G];\n    }\n\n    var n, P, Q, G;\n    /* number of serie terms */\n    n = BigInt(Math.ceil(Number(prec) / CHUD_BITS_PER_TERM)) + 10n;\n    [P, Q, G] = chud_bs(0n, n, false);\n    Q = (CHUD_C / 12n) * (Q << prec) / (P + Q * CHUD_A);\n    G = int_sqrt(CHUD_C << (2n * prec));\n    return (Q * G) >> prec;\n}\n\nfunction main(args) {\n    var r, n_digits, n_bits, out;\n    if (args.length < 1) {\n        print(\"usage: pi n_digits\");\n        return;\n    }\n    n_digits = args[0] | 0;\n\n    /* we add more bits to reduce the probability of bad rounding for\n      the last digits */\n    n_bits = BigInt(Math.ceil(n_digits * Math.log2(10))) + 32n;\n    r = calc_pi(n_bits);\n    r = ((10n ** BigInt(n_digits)) * r) >> n_bits;\n    out = r.toString();\n    print(out[0] + \".\" + out.slice(1));\n}\n\nvar args;\nif (typeof scriptArgs != \"undefined\") {\n    args = scriptArgs;\n    args.shift();\n} else if (typeof arguments != \"undefined\") {\n    args = arguments;\n} else {\n    /* default: 1000 digits */\n    args=[1000];\n}\n\nmain(args);\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/examples/point.c",
    "content": "/*\n * QuickJS: Example of C module with a class\n * \n * Copyright (c) 2019 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \"../quickjs.h\"\n#include <math.h>\n\n#define countof(x) (sizeof(x) / sizeof((x)[0]))\n\n/* Point Class */\n\ntypedef struct {\n    int x;\n    int y;\n} JSPointData;\n\nstatic JSClassID js_point_class_id;\n\nstatic void js_point_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSPointData *s = JS_GetOpaque(val, js_point_class_id);\n    /* Note: 's' can be NULL in case JS_SetOpaque() was not called */\n    js_free_rt(rt, s);\n}\n\nstatic JSValue js_point_ctor(JSContext *ctx,\n                             JSValueConst new_target,\n                             int argc, JSValueConst *argv)\n{\n    JSPointData *s;\n    JSValue obj = JS_UNDEFINED;\n    JSValue proto;\n    \n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s)\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &s->x, argv[0]))\n        goto fail;\n    if (JS_ToInt32(ctx, &s->y, argv[1]))\n        goto fail;\n    /* using new_target to get the prototype is necessary when the\n       class is extended. */\n    proto = JS_GetPropertyStr(ctx, new_target, \"prototype\");\n    if (JS_IsException(proto))\n        goto fail;\n    obj = JS_NewObjectProtoClass(ctx, proto, js_point_class_id);\n    JS_FreeValue(ctx, proto);\n    if (JS_IsException(obj))\n        goto fail;\n    JS_SetOpaque(obj, s);\n    return obj;\n fail:\n    js_free(ctx, s);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_point_get_xy(JSContext *ctx, JSValueConst this_val, int magic)\n{\n    JSPointData *s = JS_GetOpaque2(ctx, this_val, js_point_class_id);\n    if (!s)\n        return JS_EXCEPTION;\n    if (magic == 0)\n        return JS_NewInt32(ctx, s->x);\n    else\n        return JS_NewInt32(ctx, s->y);\n}\n\nstatic JSValue js_point_set_xy(JSContext *ctx, JSValueConst this_val, JSValue val, int magic)\n{\n    JSPointData *s = JS_GetOpaque2(ctx, this_val, js_point_class_id);\n    int v;\n    if (!s)\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &v, val))\n        return JS_EXCEPTION;\n    if (magic == 0)\n        s->x = v;\n    else\n        s->y = v;\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_point_norm(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    JSPointData *s = JS_GetOpaque2(ctx, this_val, js_point_class_id);\n    if (!s)\n        return JS_EXCEPTION;\n    return JS_NewFloat64(ctx, sqrt((double)s->x * s->x + (double)s->y * s->y));\n}\n\nstatic JSClassDef js_point_class = {\n    \"Point\",\n    .finalizer = js_point_finalizer,\n}; \n\nstatic const JSCFunctionListEntry js_point_proto_funcs[] = {\n    JS_CGETSET_MAGIC_DEF(\"x\", js_point_get_xy, js_point_set_xy, 0),\n    JS_CGETSET_MAGIC_DEF(\"y\", js_point_get_xy, js_point_set_xy, 1),\n    JS_CFUNC_DEF(\"norm\", 0, js_point_norm),\n};\n\nstatic int js_point_init(JSContext *ctx, JSModuleDef *m)\n{\n    JSValue point_proto, point_class;\n    \n    /* create the Point class */\n    JS_NewClassID(&js_point_class_id);\n    JS_NewClass(JS_GetRuntime(ctx), js_point_class_id, &js_point_class);\n\n    point_proto = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, point_proto, js_point_proto_funcs, countof(js_point_proto_funcs));\n    \n    point_class = JS_NewCFunction2(ctx, js_point_ctor, \"Point\", 2, JS_CFUNC_constructor, 0);\n    /* set proto.constructor and ctor.prototype */\n    JS_SetConstructor(ctx, point_class, point_proto);\n    JS_SetClassProto(ctx, js_point_class_id, point_proto);\n                      \n    JS_SetModuleExport(ctx, m, \"Point\", point_class);\n    return 0;\n}\n\nJSModuleDef *js_init_module(JSContext *ctx, const char *module_name)\n{\n    JSModuleDef *m;\n    m = JS_NewCModule(ctx, module_name, js_point_init);\n    if (!m)\n        return NULL;\n    JS_AddModuleExport(ctx, m, \"Point\");\n    return m;\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/examples/test_fib.js",
    "content": "/* example of JS module importing a C module */\n\nimport { fib } from \"./fib.so\";\n\nconsole.log(\"Hello World\");\nconsole.log(\"fib(10)=\", fib(10));\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/examples/test_point.js",
    "content": "/* example of JS module importing a C module */\nimport { Point } from \"./point.so\";\n\nfunction assert(b, str)\n{\n    if (b) {\n        return;\n    } else {\n        throw Error(\"assertion failed: \" + str);\n    }\n}\n\nclass ColorPoint extends Point {\n    constructor(x, y, color) {\n        super(x, y);\n        this.color = color;\n    }\n    get_color() {\n        return this.color;\n    }\n};\n\nfunction main()\n{\n    var pt, pt2;\n\n    pt = new Point(2, 3);\n    assert(pt.x === 2);\n    assert(pt.y === 3);\n    pt.x = 4;\n    assert(pt.x === 4);\n    assert(pt.norm() == 5);\n\n    pt2 = new ColorPoint(2, 3, 0xffffff);\n    assert(pt2.x === 2);\n    assert(pt2.color === 0xffffff);\n    assert(pt2.get_color() === 0xffffff);\n}\n\nmain();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/libbf.c",
    "content": "/*\n * Tiny arbitrary precision floating point library\n * \n * Copyright (c) 2017-2021 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <inttypes.h>\n#include <math.h>\n#include <string.h>\n#include <assert.h>\n\n#ifdef __AVX2__\n#include <immintrin.h>\n#endif\n\n#include \"cutils.h\"\n#include \"libbf.h\"\n\n/* enable it to check the multiplication result */\n//#define USE_MUL_CHECK\n/* enable it to use FFT/NTT multiplication */\n#define USE_FFT_MUL\n/* enable decimal floating point support */\n#define USE_BF_DEC\n\n//#define inline __attribute__((always_inline))\n\n#ifdef __AVX2__\n#define FFT_MUL_THRESHOLD 100 /* in limbs of the smallest factor */\n#else\n#define FFT_MUL_THRESHOLD 100 /* in limbs of the smallest factor */\n#endif\n\n/* XXX: adjust */\n#define DIVNORM_LARGE_THRESHOLD 50\n#define UDIV1NORM_THRESHOLD 3\n\n#if LIMB_BITS == 64\n#define FMT_LIMB1 \"%\" PRIx64 \n#define FMT_LIMB \"%016\" PRIx64 \n#define PRId_LIMB PRId64\n#define PRIu_LIMB PRIu64\n\n#else\n\n#define FMT_LIMB1 \"%x\"\n#define FMT_LIMB \"%08x\"\n#define PRId_LIMB \"d\"\n#define PRIu_LIMB \"u\"\n\n#endif\n\ntypedef intptr_t mp_size_t;\n\ntypedef int bf_op2_func_t(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n                          bf_flags_t flags);\n\n#ifdef USE_FFT_MUL\n\n#define FFT_MUL_R_OVERLAP_A (1 << 0)\n#define FFT_MUL_R_OVERLAP_B (1 << 1)\n#define FFT_MUL_R_NORESIZE  (1 << 2)\n\nstatic no_inline int fft_mul(bf_context_t *s,\n                             bf_t *res, limb_t *a_tab, limb_t a_len,\n                             limb_t *b_tab, limb_t b_len, int mul_flags);\nstatic void fft_clear_cache(bf_context_t *s);\n#endif\n#ifdef USE_BF_DEC\nstatic limb_t get_digit(const limb_t *tab, limb_t len, slimb_t pos);\n#endif\n\n\n/* could leading zeros */\nstatic inline int clz(limb_t a)\n{\n    if (a == 0) {\n        return LIMB_BITS;\n    } else {\n#if LIMB_BITS == 64\n        return clz64(a);\n#else\n        return clz32(a);\n#endif\n    }\n}\n\nstatic inline int ctz(limb_t a)\n{\n    if (a == 0) {\n        return LIMB_BITS;\n    } else {\n#if LIMB_BITS == 64\n        return ctz64(a);\n#else\n        return ctz32(a);\n#endif\n    }\n}\n\nstatic inline int ceil_log2(limb_t a)\n{\n    if (a <= 1)\n        return 0;\n    else\n        return LIMB_BITS - clz(a - 1);\n}\n\n/* b must be >= 1 */\nstatic inline slimb_t ceil_div(slimb_t a, slimb_t b)\n{\n    if (a >= 0)\n        return (a + b - 1) / b;\n    else\n        return a / b;\n}\n\n/* b must be >= 1 */\nstatic inline slimb_t floor_div(slimb_t a, slimb_t b)\n{\n    if (a >= 0) {\n        return a / b;\n    } else {\n        return (a - b + 1) / b;\n    }\n}\n\n/* return r = a modulo b (0 <= r <= b - 1. b must be >= 1 */\nstatic inline limb_t smod(slimb_t a, slimb_t b)\n{\n    a = a % (slimb_t)b;\n    if (a < 0)\n        a += b;\n    return a;\n}\n\n/* signed addition with saturation */\nstatic inline slimb_t sat_add(slimb_t a, slimb_t b)\n{\n    slimb_t r;\n    r = a + b;\n    /* overflow ? */\n    if (((a ^ r) & (b ^ r)) < 0)\n        r = (a >> (LIMB_BITS - 1)) ^ (((limb_t)1 << (LIMB_BITS - 1)) - 1);\n    return r;\n}\n\n#define malloc(s) malloc_is_forbidden(s)\n#define free(p) free_is_forbidden(p)\n#define realloc(p, s) realloc_is_forbidden(p, s)\n\nvoid bf_context_init(bf_context_t *s, bf_realloc_func_t *realloc_func,\n                     void *realloc_opaque)\n{\n    memset(s, 0, sizeof(*s));\n    s->realloc_func = realloc_func;\n    s->realloc_opaque = realloc_opaque;\n}\n\nvoid bf_context_end(bf_context_t *s)\n{\n    bf_clear_cache(s);\n}\n\nvoid bf_init(bf_context_t *s, bf_t *r)\n{\n    r->ctx = s;\n    r->sign = 0;\n    r->expn = BF_EXP_ZERO;\n    r->len = 0;\n    r->tab = NULL;\n}\n\n/* return 0 if OK, -1 if alloc error */\nint bf_resize(bf_t *r, limb_t len)\n{\n    limb_t *tab;\n    \n    if (len != r->len) {\n        tab = bf_realloc(r->ctx, r->tab, len * sizeof(limb_t));\n        if (!tab && len != 0)\n            return -1;\n        r->tab = tab;\n        r->len = len;\n    }\n    return 0;\n}\n\n/* return 0 or BF_ST_MEM_ERROR */\nint bf_set_ui(bf_t *r, uint64_t a)\n{\n    r->sign = 0;\n    if (a == 0) {\n        r->expn = BF_EXP_ZERO;\n        bf_resize(r, 0); /* cannot fail */\n    } \n#if LIMB_BITS == 32\n    else if (a <= 0xffffffff)\n#else\n    else\n#endif\n    {\n        int shift;\n        if (bf_resize(r, 1))\n            goto fail;\n        shift = clz(a);\n        r->tab[0] = a << shift;\n        r->expn = LIMB_BITS - shift;\n    }\n#if LIMB_BITS == 32\n    else {\n        uint32_t a1, a0;\n        int shift;\n        if (bf_resize(r, 2))\n            goto fail;\n        a0 = a;\n        a1 = a >> 32;\n        shift = clz(a1);\n        r->tab[0] = a0 << shift;\n        r->tab[1] = (a1 << shift) | (a0 >> (LIMB_BITS - shift));\n        r->expn = 2 * LIMB_BITS - shift;\n    }\n#endif\n    return 0;\n fail:\n    bf_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\n/* return 0 or BF_ST_MEM_ERROR */\nint bf_set_si(bf_t *r, int64_t a)\n{\n    int ret;\n\n    if (a < 0) {\n        ret = bf_set_ui(r, -a);\n        r->sign = 1;\n    } else {\n        ret = bf_set_ui(r, a);\n    }\n    return ret;\n}\n\nvoid bf_set_nan(bf_t *r)\n{\n    bf_resize(r, 0); /* cannot fail */\n    r->expn = BF_EXP_NAN;\n    r->sign = 0;\n}\n\nvoid bf_set_zero(bf_t *r, int is_neg)\n{\n    bf_resize(r, 0); /* cannot fail */\n    r->expn = BF_EXP_ZERO;\n    r->sign = is_neg;\n}\n\nvoid bf_set_inf(bf_t *r, int is_neg)\n{\n    bf_resize(r, 0); /* cannot fail */\n    r->expn = BF_EXP_INF;\n    r->sign = is_neg;\n}\n\n/* return 0 or BF_ST_MEM_ERROR */\nint bf_set(bf_t *r, const bf_t *a)\n{\n    if (r == a)\n        return 0;\n    if (bf_resize(r, a->len)) {\n        bf_set_nan(r);\n        return BF_ST_MEM_ERROR;\n    }\n    r->sign = a->sign;\n    r->expn = a->expn;\n    memcpy(r->tab, a->tab, a->len * sizeof(limb_t));\n    return 0;\n}\n\n/* equivalent to bf_set(r, a); bf_delete(a) */\nvoid bf_move(bf_t *r, bf_t *a)\n{\n    bf_context_t *s = r->ctx;\n    if (r == a)\n        return;\n    bf_free(s, r->tab);\n    *r = *a;\n}\n\nstatic limb_t get_limbz(const bf_t *a, limb_t idx)\n{\n    if (idx >= a->len)\n        return 0;\n    else\n        return a->tab[idx];\n}\n\n/* get LIMB_BITS at bit position 'pos' in tab */\nstatic inline limb_t get_bits(const limb_t *tab, limb_t len, slimb_t pos)\n{\n    limb_t i, a0, a1;\n    int p;\n\n    i = pos >> LIMB_LOG2_BITS;\n    p = pos & (LIMB_BITS - 1);\n    if (i < len)\n        a0 = tab[i];\n    else\n        a0 = 0;\n    if (p == 0) {\n        return a0;\n    } else {\n        i++;\n        if (i < len)\n            a1 = tab[i];\n        else\n            a1 = 0;\n        return (a0 >> p) | (a1 << (LIMB_BITS - p));\n    }\n}\n\nstatic inline limb_t get_bit(const limb_t *tab, limb_t len, slimb_t pos)\n{\n    slimb_t i;\n    i = pos >> LIMB_LOG2_BITS;\n    if (i < 0 || i >= len)\n        return 0;\n    return (tab[i] >> (pos & (LIMB_BITS - 1))) & 1;\n}\n\nstatic inline limb_t limb_mask(int start, int last)\n{\n    limb_t v;\n    int n;\n    n = last - start + 1;\n    if (n == LIMB_BITS)\n        v = -1;\n    else\n        v = (((limb_t)1 << n) - 1) << start;\n    return v;\n}\n\nstatic limb_t mp_scan_nz(const limb_t *tab, mp_size_t n)\n{\n    mp_size_t i;\n    for(i = 0; i < n; i++) {\n        if (tab[i] != 0)\n            return 1;\n    }\n    return 0;\n}\n\n/* return != 0 if one bit between 0 and bit_pos inclusive is not zero. */\nstatic inline limb_t scan_bit_nz(const bf_t *r, slimb_t bit_pos)\n{\n    slimb_t pos;\n    limb_t v;\n    \n    pos = bit_pos >> LIMB_LOG2_BITS;\n    if (pos < 0)\n        return 0;\n    v = r->tab[pos] & limb_mask(0, bit_pos & (LIMB_BITS - 1));\n    if (v != 0)\n        return 1;\n    pos--;\n    while (pos >= 0) {\n        if (r->tab[pos] != 0)\n            return 1;\n        pos--;\n    }\n    return 0;\n}\n\n/* return the addend for rounding. Note that prec can be <= 0 (for\n   BF_FLAG_RADPNT_PREC) */\nstatic int bf_get_rnd_add(int *pret, const bf_t *r, limb_t l,\n                          slimb_t prec, int rnd_mode)\n{\n    int add_one, inexact;\n    limb_t bit1, bit0;\n    \n    if (rnd_mode == BF_RNDF) {\n        bit0 = 1; /* faithful rounding does not honor the INEXACT flag */\n    } else {\n        /* starting limb for bit 'prec + 1' */\n        bit0 = scan_bit_nz(r, l * LIMB_BITS - 1 - bf_max(0, prec + 1));\n    }\n\n    /* get the bit at 'prec' */\n    bit1 = get_bit(r->tab, l, l * LIMB_BITS - 1 - prec);\n    inexact = (bit1 | bit0) != 0;\n    \n    add_one = 0;\n    switch(rnd_mode) {\n    case BF_RNDZ:\n        break;\n    case BF_RNDN:\n        if (bit1) {\n            if (bit0) {\n                add_one = 1;\n            } else {\n                /* round to even */\n                add_one =\n                    get_bit(r->tab, l, l * LIMB_BITS - 1 - (prec - 1));\n            }\n        }\n        break;\n    case BF_RNDD:\n    case BF_RNDU:\n        if (r->sign == (rnd_mode == BF_RNDD))\n            add_one = inexact;\n        break;\n    case BF_RNDA:\n        add_one = inexact;\n        break;\n    case BF_RNDNA:\n    case BF_RNDF:\n        add_one = bit1;\n        break;\n    default:\n        abort();\n    }\n    \n    if (inexact)\n        *pret |= BF_ST_INEXACT;\n    return add_one;\n}\n\nstatic int bf_set_overflow(bf_t *r, int sign, limb_t prec, bf_flags_t flags)\n{\n    slimb_t i, l, e_max;\n    int rnd_mode;\n    \n    rnd_mode = flags & BF_RND_MASK;\n    if (prec == BF_PREC_INF ||\n        rnd_mode == BF_RNDN ||\n        rnd_mode == BF_RNDNA ||\n        rnd_mode == BF_RNDA ||\n        (rnd_mode == BF_RNDD && sign == 1) ||\n        (rnd_mode == BF_RNDU && sign == 0)) {\n        bf_set_inf(r, sign);\n    } else {\n        /* set to maximum finite number */\n        l = (prec + LIMB_BITS - 1) / LIMB_BITS;\n        if (bf_resize(r, l)) {\n            bf_set_nan(r);\n            return BF_ST_MEM_ERROR;\n        }\n        r->tab[0] = limb_mask((-prec) & (LIMB_BITS - 1),\n                              LIMB_BITS - 1);\n        for(i = 1; i < l; i++)\n            r->tab[i] = (limb_t)-1;\n        e_max = (limb_t)1 << (bf_get_exp_bits(flags) - 1);\n        r->expn = e_max;\n        r->sign = sign;\n    }\n    return BF_ST_OVERFLOW | BF_ST_INEXACT;\n}\n\n/* round to prec1 bits assuming 'r' is non zero and finite. 'r' is\n   assumed to have length 'l' (1 <= l <= r->len). Note: 'prec1' can be\n   infinite (BF_PREC_INF). 'ret' is 0 or BF_ST_INEXACT if the result\n   is known to be inexact. Can fail with BF_ST_MEM_ERROR in case of\n   overflow not returning infinity. */\nstatic int __bf_round(bf_t *r, limb_t prec1, bf_flags_t flags, limb_t l,\n                      int ret)\n{\n    limb_t v, a;\n    int shift, add_one, rnd_mode;\n    slimb_t i, bit_pos, pos, e_min, e_max, e_range, prec;\n\n    /* e_min and e_max are computed to match the IEEE 754 conventions */\n    e_range = (limb_t)1 << (bf_get_exp_bits(flags) - 1);\n    e_min = -e_range + 3;\n    e_max = e_range;\n    \n    if (flags & BF_FLAG_RADPNT_PREC) {\n        /* 'prec' is the precision after the radix point */\n        if (prec1 != BF_PREC_INF)\n            prec = r->expn + prec1;\n        else\n            prec = prec1;\n    } else if (unlikely(r->expn < e_min) && (flags & BF_FLAG_SUBNORMAL)) {\n        /* restrict the precision in case of potentially subnormal\n           result */\n        assert(prec1 != BF_PREC_INF);\n        prec = prec1 - (e_min - r->expn);\n    } else {\n        prec = prec1;\n    }\n\n    /* round to prec bits */\n    rnd_mode = flags & BF_RND_MASK;\n    add_one = bf_get_rnd_add(&ret, r, l, prec, rnd_mode);\n    \n    if (prec <= 0) {\n        if (add_one) {\n            bf_resize(r, 1); /* cannot fail */\n            r->tab[0] = (limb_t)1 << (LIMB_BITS - 1);\n            r->expn += 1 - prec;\n            ret |= BF_ST_UNDERFLOW | BF_ST_INEXACT;\n            return ret;\n        } else {\n            goto underflow;\n        }\n    } else if (add_one) {\n        limb_t carry;\n        \n        /* add one starting at digit 'prec - 1' */\n        bit_pos = l * LIMB_BITS - 1 - (prec - 1);\n        pos = bit_pos >> LIMB_LOG2_BITS;\n        carry = (limb_t)1 << (bit_pos & (LIMB_BITS - 1));\n        \n        for(i = pos; i < l; i++) {\n            v = r->tab[i] + carry;\n            carry = (v < carry);\n            r->tab[i] = v;\n            if (carry == 0)\n                break;\n        }\n        if (carry) {\n            /* shift right by one digit */\n            v = 1;\n            for(i = l - 1; i >= pos; i--) {\n                a = r->tab[i];\n                r->tab[i] = (a >> 1) | (v << (LIMB_BITS - 1));\n                v = a;\n            }\n            r->expn++;\n        }\n    }\n    \n    /* check underflow */\n    if (unlikely(r->expn < e_min)) {\n        if (flags & BF_FLAG_SUBNORMAL) {\n            /* if inexact, also set the underflow flag */\n            if (ret & BF_ST_INEXACT)\n                ret |= BF_ST_UNDERFLOW;\n        } else {\n        underflow:\n            ret |= BF_ST_UNDERFLOW | BF_ST_INEXACT;\n            bf_set_zero(r, r->sign);\n            return ret;\n        }\n    }\n    \n    /* check overflow */\n    if (unlikely(r->expn > e_max))\n        return bf_set_overflow(r, r->sign, prec1, flags);\n    \n    /* keep the bits starting at 'prec - 1' */\n    bit_pos = l * LIMB_BITS - 1 - (prec - 1);\n    i = bit_pos >> LIMB_LOG2_BITS;\n    if (i >= 0) {\n        shift = bit_pos & (LIMB_BITS - 1);\n        if (shift != 0)\n            r->tab[i] &= limb_mask(shift, LIMB_BITS - 1);\n    } else {\n        i = 0;\n    }\n    /* remove trailing zeros */\n    while (r->tab[i] == 0)\n        i++;\n    if (i > 0) {\n        l -= i;\n        memmove(r->tab, r->tab + i, l * sizeof(limb_t));\n    }\n    bf_resize(r, l); /* cannot fail */\n    return ret;\n}\n\n/* 'r' must be a finite number. */\nint bf_normalize_and_round(bf_t *r, limb_t prec1, bf_flags_t flags)\n{\n    limb_t l, v, a;\n    int shift, ret;\n    slimb_t i;\n    \n    //    bf_print_str(\"bf_renorm\", r);\n    l = r->len;\n    while (l > 0 && r->tab[l - 1] == 0)\n        l--;\n    if (l == 0) {\n        /* zero */\n        r->expn = BF_EXP_ZERO;\n        bf_resize(r, 0); /* cannot fail */\n        ret = 0;\n    } else {\n        r->expn -= (r->len - l) * LIMB_BITS;\n        /* shift to have the MSB set to '1' */\n        v = r->tab[l - 1];\n        shift = clz(v);\n        if (shift != 0) {\n            v = 0;\n            for(i = 0; i < l; i++) {\n                a = r->tab[i];\n                r->tab[i] = (a << shift) | (v >> (LIMB_BITS - shift));\n                v = a;\n            }\n            r->expn -= shift;\n        }\n        ret = __bf_round(r, prec1, flags, l, 0);\n    }\n    //    bf_print_str(\"r_final\", r);\n    return ret;\n}\n\n/* return true if rounding can be done at precision 'prec' assuming\n   the exact result r is such that |r-a| <= 2^(EXP(a)-k). */\n/* XXX: check the case where the exponent would be incremented by the\n   rounding */\nint bf_can_round(const bf_t *a, slimb_t prec, bf_rnd_t rnd_mode, slimb_t k)\n{\n    BOOL is_rndn;\n    slimb_t bit_pos, n;\n    limb_t bit;\n    \n    if (a->expn == BF_EXP_INF || a->expn == BF_EXP_NAN)\n        return FALSE;\n    if (rnd_mode == BF_RNDF) {\n        return (k >= (prec + 1));\n    }\n    if (a->expn == BF_EXP_ZERO)\n        return FALSE;\n    is_rndn = (rnd_mode == BF_RNDN || rnd_mode == BF_RNDNA);\n    if (k < (prec + 2))\n        return FALSE;\n    bit_pos = a->len * LIMB_BITS - 1 - prec;\n    n = k - prec;\n    /* bit pattern for RNDN or RNDNA: 0111.. or 1000...\n       for other rounding modes: 000... or 111... \n    */\n    bit = get_bit(a->tab, a->len, bit_pos);\n    bit_pos--;\n    n--;\n    bit ^= is_rndn;\n    /* XXX: slow, but a few iterations on average */\n    while (n != 0) {\n        if (get_bit(a->tab, a->len, bit_pos) != bit)\n            return TRUE;\n        bit_pos--;\n        n--;\n    }\n    return FALSE;\n}\n\n/* Cannot fail with BF_ST_MEM_ERROR. */\nint bf_round(bf_t *r, limb_t prec, bf_flags_t flags)\n{\n    if (r->len == 0)\n        return 0;\n    return __bf_round(r, prec, flags, r->len, 0);\n}\n\n/* for debugging */\nstatic __maybe_unused void dump_limbs(const char *str, const limb_t *tab, limb_t n)\n{\n    limb_t i;\n    printf(\"%s: len=%\" PRId_LIMB \"\\n\", str, n);\n    for(i = 0; i < n; i++) {\n        printf(\"%\" PRId_LIMB \": \" FMT_LIMB \"\\n\",\n               i, tab[i]);\n    }\n}\n\nvoid mp_print_str(const char *str, const limb_t *tab, limb_t n)\n{\n    slimb_t i;\n    printf(\"%s= 0x\", str);\n    for(i = n - 1; i >= 0; i--) {\n        if (i != (n - 1))\n            printf(\"_\");\n        printf(FMT_LIMB, tab[i]);\n    }\n    printf(\"\\n\");\n}\n\nstatic __maybe_unused void mp_print_str_h(const char *str,\n                                          const limb_t *tab, limb_t n,\n                                          limb_t high)\n{\n    slimb_t i;\n    printf(\"%s= 0x\", str);\n    printf(FMT_LIMB, high);\n    for(i = n - 1; i >= 0; i--) {\n        printf(\"_\");\n        printf(FMT_LIMB, tab[i]);\n    }\n    printf(\"\\n\");\n}\n\n/* for debugging */\nvoid bf_print_str(const char *str, const bf_t *a)\n{\n    slimb_t i;\n    printf(\"%s=\", str);\n\n    if (a->expn == BF_EXP_NAN) {\n        printf(\"NaN\");\n    } else {\n        if (a->sign)\n            putchar('-');\n        if (a->expn == BF_EXP_ZERO) {\n            putchar('0');\n        } else if (a->expn == BF_EXP_INF) {\n            printf(\"Inf\");\n        } else {\n            printf(\"0x0.\");\n            for(i = a->len - 1; i >= 0; i--)\n                printf(FMT_LIMB, a->tab[i]);\n            printf(\"p%\" PRId_LIMB, a->expn);\n        }\n    }\n    printf(\"\\n\");\n}\n\n/* compare the absolute value of 'a' and 'b'. Return < 0 if a < b, 0\n   if a = b and > 0 otherwise. */\nint bf_cmpu(const bf_t *a, const bf_t *b)\n{\n    slimb_t i;\n    limb_t len, v1, v2;\n    \n    if (a->expn != b->expn) {\n        if (a->expn < b->expn)\n            return -1;\n        else\n            return 1;\n    }\n    len = bf_max(a->len, b->len);\n    for(i = len - 1; i >= 0; i--) {\n        v1 = get_limbz(a, a->len - len + i);\n        v2 = get_limbz(b, b->len - len + i);\n        if (v1 != v2) {\n            if (v1 < v2)\n                return -1;\n            else\n                return 1;\n        }\n    }\n    return 0;\n}\n\n/* Full order: -0 < 0, NaN == NaN and NaN is larger than all other numbers */\nint bf_cmp_full(const bf_t *a, const bf_t *b)\n{\n    int res;\n    \n    if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {\n        if (a->expn == b->expn)\n            res = 0;\n        else if (a->expn == BF_EXP_NAN)\n            res = 1;\n        else\n            res = -1;\n    } else if (a->sign != b->sign) {\n        res = 1 - 2 * a->sign;\n    } else {\n        res = bf_cmpu(a, b);\n        if (a->sign)\n            res = -res;\n    }\n    return res;\n}\n\n/* Standard floating point comparison: return 2 if one of the operands\n   is NaN (unordered) or -1, 0, 1 depending on the ordering assuming\n   -0 == +0 */\nint bf_cmp(const bf_t *a, const bf_t *b)\n{\n    int res;\n    \n    if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {\n        res = 2;\n    } else if (a->sign != b->sign) {\n        if (a->expn == BF_EXP_ZERO && b->expn == BF_EXP_ZERO)\n            res = 0;\n        else\n            res = 1 - 2 * a->sign;\n    } else {\n        res = bf_cmpu(a, b);\n        if (a->sign)\n            res = -res;\n    }\n    return res;\n}\n\n/* Compute the number of bits 'n' matching the pattern:\n   a= X1000..0\n   b= X0111..1\n              \n   When computing a-b, the result will have at least n leading zero\n   bits.\n\n   Precondition: a > b and a.expn - b.expn = 0 or 1\n*/\nstatic limb_t count_cancelled_bits(const bf_t *a, const bf_t *b)\n{\n    slimb_t bit_offset, b_offset, n;\n    int p, p1;\n    limb_t v1, v2, mask;\n\n    bit_offset = a->len * LIMB_BITS - 1;\n    b_offset = (b->len - a->len) * LIMB_BITS - (LIMB_BITS - 1) +\n        a->expn - b->expn;\n    n = 0;\n\n    /* first search the equals bits */\n    for(;;) {\n        v1 = get_limbz(a, bit_offset >> LIMB_LOG2_BITS);\n        v2 = get_bits(b->tab, b->len, bit_offset + b_offset);\n        //        printf(\"v1=\" FMT_LIMB \" v2=\" FMT_LIMB \"\\n\", v1, v2);\n        if (v1 != v2)\n            break;\n        n += LIMB_BITS;\n        bit_offset -= LIMB_BITS;\n    }\n    /* find the position of the first different bit */\n    p = clz(v1 ^ v2) + 1;\n    n += p;\n    /* then search for '0' in a and '1' in b */\n    p = LIMB_BITS - p;\n    if (p > 0) {\n        /* search in the trailing p bits of v1 and v2 */\n        mask = limb_mask(0, p - 1);\n        p1 = bf_min(clz(v1 & mask), clz((~v2) & mask)) - (LIMB_BITS - p);\n        n += p1;\n        if (p1 != p)\n            goto done;\n    }\n    bit_offset -= LIMB_BITS;\n    for(;;) {\n        v1 = get_limbz(a, bit_offset >> LIMB_LOG2_BITS);\n        v2 = get_bits(b->tab, b->len, bit_offset + b_offset);\n        //        printf(\"v1=\" FMT_LIMB \" v2=\" FMT_LIMB \"\\n\", v1, v2);\n        if (v1 != 0 || v2 != -1) {\n            /* different: count the matching bits */\n            p1 = bf_min(clz(v1), clz(~v2));\n            n += p1;\n            break;\n        }\n        n += LIMB_BITS;\n        bit_offset -= LIMB_BITS;\n    }\n done:\n    return n;\n}\n\nstatic int bf_add_internal(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n                           bf_flags_t flags, int b_neg)\n{\n    const bf_t *tmp;\n    int is_sub, ret, cmp_res, a_sign, b_sign;\n\n    a_sign = a->sign;\n    b_sign = b->sign ^ b_neg;\n    is_sub = a_sign ^ b_sign;\n    cmp_res = bf_cmpu(a, b);\n    if (cmp_res < 0) {\n        tmp = a;\n        a = b;\n        b = tmp;\n        a_sign = b_sign; /* b_sign is never used later */\n    }\n    /* abs(a) >= abs(b) */\n    if (cmp_res == 0 && is_sub && a->expn < BF_EXP_INF) {\n        /* zero result */\n        bf_set_zero(r, (flags & BF_RND_MASK) == BF_RNDD);\n        ret = 0;\n    } else if (a->len == 0 || b->len == 0) {\n        ret = 0;\n        if (a->expn >= BF_EXP_INF) {\n            if (a->expn == BF_EXP_NAN) {\n                /* at least one operand is NaN */\n                bf_set_nan(r);\n            } else if (b->expn == BF_EXP_INF && is_sub) {\n                /* infinities with different signs */\n                bf_set_nan(r);\n                ret = BF_ST_INVALID_OP;\n            } else {\n                bf_set_inf(r, a_sign);\n            }\n        } else {\n            /* at least one zero and not subtract */\n            bf_set(r, a);\n            r->sign = a_sign;\n            goto renorm;\n        }\n    } else {\n        slimb_t d, a_offset, b_bit_offset, i, cancelled_bits;\n        limb_t carry, v1, v2, u, r_len, carry1, precl, tot_len, z, sub_mask;\n\n        r->sign = a_sign;\n        r->expn = a->expn;\n        d = a->expn - b->expn;\n        /* must add more precision for the leading cancelled bits in\n           subtraction */\n        if (is_sub) {\n            if (d <= 1)\n                cancelled_bits = count_cancelled_bits(a, b);\n            else\n                cancelled_bits = 1;\n        } else {\n            cancelled_bits = 0;\n        }\n        \n        /* add two extra bits for rounding */\n        precl = (cancelled_bits + prec + 2 + LIMB_BITS - 1) / LIMB_BITS;\n        tot_len = bf_max(a->len, b->len + (d + LIMB_BITS - 1) / LIMB_BITS);\n        r_len = bf_min(precl, tot_len);\n        if (bf_resize(r, r_len))\n            goto fail;\n        a_offset = a->len - r_len;\n        b_bit_offset = (b->len - r_len) * LIMB_BITS + d;\n\n        /* compute the bits before for the rounding */\n        carry = is_sub;\n        z = 0;\n        sub_mask = -is_sub;\n        i = r_len - tot_len;\n        while (i < 0) {\n            slimb_t ap, bp;\n            BOOL inflag;\n            \n            ap = a_offset + i;\n            bp = b_bit_offset + i * LIMB_BITS;\n            inflag = FALSE;\n            if (ap >= 0 && ap < a->len) {\n                v1 = a->tab[ap];\n                inflag = TRUE;\n            } else {\n                v1 = 0;\n            }\n            if (bp + LIMB_BITS > 0 && bp < (slimb_t)(b->len * LIMB_BITS)) {\n                v2 = get_bits(b->tab, b->len, bp);\n                inflag = TRUE;\n            } else {\n                v2 = 0;\n            }\n            if (!inflag) {\n                /* outside 'a' and 'b': go directly to the next value\n                   inside a or b so that the running time does not\n                   depend on the exponent difference */\n                i = 0;\n                if (ap < 0)\n                    i = bf_min(i, -a_offset);\n                /* b_bit_offset + i * LIMB_BITS + LIMB_BITS >= 1\n                   equivalent to \n                   i >= ceil(-b_bit_offset + 1 - LIMB_BITS) / LIMB_BITS)\n                */\n                if (bp + LIMB_BITS <= 0)\n                    i = bf_min(i, (-b_bit_offset) >> LIMB_LOG2_BITS);\n            } else {\n                i++;\n            }\n            v2 ^= sub_mask;\n            u = v1 + v2;\n            carry1 = u < v1;\n            u += carry;\n            carry = (u < carry) | carry1;\n            z |= u;\n        }\n        /* and the result */\n        for(i = 0; i < r_len; i++) {\n            v1 = get_limbz(a, a_offset + i);\n            v2 = get_bits(b->tab, b->len, b_bit_offset + i * LIMB_BITS);\n            v2 ^= sub_mask;\n            u = v1 + v2;\n            carry1 = u < v1;\n            u += carry;\n            carry = (u < carry) | carry1;\n            r->tab[i] = u;\n        }\n        /* set the extra bits for the rounding */\n        r->tab[0] |= (z != 0);\n\n        /* carry is only possible in add case */\n        if (!is_sub && carry) {\n            if (bf_resize(r, r_len + 1))\n                goto fail;\n            r->tab[r_len] = 1;\n            r->expn += LIMB_BITS;\n        }\n    renorm:\n        ret = bf_normalize_and_round(r, prec, flags);\n    }\n    return ret;\n fail:\n    bf_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\nstatic int __bf_add(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n                     bf_flags_t flags)\n{\n    return bf_add_internal(r, a, b, prec, flags, 0);\n}\n\nstatic int __bf_sub(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n                     bf_flags_t flags)\n{\n    return bf_add_internal(r, a, b, prec, flags, 1);\n}\n\nlimb_t mp_add(limb_t *res, const limb_t *op1, const limb_t *op2, \n              limb_t n, limb_t carry)\n{\n    slimb_t i;\n    limb_t k, a, v, k1;\n    \n    k = carry;\n    for(i=0;i<n;i++) {\n        v = op1[i];\n        a = v + op2[i];\n        k1 = a < v;\n        a = a + k;\n        k = (a < k) | k1;\n        res[i] = a;\n    }\n    return k;\n}\n\nlimb_t mp_add_ui(limb_t *tab, limb_t b, size_t n)\n{\n    size_t i;\n    limb_t k, a;\n\n    k=b;\n    for(i=0;i<n;i++) {\n        if (k == 0)\n            break;\n        a = tab[i] + k;\n        k = (a < k);\n        tab[i] = a;\n    }\n    return k;\n}\n\nlimb_t mp_sub(limb_t *res, const limb_t *op1, const limb_t *op2, \n              mp_size_t n, limb_t carry)\n{\n    int i;\n    limb_t k, a, v, k1;\n    \n    k = carry;\n    for(i=0;i<n;i++) {\n        v = op1[i];\n        a = v - op2[i];\n        k1 = a > v;\n        v = a - k;\n        k = (v > a) | k1;\n        res[i] = v;\n    }\n    return k;\n}\n\n/* compute 0 - op2 */\nstatic limb_t mp_neg(limb_t *res, const limb_t *op2, mp_size_t n, limb_t carry)\n{\n    int i;\n    limb_t k, a, v, k1;\n    \n    k = carry;\n    for(i=0;i<n;i++) {\n        v = 0;\n        a = v - op2[i];\n        k1 = a > v;\n        v = a - k;\n        k = (v > a) | k1;\n        res[i] = v;\n    }\n    return k;\n}\n\nlimb_t mp_sub_ui(limb_t *tab, limb_t b, mp_size_t n)\n{\n    mp_size_t i;\n    limb_t k, a, v;\n    \n    k=b;\n    for(i=0;i<n;i++) {\n        v = tab[i];\n        a = v - k;\n        k = a > v;\n        tab[i] = a;\n        if (k == 0)\n            break;\n    }\n    return k;\n}\n\n/* r = (a + high*B^n) >> shift. Return the remainder r (0 <= r < 2^shift). \n   1 <= shift <= LIMB_BITS - 1 */\nstatic limb_t mp_shr(limb_t *tab_r, const limb_t *tab, mp_size_t n, \n                     int shift, limb_t high)\n{\n    mp_size_t i;\n    limb_t l, a;\n\n    assert(shift >= 1 && shift < LIMB_BITS);\n    l = high;\n    for(i = n - 1; i >= 0; i--) {\n        a = tab[i];\n        tab_r[i] = (a >> shift) | (l << (LIMB_BITS - shift));\n        l = a;\n    }\n    return l & (((limb_t)1 << shift) - 1);\n}\n\n/* tabr[] = taba[] * b + l. Return the high carry */\nstatic limb_t mp_mul1(limb_t *tabr, const limb_t *taba, limb_t n, \n                      limb_t b, limb_t l)\n{\n    limb_t i;\n    dlimb_t t;\n\n    for(i = 0; i < n; i++) {\n        t = (dlimb_t)taba[i] * (dlimb_t)b + l;\n        tabr[i] = t;\n        l = t >> LIMB_BITS;\n    }\n    return l;\n}\n\n/* tabr[] += taba[] * b, return the high word. */\nstatic limb_t mp_add_mul1(limb_t *tabr, const limb_t *taba, limb_t n,\n                          limb_t b)\n{\n    limb_t i, l;\n    dlimb_t t;\n    \n    l = 0;\n    for(i = 0; i < n; i++) {\n        t = (dlimb_t)taba[i] * (dlimb_t)b + l + tabr[i];\n        tabr[i] = t;\n        l = t >> LIMB_BITS;\n    }\n    return l;\n}\n\n/* size of the result : op1_size + op2_size. */\nstatic void mp_mul_basecase(limb_t *result, \n                            const limb_t *op1, limb_t op1_size, \n                            const limb_t *op2, limb_t op2_size) \n{\n    limb_t i, r;\n    \n    result[op1_size] = mp_mul1(result, op1, op1_size, op2[0], 0);\n    for(i=1;i<op2_size;i++) {\n        r = mp_add_mul1(result + i, op1, op1_size, op2[i]);\n        result[i + op1_size] = r;\n    }\n}\n\n/* return 0 if OK, -1 if memory error */\n/* XXX: change API so that result can be allocated */\nint mp_mul(bf_context_t *s, limb_t *result, \n           const limb_t *op1, limb_t op1_size, \n           const limb_t *op2, limb_t op2_size) \n{\n#ifdef USE_FFT_MUL\n    if (unlikely(bf_min(op1_size, op2_size) >= FFT_MUL_THRESHOLD)) {\n        bf_t r_s, *r = &r_s;\n        r->tab = result;\n        /* XXX: optimize memory usage in API */\n        if (fft_mul(s, r, (limb_t *)op1, op1_size,\n                    (limb_t *)op2, op2_size, FFT_MUL_R_NORESIZE))\n            return -1;\n    } else\n#endif\n    {\n        mp_mul_basecase(result, op1, op1_size, op2, op2_size);\n    }\n    return 0;\n}\n\n/* tabr[] -= taba[] * b. Return the value to substract to the high\n   word. */\nstatic limb_t mp_sub_mul1(limb_t *tabr, const limb_t *taba, limb_t n,\n                          limb_t b)\n{\n    limb_t i, l;\n    dlimb_t t;\n    \n    l = 0;\n    for(i = 0; i < n; i++) {\n        t = tabr[i] - (dlimb_t)taba[i] * (dlimb_t)b - l;\n        tabr[i] = t;\n        l = -(t >> LIMB_BITS);\n    }\n    return l;\n}\n\n/* WARNING: d must be >= 2^(LIMB_BITS-1) */\nstatic inline limb_t udiv1norm_init(limb_t d)\n{\n    limb_t a0, a1;\n    a1 = -d - 1;\n    a0 = -1;\n    return (((dlimb_t)a1 << LIMB_BITS) | a0) / d;\n}\n\n/* return the quotient and the remainder in '*pr'of 'a1*2^LIMB_BITS+a0\n   / d' with 0 <= a1 < d. */\nstatic inline limb_t udiv1norm(limb_t *pr, limb_t a1, limb_t a0,\n                                limb_t d, limb_t d_inv)\n{\n    limb_t n1m, n_adj, q, r, ah;\n    dlimb_t a;\n    n1m = ((slimb_t)a0 >> (LIMB_BITS - 1));\n    n_adj = a0 + (n1m & d);\n    a = (dlimb_t)d_inv * (a1 - n1m) + n_adj;\n    q = (a >> LIMB_BITS) + a1;\n    /* compute a - q * r and update q so that the remainder is\\\n       between 0 and d - 1 */\n    a = ((dlimb_t)a1 << LIMB_BITS) | a0;\n    a = a - (dlimb_t)q * d - d;\n    ah = a >> LIMB_BITS;\n    q += 1 + ah;\n    r = (limb_t)a + (ah & d);\n    *pr = r;\n    return q;\n}\n\n/* b must be >= 1 << (LIMB_BITS - 1) */\nstatic limb_t mp_div1norm(limb_t *tabr, const limb_t *taba, limb_t n,\n                          limb_t b, limb_t r)\n{\n    slimb_t i;\n\n    if (n >= UDIV1NORM_THRESHOLD) {\n        limb_t b_inv;\n        b_inv = udiv1norm_init(b);\n        for(i = n - 1; i >= 0; i--) {\n            tabr[i] = udiv1norm(&r, r, taba[i], b, b_inv);\n        }\n    } else {\n        dlimb_t a1;\n        for(i = n - 1; i >= 0; i--) {\n            a1 = ((dlimb_t)r << LIMB_BITS) | taba[i];\n            tabr[i] = a1 / b;\n            r = a1 % b;\n        }\n    }\n    return r;\n}\n\nstatic int mp_divnorm_large(bf_context_t *s, \n                            limb_t *tabq, limb_t *taba, limb_t na, \n                            const limb_t *tabb, limb_t nb);\n\n/* base case division: divides taba[0..na-1] by tabb[0..nb-1]. tabb[nb\n   - 1] must be >= 1 << (LIMB_BITS - 1). na - nb must be >= 0. 'taba'\n   is modified and contains the remainder (nb limbs). tabq[0..na-nb]\n   contains the quotient with tabq[na - nb] <= 1. */\nstatic int mp_divnorm(bf_context_t *s, limb_t *tabq, limb_t *taba, limb_t na, \n                      const limb_t *tabb, limb_t nb)\n{\n    limb_t r, a, c, q, v, b1, b1_inv, n, dummy_r;\n    slimb_t i, j;\n\n    b1 = tabb[nb - 1];\n    if (nb == 1) {\n        taba[0] = mp_div1norm(tabq, taba, na, b1, 0);\n        return 0;\n    }\n    n = na - nb;\n    if (bf_min(n, nb) >= DIVNORM_LARGE_THRESHOLD) {\n        return mp_divnorm_large(s, tabq, taba, na, tabb, nb);\n    }\n    \n    if (n >= UDIV1NORM_THRESHOLD)\n        b1_inv = udiv1norm_init(b1);\n    else\n        b1_inv = 0;\n\n    /* first iteration: the quotient is only 0 or 1 */\n    q = 1;\n    for(j = nb - 1; j >= 0; j--) {\n        if (taba[n + j] != tabb[j]) {\n            if (taba[n + j] < tabb[j])\n                q = 0;\n            break;\n        }\n    }\n    tabq[n] = q;\n    if (q) {\n        mp_sub(taba + n, taba + n, tabb, nb, 0);\n    }\n    \n    for(i = n - 1; i >= 0; i--) {\n        if (unlikely(taba[i + nb] >= b1)) {\n            q = -1;\n        } else if (b1_inv) {\n            q = udiv1norm(&dummy_r, taba[i + nb], taba[i + nb - 1], b1, b1_inv);\n        } else {\n            dlimb_t al;\n            al = ((dlimb_t)taba[i + nb] << LIMB_BITS) | taba[i + nb - 1];\n            q = al / b1;\n            r = al % b1;\n        }\n        r = mp_sub_mul1(taba + i, tabb, nb, q);\n\n        v = taba[i + nb];\n        a = v - r;\n        c = (a > v);\n        taba[i + nb] = a;\n\n        if (c != 0) {\n            /* negative result */\n            for(;;) {\n                q--;\n                c = mp_add(taba + i, taba + i, tabb, nb, 0);\n                /* propagate carry and test if positive result */\n                if (c != 0) {\n                    if (++taba[i + nb] == 0) {\n                        break;\n                    }\n                }\n            }\n        }\n        tabq[i] = q;\n    }\n    return 0;\n}\n\n/* compute r=B^(2*n)/a such as a*r < B^(2*n) < a*r + 2 with n >= 1. 'a'\n   has n limbs with a[n-1] >= B/2 and 'r' has n+1 limbs with r[n] = 1.\n   \n   See Modern Computer Arithmetic by Richard P. Brent and Paul\n   Zimmermann, algorithm 3.5 */\nint mp_recip(bf_context_t *s, limb_t *tabr, const limb_t *taba, limb_t n)\n{\n    mp_size_t l, h, k, i;\n    limb_t *tabxh, *tabt, c, *tabu;\n    \n    if (n <= 2) {\n        /* return ceil(B^(2*n)/a) - 1 */\n        /* XXX: could avoid allocation */\n        tabu = bf_malloc(s, sizeof(limb_t) * (2 * n + 1));\n        tabt = bf_malloc(s, sizeof(limb_t) * (n + 2));\n        if (!tabt || !tabu)\n            goto fail;\n        for(i = 0; i < 2 * n; i++)\n            tabu[i] = 0;\n        tabu[2 * n] = 1;\n        if (mp_divnorm(s, tabt, tabu, 2 * n + 1, taba, n))\n            goto fail;\n        for(i = 0; i < n + 1; i++)\n            tabr[i] = tabt[i];\n        if (mp_scan_nz(tabu, n) == 0) {\n            /* only happens for a=B^n/2 */\n            mp_sub_ui(tabr, 1, n + 1);\n        }\n    } else {\n        l = (n - 1) / 2;\n        h = n - l;\n        /* n=2p  -> l=p-1, h = p + 1, k = p + 3\n           n=2p+1-> l=p,  h = p + 1; k = p + 2\n        */\n        tabt = bf_malloc(s, sizeof(limb_t) * (n + h + 1));\n        tabu = bf_malloc(s, sizeof(limb_t) * (n + 2 * h - l + 2));\n        if (!tabt || !tabu)\n            goto fail;\n        tabxh = tabr + l;\n        if (mp_recip(s, tabxh, taba + l, h))\n            goto fail;\n        if (mp_mul(s, tabt, taba, n, tabxh, h + 1)) /* n + h + 1 limbs */\n            goto fail;\n        while (tabt[n + h] != 0) {\n            mp_sub_ui(tabxh, 1, h + 1);\n            c = mp_sub(tabt, tabt, taba, n, 0);\n            mp_sub_ui(tabt + n, c, h + 1);\n        }\n        /* T = B^(n+h) - T */\n        mp_neg(tabt, tabt, n + h + 1, 0);\n        tabt[n + h]++;\n        if (mp_mul(s, tabu, tabt + l, n + h + 1 - l, tabxh, h + 1))\n            goto fail;\n        /* n + 2*h - l + 2 limbs */\n        k = 2 * h - l;\n        for(i = 0; i < l; i++)\n            tabr[i] = tabu[i + k];\n        mp_add(tabr + l, tabr + l, tabu + 2 * h, h, 0);\n    }\n    bf_free(s, tabt);\n    bf_free(s, tabu);\n    return 0;\n fail:\n    bf_free(s, tabt);\n    bf_free(s, tabu);\n    return -1;\n}\n\n/* return -1, 0 or 1 */\nstatic int mp_cmp(const limb_t *taba, const limb_t *tabb, mp_size_t n)\n{\n    mp_size_t i;\n    for(i = n - 1; i >= 0; i--) {\n        if (taba[i] != tabb[i]) {\n            if (taba[i] < tabb[i])\n                return -1;\n            else\n                return 1;\n        }\n    }\n    return 0;\n}\n\n//#define DEBUG_DIVNORM_LARGE\n//#define DEBUG_DIVNORM_LARGE2\n\n/* subquadratic divnorm */\nstatic int mp_divnorm_large(bf_context_t *s, \n                            limb_t *tabq, limb_t *taba, limb_t na, \n                            const limb_t *tabb, limb_t nb)\n{\n    limb_t *tabb_inv, nq, *tabt, i, n;\n    nq = na - nb;\n#ifdef DEBUG_DIVNORM_LARGE\n    printf(\"na=%d nb=%d nq=%d\\n\", (int)na, (int)nb, (int)nq);\n    mp_print_str(\"a\", taba, na);\n    mp_print_str(\"b\", tabb, nb);\n#endif\n    assert(nq >= 1);\n    n = nq;\n    if (nq < nb)\n        n++; \n    tabb_inv = bf_malloc(s, sizeof(limb_t) * (n + 1));\n    tabt = bf_malloc(s, sizeof(limb_t) * 2 * (n + 1));\n    if (!tabb_inv || !tabt)\n        goto fail;\n\n    if (n >= nb) {\n        for(i = 0; i < n - nb; i++)\n            tabt[i] = 0;\n        for(i = 0; i < nb; i++)\n            tabt[i + n - nb] = tabb[i];\n    } else {\n        /* truncate B: need to increment it so that the approximate\n           inverse is smaller that the exact inverse */\n        for(i = 0; i < n; i++)\n            tabt[i] = tabb[i + nb - n];\n        if (mp_add_ui(tabt, 1, n)) {\n            /* tabt = B^n : tabb_inv = B^n */\n            memset(tabb_inv, 0, n * sizeof(limb_t));\n            tabb_inv[n] = 1;\n            goto recip_done;\n        }\n    }\n    if (mp_recip(s, tabb_inv, tabt, n))\n        goto fail;\n recip_done:\n    /* Q=A*B^-1 */\n    if (mp_mul(s, tabt, tabb_inv, n + 1, taba + na - (n + 1), n + 1))\n        goto fail;\n    \n    for(i = 0; i < nq + 1; i++)\n        tabq[i] = tabt[i + 2 * (n + 1) - (nq + 1)];\n#ifdef DEBUG_DIVNORM_LARGE\n    mp_print_str(\"q\", tabq, nq + 1);\n#endif\n\n    bf_free(s, tabt);\n    bf_free(s, tabb_inv);\n    tabb_inv = NULL;\n    \n    /* R=A-B*Q */\n    tabt = bf_malloc(s, sizeof(limb_t) * (na + 1));\n    if (!tabt)\n        goto fail;\n    if (mp_mul(s, tabt, tabq, nq + 1, tabb, nb))\n        goto fail;\n    /* we add one more limb for the result */\n    mp_sub(taba, taba, tabt, nb + 1, 0);\n    bf_free(s, tabt);\n    /* the approximated quotient is smaller than than the exact one,\n       hence we may have to increment it */\n#ifdef DEBUG_DIVNORM_LARGE2\n    int cnt = 0;\n    static int cnt_max;\n#endif\n    for(;;) {\n        if (taba[nb] == 0 && mp_cmp(taba, tabb, nb) < 0)\n            break;\n        taba[nb] -= mp_sub(taba, taba, tabb, nb, 0);\n        mp_add_ui(tabq, 1, nq + 1);\n#ifdef DEBUG_DIVNORM_LARGE2\n        cnt++;\n#endif\n    }\n#ifdef DEBUG_DIVNORM_LARGE2\n    if (cnt > cnt_max) {\n        cnt_max = cnt;\n        printf(\"\\ncnt=%d nq=%d nb=%d\\n\", cnt_max, (int)nq, (int)nb);\n    }\n#endif\n    return 0;\n fail:\n    bf_free(s, tabb_inv);\n    bf_free(s, tabt);\n    return -1;\n}\n\nint bf_mul(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n           bf_flags_t flags)\n{\n    int ret, r_sign;\n\n    if (a->len < b->len) {\n        const bf_t *tmp = a;\n        a = b;\n        b = tmp;\n    }\n    r_sign = a->sign ^ b->sign;\n    /* here b->len <= a->len */\n    if (b->len == 0) {\n        if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            ret = 0;\n        } else if (a->expn == BF_EXP_INF || b->expn == BF_EXP_INF) {\n            if ((a->expn == BF_EXP_INF && b->expn == BF_EXP_ZERO) ||\n                (a->expn == BF_EXP_ZERO && b->expn == BF_EXP_INF)) {\n                bf_set_nan(r);\n                ret = BF_ST_INVALID_OP;\n            } else {\n                bf_set_inf(r, r_sign);\n                ret = 0;\n            }\n        } else {\n            bf_set_zero(r, r_sign);\n            ret = 0;\n        }\n    } else {\n        bf_t tmp, *r1 = NULL;\n        limb_t a_len, b_len, precl;\n        limb_t *a_tab, *b_tab;\n            \n        a_len = a->len;\n        b_len = b->len;\n        \n        if ((flags & BF_RND_MASK) == BF_RNDF) {\n            /* faithful rounding does not require using the full inputs */\n            precl = (prec + 2 + LIMB_BITS - 1) / LIMB_BITS;\n            a_len = bf_min(a_len, precl);\n            b_len = bf_min(b_len, precl);\n        }\n        a_tab = a->tab + a->len - a_len;\n        b_tab = b->tab + b->len - b_len;\n        \n#ifdef USE_FFT_MUL\n        if (b_len >= FFT_MUL_THRESHOLD) {\n            int mul_flags = 0;\n            if (r == a)\n                mul_flags |= FFT_MUL_R_OVERLAP_A;\n            if (r == b)\n                mul_flags |= FFT_MUL_R_OVERLAP_B;\n            if (fft_mul(r->ctx, r, a_tab, a_len, b_tab, b_len, mul_flags))\n                goto fail;\n        } else\n#endif\n        {\n            if (r == a || r == b) {\n                bf_init(r->ctx, &tmp);\n                r1 = r;\n                r = &tmp;\n            }\n            if (bf_resize(r, a_len + b_len)) {\n            fail:\n                bf_set_nan(r);\n                ret = BF_ST_MEM_ERROR;\n                goto done;\n            }\n            mp_mul_basecase(r->tab, a_tab, a_len, b_tab, b_len);\n        }\n        r->sign = r_sign;\n        r->expn = a->expn + b->expn;\n        ret = bf_normalize_and_round(r, prec, flags);\n    done:\n        if (r == &tmp)\n            bf_move(r1, &tmp);\n    }\n    return ret;\n}\n\n/* multiply 'r' by 2^e */\nint bf_mul_2exp(bf_t *r, slimb_t e, limb_t prec, bf_flags_t flags)\n{\n    slimb_t e_max;\n    if (r->len == 0)\n        return 0;\n    e_max = ((limb_t)1 << BF_EXT_EXP_BITS_MAX) - 1;\n    e = bf_max(e, -e_max);\n    e = bf_min(e, e_max);\n    r->expn += e;\n    return __bf_round(r, prec, flags, r->len, 0);\n}\n\n/* Return e such as a=m*2^e with m odd integer. return 0 if a is zero,\n   Infinite or Nan. */\nslimb_t bf_get_exp_min(const bf_t *a)\n{\n    slimb_t i;\n    limb_t v;\n    int k;\n    \n    for(i = 0; i < a->len; i++) {\n        v = a->tab[i];\n        if (v != 0) {\n            k = ctz(v);\n            return a->expn - (a->len - i) * LIMB_BITS + k;\n        }\n    }\n    return 0;\n}\n\n/* a and b must be finite numbers with a >= 0 and b > 0. 'q' is the\n   integer defined as floor(a/b) and r = a - q * b. */\nstatic void bf_tdivremu(bf_t *q, bf_t *r,\n                        const bf_t *a, const bf_t *b)\n{\n    if (bf_cmpu(a, b) < 0) {\n        bf_set_ui(q, 0);\n        bf_set(r, a);\n    } else {\n        bf_div(q, a, b, bf_max(a->expn - b->expn + 1, 2), BF_RNDZ);\n        bf_rint(q, BF_RNDZ);\n        bf_mul(r, q, b, BF_PREC_INF, BF_RNDZ);\n        bf_sub(r, a, r, BF_PREC_INF, BF_RNDZ);\n    }\n}\n\nstatic int __bf_div(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n                    bf_flags_t flags)\n{\n    bf_context_t *s = r->ctx;\n    int ret, r_sign;\n    limb_t n, nb, precl;\n    \n    r_sign = a->sign ^ b->sign;\n    if (a->expn >= BF_EXP_INF || b->expn >= BF_EXP_INF) {\n        if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF && b->expn == BF_EXP_INF) {\n            bf_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else if (a->expn == BF_EXP_INF) {\n            bf_set_inf(r, r_sign);\n            return 0;\n        } else {\n            bf_set_zero(r, r_sign);\n            return 0;\n        }\n    } else if (a->expn == BF_EXP_ZERO) {\n        if (b->expn == BF_EXP_ZERO) {\n            bf_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bf_set_zero(r, r_sign);\n            return 0;\n        }\n    } else if (b->expn == BF_EXP_ZERO) {\n        bf_set_inf(r, r_sign);\n        return BF_ST_DIVIDE_ZERO;\n    }\n\n    /* number of limbs of the quotient (2 extra bits for rounding) */\n    precl = (prec + 2 + LIMB_BITS - 1) / LIMB_BITS;\n    nb = b->len;\n    n = bf_max(a->len, precl);\n    \n    {\n        limb_t *taba, na;\n        slimb_t d;\n        \n        na = n + nb;\n        taba = bf_malloc(s, (na + 1) * sizeof(limb_t));\n        if (!taba)\n            goto fail;\n        d = na - a->len;\n        memset(taba, 0, d * sizeof(limb_t));\n        memcpy(taba + d, a->tab, a->len * sizeof(limb_t));\n        if (bf_resize(r, n + 1))\n            goto fail1;\n        if (mp_divnorm(s, r->tab, taba, na, b->tab, nb)) {\n        fail1:\n            bf_free(s, taba);\n            goto fail;\n        }\n        /* see if non zero remainder */\n        if (mp_scan_nz(taba, nb))\n            r->tab[0] |= 1;\n        bf_free(r->ctx, taba);\n        r->expn = a->expn - b->expn + LIMB_BITS;\n        r->sign = r_sign;\n        ret = bf_normalize_and_round(r, prec, flags);\n    }\n    return ret;\n fail:\n    bf_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\n/* division and remainder. \n   \n   rnd_mode is the rounding mode for the quotient. The additional\n   rounding mode BF_RND_EUCLIDIAN is supported.\n\n   'q' is an integer. 'r' is rounded with prec and flags (prec can be\n   BF_PREC_INF).\n*/\nint bf_divrem(bf_t *q, bf_t *r, const bf_t *a, const bf_t *b,\n              limb_t prec, bf_flags_t flags, int rnd_mode)\n{\n    bf_t a1_s, *a1 = &a1_s;\n    bf_t b1_s, *b1 = &b1_s;\n    int q_sign, ret;\n    BOOL is_ceil, is_rndn;\n    \n    assert(q != a && q != b);\n    assert(r != a && r != b);\n    assert(q != r);\n    \n    if (a->len == 0 || b->len == 0) {\n        bf_set_zero(q, 0);\n        if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF || b->expn == BF_EXP_ZERO) {\n            bf_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bf_set(r, a);\n            return bf_round(r, prec, flags);\n        }\n    }\n\n    q_sign = a->sign ^ b->sign;\n    is_rndn = (rnd_mode == BF_RNDN || rnd_mode == BF_RNDNA);\n    switch(rnd_mode) {\n    default:\n    case BF_RNDZ:\n    case BF_RNDN:\n    case BF_RNDNA:\n        is_ceil = FALSE;\n        break;\n    case BF_RNDD:\n        is_ceil = q_sign;\n        break;\n    case BF_RNDU:\n        is_ceil = q_sign ^ 1;\n        break;\n    case BF_RNDA:\n        is_ceil = TRUE;\n        break;\n    case BF_DIVREM_EUCLIDIAN:\n        is_ceil = a->sign;\n        break;\n    }\n\n    a1->expn = a->expn;\n    a1->tab = a->tab;\n    a1->len = a->len;\n    a1->sign = 0;\n    \n    b1->expn = b->expn;\n    b1->tab = b->tab;\n    b1->len = b->len;\n    b1->sign = 0;\n\n    /* XXX: could improve to avoid having a large 'q' */\n    bf_tdivremu(q, r, a1, b1);\n    if (bf_is_nan(q) || bf_is_nan(r))\n        goto fail;\n\n    if (r->len != 0) {\n        if (is_rndn) {\n            int res;\n            b1->expn--;\n            res = bf_cmpu(r, b1);\n            b1->expn++;\n            if (res > 0 ||\n                (res == 0 &&\n                 (rnd_mode == BF_RNDNA ||\n                  get_bit(q->tab, q->len, q->len * LIMB_BITS - q->expn)))) {\n                goto do_sub_r;\n            }\n        } else if (is_ceil) {\n        do_sub_r:\n            ret = bf_add_si(q, q, 1, BF_PREC_INF, BF_RNDZ);\n            ret |= bf_sub(r, r, b1, BF_PREC_INF, BF_RNDZ);\n            if (ret & BF_ST_MEM_ERROR)\n                goto fail;\n        }\n    }\n\n    r->sign ^= a->sign;\n    q->sign = q_sign;\n    return bf_round(r, prec, flags);\n fail:\n    bf_set_nan(q);\n    bf_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\nint bf_rem(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n           bf_flags_t flags, int rnd_mode)\n{\n    bf_t q_s, *q = &q_s;\n    int ret;\n    \n    bf_init(r->ctx, q);\n    ret = bf_divrem(q, r, a, b, prec, flags, rnd_mode);\n    bf_delete(q);\n    return ret;\n}\n\nstatic inline int bf_get_limb(slimb_t *pres, const bf_t *a, int flags)\n{\n#if LIMB_BITS == 32\n    return bf_get_int32(pres, a, flags);\n#else\n    return bf_get_int64(pres, a, flags);\n#endif\n}\n\nint bf_remquo(slimb_t *pq, bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n              bf_flags_t flags, int rnd_mode)\n{\n    bf_t q_s, *q = &q_s;\n    int ret;\n    \n    bf_init(r->ctx, q);\n    ret = bf_divrem(q, r, a, b, prec, flags, rnd_mode);\n    bf_get_limb(pq, q, BF_GET_INT_MOD);\n    bf_delete(q);\n    return ret;\n}\n\nstatic __maybe_unused inline limb_t mul_mod(limb_t a, limb_t b, limb_t m)\n{\n    dlimb_t t;\n    t = (dlimb_t)a * (dlimb_t)b;\n    return t % m;\n}\n\n#if defined(USE_MUL_CHECK)\nstatic limb_t mp_mod1(const limb_t *tab, limb_t n, limb_t m, limb_t r)\n{\n    slimb_t i;\n    dlimb_t t;\n\n    for(i = n - 1; i >= 0; i--) {\n        t = ((dlimb_t)r << LIMB_BITS) | tab[i];\n        r = t % m;\n    }\n    return r;\n}\n#endif\n\nstatic const uint16_t sqrt_table[192] = {\n128,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,144,145,146,147,148,149,150,150,151,152,153,154,155,155,156,157,158,159,160,160,161,162,163,163,164,165,166,167,167,168,169,170,170,171,172,173,173,174,175,176,176,177,178,178,179,180,181,181,182,183,183,184,185,185,186,187,187,188,189,189,190,191,192,192,193,193,194,195,195,196,197,197,198,199,199,200,201,201,202,203,203,204,204,205,206,206,207,208,208,209,209,210,211,211,212,212,213,214,214,215,215,216,217,217,218,218,219,219,220,221,221,222,222,223,224,224,225,225,226,226,227,227,228,229,229,230,230,231,231,232,232,233,234,234,235,235,236,236,237,237,238,238,239,240,240,241,241,242,242,243,243,244,244,245,245,246,246,247,247,248,248,249,249,250,250,251,251,252,252,253,253,254,254,255,\n};\n\n/* a >= 2^(LIMB_BITS - 2).  Return (s, r) with s=floor(sqrt(a)) and\n   r=a-s^2. 0 <= r <= 2 * s */\nstatic limb_t mp_sqrtrem1(limb_t *pr, limb_t a)\n{\n    limb_t s1, r1, s, r, q, u, num;\n    \n    /* use a table for the 16 -> 8 bit sqrt */\n    s1 = sqrt_table[(a >> (LIMB_BITS - 8)) - 64];\n    r1 = (a >> (LIMB_BITS - 16)) - s1 * s1;\n    if (r1 > 2 * s1) {\n        r1 -= 2 * s1 + 1;\n        s1++;\n    }\n    \n    /* one iteration to get a 32 -> 16 bit sqrt */\n    num = (r1 << 8) | ((a >> (LIMB_BITS - 32 + 8)) & 0xff);\n    q = num / (2 * s1); /* q <= 2^8 */\n    u = num % (2 * s1);\n    s = (s1 << 8) + q;\n    r = (u << 8) | ((a >> (LIMB_BITS - 32)) & 0xff);\n    r -= q * q;\n    if ((slimb_t)r < 0) {\n        s--;\n        r += 2 * s + 1;\n    }\n\n#if LIMB_BITS == 64\n    s1 = s;\n    r1 = r;\n    /* one more iteration for 64 -> 32 bit sqrt */\n    num = (r1 << 16) | ((a >> (LIMB_BITS - 64 + 16)) & 0xffff);\n    q = num / (2 * s1); /* q <= 2^16 */\n    u = num % (2 * s1);\n    s = (s1 << 16) + q;\n    r = (u << 16) | ((a >> (LIMB_BITS - 64)) & 0xffff);\n    r -= q * q;\n    if ((slimb_t)r < 0) {\n        s--;\n        r += 2 * s + 1;\n    }\n#endif\n    *pr = r;\n    return s;\n}\n\n/* return floor(sqrt(a)) */\nlimb_t bf_isqrt(limb_t a)\n{\n    limb_t s, r;\n    int k;\n\n    if (a == 0)\n        return 0;\n    k = clz(a) & ~1;\n    s = mp_sqrtrem1(&r, a << k);\n    s >>= (k >> 1);\n    return s;\n}\n\nstatic limb_t mp_sqrtrem2(limb_t *tabs, limb_t *taba)\n{\n    limb_t s1, r1, s, q, u, a0, a1;\n    dlimb_t r, num;\n    int l;\n\n    a0 = taba[0];\n    a1 = taba[1];\n    s1 = mp_sqrtrem1(&r1, a1);\n    l = LIMB_BITS / 2;\n    num = ((dlimb_t)r1 << l) | (a0 >> l);\n    q = num / (2 * s1);\n    u = num % (2 * s1);\n    s = (s1 << l) + q;\n    r = ((dlimb_t)u << l) | (a0 & (((limb_t)1 << l) - 1));\n    if (unlikely((q >> l) != 0))\n        r -= (dlimb_t)1 << LIMB_BITS; /* special case when q=2^l */\n    else\n        r -= q * q;\n    if ((slimb_t)(r >> LIMB_BITS) < 0) {\n        s--;\n        r += 2 * (dlimb_t)s + 1;\n    }\n    tabs[0] = s;\n    taba[0] = r;\n    return r >> LIMB_BITS;\n}\n\n//#define DEBUG_SQRTREM\n\n/* tmp_buf must contain (n / 2 + 1 limbs). *prh contains the highest\n   limb of the remainder. */\nstatic int mp_sqrtrem_rec(bf_context_t *s, limb_t *tabs, limb_t *taba, limb_t n,\n                          limb_t *tmp_buf, limb_t *prh)\n{\n    limb_t l, h, rh, ql, qh, c, i;\n    \n    if (n == 1) {\n        *prh = mp_sqrtrem2(tabs, taba);\n        return 0;\n    }\n#ifdef DEBUG_SQRTREM\n    mp_print_str(\"a\", taba, 2 * n);\n#endif\n    l = n / 2;\n    h = n - l;\n    if (mp_sqrtrem_rec(s, tabs + l, taba + 2 * l, h, tmp_buf, &qh))\n        return -1;\n#ifdef DEBUG_SQRTREM\n    mp_print_str(\"s1\", tabs + l, h);\n    mp_print_str_h(\"r1\", taba + 2 * l, h, qh);\n    mp_print_str_h(\"r2\", taba + l, n, qh);\n#endif\n    \n    /* the remainder is in taba + 2 * l. Its high bit is in qh */\n    if (qh) {\n        mp_sub(taba + 2 * l, taba + 2 * l, tabs + l, h, 0);\n    }\n    /* instead of dividing by 2*s, divide by s (which is normalized)\n       and update q and r */\n    if (mp_divnorm(s, tmp_buf, taba + l, n, tabs + l, h))\n        return -1;\n    qh += tmp_buf[l];\n    for(i = 0; i < l; i++)\n        tabs[i] = tmp_buf[i];\n    ql = mp_shr(tabs, tabs, l, 1, qh & 1);\n    qh = qh >> 1; /* 0 or 1 */\n    if (ql)\n        rh = mp_add(taba + l, taba + l, tabs + l, h, 0);\n    else\n        rh = 0;\n#ifdef DEBUG_SQRTREM\n    mp_print_str_h(\"q\", tabs, l, qh);\n    mp_print_str_h(\"u\", taba + l, h, rh);\n#endif\n    \n    mp_add_ui(tabs + l, qh, h);\n#ifdef DEBUG_SQRTREM\n    mp_print_str_h(\"s2\", tabs, n, sh);\n#endif\n    \n    /* q = qh, tabs[l - 1 ... 0], r = taba[n - 1 ... l] */\n    /* subtract q^2. if qh = 1 then q = B^l, so we can take shortcuts */\n    if (qh) {\n        c = qh;\n    } else {\n        if (mp_mul(s, taba + n, tabs, l, tabs, l))\n            return -1;\n        c = mp_sub(taba, taba, taba + n, 2 * l, 0);\n    }\n    rh -= mp_sub_ui(taba + 2 * l, c, n - 2 * l);\n    if ((slimb_t)rh < 0) {\n        mp_sub_ui(tabs, 1, n);\n        rh += mp_add_mul1(taba, tabs, n, 2);\n        rh += mp_add_ui(taba, 1, n);\n    }\n    *prh = rh;\n    return 0;\n}\n\n/* 'taba' has 2*n limbs with n >= 1 and taba[2*n-1] >= 2 ^ (LIMB_BITS\n   - 2). Return (s, r) with s=floor(sqrt(a)) and r=a-s^2. 0 <= r <= 2\n   * s. tabs has n limbs. r is returned in the lower n limbs of\n   taba. Its r[n] is the returned value of the function. */\n/* Algorithm from the article \"Karatsuba Square Root\" by Paul Zimmermann and\n   inspirated from its GMP implementation */\nint mp_sqrtrem(bf_context_t *s, limb_t *tabs, limb_t *taba, limb_t n)\n{\n    limb_t tmp_buf1[8];\n    limb_t *tmp_buf;\n    mp_size_t n2;\n    int ret;\n    n2 = n / 2 + 1;\n    if (n2 <= countof(tmp_buf1)) {\n        tmp_buf = tmp_buf1;\n    } else {\n        tmp_buf = bf_malloc(s, sizeof(limb_t) * n2);\n        if (!tmp_buf)\n            return -1;\n    }\n    ret = mp_sqrtrem_rec(s, tabs, taba, n, tmp_buf, taba + n);\n    if (tmp_buf != tmp_buf1)\n        bf_free(s, tmp_buf);\n    return ret;\n}\n\n/* Integer square root with remainder. 'a' must be an integer. r =\n   floor(sqrt(a)) and rem = a - r^2.  BF_ST_INEXACT is set if the result\n   is inexact. 'rem' can be NULL if the remainder is not needed. */\nint bf_sqrtrem(bf_t *r, bf_t *rem1, const bf_t *a)\n{\n    int ret;\n    \n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n        } else if (a->expn == BF_EXP_INF && a->sign) {\n            goto invalid_op;\n        } else {\n            bf_set(r, a);\n        }\n        if (rem1)\n            bf_set_ui(rem1, 0);\n        ret = 0;\n    } else if (a->sign) {\n invalid_op:\n        bf_set_nan(r);\n        if (rem1)\n            bf_set_ui(rem1, 0);\n        ret = BF_ST_INVALID_OP;\n    } else {\n        bf_t rem_s, *rem;\n        \n        bf_sqrt(r, a, (a->expn + 1) / 2, BF_RNDZ);\n        bf_rint(r, BF_RNDZ);\n        /* see if the result is exact by computing the remainder */\n        if (rem1) {\n            rem = rem1;\n        } else {\n            rem = &rem_s;\n            bf_init(r->ctx, rem);\n        }\n        /* XXX: could avoid recomputing the remainder */\n        bf_mul(rem, r, r, BF_PREC_INF, BF_RNDZ);\n        bf_neg(rem);\n        bf_add(rem, rem, a, BF_PREC_INF, BF_RNDZ);\n        if (bf_is_nan(rem)) {\n            ret = BF_ST_MEM_ERROR;\n            goto done;\n        }\n        if (rem->len != 0) {\n            ret = BF_ST_INEXACT;\n        } else {\n            ret = 0;\n        }\n    done:\n        if (!rem1)\n            bf_delete(rem);\n    }\n    return ret;\n}\n\nint bf_sqrt(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = a->ctx;\n    int ret;\n\n    assert(r != a);\n\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n        } else if (a->expn == BF_EXP_INF && a->sign) {\n            goto invalid_op;\n        } else {\n            bf_set(r, a);\n        }\n        ret = 0;\n    } else if (a->sign) {\n invalid_op:\n        bf_set_nan(r);\n        ret = BF_ST_INVALID_OP;\n    } else {\n        limb_t *a1;\n        slimb_t n, n1;\n        limb_t res;\n        \n        /* convert the mantissa to an integer with at least 2 *\n           prec + 4 bits */\n        n = (2 * (prec + 2) + 2 * LIMB_BITS - 1) / (2 * LIMB_BITS);\n        if (bf_resize(r, n))\n            goto fail;\n        a1 = bf_malloc(s, sizeof(limb_t) * 2 * n);\n        if (!a1)\n            goto fail;\n        n1 = bf_min(2 * n, a->len);\n        memset(a1, 0, (2 * n - n1) * sizeof(limb_t));\n        memcpy(a1 + 2 * n - n1, a->tab + a->len - n1, n1 * sizeof(limb_t));\n        if (a->expn & 1) {\n            res = mp_shr(a1, a1, 2 * n, 1, 0);\n        } else {\n            res = 0;\n        }\n        if (mp_sqrtrem(s, r->tab, a1, n)) {\n            bf_free(s, a1);\n            goto fail;\n        }\n        if (!res) {\n            res = mp_scan_nz(a1, n + 1);\n        }\n        bf_free(s, a1);\n        if (!res) {\n            res = mp_scan_nz(a->tab, a->len - n1);\n        }\n        if (res != 0)\n            r->tab[0] |= 1;\n        r->sign = 0;\n        r->expn = (a->expn + 1) >> 1;\n        ret = bf_round(r, prec, flags);\n    }\n    return ret;\n fail:\n    bf_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\nstatic no_inline int bf_op2(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n                            bf_flags_t flags, bf_op2_func_t *func)\n{\n    bf_t tmp;\n    int ret;\n    \n    if (r == a || r == b) {\n        bf_init(r->ctx, &tmp);\n        ret = func(&tmp, a, b, prec, flags);\n        bf_move(r, &tmp);\n    } else {\n        ret = func(r, a, b, prec, flags);\n    }\n    return ret;\n}\n\nint bf_add(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n            bf_flags_t flags)\n{\n    return bf_op2(r, a, b, prec, flags, __bf_add);\n}\n\nint bf_sub(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n            bf_flags_t flags)\n{\n    return bf_op2(r, a, b, prec, flags, __bf_sub);\n}\n\nint bf_div(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n           bf_flags_t flags)\n{\n    return bf_op2(r, a, b, prec, flags, __bf_div);\n}\n\nint bf_mul_ui(bf_t *r, const bf_t *a, uint64_t b1, limb_t prec,\n               bf_flags_t flags)\n{\n    bf_t b;\n    int ret;\n    bf_init(r->ctx, &b);\n    ret = bf_set_ui(&b, b1);\n    ret |= bf_mul(r, a, &b, prec, flags);\n    bf_delete(&b);\n    return ret;\n}\n\nint bf_mul_si(bf_t *r, const bf_t *a, int64_t b1, limb_t prec,\n               bf_flags_t flags)\n{\n    bf_t b;\n    int ret;\n    bf_init(r->ctx, &b);\n    ret = bf_set_si(&b, b1);\n    ret |= bf_mul(r, a, &b, prec, flags);\n    bf_delete(&b);\n    return ret;\n}\n\nint bf_add_si(bf_t *r, const bf_t *a, int64_t b1, limb_t prec,\n              bf_flags_t flags)\n{\n    bf_t b;\n    int ret;\n    \n    bf_init(r->ctx, &b);\n    ret = bf_set_si(&b, b1);\n    ret |= bf_add(r, a, &b, prec, flags);\n    bf_delete(&b);\n    return ret;\n}\n\nstatic int bf_pow_ui(bf_t *r, const bf_t *a, limb_t b, limb_t prec,\n                     bf_flags_t flags)\n{\n    int ret, n_bits, i;\n    \n    assert(r != a);\n    if (b == 0)\n        return bf_set_ui(r, 1);\n    ret = bf_set(r, a);\n    n_bits = LIMB_BITS - clz(b);\n    for(i = n_bits - 2; i >= 0; i--) {\n        ret |= bf_mul(r, r, r, prec, flags);\n        if ((b >> i) & 1)\n            ret |= bf_mul(r, r, a, prec, flags);\n    }\n    return ret;\n}\n\nstatic int bf_pow_ui_ui(bf_t *r, limb_t a1, limb_t b,\n                        limb_t prec, bf_flags_t flags)\n{\n    bf_t a;\n    int ret;\n    \n    if (a1 == 10 && b <= LIMB_DIGITS) {\n        /* use precomputed powers. We do not round at this point\n           because we expect the caller to do it */\n        ret = bf_set_ui(r, mp_pow_dec[b]);\n    } else {\n        bf_init(r->ctx, &a);\n        ret = bf_set_ui(&a, a1);\n        ret |= bf_pow_ui(r, &a, b, prec, flags);\n        bf_delete(&a);\n    }\n    return ret;\n}\n\n/* convert to integer (infinite precision) */\nint bf_rint(bf_t *r, int rnd_mode)\n{\n    return bf_round(r, 0, rnd_mode | BF_FLAG_RADPNT_PREC);\n}\n\n/* logical operations */\n#define BF_LOGIC_OR  0\n#define BF_LOGIC_XOR 1\n#define BF_LOGIC_AND 2\n\nstatic inline limb_t bf_logic_op1(limb_t a, limb_t b, int op)\n{\n    switch(op) {\n    case BF_LOGIC_OR:\n        return a | b;\n    case BF_LOGIC_XOR:\n        return a ^ b;\n    default:\n    case BF_LOGIC_AND:\n        return a & b;\n    }\n}\n\nstatic int bf_logic_op(bf_t *r, const bf_t *a1, const bf_t *b1, int op)\n{\n    bf_t b1_s, a1_s, *a, *b;\n    limb_t a_sign, b_sign, r_sign;\n    slimb_t l, i, a_bit_offset, b_bit_offset;\n    limb_t v1, v2, v1_mask, v2_mask, r_mask;\n    int ret;\n    \n    assert(r != a1 && r != b1);\n\n    if (a1->expn <= 0)\n        a_sign = 0; /* minus zero is considered as positive */\n    else\n        a_sign = a1->sign;\n\n    if (b1->expn <= 0)\n        b_sign = 0; /* minus zero is considered as positive */\n    else\n        b_sign = b1->sign;\n    \n    if (a_sign) {\n        a = &a1_s;\n        bf_init(r->ctx, a);\n        if (bf_add_si(a, a1, 1, BF_PREC_INF, BF_RNDZ)) {\n            b = NULL;\n            goto fail;\n        }\n    } else {\n        a = (bf_t *)a1;\n    }\n\n    if (b_sign) {\n        b = &b1_s;\n        bf_init(r->ctx, b);\n        if (bf_add_si(b, b1, 1, BF_PREC_INF, BF_RNDZ))\n            goto fail;\n    } else {\n        b = (bf_t *)b1;\n    }\n    \n    r_sign = bf_logic_op1(a_sign, b_sign, op);\n    if (op == BF_LOGIC_AND && r_sign == 0) {\n        /* no need to compute extra zeros for and */\n        if (a_sign == 0 && b_sign == 0)\n            l = bf_min(a->expn, b->expn);\n        else if (a_sign == 0)\n            l = a->expn;\n        else\n            l = b->expn;\n    } else {\n        l = bf_max(a->expn, b->expn);\n    }\n    /* Note: a or b can be zero */\n    l = (bf_max(l, 1) + LIMB_BITS - 1) / LIMB_BITS;\n    if (bf_resize(r, l))\n        goto fail;\n    a_bit_offset = a->len * LIMB_BITS - a->expn;\n    b_bit_offset = b->len * LIMB_BITS - b->expn;\n    v1_mask = -a_sign;\n    v2_mask = -b_sign;\n    r_mask = -r_sign;\n    for(i = 0; i < l; i++) {\n        v1 = get_bits(a->tab, a->len, a_bit_offset + i * LIMB_BITS) ^ v1_mask;\n        v2 = get_bits(b->tab, b->len, b_bit_offset + i * LIMB_BITS) ^ v2_mask;\n        r->tab[i] = bf_logic_op1(v1, v2, op) ^ r_mask;\n    }\n    r->expn = l * LIMB_BITS;\n    r->sign = r_sign;\n    bf_normalize_and_round(r, BF_PREC_INF, BF_RNDZ); /* cannot fail */\n    if (r_sign) {\n        if (bf_add_si(r, r, -1, BF_PREC_INF, BF_RNDZ))\n            goto fail;\n    }\n    ret = 0;\n done:\n    if (a == &a1_s)\n        bf_delete(a);\n    if (b == &b1_s)\n        bf_delete(b);\n    return ret;\n fail:\n    bf_set_nan(r);\n    ret = BF_ST_MEM_ERROR;\n    goto done;\n}\n\n/* 'a' and 'b' must be integers. Return 0 or BF_ST_MEM_ERROR. */\nint bf_logic_or(bf_t *r, const bf_t *a, const bf_t *b)\n{\n    return bf_logic_op(r, a, b, BF_LOGIC_OR);\n}\n\n/* 'a' and 'b' must be integers. Return 0 or BF_ST_MEM_ERROR. */\nint bf_logic_xor(bf_t *r, const bf_t *a, const bf_t *b)\n{\n    return bf_logic_op(r, a, b, BF_LOGIC_XOR);\n}\n\n/* 'a' and 'b' must be integers. Return 0 or BF_ST_MEM_ERROR. */\nint bf_logic_and(bf_t *r, const bf_t *a, const bf_t *b)\n{\n    return bf_logic_op(r, a, b, BF_LOGIC_AND);\n}\n\n/* conversion between fixed size types */\n\ntypedef union {\n    double d;\n    uint64_t u;\n} Float64Union;\n\nint bf_get_float64(const bf_t *a, double *pres, bf_rnd_t rnd_mode)\n{\n    Float64Union u;\n    int e, ret;\n    uint64_t m;\n    \n    ret = 0;\n    if (a->expn == BF_EXP_NAN) {\n        u.u = 0x7ff8000000000000; /* quiet nan */\n    } else {\n        bf_t b_s, *b = &b_s;\n        \n        bf_init(a->ctx, b);\n        bf_set(b, a);\n        if (bf_is_finite(b)) {\n            ret = bf_round(b, 53, rnd_mode | BF_FLAG_SUBNORMAL | bf_set_exp_bits(11));\n        }\n        if (b->expn == BF_EXP_INF) {\n            e = (1 << 11) - 1;\n            m = 0;\n        } else if (b->expn == BF_EXP_ZERO) {\n            e = 0;\n            m = 0;\n        } else {\n            e = b->expn + 1023 - 1;\n#if LIMB_BITS == 32\n            if (b->len == 2) {\n                m = ((uint64_t)b->tab[1] << 32) | b->tab[0];\n            } else {\n                m = ((uint64_t)b->tab[0] << 32);\n            }\n#else\n            m = b->tab[0];\n#endif\n            if (e <= 0) {\n                /* subnormal */\n                m = m >> (12 - e);\n                e = 0;\n            } else {\n                m = (m << 1) >> 12;\n            }\n        }\n        u.u = m | ((uint64_t)e << 52) | ((uint64_t)b->sign << 63);\n        bf_delete(b);\n    }\n    *pres = u.d;\n    return ret;\n}\n\nint bf_set_float64(bf_t *a, double d)\n{\n    Float64Union u;\n    uint64_t m;\n    int shift, e, sgn;\n    \n    u.d = d;\n    sgn = u.u >> 63;\n    e = (u.u >> 52) & ((1 << 11) - 1);\n    m = u.u & (((uint64_t)1 << 52) - 1);\n    if (e == ((1 << 11) - 1)) {\n        if (m != 0) {\n            bf_set_nan(a);\n        } else {\n            bf_set_inf(a, sgn);\n        }\n    } else if (e == 0) {\n        if (m == 0) {\n            bf_set_zero(a, sgn);\n        } else {\n            /* subnormal number */\n            m <<= 12;\n            shift = clz64(m);\n            m <<= shift;\n            e = -shift;\n            goto norm;\n        }\n    } else {\n        m = (m << 11) | ((uint64_t)1 << 63);\n    norm:\n        a->expn = e - 1023 + 1;\n#if LIMB_BITS == 32\n        if (bf_resize(a, 2))\n            goto fail;\n        a->tab[0] = m;\n        a->tab[1] = m >> 32;\n#else\n        if (bf_resize(a, 1))\n            goto fail;\n        a->tab[0] = m;\n#endif\n        a->sign = sgn;\n    }\n    return 0;\nfail:\n    bf_set_nan(a);\n    return BF_ST_MEM_ERROR;\n}\n\n/* The rounding mode is always BF_RNDZ. Return BF_ST_INVALID_OP if there\n   is an overflow and 0 otherwise. */\nint bf_get_int32(int *pres, const bf_t *a, int flags)\n{\n    uint32_t v;\n    int ret;\n    if (a->expn >= BF_EXP_INF) {\n        ret = BF_ST_INVALID_OP;\n        if (flags & BF_GET_INT_MOD) {\n            v = 0;\n        } else if (a->expn == BF_EXP_INF) {\n            v = (uint32_t)INT32_MAX + a->sign;\n        } else {\n            v = INT32_MAX;\n        }\n    } else if (a->expn <= 0) {\n        v = 0;\n        ret = 0;\n    } else if (a->expn <= 31) {\n        v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn);\n        if (a->sign)\n            v = -v;\n        ret = 0;\n    } else if (!(flags & BF_GET_INT_MOD)) {\n        ret = BF_ST_INVALID_OP;\n        if (a->sign) {\n            v = (uint32_t)INT32_MAX + 1;\n            if (a->expn == 32 && \n                (a->tab[a->len - 1] >> (LIMB_BITS - 32)) == v) {\n                ret = 0;\n            }\n        } else {\n            v = INT32_MAX;\n        }\n    } else {\n        v = get_bits(a->tab, a->len, a->len * LIMB_BITS - a->expn); \n        if (a->sign)\n            v = -v;\n        ret = 0;\n    }\n    *pres = v;\n    return ret;\n}\n\n/* The rounding mode is always BF_RNDZ. Return BF_ST_INVALID_OP if there\n   is an overflow and 0 otherwise. */\nint bf_get_int64(int64_t *pres, const bf_t *a, int flags)\n{\n    uint64_t v;\n    int ret;\n    if (a->expn >= BF_EXP_INF) {\n        ret = BF_ST_INVALID_OP;\n        if (flags & BF_GET_INT_MOD) {\n            v = 0;\n        } else if (a->expn == BF_EXP_INF) {\n            v = (uint64_t)INT64_MAX + a->sign;\n        } else {\n            v = INT64_MAX;\n        }\n    } else if (a->expn <= 0) {\n        v = 0;\n        ret = 0;\n    } else if (a->expn <= 63) {\n#if LIMB_BITS == 32\n        if (a->expn <= 32)\n            v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn);\n        else\n            v = (((uint64_t)a->tab[a->len - 1] << 32) |\n                 get_limbz(a, a->len - 2)) >> (64 - a->expn);\n#else\n        v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn);\n#endif\n        if (a->sign)\n            v = -v;\n        ret = 0;\n    } else if (!(flags & BF_GET_INT_MOD)) {\n        ret = BF_ST_INVALID_OP;\n        if (a->sign) {\n            uint64_t v1;\n            v = (uint64_t)INT64_MAX + 1;\n            if (a->expn == 64) {\n                v1 = a->tab[a->len - 1];\n#if LIMB_BITS == 32\n                v1 = (v1 << 32) | get_limbz(a, a->len - 2);\n#endif\n                if (v1 == v)\n                    ret = 0;\n            }\n        } else {\n            v = INT64_MAX;\n        }\n    } else {\n        slimb_t bit_pos = a->len * LIMB_BITS - a->expn;\n        v = get_bits(a->tab, a->len, bit_pos); \n#if LIMB_BITS == 32\n        v |= (uint64_t)get_bits(a->tab, a->len, bit_pos + 32) << 32;\n#endif\n        if (a->sign)\n            v = -v;\n        ret = 0;\n    }\n    *pres = v;\n    return ret;\n}\n\n/* The rounding mode is always BF_RNDZ. Return BF_ST_INVALID_OP if there\n   is an overflow and 0 otherwise. */\nint bf_get_uint64(uint64_t *pres, const bf_t *a)\n{\n    uint64_t v;\n    int ret;\n    if (a->expn == BF_EXP_NAN) {\n        goto overflow;\n    } else if (a->expn <= 0) {\n        v = 0;\n        ret = 0;\n    } else if (a->sign) {\n        v = 0;\n        ret = BF_ST_INVALID_OP;\n    } else if (a->expn <= 64) {\n#if LIMB_BITS == 32\n        if (a->expn <= 32)\n            v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn);\n        else\n            v = (((uint64_t)a->tab[a->len - 1] << 32) |\n                 get_limbz(a, a->len - 2)) >> (64 - a->expn);\n#else\n        v = a->tab[a->len - 1] >> (LIMB_BITS - a->expn);\n#endif\n        ret = 0;\n    } else {\n    overflow:\n        v = UINT64_MAX;\n        ret = BF_ST_INVALID_OP;\n    }\n    *pres = v;\n    return ret;\n}\n\n/* base conversion from radix */\n\nstatic const uint8_t digits_per_limb_table[BF_RADIX_MAX - 1] = {\n#if LIMB_BITS == 32\n32,20,16,13,12,11,10,10, 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n#else\n64,40,32,27,24,22,21,20,19,18,17,17,16,16,16,15,15,15,14,14,14,14,13,13,13,13,13,13,13,12,12,12,12,12,12,\n#endif\n};\n\nstatic limb_t get_limb_radix(int radix)\n{\n    int i, k;\n    limb_t radixl;\n    \n    k = digits_per_limb_table[radix - 2];\n    radixl = radix;\n    for(i = 1; i < k; i++)\n        radixl *= radix;\n    return radixl;\n}\n\n/* return != 0 if error */\nstatic int bf_integer_from_radix_rec(bf_t *r, const limb_t *tab,\n                                     limb_t n, int level, limb_t n0,\n                                     limb_t radix, bf_t *pow_tab)\n{\n    int ret;\n    if (n == 1) {\n        ret = bf_set_ui(r, tab[0]);\n    } else {\n        bf_t T_s, *T = &T_s, *B;\n        limb_t n1, n2;\n        \n        n2 = (((n0 * 2) >> (level + 1)) + 1) / 2;\n        n1 = n - n2;\n        //        printf(\"level=%d n0=%ld n1=%ld n2=%ld\\n\", level, n0, n1, n2);\n        B = &pow_tab[level];\n        if (B->len == 0) {\n            ret = bf_pow_ui_ui(B, radix, n2, BF_PREC_INF, BF_RNDZ);\n            if (ret)\n                return ret;\n        }\n        ret = bf_integer_from_radix_rec(r, tab + n2, n1, level + 1, n0,\n                                        radix, pow_tab);\n        if (ret)\n            return ret;\n        ret = bf_mul(r, r, B, BF_PREC_INF, BF_RNDZ);\n        if (ret)\n            return ret;\n        bf_init(r->ctx, T);\n        ret = bf_integer_from_radix_rec(T, tab, n2, level + 1, n0,\n                                        radix, pow_tab);\n        if (!ret)\n            ret = bf_add(r, r, T, BF_PREC_INF, BF_RNDZ);\n        bf_delete(T);\n    }\n    return ret;\n    //    bf_print_str(\"  r=\", r);\n}\n\n/* return 0 if OK != 0 if memory error */\nstatic int bf_integer_from_radix(bf_t *r, const limb_t *tab,\n                                 limb_t n, limb_t radix)\n{\n    bf_context_t *s = r->ctx;\n    int pow_tab_len, i, ret;\n    limb_t radixl;\n    bf_t *pow_tab;\n    \n    radixl = get_limb_radix(radix);\n    pow_tab_len = ceil_log2(n) + 2; /* XXX: check */\n    pow_tab = bf_malloc(s, sizeof(pow_tab[0]) * pow_tab_len);\n    if (!pow_tab)\n        return -1;\n    for(i = 0; i < pow_tab_len; i++)\n        bf_init(r->ctx, &pow_tab[i]);\n    ret = bf_integer_from_radix_rec(r, tab, n, 0, n, radixl, pow_tab);\n    for(i = 0; i < pow_tab_len; i++) {\n        bf_delete(&pow_tab[i]);\n    }\n    bf_free(s, pow_tab);\n    return ret;\n}\n\n/* compute and round T * radix^expn. */\nint bf_mul_pow_radix(bf_t *r, const bf_t *T, limb_t radix,\n                     slimb_t expn, limb_t prec, bf_flags_t flags)\n{\n    int ret, expn_sign, overflow;\n    slimb_t e, extra_bits, prec1, ziv_extra_bits;\n    bf_t B_s, *B = &B_s;\n\n    if (T->len == 0) {\n        return bf_set(r, T);\n    } else if (expn == 0) {\n        ret = bf_set(r, T);\n        ret |= bf_round(r, prec, flags);\n        return ret;\n    }\n\n    e = expn;\n    expn_sign = 0;\n    if (e < 0) {\n        e = -e;\n        expn_sign = 1;\n    }\n    bf_init(r->ctx, B);\n    if (prec == BF_PREC_INF) {\n        /* infinite precision: only used if the result is known to be exact */\n        ret = bf_pow_ui_ui(B, radix, e, BF_PREC_INF, BF_RNDN);\n        if (expn_sign) {\n            ret |= bf_div(r, T, B, T->len * LIMB_BITS, BF_RNDN);\n        } else {\n            ret |= bf_mul(r, T, B, BF_PREC_INF, BF_RNDN);\n        }\n    } else {\n        ziv_extra_bits = 16;\n        for(;;) {\n            prec1 = prec + ziv_extra_bits;\n            /* XXX: correct overflow/underflow handling */\n            /* XXX: rigorous error analysis needed */\n            extra_bits = ceil_log2(e) * 2 + 1;\n            ret = bf_pow_ui_ui(B, radix, e, prec1 + extra_bits, BF_RNDN | BF_FLAG_EXT_EXP);\n            overflow = !bf_is_finite(B);\n            /* XXX: if bf_pow_ui_ui returns an exact result, can stop\n               after the next operation */\n            if (expn_sign)\n                ret |= bf_div(r, T, B, prec1 + extra_bits, BF_RNDN | BF_FLAG_EXT_EXP);\n            else\n                ret |= bf_mul(r, T, B, prec1 + extra_bits, BF_RNDN | BF_FLAG_EXT_EXP);\n            if (ret & BF_ST_MEM_ERROR)\n                break;\n            if ((ret & BF_ST_INEXACT) &&\n                !bf_can_round(r, prec, flags & BF_RND_MASK, prec1) &&\n                !overflow) {\n                /* and more precision and retry */\n                ziv_extra_bits = ziv_extra_bits  + (ziv_extra_bits / 2);\n            } else {\n                /* XXX: need to use __bf_round() to pass the inexact\n                   flag for the subnormal case */\n                ret = bf_round(r, prec, flags) | (ret & BF_ST_INEXACT);\n                break;\n            }\n        }\n    }\n    bf_delete(B);\n    return ret;\n}\n\nstatic inline int to_digit(int c)\n{\n    if (c >= '0' && c <= '9')\n        return c - '0';\n    else if (c >= 'A' && c <= 'Z')\n        return c - 'A' + 10;\n    else if (c >= 'a' && c <= 'z')\n        return c - 'a' + 10;\n    else\n        return 36;\n}\n\n/* add a limb at 'pos' and decrement pos. new space is created if\n   needed. Return 0 if OK, -1 if memory error */\nstatic int bf_add_limb(bf_t *a, slimb_t *ppos, limb_t v)\n{\n    slimb_t pos;\n    pos = *ppos;\n    if (unlikely(pos < 0)) {\n        limb_t new_size, d, *new_tab;\n        new_size = bf_max(a->len + 1, a->len * 3 / 2);\n        new_tab = bf_realloc(a->ctx, a->tab, sizeof(limb_t) * new_size);\n        if (!new_tab)\n            return -1;\n        a->tab = new_tab;\n        d = new_size - a->len;\n        memmove(a->tab + d, a->tab, a->len * sizeof(limb_t));\n        a->len = new_size;\n        pos += d;\n    }\n    a->tab[pos--] = v;\n    *ppos = pos;\n    return 0;\n}\n\nstatic int bf_tolower(int c)\n{\n    if (c >= 'A' && c <= 'Z')\n        c = c - 'A' + 'a';\n    return c;\n}\n\nstatic int strcasestart(const char *str, const char *val, const char **ptr)\n{\n    const char *p, *q;\n    p = str;\n    q = val;\n    while (*q != '\\0') {\n        if (bf_tolower(*p) != *q)\n            return 0;\n        p++;\n        q++;\n    }\n    if (ptr)\n        *ptr = p;\n    return 1;\n}\n\nstatic int bf_atof_internal(bf_t *r, slimb_t *pexponent,\n                            const char *str, const char **pnext, int radix,\n                            limb_t prec, bf_flags_t flags, BOOL is_dec)\n{\n    const char *p, *p_start;\n    int is_neg, radix_bits, exp_is_neg, ret, digits_per_limb, shift;\n    limb_t cur_limb;\n    slimb_t pos, expn, int_len, digit_count;\n    BOOL has_decpt, is_bin_exp;\n    bf_t a_s, *a;\n    \n    *pexponent = 0;\n    p = str;\n    if (!(flags & BF_ATOF_NO_NAN_INF) && radix <= 16 &&\n        strcasestart(p, \"nan\", &p)) {\n        bf_set_nan(r);\n        ret = 0;\n        goto done;\n    }\n    is_neg = 0;\n    \n    if (p[0] == '+') {\n        p++;\n        p_start = p;\n    } else if (p[0] == '-') {\n        is_neg = 1;\n        p++;\n        p_start = p;\n    } else {\n        p_start = p;\n    }\n    if (p[0] == '0') {\n        if ((p[1] == 'x' || p[1] == 'X') &&\n            (radix == 0 || radix == 16) &&\n            !(flags & BF_ATOF_NO_HEX)) {\n            radix = 16;\n            p += 2;\n        } else if ((p[1] == 'o' || p[1] == 'O') &&\n                   radix == 0 && (flags & BF_ATOF_BIN_OCT)) {\n            p += 2;\n            radix = 8;\n        } else if ((p[1] == 'b' || p[1] == 'B') &&\n                   radix == 0 && (flags & BF_ATOF_BIN_OCT)) {\n            p += 2;\n            radix = 2;\n        } else {\n            goto no_prefix;\n        }\n        /* there must be a digit after the prefix */\n        if (to_digit((uint8_t)*p) >= radix) {\n            bf_set_nan(r);\n            ret = 0;\n            goto done;\n        }\n    no_prefix: ;\n    } else {\n        if (!(flags & BF_ATOF_NO_NAN_INF) && radix <= 16 &&\n            strcasestart(p, \"inf\", &p)) {\n            bf_set_inf(r, is_neg);\n            ret = 0;\n            goto done;\n        }\n    }\n    \n    if (radix == 0)\n        radix = 10;\n    if (is_dec) {\n        assert(radix == 10);\n        radix_bits = 0;\n        a = r;\n    } else if ((radix & (radix - 1)) != 0) {\n        radix_bits = 0; /* base is not a power of two */\n        a = &a_s;\n        bf_init(r->ctx, a);\n    } else {\n        radix_bits = ceil_log2(radix);\n        a = r;\n    }\n\n    /* skip leading zeros */\n    /* XXX: could also skip zeros after the decimal point */\n    while (*p == '0')\n        p++;\n\n    if (radix_bits) {\n        shift = digits_per_limb = LIMB_BITS;\n    } else {\n        radix_bits = 0;\n        shift = digits_per_limb = digits_per_limb_table[radix - 2];\n    }\n    cur_limb = 0;\n    bf_resize(a, 1);\n    pos = 0;\n    has_decpt = FALSE;\n    int_len = digit_count = 0;\n    for(;;) {\n        limb_t c;\n        if (*p == '.' && (p > p_start || to_digit(p[1]) < radix)) {\n            if (has_decpt)\n                break;\n            has_decpt = TRUE;\n            int_len = digit_count;\n            p++;\n        }\n        c = to_digit(*p);\n        if (c >= radix)\n            break;\n        digit_count++;\n        p++;\n        if (radix_bits) {\n            shift -= radix_bits;\n            if (shift <= 0) {\n                cur_limb |= c >> (-shift);\n                if (bf_add_limb(a, &pos, cur_limb))\n                    goto mem_error;\n                if (shift < 0)\n                    cur_limb = c << (LIMB_BITS + shift);\n                else\n                    cur_limb = 0;\n                shift += LIMB_BITS;\n            } else {\n                cur_limb |= c << shift;\n            }\n        } else {\n            cur_limb = cur_limb * radix + c;\n            shift--;\n            if (shift == 0) {\n                if (bf_add_limb(a, &pos, cur_limb))\n                    goto mem_error;\n                shift = digits_per_limb;\n                cur_limb = 0;\n            }\n        }\n    }\n    if (!has_decpt)\n        int_len = digit_count;\n\n    /* add the last limb and pad with zeros */\n    if (shift != digits_per_limb) {\n        if (radix_bits == 0) {\n            while (shift != 0) {\n                cur_limb *= radix;\n                shift--;\n            }\n        }\n        if (bf_add_limb(a, &pos, cur_limb)) {\n        mem_error:\n            ret = BF_ST_MEM_ERROR;\n            if (!radix_bits)\n                bf_delete(a);\n            bf_set_nan(r);\n            goto done;\n        }\n    }\n            \n    /* reset the next limbs to zero (we prefer to reallocate in the\n       renormalization) */\n    memset(a->tab, 0, (pos + 1) * sizeof(limb_t));\n\n    if (p == p_start) {\n        ret = 0;\n        if (!radix_bits)\n            bf_delete(a);\n        bf_set_nan(r);\n        goto done;\n    }\n\n    /* parse the exponent, if any */\n    expn = 0;\n    is_bin_exp = FALSE;\n    if (((radix == 10 && (*p == 'e' || *p == 'E')) ||\n         (radix != 10 && (*p == '@' ||\n                          (radix_bits && (*p == 'p' || *p == 'P'))))) &&\n        p > p_start) {\n        is_bin_exp = (*p == 'p' || *p == 'P');\n        p++;\n        exp_is_neg = 0;\n        if (*p == '+') {\n            p++;\n        } else if (*p == '-') {\n            exp_is_neg = 1;\n            p++;\n        }\n        for(;;) {\n            int c;\n            c = to_digit(*p);\n            if (c >= 10)\n                break;\n            if (unlikely(expn > ((BF_RAW_EXP_MAX - 2 - 9) / 10))) {\n                /* exponent overflow */\n                if (exp_is_neg) {\n                    bf_set_zero(r, is_neg);\n                    ret = BF_ST_UNDERFLOW | BF_ST_INEXACT;\n                } else {\n                    bf_set_inf(r, is_neg);\n                    ret = BF_ST_OVERFLOW | BF_ST_INEXACT;\n                }\n                goto done;\n            }\n            p++;\n            expn = expn * 10 + c;\n        }\n        if (exp_is_neg)\n            expn = -expn;\n    }\n    if (is_dec) {\n        a->expn = expn + int_len;\n        a->sign = is_neg;\n        ret = bfdec_normalize_and_round((bfdec_t *)a, prec, flags);\n    } else if (radix_bits) {\n        /* XXX: may overflow */\n        if (!is_bin_exp)\n            expn *= radix_bits; \n        a->expn = expn + (int_len * radix_bits);\n        a->sign = is_neg;\n        ret = bf_normalize_and_round(a, prec, flags);\n    } else {\n        limb_t l;\n        pos++;\n        l = a->len - pos; /* number of limbs */\n        if (l == 0) {\n            bf_set_zero(r, is_neg);\n            ret = 0;\n        } else {\n            bf_t T_s, *T = &T_s;\n\n            expn -= l * digits_per_limb - int_len;\n            bf_init(r->ctx, T);\n            if (bf_integer_from_radix(T, a->tab + pos, l, radix)) {\n                bf_set_nan(r);\n                ret = BF_ST_MEM_ERROR;\n            } else {\n                T->sign = is_neg;\n                if (flags & BF_ATOF_EXPONENT) {\n                    /* return the exponent */\n                    *pexponent = expn;\n                    ret = bf_set(r, T);\n                } else {\n                    ret = bf_mul_pow_radix(r, T, radix, expn, prec, flags);\n                }\n            }\n            bf_delete(T);\n        }\n        bf_delete(a);\n    }\n done:\n    if (pnext)\n        *pnext = p;\n    return ret;\n}\n\n/* \n   Return (status, n, exp). 'status' is the floating point status. 'n'\n   is the parsed number. \n\n   If (flags & BF_ATOF_EXPONENT) and if the radix is not a power of\n   two, the parsed number is equal to r *\n   (*pexponent)^radix. Otherwise *pexponent = 0.\n*/\nint bf_atof2(bf_t *r, slimb_t *pexponent,\n             const char *str, const char **pnext, int radix,\n             limb_t prec, bf_flags_t flags)\n{\n    return bf_atof_internal(r, pexponent, str, pnext, radix, prec, flags,\n                            FALSE);\n}\n\nint bf_atof(bf_t *r, const char *str, const char **pnext, int radix,\n            limb_t prec, bf_flags_t flags)\n{\n    slimb_t dummy_exp;\n    return bf_atof_internal(r, &dummy_exp, str, pnext, radix, prec, flags, FALSE);\n}\n\n/* base conversion to radix */\n\n#if LIMB_BITS == 64\n#define RADIXL_10 UINT64_C(10000000000000000000)\n#else\n#define RADIXL_10 UINT64_C(1000000000)\n#endif\n\nstatic const uint32_t inv_log2_radix[BF_RADIX_MAX - 1][LIMB_BITS / 32 + 1] = {\n#if LIMB_BITS == 32\n{ 0x80000000, 0x00000000,},\n{ 0x50c24e60, 0xd4d4f4a7,},\n{ 0x40000000, 0x00000000,},\n{ 0x372068d2, 0x0a1ee5ca,},\n{ 0x3184648d, 0xb8153e7a,},\n{ 0x2d983275, 0x9d5369c4,},\n{ 0x2aaaaaaa, 0xaaaaaaab,},\n{ 0x28612730, 0x6a6a7a54,},\n{ 0x268826a1, 0x3ef3fde6,},\n{ 0x25001383, 0xbac8a744,},\n{ 0x23b46706, 0x82c0c709,},\n{ 0x229729f1, 0xb2c83ded,},\n{ 0x219e7ffd, 0xa5ad572b,},\n{ 0x20c33b88, 0xda7c29ab,},\n{ 0x20000000, 0x00000000,},\n{ 0x1f50b57e, 0xac5884b3,},\n{ 0x1eb22cc6, 0x8aa6e26f,},\n{ 0x1e21e118, 0x0c5daab2,},\n{ 0x1d9dcd21, 0x439834e4,},\n{ 0x1d244c78, 0x367a0d65,},\n{ 0x1cb40589, 0xac173e0c,},\n{ 0x1c4bd95b, 0xa8d72b0d,},\n{ 0x1bead768, 0x98f8ce4c,},\n{ 0x1b903469, 0x050f72e5,},\n{ 0x1b3b433f, 0x2eb06f15,},\n{ 0x1aeb6f75, 0x9c46fc38,},\n{ 0x1aa038eb, 0x0e3bfd17,},\n{ 0x1a593062, 0xb38d8c56,},\n{ 0x1a15f4c3, 0x2b95a2e6,},\n{ 0x19d630dc, 0xcc7ddef9,},\n{ 0x19999999, 0x9999999a,},\n{ 0x195fec80, 0x8a609431,},\n{ 0x1928ee7b, 0x0b4f22f9,},\n{ 0x18f46acf, 0x8c06e318,},\n{ 0x18c23246, 0xdc0a9f3d,},\n#else\n{ 0x80000000, 0x00000000, 0x00000000,},\n{ 0x50c24e60, 0xd4d4f4a7, 0x021f57bc,},\n{ 0x40000000, 0x00000000, 0x00000000,},\n{ 0x372068d2, 0x0a1ee5ca, 0x19ea911b,},\n{ 0x3184648d, 0xb8153e7a, 0x7fc2d2e1,},\n{ 0x2d983275, 0x9d5369c4, 0x4dec1661,},\n{ 0x2aaaaaaa, 0xaaaaaaaa, 0xaaaaaaab,},\n{ 0x28612730, 0x6a6a7a53, 0x810fabde,},\n{ 0x268826a1, 0x3ef3fde6, 0x23e2566b,},\n{ 0x25001383, 0xbac8a744, 0x385a3349,},\n{ 0x23b46706, 0x82c0c709, 0x3f891718,},\n{ 0x229729f1, 0xb2c83ded, 0x15fba800,},\n{ 0x219e7ffd, 0xa5ad572a, 0xe169744b,},\n{ 0x20c33b88, 0xda7c29aa, 0x9bddee52,},\n{ 0x20000000, 0x00000000, 0x00000000,},\n{ 0x1f50b57e, 0xac5884b3, 0x70e28eee,},\n{ 0x1eb22cc6, 0x8aa6e26f, 0x06d1a2a2,},\n{ 0x1e21e118, 0x0c5daab1, 0x81b4f4bf,},\n{ 0x1d9dcd21, 0x439834e3, 0x81667575,},\n{ 0x1d244c78, 0x367a0d64, 0xc8204d6d,},\n{ 0x1cb40589, 0xac173e0c, 0x3b7b16ba,},\n{ 0x1c4bd95b, 0xa8d72b0d, 0x5879f25a,},\n{ 0x1bead768, 0x98f8ce4c, 0x66cc2858,},\n{ 0x1b903469, 0x050f72e5, 0x0cf5488e,},\n{ 0x1b3b433f, 0x2eb06f14, 0x8c89719c,},\n{ 0x1aeb6f75, 0x9c46fc37, 0xab5fc7e9,},\n{ 0x1aa038eb, 0x0e3bfd17, 0x1bd62080,},\n{ 0x1a593062, 0xb38d8c56, 0x7998ab45,},\n{ 0x1a15f4c3, 0x2b95a2e6, 0x46aed6a0,},\n{ 0x19d630dc, 0xcc7ddef9, 0x5aadd61b,},\n{ 0x19999999, 0x99999999, 0x9999999a,},\n{ 0x195fec80, 0x8a609430, 0xe1106014,},\n{ 0x1928ee7b, 0x0b4f22f9, 0x5f69791d,},\n{ 0x18f46acf, 0x8c06e318, 0x4d2aeb2c,},\n{ 0x18c23246, 0xdc0a9f3d, 0x3fe16970,},\n#endif\n};\n\nstatic const limb_t log2_radix[BF_RADIX_MAX - 1] = {\n#if LIMB_BITS == 32\n0x20000000,\n0x32b80347,\n0x40000000,\n0x4a4d3c26,\n0x52b80347,\n0x59d5d9fd,\n0x60000000,\n0x6570068e,\n0x6a4d3c26,\n0x6eb3a9f0,\n0x72b80347,\n0x766a008e,\n0x79d5d9fd,\n0x7d053f6d,\n0x80000000,\n0x82cc7edf,\n0x8570068e,\n0x87ef05ae,\n0x8a4d3c26,\n0x8c8ddd45,\n0x8eb3a9f0,\n0x90c10501,\n0x92b80347,\n0x949a784c,\n0x966a008e,\n0x982809d6,\n0x99d5d9fd,\n0x9b74948f,\n0x9d053f6d,\n0x9e88c6b3,\n0xa0000000,\n0xa16bad37,\n0xa2cc7edf,\n0xa4231623,\n0xa570068e,\n#else\n0x2000000000000000,\n0x32b803473f7ad0f4,\n0x4000000000000000,\n0x4a4d3c25e68dc57f,\n0x52b803473f7ad0f4,\n0x59d5d9fd5010b366,\n0x6000000000000000,\n0x6570068e7ef5a1e8,\n0x6a4d3c25e68dc57f,\n0x6eb3a9f01975077f,\n0x72b803473f7ad0f4,\n0x766a008e4788cbcd,\n0x79d5d9fd5010b366,\n0x7d053f6d26089673,\n0x8000000000000000,\n0x82cc7edf592262d0,\n0x8570068e7ef5a1e8,\n0x87ef05ae409a0289,\n0x8a4d3c25e68dc57f,\n0x8c8ddd448f8b845a,\n0x8eb3a9f01975077f,\n0x90c10500d63aa659,\n0x92b803473f7ad0f4,\n0x949a784bcd1b8afe,\n0x966a008e4788cbcd,\n0x982809d5be7072dc,\n0x99d5d9fd5010b366,\n0x9b74948f5532da4b,\n0x9d053f6d26089673,\n0x9e88c6b3626a72aa,\n0xa000000000000000,\n0xa16bad3758efd873,\n0xa2cc7edf592262d0,\n0xa4231623369e78e6,\n0xa570068e7ef5a1e8,\n#endif\n};\n\n/* compute floor(a*b) or ceil(a*b) with b = log2(radix) or\n   b=1/log2(radix). For is_inv = 0, strict accuracy is not guaranteed\n   when radix is not a power of two. */\nslimb_t bf_mul_log2_radix(slimb_t a1, unsigned int radix, int is_inv,\n                          int is_ceil1)\n{\n    int is_neg;\n    limb_t a;\n    BOOL is_ceil;\n\n    is_ceil = is_ceil1;\n    a = a1;\n    if (a1 < 0) {\n        a = -a;\n        is_neg = 1;\n    } else {\n        is_neg = 0;\n    }\n    is_ceil ^= is_neg;\n    if ((radix & (radix - 1)) == 0) {\n        int radix_bits;\n        /* radix is a power of two */\n        radix_bits = ceil_log2(radix);\n        if (is_inv) {\n            if (is_ceil)\n                a += radix_bits - 1;\n            a = a / radix_bits;\n        } else {\n            a = a * radix_bits;\n        }\n    } else {\n        const uint32_t *tab;\n        limb_t b0, b1;\n        dlimb_t t;\n        \n        if (is_inv) {\n            tab = inv_log2_radix[radix - 2];\n#if LIMB_BITS == 32\n            b1 = tab[0];\n            b0 = tab[1];\n#else\n            b1 = ((limb_t)tab[0] << 32) | tab[1];\n            b0 = (limb_t)tab[2] << 32;\n#endif\n            t = (dlimb_t)b0 * (dlimb_t)a;\n            t = (dlimb_t)b1 * (dlimb_t)a + (t >> LIMB_BITS);\n            a = t >> (LIMB_BITS - 1);\n        } else {\n            b0 = log2_radix[radix - 2];\n            t = (dlimb_t)b0 * (dlimb_t)a;\n            a = t >> (LIMB_BITS - 3);\n        }\n        /* a = floor(result) and 'result' cannot be an integer */\n        a += is_ceil;\n    }\n    if (is_neg)\n        a = -a;\n    return a;\n}\n\n/* 'n' is the number of output limbs */\nstatic int bf_integer_to_radix_rec(bf_t *pow_tab,\n                                   limb_t *out, const bf_t *a, limb_t n,\n                                   int level, limb_t n0, limb_t radixl,\n                                   unsigned int radixl_bits)\n{\n    limb_t n1, n2, q_prec;\n    int ret;\n    \n    assert(n >= 1);\n    if (n == 1) {\n        out[0] = get_bits(a->tab, a->len, a->len * LIMB_BITS - a->expn);\n    } else if (n == 2) {\n        dlimb_t t;\n        slimb_t pos;\n        pos = a->len * LIMB_BITS - a->expn;\n        t = ((dlimb_t)get_bits(a->tab, a->len, pos + LIMB_BITS) << LIMB_BITS) |\n            get_bits(a->tab, a->len, pos);\n        if (likely(radixl == RADIXL_10)) {\n            /* use division by a constant when possible */\n            out[0] = t % RADIXL_10;\n            out[1] = t / RADIXL_10;\n        } else {\n            out[0] = t % radixl;\n            out[1] = t / radixl;\n        }\n    } else {\n        bf_t Q, R, *B, *B_inv;\n        int q_add;\n        bf_init(a->ctx, &Q);\n        bf_init(a->ctx, &R);\n        n2 = (((n0 * 2) >> (level + 1)) + 1) / 2;\n        n1 = n - n2;\n        B = &pow_tab[2 * level];\n        B_inv = &pow_tab[2 * level + 1];\n        ret = 0;\n        if (B->len == 0) {\n            /* compute BASE^n2 */\n            ret |= bf_pow_ui_ui(B, radixl, n2, BF_PREC_INF, BF_RNDZ);\n            /* we use enough bits for the maximum possible 'n1' value,\n               i.e. n2 + 1 */\n            ret |= bf_set_ui(&R, 1);\n            ret |= bf_div(B_inv, &R, B, (n2 + 1) * radixl_bits + 2, BF_RNDN);\n        }\n        //        printf(\"%d: n1=% \" PRId64 \" n2=%\" PRId64 \"\\n\", level, n1, n2);\n        q_prec = n1 * radixl_bits;\n        ret |= bf_mul(&Q, a, B_inv, q_prec, BF_RNDN);\n        ret |= bf_rint(&Q, BF_RNDZ);\n        \n        ret |= bf_mul(&R, &Q, B, BF_PREC_INF, BF_RNDZ);\n        ret |= bf_sub(&R, a, &R, BF_PREC_INF, BF_RNDZ);\n\n        if (ret & BF_ST_MEM_ERROR)\n            goto fail;\n        /* adjust if necessary */\n        q_add = 0;\n        while (R.sign && R.len != 0) {\n            if (bf_add(&R, &R, B, BF_PREC_INF, BF_RNDZ))\n                goto fail;\n            q_add--;\n        }\n        while (bf_cmpu(&R, B) >= 0) {\n            if (bf_sub(&R, &R, B, BF_PREC_INF, BF_RNDZ))\n                goto fail;\n            q_add++;\n        }\n        if (q_add != 0) {\n            if (bf_add_si(&Q, &Q, q_add, BF_PREC_INF, BF_RNDZ))\n                goto fail;\n        }\n        if (bf_integer_to_radix_rec(pow_tab, out + n2, &Q, n1, level + 1, n0,\n                                    radixl, radixl_bits))\n            goto fail;\n        if (bf_integer_to_radix_rec(pow_tab, out, &R, n2, level + 1, n0,\n                                    radixl, radixl_bits)) {\n        fail:\n            bf_delete(&Q);\n            bf_delete(&R);\n            return -1;\n        }\n        bf_delete(&Q);\n        bf_delete(&R);\n    }\n    return 0;\n}\n\n/* return 0 if OK != 0 if memory error */\nstatic int bf_integer_to_radix(bf_t *r, const bf_t *a, limb_t radixl)\n{\n    bf_context_t *s = r->ctx;\n    limb_t r_len;\n    bf_t *pow_tab;\n    int i, pow_tab_len, ret;\n    \n    r_len = r->len;\n    pow_tab_len = (ceil_log2(r_len) + 2) * 2; /* XXX: check */\n    pow_tab = bf_malloc(s, sizeof(pow_tab[0]) * pow_tab_len);\n    if (!pow_tab)\n        return -1;\n    for(i = 0; i < pow_tab_len; i++)\n        bf_init(r->ctx, &pow_tab[i]);\n\n    ret = bf_integer_to_radix_rec(pow_tab, r->tab, a, r_len, 0, r_len, radixl,\n                                  ceil_log2(radixl));\n\n    for(i = 0; i < pow_tab_len; i++) {\n        bf_delete(&pow_tab[i]);\n    }\n    bf_free(s, pow_tab);\n    return ret;\n}\n\n/* a must be >= 0. 'P' is the wanted number of digits in radix\n   'radix'. 'r' is the mantissa represented as an integer. *pE\n   contains the exponent. Return != 0 if memory error. */\nstatic int bf_convert_to_radix(bf_t *r, slimb_t *pE,\n                               const bf_t *a, int radix,\n                               limb_t P, bf_rnd_t rnd_mode,\n                               BOOL is_fixed_exponent)\n{\n    slimb_t E, e, prec, extra_bits, ziv_extra_bits, prec0;\n    bf_t B_s, *B = &B_s;\n    int e_sign, ret, res;\n    \n    if (a->len == 0) {\n        /* zero case */\n        *pE = 0;\n        return bf_set(r, a);\n    }\n\n    if (is_fixed_exponent) {\n        E = *pE;\n    } else {\n        /* compute the new exponent */\n        E = 1 + bf_mul_log2_radix(a->expn - 1, radix, TRUE, FALSE);\n    }\n    //    bf_print_str(\"a\", a);\n    //    printf(\"E=%ld P=%ld radix=%d\\n\", E, P, radix);\n    \n    for(;;) {\n        e = P - E;\n        e_sign = 0;\n        if (e < 0) {\n            e = -e;\n            e_sign = 1;\n        }\n        /* Note: precision for log2(radix) is not critical here */\n        prec0 = bf_mul_log2_radix(P, radix, FALSE, TRUE);\n        ziv_extra_bits = 16;\n        for(;;) {\n            prec = prec0 + ziv_extra_bits;\n            /* XXX: rigorous error analysis needed */\n            extra_bits = ceil_log2(e) * 2 + 1;\n            ret = bf_pow_ui_ui(r, radix, e, prec + extra_bits,\n                               BF_RNDN | BF_FLAG_EXT_EXP);\n            if (!e_sign)\n                ret |= bf_mul(r, r, a, prec + extra_bits,\n                              BF_RNDN | BF_FLAG_EXT_EXP);\n            else\n                ret |= bf_div(r, a, r, prec + extra_bits,\n                              BF_RNDN | BF_FLAG_EXT_EXP);\n            if (ret & BF_ST_MEM_ERROR)\n                return BF_ST_MEM_ERROR;\n            /* if the result is not exact, check that it can be safely\n               rounded to an integer */\n            if ((ret & BF_ST_INEXACT) &&\n                !bf_can_round(r, r->expn, rnd_mode, prec)) {\n                /* and more precision and retry */\n                ziv_extra_bits = ziv_extra_bits  + (ziv_extra_bits / 2);\n                continue;\n            } else {\n                ret = bf_rint(r, rnd_mode);\n                if (ret & BF_ST_MEM_ERROR)\n                    return BF_ST_MEM_ERROR;\n                break;\n            }\n        }\n        if (is_fixed_exponent)\n            break;\n        /* check that the result is < B^P */\n        /* XXX: do a fast approximate test first ? */\n        bf_init(r->ctx, B);\n        ret = bf_pow_ui_ui(B, radix, P, BF_PREC_INF, BF_RNDZ);\n        if (ret) {\n            bf_delete(B);\n            return ret;\n        }\n        res = bf_cmpu(r, B);\n        bf_delete(B);\n        if (res < 0)\n            break;\n        /* try a larger exponent */\n        E++;\n    }\n    *pE = E;\n    return 0;\n}\n\nstatic void limb_to_a(char *buf, limb_t n, unsigned int radix, int len)\n{\n    int digit, i;\n\n    if (radix == 10) {\n        /* specific case with constant divisor */\n        for(i = len - 1; i >= 0; i--) {\n            digit = (limb_t)n % 10;\n            n = (limb_t)n / 10;\n            buf[i] = digit + '0';\n        }\n    } else {\n        for(i = len - 1; i >= 0; i--) {\n            digit = (limb_t)n % radix;\n            n = (limb_t)n / radix;\n            if (digit < 10)\n                digit += '0';\n            else\n                digit += 'a' - 10;\n            buf[i] = digit;\n        }\n    }\n}\n\n/* for power of 2 radixes */\nstatic void limb_to_a2(char *buf, limb_t n, unsigned int radix_bits, int len)\n{\n    int digit, i;\n    unsigned int mask;\n\n    mask = (1 << radix_bits) - 1;\n    for(i = len - 1; i >= 0; i--) {\n        digit = n & mask;\n        n >>= radix_bits;\n        if (digit < 10)\n            digit += '0';\n        else\n            digit += 'a' - 10;\n        buf[i] = digit;\n    }\n}\n\n/* 'a' must be an integer if the is_dec = FALSE or if the radix is not\n   a power of two. A dot is added before the 'dot_pos' digit. dot_pos\n   = n_digits does not display the dot. 0 <= dot_pos <=\n   n_digits. n_digits >= 1. */\nstatic void output_digits(DynBuf *s, const bf_t *a1, int radix, limb_t n_digits,\n                          limb_t dot_pos, BOOL is_dec)\n{\n    limb_t i, v, l;\n    slimb_t pos, pos_incr;\n    int digits_per_limb, buf_pos, radix_bits, first_buf_pos;\n    char buf[65];\n    bf_t a_s, *a;\n\n    if (is_dec) {\n        digits_per_limb = LIMB_DIGITS;\n        a = (bf_t *)a1;\n        radix_bits = 0;\n        pos = a->len;\n        pos_incr = 1;\n        first_buf_pos = 0;\n    } else if ((radix & (radix - 1)) == 0) {\n        a = (bf_t *)a1;\n        radix_bits = ceil_log2(radix);\n        digits_per_limb = LIMB_BITS / radix_bits;\n        pos_incr = digits_per_limb * radix_bits;\n        /* digits are aligned relative to the radix point */\n        pos = a->len * LIMB_BITS + smod(-a->expn, radix_bits);\n        first_buf_pos = 0;\n    } else {\n        limb_t n, radixl;\n\n        digits_per_limb = digits_per_limb_table[radix - 2];\n        radixl = get_limb_radix(radix);\n        a = &a_s;\n        bf_init(a1->ctx, a);\n        n = (n_digits + digits_per_limb - 1) / digits_per_limb;\n        if (bf_resize(a, n)) {\n            dbuf_set_error(s);\n            goto done;\n        }\n        if (bf_integer_to_radix(a, a1, radixl)) {\n            dbuf_set_error(s);\n            goto done;\n        }\n        radix_bits = 0;\n        pos = n;\n        pos_incr = 1;\n        first_buf_pos = pos * digits_per_limb - n_digits;\n    }\n    buf_pos = digits_per_limb;\n    i = 0;\n    while (i < n_digits) {\n        if (buf_pos == digits_per_limb) {\n            pos -= pos_incr;\n            if (radix_bits == 0) {\n                v = get_limbz(a, pos);\n                limb_to_a(buf, v, radix, digits_per_limb);\n            } else {\n                v = get_bits(a->tab, a->len, pos);\n                limb_to_a2(buf, v, radix_bits, digits_per_limb);\n            }\n            buf_pos = first_buf_pos;\n            first_buf_pos = 0;\n        }\n        if (i < dot_pos) {\n            l = dot_pos;\n        } else {\n            if (i == dot_pos)\n                dbuf_putc(s, '.');\n            l = n_digits;\n        }\n        l = bf_min(digits_per_limb - buf_pos, l - i);\n        dbuf_put(s, (uint8_t *)(buf + buf_pos), l);\n        buf_pos += l;\n        i += l;\n    }\n done:\n    if (a != a1)\n        bf_delete(a);\n}\n\nstatic void *bf_dbuf_realloc(void *opaque, void *ptr, size_t size)\n{\n    bf_context_t *s = opaque;\n    return bf_realloc(s, ptr, size);\n}\n\n/* return the length in bytes. A trailing '\\0' is added */\nstatic char *bf_ftoa_internal(size_t *plen, const bf_t *a2, int radix,\n                              limb_t prec, bf_flags_t flags, BOOL is_dec)\n{\n    bf_context_t *ctx = a2->ctx;\n    DynBuf s_s, *s = &s_s;\n    int radix_bits;\n    \n    //    bf_print_str(\"ftoa\", a2);\n    //    printf(\"radix=%d\\n\", radix);\n    dbuf_init2(s, ctx, bf_dbuf_realloc);\n    if (a2->expn == BF_EXP_NAN) {\n        dbuf_putstr(s, \"NaN\");\n    } else {\n        if (a2->sign)\n            dbuf_putc(s, '-');\n        if (a2->expn == BF_EXP_INF) {\n            if (flags & BF_FTOA_JS_QUIRKS)\n                dbuf_putstr(s, \"Infinity\");\n            else\n                dbuf_putstr(s, \"Inf\");\n        } else {\n            int fmt, ret;\n            slimb_t n_digits, n, i, n_max, n1;\n            bf_t a1_s, *a1 = &a1_s;\n\n            if ((radix & (radix - 1)) != 0)\n                radix_bits = 0;\n            else\n                radix_bits = ceil_log2(radix);\n\n            fmt = flags & BF_FTOA_FORMAT_MASK;\n            bf_init(ctx, a1);\n            if (fmt == BF_FTOA_FORMAT_FRAC) {\n                if (is_dec || radix_bits != 0) {\n                    if (bf_set(a1, a2))\n                        goto fail1;\n#ifdef USE_BF_DEC\n                    if (is_dec) {\n                        if (bfdec_round((bfdec_t *)a1, prec, (flags & BF_RND_MASK) | BF_FLAG_RADPNT_PREC) & BF_ST_MEM_ERROR)\n                            goto fail1;\n                        n = a1->expn;\n                    } else\n#endif\n                    {\n                        if (bf_round(a1, prec * radix_bits, (flags & BF_RND_MASK) | BF_FLAG_RADPNT_PREC) & BF_ST_MEM_ERROR)\n                            goto fail1;\n                        n = ceil_div(a1->expn, radix_bits);\n                    }\n                    if (flags & BF_FTOA_ADD_PREFIX) {\n                        if (radix == 16)\n                            dbuf_putstr(s, \"0x\");\n                        else if (radix == 8)\n                            dbuf_putstr(s, \"0o\");\n                        else if (radix == 2)\n                            dbuf_putstr(s, \"0b\");\n                    }\n                    if (a1->expn == BF_EXP_ZERO) {\n                        dbuf_putstr(s, \"0\");\n                        if (prec > 0) {\n                            dbuf_putstr(s, \".\");\n                            for(i = 0; i < prec; i++) {\n                                dbuf_putc(s, '0');\n                            }\n                        }\n                    } else {\n                        n_digits = prec + n;\n                        if (n <= 0) {\n                            /* 0.x */\n                            dbuf_putstr(s, \"0.\");\n                            for(i = 0; i < -n; i++) {\n                                dbuf_putc(s, '0');\n                            }\n                            if (n_digits > 0) {\n                                output_digits(s, a1, radix, n_digits, n_digits, is_dec);\n                            }\n                        } else {\n                            output_digits(s, a1, radix, n_digits, n, is_dec);\n                        }\n                    }\n                } else {\n                    size_t pos, start;\n                    bf_t a_s, *a = &a_s;\n\n                    /* make a positive number */\n                    a->tab = a2->tab;\n                    a->len = a2->len;\n                    a->expn = a2->expn;\n                    a->sign = 0;\n                    \n                    /* one more digit for the rounding */\n                    n = 1 + bf_mul_log2_radix(bf_max(a->expn, 0), radix, TRUE, TRUE);\n                    n_digits = n + prec;\n                    n1 = n;\n                    if (bf_convert_to_radix(a1, &n1, a, radix, n_digits,\n                                            flags & BF_RND_MASK, TRUE))\n                        goto fail1;\n                    start = s->size;\n                    output_digits(s, a1, radix, n_digits, n, is_dec);\n                    /* remove leading zeros because we allocated one more digit */\n                    pos = start;\n                    while ((pos + 1) < s->size && s->buf[pos] == '0' &&\n                           s->buf[pos + 1] != '.')\n                        pos++;\n                    if (pos > start) {\n                        memmove(s->buf + start, s->buf + pos, s->size - pos);\n                        s->size -= (pos - start);\n                    }\n                }\n            } else {\n#ifdef USE_BF_DEC\n                if (is_dec) {\n                    if (bf_set(a1, a2))\n                        goto fail1;\n                    if (fmt == BF_FTOA_FORMAT_FIXED) {\n                        n_digits = prec;\n                        n_max = n_digits;\n                        if (bfdec_round((bfdec_t *)a1, prec, (flags & BF_RND_MASK)) & BF_ST_MEM_ERROR)\n                            goto fail1;\n                    } else {\n                        /* prec is ignored */\n                        prec = n_digits = a1->len * LIMB_DIGITS;\n                        /* remove the trailing zero digits */\n                        while (n_digits > 1 &&\n                               get_digit(a1->tab, a1->len, prec - n_digits) == 0) {\n                            n_digits--;\n                        }\n                        n_max = n_digits + 4;\n                    }\n                    n = a1->expn;\n                } else\n#endif\n                if (radix_bits != 0) {\n                    if (bf_set(a1, a2))\n                        goto fail1;\n                    if (fmt == BF_FTOA_FORMAT_FIXED) {\n                        slimb_t prec_bits;\n                        n_digits = prec;\n                        n_max = n_digits;\n                        /* align to the radix point */\n                        prec_bits = prec * radix_bits -\n                            smod(-a1->expn, radix_bits);\n                        if (bf_round(a1, prec_bits,\n                                     (flags & BF_RND_MASK)) & BF_ST_MEM_ERROR)\n                            goto fail1;\n                    } else {\n                        limb_t digit_mask;\n                        slimb_t pos;\n                        /* position of the digit before the most\n                           significant digit in bits */\n                        pos = a1->len * LIMB_BITS +\n                            smod(-a1->expn, radix_bits);\n                        n_digits = ceil_div(pos, radix_bits);\n                        /* remove the trailing zero digits */\n                        digit_mask = ((limb_t)1 << radix_bits) - 1;\n                        while (n_digits > 1 &&\n                               (get_bits(a1->tab, a1->len, pos - n_digits * radix_bits) & digit_mask) == 0) {\n                            n_digits--;\n                        }\n                        n_max = n_digits + 4;\n                    }\n                    n = ceil_div(a1->expn, radix_bits);\n                } else {\n                    bf_t a_s, *a = &a_s;\n                    \n                    /* make a positive number */\n                    a->tab = a2->tab;\n                    a->len = a2->len;\n                    a->expn = a2->expn;\n                    a->sign = 0;\n                    \n                    if (fmt == BF_FTOA_FORMAT_FIXED) {\n                        n_digits = prec;\n                        n_max = n_digits;\n                    } else {\n                        slimb_t n_digits_max, n_digits_min;\n                        \n                        assert(prec != BF_PREC_INF);\n                        n_digits = 1 + bf_mul_log2_radix(prec, radix, TRUE, TRUE);\n                        /* max number of digits for non exponential\n                           notation. The rational is to have the same rule\n                           as JS i.e. n_max = 21 for 64 bit float in base 10. */\n                        n_max = n_digits + 4;\n                        if (fmt == BF_FTOA_FORMAT_FREE_MIN) {\n                            bf_t b_s, *b = &b_s;\n                            \n                            /* find the minimum number of digits by\n                               dichotomy. */\n                            /* XXX: inefficient */\n                            n_digits_max = n_digits;\n                            n_digits_min = 1;\n                            bf_init(ctx, b);\n                            while (n_digits_min < n_digits_max) {\n                                n_digits = (n_digits_min + n_digits_max) / 2;\n                                if (bf_convert_to_radix(a1, &n, a, radix, n_digits,\n                                                        flags & BF_RND_MASK, FALSE)) {\n                                    bf_delete(b);\n                                    goto fail1;\n                                }\n                                /* convert back to a number and compare */\n                                ret = bf_mul_pow_radix(b, a1, radix, n - n_digits,\n                                                       prec,\n                                                       (flags & ~BF_RND_MASK) |\n                                                       BF_RNDN);\n                                if (ret & BF_ST_MEM_ERROR) {\n                                    bf_delete(b);\n                                    goto fail1;\n                                }\n                                if (bf_cmpu(b, a) == 0) {\n                                    n_digits_max = n_digits;\n                                } else {\n                                    n_digits_min = n_digits + 1;\n                                }\n                            }\n                            bf_delete(b);\n                            n_digits = n_digits_max;\n                        }\n                    }\n                    if (bf_convert_to_radix(a1, &n, a, radix, n_digits,\n                                            flags & BF_RND_MASK, FALSE)) {\n                    fail1:\n                        bf_delete(a1);\n                        goto fail;\n                    }\n                }\n                if (a1->expn == BF_EXP_ZERO &&\n                    fmt != BF_FTOA_FORMAT_FIXED &&\n                    !(flags & BF_FTOA_FORCE_EXP)) {\n                    /* just output zero */\n                    dbuf_putstr(s, \"0\");\n                } else {\n                    if (flags & BF_FTOA_ADD_PREFIX) {\n                        if (radix == 16)\n                            dbuf_putstr(s, \"0x\");\n                        else if (radix == 8)\n                            dbuf_putstr(s, \"0o\");\n                        else if (radix == 2)\n                            dbuf_putstr(s, \"0b\");\n                    }\n                    if (a1->expn == BF_EXP_ZERO)\n                        n = 1;\n                    if ((flags & BF_FTOA_FORCE_EXP) ||\n                        n <= -6 || n > n_max) {\n                        const char *fmt;\n                        /* exponential notation */\n                        output_digits(s, a1, radix, n_digits, 1, is_dec);\n                        if (radix_bits != 0 && radix <= 16) {\n                            if (flags & BF_FTOA_JS_QUIRKS)\n                                fmt = \"p%+\" PRId_LIMB;\n                            else\n                                fmt = \"p%\" PRId_LIMB;\n                            dbuf_printf(s, fmt, (n - 1) * radix_bits);\n                        } else {\n                            if (flags & BF_FTOA_JS_QUIRKS)\n                                fmt = \"%c%+\" PRId_LIMB;\n                            else\n                                fmt = \"%c%\" PRId_LIMB;\n                            dbuf_printf(s, fmt,\n                                        radix <= 10 ? 'e' : '@', n - 1);\n                        }\n                    } else if (n <= 0) {\n                        /* 0.x */\n                        dbuf_putstr(s, \"0.\");\n                        for(i = 0; i < -n; i++) {\n                            dbuf_putc(s, '0');\n                        }\n                        output_digits(s, a1, radix, n_digits, n_digits, is_dec);\n                    } else {\n                        if (n_digits <= n) {\n                            /* no dot */\n                            output_digits(s, a1, radix, n_digits, n_digits, is_dec);\n                            for(i = 0; i < (n - n_digits); i++)\n                                dbuf_putc(s, '0');\n                        } else {\n                            output_digits(s, a1, radix, n_digits, n, is_dec);\n                        }\n                    }\n                }\n            }\n            bf_delete(a1);\n        }\n    }\n    dbuf_putc(s, '\\0');\n    if (dbuf_error(s))\n        goto fail;\n    if (plen)\n        *plen = s->size - 1;\n    return (char *)s->buf;\n fail:\n    bf_free(ctx, s->buf);\n    if (plen)\n        *plen = 0;\n    return NULL;\n}\n\nchar *bf_ftoa(size_t *plen, const bf_t *a, int radix, limb_t prec,\n              bf_flags_t flags)\n{\n    return bf_ftoa_internal(plen, a, radix, prec, flags, FALSE);\n}\n\n/***************************************************************/\n/* transcendental functions */\n\n/* Note: the algorithm is from MPFR */\nstatic void bf_const_log2_rec(bf_t *T, bf_t *P, bf_t *Q, limb_t n1,\n                              limb_t n2, BOOL need_P)\n{\n    bf_context_t *s = T->ctx;\n    if ((n2 - n1) == 1) {\n        if (n1 == 0) {\n            bf_set_ui(P, 3);\n        } else {\n            bf_set_ui(P, n1);\n            P->sign = 1;\n        }\n        bf_set_ui(Q, 2 * n1 + 1);\n        Q->expn += 2;\n        bf_set(T, P);\n    } else {\n        limb_t m;\n        bf_t T1_s, *T1 = &T1_s;\n        bf_t P1_s, *P1 = &P1_s;\n        bf_t Q1_s, *Q1 = &Q1_s;\n        \n        m = n1 + ((n2 - n1) >> 1);\n        bf_const_log2_rec(T, P, Q, n1, m, TRUE);\n        bf_init(s, T1);\n        bf_init(s, P1);\n        bf_init(s, Q1);\n        bf_const_log2_rec(T1, P1, Q1, m, n2, need_P);\n        bf_mul(T, T, Q1, BF_PREC_INF, BF_RNDZ);\n        bf_mul(T1, T1, P, BF_PREC_INF, BF_RNDZ);\n        bf_add(T, T, T1, BF_PREC_INF, BF_RNDZ);\n        if (need_P)\n            bf_mul(P, P, P1, BF_PREC_INF, BF_RNDZ);\n        bf_mul(Q, Q, Q1, BF_PREC_INF, BF_RNDZ);\n        bf_delete(T1);\n        bf_delete(P1);\n        bf_delete(Q1);\n    }\n}\n\n/* compute log(2) with faithful rounding at precision 'prec' */\nstatic void bf_const_log2_internal(bf_t *T, limb_t prec)\n{\n    limb_t w, N;\n    bf_t P_s, *P = &P_s;\n    bf_t Q_s, *Q = &Q_s;\n\n    w = prec + 15;\n    N = w / 3 + 1;\n    bf_init(T->ctx, P);\n    bf_init(T->ctx, Q);\n    bf_const_log2_rec(T, P, Q, 0, N, FALSE);\n    bf_div(T, T, Q, prec, BF_RNDN);\n    bf_delete(P);\n    bf_delete(Q);\n}\n\n/* PI constant */\n\n#define CHUD_A 13591409\n#define CHUD_B 545140134\n#define CHUD_C 640320\n#define CHUD_BITS_PER_TERM 47\n\nstatic void chud_bs(bf_t *P, bf_t *Q, bf_t *G, int64_t a, int64_t b, int need_g,\n                    limb_t prec)\n{\n    bf_context_t *s = P->ctx;\n    int64_t c;\n\n    if (a == (b - 1)) {\n        bf_t T0, T1;\n        \n        bf_init(s, &T0);\n        bf_init(s, &T1);\n        bf_set_ui(G, 2 * b - 1);\n        bf_mul_ui(G, G, 6 * b - 1, prec, BF_RNDN);\n        bf_mul_ui(G, G, 6 * b - 5, prec, BF_RNDN);\n        bf_set_ui(&T0, CHUD_B);\n        bf_mul_ui(&T0, &T0, b, prec, BF_RNDN);\n        bf_set_ui(&T1, CHUD_A);\n        bf_add(&T0, &T0, &T1, prec, BF_RNDN);\n        bf_mul(P, G, &T0, prec, BF_RNDN);\n        P->sign = b & 1;\n\n        bf_set_ui(Q, b);\n        bf_mul_ui(Q, Q, b, prec, BF_RNDN);\n        bf_mul_ui(Q, Q, b, prec, BF_RNDN);\n        bf_mul_ui(Q, Q, (uint64_t)CHUD_C * CHUD_C * CHUD_C / 24, prec, BF_RNDN);\n        bf_delete(&T0);\n        bf_delete(&T1);\n    } else {\n        bf_t P2, Q2, G2;\n        \n        bf_init(s, &P2);\n        bf_init(s, &Q2);\n        bf_init(s, &G2);\n\n        c = (a + b) / 2;\n        chud_bs(P, Q, G, a, c, 1, prec);\n        chud_bs(&P2, &Q2, &G2, c, b, need_g, prec);\n        \n        /* Q = Q1 * Q2 */\n        /* G = G1 * G2 */\n        /* P = P1 * Q2 + P2 * G1 */\n        bf_mul(&P2, &P2, G, prec, BF_RNDN);\n        if (!need_g)\n            bf_set_ui(G, 0);\n        bf_mul(P, P, &Q2, prec, BF_RNDN);\n        bf_add(P, P, &P2, prec, BF_RNDN);\n        bf_delete(&P2);\n\n        bf_mul(Q, Q, &Q2, prec, BF_RNDN);\n        bf_delete(&Q2);\n        if (need_g)\n            bf_mul(G, G, &G2, prec, BF_RNDN);\n        bf_delete(&G2);\n    }\n}\n\n/* compute Pi with faithful rounding at precision 'prec' using the\n   Chudnovsky formula */\nstatic void bf_const_pi_internal(bf_t *Q, limb_t prec)\n{\n    bf_context_t *s = Q->ctx;\n    int64_t n, prec1;\n    bf_t P, G;\n\n    /* number of serie terms */\n    n = prec / CHUD_BITS_PER_TERM + 1;\n    /* XXX: precision analysis */\n    prec1 = prec + 32;\n\n    bf_init(s, &P);\n    bf_init(s, &G);\n\n    chud_bs(&P, Q, &G, 0, n, 0, BF_PREC_INF);\n    \n    bf_mul_ui(&G, Q, CHUD_A, prec1, BF_RNDN);\n    bf_add(&P, &G, &P, prec1, BF_RNDN);\n    bf_div(Q, Q, &P, prec1, BF_RNDF);\n \n    bf_set_ui(&P, CHUD_C);\n    bf_sqrt(&G, &P, prec1, BF_RNDF);\n    bf_mul_ui(&G, &G, (uint64_t)CHUD_C / 12, prec1, BF_RNDF);\n    bf_mul(Q, Q, &G, prec, BF_RNDN);\n    bf_delete(&P);\n    bf_delete(&G);\n}\n\nstatic int bf_const_get(bf_t *T, limb_t prec, bf_flags_t flags,\n                        BFConstCache *c,\n                        void (*func)(bf_t *res, limb_t prec), int sign)\n{\n    limb_t ziv_extra_bits, prec1;\n\n    ziv_extra_bits = 32;\n    for(;;) {\n        prec1 = prec + ziv_extra_bits;\n        if (c->prec < prec1) {\n            if (c->val.len == 0)\n                bf_init(T->ctx, &c->val);\n            func(&c->val, prec1);\n            c->prec = prec1;\n        } else {\n            prec1 = c->prec;\n        }\n        bf_set(T, &c->val);\n        T->sign = sign;\n        if (!bf_can_round(T, prec, flags & BF_RND_MASK, prec1)) {\n            /* and more precision and retry */\n            ziv_extra_bits = ziv_extra_bits  + (ziv_extra_bits / 2);\n        } else {\n            break;\n        }\n    }\n    return bf_round(T, prec, flags);\n}\n\nstatic void bf_const_free(BFConstCache *c)\n{\n    bf_delete(&c->val);\n    memset(c, 0, sizeof(*c));\n}\n\nint bf_const_log2(bf_t *T, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = T->ctx;\n    return bf_const_get(T, prec, flags, &s->log2_cache, bf_const_log2_internal, 0);\n}\n\n/* return rounded pi * (1 - 2 * sign) */\nstatic int bf_const_pi_signed(bf_t *T, int sign, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = T->ctx;\n    return bf_const_get(T, prec, flags, &s->pi_cache, bf_const_pi_internal,\n                        sign);\n}\n\nint bf_const_pi(bf_t *T, limb_t prec, bf_flags_t flags)\n{\n    return bf_const_pi_signed(T, 0, prec, flags);\n}\n\nvoid bf_clear_cache(bf_context_t *s)\n{\n#ifdef USE_FFT_MUL\n    fft_clear_cache(s);\n#endif\n    bf_const_free(&s->log2_cache);\n    bf_const_free(&s->pi_cache);\n}\n\n/* ZivFunc should compute the result 'r' with faithful rounding at\n   precision 'prec'. For efficiency purposes, the final bf_round()\n   does not need to be done in the function. */\ntypedef int ZivFunc(bf_t *r, const bf_t *a, limb_t prec, void *opaque);\n\nstatic int bf_ziv_rounding(bf_t *r, const bf_t *a,\n                           limb_t prec, bf_flags_t flags,\n                           ZivFunc *f, void *opaque)\n{\n    int rnd_mode, ret;\n    slimb_t prec1, ziv_extra_bits;\n    \n    rnd_mode = flags & BF_RND_MASK;\n    if (rnd_mode == BF_RNDF) {\n        /* no need to iterate */\n        f(r, a, prec, opaque);\n        ret = 0;\n    } else {\n        ziv_extra_bits = 32;\n        for(;;) {\n            prec1 = prec + ziv_extra_bits;\n            ret = f(r, a, prec1, opaque);\n            if (ret & (BF_ST_OVERFLOW | BF_ST_UNDERFLOW | BF_ST_MEM_ERROR)) {\n                /* overflow or underflow should never happen because\n                   it indicates the rounding cannot be done correctly,\n                   but we do not catch all the cases */\n                return ret;\n            }\n            /* if the result is exact, we can stop */\n            if (!(ret & BF_ST_INEXACT)) {\n                ret = 0;\n                break;\n            }\n            if (bf_can_round(r, prec, rnd_mode, prec1)) {\n                ret = BF_ST_INEXACT;\n                break;\n            }\n            ziv_extra_bits = ziv_extra_bits * 2;\n            //            printf(\"ziv_extra_bits=%\" PRId64 \"\\n\", (int64_t)ziv_extra_bits);\n        }\n    }\n    if (r->len == 0)\n        return ret;\n    else\n        return __bf_round(r, prec, flags, r->len, ret);\n}\n\n/* add (1 - 2*e_sign) * 2^e */\nstatic int bf_add_epsilon(bf_t *r, const bf_t *a, slimb_t e, int e_sign,\n                          limb_t prec, int flags)\n{\n    bf_t T_s, *T = &T_s;\n    int ret;\n    /* small argument case: result = 1 + epsilon * sign(x) */\n    bf_init(a->ctx, T);\n    bf_set_ui(T, 1);\n    T->sign = e_sign;\n    T->expn += e;\n    ret = bf_add(r, r, T, prec, flags);\n    bf_delete(T);\n    return ret;\n}\n\n/* Compute the exponential using faithful rounding at precision 'prec'.\n   Note: the algorithm is from MPFR */\nstatic int bf_exp_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    slimb_t n, K, l, i, prec1;\n    \n    assert(r != a);\n\n    /* argument reduction:\n       T = a - n*log(2) with 0 <= T < log(2) and n integer.\n    */\n    bf_init(s, T);\n    if (a->expn <= -1) {\n        /* 0 <= abs(a) <= 0.5 */\n        if (a->sign)\n            n = -1;\n        else\n            n = 0;\n    } else {\n        bf_const_log2(T, LIMB_BITS, BF_RNDZ);\n        bf_div(T, a, T, LIMB_BITS, BF_RNDD);\n        bf_get_limb(&n, T, 0);\n    }\n\n    K = bf_isqrt((prec + 1) / 2);\n    l = (prec - 1) / K + 1;\n    /* XXX: precision analysis ? */\n    prec1 = prec + (K + 2 * l + 18) + K + 8;\n    if (a->expn > 0)\n        prec1 += a->expn;\n    //    printf(\"n=%ld K=%ld prec1=%ld\\n\", n, K, prec1);\n\n    bf_const_log2(T, prec1, BF_RNDF);\n    bf_mul_si(T, T, n, prec1, BF_RNDN);\n    bf_sub(T, a, T, prec1, BF_RNDN);\n\n    /* reduce the range of T */\n    bf_mul_2exp(T, -K, BF_PREC_INF, BF_RNDZ);\n    \n    /* Taylor expansion around zero :\n     1 + x + x^2/2 + ... + x^n/n! \n     = (1 + x * (1 + x/2 * (1 + ... (x/n))))\n    */\n    {\n        bf_t U_s, *U = &U_s;\n        \n        bf_init(s, U);\n        bf_set_ui(r, 1);\n        for(i = l ; i >= 1; i--) {\n            bf_set_ui(U, i);\n            bf_div(U, T, U, prec1, BF_RNDN);\n            bf_mul(r, r, U, prec1, BF_RNDN);\n            bf_add_si(r, r, 1, prec1, BF_RNDN);\n        }\n        bf_delete(U);\n    }\n    bf_delete(T);\n    \n    /* undo the range reduction */\n    for(i = 0; i < K; i++) {\n        bf_mul(r, r, r, prec1, BF_RNDN | BF_FLAG_EXT_EXP);\n    }\n\n    /* undo the argument reduction */\n    bf_mul_2exp(r, n, BF_PREC_INF, BF_RNDZ | BF_FLAG_EXT_EXP);\n\n    return BF_ST_INEXACT;\n}\n\n/* crude overflow and underflow tests for exp(a). a_low <= a <= a_high */\nstatic int check_exp_underflow_overflow(bf_context_t *s, bf_t *r,\n                                        const bf_t *a_low, const bf_t *a_high,\n                                        limb_t prec, bf_flags_t flags)\n{\n    bf_t T_s, *T = &T_s;\n    bf_t log2_s, *log2 = &log2_s;\n    slimb_t e_min, e_max;\n    \n    if (a_high->expn <= 0)\n        return 0;\n\n    e_max = (limb_t)1 << (bf_get_exp_bits(flags) - 1);\n    e_min = -e_max + 3;\n    if (flags & BF_FLAG_SUBNORMAL)\n        e_min -= (prec - 1);\n    \n    bf_init(s, T);\n    bf_init(s, log2);\n    bf_const_log2(log2, LIMB_BITS, BF_RNDU);\n    bf_mul_ui(T, log2, e_max, LIMB_BITS, BF_RNDU);\n    /* a_low > e_max * log(2) implies exp(a) > e_max */\n    if (bf_cmp_lt(T, a_low) > 0) {\n        /* overflow */\n        bf_delete(T);\n        bf_delete(log2);\n        return bf_set_overflow(r, 0, prec, flags);\n    }\n    /* a_high < (e_min - 2) * log(2) implies exp(a) < (e_min - 2) */\n    bf_const_log2(log2, LIMB_BITS, BF_RNDD);\n    bf_mul_si(T, log2, e_min - 2, LIMB_BITS, BF_RNDD);\n    if (bf_cmp_lt(a_high, T)) {\n        int rnd_mode = flags & BF_RND_MASK;\n        \n        /* underflow */\n        bf_delete(T);\n        bf_delete(log2);\n        if (rnd_mode == BF_RNDU) {\n            /* set the smallest value */\n            bf_set_ui(r, 1);\n            r->expn = e_min;\n        } else {\n            bf_set_zero(r, 0);\n        }\n        return BF_ST_UNDERFLOW | BF_ST_INEXACT;\n    }\n    bf_delete(log2);\n    bf_delete(T);\n    return 0;\n}\n\nint bf_exp(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = r->ctx;\n    int ret;\n    assert(r != a);\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n        } else if (a->expn == BF_EXP_INF) {\n            if (a->sign)\n                bf_set_zero(r, 0);\n            else\n                bf_set_inf(r, 0);\n        } else {\n            bf_set_ui(r, 1);\n        }\n        return 0;\n    }\n\n    ret = check_exp_underflow_overflow(s, r, a, a, prec, flags);\n    if (ret)\n        return ret;\n    if (a->expn < 0 && (-a->expn) >= (prec + 2)) { \n        /* small argument case: result = 1 + epsilon * sign(x) */\n        bf_set_ui(r, 1);\n        return bf_add_epsilon(r, r, -(prec + 2), a->sign, prec, flags);\n    }\n                         \n    return bf_ziv_rounding(r, a, prec, flags, bf_exp_internal, NULL);\n}\n\nstatic int bf_log_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    bf_t U_s, *U = &U_s;\n    bf_t V_s, *V = &V_s;\n    slimb_t n, prec1, l, i, K;\n    \n    assert(r != a);\n\n    bf_init(s, T);\n    /* argument reduction 1 */\n    /* T=a*2^n with 2/3 <= T <= 4/3 */\n    {\n        bf_t U_s, *U = &U_s;\n        bf_set(T, a);\n        n = T->expn;\n        T->expn = 0;\n        /* U= ~ 2/3 */\n        bf_init(s, U);\n        bf_set_ui(U, 0xaaaaaaaa); \n        U->expn = 0;\n        if (bf_cmp_lt(T, U)) {\n            T->expn++;\n            n--;\n        }\n        bf_delete(U);\n    }\n    //    printf(\"n=%ld\\n\", n);\n    //    bf_print_str(\"T\", T);\n\n    /* XXX: precision analysis */\n    /* number of iterations for argument reduction 2 */\n    K = bf_isqrt((prec + 1) / 2); \n    /* order of Taylor expansion */\n    l = prec / (2 * K) + 1; \n    /* precision of the intermediate computations */\n    prec1 = prec + K + 2 * l + 32;\n\n    bf_init(s, U);\n    bf_init(s, V);\n    \n    /* Note: cancellation occurs here, so we use more precision (XXX:\n       reduce the precision by computing the exact cancellation) */\n    bf_add_si(T, T, -1, BF_PREC_INF, BF_RNDN); \n\n    /* argument reduction 2 */\n    for(i = 0; i < K; i++) {\n        /* T = T / (1 + sqrt(1 + T)) */\n        bf_add_si(U, T, 1, prec1, BF_RNDN);\n        bf_sqrt(V, U, prec1, BF_RNDF);\n        bf_add_si(U, V, 1, prec1, BF_RNDN);\n        bf_div(T, T, U, prec1, BF_RNDN);\n    }\n\n    {\n        bf_t Y_s, *Y = &Y_s;\n        bf_t Y2_s, *Y2 = &Y2_s;\n        bf_init(s, Y);\n        bf_init(s, Y2);\n\n        /* compute ln(1+x) = ln((1+y)/(1-y)) with y=x/(2+x)\n           = y + y^3/3 + ... + y^(2*l + 1) / (2*l+1) \n           with Y=Y^2\n           = y*(1+Y/3+Y^2/5+...) = y*(1+Y*(1/3+Y*(1/5 + ...)))\n        */\n        bf_add_si(Y, T, 2, prec1, BF_RNDN);\n        bf_div(Y, T, Y, prec1, BF_RNDN);\n\n        bf_mul(Y2, Y, Y, prec1, BF_RNDN);\n        bf_set_ui(r, 0);\n        for(i = l; i >= 1; i--) {\n            bf_set_ui(U, 1);\n            bf_set_ui(V, 2 * i + 1);\n            bf_div(U, U, V, prec1, BF_RNDN);\n            bf_add(r, r, U, prec1, BF_RNDN);\n            bf_mul(r, r, Y2, prec1, BF_RNDN);\n        }\n        bf_add_si(r, r, 1, prec1, BF_RNDN);\n        bf_mul(r, r, Y, prec1, BF_RNDN);\n        bf_delete(Y);\n        bf_delete(Y2);\n    }\n    bf_delete(V);\n    bf_delete(U);\n\n    /* multiplication by 2 for the Taylor expansion and undo the\n       argument reduction 2*/\n    bf_mul_2exp(r, K + 1, BF_PREC_INF, BF_RNDZ);\n    \n    /* undo the argument reduction 1 */\n    bf_const_log2(T, prec1, BF_RNDF);\n    bf_mul_si(T, T, n, prec1, BF_RNDN);\n    bf_add(r, r, T, prec1, BF_RNDN);\n    \n    bf_delete(T);\n    return BF_ST_INEXACT;\n}\n\nint bf_log(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    \n    assert(r != a);\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF) {\n            if (a->sign) {\n                bf_set_nan(r);\n                return BF_ST_INVALID_OP;\n            } else {\n                bf_set_inf(r, 0);\n                return 0;\n            }\n        } else {\n            bf_set_inf(r, 1);\n            return 0;\n        }\n    }\n    if (a->sign) {\n        bf_set_nan(r);\n        return BF_ST_INVALID_OP;\n    }\n    bf_init(s, T);\n    bf_set_ui(T, 1);\n    if (bf_cmp_eq(a, T)) {\n        bf_set_zero(r, 0);\n        bf_delete(T);\n        return 0;\n    }\n    bf_delete(T);\n\n    return bf_ziv_rounding(r, a, prec, flags, bf_log_internal, NULL);\n}\n\n/* x and y finite and x > 0 */\nstatic int bf_pow_generic(bf_t *r, const bf_t *x, limb_t prec, void *opaque)\n{\n    bf_context_t *s = r->ctx;\n    const bf_t *y = opaque;\n    bf_t T_s, *T = &T_s;\n    limb_t prec1;\n\n    bf_init(s, T);\n    /* XXX: proof for the added precision */\n    prec1 = prec + 32;\n    bf_log(T, x, prec1, BF_RNDF | BF_FLAG_EXT_EXP);\n    bf_mul(T, T, y, prec1, BF_RNDF | BF_FLAG_EXT_EXP);\n    if (bf_is_nan(T))\n        bf_set_nan(r);\n    else\n        bf_exp_internal(r, T, prec1, NULL); /* no overflow/underlow test needed */\n    bf_delete(T);\n    return BF_ST_INEXACT;\n}\n\n/* x and y finite, x > 0, y integer and y fits on one limb */\nstatic int bf_pow_int(bf_t *r, const bf_t *x, limb_t prec, void *opaque)\n{\n    bf_context_t *s = r->ctx;\n    const bf_t *y = opaque;\n    bf_t T_s, *T = &T_s;\n    limb_t prec1;\n    int ret;\n    slimb_t y1;\n    \n    bf_get_limb(&y1, y, 0);\n    if (y1 < 0)\n        y1 = -y1;\n    /* XXX: proof for the added precision */\n    prec1 = prec + ceil_log2(y1) * 2 + 8;\n    ret = bf_pow_ui(r, x, y1 < 0 ? -y1 : y1, prec1, BF_RNDN | BF_FLAG_EXT_EXP);\n    if (y->sign) {\n        bf_init(s, T);\n        bf_set_ui(T, 1);\n        ret |= bf_div(r, T, r, prec1, BF_RNDN | BF_FLAG_EXT_EXP);\n        bf_delete(T);\n    }\n    return ret;\n}\n\n/* x must be a finite non zero float. Return TRUE if there is a\n   floating point number r such as x=r^(2^n) and return this floating\n   point number 'r'. Otherwise return FALSE and r is undefined. */\nstatic BOOL check_exact_power2n(bf_t *r, const bf_t *x, slimb_t n)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    slimb_t e, i, er;\n    limb_t v;\n    \n    /* x = m*2^e with m odd integer */\n    e = bf_get_exp_min(x);\n    /* fast check on the exponent */\n    if (n > (LIMB_BITS - 1)) {\n        if (e != 0)\n            return FALSE;\n        er = 0;\n    } else {\n        if ((e & (((limb_t)1 << n) - 1)) != 0)\n            return FALSE;\n        er = e >> n;\n    }\n    /* every perfect odd square = 1 modulo 8 */\n    v = get_bits(x->tab, x->len, x->len * LIMB_BITS - x->expn + e);\n    if ((v & 7) != 1)\n        return FALSE;\n\n    bf_init(s, T);\n    bf_set(T, x);\n    T->expn -= e;\n    for(i = 0; i < n; i++) {\n        if (i != 0)\n            bf_set(T, r);\n        if (bf_sqrtrem(r, NULL, T) != 0)\n            return FALSE;\n    }\n    r->expn += er;\n    return TRUE;\n}\n\n/* prec = BF_PREC_INF is accepted for x and y integers and y >= 0 */\nint bf_pow(bf_t *r, const bf_t *x, const bf_t *y, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    bf_t ytmp_s;\n    BOOL y_is_int, y_is_odd;\n    int r_sign, ret, rnd_mode;\n    slimb_t y_emin;\n    \n    if (x->len == 0 || y->len == 0) {\n        if (y->expn == BF_EXP_ZERO) {\n            /* pow(x, 0) = 1 */\n            bf_set_ui(r, 1);\n        } else if (x->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n        } else {\n            int cmp_x_abs_1;\n            bf_set_ui(r, 1);\n            cmp_x_abs_1 = bf_cmpu(x, r);\n            if (cmp_x_abs_1 == 0 && (flags & BF_POW_JS_QUIRKS) &&\n                (y->expn >= BF_EXP_INF)) {\n                bf_set_nan(r);\n            } else if (cmp_x_abs_1 == 0 &&\n                       (!x->sign || y->expn != BF_EXP_NAN)) {\n                /* pow(1, y) = 1 even if y = NaN */\n                /* pow(-1, +/-inf) = 1 */\n            } else if (y->expn == BF_EXP_NAN) {\n                bf_set_nan(r);\n            } else if (y->expn == BF_EXP_INF) {\n                if (y->sign == (cmp_x_abs_1 > 0)) {\n                    bf_set_zero(r, 0);\n                } else {\n                    bf_set_inf(r, 0);\n                }\n            } else {\n                y_emin = bf_get_exp_min(y);\n                y_is_odd = (y_emin == 0);\n                if (y->sign == (x->expn == BF_EXP_ZERO)) {\n                    bf_set_inf(r, y_is_odd & x->sign);\n                    if (y->sign) {\n                        /* pow(0, y) with y < 0 */\n                        return BF_ST_DIVIDE_ZERO;\n                    }\n                } else {\n                    bf_set_zero(r, y_is_odd & x->sign);\n                }\n            }\n        }\n        return 0;\n    }\n    bf_init(s, T);\n    bf_set(T, x);\n    y_emin = bf_get_exp_min(y);\n    y_is_int = (y_emin >= 0);\n    rnd_mode = flags & BF_RND_MASK;\n    if (x->sign) {\n        if (!y_is_int) {\n            bf_set_nan(r);\n            bf_delete(T);\n            return BF_ST_INVALID_OP;\n        }\n        y_is_odd = (y_emin == 0);\n        r_sign = y_is_odd;\n        /* change the directed rounding mode if the sign of the result\n           is changed */\n        if (r_sign && (rnd_mode == BF_RNDD || rnd_mode == BF_RNDU))\n            flags ^= 1;\n        bf_neg(T);\n    } else {\n        r_sign = 0;\n    }\n\n    bf_set_ui(r, 1);\n    if (bf_cmp_eq(T, r)) {\n        /* abs(x) = 1: nothing more to do */\n        ret = 0;\n    } else {\n        /* check the overflow/underflow cases */\n        {\n            bf_t al_s, *al = &al_s;\n            bf_t ah_s, *ah = &ah_s;\n            limb_t precl = LIMB_BITS;\n            \n            bf_init(s, al);\n            bf_init(s, ah);\n            /* compute bounds of log(abs(x)) * y with a low precision */\n            /* XXX: compute bf_log() once */\n            /* XXX: add a fast test before this slow test */\n            bf_log(al, T, precl, BF_RNDD);\n            bf_log(ah, T, precl, BF_RNDU);\n            bf_mul(al, al, y, precl, BF_RNDD ^ y->sign);\n            bf_mul(ah, ah, y, precl, BF_RNDU ^ y->sign);\n            ret = check_exp_underflow_overflow(s, r, al, ah, prec, flags);\n            bf_delete(al);\n            bf_delete(ah);\n            if (ret)\n                goto done;\n        }\n        \n        if (y_is_int) {\n            slimb_t T_bits, e;\n        int_pow:\n            T_bits = T->expn - bf_get_exp_min(T);\n            if (T_bits == 1) {\n                /* pow(2^b, y) = 2^(b*y) */\n                bf_mul_si(T, y, T->expn - 1, LIMB_BITS, BF_RNDZ);\n                bf_get_limb(&e, T, 0);\n                bf_set_ui(r, 1);\n                ret = bf_mul_2exp(r, e, prec, flags);\n            } else if (prec == BF_PREC_INF) {\n                slimb_t y1;\n                /* specific case for infinite precision (integer case) */\n                bf_get_limb(&y1, y, 0);\n                assert(!y->sign);\n                /* x must be an integer, so abs(x) >= 2 */\n                if (y1 >= ((slimb_t)1 << BF_EXP_BITS_MAX)) {\n                    bf_delete(T);\n                    return bf_set_overflow(r, 0, BF_PREC_INF, flags);\n                }\n                ret = bf_pow_ui(r, T, y1, BF_PREC_INF, BF_RNDZ);\n            } else {\n                if (y->expn <= 31) {\n                    /* small enough power: use exponentiation in all cases */\n                } else if (y->sign) {\n                    /* cannot be exact */\n                    goto general_case;\n                } else {\n                    if (rnd_mode == BF_RNDF)\n                        goto general_case; /* no need to track exact results */\n                    /* see if the result has a chance to be exact:\n                       if x=a*2^b (a odd), x^y=a^y*2^(b*y)\n                       x^y needs a precision of at least floor_log2(a)*y bits\n                    */\n                    bf_mul_si(r, y, T_bits - 1, LIMB_BITS, BF_RNDZ);\n                    bf_get_limb(&e, r, 0);\n                    if (prec < e)\n                        goto general_case;\n                }\n                ret = bf_ziv_rounding(r, T, prec, flags, bf_pow_int, (void *)y);\n            }\n        } else {\n            if (rnd_mode != BF_RNDF) {\n                bf_t *y1;\n                if (y_emin < 0 && check_exact_power2n(r, T, -y_emin)) {\n                    /* the problem is reduced to a power to an integer */\n#if 0\n                    printf(\"\\nn=%\" PRId64 \"\\n\", -(int64_t)y_emin);\n                    bf_print_str(\"T\", T);\n                    bf_print_str(\"r\", r);\n#endif\n                    bf_set(T, r);\n                    y1 = &ytmp_s;\n                    y1->tab = y->tab;\n                    y1->len = y->len;\n                    y1->sign = y->sign;\n                    y1->expn = y->expn - y_emin;\n                    y = y1;\n                    goto int_pow;\n                }\n            }\n        general_case:\n            ret = bf_ziv_rounding(r, T, prec, flags, bf_pow_generic, (void *)y);\n        }\n    }\n done:\n    bf_delete(T);\n    r->sign = r_sign;\n    return ret;\n}\n\n/* compute sqrt(-2*x-x^2) to get |sin(x)| from cos(x) - 1. */\nstatic void bf_sqrt_sin(bf_t *r, const bf_t *x, limb_t prec1)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    bf_init(s, T);\n    bf_set(T, x);\n    bf_mul(r, T, T, prec1, BF_RNDN);\n    bf_mul_2exp(T, 1, BF_PREC_INF, BF_RNDZ);\n    bf_add(T, T, r, prec1, BF_RNDN);\n    bf_neg(T);\n    bf_sqrt(r, T, prec1, BF_RNDF);\n    bf_delete(T);\n}\n\nstatic int bf_sincos(bf_t *s, bf_t *c, const bf_t *a, limb_t prec)\n{\n    bf_context_t *s1 = a->ctx;\n    bf_t T_s, *T = &T_s;\n    bf_t U_s, *U = &U_s;\n    bf_t r_s, *r = &r_s;\n    slimb_t K, prec1, i, l, mod, prec2;\n    int is_neg;\n    \n    assert(c != a && s != a);\n\n    bf_init(s1, T);\n    bf_init(s1, U);\n    bf_init(s1, r);\n    \n    /* XXX: precision analysis */\n    K = bf_isqrt(prec / 2);\n    l = prec / (2 * K) + 1;\n    prec1 = prec + 2 * K + l + 8;\n    \n    /* after the modulo reduction, -pi/4 <= T <= pi/4 */\n    if (a->expn <= -1) {\n        /* abs(a) <= 0.25: no modulo reduction needed */\n        bf_set(T, a);\n        mod = 0;\n    } else {\n        slimb_t cancel;\n        cancel = 0;\n        for(;;) {\n            prec2 = prec1 + a->expn + cancel;\n            bf_const_pi(U, prec2, BF_RNDF);\n            bf_mul_2exp(U, -1, BF_PREC_INF, BF_RNDZ);\n            bf_remquo(&mod, T, a, U, prec2, BF_RNDN, BF_RNDN);\n            //            printf(\"T.expn=%ld prec2=%ld\\n\", T->expn, prec2);\n            if (mod == 0 || (T->expn != BF_EXP_ZERO &&\n                             (T->expn + prec2) >= (prec1 - 1)))\n                break;\n            /* increase the number of bits until the precision is good enough */\n            cancel = bf_max(-T->expn, (cancel + 1) * 3 / 2);\n        }\n        mod &= 3;\n    }\n    \n    is_neg = T->sign;\n        \n    /* compute cosm1(x) = cos(x) - 1 */\n    bf_mul(T, T, T, prec1, BF_RNDN);\n    bf_mul_2exp(T, -2 * K, BF_PREC_INF, BF_RNDZ);\n    \n    /* Taylor expansion:\n       -x^2/2 + x^4/4! - x^6/6! + ...\n    */\n    bf_set_ui(r, 1);\n    for(i = l ; i >= 1; i--) {\n        bf_set_ui(U, 2 * i - 1);\n        bf_mul_ui(U, U, 2 * i, BF_PREC_INF, BF_RNDZ);\n        bf_div(U, T, U, prec1, BF_RNDN);\n        bf_mul(r, r, U, prec1, BF_RNDN);\n        bf_neg(r);\n        if (i != 1)\n            bf_add_si(r, r, 1, prec1, BF_RNDN);\n    }\n    bf_delete(U);\n\n    /* undo argument reduction:\n       cosm1(2*x)= 2*(2*cosm1(x)+cosm1(x)^2)\n    */\n    for(i = 0; i < K; i++) {\n        bf_mul(T, r, r, prec1, BF_RNDN);\n        bf_mul_2exp(r, 1, BF_PREC_INF, BF_RNDZ);\n        bf_add(r, r, T, prec1, BF_RNDN);\n        bf_mul_2exp(r, 1, BF_PREC_INF, BF_RNDZ);\n    }\n    bf_delete(T);\n\n    if (c) {\n        if ((mod & 1) == 0) {\n            bf_add_si(c, r, 1, prec1, BF_RNDN);\n        } else {\n            bf_sqrt_sin(c, r, prec1);\n            c->sign = is_neg ^ 1;\n        }\n        c->sign ^= mod >> 1;\n    }\n    if (s) {\n        if ((mod & 1) == 0) {\n            bf_sqrt_sin(s, r, prec1);\n            s->sign = is_neg;\n        } else {\n            bf_add_si(s, r, 1, prec1, BF_RNDN);\n        }\n        s->sign ^= mod >> 1;\n    }\n    bf_delete(r);\n    return BF_ST_INEXACT;\n}\n\nstatic int bf_cos_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)\n{\n    return bf_sincos(NULL, r, a, prec);\n}\n\nint bf_cos(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF) {\n            bf_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bf_set_ui(r, 1);\n            return 0;\n        }\n    }\n\n    /* small argument case: result = 1+r(x) with r(x) = -x^2/2 +\n       O(X^4). We assume r(x) < 2^(2*EXP(x) - 1). */\n    if (a->expn < 0) {\n        slimb_t e;\n        e = 2 * a->expn - 1;\n        if (e < -(prec + 2)) {\n            bf_set_ui(r, 1);\n            return bf_add_epsilon(r, r, e, 1, prec, flags);\n        }\n    }\n    \n    return bf_ziv_rounding(r, a, prec, flags, bf_cos_internal, NULL);\n}\n\nstatic int bf_sin_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)\n{\n    return bf_sincos(r, NULL, a, prec);\n}\n\nint bf_sin(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF) {\n            bf_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bf_set_zero(r, a->sign);\n            return 0;\n        }\n    }\n\n    /* small argument case: result = x+r(x) with r(x) = -x^3/6 +\n       O(X^5). We assume r(x) < 2^(3*EXP(x) - 2). */\n    if (a->expn < 0) {\n        slimb_t e;\n        e = sat_add(2 * a->expn, a->expn - 2);\n        if (e < a->expn - bf_max(prec + 2, a->len * LIMB_BITS + 2)) {\n            bf_set(r, a);\n            return bf_add_epsilon(r, r, e, 1 - a->sign, prec, flags);\n        }\n    }\n\n    return bf_ziv_rounding(r, a, prec, flags, bf_sin_internal, NULL);\n}\n\nstatic int bf_tan_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    limb_t prec1;\n    \n    /* XXX: precision analysis */\n    prec1 = prec + 8;\n    bf_init(s, T);\n    bf_sincos(r, T, a, prec1);\n    bf_div(r, r, T, prec1, BF_RNDF);\n    bf_delete(T);\n    return BF_ST_INEXACT;\n}\n\nint bf_tan(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    assert(r != a);\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF) {\n            bf_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bf_set_zero(r, a->sign);\n            return 0;\n        }\n    }\n\n    /* small argument case: result = x+r(x) with r(x) = x^3/3 +\n       O(X^5). We assume r(x) < 2^(3*EXP(x) - 1). */\n    if (a->expn < 0) {\n        slimb_t e;\n        e = sat_add(2 * a->expn, a->expn - 1);\n        if (e < a->expn - bf_max(prec + 2, a->len * LIMB_BITS + 2)) {\n            bf_set(r, a);\n            return bf_add_epsilon(r, r, e, a->sign, prec, flags);\n        }\n    }\n            \n    return bf_ziv_rounding(r, a, prec, flags, bf_tan_internal, NULL);\n}\n\n/* if add_pi2 is true, add pi/2 to the result (used for acos(x) to\n   avoid cancellation) */\nstatic int bf_atan_internal(bf_t *r, const bf_t *a, limb_t prec,\n                            void *opaque)\n{\n    bf_context_t *s = r->ctx;\n    BOOL add_pi2 = (BOOL)(intptr_t)opaque;\n    bf_t T_s, *T = &T_s;\n    bf_t U_s, *U = &U_s;\n    bf_t V_s, *V = &V_s;\n    bf_t X2_s, *X2 = &X2_s;\n    int cmp_1;\n    slimb_t prec1, i, K, l;\n    \n    /* XXX: precision analysis */\n    K = bf_isqrt((prec + 1) / 2);\n    l = prec / (2 * K) + 1;\n    prec1 = prec + K + 2 * l + 32;\n    //    printf(\"prec=%d K=%d l=%d prec1=%d\\n\", (int)prec, (int)K, (int)l, (int)prec1);\n    \n    bf_init(s, T);\n    cmp_1 = (a->expn >= 1); /* a >= 1 */\n    if (cmp_1) {\n        bf_set_ui(T, 1);\n        bf_div(T, T, a, prec1, BF_RNDN);\n    } else {\n        bf_set(T, a);\n    }\n\n    /* abs(T) <= 1 */\n\n    /* argument reduction */\n\n    bf_init(s, U);\n    bf_init(s, V);\n    bf_init(s, X2);\n    for(i = 0; i < K; i++) {\n        /* T = T / (1 + sqrt(1 + T^2)) */\n        bf_mul(U, T, T, prec1, BF_RNDN);\n        bf_add_si(U, U, 1, prec1, BF_RNDN);\n        bf_sqrt(V, U, prec1, BF_RNDN);\n        bf_add_si(V, V, 1, prec1, BF_RNDN);\n        bf_div(T, T, V, prec1, BF_RNDN);\n    }\n\n    /* Taylor series: \n       x - x^3/3 + ... + (-1)^ l * y^(2*l + 1) / (2*l+1) \n    */\n    bf_mul(X2, T, T, prec1, BF_RNDN);\n    bf_set_ui(r, 0);\n    for(i = l; i >= 1; i--) {\n        bf_set_si(U, 1);\n        bf_set_ui(V, 2 * i + 1);\n        bf_div(U, U, V, prec1, BF_RNDN);\n        bf_neg(r);\n        bf_add(r, r, U, prec1, BF_RNDN);\n        bf_mul(r, r, X2, prec1, BF_RNDN);\n    }\n    bf_neg(r);\n    bf_add_si(r, r, 1, prec1, BF_RNDN);\n    bf_mul(r, r, T, prec1, BF_RNDN);\n\n    /* undo the argument reduction */\n    bf_mul_2exp(r, K, BF_PREC_INF, BF_RNDZ);\n    \n    bf_delete(U);\n    bf_delete(V);\n    bf_delete(X2);\n\n    i = add_pi2;\n    if (cmp_1 > 0) {\n        /* undo the inversion : r = sign(a)*PI/2 - r */\n        bf_neg(r);\n        i += 1 - 2 * a->sign;\n    }\n    /* add i*(pi/2) with -1 <= i <= 2 */\n    if (i != 0) {\n        bf_const_pi(T, prec1, BF_RNDF);\n        if (i != 2)\n            bf_mul_2exp(T, -1, BF_PREC_INF, BF_RNDZ);\n        T->sign = (i < 0);\n        bf_add(r, T, r, prec1, BF_RNDN);\n    }\n    \n    bf_delete(T);\n    return BF_ST_INEXACT;\n}\n\nint bf_atan(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    int res;\n    \n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF)  {\n            /* -PI/2 or PI/2 */\n            bf_const_pi_signed(r, a->sign, prec, flags);\n            bf_mul_2exp(r, -1, BF_PREC_INF, BF_RNDZ);\n            return BF_ST_INEXACT;\n        } else {\n            bf_set_zero(r, a->sign);\n            return 0;\n        }\n    }\n    \n    bf_init(s, T);\n    bf_set_ui(T, 1);\n    res = bf_cmpu(a, T);\n    bf_delete(T);\n    if (res == 0) {\n        /* short cut: abs(a) == 1 -> +/-pi/4 */\n        bf_const_pi_signed(r, a->sign, prec, flags);\n        bf_mul_2exp(r, -2, BF_PREC_INF, BF_RNDZ);\n        return BF_ST_INEXACT;\n    }\n\n    /* small argument case: result = x+r(x) with r(x) = -x^3/3 +\n       O(X^5). We assume r(x) < 2^(3*EXP(x) - 1). */\n    if (a->expn < 0) {\n        slimb_t e;\n        e = sat_add(2 * a->expn, a->expn - 1);\n        if (e < a->expn - bf_max(prec + 2, a->len * LIMB_BITS + 2)) {\n            bf_set(r, a);\n            return bf_add_epsilon(r, r, e, 1 - a->sign, prec, flags);\n        }\n    }\n    \n    return bf_ziv_rounding(r, a, prec, flags, bf_atan_internal, (void *)FALSE);\n}\n\nstatic int bf_atan2_internal(bf_t *r, const bf_t *y, limb_t prec, void *opaque)\n{\n    bf_context_t *s = r->ctx;\n    const bf_t *x = opaque;\n    bf_t T_s, *T = &T_s;\n    limb_t prec1;\n    int ret;\n    \n    if (y->expn == BF_EXP_NAN || x->expn == BF_EXP_NAN) {\n        bf_set_nan(r);\n        return 0;\n    }\n\n    /* compute atan(y/x) assumming inf/inf = 1 and 0/0 = 0 */\n    bf_init(s, T);\n    prec1 = prec + 32;\n    if (y->expn == BF_EXP_INF && x->expn == BF_EXP_INF) {\n        bf_set_ui(T, 1);\n        T->sign = y->sign ^ x->sign;\n    } else if (y->expn == BF_EXP_ZERO && x->expn == BF_EXP_ZERO) {\n        bf_set_zero(T, y->sign ^ x->sign);\n    } else {\n        bf_div(T, y, x, prec1, BF_RNDF);\n    }\n    ret = bf_atan(r, T, prec1, BF_RNDF);\n\n    if (x->sign) {\n        /* if x < 0 (it includes -0), return sign(y)*pi + atan(y/x) */\n        bf_const_pi(T, prec1, BF_RNDF);\n        T->sign = y->sign;\n        bf_add(r, r, T, prec1, BF_RNDN);\n        ret |= BF_ST_INEXACT;\n    }\n\n    bf_delete(T);\n    return ret;\n}\n\nint bf_atan2(bf_t *r, const bf_t *y, const bf_t *x,\n             limb_t prec, bf_flags_t flags)\n{\n    return bf_ziv_rounding(r, y, prec, flags, bf_atan2_internal, (void *)x);\n}\n\nstatic int bf_asin_internal(bf_t *r, const bf_t *a, limb_t prec, void *opaque)\n{\n    bf_context_t *s = r->ctx;\n    BOOL is_acos = (BOOL)(intptr_t)opaque;\n    bf_t T_s, *T = &T_s;\n    limb_t prec1, prec2;\n    \n    /* asin(x) = atan(x/sqrt(1-x^2)) \n       acos(x) = pi/2 - asin(x) */\n    prec1 = prec + 8;\n    /* increase the precision in x^2 to compensate the cancellation in\n       (1-x^2) if x is close to 1 */\n    /* XXX: use less precision when possible */\n    if (a->expn >= 0)\n        prec2 = BF_PREC_INF;\n    else\n        prec2 = prec1;\n    bf_init(s, T);\n    bf_mul(T, a, a, prec2, BF_RNDN);\n    bf_neg(T);\n    bf_add_si(T, T, 1, prec2, BF_RNDN);\n\n    bf_sqrt(r, T, prec1, BF_RNDN);\n    bf_div(T, a, r, prec1, BF_RNDN);\n    if (is_acos)\n        bf_neg(T);\n    bf_atan_internal(r, T, prec1, (void *)(intptr_t)is_acos);\n    bf_delete(T);\n    return BF_ST_INEXACT;\n}\n\nint bf_asin(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    int res;\n\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF) {\n            bf_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bf_set_zero(r, a->sign);\n            return 0;\n        }\n    }\n    bf_init(s, T);\n    bf_set_ui(T, 1);\n    res = bf_cmpu(a, T);\n    bf_delete(T);\n    if (res > 0) {\n        bf_set_nan(r);\n        return BF_ST_INVALID_OP;\n    }\n    \n    /* small argument case: result = x+r(x) with r(x) = x^3/6 +\n       O(X^5). We assume r(x) < 2^(3*EXP(x) - 2). */\n    if (a->expn < 0) {\n        slimb_t e;\n        e = sat_add(2 * a->expn, a->expn - 2);\n        if (e < a->expn - bf_max(prec + 2, a->len * LIMB_BITS + 2)) {\n            bf_set(r, a);\n            return bf_add_epsilon(r, r, e, a->sign, prec, flags);\n        }\n    }\n\n    return bf_ziv_rounding(r, a, prec, flags, bf_asin_internal, (void *)FALSE);\n}\n\nint bf_acos(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = r->ctx;\n    bf_t T_s, *T = &T_s;\n    int res;\n\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bf_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF) {\n            bf_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bf_const_pi(r, prec, flags);\n            bf_mul_2exp(r, -1, BF_PREC_INF, BF_RNDZ);\n            return BF_ST_INEXACT;\n        }\n    }\n    bf_init(s, T);\n    bf_set_ui(T, 1);\n    res = bf_cmpu(a, T);\n    bf_delete(T);\n    if (res > 0) {\n        bf_set_nan(r);\n        return BF_ST_INVALID_OP;\n    } else if (res == 0 && a->sign == 0) {\n        bf_set_zero(r, 0);\n        return 0;\n    }\n    \n    return bf_ziv_rounding(r, a, prec, flags, bf_asin_internal, (void *)TRUE);\n}\n\n/***************************************************************/\n/* decimal floating point numbers */\n\n#ifdef USE_BF_DEC\n\n#define adddq(r1, r0, a1, a0)                   \\\n    do {                                        \\\n        limb_t __t = r0;                        \\\n        r0 += (a0);                             \\\n        r1 += (a1) + (r0 < __t);                \\\n    } while (0)\n\n#define subdq(r1, r0, a1, a0)                   \\\n    do {                                        \\\n        limb_t __t = r0;                        \\\n        r0 -= (a0);                             \\\n        r1 -= (a1) + (r0 > __t);                \\\n    } while (0)\n\n#if LIMB_BITS == 64\n\n/* Note: we assume __int128 is available */\n#define muldq(r1, r0, a, b)                     \\\n    do {                                        \\\n        unsigned __int128 __t;                          \\\n        __t = (unsigned __int128)(a) * (unsigned __int128)(b);  \\\n        r0 = __t;                               \\\n        r1 = __t >> 64;                         \\\n    } while (0)\n\n#define divdq(q, r, a1, a0, b)                  \\\n    do {                                        \\\n        unsigned __int128 __t;                  \\\n        limb_t __b = (b);                       \\\n        __t = ((unsigned __int128)(a1) << 64) | (a0);   \\\n        q = __t / __b;                                  \\\n        r = __t % __b;                                  \\\n    } while (0)\n\n#else\n\n#define muldq(r1, r0, a, b)                     \\\n    do {                                        \\\n        uint64_t __t;                          \\\n        __t = (uint64_t)(a) * (uint64_t)(b);  \\\n        r0 = __t;                               \\\n        r1 = __t >> 32;                         \\\n    } while (0)\n\n#define divdq(q, r, a1, a0, b)                  \\\n    do {                                        \\\n        uint64_t __t;                  \\\n        limb_t __b = (b);                       \\\n        __t = ((uint64_t)(a1) << 32) | (a0);   \\\n        q = __t / __b;                                  \\\n        r = __t % __b;                                  \\\n    } while (0)\n\n#endif /* LIMB_BITS != 64 */\n\nstatic inline __maybe_unused limb_t shrd(limb_t low, limb_t high, long shift)\n{\n    if (shift != 0)\n        low = (low >> shift) | (high << (LIMB_BITS - shift));\n    return low;\n}\n\nstatic inline __maybe_unused limb_t shld(limb_t a1, limb_t a0, long shift)\n{\n    if (shift != 0)\n        return (a1 << shift) | (a0 >> (LIMB_BITS - shift));\n    else\n        return a1;\n}\n\n#if LIMB_DIGITS == 19\n\n/* WARNING: hardcoded for b = 1e19. It is assumed that:\n   0 <= a1 < 2^63 */\n#define divdq_base(q, r, a1, a0)\\\ndo {\\\n    uint64_t __a0, __a1, __t0, __t1, __b = BF_DEC_BASE; \\\n    __a0 = a0;\\\n    __a1 = a1;\\\n    __t0 = __a1;\\\n    __t0 = shld(__t0, __a0, 1);\\\n    muldq(q, __t1, __t0, UINT64_C(17014118346046923173)); \\\n    muldq(__t1, __t0, q, __b);\\\n    subdq(__a1, __a0, __t1, __t0);\\\n    subdq(__a1, __a0, 1, __b * 2);    \\\n    __t0 = (slimb_t)__a1 >> 1; \\\n    q += 2 + __t0;\\\n    adddq(__a1, __a0, 0, __b & __t0);\\\n    q += __a1;                  \\\n    __a0 += __b & __a1;           \\\n    r = __a0;\\\n} while(0)\n\n#elif LIMB_DIGITS == 9\n\n/* WARNING: hardcoded for b = 1e9. It is assumed that:\n   0 <= a1 < 2^29 */\n#define divdq_base(q, r, a1, a0)\\\ndo {\\\n    uint32_t __t0, __t1, __b = BF_DEC_BASE; \\\n    __t0 = a1;\\\n    __t1 = a0;\\\n    __t0 = (__t0 << 3) | (__t1 >> (32 - 3));    \\\n    muldq(q, __t1, __t0, 2305843009U);\\\n    r = a0 - q * __b;\\\n    __t1 = (r >= __b);\\\n    q += __t1;\\\n    if (__t1)\\\n        r -= __b;\\\n} while(0)\n\n#endif\n\n/* fast integer division by a fixed constant */\n\ntypedef struct FastDivData {\n    limb_t m1; /* multiplier */\n    int8_t shift1;\n    int8_t shift2;\n} FastDivData;\n\n/* From \"Division by Invariant Integers using Multiplication\" by\n   Torborn Granlund and Peter L. Montgomery */\n/* d must be != 0 */\nstatic inline __maybe_unused void fast_udiv_init(FastDivData *s, limb_t d)\n{\n    int l;\n    limb_t q, r, m1;\n    if (d == 1)\n        l = 0;\n    else\n        l = 64 - clz64(d - 1);\n    divdq(q, r, ((limb_t)1 << l) - d, 0, d);\n    (void)r;\n    m1 = q + 1;\n    //    printf(\"d=%lu l=%d m1=0x%016lx\\n\", d, l, m1);\n    s->m1 = m1;\n    s->shift1 = l;\n    if (s->shift1 > 1)\n        s->shift1 = 1;\n    s->shift2 = l - 1;\n    if (s->shift2 < 0)\n        s->shift2 = 0;\n}\n\nstatic inline limb_t fast_udiv(limb_t a, const FastDivData *s)\n{\n    limb_t t0, t1;\n    muldq(t1, t0, s->m1, a);\n    t0 = (a - t1) >> s->shift1;\n    return (t1 + t0) >> s->shift2;\n}\n\n/* contains 10^i */\nconst limb_t mp_pow_dec[LIMB_DIGITS + 1] = {\n    1U,\n    10U,\n    100U,\n    1000U,\n    10000U,\n    100000U,\n    1000000U,\n    10000000U,\n    100000000U,\n    1000000000U,\n#if LIMB_BITS == 64\n    10000000000U,\n    100000000000U,\n    1000000000000U,\n    10000000000000U,\n    100000000000000U,\n    1000000000000000U,\n    10000000000000000U,\n    100000000000000000U,\n    1000000000000000000U,\n    10000000000000000000U,\n#endif\n};\n\n/* precomputed from fast_udiv_init(10^i) */\nstatic const FastDivData mp_pow_div[LIMB_DIGITS + 1] = {\n#if LIMB_BITS == 32\n    { 0x00000001, 0, 0 },\n    { 0x9999999a, 1, 3 },\n    { 0x47ae147b, 1, 6 },\n    { 0x0624dd30, 1, 9 },\n    { 0xa36e2eb2, 1, 13 },\n    { 0x4f8b588f, 1, 16 },\n    { 0x0c6f7a0c, 1, 19 },\n    { 0xad7f29ac, 1, 23 },\n    { 0x5798ee24, 1, 26 },\n    { 0x12e0be83, 1, 29 },\n#else\n    { 0x0000000000000001, 0, 0 },\n    { 0x999999999999999a, 1, 3 },\n    { 0x47ae147ae147ae15, 1, 6 },\n    { 0x0624dd2f1a9fbe77, 1, 9 },\n    { 0xa36e2eb1c432ca58, 1, 13 },\n    { 0x4f8b588e368f0847, 1, 16 },\n    { 0x0c6f7a0b5ed8d36c, 1, 19 },\n    { 0xad7f29abcaf48579, 1, 23 },\n    { 0x5798ee2308c39dfa, 1, 26 },\n    { 0x12e0be826d694b2f, 1, 29 },\n    { 0xb7cdfd9d7bdbab7e, 1, 33 },\n    { 0x5fd7fe17964955fe, 1, 36 },\n    { 0x19799812dea11198, 1, 39 },\n    { 0xc25c268497681c27, 1, 43 },\n    { 0x6849b86a12b9b01f, 1, 46 },\n    { 0x203af9ee756159b3, 1, 49 },\n    { 0xcd2b297d889bc2b7, 1, 53 },\n    { 0x70ef54646d496893, 1, 56 },\n    { 0x2725dd1d243aba0f, 1, 59 },\n    { 0xd83c94fb6d2ac34d, 1, 63 },\n#endif\n};\n\n/* divide by 10^shift with 0 <= shift <= LIMB_DIGITS */\nstatic inline limb_t fast_shr_dec(limb_t a, int shift)\n{\n    return fast_udiv(a, &mp_pow_div[shift]);\n}\n\n/* division and remainder by 10^shift */\n#define fast_shr_rem_dec(q, r, a, shift) q = fast_shr_dec(a, shift), r = a - q * mp_pow_dec[shift]\n    \nlimb_t mp_add_dec(limb_t *res, const limb_t *op1, const limb_t *op2, \n                  mp_size_t n, limb_t carry)\n{\n    limb_t base = BF_DEC_BASE;\n    mp_size_t i;\n    limb_t k, a, v;\n\n    k=carry;\n    for(i=0;i<n;i++) {\n        /* XXX: reuse the trick in add_mod */\n        v = op1[i];\n        a = v + op2[i] + k - base;\n        k = a <= v;\n        if (!k) \n            a += base;\n        res[i]=a;\n    }\n    return k;\n}\n\nlimb_t mp_add_ui_dec(limb_t *tab, limb_t b, mp_size_t n)\n{\n    limb_t base = BF_DEC_BASE;\n    mp_size_t i;\n    limb_t k, a, v;\n\n    k=b;\n    for(i=0;i<n;i++) {\n        v = tab[i];\n        a = v + k - base;\n        k = a <= v;\n        if (!k) \n            a += base;\n        tab[i] = a;\n        if (k == 0)\n            break;\n    }\n    return k;\n}\n\nlimb_t mp_sub_dec(limb_t *res, const limb_t *op1, const limb_t *op2, \n                  mp_size_t n, limb_t carry)\n{\n    limb_t base = BF_DEC_BASE;\n    mp_size_t i;\n    limb_t k, v, a;\n\n    k=carry;\n    for(i=0;i<n;i++) {\n        v = op1[i];\n        a = v - op2[i] - k;\n        k = a > v;\n        if (k)\n            a += base;\n        res[i] = a;\n    }\n    return k;\n}\n\nlimb_t mp_sub_ui_dec(limb_t *tab, limb_t b, mp_size_t n)\n{\n    limb_t base = BF_DEC_BASE;\n    mp_size_t i;\n    limb_t k, v, a;\n    \n    k=b;\n    for(i=0;i<n;i++) {\n        v = tab[i];\n        a = v - k;\n        k = a > v;\n        if (k)\n            a += base;\n        tab[i]=a;\n        if (k == 0)\n            break;\n    }\n    return k;\n}\n\n/* taba[] = taba[] * b + l. 0 <= b, l <= base - 1. Return the high carry */\nlimb_t mp_mul1_dec(limb_t *tabr, const limb_t *taba, mp_size_t n, \n                   limb_t b, limb_t l)\n{\n    mp_size_t i;\n    limb_t t0, t1, r;\n\n    for(i = 0; i < n; i++) {\n        muldq(t1, t0, taba[i], b);\n        adddq(t1, t0, 0, l);\n        divdq_base(l, r, t1, t0);\n        tabr[i] = r;\n    }\n    return l;\n}\n\n/* tabr[] += taba[] * b. 0 <= b <= base - 1. Return the value to add\n   to the high word */\nlimb_t mp_add_mul1_dec(limb_t *tabr, const limb_t *taba, mp_size_t n,\n                       limb_t b)\n{\n    mp_size_t i;\n    limb_t l, t0, t1, r;\n\n    l = 0;\n    for(i = 0; i < n; i++) {\n        muldq(t1, t0, taba[i], b);\n        adddq(t1, t0, 0, l);\n        adddq(t1, t0, 0, tabr[i]);\n        divdq_base(l, r, t1, t0);\n        tabr[i] = r;\n    }\n    return l;\n}\n\n/* tabr[] -= taba[] * b. 0 <= b <= base - 1. Return the value to\n   substract to the high word. */\nlimb_t mp_sub_mul1_dec(limb_t *tabr, const limb_t *taba, mp_size_t n,\n                       limb_t b)\n{\n    limb_t base = BF_DEC_BASE;\n    mp_size_t i;\n    limb_t l, t0, t1, r, a, v, c;\n\n    /* XXX: optimize */\n    l = 0;\n    for(i = 0; i < n; i++) {\n        muldq(t1, t0, taba[i], b);\n        adddq(t1, t0, 0, l);\n        divdq_base(l, r, t1, t0);\n        v = tabr[i];\n        a = v - r;\n        c = a > v;\n        if (c)\n            a += base;\n        /* never bigger than base because r = 0 when l = base - 1 */\n        l += c;\n        tabr[i] = a;\n    }\n    return l;\n}\n\n/* size of the result : op1_size + op2_size. */\nvoid mp_mul_basecase_dec(limb_t *result, \n                         const limb_t *op1, mp_size_t op1_size, \n                         const limb_t *op2, mp_size_t op2_size) \n{\n    mp_size_t i;\n    limb_t r;\n    \n    result[op1_size] = mp_mul1_dec(result, op1, op1_size, op2[0], 0);\n\n    for(i=1;i<op2_size;i++) {\n        r = mp_add_mul1_dec(result + i, op1, op1_size, op2[i]);\n        result[i + op1_size] = r;\n    }\n}\n\n/* taba[] = (taba[] + r*base^na) / b. 0 <= b < base. 0 <= r <\n   b. Return the remainder. */\nlimb_t mp_div1_dec(limb_t *tabr, const limb_t *taba, mp_size_t na, \n                   limb_t b, limb_t r)\n{\n    limb_t base = BF_DEC_BASE;\n    mp_size_t i;\n    limb_t t0, t1, q;\n    int shift;\n\n#if (BF_DEC_BASE % 2) == 0\n    if (b == 2) {\n        limb_t base_div2;\n        /* Note: only works if base is even */\n        base_div2 = base >> 1;\n        if (r)\n            r = base_div2;\n        for(i = na - 1; i >= 0; i--) {\n            t0 = taba[i];\n            tabr[i] = (t0 >> 1) + r;\n            r = 0;\n            if (t0 & 1)\n                r = base_div2;\n        }\n        if (r)\n            r = 1;\n    } else \n#endif\n    if (na >= UDIV1NORM_THRESHOLD) {\n        shift = clz(b);\n        if (shift == 0) {\n            /* normalized case: b >= 2^(LIMB_BITS-1) */\n            limb_t b_inv;\n            b_inv = udiv1norm_init(b);\n            for(i = na - 1; i >= 0; i--) {\n                muldq(t1, t0, r, base);\n                adddq(t1, t0, 0, taba[i]);\n                q = udiv1norm(&r, t1, t0, b, b_inv);\n                tabr[i] = q;\n            }\n        } else {\n            limb_t b_inv;\n            b <<= shift;\n            b_inv = udiv1norm_init(b);\n            for(i = na - 1; i >= 0; i--) {\n                muldq(t1, t0, r, base);\n                adddq(t1, t0, 0, taba[i]);\n                t1 = (t1 << shift) | (t0 >> (LIMB_BITS - shift));\n                t0 <<= shift;\n                q = udiv1norm(&r, t1, t0, b, b_inv);\n                r >>= shift;\n                tabr[i] = q;\n            }\n        }\n    } else {\n        for(i = na - 1; i >= 0; i--) {\n            muldq(t1, t0, r, base);\n            adddq(t1, t0, 0, taba[i]);\n            divdq(q, r, t1, t0, b);\n            tabr[i] = q;\n        }\n    }\n    return r;\n}\n\nstatic __maybe_unused void mp_print_str_dec(const char *str,\n                                       const limb_t *tab, slimb_t n)\n{\n    slimb_t i;\n    printf(\"%s=\", str);\n    for(i = n - 1; i >= 0; i--) {\n        if (i != n - 1)\n            printf(\"_\");\n        printf(\"%0*\" PRIu_LIMB, LIMB_DIGITS, tab[i]);\n    }\n    printf(\"\\n\");\n}\n\nstatic __maybe_unused void mp_print_str_h_dec(const char *str,\n                                              const limb_t *tab, slimb_t n,\n                                              limb_t high)\n{\n    slimb_t i;\n    printf(\"%s=\", str);\n    printf(\"%0*\" PRIu_LIMB, LIMB_DIGITS, high);\n    for(i = n - 1; i >= 0; i--) {\n        printf(\"_\");\n        printf(\"%0*\" PRIu_LIMB, LIMB_DIGITS, tab[i]);\n    }\n    printf(\"\\n\");\n}\n\n//#define DEBUG_DIV_SLOW\n\n#define DIV_STATIC_ALLOC_LEN 16\n\n/* return q = a / b and r = a % b. \n\n   taba[na] must be allocated if tabb1[nb - 1] < B / 2.  tabb1[nb - 1]\n   must be != zero. na must be >= nb. 's' can be NULL if tabb1[nb - 1]\n   >= B / 2.\n\n   The remainder is is returned in taba and contains nb libms. tabq\n   contains na - nb + 1 limbs. No overlap is permitted.\n\n   Running time of the standard method: (na - nb + 1) * nb\n   Return 0 if OK, -1 if memory alloc error\n*/\n/* XXX: optimize */\nstatic int mp_div_dec(bf_context_t *s, limb_t *tabq,\n                      limb_t *taba, mp_size_t na, \n                      const limb_t *tabb1, mp_size_t nb)\n{\n    limb_t base = BF_DEC_BASE;\n    limb_t r, mult, t0, t1, a, c, q, v, *tabb;\n    mp_size_t i, j;\n    limb_t static_tabb[DIV_STATIC_ALLOC_LEN];\n    \n#ifdef DEBUG_DIV_SLOW\n    mp_print_str_dec(\"a\", taba, na);\n    mp_print_str_dec(\"b\", tabb1, nb);\n#endif\n\n    /* normalize tabb */\n    r = tabb1[nb - 1];\n    assert(r != 0);\n    i = na - nb;\n    if (r >= BF_DEC_BASE / 2) {\n        mult = 1;\n        tabb = (limb_t *)tabb1;\n        q = 1;\n        for(j = nb - 1; j >= 0; j--) {\n            if (taba[i + j] != tabb[j]) {\n                if (taba[i + j] < tabb[j])\n                    q = 0;\n                break;\n            }\n        }\n        tabq[i] = q;\n        if (q) {\n            mp_sub_dec(taba + i, taba + i, tabb, nb, 0);\n        }\n        i--;\n    } else {\n        mult = base / (r + 1);\n        if (likely(nb <= DIV_STATIC_ALLOC_LEN)) {\n            tabb = static_tabb;\n        } else {\n            tabb = bf_malloc(s, sizeof(limb_t) * nb);\n            if (!tabb)\n                return -1;\n        }\n        mp_mul1_dec(tabb, tabb1, nb, mult, 0);\n        taba[na] = mp_mul1_dec(taba, taba, na, mult, 0);\n    }\n\n#ifdef DEBUG_DIV_SLOW\n    printf(\"mult=\" FMT_LIMB \"\\n\", mult);\n    mp_print_str_dec(\"a_norm\", taba, na + 1);\n    mp_print_str_dec(\"b_norm\", tabb, nb);\n#endif\n\n    for(; i >= 0; i--) {\n        if (unlikely(taba[i + nb] >= tabb[nb - 1])) {\n            /* XXX: check if it is really possible */\n            q = base - 1;\n        } else {\n            muldq(t1, t0, taba[i + nb], base);\n            adddq(t1, t0, 0, taba[i + nb - 1]);\n            divdq(q, r, t1, t0, tabb[nb - 1]);\n        }\n        //        printf(\"i=%d q1=%ld\\n\", i, q);\n\n        r = mp_sub_mul1_dec(taba + i, tabb, nb, q);\n        //        mp_dump(\"r1\", taba + i, nb, bd);\n        //        printf(\"r2=%ld\\n\", r);\n\n        v = taba[i + nb];\n        a = v - r;\n        c = a > v;\n        if (c)\n            a += base;\n        taba[i + nb] = a;\n\n        if (c != 0) {\n            /* negative result */\n            for(;;) {\n                q--;\n                c = mp_add_dec(taba + i, taba + i, tabb, nb, 0);\n                /* propagate carry and test if positive result */\n                if (c != 0) {\n                    if (++taba[i + nb] == base) {\n                        break;\n                    }\n                }\n            }\n        }\n        tabq[i] = q;\n    }\n\n#ifdef DEBUG_DIV_SLOW\n    mp_print_str_dec(\"q\", tabq, na - nb + 1);\n    mp_print_str_dec(\"r\", taba, nb);\n#endif\n\n    /* remove the normalization */\n    if (mult != 1) {\n        mp_div1_dec(taba, taba, nb, mult, 0);\n        if (unlikely(tabb != static_tabb))\n            bf_free(s, tabb);\n    }\n    return 0;\n}\n\n/* divide by 10^shift */\nstatic limb_t mp_shr_dec(limb_t *tab_r, const limb_t *tab, mp_size_t n, \n                         limb_t shift, limb_t high)\n{\n    mp_size_t i;\n    limb_t l, a, q, r;\n\n    assert(shift >= 1 && shift < LIMB_DIGITS);\n    l = high;\n    for(i = n - 1; i >= 0; i--) {\n        a = tab[i];\n        fast_shr_rem_dec(q, r, a, shift);\n        tab_r[i] = q + l * mp_pow_dec[LIMB_DIGITS - shift];\n        l = r;\n    }\n    return l;\n}\n\n/* multiply by 10^shift */\nstatic limb_t mp_shl_dec(limb_t *tab_r, const limb_t *tab, mp_size_t n, \n                         limb_t shift, limb_t low)\n{\n    mp_size_t i;\n    limb_t l, a, q, r;\n\n    assert(shift >= 1 && shift < LIMB_DIGITS);\n    l = low;\n    for(i = 0; i < n; i++) {\n        a = tab[i];\n        fast_shr_rem_dec(q, r, a, LIMB_DIGITS - shift);\n        tab_r[i] = r * mp_pow_dec[shift] + l;\n        l = q;\n    }\n    return l;\n}\n\nstatic limb_t mp_sqrtrem2_dec(limb_t *tabs, limb_t *taba)\n{\n    int k;\n    dlimb_t a, b, r;\n    limb_t taba1[2], s, r0, r1;\n\n    /* convert to binary and normalize */\n    a = (dlimb_t)taba[1] * BF_DEC_BASE + taba[0];\n    k = clz(a >> LIMB_BITS) & ~1;\n    b = a << k;\n    taba1[0] = b;\n    taba1[1] = b >> LIMB_BITS;\n    mp_sqrtrem2(&s, taba1);\n    s >>= (k >> 1);\n    /* convert the remainder back to decimal */\n    r = a - (dlimb_t)s * (dlimb_t)s;\n    divdq_base(r1, r0, r >> LIMB_BITS, r);\n    taba[0] = r0;\n    tabs[0] = s;\n    return r1;\n}\n\n//#define DEBUG_SQRTREM_DEC\n\n/* tmp_buf must contain (n / 2 + 1 limbs) */\nstatic limb_t mp_sqrtrem_rec_dec(limb_t *tabs, limb_t *taba, limb_t n,\n                                 limb_t *tmp_buf)\n{\n    limb_t l, h, rh, ql, qh, c, i;\n    \n    if (n == 1)\n        return mp_sqrtrem2_dec(tabs, taba);\n#ifdef DEBUG_SQRTREM_DEC\n    mp_print_str_dec(\"a\", taba, 2 * n);\n#endif\n    l = n / 2;\n    h = n - l;\n    qh = mp_sqrtrem_rec_dec(tabs + l, taba + 2 * l, h, tmp_buf);\n#ifdef DEBUG_SQRTREM_DEC\n    mp_print_str_dec(\"s1\", tabs + l, h);\n    mp_print_str_h_dec(\"r1\", taba + 2 * l, h, qh);\n    mp_print_str_h_dec(\"r2\", taba + l, n, qh);\n#endif\n    \n    /* the remainder is in taba + 2 * l. Its high bit is in qh */\n    if (qh) {\n        mp_sub_dec(taba + 2 * l, taba + 2 * l, tabs + l, h, 0);\n    }\n    /* instead of dividing by 2*s, divide by s (which is normalized)\n       and update q and r */\n    mp_div_dec(NULL, tmp_buf, taba + l, n, tabs + l, h);\n    qh += tmp_buf[l];\n    for(i = 0; i < l; i++)\n        tabs[i] = tmp_buf[i];\n    ql = mp_div1_dec(tabs, tabs, l, 2, qh & 1);\n    qh = qh >> 1; /* 0 or 1 */\n    if (ql)\n        rh = mp_add_dec(taba + l, taba + l, tabs + l, h, 0);\n    else\n        rh = 0;\n#ifdef DEBUG_SQRTREM_DEC\n    mp_print_str_h_dec(\"q\", tabs, l, qh);\n    mp_print_str_h_dec(\"u\", taba + l, h, rh);\n#endif\n    \n    mp_add_ui_dec(tabs + l, qh, h);\n#ifdef DEBUG_SQRTREM_DEC\n    mp_print_str_dec(\"s2\", tabs, n);\n#endif\n    \n    /* q = qh, tabs[l - 1 ... 0], r = taba[n - 1 ... l] */\n    /* subtract q^2. if qh = 1 then q = B^l, so we can take shortcuts */\n    if (qh) {\n        c = qh;\n    } else {\n        mp_mul_basecase_dec(taba + n, tabs, l, tabs, l);\n        c = mp_sub_dec(taba, taba, taba + n, 2 * l, 0);\n    }\n    rh -= mp_sub_ui_dec(taba + 2 * l, c, n - 2 * l);\n    if ((slimb_t)rh < 0) {\n        mp_sub_ui_dec(tabs, 1, n);\n        rh += mp_add_mul1_dec(taba, tabs, n, 2);\n        rh += mp_add_ui_dec(taba, 1, n);\n    }\n    return rh;\n}\n\n/* 'taba' has 2*n limbs with n >= 1 and taba[2*n-1] >= B/4. Return (s,\n   r) with s=floor(sqrt(a)) and r=a-s^2. 0 <= r <= 2 * s. tabs has n\n   limbs. r is returned in the lower n limbs of taba. Its r[n] is the\n   returned value of the function. */\nint mp_sqrtrem_dec(bf_context_t *s, limb_t *tabs, limb_t *taba, limb_t n)\n{\n    limb_t tmp_buf1[8];\n    limb_t *tmp_buf;\n    mp_size_t n2;\n    n2 = n / 2 + 1;\n    if (n2 <= countof(tmp_buf1)) {\n        tmp_buf = tmp_buf1;\n    } else {\n        tmp_buf = bf_malloc(s, sizeof(limb_t) * n2);\n        if (!tmp_buf)\n            return -1;\n    }\n    taba[n] = mp_sqrtrem_rec_dec(tabs, taba, n, tmp_buf);\n    if (tmp_buf != tmp_buf1)\n        bf_free(s, tmp_buf);\n    return 0;\n}\n\n/* return the number of leading zero digits, from 0 to LIMB_DIGITS */\nstatic int clz_dec(limb_t a)\n{\n    if (a == 0)\n        return LIMB_DIGITS;\n    switch(LIMB_BITS - 1 - clz(a)) {\n    case 0: /* 1-1 */\n        return LIMB_DIGITS - 1;\n    case 1: /* 2-3 */\n        return LIMB_DIGITS - 1;\n    case 2: /* 4-7 */\n        return LIMB_DIGITS - 1;\n    case 3: /* 8-15 */\n        if (a < 10)\n            return LIMB_DIGITS - 1;\n        else\n            return LIMB_DIGITS - 2;\n    case 4: /* 16-31 */\n        return LIMB_DIGITS - 2;\n    case 5: /* 32-63 */\n        return LIMB_DIGITS - 2;\n    case 6: /* 64-127 */\n        if (a < 100)\n            return LIMB_DIGITS - 2;\n        else\n            return LIMB_DIGITS - 3;\n    case 7: /* 128-255 */\n        return LIMB_DIGITS - 3;\n    case 8: /* 256-511 */\n        return LIMB_DIGITS - 3;\n    case 9: /* 512-1023 */\n        if (a < 1000)\n            return LIMB_DIGITS - 3;\n        else\n            return LIMB_DIGITS - 4;\n    case 10: /* 1024-2047 */\n        return LIMB_DIGITS - 4;\n    case 11: /* 2048-4095 */\n        return LIMB_DIGITS - 4;\n    case 12: /* 4096-8191 */\n        return LIMB_DIGITS - 4;\n    case 13: /* 8192-16383 */\n        if (a < 10000)\n            return LIMB_DIGITS - 4;\n        else\n            return LIMB_DIGITS - 5;\n    case 14: /* 16384-32767 */\n        return LIMB_DIGITS - 5;\n    case 15: /* 32768-65535 */\n        return LIMB_DIGITS - 5;\n    case 16: /* 65536-131071 */\n        if (a < 100000)\n            return LIMB_DIGITS - 5;\n        else\n            return LIMB_DIGITS - 6;\n    case 17: /* 131072-262143 */\n        return LIMB_DIGITS - 6;\n    case 18: /* 262144-524287 */\n        return LIMB_DIGITS - 6;\n    case 19: /* 524288-1048575 */\n        if (a < 1000000)\n            return LIMB_DIGITS - 6;\n        else\n            return LIMB_DIGITS - 7;\n    case 20: /* 1048576-2097151 */\n        return LIMB_DIGITS - 7;\n    case 21: /* 2097152-4194303 */\n        return LIMB_DIGITS - 7;\n    case 22: /* 4194304-8388607 */\n        return LIMB_DIGITS - 7;\n    case 23: /* 8388608-16777215 */\n        if (a < 10000000)\n            return LIMB_DIGITS - 7;\n        else\n            return LIMB_DIGITS - 8;\n    case 24: /* 16777216-33554431 */\n        return LIMB_DIGITS - 8;\n    case 25: /* 33554432-67108863 */\n        return LIMB_DIGITS - 8;\n    case 26: /* 67108864-134217727 */\n        if (a < 100000000)\n            return LIMB_DIGITS - 8;\n        else\n            return LIMB_DIGITS - 9;\n#if LIMB_BITS == 64\n    case 27: /* 134217728-268435455 */\n        return LIMB_DIGITS - 9;\n    case 28: /* 268435456-536870911 */\n        return LIMB_DIGITS - 9;\n    case 29: /* 536870912-1073741823 */\n        if (a < 1000000000)\n            return LIMB_DIGITS - 9;\n        else\n            return LIMB_DIGITS - 10;\n    case 30: /* 1073741824-2147483647 */\n        return LIMB_DIGITS - 10;\n    case 31: /* 2147483648-4294967295 */\n        return LIMB_DIGITS - 10;\n    case 32: /* 4294967296-8589934591 */\n        return LIMB_DIGITS - 10;\n    case 33: /* 8589934592-17179869183 */\n        if (a < 10000000000)\n            return LIMB_DIGITS - 10;\n        else\n            return LIMB_DIGITS - 11;\n    case 34: /* 17179869184-34359738367 */\n        return LIMB_DIGITS - 11;\n    case 35: /* 34359738368-68719476735 */\n        return LIMB_DIGITS - 11;\n    case 36: /* 68719476736-137438953471 */\n        if (a < 100000000000)\n            return LIMB_DIGITS - 11;\n        else\n            return LIMB_DIGITS - 12;\n    case 37: /* 137438953472-274877906943 */\n        return LIMB_DIGITS - 12;\n    case 38: /* 274877906944-549755813887 */\n        return LIMB_DIGITS - 12;\n    case 39: /* 549755813888-1099511627775 */\n        if (a < 1000000000000)\n            return LIMB_DIGITS - 12;\n        else\n            return LIMB_DIGITS - 13;\n    case 40: /* 1099511627776-2199023255551 */\n        return LIMB_DIGITS - 13;\n    case 41: /* 2199023255552-4398046511103 */\n        return LIMB_DIGITS - 13;\n    case 42: /* 4398046511104-8796093022207 */\n        return LIMB_DIGITS - 13;\n    case 43: /* 8796093022208-17592186044415 */\n        if (a < 10000000000000)\n            return LIMB_DIGITS - 13;\n        else\n            return LIMB_DIGITS - 14;\n    case 44: /* 17592186044416-35184372088831 */\n        return LIMB_DIGITS - 14;\n    case 45: /* 35184372088832-70368744177663 */\n        return LIMB_DIGITS - 14;\n    case 46: /* 70368744177664-140737488355327 */\n        if (a < 100000000000000)\n            return LIMB_DIGITS - 14;\n        else\n            return LIMB_DIGITS - 15;\n    case 47: /* 140737488355328-281474976710655 */\n        return LIMB_DIGITS - 15;\n    case 48: /* 281474976710656-562949953421311 */\n        return LIMB_DIGITS - 15;\n    case 49: /* 562949953421312-1125899906842623 */\n        if (a < 1000000000000000)\n            return LIMB_DIGITS - 15;\n        else\n            return LIMB_DIGITS - 16;\n    case 50: /* 1125899906842624-2251799813685247 */\n        return LIMB_DIGITS - 16;\n    case 51: /* 2251799813685248-4503599627370495 */\n        return LIMB_DIGITS - 16;\n    case 52: /* 4503599627370496-9007199254740991 */\n        return LIMB_DIGITS - 16;\n    case 53: /* 9007199254740992-18014398509481983 */\n        if (a < 10000000000000000)\n            return LIMB_DIGITS - 16;\n        else\n            return LIMB_DIGITS - 17;\n    case 54: /* 18014398509481984-36028797018963967 */\n        return LIMB_DIGITS - 17;\n    case 55: /* 36028797018963968-72057594037927935 */\n        return LIMB_DIGITS - 17;\n    case 56: /* 72057594037927936-144115188075855871 */\n        if (a < 100000000000000000)\n            return LIMB_DIGITS - 17;\n        else\n            return LIMB_DIGITS - 18;\n    case 57: /* 144115188075855872-288230376151711743 */\n        return LIMB_DIGITS - 18;\n    case 58: /* 288230376151711744-576460752303423487 */\n        return LIMB_DIGITS - 18;\n    case 59: /* 576460752303423488-1152921504606846975 */\n        if (a < 1000000000000000000)\n            return LIMB_DIGITS - 18;\n        else\n            return LIMB_DIGITS - 19;\n#endif\n    default:\n        return 0;\n    }\n}\n\n/* for debugging */\nvoid bfdec_print_str(const char *str, const bfdec_t *a)\n{\n    slimb_t i;\n    printf(\"%s=\", str);\n\n    if (a->expn == BF_EXP_NAN) {\n        printf(\"NaN\");\n    } else {\n        if (a->sign)\n            putchar('-');\n        if (a->expn == BF_EXP_ZERO) {\n            putchar('0');\n        } else if (a->expn == BF_EXP_INF) {\n            printf(\"Inf\");\n        } else {\n            printf(\"0.\");\n            for(i = a->len - 1; i >= 0; i--)\n                printf(\"%0*\" PRIu_LIMB, LIMB_DIGITS, a->tab[i]);\n            printf(\"e%\" PRId_LIMB, a->expn);\n        }\n    }\n    printf(\"\\n\");\n}\n\n/* return != 0 if one digit between 0 and bit_pos inclusive is not zero. */\nstatic inline limb_t scan_digit_nz(const bfdec_t *r, slimb_t bit_pos)\n{\n    slimb_t pos;\n    limb_t v, q;\n    int shift;\n\n    if (bit_pos < 0)\n        return 0;\n    pos = (limb_t)bit_pos / LIMB_DIGITS;\n    shift = (limb_t)bit_pos % LIMB_DIGITS;\n    fast_shr_rem_dec(q, v, r->tab[pos], shift + 1);\n    (void)q;\n    if (v != 0)\n        return 1;\n    pos--;\n    while (pos >= 0) {\n        if (r->tab[pos] != 0)\n            return 1;\n        pos--;\n    }\n    return 0;\n}\n\nstatic limb_t get_digit(const limb_t *tab, limb_t len, slimb_t pos)\n{\n    slimb_t i;\n    int shift;\n    i = floor_div(pos, LIMB_DIGITS);\n    if (i < 0 || i >= len)\n        return 0;\n    shift = pos - i * LIMB_DIGITS;\n    return fast_shr_dec(tab[i], shift) % 10;\n}\n\n#if 0\nstatic limb_t get_digits(const limb_t *tab, limb_t len, slimb_t pos)\n{\n    limb_t a0, a1;\n    int shift;\n    slimb_t i;\n    \n    i = floor_div(pos, LIMB_DIGITS);\n    shift = pos - i * LIMB_DIGITS;\n    if (i >= 0 && i < len)\n        a0 = tab[i];\n    else\n        a0 = 0;\n    if (shift == 0) {\n        return a0;\n    } else {\n        i++;\n        if (i >= 0 && i < len)\n            a1 = tab[i];\n        else\n            a1 = 0;\n        return fast_shr_dec(a0, shift) +\n            fast_urem(a1, &mp_pow_div[LIMB_DIGITS - shift]) *\n            mp_pow_dec[shift];\n    }\n}\n#endif\n\n/* return the addend for rounding. Note that prec can be <= 0 for bf_rint() */\nstatic int bfdec_get_rnd_add(int *pret, const bfdec_t *r, limb_t l,\n                             slimb_t prec, int rnd_mode)\n{\n    int add_one, inexact;\n    limb_t digit1, digit0;\n    \n    //    bfdec_print_str(\"get_rnd_add\", r);\n    if (rnd_mode == BF_RNDF) {\n        digit0 = 1; /* faithful rounding does not honor the INEXACT flag */\n    } else {\n        /* starting limb for bit 'prec + 1' */\n        digit0 = scan_digit_nz(r, l * LIMB_DIGITS - 1 - bf_max(0, prec + 1));\n    }\n\n    /* get the digit at 'prec' */\n    digit1 = get_digit(r->tab, l, l * LIMB_DIGITS - 1 - prec);\n    inexact = (digit1 | digit0) != 0;\n    \n    add_one = 0;\n    switch(rnd_mode) {\n    case BF_RNDZ:\n        break;\n    case BF_RNDN:\n        if (digit1 == 5) {\n            if (digit0) {\n                add_one = 1;\n            } else {\n                /* round to even */\n                add_one =\n                    get_digit(r->tab, l, l * LIMB_DIGITS - 1 - (prec - 1)) & 1;\n            }\n        } else if (digit1 > 5) {\n            add_one = 1;\n        }\n        break;\n    case BF_RNDD:\n    case BF_RNDU:\n        if (r->sign == (rnd_mode == BF_RNDD))\n            add_one = inexact;\n        break;\n    case BF_RNDNA:\n    case BF_RNDF:\n        add_one = (digit1 >= 5);\n        break;\n    case BF_RNDA:\n        add_one = inexact;\n        break;\n    default:\n        abort();\n    }\n    \n    if (inexact)\n        *pret |= BF_ST_INEXACT;\n    return add_one;\n}\n\n/* round to prec1 bits assuming 'r' is non zero and finite. 'r' is\n   assumed to have length 'l' (1 <= l <= r->len). prec1 can be\n   BF_PREC_INF. BF_FLAG_SUBNORMAL is not supported. Cannot fail with\n   BF_ST_MEM_ERROR.\n */\nstatic int __bfdec_round(bfdec_t *r, limb_t prec1, bf_flags_t flags, limb_t l)\n{\n    int shift, add_one, rnd_mode, ret;\n    slimb_t i, bit_pos, pos, e_min, e_max, e_range, prec;\n\n    /* XXX: align to IEEE 754 2008 for decimal numbers ? */\n    e_range = (limb_t)1 << (bf_get_exp_bits(flags) - 1);\n    e_min = -e_range + 3;\n    e_max = e_range;\n    \n    if (flags & BF_FLAG_RADPNT_PREC) {\n        /* 'prec' is the precision after the decimal point */\n        if (prec1 != BF_PREC_INF)\n            prec = r->expn + prec1;\n        else\n            prec = prec1;\n    } else if (unlikely(r->expn < e_min) && (flags & BF_FLAG_SUBNORMAL)) {\n        /* restrict the precision in case of potentially subnormal\n           result */\n        assert(prec1 != BF_PREC_INF);\n        prec = prec1 - (e_min - r->expn);\n    } else {\n        prec = prec1;\n    }\n    \n    /* round to prec bits */\n    rnd_mode = flags & BF_RND_MASK;\n    ret = 0;\n    add_one = bfdec_get_rnd_add(&ret, r, l, prec, rnd_mode);\n    \n    if (prec <= 0) {\n        if (add_one) {\n            bfdec_resize(r, 1); /* cannot fail because r is non zero */\n            r->tab[0] = BF_DEC_BASE / 10;\n            r->expn += 1 - prec;\n            ret |= BF_ST_UNDERFLOW | BF_ST_INEXACT;\n            return ret;\n        } else {\n            goto underflow;\n        }\n    } else if (add_one) {\n        limb_t carry;\n        \n        /* add one starting at digit 'prec - 1' */\n        bit_pos = l * LIMB_DIGITS - 1 - (prec - 1);\n        pos = bit_pos / LIMB_DIGITS;\n        carry = mp_pow_dec[bit_pos % LIMB_DIGITS];\n        carry = mp_add_ui_dec(r->tab + pos, carry, l - pos);\n        if (carry) {\n            /* shift right by one digit */\n            mp_shr_dec(r->tab + pos, r->tab + pos, l - pos, 1, 1);\n            r->expn++;\n        }\n    }\n    \n    /* check underflow */\n    if (unlikely(r->expn < e_min)) {\n        if (flags & BF_FLAG_SUBNORMAL) {\n            /* if inexact, also set the underflow flag */\n            if (ret & BF_ST_INEXACT)\n                ret |= BF_ST_UNDERFLOW;\n        } else {\n        underflow:\n            bfdec_set_zero(r, r->sign);\n            ret |= BF_ST_UNDERFLOW | BF_ST_INEXACT;\n            return ret;\n        }\n    }\n    \n    /* check overflow */\n    if (unlikely(r->expn > e_max)) {\n        bfdec_set_inf(r, r->sign);\n        ret |= BF_ST_OVERFLOW | BF_ST_INEXACT;\n        return ret;\n    }\n    \n    /* keep the bits starting at 'prec - 1' */\n    bit_pos = l * LIMB_DIGITS - 1 - (prec - 1);\n    i = floor_div(bit_pos, LIMB_DIGITS);\n    if (i >= 0) {\n        shift = smod(bit_pos, LIMB_DIGITS);\n        if (shift != 0) {\n            r->tab[i] = fast_shr_dec(r->tab[i], shift) *\n                mp_pow_dec[shift];\n        }\n    } else {\n        i = 0;\n    }\n    /* remove trailing zeros */\n    while (r->tab[i] == 0)\n        i++;\n    if (i > 0) {\n        l -= i;\n        memmove(r->tab, r->tab + i, l * sizeof(limb_t));\n    }\n    bfdec_resize(r, l); /* cannot fail */\n    return ret;\n}\n\n/* Cannot fail with BF_ST_MEM_ERROR. */\nint bfdec_round(bfdec_t *r, limb_t prec, bf_flags_t flags)\n{\n    if (r->len == 0)\n        return 0;\n    return __bfdec_round(r, prec, flags, r->len);\n}\n\n/* 'r' must be a finite number. Cannot fail with BF_ST_MEM_ERROR.  */\nint bfdec_normalize_and_round(bfdec_t *r, limb_t prec1, bf_flags_t flags)\n{\n    limb_t l, v;\n    int shift, ret;\n    \n    //    bfdec_print_str(\"bf_renorm\", r);\n    l = r->len;\n    while (l > 0 && r->tab[l - 1] == 0)\n        l--;\n    if (l == 0) {\n        /* zero */\n        r->expn = BF_EXP_ZERO;\n        bfdec_resize(r, 0); /* cannot fail */\n        ret = 0;\n    } else {\n        r->expn -= (r->len - l) * LIMB_DIGITS;\n        /* shift to have the MSB set to '1' */\n        v = r->tab[l - 1];\n        shift = clz_dec(v);\n        if (shift != 0) {\n            mp_shl_dec(r->tab, r->tab, l, shift, 0);\n            r->expn -= shift;\n        }\n        ret = __bfdec_round(r, prec1, flags, l);\n    }\n    //    bf_print_str(\"r_final\", r);\n    return ret;\n}\n\nint bfdec_set_ui(bfdec_t *r, uint64_t v)\n{\n#if LIMB_BITS == 32\n    if (v >= BF_DEC_BASE * BF_DEC_BASE) {\n        if (bfdec_resize(r, 3))\n            goto fail;\n        r->tab[0] = v % BF_DEC_BASE;\n        v /= BF_DEC_BASE;\n        r->tab[1] = v % BF_DEC_BASE;\n        r->tab[2] = v / BF_DEC_BASE;\n        r->expn = 3 * LIMB_DIGITS;\n    } else\n#endif\n    if (v >= BF_DEC_BASE) {\n        if (bfdec_resize(r, 2))\n            goto fail;\n        r->tab[0] = v % BF_DEC_BASE;\n        r->tab[1] = v / BF_DEC_BASE;\n        r->expn = 2 * LIMB_DIGITS;\n    } else {\n        if (bfdec_resize(r, 1))\n            goto fail;\n        r->tab[0] = v;\n        r->expn = LIMB_DIGITS;\n    }\n    r->sign = 0;\n    return bfdec_normalize_and_round(r, BF_PREC_INF, 0);\n fail:\n    bfdec_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\nint bfdec_set_si(bfdec_t *r, int64_t v)\n{\n    int ret;\n    if (v < 0) {\n        ret = bfdec_set_ui(r, -v);\n        r->sign = 1;\n    } else {\n        ret = bfdec_set_ui(r, v);\n    }\n    return ret;\n}\n\nstatic int bfdec_add_internal(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec, bf_flags_t flags, int b_neg)\n{\n    bf_context_t *s = r->ctx;\n    int is_sub, cmp_res, a_sign, b_sign, ret;\n\n    a_sign = a->sign;\n    b_sign = b->sign ^ b_neg;\n    is_sub = a_sign ^ b_sign;\n    cmp_res = bfdec_cmpu(a, b);\n    if (cmp_res < 0) {\n        const bfdec_t *tmp;\n        tmp = a;\n        a = b;\n        b = tmp;\n        a_sign = b_sign; /* b_sign is never used later */\n    }\n    /* abs(a) >= abs(b) */\n    if (cmp_res == 0 && is_sub && a->expn < BF_EXP_INF) {\n        /* zero result */\n        bfdec_set_zero(r, (flags & BF_RND_MASK) == BF_RNDD);\n        ret = 0;\n    } else if (a->len == 0 || b->len == 0) {\n        ret = 0;\n        if (a->expn >= BF_EXP_INF) {\n            if (a->expn == BF_EXP_NAN) {\n                /* at least one operand is NaN */\n                bfdec_set_nan(r);\n                ret = 0;\n            } else if (b->expn == BF_EXP_INF && is_sub) {\n                /* infinities with different signs */\n                bfdec_set_nan(r);\n                ret = BF_ST_INVALID_OP;\n            } else {\n                bfdec_set_inf(r, a_sign);\n            }\n        } else {\n            /* at least one zero and not subtract */\n            if (bfdec_set(r, a))\n                return BF_ST_MEM_ERROR;\n            r->sign = a_sign;\n            goto renorm;\n        }\n    } else {\n        slimb_t d, a_offset, b_offset, i, r_len;\n        limb_t carry;\n        limb_t *b1_tab;\n        int b_shift;\n        mp_size_t b1_len;\n        \n        d = a->expn - b->expn;\n\n        /* XXX: not efficient in time and memory if the precision is\n           not infinite */\n        r_len = bf_max(a->len, b->len + (d + LIMB_DIGITS - 1) / LIMB_DIGITS);\n        if (bfdec_resize(r, r_len))\n            goto fail;\n        r->sign = a_sign;\n        r->expn = a->expn;\n\n        a_offset = r_len - a->len;\n        for(i = 0; i < a_offset; i++)\n            r->tab[i] = 0;\n        for(i = 0; i < a->len; i++)\n            r->tab[a_offset + i] = a->tab[i];\n        \n        b_shift = d % LIMB_DIGITS;\n        if (b_shift == 0) {\n            b1_len = b->len;\n            b1_tab = (limb_t *)b->tab;\n        } else {\n            b1_len = b->len + 1;\n            b1_tab = bf_malloc(s, sizeof(limb_t) * b1_len);\n            if (!b1_tab)\n                goto fail;\n            b1_tab[0] = mp_shr_dec(b1_tab + 1, b->tab, b->len, b_shift, 0) *\n                mp_pow_dec[LIMB_DIGITS - b_shift];\n        }\n        b_offset = r_len - (b->len + (d + LIMB_DIGITS - 1) / LIMB_DIGITS);\n        \n        if (is_sub) {\n            carry = mp_sub_dec(r->tab + b_offset, r->tab + b_offset,\n                               b1_tab, b1_len, 0);\n            if (carry != 0) {\n                carry = mp_sub_ui_dec(r->tab + b_offset + b1_len, carry,\n                                      r_len - (b_offset + b1_len));\n                assert(carry == 0);\n            }\n        } else {\n            carry = mp_add_dec(r->tab + b_offset, r->tab + b_offset,\n                               b1_tab, b1_len, 0);\n            if (carry != 0) {\n                carry = mp_add_ui_dec(r->tab + b_offset + b1_len, carry,\n                                      r_len - (b_offset + b1_len));\n            }\n            if (carry != 0) {\n                if (bfdec_resize(r, r_len + 1)) {\n                    if (b_shift != 0)\n                        bf_free(s, b1_tab);\n                    goto fail;\n                }\n                r->tab[r_len] = 1;\n                r->expn += LIMB_DIGITS;\n            }\n        }\n        if (b_shift != 0)\n            bf_free(s, b1_tab);\n    renorm:\n        ret = bfdec_normalize_and_round(r, prec, flags);\n    }\n    return ret;\n fail:\n    bfdec_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\nstatic int __bfdec_add(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n                     bf_flags_t flags)\n{\n    return bfdec_add_internal(r, a, b, prec, flags, 0);\n}\n\nstatic int __bfdec_sub(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n                     bf_flags_t flags)\n{\n    return bfdec_add_internal(r, a, b, prec, flags, 1);\n}\n\nint bfdec_add(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags)\n{\n    return bf_op2((bf_t *)r, (bf_t *)a, (bf_t *)b, prec, flags,\n                  (bf_op2_func_t *)__bfdec_add);\n}\n\nint bfdec_sub(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags)\n{\n    return bf_op2((bf_t *)r, (bf_t *)a, (bf_t *)b, prec, flags,\n                  (bf_op2_func_t *)__bfdec_sub);\n}\n\nint bfdec_mul(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags)\n{\n    int ret, r_sign;\n\n    if (a->len < b->len) {\n        const bfdec_t *tmp = a;\n        a = b;\n        b = tmp;\n    }\n    r_sign = a->sign ^ b->sign;\n    /* here b->len <= a->len */\n    if (b->len == 0) {\n        if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {\n            bfdec_set_nan(r);\n            ret = 0;\n        } else if (a->expn == BF_EXP_INF || b->expn == BF_EXP_INF) {\n            if ((a->expn == BF_EXP_INF && b->expn == BF_EXP_ZERO) ||\n                (a->expn == BF_EXP_ZERO && b->expn == BF_EXP_INF)) {\n                bfdec_set_nan(r);\n                ret = BF_ST_INVALID_OP;\n            } else {\n                bfdec_set_inf(r, r_sign);\n                ret = 0;\n            }\n        } else {\n            bfdec_set_zero(r, r_sign);\n            ret = 0;\n        }\n    } else {\n        bfdec_t tmp, *r1 = NULL;\n        limb_t a_len, b_len;\n        limb_t *a_tab, *b_tab;\n            \n        a_len = a->len;\n        b_len = b->len;\n        a_tab = a->tab;\n        b_tab = b->tab;\n        \n        if (r == a || r == b) {\n            bfdec_init(r->ctx, &tmp);\n            r1 = r;\n            r = &tmp;\n        }\n        if (bfdec_resize(r, a_len + b_len)) {\n            bfdec_set_nan(r);\n            ret = BF_ST_MEM_ERROR;\n            goto done;\n        }\n        mp_mul_basecase_dec(r->tab, a_tab, a_len, b_tab, b_len);\n        r->sign = r_sign;\n        r->expn = a->expn + b->expn;\n        ret = bfdec_normalize_and_round(r, prec, flags);\n    done:\n        if (r == &tmp)\n            bfdec_move(r1, &tmp);\n    }\n    return ret;\n}\n\nint bfdec_mul_si(bfdec_t *r, const bfdec_t *a, int64_t b1, limb_t prec,\n                 bf_flags_t flags)\n{\n    bfdec_t b;\n    int ret;\n    bfdec_init(r->ctx, &b);\n    ret = bfdec_set_si(&b, b1);\n    ret |= bfdec_mul(r, a, &b, prec, flags);\n    bfdec_delete(&b);\n    return ret;\n}\n\nint bfdec_add_si(bfdec_t *r, const bfdec_t *a, int64_t b1, limb_t prec,\n                 bf_flags_t flags)\n{\n    bfdec_t b;\n    int ret;\n    \n    bfdec_init(r->ctx, &b);\n    ret = bfdec_set_si(&b, b1);\n    ret |= bfdec_add(r, a, &b, prec, flags);\n    bfdec_delete(&b);\n    return ret;\n}\n\nstatic int __bfdec_div(bfdec_t *r, const bfdec_t *a, const bfdec_t *b,\n                       limb_t prec, bf_flags_t flags)\n{\n    int ret, r_sign;\n    limb_t n, nb, precl;\n    \n    r_sign = a->sign ^ b->sign;\n    if (a->expn >= BF_EXP_INF || b->expn >= BF_EXP_INF) {\n        if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {\n            bfdec_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF && b->expn == BF_EXP_INF) {\n            bfdec_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else if (a->expn == BF_EXP_INF) {\n            bfdec_set_inf(r, r_sign);\n            return 0;\n        } else {\n            bfdec_set_zero(r, r_sign);\n            return 0;\n        }\n    } else if (a->expn == BF_EXP_ZERO) {\n        if (b->expn == BF_EXP_ZERO) {\n            bfdec_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bfdec_set_zero(r, r_sign);\n            return 0;\n        }\n    } else if (b->expn == BF_EXP_ZERO) {\n        bfdec_set_inf(r, r_sign);\n        return BF_ST_DIVIDE_ZERO;\n    }\n\n    nb = b->len;\n    if (prec == BF_PREC_INF) {\n        /* infinite precision: return BF_ST_INVALID_OP if not an exact\n           result */\n        /* XXX: check */\n        precl = nb + 1;\n    } else if (flags & BF_FLAG_RADPNT_PREC) {\n        /* number of digits after the decimal point */\n        /* XXX: check (2 extra digits for rounding + 2 digits) */\n        precl = (bf_max(a->expn - b->expn, 0) + 2 +\n                 prec + 2 + LIMB_DIGITS - 1) / LIMB_DIGITS;\n    } else {\n        /* number of limbs of the quotient (2 extra digits for rounding) */\n        precl = (prec + 2 + LIMB_DIGITS - 1) / LIMB_DIGITS;\n    }\n    n = bf_max(a->len, precl);\n    \n    {\n        limb_t *taba, na, i;\n        slimb_t d;\n        \n        na = n + nb;\n        taba = bf_malloc(r->ctx, (na + 1) * sizeof(limb_t));\n        if (!taba)\n            goto fail;\n        d = na - a->len;\n        memset(taba, 0, d * sizeof(limb_t));\n        memcpy(taba + d, a->tab, a->len * sizeof(limb_t));\n        if (bfdec_resize(r, n + 1))\n            goto fail1;\n        if (mp_div_dec(r->ctx, r->tab, taba, na, b->tab, nb)) {\n        fail1:\n            bf_free(r->ctx, taba);\n            goto fail;\n        }\n        /* see if non zero remainder */\n        for(i = 0; i < nb; i++) {\n            if (taba[i] != 0)\n                break;\n        }\n        bf_free(r->ctx, taba);\n        if (i != nb) {\n            if (prec == BF_PREC_INF) {\n                bfdec_set_nan(r);\n                return BF_ST_INVALID_OP;\n            } else {\n                r->tab[0] |= 1;\n            }\n        }\n        r->expn = a->expn - b->expn + LIMB_DIGITS;\n        r->sign = r_sign;\n        ret = bfdec_normalize_and_round(r, prec, flags);\n    }\n    return ret;\n fail:\n    bfdec_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\nint bfdec_div(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags)\n{\n    return bf_op2((bf_t *)r, (bf_t *)a, (bf_t *)b, prec, flags,\n                  (bf_op2_func_t *)__bfdec_div);\n}\n\n/* a and b must be finite numbers with a >= 0 and b > 0. 'q' is the\n   integer defined as floor(a/b) and r = a - q * b. */\nstatic void bfdec_tdivremu(bf_context_t *s, bfdec_t *q, bfdec_t *r,\n                           const bfdec_t *a, const bfdec_t *b)\n{\n    if (bfdec_cmpu(a, b) < 0) {\n        bfdec_set_ui(q, 0);\n        bfdec_set(r, a);\n    } else {\n        bfdec_div(q, a, b, 0, BF_RNDZ | BF_FLAG_RADPNT_PREC);\n        bfdec_mul(r, q, b, BF_PREC_INF, BF_RNDZ);\n        bfdec_sub(r, a, r, BF_PREC_INF, BF_RNDZ);\n    }\n}\n\n/* division and remainder. \n   \n   rnd_mode is the rounding mode for the quotient. The additional\n   rounding mode BF_RND_EUCLIDIAN is supported.\n\n   'q' is an integer. 'r' is rounded with prec and flags (prec can be\n   BF_PREC_INF).\n*/\nint bfdec_divrem(bfdec_t *q, bfdec_t *r, const bfdec_t *a, const bfdec_t *b,\n                 limb_t prec, bf_flags_t flags, int rnd_mode)\n{\n    bf_context_t *s = q->ctx;\n    bfdec_t a1_s, *a1 = &a1_s;\n    bfdec_t b1_s, *b1 = &b1_s;\n    bfdec_t r1_s, *r1 = &r1_s;\n    int q_sign, res;\n    BOOL is_ceil, is_rndn;\n    \n    assert(q != a && q != b);\n    assert(r != a && r != b);\n    assert(q != r);\n    \n    if (a->len == 0 || b->len == 0) {\n        bfdec_set_zero(q, 0);\n        if (a->expn == BF_EXP_NAN || b->expn == BF_EXP_NAN) {\n            bfdec_set_nan(r);\n            return 0;\n        } else if (a->expn == BF_EXP_INF || b->expn == BF_EXP_ZERO) {\n            bfdec_set_nan(r);\n            return BF_ST_INVALID_OP;\n        } else {\n            bfdec_set(r, a);\n            return bfdec_round(r, prec, flags);\n        }\n    }\n\n    q_sign = a->sign ^ b->sign;\n    is_rndn = (rnd_mode == BF_RNDN || rnd_mode == BF_RNDNA);\n    switch(rnd_mode) {\n    default:\n    case BF_RNDZ:\n    case BF_RNDN:\n    case BF_RNDNA:\n        is_ceil = FALSE;\n        break;\n    case BF_RNDD:\n        is_ceil = q_sign;\n        break;\n    case BF_RNDU:\n        is_ceil = q_sign ^ 1;\n        break;\n    case BF_RNDA:\n        is_ceil = TRUE;\n        break;\n    case BF_DIVREM_EUCLIDIAN:\n        is_ceil = a->sign;\n        break;\n    }\n\n    a1->expn = a->expn;\n    a1->tab = a->tab;\n    a1->len = a->len;\n    a1->sign = 0;\n    \n    b1->expn = b->expn;\n    b1->tab = b->tab;\n    b1->len = b->len;\n    b1->sign = 0;\n\n    //    bfdec_print_str(\"a1\", a1);\n    //    bfdec_print_str(\"b1\", b1);\n    /* XXX: could improve to avoid having a large 'q' */\n    bfdec_tdivremu(s, q, r, a1, b1);\n    if (bfdec_is_nan(q) || bfdec_is_nan(r))\n        goto fail;\n    //    bfdec_print_str(\"q\", q);\n    //    bfdec_print_str(\"r\", r);\n    \n    if (r->len != 0) {\n        if (is_rndn) {\n            bfdec_init(s, r1);\n            if (bfdec_set(r1, r))\n                goto fail;\n            if (bfdec_mul_si(r1, r1, 2, BF_PREC_INF, BF_RNDZ)) {\n                bfdec_delete(r1);\n                goto fail;\n            }\n            res = bfdec_cmpu(r1, b);\n            bfdec_delete(r1);\n            if (res > 0 ||\n                (res == 0 &&\n                 (rnd_mode == BF_RNDNA ||\n                  (get_digit(q->tab, q->len, q->len * LIMB_DIGITS - q->expn) & 1) != 0))) {\n                goto do_sub_r;\n            }\n        } else if (is_ceil) {\n        do_sub_r:\n            res = bfdec_add_si(q, q, 1, BF_PREC_INF, BF_RNDZ);\n            res |= bfdec_sub(r, r, b1, BF_PREC_INF, BF_RNDZ);\n            if (res & BF_ST_MEM_ERROR)\n                goto fail;\n        }\n    }\n\n    r->sign ^= a->sign;\n    q->sign = q_sign;\n    return bfdec_round(r, prec, flags);\n fail:\n    bfdec_set_nan(q);\n    bfdec_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\nint bfdec_rem(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags, int rnd_mode)\n{\n    bfdec_t q_s, *q = &q_s;\n    int ret;\n    \n    bfdec_init(r->ctx, q);\n    ret = bfdec_divrem(q, r, a, b, prec, flags, rnd_mode);\n    bfdec_delete(q);\n    return ret;\n}\n\n/* convert to integer (infinite precision) */\nint bfdec_rint(bfdec_t *r, int rnd_mode)\n{\n    return bfdec_round(r, 0, rnd_mode | BF_FLAG_RADPNT_PREC);\n}\n\nint bfdec_sqrt(bfdec_t *r, const bfdec_t *a, limb_t prec, bf_flags_t flags)\n{\n    bf_context_t *s = a->ctx;\n    int ret, k;\n    limb_t *a1, v;\n    slimb_t n, n1, prec1;\n    limb_t res;\n\n    assert(r != a);\n\n    if (a->len == 0) {\n        if (a->expn == BF_EXP_NAN) {\n            bfdec_set_nan(r);\n        } else if (a->expn == BF_EXP_INF && a->sign) {\n            goto invalid_op;\n        } else {\n            bfdec_set(r, a);\n        }\n        ret = 0;\n    } else if (a->sign || prec == BF_PREC_INF) {\n invalid_op:\n        bfdec_set_nan(r);\n        ret = BF_ST_INVALID_OP;\n    } else {\n        if (flags & BF_FLAG_RADPNT_PREC) {\n            prec1 = bf_max(floor_div(a->expn + 1, 2) + prec, 1);\n        } else {\n            prec1 = prec;\n        }\n        /* convert the mantissa to an integer with at least 2 *\n           prec + 4 digits */\n        n = (2 * (prec1 + 2) + 2 * LIMB_DIGITS - 1) / (2 * LIMB_DIGITS);\n        if (bfdec_resize(r, n))\n            goto fail;\n        a1 = bf_malloc(s, sizeof(limb_t) * 2 * n);\n        if (!a1)\n            goto fail;\n        n1 = bf_min(2 * n, a->len);\n        memset(a1, 0, (2 * n - n1) * sizeof(limb_t));\n        memcpy(a1 + 2 * n - n1, a->tab + a->len - n1, n1 * sizeof(limb_t));\n        if (a->expn & 1) {\n            res = mp_shr_dec(a1, a1, 2 * n, 1, 0);\n        } else {\n            res = 0;\n        }\n        /* normalize so that a1 >= B^(2*n)/4. Not need for n = 1\n           because mp_sqrtrem2_dec already does it */\n        k = 0;\n        if (n > 1) {\n            v = a1[2 * n - 1];\n            while (v < BF_DEC_BASE / 4) {\n                k++;\n                v *= 4;\n            }\n            if (k != 0)\n                mp_mul1_dec(a1, a1, 2 * n, 1 << (2 * k), 0);\n        }\n        if (mp_sqrtrem_dec(s, r->tab, a1, n)) {\n            bf_free(s, a1);\n            goto fail;\n        }\n        if (k != 0)\n            mp_div1_dec(r->tab, r->tab, n, 1 << k, 0);\n        if (!res) {\n            res = mp_scan_nz(a1, n + 1);\n        }\n        bf_free(s, a1);\n        if (!res) {\n            res = mp_scan_nz(a->tab, a->len - n1);\n        }\n        if (res != 0)\n            r->tab[0] |= 1;\n        r->sign = 0;\n        r->expn = (a->expn + 1) >> 1;\n        ret = bfdec_round(r, prec, flags);\n    }\n    return ret;\n fail:\n    bfdec_set_nan(r);\n    return BF_ST_MEM_ERROR;\n}\n\n/* The rounding mode is always BF_RNDZ. Return BF_ST_OVERFLOW if there\n   is an overflow and 0 otherwise. No memory error is possible. */\nint bfdec_get_int32(int *pres, const bfdec_t *a)\n{\n    uint32_t v;\n    int ret;\n    if (a->expn >= BF_EXP_INF) {\n        ret = 0;\n        if (a->expn == BF_EXP_INF) {\n            v = (uint32_t)INT32_MAX + a->sign;\n             /* XXX: return overflow ? */\n        } else {\n            v = INT32_MAX;\n        }\n    } else if (a->expn <= 0) {\n        v = 0;\n        ret = 0;\n    } else if (a->expn <= 9) {\n        v = fast_shr_dec(a->tab[a->len - 1], LIMB_DIGITS - a->expn);\n        if (a->sign)\n            v = -v;\n        ret = 0;\n    } else if (a->expn == 10) {\n        uint64_t v1;\n        uint32_t v_max;\n#if LIMB_BITS == 64\n        v1 = fast_shr_dec(a->tab[a->len - 1], LIMB_DIGITS - a->expn);\n#else\n        v1 = (uint64_t)a->tab[a->len - 1] * 10 +\n            get_digit(a->tab, a->len, (a->len - 1) * LIMB_DIGITS - 1);\n#endif\n        v_max = (uint32_t)INT32_MAX + a->sign;\n        if (v1 > v_max) {\n            v = v_max;\n            ret = BF_ST_OVERFLOW;\n        } else {\n            v = v1;\n            if (a->sign)\n                v = -v;\n            ret = 0;\n        }\n    } else {\n        v = (uint32_t)INT32_MAX + a->sign;\n        ret = BF_ST_OVERFLOW;\n    }\n    *pres = v;\n    return ret;\n}\n\n/* power to an integer with infinite precision */\nint bfdec_pow_ui(bfdec_t *r, const bfdec_t *a, limb_t b)\n{\n    int ret, n_bits, i;\n    \n    assert(r != a);\n    if (b == 0)\n        return bfdec_set_ui(r, 1);\n    ret = bfdec_set(r, a);\n    n_bits = LIMB_BITS - clz(b);\n    for(i = n_bits - 2; i >= 0; i--) {\n        ret |= bfdec_mul(r, r, r, BF_PREC_INF, BF_RNDZ);\n        if ((b >> i) & 1)\n            ret |= bfdec_mul(r, r, a, BF_PREC_INF, BF_RNDZ);\n    }\n    return ret;\n}\n\nchar *bfdec_ftoa(size_t *plen, const bfdec_t *a, limb_t prec, bf_flags_t flags)\n{\n    return bf_ftoa_internal(plen, (const bf_t *)a, 10, prec, flags, TRUE);\n}\n\nint bfdec_atof(bfdec_t *r, const char *str, const char **pnext,\n               limb_t prec, bf_flags_t flags)\n{\n    slimb_t dummy_exp;\n    return bf_atof_internal((bf_t *)r, &dummy_exp, str, pnext, 10, prec,\n                            flags, TRUE);\n}\n\n#endif /* USE_BF_DEC */\n\n#ifdef USE_FFT_MUL\n/***************************************************************/\n/* Integer multiplication with FFT */\n\n/* or LIMB_BITS at bit position 'pos' in tab */\nstatic inline void put_bits(limb_t *tab, limb_t len, slimb_t pos, limb_t val)\n{\n    limb_t i;\n    int p;\n\n    i = pos >> LIMB_LOG2_BITS;\n    p = pos & (LIMB_BITS - 1);\n    if (i < len)\n        tab[i] |= val << p;\n    if (p != 0) {\n        i++;\n        if (i < len) {\n            tab[i] |= val >> (LIMB_BITS - p);\n        }\n    }\n}\n\n#if defined(__AVX2__)\n\ntypedef double NTTLimb;\n\n/* we must have: modulo >= 1 << NTT_MOD_LOG2_MIN */\n#define NTT_MOD_LOG2_MIN 50\n#define NTT_MOD_LOG2_MAX 51\n#define NB_MODS 5\n#define NTT_PROOT_2EXP 39\nstatic const int ntt_int_bits[NB_MODS] = { 254, 203, 152, 101, 50, };\n\nstatic const limb_t ntt_mods[NB_MODS] = { 0x00073a8000000001, 0x0007858000000001, 0x0007a38000000001, 0x0007a68000000001, 0x0007fd8000000001,\n};\n\nstatic const limb_t ntt_proot[2][NB_MODS] = {\n    { 0x00056198d44332c8, 0x0002eb5d640aad39, 0x00047e31eaa35fd0, 0x0005271ac118a150, 0x00075e0ce8442bd5, },\n    { 0x000461169761bcc5, 0x0002dac3cb2da688, 0x0004abc97751e3bf, 0x000656778fc8c485, 0x0000dc6469c269fa, },\n};\n\nstatic const limb_t ntt_mods_cr[NB_MODS * (NB_MODS - 1) / 2] = {\n 0x00020e4da740da8e, 0x0004c3dc09c09c1d, 0x000063bd097b4271, 0x000799d8f18f18fd,\n 0x0005384222222264, 0x000572b07c1f07fe, 0x00035cd08888889a,\n 0x00066015555557e3, 0x000725960b60b623,\n 0x0002fc1fa1d6ce12,\n};\n\n#else\n\ntypedef limb_t NTTLimb;\n\n#if LIMB_BITS == 64\n\n#define NTT_MOD_LOG2_MIN 61\n#define NTT_MOD_LOG2_MAX 62\n#define NB_MODS 5\n#define NTT_PROOT_2EXP 51\nstatic const int ntt_int_bits[NB_MODS] = { 307, 246, 185, 123, 61, };\n\nstatic const limb_t ntt_mods[NB_MODS] = { 0x28d8000000000001, 0x2a88000000000001, 0x2ed8000000000001, 0x3508000000000001, 0x3aa8000000000001,\n};\n\nstatic const limb_t ntt_proot[2][NB_MODS] = {\n    { 0x1b8ea61034a2bea7, 0x21a9762de58206fb, 0x02ca782f0756a8ea, 0x278384537a3e50a1, 0x106e13fee74ce0ab, },\n    { 0x233513af133e13b8, 0x1d13140d1c6f75f1, 0x12cde57f97e3eeda, 0x0d6149e23cbe654f, 0x36cd204f522a1379, },\n};\n\nstatic const limb_t ntt_mods_cr[NB_MODS * (NB_MODS - 1) / 2] = {\n 0x08a9ed097b425eea, 0x18a44aaaaaaaaab3, 0x2493f57f57f57f5d, 0x126b8d0649a7f8d4,\n 0x09d80ed7303b5ccc, 0x25b8bcf3cf3cf3d5, 0x2ce6ce63398ce638,\n 0x0e31fad40a57eb59, 0x02a3529fd4a7f52f,\n 0x3a5493e93e93e94a,\n};\n\n#elif LIMB_BITS == 32\n\n/* we must have: modulo >= 1 << NTT_MOD_LOG2_MIN */\n#define NTT_MOD_LOG2_MIN 29\n#define NTT_MOD_LOG2_MAX 30\n#define NB_MODS 5\n#define NTT_PROOT_2EXP 20\nstatic const int ntt_int_bits[NB_MODS] = { 148, 119, 89, 59, 29, };\n\nstatic const limb_t ntt_mods[NB_MODS] = { 0x0000000032b00001, 0x0000000033700001, 0x0000000036d00001, 0x0000000037300001, 0x000000003e500001,\n};\n\nstatic const limb_t ntt_proot[2][NB_MODS] = {\n    { 0x0000000032525f31, 0x0000000005eb3b37, 0x00000000246eda9f, 0x0000000035f25901, 0x00000000022f5768, },\n    { 0x00000000051eba1a, 0x00000000107be10e, 0x000000001cd574e0, 0x00000000053806e6, 0x000000002cd6bf98, },\n};\n\nstatic const limb_t ntt_mods_cr[NB_MODS * (NB_MODS - 1) / 2] = {\n 0x000000000449559a, 0x000000001eba6ca9, 0x000000002ec18e46, 0x000000000860160b,\n 0x000000000d321307, 0x000000000bf51120, 0x000000000f662938,\n 0x000000000932ab3e, 0x000000002f40eef8,\n 0x000000002e760905,\n};\n\n#endif /* LIMB_BITS */\n\n#endif /* !AVX2 */\n\n#if defined(__AVX2__)\n#define NTT_TRIG_K_MAX 18\n#else\n#define NTT_TRIG_K_MAX 19\n#endif\n\ntypedef struct BFNTTState {\n    bf_context_t *ctx;\n    \n    /* used for mul_mod_fast() */\n    limb_t ntt_mods_div[NB_MODS];\n\n    limb_t ntt_proot_pow[NB_MODS][2][NTT_PROOT_2EXP + 1];\n    limb_t ntt_proot_pow_inv[NB_MODS][2][NTT_PROOT_2EXP + 1];\n    NTTLimb *ntt_trig[NB_MODS][2][NTT_TRIG_K_MAX + 1];\n    /* 1/2^n mod m */\n    limb_t ntt_len_inv[NB_MODS][NTT_PROOT_2EXP + 1][2];\n#if defined(__AVX2__)\n    __m256d ntt_mods_cr_vec[NB_MODS * (NB_MODS - 1) / 2];\n    __m256d ntt_mods_vec[NB_MODS];\n    __m256d ntt_mods_inv_vec[NB_MODS];\n#else\n    limb_t ntt_mods_cr_inv[NB_MODS * (NB_MODS - 1) / 2];\n#endif\n} BFNTTState;\n\nstatic NTTLimb *get_trig(BFNTTState *s, int k, int inverse, int m_idx);\n\n/* add modulo with up to (LIMB_BITS-1) bit modulo */\nstatic inline limb_t add_mod(limb_t a, limb_t b, limb_t m)\n{\n    limb_t r;\n    r = a + b;\n    if (r >= m)\n        r -= m;\n    return r;\n}\n\n/* sub modulo with up to LIMB_BITS bit modulo */\nstatic inline limb_t sub_mod(limb_t a, limb_t b, limb_t m)\n{\n    limb_t r;\n    r = a - b;\n    if (r > a)\n        r += m;\n    return r;\n}\n\n/* return (r0+r1*B) mod m \n   precondition: 0 <= r0+r1*B < 2^(64+NTT_MOD_LOG2_MIN) \n*/\nstatic inline limb_t mod_fast(dlimb_t r, \n                                limb_t m, limb_t m_inv)\n{\n    limb_t a1, q, t0, r1, r0;\n    \n    a1 = r >> NTT_MOD_LOG2_MIN;\n    \n    q = ((dlimb_t)a1 * m_inv) >> LIMB_BITS;\n    r = r - (dlimb_t)q * m - m * 2;\n    r1 = r >> LIMB_BITS;\n    t0 = (slimb_t)r1 >> 1;\n    r += m & t0;\n    r0 = r;\n    r1 = r >> LIMB_BITS;\n    r0 += m & r1;\n    return r0;\n}\n\n/* faster version using precomputed modulo inverse. \n   precondition: 0 <= a * b < 2^(64+NTT_MOD_LOG2_MIN) */\nstatic inline limb_t mul_mod_fast(limb_t a, limb_t b, \n                                    limb_t m, limb_t m_inv)\n{\n    dlimb_t r;\n    r = (dlimb_t)a * (dlimb_t)b;\n    return mod_fast(r, m, m_inv);\n}\n\nstatic inline limb_t init_mul_mod_fast(limb_t m)\n{\n    dlimb_t t;\n    assert(m < (limb_t)1 << NTT_MOD_LOG2_MAX);\n    assert(m >= (limb_t)1 << NTT_MOD_LOG2_MIN);\n    t = (dlimb_t)1 << (LIMB_BITS + NTT_MOD_LOG2_MIN);\n    return t / m;\n}\n\n/* Faster version used when the multiplier is constant. 0 <= a < 2^64,\n   0 <= b < m. */\nstatic inline limb_t mul_mod_fast2(limb_t a, limb_t b, \n                                     limb_t m, limb_t b_inv)\n{\n    limb_t r, q;\n\n    q = ((dlimb_t)a * (dlimb_t)b_inv) >> LIMB_BITS;\n    r = a * b - q * m;\n    if (r >= m)\n        r -= m;\n    return r;\n}\n\n/* Faster version used when the multiplier is constant. 0 <= a < 2^64,\n   0 <= b < m. Let r = a * b mod m. The return value is 'r' or 'r +\n   m'. */\nstatic inline limb_t mul_mod_fast3(limb_t a, limb_t b, \n                                     limb_t m, limb_t b_inv)\n{\n    limb_t r, q;\n\n    q = ((dlimb_t)a * (dlimb_t)b_inv) >> LIMB_BITS;\n    r = a * b - q * m;\n    return r;\n}\n\nstatic inline limb_t init_mul_mod_fast2(limb_t b, limb_t m)\n{\n    return ((dlimb_t)b << LIMB_BITS) / m;\n}\n\n#ifdef __AVX2__\n\nstatic inline limb_t ntt_limb_to_int(NTTLimb a, limb_t m)\n{\n    slimb_t v;\n    v = a;\n    if (v < 0)\n        v += m;\n    if (v >= m)\n        v -= m;\n    return v;\n}\n\nstatic inline NTTLimb int_to_ntt_limb(limb_t a, limb_t m)\n{\n    return (slimb_t)a;\n}\n\nstatic inline NTTLimb int_to_ntt_limb2(limb_t a, limb_t m)\n{\n    if (a >= (m / 2))\n        a -= m;\n    return (slimb_t)a;\n}\n\n/* return r + m if r < 0 otherwise r. */\nstatic inline __m256d ntt_mod1(__m256d r, __m256d m)\n{\n    return _mm256_blendv_pd(r, r + m, r);\n}\n\n/* input: abs(r) < 2 * m. Output: abs(r) < m */\nstatic inline __m256d ntt_mod(__m256d r, __m256d mf, __m256d m2f)\n{\n    return _mm256_blendv_pd(r, r + m2f, r) - mf;\n}\n\n/* input: abs(a*b) < 2 * m^2, output: abs(r) < m */\nstatic inline __m256d ntt_mul_mod(__m256d a, __m256d b, __m256d mf,\n                                  __m256d m_inv)\n{\n    __m256d r, q, ab1, ab0, qm0, qm1;\n    ab1 = a * b;\n    q = _mm256_round_pd(ab1 * m_inv, 0); /* round to nearest */\n    qm1 = q * mf;\n    qm0 = _mm256_fmsub_pd(q, mf, qm1); /* low part */\n    ab0 = _mm256_fmsub_pd(a, b, ab1); /* low part */\n    r = (ab1 - qm1) + (ab0 - qm0);\n    return r;\n}\n\nstatic void *bf_aligned_malloc(bf_context_t *s, size_t size, size_t align)\n{\n    void *ptr;\n    void **ptr1;\n    ptr = bf_malloc(s, size + sizeof(void *) + align - 1);\n    if (!ptr)\n        return NULL;\n    ptr1 = (void **)(((uintptr_t)ptr + sizeof(void *) + align - 1) &\n                     ~(align - 1));\n    ptr1[-1] = ptr;\n    return ptr1;\n}\n\nstatic void bf_aligned_free(bf_context_t *s, void *ptr)\n{\n    if (!ptr)\n        return;\n    bf_free(s, ((void **)ptr)[-1]);\n}\n\nstatic void *ntt_malloc(BFNTTState *s, size_t size)\n{\n    return bf_aligned_malloc(s->ctx, size, 64);\n}\n\nstatic void ntt_free(BFNTTState *s, void *ptr)\n{\n    bf_aligned_free(s->ctx, ptr);\n}\n\nstatic no_inline int ntt_fft(BFNTTState *s,\n                             NTTLimb *out_buf, NTTLimb *in_buf,\n                             NTTLimb *tmp_buf, int fft_len_log2,\n                             int inverse, int m_idx)\n{\n    limb_t nb_blocks, fft_per_block, p, k, n, stride_in, i, j;\n    NTTLimb *tab_in, *tab_out, *tmp, *trig;\n    __m256d m_inv, mf, m2f, c, a0, a1, b0, b1;\n    limb_t m;\n    int l;\n    \n    m = ntt_mods[m_idx];\n    \n    m_inv = _mm256_set1_pd(1.0 / (double)m);\n    mf = _mm256_set1_pd(m);\n    m2f = _mm256_set1_pd(m * 2);\n\n    n = (limb_t)1 << fft_len_log2;\n    assert(n >= 8);\n    stride_in = n / 2;\n\n    tab_in = in_buf;\n    tab_out = tmp_buf;\n    trig = get_trig(s, fft_len_log2, inverse, m_idx);\n    if (!trig)\n        return -1;\n    p = 0;\n    for(k = 0; k < stride_in; k += 4) {\n        a0 = _mm256_load_pd(&tab_in[k]);\n        a1 = _mm256_load_pd(&tab_in[k + stride_in]);\n        c = _mm256_load_pd(trig);\n        trig += 4;\n        b0 = ntt_mod(a0 + a1, mf, m2f);\n        b1 = ntt_mul_mod(a0 - a1, c, mf, m_inv);\n        a0 = _mm256_permute2f128_pd(b0, b1, 0x20);\n        a1 = _mm256_permute2f128_pd(b0, b1, 0x31);\n        a0 = _mm256_permute4x64_pd(a0, 0xd8);\n        a1 = _mm256_permute4x64_pd(a1, 0xd8);\n        _mm256_store_pd(&tab_out[p], a0);\n        _mm256_store_pd(&tab_out[p + 4], a1);\n        p += 2 * 4;\n    }\n    tmp = tab_in;\n    tab_in = tab_out;\n    tab_out = tmp;\n\n    trig = get_trig(s, fft_len_log2 - 1, inverse, m_idx);\n    if (!trig)\n        return -1;\n    p = 0;\n    for(k = 0; k < stride_in; k += 4) {\n        a0 = _mm256_load_pd(&tab_in[k]);\n        a1 = _mm256_load_pd(&tab_in[k + stride_in]);\n        c = _mm256_setr_pd(trig[0], trig[0], trig[1], trig[1]);\n        trig += 2;\n        b0 = ntt_mod(a0 + a1, mf, m2f);\n        b1 = ntt_mul_mod(a0 - a1, c, mf, m_inv);\n        a0 = _mm256_permute2f128_pd(b0, b1, 0x20);\n        a1 = _mm256_permute2f128_pd(b0, b1, 0x31);\n        _mm256_store_pd(&tab_out[p], a0);\n        _mm256_store_pd(&tab_out[p + 4], a1);\n        p += 2 * 4;\n    }\n    tmp = tab_in;\n    tab_in = tab_out;\n    tab_out = tmp;\n    \n    nb_blocks = n / 4;\n    fft_per_block = 4;\n\n    l = fft_len_log2 - 2;\n    while (nb_blocks != 2) {\n        nb_blocks >>= 1;\n        p = 0;\n        k = 0;\n        trig = get_trig(s, l, inverse, m_idx);\n        if (!trig)\n            return -1;\n        for(i = 0; i < nb_blocks; i++) {\n            c = _mm256_set1_pd(trig[0]);\n            trig++;\n            for(j = 0; j < fft_per_block; j += 4) {\n                a0 = _mm256_load_pd(&tab_in[k + j]);\n                a1 = _mm256_load_pd(&tab_in[k + j + stride_in]);\n                b0 = ntt_mod(a0 + a1, mf, m2f);\n                b1 = ntt_mul_mod(a0 - a1, c, mf, m_inv);\n                _mm256_store_pd(&tab_out[p + j], b0);\n                _mm256_store_pd(&tab_out[p + j + fft_per_block], b1);\n            }\n            k += fft_per_block;\n            p += 2 * fft_per_block;\n        }\n        fft_per_block <<= 1;\n        l--;\n        tmp = tab_in;\n        tab_in = tab_out;\n        tab_out = tmp;\n    }\n\n    tab_out = out_buf;\n    for(k = 0; k < stride_in; k += 4) {\n        a0 = _mm256_load_pd(&tab_in[k]);\n        a1 = _mm256_load_pd(&tab_in[k + stride_in]);\n        b0 = ntt_mod(a0 + a1, mf, m2f);\n        b1 = ntt_mod(a0 - a1, mf, m2f);\n        _mm256_store_pd(&tab_out[k], b0);\n        _mm256_store_pd(&tab_out[k + stride_in], b1);\n    }\n    return 0;\n}\n\nstatic void ntt_vec_mul(BFNTTState *s,\n                        NTTLimb *tab1, NTTLimb *tab2, limb_t fft_len_log2,\n                        int k_tot, int m_idx)\n{\n    limb_t i, c_inv, n, m;\n    __m256d m_inv, mf, a, b, c;\n    \n    m = ntt_mods[m_idx];\n    c_inv = s->ntt_len_inv[m_idx][k_tot][0];\n    m_inv = _mm256_set1_pd(1.0 / (double)m);\n    mf = _mm256_set1_pd(m);\n    c = _mm256_set1_pd(int_to_ntt_limb(c_inv, m));\n    n = (limb_t)1 << fft_len_log2;\n    for(i = 0; i < n; i += 4) {\n        a = _mm256_load_pd(&tab1[i]);\n        b = _mm256_load_pd(&tab2[i]);\n        a = ntt_mul_mod(a, b, mf, m_inv);\n        a = ntt_mul_mod(a, c, mf, m_inv);\n        _mm256_store_pd(&tab1[i], a);\n    }\n}\n\nstatic no_inline void mul_trig(NTTLimb *buf,\n                               limb_t n, limb_t c1, limb_t m, limb_t m_inv1)\n{\n    limb_t i, c2, c3, c4;\n    __m256d c, c_mul, a0, mf, m_inv;\n    assert(n >= 2);\n    \n    mf = _mm256_set1_pd(m);\n    m_inv = _mm256_set1_pd(1.0 / (double)m);\n\n    c2 = mul_mod_fast(c1, c1, m, m_inv1);\n    c3 = mul_mod_fast(c2, c1, m, m_inv1);\n    c4 = mul_mod_fast(c2, c2, m, m_inv1);\n    c = _mm256_setr_pd(1, int_to_ntt_limb(c1, m),\n                       int_to_ntt_limb(c2, m), int_to_ntt_limb(c3, m));\n    c_mul = _mm256_set1_pd(int_to_ntt_limb(c4, m));\n    for(i = 0; i < n; i += 4) {\n        a0 = _mm256_load_pd(&buf[i]);\n        a0 = ntt_mul_mod(a0, c, mf, m_inv);\n        _mm256_store_pd(&buf[i], a0);\n        c = ntt_mul_mod(c, c_mul, mf, m_inv);\n    }\n}\n\n#else\n\nstatic void *ntt_malloc(BFNTTState *s, size_t size)\n{\n    return bf_malloc(s->ctx, size);\n}\n\nstatic void ntt_free(BFNTTState *s, void *ptr)\n{\n    bf_free(s->ctx, ptr);\n}\n\nstatic inline limb_t ntt_limb_to_int(NTTLimb a, limb_t m)\n{\n    if (a >= m)\n        a -= m;\n    return a;\n}\n\nstatic inline NTTLimb int_to_ntt_limb(slimb_t a, limb_t m)\n{\n    return a;\n}\n\nstatic no_inline int ntt_fft(BFNTTState *s, NTTLimb *out_buf, NTTLimb *in_buf,\n                             NTTLimb *tmp_buf, int fft_len_log2,\n                             int inverse, int m_idx)\n{\n    limb_t nb_blocks, fft_per_block, p, k, n, stride_in, i, j, m, m2;\n    NTTLimb *tab_in, *tab_out, *tmp, a0, a1, b0, b1, c, *trig, c_inv;\n    int l;\n    \n    m = ntt_mods[m_idx];\n    m2 = 2 * m;\n    n = (limb_t)1 << fft_len_log2;\n    nb_blocks = n;\n    fft_per_block = 1;\n    stride_in = n / 2;\n    tab_in = in_buf;\n    tab_out = tmp_buf;\n    l = fft_len_log2;\n    while (nb_blocks != 2) {\n        nb_blocks >>= 1;\n        p = 0;\n        k = 0;\n        trig = get_trig(s, l, inverse, m_idx);\n        if (!trig)\n            return -1;\n        for(i = 0; i < nb_blocks; i++) {\n            c = trig[0];\n            c_inv = trig[1];\n            trig += 2;\n            for(j = 0; j < fft_per_block; j++) {\n                a0 = tab_in[k + j];\n                a1 = tab_in[k + j + stride_in];\n                b0 = add_mod(a0, a1, m2);\n                b1 = a0 - a1 + m2;\n                b1 = mul_mod_fast3(b1, c, m, c_inv);\n                tab_out[p + j] = b0;\n                tab_out[p + j + fft_per_block] = b1;\n            }\n            k += fft_per_block;\n            p += 2 * fft_per_block;\n        }\n        fft_per_block <<= 1;\n        l--;\n        tmp = tab_in;\n        tab_in = tab_out;\n        tab_out = tmp;\n    }\n    /* no twiddle in last step */\n    tab_out = out_buf; \n    for(k = 0; k < stride_in; k++) {\n        a0 = tab_in[k];\n        a1 = tab_in[k + stride_in];\n        b0 = add_mod(a0, a1, m2);\n        b1 = sub_mod(a0, a1, m2);\n        tab_out[k] = b0;\n        tab_out[k + stride_in] = b1;\n    }\n    return 0;\n}\n\nstatic void ntt_vec_mul(BFNTTState *s,\n                        NTTLimb *tab1, NTTLimb *tab2, int fft_len_log2,\n                        int k_tot, int m_idx)\n{\n    limb_t i, norm, norm_inv, a, n, m, m_inv;\n    \n    m = ntt_mods[m_idx];\n    m_inv = s->ntt_mods_div[m_idx];\n    norm = s->ntt_len_inv[m_idx][k_tot][0];\n    norm_inv = s->ntt_len_inv[m_idx][k_tot][1];\n    n = (limb_t)1 << fft_len_log2;\n    for(i = 0; i < n; i++) {\n        a = tab1[i];\n        /* need to reduce the range so that the product is <\n           2^(LIMB_BITS+NTT_MOD_LOG2_MIN) */\n        if (a >= m)\n            a -= m;\n        a = mul_mod_fast(a, tab2[i], m, m_inv);\n        a = mul_mod_fast3(a, norm, m, norm_inv);\n        tab1[i] = a;\n    }\n}\n\nstatic no_inline void mul_trig(NTTLimb *buf,\n                               limb_t n, limb_t c_mul, limb_t m, limb_t m_inv)\n{\n    limb_t i, c0, c_mul_inv;\n    \n    c0 = 1;\n    c_mul_inv = init_mul_mod_fast2(c_mul, m);\n    for(i = 0; i < n; i++) {\n        buf[i] = mul_mod_fast(buf[i], c0, m, m_inv);\n        c0 = mul_mod_fast2(c0, c_mul, m, c_mul_inv);\n    }\n}\n\n#endif /* !AVX2 */\n\nstatic no_inline NTTLimb *get_trig(BFNTTState *s,\n                                   int k, int inverse, int m_idx)\n{\n    NTTLimb *tab;\n    limb_t i, n2, c, c_mul, m, c_mul_inv;\n    \n    if (k > NTT_TRIG_K_MAX)\n        return NULL;\n\n    tab = s->ntt_trig[m_idx][inverse][k];\n    if (tab)\n        return tab;\n    n2 = (limb_t)1 << (k - 1);\n    m = ntt_mods[m_idx];\n#ifdef __AVX2__\n    tab = ntt_malloc(s, sizeof(NTTLimb) * n2);\n#else\n    tab = ntt_malloc(s, sizeof(NTTLimb) * n2 * 2);\n#endif\n    if (!tab)\n        return NULL;\n    c = 1;\n    c_mul = s->ntt_proot_pow[m_idx][inverse][k];\n    c_mul_inv = s->ntt_proot_pow_inv[m_idx][inverse][k];\n    for(i = 0; i < n2; i++) {\n#ifdef __AVX2__\n        tab[i] = int_to_ntt_limb2(c, m);\n#else\n        tab[2 * i] = int_to_ntt_limb(c, m);\n        tab[2 * i + 1] = init_mul_mod_fast2(c, m);\n#endif\n        c = mul_mod_fast2(c, c_mul, m, c_mul_inv);\n    }\n    s->ntt_trig[m_idx][inverse][k] = tab;\n    return tab;\n}\n\nvoid fft_clear_cache(bf_context_t *s1)\n{\n    int m_idx, inverse, k;\n    BFNTTState *s = s1->ntt_state;\n    if (s) {\n        for(m_idx = 0; m_idx < NB_MODS; m_idx++) {\n            for(inverse = 0; inverse < 2; inverse++) {\n                for(k = 0; k < NTT_TRIG_K_MAX + 1; k++) {\n                    if (s->ntt_trig[m_idx][inverse][k]) {\n                        ntt_free(s, s->ntt_trig[m_idx][inverse][k]);\n                        s->ntt_trig[m_idx][inverse][k] = NULL;\n                    }\n                }\n            }\n        }\n#if defined(__AVX2__)\n        bf_aligned_free(s1, s);\n#else\n        bf_free(s1, s);\n#endif\n        s1->ntt_state = NULL;\n    }\n}\n\n#define STRIP_LEN 16\n\n/* dst = buf1, src = buf2 */\nstatic int ntt_fft_partial(BFNTTState *s, NTTLimb *buf1,\n                           int k1, int k2, limb_t n1, limb_t n2, int inverse,\n                           limb_t m_idx)\n{\n    limb_t i, j, c_mul, c0, m, m_inv, strip_len, l;\n    NTTLimb *buf2, *buf3;\n    \n    buf2 = NULL;\n    buf3 = ntt_malloc(s, sizeof(NTTLimb) * n1);\n    if (!buf3)\n        goto fail;\n    if (k2 == 0) {\n        if (ntt_fft(s, buf1, buf1, buf3, k1, inverse, m_idx))\n            goto fail;\n    } else {\n        strip_len = STRIP_LEN;\n        buf2 = ntt_malloc(s, sizeof(NTTLimb) * n1 * strip_len);\n        if (!buf2)\n            goto fail;\n        m = ntt_mods[m_idx];\n        m_inv = s->ntt_mods_div[m_idx];\n        c0 = s->ntt_proot_pow[m_idx][inverse][k1 + k2];\n        c_mul = 1;\n        assert((n2 % strip_len) == 0);\n        for(j = 0; j < n2; j += strip_len) {\n            for(i = 0; i < n1; i++) {\n                for(l = 0; l < strip_len; l++) {\n                    buf2[i + l * n1] = buf1[i * n2 + (j + l)];\n                }\n            }\n            for(l = 0; l < strip_len; l++) {\n                if (inverse)\n                    mul_trig(buf2 + l * n1, n1, c_mul, m, m_inv);\n                if (ntt_fft(s, buf2 + l * n1, buf2 + l * n1, buf3, k1, inverse, m_idx))\n                    goto fail;\n                if (!inverse)\n                    mul_trig(buf2 + l * n1, n1, c_mul, m, m_inv);\n                c_mul = mul_mod_fast(c_mul, c0, m, m_inv);\n            }\n            \n            for(i = 0; i < n1; i++) {\n                for(l = 0; l < strip_len; l++) {\n                    buf1[i * n2 + (j + l)] = buf2[i + l *n1];\n                }\n            }\n        }\n        ntt_free(s, buf2);\n    }\n    ntt_free(s, buf3);\n    return 0;\n fail:\n    ntt_free(s, buf2);\n    ntt_free(s, buf3);\n    return -1;\n}\n\n\n/* dst = buf1, src = buf2, tmp = buf3 */\nstatic int ntt_conv(BFNTTState *s, NTTLimb *buf1, NTTLimb *buf2,\n                    int k, int k_tot, limb_t m_idx)\n{\n    limb_t n1, n2, i;\n    int k1, k2;\n    \n    if (k <= NTT_TRIG_K_MAX) {\n        k1 = k;\n    } else {\n        /* recursive split of the FFT */\n        k1 = bf_min(k / 2, NTT_TRIG_K_MAX);\n    }\n    k2 = k - k1;\n    n1 = (limb_t)1 << k1;\n    n2 = (limb_t)1 << k2;\n    \n    if (ntt_fft_partial(s, buf1, k1, k2, n1, n2, 0, m_idx))\n        return -1;\n    if (ntt_fft_partial(s, buf2, k1, k2, n1, n2, 0, m_idx))\n        return -1;\n    if (k2 == 0) {\n        ntt_vec_mul(s, buf1, buf2, k, k_tot, m_idx);\n    } else {\n        for(i = 0; i < n1; i++) {\n            ntt_conv(s, buf1 + i * n2, buf2 + i * n2, k2, k_tot, m_idx);\n        }\n    }\n    if (ntt_fft_partial(s, buf1, k1, k2, n1, n2, 1, m_idx))\n        return -1;\n    return 0;\n}\n\n\nstatic no_inline void limb_to_ntt(BFNTTState *s,\n                                  NTTLimb *tabr, limb_t fft_len,\n                                  const limb_t *taba, limb_t a_len, int dpl,\n                                  int first_m_idx, int nb_mods)\n{\n    slimb_t i, n;\n    dlimb_t a, b;\n    int j, shift;\n    limb_t base_mask1, a0, a1, a2, r, m, m_inv;\n    \n#if 0\n    for(i = 0; i < a_len; i++) {\n        printf(\"%\" PRId64 \": \" FMT_LIMB \"\\n\",\n               (int64_t)i, taba[i]);\n    }\n#endif   \n    memset(tabr, 0, sizeof(NTTLimb) * fft_len * nb_mods);\n    shift = dpl & (LIMB_BITS - 1);\n    if (shift == 0)\n        base_mask1 = -1;\n    else\n        base_mask1 = ((limb_t)1 << shift) - 1;\n    n = bf_min(fft_len, (a_len * LIMB_BITS + dpl - 1) / dpl);\n    for(i = 0; i < n; i++) {\n        a0 = get_bits(taba, a_len, i * dpl);\n        if (dpl <= LIMB_BITS) {\n            a0 &= base_mask1;\n            a = a0;\n        } else {\n            a1 = get_bits(taba, a_len, i * dpl + LIMB_BITS);\n            if (dpl <= (LIMB_BITS + NTT_MOD_LOG2_MIN)) {\n                a = a0 | ((dlimb_t)(a1 & base_mask1) << LIMB_BITS);\n            } else {\n                if (dpl > 2 * LIMB_BITS) {\n                    a2 = get_bits(taba, a_len, i * dpl + LIMB_BITS * 2) &\n                        base_mask1;\n                } else {\n                    a1 &= base_mask1;\n                    a2 = 0;\n                }\n                //            printf(\"a=0x%016lx%016lx%016lx\\n\", a2, a1, a0);\n                a = (a0 >> (LIMB_BITS - NTT_MOD_LOG2_MAX + NTT_MOD_LOG2_MIN)) |\n                    ((dlimb_t)a1 << (NTT_MOD_LOG2_MAX - NTT_MOD_LOG2_MIN)) |\n                    ((dlimb_t)a2 << (LIMB_BITS + NTT_MOD_LOG2_MAX - NTT_MOD_LOG2_MIN));\n                a0 &= ((limb_t)1 << (LIMB_BITS - NTT_MOD_LOG2_MAX + NTT_MOD_LOG2_MIN)) - 1;\n            }\n        }\n        for(j = 0; j < nb_mods; j++) {\n            m = ntt_mods[first_m_idx + j];\n            m_inv = s->ntt_mods_div[first_m_idx + j];\n            r = mod_fast(a, m, m_inv);\n            if (dpl > (LIMB_BITS + NTT_MOD_LOG2_MIN)) {\n                b = ((dlimb_t)r << (LIMB_BITS - NTT_MOD_LOG2_MAX + NTT_MOD_LOG2_MIN)) | a0;\n                r = mod_fast(b, m, m_inv);\n            }\n            tabr[i + j * fft_len] = int_to_ntt_limb(r, m);\n        }\n    }\n}\n\n#if defined(__AVX2__)\n\n#define VEC_LEN 4\n\ntypedef union {\n    __m256d v;\n    double d[4];\n} VecUnion;\n\nstatic no_inline void ntt_to_limb(BFNTTState *s, limb_t *tabr, limb_t r_len,\n                                  const NTTLimb *buf, int fft_len_log2, int dpl,\n                                  int nb_mods)\n{\n    const limb_t *mods = ntt_mods + NB_MODS - nb_mods;\n    const __m256d *mods_cr_vec, *mf, *m_inv;\n    VecUnion y[NB_MODS];\n    limb_t u[NB_MODS], carry[NB_MODS], fft_len, base_mask1, r;\n    slimb_t i, len, pos;\n    int j, k, l, shift, n_limb1, p;\n    dlimb_t t;\n        \n    j = NB_MODS * (NB_MODS - 1) / 2 - nb_mods * (nb_mods - 1) / 2;\n    mods_cr_vec = s->ntt_mods_cr_vec + j;\n    mf = s->ntt_mods_vec + NB_MODS - nb_mods;\n    m_inv = s->ntt_mods_inv_vec + NB_MODS - nb_mods;\n        \n    shift = dpl & (LIMB_BITS - 1);\n    if (shift == 0)\n        base_mask1 = -1;\n    else\n        base_mask1 = ((limb_t)1 << shift) - 1;\n    n_limb1 = ((unsigned)dpl - 1) / LIMB_BITS;\n    for(j = 0; j < NB_MODS; j++) \n        carry[j] = 0;\n    for(j = 0; j < NB_MODS; j++) \n        u[j] = 0; /* avoid warnings */\n    memset(tabr, 0, sizeof(limb_t) * r_len);\n    fft_len = (limb_t)1 << fft_len_log2;\n    len = bf_min(fft_len, (r_len * LIMB_BITS + dpl - 1) / dpl);\n    len = (len + VEC_LEN - 1) & ~(VEC_LEN - 1);\n    i = 0;\n    while (i < len) {\n        for(j = 0; j < nb_mods; j++)\n            y[j].v = *(__m256d *)&buf[i + fft_len * j];\n\n        /* Chinese remainder to get mixed radix representation */\n        l = 0;\n        for(j = 0; j < nb_mods - 1; j++) {\n            y[j].v = ntt_mod1(y[j].v, mf[j]);\n            for(k = j + 1; k < nb_mods; k++) {\n                y[k].v = ntt_mul_mod(y[k].v - y[j].v,\n                                     mods_cr_vec[l], mf[k], m_inv[k]);\n                l++;\n            }\n        }\n        y[j].v = ntt_mod1(y[j].v, mf[j]);\n        \n        for(p = 0; p < VEC_LEN; p++) {\n            /* back to normal representation */\n            u[0] = (int64_t)y[nb_mods - 1].d[p];\n            l = 1;\n            for(j = nb_mods - 2; j >= 1; j--) {\n                r = (int64_t)y[j].d[p];\n                for(k = 0; k < l; k++) {\n                    t = (dlimb_t)u[k] * mods[j] + r;\n                    r = t >> LIMB_BITS;\n                    u[k] = t;\n                }\n                u[l] = r;\n                l++;\n            }\n            /* XXX: for nb_mods = 5, l should be 4 */\n            \n            /* last step adds the carry */\n            r = (int64_t)y[0].d[p];\n            for(k = 0; k < l; k++) {\n                t = (dlimb_t)u[k] * mods[j] + r + carry[k];\n                r = t >> LIMB_BITS;\n                u[k] = t;\n            }\n            u[l] = r + carry[l];\n\n#if 0\n            printf(\"%\" PRId64 \": \", i);\n            for(j = nb_mods - 1; j >= 0; j--) {\n                printf(\" %019\" PRIu64, u[j]);\n            }\n            printf(\"\\n\");\n#endif\n            \n            /* write the digits */\n            pos = i * dpl;\n            for(j = 0; j < n_limb1; j++) {\n                put_bits(tabr, r_len, pos, u[j]);\n                pos += LIMB_BITS;\n            }\n            put_bits(tabr, r_len, pos, u[n_limb1] & base_mask1);\n            /* shift by dpl digits and set the carry */\n            if (shift == 0) {\n                for(j = n_limb1 + 1; j < nb_mods; j++)\n                    carry[j - (n_limb1 + 1)] = u[j];\n            } else {\n                for(j = n_limb1; j < nb_mods - 1; j++) {\n                    carry[j - n_limb1] = (u[j] >> shift) |\n                        (u[j + 1] << (LIMB_BITS - shift));\n                }\n                carry[nb_mods - 1 - n_limb1] = u[nb_mods - 1] >> shift;\n            }\n            i++;\n        }\n    }\n}\n#else\nstatic no_inline void ntt_to_limb(BFNTTState *s, limb_t *tabr, limb_t r_len,\n                                  const NTTLimb *buf, int fft_len_log2, int dpl,\n                                  int nb_mods)\n{\n    const limb_t *mods = ntt_mods + NB_MODS - nb_mods;\n    const limb_t *mods_cr, *mods_cr_inv;\n    limb_t y[NB_MODS], u[NB_MODS], carry[NB_MODS], fft_len, base_mask1, r;\n    slimb_t i, len, pos;\n    int j, k, l, shift, n_limb1;\n    dlimb_t t;\n        \n    j = NB_MODS * (NB_MODS - 1) / 2 - nb_mods * (nb_mods - 1) / 2;\n    mods_cr = ntt_mods_cr + j;\n    mods_cr_inv = s->ntt_mods_cr_inv + j;\n\n    shift = dpl & (LIMB_BITS - 1);\n    if (shift == 0)\n        base_mask1 = -1;\n    else\n        base_mask1 = ((limb_t)1 << shift) - 1;\n    n_limb1 = ((unsigned)dpl - 1) / LIMB_BITS;\n    for(j = 0; j < NB_MODS; j++) \n        carry[j] = 0;\n    for(j = 0; j < NB_MODS; j++) \n        u[j] = 0; /* avoid warnings */\n    memset(tabr, 0, sizeof(limb_t) * r_len);\n    fft_len = (limb_t)1 << fft_len_log2;\n    len = bf_min(fft_len, (r_len * LIMB_BITS + dpl - 1) / dpl);\n    for(i = 0; i < len; i++) {\n        for(j = 0; j < nb_mods; j++)  {\n            y[j] = ntt_limb_to_int(buf[i + fft_len * j], mods[j]);\n        }\n\n        /* Chinese remainder to get mixed radix representation */\n        l = 0;\n        for(j = 0; j < nb_mods - 1; j++) {\n            for(k = j + 1; k < nb_mods; k++) {\n                limb_t m;\n                m = mods[k];\n                /* Note: there is no overflow in the sub_mod() because\n                   the modulos are sorted by increasing order */\n                y[k] = mul_mod_fast2(y[k] - y[j] + m, \n                                     mods_cr[l], m, mods_cr_inv[l]);\n                l++;\n            }\n        }\n        \n        /* back to normal representation */\n        u[0] = y[nb_mods - 1];\n        l = 1;\n        for(j = nb_mods - 2; j >= 1; j--) {\n            r = y[j];\n            for(k = 0; k < l; k++) {\n                t = (dlimb_t)u[k] * mods[j] + r;\n                r = t >> LIMB_BITS;\n                u[k] = t;\n            }\n            u[l] = r;\n            l++;\n        }\n        \n        /* last step adds the carry */\n        r = y[0];\n        for(k = 0; k < l; k++) {\n            t = (dlimb_t)u[k] * mods[j] + r + carry[k];\n            r = t >> LIMB_BITS;\n            u[k] = t;\n        }\n        u[l] = r + carry[l];\n\n#if 0\n        printf(\"%\" PRId64 \": \", (int64_t)i);\n        for(j = nb_mods - 1; j >= 0; j--) {\n            printf(\" \" FMT_LIMB, u[j]);\n        }\n        printf(\"\\n\");\n#endif\n        \n        /* write the digits */\n        pos = i * dpl;\n        for(j = 0; j < n_limb1; j++) {\n            put_bits(tabr, r_len, pos, u[j]);\n            pos += LIMB_BITS;\n        }\n        put_bits(tabr, r_len, pos, u[n_limb1] & base_mask1);\n        /* shift by dpl digits and set the carry */\n        if (shift == 0) {\n            for(j = n_limb1 + 1; j < nb_mods; j++)\n                carry[j - (n_limb1 + 1)] = u[j];\n        } else {\n            for(j = n_limb1; j < nb_mods - 1; j++) {\n                carry[j - n_limb1] = (u[j] >> shift) |\n                    (u[j + 1] << (LIMB_BITS - shift));\n            }\n            carry[nb_mods - 1 - n_limb1] = u[nb_mods - 1] >> shift;\n        }\n    }\n}\n#endif\n\nstatic int ntt_static_init(bf_context_t *s1)\n{\n    BFNTTState *s;\n    int inverse, i, j, k, l;\n    limb_t c, c_inv, c_inv2, m, m_inv;\n\n    if (s1->ntt_state)\n        return 0;\n#if defined(__AVX2__)\n    s = bf_aligned_malloc(s1, sizeof(*s), 64);\n#else\n    s = bf_malloc(s1, sizeof(*s));\n#endif\n    if (!s)\n        return -1;\n    memset(s, 0, sizeof(*s));\n    s1->ntt_state = s;\n    s->ctx = s1;\n    \n    for(j = 0; j < NB_MODS; j++) {\n        m = ntt_mods[j];\n        m_inv = init_mul_mod_fast(m);\n        s->ntt_mods_div[j] = m_inv;\n#if defined(__AVX2__)\n        s->ntt_mods_vec[j] = _mm256_set1_pd(m);\n        s->ntt_mods_inv_vec[j] = _mm256_set1_pd(1.0 / (double)m);\n#endif\n        c_inv2 = (m + 1) / 2; /* 1/2 */\n        c_inv = 1;\n        for(i = 0; i <= NTT_PROOT_2EXP; i++) {\n            s->ntt_len_inv[j][i][0] = c_inv;\n            s->ntt_len_inv[j][i][1] = init_mul_mod_fast2(c_inv, m);\n            c_inv = mul_mod_fast(c_inv, c_inv2, m, m_inv);\n        }\n\n        for(inverse = 0; inverse < 2; inverse++) {\n            c = ntt_proot[inverse][j];\n            for(i = 0; i < NTT_PROOT_2EXP; i++) {\n                s->ntt_proot_pow[j][inverse][NTT_PROOT_2EXP - i] = c;\n                s->ntt_proot_pow_inv[j][inverse][NTT_PROOT_2EXP - i] =\n                    init_mul_mod_fast2(c, m);\n                c = mul_mod_fast(c, c, m, m_inv);\n            }\n        }\n    }\n\n    l = 0;\n    for(j = 0; j < NB_MODS - 1; j++) {\n        for(k = j + 1; k < NB_MODS; k++) {\n#if defined(__AVX2__)\n            s->ntt_mods_cr_vec[l] = _mm256_set1_pd(int_to_ntt_limb2(ntt_mods_cr[l],\n                                                                    ntt_mods[k]));\n#else\n            s->ntt_mods_cr_inv[l] = init_mul_mod_fast2(ntt_mods_cr[l],\n                                                       ntt_mods[k]);\n#endif\n            l++;\n        }\n    }\n    return 0;\n}\n\nint bf_get_fft_size(int *pdpl, int *pnb_mods, limb_t len)\n{\n    int dpl, fft_len_log2, n_bits, nb_mods, dpl_found, fft_len_log2_found;\n    int int_bits, nb_mods_found;\n    limb_t cost, min_cost;\n    \n    min_cost = -1;\n    dpl_found = 0;\n    nb_mods_found = 4;\n    fft_len_log2_found = 0;\n    for(nb_mods = 3; nb_mods <= NB_MODS; nb_mods++) {\n        int_bits = ntt_int_bits[NB_MODS - nb_mods];\n        dpl = bf_min((int_bits - 4) / 2,\n                     2 * LIMB_BITS + 2 * NTT_MOD_LOG2_MIN - NTT_MOD_LOG2_MAX);\n        for(;;) {\n            fft_len_log2 = ceil_log2((len * LIMB_BITS + dpl - 1) / dpl);\n            if (fft_len_log2 > NTT_PROOT_2EXP)\n                goto next;\n            n_bits = fft_len_log2 + 2 * dpl;\n            if (n_bits <= int_bits) {\n                cost = ((limb_t)(fft_len_log2 + 1) << fft_len_log2) * nb_mods;\n                //                printf(\"n=%d dpl=%d: cost=%\" PRId64 \"\\n\", nb_mods, dpl, (int64_t)cost);\n                if (cost < min_cost) {\n                    min_cost = cost;\n                    dpl_found = dpl;\n                    nb_mods_found = nb_mods;\n                    fft_len_log2_found = fft_len_log2;\n                }\n                break;\n            }\n            dpl--;\n            if (dpl == 0)\n                break;\n        }\n    next: ;\n    }\n    if (!dpl_found)\n        abort();\n    /* limit dpl if possible to reduce fixed cost of limb/NTT conversion */\n    if (dpl_found > (LIMB_BITS + NTT_MOD_LOG2_MIN) &&\n        ((limb_t)(LIMB_BITS + NTT_MOD_LOG2_MIN) << fft_len_log2_found) >=\n        len * LIMB_BITS) {\n        dpl_found = LIMB_BITS + NTT_MOD_LOG2_MIN;\n    }\n    *pnb_mods = nb_mods_found;\n    *pdpl = dpl_found;\n    return fft_len_log2_found;\n}\n\n/* return 0 if OK, -1 if memory error */\nstatic no_inline int fft_mul(bf_context_t *s1,\n                             bf_t *res, limb_t *a_tab, limb_t a_len,\n                             limb_t *b_tab, limb_t b_len, int mul_flags)\n{\n    BFNTTState *s;\n    int dpl, fft_len_log2, j, nb_mods, reduced_mem;\n    slimb_t len, fft_len;\n    NTTLimb *buf1, *buf2, *ptr;\n#if defined(USE_MUL_CHECK)\n    limb_t ha, hb, hr, h_ref;\n#endif\n    \n    if (ntt_static_init(s1))\n        return -1;\n    s = s1->ntt_state;\n    \n    /* find the optimal number of digits per limb (dpl) */\n    len = a_len + b_len;\n    fft_len_log2 = bf_get_fft_size(&dpl, &nb_mods, len);\n    fft_len = (uint64_t)1 << fft_len_log2;\n    //    printf(\"len=%\" PRId64 \" fft_len_log2=%d dpl=%d\\n\", len, fft_len_log2, dpl);\n#if defined(USE_MUL_CHECK)\n    ha = mp_mod1(a_tab, a_len, BF_CHKSUM_MOD, 0);\n    hb = mp_mod1(b_tab, b_len, BF_CHKSUM_MOD, 0);\n#endif\n    if ((mul_flags & (FFT_MUL_R_OVERLAP_A | FFT_MUL_R_OVERLAP_B)) == 0) {\n        if (!(mul_flags & FFT_MUL_R_NORESIZE))\n            bf_resize(res, 0);\n    } else if (mul_flags & FFT_MUL_R_OVERLAP_B) {\n        limb_t *tmp_tab, tmp_len;\n        /* it is better to free 'b' first */\n        tmp_tab = a_tab;\n        a_tab = b_tab;\n        b_tab = tmp_tab;\n        tmp_len = a_len;\n        a_len = b_len;\n        b_len = tmp_len;\n    }\n    buf1 = ntt_malloc(s, sizeof(NTTLimb) * fft_len * nb_mods);\n    if (!buf1)\n        return -1;\n    limb_to_ntt(s, buf1, fft_len, a_tab, a_len, dpl,\n                NB_MODS - nb_mods, nb_mods);\n    if ((mul_flags & (FFT_MUL_R_OVERLAP_A | FFT_MUL_R_OVERLAP_B)) == \n        FFT_MUL_R_OVERLAP_A) {\n        if (!(mul_flags & FFT_MUL_R_NORESIZE))\n            bf_resize(res, 0);\n    }\n    reduced_mem = (fft_len_log2 >= 14);\n    if (!reduced_mem) {\n        buf2 = ntt_malloc(s, sizeof(NTTLimb) * fft_len * nb_mods);\n        if (!buf2)\n            goto fail;\n        limb_to_ntt(s, buf2, fft_len, b_tab, b_len, dpl,\n                    NB_MODS - nb_mods, nb_mods);\n        if (!(mul_flags & FFT_MUL_R_NORESIZE))\n            bf_resize(res, 0); /* in case res == b */\n    } else {\n        buf2 = ntt_malloc(s, sizeof(NTTLimb) * fft_len);\n        if (!buf2)\n            goto fail;\n    }\n    for(j = 0; j < nb_mods; j++) {\n        if (reduced_mem) {\n            limb_to_ntt(s, buf2, fft_len, b_tab, b_len, dpl,\n                        NB_MODS - nb_mods + j, 1);\n            ptr = buf2;\n        } else {\n            ptr = buf2 + fft_len * j;\n        }\n        if (ntt_conv(s, buf1 + fft_len * j, ptr,\n                     fft_len_log2, fft_len_log2, j + NB_MODS - nb_mods))\n            goto fail;\n    }\n    if (!(mul_flags & FFT_MUL_R_NORESIZE))\n        bf_resize(res, 0); /* in case res == b and reduced mem */\n    ntt_free(s, buf2);\n    buf2 = NULL;\n    if (!(mul_flags & FFT_MUL_R_NORESIZE)) {\n        if (bf_resize(res, len))\n            goto fail;\n    }\n    ntt_to_limb(s, res->tab, len, buf1, fft_len_log2, dpl, nb_mods);\n    ntt_free(s, buf1);\n#if defined(USE_MUL_CHECK)\n    hr = mp_mod1(res->tab, len, BF_CHKSUM_MOD, 0);\n    h_ref = mul_mod(ha, hb, BF_CHKSUM_MOD);\n    if (hr != h_ref) {\n        printf(\"ntt_mul_error: len=%\" PRId_LIMB \" fft_len_log2=%d dpl=%d nb_mods=%d\\n\",\n               len, fft_len_log2, dpl, nb_mods);\n        //        printf(\"ha=0x\" FMT_LIMB\" hb=0x\" FMT_LIMB \" hr=0x\" FMT_LIMB \" expected=0x\" FMT_LIMB \"\\n\", ha, hb, hr, h_ref);\n        exit(1);\n    }\n#endif    \n    return 0;\n fail:\n    ntt_free(s, buf1);\n    ntt_free(s, buf2);\n    return -1;\n}\n\n#else /* USE_FFT_MUL */\n\nint bf_get_fft_size(int *pdpl, int *pnb_mods, limb_t len)\n{\n    return 0;\n}\n\n#endif /* !USE_FFT_MUL */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/libbf.h",
    "content": "/*\n * Tiny arbitrary precision floating point library\n * \n * Copyright (c) 2017-2021 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#ifndef LIBBF_H\n#define LIBBF_H\n\n#include <stddef.h>\n#include <stdint.h>\n\n#if INTPTR_MAX >= INT64_MAX\n#define LIMB_LOG2_BITS 6\n#else\n#define LIMB_LOG2_BITS 5\n#endif\n\n#define LIMB_BITS (1 << LIMB_LOG2_BITS)\n\n#if LIMB_BITS == 64\ntypedef __int128 int128_t;\ntypedef unsigned __int128 uint128_t;\ntypedef int64_t slimb_t;\ntypedef uint64_t limb_t;\ntypedef uint128_t dlimb_t;\n#define BF_RAW_EXP_MIN INT64_MIN\n#define BF_RAW_EXP_MAX INT64_MAX\n\n#define LIMB_DIGITS 19\n#define BF_DEC_BASE UINT64_C(10000000000000000000)\n\n#else\n\ntypedef int32_t slimb_t;\ntypedef uint32_t limb_t;\ntypedef uint64_t dlimb_t;\n#define BF_RAW_EXP_MIN INT32_MIN\n#define BF_RAW_EXP_MAX INT32_MAX\n\n#define LIMB_DIGITS 9\n#define BF_DEC_BASE 1000000000U\n\n#endif\n\n/* in bits */\n/* minimum number of bits for the exponent */\n#define BF_EXP_BITS_MIN 3\n/* maximum number of bits for the exponent */\n#define BF_EXP_BITS_MAX (LIMB_BITS - 3)\n/* extended range for exponent, used internally */\n#define BF_EXT_EXP_BITS_MAX (BF_EXP_BITS_MAX + 1)\n/* minimum possible precision */\n#define BF_PREC_MIN 2\n/* minimum possible precision */\n#define BF_PREC_MAX (((limb_t)1 << (LIMB_BITS - 2)) - 2)\n/* some operations support infinite precision */\n#define BF_PREC_INF (BF_PREC_MAX + 1) /* infinite precision */\n\n#if LIMB_BITS == 64\n#define BF_CHKSUM_MOD (UINT64_C(975620677) * UINT64_C(9795002197))\n#else\n#define BF_CHKSUM_MOD 975620677U\n#endif\n\n#define BF_EXP_ZERO BF_RAW_EXP_MIN\n#define BF_EXP_INF (BF_RAW_EXP_MAX - 1)\n#define BF_EXP_NAN BF_RAW_EXP_MAX\n\n/* +/-zero is represented with expn = BF_EXP_ZERO and len = 0,\n   +/-infinity is represented with expn = BF_EXP_INF and len = 0,\n   NaN is represented with expn = BF_EXP_NAN and len = 0 (sign is ignored)\n */\ntypedef struct {\n    struct bf_context_t *ctx;\n    int sign;\n    slimb_t expn;\n    limb_t len;\n    limb_t *tab;\n} bf_t;\n\ntypedef struct {\n    /* must be kept identical to bf_t */\n    struct bf_context_t *ctx;\n    int sign;\n    slimb_t expn;\n    limb_t len;\n    limb_t *tab;\n} bfdec_t;\n\ntypedef enum {\n    BF_RNDN, /* round to nearest, ties to even */\n    BF_RNDZ, /* round to zero */\n    BF_RNDD, /* round to -inf (the code relies on (BF_RNDD xor BF_RNDU) = 1) */\n    BF_RNDU, /* round to +inf */\n    BF_RNDNA, /* round to nearest, ties away from zero */\n    BF_RNDA, /* round away from zero */\n    BF_RNDF, /* faithful rounding (nondeterministic, either RNDD or RNDU,\n                inexact flag is always set)  */\n} bf_rnd_t;\n\n/* allow subnormal numbers. Only available if the number of exponent\n   bits is <= BF_EXP_BITS_USER_MAX and prec != BF_PREC_INF. */\n#define BF_FLAG_SUBNORMAL (1 << 3)\n/* 'prec' is the precision after the radix point instead of the whole\n   mantissa. Can only be used with bf_round() and\n   bfdec_[add|sub|mul|div|sqrt|round](). */\n#define BF_FLAG_RADPNT_PREC (1 << 4)\n\n#define BF_RND_MASK 0x7\n#define BF_EXP_BITS_SHIFT 5\n#define BF_EXP_BITS_MASK 0x3f\n\n/* shortcut for bf_set_exp_bits(BF_EXT_EXP_BITS_MAX) */\n#define BF_FLAG_EXT_EXP (BF_EXP_BITS_MASK << BF_EXP_BITS_SHIFT)\n\n/* contains the rounding mode and number of exponents bits */\ntypedef uint32_t bf_flags_t;\n\ntypedef void *bf_realloc_func_t(void *opaque, void *ptr, size_t size);\n\ntypedef struct {\n    bf_t val;\n    limb_t prec;\n} BFConstCache;\n\ntypedef struct bf_context_t {\n    void *realloc_opaque;\n    bf_realloc_func_t *realloc_func;\n    BFConstCache log2_cache;\n    BFConstCache pi_cache;\n    struct BFNTTState *ntt_state;\n} bf_context_t;\n\nstatic inline int bf_get_exp_bits(bf_flags_t flags)\n{\n    int e;\n    e = (flags >> BF_EXP_BITS_SHIFT) & BF_EXP_BITS_MASK;\n    if (e == BF_EXP_BITS_MASK)\n        return BF_EXP_BITS_MAX + 1;\n    else\n        return BF_EXP_BITS_MAX - e;\n}\n\nstatic inline bf_flags_t bf_set_exp_bits(int n)\n{\n    return ((BF_EXP_BITS_MAX - n) & BF_EXP_BITS_MASK) << BF_EXP_BITS_SHIFT;\n}\n\n/* returned status */\n#define BF_ST_INVALID_OP  (1 << 0)\n#define BF_ST_DIVIDE_ZERO (1 << 1)\n#define BF_ST_OVERFLOW    (1 << 2)\n#define BF_ST_UNDERFLOW   (1 << 3)\n#define BF_ST_INEXACT     (1 << 4)\n/* indicate that a memory allocation error occured. NaN is returned */\n#define BF_ST_MEM_ERROR   (1 << 5) \n\n#define BF_RADIX_MAX 36 /* maximum radix for bf_atof() and bf_ftoa() */\n\nstatic inline slimb_t bf_max(slimb_t a, slimb_t b)\n{\n    if (a > b)\n        return a;\n    else\n        return b;\n}\n\nstatic inline slimb_t bf_min(slimb_t a, slimb_t b)\n{\n    if (a < b)\n        return a;\n    else\n        return b;\n}\n\nvoid bf_context_init(bf_context_t *s, bf_realloc_func_t *realloc_func,\n                     void *realloc_opaque);\nvoid bf_context_end(bf_context_t *s);\n/* free memory allocated for the bf cache data */\nvoid bf_clear_cache(bf_context_t *s);\n\nstatic inline void *bf_realloc(bf_context_t *s, void *ptr, size_t size)\n{\n    return s->realloc_func(s->realloc_opaque, ptr, size);\n}\n\n/* 'size' must be != 0 */\nstatic inline void *bf_malloc(bf_context_t *s, size_t size)\n{\n    return bf_realloc(s, NULL, size);\n}\n\nstatic inline void bf_free(bf_context_t *s, void *ptr)\n{\n    /* must test ptr otherwise equivalent to malloc(0) */\n    if (ptr)\n        bf_realloc(s, ptr, 0);\n}\n\nvoid bf_init(bf_context_t *s, bf_t *r);\n\nstatic inline void bf_delete(bf_t *r)\n{\n    bf_context_t *s = r->ctx;\n    /* we accept to delete a zeroed bf_t structure */\n    if (s && r->tab) {\n        bf_realloc(s, r->tab, 0);\n    }\n}\n\nstatic inline void bf_neg(bf_t *r)\n{\n    r->sign ^= 1;\n}\n\nstatic inline int bf_is_finite(const bf_t *a)\n{\n    return (a->expn < BF_EXP_INF);\n}\n\nstatic inline int bf_is_nan(const bf_t *a)\n{\n    return (a->expn == BF_EXP_NAN);\n}\n\nstatic inline int bf_is_zero(const bf_t *a)\n{\n    return (a->expn == BF_EXP_ZERO);\n}\n\nstatic inline void bf_memcpy(bf_t *r, const bf_t *a)\n{\n    *r = *a;\n}\n\nint bf_set_ui(bf_t *r, uint64_t a);\nint bf_set_si(bf_t *r, int64_t a);\nvoid bf_set_nan(bf_t *r);\nvoid bf_set_zero(bf_t *r, int is_neg);\nvoid bf_set_inf(bf_t *r, int is_neg);\nint bf_set(bf_t *r, const bf_t *a);\nvoid bf_move(bf_t *r, bf_t *a);\nint bf_get_float64(const bf_t *a, double *pres, bf_rnd_t rnd_mode);\nint bf_set_float64(bf_t *a, double d);\n\nint bf_cmpu(const bf_t *a, const bf_t *b);\nint bf_cmp_full(const bf_t *a, const bf_t *b);\nint bf_cmp(const bf_t *a, const bf_t *b);\nstatic inline int bf_cmp_eq(const bf_t *a, const bf_t *b)\n{\n    return bf_cmp(a, b) == 0;\n}\n\nstatic inline int bf_cmp_le(const bf_t *a, const bf_t *b)\n{\n    return bf_cmp(a, b) <= 0;\n}\n\nstatic inline int bf_cmp_lt(const bf_t *a, const bf_t *b)\n{\n    return bf_cmp(a, b) < 0;\n}\n\nint bf_add(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags);\nint bf_sub(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags);\nint bf_add_si(bf_t *r, const bf_t *a, int64_t b1, limb_t prec, bf_flags_t flags);\nint bf_mul(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags);\nint bf_mul_ui(bf_t *r, const bf_t *a, uint64_t b1, limb_t prec, bf_flags_t flags);\nint bf_mul_si(bf_t *r, const bf_t *a, int64_t b1, limb_t prec, \n              bf_flags_t flags);\nint bf_mul_2exp(bf_t *r, slimb_t e, limb_t prec, bf_flags_t flags);\nint bf_div(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec, bf_flags_t flags);\n#define BF_DIVREM_EUCLIDIAN BF_RNDF\nint bf_divrem(bf_t *q, bf_t *r, const bf_t *a, const bf_t *b,\n              limb_t prec, bf_flags_t flags, int rnd_mode);\nint bf_rem(bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n           bf_flags_t flags, int rnd_mode);\nint bf_remquo(slimb_t *pq, bf_t *r, const bf_t *a, const bf_t *b, limb_t prec,\n              bf_flags_t flags, int rnd_mode);\n/* round to integer with infinite precision */\nint bf_rint(bf_t *r, int rnd_mode);\nint bf_round(bf_t *r, limb_t prec, bf_flags_t flags);\nint bf_sqrtrem(bf_t *r, bf_t *rem1, const bf_t *a);\nint bf_sqrt(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\nslimb_t bf_get_exp_min(const bf_t *a);\nint bf_logic_or(bf_t *r, const bf_t *a, const bf_t *b);\nint bf_logic_xor(bf_t *r, const bf_t *a, const bf_t *b);\nint bf_logic_and(bf_t *r, const bf_t *a, const bf_t *b);\n\n/* additional flags for bf_atof */\n/* do not accept hex radix prefix (0x or 0X) if radix = 0 or radix = 16 */\n#define BF_ATOF_NO_HEX       (1 << 16)\n/* accept binary (0b or 0B) or octal (0o or 0O) radix prefix if radix = 0 */\n#define BF_ATOF_BIN_OCT      (1 << 17)\n/* Do not parse NaN or Inf */\n#define BF_ATOF_NO_NAN_INF   (1 << 18)\n/* return the exponent separately */\n#define BF_ATOF_EXPONENT       (1 << 19)\n\nint bf_atof(bf_t *a, const char *str, const char **pnext, int radix,\n            limb_t prec, bf_flags_t flags);\n/* this version accepts prec = BF_PREC_INF and returns the radix\n   exponent */\nint bf_atof2(bf_t *r, slimb_t *pexponent,\n             const char *str, const char **pnext, int radix,\n             limb_t prec, bf_flags_t flags);\nint bf_mul_pow_radix(bf_t *r, const bf_t *T, limb_t radix,\n                     slimb_t expn, limb_t prec, bf_flags_t flags);\n\n\n/* Conversion of floating point number to string. Return a null\n   terminated string or NULL if memory error. *plen contains its\n   length if plen != NULL.  The exponent letter is \"e\" for base 10,\n   \"p\" for bases 2, 8, 16 with a binary exponent and \"@\" for the other\n   bases. */\n\n#define BF_FTOA_FORMAT_MASK (3 << 16)\n\n/* fixed format: prec significant digits rounded with (flags &\n   BF_RND_MASK). Exponential notation is used if too many zeros are\n   needed.*/\n#define BF_FTOA_FORMAT_FIXED (0 << 16)\n/* fractional format: prec digits after the decimal point rounded with\n   (flags & BF_RND_MASK) */\n#define BF_FTOA_FORMAT_FRAC  (1 << 16)\n/* free format: \n   \n   For binary radices with bf_ftoa() and for bfdec_ftoa(): use the minimum\n   number of digits to represent 'a'. The precision and the rounding\n   mode are ignored.\n   \n   For the non binary radices with bf_ftoa(): use as many digits as\n   necessary so that bf_atof() return the same number when using\n   precision 'prec', rounding to nearest and the subnormal\n   configuration of 'flags'. The result is meaningful only if 'a' is\n   already rounded to 'prec' bits. If the subnormal flag is set, the\n   exponent in 'flags' must also be set to the desired exponent range.\n*/\n#define BF_FTOA_FORMAT_FREE  (2 << 16)\n/* same as BF_FTOA_FORMAT_FREE but uses the minimum number of digits\n   (takes more computation time). Identical to BF_FTOA_FORMAT_FREE for\n   binary radices with bf_ftoa() and for bfdec_ftoa(). */\n#define BF_FTOA_FORMAT_FREE_MIN (3 << 16)\n\n/* force exponential notation for fixed or free format */\n#define BF_FTOA_FORCE_EXP    (1 << 20)\n/* add 0x prefix for base 16, 0o prefix for base 8 or 0b prefix for\n   base 2 if non zero value */\n#define BF_FTOA_ADD_PREFIX   (1 << 21)\n/* return \"Infinity\" instead of \"Inf\" and add a \"+\" for positive\n   exponents */\n#define BF_FTOA_JS_QUIRKS    (1 << 22)\n\nchar *bf_ftoa(size_t *plen, const bf_t *a, int radix, limb_t prec,\n              bf_flags_t flags);\n\n/* modulo 2^n instead of saturation. NaN and infinity return 0 */\n#define BF_GET_INT_MOD (1 << 0) \nint bf_get_int32(int *pres, const bf_t *a, int flags);\nint bf_get_int64(int64_t *pres, const bf_t *a, int flags);\nint bf_get_uint64(uint64_t *pres, const bf_t *a);\n\n/* the following functions are exported for testing only. */\nvoid mp_print_str(const char *str, const limb_t *tab, limb_t n);\nvoid bf_print_str(const char *str, const bf_t *a);\nint bf_resize(bf_t *r, limb_t len);\nint bf_get_fft_size(int *pdpl, int *pnb_mods, limb_t len);\nint bf_normalize_and_round(bf_t *r, limb_t prec1, bf_flags_t flags);\nint bf_can_round(const bf_t *a, slimb_t prec, bf_rnd_t rnd_mode, slimb_t k);\nslimb_t bf_mul_log2_radix(slimb_t a1, unsigned int radix, int is_inv,\n                          int is_ceil1);\nint mp_mul(bf_context_t *s, limb_t *result, \n           const limb_t *op1, limb_t op1_size, \n           const limb_t *op2, limb_t op2_size);\nlimb_t mp_add(limb_t *res, const limb_t *op1, const limb_t *op2, \n              limb_t n, limb_t carry);\nlimb_t mp_add_ui(limb_t *tab, limb_t b, size_t n);\nint mp_sqrtrem(bf_context_t *s, limb_t *tabs, limb_t *taba, limb_t n);\nint mp_recip(bf_context_t *s, limb_t *tabr, const limb_t *taba, limb_t n);\nlimb_t bf_isqrt(limb_t a);\n\n/* transcendental functions */\nint bf_const_log2(bf_t *T, limb_t prec, bf_flags_t flags);\nint bf_const_pi(bf_t *T, limb_t prec, bf_flags_t flags);\nint bf_exp(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\nint bf_log(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\n#define BF_POW_JS_QUIRKS (1 << 16) /* (+/-1)^(+/-Inf) = NaN, 1^NaN = NaN */\nint bf_pow(bf_t *r, const bf_t *x, const bf_t *y, limb_t prec, bf_flags_t flags);\nint bf_cos(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\nint bf_sin(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\nint bf_tan(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\nint bf_atan(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\nint bf_atan2(bf_t *r, const bf_t *y, const bf_t *x,\n             limb_t prec, bf_flags_t flags);\nint bf_asin(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\nint bf_acos(bf_t *r, const bf_t *a, limb_t prec, bf_flags_t flags);\n\n/* decimal floating point */\n\nstatic inline void bfdec_init(bf_context_t *s, bfdec_t *r)\n{\n    bf_init(s, (bf_t *)r);\n}\nstatic inline void bfdec_delete(bfdec_t *r)\n{\n    bf_delete((bf_t *)r);\n}\n\nstatic inline void bfdec_neg(bfdec_t *r)\n{\n    r->sign ^= 1;\n}\n\nstatic inline int bfdec_is_finite(const bfdec_t *a)\n{\n    return (a->expn < BF_EXP_INF);\n}\n\nstatic inline int bfdec_is_nan(const bfdec_t *a)\n{\n    return (a->expn == BF_EXP_NAN);\n}\n\nstatic inline int bfdec_is_zero(const bfdec_t *a)\n{\n    return (a->expn == BF_EXP_ZERO);\n}\n\nstatic inline void bfdec_memcpy(bfdec_t *r, const bfdec_t *a)\n{\n    bf_memcpy((bf_t *)r, (const bf_t *)a);\n}\n\nint bfdec_set_ui(bfdec_t *r, uint64_t a);\nint bfdec_set_si(bfdec_t *r, int64_t a);\n\nstatic inline void bfdec_set_nan(bfdec_t *r)\n{\n    bf_set_nan((bf_t *)r);\n}\nstatic inline void bfdec_set_zero(bfdec_t *r, int is_neg)\n{\n    bf_set_zero((bf_t *)r, is_neg);\n}\nstatic inline void bfdec_set_inf(bfdec_t *r, int is_neg)\n{\n    bf_set_inf((bf_t *)r, is_neg);\n}\nstatic inline int bfdec_set(bfdec_t *r, const bfdec_t *a)\n{\n    return bf_set((bf_t *)r, (bf_t *)a);\n}\nstatic inline void bfdec_move(bfdec_t *r, bfdec_t *a)\n{\n    bf_move((bf_t *)r, (bf_t *)a);\n}\nstatic inline int bfdec_cmpu(const bfdec_t *a, const bfdec_t *b)\n{\n    return bf_cmpu((const bf_t *)a, (const bf_t *)b);\n}\nstatic inline int bfdec_cmp_full(const bfdec_t *a, const bfdec_t *b)\n{\n    return bf_cmp_full((const bf_t *)a, (const bf_t *)b);\n}\nstatic inline int bfdec_cmp(const bfdec_t *a, const bfdec_t *b)\n{\n    return bf_cmp((const bf_t *)a, (const bf_t *)b);\n}\nstatic inline int bfdec_cmp_eq(const bfdec_t *a, const bfdec_t *b)\n{\n    return bfdec_cmp(a, b) == 0;\n}\nstatic inline int bfdec_cmp_le(const bfdec_t *a, const bfdec_t *b)\n{\n    return bfdec_cmp(a, b) <= 0;\n}\nstatic inline int bfdec_cmp_lt(const bfdec_t *a, const bfdec_t *b)\n{\n    return bfdec_cmp(a, b) < 0;\n}\n\nint bfdec_add(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags);\nint bfdec_sub(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags);\nint bfdec_add_si(bfdec_t *r, const bfdec_t *a, int64_t b1, limb_t prec,\n                 bf_flags_t flags);\nint bfdec_mul(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags);\nint bfdec_mul_si(bfdec_t *r, const bfdec_t *a, int64_t b1, limb_t prec,\n                 bf_flags_t flags);\nint bfdec_div(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags);\nint bfdec_divrem(bfdec_t *q, bfdec_t *r, const bfdec_t *a, const bfdec_t *b,\n                 limb_t prec, bf_flags_t flags, int rnd_mode);\nint bfdec_rem(bfdec_t *r, const bfdec_t *a, const bfdec_t *b, limb_t prec,\n              bf_flags_t flags, int rnd_mode);\nint bfdec_rint(bfdec_t *r, int rnd_mode);\nint bfdec_sqrt(bfdec_t *r, const bfdec_t *a, limb_t prec, bf_flags_t flags);\nint bfdec_round(bfdec_t *r, limb_t prec, bf_flags_t flags);\nint bfdec_get_int32(int *pres, const bfdec_t *a);\nint bfdec_pow_ui(bfdec_t *r, const bfdec_t *a, limb_t b);\n\nchar *bfdec_ftoa(size_t *plen, const bfdec_t *a, limb_t prec, bf_flags_t flags);\nint bfdec_atof(bfdec_t *r, const char *str, const char **pnext,\n               limb_t prec, bf_flags_t flags);\n\n/* the following functions are exported for testing only. */\nextern const limb_t mp_pow_dec[LIMB_DIGITS + 1];\nvoid bfdec_print_str(const char *str, const bfdec_t *a);\nstatic inline int bfdec_resize(bfdec_t *r, limb_t len)\n{\n    return bf_resize((bf_t *)r, len);\n}\nint bfdec_normalize_and_round(bfdec_t *r, limb_t prec1, bf_flags_t flags);\n\n#endif /* LIBBF_H */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/libregexp-opcode.h",
    "content": "/*\n * Regular Expression Engine\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n#ifdef DEF\n\nDEF(invalid, 1) /* never used */\nDEF(char, 3)\nDEF(char32, 5)\nDEF(dot, 1)\nDEF(any, 1) /* same as dot but match any character including line terminator */\nDEF(line_start, 1)\nDEF(line_end, 1)\nDEF(goto, 5)\nDEF(split_goto_first, 5)\nDEF(split_next_first, 5)\nDEF(match, 1)\nDEF(save_start, 2) /* save start position */\nDEF(save_end, 2) /* save end position, must come after saved_start */\nDEF(save_reset, 3) /* reset save positions */\nDEF(loop, 5) /* decrement the top the stack and goto if != 0 */\nDEF(push_i32, 5) /* push integer on the stack */\nDEF(drop, 1)\nDEF(word_boundary, 1)\nDEF(not_word_boundary, 1)\nDEF(back_reference, 2)\nDEF(backward_back_reference, 2) /* must come after back_reference */\nDEF(range, 3) /* variable length */\nDEF(range32, 3) /* variable length */\nDEF(lookahead, 5)\nDEF(negative_lookahead, 5)\nDEF(push_char_pos, 1) /* push the character position on the stack */\nDEF(bne_char_pos, 5) /* pop one stack element and jump if equal to the character\n position */\nDEF(prev, 1) /* go to the previous char */\nDEF(simple_greedy_quant, 17)\n\n#endif /* DEF */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/libregexp.c",
    "content": "/*\n * Regular Expression Engine\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <inttypes.h>\n#include <string.h>\n#include <assert.h>\n\n#include \"cutils.h\"\n#include \"libregexp.h\"\n\n/*\n  TODO:\n\n  - Add full unicode canonicalize rules for character ranges (not\n    really useful but needed for exact \"ignorecase\" compatibility).\n\n  - Add a lock step execution mode (=linear time execution guaranteed)\n    when the regular expression is \"simple\" i.e. no backreference nor\n    complicated lookahead. The opcodes are designed for this execution\n    model.\n*/\n\n#if defined(TEST)\n#define DUMP_REOP\n#endif\n\ntypedef enum {\n#define DEF(id, size) REOP_ ## id,\n#include \"libregexp-opcode.h\"\n#undef DEF\n    REOP_COUNT,\n} REOPCodeEnum;\n\n#define CAPTURE_COUNT_MAX 255\n#define STACK_SIZE_MAX 255\n\n/* unicode code points */\n#define CP_LS   0x2028\n#define CP_PS   0x2029\n\n#define TMP_BUF_SIZE 128\n\ntypedef struct {\n    DynBuf byte_code;\n    const uint8_t *buf_ptr;\n    const uint8_t *buf_end;\n    const uint8_t *buf_start;\n    int re_flags;\n    BOOL is_utf16;\n    BOOL ignore_case;\n    BOOL dotall;\n    int capture_count;\n    int total_capture_count; /* -1 = not computed yet */\n    int has_named_captures; /* -1 = don't know, 0 = no, 1 = yes */\n    void *opaque;\n    DynBuf group_names;\n    union {\n        char error_msg[TMP_BUF_SIZE];\n        char tmp_buf[TMP_BUF_SIZE];\n    } u;\n} REParseState;\n\ntypedef struct {\n#ifdef DUMP_REOP\n    const char *name;\n#endif\n    uint8_t size;\n} REOpCode;\n\nstatic const REOpCode reopcode_info[REOP_COUNT] = {\n#ifdef DUMP_REOP\n#define DEF(id, size) { #id, size },\n#else\n#define DEF(id, size) { size },\n#endif\n#include \"libregexp-opcode.h\"\n#undef DEF\n};\n\n#define RE_HEADER_FLAGS         0\n#define RE_HEADER_CAPTURE_COUNT 1\n#define RE_HEADER_STACK_SIZE    2\n\n#define RE_HEADER_LEN 7\n\nstatic inline int is_digit(int c) {\n    return c >= '0' && c <= '9';\n}\n\n/* insert 'len' bytes at position 'pos'. Return < 0 if error. */\nstatic int dbuf_insert(DynBuf *s, int pos, int len)\n{\n    if (dbuf_realloc(s, s->size + len))\n        return -1;\n    memmove(s->buf + pos + len, s->buf + pos, s->size - pos);\n    s->size += len;\n    return 0;\n}\n\n/* canonicalize with the specific JS regexp rules */\nstatic uint32_t lre_canonicalize(uint32_t c, BOOL is_utf16)\n{\n    uint32_t res[LRE_CC_RES_LEN_MAX];\n    int len;\n    if (is_utf16) {\n        if (likely(c < 128)) {\n            if (c >= 'A' && c <= 'Z')\n                c = c - 'A' + 'a';\n        } else {\n            lre_case_conv(res, c, 2);\n            c = res[0];\n        }\n    } else {\n        if (likely(c < 128)) {\n            if (c >= 'a' && c <= 'z')\n                c = c - 'a' + 'A';\n        } else {\n            /* legacy regexp: to upper case if single char >= 128 */\n            len = lre_case_conv(res, c, FALSE);\n            if (len == 1 && res[0] >= 128)\n                c = res[0];\n        }\n    }\n    return c;\n}\n\nstatic const uint16_t char_range_d[] = {\n    1,\n    0x0030, 0x0039 + 1,\n};\n\n/* code point ranges for Zs,Zl or Zp property */\nstatic const uint16_t char_range_s[] = {\n    10,\n    0x0009, 0x000D + 1,\n    0x0020, 0x0020 + 1,\n    0x00A0, 0x00A0 + 1,\n    0x1680, 0x1680 + 1,\n    0x2000, 0x200A + 1,\n    /* 2028;LINE SEPARATOR;Zl;0;WS;;;;;N;;;;; */\n    /* 2029;PARAGRAPH SEPARATOR;Zp;0;B;;;;;N;;;;; */\n    0x2028, 0x2029 + 1,\n    0x202F, 0x202F + 1,\n    0x205F, 0x205F + 1,\n    0x3000, 0x3000 + 1,\n    /* FEFF;ZERO WIDTH NO-BREAK SPACE;Cf;0;BN;;;;;N;BYTE ORDER MARK;;;; */\n    0xFEFF, 0xFEFF + 1,\n};\n\nBOOL lre_is_space(int c)\n{\n    int i, n, low, high;\n    n = (countof(char_range_s) - 1) / 2;\n    for(i = 0; i < n; i++) {\n        low = char_range_s[2 * i + 1];\n        if (c < low)\n            return FALSE;\n        high = char_range_s[2 * i + 2];\n        if (c < high)\n            return TRUE;\n    }\n    return FALSE;\n}\n\nuint32_t const lre_id_start_table_ascii[4] = {\n    /* $ A-Z _ a-z */\n    0x00000000, 0x00000010, 0x87FFFFFE, 0x07FFFFFE\n};\n\nuint32_t const lre_id_continue_table_ascii[4] = {\n    /* $ 0-9 A-Z _ a-z */\n    0x00000000, 0x03FF0010, 0x87FFFFFE, 0x07FFFFFE\n};\n\n\nstatic const uint16_t char_range_w[] = {\n    4,\n    0x0030, 0x0039 + 1,\n    0x0041, 0x005A + 1,\n    0x005F, 0x005F + 1,\n    0x0061, 0x007A + 1,\n};\n\n#define CLASS_RANGE_BASE 0x40000000\n\ntypedef enum {\n    CHAR_RANGE_d,\n    CHAR_RANGE_D,\n    CHAR_RANGE_s,\n    CHAR_RANGE_S,\n    CHAR_RANGE_w,\n    CHAR_RANGE_W,\n} CharRangeEnum;\n\nstatic const uint16_t *char_range_table[] = {\n    char_range_d,\n    char_range_s,\n    char_range_w,\n};\n\nstatic int cr_init_char_range(REParseState *s, CharRange *cr, uint32_t c)\n{\n    BOOL invert;\n    const uint16_t *c_pt;\n    int len, i;\n    \n    invert = c & 1;\n    c_pt = char_range_table[c >> 1];\n    len = *c_pt++;\n    cr_init(cr, s->opaque, lre_realloc);\n    for(i = 0; i < len * 2; i++) {\n        if (cr_add_point(cr, c_pt[i]))\n            goto fail;\n    }\n    if (invert) {\n        if (cr_invert(cr))\n            goto fail;\n    }\n    return 0;\n fail:\n    cr_free(cr);\n    return -1;\n}\n\nstatic int cr_canonicalize(CharRange *cr)\n{\n    CharRange a;\n    uint32_t pt[2];\n    int i, ret;\n\n    cr_init(&a, cr->mem_opaque, lre_realloc);\n    pt[0] = 'a';\n    pt[1] = 'z' + 1;\n    ret = cr_op(&a, cr->points, cr->len, pt, 2, CR_OP_INTER);\n    if (ret)\n        goto fail;\n    /* convert to upper case */\n    /* XXX: the generic unicode case would be much more complicated\n       and not really useful */\n    for(i = 0; i < a.len; i++) {\n        a.points[i] += 'A' - 'a';\n    }\n    /* Note: for simplicity we keep the lower case ranges */\n    ret = cr_union1(cr, a.points, a.len);\n fail:\n    cr_free(&a);\n    return ret;\n}\n\n#ifdef DUMP_REOP\nstatic __maybe_unused void lre_dump_bytecode(const uint8_t *buf,\n                                                     int buf_len)\n{\n    int pos, len, opcode, bc_len, re_flags, i;\n    uint32_t val;\n    \n    assert(buf_len >= RE_HEADER_LEN);\n\n    re_flags=  buf[0];\n    bc_len = get_u32(buf + 3);\n    assert(bc_len + RE_HEADER_LEN <= buf_len);\n    printf(\"flags: 0x%x capture_count=%d stack_size=%d\\n\",\n           re_flags, buf[1], buf[2]);\n    if (re_flags & LRE_FLAG_NAMED_GROUPS) {\n        const char *p;\n        p = (char *)buf + RE_HEADER_LEN + bc_len;\n        printf(\"named groups: \");\n        for(i = 1; i < buf[1]; i++) {\n            if (i != 1)\n                printf(\",\");\n            printf(\"<%s>\", p);\n            p += strlen(p) + 1;\n        }\n        printf(\"\\n\");\n        assert(p == (char *)(buf + buf_len));\n    }\n    printf(\"bytecode_len=%d\\n\", bc_len);\n\n    buf += RE_HEADER_LEN;\n    pos = 0;\n    while (pos < bc_len) {\n        printf(\"%5u: \", pos);\n        opcode = buf[pos];\n        len = reopcode_info[opcode].size;\n        if (opcode >= REOP_COUNT) {\n            printf(\" invalid opcode=0x%02x\\n\", opcode);\n            break;\n        }\n        if ((pos + len) > bc_len) {\n            printf(\" buffer overflow (opcode=0x%02x)\\n\", opcode);\n            break;\n        }\n        printf(\"%s\", reopcode_info[opcode].name);\n        switch(opcode) {\n        case REOP_char:\n            val = get_u16(buf + pos + 1);\n            if (val >= ' ' && val <= 126)\n                printf(\" '%c'\", val);\n            else\n                printf(\" 0x%04x\", val);\n            break;\n        case REOP_char32:\n            val = get_u32(buf + pos + 1);\n            if (val >= ' ' && val <= 126)\n                printf(\" '%c'\", val);\n            else\n                printf(\" 0x%08x\", val);\n            break;\n        case REOP_goto:\n        case REOP_split_goto_first:\n        case REOP_split_next_first:\n        case REOP_loop:\n        case REOP_lookahead:\n        case REOP_negative_lookahead:\n        case REOP_bne_char_pos:\n            val = get_u32(buf + pos + 1);\n            val += (pos + 5);\n            printf(\" %u\", val);\n            break;\n        case REOP_simple_greedy_quant:\n            printf(\" %u %u %u %u\",\n                   get_u32(buf + pos + 1) + (pos + 17),\n                   get_u32(buf + pos + 1 + 4),\n                   get_u32(buf + pos + 1 + 8),\n                   get_u32(buf + pos + 1 + 12));\n            break;\n        case REOP_save_start:\n        case REOP_save_end:\n        case REOP_back_reference:\n        case REOP_backward_back_reference:\n            printf(\" %u\", buf[pos + 1]);\n            break;\n        case REOP_save_reset:\n            printf(\" %u %u\", buf[pos + 1], buf[pos + 2]);\n            break;\n        case REOP_push_i32:\n            val = get_u32(buf + pos + 1);\n            printf(\" %d\", val);\n            break;\n        case REOP_range:\n            {\n                int n, i;\n                n = get_u16(buf + pos + 1);\n                len += n * 4;\n                for(i = 0; i < n * 2; i++) {\n                    val = get_u16(buf + pos + 3 + i * 2);\n                    printf(\" 0x%04x\", val);\n                }\n            }\n            break;\n        case REOP_range32:\n            {\n                int n, i;\n                n = get_u16(buf + pos + 1);\n                len += n * 8;\n                for(i = 0; i < n * 2; i++) {\n                    val = get_u32(buf + pos + 3 + i * 4);\n                    printf(\" 0x%08x\", val);\n                }\n            }\n            break;\n        default:\n            break;\n        }\n        printf(\"\\n\");\n        pos += len;\n    }\n}\n#endif\n\nstatic void re_emit_op(REParseState *s, int op)\n{\n    dbuf_putc(&s->byte_code, op);\n}\n\n/* return the offset of the u32 value */\nstatic int re_emit_op_u32(REParseState *s, int op, uint32_t val)\n{\n    int pos;\n    dbuf_putc(&s->byte_code, op);\n    pos = s->byte_code.size;\n    dbuf_put_u32(&s->byte_code, val);\n    return pos;\n}\n\nstatic int re_emit_goto(REParseState *s, int op, uint32_t val)\n{\n    int pos;\n    dbuf_putc(&s->byte_code, op);\n    pos = s->byte_code.size;\n    dbuf_put_u32(&s->byte_code, val - (pos + 4));\n    return pos;\n}\n\nstatic void re_emit_op_u8(REParseState *s, int op, uint32_t val)\n{\n    dbuf_putc(&s->byte_code, op);\n    dbuf_putc(&s->byte_code, val);\n}\n\nstatic void re_emit_op_u16(REParseState *s, int op, uint32_t val)\n{\n    dbuf_putc(&s->byte_code, op);\n    dbuf_put_u16(&s->byte_code, val);\n}\n\nstatic int __attribute__((format(printf, 2, 3))) re_parse_error(REParseState *s, const char *fmt, ...)\n{\n    va_list ap;\n    va_start(ap, fmt);\n    vsnprintf(s->u.error_msg, sizeof(s->u.error_msg), fmt, ap);\n    va_end(ap);\n    return -1;\n}\n\nstatic int re_parse_out_of_memory(REParseState *s)\n{\n    return re_parse_error(s, \"out of memory\");\n}\n\n/* If allow_overflow is false, return -1 in case of\n   overflow. Otherwise return INT32_MAX. */\nstatic int parse_digits(const uint8_t **pp, BOOL allow_overflow)\n{\n    const uint8_t *p;\n    uint64_t v;\n    int c;\n    \n    p = *pp;\n    v = 0;\n    for(;;) {\n        c = *p;\n        if (c < '0' || c > '9')\n            break;\n        v = v * 10 + c - '0';\n        if (v >= INT32_MAX) {\n            if (allow_overflow)\n                v = INT32_MAX;\n            else\n                return -1;\n        }\n        p++;\n    }\n    *pp = p;\n    return v;\n}\n\nstatic int re_parse_expect(REParseState *s, const uint8_t **pp, int c)\n{\n    const uint8_t *p;\n    p = *pp;\n    if (*p != c)\n        return re_parse_error(s, \"expecting '%c'\", c);\n    p++;\n    *pp = p;\n    return 0;\n}\n\n/* Parse an escape sequence, *pp points after the '\\':\n   allow_utf16 value:\n   0 : no UTF-16 escapes allowed\n   1 : UTF-16 escapes allowed\n   2 : UTF-16 escapes allowed and escapes of surrogate pairs are\n   converted to a unicode character (unicode regexp case).\n\n   Return the unicode char and update *pp if recognized,\n   return -1 if malformed escape,\n   return -2 otherwise. */\nint lre_parse_escape(const uint8_t **pp, int allow_utf16)\n{\n    const uint8_t *p;\n    uint32_t c;\n\n    p = *pp;\n    c = *p++;\n    switch(c) {\n    case 'b':\n        c = '\\b';\n        break;\n    case 'f':\n        c = '\\f';\n        break;\n    case 'n':\n        c = '\\n';\n        break;\n    case 'r':\n        c = '\\r';\n        break;\n    case 't':\n        c = '\\t';\n        break;\n    case 'v':\n        c = '\\v';\n        break;\n    case 'x':\n    case 'u':\n        {\n            int h, n, i;\n            uint32_t c1;\n            \n            if (*p == '{' && allow_utf16) {\n                p++;\n                c = 0;\n                for(;;) {\n                    h = from_hex(*p++);\n                    if (h < 0)\n                        return -1;\n                    c = (c << 4) | h;\n                    if (c > 0x10FFFF)\n                        return -1;\n                    if (*p == '}')\n                        break;\n                }\n                p++;\n            } else {\n                if (c == 'x') {\n                    n = 2;\n                } else {\n                    n = 4;\n                }\n\n                c = 0;\n                for(i = 0; i < n; i++) {\n                    h = from_hex(*p++);\n                    if (h < 0) {\n                        return -1;\n                    }\n                    c = (c << 4) | h;\n                }\n                if (c >= 0xd800 && c < 0xdc00 &&\n                    allow_utf16 == 2 && p[0] == '\\\\' && p[1] == 'u') {\n                    /* convert an escaped surrogate pair into a\n                       unicode char */\n                    c1 = 0;\n                    for(i = 0; i < 4; i++) {\n                        h = from_hex(p[2 + i]);\n                        if (h < 0)\n                            break;\n                        c1 = (c1 << 4) | h;\n                    }\n                    if (i == 4 && c1 >= 0xdc00 && c1 < 0xe000) {\n                        p += 6;\n                        c = (((c & 0x3ff) << 10) | (c1 & 0x3ff)) + 0x10000;\n                    }\n                }\n            }\n        }\n        break;\n    case '0': case '1': case '2': case '3':\n    case '4': case '5': case '6': case '7':\n        c -= '0';\n        if (allow_utf16 == 2) {\n            /* only accept \\0 not followed by digit */\n            if (c != 0 || is_digit(*p))\n                return -1;\n        } else {\n            /* parse a legacy octal sequence */\n            uint32_t v;\n            v = *p - '0';\n            if (v > 7)\n                break;\n            c = (c << 3) | v;\n            p++;\n            if (c >= 32)\n                break;\n            v = *p - '0';\n            if (v > 7)\n                break;\n            c = (c << 3) | v;\n            p++;\n        }\n        break;\n    default:\n        return -2;\n    }\n    *pp = p;\n    return c;\n}\n\n#ifdef CONFIG_ALL_UNICODE\n/* XXX: we use the same chars for name and value */\nstatic BOOL is_unicode_char(int c)\n{\n    return ((c >= '0' && c <= '9') ||\n            (c >= 'A' && c <= 'Z') ||\n            (c >= 'a' && c <= 'z') ||\n            (c == '_'));\n}\n\nstatic int parse_unicode_property(REParseState *s, CharRange *cr,\n                                  const uint8_t **pp, BOOL is_inv)\n{\n    const uint8_t *p;\n    char name[64], value[64];\n    char *q;\n    BOOL script_ext;\n    int ret;\n\n    p = *pp;\n    if (*p != '{')\n        return re_parse_error(s, \"expecting '{' after \\\\p\");\n    p++;\n    q = name;\n    while (is_unicode_char(*p)) {\n        if ((q - name) >= sizeof(name) - 1)\n            goto unknown_property_name;\n        *q++ = *p++;\n    }\n    *q = '\\0';\n    q = value;\n    if (*p == '=') {\n        p++;\n        while (is_unicode_char(*p)) {\n            if ((q - value) >= sizeof(value) - 1)\n                return re_parse_error(s, \"unknown unicode property value\");\n            *q++ = *p++;\n        }\n    }\n    *q = '\\0';\n    if (*p != '}')\n        return re_parse_error(s, \"expecting '}'\");\n    p++;\n    //    printf(\"name=%s value=%s\\n\", name, value);\n\n    if (!strcmp(name, \"Script\") || !strcmp(name, \"sc\")) {\n        script_ext = FALSE;\n        goto do_script;\n    } else if (!strcmp(name, \"Script_Extensions\") || !strcmp(name, \"scx\")) {\n        script_ext = TRUE;\n    do_script:\n        cr_init(cr, s->opaque, lre_realloc);\n        ret = unicode_script(cr, value, script_ext);\n        if (ret) {\n            cr_free(cr);\n            if (ret == -2)\n                return re_parse_error(s, \"unknown unicode script\");\n            else\n                goto out_of_memory;\n        }\n    } else if (!strcmp(name, \"General_Category\") || !strcmp(name, \"gc\")) {\n        cr_init(cr, s->opaque, lre_realloc);\n        ret = unicode_general_category(cr, value);\n        if (ret) {\n            cr_free(cr);\n            if (ret == -2)\n                return re_parse_error(s, \"unknown unicode general category\");\n            else\n                goto out_of_memory;\n        }\n    } else if (value[0] == '\\0') {\n        cr_init(cr, s->opaque, lre_realloc);\n        ret = unicode_general_category(cr, name);\n        if (ret == -1) {\n            cr_free(cr);\n            goto out_of_memory;\n        }\n        if (ret < 0) {\n            ret = unicode_prop(cr, name);\n            if (ret) {\n                cr_free(cr);\n                if (ret == -2)\n                    goto unknown_property_name;\n                else\n                    goto out_of_memory;\n            }\n        }\n    } else {\n    unknown_property_name:\n        return re_parse_error(s, \"unknown unicode property name\");\n    }\n\n    if (is_inv) {\n        if (cr_invert(cr)) {\n            cr_free(cr);\n            return -1;\n        }\n    }\n    *pp = p;\n    return 0;\n out_of_memory:\n    return re_parse_out_of_memory(s);\n}\n#endif /* CONFIG_ALL_UNICODE */\n\n/* return -1 if error otherwise the character or a class range\n   (CLASS_RANGE_BASE). In case of class range, 'cr' is\n   initialized. Otherwise, it is ignored. */\nstatic int get_class_atom(REParseState *s, CharRange *cr,\n                          const uint8_t **pp, BOOL inclass)\n{\n    const uint8_t *p;\n    uint32_t c;\n    int ret;\n    \n    p = *pp;\n\n    c = *p;\n    switch(c) {\n    case '\\\\':\n        p++;\n        if (p >= s->buf_end)\n            goto unexpected_end;\n        c = *p++;\n        switch(c) {\n        case 'd':\n            c = CHAR_RANGE_d;\n            goto class_range;\n        case 'D':\n            c = CHAR_RANGE_D;\n            goto class_range;\n        case 's':\n            c = CHAR_RANGE_s;\n            goto class_range;\n        case 'S':\n            c = CHAR_RANGE_S;\n            goto class_range;\n        case 'w':\n            c = CHAR_RANGE_w;\n            goto class_range;\n        case 'W':\n            c = CHAR_RANGE_W;\n        class_range:\n            if (cr_init_char_range(s, cr, c))\n                return -1;\n            c = CLASS_RANGE_BASE;\n            break;\n        case 'c':\n            c = *p;\n            if ((c >= 'a' && c <= 'z') ||\n                (c >= 'A' && c <= 'Z') ||\n                (((c >= '0' && c <= '9') || c == '_') &&\n                 inclass && !s->is_utf16)) {   /* Annex B.1.4 */\n                c &= 0x1f;\n                p++;\n            } else if (s->is_utf16) {\n                goto invalid_escape;\n            } else {\n                /* otherwise return '\\' and 'c' */\n                p--;\n                c = '\\\\';\n            }\n            break;\n#ifdef CONFIG_ALL_UNICODE\n        case 'p':\n        case 'P':\n            if (s->is_utf16) {\n                if (parse_unicode_property(s, cr, &p, (c == 'P')))\n                    return -1;\n                c = CLASS_RANGE_BASE;\n                break;\n            }\n            /* fall thru */\n#endif\n        default:\n            p--;\n            ret = lre_parse_escape(&p, s->is_utf16 * 2);\n            if (ret >= 0) {\n                c = ret;\n            } else {\n                if (ret == -2 && *p != '\\0' && strchr(\"^$\\\\.*+?()[]{}|/\", *p)) {\n                    /* always valid to escape these characters */\n                    goto normal_char;\n                } else if (s->is_utf16) {\n                invalid_escape:\n                    return re_parse_error(s, \"invalid escape sequence in regular expression\");\n                } else {\n                    /* just ignore the '\\' */\n                    goto normal_char;\n                }\n            }\n            break;\n        }\n        break;\n    case '\\0':\n        if (p >= s->buf_end) {\n        unexpected_end:\n            return re_parse_error(s, \"unexpected end\");\n        }\n        /* fall thru */\n    default:\n    normal_char:\n        /* normal char */\n        if (c >= 128) {\n            c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);\n            if ((unsigned)c > 0xffff && !s->is_utf16) {\n                /* XXX: should handle non BMP-1 code points */\n                return re_parse_error(s, \"malformed unicode char\");\n            }\n        } else {\n            p++;\n        }\n        break;\n    }\n    *pp = p;\n    return c;\n}\n\nstatic int re_emit_range(REParseState *s, const CharRange *cr)\n{\n    int len, i;\n    uint32_t high;\n    \n    len = (unsigned)cr->len / 2;\n    if (len >= 65535)\n        return re_parse_error(s, \"too many ranges\");\n    if (len == 0) {\n        /* not sure it can really happen. Emit a match that is always\n           false */\n        re_emit_op_u32(s, REOP_char32, -1);\n    } else {\n        high = cr->points[cr->len - 1];\n        if (high == UINT32_MAX)\n            high = cr->points[cr->len - 2];\n        if (high <= 0xffff) {\n            /* can use 16 bit ranges with the conversion that 0xffff =\n               infinity */\n            re_emit_op_u16(s, REOP_range, len);\n            for(i = 0; i < cr->len; i += 2) {\n                dbuf_put_u16(&s->byte_code, cr->points[i]);\n                high = cr->points[i + 1] - 1;\n                if (high == UINT32_MAX - 1)\n                    high = 0xffff;\n                dbuf_put_u16(&s->byte_code, high);\n            }\n        } else {\n            re_emit_op_u16(s, REOP_range32, len);\n            for(i = 0; i < cr->len; i += 2) {\n                dbuf_put_u32(&s->byte_code, cr->points[i]);\n                dbuf_put_u32(&s->byte_code, cr->points[i + 1] - 1);\n            }\n        }\n    }\n    return 0;\n}\n\nstatic int re_parse_char_class(REParseState *s, const uint8_t **pp)\n{\n    const uint8_t *p;\n    uint32_t c1, c2;\n    CharRange cr_s, *cr = &cr_s;\n    CharRange cr1_s, *cr1 = &cr1_s;\n    BOOL invert;\n    \n    cr_init(cr, s->opaque, lre_realloc);\n    p = *pp;\n    p++;    /* skip '[' */\n    invert = FALSE;\n    if (*p == '^') {\n        p++;\n        invert = TRUE;\n    }\n    for(;;) {\n        if (*p == ']')\n            break;\n        c1 = get_class_atom(s, cr1, &p, TRUE);\n        if ((int)c1 < 0)\n            goto fail;\n        if (*p == '-' && p[1] != ']') {\n            const uint8_t *p0 = p + 1;\n            if (c1 >= CLASS_RANGE_BASE) {\n                if (s->is_utf16) {\n                    cr_free(cr1);\n                    goto invalid_class_range;\n                }\n                /* Annex B: match '-' character */\n                goto class_atom;\n            }\n            c2 = get_class_atom(s, cr1, &p0, TRUE);\n            if ((int)c2 < 0)\n                goto fail;\n            if (c2 >= CLASS_RANGE_BASE) {\n                cr_free(cr1);\n                if (s->is_utf16) {\n                    goto invalid_class_range;\n                }\n                /* Annex B: match '-' character */\n                goto class_atom;\n            }\n            p = p0;\n            if (c2 < c1) {\n            invalid_class_range:\n                re_parse_error(s, \"invalid class range\");\n                goto fail;\n            }\n            if (cr_union_interval(cr, c1, c2))\n                goto memory_error;\n        } else {\n        class_atom:\n            if (c1 >= CLASS_RANGE_BASE) {\n                int ret;\n                ret = cr_union1(cr, cr1->points, cr1->len);\n                cr_free(cr1);\n                if (ret)\n                    goto memory_error;\n            } else {\n                if (cr_union_interval(cr, c1, c1))\n                    goto memory_error;\n            }\n        }\n    }\n    if (s->ignore_case) {\n        if (cr_canonicalize(cr))\n            goto memory_error;\n    }\n    if (invert) {\n        if (cr_invert(cr))\n            goto memory_error;\n    }\n    if (re_emit_range(s, cr))\n        goto fail;\n    cr_free(cr);\n    p++;    /* skip ']' */\n    *pp = p;\n    return 0;\n memory_error:\n    re_parse_out_of_memory(s);\n fail:\n    cr_free(cr);\n    return -1;\n}\n\n/* Return:\n   1 if the opcodes in bc_buf[] always advance the character pointer.\n   0 if the character pointer may not be advanced.\n   -1 if the code may depend on side effects of its previous execution (backreference)\n*/\nstatic int re_check_advance(const uint8_t *bc_buf, int bc_buf_len)\n{\n    int pos, opcode, ret, len, i;\n    uint32_t val, last;\n    BOOL has_back_reference;\n    uint8_t capture_bitmap[CAPTURE_COUNT_MAX];\n    \n    ret = -2; /* not known yet */\n    pos = 0;\n    has_back_reference = FALSE;\n    memset(capture_bitmap, 0, sizeof(capture_bitmap));\n    \n    while (pos < bc_buf_len) {\n        opcode = bc_buf[pos];\n        len = reopcode_info[opcode].size;\n        switch(opcode) {\n        case REOP_range:\n            val = get_u16(bc_buf + pos + 1);\n            len += val * 4;\n            goto simple_char;\n        case REOP_range32:\n            val = get_u16(bc_buf + pos + 1);\n            len += val * 8;\n            goto simple_char;\n        case REOP_char:\n        case REOP_char32:\n        case REOP_dot:\n        case REOP_any:\n        simple_char:\n            if (ret == -2)\n                ret = 1;\n            break;\n        case REOP_line_start:\n        case REOP_line_end:\n        case REOP_push_i32:\n        case REOP_push_char_pos:\n        case REOP_drop:\n        case REOP_word_boundary:\n        case REOP_not_word_boundary:\n        case REOP_prev:\n            /* no effect */\n            break;\n        case REOP_save_start:\n        case REOP_save_end:\n            val = bc_buf[pos + 1];\n            capture_bitmap[val] |= 1;\n            break;\n        case REOP_save_reset:\n            {\n                val = bc_buf[pos + 1];\n                last = bc_buf[pos + 2];\n                while (val < last)\n                    capture_bitmap[val++] |= 1;\n            }\n            break;\n        case REOP_back_reference:\n        case REOP_backward_back_reference:\n            val = bc_buf[pos + 1];\n            capture_bitmap[val] |= 2;\n            has_back_reference = TRUE;\n            break;\n        default:\n            /* safe behvior: we cannot predict the outcome */\n            if (ret == -2)\n                ret = 0;\n            break;\n        }\n        pos += len;\n    }\n    if (has_back_reference) {\n        /* check if there is back reference which references a capture\n           made in the some code */\n        for(i = 0; i < CAPTURE_COUNT_MAX; i++) {\n            if (capture_bitmap[i] == 3)\n                return -1;\n        }\n    }\n    if (ret == -2)\n        ret = 0;\n    return ret;\n}\n\n/* return -1 if a simple quantifier cannot be used. Otherwise return\n   the number of characters in the atom. */\nstatic int re_is_simple_quantifier(const uint8_t *bc_buf, int bc_buf_len)\n{\n    int pos, opcode, len, count;\n    uint32_t val;\n    \n    count = 0;\n    pos = 0;\n    while (pos < bc_buf_len) {\n        opcode = bc_buf[pos];\n        len = reopcode_info[opcode].size;\n        switch(opcode) {\n        case REOP_range:\n            val = get_u16(bc_buf + pos + 1);\n            len += val * 4;\n            goto simple_char;\n        case REOP_range32:\n            val = get_u16(bc_buf + pos + 1);\n            len += val * 8;\n            goto simple_char;\n        case REOP_char:\n        case REOP_char32:\n        case REOP_dot:\n        case REOP_any:\n        simple_char:\n            count++;\n            break;\n        case REOP_line_start:\n        case REOP_line_end:\n        case REOP_word_boundary:\n        case REOP_not_word_boundary:\n            break;\n        default:\n            return -1;\n        }\n        pos += len;\n    }\n    return count;\n}\n\n/* '*pp' is the first char after '<' */\nstatic int re_parse_group_name(char *buf, int buf_size,\n                               const uint8_t **pp, BOOL is_utf16)\n{\n    const uint8_t *p;\n    uint32_t c;\n    char *q;\n\n    p = *pp;\n    q = buf;\n    for(;;) {\n        c = *p;\n        if (c == '\\\\') {\n            p++;\n            if (*p != 'u')\n                return -1;\n            c = lre_parse_escape(&p, is_utf16 * 2);\n        } else if (c == '>') {\n            break;\n        } else if (c >= 128) {\n            c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);\n        } else {\n            p++;\n        }\n        if (c > 0x10FFFF)\n            return -1;\n        if (q == buf) {\n            if (!lre_js_is_ident_first(c))\n                return -1;\n        } else {\n            if (!lre_js_is_ident_next(c))\n                return -1;\n        }\n        if ((q - buf + UTF8_CHAR_LEN_MAX + 1) > buf_size)\n            return -1;\n        if (c < 128) {\n            *q++ = c;\n        } else {\n            q += unicode_to_utf8((uint8_t*)q, c);\n        }\n    }\n    if (q == buf)\n        return -1;\n    *q = '\\0';\n    p++;\n    *pp = p;\n    return 0;\n}\n\n/* if capture_name = NULL: return the number of captures + 1.\n   Otherwise, return the capture index corresponding to capture_name\n   or -1 if none */\nstatic int re_parse_captures(REParseState *s, int *phas_named_captures,\n                             const char *capture_name)\n{\n    const uint8_t *p;\n    int capture_index;\n    char name[TMP_BUF_SIZE];\n\n    capture_index = 1;\n    *phas_named_captures = 0;\n    for (p = s->buf_start; p < s->buf_end; p++) {\n        switch (*p) {\n        case '(':\n            if (p[1] == '?') {\n                if (p[2] == '<' && p[3] != '=' && p[3] != '!') {\n                    *phas_named_captures = 1;\n                    /* potential named capture */\n                    if (capture_name) {\n                        p += 3;\n                        if (re_parse_group_name(name, sizeof(name), &p,\n                                                s->is_utf16) == 0) {\n                            if (!strcmp(name, capture_name))\n                                return capture_index;\n                        }\n                    }\n                    capture_index++;\n                    if (capture_index >= CAPTURE_COUNT_MAX)\n                        goto done;\n                }\n            } else {\n                capture_index++;\n                if (capture_index >= CAPTURE_COUNT_MAX)\n                    goto done;\n            }\n            break;\n        case '\\\\':\n            p++;\n            break;\n        case '[':\n            for (p += 1 + (*p == ']'); p < s->buf_end && *p != ']'; p++) {\n                if (*p == '\\\\')\n                    p++;\n            }\n            break;\n        }\n    }\n done:\n    if (capture_name)\n        return -1;\n    else\n        return capture_index;\n}\n\nstatic int re_count_captures(REParseState *s)\n{\n    if (s->total_capture_count < 0) {\n        s->total_capture_count = re_parse_captures(s, &s->has_named_captures,\n                                                   NULL);\n    }\n    return s->total_capture_count;\n}\n\nstatic BOOL re_has_named_captures(REParseState *s)\n{\n    if (s->has_named_captures < 0)\n        re_count_captures(s);\n    return s->has_named_captures;\n}\n\nstatic int find_group_name(REParseState *s, const char *name)\n{\n    const char *p, *buf_end;\n    size_t len, name_len;\n    int capture_index;\n    \n    name_len = strlen(name);\n    p = (char *)s->group_names.buf;\n    buf_end = (char *)s->group_names.buf + s->group_names.size;\n    capture_index = 1;\n    while (p < buf_end) {\n        len = strlen(p);\n        if (len == name_len && memcmp(name, p, name_len) == 0)\n            return capture_index;\n        p += len + 1;\n        capture_index++;\n    }\n    return -1;\n}\n\nstatic int re_parse_disjunction(REParseState *s, BOOL is_backward_dir);\n\nstatic int re_parse_term(REParseState *s, BOOL is_backward_dir)\n{\n    const uint8_t *p;\n    int c, last_atom_start, quant_min, quant_max, last_capture_count;\n    BOOL greedy, add_zero_advance_check, is_neg, is_backward_lookahead;\n    CharRange cr_s, *cr = &cr_s;\n    \n    last_atom_start = -1;\n    last_capture_count = 0;\n    p = s->buf_ptr;\n    c = *p;\n    switch(c) {\n    case '^':\n        p++;\n        re_emit_op(s, REOP_line_start);\n        break;\n    case '$':\n        p++;\n        re_emit_op(s, REOP_line_end);\n        break;\n    case '.':\n        p++;\n        last_atom_start = s->byte_code.size;\n        last_capture_count = s->capture_count;\n        if (is_backward_dir)\n            re_emit_op(s, REOP_prev);\n        re_emit_op(s, s->dotall ? REOP_any : REOP_dot);\n        if (is_backward_dir)\n            re_emit_op(s, REOP_prev);\n        break;\n    case '{':\n        if (s->is_utf16) {\n            return re_parse_error(s, \"syntax error\");\n        } else if (!is_digit(p[1])) {\n            /* Annex B: we accept '{' not followed by digits as a\n               normal atom */\n            goto parse_class_atom;\n        } else {\n            const uint8_t *p1 = p + 1;\n            /* Annex B: error if it is like a repetition count */\n            parse_digits(&p1, TRUE);\n            if (*p1 == ',') {\n                p1++;\n                if (is_digit(*p1)) {\n                    parse_digits(&p1, TRUE);\n                }\n            }\n            if (*p1 != '}') {\n                goto parse_class_atom;\n            }\n        }\n        /* fall thru */\n    case '*':\n    case '+':\n    case '?':\n        return re_parse_error(s, \"nothing to repeat\");\n    case '(':\n        if (p[1] == '?') {\n            if (p[2] == ':') {\n                p += 3;\n                last_atom_start = s->byte_code.size;\n                last_capture_count = s->capture_count;\n                s->buf_ptr = p;\n                if (re_parse_disjunction(s, is_backward_dir))\n                    return -1;\n                p = s->buf_ptr;\n                if (re_parse_expect(s, &p, ')'))\n                    return -1;\n            } else if ((p[2] == '=' || p[2] == '!')) {\n                is_neg = (p[2] == '!');\n                is_backward_lookahead = FALSE;\n                p += 3;\n                goto lookahead;\n            } else if (p[2] == '<' &&\n                       (p[3] == '=' || p[3] == '!')) {\n                int pos;\n                is_neg = (p[3] == '!');\n                is_backward_lookahead = TRUE;\n                p += 4;\n                /* lookahead */\n            lookahead:\n                /* Annex B allows lookahead to be used as an atom for\n                   the quantifiers */\n                if (!s->is_utf16 && !is_backward_lookahead)  {\n                    last_atom_start = s->byte_code.size;\n                    last_capture_count = s->capture_count;\n                }\n                pos = re_emit_op_u32(s, REOP_lookahead + is_neg, 0);\n                s->buf_ptr = p;\n                if (re_parse_disjunction(s, is_backward_lookahead))\n                    return -1;\n                p = s->buf_ptr;\n                if (re_parse_expect(s, &p, ')'))\n                    return -1;\n                re_emit_op(s, REOP_match);\n                /* jump after the 'match' after the lookahead is successful */\n                if (dbuf_error(&s->byte_code))\n                    return -1;\n                put_u32(s->byte_code.buf + pos, s->byte_code.size - (pos + 4));\n            } else if (p[2] == '<') {\n                p += 3;\n                if (re_parse_group_name(s->u.tmp_buf, sizeof(s->u.tmp_buf),\n                                        &p, s->is_utf16)) {\n                    return re_parse_error(s, \"invalid group name\");\n                }\n                if (find_group_name(s, s->u.tmp_buf) > 0) {\n                    return re_parse_error(s, \"duplicate group name\");\n                }\n                /* group name with a trailing zero */\n                dbuf_put(&s->group_names, (uint8_t *)s->u.tmp_buf,\n                         strlen(s->u.tmp_buf) + 1);\n                s->has_named_captures = 1;\n                goto parse_capture;\n            } else {\n                return re_parse_error(s, \"invalid group\");\n            }\n        } else {\n            int capture_index;\n            p++;\n            /* capture without group name */\n            dbuf_putc(&s->group_names, 0);\n        parse_capture:\n            if (s->capture_count >= CAPTURE_COUNT_MAX)\n                return re_parse_error(s, \"too many captures\");\n            last_atom_start = s->byte_code.size;\n            last_capture_count = s->capture_count;\n            capture_index = s->capture_count++;\n            re_emit_op_u8(s, REOP_save_start + is_backward_dir,\n                          capture_index);\n            \n            s->buf_ptr = p;\n            if (re_parse_disjunction(s, is_backward_dir))\n                return -1;\n            p = s->buf_ptr;\n            \n            re_emit_op_u8(s, REOP_save_start + 1 - is_backward_dir,\n                          capture_index);\n            \n            if (re_parse_expect(s, &p, ')'))\n                return -1;\n        }\n        break;\n    case '\\\\':\n        switch(p[1]) {\n        case 'b':\n        case 'B':\n            re_emit_op(s, REOP_word_boundary + (p[1] != 'b'));\n            p += 2;\n            break;\n        case 'k':\n            {\n                const uint8_t *p1;\n                int dummy_res;\n                \n                p1 = p;\n                if (p1[2] != '<') {\n                    /* annex B: we tolerate invalid group names in non\n                       unicode mode if there is no named capture\n                       definition */\n                    if (s->is_utf16 || re_has_named_captures(s))\n                        return re_parse_error(s, \"expecting group name\");\n                    else\n                        goto parse_class_atom;\n                }\n                p1 += 3;\n                if (re_parse_group_name(s->u.tmp_buf, sizeof(s->u.tmp_buf),\n                                        &p1, s->is_utf16)) {\n                    if (s->is_utf16 || re_has_named_captures(s))\n                        return re_parse_error(s, \"invalid group name\");\n                    else\n                        goto parse_class_atom;\n                }\n                c = find_group_name(s, s->u.tmp_buf);\n                if (c < 0) {\n                    /* no capture name parsed before, try to look\n                       after (inefficient, but hopefully not common */\n                    c = re_parse_captures(s, &dummy_res, s->u.tmp_buf);\n                    if (c < 0) {\n                        if (s->is_utf16 || re_has_named_captures(s))\n                            return re_parse_error(s, \"group name not defined\");\n                        else\n                            goto parse_class_atom;\n                    }\n                }\n                p = p1;\n            }\n            goto emit_back_reference;\n        case '0':\n            p += 2;\n            c = 0;\n            if (s->is_utf16) {\n                if (is_digit(*p)) {\n                    return re_parse_error(s, \"invalid decimal escape in regular expression\");\n                }\n            } else {\n                /* Annex B.1.4: accept legacy octal */\n                if (*p >= '0' && *p <= '7') {\n                    c = *p++ - '0';\n                    if (*p >= '0' && *p <= '7') {\n                        c = (c << 3) + *p++ - '0';\n                    }\n                }\n            }\n            goto normal_char;\n        case '1': case '2': case '3': case '4':\n        case '5': case '6': case '7': case '8':\n        case '9': \n            {\n                const uint8_t *q = ++p;\n                \n                c = parse_digits(&p, FALSE);\n                if (c < 0 || (c >= s->capture_count && c >= re_count_captures(s))) {\n                    if (!s->is_utf16) {\n                        /* Annex B.1.4: accept legacy octal */\n                        p = q;\n                        if (*p <= '7') {\n                            c = 0;\n                            if (*p <= '3')\n                                c = *p++ - '0';\n                            if (*p >= '0' && *p <= '7') {\n                                c = (c << 3) + *p++ - '0';\n                                if (*p >= '0' && *p <= '7') {\n                                    c = (c << 3) + *p++ - '0';\n                                }\n                            }\n                        } else {\n                            c = *p++;\n                        }\n                        goto normal_char;\n                    }\n                    return re_parse_error(s, \"back reference out of range in regular expression\");\n                }\n            emit_back_reference:\n                last_atom_start = s->byte_code.size;\n                last_capture_count = s->capture_count;\n                re_emit_op_u8(s, REOP_back_reference + is_backward_dir, c);\n            }\n            break;\n        default:\n            goto parse_class_atom;\n        }\n        break;\n    case '[':\n        last_atom_start = s->byte_code.size;\n        last_capture_count = s->capture_count;\n        if (is_backward_dir)\n            re_emit_op(s, REOP_prev);\n        if (re_parse_char_class(s, &p))\n            return -1;\n        if (is_backward_dir)\n            re_emit_op(s, REOP_prev);\n        break;\n    case ']':\n    case '}':\n        if (s->is_utf16)\n            return re_parse_error(s, \"syntax error\");\n        goto parse_class_atom;\n    default:\n    parse_class_atom:\n        c = get_class_atom(s, cr, &p, FALSE);\n        if ((int)c < 0)\n            return -1;\n    normal_char:\n        last_atom_start = s->byte_code.size;\n        last_capture_count = s->capture_count;\n        if (is_backward_dir)\n            re_emit_op(s, REOP_prev);\n        if (c >= CLASS_RANGE_BASE) {\n            int ret;\n            /* Note: canonicalization is not needed */\n            ret = re_emit_range(s, cr);\n            cr_free(cr);\n            if (ret)\n                return -1;\n        } else {\n            if (s->ignore_case)\n                c = lre_canonicalize(c, s->is_utf16);\n            if (c <= 0xffff)\n                re_emit_op_u16(s, REOP_char, c);\n            else\n                re_emit_op_u32(s, REOP_char32, c);\n        }\n        if (is_backward_dir)\n            re_emit_op(s, REOP_prev);\n        break;\n    }\n\n    /* quantifier */\n    if (last_atom_start >= 0) {\n        c = *p;\n        switch(c) {\n        case '*':\n            p++;\n            quant_min = 0;\n            quant_max = INT32_MAX;\n            goto quantifier;\n        case '+':\n            p++;\n            quant_min = 1;\n            quant_max = INT32_MAX;\n            goto quantifier;\n        case '?':\n            p++;\n            quant_min = 0;\n            quant_max = 1;\n            goto quantifier;\n        case '{':\n            {\n                const uint8_t *p1 = p;\n                /* As an extension (see ES6 annex B), we accept '{' not\n                   followed by digits as a normal atom */\n                if (!is_digit(p[1])) {\n                    if (s->is_utf16)\n                        goto invalid_quant_count;\n                    break;\n                }\n                p++;\n                quant_min = parse_digits(&p, TRUE);\n                quant_max = quant_min;\n                if (*p == ',') {\n                    p++;\n                    if (is_digit(*p)) {\n                        quant_max = parse_digits(&p, TRUE);\n                        if (quant_max < quant_min) {\n                        invalid_quant_count:\n                            return re_parse_error(s, \"invalid repetition count\");\n                        }\n                    } else {\n                        quant_max = INT32_MAX; /* infinity */\n                    }\n                }\n                if (*p != '}' && !s->is_utf16) {\n                    /* Annex B: normal atom if invalid '{' syntax */\n                    p = p1;\n                    break;\n                }\n                if (re_parse_expect(s, &p, '}'))\n                    return -1;\n            }\n        quantifier:\n            greedy = TRUE;\n            if (*p == '?') {\n                p++;\n                greedy = FALSE;\n            }\n            if (last_atom_start < 0) {\n                return re_parse_error(s, \"nothing to repeat\");\n            }\n            if (greedy) {\n                int len, pos;\n                \n                if (quant_max > 0) {\n                    /* specific optimization for simple quantifiers */\n                    if (dbuf_error(&s->byte_code))\n                        goto out_of_memory;\n                    len = re_is_simple_quantifier(s->byte_code.buf + last_atom_start,\n                                                 s->byte_code.size - last_atom_start);\n                    if (len > 0) {\n                        re_emit_op(s, REOP_match);\n                        \n                        if (dbuf_insert(&s->byte_code, last_atom_start, 17))\n                            goto out_of_memory;\n                        pos = last_atom_start;\n                        s->byte_code.buf[pos++] = REOP_simple_greedy_quant;\n                        put_u32(&s->byte_code.buf[pos],\n                                s->byte_code.size - last_atom_start - 17);\n                        pos += 4;\n                        put_u32(&s->byte_code.buf[pos], quant_min);\n                        pos += 4;\n                        put_u32(&s->byte_code.buf[pos], quant_max);\n                        pos += 4;\n                        put_u32(&s->byte_code.buf[pos], len);\n                        pos += 4;\n                        goto done;\n                    }\n                }\n                \n                if (dbuf_error(&s->byte_code))\n                    goto out_of_memory;\n                add_zero_advance_check = (re_check_advance(s->byte_code.buf + last_atom_start,\n                                                           s->byte_code.size - last_atom_start) == 0);\n            } else {\n                add_zero_advance_check = FALSE;\n            }\n            \n            {\n                int len, pos;\n                len = s->byte_code.size - last_atom_start;\n                if (quant_min == 0) {\n                    /* need to reset the capture in case the atom is\n                       not executed */\n                    if (last_capture_count != s->capture_count) {\n                        if (dbuf_insert(&s->byte_code, last_atom_start, 3))\n                            goto out_of_memory;\n                        s->byte_code.buf[last_atom_start++] = REOP_save_reset;\n                        s->byte_code.buf[last_atom_start++] = last_capture_count;\n                        s->byte_code.buf[last_atom_start++] = s->capture_count - 1;\n                    }\n                    if (quant_max == 0) {\n                        s->byte_code.size = last_atom_start;\n                    } else if (quant_max == 1) {\n                        if (dbuf_insert(&s->byte_code, last_atom_start, 5))\n                            goto out_of_memory;\n                        s->byte_code.buf[last_atom_start] = REOP_split_goto_first +\n                            greedy;\n                        put_u32(s->byte_code.buf + last_atom_start + 1, len);\n                    } else if (quant_max == INT32_MAX) {\n                        if (dbuf_insert(&s->byte_code, last_atom_start, 5 + add_zero_advance_check))\n                            goto out_of_memory;\n                        s->byte_code.buf[last_atom_start] = REOP_split_goto_first +\n                            greedy;\n                        put_u32(s->byte_code.buf + last_atom_start + 1,\n                                len + 5 + add_zero_advance_check);\n                        if (add_zero_advance_check) {\n                            /* avoid infinite loop by stoping the\n                               recursion if no advance was made in the\n                               atom (only works if the atom has no\n                               side effect) */\n                            s->byte_code.buf[last_atom_start + 1 + 4] = REOP_push_char_pos;\n                            re_emit_goto(s, REOP_bne_char_pos, last_atom_start); \n                        } else {\n                            re_emit_goto(s, REOP_goto, last_atom_start);\n                        }\n                    } else {\n                        if (dbuf_insert(&s->byte_code, last_atom_start, 10))\n                            goto out_of_memory;\n                        pos = last_atom_start;\n                        s->byte_code.buf[pos++] = REOP_push_i32;\n                        put_u32(s->byte_code.buf + pos, quant_max);\n                        pos += 4;\n                        s->byte_code.buf[pos++] = REOP_split_goto_first + greedy;\n                        put_u32(s->byte_code.buf + pos, len + 5);\n                        re_emit_goto(s, REOP_loop, last_atom_start + 5);\n                        re_emit_op(s, REOP_drop);\n                    }\n                } else if (quant_min == 1 && quant_max == INT32_MAX &&\n                           !add_zero_advance_check) {\n                    re_emit_goto(s, REOP_split_next_first - greedy,\n                                 last_atom_start);\n                } else {\n                    if (quant_min == 1) {\n                        /* nothing to add */\n                    } else {\n                        if (dbuf_insert(&s->byte_code, last_atom_start, 5))\n                            goto out_of_memory;\n                        s->byte_code.buf[last_atom_start] = REOP_push_i32;\n                        put_u32(s->byte_code.buf + last_atom_start + 1,\n                                quant_min);\n                        last_atom_start += 5;\n                        re_emit_goto(s, REOP_loop, last_atom_start);\n                        re_emit_op(s, REOP_drop);\n                    }\n                    if (quant_max == INT32_MAX) {\n                        pos = s->byte_code.size;\n                        re_emit_op_u32(s, REOP_split_goto_first + greedy,\n                                       len + 5 + add_zero_advance_check);\n                        if (add_zero_advance_check)\n                            re_emit_op(s, REOP_push_char_pos);\n                        /* copy the atom */\n                        dbuf_put_self(&s->byte_code, last_atom_start, len);\n                        if (add_zero_advance_check)\n                            re_emit_goto(s, REOP_bne_char_pos, pos);\n                        else\n                            re_emit_goto(s, REOP_goto, pos);\n                    } else if (quant_max > quant_min) {\n                        re_emit_op_u32(s, REOP_push_i32, quant_max - quant_min);\n                        pos = s->byte_code.size;\n                        re_emit_op_u32(s, REOP_split_goto_first + greedy, len + 5);\n                        /* copy the atom */\n                        dbuf_put_self(&s->byte_code, last_atom_start, len);\n                        \n                        re_emit_goto(s, REOP_loop, pos);\n                        re_emit_op(s, REOP_drop);\n                    }\n                }\n                last_atom_start = -1;\n            }\n            break;\n        default:\n            break;\n        }\n    }\n done:\n    s->buf_ptr = p;\n    return 0;\n out_of_memory:\n    return re_parse_out_of_memory(s);\n}\n\nstatic int re_parse_alternative(REParseState *s, BOOL is_backward_dir)\n{\n    const uint8_t *p;\n    int ret;\n    size_t start, term_start, end, term_size;\n\n    start = s->byte_code.size;\n    for(;;) {\n        p = s->buf_ptr;\n        if (p >= s->buf_end)\n            break;\n        if (*p == '|' || *p == ')')\n            break;\n        term_start = s->byte_code.size;\n        ret = re_parse_term(s, is_backward_dir);\n        if (ret)\n            return ret;\n        if (is_backward_dir) {\n            /* reverse the order of the terms (XXX: inefficient, but\n               speed is not really critical here) */\n            end = s->byte_code.size;\n            term_size = end - term_start;\n            if (dbuf_realloc(&s->byte_code, end + term_size))\n                return -1;\n            memmove(s->byte_code.buf + start + term_size,\n                    s->byte_code.buf + start,\n                    end - start);\n            memcpy(s->byte_code.buf + start, s->byte_code.buf + end,\n                   term_size);\n        }\n    }\n    return 0;\n}\n    \nstatic int re_parse_disjunction(REParseState *s, BOOL is_backward_dir)\n{\n    int start, len, pos;\n\n    if (lre_check_stack_overflow(s->opaque, 0))\n        return re_parse_error(s, \"stack overflow\");\n    \n    start = s->byte_code.size;\n    if (re_parse_alternative(s, is_backward_dir))\n        return -1;\n    while (*s->buf_ptr == '|') {\n        s->buf_ptr++;\n\n        len = s->byte_code.size - start;\n\n        /* insert a split before the first alternative */\n        if (dbuf_insert(&s->byte_code, start, 5)) {\n            return re_parse_out_of_memory(s);\n        }\n        s->byte_code.buf[start] = REOP_split_next_first;\n        put_u32(s->byte_code.buf + start + 1, len + 5);\n\n        pos = re_emit_op_u32(s, REOP_goto, 0);\n\n        if (re_parse_alternative(s, is_backward_dir))\n            return -1;\n        \n        /* patch the goto */\n        len = s->byte_code.size - (pos + 4);\n        put_u32(s->byte_code.buf + pos, len);\n    }\n    return 0;\n}\n\n/* the control flow is recursive so the analysis can be linear */\nstatic int compute_stack_size(const uint8_t *bc_buf, int bc_buf_len)\n{\n    int stack_size, stack_size_max, pos, opcode, len;\n    uint32_t val;\n    \n    stack_size = 0;\n    stack_size_max = 0;\n    bc_buf += RE_HEADER_LEN;\n    bc_buf_len -= RE_HEADER_LEN;\n    pos = 0;\n    while (pos < bc_buf_len) {\n        opcode = bc_buf[pos];\n        len = reopcode_info[opcode].size;\n        assert(opcode < REOP_COUNT);\n        assert((pos + len) <= bc_buf_len);\n        switch(opcode) {\n        case REOP_push_i32:\n        case REOP_push_char_pos:\n            stack_size++;\n            if (stack_size > stack_size_max) {\n                if (stack_size > STACK_SIZE_MAX)\n                    return -1;\n                stack_size_max = stack_size;\n            }\n            break;\n        case REOP_drop:\n        case REOP_bne_char_pos:\n            assert(stack_size > 0);\n            stack_size--;\n            break;\n        case REOP_range:\n            val = get_u16(bc_buf + pos + 1);\n            len += val * 4;\n            break;\n        case REOP_range32:\n            val = get_u16(bc_buf + pos + 1);\n            len += val * 8;\n            break;\n        }\n        pos += len;\n    }\n    return stack_size_max;\n}\n\n/* 'buf' must be a zero terminated UTF-8 string of length buf_len.\n   Return NULL if error and allocate an error message in *perror_msg,\n   otherwise the compiled bytecode and its length in plen.\n*/\nuint8_t *lre_compile(int *plen, char *error_msg, int error_msg_size,\n                     const char *buf, size_t buf_len, int re_flags,\n                     void *opaque)\n{\n    REParseState s_s, *s = &s_s;\n    int stack_size;\n    BOOL is_sticky;\n    \n    memset(s, 0, sizeof(*s));\n    s->opaque = opaque;\n    s->buf_ptr = (const uint8_t *)buf;\n    s->buf_end = s->buf_ptr + buf_len;\n    s->buf_start = s->buf_ptr;\n    s->re_flags = re_flags;\n    s->is_utf16 = ((re_flags & LRE_FLAG_UTF16) != 0);\n    is_sticky = ((re_flags & LRE_FLAG_STICKY) != 0);\n    s->ignore_case = ((re_flags & LRE_FLAG_IGNORECASE) != 0);\n    s->dotall = ((re_flags & LRE_FLAG_DOTALL) != 0);\n    s->capture_count = 1;\n    s->total_capture_count = -1;\n    s->has_named_captures = -1;\n    \n    dbuf_init2(&s->byte_code, opaque, lre_realloc);\n    dbuf_init2(&s->group_names, opaque, lre_realloc);\n\n    dbuf_putc(&s->byte_code, re_flags); /* first element is the flags */\n    dbuf_putc(&s->byte_code, 0); /* second element is the number of captures */\n    dbuf_putc(&s->byte_code, 0); /* stack size */\n    dbuf_put_u32(&s->byte_code, 0); /* bytecode length */\n    \n    if (!is_sticky) {\n        /* iterate thru all positions (about the same as .*?( ... ) )\n           .  We do it without an explicit loop so that lock step\n           thread execution will be possible in an optimized\n           implementation */\n        re_emit_op_u32(s, REOP_split_goto_first, 1 + 5);\n        re_emit_op(s, REOP_any);\n        re_emit_op_u32(s, REOP_goto, -(5 + 1 + 5));\n    }\n    re_emit_op_u8(s, REOP_save_start, 0);\n\n    if (re_parse_disjunction(s, FALSE)) {\n    error:\n        dbuf_free(&s->byte_code);\n        dbuf_free(&s->group_names);\n        pstrcpy(error_msg, error_msg_size, s->u.error_msg);\n        *plen = 0;\n        return NULL;\n    }\n\n    re_emit_op_u8(s, REOP_save_end, 0);\n    \n    re_emit_op(s, REOP_match);\n\n    if (*s->buf_ptr != '\\0') {\n        re_parse_error(s, \"extraneous characters at the end\");\n        goto error;\n    }\n\n    if (dbuf_error(&s->byte_code)) {\n        re_parse_out_of_memory(s);\n        goto error;\n    }\n    \n    stack_size = compute_stack_size(s->byte_code.buf, s->byte_code.size);\n    if (stack_size < 0) {\n        re_parse_error(s, \"too many imbricated quantifiers\");\n        goto error;\n    }\n    \n    s->byte_code.buf[RE_HEADER_CAPTURE_COUNT] = s->capture_count;\n    s->byte_code.buf[RE_HEADER_STACK_SIZE] = stack_size;\n    put_u32(s->byte_code.buf + 3, s->byte_code.size - RE_HEADER_LEN);\n\n    /* add the named groups if needed */\n    if (s->group_names.size > (s->capture_count - 1)) {\n        dbuf_put(&s->byte_code, s->group_names.buf, s->group_names.size);\n        s->byte_code.buf[RE_HEADER_FLAGS] |= LRE_FLAG_NAMED_GROUPS;\n    }\n    dbuf_free(&s->group_names);\n    \n#ifdef DUMP_REOP\n    lre_dump_bytecode(s->byte_code.buf, s->byte_code.size);\n#endif\n    \n    error_msg[0] = '\\0';\n    *plen = s->byte_code.size;\n    return s->byte_code.buf;\n}\n\nstatic BOOL is_line_terminator(uint32_t c)\n{\n    return (c == '\\n' || c == '\\r' || c == CP_LS || c == CP_PS);\n}\n\nstatic BOOL is_word_char(uint32_t c)\n{\n    return ((c >= '0' && c <= '9') ||\n            (c >= 'a' && c <= 'z') ||\n            (c >= 'A' && c <= 'Z') ||\n            (c == '_'));\n}\n\n#define GET_CHAR(c, cptr, cbuf_end)                                     \\\n    do {                                                                \\\n        if (cbuf_type == 0) {                                           \\\n            c = *cptr++;                                                \\\n        } else {                                                        \\\n            uint32_t __c1;                                              \\\n            c = *(uint16_t *)cptr;                                      \\\n            cptr += 2;                                                  \\\n            if (c >= 0xd800 && c < 0xdc00 &&                            \\\n                cbuf_type == 2 && cptr < cbuf_end) {                    \\\n                __c1 = *(uint16_t *)cptr;                               \\\n                if (__c1 >= 0xdc00 && __c1 < 0xe000) {                  \\\n                    c = (((c & 0x3ff) << 10) | (__c1 & 0x3ff)) + 0x10000; \\\n                    cptr += 2;                                          \\\n                }                                                       \\\n            }                                                           \\\n        }                                                               \\\n    } while (0)\n\n#define PEEK_CHAR(c, cptr, cbuf_end)             \\\n    do {                                         \\\n        if (cbuf_type == 0) {                    \\\n            c = cptr[0];                         \\\n        } else {                                 \\\n            uint32_t __c1;                                              \\\n            c = ((uint16_t *)cptr)[0];                                  \\\n            if (c >= 0xd800 && c < 0xdc00 &&                            \\\n                cbuf_type == 2 && (cptr + 2) < cbuf_end) {              \\\n                __c1 = ((uint16_t *)cptr)[1];                           \\\n                if (__c1 >= 0xdc00 && __c1 < 0xe000) {                  \\\n                    c = (((c & 0x3ff) << 10) | (__c1 & 0x3ff)) + 0x10000; \\\n                }                                                       \\\n            }                                                           \\\n        }                                        \\\n    } while (0)\n\n#define PEEK_PREV_CHAR(c, cptr, cbuf_start)                 \\\n    do {                                         \\\n        if (cbuf_type == 0) {                    \\\n            c = cptr[-1];                        \\\n        } else {                                 \\\n            uint32_t __c1;                                              \\\n            c = ((uint16_t *)cptr)[-1];                                 \\\n            if (c >= 0xdc00 && c < 0xe000 &&                            \\\n                cbuf_type == 2 && (cptr - 4) >= cbuf_start) {              \\\n                __c1 = ((uint16_t *)cptr)[-2];                          \\\n                if (__c1 >= 0xd800 && __c1 < 0xdc00 ) {                 \\\n                    c = (((__c1 & 0x3ff) << 10) | (c & 0x3ff)) + 0x10000; \\\n                }                                                       \\\n            }                                                           \\\n        }                                                               \\\n    } while (0)\n\n#define GET_PREV_CHAR(c, cptr, cbuf_start)       \\\n    do {                                         \\\n        if (cbuf_type == 0) {                    \\\n            cptr--;                              \\\n            c = cptr[0];                         \\\n        } else {                                 \\\n            uint32_t __c1;                                              \\\n            cptr -= 2;                                                  \\\n            c = ((uint16_t *)cptr)[0];                                 \\\n            if (c >= 0xdc00 && c < 0xe000 &&                            \\\n                cbuf_type == 2 && cptr > cbuf_start) {                  \\\n                __c1 = ((uint16_t *)cptr)[-1];                          \\\n                if (__c1 >= 0xd800 && __c1 < 0xdc00 ) {                 \\\n                    cptr -= 2;                                          \\\n                    c = (((__c1 & 0x3ff) << 10) | (c & 0x3ff)) + 0x10000; \\\n                }                                                       \\\n            }                                                           \\\n        }                                                               \\\n    } while (0)\n\n#define PREV_CHAR(cptr, cbuf_start)       \\\n    do {                                  \\\n        if (cbuf_type == 0) {             \\\n            cptr--;                       \\\n        } else {                          \\\n            cptr -= 2;                          \\\n            if (cbuf_type == 2) {                                       \\\n                c = ((uint16_t *)cptr)[0];                              \\\n                if (c >= 0xdc00 && c < 0xe000 && cptr > cbuf_start) {   \\\n                    c = ((uint16_t *)cptr)[-1];                         \\\n                    if (c >= 0xd800 && c < 0xdc00)                      \\\n                        cptr -= 2;                                      \\\n                }                                                       \\\n            }                                                           \\\n        }                                                               \\\n    } while (0)\n\ntypedef uintptr_t StackInt;\n\ntypedef enum {\n    RE_EXEC_STATE_SPLIT,\n    RE_EXEC_STATE_LOOKAHEAD,\n    RE_EXEC_STATE_NEGATIVE_LOOKAHEAD,\n    RE_EXEC_STATE_GREEDY_QUANT,\n} REExecStateEnum;\n\ntypedef struct REExecState {\n    REExecStateEnum type : 8;\n    uint8_t stack_len;\n    size_t count; /* only used for RE_EXEC_STATE_GREEDY_QUANT */\n    const uint8_t *cptr;\n    const uint8_t *pc;\n    void *buf[0];\n} REExecState;\n\ntypedef struct {\n    const uint8_t *cbuf;\n    const uint8_t *cbuf_end;\n    /* 0 = 8 bit chars, 1 = 16 bit chars, 2 = 16 bit chars, UTF-16 */\n    int cbuf_type; \n    int capture_count;\n    int stack_size_max;\n    BOOL multi_line;\n    BOOL ignore_case;\n    BOOL is_utf16;\n    void *opaque; /* used for stack overflow check */\n\n    size_t state_size;\n    uint8_t *state_stack;\n    size_t state_stack_size;\n    size_t state_stack_len;\n} REExecContext;\n\nstatic int push_state(REExecContext *s,\n                      uint8_t **capture,\n                      StackInt *stack, size_t stack_len,\n                      const uint8_t *pc, const uint8_t *cptr,\n                      REExecStateEnum type, size_t count)\n{\n    REExecState *rs;\n    uint8_t *new_stack;\n    size_t new_size, i, n;\n    StackInt *stack_buf;\n\n    if (unlikely((s->state_stack_len + 1) > s->state_stack_size)) {\n        /* reallocate the stack */\n        new_size = s->state_stack_size * 3 / 2;\n        if (new_size < 8)\n            new_size = 8;\n        new_stack = lre_realloc(s->opaque, s->state_stack, new_size * s->state_size);\n        if (!new_stack)\n            return -1;\n        s->state_stack_size = new_size;\n        s->state_stack = new_stack;\n    }\n    rs = (REExecState *)(s->state_stack + s->state_stack_len * s->state_size);\n    s->state_stack_len++;\n    rs->type = type;\n    rs->count = count;\n    rs->stack_len = stack_len;\n    rs->cptr = cptr;\n    rs->pc = pc;\n    n = 2 * s->capture_count;\n    for(i = 0; i < n; i++)\n        rs->buf[i] = capture[i];\n    stack_buf = (StackInt *)(rs->buf + n);\n    for(i = 0; i < stack_len; i++)\n        stack_buf[i] = stack[i];\n    return 0;\n}\n\n/* return 1 if match, 0 if not match or -1 if error. */\nstatic intptr_t lre_exec_backtrack(REExecContext *s, uint8_t **capture,\n                                   StackInt *stack, int stack_len,\n                                   const uint8_t *pc, const uint8_t *cptr,\n                                   BOOL no_recurse)\n{\n    int opcode, ret;\n    int cbuf_type;\n    uint32_t val, c;\n    const uint8_t *cbuf_end;\n    \n    cbuf_type = s->cbuf_type;\n    cbuf_end = s->cbuf_end;\n\n    for(;;) {\n        //        printf(\"top=%p: pc=%d\\n\", th_list.top, (int)(pc - (bc_buf + RE_HEADER_LEN)));\n        opcode = *pc++;\n        switch(opcode) {\n        case REOP_match:\n            {\n                REExecState *rs;\n                if (no_recurse)\n                    return (intptr_t)cptr;\n                ret = 1;\n                goto recurse;\n            no_match:\n                if (no_recurse)\n                    return 0;\n                ret = 0;\n            recurse:\n                for(;;) {\n                    if (s->state_stack_len == 0)\n                        return ret;\n                    rs = (REExecState *)(s->state_stack +\n                                         (s->state_stack_len - 1) * s->state_size);\n                    if (rs->type == RE_EXEC_STATE_SPLIT) {\n                        if (!ret) {\n                        pop_state:\n                            memcpy(capture, rs->buf,\n                                   sizeof(capture[0]) * 2 * s->capture_count);\n                        pop_state1:\n                            pc = rs->pc;\n                            cptr = rs->cptr;\n                            stack_len = rs->stack_len;\n                            memcpy(stack, rs->buf + 2 * s->capture_count,\n                                   stack_len * sizeof(stack[0]));\n                            s->state_stack_len--;\n                            break;\n                        }\n                    } else if (rs->type == RE_EXEC_STATE_GREEDY_QUANT) {\n                        if (!ret) {\n                            uint32_t char_count, i;\n                            memcpy(capture, rs->buf,\n                                   sizeof(capture[0]) * 2 * s->capture_count);\n                            stack_len = rs->stack_len;\n                            memcpy(stack, rs->buf + 2 * s->capture_count,\n                                   stack_len * sizeof(stack[0]));\n                            pc = rs->pc;\n                            cptr = rs->cptr;\n                            /* go backward */\n                            char_count = get_u32(pc + 12);\n                            for(i = 0; i < char_count; i++) {\n                                PREV_CHAR(cptr, s->cbuf);\n                            }\n                            pc = (pc + 16) + (int)get_u32(pc);\n                            rs->cptr = cptr;\n                            rs->count--;\n                            if (rs->count == 0) {\n                                s->state_stack_len--;\n                            }\n                            break;\n                        }\n                    } else {\n                        ret = ((rs->type == RE_EXEC_STATE_LOOKAHEAD && ret) ||\n                               (rs->type == RE_EXEC_STATE_NEGATIVE_LOOKAHEAD && !ret));\n                        if (ret) {\n                            /* keep the capture in case of positive lookahead */\n                            if (rs->type == RE_EXEC_STATE_LOOKAHEAD)\n                                goto pop_state1;\n                            else\n                                goto pop_state;\n                        }\n                    }\n                    s->state_stack_len--;\n                }\n            }\n            break;\n        case REOP_char32:\n            val = get_u32(pc);\n            pc += 4;\n            goto test_char;\n        case REOP_char:\n            val = get_u16(pc);\n            pc += 2;\n        test_char:\n            if (cptr >= cbuf_end)\n                goto no_match;\n            GET_CHAR(c, cptr, cbuf_end);\n            if (s->ignore_case) {\n                c = lre_canonicalize(c, s->is_utf16);\n            }\n            if (val != c)\n                goto no_match;\n            break;\n        case REOP_split_goto_first:\n        case REOP_split_next_first:\n            {\n                const uint8_t *pc1;\n                \n                val = get_u32(pc);\n                pc += 4;\n                if (opcode == REOP_split_next_first) {\n                    pc1 = pc + (int)val;\n                } else {\n                    pc1 = pc;\n                    pc = pc + (int)val;\n                }\n                ret = push_state(s, capture, stack, stack_len,\n                                 pc1, cptr, RE_EXEC_STATE_SPLIT, 0);\n                if (ret < 0)\n                    return -1;\n                break;\n            }\n        case REOP_lookahead:\n        case REOP_negative_lookahead:\n            val = get_u32(pc);\n            pc += 4;\n            ret = push_state(s, capture, stack, stack_len,\n                             pc + (int)val, cptr,\n                             RE_EXEC_STATE_LOOKAHEAD + opcode - REOP_lookahead,\n                             0);\n            if (ret < 0)\n                return -1;\n            break;\n            \n        case REOP_goto:\n            val = get_u32(pc);\n            pc += 4 + (int)val;\n            break;\n        case REOP_line_start:\n            if (cptr == s->cbuf)\n                break;\n            if (!s->multi_line)\n                goto no_match;\n            PEEK_PREV_CHAR(c, cptr, s->cbuf);\n            if (!is_line_terminator(c))\n                goto no_match;\n            break;\n        case REOP_line_end:\n            if (cptr == cbuf_end)\n                break;\n            if (!s->multi_line)\n                goto no_match;\n            PEEK_CHAR(c, cptr, cbuf_end);\n            if (!is_line_terminator(c))\n                goto no_match;\n            break;\n        case REOP_dot:\n            if (cptr == cbuf_end)\n                goto no_match;\n            GET_CHAR(c, cptr, cbuf_end);\n            if (is_line_terminator(c))\n                goto no_match;\n            break;\n        case REOP_any:\n            if (cptr == cbuf_end)\n                goto no_match;\n            GET_CHAR(c, cptr, cbuf_end);\n            break;\n        case REOP_save_start:\n        case REOP_save_end:\n            val = *pc++;\n            assert(val < s->capture_count);\n            capture[2 * val + opcode - REOP_save_start] = (uint8_t *)cptr;\n            break;\n        case REOP_save_reset:\n            {\n                uint32_t val2;\n                val = pc[0];\n                val2 = pc[1];\n                pc += 2;\n                assert(val2 < s->capture_count);\n                while (val <= val2) {\n                    capture[2 * val] = NULL;\n                    capture[2 * val + 1] = NULL;\n                    val++;\n                }\n            }\n            break;\n        case REOP_push_i32:\n            val = get_u32(pc);\n            pc += 4;\n            stack[stack_len++] = val;\n            break;\n        case REOP_drop:\n            stack_len--;\n            break;\n        case REOP_loop:\n            val = get_u32(pc);\n            pc += 4;\n            if (--stack[stack_len - 1] != 0) {\n                pc += (int)val;\n            }\n            break;\n        case REOP_push_char_pos:\n            stack[stack_len++] = (uintptr_t)cptr;\n            break;\n        case REOP_bne_char_pos:\n            val = get_u32(pc);\n            pc += 4;\n            if (stack[--stack_len] != (uintptr_t)cptr)\n                pc += (int)val;\n            break;\n        case REOP_word_boundary:\n        case REOP_not_word_boundary:\n            {\n                BOOL v1, v2;\n                /* char before */\n                if (cptr == s->cbuf) {\n                    v1 = FALSE;\n                } else {\n                    PEEK_PREV_CHAR(c, cptr, s->cbuf);\n                    v1 = is_word_char(c);\n                }\n                /* current char */\n                if (cptr >= cbuf_end) {\n                    v2 = FALSE;\n                } else {\n                    PEEK_CHAR(c, cptr, cbuf_end);\n                    v2 = is_word_char(c);\n                }\n                if (v1 ^ v2 ^ (REOP_not_word_boundary - opcode))\n                    goto no_match;\n            }\n            break;\n        case REOP_back_reference:\n        case REOP_backward_back_reference:\n            {\n                const uint8_t *cptr1, *cptr1_end, *cptr1_start;\n                uint32_t c1, c2;\n                \n                val = *pc++;\n                if (val >= s->capture_count)\n                    goto no_match;\n                cptr1_start = capture[2 * val];\n                cptr1_end = capture[2 * val + 1];\n                if (!cptr1_start || !cptr1_end)\n                    break;\n                if (opcode == REOP_back_reference) {\n                    cptr1 = cptr1_start;\n                    while (cptr1 < cptr1_end) {\n                        if (cptr >= cbuf_end)\n                            goto no_match;\n                        GET_CHAR(c1, cptr1, cptr1_end);\n                        GET_CHAR(c2, cptr, cbuf_end);\n                        if (s->ignore_case) {\n                            c1 = lre_canonicalize(c1, s->is_utf16);\n                            c2 = lre_canonicalize(c2, s->is_utf16);\n                        }\n                        if (c1 != c2)\n                            goto no_match;\n                    }\n                } else {\n                    cptr1 = cptr1_end;\n                    while (cptr1 > cptr1_start) {\n                        if (cptr == s->cbuf)\n                            goto no_match;\n                        GET_PREV_CHAR(c1, cptr1, cptr1_start);\n                        GET_PREV_CHAR(c2, cptr, s->cbuf);\n                        if (s->ignore_case) {\n                            c1 = lre_canonicalize(c1, s->is_utf16);\n                            c2 = lre_canonicalize(c2, s->is_utf16);\n                        }\n                        if (c1 != c2)\n                            goto no_match;\n                    }\n                }\n            }\n            break;\n        case REOP_range:\n            {\n                int n;\n                uint32_t low, high, idx_min, idx_max, idx;\n                \n                n = get_u16(pc); /* n must be >= 1 */\n                pc += 2;\n                if (cptr >= cbuf_end)\n                    goto no_match;\n                GET_CHAR(c, cptr, cbuf_end);\n                if (s->ignore_case) {\n                    c = lre_canonicalize(c, s->is_utf16);\n                }\n                idx_min = 0;\n                low = get_u16(pc + 0 * 4);\n                if (c < low)\n                    goto no_match;\n                idx_max = n - 1;\n                high = get_u16(pc + idx_max * 4 + 2);\n                /* 0xffff in for last value means +infinity */\n                if (unlikely(c >= 0xffff) && high == 0xffff)\n                    goto range_match;\n                if (c > high)\n                    goto no_match;\n                while (idx_min <= idx_max) {\n                    idx = (idx_min + idx_max) / 2;\n                    low = get_u16(pc + idx * 4);\n                    high = get_u16(pc + idx * 4 + 2);\n                    if (c < low)\n                        idx_max = idx - 1;\n                    else if (c > high)\n                        idx_min = idx + 1;\n                    else\n                        goto range_match;\n                }\n                goto no_match;\n            range_match:\n                pc += 4 * n;\n            }\n            break;\n        case REOP_range32:\n            {\n                int n;\n                uint32_t low, high, idx_min, idx_max, idx;\n                \n                n = get_u16(pc); /* n must be >= 1 */\n                pc += 2;\n                if (cptr >= cbuf_end)\n                    goto no_match;\n                GET_CHAR(c, cptr, cbuf_end);\n                if (s->ignore_case) {\n                    c = lre_canonicalize(c, s->is_utf16);\n                }\n                idx_min = 0;\n                low = get_u32(pc + 0 * 8);\n                if (c < low)\n                    goto no_match;\n                idx_max = n - 1;\n                high = get_u32(pc + idx_max * 8 + 4);\n                if (c > high)\n                    goto no_match;\n                while (idx_min <= idx_max) {\n                    idx = (idx_min + idx_max) / 2;\n                    low = get_u32(pc + idx * 8);\n                    high = get_u32(pc + idx * 8 + 4);\n                    if (c < low)\n                        idx_max = idx - 1;\n                    else if (c > high)\n                        idx_min = idx + 1;\n                    else\n                        goto range32_match;\n                }\n                goto no_match;\n            range32_match:\n                pc += 8 * n;\n            }\n            break;\n        case REOP_prev:\n            /* go to the previous char */\n            if (cptr == s->cbuf)\n                goto no_match;\n            PREV_CHAR(cptr, s->cbuf);\n            break;\n        case REOP_simple_greedy_quant:\n            {\n                uint32_t next_pos, quant_min, quant_max;\n                size_t q;\n                intptr_t res;\n                const uint8_t *pc1;\n                \n                next_pos = get_u32(pc);\n                quant_min = get_u32(pc + 4);\n                quant_max = get_u32(pc + 8);\n                pc += 16;\n                pc1 = pc;\n                pc += (int)next_pos;\n                \n                q = 0;\n                for(;;) {\n                    res = lre_exec_backtrack(s, capture, stack, stack_len,\n                                             pc1, cptr, TRUE);\n                    if (res == -1)\n                        return res;\n                    if (!res)\n                        break;\n                    cptr = (uint8_t *)res;\n                    q++;\n                    if (q >= quant_max && quant_max != INT32_MAX)\n                        break;\n                }\n                if (q < quant_min)\n                    goto no_match;\n                if (q > quant_min) {\n                    /* will examine all matches down to quant_min */\n                    ret = push_state(s, capture, stack, stack_len,\n                                     pc1 - 16, cptr,\n                                     RE_EXEC_STATE_GREEDY_QUANT,\n                                     q - quant_min);\n                    if (ret < 0)\n                        return -1;\n                }\n            }\n            break;\n        default:\n            abort();\n        }\n    }\n}\n\n/* Return 1 if match, 0 if not match or -1 if error. cindex is the\n   starting position of the match and must be such as 0 <= cindex <=\n   clen. */\nint lre_exec(uint8_t **capture,\n             const uint8_t *bc_buf, const uint8_t *cbuf, int cindex, int clen,\n             int cbuf_type, void *opaque)\n{\n    REExecContext s_s, *s = &s_s;\n    int re_flags, i, alloca_size, ret;\n    StackInt *stack_buf;\n    \n    re_flags = bc_buf[RE_HEADER_FLAGS];\n    s->multi_line = (re_flags & LRE_FLAG_MULTILINE) != 0;\n    s->ignore_case = (re_flags & LRE_FLAG_IGNORECASE) != 0;\n    s->is_utf16 = (re_flags & LRE_FLAG_UTF16) != 0;\n    s->capture_count = bc_buf[RE_HEADER_CAPTURE_COUNT];\n    s->stack_size_max = bc_buf[RE_HEADER_STACK_SIZE];\n    s->cbuf = cbuf;\n    s->cbuf_end = cbuf + (clen << cbuf_type);\n    s->cbuf_type = cbuf_type;\n    if (s->cbuf_type == 1 && s->is_utf16)\n        s->cbuf_type = 2;\n    s->opaque = opaque;\n\n    s->state_size = sizeof(REExecState) +\n        s->capture_count * sizeof(capture[0]) * 2 +\n        s->stack_size_max * sizeof(stack_buf[0]);\n    s->state_stack = NULL;\n    s->state_stack_len = 0;\n    s->state_stack_size = 0;\n    \n    for(i = 0; i < s->capture_count * 2; i++)\n        capture[i] = NULL;\n    alloca_size = s->stack_size_max * sizeof(stack_buf[0]);\n    stack_buf = alloca(alloca_size);\n    ret = lre_exec_backtrack(s, capture, stack_buf, 0, bc_buf + RE_HEADER_LEN,\n                             cbuf + (cindex << cbuf_type), FALSE);\n    lre_realloc(s->opaque, s->state_stack, 0);\n    return ret;\n}\n\nint lre_get_capture_count(const uint8_t *bc_buf)\n{\n    return bc_buf[RE_HEADER_CAPTURE_COUNT];\n}\n\nint lre_get_flags(const uint8_t *bc_buf)\n{\n    return bc_buf[RE_HEADER_FLAGS];\n}\n\n/* Return NULL if no group names. Otherwise, return a pointer to\n   'capture_count - 1' zero terminated UTF-8 strings. */\nconst char *lre_get_groupnames(const uint8_t *bc_buf)\n{\n    uint32_t re_bytecode_len;\n    if ((lre_get_flags(bc_buf) & LRE_FLAG_NAMED_GROUPS) == 0)\n        return NULL;\n    re_bytecode_len = get_u32(bc_buf + 3);\n    return (const char *)(bc_buf + 7 + re_bytecode_len);\n}\n\n#ifdef TEST\n\nBOOL lre_check_stack_overflow(void *opaque, size_t alloca_size)\n{\n    return FALSE;\n}\n\nvoid *lre_realloc(void *opaque, void *ptr, size_t size)\n{\n    return realloc(ptr, size);\n}\n\nint main(int argc, char **argv)\n{\n    int len, ret, i;\n    uint8_t *bc;\n    char error_msg[64];\n    uint8_t *capture[CAPTURE_COUNT_MAX * 2];\n    const char *input;\n    int input_len, capture_count;\n    \n    if (argc < 3) {\n        printf(\"usage: %s regexp input\\n\", argv[0]);\n        exit(1);\n    }\n    bc = lre_compile(&len, error_msg, sizeof(error_msg), argv[1],\n                     strlen(argv[1]), 0, NULL);\n    if (!bc) {\n        fprintf(stderr, \"error: %s\\n\", error_msg);\n        exit(1);\n    }\n\n    input = argv[2];\n    input_len = strlen(input);\n    \n    ret = lre_exec(capture, bc, (uint8_t *)input, 0, input_len, 0, NULL);\n    printf(\"ret=%d\\n\", ret);\n    if (ret == 1) {\n        capture_count = lre_get_capture_count(bc);\n        for(i = 0; i < 2 * capture_count; i++) {\n            uint8_t *ptr;\n            ptr = capture[i];\n            printf(\"%d: \", i);\n            if (!ptr)\n                printf(\"<nil>\");\n            else\n                printf(\"%u\", (int)(ptr - (uint8_t *)input));\n            printf(\"\\n\");\n        }\n    }\n    return 0;\n}\n#endif\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/libregexp.h",
    "content": "/*\n * Regular Expression Engine\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#ifndef LIBREGEXP_H\n#define LIBREGEXP_H\n\n#include <stddef.h>\n\n#include \"libunicode.h\"\n\n#define LRE_BOOL  int       /* for documentation purposes */\n\n#define LRE_FLAG_GLOBAL     (1 << 0)\n#define LRE_FLAG_IGNORECASE (1 << 1)\n#define LRE_FLAG_MULTILINE  (1 << 2)\n#define LRE_FLAG_DOTALL     (1 << 3)\n#define LRE_FLAG_UTF16      (1 << 4)\n#define LRE_FLAG_STICKY     (1 << 5)\n\n#define LRE_FLAG_NAMED_GROUPS (1 << 7) /* named groups are present in the regexp */\n\nuint8_t *lre_compile(int *plen, char *error_msg, int error_msg_size,\n                     const char *buf, size_t buf_len, int re_flags,\n                     void *opaque);\nint lre_get_capture_count(const uint8_t *bc_buf);\nint lre_get_flags(const uint8_t *bc_buf);\nconst char *lre_get_groupnames(const uint8_t *bc_buf);\nint lre_exec(uint8_t **capture,\n             const uint8_t *bc_buf, const uint8_t *cbuf, int cindex, int clen,\n             int cbuf_type, void *opaque);\n\nint lre_parse_escape(const uint8_t **pp, int allow_utf16);\nLRE_BOOL lre_is_space(int c);\n\n/* must be provided by the user */\nLRE_BOOL lre_check_stack_overflow(void *opaque, size_t alloca_size); \nvoid *lre_realloc(void *opaque, void *ptr, size_t size);\n\n/* JS identifier test */\nextern uint32_t const lre_id_start_table_ascii[4];\nextern uint32_t const lre_id_continue_table_ascii[4];\n\nstatic inline int lre_js_is_ident_first(int c)\n{\n    if ((uint32_t)c < 128) {\n        return (lre_id_start_table_ascii[c >> 5] >> (c & 31)) & 1;\n    } else {\n#ifdef CONFIG_ALL_UNICODE\n        return lre_is_id_start(c);\n#else\n        return !lre_is_space(c);\n#endif\n    }\n}\n\nstatic inline int lre_js_is_ident_next(int c)\n{\n    if ((uint32_t)c < 128) {\n        return (lre_id_continue_table_ascii[c >> 5] >> (c & 31)) & 1;\n    } else {\n        /* ZWNJ and ZWJ are accepted in identifiers */\n#ifdef CONFIG_ALL_UNICODE\n        return lre_is_id_continue(c) || c == 0x200C || c == 0x200D;\n#else\n        return !lre_is_space(c) || c == 0x200C || c == 0x200D;\n#endif\n    }\n}\n\n#undef LRE_BOOL\n\n#endif /* LIBREGEXP_H */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/libunicode-table.h",
    "content": "/* Compressed unicode tables */\n/* Automatically generated file - do not edit */\n\n#include <stdint.h>\n\nstatic const uint32_t case_conv_table1[361] = {\n    0x00209a30, 0x00309a00, 0x005a8173, 0x00601730,\n    0x006c0730, 0x006f81b3, 0x00701700, 0x007c0700,\n    0x007f8100, 0x00803040, 0x009801c3, 0x00988190,\n    0x00990640, 0x009c9040, 0x00a481b4, 0x00a52e40,\n    0x00bc0130, 0x00bc8640, 0x00bf8170, 0x00c00100,\n    0x00c08130, 0x00c10440, 0x00c30130, 0x00c38240,\n    0x00c48230, 0x00c58240, 0x00c70130, 0x00c78130,\n    0x00c80130, 0x00c88240, 0x00c98130, 0x00ca0130,\n    0x00ca8100, 0x00cb0130, 0x00cb8130, 0x00cc0240,\n    0x00cd0100, 0x00ce0130, 0x00ce8130, 0x00cf0100,\n    0x00cf8130, 0x00d00640, 0x00d30130, 0x00d38240,\n    0x00d48130, 0x00d60240, 0x00d70130, 0x00d78240,\n    0x00d88230, 0x00d98440, 0x00db8130, 0x00dc0240,\n    0x00de0240, 0x00df8100, 0x00e20350, 0x00e38350,\n    0x00e50350, 0x00e69040, 0x00ee8100, 0x00ef1240,\n    0x00f801b4, 0x00f88350, 0x00fa0240, 0x00fb0130,\n    0x00fb8130, 0x00fc2840, 0x01100130, 0x01111240,\n    0x011d0131, 0x011d8240, 0x011e8130, 0x011f0131,\n    0x011f8201, 0x01208240, 0x01218130, 0x01220130,\n    0x01228130, 0x01230a40, 0x01280101, 0x01288101,\n    0x01290101, 0x01298100, 0x012a0100, 0x012b0200,\n    0x012c8100, 0x012d8100, 0x012e0101, 0x01300100,\n    0x01308101, 0x01318100, 0x01328101, 0x01330101,\n    0x01340100, 0x01348100, 0x01350101, 0x01358101,\n    0x01360101, 0x01378100, 0x01388101, 0x01390100,\n    0x013a8100, 0x013e8101, 0x01400100, 0x01410101,\n    0x01418100, 0x01438101, 0x01440100, 0x01448100,\n    0x01450200, 0x01460100, 0x01490100, 0x014e8101,\n    0x014f0101, 0x01a28173, 0x01b80440, 0x01bb0240,\n    0x01bd8300, 0x01bf8130, 0x01c30130, 0x01c40330,\n    0x01c60130, 0x01c70230, 0x01c801d0, 0x01c89130,\n    0x01d18930, 0x01d60100, 0x01d68300, 0x01d801d3,\n    0x01d89100, 0x01e10173, 0x01e18900, 0x01e60100,\n    0x01e68200, 0x01e78130, 0x01e80173, 0x01e88173,\n    0x01ea8173, 0x01eb0173, 0x01eb8100, 0x01ec1840,\n    0x01f80173, 0x01f88173, 0x01f90100, 0x01f98100,\n    0x01fa01a0, 0x01fa8173, 0x01fb8240, 0x01fc8130,\n    0x01fd0240, 0x01fe8330, 0x02001030, 0x02082030,\n    0x02182000, 0x02281000, 0x02302240, 0x02453640,\n    0x02600130, 0x02608e40, 0x02678100, 0x02686040,\n    0x0298a630, 0x02b0a600, 0x02c381b5, 0x08502631,\n    0x08638131, 0x08668131, 0x08682b00, 0x087e8300,\n    0x09d05011, 0x09f80610, 0x09fc0620, 0x0e400174,\n    0x0e408174, 0x0e410174, 0x0e418174, 0x0e420174,\n    0x0e428174, 0x0e430174, 0x0e438180, 0x0e440180,\n    0x0e482b30, 0x0e5e8330, 0x0ebc8101, 0x0ebe8101,\n    0x0ec70101, 0x0f007e40, 0x0f3f1840, 0x0f4b01b5,\n    0x0f4b81b6, 0x0f4c01b6, 0x0f4c81b6, 0x0f4d01b7,\n    0x0f4d8180, 0x0f4f0130, 0x0f506040, 0x0f800800,\n    0x0f840830, 0x0f880600, 0x0f8c0630, 0x0f900800,\n    0x0f940830, 0x0f980800, 0x0f9c0830, 0x0fa00600,\n    0x0fa40630, 0x0fa801b0, 0x0fa88100, 0x0fa901d3,\n    0x0fa98100, 0x0faa01d3, 0x0faa8100, 0x0fab01d3,\n    0x0fab8100, 0x0fac8130, 0x0fad8130, 0x0fae8130,\n    0x0faf8130, 0x0fb00800, 0x0fb40830, 0x0fb80200,\n    0x0fb90400, 0x0fbb0200, 0x0fbc0201, 0x0fbd0201,\n    0x0fbe0201, 0x0fc008b7, 0x0fc40867, 0x0fc808b8,\n    0x0fcc0868, 0x0fd008b8, 0x0fd40868, 0x0fd80200,\n    0x0fd901b9, 0x0fd981b1, 0x0fda01b9, 0x0fdb01b1,\n    0x0fdb81d7, 0x0fdc0230, 0x0fdd0230, 0x0fde0161,\n    0x0fdf0173, 0x0fe101b9, 0x0fe181b2, 0x0fe201ba,\n    0x0fe301b2, 0x0fe381d8, 0x0fe40430, 0x0fe60162,\n    0x0fe80200, 0x0fe901d0, 0x0fe981d0, 0x0feb01b0,\n    0x0feb81d0, 0x0fec0230, 0x0fed0230, 0x0ff00201,\n    0x0ff101d3, 0x0ff181d3, 0x0ff201ba, 0x0ff28101,\n    0x0ff301b0, 0x0ff381d3, 0x0ff40230, 0x0ff50230,\n    0x0ff60131, 0x0ff901ba, 0x0ff981b2, 0x0ffa01bb,\n    0x0ffb01b2, 0x0ffb81d9, 0x0ffc0230, 0x0ffd0230,\n    0x0ffe0162, 0x109301a0, 0x109501a0, 0x109581a0,\n    0x10990131, 0x10a70101, 0x10b01031, 0x10b81001,\n    0x10c18240, 0x125b1a31, 0x12681a01, 0x16002f31,\n    0x16182f01, 0x16300240, 0x16310130, 0x16318130,\n    0x16320130, 0x16328100, 0x16330100, 0x16338640,\n    0x16368130, 0x16370130, 0x16378130, 0x16380130,\n    0x16390240, 0x163a8240, 0x163f0230, 0x16406440,\n    0x16758440, 0x16790240, 0x16802600, 0x16938100,\n    0x16968100, 0x53202e40, 0x53401c40, 0x53910e40,\n    0x53993e40, 0x53bc8440, 0x53be8130, 0x53bf0a40,\n    0x53c58240, 0x53c68130, 0x53c80440, 0x53ca0101,\n    0x53cb1440, 0x53d50130, 0x53d58130, 0x53d60130,\n    0x53d68130, 0x53d70130, 0x53d80130, 0x53d88130,\n    0x53d90130, 0x53d98131, 0x53da0c40, 0x53e10240,\n    0x53e20131, 0x53e28130, 0x53e30130, 0x53e38440,\n    0x53fa8240, 0x55a98101, 0x55b85020, 0x7d8001b2,\n    0x7d8081b2, 0x7d8101b2, 0x7d8181da, 0x7d8201da,\n    0x7d8281b3, 0x7d8301b3, 0x7d8981bb, 0x7d8a01bb,\n    0x7d8a81bb, 0x7d8b01bc, 0x7d8b81bb, 0x7f909a31,\n    0x7fa09a01, 0x82002831, 0x82142801, 0x82582431,\n    0x826c2401, 0x86403331, 0x86603301, 0x8c502031,\n    0x8c602001, 0xb7202031, 0xb7302001, 0xf4802231,\n    0xf4912201,\n};\n\nstatic const uint8_t case_conv_table2[361] = {\n    0x01, 0x00, 0x9c, 0x06, 0x07, 0x4d, 0x03, 0x04,\n    0x10, 0x00, 0x8f, 0x0b, 0x00, 0x00, 0x11, 0x00,\n    0x08, 0x00, 0x53, 0x4a, 0x51, 0x00, 0x52, 0x00,\n    0x53, 0x00, 0x3a, 0x54, 0x55, 0x00, 0x57, 0x59,\n    0x3f, 0x5d, 0x5c, 0x00, 0x46, 0x61, 0x63, 0x42,\n    0x64, 0x00, 0x66, 0x00, 0x68, 0x00, 0x6a, 0x00,\n    0x6c, 0x00, 0x6e, 0x00, 0x00, 0x40, 0x00, 0x00,\n    0x00, 0x00, 0x1a, 0x00, 0x93, 0x00, 0x00, 0x20,\n    0x35, 0x00, 0x27, 0x00, 0x21, 0x00, 0x24, 0x22,\n    0x2a, 0x00, 0x13, 0x6b, 0x6d, 0x00, 0x26, 0x24,\n    0x27, 0x14, 0x16, 0x18, 0x1b, 0x1c, 0x3e, 0x1e,\n    0x3f, 0x1f, 0x39, 0x3d, 0x22, 0x21, 0x41, 0x1e,\n    0x40, 0x25, 0x25, 0x26, 0x28, 0x20, 0x2a, 0x49,\n    0x2c, 0x43, 0x2e, 0x4b, 0x30, 0x4c, 0x32, 0x44,\n    0x42, 0x99, 0x00, 0x00, 0x95, 0x8f, 0x7d, 0x7e,\n    0x83, 0x84, 0x12, 0x80, 0x82, 0x76, 0x77, 0x12,\n    0x7b, 0xa3, 0x7c, 0x78, 0x79, 0x8a, 0x92, 0x98,\n    0xa6, 0xa0, 0x85, 0x00, 0x9a, 0xa1, 0x93, 0x75,\n    0x33, 0x95, 0x00, 0x8e, 0x00, 0x74, 0x99, 0x98,\n    0x97, 0x96, 0x00, 0x00, 0x9e, 0x00, 0x9c, 0x00,\n    0xa1, 0xa0, 0x15, 0x2e, 0x2f, 0x30, 0xb4, 0xb5,\n    0x4e, 0xaa, 0xa9, 0x12, 0x14, 0x1e, 0x21, 0x22,\n    0x22, 0x2a, 0x34, 0x35, 0xa6, 0xa7, 0x36, 0x1f,\n    0x4a, 0x00, 0x00, 0x97, 0x01, 0x5a, 0xda, 0x1d,\n    0x36, 0x05, 0x00, 0xc4, 0xc3, 0xc6, 0xc5, 0xc8,\n    0xc7, 0xca, 0xc9, 0xcc, 0xcb, 0xc4, 0xd5, 0x45,\n    0xd6, 0x42, 0xd7, 0x46, 0xd8, 0xce, 0xd0, 0xd2,\n    0xd4, 0xda, 0xd9, 0xee, 0xf6, 0xfe, 0x0e, 0x07,\n    0x0f, 0x80, 0x9f, 0x00, 0x21, 0x80, 0xa3, 0xed,\n    0x00, 0xc0, 0x40, 0xc6, 0x60, 0xe7, 0xdb, 0xe6,\n    0x99, 0xc0, 0x00, 0x00, 0x06, 0x60, 0xdc, 0x29,\n    0xfd, 0x15, 0x12, 0x06, 0x16, 0xf8, 0xdd, 0x06,\n    0x15, 0x12, 0x84, 0x08, 0xc6, 0x16, 0xff, 0xdf,\n    0x03, 0xc0, 0x40, 0x00, 0x46, 0x60, 0xde, 0xe0,\n    0x6d, 0x37, 0x38, 0x39, 0x15, 0x14, 0x17, 0x16,\n    0x00, 0x1a, 0x19, 0x1c, 0x1b, 0x00, 0x5f, 0xb7,\n    0x65, 0x44, 0x47, 0x00, 0x4f, 0x62, 0x4e, 0x50,\n    0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0xa3, 0xa4,\n    0xa5, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb6, 0x00,\n    0x00, 0x5a, 0x00, 0x48, 0x00, 0x5b, 0x56, 0x58,\n    0x60, 0x5e, 0x70, 0x69, 0x6f, 0x4d, 0x00, 0x00,\n    0x3b, 0x67, 0xb8, 0x00, 0x00, 0x45, 0xa8, 0x8a,\n    0x8b, 0x8c, 0xab, 0xac, 0x58, 0x58, 0xaf, 0x94,\n    0xb0, 0x6f, 0xb2, 0x5c, 0x5b, 0x5e, 0x5d, 0x60,\n    0x5f, 0x62, 0x61, 0x64, 0x63, 0x66, 0x65, 0x68,\n    0x67,\n};\n\nstatic const uint16_t case_conv_ext[58] = {\n    0x0399, 0x0308, 0x0301, 0x03a5, 0x0313, 0x0300, 0x0342, 0x0391,\n    0x0397, 0x03a9, 0x0046, 0x0049, 0x004c, 0x0053, 0x0069, 0x0307,\n    0x02bc, 0x004e, 0x004a, 0x030c, 0x0535, 0x0552, 0x0048, 0x0331,\n    0x0054, 0x0057, 0x030a, 0x0059, 0x0041, 0x02be, 0x1f08, 0x1f80,\n    0x1f28, 0x1f90, 0x1f68, 0x1fa0, 0x1fba, 0x0386, 0x1fb3, 0x1fca,\n    0x0389, 0x1fc3, 0x03a1, 0x1ffa, 0x038f, 0x1ff3, 0x0544, 0x0546,\n    0x053b, 0x054e, 0x053d, 0x03b8, 0x0462, 0xa64a, 0x1e60, 0x03c9,\n    0x006b, 0x00e5,\n};\n\nstatic const uint8_t unicode_prop_Cased1_table[172] = {\n    0x40, 0xa9, 0x80, 0x8e, 0x80, 0xfc, 0x80, 0xd3,\n    0x80, 0x8c, 0x80, 0x8d, 0x81, 0x8d, 0x02, 0x80,\n    0xe1, 0x80, 0x91, 0x85, 0x9a, 0x01, 0x00, 0x01,\n    0x11, 0x00, 0x01, 0x04, 0x08, 0x01, 0x08, 0x30,\n    0x08, 0x01, 0x15, 0x20, 0x00, 0x39, 0x99, 0x31,\n    0x9d, 0x84, 0x40, 0x94, 0x80, 0xd6, 0x82, 0xa6,\n    0x80, 0x41, 0x62, 0x80, 0xa6, 0x80, 0x57, 0x76,\n    0xf8, 0x02, 0x80, 0x8f, 0x80, 0xb0, 0x40, 0xdb,\n    0x08, 0x80, 0x41, 0xd0, 0x80, 0x8c, 0x80, 0x8f,\n    0x8c, 0xe4, 0x03, 0x01, 0x89, 0x00, 0x14, 0x28,\n    0x10, 0x11, 0x02, 0x01, 0x18, 0x0b, 0x24, 0x4b,\n    0x26, 0x01, 0x01, 0x86, 0xe5, 0x80, 0x60, 0x79,\n    0xb6, 0x81, 0x40, 0x91, 0x81, 0xbd, 0x88, 0x94,\n    0x05, 0x80, 0x98, 0x80, 0xc7, 0x82, 0x43, 0x34,\n    0xa2, 0x06, 0x80, 0x8c, 0x61, 0x28, 0x96, 0xd4,\n    0x80, 0xc6, 0x01, 0x08, 0x09, 0x0b, 0x80, 0x8b,\n    0x00, 0x06, 0x80, 0xc0, 0x03, 0x0f, 0x06, 0x80,\n    0x9b, 0x03, 0x04, 0x00, 0x16, 0x80, 0x41, 0x53,\n    0x81, 0x98, 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98,\n    0x80, 0x9e, 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98,\n    0x80, 0x9e, 0x80, 0x98, 0x07, 0x59, 0x63, 0x99,\n    0x85, 0x99, 0x85, 0x99,\n};\n\nstatic const uint8_t unicode_prop_Cased1_index[18] = {\n    0xb9, 0x02, 0xe0, 0xa0, 0x1e, 0x40, 0x9e, 0xa6,\n    0x40, 0xba, 0xd4, 0x01, 0x89, 0xd7, 0x01, 0x8a,\n    0xf1, 0x01,\n};\n\nstatic const uint8_t unicode_prop_Case_Ignorable_table[692] = {\n    0xa6, 0x05, 0x80, 0x8a, 0x80, 0xa2, 0x00, 0x80,\n    0xc6, 0x03, 0x00, 0x03, 0x01, 0x81, 0x41, 0xf6,\n    0x40, 0xbf, 0x19, 0x18, 0x88, 0x08, 0x80, 0x40,\n    0xfa, 0x86, 0x40, 0xce, 0x04, 0x80, 0xb0, 0xac,\n    0x00, 0x01, 0x01, 0x00, 0xab, 0x80, 0x8a, 0x85,\n    0x89, 0x8a, 0x00, 0xa2, 0x80, 0x89, 0x94, 0x8f,\n    0x80, 0xe4, 0x38, 0x89, 0x03, 0xa0, 0x00, 0x80,\n    0x9d, 0x9a, 0xda, 0x8a, 0xb9, 0x8a, 0x18, 0x08,\n    0x97, 0x97, 0xaa, 0x82, 0xf6, 0xaf, 0xb6, 0x00,\n    0x03, 0x3b, 0x02, 0x86, 0x89, 0x81, 0x8c, 0x80,\n    0x8e, 0x80, 0xb9, 0x03, 0x1f, 0x80, 0x93, 0x81,\n    0x99, 0x01, 0x81, 0xb8, 0x03, 0x0b, 0x09, 0x12,\n    0x80, 0x9d, 0x0a, 0x80, 0x8a, 0x81, 0xb8, 0x03,\n    0x20, 0x0b, 0x80, 0x93, 0x81, 0x95, 0x28, 0x80,\n    0xb9, 0x01, 0x00, 0x1f, 0x06, 0x81, 0x8a, 0x81,\n    0x9d, 0x80, 0xbc, 0x80, 0x8b, 0x80, 0xb1, 0x02,\n    0x80, 0xb8, 0x14, 0x10, 0x1e, 0x81, 0x8a, 0x81,\n    0x9c, 0x80, 0xb9, 0x01, 0x05, 0x04, 0x81, 0x93,\n    0x81, 0x9b, 0x81, 0xb8, 0x0b, 0x1f, 0x80, 0x93,\n    0x81, 0x9c, 0x80, 0xc7, 0x06, 0x10, 0x80, 0xd9,\n    0x01, 0x86, 0x8a, 0x88, 0xe1, 0x01, 0x88, 0x88,\n    0x00, 0x85, 0xc9, 0x81, 0x9a, 0x00, 0x00, 0x80,\n    0xb6, 0x8d, 0x04, 0x01, 0x84, 0x8a, 0x80, 0xa3,\n    0x88, 0x80, 0xe5, 0x18, 0x28, 0x09, 0x81, 0x98,\n    0x0b, 0x82, 0x8f, 0x83, 0x8c, 0x01, 0x0d, 0x80,\n    0x8e, 0x80, 0xdd, 0x80, 0x42, 0x5f, 0x82, 0x43,\n    0xb1, 0x82, 0x9c, 0x82, 0x9c, 0x81, 0x9d, 0x81,\n    0xbf, 0x08, 0x37, 0x01, 0x8a, 0x10, 0x20, 0xac,\n    0x83, 0xb3, 0x80, 0xc0, 0x81, 0xa1, 0x80, 0xf5,\n    0x13, 0x81, 0x88, 0x05, 0x82, 0x40, 0xda, 0x09,\n    0x80, 0xb9, 0x00, 0x30, 0x00, 0x01, 0x3d, 0x89,\n    0x08, 0xa6, 0x07, 0x90, 0xbe, 0x83, 0xaf, 0x00,\n    0x20, 0x04, 0x80, 0xa7, 0x88, 0x8b, 0x81, 0x9f,\n    0x19, 0x08, 0x82, 0xb7, 0x00, 0x0a, 0x00, 0x82,\n    0xb9, 0x39, 0x81, 0xbf, 0x85, 0xd1, 0x10, 0x8c,\n    0x06, 0x18, 0x28, 0x11, 0xb1, 0xbe, 0x8c, 0x80,\n    0xa1, 0xde, 0x04, 0x41, 0xbc, 0x00, 0x82, 0x8a,\n    0x82, 0x8c, 0x82, 0x8c, 0x82, 0x8c, 0x81, 0x8b,\n    0x27, 0x81, 0x89, 0x01, 0x01, 0x84, 0xb0, 0x20,\n    0x89, 0x00, 0x8c, 0x80, 0x8f, 0x8c, 0xb2, 0xa0,\n    0x4b, 0x8a, 0x81, 0xf0, 0x82, 0xfc, 0x80, 0x8e,\n    0x80, 0xdf, 0x9f, 0xae, 0x80, 0x41, 0xd4, 0x80,\n    0xa3, 0x1a, 0x24, 0x80, 0xdc, 0x85, 0xdc, 0x82,\n    0x60, 0x6f, 0x15, 0x80, 0x44, 0xe1, 0x85, 0x41,\n    0x0d, 0x80, 0xe1, 0x18, 0x89, 0x00, 0x9b, 0x83,\n    0xcf, 0x81, 0x8d, 0xa1, 0xcd, 0x80, 0x96, 0x82,\n    0xec, 0x0f, 0x02, 0x03, 0x80, 0x98, 0x0c, 0x80,\n    0x40, 0x96, 0x81, 0x99, 0x91, 0x8c, 0x80, 0xa5,\n    0x87, 0x98, 0x8a, 0xad, 0x82, 0xaf, 0x01, 0x19,\n    0x81, 0x90, 0x80, 0x94, 0x81, 0xc1, 0x29, 0x09,\n    0x81, 0x8b, 0x07, 0x80, 0xa2, 0x80, 0x8a, 0x80,\n    0xb2, 0x00, 0x11, 0x0c, 0x08, 0x80, 0x9a, 0x80,\n    0x8d, 0x0c, 0x08, 0x80, 0xe3, 0x84, 0x88, 0x82,\n    0xf8, 0x01, 0x03, 0x80, 0x60, 0x4f, 0x2f, 0x80,\n    0x40, 0x92, 0x8f, 0x42, 0x3d, 0x8f, 0x10, 0x8b,\n    0x8f, 0xa1, 0x01, 0x80, 0x40, 0xa8, 0x06, 0x05,\n    0x80, 0x8a, 0x80, 0xa2, 0x00, 0x80, 0xae, 0x80,\n    0xac, 0x81, 0xc2, 0x80, 0x94, 0x82, 0x42, 0x00,\n    0x80, 0x40, 0xe1, 0x80, 0x40, 0x94, 0x84, 0x46,\n    0x85, 0x10, 0x0c, 0x83, 0xa7, 0x13, 0x80, 0x40,\n    0xa4, 0x81, 0x42, 0x3c, 0x83, 0x41, 0x82, 0x81,\n    0x40, 0x98, 0x8a, 0x40, 0xaf, 0x80, 0xb5, 0x8e,\n    0xb7, 0x82, 0xb0, 0x19, 0x09, 0x80, 0x8e, 0x80,\n    0xb1, 0x82, 0xa3, 0x20, 0x87, 0xbd, 0x80, 0x8b,\n    0x81, 0xb3, 0x88, 0x89, 0x19, 0x80, 0xde, 0x11,\n    0x00, 0x0d, 0x80, 0x40, 0x9f, 0x02, 0x87, 0x94,\n    0x81, 0xb8, 0x0a, 0x80, 0xa4, 0x32, 0x84, 0x40,\n    0xc2, 0x39, 0x10, 0x80, 0x96, 0x80, 0xd3, 0x28,\n    0x03, 0x08, 0x81, 0x40, 0xed, 0x1d, 0x08, 0x81,\n    0x9a, 0x81, 0xd4, 0x39, 0x00, 0x81, 0xe9, 0x00,\n    0x01, 0x28, 0x80, 0xe4, 0x11, 0x18, 0x84, 0x41,\n    0x02, 0x88, 0x01, 0x40, 0xff, 0x08, 0x03, 0x80,\n    0x40, 0x8f, 0x19, 0x0b, 0x80, 0x9f, 0x89, 0xa7,\n    0x29, 0x1f, 0x80, 0x88, 0x29, 0x82, 0xad, 0x8c,\n    0x01, 0x41, 0x95, 0x30, 0x28, 0x80, 0xd1, 0x95,\n    0x0e, 0x01, 0x01, 0xf9, 0x2a, 0x00, 0x08, 0x30,\n    0x80, 0xc7, 0x0a, 0x00, 0x80, 0x41, 0x5a, 0x81,\n    0x55, 0x3a, 0x88, 0x60, 0x36, 0xb6, 0x84, 0xba,\n    0x86, 0x88, 0x83, 0x44, 0x0a, 0x80, 0xbe, 0x90,\n    0xbf, 0x08, 0x81, 0x60, 0x4c, 0xb7, 0x08, 0x83,\n    0x54, 0xc2, 0x82, 0x88, 0x8f, 0x0e, 0x9d, 0x83,\n    0x40, 0x93, 0x82, 0x47, 0xba, 0xb6, 0x83, 0xb1,\n    0x38, 0x8d, 0x80, 0x95, 0x20, 0x8e, 0x45, 0x4f,\n    0x30, 0x90, 0x0e, 0x01, 0x04, 0x41, 0x04, 0x8d,\n    0x41, 0xad, 0x83, 0x45, 0xdf, 0x86, 0xec, 0x87,\n    0x4a, 0xae, 0x84, 0x6c, 0x0c, 0x00, 0x80, 0x9d,\n    0xdf, 0xff, 0x40, 0xef,\n};\n\nstatic const uint8_t unicode_prop_Case_Ignorable_index[66] = {\n    0xbe, 0x05, 0x00, 0xfe, 0x07, 0x00, 0x52, 0x0a,\n    0x20, 0x05, 0x0c, 0x20, 0x3b, 0x0e, 0x40, 0x61,\n    0x10, 0x40, 0x0f, 0x18, 0x20, 0x43, 0x1b, 0x60,\n    0x79, 0x1d, 0x00, 0xf1, 0x20, 0x00, 0x0d, 0xa6,\n    0x40, 0x2e, 0xa9, 0x20, 0xde, 0xaa, 0x00, 0x0f,\n    0xff, 0x20, 0xe7, 0x0a, 0x41, 0x82, 0x11, 0x21,\n    0xc4, 0x14, 0x61, 0x44, 0x19, 0x01, 0x48, 0x1d,\n    0x21, 0xa4, 0xbc, 0x01, 0x3e, 0xe1, 0x01, 0xf0,\n    0x01, 0x0e,\n};\n\nstatic const uint8_t unicode_prop_ID_Start_table[1045] = {\n    0xc0, 0x99, 0x85, 0x99, 0xae, 0x80, 0x89, 0x03,\n    0x04, 0x96, 0x80, 0x9e, 0x80, 0x41, 0xc9, 0x83,\n    0x8b, 0x8d, 0x26, 0x00, 0x80, 0x40, 0x80, 0x20,\n    0x09, 0x18, 0x05, 0x00, 0x10, 0x00, 0x93, 0x80,\n    0xd2, 0x80, 0x40, 0x8a, 0x87, 0x40, 0xa5, 0x80,\n    0xa5, 0x08, 0x85, 0xa8, 0xc6, 0x9a, 0x1b, 0xac,\n    0xaa, 0xa2, 0x08, 0xe2, 0x00, 0x8e, 0x0e, 0x81,\n    0x89, 0x11, 0x80, 0x8f, 0x00, 0x9d, 0x9c, 0xd8,\n    0x8a, 0x80, 0x97, 0xa0, 0x88, 0x0b, 0x04, 0x95,\n    0x18, 0x88, 0x02, 0x80, 0x96, 0x98, 0x86, 0x8a,\n    0xb4, 0x94, 0x80, 0x91, 0xbb, 0xb5, 0x10, 0x91,\n    0x06, 0x89, 0x8e, 0x8f, 0x1f, 0x09, 0x81, 0x95,\n    0x06, 0x00, 0x13, 0x10, 0x8f, 0x80, 0x8c, 0x08,\n    0x82, 0x8d, 0x81, 0x89, 0x07, 0x2b, 0x09, 0x95,\n    0x06, 0x01, 0x01, 0x01, 0x9e, 0x18, 0x80, 0x92,\n    0x82, 0x8f, 0x88, 0x02, 0x80, 0x95, 0x06, 0x01,\n    0x04, 0x10, 0x91, 0x80, 0x8e, 0x81, 0x96, 0x80,\n    0x8a, 0x39, 0x09, 0x95, 0x06, 0x01, 0x04, 0x10,\n    0x9d, 0x08, 0x82, 0x8e, 0x80, 0x90, 0x00, 0x2a,\n    0x10, 0x1a, 0x08, 0x00, 0x0a, 0x0a, 0x12, 0x8b,\n    0x95, 0x80, 0xb3, 0x38, 0x10, 0x96, 0x80, 0x8f,\n    0x10, 0x99, 0x14, 0x81, 0x9d, 0x03, 0x38, 0x10,\n    0x96, 0x80, 0x89, 0x04, 0x10, 0x9f, 0x00, 0x81,\n    0x8e, 0x81, 0x90, 0x88, 0x02, 0x80, 0xa8, 0x08,\n    0x8f, 0x04, 0x17, 0x82, 0x97, 0x2c, 0x91, 0x82,\n    0x97, 0x80, 0x88, 0x00, 0x0e, 0xb9, 0xaf, 0x01,\n    0x8b, 0x86, 0xb9, 0x08, 0x00, 0x20, 0x97, 0x00,\n    0x80, 0x89, 0x01, 0x88, 0x01, 0x20, 0x80, 0x94,\n    0x83, 0x9f, 0x80, 0xbe, 0x38, 0xa3, 0x9a, 0x84,\n    0xf2, 0xaa, 0x93, 0x80, 0x8f, 0x2b, 0x1a, 0x02,\n    0x0e, 0x13, 0x8c, 0x8b, 0x80, 0x90, 0xa5, 0x00,\n    0x20, 0x81, 0xaa, 0x80, 0x41, 0x4c, 0x03, 0x0e,\n    0x00, 0x03, 0x81, 0xa8, 0x03, 0x81, 0xa0, 0x03,\n    0x0e, 0x00, 0x03, 0x81, 0x8e, 0x80, 0xb8, 0x03,\n    0x81, 0xc2, 0xa4, 0x8f, 0x8f, 0xd5, 0x0d, 0x82,\n    0x42, 0x6b, 0x81, 0x90, 0x80, 0x99, 0x84, 0xca,\n    0x82, 0x8a, 0x86, 0x8c, 0x03, 0x8d, 0x91, 0x8d,\n    0x91, 0x8d, 0x8c, 0x02, 0x8e, 0xb3, 0xa2, 0x03,\n    0x80, 0xc2, 0xd8, 0x86, 0xa8, 0x00, 0x84, 0xc5,\n    0x89, 0x9e, 0xb0, 0x9d, 0x0c, 0x8a, 0xab, 0x83,\n    0x99, 0xb5, 0x96, 0x88, 0xb4, 0xd1, 0x80, 0xdc,\n    0xae, 0x90, 0x86, 0xb6, 0x9d, 0x8c, 0x81, 0x89,\n    0xab, 0x99, 0xa3, 0xa8, 0x82, 0x89, 0xa3, 0x81,\n    0x88, 0x86, 0xaa, 0x0a, 0xa8, 0x18, 0x28, 0x0a,\n    0x04, 0x40, 0xbf, 0xbf, 0x41, 0x15, 0x0d, 0x81,\n    0xa5, 0x0d, 0x0f, 0x00, 0x00, 0x00, 0x80, 0x9e,\n    0x81, 0xb4, 0x06, 0x00, 0x12, 0x06, 0x13, 0x0d,\n    0x83, 0x8c, 0x22, 0x06, 0xf3, 0x80, 0x8c, 0x80,\n    0x8f, 0x8c, 0xe4, 0x03, 0x01, 0x89, 0x00, 0x0d,\n    0x28, 0x00, 0x00, 0x80, 0x8f, 0x0b, 0x24, 0x18,\n    0x90, 0xa8, 0x4a, 0x76, 0xae, 0x80, 0xae, 0x80,\n    0x40, 0x84, 0x2b, 0x11, 0x8b, 0xa5, 0x00, 0x20,\n    0x81, 0xb7, 0x30, 0x8f, 0x96, 0x88, 0x30, 0x30,\n    0x30, 0x30, 0x30, 0x30, 0x30, 0x86, 0x42, 0x25,\n    0x82, 0x98, 0x88, 0x34, 0x0c, 0x83, 0xd5, 0x1c,\n    0x80, 0xd9, 0x03, 0x84, 0xaa, 0x80, 0xdd, 0x90,\n    0x9f, 0xaf, 0x8f, 0x41, 0xff, 0x59, 0xbf, 0xbf,\n    0x60, 0x51, 0xfc, 0x82, 0x44, 0x8c, 0xc2, 0xad,\n    0x81, 0x41, 0x0c, 0x82, 0x8f, 0x89, 0x81, 0x93,\n    0xae, 0x8f, 0x9e, 0x81, 0xcf, 0xa6, 0x88, 0x81,\n    0xe6, 0x81, 0xb4, 0x81, 0x88, 0xa9, 0x8c, 0x02,\n    0x03, 0x80, 0x96, 0x9c, 0xb3, 0x8d, 0xb1, 0xbd,\n    0x2a, 0x00, 0x81, 0x8a, 0x9b, 0x89, 0x96, 0x98,\n    0x9c, 0x86, 0xae, 0x9b, 0x80, 0x8f, 0x20, 0x89,\n    0x89, 0x20, 0xa8, 0x96, 0x10, 0x87, 0x93, 0x96,\n    0x10, 0x82, 0xb1, 0x00, 0x11, 0x0c, 0x08, 0x00,\n    0x97, 0x11, 0x8a, 0x32, 0x8b, 0x29, 0x29, 0x85,\n    0x88, 0x30, 0x30, 0xaa, 0x80, 0x8d, 0x85, 0xf2,\n    0x9c, 0x60, 0x2b, 0xa3, 0x8b, 0x96, 0x83, 0xb0,\n    0x60, 0x21, 0x03, 0x41, 0x6d, 0x81, 0xe9, 0xa5,\n    0x86, 0x8b, 0x24, 0x00, 0x89, 0x80, 0x8c, 0x04,\n    0x00, 0x01, 0x01, 0x80, 0xeb, 0xa0, 0x41, 0x6a,\n    0x91, 0xbf, 0x81, 0xb5, 0xa7, 0x8b, 0xf3, 0x20,\n    0x40, 0x86, 0xa3, 0x99, 0x85, 0x99, 0x8a, 0xd8,\n    0x15, 0x0d, 0x0d, 0x0a, 0xa2, 0x8b, 0x80, 0x99,\n    0x80, 0x92, 0x01, 0x80, 0x8e, 0x81, 0x8d, 0xa1,\n    0xfa, 0xc4, 0xb4, 0x41, 0x0a, 0x9c, 0x82, 0xb0,\n    0xae, 0x9f, 0x8c, 0x9d, 0x84, 0xa5, 0x89, 0x9d,\n    0x81, 0xa3, 0x1f, 0x04, 0xa9, 0x40, 0x9d, 0x91,\n    0xa3, 0x83, 0xa3, 0x83, 0xa7, 0x87, 0xb3, 0x40,\n    0x9b, 0x41, 0x36, 0x88, 0x95, 0x89, 0x87, 0x40,\n    0x97, 0x29, 0x00, 0xab, 0x01, 0x10, 0x81, 0x96,\n    0x89, 0x96, 0x88, 0x9e, 0xc0, 0x92, 0x01, 0x89,\n    0x95, 0x89, 0x99, 0xc5, 0xb7, 0x29, 0xbf, 0x80,\n    0x8e, 0x18, 0x10, 0x9c, 0xa9, 0x9c, 0x82, 0x9c,\n    0xa2, 0x38, 0x9b, 0x9a, 0xb5, 0x89, 0x95, 0x89,\n    0x92, 0x8c, 0x91, 0xed, 0xc8, 0xb6, 0xb2, 0x8c,\n    0xb2, 0x8c, 0xa3, 0x41, 0x5b, 0xa9, 0x29, 0xcd,\n    0x9c, 0x89, 0x07, 0x95, 0xe9, 0x94, 0x9a, 0x96,\n    0x8b, 0xb4, 0xca, 0xac, 0x9f, 0x98, 0x99, 0xa3,\n    0x9c, 0x01, 0x07, 0xa2, 0x10, 0x8b, 0xaf, 0x8d,\n    0x83, 0x94, 0x00, 0x80, 0xa2, 0x91, 0x80, 0x98,\n    0xd3, 0x30, 0x00, 0x18, 0x8e, 0x80, 0x89, 0x86,\n    0xae, 0xa5, 0x39, 0x09, 0x95, 0x06, 0x01, 0x04,\n    0x10, 0x91, 0x80, 0x8b, 0x84, 0x40, 0x9d, 0xb4,\n    0x91, 0x83, 0x93, 0x82, 0x9d, 0xaf, 0x93, 0x08,\n    0x80, 0x40, 0xb7, 0xae, 0xa8, 0x83, 0xa3, 0xaf,\n    0x93, 0x80, 0xba, 0xaa, 0x8c, 0x80, 0xc6, 0x9a,\n    0x40, 0xe4, 0xab, 0xf3, 0xbf, 0x9e, 0x39, 0x01,\n    0x38, 0x08, 0x97, 0x8e, 0x00, 0x80, 0xdd, 0x39,\n    0xa6, 0x8f, 0x00, 0x80, 0x9b, 0x80, 0x89, 0xa7,\n    0x30, 0x94, 0x80, 0x8a, 0xad, 0x92, 0x80, 0xa1,\n    0xb8, 0x41, 0x06, 0x88, 0x80, 0xa4, 0x90, 0x80,\n    0xb0, 0x9d, 0xef, 0x30, 0x08, 0xa5, 0x94, 0x80,\n    0x98, 0x28, 0x08, 0x9f, 0x8d, 0x80, 0x41, 0x46,\n    0x92, 0x40, 0xbc, 0x80, 0xce, 0x43, 0x99, 0xe5,\n    0xee, 0x90, 0x40, 0xc3, 0x4a, 0xbb, 0x44, 0x2e,\n    0x4f, 0xd0, 0x42, 0x46, 0x60, 0x21, 0xb8, 0x42,\n    0x38, 0x86, 0x9e, 0xf0, 0x9d, 0x91, 0xaf, 0x8f,\n    0x83, 0x9e, 0x94, 0x84, 0x92, 0x42, 0xaf, 0xbf,\n    0xff, 0xca, 0x20, 0xc1, 0x8c, 0xbf, 0x08, 0x80,\n    0x9b, 0x57, 0xf7, 0x87, 0x44, 0xd5, 0xa9, 0x88,\n    0x60, 0x22, 0xf6, 0x41, 0x1e, 0xb0, 0x82, 0x90,\n    0x1f, 0x41, 0x8b, 0x49, 0x03, 0xea, 0x84, 0x8c,\n    0x82, 0x88, 0x86, 0x89, 0x57, 0x65, 0xd4, 0x80,\n    0xc6, 0x01, 0x08, 0x09, 0x0b, 0x80, 0x8b, 0x00,\n    0x06, 0x80, 0xc0, 0x03, 0x0f, 0x06, 0x80, 0x9b,\n    0x03, 0x04, 0x00, 0x16, 0x80, 0x41, 0x53, 0x81,\n    0x98, 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98, 0x80,\n    0x9e, 0x80, 0x98, 0x80, 0x9e, 0x80, 0x98, 0x80,\n    0x9e, 0x80, 0x98, 0x07, 0x49, 0x33, 0xac, 0x89,\n    0x86, 0x8f, 0x80, 0x41, 0x70, 0xab, 0x45, 0x13,\n    0x40, 0xc4, 0xba, 0xc3, 0x30, 0x44, 0xb3, 0x18,\n    0x9a, 0x01, 0x00, 0x08, 0x80, 0x89, 0x03, 0x00,\n    0x00, 0x28, 0x18, 0x00, 0x00, 0x02, 0x01, 0x00,\n    0x08, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x0b,\n    0x06, 0x03, 0x03, 0x00, 0x80, 0x89, 0x80, 0x90,\n    0x22, 0x04, 0x80, 0x90, 0x51, 0x43, 0x60, 0xa6,\n    0xdd, 0xa1, 0x50, 0x34, 0x8a, 0x40, 0xdd, 0x81,\n    0x56, 0x81, 0x8d, 0x5d, 0x30, 0x4c, 0x1e, 0x42,\n    0x1d, 0x45, 0xe1, 0x53, 0x4a,\n};\n\nstatic const uint8_t unicode_prop_ID_Start_index[99] = {\n    0xf6, 0x03, 0x20, 0xa6, 0x07, 0x00, 0xa9, 0x09,\n    0x00, 0xb4, 0x0a, 0x00, 0xba, 0x0b, 0x00, 0x3e,\n    0x0d, 0x00, 0xe0, 0x0e, 0x20, 0x57, 0x12, 0x00,\n    0xeb, 0x16, 0x00, 0xca, 0x19, 0x20, 0xc0, 0x1d,\n    0x60, 0x80, 0x20, 0x00, 0x2e, 0x2d, 0x00, 0xc0,\n    0x31, 0x20, 0x89, 0xa7, 0x20, 0xf0, 0xa9, 0x00,\n    0xe3, 0xab, 0x00, 0x3e, 0xfd, 0x00, 0xfb, 0x00,\n    0x21, 0x37, 0x07, 0x61, 0x01, 0x0a, 0x01, 0x1d,\n    0x0f, 0x21, 0x2c, 0x12, 0x01, 0xc8, 0x14, 0x21,\n    0xd1, 0x19, 0x21, 0x47, 0x1d, 0x01, 0x39, 0x6a,\n    0x21, 0x09, 0x8d, 0x01, 0xbc, 0xd4, 0x01, 0xa9,\n    0xd7, 0x21, 0x3a, 0xee, 0x01, 0xde, 0xa6, 0x22,\n    0x4b, 0x13, 0x03,\n};\n\nstatic const uint8_t unicode_prop_ID_Continue1_table[626] = {\n    0xaf, 0x89, 0xa4, 0x80, 0xd6, 0x80, 0x42, 0x47,\n    0xef, 0x96, 0x80, 0x40, 0xfa, 0x84, 0x41, 0x08,\n    0xac, 0x00, 0x01, 0x01, 0x00, 0xc7, 0x8a, 0xaf,\n    0x9e, 0x28, 0xe4, 0x31, 0x29, 0x08, 0x19, 0x89,\n    0x96, 0x80, 0x9d, 0x9a, 0xda, 0x8a, 0x8e, 0x89,\n    0xa0, 0x88, 0x88, 0x80, 0x97, 0x18, 0x88, 0x02,\n    0x04, 0xaa, 0x82, 0xf6, 0x8e, 0x80, 0xa0, 0xb5,\n    0x10, 0x91, 0x06, 0x89, 0x09, 0x89, 0x90, 0x82,\n    0xb7, 0x00, 0x31, 0x09, 0x82, 0x88, 0x80, 0x89,\n    0x09, 0x89, 0x8d, 0x01, 0x82, 0xb7, 0x00, 0x23,\n    0x09, 0x12, 0x80, 0x93, 0x8b, 0x10, 0x8a, 0x82,\n    0xb7, 0x00, 0x38, 0x10, 0x82, 0x93, 0x09, 0x89,\n    0x89, 0x28, 0x82, 0xb7, 0x00, 0x31, 0x09, 0x16,\n    0x82, 0x89, 0x09, 0x89, 0x91, 0x80, 0xba, 0x22,\n    0x10, 0x83, 0x88, 0x80, 0x8d, 0x89, 0x8f, 0x84,\n    0xb8, 0x30, 0x10, 0x1e, 0x81, 0x8a, 0x09, 0x89,\n    0x90, 0x82, 0xb7, 0x00, 0x30, 0x10, 0x1e, 0x81,\n    0x8a, 0x09, 0x89, 0x8f, 0x83, 0xb6, 0x08, 0x30,\n    0x10, 0x83, 0x88, 0x80, 0x89, 0x09, 0x89, 0x90,\n    0x82, 0xc5, 0x03, 0x28, 0x00, 0x3d, 0x89, 0x09,\n    0xbc, 0x01, 0x86, 0x8b, 0x38, 0x89, 0xd6, 0x01,\n    0x88, 0x8a, 0x29, 0x89, 0xbd, 0x0d, 0x89, 0x8a,\n    0x00, 0x00, 0x03, 0x81, 0xb0, 0x93, 0x01, 0x84,\n    0x8a, 0x80, 0xa3, 0x88, 0x80, 0xe3, 0x93, 0x80,\n    0x89, 0x8b, 0x1b, 0x10, 0x11, 0x32, 0x83, 0x8c,\n    0x8b, 0x80, 0x8e, 0x42, 0xbe, 0x82, 0x88, 0x88,\n    0x43, 0x9f, 0x82, 0x9c, 0x82, 0x9c, 0x81, 0x9d,\n    0x81, 0xbf, 0x9f, 0x88, 0x01, 0x89, 0xa0, 0x11,\n    0x89, 0x40, 0x8e, 0x80, 0xf5, 0x8b, 0x83, 0x8b,\n    0x89, 0x89, 0xff, 0x8a, 0xbb, 0x84, 0xb8, 0x89,\n    0x80, 0x9c, 0x81, 0x8a, 0x85, 0x89, 0x95, 0x8d,\n    0x01, 0xbe, 0x84, 0xae, 0x90, 0x8a, 0x89, 0x90,\n    0x88, 0x8b, 0x82, 0x9d, 0x8c, 0x81, 0x89, 0xab,\n    0x8d, 0xaf, 0x93, 0x87, 0x89, 0x85, 0x89, 0xf5,\n    0x10, 0x94, 0x18, 0x28, 0x0a, 0x40, 0xc5, 0xb9,\n    0x04, 0x42, 0x3e, 0x81, 0x92, 0x80, 0xfa, 0x8c,\n    0x18, 0x82, 0x8b, 0x4b, 0xfd, 0x82, 0x40, 0x8c,\n    0x80, 0xdf, 0x9f, 0x42, 0x29, 0x85, 0xe8, 0x81,\n    0x60, 0x75, 0x84, 0x89, 0xc4, 0x03, 0x89, 0x9f,\n    0x81, 0xcf, 0x81, 0x41, 0x0f, 0x02, 0x03, 0x80,\n    0x96, 0x23, 0x80, 0xd2, 0x81, 0xb1, 0x91, 0x89,\n    0x89, 0x85, 0x91, 0x8c, 0x8a, 0x9b, 0x87, 0x98,\n    0x8c, 0xab, 0x83, 0xae, 0x8d, 0x8e, 0x89, 0x8a,\n    0x80, 0x89, 0x89, 0xae, 0x8d, 0x8b, 0x07, 0x09,\n    0x89, 0xa0, 0x82, 0xb1, 0x00, 0x11, 0x0c, 0x08,\n    0x80, 0xa8, 0x24, 0x81, 0x40, 0xeb, 0x38, 0x09,\n    0x89, 0x60, 0x4f, 0x23, 0x80, 0x42, 0xe0, 0x8f,\n    0x8f, 0x8f, 0x11, 0x97, 0x82, 0x40, 0xbf, 0x89,\n    0xa4, 0x80, 0x42, 0xbc, 0x80, 0x40, 0xe1, 0x80,\n    0x40, 0x94, 0x84, 0x41, 0x24, 0x89, 0x45, 0x56,\n    0x10, 0x0c, 0x83, 0xa7, 0x13, 0x80, 0x40, 0xa4,\n    0x81, 0x42, 0x3c, 0x1f, 0x89, 0x41, 0x70, 0x81,\n    0x40, 0x98, 0x8a, 0x40, 0xae, 0x82, 0xb4, 0x8e,\n    0x9e, 0x89, 0x8e, 0x83, 0xac, 0x8a, 0xb4, 0x89,\n    0x2a, 0xa3, 0x8d, 0x80, 0x89, 0x21, 0xab, 0x80,\n    0x8b, 0x82, 0xaf, 0x8d, 0x3b, 0x80, 0x8b, 0xd1,\n    0x8b, 0x28, 0x40, 0x9f, 0x8b, 0x84, 0x89, 0x2b,\n    0xb6, 0x08, 0x31, 0x09, 0x82, 0x88, 0x80, 0x89,\n    0x09, 0x32, 0x84, 0x40, 0xbf, 0x91, 0x88, 0x89,\n    0x18, 0xd0, 0x93, 0x8b, 0x89, 0x40, 0xd4, 0x31,\n    0x88, 0x9a, 0x81, 0xd1, 0x90, 0x8e, 0x89, 0xd0,\n    0x8c, 0x87, 0x89, 0xd2, 0x8e, 0x83, 0x89, 0x40,\n    0xf1, 0x8e, 0x40, 0xa4, 0x89, 0xc5, 0x28, 0x09,\n    0x18, 0x00, 0x81, 0x8b, 0x89, 0xf6, 0x31, 0x32,\n    0x80, 0x9b, 0x89, 0xa7, 0x30, 0x1f, 0x80, 0x88,\n    0x8a, 0xad, 0x8f, 0x41, 0x94, 0x38, 0x87, 0x8f,\n    0x89, 0xb7, 0x95, 0x80, 0x8d, 0xf9, 0x2a, 0x00,\n    0x08, 0x30, 0x07, 0x89, 0xaf, 0x20, 0x08, 0x27,\n    0x89, 0x41, 0x48, 0x83, 0x60, 0x4b, 0x68, 0x89,\n    0x40, 0x85, 0x84, 0xba, 0x86, 0x98, 0x89, 0x43,\n    0xf4, 0x00, 0xb6, 0x33, 0xd0, 0x80, 0x8a, 0x81,\n    0x60, 0x4c, 0xaa, 0x81, 0x54, 0xc5, 0x22, 0x2f,\n    0x39, 0x86, 0x9d, 0x83, 0x40, 0x93, 0x82, 0x45,\n    0x88, 0xb1, 0x41, 0xff, 0xb6, 0x83, 0xb1, 0x38,\n    0x8d, 0x80, 0x95, 0x20, 0x8e, 0x45, 0x4f, 0x30,\n    0x90, 0x0e, 0x01, 0x04, 0x41, 0x04, 0x86, 0x88,\n    0x89, 0x41, 0xa1, 0x8d, 0x45, 0xd5, 0x86, 0xec,\n    0x34, 0x89, 0x52, 0x95, 0x89, 0x6c, 0x05, 0x05,\n    0x40, 0xef,\n};\n\nstatic const uint8_t unicode_prop_ID_Continue1_index[60] = {\n    0xfa, 0x06, 0x00, 0x84, 0x09, 0x00, 0xf0, 0x0a,\n    0x00, 0x70, 0x0c, 0x00, 0xf4, 0x0d, 0x00, 0x4a,\n    0x10, 0x20, 0x1a, 0x18, 0x20, 0x74, 0x1b, 0x20,\n    0xdd, 0x20, 0x00, 0x0c, 0xa8, 0x00, 0x5a, 0xaa,\n    0x20, 0x1a, 0xff, 0x00, 0xad, 0x0e, 0x01, 0x38,\n    0x12, 0x21, 0xc1, 0x15, 0x21, 0xe5, 0x19, 0x21,\n    0xaa, 0x1d, 0x21, 0x8c, 0xd1, 0x41, 0x4a, 0xe1,\n    0x21, 0xf0, 0x01, 0x0e,\n};\n\n#ifdef CONFIG_ALL_UNICODE\n\nstatic const uint8_t unicode_cc_table[851] = {\n    0xb2, 0xcf, 0xd4, 0x00, 0xe8, 0x03, 0xdc, 0x00,\n    0xe8, 0x00, 0xd8, 0x04, 0xdc, 0x01, 0xca, 0x03,\n    0xdc, 0x01, 0xca, 0x0a, 0xdc, 0x04, 0x01, 0x03,\n    0xdc, 0xc7, 0x00, 0xf0, 0xc0, 0x02, 0xdc, 0xc2,\n    0x01, 0xdc, 0x80, 0xc2, 0x03, 0xdc, 0xc0, 0x00,\n    0xe8, 0x01, 0xdc, 0xc0, 0x41, 0xe9, 0x00, 0xea,\n    0x41, 0xe9, 0x00, 0xea, 0x00, 0xe9, 0xcc, 0xb0,\n    0xe2, 0xc4, 0xb0, 0xd8, 0x00, 0xdc, 0xc3, 0x00,\n    0xdc, 0xc2, 0x00, 0xde, 0x00, 0xdc, 0xc5, 0x05,\n    0xdc, 0xc1, 0x00, 0xdc, 0xc1, 0x00, 0xde, 0x00,\n    0xe4, 0xc0, 0x49, 0x0a, 0x43, 0x13, 0x80, 0x00,\n    0x17, 0x80, 0x41, 0x18, 0x80, 0xc0, 0x00, 0xdc,\n    0x80, 0x00, 0x12, 0xb0, 0x17, 0xc7, 0x42, 0x1e,\n    0xaf, 0x47, 0x1b, 0xc1, 0x01, 0xdc, 0xc4, 0x00,\n    0xdc, 0xc1, 0x00, 0xdc, 0x8f, 0x00, 0x23, 0xb0,\n    0x34, 0xc6, 0x81, 0xc3, 0x00, 0xdc, 0xc0, 0x81,\n    0xc1, 0x80, 0x00, 0xdc, 0xc1, 0x00, 0xdc, 0xa2,\n    0x00, 0x24, 0x9d, 0xc0, 0x00, 0xdc, 0xc1, 0x00,\n    0xdc, 0xc1, 0x02, 0xdc, 0xc0, 0x01, 0xdc, 0xc0,\n    0x00, 0xdc, 0xc2, 0x00, 0xdc, 0xc0, 0x00, 0xdc,\n    0xc0, 0x00, 0xdc, 0xc0, 0x00, 0xdc, 0xc1, 0xb0,\n    0x6f, 0xc6, 0x00, 0xdc, 0xc0, 0x88, 0x00, 0xdc,\n    0x97, 0xc3, 0x80, 0xc8, 0x80, 0xc2, 0x80, 0xc4,\n    0xaa, 0x02, 0xdc, 0xb0, 0x46, 0x00, 0xdc, 0xcd,\n    0x80, 0x00, 0xdc, 0xc1, 0x00, 0xdc, 0xc1, 0x00,\n    0xdc, 0xc2, 0x02, 0xdc, 0x42, 0x1b, 0xc2, 0x00,\n    0xdc, 0xc1, 0x01, 0xdc, 0xc4, 0xb0, 0x0b, 0x00,\n    0x07, 0x8f, 0x00, 0x09, 0x82, 0xc0, 0x00, 0xdc,\n    0xc1, 0xb0, 0x36, 0x00, 0x07, 0x8f, 0x00, 0x09,\n    0xaf, 0xc0, 0xb0, 0x0c, 0x00, 0x07, 0x8f, 0x00,\n    0x09, 0xb0, 0x3d, 0x00, 0x07, 0x8f, 0x00, 0x09,\n    0xb0, 0x3d, 0x00, 0x07, 0x8f, 0x00, 0x09, 0xb0,\n    0x4e, 0x00, 0x09, 0xb0, 0x4e, 0x00, 0x09, 0x86,\n    0x00, 0x54, 0x00, 0x5b, 0xb0, 0x34, 0x00, 0x07,\n    0x8f, 0x00, 0x09, 0xb0, 0x3c, 0x01, 0x09, 0x8f,\n    0x00, 0x09, 0xb0, 0x4b, 0x00, 0x09, 0xb0, 0x3c,\n    0x01, 0x67, 0x00, 0x09, 0x8c, 0x03, 0x6b, 0xb0,\n    0x3b, 0x01, 0x76, 0x00, 0x09, 0x8c, 0x03, 0x7a,\n    0xb0, 0x1b, 0x01, 0xdc, 0x9a, 0x00, 0xdc, 0x80,\n    0x00, 0xdc, 0x80, 0x00, 0xd8, 0xb0, 0x06, 0x41,\n    0x81, 0x80, 0x00, 0x84, 0x84, 0x03, 0x82, 0x81,\n    0x00, 0x82, 0x80, 0xc1, 0x00, 0x09, 0x80, 0xc1,\n    0xb0, 0x0d, 0x00, 0xdc, 0xb0, 0x3f, 0x00, 0x07,\n    0x80, 0x01, 0x09, 0xb0, 0x21, 0x00, 0xdc, 0xb2,\n    0x9e, 0xc2, 0xb3, 0x83, 0x00, 0x09, 0x9e, 0x00,\n    0x09, 0xb0, 0x6c, 0x00, 0x09, 0x89, 0xc0, 0xb0,\n    0x9a, 0x00, 0xe4, 0xb0, 0x5e, 0x00, 0xde, 0xc0,\n    0x00, 0xdc, 0xb0, 0xaa, 0xc0, 0x00, 0xdc, 0xb0,\n    0x16, 0x00, 0x09, 0x93, 0xc7, 0x81, 0x00, 0xdc,\n    0xaf, 0xc4, 0x05, 0xdc, 0xc1, 0x00, 0xdc, 0x80,\n    0x01, 0xdc, 0xb0, 0x42, 0x00, 0x07, 0x8e, 0x00,\n    0x09, 0xa5, 0xc0, 0x00, 0xdc, 0xc6, 0xb0, 0x05,\n    0x01, 0x09, 0xb0, 0x09, 0x00, 0x07, 0x8a, 0x01,\n    0x09, 0xb0, 0x12, 0x00, 0x07, 0xb0, 0x67, 0xc2,\n    0x41, 0x00, 0x04, 0xdc, 0xc1, 0x03, 0xdc, 0xc0,\n    0x41, 0x00, 0x05, 0x01, 0x83, 0x00, 0xdc, 0x85,\n    0xc0, 0x82, 0xc1, 0xb0, 0x95, 0xc1, 0x00, 0xdc,\n    0xc6, 0x00, 0xdc, 0xc1, 0x00, 0xea, 0x00, 0xd6,\n    0x00, 0xdc, 0x00, 0xca, 0xe4, 0x00, 0xe8, 0x01,\n    0xe4, 0x00, 0xdc, 0x80, 0xc0, 0x00, 0xe9, 0x00,\n    0xdc, 0xc0, 0x00, 0xdc, 0xb2, 0x9f, 0xc1, 0x01,\n    0x01, 0xc3, 0x02, 0x01, 0xc1, 0x83, 0xc0, 0x82,\n    0x01, 0x01, 0xc0, 0x00, 0xdc, 0xc0, 0x01, 0x01,\n    0x03, 0xdc, 0xc0, 0xb8, 0x03, 0xcd, 0xc2, 0xb0,\n    0x5c, 0x00, 0x09, 0xb0, 0x2f, 0xdf, 0xb1, 0xf9,\n    0x00, 0xda, 0x00, 0xe4, 0x00, 0xe8, 0x00, 0xde,\n    0x01, 0xe0, 0xb0, 0x38, 0x01, 0x08, 0xb8, 0x6d,\n    0xa3, 0xc0, 0x83, 0xc9, 0x9f, 0xc1, 0xb0, 0x1f,\n    0xc1, 0xb0, 0xe3, 0x00, 0x09, 0xa4, 0x00, 0x09,\n    0xb0, 0x66, 0x00, 0x09, 0x9a, 0xd1, 0xb0, 0x08,\n    0x02, 0xdc, 0xa4, 0x00, 0x09, 0xb0, 0x2e, 0x00,\n    0x07, 0x8b, 0x00, 0x09, 0xb0, 0xbe, 0xc0, 0x80,\n    0xc1, 0x00, 0xdc, 0x81, 0xc1, 0x84, 0xc1, 0x80,\n    0xc0, 0xb0, 0x03, 0x00, 0x09, 0xb0, 0xc5, 0x00,\n    0x09, 0xb8, 0x46, 0xff, 0x00, 0x1a, 0xb2, 0xd0,\n    0xc6, 0x06, 0xdc, 0xc1, 0xb3, 0x9c, 0x00, 0xdc,\n    0xb0, 0xb1, 0x00, 0xdc, 0xb0, 0x64, 0xc4, 0xb6,\n    0x61, 0x00, 0xdc, 0x80, 0xc0, 0xa7, 0xc0, 0x00,\n    0x01, 0x00, 0xdc, 0x83, 0x00, 0x09, 0xb0, 0x74,\n    0xc0, 0x00, 0xdc, 0xb2, 0x0c, 0xc3, 0xb1, 0x52,\n    0xc1, 0xb0, 0x68, 0x01, 0xdc, 0xc2, 0x00, 0xdc,\n    0xc0, 0x03, 0xdc, 0xb0, 0xc4, 0x00, 0x09, 0xb0,\n    0x07, 0x00, 0x09, 0xb0, 0x08, 0x00, 0x09, 0x00,\n    0x07, 0xb0, 0x14, 0xc2, 0xaf, 0x01, 0x09, 0xb0,\n    0x0d, 0x00, 0x07, 0xb0, 0x1b, 0x00, 0x09, 0x88,\n    0x00, 0x07, 0xb0, 0x39, 0x00, 0x09, 0x00, 0x07,\n    0xb0, 0x81, 0x00, 0x07, 0x00, 0x09, 0xb0, 0x1f,\n    0x01, 0x07, 0x8f, 0x00, 0x09, 0x97, 0xc6, 0x82,\n    0xc4, 0xb0, 0x9c, 0x00, 0x09, 0x82, 0x00, 0x07,\n    0x96, 0xc0, 0xb0, 0x32, 0x00, 0x09, 0x00, 0x07,\n    0xb0, 0xca, 0x00, 0x09, 0x00, 0x07, 0xb0, 0x4d,\n    0x00, 0x09, 0xb0, 0x45, 0x00, 0x09, 0x00, 0x07,\n    0xb0, 0x42, 0x00, 0x09, 0xb0, 0xdc, 0x00, 0x09,\n    0x00, 0x07, 0xb0, 0xd1, 0x01, 0x09, 0x83, 0x00,\n    0x07, 0xb0, 0x6b, 0x00, 0x09, 0xb0, 0x22, 0x00,\n    0x09, 0x91, 0x00, 0x09, 0xb0, 0x20, 0x00, 0x09,\n    0xb1, 0x74, 0x00, 0x09, 0xb0, 0xd1, 0x00, 0x07,\n    0x80, 0x01, 0x09, 0xb0, 0x20, 0x00, 0x09, 0xb8,\n    0x45, 0x27, 0x04, 0x01, 0xb0, 0x0a, 0xc6, 0xb4,\n    0x88, 0x01, 0x06, 0xb8, 0x44, 0x7b, 0x00, 0x01,\n    0xb8, 0x0c, 0x95, 0x01, 0xd8, 0x02, 0x01, 0x82,\n    0x00, 0xe2, 0x04, 0xd8, 0x87, 0x07, 0xdc, 0x81,\n    0xc4, 0x01, 0xdc, 0x9d, 0xc3, 0xb0, 0x63, 0xc2,\n    0xb8, 0x05, 0x8a, 0xc6, 0x80, 0xd0, 0x81, 0xc6,\n    0x80, 0xc1, 0x80, 0xc4, 0xb0, 0xd4, 0xc6, 0xb1,\n    0x84, 0xc3, 0xb5, 0xaf, 0x06, 0xdc, 0xb0, 0x3c,\n    0xc5, 0x00, 0x07,\n};\n\nstatic const uint8_t unicode_cc_index[81] = {\n    0x4d, 0x03, 0x00, 0x97, 0x05, 0x20, 0xc6, 0x05,\n    0x00, 0xe7, 0x06, 0x00, 0x45, 0x07, 0x00, 0xe2,\n    0x08, 0x00, 0x53, 0x09, 0x00, 0xcd, 0x0b, 0x20,\n    0x38, 0x0e, 0x00, 0x73, 0x0f, 0x20, 0x5d, 0x13,\n    0x20, 0x60, 0x1a, 0x20, 0xaa, 0x1b, 0x00, 0xf4,\n    0x1c, 0x00, 0xfe, 0x1d, 0x20, 0x7f, 0x2d, 0x20,\n    0xf0, 0xa6, 0x00, 0xb2, 0xaa, 0x00, 0xfe, 0x01,\n    0x01, 0xab, 0x0e, 0x01, 0x73, 0x11, 0x21, 0x70,\n    0x13, 0x01, 0xb8, 0x16, 0x01, 0x9a, 0x1a, 0x01,\n    0x9f, 0xbc, 0x01, 0x22, 0xe0, 0x01, 0x4b, 0xe9,\n    0x01,\n};\n\nstatic const uint32_t unicode_decomp_table1[690] = {\n    0x00280081, 0x002a0097, 0x002a8081, 0x002bc097,\n    0x002c8115, 0x002d0097, 0x002d4081, 0x002e0097,\n    0x002e4115, 0x002f0199, 0x00302016, 0x00400842,\n    0x00448a42, 0x004a0442, 0x004c0096, 0x004c8117,\n    0x004d0242, 0x004e4342, 0x004fc12f, 0x0050c342,\n    0x005240bf, 0x00530342, 0x00550942, 0x005a0842,\n    0x005e0096, 0x005e4342, 0x005fc081, 0x00680142,\n    0x006bc142, 0x00710185, 0x0071c317, 0x00734844,\n    0x00778344, 0x00798342, 0x007b02be, 0x007c4197,\n    0x007d0142, 0x007e0444, 0x00800e42, 0x00878142,\n    0x00898744, 0x00ac0483, 0x00b60317, 0x00b80283,\n    0x00d00214, 0x00d10096, 0x00dd0080, 0x00de8097,\n    0x00df8080, 0x00e10097, 0x00e1413e, 0x00e1c080,\n    0x00e204be, 0x00ea83ae, 0x00f282ae, 0x00f401ad,\n    0x00f4c12e, 0x00f54103, 0x00fc0303, 0x00fe4081,\n    0x0100023e, 0x0101c0be, 0x010301be, 0x010640be,\n    0x010e40be, 0x0114023e, 0x0115c0be, 0x011701be,\n    0x011d8144, 0x01304144, 0x01340244, 0x01358144,\n    0x01368344, 0x01388344, 0x013a8644, 0x013e0144,\n    0x0161c085, 0x018882ae, 0x019d422f, 0x01b00184,\n    0x01b4c084, 0x024a4084, 0x024c4084, 0x024d0084,\n    0x0256042e, 0x0272c12e, 0x02770120, 0x0277c084,\n    0x028cc084, 0x028d8084, 0x029641ae, 0x02978084,\n    0x02d20084, 0x02d2c12e, 0x02d70120, 0x02e50084,\n    0x02f281ae, 0x03120084, 0x03300084, 0x0331c122,\n    0x0332812e, 0x035281ae, 0x03768084, 0x037701ae,\n    0x038cc085, 0x03acc085, 0x03b7012f, 0x03c30081,\n    0x03d0c084, 0x03d34084, 0x03d48084, 0x03d5c084,\n    0x03d70084, 0x03da4084, 0x03dcc084, 0x03dd412e,\n    0x03ddc085, 0x03de0084, 0x03de4085, 0x03e04084,\n    0x03e4c084, 0x03e74084, 0x03e88084, 0x03e9c084,\n    0x03eb0084, 0x03ee4084, 0x04098084, 0x043f0081,\n    0x06c18484, 0x06c48084, 0x06cec184, 0x06d00120,\n    0x06d0c084, 0x074b0383, 0x074cc41f, 0x074f1783,\n    0x075e0081, 0x0766d283, 0x07801d44, 0x078e8942,\n    0x07931844, 0x079f0d42, 0x07a58216, 0x07a68085,\n    0x07a6c0be, 0x07a80d44, 0x07aea044, 0x07c00122,\n    0x07c08344, 0x07c20122, 0x07c28344, 0x07c40122,\n    0x07c48244, 0x07c60122, 0x07c68244, 0x07c8113e,\n    0x07d08244, 0x07d20122, 0x07d28244, 0x07d40122,\n    0x07d48344, 0x07d64c3e, 0x07dc4080, 0x07dc80be,\n    0x07dcc080, 0x07dd00be, 0x07dd4080, 0x07dd80be,\n    0x07ddc080, 0x07de00be, 0x07de4080, 0x07de80be,\n    0x07dec080, 0x07df00be, 0x07df4080, 0x07e00820,\n    0x07e40820, 0x07e80820, 0x07ec05be, 0x07eec080,\n    0x07ef00be, 0x07ef4097, 0x07ef8080, 0x07efc117,\n    0x07f0443e, 0x07f24080, 0x07f280be, 0x07f2c080,\n    0x07f303be, 0x07f4c080, 0x07f582ae, 0x07f6c080,\n    0x07f7433e, 0x07f8c080, 0x07f903ae, 0x07fac080,\n    0x07fb013e, 0x07fb8102, 0x07fc83be, 0x07fe4080,\n    0x07fe80be, 0x07fec080, 0x07ff00be, 0x07ff4080,\n    0x07ff8097, 0x0800011e, 0x08008495, 0x08044081,\n    0x0805c097, 0x08090081, 0x08094097, 0x08098099,\n    0x080bc081, 0x080cc085, 0x080d00b1, 0x080d8085,\n    0x080dc0b1, 0x080f0197, 0x0811c197, 0x0815c0b3,\n    0x0817c081, 0x081c0595, 0x081ec081, 0x081f0215,\n    0x0820051f, 0x08228583, 0x08254415, 0x082a0097,\n    0x08400119, 0x08408081, 0x0840c0bf, 0x08414119,\n    0x0841c081, 0x084240bf, 0x0842852d, 0x08454081,\n    0x08458097, 0x08464295, 0x08480097, 0x08484099,\n    0x08488097, 0x08490081, 0x08498080, 0x084a0081,\n    0x084a8102, 0x084b0495, 0x084d421f, 0x084e4081,\n    0x084ec099, 0x084f0283, 0x08514295, 0x08540119,\n    0x0854809b, 0x0854c619, 0x0857c097, 0x08580081,\n    0x08584097, 0x08588099, 0x0858c097, 0x08590081,\n    0x08594097, 0x08598099, 0x0859c09b, 0x085a0097,\n    0x085a4081, 0x085a8097, 0x085ac099, 0x085b0295,\n    0x085c4097, 0x085c8099, 0x085cc097, 0x085d0081,\n    0x085d4097, 0x085d8099, 0x085dc09b, 0x085e0097,\n    0x085e4081, 0x085e8097, 0x085ec099, 0x085f0215,\n    0x08624099, 0x0866813e, 0x086b80be, 0x087341be,\n    0x088100be, 0x088240be, 0x088300be, 0x088901be,\n    0x088b0085, 0x088b40b1, 0x088bc085, 0x088c00b1,\n    0x089040be, 0x089100be, 0x0891c1be, 0x089801be,\n    0x089b42be, 0x089d0144, 0x089e0144, 0x08a00144,\n    0x08a10144, 0x08a20144, 0x08ab023e, 0x08b80244,\n    0x08ba8220, 0x08ca411e, 0x0918049f, 0x091a4523,\n    0x091cc097, 0x091d04a5, 0x091f452b, 0x0921c09b,\n    0x092204a1, 0x09244525, 0x0926c099, 0x09270d25,\n    0x092d8d1f, 0x09340d1f, 0x093a8081, 0x0a8300b3,\n    0x0a9d0099, 0x0a9d4097, 0x0a9d8099, 0x0ab700be,\n    0x0b1f0115, 0x0b5bc081, 0x0ba7c081, 0x0bbcc081,\n    0x0bc004ad, 0x0bc244ad, 0x0bc484ad, 0x0bc6f383,\n    0x0be0852d, 0x0be31d03, 0x0bf1882d, 0x0c000081,\n    0x0c0d8283, 0x0c130b84, 0x0c194284, 0x0c1c0122,\n    0x0c1cc122, 0x0c1d8122, 0x0c1e4122, 0x0c1f0122,\n    0x0c250084, 0x0c26c123, 0x0c278084, 0x0c27c085,\n    0x0c2b0b84, 0x0c314284, 0x0c340122, 0x0c34c122,\n    0x0c358122, 0x0c364122, 0x0c370122, 0x0c3d0084,\n    0x0c3dc220, 0x0c3f8084, 0x0c3fc085, 0x0c4c4a2d,\n    0x0c51451f, 0x0c53ca9f, 0x0c5915ad, 0x0c648703,\n    0x0c800741, 0x0c838089, 0x0c83c129, 0x0c8441a9,\n    0x0c850089, 0x0c854129, 0x0c85c2a9, 0x0c870089,\n    0x0c87408f, 0x0c87808d, 0x0c881241, 0x0c910203,\n    0x0c940099, 0x0c9444a3, 0x0c968323, 0x0c98072d,\n    0x0c9b84af, 0x0c9dc2a1, 0x0c9f00b5, 0x0c9f40b3,\n    0x0c9f8085, 0x0ca01883, 0x0cac4223, 0x0cad4523,\n    0x0cafc097, 0x0cb004a1, 0x0cb241a5, 0x0cb30097,\n    0x0cb34099, 0x0cb38097, 0x0cb3c099, 0x0cb417ad,\n    0x0cbfc085, 0x0cc001b3, 0x0cc0c0b1, 0x0cc100b3,\n    0x0cc14131, 0x0cc1c0b5, 0x0cc200b3, 0x0cc241b1,\n    0x0cc30133, 0x0cc38131, 0x0cc40085, 0x0cc440b1,\n    0x0cc48133, 0x0cc50085, 0x0cc540b5, 0x0cc580b7,\n    0x0cc5c0b5, 0x0cc600b1, 0x0cc64135, 0x0cc6c0b3,\n    0x0cc701b1, 0x0cc7c0b3, 0x0cc800b5, 0x0cc840b3,\n    0x0cc881b1, 0x0cc9422f, 0x0cca4131, 0x0ccac0b5,\n    0x0ccb00b1, 0x0ccb40b3, 0x0ccb80b5, 0x0ccbc0b1,\n    0x0ccc012f, 0x0ccc80b5, 0x0cccc0b3, 0x0ccd00b5,\n    0x0ccd40b1, 0x0ccd80b5, 0x0ccdc085, 0x0cce02b1,\n    0x0ccf40b3, 0x0ccf80b1, 0x0ccfc085, 0x0cd001b1,\n    0x0cd0c0b3, 0x0cd101b1, 0x0cd1c0b5, 0x0cd200b3,\n    0x0cd24085, 0x0cd280b5, 0x0cd2c085, 0x0cd30133,\n    0x0cd381b1, 0x0cd440b3, 0x0cd48085, 0x0cd4c0b1,\n    0x0cd500b3, 0x0cd54085, 0x0cd580b5, 0x0cd5c0b1,\n    0x0cd60521, 0x0cd88525, 0x0cdb02a5, 0x0cdc4099,\n    0x0cdc8117, 0x0cdd0099, 0x0cdd4197, 0x0cde0127,\n    0x0cde8285, 0x0cdfc089, 0x0ce0043f, 0x0ce20099,\n    0x0ce2409b, 0x0ce283bf, 0x0ce44219, 0x0ce54205,\n    0x0ce6433f, 0x0ce7c131, 0x0ce84085, 0x0ce881b1,\n    0x0ce94085, 0x0ce98107, 0x0cea0089, 0x0cea4097,\n    0x0cea8219, 0x0ceb809d, 0x0cebc08d, 0x0cec083f,\n    0x0cf00105, 0x0cf0809b, 0x0cf0c197, 0x0cf1809b,\n    0x0cf1c099, 0x0cf20517, 0x0cf48099, 0x0cf4c117,\n    0x0cf54119, 0x0cf5c097, 0x0cf6009b, 0x0cf64099,\n    0x0cf68217, 0x0cf78119, 0x0cf804a1, 0x0cfa4525,\n    0x0cfcc525, 0x0cff4125, 0x0cffc099, 0x29a70103,\n    0x29dc0081, 0x29fe0103, 0x2ad70203, 0x2ada4081,\n    0x3e401482, 0x3e4a7f82, 0x3e6a3f82, 0x3e8aa102,\n    0x3e9b0110, 0x3e9c2f82, 0x3eb3c590, 0x3ec00197,\n    0x3ec0c119, 0x3ec1413f, 0x3ec4c2af, 0x3ec74184,\n    0x3ec804ad, 0x3eca4081, 0x3eca8304, 0x3ecc03a0,\n    0x3ece02a0, 0x3ecf8084, 0x3ed00120, 0x3ed0c120,\n    0x3ed184ae, 0x3ed3c085, 0x3ed4312d, 0x3ef4cbad,\n    0x3efa892f, 0x3eff022d, 0x3f002f2f, 0x3f1782a5,\n    0x3f18c0b1, 0x3f1907af, 0x3f1cffaf, 0x3f3c81a5,\n    0x3f3d64af, 0x3f542031, 0x3f649b31, 0x3f7c0131,\n    0x3f7c83b3, 0x3f7e40b1, 0x3f7e80bd, 0x3f7ec0bb,\n    0x3f7f00b3, 0x3f840503, 0x3f8c01ad, 0x3f8cc315,\n    0x3f8e462d, 0x3f91cc03, 0x3f97c695, 0x3f9c01af,\n    0x3f9d0085, 0x3f9d852f, 0x3fa03aad, 0x3fbd442f,\n    0x3fc06f1f, 0x3fd7c11f, 0x3fd85fad, 0x3fe80081,\n    0x3fe84f1f, 0x3ff0831f, 0x3ff2831f, 0x3ff4831f,\n    0x3ff6819f, 0x3ff80783, 0x44268192, 0x442ac092,\n    0x444b8112, 0x44d2c112, 0x452ec212, 0x456e8112,\n    0x464e0092, 0x74578392, 0x746ec312, 0x75000d1f,\n    0x75068d1f, 0x750d0d1f, 0x7513839f, 0x7515891f,\n    0x751a0d1f, 0x75208d1f, 0x75271015, 0x752f439f,\n    0x7531459f, 0x75340d1f, 0x753a8d1f, 0x75410395,\n    0x7543441f, 0x7545839f, 0x75478d1f, 0x754e0795,\n    0x7552839f, 0x75548d1f, 0x755b0d1f, 0x75618d1f,\n    0x75680d1f, 0x756e8d1f, 0x75750d1f, 0x757b8d1f,\n    0x75820d1f, 0x75888d1f, 0x758f0d1f, 0x75958d1f,\n    0x759c0d1f, 0x75a28d1f, 0x75a90103, 0x75aa089f,\n    0x75ae4081, 0x75ae839f, 0x75b04081, 0x75b08c9f,\n    0x75b6c081, 0x75b7032d, 0x75b8889f, 0x75bcc081,\n    0x75bd039f, 0x75bec081, 0x75bf0c9f, 0x75c54081,\n    0x75c5832d, 0x75c7089f, 0x75cb4081, 0x75cb839f,\n    0x75cd4081, 0x75cd8c9f, 0x75d3c081, 0x75d4032d,\n    0x75d5889f, 0x75d9c081, 0x75da039f, 0x75dbc081,\n    0x75dc0c9f, 0x75e24081, 0x75e2832d, 0x75e4089f,\n    0x75e84081, 0x75e8839f, 0x75ea4081, 0x75ea8c9f,\n    0x75f0c081, 0x75f1042d, 0x75f3851f, 0x75f6051f,\n    0x75f8851f, 0x75fb051f, 0x75fd851f, 0x7b80022d,\n    0x7b814dad, 0x7b884203, 0x7b89c081, 0x7b8a452d,\n    0x7b8d0403, 0x7b908081, 0x7b91dc03, 0x7ba0052d,\n    0x7ba2c8ad, 0x7ba84483, 0x7baac8ad, 0x7c400097,\n    0x7c404521, 0x7c440d25, 0x7c4a8087, 0x7c4ac115,\n    0x7c4b4117, 0x7c4c0d1f, 0x7c528217, 0x7c538099,\n    0x7c53c097, 0x7c5a8197, 0x7c640097, 0x7c80012f,\n    0x7c808081, 0x7c841603, 0x7c9004c1, 0x7c940103,\n    0x7efc051f, 0xbe0001ac, 0xbe00d110, 0xbe0947ac,\n    0xbe0d3910, 0xbe29872c, 0xbe2d022c, 0xbe2e3790,\n    0xbe49ff90, 0xbe69bc10,\n};\n\nstatic const uint16_t unicode_decomp_table2[690] = {\n    0x0020, 0x0000, 0x0061, 0x0002, 0x0004, 0x0006, 0x03bc, 0x0008,\n    0x000a, 0x000c, 0x0015, 0x0095, 0x00a5, 0x00b9, 0x00c1, 0x00c3,\n    0x00c7, 0x00cb, 0x00d1, 0x00d7, 0x00dd, 0x00e0, 0x00e6, 0x00f8,\n    0x0108, 0x010a, 0x0073, 0x0110, 0x0112, 0x0114, 0x0120, 0x012c,\n    0x0144, 0x014d, 0x0153, 0x0162, 0x0168, 0x016a, 0x0176, 0x0192,\n    0x0194, 0x01a9, 0x01bb, 0x01c7, 0x01d1, 0x01d5, 0x02b9, 0x01d7,\n    0x003b, 0x01d9, 0x01db, 0x00b7, 0x01e1, 0x01fc, 0x020c, 0x0218,\n    0x021d, 0x0223, 0x0227, 0x03a3, 0x0233, 0x023f, 0x0242, 0x024b,\n    0x024e, 0x0251, 0x025d, 0x0260, 0x0269, 0x026c, 0x026f, 0x0275,\n    0x0278, 0x0281, 0x028a, 0x029c, 0x029f, 0x02a3, 0x02af, 0x02b9,\n    0x02c5, 0x02c9, 0x02cd, 0x02d1, 0x02d5, 0x02e7, 0x02ed, 0x02f1,\n    0x02f5, 0x02f9, 0x02fd, 0x0305, 0x0309, 0x030d, 0x0313, 0x0317,\n    0x031b, 0x0323, 0x0327, 0x032b, 0x032f, 0x0335, 0x033d, 0x0341,\n    0x0349, 0x034d, 0x0351, 0x0f0b, 0x0357, 0x035b, 0x035f, 0x0363,\n    0x0367, 0x036b, 0x036f, 0x0373, 0x0379, 0x037d, 0x0381, 0x0385,\n    0x0389, 0x038d, 0x0391, 0x0395, 0x0399, 0x039d, 0x03a1, 0x10dc,\n    0x03a5, 0x03c9, 0x03cd, 0x03d9, 0x03dd, 0x03e1, 0x03ef, 0x03f1,\n    0x043d, 0x044f, 0x0499, 0x04f0, 0x0502, 0x054a, 0x0564, 0x056c,\n    0x0570, 0x0573, 0x059a, 0x05fa, 0x05fe, 0x0607, 0x060b, 0x0614,\n    0x0618, 0x061e, 0x0622, 0x0628, 0x068e, 0x0694, 0x0698, 0x069e,\n    0x06a2, 0x06ab, 0x03ac, 0x06f3, 0x03ad, 0x06f6, 0x03ae, 0x06f9,\n    0x03af, 0x06fc, 0x03cc, 0x06ff, 0x03cd, 0x0702, 0x03ce, 0x0705,\n    0x0709, 0x070d, 0x0711, 0x0386, 0x0732, 0x0735, 0x03b9, 0x0737,\n    0x073b, 0x0388, 0x0753, 0x0389, 0x0756, 0x0390, 0x076b, 0x038a,\n    0x0777, 0x03b0, 0x0789, 0x038e, 0x0799, 0x079f, 0x07a3, 0x038c,\n    0x07b8, 0x038f, 0x07bb, 0x00b4, 0x07be, 0x07c0, 0x07c2, 0x2010,\n    0x07cb, 0x002e, 0x07cd, 0x07cf, 0x0020, 0x07d2, 0x07d6, 0x07db,\n    0x07df, 0x07e4, 0x07ea, 0x07f0, 0x0020, 0x07f6, 0x2212, 0x0801,\n    0x0805, 0x0807, 0x081d, 0x0825, 0x0827, 0x0043, 0x082d, 0x0830,\n    0x0190, 0x0836, 0x0839, 0x004e, 0x0845, 0x0847, 0x084c, 0x084e,\n    0x0851, 0x005a, 0x03a9, 0x005a, 0x0853, 0x0857, 0x0860, 0x0069,\n    0x0862, 0x0865, 0x086f, 0x0874, 0x087a, 0x087e, 0x08a2, 0x0049,\n    0x08a4, 0x08a6, 0x08a9, 0x0056, 0x08ab, 0x08ad, 0x08b0, 0x08b4,\n    0x0058, 0x08b6, 0x08b8, 0x08bb, 0x08c0, 0x08c2, 0x08c5, 0x0076,\n    0x08c7, 0x08c9, 0x08cc, 0x08d0, 0x0078, 0x08d2, 0x08d4, 0x08d7,\n    0x08db, 0x08de, 0x08e4, 0x08e7, 0x08f0, 0x08f3, 0x08f6, 0x08f9,\n    0x0902, 0x0906, 0x090b, 0x090f, 0x0914, 0x0917, 0x091a, 0x0923,\n    0x092c, 0x093b, 0x093e, 0x0941, 0x0944, 0x0947, 0x094a, 0x0956,\n    0x095c, 0x0960, 0x0962, 0x0964, 0x0968, 0x096a, 0x0970, 0x0978,\n    0x097c, 0x0980, 0x0986, 0x0989, 0x098f, 0x0991, 0x0030, 0x0993,\n    0x0999, 0x099c, 0x099e, 0x09a1, 0x09a4, 0x2d61, 0x6bcd, 0x9f9f,\n    0x09a6, 0x09b1, 0x09bc, 0x09c7, 0x0a95, 0x0aa1, 0x0b15, 0x0020,\n    0x0b27, 0x0b31, 0x0b8d, 0x0ba1, 0x0ba5, 0x0ba9, 0x0bad, 0x0bb1,\n    0x0bb5, 0x0bb9, 0x0bbd, 0x0bc1, 0x0bc5, 0x0c21, 0x0c35, 0x0c39,\n    0x0c3d, 0x0c41, 0x0c45, 0x0c49, 0x0c4d, 0x0c51, 0x0c55, 0x0c59,\n    0x0c6f, 0x0c71, 0x0c73, 0x0ca0, 0x0cbc, 0x0cdc, 0x0ce4, 0x0cec,\n    0x0cf4, 0x0cfc, 0x0d04, 0x0d0c, 0x0d14, 0x0d22, 0x0d2e, 0x0d7a,\n    0x0d82, 0x0d85, 0x0d89, 0x0d8d, 0x0d9d, 0x0db1, 0x0db5, 0x0dbc,\n    0x0dc2, 0x0dc6, 0x0e28, 0x0e2c, 0x0e30, 0x0e32, 0x0e36, 0x0e3c,\n    0x0e3e, 0x0e41, 0x0e43, 0x0e46, 0x0e77, 0x0e7b, 0x0e89, 0x0e8e,\n    0x0e94, 0x0e9c, 0x0ea3, 0x0ea9, 0x0eb4, 0x0ebe, 0x0ec6, 0x0eca,\n    0x0ecf, 0x0ed9, 0x0edd, 0x0ee4, 0x0eec, 0x0ef3, 0x0ef8, 0x0f04,\n    0x0f0a, 0x0f15, 0x0f1b, 0x0f22, 0x0f28, 0x0f33, 0x0f3d, 0x0f45,\n    0x0f4c, 0x0f51, 0x0f57, 0x0f5e, 0x0f63, 0x0f69, 0x0f70, 0x0f76,\n    0x0f7d, 0x0f82, 0x0f89, 0x0f8d, 0x0f9e, 0x0fa4, 0x0fa9, 0x0fad,\n    0x0fb8, 0x0fbe, 0x0fc9, 0x0fd0, 0x0fd6, 0x0fda, 0x0fe1, 0x0fe5,\n    0x0fef, 0x0ffa, 0x1000, 0x1004, 0x1009, 0x100f, 0x1013, 0x101a,\n    0x101f, 0x1023, 0x1029, 0x102f, 0x1032, 0x1036, 0x1039, 0x103f,\n    0x1045, 0x1059, 0x1061, 0x1079, 0x107c, 0x1080, 0x1095, 0x10a1,\n    0x10b1, 0x10c3, 0x10cb, 0x10cf, 0x10da, 0x10de, 0x10ea, 0x10f2,\n    0x10f4, 0x1100, 0x1105, 0x1111, 0x1141, 0x1149, 0x114d, 0x1153,\n    0x1157, 0x115a, 0x116e, 0x1171, 0x1175, 0x117b, 0x117d, 0x1181,\n    0x1184, 0x118c, 0x1192, 0x1196, 0x119c, 0x11a2, 0x11a8, 0x11ab,\n    0xa76f, 0x11af, 0x11b3, 0x028d, 0x11bb, 0x120d, 0x130b, 0x1409,\n    0x148d, 0x1492, 0x1550, 0x1569, 0x156f, 0x1575, 0x157b, 0x1587,\n    0x1593, 0x002b, 0x159e, 0x15b6, 0x15ba, 0x15be, 0x15c2, 0x15c6,\n    0x15ca, 0x15de, 0x15e2, 0x1646, 0x165f, 0x1685, 0x168b, 0x1749,\n    0x174f, 0x1754, 0x1774, 0x1874, 0x187a, 0x190e, 0x19d0, 0x1a74,\n    0x1a7c, 0x1a9a, 0x1a9f, 0x1ab3, 0x1abd, 0x1ac3, 0x1ad7, 0x1adc,\n    0x1ae2, 0x1af0, 0x1b20, 0x1b2d, 0x1b35, 0x1b39, 0x1b4f, 0x1bc6,\n    0x1bd8, 0x1bda, 0x1bdc, 0x3164, 0x1c1d, 0x1c1f, 0x1c21, 0x1c23,\n    0x1c25, 0x1c27, 0x1c45, 0x1c53, 0x1c58, 0x1c61, 0x1c6a, 0x1c7c,\n    0x1c85, 0x1c8a, 0x1caa, 0x1cc5, 0x1cc7, 0x1cc9, 0x1ccb, 0x1ccd,\n    0x1ccf, 0x1cd1, 0x1cd3, 0x1cf3, 0x1cf5, 0x1cf7, 0x1cf9, 0x1cfb,\n    0x1d02, 0x1d04, 0x1d06, 0x1d08, 0x1d17, 0x1d19, 0x1d1b, 0x1d1d,\n    0x1d1f, 0x1d21, 0x1d23, 0x1d25, 0x1d27, 0x1d29, 0x1d2b, 0x1d2d,\n    0x1d2f, 0x1d31, 0x1d33, 0x1d37, 0x03f4, 0x1d39, 0x2207, 0x1d3b,\n    0x2202, 0x1d3d, 0x1d45, 0x03f4, 0x1d47, 0x2207, 0x1d49, 0x2202,\n    0x1d4b, 0x1d53, 0x03f4, 0x1d55, 0x2207, 0x1d57, 0x2202, 0x1d59,\n    0x1d61, 0x03f4, 0x1d63, 0x2207, 0x1d65, 0x2202, 0x1d67, 0x1d6f,\n    0x03f4, 0x1d71, 0x2207, 0x1d73, 0x2202, 0x1d75, 0x1d7f, 0x1d81,\n    0x1d83, 0x1d85, 0x1d87, 0x1d89, 0x1d8f, 0x1dac, 0x062d, 0x1db4,\n    0x1dc0, 0x062c, 0x1dd0, 0x1e40, 0x1e4c, 0x1e5f, 0x1e71, 0x1e84,\n    0x1e86, 0x1e8a, 0x1e90, 0x1e96, 0x1e98, 0x1e9c, 0x1e9e, 0x1ea6,\n    0x1ea9, 0x1eab, 0x1eb1, 0x1eb3, 0x30b5, 0x1eb9, 0x1f11, 0x1f27,\n    0x1f2b, 0x1f2d, 0x1f32, 0x1f7f, 0x1f90, 0x2091, 0x20a1, 0x20a7,\n    0x21a1, 0x22bf,\n};\n\nstatic const uint8_t unicode_decomp_data[9165] = {\n    0x20, 0x88, 0x20, 0x84, 0x32, 0x33, 0x20, 0x81,\n    0x20, 0xa7, 0x31, 0x6f, 0x31, 0xd0, 0x34, 0x31,\n    0xd0, 0x32, 0x33, 0xd0, 0x34, 0x41, 0x80, 0x41,\n    0x81, 0x41, 0x82, 0x41, 0x83, 0x41, 0x88, 0x41,\n    0x8a, 0x00, 0x00, 0x43, 0xa7, 0x45, 0x80, 0x45,\n    0x81, 0x45, 0x82, 0x45, 0x88, 0x49, 0x80, 0x49,\n    0x81, 0x49, 0x82, 0x49, 0x88, 0x00, 0x00, 0x4e,\n    0x83, 0x4f, 0x80, 0x4f, 0x81, 0x4f, 0x82, 0x4f,\n    0x83, 0x4f, 0x88, 0x00, 0x00, 0x00, 0x00, 0x55,\n    0x80, 0x55, 0x81, 0x55, 0x82, 0x55, 0x88, 0x59,\n    0x81, 0x00, 0x00, 0x00, 0x00, 0x61, 0x80, 0x61,\n    0x81, 0x61, 0x82, 0x61, 0x83, 0x61, 0x88, 0x61,\n    0x8a, 0x00, 0x00, 0x63, 0xa7, 0x65, 0x80, 0x65,\n    0x81, 0x65, 0x82, 0x65, 0x88, 0x69, 0x80, 0x69,\n    0x81, 0x69, 0x82, 0x69, 0x88, 0x00, 0x00, 0x6e,\n    0x83, 0x6f, 0x80, 0x6f, 0x81, 0x6f, 0x82, 0x6f,\n    0x83, 0x6f, 0x88, 0x00, 0x00, 0x00, 0x00, 0x75,\n    0x80, 0x75, 0x81, 0x75, 0x82, 0x75, 0x88, 0x79,\n    0x81, 0x00, 0x00, 0x79, 0x88, 0x41, 0x84, 0x41,\n    0x86, 0x41, 0xa8, 0x43, 0x81, 0x43, 0x82, 0x43,\n    0x87, 0x43, 0x8c, 0x44, 0x8c, 0x45, 0x84, 0x45,\n    0x86, 0x45, 0x87, 0x45, 0xa8, 0x45, 0x8c, 0x47,\n    0x82, 0x47, 0x86, 0x47, 0x87, 0x47, 0xa7, 0x48,\n    0x82, 0x49, 0x83, 0x49, 0x84, 0x49, 0x86, 0x49,\n    0xa8, 0x49, 0x87, 0x49, 0x4a, 0x69, 0x6a, 0x4a,\n    0x82, 0x4b, 0xa7, 0x4c, 0x81, 0x4c, 0xa7, 0x4c,\n    0x8c, 0x4c, 0x00, 0x00, 0x6b, 0x20, 0x6b, 0x4e,\n    0x81, 0x4e, 0xa7, 0x4e, 0x8c, 0xbc, 0x02, 0x6e,\n    0x4f, 0x84, 0x4f, 0x86, 0x4f, 0x8b, 0x52, 0x81,\n    0x52, 0xa7, 0x52, 0x8c, 0x53, 0x81, 0x53, 0x82,\n    0x53, 0xa7, 0x53, 0x8c, 0x54, 0xa7, 0x54, 0x8c,\n    0x55, 0x83, 0x55, 0x84, 0x55, 0x86, 0x55, 0x8a,\n    0x55, 0x8b, 0x55, 0xa8, 0x57, 0x82, 0x59, 0x82,\n    0x59, 0x88, 0x5a, 0x81, 0x5a, 0x87, 0x5a, 0x8c,\n    0x4f, 0x9b, 0x55, 0x9b, 0x44, 0x00, 0x7d, 0x01,\n    0x44, 0x00, 0x7e, 0x01, 0x64, 0x00, 0x7e, 0x01,\n    0x4c, 0x4a, 0x4c, 0x6a, 0x6c, 0x6a, 0x4e, 0x4a,\n    0x4e, 0x6a, 0x6e, 0x6a, 0x41, 0x00, 0x8c, 0x49,\n    0x00, 0x8c, 0x4f, 0x00, 0x8c, 0x55, 0x00, 0x8c,\n    0xdc, 0x00, 0x84, 0xdc, 0x00, 0x81, 0xdc, 0x00,\n    0x8c, 0xdc, 0x00, 0x80, 0xc4, 0x00, 0x84, 0x26,\n    0x02, 0x84, 0xc6, 0x00, 0x84, 0x47, 0x8c, 0x4b,\n    0x8c, 0x4f, 0xa8, 0xea, 0x01, 0x84, 0xeb, 0x01,\n    0x84, 0xb7, 0x01, 0x8c, 0x92, 0x02, 0x8c, 0x6a,\n    0x00, 0x8c, 0x44, 0x5a, 0x44, 0x7a, 0x64, 0x7a,\n    0x47, 0x81, 0x4e, 0x00, 0x80, 0xc5, 0x00, 0x81,\n    0xc6, 0x00, 0x81, 0xd8, 0x00, 0x81, 0x41, 0x8f,\n    0x41, 0x91, 0x45, 0x8f, 0x45, 0x91, 0x49, 0x8f,\n    0x49, 0x91, 0x4f, 0x8f, 0x4f, 0x91, 0x52, 0x8f,\n    0x52, 0x91, 0x55, 0x8f, 0x55, 0x91, 0x53, 0xa6,\n    0x54, 0xa6, 0x48, 0x8c, 0x41, 0x00, 0x87, 0x45,\n    0x00, 0xa7, 0xd6, 0x00, 0x84, 0xd5, 0x00, 0x84,\n    0x4f, 0x00, 0x87, 0x2e, 0x02, 0x84, 0x59, 0x00,\n    0x84, 0x68, 0x00, 0x66, 0x02, 0x6a, 0x00, 0x72,\n    0x00, 0x79, 0x02, 0x7b, 0x02, 0x81, 0x02, 0x77,\n    0x00, 0x79, 0x00, 0x20, 0x86, 0x20, 0x87, 0x20,\n    0x8a, 0x20, 0xa8, 0x20, 0x83, 0x20, 0x8b, 0x63,\n    0x02, 0x6c, 0x00, 0x73, 0x00, 0x78, 0x00, 0x95,\n    0x02, 0x80, 0x81, 0x00, 0x93, 0x88, 0x81, 0x20,\n    0xc5, 0x20, 0x81, 0xa8, 0x00, 0x81, 0x91, 0x03,\n    0x81, 0x95, 0x03, 0x81, 0x97, 0x03, 0x81, 0x99,\n    0x03, 0x81, 0x00, 0x00, 0x00, 0x9f, 0x03, 0x81,\n    0x00, 0x00, 0x00, 0xa5, 0x03, 0x81, 0xa9, 0x03,\n    0x81, 0xca, 0x03, 0x81, 0x01, 0x03, 0x98, 0x07,\n    0xa4, 0x07, 0xb0, 0x00, 0xb4, 0x00, 0xb6, 0x00,\n    0xb8, 0x00, 0xca, 0x00, 0x01, 0x03, 0xb8, 0x07,\n    0xc4, 0x07, 0xbe, 0x00, 0xc4, 0x00, 0xc8, 0x00,\n    0xa5, 0x03, 0x0d, 0x13, 0x00, 0x01, 0x03, 0xd1,\n    0x00, 0xd1, 0x07, 0xc6, 0x03, 0xc0, 0x03, 0xba,\n    0x03, 0xc1, 0x03, 0xc2, 0x03, 0x00, 0x00, 0x98,\n    0x03, 0xb5, 0x03, 0x15, 0x04, 0x80, 0x15, 0x04,\n    0x88, 0x00, 0x00, 0x00, 0x13, 0x04, 0x81, 0x06,\n    0x04, 0x88, 0x1a, 0x04, 0x81, 0x18, 0x04, 0x80,\n    0x23, 0x04, 0x86, 0x18, 0x04, 0x86, 0x38, 0x04,\n    0x86, 0x35, 0x04, 0x80, 0x35, 0x04, 0x88, 0x00,\n    0x00, 0x00, 0x33, 0x04, 0x81, 0x56, 0x04, 0x88,\n    0x3a, 0x04, 0x81, 0x38, 0x04, 0x80, 0x43, 0x04,\n    0x86, 0x74, 0x04, 0x8f, 0x16, 0x04, 0x86, 0x10,\n    0x04, 0x86, 0x10, 0x04, 0x88, 0x15, 0x04, 0x86,\n    0xd8, 0x04, 0x88, 0x16, 0x04, 0x88, 0x17, 0x04,\n    0x88, 0x18, 0x04, 0x84, 0x18, 0x04, 0x88, 0x1e,\n    0x04, 0x88, 0xe8, 0x04, 0x88, 0x2d, 0x04, 0x88,\n    0x23, 0x04, 0x84, 0x23, 0x04, 0x88, 0x23, 0x04,\n    0x8b, 0x27, 0x04, 0x88, 0x2b, 0x04, 0x88, 0x65,\n    0x05, 0x82, 0x05, 0x27, 0x06, 0x00, 0x2c, 0x00,\n    0x2d, 0x21, 0x2d, 0x00, 0x2e, 0x23, 0x2d, 0x27,\n    0x06, 0x00, 0x4d, 0x21, 0x4d, 0xa0, 0x4d, 0x23,\n    0x4d, 0xd5, 0x06, 0x54, 0x06, 0x00, 0x00, 0x00,\n    0x00, 0xc1, 0x06, 0x54, 0x06, 0xd2, 0x06, 0x54,\n    0x06, 0x28, 0x09, 0x3c, 0x09, 0x30, 0x09, 0x3c,\n    0x09, 0x33, 0x09, 0x3c, 0x09, 0x15, 0x09, 0x00,\n    0x27, 0x01, 0x27, 0x02, 0x27, 0x07, 0x27, 0x0c,\n    0x27, 0x0d, 0x27, 0x16, 0x27, 0x1a, 0x27, 0xbe,\n    0x09, 0x09, 0x00, 0x09, 0x19, 0xa1, 0x09, 0xbc,\n    0x09, 0xaf, 0x09, 0xbc, 0x09, 0x32, 0x0a, 0x3c,\n    0x0a, 0x38, 0x0a, 0x3c, 0x0a, 0x16, 0x0a, 0x00,\n    0x26, 0x01, 0x26, 0x06, 0x26, 0x2b, 0x0a, 0x3c,\n    0x0a, 0x47, 0x0b, 0x56, 0x0b, 0x3e, 0x0b, 0x09,\n    0x00, 0x09, 0x19, 0x21, 0x0b, 0x3c, 0x0b, 0x92,\n    0x0b, 0xd7, 0x0b, 0xbe, 0x0b, 0x08, 0x00, 0x09,\n    0x00, 0x08, 0x19, 0x46, 0x0c, 0x56, 0x0c, 0xbf,\n    0x0c, 0xd5, 0x0c, 0xc6, 0x0c, 0xd5, 0x0c, 0xc2,\n    0x0c, 0x04, 0x00, 0x08, 0x13, 0x3e, 0x0d, 0x08,\n    0x00, 0x09, 0x00, 0x08, 0x19, 0xd9, 0x0d, 0xca,\n    0x0d, 0xca, 0x0d, 0x0f, 0x05, 0x12, 0x00, 0x0f,\n    0x15, 0x4d, 0x0e, 0x32, 0x0e, 0xcd, 0x0e, 0xb2,\n    0x0e, 0x99, 0x0e, 0x12, 0x00, 0x12, 0x08, 0x42,\n    0x0f, 0xb7, 0x0f, 0x4c, 0x0f, 0xb7, 0x0f, 0x51,\n    0x0f, 0xb7, 0x0f, 0x56, 0x0f, 0xb7, 0x0f, 0x5b,\n    0x0f, 0xb7, 0x0f, 0x40, 0x0f, 0xb5, 0x0f, 0x71,\n    0x0f, 0x72, 0x0f, 0x71, 0x0f, 0x00, 0x03, 0x41,\n    0x0f, 0xb2, 0x0f, 0x81, 0x0f, 0xb3, 0x0f, 0x80,\n    0x0f, 0xb3, 0x0f, 0x81, 0x0f, 0x71, 0x0f, 0x80,\n    0x0f, 0x92, 0x0f, 0xb7, 0x0f, 0x9c, 0x0f, 0xb7,\n    0x0f, 0xa1, 0x0f, 0xb7, 0x0f, 0xa6, 0x0f, 0xb7,\n    0x0f, 0xab, 0x0f, 0xb7, 0x0f, 0x90, 0x0f, 0xb5,\n    0x0f, 0x25, 0x10, 0x2e, 0x10, 0x05, 0x1b, 0x35,\n    0x1b, 0x00, 0x00, 0x00, 0x00, 0x07, 0x1b, 0x35,\n    0x1b, 0x00, 0x00, 0x00, 0x00, 0x09, 0x1b, 0x35,\n    0x1b, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x1b, 0x35,\n    0x1b, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x1b, 0x35,\n    0x1b, 0x11, 0x1b, 0x35, 0x1b, 0x3a, 0x1b, 0x35,\n    0x1b, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x1b, 0x35,\n    0x1b, 0x3e, 0x1b, 0x35, 0x1b, 0x42, 0x1b, 0x35,\n    0x1b, 0x41, 0x00, 0xc6, 0x00, 0x42, 0x00, 0x00,\n    0x00, 0x44, 0x00, 0x45, 0x00, 0x8e, 0x01, 0x47,\n    0x00, 0x4f, 0x00, 0x22, 0x02, 0x50, 0x00, 0x52,\n    0x00, 0x54, 0x00, 0x55, 0x00, 0x57, 0x00, 0x61,\n    0x00, 0x50, 0x02, 0x51, 0x02, 0x02, 0x1d, 0x62,\n    0x00, 0x64, 0x00, 0x65, 0x00, 0x59, 0x02, 0x5b,\n    0x02, 0x5c, 0x02, 0x67, 0x00, 0x00, 0x00, 0x6b,\n    0x00, 0x6d, 0x00, 0x4b, 0x01, 0x6f, 0x00, 0x54,\n    0x02, 0x16, 0x1d, 0x17, 0x1d, 0x70, 0x00, 0x74,\n    0x00, 0x75, 0x00, 0x1d, 0x1d, 0x6f, 0x02, 0x76,\n    0x00, 0x25, 0x1d, 0xb2, 0x03, 0xb3, 0x03, 0xb4,\n    0x03, 0xc6, 0x03, 0xc7, 0x03, 0x69, 0x00, 0x72,\n    0x00, 0x75, 0x00, 0x76, 0x00, 0xb2, 0x03, 0xb3,\n    0x03, 0xc1, 0x03, 0xc6, 0x03, 0xc7, 0x03, 0x52,\n    0x02, 0x63, 0x00, 0x55, 0x02, 0xf0, 0x00, 0x5c,\n    0x02, 0x66, 0x00, 0x5f, 0x02, 0x61, 0x02, 0x65,\n    0x02, 0x68, 0x02, 0x69, 0x02, 0x6a, 0x02, 0x7b,\n    0x1d, 0x9d, 0x02, 0x6d, 0x02, 0x85, 0x1d, 0x9f,\n    0x02, 0x71, 0x02, 0x70, 0x02, 0x72, 0x02, 0x73,\n    0x02, 0x74, 0x02, 0x75, 0x02, 0x78, 0x02, 0x82,\n    0x02, 0x83, 0x02, 0xab, 0x01, 0x89, 0x02, 0x8a,\n    0x02, 0x1c, 0x1d, 0x8b, 0x02, 0x8c, 0x02, 0x7a,\n    0x00, 0x90, 0x02, 0x91, 0x02, 0x92, 0x02, 0xb8,\n    0x03, 0x41, 0x00, 0xa5, 0x42, 0x00, 0x87, 0x42,\n    0x00, 0xa3, 0x42, 0x00, 0xb1, 0xc7, 0x00, 0x81,\n    0x44, 0x00, 0x87, 0x44, 0x00, 0xa3, 0x44, 0x00,\n    0xb1, 0x44, 0x00, 0xa7, 0x44, 0x00, 0xad, 0x12,\n    0x01, 0x80, 0x12, 0x01, 0x81, 0x45, 0x00, 0xad,\n    0x45, 0x00, 0xb0, 0x28, 0x02, 0x86, 0x46, 0x00,\n    0x87, 0x47, 0x00, 0x84, 0x48, 0x00, 0x87, 0x48,\n    0x00, 0xa3, 0x48, 0x00, 0x88, 0x48, 0x00, 0xa7,\n    0x48, 0x00, 0xae, 0x49, 0x00, 0xb0, 0xcf, 0x00,\n    0x81, 0x4b, 0x00, 0x81, 0x4b, 0x00, 0xa3, 0x4b,\n    0x00, 0xb1, 0x4c, 0x00, 0xa3, 0x36, 0x1e, 0x84,\n    0x4c, 0xb1, 0x4c, 0xad, 0x4d, 0x81, 0x4d, 0x87,\n    0x4d, 0xa3, 0x4e, 0x87, 0x4e, 0xa3, 0x4e, 0xb1,\n    0x4e, 0xad, 0xd5, 0x00, 0x81, 0xd5, 0x00, 0x88,\n    0x4c, 0x01, 0x80, 0x4c, 0x01, 0x81, 0x50, 0x00,\n    0x81, 0x50, 0x00, 0x87, 0x52, 0x00, 0x87, 0x52,\n    0x00, 0xa3, 0x5a, 0x1e, 0x84, 0x52, 0x00, 0xb1,\n    0x53, 0x00, 0x87, 0x53, 0x00, 0xa3, 0x5a, 0x01,\n    0x87, 0x60, 0x01, 0x87, 0x62, 0x1e, 0x87, 0x54,\n    0x00, 0x87, 0x54, 0x00, 0xa3, 0x54, 0x00, 0xb1,\n    0x54, 0x00, 0xad, 0x55, 0x00, 0xa4, 0x55, 0x00,\n    0xb0, 0x55, 0x00, 0xad, 0x68, 0x01, 0x81, 0x6a,\n    0x01, 0x88, 0x56, 0x83, 0x56, 0xa3, 0x57, 0x80,\n    0x57, 0x81, 0x57, 0x88, 0x57, 0x87, 0x57, 0xa3,\n    0x58, 0x87, 0x58, 0x88, 0x59, 0x87, 0x5a, 0x82,\n    0x5a, 0xa3, 0x5a, 0xb1, 0x68, 0xb1, 0x74, 0x88,\n    0x77, 0x8a, 0x79, 0x8a, 0x61, 0x00, 0xbe, 0x02,\n    0x7f, 0x01, 0x87, 0x41, 0x00, 0xa3, 0x41, 0x00,\n    0x89, 0xc2, 0x00, 0x81, 0xc2, 0x00, 0x80, 0xc2,\n    0x00, 0x89, 0xc2, 0x00, 0x83, 0xa0, 0x1e, 0x82,\n    0x02, 0x01, 0x81, 0x02, 0x01, 0x80, 0x02, 0x01,\n    0x89, 0x02, 0x01, 0x83, 0xa0, 0x1e, 0x86, 0x45,\n    0x00, 0xa3, 0x45, 0x00, 0x89, 0x45, 0x00, 0x83,\n    0xca, 0x00, 0x81, 0xca, 0x00, 0x80, 0xca, 0x00,\n    0x89, 0xca, 0x00, 0x83, 0xb8, 0x1e, 0x82, 0x49,\n    0x00, 0x89, 0x49, 0x00, 0xa3, 0x4f, 0x00, 0xa3,\n    0x4f, 0x00, 0x89, 0xd4, 0x00, 0x81, 0xd4, 0x00,\n    0x80, 0xd4, 0x00, 0x89, 0xd4, 0x00, 0x83, 0xcc,\n    0x1e, 0x82, 0xa0, 0x01, 0x81, 0xa0, 0x01, 0x80,\n    0xa0, 0x01, 0x89, 0xa0, 0x01, 0x83, 0xa0, 0x01,\n    0xa3, 0x55, 0x00, 0xa3, 0x55, 0x00, 0x89, 0xaf,\n    0x01, 0x81, 0xaf, 0x01, 0x80, 0xaf, 0x01, 0x89,\n    0xaf, 0x01, 0x83, 0xaf, 0x01, 0xa3, 0x59, 0x00,\n    0x80, 0x59, 0x00, 0xa3, 0x59, 0x00, 0x89, 0x59,\n    0x00, 0x83, 0xb1, 0x03, 0x13, 0x03, 0x00, 0x1f,\n    0x80, 0x00, 0x1f, 0x81, 0x00, 0x1f, 0xc2, 0x91,\n    0x03, 0x13, 0x03, 0x08, 0x1f, 0x80, 0x08, 0x1f,\n    0x81, 0x08, 0x1f, 0xc2, 0xb5, 0x03, 0x13, 0x03,\n    0x10, 0x1f, 0x80, 0x10, 0x1f, 0x81, 0x95, 0x03,\n    0x13, 0x03, 0x18, 0x1f, 0x80, 0x18, 0x1f, 0x81,\n    0xb7, 0x03, 0x93, 0xb7, 0x03, 0x94, 0x20, 0x1f,\n    0x80, 0x21, 0x1f, 0x80, 0x20, 0x1f, 0x81, 0x21,\n    0x1f, 0x81, 0x20, 0x1f, 0xc2, 0x21, 0x1f, 0xc2,\n    0x97, 0x03, 0x93, 0x97, 0x03, 0x94, 0x28, 0x1f,\n    0x80, 0x29, 0x1f, 0x80, 0x28, 0x1f, 0x81, 0x29,\n    0x1f, 0x81, 0x28, 0x1f, 0xc2, 0x29, 0x1f, 0xc2,\n    0xb9, 0x03, 0x93, 0xb9, 0x03, 0x94, 0x30, 0x1f,\n    0x80, 0x31, 0x1f, 0x80, 0x30, 0x1f, 0x81, 0x31,\n    0x1f, 0x81, 0x30, 0x1f, 0xc2, 0x31, 0x1f, 0xc2,\n    0x99, 0x03, 0x93, 0x99, 0x03, 0x94, 0x38, 0x1f,\n    0x80, 0x39, 0x1f, 0x80, 0x38, 0x1f, 0x81, 0x39,\n    0x1f, 0x81, 0x38, 0x1f, 0xc2, 0x39, 0x1f, 0xc2,\n    0xbf, 0x03, 0x93, 0xbf, 0x03, 0x94, 0x40, 0x1f,\n    0x80, 0x40, 0x1f, 0x81, 0x9f, 0x03, 0x13, 0x03,\n    0x48, 0x1f, 0x80, 0x48, 0x1f, 0x81, 0xc5, 0x03,\n    0x13, 0x03, 0x50, 0x1f, 0x80, 0x50, 0x1f, 0x81,\n    0x50, 0x1f, 0xc2, 0xa5, 0x03, 0x94, 0x00, 0x00,\n    0x00, 0x59, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x59,\n    0x1f, 0x81, 0x00, 0x00, 0x00, 0x59, 0x1f, 0xc2,\n    0xc9, 0x03, 0x93, 0xc9, 0x03, 0x94, 0x60, 0x1f,\n    0x80, 0x61, 0x1f, 0x80, 0x60, 0x1f, 0x81, 0x61,\n    0x1f, 0x81, 0x60, 0x1f, 0xc2, 0x61, 0x1f, 0xc2,\n    0xa9, 0x03, 0x93, 0xa9, 0x03, 0x94, 0x68, 0x1f,\n    0x80, 0x69, 0x1f, 0x80, 0x68, 0x1f, 0x81, 0x69,\n    0x1f, 0x81, 0x68, 0x1f, 0xc2, 0x69, 0x1f, 0xc2,\n    0xb1, 0x03, 0x80, 0xb5, 0x03, 0x80, 0xb7, 0x03,\n    0x80, 0xb9, 0x03, 0x80, 0xbf, 0x03, 0x80, 0xc5,\n    0x03, 0x80, 0xc9, 0x03, 0x80, 0x00, 0x1f, 0x45,\n    0x03, 0x20, 0x1f, 0x45, 0x03, 0x60, 0x1f, 0x45,\n    0x03, 0xb1, 0x03, 0x86, 0xb1, 0x03, 0x84, 0x70,\n    0x1f, 0xc5, 0xb1, 0x03, 0xc5, 0xac, 0x03, 0xc5,\n    0x00, 0x00, 0x00, 0xb1, 0x03, 0xc2, 0xb6, 0x1f,\n    0xc5, 0x91, 0x03, 0x86, 0x91, 0x03, 0x84, 0x91,\n    0x03, 0x80, 0x91, 0x03, 0xc5, 0x20, 0x93, 0x20,\n    0x93, 0x20, 0xc2, 0xa8, 0x00, 0xc2, 0x74, 0x1f,\n    0xc5, 0xb7, 0x03, 0xc5, 0xae, 0x03, 0xc5, 0x00,\n    0x00, 0x00, 0xb7, 0x03, 0xc2, 0xc6, 0x1f, 0xc5,\n    0x95, 0x03, 0x80, 0x97, 0x03, 0x80, 0x97, 0x03,\n    0xc5, 0xbf, 0x1f, 0x80, 0xbf, 0x1f, 0x81, 0xbf,\n    0x1f, 0xc2, 0xb9, 0x03, 0x86, 0xb9, 0x03, 0x84,\n    0xca, 0x03, 0x80, 0x00, 0x03, 0xb9, 0x42, 0xca,\n    0x42, 0x99, 0x06, 0x99, 0x04, 0x99, 0x00, 0xfe,\n    0x1f, 0x80, 0xfe, 0x1f, 0x81, 0xfe, 0x1f, 0xc2,\n    0xc5, 0x03, 0x86, 0xc5, 0x03, 0x84, 0xcb, 0x03,\n    0x80, 0x00, 0x03, 0xc1, 0x13, 0xc1, 0x14, 0xc5,\n    0x42, 0xcb, 0x42, 0xa5, 0x06, 0xa5, 0x04, 0xa5,\n    0x00, 0xa1, 0x03, 0x94, 0xa8, 0x00, 0x80, 0x85,\n    0x03, 0x60, 0x00, 0x7c, 0x1f, 0xc5, 0xc9, 0x03,\n    0xc5, 0xce, 0x03, 0xc5, 0x00, 0x00, 0x00, 0xc9,\n    0x03, 0xc2, 0xf6, 0x1f, 0xc5, 0x9f, 0x03, 0x80,\n    0xa9, 0x03, 0x80, 0xa9, 0x03, 0xc5, 0x20, 0x94,\n    0x02, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,\n    0x20, 0x20, 0x20, 0x20, 0xb3, 0x2e, 0x2e, 0x2e,\n    0x2e, 0x2e, 0x32, 0x20, 0x32, 0x20, 0x32, 0x20,\n    0x00, 0x00, 0x00, 0x35, 0x20, 0x35, 0x20, 0x35,\n    0x20, 0x00, 0x00, 0x00, 0x21, 0x21, 0x00, 0x00,\n    0x20, 0x85, 0x3f, 0x3f, 0x3f, 0x21, 0x21, 0x3f,\n    0x32, 0x20, 0x00, 0x00, 0x00, 0x00, 0x30, 0x69,\n    0x00, 0x00, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,\n    0x2b, 0x3d, 0x28, 0x29, 0x6e, 0x30, 0x00, 0x2b,\n    0x00, 0x12, 0x22, 0x3d, 0x00, 0x28, 0x00, 0x29,\n    0x00, 0x00, 0x00, 0x61, 0x00, 0x65, 0x00, 0x6f,\n    0x00, 0x78, 0x00, 0x59, 0x02, 0x68, 0x6b, 0x6c,\n    0x6d, 0x6e, 0x70, 0x73, 0x74, 0x52, 0x73, 0x61,\n    0x2f, 0x63, 0x61, 0x2f, 0x73, 0xb0, 0x00, 0x43,\n    0x63, 0x2f, 0x6f, 0x63, 0x2f, 0x75, 0xb0, 0x00,\n    0x46, 0x48, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x20,\n    0xdf, 0x01, 0x01, 0x04, 0x24, 0x4e, 0x6f, 0x50,\n    0x51, 0x52, 0x52, 0x52, 0x53, 0x4d, 0x54, 0x45,\n    0x4c, 0x54, 0x4d, 0x4b, 0x00, 0xc5, 0x00, 0x42,\n    0x43, 0x00, 0x65, 0x45, 0x46, 0x00, 0x4d, 0x6f,\n    0xd0, 0x05, 0x46, 0x41, 0x58, 0xc0, 0x03, 0xb3,\n    0x03, 0x93, 0x03, 0xa0, 0x03, 0x11, 0x22, 0x44,\n    0x64, 0x65, 0x69, 0x6a, 0x31, 0xd0, 0x37, 0x31,\n    0xd0, 0x39, 0x31, 0xd0, 0x31, 0x30, 0x31, 0xd0,\n    0x33, 0x32, 0xd0, 0x33, 0x31, 0xd0, 0x35, 0x32,\n    0xd0, 0x35, 0x33, 0xd0, 0x35, 0x34, 0xd0, 0x35,\n    0x31, 0xd0, 0x36, 0x35, 0xd0, 0x36, 0x31, 0xd0,\n    0x38, 0x33, 0xd0, 0x38, 0x35, 0xd0, 0x38, 0x37,\n    0xd0, 0x38, 0x31, 0xd0, 0x49, 0x49, 0x49, 0x49,\n    0x49, 0x49, 0x56, 0x56, 0x49, 0x56, 0x49, 0x49,\n    0x56, 0x49, 0x49, 0x49, 0x49, 0x58, 0x58, 0x49,\n    0x58, 0x49, 0x49, 0x4c, 0x43, 0x44, 0x4d, 0x69,\n    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x76, 0x76,\n    0x69, 0x76, 0x69, 0x69, 0x76, 0x69, 0x69, 0x69,\n    0x69, 0x78, 0x78, 0x69, 0x78, 0x69, 0x69, 0x6c,\n    0x63, 0x64, 0x6d, 0x30, 0xd0, 0x33, 0x90, 0x21,\n    0xb8, 0x92, 0x21, 0xb8, 0x94, 0x21, 0xb8, 0xd0,\n    0x21, 0xb8, 0xd4, 0x21, 0xb8, 0xd2, 0x21, 0xb8,\n    0x03, 0x22, 0xb8, 0x08, 0x22, 0xb8, 0x0b, 0x22,\n    0xb8, 0x23, 0x22, 0xb8, 0x00, 0x00, 0x00, 0x25,\n    0x22, 0xb8, 0x2b, 0x22, 0x2b, 0x22, 0x2b, 0x22,\n    0x00, 0x00, 0x00, 0x2e, 0x22, 0x2e, 0x22, 0x2e,\n    0x22, 0x00, 0x00, 0x00, 0x3c, 0x22, 0xb8, 0x43,\n    0x22, 0xb8, 0x45, 0x22, 0xb8, 0x00, 0x00, 0x00,\n    0x48, 0x22, 0xb8, 0x3d, 0x00, 0xb8, 0x00, 0x00,\n    0x00, 0x61, 0x22, 0xb8, 0x4d, 0x22, 0xb8, 0x3c,\n    0x00, 0xb8, 0x3e, 0x00, 0xb8, 0x64, 0x22, 0xb8,\n    0x65, 0x22, 0xb8, 0x72, 0x22, 0xb8, 0x76, 0x22,\n    0xb8, 0x7a, 0x22, 0xb8, 0x82, 0x22, 0xb8, 0x86,\n    0x22, 0xb8, 0xa2, 0x22, 0xb8, 0xa8, 0x22, 0xb8,\n    0xa9, 0x22, 0xb8, 0xab, 0x22, 0xb8, 0x7c, 0x22,\n    0xb8, 0x91, 0x22, 0xb8, 0xb2, 0x22, 0x38, 0x03,\n    0x08, 0x30, 0x31, 0x00, 0x31, 0x00, 0x30, 0x00,\n    0x32, 0x30, 0x28, 0x00, 0x31, 0x00, 0x29, 0x00,\n    0x28, 0x00, 0x31, 0x00, 0x30, 0x00, 0x29, 0x00,\n    0x28, 0x32, 0x30, 0x29, 0x31, 0x00, 0x2e, 0x00,\n    0x31, 0x00, 0x30, 0x00, 0x2e, 0x00, 0x32, 0x30,\n    0x2e, 0x28, 0x00, 0x61, 0x00, 0x29, 0x00, 0x41,\n    0x00, 0x61, 0x00, 0x2b, 0x22, 0x00, 0x00, 0x00,\n    0x00, 0x3a, 0x3a, 0x3d, 0x3d, 0x3d, 0x3d, 0x3d,\n    0x3d, 0xdd, 0x2a, 0xb8, 0x6a, 0x56, 0x00, 0x4e,\n    0x00, 0x28, 0x36, 0x3f, 0x59, 0x85, 0x8c, 0xa0,\n    0xba, 0x3f, 0x51, 0x00, 0x26, 0x2c, 0x43, 0x57,\n    0x6c, 0xa1, 0xb6, 0xc1, 0x9b, 0x52, 0x00, 0x5e,\n    0x7a, 0x7f, 0x9d, 0xa6, 0xc1, 0xce, 0xe7, 0xb6,\n    0x53, 0xc8, 0x53, 0xe3, 0x53, 0xd7, 0x56, 0x1f,\n    0x57, 0xeb, 0x58, 0x02, 0x59, 0x0a, 0x59, 0x15,\n    0x59, 0x27, 0x59, 0x73, 0x59, 0x50, 0x5b, 0x80,\n    0x5b, 0xf8, 0x5b, 0x0f, 0x5c, 0x22, 0x5c, 0x38,\n    0x5c, 0x6e, 0x5c, 0x71, 0x5c, 0xdb, 0x5d, 0xe5,\n    0x5d, 0xf1, 0x5d, 0xfe, 0x5d, 0x72, 0x5e, 0x7a,\n    0x5e, 0x7f, 0x5e, 0xf4, 0x5e, 0xfe, 0x5e, 0x0b,\n    0x5f, 0x13, 0x5f, 0x50, 0x5f, 0x61, 0x5f, 0x73,\n    0x5f, 0xc3, 0x5f, 0x08, 0x62, 0x36, 0x62, 0x4b,\n    0x62, 0x2f, 0x65, 0x34, 0x65, 0x87, 0x65, 0x97,\n    0x65, 0xa4, 0x65, 0xb9, 0x65, 0xe0, 0x65, 0xe5,\n    0x65, 0xf0, 0x66, 0x08, 0x67, 0x28, 0x67, 0x20,\n    0x6b, 0x62, 0x6b, 0x79, 0x6b, 0xb3, 0x6b, 0xcb,\n    0x6b, 0xd4, 0x6b, 0xdb, 0x6b, 0x0f, 0x6c, 0x14,\n    0x6c, 0x34, 0x6c, 0x6b, 0x70, 0x2a, 0x72, 0x36,\n    0x72, 0x3b, 0x72, 0x3f, 0x72, 0x47, 0x72, 0x59,\n    0x72, 0x5b, 0x72, 0xac, 0x72, 0x84, 0x73, 0x89,\n    0x73, 0xdc, 0x74, 0xe6, 0x74, 0x18, 0x75, 0x1f,\n    0x75, 0x28, 0x75, 0x30, 0x75, 0x8b, 0x75, 0x92,\n    0x75, 0x76, 0x76, 0x7d, 0x76, 0xae, 0x76, 0xbf,\n    0x76, 0xee, 0x76, 0xdb, 0x77, 0xe2, 0x77, 0xf3,\n    0x77, 0x3a, 0x79, 0xb8, 0x79, 0xbe, 0x79, 0x74,\n    0x7a, 0xcb, 0x7a, 0xf9, 0x7a, 0x73, 0x7c, 0xf8,\n    0x7c, 0x36, 0x7f, 0x51, 0x7f, 0x8a, 0x7f, 0xbd,\n    0x7f, 0x01, 0x80, 0x0c, 0x80, 0x12, 0x80, 0x33,\n    0x80, 0x7f, 0x80, 0x89, 0x80, 0xe3, 0x81, 0x00,\n    0x07, 0x10, 0x19, 0x29, 0x38, 0x3c, 0x8b, 0x8f,\n    0x95, 0x4d, 0x86, 0x6b, 0x86, 0x40, 0x88, 0x4c,\n    0x88, 0x63, 0x88, 0x7e, 0x89, 0x8b, 0x89, 0xd2,\n    0x89, 0x00, 0x8a, 0x37, 0x8c, 0x46, 0x8c, 0x55,\n    0x8c, 0x78, 0x8c, 0x9d, 0x8c, 0x64, 0x8d, 0x70,\n    0x8d, 0xb3, 0x8d, 0xab, 0x8e, 0xca, 0x8e, 0x9b,\n    0x8f, 0xb0, 0x8f, 0xb5, 0x8f, 0x91, 0x90, 0x49,\n    0x91, 0xc6, 0x91, 0xcc, 0x91, 0xd1, 0x91, 0x77,\n    0x95, 0x80, 0x95, 0x1c, 0x96, 0xb6, 0x96, 0xb9,\n    0x96, 0xe8, 0x96, 0x51, 0x97, 0x5e, 0x97, 0x62,\n    0x97, 0x69, 0x97, 0xcb, 0x97, 0xed, 0x97, 0xf3,\n    0x97, 0x01, 0x98, 0xa8, 0x98, 0xdb, 0x98, 0xdf,\n    0x98, 0x96, 0x99, 0x99, 0x99, 0xac, 0x99, 0xa8,\n    0x9a, 0xd8, 0x9a, 0xdf, 0x9a, 0x25, 0x9b, 0x2f,\n    0x9b, 0x32, 0x9b, 0x3c, 0x9b, 0x5a, 0x9b, 0xe5,\n    0x9c, 0x75, 0x9e, 0x7f, 0x9e, 0xa5, 0x9e, 0x00,\n    0x16, 0x1e, 0x28, 0x2c, 0x54, 0x58, 0x69, 0x6e,\n    0x7b, 0x96, 0xa5, 0xad, 0xe8, 0xf7, 0xfb, 0x12,\n    0x30, 0x00, 0x00, 0x41, 0x53, 0x44, 0x53, 0x45,\n    0x53, 0x4b, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x4d, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x4f, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x51, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x53, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x55, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x57, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x59, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x5b, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x5d, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x5f, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0x61, 0x30, 0x99, 0x30, 0x64, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0x66, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0x68, 0x30, 0x99,\n    0x30, 0x6f, 0x30, 0x99, 0x30, 0x72, 0x30, 0x99,\n    0x30, 0x75, 0x30, 0x99, 0x30, 0x78, 0x30, 0x99,\n    0x30, 0x7b, 0x30, 0x99, 0x30, 0x46, 0x30, 0x99,\n    0x30, 0x20, 0x00, 0x99, 0x30, 0x9d, 0x30, 0x99,\n    0x30, 0x88, 0x30, 0x8a, 0x30, 0xab, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xad, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xaf, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xb1, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xb3, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xb5, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xb7, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xb9, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xbb, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xbd, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xbf, 0x30, 0x99,\n    0x30, 0x00, 0x00, 0x00, 0x00, 0xc1, 0x30, 0x99,\n    0x30, 0xc4, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0xc6, 0x30, 0x99, 0x30, 0x00, 0x00, 0x00,\n    0x00, 0xc8, 0x30, 0x99, 0x30, 0xcf, 0x30, 0x99,\n    0x30, 0xd2, 0x30, 0x99, 0x30, 0xd5, 0x30, 0x99,\n    0x30, 0xd8, 0x30, 0x99, 0x30, 0xdb, 0x30, 0x99,\n    0x30, 0xa6, 0x30, 0x99, 0x30, 0xef, 0x30, 0x99,\n    0x30, 0xfd, 0x30, 0x99, 0x30, 0xb3, 0x30, 0xc8,\n    0x30, 0x00, 0x11, 0x00, 0x01, 0xaa, 0x02, 0xac,\n    0xad, 0x03, 0x04, 0x05, 0xb0, 0xb1, 0xb2, 0xb3,\n    0xb4, 0xb5, 0x1a, 0x06, 0x07, 0x08, 0x21, 0x09,\n    0x11, 0x61, 0x11, 0x14, 0x11, 0x4c, 0x00, 0x01,\n    0xb3, 0xb4, 0xb8, 0xba, 0xbf, 0xc3, 0xc5, 0x08,\n    0xc9, 0xcb, 0x09, 0x0a, 0x0c, 0x0e, 0x0f, 0x13,\n    0x15, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1e, 0x22,\n    0x2c, 0x33, 0x38, 0xdd, 0xde, 0x43, 0x44, 0x45,\n    0x70, 0x71, 0x74, 0x7d, 0x7e, 0x80, 0x8a, 0x8d,\n    0x00, 0x4e, 0x8c, 0x4e, 0x09, 0x4e, 0xdb, 0x56,\n    0x0a, 0x4e, 0x2d, 0x4e, 0x0b, 0x4e, 0x32, 0x75,\n    0x59, 0x4e, 0x19, 0x4e, 0x01, 0x4e, 0x29, 0x59,\n    0x30, 0x57, 0xba, 0x4e, 0x28, 0x00, 0x29, 0x00,\n    0x00, 0x11, 0x02, 0x11, 0x03, 0x11, 0x05, 0x11,\n    0x06, 0x11, 0x07, 0x11, 0x09, 0x11, 0x0b, 0x11,\n    0x0c, 0x11, 0x0e, 0x11, 0x0f, 0x11, 0x10, 0x11,\n    0x11, 0x11, 0x12, 0x11, 0x28, 0x00, 0x00, 0x11,\n    0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x02, 0x11,\n    0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x05, 0x11,\n    0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x09, 0x11,\n    0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x0b, 0x11,\n    0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x0e, 0x11,\n    0x61, 0x11, 0x29, 0x00, 0x28, 0x00, 0x0c, 0x11,\n    0x6e, 0x11, 0x29, 0x00, 0x28, 0x00, 0x0b, 0x11,\n    0x69, 0x11, 0x0c, 0x11, 0x65, 0x11, 0xab, 0x11,\n    0x29, 0x00, 0x28, 0x00, 0x0b, 0x11, 0x69, 0x11,\n    0x12, 0x11, 0x6e, 0x11, 0x29, 0x00, 0x28, 0x00,\n    0x29, 0x00, 0x00, 0x4e, 0x8c, 0x4e, 0x09, 0x4e,\n    0xdb, 0x56, 0x94, 0x4e, 0x6d, 0x51, 0x03, 0x4e,\n    0x6b, 0x51, 0x5d, 0x4e, 0x41, 0x53, 0x08, 0x67,\n    0x6b, 0x70, 0x34, 0x6c, 0x28, 0x67, 0xd1, 0x91,\n    0x1f, 0x57, 0xe5, 0x65, 0x2a, 0x68, 0x09, 0x67,\n    0x3e, 0x79, 0x0d, 0x54, 0x79, 0x72, 0xa1, 0x8c,\n    0x5d, 0x79, 0xb4, 0x52, 0xe3, 0x4e, 0x7c, 0x54,\n    0x66, 0x5b, 0xe3, 0x76, 0x01, 0x4f, 0xc7, 0x8c,\n    0x54, 0x53, 0x6d, 0x79, 0x11, 0x4f, 0xea, 0x81,\n    0xf3, 0x81, 0x4f, 0x55, 0x7c, 0x5e, 0x87, 0x65,\n    0x8f, 0x7b, 0x50, 0x54, 0x45, 0x32, 0x00, 0x31,\n    0x00, 0x33, 0x00, 0x30, 0x00, 0x00, 0x11, 0x00,\n    0x02, 0x03, 0x05, 0x06, 0x07, 0x09, 0x0b, 0x0c,\n    0x0e, 0x0f, 0x10, 0x11, 0x12, 0x00, 0x11, 0x00,\n    0x61, 0x02, 0x61, 0x03, 0x61, 0x05, 0x61, 0x06,\n    0x61, 0x07, 0x61, 0x09, 0x61, 0x0b, 0x61, 0x0c,\n    0x61, 0x0e, 0x11, 0x61, 0x11, 0x00, 0x11, 0x0e,\n    0x61, 0xb7, 0x00, 0x69, 0x0b, 0x11, 0x01, 0x63,\n    0x00, 0x69, 0x0b, 0x11, 0x6e, 0x11, 0x00, 0x4e,\n    0x8c, 0x4e, 0x09, 0x4e, 0xdb, 0x56, 0x94, 0x4e,\n    0x6d, 0x51, 0x03, 0x4e, 0x6b, 0x51, 0x5d, 0x4e,\n    0x41, 0x53, 0x08, 0x67, 0x6b, 0x70, 0x34, 0x6c,\n    0x28, 0x67, 0xd1, 0x91, 0x1f, 0x57, 0xe5, 0x65,\n    0x2a, 0x68, 0x09, 0x67, 0x3e, 0x79, 0x0d, 0x54,\n    0x79, 0x72, 0xa1, 0x8c, 0x5d, 0x79, 0xb4, 0x52,\n    0xd8, 0x79, 0x37, 0x75, 0x73, 0x59, 0x69, 0x90,\n    0x2a, 0x51, 0x70, 0x53, 0xe8, 0x6c, 0x05, 0x98,\n    0x11, 0x4f, 0x99, 0x51, 0x63, 0x6b, 0x0a, 0x4e,\n    0x2d, 0x4e, 0x0b, 0x4e, 0xe6, 0x5d, 0xf3, 0x53,\n    0x3b, 0x53, 0x97, 0x5b, 0x66, 0x5b, 0xe3, 0x76,\n    0x01, 0x4f, 0xc7, 0x8c, 0x54, 0x53, 0x1c, 0x59,\n    0x33, 0x00, 0x36, 0x00, 0x34, 0x00, 0x30, 0x00,\n    0x35, 0x30, 0x31, 0x00, 0x08, 0x67, 0x31, 0x00,\n    0x30, 0x00, 0x08, 0x67, 0x48, 0x67, 0x65, 0x72,\n    0x67, 0x65, 0x56, 0x4c, 0x54, 0x44, 0xa2, 0x30,\n    0x00, 0x02, 0x04, 0x06, 0x08, 0x09, 0x0b, 0x0d,\n    0x0f, 0x11, 0x13, 0x15, 0x17, 0x19, 0x1b, 0x1d,\n    0x1f, 0x22, 0x24, 0x26, 0x28, 0x29, 0x2a, 0x2b,\n    0x2c, 0x2d, 0x30, 0x33, 0x36, 0x39, 0x3c, 0x3d,\n    0x3e, 0x3f, 0x40, 0x42, 0x44, 0x46, 0x47, 0x48,\n    0x49, 0x4a, 0x4b, 0x4d, 0x4e, 0x4f, 0x50, 0xe4,\n    0x4e, 0x8c, 0x54, 0xa1, 0x30, 0x01, 0x30, 0x5b,\n    0x27, 0x01, 0x4a, 0x34, 0x00, 0x01, 0x52, 0x39,\n    0x01, 0xa2, 0x30, 0x00, 0x5a, 0x49, 0xa4, 0x30,\n    0x00, 0x27, 0x4f, 0x0c, 0xa4, 0x30, 0x00, 0x4f,\n    0x1d, 0x02, 0x05, 0x4f, 0xa8, 0x30, 0x00, 0x11,\n    0x07, 0x54, 0x21, 0xa8, 0x30, 0x00, 0x54, 0x03,\n    0x54, 0xa4, 0x30, 0x06, 0x4f, 0x15, 0x06, 0x58,\n    0x3c, 0x07, 0x00, 0x46, 0xab, 0x30, 0x00, 0x3e,\n    0x18, 0x1d, 0x00, 0x42, 0x3f, 0x51, 0xac, 0x30,\n    0x00, 0x41, 0x47, 0x00, 0x47, 0x32, 0xae, 0x30,\n    0xac, 0x30, 0xae, 0x30, 0x00, 0x1d, 0x4e, 0xad,\n    0x30, 0x00, 0x38, 0x3d, 0x4f, 0x01, 0x3e, 0x13,\n    0x4f, 0xad, 0x30, 0xed, 0x30, 0xad, 0x30, 0x00,\n    0x40, 0x03, 0x3c, 0x33, 0xad, 0x30, 0x00, 0x40,\n    0x34, 0x4f, 0x1b, 0x3e, 0xad, 0x30, 0x00, 0x40,\n    0x42, 0x16, 0x1b, 0xb0, 0x30, 0x00, 0x39, 0x30,\n    0xa4, 0x30, 0x0c, 0x45, 0x3c, 0x24, 0x4f, 0x0b,\n    0x47, 0x18, 0x00, 0x49, 0xaf, 0x30, 0x00, 0x3e,\n    0x4d, 0x1e, 0xb1, 0x30, 0x00, 0x4b, 0x08, 0x02,\n    0x3a, 0x19, 0x02, 0x4b, 0x2c, 0xa4, 0x30, 0x11,\n    0x00, 0x0b, 0x47, 0xb5, 0x30, 0x00, 0x3e, 0x0c,\n    0x47, 0x2b, 0xb0, 0x30, 0x07, 0x3a, 0x43, 0x00,\n    0xb9, 0x30, 0x02, 0x3a, 0x08, 0x02, 0x3a, 0x0f,\n    0x07, 0x43, 0x00, 0xb7, 0x30, 0x10, 0x00, 0x12,\n    0x34, 0x11, 0x3c, 0x13, 0x17, 0xa4, 0x30, 0x2a,\n    0x1f, 0x24, 0x2b, 0x00, 0x20, 0xbb, 0x30, 0x16,\n    0x41, 0x00, 0x38, 0x0d, 0xc4, 0x30, 0x0d, 0x38,\n    0x00, 0xd0, 0x30, 0x00, 0x2c, 0x1c, 0x1b, 0xa2,\n    0x30, 0x32, 0x00, 0x17, 0x26, 0x49, 0xaf, 0x30,\n    0x25, 0x00, 0x3c, 0xb3, 0x30, 0x21, 0x00, 0x20,\n    0x38, 0xa1, 0x30, 0x34, 0x00, 0x48, 0x22, 0x28,\n    0xa3, 0x30, 0x32, 0x00, 0x59, 0x25, 0xa7, 0x30,\n    0x2f, 0x1c, 0x10, 0x00, 0x44, 0xd5, 0x30, 0x00,\n    0x14, 0x1e, 0xaf, 0x30, 0x29, 0x00, 0x10, 0x4d,\n    0x3c, 0xda, 0x30, 0xbd, 0x30, 0xb8, 0x30, 0x22,\n    0x13, 0x1a, 0x20, 0x33, 0x0c, 0x22, 0x3b, 0x01,\n    0x22, 0x44, 0x00, 0x21, 0x44, 0x07, 0xa4, 0x30,\n    0x39, 0x00, 0x4f, 0x24, 0xc8, 0x30, 0x14, 0x23,\n    0x00, 0xdb, 0x30, 0xf3, 0x30, 0xc9, 0x30, 0x14,\n    0x2a, 0x00, 0x12, 0x33, 0x22, 0x12, 0x33, 0x2a,\n    0xa4, 0x30, 0x3a, 0x00, 0x0b, 0x49, 0xa4, 0x30,\n    0x3a, 0x00, 0x47, 0x3a, 0x1f, 0x2b, 0x3a, 0x47,\n    0x0b, 0xb7, 0x30, 0x27, 0x3c, 0x00, 0x30, 0x3c,\n    0xaf, 0x30, 0x30, 0x00, 0x3e, 0x44, 0xdf, 0x30,\n    0xea, 0x30, 0xd0, 0x30, 0x0f, 0x1a, 0x00, 0x2c,\n    0x1b, 0xe1, 0x30, 0xac, 0x30, 0xac, 0x30, 0x35,\n    0x00, 0x1c, 0x47, 0x35, 0x50, 0x1c, 0x3f, 0xa2,\n    0x30, 0x42, 0x5a, 0x27, 0x42, 0x5a, 0x49, 0x44,\n    0x00, 0x51, 0xc3, 0x30, 0x27, 0x00, 0x05, 0x28,\n    0xea, 0x30, 0xe9, 0x30, 0xd4, 0x30, 0x17, 0x00,\n    0x28, 0xd6, 0x30, 0x15, 0x26, 0x00, 0x15, 0xec,\n    0x30, 0xe0, 0x30, 0xb2, 0x30, 0x3a, 0x41, 0x16,\n    0x00, 0x41, 0xc3, 0x30, 0x2c, 0x00, 0x05, 0x30,\n    0x00, 0xb9, 0x70, 0x31, 0x00, 0x30, 0x00, 0xb9,\n    0x70, 0x32, 0x00, 0x30, 0x00, 0xb9, 0x70, 0x68,\n    0x50, 0x61, 0x64, 0x61, 0x41, 0x55, 0x62, 0x61,\n    0x72, 0x6f, 0x56, 0x70, 0x63, 0x64, 0x6d, 0x64,\n    0x00, 0x6d, 0x00, 0xb2, 0x00, 0x49, 0x00, 0x55,\n    0x00, 0x73, 0x5e, 0x10, 0x62, 0x2d, 0x66, 0x8c,\n    0x54, 0x27, 0x59, 0x63, 0x6b, 0x0e, 0x66, 0xbb,\n    0x6c, 0x2a, 0x68, 0x0f, 0x5f, 0x1a, 0x4f, 0x3e,\n    0x79, 0x70, 0x00, 0x41, 0x6e, 0x00, 0x41, 0xbc,\n    0x03, 0x41, 0x6d, 0x00, 0x41, 0x6b, 0x00, 0x41,\n    0x4b, 0x00, 0x42, 0x4d, 0x00, 0x42, 0x47, 0x00,\n    0x42, 0x63, 0x61, 0x6c, 0x6b, 0x63, 0x61, 0x6c,\n    0x70, 0x00, 0x46, 0x6e, 0x00, 0x46, 0xbc, 0x03,\n    0x46, 0xbc, 0x03, 0x67, 0x6d, 0x00, 0x67, 0x6b,\n    0x00, 0x67, 0x48, 0x00, 0x7a, 0x6b, 0x48, 0x7a,\n    0x4d, 0x48, 0x7a, 0x47, 0x48, 0x7a, 0x54, 0x48,\n    0x7a, 0xbc, 0x03, 0x13, 0x21, 0x6d, 0x00, 0x13,\n    0x21, 0x64, 0x00, 0x13, 0x21, 0x6b, 0x00, 0x13,\n    0x21, 0x66, 0x00, 0x6d, 0x6e, 0x00, 0x6d, 0xbc,\n    0x03, 0x6d, 0x6d, 0x00, 0x6d, 0x63, 0x00, 0x6d,\n    0x6b, 0x00, 0x6d, 0x63, 0x00, 0x0a, 0x0a, 0x4f,\n    0x00, 0x0a, 0x4f, 0x6d, 0x00, 0xb2, 0x00, 0x63,\n    0x00, 0x08, 0x0a, 0x4f, 0x0a, 0x0a, 0x50, 0x00,\n    0x0a, 0x50, 0x6d, 0x00, 0xb3, 0x00, 0x6b, 0x00,\n    0x6d, 0x00, 0xb3, 0x00, 0x6d, 0x00, 0x15, 0x22,\n    0x73, 0x00, 0x6d, 0x00, 0x15, 0x22, 0x73, 0x00,\n    0xb2, 0x00, 0x50, 0x61, 0x6b, 0x50, 0x61, 0x4d,\n    0x50, 0x61, 0x47, 0x50, 0x61, 0x72, 0x61, 0x64,\n    0x72, 0x61, 0x64, 0xd1, 0x73, 0x72, 0x00, 0x61,\n    0x00, 0x64, 0x00, 0x15, 0x22, 0x73, 0x00, 0xb2,\n    0x00, 0x70, 0x00, 0x73, 0x6e, 0x00, 0x73, 0xbc,\n    0x03, 0x73, 0x6d, 0x00, 0x73, 0x70, 0x00, 0x56,\n    0x6e, 0x00, 0x56, 0xbc, 0x03, 0x56, 0x6d, 0x00,\n    0x56, 0x6b, 0x00, 0x56, 0x4d, 0x00, 0x56, 0x70,\n    0x00, 0x57, 0x6e, 0x00, 0x57, 0xbc, 0x03, 0x57,\n    0x6d, 0x00, 0x57, 0x6b, 0x00, 0x57, 0x4d, 0x00,\n    0x57, 0x6b, 0x00, 0xa9, 0x03, 0x4d, 0x00, 0xa9,\n    0x03, 0x61, 0x2e, 0x6d, 0x2e, 0x42, 0x71, 0x63,\n    0x63, 0x63, 0x64, 0x43, 0xd1, 0x6b, 0x67, 0x43,\n    0x6f, 0x2e, 0x64, 0x42, 0x47, 0x79, 0x68, 0x61,\n    0x48, 0x50, 0x69, 0x6e, 0x4b, 0x4b, 0x4b, 0x4d,\n    0x6b, 0x74, 0x6c, 0x6d, 0x6c, 0x6e, 0x6c, 0x6f,\n    0x67, 0x6c, 0x78, 0x6d, 0x62, 0x6d, 0x69, 0x6c,\n    0x6d, 0x6f, 0x6c, 0x50, 0x48, 0x70, 0x2e, 0x6d,\n    0x2e, 0x50, 0x50, 0x4d, 0x50, 0x52, 0x73, 0x72,\n    0x53, 0x76, 0x57, 0x62, 0x56, 0xd1, 0x6d, 0x41,\n    0xd1, 0x6d, 0x31, 0x00, 0xe5, 0x65, 0x31, 0x00,\n    0x30, 0x00, 0xe5, 0x65, 0x32, 0x00, 0x30, 0x00,\n    0xe5, 0x65, 0x33, 0x00, 0x30, 0x00, 0xe5, 0x65,\n    0x67, 0x61, 0x6c, 0x4a, 0x04, 0x4c, 0x04, 0x26,\n    0x01, 0x53, 0x01, 0x27, 0xa7, 0x37, 0xab, 0x6b,\n    0x02, 0x52, 0xab, 0x48, 0x8c, 0xf4, 0x66, 0xca,\n    0x8e, 0xc8, 0x8c, 0xd1, 0x6e, 0x32, 0x4e, 0xe5,\n    0x53, 0x9c, 0x9f, 0x9c, 0x9f, 0x51, 0x59, 0xd1,\n    0x91, 0x87, 0x55, 0x48, 0x59, 0xf6, 0x61, 0x69,\n    0x76, 0x85, 0x7f, 0x3f, 0x86, 0xba, 0x87, 0xf8,\n    0x88, 0x8f, 0x90, 0x02, 0x6a, 0x1b, 0x6d, 0xd9,\n    0x70, 0xde, 0x73, 0x3d, 0x84, 0x6a, 0x91, 0xf1,\n    0x99, 0x82, 0x4e, 0x75, 0x53, 0x04, 0x6b, 0x1b,\n    0x72, 0x2d, 0x86, 0x1e, 0x9e, 0x50, 0x5d, 0xeb,\n    0x6f, 0xcd, 0x85, 0x64, 0x89, 0xc9, 0x62, 0xd8,\n    0x81, 0x1f, 0x88, 0xca, 0x5e, 0x17, 0x67, 0x6a,\n    0x6d, 0xfc, 0x72, 0xce, 0x90, 0x86, 0x4f, 0xb7,\n    0x51, 0xde, 0x52, 0xc4, 0x64, 0xd3, 0x6a, 0x10,\n    0x72, 0xe7, 0x76, 0x01, 0x80, 0x06, 0x86, 0x5c,\n    0x86, 0xef, 0x8d, 0x32, 0x97, 0x6f, 0x9b, 0xfa,\n    0x9d, 0x8c, 0x78, 0x7f, 0x79, 0xa0, 0x7d, 0xc9,\n    0x83, 0x04, 0x93, 0x7f, 0x9e, 0xd6, 0x8a, 0xdf,\n    0x58, 0x04, 0x5f, 0x60, 0x7c, 0x7e, 0x80, 0x62,\n    0x72, 0xca, 0x78, 0xc2, 0x8c, 0xf7, 0x96, 0xd8,\n    0x58, 0x62, 0x5c, 0x13, 0x6a, 0xda, 0x6d, 0x0f,\n    0x6f, 0x2f, 0x7d, 0x37, 0x7e, 0x4b, 0x96, 0xd2,\n    0x52, 0x8b, 0x80, 0xdc, 0x51, 0xcc, 0x51, 0x1c,\n    0x7a, 0xbe, 0x7d, 0xf1, 0x83, 0x75, 0x96, 0x80,\n    0x8b, 0xcf, 0x62, 0x02, 0x6a, 0xfe, 0x8a, 0x39,\n    0x4e, 0xe7, 0x5b, 0x12, 0x60, 0x87, 0x73, 0x70,\n    0x75, 0x17, 0x53, 0xfb, 0x78, 0xbf, 0x4f, 0xa9,\n    0x5f, 0x0d, 0x4e, 0xcc, 0x6c, 0x78, 0x65, 0x22,\n    0x7d, 0xc3, 0x53, 0x5e, 0x58, 0x01, 0x77, 0x49,\n    0x84, 0xaa, 0x8a, 0xba, 0x6b, 0xb0, 0x8f, 0x88,\n    0x6c, 0xfe, 0x62, 0xe5, 0x82, 0xa0, 0x63, 0x65,\n    0x75, 0xae, 0x4e, 0x69, 0x51, 0xc9, 0x51, 0x81,\n    0x68, 0xe7, 0x7c, 0x6f, 0x82, 0xd2, 0x8a, 0xcf,\n    0x91, 0xf5, 0x52, 0x42, 0x54, 0x73, 0x59, 0xec,\n    0x5e, 0xc5, 0x65, 0xfe, 0x6f, 0x2a, 0x79, 0xad,\n    0x95, 0x6a, 0x9a, 0x97, 0x9e, 0xce, 0x9e, 0x9b,\n    0x52, 0xc6, 0x66, 0x77, 0x6b, 0x62, 0x8f, 0x74,\n    0x5e, 0x90, 0x61, 0x00, 0x62, 0x9a, 0x64, 0x23,\n    0x6f, 0x49, 0x71, 0x89, 0x74, 0xca, 0x79, 0xf4,\n    0x7d, 0x6f, 0x80, 0x26, 0x8f, 0xee, 0x84, 0x23,\n    0x90, 0x4a, 0x93, 0x17, 0x52, 0xa3, 0x52, 0xbd,\n    0x54, 0xc8, 0x70, 0xc2, 0x88, 0xaa, 0x8a, 0xc9,\n    0x5e, 0xf5, 0x5f, 0x7b, 0x63, 0xae, 0x6b, 0x3e,\n    0x7c, 0x75, 0x73, 0xe4, 0x4e, 0xf9, 0x56, 0xe7,\n    0x5b, 0xba, 0x5d, 0x1c, 0x60, 0xb2, 0x73, 0x69,\n    0x74, 0x9a, 0x7f, 0x46, 0x80, 0x34, 0x92, 0xf6,\n    0x96, 0x48, 0x97, 0x18, 0x98, 0x8b, 0x4f, 0xae,\n    0x79, 0xb4, 0x91, 0xb8, 0x96, 0xe1, 0x60, 0x86,\n    0x4e, 0xda, 0x50, 0xee, 0x5b, 0x3f, 0x5c, 0x99,\n    0x65, 0x02, 0x6a, 0xce, 0x71, 0x42, 0x76, 0xfc,\n    0x84, 0x7c, 0x90, 0x8d, 0x9f, 0x88, 0x66, 0x2e,\n    0x96, 0x89, 0x52, 0x7b, 0x67, 0xf3, 0x67, 0x41,\n    0x6d, 0x9c, 0x6e, 0x09, 0x74, 0x59, 0x75, 0x6b,\n    0x78, 0x10, 0x7d, 0x5e, 0x98, 0x6d, 0x51, 0x2e,\n    0x62, 0x78, 0x96, 0x2b, 0x50, 0x19, 0x5d, 0xea,\n    0x6d, 0x2a, 0x8f, 0x8b, 0x5f, 0x44, 0x61, 0x17,\n    0x68, 0x87, 0x73, 0x86, 0x96, 0x29, 0x52, 0x0f,\n    0x54, 0x65, 0x5c, 0x13, 0x66, 0x4e, 0x67, 0xa8,\n    0x68, 0xe5, 0x6c, 0x06, 0x74, 0xe2, 0x75, 0x79,\n    0x7f, 0xcf, 0x88, 0xe1, 0x88, 0xcc, 0x91, 0xe2,\n    0x96, 0x3f, 0x53, 0xba, 0x6e, 0x1d, 0x54, 0xd0,\n    0x71, 0x98, 0x74, 0xfa, 0x85, 0xa3, 0x96, 0x57,\n    0x9c, 0x9f, 0x9e, 0x97, 0x67, 0xcb, 0x6d, 0xe8,\n    0x81, 0xcb, 0x7a, 0x20, 0x7b, 0x92, 0x7c, 0xc0,\n    0x72, 0x99, 0x70, 0x58, 0x8b, 0xc0, 0x4e, 0x36,\n    0x83, 0x3a, 0x52, 0x07, 0x52, 0xa6, 0x5e, 0xd3,\n    0x62, 0xd6, 0x7c, 0x85, 0x5b, 0x1e, 0x6d, 0xb4,\n    0x66, 0x3b, 0x8f, 0x4c, 0x88, 0x4d, 0x96, 0x8b,\n    0x89, 0xd3, 0x5e, 0x40, 0x51, 0xc0, 0x55, 0x00,\n    0x00, 0x00, 0x00, 0x5a, 0x58, 0x00, 0x00, 0x74,\n    0x66, 0x00, 0x00, 0x00, 0x00, 0xde, 0x51, 0x2a,\n    0x73, 0xca, 0x76, 0x3c, 0x79, 0x5e, 0x79, 0x65,\n    0x79, 0x8f, 0x79, 0x56, 0x97, 0xbe, 0x7c, 0xbd,\n    0x7f, 0x00, 0x00, 0x12, 0x86, 0x00, 0x00, 0xf8,\n    0x8a, 0x00, 0x00, 0x00, 0x00, 0x38, 0x90, 0xfd,\n    0x90, 0xef, 0x98, 0xfc, 0x98, 0x28, 0x99, 0xb4,\n    0x9d, 0xde, 0x90, 0xb7, 0x96, 0xae, 0x4f, 0xe7,\n    0x50, 0x4d, 0x51, 0xc9, 0x52, 0xe4, 0x52, 0x51,\n    0x53, 0x9d, 0x55, 0x06, 0x56, 0x68, 0x56, 0x40,\n    0x58, 0xa8, 0x58, 0x64, 0x5c, 0x6e, 0x5c, 0x94,\n    0x60, 0x68, 0x61, 0x8e, 0x61, 0xf2, 0x61, 0x4f,\n    0x65, 0xe2, 0x65, 0x91, 0x66, 0x85, 0x68, 0x77,\n    0x6d, 0x1a, 0x6e, 0x22, 0x6f, 0x6e, 0x71, 0x2b,\n    0x72, 0x22, 0x74, 0x91, 0x78, 0x3e, 0x79, 0x49,\n    0x79, 0x48, 0x79, 0x50, 0x79, 0x56, 0x79, 0x5d,\n    0x79, 0x8d, 0x79, 0x8e, 0x79, 0x40, 0x7a, 0x81,\n    0x7a, 0xc0, 0x7b, 0xf4, 0x7d, 0x09, 0x7e, 0x41,\n    0x7e, 0x72, 0x7f, 0x05, 0x80, 0xed, 0x81, 0x79,\n    0x82, 0x79, 0x82, 0x57, 0x84, 0x10, 0x89, 0x96,\n    0x89, 0x01, 0x8b, 0x39, 0x8b, 0xd3, 0x8c, 0x08,\n    0x8d, 0xb6, 0x8f, 0x38, 0x90, 0xe3, 0x96, 0xff,\n    0x97, 0x3b, 0x98, 0x75, 0x60, 0xee, 0x42, 0x18,\n    0x82, 0x02, 0x26, 0x4e, 0xb5, 0x51, 0x68, 0x51,\n    0x80, 0x4f, 0x45, 0x51, 0x80, 0x51, 0xc7, 0x52,\n    0xfa, 0x52, 0x9d, 0x55, 0x55, 0x55, 0x99, 0x55,\n    0xe2, 0x55, 0x5a, 0x58, 0xb3, 0x58, 0x44, 0x59,\n    0x54, 0x59, 0x62, 0x5a, 0x28, 0x5b, 0xd2, 0x5e,\n    0xd9, 0x5e, 0x69, 0x5f, 0xad, 0x5f, 0xd8, 0x60,\n    0x4e, 0x61, 0x08, 0x61, 0x8e, 0x61, 0x60, 0x61,\n    0xf2, 0x61, 0x34, 0x62, 0xc4, 0x63, 0x1c, 0x64,\n    0x52, 0x64, 0x56, 0x65, 0x74, 0x66, 0x17, 0x67,\n    0x1b, 0x67, 0x56, 0x67, 0x79, 0x6b, 0xba, 0x6b,\n    0x41, 0x6d, 0xdb, 0x6e, 0xcb, 0x6e, 0x22, 0x6f,\n    0x1e, 0x70, 0x6e, 0x71, 0xa7, 0x77, 0x35, 0x72,\n    0xaf, 0x72, 0x2a, 0x73, 0x71, 0x74, 0x06, 0x75,\n    0x3b, 0x75, 0x1d, 0x76, 0x1f, 0x76, 0xca, 0x76,\n    0xdb, 0x76, 0xf4, 0x76, 0x4a, 0x77, 0x40, 0x77,\n    0xcc, 0x78, 0xb1, 0x7a, 0xc0, 0x7b, 0x7b, 0x7c,\n    0x5b, 0x7d, 0xf4, 0x7d, 0x3e, 0x7f, 0x05, 0x80,\n    0x52, 0x83, 0xef, 0x83, 0x79, 0x87, 0x41, 0x89,\n    0x86, 0x89, 0x96, 0x89, 0xbf, 0x8a, 0xf8, 0x8a,\n    0xcb, 0x8a, 0x01, 0x8b, 0xfe, 0x8a, 0xed, 0x8a,\n    0x39, 0x8b, 0x8a, 0x8b, 0x08, 0x8d, 0x38, 0x8f,\n    0x72, 0x90, 0x99, 0x91, 0x76, 0x92, 0x7c, 0x96,\n    0xe3, 0x96, 0x56, 0x97, 0xdb, 0x97, 0xff, 0x97,\n    0x0b, 0x98, 0x3b, 0x98, 0x12, 0x9b, 0x9c, 0x9f,\n    0x4a, 0x28, 0x44, 0x28, 0xd5, 0x33, 0x9d, 0x3b,\n    0x18, 0x40, 0x39, 0x40, 0x49, 0x52, 0xd0, 0x5c,\n    0xd3, 0x7e, 0x43, 0x9f, 0x8e, 0x9f, 0x2a, 0xa0,\n    0x02, 0x66, 0x66, 0x66, 0x69, 0x66, 0x6c, 0x66,\n    0x66, 0x69, 0x66, 0x66, 0x6c, 0x7f, 0x01, 0x74,\n    0x73, 0x00, 0x74, 0x65, 0x05, 0x0f, 0x11, 0x0f,\n    0x00, 0x0f, 0x06, 0x19, 0x11, 0x0f, 0x08, 0xd9,\n    0x05, 0xb4, 0x05, 0x00, 0x00, 0x00, 0x00, 0xf2,\n    0x05, 0xb7, 0x05, 0xd0, 0x05, 0x12, 0x00, 0x03,\n    0x04, 0x0b, 0x0c, 0x0d, 0x18, 0x1a, 0xe9, 0x05,\n    0xc1, 0x05, 0xe9, 0x05, 0xc2, 0x05, 0x49, 0xfb,\n    0xc1, 0x05, 0x49, 0xfb, 0xc2, 0x05, 0xd0, 0x05,\n    0xb7, 0x05, 0xd0, 0x05, 0xb8, 0x05, 0xd0, 0x05,\n    0xbc, 0x05, 0xd8, 0x05, 0xbc, 0x05, 0xde, 0x05,\n    0xbc, 0x05, 0xe0, 0x05, 0xbc, 0x05, 0xe3, 0x05,\n    0xbc, 0x05, 0xb9, 0x05, 0x2d, 0x03, 0x2e, 0x03,\n    0x2f, 0x03, 0x30, 0x03, 0x31, 0x03, 0x1c, 0x00,\n    0x18, 0x06, 0x22, 0x06, 0x2b, 0x06, 0xd0, 0x05,\n    0xdc, 0x05, 0x71, 0x06, 0x00, 0x00, 0x0a, 0x0a,\n    0x0a, 0x0a, 0x0d, 0x0d, 0x0d, 0x0d, 0x0f, 0x0f,\n    0x0f, 0x0f, 0x09, 0x09, 0x09, 0x09, 0x0e, 0x0e,\n    0x0e, 0x0e, 0x08, 0x08, 0x08, 0x08, 0x33, 0x33,\n    0x33, 0x33, 0x35, 0x35, 0x35, 0x35, 0x13, 0x13,\n    0x13, 0x13, 0x12, 0x12, 0x12, 0x12, 0x15, 0x15,\n    0x15, 0x15, 0x16, 0x16, 0x16, 0x16, 0x1c, 0x1c,\n    0x1b, 0x1b, 0x1d, 0x1d, 0x17, 0x17, 0x27, 0x27,\n    0x20, 0x20, 0x38, 0x38, 0x38, 0x38, 0x3e, 0x3e,\n    0x3e, 0x3e, 0x42, 0x42, 0x42, 0x42, 0x40, 0x40,\n    0x40, 0x40, 0x49, 0x49, 0x4a, 0x4a, 0x4a, 0x4a,\n    0x4f, 0x4f, 0x50, 0x50, 0x50, 0x50, 0x4d, 0x4d,\n    0x4d, 0x4d, 0x61, 0x61, 0x62, 0x62, 0x49, 0x06,\n    0x64, 0x64, 0x64, 0x64, 0x7e, 0x7e, 0x7d, 0x7d,\n    0x7f, 0x7f, 0x2e, 0x82, 0x82, 0x7c, 0x7c, 0x80,\n    0x80, 0x87, 0x87, 0x87, 0x87, 0x00, 0x00, 0x26,\n    0x06, 0x00, 0x01, 0x00, 0x01, 0x00, 0xaf, 0x00,\n    0xaf, 0x00, 0x22, 0x00, 0x22, 0x00, 0xa1, 0x00,\n    0xa1, 0x00, 0xa0, 0x00, 0xa0, 0x00, 0xa2, 0x00,\n    0xa2, 0x00, 0xaa, 0x00, 0xaa, 0x00, 0xaa, 0x00,\n    0x23, 0x00, 0x23, 0x00, 0x23, 0xcc, 0x06, 0x00,\n    0x00, 0x00, 0x00, 0x26, 0x06, 0x00, 0x06, 0x00,\n    0x07, 0x00, 0x1f, 0x00, 0x23, 0x00, 0x24, 0x02,\n    0x06, 0x02, 0x07, 0x02, 0x08, 0x02, 0x1f, 0x02,\n    0x23, 0x02, 0x24, 0x04, 0x06, 0x04, 0x07, 0x04,\n    0x08, 0x04, 0x1f, 0x04, 0x23, 0x04, 0x24, 0x05,\n    0x06, 0x05, 0x1f, 0x05, 0x23, 0x05, 0x24, 0x06,\n    0x07, 0x06, 0x1f, 0x07, 0x06, 0x07, 0x1f, 0x08,\n    0x06, 0x08, 0x07, 0x08, 0x1f, 0x0d, 0x06, 0x0d,\n    0x07, 0x0d, 0x08, 0x0d, 0x1f, 0x0f, 0x07, 0x0f,\n    0x1f, 0x10, 0x06, 0x10, 0x07, 0x10, 0x08, 0x10,\n    0x1f, 0x11, 0x07, 0x11, 0x1f, 0x12, 0x1f, 0x13,\n    0x06, 0x13, 0x1f, 0x14, 0x06, 0x14, 0x1f, 0x1b,\n    0x06, 0x1b, 0x07, 0x1b, 0x08, 0x1b, 0x1f, 0x1b,\n    0x23, 0x1b, 0x24, 0x1c, 0x07, 0x1c, 0x1f, 0x1c,\n    0x23, 0x1c, 0x24, 0x1d, 0x01, 0x1d, 0x06, 0x1d,\n    0x07, 0x1d, 0x08, 0x1d, 0x1e, 0x1d, 0x1f, 0x1d,\n    0x23, 0x1d, 0x24, 0x1e, 0x06, 0x1e, 0x07, 0x1e,\n    0x08, 0x1e, 0x1f, 0x1e, 0x23, 0x1e, 0x24, 0x1f,\n    0x06, 0x1f, 0x07, 0x1f, 0x08, 0x1f, 0x1f, 0x1f,\n    0x23, 0x1f, 0x24, 0x20, 0x06, 0x20, 0x07, 0x20,\n    0x08, 0x20, 0x1f, 0x20, 0x23, 0x20, 0x24, 0x21,\n    0x06, 0x21, 0x1f, 0x21, 0x23, 0x21, 0x24, 0x24,\n    0x06, 0x24, 0x07, 0x24, 0x08, 0x24, 0x1f, 0x24,\n    0x23, 0x24, 0x24, 0x0a, 0x4a, 0x0b, 0x4a, 0x23,\n    0x4a, 0x20, 0x00, 0x4c, 0x06, 0x51, 0x06, 0x51,\n    0x06, 0xff, 0x00, 0x1f, 0x26, 0x06, 0x00, 0x0b,\n    0x00, 0x0c, 0x00, 0x1f, 0x00, 0x20, 0x00, 0x23,\n    0x00, 0x24, 0x02, 0x0b, 0x02, 0x0c, 0x02, 0x1f,\n    0x02, 0x20, 0x02, 0x23, 0x02, 0x24, 0x04, 0x0b,\n    0x04, 0x0c, 0x04, 0x1f, 0x26, 0x06, 0x04, 0x20,\n    0x04, 0x23, 0x04, 0x24, 0x05, 0x0b, 0x05, 0x0c,\n    0x05, 0x1f, 0x05, 0x20, 0x05, 0x23, 0x05, 0x24,\n    0x1b, 0x23, 0x1b, 0x24, 0x1c, 0x23, 0x1c, 0x24,\n    0x1d, 0x01, 0x1d, 0x1e, 0x1d, 0x1f, 0x1d, 0x23,\n    0x1d, 0x24, 0x1e, 0x1f, 0x1e, 0x23, 0x1e, 0x24,\n    0x1f, 0x01, 0x1f, 0x1f, 0x20, 0x0b, 0x20, 0x0c,\n    0x20, 0x1f, 0x20, 0x20, 0x20, 0x23, 0x20, 0x24,\n    0x23, 0x4a, 0x24, 0x0b, 0x24, 0x0c, 0x24, 0x1f,\n    0x24, 0x20, 0x24, 0x23, 0x24, 0x24, 0x00, 0x06,\n    0x00, 0x07, 0x00, 0x08, 0x00, 0x1f, 0x00, 0x21,\n    0x02, 0x06, 0x02, 0x07, 0x02, 0x08, 0x02, 0x1f,\n    0x02, 0x21, 0x04, 0x06, 0x04, 0x07, 0x04, 0x08,\n    0x04, 0x1f, 0x04, 0x21, 0x05, 0x1f, 0x06, 0x07,\n    0x06, 0x1f, 0x07, 0x06, 0x07, 0x1f, 0x08, 0x06,\n    0x08, 0x1f, 0x0d, 0x06, 0x0d, 0x07, 0x0d, 0x08,\n    0x0d, 0x1f, 0x0f, 0x07, 0x0f, 0x08, 0x0f, 0x1f,\n    0x10, 0x06, 0x10, 0x07, 0x10, 0x08, 0x10, 0x1f,\n    0x11, 0x07, 0x12, 0x1f, 0x13, 0x06, 0x13, 0x1f,\n    0x14, 0x06, 0x14, 0x1f, 0x1b, 0x06, 0x1b, 0x07,\n    0x1b, 0x08, 0x1b, 0x1f, 0x1c, 0x07, 0x1c, 0x1f,\n    0x1d, 0x06, 0x1d, 0x07, 0x1d, 0x08, 0x1d, 0x1e,\n    0x1d, 0x1f, 0x1e, 0x06, 0x1e, 0x07, 0x1e, 0x08,\n    0x1e, 0x1f, 0x1e, 0x21, 0x1f, 0x06, 0x1f, 0x07,\n    0x1f, 0x08, 0x1f, 0x1f, 0x20, 0x06, 0x20, 0x07,\n    0x20, 0x08, 0x20, 0x1f, 0x20, 0x21, 0x21, 0x06,\n    0x21, 0x1f, 0x21, 0x4a, 0x24, 0x06, 0x24, 0x07,\n    0x24, 0x08, 0x24, 0x1f, 0x24, 0x21, 0x00, 0x1f,\n    0x00, 0x21, 0x02, 0x1f, 0x02, 0x21, 0x04, 0x1f,\n    0x04, 0x21, 0x05, 0x1f, 0x05, 0x21, 0x0d, 0x1f,\n    0x0d, 0x21, 0x0e, 0x1f, 0x0e, 0x21, 0x1d, 0x1e,\n    0x1d, 0x1f, 0x1e, 0x1f, 0x20, 0x1f, 0x20, 0x21,\n    0x24, 0x1f, 0x24, 0x21, 0x40, 0x06, 0x4e, 0x06,\n    0x51, 0x06, 0x27, 0x06, 0x10, 0x22, 0x10, 0x23,\n    0x12, 0x22, 0x12, 0x23, 0x13, 0x22, 0x13, 0x23,\n    0x0c, 0x22, 0x0c, 0x23, 0x0d, 0x22, 0x0d, 0x23,\n    0x06, 0x22, 0x06, 0x23, 0x05, 0x22, 0x05, 0x23,\n    0x07, 0x22, 0x07, 0x23, 0x0e, 0x22, 0x0e, 0x23,\n    0x0f, 0x22, 0x0f, 0x23, 0x0d, 0x05, 0x0d, 0x06,\n    0x0d, 0x07, 0x0d, 0x1e, 0x0d, 0x0a, 0x0c, 0x0a,\n    0x0e, 0x0a, 0x0f, 0x0a, 0x10, 0x22, 0x10, 0x23,\n    0x12, 0x22, 0x12, 0x23, 0x13, 0x22, 0x13, 0x23,\n    0x0c, 0x22, 0x0c, 0x23, 0x0d, 0x22, 0x0d, 0x23,\n    0x06, 0x22, 0x06, 0x23, 0x05, 0x22, 0x05, 0x23,\n    0x07, 0x22, 0x07, 0x23, 0x0e, 0x22, 0x0e, 0x23,\n    0x0f, 0x22, 0x0f, 0x23, 0x0d, 0x05, 0x0d, 0x06,\n    0x0d, 0x07, 0x0d, 0x1e, 0x0d, 0x0a, 0x0c, 0x0a,\n    0x0e, 0x0a, 0x0f, 0x0a, 0x0d, 0x05, 0x0d, 0x06,\n    0x0d, 0x07, 0x0d, 0x1e, 0x0c, 0x20, 0x0d, 0x20,\n    0x10, 0x1e, 0x0c, 0x05, 0x0c, 0x06, 0x0c, 0x07,\n    0x0d, 0x05, 0x0d, 0x06, 0x0d, 0x07, 0x10, 0x1e,\n    0x11, 0x1e, 0x00, 0x24, 0x00, 0x24, 0x2a, 0x06,\n    0x00, 0x02, 0x1b, 0x00, 0x03, 0x02, 0x00, 0x03,\n    0x02, 0x00, 0x03, 0x1b, 0x00, 0x04, 0x1b, 0x00,\n    0x1b, 0x02, 0x00, 0x1b, 0x03, 0x00, 0x1b, 0x04,\n    0x02, 0x1b, 0x03, 0x02, 0x1b, 0x03, 0x03, 0x1b,\n    0x20, 0x03, 0x1b, 0x1f, 0x09, 0x03, 0x02, 0x09,\n    0x02, 0x03, 0x09, 0x02, 0x1f, 0x09, 0x1b, 0x03,\n    0x09, 0x1b, 0x03, 0x09, 0x1b, 0x02, 0x09, 0x1b,\n    0x1b, 0x09, 0x1b, 0x1b, 0x0b, 0x03, 0x03, 0x0b,\n    0x03, 0x03, 0x0b, 0x1b, 0x1b, 0x0a, 0x03, 0x1b,\n    0x0a, 0x03, 0x1b, 0x0a, 0x02, 0x20, 0x0a, 0x1b,\n    0x04, 0x0a, 0x1b, 0x04, 0x0a, 0x1b, 0x1b, 0x0a,\n    0x1b, 0x1b, 0x0c, 0x03, 0x1f, 0x0c, 0x04, 0x1b,\n    0x0c, 0x04, 0x1b, 0x0d, 0x1b, 0x03, 0x0d, 0x1b,\n    0x03, 0x0d, 0x1b, 0x1b, 0x0d, 0x1b, 0x20, 0x0f,\n    0x02, 0x1b, 0x0f, 0x1b, 0x1b, 0x0f, 0x1b, 0x1b,\n    0x0f, 0x1b, 0x1f, 0x10, 0x1b, 0x1b, 0x10, 0x1b,\n    0x20, 0x10, 0x1b, 0x1f, 0x17, 0x04, 0x1b, 0x17,\n    0x04, 0x1b, 0x18, 0x1b, 0x03, 0x18, 0x1b, 0x1b,\n    0x1a, 0x03, 0x1b, 0x1a, 0x03, 0x20, 0x1a, 0x03,\n    0x1f, 0x1a, 0x02, 0x02, 0x1a, 0x02, 0x02, 0x1a,\n    0x04, 0x1b, 0x1a, 0x04, 0x1b, 0x1a, 0x1b, 0x03,\n    0x1a, 0x1b, 0x03, 0x1b, 0x03, 0x02, 0x1b, 0x03,\n    0x1b, 0x1b, 0x03, 0x20, 0x1b, 0x02, 0x03, 0x1b,\n    0x02, 0x1b, 0x1b, 0x04, 0x02, 0x1b, 0x04, 0x1b,\n    0x28, 0x06, 0x1d, 0x04, 0x06, 0x1f, 0x1d, 0x04,\n    0x1f, 0x1d, 0x1d, 0x1e, 0x05, 0x1d, 0x1e, 0x05,\n    0x21, 0x1e, 0x04, 0x1d, 0x1e, 0x04, 0x1d, 0x1e,\n    0x04, 0x21, 0x1e, 0x1d, 0x22, 0x1e, 0x1d, 0x21,\n    0x22, 0x1d, 0x1d, 0x22, 0x1d, 0x1d, 0x00, 0x06,\n    0x22, 0x02, 0x04, 0x22, 0x02, 0x04, 0x21, 0x02,\n    0x06, 0x22, 0x02, 0x06, 0x21, 0x02, 0x1d, 0x22,\n    0x02, 0x1d, 0x21, 0x04, 0x1d, 0x22, 0x04, 0x05,\n    0x21, 0x04, 0x1d, 0x21, 0x0b, 0x06, 0x21, 0x0d,\n    0x05, 0x22, 0x0c, 0x05, 0x22, 0x0e, 0x05, 0x22,\n    0x1c, 0x04, 0x22, 0x1c, 0x1d, 0x22, 0x22, 0x05,\n    0x22, 0x22, 0x04, 0x22, 0x22, 0x1d, 0x22, 0x1d,\n    0x1d, 0x22, 0x1a, 0x1d, 0x22, 0x1e, 0x05, 0x22,\n    0x1a, 0x1d, 0x05, 0x1c, 0x05, 0x1d, 0x11, 0x1d,\n    0x22, 0x1b, 0x1d, 0x22, 0x1e, 0x04, 0x05, 0x1d,\n    0x06, 0x22, 0x1c, 0x04, 0x1d, 0x1b, 0x1d, 0x1d,\n    0x1c, 0x04, 0x1d, 0x1e, 0x04, 0x05, 0x04, 0x05,\n    0x22, 0x05, 0x04, 0x22, 0x1d, 0x04, 0x22, 0x19,\n    0x1d, 0x22, 0x00, 0x05, 0x22, 0x1b, 0x1d, 0x1d,\n    0x11, 0x04, 0x1d, 0x0d, 0x1d, 0x1d, 0x0b, 0x06,\n    0x22, 0x1e, 0x04, 0x22, 0x35, 0x06, 0x00, 0x0f,\n    0x9d, 0x0d, 0x0f, 0x9d, 0x27, 0x06, 0x00, 0x1d,\n    0x1d, 0x20, 0x00, 0x1c, 0x01, 0x0a, 0x1e, 0x06,\n    0x1e, 0x08, 0x0e, 0x1d, 0x12, 0x1e, 0x0a, 0x0c,\n    0x21, 0x1d, 0x12, 0x1d, 0x23, 0x20, 0x21, 0x0c,\n    0x1d, 0x1e, 0x35, 0x06, 0x00, 0x0f, 0x14, 0x27,\n    0x06, 0x0e, 0x1d, 0x22, 0xff, 0x00, 0x1d, 0x1d,\n    0x20, 0xff, 0x12, 0x1d, 0x23, 0x20, 0xff, 0x21,\n    0x0c, 0x1d, 0x1e, 0x27, 0x06, 0x05, 0x1d, 0xff,\n    0x05, 0x1d, 0x00, 0x1d, 0x20, 0x27, 0x06, 0x0a,\n    0xa5, 0x00, 0x1d, 0x2c, 0x00, 0x01, 0x30, 0x02,\n    0x30, 0x3a, 0x00, 0x3b, 0x00, 0x21, 0x00, 0x3f,\n    0x00, 0x16, 0x30, 0x17, 0x30, 0x26, 0x20, 0x13,\n    0x20, 0x12, 0x01, 0x00, 0x5f, 0x5f, 0x28, 0x29,\n    0x7b, 0x7d, 0x08, 0x30, 0x0c, 0x0d, 0x08, 0x09,\n    0x02, 0x03, 0x00, 0x01, 0x04, 0x05, 0x06, 0x07,\n    0x5b, 0x00, 0x5d, 0x00, 0x3e, 0x20, 0x3e, 0x20,\n    0x3e, 0x20, 0x3e, 0x20, 0x5f, 0x00, 0x5f, 0x00,\n    0x5f, 0x00, 0x2c, 0x00, 0x01, 0x30, 0x2e, 0x00,\n    0x00, 0x00, 0x3b, 0x00, 0x3a, 0x00, 0x3f, 0x00,\n    0x21, 0x00, 0x14, 0x20, 0x28, 0x00, 0x29, 0x00,\n    0x7b, 0x00, 0x7d, 0x00, 0x14, 0x30, 0x15, 0x30,\n    0x23, 0x26, 0x2a, 0x2b, 0x2d, 0x3c, 0x3e, 0x3d,\n    0x00, 0x5c, 0x24, 0x25, 0x40, 0x40, 0x06, 0xff,\n    0x0b, 0x00, 0x0b, 0xff, 0x0c, 0x20, 0x00, 0x4d,\n    0x06, 0x40, 0x06, 0xff, 0x0e, 0x00, 0x0e, 0xff,\n    0x0f, 0x00, 0x0f, 0xff, 0x10, 0x00, 0x10, 0xff,\n    0x11, 0x00, 0x11, 0xff, 0x12, 0x00, 0x12, 0x21,\n    0x06, 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, 0x03,\n    0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x06, 0x06,\n    0x07, 0x07, 0x07, 0x07, 0x08, 0x08, 0x09, 0x09,\n    0x09, 0x09, 0x0a, 0x0a, 0x0a, 0x0a, 0x0b, 0x0b,\n    0x0b, 0x0b, 0x0c, 0x0c, 0x0c, 0x0c, 0x0d, 0x0d,\n    0x0d, 0x0d, 0x0e, 0x0e, 0x0f, 0x0f, 0x10, 0x10,\n    0x11, 0x11, 0x12, 0x12, 0x12, 0x12, 0x13, 0x13,\n    0x13, 0x13, 0x14, 0x14, 0x14, 0x14, 0x15, 0x15,\n    0x15, 0x15, 0x16, 0x16, 0x16, 0x16, 0x17, 0x17,\n    0x17, 0x17, 0x18, 0x18, 0x18, 0x18, 0x19, 0x19,\n    0x19, 0x19, 0x20, 0x20, 0x20, 0x20, 0x21, 0x21,\n    0x21, 0x21, 0x22, 0x22, 0x22, 0x22, 0x23, 0x23,\n    0x23, 0x23, 0x24, 0x24, 0x24, 0x24, 0x25, 0x25,\n    0x25, 0x25, 0x26, 0x26, 0x26, 0x26, 0x27, 0x27,\n    0x28, 0x28, 0x29, 0x29, 0x29, 0x29, 0x22, 0x06,\n    0x22, 0x00, 0x22, 0x00, 0x22, 0x01, 0x22, 0x01,\n    0x22, 0x03, 0x22, 0x03, 0x22, 0x05, 0x22, 0x05,\n    0x21, 0x00, 0x85, 0x29, 0x01, 0x30, 0x01, 0x0b,\n    0x0c, 0x00, 0xfa, 0xf1, 0xa0, 0xa2, 0xa4, 0xa6,\n    0xa8, 0xe2, 0xe4, 0xe6, 0xc2, 0xfb, 0xa1, 0xa3,\n    0xa5, 0xa7, 0xa9, 0xaa, 0xac, 0xae, 0xb0, 0xb2,\n    0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe, 0xc0, 0xc3,\n    0xc5, 0xc7, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce,\n    0xd1, 0xd4, 0xd7, 0xda, 0xdd, 0xde, 0xdf, 0xe0,\n    0xe1, 0xe3, 0xe5, 0xe7, 0xe8, 0xe9, 0xea, 0xeb,\n    0xec, 0xee, 0xf2, 0x98, 0x99, 0x31, 0x31, 0x4f,\n    0x31, 0x55, 0x31, 0x5b, 0x31, 0x61, 0x31, 0xa2,\n    0x00, 0xa3, 0x00, 0xac, 0x00, 0xaf, 0x00, 0xa6,\n    0x00, 0xa5, 0x00, 0xa9, 0x20, 0x00, 0x00, 0x02,\n    0x25, 0x90, 0x21, 0x91, 0x21, 0x92, 0x21, 0x93,\n    0x21, 0xa0, 0x25, 0xcb, 0x25, 0x99, 0x10, 0xba,\n    0x10, 0x00, 0x00, 0x00, 0x00, 0x9b, 0x10, 0xba,\n    0x10, 0x05, 0x05, 0xa5, 0x10, 0xba, 0x10, 0x05,\n    0x31, 0x11, 0x27, 0x11, 0x32, 0x11, 0x27, 0x11,\n    0x55, 0x47, 0x13, 0x3e, 0x13, 0x47, 0x13, 0x57,\n    0x13, 0x55, 0xb9, 0x14, 0xba, 0x14, 0xb9, 0x14,\n    0xb0, 0x14, 0x00, 0x00, 0x00, 0x00, 0xb9, 0x14,\n    0xbd, 0x14, 0x55, 0x50, 0xb8, 0x15, 0xaf, 0x15,\n    0xb9, 0x15, 0xaf, 0x15, 0x55, 0x35, 0x19, 0x30,\n    0x19, 0x05, 0x57, 0xd1, 0x65, 0xd1, 0x58, 0xd1,\n    0x65, 0xd1, 0x5f, 0xd1, 0x6e, 0xd1, 0x5f, 0xd1,\n    0x6f, 0xd1, 0x5f, 0xd1, 0x70, 0xd1, 0x5f, 0xd1,\n    0x71, 0xd1, 0x5f, 0xd1, 0x72, 0xd1, 0x55, 0x55,\n    0x55, 0x05, 0xb9, 0xd1, 0x65, 0xd1, 0xba, 0xd1,\n    0x65, 0xd1, 0xbb, 0xd1, 0x6e, 0xd1, 0xbc, 0xd1,\n    0x6e, 0xd1, 0xbb, 0xd1, 0x6f, 0xd1, 0xbc, 0xd1,\n    0x6f, 0xd1, 0x55, 0x55, 0x55, 0x41, 0x00, 0x61,\n    0x00, 0x41, 0x00, 0x61, 0x00, 0x69, 0x00, 0x41,\n    0x00, 0x61, 0x00, 0x41, 0x00, 0x43, 0x44, 0x00,\n    0x00, 0x47, 0x00, 0x00, 0x4a, 0x4b, 0x00, 0x00,\n    0x4e, 0x4f, 0x50, 0x51, 0x00, 0x53, 0x54, 0x55,\n    0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63,\n    0x64, 0x00, 0x66, 0x68, 0x00, 0x70, 0x00, 0x41,\n    0x00, 0x61, 0x00, 0x41, 0x42, 0x00, 0x44, 0x45,\n    0x46, 0x47, 0x4a, 0x00, 0x53, 0x00, 0x61, 0x00,\n    0x41, 0x42, 0x00, 0x44, 0x45, 0x46, 0x47, 0x00,\n    0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x00, 0x4f, 0x53,\n    0x00, 0x61, 0x00, 0x41, 0x00, 0x61, 0x00, 0x41,\n    0x00, 0x61, 0x00, 0x41, 0x00, 0x61, 0x00, 0x41,\n    0x00, 0x61, 0x00, 0x41, 0x00, 0x61, 0x00, 0x41,\n    0x00, 0x61, 0x00, 0x31, 0x01, 0x37, 0x02, 0x91,\n    0x03, 0xa3, 0x03, 0xb1, 0x03, 0xd1, 0x03, 0x24,\n    0x00, 0x1f, 0x04, 0x20, 0x05, 0x91, 0x03, 0xa3,\n    0x03, 0xb1, 0x03, 0xd1, 0x03, 0x24, 0x00, 0x1f,\n    0x04, 0x20, 0x05, 0x91, 0x03, 0xa3, 0x03, 0xb1,\n    0x03, 0xd1, 0x03, 0x24, 0x00, 0x1f, 0x04, 0x20,\n    0x05, 0x91, 0x03, 0xa3, 0x03, 0xb1, 0x03, 0xd1,\n    0x03, 0x24, 0x00, 0x1f, 0x04, 0x20, 0x05, 0x91,\n    0x03, 0xa3, 0x03, 0xb1, 0x03, 0xd1, 0x03, 0x24,\n    0x00, 0x1f, 0x04, 0x20, 0x05, 0x0b, 0x0c, 0x30,\n    0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30,\n    0x00, 0x27, 0x06, 0x00, 0x01, 0x05, 0x08, 0x2a,\n    0x06, 0x1e, 0x08, 0x03, 0x0d, 0x20, 0x19, 0x1a,\n    0x1b, 0x1c, 0x09, 0x0f, 0x17, 0x0b, 0x18, 0x07,\n    0x0a, 0x00, 0x01, 0x04, 0x06, 0x0c, 0x0e, 0x10,\n    0x44, 0x90, 0x77, 0x45, 0x28, 0x06, 0x2c, 0x06,\n    0x00, 0x00, 0x47, 0x06, 0x33, 0x06, 0x17, 0x10,\n    0x11, 0x12, 0x13, 0x00, 0x06, 0x0e, 0x02, 0x0f,\n    0x34, 0x06, 0x2a, 0x06, 0x2b, 0x06, 0x2e, 0x06,\n    0x00, 0x00, 0x36, 0x06, 0x00, 0x00, 0x3a, 0x06,\n    0x2d, 0x06, 0x00, 0x00, 0x4a, 0x06, 0x00, 0x00,\n    0x44, 0x06, 0x00, 0x00, 0x46, 0x06, 0x33, 0x06,\n    0x39, 0x06, 0x00, 0x00, 0x35, 0x06, 0x42, 0x06,\n    0x00, 0x00, 0x34, 0x06, 0x00, 0x00, 0x00, 0x00,\n    0x2e, 0x06, 0x00, 0x00, 0x36, 0x06, 0x00, 0x00,\n    0x3a, 0x06, 0x00, 0x00, 0xba, 0x06, 0x00, 0x00,\n    0x6f, 0x06, 0x00, 0x00, 0x28, 0x06, 0x2c, 0x06,\n    0x00, 0x00, 0x47, 0x06, 0x00, 0x00, 0x00, 0x00,\n    0x2d, 0x06, 0x37, 0x06, 0x4a, 0x06, 0x43, 0x06,\n    0x00, 0x00, 0x45, 0x06, 0x46, 0x06, 0x33, 0x06,\n    0x39, 0x06, 0x41, 0x06, 0x35, 0x06, 0x42, 0x06,\n    0x00, 0x00, 0x34, 0x06, 0x2a, 0x06, 0x2b, 0x06,\n    0x2e, 0x06, 0x00, 0x00, 0x36, 0x06, 0x38, 0x06,\n    0x3a, 0x06, 0x6e, 0x06, 0x00, 0x00, 0xa1, 0x06,\n    0x27, 0x06, 0x00, 0x01, 0x05, 0x08, 0x20, 0x21,\n    0x0b, 0x06, 0x10, 0x23, 0x2a, 0x06, 0x1a, 0x1b,\n    0x1c, 0x09, 0x0f, 0x17, 0x0b, 0x18, 0x07, 0x0a,\n    0x00, 0x01, 0x04, 0x06, 0x0c, 0x0e, 0x10, 0x28,\n    0x06, 0x2c, 0x06, 0x2f, 0x06, 0x00, 0x00, 0x48,\n    0x06, 0x32, 0x06, 0x2d, 0x06, 0x37, 0x06, 0x4a,\n    0x06, 0x2a, 0x06, 0x1a, 0x1b, 0x1c, 0x09, 0x0f,\n    0x17, 0x0b, 0x18, 0x07, 0x0a, 0x00, 0x01, 0x04,\n    0x06, 0x0c, 0x0e, 0x10, 0x30, 0x2e, 0x30, 0x00,\n    0x2c, 0x00, 0x28, 0x00, 0x41, 0x00, 0x29, 0x00,\n    0x14, 0x30, 0x53, 0x00, 0x15, 0x30, 0x43, 0x52,\n    0x43, 0x44, 0x57, 0x5a, 0x41, 0x00, 0x48, 0x56,\n    0x4d, 0x56, 0x53, 0x44, 0x53, 0x53, 0x50, 0x50,\n    0x56, 0x57, 0x43, 0x4d, 0x43, 0x4d, 0x44, 0x4d,\n    0x52, 0x44, 0x4a, 0x4b, 0x30, 0x30, 0x00, 0x68,\n    0x68, 0x4b, 0x62, 0x57, 0x5b, 0xcc, 0x53, 0xc7,\n    0x30, 0x8c, 0x4e, 0x1a, 0x59, 0xe3, 0x89, 0x29,\n    0x59, 0xa4, 0x4e, 0x20, 0x66, 0x21, 0x71, 0x99,\n    0x65, 0x4d, 0x52, 0x8c, 0x5f, 0x8d, 0x51, 0xb0,\n    0x65, 0x1d, 0x52, 0x42, 0x7d, 0x1f, 0x75, 0xa9,\n    0x8c, 0xf0, 0x58, 0x39, 0x54, 0x14, 0x6f, 0x95,\n    0x62, 0x55, 0x63, 0x00, 0x4e, 0x09, 0x4e, 0x4a,\n    0x90, 0xe6, 0x5d, 0x2d, 0x4e, 0xf3, 0x53, 0x07,\n    0x63, 0x70, 0x8d, 0x53, 0x62, 0x81, 0x79, 0x7a,\n    0x7a, 0x08, 0x54, 0x80, 0x6e, 0x09, 0x67, 0x08,\n    0x67, 0x33, 0x75, 0x72, 0x52, 0xb6, 0x55, 0x4d,\n    0x91, 0x14, 0x30, 0x15, 0x30, 0x2c, 0x67, 0x09,\n    0x4e, 0x8c, 0x4e, 0x89, 0x5b, 0xb9, 0x70, 0x53,\n    0x62, 0xd7, 0x76, 0xdd, 0x52, 0x57, 0x65, 0x97,\n    0x5f, 0xef, 0x53, 0x30, 0x00, 0x38, 0x4e, 0x05,\n    0x00, 0x09, 0x22, 0x01, 0x60, 0x4f, 0xae, 0x4f,\n    0xbb, 0x4f, 0x02, 0x50, 0x7a, 0x50, 0x99, 0x50,\n    0xe7, 0x50, 0xcf, 0x50, 0x9e, 0x34, 0x3a, 0x06,\n    0x4d, 0x51, 0x54, 0x51, 0x64, 0x51, 0x77, 0x51,\n    0x1c, 0x05, 0xb9, 0x34, 0x67, 0x51, 0x8d, 0x51,\n    0x4b, 0x05, 0x97, 0x51, 0xa4, 0x51, 0xcc, 0x4e,\n    0xac, 0x51, 0xb5, 0x51, 0xdf, 0x91, 0xf5, 0x51,\n    0x03, 0x52, 0xdf, 0x34, 0x3b, 0x52, 0x46, 0x52,\n    0x72, 0x52, 0x77, 0x52, 0x15, 0x35, 0x02, 0x00,\n    0x20, 0x80, 0x80, 0x00, 0x08, 0x00, 0x00, 0xc7,\n    0x52, 0x00, 0x02, 0x1d, 0x33, 0x3e, 0x3f, 0x50,\n    0x82, 0x8a, 0x93, 0xac, 0xb6, 0xb8, 0xb8, 0xb8,\n    0x2c, 0x0a, 0x70, 0x70, 0xca, 0x53, 0xdf, 0x53,\n    0x63, 0x0b, 0xeb, 0x53, 0xf1, 0x53, 0x06, 0x54,\n    0x9e, 0x54, 0x38, 0x54, 0x48, 0x54, 0x68, 0x54,\n    0xa2, 0x54, 0xf6, 0x54, 0x10, 0x55, 0x53, 0x55,\n    0x63, 0x55, 0x84, 0x55, 0x84, 0x55, 0x99, 0x55,\n    0xab, 0x55, 0xb3, 0x55, 0xc2, 0x55, 0x16, 0x57,\n    0x06, 0x56, 0x17, 0x57, 0x51, 0x56, 0x74, 0x56,\n    0x07, 0x52, 0xee, 0x58, 0xce, 0x57, 0xf4, 0x57,\n    0x0d, 0x58, 0x8b, 0x57, 0x32, 0x58, 0x31, 0x58,\n    0xac, 0x58, 0xe4, 0x14, 0xf2, 0x58, 0xf7, 0x58,\n    0x06, 0x59, 0x1a, 0x59, 0x22, 0x59, 0x62, 0x59,\n    0xa8, 0x16, 0xea, 0x16, 0xec, 0x59, 0x1b, 0x5a,\n    0x27, 0x5a, 0xd8, 0x59, 0x66, 0x5a, 0xee, 0x36,\n    0xfc, 0x36, 0x08, 0x5b, 0x3e, 0x5b, 0x3e, 0x5b,\n    0xc8, 0x19, 0xc3, 0x5b, 0xd8, 0x5b, 0xe7, 0x5b,\n    0xf3, 0x5b, 0x18, 0x1b, 0xff, 0x5b, 0x06, 0x5c,\n    0x53, 0x5f, 0x22, 0x5c, 0x81, 0x37, 0x60, 0x5c,\n    0x6e, 0x5c, 0xc0, 0x5c, 0x8d, 0x5c, 0xe4, 0x1d,\n    0x43, 0x5d, 0xe6, 0x1d, 0x6e, 0x5d, 0x6b, 0x5d,\n    0x7c, 0x5d, 0xe1, 0x5d, 0xe2, 0x5d, 0x2f, 0x38,\n    0xfd, 0x5d, 0x28, 0x5e, 0x3d, 0x5e, 0x69, 0x5e,\n    0x62, 0x38, 0x83, 0x21, 0x7c, 0x38, 0xb0, 0x5e,\n    0xb3, 0x5e, 0xb6, 0x5e, 0xca, 0x5e, 0x92, 0xa3,\n    0xfe, 0x5e, 0x31, 0x23, 0x31, 0x23, 0x01, 0x82,\n    0x22, 0x5f, 0x22, 0x5f, 0xc7, 0x38, 0xb8, 0x32,\n    0xda, 0x61, 0x62, 0x5f, 0x6b, 0x5f, 0xe3, 0x38,\n    0x9a, 0x5f, 0xcd, 0x5f, 0xd7, 0x5f, 0xf9, 0x5f,\n    0x81, 0x60, 0x3a, 0x39, 0x1c, 0x39, 0x94, 0x60,\n    0xd4, 0x26, 0xc7, 0x60, 0x02, 0x02, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0a,\n    0x00, 0x00, 0x02, 0x08, 0x00, 0x80, 0x08, 0x00,\n    0x00, 0x08, 0x80, 0x28, 0x80, 0x02, 0x00, 0x00,\n    0x02, 0x48, 0x61, 0x00, 0x04, 0x06, 0x04, 0x32,\n    0x46, 0x6a, 0x5c, 0x67, 0x96, 0xaa, 0xae, 0xc8,\n    0xd3, 0x5d, 0x62, 0x00, 0x54, 0x77, 0xf3, 0x0c,\n    0x2b, 0x3d, 0x63, 0xfc, 0x62, 0x68, 0x63, 0x83,\n    0x63, 0xe4, 0x63, 0xf1, 0x2b, 0x22, 0x64, 0xc5,\n    0x63, 0xa9, 0x63, 0x2e, 0x3a, 0x69, 0x64, 0x7e,\n    0x64, 0x9d, 0x64, 0x77, 0x64, 0x6c, 0x3a, 0x4f,\n    0x65, 0x6c, 0x65, 0x0a, 0x30, 0xe3, 0x65, 0xf8,\n    0x66, 0x49, 0x66, 0x19, 0x3b, 0x91, 0x66, 0x08,\n    0x3b, 0xe4, 0x3a, 0x92, 0x51, 0x95, 0x51, 0x00,\n    0x67, 0x9c, 0x66, 0xad, 0x80, 0xd9, 0x43, 0x17,\n    0x67, 0x1b, 0x67, 0x21, 0x67, 0x5e, 0x67, 0x53,\n    0x67, 0xc3, 0x33, 0x49, 0x3b, 0xfa, 0x67, 0x85,\n    0x67, 0x52, 0x68, 0x85, 0x68, 0x6d, 0x34, 0x8e,\n    0x68, 0x1f, 0x68, 0x14, 0x69, 0x9d, 0x3b, 0x42,\n    0x69, 0xa3, 0x69, 0xea, 0x69, 0xa8, 0x6a, 0xa3,\n    0x36, 0xdb, 0x6a, 0x18, 0x3c, 0x21, 0x6b, 0xa7,\n    0x38, 0x54, 0x6b, 0x4e, 0x3c, 0x72, 0x6b, 0x9f,\n    0x6b, 0xba, 0x6b, 0xbb, 0x6b, 0x8d, 0x3a, 0x0b,\n    0x1d, 0xfa, 0x3a, 0x4e, 0x6c, 0xbc, 0x3c, 0xbf,\n    0x6c, 0xcd, 0x6c, 0x67, 0x6c, 0x16, 0x6d, 0x3e,\n    0x6d, 0x77, 0x6d, 0x41, 0x6d, 0x69, 0x6d, 0x78,\n    0x6d, 0x85, 0x6d, 0x1e, 0x3d, 0x34, 0x6d, 0x2f,\n    0x6e, 0x6e, 0x6e, 0x33, 0x3d, 0xcb, 0x6e, 0xc7,\n    0x6e, 0xd1, 0x3e, 0xf9, 0x6d, 0x6e, 0x6f, 0x5e,\n    0x3f, 0x8e, 0x3f, 0xc6, 0x6f, 0x39, 0x70, 0x1e,\n    0x70, 0x1b, 0x70, 0x96, 0x3d, 0x4a, 0x70, 0x7d,\n    0x70, 0x77, 0x70, 0xad, 0x70, 0x25, 0x05, 0x45,\n    0x71, 0x63, 0x42, 0x9c, 0x71, 0xab, 0x43, 0x28,\n    0x72, 0x35, 0x72, 0x50, 0x72, 0x08, 0x46, 0x80,\n    0x72, 0x95, 0x72, 0x35, 0x47, 0x02, 0x20, 0x00,\n    0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x08, 0x80,\n    0x00, 0x00, 0x02, 0x02, 0x80, 0x8a, 0x00, 0x00,\n    0x20, 0x00, 0x08, 0x0a, 0x00, 0x80, 0x88, 0x80,\n    0x20, 0x14, 0x48, 0x7a, 0x73, 0x8b, 0x73, 0xac,\n    0x3e, 0xa5, 0x73, 0xb8, 0x3e, 0xb8, 0x3e, 0x47,\n    0x74, 0x5c, 0x74, 0x71, 0x74, 0x85, 0x74, 0xca,\n    0x74, 0x1b, 0x3f, 0x24, 0x75, 0x36, 0x4c, 0x3e,\n    0x75, 0x92, 0x4c, 0x70, 0x75, 0x9f, 0x21, 0x10,\n    0x76, 0xa1, 0x4f, 0xb8, 0x4f, 0x44, 0x50, 0xfc,\n    0x3f, 0x08, 0x40, 0xf4, 0x76, 0xf3, 0x50, 0xf2,\n    0x50, 0x19, 0x51, 0x33, 0x51, 0x1e, 0x77, 0x1f,\n    0x77, 0x1f, 0x77, 0x4a, 0x77, 0x39, 0x40, 0x8b,\n    0x77, 0x46, 0x40, 0x96, 0x40, 0x1d, 0x54, 0x4e,\n    0x78, 0x8c, 0x78, 0xcc, 0x78, 0xe3, 0x40, 0x26,\n    0x56, 0x56, 0x79, 0x9a, 0x56, 0xc5, 0x56, 0x8f,\n    0x79, 0xeb, 0x79, 0x2f, 0x41, 0x40, 0x7a, 0x4a,\n    0x7a, 0x4f, 0x7a, 0x7c, 0x59, 0xa7, 0x5a, 0xa7,\n    0x5a, 0xee, 0x7a, 0x02, 0x42, 0xab, 0x5b, 0xc6,\n    0x7b, 0xc9, 0x7b, 0x27, 0x42, 0x80, 0x5c, 0xd2,\n    0x7c, 0xa0, 0x42, 0xe8, 0x7c, 0xe3, 0x7c, 0x00,\n    0x7d, 0x86, 0x5f, 0x63, 0x7d, 0x01, 0x43, 0xc7,\n    0x7d, 0x02, 0x7e, 0x45, 0x7e, 0x34, 0x43, 0x28,\n    0x62, 0x47, 0x62, 0x59, 0x43, 0xd9, 0x62, 0x7a,\n    0x7f, 0x3e, 0x63, 0x95, 0x7f, 0xfa, 0x7f, 0x05,\n    0x80, 0xda, 0x64, 0x23, 0x65, 0x60, 0x80, 0xa8,\n    0x65, 0x70, 0x80, 0x5f, 0x33, 0xd5, 0x43, 0xb2,\n    0x80, 0x03, 0x81, 0x0b, 0x44, 0x3e, 0x81, 0xb5,\n    0x5a, 0xa7, 0x67, 0xb5, 0x67, 0x93, 0x33, 0x9c,\n    0x33, 0x01, 0x82, 0x04, 0x82, 0x9e, 0x8f, 0x6b,\n    0x44, 0x91, 0x82, 0x8b, 0x82, 0x9d, 0x82, 0xb3,\n    0x52, 0xb1, 0x82, 0xb3, 0x82, 0xbd, 0x82, 0xe6,\n    0x82, 0x3c, 0x6b, 0xe5, 0x82, 0x1d, 0x83, 0x63,\n    0x83, 0xad, 0x83, 0x23, 0x83, 0xbd, 0x83, 0xe7,\n    0x83, 0x57, 0x84, 0x53, 0x83, 0xca, 0x83, 0xcc,\n    0x83, 0xdc, 0x83, 0x36, 0x6c, 0x6b, 0x6d, 0x02,\n    0x00, 0x00, 0x20, 0x22, 0x2a, 0xa0, 0x0a, 0x00,\n    0x20, 0x80, 0x28, 0x00, 0xa8, 0x20, 0x20, 0x00,\n    0x02, 0x80, 0x22, 0x02, 0x8a, 0x08, 0x00, 0xaa,\n    0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x28, 0xd5,\n    0x6c, 0x2b, 0x45, 0xf1, 0x84, 0xf3, 0x84, 0x16,\n    0x85, 0xca, 0x73, 0x64, 0x85, 0x2c, 0x6f, 0x5d,\n    0x45, 0x61, 0x45, 0xb1, 0x6f, 0xd2, 0x70, 0x6b,\n    0x45, 0x50, 0x86, 0x5c, 0x86, 0x67, 0x86, 0x69,\n    0x86, 0xa9, 0x86, 0x88, 0x86, 0x0e, 0x87, 0xe2,\n    0x86, 0x79, 0x87, 0x28, 0x87, 0x6b, 0x87, 0x86,\n    0x87, 0xd7, 0x45, 0xe1, 0x87, 0x01, 0x88, 0xf9,\n    0x45, 0x60, 0x88, 0x63, 0x88, 0x67, 0x76, 0xd7,\n    0x88, 0xde, 0x88, 0x35, 0x46, 0xfa, 0x88, 0xbb,\n    0x34, 0xae, 0x78, 0x66, 0x79, 0xbe, 0x46, 0xc7,\n    0x46, 0xa0, 0x8a, 0xed, 0x8a, 0x8a, 0x8b, 0x55,\n    0x8c, 0xa8, 0x7c, 0xab, 0x8c, 0xc1, 0x8c, 0x1b,\n    0x8d, 0x77, 0x8d, 0x2f, 0x7f, 0x04, 0x08, 0xcb,\n    0x8d, 0xbc, 0x8d, 0xf0, 0x8d, 0xde, 0x08, 0xd4,\n    0x8e, 0x38, 0x8f, 0xd2, 0x85, 0xed, 0x85, 0x94,\n    0x90, 0xf1, 0x90, 0x11, 0x91, 0x2e, 0x87, 0x1b,\n    0x91, 0x38, 0x92, 0xd7, 0x92, 0xd8, 0x92, 0x7c,\n    0x92, 0xf9, 0x93, 0x15, 0x94, 0xfa, 0x8b, 0x8b,\n    0x95, 0x95, 0x49, 0xb7, 0x95, 0x77, 0x8d, 0xe6,\n    0x49, 0xc3, 0x96, 0xb2, 0x5d, 0x23, 0x97, 0x45,\n    0x91, 0x1a, 0x92, 0x6e, 0x4a, 0x76, 0x4a, 0xe0,\n    0x97, 0x0a, 0x94, 0xb2, 0x4a, 0x96, 0x94, 0x0b,\n    0x98, 0x0b, 0x98, 0x29, 0x98, 0xb6, 0x95, 0xe2,\n    0x98, 0x33, 0x4b, 0x29, 0x99, 0xa7, 0x99, 0xc2,\n    0x99, 0xfe, 0x99, 0xce, 0x4b, 0x30, 0x9b, 0x12,\n    0x9b, 0x40, 0x9c, 0xfd, 0x9c, 0xce, 0x4c, 0xed,\n    0x4c, 0x67, 0x9d, 0xce, 0xa0, 0xf8, 0x4c, 0x05,\n    0xa1, 0x0e, 0xa2, 0x91, 0xa2, 0xbb, 0x9e, 0x56,\n    0x4d, 0xf9, 0x9e, 0xfe, 0x9e, 0x05, 0x9f, 0x0f,\n    0x9f, 0x16, 0x9f, 0x3b, 0x9f, 0x00, 0xa6, 0x02,\n    0x88, 0xa0, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00,\n    0x28, 0x00, 0x08, 0xa0, 0x80, 0xa0, 0x80, 0x00,\n    0x80, 0x80, 0x00, 0x0a, 0x88, 0x80, 0x00, 0x80,\n    0x00, 0x20, 0x2a, 0x00, 0x80,\n};\n\nstatic const uint16_t unicode_comp_table[945] = {\n    0x4a01, 0x49c0, 0x4a02, 0x0280, 0x0281, 0x0282, 0x0283, 0x02c0,\n    0x02c2, 0x0a00, 0x0284, 0x2442, 0x0285, 0x07c0, 0x0980, 0x0982,\n    0x2440, 0x2280, 0x02c4, 0x2282, 0x2284, 0x2286, 0x02c6, 0x02c8,\n    0x02ca, 0x02cc, 0x0287, 0x228a, 0x02ce, 0x228c, 0x2290, 0x2292,\n    0x228e, 0x0288, 0x0289, 0x028a, 0x2482, 0x0300, 0x0302, 0x0304,\n    0x028b, 0x2480, 0x0308, 0x0984, 0x0986, 0x2458, 0x0a02, 0x0306,\n    0x2298, 0x229a, 0x229e, 0x0900, 0x030a, 0x22a0, 0x030c, 0x030e,\n    0x0840, 0x0310, 0x0312, 0x22a2, 0x22a6, 0x09c0, 0x22a4, 0x22a8,\n    0x22aa, 0x028c, 0x028d, 0x028e, 0x0340, 0x0342, 0x0344, 0x0380,\n    0x028f, 0x248e, 0x07c2, 0x0988, 0x098a, 0x2490, 0x0346, 0x22ac,\n    0x0400, 0x22b0, 0x0842, 0x22b2, 0x0402, 0x22b4, 0x0440, 0x0444,\n    0x22b6, 0x0442, 0x22c2, 0x22c0, 0x22c4, 0x22c6, 0x22c8, 0x0940,\n    0x04c0, 0x0291, 0x22ca, 0x04c4, 0x22cc, 0x04c2, 0x22d0, 0x22ce,\n    0x0292, 0x0293, 0x0294, 0x0295, 0x0540, 0x0542, 0x0a08, 0x0296,\n    0x2494, 0x0544, 0x07c4, 0x098c, 0x098e, 0x06c0, 0x2492, 0x0844,\n    0x2308, 0x230a, 0x0580, 0x230c, 0x0584, 0x0990, 0x0992, 0x230e,\n    0x0582, 0x2312, 0x0586, 0x0588, 0x2314, 0x058c, 0x2316, 0x0998,\n    0x058a, 0x231e, 0x0590, 0x2320, 0x099a, 0x058e, 0x2324, 0x2322,\n    0x0299, 0x029a, 0x029b, 0x05c0, 0x05c2, 0x05c4, 0x029c, 0x24ac,\n    0x05c6, 0x05c8, 0x07c6, 0x0994, 0x0996, 0x0700, 0x24aa, 0x2326,\n    0x05ca, 0x232a, 0x2328, 0x2340, 0x2342, 0x2344, 0x2346, 0x05cc,\n    0x234a, 0x2348, 0x234c, 0x234e, 0x2350, 0x24b8, 0x029d, 0x05ce,\n    0x24be, 0x0a0c, 0x2352, 0x0600, 0x24bc, 0x24ba, 0x0640, 0x2354,\n    0x0642, 0x0644, 0x2356, 0x2358, 0x02a0, 0x02a1, 0x02a2, 0x02a3,\n    0x02c1, 0x02c3, 0x0a01, 0x02a4, 0x2443, 0x02a5, 0x07c1, 0x0981,\n    0x0983, 0x2441, 0x2281, 0x02c5, 0x2283, 0x2285, 0x2287, 0x02c7,\n    0x02c9, 0x02cb, 0x02cd, 0x02a7, 0x228b, 0x02cf, 0x228d, 0x2291,\n    0x2293, 0x228f, 0x02a8, 0x02a9, 0x02aa, 0x2483, 0x0301, 0x0303,\n    0x0305, 0x02ab, 0x2481, 0x0309, 0x0985, 0x0987, 0x2459, 0x0a03,\n    0x0307, 0x2299, 0x229b, 0x229f, 0x0901, 0x030b, 0x22a1, 0x030d,\n    0x030f, 0x0841, 0x0311, 0x0313, 0x22a3, 0x22a7, 0x09c1, 0x22a5,\n    0x22a9, 0x22ab, 0x2380, 0x02ac, 0x02ad, 0x02ae, 0x0341, 0x0343,\n    0x0345, 0x02af, 0x248f, 0x07c3, 0x0989, 0x098b, 0x2491, 0x0347,\n    0x22ad, 0x0401, 0x0884, 0x22b1, 0x0843, 0x22b3, 0x0403, 0x22b5,\n    0x0441, 0x0445, 0x22b7, 0x0443, 0x22c3, 0x22c1, 0x22c5, 0x22c7,\n    0x22c9, 0x0941, 0x04c1, 0x02b1, 0x22cb, 0x04c5, 0x22cd, 0x04c3,\n    0x22d1, 0x22cf, 0x02b2, 0x02b3, 0x02b4, 0x02b5, 0x0541, 0x0543,\n    0x0a09, 0x02b6, 0x2495, 0x0545, 0x07c5, 0x098d, 0x098f, 0x06c1,\n    0x2493, 0x0845, 0x2309, 0x230b, 0x0581, 0x230d, 0x0585, 0x0991,\n    0x0993, 0x230f, 0x0583, 0x2313, 0x0587, 0x0589, 0x2315, 0x058d,\n    0x2317, 0x0999, 0x058b, 0x231f, 0x2381, 0x0591, 0x2321, 0x099b,\n    0x058f, 0x2325, 0x2323, 0x02b9, 0x02ba, 0x02bb, 0x05c1, 0x05c3,\n    0x05c5, 0x02bc, 0x24ad, 0x05c7, 0x05c9, 0x07c7, 0x0995, 0x0997,\n    0x0701, 0x24ab, 0x2327, 0x05cb, 0x232b, 0x2329, 0x2341, 0x2343,\n    0x2345, 0x2347, 0x05cd, 0x234b, 0x2349, 0x2382, 0x234d, 0x234f,\n    0x2351, 0x24b9, 0x02bd, 0x05cf, 0x24bf, 0x0a0d, 0x2353, 0x02bf,\n    0x24bd, 0x2383, 0x24bb, 0x0641, 0x2355, 0x0643, 0x0645, 0x2357,\n    0x2359, 0x3101, 0x0c80, 0x2e00, 0x2446, 0x2444, 0x244a, 0x2448,\n    0x0800, 0x0942, 0x0944, 0x0804, 0x2288, 0x2486, 0x2484, 0x248a,\n    0x2488, 0x22ae, 0x2498, 0x2496, 0x249c, 0x249a, 0x2300, 0x0a06,\n    0x2302, 0x0a04, 0x0946, 0x07ce, 0x07ca, 0x07c8, 0x07cc, 0x2447,\n    0x2445, 0x244b, 0x2449, 0x0801, 0x0943, 0x0945, 0x0805, 0x2289,\n    0x2487, 0x2485, 0x248b, 0x2489, 0x22af, 0x2499, 0x2497, 0x249d,\n    0x249b, 0x2301, 0x0a07, 0x2303, 0x0a05, 0x0947, 0x07cf, 0x07cb,\n    0x07c9, 0x07cd, 0x2450, 0x244e, 0x2454, 0x2452, 0x2451, 0x244f,\n    0x2455, 0x2453, 0x2294, 0x2296, 0x2295, 0x2297, 0x2304, 0x2306,\n    0x2305, 0x2307, 0x2318, 0x2319, 0x231a, 0x231b, 0x232c, 0x232d,\n    0x232e, 0x232f, 0x2400, 0x24a2, 0x24a0, 0x24a6, 0x24a4, 0x24a8,\n    0x24a3, 0x24a1, 0x24a7, 0x24a5, 0x24a9, 0x24b0, 0x24ae, 0x24b4,\n    0x24b2, 0x24b6, 0x24b1, 0x24af, 0x24b5, 0x24b3, 0x24b7, 0x0882,\n    0x0880, 0x0881, 0x0802, 0x0803, 0x229c, 0x229d, 0x0a0a, 0x0a0b,\n    0x0883, 0x0b40, 0x2c8a, 0x0c81, 0x2c89, 0x2c88, 0x2540, 0x2541,\n    0x2d00, 0x2e07, 0x0d00, 0x2640, 0x2641, 0x2e80, 0x0d01, 0x26c8,\n    0x26c9, 0x2f00, 0x2f84, 0x0d02, 0x2f83, 0x2f82, 0x0d40, 0x26d8,\n    0x26d9, 0x3186, 0x0d04, 0x2740, 0x2741, 0x3100, 0x3086, 0x0d06,\n    0x3085, 0x3084, 0x0d41, 0x2840, 0x3200, 0x0d07, 0x284f, 0x2850,\n    0x3280, 0x2c84, 0x2e03, 0x2857, 0x0d42, 0x2c81, 0x2c80, 0x24c0,\n    0x24c1, 0x2c86, 0x2c83, 0x28c0, 0x0d43, 0x25c0, 0x25c1, 0x2940,\n    0x0d44, 0x26c0, 0x26c1, 0x2e05, 0x2e02, 0x29c0, 0x0d45, 0x2f05,\n    0x2f04, 0x0d80, 0x26d0, 0x26d1, 0x2f80, 0x2a40, 0x0d82, 0x26e0,\n    0x26e1, 0x3080, 0x3081, 0x2ac0, 0x0d83, 0x3004, 0x3003, 0x0d81,\n    0x27c0, 0x27c1, 0x3082, 0x2b40, 0x0d84, 0x2847, 0x2848, 0x3184,\n    0x3181, 0x2f06, 0x0d08, 0x2f81, 0x3005, 0x0d46, 0x3083, 0x3182,\n    0x0e00, 0x0e01, 0x0f40, 0x1180, 0x1182, 0x0f03, 0x0f00, 0x11c0,\n    0x0f01, 0x1140, 0x1202, 0x1204, 0x0f81, 0x1240, 0x0fc0, 0x1242,\n    0x0f80, 0x1244, 0x1284, 0x0f82, 0x1286, 0x1288, 0x128a, 0x12c0,\n    0x1282, 0x1181, 0x1183, 0x1043, 0x1040, 0x11c1, 0x1041, 0x1141,\n    0x1203, 0x1205, 0x10c1, 0x1241, 0x1000, 0x1243, 0x10c0, 0x1245,\n    0x1285, 0x10c2, 0x1287, 0x1289, 0x128b, 0x12c1, 0x1283, 0x1080,\n    0x1100, 0x1101, 0x1200, 0x1201, 0x1280, 0x1281, 0x1340, 0x1341,\n    0x1343, 0x1342, 0x1344, 0x13c2, 0x1400, 0x13c0, 0x1440, 0x1480,\n    0x14c0, 0x1540, 0x1541, 0x1740, 0x1700, 0x1741, 0x17c0, 0x1800,\n    0x1802, 0x1801, 0x1840, 0x1880, 0x1900, 0x18c0, 0x18c1, 0x1901,\n    0x1940, 0x1942, 0x1941, 0x1980, 0x19c0, 0x19c2, 0x19c1, 0x1c80,\n    0x1cc0, 0x1dc0, 0x1f80, 0x2000, 0x2002, 0x2004, 0x2006, 0x2008,\n    0x2040, 0x2080, 0x2082, 0x20c0, 0x20c1, 0x2100, 0x22b8, 0x22b9,\n    0x2310, 0x2311, 0x231c, 0x231d, 0x244c, 0x2456, 0x244d, 0x2457,\n    0x248c, 0x248d, 0x249e, 0x249f, 0x2500, 0x2502, 0x2504, 0x2bc0,\n    0x2501, 0x2503, 0x2505, 0x2bc1, 0x2bc2, 0x2bc3, 0x2bc4, 0x2bc5,\n    0x2bc6, 0x2bc7, 0x2580, 0x2582, 0x2584, 0x2bc8, 0x2581, 0x2583,\n    0x2585, 0x2bc9, 0x2bca, 0x2bcb, 0x2bcc, 0x2bcd, 0x2bce, 0x2bcf,\n    0x2600, 0x2602, 0x2601, 0x2603, 0x2680, 0x2682, 0x2681, 0x2683,\n    0x26c2, 0x26c4, 0x26c6, 0x2c00, 0x26c3, 0x26c5, 0x26c7, 0x2c01,\n    0x2c02, 0x2c03, 0x2c04, 0x2c05, 0x2c06, 0x2c07, 0x26ca, 0x26cc,\n    0x26ce, 0x2c08, 0x26cb, 0x26cd, 0x26cf, 0x2c09, 0x2c0a, 0x2c0b,\n    0x2c0c, 0x2c0d, 0x2c0e, 0x2c0f, 0x26d2, 0x26d4, 0x26d6, 0x26d3,\n    0x26d5, 0x26d7, 0x26da, 0x26dc, 0x26de, 0x26db, 0x26dd, 0x26df,\n    0x2700, 0x2702, 0x2701, 0x2703, 0x2780, 0x2782, 0x2781, 0x2783,\n    0x2800, 0x2802, 0x2804, 0x2801, 0x2803, 0x2805, 0x2842, 0x2844,\n    0x2846, 0x2849, 0x284b, 0x284d, 0x2c40, 0x284a, 0x284c, 0x284e,\n    0x2c41, 0x2c42, 0x2c43, 0x2c44, 0x2c45, 0x2c46, 0x2c47, 0x2851,\n    0x2853, 0x2855, 0x2c48, 0x2852, 0x2854, 0x2856, 0x2c49, 0x2c4a,\n    0x2c4b, 0x2c4c, 0x2c4d, 0x2c4e, 0x2c4f, 0x2c82, 0x2e01, 0x3180,\n    0x2c87, 0x2f01, 0x2f02, 0x2f03, 0x2e06, 0x3185, 0x3000, 0x3001,\n    0x3002, 0x4640, 0x4641, 0x4680, 0x46c0, 0x46c2, 0x46c1, 0x4700,\n    0x4740, 0x4780, 0x47c0, 0x47c2, 0x4900, 0x4940, 0x4980, 0x4982,\n    0x4a00, 0x49c2, 0x4a03, 0x4a04, 0x4a40, 0x4a41, 0x4a80, 0x4a81,\n    0x4ac0, 0x4ac1, 0x4bc0, 0x4bc1, 0x4b00, 0x4b01, 0x4b40, 0x4b41,\n    0x4bc2, 0x4bc3, 0x4b80, 0x4b81, 0x4b82, 0x4b83, 0x4c00, 0x4c01,\n    0x4c02, 0x4c03, 0x5600, 0x5440, 0x5442, 0x5444, 0x5446, 0x5448,\n    0x544a, 0x544c, 0x544e, 0x5450, 0x5452, 0x5454, 0x5456, 0x5480,\n    0x5482, 0x5484, 0x54c0, 0x54c1, 0x5500, 0x5501, 0x5540, 0x5541,\n    0x5580, 0x5581, 0x55c0, 0x55c1, 0x5680, 0x58c0, 0x5700, 0x5702,\n    0x5704, 0x5706, 0x5708, 0x570a, 0x570c, 0x570e, 0x5710, 0x5712,\n    0x5714, 0x5716, 0x5740, 0x5742, 0x5744, 0x5780, 0x5781, 0x57c0,\n    0x57c1, 0x5800, 0x5801, 0x5840, 0x5841, 0x5880, 0x5881, 0x5900,\n    0x5901, 0x5902, 0x5903, 0x5940, 0x8e80, 0x8e82, 0x8ec0, 0x8f00,\n    0x8f01, 0x8f40, 0x8f41, 0x8f81, 0x8f80, 0x8f83, 0x8fc0, 0x8fc1,\n    0x9000,\n};\n\ntypedef enum {\n    UNICODE_GC_Cn,\n    UNICODE_GC_Lu,\n    UNICODE_GC_Ll,\n    UNICODE_GC_Lt,\n    UNICODE_GC_Lm,\n    UNICODE_GC_Lo,\n    UNICODE_GC_Mn,\n    UNICODE_GC_Mc,\n    UNICODE_GC_Me,\n    UNICODE_GC_Nd,\n    UNICODE_GC_Nl,\n    UNICODE_GC_No,\n    UNICODE_GC_Sm,\n    UNICODE_GC_Sc,\n    UNICODE_GC_Sk,\n    UNICODE_GC_So,\n    UNICODE_GC_Pc,\n    UNICODE_GC_Pd,\n    UNICODE_GC_Ps,\n    UNICODE_GC_Pe,\n    UNICODE_GC_Pi,\n    UNICODE_GC_Pf,\n    UNICODE_GC_Po,\n    UNICODE_GC_Zs,\n    UNICODE_GC_Zl,\n    UNICODE_GC_Zp,\n    UNICODE_GC_Cc,\n    UNICODE_GC_Cf,\n    UNICODE_GC_Cs,\n    UNICODE_GC_Co,\n    UNICODE_GC_LC,\n    UNICODE_GC_L,\n    UNICODE_GC_M,\n    UNICODE_GC_N,\n    UNICODE_GC_S,\n    UNICODE_GC_P,\n    UNICODE_GC_Z,\n    UNICODE_GC_C,\n    UNICODE_GC_COUNT,\n} UnicodeGCEnum;\n\nstatic const char unicode_gc_name_table[] =\n    \"Cn,Unassigned\"            \"\\0\"\n    \"Lu,Uppercase_Letter\"      \"\\0\"\n    \"Ll,Lowercase_Letter\"      \"\\0\"\n    \"Lt,Titlecase_Letter\"      \"\\0\"\n    \"Lm,Modifier_Letter\"       \"\\0\"\n    \"Lo,Other_Letter\"          \"\\0\"\n    \"Mn,Nonspacing_Mark\"       \"\\0\"\n    \"Mc,Spacing_Mark\"          \"\\0\"\n    \"Me,Enclosing_Mark\"        \"\\0\"\n    \"Nd,Decimal_Number,digit\"  \"\\0\"\n    \"Nl,Letter_Number\"         \"\\0\"\n    \"No,Other_Number\"          \"\\0\"\n    \"Sm,Math_Symbol\"           \"\\0\"\n    \"Sc,Currency_Symbol\"       \"\\0\"\n    \"Sk,Modifier_Symbol\"       \"\\0\"\n    \"So,Other_Symbol\"          \"\\0\"\n    \"Pc,Connector_Punctuation\" \"\\0\"\n    \"Pd,Dash_Punctuation\"      \"\\0\"\n    \"Ps,Open_Punctuation\"      \"\\0\"\n    \"Pe,Close_Punctuation\"     \"\\0\"\n    \"Pi,Initial_Punctuation\"   \"\\0\"\n    \"Pf,Final_Punctuation\"     \"\\0\"\n    \"Po,Other_Punctuation\"     \"\\0\"\n    \"Zs,Space_Separator\"       \"\\0\"\n    \"Zl,Line_Separator\"        \"\\0\"\n    \"Zp,Paragraph_Separator\"   \"\\0\"\n    \"Cc,Control,cntrl\"         \"\\0\"\n    \"Cf,Format\"                \"\\0\"\n    \"Cs,Surrogate\"             \"\\0\"\n    \"Co,Private_Use\"           \"\\0\"\n    \"LC,Cased_Letter\"          \"\\0\"\n    \"L,Letter\"                 \"\\0\"\n    \"M,Mark,Combining_Mark\"    \"\\0\"\n    \"N,Number\"                 \"\\0\"\n    \"S,Symbol\"                 \"\\0\"\n    \"P,Punctuation,punct\"      \"\\0\"\n    \"Z,Separator\"              \"\\0\"\n    \"C,Other\"                  \"\\0\"\n;\n\nstatic const uint8_t unicode_gc_table[3790] = {\n    0xfa, 0x18, 0x17, 0x56, 0x0d, 0x56, 0x12, 0x13,\n    0x16, 0x0c, 0x16, 0x11, 0x36, 0xe9, 0x02, 0x36,\n    0x4c, 0x36, 0xe1, 0x12, 0x12, 0x16, 0x13, 0x0e,\n    0x10, 0x0e, 0xe2, 0x12, 0x12, 0x0c, 0x13, 0x0c,\n    0xfa, 0x19, 0x17, 0x16, 0x6d, 0x0f, 0x16, 0x0e,\n    0x0f, 0x05, 0x14, 0x0c, 0x1b, 0x0f, 0x0e, 0x0f,\n    0x0c, 0x2b, 0x0e, 0x02, 0x36, 0x0e, 0x0b, 0x05,\n    0x15, 0x4b, 0x16, 0xe1, 0x0f, 0x0c, 0xc1, 0xe2,\n    0x10, 0x0c, 0xe2, 0x00, 0xff, 0x30, 0x02, 0xff,\n    0x08, 0x02, 0xff, 0x27, 0xbf, 0x22, 0x21, 0x02,\n    0x5f, 0x5f, 0x21, 0x22, 0x61, 0x02, 0x21, 0x02,\n    0x41, 0x42, 0x21, 0x02, 0x21, 0x02, 0x9f, 0x7f,\n    0x02, 0x5f, 0x5f, 0x21, 0x02, 0x5f, 0x3f, 0x02,\n    0x05, 0x3f, 0x22, 0x65, 0x01, 0x03, 0x02, 0x01,\n    0x03, 0x02, 0x01, 0x03, 0x02, 0xff, 0x08, 0x02,\n    0xff, 0x0a, 0x02, 0x01, 0x03, 0x02, 0x5f, 0x21,\n    0x02, 0xff, 0x32, 0xa2, 0x21, 0x02, 0x21, 0x22,\n    0x5f, 0x41, 0x02, 0xff, 0x00, 0xe2, 0x3c, 0x05,\n    0xe2, 0x13, 0xe4, 0x0a, 0x6e, 0xe4, 0x04, 0xee,\n    0x06, 0x84, 0xce, 0x04, 0x0e, 0x04, 0xee, 0x09,\n    0xe6, 0x68, 0x7f, 0x04, 0x0e, 0x3f, 0x20, 0x04,\n    0x42, 0x16, 0x01, 0x60, 0x2e, 0x01, 0x16, 0x41,\n    0x00, 0x01, 0x00, 0x21, 0x02, 0xe1, 0x09, 0x00,\n    0xe1, 0x01, 0xe2, 0x1b, 0x3f, 0x02, 0x41, 0x42,\n    0xff, 0x10, 0x62, 0x3f, 0x0c, 0x5f, 0x3f, 0x02,\n    0xe1, 0x2b, 0xe2, 0x28, 0xff, 0x1a, 0x0f, 0x86,\n    0x28, 0xff, 0x2f, 0xff, 0x06, 0x02, 0xff, 0x58,\n    0x00, 0xe1, 0x1e, 0x20, 0x04, 0xb6, 0xe2, 0x21,\n    0x16, 0x11, 0x20, 0x2f, 0x0d, 0x00, 0xe6, 0x25,\n    0x11, 0x06, 0x16, 0x26, 0x16, 0x26, 0x16, 0x06,\n    0xe0, 0x00, 0xe5, 0x13, 0x60, 0x65, 0x36, 0xe0,\n    0x03, 0xbb, 0x4c, 0x36, 0x0d, 0x36, 0x2f, 0xe6,\n    0x03, 0x16, 0x1b, 0x00, 0x36, 0xe5, 0x18, 0x04,\n    0xe5, 0x02, 0xe6, 0x0d, 0xe9, 0x02, 0x76, 0x25,\n    0x06, 0xe5, 0x5b, 0x16, 0x05, 0xc6, 0x1b, 0x0f,\n    0xa6, 0x24, 0x26, 0x0f, 0x66, 0x25, 0xe9, 0x02,\n    0x45, 0x2f, 0x05, 0xf6, 0x06, 0x00, 0x1b, 0x05,\n    0x06, 0xe5, 0x16, 0xe6, 0x13, 0x20, 0xe5, 0x51,\n    0xe6, 0x03, 0x05, 0xe0, 0x06, 0xe9, 0x02, 0xe5,\n    0x19, 0xe6, 0x01, 0x24, 0x0f, 0x56, 0x04, 0x20,\n    0x06, 0x2d, 0xe5, 0x0e, 0x66, 0x04, 0xe6, 0x01,\n    0x04, 0x46, 0x04, 0x86, 0x20, 0xf6, 0x07, 0x00,\n    0xe5, 0x11, 0x46, 0x20, 0x16, 0x00, 0xe5, 0x03,\n    0xe0, 0x2d, 0xe5, 0x0d, 0x00, 0xe5, 0x0a, 0xe0,\n    0x03, 0xe6, 0x07, 0x1b, 0xe6, 0x18, 0x07, 0xe5,\n    0x2e, 0x06, 0x07, 0x06, 0x05, 0x47, 0xe6, 0x00,\n    0x67, 0x06, 0x27, 0x05, 0xc6, 0xe5, 0x02, 0x26,\n    0x36, 0xe9, 0x02, 0x16, 0x04, 0xe5, 0x07, 0x06,\n    0x27, 0x00, 0xe5, 0x00, 0x20, 0x25, 0x20, 0xe5,\n    0x0e, 0x00, 0xc5, 0x00, 0x05, 0x40, 0x65, 0x20,\n    0x06, 0x05, 0x47, 0x66, 0x20, 0x27, 0x20, 0x27,\n    0x06, 0x05, 0xe0, 0x00, 0x07, 0x60, 0x25, 0x00,\n    0x45, 0x26, 0x20, 0xe9, 0x02, 0x25, 0x2d, 0xab,\n    0x0f, 0x0d, 0x05, 0x16, 0x06, 0x20, 0x26, 0x07,\n    0x00, 0xa5, 0x60, 0x25, 0x20, 0xe5, 0x0e, 0x00,\n    0xc5, 0x00, 0x25, 0x00, 0x25, 0x00, 0x25, 0x20,\n    0x06, 0x00, 0x47, 0x26, 0x60, 0x26, 0x20, 0x46,\n    0x40, 0x06, 0xc0, 0x65, 0x00, 0x05, 0xc0, 0xe9,\n    0x02, 0x26, 0x45, 0x06, 0x16, 0xe0, 0x02, 0x26,\n    0x07, 0x00, 0xe5, 0x01, 0x00, 0x45, 0x00, 0xe5,\n    0x0e, 0x00, 0xc5, 0x00, 0x25, 0x00, 0x85, 0x20,\n    0x06, 0x05, 0x47, 0x86, 0x00, 0x26, 0x07, 0x00,\n    0x27, 0x06, 0x20, 0x05, 0xe0, 0x07, 0x25, 0x26,\n    0x20, 0xe9, 0x02, 0x16, 0x0d, 0xc0, 0x05, 0xa6,\n    0x00, 0x06, 0x27, 0x00, 0xe5, 0x00, 0x20, 0x25,\n    0x20, 0xe5, 0x0e, 0x00, 0xc5, 0x00, 0x25, 0x00,\n    0x85, 0x20, 0x06, 0x05, 0x07, 0x06, 0x07, 0x66,\n    0x20, 0x27, 0x20, 0x27, 0x06, 0xc0, 0x26, 0x07,\n    0x60, 0x25, 0x00, 0x45, 0x26, 0x20, 0xe9, 0x02,\n    0x0f, 0x05, 0xab, 0xe0, 0x02, 0x06, 0x05, 0x00,\n    0xa5, 0x40, 0x45, 0x00, 0x65, 0x40, 0x25, 0x00,\n    0x05, 0x00, 0x25, 0x40, 0x25, 0x40, 0x45, 0x40,\n    0xe5, 0x04, 0x60, 0x27, 0x06, 0x27, 0x40, 0x47,\n    0x00, 0x47, 0x06, 0x20, 0x05, 0xa0, 0x07, 0xe0,\n    0x06, 0xe9, 0x02, 0x4b, 0xaf, 0x0d, 0x0f, 0x80,\n    0x06, 0x47, 0x06, 0xe5, 0x00, 0x00, 0x45, 0x00,\n    0xe5, 0x0f, 0x00, 0xe5, 0x08, 0x40, 0x05, 0x46,\n    0x67, 0x00, 0x46, 0x00, 0x66, 0xc0, 0x26, 0x00,\n    0x45, 0x80, 0x25, 0x26, 0x20, 0xe9, 0x02, 0xc0,\n    0x16, 0xcb, 0x0f, 0x05, 0x06, 0x27, 0x16, 0xe5,\n    0x00, 0x00, 0x45, 0x00, 0xe5, 0x0f, 0x00, 0xe5,\n    0x02, 0x00, 0x85, 0x20, 0x06, 0x05, 0x07, 0x06,\n    0x87, 0x00, 0x06, 0x27, 0x00, 0x27, 0x26, 0xc0,\n    0x27, 0xc0, 0x05, 0x00, 0x25, 0x26, 0x20, 0xe9,\n    0x02, 0x00, 0x25, 0xe0, 0x05, 0x26, 0x27, 0xe5,\n    0x01, 0x00, 0x45, 0x00, 0xe5, 0x21, 0x26, 0x05,\n    0x47, 0x66, 0x00, 0x47, 0x00, 0x47, 0x06, 0x05,\n    0x0f, 0x60, 0x45, 0x07, 0xcb, 0x45, 0x26, 0x20,\n    0xe9, 0x02, 0xeb, 0x01, 0x0f, 0xa5, 0x00, 0x06,\n    0x27, 0x00, 0xe5, 0x0a, 0x40, 0xe5, 0x10, 0x00,\n    0xe5, 0x01, 0x00, 0x05, 0x20, 0xc5, 0x40, 0x06,\n    0x60, 0x47, 0x46, 0x00, 0x06, 0x00, 0xe7, 0x00,\n    0xa0, 0xe9, 0x02, 0x20, 0x27, 0x16, 0xe0, 0x04,\n    0xe5, 0x28, 0x06, 0x25, 0xc6, 0x60, 0x0d, 0xa5,\n    0x04, 0xe6, 0x00, 0x16, 0xe9, 0x02, 0x36, 0xe0,\n    0x1d, 0x25, 0x00, 0x05, 0x00, 0x85, 0x00, 0xe5,\n    0x10, 0x00, 0x05, 0x00, 0xe5, 0x02, 0x06, 0x25,\n    0xe6, 0x01, 0x05, 0x20, 0x85, 0x00, 0x04, 0x00,\n    0xa6, 0x20, 0xe9, 0x02, 0x20, 0x65, 0xe0, 0x18,\n    0x05, 0x4f, 0xf6, 0x07, 0x0f, 0x16, 0x4f, 0x26,\n    0xaf, 0xe9, 0x02, 0xeb, 0x02, 0x0f, 0x06, 0x0f,\n    0x06, 0x0f, 0x06, 0x12, 0x13, 0x12, 0x13, 0x27,\n    0xe5, 0x00, 0x00, 0xe5, 0x1c, 0x60, 0xe6, 0x06,\n    0x07, 0x86, 0x16, 0x26, 0x85, 0xe6, 0x03, 0x00,\n    0xe6, 0x1c, 0x00, 0xef, 0x00, 0x06, 0xaf, 0x00,\n    0x2f, 0x96, 0x6f, 0x36, 0xe0, 0x1d, 0xe5, 0x23,\n    0x27, 0x66, 0x07, 0xa6, 0x07, 0x26, 0x27, 0x26,\n    0x05, 0xe9, 0x02, 0xb6, 0xa5, 0x27, 0x26, 0x65,\n    0x46, 0x05, 0x47, 0x25, 0xc7, 0x45, 0x66, 0xe5,\n    0x05, 0x06, 0x27, 0x26, 0xa7, 0x06, 0x05, 0x07,\n    0xe9, 0x02, 0x47, 0x06, 0x2f, 0xe1, 0x1e, 0x00,\n    0x01, 0x80, 0x01, 0x20, 0xe2, 0x23, 0x16, 0x04,\n    0x42, 0xe5, 0x80, 0xc1, 0x00, 0x65, 0x20, 0xc5,\n    0x00, 0x05, 0x00, 0x65, 0x20, 0xe5, 0x21, 0x00,\n    0x65, 0x20, 0xe5, 0x19, 0x00, 0x65, 0x20, 0xc5,\n    0x00, 0x05, 0x00, 0x65, 0x20, 0xe5, 0x07, 0x00,\n    0xe5, 0x31, 0x00, 0x65, 0x20, 0xe5, 0x3b, 0x20,\n    0x46, 0xf6, 0x01, 0xeb, 0x0c, 0x40, 0xe5, 0x08,\n    0xef, 0x02, 0xa0, 0xe1, 0x4e, 0x20, 0xa2, 0x20,\n    0x11, 0xe5, 0x81, 0xe4, 0x0f, 0x16, 0xe5, 0x09,\n    0x17, 0xe5, 0x12, 0x12, 0x13, 0x40, 0xe5, 0x43,\n    0x56, 0x4a, 0xe5, 0x00, 0xc0, 0xe5, 0x05, 0x00,\n    0x65, 0x46, 0xe0, 0x03, 0xe5, 0x0a, 0x46, 0x36,\n    0xe0, 0x01, 0xe5, 0x0a, 0x26, 0xe0, 0x04, 0xe5,\n    0x05, 0x00, 0x45, 0x00, 0x26, 0xe0, 0x04, 0xe5,\n    0x2c, 0x26, 0x07, 0xc6, 0xe7, 0x00, 0x06, 0x27,\n    0xe6, 0x03, 0x56, 0x04, 0x56, 0x0d, 0x05, 0x06,\n    0x20, 0xe9, 0x02, 0xa0, 0xeb, 0x02, 0xa0, 0xb6,\n    0x11, 0x76, 0x46, 0x1b, 0x00, 0xe9, 0x02, 0xa0,\n    0xe5, 0x1b, 0x04, 0xe5, 0x2d, 0xc0, 0x85, 0x26,\n    0xe5, 0x1a, 0x06, 0x05, 0x80, 0xe5, 0x3e, 0xe0,\n    0x02, 0xe5, 0x17, 0x00, 0x46, 0x67, 0x26, 0x47,\n    0x60, 0x27, 0x06, 0xa7, 0x46, 0x60, 0x0f, 0x40,\n    0x36, 0xe9, 0x02, 0xe5, 0x16, 0x20, 0x85, 0xe0,\n    0x03, 0xe5, 0x24, 0x60, 0xe5, 0x12, 0xa0, 0xe9,\n    0x02, 0x0b, 0x40, 0xef, 0x1a, 0xe5, 0x0f, 0x26,\n    0x27, 0x06, 0x20, 0x36, 0xe5, 0x2d, 0x07, 0x06,\n    0x07, 0xc6, 0x00, 0x06, 0x07, 0x06, 0x27, 0xe6,\n    0x00, 0xa7, 0xe6, 0x02, 0x20, 0x06, 0xe9, 0x02,\n    0xa0, 0xe9, 0x02, 0xa0, 0xd6, 0x04, 0xb6, 0x20,\n    0xe6, 0x06, 0x08, 0x26, 0xe0, 0x37, 0x66, 0x07,\n    0xe5, 0x27, 0x06, 0x07, 0x86, 0x07, 0x06, 0x87,\n    0x06, 0x27, 0xc5, 0x60, 0xe9, 0x02, 0xd6, 0xef,\n    0x02, 0xe6, 0x01, 0xef, 0x01, 0x40, 0x26, 0x07,\n    0xe5, 0x16, 0x07, 0x66, 0x27, 0x26, 0x07, 0x46,\n    0x25, 0xe9, 0x02, 0xe5, 0x24, 0x06, 0x07, 0x26,\n    0x47, 0x06, 0x07, 0x46, 0x27, 0xe0, 0x00, 0x76,\n    0xe5, 0x1c, 0xe7, 0x00, 0xe6, 0x00, 0x27, 0x26,\n    0x40, 0x96, 0xe9, 0x02, 0x40, 0x45, 0xe9, 0x02,\n    0xe5, 0x16, 0xa4, 0x36, 0xe2, 0x01, 0xc0, 0xe1,\n    0x23, 0x20, 0x41, 0xf6, 0x00, 0xe0, 0x00, 0x46,\n    0x16, 0xe6, 0x05, 0x07, 0xc6, 0x65, 0x06, 0xa5,\n    0x06, 0x25, 0x07, 0x26, 0x05, 0x80, 0xe2, 0x24,\n    0xe4, 0x37, 0xe2, 0x05, 0x04, 0xe2, 0x1a, 0xe4,\n    0x1d, 0xe6, 0x32, 0x00, 0x86, 0xff, 0x80, 0x0e,\n    0xe2, 0x00, 0xff, 0x5a, 0xe2, 0x00, 0xe1, 0x00,\n    0xa2, 0x20, 0xa1, 0x20, 0xe2, 0x00, 0xe1, 0x00,\n    0xe2, 0x00, 0xe1, 0x00, 0xa2, 0x20, 0xa1, 0x20,\n    0xe2, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01,\n    0x00, 0x3f, 0xc2, 0xe1, 0x00, 0xe2, 0x06, 0x20,\n    0xe2, 0x00, 0xe3, 0x00, 0xe2, 0x00, 0xe3, 0x00,\n    0xe2, 0x00, 0xe3, 0x00, 0x82, 0x00, 0x22, 0x61,\n    0x03, 0x0e, 0x02, 0x4e, 0x42, 0x00, 0x22, 0x61,\n    0x03, 0x4e, 0x62, 0x20, 0x22, 0x61, 0x00, 0x4e,\n    0xe2, 0x00, 0x81, 0x4e, 0x20, 0x42, 0x00, 0x22,\n    0x61, 0x03, 0x2e, 0x00, 0xf7, 0x03, 0x9b, 0xb1,\n    0x36, 0x14, 0x15, 0x12, 0x34, 0x15, 0x12, 0x14,\n    0xf6, 0x00, 0x18, 0x19, 0x9b, 0x17, 0xf6, 0x01,\n    0x14, 0x15, 0x76, 0x30, 0x56, 0x0c, 0x12, 0x13,\n    0xf6, 0x03, 0x0c, 0x16, 0x10, 0xf6, 0x02, 0x17,\n    0x9b, 0x00, 0xfb, 0x02, 0x0b, 0x04, 0x20, 0xab,\n    0x4c, 0x12, 0x13, 0x04, 0xeb, 0x02, 0x4c, 0x12,\n    0x13, 0x00, 0xe4, 0x05, 0x40, 0xed, 0x18, 0xe0,\n    0x08, 0xe6, 0x05, 0x68, 0x06, 0x48, 0xe6, 0x04,\n    0xe0, 0x07, 0x2f, 0x01, 0x6f, 0x01, 0x2f, 0x02,\n    0x41, 0x22, 0x41, 0x02, 0x0f, 0x01, 0x2f, 0x0c,\n    0x81, 0xaf, 0x01, 0x0f, 0x01, 0x0f, 0x01, 0x0f,\n    0x61, 0x0f, 0x02, 0x61, 0x02, 0x65, 0x02, 0x2f,\n    0x22, 0x21, 0x8c, 0x3f, 0x42, 0x0f, 0x0c, 0x2f,\n    0x02, 0x0f, 0xeb, 0x08, 0xea, 0x1b, 0x3f, 0x6a,\n    0x0b, 0x2f, 0x60, 0x8c, 0x8f, 0x2c, 0x6f, 0x0c,\n    0x2f, 0x0c, 0x2f, 0x0c, 0xcf, 0x0c, 0xef, 0x17,\n    0x2c, 0x2f, 0x0c, 0x0f, 0x0c, 0xef, 0x17, 0xec,\n    0x80, 0x84, 0xef, 0x00, 0x12, 0x13, 0x12, 0x13,\n    0xef, 0x0c, 0x2c, 0xcf, 0x12, 0x13, 0xef, 0x49,\n    0x0c, 0xef, 0x16, 0xec, 0x11, 0xef, 0x20, 0xac,\n    0xef, 0x3d, 0xe0, 0x11, 0xef, 0x03, 0xe0, 0x0d,\n    0xeb, 0x34, 0xef, 0x46, 0xeb, 0x0e, 0xef, 0x80,\n    0x2f, 0x0c, 0xef, 0x01, 0x0c, 0xef, 0x2e, 0xec,\n    0x00, 0xef, 0x67, 0x0c, 0xef, 0x80, 0x70, 0x12,\n    0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12,\n    0x13, 0x12, 0x13, 0x12, 0x13, 0xeb, 0x16, 0xef,\n    0x24, 0x8c, 0x12, 0x13, 0xec, 0x17, 0x12, 0x13,\n    0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13,\n    0xec, 0x08, 0xef, 0x80, 0x78, 0xec, 0x7b, 0x12,\n    0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12,\n    0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12,\n    0x13, 0x12, 0x13, 0x12, 0x13, 0xec, 0x37, 0x12,\n    0x13, 0x12, 0x13, 0xec, 0x18, 0x12, 0x13, 0xec,\n    0x80, 0x7a, 0xef, 0x28, 0xec, 0x0d, 0x2f, 0xac,\n    0xef, 0x1f, 0x20, 0xef, 0x18, 0x00, 0xef, 0x61,\n    0xe1, 0x27, 0x00, 0xe2, 0x27, 0x00, 0x5f, 0x21,\n    0x22, 0xdf, 0x41, 0x02, 0x3f, 0x02, 0x3f, 0x82,\n    0x24, 0x41, 0x02, 0xff, 0x5a, 0x02, 0xaf, 0x7f,\n    0x46, 0x3f, 0x80, 0x76, 0x0b, 0x36, 0xe2, 0x1e,\n    0x00, 0x02, 0x80, 0x02, 0x20, 0xe5, 0x30, 0xc0,\n    0x04, 0x16, 0xe0, 0x06, 0x06, 0xe5, 0x0f, 0xe0,\n    0x01, 0xc5, 0x00, 0xc5, 0x00, 0xc5, 0x00, 0xc5,\n    0x00, 0xc5, 0x00, 0xc5, 0x00, 0xc5, 0x00, 0xc5,\n    0x00, 0xe6, 0x18, 0x36, 0x14, 0x15, 0x14, 0x15,\n    0x56, 0x14, 0x15, 0x16, 0x14, 0x15, 0xf6, 0x01,\n    0x11, 0x36, 0x11, 0x16, 0x14, 0x15, 0x36, 0x14,\n    0x15, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12,\n    0x13, 0x96, 0x04, 0xf6, 0x02, 0x31, 0x76, 0x11,\n    0x16, 0x12, 0xf6, 0x05, 0x2f, 0x16, 0xe0, 0x25,\n    0xef, 0x12, 0x00, 0xef, 0x51, 0xe0, 0x04, 0xef,\n    0x80, 0x4e, 0xe0, 0x12, 0xef, 0x04, 0x60, 0x17,\n    0x56, 0x0f, 0x04, 0x05, 0x0a, 0x12, 0x13, 0x12,\n    0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x2f,\n    0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13,\n    0x11, 0x12, 0x33, 0x0f, 0xea, 0x01, 0x66, 0x27,\n    0x11, 0x84, 0x2f, 0x4a, 0x04, 0x05, 0x16, 0x2f,\n    0x00, 0xe5, 0x4e, 0x20, 0x26, 0x2e, 0x24, 0x05,\n    0x11, 0xe5, 0x52, 0x16, 0x44, 0x05, 0x80, 0xe5,\n    0x23, 0x00, 0xe5, 0x56, 0x00, 0x2f, 0x6b, 0xef,\n    0x02, 0xe5, 0x18, 0xef, 0x1c, 0xe0, 0x04, 0xe5,\n    0x08, 0xef, 0x17, 0x00, 0xeb, 0x02, 0xef, 0x16,\n    0xeb, 0x00, 0x0f, 0xeb, 0x07, 0xef, 0x18, 0xeb,\n    0x02, 0xef, 0x1f, 0xeb, 0x07, 0xef, 0x80, 0xb8,\n    0xe5, 0x99, 0x38, 0xef, 0x38, 0xe5, 0xc0, 0x11,\n    0x75, 0x40, 0xe5, 0x0d, 0x04, 0xe5, 0x83, 0xef,\n    0x40, 0xef, 0x2f, 0xe0, 0x01, 0xe5, 0x20, 0xa4,\n    0x36, 0xe5, 0x80, 0x84, 0x04, 0x56, 0xe5, 0x08,\n    0xe9, 0x02, 0x25, 0xe0, 0x0c, 0xff, 0x26, 0x05,\n    0x06, 0x48, 0x16, 0xe6, 0x02, 0x16, 0x04, 0xff,\n    0x14, 0x24, 0x26, 0xe5, 0x3e, 0xea, 0x02, 0x26,\n    0xb6, 0xe0, 0x00, 0xee, 0x0f, 0xe4, 0x01, 0x2e,\n    0xff, 0x06, 0x22, 0xff, 0x36, 0x04, 0xe2, 0x00,\n    0x9f, 0xff, 0x02, 0x04, 0x2e, 0x7f, 0x05, 0x7f,\n    0x22, 0xff, 0x0d, 0x61, 0x02, 0x81, 0x02, 0xff,\n    0x02, 0x20, 0x5f, 0x41, 0x02, 0x3f, 0xe0, 0x22,\n    0x3f, 0x05, 0x24, 0x02, 0xc5, 0x06, 0x45, 0x06,\n    0x65, 0x06, 0xe5, 0x0f, 0x27, 0x26, 0x07, 0x6f,\n    0x06, 0x40, 0xab, 0x2f, 0x0d, 0x0f, 0xa0, 0xe5,\n    0x2c, 0x76, 0xe0, 0x00, 0x27, 0xe5, 0x2a, 0xe7,\n    0x08, 0x26, 0xe0, 0x00, 0x36, 0xe9, 0x02, 0xa0,\n    0xe6, 0x0a, 0xa5, 0x56, 0x05, 0x16, 0x25, 0x06,\n    0xe9, 0x02, 0xe5, 0x14, 0xe6, 0x00, 0x36, 0xe5,\n    0x0f, 0xe6, 0x03, 0x27, 0xe0, 0x03, 0x16, 0xe5,\n    0x15, 0x40, 0x46, 0x07, 0xe5, 0x27, 0x06, 0x27,\n    0x66, 0x27, 0x26, 0x47, 0xf6, 0x05, 0x00, 0x04,\n    0xe9, 0x02, 0x60, 0x36, 0x85, 0x06, 0x04, 0xe5,\n    0x01, 0xe9, 0x02, 0x85, 0x00, 0xe5, 0x21, 0xa6,\n    0x27, 0x26, 0x27, 0x26, 0xe0, 0x01, 0x45, 0x06,\n    0xe5, 0x00, 0x06, 0x07, 0x20, 0xe9, 0x02, 0x20,\n    0x76, 0xe5, 0x08, 0x04, 0xa5, 0x4f, 0x05, 0x07,\n    0x06, 0x07, 0xe5, 0x2a, 0x06, 0x05, 0x46, 0x25,\n    0x26, 0x85, 0x26, 0x05, 0x06, 0x05, 0xe0, 0x10,\n    0x25, 0x04, 0x36, 0xe5, 0x03, 0x07, 0x26, 0x27,\n    0x36, 0x05, 0x24, 0x07, 0x06, 0xe0, 0x02, 0xa5,\n    0x20, 0xa5, 0x20, 0xa5, 0xe0, 0x01, 0xc5, 0x00,\n    0xc5, 0x00, 0xe2, 0x23, 0x0e, 0x64, 0xe2, 0x01,\n    0x04, 0x2e, 0x60, 0xe2, 0x48, 0xe5, 0x1b, 0x27,\n    0x06, 0x27, 0x06, 0x27, 0x16, 0x07, 0x06, 0x20,\n    0xe9, 0x02, 0xa0, 0xe5, 0xab, 0x1c, 0xe0, 0x04,\n    0xe5, 0x0f, 0x60, 0xe5, 0x29, 0x60, 0xfc, 0x87,\n    0x78, 0xfd, 0x98, 0x78, 0xe5, 0x80, 0xe6, 0x20,\n    0xe5, 0x62, 0xe0, 0x1e, 0xc2, 0xe0, 0x04, 0x82,\n    0x80, 0x05, 0x06, 0xe5, 0x02, 0x0c, 0xe5, 0x05,\n    0x00, 0x85, 0x00, 0x05, 0x00, 0x25, 0x00, 0x25,\n    0x00, 0xe5, 0x64, 0xee, 0x08, 0xe0, 0x09, 0xe5,\n    0x80, 0xe3, 0x13, 0x12, 0xe0, 0x08, 0xe5, 0x38,\n    0x20, 0xe5, 0x2e, 0xe0, 0x20, 0xe5, 0x04, 0x0d,\n    0x0f, 0x20, 0xe6, 0x08, 0xd6, 0x12, 0x13, 0x16,\n    0xa0, 0xe6, 0x08, 0x16, 0x31, 0x30, 0x12, 0x13,\n    0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x12, 0x13,\n    0x12, 0x13, 0x12, 0x13, 0x12, 0x13, 0x36, 0x12,\n    0x13, 0x76, 0x50, 0x56, 0x00, 0x76, 0x11, 0x12,\n    0x13, 0x12, 0x13, 0x12, 0x13, 0x56, 0x0c, 0x11,\n    0x4c, 0x00, 0x16, 0x0d, 0x36, 0x60, 0x85, 0x00,\n    0xe5, 0x7f, 0x20, 0x1b, 0x00, 0x56, 0x0d, 0x56,\n    0x12, 0x13, 0x16, 0x0c, 0x16, 0x11, 0x36, 0xe9,\n    0x02, 0x36, 0x4c, 0x36, 0xe1, 0x12, 0x12, 0x16,\n    0x13, 0x0e, 0x10, 0x0e, 0xe2, 0x12, 0x12, 0x0c,\n    0x13, 0x0c, 0x12, 0x13, 0x16, 0x12, 0x13, 0x36,\n    0xe5, 0x02, 0x04, 0xe5, 0x25, 0x24, 0xe5, 0x17,\n    0x40, 0xa5, 0x20, 0xa5, 0x20, 0xa5, 0x20, 0x45,\n    0x40, 0x2d, 0x0c, 0x0e, 0x0f, 0x2d, 0x00, 0x0f,\n    0x6c, 0x2f, 0xe0, 0x02, 0x5b, 0x2f, 0x20, 0xe5,\n    0x04, 0x00, 0xe5, 0x12, 0x00, 0xe5, 0x0b, 0x00,\n    0x25, 0x00, 0xe5, 0x07, 0x20, 0xe5, 0x06, 0xe0,\n    0x1a, 0xe5, 0x73, 0x80, 0x56, 0x60, 0xeb, 0x25,\n    0x40, 0xef, 0x01, 0xea, 0x2d, 0x6b, 0xef, 0x09,\n    0x2b, 0x4f, 0x00, 0xef, 0x05, 0x40, 0x0f, 0xe0,\n    0x27, 0xef, 0x25, 0x06, 0xe0, 0x7a, 0xe5, 0x15,\n    0x40, 0xe5, 0x29, 0xe0, 0x07, 0x06, 0xeb, 0x13,\n    0x60, 0xe5, 0x18, 0x6b, 0xe0, 0x01, 0xe5, 0x0c,\n    0x0a, 0xe5, 0x00, 0x0a, 0x80, 0xe5, 0x1e, 0x86,\n    0x80, 0xe5, 0x16, 0x00, 0x16, 0xe5, 0x1c, 0x60,\n    0xe5, 0x00, 0x16, 0x8a, 0xe0, 0x22, 0xe1, 0x20,\n    0xe2, 0x20, 0xe5, 0x46, 0x20, 0xe9, 0x02, 0xa0,\n    0xe1, 0x1c, 0x60, 0xe2, 0x1c, 0x60, 0xe5, 0x20,\n    0xe0, 0x00, 0xe5, 0x2c, 0xe0, 0x03, 0x16, 0xe0,\n    0x80, 0x08, 0xe5, 0x80, 0xaf, 0xe0, 0x01, 0xe5,\n    0x0e, 0xe0, 0x02, 0xe5, 0x00, 0xe0, 0x80, 0x10,\n    0xa5, 0x20, 0x05, 0x00, 0xe5, 0x24, 0x00, 0x25,\n    0x40, 0x05, 0x20, 0xe5, 0x0f, 0x00, 0x16, 0xeb,\n    0x00, 0xe5, 0x0f, 0x2f, 0xcb, 0xe5, 0x17, 0xe0,\n    0x00, 0xeb, 0x01, 0xe0, 0x28, 0xe5, 0x0b, 0x00,\n    0x25, 0x80, 0x8b, 0xe5, 0x0e, 0xab, 0x40, 0x16,\n    0xe5, 0x12, 0x80, 0x16, 0xe0, 0x38, 0xe5, 0x30,\n    0x60, 0x2b, 0x25, 0xeb, 0x08, 0x20, 0xeb, 0x26,\n    0x05, 0x46, 0x00, 0x26, 0x80, 0x66, 0x65, 0x00,\n    0x45, 0x00, 0xe5, 0x15, 0x20, 0x46, 0x60, 0x06,\n    0xeb, 0x01, 0xc0, 0xf6, 0x01, 0xc0, 0xe5, 0x15,\n    0x2b, 0x16, 0xe5, 0x15, 0x4b, 0xe0, 0x18, 0xe5,\n    0x00, 0x0f, 0xe5, 0x14, 0x26, 0x60, 0x8b, 0xd6,\n    0xe0, 0x01, 0xe5, 0x2e, 0x40, 0xd6, 0xe5, 0x0e,\n    0x20, 0xeb, 0x00, 0xe5, 0x0b, 0x80, 0xeb, 0x00,\n    0xe5, 0x0a, 0xc0, 0x76, 0xe0, 0x04, 0xcb, 0xe0,\n    0x48, 0xe5, 0x41, 0xe0, 0x2f, 0xe1, 0x2b, 0xe0,\n    0x05, 0xe2, 0x2b, 0xc0, 0xab, 0xe5, 0x1c, 0x66,\n    0xe0, 0x00, 0xe9, 0x02, 0xe0, 0x80, 0x9e, 0xeb,\n    0x17, 0x00, 0xe5, 0x22, 0x00, 0x26, 0x11, 0x20,\n    0x25, 0xe0, 0x46, 0xe5, 0x15, 0xeb, 0x02, 0x05,\n    0xe0, 0x00, 0xe5, 0x0e, 0xe6, 0x03, 0x6b, 0x96,\n    0xe0, 0x4e, 0xe5, 0x0d, 0xcb, 0xe0, 0x0c, 0xe5,\n    0x0f, 0xe0, 0x01, 0x07, 0x06, 0x07, 0xe5, 0x2d,\n    0xe6, 0x07, 0xd6, 0x60, 0xeb, 0x0c, 0xe9, 0x02,\n    0xe0, 0x07, 0x46, 0x07, 0xe5, 0x25, 0x47, 0x66,\n    0x27, 0x26, 0x36, 0x1b, 0x76, 0xe0, 0x03, 0x1b,\n    0x20, 0xe5, 0x11, 0xc0, 0xe9, 0x02, 0xa0, 0x46,\n    0xe5, 0x1c, 0x86, 0x07, 0xe6, 0x00, 0x00, 0xe9,\n    0x02, 0x76, 0x05, 0x27, 0x05, 0xe0, 0x00, 0xe5,\n    0x1b, 0x06, 0x36, 0x05, 0xe0, 0x01, 0x26, 0x07,\n    0xe5, 0x28, 0x47, 0xe6, 0x01, 0x27, 0x65, 0x76,\n    0x66, 0x16, 0x07, 0x06, 0xe9, 0x02, 0x05, 0x16,\n    0x05, 0x56, 0x00, 0xeb, 0x0c, 0xe0, 0x03, 0xe5,\n    0x0a, 0x00, 0xe5, 0x11, 0x47, 0x46, 0x27, 0x06,\n    0x07, 0x26, 0xb6, 0x06, 0xe0, 0x39, 0xc5, 0x00,\n    0x05, 0x00, 0x65, 0x00, 0xe5, 0x07, 0x00, 0xe5,\n    0x02, 0x16, 0xa0, 0xe5, 0x27, 0x06, 0x47, 0xe6,\n    0x00, 0x80, 0xe9, 0x02, 0xa0, 0x26, 0x27, 0x00,\n    0xe5, 0x00, 0x20, 0x25, 0x20, 0xe5, 0x0e, 0x00,\n    0xc5, 0x00, 0x25, 0x00, 0x85, 0x00, 0x26, 0x05,\n    0x27, 0x06, 0x67, 0x20, 0x27, 0x20, 0x47, 0x20,\n    0x05, 0xa0, 0x07, 0x80, 0x85, 0x27, 0x20, 0xc6,\n    0x40, 0x86, 0xe0, 0x80, 0x03, 0xe5, 0x2d, 0x47,\n    0xe6, 0x00, 0x27, 0x46, 0x07, 0x06, 0x65, 0x96,\n    0xe9, 0x02, 0x36, 0x00, 0x16, 0x06, 0x45, 0xe0,\n    0x16, 0xe5, 0x28, 0x47, 0xa6, 0x07, 0x06, 0x67,\n    0x26, 0x07, 0x26, 0x25, 0x16, 0x05, 0xe0, 0x00,\n    0xe9, 0x02, 0xe0, 0x80, 0x1e, 0xe5, 0x27, 0x47,\n    0x66, 0x20, 0x67, 0x26, 0x07, 0x26, 0xf6, 0x0f,\n    0x65, 0x26, 0xe0, 0x1a, 0xe5, 0x28, 0x47, 0xe6,\n    0x00, 0x27, 0x06, 0x07, 0x26, 0x56, 0x05, 0xe0,\n    0x03, 0xe9, 0x02, 0xa0, 0xf6, 0x05, 0xe0, 0x0b,\n    0xe5, 0x23, 0x06, 0x07, 0x06, 0x27, 0xa6, 0x07,\n    0x06, 0x05, 0xc0, 0xe9, 0x02, 0xe0, 0x2e, 0xe5,\n    0x13, 0x20, 0x46, 0x27, 0x66, 0x07, 0x86, 0x60,\n    0xe9, 0x02, 0x2b, 0x56, 0x0f, 0xe0, 0x80, 0x38,\n    0xe5, 0x24, 0x47, 0xe6, 0x01, 0x07, 0x26, 0x16,\n    0xe0, 0x5c, 0xe1, 0x18, 0xe2, 0x18, 0xe9, 0x02,\n    0xeb, 0x01, 0xe0, 0x04, 0xe5, 0x00, 0x20, 0x05,\n    0x20, 0xe5, 0x00, 0x00, 0x25, 0x00, 0xe5, 0x10,\n    0xa7, 0x00, 0x27, 0x20, 0x26, 0x07, 0x06, 0x05,\n    0x07, 0x05, 0x07, 0x06, 0x56, 0xe0, 0x01, 0xe9,\n    0x02, 0xe0, 0x3e, 0xe5, 0x00, 0x20, 0xe5, 0x1f,\n    0x47, 0x66, 0x20, 0x26, 0x67, 0x06, 0x05, 0x16,\n    0x05, 0x07, 0xe0, 0x13, 0x05, 0xe6, 0x02, 0xe5,\n    0x20, 0xa6, 0x07, 0x05, 0x66, 0xf6, 0x00, 0x06,\n    0xe0, 0x00, 0x05, 0xa6, 0x27, 0x46, 0xe5, 0x26,\n    0xe6, 0x05, 0x07, 0x26, 0x56, 0x05, 0x96, 0xe0,\n    0x15, 0xe5, 0x31, 0xe0, 0x80, 0x7f, 0xe5, 0x01,\n    0x00, 0xe5, 0x1d, 0x07, 0xc6, 0x00, 0xa6, 0x07,\n    0x06, 0x05, 0x96, 0xe0, 0x02, 0xe9, 0x02, 0xeb,\n    0x0b, 0x40, 0x36, 0xe5, 0x16, 0x20, 0xe6, 0x0e,\n    0x00, 0x07, 0xc6, 0x07, 0x26, 0x07, 0x26, 0xe0,\n    0x41, 0xc5, 0x00, 0x25, 0x00, 0xe5, 0x1e, 0xa6,\n    0x40, 0x06, 0x00, 0x26, 0x00, 0xc6, 0x05, 0x06,\n    0xe0, 0x00, 0xe9, 0x02, 0xa0, 0xa5, 0x00, 0x25,\n    0x00, 0xe5, 0x18, 0x87, 0x00, 0x26, 0x00, 0x27,\n    0x06, 0x07, 0x06, 0x05, 0xc0, 0xe9, 0x02, 0xe0,\n    0x80, 0xae, 0xe5, 0x0b, 0x26, 0x27, 0x36, 0xe0,\n    0x80, 0x2f, 0x05, 0xe0, 0x07, 0xeb, 0x0d, 0xef,\n    0x00, 0x6d, 0xef, 0x09, 0xe0, 0x05, 0x16, 0xe5,\n    0x83, 0x12, 0xe0, 0x5e, 0xea, 0x67, 0x00, 0x96,\n    0xe0, 0x03, 0xe5, 0x80, 0x3c, 0xe0, 0x8a, 0x34,\n    0xe5, 0x83, 0xa7, 0x00, 0xfb, 0x01, 0xe0, 0x8f,\n    0x3f, 0xe5, 0x81, 0xbf, 0xe0, 0xa1, 0x31, 0xe5,\n    0x81, 0xb1, 0xc0, 0xe5, 0x17, 0x00, 0xe9, 0x02,\n    0x60, 0x36, 0xe0, 0x58, 0xe5, 0x16, 0x20, 0x86,\n    0x16, 0xe0, 0x02, 0xe5, 0x28, 0xc6, 0x96, 0x6f,\n    0x64, 0x16, 0x0f, 0xe0, 0x02, 0xe9, 0x02, 0x00,\n    0xcb, 0x00, 0xe5, 0x0d, 0x80, 0xe5, 0x0b, 0xe0,\n    0x82, 0x28, 0xe1, 0x18, 0xe2, 0x18, 0xeb, 0x0f,\n    0x76, 0xe0, 0x5d, 0xe5, 0x43, 0x60, 0x06, 0x05,\n    0xe7, 0x2f, 0xc0, 0x66, 0xe4, 0x05, 0xe0, 0x38,\n    0x24, 0x16, 0x04, 0x06, 0xe0, 0x03, 0x27, 0xe0,\n    0x06, 0xe5, 0x97, 0x70, 0xe0, 0x00, 0xe5, 0x84,\n    0x4e, 0xe0, 0x22, 0xe5, 0x01, 0xe0, 0xa2, 0x6f,\n    0xe5, 0x80, 0x97, 0xe0, 0x29, 0x45, 0xe0, 0x09,\n    0x65, 0xe0, 0x00, 0xe5, 0x81, 0x04, 0xe0, 0x88,\n    0x7c, 0xe5, 0x63, 0x80, 0xe5, 0x05, 0x40, 0xe5,\n    0x01, 0xc0, 0xe5, 0x02, 0x20, 0x0f, 0x26, 0x16,\n    0x7b, 0xe0, 0x92, 0xd4, 0xef, 0x80, 0x6e, 0xe0,\n    0x02, 0xef, 0x1f, 0x20, 0xef, 0x34, 0x27, 0x46,\n    0x4f, 0xa7, 0xfb, 0x00, 0xe6, 0x00, 0x2f, 0xc6,\n    0xef, 0x16, 0x66, 0xef, 0x33, 0xe0, 0x0f, 0xef,\n    0x3a, 0x46, 0x0f, 0xe0, 0x80, 0x12, 0xeb, 0x0c,\n    0xe0, 0x04, 0xef, 0x4f, 0xe0, 0x01, 0xeb, 0x11,\n    0xe0, 0x7f, 0xe1, 0x12, 0xe2, 0x12, 0xe1, 0x12,\n    0xc2, 0x00, 0xe2, 0x0a, 0xe1, 0x12, 0xe2, 0x12,\n    0x01, 0x00, 0x21, 0x20, 0x01, 0x20, 0x21, 0x20,\n    0x61, 0x00, 0xe1, 0x00, 0x62, 0x00, 0x02, 0x00,\n    0xc2, 0x00, 0xe2, 0x03, 0xe1, 0x12, 0xe2, 0x12,\n    0x21, 0x00, 0x61, 0x20, 0xe1, 0x00, 0x00, 0xc1,\n    0x00, 0xe2, 0x12, 0x21, 0x00, 0x61, 0x00, 0x81,\n    0x00, 0x01, 0x40, 0xc1, 0x00, 0xe2, 0x12, 0xe1,\n    0x12, 0xe2, 0x12, 0xe1, 0x12, 0xe2, 0x12, 0xe1,\n    0x12, 0xe2, 0x12, 0xe1, 0x12, 0xe2, 0x12, 0xe1,\n    0x12, 0xe2, 0x12, 0xe1, 0x12, 0xe2, 0x14, 0x20,\n    0xe1, 0x11, 0x0c, 0xe2, 0x11, 0x0c, 0xa2, 0xe1,\n    0x11, 0x0c, 0xe2, 0x11, 0x0c, 0xa2, 0xe1, 0x11,\n    0x0c, 0xe2, 0x11, 0x0c, 0xa2, 0xe1, 0x11, 0x0c,\n    0xe2, 0x11, 0x0c, 0xa2, 0xe1, 0x11, 0x0c, 0xe2,\n    0x11, 0x0c, 0xa2, 0x3f, 0x20, 0xe9, 0x2a, 0xef,\n    0x81, 0x78, 0xe6, 0x2f, 0x6f, 0xe6, 0x2a, 0xef,\n    0x00, 0x06, 0xef, 0x06, 0x06, 0x2f, 0x96, 0xe0,\n    0x07, 0x86, 0x00, 0xe6, 0x07, 0xe0, 0x84, 0xc8,\n    0xc6, 0x00, 0xe6, 0x09, 0x20, 0xc6, 0x00, 0x26,\n    0x00, 0x86, 0xe0, 0x80, 0x4d, 0xe5, 0x25, 0x40,\n    0xc6, 0xc4, 0x20, 0xe9, 0x02, 0x60, 0x05, 0x0f,\n    0xe0, 0x80, 0xe8, 0xe5, 0x24, 0x66, 0xe9, 0x02,\n    0x80, 0x0d, 0xe0, 0x84, 0x78, 0xe5, 0x80, 0x3d,\n    0x20, 0xeb, 0x01, 0xc6, 0xe0, 0x21, 0xe1, 0x1a,\n    0xe2, 0x1a, 0xc6, 0x04, 0x60, 0xe9, 0x02, 0x60,\n    0x36, 0xe0, 0x82, 0x89, 0xeb, 0x33, 0x0f, 0x4b,\n    0x0d, 0x6b, 0xe0, 0x44, 0xeb, 0x25, 0x0f, 0xeb,\n    0x07, 0xe0, 0x80, 0x3a, 0x65, 0x00, 0xe5, 0x13,\n    0x00, 0x25, 0x00, 0x05, 0x20, 0x05, 0x00, 0xe5,\n    0x02, 0x00, 0x65, 0x00, 0x05, 0x00, 0x05, 0xa0,\n    0x05, 0x60, 0x05, 0x00, 0x05, 0x00, 0x05, 0x00,\n    0x45, 0x00, 0x25, 0x00, 0x05, 0x20, 0x05, 0x00,\n    0x05, 0x00, 0x05, 0x00, 0x05, 0x00, 0x05, 0x00,\n    0x25, 0x00, 0x05, 0x20, 0x65, 0x00, 0xc5, 0x00,\n    0x65, 0x00, 0x65, 0x00, 0x05, 0x00, 0xe5, 0x02,\n    0x00, 0xe5, 0x09, 0x80, 0x45, 0x00, 0x85, 0x00,\n    0xe5, 0x09, 0xe0, 0x2c, 0x2c, 0xe0, 0x80, 0x86,\n    0xef, 0x24, 0x60, 0xef, 0x5c, 0xe0, 0x04, 0xef,\n    0x07, 0x20, 0xef, 0x07, 0x00, 0xef, 0x07, 0x00,\n    0xef, 0x1d, 0xe0, 0x02, 0xeb, 0x05, 0xef, 0x80,\n    0x19, 0xe0, 0x30, 0xef, 0x15, 0xe0, 0x05, 0xef,\n    0x24, 0x60, 0xef, 0x01, 0xc0, 0x2f, 0xe0, 0x06,\n    0xaf, 0xe0, 0x80, 0x12, 0xef, 0x80, 0x73, 0x8e,\n    0xef, 0x82, 0x50, 0xe0, 0x00, 0xef, 0x05, 0x40,\n    0xef, 0x05, 0x40, 0xef, 0x6c, 0xe0, 0x04, 0xef,\n    0x51, 0xc0, 0xef, 0x04, 0xe0, 0x0c, 0xef, 0x04,\n    0x60, 0xef, 0x30, 0xe0, 0x00, 0xef, 0x02, 0xa0,\n    0xef, 0x20, 0xe0, 0x00, 0xef, 0x16, 0x20, 0x2f,\n    0xe0, 0x46, 0xef, 0x71, 0x00, 0xef, 0x4a, 0x00,\n    0xef, 0x7f, 0xe0, 0x04, 0xef, 0x06, 0x20, 0x8f,\n    0x40, 0x4f, 0x80, 0xcf, 0xe0, 0x01, 0xef, 0x11,\n    0xc0, 0xcf, 0xe0, 0x01, 0x4f, 0xe0, 0x05, 0xcf,\n    0xe0, 0x21, 0xef, 0x80, 0x0b, 0x00, 0xef, 0x2f,\n    0xe0, 0x1d, 0xe9, 0x02, 0xe0, 0x83, 0x7e, 0xe5,\n    0xc0, 0x66, 0x56, 0xe0, 0x1a, 0xe5, 0x8f, 0xad,\n    0xe0, 0x03, 0xe5, 0x80, 0x56, 0x20, 0xe5, 0x95,\n    0xfa, 0xe0, 0x06, 0xe5, 0x9c, 0xa9, 0xe0, 0x8b,\n    0x97, 0xe5, 0x81, 0x96, 0xe0, 0x85, 0x5a, 0xe5,\n    0x92, 0xc3, 0xe0, 0xca, 0xac, 0x2e, 0x1b, 0xe0,\n    0x16, 0xfb, 0x58, 0xe0, 0x78, 0xe6, 0x80, 0x68,\n    0xe0, 0xc0, 0xbd, 0x88, 0xfd, 0xc0, 0xbf, 0x76,\n    0x20, 0xfd, 0xc0, 0xbf, 0x76, 0x20,\n};\n\ntypedef enum {\n    UNICODE_SCRIPT_Unknown,\n    UNICODE_SCRIPT_Adlam,\n    UNICODE_SCRIPT_Ahom,\n    UNICODE_SCRIPT_Anatolian_Hieroglyphs,\n    UNICODE_SCRIPT_Arabic,\n    UNICODE_SCRIPT_Armenian,\n    UNICODE_SCRIPT_Avestan,\n    UNICODE_SCRIPT_Balinese,\n    UNICODE_SCRIPT_Bamum,\n    UNICODE_SCRIPT_Bassa_Vah,\n    UNICODE_SCRIPT_Batak,\n    UNICODE_SCRIPT_Bengali,\n    UNICODE_SCRIPT_Bhaiksuki,\n    UNICODE_SCRIPT_Bopomofo,\n    UNICODE_SCRIPT_Brahmi,\n    UNICODE_SCRIPT_Braille,\n    UNICODE_SCRIPT_Buginese,\n    UNICODE_SCRIPT_Buhid,\n    UNICODE_SCRIPT_Canadian_Aboriginal,\n    UNICODE_SCRIPT_Carian,\n    UNICODE_SCRIPT_Caucasian_Albanian,\n    UNICODE_SCRIPT_Chakma,\n    UNICODE_SCRIPT_Cham,\n    UNICODE_SCRIPT_Cherokee,\n    UNICODE_SCRIPT_Chorasmian,\n    UNICODE_SCRIPT_Common,\n    UNICODE_SCRIPT_Coptic,\n    UNICODE_SCRIPT_Cuneiform,\n    UNICODE_SCRIPT_Cypriot,\n    UNICODE_SCRIPT_Cyrillic,\n    UNICODE_SCRIPT_Deseret,\n    UNICODE_SCRIPT_Devanagari,\n    UNICODE_SCRIPT_Dives_Akuru,\n    UNICODE_SCRIPT_Dogra,\n    UNICODE_SCRIPT_Duployan,\n    UNICODE_SCRIPT_Egyptian_Hieroglyphs,\n    UNICODE_SCRIPT_Elbasan,\n    UNICODE_SCRIPT_Elymaic,\n    UNICODE_SCRIPT_Ethiopic,\n    UNICODE_SCRIPT_Georgian,\n    UNICODE_SCRIPT_Glagolitic,\n    UNICODE_SCRIPT_Gothic,\n    UNICODE_SCRIPT_Grantha,\n    UNICODE_SCRIPT_Greek,\n    UNICODE_SCRIPT_Gujarati,\n    UNICODE_SCRIPT_Gunjala_Gondi,\n    UNICODE_SCRIPT_Gurmukhi,\n    UNICODE_SCRIPT_Han,\n    UNICODE_SCRIPT_Hangul,\n    UNICODE_SCRIPT_Hanifi_Rohingya,\n    UNICODE_SCRIPT_Hanunoo,\n    UNICODE_SCRIPT_Hatran,\n    UNICODE_SCRIPT_Hebrew,\n    UNICODE_SCRIPT_Hiragana,\n    UNICODE_SCRIPT_Imperial_Aramaic,\n    UNICODE_SCRIPT_Inherited,\n    UNICODE_SCRIPT_Inscriptional_Pahlavi,\n    UNICODE_SCRIPT_Inscriptional_Parthian,\n    UNICODE_SCRIPT_Javanese,\n    UNICODE_SCRIPT_Kaithi,\n    UNICODE_SCRIPT_Kannada,\n    UNICODE_SCRIPT_Katakana,\n    UNICODE_SCRIPT_Kayah_Li,\n    UNICODE_SCRIPT_Kharoshthi,\n    UNICODE_SCRIPT_Khmer,\n    UNICODE_SCRIPT_Khojki,\n    UNICODE_SCRIPT_Khitan_Small_Script,\n    UNICODE_SCRIPT_Khudawadi,\n    UNICODE_SCRIPT_Lao,\n    UNICODE_SCRIPT_Latin,\n    UNICODE_SCRIPT_Lepcha,\n    UNICODE_SCRIPT_Limbu,\n    UNICODE_SCRIPT_Linear_A,\n    UNICODE_SCRIPT_Linear_B,\n    UNICODE_SCRIPT_Lisu,\n    UNICODE_SCRIPT_Lycian,\n    UNICODE_SCRIPT_Lydian,\n    UNICODE_SCRIPT_Makasar,\n    UNICODE_SCRIPT_Mahajani,\n    UNICODE_SCRIPT_Malayalam,\n    UNICODE_SCRIPT_Mandaic,\n    UNICODE_SCRIPT_Manichaean,\n    UNICODE_SCRIPT_Marchen,\n    UNICODE_SCRIPT_Masaram_Gondi,\n    UNICODE_SCRIPT_Medefaidrin,\n    UNICODE_SCRIPT_Meetei_Mayek,\n    UNICODE_SCRIPT_Mende_Kikakui,\n    UNICODE_SCRIPT_Meroitic_Cursive,\n    UNICODE_SCRIPT_Meroitic_Hieroglyphs,\n    UNICODE_SCRIPT_Miao,\n    UNICODE_SCRIPT_Modi,\n    UNICODE_SCRIPT_Mongolian,\n    UNICODE_SCRIPT_Mro,\n    UNICODE_SCRIPT_Multani,\n    UNICODE_SCRIPT_Myanmar,\n    UNICODE_SCRIPT_Nabataean,\n    UNICODE_SCRIPT_Nandinagari,\n    UNICODE_SCRIPT_New_Tai_Lue,\n    UNICODE_SCRIPT_Newa,\n    UNICODE_SCRIPT_Nko,\n    UNICODE_SCRIPT_Nushu,\n    UNICODE_SCRIPT_Nyiakeng_Puachue_Hmong,\n    UNICODE_SCRIPT_Ogham,\n    UNICODE_SCRIPT_Ol_Chiki,\n    UNICODE_SCRIPT_Old_Hungarian,\n    UNICODE_SCRIPT_Old_Italic,\n    UNICODE_SCRIPT_Old_North_Arabian,\n    UNICODE_SCRIPT_Old_Permic,\n    UNICODE_SCRIPT_Old_Persian,\n    UNICODE_SCRIPT_Old_Sogdian,\n    UNICODE_SCRIPT_Old_South_Arabian,\n    UNICODE_SCRIPT_Old_Turkic,\n    UNICODE_SCRIPT_Oriya,\n    UNICODE_SCRIPT_Osage,\n    UNICODE_SCRIPT_Osmanya,\n    UNICODE_SCRIPT_Pahawh_Hmong,\n    UNICODE_SCRIPT_Palmyrene,\n    UNICODE_SCRIPT_Pau_Cin_Hau,\n    UNICODE_SCRIPT_Phags_Pa,\n    UNICODE_SCRIPT_Phoenician,\n    UNICODE_SCRIPT_Psalter_Pahlavi,\n    UNICODE_SCRIPT_Rejang,\n    UNICODE_SCRIPT_Runic,\n    UNICODE_SCRIPT_Samaritan,\n    UNICODE_SCRIPT_Saurashtra,\n    UNICODE_SCRIPT_Sharada,\n    UNICODE_SCRIPT_Shavian,\n    UNICODE_SCRIPT_Siddham,\n    UNICODE_SCRIPT_SignWriting,\n    UNICODE_SCRIPT_Sinhala,\n    UNICODE_SCRIPT_Sogdian,\n    UNICODE_SCRIPT_Sora_Sompeng,\n    UNICODE_SCRIPT_Soyombo,\n    UNICODE_SCRIPT_Sundanese,\n    UNICODE_SCRIPT_Syloti_Nagri,\n    UNICODE_SCRIPT_Syriac,\n    UNICODE_SCRIPT_Tagalog,\n    UNICODE_SCRIPT_Tagbanwa,\n    UNICODE_SCRIPT_Tai_Le,\n    UNICODE_SCRIPT_Tai_Tham,\n    UNICODE_SCRIPT_Tai_Viet,\n    UNICODE_SCRIPT_Takri,\n    UNICODE_SCRIPT_Tamil,\n    UNICODE_SCRIPT_Tangut,\n    UNICODE_SCRIPT_Telugu,\n    UNICODE_SCRIPT_Thaana,\n    UNICODE_SCRIPT_Thai,\n    UNICODE_SCRIPT_Tibetan,\n    UNICODE_SCRIPT_Tifinagh,\n    UNICODE_SCRIPT_Tirhuta,\n    UNICODE_SCRIPT_Ugaritic,\n    UNICODE_SCRIPT_Vai,\n    UNICODE_SCRIPT_Wancho,\n    UNICODE_SCRIPT_Warang_Citi,\n    UNICODE_SCRIPT_Yezidi,\n    UNICODE_SCRIPT_Yi,\n    UNICODE_SCRIPT_Zanabazar_Square,\n    UNICODE_SCRIPT_COUNT,\n} UnicodeScriptEnum;\n\nstatic const char unicode_script_name_table[] =\n    \"Adlam,Adlm\"                  \"\\0\"\n    \"Ahom,Ahom\"                   \"\\0\"\n    \"Anatolian_Hieroglyphs,Hluw\"  \"\\0\"\n    \"Arabic,Arab\"                 \"\\0\"\n    \"Armenian,Armn\"               \"\\0\"\n    \"Avestan,Avst\"                \"\\0\"\n    \"Balinese,Bali\"               \"\\0\"\n    \"Bamum,Bamu\"                  \"\\0\"\n    \"Bassa_Vah,Bass\"              \"\\0\"\n    \"Batak,Batk\"                  \"\\0\"\n    \"Bengali,Beng\"                \"\\0\"\n    \"Bhaiksuki,Bhks\"              \"\\0\"\n    \"Bopomofo,Bopo\"               \"\\0\"\n    \"Brahmi,Brah\"                 \"\\0\"\n    \"Braille,Brai\"                \"\\0\"\n    \"Buginese,Bugi\"               \"\\0\"\n    \"Buhid,Buhd\"                  \"\\0\"\n    \"Canadian_Aboriginal,Cans\"    \"\\0\"\n    \"Carian,Cari\"                 \"\\0\"\n    \"Caucasian_Albanian,Aghb\"     \"\\0\"\n    \"Chakma,Cakm\"                 \"\\0\"\n    \"Cham,Cham\"                   \"\\0\"\n    \"Cherokee,Cher\"               \"\\0\"\n    \"Chorasmian,Chrs\"             \"\\0\"\n    \"Common,Zyyy\"                 \"\\0\"\n    \"Coptic,Copt,Qaac\"            \"\\0\"\n    \"Cuneiform,Xsux\"              \"\\0\"\n    \"Cypriot,Cprt\"                \"\\0\"\n    \"Cyrillic,Cyrl\"               \"\\0\"\n    \"Deseret,Dsrt\"                \"\\0\"\n    \"Devanagari,Deva\"             \"\\0\"\n    \"Dives_Akuru,Diak\"            \"\\0\"\n    \"Dogra,Dogr\"                  \"\\0\"\n    \"Duployan,Dupl\"               \"\\0\"\n    \"Egyptian_Hieroglyphs,Egyp\"   \"\\0\"\n    \"Elbasan,Elba\"                \"\\0\"\n    \"Elymaic,Elym\"                \"\\0\"\n    \"Ethiopic,Ethi\"               \"\\0\"\n    \"Georgian,Geor\"               \"\\0\"\n    \"Glagolitic,Glag\"             \"\\0\"\n    \"Gothic,Goth\"                 \"\\0\"\n    \"Grantha,Gran\"                \"\\0\"\n    \"Greek,Grek\"                  \"\\0\"\n    \"Gujarati,Gujr\"               \"\\0\"\n    \"Gunjala_Gondi,Gong\"          \"\\0\"\n    \"Gurmukhi,Guru\"               \"\\0\"\n    \"Han,Hani\"                    \"\\0\"\n    \"Hangul,Hang\"                 \"\\0\"\n    \"Hanifi_Rohingya,Rohg\"        \"\\0\"\n    \"Hanunoo,Hano\"                \"\\0\"\n    \"Hatran,Hatr\"                 \"\\0\"\n    \"Hebrew,Hebr\"                 \"\\0\"\n    \"Hiragana,Hira\"               \"\\0\"\n    \"Imperial_Aramaic,Armi\"       \"\\0\"\n    \"Inherited,Zinh,Qaai\"         \"\\0\"\n    \"Inscriptional_Pahlavi,Phli\"  \"\\0\"\n    \"Inscriptional_Parthian,Prti\" \"\\0\"\n    \"Javanese,Java\"               \"\\0\"\n    \"Kaithi,Kthi\"                 \"\\0\"\n    \"Kannada,Knda\"                \"\\0\"\n    \"Katakana,Kana\"               \"\\0\"\n    \"Kayah_Li,Kali\"               \"\\0\"\n    \"Kharoshthi,Khar\"             \"\\0\"\n    \"Khmer,Khmr\"                  \"\\0\"\n    \"Khojki,Khoj\"                 \"\\0\"\n    \"Khitan_Small_Script,Kits\"    \"\\0\"\n    \"Khudawadi,Sind\"              \"\\0\"\n    \"Lao,Laoo\"                    \"\\0\"\n    \"Latin,Latn\"                  \"\\0\"\n    \"Lepcha,Lepc\"                 \"\\0\"\n    \"Limbu,Limb\"                  \"\\0\"\n    \"Linear_A,Lina\"               \"\\0\"\n    \"Linear_B,Linb\"               \"\\0\"\n    \"Lisu,Lisu\"                   \"\\0\"\n    \"Lycian,Lyci\"                 \"\\0\"\n    \"Lydian,Lydi\"                 \"\\0\"\n    \"Makasar,Maka\"                \"\\0\"\n    \"Mahajani,Mahj\"               \"\\0\"\n    \"Malayalam,Mlym\"              \"\\0\"\n    \"Mandaic,Mand\"                \"\\0\"\n    \"Manichaean,Mani\"             \"\\0\"\n    \"Marchen,Marc\"                \"\\0\"\n    \"Masaram_Gondi,Gonm\"          \"\\0\"\n    \"Medefaidrin,Medf\"            \"\\0\"\n    \"Meetei_Mayek,Mtei\"           \"\\0\"\n    \"Mende_Kikakui,Mend\"          \"\\0\"\n    \"Meroitic_Cursive,Merc\"       \"\\0\"\n    \"Meroitic_Hieroglyphs,Mero\"   \"\\0\"\n    \"Miao,Plrd\"                   \"\\0\"\n    \"Modi,Modi\"                   \"\\0\"\n    \"Mongolian,Mong\"              \"\\0\"\n    \"Mro,Mroo\"                    \"\\0\"\n    \"Multani,Mult\"                \"\\0\"\n    \"Myanmar,Mymr\"                \"\\0\"\n    \"Nabataean,Nbat\"              \"\\0\"\n    \"Nandinagari,Nand\"            \"\\0\"\n    \"New_Tai_Lue,Talu\"            \"\\0\"\n    \"Newa,Newa\"                   \"\\0\"\n    \"Nko,Nkoo\"                    \"\\0\"\n    \"Nushu,Nshu\"                  \"\\0\"\n    \"Nyiakeng_Puachue_Hmong,Hmnp\" \"\\0\"\n    \"Ogham,Ogam\"                  \"\\0\"\n    \"Ol_Chiki,Olck\"               \"\\0\"\n    \"Old_Hungarian,Hung\"          \"\\0\"\n    \"Old_Italic,Ital\"             \"\\0\"\n    \"Old_North_Arabian,Narb\"      \"\\0\"\n    \"Old_Permic,Perm\"             \"\\0\"\n    \"Old_Persian,Xpeo\"            \"\\0\"\n    \"Old_Sogdian,Sogo\"            \"\\0\"\n    \"Old_South_Arabian,Sarb\"      \"\\0\"\n    \"Old_Turkic,Orkh\"             \"\\0\"\n    \"Oriya,Orya\"                  \"\\0\"\n    \"Osage,Osge\"                  \"\\0\"\n    \"Osmanya,Osma\"                \"\\0\"\n    \"Pahawh_Hmong,Hmng\"           \"\\0\"\n    \"Palmyrene,Palm\"              \"\\0\"\n    \"Pau_Cin_Hau,Pauc\"            \"\\0\"\n    \"Phags_Pa,Phag\"               \"\\0\"\n    \"Phoenician,Phnx\"             \"\\0\"\n    \"Psalter_Pahlavi,Phlp\"        \"\\0\"\n    \"Rejang,Rjng\"                 \"\\0\"\n    \"Runic,Runr\"                  \"\\0\"\n    \"Samaritan,Samr\"              \"\\0\"\n    \"Saurashtra,Saur\"             \"\\0\"\n    \"Sharada,Shrd\"                \"\\0\"\n    \"Shavian,Shaw\"                \"\\0\"\n    \"Siddham,Sidd\"                \"\\0\"\n    \"SignWriting,Sgnw\"            \"\\0\"\n    \"Sinhala,Sinh\"                \"\\0\"\n    \"Sogdian,Sogd\"                \"\\0\"\n    \"Sora_Sompeng,Sora\"           \"\\0\"\n    \"Soyombo,Soyo\"                \"\\0\"\n    \"Sundanese,Sund\"              \"\\0\"\n    \"Syloti_Nagri,Sylo\"           \"\\0\"\n    \"Syriac,Syrc\"                 \"\\0\"\n    \"Tagalog,Tglg\"                \"\\0\"\n    \"Tagbanwa,Tagb\"               \"\\0\"\n    \"Tai_Le,Tale\"                 \"\\0\"\n    \"Tai_Tham,Lana\"               \"\\0\"\n    \"Tai_Viet,Tavt\"               \"\\0\"\n    \"Takri,Takr\"                  \"\\0\"\n    \"Tamil,Taml\"                  \"\\0\"\n    \"Tangut,Tang\"                 \"\\0\"\n    \"Telugu,Telu\"                 \"\\0\"\n    \"Thaana,Thaa\"                 \"\\0\"\n    \"Thai,Thai\"                   \"\\0\"\n    \"Tibetan,Tibt\"                \"\\0\"\n    \"Tifinagh,Tfng\"               \"\\0\"\n    \"Tirhuta,Tirh\"                \"\\0\"\n    \"Ugaritic,Ugar\"               \"\\0\"\n    \"Vai,Vaii\"                    \"\\0\"\n    \"Wancho,Wcho\"                 \"\\0\"\n    \"Warang_Citi,Wara\"            \"\\0\"\n    \"Yezidi,Yezi\"                 \"\\0\"\n    \"Yi,Yiii\"                     \"\\0\"\n    \"Zanabazar_Square,Zanb\"       \"\\0\"\n;\n\nstatic const uint8_t unicode_script_table[2609] = {\n    0xc0, 0x19, 0x99, 0x45, 0x85, 0x19, 0x99, 0x45,\n    0xae, 0x19, 0x80, 0x45, 0x8e, 0x19, 0x80, 0x45,\n    0x84, 0x19, 0x96, 0x45, 0x80, 0x19, 0x9e, 0x45,\n    0x80, 0x19, 0xe1, 0x60, 0x45, 0xa6, 0x19, 0x84,\n    0x45, 0x84, 0x19, 0x81, 0x0d, 0x93, 0x19, 0xe0,\n    0x0f, 0x37, 0x83, 0x2b, 0x80, 0x19, 0x82, 0x2b,\n    0x01, 0x83, 0x2b, 0x80, 0x19, 0x80, 0x2b, 0x03,\n    0x80, 0x2b, 0x80, 0x19, 0x80, 0x2b, 0x80, 0x19,\n    0x82, 0x2b, 0x00, 0x80, 0x2b, 0x00, 0x93, 0x2b,\n    0x00, 0xbe, 0x2b, 0x8d, 0x1a, 0x8f, 0x2b, 0xe0,\n    0x24, 0x1d, 0x81, 0x37, 0xe0, 0x48, 0x1d, 0x00,\n    0xa5, 0x05, 0x01, 0xb1, 0x05, 0x01, 0x82, 0x05,\n    0x00, 0xb6, 0x34, 0x07, 0x9a, 0x34, 0x03, 0x85,\n    0x34, 0x0a, 0x84, 0x04, 0x80, 0x19, 0x85, 0x04,\n    0x80, 0x19, 0x8d, 0x04, 0x80, 0x19, 0x80, 0x04,\n    0x00, 0x80, 0x04, 0x80, 0x19, 0x9f, 0x04, 0x80,\n    0x19, 0x89, 0x04, 0x8a, 0x37, 0x99, 0x04, 0x80,\n    0x37, 0xe0, 0x0b, 0x04, 0x80, 0x19, 0xa1, 0x04,\n    0x8d, 0x87, 0x00, 0xbb, 0x87, 0x01, 0x82, 0x87,\n    0xaf, 0x04, 0xb1, 0x91, 0x0d, 0xba, 0x63, 0x01,\n    0x82, 0x63, 0xad, 0x7b, 0x01, 0x8e, 0x7b, 0x00,\n    0x9b, 0x50, 0x01, 0x80, 0x50, 0x00, 0x8a, 0x87,\n    0x34, 0x94, 0x04, 0x00, 0x91, 0x04, 0x0a, 0x8e,\n    0x04, 0x80, 0x19, 0x9c, 0x04, 0xd0, 0x1f, 0x83,\n    0x37, 0x8e, 0x1f, 0x81, 0x19, 0x99, 0x1f, 0x83,\n    0x0b, 0x00, 0x87, 0x0b, 0x01, 0x81, 0x0b, 0x01,\n    0x95, 0x0b, 0x00, 0x86, 0x0b, 0x00, 0x80, 0x0b,\n    0x02, 0x83, 0x0b, 0x01, 0x88, 0x0b, 0x01, 0x81,\n    0x0b, 0x01, 0x83, 0x0b, 0x07, 0x80, 0x0b, 0x03,\n    0x81, 0x0b, 0x00, 0x84, 0x0b, 0x01, 0x98, 0x0b,\n    0x01, 0x82, 0x2e, 0x00, 0x85, 0x2e, 0x03, 0x81,\n    0x2e, 0x01, 0x95, 0x2e, 0x00, 0x86, 0x2e, 0x00,\n    0x81, 0x2e, 0x00, 0x81, 0x2e, 0x00, 0x81, 0x2e,\n    0x01, 0x80, 0x2e, 0x00, 0x84, 0x2e, 0x03, 0x81,\n    0x2e, 0x01, 0x82, 0x2e, 0x02, 0x80, 0x2e, 0x06,\n    0x83, 0x2e, 0x00, 0x80, 0x2e, 0x06, 0x90, 0x2e,\n    0x09, 0x82, 0x2c, 0x00, 0x88, 0x2c, 0x00, 0x82,\n    0x2c, 0x00, 0x95, 0x2c, 0x00, 0x86, 0x2c, 0x00,\n    0x81, 0x2c, 0x00, 0x84, 0x2c, 0x01, 0x89, 0x2c,\n    0x00, 0x82, 0x2c, 0x00, 0x82, 0x2c, 0x01, 0x80,\n    0x2c, 0x0e, 0x83, 0x2c, 0x01, 0x8b, 0x2c, 0x06,\n    0x86, 0x2c, 0x00, 0x82, 0x70, 0x00, 0x87, 0x70,\n    0x01, 0x81, 0x70, 0x01, 0x95, 0x70, 0x00, 0x86,\n    0x70, 0x00, 0x81, 0x70, 0x00, 0x84, 0x70, 0x01,\n    0x88, 0x70, 0x01, 0x81, 0x70, 0x01, 0x82, 0x70,\n    0x06, 0x82, 0x70, 0x03, 0x81, 0x70, 0x00, 0x84,\n    0x70, 0x01, 0x91, 0x70, 0x09, 0x81, 0x8e, 0x00,\n    0x85, 0x8e, 0x02, 0x82, 0x8e, 0x00, 0x83, 0x8e,\n    0x02, 0x81, 0x8e, 0x00, 0x80, 0x8e, 0x00, 0x81,\n    0x8e, 0x02, 0x81, 0x8e, 0x02, 0x82, 0x8e, 0x02,\n    0x8b, 0x8e, 0x03, 0x84, 0x8e, 0x02, 0x82, 0x8e,\n    0x00, 0x83, 0x8e, 0x01, 0x80, 0x8e, 0x05, 0x80,\n    0x8e, 0x0d, 0x94, 0x8e, 0x04, 0x8c, 0x90, 0x00,\n    0x82, 0x90, 0x00, 0x96, 0x90, 0x00, 0x8f, 0x90,\n    0x02, 0x87, 0x90, 0x00, 0x82, 0x90, 0x00, 0x83,\n    0x90, 0x06, 0x81, 0x90, 0x00, 0x82, 0x90, 0x04,\n    0x83, 0x90, 0x01, 0x89, 0x90, 0x06, 0x88, 0x90,\n    0x8c, 0x3c, 0x00, 0x82, 0x3c, 0x00, 0x96, 0x3c,\n    0x00, 0x89, 0x3c, 0x00, 0x84, 0x3c, 0x01, 0x88,\n    0x3c, 0x00, 0x82, 0x3c, 0x00, 0x83, 0x3c, 0x06,\n    0x81, 0x3c, 0x06, 0x80, 0x3c, 0x00, 0x83, 0x3c,\n    0x01, 0x89, 0x3c, 0x00, 0x81, 0x3c, 0x0c, 0x8c,\n    0x4f, 0x00, 0x82, 0x4f, 0x00, 0xb2, 0x4f, 0x00,\n    0x82, 0x4f, 0x00, 0x85, 0x4f, 0x03, 0x8f, 0x4f,\n    0x01, 0x99, 0x4f, 0x00, 0x82, 0x81, 0x00, 0x91,\n    0x81, 0x02, 0x97, 0x81, 0x00, 0x88, 0x81, 0x00,\n    0x80, 0x81, 0x01, 0x86, 0x81, 0x02, 0x80, 0x81,\n    0x03, 0x85, 0x81, 0x00, 0x80, 0x81, 0x00, 0x87,\n    0x81, 0x05, 0x89, 0x81, 0x01, 0x82, 0x81, 0x0b,\n    0xb9, 0x92, 0x03, 0x80, 0x19, 0x9b, 0x92, 0x24,\n    0x81, 0x44, 0x00, 0x80, 0x44, 0x00, 0x84, 0x44,\n    0x00, 0x97, 0x44, 0x00, 0x80, 0x44, 0x00, 0x96,\n    0x44, 0x01, 0x84, 0x44, 0x00, 0x80, 0x44, 0x00,\n    0x85, 0x44, 0x01, 0x89, 0x44, 0x01, 0x83, 0x44,\n    0x1f, 0xc7, 0x93, 0x00, 0xa3, 0x93, 0x03, 0xa6,\n    0x93, 0x00, 0xa3, 0x93, 0x00, 0x8e, 0x93, 0x00,\n    0x86, 0x93, 0x83, 0x19, 0x81, 0x93, 0x24, 0xe0,\n    0x3f, 0x5e, 0xa5, 0x27, 0x00, 0x80, 0x27, 0x04,\n    0x80, 0x27, 0x01, 0xaa, 0x27, 0x80, 0x19, 0x83,\n    0x27, 0xe0, 0x9f, 0x30, 0xc8, 0x26, 0x00, 0x83,\n    0x26, 0x01, 0x86, 0x26, 0x00, 0x80, 0x26, 0x00,\n    0x83, 0x26, 0x01, 0xa8, 0x26, 0x00, 0x83, 0x26,\n    0x01, 0xa0, 0x26, 0x00, 0x83, 0x26, 0x01, 0x86,\n    0x26, 0x00, 0x80, 0x26, 0x00, 0x83, 0x26, 0x01,\n    0x8e, 0x26, 0x00, 0xb8, 0x26, 0x00, 0x83, 0x26,\n    0x01, 0xc2, 0x26, 0x01, 0x9f, 0x26, 0x02, 0x99,\n    0x26, 0x05, 0xd5, 0x17, 0x01, 0x85, 0x17, 0x01,\n    0xe2, 0x1f, 0x12, 0x9c, 0x66, 0x02, 0xca, 0x7a,\n    0x82, 0x19, 0x8a, 0x7a, 0x06, 0x8c, 0x88, 0x00,\n    0x86, 0x88, 0x0a, 0x94, 0x32, 0x81, 0x19, 0x08,\n    0x93, 0x11, 0x0b, 0x8c, 0x89, 0x00, 0x82, 0x89,\n    0x00, 0x81, 0x89, 0x0b, 0xdd, 0x40, 0x01, 0x89,\n    0x40, 0x05, 0x89, 0x40, 0x05, 0x81, 0x5b, 0x81,\n    0x19, 0x80, 0x5b, 0x80, 0x19, 0x88, 0x5b, 0x00,\n    0x89, 0x5b, 0x05, 0xd8, 0x5b, 0x06, 0xaa, 0x5b,\n    0x04, 0xc5, 0x12, 0x09, 0x9e, 0x47, 0x00, 0x8b,\n    0x47, 0x03, 0x8b, 0x47, 0x03, 0x80, 0x47, 0x02,\n    0x8b, 0x47, 0x9d, 0x8a, 0x01, 0x84, 0x8a, 0x0a,\n    0xab, 0x61, 0x03, 0x99, 0x61, 0x05, 0x8a, 0x61,\n    0x02, 0x81, 0x61, 0x9f, 0x40, 0x9b, 0x10, 0x01,\n    0x81, 0x10, 0xbe, 0x8b, 0x00, 0x9c, 0x8b, 0x01,\n    0x8a, 0x8b, 0x05, 0x89, 0x8b, 0x05, 0x8d, 0x8b,\n    0x01, 0x90, 0x37, 0x3e, 0xcb, 0x07, 0x03, 0xac,\n    0x07, 0x02, 0xbf, 0x85, 0xb3, 0x0a, 0x07, 0x83,\n    0x0a, 0xb7, 0x46, 0x02, 0x8e, 0x46, 0x02, 0x82,\n    0x46, 0xaf, 0x67, 0x88, 0x1d, 0x06, 0xaa, 0x27,\n    0x01, 0x82, 0x27, 0x87, 0x85, 0x07, 0x82, 0x37,\n    0x80, 0x19, 0x8c, 0x37, 0x80, 0x19, 0x86, 0x37,\n    0x83, 0x19, 0x80, 0x37, 0x85, 0x19, 0x80, 0x37,\n    0x82, 0x19, 0x81, 0x37, 0x80, 0x19, 0x04, 0xa5,\n    0x45, 0x84, 0x2b, 0x80, 0x1d, 0xb0, 0x45, 0x84,\n    0x2b, 0x83, 0x45, 0x84, 0x2b, 0x8c, 0x45, 0x80,\n    0x1d, 0xc5, 0x45, 0x80, 0x2b, 0xb9, 0x37, 0x00,\n    0x84, 0x37, 0xe0, 0x9f, 0x45, 0x95, 0x2b, 0x01,\n    0x85, 0x2b, 0x01, 0xa5, 0x2b, 0x01, 0x85, 0x2b,\n    0x01, 0x87, 0x2b, 0x00, 0x80, 0x2b, 0x00, 0x80,\n    0x2b, 0x00, 0x80, 0x2b, 0x00, 0x9e, 0x2b, 0x01,\n    0xb4, 0x2b, 0x00, 0x8e, 0x2b, 0x00, 0x8d, 0x2b,\n    0x01, 0x85, 0x2b, 0x00, 0x92, 0x2b, 0x01, 0x82,\n    0x2b, 0x00, 0x88, 0x2b, 0x00, 0x8b, 0x19, 0x81,\n    0x37, 0xd6, 0x19, 0x00, 0x8a, 0x19, 0x80, 0x45,\n    0x01, 0x8a, 0x19, 0x80, 0x45, 0x8e, 0x19, 0x00,\n    0x8c, 0x45, 0x02, 0x9f, 0x19, 0x0f, 0xa0, 0x37,\n    0x0e, 0xa5, 0x19, 0x80, 0x2b, 0x82, 0x19, 0x81,\n    0x45, 0x85, 0x19, 0x80, 0x45, 0x9a, 0x19, 0x80,\n    0x45, 0x90, 0x19, 0xa8, 0x45, 0x82, 0x19, 0x03,\n    0xe2, 0x36, 0x19, 0x18, 0x8a, 0x19, 0x14, 0xe3,\n    0x3f, 0x19, 0xe0, 0x9f, 0x0f, 0xe2, 0x13, 0x19,\n    0x01, 0x9f, 0x19, 0x00, 0xe0, 0x08, 0x19, 0xae,\n    0x28, 0x00, 0xae, 0x28, 0x00, 0x9f, 0x45, 0xe0,\n    0x13, 0x1a, 0x04, 0x86, 0x1a, 0xa5, 0x27, 0x00,\n    0x80, 0x27, 0x04, 0x80, 0x27, 0x01, 0xb7, 0x94,\n    0x06, 0x81, 0x94, 0x0d, 0x80, 0x94, 0x96, 0x26,\n    0x08, 0x86, 0x26, 0x00, 0x86, 0x26, 0x00, 0x86,\n    0x26, 0x00, 0x86, 0x26, 0x00, 0x86, 0x26, 0x00,\n    0x86, 0x26, 0x00, 0x86, 0x26, 0x00, 0x86, 0x26,\n    0x00, 0x9f, 0x1d, 0xd2, 0x19, 0x2c, 0x99, 0x2f,\n    0x00, 0xd8, 0x2f, 0x0b, 0xe0, 0x75, 0x2f, 0x19,\n    0x8b, 0x19, 0x03, 0x84, 0x19, 0x80, 0x2f, 0x80,\n    0x19, 0x80, 0x2f, 0x98, 0x19, 0x88, 0x2f, 0x83,\n    0x37, 0x81, 0x30, 0x87, 0x19, 0x83, 0x2f, 0x83,\n    0x19, 0x00, 0xd5, 0x35, 0x01, 0x81, 0x37, 0x81,\n    0x19, 0x82, 0x35, 0x80, 0x19, 0xd9, 0x3d, 0x81,\n    0x19, 0x82, 0x3d, 0x04, 0xaa, 0x0d, 0x00, 0xdd,\n    0x30, 0x00, 0x8f, 0x19, 0x9f, 0x0d, 0xa3, 0x19,\n    0x0b, 0x8f, 0x3d, 0x9e, 0x30, 0x00, 0xbf, 0x19,\n    0x9e, 0x30, 0xd0, 0x19, 0xae, 0x3d, 0x80, 0x19,\n    0xd7, 0x3d, 0xe0, 0x47, 0x19, 0xf0, 0x09, 0x5f,\n    0x2f, 0xbf, 0x19, 0xf0, 0x41, 0x9c, 0x2f, 0x02,\n    0xe4, 0x2c, 0x9b, 0x02, 0xb6, 0x9b, 0x08, 0xaf,\n    0x4a, 0xe0, 0xcb, 0x97, 0x13, 0xdf, 0x1d, 0xd7,\n    0x08, 0x07, 0xa1, 0x19, 0xe0, 0x05, 0x45, 0x82,\n    0x19, 0xb4, 0x45, 0x01, 0x88, 0x45, 0x29, 0x8a,\n    0x45, 0xac, 0x86, 0x02, 0x89, 0x19, 0x05, 0xb7,\n    0x76, 0x07, 0xc5, 0x7c, 0x07, 0x8b, 0x7c, 0x05,\n    0x9f, 0x1f, 0xad, 0x3e, 0x80, 0x19, 0x80, 0x3e,\n    0xa3, 0x79, 0x0a, 0x80, 0x79, 0x9c, 0x30, 0x02,\n    0xcd, 0x3a, 0x00, 0x80, 0x19, 0x89, 0x3a, 0x03,\n    0x81, 0x3a, 0x9e, 0x5e, 0x00, 0xb6, 0x16, 0x08,\n    0x8d, 0x16, 0x01, 0x89, 0x16, 0x01, 0x83, 0x16,\n    0x9f, 0x5e, 0xc2, 0x8c, 0x17, 0x84, 0x8c, 0x96,\n    0x55, 0x09, 0x85, 0x26, 0x01, 0x85, 0x26, 0x01,\n    0x85, 0x26, 0x08, 0x86, 0x26, 0x00, 0x86, 0x26,\n    0x00, 0xaa, 0x45, 0x80, 0x19, 0x88, 0x45, 0x80,\n    0x2b, 0x83, 0x45, 0x81, 0x19, 0x03, 0xcf, 0x17,\n    0xad, 0x55, 0x01, 0x89, 0x55, 0x05, 0xf0, 0x1b,\n    0x43, 0x30, 0x0b, 0x96, 0x30, 0x03, 0xb0, 0x30,\n    0x70, 0x10, 0xa3, 0xe1, 0x0d, 0x2f, 0x01, 0xe0,\n    0x09, 0x2f, 0x25, 0x86, 0x45, 0x0b, 0x84, 0x05,\n    0x04, 0x99, 0x34, 0x00, 0x84, 0x34, 0x00, 0x80,\n    0x34, 0x00, 0x81, 0x34, 0x00, 0x81, 0x34, 0x00,\n    0x89, 0x34, 0xe0, 0x11, 0x04, 0x10, 0xe1, 0x0a,\n    0x04, 0x81, 0x19, 0x0f, 0xbf, 0x04, 0x01, 0xb5,\n    0x04, 0x27, 0x8d, 0x04, 0x01, 0x8f, 0x37, 0x89,\n    0x19, 0x05, 0x8d, 0x37, 0x81, 0x1d, 0xa2, 0x19,\n    0x00, 0x92, 0x19, 0x00, 0x83, 0x19, 0x03, 0x84,\n    0x04, 0x00, 0xe0, 0x26, 0x04, 0x01, 0x80, 0x19,\n    0x00, 0x9f, 0x19, 0x99, 0x45, 0x85, 0x19, 0x99,\n    0x45, 0x8a, 0x19, 0x89, 0x3d, 0x80, 0x19, 0xac,\n    0x3d, 0x81, 0x19, 0x9e, 0x30, 0x02, 0x85, 0x30,\n    0x01, 0x85, 0x30, 0x01, 0x85, 0x30, 0x01, 0x82,\n    0x30, 0x02, 0x86, 0x19, 0x00, 0x86, 0x19, 0x09,\n    0x84, 0x19, 0x01, 0x8b, 0x49, 0x00, 0x99, 0x49,\n    0x00, 0x92, 0x49, 0x00, 0x81, 0x49, 0x00, 0x8e,\n    0x49, 0x01, 0x8d, 0x49, 0x21, 0xe0, 0x1a, 0x49,\n    0x04, 0x82, 0x19, 0x03, 0xac, 0x19, 0x02, 0x88,\n    0x19, 0xce, 0x2b, 0x00, 0x8c, 0x19, 0x02, 0x80,\n    0x2b, 0x2e, 0xac, 0x19, 0x80, 0x37, 0x60, 0x21,\n    0x9c, 0x4b, 0x02, 0xb0, 0x13, 0x0e, 0x80, 0x37,\n    0x9a, 0x19, 0x03, 0xa3, 0x69, 0x08, 0x82, 0x69,\n    0x9a, 0x29, 0x04, 0xaa, 0x6b, 0x04, 0x9d, 0x96,\n    0x00, 0x80, 0x96, 0xa3, 0x6c, 0x03, 0x8d, 0x6c,\n    0x29, 0xcf, 0x1e, 0xaf, 0x7e, 0x9d, 0x72, 0x01,\n    0x89, 0x72, 0x05, 0xa3, 0x71, 0x03, 0xa3, 0x71,\n    0x03, 0xa7, 0x24, 0x07, 0xb3, 0x14, 0x0a, 0x80,\n    0x14, 0x60, 0x2f, 0xe0, 0xd6, 0x48, 0x08, 0x95,\n    0x48, 0x09, 0x87, 0x48, 0x60, 0x37, 0x85, 0x1c,\n    0x01, 0x80, 0x1c, 0x00, 0xab, 0x1c, 0x00, 0x81,\n    0x1c, 0x02, 0x80, 0x1c, 0x01, 0x80, 0x1c, 0x95,\n    0x36, 0x00, 0x88, 0x36, 0x9f, 0x74, 0x9e, 0x5f,\n    0x07, 0x88, 0x5f, 0x2f, 0x92, 0x33, 0x00, 0x81,\n    0x33, 0x04, 0x84, 0x33, 0x9b, 0x77, 0x02, 0x80,\n    0x77, 0x99, 0x4c, 0x04, 0x80, 0x4c, 0x3f, 0x9f,\n    0x58, 0x97, 0x57, 0x03, 0x93, 0x57, 0x01, 0xad,\n    0x57, 0x83, 0x3f, 0x00, 0x81, 0x3f, 0x04, 0x87,\n    0x3f, 0x00, 0x82, 0x3f, 0x00, 0x9c, 0x3f, 0x01,\n    0x82, 0x3f, 0x03, 0x89, 0x3f, 0x06, 0x88, 0x3f,\n    0x06, 0x9f, 0x6e, 0x9f, 0x6a, 0x1f, 0xa6, 0x51,\n    0x03, 0x8b, 0x51, 0x08, 0xb5, 0x06, 0x02, 0x86,\n    0x06, 0x95, 0x39, 0x01, 0x87, 0x39, 0x92, 0x38,\n    0x04, 0x87, 0x38, 0x91, 0x78, 0x06, 0x83, 0x78,\n    0x0b, 0x86, 0x78, 0x4f, 0xc8, 0x6f, 0x36, 0xb2,\n    0x68, 0x0c, 0xb2, 0x68, 0x06, 0x85, 0x68, 0xa7,\n    0x31, 0x07, 0x89, 0x31, 0x60, 0xc5, 0x9e, 0x04,\n    0x00, 0xa9, 0x9a, 0x00, 0x82, 0x9a, 0x01, 0x81,\n    0x9a, 0x4d, 0xa7, 0x6d, 0x07, 0xa9, 0x82, 0x55,\n    0x9b, 0x18, 0x13, 0x96, 0x25, 0x08, 0xcd, 0x0e,\n    0x03, 0x9d, 0x0e, 0x0e, 0x80, 0x0e, 0xc1, 0x3b,\n    0x0a, 0x80, 0x3b, 0x01, 0x98, 0x83, 0x06, 0x89,\n    0x83, 0x05, 0xb4, 0x15, 0x00, 0x91, 0x15, 0x07,\n    0xa6, 0x4e, 0x08, 0xdf, 0x7d, 0x00, 0x93, 0x81,\n    0x0a, 0x91, 0x41, 0x00, 0xab, 0x41, 0x40, 0x86,\n    0x5d, 0x00, 0x80, 0x5d, 0x00, 0x83, 0x5d, 0x00,\n    0x8e, 0x5d, 0x00, 0x8a, 0x5d, 0x05, 0xba, 0x43,\n    0x04, 0x89, 0x43, 0x05, 0x83, 0x2a, 0x00, 0x87,\n    0x2a, 0x01, 0x81, 0x2a, 0x01, 0x95, 0x2a, 0x00,\n    0x86, 0x2a, 0x00, 0x81, 0x2a, 0x00, 0x84, 0x2a,\n    0x00, 0x80, 0x37, 0x88, 0x2a, 0x01, 0x81, 0x2a,\n    0x01, 0x82, 0x2a, 0x01, 0x80, 0x2a, 0x05, 0x80,\n    0x2a, 0x04, 0x86, 0x2a, 0x01, 0x86, 0x2a, 0x02,\n    0x84, 0x2a, 0x60, 0x2a, 0xdb, 0x62, 0x00, 0x84,\n    0x62, 0x1d, 0xc7, 0x95, 0x07, 0x89, 0x95, 0x60,\n    0x45, 0xb5, 0x7f, 0x01, 0xa5, 0x7f, 0x21, 0xc4,\n    0x5a, 0x0a, 0x89, 0x5a, 0x05, 0x8c, 0x5b, 0x12,\n    0xb8, 0x8d, 0x06, 0x89, 0x8d, 0x35, 0x9a, 0x02,\n    0x01, 0x8e, 0x02, 0x03, 0x8f, 0x02, 0x60, 0x5f,\n    0xbb, 0x21, 0x60, 0x03, 0xd2, 0x99, 0x0b, 0x80,\n    0x99, 0x86, 0x20, 0x01, 0x80, 0x20, 0x01, 0x87,\n    0x20, 0x00, 0x81, 0x20, 0x00, 0x9d, 0x20, 0x00,\n    0x81, 0x20, 0x01, 0x8b, 0x20, 0x08, 0x89, 0x20,\n    0x45, 0x87, 0x60, 0x01, 0xad, 0x60, 0x01, 0x8a,\n    0x60, 0x1a, 0xc7, 0x9c, 0x07, 0xd2, 0x84, 0x1c,\n    0xb8, 0x75, 0x60, 0xa6, 0x88, 0x0c, 0x00, 0xac,\n    0x0c, 0x00, 0x8d, 0x0c, 0x09, 0x9c, 0x0c, 0x02,\n    0x9f, 0x52, 0x01, 0x95, 0x52, 0x00, 0x8d, 0x52,\n    0x48, 0x86, 0x53, 0x00, 0x81, 0x53, 0x00, 0xab,\n    0x53, 0x02, 0x80, 0x53, 0x00, 0x81, 0x53, 0x00,\n    0x88, 0x53, 0x07, 0x89, 0x53, 0x05, 0x85, 0x2d,\n    0x00, 0x81, 0x2d, 0x00, 0xa4, 0x2d, 0x00, 0x81,\n    0x2d, 0x00, 0x85, 0x2d, 0x06, 0x89, 0x2d, 0x60,\n    0xd5, 0x98, 0x4d, 0x60, 0x56, 0x80, 0x4a, 0x0e,\n    0xb1, 0x8e, 0x0c, 0x80, 0x8e, 0xe3, 0x39, 0x1b,\n    0x60, 0x05, 0xe0, 0x0e, 0x1b, 0x00, 0x84, 0x1b,\n    0x0a, 0xe0, 0x63, 0x1b, 0x6a, 0x5b, 0xe3, 0xce,\n    0x23, 0x00, 0x88, 0x23, 0x6f, 0x66, 0xe1, 0xe6,\n    0x03, 0x70, 0x11, 0x58, 0xe1, 0xd8, 0x08, 0x06,\n    0x9e, 0x5c, 0x00, 0x89, 0x5c, 0x03, 0x81, 0x5c,\n    0x5f, 0x9d, 0x09, 0x01, 0x85, 0x09, 0x09, 0xc5,\n    0x73, 0x09, 0x89, 0x73, 0x00, 0x86, 0x73, 0x00,\n    0x94, 0x73, 0x04, 0x92, 0x73, 0x62, 0x4f, 0xda,\n    0x54, 0x60, 0x04, 0xca, 0x59, 0x03, 0xb8, 0x59,\n    0x06, 0x90, 0x59, 0x3f, 0x80, 0x8f, 0x80, 0x64,\n    0x81, 0x19, 0x80, 0x42, 0x0a, 0x81, 0x2f, 0x0d,\n    0xf0, 0x07, 0x97, 0x8f, 0x07, 0xe2, 0x9f, 0x8f,\n    0xe1, 0x75, 0x42, 0x29, 0x88, 0x8f, 0x70, 0x12,\n    0x96, 0x80, 0x3d, 0xe0, 0xbd, 0x35, 0x30, 0x82,\n    0x35, 0x10, 0x83, 0x3d, 0x07, 0xe1, 0x2b, 0x64,\n    0x68, 0xa3, 0xe0, 0x0a, 0x22, 0x04, 0x8c, 0x22,\n    0x02, 0x88, 0x22, 0x06, 0x89, 0x22, 0x01, 0x83,\n    0x22, 0x83, 0x19, 0x70, 0x02, 0xfb, 0xe0, 0x95,\n    0x19, 0x09, 0xa6, 0x19, 0x01, 0xbd, 0x19, 0x82,\n    0x37, 0x90, 0x19, 0x87, 0x37, 0x81, 0x19, 0x86,\n    0x37, 0x9d, 0x19, 0x83, 0x37, 0xba, 0x19, 0x16,\n    0xc5, 0x2b, 0x60, 0x39, 0x93, 0x19, 0x0b, 0xd6,\n    0x19, 0x08, 0x98, 0x19, 0x60, 0x26, 0xd4, 0x19,\n    0x00, 0xc6, 0x19, 0x00, 0x81, 0x19, 0x01, 0x80,\n    0x19, 0x01, 0x81, 0x19, 0x01, 0x83, 0x19, 0x00,\n    0x8b, 0x19, 0x00, 0x80, 0x19, 0x00, 0x86, 0x19,\n    0x00, 0xc0, 0x19, 0x00, 0x83, 0x19, 0x01, 0x87,\n    0x19, 0x00, 0x86, 0x19, 0x00, 0x9b, 0x19, 0x00,\n    0x83, 0x19, 0x00, 0x84, 0x19, 0x00, 0x80, 0x19,\n    0x02, 0x86, 0x19, 0x00, 0xe0, 0xf3, 0x19, 0x01,\n    0xe0, 0xc3, 0x19, 0x01, 0xb1, 0x19, 0xe2, 0x2b,\n    0x80, 0x0e, 0x84, 0x80, 0x00, 0x8e, 0x80, 0x64,\n    0xef, 0x86, 0x28, 0x00, 0x90, 0x28, 0x01, 0x86,\n    0x28, 0x00, 0x81, 0x28, 0x00, 0x84, 0x28, 0x60,\n    0x74, 0xac, 0x65, 0x02, 0x8d, 0x65, 0x01, 0x89,\n    0x65, 0x03, 0x81, 0x65, 0x61, 0x0f, 0xb9, 0x98,\n    0x04, 0x80, 0x98, 0x64, 0x9f, 0xe0, 0x64, 0x56,\n    0x01, 0x8f, 0x56, 0x28, 0xcb, 0x01, 0x03, 0x89,\n    0x01, 0x03, 0x81, 0x01, 0x62, 0xb0, 0xc3, 0x19,\n    0x4b, 0xbc, 0x19, 0x60, 0x61, 0x83, 0x04, 0x00,\n    0x9a, 0x04, 0x00, 0x81, 0x04, 0x00, 0x80, 0x04,\n    0x01, 0x80, 0x04, 0x00, 0x89, 0x04, 0x00, 0x83,\n    0x04, 0x00, 0x80, 0x04, 0x00, 0x80, 0x04, 0x05,\n    0x80, 0x04, 0x03, 0x80, 0x04, 0x00, 0x80, 0x04,\n    0x00, 0x80, 0x04, 0x00, 0x82, 0x04, 0x00, 0x81,\n    0x04, 0x00, 0x80, 0x04, 0x01, 0x80, 0x04, 0x00,\n    0x80, 0x04, 0x00, 0x80, 0x04, 0x00, 0x80, 0x04,\n    0x00, 0x80, 0x04, 0x00, 0x81, 0x04, 0x00, 0x80,\n    0x04, 0x01, 0x83, 0x04, 0x00, 0x86, 0x04, 0x00,\n    0x83, 0x04, 0x00, 0x83, 0x04, 0x00, 0x80, 0x04,\n    0x00, 0x89, 0x04, 0x00, 0x90, 0x04, 0x04, 0x82,\n    0x04, 0x00, 0x84, 0x04, 0x00, 0x90, 0x04, 0x33,\n    0x81, 0x04, 0x60, 0xad, 0xab, 0x19, 0x03, 0xe0,\n    0x03, 0x19, 0x0b, 0x8e, 0x19, 0x01, 0x8e, 0x19,\n    0x00, 0x8e, 0x19, 0x00, 0xa4, 0x19, 0x09, 0xe0,\n    0x4d, 0x19, 0x37, 0x99, 0x19, 0x80, 0x35, 0x81,\n    0x19, 0x0c, 0xab, 0x19, 0x03, 0x88, 0x19, 0x06,\n    0x81, 0x19, 0x0d, 0x85, 0x19, 0x60, 0x39, 0xe3,\n    0x77, 0x19, 0x07, 0x8c, 0x19, 0x02, 0x8c, 0x19,\n    0x02, 0xe0, 0x13, 0x19, 0x0b, 0xd8, 0x19, 0x06,\n    0x8b, 0x19, 0x13, 0x8b, 0x19, 0x03, 0xb7, 0x19,\n    0x07, 0x89, 0x19, 0x05, 0xa7, 0x19, 0x07, 0x9d,\n    0x19, 0x01, 0x81, 0x19, 0x4d, 0xe0, 0x18, 0x19,\n    0x00, 0xd1, 0x19, 0x00, 0xe0, 0x26, 0x19, 0x0b,\n    0x8d, 0x19, 0x01, 0x84, 0x19, 0x02, 0x82, 0x19,\n    0x04, 0x86, 0x19, 0x08, 0x98, 0x19, 0x06, 0x86,\n    0x19, 0x08, 0x82, 0x19, 0x0c, 0x86, 0x19, 0x28,\n    0xe0, 0x32, 0x19, 0x00, 0xb6, 0x19, 0x24, 0x89,\n    0x19, 0x63, 0xa5, 0xf0, 0x96, 0x7d, 0x2f, 0x21,\n    0xef, 0xd4, 0x2f, 0x0a, 0xe0, 0x7d, 0x2f, 0x01,\n    0xf0, 0x06, 0x21, 0x2f, 0x0d, 0xf0, 0x0c, 0xd0,\n    0x2f, 0x6b, 0xbe, 0xe1, 0xbd, 0x2f, 0x65, 0x81,\n    0xf0, 0x02, 0xea, 0x2f, 0x7a, 0xdc, 0x55, 0x80,\n    0x19, 0x1d, 0xdf, 0x19, 0x60, 0x1f, 0xe0, 0x8f,\n    0x37,\n};\n\nstatic const uint8_t unicode_script_ext_table[799] = {\n    0x82, 0xc1, 0x00, 0x00, 0x01, 0x2b, 0x01, 0x00,\n    0x00, 0x01, 0x2b, 0x1c, 0x00, 0x0c, 0x01, 0x45,\n    0x80, 0x92, 0x00, 0x00, 0x02, 0x1d, 0x6b, 0x00,\n    0x02, 0x1d, 0x28, 0x01, 0x02, 0x1d, 0x45, 0x00,\n    0x02, 0x1d, 0x28, 0x81, 0x03, 0x00, 0x00, 0x05,\n    0x04, 0x31, 0x87, 0x91, 0x9a, 0x0d, 0x00, 0x00,\n    0x05, 0x04, 0x31, 0x87, 0x91, 0x9a, 0x00, 0x03,\n    0x04, 0x87, 0x91, 0x01, 0x00, 0x00, 0x05, 0x04,\n    0x31, 0x87, 0x91, 0x9a, 0x1f, 0x00, 0x00, 0x08,\n    0x01, 0x04, 0x50, 0x51, 0x78, 0x31, 0x82, 0x87,\n    0x09, 0x00, 0x0a, 0x02, 0x04, 0x87, 0x09, 0x00,\n    0x09, 0x03, 0x04, 0x91, 0x9a, 0x05, 0x00, 0x00,\n    0x02, 0x04, 0x87, 0x62, 0x00, 0x00, 0x02, 0x04,\n    0x31, 0x81, 0xfb, 0x00, 0x00, 0x0d, 0x0b, 0x1f,\n    0x2a, 0x2c, 0x2e, 0x3c, 0x45, 0x4f, 0x70, 0x7d,\n    0x8e, 0x90, 0x95, 0x00, 0x0c, 0x0b, 0x1f, 0x2a,\n    0x2c, 0x2e, 0x3c, 0x45, 0x4f, 0x70, 0x8e, 0x90,\n    0x95, 0x10, 0x00, 0x00, 0x14, 0x0b, 0x1f, 0x21,\n    0x2d, 0x53, 0x2a, 0x2c, 0x2e, 0x3c, 0x4e, 0x4f,\n    0x60, 0x70, 0x43, 0x81, 0x86, 0x8d, 0x8e, 0x90,\n    0x95, 0x00, 0x15, 0x0b, 0x1f, 0x21, 0x2d, 0x53,\n    0x2a, 0x2c, 0x2e, 0x3c, 0x47, 0x4e, 0x4f, 0x60,\n    0x70, 0x43, 0x81, 0x86, 0x8d, 0x8e, 0x90, 0x95,\n    0x09, 0x04, 0x1f, 0x21, 0x3b, 0x4e, 0x75, 0x00,\n    0x09, 0x03, 0x0b, 0x15, 0x86, 0x75, 0x00, 0x09,\n    0x02, 0x2e, 0x5d, 0x75, 0x00, 0x09, 0x02, 0x2c,\n    0x41, 0x80, 0x75, 0x00, 0x0d, 0x02, 0x2a, 0x8e,\n    0x80, 0x71, 0x00, 0x09, 0x02, 0x3c, 0x60, 0x82,\n    0xcf, 0x00, 0x09, 0x03, 0x15, 0x5e, 0x8a, 0x80,\n    0x30, 0x00, 0x00, 0x02, 0x27, 0x45, 0x85, 0xb8,\n    0x00, 0x01, 0x04, 0x11, 0x32, 0x89, 0x88, 0x80,\n    0x4a, 0x00, 0x01, 0x02, 0x5b, 0x76, 0x00, 0x00,\n    0x00, 0x02, 0x5b, 0x76, 0x84, 0x49, 0x00, 0x00,\n    0x04, 0x0b, 0x1f, 0x2a, 0x3c, 0x00, 0x01, 0x1f,\n    0x00, 0x04, 0x0b, 0x1f, 0x2a, 0x3c, 0x00, 0x02,\n    0x1f, 0x2a, 0x00, 0x01, 0x1f, 0x01, 0x02, 0x0b,\n    0x1f, 0x00, 0x02, 0x1f, 0x7d, 0x00, 0x02, 0x0b,\n    0x1f, 0x00, 0x02, 0x1f, 0x7d, 0x00, 0x06, 0x1f,\n    0x3c, 0x4f, 0x70, 0x8e, 0x90, 0x00, 0x01, 0x1f,\n    0x01, 0x02, 0x1f, 0x7d, 0x01, 0x01, 0x1f, 0x00,\n    0x02, 0x1f, 0x7d, 0x00, 0x02, 0x0b, 0x1f, 0x06,\n    0x01, 0x1f, 0x00, 0x02, 0x1f, 0x60, 0x00, 0x02,\n    0x0b, 0x1f, 0x01, 0x01, 0x1f, 0x00, 0x02, 0x0b,\n    0x1f, 0x03, 0x01, 0x1f, 0x00, 0x08, 0x0b, 0x1f,\n    0x2a, 0x3c, 0x60, 0x70, 0x90, 0x95, 0x00, 0x02,\n    0x1f, 0x2a, 0x00, 0x03, 0x1f, 0x2a, 0x3c, 0x01,\n    0x02, 0x0b, 0x1f, 0x00, 0x01, 0x0b, 0x01, 0x02,\n    0x1f, 0x2a, 0x00, 0x01, 0x60, 0x80, 0x44, 0x00,\n    0x01, 0x01, 0x2b, 0x35, 0x00, 0x00, 0x02, 0x1d,\n    0x87, 0x81, 0xb5, 0x00, 0x00, 0x02, 0x45, 0x5b,\n    0x80, 0x3f, 0x00, 0x00, 0x03, 0x1f, 0x2a, 0x45,\n    0x8c, 0xd1, 0x00, 0x00, 0x02, 0x1d, 0x28, 0x81,\n    0x3c, 0x00, 0x01, 0x06, 0x0d, 0x30, 0x2f, 0x35,\n    0x3d, 0x9b, 0x00, 0x05, 0x0d, 0x30, 0x2f, 0x35,\n    0x3d, 0x01, 0x00, 0x00, 0x01, 0x2f, 0x00, 0x00,\n    0x09, 0x06, 0x0d, 0x30, 0x2f, 0x35, 0x3d, 0x9b,\n    0x00, 0x00, 0x00, 0x05, 0x0d, 0x30, 0x2f, 0x35,\n    0x3d, 0x07, 0x06, 0x0d, 0x30, 0x2f, 0x35, 0x3d,\n    0x9b, 0x03, 0x05, 0x0d, 0x30, 0x2f, 0x35, 0x3d,\n    0x09, 0x00, 0x03, 0x02, 0x0d, 0x2f, 0x01, 0x00,\n    0x00, 0x05, 0x0d, 0x30, 0x2f, 0x35, 0x3d, 0x04,\n    0x02, 0x35, 0x3d, 0x00, 0x00, 0x00, 0x05, 0x0d,\n    0x30, 0x2f, 0x35, 0x3d, 0x03, 0x00, 0x01, 0x03,\n    0x2f, 0x35, 0x3d, 0x01, 0x01, 0x2f, 0x58, 0x00,\n    0x03, 0x02, 0x35, 0x3d, 0x02, 0x00, 0x00, 0x02,\n    0x35, 0x3d, 0x59, 0x00, 0x00, 0x06, 0x0d, 0x30,\n    0x2f, 0x35, 0x3d, 0x9b, 0x00, 0x02, 0x35, 0x3d,\n    0x80, 0x12, 0x00, 0x0f, 0x01, 0x2f, 0x1f, 0x00,\n    0x23, 0x01, 0x2f, 0x3b, 0x00, 0x27, 0x01, 0x2f,\n    0x37, 0x00, 0x30, 0x01, 0x2f, 0x0e, 0x00, 0x0b,\n    0x01, 0x2f, 0x32, 0x00, 0x00, 0x01, 0x2f, 0x57,\n    0x00, 0x18, 0x01, 0x2f, 0x09, 0x00, 0x04, 0x01,\n    0x2f, 0x5f, 0x00, 0x1e, 0x01, 0x2f, 0xc0, 0x31,\n    0xef, 0x00, 0x00, 0x02, 0x1d, 0x28, 0x80, 0x0f,\n    0x00, 0x07, 0x02, 0x2f, 0x45, 0x80, 0xa7, 0x00,\n    0x02, 0x0e, 0x1f, 0x21, 0x2c, 0x2e, 0x41, 0x3c,\n    0x3b, 0x4e, 0x4f, 0x5a, 0x60, 0x43, 0x8d, 0x95,\n    0x02, 0x0d, 0x1f, 0x21, 0x2c, 0x2e, 0x41, 0x3c,\n    0x3b, 0x4e, 0x5a, 0x60, 0x43, 0x8d, 0x95, 0x03,\n    0x0b, 0x1f, 0x21, 0x2c, 0x2e, 0x41, 0x3b, 0x4e,\n    0x5a, 0x43, 0x8d, 0x95, 0x80, 0x36, 0x00, 0x00,\n    0x02, 0x0b, 0x1f, 0x00, 0x00, 0x00, 0x02, 0x1f,\n    0x8e, 0x39, 0x00, 0x00, 0x03, 0x3e, 0x45, 0x5e,\n    0x80, 0x1f, 0x00, 0x00, 0x02, 0x10, 0x3a, 0xc0,\n    0x13, 0xa1, 0x00, 0x00, 0x02, 0x04, 0x91, 0x09,\n    0x00, 0x00, 0x02, 0x04, 0x91, 0x46, 0x00, 0x01,\n    0x05, 0x0d, 0x30, 0x2f, 0x35, 0x3d, 0x80, 0x99,\n    0x00, 0x04, 0x06, 0x0d, 0x30, 0x2f, 0x35, 0x3d,\n    0x9b, 0x09, 0x00, 0x00, 0x02, 0x35, 0x3d, 0x2c,\n    0x00, 0x01, 0x02, 0x35, 0x3d, 0x80, 0xdf, 0x00,\n    0x02, 0x02, 0x1c, 0x49, 0x03, 0x00, 0x2c, 0x03,\n    0x1c, 0x48, 0x49, 0x02, 0x00, 0x08, 0x02, 0x1c,\n    0x49, 0x81, 0x1f, 0x00, 0x1b, 0x02, 0x04, 0x1a,\n    0x8f, 0x84, 0x00, 0x00, 0x02, 0x2a, 0x8e, 0x00,\n    0x00, 0x00, 0x02, 0x2a, 0x8e, 0x36, 0x00, 0x01,\n    0x02, 0x2a, 0x8e, 0x8c, 0x12, 0x00, 0x01, 0x02,\n    0x2a, 0x8e, 0x00, 0x00, 0x00, 0x02, 0x2a, 0x8e,\n    0xc0, 0x5c, 0x4b, 0x00, 0x03, 0x01, 0x22, 0x96,\n    0x3b, 0x00, 0x11, 0x01, 0x2f, 0x9e, 0x5d, 0x00,\n    0x01, 0x01, 0x2f, 0xce, 0xcd, 0x2d, 0x00,\n};\n\nstatic const uint8_t unicode_prop_Hyphen_table[28] = {\n    0xac, 0x80, 0xfe, 0x80, 0x44, 0xdb, 0x80, 0x52,\n    0x7a, 0x80, 0x48, 0x08, 0x81, 0x4e, 0x04, 0x80,\n    0x42, 0xe2, 0x80, 0x60, 0xcd, 0x66, 0x80, 0x40,\n    0xa8, 0x80, 0xd6, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Other_Math_table[200] = {\n    0xdd, 0x80, 0x43, 0x70, 0x11, 0x80, 0x99, 0x09,\n    0x81, 0x5c, 0x1f, 0x80, 0x9a, 0x82, 0x8a, 0x80,\n    0x9f, 0x83, 0x97, 0x81, 0x8d, 0x81, 0xc0, 0x8c,\n    0x18, 0x11, 0x1c, 0x91, 0x03, 0x01, 0x89, 0x00,\n    0x14, 0x28, 0x11, 0x09, 0x02, 0x05, 0x13, 0x24,\n    0xca, 0x21, 0x18, 0x08, 0x08, 0x00, 0x21, 0x0b,\n    0x0b, 0x91, 0x09, 0x00, 0x06, 0x00, 0x29, 0x41,\n    0x21, 0x83, 0x40, 0xa7, 0x08, 0x80, 0x97, 0x80,\n    0x90, 0x80, 0x41, 0xbc, 0x81, 0x8b, 0x88, 0x24,\n    0x21, 0x09, 0x14, 0x8d, 0x00, 0x01, 0x85, 0x97,\n    0x81, 0xb8, 0x00, 0x80, 0x9c, 0x83, 0x88, 0x81,\n    0x41, 0x55, 0x81, 0x9e, 0x89, 0x41, 0x92, 0x95,\n    0xbe, 0x83, 0x9f, 0x81, 0x60, 0xd4, 0x62, 0x00,\n    0x03, 0x80, 0x40, 0xd2, 0x00, 0x80, 0x60, 0xd4,\n    0xc0, 0xd4, 0x80, 0xc6, 0x01, 0x08, 0x09, 0x0b,\n    0x80, 0x8b, 0x00, 0x06, 0x80, 0xc0, 0x03, 0x0f,\n    0x06, 0x80, 0x9b, 0x03, 0x04, 0x00, 0x16, 0x80,\n    0x41, 0x53, 0x81, 0x98, 0x80, 0x98, 0x80, 0x9e,\n    0x80, 0x98, 0x80, 0x9e, 0x80, 0x98, 0x80, 0x9e,\n    0x80, 0x98, 0x80, 0x9e, 0x80, 0x98, 0x07, 0x81,\n    0xb1, 0x55, 0xff, 0x18, 0x9a, 0x01, 0x00, 0x08,\n    0x80, 0x89, 0x03, 0x00, 0x00, 0x28, 0x18, 0x00,\n    0x00, 0x02, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00,\n    0x00, 0x01, 0x00, 0x0b, 0x06, 0x03, 0x03, 0x00,\n    0x80, 0x89, 0x80, 0x90, 0x22, 0x04, 0x80, 0x90,\n};\n\nstatic const uint8_t unicode_prop_Other_Alphabetic_table[411] = {\n    0x43, 0x44, 0x80, 0x42, 0x69, 0x8d, 0x00, 0x01,\n    0x01, 0x00, 0xc7, 0x8a, 0xaf, 0x8c, 0x06, 0x8f,\n    0x80, 0xe4, 0x33, 0x19, 0x0b, 0x80, 0xa2, 0x80,\n    0x9d, 0x8f, 0xe5, 0x8a, 0xe4, 0x0a, 0x88, 0x02,\n    0x03, 0x40, 0xa6, 0x8b, 0x16, 0x85, 0x93, 0xb5,\n    0x09, 0x8e, 0x01, 0x22, 0x89, 0x81, 0x9c, 0x82,\n    0xb9, 0x31, 0x09, 0x81, 0x89, 0x80, 0x89, 0x81,\n    0x9c, 0x82, 0xb9, 0x23, 0x09, 0x0b, 0x80, 0x9d,\n    0x0a, 0x80, 0x8a, 0x82, 0xb9, 0x38, 0x10, 0x81,\n    0x94, 0x81, 0x95, 0x13, 0x82, 0xb9, 0x31, 0x09,\n    0x81, 0x88, 0x81, 0x89, 0x81, 0x9d, 0x80, 0xba,\n    0x22, 0x10, 0x82, 0x89, 0x80, 0xa7, 0x83, 0xb9,\n    0x30, 0x10, 0x17, 0x81, 0x8a, 0x81, 0x9c, 0x82,\n    0xb9, 0x30, 0x10, 0x17, 0x81, 0x8a, 0x81, 0x9b,\n    0x83, 0xb9, 0x30, 0x10, 0x82, 0x89, 0x80, 0x89,\n    0x81, 0x9c, 0x82, 0xca, 0x28, 0x00, 0x87, 0x91,\n    0x81, 0xbc, 0x01, 0x86, 0x91, 0x80, 0xe2, 0x01,\n    0x28, 0x81, 0x8f, 0x80, 0x40, 0xa2, 0x90, 0x8a,\n    0x8a, 0x80, 0xa3, 0xed, 0x8b, 0x00, 0x0b, 0x96,\n    0x1b, 0x10, 0x11, 0x32, 0x83, 0x8c, 0x8b, 0x00,\n    0x89, 0x83, 0x46, 0x73, 0x81, 0x9d, 0x81, 0x9d,\n    0x81, 0x9d, 0x81, 0xc1, 0x92, 0x40, 0xbb, 0x81,\n    0xa1, 0x80, 0xf5, 0x8b, 0x83, 0x88, 0x40, 0xdd,\n    0x84, 0xb8, 0x89, 0x81, 0x93, 0xc9, 0x81, 0xbe,\n    0x84, 0xaf, 0x8e, 0xbb, 0x82, 0x9d, 0x88, 0x09,\n    0xb8, 0x8a, 0xb1, 0x92, 0x41, 0xaf, 0x8d, 0x46,\n    0xc0, 0xb3, 0x48, 0xf5, 0x9f, 0x60, 0x78, 0x73,\n    0x87, 0xa1, 0x81, 0x41, 0x61, 0x07, 0x80, 0x96,\n    0x84, 0xd7, 0x81, 0xb1, 0x8f, 0x00, 0xb8, 0x80,\n    0xa5, 0x84, 0x9b, 0x8b, 0xac, 0x83, 0xaf, 0x8b,\n    0xa4, 0x80, 0xc2, 0x8d, 0x8b, 0x07, 0x81, 0xac,\n    0x82, 0xb1, 0x00, 0x11, 0x0c, 0x80, 0xab, 0x24,\n    0x80, 0x40, 0xec, 0x87, 0x60, 0x4f, 0x32, 0x80,\n    0x48, 0x56, 0x84, 0x46, 0x85, 0x10, 0x0c, 0x83,\n    0x43, 0x13, 0x83, 0x41, 0x82, 0x81, 0x41, 0x52,\n    0x82, 0xb4, 0x8d, 0xbb, 0x80, 0xac, 0x88, 0xc6,\n    0x82, 0xa3, 0x8b, 0x91, 0x81, 0xb8, 0x82, 0xaf,\n    0x8c, 0x8d, 0x81, 0xdb, 0x88, 0x08, 0x28, 0x40,\n    0x9f, 0x89, 0x96, 0x83, 0xb9, 0x31, 0x09, 0x81,\n    0x89, 0x80, 0x89, 0x81, 0x40, 0xd0, 0x8c, 0x02,\n    0xe9, 0x91, 0x40, 0xec, 0x31, 0x86, 0x9c, 0x81,\n    0xd1, 0x8e, 0x00, 0xe9, 0x8a, 0xe6, 0x8d, 0x41,\n    0x00, 0x8c, 0x40, 0xf6, 0x28, 0x09, 0x0a, 0x00,\n    0x80, 0x40, 0x8d, 0x31, 0x2b, 0x80, 0x9b, 0x89,\n    0xa9, 0x20, 0x83, 0x91, 0x8a, 0xad, 0x8d, 0x41,\n    0x96, 0x38, 0x86, 0xd2, 0x95, 0x80, 0x8d, 0xf9,\n    0x2a, 0x00, 0x08, 0x10, 0x02, 0x80, 0xc1, 0x20,\n    0x08, 0x83, 0x41, 0x5b, 0x83, 0x60, 0x50, 0x57,\n    0x00, 0xb6, 0x33, 0xdc, 0x81, 0x60, 0x4c, 0xab,\n    0x80, 0x60, 0x23, 0x60, 0x30, 0x90, 0x0e, 0x01,\n    0x04, 0x49, 0x1b, 0x80, 0x47, 0xe7, 0x99, 0x85,\n    0x99, 0x85, 0x99,\n};\n\nstatic const uint8_t unicode_prop_Other_Lowercase_table[51] = {\n    0x40, 0xa9, 0x80, 0x8e, 0x80, 0x41, 0xf4, 0x88,\n    0x31, 0x9d, 0x84, 0xdf, 0x80, 0xb3, 0x80, 0x59,\n    0xb0, 0xbe, 0x8c, 0x80, 0xa1, 0xa4, 0x42, 0xb0,\n    0x80, 0x8c, 0x80, 0x8f, 0x8c, 0x40, 0xd2, 0x8f,\n    0x43, 0x4f, 0x99, 0x47, 0x91, 0x81, 0x60, 0x7a,\n    0x1d, 0x81, 0x40, 0xd1, 0x80, 0x40, 0x86, 0x81,\n    0x43, 0x61, 0x83,\n};\n\nstatic const uint8_t unicode_prop_Other_Uppercase_table[15] = {\n    0x60, 0x21, 0x5f, 0x8f, 0x43, 0x45, 0x99, 0x61,\n    0xcc, 0x5f, 0x99, 0x85, 0x99, 0x85, 0x99,\n};\n\nstatic const uint8_t unicode_prop_Other_Grapheme_Extend_table[65] = {\n    0x49, 0xbd, 0x80, 0x97, 0x80, 0x41, 0x65, 0x80,\n    0x97, 0x80, 0xe5, 0x80, 0x97, 0x80, 0x40, 0xe9,\n    0x80, 0x91, 0x81, 0xe6, 0x80, 0x97, 0x80, 0xf6,\n    0x80, 0x8e, 0x80, 0x4d, 0x54, 0x80, 0x44, 0xd5,\n    0x80, 0x50, 0x20, 0x81, 0x60, 0xcf, 0x6d, 0x81,\n    0x53, 0x9d, 0x80, 0x97, 0x80, 0x41, 0x57, 0x80,\n    0x8b, 0x80, 0x40, 0xf0, 0x80, 0x43, 0x7f, 0x80,\n    0x60, 0xb8, 0x33, 0x07, 0x84, 0x6c, 0x2e, 0xac,\n    0xdf,\n};\n\nstatic const uint8_t unicode_prop_Other_Default_Ignorable_Code_Point_table[32] = {\n    0x43, 0x4e, 0x80, 0x4e, 0x0e, 0x81, 0x46, 0x52,\n    0x81, 0x48, 0xae, 0x80, 0x50, 0xfd, 0x80, 0x60,\n    0xce, 0x3a, 0x80, 0xce, 0x88, 0x6d, 0x00, 0x06,\n    0x00, 0x9d, 0xdf, 0xff, 0x40, 0xef, 0x4e, 0x0f,\n};\n\nstatic const uint8_t unicode_prop_Other_ID_Start_table[11] = {\n    0x58, 0x84, 0x81, 0x48, 0x90, 0x80, 0x94, 0x80,\n    0x4f, 0x6b, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Other_ID_Continue_table[12] = {\n    0x40, 0xb6, 0x80, 0x42, 0xce, 0x80, 0x4f, 0xe0,\n    0x88, 0x46, 0x67, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Prepended_Concatenation_Mark_table[17] = {\n    0x45, 0xff, 0x85, 0x40, 0xd6, 0x80, 0xb0, 0x80,\n    0x41, 0xd1, 0x80, 0x61, 0x07, 0xd9, 0x80, 0x8e,\n    0x80,\n};\n\nstatic const uint8_t unicode_prop_XID_Start1_table[31] = {\n    0x43, 0x79, 0x80, 0x4a, 0xb7, 0x80, 0xfe, 0x80,\n    0x60, 0x21, 0xe6, 0x81, 0x60, 0xcb, 0xc0, 0x85,\n    0x41, 0x95, 0x81, 0xf3, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x80, 0x41, 0x1e, 0x81,\n};\n\nstatic const uint8_t unicode_prop_XID_Continue1_table[23] = {\n    0x43, 0x79, 0x80, 0x60, 0x2d, 0x1f, 0x81, 0x60,\n    0xcb, 0xc0, 0x85, 0x41, 0x95, 0x81, 0xf3, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Changes_When_Titlecased1_table[22] = {\n    0x41, 0xc3, 0x08, 0x08, 0x81, 0xa4, 0x81, 0x4e,\n    0xdc, 0xaa, 0x0a, 0x4e, 0x87, 0x3f, 0x3f, 0x87,\n    0x8b, 0x80, 0x8e, 0x80, 0xae, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Changes_When_Casefolded1_table[33] = {\n    0x40, 0xde, 0x80, 0xcf, 0x80, 0x97, 0x80, 0x44,\n    0x3c, 0x80, 0x59, 0x11, 0x80, 0x40, 0xe4, 0x3f,\n    0x3f, 0x87, 0x89, 0x11, 0x05, 0x02, 0x11, 0x80,\n    0xa9, 0x11, 0x80, 0x60, 0xdb, 0x07, 0x86, 0x8b,\n    0x84,\n};\n\nstatic const uint8_t unicode_prop_Changes_When_NFKC_Casefolded1_table[441] = {\n    0x40, 0x9f, 0x06, 0x00, 0x01, 0x00, 0x01, 0x12,\n    0x10, 0x82, 0x9f, 0x80, 0xcf, 0x01, 0x80, 0x8b,\n    0x07, 0x80, 0xfb, 0x01, 0x01, 0x80, 0xa5, 0x80,\n    0x40, 0xbb, 0x88, 0x9e, 0x29, 0x84, 0xda, 0x08,\n    0x81, 0x89, 0x80, 0xa3, 0x04, 0x02, 0x04, 0x08,\n    0x80, 0xc9, 0x82, 0x9c, 0x80, 0x41, 0x93, 0x80,\n    0x40, 0x93, 0x80, 0xd7, 0x83, 0x42, 0xde, 0x87,\n    0xfb, 0x08, 0x80, 0xd2, 0x01, 0x80, 0xa1, 0x11,\n    0x80, 0x40, 0xfc, 0x81, 0x42, 0xd4, 0x80, 0xfe,\n    0x80, 0xa7, 0x81, 0xad, 0x80, 0xb5, 0x80, 0x88,\n    0x03, 0x03, 0x03, 0x80, 0x8b, 0x80, 0x88, 0x00,\n    0x26, 0x80, 0x90, 0x80, 0x88, 0x03, 0x03, 0x03,\n    0x80, 0x8b, 0x80, 0x41, 0x41, 0x80, 0xe1, 0x81,\n    0x46, 0x52, 0x81, 0xd4, 0x83, 0x45, 0x1c, 0x10,\n    0x8a, 0x80, 0x91, 0x80, 0x9b, 0x8c, 0x80, 0xa1,\n    0xa4, 0x40, 0xd9, 0x80, 0x40, 0xd5, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x01, 0x3f, 0x3f, 0x87,\n    0x89, 0x11, 0x04, 0x00, 0x29, 0x04, 0x12, 0x80,\n    0x88, 0x12, 0x80, 0x88, 0x11, 0x11, 0x04, 0x08,\n    0x8f, 0x00, 0x20, 0x8b, 0x12, 0x2a, 0x08, 0x0b,\n    0x00, 0x07, 0x82, 0x8c, 0x06, 0x92, 0x81, 0x9a,\n    0x80, 0x8c, 0x8a, 0x80, 0xd6, 0x18, 0x10, 0x8a,\n    0x01, 0x0c, 0x0a, 0x00, 0x10, 0x11, 0x02, 0x06,\n    0x05, 0x1c, 0x85, 0x8f, 0x8f, 0x8f, 0x88, 0x80,\n    0x40, 0xa1, 0x08, 0x81, 0x40, 0xf7, 0x81, 0x41,\n    0x34, 0xd5, 0x99, 0x9a, 0x45, 0x20, 0x80, 0xe6,\n    0x82, 0xe4, 0x80, 0x41, 0x9e, 0x81, 0x40, 0xf0,\n    0x80, 0x41, 0x2e, 0x80, 0xd2, 0x80, 0x8b, 0x40,\n    0xd5, 0xa9, 0x80, 0xb4, 0x00, 0x82, 0xdf, 0x09,\n    0x80, 0xde, 0x80, 0xb0, 0xdd, 0x82, 0x8d, 0xdf,\n    0x9e, 0x80, 0xa7, 0x87, 0xae, 0x80, 0x41, 0x7f,\n    0x60, 0x72, 0x9b, 0x81, 0x40, 0xd1, 0x80, 0x40,\n    0x86, 0x81, 0x43, 0x61, 0x83, 0x88, 0x80, 0x60,\n    0x4d, 0x95, 0x41, 0x0d, 0x08, 0x00, 0x81, 0x89,\n    0x00, 0x00, 0x09, 0x82, 0xc3, 0x81, 0xe9, 0xa5,\n    0x86, 0x8b, 0x24, 0x00, 0x97, 0x04, 0x00, 0x01,\n    0x01, 0x80, 0xeb, 0xa0, 0x41, 0x6a, 0x91, 0xbf,\n    0x81, 0xb5, 0xa7, 0x8c, 0x82, 0x99, 0x95, 0x94,\n    0x81, 0x8b, 0x80, 0x92, 0x03, 0x1a, 0x00, 0x80,\n    0x40, 0x86, 0x08, 0x80, 0x9f, 0x99, 0x40, 0x83,\n    0x15, 0x0d, 0x0d, 0x0a, 0x16, 0x06, 0x80, 0x88,\n    0x60, 0xbc, 0xa6, 0x83, 0x54, 0xb9, 0x86, 0x8d,\n    0x87, 0xbf, 0x85, 0x42, 0x3e, 0xd4, 0x80, 0xc6,\n    0x01, 0x08, 0x09, 0x0b, 0x80, 0x8b, 0x00, 0x06,\n    0x80, 0xc0, 0x03, 0x0f, 0x06, 0x80, 0x9b, 0x03,\n    0x04, 0x00, 0x16, 0x80, 0x41, 0x53, 0x81, 0x41,\n    0x23, 0x81, 0xb1, 0x55, 0xff, 0x18, 0x9a, 0x01,\n    0x00, 0x08, 0x80, 0x89, 0x03, 0x00, 0x00, 0x28,\n    0x18, 0x00, 0x00, 0x02, 0x01, 0x00, 0x08, 0x00,\n    0x00, 0x00, 0x00, 0x01, 0x00, 0x0b, 0x06, 0x03,\n    0x03, 0x00, 0x80, 0x89, 0x80, 0x90, 0x22, 0x04,\n    0x80, 0x90, 0x42, 0x43, 0x8a, 0x84, 0x9e, 0x80,\n    0x9f, 0x99, 0x82, 0xa2, 0x80, 0xee, 0x82, 0x8c,\n    0xab, 0x83, 0x88, 0x31, 0x49, 0x9d, 0x89, 0x60,\n    0xfc, 0x05, 0x42, 0x1d, 0x6b, 0x05, 0xe1, 0x4f,\n    0xff,\n};\n\nstatic const uint8_t unicode_prop_ASCII_Hex_Digit_table[5] = {\n    0xaf, 0x89, 0x35, 0x99, 0x85,\n};\n\nstatic const uint8_t unicode_prop_Bidi_Control_table[10] = {\n    0x46, 0x1b, 0x80, 0x59, 0xf0, 0x81, 0x99, 0x84,\n    0xb6, 0x83,\n};\n\nstatic const uint8_t unicode_prop_Dash_table[53] = {\n    0xac, 0x80, 0x45, 0x5b, 0x80, 0xb2, 0x80, 0x4e,\n    0x40, 0x80, 0x44, 0x04, 0x80, 0x48, 0x08, 0x85,\n    0xbc, 0x80, 0xa6, 0x80, 0x8e, 0x80, 0x41, 0x85,\n    0x80, 0x4c, 0x03, 0x01, 0x80, 0x9e, 0x0b, 0x80,\n    0x41, 0xda, 0x80, 0x92, 0x80, 0xee, 0x80, 0x60,\n    0xcd, 0x8f, 0x81, 0xa4, 0x80, 0x89, 0x80, 0x40,\n    0xa8, 0x80, 0x4f, 0x9e, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Deprecated_table[23] = {\n    0x41, 0x48, 0x80, 0x45, 0x28, 0x80, 0x49, 0x02,\n    0x00, 0x80, 0x48, 0x28, 0x81, 0x48, 0xc4, 0x85,\n    0x42, 0xb8, 0x81, 0x6d, 0xdc, 0xd5, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Diacritic_table[358] = {\n    0xdd, 0x00, 0x80, 0xc6, 0x05, 0x03, 0x01, 0x81,\n    0x41, 0xf6, 0x40, 0x9e, 0x07, 0x25, 0x90, 0x0b,\n    0x80, 0x88, 0x81, 0x40, 0xfc, 0x84, 0x40, 0xd0,\n    0x80, 0xb6, 0x90, 0x80, 0x9a, 0x00, 0x01, 0x00,\n    0x40, 0x85, 0x3b, 0x81, 0x40, 0x85, 0x0b, 0x0a,\n    0x82, 0xc2, 0x9a, 0xda, 0x8a, 0xb9, 0x8a, 0xa1,\n    0x81, 0x40, 0xc8, 0x9b, 0xbc, 0x80, 0x8f, 0x02,\n    0x83, 0x9b, 0x80, 0xc9, 0x80, 0x8f, 0x80, 0xed,\n    0x80, 0x8f, 0x80, 0xed, 0x80, 0x8f, 0x80, 0xae,\n    0x82, 0xbb, 0x80, 0x8f, 0x06, 0x80, 0xf6, 0x80,\n    0xfe, 0x80, 0xed, 0x80, 0x8f, 0x80, 0xec, 0x81,\n    0x8f, 0x80, 0xfb, 0x80, 0xfb, 0x28, 0x80, 0xea,\n    0x80, 0x8c, 0x84, 0xca, 0x81, 0x9a, 0x00, 0x00,\n    0x03, 0x81, 0xc1, 0x10, 0x81, 0xbd, 0x80, 0xef,\n    0x00, 0x81, 0xa7, 0x0b, 0x84, 0x98, 0x30, 0x80,\n    0x89, 0x81, 0x42, 0xc0, 0x82, 0x44, 0x68, 0x8a,\n    0x88, 0x80, 0x41, 0x5a, 0x82, 0x41, 0x38, 0x39,\n    0x80, 0xaf, 0x8d, 0xf5, 0x80, 0x8e, 0x80, 0xa5,\n    0x88, 0xb5, 0x81, 0x40, 0x89, 0x81, 0xbf, 0x85,\n    0xd1, 0x98, 0x18, 0x28, 0x0a, 0xb1, 0xbe, 0xd8,\n    0x8b, 0xa4, 0x22, 0x82, 0x41, 0xbc, 0x00, 0x82,\n    0x8a, 0x82, 0x8c, 0x82, 0x8c, 0x82, 0x8c, 0x81,\n    0x4c, 0xef, 0x82, 0x41, 0x3c, 0x80, 0x41, 0xf9,\n    0x85, 0xe8, 0x83, 0xde, 0x80, 0x60, 0x75, 0x71,\n    0x80, 0x8b, 0x08, 0x80, 0x9b, 0x81, 0xd1, 0x81,\n    0x8d, 0xa1, 0xe5, 0x82, 0xec, 0x81, 0x40, 0xc9,\n    0x80, 0x9a, 0x91, 0xb8, 0x83, 0xa3, 0x80, 0xde,\n    0x80, 0x8b, 0x80, 0xa3, 0x80, 0x40, 0x94, 0x82,\n    0xc0, 0x83, 0xb2, 0x80, 0xe3, 0x84, 0x88, 0x82,\n    0xff, 0x81, 0x60, 0x4f, 0x2f, 0x80, 0x43, 0x00,\n    0x8f, 0x41, 0x0d, 0x00, 0x80, 0xae, 0x80, 0xac,\n    0x81, 0xc2, 0x80, 0x42, 0xfb, 0x80, 0x48, 0x03,\n    0x81, 0x42, 0x3a, 0x85, 0x42, 0x1d, 0x8a, 0x41,\n    0x67, 0x81, 0xf7, 0x81, 0xbd, 0x80, 0xcb, 0x80,\n    0x88, 0x82, 0xe7, 0x81, 0x40, 0xb1, 0x81, 0xd0,\n    0x80, 0x8f, 0x80, 0x97, 0x32, 0x84, 0x40, 0xcc,\n    0x02, 0x80, 0xfa, 0x81, 0x40, 0xfa, 0x81, 0xfd,\n    0x80, 0xf5, 0x81, 0xf2, 0x80, 0x41, 0x0c, 0x81,\n    0x41, 0x01, 0x0b, 0x80, 0x40, 0x9b, 0x80, 0xd2,\n    0x80, 0x91, 0x80, 0xd0, 0x80, 0x41, 0xa4, 0x80,\n    0x41, 0x01, 0x00, 0x81, 0xd0, 0x80, 0x60, 0x4d,\n    0x57, 0x84, 0xba, 0x86, 0x44, 0x57, 0x90, 0xcf,\n    0x81, 0x60, 0x61, 0x74, 0x12, 0x2f, 0x39, 0x86,\n    0x9d, 0x83, 0x4f, 0x81, 0x86, 0x41, 0xb4, 0x83,\n    0x45, 0xdf, 0x86, 0xec, 0x10, 0x82,\n};\n\nstatic const uint8_t unicode_prop_Extender_table[89] = {\n    0x40, 0xb6, 0x80, 0x42, 0x17, 0x81, 0x43, 0x6d,\n    0x80, 0x41, 0xb8, 0x80, 0x43, 0x59, 0x80, 0x42,\n    0xef, 0x80, 0xfe, 0x80, 0x49, 0x42, 0x80, 0xb7,\n    0x80, 0x42, 0x62, 0x80, 0x41, 0x8d, 0x80, 0xc3,\n    0x80, 0x53, 0x88, 0x80, 0xaa, 0x84, 0xe6, 0x81,\n    0xdc, 0x82, 0x60, 0x6f, 0x15, 0x80, 0x45, 0xf5,\n    0x80, 0x43, 0xc1, 0x80, 0x95, 0x80, 0x40, 0x88,\n    0x80, 0xeb, 0x80, 0x94, 0x81, 0x60, 0x54, 0x7a,\n    0x80, 0x53, 0xeb, 0x80, 0x42, 0x67, 0x82, 0x44,\n    0xce, 0x80, 0x60, 0x50, 0xa8, 0x81, 0x44, 0x9b,\n    0x08, 0x80, 0x60, 0x71, 0x57, 0x81, 0x48, 0x05,\n    0x82,\n};\n\nstatic const uint8_t unicode_prop_Hex_Digit_table[12] = {\n    0xaf, 0x89, 0x35, 0x99, 0x85, 0x60, 0xfe, 0xa8,\n    0x89, 0x35, 0x99, 0x85,\n};\n\nstatic const uint8_t unicode_prop_IDS_Binary_Operator_table[5] = {\n    0x60, 0x2f, 0xef, 0x09, 0x87,\n};\n\nstatic const uint8_t unicode_prop_IDS_Trinary_Operator_table[4] = {\n    0x60, 0x2f, 0xf1, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Ideographic_table[66] = {\n    0x60, 0x30, 0x05, 0x81, 0x98, 0x88, 0x8d, 0x82,\n    0x43, 0xc4, 0x59, 0xbf, 0xbf, 0x60, 0x51, 0xfc,\n    0x60, 0x59, 0x02, 0x41, 0x6d, 0x81, 0xe9, 0x60,\n    0x75, 0x09, 0x80, 0x9a, 0x57, 0xf7, 0x87, 0x44,\n    0xd5, 0xa9, 0x88, 0x60, 0x24, 0x66, 0x41, 0x8b,\n    0x60, 0x4d, 0x03, 0x60, 0xa6, 0xdd, 0xa1, 0x50,\n    0x34, 0x8a, 0x40, 0xdd, 0x81, 0x56, 0x81, 0x8d,\n    0x5d, 0x30, 0x4c, 0x1e, 0x42, 0x1d, 0x45, 0xe1,\n    0x53, 0x4a,\n};\n\nstatic const uint8_t unicode_prop_Join_Control_table[4] = {\n    0x60, 0x20, 0x0b, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Logical_Order_Exception_table[15] = {\n    0x4e, 0x3f, 0x84, 0xfa, 0x84, 0x4a, 0xef, 0x11,\n    0x80, 0x60, 0x90, 0xf9, 0x09, 0x00, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Noncharacter_Code_Point_table[71] = {\n    0x60, 0xfd, 0xcf, 0x9f, 0x42, 0x0d, 0x81, 0x60,\n    0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,\n    0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,\n    0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,\n    0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,\n    0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,\n    0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,\n    0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81, 0x60,\n    0xff, 0xfd, 0x81, 0x60, 0xff, 0xfd, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Pattern_Syntax_table[58] = {\n    0xa0, 0x8e, 0x89, 0x86, 0x99, 0x18, 0x80, 0x99,\n    0x83, 0xa1, 0x30, 0x00, 0x08, 0x00, 0x0b, 0x03,\n    0x02, 0x80, 0x96, 0x80, 0x9e, 0x80, 0x5f, 0x17,\n    0x97, 0x87, 0x8e, 0x81, 0x92, 0x80, 0x89, 0x41,\n    0x30, 0x42, 0xcf, 0x40, 0x9f, 0x42, 0x75, 0x9d,\n    0x44, 0x6b, 0x41, 0xff, 0xff, 0x41, 0x80, 0x13,\n    0x98, 0x8e, 0x80, 0x60, 0xcd, 0x0c, 0x81, 0x41,\n    0x04, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Pattern_White_Space_table[11] = {\n    0x88, 0x84, 0x91, 0x80, 0xe3, 0x80, 0x5f, 0x87,\n    0x81, 0x97, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Quotation_Mark_table[31] = {\n    0xa1, 0x03, 0x80, 0x40, 0x82, 0x80, 0x8e, 0x80,\n    0x5f, 0x5b, 0x87, 0x98, 0x81, 0x4e, 0x06, 0x80,\n    0x41, 0xc8, 0x83, 0x8c, 0x82, 0x60, 0xce, 0x20,\n    0x83, 0x40, 0xbc, 0x03, 0x80, 0xd9, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Radical_table[9] = {\n    0x60, 0x2e, 0x7f, 0x99, 0x80, 0xd8, 0x8b, 0x40,\n    0xd5,\n};\n\nstatic const uint8_t unicode_prop_Regional_Indicator_table[4] = {\n    0x61, 0xf1, 0xe5, 0x99,\n};\n\nstatic const uint8_t unicode_prop_Sentence_Terminal_table[188] = {\n    0xa0, 0x80, 0x8b, 0x80, 0x8f, 0x80, 0x45, 0x48,\n    0x80, 0x40, 0x93, 0x81, 0x40, 0xb3, 0x80, 0xaa,\n    0x82, 0x40, 0xf5, 0x80, 0xbc, 0x00, 0x02, 0x81,\n    0x41, 0x24, 0x81, 0x46, 0xe3, 0x81, 0x43, 0x15,\n    0x03, 0x81, 0x43, 0x04, 0x80, 0x40, 0xc5, 0x81,\n    0x40, 0xcb, 0x04, 0x80, 0x41, 0x39, 0x81, 0x41,\n    0x61, 0x83, 0x40, 0xad, 0x09, 0x81, 0x40, 0xda,\n    0x81, 0xc0, 0x81, 0x43, 0xbb, 0x81, 0x88, 0x82,\n    0x4d, 0xe3, 0x80, 0x8c, 0x80, 0x41, 0xc4, 0x80,\n    0x60, 0x74, 0xfb, 0x80, 0x41, 0x0d, 0x81, 0x40,\n    0xe2, 0x02, 0x80, 0x41, 0x7d, 0x81, 0xd5, 0x81,\n    0xde, 0x80, 0x40, 0x97, 0x81, 0x40, 0x92, 0x82,\n    0x40, 0x8f, 0x81, 0x40, 0xf8, 0x80, 0x60, 0x52,\n    0x65, 0x02, 0x81, 0x40, 0xa8, 0x80, 0x8b, 0x80,\n    0x8f, 0x80, 0xc0, 0x80, 0x4a, 0xf3, 0x81, 0x44,\n    0xfc, 0x84, 0x40, 0xec, 0x81, 0xf4, 0x83, 0xfe,\n    0x82, 0x40, 0x80, 0x0d, 0x80, 0x8f, 0x81, 0xd7,\n    0x08, 0x81, 0xeb, 0x80, 0x41, 0xa0, 0x81, 0x41,\n    0x74, 0x0c, 0x8e, 0xe8, 0x81, 0x40, 0xf8, 0x82,\n    0x42, 0x04, 0x00, 0x80, 0x40, 0xfa, 0x81, 0xd6,\n    0x81, 0x41, 0xa3, 0x81, 0x42, 0xb3, 0x81, 0x60,\n    0x4b, 0x74, 0x81, 0x40, 0x84, 0x80, 0xc0, 0x81,\n    0x8a, 0x80, 0x43, 0x52, 0x80, 0x60, 0x4e, 0x05,\n    0x80, 0x5d, 0xe7, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Soft_Dotted_table[71] = {\n    0xe8, 0x81, 0x40, 0xc3, 0x80, 0x41, 0x18, 0x80,\n    0x9d, 0x80, 0xb3, 0x80, 0x93, 0x80, 0x41, 0x3f,\n    0x80, 0xe1, 0x00, 0x80, 0x59, 0x08, 0x80, 0xb2,\n    0x80, 0x8c, 0x02, 0x80, 0x40, 0x83, 0x80, 0x40,\n    0x9c, 0x80, 0x41, 0xa4, 0x80, 0x40, 0xd5, 0x81,\n    0x4b, 0x31, 0x80, 0x61, 0xa7, 0xa4, 0x81, 0xb1,\n    0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1,\n    0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1,\n    0x81, 0xb1, 0x81, 0xb1, 0x81, 0xb1, 0x81,\n};\n\nstatic const uint8_t unicode_prop_Terminal_Punctuation_table[241] = {\n    0xa0, 0x80, 0x89, 0x00, 0x80, 0x8a, 0x0a, 0x80,\n    0x43, 0x3d, 0x07, 0x80, 0x42, 0x00, 0x80, 0xb8,\n    0x80, 0xc7, 0x80, 0x8d, 0x01, 0x81, 0x40, 0xb3,\n    0x80, 0xaa, 0x8a, 0x00, 0x40, 0xea, 0x81, 0xb5,\n    0x8e, 0x9e, 0x80, 0x41, 0x04, 0x81, 0x44, 0xf3,\n    0x81, 0x40, 0xab, 0x03, 0x85, 0x41, 0x36, 0x81,\n    0x43, 0x14, 0x87, 0x43, 0x04, 0x80, 0xfb, 0x82,\n    0xc6, 0x81, 0x40, 0x9c, 0x12, 0x80, 0xa6, 0x19,\n    0x81, 0x41, 0x39, 0x81, 0x41, 0x61, 0x83, 0x40,\n    0xad, 0x08, 0x82, 0x40, 0xda, 0x84, 0xbd, 0x81,\n    0x43, 0xbb, 0x81, 0x88, 0x82, 0x4d, 0xe3, 0x80,\n    0x8c, 0x03, 0x80, 0x89, 0x00, 0x81, 0x41, 0xb0,\n    0x81, 0x60, 0x74, 0xfa, 0x81, 0x41, 0x0c, 0x82,\n    0x40, 0xe2, 0x84, 0x41, 0x7d, 0x81, 0xd5, 0x81,\n    0xde, 0x80, 0x40, 0x96, 0x82, 0x40, 0x92, 0x82,\n    0xfe, 0x80, 0x8f, 0x81, 0x40, 0xf8, 0x80, 0x60,\n    0x52, 0x63, 0x10, 0x83, 0x40, 0xa8, 0x80, 0x89,\n    0x00, 0x80, 0x8a, 0x0a, 0x80, 0xc0, 0x01, 0x80,\n    0x44, 0x39, 0x80, 0xaf, 0x80, 0x44, 0x85, 0x80,\n    0x40, 0xc6, 0x80, 0x41, 0x35, 0x81, 0x40, 0x97,\n    0x85, 0xc3, 0x85, 0xd8, 0x83, 0x43, 0xb7, 0x84,\n    0x40, 0xec, 0x86, 0xef, 0x83, 0xfe, 0x82, 0x40,\n    0x80, 0x0d, 0x80, 0x8f, 0x81, 0xd7, 0x84, 0xeb,\n    0x80, 0x41, 0xa0, 0x82, 0x8b, 0x81, 0x41, 0x65,\n    0x1a, 0x8e, 0xe8, 0x81, 0x40, 0xf8, 0x82, 0x42,\n    0x04, 0x00, 0x80, 0x40, 0xfa, 0x81, 0xd6, 0x0b,\n    0x81, 0x41, 0x9d, 0x82, 0xac, 0x80, 0x42, 0x84,\n    0x81, 0x45, 0x76, 0x84, 0x60, 0x45, 0xf8, 0x81,\n    0x40, 0x84, 0x80, 0xc0, 0x82, 0x89, 0x80, 0x43,\n    0x51, 0x81, 0x60, 0x4e, 0x05, 0x80, 0x5d, 0xe6,\n    0x83,\n};\n\nstatic const uint8_t unicode_prop_Unified_Ideograph_table[42] = {\n    0x60, 0x33, 0xff, 0x59, 0xbf, 0xbf, 0x60, 0x51,\n    0xfc, 0x60, 0x5a, 0x10, 0x08, 0x00, 0x81, 0x89,\n    0x00, 0x00, 0x09, 0x82, 0x61, 0x05, 0xd5, 0x60,\n    0xa6, 0xdd, 0xa1, 0x50, 0x34, 0x8a, 0x40, 0xdd,\n    0x81, 0x56, 0x81, 0x8d, 0x5d, 0x30, 0x54, 0x1e,\n    0x53, 0x4a,\n};\n\nstatic const uint8_t unicode_prop_Variation_Selector_table[12] = {\n    0x58, 0x0a, 0x82, 0x60, 0xe5, 0xf1, 0x8f, 0x6d,\n    0x02, 0xef, 0x40, 0xef,\n};\n\nstatic const uint8_t unicode_prop_White_Space_table[22] = {\n    0x88, 0x84, 0x91, 0x80, 0xe3, 0x80, 0x99, 0x80,\n    0x55, 0xde, 0x80, 0x49, 0x7e, 0x8a, 0x9c, 0x0c,\n    0x80, 0xae, 0x80, 0x4f, 0x9f, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Bidi_Mirrored_table[171] = {\n    0xa7, 0x81, 0x91, 0x00, 0x80, 0x9b, 0x00, 0x80,\n    0x9c, 0x00, 0x80, 0xac, 0x80, 0x8e, 0x80, 0x4e,\n    0x7d, 0x83, 0x47, 0x5c, 0x81, 0x49, 0x9b, 0x81,\n    0x89, 0x81, 0xb5, 0x81, 0x8d, 0x81, 0x40, 0xb0,\n    0x80, 0x40, 0xbf, 0x1a, 0x2a, 0x02, 0x0a, 0x18,\n    0x18, 0x00, 0x03, 0x88, 0x20, 0x80, 0x91, 0x23,\n    0x88, 0x08, 0x00, 0x39, 0x9e, 0x0b, 0x20, 0x88,\n    0x09, 0x92, 0x21, 0x88, 0x21, 0x0b, 0x97, 0x81,\n    0x8f, 0x3b, 0x93, 0x0e, 0x81, 0x44, 0x3c, 0x8d,\n    0xc9, 0x01, 0x18, 0x08, 0x14, 0x1c, 0x12, 0x8d,\n    0x41, 0x92, 0x95, 0x0d, 0x80, 0x8d, 0x38, 0x35,\n    0x10, 0x1c, 0x01, 0x0c, 0x18, 0x02, 0x09, 0x89,\n    0x29, 0x81, 0x8b, 0x92, 0x03, 0x08, 0x00, 0x08,\n    0x03, 0x21, 0x2a, 0x97, 0x81, 0x8a, 0x0b, 0x18,\n    0x09, 0x0b, 0xaa, 0x0f, 0x80, 0xa7, 0x20, 0x00,\n    0x14, 0x22, 0x18, 0x14, 0x00, 0x40, 0xff, 0x80,\n    0x42, 0x02, 0x1a, 0x08, 0x81, 0x8d, 0x09, 0x89,\n    0x41, 0xdd, 0x89, 0x0f, 0x60, 0xce, 0x3c, 0x2c,\n    0x81, 0x40, 0xa1, 0x81, 0x91, 0x00, 0x80, 0x9b,\n    0x00, 0x80, 0x9c, 0x00, 0x00, 0x08, 0x81, 0x60,\n    0xd7, 0x76, 0x80, 0xb8, 0x80, 0xb8, 0x80, 0xb8,\n    0x80, 0xb8, 0x80,\n};\n\nstatic const uint8_t unicode_prop_Emoji_table[238] = {\n    0xa2, 0x05, 0x04, 0x89, 0xee, 0x03, 0x80, 0x5f,\n    0x8c, 0x80, 0x8b, 0x80, 0x40, 0xd7, 0x80, 0x95,\n    0x80, 0xd9, 0x85, 0x8e, 0x81, 0x41, 0x6e, 0x81,\n    0x8b, 0x80, 0x40, 0xa5, 0x80, 0x98, 0x8a, 0x1a,\n    0x40, 0xc6, 0x80, 0x40, 0xe6, 0x81, 0x89, 0x80,\n    0x88, 0x80, 0xb9, 0x18, 0x84, 0x88, 0x01, 0x01,\n    0x09, 0x03, 0x01, 0x00, 0x09, 0x02, 0x02, 0x0f,\n    0x14, 0x00, 0x04, 0x8b, 0x8a, 0x09, 0x00, 0x08,\n    0x80, 0x91, 0x01, 0x81, 0x91, 0x28, 0x00, 0x0a,\n    0x0c, 0x01, 0x0b, 0x81, 0x8a, 0x0c, 0x09, 0x04,\n    0x08, 0x00, 0x81, 0x93, 0x0c, 0x28, 0x19, 0x03,\n    0x01, 0x01, 0x28, 0x01, 0x00, 0x00, 0x05, 0x02,\n    0x05, 0x80, 0x89, 0x81, 0x8e, 0x01, 0x03, 0x00,\n    0x03, 0x10, 0x80, 0x8a, 0x81, 0xaf, 0x82, 0x88,\n    0x80, 0x8d, 0x80, 0x8d, 0x80, 0x41, 0x73, 0x81,\n    0x41, 0xce, 0x82, 0x92, 0x81, 0xb2, 0x03, 0x80,\n    0x44, 0xd9, 0x80, 0x8b, 0x80, 0x42, 0x58, 0x00,\n    0x80, 0x61, 0xbd, 0x69, 0x80, 0x40, 0xc9, 0x80,\n    0x40, 0x9f, 0x81, 0x8b, 0x81, 0x8d, 0x01, 0x89,\n    0xca, 0x99, 0x01, 0x96, 0x80, 0x93, 0x01, 0x88,\n    0x94, 0x81, 0x40, 0xad, 0xa1, 0x81, 0xef, 0x09,\n    0x02, 0x81, 0xd2, 0x0a, 0x80, 0x41, 0x06, 0x80,\n    0xbe, 0x8a, 0x28, 0x97, 0x31, 0x0f, 0x8b, 0x01,\n    0x19, 0x03, 0x81, 0x8c, 0x09, 0x07, 0x81, 0x88,\n    0x04, 0x82, 0x8b, 0x17, 0x11, 0x00, 0x03, 0x05,\n    0x02, 0x05, 0xd5, 0xaf, 0xc5, 0x27, 0x0a, 0x3d,\n    0x10, 0x01, 0x10, 0x81, 0x89, 0x40, 0xe2, 0x8b,\n    0x41, 0x1f, 0xae, 0x80, 0x89, 0x80, 0xb1, 0x80,\n    0xd1, 0x80, 0xb2, 0xef, 0x22, 0x14, 0x86, 0x88,\n    0x98, 0x36, 0x88, 0x82, 0x8c, 0x86,\n};\n\nstatic const uint8_t unicode_prop_Emoji_Component_table[28] = {\n    0xa2, 0x05, 0x04, 0x89, 0x5f, 0xd2, 0x80, 0x40,\n    0xd4, 0x80, 0x60, 0xdd, 0x2a, 0x80, 0x60, 0xf3,\n    0xd5, 0x99, 0x41, 0xfa, 0x84, 0x45, 0xaf, 0x83,\n    0x6c, 0x06, 0x6b, 0xdf,\n};\n\nstatic const uint8_t unicode_prop_Emoji_Modifier_table[4] = {\n    0x61, 0xf3, 0xfa, 0x84,\n};\n\nstatic const uint8_t unicode_prop_Emoji_Modifier_Base_table[66] = {\n    0x60, 0x26, 0x1c, 0x80, 0x40, 0xda, 0x80, 0x8f,\n    0x83, 0x61, 0xcc, 0x76, 0x80, 0xbb, 0x11, 0x01,\n    0x82, 0xf4, 0x09, 0x8a, 0x94, 0x92, 0x10, 0x1a,\n    0x02, 0x30, 0x00, 0x97, 0x80, 0x40, 0xc8, 0x0b,\n    0x80, 0x94, 0x03, 0x81, 0x40, 0xad, 0x12, 0x84,\n    0xd2, 0x80, 0x8f, 0x82, 0x88, 0x80, 0x8a, 0x80,\n    0x42, 0x3e, 0x01, 0x07, 0x3d, 0x80, 0x88, 0x89,\n    0x0a, 0xb7, 0x80, 0xbc, 0x08, 0x08, 0x80, 0x90,\n    0x10, 0x8c,\n};\n\nstatic const uint8_t unicode_prop_Emoji_Presentation_table[144] = {\n    0x60, 0x23, 0x19, 0x81, 0x40, 0xcc, 0x1a, 0x01,\n    0x80, 0x42, 0x08, 0x81, 0x94, 0x81, 0xb1, 0x8b,\n    0xaa, 0x80, 0x92, 0x80, 0x8c, 0x07, 0x81, 0x90,\n    0x0c, 0x0f, 0x04, 0x80, 0x94, 0x06, 0x08, 0x03,\n    0x01, 0x06, 0x03, 0x81, 0x9b, 0x80, 0xa2, 0x00,\n    0x03, 0x10, 0x80, 0xbc, 0x82, 0x97, 0x80, 0x8d,\n    0x80, 0x43, 0x5a, 0x81, 0xb2, 0x03, 0x80, 0x61,\n    0xc4, 0xad, 0x80, 0x40, 0xc9, 0x80, 0x40, 0xbd,\n    0x01, 0x89, 0xca, 0x99, 0x00, 0x97, 0x80, 0x93,\n    0x01, 0x20, 0x82, 0x94, 0x81, 0x40, 0xad, 0xa0,\n    0x8b, 0x88, 0x80, 0xc5, 0x80, 0x95, 0x8b, 0xaa,\n    0x1c, 0x8b, 0x90, 0x10, 0x82, 0xc6, 0x00, 0x80,\n    0x40, 0xba, 0x81, 0xbe, 0x8c, 0x18, 0x97, 0x91,\n    0x80, 0x99, 0x81, 0x8c, 0x80, 0xd5, 0xd4, 0xaf,\n    0xc5, 0x28, 0x12, 0x0a, 0x92, 0x0e, 0x88, 0x40,\n    0xe2, 0x8b, 0x41, 0x1f, 0xae, 0x80, 0x89, 0x80,\n    0xb1, 0x80, 0xd1, 0x80, 0xb2, 0xef, 0x22, 0x14,\n    0x86, 0x88, 0x98, 0x36, 0x88, 0x82, 0x8c, 0x86,\n};\n\nstatic const uint8_t unicode_prop_Extended_Pictographic_table[156] = {\n    0x40, 0xa8, 0x03, 0x80, 0x5f, 0x8c, 0x80, 0x8b,\n    0x80, 0x40, 0xd7, 0x80, 0x95, 0x80, 0xd9, 0x85,\n    0x8e, 0x81, 0x41, 0x6e, 0x81, 0x8b, 0x80, 0xde,\n    0x80, 0xc5, 0x80, 0x98, 0x8a, 0x1a, 0x40, 0xc6,\n    0x80, 0x40, 0xe6, 0x81, 0x89, 0x80, 0x88, 0x80,\n    0xb9, 0x18, 0x28, 0x8b, 0x80, 0xf1, 0x89, 0xf5,\n    0x81, 0x8a, 0x00, 0x00, 0x28, 0x10, 0x28, 0x89,\n    0x81, 0x8e, 0x01, 0x03, 0x00, 0x03, 0x10, 0x80,\n    0x8a, 0x84, 0xac, 0x82, 0x88, 0x80, 0x8d, 0x80,\n    0x8d, 0x80, 0x41, 0x73, 0x81, 0x41, 0xce, 0x82,\n    0x92, 0x81, 0xb2, 0x03, 0x80, 0x44, 0xd9, 0x80,\n    0x8b, 0x80, 0x42, 0x58, 0x00, 0x80, 0x61, 0xbd,\n    0x65, 0x40, 0xff, 0x8c, 0x82, 0x9e, 0x80, 0xbb,\n    0x85, 0x8b, 0x81, 0x8d, 0x01, 0x89, 0x91, 0xb8,\n    0x9a, 0x8e, 0x89, 0x80, 0x93, 0x01, 0x88, 0x03,\n    0x88, 0x41, 0xb1, 0x84, 0x41, 0x3d, 0x87, 0x41,\n    0x09, 0xaf, 0xff, 0xf3, 0x8b, 0xd4, 0xaa, 0x8b,\n    0x83, 0xb7, 0x87, 0x89, 0x85, 0xa7, 0x87, 0x9d,\n    0xd1, 0x8b, 0xae, 0x80, 0x89, 0x80, 0x41, 0xb8,\n    0x40, 0xff, 0x43, 0xfd,\n};\n\nstatic const uint8_t unicode_prop_Default_Ignorable_Code_Point_table[51] = {\n    0x40, 0xac, 0x80, 0x42, 0xa0, 0x80, 0x42, 0xcb,\n    0x80, 0x4b, 0x41, 0x81, 0x46, 0x52, 0x81, 0xd4,\n    0x83, 0x47, 0xfb, 0x84, 0x99, 0x84, 0xb0, 0x8f,\n    0x50, 0xf3, 0x80, 0x60, 0xcc, 0x9a, 0x8f, 0x40,\n    0xee, 0x80, 0x40, 0x9f, 0x80, 0xce, 0x88, 0x60,\n    0xbc, 0xa6, 0x83, 0x54, 0xce, 0x87, 0x6c, 0x2e,\n    0x84, 0x4f, 0xff,\n};\n\ntypedef enum {\n    UNICODE_PROP_Hyphen,\n    UNICODE_PROP_Other_Math,\n    UNICODE_PROP_Other_Alphabetic,\n    UNICODE_PROP_Other_Lowercase,\n    UNICODE_PROP_Other_Uppercase,\n    UNICODE_PROP_Other_Grapheme_Extend,\n    UNICODE_PROP_Other_Default_Ignorable_Code_Point,\n    UNICODE_PROP_Other_ID_Start,\n    UNICODE_PROP_Other_ID_Continue,\n    UNICODE_PROP_Prepended_Concatenation_Mark,\n    UNICODE_PROP_ID_Continue1,\n    UNICODE_PROP_XID_Start1,\n    UNICODE_PROP_XID_Continue1,\n    UNICODE_PROP_Changes_When_Titlecased1,\n    UNICODE_PROP_Changes_When_Casefolded1,\n    UNICODE_PROP_Changes_When_NFKC_Casefolded1,\n    UNICODE_PROP_ASCII_Hex_Digit,\n    UNICODE_PROP_Bidi_Control,\n    UNICODE_PROP_Dash,\n    UNICODE_PROP_Deprecated,\n    UNICODE_PROP_Diacritic,\n    UNICODE_PROP_Extender,\n    UNICODE_PROP_Hex_Digit,\n    UNICODE_PROP_IDS_Binary_Operator,\n    UNICODE_PROP_IDS_Trinary_Operator,\n    UNICODE_PROP_Ideographic,\n    UNICODE_PROP_Join_Control,\n    UNICODE_PROP_Logical_Order_Exception,\n    UNICODE_PROP_Noncharacter_Code_Point,\n    UNICODE_PROP_Pattern_Syntax,\n    UNICODE_PROP_Pattern_White_Space,\n    UNICODE_PROP_Quotation_Mark,\n    UNICODE_PROP_Radical,\n    UNICODE_PROP_Regional_Indicator,\n    UNICODE_PROP_Sentence_Terminal,\n    UNICODE_PROP_Soft_Dotted,\n    UNICODE_PROP_Terminal_Punctuation,\n    UNICODE_PROP_Unified_Ideograph,\n    UNICODE_PROP_Variation_Selector,\n    UNICODE_PROP_White_Space,\n    UNICODE_PROP_Bidi_Mirrored,\n    UNICODE_PROP_Emoji,\n    UNICODE_PROP_Emoji_Component,\n    UNICODE_PROP_Emoji_Modifier,\n    UNICODE_PROP_Emoji_Modifier_Base,\n    UNICODE_PROP_Emoji_Presentation,\n    UNICODE_PROP_Extended_Pictographic,\n    UNICODE_PROP_Default_Ignorable_Code_Point,\n    UNICODE_PROP_ID_Start,\n    UNICODE_PROP_Case_Ignorable,\n    UNICODE_PROP_ASCII,\n    UNICODE_PROP_Alphabetic,\n    UNICODE_PROP_Any,\n    UNICODE_PROP_Assigned,\n    UNICODE_PROP_Cased,\n    UNICODE_PROP_Changes_When_Casefolded,\n    UNICODE_PROP_Changes_When_Casemapped,\n    UNICODE_PROP_Changes_When_Lowercased,\n    UNICODE_PROP_Changes_When_NFKC_Casefolded,\n    UNICODE_PROP_Changes_When_Titlecased,\n    UNICODE_PROP_Changes_When_Uppercased,\n    UNICODE_PROP_Grapheme_Base,\n    UNICODE_PROP_Grapheme_Extend,\n    UNICODE_PROP_ID_Continue,\n    UNICODE_PROP_Lowercase,\n    UNICODE_PROP_Math,\n    UNICODE_PROP_Uppercase,\n    UNICODE_PROP_XID_Continue,\n    UNICODE_PROP_XID_Start,\n    UNICODE_PROP_Cased1,\n    UNICODE_PROP_COUNT,\n} UnicodePropertyEnum;\n\nstatic const char unicode_prop_name_table[] =\n    \"ASCII_Hex_Digit,AHex\"               \"\\0\"\n    \"Bidi_Control,Bidi_C\"                \"\\0\"\n    \"Dash\"                               \"\\0\"\n    \"Deprecated,Dep\"                     \"\\0\"\n    \"Diacritic,Dia\"                      \"\\0\"\n    \"Extender,Ext\"                       \"\\0\"\n    \"Hex_Digit,Hex\"                      \"\\0\"\n    \"IDS_Binary_Operator,IDSB\"           \"\\0\"\n    \"IDS_Trinary_Operator,IDST\"          \"\\0\"\n    \"Ideographic,Ideo\"                   \"\\0\"\n    \"Join_Control,Join_C\"                \"\\0\"\n    \"Logical_Order_Exception,LOE\"        \"\\0\"\n    \"Noncharacter_Code_Point,NChar\"      \"\\0\"\n    \"Pattern_Syntax,Pat_Syn\"             \"\\0\"\n    \"Pattern_White_Space,Pat_WS\"         \"\\0\"\n    \"Quotation_Mark,QMark\"               \"\\0\"\n    \"Radical\"                            \"\\0\"\n    \"Regional_Indicator,RI\"              \"\\0\"\n    \"Sentence_Terminal,STerm\"            \"\\0\"\n    \"Soft_Dotted,SD\"                     \"\\0\"\n    \"Terminal_Punctuation,Term\"          \"\\0\"\n    \"Unified_Ideograph,UIdeo\"            \"\\0\"\n    \"Variation_Selector,VS\"              \"\\0\"\n    \"White_Space,space\"                  \"\\0\"\n    \"Bidi_Mirrored,Bidi_M\"               \"\\0\"\n    \"Emoji\"                              \"\\0\"\n    \"Emoji_Component,EComp\"              \"\\0\"\n    \"Emoji_Modifier,EMod\"                \"\\0\"\n    \"Emoji_Modifier_Base,EBase\"          \"\\0\"\n    \"Emoji_Presentation,EPres\"           \"\\0\"\n    \"Extended_Pictographic,ExtPict\"      \"\\0\"\n    \"Default_Ignorable_Code_Point,DI\"    \"\\0\"\n    \"ID_Start,IDS\"                       \"\\0\"\n    \"Case_Ignorable,CI\"                  \"\\0\"\n    \"ASCII\"                              \"\\0\"\n    \"Alphabetic,Alpha\"                   \"\\0\"\n    \"Any\"                                \"\\0\"\n    \"Assigned\"                           \"\\0\"\n    \"Cased\"                              \"\\0\"\n    \"Changes_When_Casefolded,CWCF\"       \"\\0\"\n    \"Changes_When_Casemapped,CWCM\"       \"\\0\"\n    \"Changes_When_Lowercased,CWL\"        \"\\0\"\n    \"Changes_When_NFKC_Casefolded,CWKCF\" \"\\0\"\n    \"Changes_When_Titlecased,CWT\"        \"\\0\"\n    \"Changes_When_Uppercased,CWU\"        \"\\0\"\n    \"Grapheme_Base,Gr_Base\"              \"\\0\"\n    \"Grapheme_Extend,Gr_Ext\"             \"\\0\"\n    \"ID_Continue,IDC\"                    \"\\0\"\n    \"Lowercase,Lower\"                    \"\\0\"\n    \"Math\"                               \"\\0\"\n    \"Uppercase,Upper\"                    \"\\0\"\n    \"XID_Continue,XIDC\"                  \"\\0\"\n    \"XID_Start,XIDS\"                     \"\\0\"\n;\n\nstatic const uint8_t * const unicode_prop_table[] = {\n    unicode_prop_Hyphen_table,\n    unicode_prop_Other_Math_table,\n    unicode_prop_Other_Alphabetic_table,\n    unicode_prop_Other_Lowercase_table,\n    unicode_prop_Other_Uppercase_table,\n    unicode_prop_Other_Grapheme_Extend_table,\n    unicode_prop_Other_Default_Ignorable_Code_Point_table,\n    unicode_prop_Other_ID_Start_table,\n    unicode_prop_Other_ID_Continue_table,\n    unicode_prop_Prepended_Concatenation_Mark_table,\n    unicode_prop_ID_Continue1_table,\n    unicode_prop_XID_Start1_table,\n    unicode_prop_XID_Continue1_table,\n    unicode_prop_Changes_When_Titlecased1_table,\n    unicode_prop_Changes_When_Casefolded1_table,\n    unicode_prop_Changes_When_NFKC_Casefolded1_table,\n    unicode_prop_ASCII_Hex_Digit_table,\n    unicode_prop_Bidi_Control_table,\n    unicode_prop_Dash_table,\n    unicode_prop_Deprecated_table,\n    unicode_prop_Diacritic_table,\n    unicode_prop_Extender_table,\n    unicode_prop_Hex_Digit_table,\n    unicode_prop_IDS_Binary_Operator_table,\n    unicode_prop_IDS_Trinary_Operator_table,\n    unicode_prop_Ideographic_table,\n    unicode_prop_Join_Control_table,\n    unicode_prop_Logical_Order_Exception_table,\n    unicode_prop_Noncharacter_Code_Point_table,\n    unicode_prop_Pattern_Syntax_table,\n    unicode_prop_Pattern_White_Space_table,\n    unicode_prop_Quotation_Mark_table,\n    unicode_prop_Radical_table,\n    unicode_prop_Regional_Indicator_table,\n    unicode_prop_Sentence_Terminal_table,\n    unicode_prop_Soft_Dotted_table,\n    unicode_prop_Terminal_Punctuation_table,\n    unicode_prop_Unified_Ideograph_table,\n    unicode_prop_Variation_Selector_table,\n    unicode_prop_White_Space_table,\n    unicode_prop_Bidi_Mirrored_table,\n    unicode_prop_Emoji_table,\n    unicode_prop_Emoji_Component_table,\n    unicode_prop_Emoji_Modifier_table,\n    unicode_prop_Emoji_Modifier_Base_table,\n    unicode_prop_Emoji_Presentation_table,\n    unicode_prop_Extended_Pictographic_table,\n    unicode_prop_Default_Ignorable_Code_Point_table,\n    unicode_prop_ID_Start_table,\n    unicode_prop_Case_Ignorable_table,\n};\n\nstatic const uint16_t unicode_prop_len_table[] = {\n    countof(unicode_prop_Hyphen_table),\n    countof(unicode_prop_Other_Math_table),\n    countof(unicode_prop_Other_Alphabetic_table),\n    countof(unicode_prop_Other_Lowercase_table),\n    countof(unicode_prop_Other_Uppercase_table),\n    countof(unicode_prop_Other_Grapheme_Extend_table),\n    countof(unicode_prop_Other_Default_Ignorable_Code_Point_table),\n    countof(unicode_prop_Other_ID_Start_table),\n    countof(unicode_prop_Other_ID_Continue_table),\n    countof(unicode_prop_Prepended_Concatenation_Mark_table),\n    countof(unicode_prop_ID_Continue1_table),\n    countof(unicode_prop_XID_Start1_table),\n    countof(unicode_prop_XID_Continue1_table),\n    countof(unicode_prop_Changes_When_Titlecased1_table),\n    countof(unicode_prop_Changes_When_Casefolded1_table),\n    countof(unicode_prop_Changes_When_NFKC_Casefolded1_table),\n    countof(unicode_prop_ASCII_Hex_Digit_table),\n    countof(unicode_prop_Bidi_Control_table),\n    countof(unicode_prop_Dash_table),\n    countof(unicode_prop_Deprecated_table),\n    countof(unicode_prop_Diacritic_table),\n    countof(unicode_prop_Extender_table),\n    countof(unicode_prop_Hex_Digit_table),\n    countof(unicode_prop_IDS_Binary_Operator_table),\n    countof(unicode_prop_IDS_Trinary_Operator_table),\n    countof(unicode_prop_Ideographic_table),\n    countof(unicode_prop_Join_Control_table),\n    countof(unicode_prop_Logical_Order_Exception_table),\n    countof(unicode_prop_Noncharacter_Code_Point_table),\n    countof(unicode_prop_Pattern_Syntax_table),\n    countof(unicode_prop_Pattern_White_Space_table),\n    countof(unicode_prop_Quotation_Mark_table),\n    countof(unicode_prop_Radical_table),\n    countof(unicode_prop_Regional_Indicator_table),\n    countof(unicode_prop_Sentence_Terminal_table),\n    countof(unicode_prop_Soft_Dotted_table),\n    countof(unicode_prop_Terminal_Punctuation_table),\n    countof(unicode_prop_Unified_Ideograph_table),\n    countof(unicode_prop_Variation_Selector_table),\n    countof(unicode_prop_White_Space_table),\n    countof(unicode_prop_Bidi_Mirrored_table),\n    countof(unicode_prop_Emoji_table),\n    countof(unicode_prop_Emoji_Component_table),\n    countof(unicode_prop_Emoji_Modifier_table),\n    countof(unicode_prop_Emoji_Modifier_Base_table),\n    countof(unicode_prop_Emoji_Presentation_table),\n    countof(unicode_prop_Extended_Pictographic_table),\n    countof(unicode_prop_Default_Ignorable_Code_Point_table),\n    countof(unicode_prop_ID_Start_table),\n    countof(unicode_prop_Case_Ignorable_table),\n};\n\n#endif /* CONFIG_ALL_UNICODE */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/libunicode.c",
    "content": "/*\n * Unicode utilities\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <string.h>\n#include <assert.h>\n\n#include \"cutils.h\"\n#include \"libunicode.h\"\n#include \"libunicode-table.h\"\n\nenum {\n    RUN_TYPE_U,\n    RUN_TYPE_L,\n    RUN_TYPE_UF,\n    RUN_TYPE_LF,\n    RUN_TYPE_UL,\n    RUN_TYPE_LSU,\n    RUN_TYPE_U2L_399_EXT2,\n    RUN_TYPE_UF_D20,\n    RUN_TYPE_UF_D1_EXT,\n    RUN_TYPE_U_EXT,\n    RUN_TYPE_LF_EXT,\n    RUN_TYPE_U_EXT2,\n    RUN_TYPE_L_EXT2,\n    RUN_TYPE_U_EXT3,\n};\n\n/* conv_type:\n   0 = to upper \n   1 = to lower\n   2 = case folding (= to lower with modifications) \n*/\nint lre_case_conv(uint32_t *res, uint32_t c, int conv_type)\n{\n    if (c < 128) {\n        if (conv_type) {\n            if (c >= 'A' && c <= 'Z') {\n                c = c - 'A' + 'a';\n            }\n        } else {\n            if (c >= 'a' && c <= 'z') {\n                c = c - 'a' + 'A';\n            }\n        }\n    } else {\n        uint32_t v, code, data, type, len, a, is_lower;\n        int idx, idx_min, idx_max;\n        \n        is_lower = (conv_type != 0);\n        idx_min = 0;\n        idx_max = countof(case_conv_table1) - 1;\n        while (idx_min <= idx_max) {\n            idx = (unsigned)(idx_max + idx_min) / 2;\n            v = case_conv_table1[idx];\n            code = v >> (32 - 17);\n            len = (v >> (32 - 17 - 7)) & 0x7f;\n            if (c < code) {\n                idx_max = idx - 1;\n            } else if (c >= code + len) {\n                idx_min = idx + 1;\n            } else {\n                type = (v >> (32 - 17 - 7 - 4)) & 0xf;\n                data = ((v & 0xf) << 8) | case_conv_table2[idx];\n                switch(type) {\n                case RUN_TYPE_U:\n                case RUN_TYPE_L:\n                case RUN_TYPE_UF:\n                case RUN_TYPE_LF:\n                    if (conv_type == (type & 1) ||\n                        (type >= RUN_TYPE_UF && conv_type == 2)) {\n                        c = c - code + (case_conv_table1[data] >> (32 - 17));\n                    }\n                    break;\n                case RUN_TYPE_UL:\n                    a = c - code;\n                    if ((a & 1) != (1 - is_lower))\n                        break;\n                    c = (a ^ 1) + code;\n                    break;\n                case RUN_TYPE_LSU:\n                    a = c - code;\n                    if (a == 1) {\n                        c += 2 * is_lower - 1;\n                    } else if (a == (1 - is_lower) * 2) {\n                        c += (2 * is_lower - 1) * 2;\n                    }\n                    break;\n                case RUN_TYPE_U2L_399_EXT2:\n                    if (!is_lower) {\n                        res[0] = c - code + case_conv_ext[data >> 6];\n                        res[1] = 0x399;\n                        return 2;\n                    } else {\n                        c = c - code + case_conv_ext[data & 0x3f];\n                    }\n                    break;\n                case RUN_TYPE_UF_D20:\n                    if (conv_type == 1)\n                        break;\n                    c = data + (conv_type == 2) * 0x20;\n                    break;\n                case RUN_TYPE_UF_D1_EXT:\n                    if (conv_type == 1)\n                        break;\n                    c = case_conv_ext[data] + (conv_type == 2);\n                    break;\n                case RUN_TYPE_U_EXT:\n                case RUN_TYPE_LF_EXT:\n                    if (is_lower != (type - RUN_TYPE_U_EXT))\n                        break;\n                    c = case_conv_ext[data];\n                    break;\n                case RUN_TYPE_U_EXT2:\n                case RUN_TYPE_L_EXT2:\n                    if (conv_type != (type - RUN_TYPE_U_EXT2))\n                        break;\n                    res[0] = c - code + case_conv_ext[data >> 6];\n                    res[1] = case_conv_ext[data & 0x3f];\n                    return 2;\n                default:\n                case RUN_TYPE_U_EXT3:\n                    if (conv_type != 0)\n                        break;\n                    res[0] = case_conv_ext[data >> 8];\n                    res[1] = case_conv_ext[(data >> 4) & 0xf];\n                    res[2] = case_conv_ext[data & 0xf];\n                    return 3;\n                }\n                break;\n            }\n        }\n    }\n    res[0] = c;\n    return 1;\n}\n\nstatic uint32_t get_le24(const uint8_t *ptr)\n{\n#if defined(__x86__) || defined(__x86_64__)\n    return *(uint16_t *)ptr | (ptr[2] << 16);\n#else\n    return ptr[0] | (ptr[1] << 8) | (ptr[2] << 16);\n#endif\n}\n\n#define UNICODE_INDEX_BLOCK_LEN 32\n\n/* return -1 if not in table, otherwise the offset in the block */\nstatic int get_index_pos(uint32_t *pcode, uint32_t c,\n                         const uint8_t *index_table, int index_table_len)\n{\n    uint32_t code, v;\n    int idx_min, idx_max, idx;\n\n    idx_min = 0;\n    v = get_le24(index_table);\n    code = v & ((1 << 21) - 1);\n    if (c < code) {\n        *pcode = 0;\n        return 0;\n    }\n    idx_max = index_table_len - 1;\n    code = get_le24(index_table + idx_max * 3);\n    if (c >= code)\n        return -1;\n    /* invariant: tab[idx_min] <= c < tab2[idx_max] */\n    while ((idx_max - idx_min) > 1) {\n        idx = (idx_max + idx_min) / 2;\n        v = get_le24(index_table + idx * 3);\n        code = v & ((1 << 21) - 1);\n        if (c < code) {\n            idx_max = idx;\n        } else {\n            idx_min = idx;\n        }\n    }\n    v = get_le24(index_table + idx_min * 3);\n    *pcode = v & ((1 << 21) - 1);\n    return (idx_min + 1) * UNICODE_INDEX_BLOCK_LEN + (v >> 21);\n}\n\nstatic BOOL lre_is_in_table(uint32_t c, const uint8_t *table,\n                            const uint8_t *index_table, int index_table_len)\n{\n    uint32_t code, b, bit;\n    int pos;\n    const uint8_t *p;\n    \n    pos = get_index_pos(&code, c, index_table, index_table_len);\n    if (pos < 0)\n        return FALSE; /* outside the table */\n    p = table + pos;\n    bit = 0;\n    for(;;) {\n        b = *p++;\n        if (b < 64) {\n            code += (b >> 3) + 1;\n            if (c < code)\n                return bit;\n            bit ^= 1;\n            code += (b & 7) + 1;\n        } else if (b >= 0x80) {\n            code += b - 0x80 + 1;\n        } else if (b < 0x60) {\n            code += (((b - 0x40) << 8) | p[0]) + 1;\n            p++;\n        } else {\n            code += (((b - 0x60) << 16) | (p[0] << 8) | p[1]) + 1;\n            p += 2;\n        }\n        if (c < code)\n            return bit;\n        bit ^= 1;\n    }\n}\n\nBOOL lre_is_cased(uint32_t c)\n{\n    uint32_t v, code, len;\n    int idx, idx_min, idx_max;\n        \n    idx_min = 0;\n    idx_max = countof(case_conv_table1) - 1;\n    while (idx_min <= idx_max) {\n        idx = (unsigned)(idx_max + idx_min) / 2;\n        v = case_conv_table1[idx];\n        code = v >> (32 - 17);\n        len = (v >> (32 - 17 - 7)) & 0x7f;\n        if (c < code) {\n            idx_max = idx - 1;\n        } else if (c >= code + len) {\n            idx_min = idx + 1;\n        } else {\n            return TRUE;\n        }\n    }\n    return lre_is_in_table(c, unicode_prop_Cased1_table,\n                           unicode_prop_Cased1_index,\n                           sizeof(unicode_prop_Cased1_index) / 3);\n}\n\nBOOL lre_is_case_ignorable(uint32_t c)\n{\n    return lre_is_in_table(c, unicode_prop_Case_Ignorable_table,\n                           unicode_prop_Case_Ignorable_index,\n                           sizeof(unicode_prop_Case_Ignorable_index) / 3);\n}\n\n/* character range */\n\nstatic __maybe_unused void cr_dump(CharRange *cr)\n{\n    int i;\n    for(i = 0; i < cr->len; i++)\n        printf(\"%d: 0x%04x\\n\", i, cr->points[i]);\n}\n\nstatic void *cr_default_realloc(void *opaque, void *ptr, size_t size)\n{\n    return realloc(ptr, size);\n}\n\nvoid cr_init(CharRange *cr, void *mem_opaque, DynBufReallocFunc *realloc_func)\n{\n    cr->len = cr->size = 0;\n    cr->points = NULL;\n    cr->mem_opaque = mem_opaque;\n    cr->realloc_func = realloc_func ? realloc_func : cr_default_realloc;\n}\n\nvoid cr_free(CharRange *cr)\n{\n    cr->realloc_func(cr->mem_opaque, cr->points, 0);\n}\n\nint cr_realloc(CharRange *cr, int size)\n{\n    int new_size;\n    uint32_t *new_buf;\n    \n    if (size > cr->size) {\n        new_size = max_int(size, cr->size * 3 / 2);\n        new_buf = cr->realloc_func(cr->mem_opaque, cr->points,\n                                   new_size * sizeof(cr->points[0]));\n        if (!new_buf)\n            return -1;\n        cr->points = new_buf;\n        cr->size = new_size;\n    }\n    return 0;\n}\n\nint cr_copy(CharRange *cr, const CharRange *cr1)\n{\n    if (cr_realloc(cr, cr1->len))\n        return -1;\n    memcpy(cr->points, cr1->points, sizeof(cr->points[0]) * cr1->len);\n    cr->len = cr1->len;\n    return 0;\n}\n\n/* merge consecutive intervals and remove empty intervals */\nstatic void cr_compress(CharRange *cr)\n{\n    int i, j, k, len;\n    uint32_t *pt;\n    \n    pt = cr->points;\n    len = cr->len;\n    i = 0;\n    j = 0;\n    k = 0;\n    while ((i + 1) < len) {\n        if (pt[i] == pt[i + 1]) {\n            /* empty interval */\n            i += 2;\n        } else {\n            j = i;\n            while ((j + 3) < len && pt[j + 1] == pt[j + 2])\n                j += 2;\n            /* just copy */\n            pt[k] = pt[i];\n            pt[k + 1] = pt[j + 1];\n            k += 2;\n            i = j + 2;\n        }\n    }\n    cr->len = k;\n}\n\n/* union or intersection */\nint cr_op(CharRange *cr, const uint32_t *a_pt, int a_len,\n          const uint32_t *b_pt, int b_len, int op)\n{\n    int a_idx, b_idx, is_in;\n    uint32_t v;\n    \n    a_idx = 0;\n    b_idx = 0;\n    for(;;) {\n        /* get one more point from a or b in increasing order */\n        if (a_idx < a_len && b_idx < b_len) {\n            if (a_pt[a_idx] < b_pt[b_idx]) {\n                goto a_add;\n            } else if (a_pt[a_idx] == b_pt[b_idx]) {\n                v = a_pt[a_idx];\n                a_idx++;\n                b_idx++;\n            } else {\n                goto b_add;\n            }\n        } else if (a_idx < a_len) {\n        a_add:\n            v = a_pt[a_idx++];\n        } else if (b_idx < b_len) {\n        b_add:\n            v = b_pt[b_idx++];\n        } else {\n            break;\n        }\n        /* add the point if the in/out status changes */\n        switch(op) {\n        case CR_OP_UNION:\n            is_in = (a_idx & 1) | (b_idx & 1);\n            break;\n        case CR_OP_INTER:\n            is_in = (a_idx & 1) & (b_idx & 1);\n            break;\n        case CR_OP_XOR:\n            is_in = (a_idx & 1) ^ (b_idx & 1);\n            break;\n        default:\n            abort();\n        }\n        if (is_in != (cr->len & 1)) {\n            if (cr_add_point(cr, v))\n                return -1;\n        }\n    }\n    cr_compress(cr);\n    return 0;\n}\n\nint cr_union1(CharRange *cr, const uint32_t *b_pt, int b_len)\n{\n    CharRange a = *cr;\n    int ret;\n    cr->len = 0;\n    cr->size = 0;\n    cr->points = NULL;\n    ret = cr_op(cr, a.points, a.len, b_pt, b_len, CR_OP_UNION);\n    cr_free(&a);\n    return ret;\n}\n\nint cr_invert(CharRange *cr)\n{\n    int len;\n    len = cr->len;\n    if (cr_realloc(cr, len + 2))\n        return -1;\n    memmove(cr->points + 1, cr->points, len * sizeof(cr->points[0]));\n    cr->points[0] = 0;\n    cr->points[len + 1] = UINT32_MAX;\n    cr->len = len + 2;\n    cr_compress(cr);\n    return 0;\n}\n\n#ifdef CONFIG_ALL_UNICODE\n\nBOOL lre_is_id_start(uint32_t c)\n{\n    return lre_is_in_table(c, unicode_prop_ID_Start_table,\n                           unicode_prop_ID_Start_index,\n                           sizeof(unicode_prop_ID_Start_index) / 3);\n}\n\nBOOL lre_is_id_continue(uint32_t c)\n{\n    return lre_is_id_start(c) ||\n        lre_is_in_table(c, unicode_prop_ID_Continue1_table,\n                        unicode_prop_ID_Continue1_index,\n                        sizeof(unicode_prop_ID_Continue1_index) / 3);\n}\n\n#define UNICODE_DECOMP_LEN_MAX 18\n\ntypedef enum {\n    DECOMP_TYPE_C1, /* 16 bit char */\n    DECOMP_TYPE_L1, /* 16 bit char table */\n    DECOMP_TYPE_L2,\n    DECOMP_TYPE_L3,\n    DECOMP_TYPE_L4,\n    DECOMP_TYPE_L5, /* XXX: not used */\n    DECOMP_TYPE_L6, /* XXX: could remove */\n    DECOMP_TYPE_L7, /* XXX: could remove */\n    DECOMP_TYPE_LL1, /* 18 bit char table */\n    DECOMP_TYPE_LL2,\n    DECOMP_TYPE_S1, /* 8 bit char table */\n    DECOMP_TYPE_S2,\n    DECOMP_TYPE_S3,\n    DECOMP_TYPE_S4,\n    DECOMP_TYPE_S5,\n    DECOMP_TYPE_I1, /* increment 16 bit char value */\n    DECOMP_TYPE_I2_0,\n    DECOMP_TYPE_I2_1,\n    DECOMP_TYPE_I3_1,\n    DECOMP_TYPE_I3_2,\n    DECOMP_TYPE_I4_1,\n    DECOMP_TYPE_I4_2,\n    DECOMP_TYPE_B1, /* 16 bit base + 8 bit offset */\n    DECOMP_TYPE_B2,\n    DECOMP_TYPE_B3,\n    DECOMP_TYPE_B4,\n    DECOMP_TYPE_B5,\n    DECOMP_TYPE_B6,\n    DECOMP_TYPE_B7,\n    DECOMP_TYPE_B8,\n    DECOMP_TYPE_B18,\n    DECOMP_TYPE_LS2,\n    DECOMP_TYPE_PAT3,\n    DECOMP_TYPE_S2_UL,\n    DECOMP_TYPE_LS2_UL,\n} DecompTypeEnum;\n\nstatic uint32_t unicode_get_short_code(uint32_t c)\n{\n    static const uint16_t unicode_short_table[2] = { 0x2044, 0x2215 };\n\n    if (c < 0x80)\n        return c;\n    else if (c < 0x80 + 0x50)\n        return c - 0x80 + 0x300;\n    else\n        return unicode_short_table[c - 0x80 - 0x50];\n}\n\nstatic uint32_t unicode_get_lower_simple(uint32_t c)\n{\n    if (c < 0x100 || (c >= 0x410 && c <= 0x42f))\n        c += 0x20;\n    else\n        c++;\n    return c;\n}\n\nstatic uint16_t unicode_get16(const uint8_t *p)\n{\n    return p[0] | (p[1] << 8);\n}\n\nstatic int unicode_decomp_entry(uint32_t *res, uint32_t c,\n                                int idx, uint32_t code, uint32_t len,\n                                uint32_t type)\n{\n    uint32_t c1;\n    int l, i, p;\n    const uint8_t *d;\n\n    if (type == DECOMP_TYPE_C1) {\n        res[0] = unicode_decomp_table2[idx];\n        return 1;\n    } else {\n        d = unicode_decomp_data + unicode_decomp_table2[idx];\n        switch(type) {\n        case DECOMP_TYPE_L1:\n        case DECOMP_TYPE_L2:\n        case DECOMP_TYPE_L3:\n        case DECOMP_TYPE_L4:\n        case DECOMP_TYPE_L5:\n        case DECOMP_TYPE_L6:\n        case DECOMP_TYPE_L7:\n            l = type - DECOMP_TYPE_L1 + 1;\n            d += (c - code) * l * 2;\n            for(i = 0; i < l; i++) {\n                if ((res[i] = unicode_get16(d + 2 * i)) == 0)\n                    return 0;\n            }\n            return l;\n        case DECOMP_TYPE_LL1:\n        case DECOMP_TYPE_LL2:\n            {\n                uint32_t k, p;\n                l = type - DECOMP_TYPE_LL1 + 1;\n                k = (c - code) * l;\n                p = len * l * 2;\n                for(i = 0; i < l; i++) {\n                    c1 = unicode_get16(d + 2 * k) |\n                        (((d[p + (k / 4)] >> ((k % 4) * 2)) & 3) << 16);\n                    if (!c1)\n                        return 0;\n                    res[i] = c1;\n                    k++;\n                }\n            }\n            return l;\n        case DECOMP_TYPE_S1:\n        case DECOMP_TYPE_S2:\n        case DECOMP_TYPE_S3:\n        case DECOMP_TYPE_S4:\n        case DECOMP_TYPE_S5:\n            l = type - DECOMP_TYPE_S1 + 1;\n            d += (c - code) * l;\n            for(i = 0; i < l; i++) {\n                if ((res[i] = unicode_get_short_code(d[i])) == 0)\n                    return 0;\n            }\n            return l;\n        case DECOMP_TYPE_I1:\n            l = 1;\n            p = 0;\n            goto decomp_type_i;\n        case DECOMP_TYPE_I2_0:\n        case DECOMP_TYPE_I2_1:\n        case DECOMP_TYPE_I3_1:\n        case DECOMP_TYPE_I3_2:\n        case DECOMP_TYPE_I4_1:\n        case DECOMP_TYPE_I4_2:\n            l = 2 + ((type - DECOMP_TYPE_I2_0) >> 1);\n            p = ((type - DECOMP_TYPE_I2_0) & 1) + (l > 2);\n        decomp_type_i:\n            for(i = 0; i < l; i++) {\n                c1 = unicode_get16(d + 2 * i);\n                if (i == p)\n                    c1 += c - code;\n                res[i] = c1;\n            }\n            return l;\n        case DECOMP_TYPE_B18:\n            l = 18;\n            goto decomp_type_b;\n        case DECOMP_TYPE_B1:\n        case DECOMP_TYPE_B2:\n        case DECOMP_TYPE_B3:\n        case DECOMP_TYPE_B4:\n        case DECOMP_TYPE_B5:\n        case DECOMP_TYPE_B6:\n        case DECOMP_TYPE_B7:\n        case DECOMP_TYPE_B8:\n            l = type - DECOMP_TYPE_B1 + 1;\n        decomp_type_b:\n            {\n                uint32_t c_min;\n                c_min = unicode_get16(d);\n                d += 2 + (c - code) * l;\n                for(i = 0; i < l; i++) {\n                    c1 = d[i];\n                    if (c1 == 0xff)\n                        c1 = 0x20;\n                    else\n                        c1 += c_min;\n                    res[i] = c1;\n                }\n            }\n            return l;\n        case DECOMP_TYPE_LS2:\n            d += (c - code) * 3;\n            if (!(res[0] = unicode_get16(d)))\n                return 0;\n            res[1] = unicode_get_short_code(d[2]);\n            return 2;\n        case DECOMP_TYPE_PAT3:\n            res[0] = unicode_get16(d);\n            res[2] = unicode_get16(d + 2);\n            d += 4 + (c - code) * 2;\n            res[1] = unicode_get16(d);\n            return 3;\n        case DECOMP_TYPE_S2_UL:\n        case DECOMP_TYPE_LS2_UL:\n            c1 = c - code;\n            if (type == DECOMP_TYPE_S2_UL) {\n                d += c1 & ~1;\n                c = unicode_get_short_code(*d);\n                d++;\n            } else {\n                d += (c1 >> 1) * 3;\n                c = unicode_get16(d);\n                d += 2;\n            }\n            if (c1 & 1)\n                c = unicode_get_lower_simple(c);\n            res[0] = c;\n            res[1] = unicode_get_short_code(*d);\n            return 2;\n        }\n    }\n    return 0;\n}\n\n\n/* return the length of the decomposition (length <=\n   UNICODE_DECOMP_LEN_MAX) or 0 if no decomposition */\nstatic int unicode_decomp_char(uint32_t *res, uint32_t c, BOOL is_compat1)\n{\n    uint32_t v, type, is_compat, code, len;\n    int idx_min, idx_max, idx;\n    \n    idx_min = 0;\n    idx_max = countof(unicode_decomp_table1) - 1;\n    while (idx_min <= idx_max) {\n        idx = (idx_max + idx_min) / 2;\n        v = unicode_decomp_table1[idx];\n        code = v >> (32 - 18);\n        len = (v >> (32 - 18 - 7)) & 0x7f;\n        //        printf(\"idx=%d code=%05x len=%d\\n\", idx, code, len);\n        if (c < code) {\n            idx_max = idx - 1;\n        } else if (c >= code + len) {\n            idx_min = idx + 1;\n        } else {\n            is_compat = v & 1;\n            if (is_compat1 < is_compat)\n                break;\n            type = (v >> (32 - 18 - 7 - 6)) & 0x3f;\n            return unicode_decomp_entry(res, c, idx, code, len, type);\n        }\n    }\n    return 0;\n}\n\n/* return 0 if no pair found */\nstatic int unicode_compose_pair(uint32_t c0, uint32_t c1)\n{\n    uint32_t code, len, type, v, idx1, d_idx, d_offset, ch;\n    int idx_min, idx_max, idx, d;\n    uint32_t pair[2];\n    \n    idx_min = 0;\n    idx_max = countof(unicode_comp_table) - 1;\n    while (idx_min <= idx_max) {\n        idx = (idx_max + idx_min) / 2;\n        idx1 = unicode_comp_table[idx];\n\n        /* idx1 represent an entry of the decomposition table */\n        d_idx = idx1 >> 6;\n        d_offset = idx1 & 0x3f;\n        v = unicode_decomp_table1[d_idx];\n        code = v >> (32 - 18);\n        len = (v >> (32 - 18 - 7)) & 0x7f;\n        type = (v >> (32 - 18 - 7 - 6)) & 0x3f;\n        ch = code + d_offset;\n        unicode_decomp_entry(pair, ch, d_idx, code, len, type);\n        d = c0 - pair[0];\n        if (d == 0)\n            d = c1 - pair[1];\n        if (d < 0) {\n            idx_max = idx - 1;\n        } else if (d > 0) {\n            idx_min = idx + 1;\n        } else {\n            return ch;\n        }\n    }\n    return 0;\n}\n\n/* return the combining class of character c (between 0 and 255) */\nstatic int unicode_get_cc(uint32_t c)\n{\n    uint32_t code, n, type, cc, c1, b;\n    int pos;\n    const uint8_t *p;\n    \n    pos = get_index_pos(&code, c,\n                        unicode_cc_index, sizeof(unicode_cc_index) / 3);\n    if (pos < 0)\n        return 0;\n    p = unicode_cc_table + pos;\n    for(;;) {\n        b = *p++;\n        type = b >> 6;\n        n = b & 0x3f;\n        if (n < 48) {\n        } else if (n < 56) {\n            n = (n - 48) << 8;\n            n |= *p++;\n            n += 48;\n        } else {\n            n = (n - 56) << 8;\n            n |= *p++ << 8;\n            n |= *p++;\n            n += 48 + (1 << 11);\n        }\n        if (type <= 1)\n            p++;\n        c1 = code + n + 1;\n        if (c < c1) {\n            switch(type) {\n            case 0:\n                cc = p[-1];\n                break;\n            case 1:\n                cc = p[-1] + c - code;\n                break;\n            case 2:\n                cc = 0;\n                break;\n            default:\n            case 3:\n                cc = 230;\n                break;\n            }\n            return cc;\n        }\n        code = c1;\n    }\n}\n\nstatic void sort_cc(int *buf, int len)\n{\n    int i, j, k, cc, cc1, start, ch1;\n    \n    for(i = 0; i < len; i++) {\n        cc = unicode_get_cc(buf[i]);\n        if (cc != 0) {\n            start = i;\n            j = i + 1;\n            while (j < len) {\n                ch1 = buf[j];\n                cc1 = unicode_get_cc(ch1);\n                if (cc1 == 0)\n                    break;\n                k = j - 1;\n                while (k >= start) {\n                    if (unicode_get_cc(buf[k]) <= cc1)\n                        break;\n                    buf[k + 1] = buf[k];\n                    k--;\n                }\n                buf[k + 1] = ch1;\n                j++;\n            }\n#if 0\n            printf(\"cc:\");\n            for(k = start; k < j; k++) {\n                printf(\" %3d\", unicode_get_cc(buf[k]));\n            }\n            printf(\"\\n\");\n#endif\n            i = j;\n        }\n    }\n}\n\nstatic void to_nfd_rec(DynBuf *dbuf,\n                       const int *src, int src_len, int is_compat)\n{\n    uint32_t c, v;\n    int i, l;\n    uint32_t res[UNICODE_DECOMP_LEN_MAX];\n    \n    for(i = 0; i < src_len; i++) {\n        c = src[i];\n        if (c >= 0xac00 && c < 0xd7a4) {\n            /* Hangul decomposition */\n            c -= 0xac00;\n            dbuf_put_u32(dbuf, 0x1100 + c / 588);\n            dbuf_put_u32(dbuf, 0x1161 + (c % 588) / 28);\n            v = c % 28;\n            if (v != 0)\n                dbuf_put_u32(dbuf, 0x11a7 + v);\n        } else {\n            l = unicode_decomp_char(res, c, is_compat);\n            if (l) {\n                to_nfd_rec(dbuf, (int *)res, l, is_compat);\n            } else {\n                dbuf_put_u32(dbuf, c);\n            }\n        }\n    }\n}\n\n/* return 0 if not found */\nstatic int compose_pair(uint32_t c0, uint32_t c1)\n{\n    /* Hangul composition */\n    if (c0 >= 0x1100 && c0 < 0x1100 + 19 &&\n        c1 >= 0x1161 && c1 < 0x1161 + 21) {\n        return 0xac00 + (c0 - 0x1100) * 588 + (c1 - 0x1161) * 28;\n    } else if (c0 >= 0xac00 && c0 < 0xac00 + 11172 &&\n               (c0 - 0xac00) % 28 == 0 &&\n               c1 >= 0x11a7 && c1 < 0x11a7 + 28) {\n        return c0 + c1 - 0x11a7;\n    } else {\n        return unicode_compose_pair(c0, c1);\n    }\n}\n\nint unicode_normalize(uint32_t **pdst, const uint32_t *src, int src_len,\n                      UnicodeNormalizationEnum n_type,\n                      void *opaque, DynBufReallocFunc *realloc_func)\n{\n    int *buf, buf_len, i, p, starter_pos, cc, last_cc, out_len;\n    BOOL is_compat;\n    DynBuf dbuf_s, *dbuf = &dbuf_s;\n    \n    is_compat = n_type >> 1;\n\n    dbuf_init2(dbuf, opaque, realloc_func);\n    if (dbuf_realloc(dbuf, sizeof(int) * src_len))\n        goto fail;\n\n    /* common case: latin1 is unaffected by NFC */\n    if (n_type == UNICODE_NFC) {\n        for(i = 0; i < src_len; i++) {\n            if (src[i] >= 0x100)\n                goto not_latin1;\n        }\n        buf = (int *)dbuf->buf;\n        memcpy(buf, src, src_len * sizeof(int));\n        *pdst = (uint32_t *)buf;\n        return src_len;\n    not_latin1: ;\n    }\n\n    to_nfd_rec(dbuf, (const int *)src, src_len, is_compat);\n    if (dbuf_error(dbuf)) {\n    fail:\n        *pdst = NULL;\n        return -1;\n    }\n    buf = (int *)dbuf->buf;\n    buf_len = dbuf->size / sizeof(int);\n        \n    sort_cc(buf, buf_len);\n    \n    if (buf_len <= 1 || (n_type & 1) != 0) {\n        /* NFD / NFKD */\n        *pdst = (uint32_t *)buf;\n        return buf_len;\n    }\n    \n    i = 1;\n    out_len = 1;\n    while (i < buf_len) {\n        /* find the starter character and test if it is blocked from\n           the character at 'i' */\n        last_cc = unicode_get_cc(buf[i]);\n        starter_pos = out_len - 1;\n        while (starter_pos >= 0) {\n            cc = unicode_get_cc(buf[starter_pos]);\n            if (cc == 0)\n                break;\n            if (cc >= last_cc)\n                goto next;\n            last_cc = 256;\n            starter_pos--;\n        }\n        if (starter_pos >= 0 &&\n            (p = compose_pair(buf[starter_pos], buf[i])) != 0) {\n            buf[starter_pos] = p;\n            i++;\n        } else {\n        next:\n            buf[out_len++] = buf[i++];\n        }\n    }\n    *pdst = (uint32_t *)buf;\n    return out_len;\n}\n\n/* char ranges for various unicode properties */\n\nstatic int unicode_find_name(const char *name_table, const char *name)\n{\n    const char *p, *r;\n    int pos;\n    size_t name_len, len;\n    \n    p = name_table;\n    pos = 0;\n    name_len = strlen(name);\n    while (*p) {\n        for(;;) {\n            r = strchr(p, ',');\n            if (!r)\n                len = strlen(p);\n            else\n                len = r - p;\n            if (len == name_len && !memcmp(p, name, name_len))\n                return pos;\n            p += len + 1;\n            if (!r)\n                break;\n        }\n        pos++;\n    }\n    return -1;\n}\n\n/* 'cr' must be initialized and empty. Return 0 if OK, -1 if error, -2\n   if not found */\nint unicode_script(CharRange *cr,\n                   const char *script_name, BOOL is_ext)\n{\n    int script_idx;\n    const uint8_t *p, *p_end;\n    uint32_t c, c1, b, n, v, v_len, i, type;\n    CharRange cr1_s, *cr1;\n    CharRange cr2_s, *cr2 = &cr2_s;\n    BOOL is_common;\n    \n    script_idx = unicode_find_name(unicode_script_name_table, script_name);\n    if (script_idx < 0)\n        return -2;\n    /* Note: we remove the \"Unknown\" Script */\n    script_idx += UNICODE_SCRIPT_Unknown + 1;\n        \n    is_common = (script_idx == UNICODE_SCRIPT_Common ||\n                 script_idx == UNICODE_SCRIPT_Inherited);\n    if (is_ext) {\n        cr1 = &cr1_s;\n        cr_init(cr1, cr->mem_opaque, cr->realloc_func);\n        cr_init(cr2, cr->mem_opaque, cr->realloc_func);\n    } else {\n        cr1 = cr;\n    }\n\n    p = unicode_script_table;\n    p_end = unicode_script_table + countof(unicode_script_table);\n    c = 0;\n    while (p < p_end) {\n        b = *p++;\n        type = b >> 7;\n        n = b & 0x7f;\n        if (n < 96) {\n        } else if (n < 112) {\n            n = (n - 96) << 8;\n            n |= *p++;\n            n += 96;\n        } else {\n            n = (n - 112) << 16;\n            n |= *p++ << 8;\n            n |= *p++;\n            n += 96 + (1 << 12);\n        }\n        if (type == 0)\n            v = 0;\n        else\n            v = *p++;\n        c1 = c + n + 1;\n        if (v == script_idx) {\n            if (cr_add_interval(cr1, c, c1))\n                goto fail;\n        }\n        c = c1;\n    }\n\n    if (is_ext) {\n        /* add the script extensions */\n        p = unicode_script_ext_table;\n        p_end = unicode_script_ext_table + countof(unicode_script_ext_table);\n        c = 0;\n        while (p < p_end) {\n            b = *p++;\n            if (b < 128) {\n                n = b;\n            } else if (b < 128 + 64) {\n                n = (b - 128) << 8;\n                n |= *p++;\n                n += 128;\n            } else {\n                n = (b - 128 - 64) << 16;\n                n |= *p++ << 8;\n                n |= *p++;\n                n += 128 + (1 << 14);\n            }\n            c1 = c + n + 1;\n            v_len = *p++;\n            if (is_common) {\n                if (v_len != 0) {\n                    if (cr_add_interval(cr2, c, c1))\n                        goto fail;\n                }\n            } else {\n                for(i = 0; i < v_len; i++) {\n                    if (p[i] == script_idx) {\n                        if (cr_add_interval(cr2, c, c1))\n                            goto fail;\n                        break;\n                    }\n                }\n            }\n            p += v_len;\n            c = c1;\n        }\n        if (is_common) {\n            /* remove all the characters with script extensions */\n            if (cr_invert(cr2))\n                goto fail;\n            if (cr_op(cr, cr1->points, cr1->len, cr2->points, cr2->len,\n                      CR_OP_INTER))\n                goto fail;\n        } else {\n            if (cr_op(cr, cr1->points, cr1->len, cr2->points, cr2->len,\n                      CR_OP_UNION))\n                goto fail;\n        }\n        cr_free(cr1);\n        cr_free(cr2);\n    }\n    return 0;\n fail:\n    if (is_ext) {\n        cr_free(cr1);\n        cr_free(cr2);\n    }\n    goto fail;\n}\n\n#define M(id) (1U << UNICODE_GC_ ## id)\n\nstatic int unicode_general_category1(CharRange *cr, uint32_t gc_mask)\n{\n    const uint8_t *p, *p_end;\n    uint32_t c, c0, b, n, v;\n\n    p = unicode_gc_table;\n    p_end = unicode_gc_table + countof(unicode_gc_table);\n    c = 0;\n    while (p < p_end) {\n        b = *p++;\n        n = b >> 5;\n        v = b & 0x1f;\n        if (n == 7) {\n            n = *p++;\n            if (n < 128) {\n                n += 7;\n            } else if (n < 128 + 64) {\n                n = (n - 128) << 8;\n                n |= *p++;\n                n += 7 + 128;\n            } else {\n                n = (n - 128 - 64) << 16;\n                n |= *p++ << 8;\n                n |= *p++;\n                n += 7 + 128 + (1 << 14);\n            }\n        }\n        c0 = c;\n        c += n + 1;\n        if (v == 31) {\n            /* run of Lu / Ll */\n            b = gc_mask & (M(Lu) | M(Ll));\n            if (b != 0) {\n                if (b == (M(Lu) | M(Ll))) {\n                    goto add_range;\n                } else {\n                    c0 += ((gc_mask & M(Ll)) != 0);\n                    for(; c0 < c; c0 += 2) {\n                        if (cr_add_interval(cr, c0, c0 + 1))\n                            return -1;\n                    }\n                }\n            }\n        } else if ((gc_mask >> v) & 1) {\n        add_range:\n            if (cr_add_interval(cr, c0, c))\n                return -1;\n        }\n    }\n    return 0;\n}\n\nstatic int unicode_prop1(CharRange *cr, int prop_idx)\n{\n    const uint8_t *p, *p_end;\n    uint32_t c, c0, b, bit;\n\n    p = unicode_prop_table[prop_idx];\n    p_end = p + unicode_prop_len_table[prop_idx];\n    c = 0;\n    bit = 0;\n    while (p < p_end) {\n        c0 = c;\n        b = *p++;\n        if (b < 64) {\n            c += (b >> 3) + 1;\n            if (bit)  {\n                if (cr_add_interval(cr, c0, c))\n                    return -1;\n            }\n            bit ^= 1;\n            c0 = c;\n            c += (b & 7) + 1;\n        } else if (b >= 0x80) {\n            c += b - 0x80 + 1;\n        } else if (b < 0x60) {\n            c += (((b - 0x40) << 8) | p[0]) + 1;\n            p++;\n        } else {\n            c += (((b - 0x60) << 16) | (p[0] << 8) | p[1]) + 1;\n            p += 2;\n        }\n        if (bit)  {\n            if (cr_add_interval(cr, c0, c))\n                return -1;\n        }\n        bit ^= 1;\n    }\n    return 0;\n}\n\n#define CASE_U (1 << 0)\n#define CASE_L (1 << 1)\n#define CASE_F (1 << 2)\n\n/* use the case conversion table to generate range of characters.\n   CASE_U: set char if modified by uppercasing,\n   CASE_L: set char if modified by lowercasing,\n   CASE_F: set char if modified by case folding,\n */\nstatic int unicode_case1(CharRange *cr, int case_mask)\n{\n#define MR(x) (1 << RUN_TYPE_ ## x)\n    const uint32_t tab_run_mask[3] = {\n        MR(U) | MR(UF) | MR(UL) | MR(LSU) | MR(U2L_399_EXT2) | MR(UF_D20) |\n        MR(UF_D1_EXT) | MR(U_EXT) | MR(U_EXT2) | MR(U_EXT3),\n\n        MR(L) | MR(LF) | MR(UL) | MR(LSU) | MR(U2L_399_EXT2) | MR(LF_EXT) | MR(L_EXT2),\n\n        MR(UF) | MR(LF) | MR(UL) | MR(LSU) | MR(U2L_399_EXT2) | MR(LF_EXT) | MR(UF_D20) | MR(UF_D1_EXT) | MR(LF_EXT),\n    };\n#undef MR\n    uint32_t mask, v, code, type, len, i, idx;\n\n    if (case_mask == 0)\n        return 0;\n    mask = 0;\n    for(i = 0; i < 3; i++) {\n        if ((case_mask >> i) & 1)\n            mask |= tab_run_mask[i];\n    }\n    for(idx = 0; idx < countof(case_conv_table1); idx++) {\n        v = case_conv_table1[idx];\n        type = (v >> (32 - 17 - 7 - 4)) & 0xf;\n        code = v >> (32 - 17);\n        len = (v >> (32 - 17 - 7)) & 0x7f;\n        if ((mask >> type) & 1) {\n            //            printf(\"%d: type=%d %04x %04x\\n\", idx, type, code, code + len - 1);\n            switch(type) {\n            case RUN_TYPE_UL:\n                if ((case_mask & CASE_U) && (case_mask & (CASE_L | CASE_F)))\n                    goto def_case;\n                code += ((case_mask & CASE_U) != 0);\n                for(i = 0; i < len; i += 2) {\n                    if (cr_add_interval(cr, code + i, code + i + 1))\n                        return -1;\n                }\n                break;\n            case RUN_TYPE_LSU:\n                if ((case_mask & CASE_U) && (case_mask & (CASE_L | CASE_F)))\n                    goto def_case;\n                if (!(case_mask & CASE_U)) {\n                    if (cr_add_interval(cr, code, code + 1))\n                        return -1;\n                }\n                if (cr_add_interval(cr, code + 1, code + 2))\n                    return -1;\n                if (case_mask & CASE_U) {\n                    if (cr_add_interval(cr, code + 2, code + 3))\n                        return -1;\n                }\n                break;\n            default:\n            def_case:\n                if (cr_add_interval(cr, code, code + len))\n                    return -1;\n                break;\n            }\n        }\n    }\n    return 0;\n}\n        \ntypedef enum {\n    POP_GC,\n    POP_PROP,\n    POP_CASE,\n    POP_UNION,\n    POP_INTER,\n    POP_XOR,\n    POP_INVERT,\n    POP_END,\n} PropOPEnum;\n\n#define POP_STACK_LEN_MAX 4\n\nstatic int unicode_prop_ops(CharRange *cr, ...)\n{\n    va_list ap;\n    CharRange stack[POP_STACK_LEN_MAX];\n    int stack_len, op, ret, i;\n    uint32_t a;\n    \n    va_start(ap, cr);\n    stack_len = 0;\n    for(;;) {\n        op = va_arg(ap, int);\n        switch(op) {\n        case POP_GC:\n            assert(stack_len < POP_STACK_LEN_MAX);\n            a = va_arg(ap, int);\n            cr_init(&stack[stack_len++], cr->mem_opaque, cr->realloc_func);\n            if (unicode_general_category1(&stack[stack_len - 1], a))\n                goto fail;\n            break;\n        case POP_PROP:\n            assert(stack_len < POP_STACK_LEN_MAX);\n            a = va_arg(ap, int);\n            cr_init(&stack[stack_len++], cr->mem_opaque, cr->realloc_func);\n            if (unicode_prop1(&stack[stack_len - 1], a))\n                goto fail;\n            break;\n        case POP_CASE:\n            assert(stack_len < POP_STACK_LEN_MAX);\n            a = va_arg(ap, int);\n            cr_init(&stack[stack_len++], cr->mem_opaque, cr->realloc_func);\n            if (unicode_case1(&stack[stack_len - 1], a))\n                goto fail;\n            break;\n        case POP_UNION:\n        case POP_INTER:\n        case POP_XOR:\n            {\n                CharRange *cr1, *cr2, *cr3;\n                assert(stack_len >= 2);\n                assert(stack_len < POP_STACK_LEN_MAX);\n                cr1 = &stack[stack_len - 2];\n                cr2 = &stack[stack_len - 1];\n                cr3 = &stack[stack_len++];\n                cr_init(cr3, cr->mem_opaque, cr->realloc_func);\n                if (cr_op(cr3, cr1->points, cr1->len,\n                          cr2->points, cr2->len, op - POP_UNION + CR_OP_UNION))\n                    goto fail;\n                cr_free(cr1);\n                cr_free(cr2);\n                *cr1 = *cr3;\n                stack_len -= 2;\n            }\n            break;\n        case POP_INVERT:\n            assert(stack_len >= 1);\n            if (cr_invert(&stack[stack_len - 1]))\n                goto fail;\n            break;\n        case POP_END:\n            goto done;\n        default:\n            abort();\n        }\n    }\n done:\n    assert(stack_len == 1);\n    ret = cr_copy(cr, &stack[0]);\n    cr_free(&stack[0]);\n    return ret;\n fail:\n    for(i = 0; i < stack_len; i++)\n        cr_free(&stack[i]);\n    return -1;\n}\n\nstatic const uint32_t unicode_gc_mask_table[] = {\n    M(Lu) | M(Ll) | M(Lt), /* LC */\n    M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo), /* L */\n    M(Mn) | M(Mc) | M(Me), /* M */\n    M(Nd) | M(Nl) | M(No), /* N */\n    M(Sm) | M(Sc) | M(Sk) | M(So), /* S */\n    M(Pc) | M(Pd) | M(Ps) | M(Pe) | M(Pi) | M(Pf) | M(Po), /* P */\n    M(Zs) | M(Zl) | M(Zp), /* Z */\n    M(Cc) | M(Cf) | M(Cs) | M(Co) | M(Cn), /* C */\n};\n\n/* 'cr' must be initialized and empty. Return 0 if OK, -1 if error, -2\n   if not found */\nint unicode_general_category(CharRange *cr, const char *gc_name)\n{\n    int gc_idx;\n    uint32_t gc_mask;\n    \n    gc_idx = unicode_find_name(unicode_gc_name_table, gc_name);\n    if (gc_idx < 0)\n        return -2;\n    if (gc_idx <= UNICODE_GC_Co) {\n        gc_mask = (uint64_t)1 << gc_idx;\n    } else {\n        gc_mask = unicode_gc_mask_table[gc_idx - UNICODE_GC_LC];\n    }\n    return unicode_general_category1(cr, gc_mask);\n}\n\n\n/* 'cr' must be initialized and empty. Return 0 if OK, -1 if error, -2\n   if not found */\nint unicode_prop(CharRange *cr, const char *prop_name)\n{\n    int prop_idx, ret;\n    \n    prop_idx = unicode_find_name(unicode_prop_name_table, prop_name);\n    if (prop_idx < 0)\n        return -2;\n    prop_idx += UNICODE_PROP_ASCII_Hex_Digit;\n\n    ret = 0;\n    switch(prop_idx) {\n    case UNICODE_PROP_ASCII:\n        if (cr_add_interval(cr, 0x00, 0x7f + 1))\n            return -1;\n        break;\n    case UNICODE_PROP_Any:\n        if (cr_add_interval(cr, 0x00000, 0x10ffff + 1))\n            return -1;\n        break;\n    case UNICODE_PROP_Assigned:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Cn),\n                               POP_INVERT,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Math:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Sm),\n                               POP_PROP, UNICODE_PROP_Other_Math,\n                               POP_UNION,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Lowercase:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Ll),\n                               POP_PROP, UNICODE_PROP_Other_Lowercase,\n                               POP_UNION,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Uppercase:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Lu),\n                               POP_PROP, UNICODE_PROP_Other_Uppercase,\n                               POP_UNION,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Cased:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Lu) | M(Ll) | M(Lt),\n                               POP_PROP, UNICODE_PROP_Other_Uppercase,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Other_Lowercase,\n                               POP_UNION,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Alphabetic:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl),\n                               POP_PROP, UNICODE_PROP_Other_Uppercase,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Other_Lowercase,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Other_Alphabetic,\n                               POP_UNION,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Grapheme_Base:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Cc) | M(Cf) | M(Cs) | M(Co) | M(Cn) | M(Zl) | M(Zp) | M(Me) | M(Mn),\n                               POP_PROP, UNICODE_PROP_Other_Grapheme_Extend,\n                               POP_UNION,\n                               POP_INVERT,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Grapheme_Extend:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Me) | M(Mn),\n                               POP_PROP, UNICODE_PROP_Other_Grapheme_Extend,\n                               POP_UNION,\n                               POP_END);\n        break;\n    case UNICODE_PROP_XID_Start:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl),\n                               POP_PROP, UNICODE_PROP_Other_ID_Start,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Pattern_Syntax,\n                               POP_PROP, UNICODE_PROP_Pattern_White_Space,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_XID_Start1,\n                               POP_UNION,\n                               POP_INVERT,\n                               POP_INTER,\n                               POP_END);\n        break;\n    case UNICODE_PROP_XID_Continue:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl) |\n                               M(Mn) | M(Mc) | M(Nd) | M(Pc),\n                               POP_PROP, UNICODE_PROP_Other_ID_Start,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Other_ID_Continue,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Pattern_Syntax,\n                               POP_PROP, UNICODE_PROP_Pattern_White_Space,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_XID_Continue1,\n                               POP_UNION,\n                               POP_INVERT,\n                               POP_INTER,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Changes_When_Uppercased:\n        ret = unicode_case1(cr, CASE_U);\n        break;\n    case UNICODE_PROP_Changes_When_Lowercased:\n        ret = unicode_case1(cr, CASE_L);\n        break;\n    case UNICODE_PROP_Changes_When_Casemapped:\n        ret = unicode_case1(cr, CASE_U | CASE_L | CASE_F);\n        break;\n    case UNICODE_PROP_Changes_When_Titlecased:\n        ret = unicode_prop_ops(cr,\n                               POP_CASE, CASE_U,\n                               POP_PROP, UNICODE_PROP_Changes_When_Titlecased1,\n                               POP_XOR,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Changes_When_Casefolded:\n        ret = unicode_prop_ops(cr,\n                               POP_CASE, CASE_F,\n                               POP_PROP, UNICODE_PROP_Changes_When_Casefolded1,\n                               POP_XOR,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Changes_When_NFKC_Casefolded:\n        ret = unicode_prop_ops(cr,\n                               POP_CASE, CASE_F,\n                               POP_PROP, UNICODE_PROP_Changes_When_NFKC_Casefolded1,\n                               POP_XOR,\n                               POP_END);\n        break;\n#if 0\n    case UNICODE_PROP_ID_Start:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl),\n                               POP_PROP, UNICODE_PROP_Other_ID_Start,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Pattern_Syntax,\n                               POP_PROP, UNICODE_PROP_Pattern_White_Space,\n                               POP_UNION,\n                               POP_INVERT,\n                               POP_INTER,\n                               POP_END);\n        break;\n    case UNICODE_PROP_ID_Continue:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Lu) | M(Ll) | M(Lt) | M(Lm) | M(Lo) | M(Nl) |\n                               M(Mn) | M(Mc) | M(Nd) | M(Pc),\n                               POP_PROP, UNICODE_PROP_Other_ID_Start,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Other_ID_Continue,\n                               POP_UNION,\n                               POP_PROP, UNICODE_PROP_Pattern_Syntax,\n                               POP_PROP, UNICODE_PROP_Pattern_White_Space,\n                               POP_UNION,\n                               POP_INVERT,\n                               POP_INTER,\n                               POP_END);\n        break;\n    case UNICODE_PROP_Case_Ignorable:\n        ret = unicode_prop_ops(cr,\n                               POP_GC, M(Mn) | M(Cf) | M(Lm) | M(Sk),\n                               POP_PROP, UNICODE_PROP_Case_Ignorable1,\n                               POP_XOR,\n                               POP_END);\n        break;\n#else\n        /* we use the existing tables */\n    case UNICODE_PROP_ID_Continue:\n        ret = unicode_prop_ops(cr,\n                               POP_PROP, UNICODE_PROP_ID_Start,\n                               POP_PROP, UNICODE_PROP_ID_Continue1,\n                               POP_XOR,\n                               POP_END);\n        break;\n#endif\n    default:\n        if (prop_idx >= countof(unicode_prop_table))\n            return -2;\n        ret = unicode_prop1(cr, prop_idx);\n        break;\n    }\n    return ret;\n}\n\n#endif /* CONFIG_ALL_UNICODE */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/libunicode.h",
    "content": "/*\n * Unicode utilities\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#ifndef LIBUNICODE_H\n#define LIBUNICODE_H\n\n#include <inttypes.h>\n\n#define LRE_BOOL  int       /* for documentation purposes */\n\n/* define it to include all the unicode tables (40KB larger) */\n#define CONFIG_ALL_UNICODE\n\n#define LRE_CC_RES_LEN_MAX 3\n\ntypedef enum {\n    UNICODE_NFC,\n    UNICODE_NFD,\n    UNICODE_NFKC,\n    UNICODE_NFKD,\n} UnicodeNormalizationEnum;\n\nint lre_case_conv(uint32_t *res, uint32_t c, int conv_type);\nLRE_BOOL lre_is_cased(uint32_t c);\nLRE_BOOL lre_is_case_ignorable(uint32_t c);\n\n/* char ranges */\n\ntypedef struct {\n    int len; /* in points, always even */\n    int size;\n    uint32_t *points; /* points sorted by increasing value */\n    void *mem_opaque;\n    void *(*realloc_func)(void *opaque, void *ptr, size_t size);\n} CharRange;\n\ntypedef enum {\n    CR_OP_UNION,\n    CR_OP_INTER,\n    CR_OP_XOR,\n} CharRangeOpEnum;\n\nvoid cr_init(CharRange *cr, void *mem_opaque, void *(*realloc_func)(void *opaque, void *ptr, size_t size));\nvoid cr_free(CharRange *cr);\nint cr_realloc(CharRange *cr, int size);\nint cr_copy(CharRange *cr, const CharRange *cr1);\n\nstatic inline int cr_add_point(CharRange *cr, uint32_t v)\n{\n    if (cr->len >= cr->size) {\n        if (cr_realloc(cr, cr->len + 1))\n            return -1;\n    }\n    cr->points[cr->len++] = v;\n    return 0;\n}\n\nstatic inline int cr_add_interval(CharRange *cr, uint32_t c1, uint32_t c2)\n{\n    if ((cr->len + 2) > cr->size) {\n        if (cr_realloc(cr, cr->len + 2))\n            return -1;\n    }\n    cr->points[cr->len++] = c1;\n    cr->points[cr->len++] = c2;\n    return 0;\n}\n\nint cr_union1(CharRange *cr, const uint32_t *b_pt, int b_len);\n\nstatic inline int cr_union_interval(CharRange *cr, uint32_t c1, uint32_t c2)\n{\n    uint32_t b_pt[2];\n    b_pt[0] = c1;\n    b_pt[1] = c2 + 1;\n    return cr_union1(cr, b_pt, 2);\n}\n\nint cr_op(CharRange *cr, const uint32_t *a_pt, int a_len,\n          const uint32_t *b_pt, int b_len, int op);\n\nint cr_invert(CharRange *cr);\n\n#ifdef CONFIG_ALL_UNICODE\n\nLRE_BOOL lre_is_id_start(uint32_t c);\nLRE_BOOL lre_is_id_continue(uint32_t c);\n\nint unicode_normalize(uint32_t **pdst, const uint32_t *src, int src_len,\n                      UnicodeNormalizationEnum n_type,\n                      void *opaque, void *(*realloc_func)(void *opaque, void *ptr, size_t size));\n\n/* Unicode character range functions */\n\nint unicode_script(CharRange *cr,\n                   const char *script_name, LRE_BOOL is_ext);\nint unicode_general_category(CharRange *cr, const char *gc_name);\nint unicode_prop(CharRange *cr, const char *prop_name);\n\n#endif /* CONFIG_ALL_UNICODE */\n\n#undef LRE_BOOL\n\n#endif /* LIBUNICODE_H */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/list.h",
    "content": "/*\n * Linux klist like system\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#ifndef LIST_H\n#define LIST_H\n\n#ifndef NULL\n#include <stddef.h>\n#endif\n\nstruct list_head {\n    struct list_head *prev;\n    struct list_head *next;\n};\n\n#define LIST_HEAD_INIT(el) { &(el), &(el) }\n\n/* return the pointer of type 'type *' containing 'el' as field 'member' */\n#define list_entry(el, type, member) \\\n    ((type *)((uint8_t *)(el) - offsetof(type, member)))\n\nstatic inline void init_list_head(struct list_head *head)\n{\n    head->prev = head;\n    head->next = head;\n}\n\n/* insert 'el' between 'prev' and 'next' */\nstatic inline void __list_add(struct list_head *el, \n                              struct list_head *prev, struct list_head *next)\n{\n    prev->next = el;\n    el->prev = prev;\n    el->next = next;\n    next->prev = el;\n}\n\n/* add 'el' at the head of the list 'head' (= after element head) */\nstatic inline void list_add(struct list_head *el, struct list_head *head)\n{\n    __list_add(el, head, head->next);\n}\n\n/* add 'el' at the end of the list 'head' (= before element head) */\nstatic inline void list_add_tail(struct list_head *el, struct list_head *head)\n{\n    __list_add(el, head->prev, head);\n}\n\nstatic inline void list_del(struct list_head *el)\n{\n    struct list_head *prev, *next;\n    prev = el->prev;\n    next = el->next;\n    prev->next = next;\n    next->prev = prev;\n    el->prev = NULL; /* fail safe */\n    el->next = NULL; /* fail safe */\n}\n\nstatic inline int list_empty(struct list_head *el)\n{\n    return el->next == el;\n}\n\n#define list_for_each(el, head) \\\n  for(el = (head)->next; el != (head); el = el->next)\n\n#define list_for_each_safe(el, el1, head)                \\\n    for(el = (head)->next, el1 = el->next; el != (head); \\\n        el = el1, el1 = el->next)\n\n#define list_for_each_prev(el, head) \\\n  for(el = (head)->prev; el != (head); el = el->prev)\n\n#define list_for_each_prev_safe(el, el1, head)           \\\n    for(el = (head)->prev, el1 = el->prev; el != (head); \\\n        el = el1, el1 = el->prev)\n\n#endif /* LIST_H */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/qjs.c",
    "content": "/*\n * QuickJS stand alone interpreter\n * \n * Copyright (c) 2017-2021 Fabrice Bellard\n * Copyright (c) 2017-2021 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <inttypes.h>\n#include <string.h>\n#include <assert.h>\n#include <unistd.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <time.h>\n#if defined(__APPLE__)\n#include <malloc/malloc.h>\n#elif defined(__linux__)\n#include <malloc.h>\n#endif\n\n#include \"cutils.h\"\n#include \"quickjs-libc.h\"\n\nextern const uint8_t qjsc_repl[];\nextern const uint32_t qjsc_repl_size;\n#ifdef CONFIG_BIGNUM\nextern const uint8_t qjsc_qjscalc[];\nextern const uint32_t qjsc_qjscalc_size;\nstatic int bignum_ext;\n#endif\n\nstatic int eval_buf(JSContext *ctx, const void *buf, int buf_len,\n                    const char *filename, int eval_flags)\n{\n    JSValue val;\n    int ret;\n\n    if ((eval_flags & JS_EVAL_TYPE_MASK) == JS_EVAL_TYPE_MODULE) {\n        /* for the modules, we compile then run to be able to set\n           import.meta */\n        val = JS_Eval(ctx, buf, buf_len, filename,\n                      eval_flags | JS_EVAL_FLAG_COMPILE_ONLY);\n        if (!JS_IsException(val)) {\n            js_module_set_import_meta(ctx, val, TRUE, TRUE);\n            val = JS_EvalFunction(ctx, val);\n        }\n    } else {\n        val = JS_Eval(ctx, buf, buf_len, filename, eval_flags);\n    }\n    if (JS_IsException(val)) {\n        js_std_dump_error(ctx);\n        ret = -1;\n    } else {\n        ret = 0;\n    }\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nstatic int eval_file(JSContext *ctx, const char *filename, int module)\n{\n    uint8_t *buf;\n    int ret, eval_flags;\n    size_t buf_len;\n    \n    buf = js_load_file(ctx, &buf_len, filename);\n    if (!buf) {\n        perror(filename);\n        exit(1);\n    }\n\n    if (module < 0) {\n        module = (has_suffix(filename, \".mjs\") ||\n                  JS_DetectModule((const char *)buf, buf_len));\n    }\n    if (module)\n        eval_flags = JS_EVAL_TYPE_MODULE;\n    else\n        eval_flags = JS_EVAL_TYPE_GLOBAL;\n    ret = eval_buf(ctx, buf, buf_len, filename, eval_flags);\n    js_free(ctx, buf);\n    return ret;\n}\n\n/* also used to initialize the worker context */\nstatic JSContext *JS_NewCustomContext(JSRuntime *rt)\n{\n    JSContext *ctx;\n    ctx = JS_NewContext(rt);\n    if (!ctx)\n        return NULL;\n#ifdef CONFIG_BIGNUM\n    if (bignum_ext) {\n        JS_AddIntrinsicBigFloat(ctx);\n        JS_AddIntrinsicBigDecimal(ctx);\n        JS_AddIntrinsicOperators(ctx);\n        JS_EnableBignumExt(ctx, TRUE);\n    }\n#endif\n    /* system modules */\n    js_init_module_std(ctx, \"std\");\n    js_init_module_os(ctx, \"os\");\n    return ctx;\n}\n\n#if defined(__APPLE__)\n#define MALLOC_OVERHEAD  0\n#else\n#define MALLOC_OVERHEAD  8\n#endif\n\nstruct trace_malloc_data {\n    uint8_t *base;\n};\n\nstatic inline unsigned long long js_trace_malloc_ptr_offset(uint8_t *ptr,\n                                                struct trace_malloc_data *dp)\n{\n    return ptr - dp->base;\n}\n\n/* default memory allocation functions with memory limitation */\nstatic inline size_t js_trace_malloc_usable_size(void *ptr)\n{\n#if defined(__APPLE__)\n    return malloc_size(ptr);\n#elif defined(_WIN32)\n    return _msize(ptr);\n#elif defined(EMSCRIPTEN)\n    return 0;\n#elif defined(__linux__)\n    return malloc_usable_size(ptr);\n#else\n    /* change this to `return 0;` if compilation fails */\n    return malloc_usable_size(ptr);\n#endif\n}\n\nstatic void\n#ifdef _WIN32\n/* mingw printf is used */\n__attribute__((format(gnu_printf, 2, 3)))\n#else\n__attribute__((format(printf, 2, 3)))\n#endif\n    js_trace_malloc_printf(JSMallocState *s, const char *fmt, ...)\n{\n    va_list ap;\n    int c;\n\n    va_start(ap, fmt);\n    while ((c = *fmt++) != '\\0') {\n        if (c == '%') {\n            /* only handle %p and %zd */\n            if (*fmt == 'p') {\n                uint8_t *ptr = va_arg(ap, void *);\n                if (ptr == NULL) {\n                    printf(\"NULL\");\n                } else {\n                    printf(\"H%+06lld.%zd\",\n                           js_trace_malloc_ptr_offset(ptr, s->opaque),\n                           js_trace_malloc_usable_size(ptr));\n                }\n                fmt++;\n                continue;\n            }\n            if (fmt[0] == 'z' && fmt[1] == 'd') {\n                size_t sz = va_arg(ap, size_t);\n                printf(\"%zd\", sz);\n                fmt += 2;\n                continue;\n            }\n        }\n        putc(c, stdout);\n    }\n    va_end(ap);\n}\n\nstatic void js_trace_malloc_init(struct trace_malloc_data *s)\n{\n    free(s->base = malloc(8));\n}\n\nstatic void *js_trace_malloc(JSMallocState *s, size_t size)\n{\n    void *ptr;\n\n    /* Do not allocate zero bytes: behavior is platform dependent */\n    assert(size != 0);\n\n    if (unlikely(s->malloc_size + size > s->malloc_limit))\n        return NULL;\n    ptr = malloc(size);\n    js_trace_malloc_printf(s, \"A %zd -> %p\\n\", size, ptr);\n    if (ptr) {\n        s->malloc_count++;\n        s->malloc_size += js_trace_malloc_usable_size(ptr) + MALLOC_OVERHEAD;\n    }\n    return ptr;\n}\n\nstatic void js_trace_free(JSMallocState *s, void *ptr)\n{\n    if (!ptr)\n        return;\n\n    js_trace_malloc_printf(s, \"F %p\\n\", ptr);\n    s->malloc_count--;\n    s->malloc_size -= js_trace_malloc_usable_size(ptr) + MALLOC_OVERHEAD;\n    free(ptr);\n}\n\nstatic void *js_trace_realloc(JSMallocState *s, void *ptr, size_t size)\n{\n    size_t old_size;\n\n    if (!ptr) {\n        if (size == 0)\n            return NULL;\n        return js_trace_malloc(s, size);\n    }\n    old_size = js_trace_malloc_usable_size(ptr);\n    if (size == 0) {\n        js_trace_malloc_printf(s, \"R %zd %p\\n\", size, ptr);\n        s->malloc_count--;\n        s->malloc_size -= old_size + MALLOC_OVERHEAD;\n        free(ptr);\n        return NULL;\n    }\n    if (s->malloc_size + size - old_size > s->malloc_limit)\n        return NULL;\n\n    js_trace_malloc_printf(s, \"R %zd %p\", size, ptr);\n\n    ptr = realloc(ptr, size);\n    js_trace_malloc_printf(s, \" -> %p\\n\", ptr);\n    if (ptr) {\n        s->malloc_size += js_trace_malloc_usable_size(ptr) - old_size;\n    }\n    return ptr;\n}\n\nstatic const JSMallocFunctions trace_mf = {\n    js_trace_malloc,\n    js_trace_free,\n    js_trace_realloc,\n#if defined(__APPLE__)\n    malloc_size,\n#elif defined(_WIN32)\n    (size_t (*)(const void *))_msize,\n#elif defined(EMSCRIPTEN)\n    NULL,\n#elif defined(__linux__)\n    (size_t (*)(const void *))malloc_usable_size,\n#else\n    /* change this to `NULL,` if compilation fails */\n    malloc_usable_size,\n#endif\n};\n\n#define PROG_NAME \"qjs\"\n\nvoid help(void)\n{\n    printf(\"QuickJS version \" CONFIG_VERSION \"\\n\"\n           \"usage: \" PROG_NAME \" [options] [file [args]]\\n\"\n           \"-h  --help         list options\\n\"\n           \"-e  --eval EXPR    evaluate EXPR\\n\"\n           \"-i  --interactive  go to interactive mode\\n\"\n           \"-m  --module       load as ES6 module (default=autodetect)\\n\"\n           \"    --script       load as ES6 script (default=autodetect)\\n\"\n           \"-I  --include file include an additional file\\n\"\n           \"    --std          make 'std' and 'os' available to the loaded script\\n\"\n#ifdef CONFIG_BIGNUM\n           \"    --bignum       enable the bignum extensions (BigFloat, BigDecimal)\\n\"\n           \"    --qjscalc      load the QJSCalc runtime (default if invoked as qjscalc)\\n\"\n#endif\n           \"-T  --trace        trace memory allocation\\n\"\n           \"-d  --dump         dump the memory usage stats\\n\"\n           \"    --memory-limit n       limit the memory usage to 'n' bytes\\n\"\n           \"    --stack-size n         limit the stack size to 'n' bytes\\n\"\n           \"    --unhandled-rejection  dump unhandled promise rejections\\n\"\n           \"-q  --quit         just instantiate the interpreter and quit\\n\");\n    exit(1);\n}\n\nint main(int argc, char **argv)\n{\n    JSRuntime *rt;\n    JSContext *ctx;\n    struct trace_malloc_data trace_data = { NULL };\n    int optind;\n    char *expr = NULL;\n    int interactive = 0;\n    int dump_memory = 0;\n    int trace_memory = 0;\n    int empty_run = 0;\n    int module = -1;\n    int load_std = 0;\n    int dump_unhandled_promise_rejection = 0;\n    size_t memory_limit = 0;\n    char *include_list[32];\n    int i, include_count = 0;\n#ifdef CONFIG_BIGNUM\n    int load_jscalc;\n#endif\n    size_t stack_size = 0;\n    \n#ifdef CONFIG_BIGNUM\n    /* load jscalc runtime if invoked as 'qjscalc' */\n    {\n        const char *p, *exename;\n        exename = argv[0];\n        p = strrchr(exename, '/');\n        if (p)\n            exename = p + 1;\n        load_jscalc = !strcmp(exename, \"qjscalc\");\n    }\n#endif\n    \n    /* cannot use getopt because we want to pass the command line to\n       the script */\n    optind = 1;\n    while (optind < argc && *argv[optind] == '-') {\n        char *arg = argv[optind] + 1;\n        const char *longopt = \"\";\n        /* a single - is not an option, it also stops argument scanning */\n        if (!*arg)\n            break;\n        optind++;\n        if (*arg == '-') {\n            longopt = arg + 1;\n            arg += strlen(arg);\n            /* -- stops argument scanning */\n            if (!*longopt)\n                break;\n        }\n        for (; *arg || *longopt; longopt = \"\") {\n            char opt = *arg;\n            if (opt)\n                arg++;\n            if (opt == 'h' || opt == '?' || !strcmp(longopt, \"help\")) {\n                help();\n                continue;\n            }\n            if (opt == 'e' || !strcmp(longopt, \"eval\")) {\n                if (*arg) {\n                    expr = arg;\n                    break;\n                }\n                if (optind < argc) {\n                    expr = argv[optind++];\n                    break;\n                }\n                fprintf(stderr, \"qjs: missing expression for -e\\n\");\n                exit(2);\n            }\n            if (opt == 'I' || !strcmp(longopt, \"include\")) {\n                if (optind >= argc) {\n                    fprintf(stderr, \"expecting filename\");\n                    exit(1);\n                }\n                if (include_count >= countof(include_list)) {\n                    fprintf(stderr, \"too many included files\");\n                    exit(1);\n                }\n                include_list[include_count++] = argv[optind++];\n                continue;\n            }\n            if (opt == 'i' || !strcmp(longopt, \"interactive\")) {\n                interactive++;\n                continue;\n            }\n            if (opt == 'm' || !strcmp(longopt, \"module\")) {\n                module = 1;\n                continue;\n            }\n            if (!strcmp(longopt, \"script\")) {\n                module = 0;\n                continue;\n            }\n            if (opt == 'd' || !strcmp(longopt, \"dump\")) {\n                dump_memory++;\n                continue;\n            }\n            if (opt == 'T' || !strcmp(longopt, \"trace\")) {\n                trace_memory++;\n                continue;\n            }\n            if (!strcmp(longopt, \"std\")) {\n                load_std = 1;\n                continue;\n            }\n            if (!strcmp(longopt, \"unhandled-rejection\")) {\n                dump_unhandled_promise_rejection = 1;\n                continue;\n            }\n#ifdef CONFIG_BIGNUM\n            if (!strcmp(longopt, \"bignum\")) {\n                bignum_ext = 1;\n                continue;\n            }\n            if (!strcmp(longopt, \"qjscalc\")) {\n                load_jscalc = 1;\n                continue;\n            }\n#endif\n            if (opt == 'q' || !strcmp(longopt, \"quit\")) {\n                empty_run++;\n                continue;\n            }\n            if (!strcmp(longopt, \"memory-limit\")) {\n                if (optind >= argc) {\n                    fprintf(stderr, \"expecting memory limit\");\n                    exit(1);\n                }\n                memory_limit = (size_t)strtod(argv[optind++], NULL);\n                continue;\n            }\n            if (!strcmp(longopt, \"stack-size\")) {\n                if (optind >= argc) {\n                    fprintf(stderr, \"expecting stack size\");\n                    exit(1);\n                }\n                stack_size = (size_t)strtod(argv[optind++], NULL);\n                continue;\n            }\n            if (opt) {\n                fprintf(stderr, \"qjs: unknown option '-%c'\\n\", opt);\n            } else {\n                fprintf(stderr, \"qjs: unknown option '--%s'\\n\", longopt);\n            }\n            help();\n        }\n    }\n\n    if (load_jscalc)\n        bignum_ext = 1;\n\n    if (trace_memory) {\n        js_trace_malloc_init(&trace_data);\n        rt = JS_NewRuntime2(&trace_mf, &trace_data);\n    } else {\n        rt = JS_NewRuntime();\n    }\n    if (!rt) {\n        fprintf(stderr, \"qjs: cannot allocate JS runtime\\n\");\n        exit(2);\n    }\n    if (memory_limit != 0)\n        JS_SetMemoryLimit(rt, memory_limit);\n    if (stack_size != 0)\n        JS_SetMaxStackSize(rt, stack_size);\n    js_std_set_worker_new_context_func(JS_NewCustomContext);\n    js_std_init_handlers(rt);\n    ctx = JS_NewCustomContext(rt);\n    if (!ctx) {\n        fprintf(stderr, \"qjs: cannot allocate JS context\\n\");\n        exit(2);\n    }\n\n    /* loader for ES6 modules */\n    JS_SetModuleLoaderFunc(rt, NULL, js_module_loader, NULL);\n\n    if (dump_unhandled_promise_rejection) {\n        JS_SetHostPromiseRejectionTracker(rt, js_std_promise_rejection_tracker,\n                                          NULL);\n    }\n    \n    if (!empty_run) {\n#ifdef CONFIG_BIGNUM\n        if (load_jscalc) {\n            js_std_eval_binary(ctx, qjsc_qjscalc, qjsc_qjscalc_size, 0);\n        }\n#endif\n        js_std_add_helpers(ctx, argc - optind, argv + optind);\n\n        /* make 'std' and 'os' visible to non module code */\n        if (load_std) {\n            const char *str = \"import * as std from 'std';\\n\"\n                \"import * as os from 'os';\\n\"\n                \"globalThis.std = std;\\n\"\n                \"globalThis.os = os;\\n\";\n            eval_buf(ctx, str, strlen(str), \"<input>\", JS_EVAL_TYPE_MODULE);\n        }\n\n        for(i = 0; i < include_count; i++) {\n            if (eval_file(ctx, include_list[i], module))\n                goto fail;\n        }\n\n        if (expr) {\n            if (eval_buf(ctx, expr, strlen(expr), \"<cmdline>\", 0))\n                goto fail;\n        } else\n        if (optind >= argc) {\n            /* interactive mode */\n            interactive = 1;\n        } else {\n            const char *filename;\n            filename = argv[optind];\n            if (eval_file(ctx, filename, module))\n                goto fail;\n        }\n        if (interactive) {\n            js_std_eval_binary(ctx, qjsc_repl, qjsc_repl_size, 0);\n        }\n        js_std_loop(ctx);\n    }\n    \n    if (dump_memory) {\n        JSMemoryUsage stats;\n        JS_ComputeMemoryUsage(rt, &stats);\n        JS_DumpMemoryUsage(stdout, &stats, rt);\n    }\n    js_std_free_handlers(rt);\n    JS_FreeContext(ctx);\n    JS_FreeRuntime(rt);\n\n    if (empty_run && dump_memory) {\n        clock_t t[5];\n        double best[5];\n        int i, j;\n        for (i = 0; i < 100; i++) {\n            t[0] = clock();\n            rt = JS_NewRuntime();\n            t[1] = clock();\n            ctx = JS_NewContext(rt);\n            t[2] = clock();\n            JS_FreeContext(ctx);\n            t[3] = clock();\n            JS_FreeRuntime(rt);\n            t[4] = clock();\n            for (j = 4; j > 0; j--) {\n                double ms = 1000.0 * (t[j] - t[j - 1]) / CLOCKS_PER_SEC;\n                if (i == 0 || best[j] > ms)\n                    best[j] = ms;\n            }\n        }\n        printf(\"\\nInstantiation times (ms): %.3f = %.3f+%.3f+%.3f+%.3f\\n\",\n               best[1] + best[2] + best[3] + best[4],\n               best[1], best[2], best[3], best[4]);\n    }\n    return 0;\n fail:\n    js_std_free_handlers(rt);\n    JS_FreeContext(ctx);\n    JS_FreeRuntime(rt);\n    return 1;\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/qjsc.c",
    "content": "/*\n * QuickJS command line compiler\n * \n * Copyright (c) 2018-2021 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <inttypes.h>\n#include <string.h>\n#include <assert.h>\n#include <unistd.h>\n#include <errno.h>\n#if !defined(_WIN32)\n#include <sys/wait.h>\n#endif\n\n#include \"cutils.h\"\n#include \"quickjs-libc.h\"\n\ntypedef struct {\n    char *name;\n    char *short_name;\n    int flags;\n} namelist_entry_t;\n\ntypedef struct namelist_t {\n    namelist_entry_t *array;\n    int count;\n    int size;\n} namelist_t;\n\ntypedef struct {\n    const char *option_name;\n    const char *init_name;\n} FeatureEntry;\n\nstatic namelist_t cname_list;\nstatic namelist_t cmodule_list;\nstatic namelist_t init_module_list;\nstatic uint64_t feature_bitmap;\nstatic FILE *outfile;\nstatic BOOL byte_swap;\nstatic BOOL dynamic_export;\nstatic const char *c_ident_prefix = \"qjsc_\";\n\n#define FE_ALL (-1)\n\nstatic const FeatureEntry feature_list[] = {\n    { \"date\", \"Date\" },\n    { \"eval\", \"Eval\" },\n    { \"string-normalize\", \"StringNormalize\" },\n    { \"regexp\", \"RegExp\" },\n    { \"json\", \"JSON\" },\n    { \"proxy\", \"Proxy\" },\n    { \"map\", \"MapSet\" },\n    { \"typedarray\", \"TypedArrays\" },\n    { \"promise\", \"Promise\" },\n#define FE_MODULE_LOADER 9\n    { \"module-loader\", NULL },\n#ifdef CONFIG_BIGNUM\n    { \"bigint\", \"BigInt\" },\n#endif\n};\n\nvoid namelist_add(namelist_t *lp, const char *name, const char *short_name,\n                  int flags)\n{\n    namelist_entry_t *e;\n    if (lp->count == lp->size) {\n        size_t newsize = lp->size + (lp->size >> 1) + 4;\n        namelist_entry_t *a =\n            realloc(lp->array, sizeof(lp->array[0]) * newsize);\n        /* XXX: check for realloc failure */\n        lp->array = a;\n        lp->size = newsize;\n    }\n    e =  &lp->array[lp->count++];\n    e->name = strdup(name);\n    if (short_name)\n        e->short_name = strdup(short_name);\n    else\n        e->short_name = NULL;\n    e->flags = flags;\n}\n\nvoid namelist_free(namelist_t *lp)\n{\n    while (lp->count > 0) {\n        namelist_entry_t *e = &lp->array[--lp->count];\n        free(e->name);\n        free(e->short_name);\n    }\n    free(lp->array);\n    lp->array = NULL;\n    lp->size = 0;\n}\n\nnamelist_entry_t *namelist_find(namelist_t *lp, const char *name)\n{\n    int i;\n    for(i = 0; i < lp->count; i++) {\n        namelist_entry_t *e = &lp->array[i];\n        if (!strcmp(e->name, name))\n            return e;\n    }\n    return NULL;\n}\n\nstatic void get_c_name(char *buf, size_t buf_size, const char *file)\n{\n    const char *p, *r;\n    size_t len, i;\n    int c;\n    char *q;\n    \n    p = strrchr(file, '/');\n    if (!p)\n        p = file;\n    else\n        p++;\n    r = strrchr(p, '.');\n    if (!r)\n        len = strlen(p);\n    else\n        len = r - p;\n    pstrcpy(buf, buf_size, c_ident_prefix);\n    q = buf + strlen(buf);\n    for(i = 0; i < len; i++) {\n        c = p[i];\n        if (!((c >= '0' && c <= '9') ||\n              (c >= 'A' && c <= 'Z') ||\n              (c >= 'a' && c <= 'z'))) {\n            c = '_';\n        }\n        if ((q - buf) < buf_size - 1)\n            *q++ = c;\n    }\n    *q = '\\0';\n}\n\nstatic void dump_hex(FILE *f, const uint8_t *buf, size_t len)\n{\n    size_t i, col;\n    col = 0;\n    for(i = 0; i < len; i++) {\n        fprintf(f, \" 0x%02x,\", buf[i]);\n        if (++col == 8) {\n            fprintf(f, \"\\n\");\n            col = 0;\n        }\n    }\n    if (col != 0)\n        fprintf(f, \"\\n\");\n}\n\nstatic void output_object_code(JSContext *ctx,\n                               FILE *fo, JSValueConst obj, const char *c_name,\n                               BOOL load_only)\n{\n    uint8_t *out_buf;\n    size_t out_buf_len;\n    int flags;\n    flags = JS_WRITE_OBJ_BYTECODE;\n    if (byte_swap)\n        flags |= JS_WRITE_OBJ_BSWAP;\n    out_buf = JS_WriteObject(ctx, &out_buf_len, obj, flags);\n    if (!out_buf) {\n        js_std_dump_error(ctx);\n        exit(1);\n    }\n\n    namelist_add(&cname_list, c_name, NULL, load_only);\n    \n    fprintf(fo, \"const uint32_t %s_size = %u;\\n\\n\", \n            c_name, (unsigned int)out_buf_len);\n    fprintf(fo, \"const uint8_t %s[%u] = {\\n\",\n            c_name, (unsigned int)out_buf_len);\n    dump_hex(fo, out_buf, out_buf_len);\n    fprintf(fo, \"};\\n\\n\");\n\n    js_free(ctx, out_buf);\n}\n\nstatic int js_module_dummy_init(JSContext *ctx, JSModuleDef *m)\n{\n    /* should never be called when compiling JS code */\n    abort();\n}\n\nstatic void find_unique_cname(char *cname, size_t cname_size)\n{\n    char cname1[1024];\n    int suffix_num;\n    size_t len, max_len;\n    assert(cname_size >= 32);\n    /* find a C name not matching an existing module C name by\n       adding a numeric suffix */\n    len = strlen(cname);\n    max_len = cname_size - 16;\n    if (len > max_len)\n        cname[max_len] = '\\0';\n    suffix_num = 1;\n    for(;;) {\n        snprintf(cname1, sizeof(cname1), \"%s_%d\", cname, suffix_num);\n        if (!namelist_find(&cname_list, cname1))\n            break;\n        suffix_num++;\n    }\n    pstrcpy(cname, cname_size, cname1);\n}\n\nJSModuleDef *jsc_module_loader(JSContext *ctx,\n                              const char *module_name, void *opaque)\n{\n    JSModuleDef *m;\n    namelist_entry_t *e;\n\n    /* check if it is a declared C or system module */\n    e = namelist_find(&cmodule_list, module_name);\n    if (e) {\n        /* add in the static init module list */\n        namelist_add(&init_module_list, e->name, e->short_name, 0);\n        /* create a dummy module */\n        m = JS_NewCModule(ctx, module_name, js_module_dummy_init);\n    } else if (has_suffix(module_name, \".so\")) {\n        fprintf(stderr, \"Warning: binary module '%s' will be dynamically loaded\\n\", module_name);\n        /* create a dummy module */\n        m = JS_NewCModule(ctx, module_name, js_module_dummy_init);\n        /* the resulting executable will export its symbols for the\n           dynamic library */\n        dynamic_export = TRUE;\n    } else {\n        size_t buf_len;\n        uint8_t *buf;\n        JSValue func_val;\n        char cname[1024];\n        \n        buf = js_load_file(ctx, &buf_len, module_name);\n        if (!buf) {\n            JS_ThrowReferenceError(ctx, \"could not load module filename '%s'\",\n                                   module_name);\n            return NULL;\n        }\n        \n        /* compile the module */\n        func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name,\n                           JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);\n        js_free(ctx, buf);\n        if (JS_IsException(func_val))\n            return NULL;\n        get_c_name(cname, sizeof(cname), module_name);\n        if (namelist_find(&cname_list, cname)) {\n            find_unique_cname(cname, sizeof(cname));\n        }\n        output_object_code(ctx, outfile, func_val, cname, TRUE);\n        \n        /* the module is already referenced, so we must free it */\n        m = JS_VALUE_GET_PTR(func_val);\n        JS_FreeValue(ctx, func_val);\n    }\n    return m;\n}\n\nstatic void compile_file(JSContext *ctx, FILE *fo,\n                         const char *filename,\n                         const char *c_name1,\n                         int module)\n{\n    uint8_t *buf;\n    char c_name[1024];\n    int eval_flags;\n    JSValue obj;\n    size_t buf_len;\n    \n    buf = js_load_file(ctx, &buf_len, filename);\n    if (!buf) {\n        fprintf(stderr, \"Could not load '%s'\\n\", filename);\n        exit(1);\n    }\n    eval_flags = JS_EVAL_FLAG_COMPILE_ONLY;\n    if (module < 0) {\n        module = (has_suffix(filename, \".mjs\") ||\n                  JS_DetectModule((const char *)buf, buf_len));\n    }\n    if (module)\n        eval_flags |= JS_EVAL_TYPE_MODULE;\n    else\n        eval_flags |= JS_EVAL_TYPE_GLOBAL;\n    obj = JS_Eval(ctx, (const char *)buf, buf_len, filename, eval_flags);\n    if (JS_IsException(obj)) {\n        js_std_dump_error(ctx);\n        exit(1);\n    }\n    js_free(ctx, buf);\n    if (c_name1) {\n        pstrcpy(c_name, sizeof(c_name), c_name1);\n    } else {\n        get_c_name(c_name, sizeof(c_name), filename);\n    }\n    output_object_code(ctx, fo, obj, c_name, FALSE);\n    JS_FreeValue(ctx, obj);\n}\n\nstatic const char main_c_template1[] =\n    \"int main(int argc, char **argv)\\n\"\n    \"{\\n\"\n    \"  JSRuntime *rt;\\n\"\n    \"  JSContext *ctx;\\n\"\n    \"  rt = JS_NewRuntime();\\n\"\n    \"  js_std_set_worker_new_context_func(JS_NewCustomContext);\\n\"\n    \"  js_std_init_handlers(rt);\\n\"\n    ;\n\nstatic const char main_c_template2[] =\n    \"  js_std_loop(ctx);\\n\"\n    \"  JS_FreeContext(ctx);\\n\"\n    \"  JS_FreeRuntime(rt);\\n\"\n    \"  return 0;\\n\"\n    \"}\\n\";\n\n#define PROG_NAME \"qjsc\"\n\nvoid help(void)\n{\n    printf(\"QuickJS Compiler version \" CONFIG_VERSION \"\\n\"\n           \"usage: \" PROG_NAME \" [options] [files]\\n\"\n           \"\\n\"\n           \"options are:\\n\"\n           \"-c          only output bytecode in a C file\\n\"\n           \"-e          output main() and bytecode in a C file (default = executable output)\\n\"\n           \"-o output   set the output filename\\n\"\n           \"-N cname    set the C name of the generated data\\n\"\n           \"-m          compile as Javascript module (default=autodetect)\\n\"\n           \"-D module_name         compile a dynamically loaded module or worker\\n\"\n           \"-M module_name[,cname] add initialization code for an external C module\\n\"\n           \"-x          byte swapped output\\n\"\n           \"-p prefix   set the prefix of the generated C names\\n\"\n           \"-S n        set the maximum stack size to 'n' bytes (default=%d)\\n\",\n           JS_DEFAULT_STACK_SIZE);\n#ifdef CONFIG_LTO\n    {\n        int i;\n        printf(\"-flto       use link time optimization\\n\");\n        printf(\"-fbignum    enable bignum extensions\\n\");\n        printf(\"-fno-[\");\n        for(i = 0; i < countof(feature_list); i++) {\n            if (i != 0)\n                printf(\"|\");\n            printf(\"%s\", feature_list[i].option_name);\n        }\n        printf(\"]\\n\"\n               \"            disable selected language features (smaller code size)\\n\");\n    }\n#endif\n    exit(1);\n}\n\n#if defined(CONFIG_CC) && !defined(_WIN32)\n\nint exec_cmd(char **argv)\n{\n    int pid, status, ret;\n\n    pid = fork();\n    if (pid == 0) {\n        execvp(argv[0], argv);\n        exit(1);\n    } \n\n    for(;;) {\n        ret = waitpid(pid, &status, 0);\n        if (ret == pid && WIFEXITED(status))\n            break;\n    }\n    return WEXITSTATUS(status);\n}\n\nstatic int output_executable(const char *out_filename, const char *cfilename,\n                             BOOL use_lto, BOOL verbose, const char *exename)\n{\n    const char *argv[64];\n    const char **arg, *bn_suffix, *lto_suffix;\n    char libjsname[1024];\n    char exe_dir[1024], inc_dir[1024], lib_dir[1024], buf[1024], *p;\n    int ret;\n    \n    /* get the directory of the executable */\n    pstrcpy(exe_dir, sizeof(exe_dir), exename);\n    p = strrchr(exe_dir, '/');\n    if (p) {\n        *p = '\\0';\n    } else {\n        pstrcpy(exe_dir, sizeof(exe_dir), \".\");\n    }\n\n    /* if 'quickjs.h' is present at the same path as the executable, we\n       use it as include and lib directory */\n    snprintf(buf, sizeof(buf), \"%s/quickjs.h\", exe_dir);\n    if (access(buf, R_OK) == 0) {\n        pstrcpy(inc_dir, sizeof(inc_dir), exe_dir);\n        pstrcpy(lib_dir, sizeof(lib_dir), exe_dir);\n    } else {\n        snprintf(inc_dir, sizeof(inc_dir), \"%s/include/quickjs\", CONFIG_PREFIX);\n        snprintf(lib_dir, sizeof(lib_dir), \"%s/lib/quickjs\", CONFIG_PREFIX);\n    }\n    \n    lto_suffix = \"\";\n    bn_suffix = \"\";\n    \n    arg = argv;\n    *arg++ = CONFIG_CC;\n    *arg++ = \"-O2\";\n#ifdef CONFIG_LTO\n    if (use_lto) {\n        *arg++ = \"-flto\";\n        lto_suffix = \".lto\";\n    }\n#endif\n    /* XXX: use the executable path to find the includes files and\n       libraries */\n    *arg++ = \"-D\";\n    *arg++ = \"_GNU_SOURCE\";\n    *arg++ = \"-I\";\n    *arg++ = inc_dir;\n    *arg++ = \"-o\";\n    *arg++ = out_filename;\n    if (dynamic_export)\n        *arg++ = \"-rdynamic\";\n    *arg++ = cfilename;\n    snprintf(libjsname, sizeof(libjsname), \"%s/libquickjs%s%s.a\",\n             lib_dir, bn_suffix, lto_suffix);\n    *arg++ = libjsname;\n    *arg++ = \"-lm\";\n    *arg++ = \"-ldl\";\n    *arg++ = \"-lpthread\";\n    *arg = NULL;\n    \n    if (verbose) {\n        for(arg = argv; *arg != NULL; arg++)\n            printf(\"%s \", *arg);\n        printf(\"\\n\");\n    }\n    \n    ret = exec_cmd((char **)argv);\n    unlink(cfilename);\n    return ret;\n}\n#else\nstatic int output_executable(const char *out_filename, const char *cfilename,\n                             BOOL use_lto, BOOL verbose, const char *exename)\n{\n    fprintf(stderr, \"Executable output is not supported for this target\\n\");\n    exit(1);\n    return 0;\n}\n#endif\n\n\ntypedef enum {\n    OUTPUT_C,\n    OUTPUT_C_MAIN,\n    OUTPUT_EXECUTABLE,\n} OutputTypeEnum;\n\nint main(int argc, char **argv)\n{\n    int c, i, verbose;\n    const char *out_filename, *cname;\n    char cfilename[1024];\n    FILE *fo;\n    JSRuntime *rt;\n    JSContext *ctx;\n    BOOL use_lto;\n    int module;\n    OutputTypeEnum output_type;\n    size_t stack_size;\n#ifdef CONFIG_BIGNUM\n    BOOL bignum_ext = FALSE;\n#endif\n    namelist_t dynamic_module_list;\n    \n    out_filename = NULL;\n    output_type = OUTPUT_EXECUTABLE;\n    cname = NULL;\n    feature_bitmap = FE_ALL;\n    module = -1;\n    byte_swap = FALSE;\n    verbose = 0;\n    use_lto = FALSE;\n    stack_size = 0;\n    memset(&dynamic_module_list, 0, sizeof(dynamic_module_list));\n    \n    /* add system modules */\n    namelist_add(&cmodule_list, \"std\", \"std\", 0);\n    namelist_add(&cmodule_list, \"os\", \"os\", 0);\n\n    for(;;) {\n        c = getopt(argc, argv, \"ho:cN:f:mxevM:p:S:D:\");\n        if (c == -1)\n            break;\n        switch(c) {\n        case 'h':\n            help();\n        case 'o':\n            out_filename = optarg;\n            break;\n        case 'c':\n            output_type = OUTPUT_C;\n            break;\n        case 'e':\n            output_type = OUTPUT_C_MAIN;\n            break;\n        case 'N':\n            cname = optarg;\n            break;\n        case 'f':\n            {\n                const char *p;\n                p = optarg;\n                if (!strcmp(optarg, \"lto\")) {\n                    use_lto = TRUE;\n                } else if (strstart(p, \"no-\", &p)) {\n                    use_lto = TRUE;\n                    for(i = 0; i < countof(feature_list); i++) {\n                        if (!strcmp(p, feature_list[i].option_name)) {\n                            feature_bitmap &= ~((uint64_t)1 << i);\n                            break;\n                        }\n                    }\n                    if (i == countof(feature_list))\n                        goto bad_feature;\n                } else\n#ifdef CONFIG_BIGNUM\n                if (!strcmp(optarg, \"bignum\")) {\n                    bignum_ext = TRUE;\n                } else\n#endif\n                {\n                bad_feature:\n                    fprintf(stderr, \"unsupported feature: %s\\n\", optarg);\n                    exit(1);\n                }\n            }\n            break;\n        case 'm':\n            module = 1;\n            break;\n        case 'M':\n            {\n                char *p;\n                char path[1024];\n                char cname[1024];\n                pstrcpy(path, sizeof(path), optarg);\n                p = strchr(path, ',');\n                if (p) {\n                    *p = '\\0';\n                    pstrcpy(cname, sizeof(cname), p + 1);\n                } else {\n                    get_c_name(cname, sizeof(cname), path);\n                }\n                namelist_add(&cmodule_list, path, cname, 0);\n            }\n            break;\n        case 'D':\n            namelist_add(&dynamic_module_list, optarg, NULL, 0);\n            break;\n        case 'x':\n            byte_swap = TRUE;\n            break;\n        case 'v':\n            verbose++;\n            break;\n        case 'p':\n            c_ident_prefix = optarg;\n            break;\n        case 'S':\n            stack_size = (size_t)strtod(optarg, NULL);\n            break;\n        default:\n            break;\n        }\n    }\n\n    if (optind >= argc)\n        help();\n\n    if (!out_filename) {\n        if (output_type == OUTPUT_EXECUTABLE) {\n            out_filename = \"a.out\";\n        } else {\n            out_filename = \"out.c\";\n        }\n    }\n\n    if (output_type == OUTPUT_EXECUTABLE) {\n#if defined(_WIN32) || defined(__ANDROID__)\n        /* XXX: find a /tmp directory ? */\n        snprintf(cfilename, sizeof(cfilename), \"out%d.c\", getpid());\n#else\n        snprintf(cfilename, sizeof(cfilename), \"/tmp/out%d.c\", getpid());\n#endif\n    } else {\n        pstrcpy(cfilename, sizeof(cfilename), out_filename);\n    }\n    \n    fo = fopen(cfilename, \"w\");\n    if (!fo) {\n        perror(cfilename);\n        exit(1);\n    }\n    outfile = fo;\n    \n    rt = JS_NewRuntime();\n    ctx = JS_NewContext(rt);\n#ifdef CONFIG_BIGNUM\n    if (bignum_ext) {\n        JS_AddIntrinsicBigFloat(ctx);\n        JS_AddIntrinsicBigDecimal(ctx);\n        JS_AddIntrinsicOperators(ctx);\n        JS_EnableBignumExt(ctx, TRUE);\n    }\n#endif\n    \n    /* loader for ES6 modules */\n    JS_SetModuleLoaderFunc(rt, NULL, jsc_module_loader, NULL);\n\n    fprintf(fo, \"/* File generated automatically by the QuickJS compiler. */\\n\"\n            \"\\n\"\n            );\n    \n    if (output_type != OUTPUT_C) {\n        fprintf(fo, \"#include \\\"quickjs-libc.h\\\"\\n\"\n                \"\\n\"\n                );\n    } else {\n        fprintf(fo, \"#include <inttypes.h>\\n\"\n                \"\\n\"\n                );\n    }\n\n    for(i = optind; i < argc; i++) {\n        const char *filename = argv[i];\n        compile_file(ctx, fo, filename, cname, module);\n        cname = NULL;\n    }\n\n    for(i = 0; i < dynamic_module_list.count; i++) {\n        if (!jsc_module_loader(ctx, dynamic_module_list.array[i].name, NULL)) {\n            fprintf(stderr, \"Could not load dynamic module '%s'\\n\",\n                    dynamic_module_list.array[i].name);\n            exit(1);\n        }\n    }\n    \n    if (output_type != OUTPUT_C) {\n        fprintf(fo,\n                \"static JSContext *JS_NewCustomContext(JSRuntime *rt)\\n\"\n                \"{\\n\"\n                \"  JSContext *ctx = JS_NewContextRaw(rt);\\n\"\n                \"  if (!ctx)\\n\"\n                \"    return NULL;\\n\");\n        /* add the basic objects */\n        fprintf(fo, \"  JS_AddIntrinsicBaseObjects(ctx);\\n\");\n        for(i = 0; i < countof(feature_list); i++) {\n            if ((feature_bitmap & ((uint64_t)1 << i)) &&\n                feature_list[i].init_name) {\n                fprintf(fo, \"  JS_AddIntrinsic%s(ctx);\\n\",\n                        feature_list[i].init_name);\n            }\n        }\n#ifdef CONFIG_BIGNUM\n        if (bignum_ext) {\n            fprintf(fo,\n                    \"  JS_AddIntrinsicBigFloat(ctx);\\n\"\n                    \"  JS_AddIntrinsicBigDecimal(ctx);\\n\"\n                    \"  JS_AddIntrinsicOperators(ctx);\\n\"\n                    \"  JS_EnableBignumExt(ctx, 1);\\n\");\n        }\n#endif\n        /* add the precompiled modules (XXX: could modify the module\n           loader instead) */\n        for(i = 0; i < init_module_list.count; i++) {\n            namelist_entry_t *e = &init_module_list.array[i];\n            /* initialize the static C modules */\n            \n            fprintf(fo,\n                    \"  {\\n\"\n                    \"    extern JSModuleDef *js_init_module_%s(JSContext *ctx, const char *name);\\n\"\n                    \"    js_init_module_%s(ctx, \\\"%s\\\");\\n\"\n                    \"  }\\n\",\n                    e->short_name, e->short_name, e->name);\n        }\n        for(i = 0; i < cname_list.count; i++) {\n            namelist_entry_t *e = &cname_list.array[i];\n            if (e->flags) {\n                fprintf(fo, \"  js_std_eval_binary(ctx, %s, %s_size, 1);\\n\",\n                        e->name, e->name);\n            }\n        }\n        fprintf(fo,\n                \"  return ctx;\\n\"\n                \"}\\n\\n\");\n        \n        fputs(main_c_template1, fo);\n\n        if (stack_size != 0) {\n            fprintf(fo, \"  JS_SetMaxStackSize(rt, %u);\\n\",\n                    (unsigned int)stack_size);\n        }\n        \n        /* add the module loader if necessary */\n        if (feature_bitmap & (1 << FE_MODULE_LOADER)) {\n            fprintf(fo, \"  JS_SetModuleLoaderFunc(rt, NULL, js_module_loader, NULL);\\n\");\n        }\n        \n        fprintf(fo,\n                \"  ctx = JS_NewCustomContext(rt);\\n\"\n                \"  js_std_add_helpers(ctx, argc, argv);\\n\");\n\n        for(i = 0; i < cname_list.count; i++) {\n            namelist_entry_t *e = &cname_list.array[i];\n            if (!e->flags) {\n                fprintf(fo, \"  js_std_eval_binary(ctx, %s, %s_size, 0);\\n\",\n                        e->name, e->name);\n            }\n        }\n        fputs(main_c_template2, fo);\n    }\n    \n    JS_FreeContext(ctx);\n    JS_FreeRuntime(rt);\n\n    fclose(fo);\n\n    if (output_type == OUTPUT_EXECUTABLE) {\n        return output_executable(out_filename, cfilename, use_lto, verbose,\n                                 argv[0]);\n    }\n    namelist_free(&cname_list);\n    namelist_free(&cmodule_list);\n    namelist_free(&init_module_list);\n    return 0;\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/qjscalc.js",
    "content": "/*\n * QuickJS Javascript Calculator\n * \n * Copyright (c) 2017-2020 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\"use strict\";\n\"use math\";\n\nvar Integer, Float, Fraction, Complex, Mod, Polynomial, PolyMod, RationalFunction, Series, Matrix;\n\n(function(global) {\n    global.Integer = global.BigInt;\n    global.Float = global.BigFloat;\n    global.algebraicMode = true;\n    \n    /* add non enumerable properties */\n    function add_props(obj, props) {\n        var i, val, prop, tab, desc;\n        tab = Reflect.ownKeys(props);\n        for(i = 0; i < tab.length; i++) {\n            prop = tab[i];\n            desc = Object.getOwnPropertyDescriptor(props, prop);\n            desc.enumerable = false;\n            if (\"value\" in desc) {\n                if (typeof desc.value !== \"function\") {\n                    desc.writable = false;\n                    desc.configurable = false;\n                }\n            } else {\n                /* getter/setter */\n                desc.configurable = false;\n            }\n            Object.defineProperty(obj, prop, desc);\n        }\n    }\n\n    /* same as proto[Symbol.operatorSet] = Operators.create(..op_list)\n       but allow shortcuts: left: [], right: [] or both\n    */\n    function operators_set(proto, ...op_list)\n    {\n        var new_op_list, i, a, j, b, k, obj, tab;\n        var fields = [ \"left\", \"right\" ];\n        new_op_list = [];\n        for(i = 0; i < op_list.length; i++) {\n            a = op_list[i];\n            if (a.left || a.right) {\n                tab = [ a.left, a.right ];\n                delete a.left;\n                delete a.right;\n                for(k = 0; k < 2; k++) {\n                    obj = tab[k];\n                    if (obj) {\n                        if (!Array.isArray(obj)) {\n                            obj = [ obj ];\n                        }\n                        for(j = 0; j < obj.length; j++) {\n                            b = {};\n                            Object.assign(b, a);\n                            b[fields[k]] = obj[j];\n                            new_op_list.push(b);\n                        }\n                    }\n                }\n            } else {\n                new_op_list.push(a);\n            }\n        }\n        proto[Symbol.operatorSet] =\n            Operators.create.call(null, ...new_op_list); \n    }\n    \n    /* Integer */\n\n    function generic_pow(a, b) {\n        var r, is_neg, i;\n        if (!Integer.isInteger(b)) {\n            return exp(log(a) * b);\n        }\n        if (Array.isArray(a) && !(a instanceof Polynomial ||\n                                  a instanceof Series)) {\n            r = idn(Matrix.check_square(a));\n        } else {\n            r = 1;\n        }\n        if (b == 0)\n            return r;\n        is_neg = false;\n        if (b < 0) {\n            is_neg = true;\n            b = -b;\n        }\n        r = a;\n        for(i = Integer.floorLog2(b) - 1; i >= 0; i--) {\n            r *= r;\n            if ((b >> i) & 1)\n                r *= a;\n        }\n        if (is_neg) {\n            if (typeof r.inverse != \"function\")\n                throw \"negative powers are not supported for this type\";\n            r = r.inverse();\n        }\n        return r;\n    }\n    \n    var small_primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499 ];\n\n    function miller_rabin_test(n, t) {\n        var d, r, s, i, j, a;\n        d = n - 1;\n        s = 0;\n        while ((d & 1) == 0) {\n            d >>= 1;\n            s++;\n        }\n        if (small_primes.length < t)\n            t = small_primes.length;\n        loop: for(j = 0; j < t; j++) {\n            a = small_primes[j];\n            r = Integer.pmod(a, d, n);\n            if (r == 1 || r == (n - 1))\n                continue;\n            for(i = 1; i < s; i++) {\n                r = (r * r) % n;\n                if (r == 1)\n                    return false;\n                if (r == (n - 1))\n                    continue loop;\n            }\n            return false; /* n is composite */\n        }\n        return true; /* n is probably prime with probability (1-0.5^t) */\n    }\n\n    function fact_rec(a, b) {  /* assumes a <= b */\n        var i, r;\n        if ((b - a) <= 5) {\n            r = a;\n            for(i = a + 1; i <= b; i++)\n                r *= i;\n            return r;\n        } else {\n            /* to avoid a quadratic running time it is better to\n               multiply numbers of similar size */\n            i = (a + b) >> 1;\n            return fact_rec(a, i) * fact_rec(i + 1, b);\n        }\n    }\n\n    /* math mode specific quirk to overload the integer division and power */\n    Operators.updateBigIntOperators(\n        {\n            \"/\"(a, b) {\n                if (algebraicMode) {\n                    return Fraction.toFraction(a, b);\n                } else {\n                    return Float(a) / Float(b);\n                }\n            },\n            \"**\"(a, b) {\n                if (algebraicMode) {\n                    return generic_pow(a, b);\n                } else {\n                    return Float(a) ** Float(b);\n                }\n            }\n        });\n            \n    add_props(Integer, {\n        isInteger(a) {\n            /* integers are represented either as bigint or as number */\n            return typeof a === \"bigint\" ||\n                (typeof a === \"number\" && Number.isSafeInteger(a));\n        },\n        gcd(a, b) {\n            var r;\n            while (b != 0) {\n                r = a % b;\n                a = b;\n                b = r;\n            }\n            return a;\n        },\n        fact(n) {\n            return n <= 0 ? 1 : fact_rec(1, n);\n        },\n        /* binomial coefficient */\n        comb(n, k) {\n            if (k < 0 || k > n)\n                return 0;\n            if (k > n - k)\n                k = n - k;\n            if (k == 0)\n                return 1;\n            return Integer.tdiv(fact_rec(n - k + 1, n), fact_rec(1, k));\n        },\n        /* inverse of x modulo y */\n        invmod(x, y) {\n            var q, u, v, a, c, t;\n            u = x;\n            v = y;\n            c = 1;\n            a = 0;\n            while (u != 0) {\n                t = Integer.fdivrem(v, u);\n                q = t[0];\n                v = u;\n                u = t[1];\n                t = c;\n                c = a - q * c;\n                a = t;\n            }\n            /* v = gcd(x, y) */\n            if (v != 1)\n                throw RangeError(\"not invertible\");\n            return a % y;\n        },\n        /* return a ^ b modulo m */\n        pmod(a, b, m) {\n            var r;\n            if (b == 0)\n                return 1;\n            if (b < 0) {\n                a = Integer.invmod(a, m);\n                b = -b;\n            }\n            r = 1;\n            for(;;) {\n                if (b & 1) {\n                    r = (r * a) % m;\n                }\n                b >>= 1;\n                if (b == 0)\n                    break;\n                a = (a * a) % m;\n            }\n            return r;\n        },\n\n        /* return true if n is prime (or probably prime with\n           probability 1-0.5^t) */\n        isPrime(n, t) {\n            var i, d, n1;\n            if (!Integer.isInteger(n))\n                throw TypeError(\"invalid type\");\n            if (n <= 1)\n                return false;\n            n1 = small_primes.length;\n            /* XXX: need Integer.sqrt() */\n            for(i = 0; i < n1; i++) {\n                d = small_primes[i];\n                if (d == n)\n                    return true;\n                if (d > n)\n                    return false;\n                if ((n % d) == 0)\n                    return false;\n            }\n            if (n < d * d)\n                return true;\n            if (typeof t == \"undefined\")\n                t = 64;\n            return miller_rabin_test(n, t);\n        },\n        nextPrime(n) {\n            if (!Integer.isInteger(n))\n                throw TypeError(\"invalid type\");\n            if (n < 1)\n                n = 1;\n            for(;;) {\n                n++;\n                if (Integer.isPrime(n))\n                    return n;\n            }\n        },\n        factor(n) {\n            var r, d;\n            if (!Integer.isInteger(n))\n                throw TypeError(\"invalid type\");\n            r = [];\n            if (abs(n) <= 1) {\n                r.push(n);\n                return r;\n            }\n            if (n < 0) {\n                r.push(-1);\n                n = -n;\n            }\n            \n            while ((n % 2) == 0) {\n                n >>= 1;\n                r.push(2);\n            }\n\n            d = 3;\n            while (n != 1) {\n                if (Integer.isPrime(n)) {\n                    r.push(n);\n                    break;\n                }\n                /* we are sure there is at least one divisor, so one test */\n                for(;;) {\n                    if ((n % d) == 0)\n                        break;\n                    d += 2;\n                }\n                for(;;) {\n                    r.push(d);\n                    n = Integer.tdiv(n, d);\n                    if ((n % d) != 0)\n                        break;\n                }\n            }\n            return r;\n        },\n    });\n\n    add_props(Integer.prototype, {\n        inverse() {\n            return 1 / this;\n        },\n        norm2() {\n            return this * this;\n        },\n        abs() {\n            var v = this;\n            if (v < 0)\n                v = -v;\n            return v;\n        },\n        conj() {\n            return this;\n        },\n        arg() {\n            if (this >= 0)\n                return 0;\n            else\n                return Float.PI;\n        },\n        exp() {\n            if (this == 0)\n                return 1;\n            else\n                return Float.exp(this);\n        },\n        log() {\n            if (this == 1)\n                return 0;\n            else\n                return Float(this).log();\n        },\n    });\n\n    /* Fraction */\n\n    Fraction = function Fraction(a, b)\n    {\n        var d, r, obj;\n\n        if (new.target)\n            throw TypeError(\"not a constructor\");\n        if (a instanceof Fraction)\n            return a;\n        if (!Integer.isInteger(a))\n            throw TypeError(\"integer expected\");\n        if (typeof b === \"undefined\") {\n            b = 1;\n        } else {\n            if (!Integer.isInteger(b))\n                throw TypeError(\"integer expected\");\n            if (b == 0)\n                throw RangeError(\"division by zero\");\n            d = Integer.gcd(a, b);\n            if (d != 1) {\n                a = Integer.tdiv(a, d);\n                b = Integer.tdiv(b, d);\n            }\n            \n            /* the fractions are normalized with den > 0 */\n            if (b < 0) {\n                a = -a;\n                b = -b;\n            }\n        }\n        obj = Object.create(Fraction.prototype);\n        obj.num = a;\n        obj.den = b;\n        return obj;\n    }\n\n    function fraction_add(a, b) {\n        a = Fraction(a);\n        b = Fraction(b);\n        return Fraction.toFraction(a.num * b.den + a.den * b.num, a.den * b.den);\n    }\n    function fraction_sub(a, b) {\n        a = Fraction(a);\n        b = Fraction(b);\n        return Fraction.toFraction(a.num * b.den - a.den * b.num, a.den * b.den);\n    }\n    function fraction_mul(a, b) {\n        a = Fraction(a);\n        b = Fraction(b);\n        return Fraction.toFraction(a.num * b.num, a.den * b.den);\n    }\n    function fraction_div(a, b) {\n        a = Fraction(a);\n        b = Fraction(b);\n        return Fraction.toFraction(a.num * b.den, a.den * b.num);\n    }\n    function fraction_mod(a, b) {\n        var a1 = Fraction(a);\n        var b1 = Fraction(b);\n        return a - Integer.ediv(a1.num * b1.den, a1.den * b1.num) * b;\n    }\n    function fraction_eq(a, b) {\n        a = Fraction(a);\n        b = Fraction(b);\n        /* we assume the fractions are normalized */\n        return (a.num == b.num && a.den == b.den);\n    }\n    function fraction_lt(a, b) {\n        a = Fraction(a);\n        b = Fraction(b);\n        return (a.num * b.den < b.num * a.den);\n    }\n\n    /* operators are needed for fractions */\n    function float_add(a, b) {\n        return Float(a) + Float(b);\n    }\n    function float_sub(a, b) {\n        return Float(a) - Float(b);\n    }\n    function float_mul(a, b) {\n        return Float(a) * Float(b);\n    }\n    function float_div(a, b) {\n        return Float(a) / Float(b);\n    }\n    function float_mod(a, b) {\n        return Float(a) % Float(b);\n    }\n    function float_pow(a, b) {\n        return Float(a) ** Float(b);\n    }\n    function float_eq(a, b) {\n        /* XXX: may be better to use infinite precision for the comparison */\n        return Float(a) === Float(b);\n    }\n    function float_lt(a, b) {\n        a = Float(a);\n        b = Float(b);\n        /* XXX: may be better to use infinite precision for the comparison */\n        if (Float.isNaN(a) || Float.isNaN(b))\n            return undefined;\n        else\n            return a < b;\n    }\n    \n    operators_set(Fraction.prototype,\n        {\n            \"+\": fraction_add,\n            \"-\": fraction_sub,\n            \"*\": fraction_mul,\n            \"/\": fraction_div,\n            \"%\": fraction_mod,\n            \"**\": generic_pow,\n            \"==\": fraction_eq,\n            \"<\": fraction_lt,\n            \"pos\"(a) {\n                return a;\n            },\n            \"neg\"(a) {\n                return Fraction(-a.num, a.den);\n            },\n        },\n        {\n            left: [Number, BigInt],\n            right: [Number, BigInt],\n            \"+\": fraction_add,\n            \"-\": fraction_sub,\n            \"*\": fraction_mul,\n            \"/\": fraction_div,\n            \"%\": fraction_mod,\n            \"**\": generic_pow,\n            \"==\": fraction_eq,\n            \"<\": fraction_lt,\n        },\n        {\n            left: Float,\n            right: Float,\n            \"+\": float_add,\n            \"-\": float_sub,\n            \"*\": float_mul,\n            \"/\": float_div,\n            \"%\": float_mod,\n            \"**\": float_pow,\n            \"==\": float_eq,\n            \"<\": float_lt,\n        });\n    \n    add_props(Fraction, {\n        /* (internal use) simplify 'a' to an integer when possible */\n        toFraction(a, b) {\n            var r = Fraction(a, b);\n            if (algebraicMode && r.den == 1)\n                return r.num;\n            else\n                return r;\n        },\n    });\n\n    add_props(Fraction.prototype, {\n        [Symbol.toPrimitive](hint) {\n            if (hint === \"string\") {\n                return this.toString();\n            } else {\n                return Float(this.num) / this.den;\n            }\n        },\n        inverse() {\n            return Fraction(this.den, this.num);\n        },\n        toString() {\n            return this.num + \"/\" + this.den;\n        },\n        norm2() {\n            return this * this;\n        },\n        abs() {\n            if (this.num < 0)\n                return -this;\n            else\n                return this;\n        },\n        conj() {\n            return this;\n        },\n        arg() {\n            if (this.num >= 0)\n                return 0;\n            else\n                return Float.PI;\n        },\n        exp() {\n            return Float.exp(Float(this));\n        },\n        log() {\n            return Float(this).log();\n        },\n    });\n\n    /* Number (Float64) */\n\n    add_props(Number.prototype, {\n        inverse() {\n            return 1 / this;\n        },\n        norm2() {\n            return this * this;\n        },\n        abs() {\n            return Math.abs(this);\n        },\n        conj() {\n            return this;\n        },\n        arg() {\n            if (this >= 0)\n                return 0;\n            else\n                return Float.PI;\n        },\n        exp() {\n            return Float.exp(this);\n        },\n        log() {\n            if (this < 0) {\n                return Complex(this).log();\n            } else {\n                return Float.log(this);\n            }\n        },\n    });\n    \n    /* Float */\n\n    var const_tab = [];\n    \n    /* we cache the constants for small precisions */\n    function get_const(n) {\n        var t, c, p;\n        t = const_tab[n];\n        p = BigFloatEnv.prec;\n        if (t && t.prec == p) {\n            return t.val;\n        } else {\n            switch(n) {\n            case 0: c = Float.exp(1); break;\n            case 1: c = Float.log(10); break;\n//            case 2: c = Float.log(2); break;\n            case 3: c = 1/Float.log(2); break;\n            case 4: c = 1/Float.log(10); break;\n//            case 5: c = Float.atan(1) * 4; break;\n            case 6: c = Float.sqrt(0.5); break;\n            case 7: c = Float.sqrt(2); break;\n            }\n            if (p <= 1024) {\n                const_tab[n] = { prec: p, val: c };\n            }\n            return c;\n        }\n    }\n    \n    add_props(Float, {\n        isFloat(a) {\n            return typeof a === \"number\" || typeof a === \"bigfloat\";\n        },\n        bestappr(u, b) {\n            var num1, num0, den1, den0, u, num, den, n;\n\n            if (typeof b === \"undefined\")\n                throw TypeError(\"second argument expected\");\n            num1 = 1;\n            num0 = 0;\n            den1 = 0;\n            den0 = 1;\n            for(;;) {\n                n = Integer(Float.floor(u));\n                num = n * num1 + num0;\n                den = n * den1 + den0;\n                if (den > b)\n                    break;\n                u = 1.0 / (u - n);\n                num0 = num1;\n                num1 = num;\n                den0 = den1;\n                den1 = den;\n            }\n            return Fraction(num1, den1);\n        },\n        /* similar constants as Math.x */\n        get E() { return get_const(0); },\n        get LN10() { return get_const(1); },\n//        get LN2() { return get_const(2); },\n        get LOG2E() { return get_const(3); },\n        get LOG10E() { return get_const(4); },\n//        get PI() { return get_const(5); },\n        get SQRT1_2() { return get_const(6); },\n        get SQRT2() { return get_const(7); },\n    });\n\n    add_props(Float.prototype, {\n        inverse() {\n            return 1.0 / this;\n        },\n        norm2() {\n            return this * this;\n        },\n        abs() {\n            return Float.abs(this);\n        },\n        conj() {\n            return this;\n        },\n        arg() {\n            if (this >= 0)\n                return 0;\n            else\n                return Float.PI;\n        },\n        exp() {\n            return Float.exp(this);\n        },\n        log() {\n            if (this < 0) {\n                return Complex(this).log();\n            } else {\n                return Float.log(this);\n            }\n        },\n    });\n       \n    /* Complex */\n    \n    Complex = function Complex(re, im)\n    {\n        var obj;\n        if (new.target)\n            throw TypeError(\"not a constructor\");\n        if (re instanceof Complex)\n            return re;\n        if (typeof im === \"undefined\") {\n            im = 0;\n        }\n        obj = Object.create(Complex.prototype);\n        obj.re = re;\n        obj.im = im;\n        return obj;\n    }\n\n        \n    function complex_add(a, b) {\n        a = Complex(a);\n        b = Complex(b);\n        return Complex.toComplex(a.re + b.re, a.im + b.im);\n    }\n    function complex_sub(a, b) {\n        a = Complex(a);\n        b = Complex(b);\n        return Complex.toComplex(a.re - b.re, a.im - b.im);\n    }\n    function complex_mul(a, b) {\n        a = Complex(a);\n        b = Complex(b);\n        return Complex.toComplex(a.re * b.re - a.im * b.im,\n                                 a.re * b.im + a.im * b.re);\n    }\n    function complex_div(a, b) {\n        a = Complex(a);\n        b = Complex(b);\n        return a * b.inverse();\n    }\n    function complex_eq(a, b) {\n        a = Complex(a);\n        b = Complex(b);\n        return a.re == b.re && a.im == b.im;\n    }\n    \n    operators_set(Complex.prototype,\n        {\n            \"+\": complex_add,\n            \"-\": complex_sub,\n            \"*\": complex_mul,\n            \"/\": complex_div,\n            \"**\": generic_pow,\n            \"==\": complex_eq,\n            \"pos\"(a) {\n                return a;\n            },\n            \"neg\"(a) {\n                return Complex(-a.re, -a.im);\n            }\n        },\n        {\n            left: [Number, BigInt, Float, Fraction],\n            right: [Number, BigInt, Float, Fraction],\n            \"+\": complex_add,\n            \"-\": complex_sub,\n            \"*\": complex_mul,\n            \"/\": complex_div,\n            \"**\": generic_pow,\n            \"==\": complex_eq,\n        });\n    \n    add_props(Complex, {\n        /* simplify to real number when possible */\n        toComplex(re, im) {\n            if (algebraicMode && im == 0)\n                return re;\n            else\n                return Complex(re, im);\n        },\n    });\n\n    add_props(Complex.prototype, {\n        inverse() {\n            var c = this.norm2();\n            return Complex(this.re / c, -this.im / c);\n        },\n        toString() {\n            var v, s = \"\", a = this;\n            if (a.re != 0)\n                s += a.re.toString();\n            if (a.im == 1) {\n                if (s != \"\")\n                    s += \"+\";\n                s += \"I\";\n            } else if (a.im == -1) {\n                s += \"-I\";\n            } else {\n                v = a.im.toString();\n                if (v[0] != \"-\" && s != \"\")\n                    s += \"+\";\n                s += v + \"*I\";\n            }\n            return s;\n        },\n        norm2() {\n            return this.re * this.re + this.im * this.im;\n        },\n        abs() {\n            return Float.sqrt(norm2(this));\n        },\n        conj() {\n            return Complex(this.re, -this.im);\n        },\n        arg() {\n            return Float.atan2(this.im, this.re);\n        },\n        exp() {\n            var arg = this.im, r = this.re.exp();\n            return Complex(r * cos(arg), r * sin(arg));\n        },\n        log() {\n            return Complex(abs(this).log(), atan2(this.im, this.re));\n        },\n    });\n\n    /* Mod */\n\n    Mod = function Mod(a, m) {\n        var obj, t;\n        if (new.target)\n            throw TypeError(\"not a constructor\");\n        obj = Object.create(Mod.prototype);\n        if (Integer.isInteger(m)) {\n            if (m <= 0)\n                throw RangeError(\"the modulo cannot be <= 0\");\n            if (Integer.isInteger(a)) {\n                a %= m;\n            } else if (a instanceof Fraction) {\n                return Mod(a.num, m) / a.den;\n            } else {\n                throw TypeError(\"invalid types\");\n            }\n        } else {\n            throw TypeError(\"invalid types\");\n        }\n        obj.res = a;\n        obj.mod = m;\n        return obj;\n    };\n    \n    function mod_add(a, b) {\n        if (!(a instanceof Mod)) {\n            return Mod(a + b.res, b.mod);\n        } else if (!(b instanceof Mod)) {\n            return Mod(a.res + b, a.mod);\n        } else {\n            if (a.mod != b.mod)\n                throw TypeError(\"different modulo for binary operator\");\n            return Mod(a.res + b.res, a.mod);\n        }\n    }\n    function mod_sub(a, b) {\n        if (!(a instanceof Mod)) {\n            return Mod(a - b.res, b.mod);\n        } else if (!(b instanceof Mod)) {\n            return Mod(a.res - b, a.mod);\n        } else {\n            if (a.mod != b.mod)\n                throw TypeError(\"different modulo for binary operator\");\n            return Mod(a.res - b.res, a.mod);\n        }\n    }\n    function mod_mul(a, b) {\n        if (!(a instanceof Mod)) {\n            return Mod(a * b.res, b.mod);\n        } else if (!(b instanceof Mod)) {\n            return Mod(a.res * b, a.mod);\n        } else {\n            if (a.mod != b.mod)\n                throw TypeError(\"different modulo for binary operator\");\n            return Mod(a.res * b.res, a.mod);\n        }\n    }\n    function mod_div(a, b) {\n        if (!(b instanceof Mod))\n            b = Mod(b, a.mod);\n        return mod_mul(a, b.inverse());\n    }\n    function mod_eq(a, b) {\n        return (a.mod == b.mod && a.res == b.res);\n    }\n\n    operators_set(Mod.prototype,\n        {\n            \"+\": mod_add,\n            \"-\": mod_sub,\n            \"*\": mod_mul,\n            \"/\": mod_div,\n            \"**\": generic_pow,\n            \"==\": mod_eq,\n            \"pos\"(a) {\n                return a;\n            },\n            \"neg\"(a) {\n                return Mod(-a.res, a.mod);\n            }\n        },\n        {\n            left: [Number, BigInt, Float, Fraction],\n            right: [Number, BigInt, Float, Fraction],\n            \"+\": mod_add,\n            \"-\": mod_sub,\n            \"*\": mod_mul,\n            \"/\": mod_div,\n            \"**\": generic_pow,\n        });\n\n    add_props(Mod.prototype, {\n        inverse() {\n            var a = this, m = a.mod;\n            if (Integer.isInteger(m)) {\n                return Mod(Integer.invmod(a.res, m), m);\n            } else {\n                throw TypeError(\"unsupported type\");\n            }\n        },\n        toString() {\n            return \"Mod(\" + this.res + \",\" + this.mod + \")\";\n        },\n    });\n\n    /* Polynomial */\n\n    function polynomial_is_scalar(a)\n    {\n        if (typeof a === \"number\" ||\n            typeof a === \"bigint\" ||\n            typeof a === \"bigfloat\")\n            return true;\n        if (a instanceof Fraction ||\n            a instanceof Complex ||\n            a instanceof Mod)\n            return true;\n        return false;\n    }\n    \n    Polynomial = function Polynomial(a)\n    {\n        if (new.target)\n            throw TypeError(\"not a constructor\");\n        if (a instanceof Polynomial) {\n            return a;\n        } else if (Array.isArray(a)) {\n            if (a.length == 0)\n                a = [ 0 ];\n            Object.setPrototypeOf(a, Polynomial.prototype);\n            return a.trim();\n        } else if (polynomial_is_scalar(a)) {\n            a = [a];\n            Object.setPrototypeOf(a, Polynomial.prototype);\n            return a;\n        } else {\n            throw TypeError(\"invalid type\");\n        }\n    }\n\n    function number_need_paren(c)\n    {\n        return !(Integer.isInteger(c) ||\n                 Float.isFloat(c) ||\n                 c instanceof Fraction ||\n                 (c instanceof Complex && c.re == 0));\n    }\n\n    /* string for c*X^i */\n    function monomial_toString(c, i)\n    {\n        var str1;\n        if (i == 0) {\n            str1 = c.toString();\n        } else {\n            if (c == 1) {\n                str1 = \"\";\n            } else if (c == -1) {\n                str1 = \"-\";\n            } else {\n                if (number_need_paren(c)) {\n                    str1 = \"(\" + c + \")\";\n                } else {\n                    str1 = String(c);\n                }\n                str1 += \"*\";\n            }\n            str1 += \"X\";\n            if (i != 1) {\n                str1 += \"^\" + i;\n            }\n        }\n        return str1;\n    }\n\n    /* find one complex root of 'p' starting from z at precision eps using\n       at most max_it iterations. Return null if could not find root. */\n    function poly_root_laguerre1(p, z, max_it)\n    {\n        var p1, p2, i, z0, z1, z2, d, t0, t1, d1, d2, e, el, zl;\n\n        d = p.deg();\n        if (d == 1) {\n            /* monomial case */\n            return -p[0] / p[1];\n        }\n        /* trivial zero */\n        if (p[0] == 0)\n            return 0.0;\n        \n        p1 = p.deriv();\n        p2 = p1.deriv();\n        el = 0.0;\n        zl = 0.0;\n        for(i = 0; i < max_it; i++) {\n            z0 = p.apply(z);\n            if (z0 == 0)\n                return z; /* simple exit case */\n\n            /* Ward stopping criteria */\n            e = abs(z - zl);\n//            print(\"e\", i, e);\n            if (i >= 2 && e >= el) {\n                if (abs(zl) < 1e-4) {\n                    if (e < 1e-7)\n                        return zl;\n                } else {\n                    if (e < abs(zl) * 1e-3)\n                        return zl;\n                }\n            }\n            el = e;\n            zl = z;\n            \n            z1 = p1.apply(z);\n            z2 = p2.apply(z);\n            t0 = (d - 1) * z1;\n            t0 = t0 * t0;\n            t1 = d * (d - 1) * z0 * z2;\n            t0 = sqrt(t0 - t1);\n            d1 = z1 + t0;\n            d2 = z1 - t0;\n            if (norm2(d2) > norm2(d1))\n                d1 = d2;\n            if (d1 == 0) \n                return null;\n            z = z - d * z0 / d1;\n        }\n        return null;\n    }\n\n    function poly_roots(p)\n    {\n        var d, i, roots, j, z, eps;\n        var start_points = [ 0.1, -1.4, 1.7 ];\n\n        if (!(p instanceof Polynomial))\n            throw TypeError(\"polynomial expected\");\n        d = p.deg();\n        if (d <= 0)\n            return [];\n        eps = 2.0 ^ (-BigFloatEnv.prec);\n        roots = [];\n        for(i = 0; i < d; i++) {\n            /* XXX: should select another start point if error */\n            for(j = 0; j < 3; j++) {\n                z = poly_root_laguerre1(p, start_points[j], 100);\n                if (z !== null)\n                    break;\n            }\n            if (j == 3)\n                throw RangeError(\"error in root finding algorithm\");\n            roots[i] = z;\n            p = Polynomial.divrem(p, X - z)[0];\n        }\n        return roots;\n    }\n\n    add_props(Polynomial.prototype, {\n        trim() {\n            var a = this, i;\n            i = a.length;\n            while (i > 1 && a[i - 1] == 0)\n                i--;\n            a.length = i;\n            return a;\n        },\n        conj() {\n            var r, i, n, a;\n            a = this;\n            n = a.length;\n            r = [];\n            for(i = 0; i < n; i++)\n                r[i] = a[i].conj();\n            return Polynomial(r);\n        },\n        inverse() {\n            return RationalFunction(Polynomial([1]), this);\n        },\n        toString() {\n            var i, str, str1, c, a = this;\n            if (a.length == 1) {\n                return a[0].toString();\n            }\n            str=\"\";\n            for(i = a.length - 1; i >= 0; i--) {\n                c = a[i];\n                if (c == 0 ||\n                    (c instanceof Mod) && c.res == 0)\n                    continue;\n                str1 = monomial_toString(c, i);\n                if (str1[0] != \"-\") {\n                    if (str != \"\")\n                        str += \"+\";\n                }\n                str += str1;\n            }\n            return str;\n        },\n        deg() {\n            if (this.length == 1 && this[0] == 0)\n                return -Infinity;\n            else\n                return this.length - 1;\n        },\n        apply(b) {\n            var i, n, r, a = this;\n            n = a.length - 1;\n            r = a[n];\n            while (n > 0) {\n                n--;\n                r = r * b + a[n];\n            }\n            return r;\n        },\n        deriv() {\n            var a = this, n, r, i;\n            n = a.length;\n            if (n == 1) {\n                return Polynomial(0);\n            } else {\n                r = [];\n                for(i = 1; i < n; i++) {\n                    r[i - 1] = i * a[i];\n                }\n                return Polynomial(r);\n            }\n        },\n        integ() {\n            var a = this, n, r, i;\n            n = a.length;\n            r = [0];\n            for(i = 0; i < n; i++) {\n                r[i + 1] = a[i] / (i + 1);\n            }\n            return Polynomial(r);\n        },\n        norm2() {\n            var a = this, n, r, i;\n            n = a.length;\n            r = 0;\n            for(i = 0; i < n; i++) {\n                r += a[i].norm2();\n            }\n            return r;\n        },\n    });\n\n\n    function polynomial_add(a, b) {\n        var tmp, r, i, n1, n2;\n        a = Polynomial(a);\n        b = Polynomial(b);\n        if (a.length < b.length) {\n            tmp = a;\n            a = b;\n            b = tmp;\n        }\n        n1 = b.length;\n        n2 = a.length;\n        r = [];\n        for(i = 0; i < n1; i++)\n            r[i] = a[i] + b[i];\n        for(i = n1; i < n2; i++)\n            r[i] = a[i];\n        return Polynomial(r);\n    }\n    function polynomial_sub(a, b) {\n        return polynomial_add(a, -b);\n    }\n    function polynomial_mul(a, b) {\n        var i, j, n1, n2, n, r;\n        a = Polynomial(a);\n        b = Polynomial(b);\n        n1 = a.length;\n        n2 = b.length;\n        n = n1 + n2 - 1;\n        r = [];\n        for(i = 0; i < n; i++)\n            r[i] = 0;\n        for(i = 0; i < n1; i++) {\n            for(j = 0; j < n2; j++) {\n                r[i + j] += a[i] * b[j];\n            }\n        }\n        return Polynomial(r);\n    }\n    function polynomial_div_scalar(a, b) {\n        return a * (1 / b);\n    }\n    function polynomial_div(a, b)\n    {\n        return RationalFunction(Polynomial(a),\n                                Polynomial(b));\n    }\n    function polynomial_mod(a, b) {\n        return Polynomial.divrem(a, b)[1];\n    }\n    function polynomial_eq(a, b) {\n        var n, i;\n        n = a.length;\n        if (n != b.length)\n            return false;\n        for(i = 0; i < n; i++) {\n            if (a[i] != b[i])\n                return false;\n        }\n        return true;\n    }\n\n    operators_set(Polynomial.prototype,\n        {\n            \"+\": polynomial_add,\n            \"-\": polynomial_sub,\n            \"*\": polynomial_mul,\n            \"/\": polynomial_div,\n            \"**\": generic_pow,\n            \"==\": polynomial_eq,\n            \"pos\"(a) {\n                return a;\n            },\n            \"neg\"(a) {\n                var r, i, n, a;\n                n = a.length;\n                r = [];\n                for(i = 0; i < n; i++)\n                r[i] = -a[i];\n                return Polynomial(r);\n            },\n        },\n        {\n            left: [Number, BigInt, Float, Fraction, Complex, Mod],\n            \"+\": polynomial_add,\n            \"-\": polynomial_sub,\n            \"*\": polynomial_mul,\n            \"/\": polynomial_div,\n            \"**\": generic_pow, /* XXX: only for integer */\n        },\n        {\n            right: [Number, BigInt, Float, Fraction, Complex, Mod],\n            \"+\": polynomial_add,\n            \"-\": polynomial_sub,\n            \"*\": polynomial_mul,\n            \"/\": polynomial_div_scalar,\n            \"**\": generic_pow, /* XXX: only for integer */\n        });\n    \n    add_props(Polynomial, {\n        divrem(a, b) {\n            var n1, n2, i, j, q, r, n, c;\n            if (b.deg() < 0)\n                throw RangeError(\"division by zero\");\n            n1 = a.length;\n            n2 = b.length;\n            if (n1 < n2)\n                return [Polynomial([0]), a];\n            r = Array.prototype.dup.call(a);\n            q = [];\n            n2--;\n            n = n1 - n2;\n            for(i = 0; i < n; i++)\n                q[i] = 0;\n            for(i = n - 1; i >= 0; i--) {\n                c = r[i + n2];\n                if (c != 0) {\n                    c = c / b[n2];\n                    r[i + n2] = 0;\n                    for(j = 0; j < n2; j++) {\n                        r[i + j] -= b[j] * c;\n                    }\n                    q[i] = c;\n                }\n            }\n            return [Polynomial(q), Polynomial(r)];\n        },\n        gcd(a, b) {\n            var t;\n            while (b.deg() >= 0) {\n                t = Polynomial.divrem(a, b);\n                a = b;\n                b = t[1];\n            }\n            /* convert to monic form */\n            return a / a[a.length - 1];\n        },\n        invmod(x, y) {\n            var q, u, v, a, c, t;\n            u = x;\n            v = y;\n            c = Polynomial([1]);\n            a = Polynomial([0]);\n            while (u.deg() >= 0) {\n                t = Polynomial.divrem(v, u);\n                q = t[0];\n                v = u;\n                u = t[1];\n                t = c;\n                c = a - q * c;\n                a = t;\n            }\n            /* v = gcd(x, y) */\n            if (v.deg() > 0)\n                throw RangeError(\"not invertible\");\n            return Polynomial.divrem(a, y)[1];\n        },\n        roots(p) {\n            return poly_roots(p);\n        }\n    });\n\n    /* Polynomial Modulo Q */\n\n    PolyMod = function PolyMod(a, m) {\n        var obj, t;\n        if (new.target)\n            throw TypeError(\"not a constructor\");\n        obj = Object.create(PolyMod.prototype);\n        if (m instanceof Polynomial) {\n            if (m.deg() <= 0)\n                throw RangeError(\"the modulo cannot have a degree <= 0\");\n            if (a instanceof RationalFunction) {\n                return PolyMod(a.num, m) / a.den;\n            } else {\n                a = Polynomial(a);\n                t = Polynomial.divrem(a, m);\n                a = t[1];\n            }\n        } else {\n            throw TypeError(\"invalid types\");\n        }\n        obj.res = a;\n        obj.mod = m;\n        return obj;\n    };\n\n    function polymod_add(a, b) {\n        if (!(a instanceof PolyMod)) {\n            return PolyMod(a + b.res, b.mod);\n        } else if (!(b instanceof PolyMod)) {\n            return PolyMod(a.res + b, a.mod);\n        } else {\n            if (a.mod != b.mod)\n                throw TypeError(\"different modulo for binary operator\");\n            return PolyMod(a.res + b.res, a.mod);\n        }\n    }\n    function polymod_sub(a, b) {\n        return polymod_add(a, -b);\n    }\n    function polymod_mul(a, b) {\n        if (!(a instanceof PolyMod)) {\n            return PolyMod(a * b.res, b.mod);\n        } else if (!(b instanceof PolyMod)) {\n            return PolyMod(a.res * b, a.mod);\n        } else {\n            if (a.mod != b.mod)\n                    throw TypeError(\"different modulo for binary operator\");\n            return PolyMod(a.res * b.res, a.mod);\n        }\n    }\n    function polymod_div(a, b) {\n        if (!(b instanceof PolyMod))\n            b = PolyMod(b, a.mod);\n        return polymod_mul(a, b.inverse());\n    }\n    function polymod_eq(a, b) {\n        return (a.mod == b.mod && a.res == b.res);\n    }\n\n    operators_set(PolyMod.prototype,\n        {\n            \"+\": polymod_add,\n            \"-\": polymod_sub,\n            \"*\": polymod_mul,\n            \"/\": polymod_div,\n            \"**\": generic_pow,\n            \"==\": polymod_eq,\n            \"pos\"(a) {\n                return a;\n            },\n            \"neg\"(a) {\n                return PolyMod(-a.res, a.mod);\n            },\n        },\n        {\n            left: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial],\n            right: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial],\n            \"+\": polymod_add,\n            \"-\": polymod_sub,\n            \"*\": polymod_mul,\n            \"/\": polymod_div,\n            \"**\": generic_pow, /* XXX: only for integer */\n        });\n\n    add_props(PolyMod.prototype, {\n        inverse() {\n            var a = this, m = a.mod;\n            if (m instanceof Polynomial) {\n                return PolyMod(Polynomial.invmod(a.res, m), m);\n            } else {\n                throw TypeError(\"unsupported type\");\n            }\n        },\n        toString() {\n            return \"PolyMod(\" + this.res + \",\" + this.mod + \")\";\n        },\n    });\n\n    /* Rational function */\n    \n    RationalFunction = function RationalFunction(a, b)\n    {\n        var t, r, d, obj;\n        if (new.target)\n            throw TypeError(\"not a constructor\");\n        if (!(a instanceof Polynomial) ||\n            !(b instanceof Polynomial))\n            throw TypeError(\"polynomial expected\");\n        t = Polynomial.divrem(a, b);\n        r = t[1];\n        if (r.deg() < 0)\n            return t[0]; /* no need for a fraction */\n        d = Polynomial.gcd(b, r);\n        if (d.deg() > 0) {\n            a = Polynomial.divrem(a, d)[0];\n            b = Polynomial.divrem(b, d)[0];\n        }\n        obj = Object.create(RationalFunction.prototype);\n        obj.num = a;\n        obj.den = b;\n        return obj;\n    }\n\n    add_props(RationalFunction.prototype, {\n        inverse() {\n            return RationalFunction(this.den, this.num);\n        },\n        conj() {\n            return RationalFunction(this.num.conj(), this.den.conj());\n        },\n        toString() {\n            var str;\n            if (this.num.deg() <= 0 &&\n                !number_need_paren(this.num[0]))\n                str = this.num.toString();\n            else\n                str = \"(\" + this.num.toString() + \")\";\n            str += \"/(\" + this.den.toString() + \")\"\n            return str;\n        },\n        apply(b) {\n            return this.num.apply(b) / this.den.apply(b);\n        },\n        deriv() {\n            var n = this.num, d = this.den;\n            return RationalFunction(n.deriv() * d - n * d.deriv(), d * d);\n        },\n    });\n\n    function ratfunc_add(a, b) {\n        a = RationalFunction.toRationalFunction(a);\n        b = RationalFunction.toRationalFunction(b);\n        return RationalFunction(a.num * b.den + a.den * b.num, a.den * b.den);\n    }\n    function ratfunc_sub(a, b) {\n        a = RationalFunction.toRationalFunction(a);\n        b = RationalFunction.toRationalFunction(b);\n        return RationalFunction(a.num * b.den - a.den * b.num, a.den * b.den);\n    }\n    function ratfunc_mul(a, b) {\n        a = RationalFunction.toRationalFunction(a);\n        b = RationalFunction.toRationalFunction(b);\n        return RationalFunction(a.num * b.num, a.den * b.den);\n    }\n    function ratfunc_div(a, b) {\n        a = RationalFunction.toRationalFunction(a);\n        b = RationalFunction.toRationalFunction(b);\n        return RationalFunction(a.num * b.den, a.den * b.num);\n    }\n    function ratfunc_eq(a, b) {\n        a = RationalFunction.toRationalFunction(a);\n        b = RationalFunction.toRationalFunction(b);\n        /* we assume the fractions are normalized */\n        return (a.num == b.num && a.den == b.den);\n    }\n\n    operators_set(RationalFunction.prototype,\n        {\n            \"+\": ratfunc_add,\n            \"-\": ratfunc_sub,\n            \"*\": ratfunc_mul,\n            \"/\": ratfunc_div,\n            \"**\": generic_pow,\n            \"==\": ratfunc_eq,\n            \"pos\"(a) {\n                return a;\n            },\n            \"neg\"(a) {\n                return RationalFunction(-this.num, this.den);\n            },\n        },\n        {\n            left: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial],\n            right: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial],\n            \"+\": ratfunc_add,\n            \"-\": ratfunc_sub,\n            \"*\": ratfunc_mul,\n            \"/\": ratfunc_div,\n            \"**\": generic_pow, /* should only be used with integers */\n        });\n    \n    add_props(RationalFunction, {\n        /* This function always return a RationalFunction object even\n           if it could simplified to a polynomial, so it is not\n           equivalent to RationalFunction(a) */\n        toRationalFunction(a) {\n            var obj;\n            if (a instanceof RationalFunction) {\n                return a;\n            } else {\n                obj = Object.create(RationalFunction.prototype);\n                obj.num = Polynomial(a);\n                obj.den = Polynomial(1);\n                return obj;\n            }\n        },\n    });\n              \n    /* Power series */\n\n    /* 'a' is an array */\n    function get_emin(a) {\n        var i, n;\n        n = a.length;\n        for(i = 0; i < n; i++) {\n            if (a[i] != 0)\n                return i;\n        }\n        return n;\n    };\n\n    function series_is_scalar_or_polynomial(a)\n    {\n        return polynomial_is_scalar(a) ||\n            (a instanceof Polynomial);\n    }\n    \n    /* n is the maximum number of terms if 'a' is not a serie */\n    Series = function Series(a, n) {\n        var emin, r, i;\n        \n        if (a instanceof Series) {\n            return a;\n        } else if (series_is_scalar_or_polynomial(a)) {\n            if (n <= 0) {\n                /* XXX: should still use the polynomial degree */\n                return Series.zero(0, 0);\n            } else {\n                a = Polynomial(a);\n                emin = get_emin(a);\n                r = Series.zero(n, emin);\n                n = Math.min(a.length - emin, n);\n                for(i = 0; i < n; i++)\n                    r[i] = a[i + emin];\n                return r;\n            }\n        } else if (a instanceof RationalFunction) {\n            return Series(a.num, n) / a.den;\n        } else {\n            throw TypeError(\"invalid type\");\n        }\n    };\n\n    function series_add(v1, v2) {\n        var tmp, d, emin, n, r, i, j, v2_emin, c1, c2;\n        if (!(v1 instanceof Series)) {\n            tmp = v1;\n            v1 = v2;\n            v2 = tmp;\n        }\n        d = v1.emin + v1.length;\n        if (series_is_scalar_or_polynomial(v2)) {\n            v2 = Polynomial(v2);\n            if (d <= 0)\n                return v1;\n            v2_emin = 0;\n        } else if (v2 instanceof RationalFunction) {\n            /* compute the emin of the rational fonction */\n            i = get_emin(v2.num) - get_emin(v2.den);\n            if (d <= i)\n                return v1;\n            /* compute the serie with the required terms */\n            v2 = Series(v2, d - i);\n            v2_emin = v2.emin;\n        } else {\n            v2_emin = v2.emin;\n            d = Math.min(d, v2_emin + v2.length);\n        }\n        emin = Math.min(v1.emin, v2_emin);\n        n = d - emin;\n        r = Series.zero(n, emin);\n        /* XXX: slow */\n        for(i = emin; i < d; i++) {\n            j = i - v1.emin;\n            if (j >= 0 && j < v1.length)\n                c1 = v1[j];\n            else\n                c1 = 0;\n            j = i - v2_emin;\n            if (j >= 0 && j < v2.length)\n                c2 = v2[j];\n            else\n                c2 = 0;\n            r[i - emin] = c1 + c2;\n        }\n        return r.trim();\n    }\n    function series_sub(a, b) {\n        return series_add(a, -b);\n    }\n    function series_mul(v1, v2) {\n        var n, i, j, r, n, emin, n1, n2, k;\n        if (!(v1 instanceof Series))\n            v1 = Series(v1, v2.length);\n        else if (!(v2 instanceof Series))\n            v2 = Series(v2, v1.length);\n        emin = v1.emin + v2.emin;\n        n = Math.min(v1.length, v2.length);\n        n1 = v1.length;\n        n2 = v2.length;\n        r = Series.zero(n, emin);\n        for(i = 0; i < n1; i++) {\n            k = Math.min(n2, n - i);\n            for(j = 0; j < k; j++) {\n                r[i + j] += v1[i] * v2[j];\n            }\n        }\n        return r.trim();\n    }\n    function series_div(v1, v2) {\n        if (!(v2 instanceof Series))\n            v2 = Series(v2, v1.length);\n        return series_mul(v1, v2.inverse());\n    }\n    function series_pow(a, b) {\n        if (Integer.isInteger(b)) {\n            return generic_pow(a, b);\n        } else {\n            if (!(a instanceof Series))\n                a = Series(a, b.length);\n            return exp(log(a) * b);\n        }\n    }\n    function series_eq(a, b) {\n        var n, i;\n        if (a.emin != b.emin)\n            return false;\n        n = a.length;\n        if (n != b.length)\n            return false;\n        for(i = 0; i < n; i++) {\n            if (a[i] != b[i])\n                return false;\n        }\n        return true;\n    }\n\n    operators_set(Series.prototype,\n        {\n            \"+\": series_add,\n            \"-\": series_sub,\n            \"*\": series_mul,\n            \"/\": series_div,\n            \"**\": series_pow,\n            \"==\": series_eq,\n            \"pos\"(a) {\n                return a;\n            },\n            \"neg\"(a) {\n                var obj, n, i;\n                n = a.length;\n                obj = Series.zero(a.length, a.emin);\n                for(i = 0; i < n; i++) {\n                    obj[i] = -a[i];\n                }\n                return obj;\n            },\n        },\n        {\n            left: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial],\n            right: [Number, BigInt, Float, Fraction, Complex, Mod, Polynomial],\n            \"+\": series_add,\n            \"-\": series_sub,\n            \"*\": series_mul,\n            \"/\": series_div,\n            \"**\": series_pow,\n        });\n\n    add_props(Series.prototype, {\n        conj() {\n            var obj, n, i;\n            n = this.length;\n            obj = Series.zero(this.length, this.emin);\n            for(i = 0; i < n; i++) {\n                obj[i] = this[i].conj();\n            }\n            return obj;\n        },\n        inverse() {\n            var r, n, i, j, sum, v1 = this;\n            n = v1.length;\n            if (n == 0)\n                throw RangeError(\"division by zero\");\n            r = Series.zero(n, -v1.emin);\n            r[0] = 1 / v1[0];\n            for(i = 1; i < n; i++) {\n                sum = 0;\n                for(j = 1; j <= i; j++) {\n                    sum += v1[j] * r[i - j];\n                }\n                r[i] = -sum * r[0];\n            }\n            return r;\n        },\n        /* remove leading zero terms */\n        trim() {\n            var i, j, n, r, v1 = this;\n            n = v1.length;\n            i = 0;\n            while (i < n && v1[i] == 0)\n                i++;\n            if (i == 0)\n                return v1;\n            for(j = i; j < n; j++)\n                v1[j - i] = v1[j];\n            v1.length = n - i;\n            v1.__proto__.emin += i;\n            return v1;\n        },\n        toString() {\n            var i, j, str, str1, c, a = this, emin, n;\n            str=\"\";\n            emin = this.emin;\n            n = this.length;\n            for(j = 0; j < n; j++) {\n                i = j + emin;\n                c = a[j];\n                if (c != 0) {\n                    str1 = monomial_toString(c, i);\n                    if (str1[0] != \"-\") {\n                        if (str != \"\")\n                            str += \"+\";\n                    }\n                    str += str1;\n                }\n            }\n            if (str != \"\")\n                str += \"+\";\n            str += \"O(\" + monomial_toString(1, n + emin) + \")\";\n            return str;\n        },\n        apply(b) {\n            var i, n, r, a = this;\n            n = a.length;\n            if (n == 0)\n                return 0;\n            r = a[--n];\n            while (n > 0) {\n                n--;\n                r = r * b + a[n];\n            }\n            if (a.emin != 0)\n                r *= b ^ a.emin;\n            return r;\n        },\n        deriv() {\n            var a = this, n = a.length, emin = a.emin, r, i, j;\n            if (n == 0 && emin == 0) {\n                return Series.zero(0, 0);\n            } else {\n                r = Series.zero(n, emin - 1);\n                for(i = 0; i < n; i++) {\n                    j = emin + i;\n                    if (j == 0)\n                        r[i] = 0;\n                    else\n                        r[i] = j * a[i];\n                }\n                return r.trim();\n            }\n        },\n        integ() {\n            var a = this, n = a.length, emin = a.emin, i, j, r;\n            r = Series.zero(n, emin + 1);\n            for(i = 0; i < n; i++) {\n                j = emin + i;\n                if (j == -1) {\n                    if (a[i] != 0)\n                        throw RangeError(\"cannot represent integ(1/X)\");\n                } else {\n                    r[i] = a[i] / (j + 1);\n                }\n            }\n            return r.trim();\n        },\n        exp() {\n            var c, i, r, n, a = this;\n            if (a.emin < 0)\n                throw RangeError(\"negative exponent in exp\");\n            n = a.emin + a.length;\n            if (a.emin > 0 || a[0] == 0) {\n                c = 1;\n            } else {\n                c = global.exp(a[0]);\n                a -= a[0];\n            }\n            r = Series.zero(n, 0);\n            for(i = 0; i < n; i++) {\n                r[i] = c / fact(i);\n            }\n            return r.apply(a);\n        },\n        log() {\n            var a = this, r;\n            if (a.emin != 0)\n                throw RangeError(\"log argument must have a non zero constant term\");\n            r = integ(deriv(a) / a);\n            /* add the constant term */\n            r += global.log(a[0]);\n            return r;\n        },\n    });\n\n    add_props(Series, {\n        /* new series of length n and first exponent emin */\n        zero(n, emin) {\n            var r, i, obj;\n\n            r = [];\n            for(i = 0; i < n; i++)\n                r[i] = 0;\n            /* we return an array and store emin in its prototype */\n            obj = Object.create(Series.prototype);\n            obj.emin = emin;\n            Object.setPrototypeOf(r, obj);\n            return r;\n        },\n        O(a) {\n            function ErrorO() {\n                return TypeError(\"invalid O() argument\");\n            }\n            var n;\n            if (series_is_scalar_or_polynomial(a)) {\n                a = Polynomial(a);\n                n = a.deg();\n                if (n < 0)\n                    throw ErrorO();\n            } else if (a instanceof RationalFunction) {\n                if (a.num.deg() != 0)\n                    throw ErrorO();\n                n = a.den.deg();\n                if (n < 0)\n                    throw ErrorO();\n                n = -n;\n            } else\n                throw ErrorO();\n            return Series.zero(0, n);\n        },\n    });\n    \n    /* Array (Matrix) */\n\n    Matrix = function Matrix(h, w) {\n        var i, j, r, rl;\n        if (typeof w === \"undefined\")\n            w = h;\n        r = [];\n        for(i = 0; i < h; i++) {\n            rl = [];\n            for(j = 0; j < w; j++)\n                rl[j] = 0;\n            r[i] = rl;\n        }\n        return r;\n    };\n\n    add_props(Matrix, {\n        idn(n) {\n            var r, i;\n            r = Matrix(n, n);\n            for(i = 0; i < n; i++)\n                r[i][i] = 1;\n            return r;\n        },\n        diag(a) {\n            var r, i, n;\n            n = a.length;\n            r = Matrix(n, n);\n            for(i = 0; i < n; i++)\n                r[i][i] = a[i];\n            return r;\n        },\n        hilbert(n) {\n            var i, j, r;\n            r = Matrix(n);\n            for(i = 0; i < n; i++) {\n                for(j = 0; j < n; j++) {\n                    r[i][j] = 1 / (1 + i + j);\n                }\n            }\n            return r;\n        },\n        trans(a) {\n            var h, w, r, i, j;\n            if (!Array.isArray(a))\n                throw TypeError(\"matrix expected\");\n            h = a.length;\n            if (!Array.isArray(a[0])) {\n                w = 1;\n                r = Matrix(w, h);\n                for(i = 0; i < h; i++) {\n                    r[0][i] = a[i];\n                }\n            } else {\n                w = a[0].length;\n                r = Matrix(w, h);\n                for(i = 0; i < h; i++) {\n                    for(j = 0; j < w; j++) {\n                        r[j][i] = a[i][j];\n                    }\n                }\n            }\n            return r;\n        },\n        check_square(a) {\n            var a, n;\n            if (!Array.isArray(a))\n                throw TypeError(\"array expected\");\n            n = a.length;\n            if (!Array.isArray(a[0]) || n != a[0].length)\n                throw TypeError(\"square matrix expected\");\n            return n;\n        },\n        trace(a) {\n            var n, r, i;\n            n = Matrix.check_square(a);\n            r = a[0][0];\n            for(i = 1; i < n; i++) {\n                r += a[i][i];\n            }\n            return r;\n        },\n        charpoly(a) {\n            var n, p, c, i, j, coef;\n            n = Matrix.check_square(a);\n            p = [];\n            for(i = 0; i < n + 1; i++)\n                p[i] = 0;\n            p[n] = 1;\n            c = Matrix.idn(n);\n            for(i = 0; i < n; i++) {\n                c = c * a;\n                coef = -trace(c) / (i + 1);\n                p[n - i - 1] = coef;\n                for(j = 0; j < n; j++)\n                    c[j][j] += coef;\n            }\n            return Polynomial(p);\n        },\n        eigenvals(a) {\n            return Polynomial.roots(Matrix.charpoly(a));\n        },\n        det(a) {\n            var n, i, j, k, s, src, v, c;\n            \n            n = Matrix.check_square(a);\n            s = 1;\n            src = a.dup();\n            for(i=0;i<n;i++) {\n                for(j = i; j < n; j++) {\n                    if (src[j][i] != 0)\n                        break;\n                }\n                if (j == n)\n                    return 0;\n                if (j != i) {\n                    for(k = 0;k < n; k++) {\n                        v = src[j][k];\n                        src[j][k] = src[i][k];\n                        src[i][k] = v;\n                    }\n                    s = -s;\n                }\n                c = src[i][i].inverse();\n                for(j = i + 1; j < n; j++) {\n                    v = c * src[j][i];\n                    for(k = 0;k < n; k++) {\n                        src[j][k] -= src[i][k] * v;\n                    }\n                }\n            }\n            c = s;\n            for(i=0;i<n;i++)\n                c *= src[i][i];\n            return c;\n        },\n        inverse(a) {\n            var n, dst, src, i, j, k, n2, r, c, v;\n            n = Matrix.check_square(a);\n            src = a.dup();\n            dst = Matrix.idn(n);\n            for(i=0;i<n;i++) {\n                for(j = i; j < n; j++) {\n                    if (src[j][i] != 0)\n                        break;\n                }\n                if (j == n)\n                    throw RangeError(\"matrix is not invertible\");\n                if (j != i) {\n                    /* swap lines in src and dst */\n                    v = src[j];\n                    src[j] = src[i];\n                    src[i] = v;\n                    v = dst[j];\n                    dst[j] = dst[i];\n                    dst[i] = v;\n                }\n\n                c = src[i][i].inverse();\n                for(k = 0; k < n; k++) {\n                    src[i][k] *= c;\n                    dst[i][k] *= c;\n                }\n                \n                for(j = 0; j < n; j++) {\n                    if (j != i) {\n                        c = src[j][i];\n                        for(k = i; k < n; k++) {\n                            src[j][k] -= src[i][k] * c;\n                        }\n                        for(k = 0; k < n; k++) {\n                            dst[j][k] -= dst[i][k] * c;\n                        }\n                    }\n                }\n            }\n            return dst;\n        },\n        rank(a) {\n            var src, i, j, k, w, h, l, c;\n            \n            if (!Array.isArray(a) ||\n                !Array.isArray(a[0]))\n                throw TypeError(\"matrix expected\");\n            h = a.length;\n            w = a[0].length;\n            src = a.dup();\n            l = 0;\n            for(i=0;i<w;i++) {\n                for(j = l; j < h; j++) {\n                    if (src[j][i] != 0)\n                        break;\n                }\n                if (j == h)\n                    continue;\n                if (j != l) {\n                    /* swap lines */\n                    for(k = 0; k < w; k++) {\n                        v = src[j][k];\n                        src[j][k] = src[l][k];\n                        src[l][k] = v;\n                    }\n                }\n                \n                c = src[l][i].inverse();\n                for(k = 0; k < w; k++) {\n                    src[l][k] *= c;\n                }\n                \n                for(j = l + 1; j < h; j++) {\n                    c = src[j][i];\n                    for(k = i; k < w; k++) {\n                        src[j][k] -= src[l][k] * c;\n                    }\n                }\n                l++;\n            }\n            return l;\n        },\n        ker(a) {\n            var src, i, j, k, w, h, l, m, r, im_cols, ker_dim, c;\n            \n            if (!Array.isArray(a) ||\n                !Array.isArray(a[0]))\n                throw TypeError(\"matrix expected\");\n            h = a.length;\n            w = a[0].length;\n            src = a.dup();\n            im_cols = [];\n            l = 0;\n            for(i=0;i<w;i++) {\n                im_cols[i] = false;\n                for(j = l; j < h; j++) {\n                    if (src[j][i] != 0)\n                        break;\n                }\n                if (j == h)\n                    continue;\n                im_cols[i] = true;\n                if (j != l) {\n                    /* swap lines */\n                    for(k = 0; k < w; k++) {\n                        v = src[j][k];\n                        src[j][k] = src[l][k];\n                        src[l][k] = v;\n                    }\n                }\n                \n                c = src[l][i].inverse();\n                for(k = 0; k < w; k++) {\n                    src[l][k] *= c;\n                }\n                \n                for(j = 0; j < h; j++) {\n                    if (j != l) {\n                        c = src[j][i];\n                        for(k = i; k < w; k++) {\n                            src[j][k] -= src[l][k] * c;\n                        }\n                    }\n                }\n                l++;\n                //        log_str(\"m=\" + cval_toString(v1) + \"\\n\");\n            }\n            //    log_str(\"im cols=\"+im_cols+\"\\n\");\n\n            /* build the kernel vectors */\n            ker_dim = w - l;\n            r = Matrix(w, ker_dim);\n            k = 0;\n            for(i = 0; i < w; i++) {\n                if (!im_cols[i]) {\n                    /* select this column from the matrix */\n                    l = 0;\n                    m = 0;\n                    for(j = 0; j < w; j++) {\n                        if (im_cols[j]) {\n                            r[j][k] = -src[m][i];\n                            m++;\n                        } else {\n                            if (l == k) {\n                                r[j][k] = 1;\n                            } else {\n                                r[j][k] = 0;\n                            }\n                            l++;\n                        }\n                    }\n                    k++;\n                }\n            }\n            return r;\n        },\n        dp(a, b) {\n            var i, n, r;\n            n = a.length;\n            if (n != b.length)\n                throw TypeError(\"incompatible array length\");\n            /* XXX: could do complex product */\n            r = 0;\n            for(i = 0; i < n; i++) {\n                r += a[i] * b[i];\n            }\n            return r;\n        },\n        /* cross product */\n        cp(v1, v2) {\n            var r;\n            if (v1.length != 3 || v2.length != 3)\n                throw TypeError(\"vectors must have 3 elements\");\n            r = [];\n            r[0] = v1[1] * v2[2] - v1[2] * v2[1];\n            r[1] = v1[2] * v2[0] - v1[0] * v2[2];\n            r[2] = v1[0] * v2[1] - v1[1] * v2[0];\n            return r;\n        },\n    });\n\n    function array_add(a, b) {\n        var r, i, n;\n        n = a.length;\n        if (n != b.length)\n            throw TypeError(\"incompatible array size\");\n        r = [];\n        for(i = 0; i < n; i++)\n            r[i] = a[i] + b[i];\n        return r;\n    }\n    function array_sub(a, b) {\n        var r, i, n;\n        n = a.length;\n        if (n != b.length)\n            throw TypeError(\"incompatible array size\");\n        r = [];\n        for(i = 0; i < n; i++)\n            r[i] = a[i] - b[i];\n        return r;\n    }\n    function array_scalar_mul(a, b) {\n        var r, i, n;\n        n = a.length;\n        r = [];\n        for(i = 0; i < n; i++)\n            r[i] = a[i] * b;\n        return r;\n    }\n    function array_mul(a, b) {\n        var h, w, l, i, j, k, r, rl, sum, a_mat, b_mat;\n        h = a.length;\n        a_mat = Array.isArray(a[0]);\n        if (a_mat) {\n            l = a[0].length;\n        } else {\n            l = 1;\n        }\n        if (l != b.length)\n            throw RangeError(\"incompatible matrix size\");\n        b_mat = Array.isArray(b[0]);\n        if (b_mat)\n            w = b[0].length;\n        else\n            w = 1;\n        r = [];\n        if (a_mat && b_mat) {\n            for(i = 0; i < h; i++) {\n                rl = [];\n                for(j = 0; j < w; j++) {\n                    sum = 0;\n                    for(k = 0; k < l; k++) {\n                        sum += a[i][k] * b[k][j];\n                    }\n                    rl[j] = sum;\n                }\n                r[i] = rl;\n            }\n        } else if (a_mat && !b_mat) {\n            for(i = 0; i < h; i++) {\n                sum = 0;\n                for(k = 0; k < l; k++) {\n                    sum += a[i][k] * b[k];\n                }\n                r[i] = sum;\n            }\n        } else if (!a_mat && b_mat) {\n            for(i = 0; i < h; i++) {\n                rl = [];\n                for(j = 0; j < w; j++) {\n                    rl[j] = a[i] * b[0][j];\n                }\n                r[i] = rl;\n            }\n        } else {\n            for(i = 0; i < h; i++) {\n                r[i] = a[i] * b[0];\n            }\n        }\n        return r;\n    }\n    function array_div(a, b) {\n        return array_mul(a, b.inverse());\n    }\n    function array_element_wise_inverse(a) {\n        var r, i, n;\n        n = a.length;\n        r = [];\n        for(i = 0; i < n; i++)\n            r[i] = a[i].inverse();\n        return r;\n    }\n    function array_eq(a, b) {\n        var n, i;\n        n = a.length;\n        if (n != b.length)\n            return false;\n        for(i = 0; i < n; i++) {\n            if (a[i] != b[i])\n                return false;\n        }\n        return true;\n    }\n\n    operators_set(Array.prototype,\n        {\n            \"+\": array_add,\n            \"-\": array_sub,\n            \"*\": array_mul,\n            \"/\": array_div,\n            \"==\": array_eq,\n            \"pos\"(a) {\n                return a;\n            },\n            \"neg\"(a) {\n                var i, n, r;\n                n = a.length;\n                r = [];\n                for(i = 0; i < n; i++)\n                    r[i] = -a[i];\n                return r;\n            }\n        },\n        {\n            right: [Number, BigInt, Float, Fraction, Complex, Mod,\n                    Polynomial, PolyMod, RationalFunction, Series],\n            \"*\": array_scalar_mul,\n            \"/\"(a, b) { return a * b.inverse(); },\n            \"**\": generic_pow, /* XXX: only for integer */\n        },\n        {\n            left: [Number, BigInt, Float, Fraction, Complex, Mod,\n                   Polynomial, PolyMod, RationalFunction, Series],\n            \"*\"(a, b) { return array_scalar_mul(b, a); },\n            \"/\"(a, b) { return a * array_element_wise_inverse(b); },\n        });\n\n    add_props(Array.prototype, {\n        conj() {\n            var i, n, r;\n            n = this.length;\n            r = [];\n            for(i = 0; i < n; i++)\n                r[i] = this[i].conj();\n            return r;\n        },\n        dup() {\n            var r, i, n, el, a = this;\n            r = [];\n            n = a.length;\n            for(i = 0; i < n; i++) {\n                el = a[i];\n                if (Array.isArray(el))\n                    el = el.dup();\n                r[i] = el;\n            }\n            return r;\n        },\n        inverse() {\n            return Matrix.inverse(this);\n        },\n        norm2: Polynomial.prototype.norm2,\n    });\n\n})(this);\n\n/* global definitions */\nvar I = Complex(0, 1);\nvar X = Polynomial([0, 1]);\nvar O = Series.O;\n\nObject.defineProperty(this, \"PI\", { get: function () { return Float.PI } });\n\n/* put frequently used functions in the global context */\nvar gcd = Integer.gcd;\nvar fact = Integer.fact;\nvar comb = Integer.comb;\nvar pmod = Integer.pmod;\nvar invmod = Integer.invmod;\nvar factor = Integer.factor;\nvar isprime = Integer.isPrime;\nvar nextprime = Integer.nextPrime;\n\nfunction deriv(a)\n{\n    return a.deriv();\n}\n\nfunction integ(a)\n{\n    return a.integ();\n}\n\nfunction norm2(a)\n{\n    return a.norm2();\n}\n\nfunction abs(a)\n{\n    return a.abs();\n}\n\nfunction conj(a)\n{\n    return a.conj();\n}\n\nfunction arg(a)\n{\n    return a.arg();\n}\n\nfunction inverse(a)\n{\n    return a.inverse();\n}\n\nfunction trunc(a)\n{\n    if (Integer.isInteger(a)) {\n        return a;\n    } else if (a instanceof Fraction) {\n        return Integer.tdiv(a.num, a.den);\n    } else if (a instanceof Polynomial) {\n        return a;\n    } else if (a instanceof RationalFunction) {\n        return Polynomial.divrem(a.num, a.den)[0];\n    } else {\n        return Float.ceil(a);\n    }\n}\n\nfunction floor(a)\n{\n    if (Integer.isInteger(a)) {\n        return a;\n    } else if (a instanceof Fraction) {\n        return Integer.fdiv(a.num, a.den);\n    } else {\n        return Float.floor(a);\n    }\n}\n\nfunction ceil(a)\n{\n    if (Integer.isInteger(a)) {\n        return a;\n    } else if (a instanceof Fraction) {\n        return Integer.cdiv(a.num, a.den);\n    } else {\n        return Float.ceil(a);\n    }\n}\n\nfunction sqrt(a)\n{\n    var t, u, re, im;\n    if (a instanceof Series) {\n        return a ^ (1/2);\n    } else if (a instanceof Complex) {\n        t = abs(a);\n        u = a.re;\n        re = sqrt((t + u) / 2);\n        im = sqrt((t - u) / 2);\n        if (a.im < 0)\n            im = -im;\n        return Complex.toComplex(re, im);\n    } else {\n        a = Float(a);\n        if (a < 0) {\n            return Complex(0, Float.sqrt(-a));\n        } else {\n            return Float.sqrt(a);\n        }\n    }\n}\n\nfunction exp(a)\n{\n    return a.exp();\n}\n\nfunction log(a)\n{\n    return a.log();\n}\n\nfunction log2(a)\n{\n    return log(a) * Float.LOG2E;\n}\n\nfunction log10(a)\n{\n    return log(a) * Float.LOG10E;\n}\n\nfunction todb(a)\n{\n    return log10(a) * 10;\n}\n\nfunction fromdb(a)\n{\n    return 10 ^ (a / 10);\n}\n\nfunction sin(a)\n{\n    var t;\n    if (a instanceof Complex || a instanceof Series) {\n        t = exp(a * I);\n        return (t - 1/t) / (2 * I);\n    } else {\n        return Float.sin(Float(a));\n    }\n}\n\nfunction cos(a)\n{\n    var t;\n    if (a instanceof Complex || a instanceof Series) {\n        t = exp(a * I);\n        return (t + 1/t) / 2;\n    } else {\n        return Float.cos(Float(a));\n    }\n}\n\nfunction tan(a)\n{\n    if (a instanceof Complex || a instanceof Series) {\n        return sin(a) / cos(a);\n    } else {\n        return Float.tan(Float(a));\n    }\n}\n\nfunction asin(a)\n{\n    return Float.asin(Float(a));\n}\n\nfunction acos(a)\n{\n    return Float.acos(Float(a));\n}\n\nfunction atan(a)\n{\n    return Float.atan(Float(a));\n}\n\nfunction atan2(a, b)\n{\n    return Float.atan2(Float(a), Float(b));\n}\n\nfunction sinc(a)\n{\n    if (a == 0) {\n        return 1;\n    } else {\n        a *= Float.PI;\n        return sin(a) / a;\n    }\n}\n\nfunction todeg(a)\n{\n    return a * 180 / Float.PI;\n}\n\nfunction fromdeg(a)\n{\n    return a * Float.PI / 180;\n}\n\nfunction sinh(a)\n{\n    var e = Float.exp(Float(a));\n    return (e - 1/e) * 0.5;\n}\n\nfunction cosh(a)\n{\n    var e = Float.exp(Float(a));\n    return (e + 1/e) * 0.5;\n}\n\nfunction tanh(a)\n{\n    var e = Float.exp(Float(a) * 2);\n    return (e - 1) / (e + 1);\n}\n\nfunction asinh(a)\n{\n    var x = Float(a);\n    return log(sqrt(x * x + 1) + x);\n}\n\nfunction acosh(a)\n{\n    var x = Float(a);\n    return log(sqrt(x * x - 1) + x);\n}\n\nfunction atanh(a)\n{\n    var x = Float(a);\n    return 0.5 * log((1 + x) / (1 - x));\n}\n\nfunction sigmoid(x)\n{\n    x = Float(x);\n    return 1 / (1 + exp(-x));\n}\n\nfunction lerp(a, b, t)\n{\n    return a + (b - a) * t;\n}\n\nvar idn = Matrix.idn;\nvar diag = Matrix.diag;\nvar trans = Matrix.trans;\nvar trace = Matrix.trace;\nvar charpoly = Matrix.charpoly;\nvar eigenvals = Matrix.eigenvals;\nvar det = Matrix.det;\nvar rank = Matrix.rank;\nvar ker = Matrix.ker;\nvar cp = Matrix.cp;\nvar dp = Matrix.dp;\n\nvar polroots = Polynomial.roots;\nvar bestappr = Float.bestappr;\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/quickjs-atom.h",
    "content": "/*\n * QuickJS atom definitions\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n * Copyright (c) 2017-2018 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n#ifdef DEF\n\n/* Note: first atoms are considered as keywords in the parser */\nDEF(null, \"null\") /* must be first */\nDEF(false, \"false\")\nDEF(true, \"true\")\nDEF(if, \"if\")\nDEF(else, \"else\")\nDEF(return, \"return\")\nDEF(var, \"var\")\nDEF(this, \"this\")\nDEF(delete, \"delete\")\nDEF(void, \"void\")\nDEF(typeof, \"typeof\")\nDEF(new, \"new\")\nDEF(in, \"in\")\nDEF(instanceof, \"instanceof\")\nDEF(do, \"do\")\nDEF(while, \"while\")\nDEF(for, \"for\")\nDEF(break, \"break\")\nDEF(continue, \"continue\")\nDEF(switch, \"switch\")\nDEF(case, \"case\")\nDEF(default, \"default\")\nDEF(throw, \"throw\")\nDEF(try, \"try\")\nDEF(catch, \"catch\")\nDEF(finally, \"finally\")\nDEF(function, \"function\")\nDEF(debugger, \"debugger\")\nDEF(with, \"with\")\n/* FutureReservedWord */\nDEF(class, \"class\")\nDEF(const, \"const\")\nDEF(enum, \"enum\")\nDEF(export, \"export\")\nDEF(extends, \"extends\")\nDEF(import, \"import\")\nDEF(super, \"super\")\n/* FutureReservedWords when parsing strict mode code */\nDEF(implements, \"implements\")\nDEF(interface, \"interface\")\nDEF(let, \"let\")\nDEF(package, \"package\")\nDEF(private, \"private\")\nDEF(protected, \"protected\")\nDEF(public, \"public\")\nDEF(static, \"static\")\nDEF(yield, \"yield\")\nDEF(await, \"await\")\n\n/* empty string */\nDEF(empty_string, \"\")\n/* identifiers */\nDEF(length, \"length\")\nDEF(fileName, \"fileName\")\nDEF(lineNumber, \"lineNumber\")\nDEF(message, \"message\")\nDEF(errors, \"errors\")\nDEF(stack, \"stack\")\nDEF(name, \"name\")\nDEF(toString, \"toString\")\nDEF(toLocaleString, \"toLocaleString\")\nDEF(valueOf, \"valueOf\")\nDEF(eval, \"eval\")\nDEF(prototype, \"prototype\")\nDEF(constructor, \"constructor\")\nDEF(configurable, \"configurable\")\nDEF(writable, \"writable\")\nDEF(enumerable, \"enumerable\")\nDEF(value, \"value\")\nDEF(get, \"get\")\nDEF(set, \"set\")\nDEF(of, \"of\")\nDEF(__proto__, \"__proto__\")\nDEF(undefined, \"undefined\")\nDEF(number, \"number\")\nDEF(boolean, \"boolean\")\nDEF(string, \"string\")\nDEF(object, \"object\")\nDEF(symbol, \"symbol\")\nDEF(integer, \"integer\")\nDEF(unknown, \"unknown\")\nDEF(arguments, \"arguments\")\nDEF(callee, \"callee\")\nDEF(caller, \"caller\")\nDEF(_eval_, \"<eval>\")\nDEF(_ret_, \"<ret>\")\nDEF(_var_, \"<var>\")\nDEF(_arg_var_, \"<arg_var>\")\nDEF(_with_, \"<with>\")\nDEF(lastIndex, \"lastIndex\")\nDEF(target, \"target\")\nDEF(index, \"index\")\nDEF(input, \"input\")\nDEF(defineProperties, \"defineProperties\")\nDEF(apply, \"apply\")\nDEF(join, \"join\")\nDEF(concat, \"concat\")\nDEF(split, \"split\")\nDEF(construct, \"construct\")\nDEF(getPrototypeOf, \"getPrototypeOf\")\nDEF(setPrototypeOf, \"setPrototypeOf\")\nDEF(isExtensible, \"isExtensible\")\nDEF(preventExtensions, \"preventExtensions\")\nDEF(has, \"has\")\nDEF(deleteProperty, \"deleteProperty\")\nDEF(defineProperty, \"defineProperty\")\nDEF(getOwnPropertyDescriptor, \"getOwnPropertyDescriptor\")\nDEF(ownKeys, \"ownKeys\")\nDEF(add, \"add\")\nDEF(done, \"done\")\nDEF(next, \"next\")\nDEF(values, \"values\")\nDEF(source, \"source\")\nDEF(flags, \"flags\")\nDEF(global, \"global\")\nDEF(unicode, \"unicode\")\nDEF(raw, \"raw\")\nDEF(new_target, \"new.target\")\nDEF(this_active_func, \"this.active_func\")\nDEF(home_object, \"<home_object>\")\nDEF(computed_field, \"<computed_field>\")\nDEF(static_computed_field, \"<static_computed_field>\") /* must come after computed_fields */\nDEF(class_fields_init, \"<class_fields_init>\")\nDEF(brand, \"<brand>\")\nDEF(hash_constructor, \"#constructor\")\nDEF(as, \"as\")\nDEF(from, \"from\")\nDEF(meta, \"meta\")\nDEF(_default_, \"*default*\")\nDEF(_star_, \"*\")\nDEF(Module, \"Module\")\nDEF(then, \"then\")\nDEF(resolve, \"resolve\")\nDEF(reject, \"reject\")\nDEF(promise, \"promise\")\nDEF(proxy, \"proxy\")\nDEF(revoke, \"revoke\")\nDEF(async, \"async\")\nDEF(exec, \"exec\")\nDEF(groups, \"groups\")\nDEF(status, \"status\")\nDEF(reason, \"reason\")\nDEF(globalThis, \"globalThis\")\n#ifdef CONFIG_BIGNUM\nDEF(bigint, \"bigint\")\nDEF(bigfloat, \"bigfloat\")\nDEF(bigdecimal, \"bigdecimal\")\nDEF(roundingMode, \"roundingMode\")\nDEF(maximumSignificantDigits, \"maximumSignificantDigits\")\nDEF(maximumFractionDigits, \"maximumFractionDigits\")\n#endif\n#ifdef CONFIG_ATOMICS\nDEF(not_equal, \"not-equal\")\nDEF(timed_out, \"timed-out\")\nDEF(ok, \"ok\")\n#endif\nDEF(toJSON, \"toJSON\")\n/* class names */\nDEF(Object, \"Object\")\nDEF(Array, \"Array\")\nDEF(Error, \"Error\")\nDEF(Number, \"Number\")\nDEF(String, \"String\")\nDEF(Boolean, \"Boolean\")\nDEF(Symbol, \"Symbol\")\nDEF(Arguments, \"Arguments\")\nDEF(Math, \"Math\")\nDEF(JSON, \"JSON\")\nDEF(Date, \"Date\")\nDEF(Function, \"Function\")\nDEF(GeneratorFunction, \"GeneratorFunction\")\nDEF(ForInIterator, \"ForInIterator\")\nDEF(RegExp, \"RegExp\")\nDEF(ArrayBuffer, \"ArrayBuffer\")\nDEF(SharedArrayBuffer, \"SharedArrayBuffer\")\n/* must keep same order as class IDs for typed arrays */\nDEF(Uint8ClampedArray, \"Uint8ClampedArray\") \nDEF(Int8Array, \"Int8Array\")\nDEF(Uint8Array, \"Uint8Array\")\nDEF(Int16Array, \"Int16Array\")\nDEF(Uint16Array, \"Uint16Array\")\nDEF(Int32Array, \"Int32Array\")\nDEF(Uint32Array, \"Uint32Array\")\n#ifdef CONFIG_BIGNUM\nDEF(BigInt64Array, \"BigInt64Array\")\nDEF(BigUint64Array, \"BigUint64Array\")\n#endif\nDEF(Float32Array, \"Float32Array\")\nDEF(Float64Array, \"Float64Array\")\nDEF(DataView, \"DataView\")\n#ifdef CONFIG_BIGNUM\nDEF(BigInt, \"BigInt\")\nDEF(BigFloat, \"BigFloat\")\nDEF(BigFloatEnv, \"BigFloatEnv\")\nDEF(BigDecimal, \"BigDecimal\")\nDEF(OperatorSet, \"OperatorSet\")\nDEF(Operators, \"Operators\")\n#endif\nDEF(Map, \"Map\")\nDEF(Set, \"Set\") /* Map + 1 */\nDEF(WeakMap, \"WeakMap\") /* Map + 2 */\nDEF(WeakSet, \"WeakSet\") /* Map + 3 */\nDEF(Map_Iterator, \"Map Iterator\")\nDEF(Set_Iterator, \"Set Iterator\")\nDEF(Array_Iterator, \"Array Iterator\")\nDEF(String_Iterator, \"String Iterator\")\nDEF(RegExp_String_Iterator, \"RegExp String Iterator\")\nDEF(Generator, \"Generator\")\nDEF(Proxy, \"Proxy\")\nDEF(Promise, \"Promise\")\nDEF(PromiseResolveFunction, \"PromiseResolveFunction\")\nDEF(PromiseRejectFunction, \"PromiseRejectFunction\")\nDEF(AsyncFunction, \"AsyncFunction\")\nDEF(AsyncFunctionResolve, \"AsyncFunctionResolve\")\nDEF(AsyncFunctionReject, \"AsyncFunctionReject\")\nDEF(AsyncGeneratorFunction, \"AsyncGeneratorFunction\")\nDEF(AsyncGenerator, \"AsyncGenerator\")\nDEF(EvalError, \"EvalError\")\nDEF(RangeError, \"RangeError\")\nDEF(ReferenceError, \"ReferenceError\")\nDEF(SyntaxError, \"SyntaxError\")\nDEF(TypeError, \"TypeError\")\nDEF(URIError, \"URIError\")\nDEF(InternalError, \"InternalError\")\n/* private symbols */\nDEF(Private_brand, \"<brand>\")\n/* symbols */\nDEF(Symbol_toPrimitive, \"Symbol.toPrimitive\")\nDEF(Symbol_iterator, \"Symbol.iterator\")\nDEF(Symbol_match, \"Symbol.match\")\nDEF(Symbol_matchAll, \"Symbol.matchAll\")\nDEF(Symbol_replace, \"Symbol.replace\")\nDEF(Symbol_search, \"Symbol.search\")\nDEF(Symbol_split, \"Symbol.split\")\nDEF(Symbol_toStringTag, \"Symbol.toStringTag\")\nDEF(Symbol_isConcatSpreadable, \"Symbol.isConcatSpreadable\")\nDEF(Symbol_hasInstance, \"Symbol.hasInstance\")\nDEF(Symbol_species, \"Symbol.species\")\nDEF(Symbol_unscopables, \"Symbol.unscopables\")\nDEF(Symbol_asyncIterator, \"Symbol.asyncIterator\")\n#ifdef CONFIG_BIGNUM\nDEF(Symbol_operatorSet, \"Symbol.operatorSet\")\n#endif\n    \n#endif /* DEF */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/quickjs-libc.c",
    "content": "/*\n * QuickJS C library\n * \n * Copyright (c) 2017-2021 Fabrice Bellard\n * Copyright (c) 2017-2021 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <inttypes.h>\n#include <string.h>\n#include <assert.h>\n#include <unistd.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sys/time.h>\n#include <time.h>\n#include <signal.h>\n#include <limits.h>\n#include <sys/stat.h>\n#include <dirent.h>\n#if defined(_WIN32)\n#include <windows.h>\n#include <conio.h>\n#include <utime.h>\n#else\n#include <dlfcn.h>\n#include <termios.h>\n#include <sys/ioctl.h>\n#include <sys/wait.h>\n\n#if defined(__APPLE__)\ntypedef sig_t sighandler_t;\n#if !defined(environ)\n#include <crt_externs.h>\n#define environ (*_NSGetEnviron())\n#endif\n#endif /* __APPLE__ */\n\n#endif\n\n#if !defined(_WIN32)\n/* enable the os.Worker API. IT relies on POSIX threads */\n#define USE_WORKER\n#endif\n\n#ifdef USE_WORKER\n#include <pthread.h>\n#include <stdatomic.h>\n#endif\n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"quickjs-libc.h\"\n\n/* TODO:\n   - add socket calls\n*/\n\ntypedef struct {\n    struct list_head link;\n    int fd;\n    JSValue rw_func[2];\n} JSOSRWHandler;\n\ntypedef struct {\n    struct list_head link;\n    int sig_num;\n    JSValue func;\n} JSOSSignalHandler;\n\ntypedef struct {\n    struct list_head link;\n    BOOL has_object;\n    int64_t timeout;\n    JSValue func;\n} JSOSTimer;\n\ntypedef struct {\n    struct list_head link;\n    uint8_t *data;\n    size_t data_len;\n    /* list of SharedArrayBuffers, necessary to free the message */\n    uint8_t **sab_tab;\n    size_t sab_tab_len;\n} JSWorkerMessage;\n\ntypedef struct {\n    int ref_count;\n#ifdef USE_WORKER\n    pthread_mutex_t mutex;\n#endif\n    struct list_head msg_queue; /* list of JSWorkerMessage.link */\n    int read_fd;\n    int write_fd;\n} JSWorkerMessagePipe;\n\ntypedef struct {\n    struct list_head link;\n    JSWorkerMessagePipe *recv_pipe;\n    JSValue on_message_func;\n} JSWorkerMessageHandler;\n\ntypedef struct JSThreadState {\n    struct list_head os_rw_handlers; /* list of JSOSRWHandler.link */\n    struct list_head os_signal_handlers; /* list JSOSSignalHandler.link */\n    struct list_head os_timers; /* list of JSOSTimer.link */\n    struct list_head port_list; /* list of JSWorkerMessageHandler.link */\n    int eval_script_recurse; /* only used in the main thread */\n    /* not used in the main thread */\n    JSWorkerMessagePipe *recv_pipe, *send_pipe;\n} JSThreadState;\n\nstatic uint64_t os_pending_signals;\nstatic int (*os_poll_func)(JSContext *ctx);\n\nstatic void js_std_dbuf_init(JSContext *ctx, DynBuf *s)\n{\n    dbuf_init2(s, JS_GetRuntime(ctx), (DynBufReallocFunc *)js_realloc_rt);\n}\n\nstatic BOOL my_isdigit(int c)\n{\n    return (c >= '0' && c <= '9');\n}\n\nstatic JSValue js_printf_internal(JSContext *ctx,\n                                  int argc, JSValueConst *argv, FILE *fp)\n{\n    char fmtbuf[32];\n    uint8_t cbuf[UTF8_CHAR_LEN_MAX+1];\n    JSValue res;\n    DynBuf dbuf;\n    const char *fmt_str;\n    const uint8_t *fmt, *fmt_end;\n    const uint8_t *p;\n    char *q;\n    int i, c, len, mod;\n    size_t fmt_len;\n    int32_t int32_arg;\n    int64_t int64_arg;\n    double double_arg;\n    const char *string_arg;\n    /* Use indirect call to dbuf_printf to prevent gcc warning */\n    int (*dbuf_printf_fun)(DynBuf *s, const char *fmt, ...) = (void*)dbuf_printf;\n\n    js_std_dbuf_init(ctx, &dbuf);\n\n    if (argc > 0) {\n        fmt_str = JS_ToCStringLen(ctx, &fmt_len, argv[0]);\n        if (!fmt_str)\n            goto fail;\n\n        i = 1;\n        fmt = (const uint8_t *)fmt_str;\n        fmt_end = fmt + fmt_len;\n        while (fmt < fmt_end) {\n            for (p = fmt; fmt < fmt_end && *fmt != '%'; fmt++)\n                continue;\n            dbuf_put(&dbuf, p, fmt - p);\n            if (fmt >= fmt_end)\n                break;\n            q = fmtbuf;\n            *q++ = *fmt++;  /* copy '%' */\n            \n            /* flags */\n            for(;;) {\n                c = *fmt;\n                if (c == '0' || c == '#' || c == '+' || c == '-' || c == ' ' ||\n                    c == '\\'') {\n                    if (q >= fmtbuf + sizeof(fmtbuf) - 1)\n                        goto invalid;\n                    *q++ = c;\n                    fmt++;\n                } else {\n                    break;\n                }\n            }\n            /* width */\n            if (*fmt == '*') {\n                if (i >= argc)\n                    goto missing;\n                if (JS_ToInt32(ctx, &int32_arg, argv[i++]))\n                    goto fail;\n                q += snprintf(q, fmtbuf + sizeof(fmtbuf) - q, \"%d\", int32_arg);\n                fmt++;\n            } else {\n                while (my_isdigit(*fmt)) {\n                    if (q >= fmtbuf + sizeof(fmtbuf) - 1)\n                        goto invalid;\n                    *q++ = *fmt++;\n                }\n            }\n            if (*fmt == '.') {\n                if (q >= fmtbuf + sizeof(fmtbuf) - 1)\n                    goto invalid;\n                *q++ = *fmt++;\n                if (*fmt == '*') {\n                    if (i >= argc)\n                        goto missing;\n                    if (JS_ToInt32(ctx, &int32_arg, argv[i++]))\n                        goto fail;\n                    q += snprintf(q, fmtbuf + sizeof(fmtbuf) - q, \"%d\", int32_arg);\n                    fmt++;\n                } else {\n                    while (my_isdigit(*fmt)) {\n                        if (q >= fmtbuf + sizeof(fmtbuf) - 1)\n                            goto invalid;\n                        *q++ = *fmt++;\n                    }\n                }\n            }\n\n            /* we only support the \"l\" modifier for 64 bit numbers */\n            mod = ' ';\n            if (*fmt == 'l') {\n                mod = *fmt++;\n            }\n            \n            /* type */\n            c = *fmt++;\n            if (q >= fmtbuf + sizeof(fmtbuf) - 1)\n                goto invalid;\n            *q++ = c;\n            *q = '\\0';\n            \n            switch (c) {\n            case 'c':\n                if (i >= argc)\n                    goto missing;\n                if (JS_IsString(argv[i])) {\n                    string_arg = JS_ToCString(ctx, argv[i++]);\n                    if (!string_arg)\n                        goto fail;\n                    int32_arg = unicode_from_utf8((uint8_t *)string_arg, UTF8_CHAR_LEN_MAX, &p);\n                    JS_FreeCString(ctx, string_arg);\n                } else {\n                    if (JS_ToInt32(ctx, &int32_arg, argv[i++]))\n                        goto fail;\n                }\n                /* handle utf-8 encoding explicitly */\n                if ((unsigned)int32_arg > 0x10FFFF)\n                    int32_arg = 0xFFFD;\n                /* ignore conversion flags, width and precision */\n                len = unicode_to_utf8(cbuf, int32_arg);\n                dbuf_put(&dbuf, cbuf, len);\n                break;\n                \n            case 'd':\n            case 'i':\n            case 'o':\n            case 'u':\n            case 'x':\n            case 'X':\n                if (i >= argc)\n                    goto missing;\n                if (JS_ToInt64Ext(ctx, &int64_arg, argv[i++]))\n                    goto fail;\n                if (mod == 'l') {\n                    /* 64 bit number */\n#if defined(_WIN32)\n                    if (q >= fmtbuf + sizeof(fmtbuf) - 3)\n                        goto invalid;\n                    q[2] = q[-1];\n                    q[-1] = 'I';\n                    q[0] = '6';\n                    q[1] = '4';\n                    q[3] = '\\0';\n                    dbuf_printf_fun(&dbuf, fmtbuf, (int64_t)int64_arg);\n#else\n                    if (q >= fmtbuf + sizeof(fmtbuf) - 2)\n                        goto invalid;\n                    q[1] = q[-1];\n                    q[-1] = q[0] = 'l';\n                    q[2] = '\\0';\n                    dbuf_printf_fun(&dbuf, fmtbuf, (long long)int64_arg);\n#endif\n                } else {\n                    dbuf_printf_fun(&dbuf, fmtbuf, (int)int64_arg);\n                }\n                break;\n\n            case 's':\n                if (i >= argc)\n                    goto missing;\n                /* XXX: handle strings containing null characters */\n                string_arg = JS_ToCString(ctx, argv[i++]);\n                if (!string_arg)\n                    goto fail;\n                dbuf_printf_fun(&dbuf, fmtbuf, string_arg);\n                JS_FreeCString(ctx, string_arg);\n                break;\n                \n            case 'e':\n            case 'f':\n            case 'g':\n            case 'a':\n            case 'E':\n            case 'F':\n            case 'G':\n            case 'A':\n                if (i >= argc)\n                    goto missing;\n                if (JS_ToFloat64(ctx, &double_arg, argv[i++]))\n                    goto fail;\n                dbuf_printf_fun(&dbuf, fmtbuf, double_arg);\n                break;\n                \n            case '%':\n                dbuf_putc(&dbuf, '%');\n                break;\n                \n            default:\n                /* XXX: should support an extension mechanism */\n            invalid:\n                JS_ThrowTypeError(ctx, \"invalid conversion specifier in format string\");\n                goto fail;\n            missing:\n                JS_ThrowReferenceError(ctx, \"missing argument for conversion specifier\");\n                goto fail;\n            }\n        }\n        JS_FreeCString(ctx, fmt_str);\n    }\n    if (dbuf.error) {\n        res = JS_ThrowOutOfMemory(ctx);\n    } else {\n        if (fp) {\n            len = fwrite(dbuf.buf, 1, dbuf.size, fp);\n            res = JS_NewInt32(ctx, len);\n        } else {\n            res = JS_NewStringLen(ctx, (char *)dbuf.buf, dbuf.size);\n        }\n    }\n    dbuf_free(&dbuf);\n    return res;\n\nfail:\n    dbuf_free(&dbuf);\n    return JS_EXCEPTION;\n}\n\nuint8_t *js_load_file(JSContext *ctx, size_t *pbuf_len, const char *filename)\n{\n    FILE *f;\n    uint8_t *buf;\n    size_t buf_len;\n    long lret;\n    \n    f = fopen(filename, \"rb\");\n    if (!f)\n        return NULL;\n    if (fseek(f, 0, SEEK_END) < 0)\n        goto fail;\n    lret = ftell(f);\n    if (lret < 0)\n        goto fail;\n    /* XXX: on Linux, ftell() return LONG_MAX for directories */\n    if (lret == LONG_MAX) {\n        errno = EISDIR;\n        goto fail;\n    }\n    buf_len = lret;\n    if (fseek(f, 0, SEEK_SET) < 0)\n        goto fail;\n    if (ctx)\n        buf = js_malloc(ctx, buf_len + 1);\n    else\n        buf = malloc(buf_len + 1);\n    if (!buf)\n        goto fail;\n    if (fread(buf, 1, buf_len, f) != buf_len) {\n        errno = EIO;\n        if (ctx)\n            js_free(ctx, buf);\n        else\n            free(buf);\n    fail:\n        fclose(f);\n        return NULL;\n    }\n    buf[buf_len] = '\\0';\n    fclose(f);\n    *pbuf_len = buf_len;\n    return buf;\n}\n\n/* load and evaluate a file */\nstatic JSValue js_loadScript(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    uint8_t *buf;\n    const char *filename;\n    JSValue ret;\n    size_t buf_len;\n    \n    filename = JS_ToCString(ctx, argv[0]);\n    if (!filename)\n        return JS_EXCEPTION;\n    buf = js_load_file(ctx, &buf_len, filename);\n    if (!buf) {\n        JS_ThrowReferenceError(ctx, \"could not load '%s'\", filename);\n        JS_FreeCString(ctx, filename);\n        return JS_EXCEPTION;\n    }\n    ret = JS_Eval(ctx, (char *)buf, buf_len, filename,\n                  JS_EVAL_TYPE_GLOBAL);\n    js_free(ctx, buf);\n    JS_FreeCString(ctx, filename);\n    return ret;\n}\n\n/* load a file as a UTF-8 encoded string */\nstatic JSValue js_std_loadFile(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    uint8_t *buf;\n    const char *filename;\n    JSValue ret;\n    size_t buf_len;\n    \n    filename = JS_ToCString(ctx, argv[0]);\n    if (!filename)\n        return JS_EXCEPTION;\n    buf = js_load_file(ctx, &buf_len, filename);\n    JS_FreeCString(ctx, filename);\n    if (!buf)\n        return JS_NULL;\n    ret = JS_NewStringLen(ctx, (char *)buf, buf_len);\n    js_free(ctx, buf);\n    return ret;\n}\n\ntypedef JSModuleDef *(JSInitModuleFunc)(JSContext *ctx,\n                                        const char *module_name);\n\n\n#if defined(_WIN32)\nstatic JSModuleDef *js_module_loader_so(JSContext *ctx,\n                                        const char *module_name)\n{\n    JS_ThrowReferenceError(ctx, \"shared library modules are not supported yet\");\n    return NULL;\n}\n#else\nstatic JSModuleDef *js_module_loader_so(JSContext *ctx,\n                                        const char *module_name)\n{\n    JSModuleDef *m;\n    void *hd;\n    JSInitModuleFunc *init;\n    char *filename;\n    \n    if (!strchr(module_name, '/')) {\n        /* must add a '/' so that the DLL is not searched in the\n           system library paths */\n        filename = js_malloc(ctx, strlen(module_name) + 2 + 1);\n        if (!filename)\n            return NULL;\n        strcpy(filename, \"./\");\n        strcpy(filename + 2, module_name);\n    } else {\n        filename = (char *)module_name;\n    }\n    \n    /* C module */\n    hd = dlopen(filename, RTLD_NOW | RTLD_LOCAL);\n    if (filename != module_name)\n        js_free(ctx, filename);\n    if (!hd) {\n        JS_ThrowReferenceError(ctx, \"could not load module filename '%s' as shared library\",\n                               module_name);\n        goto fail;\n    }\n\n    init = dlsym(hd, \"js_init_module\");\n    if (!init) {\n        JS_ThrowReferenceError(ctx, \"could not load module filename '%s': js_init_module not found\",\n                               module_name);\n        goto fail;\n    }\n\n    m = init(ctx, module_name);\n    if (!m) {\n        JS_ThrowReferenceError(ctx, \"could not load module filename '%s': initialization error\",\n                               module_name);\n    fail:\n        if (hd)\n            dlclose(hd);\n        return NULL;\n    }\n    return m;\n}\n#endif /* !_WIN32 */\n\nint js_module_set_import_meta(JSContext *ctx, JSValueConst func_val,\n                              JS_BOOL use_realpath, JS_BOOL is_main)\n{\n    JSModuleDef *m;\n    char buf[PATH_MAX + 16];\n    JSValue meta_obj;\n    JSAtom module_name_atom;\n    const char *module_name;\n    \n    assert(JS_VALUE_GET_TAG(func_val) == JS_TAG_MODULE);\n    m = JS_VALUE_GET_PTR(func_val);\n\n    module_name_atom = JS_GetModuleName(ctx, m);\n    module_name = JS_AtomToCString(ctx, module_name_atom);\n    JS_FreeAtom(ctx, module_name_atom);\n    if (!module_name)\n        return -1;\n    if (!strchr(module_name, ':')) {\n        strcpy(buf, \"file://\");\n#if !defined(_WIN32)\n        /* realpath() cannot be used with modules compiled with qjsc\n           because the corresponding module source code is not\n           necessarily present */\n        if (use_realpath) {\n            char *res = realpath(module_name, buf + strlen(buf));\n            if (!res) {\n                JS_ThrowTypeError(ctx, \"realpath failure\");\n                JS_FreeCString(ctx, module_name);\n                return -1;\n            }\n        } else\n#endif\n        {\n            pstrcat(buf, sizeof(buf), module_name);\n        }\n    } else {\n        pstrcpy(buf, sizeof(buf), module_name);\n    }\n    JS_FreeCString(ctx, module_name);\n    \n    meta_obj = JS_GetImportMeta(ctx, m);\n    if (JS_IsException(meta_obj))\n        return -1;\n    JS_DefinePropertyValueStr(ctx, meta_obj, \"url\",\n                              JS_NewString(ctx, buf),\n                              JS_PROP_C_W_E);\n    JS_DefinePropertyValueStr(ctx, meta_obj, \"main\",\n                              JS_NewBool(ctx, is_main),\n                              JS_PROP_C_W_E);\n    JS_FreeValue(ctx, meta_obj);\n    return 0;\n}\n\nJSModuleDef *js_module_loader(JSContext *ctx,\n                              const char *module_name, void *opaque)\n{\n    JSModuleDef *m;\n\n    if (has_suffix(module_name, \".so\")) {\n        m = js_module_loader_so(ctx, module_name);\n    } else {\n        size_t buf_len;\n        uint8_t *buf;\n        JSValue func_val;\n    \n        buf = js_load_file(ctx, &buf_len, module_name);\n        if (!buf) {\n            JS_ThrowReferenceError(ctx, \"could not load module filename '%s'\",\n                                   module_name);\n            return NULL;\n        }\n        \n        /* compile the module */\n        func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name,\n                           JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);\n        js_free(ctx, buf);\n        if (JS_IsException(func_val))\n            return NULL;\n        /* XXX: could propagate the exception */\n        js_module_set_import_meta(ctx, func_val, TRUE, FALSE);\n        /* the module is already referenced, so we must free it */\n        m = JS_VALUE_GET_PTR(func_val);\n        JS_FreeValue(ctx, func_val);\n    }\n    return m;\n}\n\nstatic JSValue js_std_exit(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    int status;\n    if (JS_ToInt32(ctx, &status, argv[0]))\n        status = -1;\n    exit(status);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_std_getenv(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    const char *name, *str;\n    name = JS_ToCString(ctx, argv[0]);\n    if (!name)\n        return JS_EXCEPTION;\n    str = getenv(name);\n    JS_FreeCString(ctx, name);\n    if (!str)\n        return JS_UNDEFINED;\n    else\n        return JS_NewString(ctx, str);\n}\n\n#if defined(_WIN32)\nstatic void setenv(const char *name, const char *value, int overwrite)\n{\n    char *str;\n    size_t name_len, value_len;\n    name_len = strlen(name);\n    value_len = strlen(value);\n    str = malloc(name_len + 1 + value_len + 1);\n    memcpy(str, name, name_len);\n    str[name_len] = '=';\n    memcpy(str + name_len + 1, value, value_len);\n    str[name_len + 1 + value_len] = '\\0';\n    _putenv(str);\n    free(str);\n}\n\nstatic void unsetenv(const char *name)\n{\n    setenv(name, \"\", TRUE);\n}\n#endif /* _WIN32 */\n\nstatic JSValue js_std_setenv(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    const char *name, *value;\n    name = JS_ToCString(ctx, argv[0]);\n    if (!name)\n        return JS_EXCEPTION;\n    value = JS_ToCString(ctx, argv[1]);\n    if (!value) {\n        JS_FreeCString(ctx, name);\n        return JS_EXCEPTION;\n    }\n    setenv(name, value, TRUE);\n    JS_FreeCString(ctx, name);\n    JS_FreeCString(ctx, value);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_std_unsetenv(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    const char *name;\n    name = JS_ToCString(ctx, argv[0]);\n    if (!name)\n        return JS_EXCEPTION;\n    unsetenv(name);\n    JS_FreeCString(ctx, name);\n    return JS_UNDEFINED;\n}\n\n/* return an object containing the list of the available environment\n   variables. */\nstatic JSValue js_std_getenviron(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    char **envp;\n    const char *name, *p, *value;\n    JSValue obj;\n    uint32_t idx;\n    size_t name_len;\n    JSAtom atom;\n    int ret;\n\n    obj = JS_NewObject(ctx);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    envp = environ;\n    for(idx = 0; envp[idx] != NULL; idx++) {\n        name = envp[idx];\n        p = strchr(name, '=');\n        name_len = p - name;\n        if (!p)\n            continue;\n        value = p + 1;\n        atom = JS_NewAtomLen(ctx, name, name_len);\n        if (atom == JS_ATOM_NULL)\n            goto fail;\n        ret = JS_DefinePropertyValue(ctx, obj, atom, JS_NewString(ctx, value),\n                                     JS_PROP_C_W_E);\n        JS_FreeAtom(ctx, atom);\n        if (ret < 0)\n            goto fail;\n    }\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_std_gc(JSContext *ctx, JSValueConst this_val,\n                         int argc, JSValueConst *argv)\n{\n    JS_RunGC(JS_GetRuntime(ctx));\n    return JS_UNDEFINED;\n}\n\nstatic int interrupt_handler(JSRuntime *rt, void *opaque)\n{\n    return (os_pending_signals >> SIGINT) & 1;\n}\n\nstatic int get_bool_option(JSContext *ctx, BOOL *pbool,\n                           JSValueConst obj,\n                           const char *option)\n{\n    JSValue val;\n    val = JS_GetPropertyStr(ctx, obj, option);\n    if (JS_IsException(val))\n        return -1;\n    if (!JS_IsUndefined(val)) {\n        *pbool = JS_ToBool(ctx, val);\n    }\n    JS_FreeValue(ctx, val);\n    return 0;\n}\n\nstatic JSValue js_evalScript(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    JSRuntime *rt = JS_GetRuntime(ctx);\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    const char *str;\n    size_t len;\n    JSValue ret;\n    JSValueConst options_obj;\n    BOOL backtrace_barrier = FALSE;\n    int flags;\n    \n    if (argc >= 2) {\n        options_obj = argv[1];\n        if (get_bool_option(ctx, &backtrace_barrier, options_obj,\n                            \"backtrace_barrier\"))\n            return JS_EXCEPTION;\n    }\n\n    str = JS_ToCStringLen(ctx, &len, argv[0]);\n    if (!str)\n        return JS_EXCEPTION;\n    if (!ts->recv_pipe && ++ts->eval_script_recurse == 1) {\n        /* install the interrupt handler */\n        JS_SetInterruptHandler(JS_GetRuntime(ctx), interrupt_handler, NULL);\n    }\n    flags = JS_EVAL_TYPE_GLOBAL; \n    if (backtrace_barrier)\n        flags |= JS_EVAL_FLAG_BACKTRACE_BARRIER;\n    ret = JS_Eval(ctx, str, len, \"<evalScript>\", flags);\n    JS_FreeCString(ctx, str);\n    if (!ts->recv_pipe && --ts->eval_script_recurse == 0) {\n        /* remove the interrupt handler */\n        JS_SetInterruptHandler(JS_GetRuntime(ctx), NULL, NULL);\n        os_pending_signals &= ~((uint64_t)1 << SIGINT);\n        /* convert the uncatchable \"interrupted\" error into a normal error\n           so that it can be caught by the REPL */\n        if (JS_IsException(ret))\n            JS_ResetUncatchableError(ctx);\n    }\n    return ret;\n}\n\nstatic JSClassID js_std_file_class_id;\n\ntypedef struct {\n    FILE *f;\n    BOOL close_in_finalizer;\n    BOOL is_popen;\n} JSSTDFile;\n\nstatic void js_std_file_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSSTDFile *s = JS_GetOpaque(val, js_std_file_class_id);\n    if (s) {\n        if (s->f && s->close_in_finalizer) {\n            if (s->is_popen)\n                pclose(s->f);\n            else\n                fclose(s->f);\n        }\n        js_free_rt(rt, s);\n    }\n}\n\nstatic ssize_t js_get_errno(ssize_t ret)\n{\n    if (ret == -1)\n        ret = -errno;\n    return ret;\n}\n\nstatic JSValue js_std_strerror(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    int err;\n    if (JS_ToInt32(ctx, &err, argv[0]))\n        return JS_EXCEPTION;\n    return JS_NewString(ctx, strerror(err));\n}\n\nstatic JSValue js_std_parseExtJSON(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    JSValue obj;\n    const char *str;\n    size_t len;\n\n    str = JS_ToCStringLen(ctx, &len, argv[0]);\n    if (!str)\n        return JS_EXCEPTION;\n    obj = JS_ParseJSON2(ctx, str, len, \"<input>\", JS_PARSE_JSON_EXT);\n    JS_FreeCString(ctx, str);\n    return obj;\n}\n\nstatic JSValue js_new_std_file(JSContext *ctx, FILE *f,\n                               BOOL close_in_finalizer,\n                               BOOL is_popen)\n{\n    JSSTDFile *s;\n    JSValue obj;\n    obj = JS_NewObjectClass(ctx, js_std_file_class_id);\n    if (JS_IsException(obj))\n        return obj;\n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s) {\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    s->close_in_finalizer = close_in_finalizer;\n    s->is_popen = is_popen;\n    s->f = f;\n    JS_SetOpaque(obj, s);\n    return obj;\n}\n\nstatic void js_set_error_object(JSContext *ctx, JSValue obj, int err)\n{\n    if (!JS_IsUndefined(obj)) {\n        JS_SetPropertyStr(ctx, obj, \"errno\", JS_NewInt32(ctx, err));\n    }\n}\n\nstatic JSValue js_std_open(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    const char *filename, *mode = NULL;\n    FILE *f;\n    int err;\n    \n    filename = JS_ToCString(ctx, argv[0]);\n    if (!filename)\n        goto fail;\n    mode = JS_ToCString(ctx, argv[1]);\n    if (!mode)\n        goto fail;\n    if (mode[strspn(mode, \"rwa+b\")] != '\\0') {\n        JS_ThrowTypeError(ctx, \"invalid file mode\");\n        goto fail;\n    }\n\n    f = fopen(filename, mode);\n    if (!f)\n        err = errno;\n    else\n        err = 0;\n    if (argc >= 3)\n        js_set_error_object(ctx, argv[2], err);\n    JS_FreeCString(ctx, filename);\n    JS_FreeCString(ctx, mode);\n    if (!f)\n        return JS_NULL;\n    return js_new_std_file(ctx, f, TRUE, FALSE);\n fail:\n    JS_FreeCString(ctx, filename);\n    JS_FreeCString(ctx, mode);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_std_popen(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv)\n{\n    const char *filename, *mode = NULL;\n    FILE *f;\n    int err;\n    \n    filename = JS_ToCString(ctx, argv[0]);\n    if (!filename)\n        goto fail;\n    mode = JS_ToCString(ctx, argv[1]);\n    if (!mode)\n        goto fail;\n    if (mode[strspn(mode, \"rw\")] != '\\0') {\n        JS_ThrowTypeError(ctx, \"invalid file mode\");\n        goto fail;\n    }\n\n    f = popen(filename, mode);\n    if (!f)\n        err = errno;\n    else\n        err = 0;\n    if (argc >= 3)\n        js_set_error_object(ctx, argv[2], err);\n    JS_FreeCString(ctx, filename);\n    JS_FreeCString(ctx, mode);\n    if (!f)\n        return JS_NULL;\n    return js_new_std_file(ctx, f, TRUE, TRUE);\n fail:\n    JS_FreeCString(ctx, filename);\n    JS_FreeCString(ctx, mode);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_std_fdopen(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    const char *mode;\n    FILE *f;\n    int fd, err;\n\n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    mode = JS_ToCString(ctx, argv[1]);\n    if (!mode)\n        goto fail;\n    if (mode[strspn(mode, \"rwa+\")] != '\\0') {\n        JS_ThrowTypeError(ctx, \"invalid file mode\");\n        goto fail;\n    }\n\n    f = fdopen(fd, mode);\n    if (!f)\n        err = errno;\n    else\n        err = 0;\n    if (argc >= 3)\n        js_set_error_object(ctx, argv[2], err);\n    JS_FreeCString(ctx, mode);\n    if (!f)\n        return JS_NULL;\n    return js_new_std_file(ctx, f, TRUE, FALSE);\n fail:\n    JS_FreeCString(ctx, mode);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_std_tmpfile(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    FILE *f;\n    f = tmpfile();\n    if (argc >= 1)\n        js_set_error_object(ctx, argv[0], f ? 0 : errno);\n    if (!f)\n        return JS_NULL;\n    return js_new_std_file(ctx, f, TRUE, FALSE);\n}\n\nstatic JSValue js_std_sprintf(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv)\n{\n    return js_printf_internal(ctx, argc, argv, NULL);\n}\n\nstatic JSValue js_std_printf(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    return js_printf_internal(ctx, argc, argv, stdout);\n}\n\nstatic FILE *js_std_file_get(JSContext *ctx, JSValueConst obj)\n{\n    JSSTDFile *s = JS_GetOpaque2(ctx, obj, js_std_file_class_id);\n    if (!s)\n        return NULL;\n    if (!s->f) {\n        JS_ThrowTypeError(ctx, \"invalid file handle\");\n        return NULL;\n    }\n    return s->f;\n}\n\nstatic JSValue js_std_file_puts(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv, int magic)\n{\n    FILE *f;\n    int i;\n    const char *str;\n    size_t len;\n\n    if (magic == 0) {\n        f = stdout;\n    } else {\n        f = js_std_file_get(ctx, this_val);\n        if (!f)\n            return JS_EXCEPTION;\n    }\n    \n    for(i = 0; i < argc; i++) {\n        str = JS_ToCStringLen(ctx, &len, argv[i]);\n        if (!str)\n            return JS_EXCEPTION;\n        fwrite(str, 1, len, f);\n        JS_FreeCString(ctx, str);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_std_file_close(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSSTDFile *s = JS_GetOpaque2(ctx, this_val, js_std_file_class_id);\n    int err;\n    if (!s)\n        return JS_EXCEPTION;\n    if (!s->f)\n        return JS_ThrowTypeError(ctx, \"invalid file handle\");\n    if (s->is_popen)\n        err = js_get_errno(pclose(s->f));\n    else\n        err = js_get_errno(fclose(s->f));\n    s->f = NULL;\n    return JS_NewInt32(ctx, err);\n}\n\nstatic JSValue js_std_file_printf(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    if (!f)\n        return JS_EXCEPTION;\n    return js_printf_internal(ctx, argc, argv, f);\n}\n\nstatic JSValue js_std_file_flush(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    if (!f)\n        return JS_EXCEPTION;\n    fflush(f);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_std_file_tell(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv, int is_bigint)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    int64_t pos;\n    if (!f)\n        return JS_EXCEPTION;\n#if defined(__linux__)\n    pos = ftello(f);\n#else\n    pos = ftell(f);\n#endif\n    if (is_bigint)\n        return JS_NewBigInt64(ctx, pos);\n    else\n        return JS_NewInt64(ctx, pos);\n}\n\nstatic JSValue js_std_file_seek(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    int64_t pos;\n    int whence, ret;\n    if (!f)\n        return JS_EXCEPTION;\n    if (JS_ToInt64Ext(ctx, &pos, argv[0]))\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &whence, argv[1]))\n        return JS_EXCEPTION;\n#if defined(__linux__)\n    ret = fseeko(f, pos, whence);\n#else\n    ret = fseek(f, pos, whence);\n#endif\n    if (ret < 0)\n        ret = -errno;\n    return JS_NewInt32(ctx, ret);\n}\n\nstatic JSValue js_std_file_eof(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    if (!f)\n        return JS_EXCEPTION;\n    return JS_NewBool(ctx, feof(f));\n}\n\nstatic JSValue js_std_file_error(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    if (!f)\n        return JS_EXCEPTION;\n    return JS_NewBool(ctx, ferror(f));\n}\n\nstatic JSValue js_std_file_clearerr(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    if (!f)\n        return JS_EXCEPTION;\n    clearerr(f);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_std_file_fileno(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    if (!f)\n        return JS_EXCEPTION;\n    return JS_NewInt32(ctx, fileno(f));\n}\n\nstatic JSValue js_std_file_read_write(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv, int magic)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    uint64_t pos, len;\n    size_t size, ret;\n    uint8_t *buf;\n    \n    if (!f)\n        return JS_EXCEPTION;\n    if (JS_ToIndex(ctx, &pos, argv[1]))\n        return JS_EXCEPTION;\n    if (JS_ToIndex(ctx, &len, argv[2]))\n        return JS_EXCEPTION;\n    buf = JS_GetArrayBuffer(ctx, &size, argv[0]);\n    if (!buf)\n        return JS_EXCEPTION;\n    if (pos + len > size)\n        return JS_ThrowRangeError(ctx, \"read/write array buffer overflow\");\n    if (magic)\n        ret = fwrite(buf + pos, 1, len, f);\n    else\n        ret = fread(buf + pos, 1, len, f);\n    return JS_NewInt64(ctx, ret);\n}\n\n/* XXX: could use less memory and go faster */\nstatic JSValue js_std_file_getline(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    int c;\n    DynBuf dbuf;\n    JSValue obj;\n    \n    if (!f)\n        return JS_EXCEPTION;\n\n    js_std_dbuf_init(ctx, &dbuf);\n    for(;;) {\n        c = fgetc(f);\n        if (c == EOF) {\n            if (dbuf.size == 0) {\n                /* EOF */\n                dbuf_free(&dbuf);\n                return JS_NULL;\n            } else {\n                break;\n            }\n        }\n        if (c == '\\n')\n            break;\n        if (dbuf_putc(&dbuf, c)) {\n            dbuf_free(&dbuf);\n            return JS_ThrowOutOfMemory(ctx);\n        }\n    }\n    obj = JS_NewStringLen(ctx, (const char *)dbuf.buf, dbuf.size);\n    dbuf_free(&dbuf);\n    return obj;\n}\n\n/* XXX: could use less memory and go faster */\nstatic JSValue js_std_file_readAsString(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    int c;\n    DynBuf dbuf;\n    JSValue obj;\n    uint64_t max_size64;\n    size_t max_size;\n    JSValueConst max_size_val;\n    \n    if (!f)\n        return JS_EXCEPTION;\n\n    if (argc >= 1)\n        max_size_val = argv[0];\n    else\n        max_size_val = JS_UNDEFINED;\n    max_size = (size_t)-1;\n    if (!JS_IsUndefined(max_size_val)) {\n        if (JS_ToIndex(ctx, &max_size64, max_size_val))\n            return JS_EXCEPTION;\n        if (max_size64 < max_size)\n            max_size = max_size64;\n    }\n\n    js_std_dbuf_init(ctx, &dbuf);\n    while (max_size != 0) {\n        c = fgetc(f);\n        if (c == EOF)\n            break;\n        if (dbuf_putc(&dbuf, c)) {\n            dbuf_free(&dbuf);\n            return JS_EXCEPTION;\n        }\n        max_size--;\n    }\n    obj = JS_NewStringLen(ctx, (const char *)dbuf.buf, dbuf.size);\n    dbuf_free(&dbuf);\n    return obj;\n}\n\nstatic JSValue js_std_file_getByte(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    if (!f)\n        return JS_EXCEPTION;\n    return JS_NewInt32(ctx, fgetc(f));\n}\n\nstatic JSValue js_std_file_putByte(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    FILE *f = js_std_file_get(ctx, this_val);\n    int c;\n    if (!f)\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &c, argv[0]))\n        return JS_EXCEPTION;\n    c = fputc(c, f);\n    return JS_NewInt32(ctx, c);\n}\n\n/* urlGet */\n\n#define URL_GET_PROGRAM \"curl -s -i\"\n#define URL_GET_BUF_SIZE 4096\n\nstatic int http_get_header_line(FILE *f, char *buf, size_t buf_size,\n                                DynBuf *dbuf)\n{\n    int c;\n    char *p;\n    \n    p = buf;\n    for(;;) {\n        c = fgetc(f);\n        if (c < 0)\n            return -1;\n        if ((p - buf) < buf_size - 1)\n            *p++ = c;\n        if (dbuf)\n            dbuf_putc(dbuf, c);\n        if (c == '\\n')\n            break;\n    }\n    *p = '\\0';\n    return 0;\n}\n\nstatic int http_get_status(const char *buf)\n{\n    const char *p = buf;\n    while (*p != ' ' && *p != '\\0')\n        p++;\n    if (*p != ' ')\n        return 0;\n    while (*p == ' ')\n        p++;\n    return atoi(p);\n}\n\nstatic JSValue js_std_urlGet(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    const char *url;\n    DynBuf cmd_buf;\n    DynBuf data_buf_s, *data_buf = &data_buf_s;\n    DynBuf header_buf_s, *header_buf = &header_buf_s;\n    char *buf; \n    size_t i, len;\n    int c, status;\n    JSValue response = JS_UNDEFINED, ret_obj;\n    JSValueConst options_obj;\n    FILE *f;\n    BOOL binary_flag, full_flag;\n    \n    url = JS_ToCString(ctx, argv[0]);\n    if (!url)\n        return JS_EXCEPTION;\n    \n    binary_flag = FALSE;\n    full_flag = FALSE;\n    \n    if (argc >= 2) {\n        options_obj = argv[1];\n\n        if (get_bool_option(ctx, &binary_flag, options_obj, \"binary\"))\n            goto fail_obj;\n\n        if (get_bool_option(ctx, &full_flag, options_obj, \"full\")) {\n        fail_obj:\n            JS_FreeCString(ctx, url);\n            return JS_EXCEPTION;\n        }\n    }\n    \n    js_std_dbuf_init(ctx, &cmd_buf);\n    dbuf_printf(&cmd_buf, \"%s ''\", URL_GET_PROGRAM);\n    len = strlen(url);\n    for(i = 0; i < len; i++) {\n        c = url[i];\n        if (c == '\\'' || c == '\\\\')\n            dbuf_putc(&cmd_buf, '\\\\');\n        dbuf_putc(&cmd_buf, c);\n    }\n    JS_FreeCString(ctx, url);\n    dbuf_putstr(&cmd_buf, \"''\");\n    dbuf_putc(&cmd_buf, '\\0');\n    if (dbuf_error(&cmd_buf)) {\n        dbuf_free(&cmd_buf);\n        return JS_EXCEPTION;\n    }\n    //    printf(\"%s\\n\", (char *)cmd_buf.buf);\n    f = popen((char *)cmd_buf.buf, \"r\");\n    dbuf_free(&cmd_buf);\n    if (!f) {\n        return JS_ThrowTypeError(ctx, \"could not start curl\");\n    }\n\n    js_std_dbuf_init(ctx, data_buf);\n    js_std_dbuf_init(ctx, header_buf);\n    \n    buf = js_malloc(ctx, URL_GET_BUF_SIZE);\n    if (!buf)\n        goto fail;\n\n    /* get the HTTP status */\n    if (http_get_header_line(f, buf, URL_GET_BUF_SIZE, NULL) < 0) {\n        status = 0;\n        goto bad_header;\n    }\n    status = http_get_status(buf);\n    if (!full_flag && !(status >= 200 && status <= 299)) {\n        goto bad_header;\n    }\n    \n    /* wait until there is an empty line */\n    for(;;) {\n        if (http_get_header_line(f, buf, URL_GET_BUF_SIZE, header_buf) < 0) {\n        bad_header:\n            response = JS_NULL;\n            goto done;\n        }\n        if (!strcmp(buf, \"\\r\\n\"))\n            break;\n    }\n    if (dbuf_error(header_buf))\n        goto fail;\n    header_buf->size -= 2; /* remove the trailing CRLF */\n\n    /* download the data */\n    for(;;) {\n        len = fread(buf, 1, URL_GET_BUF_SIZE, f);\n        if (len == 0)\n            break;\n        dbuf_put(data_buf, (uint8_t *)buf, len);\n    }\n    if (dbuf_error(data_buf))\n        goto fail;\n    if (binary_flag) {\n        response = JS_NewArrayBufferCopy(ctx,\n                                         data_buf->buf, data_buf->size);\n    } else {\n        response = JS_NewStringLen(ctx, (char *)data_buf->buf, data_buf->size);\n    }\n    if (JS_IsException(response))\n        goto fail;\n done:\n    js_free(ctx, buf);\n    buf = NULL;\n    pclose(f);\n    f = NULL;\n    dbuf_free(data_buf);\n    data_buf = NULL;\n\n    if (full_flag) {\n        ret_obj = JS_NewObject(ctx);\n        if (JS_IsException(ret_obj))\n            goto fail;\n        JS_DefinePropertyValueStr(ctx, ret_obj, \"response\",\n                                  response,\n                                  JS_PROP_C_W_E);\n        if (!JS_IsNull(response)) {\n            JS_DefinePropertyValueStr(ctx, ret_obj, \"responseHeaders\",\n                                      JS_NewStringLen(ctx, (char *)header_buf->buf,\n                                                      header_buf->size),\n                                      JS_PROP_C_W_E);\n            JS_DefinePropertyValueStr(ctx, ret_obj, \"status\",\n                                      JS_NewInt32(ctx, status),\n                                      JS_PROP_C_W_E);\n        }\n    } else {\n        ret_obj = response;\n    }\n    dbuf_free(header_buf);\n    return ret_obj;\n fail:\n    if (f)\n        pclose(f);\n    js_free(ctx, buf);\n    if (data_buf)\n        dbuf_free(data_buf);\n    if (header_buf)\n        dbuf_free(header_buf);\n    JS_FreeValue(ctx, response);\n    return JS_EXCEPTION;\n}\n\nstatic JSClassDef js_std_file_class = {\n    \"FILE\",\n    .finalizer = js_std_file_finalizer,\n}; \n\nstatic const JSCFunctionListEntry js_std_error_props[] = {\n    /* various errno values */\n#define DEF(x) JS_PROP_INT32_DEF(#x, x, JS_PROP_CONFIGURABLE )\n    DEF(EINVAL),\n    DEF(EIO),\n    DEF(EACCES),\n    DEF(EEXIST),\n    DEF(ENOSPC),\n    DEF(ENOSYS),\n    DEF(EBUSY),\n    DEF(ENOENT),\n    DEF(EPERM),\n    DEF(EPIPE),\n    DEF(EBADF),\n#undef DEF\n};\n\nstatic const JSCFunctionListEntry js_std_funcs[] = {\n    JS_CFUNC_DEF(\"exit\", 1, js_std_exit ),\n    JS_CFUNC_DEF(\"gc\", 0, js_std_gc ),\n    JS_CFUNC_DEF(\"evalScript\", 1, js_evalScript ),\n    JS_CFUNC_DEF(\"loadScript\", 1, js_loadScript ),\n    JS_CFUNC_DEF(\"getenv\", 1, js_std_getenv ),\n    JS_CFUNC_DEF(\"setenv\", 1, js_std_setenv ),\n    JS_CFUNC_DEF(\"unsetenv\", 1, js_std_unsetenv ),\n    JS_CFUNC_DEF(\"getenviron\", 1, js_std_getenviron ),\n    JS_CFUNC_DEF(\"urlGet\", 1, js_std_urlGet ),\n    JS_CFUNC_DEF(\"loadFile\", 1, js_std_loadFile ),\n    JS_CFUNC_DEF(\"strerror\", 1, js_std_strerror ),\n    JS_CFUNC_DEF(\"parseExtJSON\", 1, js_std_parseExtJSON ),\n    \n    /* FILE I/O */\n    JS_CFUNC_DEF(\"open\", 2, js_std_open ),\n    JS_CFUNC_DEF(\"popen\", 2, js_std_popen ),\n    JS_CFUNC_DEF(\"fdopen\", 2, js_std_fdopen ),\n    JS_CFUNC_DEF(\"tmpfile\", 0, js_std_tmpfile ),\n    JS_CFUNC_MAGIC_DEF(\"puts\", 1, js_std_file_puts, 0 ),\n    JS_CFUNC_DEF(\"printf\", 1, js_std_printf ),\n    JS_CFUNC_DEF(\"sprintf\", 1, js_std_sprintf ),\n    JS_PROP_INT32_DEF(\"SEEK_SET\", SEEK_SET, JS_PROP_CONFIGURABLE ),\n    JS_PROP_INT32_DEF(\"SEEK_CUR\", SEEK_CUR, JS_PROP_CONFIGURABLE ),\n    JS_PROP_INT32_DEF(\"SEEK_END\", SEEK_END, JS_PROP_CONFIGURABLE ),\n    JS_OBJECT_DEF(\"Error\", js_std_error_props, countof(js_std_error_props), JS_PROP_CONFIGURABLE),\n};\n    \nstatic const JSCFunctionListEntry js_std_file_proto_funcs[] = {\n    JS_CFUNC_DEF(\"close\", 0, js_std_file_close ),\n    JS_CFUNC_MAGIC_DEF(\"puts\", 1, js_std_file_puts, 1 ),\n    JS_CFUNC_DEF(\"printf\", 1, js_std_file_printf ),\n    JS_CFUNC_DEF(\"flush\", 0, js_std_file_flush ),\n    JS_CFUNC_MAGIC_DEF(\"tell\", 0, js_std_file_tell, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"tello\", 0, js_std_file_tell, 1 ),\n    JS_CFUNC_DEF(\"seek\", 2, js_std_file_seek ),\n    JS_CFUNC_DEF(\"eof\", 0, js_std_file_eof ),\n    JS_CFUNC_DEF(\"fileno\", 0, js_std_file_fileno ),\n    JS_CFUNC_DEF(\"error\", 0, js_std_file_error ),\n    JS_CFUNC_DEF(\"clearerr\", 0, js_std_file_clearerr ),\n    JS_CFUNC_MAGIC_DEF(\"read\", 3, js_std_file_read_write, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"write\", 3, js_std_file_read_write, 1 ),\n    JS_CFUNC_DEF(\"getline\", 0, js_std_file_getline ),\n    JS_CFUNC_DEF(\"readAsString\", 0, js_std_file_readAsString ),\n    JS_CFUNC_DEF(\"getByte\", 0, js_std_file_getByte ),\n    JS_CFUNC_DEF(\"putByte\", 1, js_std_file_putByte ),\n    /* setvbuf, ...  */\n};\n\nstatic int js_std_init(JSContext *ctx, JSModuleDef *m)\n{\n    JSValue proto;\n    \n    /* FILE class */\n    /* the class ID is created once */\n    JS_NewClassID(&js_std_file_class_id);\n    /* the class is created once per runtime */\n    JS_NewClass(JS_GetRuntime(ctx), js_std_file_class_id, &js_std_file_class);\n    proto = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, proto, js_std_file_proto_funcs,\n                               countof(js_std_file_proto_funcs));\n    JS_SetClassProto(ctx, js_std_file_class_id, proto);\n\n    JS_SetModuleExportList(ctx, m, js_std_funcs,\n                           countof(js_std_funcs));\n    JS_SetModuleExport(ctx, m, \"in\", js_new_std_file(ctx, stdin, FALSE, FALSE));\n    JS_SetModuleExport(ctx, m, \"out\", js_new_std_file(ctx, stdout, FALSE, FALSE));\n    JS_SetModuleExport(ctx, m, \"err\", js_new_std_file(ctx, stderr, FALSE, FALSE));\n    return 0;\n}\n\nJSModuleDef *js_init_module_std(JSContext *ctx, const char *module_name)\n{\n    JSModuleDef *m;\n    m = JS_NewCModule(ctx, module_name, js_std_init);\n    if (!m)\n        return NULL;\n    JS_AddModuleExportList(ctx, m, js_std_funcs, countof(js_std_funcs));\n    JS_AddModuleExport(ctx, m, \"in\");\n    JS_AddModuleExport(ctx, m, \"out\");\n    JS_AddModuleExport(ctx, m, \"err\");\n    return m;\n}\n\n/**********************************************************/\n/* 'os' object */\n\nstatic JSValue js_os_open(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv)\n{\n    const char *filename;\n    int flags, mode, ret;\n\n    filename = JS_ToCString(ctx, argv[0]);\n    if (!filename)\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &flags, argv[1]))\n        goto fail;\n    if (argc >= 3 && !JS_IsUndefined(argv[2])) {\n        if (JS_ToInt32(ctx, &mode, argv[2])) {\n        fail:\n            JS_FreeCString(ctx, filename);\n            return JS_EXCEPTION;\n        }\n    } else {\n        mode = 0666;\n    }\n#if defined(_WIN32)\n    /* force binary mode by default */\n    if (!(flags & O_TEXT))\n        flags |= O_BINARY;\n#endif\n    ret = js_get_errno(open(filename, flags, mode));\n    JS_FreeCString(ctx, filename);\n    return JS_NewInt32(ctx, ret);\n}\n\nstatic JSValue js_os_close(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    int fd, ret;\n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    ret = js_get_errno(close(fd));\n    return JS_NewInt32(ctx, ret);\n}\n\nstatic JSValue js_os_seek(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv)\n{\n    int fd, whence;\n    int64_t pos, ret;\n    BOOL is_bigint;\n    \n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    is_bigint = JS_IsBigInt(ctx, argv[1]);\n    if (JS_ToInt64Ext(ctx, &pos, argv[1]))\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &whence, argv[2]))\n        return JS_EXCEPTION;\n    ret = lseek(fd, pos, whence);\n    if (ret == -1)\n        ret = -errno;\n    if (is_bigint)\n        return JS_NewBigInt64(ctx, ret);\n    else\n        return JS_NewInt64(ctx, ret);\n}\n\nstatic JSValue js_os_read_write(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv, int magic)\n{\n    int fd;\n    uint64_t pos, len;\n    size_t size;\n    ssize_t ret;\n    uint8_t *buf;\n    \n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    if (JS_ToIndex(ctx, &pos, argv[2]))\n        return JS_EXCEPTION;\n    if (JS_ToIndex(ctx, &len, argv[3]))\n        return JS_EXCEPTION;\n    buf = JS_GetArrayBuffer(ctx, &size, argv[1]);\n    if (!buf)\n        return JS_EXCEPTION;\n    if (pos + len > size)\n        return JS_ThrowRangeError(ctx, \"read/write array buffer overflow\");\n    if (magic)\n        ret = js_get_errno(write(fd, buf + pos, len));\n    else\n        ret = js_get_errno(read(fd, buf + pos, len));\n    return JS_NewInt64(ctx, ret);\n}\n\nstatic JSValue js_os_isatty(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv)\n{\n    int fd;\n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    return JS_NewBool(ctx, (isatty(fd) != 0));\n}\n\n#if defined(_WIN32)\nstatic JSValue js_os_ttyGetWinSize(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    int fd;\n    HANDLE handle;\n    CONSOLE_SCREEN_BUFFER_INFO info;\n    JSValue obj;\n\n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    handle = (HANDLE)_get_osfhandle(fd);\n    \n    if (!GetConsoleScreenBufferInfo(handle, &info))\n        return JS_NULL;\n    obj = JS_NewArray(ctx);\n    if (JS_IsException(obj))\n        return obj;\n    JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, info.dwSize.X), JS_PROP_C_W_E);\n    JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, info.dwSize.Y), JS_PROP_C_W_E);\n    return obj;\n}\n\n/* Windows 10 built-in VT100 emulation */\n#define __ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004\n#define __ENABLE_VIRTUAL_TERMINAL_INPUT 0x0200\n\nstatic JSValue js_os_ttySetRaw(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    int fd;\n    HANDLE handle;\n\n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    handle = (HANDLE)_get_osfhandle(fd);\n    SetConsoleMode(handle, ENABLE_WINDOW_INPUT | __ENABLE_VIRTUAL_TERMINAL_INPUT);\n    _setmode(fd, _O_BINARY);\n    if (fd == 0) {\n        handle = (HANDLE)_get_osfhandle(1); /* corresponding output */\n        SetConsoleMode(handle, ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT | __ENABLE_VIRTUAL_TERMINAL_PROCESSING);\n    }\n    return JS_UNDEFINED;\n}\n#else\nstatic JSValue js_os_ttyGetWinSize(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    int fd;\n    struct winsize ws;\n    JSValue obj;\n    \n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    if (ioctl(fd, TIOCGWINSZ, &ws) == 0 &&\n        ws.ws_col >= 4 && ws.ws_row >= 4) {\n        obj = JS_NewArray(ctx);\n        if (JS_IsException(obj))\n            return obj;\n        JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, ws.ws_col), JS_PROP_C_W_E);\n        JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, ws.ws_row), JS_PROP_C_W_E);\n        return obj;\n    } else {\n        return JS_NULL;\n    }\n}\n\nstatic struct termios oldtty;\n\nstatic void term_exit(void)\n{\n    tcsetattr(0, TCSANOW, &oldtty);\n}\n\n/* XXX: should add a way to go back to normal mode */\nstatic JSValue js_os_ttySetRaw(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    struct termios tty;\n    int fd;\n    \n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    \n    memset(&tty, 0, sizeof(tty));\n    tcgetattr(fd, &tty);\n    oldtty = tty;\n\n    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP\n                          |INLCR|IGNCR|ICRNL|IXON);\n    tty.c_oflag |= OPOST;\n    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);\n    tty.c_cflag &= ~(CSIZE|PARENB);\n    tty.c_cflag |= CS8;\n    tty.c_cc[VMIN] = 1;\n    tty.c_cc[VTIME] = 0;\n\n    tcsetattr(fd, TCSANOW, &tty);\n\n    atexit(term_exit);\n    return JS_UNDEFINED;\n}\n\n#endif /* !_WIN32 */\n\nstatic JSValue js_os_remove(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    const char *filename;\n    int ret;\n    \n    filename = JS_ToCString(ctx, argv[0]);\n    if (!filename)\n        return JS_EXCEPTION;\n#if defined(_WIN32)\n    {\n        struct stat st;\n        if (stat(filename, &st) == 0 && S_ISDIR(st.st_mode)) {\n            ret = rmdir(filename);\n        } else {\n            ret = unlink(filename);\n        }\n    }\n#else\n    ret = remove(filename);\n#endif\n    ret = js_get_errno(ret);\n    JS_FreeCString(ctx, filename);\n    return JS_NewInt32(ctx, ret);\n}\n\nstatic JSValue js_os_rename(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv)\n{\n    const char *oldpath, *newpath;\n    int ret;\n    \n    oldpath = JS_ToCString(ctx, argv[0]);\n    if (!oldpath)\n        return JS_EXCEPTION;\n    newpath = JS_ToCString(ctx, argv[1]);\n    if (!newpath) {\n        JS_FreeCString(ctx, oldpath);\n        return JS_EXCEPTION;\n    }\n    ret = js_get_errno(rename(oldpath, newpath));\n    JS_FreeCString(ctx, oldpath);\n    JS_FreeCString(ctx, newpath);\n    return JS_NewInt32(ctx, ret);\n}\n\nstatic BOOL is_main_thread(JSRuntime *rt)\n{\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    return !ts->recv_pipe;\n}\n\nstatic JSOSRWHandler *find_rh(JSThreadState *ts, int fd)\n{\n    JSOSRWHandler *rh;\n    struct list_head *el;\n\n    list_for_each(el, &ts->os_rw_handlers) {\n        rh = list_entry(el, JSOSRWHandler, link);\n        if (rh->fd == fd)\n            return rh;\n    }\n    return NULL;\n}\n\nstatic void free_rw_handler(JSRuntime *rt, JSOSRWHandler *rh)\n{\n    int i;\n    list_del(&rh->link);\n    for(i = 0; i < 2; i++) {\n        JS_FreeValueRT(rt, rh->rw_func[i]);\n    }\n    js_free_rt(rt, rh);\n}\n\nstatic JSValue js_os_setReadHandler(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv, int magic)\n{\n    JSRuntime *rt = JS_GetRuntime(ctx);\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    JSOSRWHandler *rh;\n    int fd;\n    JSValueConst func;\n    \n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    func = argv[1];\n    if (JS_IsNull(func)) {\n        rh = find_rh(ts, fd);\n        if (rh) {\n            JS_FreeValue(ctx, rh->rw_func[magic]);\n            rh->rw_func[magic] = JS_NULL;\n            if (JS_IsNull(rh->rw_func[0]) &&\n                JS_IsNull(rh->rw_func[1])) {\n                /* remove the entry */\n                free_rw_handler(JS_GetRuntime(ctx), rh);\n            }\n        }\n    } else {\n        if (!JS_IsFunction(ctx, func))\n            return JS_ThrowTypeError(ctx, \"not a function\");\n        rh = find_rh(ts, fd);\n        if (!rh) {\n            rh = js_mallocz(ctx, sizeof(*rh));\n            if (!rh)\n                return JS_EXCEPTION;\n            rh->fd = fd;\n            rh->rw_func[0] = JS_NULL;\n            rh->rw_func[1] = JS_NULL;\n            list_add_tail(&rh->link, &ts->os_rw_handlers);\n        }\n        JS_FreeValue(ctx, rh->rw_func[magic]);\n        rh->rw_func[magic] = JS_DupValue(ctx, func);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSOSSignalHandler *find_sh(JSThreadState *ts, int sig_num)\n{\n    JSOSSignalHandler *sh;\n    struct list_head *el;\n    list_for_each(el, &ts->os_signal_handlers) {\n        sh = list_entry(el, JSOSSignalHandler, link);\n        if (sh->sig_num == sig_num)\n            return sh;\n    }\n    return NULL;\n}\n\nstatic void free_sh(JSRuntime *rt, JSOSSignalHandler *sh)\n{\n    list_del(&sh->link);\n    JS_FreeValueRT(rt, sh->func);\n    js_free_rt(rt, sh);\n}\n\nstatic void os_signal_handler(int sig_num)\n{\n    os_pending_signals |= ((uint64_t)1 << sig_num);\n}\n\n#if defined(_WIN32)\ntypedef void (*sighandler_t)(int sig_num);\n#endif\n\nstatic JSValue js_os_signal(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv)\n{\n    JSRuntime *rt = JS_GetRuntime(ctx);\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    JSOSSignalHandler *sh;\n    uint32_t sig_num;\n    JSValueConst func;\n    sighandler_t handler;\n\n    if (!is_main_thread(rt))\n        return JS_ThrowTypeError(ctx, \"signal handler can only be set in the main thread\");\n    \n    if (JS_ToUint32(ctx, &sig_num, argv[0]))\n        return JS_EXCEPTION;\n    if (sig_num >= 64)\n        return JS_ThrowRangeError(ctx, \"invalid signal number\");\n    func = argv[1];\n    /* func = null: SIG_DFL, func = undefined, SIG_IGN */\n    if (JS_IsNull(func) || JS_IsUndefined(func)) {\n        sh = find_sh(ts, sig_num);\n        if (sh) {\n            free_sh(JS_GetRuntime(ctx), sh);\n        }\n        if (JS_IsNull(func))\n            handler = SIG_DFL;\n        else\n            handler = SIG_IGN;\n        signal(sig_num, handler);\n    } else {\n        if (!JS_IsFunction(ctx, func))\n            return JS_ThrowTypeError(ctx, \"not a function\");\n        sh = find_sh(ts, sig_num);\n        if (!sh) {\n            sh = js_mallocz(ctx, sizeof(*sh));\n            if (!sh)\n                return JS_EXCEPTION;\n            sh->sig_num = sig_num;\n            list_add_tail(&sh->link, &ts->os_signal_handlers);\n        }\n        JS_FreeValue(ctx, sh->func);\n        sh->func = JS_DupValue(ctx, func);\n        signal(sig_num, os_signal_handler);\n    }\n    return JS_UNDEFINED;\n}\n\n#if defined(__linux__) || defined(__APPLE__)\nstatic int64_t get_time_ms(void)\n{\n    struct timespec ts;\n    clock_gettime(CLOCK_MONOTONIC, &ts);\n    return (uint64_t)ts.tv_sec * 1000 + (ts.tv_nsec / 1000000);\n}\n#else\n/* more portable, but does not work if the date is updated */\nstatic int64_t get_time_ms(void)\n{\n    struct timeval tv;\n    gettimeofday(&tv, NULL);\n    return (int64_t)tv.tv_sec * 1000 + (tv.tv_usec / 1000);\n}\n#endif\n\nstatic void unlink_timer(JSRuntime *rt, JSOSTimer *th)\n{\n    if (th->link.prev) {\n        list_del(&th->link);\n        th->link.prev = th->link.next = NULL;\n    }\n}\n\nstatic void free_timer(JSRuntime *rt, JSOSTimer *th)\n{\n    JS_FreeValueRT(rt, th->func);\n    js_free_rt(rt, th);\n}\n\nstatic JSClassID js_os_timer_class_id;\n\nstatic void js_os_timer_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSOSTimer *th = JS_GetOpaque(val, js_os_timer_class_id);\n    if (th) {\n        th->has_object = FALSE;\n        if (!th->link.prev)\n            free_timer(rt, th);\n    }\n}\n\nstatic void js_os_timer_mark(JSRuntime *rt, JSValueConst val,\n                             JS_MarkFunc *mark_func)\n{\n    JSOSTimer *th = JS_GetOpaque(val, js_os_timer_class_id);\n    if (th) {\n        JS_MarkValue(rt, th->func, mark_func);\n    }\n}\n\nstatic JSValue js_os_setTimeout(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSRuntime *rt = JS_GetRuntime(ctx);\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    int64_t delay;\n    JSValueConst func;\n    JSOSTimer *th;\n    JSValue obj;\n\n    func = argv[0];\n    if (!JS_IsFunction(ctx, func))\n        return JS_ThrowTypeError(ctx, \"not a function\");\n    if (JS_ToInt64(ctx, &delay, argv[1]))\n        return JS_EXCEPTION;\n    obj = JS_NewObjectClass(ctx, js_os_timer_class_id);\n    if (JS_IsException(obj))\n        return obj;\n    th = js_mallocz(ctx, sizeof(*th));\n    if (!th) {\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    th->has_object = TRUE;\n    th->timeout = get_time_ms() + delay;\n    th->func = JS_DupValue(ctx, func);\n    list_add_tail(&th->link, &ts->os_timers);\n    JS_SetOpaque(obj, th);\n    return obj;\n}\n\nstatic JSValue js_os_clearTimeout(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    JSOSTimer *th = JS_GetOpaque2(ctx, argv[0], js_os_timer_class_id);\n    if (!th)\n        return JS_EXCEPTION;\n    unlink_timer(JS_GetRuntime(ctx), th);\n    return JS_UNDEFINED;\n}\n\nstatic JSClassDef js_os_timer_class = {\n    \"OSTimer\",\n    .finalizer = js_os_timer_finalizer,\n    .gc_mark = js_os_timer_mark,\n}; \n\nstatic void call_handler(JSContext *ctx, JSValueConst func)\n{\n    JSValue ret, func1;\n    /* 'func' might be destroyed when calling itself (if it frees the\n       handler), so must take extra care */\n    func1 = JS_DupValue(ctx, func);\n    ret = JS_Call(ctx, func1, JS_UNDEFINED, 0, NULL);\n    JS_FreeValue(ctx, func1);\n    if (JS_IsException(ret))\n        js_std_dump_error(ctx);\n    JS_FreeValue(ctx, ret);\n}\n\n#if defined(_WIN32)\n\nstatic int js_os_poll(JSContext *ctx)\n{\n    JSRuntime *rt = JS_GetRuntime(ctx);\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    int min_delay, console_fd;\n    int64_t cur_time, delay;\n    JSOSRWHandler *rh;\n    struct list_head *el;\n    \n    /* XXX: handle signals if useful */\n\n    if (list_empty(&ts->os_rw_handlers) && list_empty(&ts->os_timers))\n        return -1; /* no more events */\n    \n    /* XXX: only timers and basic console input are supported */\n    if (!list_empty(&ts->os_timers)) {\n        cur_time = get_time_ms();\n        min_delay = 10000;\n        list_for_each(el, &ts->os_timers) {\n            JSOSTimer *th = list_entry(el, JSOSTimer, link);\n            delay = th->timeout - cur_time;\n            if (delay <= 0) {\n                JSValue func;\n                /* the timer expired */\n                func = th->func;\n                th->func = JS_UNDEFINED;\n                unlink_timer(rt, th);\n                if (!th->has_object)\n                    free_timer(rt, th);\n                call_handler(ctx, func);\n                JS_FreeValue(ctx, func);\n                return 0;\n            } else if (delay < min_delay) {\n                min_delay = delay;\n            }\n        }\n    } else {\n        min_delay = -1;\n    }\n\n    console_fd = -1;\n    list_for_each(el, &ts->os_rw_handlers) {\n        rh = list_entry(el, JSOSRWHandler, link);\n        if (rh->fd == 0 && !JS_IsNull(rh->rw_func[0])) {\n            console_fd = rh->fd;\n            break;\n        }\n    }\n\n    if (console_fd >= 0) {\n        DWORD ti, ret;\n        HANDLE handle;\n        if (min_delay == -1)\n            ti = INFINITE;\n        else\n            ti = min_delay;\n        handle = (HANDLE)_get_osfhandle(console_fd);\n        ret = WaitForSingleObject(handle, ti);\n        if (ret == WAIT_OBJECT_0) {\n            list_for_each(el, &ts->os_rw_handlers) {\n                rh = list_entry(el, JSOSRWHandler, link);\n                if (rh->fd == console_fd && !JS_IsNull(rh->rw_func[0])) {\n                    call_handler(ctx, rh->rw_func[0]);\n                    /* must stop because the list may have been modified */\n                    break;\n                }\n            }\n        }\n    } else {\n        Sleep(min_delay);\n    }\n    return 0;\n}\n#else\n\n#ifdef USE_WORKER\n\nstatic void js_free_message(JSWorkerMessage *msg);\n\n/* return 1 if a message was handled, 0 if no message */\nstatic int handle_posted_message(JSRuntime *rt, JSContext *ctx,\n                                 JSWorkerMessageHandler *port)\n{\n    JSWorkerMessagePipe *ps = port->recv_pipe;\n    int ret;\n    struct list_head *el;\n    JSWorkerMessage *msg;\n    JSValue obj, data_obj, func, retval;\n    \n    pthread_mutex_lock(&ps->mutex);\n    if (!list_empty(&ps->msg_queue)) {\n        el = ps->msg_queue.next;\n        msg = list_entry(el, JSWorkerMessage, link);\n\n        /* remove the message from the queue */\n        list_del(&msg->link);\n\n        if (list_empty(&ps->msg_queue)) {\n            uint8_t buf[16];\n            int ret;\n            for(;;) {\n                ret = read(ps->read_fd, buf, sizeof(buf));\n                if (ret >= 0)\n                    break;\n                if (errno != EAGAIN && errno != EINTR)\n                    break;\n            }\n        }\n\n        pthread_mutex_unlock(&ps->mutex);\n\n        data_obj = JS_ReadObject(ctx, msg->data, msg->data_len,\n                                 JS_READ_OBJ_SAB | JS_READ_OBJ_REFERENCE);\n\n        js_free_message(msg);\n        \n        if (JS_IsException(data_obj))\n            goto fail;\n        obj = JS_NewObject(ctx);\n        if (JS_IsException(obj)) {\n            JS_FreeValue(ctx, data_obj);\n            goto fail;\n        }\n        JS_DefinePropertyValueStr(ctx, obj, \"data\", data_obj, JS_PROP_C_W_E);\n\n        /* 'func' might be destroyed when calling itself (if it frees the\n           handler), so must take extra care */\n        func = JS_DupValue(ctx, port->on_message_func);\n        retval = JS_Call(ctx, func, JS_UNDEFINED, 1, (JSValueConst *)&obj);\n        JS_FreeValue(ctx, obj);\n        JS_FreeValue(ctx, func);\n        if (JS_IsException(retval)) {\n        fail:\n            js_std_dump_error(ctx);\n        } else {\n            JS_FreeValue(ctx, retval);\n        }\n        ret = 1;\n    } else {\n        pthread_mutex_unlock(&ps->mutex);\n        ret = 0;\n    }\n    return ret;\n}\n#else\nstatic int handle_posted_message(JSRuntime *rt, JSContext *ctx,\n                                 JSWorkerMessageHandler *port)\n{\n    return 0;\n}\n#endif\n\nstatic int js_os_poll(JSContext *ctx)\n{\n    JSRuntime *rt = JS_GetRuntime(ctx);\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    int ret, fd_max, min_delay;\n    int64_t cur_time, delay;\n    fd_set rfds, wfds;\n    JSOSRWHandler *rh;\n    struct list_head *el;\n    struct timeval tv, *tvp;\n\n    /* only check signals in the main thread */\n    if (!ts->recv_pipe &&\n        unlikely(os_pending_signals != 0)) {\n        JSOSSignalHandler *sh;\n        uint64_t mask;\n        \n        list_for_each(el, &ts->os_signal_handlers) {\n            sh = list_entry(el, JSOSSignalHandler, link);\n            mask = (uint64_t)1 << sh->sig_num;\n            if (os_pending_signals & mask) {\n                os_pending_signals &= ~mask;\n                call_handler(ctx, sh->func);\n                return 0;\n            }\n        }\n    }\n\n    if (list_empty(&ts->os_rw_handlers) && list_empty(&ts->os_timers) &&\n        list_empty(&ts->port_list))\n        return -1; /* no more events */\n    \n    if (!list_empty(&ts->os_timers)) {\n        cur_time = get_time_ms();\n        min_delay = 10000;\n        list_for_each(el, &ts->os_timers) {\n            JSOSTimer *th = list_entry(el, JSOSTimer, link);\n            delay = th->timeout - cur_time;\n            if (delay <= 0) {\n                JSValue func;\n                /* the timer expired */\n                func = th->func;\n                th->func = JS_UNDEFINED;\n                unlink_timer(rt, th);\n                if (!th->has_object)\n                    free_timer(rt, th);\n                call_handler(ctx, func);\n                JS_FreeValue(ctx, func);\n                return 0;\n            } else if (delay < min_delay) {\n                min_delay = delay;\n            }\n        }\n        tv.tv_sec = min_delay / 1000;\n        tv.tv_usec = (min_delay % 1000) * 1000;\n        tvp = &tv;\n    } else {\n        tvp = NULL;\n    }\n    \n    FD_ZERO(&rfds);\n    FD_ZERO(&wfds);\n    fd_max = -1;\n    list_for_each(el, &ts->os_rw_handlers) {\n        rh = list_entry(el, JSOSRWHandler, link);\n        fd_max = max_int(fd_max, rh->fd);\n        if (!JS_IsNull(rh->rw_func[0]))\n            FD_SET(rh->fd, &rfds);\n        if (!JS_IsNull(rh->rw_func[1]))\n            FD_SET(rh->fd, &wfds);\n    }\n\n    list_for_each(el, &ts->port_list) {\n        JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link);\n        if (!JS_IsNull(port->on_message_func)) {\n            JSWorkerMessagePipe *ps = port->recv_pipe;\n            fd_max = max_int(fd_max, ps->read_fd);\n            FD_SET(ps->read_fd, &rfds);\n        }\n    }\n\n    ret = select(fd_max + 1, &rfds, &wfds, NULL, tvp);\n    if (ret > 0) {\n        list_for_each(el, &ts->os_rw_handlers) {\n            rh = list_entry(el, JSOSRWHandler, link);\n            if (!JS_IsNull(rh->rw_func[0]) &&\n                FD_ISSET(rh->fd, &rfds)) {\n                call_handler(ctx, rh->rw_func[0]);\n                /* must stop because the list may have been modified */\n                goto done;\n            }\n            if (!JS_IsNull(rh->rw_func[1]) &&\n                FD_ISSET(rh->fd, &wfds)) {\n                call_handler(ctx, rh->rw_func[1]);\n                /* must stop because the list may have been modified */\n                goto done;\n            }\n        }\n\n        list_for_each(el, &ts->port_list) {\n            JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link);\n            if (!JS_IsNull(port->on_message_func)) {\n                JSWorkerMessagePipe *ps = port->recv_pipe;\n                if (FD_ISSET(ps->read_fd, &rfds)) {\n                    if (handle_posted_message(rt, ctx, port))\n                        goto done;\n                }\n            }\n        }\n    }\n    done:\n    return 0;\n}\n#endif /* !_WIN32 */\n\nstatic JSValue make_obj_error(JSContext *ctx,\n                              JSValue obj,\n                              int err)\n{\n    JSValue arr;\n    if (JS_IsException(obj))\n        return obj;\n    arr = JS_NewArray(ctx);\n    if (JS_IsException(arr))\n        return JS_EXCEPTION;\n    JS_DefinePropertyValueUint32(ctx, arr, 0, obj,\n                                 JS_PROP_C_W_E);\n    JS_DefinePropertyValueUint32(ctx, arr, 1, JS_NewInt32(ctx, err),\n                                 JS_PROP_C_W_E);\n    return arr;\n}\n\nstatic JSValue make_string_error(JSContext *ctx,\n                                 const char *buf,\n                                 int err)\n{\n    return make_obj_error(ctx, JS_NewString(ctx, buf), err);\n}\n\n/* return [cwd, errorcode] */\nstatic JSValue js_os_getcwd(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv)\n{\n    char buf[PATH_MAX];\n    int err;\n    \n    if (!getcwd(buf, sizeof(buf))) {\n        buf[0] = '\\0';\n        err = errno;\n    } else {\n        err = 0;\n    }\n    return make_string_error(ctx, buf, err);\n}\n\nstatic JSValue js_os_chdir(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    const char *target;\n    int err;\n\n    target = JS_ToCString(ctx, argv[0]);\n    if (!target)\n        return JS_EXCEPTION;\n    err = js_get_errno(chdir(target));\n    JS_FreeCString(ctx, target);\n    return JS_NewInt32(ctx, err);\n}\n\nstatic JSValue js_os_mkdir(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    int mode, ret;\n    const char *path;\n    \n    if (argc >= 2) {\n        if (JS_ToInt32(ctx, &mode, argv[1]))\n            return JS_EXCEPTION;\n    } else {\n        mode = 0777;\n    }\n    path = JS_ToCString(ctx, argv[0]);\n    if (!path)\n        return JS_EXCEPTION;\n#if defined(_WIN32)\n    (void)mode;\n    ret = js_get_errno(mkdir(path));\n#else\n    ret = js_get_errno(mkdir(path, mode));\n#endif\n    JS_FreeCString(ctx, path);\n    return JS_NewInt32(ctx, ret);\n}\n\n/* return [array, errorcode] */\nstatic JSValue js_os_readdir(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    const char *path;\n    DIR *f;\n    struct dirent *d;\n    JSValue obj;\n    int err;\n    uint32_t len;\n    \n    path = JS_ToCString(ctx, argv[0]);\n    if (!path)\n        return JS_EXCEPTION;\n    obj = JS_NewArray(ctx);\n    if (JS_IsException(obj)) {\n        JS_FreeCString(ctx, path);\n        return JS_EXCEPTION;\n    }\n    f = opendir(path);\n    if (!f)\n        err = errno;\n    else\n        err = 0;\n    JS_FreeCString(ctx, path);\n    if (!f)\n        goto done;\n    len = 0;\n    for(;;) {\n        errno = 0;\n        d = readdir(f);\n        if (!d) {\n            err = errno;\n            break;\n        }\n        JS_DefinePropertyValueUint32(ctx, obj, len++,\n                                     JS_NewString(ctx, d->d_name),\n                                     JS_PROP_C_W_E);\n    }\n    closedir(f);\n done:\n    return make_obj_error(ctx, obj, err);\n}\n\n#if !defined(_WIN32)\nstatic int64_t timespec_to_ms(const struct timespec *tv)\n{\n    return (int64_t)tv->tv_sec * 1000 + (tv->tv_nsec / 1000000);\n}\n#endif\n\n/* return [obj, errcode] */\nstatic JSValue js_os_stat(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv, int is_lstat)\n{\n    const char *path;\n    int err, res;\n    struct stat st;\n    JSValue obj;\n\n    path = JS_ToCString(ctx, argv[0]);\n    if (!path)\n        return JS_EXCEPTION;\n#if defined(_WIN32)\n    res = stat(path, &st);\n#else\n    if (is_lstat)\n        res = lstat(path, &st);\n    else\n        res = stat(path, &st);\n#endif\n    JS_FreeCString(ctx, path);\n    if (res < 0) {\n        err = errno;\n        obj = JS_NULL;\n    } else {\n        err = 0;\n        obj = JS_NewObject(ctx);\n        if (JS_IsException(obj))\n            return JS_EXCEPTION;\n        JS_DefinePropertyValueStr(ctx, obj, \"dev\",\n                                  JS_NewInt64(ctx, st.st_dev),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"ino\",\n                                  JS_NewInt64(ctx, st.st_ino),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"mode\",\n                                  JS_NewInt32(ctx, st.st_mode),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"nlink\",\n                                  JS_NewInt64(ctx, st.st_nlink),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"uid\",\n                                  JS_NewInt64(ctx, st.st_uid),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"gid\",\n                                  JS_NewInt64(ctx, st.st_gid),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"rdev\",\n                                  JS_NewInt64(ctx, st.st_rdev),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"size\",\n                                  JS_NewInt64(ctx, st.st_size),\n                                  JS_PROP_C_W_E);\n#if !defined(_WIN32)\n        JS_DefinePropertyValueStr(ctx, obj, \"blocks\",\n                                  JS_NewInt64(ctx, st.st_blocks),\n                                  JS_PROP_C_W_E);\n#endif\n#if defined(_WIN32)\n        JS_DefinePropertyValueStr(ctx, obj, \"atime\",\n                                  JS_NewInt64(ctx, (int64_t)st.st_atime * 1000),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"mtime\",\n                                  JS_NewInt64(ctx, (int64_t)st.st_mtime * 1000),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"ctime\",\n                                  JS_NewInt64(ctx, (int64_t)st.st_ctime * 1000),\n                                  JS_PROP_C_W_E);\n#elif defined(__APPLE__)\n        JS_DefinePropertyValueStr(ctx, obj, \"atime\",\n                                  JS_NewInt64(ctx, timespec_to_ms(&st.st_atimespec)),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"mtime\",\n                                  JS_NewInt64(ctx, timespec_to_ms(&st.st_mtimespec)),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"ctime\",\n                                  JS_NewInt64(ctx, timespec_to_ms(&st.st_ctimespec)),\n                                  JS_PROP_C_W_E);\n#else\n        JS_DefinePropertyValueStr(ctx, obj, \"atime\",\n                                  JS_NewInt64(ctx, timespec_to_ms(&st.st_atim)),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"mtime\",\n                                  JS_NewInt64(ctx, timespec_to_ms(&st.st_mtim)),\n                                  JS_PROP_C_W_E);\n        JS_DefinePropertyValueStr(ctx, obj, \"ctime\",\n                                  JS_NewInt64(ctx, timespec_to_ms(&st.st_ctim)),\n                                  JS_PROP_C_W_E);\n#endif\n    }\n    return make_obj_error(ctx, obj, err);\n}\n\n#if !defined(_WIN32)\nstatic void ms_to_timeval(struct timeval *tv, uint64_t v)\n{\n    tv->tv_sec = v / 1000;\n    tv->tv_usec = (v % 1000) * 1000;\n}\n#endif\n\nstatic JSValue js_os_utimes(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv)\n{\n    const char *path;\n    int64_t atime, mtime;\n    int ret;\n    \n    if (JS_ToInt64(ctx, &atime, argv[1]))\n        return JS_EXCEPTION;\n    if (JS_ToInt64(ctx, &mtime, argv[2]))\n        return JS_EXCEPTION;\n    path = JS_ToCString(ctx, argv[0]);\n    if (!path)\n        return JS_EXCEPTION;\n#if defined(_WIN32)\n    {\n        struct _utimbuf times;\n        times.actime = atime / 1000;\n        times.modtime = mtime / 1000;\n        ret = js_get_errno(_utime(path, &times));\n    }\n#else\n    {\n        struct timeval times[2];\n        ms_to_timeval(&times[0], atime);\n        ms_to_timeval(&times[1], mtime);\n        ret = js_get_errno(utimes(path, times));\n    }\n#endif\n    JS_FreeCString(ctx, path);\n    return JS_NewInt32(ctx, ret);\n}\n\n/* sleep(delay_ms) */\nstatic JSValue js_os_sleep(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv)\n{\n    int64_t delay;\n    int ret;\n    \n    if (JS_ToInt64(ctx, &delay, argv[0]))\n        return JS_EXCEPTION;\n    if (delay < 0)\n        delay = 0;\n#if defined(_WIN32)\n    {\n        if (delay > INT32_MAX)\n            delay = INT32_MAX;\n        Sleep(delay);\n        ret = 0;\n    }\n#else\n    {\n        struct timespec ts;\n\n        ts.tv_sec = delay / 1000;\n        ts.tv_nsec = (delay % 1000) * 1000000;\n        ret = js_get_errno(nanosleep(&ts, NULL));\n    }\n#endif\n    return JS_NewInt32(ctx, ret);\n}\n\n#if defined(_WIN32)\nstatic char *realpath(const char *path, char *buf)\n{\n    if (!_fullpath(buf, path, PATH_MAX)) {\n        errno = ENOENT;\n        return NULL;\n    } else {\n        return buf;\n    }\n}\n#endif\n\n/* return [path, errorcode] */\nstatic JSValue js_os_realpath(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    const char *path;\n    char buf[PATH_MAX], *res;\n    int err;\n\n    path = JS_ToCString(ctx, argv[0]);\n    if (!path)\n        return JS_EXCEPTION;\n    res = realpath(path, buf);\n    JS_FreeCString(ctx, path);\n    if (!res) {\n        buf[0] = '\\0';\n        err = errno;\n    } else {\n        err = 0;\n    }\n    return make_string_error(ctx, buf, err);\n}\n\n#if !defined(_WIN32)\nstatic JSValue js_os_symlink(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    const char *target, *linkpath;\n    int err;\n    \n    target = JS_ToCString(ctx, argv[0]);\n    if (!target)\n        return JS_EXCEPTION;\n    linkpath = JS_ToCString(ctx, argv[1]);\n    if (!linkpath) {\n        JS_FreeCString(ctx, target);\n        return JS_EXCEPTION;\n    }\n    err = js_get_errno(symlink(target, linkpath));\n    JS_FreeCString(ctx, target);\n    JS_FreeCString(ctx, linkpath);\n    return JS_NewInt32(ctx, err);\n}\n\n/* return [path, errorcode] */\nstatic JSValue js_os_readlink(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    const char *path;\n    char buf[PATH_MAX];\n    int err;\n    ssize_t res;\n    \n    path = JS_ToCString(ctx, argv[0]);\n    if (!path)\n        return JS_EXCEPTION;\n    res = readlink(path, buf, sizeof(buf) - 1);\n    if (res < 0) {\n        buf[0] = '\\0';\n        err = errno;\n    } else {\n        buf[res] = '\\0';\n        err = 0;\n    }\n    JS_FreeCString(ctx, path);\n    return make_string_error(ctx, buf, err);\n}\n\nstatic char **build_envp(JSContext *ctx, JSValueConst obj)\n{\n    uint32_t len, i;\n    JSPropertyEnum *tab;\n    char **envp, *pair;\n    const char *key, *str;\n    JSValue val;\n    size_t key_len, str_len;\n    \n    if (JS_GetOwnPropertyNames(ctx, &tab, &len, obj,\n                               JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) < 0)\n        return NULL;\n    envp = js_mallocz(ctx, sizeof(envp[0]) * ((size_t)len + 1));\n    if (!envp)\n        goto fail;\n    for(i = 0; i < len; i++) {\n        val = JS_GetProperty(ctx, obj, tab[i].atom);\n        if (JS_IsException(val))\n            goto fail;\n        str = JS_ToCString(ctx, val);\n        JS_FreeValue(ctx, val);\n        if (!str)\n            goto fail;\n        key = JS_AtomToCString(ctx, tab[i].atom);\n        if (!key) {\n            JS_FreeCString(ctx, str);\n            goto fail;\n        }\n        key_len = strlen(key);\n        str_len = strlen(str);\n        pair = js_malloc(ctx, key_len + str_len + 2);\n        if (!pair) {\n            JS_FreeCString(ctx, key);\n            JS_FreeCString(ctx, str);\n            goto fail;\n        }\n        memcpy(pair, key, key_len);\n        pair[key_len] = '=';\n        memcpy(pair + key_len + 1, str, str_len);\n        pair[key_len + 1 + str_len] = '\\0';\n        envp[i] = pair;\n        JS_FreeCString(ctx, key);\n        JS_FreeCString(ctx, str);\n    }\n done:\n    for(i = 0; i < len; i++)\n        JS_FreeAtom(ctx, tab[i].atom);\n    js_free(ctx, tab);\n    return envp;\n fail:\n    if (envp) {\n        for(i = 0; i < len; i++)\n            js_free(ctx, envp[i]);\n        js_free(ctx, envp);\n        envp = NULL;\n    }\n    goto done;\n}\n\n/* execvpe is not available on non GNU systems */\nstatic int my_execvpe(const char *filename, char **argv, char **envp)\n{\n    char *path, *p, *p_next, *p1;\n    char buf[PATH_MAX];\n    size_t filename_len, path_len;\n    BOOL eacces_error;\n    \n    filename_len = strlen(filename);\n    if (filename_len == 0) {\n        errno = ENOENT;\n        return -1;\n    }\n    if (strchr(filename, '/'))\n        return execve(filename, argv, envp);\n    \n    path = getenv(\"PATH\");\n    if (!path)\n        path = (char *)\"/bin:/usr/bin\";\n    eacces_error = FALSE;\n    p = path;\n    for(p = path; p != NULL; p = p_next) {\n        p1 = strchr(p, ':');\n        if (!p1) {\n            p_next = NULL;\n            path_len = strlen(p);\n        } else {\n            p_next = p1 + 1;\n            path_len = p1 - p;\n        }\n        /* path too long */\n        if ((path_len + 1 + filename_len + 1) > PATH_MAX)\n            continue;\n        memcpy(buf, p, path_len);\n        buf[path_len] = '/';\n        memcpy(buf + path_len + 1, filename, filename_len);\n        buf[path_len + 1 + filename_len] = '\\0';\n        \n        execve(buf, argv, envp);\n\n        switch(errno) {\n        case EACCES:\n            eacces_error = TRUE;\n            break;\n        case ENOENT:\n        case ENOTDIR:\n            break;\n        default:\n            return -1;\n        }\n    }\n    if (eacces_error)\n        errno = EACCES;\n    return -1;\n}\n\n/* exec(args[, options]) -> exitcode */\nstatic JSValue js_os_exec(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv)\n{\n    JSValueConst options, args = argv[0];\n    JSValue val, ret_val;\n    const char **exec_argv, *file = NULL, *str, *cwd = NULL;\n    char **envp = environ;\n    uint32_t exec_argc, i;\n    int ret, pid, status;\n    BOOL block_flag = TRUE, use_path = TRUE;\n    static const char *std_name[3] = { \"stdin\", \"stdout\", \"stderr\" };\n    int std_fds[3];\n    uint32_t uid = -1, gid = -1;\n    \n    val = JS_GetPropertyStr(ctx, args, \"length\");\n    if (JS_IsException(val))\n        return JS_EXCEPTION;\n    ret = JS_ToUint32(ctx, &exec_argc, val);\n    JS_FreeValue(ctx, val);\n    if (ret)\n        return JS_EXCEPTION;\n    /* arbitrary limit to avoid overflow */\n    if (exec_argc < 1 || exec_argc > 65535) {\n        return JS_ThrowTypeError(ctx, \"invalid number of arguments\");\n    }\n    exec_argv = js_mallocz(ctx, sizeof(exec_argv[0]) * (exec_argc + 1));\n    if (!exec_argv)\n        return JS_EXCEPTION;\n    for(i = 0; i < exec_argc; i++) {\n        val = JS_GetPropertyUint32(ctx, args, i);\n        if (JS_IsException(val))\n            goto exception;\n        str = JS_ToCString(ctx, val);\n        JS_FreeValue(ctx, val);\n        if (!str)\n            goto exception;\n        exec_argv[i] = str;\n    }\n    exec_argv[exec_argc] = NULL;\n\n    for(i = 0; i < 3; i++)\n        std_fds[i] = i;\n    \n    /* get the options, if any */\n    if (argc >= 2) {\n        options = argv[1];\n\n        if (get_bool_option(ctx, &block_flag, options, \"block\"))\n            goto exception;\n        if (get_bool_option(ctx, &use_path, options, \"usePath\"))\n            goto exception;\n        \n        val = JS_GetPropertyStr(ctx, options, \"file\");\n        if (JS_IsException(val))\n            goto exception;\n        if (!JS_IsUndefined(val)) {\n            file = JS_ToCString(ctx, val);\n            JS_FreeValue(ctx, val);\n            if (!file)\n                goto exception;\n        }\n\n        val = JS_GetPropertyStr(ctx, options, \"cwd\");\n        if (JS_IsException(val))\n            goto exception;\n        if (!JS_IsUndefined(val)) {\n            cwd = JS_ToCString(ctx, val);\n            JS_FreeValue(ctx, val);\n            if (!cwd)\n                goto exception;\n        }\n\n        /* stdin/stdout/stderr handles */\n        for(i = 0; i < 3; i++) {\n            val = JS_GetPropertyStr(ctx, options, std_name[i]);\n            if (JS_IsException(val))\n                goto exception;\n            if (!JS_IsUndefined(val)) {\n                int fd;\n                ret = JS_ToInt32(ctx, &fd, val);\n                JS_FreeValue(ctx, val);\n                if (ret)\n                    goto exception;\n                std_fds[i] = fd;\n            }\n        }\n\n        val = JS_GetPropertyStr(ctx, options, \"env\");\n        if (JS_IsException(val))\n            goto exception;\n        if (!JS_IsUndefined(val)) {\n            envp = build_envp(ctx, val);\n            JS_FreeValue(ctx, val);\n            if (!envp)\n                goto exception;\n        }\n        \n        val = JS_GetPropertyStr(ctx, options, \"uid\");\n        if (JS_IsException(val))\n            goto exception;\n        if (!JS_IsUndefined(val)) {\n            ret = JS_ToUint32(ctx, &uid, val);\n            JS_FreeValue(ctx, val);\n            if (ret)\n                goto exception;\n        }\n\n        val = JS_GetPropertyStr(ctx, options, \"gid\");\n        if (JS_IsException(val))\n            goto exception;\n        if (!JS_IsUndefined(val)) {\n            ret = JS_ToUint32(ctx, &gid, val);\n            JS_FreeValue(ctx, val);\n            if (ret)\n                goto exception;\n        }\n    }\n\n    pid = fork();\n    if (pid < 0) {\n        JS_ThrowTypeError(ctx, \"fork error\");\n        goto exception;\n    }\n    if (pid == 0) {\n        /* child */\n        int fd_max = sysconf(_SC_OPEN_MAX);\n\n        /* remap the stdin/stdout/stderr handles if necessary */\n        for(i = 0; i < 3; i++) {\n            if (std_fds[i] != i) {\n                if (dup2(std_fds[i], i) < 0)\n                    _exit(127);\n            }\n        }\n\n        for(i = 3; i < fd_max; i++)\n            close(i);\n        if (cwd) {\n            if (chdir(cwd) < 0)\n                _exit(127);\n        }\n        if (uid != -1) {\n            if (setuid(uid) < 0)\n                _exit(127);\n        }\n        if (gid != -1) {\n            if (setgid(gid) < 0)\n                _exit(127);\n        }\n\n        if (!file)\n            file = exec_argv[0];\n        if (use_path)\n            ret = my_execvpe(file, (char **)exec_argv, envp);\n        else\n            ret = execve(file, (char **)exec_argv, envp);\n        _exit(127);\n    }\n    /* parent */\n    if (block_flag) {\n        for(;;) {\n            ret = waitpid(pid, &status, 0);\n            if (ret == pid) {\n                if (WIFEXITED(status)) {\n                    ret = WEXITSTATUS(status);\n                    break;\n                } else if (WIFSIGNALED(status)) {\n                    ret = -WTERMSIG(status);\n                    break;\n                }\n            }\n        }\n    } else {\n        ret = pid;\n    }\n    ret_val = JS_NewInt32(ctx, ret);\n done:\n    JS_FreeCString(ctx, file);\n    JS_FreeCString(ctx, cwd);\n    for(i = 0; i < exec_argc; i++)\n        JS_FreeCString(ctx, exec_argv[i]);\n    js_free(ctx, exec_argv);\n    if (envp != environ) {\n        char **p;\n        p = envp;\n        while (*p != NULL) {\n            js_free(ctx, *p);\n            p++;\n        }\n        js_free(ctx, envp);\n    }\n    return ret_val;\n exception:\n    ret_val = JS_EXCEPTION;\n    goto done;\n}\n\n/* waitpid(pid, block) -> [pid, status] */\nstatic JSValue js_os_waitpid(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    int pid, status, options, ret;\n    JSValue obj;\n    \n    if (JS_ToInt32(ctx, &pid, argv[0]))\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &options, argv[1]))\n        return JS_EXCEPTION;\n\n    ret = waitpid(pid, &status, options);\n    if (ret < 0) {\n        ret = -errno;\n        status = 0;\n    }\n\n    obj = JS_NewArray(ctx);\n    if (JS_IsException(obj))\n        return obj;\n    JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, ret),\n                                 JS_PROP_C_W_E);\n    JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, status),\n                                 JS_PROP_C_W_E);\n    return obj;\n}    \n\n/* pipe() -> [read_fd, write_fd] or null if error */\nstatic JSValue js_os_pipe(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv)\n{\n    int pipe_fds[2], ret;\n    JSValue obj;\n    \n    ret = pipe(pipe_fds);\n    if (ret < 0)\n        return JS_NULL;\n    obj = JS_NewArray(ctx);\n    if (JS_IsException(obj))\n        return obj;\n    JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, pipe_fds[0]),\n                                 JS_PROP_C_W_E);\n    JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, pipe_fds[1]),\n                                 JS_PROP_C_W_E);\n    return obj;\n}\n\n/* kill(pid, sig) */\nstatic JSValue js_os_kill(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv)\n{\n    int pid, sig, ret;\n    \n    if (JS_ToInt32(ctx, &pid, argv[0]))\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &sig, argv[1]))\n        return JS_EXCEPTION;\n    ret = js_get_errno(kill(pid, sig));\n    return JS_NewInt32(ctx, ret);\n}\n\n/* dup(fd) */\nstatic JSValue js_os_dup(JSContext *ctx, JSValueConst this_val,\n                         int argc, JSValueConst *argv)\n{\n    int fd, ret;\n    \n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    ret = js_get_errno(dup(fd));\n    return JS_NewInt32(ctx, ret);\n}\n\n/* dup2(fd) */\nstatic JSValue js_os_dup2(JSContext *ctx, JSValueConst this_val,\n                         int argc, JSValueConst *argv)\n{\n    int fd, fd2, ret;\n    \n    if (JS_ToInt32(ctx, &fd, argv[0]))\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &fd2, argv[1]))\n        return JS_EXCEPTION;\n    ret = js_get_errno(dup2(fd, fd2));\n    return JS_NewInt32(ctx, ret);\n}\n\n#endif /* !_WIN32 */\n\n#ifdef USE_WORKER\n\n/* Worker */\n\ntypedef struct {\n    JSWorkerMessagePipe *recv_pipe;\n    JSWorkerMessagePipe *send_pipe;\n    JSWorkerMessageHandler *msg_handler;\n} JSWorkerData;\n\ntypedef struct {\n    char *filename; /* module filename */\n    char *basename; /* module base name */\n    JSWorkerMessagePipe *recv_pipe, *send_pipe;\n} WorkerFuncArgs;\n\ntypedef struct {\n    int ref_count;\n    uint64_t buf[0];\n} JSSABHeader;\n\nstatic JSClassID js_worker_class_id;\nstatic JSContext *(*js_worker_new_context_func)(JSRuntime *rt);\n\nstatic int atomic_add_int(int *ptr, int v)\n{\n    return atomic_fetch_add((_Atomic(uint32_t) *)ptr, v) + v;\n}\n\n/* shared array buffer allocator */\nstatic void *js_sab_alloc(void *opaque, size_t size)\n{\n    JSSABHeader *sab;\n    sab = malloc(sizeof(JSSABHeader) + size);\n    if (!sab)\n        return NULL;\n    sab->ref_count = 1;\n    return sab->buf;\n}\n\nstatic void js_sab_free(void *opaque, void *ptr)\n{\n    JSSABHeader *sab;\n    int ref_count;\n    sab = (JSSABHeader *)((uint8_t *)ptr - sizeof(JSSABHeader));\n    ref_count = atomic_add_int(&sab->ref_count, -1);\n    assert(ref_count >= 0);\n    if (ref_count == 0) {\n        free(sab);\n    }\n}\n\nstatic void js_sab_dup(void *opaque, void *ptr)\n{\n    JSSABHeader *sab;\n    sab = (JSSABHeader *)((uint8_t *)ptr - sizeof(JSSABHeader));\n    atomic_add_int(&sab->ref_count, 1);\n}\n\nstatic JSWorkerMessagePipe *js_new_message_pipe(void)\n{\n    JSWorkerMessagePipe *ps;\n    int pipe_fds[2];\n    \n    if (pipe(pipe_fds) < 0)\n        return NULL;\n\n    ps = malloc(sizeof(*ps));\n    if (!ps) {\n        close(pipe_fds[0]);\n        close(pipe_fds[1]);\n        return NULL;\n    }\n    ps->ref_count = 1;\n    init_list_head(&ps->msg_queue);\n    pthread_mutex_init(&ps->mutex, NULL);\n    ps->read_fd = pipe_fds[0];\n    ps->write_fd = pipe_fds[1];\n    return ps;\n}\n\nstatic JSWorkerMessagePipe *js_dup_message_pipe(JSWorkerMessagePipe *ps)\n{\n    atomic_add_int(&ps->ref_count, 1);\n    return ps;\n}\n\nstatic void js_free_message(JSWorkerMessage *msg)\n{\n    size_t i;\n    /* free the SAB */\n    for(i = 0; i < msg->sab_tab_len; i++) {\n        js_sab_free(NULL, msg->sab_tab[i]);\n    }\n    free(msg->sab_tab);\n    free(msg->data);\n    free(msg);\n}\n\nstatic void js_free_message_pipe(JSWorkerMessagePipe *ps)\n{\n    struct list_head *el, *el1;\n    JSWorkerMessage *msg;\n    int ref_count;\n    \n    if (!ps)\n        return;\n    \n    ref_count = atomic_add_int(&ps->ref_count, -1);\n    assert(ref_count >= 0);\n    if (ref_count == 0) {\n        list_for_each_safe(el, el1, &ps->msg_queue) {\n            msg = list_entry(el, JSWorkerMessage, link);\n            js_free_message(msg);\n        }\n        pthread_mutex_destroy(&ps->mutex);\n        close(ps->read_fd);\n        close(ps->write_fd);\n        free(ps);\n    }\n}\n\nstatic void js_free_port(JSRuntime *rt, JSWorkerMessageHandler *port)\n{\n    if (port) {\n        js_free_message_pipe(port->recv_pipe);\n        JS_FreeValueRT(rt, port->on_message_func);\n        list_del(&port->link);\n        js_free_rt(rt, port);\n    }\n}\n\nstatic void js_worker_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSWorkerData *worker = JS_GetOpaque(val, js_worker_class_id);\n    if (worker) {\n        js_free_message_pipe(worker->recv_pipe);\n        js_free_message_pipe(worker->send_pipe);\n        js_free_port(rt, worker->msg_handler);\n        js_free_rt(rt, worker);\n    }\n}\n\nstatic JSClassDef js_worker_class = {\n    \"Worker\",\n    .finalizer = js_worker_finalizer,\n}; \n\nstatic void *worker_func(void *opaque)\n{\n    WorkerFuncArgs *args = opaque;\n    JSRuntime *rt;\n    JSThreadState *ts;\n    JSContext *ctx;\n    \n    rt = JS_NewRuntime();\n    if (rt == NULL) {\n        fprintf(stderr, \"JS_NewRuntime failure\");\n        exit(1);\n    }        \n    js_std_init_handlers(rt);\n\n    JS_SetModuleLoaderFunc(rt, NULL, js_module_loader, NULL);\n\n    /* set the pipe to communicate with the parent */\n    ts = JS_GetRuntimeOpaque(rt);\n    ts->recv_pipe = args->recv_pipe;\n    ts->send_pipe = args->send_pipe;\n    \n    /* function pointer to avoid linking the whole JS_NewContext() if\n       not needed */\n    ctx = js_worker_new_context_func(rt);\n    if (ctx == NULL) {\n        fprintf(stderr, \"JS_NewContext failure\");\n    }\n\n    JS_SetCanBlock(rt, TRUE);\n\n    js_std_add_helpers(ctx, -1, NULL);\n\n    if (!JS_RunModule(ctx, args->basename, args->filename))\n        js_std_dump_error(ctx);\n    free(args->filename);\n    free(args->basename);\n    free(args);\n\n    js_std_loop(ctx);\n\n    JS_FreeContext(ctx);\n    js_std_free_handlers(rt);\n    JS_FreeRuntime(rt);\n    return NULL;\n}\n\nstatic JSValue js_worker_ctor_internal(JSContext *ctx, JSValueConst new_target,\n                                       JSWorkerMessagePipe *recv_pipe,\n                                       JSWorkerMessagePipe *send_pipe)\n{\n    JSValue obj = JS_UNDEFINED, proto;\n    JSWorkerData *s;\n    \n    /* create the object */\n    if (JS_IsUndefined(new_target)) {\n        proto = JS_GetClassProto(ctx, js_worker_class_id);\n    } else {\n        proto = JS_GetPropertyStr(ctx, new_target, \"prototype\");\n        if (JS_IsException(proto))\n            goto fail;\n    }\n    obj = JS_NewObjectProtoClass(ctx, proto, js_worker_class_id);\n    JS_FreeValue(ctx, proto);\n    if (JS_IsException(obj))\n        goto fail;\n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s)\n        goto fail;\n    s->recv_pipe = js_dup_message_pipe(recv_pipe);\n    s->send_pipe = js_dup_message_pipe(send_pipe);\n\n    JS_SetOpaque(obj, s);\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_worker_ctor(JSContext *ctx, JSValueConst new_target,\n                              int argc, JSValueConst *argv)\n{\n    JSRuntime *rt = JS_GetRuntime(ctx);\n    WorkerFuncArgs *args = NULL;\n    pthread_t tid;\n    pthread_attr_t attr;\n    JSValue obj = JS_UNDEFINED;\n    int ret;\n    const char *filename = NULL, *basename;\n    JSAtom basename_atom;\n    \n    /* XXX: in order to avoid problems with resource liberation, we\n       don't support creating workers inside workers */\n    if (!is_main_thread(rt))\n        return JS_ThrowTypeError(ctx, \"cannot create a worker inside a worker\");\n\n    /* base name, assuming the calling function is a normal JS\n       function */\n    basename_atom = JS_GetScriptOrModuleName(ctx, 1);\n    if (basename_atom == JS_ATOM_NULL) {\n        return JS_ThrowTypeError(ctx, \"could not determine calling script or module name\");\n    }\n    basename = JS_AtomToCString(ctx, basename_atom);\n    JS_FreeAtom(ctx, basename_atom);\n    if (!basename)\n        goto fail;\n    \n    /* module name */\n    filename = JS_ToCString(ctx, argv[0]);\n    if (!filename)\n        goto fail;\n\n    args = malloc(sizeof(*args));\n    if (!args)\n        goto oom_fail;\n    memset(args, 0, sizeof(*args));\n    args->filename = strdup(filename);\n    args->basename = strdup(basename);\n\n    /* ports */\n    args->recv_pipe = js_new_message_pipe();\n    if (!args->recv_pipe)\n        goto oom_fail;\n    args->send_pipe = js_new_message_pipe();\n    if (!args->send_pipe)\n        goto oom_fail;\n\n    obj = js_worker_ctor_internal(ctx, new_target,\n                                  args->send_pipe, args->recv_pipe);\n    if (JS_IsException(obj))\n        goto fail;\n    \n    pthread_attr_init(&attr);\n    /* no join at the end */\n    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);\n    ret = pthread_create(&tid, &attr, worker_func, args);\n    pthread_attr_destroy(&attr);\n    if (ret != 0) {\n        JS_ThrowTypeError(ctx, \"could not create worker\");\n        goto fail;\n    }\n    JS_FreeCString(ctx, basename);\n    JS_FreeCString(ctx, filename);\n    return obj;\n oom_fail:\n    JS_ThrowOutOfMemory(ctx);\n fail:\n    JS_FreeCString(ctx, basename);\n    JS_FreeCString(ctx, filename);\n    if (args) {\n        free(args->filename);\n        free(args->basename);\n        js_free_message_pipe(args->recv_pipe);\n        js_free_message_pipe(args->send_pipe);\n        free(args);\n    }\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_worker_postMessage(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, js_worker_class_id);\n    JSWorkerMessagePipe *ps;\n    size_t data_len, sab_tab_len, i;\n    uint8_t *data;\n    JSWorkerMessage *msg;\n    uint8_t **sab_tab;\n    \n    if (!worker)\n        return JS_EXCEPTION;\n    \n    data = JS_WriteObject2(ctx, &data_len, argv[0],\n                           JS_WRITE_OBJ_SAB | JS_WRITE_OBJ_REFERENCE,\n                           &sab_tab, &sab_tab_len);\n    if (!data)\n        return JS_EXCEPTION;\n\n    msg = malloc(sizeof(*msg));\n    if (!msg)\n        goto fail;\n    msg->data = NULL;\n    msg->sab_tab = NULL;\n\n    /* must reallocate because the allocator may be different */\n    msg->data = malloc(data_len);\n    if (!msg->data)\n        goto fail;\n    memcpy(msg->data, data, data_len);\n    msg->data_len = data_len;\n\n    msg->sab_tab = malloc(sizeof(msg->sab_tab[0]) * sab_tab_len);\n    if (!msg->sab_tab)\n        goto fail;\n    memcpy(msg->sab_tab, sab_tab, sizeof(msg->sab_tab[0]) * sab_tab_len);\n    msg->sab_tab_len = sab_tab_len;\n\n    js_free(ctx, data);\n    js_free(ctx, sab_tab);\n    \n    /* increment the SAB reference counts */\n    for(i = 0; i < msg->sab_tab_len; i++) {\n        js_sab_dup(NULL, msg->sab_tab[i]);\n    }\n\n    ps = worker->send_pipe;\n    pthread_mutex_lock(&ps->mutex);\n    /* indicate that data is present */\n    if (list_empty(&ps->msg_queue)) {\n        uint8_t ch = '\\0';\n        int ret;\n        for(;;) {\n            ret = write(ps->write_fd, &ch, 1);\n            if (ret == 1)\n                break;\n            if (ret < 0 && (errno != EAGAIN || errno != EINTR))\n                break;\n        }\n    }\n    list_add_tail(&msg->link, &ps->msg_queue);\n    pthread_mutex_unlock(&ps->mutex);\n    return JS_UNDEFINED;\n fail:\n    if (msg) {\n        free(msg->data);\n        free(msg->sab_tab);\n        free(msg);\n    }\n    js_free(ctx, data);\n    js_free(ctx, sab_tab);\n    return JS_EXCEPTION;\n    \n}\n\nstatic JSValue js_worker_set_onmessage(JSContext *ctx, JSValueConst this_val,\n                                   JSValueConst func)\n{\n    JSRuntime *rt = JS_GetRuntime(ctx);\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, js_worker_class_id);\n    JSWorkerMessageHandler *port;\n    \n    if (!worker)\n        return JS_EXCEPTION;\n\n    port = worker->msg_handler;\n    if (JS_IsNull(func)) {\n        if (port) {\n            js_free_port(rt, port);\n            worker->msg_handler = NULL;\n        }\n    } else {\n        if (!JS_IsFunction(ctx, func))\n            return JS_ThrowTypeError(ctx, \"not a function\");\n        if (!port) {\n            port = js_mallocz(ctx, sizeof(*port));\n            if (!port)\n                return JS_EXCEPTION;\n            port->recv_pipe = js_dup_message_pipe(worker->recv_pipe);\n            port->on_message_func = JS_NULL;\n            list_add_tail(&port->link, &ts->port_list);\n            worker->msg_handler = port;\n        }\n        JS_FreeValue(ctx, port->on_message_func);\n        port->on_message_func = JS_DupValue(ctx, func);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_worker_get_onmessage(JSContext *ctx, JSValueConst this_val)\n{\n    JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, js_worker_class_id);\n    JSWorkerMessageHandler *port;\n    if (!worker)\n        return JS_EXCEPTION;\n    port = worker->msg_handler;\n    if (port) {\n        return JS_DupValue(ctx, port->on_message_func);\n    } else {\n        return JS_NULL;\n    }\n}\n\nstatic const JSCFunctionListEntry js_worker_proto_funcs[] = {\n    JS_CFUNC_DEF(\"postMessage\", 1, js_worker_postMessage ),\n    JS_CGETSET_DEF(\"onmessage\", js_worker_get_onmessage, js_worker_set_onmessage ),\n};\n\n#endif /* USE_WORKER */\n\nvoid js_std_set_worker_new_context_func(JSContext *(*func)(JSRuntime *rt))\n{\n#ifdef USE_WORKER\n    js_worker_new_context_func = func;\n#endif\n}\n\n#if defined(_WIN32)\n#define OS_PLATFORM \"win32\"\n#elif defined(__APPLE__)\n#define OS_PLATFORM \"darwin\"\n#elif defined(EMSCRIPTEN)\n#define OS_PLATFORM \"js\"\n#else\n#define OS_PLATFORM \"linux\"\n#endif\n\n#define OS_FLAG(x) JS_PROP_INT32_DEF(#x, x, JS_PROP_CONFIGURABLE )\n\nstatic const JSCFunctionListEntry js_os_funcs[] = {\n    JS_CFUNC_DEF(\"open\", 2, js_os_open ),\n    OS_FLAG(O_RDONLY),\n    OS_FLAG(O_WRONLY),\n    OS_FLAG(O_RDWR),\n    OS_FLAG(O_APPEND),\n    OS_FLAG(O_CREAT),\n    OS_FLAG(O_EXCL),\n    OS_FLAG(O_TRUNC),\n#if defined(_WIN32)\n    OS_FLAG(O_BINARY),\n    OS_FLAG(O_TEXT),\n#endif\n    JS_CFUNC_DEF(\"close\", 1, js_os_close ),\n    JS_CFUNC_DEF(\"seek\", 3, js_os_seek ),\n    JS_CFUNC_MAGIC_DEF(\"read\", 4, js_os_read_write, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"write\", 4, js_os_read_write, 1 ),\n    JS_CFUNC_DEF(\"isatty\", 1, js_os_isatty ),\n    JS_CFUNC_DEF(\"ttyGetWinSize\", 1, js_os_ttyGetWinSize ),\n    JS_CFUNC_DEF(\"ttySetRaw\", 1, js_os_ttySetRaw ),\n    JS_CFUNC_DEF(\"remove\", 1, js_os_remove ),\n    JS_CFUNC_DEF(\"rename\", 2, js_os_rename ),\n    JS_CFUNC_MAGIC_DEF(\"setReadHandler\", 2, js_os_setReadHandler, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"setWriteHandler\", 2, js_os_setReadHandler, 1 ),\n    JS_CFUNC_DEF(\"signal\", 2, js_os_signal ),\n    OS_FLAG(SIGINT),\n    OS_FLAG(SIGABRT),\n    OS_FLAG(SIGFPE),\n    OS_FLAG(SIGILL),\n    OS_FLAG(SIGSEGV),\n    OS_FLAG(SIGTERM),\n#if !defined(_WIN32)\n    OS_FLAG(SIGQUIT),\n    OS_FLAG(SIGPIPE),\n    OS_FLAG(SIGALRM),\n    OS_FLAG(SIGUSR1),\n    OS_FLAG(SIGUSR2),\n    OS_FLAG(SIGCHLD),\n    OS_FLAG(SIGCONT),\n    OS_FLAG(SIGSTOP),\n    OS_FLAG(SIGTSTP),\n    OS_FLAG(SIGTTIN),\n    OS_FLAG(SIGTTOU),\n#endif\n    JS_CFUNC_DEF(\"setTimeout\", 2, js_os_setTimeout ),\n    JS_CFUNC_DEF(\"clearTimeout\", 1, js_os_clearTimeout ),\n    JS_PROP_STRING_DEF(\"platform\", OS_PLATFORM, 0 ),\n    JS_CFUNC_DEF(\"getcwd\", 0, js_os_getcwd ),\n    JS_CFUNC_DEF(\"chdir\", 0, js_os_chdir ),\n    JS_CFUNC_DEF(\"mkdir\", 1, js_os_mkdir ),\n    JS_CFUNC_DEF(\"readdir\", 1, js_os_readdir ),\n    /* st_mode constants */\n    OS_FLAG(S_IFMT),\n    OS_FLAG(S_IFIFO),\n    OS_FLAG(S_IFCHR),\n    OS_FLAG(S_IFDIR),\n    OS_FLAG(S_IFBLK),\n    OS_FLAG(S_IFREG),\n#if !defined(_WIN32)\n    OS_FLAG(S_IFSOCK),\n    OS_FLAG(S_IFLNK),\n    OS_FLAG(S_ISGID),\n    OS_FLAG(S_ISUID),\n#endif\n    JS_CFUNC_MAGIC_DEF(\"stat\", 1, js_os_stat, 0 ),\n    JS_CFUNC_DEF(\"utimes\", 3, js_os_utimes ),\n    JS_CFUNC_DEF(\"sleep\", 1, js_os_sleep ),\n    JS_CFUNC_DEF(\"realpath\", 1, js_os_realpath ),\n#if !defined(_WIN32)\n    JS_CFUNC_MAGIC_DEF(\"lstat\", 1, js_os_stat, 1 ),\n    JS_CFUNC_DEF(\"symlink\", 2, js_os_symlink ),\n    JS_CFUNC_DEF(\"readlink\", 1, js_os_readlink ),\n    JS_CFUNC_DEF(\"exec\", 1, js_os_exec ),\n    JS_CFUNC_DEF(\"waitpid\", 2, js_os_waitpid ),\n    OS_FLAG(WNOHANG),\n    JS_CFUNC_DEF(\"pipe\", 0, js_os_pipe ),\n    JS_CFUNC_DEF(\"kill\", 2, js_os_kill ),\n    JS_CFUNC_DEF(\"dup\", 1, js_os_dup ),\n    JS_CFUNC_DEF(\"dup2\", 2, js_os_dup2 ),\n#endif\n};\n\nstatic int js_os_init(JSContext *ctx, JSModuleDef *m)\n{\n    os_poll_func = js_os_poll;\n    \n    /* OSTimer class */\n    JS_NewClassID(&js_os_timer_class_id);\n    JS_NewClass(JS_GetRuntime(ctx), js_os_timer_class_id, &js_os_timer_class);\n\n#ifdef USE_WORKER\n    {\n        JSRuntime *rt = JS_GetRuntime(ctx);\n        JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n        JSValue proto, obj;\n        /* Worker class */\n        JS_NewClassID(&js_worker_class_id);\n        JS_NewClass(JS_GetRuntime(ctx), js_worker_class_id, &js_worker_class);\n        proto = JS_NewObject(ctx);\n        JS_SetPropertyFunctionList(ctx, proto, js_worker_proto_funcs, countof(js_worker_proto_funcs));\n        \n        obj = JS_NewCFunction2(ctx, js_worker_ctor, \"Worker\", 1,\n                               JS_CFUNC_constructor, 0);\n        JS_SetConstructor(ctx, obj, proto);\n        \n        JS_SetClassProto(ctx, js_worker_class_id, proto);\n        \n        /* set 'Worker.parent' if necessary */\n        if (ts->recv_pipe && ts->send_pipe) {\n            JS_DefinePropertyValueStr(ctx, obj, \"parent\",\n                                      js_worker_ctor_internal(ctx, JS_UNDEFINED, ts->recv_pipe, ts->send_pipe),\n                                      JS_PROP_C_W_E);\n        }\n        \n        JS_SetModuleExport(ctx, m, \"Worker\", obj);\n    }\n#endif /* USE_WORKER */\n\n    return JS_SetModuleExportList(ctx, m, js_os_funcs,\n                                  countof(js_os_funcs));\n}\n\nJSModuleDef *js_init_module_os(JSContext *ctx, const char *module_name)\n{\n    JSModuleDef *m;\n    m = JS_NewCModule(ctx, module_name, js_os_init);\n    if (!m)\n        return NULL;\n    JS_AddModuleExportList(ctx, m, js_os_funcs, countof(js_os_funcs));\n#ifdef USE_WORKER\n    JS_AddModuleExport(ctx, m, \"Worker\");\n#endif\n    return m;\n}\n\n/**********************************************************/\n\nstatic JSValue js_print(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    int i;\n    const char *str;\n    size_t len;\n\n    for(i = 0; i < argc; i++) {\n        if (i != 0)\n            putchar(' ');\n        str = JS_ToCStringLen(ctx, &len, argv[i]);\n        if (!str)\n            return JS_EXCEPTION;\n        fwrite(str, 1, len, stdout);\n        JS_FreeCString(ctx, str);\n    }\n    putchar('\\n');\n    return JS_UNDEFINED;\n}\n\nvoid js_std_add_helpers(JSContext *ctx, int argc, char **argv)\n{\n    JSValue global_obj, console, args;\n    int i;\n\n    /* XXX: should these global definitions be enumerable? */\n    global_obj = JS_GetGlobalObject(ctx);\n\n    console = JS_NewObject(ctx);\n    JS_SetPropertyStr(ctx, console, \"log\",\n                      JS_NewCFunction(ctx, js_print, \"log\", 1));\n    JS_SetPropertyStr(ctx, global_obj, \"console\", console);\n\n    /* same methods as the mozilla JS shell */\n    if (argc >= 0) {\n        args = JS_NewArray(ctx);\n        for(i = 0; i < argc; i++) {\n            JS_SetPropertyUint32(ctx, args, i, JS_NewString(ctx, argv[i]));\n        }\n        JS_SetPropertyStr(ctx, global_obj, \"scriptArgs\", args);\n    }\n    \n    JS_SetPropertyStr(ctx, global_obj, \"print\",\n                      JS_NewCFunction(ctx, js_print, \"print\", 1));\n    JS_SetPropertyStr(ctx, global_obj, \"__loadScript\",\n                      JS_NewCFunction(ctx, js_loadScript, \"__loadScript\", 1));\n    \n    JS_FreeValue(ctx, global_obj);\n}\n\nvoid js_std_init_handlers(JSRuntime *rt)\n{\n    JSThreadState *ts;\n\n    ts = malloc(sizeof(*ts));\n    if (!ts) {\n        fprintf(stderr, \"Could not allocate memory for the worker\");\n        exit(1);\n    }\n    memset(ts, 0, sizeof(*ts));\n    init_list_head(&ts->os_rw_handlers);\n    init_list_head(&ts->os_signal_handlers);\n    init_list_head(&ts->os_timers);\n    init_list_head(&ts->port_list);\n\n    JS_SetRuntimeOpaque(rt, ts);\n\n#ifdef USE_WORKER\n    /* set the SharedArrayBuffer memory handlers */\n    {\n        JSSharedArrayBufferFunctions sf;\n        memset(&sf, 0, sizeof(sf));\n        sf.sab_alloc = js_sab_alloc;\n        sf.sab_free = js_sab_free;\n        sf.sab_dup = js_sab_dup;\n        JS_SetSharedArrayBufferFunctions(rt, &sf);\n    }\n#endif\n}\n\nvoid js_std_free_handlers(JSRuntime *rt)\n{\n    JSThreadState *ts = JS_GetRuntimeOpaque(rt);\n    struct list_head *el, *el1;\n\n    list_for_each_safe(el, el1, &ts->os_rw_handlers) {\n        JSOSRWHandler *rh = list_entry(el, JSOSRWHandler, link);\n        free_rw_handler(rt, rh);\n    }\n\n    list_for_each_safe(el, el1, &ts->os_signal_handlers) {\n        JSOSSignalHandler *sh = list_entry(el, JSOSSignalHandler, link);\n        free_sh(rt, sh);\n    }\n    \n    list_for_each_safe(el, el1, &ts->os_timers) {\n        JSOSTimer *th = list_entry(el, JSOSTimer, link);\n        unlink_timer(rt, th);\n        if (!th->has_object)\n            free_timer(rt, th);\n    }\n\n#ifdef USE_WORKER\n    /* XXX: free port_list ? */\n    js_free_message_pipe(ts->recv_pipe);\n    js_free_message_pipe(ts->send_pipe);\n#endif\n\n    free(ts);\n    JS_SetRuntimeOpaque(rt, NULL); /* fail safe */\n}\n\nstatic void js_dump_obj(JSContext *ctx, FILE *f, JSValueConst val)\n{\n    const char *str;\n    \n    str = JS_ToCString(ctx, val);\n    if (str) {\n        fprintf(f, \"%s\\n\", str);\n        JS_FreeCString(ctx, str);\n    } else {\n        fprintf(f, \"[exception]\\n\");\n    }\n}\n\nstatic void js_std_dump_error1(JSContext *ctx, JSValueConst exception_val)\n{\n    JSValue val;\n    BOOL is_error;\n    \n    is_error = JS_IsError(ctx, exception_val);\n    js_dump_obj(ctx, stderr, exception_val);\n    if (is_error) {\n        val = JS_GetPropertyStr(ctx, exception_val, \"stack\");\n        if (!JS_IsUndefined(val)) {\n            js_dump_obj(ctx, stderr, val);\n        }\n        JS_FreeValue(ctx, val);\n    }\n}\n\nvoid js_std_dump_error(JSContext *ctx)\n{\n    JSValue exception_val;\n    \n    exception_val = JS_GetException(ctx);\n    js_std_dump_error1(ctx, exception_val);\n    JS_FreeValue(ctx, exception_val);\n}\n\nvoid js_std_promise_rejection_tracker(JSContext *ctx, JSValueConst promise,\n                                      JSValueConst reason,\n                                      BOOL is_handled, void *opaque)\n{\n    if (!is_handled) {\n        fprintf(stderr, \"Possibly unhandled promise rejection: \");\n        js_std_dump_error1(ctx, reason);\n    }\n}\n\n/* main loop which calls the user JS callbacks */\nvoid js_std_loop(JSContext *ctx)\n{\n    JSContext *ctx1;\n    int err;\n\n    for(;;) {\n        /* execute the pending jobs */\n        for(;;) {\n            err = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1);\n            if (err <= 0) {\n                if (err < 0) {\n                    js_std_dump_error(ctx1);\n                }\n                break;\n            }\n        }\n\n        if (!os_poll_func || os_poll_func(ctx))\n            break;\n    }\n}\n\nvoid js_std_eval_binary(JSContext *ctx, const uint8_t *buf, size_t buf_len,\n                        int load_only)\n{\n    JSValue obj, val;\n    obj = JS_ReadObject(ctx, buf, buf_len, JS_READ_OBJ_BYTECODE);\n    if (JS_IsException(obj))\n        goto exception;\n    if (load_only) {\n        if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) {\n            js_module_set_import_meta(ctx, obj, FALSE, FALSE);\n        }\n    } else {\n        if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) {\n            if (JS_ResolveModule(ctx, obj) < 0) {\n                JS_FreeValue(ctx, obj);\n                goto exception;\n            }\n            js_module_set_import_meta(ctx, obj, FALSE, TRUE);\n        }\n        val = JS_EvalFunction(ctx, obj);\n        if (JS_IsException(val)) {\n        exception:\n            js_std_dump_error(ctx);\n            exit(1);\n        }\n        JS_FreeValue(ctx, val);\n    }\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/quickjs-libc.h",
    "content": "/*\n * QuickJS C library\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#ifndef QUICKJS_LIBC_H\n#define QUICKJS_LIBC_H\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"quickjs.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nJSModuleDef *js_init_module_std(JSContext *ctx, const char *module_name);\nJSModuleDef *js_init_module_os(JSContext *ctx, const char *module_name);\nvoid js_std_add_helpers(JSContext *ctx, int argc, char **argv);\nvoid js_std_loop(JSContext *ctx);\nvoid js_std_init_handlers(JSRuntime *rt);\nvoid js_std_free_handlers(JSRuntime *rt);\nvoid js_std_dump_error(JSContext *ctx);\nuint8_t *js_load_file(JSContext *ctx, size_t *pbuf_len, const char *filename);\nint js_module_set_import_meta(JSContext *ctx, JSValueConst func_val,\n                              JS_BOOL use_realpath, JS_BOOL is_main);\nJSModuleDef *js_module_loader(JSContext *ctx,\n                              const char *module_name, void *opaque);\nvoid js_std_eval_binary(JSContext *ctx, const uint8_t *buf, size_t buf_len,\n                        int flags);\nvoid js_std_promise_rejection_tracker(JSContext *ctx, JSValueConst promise,\n                                      JSValueConst reason,\n                                      JS_BOOL is_handled, void *opaque);\nvoid js_std_set_worker_new_context_func(JSContext *(*func)(JSRuntime *rt));\n                                        \n#ifdef __cplusplus\n} /* extern \"C\" { */\n#endif\n\n#endif /* QUICKJS_LIBC_H */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/quickjs-opcode.h",
    "content": "/*\n * QuickJS opcode definitions\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n * Copyright (c) 2017-2018 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n#ifdef FMT\nFMT(none)\nFMT(none_int)\nFMT(none_loc)\nFMT(none_arg)\nFMT(none_var_ref)\nFMT(u8)\nFMT(i8)\nFMT(loc8)\nFMT(const8)\nFMT(label8)\nFMT(u16)\nFMT(i16)\nFMT(label16)\nFMT(npop)\nFMT(npopx)\nFMT(npop_u16)\nFMT(loc)\nFMT(arg)\nFMT(var_ref)\nFMT(u32)\nFMT(i32)\nFMT(const)\nFMT(label)\nFMT(atom)\nFMT(atom_u8)\nFMT(atom_u16)\nFMT(atom_label_u8)\nFMT(atom_label_u16)\nFMT(label_u16)\n#undef FMT\n#endif /* FMT */\n\n#ifdef DEF\n\n#ifndef def\n#define def(id, size, n_pop, n_push, f) DEF(id, size, n_pop, n_push, f)\n#endif\n\nDEF(invalid, 1, 0, 0, none) /* never emitted */\n\n/* push values */\nDEF(       push_i32, 5, 0, 1, i32)\nDEF(     push_const, 5, 0, 1, const)\nDEF(       fclosure, 5, 0, 1, const) /* must follow push_const */\nDEF(push_atom_value, 5, 0, 1, atom)\nDEF( private_symbol, 5, 0, 1, atom)\nDEF(      undefined, 1, 0, 1, none)\nDEF(           null, 1, 0, 1, none)\nDEF(      push_this, 1, 0, 1, none) /* only used at the start of a function */\nDEF(     push_false, 1, 0, 1, none)\nDEF(      push_true, 1, 0, 1, none)\nDEF(         object, 1, 0, 1, none)\nDEF( special_object, 2, 0, 1, u8) /* only used at the start of a function */\nDEF(           rest, 3, 0, 1, u16) /* only used at the start of a function */\n\nDEF(           drop, 1, 1, 0, none) /* a -> */\nDEF(            nip, 1, 2, 1, none) /* a b -> b */\nDEF(           nip1, 1, 3, 2, none) /* a b c -> b c */\nDEF(            dup, 1, 1, 2, none) /* a -> a a */\nDEF(           dup1, 1, 2, 3, none) /* a b -> a a b */\nDEF(           dup2, 1, 2, 4, none) /* a b -> a b a b */\nDEF(           dup3, 1, 3, 6, none) /* a b c -> a b c a b c */\nDEF(        insert2, 1, 2, 3, none) /* obj a -> a obj a (dup_x1) */\nDEF(        insert3, 1, 3, 4, none) /* obj prop a -> a obj prop a (dup_x2) */\nDEF(        insert4, 1, 4, 5, none) /* this obj prop a -> a this obj prop a */\nDEF(          perm3, 1, 3, 3, none) /* obj a b -> a obj b */\nDEF(          perm4, 1, 4, 4, none) /* obj prop a b -> a obj prop b */\nDEF(          perm5, 1, 5, 5, none) /* this obj prop a b -> a this obj prop b */\nDEF(           swap, 1, 2, 2, none) /* a b -> b a */\nDEF(          swap2, 1, 4, 4, none) /* a b c d -> c d a b */\nDEF(          rot3l, 1, 3, 3, none) /* x a b -> a b x */\nDEF(          rot3r, 1, 3, 3, none) /* a b x -> x a b */\nDEF(          rot4l, 1, 4, 4, none) /* x a b c -> a b c x */\nDEF(          rot5l, 1, 5, 5, none) /* x a b c d -> a b c d x */\n\nDEF(call_constructor, 3, 2, 1, npop) /* func new.target args -> ret. arguments are not counted in n_pop */\nDEF(           call, 3, 1, 1, npop) /* arguments are not counted in n_pop */\nDEF(      tail_call, 3, 1, 0, npop) /* arguments are not counted in n_pop */\nDEF(    call_method, 3, 2, 1, npop) /* arguments are not counted in n_pop */\nDEF(tail_call_method, 3, 2, 0, npop) /* arguments are not counted in n_pop */\nDEF(     array_from, 3, 0, 1, npop) /* arguments are not counted in n_pop */\nDEF(          apply, 3, 3, 1, u16)\nDEF(         return, 1, 1, 0, none)\nDEF(   return_undef, 1, 0, 0, none)\nDEF(check_ctor_return, 1, 1, 2, none)\nDEF(     check_ctor, 1, 0, 0, none)\nDEF(    check_brand, 1, 2, 2, none) /* this_obj func -> this_obj func */\nDEF(      add_brand, 1, 2, 0, none) /* this_obj home_obj -> */\nDEF(   return_async, 1, 1, 0, none)\nDEF(          throw, 1, 1, 0, none)\nDEF(    throw_error, 6, 0, 0, atom_u8)\nDEF(           eval, 5, 1, 1, npop_u16) /* func args... -> ret_val */\nDEF(     apply_eval, 3, 2, 1, u16) /* func array -> ret_eval */\nDEF(         regexp, 1, 2, 1, none) /* create a RegExp object from the pattern and a\n                                       bytecode string */\nDEF(      get_super, 1, 1, 1, none)\nDEF(         import, 1, 1, 1, none) /* dynamic module import */\n\nDEF(      check_var, 5, 0, 1, atom) /* check if a variable exists */\nDEF(  get_var_undef, 5, 0, 1, atom) /* push undefined if the variable does not exist */\nDEF(        get_var, 5, 0, 1, atom) /* throw an exception if the variable does not exist */\nDEF(        put_var, 5, 1, 0, atom) /* must come after get_var */\nDEF(   put_var_init, 5, 1, 0, atom) /* must come after put_var. Used to initialize a global lexical variable */\nDEF( put_var_strict, 5, 2, 0, atom) /* for strict mode variable write */\n\nDEF(  get_ref_value, 1, 2, 3, none)\nDEF(  put_ref_value, 1, 3, 0, none)\n\nDEF(     define_var, 6, 0, 0, atom_u8)\nDEF(check_define_var, 6, 0, 0, atom_u8)\nDEF(    define_func, 6, 1, 0, atom_u8)\nDEF(      get_field, 5, 1, 1, atom)\nDEF(     get_field2, 5, 1, 2, atom)\nDEF(      put_field, 5, 2, 0, atom)\nDEF( get_private_field, 1, 2, 1, none) /* obj prop -> value */\nDEF( put_private_field, 1, 3, 0, none) /* obj value prop -> */\nDEF(define_private_field, 1, 3, 1, none) /* obj prop value -> obj */\nDEF(   get_array_el, 1, 2, 1, none)\nDEF(  get_array_el2, 1, 2, 2, none) /* obj prop -> obj value */\nDEF(   put_array_el, 1, 3, 0, none)\nDEF(get_super_value, 1, 3, 1, none) /* this obj prop -> value */\nDEF(put_super_value, 1, 4, 0, none) /* this obj prop value -> */\nDEF(   define_field, 5, 2, 1, atom)\nDEF(       set_name, 5, 1, 1, atom)\nDEF(set_name_computed, 1, 2, 2, none)\nDEF(      set_proto, 1, 2, 1, none)\nDEF(set_home_object, 1, 2, 2, none)\nDEF(define_array_el, 1, 3, 2, none)\nDEF(         append, 1, 3, 2, none) /* append enumerated object, update length */\nDEF(copy_data_properties, 2, 3, 3, u8)\nDEF(  define_method, 6, 2, 1, atom_u8)\nDEF(define_method_computed, 2, 3, 1, u8) /* must come after define_method */\nDEF(   define_class, 6, 2, 2, atom_u8) /* parent ctor -> ctor proto */\nDEF(   define_class_computed, 6, 3, 3, atom_u8) /* field_name parent ctor -> field_name ctor proto (class with computed name) */\n\nDEF(        get_loc, 3, 0, 1, loc)\nDEF(        put_loc, 3, 1, 0, loc) /* must come after get_loc */\nDEF(        set_loc, 3, 1, 1, loc) /* must come after put_loc */\nDEF(        get_arg, 3, 0, 1, arg)\nDEF(        put_arg, 3, 1, 0, arg) /* must come after get_arg */\nDEF(        set_arg, 3, 1, 1, arg) /* must come after put_arg */\nDEF(    get_var_ref, 3, 0, 1, var_ref) \nDEF(    put_var_ref, 3, 1, 0, var_ref) /* must come after get_var_ref */\nDEF(    set_var_ref, 3, 1, 1, var_ref) /* must come after put_var_ref */\nDEF(set_loc_uninitialized, 3, 0, 0, loc)\nDEF(  get_loc_check, 3, 0, 1, loc)\nDEF(  put_loc_check, 3, 1, 0, loc) /* must come after get_loc_check */\nDEF(  put_loc_check_init, 3, 1, 0, loc)\nDEF(get_var_ref_check, 3, 0, 1, var_ref) \nDEF(put_var_ref_check, 3, 1, 0, var_ref) /* must come after get_var_ref_check */\nDEF(put_var_ref_check_init, 3, 1, 0, var_ref)\nDEF(      close_loc, 3, 0, 0, loc)\nDEF(       if_false, 5, 1, 0, label)\nDEF(        if_true, 5, 1, 0, label) /* must come after if_false */\nDEF(           goto, 5, 0, 0, label) /* must come after if_true */\nDEF(          catch, 5, 0, 1, label)\nDEF(          gosub, 5, 0, 0, label) /* used to execute the finally block */\nDEF(            ret, 1, 1, 0, none) /* used to return from the finally block */\n\nDEF(      to_object, 1, 1, 1, none)\n//DEF(      to_string, 1, 1, 1, none)\nDEF(     to_propkey, 1, 1, 1, none)\nDEF(    to_propkey2, 1, 2, 2, none)\n\nDEF(   with_get_var, 10, 1, 0, atom_label_u8)     /* must be in the same order as scope_xxx */\nDEF(   with_put_var, 10, 2, 1, atom_label_u8)     /* must be in the same order as scope_xxx */\nDEF(with_delete_var, 10, 1, 0, atom_label_u8)     /* must be in the same order as scope_xxx */\nDEF(  with_make_ref, 10, 1, 0, atom_label_u8)     /* must be in the same order as scope_xxx */\nDEF(   with_get_ref, 10, 1, 0, atom_label_u8)     /* must be in the same order as scope_xxx */\nDEF(with_get_ref_undef, 10, 1, 0, atom_label_u8)\n\nDEF(   make_loc_ref, 7, 0, 2, atom_u16)\nDEF(   make_arg_ref, 7, 0, 2, atom_u16)\nDEF(make_var_ref_ref, 7, 0, 2, atom_u16)\nDEF(   make_var_ref, 5, 0, 2, atom)\n\nDEF(   for_in_start, 1, 1, 1, none)\nDEF(   for_of_start, 1, 1, 3, none)\nDEF(for_await_of_start, 1, 1, 3, none)\nDEF(    for_in_next, 1, 1, 3, none)\nDEF(    for_of_next, 2, 3, 5, u8)\nDEF(iterator_check_object, 1, 1, 1, none)\nDEF(iterator_get_value_done, 1, 1, 2, none)\nDEF( iterator_close, 1, 3, 0, none)\nDEF(iterator_close_return, 1, 4, 4, none)\nDEF(  iterator_next, 1, 4, 4, none)\nDEF(  iterator_call, 2, 4, 5, u8)\nDEF(  initial_yield, 1, 0, 0, none)\nDEF(          yield, 1, 1, 2, none)\nDEF(     yield_star, 1, 1, 2, none)\nDEF(async_yield_star, 1, 1, 2, none)\nDEF(          await, 1, 1, 1, none)\n\n/* arithmetic/logic operations */\nDEF(            neg, 1, 1, 1, none)\nDEF(           plus, 1, 1, 1, none)\nDEF(            dec, 1, 1, 1, none)\nDEF(            inc, 1, 1, 1, none)\nDEF(       post_dec, 1, 1, 2, none)\nDEF(       post_inc, 1, 1, 2, none)\nDEF(        dec_loc, 2, 0, 0, loc8)\nDEF(        inc_loc, 2, 0, 0, loc8)\nDEF(        add_loc, 2, 1, 0, loc8)\nDEF(            not, 1, 1, 1, none)\nDEF(           lnot, 1, 1, 1, none)\nDEF(         typeof, 1, 1, 1, none)\nDEF(         delete, 1, 2, 1, none)\nDEF(     delete_var, 5, 0, 1, atom)\n\nDEF(            mul, 1, 2, 1, none)\nDEF(            div, 1, 2, 1, none)\nDEF(            mod, 1, 2, 1, none)\nDEF(            add, 1, 2, 1, none)\nDEF(            sub, 1, 2, 1, none)\nDEF(            pow, 1, 2, 1, none)\nDEF(            shl, 1, 2, 1, none)\nDEF(            sar, 1, 2, 1, none)\nDEF(            shr, 1, 2, 1, none)\nDEF(             lt, 1, 2, 1, none)\nDEF(            lte, 1, 2, 1, none)\nDEF(             gt, 1, 2, 1, none)\nDEF(            gte, 1, 2, 1, none)\nDEF(     instanceof, 1, 2, 1, none)\nDEF(             in, 1, 2, 1, none)\nDEF(             eq, 1, 2, 1, none)\nDEF(            neq, 1, 2, 1, none)\nDEF(      strict_eq, 1, 2, 1, none)\nDEF(     strict_neq, 1, 2, 1, none)\nDEF(            and, 1, 2, 1, none)\nDEF(            xor, 1, 2, 1, none)\nDEF(             or, 1, 2, 1, none)\nDEF(is_undefined_or_null, 1, 1, 1, none)\n#ifdef CONFIG_BIGNUM\nDEF(      mul_pow10, 1, 2, 1, none)\nDEF(       math_mod, 1, 2, 1, none)\n#endif\n/* must be the last non short and non temporary opcode */\nDEF(            nop, 1, 0, 0, none) \n\n/* temporary opcodes: never emitted in the final bytecode */\n\ndef(    enter_scope, 3, 0, 0, u16)  /* emitted in phase 1, removed in phase 2 */\ndef(    leave_scope, 3, 0, 0, u16)  /* emitted in phase 1, removed in phase 2 */\n\ndef(          label, 5, 0, 0, label) /* emitted in phase 1, removed in phase 3 */\n\ndef(scope_get_var_undef, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */\ndef(  scope_get_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */\ndef(  scope_put_var, 7, 1, 0, atom_u16) /* emitted in phase 1, removed in phase 2 */\ndef(scope_delete_var, 7, 0, 1, atom_u16) /* emitted in phase 1, removed in phase 2 */\ndef( scope_make_ref, 11, 0, 2, atom_label_u16) /* emitted in phase 1, removed in phase 2 */\ndef(  scope_get_ref, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */\ndef(scope_put_var_init, 7, 0, 2, atom_u16) /* emitted in phase 1, removed in phase 2 */\ndef(scope_get_private_field, 7, 1, 1, atom_u16) /* obj -> value, emitted in phase 1, removed in phase 2 */\ndef(scope_get_private_field2, 7, 1, 2, atom_u16) /* obj -> obj value, emitted in phase 1, removed in phase 2 */\ndef(scope_put_private_field, 7, 1, 1, atom_u16) /* obj value ->, emitted in phase 1, removed in phase 2 */\n\ndef( set_class_name, 5, 1, 1, u32) /* emitted in phase 1, removed in phase 2 */\n    \ndef(       line_num, 5, 0, 0, u32) /* emitted in phase 1, removed in phase 3 */\n\n#if SHORT_OPCODES\nDEF(    push_minus1, 1, 0, 1, none_int)\nDEF(         push_0, 1, 0, 1, none_int)\nDEF(         push_1, 1, 0, 1, none_int)\nDEF(         push_2, 1, 0, 1, none_int)\nDEF(         push_3, 1, 0, 1, none_int)\nDEF(         push_4, 1, 0, 1, none_int)\nDEF(         push_5, 1, 0, 1, none_int)\nDEF(         push_6, 1, 0, 1, none_int)\nDEF(         push_7, 1, 0, 1, none_int)\nDEF(        push_i8, 2, 0, 1, i8)\nDEF(       push_i16, 3, 0, 1, i16)\nDEF(    push_const8, 2, 0, 1, const8)\nDEF(      fclosure8, 2, 0, 1, const8) /* must follow push_const8 */\nDEF(push_empty_string, 1, 0, 1, none)\n\nDEF(       get_loc8, 2, 0, 1, loc8)\nDEF(       put_loc8, 2, 1, 0, loc8)\nDEF(       set_loc8, 2, 1, 1, loc8)\n\nDEF(       get_loc0, 1, 0, 1, none_loc)\nDEF(       get_loc1, 1, 0, 1, none_loc)\nDEF(       get_loc2, 1, 0, 1, none_loc)\nDEF(       get_loc3, 1, 0, 1, none_loc)\nDEF(       put_loc0, 1, 1, 0, none_loc)\nDEF(       put_loc1, 1, 1, 0, none_loc)\nDEF(       put_loc2, 1, 1, 0, none_loc)\nDEF(       put_loc3, 1, 1, 0, none_loc)\nDEF(       set_loc0, 1, 1, 1, none_loc)\nDEF(       set_loc1, 1, 1, 1, none_loc)\nDEF(       set_loc2, 1, 1, 1, none_loc)\nDEF(       set_loc3, 1, 1, 1, none_loc)\nDEF(       get_arg0, 1, 0, 1, none_arg)\nDEF(       get_arg1, 1, 0, 1, none_arg)\nDEF(       get_arg2, 1, 0, 1, none_arg)\nDEF(       get_arg3, 1, 0, 1, none_arg)\nDEF(       put_arg0, 1, 1, 0, none_arg)\nDEF(       put_arg1, 1, 1, 0, none_arg)\nDEF(       put_arg2, 1, 1, 0, none_arg)\nDEF(       put_arg3, 1, 1, 0, none_arg)\nDEF(       set_arg0, 1, 1, 1, none_arg)\nDEF(       set_arg1, 1, 1, 1, none_arg)\nDEF(       set_arg2, 1, 1, 1, none_arg)\nDEF(       set_arg3, 1, 1, 1, none_arg)\nDEF(   get_var_ref0, 1, 0, 1, none_var_ref)\nDEF(   get_var_ref1, 1, 0, 1, none_var_ref)\nDEF(   get_var_ref2, 1, 0, 1, none_var_ref)\nDEF(   get_var_ref3, 1, 0, 1, none_var_ref)\nDEF(   put_var_ref0, 1, 1, 0, none_var_ref)\nDEF(   put_var_ref1, 1, 1, 0, none_var_ref)\nDEF(   put_var_ref2, 1, 1, 0, none_var_ref)\nDEF(   put_var_ref3, 1, 1, 0, none_var_ref)\nDEF(   set_var_ref0, 1, 1, 1, none_var_ref)\nDEF(   set_var_ref1, 1, 1, 1, none_var_ref)\nDEF(   set_var_ref2, 1, 1, 1, none_var_ref)\nDEF(   set_var_ref3, 1, 1, 1, none_var_ref)\n\nDEF(     get_length, 1, 1, 1, none)\n\nDEF(      if_false8, 2, 1, 0, label8)\nDEF(       if_true8, 2, 1, 0, label8) /* must come after if_false8 */\nDEF(          goto8, 2, 0, 0, label8) /* must come after if_true8 */\nDEF(         goto16, 3, 0, 0, label16)\n\nDEF(          call0, 1, 1, 1, npopx)\nDEF(          call1, 1, 1, 1, npopx)\nDEF(          call2, 1, 1, 1, npopx)\nDEF(          call3, 1, 1, 1, npopx)\n\nDEF(   is_undefined, 1, 1, 1, none)\nDEF(        is_null, 1, 1, 1, none)\nDEF(typeof_is_undefined, 1, 1, 1, none)\nDEF( typeof_is_function, 1, 1, 1, none)\n#endif\n\n#undef DEF\n#undef def\n#endif  /* DEF */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/quickjs.c",
    "content": "/*\n * QuickJS Javascript Engine\n * \n * Copyright (c) 2017-2021 Fabrice Bellard\n * Copyright (c) 2017-2021 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <inttypes.h>\n#include <string.h>\n#include <assert.h>\n#ifndef _MSC_VER\n#include <sys/time.h>\n#endif\n#include <time.h>\n#include <fenv.h>\n#include <math.h>\n#if defined(__APPLE__)\n#include <malloc/malloc.h>\n#elif defined(__linux__)\n#include <malloc.h>\n#elif defined(__FreeBSD__)\n#include <malloc_np.h>\n#endif\n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"quickjs.h\"\n#include \"libregexp.h\"\n#ifdef CONFIG_BIGNUM\n#include \"libbf.h\"\n#endif\n\n#define OPTIMIZE         1\n#define SHORT_OPCODES    1\n#if defined(EMSCRIPTEN) || defined(_MSC_VER)\n#define DIRECT_DISPATCH  0\n#else\n#define DIRECT_DISPATCH  1\n#endif\n\n#if defined(__APPLE__)\n#define MALLOC_OVERHEAD  0\n#else\n#define MALLOC_OVERHEAD  8\n#endif\n\n#if !defined(_WIN32)\n/* define it if printf uses the RNDN rounding mode instead of RNDNA */\n#define CONFIG_PRINTF_RNDN\n#endif\n\n/* define to include Atomics.* operations which depend on the OS\n   threads */\n#if !defined(EMSCRIPTEN) && !defined(_MSC_VER)\n#define CONFIG_ATOMICS\n#endif\n\n#if !defined(EMSCRIPTEN)\n/* enable stack limitation */\n#define CONFIG_STACK_CHECK\n#endif\n\n#if defined(JSB_DEF_LOG2)\nstatic double log2(double v) { return log(v) / log(2.0); }\n#endif\n\n/* dump object free */\n//#define DUMP_FREE\n//#define DUMP_CLOSURE\n/* dump the bytecode of the compiled functions: combination of bits\n   1: dump pass 3 final byte code\n   2: dump pass 2 code\n   4: dump pass 1 code\n   8: dump stdlib functions\n  16: dump bytecode in hex\n  32: dump line number table\n */\n//#define DUMP_BYTECODE  (1)\n/* dump the occurence of the automatic GC */\n//#define DUMP_GC\n/* dump objects freed by the garbage collector */\n//#define DUMP_GC_FREE\n/* dump objects leaking when freeing the runtime */\n//#define DUMP_LEAKS  1\n/* dump memory usage before running the garbage collector */\n//#define DUMP_MEM\n//#define DUMP_OBJECTS    /* dump objects in JS_FreeContext */\n//#define DUMP_ATOMS      /* dump atoms in JS_FreeContext */\n//#define DUMP_SHAPES     /* dump shapes in JS_FreeContext */\n//#define DUMP_MODULE_RESOLVE\n//#define DUMP_PROMISE\n//#define DUMP_READ_OBJECT\n\n/* test the GC by forcing it before each object allocation */\n//#define FORCE_GC_AT_MALLOC\n\n#ifdef CONFIG_ATOMICS\n#include <pthread.h>\n#include <stdatomic.h>\n#include <errno.h>\n#endif\n\nenum {\n    /* classid tag        */    /* union usage   | properties */\n    JS_CLASS_OBJECT = 1,        /* must be first */\n    JS_CLASS_ARRAY,             /* u.array       | length */\n    JS_CLASS_ERROR,\n    JS_CLASS_NUMBER,            /* u.object_data */\n    JS_CLASS_STRING,            /* u.object_data */\n    JS_CLASS_BOOLEAN,           /* u.object_data */\n    JS_CLASS_SYMBOL,            /* u.object_data */\n    JS_CLASS_ARGUMENTS,         /* u.array       | length */\n    JS_CLASS_MAPPED_ARGUMENTS,  /*               | length */\n    JS_CLASS_DATE,              /* u.object_data */\n    JS_CLASS_MODULE_NS,\n    JS_CLASS_C_FUNCTION,        /* u.cfunc */\n    JS_CLASS_BYTECODE_FUNCTION, /* u.func */\n    JS_CLASS_BOUND_FUNCTION,    /* u.bound_function */\n    JS_CLASS_C_FUNCTION_DATA,   /* u.c_function_data_record */\n    JS_CLASS_GENERATOR_FUNCTION, /* u.func */\n    JS_CLASS_FOR_IN_ITERATOR,   /* u.for_in_iterator */\n    JS_CLASS_REGEXP,            /* u.regexp */\n    JS_CLASS_ARRAY_BUFFER,      /* u.array_buffer */\n    JS_CLASS_SHARED_ARRAY_BUFFER, /* u.array_buffer */\n    JS_CLASS_UINT8C_ARRAY,      /* u.array (typed_array) */\n    JS_CLASS_INT8_ARRAY,        /* u.array (typed_array) */\n    JS_CLASS_UINT8_ARRAY,       /* u.array (typed_array) */\n    JS_CLASS_INT16_ARRAY,       /* u.array (typed_array) */\n    JS_CLASS_UINT16_ARRAY,      /* u.array (typed_array) */\n    JS_CLASS_INT32_ARRAY,       /* u.array (typed_array) */\n    JS_CLASS_UINT32_ARRAY,      /* u.array (typed_array) */\n#ifdef CONFIG_BIGNUM\n    JS_CLASS_BIG_INT64_ARRAY,   /* u.array (typed_array) */\n    JS_CLASS_BIG_UINT64_ARRAY,  /* u.array (typed_array) */\n#endif\n    JS_CLASS_FLOAT32_ARRAY,     /* u.array (typed_array) */\n    JS_CLASS_FLOAT64_ARRAY,     /* u.array (typed_array) */\n    JS_CLASS_DATAVIEW,          /* u.typed_array */\n#ifdef CONFIG_BIGNUM\n    JS_CLASS_BIG_INT,           /* u.object_data */\n    JS_CLASS_BIG_FLOAT,         /* u.object_data */\n    JS_CLASS_FLOAT_ENV,         /* u.float_env */\n    JS_CLASS_BIG_DECIMAL,       /* u.object_data */\n    JS_CLASS_OPERATOR_SET,      /* u.operator_set */\n#endif\n    JS_CLASS_MAP,               /* u.map_state */\n    JS_CLASS_SET,               /* u.map_state */\n    JS_CLASS_WEAKMAP,           /* u.map_state */\n    JS_CLASS_WEAKSET,           /* u.map_state */\n    JS_CLASS_MAP_ITERATOR,      /* u.map_iterator_data */\n    JS_CLASS_SET_ITERATOR,      /* u.map_iterator_data */\n    JS_CLASS_ARRAY_ITERATOR,    /* u.array_iterator_data */\n    JS_CLASS_STRING_ITERATOR,   /* u.array_iterator_data */\n    JS_CLASS_REGEXP_STRING_ITERATOR,   /* u.regexp_string_iterator_data */\n    JS_CLASS_GENERATOR,         /* u.generator_data */\n    JS_CLASS_PROXY,             /* u.proxy_data */\n    JS_CLASS_PROMISE,           /* u.promise_data */\n    JS_CLASS_PROMISE_RESOLVE_FUNCTION,  /* u.promise_function_data */\n    JS_CLASS_PROMISE_REJECT_FUNCTION,   /* u.promise_function_data */\n    JS_CLASS_ASYNC_FUNCTION,            /* u.func */\n    JS_CLASS_ASYNC_FUNCTION_RESOLVE,    /* u.async_function_data */\n    JS_CLASS_ASYNC_FUNCTION_REJECT,     /* u.async_function_data */\n    JS_CLASS_ASYNC_FROM_SYNC_ITERATOR,  /* u.async_from_sync_iterator_data */\n    JS_CLASS_ASYNC_GENERATOR_FUNCTION,  /* u.func */\n    JS_CLASS_ASYNC_GENERATOR,   /* u.async_generator_data */\n\n    JS_CLASS_INIT_COUNT, /* last entry for predefined classes */\n};\n\n/* number of typed array types */\n#define JS_TYPED_ARRAY_COUNT  (JS_CLASS_FLOAT64_ARRAY - JS_CLASS_UINT8C_ARRAY + 1)\nstatic uint8_t const typed_array_size_log2[JS_TYPED_ARRAY_COUNT];\n#define typed_array_size_log2(classid)  (typed_array_size_log2[(classid)- JS_CLASS_UINT8C_ARRAY])\n\ntypedef enum JSErrorEnum {\n    JS_EVAL_ERROR,\n    JS_RANGE_ERROR,\n    JS_REFERENCE_ERROR,\n    JS_SYNTAX_ERROR,\n    JS_TYPE_ERROR,\n    JS_URI_ERROR,\n    JS_INTERNAL_ERROR,\n    JS_AGGREGATE_ERROR,\n    \n    JS_NATIVE_ERROR_COUNT, /* number of different NativeError objects */\n} JSErrorEnum;\n\n#define JS_MAX_LOCAL_VARS 65536\n#define JS_STACK_SIZE_MAX 65534\n#define JS_STRING_LEN_MAX ((1 << 30) - 1)\n\n#define __exception __attribute__((warn_unused_result))\n\ntypedef struct JSShape JSShape;\ntypedef struct JSString JSString;\ntypedef struct JSString JSAtomStruct;\n\ntypedef enum {\n    JS_GC_PHASE_NONE,\n    JS_GC_PHASE_DECREF,\n    JS_GC_PHASE_REMOVE_CYCLES,\n} JSGCPhaseEnum;\n\ntypedef enum OPCodeEnum OPCodeEnum;\n\n#ifdef CONFIG_BIGNUM\n/* function pointers are used for numeric operations so that it is\n   possible to remove some numeric types */\ntypedef struct {\n    JSValue (*to_string)(JSContext *ctx, JSValueConst val);\n    JSValue (*from_string)(JSContext *ctx, const char *buf,\n                           int radix, int flags, slimb_t *pexponent);\n    int (*unary_arith)(JSContext *ctx,\n                       JSValue *pres, OPCodeEnum op, JSValue op1);\n    int (*binary_arith)(JSContext *ctx, OPCodeEnum op,\n                        JSValue *pres, JSValue op1, JSValue op2);\n    int (*compare)(JSContext *ctx, OPCodeEnum op,\n                   JSValue op1, JSValue op2);\n    /* only for bigfloat: */\n    JSValue (*mul_pow10_to_float64)(JSContext *ctx, const bf_t *a,\n                                    int64_t exponent);\n    int (*mul_pow10)(JSContext *ctx, JSValue *sp);\n} JSNumericOperations;\n#endif\n\nstruct JSRuntime {\n    JSMallocFunctions mf;\n    JSMallocState malloc_state;\n    const char *rt_info;\n\n    int atom_hash_size; /* power of two */\n    int atom_count;\n    int atom_size;\n    int atom_count_resize; /* resize hash table at this count */\n    uint32_t *atom_hash;\n    JSAtomStruct **atom_array;\n    int atom_free_index; /* 0 = none */\n\n    int class_count;    /* size of class_array */\n    JSClass *class_array;\n\n    struct list_head context_list; /* list of JSContext.link */\n    /* list of JSGCObjectHeader.link. List of allocated GC objects (used\n       by the garbage collector) */\n    struct list_head gc_obj_list;\n    /* list of JSGCObjectHeader.link. Used during JS_FreeValueRT() */\n    struct list_head gc_zero_ref_count_list; \n    struct list_head tmp_obj_list; /* used during GC */\n    JSGCPhaseEnum gc_phase : 8;\n    size_t malloc_gc_threshold;\n#ifdef DUMP_LEAKS\n    struct list_head string_list; /* list of JSString.link */\n#endif\n    /* stack limitation */\n    uintptr_t stack_size; /* in bytes, 0 if no limit */\n    uintptr_t stack_top;\n    uintptr_t stack_limit; /* lower stack limit */\n    \n    JSValue current_exception;\n    /* true if inside an out of memory error, to avoid recursing */\n    BOOL in_out_of_memory : 8;\n\n    struct JSStackFrame *current_stack_frame;\n\n    JSInterruptHandler *interrupt_handler;\n    void *interrupt_opaque;\n\n    JSHostPromiseRejectionTracker *host_promise_rejection_tracker;\n    void *host_promise_rejection_tracker_opaque;\n    \n    struct list_head job_list; /* list of JSJobEntry.link */\n\n    JSModuleNormalizeFunc *module_normalize_func;\n    JSModuleLoaderFunc *module_loader_func;\n    void *module_loader_opaque;\n\n    BOOL can_block : 8; /* TRUE if Atomics.wait can block */\n    /* used to allocate, free and clone SharedArrayBuffers */\n    JSSharedArrayBufferFunctions sab_funcs;\n    \n    /* Shape hash table */\n    int shape_hash_bits;\n    int shape_hash_size;\n    int shape_hash_count; /* number of hashed shapes */\n    JSShape **shape_hash;\n#ifdef CONFIG_BIGNUM\n    bf_context_t bf_ctx;\n    JSNumericOperations bigint_ops;\n    JSNumericOperations bigfloat_ops;\n    JSNumericOperations bigdecimal_ops;\n    uint32_t operator_count;\n#endif\n    void *user_opaque;\n};\n\nstruct JSClass {\n    uint32_t class_id; /* 0 means free entry */\n    JSAtom class_name;\n    JSClassFinalizer *finalizer;\n    JSClassGCMark *gc_mark;\n    JSClassCall *call;\n    /* pointers for exotic behavior, can be NULL if none are present */\n    const JSClassExoticMethods *exotic;\n};\n\n#define JS_MODE_STRICT (1 << 0)\n#define JS_MODE_STRIP  (1 << 1)\n#define JS_MODE_MATH   (1 << 2)\n\ntypedef struct JSStackFrame {\n    struct JSStackFrame *prev_frame; /* NULL if first stack frame */\n    JSValue cur_func; /* current function, JS_UNDEFINED if the frame is detached */\n    JSValue *arg_buf; /* arguments */\n    JSValue *var_buf; /* variables */\n    struct list_head var_ref_list; /* list of JSVarRef.link */\n    const uint8_t *cur_pc; /* only used in bytecode functions : PC of the\n                        instruction after the call */\n    int arg_count;\n    int js_mode; /* 0 or JS_MODE_MATH for C functions */\n    /* only used in generators. Current stack pointer value. NULL if\n       the function is running. */ \n    JSValue *cur_sp;\n} JSStackFrame;\n\ntypedef enum {\n    JS_GC_OBJ_TYPE_JS_OBJECT,\n    JS_GC_OBJ_TYPE_FUNCTION_BYTECODE,\n    JS_GC_OBJ_TYPE_SHAPE,\n    JS_GC_OBJ_TYPE_VAR_REF,\n    JS_GC_OBJ_TYPE_ASYNC_FUNCTION,\n    JS_GC_OBJ_TYPE_JS_CONTEXT,\n} JSGCObjectTypeEnum;\n\n/* header for GC objects. GC objects are C data structures with a\n   reference count that can reference other GC objects. JS Objects are\n   a particular type of GC object. */\nstruct JSGCObjectHeader {\n    int ref_count; /* must come first, 32-bit */\n    JSGCObjectTypeEnum gc_obj_type : 4;\n    uint8_t mark : 4; /* used by the GC */\n    uint8_t dummy1; /* not used by the GC */\n    uint16_t dummy2; /* not used by the GC */\n    struct list_head link;\n};\n\ntypedef struct JSVarRef {\n    union {\n        JSGCObjectHeader header; /* must come first */\n        struct {\n            int __gc_ref_count; /* corresponds to header.ref_count */\n            uint8_t __gc_mark; /* corresponds to header.mark/gc_obj_type */\n\n            /* 0 : the JSVarRef is on the stack. header.link is an element\n               of JSStackFrame.var_ref_list.\n               1 : the JSVarRef is detached. header.link has the normal meanning \n            */\n            uint8_t is_detached : 1; \n            uint8_t is_arg : 1;\n            uint16_t var_idx; /* index of the corresponding function variable on\n                                 the stack */\n        };\n    };\n    JSValue *pvalue; /* pointer to the value, either on the stack or\n                        to 'value' */\n    JSValue value; /* used when the variable is no longer on the stack */\n} JSVarRef;\n\n#ifdef CONFIG_BIGNUM\ntypedef struct JSFloatEnv {\n    limb_t prec;\n    bf_flags_t flags;\n    unsigned int status;\n} JSFloatEnv;\n\n/* the same structure is used for big integers and big floats. Big\n   integers are never infinite or NaNs */\ntypedef struct JSBigFloat {\n    JSRefCountHeader header; /* must come first, 32-bit */\n    bf_t num;\n} JSBigFloat;\n\ntypedef struct JSBigDecimal {\n    JSRefCountHeader header; /* must come first, 32-bit */\n    bfdec_t num;\n} JSBigDecimal;\n#endif\n\ntypedef enum {\n    JS_AUTOINIT_ID_PROTOTYPE,\n    JS_AUTOINIT_ID_MODULE_NS,\n    JS_AUTOINIT_ID_PROP,\n} JSAutoInitIDEnum;\n\n/* must be large enough to have a negligible runtime cost and small\n   enough to call the interrupt callback often. */\n#define JS_INTERRUPT_COUNTER_INIT 10000\n\nstruct JSContext {\n    JSGCObjectHeader header; /* must come first */\n    JSRuntime *rt;\n    struct list_head link;\n\n    uint16_t binary_object_count;\n    int binary_object_size;\n\n    JSShape *array_shape;   /* initial shape for Array objects */\n\n    JSValue *class_proto;\n    JSValue function_proto;\n    JSValue function_ctor;\n    JSValue array_ctor;\n    JSValue regexp_ctor;\n    JSValue promise_ctor;\n    JSValue native_error_proto[JS_NATIVE_ERROR_COUNT];\n    JSValue iterator_proto;\n    JSValue async_iterator_proto;\n    JSValue array_proto_values;\n    JSValue throw_type_error;\n    JSValue eval_obj;\n\n    JSValue global_obj; /* global object */\n    JSValue global_var_obj; /* contains the global let/const definitions */\n\n    uint64_t random_state;\n#ifdef CONFIG_BIGNUM\n    bf_context_t *bf_ctx;   /* points to rt->bf_ctx, shared by all contexts */\n    JSFloatEnv fp_env; /* global FP environment */\n    BOOL bignum_ext : 8; /* enable math mode */\n    BOOL allow_operator_overloading : 8;\n#endif\n    /* when the counter reaches zero, JSRutime.interrupt_handler is called */\n    int interrupt_counter;\n    BOOL is_error_property_enabled;\n\n    struct list_head loaded_modules; /* list of JSModuleDef.link */\n\n    /* if NULL, RegExp compilation is not supported */\n    JSValue (*compile_regexp)(JSContext *ctx, JSValueConst pattern,\n                              JSValueConst flags);\n    /* if NULL, eval is not supported */\n    JSValue (*eval_internal)(JSContext *ctx, JSValueConst this_obj,\n                             const char *input, size_t input_len,\n                             const char *filename, int flags, int scope_idx);\n    void *user_opaque;\n};\n\ntypedef union JSFloat64Union {\n    double d;\n    uint64_t u64;\n    uint32_t u32[2];\n} JSFloat64Union;\n\nenum {\n    JS_ATOM_TYPE_STRING = 1,\n    JS_ATOM_TYPE_GLOBAL_SYMBOL,\n    JS_ATOM_TYPE_SYMBOL,\n    JS_ATOM_TYPE_PRIVATE,\n};\n\nenum {\n    JS_ATOM_HASH_SYMBOL,\n    JS_ATOM_HASH_PRIVATE,\n};\n\ntypedef enum {\n    JS_ATOM_KIND_STRING,\n    JS_ATOM_KIND_SYMBOL,\n    JS_ATOM_KIND_PRIVATE,\n} JSAtomKindEnum;\n\n#define JS_ATOM_HASH_MASK  ((1 << 30) - 1)\n\nstruct JSString {\n    JSRefCountHeader header; /* must come first, 32-bit */\n    uint32_t len : 31;\n    uint8_t is_wide_char : 1; /* 0 = 8 bits, 1 = 16 bits characters */\n    /* for JS_ATOM_TYPE_SYMBOL: hash = 0, atom_type = 3,\n       for JS_ATOM_TYPE_PRIVATE: hash = 1, atom_type = 3\n       XXX: could change encoding to have one more bit in hash */\n    uint32_t hash : 30;\n    uint8_t atom_type : 2; /* != 0 if atom, JS_ATOM_TYPE_x */\n    uint32_t hash_next; /* atom_index for JS_ATOM_TYPE_SYMBOL */\n#ifdef DUMP_LEAKS\n    struct list_head link; /* string list */\n#endif\n    union {\n        uint8_t str8[0]; /* 8 bit strings will get an extra null terminator */\n        uint16_t str16[0];\n    } u;\n};\n\ntypedef struct JSClosureVar {\n    uint8_t is_local : 1;\n    uint8_t is_arg : 1;\n    uint8_t is_const : 1;\n    uint8_t is_lexical : 1;\n    uint8_t var_kind : 4; /* see JSVarKindEnum */\n    /* 8 bits available */\n    uint16_t var_idx; /* is_local = TRUE: index to a normal variable of the\n                    parent function. otherwise: index to a closure\n                    variable of the parent function */\n    JSAtom var_name;\n} JSClosureVar;\n\n#define ARG_SCOPE_INDEX 1\n#define ARG_SCOPE_END (-2)\n\ntypedef struct JSVarScope {\n    int parent;  /* index into fd->scopes of the enclosing scope */\n    int first;   /* index into fd->vars of the last variable in this scope */\n} JSVarScope;\n\ntypedef enum {\n    /* XXX: add more variable kinds here instead of using bit fields */\n    JS_VAR_NORMAL,\n    JS_VAR_FUNCTION_DECL, /* lexical var with function declaration */\n    JS_VAR_NEW_FUNCTION_DECL, /* lexical var with async/generator\n                                 function declaration */\n    JS_VAR_CATCH,\n    JS_VAR_FUNCTION_NAME, /* function expression name */\n    JS_VAR_PRIVATE_FIELD,\n    JS_VAR_PRIVATE_METHOD,\n    JS_VAR_PRIVATE_GETTER,\n    JS_VAR_PRIVATE_SETTER, /* must come after JS_VAR_PRIVATE_GETTER */\n    JS_VAR_PRIVATE_GETTER_SETTER, /* must come after JS_VAR_PRIVATE_SETTER */\n} JSVarKindEnum;\n\n/* XXX: could use a different structure in bytecode functions to save\n   memory */\ntypedef struct JSVarDef {\n    JSAtom var_name;\n    /* index into fd->scopes of this variable lexical scope */\n    int scope_level;\n    /* during compilation: \n        - if scope_level = 0: scope in which the variable is defined\n        - if scope_level != 0: index into fd->vars of the next\n          variable in the same or enclosing lexical scope\n       in a bytecode function:\n       index into fd->vars of the next\n       variable in the same or enclosing lexical scope\n    */\n    int scope_next;    \n    uint8_t is_const : 1;\n    uint8_t is_lexical : 1;\n    uint8_t is_captured : 1;\n    uint8_t var_kind : 4; /* see JSVarKindEnum */\n    /* only used during compilation: function pool index for lexical\n       variables with var_kind =\n       JS_VAR_FUNCTION_DECL/JS_VAR_NEW_FUNCTION_DECL or scope level of\n       the definition of the 'var' variables (they have scope_level =\n       0) */\n    int func_pool_idx : 24; /* only used during compilation : index in\n                               the constant pool for hoisted function\n                               definition */\n} JSVarDef;\n\n/* for the encoding of the pc2line table */\n#define PC2LINE_BASE     (-1)\n#define PC2LINE_RANGE    5\n#define PC2LINE_OP_FIRST 1\n#define PC2LINE_DIFF_PC_MAX ((255 - PC2LINE_OP_FIRST) / PC2LINE_RANGE)\n\ntypedef enum JSFunctionKindEnum {\n    JS_FUNC_NORMAL = 0,\n    JS_FUNC_GENERATOR = (1 << 0),\n    JS_FUNC_ASYNC = (1 << 1),\n    JS_FUNC_ASYNC_GENERATOR = (JS_FUNC_GENERATOR | JS_FUNC_ASYNC),\n} JSFunctionKindEnum;\n\ntypedef struct JSFunctionBytecode {\n    JSGCObjectHeader header; /* must come first */\n    uint8_t js_mode;\n    uint8_t has_prototype : 1; /* true if a prototype field is necessary */\n    uint8_t has_simple_parameter_list : 1;\n    uint8_t is_derived_class_constructor : 1;\n    /* true if home_object needs to be initialized */\n    uint8_t need_home_object : 1;\n    uint8_t func_kind : 2;\n    uint8_t new_target_allowed : 1;\n    uint8_t super_call_allowed : 1;\n    uint8_t super_allowed : 1;\n    uint8_t arguments_allowed : 1;\n    uint8_t has_debug : 1;\n    uint8_t backtrace_barrier : 1; /* stop backtrace on this function */\n    uint8_t read_only_bytecode : 1;\n    /* XXX: 4 bits available */\n    uint8_t *byte_code_buf; /* (self pointer) */\n    int byte_code_len;\n    JSAtom func_name;\n    JSVarDef *vardefs; /* arguments + local variables (arg_count + var_count) (self pointer) */\n    JSClosureVar *closure_var; /* list of variables in the closure (self pointer) */\n    uint16_t arg_count;\n    uint16_t var_count;\n    uint16_t defined_arg_count; /* for length function property */\n    uint16_t stack_size; /* maximum stack size */\n    JSContext *realm; /* function realm */\n    JSValue *cpool; /* constant pool (self pointer) */\n    int cpool_count;\n    int closure_var_count;\n    struct {\n        /* debug info, move to separate structure to save memory? */\n        JSAtom filename;\n        int line_num;\n        int source_len;\n        int pc2line_len;\n        uint8_t *pc2line_buf;\n        char *source;\n    } debug;\n} JSFunctionBytecode;\n\ntypedef struct JSBoundFunction {\n    JSValue func_obj;\n    JSValue this_val;\n    int argc;\n    JSValue argv[0];\n} JSBoundFunction;\n\ntypedef enum JSIteratorKindEnum {\n    JS_ITERATOR_KIND_KEY,\n    JS_ITERATOR_KIND_VALUE,\n    JS_ITERATOR_KIND_KEY_AND_VALUE,\n} JSIteratorKindEnum;\n\ntypedef struct JSForInIterator {\n    JSValue obj;\n    BOOL is_array;\n    uint32_t array_length;\n    uint32_t idx;\n} JSForInIterator;\n\ntypedef struct JSRegExp {\n    JSString *pattern;\n    JSString *bytecode; /* also contains the flags */\n} JSRegExp;\n\ntypedef struct JSProxyData {\n    JSValue target;\n    JSValue handler;\n    uint8_t is_func;\n    uint8_t is_revoked;\n} JSProxyData;\n\ntypedef struct JSArrayBuffer {\n    int byte_length; /* 0 if detached */\n    uint8_t detached;\n    uint8_t shared; /* if shared, the array buffer cannot be detached */\n    uint8_t *data; /* NULL if detached */\n    struct list_head array_list;\n    void *opaque;\n    JSFreeArrayBufferDataFunc *free_func;\n} JSArrayBuffer;\n\ntypedef struct JSTypedArray {\n    struct list_head link; /* link to arraybuffer */\n    JSObject *obj; /* back pointer to the TypedArray/DataView object */\n    JSObject *buffer; /* based array buffer */\n    uint32_t offset; /* offset in the array buffer */\n    uint32_t length; /* length in the array buffer */\n} JSTypedArray;\n\ntypedef struct JSAsyncFunctionState {\n    JSValue this_val; /* 'this' generator argument */\n    int argc; /* number of function arguments */\n    BOOL throw_flag; /* used to throw an exception in JS_CallInternal() */\n    JSStackFrame frame;\n} JSAsyncFunctionState;\n\n/* XXX: could use an object instead to avoid the\n   JS_TAG_ASYNC_FUNCTION tag for the GC */\ntypedef struct JSAsyncFunctionData {\n    JSGCObjectHeader header; /* must come first */\n    JSValue resolving_funcs[2];\n    BOOL is_active; /* true if the async function state is valid */\n    JSAsyncFunctionState func_state;\n} JSAsyncFunctionData;\n\ntypedef enum {\n   /* binary operators */\n   JS_OVOP_ADD,\n   JS_OVOP_SUB,\n   JS_OVOP_MUL,\n   JS_OVOP_DIV,\n   JS_OVOP_MOD,\n   JS_OVOP_POW,\n   JS_OVOP_OR,\n   JS_OVOP_AND,\n   JS_OVOP_XOR,\n   JS_OVOP_SHL,\n   JS_OVOP_SAR,\n   JS_OVOP_SHR,\n   JS_OVOP_EQ,\n   JS_OVOP_LESS,\n\n   JS_OVOP_BINARY_COUNT,\n   /* unary operators */\n   JS_OVOP_POS = JS_OVOP_BINARY_COUNT,\n   JS_OVOP_NEG,\n   JS_OVOP_INC,\n   JS_OVOP_DEC,\n   JS_OVOP_NOT,\n\n   JS_OVOP_COUNT,\n} JSOverloadableOperatorEnum;\n\ntypedef struct {\n    uint32_t operator_index;\n    JSObject *ops[JS_OVOP_BINARY_COUNT]; /* self operators */\n} JSBinaryOperatorDefEntry;\n\ntypedef struct {\n    int count;\n    JSBinaryOperatorDefEntry *tab;\n} JSBinaryOperatorDef;\n\ntypedef struct {\n    uint32_t operator_counter;\n    BOOL is_primitive; /* OperatorSet for a primitive type */\n    /* NULL if no operator is defined */\n    JSObject *self_ops[JS_OVOP_COUNT]; /* self operators */\n    JSBinaryOperatorDef left;\n    JSBinaryOperatorDef right;\n} JSOperatorSetData;\n\ntypedef struct JSReqModuleEntry {\n    JSAtom module_name;\n    JSModuleDef *module; /* used using resolution */\n} JSReqModuleEntry;\n\ntypedef enum JSExportTypeEnum {\n    JS_EXPORT_TYPE_LOCAL,\n    JS_EXPORT_TYPE_INDIRECT,\n} JSExportTypeEnum;\n\ntypedef struct JSExportEntry {\n    union {\n        struct {\n            int var_idx; /* closure variable index */\n            JSVarRef *var_ref; /* if != NULL, reference to the variable */\n        } local; /* for local export */\n        int req_module_idx; /* module for indirect export */\n    } u;\n    JSExportTypeEnum export_type;\n    JSAtom local_name; /* '*' if export ns from. not used for local\n                          export after compilation */\n    JSAtom export_name; /* exported variable name */\n} JSExportEntry;\n\ntypedef struct JSStarExportEntry {\n    int req_module_idx; /* in req_module_entries */\n} JSStarExportEntry;\n\ntypedef struct JSImportEntry {\n    int var_idx; /* closure variable index */\n    JSAtom import_name;\n    int req_module_idx; /* in req_module_entries */\n} JSImportEntry;\n\nstruct JSModuleDef {\n    JSRefCountHeader header; /* must come first, 32-bit */\n    JSAtom module_name;\n    struct list_head link;\n\n    JSReqModuleEntry *req_module_entries;\n    int req_module_entries_count;\n    int req_module_entries_size;\n\n    JSExportEntry *export_entries;\n    int export_entries_count;\n    int export_entries_size;\n\n    JSStarExportEntry *star_export_entries;\n    int star_export_entries_count;\n    int star_export_entries_size;\n\n    JSImportEntry *import_entries;\n    int import_entries_count;\n    int import_entries_size;\n\n    JSValue module_ns;\n    JSValue func_obj; /* only used for JS modules */\n    JSModuleInitFunc *init_func; /* only used for C modules */\n    BOOL resolved : 8;\n    BOOL func_created : 8;\n    BOOL instantiated : 8;\n    BOOL evaluated : 8;\n    BOOL eval_mark : 8; /* temporary use during js_evaluate_module() */\n    /* true if evaluation yielded an exception. It is saved in\n       eval_exception */\n    BOOL eval_has_exception : 8; \n    JSValue eval_exception;\n    JSValue meta_obj; /* for import.meta */\n};\n\ntypedef struct JSJobEntry {\n    struct list_head link;\n    JSContext *ctx;\n    JSJobFunc *job_func;\n    int argc;\n    JSValue argv[0];\n} JSJobEntry;\n\ntypedef struct JSProperty {\n    union {\n        JSValue value;      /* JS_PROP_NORMAL */\n        struct {            /* JS_PROP_GETSET */\n            JSObject *getter; /* NULL if undefined */\n            JSObject *setter; /* NULL if undefined */\n        } getset;\n        JSVarRef *var_ref;  /* JS_PROP_VARREF */\n        struct {            /* JS_PROP_AUTOINIT */\n            /* in order to use only 2 pointers, we compress the realm\n               and the init function pointer */\n            uintptr_t realm_and_id; /* realm and init_id (JS_AUTOINIT_ID_x)\n                                       in the 2 low bits */\n            void *opaque;\n        } init;\n    } u;\n} JSProperty;\n\n#define JS_PROP_INITIAL_SIZE 2\n#define JS_PROP_INITIAL_HASH_SIZE 4 /* must be a power of two */\n#define JS_ARRAY_INITIAL_SIZE 2\n\ntypedef struct JSShapeProperty {\n    uint32_t hash_next : 26; /* 0 if last in list */\n    uint32_t flags : 6;   /* JS_PROP_XXX */\n    JSAtom atom; /* JS_ATOM_NULL = free property entry */\n} JSShapeProperty;\n\nstruct JSShape {\n    /* hash table of size hash_mask + 1 before the start of the\n       structure (see prop_hash_end()). */\n    JSGCObjectHeader header;\n    /* true if the shape is inserted in the shape hash table. If not,\n       JSShape.hash is not valid */\n    uint8_t is_hashed;\n    /* If true, the shape may have small array index properties 'n' with 0\n       <= n <= 2^31-1. If false, the shape is guaranteed not to have\n       small array index properties */\n    uint8_t has_small_array_index;\n    uint32_t hash; /* current hash value */\n    uint32_t prop_hash_mask;\n    int prop_size; /* allocated properties */\n    int prop_count; /* include deleted properties */\n    int deleted_prop_count;\n    JSShape *shape_hash_next; /* in JSRuntime.shape_hash[h] list */\n    JSObject *proto;\n    JSShapeProperty prop[0]; /* prop_size elements */\n};\n\nstruct JSObject {\n    union {\n        JSGCObjectHeader header;\n        struct {\n            int __gc_ref_count; /* corresponds to header.ref_count */\n            uint8_t __gc_mark; /* corresponds to header.mark/gc_obj_type */\n            \n            uint8_t extensible : 1;\n            uint8_t free_mark : 1; /* only used when freeing objects with cycles */\n            uint8_t is_exotic : 1; /* TRUE if object has exotic property handlers */\n            uint8_t fast_array : 1; /* TRUE if u.array is used for get/put (for JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS and typed arrays) */\n            uint8_t is_constructor : 1; /* TRUE if object is a constructor function */\n            uint8_t is_uncatchable_error : 1; /* if TRUE, error is not catchable */\n            uint8_t tmp_mark : 1; /* used in JS_WriteObjectRec() */\n            uint8_t is_HTMLDDA : 1; /* specific annex B IsHtmlDDA behavior */\n            uint16_t class_id; /* see JS_CLASS_x */\n        };\n    };\n    /* byte offsets: 16/24 */\n    JSShape *shape; /* prototype and property names + flag */\n    JSProperty *prop; /* array of properties */\n    /* byte offsets: 24/40 */\n    struct JSMapRecord *first_weak_ref; /* XXX: use a bit and an external hash table? */\n    /* byte offsets: 28/48 */\n    union {\n        void *opaque;\n        struct JSBoundFunction *bound_function; /* JS_CLASS_BOUND_FUNCTION */\n        struct JSCFunctionDataRecord *c_function_data_record; /* JS_CLASS_C_FUNCTION_DATA */\n        struct JSForInIterator *for_in_iterator; /* JS_CLASS_FOR_IN_ITERATOR */\n        struct JSArrayBuffer *array_buffer; /* JS_CLASS_ARRAY_BUFFER, JS_CLASS_SHARED_ARRAY_BUFFER */\n        struct JSTypedArray *typed_array; /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_DATAVIEW */\n#ifdef CONFIG_BIGNUM\n        struct JSFloatEnv *float_env; /* JS_CLASS_FLOAT_ENV */\n        struct JSOperatorSetData *operator_set; /* JS_CLASS_OPERATOR_SET */\n#endif\n        struct JSMapState *map_state;   /* JS_CLASS_MAP..JS_CLASS_WEAKSET */\n        struct JSMapIteratorData *map_iterator_data; /* JS_CLASS_MAP_ITERATOR, JS_CLASS_SET_ITERATOR */\n        struct JSArrayIteratorData *array_iterator_data; /* JS_CLASS_ARRAY_ITERATOR, JS_CLASS_STRING_ITERATOR */\n        struct JSRegExpStringIteratorData *regexp_string_iterator_data; /* JS_CLASS_REGEXP_STRING_ITERATOR */\n        struct JSGeneratorData *generator_data; /* JS_CLASS_GENERATOR */\n        struct JSProxyData *proxy_data; /* JS_CLASS_PROXY */\n        struct JSPromiseData *promise_data; /* JS_CLASS_PROMISE */\n        struct JSPromiseFunctionData *promise_function_data; /* JS_CLASS_PROMISE_RESOLVE_FUNCTION, JS_CLASS_PROMISE_REJECT_FUNCTION */\n        struct JSAsyncFunctionData *async_function_data; /* JS_CLASS_ASYNC_FUNCTION_RESOLVE, JS_CLASS_ASYNC_FUNCTION_REJECT */\n        struct JSAsyncFromSyncIteratorData *async_from_sync_iterator_data; /* JS_CLASS_ASYNC_FROM_SYNC_ITERATOR */\n        struct JSAsyncGeneratorData *async_generator_data; /* JS_CLASS_ASYNC_GENERATOR */\n        struct { /* JS_CLASS_BYTECODE_FUNCTION: 12/24 bytes */\n            /* also used by JS_CLASS_GENERATOR_FUNCTION, JS_CLASS_ASYNC_FUNCTION and JS_CLASS_ASYNC_GENERATOR_FUNCTION */\n            struct JSFunctionBytecode *function_bytecode;\n            JSVarRef **var_refs;\n            JSObject *home_object; /* for 'super' access */\n        } func;\n        struct { /* JS_CLASS_C_FUNCTION: 12/20 bytes */\n            JSContext *realm;\n            JSCFunctionType c_function;\n            uint8_t length;\n            uint8_t cproto;\n            int32_t magic;\n        } cfunc;\n        /* array part for fast arrays and typed arrays */\n        struct { /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS, JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */\n            union {\n                uint32_t size;          /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS */\n                struct JSTypedArray *typed_array; /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */\n            } u1;\n            union {\n                JSValue *values;        /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS */ \n                void *ptr;              /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */\n                int8_t *int8_ptr;       /* JS_CLASS_INT8_ARRAY */\n                uint8_t *uint8_ptr;     /* JS_CLASS_UINT8_ARRAY, JS_CLASS_UINT8C_ARRAY */\n                int16_t *int16_ptr;     /* JS_CLASS_INT16_ARRAY */\n                uint16_t *uint16_ptr;   /* JS_CLASS_UINT16_ARRAY */\n                int32_t *int32_ptr;     /* JS_CLASS_INT32_ARRAY */\n                uint32_t *uint32_ptr;   /* JS_CLASS_UINT32_ARRAY */\n                int64_t *int64_ptr;     /* JS_CLASS_INT64_ARRAY */\n                uint64_t *uint64_ptr;   /* JS_CLASS_UINT64_ARRAY */\n                float *float_ptr;       /* JS_CLASS_FLOAT32_ARRAY */\n                double *double_ptr;     /* JS_CLASS_FLOAT64_ARRAY */\n            } u;\n            uint32_t count; /* <= 2^31-1. 0 for a detached typed array */\n        } array;    /* 12/20 bytes */\n        JSRegExp regexp;    /* JS_CLASS_REGEXP: 8/16 bytes */\n        JSValue object_data;    /* for JS_SetObjectData(): 8/16/16 bytes */\n    } u;\n    /* byte sizes: 40/48/72 */\n};\nenum {\n    __JS_ATOM_NULL = JS_ATOM_NULL,\n#define DEF(name, str) JS_ATOM_ ## name,\n#include \"quickjs-atom.h\"\n#undef DEF\n    JS_ATOM_END,\n};\n#define JS_ATOM_LAST_KEYWORD JS_ATOM_super\n#define JS_ATOM_LAST_STRICT_KEYWORD JS_ATOM_yield\n\nstatic const char js_atom_init[] =\n#define DEF(name, str) str \"\\0\"\n#include \"quickjs-atom.h\"\n#undef DEF\n;\n\ntypedef enum OPCodeFormat {\n#define FMT(f) OP_FMT_ ## f,\n#define DEF(id, size, n_pop, n_push, f)\n#include \"quickjs-opcode.h\"\n#undef DEF\n#undef FMT\n} OPCodeFormat;\n\nenum OPCodeEnum {\n#define FMT(f)\n#define DEF(id, size, n_pop, n_push, f) OP_ ## id,\n#define def(id, size, n_pop, n_push, f)\n#include \"quickjs-opcode.h\"\n#undef def\n#undef DEF\n#undef FMT\n    OP_COUNT, /* excluding temporary opcodes */\n    /* temporary opcodes : overlap with the short opcodes */\n    OP_TEMP_START = OP_nop + 1,\n    OP___dummy = OP_TEMP_START - 1,\n#define FMT(f)\n#define DEF(id, size, n_pop, n_push, f)\n#define def(id, size, n_pop, n_push, f) OP_ ## id,\n#include \"quickjs-opcode.h\"\n#undef def\n#undef DEF\n#undef FMT\n    OP_TEMP_END,\n};\n\nstatic int JS_InitAtoms(JSRuntime *rt);\nstatic JSAtom __JS_NewAtomInit(JSRuntime *rt, const char *str, int len,\n                               int atom_type);\nstatic void JS_FreeAtomStruct(JSRuntime *rt, JSAtomStruct *p);\nstatic void free_function_bytecode(JSRuntime *rt, JSFunctionBytecode *b);\nstatic JSValue js_call_c_function(JSContext *ctx, JSValueConst func_obj,\n                                  JSValueConst this_obj,\n                                  int argc, JSValueConst *argv, int flags);\nstatic JSValue js_call_bound_function(JSContext *ctx, JSValueConst func_obj,\n                                      JSValueConst this_obj,\n                                      int argc, JSValueConst *argv, int flags);\nstatic JSValue JS_CallInternal(JSContext *ctx, JSValueConst func_obj,\n                               JSValueConst this_obj, JSValueConst new_target,\n                               int argc, JSValue *argv, int flags);\nstatic JSValue JS_CallConstructorInternal(JSContext *ctx,\n                                          JSValueConst func_obj,\n                                          JSValueConst new_target,\n                                          int argc, JSValue *argv, int flags);\nstatic JSValue JS_CallFree(JSContext *ctx, JSValue func_obj, JSValueConst this_obj,\n                           int argc, JSValueConst *argv);\nstatic JSValue JS_InvokeFree(JSContext *ctx, JSValue this_val, JSAtom atom,\n                             int argc, JSValueConst *argv);\nstatic __exception int JS_ToArrayLengthFree(JSContext *ctx, uint32_t *plen,\n                                            JSValue val, BOOL is_array_ctor);\nstatic JSValue JS_EvalObject(JSContext *ctx, JSValueConst this_obj,\n                             JSValueConst val, int flags, int scope_idx);\nJSValue __attribute__((format(printf, 2, 3))) JS_ThrowInternalError(JSContext *ctx, const char *fmt, ...);\nstatic __maybe_unused void JS_DumpAtoms(JSRuntime *rt);\nstatic __maybe_unused void JS_DumpString(JSRuntime *rt,\n                                                  const JSString *p);\nstatic __maybe_unused void JS_DumpObjectHeader(JSRuntime *rt);\nstatic __maybe_unused void JS_DumpObject(JSRuntime *rt, JSObject *p);\nstatic __maybe_unused void JS_DumpGCObject(JSRuntime *rt, JSGCObjectHeader *p);\nstatic __maybe_unused void JS_DumpValueShort(JSRuntime *rt,\n                                                      JSValueConst val);\nstatic __maybe_unused void JS_DumpValue(JSContext *ctx, JSValueConst val);\nstatic __maybe_unused void JS_PrintValue(JSContext *ctx,\n                                                  const char *str,\n                                                  JSValueConst val);\nstatic __maybe_unused void JS_DumpShapes(JSRuntime *rt);\nstatic JSValue js_function_apply(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv, int magic);\nstatic void js_array_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_array_mark(JSRuntime *rt, JSValueConst val,\n                          JS_MarkFunc *mark_func);\nstatic void js_object_data_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_object_data_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_c_function_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_c_function_mark(JSRuntime *rt, JSValueConst val,\n                               JS_MarkFunc *mark_func);\nstatic void js_bytecode_function_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_bytecode_function_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_bound_function_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_bound_function_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_for_in_iterator_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_for_in_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_regexp_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_array_buffer_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_typed_array_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_typed_array_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_proxy_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_proxy_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_map_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_map_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_map_iterator_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_map_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_array_iterator_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_array_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_regexp_string_iterator_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_regexp_string_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_generator_finalizer(JSRuntime *rt, JSValue obj);\nstatic void js_generator_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_promise_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_promise_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\nstatic void js_promise_resolve_function_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_promise_resolve_function_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func);\n#ifdef CONFIG_BIGNUM\nstatic void js_operator_set_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_operator_set_mark(JSRuntime *rt, JSValueConst val,\n                                 JS_MarkFunc *mark_func);\n#endif\nstatic JSValue JS_ToStringFree(JSContext *ctx, JSValue val);\nstatic int JS_ToBoolFree(JSContext *ctx, JSValue val);\nstatic int JS_ToInt32Free(JSContext *ctx, int32_t *pres, JSValue val);\nstatic int JS_ToFloat64Free(JSContext *ctx, double *pres, JSValue val);\nstatic int JS_ToUint8ClampFree(JSContext *ctx, int32_t *pres, JSValue val);\nstatic JSValue js_compile_regexp(JSContext *ctx, JSValueConst pattern,\n                                 JSValueConst flags);\nstatic JSValue js_regexp_constructor_internal(JSContext *ctx, JSValueConst ctor,\n                                              JSValue pattern, JSValue bc);\nstatic void gc_decref(JSRuntime *rt);\nstatic int JS_NewClass1(JSRuntime *rt, JSClassID class_id,\n                        const JSClassDef *class_def, JSAtom name);\n\ntypedef enum JSStrictEqModeEnum {\n    JS_EQ_STRICT,\n    JS_EQ_SAME_VALUE,\n    JS_EQ_SAME_VALUE_ZERO,\n} JSStrictEqModeEnum;\n\nstatic BOOL js_strict_eq2(JSContext *ctx, JSValue op1, JSValue op2,\n                          JSStrictEqModeEnum eq_mode);\nstatic BOOL js_strict_eq(JSContext *ctx, JSValue op1, JSValue op2);\nstatic BOOL js_same_value(JSContext *ctx, JSValueConst op1, JSValueConst op2);\nstatic BOOL js_same_value_zero(JSContext *ctx, JSValueConst op1, JSValueConst op2);\nstatic JSValue JS_ToObject(JSContext *ctx, JSValueConst val);\nstatic JSValue JS_ToObjectFree(JSContext *ctx, JSValue val);\nstatic JSProperty *add_property(JSContext *ctx,\n                                JSObject *p, JSAtom prop, int prop_flags);\n#ifdef CONFIG_BIGNUM\nstatic void js_float_env_finalizer(JSRuntime *rt, JSValue val);\nstatic JSValue JS_NewBigFloat(JSContext *ctx);\nstatic inline bf_t *JS_GetBigFloat(JSValueConst val)\n{\n    JSBigFloat *p = JS_VALUE_GET_PTR(val);\n    return &p->num;\n}\nstatic JSValue JS_NewBigDecimal(JSContext *ctx);\nstatic inline bfdec_t *JS_GetBigDecimal(JSValueConst val)\n{\n    JSBigDecimal *p = JS_VALUE_GET_PTR(val);\n    return &p->num;\n}\nstatic JSValue JS_NewBigInt(JSContext *ctx);\nstatic inline bf_t *JS_GetBigInt(JSValueConst val)\n{\n    JSBigFloat *p = JS_VALUE_GET_PTR(val);\n    return &p->num;\n}\nstatic JSValue JS_CompactBigInt1(JSContext *ctx, JSValue val,\n                                 BOOL convert_to_safe_integer);\nstatic JSValue JS_CompactBigInt(JSContext *ctx, JSValue val);\nstatic int JS_ToBigInt64Free(JSContext *ctx, int64_t *pres, JSValue val);\nstatic bf_t *JS_ToBigInt(JSContext *ctx, bf_t *buf, JSValueConst val);\nstatic void JS_FreeBigInt(JSContext *ctx, bf_t *a, bf_t *buf);\nstatic bf_t *JS_ToBigFloat(JSContext *ctx, bf_t *buf, JSValueConst val);\nstatic JSValue JS_ToBigDecimalFree(JSContext *ctx, JSValue val,\n                                   BOOL allow_null_or_undefined);\nstatic bfdec_t *JS_ToBigDecimal(JSContext *ctx, JSValueConst val);\n#endif\nJSValue JS_ThrowOutOfMemory(JSContext *ctx);\nstatic JSValue JS_ThrowTypeErrorRevokedProxy(JSContext *ctx);\nstatic JSValue js_proxy_getPrototypeOf(JSContext *ctx, JSValueConst obj);\nstatic int js_proxy_setPrototypeOf(JSContext *ctx, JSValueConst obj,\n                                   JSValueConst proto_val, BOOL throw_flag);\nstatic int js_proxy_isExtensible(JSContext *ctx, JSValueConst obj);\nstatic int js_proxy_preventExtensions(JSContext *ctx, JSValueConst obj);\nstatic int js_proxy_isArray(JSContext *ctx, JSValueConst obj);\nstatic int JS_CreateProperty(JSContext *ctx, JSObject *p,\n                             JSAtom prop, JSValueConst val,\n                             JSValueConst getter, JSValueConst setter,\n                             int flags);\nstatic int js_string_memcmp(const JSString *p1, const JSString *p2, int len);\nstatic void reset_weak_ref(JSRuntime *rt, JSObject *p);\nstatic JSValue js_array_buffer_constructor3(JSContext *ctx,\n                                            JSValueConst new_target,\n                                            uint64_t len, JSClassID class_id,\n                                            uint8_t *buf,\n                                            JSFreeArrayBufferDataFunc *free_func,\n                                            void *opaque, BOOL alloc_flag);\nstatic JSArrayBuffer *js_get_array_buffer(JSContext *ctx, JSValueConst obj);\nstatic JSValue js_typed_array_constructor(JSContext *ctx,\n                                          JSValueConst this_val,\n                                          int argc, JSValueConst *argv,\n                                          int classid);\nstatic BOOL typed_array_is_detached(JSContext *ctx, JSObject *p);\nstatic uint32_t typed_array_get_length(JSContext *ctx, JSObject *p);\nstatic JSValue JS_ThrowTypeErrorDetachedArrayBuffer(JSContext *ctx);\nstatic JSVarRef *get_var_ref(JSContext *ctx, JSStackFrame *sf, int var_idx,\n                             BOOL is_arg);\nstatic JSValue js_generator_function_call(JSContext *ctx, JSValueConst func_obj,\n                                          JSValueConst this_obj,\n                                          int argc, JSValueConst *argv,\n                                          int flags);\nstatic void js_async_function_resolve_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_async_function_resolve_mark(JSRuntime *rt, JSValueConst val,\n                                           JS_MarkFunc *mark_func);\nstatic JSValue JS_EvalInternal(JSContext *ctx, JSValueConst this_obj,\n                               const char *input, size_t input_len,\n                               const char *filename, int flags, int scope_idx);\nstatic void js_free_module_def(JSContext *ctx, JSModuleDef *m);\nstatic void js_mark_module_def(JSRuntime *rt, JSModuleDef *m,\n                               JS_MarkFunc *mark_func);\nstatic JSValue js_import_meta(JSContext *ctx);\nstatic JSValue js_dynamic_import(JSContext *ctx, JSValueConst specifier);\nstatic void free_var_ref(JSRuntime *rt, JSVarRef *var_ref);\nstatic JSValue js_new_promise_capability(JSContext *ctx,\n                                         JSValue *resolving_funcs,\n                                         JSValueConst ctor);\nstatic __exception int perform_promise_then(JSContext *ctx,\n                                            JSValueConst promise,\n                                            JSValueConst *resolve_reject,\n                                            JSValueConst *cap_resolving_funcs);\nstatic JSValue js_promise_resolve(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv, int magic);\nstatic int js_string_compare(JSContext *ctx,\n                             const JSString *p1, const JSString *p2);\nstatic JSValue JS_ToNumber(JSContext *ctx, JSValueConst val);\nstatic int JS_SetPropertyValue(JSContext *ctx, JSValueConst this_obj,\n                               JSValue prop, JSValue val, int flags);\nstatic int JS_NumberIsInteger(JSContext *ctx, JSValueConst val);\nstatic BOOL JS_NumberIsNegativeOrMinusZero(JSContext *ctx, JSValueConst val);\nstatic JSValue JS_ToNumberFree(JSContext *ctx, JSValue val);\nstatic int JS_GetOwnPropertyInternal(JSContext *ctx, JSPropertyDescriptor *desc,\n                                     JSObject *p, JSAtom prop);\nstatic void js_free_desc(JSContext *ctx, JSPropertyDescriptor *desc);\nstatic void async_func_mark(JSRuntime *rt, JSAsyncFunctionState *s,\n                            JS_MarkFunc *mark_func);\nstatic void JS_AddIntrinsicBasicObjects(JSContext *ctx);\nstatic void js_free_shape(JSRuntime *rt, JSShape *sh);\nstatic void js_free_shape_null(JSRuntime *rt, JSShape *sh);\nstatic int js_shape_prepare_update(JSContext *ctx, JSObject *p,\n                                   JSShapeProperty **pprs);\nstatic int init_shape_hash(JSRuntime *rt);\nstatic __exception int js_get_length32(JSContext *ctx, uint32_t *pres,\n                                       JSValueConst obj);\nstatic __exception int js_get_length64(JSContext *ctx, int64_t *pres,\n                                       JSValueConst obj);\nstatic void free_arg_list(JSContext *ctx, JSValue *tab, uint32_t len);\nstatic JSValue *build_arg_list(JSContext *ctx, uint32_t *plen,\n                               JSValueConst array_arg);\nstatic BOOL js_get_fast_array(JSContext *ctx, JSValueConst obj,\n                              JSValue **arrpp, uint32_t *countp);\nstatic JSValue JS_CreateAsyncFromSyncIterator(JSContext *ctx,\n                                              JSValueConst sync_iter);\nstatic void js_c_function_data_finalizer(JSRuntime *rt, JSValue val);\nstatic void js_c_function_data_mark(JSRuntime *rt, JSValueConst val,\n                                    JS_MarkFunc *mark_func);\nstatic JSValue js_c_function_data_call(JSContext *ctx, JSValueConst func_obj,\n                                       JSValueConst this_val,\n                                       int argc, JSValueConst *argv, int flags);\nstatic JSAtom js_symbol_to_atom(JSContext *ctx, JSValue val);\nstatic void add_gc_object(JSRuntime *rt, JSGCObjectHeader *h,\n                          JSGCObjectTypeEnum type);\nstatic void remove_gc_object(JSGCObjectHeader *h);\nstatic void js_async_function_free0(JSRuntime *rt, JSAsyncFunctionData *s);\nstatic JSValue js_instantiate_prototype(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque);\nstatic JSValue js_module_ns_autoinit(JSContext *ctx, JSObject *p, JSAtom atom,\n                                 void *opaque);\nstatic JSValue JS_InstantiateFunctionListItem2(JSContext *ctx, JSObject *p,\n                                               JSAtom atom, void *opaque);\nvoid JS_SetUncatchableError(JSContext *ctx, JSValueConst val, BOOL flag);\n\nstatic const JSClassExoticMethods js_arguments_exotic_methods;\nstatic const JSClassExoticMethods js_string_exotic_methods;\nstatic const JSClassExoticMethods js_proxy_exotic_methods;\nstatic const JSClassExoticMethods js_module_ns_exotic_methods;\nstatic JSClassID js_class_id_alloc = JS_CLASS_INIT_COUNT;\n\nstatic void js_trigger_gc(JSRuntime *rt, size_t size)\n{\n    BOOL force_gc;\n#ifdef FORCE_GC_AT_MALLOC\n    force_gc = TRUE;\n#else\n    force_gc = ((rt->malloc_state.malloc_size + size) >\n                rt->malloc_gc_threshold);\n#endif\n    if (force_gc) {\n#ifdef DUMP_GC\n        printf(\"GC: size=%\" PRIu64 \"\\n\",\n               (uint64_t)rt->malloc_state.malloc_size);\n#endif\n        JS_RunGC(rt);\n        rt->malloc_gc_threshold = rt->malloc_state.malloc_size +\n            (rt->malloc_state.malloc_size >> 1);\n    }\n}\n\nstatic size_t js_malloc_usable_size_unknown(const void *ptr)\n{\n    return 0;\n}\n\nvoid *js_malloc_rt(JSRuntime *rt, size_t size)\n{\n    return rt->mf.js_malloc(&rt->malloc_state, size);\n}\n\nvoid js_free_rt(JSRuntime *rt, void *ptr)\n{\n    rt->mf.js_free(&rt->malloc_state, ptr);\n}\n\nvoid *js_realloc_rt(JSRuntime *rt, void *ptr, size_t size)\n{\n    return rt->mf.js_realloc(&rt->malloc_state, ptr, size);\n}\n\nsize_t js_malloc_usable_size_rt(JSRuntime *rt, const void *ptr)\n{\n    return rt->mf.js_malloc_usable_size(ptr);\n}\n\nvoid *js_mallocz_rt(JSRuntime *rt, size_t size)\n{\n    void *ptr;\n    ptr = js_malloc_rt(rt, size);\n    if (!ptr)\n        return NULL;\n    return memset(ptr, 0, size);\n}\n\n#ifdef CONFIG_BIGNUM\n/* called by libbf */\nstatic void *js_bf_realloc(void *opaque, void *ptr, size_t size)\n{\n    JSRuntime *rt = opaque;\n    return js_realloc_rt(rt, ptr, size);\n}\n#endif /* CONFIG_BIGNUM */\n\n/* Throw out of memory in case of error */\nvoid *js_malloc(JSContext *ctx, size_t size)\n{\n    void *ptr;\n    ptr = js_malloc_rt(ctx->rt, size);\n    if (unlikely(!ptr)) {\n        JS_ThrowOutOfMemory(ctx);\n        return NULL;\n    }\n    return ptr;\n}\n\n/* Throw out of memory in case of error */\nvoid *js_mallocz(JSContext *ctx, size_t size)\n{\n    void *ptr;\n    ptr = js_mallocz_rt(ctx->rt, size);\n    if (unlikely(!ptr)) {\n        JS_ThrowOutOfMemory(ctx);\n        return NULL;\n    }\n    return ptr;\n}\n\nvoid js_free(JSContext *ctx, void *ptr)\n{\n    js_free_rt(ctx->rt, ptr);\n}\n\n/* Throw out of memory in case of error */\nvoid *js_realloc(JSContext *ctx, void *ptr, size_t size)\n{\n    void *ret;\n    ret = js_realloc_rt(ctx->rt, ptr, size);\n    if (unlikely(!ret && size != 0)) {\n        JS_ThrowOutOfMemory(ctx);\n        return NULL;\n    }\n    return ret;\n}\n\n/* store extra allocated size in *pslack if successful */\nvoid *js_realloc2(JSContext *ctx, void *ptr, size_t size, size_t *pslack)\n{\n    void *ret;\n    ret = js_realloc_rt(ctx->rt, ptr, size);\n    if (unlikely(!ret && size != 0)) {\n        JS_ThrowOutOfMemory(ctx);\n        return NULL;\n    }\n    if (pslack) {\n        size_t new_size = js_malloc_usable_size_rt(ctx->rt, ret);\n        *pslack = (new_size > size) ? new_size - size : 0;\n    }\n    return ret;\n}\n\nsize_t js_malloc_usable_size(JSContext *ctx, const void *ptr)\n{\n    return js_malloc_usable_size_rt(ctx->rt, ptr);\n}\n\n/* Throw out of memory exception in case of error */\nchar *js_strndup(JSContext *ctx, const char *s, size_t n)\n{\n    char *ptr;\n    ptr = js_malloc(ctx, n + 1);\n    if (ptr) {\n        memcpy(ptr, s, n);\n        ptr[n] = '\\0';\n    }\n    return ptr;\n}\n\nchar *js_strdup(JSContext *ctx, const char *str)\n{\n    return js_strndup(ctx, str, strlen(str));\n}\n\nstatic no_inline int js_realloc_array(JSContext *ctx, void **parray,\n                                      int elem_size, int *psize, int req_size)\n{\n    int new_size;\n    size_t slack;\n    void *new_array;\n    /* XXX: potential arithmetic overflow */\n    new_size = max_int(req_size, *psize * 3 / 2);\n    new_array = js_realloc2(ctx, *parray, new_size * elem_size, &slack);\n    if (!new_array)\n        return -1;\n    new_size += slack / elem_size;\n    *psize = new_size;\n    *parray = new_array;\n    return 0;\n}\n\n/* resize the array and update its size if req_size > *psize */\nstatic inline int js_resize_array(JSContext *ctx, void **parray, int elem_size,\n                                  int *psize, int req_size)\n{\n    if (unlikely(req_size > *psize))\n        return js_realloc_array(ctx, parray, elem_size, psize, req_size);\n    else\n        return 0;\n}\n\nstatic inline void js_dbuf_init(JSContext *ctx, DynBuf *s)\n{\n    dbuf_init2(s, ctx->rt, (DynBufReallocFunc *)js_realloc_rt);\n}\n\nstatic inline int is_digit(int c) {\n    return c >= '0' && c <= '9';\n}\n\ntypedef struct JSClassShortDef {\n    JSAtom class_name;\n    JSClassFinalizer *finalizer;\n    JSClassGCMark *gc_mark;\n} JSClassShortDef;\n\nstatic JSClassShortDef const js_std_class_def[] = {\n    { JS_ATOM_Object, NULL, NULL },                             /* JS_CLASS_OBJECT */\n    { JS_ATOM_Array, js_array_finalizer, js_array_mark },       /* JS_CLASS_ARRAY */\n    { JS_ATOM_Error, NULL, NULL }, /* JS_CLASS_ERROR */\n    { JS_ATOM_Number, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_NUMBER */\n    { JS_ATOM_String, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_STRING */\n    { JS_ATOM_Boolean, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_BOOLEAN */\n    { JS_ATOM_Symbol, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_SYMBOL */\n    { JS_ATOM_Arguments, js_array_finalizer, js_array_mark },   /* JS_CLASS_ARGUMENTS */\n    { JS_ATOM_Arguments, NULL, NULL },                          /* JS_CLASS_MAPPED_ARGUMENTS */\n    { JS_ATOM_Date, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_DATE */\n    { JS_ATOM_Object, NULL, NULL },                             /* JS_CLASS_MODULE_NS */\n    { JS_ATOM_Function, js_c_function_finalizer, js_c_function_mark }, /* JS_CLASS_C_FUNCTION */\n    { JS_ATOM_Function, js_bytecode_function_finalizer, js_bytecode_function_mark }, /* JS_CLASS_BYTECODE_FUNCTION */\n    { JS_ATOM_Function, js_bound_function_finalizer, js_bound_function_mark }, /* JS_CLASS_BOUND_FUNCTION */\n    { JS_ATOM_Function, js_c_function_data_finalizer, js_c_function_data_mark }, /* JS_CLASS_C_FUNCTION_DATA */\n    { JS_ATOM_GeneratorFunction, js_bytecode_function_finalizer, js_bytecode_function_mark },  /* JS_CLASS_GENERATOR_FUNCTION */\n    { JS_ATOM_ForInIterator, js_for_in_iterator_finalizer, js_for_in_iterator_mark },      /* JS_CLASS_FOR_IN_ITERATOR */\n    { JS_ATOM_RegExp, js_regexp_finalizer, NULL },                              /* JS_CLASS_REGEXP */\n    { JS_ATOM_ArrayBuffer, js_array_buffer_finalizer, NULL },                   /* JS_CLASS_ARRAY_BUFFER */\n    { JS_ATOM_SharedArrayBuffer, js_array_buffer_finalizer, NULL },             /* JS_CLASS_SHARED_ARRAY_BUFFER */\n    { JS_ATOM_Uint8ClampedArray, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_UINT8C_ARRAY */\n    { JS_ATOM_Int8Array, js_typed_array_finalizer, js_typed_array_mark },       /* JS_CLASS_INT8_ARRAY */\n    { JS_ATOM_Uint8Array, js_typed_array_finalizer, js_typed_array_mark },      /* JS_CLASS_UINT8_ARRAY */\n    { JS_ATOM_Int16Array, js_typed_array_finalizer, js_typed_array_mark },      /* JS_CLASS_INT16_ARRAY */\n    { JS_ATOM_Uint16Array, js_typed_array_finalizer, js_typed_array_mark },     /* JS_CLASS_UINT16_ARRAY */\n    { JS_ATOM_Int32Array, js_typed_array_finalizer, js_typed_array_mark },      /* JS_CLASS_INT32_ARRAY */\n    { JS_ATOM_Uint32Array, js_typed_array_finalizer, js_typed_array_mark },     /* JS_CLASS_UINT32_ARRAY */\n#ifdef CONFIG_BIGNUM\n    { JS_ATOM_BigInt64Array, js_typed_array_finalizer, js_typed_array_mark },   /* JS_CLASS_BIG_INT64_ARRAY */\n    { JS_ATOM_BigUint64Array, js_typed_array_finalizer, js_typed_array_mark },  /* JS_CLASS_BIG_UINT64_ARRAY */\n#endif\n    { JS_ATOM_Float32Array, js_typed_array_finalizer, js_typed_array_mark },    /* JS_CLASS_FLOAT32_ARRAY */\n    { JS_ATOM_Float64Array, js_typed_array_finalizer, js_typed_array_mark },    /* JS_CLASS_FLOAT64_ARRAY */\n    { JS_ATOM_DataView, js_typed_array_finalizer, js_typed_array_mark },        /* JS_CLASS_DATAVIEW */\n#ifdef CONFIG_BIGNUM\n    { JS_ATOM_BigInt, js_object_data_finalizer, js_object_data_mark },      /* JS_CLASS_BIG_INT */\n    { JS_ATOM_BigFloat, js_object_data_finalizer, js_object_data_mark },    /* JS_CLASS_BIG_FLOAT */\n    { JS_ATOM_BigFloatEnv, js_float_env_finalizer, NULL },      /* JS_CLASS_FLOAT_ENV */\n    { JS_ATOM_BigDecimal, js_object_data_finalizer, js_object_data_mark },    /* JS_CLASS_BIG_DECIMAL */\n    { JS_ATOM_OperatorSet, js_operator_set_finalizer, js_operator_set_mark },    /* JS_CLASS_OPERATOR_SET */\n#endif\n    { JS_ATOM_Map, js_map_finalizer, js_map_mark },             /* JS_CLASS_MAP */\n    { JS_ATOM_Set, js_map_finalizer, js_map_mark },             /* JS_CLASS_SET */\n    { JS_ATOM_WeakMap, js_map_finalizer, js_map_mark },         /* JS_CLASS_WEAKMAP */\n    { JS_ATOM_WeakSet, js_map_finalizer, js_map_mark },         /* JS_CLASS_WEAKSET */\n    { JS_ATOM_Map_Iterator, js_map_iterator_finalizer, js_map_iterator_mark }, /* JS_CLASS_MAP_ITERATOR */\n    { JS_ATOM_Set_Iterator, js_map_iterator_finalizer, js_map_iterator_mark }, /* JS_CLASS_SET_ITERATOR */\n    { JS_ATOM_Array_Iterator, js_array_iterator_finalizer, js_array_iterator_mark }, /* JS_CLASS_ARRAY_ITERATOR */\n    { JS_ATOM_String_Iterator, js_array_iterator_finalizer, js_array_iterator_mark }, /* JS_CLASS_STRING_ITERATOR */\n    { JS_ATOM_RegExp_String_Iterator, js_regexp_string_iterator_finalizer, js_regexp_string_iterator_mark }, /* JS_CLASS_REGEXP_STRING_ITERATOR */\n    { JS_ATOM_Generator, js_generator_finalizer, js_generator_mark }, /* JS_CLASS_GENERATOR */\n};\n\nstatic int init_class_range(JSRuntime *rt, JSClassShortDef const *tab,\n                            int start, int count)\n{\n    JSClassDef cm_s, *cm = &cm_s;\n    int i, class_id;\n\n    for(i = 0; i < count; i++) {\n        class_id = i + start;\n        memset(cm, 0, sizeof(*cm));\n        cm->finalizer = tab[i].finalizer;\n        cm->gc_mark = tab[i].gc_mark;\n        if (JS_NewClass1(rt, class_id, cm, tab[i].class_name) < 0)\n            return -1;\n    }\n    return 0;\n}\n\n#ifdef CONFIG_BIGNUM\nstatic JSValue JS_ThrowUnsupportedOperation(JSContext *ctx)\n{\n    return JS_ThrowTypeError(ctx, \"unsupported operation\");\n}\n\nstatic JSValue invalid_to_string(JSContext *ctx, JSValueConst val)\n{\n    return JS_ThrowUnsupportedOperation(ctx);\n}\n\nstatic JSValue invalid_from_string(JSContext *ctx, const char *buf,\n                                   int radix, int flags, slimb_t *pexponent)\n{\n    return JS_NAN;\n}\n\nstatic int invalid_unary_arith(JSContext *ctx,\n                               JSValue *pres, OPCodeEnum op, JSValue op1)\n{\n    JS_FreeValue(ctx, op1);\n    JS_ThrowUnsupportedOperation(ctx);\n    return -1;\n}\n\nstatic int invalid_binary_arith(JSContext *ctx, OPCodeEnum op,\n                                JSValue *pres, JSValue op1, JSValue op2)\n{\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    JS_ThrowUnsupportedOperation(ctx);\n    return -1;\n}\n\nstatic JSValue invalid_mul_pow10_to_float64(JSContext *ctx, const bf_t *a,\n                                            int64_t exponent)\n{\n    return JS_ThrowUnsupportedOperation(ctx);\n}\n\nstatic int invalid_mul_pow10(JSContext *ctx, JSValue *sp)\n{\n    JS_ThrowUnsupportedOperation(ctx);\n    return -1;\n}\n\nstatic void set_dummy_numeric_ops(JSNumericOperations *ops)\n{\n    ops->to_string = invalid_to_string;\n    ops->from_string = invalid_from_string;\n    ops->unary_arith = invalid_unary_arith;\n    ops->binary_arith = invalid_binary_arith;\n    ops->mul_pow10_to_float64 = invalid_mul_pow10_to_float64;\n    ops->mul_pow10 = invalid_mul_pow10;\n}\n\n#endif /* CONFIG_BIGNUM */\n\n#if !defined(CONFIG_STACK_CHECK) || defined(CONFIG_DISABLE_STACK_CHECK)\n/* no stack limitation */\nstatic inline uintptr_t js_get_stack_pointer(void)\n{\n    return 0;\n}\n\nstatic inline BOOL js_check_stack_overflow(JSRuntime *rt, size_t alloca_size)\n{\n    return FALSE;\n}\n#else\n/* Note: OS and CPU dependent */\nstatic inline uintptr_t js_get_stack_pointer(void)\n{\n    return (uintptr_t)__builtin_frame_address(0);\n}\n\nstatic inline BOOL js_check_stack_overflow(JSRuntime *rt, size_t alloca_size)\n{\n    uintptr_t sp;\n    sp = js_get_stack_pointer() - alloca_size;\n    return unlikely(sp < rt->stack_limit);\n}\n#endif\n\nJSRuntime *JS_NewRuntime2(const JSMallocFunctions *mf, void *opaque)\n{\n    JSRuntime *rt;\n    JSMallocState ms;\n\n    memset(&ms, 0, sizeof(ms));\n    ms.opaque = opaque;\n    ms.malloc_limit = -1;\n\n    rt = mf->js_malloc(&ms, sizeof(JSRuntime));\n    if (!rt)\n        return NULL;\n    memset(rt, 0, sizeof(*rt));\n    rt->mf = *mf;\n    if (!rt->mf.js_malloc_usable_size) {\n        /* use dummy function if none provided */\n        rt->mf.js_malloc_usable_size = js_malloc_usable_size_unknown;\n    }\n    rt->malloc_state = ms;\n    rt->malloc_gc_threshold = 256 * 1024;\n\n#ifdef CONFIG_BIGNUM\n    bf_context_init(&rt->bf_ctx, js_bf_realloc, rt);\n    set_dummy_numeric_ops(&rt->bigint_ops);\n    set_dummy_numeric_ops(&rt->bigfloat_ops);\n    set_dummy_numeric_ops(&rt->bigdecimal_ops);\n#endif\n\n    init_list_head(&rt->context_list);\n    init_list_head(&rt->gc_obj_list);\n    init_list_head(&rt->gc_zero_ref_count_list);\n    rt->gc_phase = JS_GC_PHASE_NONE;\n    \n#ifdef DUMP_LEAKS\n    init_list_head(&rt->string_list);\n#endif\n    init_list_head(&rt->job_list);\n\n    if (JS_InitAtoms(rt))\n        goto fail;\n\n    /* create the object, array and function classes */\n    if (init_class_range(rt, js_std_class_def, JS_CLASS_OBJECT,\n                         countof(js_std_class_def)) < 0)\n        goto fail;\n    rt->class_array[JS_CLASS_ARGUMENTS].exotic = &js_arguments_exotic_methods;\n    rt->class_array[JS_CLASS_STRING].exotic = &js_string_exotic_methods;\n    rt->class_array[JS_CLASS_MODULE_NS].exotic = &js_module_ns_exotic_methods;\n\n    rt->class_array[JS_CLASS_C_FUNCTION].call = js_call_c_function;\n    rt->class_array[JS_CLASS_C_FUNCTION_DATA].call = js_c_function_data_call;\n    rt->class_array[JS_CLASS_BOUND_FUNCTION].call = js_call_bound_function;\n    rt->class_array[JS_CLASS_GENERATOR_FUNCTION].call = js_generator_function_call;\n    if (init_shape_hash(rt))\n        goto fail;\n\n    rt->stack_size = JS_DEFAULT_STACK_SIZE;\n    JS_UpdateStackTop(rt);\n\n    rt->current_exception = JS_NULL;\n\n    return rt;\n fail:\n    JS_FreeRuntime(rt);\n    return NULL;\n}\n\nvoid *JS_GetRuntimeOpaque(JSRuntime *rt)\n{\n    return rt->user_opaque;\n}\n\nvoid JS_SetRuntimeOpaque(JSRuntime *rt, void *opaque)\n{\n    rt->user_opaque = opaque;\n}\n\n/* default memory allocation functions with memory limitation */\nstatic inline size_t js_def_malloc_usable_size(void *ptr)\n{\n#if defined(__APPLE__)\n    return malloc_size(ptr);\n#elif defined(_WIN32)\n    return _msize(ptr);\n#elif defined(EMSCRIPTEN)\n    return 0;\n#elif defined(__ANDROID__)\n    return 0;\n#elif defined(__linux__)\n    return malloc_usable_size(ptr);\n#else\n    /* change this to `return 0;` if compilation fails */\n    return 0;\n#endif\n}\n\nstatic void *js_def_malloc(JSMallocState *s, size_t size)\n{\n    void *ptr;\n\n    /* Do not allocate zero bytes: behavior is platform dependent */\n    assert(size != 0);\n\n    if (unlikely(s->malloc_size + size > s->malloc_limit))\n        return NULL;\n\n    ptr = malloc(size);\n    if (!ptr)\n        return NULL;\n\n    s->malloc_count++;\n    s->malloc_size += js_def_malloc_usable_size(ptr) + MALLOC_OVERHEAD;\n    return ptr;\n}\n\nstatic void js_def_free(JSMallocState *s, void *ptr)\n{\n    if (!ptr)\n        return;\n\n    s->malloc_count--;\n    s->malloc_size -= js_def_malloc_usable_size(ptr) + MALLOC_OVERHEAD;\n    free(ptr);\n}\n\nstatic void *js_def_realloc(JSMallocState *s, void *ptr, size_t size)\n{\n    size_t old_size;\n\n    if (!ptr) {\n        if (size == 0)\n            return NULL;\n        return js_def_malloc(s, size);\n    }\n    old_size = js_def_malloc_usable_size(ptr);\n    if (size == 0) {\n        s->malloc_count--;\n        s->malloc_size -= old_size + MALLOC_OVERHEAD;\n        free(ptr);\n        return NULL;\n    }\n    if (s->malloc_size + size - old_size > s->malloc_limit)\n        return NULL;\n\n    ptr = realloc(ptr, size);\n    if (!ptr)\n        return NULL;\n\n    s->malloc_size += js_def_malloc_usable_size(ptr) - old_size;\n    return ptr;\n}\n\nstatic const JSMallocFunctions def_malloc_funcs = {\n    js_def_malloc,\n    js_def_free,\n    js_def_realloc,\n#if defined(__APPLE__)\n    malloc_size,\n#elif defined(_WIN32)\n    (size_t (*)(const void *))_msize,\n#elif defined(EMSCRIPTEN)\n    NULL,\n#elif defined(__ANDROID__)\n    NULL, \n#elif defined(__linux__)\n    (size_t (*)(const void *))malloc_usable_size,\n#else\n    /* change this to `NULL,` if compilation fails */\n    malloc_usable_size,\n#endif\n};\n\nJSRuntime *JS_NewRuntime(void)\n{\n    return JS_NewRuntime2(&def_malloc_funcs, NULL);\n}\n\nvoid JS_SetMemoryLimit(JSRuntime *rt, size_t limit)\n{\n    rt->malloc_state.malloc_limit = limit;\n}\n\n/* use -1 to disable automatic GC */\nvoid JS_SetGCThreshold(JSRuntime *rt, size_t gc_threshold)\n{\n    rt->malloc_gc_threshold = gc_threshold;\n}\n\n#define malloc(s) malloc_is_forbidden(s)\n#define free(p) free_is_forbidden(p)\n#define realloc(p,s) realloc_is_forbidden(p,s)\n\nvoid JS_SetInterruptHandler(JSRuntime *rt, JSInterruptHandler *cb, void *opaque)\n{\n    rt->interrupt_handler = cb;\n    rt->interrupt_opaque = opaque;\n}\n\nvoid JS_SetCanBlock(JSRuntime *rt, BOOL can_block)\n{\n    rt->can_block = can_block;\n}\n\nvoid JS_SetSharedArrayBufferFunctions(JSRuntime *rt,\n                                      const JSSharedArrayBufferFunctions *sf)\n{\n    rt->sab_funcs = *sf;\n}\n\n/* return 0 if OK, < 0 if exception */\nint JS_EnqueueJob(JSContext *ctx, JSJobFunc *job_func,\n                  int argc, JSValueConst *argv)\n{\n    JSRuntime *rt = ctx->rt;\n    JSJobEntry *e;\n    int i;\n\n    e = js_malloc(ctx, sizeof(*e) + argc * sizeof(JSValue));\n    if (!e)\n        return -1;\n    e->ctx = ctx;\n    e->job_func = job_func;\n    e->argc = argc;\n    for(i = 0; i < argc; i++) {\n        e->argv[i] = JS_DupValue(ctx, argv[i]);\n    }\n    list_add_tail(&e->link, &rt->job_list);\n    return 0;\n}\n\nBOOL JS_IsJobPending(JSRuntime *rt)\n{\n    return !list_empty(&rt->job_list);\n}\n\n/* return < 0 if exception, 0 if no job pending, 1 if a job was\n   executed successfully. the context of the job is stored in '*pctx' */\nint JS_ExecutePendingJob(JSRuntime *rt, JSContext **pctx)\n{\n    JSContext *ctx;\n    JSJobEntry *e;\n    JSValue res;\n    int i, ret;\n\n    if (list_empty(&rt->job_list)) {\n        *pctx = NULL;\n        return 0;\n    }\n\n    /* get the first pending job and execute it */\n    e = list_entry(rt->job_list.next, JSJobEntry, link);\n    list_del(&e->link);\n    ctx = e->ctx;\n    res = e->job_func(e->ctx, e->argc, (JSValueConst *)e->argv);\n    for(i = 0; i < e->argc; i++)\n        JS_FreeValue(ctx, e->argv[i]);\n    if (JS_IsException(res))\n        ret = -1;\n    else\n        ret = 1;\n    JS_FreeValue(ctx, res);\n    js_free(ctx, e);\n    *pctx = ctx;\n    return ret;\n}\n\nstatic inline uint32_t atom_get_free(const JSAtomStruct *p)\n{\n    return (uintptr_t)p >> 1;\n}\n\nstatic inline BOOL atom_is_free(const JSAtomStruct *p)\n{\n    return (uintptr_t)p & 1;\n}\n\nstatic inline JSAtomStruct *atom_set_free(uint32_t v)\n{\n    return (JSAtomStruct *)(((uintptr_t)v << 1) | 1);\n}\n\n/* Note: the string contents are uninitialized */\nstatic JSString *js_alloc_string_rt(JSRuntime *rt, int max_len, int is_wide_char)\n{\n    JSString *str;\n    str = js_malloc_rt(rt, sizeof(JSString) + (max_len << is_wide_char) + 1 - is_wide_char);\n    if (unlikely(!str))\n        return NULL;\n    str->header.ref_count = 1;\n    str->is_wide_char = is_wide_char;\n    str->len = max_len;\n    str->atom_type = 0;\n    str->hash = 0;          /* optional but costless */\n    str->hash_next = 0;     /* optional */\n#ifdef DUMP_LEAKS\n    list_add_tail(&str->link, &rt->string_list);\n#endif\n    return str;\n}\n\nstatic JSString *js_alloc_string(JSContext *ctx, int max_len, int is_wide_char)\n{\n    JSString *p;\n    p = js_alloc_string_rt(ctx->rt, max_len, is_wide_char);\n    if (unlikely(!p)) {\n        JS_ThrowOutOfMemory(ctx);\n        return NULL;\n    }\n    return p;\n}\n\n/* same as JS_FreeValueRT() but faster */\nstatic inline void js_free_string(JSRuntime *rt, JSString *str)\n{\n    if (--str->header.ref_count <= 0) {\n        if (str->atom_type) {\n            JS_FreeAtomStruct(rt, str);\n        } else {\n#ifdef DUMP_LEAKS\n            list_del(&str->link);\n#endif\n            js_free_rt(rt, str);\n        }\n    }\n}\n\nvoid JS_SetRuntimeInfo(JSRuntime *rt, const char *s)\n{\n    if (rt)\n        rt->rt_info = s;\n}\n\nint JS_FreeRuntime(JSRuntime *rt)\n{\n    struct list_head *el, *el1;\n    int i;\n    int ret_leaks;\n\n    JS_FreeValueRT(rt, rt->current_exception);\n\n    list_for_each_safe(el, el1, &rt->job_list) {\n        JSJobEntry *e = list_entry(el, JSJobEntry, link);\n        for(i = 0; i < e->argc; i++)\n            JS_FreeValueRT(rt, e->argv[i]);\n        js_free_rt(rt, e);\n    }\n    init_list_head(&rt->job_list);\n\n    JS_RunGC(rt);\n\n#ifdef DUMP_LEAKS\n    /* leaking objects */\n    {\n        BOOL header_done;\n        JSGCObjectHeader *p;\n        int count;\n\n        /* remove the internal refcounts to display only the object\n           referenced externally */\n        list_for_each(el, &rt->gc_obj_list) {\n            p = list_entry(el, JSGCObjectHeader, link);\n            p->mark = 0;\n        }\n        gc_decref(rt);\n\n        header_done = FALSE;\n        list_for_each(el, &rt->gc_obj_list) {\n            p = list_entry(el, JSGCObjectHeader, link);\n            if (p->ref_count != 0) {\n                if (!header_done) {\n                    printf(\"Object leaks:\\n\");\n                    JS_DumpObjectHeader(rt);\n                    header_done = TRUE;\n                }\n                JS_DumpGCObject(rt, p);\n            }\n        }\n\n        count = 0;\n        list_for_each(el, &rt->gc_obj_list) {\n            p = list_entry(el, JSGCObjectHeader, link);\n            if (p->ref_count == 0) {\n                count++;\n            }\n        }\n        if (count != 0)\n            printf(\"Secondary object leaks: %d\\n\", count);\n    }\n#endif\n    ret_leaks = (list_empty(&rt->gc_obj_list));\n\n    /* free the classes */\n    for(i = 0; i < rt->class_count; i++) {\n        JSClass *cl = &rt->class_array[i];\n        if (cl->class_id != 0) {\n            JS_FreeAtomRT(rt, cl->class_name);\n        }\n    }\n    js_free_rt(rt, rt->class_array);\n\n#ifdef CONFIG_BIGNUM\n    bf_context_end(&rt->bf_ctx);\n#endif\n\n#ifdef DUMP_LEAKS\n    /* only the atoms defined in JS_InitAtoms() should be left */\n    {\n        BOOL header_done = FALSE;\n\n        for(i = 0; i < rt->atom_size; i++) {\n            JSAtomStruct *p = rt->atom_array[i];\n            if (!atom_is_free(p) /* && p->str*/) {\n                if (i >= JS_ATOM_END || p->header.ref_count != 1) {\n                    if (!header_done) {\n                        header_done = TRUE;\n                        if (rt->rt_info) {\n                            printf(\"%s:1: atom leakage:\", rt->rt_info);\n                        } else {\n                            printf(\"Atom leaks:\\n\"\n                                   \"    %6s %6s %s\\n\",\n                                   \"ID\", \"REFCNT\", \"NAME\");\n                        }\n                    }\n                    if (rt->rt_info) {\n                        printf(\" \");\n                    } else {\n                        printf(\"    %6u %6u \", i, p->header.ref_count);\n                    }\n                    switch (p->atom_type) {\n                    case JS_ATOM_TYPE_STRING:\n                        JS_DumpString(rt, p);\n                        break;\n                    case JS_ATOM_TYPE_GLOBAL_SYMBOL:\n                        printf(\"Symbol.for(\");\n                        JS_DumpString(rt, p);\n                        printf(\")\");\n                        break;\n                    case JS_ATOM_TYPE_SYMBOL:\n                        if (p->hash == JS_ATOM_HASH_SYMBOL) {\n                            printf(\"Symbol(\");\n                            JS_DumpString(rt, p);\n                            printf(\")\");\n                        } else {\n                            printf(\"Private(\");\n                            JS_DumpString(rt, p);\n                            printf(\")\");\n                        }\n                        break;\n                    }\n                    if (rt->rt_info) {\n                        printf(\":%u\", p->header.ref_count);\n                    } else {\n                        printf(\"\\n\");\n                    }\n                }\n            }\n        }\n        if (rt->rt_info && header_done)\n            printf(\"\\n\");\n    }\n#endif\n\n    /* free the atoms */\n    for(i = 0; i < rt->atom_size; i++) {\n        JSAtomStruct *p = rt->atom_array[i];\n        if (!atom_is_free(p)) {\n#ifdef DUMP_LEAKS\n            list_del(&p->link);\n#endif\n            js_free_rt(rt, p);\n        }\n    }\n    js_free_rt(rt, rt->atom_array);\n    js_free_rt(rt, rt->atom_hash);\n    js_free_rt(rt, rt->shape_hash);\n#ifdef DUMP_LEAKS\n    if (!list_empty(&rt->string_list)) {\n        if (rt->rt_info) {\n            printf(\"%s:1: string leakage:\", rt->rt_info);\n        } else {\n            printf(\"String leaks:\\n\"\n                   \"    %6s %s\\n\",\n                   \"REFCNT\", \"VALUE\");\n        }\n        list_for_each_safe(el, el1, &rt->string_list) {\n            JSString *str = list_entry(el, JSString, link);\n            if (rt->rt_info) {\n                printf(\" \");\n            } else {\n                printf(\"    %6u \", str->header.ref_count);\n            }\n            JS_DumpString(rt, str);\n            if (rt->rt_info) {\n                printf(\":%u\", str->header.ref_count);\n            } else {\n                printf(\"\\n\");\n            }\n            list_del(&str->link);\n            js_free_rt(rt, str);\n        }\n        if (rt->rt_info)\n            printf(\"\\n\");\n    }\n    {\n        JSMallocState *s = &rt->malloc_state;\n        if (s->malloc_count > 1) {\n            if (rt->rt_info)\n                printf(\"%s:1: \", rt->rt_info);\n            printf(\"Memory leak: %\"PRIu64\" bytes lost in %\"PRIu64\" block%s\\n\",\n                   (uint64_t)(s->malloc_size - sizeof(JSRuntime)),\n                   (uint64_t)(s->malloc_count - 1), &\"s\"[s->malloc_count == 2]);\n        }\n    }\n#endif\n\n    {\n        JSMallocState ms = rt->malloc_state;\n        rt->mf.js_free(&ms, rt);\n    }\n    return ret_leaks;\n}\n\nJSContext *JS_NewContextRaw(JSRuntime *rt)\n{\n    JSContext *ctx;\n    int i;\n\n    ctx = js_mallocz_rt(rt, sizeof(JSContext));\n    if (!ctx)\n        return NULL;\n    ctx->header.ref_count = 1;\n    add_gc_object(rt, &ctx->header, JS_GC_OBJ_TYPE_JS_CONTEXT);\n\n    ctx->class_proto = js_malloc_rt(rt, sizeof(ctx->class_proto[0]) *\n                                    rt->class_count);\n    if (!ctx->class_proto) {\n        js_free_rt(rt, ctx);\n        return NULL;\n    }\n    ctx->rt = rt;\n    list_add_tail(&ctx->link, &rt->context_list);\n#ifdef CONFIG_BIGNUM\n    ctx->bf_ctx = &rt->bf_ctx;\n    ctx->fp_env.prec = 113;\n    ctx->fp_env.flags = bf_set_exp_bits(15) | BF_RNDN | BF_FLAG_SUBNORMAL;\n#endif\n    for(i = 0; i < rt->class_count; i++)\n        ctx->class_proto[i] = JS_NULL;\n    ctx->array_ctor = JS_NULL;\n    ctx->regexp_ctor = JS_NULL;\n    ctx->promise_ctor = JS_NULL;\n    init_list_head(&ctx->loaded_modules);\n\n    JS_AddIntrinsicBasicObjects(ctx);\n    return ctx;\n}\n\nJSContext *JS_NewContext(JSRuntime *rt)\n{\n    JSContext *ctx;\n\n    ctx = JS_NewContextRaw(rt);\n    if (!ctx)\n        return NULL;\n\n    JS_AddIntrinsicBaseObjects(ctx);\n    JS_AddIntrinsicDate(ctx);\n    JS_AddIntrinsicEval(ctx);\n    JS_AddIntrinsicStringNormalize(ctx);\n    JS_AddIntrinsicRegExp(ctx);\n    JS_AddIntrinsicJSON(ctx);\n    JS_AddIntrinsicProxy(ctx);\n    JS_AddIntrinsicMapSet(ctx);\n    JS_AddIntrinsicTypedArrays(ctx);\n    JS_AddIntrinsicPromise(ctx);\n#ifdef CONFIG_BIGNUM\n    JS_AddIntrinsicBigInt(ctx);\n#endif\n    return ctx;\n}\n\nvoid *JS_GetContextOpaque(JSContext *ctx)\n{\n    return ctx->user_opaque;\n}\n\nvoid JS_SetContextOpaque(JSContext *ctx, void *opaque)\n{\n    ctx->user_opaque = opaque;\n}\n\n/* set the new value and free the old value after (freeing the value\n   can reallocate the object data) */\nstatic inline void set_value(JSContext *ctx, JSValue *pval, JSValue new_val)\n{\n    JSValue old_val;\n    old_val = *pval;\n    *pval = new_val;\n    JS_FreeValue(ctx, old_val);\n}\n\nvoid JS_SetClassProto(JSContext *ctx, JSClassID class_id, JSValue obj)\n{\n    JSRuntime *rt = ctx->rt;\n    assert(class_id < rt->class_count);\n    set_value(ctx, &ctx->class_proto[class_id], obj);\n}\n\nJSValue JS_GetClassProto(JSContext *ctx, JSClassID class_id)\n{\n    JSRuntime *rt = ctx->rt;\n    assert(class_id < rt->class_count);\n    return JS_DupValue(ctx, ctx->class_proto[class_id]);\n}\n\ntypedef enum JSFreeModuleEnum {\n    JS_FREE_MODULE_ALL,\n    JS_FREE_MODULE_NOT_RESOLVED,\n    JS_FREE_MODULE_NOT_EVALUATED,\n} JSFreeModuleEnum;\n\n/* XXX: would be more efficient with separate module lists */\nstatic void js_free_modules(JSContext *ctx, JSFreeModuleEnum flag)\n{\n    struct list_head *el, *el1;\n    list_for_each_safe(el, el1, &ctx->loaded_modules) {\n        JSModuleDef *m = list_entry(el, JSModuleDef, link);\n        if (flag == JS_FREE_MODULE_ALL ||\n            (flag == JS_FREE_MODULE_NOT_RESOLVED && !m->resolved) ||\n            (flag == JS_FREE_MODULE_NOT_EVALUATED && !m->evaluated)) {\n            js_free_module_def(ctx, m);\n        }\n    }\n}\n\nJSContext *JS_DupContext(JSContext *ctx)\n{\n    ctx->header.ref_count++;\n    return ctx;\n}\n\n/* used by the GC */\nstatic void JS_MarkContext(JSRuntime *rt, JSContext *ctx,\n                           JS_MarkFunc *mark_func)\n{\n    int i;\n    struct list_head *el;\n\n    /* modules are not seen by the GC, so we directly mark the objects\n       referenced by each module */\n    list_for_each(el, &ctx->loaded_modules) {\n        JSModuleDef *m = list_entry(el, JSModuleDef, link);\n        js_mark_module_def(rt, m, mark_func);\n    }\n\n    JS_MarkValue(rt, ctx->global_obj, mark_func);\n    JS_MarkValue(rt, ctx->global_var_obj, mark_func);\n\n    JS_MarkValue(rt, ctx->throw_type_error, mark_func);\n    JS_MarkValue(rt, ctx->eval_obj, mark_func);\n\n    JS_MarkValue(rt, ctx->array_proto_values, mark_func);\n    for(i = 0; i < JS_NATIVE_ERROR_COUNT; i++) {\n        JS_MarkValue(rt, ctx->native_error_proto[i], mark_func);\n    }\n    for(i = 0; i < rt->class_count; i++) {\n        JS_MarkValue(rt, ctx->class_proto[i], mark_func);\n    }\n    JS_MarkValue(rt, ctx->iterator_proto, mark_func);\n    JS_MarkValue(rt, ctx->async_iterator_proto, mark_func);\n    JS_MarkValue(rt, ctx->promise_ctor, mark_func);\n    JS_MarkValue(rt, ctx->array_ctor, mark_func);\n    JS_MarkValue(rt, ctx->regexp_ctor, mark_func);\n    JS_MarkValue(rt, ctx->function_ctor, mark_func);\n    JS_MarkValue(rt, ctx->function_proto, mark_func);\n\n    if (ctx->array_shape)\n        mark_func(rt, &ctx->array_shape->header);\n}\n\nvoid JS_FreeContext(JSContext *ctx)\n{\n    JSRuntime *rt = ctx->rt;\n    int i;\n\n    if (--ctx->header.ref_count > 0)\n        return;\n    assert(ctx->header.ref_count == 0);\n    \n#ifdef DUMP_ATOMS\n    JS_DumpAtoms(ctx->rt);\n#endif\n#ifdef DUMP_SHAPES\n    JS_DumpShapes(ctx->rt);\n#endif\n#ifdef DUMP_OBJECTS\n    {\n        struct list_head *el;\n        JSGCObjectHeader *p;\n        printf(\"JSObjects: {\\n\");\n        JS_DumpObjectHeader(ctx->rt);\n        list_for_each(el, &rt->gc_obj_list) {\n            p = list_entry(el, JSGCObjectHeader, link);\n            JS_DumpGCObject(rt, p);\n        }\n        printf(\"}\\n\");\n    }\n#endif\n#ifdef DUMP_MEM\n    {\n        JSMemoryUsage stats;\n        JS_ComputeMemoryUsage(rt, &stats);\n        JS_DumpMemoryUsage(stdout, &stats, rt);\n    }\n#endif\n\n    js_free_modules(ctx, JS_FREE_MODULE_ALL);\n\n    JS_FreeValue(ctx, ctx->global_obj);\n    JS_FreeValue(ctx, ctx->global_var_obj);\n\n    JS_FreeValue(ctx, ctx->throw_type_error);\n    JS_FreeValue(ctx, ctx->eval_obj);\n\n    JS_FreeValue(ctx, ctx->array_proto_values);\n    for(i = 0; i < JS_NATIVE_ERROR_COUNT; i++) {\n        JS_FreeValue(ctx, ctx->native_error_proto[i]);\n    }\n    for(i = 0; i < rt->class_count; i++) {\n        JS_FreeValue(ctx, ctx->class_proto[i]);\n    }\n    js_free_rt(rt, ctx->class_proto);\n    JS_FreeValue(ctx, ctx->iterator_proto);\n    JS_FreeValue(ctx, ctx->async_iterator_proto);\n    JS_FreeValue(ctx, ctx->promise_ctor);\n    JS_FreeValue(ctx, ctx->array_ctor);\n    JS_FreeValue(ctx, ctx->regexp_ctor);\n    JS_FreeValue(ctx, ctx->function_ctor);\n    JS_FreeValue(ctx, ctx->function_proto);\n\n    js_free_shape_null(ctx->rt, ctx->array_shape);\n\n    list_del(&ctx->link);\n    remove_gc_object(&ctx->header);\n    js_free_rt(ctx->rt, ctx);\n}\n\nJSRuntime *JS_GetRuntime(JSContext *ctx)\n{\n    return ctx->rt;\n}\n\nstatic void update_stack_limit(JSRuntime *rt)\n{\n    if (rt->stack_size == 0) {\n        rt->stack_limit = 0; /* no limit */\n    } else {\n        rt->stack_limit = rt->stack_top - rt->stack_size;\n    }\n}\n\nvoid JS_SetMaxStackSize(JSRuntime *rt, size_t stack_size)\n{\n    rt->stack_size = stack_size;\n    update_stack_limit(rt);\n}\n\nvoid JS_UpdateStackTop(JSRuntime *rt)\n{\n    rt->stack_top = js_get_stack_pointer();\n    update_stack_limit(rt);\n}\n\nstatic inline BOOL is_strict_mode(JSContext *ctx)\n{\n    JSStackFrame *sf = ctx->rt->current_stack_frame;\n    return (sf && (sf->js_mode & JS_MODE_STRICT));\n}\n\n#ifdef CONFIG_BIGNUM\nstatic inline BOOL is_math_mode(JSContext *ctx)\n{\n    JSStackFrame *sf = ctx->rt->current_stack_frame;\n    return (sf && (sf->js_mode & JS_MODE_MATH));\n}\n#endif\n\n/* JSAtom support */\n\n#define JS_ATOM_TAG_INT (1U << 31)\n#define JS_ATOM_MAX_INT (JS_ATOM_TAG_INT - 1)\n#define JS_ATOM_MAX     ((1U << 30) - 1)\n\n/* return the max count from the hash size */\n#define JS_ATOM_COUNT_RESIZE(n) ((n) * 2)\n\nstatic inline BOOL __JS_AtomIsConst(JSAtom v)\n{\n#if defined(DUMP_LEAKS) && DUMP_LEAKS > 1\n        return (int32_t)v <= 0;\n#else\n        return (int32_t)v < JS_ATOM_END;\n#endif\n}\n\nstatic inline BOOL __JS_AtomIsTaggedInt(JSAtom v)\n{\n    return (v & JS_ATOM_TAG_INT) != 0;\n}\n\nstatic inline JSAtom __JS_AtomFromUInt32(uint32_t v)\n{\n    return v | JS_ATOM_TAG_INT;\n}\n\nstatic inline uint32_t __JS_AtomToUInt32(JSAtom atom)\n{\n    return atom & ~JS_ATOM_TAG_INT;\n}\n\nstatic inline int is_num(int c)\n{\n    return c >= '0' && c <= '9';\n}\n\n/* return TRUE if the string is a number n with 0 <= n <= 2^32-1 */\nstatic inline BOOL is_num_string(uint32_t *pval, const JSString *p)\n{\n    uint32_t n;\n    uint64_t n64;\n    int c, i, len;\n\n    len = p->len;\n    if (len == 0 || len > 10)\n        return FALSE;\n    if (p->is_wide_char)\n        c = p->u.str16[0];\n    else\n        c = p->u.str8[0];\n    if (is_num(c)) {\n        if (c == '0') {\n            if (len != 1)\n                return FALSE;\n            n = 0;\n        } else {\n            n = c - '0';\n            for(i = 1; i < len; i++) {\n                if (p->is_wide_char)\n                    c = p->u.str16[i];\n                else\n                    c = p->u.str8[i];\n                if (!is_num(c))\n                    return FALSE;\n                n64 = (uint64_t)n * 10 + (c - '0');\n                if ((n64 >> 32) != 0)\n                    return FALSE;\n                n = n64;\n            }\n        }\n        *pval = n;\n        return TRUE;\n    } else {\n        return FALSE;\n    }\n}\n\n/* XXX: could use faster version ? */\nstatic inline uint32_t hash_string8(const uint8_t *str, size_t len, uint32_t h)\n{\n    size_t i;\n\n    for(i = 0; i < len; i++)\n        h = h * 263 + str[i];\n    return h;\n}\n\nstatic inline uint32_t hash_string16(const uint16_t *str,\n                                     size_t len, uint32_t h)\n{\n    size_t i;\n\n    for(i = 0; i < len; i++)\n        h = h * 263 + str[i];\n    return h;\n}\n\nstatic uint32_t hash_string(const JSString *str, uint32_t h)\n{\n    if (str->is_wide_char)\n        h = hash_string16(str->u.str16, str->len, h);\n    else\n        h = hash_string8(str->u.str8, str->len, h);\n    return h;\n}\n\nstatic __maybe_unused void JS_DumpString(JSRuntime *rt,\n                                                  const JSString *p)\n{\n    int i, c, sep;\n\n    if (p == NULL) {\n        printf(\"<null>\");\n        return;\n    }\n    printf(\"%d\", p->header.ref_count);\n    sep = (p->header.ref_count == 1) ? '\\\"' : '\\'';\n    putchar(sep);\n    for(i = 0; i < p->len; i++) {\n        if (p->is_wide_char)\n            c = p->u.str16[i];\n        else\n            c = p->u.str8[i];\n        if (c == sep || c == '\\\\') {\n            putchar('\\\\');\n            putchar(c);\n        } else if (c >= ' ' && c <= 126) {\n            putchar(c);\n        } else if (c == '\\n') {\n            putchar('\\\\');\n            putchar('n');\n        } else {\n            printf(\"\\\\u%04x\", c);\n        }\n    }\n    putchar(sep);\n}\n\nstatic __maybe_unused void JS_DumpAtoms(JSRuntime *rt)\n{\n    JSAtomStruct *p;\n    int h, i;\n    /* This only dumps hashed atoms, not JS_ATOM_TYPE_SYMBOL atoms */\n    printf(\"JSAtom count=%d size=%d hash_size=%d:\\n\",\n           rt->atom_count, rt->atom_size, rt->atom_hash_size);\n    printf(\"JSAtom hash table: {\\n\");\n    for(i = 0; i < rt->atom_hash_size; i++) {\n        h = rt->atom_hash[i];\n        if (h) {\n            printf(\"  %d:\", i);\n            while (h) {\n                p = rt->atom_array[h];\n                printf(\" \");\n                JS_DumpString(rt, p);\n                h = p->hash_next;\n            }\n            printf(\"\\n\");\n        }\n    }\n    printf(\"}\\n\");\n    printf(\"JSAtom table: {\\n\");\n    for(i = 0; i < rt->atom_size; i++) {\n        p = rt->atom_array[i];\n        if (!atom_is_free(p)) {\n            printf(\"  %d: { %d %08x \", i, p->atom_type, p->hash);\n            if (!(p->len == 0 && p->is_wide_char != 0))\n                JS_DumpString(rt, p);\n            printf(\" %d }\\n\", p->hash_next);\n        }\n    }\n    printf(\"}\\n\");\n}\n\nstatic int JS_ResizeAtomHash(JSRuntime *rt, int new_hash_size)\n{\n    JSAtomStruct *p;\n    uint32_t new_hash_mask, h, i, hash_next1, j, *new_hash;\n\n    assert((new_hash_size & (new_hash_size - 1)) == 0); /* power of two */\n    new_hash_mask = new_hash_size - 1;\n    new_hash = js_mallocz_rt(rt, sizeof(rt->atom_hash[0]) * new_hash_size);\n    if (!new_hash)\n        return -1;\n    for(i = 0; i < rt->atom_hash_size; i++) {\n        h = rt->atom_hash[i];\n        while (h != 0) {\n            p = rt->atom_array[h];\n            hash_next1 = p->hash_next;\n            /* add in new hash table */\n            j = p->hash & new_hash_mask;\n            p->hash_next = new_hash[j];\n            new_hash[j] = h;\n            h = hash_next1;\n        }\n    }\n    js_free_rt(rt, rt->atom_hash);\n    rt->atom_hash = new_hash;\n    rt->atom_hash_size = new_hash_size;\n    rt->atom_count_resize = JS_ATOM_COUNT_RESIZE(new_hash_size);\n    //    JS_DumpAtoms(rt);\n    return 0;\n}\n\n#if defined(__APPLE__)\n// not best solution\n#include <mach/mach_time.h>\n#ifndef CLOCK_REALTIME\n#define CLOCK_REALTIME 0\nint clock_gettime(int clk_id, struct timespec *t){\n    mach_timebase_info_data_t timebase;\n    mach_timebase_info(&timebase);\n    uint64_t time;\n    time = mach_absolute_time();\n    double nseconds = ((double)time * (double)timebase.numer)/((double)timebase.denom);\n    double seconds = ((double)time * (double)timebase.numer)/((double)timebase.denom * 1e9);\n    t->tv_sec = seconds;\n    t->tv_nsec = nseconds;\n    return 0;\n}\n#endif\n#endif\n\nstatic int JS_InitAtoms(JSRuntime *rt)\n{\n    int i, len, atom_type;\n    const char *p;\n\n    rt->atom_hash_size = 0;\n    rt->atom_hash = NULL;\n    rt->atom_count = 0;\n    rt->atom_size = 0;\n    rt->atom_free_index = 0;\n    if (JS_ResizeAtomHash(rt, 256))     /* there are at least 195 predefined atoms */\n        return -1;\n\n    p = js_atom_init;\n    for(i = 1; i < JS_ATOM_END; i++) {\n        if (i == JS_ATOM_Private_brand)\n            atom_type = JS_ATOM_TYPE_PRIVATE;\n        else if (i >= JS_ATOM_Symbol_toPrimitive)\n            atom_type = JS_ATOM_TYPE_SYMBOL;\n        else\n            atom_type = JS_ATOM_TYPE_STRING;\n        len = strlen(p);\n        if (__JS_NewAtomInit(rt, p, len, atom_type) == JS_ATOM_NULL)\n            return -1;\n        p = p + len + 1;\n    }\n    return 0;\n}\n\nstatic JSAtom JS_DupAtomRT(JSRuntime *rt, JSAtom v)\n{\n    JSAtomStruct *p;\n\n    if (!__JS_AtomIsConst(v)) {\n        p = rt->atom_array[v];\n        p->header.ref_count++;\n    }\n    return v;\n}\n\nJSAtom JS_DupAtom(JSContext *ctx, JSAtom v)\n{\n    JSRuntime *rt;\n    JSAtomStruct *p;\n\n    if (!__JS_AtomIsConst(v)) {\n        rt = ctx->rt;\n        p = rt->atom_array[v];\n        p->header.ref_count++;\n    }\n    return v;\n}\n\nstatic JSAtomKindEnum JS_AtomGetKind(JSContext *ctx, JSAtom v)\n{\n    JSRuntime *rt;\n    JSAtomStruct *p;\n\n    rt = ctx->rt;\n    if (__JS_AtomIsTaggedInt(v))\n        return JS_ATOM_KIND_STRING;\n    p = rt->atom_array[v];\n    switch(p->atom_type) {\n    case JS_ATOM_TYPE_STRING:\n        return JS_ATOM_KIND_STRING;\n    case JS_ATOM_TYPE_GLOBAL_SYMBOL:\n        return JS_ATOM_KIND_SYMBOL;\n    case JS_ATOM_TYPE_SYMBOL:\n        switch(p->hash) {\n        case JS_ATOM_HASH_SYMBOL:\n            return JS_ATOM_KIND_SYMBOL;\n        case JS_ATOM_HASH_PRIVATE:\n            return JS_ATOM_KIND_PRIVATE;\n        default:\n            abort();\n        }\n    default:\n        abort();\n    }\n}\n\nstatic BOOL JS_AtomIsString(JSContext *ctx, JSAtom v)\n{\n    return JS_AtomGetKind(ctx, v) == JS_ATOM_KIND_STRING;\n}\n\nstatic JSAtom js_get_atom_index(JSRuntime *rt, JSAtomStruct *p)\n{\n    uint32_t i = p->hash_next;  /* atom_index */\n    if (p->atom_type != JS_ATOM_TYPE_SYMBOL) {\n        JSAtomStruct *p1;\n\n        i = rt->atom_hash[p->hash & (rt->atom_hash_size - 1)];\n        p1 = rt->atom_array[i];\n        while (p1 != p) {\n            assert(i != 0);\n            i = p1->hash_next;\n            p1 = rt->atom_array[i];\n        }\n    }\n    return i;\n}\n\n/* string case (internal). Return JS_ATOM_NULL if error. 'str' is\n   freed. */\nstatic JSAtom __JS_NewAtom(JSRuntime *rt, JSString *str, int atom_type)\n{\n    uint32_t h, h1, i;\n    JSAtomStruct *p;\n    int len;\n\n#if 0\n    printf(\"__JS_NewAtom: \");  JS_DumpString(rt, str); printf(\"\\n\");\n#endif\n    if (atom_type < JS_ATOM_TYPE_SYMBOL) {\n        /* str is not NULL */\n        if (str->atom_type == atom_type) {\n            /* str is the atom, return its index */\n            i = js_get_atom_index(rt, str);\n            /* reduce string refcount and increase atom's unless constant */\n            if (__JS_AtomIsConst(i))\n                str->header.ref_count--;\n            return i;\n        }\n        /* try and locate an already registered atom */\n        len = str->len;\n        h = hash_string(str, atom_type);\n        h &= JS_ATOM_HASH_MASK;\n        h1 = h & (rt->atom_hash_size - 1);\n        i = rt->atom_hash[h1];\n        while (i != 0) {\n            p = rt->atom_array[i];\n            if (p->hash == h &&\n                p->atom_type == atom_type &&\n                p->len == len &&\n                js_string_memcmp(p, str, len) == 0) {\n                if (!__JS_AtomIsConst(i))\n                    p->header.ref_count++;\n                goto done;\n            }\n            i = p->hash_next;\n        }\n    } else {\n        h1 = 0; /* avoid warning */\n        if (atom_type == JS_ATOM_TYPE_SYMBOL) {\n            h = JS_ATOM_HASH_SYMBOL;\n        } else {\n            h = JS_ATOM_HASH_PRIVATE;\n            atom_type = JS_ATOM_TYPE_SYMBOL;\n        }\n    }\n\n    if (rt->atom_free_index == 0) {\n        /* allow new atom entries */\n        uint32_t new_size, start;\n        JSAtomStruct **new_array;\n\n        /* alloc new with size progression 3/2:\n           4 6 9 13 19 28 42 63 94 141 211 316 474 711 1066 1599 2398 3597 5395 8092\n           preallocating space for predefined atoms (at least 195).\n         */\n        new_size = max_int(211, rt->atom_size * 3 / 2);\n        if (new_size > JS_ATOM_MAX)\n            goto fail;\n        /* XXX: should use realloc2 to use slack space */\n        new_array = js_realloc_rt(rt, rt->atom_array, sizeof(*new_array) * new_size);\n        if (!new_array)\n            goto fail;\n        /* Note: the atom 0 is not used */\n        start = rt->atom_size;\n        if (start == 0) {\n            /* JS_ATOM_NULL entry */\n            p = js_mallocz_rt(rt, sizeof(JSAtomStruct));\n            if (!p) {\n                js_free_rt(rt, new_array);\n                goto fail;\n            }\n            p->header.ref_count = 1;  /* not refcounted */\n            p->atom_type = JS_ATOM_TYPE_SYMBOL;\n#ifdef DUMP_LEAKS\n            list_add_tail(&p->link, &rt->string_list);\n#endif\n            new_array[0] = p;\n            rt->atom_count++;\n            start = 1;\n        }\n        rt->atom_size = new_size;\n        rt->atom_array = new_array;\n        rt->atom_free_index = start;\n        for(i = start; i < new_size; i++) {\n            uint32_t next;\n            if (i == (new_size - 1))\n                next = 0;\n            else\n                next = i + 1;\n            rt->atom_array[i] = atom_set_free(next);\n        }\n    }\n\n    if (str) {\n        if (str->atom_type == 0) {\n            p = str;\n            p->atom_type = atom_type;\n        } else {\n            p = js_malloc_rt(rt, sizeof(JSString) +\n                             (str->len << str->is_wide_char) +\n                             1 - str->is_wide_char);\n            if (unlikely(!p))\n                goto fail;\n            p->header.ref_count = 1;\n            p->is_wide_char = str->is_wide_char;\n            p->len = str->len;\n#ifdef DUMP_LEAKS\n            list_add_tail(&p->link, &rt->string_list);\n#endif\n            memcpy(p->u.str8, str->u.str8, (str->len << str->is_wide_char) +\n                   1 - str->is_wide_char);\n            js_free_string(rt, str);\n        }\n    } else {\n        p = js_malloc_rt(rt, sizeof(JSAtomStruct)); /* empty wide string */\n        if (!p)\n            return JS_ATOM_NULL;\n        p->header.ref_count = 1;\n        p->is_wide_char = 1;    /* Hack to represent NULL as a JSString */\n        p->len = 0;\n#ifdef DUMP_LEAKS\n        list_add_tail(&p->link, &rt->string_list);\n#endif\n    }\n\n    /* use an already free entry */\n    i = rt->atom_free_index;\n    rt->atom_free_index = atom_get_free(rt->atom_array[i]);\n    rt->atom_array[i] = p;\n\n    p->hash = h;\n    p->hash_next = i;   /* atom_index */\n    p->atom_type = atom_type;\n\n    rt->atom_count++;\n\n    if (atom_type != JS_ATOM_TYPE_SYMBOL) {\n        p->hash_next = rt->atom_hash[h1];\n        rt->atom_hash[h1] = i;\n        if (unlikely(rt->atom_count >= rt->atom_count_resize))\n            JS_ResizeAtomHash(rt, rt->atom_hash_size * 2);\n    }\n\n    //    JS_DumpAtoms(rt);\n    return i;\n\n fail:\n    i = JS_ATOM_NULL;\n done:\n    if (str)\n        js_free_string(rt, str);\n    return i;\n}\n\n/* only works with zero terminated 8 bit strings */\nstatic JSAtom __JS_NewAtomInit(JSRuntime *rt, const char *str, int len,\n                               int atom_type)\n{\n    JSString *p;\n    p = js_alloc_string_rt(rt, len, 0);\n    if (!p)\n        return JS_ATOM_NULL;\n    memcpy(p->u.str8, str, len);\n    p->u.str8[len] = '\\0';\n    return __JS_NewAtom(rt, p, atom_type);\n}\n\nstatic JSAtom __JS_FindAtom(JSRuntime *rt, const char *str, size_t len,\n                            int atom_type)\n{\n    uint32_t h, h1, i;\n    JSAtomStruct *p;\n\n    h = hash_string8((const uint8_t *)str, len, JS_ATOM_TYPE_STRING);\n    h &= JS_ATOM_HASH_MASK;\n    h1 = h & (rt->atom_hash_size - 1);\n    i = rt->atom_hash[h1];\n    while (i != 0) {\n        p = rt->atom_array[i];\n        if (p->hash == h &&\n            p->atom_type == JS_ATOM_TYPE_STRING &&\n            p->len == len &&\n            p->is_wide_char == 0 &&\n            memcmp(p->u.str8, str, len) == 0) {\n            if (!__JS_AtomIsConst(i))\n                p->header.ref_count++;\n            return i;\n        }\n        i = p->hash_next;\n    }\n    return JS_ATOM_NULL;\n}\n\nstatic void JS_FreeAtomStruct(JSRuntime *rt, JSAtomStruct *p)\n{\n#if 0   /* JS_ATOM_NULL is not refcounted: __JS_AtomIsConst() includes 0 */\n    if (unlikely(i == JS_ATOM_NULL)) {\n        p->header.ref_count = INT32_MAX / 2;\n        return;\n    }\n#endif\n    uint32_t i = p->hash_next;  /* atom_index */\n    if (p->atom_type != JS_ATOM_TYPE_SYMBOL) {\n        JSAtomStruct *p0, *p1;\n        uint32_t h0;\n\n        h0 = p->hash & (rt->atom_hash_size - 1);\n        i = rt->atom_hash[h0];\n        p1 = rt->atom_array[i];\n        if (p1 == p) {\n            rt->atom_hash[h0] = p1->hash_next;\n        } else {\n            for(;;) {\n                assert(i != 0);\n                p0 = p1;\n                i = p1->hash_next;\n                p1 = rt->atom_array[i];\n                if (p1 == p) {\n                    p0->hash_next = p1->hash_next;\n                    break;\n                }\n            }\n        }\n    }\n    /* insert in free atom list */\n    rt->atom_array[i] = atom_set_free(rt->atom_free_index);\n    rt->atom_free_index = i;\n    /* free the string structure */\n#ifdef DUMP_LEAKS\n    list_del(&p->link);\n#endif\n    js_free_rt(rt, p);\n    rt->atom_count--;\n    assert(rt->atom_count >= 0);\n}\n\nstatic void __JS_FreeAtom(JSRuntime *rt, uint32_t i)\n{\n    JSAtomStruct *p;\n\n    p = rt->atom_array[i];\n    if (--p->header.ref_count > 0)\n        return;\n    JS_FreeAtomStruct(rt, p);\n}\n\n/* Warning: 'p' is freed */\nstatic JSAtom JS_NewAtomStr(JSContext *ctx, JSString *p)\n{\n    JSRuntime *rt = ctx->rt;\n    uint32_t n;\n    if (is_num_string(&n, p)) {\n        if (n <= JS_ATOM_MAX_INT) {\n            js_free_string(rt, p);\n            return __JS_AtomFromUInt32(n);\n        }\n    }\n    /* XXX: should generate an exception */\n    return __JS_NewAtom(rt, p, JS_ATOM_TYPE_STRING);\n}\n\nJSAtom JS_NewAtomLen(JSContext *ctx, const char *str, size_t len)\n{\n    JSValue val;\n\n    if (len == 0 || !is_digit(*str)) {\n        JSAtom atom = __JS_FindAtom(ctx->rt, str, len, JS_ATOM_TYPE_STRING);\n        if (atom)\n            return atom;\n    }\n    val = JS_NewStringLen(ctx, str, len);\n    if (JS_IsException(val))\n        return JS_ATOM_NULL;\n    return JS_NewAtomStr(ctx, JS_VALUE_GET_STRING(val));\n}\n\nJSAtom JS_NewAtom(JSContext *ctx, const char *str)\n{\n    return JS_NewAtomLen(ctx, str, strlen(str));\n}\n\nJSAtom JS_NewAtomUInt32(JSContext *ctx, uint32_t n)\n{\n    if (n <= JS_ATOM_MAX_INT) {\n        return __JS_AtomFromUInt32(n);\n    } else {\n        char buf[11];\n        JSValue val;\n        snprintf(buf, sizeof(buf), \"%u\", n);\n        val = JS_NewString(ctx, buf);\n        if (JS_IsException(val))\n            return JS_ATOM_NULL;\n        return __JS_NewAtom(ctx->rt, JS_VALUE_GET_STRING(val),\n                            JS_ATOM_TYPE_STRING);\n    }\n}\n\nstatic JSAtom JS_NewAtomInt64(JSContext *ctx, int64_t n)\n{\n    if ((uint64_t)n <= JS_ATOM_MAX_INT) {\n        return __JS_AtomFromUInt32((uint32_t)n);\n    } else {\n        char buf[24];\n        JSValue val;\n        snprintf(buf, sizeof(buf), \"%\" PRId64 , n);\n        val = JS_NewString(ctx, buf);\n        if (JS_IsException(val))\n            return JS_ATOM_NULL;\n        return __JS_NewAtom(ctx->rt, JS_VALUE_GET_STRING(val),\n                            JS_ATOM_TYPE_STRING);\n    }\n}\n\n/* 'p' is freed */\nstatic JSValue JS_NewSymbol(JSContext *ctx, JSString *p, int atom_type)\n{\n    JSRuntime *rt = ctx->rt;\n    JSAtom atom;\n    atom = __JS_NewAtom(rt, p, atom_type);\n    if (atom == JS_ATOM_NULL)\n        return JS_ThrowOutOfMemory(ctx);\n    return JS_MKPTR(JS_TAG_SYMBOL, rt->atom_array[atom]);\n}\n\n/* descr must be a non-numeric string atom */\nstatic JSValue JS_NewSymbolFromAtom(JSContext *ctx, JSAtom descr,\n                                    int atom_type)\n{\n    JSRuntime *rt = ctx->rt;\n    JSString *p;\n\n    assert(!__JS_AtomIsTaggedInt(descr));\n    assert(descr < rt->atom_size);\n    p = rt->atom_array[descr];\n    JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, p));\n    return JS_NewSymbol(ctx, p, atom_type);\n}\n\n#define ATOM_GET_STR_BUF_SIZE 64\n\n/* Should only be used for debug. */\nstatic const char *JS_AtomGetStrRT(JSRuntime *rt, char *buf, int buf_size,\n                                   JSAtom atom)\n{\n    if (__JS_AtomIsTaggedInt(atom)) {\n        snprintf(buf, buf_size, \"%u\", __JS_AtomToUInt32(atom));\n    } else {\n        JSAtomStruct *p;\n        assert(atom < rt->atom_size);\n        if (atom == JS_ATOM_NULL) {\n            snprintf(buf, buf_size, \"<null>\");\n        } else {\n            int i, c;\n            char *q;\n            JSString *str;\n\n            q = buf;\n            p = rt->atom_array[atom];\n            assert(!atom_is_free(p));\n            str = p;\n            if (str) {\n                if (!str->is_wide_char) {\n                    /* special case ASCII strings */\n                    c = 0;\n                    for(i = 0; i < str->len; i++) {\n                        c |= str->u.str8[i];\n                    }\n                    if (c < 0x80)\n                        return (const char *)str->u.str8;\n                }\n                for(i = 0; i < str->len; i++) {\n                    if (str->is_wide_char)\n                        c = str->u.str16[i];\n                    else\n                        c = str->u.str8[i];\n                    if ((q - buf) >= buf_size - UTF8_CHAR_LEN_MAX)\n                        break;\n                    if (c < 128) {\n                        *q++ = c;\n                    } else {\n                        q += unicode_to_utf8((uint8_t *)q, c);\n                    }\n                }\n            }\n            *q = '\\0';\n        }\n    }\n    return buf;\n}\n\nstatic const char *JS_AtomGetStr(JSContext *ctx, char *buf, int buf_size, JSAtom atom)\n{\n    return JS_AtomGetStrRT(ctx->rt, buf, buf_size, atom);\n}\n\nstatic JSValue __JS_AtomToValue(JSContext *ctx, JSAtom atom, BOOL force_string)\n{\n    char buf[ATOM_GET_STR_BUF_SIZE];\n\n    if (__JS_AtomIsTaggedInt(atom)) {\n        snprintf(buf, sizeof(buf), \"%u\", __JS_AtomToUInt32(atom));\n        return JS_NewString(ctx, buf);\n    } else {\n        JSRuntime *rt = ctx->rt;\n        JSAtomStruct *p;\n        assert(atom < rt->atom_size);\n        p = rt->atom_array[atom];\n        if (p->atom_type == JS_ATOM_TYPE_STRING) {\n            goto ret_string;\n        } else if (force_string) {\n            if (p->len == 0 && p->is_wide_char != 0) {\n                /* no description string */\n                p = rt->atom_array[JS_ATOM_empty_string];\n            }\n        ret_string:\n            return JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, p));\n        } else {\n            return JS_DupValue(ctx, JS_MKPTR(JS_TAG_SYMBOL, p));\n        }\n    }\n}\n\nJSValue JS_AtomToValue(JSContext *ctx, JSAtom atom)\n{\n    return __JS_AtomToValue(ctx, atom, FALSE);\n}\n\nJSValue JS_AtomToString(JSContext *ctx, JSAtom atom)\n{\n    return __JS_AtomToValue(ctx, atom, TRUE);\n}\n\n/* return TRUE if the atom is an array index (i.e. 0 <= index <=\n   2^32-2 and return its value */\nstatic BOOL JS_AtomIsArrayIndex(JSContext *ctx, uint32_t *pval, JSAtom atom)\n{\n    if (__JS_AtomIsTaggedInt(atom)) {\n        *pval = __JS_AtomToUInt32(atom);\n        return TRUE;\n    } else {\n        JSRuntime *rt = ctx->rt;\n        JSAtomStruct *p;\n        uint32_t val;\n\n        assert(atom < rt->atom_size);\n        p = rt->atom_array[atom];\n        if (p->atom_type == JS_ATOM_TYPE_STRING &&\n            is_num_string(&val, p) && val != -1) {\n            *pval = val;\n            return TRUE;\n        } else {\n            *pval = 0;\n            return FALSE;\n        }\n    }\n}\n\n/* This test must be fast if atom is not a numeric index (e.g. a\n   method name). Return JS_UNDEFINED if not a numeric\n   index. JS_EXCEPTION can also be returned. */\nstatic JSValue JS_AtomIsNumericIndex1(JSContext *ctx, JSAtom atom)\n{\n    JSRuntime *rt = ctx->rt;\n    JSAtomStruct *p1;\n    JSString *p;\n    int c, len, ret;\n    JSValue num, str;\n\n    if (__JS_AtomIsTaggedInt(atom))\n        return JS_NewInt32(ctx, __JS_AtomToUInt32(atom));\n    assert(atom < rt->atom_size);\n    p1 = rt->atom_array[atom];\n    if (p1->atom_type != JS_ATOM_TYPE_STRING)\n        return JS_UNDEFINED;\n    p = p1;\n    len = p->len;\n    if (p->is_wide_char) {\n        const uint16_t *r = p->u.str16, *r_end = p->u.str16 + len;\n        if (r >= r_end)\n            return JS_UNDEFINED;\n        c = *r;\n        if (c == '-') {\n            if (r >= r_end)\n                return JS_UNDEFINED;\n            r++;\n            c = *r;\n            /* -0 case is specific */\n            if (c == '0' && len == 2)\n                goto minus_zero;\n        }\n        /* XXX: should test NaN, but the tests do not check it */\n        if (!is_num(c)) {\n            /* XXX: String should be normalized, therefore 8-bit only */\n            const uint16_t nfinity16[7] = { 'n', 'f', 'i', 'n', 'i', 't', 'y' };\n            if (!(c =='I' && (r_end - r) == 8 &&\n                  !memcmp(r + 1, nfinity16, sizeof(nfinity16))))\n                return JS_UNDEFINED;\n        }\n    } else {\n        const uint8_t *r = p->u.str8, *r_end = p->u.str8 + len;\n        if (r >= r_end)\n            return JS_UNDEFINED;\n        c = *r;\n        if (c == '-') {\n            if (r >= r_end)\n                return JS_UNDEFINED;\n            r++;\n            c = *r;\n            /* -0 case is specific */\n            if (c == '0' && len == 2) {\n            minus_zero:\n                return __JS_NewFloat64(ctx, -0.0);\n            }\n        }\n        if (!is_num(c)) {\n            if (!(c =='I' && (r_end - r) == 8 &&\n                  !memcmp(r + 1, \"nfinity\", 7)))\n                return JS_UNDEFINED;\n        }\n    }\n    /* XXX: bignum: would be better to only accept integer to avoid\n       relying on current floating point precision */\n    /* this is ECMA CanonicalNumericIndexString primitive */\n    num = JS_ToNumber(ctx, JS_MKPTR(JS_TAG_STRING, p));\n    if (JS_IsException(num))\n        return num;\n    str = JS_ToString(ctx, num);\n    if (JS_IsException(str)) {\n        JS_FreeValue(ctx, num);\n        return str;\n    }\n    ret = js_string_compare(ctx, p, JS_VALUE_GET_STRING(str));\n    JS_FreeValue(ctx, str);\n    if (ret == 0) {\n        return num;\n    } else {\n        JS_FreeValue(ctx, num);\n        return JS_UNDEFINED;\n    }\n}\n\n/* return -1 if exception or TRUE/FALSE */\nstatic int JS_AtomIsNumericIndex(JSContext *ctx, JSAtom atom)\n{\n    JSValue num;\n    num = JS_AtomIsNumericIndex1(ctx, atom);\n    if (likely(JS_IsUndefined(num)))\n        return FALSE;\n    if (JS_IsException(num))\n        return -1;\n    JS_FreeValue(ctx, num);\n    return TRUE;\n}\n\nvoid JS_FreeAtom(JSContext *ctx, JSAtom v)\n{\n    if (!__JS_AtomIsConst(v))\n        __JS_FreeAtom(ctx->rt, v);\n}\n\nvoid JS_FreeAtomRT(JSRuntime *rt, JSAtom v)\n{\n    if (!__JS_AtomIsConst(v))\n        __JS_FreeAtom(rt, v);\n}\n\n/* return TRUE if 'v' is a symbol with a string description */\nstatic BOOL JS_AtomSymbolHasDescription(JSContext *ctx, JSAtom v)\n{\n    JSRuntime *rt;\n    JSAtomStruct *p;\n\n    rt = ctx->rt;\n    if (__JS_AtomIsTaggedInt(v))\n        return FALSE;\n    p = rt->atom_array[v];\n    return (((p->atom_type == JS_ATOM_TYPE_SYMBOL &&\n              p->hash == JS_ATOM_HASH_SYMBOL) ||\n             p->atom_type == JS_ATOM_TYPE_GLOBAL_SYMBOL) &&\n            !(p->len == 0 && p->is_wide_char != 0));\n}\n\nstatic __maybe_unused void print_atom(JSContext *ctx, JSAtom atom)\n{\n    char buf[ATOM_GET_STR_BUF_SIZE];\n    const char *p;\n    int i;\n\n    /* XXX: should handle embedded null characters */\n    /* XXX: should move encoding code to JS_AtomGetStr */\n    p = JS_AtomGetStr(ctx, buf, sizeof(buf), atom);\n    for (i = 0; p[i]; i++) {\n        int c = (unsigned char)p[i];\n        if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||\n              (c == '_' || c == '$') || (c >= '0' && c <= '9' && i > 0)))\n            break;\n    }\n    if (i > 0 && p[i] == '\\0') {\n        printf(\"%s\", p);\n    } else {\n        putchar('\"');\n        printf(\"%.*s\", i, p);\n        for (; p[i]; i++) {\n            int c = (unsigned char)p[i];\n            if (c == '\\\"' || c == '\\\\') {\n                putchar('\\\\');\n                putchar(c);\n            } else if (c >= ' ' && c <= 126) {\n                putchar(c);\n            } else if (c == '\\n') {\n                putchar('\\\\');\n                putchar('n');\n            } else {\n                printf(\"\\\\u%04x\", c);\n            }\n        }\n        putchar('\\\"');\n    }\n}\n\n/* free with JS_FreeCString() */\nconst char *JS_AtomToCString(JSContext *ctx, JSAtom atom)\n{\n    JSValue str;\n    const char *cstr;\n\n    str = JS_AtomToString(ctx, atom);\n    if (JS_IsException(str))\n        return NULL;\n    cstr = JS_ToCString(ctx, str);\n    JS_FreeValue(ctx, str);\n    return cstr;\n}\n\n/* return a string atom containing name concatenated with str1 */\nstatic JSAtom js_atom_concat_str(JSContext *ctx, JSAtom name, const char *str1)\n{\n    JSValue str;\n    JSAtom atom;\n    const char *cstr;\n    char *cstr2;\n    size_t len, len1;\n    \n    str = JS_AtomToString(ctx, name);\n    if (JS_IsException(str))\n        return JS_ATOM_NULL;\n    cstr = JS_ToCStringLen(ctx, &len, str);\n    if (!cstr)\n        goto fail;\n    len1 = strlen(str1);\n    cstr2 = js_malloc(ctx, len + len1 + 1);\n    if (!cstr2)\n        goto fail;\n    memcpy(cstr2, cstr, len);\n    memcpy(cstr2 + len, str1, len1);\n    cstr2[len + len1] = '\\0';\n    atom = JS_NewAtomLen(ctx, cstr2, len + len1);\n    js_free(ctx, cstr2);\n    JS_FreeCString(ctx, cstr);\n    JS_FreeValue(ctx, str);\n    return atom;\n fail:\n    JS_FreeCString(ctx, cstr);\n    JS_FreeValue(ctx, str);\n    return JS_ATOM_NULL;\n}\n\nstatic JSAtom js_atom_concat_num(JSContext *ctx, JSAtom name, uint32_t n)\n{\n    char buf[16];\n    snprintf(buf, sizeof(buf), \"%u\", n);\n    return js_atom_concat_str(ctx, name, buf);\n}\n\nstatic inline BOOL JS_IsEmptyString(JSValueConst v)\n{\n    return JS_VALUE_GET_TAG(v) == JS_TAG_STRING && JS_VALUE_GET_STRING(v)->len == 0;\n}\n\n/* JSClass support */\n\n/* a new class ID is allocated if *pclass_id != 0 */\nJSClassID JS_NewClassID(JSClassID *pclass_id)\n{\n    JSClassID class_id;\n    /* XXX: make it thread safe */\n    class_id = *pclass_id;\n    if (class_id == 0) {\n        class_id = js_class_id_alloc++;\n        *pclass_id = class_id;\n    }\n    return class_id;\n}\n\nBOOL JS_IsRegisteredClass(JSRuntime *rt, JSClassID class_id)\n{\n    return (class_id < rt->class_count &&\n            rt->class_array[class_id].class_id != 0);\n}\n\n/* create a new object internal class. Return -1 if error, 0 if\n   OK. The finalizer can be NULL if none is needed. */\nstatic int JS_NewClass1(JSRuntime *rt, JSClassID class_id,\n                        const JSClassDef *class_def, JSAtom name)\n{\n    int new_size, i;\n    JSClass *cl, *new_class_array;\n    struct list_head *el;\n\n    if (class_id >= (1 << 16))\n        return -1;\n    if (class_id < rt->class_count &&\n        rt->class_array[class_id].class_id != 0)\n        return -1;\n\n    if (class_id >= rt->class_count) {\n        new_size = max_int(JS_CLASS_INIT_COUNT,\n                           max_int(class_id + 1, rt->class_count * 3 / 2));\n\n        /* reallocate the context class prototype array, if any */\n        list_for_each(el, &rt->context_list) {\n            JSContext *ctx = list_entry(el, JSContext, link);\n            JSValue *new_tab;\n            new_tab = js_realloc_rt(rt, ctx->class_proto,\n                                    sizeof(ctx->class_proto[0]) * new_size);\n            if (!new_tab)\n                return -1;\n            for(i = rt->class_count; i < new_size; i++)\n                new_tab[i] = JS_NULL;\n            ctx->class_proto = new_tab;\n        }\n        /* reallocate the class array */\n        new_class_array = js_realloc_rt(rt, rt->class_array,\n                                        sizeof(JSClass) * new_size);\n        if (!new_class_array)\n            return -1;\n        memset(new_class_array + rt->class_count, 0,\n               (new_size - rt->class_count) * sizeof(JSClass));\n        rt->class_array = new_class_array;\n        rt->class_count = new_size;\n    }\n    cl = &rt->class_array[class_id];\n    cl->class_id = class_id;\n    cl->class_name = JS_DupAtomRT(rt, name);\n    cl->finalizer = class_def->finalizer;\n    cl->gc_mark = class_def->gc_mark;\n    cl->call = class_def->call;\n    cl->exotic = class_def->exotic;\n    return 0;\n}\n\nint JS_NewClass(JSRuntime *rt, JSClassID class_id, const JSClassDef *class_def)\n{\n    int ret, len;\n    JSAtom name;\n\n    len = strlen(class_def->class_name);\n    name = __JS_FindAtom(rt, class_def->class_name, len, JS_ATOM_TYPE_STRING);\n    if (name == JS_ATOM_NULL) {\n        name = __JS_NewAtomInit(rt, class_def->class_name, len, JS_ATOM_TYPE_STRING);\n        if (name == JS_ATOM_NULL)\n            return -1;\n    }\n    ret = JS_NewClass1(rt, class_id, class_def, name);\n    JS_FreeAtomRT(rt, name);\n    return ret;\n}\n\nstatic JSValue js_new_string8(JSContext *ctx, const uint8_t *buf, int len)\n{\n    JSString *str;\n\n    if (len <= 0) {\n        return JS_AtomToString(ctx, JS_ATOM_empty_string);\n    }\n    str = js_alloc_string(ctx, len, 0);\n    if (!str)\n        return JS_EXCEPTION;\n    memcpy(str->u.str8, buf, len);\n    str->u.str8[len] = '\\0';\n    return JS_MKPTR(JS_TAG_STRING, str);\n}\n\nstatic JSValue js_new_string16(JSContext *ctx, const uint16_t *buf, int len)\n{\n    JSString *str;\n    str = js_alloc_string(ctx, len, 1);\n    if (!str)\n        return JS_EXCEPTION;\n    memcpy(str->u.str16, buf, len * 2);\n    return JS_MKPTR(JS_TAG_STRING, str);\n}\n\nstatic JSValue js_new_string_char(JSContext *ctx, uint16_t c)\n{\n    if (c < 0x100) {\n        uint8_t ch8 = c;\n        return js_new_string8(ctx, &ch8, 1);\n    } else {\n        uint16_t ch16 = c;\n        return js_new_string16(ctx, &ch16, 1);\n    }\n}\n\nstatic JSValue js_sub_string(JSContext *ctx, JSString *p, int start, int end)\n{\n    int len = end - start;\n    if (start == 0 && end == p->len) {\n        return JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, p));\n    }\n    if (p->is_wide_char && len > 0) {\n        JSString *str;\n        int i;\n        uint16_t c = 0;\n        for (i = start; i < end; i++) {\n            c |= p->u.str16[i];\n        }\n        if (c > 0xFF)\n            return js_new_string16(ctx, p->u.str16 + start, len);\n\n        str = js_alloc_string(ctx, len, 0);\n        if (!str)\n            return JS_EXCEPTION;\n        for (i = 0; i < len; i++) {\n            str->u.str8[i] = p->u.str16[start + i];\n        }\n        str->u.str8[len] = '\\0';\n        return JS_MKPTR(JS_TAG_STRING, str);\n    } else {\n        return js_new_string8(ctx, p->u.str8 + start, len);\n    }\n}\n\ntypedef struct StringBuffer {\n    JSContext *ctx;\n    JSString *str;\n    int len;\n    int size;\n    int is_wide_char;\n    int error_status;\n} StringBuffer;\n\n/* It is valid to call string_buffer_end() and all string_buffer functions even\n   if string_buffer_init() or another string_buffer function returns an error.\n   If the error_status is set, string_buffer_end() returns JS_EXCEPTION.\n */\nstatic int string_buffer_init2(JSContext *ctx, StringBuffer *s, int size,\n                               int is_wide)\n{\n    s->ctx = ctx;\n    s->size = size;\n    s->len = 0;\n    s->is_wide_char = is_wide;\n    s->error_status = 0;\n    s->str = js_alloc_string(ctx, size, is_wide);\n    if (unlikely(!s->str)) {\n        s->size = 0;\n        return s->error_status = -1;\n    }\n#ifdef DUMP_LEAKS\n    /* the StringBuffer may reallocate the JSString, only link it at the end */\n    list_del(&s->str->link);\n#endif\n    return 0;\n}\n\nstatic inline int string_buffer_init(JSContext *ctx, StringBuffer *s, int size)\n{\n    return string_buffer_init2(ctx, s, size, 0);\n}\n\nstatic void string_buffer_free(StringBuffer *s)\n{\n    js_free(s->ctx, s->str);\n    s->str = NULL;\n}\n\nstatic int string_buffer_set_error(StringBuffer *s)\n{\n    js_free(s->ctx, s->str);\n    s->str = NULL;\n    s->size = 0;\n    s->len = 0;\n    return s->error_status = -1;\n}\n\nstatic no_inline int string_buffer_widen(StringBuffer *s, int size)\n{\n    JSString *str;\n    size_t slack;\n    int i;\n\n    if (s->error_status)\n        return -1;\n\n    str = js_realloc2(s->ctx, s->str, sizeof(JSString) + (size << 1), &slack);\n    if (!str)\n        return string_buffer_set_error(s);\n    size += slack >> 1;\n    for(i = s->len; i-- > 0;) {\n        str->u.str16[i] = str->u.str8[i];\n    }\n    s->is_wide_char = 1;\n    s->size = size;\n    s->str = str;\n    return 0;\n}\n\nstatic no_inline int string_buffer_realloc(StringBuffer *s, int new_len, int c)\n{\n    JSString *new_str;\n    int new_size;\n    size_t new_size_bytes, slack;\n\n    if (s->error_status)\n        return -1;\n\n    if (new_len > JS_STRING_LEN_MAX) {\n        JS_ThrowInternalError(s->ctx, \"string too long\");\n        return string_buffer_set_error(s);\n    }\n    new_size = min_int(max_int(new_len, s->size * 3 / 2), JS_STRING_LEN_MAX);\n    if (!s->is_wide_char && c >= 0x100) {\n        return string_buffer_widen(s, new_size);\n    }\n    new_size_bytes = sizeof(JSString) + (new_size << s->is_wide_char) + 1 - s->is_wide_char;\n    new_str = js_realloc2(s->ctx, s->str, new_size_bytes, &slack);\n    if (!new_str)\n        return string_buffer_set_error(s);\n    new_size = min_int(new_size + (slack >> s->is_wide_char), JS_STRING_LEN_MAX);\n    s->size = new_size;\n    s->str = new_str;\n    return 0;\n}\n\nstatic no_inline int string_buffer_putc_slow(StringBuffer *s, uint32_t c)\n{\n    if (unlikely(s->len >= s->size)) {\n        if (string_buffer_realloc(s, s->len + 1, c))\n            return -1;\n    }\n    if (s->is_wide_char) {\n        s->str->u.str16[s->len++] = c;\n    } else if (c < 0x100) {\n        s->str->u.str8[s->len++] = c;\n    } else {\n        if (string_buffer_widen(s, s->size))\n            return -1;\n        s->str->u.str16[s->len++] = c;\n    }\n    return 0;\n}\n\n/* 0 <= c <= 0xff */\nstatic int string_buffer_putc8(StringBuffer *s, uint32_t c)\n{\n    if (unlikely(s->len >= s->size)) {\n        if (string_buffer_realloc(s, s->len + 1, c))\n            return -1;\n    }\n    if (s->is_wide_char) {\n        s->str->u.str16[s->len++] = c;\n    } else {\n        s->str->u.str8[s->len++] = c;\n    }\n    return 0;\n}\n\n/* 0 <= c <= 0xffff */\nstatic int string_buffer_putc16(StringBuffer *s, uint32_t c)\n{\n    if (likely(s->len < s->size)) {\n        if (s->is_wide_char) {\n            s->str->u.str16[s->len++] = c;\n            return 0;\n        } else if (c < 0x100) {\n            s->str->u.str8[s->len++] = c;\n            return 0;\n        }\n    }\n    return string_buffer_putc_slow(s, c);\n}\n\n/* 0 <= c <= 0x10ffff */\nstatic int string_buffer_putc(StringBuffer *s, uint32_t c)\n{\n    if (unlikely(c >= 0x10000)) {\n        /* surrogate pair */\n        c -= 0x10000;\n        if (string_buffer_putc16(s, (c >> 10) + 0xd800))\n            return -1;\n        c = (c & 0x3ff) + 0xdc00;\n    }\n    return string_buffer_putc16(s, c);\n}\n\nstatic int string_get(const JSString *p, int idx) {\n    return p->is_wide_char ? p->u.str16[idx] : p->u.str8[idx];\n}\n\nstatic int string_getc(const JSString *p, int *pidx)\n{\n    int idx, c, c1;\n    idx = *pidx;\n    if (p->is_wide_char) {\n        c = p->u.str16[idx++];\n        if (c >= 0xd800 && c < 0xdc00 && idx < p->len) {\n            c1 = p->u.str16[idx];\n            if (c1 >= 0xdc00 && c1 < 0xe000) {\n                c = (((c & 0x3ff) << 10) | (c1 & 0x3ff)) + 0x10000;\n                idx++;\n            }\n        }\n    } else {\n        c = p->u.str8[idx++];\n    }\n    *pidx = idx;\n    return c;\n}\n\nstatic int string_buffer_write8(StringBuffer *s, const uint8_t *p, int len)\n{\n    int i;\n\n    if (s->len + len > s->size) {\n        if (string_buffer_realloc(s, s->len + len, 0))\n            return -1;\n    }\n    if (s->is_wide_char) {\n        for (i = 0; i < len; i++) {\n            s->str->u.str16[s->len + i] = p[i];\n        }\n        s->len += len;\n    } else {\n        memcpy(&s->str->u.str8[s->len], p, len);\n        s->len += len;\n    }\n    return 0;\n}\n\nstatic int string_buffer_write16(StringBuffer *s, const uint16_t *p, int len)\n{\n    int c = 0, i;\n\n    for (i = 0; i < len; i++) {\n        c |= p[i];\n    }\n    if (s->len + len > s->size) {\n        if (string_buffer_realloc(s, s->len + len, c))\n            return -1;\n    } else if (!s->is_wide_char && c >= 0x100) {\n        if (string_buffer_widen(s, s->size))\n            return -1;\n    }\n    if (s->is_wide_char) {\n        memcpy(&s->str->u.str16[s->len], p, len << 1);\n        s->len += len;\n    } else {\n        for (i = 0; i < len; i++) {\n            s->str->u.str8[s->len + i] = p[i];\n        }\n        s->len += len;\n    }\n    return 0;\n}\n\n/* appending an ASCII string */\nstatic int string_buffer_puts8(StringBuffer *s, const char *str)\n{\n    return string_buffer_write8(s, (const uint8_t *)str, strlen(str));\n}\n\nstatic int string_buffer_concat(StringBuffer *s, const JSString *p,\n                                uint32_t from, uint32_t to)\n{\n    if (to <= from)\n        return 0;\n    if (p->is_wide_char)\n        return string_buffer_write16(s, p->u.str16 + from, to - from);\n    else\n        return string_buffer_write8(s, p->u.str8 + from, to - from);\n}\n\nstatic int string_buffer_concat_value(StringBuffer *s, JSValueConst v)\n{\n    JSString *p;\n    JSValue v1;\n    int res;\n\n    if (s->error_status) {\n        /* prevent exception overload */\n        return -1;\n    }\n    if (unlikely(JS_VALUE_GET_TAG(v) != JS_TAG_STRING)) {\n        v1 = JS_ToString(s->ctx, v);\n        if (JS_IsException(v1))\n            return string_buffer_set_error(s);\n        p = JS_VALUE_GET_STRING(v1);\n        res = string_buffer_concat(s, p, 0, p->len);\n        JS_FreeValue(s->ctx, v1);\n        return res;\n    }\n    p = JS_VALUE_GET_STRING(v);\n    return string_buffer_concat(s, p, 0, p->len);\n}\n\nstatic int string_buffer_concat_value_free(StringBuffer *s, JSValue v)\n{\n    JSString *p;\n    int res;\n\n    if (s->error_status) {\n        /* prevent exception overload */\n        JS_FreeValue(s->ctx, v);\n        return -1;\n    }\n    if (unlikely(JS_VALUE_GET_TAG(v) != JS_TAG_STRING)) {\n        v = JS_ToStringFree(s->ctx, v);\n        if (JS_IsException(v))\n            return string_buffer_set_error(s);\n    }\n    p = JS_VALUE_GET_STRING(v);\n    res = string_buffer_concat(s, p, 0, p->len);\n    JS_FreeValue(s->ctx, v);\n    return res;\n}\n\nstatic int string_buffer_fill(StringBuffer *s, int c, int count)\n{\n    /* XXX: optimize */\n    if (s->len + count > s->size) {\n        if (string_buffer_realloc(s, s->len + count, c))\n            return -1;\n    }\n    while (count-- > 0) {\n        if (string_buffer_putc16(s, c))\n            return -1;\n    }\n    return 0;\n}\n\nstatic JSValue string_buffer_end(StringBuffer *s)\n{\n    JSString *str;\n    str = s->str;\n    if (s->error_status)\n        return JS_EXCEPTION;\n    if (s->len == 0) {\n        js_free(s->ctx, str);\n        s->str = NULL;\n        return JS_AtomToString(s->ctx, JS_ATOM_empty_string);\n    }\n    if (s->len < s->size) {\n        /* smaller size so js_realloc should not fail, but OK if it does */\n        /* XXX: should add some slack to avoid unnecessary calls */\n        /* XXX: might need to use malloc+free to ensure smaller size */\n        str = js_realloc_rt(s->ctx->rt, str, sizeof(JSString) +\n                            (s->len << s->is_wide_char) + 1 - s->is_wide_char);\n        if (str == NULL)\n            str = s->str;\n        s->str = str;\n    }\n    if (!s->is_wide_char)\n        str->u.str8[s->len] = 0;\n#ifdef DUMP_LEAKS\n    list_add_tail(&str->link, &s->ctx->rt->string_list);\n#endif\n    str->is_wide_char = s->is_wide_char;\n    str->len = s->len;\n    s->str = NULL;\n    return JS_MKPTR(JS_TAG_STRING, str);\n}\n\n/* create a string from a UTF-8 buffer */\nJSValue JS_NewStringLen(JSContext *ctx, const char *buf, size_t buf_len)\n{\n    const uint8_t *p, *p_end, *p_start, *p_next;\n    uint32_t c;\n    StringBuffer b_s, *b = &b_s;\n    size_t len1;\n    \n    p_start = (const uint8_t *)buf;\n    p_end = p_start + buf_len;\n    p = p_start;\n    while (p < p_end && *p < 128)\n        p++;\n    len1 = p - p_start;\n    if (len1 > JS_STRING_LEN_MAX)\n        return JS_ThrowInternalError(ctx, \"string too long\");\n    if (p == p_end) {\n        /* ASCII string */\n        return js_new_string8(ctx, (const uint8_t *)buf, buf_len);\n    } else {\n        if (string_buffer_init(ctx, b, buf_len))\n            goto fail;\n        string_buffer_write8(b, p_start, len1);\n        while (p < p_end) {\n            if (*p < 128) {\n                string_buffer_putc8(b, *p++);\n            } else {\n                /* parse utf-8 sequence, return 0xFFFFFFFF for error */\n                c = unicode_from_utf8(p, p_end - p, &p_next);\n                if (c < 0x10000) {\n                    p = p_next;\n                } else if (c <= 0x10FFFF) {\n                    p = p_next;\n                    /* surrogate pair */\n                    c -= 0x10000;\n                    string_buffer_putc16(b, (c >> 10) + 0xd800);\n                    c = (c & 0x3ff) + 0xdc00;\n                } else {\n                    /* invalid char */\n                    c = 0xfffd;\n                    /* skip the invalid chars */\n                    /* XXX: seems incorrect. Why not just use c = *p++; ? */\n                    while (p < p_end && (*p >= 0x80 && *p < 0xc0))\n                        p++;\n                    if (p < p_end) {\n                        p++;\n                        while (p < p_end && (*p >= 0x80 && *p < 0xc0))\n                            p++;\n                    }\n                }\n                string_buffer_putc16(b, c);\n            }\n        }\n    }\n    return string_buffer_end(b);\n\n fail:\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ConcatString3(JSContext *ctx, const char *str1,\n                                JSValue str2, const char *str3)\n{\n    StringBuffer b_s, *b = &b_s;\n    int len1, len3;\n    JSString *p;\n\n    if (unlikely(JS_VALUE_GET_TAG(str2) != JS_TAG_STRING)) {\n        str2 = JS_ToStringFree(ctx, str2);\n        if (JS_IsException(str2))\n            goto fail;\n    }\n    p = JS_VALUE_GET_STRING(str2);\n    len1 = strlen(str1);\n    len3 = strlen(str3);\n\n    if (string_buffer_init2(ctx, b, len1 + p->len + len3, p->is_wide_char))\n        goto fail;\n\n    string_buffer_write8(b, (const uint8_t *)str1, len1);\n    string_buffer_concat(b, p, 0, p->len);\n    string_buffer_write8(b, (const uint8_t *)str3, len3);\n\n    JS_FreeValue(ctx, str2);\n    return string_buffer_end(b);\n\n fail:\n    JS_FreeValue(ctx, str2);\n    return JS_EXCEPTION;\n}\n\nJSValue JS_NewString(JSContext *ctx, const char *str)\n{\n    return JS_NewStringLen(ctx, str, strlen(str));\n}\n\nJSValue JS_NewAtomString(JSContext *ctx, const char *str)\n{\n    JSAtom atom = JS_NewAtom(ctx, str);\n    if (atom == JS_ATOM_NULL)\n        return JS_EXCEPTION;\n    JSValue val = JS_AtomToString(ctx, atom);\n    JS_FreeAtom(ctx, atom);\n    return val;\n}\n\n/* return (NULL, 0) if exception. */\n/* return pointer into a JSString with a live ref_count */\n/* cesu8 determines if non-BMP1 codepoints are encoded as 1 or 2 utf-8 sequences */\nconst char *JS_ToCStringLen2(JSContext *ctx, size_t *plen, JSValueConst val1, BOOL cesu8)\n{\n    JSValue val;\n    JSString *str, *str_new;\n    int pos, len, c, c1;\n    uint8_t *q;\n\n    if (JS_VALUE_GET_TAG(val1) != JS_TAG_STRING) {\n        val = JS_ToString(ctx, val1);\n        if (JS_IsException(val))\n            goto fail;\n    } else {\n        val = JS_DupValue(ctx, val1);\n    }\n\n    str = JS_VALUE_GET_STRING(val);\n    len = str->len;\n    if (!str->is_wide_char) {\n        const uint8_t *src = str->u.str8;\n        int count;\n\n        /* count the number of non-ASCII characters */\n        /* Scanning the whole string is required for ASCII strings,\n           and computing the number of non-ASCII bytes is less expensive\n           than testing each byte, hence this method is faster for ASCII\n           strings, which is the most common case.\n         */\n        count = 0;\n        for (pos = 0; pos < len; pos++) {\n            count += src[pos] >> 7;\n        }\n        if (count == 0) {\n            if (plen)\n                *plen = len;\n            return (const char *)src;\n        }\n        str_new = js_alloc_string(ctx, len + count, 0);\n        if (!str_new)\n            goto fail;\n        q = str_new->u.str8;\n        for (pos = 0; pos < len; pos++) {\n            c = src[pos];\n            if (c < 0x80) {\n                *q++ = c;\n            } else {\n                *q++ = (c >> 6) | 0xc0;\n                *q++ = (c & 0x3f) | 0x80;\n            }\n        }\n    } else {\n        const uint16_t *src = str->u.str16;\n        /* Allocate 3 bytes per 16 bit code point. Surrogate pairs may\n           produce 4 bytes but use 2 code points.\n         */\n        str_new = js_alloc_string(ctx, len * 3, 0);\n        if (!str_new)\n            goto fail;\n        q = str_new->u.str8;\n        pos = 0;\n        while (pos < len) {\n            c = src[pos++];\n            if (c < 0x80) {\n                *q++ = c;\n            } else {\n                if (c >= 0xd800 && c < 0xdc00) {\n                    if (pos < len && !cesu8) {\n                        c1 = src[pos];\n                        if (c1 >= 0xdc00 && c1 < 0xe000) {\n                            pos++;\n                            /* surrogate pair */\n                            c = (((c & 0x3ff) << 10) | (c1 & 0x3ff)) + 0x10000;\n                        } else {\n                            /* Keep unmatched surrogate code points */\n                            /* c = 0xfffd; */ /* error */\n                        }\n                    } else {\n                        /* Keep unmatched surrogate code points */\n                        /* c = 0xfffd; */ /* error */\n                    }\n                }\n                q += unicode_to_utf8(q, c);\n            }\n        }\n    }\n\n    *q = '\\0';\n    str_new->len = q - str_new->u.str8;\n    JS_FreeValue(ctx, val);\n    if (plen)\n        *plen = str_new->len;\n    return (const char *)str_new->u.str8;\n fail:\n    if (plen)\n        *plen = 0;\n    return NULL;\n}\n\nvoid JS_FreeCString(JSContext *ctx, const char *ptr)\n{\n    JSString *p;\n    if (!ptr)\n        return;\n    /* purposely removing constness */\n    p = (JSString *)(void *)(ptr - offsetof(JSString, u));\n    JS_FreeValue(ctx, JS_MKPTR(JS_TAG_STRING, p));\n}\n\nstatic int memcmp16_8(const uint16_t *src1, const uint8_t *src2, int len)\n{\n    int c, i;\n    for(i = 0; i < len; i++) {\n        c = src1[i] - src2[i];\n        if (c != 0)\n            return c;\n    }\n    return 0;\n}\n\nstatic int memcmp16(const uint16_t *src1, const uint16_t *src2, int len)\n{\n    int c, i;\n    for(i = 0; i < len; i++) {\n        c = src1[i] - src2[i];\n        if (c != 0)\n            return c;\n    }\n    return 0;\n}\n\nstatic int js_string_memcmp(const JSString *p1, const JSString *p2, int len)\n{\n    int res;\n\n    if (likely(!p1->is_wide_char)) {\n        if (likely(!p2->is_wide_char))\n            res = memcmp(p1->u.str8, p2->u.str8, len);\n        else\n            res = -memcmp16_8(p2->u.str16, p1->u.str8, len);\n    } else {\n        if (!p2->is_wide_char)\n            res = memcmp16_8(p1->u.str16, p2->u.str8, len);\n        else\n            res = memcmp16(p1->u.str16, p2->u.str16, len);\n    }\n    return res;\n}\n\n/* return < 0, 0 or > 0 */\nint js_string_compare(JSContext *ctx,\n                             const JSString *p1, const JSString *p2)\n{\n    int res, len;\n    len = min_int(p1->len, p2->len);\n    res = js_string_memcmp(p1, p2, len);\n    if (res == 0) {\n        if (p1->len == p2->len)\n            res = 0;\n        else if (p1->len < p2->len)\n            res = -1;\n        else\n            res = 1;\n    }\n    return res;\n}\n\nstatic void copy_str16(uint16_t *dst, const JSString *p, int offset, int len)\n{\n    if (p->is_wide_char) {\n        memcpy(dst, p->u.str16 + offset, len * 2);\n    } else {\n        const uint8_t *src1 = p->u.str8 + offset;\n        int i;\n\n        for(i = 0; i < len; i++)\n            dst[i] = src1[i];\n    }\n}\n\nstatic JSValue JS_ConcatString1(JSContext *ctx,\n                                const JSString *p1, const JSString *p2)\n{\n    JSString *p;\n    uint32_t len;\n    int is_wide_char;\n\n    len = p1->len + p2->len;\n    if (len > JS_STRING_LEN_MAX)\n        return JS_ThrowInternalError(ctx, \"string too long\");\n    is_wide_char = p1->is_wide_char | p2->is_wide_char;\n    p = js_alloc_string(ctx, len, is_wide_char);\n    if (!p)\n        return JS_EXCEPTION;\n    if (!is_wide_char) {\n        memcpy(p->u.str8, p1->u.str8, p1->len);\n        memcpy(p->u.str8 + p1->len, p2->u.str8, p2->len);\n        p->u.str8[len] = '\\0';\n    } else {\n        copy_str16(p->u.str16, p1, 0, p1->len);\n        copy_str16(p->u.str16 + p1->len, p2, 0, p2->len);\n    }\n    return JS_MKPTR(JS_TAG_STRING, p);\n}\n\n/* op1 and op2 are converted to strings. For convience, op1 or op2 =\n   JS_EXCEPTION are accepted and return JS_EXCEPTION.  */\nstatic JSValue JS_ConcatString(JSContext *ctx, JSValue op1, JSValue op2)\n{\n    JSValue ret;\n    JSString *p1, *p2;\n\n    if (unlikely(JS_VALUE_GET_TAG(op1) != JS_TAG_STRING)) {\n        op1 = JS_ToStringFree(ctx, op1);\n        if (JS_IsException(op1)) {\n            JS_FreeValue(ctx, op2);\n            return JS_EXCEPTION;\n        }\n    }\n    if (unlikely(JS_VALUE_GET_TAG(op2) != JS_TAG_STRING)) {\n        op2 = JS_ToStringFree(ctx, op2);\n        if (JS_IsException(op2)) {\n            JS_FreeValue(ctx, op1);\n            return JS_EXCEPTION;\n        }\n    }\n    p1 = JS_VALUE_GET_STRING(op1);\n    p2 = JS_VALUE_GET_STRING(op2);\n\n    /* XXX: could also check if p1 is empty */\n    if (p2->len == 0) {\n        goto ret_op1;\n    }\n    if (p1->header.ref_count == 1 && p1->is_wide_char == p2->is_wide_char\n    &&  js_malloc_usable_size(ctx, p1) >= sizeof(*p1) + ((p1->len + p2->len) << p2->is_wide_char) + 1 - p1->is_wide_char) {\n        /* Concatenate in place in available space at the end of p1 */\n        if (p1->is_wide_char) {\n            memcpy(p1->u.str16 + p1->len, p2->u.str16, p2->len << 1);\n            p1->len += p2->len;\n        } else {\n            memcpy(p1->u.str8 + p1->len, p2->u.str8, p2->len);\n            p1->len += p2->len;\n            p1->u.str8[p1->len] = '\\0';\n        }\n    ret_op1:\n        JS_FreeValue(ctx, op2);\n        return op1;\n    }\n    ret = JS_ConcatString1(ctx, p1, p2);\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    return ret;\n}\n\n/* Shape support */\n\nstatic inline size_t get_shape_size(size_t hash_size, size_t prop_size)\n{\n    return hash_size * sizeof(uint32_t) + sizeof(JSShape) +\n        prop_size * sizeof(JSShapeProperty);\n}\n\nstatic inline JSShape *get_shape_from_alloc(void *sh_alloc, size_t hash_size)\n{\n    return (JSShape *)(void *)((uint32_t *)sh_alloc + hash_size);\n}\n\nstatic inline uint32_t *prop_hash_end(JSShape *sh)\n{\n    return (uint32_t *)sh;\n}\n\nstatic inline void *get_alloc_from_shape(JSShape *sh)\n{\n    return prop_hash_end(sh) - ((intptr_t)sh->prop_hash_mask + 1);\n}\n\nstatic inline JSShapeProperty *get_shape_prop(JSShape *sh)\n{\n    return sh->prop;\n}\n\nstatic int init_shape_hash(JSRuntime *rt)\n{\n    rt->shape_hash_bits = 4;   /* 16 shapes */\n    rt->shape_hash_size = 1 << rt->shape_hash_bits;\n    rt->shape_hash_count = 0;\n    rt->shape_hash = js_mallocz_rt(rt, sizeof(rt->shape_hash[0]) *\n                                   rt->shape_hash_size);\n    if (!rt->shape_hash)\n        return -1;\n    return 0;\n}\n\n/* same magic hash multiplier as the Linux kernel */\nstatic uint32_t shape_hash(uint32_t h, uint32_t val)\n{\n    return (h + val) * 0x9e370001;\n}\n\n/* truncate the shape hash to 'hash_bits' bits */\nstatic uint32_t get_shape_hash(uint32_t h, int hash_bits)\n{\n    return h >> (32 - hash_bits);\n}\n\nstatic uint32_t shape_initial_hash(JSObject *proto)\n{\n    uint32_t h;\n    h = shape_hash(1, (uintptr_t)proto);\n    if (sizeof(proto) > 4)\n        h = shape_hash(h, (uint64_t)(uintptr_t)proto >> 32);\n    return h;\n}\n\nstatic int resize_shape_hash(JSRuntime *rt, int new_shape_hash_bits)\n{\n    int new_shape_hash_size, i;\n    uint32_t h;\n    JSShape **new_shape_hash, *sh, *sh_next;\n\n    new_shape_hash_size = 1 << new_shape_hash_bits;\n    new_shape_hash = js_mallocz_rt(rt, sizeof(rt->shape_hash[0]) *\n                                   new_shape_hash_size);\n    if (!new_shape_hash)\n        return -1;\n    for(i = 0; i < rt->shape_hash_size; i++) {\n        for(sh = rt->shape_hash[i]; sh != NULL; sh = sh_next) {\n            sh_next = sh->shape_hash_next;\n            h = get_shape_hash(sh->hash, new_shape_hash_bits);\n            sh->shape_hash_next = new_shape_hash[h];\n            new_shape_hash[h] = sh;\n        }\n    }\n    js_free_rt(rt, rt->shape_hash);\n    rt->shape_hash_bits = new_shape_hash_bits;\n    rt->shape_hash_size = new_shape_hash_size;\n    rt->shape_hash = new_shape_hash;\n    return 0;\n}\n\nstatic void js_shape_hash_link(JSRuntime *rt, JSShape *sh)\n{\n    uint32_t h;\n    h = get_shape_hash(sh->hash, rt->shape_hash_bits);\n    sh->shape_hash_next = rt->shape_hash[h];\n    rt->shape_hash[h] = sh;\n    rt->shape_hash_count++;\n}\n\nstatic void js_shape_hash_unlink(JSRuntime *rt, JSShape *sh)\n{\n    uint32_t h;\n    JSShape **psh;\n\n    h = get_shape_hash(sh->hash, rt->shape_hash_bits);\n    psh = &rt->shape_hash[h];\n    while (*psh != sh)\n        psh = &(*psh)->shape_hash_next;\n    *psh = sh->shape_hash_next;\n    rt->shape_hash_count--;\n}\n\n/* create a new empty shape with prototype 'proto' */\nstatic no_inline JSShape *js_new_shape2(JSContext *ctx, JSObject *proto,\n                                        int hash_size, int prop_size)\n{\n    JSRuntime *rt = ctx->rt;\n    void *sh_alloc;\n    JSShape *sh;\n\n    /* resize the shape hash table if necessary */\n    if (2 * (rt->shape_hash_count + 1) > rt->shape_hash_size) {\n        resize_shape_hash(rt, rt->shape_hash_bits + 1);\n    }\n\n    sh_alloc = js_malloc(ctx, get_shape_size(hash_size, prop_size));\n    if (!sh_alloc)\n        return NULL;\n    sh = get_shape_from_alloc(sh_alloc, hash_size);\n    sh->header.ref_count = 1;\n    add_gc_object(rt, &sh->header, JS_GC_OBJ_TYPE_SHAPE);\n    if (proto)\n        JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, proto));\n    sh->proto = proto;\n    memset(prop_hash_end(sh) - hash_size, 0, sizeof(prop_hash_end(sh)[0]) *\n           hash_size);\n    sh->prop_hash_mask = hash_size - 1;\n    sh->prop_size = prop_size;\n    sh->prop_count = 0;\n    sh->deleted_prop_count = 0;\n    \n    /* insert in the hash table */\n    sh->hash = shape_initial_hash(proto);\n    sh->is_hashed = TRUE;\n    sh->has_small_array_index = FALSE;\n    js_shape_hash_link(ctx->rt, sh);\n    return sh;\n}\n\nstatic JSShape *js_new_shape(JSContext *ctx, JSObject *proto)\n{\n    return js_new_shape2(ctx, proto, JS_PROP_INITIAL_HASH_SIZE,\n                         JS_PROP_INITIAL_SIZE);\n}\n\n/* The shape is cloned. The new shape is not inserted in the shape\n   hash table */\nstatic JSShape *js_clone_shape(JSContext *ctx, JSShape *sh1)\n{\n    JSShape *sh;\n    void *sh_alloc, *sh_alloc1;\n    size_t size;\n    JSShapeProperty *pr;\n    uint32_t i, hash_size;\n\n    hash_size = sh1->prop_hash_mask + 1;\n    size = get_shape_size(hash_size, sh1->prop_size);\n    sh_alloc = js_malloc(ctx, size);\n    if (!sh_alloc)\n        return NULL;\n    sh_alloc1 = get_alloc_from_shape(sh1);\n    memcpy(sh_alloc, sh_alloc1, size);\n    sh = get_shape_from_alloc(sh_alloc, hash_size);\n    sh->header.ref_count = 1;\n    add_gc_object(ctx->rt, &sh->header, JS_GC_OBJ_TYPE_SHAPE);\n    sh->is_hashed = FALSE;\n    if (sh->proto) {\n        JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, sh->proto));\n    }\n    for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count; i++, pr++) {\n        JS_DupAtom(ctx, pr->atom);\n    }\n    return sh;\n}\n\nstatic JSShape *js_dup_shape(JSShape *sh)\n{\n    sh->header.ref_count++;\n    return sh;\n}\n\nstatic void js_free_shape0(JSRuntime *rt, JSShape *sh)\n{\n    uint32_t i;\n    JSShapeProperty *pr;\n\n    assert(sh->header.ref_count == 0);\n    if (sh->is_hashed)\n        js_shape_hash_unlink(rt, sh);\n    if (sh->proto != NULL) {\n        JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, sh->proto));\n    }\n    pr = get_shape_prop(sh);\n    for(i = 0; i < sh->prop_count; i++) {\n        JS_FreeAtomRT(rt, pr->atom);\n        pr++;\n    }\n    remove_gc_object(&sh->header);\n    js_free_rt(rt, get_alloc_from_shape(sh));\n}\n\nstatic void js_free_shape(JSRuntime *rt, JSShape *sh)\n{\n    if (unlikely(--sh->header.ref_count <= 0)) {\n        js_free_shape0(rt, sh);\n    }\n}\n\nstatic void js_free_shape_null(JSRuntime *rt, JSShape *sh)\n{\n    if (sh)\n        js_free_shape(rt, sh);\n}\n\n/* make space to hold at least 'count' properties */\nstatic no_inline int resize_properties(JSContext *ctx, JSShape **psh,\n                                       JSObject *p, uint32_t count)\n{\n    JSShape *sh;\n    uint32_t new_size, new_hash_size, new_hash_mask, i;\n    JSShapeProperty *pr;\n    void *sh_alloc;\n    intptr_t h;\n\n    sh = *psh;\n    new_size = max_int(count, sh->prop_size * 3 / 2);\n    /* Reallocate prop array first to avoid crash or size inconsistency\n       in case of memory allocation failure */\n    if (p) {\n        JSProperty *new_prop;\n        new_prop = js_realloc(ctx, p->prop, sizeof(new_prop[0]) * new_size);\n        if (unlikely(!new_prop))\n            return -1;\n        p->prop = new_prop;\n    }\n    new_hash_size = sh->prop_hash_mask + 1;\n    while (new_hash_size < new_size)\n        new_hash_size = 2 * new_hash_size;\n    if (new_hash_size != (sh->prop_hash_mask + 1)) {\n        JSShape *old_sh;\n        /* resize the hash table and the properties */\n        old_sh = sh;\n        sh_alloc = js_malloc(ctx, get_shape_size(new_hash_size, new_size));\n        if (!sh_alloc)\n            return -1;\n        sh = get_shape_from_alloc(sh_alloc, new_hash_size);\n        list_del(&old_sh->header.link);\n        /* copy all the fields and the properties */\n        memcpy(sh, old_sh,\n               sizeof(JSShape) + sizeof(sh->prop[0]) * old_sh->prop_count);\n        list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list);\n        new_hash_mask = new_hash_size - 1;\n        sh->prop_hash_mask = new_hash_mask;\n        memset(prop_hash_end(sh) - new_hash_size, 0,\n               sizeof(prop_hash_end(sh)[0]) * new_hash_size);\n        for(i = 0, pr = sh->prop; i < sh->prop_count; i++, pr++) {\n            if (pr->atom != JS_ATOM_NULL) {\n                h = ((uintptr_t)pr->atom & new_hash_mask);\n                pr->hash_next = prop_hash_end(sh)[-h - 1];\n                prop_hash_end(sh)[-h - 1] = i + 1;\n            }\n        }\n        js_free(ctx, get_alloc_from_shape(old_sh));\n    } else {\n        /* only resize the properties */\n        list_del(&sh->header.link);\n        sh_alloc = js_realloc(ctx, get_alloc_from_shape(sh),\n                              get_shape_size(new_hash_size, new_size));\n        if (unlikely(!sh_alloc)) {\n            /* insert again in the GC list */\n            list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list);\n            return -1;\n        }\n        sh = get_shape_from_alloc(sh_alloc, new_hash_size);\n        list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list);\n    }\n    *psh = sh;\n    sh->prop_size = new_size;\n    return 0;\n}\n\n/* remove the deleted properties. */\nstatic int compact_properties(JSContext *ctx, JSObject *p)\n{\n    JSShape *sh, *old_sh;\n    void *sh_alloc;\n    intptr_t h;\n    uint32_t new_hash_size, i, j, new_hash_mask, new_size;\n    JSShapeProperty *old_pr, *pr;\n    JSProperty *prop, *new_prop;\n    \n    sh = p->shape;\n    assert(!sh->is_hashed);\n\n    new_size = max_int(JS_PROP_INITIAL_SIZE,\n                       sh->prop_count - sh->deleted_prop_count);\n    assert(new_size <= sh->prop_size);\n\n    new_hash_size = sh->prop_hash_mask + 1;\n    while ((new_hash_size / 2) >= new_size)\n        new_hash_size = new_hash_size / 2;\n    new_hash_mask = new_hash_size - 1;\n\n    /* resize the hash table and the properties */\n    old_sh = sh;\n    sh_alloc = js_malloc(ctx, get_shape_size(new_hash_size, new_size));\n    if (!sh_alloc)\n        return -1;\n    sh = get_shape_from_alloc(sh_alloc, new_hash_size);\n    list_del(&old_sh->header.link);\n    memcpy(sh, old_sh, sizeof(JSShape));\n    list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list);\n    \n    memset(prop_hash_end(sh) - new_hash_size, 0,\n           sizeof(prop_hash_end(sh)[0]) * new_hash_size);\n\n    j = 0;\n    old_pr = old_sh->prop;\n    pr = sh->prop;\n    prop = p->prop;\n    for(i = 0; i < sh->prop_count; i++) {\n        if (old_pr->atom != JS_ATOM_NULL) {\n            pr->atom = old_pr->atom;\n            pr->flags = old_pr->flags;\n            h = ((uintptr_t)old_pr->atom & new_hash_mask);\n            pr->hash_next = prop_hash_end(sh)[-h - 1];\n            prop_hash_end(sh)[-h - 1] = j + 1;\n            prop[j] = prop[i];\n            j++;\n            pr++;\n        }\n        old_pr++;\n    }\n    assert(j == (sh->prop_count - sh->deleted_prop_count));\n    sh->prop_hash_mask = new_hash_mask;\n    sh->prop_size = new_size;\n    sh->deleted_prop_count = 0;\n    sh->prop_count = j;\n\n    p->shape = sh;\n    js_free(ctx, get_alloc_from_shape(old_sh));\n    \n    /* reduce the size of the object properties */\n    new_prop = js_realloc(ctx, p->prop, sizeof(new_prop[0]) * new_size);\n    if (new_prop)\n        p->prop = new_prop;\n    return 0;\n}\n\nstatic int add_shape_property(JSContext *ctx, JSShape **psh,\n                              JSObject *p, JSAtom atom, int prop_flags)\n{\n    JSRuntime *rt = ctx->rt;\n    JSShape *sh = *psh;\n    JSShapeProperty *pr, *prop;\n    uint32_t hash_mask, new_shape_hash = 0;\n    intptr_t h;\n\n    /* update the shape hash */\n    if (sh->is_hashed) {\n        js_shape_hash_unlink(rt, sh);\n        new_shape_hash = shape_hash(shape_hash(sh->hash, atom), prop_flags);\n    }\n\n    if (unlikely(sh->prop_count >= sh->prop_size)) {\n        if (resize_properties(ctx, psh, p, sh->prop_count + 1)) {\n            /* in case of error, reinsert in the hash table.\n               sh is still valid if resize_properties() failed */\n            if (sh->is_hashed)\n                js_shape_hash_link(rt, sh);\n            return -1;\n        }\n        sh = *psh;\n    }\n    if (sh->is_hashed) {\n        sh->hash = new_shape_hash;\n        js_shape_hash_link(rt, sh);\n    }\n    /* Initialize the new shape property.\n       The object property at p->prop[sh->prop_count] is uninitialized */\n    prop = get_shape_prop(sh);\n    pr = &prop[sh->prop_count++];\n    pr->atom = JS_DupAtom(ctx, atom);\n    pr->flags = prop_flags;\n    sh->has_small_array_index |= __JS_AtomIsTaggedInt(atom);\n    /* add in hash table */\n    hash_mask = sh->prop_hash_mask;\n    h = atom & hash_mask;\n    pr->hash_next = prop_hash_end(sh)[-h - 1];\n    prop_hash_end(sh)[-h - 1] = sh->prop_count;\n    return 0;\n}\n\n/* find a hashed empty shape matching the prototype. Return NULL if\n   not found */\nstatic JSShape *find_hashed_shape_proto(JSRuntime *rt, JSObject *proto)\n{\n    JSShape *sh1;\n    uint32_t h, h1;\n\n    h = shape_initial_hash(proto);\n    h1 = get_shape_hash(h, rt->shape_hash_bits);\n    for(sh1 = rt->shape_hash[h1]; sh1 != NULL; sh1 = sh1->shape_hash_next) {\n        if (sh1->hash == h &&\n            sh1->proto == proto &&\n            sh1->prop_count == 0) {\n            return sh1;\n        }\n    }\n    return NULL;\n}\n\n/* find a hashed shape matching sh + (prop, prop_flags). Return NULL if\n   not found */\nstatic JSShape *find_hashed_shape_prop(JSRuntime *rt, JSShape *sh,\n                                       JSAtom atom, int prop_flags)\n{\n    JSShape *sh1;\n    uint32_t h, h1, i, n;\n\n    h = sh->hash;\n    h = shape_hash(h, atom);\n    h = shape_hash(h, prop_flags);\n    h1 = get_shape_hash(h, rt->shape_hash_bits);\n    for(sh1 = rt->shape_hash[h1]; sh1 != NULL; sh1 = sh1->shape_hash_next) {\n        /* we test the hash first so that the rest is done only if the\n           shapes really match */\n        if (sh1->hash == h &&\n            sh1->proto == sh->proto &&\n            sh1->prop_count == ((n = sh->prop_count) + 1)) {\n            for(i = 0; i < n; i++) {\n                if (unlikely(sh1->prop[i].atom != sh->prop[i].atom) ||\n                    unlikely(sh1->prop[i].flags != sh->prop[i].flags))\n                    goto next;\n            }\n            if (unlikely(sh1->prop[n].atom != atom) ||\n                unlikely(sh1->prop[n].flags != prop_flags))\n                goto next;\n            return sh1;\n        }\n    next: ;\n    }\n    return NULL;\n}\n\nstatic __maybe_unused void JS_DumpShape(JSRuntime *rt, int i, JSShape *sh)\n{\n    char atom_buf[ATOM_GET_STR_BUF_SIZE];\n    int j;\n\n    /* XXX: should output readable class prototype */\n    printf(\"%5d %3d%c %14p %5d %5d\", i,\n           sh->header.ref_count, \" *\"[sh->is_hashed],\n           (void *)sh->proto, sh->prop_size, sh->prop_count);\n    for(j = 0; j < sh->prop_count; j++) {\n        printf(\" %s\", JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf),\n                                      sh->prop[j].atom));\n    }\n    printf(\"\\n\");\n}\n\nstatic __maybe_unused void JS_DumpShapes(JSRuntime *rt)\n{\n    int i;\n    JSShape *sh;\n    struct list_head *el;\n    JSObject *p;\n    JSGCObjectHeader *gp;\n    \n    printf(\"JSShapes: {\\n\");\n    printf(\"%5s %4s %14s %5s %5s %s\\n\", \"SLOT\", \"REFS\", \"PROTO\", \"SIZE\", \"COUNT\", \"PROPS\");\n    for(i = 0; i < rt->shape_hash_size; i++) {\n        for(sh = rt->shape_hash[i]; sh != NULL; sh = sh->shape_hash_next) {\n            JS_DumpShape(rt, i, sh);\n            assert(sh->is_hashed);\n        }\n    }\n    /* dump non-hashed shapes */\n    list_for_each(el, &rt->gc_obj_list) {\n        gp = list_entry(el, JSGCObjectHeader, link);\n        if (gp->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT) {\n            p = (JSObject *)gp;\n            if (!p->shape->is_hashed) {\n                JS_DumpShape(rt, -1, p->shape);\n            }\n        }\n    }\n    printf(\"}\\n\");\n}\n\nstatic JSValue JS_NewObjectFromShape(JSContext *ctx, JSShape *sh, JSClassID class_id)\n{\n    JSObject *p;\n\n    js_trigger_gc(ctx->rt, sizeof(JSObject));\n    p = js_malloc(ctx, sizeof(JSObject));\n    if (unlikely(!p))\n        goto fail;\n    p->class_id = class_id;\n    p->extensible = TRUE;\n    p->free_mark = 0;\n    p->is_exotic = 0;\n    p->fast_array = 0;\n    p->is_constructor = 0;\n    p->is_uncatchable_error = 0;\n    p->tmp_mark = 0;\n    p->is_HTMLDDA = 0;\n    p->first_weak_ref = NULL;\n    p->u.opaque = NULL;\n    p->shape = sh;\n    p->prop = js_malloc(ctx, sizeof(JSProperty) * sh->prop_size);\n    if (unlikely(!p->prop)) {\n        js_free(ctx, p);\n    fail:\n        js_free_shape(ctx->rt, sh);\n        return JS_EXCEPTION;\n    }\n\n    switch(class_id) {\n    case JS_CLASS_OBJECT:\n        break;\n    case JS_CLASS_ARRAY:\n        {\n            JSProperty *pr;\n            p->is_exotic = 1;\n            p->fast_array = 1;\n            p->u.array.u.values = NULL;\n            p->u.array.count = 0;\n            p->u.array.u1.size = 0;\n            /* the length property is always the first one */\n            if (likely(sh == ctx->array_shape)) {\n                pr = &p->prop[0];\n            } else {\n                /* only used for the first array */\n                /* cannot fail */\n                pr = add_property(ctx, p, JS_ATOM_length,\n                                  JS_PROP_WRITABLE | JS_PROP_LENGTH);\n            }\n            pr->u.value = JS_NewInt32(ctx, 0);\n        }\n        break;\n    case JS_CLASS_C_FUNCTION:\n        p->prop[0].u.value = JS_UNDEFINED;\n        break;\n    case JS_CLASS_ARGUMENTS:\n    case JS_CLASS_UINT8C_ARRAY:\n    case JS_CLASS_INT8_ARRAY:\n    case JS_CLASS_UINT8_ARRAY:\n    case JS_CLASS_INT16_ARRAY:\n    case JS_CLASS_UINT16_ARRAY:\n    case JS_CLASS_INT32_ARRAY:\n    case JS_CLASS_UINT32_ARRAY:\n#ifdef CONFIG_BIGNUM\n    case JS_CLASS_BIG_INT64_ARRAY:\n    case JS_CLASS_BIG_UINT64_ARRAY:\n#endif\n    case JS_CLASS_FLOAT32_ARRAY:\n    case JS_CLASS_FLOAT64_ARRAY:\n        p->is_exotic = 1;\n        p->fast_array = 1;\n        p->u.array.u.ptr = NULL;\n        p->u.array.count = 0;\n        break;\n    case JS_CLASS_DATAVIEW:\n        p->u.array.u.ptr = NULL;\n        p->u.array.count = 0;\n        break;\n    case JS_CLASS_NUMBER:\n    case JS_CLASS_STRING:\n    case JS_CLASS_BOOLEAN:\n    case JS_CLASS_SYMBOL:\n    case JS_CLASS_DATE:\n#ifdef CONFIG_BIGNUM\n    case JS_CLASS_BIG_INT:\n    case JS_CLASS_BIG_FLOAT:\n    case JS_CLASS_BIG_DECIMAL:\n#endif\n        p->u.object_data = JS_UNDEFINED;\n        goto set_exotic;\n    case JS_CLASS_REGEXP:\n        p->u.regexp.pattern = NULL;\n        p->u.regexp.bytecode = NULL;\n        goto set_exotic;\n    default:\n    set_exotic:\n        if (ctx->rt->class_array[class_id].exotic) {\n            p->is_exotic = 1;\n        }\n        break;\n    }\n    p->header.ref_count = 1;\n    add_gc_object(ctx->rt, &p->header, JS_GC_OBJ_TYPE_JS_OBJECT);\n    return JS_MKPTR(JS_TAG_OBJECT, p);\n}\n\nstatic JSObject *get_proto_obj(JSValueConst proto_val)\n{\n    if (JS_VALUE_GET_TAG(proto_val) != JS_TAG_OBJECT)\n        return NULL;\n    else\n        return JS_VALUE_GET_OBJ(proto_val);\n}\n\n/* WARNING: proto must be an object or JS_NULL */\nJSValue JS_NewObjectProtoClass(JSContext *ctx, JSValueConst proto_val,\n                               JSClassID class_id)\n{\n    JSShape *sh;\n    JSObject *proto;\n\n    proto = get_proto_obj(proto_val);\n    sh = find_hashed_shape_proto(ctx->rt, proto);\n    if (likely(sh)) {\n        sh = js_dup_shape(sh);\n    } else {\n        sh = js_new_shape(ctx, proto);\n        if (!sh)\n            return JS_EXCEPTION;\n    }\n    return JS_NewObjectFromShape(ctx, sh, class_id);\n}\n\n#if 0\nstatic JSValue JS_GetObjectData(JSContext *ctx, JSValueConst obj)\n{\n    JSObject *p;\n\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        p = JS_VALUE_GET_OBJ(obj);\n        switch(p->class_id) {\n        case JS_CLASS_NUMBER:\n        case JS_CLASS_STRING:\n        case JS_CLASS_BOOLEAN:\n        case JS_CLASS_SYMBOL:\n        case JS_CLASS_DATE:\n#ifdef CONFIG_BIGNUM\n        case JS_CLASS_BIG_INT:\n        case JS_CLASS_BIG_FLOAT:\n        case JS_CLASS_BIG_DECIMAL:\n#endif\n            return JS_DupValue(ctx, p->u.object_data);\n        }\n    }\n    return JS_UNDEFINED;\n}\n#endif\n\nstatic int JS_SetObjectData(JSContext *ctx, JSValueConst obj, JSValue val)\n{\n    JSObject *p;\n\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        p = JS_VALUE_GET_OBJ(obj);\n        switch(p->class_id) {\n        case JS_CLASS_NUMBER:\n        case JS_CLASS_STRING:\n        case JS_CLASS_BOOLEAN:\n        case JS_CLASS_SYMBOL:\n        case JS_CLASS_DATE:\n#ifdef CONFIG_BIGNUM\n        case JS_CLASS_BIG_INT:\n        case JS_CLASS_BIG_FLOAT:\n        case JS_CLASS_BIG_DECIMAL:\n#endif\n            JS_FreeValue(ctx, p->u.object_data);\n            p->u.object_data = val;\n            return 0;\n        }\n    }\n    JS_FreeValue(ctx, val);\n    if (!JS_IsException(obj))\n        JS_ThrowTypeError(ctx, \"invalid object type\");\n    return -1;\n}\n\nJSValue JS_NewObjectClass(JSContext *ctx, int class_id)\n{\n    return JS_NewObjectProtoClass(ctx, ctx->class_proto[class_id], class_id);\n}\n\nJSValue JS_NewObjectProto(JSContext *ctx, JSValueConst proto)\n{\n    return JS_NewObjectProtoClass(ctx, proto, JS_CLASS_OBJECT);\n}\n\nJSValue JS_NewArray(JSContext *ctx)\n{\n    return JS_NewObjectFromShape(ctx, js_dup_shape(ctx->array_shape),\n                                 JS_CLASS_ARRAY);\n}\n\nJSValue JS_NewObject(JSContext *ctx)\n{\n    /* inline JS_NewObjectClass(ctx, JS_CLASS_OBJECT); */\n    return JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT], JS_CLASS_OBJECT);\n}\n\nstatic void js_function_set_properties(JSContext *ctx, JSValueConst func_obj,\n                                       JSAtom name, int len)\n{\n    /* ES6 feature non compatible with ES5.1: length is configurable */\n    JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_length, JS_NewInt32(ctx, len),\n                           JS_PROP_CONFIGURABLE);\n    JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_name,\n                           JS_AtomToString(ctx, name), JS_PROP_CONFIGURABLE);\n}\n\nstatic BOOL js_class_has_bytecode(JSClassID class_id)\n{\n    return (class_id == JS_CLASS_BYTECODE_FUNCTION ||\n            class_id == JS_CLASS_GENERATOR_FUNCTION ||\n            class_id == JS_CLASS_ASYNC_FUNCTION ||\n            class_id == JS_CLASS_ASYNC_GENERATOR_FUNCTION);\n}\n\n/* return NULL without exception if not a function or no bytecode */\nstatic JSFunctionBytecode *JS_GetFunctionBytecode(JSValueConst val)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return NULL;\n    p = JS_VALUE_GET_OBJ(val);\n    if (!js_class_has_bytecode(p->class_id))\n        return NULL;\n    return p->u.func.function_bytecode;\n}\n\nstatic void js_method_set_home_object(JSContext *ctx, JSValueConst func_obj,\n                                      JSValueConst home_obj)\n{\n    JSObject *p, *p1;\n    JSFunctionBytecode *b;\n\n    if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT)\n        return;\n    p = JS_VALUE_GET_OBJ(func_obj);\n    if (!js_class_has_bytecode(p->class_id))\n        return;\n    b = p->u.func.function_bytecode;\n    if (b->need_home_object) {\n        p1 = p->u.func.home_object;\n        if (p1) {\n            JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p1));\n        }\n        if (JS_VALUE_GET_TAG(home_obj) == JS_TAG_OBJECT)\n            p1 = JS_VALUE_GET_OBJ(JS_DupValue(ctx, home_obj));\n        else\n            p1 = NULL;\n        p->u.func.home_object = p1;\n    }\n}\n\nstatic JSValue js_get_function_name(JSContext *ctx, JSAtom name)\n{\n    JSValue name_str;\n\n    name_str = JS_AtomToString(ctx, name);\n    if (JS_AtomSymbolHasDescription(ctx, name)) {\n        name_str = JS_ConcatString3(ctx, \"[\", name_str, \"]\");\n    }\n    return name_str;\n}\n\n/* Modify the name of a method according to the atom and\n   'flags'. 'flags' is a bitmask of JS_PROP_HAS_GET and\n   JS_PROP_HAS_SET. Also set the home object of the method.\n   Return < 0 if exception. */\nstatic int js_method_set_properties(JSContext *ctx, JSValueConst func_obj,\n                                    JSAtom name, int flags, JSValueConst home_obj)\n{\n    JSValue name_str;\n\n    name_str = js_get_function_name(ctx, name);\n    if (flags & JS_PROP_HAS_GET) {\n        name_str = JS_ConcatString3(ctx, \"get \", name_str, \"\");\n    } else if (flags & JS_PROP_HAS_SET) {\n        name_str = JS_ConcatString3(ctx, \"set \", name_str, \"\");\n    }\n    if (JS_IsException(name_str))\n        return -1;\n    if (JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_name, name_str,\n                               JS_PROP_CONFIGURABLE) < 0)\n        return -1;\n    js_method_set_home_object(ctx, func_obj, home_obj);\n    return 0;\n}\n\n/* Note: at least 'length' arguments will be readable in 'argv' */\nstatic JSValue JS_NewCFunction3(JSContext *ctx, JSCFunction *func,\n                                const char *name,\n                                int length, JSCFunctionEnum cproto, int magic,\n                                JSValueConst proto_val)\n{\n    JSValue func_obj;\n    JSObject *p;\n    JSAtom name_atom;\n    \n    func_obj = JS_NewObjectProtoClass(ctx, proto_val, JS_CLASS_C_FUNCTION);\n    if (JS_IsException(func_obj))\n        return func_obj;\n    p = JS_VALUE_GET_OBJ(func_obj);\n    p->u.cfunc.realm = JS_DupContext(ctx);\n    p->u.cfunc.c_function.generic = func;\n    p->u.cfunc.length = length;\n    p->u.cfunc.cproto = cproto;\n    p->u.cfunc.magic = magic;\n    p->is_constructor = (cproto == JS_CFUNC_constructor ||\n                         cproto == JS_CFUNC_constructor_magic ||\n                         cproto == JS_CFUNC_constructor_or_func ||\n                         cproto == JS_CFUNC_constructor_or_func_magic);\n    if (!name)\n        name = \"\";\n    name_atom = JS_NewAtom(ctx, name);\n    js_function_set_properties(ctx, func_obj, name_atom, length);\n    JS_FreeAtom(ctx, name_atom);\n    return func_obj;\n}\n\n/* Note: at least 'length' arguments will be readable in 'argv' */\nJSValue JS_NewCFunction2(JSContext *ctx, JSCFunction *func,\n                         const char *name,\n                         int length, JSCFunctionEnum cproto, int magic)\n{\n    return JS_NewCFunction3(ctx, func, name, length, cproto, magic,\n                            ctx->function_proto);\n}\n\ntypedef struct JSCFunctionDataRecord {\n    JSCFunctionData *func;\n    uint8_t length;\n    uint8_t data_len;\n    uint16_t magic;\n    JSValue data[0];\n} JSCFunctionDataRecord;\n\nstatic void js_c_function_data_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSCFunctionDataRecord *s = JS_GetOpaque(val, JS_CLASS_C_FUNCTION_DATA);\n    int i;\n\n    if (s) {\n        for(i = 0; i < s->data_len; i++) {\n            JS_FreeValueRT(rt, s->data[i]);\n        }\n        js_free_rt(rt, s);\n    }\n}\n\nstatic void js_c_function_data_mark(JSRuntime *rt, JSValueConst val,\n                                    JS_MarkFunc *mark_func)\n{\n    JSCFunctionDataRecord *s = JS_GetOpaque(val, JS_CLASS_C_FUNCTION_DATA);\n    int i;\n\n    if (s) {\n        for(i = 0; i < s->data_len; i++) {\n            JS_MarkValue(rt, s->data[i], mark_func);\n        }\n    }\n}\n\nstatic JSValue js_c_function_data_call(JSContext *ctx, JSValueConst func_obj,\n                                       JSValueConst this_val,\n                                       int argc, JSValueConst *argv, int flags)\n{\n    JSCFunctionDataRecord *s = JS_GetOpaque(func_obj, JS_CLASS_C_FUNCTION_DATA);\n    JSValueConst *arg_buf;\n    int i;\n\n    /* XXX: could add the function on the stack for debug */\n    if (unlikely(argc < s->length)) {\n        arg_buf = alloca(sizeof(arg_buf[0]) * s->length);\n        for(i = 0; i < argc; i++)\n            arg_buf[i] = argv[i];\n        for(i = argc; i < s->length; i++)\n            arg_buf[i] = JS_UNDEFINED;\n    } else {\n        arg_buf = argv;\n    }\n\n    return s->func(ctx, this_val, argc, arg_buf, s->magic, s->data);\n}\n\nJSValue JS_NewCFunctionData(JSContext *ctx, JSCFunctionData *func,\n                            int length, int magic, int data_len,\n                            JSValueConst *data)\n{\n    JSCFunctionDataRecord *s;\n    JSValue func_obj;\n    int i;\n\n    func_obj = JS_NewObjectProtoClass(ctx, ctx->function_proto,\n                                      JS_CLASS_C_FUNCTION_DATA);\n    if (JS_IsException(func_obj))\n        return func_obj;\n    s = js_malloc(ctx, sizeof(*s) + data_len * sizeof(JSValue));\n    if (!s) {\n        JS_FreeValue(ctx, func_obj);\n        return JS_EXCEPTION;\n    }\n    s->func = func;\n    s->length = length;\n    s->data_len = data_len;\n    s->magic = magic;\n    for(i = 0; i < data_len; i++)\n        s->data[i] = JS_DupValue(ctx, data[i]);\n    JS_SetOpaque(func_obj, s);\n    js_function_set_properties(ctx, func_obj,\n                               JS_ATOM_empty_string, length);\n    return func_obj;\n}\n\nstatic JSContext *js_autoinit_get_realm(JSProperty *pr)\n{\n    return (JSContext *)(pr->u.init.realm_and_id & ~3);\n}\n\nstatic JSAutoInitIDEnum js_autoinit_get_id(JSProperty *pr)\n{\n    return pr->u.init.realm_and_id & 3;\n}\n\nstatic void js_autoinit_free(JSRuntime *rt, JSProperty *pr)\n{\n    JS_FreeContext(js_autoinit_get_realm(pr));\n}\n\nstatic void js_autoinit_mark(JSRuntime *rt, JSProperty *pr,\n                             JS_MarkFunc *mark_func)\n{\n    mark_func(rt, &js_autoinit_get_realm(pr)->header);\n}\n\nstatic void free_property(JSRuntime *rt, JSProperty *pr, int prop_flags)\n{\n    if (unlikely(prop_flags & JS_PROP_TMASK)) {\n        if ((prop_flags & JS_PROP_TMASK) == JS_PROP_GETSET) {\n            if (pr->u.getset.getter)\n                JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter));\n            if (pr->u.getset.setter)\n                JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter));\n        } else if ((prop_flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n            free_var_ref(rt, pr->u.var_ref);\n        } else if ((prop_flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n            js_autoinit_free(rt, pr);\n        }\n    } else {\n        JS_FreeValueRT(rt, pr->u.value);\n    }\n}\n\nstatic force_inline JSShapeProperty *find_own_property1(JSObject *p,\n                                                        JSAtom atom)\n{\n    JSShape *sh;\n    JSShapeProperty *pr, *prop;\n    intptr_t h;\n    sh = p->shape;\n    h = (uintptr_t)atom & sh->prop_hash_mask;\n    h = prop_hash_end(sh)[-h - 1];\n    prop = get_shape_prop(sh);\n    while (h) {\n        pr = &prop[h - 1];\n        if (likely(pr->atom == atom)) {\n            return pr;\n        }\n        h = pr->hash_next;\n    }\n    return NULL;\n}\n\nstatic force_inline JSShapeProperty *find_own_property(JSProperty **ppr,\n                                                       JSObject *p,\n                                                       JSAtom atom)\n{\n    JSShape *sh;\n    JSShapeProperty *pr, *prop;\n    intptr_t h;\n    sh = p->shape;\n    h = (uintptr_t)atom & sh->prop_hash_mask;\n    h = prop_hash_end(sh)[-h - 1];\n    prop = get_shape_prop(sh);\n    while (h) {\n        pr = &prop[h - 1];\n        if (likely(pr->atom == atom)) {\n            *ppr = &p->prop[h - 1];\n            /* the compiler should be able to assume that pr != NULL here */\n            return pr;\n        }\n        h = pr->hash_next;\n    }\n    *ppr = NULL;\n    return NULL;\n}\n\n/* indicate that the object may be part of a function prototype cycle */\nstatic void set_cycle_flag(JSContext *ctx, JSValueConst obj)\n{\n}\n\nstatic void free_var_ref(JSRuntime *rt, JSVarRef *var_ref)\n{\n    if (var_ref) {\n        assert(var_ref->header.ref_count > 0);\n        if (--var_ref->header.ref_count == 0) {\n            if (var_ref->is_detached) {\n                JS_FreeValueRT(rt, var_ref->value);\n                remove_gc_object(&var_ref->header);\n            } else {\n                list_del(&var_ref->header.link); /* still on the stack */\n            }\n            js_free_rt(rt, var_ref);\n        }\n    }\n}\n\nstatic void js_array_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    int i;\n\n    for(i = 0; i < p->u.array.count; i++) {\n        JS_FreeValueRT(rt, p->u.array.u.values[i]);\n    }\n    js_free_rt(rt, p->u.array.u.values);\n}\n\nstatic void js_array_mark(JSRuntime *rt, JSValueConst val,\n                          JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    int i;\n\n    for(i = 0; i < p->u.array.count; i++) {\n        JS_MarkValue(rt, p->u.array.u.values[i], mark_func);\n    }\n}\n\nstatic void js_object_data_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JS_FreeValueRT(rt, p->u.object_data);\n    p->u.object_data = JS_UNDEFINED;\n}\n\nstatic void js_object_data_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JS_MarkValue(rt, p->u.object_data, mark_func);\n}\n\nstatic void js_c_function_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n\n    if (p->u.cfunc.realm)\n        JS_FreeContext(p->u.cfunc.realm);\n}\n\nstatic void js_c_function_mark(JSRuntime *rt, JSValueConst val,\n                               JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n\n    if (p->u.cfunc.realm)\n        mark_func(rt, &p->u.cfunc.realm->header);\n}\n\nstatic void js_bytecode_function_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p1, *p = JS_VALUE_GET_OBJ(val);\n    JSFunctionBytecode *b;\n    JSVarRef **var_refs;\n    int i;\n\n    p1 = p->u.func.home_object;\n    if (p1) {\n        JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, p1));\n    }\n    b = p->u.func.function_bytecode;\n    if (b) {\n        var_refs = p->u.func.var_refs;\n        if (var_refs) {\n            for(i = 0; i < b->closure_var_count; i++)\n                free_var_ref(rt, var_refs[i]);\n            js_free_rt(rt, var_refs);\n        }\n        JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_FUNCTION_BYTECODE, b));\n    }\n}\n\nstatic void js_bytecode_function_mark(JSRuntime *rt, JSValueConst val,\n                                      JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSVarRef **var_refs = p->u.func.var_refs;\n    JSFunctionBytecode *b = p->u.func.function_bytecode;\n    int i;\n\n    if (p->u.func.home_object) {\n        JS_MarkValue(rt, JS_MKPTR(JS_TAG_OBJECT, p->u.func.home_object),\n                     mark_func);\n    }\n    if (b) {\n        if (var_refs) {\n            for(i = 0; i < b->closure_var_count; i++) {\n                JSVarRef *var_ref = var_refs[i];\n                if (var_ref && var_ref->is_detached) {\n                    mark_func(rt, &var_ref->header);\n                }\n            }\n        }\n        /* must mark the function bytecode because template objects may be\n           part of a cycle */\n        JS_MarkValue(rt, JS_MKPTR(JS_TAG_FUNCTION_BYTECODE, b), mark_func);\n    }\n}\n\nstatic void js_bound_function_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSBoundFunction *bf = p->u.bound_function;\n    int i;\n\n    JS_FreeValueRT(rt, bf->func_obj);\n    JS_FreeValueRT(rt, bf->this_val);\n    for(i = 0; i < bf->argc; i++) {\n        JS_FreeValueRT(rt, bf->argv[i]);\n    }\n    js_free_rt(rt, bf);\n}\n\nstatic void js_bound_function_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSBoundFunction *bf = p->u.bound_function;\n    int i;\n\n    JS_MarkValue(rt, bf->func_obj, mark_func);\n    JS_MarkValue(rt, bf->this_val, mark_func);\n    for(i = 0; i < bf->argc; i++)\n        JS_MarkValue(rt, bf->argv[i], mark_func);\n}\n\nstatic void js_for_in_iterator_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSForInIterator *it = p->u.for_in_iterator;\n    JS_FreeValueRT(rt, it->obj);\n    js_free_rt(rt, it);\n}\n\nstatic void js_for_in_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSForInIterator *it = p->u.for_in_iterator;\n    JS_MarkValue(rt, it->obj, mark_func);\n}\n\nstatic void free_object(JSRuntime *rt, JSObject *p)\n{\n    int i;\n    JSClassFinalizer *finalizer;\n    JSShape *sh;\n    JSShapeProperty *pr;\n\n    p->free_mark = 1; /* used to tell the object is invalid when\n                         freeing cycles */\n    /* free all the fields */\n    sh = p->shape;\n    pr = get_shape_prop(sh);\n    for(i = 0; i < sh->prop_count; i++) {\n        free_property(rt, &p->prop[i], pr->flags);\n        pr++;\n    }\n    js_free_rt(rt, p->prop);\n    /* as an optimization we destroy the shape immediately without\n       putting it in gc_zero_ref_count_list */\n    js_free_shape(rt, sh);\n\n    /* fail safe */\n    p->shape = NULL;\n    p->prop = NULL;\n\n    if (unlikely(p->first_weak_ref)) {\n        reset_weak_ref(rt, p);\n    }\n\n    finalizer = rt->class_array[p->class_id].finalizer;\n    if (finalizer)\n        (*finalizer)(rt, JS_MKPTR(JS_TAG_OBJECT, p));\n\n    /* fail safe */\n    p->class_id = 0;\n    p->u.opaque = NULL;\n    p->u.func.var_refs = NULL;\n    p->u.func.home_object = NULL;\n\n    remove_gc_object(&p->header);\n    if (rt->gc_phase == JS_GC_PHASE_REMOVE_CYCLES && p->header.ref_count != 0) {\n        list_add_tail(&p->header.link, &rt->gc_zero_ref_count_list);\n    } else {\n        js_free_rt(rt, p);\n    }\n}\n\nstatic void free_gc_object(JSRuntime *rt, JSGCObjectHeader *gp)\n{\n    switch(gp->gc_obj_type) {\n    case JS_GC_OBJ_TYPE_JS_OBJECT:\n        free_object(rt, (JSObject *)gp);\n        break;\n    case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE:\n        free_function_bytecode(rt, (JSFunctionBytecode *)gp);\n        break;\n    default:\n        abort();\n    }\n}\n\nstatic void free_zero_refcount(JSRuntime *rt)\n{\n    struct list_head *el;\n    JSGCObjectHeader *p;\n    \n    rt->gc_phase = JS_GC_PHASE_DECREF;\n    for(;;) {\n        el = rt->gc_zero_ref_count_list.next;\n        if (el == &rt->gc_zero_ref_count_list)\n            break;\n        p = list_entry(el, JSGCObjectHeader, link);\n        assert(p->ref_count == 0);\n        free_gc_object(rt, p);\n    }\n    rt->gc_phase = JS_GC_PHASE_NONE;\n}\n\n/* called with the ref_count of 'v' reaches zero. */\nvoid __JS_FreeValueRT(JSRuntime *rt, JSValue v)\n{\n    uint32_t tag = JS_VALUE_GET_TAG(v);\n\n#ifdef DUMP_FREE\n    {\n        printf(\"Freeing \");\n        if (tag == JS_TAG_OBJECT) {\n            JS_DumpObject(rt, JS_VALUE_GET_OBJ(v));\n        } else {\n            JS_DumpValueShort(rt, v);\n            printf(\"\\n\");\n        }\n    }\n#endif\n\n    switch(tag) {\n    case JS_TAG_STRING:\n        {\n            JSString *p = JS_VALUE_GET_STRING(v);\n            if (p->atom_type) {\n                JS_FreeAtomStruct(rt, p);\n            } else {\n#ifdef DUMP_LEAKS\n                list_del(&p->link);\n#endif\n                js_free_rt(rt, p);\n            }\n        }\n        break;\n    case JS_TAG_OBJECT:\n    case JS_TAG_FUNCTION_BYTECODE:\n        {\n            JSGCObjectHeader *p = JS_VALUE_GET_PTR(v);\n            if (rt->gc_phase != JS_GC_PHASE_REMOVE_CYCLES) {\n                list_del(&p->link);\n                list_add(&p->link, &rt->gc_zero_ref_count_list);\n                if (rt->gc_phase == JS_GC_PHASE_NONE) {\n                    free_zero_refcount(rt);\n                }\n            }\n        }\n        break;\n    case JS_TAG_MODULE:\n        abort(); /* never freed here */\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *bf = JS_VALUE_GET_PTR(v);\n            bf_delete(&bf->num);\n            js_free_rt(rt, bf);\n        }\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        {\n            JSBigDecimal *bf = JS_VALUE_GET_PTR(v);\n            bfdec_delete(&bf->num);\n            js_free_rt(rt, bf);\n        }\n        break;\n#endif\n    case JS_TAG_SYMBOL:\n        {\n            JSAtomStruct *p = JS_VALUE_GET_PTR(v);\n            JS_FreeAtomStruct(rt, p);\n        }\n        break;\n    default:\n        printf(\"__JS_FreeValue: unknown tag=%d\\n\", tag);\n        abort();\n    }\n}\n\nvoid __JS_FreeValue(JSContext *ctx, JSValue v)\n{\n    __JS_FreeValueRT(ctx->rt, v);\n}\n\n/* garbage collection */\n\nstatic void add_gc_object(JSRuntime *rt, JSGCObjectHeader *h,\n                          JSGCObjectTypeEnum type)\n{\n    h->mark = 0;\n    h->gc_obj_type = type;\n    list_add_tail(&h->link, &rt->gc_obj_list);\n}\n\nstatic void remove_gc_object(JSGCObjectHeader *h)\n{\n    list_del(&h->link);\n}\n\nvoid JS_MarkValue(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func)\n{\n    if (JS_VALUE_HAS_REF_COUNT(val)) {\n        switch(JS_VALUE_GET_TAG(val)) {\n        case JS_TAG_OBJECT:\n        case JS_TAG_FUNCTION_BYTECODE:\n            mark_func(rt, JS_VALUE_GET_PTR(val));\n            break;\n        default:\n            break;\n        }\n    }\n}\n\nstatic void mark_children(JSRuntime *rt, JSGCObjectHeader *gp,\n                          JS_MarkFunc *mark_func)\n{\n    switch(gp->gc_obj_type) {\n    case JS_GC_OBJ_TYPE_JS_OBJECT:\n        {\n            JSObject *p = (JSObject *)gp;\n            JSShapeProperty *prs;\n            JSShape *sh;\n            int i;\n            sh = p->shape;\n            mark_func(rt, &sh->header);\n            /* mark all the fields */\n            prs = get_shape_prop(sh);\n            for(i = 0; i < sh->prop_count; i++) {\n                JSProperty *pr = &p->prop[i];\n                if (prs->atom != JS_ATOM_NULL) {\n                    if (prs->flags & JS_PROP_TMASK) {\n                        if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {\n                            if (pr->u.getset.getter)\n                                mark_func(rt, &pr->u.getset.getter->header);\n                            if (pr->u.getset.setter)\n                                mark_func(rt, &pr->u.getset.setter->header);\n                        } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n                            if (pr->u.var_ref->is_detached) {\n                                /* Note: the tag does not matter\n                                   provided it is a GC object */\n                                mark_func(rt, &pr->u.var_ref->header);\n                            }\n                        } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n                            js_autoinit_mark(rt, pr, mark_func);\n                        }\n                    } else {\n                        JS_MarkValue(rt, pr->u.value, mark_func);\n                    }\n                }\n                prs++;\n            }\n\n            if (p->class_id != JS_CLASS_OBJECT) {\n                JSClassGCMark *gc_mark;\n                gc_mark = rt->class_array[p->class_id].gc_mark;\n                if (gc_mark)\n                    gc_mark(rt, JS_MKPTR(JS_TAG_OBJECT, p), mark_func);\n            }\n        }\n        break;\n    case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE:\n        /* the template objects can be part of a cycle */\n        {\n            JSFunctionBytecode *b = (JSFunctionBytecode *)gp;\n            int i;\n            for(i = 0; i < b->cpool_count; i++) {\n                JS_MarkValue(rt, b->cpool[i], mark_func);\n            }\n            if (b->realm)\n                mark_func(rt, &b->realm->header);\n        }\n        break;\n    case JS_GC_OBJ_TYPE_VAR_REF:\n        {\n            JSVarRef *var_ref = (JSVarRef *)gp;\n            /* only detached variable referenced are taken into account */\n            assert(var_ref->is_detached);\n            JS_MarkValue(rt, *var_ref->pvalue, mark_func);\n        }\n        break;\n    case JS_GC_OBJ_TYPE_ASYNC_FUNCTION:\n        {\n            JSAsyncFunctionData *s = (JSAsyncFunctionData *)gp;\n            if (s->is_active)\n                async_func_mark(rt, &s->func_state, mark_func);\n            JS_MarkValue(rt, s->resolving_funcs[0], mark_func);\n            JS_MarkValue(rt, s->resolving_funcs[1], mark_func);\n        }\n        break;\n    case JS_GC_OBJ_TYPE_SHAPE:\n        {\n            JSShape *sh = (JSShape *)gp;\n            if (sh->proto != NULL) {\n                mark_func(rt, &sh->proto->header);\n            }\n        }\n        break;\n    case JS_GC_OBJ_TYPE_JS_CONTEXT:\n        {\n            JSContext *ctx = (JSContext *)gp;\n            JS_MarkContext(rt, ctx, mark_func);\n        }\n        break;\n    default:\n        abort();\n    }\n}\n\nstatic void gc_decref_child(JSRuntime *rt, JSGCObjectHeader *p)\n{\n    assert(p->ref_count > 0);\n    p->ref_count--;\n    if (p->ref_count == 0 && p->mark == 1) {\n        list_del(&p->link);\n        list_add_tail(&p->link, &rt->tmp_obj_list);\n    }\n}\n\nstatic void gc_decref(JSRuntime *rt)\n{\n    struct list_head *el, *el1;\n    JSGCObjectHeader *p;\n    \n    init_list_head(&rt->tmp_obj_list);\n\n    /* decrement the refcount of all the children of all the GC\n       objects and move the GC objects with zero refcount to\n       tmp_obj_list */\n    list_for_each_safe(el, el1, &rt->gc_obj_list) {\n        p = list_entry(el, JSGCObjectHeader, link);\n        assert(p->mark == 0);\n        mark_children(rt, p, gc_decref_child);\n        p->mark = 1;\n        if (p->ref_count == 0) {\n            list_del(&p->link);\n            list_add_tail(&p->link, &rt->tmp_obj_list);\n        }\n    }\n}\n\nstatic void gc_scan_incref_child(JSRuntime *rt, JSGCObjectHeader *p)\n{\n    p->ref_count++;\n    if (p->ref_count == 1) {\n        /* ref_count was 0: remove from tmp_obj_list and add at the\n           end of gc_obj_list */\n        list_del(&p->link);\n        list_add_tail(&p->link, &rt->gc_obj_list);\n        p->mark = 0; /* reset the mark for the next GC call */\n    }\n}\n\nstatic void gc_scan_incref_child2(JSRuntime *rt, JSGCObjectHeader *p)\n{\n    p->ref_count++;\n}\n\nstatic void gc_scan(JSRuntime *rt)\n{\n    struct list_head *el;\n    JSGCObjectHeader *p;\n\n    /* keep the objects with a refcount > 0 and their children. */\n    list_for_each(el, &rt->gc_obj_list) {\n        p = list_entry(el, JSGCObjectHeader, link);\n        assert(p->ref_count > 0);\n        p->mark = 0; /* reset the mark for the next GC call */\n        mark_children(rt, p, gc_scan_incref_child);\n    }\n    \n    /* restore the refcount of the objects to be deleted. */\n    list_for_each(el, &rt->tmp_obj_list) {\n        p = list_entry(el, JSGCObjectHeader, link);\n        mark_children(rt, p, gc_scan_incref_child2);\n    }\n}\n\nstatic void gc_free_cycles(JSRuntime *rt)\n{\n    struct list_head *el, *el1;\n    JSGCObjectHeader *p;\n#ifdef DUMP_GC_FREE\n    BOOL header_done = FALSE;\n#endif\n\n    rt->gc_phase = JS_GC_PHASE_REMOVE_CYCLES;\n\n    for(;;) {\n        el = rt->tmp_obj_list.next;\n        if (el == &rt->tmp_obj_list)\n            break;\n        p = list_entry(el, JSGCObjectHeader, link);\n        /* Only need to free the GC object associated with JS\n           values. The rest will be automatically removed because they\n           must be referenced by them. */\n        switch(p->gc_obj_type) {\n        case JS_GC_OBJ_TYPE_JS_OBJECT:\n        case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE:\n#ifdef DUMP_GC_FREE\n            if (!header_done) {\n                printf(\"Freeing cycles:\\n\");\n                JS_DumpObjectHeader(rt);\n                header_done = TRUE;\n            }\n            JS_DumpGCObject(rt, p);\n#endif\n            free_gc_object(rt, p);\n            break;\n        default:\n            list_del(&p->link);\n            list_add_tail(&p->link, &rt->gc_zero_ref_count_list);\n            break;\n        }\n    }\n    rt->gc_phase = JS_GC_PHASE_NONE;\n           \n    list_for_each_safe(el, el1, &rt->gc_zero_ref_count_list) {\n        p = list_entry(el, JSGCObjectHeader, link);\n        assert(p->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT ||\n               p->gc_obj_type == JS_GC_OBJ_TYPE_FUNCTION_BYTECODE);\n        js_free_rt(rt, p);\n    }\n\n    init_list_head(&rt->gc_zero_ref_count_list);\n}\n\nvoid JS_RunGC(JSRuntime *rt)\n{\n    /* decrement the reference of the children of each object. mark =\n       1 after this pass. */\n    gc_decref(rt);\n\n    /* keep the GC objects with a non zero refcount and their childs */\n    gc_scan(rt);\n\n    /* free the GC objects in a cycle */\n    gc_free_cycles(rt);\n}\n\n/* Return false if not an object or if the object has already been\n   freed (zombie objects are visible in finalizers when freeing\n   cycles). */\nBOOL JS_IsLiveObject(JSRuntime *rt, JSValueConst obj)\n{\n    JSObject *p;\n    if (!JS_IsObject(obj))\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(obj);\n    return !p->free_mark;\n}\n\n/* Compute memory used by various object types */\n/* XXX: poor man's approach to handling multiply referenced objects */\ntypedef struct JSMemoryUsage_helper {\n    double memory_used_count;\n    double str_count;\n    double str_size;\n    int64_t js_func_count;\n    double js_func_size;\n    int64_t js_func_code_size;\n    int64_t js_func_pc2line_count;\n    int64_t js_func_pc2line_size;\n} JSMemoryUsage_helper;\n\nstatic void compute_value_size(JSValueConst val, JSMemoryUsage_helper *hp);\n\nstatic void compute_jsstring_size(JSString *str, JSMemoryUsage_helper *hp)\n{\n    if (!str->atom_type) {  /* atoms are handled separately */\n        double s_ref_count = str->header.ref_count;\n        hp->str_count += 1 / s_ref_count;\n        hp->str_size += ((sizeof(*str) + (str->len << str->is_wide_char) +\n                          1 - str->is_wide_char) / s_ref_count);\n    }\n}\n\nstatic void compute_bytecode_size(JSFunctionBytecode *b, JSMemoryUsage_helper *hp)\n{\n    int memory_used_count, js_func_size, i;\n\n    memory_used_count = 0;\n    js_func_size = offsetof(JSFunctionBytecode, debug);\n    if (b->vardefs) {\n        js_func_size += (b->arg_count + b->var_count) * sizeof(*b->vardefs);\n    }\n    if (b->cpool) {\n        js_func_size += b->cpool_count * sizeof(*b->cpool);\n        for (i = 0; i < b->cpool_count; i++) {\n            JSValueConst val = b->cpool[i];\n            compute_value_size(val, hp);\n        }\n    }\n    if (b->closure_var) {\n        js_func_size += b->closure_var_count * sizeof(*b->closure_var);\n    }\n    if (!b->read_only_bytecode && b->byte_code_buf) {\n        hp->js_func_code_size += b->byte_code_len;\n    }\n    if (b->has_debug) {\n        js_func_size += sizeof(*b) - offsetof(JSFunctionBytecode, debug);\n        if (b->debug.source) {\n            memory_used_count++;\n            js_func_size += b->debug.source_len + 1;\n        }\n        if (b->debug.pc2line_len) {\n            memory_used_count++;\n            hp->js_func_pc2line_count += 1;\n            hp->js_func_pc2line_size += b->debug.pc2line_len;\n        }\n    }\n    hp->js_func_size += js_func_size;\n    hp->js_func_count += 1;\n    hp->memory_used_count += memory_used_count;\n}\n\nstatic void compute_value_size(JSValueConst val, JSMemoryUsage_helper *hp)\n{\n    switch(JS_VALUE_GET_TAG(val)) {\n    case JS_TAG_STRING:\n        compute_jsstring_size(JS_VALUE_GET_STRING(val), hp);\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n    case JS_TAG_BIG_FLOAT:\n    case JS_TAG_BIG_DECIMAL:\n        /* should track JSBigFloat usage */\n        break;\n#endif\n    }\n}\n\nvoid JS_ComputeMemoryUsage(JSRuntime *rt, JSMemoryUsage *s)\n{\n    struct list_head *el, *el1;\n    int i;\n    JSMemoryUsage_helper mem = { 0 }, *hp = &mem;\n\n    memset(s, 0, sizeof(*s));\n    s->malloc_count = rt->malloc_state.malloc_count;\n    s->malloc_size = rt->malloc_state.malloc_size;\n    s->malloc_limit = rt->malloc_state.malloc_limit;\n\n    s->memory_used_count = 2; /* rt + rt->class_array */\n    s->memory_used_size = sizeof(JSRuntime) + sizeof(JSValue) * rt->class_count;\n\n    list_for_each(el, &rt->context_list) {\n        JSContext *ctx = list_entry(el, JSContext, link);\n        JSShape *sh = ctx->array_shape;\n        s->memory_used_count += 2; /* ctx + ctx->class_proto */\n        s->memory_used_size += sizeof(JSContext) +\n            sizeof(JSValue) * rt->class_count;\n        s->binary_object_count += ctx->binary_object_count;\n        s->binary_object_size += ctx->binary_object_size;\n\n        /* the hashed shapes are counted separately */\n        if (sh && !sh->is_hashed) {\n            int hash_size = sh->prop_hash_mask + 1;\n            s->shape_count++;\n            s->shape_size += get_shape_size(hash_size, sh->prop_size);\n        }\n        list_for_each(el1, &ctx->loaded_modules) {\n            JSModuleDef *m = list_entry(el1, JSModuleDef, link);\n            s->memory_used_count += 1;\n            s->memory_used_size += sizeof(*m);\n            if (m->req_module_entries) {\n                s->memory_used_count += 1;\n                s->memory_used_size += m->req_module_entries_count * sizeof(*m->req_module_entries);\n            }\n            if (m->export_entries) {\n                s->memory_used_count += 1;\n                s->memory_used_size += m->export_entries_count * sizeof(*m->export_entries);\n                for (i = 0; i < m->export_entries_count; i++) {\n                    JSExportEntry *me = &m->export_entries[i];\n                    if (me->export_type == JS_EXPORT_TYPE_LOCAL && me->u.local.var_ref) {\n                        /* potential multiple count */\n                        s->memory_used_count += 1;\n                        compute_value_size(me->u.local.var_ref->value, hp);\n                    }\n                }\n            }\n            if (m->star_export_entries) {\n                s->memory_used_count += 1;\n                s->memory_used_size += m->star_export_entries_count * sizeof(*m->star_export_entries);\n            }\n            if (m->import_entries) {\n                s->memory_used_count += 1;\n                s->memory_used_size += m->import_entries_count * sizeof(*m->import_entries);\n            }\n            compute_value_size(m->module_ns, hp);\n            compute_value_size(m->func_obj, hp);\n        }\n    }\n\n    list_for_each(el, &rt->gc_obj_list) {\n        JSGCObjectHeader *gp = list_entry(el, JSGCObjectHeader, link);\n        JSObject *p;\n        JSShape *sh;\n        JSShapeProperty *prs;\n\n        /* XXX: could count the other GC object types too */\n        if (gp->gc_obj_type == JS_GC_OBJ_TYPE_FUNCTION_BYTECODE) {\n            compute_bytecode_size((JSFunctionBytecode *)gp, hp);\n            continue;\n        } else if (gp->gc_obj_type != JS_GC_OBJ_TYPE_JS_OBJECT) {\n            continue;\n        }\n        p = (JSObject *)gp;\n        sh = p->shape;\n        s->obj_count++;\n        if (p->prop) {\n            s->memory_used_count++;\n            s->prop_size += sh->prop_size * sizeof(*p->prop);\n            s->prop_count += sh->prop_count;\n            prs = get_shape_prop(sh);\n            for(i = 0; i < sh->prop_count; i++) {\n                JSProperty *pr = &p->prop[i];\n                if (prs->atom != JS_ATOM_NULL && !(prs->flags & JS_PROP_TMASK)) {\n                    compute_value_size(pr->u.value, hp);\n                }\n                prs++;\n            }\n        }\n        /* the hashed shapes are counted separately */\n        if (!sh->is_hashed) {\n            int hash_size = sh->prop_hash_mask + 1;\n            s->shape_count++;\n            s->shape_size += get_shape_size(hash_size, sh->prop_size);\n        }\n\n        switch(p->class_id) {\n        case JS_CLASS_ARRAY:             /* u.array | length */\n        case JS_CLASS_ARGUMENTS:         /* u.array | length */\n            s->array_count++;\n            if (p->fast_array) {\n                s->fast_array_count++;\n                if (p->u.array.u.values) {\n                    s->memory_used_count++;\n                    s->memory_used_size += p->u.array.count *\n                        sizeof(*p->u.array.u.values);\n                    s->fast_array_elements += p->u.array.count;\n                    for (i = 0; i < p->u.array.count; i++) {\n                        compute_value_size(p->u.array.u.values[i], hp);\n                    }\n                }\n            }\n            break;\n        case JS_CLASS_NUMBER:            /* u.object_data */\n        case JS_CLASS_STRING:            /* u.object_data */\n        case JS_CLASS_BOOLEAN:           /* u.object_data */\n        case JS_CLASS_SYMBOL:            /* u.object_data */\n        case JS_CLASS_DATE:              /* u.object_data */\n#ifdef CONFIG_BIGNUM\n        case JS_CLASS_BIG_INT:           /* u.object_data */\n        case JS_CLASS_BIG_FLOAT:         /* u.object_data */\n        case JS_CLASS_BIG_DECIMAL:         /* u.object_data */\n#endif\n            compute_value_size(p->u.object_data, hp);\n            break;\n        case JS_CLASS_C_FUNCTION:        /* u.cfunc */\n            s->c_func_count++;\n            break;\n        case JS_CLASS_BYTECODE_FUNCTION: /* u.func */\n            {\n                JSFunctionBytecode *b = p->u.func.function_bytecode;\n                JSVarRef **var_refs = p->u.func.var_refs;\n                /* home_object: object will be accounted for in list scan */\n                if (var_refs) {\n                    s->memory_used_count++;\n                    s->js_func_size += b->closure_var_count * sizeof(*var_refs);\n                    for (i = 0; i < b->closure_var_count; i++) {\n                        if (var_refs[i]) {\n                            double ref_count = var_refs[i]->header.ref_count;\n                            s->memory_used_count += 1 / ref_count;\n                            s->js_func_size += sizeof(*var_refs[i]) / ref_count;\n                            /* handle non object closed values */\n                            if (var_refs[i]->pvalue == &var_refs[i]->value) {\n                                /* potential multiple count */\n                                compute_value_size(var_refs[i]->value, hp);\n                            }\n                        }\n                    }\n                }\n            }\n            break;\n        case JS_CLASS_BOUND_FUNCTION:    /* u.bound_function */\n            {\n                JSBoundFunction *bf = p->u.bound_function;\n                /* func_obj and this_val are objects */\n                for (i = 0; i < bf->argc; i++) {\n                    compute_value_size(bf->argv[i], hp);\n                }\n                s->memory_used_count += 1;\n                s->memory_used_size += sizeof(*bf) + bf->argc * sizeof(*bf->argv);\n            }\n            break;\n        case JS_CLASS_C_FUNCTION_DATA:   /* u.c_function_data_record */\n            {\n                JSCFunctionDataRecord *fd = p->u.c_function_data_record;\n                if (fd) {\n                    for (i = 0; i < fd->data_len; i++) {\n                        compute_value_size(fd->data[i], hp);\n                    }\n                    s->memory_used_count += 1;\n                    s->memory_used_size += sizeof(*fd) + fd->data_len * sizeof(*fd->data);\n                }\n            }\n            break;\n        case JS_CLASS_REGEXP:            /* u.regexp */\n            compute_jsstring_size(p->u.regexp.pattern, hp);\n            compute_jsstring_size(p->u.regexp.bytecode, hp);\n            break;\n\n        case JS_CLASS_FOR_IN_ITERATOR:   /* u.for_in_iterator */\n            {\n                JSForInIterator *it = p->u.for_in_iterator;\n                if (it) {\n                    compute_value_size(it->obj, hp);\n                    s->memory_used_count += 1;\n                    s->memory_used_size += sizeof(*it);\n                }\n            }\n            break;\n        case JS_CLASS_ARRAY_BUFFER:      /* u.array_buffer */\n        case JS_CLASS_SHARED_ARRAY_BUFFER: /* u.array_buffer */\n            {\n                JSArrayBuffer *abuf = p->u.array_buffer;\n                if (abuf) {\n                    s->memory_used_count += 1;\n                    s->memory_used_size += sizeof(*abuf);\n                    if (abuf->data) {\n                        s->memory_used_count += 1;\n                        s->memory_used_size += abuf->byte_length;\n                    }\n                }\n            }\n            break;\n        case JS_CLASS_GENERATOR:         /* u.generator_data */\n        case JS_CLASS_UINT8C_ARRAY:      /* u.typed_array / u.array */\n        case JS_CLASS_INT8_ARRAY:        /* u.typed_array / u.array */\n        case JS_CLASS_UINT8_ARRAY:       /* u.typed_array / u.array */\n        case JS_CLASS_INT16_ARRAY:       /* u.typed_array / u.array */\n        case JS_CLASS_UINT16_ARRAY:      /* u.typed_array / u.array */\n        case JS_CLASS_INT32_ARRAY:       /* u.typed_array / u.array */\n        case JS_CLASS_UINT32_ARRAY:      /* u.typed_array / u.array */\n#ifdef CONFIG_BIGNUM\n        case JS_CLASS_BIG_INT64_ARRAY:   /* u.typed_array / u.array */\n        case JS_CLASS_BIG_UINT64_ARRAY:  /* u.typed_array / u.array */\n#endif\n        case JS_CLASS_FLOAT32_ARRAY:     /* u.typed_array / u.array */\n        case JS_CLASS_FLOAT64_ARRAY:     /* u.typed_array / u.array */\n        case JS_CLASS_DATAVIEW:          /* u.typed_array */\n#ifdef CONFIG_BIGNUM\n        case JS_CLASS_FLOAT_ENV:         /* u.float_env */\n#endif\n        case JS_CLASS_MAP:               /* u.map_state */\n        case JS_CLASS_SET:               /* u.map_state */\n        case JS_CLASS_WEAKMAP:           /* u.map_state */\n        case JS_CLASS_WEAKSET:           /* u.map_state */\n        case JS_CLASS_MAP_ITERATOR:      /* u.map_iterator_data */\n        case JS_CLASS_SET_ITERATOR:      /* u.map_iterator_data */\n        case JS_CLASS_ARRAY_ITERATOR:    /* u.array_iterator_data */\n        case JS_CLASS_STRING_ITERATOR:   /* u.array_iterator_data */\n        case JS_CLASS_PROXY:             /* u.proxy_data */\n        case JS_CLASS_PROMISE:           /* u.promise_data */\n        case JS_CLASS_PROMISE_RESOLVE_FUNCTION:  /* u.promise_function_data */\n        case JS_CLASS_PROMISE_REJECT_FUNCTION:   /* u.promise_function_data */\n        case JS_CLASS_ASYNC_FUNCTION_RESOLVE:    /* u.async_function_data */\n        case JS_CLASS_ASYNC_FUNCTION_REJECT:     /* u.async_function_data */\n        case JS_CLASS_ASYNC_FROM_SYNC_ITERATOR:  /* u.async_from_sync_iterator_data */\n        case JS_CLASS_ASYNC_GENERATOR:   /* u.async_generator_data */\n            /* TODO */\n        default:\n            /* XXX: class definition should have an opaque block size */\n            if (p->u.opaque) {\n                s->memory_used_count += 1;\n            }\n            break;\n        }\n    }\n    s->obj_size += s->obj_count * sizeof(JSObject);\n\n    /* hashed shapes */\n    s->memory_used_count++; /* rt->shape_hash */\n    s->memory_used_size += sizeof(rt->shape_hash[0]) * rt->shape_hash_size;\n    for(i = 0; i < rt->shape_hash_size; i++) {\n        JSShape *sh;\n        for(sh = rt->shape_hash[i]; sh != NULL; sh = sh->shape_hash_next) {\n            int hash_size = sh->prop_hash_mask + 1;\n            s->shape_count++;\n            s->shape_size += get_shape_size(hash_size, sh->prop_size);\n        }\n    }\n\n    /* atoms */\n    s->memory_used_count += 2; /* rt->atom_array, rt->atom_hash */\n    s->atom_count = rt->atom_count;\n    s->atom_size = sizeof(rt->atom_array[0]) * rt->atom_size +\n        sizeof(rt->atom_hash[0]) * rt->atom_hash_size;\n    for(i = 0; i < rt->atom_size; i++) {\n        JSAtomStruct *p = rt->atom_array[i];\n        if (!atom_is_free(p)) {\n            s->atom_size += (sizeof(*p) + (p->len << p->is_wide_char) +\n                             1 - p->is_wide_char);\n        }\n    }\n    s->str_count = round(mem.str_count);\n    s->str_size = round(mem.str_size);\n    s->js_func_count = mem.js_func_count;\n    s->js_func_size = round(mem.js_func_size);\n    s->js_func_code_size = mem.js_func_code_size;\n    s->js_func_pc2line_count = mem.js_func_pc2line_count;\n    s->js_func_pc2line_size = mem.js_func_pc2line_size;\n    s->memory_used_count += round(mem.memory_used_count) +\n        s->atom_count + s->str_count +\n        s->obj_count + s->shape_count +\n        s->js_func_count + s->js_func_pc2line_count;\n    s->memory_used_size += s->atom_size + s->str_size +\n        s->obj_size + s->prop_size + s->shape_size +\n        s->js_func_size + s->js_func_code_size + s->js_func_pc2line_size;\n}\n\nvoid JS_DumpMemoryUsage(FILE *fp, const JSMemoryUsage *s, JSRuntime *rt)\n{\n    fprintf(fp, \"QuickJS memory usage -- \"\n#ifdef CONFIG_BIGNUM\n            \"BigNum \"\n#endif\n            CONFIG_VERSION \" version, %d-bit, malloc limit: %\"PRId64\"\\n\\n\",\n            (int)sizeof(void *) * 8, (int64_t)(ssize_t)s->malloc_limit);\n#if 1\n    if (rt) {\n        static const struct {\n            const char *name;\n            size_t size;\n        } object_types[] = {\n            { \"JSRuntime\", sizeof(JSRuntime) },\n            { \"JSContext\", sizeof(JSContext) },\n            { \"JSObject\", sizeof(JSObject) },\n            { \"JSString\", sizeof(JSString) },\n            { \"JSFunctionBytecode\", sizeof(JSFunctionBytecode) },\n        };\n        int i, usage_size_ok = 0;\n        for(i = 0; i < countof(object_types); i++) {\n            unsigned int size = object_types[i].size;\n            void *p = js_malloc_rt(rt, size);\n            if (p) {\n                unsigned int size1 = js_malloc_usable_size_rt(rt, p);\n                if (size1 >= size) {\n                    usage_size_ok = 1;\n                    fprintf(fp, \"  %3u + %-2u  %s\\n\",\n                            size, size1 - size, object_types[i].name);\n                }\n                js_free_rt(rt, p);\n            }\n        }\n        if (!usage_size_ok) {\n            fprintf(fp, \"  malloc_usable_size unavailable\\n\");\n        }\n        {\n            int obj_classes[JS_CLASS_INIT_COUNT + 1] = { 0 };\n            int class_id;\n            struct list_head *el;\n            list_for_each(el, &rt->gc_obj_list) {\n                JSGCObjectHeader *gp = list_entry(el, JSGCObjectHeader, link);\n                JSObject *p;\n                if (gp->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT) {\n                    p = (JSObject *)gp;\n                    obj_classes[min_uint32(p->class_id, JS_CLASS_INIT_COUNT)]++;\n                }\n            }\n            fprintf(fp, \"\\n\" \"JSObject classes\\n\");\n            if (obj_classes[0])\n                fprintf(fp, \"  %5d  %2.0d %s\\n\", obj_classes[0], 0, \"none\");\n            for (class_id = 1; class_id < JS_CLASS_INIT_COUNT; class_id++) {\n                if (obj_classes[class_id]) {\n                    char buf[ATOM_GET_STR_BUF_SIZE];\n                    fprintf(fp, \"  %5d  %2.0d %s\\n\", obj_classes[class_id], class_id,\n                            JS_AtomGetStrRT(rt, buf, sizeof(buf), js_std_class_def[class_id - 1].class_name));\n                }\n            }\n            if (obj_classes[JS_CLASS_INIT_COUNT])\n                fprintf(fp, \"  %5d  %2.0d %s\\n\", obj_classes[JS_CLASS_INIT_COUNT], 0, \"other\");\n        }\n        fprintf(fp, \"\\n\");\n    }\n#endif\n    fprintf(fp, \"%-20s %8s %8s\\n\", \"NAME\", \"COUNT\", \"SIZE\");\n\n    if (s->malloc_count) {\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per block)\\n\",\n                \"memory allocated\", s->malloc_count, s->malloc_size,\n                (double)s->malloc_size / s->malloc_count);\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%d overhead, %0.1f average slack)\\n\",\n                \"memory used\", s->memory_used_count, s->memory_used_size,\n                MALLOC_OVERHEAD, ((double)(s->malloc_size - s->memory_used_size) /\n                                  s->memory_used_count));\n    }\n    if (s->atom_count) {\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per atom)\\n\",\n                \"atoms\", s->atom_count, s->atom_size,\n                (double)s->atom_size / s->atom_count);\n    }\n    if (s->str_count) {\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per string)\\n\",\n                \"strings\", s->str_count, s->str_size,\n                (double)s->str_size / s->str_count);\n    }\n    if (s->obj_count) {\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per object)\\n\",\n                \"objects\", s->obj_count, s->obj_size,\n                (double)s->obj_size / s->obj_count);\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per object)\\n\",\n                \"  properties\", s->prop_count, s->prop_size,\n                (double)s->prop_count / s->obj_count);\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per shape)\\n\",\n                \"  shapes\", s->shape_count, s->shape_size,\n                (double)s->shape_size / s->shape_count);\n    }\n    if (s->js_func_count) {\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"\\n\",\n                \"bytecode functions\", s->js_func_count, s->js_func_size);\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per function)\\n\",\n                \"  bytecode\", s->js_func_count, s->js_func_code_size,\n                (double)s->js_func_code_size / s->js_func_count);\n        if (s->js_func_pc2line_count) {\n            fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per function)\\n\",\n                    \"  pc2line\", s->js_func_pc2line_count,\n                    s->js_func_pc2line_size,\n                    (double)s->js_func_pc2line_size / s->js_func_pc2line_count);\n        }\n    }\n    if (s->c_func_count) {\n        fprintf(fp, \"%-20s %8\"PRId64\"\\n\", \"C functions\", s->c_func_count);\n    }\n    if (s->array_count) {\n        fprintf(fp, \"%-20s %8\"PRId64\"\\n\", \"arrays\", s->array_count);\n        if (s->fast_array_count) {\n            fprintf(fp, \"%-20s %8\"PRId64\"\\n\", \"  fast arrays\", s->fast_array_count);\n            fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"  (%0.1f per fast array)\\n\",\n                    \"  elements\", s->fast_array_elements,\n                    s->fast_array_elements * (int)sizeof(JSValue),\n                    (double)s->fast_array_elements / s->fast_array_count);\n        }\n    }\n    if (s->binary_object_count) {\n        fprintf(fp, \"%-20s %8\"PRId64\" %8\"PRId64\"\\n\",\n                \"binary objects\", s->binary_object_count, s->binary_object_size);\n    }\n}\n\nJSValue JS_GetGlobalObject(JSContext *ctx)\n{\n    return JS_DupValue(ctx, ctx->global_obj);\n}\n\n/* WARNING: obj is freed */\nJSValue JS_Throw(JSContext *ctx, JSValue obj)\n{\n    JSRuntime *rt = ctx->rt;\n    JS_FreeValue(ctx, rt->current_exception);\n    rt->current_exception = obj;\n    return JS_EXCEPTION;\n}\n\n/* return the pending exception (cannot be called twice). */\nJSValue JS_GetException(JSContext *ctx)\n{\n    JSValue val;\n    JSRuntime *rt = ctx->rt;\n    val = rt->current_exception;\n    rt->current_exception = JS_NULL;\n    return val;\n}\n\nstatic void dbuf_put_leb128(DynBuf *s, uint32_t v)\n{\n    uint32_t a;\n    for(;;) {\n        a = v & 0x7f;\n        v >>= 7;\n        if (v != 0) {\n            dbuf_putc(s, a | 0x80);\n        } else {\n            dbuf_putc(s, a);\n            break;\n        }\n    }\n}\n\nstatic void dbuf_put_sleb128(DynBuf *s, int32_t v1)\n{\n    uint32_t v = v1;\n    dbuf_put_leb128(s, (2 * v) ^ -(v >> 31));\n}\n\nstatic int get_leb128(uint32_t *pval, const uint8_t *buf,\n                      const uint8_t *buf_end)\n{\n    const uint8_t *ptr = buf;\n    uint32_t v, a, i;\n    v = 0;\n    for(i = 0; i < 5; i++) {\n        if (unlikely(ptr >= buf_end))\n            break;\n        a = *ptr++;\n        v |= (a & 0x7f) << (i * 7);\n        if (!(a & 0x80)) {\n            *pval = v;\n            return ptr - buf;\n        }\n    }\n    *pval = 0;\n    return -1;\n}\n\nstatic int get_sleb128(int32_t *pval, const uint8_t *buf,\n                       const uint8_t *buf_end)\n{\n    int ret;\n    uint32_t val;\n    ret = get_leb128(&val, buf, buf_end);\n    if (ret < 0) {\n        *pval = 0;\n        return -1;\n    }\n    *pval = (val >> 1) ^ -(val & 1);\n    return ret;\n}\n\nstatic int find_line_num(JSContext *ctx, JSFunctionBytecode *b,\n                         uint32_t pc_value)\n{\n    const uint8_t *p_end, *p;\n    int new_line_num, line_num, pc, v, ret;\n    unsigned int op;\n\n    if (!b->has_debug || !b->debug.pc2line_buf) {\n        /* function was stripped */\n        return -1;\n    }\n\n    p = b->debug.pc2line_buf;\n    p_end = p + b->debug.pc2line_len;\n    pc = 0;\n    line_num = b->debug.line_num;\n    while (p < p_end) {\n        op = *p++;\n        if (op == 0) {\n            uint32_t val;\n            ret = get_leb128(&val, p, p_end);\n            if (ret < 0)\n                goto fail;\n            pc += val;\n            p += ret;\n            ret = get_sleb128(&v, p, p_end);\n            if (ret < 0) {\n            fail:\n                /* should never happen */\n                return b->debug.line_num;\n            }\n            p += ret;\n            new_line_num = line_num + v;\n        } else {\n            op -= PC2LINE_OP_FIRST;\n            pc += (op / PC2LINE_RANGE);\n            new_line_num = line_num + (op % PC2LINE_RANGE) + PC2LINE_BASE;\n        }\n        if (pc_value < pc)\n            return line_num;\n        line_num = new_line_num;\n    }\n    return line_num;\n}\n\n/* in order to avoid executing arbitrary code during the stack trace\n   generation, we only look at simple 'name' properties containing a\n   string. */\nstatic const char *get_func_name(JSContext *ctx, JSValueConst func)\n{\n    JSProperty *pr;\n    JSShapeProperty *prs;\n    JSValueConst val;\n    \n    if (JS_VALUE_GET_TAG(func) != JS_TAG_OBJECT)\n        return NULL;\n    prs = find_own_property(&pr, JS_VALUE_GET_OBJ(func), JS_ATOM_name);\n    if (!prs)\n        return NULL;\n    if ((prs->flags & JS_PROP_TMASK) != JS_PROP_NORMAL)\n        return NULL;\n    val = pr->u.value;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_STRING)\n        return NULL;\n    return JS_ToCString(ctx, val);\n}\n\n#define JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL (1 << 0)\n/* only taken into account if filename is provided */\n#define JS_BACKTRACE_FLAG_SINGLE_LEVEL     (1 << 1)\n\n/* if filename != NULL, an additional level is added with the filename\n   and line number information (used for parse error). */\nstatic void build_backtrace(JSContext *ctx, JSValueConst error_obj,\n                            const char *filename, int line_num,\n                            int backtrace_flags)\n{\n    JSStackFrame *sf;\n    JSValue str;\n    DynBuf dbuf;\n    const char *func_name_str;\n    const char *str1;\n    JSObject *p;\n    BOOL backtrace_barrier;\n    \n    js_dbuf_init(ctx, &dbuf);\n    if (filename) {\n        dbuf_printf(&dbuf, \"    at %s\", filename);\n        if (line_num != -1)\n            dbuf_printf(&dbuf, \":%d\", line_num);\n        dbuf_putc(&dbuf, '\\n');\n        str = JS_NewString(ctx, filename);\n        JS_DefinePropertyValue(ctx, error_obj, JS_ATOM_fileName, str,\n                               JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n        JS_DefinePropertyValue(ctx, error_obj, JS_ATOM_lineNumber, JS_NewInt32(ctx, line_num),\n                               JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n        if (backtrace_flags & JS_BACKTRACE_FLAG_SINGLE_LEVEL)\n            goto done;\n    }\n    for(sf = ctx->rt->current_stack_frame; sf != NULL; sf = sf->prev_frame) {\n        if (backtrace_flags & JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL) {\n            backtrace_flags &= ~JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL;\n            continue;\n        }\n        func_name_str = get_func_name(ctx, sf->cur_func);\n        if (!func_name_str || func_name_str[0] == '\\0')\n            str1 = \"<anonymous>\";\n        else\n            str1 = func_name_str;\n        dbuf_printf(&dbuf, \"    at %s\", str1);\n        JS_FreeCString(ctx, func_name_str);\n\n        p = JS_VALUE_GET_OBJ(sf->cur_func);\n        backtrace_barrier = FALSE;\n        if (js_class_has_bytecode(p->class_id)) {\n            JSFunctionBytecode *b;\n            const char *atom_str;\n            int line_num1;\n\n            b = p->u.func.function_bytecode;\n            backtrace_barrier = b->backtrace_barrier;\n            if (b->has_debug) {\n                line_num1 = find_line_num(ctx, b,\n                                          sf->cur_pc - b->byte_code_buf - 1);\n                atom_str = JS_AtomToCString(ctx, b->debug.filename);\n                dbuf_printf(&dbuf, \" (%s\",\n                            atom_str ? atom_str : \"<null>\");\n                JS_FreeCString(ctx, atom_str);\n                if (line_num1 != -1)\n                    dbuf_printf(&dbuf, \":%d\", line_num1);\n                dbuf_putc(&dbuf, ')');\n            }\n        } else {\n            dbuf_printf(&dbuf, \" (native)\");\n        }\n        dbuf_putc(&dbuf, '\\n');\n        /* stop backtrace if JS_EVAL_FLAG_BACKTRACE_BARRIER was used */\n        if (backtrace_barrier)\n            break;\n    }\n done:\n    dbuf_putc(&dbuf, '\\0');\n    if (dbuf_error(&dbuf))\n        str = JS_NULL;\n    else\n        str = JS_NewString(ctx, (char *)dbuf.buf);\n    dbuf_free(&dbuf);\n    JS_DefinePropertyValue(ctx, error_obj, JS_ATOM_stack, str,\n                           JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n}\n\n/* Note: it is important that no exception is returned by this function */\nstatic BOOL is_backtrace_needed(JSContext *ctx, JSValueConst obj)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(obj);\n    if (p->class_id != JS_CLASS_ERROR)\n        return FALSE;\n    if (find_own_property1(p, JS_ATOM_stack))\n        return FALSE;\n    return TRUE;\n}\n\nJSValue JS_NewError(JSContext *ctx)\n{\n    return JS_NewObjectClass(ctx, JS_CLASS_ERROR);\n}\n\nstatic JSValue JS_ThrowError2(JSContext *ctx, JSErrorEnum error_num,\n                              const char *fmt, va_list ap, BOOL add_backtrace)\n{\n    char buf[256];\n    JSValue obj, ret;\n\n    vsnprintf(buf, sizeof(buf), fmt, ap);\n    obj = JS_NewObjectProtoClass(ctx, ctx->native_error_proto[error_num],\n                                 JS_CLASS_ERROR);\n    if (unlikely(JS_IsException(obj))) {\n        /* out of memory: throw JS_NULL to avoid recursing */\n        obj = JS_NULL;\n    } else {\n        JS_DefinePropertyValue(ctx, obj, JS_ATOM_message,\n                               JS_NewString(ctx, buf),\n                               JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    }\n    if (add_backtrace) {\n        build_backtrace(ctx, obj, NULL, 0, 0);\n    }\n    ret = JS_Throw(ctx, obj);\n    return ret;\n}\n\nstatic JSValue JS_ThrowError(JSContext *ctx, JSErrorEnum error_num,\n                             const char *fmt, va_list ap)\n{\n    JSRuntime *rt = ctx->rt;\n    JSStackFrame *sf;\n    BOOL add_backtrace;\n\n    /* the backtrace is added later if called from a bytecode function */\n    sf = rt->current_stack_frame;\n    add_backtrace = !rt->in_out_of_memory &&\n        (!sf || (JS_GetFunctionBytecode(sf->cur_func) == NULL));\n    return JS_ThrowError2(ctx, error_num, fmt, ap, add_backtrace);\n}\n\nJSValue __attribute__((format(printf, 2, 3))) JS_ThrowSyntaxError(JSContext *ctx, const char *fmt, ...)\n{\n    JSValue val;\n    va_list ap;\n\n    va_start(ap, fmt);\n    val = JS_ThrowError(ctx, JS_SYNTAX_ERROR, fmt, ap);\n    va_end(ap);\n    return val;\n}\n\nJSValue __attribute__((format(printf, 2, 3))) JS_ThrowTypeError(JSContext *ctx, const char *fmt, ...)\n{\n    JSValue val;\n    va_list ap;\n\n    va_start(ap, fmt);\n    val = JS_ThrowError(ctx, JS_TYPE_ERROR, fmt, ap);\n    va_end(ap);\n    return val;\n}\n\nstatic int __attribute__((format(printf, 3, 4))) JS_ThrowTypeErrorOrFalse(JSContext *ctx, int flags, const char *fmt, ...)\n{\n    va_list ap;\n\n    if ((flags & JS_PROP_THROW) ||\n        ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) {\n        va_start(ap, fmt);\n        JS_ThrowError(ctx, JS_TYPE_ERROR, fmt, ap);\n        va_end(ap);\n        return -1;\n    } else {\n        return FALSE;\n    }\n}\n\n/* never use it directly */\nstatic JSValue __attribute__((format(printf, 3, 4))) __JS_ThrowTypeErrorAtom(JSContext *ctx, JSAtom atom, const char *fmt, ...)\n{\n    char buf[ATOM_GET_STR_BUF_SIZE];\n    return JS_ThrowTypeError(ctx, fmt,\n                             JS_AtomGetStr(ctx, buf, sizeof(buf), atom));\n}\n\n/* never use it directly */\nstatic JSValue __attribute__((format(printf, 3, 4))) __JS_ThrowSyntaxErrorAtom(JSContext *ctx, JSAtom atom, const char *fmt, ...)\n{\n    char buf[ATOM_GET_STR_BUF_SIZE];\n    return JS_ThrowSyntaxError(ctx, fmt,\n                             JS_AtomGetStr(ctx, buf, sizeof(buf), atom));\n}\n\n/* %s is replaced by 'atom'. The macro is used so that gcc can check\n    the format string. */\n#define JS_ThrowTypeErrorAtom(ctx, fmt, atom) __JS_ThrowTypeErrorAtom(ctx, atom, fmt, \"\")\n#define JS_ThrowSyntaxErrorAtom(ctx, fmt, atom) __JS_ThrowSyntaxErrorAtom(ctx, atom, fmt, \"\")\n\nstatic int JS_ThrowTypeErrorReadOnly(JSContext *ctx, int flags, JSAtom atom)\n{\n    if ((flags & JS_PROP_THROW) ||\n        ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) {\n        JS_ThrowTypeErrorAtom(ctx, \"'%s' is read-only\", atom);\n        return -1;\n    } else {\n        return FALSE;\n    }\n}\n\nJSValue __attribute__((format(printf, 2, 3))) JS_ThrowReferenceError(JSContext *ctx, const char *fmt, ...)\n{\n    JSValue val;\n    va_list ap;\n\n    va_start(ap, fmt);\n    val = JS_ThrowError(ctx, JS_REFERENCE_ERROR, fmt, ap);\n    va_end(ap);\n    return val;\n}\n\nJSValue __attribute__((format(printf, 2, 3))) JS_ThrowRangeError(JSContext *ctx, const char *fmt, ...)\n{\n    JSValue val;\n    va_list ap;\n\n    va_start(ap, fmt);\n    val = JS_ThrowError(ctx, JS_RANGE_ERROR, fmt, ap);\n    va_end(ap);\n    return val;\n}\n\nJSValue __attribute__((format(printf, 2, 3))) JS_ThrowInternalError(JSContext *ctx, const char *fmt, ...)\n{\n    JSValue val;\n    va_list ap;\n\n    va_start(ap, fmt);\n    val = JS_ThrowError(ctx, JS_INTERNAL_ERROR, fmt, ap);\n    va_end(ap);\n    return val;\n}\n\nJSValue JS_ThrowOutOfMemory(JSContext *ctx)\n{\n    JSRuntime *rt = ctx->rt;\n    if (!rt->in_out_of_memory) {\n        rt->in_out_of_memory = TRUE;\n        JS_ThrowInternalError(ctx, \"out of memory\");\n        rt->in_out_of_memory = FALSE;\n    }\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ThrowStackOverflow(JSContext *ctx)\n{\n    return JS_ThrowInternalError(ctx, \"stack overflow\");\n}\n\nstatic JSValue JS_ThrowTypeErrorNotAnObject(JSContext *ctx)\n{\n    return JS_ThrowTypeError(ctx, \"not an object\");\n}\n\nstatic JSValue JS_ThrowTypeErrorNotASymbol(JSContext *ctx)\n{\n    return JS_ThrowTypeError(ctx, \"not a symbol\");\n}\n\nstatic JSValue JS_ThrowReferenceErrorNotDefined(JSContext *ctx, JSAtom name)\n{\n    char buf[ATOM_GET_STR_BUF_SIZE];\n    return JS_ThrowReferenceError(ctx, \"'%s' is not defined\",\n                                  JS_AtomGetStr(ctx, buf, sizeof(buf), name));\n}\n\nstatic JSValue JS_ThrowReferenceErrorUninitialized(JSContext *ctx, JSAtom name)\n{\n    char buf[ATOM_GET_STR_BUF_SIZE];\n    return JS_ThrowReferenceError(ctx, \"%s is not initialized\",\n                                  name == JS_ATOM_NULL ? \"lexical variable\" :\n                                  JS_AtomGetStr(ctx, buf, sizeof(buf), name));\n}\n\nstatic JSValue JS_ThrowReferenceErrorUninitialized2(JSContext *ctx,\n                                                    JSFunctionBytecode *b,\n                                                    int idx, BOOL is_ref)\n{\n    JSAtom atom = JS_ATOM_NULL;\n    if (is_ref) {\n        atom = b->closure_var[idx].var_name;\n    } else {\n        /* not present if the function is stripped and contains no eval() */\n        if (b->vardefs)\n            atom = b->vardefs[b->arg_count + idx].var_name;\n    }\n    return JS_ThrowReferenceErrorUninitialized(ctx, atom);\n}\n\nstatic JSValue JS_ThrowTypeErrorInvalidClass(JSContext *ctx, int class_id)\n{\n    JSRuntime *rt = ctx->rt;\n    JSAtom name;\n    name = rt->class_array[class_id].class_name;\n    return JS_ThrowTypeErrorAtom(ctx, \"%s object expected\", name);\n}\n\nstatic no_inline __exception int __js_poll_interrupts(JSContext *ctx)\n{\n    JSRuntime *rt = ctx->rt;\n    ctx->interrupt_counter = JS_INTERRUPT_COUNTER_INIT;\n    if (rt->interrupt_handler) {\n        if (rt->interrupt_handler(rt, rt->interrupt_opaque)) {\n            /* XXX: should set a specific flag to avoid catching */\n            JS_ThrowInternalError(ctx, \"interrupted\");\n            JS_SetUncatchableError(ctx, ctx->rt->current_exception, TRUE);\n            return -1;\n        }\n    }\n    return 0;\n}\n\nstatic inline __exception int js_poll_interrupts(JSContext *ctx)\n{\n    if (unlikely(--ctx->interrupt_counter <= 0)) {\n        return __js_poll_interrupts(ctx);\n    } else {\n        return 0;\n    }\n}\n\n/* return -1 (exception) or TRUE/FALSE */\nstatic int JS_SetPrototypeInternal(JSContext *ctx, JSValueConst obj,\n                                   JSValueConst proto_val,\n                                   BOOL throw_flag)\n{\n    JSObject *proto, *p, *p1;\n    JSShape *sh;\n\n    if (throw_flag) {\n        if (JS_VALUE_GET_TAG(obj) == JS_TAG_NULL ||\n            JS_VALUE_GET_TAG(obj) == JS_TAG_UNDEFINED)\n            goto not_obj;\n    } else {\n        if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n            goto not_obj;\n    }\n    p = JS_VALUE_GET_OBJ(obj);\n    if (JS_VALUE_GET_TAG(proto_val) != JS_TAG_OBJECT) {\n        if (JS_VALUE_GET_TAG(proto_val) != JS_TAG_NULL) {\n        not_obj:\n            JS_ThrowTypeErrorNotAnObject(ctx);\n            return -1;\n        }\n        proto = NULL;\n    } else {\n        proto = JS_VALUE_GET_OBJ(proto_val);\n    }\n\n    if (throw_flag && JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return TRUE;\n\n    if (unlikely(p->class_id == JS_CLASS_PROXY))\n        return js_proxy_setPrototypeOf(ctx, obj, proto_val, throw_flag);\n    sh = p->shape;\n    if (sh->proto == proto)\n        return TRUE;\n    if (!p->extensible) {\n        if (throw_flag) {\n            JS_ThrowTypeError(ctx, \"object is not extensible\");\n            return -1;\n        } else {\n            return FALSE;\n        }\n    }\n    if (proto) {\n        /* check if there is a cycle */\n        p1 = proto;\n        do {\n            if (p1 == p) {\n                if (throw_flag) {\n                    JS_ThrowTypeError(ctx, \"circular prototype chain\");\n                    return -1;\n                } else {\n                    return FALSE;\n                }\n            }\n            /* Note: for Proxy objects, proto is NULL */\n            p1 = p1->shape->proto;\n        } while (p1 != NULL);\n        JS_DupValue(ctx, proto_val);\n    }\n\n    if (js_shape_prepare_update(ctx, p, NULL))\n        return -1;\n    sh = p->shape;\n    if (sh->proto)\n        JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, sh->proto));\n    sh->proto = proto;\n    return TRUE;\n}\n\n/* return -1 (exception) or TRUE/FALSE */\nint JS_SetPrototype(JSContext *ctx, JSValueConst obj, JSValueConst proto_val)\n{\n    return JS_SetPrototypeInternal(ctx, obj, proto_val, TRUE);\n}\n\n/* Only works for primitive types, otherwise return JS_NULL. */\nstatic JSValueConst JS_GetPrototypePrimitive(JSContext *ctx, JSValueConst val)\n{\n    switch(JS_VALUE_GET_NORM_TAG(val)) {\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n        val = ctx->class_proto[JS_CLASS_BIG_INT];\n        break;\n    case JS_TAG_BIG_FLOAT:\n        val = ctx->class_proto[JS_CLASS_BIG_FLOAT];\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        val = ctx->class_proto[JS_CLASS_BIG_DECIMAL];\n        break;\n#endif\n    case JS_TAG_INT:\n    case JS_TAG_FLOAT64:\n        val = ctx->class_proto[JS_CLASS_NUMBER];\n        break;\n    case JS_TAG_BOOL:\n        val = ctx->class_proto[JS_CLASS_BOOLEAN];\n        break;\n    case JS_TAG_STRING:\n        val = ctx->class_proto[JS_CLASS_STRING];\n        break;\n    case JS_TAG_SYMBOL:\n        val = ctx->class_proto[JS_CLASS_SYMBOL];\n        break;\n    case JS_TAG_OBJECT:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n    default:\n        val = JS_NULL;\n        break;\n    }\n    return val;\n}\n\n/* Return an Object, JS_NULL or JS_EXCEPTION in case of Proxy object. */\nJSValue JS_GetPrototype(JSContext *ctx, JSValueConst obj)\n{\n    JSValue val;\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        JSObject *p;\n        p = JS_VALUE_GET_OBJ(obj);\n        if (unlikely(p->class_id == JS_CLASS_PROXY)) {\n            val = js_proxy_getPrototypeOf(ctx, obj);\n        } else {\n            p = p->shape->proto;\n            if (!p)\n                val = JS_NULL;\n            else\n                val = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n        }\n    } else {\n        val = JS_DupValue(ctx, JS_GetPrototypePrimitive(ctx, obj));\n    }\n    return val;\n}\n\nstatic JSValue JS_GetPrototypeFree(JSContext *ctx, JSValue obj)\n{\n    JSValue obj1;\n    obj1 = JS_GetPrototype(ctx, obj);\n    JS_FreeValue(ctx, obj);\n    return obj1;\n}\n\n/* return TRUE, FALSE or (-1) in case of exception */\nstatic int JS_OrdinaryIsInstanceOf(JSContext *ctx, JSValueConst val,\n                                   JSValueConst obj)\n{\n    JSValue obj_proto;\n    JSObject *proto;\n    const JSObject *p, *proto1;\n    BOOL ret;\n\n    if (!JS_IsFunction(ctx, obj))\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(obj);\n    if (p->class_id == JS_CLASS_BOUND_FUNCTION) {\n        JSBoundFunction *s = p->u.bound_function;\n        return JS_IsInstanceOf(ctx, val, s->func_obj);\n    }\n\n    /* Only explicitly boxed values are instances of constructors */\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return FALSE;\n    obj_proto = JS_GetProperty(ctx, obj, JS_ATOM_prototype);\n    if (JS_VALUE_GET_TAG(obj_proto) != JS_TAG_OBJECT) {\n        if (!JS_IsException(obj_proto))\n            JS_ThrowTypeError(ctx, \"operand 'prototype' property is not an object\");\n        ret = -1;\n        goto done;\n    }\n    proto = JS_VALUE_GET_OBJ(obj_proto);\n    p = JS_VALUE_GET_OBJ(val);\n    for(;;) {\n        proto1 = p->shape->proto;\n        if (!proto1) {\n            /* slow case if proxy in the prototype chain */\n            if (unlikely(p->class_id == JS_CLASS_PROXY)) {\n                JSValue obj1;\n                obj1 = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, (JSObject *)p));\n                for(;;) {\n                    obj1 = JS_GetPrototypeFree(ctx, obj1);\n                    if (JS_IsException(obj1)) {\n                        ret = -1;\n                        break;\n                    }\n                    if (JS_IsNull(obj1)) {\n                        ret = FALSE;\n                        break;\n                    }\n                    if (proto == JS_VALUE_GET_OBJ(obj1)) {\n                        JS_FreeValue(ctx, obj1);\n                        ret = TRUE;\n                        break;\n                    }\n                    /* must check for timeout to avoid infinite loop */\n                    if (js_poll_interrupts(ctx)) {\n                        JS_FreeValue(ctx, obj1);\n                        ret = -1;\n                        break;\n                    }\n                }\n            } else {\n                ret = FALSE;\n            }\n            break;\n        }\n        p = proto1;\n        if (proto == p) {\n            ret = TRUE;\n            break;\n        }\n    }\ndone:\n    JS_FreeValue(ctx, obj_proto);\n    return ret;\n}\n\n/* return TRUE, FALSE or (-1) in case of exception */\nint JS_IsInstanceOf(JSContext *ctx, JSValueConst val, JSValueConst obj)\n{\n    JSValue method;\n\n    if (!JS_IsObject(obj))\n        goto fail;\n    method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_hasInstance);\n    if (JS_IsException(method))\n        return -1;\n    if (!JS_IsNull(method) && !JS_IsUndefined(method)) {\n        JSValue ret;\n        ret = JS_CallFree(ctx, method, obj, 1, &val);\n        return JS_ToBoolFree(ctx, ret);\n    }\n\n    /* legacy case */\n    if (!JS_IsFunction(ctx, obj)) {\n    fail:\n        JS_ThrowTypeError(ctx, \"invalid 'instanceof' right operand\");\n        return -1;\n    }\n    return JS_OrdinaryIsInstanceOf(ctx, val, obj);\n}\n\n/* return the value associated to the autoinit property or an exception */\ntypedef JSValue JSAutoInitFunc(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque);\n\nstatic JSAutoInitFunc *js_autoinit_func_table[] = {\n    js_instantiate_prototype, /* JS_AUTOINIT_ID_PROTOTYPE */\n    js_module_ns_autoinit, /* JS_AUTOINIT_ID_MODULE_NS */\n    JS_InstantiateFunctionListItem2, /* JS_AUTOINIT_ID_PROP */\n};\n\n/* warning: 'prs' is reallocated after it */\nstatic int JS_AutoInitProperty(JSContext *ctx, JSObject *p, JSAtom prop,\n                               JSProperty *pr, JSShapeProperty *prs)\n{\n    JSValue val;\n    JSContext *realm;\n    JSAutoInitFunc *func;\n\n    if (js_shape_prepare_update(ctx, p, &prs))\n        return -1;\n\n    realm = js_autoinit_get_realm(pr);\n    func = js_autoinit_func_table[js_autoinit_get_id(pr)];\n    /* 'func' shall not modify the object properties 'pr' */\n    val = func(realm, p, prop, pr->u.init.opaque);\n    js_autoinit_free(ctx->rt, pr);\n    prs->flags &= ~JS_PROP_TMASK;\n    pr->u.value = JS_UNDEFINED;\n    if (JS_IsException(val))\n        return -1;\n    pr->u.value = val;\n    return 0;\n}\n\nJSValue JS_GetPropertyInternal(JSContext *ctx, JSValueConst obj,\n                               JSAtom prop, JSValueConst this_obj,\n                               BOOL throw_ref_error)\n{\n    JSObject *p;\n    JSProperty *pr;\n    JSShapeProperty *prs;\n    uint32_t tag;\n\n    tag = JS_VALUE_GET_TAG(obj);\n    if (unlikely(tag != JS_TAG_OBJECT)) {\n        switch(tag) {\n        case JS_TAG_NULL:\n            return JS_ThrowTypeErrorAtom(ctx, \"cannot read property '%s' of null\", prop);\n        case JS_TAG_UNDEFINED:\n            return JS_ThrowTypeErrorAtom(ctx, \"cannot read property '%s' of undefined\", prop);\n        case JS_TAG_EXCEPTION:\n            return JS_EXCEPTION;\n        case JS_TAG_STRING:\n            {\n                JSString *p1 = JS_VALUE_GET_STRING(obj);\n                if (__JS_AtomIsTaggedInt(prop)) {\n                    uint32_t idx, ch;\n                    idx = __JS_AtomToUInt32(prop);\n                    if (idx < p1->len) {\n                        if (p1->is_wide_char)\n                            ch = p1->u.str16[idx];\n                        else\n                            ch = p1->u.str8[idx];\n                        return js_new_string_char(ctx, ch);\n                    }\n                } else if (prop == JS_ATOM_length) {\n                    return JS_NewInt32(ctx, p1->len);\n                }\n            }\n            break;\n        default:\n            break;\n        }\n        /* cannot raise an exception */\n        p = JS_VALUE_GET_OBJ(JS_GetPrototypePrimitive(ctx, obj));\n        if (!p)\n            return JS_UNDEFINED;\n    } else {\n        p = JS_VALUE_GET_OBJ(obj);\n    }\n\n    for(;;) {\n        prs = find_own_property(&pr, p, prop);\n        if (prs) {\n            /* found */\n            if (unlikely(prs->flags & JS_PROP_TMASK)) {\n                if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {\n                    if (unlikely(!pr->u.getset.getter)) {\n                        return JS_UNDEFINED;\n                    } else {\n                        JSValue func = JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter);\n                        /* Note: the field could be removed in the getter */\n                        func = JS_DupValue(ctx, func);\n                        return JS_CallFree(ctx, func, this_obj, 0, NULL);\n                    }\n                } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n                    JSValue val = *pr->u.var_ref->pvalue;\n                    if (unlikely(JS_IsUninitialized(val)))\n                        return JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);\n                    return JS_DupValue(ctx, val);\n                } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n                    /* Instantiate property and retry */\n                    if (JS_AutoInitProperty(ctx, p, prop, pr, prs))\n                        return JS_EXCEPTION;\n                    continue;\n                }\n            } else {\n                return JS_DupValue(ctx, pr->u.value);\n            }\n        }\n        if (unlikely(p->is_exotic)) {\n            /* exotic behaviors */\n            if (p->fast_array) {\n                if (__JS_AtomIsTaggedInt(prop)) {\n                    uint32_t idx = __JS_AtomToUInt32(prop);\n                    if (idx < p->u.array.count) {\n                        /* we avoid duplicating the code */\n                        return JS_GetPropertyUint32(ctx, JS_MKPTR(JS_TAG_OBJECT, p), idx);\n                    } else if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n                               p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n                        return JS_UNDEFINED;\n                    }\n                } else if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n                           p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n                    int ret;\n                    ret = JS_AtomIsNumericIndex(ctx, prop);\n                    if (ret != 0) {\n                        if (ret < 0)\n                            return JS_EXCEPTION;\n                        return JS_UNDEFINED;\n                    }\n                }\n            } else {\n                const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;\n                if (em) {\n                    if (em->get_property) {\n                        JSValue obj1, retval;\n                        /* XXX: should pass throw_ref_error */\n                        /* Note: if 'p' is a prototype, it can be\n                           freed in the called function */\n                        obj1 = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n                        retval = em->get_property(ctx, obj1, prop, this_obj);\n                        JS_FreeValue(ctx, obj1);\n                        return retval;\n                    }\n                    if (em->get_own_property) {\n                        JSPropertyDescriptor desc;\n                        int ret;\n                        JSValue obj1;\n\n                        /* Note: if 'p' is a prototype, it can be\n                           freed in the called function */\n                        obj1 = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n                        ret = em->get_own_property(ctx, &desc, obj1, prop);\n                        JS_FreeValue(ctx, obj1);\n                        if (ret < 0)\n                            return JS_EXCEPTION;\n                        if (ret) {\n                            if (desc.flags & JS_PROP_GETSET) {\n                                JS_FreeValue(ctx, desc.setter);\n                                return JS_CallFree(ctx, desc.getter, this_obj, 0, NULL);\n                            } else {\n                                return desc.value;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        p = p->shape->proto;\n        if (!p)\n            break;\n    }\n    if (unlikely(throw_ref_error)) {\n        return JS_ThrowReferenceErrorNotDefined(ctx, prop);\n    } else {\n        return JS_UNDEFINED;\n    }\n}\n\nstatic JSValue JS_ThrowTypeErrorPrivateNotFound(JSContext *ctx, JSAtom atom)\n{\n    return JS_ThrowTypeErrorAtom(ctx, \"private class field '%s' does not exist\",\n                                 atom);\n}\n\n/* Private fields can be added even on non extensible objects or\n   Proxies */\nstatic int JS_DefinePrivateField(JSContext *ctx, JSValueConst obj,\n                                 JSValueConst name, JSValue val)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    JSAtom prop;\n\n    if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        goto fail;\n    }\n    /* safety check */\n    if (unlikely(JS_VALUE_GET_TAG(name) != JS_TAG_SYMBOL)) {\n        JS_ThrowTypeErrorNotASymbol(ctx);\n        goto fail;\n    }\n    prop = js_symbol_to_atom(ctx, name);\n    p = JS_VALUE_GET_OBJ(obj);\n    prs = find_own_property(&pr, p, prop);\n    if (prs) {\n        JS_ThrowTypeErrorAtom(ctx, \"private class field '%s' already exists\",\n                              prop);\n        goto fail;\n    }\n    pr = add_property(ctx, p, prop, JS_PROP_C_W_E);\n    if (unlikely(!pr)) {\n    fail:\n        JS_FreeValue(ctx, val);\n        return -1;\n    }\n    pr->u.value = val;\n    return 0;\n}\n\nstatic JSValue JS_GetPrivateField(JSContext *ctx, JSValueConst obj,\n                                  JSValueConst name)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    JSAtom prop;\n\n    if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    /* safety check */\n    if (unlikely(JS_VALUE_GET_TAG(name) != JS_TAG_SYMBOL))\n        return JS_ThrowTypeErrorNotASymbol(ctx);\n    prop = js_symbol_to_atom(ctx, name);\n    p = JS_VALUE_GET_OBJ(obj);\n    prs = find_own_property(&pr, p, prop);\n    if (!prs) {\n        JS_ThrowTypeErrorPrivateNotFound(ctx, prop);\n        return JS_EXCEPTION;\n    }\n    return JS_DupValue(ctx, pr->u.value);\n}\n\nstatic int JS_SetPrivateField(JSContext *ctx, JSValueConst obj,\n                              JSValueConst name, JSValue val)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    JSAtom prop;\n\n    if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        goto fail;\n    }\n    /* safety check */\n    if (unlikely(JS_VALUE_GET_TAG(name) != JS_TAG_SYMBOL)) {\n        JS_ThrowTypeErrorNotASymbol(ctx);\n        goto fail;\n    }\n    prop = js_symbol_to_atom(ctx, name);\n    p = JS_VALUE_GET_OBJ(obj);\n    prs = find_own_property(&pr, p, prop);\n    if (!prs) {\n        JS_ThrowTypeErrorPrivateNotFound(ctx, prop);\n    fail:\n        JS_FreeValue(ctx, val);\n        return -1;\n    }\n    set_value(ctx, &pr->u.value, val);\n    return 0;\n}\n\nstatic int JS_AddBrand(JSContext *ctx, JSValueConst obj, JSValueConst home_obj)\n{\n    JSObject *p, *p1;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    JSValue brand;\n    JSAtom brand_atom;\n    \n    if (unlikely(JS_VALUE_GET_TAG(home_obj) != JS_TAG_OBJECT)) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        return -1;\n    }\n    p = JS_VALUE_GET_OBJ(home_obj);\n    prs = find_own_property(&pr, p, JS_ATOM_Private_brand);\n    if (!prs) {\n        brand = JS_NewSymbolFromAtom(ctx, JS_ATOM_brand, JS_ATOM_TYPE_PRIVATE);\n        if (JS_IsException(brand))\n            return -1;\n        /* if the brand is not present, add it */\n        pr = add_property(ctx, p, JS_ATOM_Private_brand, JS_PROP_C_W_E);\n        if (!pr) {\n            JS_FreeValue(ctx, brand);\n            return -1;\n        }\n        pr->u.value = JS_DupValue(ctx, brand);\n    } else {\n        brand = JS_DupValue(ctx, pr->u.value);\n    }\n    brand_atom = js_symbol_to_atom(ctx, brand);\n    \n    if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        JS_FreeAtom(ctx, brand_atom);\n        return -1;\n    }\n    p1 = JS_VALUE_GET_OBJ(obj);\n    pr = add_property(ctx, p1, brand_atom, JS_PROP_C_W_E);\n    JS_FreeAtom(ctx, brand_atom);\n    if (!pr)\n        return -1;\n    pr->u.value = JS_UNDEFINED;\n    return 0;\n}\n\nstatic int JS_CheckBrand(JSContext *ctx, JSValueConst obj, JSValueConst func)\n{\n    JSObject *p, *p1, *home_obj;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    JSValueConst brand;\n    \n    /* get the home object of 'func' */\n    if (unlikely(JS_VALUE_GET_TAG(func) != JS_TAG_OBJECT)) {\n    not_obj:\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        return -1;\n    }\n    p1 = JS_VALUE_GET_OBJ(func);\n    if (!js_class_has_bytecode(p1->class_id))\n        goto not_obj;\n    home_obj = p1->u.func.home_object;\n    if (!home_obj)\n        goto not_obj;\n    prs = find_own_property(&pr, home_obj, JS_ATOM_Private_brand);\n    if (!prs) {\n        JS_ThrowTypeError(ctx, \"expecting <brand> private field\");\n        return -1;\n    }\n    brand = pr->u.value;\n    /* safety check */\n    if (unlikely(JS_VALUE_GET_TAG(brand) != JS_TAG_SYMBOL))\n        goto not_obj;\n    \n    /* get the brand array of 'obj' */\n    if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT))\n        goto not_obj;\n    p = JS_VALUE_GET_OBJ(obj);\n    prs = find_own_property(&pr, p, js_symbol_to_atom(ctx, brand));\n    if (!prs) {\n        JS_ThrowTypeError(ctx, \"invalid brand on object\");\n        return -1;\n    }\n    return 0;\n}\n\nstatic uint32_t js_string_obj_get_length(JSContext *ctx,\n                                         JSValueConst obj)\n{\n    JSObject *p;\n    JSString *p1;\n    uint32_t len = 0;\n\n    /* This is a class exotic method: obj class_id is JS_CLASS_STRING */\n    p = JS_VALUE_GET_OBJ(obj);\n    if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_STRING) {\n        p1 = JS_VALUE_GET_STRING(p->u.object_data);\n        len = p1->len;\n    }\n    return len;\n}\n\nstatic int num_keys_cmp(const void *p1, const void *p2, void *opaque)\n{\n    JSContext *ctx = opaque;\n    JSAtom atom1 = ((const JSPropertyEnum *)p1)->atom;\n    JSAtom atom2 = ((const JSPropertyEnum *)p2)->atom;\n    uint32_t v1, v2;\n    BOOL atom1_is_integer, atom2_is_integer;\n\n    atom1_is_integer = JS_AtomIsArrayIndex(ctx, &v1, atom1);\n    atom2_is_integer = JS_AtomIsArrayIndex(ctx, &v2, atom2);\n    assert(atom1_is_integer && atom2_is_integer);\n    if (v1 < v2)\n        return -1;\n    else if (v1 == v2)\n        return 0;\n    else\n        return 1;\n}\n\nstatic void js_free_prop_enum(JSContext *ctx, JSPropertyEnum *tab, uint32_t len)\n{\n    uint32_t i;\n    if (tab) {\n        for(i = 0; i < len; i++)\n            JS_FreeAtom(ctx, tab[i].atom);\n        js_free(ctx, tab);\n    }\n}\n\n/* return < 0 in case if exception, 0 if OK. ptab and its atoms must\n   be freed by the user. */\nstatic int __exception JS_GetOwnPropertyNamesInternal(JSContext *ctx,\n                                                      JSPropertyEnum **ptab,\n                                                      uint32_t *plen,\n                                                      JSObject *p, int flags)\n{\n    int i, j;\n    JSShape *sh;\n    JSShapeProperty *prs;\n    JSPropertyEnum *tab_atom, *tab_exotic;\n    JSAtom atom;\n    uint32_t num_keys_count, str_keys_count, sym_keys_count, atom_count;\n    uint32_t num_index, str_index, sym_index, exotic_count, exotic_keys_count;\n    BOOL is_enumerable, num_sorted;\n    uint32_t num_key;\n    JSAtomKindEnum kind;\n    \n    /* clear pointer for consistency in case of failure */\n    *ptab = NULL;\n    *plen = 0;\n\n    /* compute the number of returned properties */\n    num_keys_count = 0;\n    str_keys_count = 0;\n    sym_keys_count = 0;\n    exotic_keys_count = 0;\n    exotic_count = 0;\n    tab_exotic = NULL;\n    sh = p->shape;\n    for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) {\n        atom = prs->atom;\n        if (atom != JS_ATOM_NULL) {\n            is_enumerable = ((prs->flags & JS_PROP_ENUMERABLE) != 0);\n            kind = JS_AtomGetKind(ctx, atom);\n            if ((!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) &&\n                ((flags >> kind) & 1) != 0) {\n                /* need to raise an exception in case of the module\n                   name space (implicit GetOwnProperty) */\n                if (unlikely((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) &&\n                    (flags & (JS_GPN_SET_ENUM | JS_GPN_ENUM_ONLY))) {\n                    JSVarRef *var_ref = p->prop[i].u.var_ref;\n                    if (unlikely(JS_IsUninitialized(*var_ref->pvalue))) {\n                        JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);\n                        return -1;\n                    }\n                }\n                if (JS_AtomIsArrayIndex(ctx, &num_key, atom)) {\n                    num_keys_count++;\n                } else if (kind == JS_ATOM_KIND_STRING) {\n                    str_keys_count++;\n                } else {\n                    sym_keys_count++;\n                }\n            }\n        }\n    }\n\n    if (p->is_exotic) {\n        if (p->fast_array) {\n            if (flags & JS_GPN_STRING_MASK) {\n                num_keys_count += p->u.array.count;\n            }\n        } else if (p->class_id == JS_CLASS_STRING) {\n            if (flags & JS_GPN_STRING_MASK) {\n                num_keys_count += js_string_obj_get_length(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n            }\n        } else {\n            const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;\n            if (em && em->get_own_property_names) {\n                if (em->get_own_property_names(ctx, &tab_exotic, &exotic_count,\n                                               JS_MKPTR(JS_TAG_OBJECT, p)))\n                    return -1;\n                for(i = 0; i < exotic_count; i++) {\n                    atom = tab_exotic[i].atom;\n                    kind = JS_AtomGetKind(ctx, atom);\n                    if (((flags >> kind) & 1) != 0) {\n                        is_enumerable = FALSE;\n                        if (flags & (JS_GPN_SET_ENUM | JS_GPN_ENUM_ONLY)) {\n                            JSPropertyDescriptor desc;\n                            int res;\n                            /* set the \"is_enumerable\" field if necessary */\n                            res = JS_GetOwnPropertyInternal(ctx, &desc, p, atom);\n                            if (res < 0) {\n                                js_free_prop_enum(ctx, tab_exotic, exotic_count);\n                                return -1;\n                            }\n                            if (res) {\n                                is_enumerable =\n                                    ((desc.flags & JS_PROP_ENUMERABLE) != 0);\n                                js_free_desc(ctx, &desc);\n                            }\n                            tab_exotic[i].is_enumerable = is_enumerable;\n                        }\n                        if (!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) {\n                            exotic_keys_count++;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    /* fill them */\n\n    atom_count = num_keys_count + str_keys_count + sym_keys_count + exotic_keys_count;\n    /* avoid allocating 0 bytes */\n    tab_atom = js_malloc(ctx, sizeof(tab_atom[0]) * max_int(atom_count, 1));\n    if (!tab_atom) {\n        js_free_prop_enum(ctx, tab_exotic, exotic_count);\n        return -1;\n    }\n\n    num_index = 0;\n    str_index = num_keys_count;\n    sym_index = str_index + str_keys_count;\n\n    num_sorted = TRUE;\n    sh = p->shape;\n    for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) {\n        atom = prs->atom;\n        if (atom != JS_ATOM_NULL) {\n            is_enumerable = ((prs->flags & JS_PROP_ENUMERABLE) != 0);\n            kind = JS_AtomGetKind(ctx, atom);\n            if ((!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) &&\n                ((flags >> kind) & 1) != 0) {\n                if (JS_AtomIsArrayIndex(ctx, &num_key, atom)) {\n                    j = num_index++;\n                    num_sorted = FALSE;\n                } else if (kind == JS_ATOM_KIND_STRING) {\n                    j = str_index++;\n                } else {\n                    j = sym_index++;\n                }\n                tab_atom[j].atom = JS_DupAtom(ctx, atom);\n                tab_atom[j].is_enumerable = is_enumerable;\n            }\n        }\n    }\n\n    if (p->is_exotic) {\n        int len;\n        if (p->fast_array) {\n            if (flags & JS_GPN_STRING_MASK) {\n                len = p->u.array.count;\n                goto add_array_keys;\n            }\n        } else if (p->class_id == JS_CLASS_STRING) {\n            if (flags & JS_GPN_STRING_MASK) {\n                len = js_string_obj_get_length(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n            add_array_keys:\n                for(i = 0; i < len; i++) {\n                    tab_atom[num_index].atom = __JS_AtomFromUInt32(i);\n                    if (tab_atom[num_index].atom == JS_ATOM_NULL) {\n                        js_free_prop_enum(ctx, tab_atom, num_index);\n                        return -1;\n                    }\n                    tab_atom[num_index].is_enumerable = TRUE;\n                    num_index++;\n                }\n            }\n        } else {\n            /* Note: exotic keys are not reordered and comes after the object own properties. */\n            for(i = 0; i < exotic_count; i++) {\n                atom = tab_exotic[i].atom;\n                is_enumerable = tab_exotic[i].is_enumerable;\n                kind = JS_AtomGetKind(ctx, atom);\n                if ((!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) &&\n                    ((flags >> kind) & 1) != 0) {\n                    tab_atom[sym_index].atom = atom;\n                    tab_atom[sym_index].is_enumerable = is_enumerable;\n                    sym_index++;\n                } else {\n                    JS_FreeAtom(ctx, atom);\n                }\n            }\n            js_free(ctx, tab_exotic);\n        }\n    }\n\n    assert(num_index == num_keys_count);\n    assert(str_index == num_keys_count + str_keys_count);\n    assert(sym_index == atom_count);\n\n    if (num_keys_count != 0 && !num_sorted) {\n        rqsort(tab_atom, num_keys_count, sizeof(tab_atom[0]), num_keys_cmp,\n               ctx);\n    }\n    *ptab = tab_atom;\n    *plen = atom_count;\n    return 0;\n}\n\nint JS_GetOwnPropertyNames(JSContext *ctx, JSPropertyEnum **ptab,\n                           uint32_t *plen, JSValueConst obj, int flags)\n{\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        return -1;\n    }\n    return JS_GetOwnPropertyNamesInternal(ctx, ptab, plen,\n                                          JS_VALUE_GET_OBJ(obj), flags);\n}\n\n/* Return -1 if exception,\n   FALSE if the property does not exist, TRUE if it exists. If TRUE is\n   returned, the property descriptor 'desc' is filled present. */\nstatic int JS_GetOwnPropertyInternal(JSContext *ctx, JSPropertyDescriptor *desc,\n                                     JSObject *p, JSAtom prop)\n{\n    JSShapeProperty *prs;\n    JSProperty *pr;\n\nretry:\n    prs = find_own_property(&pr, p, prop);\n    if (prs) {\n        if (desc) {\n            desc->flags = prs->flags & JS_PROP_C_W_E;\n            desc->getter = JS_UNDEFINED;\n            desc->setter = JS_UNDEFINED;\n            desc->value = JS_UNDEFINED;\n            if (unlikely(prs->flags & JS_PROP_TMASK)) {\n                if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {\n                    desc->flags |= JS_PROP_GETSET;\n                    if (pr->u.getset.getter)\n                        desc->getter = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter));\n                    if (pr->u.getset.setter)\n                        desc->setter = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter));\n                } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n                    JSValue val = *pr->u.var_ref->pvalue;\n                    if (unlikely(JS_IsUninitialized(val))) {\n                        JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);\n                        return -1;\n                    }\n                    desc->value = JS_DupValue(ctx, val);\n                } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n                    /* Instantiate property and retry */\n                    if (JS_AutoInitProperty(ctx, p, prop, pr, prs))\n                        return -1;\n                    goto retry;\n                }\n            } else {\n                desc->value = JS_DupValue(ctx, pr->u.value);\n            }\n        } else {\n            /* for consistency, send the exception even if desc is NULL */\n            if (unlikely((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF)) {\n                if (unlikely(JS_IsUninitialized(*pr->u.var_ref->pvalue))) {\n                    JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);\n                    return -1;\n                }\n            } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n                /* nothing to do: delay instantiation until actual value and/or attributes are read */\n            }\n        }\n        return TRUE;\n    }\n    if (p->is_exotic) {\n        if (p->fast_array) {\n            /* specific case for fast arrays */\n            if (__JS_AtomIsTaggedInt(prop)) {\n                uint32_t idx;\n                idx = __JS_AtomToUInt32(prop);\n                if (idx < p->u.array.count) {\n                    if (desc) {\n                        desc->flags = JS_PROP_WRITABLE | JS_PROP_ENUMERABLE |\n                            JS_PROP_CONFIGURABLE;\n                        desc->getter = JS_UNDEFINED;\n                        desc->setter = JS_UNDEFINED;\n                        desc->value = JS_GetPropertyUint32(ctx, JS_MKPTR(JS_TAG_OBJECT, p), idx);\n                    }\n                    return TRUE;\n                }\n            }\n        } else {\n            const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;\n            if (em && em->get_own_property) {\n                return em->get_own_property(ctx, desc,\n                                            JS_MKPTR(JS_TAG_OBJECT, p), prop);\n            }\n        }\n    }\n    return FALSE;\n}\n\nint JS_GetOwnProperty(JSContext *ctx, JSPropertyDescriptor *desc,\n                      JSValueConst obj, JSAtom prop)\n{\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        return -1;\n    }\n    return JS_GetOwnPropertyInternal(ctx, desc, JS_VALUE_GET_OBJ(obj), prop);\n}\n\n/* return -1 if exception (Proxy object only) or TRUE/FALSE */\nint JS_IsExtensible(JSContext *ctx, JSValueConst obj)\n{\n    JSObject *p;\n\n    if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT))\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(obj);\n    if (unlikely(p->class_id == JS_CLASS_PROXY))\n        return js_proxy_isExtensible(ctx, obj);\n    else\n        return p->extensible;\n}\n\n/* return -1 if exception (Proxy object only) or TRUE/FALSE */\nint JS_PreventExtensions(JSContext *ctx, JSValueConst obj)\n{\n    JSObject *p;\n\n    if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT))\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(obj);\n    if (unlikely(p->class_id == JS_CLASS_PROXY))\n        return js_proxy_preventExtensions(ctx, obj);\n    p->extensible = FALSE;\n    return TRUE;\n}\n\n/* return -1 if exception otherwise TRUE or FALSE */\nint JS_HasProperty(JSContext *ctx, JSValueConst obj, JSAtom prop)\n{\n    JSObject *p;\n    int ret;\n    JSValue obj1;\n\n    if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT))\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(obj);\n    for(;;) {\n        if (p->is_exotic) {\n            const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;\n            if (em && em->has_property) {\n                /* has_property can free the prototype */\n                obj1 = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n                ret = em->has_property(ctx, obj1, prop);\n                JS_FreeValue(ctx, obj1);\n                return ret;\n            }\n        }\n        /* JS_GetOwnPropertyInternal can free the prototype */\n        JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n        ret = JS_GetOwnPropertyInternal(ctx, NULL, p, prop);\n        JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n        if (ret != 0)\n            return ret;\n        if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n            p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n            ret = JS_AtomIsNumericIndex(ctx, prop);\n            if (ret != 0) {\n                if (ret < 0)\n                    return -1;\n                return FALSE;\n            }\n        }\n        p = p->shape->proto;\n        if (!p)\n            break;\n    }\n    return FALSE;\n}\n\n/* val must be a symbol */\nstatic JSAtom js_symbol_to_atom(JSContext *ctx, JSValue val)\n{\n    JSAtomStruct *p = JS_VALUE_GET_PTR(val);\n    return js_get_atom_index(ctx->rt, p);\n}\n\n/* return JS_ATOM_NULL in case of exception */\nJSAtom JS_ValueToAtom(JSContext *ctx, JSValueConst val)\n{\n    JSAtom atom;\n    uint32_t tag;\n    tag = JS_VALUE_GET_TAG(val);\n    if (tag == JS_TAG_INT &&\n        (uint32_t)JS_VALUE_GET_INT(val) <= JS_ATOM_MAX_INT) {\n        /* fast path for integer values */\n        atom = __JS_AtomFromUInt32(JS_VALUE_GET_INT(val));\n    } else if (tag == JS_TAG_SYMBOL) {\n        JSAtomStruct *p = JS_VALUE_GET_PTR(val);\n        atom = JS_DupAtom(ctx, js_get_atom_index(ctx->rt, p));\n    } else {\n        JSValue str;\n        str = JS_ToPropertyKey(ctx, val);\n        if (JS_IsException(str))\n            return JS_ATOM_NULL;\n        if (JS_VALUE_GET_TAG(str) == JS_TAG_SYMBOL) {\n            atom = js_symbol_to_atom(ctx, str);\n        } else {\n            atom = JS_NewAtomStr(ctx, JS_VALUE_GET_STRING(str));\n        }\n    }\n    return atom;\n}\n\nstatic JSValue JS_GetPropertyValue(JSContext *ctx, JSValueConst this_obj,\n                                   JSValue prop)\n{\n    JSAtom atom;\n    JSValue ret;\n\n    if (likely(JS_VALUE_GET_TAG(this_obj) == JS_TAG_OBJECT &&\n               JS_VALUE_GET_TAG(prop) == JS_TAG_INT)) {\n        JSObject *p;\n        uint32_t idx, len;\n        /* fast path for array access */\n        p = JS_VALUE_GET_OBJ(this_obj);\n        idx = JS_VALUE_GET_INT(prop);\n        len = (uint32_t)p->u.array.count;\n        if (unlikely(idx >= len))\n            goto slow_path;\n        switch(p->class_id) {\n        case JS_CLASS_ARRAY:\n        case JS_CLASS_ARGUMENTS:\n            return JS_DupValue(ctx, p->u.array.u.values[idx]);\n        case JS_CLASS_INT8_ARRAY:\n            return JS_NewInt32(ctx, p->u.array.u.int8_ptr[idx]);\n        case JS_CLASS_UINT8C_ARRAY:\n        case JS_CLASS_UINT8_ARRAY:\n            return JS_NewInt32(ctx, p->u.array.u.uint8_ptr[idx]);\n        case JS_CLASS_INT16_ARRAY:\n            return JS_NewInt32(ctx, p->u.array.u.int16_ptr[idx]);\n        case JS_CLASS_UINT16_ARRAY:\n            return JS_NewInt32(ctx, p->u.array.u.uint16_ptr[idx]);\n        case JS_CLASS_INT32_ARRAY:\n            return JS_NewInt32(ctx, p->u.array.u.int32_ptr[idx]);\n        case JS_CLASS_UINT32_ARRAY:\n            return JS_NewUint32(ctx, p->u.array.u.uint32_ptr[idx]);\n#ifdef CONFIG_BIGNUM\n        case JS_CLASS_BIG_INT64_ARRAY:\n            return JS_NewBigInt64(ctx, p->u.array.u.int64_ptr[idx]);\n        case JS_CLASS_BIG_UINT64_ARRAY:\n            return JS_NewBigUint64(ctx, p->u.array.u.uint64_ptr[idx]);\n#endif\n        case JS_CLASS_FLOAT32_ARRAY:\n            return __JS_NewFloat64(ctx, p->u.array.u.float_ptr[idx]);\n        case JS_CLASS_FLOAT64_ARRAY:\n            return __JS_NewFloat64(ctx, p->u.array.u.double_ptr[idx]);\n        default:\n            goto slow_path;\n        }\n    } else {\n    slow_path:\n        atom = JS_ValueToAtom(ctx, prop);\n        JS_FreeValue(ctx, prop);\n        if (unlikely(atom == JS_ATOM_NULL))\n            return JS_EXCEPTION;\n        ret = JS_GetProperty(ctx, this_obj, atom);\n        JS_FreeAtom(ctx, atom);\n        return ret;\n    }\n}\n\nJSValue JS_GetPropertyUint32(JSContext *ctx, JSValueConst this_obj,\n                             uint32_t idx)\n{\n    return JS_GetPropertyValue(ctx, this_obj, JS_NewUint32(ctx, idx));\n}\n\n/* Check if an object has a generalized numeric property. Return value:\n   -1 for exception,\n   TRUE if property exists, stored into *pval,\n   FALSE if proprty does not exist.\n */\nstatic int JS_TryGetPropertyInt64(JSContext *ctx, JSValueConst obj, int64_t idx, JSValue *pval)\n{\n    JSValue val = JS_UNDEFINED;\n    JSAtom prop;\n    int present;\n\n    if (likely((uint64_t)idx <= JS_ATOM_MAX_INT)) {\n        /* fast path */\n        present = JS_HasProperty(ctx, obj, __JS_AtomFromUInt32(idx));\n        if (present > 0) {\n            val = JS_GetPropertyValue(ctx, obj, JS_NewInt32(ctx, idx));\n            if (unlikely(JS_IsException(val)))\n                present = -1;\n        }\n    } else {\n        prop = JS_NewAtomInt64(ctx, idx);\n        present = -1;\n        if (likely(prop != JS_ATOM_NULL)) {\n            present = JS_HasProperty(ctx, obj, prop);\n            if (present > 0) {\n                val = JS_GetProperty(ctx, obj, prop);\n                if (unlikely(JS_IsException(val)))\n                    present = -1;\n            }\n            JS_FreeAtom(ctx, prop);\n        }\n    }\n    *pval = val;\n    return present;\n}\n\nstatic JSValue JS_GetPropertyInt64(JSContext *ctx, JSValueConst obj, int64_t idx)\n{\n    JSAtom prop;\n    JSValue val;\n\n    if ((uint64_t)idx <= INT32_MAX) {\n        /* fast path for fast arrays */\n        return JS_GetPropertyValue(ctx, obj, JS_NewInt32(ctx, idx));\n    }\n    prop = JS_NewAtomInt64(ctx, idx);\n    if (prop == JS_ATOM_NULL)\n        return JS_EXCEPTION;\n\n    val = JS_GetProperty(ctx, obj, prop);\n    JS_FreeAtom(ctx, prop);\n    return val;\n}\n\nJSValue JS_GetPropertyStr(JSContext *ctx, JSValueConst this_obj,\n                          const char *prop)\n{\n    JSAtom atom;\n    JSValue ret;\n    atom = JS_NewAtom(ctx, prop);\n    ret = JS_GetProperty(ctx, this_obj, atom);\n    JS_FreeAtom(ctx, atom);\n    return ret;\n}\n\n/* Note: the property value is not initialized. Return NULL if memory\n   error. */\nstatic JSProperty *add_property(JSContext *ctx,\n                                JSObject *p, JSAtom prop, int prop_flags)\n{\n    JSShape *sh, *new_sh;\n\n    sh = p->shape;\n    if (sh->is_hashed) {\n        /* try to find an existing shape */\n        new_sh = find_hashed_shape_prop(ctx->rt, sh, prop, prop_flags);\n        if (new_sh) {\n            /* matching shape found: use it */\n            /*  the property array may need to be resized */\n            if (new_sh->prop_size != sh->prop_size) {\n                JSProperty *new_prop;\n                new_prop = js_realloc(ctx, p->prop, sizeof(p->prop[0]) *\n                                      new_sh->prop_size);\n                if (!new_prop)\n                    return NULL;\n                p->prop = new_prop;\n            }\n            p->shape = js_dup_shape(new_sh);\n            js_free_shape(ctx->rt, sh);\n            return &p->prop[new_sh->prop_count - 1];\n        } else if (sh->header.ref_count != 1) {\n            /* if the shape is shared, clone it */\n            new_sh = js_clone_shape(ctx, sh);\n            if (!new_sh)\n                return NULL;\n            /* hash the cloned shape */\n            new_sh->is_hashed = TRUE;\n            js_shape_hash_link(ctx->rt, new_sh);\n            js_free_shape(ctx->rt, p->shape);\n            p->shape = new_sh;\n        }\n    }\n    assert(p->shape->header.ref_count == 1);\n    if (add_shape_property(ctx, &p->shape, p, prop, prop_flags))\n        return NULL;\n    return &p->prop[p->shape->prop_count - 1];\n}\n\n/* can be called on Array or Arguments objects. return < 0 if\n   memory alloc error. */\nstatic no_inline __exception int convert_fast_array_to_array(JSContext *ctx,\n                                                             JSObject *p)\n{\n    JSProperty *pr;\n    JSShape *sh;\n    JSValue *tab;\n    uint32_t i, len, new_count;\n\n    if (js_shape_prepare_update(ctx, p, NULL))\n        return -1;\n    len = p->u.array.count;\n    /* resize the properties once to simplify the error handling */\n    sh = p->shape;\n    new_count = sh->prop_count + len;\n    if (new_count > sh->prop_size) {\n        if (resize_properties(ctx, &p->shape, p, new_count))\n            return -1;\n    }\n\n    tab = p->u.array.u.values;\n    for(i = 0; i < len; i++) {\n        /* add_property cannot fail here but\n           __JS_AtomFromUInt32(i) fails for i > INT32_MAX */\n        pr = add_property(ctx, p, __JS_AtomFromUInt32(i), JS_PROP_C_W_E);\n        pr->u.value = *tab++;\n    }\n    js_free(ctx, p->u.array.u.values);\n    p->u.array.count = 0;\n    p->u.array.u.values = NULL; /* fail safe */\n    p->u.array.u1.size = 0;\n    p->fast_array = 0;\n    return 0;\n}\n\nstatic int delete_property(JSContext *ctx, JSObject *p, JSAtom atom)\n{\n    JSShape *sh;\n    JSShapeProperty *pr, *lpr, *prop;\n    JSProperty *pr1;\n    uint32_t lpr_idx;\n    intptr_t h, h1;\n\n redo:\n    sh = p->shape;\n    h1 = atom & sh->prop_hash_mask;\n    h = prop_hash_end(sh)[-h1 - 1];\n    prop = get_shape_prop(sh);\n    lpr = NULL;\n    lpr_idx = 0;   /* prevent warning */\n    while (h != 0) {\n        pr = &prop[h - 1];\n        if (likely(pr->atom == atom)) {\n            /* found ! */\n            if (!(pr->flags & JS_PROP_CONFIGURABLE))\n                return FALSE;\n            /* realloc the shape if needed */\n            if (lpr)\n                lpr_idx = lpr - get_shape_prop(sh);\n            if (js_shape_prepare_update(ctx, p, &pr))\n                return -1;\n            sh = p->shape;\n            /* remove property */\n            if (lpr) {\n                lpr = get_shape_prop(sh) + lpr_idx;\n                lpr->hash_next = pr->hash_next;\n            } else {\n                prop_hash_end(sh)[-h1 - 1] = pr->hash_next;\n            }\n            sh->deleted_prop_count++;\n            /* free the entry */\n            pr1 = &p->prop[h - 1];\n            free_property(ctx->rt, pr1, pr->flags);\n            JS_FreeAtom(ctx, pr->atom);\n            /* put default values */\n            pr->flags = 0;\n            pr->atom = JS_ATOM_NULL;\n            pr1->u.value = JS_UNDEFINED;\n\n            /* compact the properties if too many deleted properties */\n            if (sh->deleted_prop_count >= 8 &&\n                sh->deleted_prop_count >= ((unsigned)sh->prop_count / 2)) {\n                compact_properties(ctx, p);\n            }\n            return TRUE;\n        }\n        lpr = pr;\n        h = pr->hash_next;\n    }\n\n    if (p->is_exotic) {\n        if (p->fast_array) {\n            uint32_t idx;\n            if (JS_AtomIsArrayIndex(ctx, &idx, atom) &&\n                idx < p->u.array.count) {\n                if (p->class_id == JS_CLASS_ARRAY ||\n                    p->class_id == JS_CLASS_ARGUMENTS) {\n                    /* Special case deleting the last element of a fast Array */\n                    if (idx == p->u.array.count - 1) {\n                        JS_FreeValue(ctx, p->u.array.u.values[idx]);\n                        p->u.array.count = idx;\n                        return TRUE;\n                    }\n                    if (convert_fast_array_to_array(ctx, p))\n                        return -1;\n                    goto redo;\n                } else {\n                    return FALSE;\n                }\n            }\n        } else {\n            const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;\n            if (em && em->delete_property) {\n                return em->delete_property(ctx, JS_MKPTR(JS_TAG_OBJECT, p), atom);\n            }\n        }\n    }\n    /* not found */\n    return TRUE;\n}\n\nstatic int call_setter(JSContext *ctx, JSObject *setter,\n                       JSValueConst this_obj, JSValue val, int flags)\n{\n    JSValue ret, func;\n    if (likely(setter)) {\n        func = JS_MKPTR(JS_TAG_OBJECT, setter);\n        /* Note: the field could be removed in the setter */\n        func = JS_DupValue(ctx, func);\n        ret = JS_CallFree(ctx, func, this_obj, 1, (JSValueConst *)&val);\n        JS_FreeValue(ctx, val);\n        if (JS_IsException(ret))\n            return -1;\n        JS_FreeValue(ctx, ret);\n        return TRUE;\n    } else {\n        JS_FreeValue(ctx, val);\n        if ((flags & JS_PROP_THROW) ||\n            ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) {\n            JS_ThrowTypeError(ctx, \"no setter for property\");\n            return -1;\n        }\n        return FALSE;\n    }\n}\n\n/* set the array length and remove the array elements if necessary. */\nstatic int set_array_length(JSContext *ctx, JSObject *p, JSValue val,\n                            int flags)\n{\n    uint32_t len, idx, cur_len;\n    int i, ret;\n\n    /* Note: this call can reallocate the properties of 'p' */\n    ret = JS_ToArrayLengthFree(ctx, &len, val, FALSE);\n    if (ret)\n        return -1;\n    /* JS_ToArrayLengthFree() must be done before the read-only test */\n    if (unlikely(!(p->shape->prop[0].flags & JS_PROP_WRITABLE)))\n        return JS_ThrowTypeErrorReadOnly(ctx, flags, JS_ATOM_length);\n\n    if (likely(p->fast_array)) {\n        uint32_t old_len = p->u.array.count;\n        if (len < old_len) {\n            for(i = len; i < old_len; i++) {\n                JS_FreeValue(ctx, p->u.array.u.values[i]);\n            }\n            p->u.array.count = len;\n        }\n        p->prop[0].u.value = JS_NewUint32(ctx, len);\n    } else {\n        /* Note: length is always a uint32 because the object is an\n           array */\n        JS_ToUint32(ctx, &cur_len, p->prop[0].u.value);\n        if (len < cur_len) {\n            uint32_t d;\n            JSShape *sh;\n            JSShapeProperty *pr;\n\n            d = cur_len - len;\n            sh = p->shape;\n            if (d <= sh->prop_count) {\n                JSAtom atom;\n\n                /* faster to iterate */\n                while (cur_len > len) {\n                    atom = JS_NewAtomUInt32(ctx, cur_len - 1);\n                    ret = delete_property(ctx, p, atom);\n                    JS_FreeAtom(ctx, atom);\n                    if (unlikely(!ret)) {\n                        /* unlikely case: property is not\n                           configurable */\n                        break;\n                    }\n                    cur_len--;\n                }\n            } else {\n                /* faster to iterate thru all the properties. Need two\n                   passes in case one of the property is not\n                   configurable */\n                cur_len = len;\n                for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count;\n                    i++, pr++) {\n                    if (pr->atom != JS_ATOM_NULL &&\n                        JS_AtomIsArrayIndex(ctx, &idx, pr->atom)) {\n                        if (idx >= cur_len &&\n                            !(pr->flags & JS_PROP_CONFIGURABLE)) {\n                            cur_len = idx + 1;\n                        }\n                    }\n                }\n\n                for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count;\n                    i++, pr++) {\n                    if (pr->atom != JS_ATOM_NULL &&\n                        JS_AtomIsArrayIndex(ctx, &idx, pr->atom)) {\n                        if (idx >= cur_len) {\n                            /* remove the property */\n                            delete_property(ctx, p, pr->atom);\n                            /* WARNING: the shape may have been modified */\n                            sh = p->shape;\n                            pr = get_shape_prop(sh) + i;\n                        }\n                    }\n                }\n            }\n        } else {\n            cur_len = len;\n        }\n        set_value(ctx, &p->prop[0].u.value, JS_NewUint32(ctx, cur_len));\n        if (unlikely(cur_len > len)) {\n            return JS_ThrowTypeErrorOrFalse(ctx, flags, \"not configurable\");\n        }\n    }\n    return TRUE;\n}\n\n/* return -1 if exception */\nstatic int expand_fast_array(JSContext *ctx, JSObject *p, uint32_t new_len)\n{\n    uint32_t new_size;\n    size_t slack;\n    JSValue *new_array_prop;\n    /* XXX: potential arithmetic overflow */\n    new_size = max_int(new_len, p->u.array.u1.size * 3 / 2);\n    new_array_prop = js_realloc2(ctx, p->u.array.u.values, sizeof(JSValue) * new_size, &slack);\n    if (!new_array_prop)\n        return -1;\n    new_size += slack / sizeof(*new_array_prop);\n    p->u.array.u.values = new_array_prop;\n    p->u.array.u1.size = new_size;\n    return 0;\n}\n\n/* Preconditions: 'p' must be of class JS_CLASS_ARRAY, p->fast_array =\n   TRUE and p->extensible = TRUE */\nstatic int add_fast_array_element(JSContext *ctx, JSObject *p,\n                                  JSValue val, int flags)\n{\n    uint32_t new_len, array_len;\n    /* extend the array by one */\n    /* XXX: convert to slow array if new_len > 2^31-1 elements */\n    new_len = p->u.array.count + 1;\n    /* update the length if necessary. We assume that if the length is\n       not an integer, then if it >= 2^31.  */\n    if (likely(JS_VALUE_GET_TAG(p->prop[0].u.value) == JS_TAG_INT)) {\n        array_len = JS_VALUE_GET_INT(p->prop[0].u.value);\n        if (new_len > array_len) {\n            if (unlikely(!(get_shape_prop(p->shape)->flags & JS_PROP_WRITABLE))) {\n                JS_FreeValue(ctx, val);\n                return JS_ThrowTypeErrorReadOnly(ctx, flags, JS_ATOM_length);\n            }\n            p->prop[0].u.value = JS_NewInt32(ctx, new_len);\n        }\n    }\n    if (unlikely(new_len > p->u.array.u1.size)) {\n        if (expand_fast_array(ctx, p, new_len)) {\n            JS_FreeValue(ctx, val);\n            return -1;\n        }\n    }\n    p->u.array.u.values[new_len - 1] = val;\n    p->u.array.count = new_len;\n    return TRUE;\n}\n\nstatic void js_free_desc(JSContext *ctx, JSPropertyDescriptor *desc)\n{\n    JS_FreeValue(ctx, desc->getter);\n    JS_FreeValue(ctx, desc->setter);\n    JS_FreeValue(ctx, desc->value);\n}\n\n/* generic (and slower) version of JS_SetProperty() for\n * Reflect.set(). 'obj' must be an object.  */\nstatic int JS_SetPropertyGeneric(JSContext *ctx,\n                                 JSValueConst obj, JSAtom prop,\n                                 JSValue val, JSValueConst this_obj,\n                                 int flags)\n{\n    int ret;\n    JSPropertyDescriptor desc;\n    JSValue obj1;\n    JSObject *p;\n    \n    obj1 = JS_DupValue(ctx, obj);\n    for(;;) {\n        p = JS_VALUE_GET_OBJ(obj1);\n        if (p->is_exotic) {\n            const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;\n            if (em && em->set_property) {\n                ret = em->set_property(ctx, obj1, prop,\n                                       val, this_obj, flags);\n                JS_FreeValue(ctx, obj1);\n                JS_FreeValue(ctx, val);\n                return ret;\n            }\n        }\n\n        ret = JS_GetOwnPropertyInternal(ctx, &desc, p, prop);\n        if (ret < 0) {\n            JS_FreeValue(ctx, obj1);\n            JS_FreeValue(ctx, val);\n            return ret;\n        }\n        if (ret) {\n            if (desc.flags & JS_PROP_GETSET) {\n                JSObject *setter;\n                if (JS_IsUndefined(desc.setter))\n                    setter = NULL;\n                else\n                    setter = JS_VALUE_GET_OBJ(desc.setter);\n                ret = call_setter(ctx, setter, this_obj, val, flags);\n                JS_FreeValue(ctx, desc.getter);\n                JS_FreeValue(ctx, desc.setter);\n                JS_FreeValue(ctx, obj1);\n                return ret;\n            } else {\n                JS_FreeValue(ctx, desc.value);\n                if (!(desc.flags & JS_PROP_WRITABLE)) {\n                    JS_FreeValue(ctx, obj1);\n                    goto read_only_error;\n                }\n            }\n            break;\n        }\n        /* Note: at this point 'obj1' cannot be a proxy. XXX: may have\n           to check recursion */\n        obj1 = JS_GetPrototypeFree(ctx, obj1);\n        if (JS_IsNull(obj1))\n            break;\n    }\n    JS_FreeValue(ctx, obj1);\n\n    if (!JS_IsObject(this_obj)) {\n        JS_FreeValue(ctx, val);\n        return JS_ThrowTypeErrorOrFalse(ctx, flags, \"receiver is not an object\");\n    }\n    \n    p = JS_VALUE_GET_OBJ(this_obj);\n\n    /* modify the property in this_obj if it already exists */\n    ret = JS_GetOwnPropertyInternal(ctx, &desc, p, prop);\n    if (ret < 0) {\n        JS_FreeValue(ctx, val);\n        return ret;\n    }\n    if (ret) {\n        if (desc.flags & JS_PROP_GETSET) {\n            JS_FreeValue(ctx, desc.getter);\n            JS_FreeValue(ctx, desc.setter);\n            JS_FreeValue(ctx, val);\n            return JS_ThrowTypeErrorOrFalse(ctx, flags, \"setter is forbidden\");\n        } else {\n            JS_FreeValue(ctx, desc.value);\n            if (!(desc.flags & JS_PROP_WRITABLE) ||\n                p->class_id == JS_CLASS_MODULE_NS) {\n            read_only_error:\n                JS_FreeValue(ctx, val);\n                return JS_ThrowTypeErrorReadOnly(ctx, flags, prop);\n            }\n        }\n        ret = JS_DefineProperty(ctx, this_obj, prop, val,\n                                JS_UNDEFINED, JS_UNDEFINED,\n                                JS_PROP_HAS_VALUE);\n        JS_FreeValue(ctx, val);\n        return ret;\n    }\n\n    ret = JS_CreateProperty(ctx, p, prop, val, JS_UNDEFINED, JS_UNDEFINED,\n                            flags |\n                            JS_PROP_HAS_VALUE |\n                            JS_PROP_HAS_ENUMERABLE |\n                            JS_PROP_HAS_WRITABLE |\n                            JS_PROP_HAS_CONFIGURABLE |\n                            JS_PROP_C_W_E);\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\n/* return -1 in case of exception or TRUE or FALSE. Warning: 'val' is\n   freed by the function. 'flags' is a bitmask of JS_PROP_NO_ADD,\n   JS_PROP_THROW or JS_PROP_THROW_STRICT. If JS_PROP_NO_ADD is set,\n   the new property is not added and an error is raised. */\nint JS_SetPropertyInternal(JSContext *ctx, JSValueConst this_obj,\n                           JSAtom prop, JSValue val, int flags)\n{\n    JSObject *p, *p1;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    uint32_t tag;\n    JSPropertyDescriptor desc;\n    int ret;\n#if 0\n    printf(\"JS_SetPropertyInternal: \"); print_atom(ctx, prop); printf(\"\\n\");\n#endif\n    tag = JS_VALUE_GET_TAG(this_obj);\n    if (unlikely(tag != JS_TAG_OBJECT)) {\n        switch(tag) {\n        case JS_TAG_NULL:\n            JS_FreeValue(ctx, val);\n            JS_ThrowTypeErrorAtom(ctx, \"cannot set property '%s' of null\", prop);\n            return -1;\n        case JS_TAG_UNDEFINED:\n            JS_FreeValue(ctx, val);\n            JS_ThrowTypeErrorAtom(ctx, \"cannot set property '%s' of undefined\", prop);\n            return -1;\n        default:\n            /* even on a primitive type we can have setters on the prototype */\n            p = NULL;\n            p1 = JS_VALUE_GET_OBJ(JS_GetPrototypePrimitive(ctx, this_obj));\n            goto prototype_lookup;\n        }\n    }\n    p = JS_VALUE_GET_OBJ(this_obj);\nretry:\n    prs = find_own_property(&pr, p, prop);\n    if (prs) {\n        if (likely((prs->flags & (JS_PROP_TMASK | JS_PROP_WRITABLE |\n                                  JS_PROP_LENGTH)) == JS_PROP_WRITABLE)) {\n            /* fast case */\n            set_value(ctx, &pr->u.value, val);\n            return TRUE;\n        } else if (prs->flags & JS_PROP_LENGTH) {\n            assert(p->class_id == JS_CLASS_ARRAY);\n            assert(prop == JS_ATOM_length);\n            return set_array_length(ctx, p, val, flags);\n        } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {\n            return call_setter(ctx, pr->u.getset.setter, this_obj, val, flags);\n        } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n            /* JS_PROP_WRITABLE is always true for variable\n               references, but they are write protected in module name\n               spaces. */\n            if (p->class_id == JS_CLASS_MODULE_NS)\n                goto read_only_prop;\n            set_value(ctx, pr->u.var_ref->pvalue, val);\n            return TRUE;\n        } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n            /* Instantiate property and retry (potentially useless) */\n            if (JS_AutoInitProperty(ctx, p, prop, pr, prs)) {\n                JS_FreeValue(ctx, val);\n                return -1;\n            }\n            goto retry;\n        } else {\n            goto read_only_prop;\n        }\n    }\n\n    p1 = p;\n    for(;;) {\n        if (p1->is_exotic) {\n            if (p1->fast_array) {\n                if (__JS_AtomIsTaggedInt(prop)) {\n                    uint32_t idx = __JS_AtomToUInt32(prop);\n                    if (idx < p1->u.array.count) {\n                        if (unlikely(p == p1))\n                            return JS_SetPropertyValue(ctx, this_obj, JS_NewInt32(ctx, idx), val, flags);\n                        else\n                            break;\n                    } else if (p1->class_id >= JS_CLASS_UINT8C_ARRAY &&\n                               p1->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n                        goto typed_array_oob;\n                    }\n                } else if (p1->class_id >= JS_CLASS_UINT8C_ARRAY &&\n                           p1->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n                    ret = JS_AtomIsNumericIndex(ctx, prop);\n                    if (ret != 0) {\n                        if (ret < 0) {\n                            JS_FreeValue(ctx, val);\n                            return -1;\n                        }\n                    typed_array_oob:\n                        val = JS_ToNumberFree(ctx, val);\n                        JS_FreeValue(ctx, val);\n                        if (JS_IsException(val))\n                            return -1;\n#ifdef JSB_TYPED_ARRAY_NO_THROW\n                        return TRUE;\n#else                        \n                        return JS_ThrowTypeErrorOrFalse(ctx, flags, \"out-of-bound numeric index\");\n#endif\n                    }\n                }\n            } else {\n                const JSClassExoticMethods *em = ctx->rt->class_array[p1->class_id].exotic;\n                if (em) {\n                    JSValue obj1;\n                    if (em->set_property) {\n                        /* set_property can free the prototype */\n                        obj1 = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p1));\n                        ret = em->set_property(ctx, obj1, prop,\n                                               val, this_obj, flags);\n                        JS_FreeValue(ctx, obj1);\n                        JS_FreeValue(ctx, val);\n                        return ret;\n                    }\n                    if (em->get_own_property) {\n                        /* get_own_property can free the prototype */\n                        obj1 = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p1));\n                        ret = em->get_own_property(ctx, &desc,\n                                                   obj1, prop);\n                        JS_FreeValue(ctx, obj1);\n                        if (ret < 0) {\n                            JS_FreeValue(ctx, val);\n                            return ret;\n                        }\n                        if (ret) {\n                            if (desc.flags & JS_PROP_GETSET) {\n                                JSObject *setter;\n                                if (JS_IsUndefined(desc.setter))\n                                    setter = NULL;\n                                else\n                                    setter = JS_VALUE_GET_OBJ(desc.setter);\n                                ret = call_setter(ctx, setter, this_obj, val, flags);\n                                JS_FreeValue(ctx, desc.getter);\n                                JS_FreeValue(ctx, desc.setter);\n                                return ret;\n                            } else {\n                                JS_FreeValue(ctx, desc.value);\n                                if (!(desc.flags & JS_PROP_WRITABLE))\n                                    goto read_only_prop;\n                                if (likely(p == p1)) {\n                                    ret = JS_DefineProperty(ctx, this_obj, prop, val,\n                                                            JS_UNDEFINED, JS_UNDEFINED,\n                                                            JS_PROP_HAS_VALUE);\n                                    JS_FreeValue(ctx, val);\n                                    return ret;\n                                } else {\n                                    break;\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        p1 = p1->shape->proto;\n    prototype_lookup:\n        if (!p1)\n            break;\n\n    retry2:\n        prs = find_own_property(&pr, p1, prop);\n        if (prs) {\n            if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {\n                return call_setter(ctx, pr->u.getset.setter, this_obj, val, flags);\n            } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n                /* Instantiate property and retry (potentially useless) */\n                if (JS_AutoInitProperty(ctx, p1, prop, pr, prs))\n                    return -1;\n                goto retry2;\n            } else if (!(prs->flags & JS_PROP_WRITABLE)) {\n            read_only_prop:\n                JS_FreeValue(ctx, val);\n                return JS_ThrowTypeErrorReadOnly(ctx, flags, prop);\n            }\n        }\n    }\n\n    if (unlikely(flags & JS_PROP_NO_ADD)) {\n        JS_FreeValue(ctx, val);\n        JS_ThrowReferenceErrorNotDefined(ctx, prop);\n        return -1;\n    }\n\n    if (unlikely(!p)) {\n        JS_FreeValue(ctx, val);\n        return JS_ThrowTypeErrorOrFalse(ctx, flags, \"not an object\");\n    }\n\n    if (unlikely(!p->extensible)) {\n        JS_FreeValue(ctx, val);\n        return JS_ThrowTypeErrorOrFalse(ctx, flags, \"object is not extensible\");\n    }\n\n    if (p->is_exotic) {\n        if (p->class_id == JS_CLASS_ARRAY && p->fast_array &&\n            __JS_AtomIsTaggedInt(prop)) {\n            uint32_t idx = __JS_AtomToUInt32(prop);\n            if (idx == p->u.array.count) {\n                /* fast case */\n                return add_fast_array_element(ctx, p, val, flags);\n            } else {\n                goto generic_create_prop;\n            }\n        } else {\n        generic_create_prop:\n            ret = JS_CreateProperty(ctx, p, prop, val, JS_UNDEFINED, JS_UNDEFINED,\n                                    flags |\n                                    JS_PROP_HAS_VALUE |\n                                    JS_PROP_HAS_ENUMERABLE |\n                                    JS_PROP_HAS_WRITABLE |\n                                    JS_PROP_HAS_CONFIGURABLE |\n                                    JS_PROP_C_W_E);\n            JS_FreeValue(ctx, val);\n            return ret;\n        }\n    }\n\n    pr = add_property(ctx, p, prop, JS_PROP_C_W_E);\n    if (unlikely(!pr)) {\n        JS_FreeValue(ctx, val);\n        return -1;\n    }\n    pr->u.value = val;\n    return TRUE;\n}\n\n/* flags can be JS_PROP_THROW or JS_PROP_THROW_STRICT */\nstatic int JS_SetPropertyValue(JSContext *ctx, JSValueConst this_obj,\n                               JSValue prop, JSValue val, int flags)\n{\n    if (likely(JS_VALUE_GET_TAG(this_obj) == JS_TAG_OBJECT &&\n               JS_VALUE_GET_TAG(prop) == JS_TAG_INT)) {\n        JSObject *p;\n        uint32_t idx;\n        double d;\n        int32_t v;\n\n        /* fast path for array access */\n        p = JS_VALUE_GET_OBJ(this_obj);\n        idx = JS_VALUE_GET_INT(prop);\n        switch(p->class_id) {\n        case JS_CLASS_ARRAY:\n            if (unlikely(idx >= (uint32_t)p->u.array.count)) {\n                JSObject *p1;\n                JSShape *sh1;\n\n                /* fast path to add an element to the array */\n                if (idx != (uint32_t)p->u.array.count ||\n                    !p->fast_array || !p->extensible)\n                    goto slow_path;\n                /* check if prototype chain has a numeric property */\n                p1 = p->shape->proto;\n                while (p1 != NULL) {\n                    sh1 = p1->shape;\n                    if (p1->class_id == JS_CLASS_ARRAY) {\n                        if (unlikely(!p1->fast_array))\n                            goto slow_path;\n                    } else if (p1->class_id == JS_CLASS_OBJECT) {\n                        if (unlikely(sh1->has_small_array_index))\n                            goto slow_path;\n                    } else {\n                        goto slow_path;\n                    }\n                    p1 = sh1->proto;\n                }\n                /* add element */\n                return add_fast_array_element(ctx, p, val, flags);\n            }\n            set_value(ctx, &p->u.array.u.values[idx], val);\n            break;\n        case JS_CLASS_ARGUMENTS:\n            if (unlikely(idx >= (uint32_t)p->u.array.count))\n                goto slow_path;\n            set_value(ctx, &p->u.array.u.values[idx], val);\n            break;\n        case JS_CLASS_UINT8C_ARRAY:\n            if (JS_ToUint8ClampFree(ctx, &v, val))\n                return -1;\n            /* Note: the conversion can detach the typed array, so the\n               array bound check must be done after */\n            if (unlikely(idx >= (uint32_t)p->u.array.count))\n                goto ta_out_of_bound;\n            p->u.array.u.uint8_ptr[idx] = v;\n            break;\n        case JS_CLASS_INT8_ARRAY:\n        case JS_CLASS_UINT8_ARRAY:\n            if (JS_ToInt32Free(ctx, &v, val))\n                return -1;\n            if (unlikely(idx >= (uint32_t)p->u.array.count))\n                goto ta_out_of_bound;\n            p->u.array.u.uint8_ptr[idx] = v;\n            break;\n        case JS_CLASS_INT16_ARRAY:\n        case JS_CLASS_UINT16_ARRAY:\n            if (JS_ToInt32Free(ctx, &v, val))\n                return -1;\n            if (unlikely(idx >= (uint32_t)p->u.array.count))\n                goto ta_out_of_bound;\n            p->u.array.u.uint16_ptr[idx] = v;\n            break;\n        case JS_CLASS_INT32_ARRAY:\n        case JS_CLASS_UINT32_ARRAY:\n            if (JS_ToInt32Free(ctx, &v, val))\n                return -1;\n            if (unlikely(idx >= (uint32_t)p->u.array.count))\n                goto ta_out_of_bound;\n            p->u.array.u.uint32_ptr[idx] = v;\n            break;\n#ifdef CONFIG_BIGNUM\n        case JS_CLASS_BIG_INT64_ARRAY:\n        case JS_CLASS_BIG_UINT64_ARRAY:\n            /* XXX: need specific conversion function */\n            {\n                int64_t v;\n                if (JS_ToBigInt64Free(ctx, &v, val))\n                    return -1;\n                if (unlikely(idx >= (uint32_t)p->u.array.count))\n                    goto ta_out_of_bound;\n                p->u.array.u.uint64_ptr[idx] = v;\n            }\n            break;\n#endif\n        case JS_CLASS_FLOAT32_ARRAY:\n            if (JS_ToFloat64Free(ctx, &d, val))\n                return -1;\n            if (unlikely(idx >= (uint32_t)p->u.array.count))\n                goto ta_out_of_bound;\n            p->u.array.u.float_ptr[idx] = d;\n            break;\n        case JS_CLASS_FLOAT64_ARRAY:\n            if (JS_ToFloat64Free(ctx, &d, val))\n                return -1;\n            if (unlikely(idx >= (uint32_t)p->u.array.count)) {\n            ta_out_of_bound:\n#ifdef JSB_TYPED_ARRAY_NO_THROW\n                break;\n#else\n                return JS_ThrowTypeErrorOrFalse(ctx, flags, \"out-of-bound numeric index\");\n#endif\n            }\n            p->u.array.u.double_ptr[idx] = d;\n            break;\n        default:\n            goto slow_path;\n        }\n        return TRUE;\n    } else {\n        JSAtom atom;\n        int ret;\n    slow_path:\n        atom = JS_ValueToAtom(ctx, prop);\n        JS_FreeValue(ctx, prop);\n        if (unlikely(atom == JS_ATOM_NULL)) {\n            JS_FreeValue(ctx, val);\n            return -1;\n        }\n        ret = JS_SetPropertyInternal(ctx, this_obj, atom, val, flags);\n        JS_FreeAtom(ctx, atom);\n        return ret;\n    }\n}\n\nint JS_SetPropertyUint32(JSContext *ctx, JSValueConst this_obj,\n                         uint32_t idx, JSValue val)\n{\n    return JS_SetPropertyValue(ctx, this_obj, JS_NewUint32(ctx, idx), val,\n                               JS_PROP_THROW);\n}\n\nint JS_SetPropertyInt64(JSContext *ctx, JSValueConst this_obj,\n                        int64_t idx, JSValue val)\n{\n    JSAtom prop;\n    int res;\n\n    if ((uint64_t)idx <= INT32_MAX) {\n        /* fast path for fast arrays */\n        return JS_SetPropertyValue(ctx, this_obj, JS_NewInt32(ctx, idx), val,\n                                   JS_PROP_THROW);\n    }\n    prop = JS_NewAtomInt64(ctx, idx);\n    if (prop == JS_ATOM_NULL) {\n        JS_FreeValue(ctx, val);\n        return -1;\n    }\n    res = JS_SetProperty(ctx, this_obj, prop, val);\n    JS_FreeAtom(ctx, prop);\n    return res;\n}\n\nint JS_SetPropertyStr(JSContext *ctx, JSValueConst this_obj,\n                      const char *prop, JSValue val)\n{\n    JSAtom atom;\n    int ret;\n    atom = JS_NewAtom(ctx, prop);\n    ret = JS_SetPropertyInternal(ctx, this_obj, atom, val, JS_PROP_THROW);\n    JS_FreeAtom(ctx, atom);\n    return ret;\n}\n\n/* compute the property flags. For each flag: (JS_PROP_HAS_x forces\n   it, otherwise def_flags is used)\n   Note: makes assumption about the bit pattern of the flags\n*/\nstatic int get_prop_flags(int flags, int def_flags)\n{\n    int mask;\n    mask = (flags >> JS_PROP_HAS_SHIFT) & JS_PROP_C_W_E;\n    return (flags & mask) | (def_flags & ~mask);\n}\n\nstatic int JS_CreateProperty(JSContext *ctx, JSObject *p,\n                             JSAtom prop, JSValueConst val,\n                             JSValueConst getter, JSValueConst setter,\n                             int flags)\n{\n    JSProperty *pr;\n    int ret, prop_flags;\n\n    /* add a new property or modify an existing exotic one */\n    if (p->is_exotic) {\n        if (p->class_id == JS_CLASS_ARRAY) {\n            uint32_t idx, len;\n\n            if (p->fast_array) {\n                if (__JS_AtomIsTaggedInt(prop)) {\n                    idx = __JS_AtomToUInt32(prop);\n                    if (idx == p->u.array.count) {\n                        if (!p->extensible)\n                            goto not_extensible;\n                        if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET))\n                            goto convert_to_array;\n                        prop_flags = get_prop_flags(flags, 0);\n                        if (prop_flags != JS_PROP_C_W_E)\n                            goto convert_to_array;\n                        return add_fast_array_element(ctx, p,\n                                                      JS_DupValue(ctx, val), flags);\n                    } else {\n                        goto convert_to_array;\n                    }\n                } else if (JS_AtomIsArrayIndex(ctx, &idx, prop)) {\n                    /* convert the fast array to normal array */\n                convert_to_array:\n                    if (convert_fast_array_to_array(ctx, p))\n                        return -1;\n                    goto generic_array;\n                }\n            } else if (JS_AtomIsArrayIndex(ctx, &idx, prop)) {\n                JSProperty *plen;\n                JSShapeProperty *pslen;\n            generic_array:\n                /* update the length field */\n                plen = &p->prop[0];\n                JS_ToUint32(ctx, &len, plen->u.value);\n                if ((idx + 1) > len) {\n                    pslen = get_shape_prop(p->shape);\n                    if (unlikely(!(pslen->flags & JS_PROP_WRITABLE)))\n                        return JS_ThrowTypeErrorReadOnly(ctx, flags, JS_ATOM_length);\n                    /* XXX: should update the length after defining\n                       the property */\n                    len = idx + 1;\n                    set_value(ctx, &plen->u.value, JS_NewUint32(ctx, len));\n                }\n            }\n        } else if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n                   p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n            ret = JS_AtomIsNumericIndex(ctx, prop);\n            if (ret != 0) {\n                if (ret < 0)\n                    return -1;\n                return JS_ThrowTypeErrorOrFalse(ctx, flags, \"cannot create numeric index in typed array\");\n            }\n        } else if (!(flags & JS_PROP_NO_EXOTIC)) {\n            const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;\n            if (em) {\n                if (em->define_own_property) {\n                    return em->define_own_property(ctx, JS_MKPTR(JS_TAG_OBJECT, p),\n                                                   prop, val, getter, setter, flags);\n                }\n                ret = JS_IsExtensible(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n                if (ret < 0)\n                    return -1;\n                if (!ret)\n                    goto not_extensible;\n            }\n        }\n    }\n\n    if (!p->extensible) {\n    not_extensible:\n        return JS_ThrowTypeErrorOrFalse(ctx, flags, \"object is not extensible\");\n    }\n\n    if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {\n        prop_flags = (flags & (JS_PROP_CONFIGURABLE | JS_PROP_ENUMERABLE)) |\n            JS_PROP_GETSET;\n    } else {\n        prop_flags = flags & JS_PROP_C_W_E;\n    }\n    pr = add_property(ctx, p, prop, prop_flags);\n    if (unlikely(!pr))\n        return -1;\n    if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {\n        pr->u.getset.getter = NULL;\n        if ((flags & JS_PROP_HAS_GET) && JS_IsFunction(ctx, getter)) {\n            pr->u.getset.getter =\n                JS_VALUE_GET_OBJ(JS_DupValue(ctx, getter));\n        }\n        pr->u.getset.setter = NULL;\n        if ((flags & JS_PROP_HAS_SET) && JS_IsFunction(ctx, setter)) {\n            pr->u.getset.setter =\n                JS_VALUE_GET_OBJ(JS_DupValue(ctx, setter));\n        }\n    } else {\n        if (flags & JS_PROP_HAS_VALUE) {\n            pr->u.value = JS_DupValue(ctx, val);\n        } else {\n            pr->u.value = JS_UNDEFINED;\n        }\n    }\n    return TRUE;\n}\n\n/* return FALSE if not OK */\nstatic BOOL check_define_prop_flags(int prop_flags, int flags)\n{\n    BOOL has_accessor, is_getset;\n\n    if (!(prop_flags & JS_PROP_CONFIGURABLE)) {\n        if ((flags & (JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE)) ==\n            (JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE)) {\n            return FALSE;\n        }\n        if ((flags & JS_PROP_HAS_ENUMERABLE) &&\n            (flags & JS_PROP_ENUMERABLE) != (prop_flags & JS_PROP_ENUMERABLE))\n            return FALSE;\n    }\n    if (flags & (JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE |\n                 JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {\n        if (!(prop_flags & JS_PROP_CONFIGURABLE)) {\n            has_accessor = ((flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) != 0);\n            is_getset = ((prop_flags & JS_PROP_TMASK) == JS_PROP_GETSET);\n            if (has_accessor != is_getset)\n                return FALSE;\n            if (!has_accessor && !is_getset && !(prop_flags & JS_PROP_WRITABLE)) {\n                /* not writable: cannot set the writable bit */\n                if ((flags & (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) ==\n                    (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE))\n                    return FALSE;\n            }\n        }\n    }\n    return TRUE;\n}\n\n/* ensure that the shape can be safely modified */\nstatic int js_shape_prepare_update(JSContext *ctx, JSObject *p,\n                                   JSShapeProperty **pprs)\n{\n    JSShape *sh;\n    uint32_t idx = 0;    /* prevent warning */\n\n    sh = p->shape;\n    if (sh->is_hashed) {\n        if (sh->header.ref_count != 1) {\n            if (pprs)\n                idx = *pprs - get_shape_prop(sh);\n            /* clone the shape (the resulting one is no longer hashed) */\n            sh = js_clone_shape(ctx, sh);\n            if (!sh)\n                return -1;\n            js_free_shape(ctx->rt, p->shape);\n            p->shape = sh;\n            if (pprs)\n                *pprs = get_shape_prop(sh) + idx;\n        } else {\n            js_shape_hash_unlink(ctx->rt, sh);\n            sh->is_hashed = FALSE;\n        }\n    }\n    return 0;\n}\n\nstatic int js_update_property_flags(JSContext *ctx, JSObject *p,\n                                    JSShapeProperty **pprs, int flags)\n{\n    if (flags != (*pprs)->flags) {\n        if (js_shape_prepare_update(ctx, p, pprs))\n            return -1;\n        (*pprs)->flags = flags;\n    }\n    return 0;\n}\n\n/* allowed flags:\n   JS_PROP_CONFIGURABLE, JS_PROP_WRITABLE, JS_PROP_ENUMERABLE\n   JS_PROP_HAS_GET, JS_PROP_HAS_SET, JS_PROP_HAS_VALUE,\n   JS_PROP_HAS_CONFIGURABLE, JS_PROP_HAS_WRITABLE, JS_PROP_HAS_ENUMERABLE,\n   JS_PROP_THROW, JS_PROP_NO_EXOTIC.\n   If JS_PROP_THROW is set, return an exception instead of FALSE.\n   if JS_PROP_NO_EXOTIC is set, do not call the exotic\n   define_own_property callback.\n   return -1 (exception), FALSE or TRUE.\n*/\nint JS_DefineProperty(JSContext *ctx, JSValueConst this_obj,\n                      JSAtom prop, JSValueConst val,\n                      JSValueConst getter, JSValueConst setter, int flags)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    int mask, res;\n\n    if (JS_VALUE_GET_TAG(this_obj) != JS_TAG_OBJECT) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        return -1;\n    }\n    p = JS_VALUE_GET_OBJ(this_obj);\n\n redo_prop_update:\n    prs = find_own_property(&pr, p, prop);\n    if (prs) {\n        /* the range of the Array length property is always tested before */\n        if ((prs->flags & JS_PROP_LENGTH) && (flags & JS_PROP_HAS_VALUE)) {\n            uint32_t array_length;\n            if (JS_ToArrayLengthFree(ctx, &array_length,\n                                     JS_DupValue(ctx, val), FALSE)) {\n                return -1;\n            }\n            /* this code relies on the fact that Uint32 are never allocated */\n            val = JS_NewUint32(ctx, array_length);\n            /* prs may have been modified */\n            prs = find_own_property(&pr, p, prop);\n            assert(prs != NULL);\n        }\n        /* property already exists */\n        if (!check_define_prop_flags(prs->flags, flags)) {\n        not_configurable:\n            return JS_ThrowTypeErrorOrFalse(ctx, flags, \"property is not configurable\");\n        }\n\n        if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n            /* Instantiate property and retry */\n            if (JS_AutoInitProperty(ctx, p, prop, pr, prs))\n                return -1;\n            goto redo_prop_update;\n        }\n\n        if (flags & (JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE |\n                     JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {\n            if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {\n                JSObject *new_getter, *new_setter;\n\n                if (JS_IsFunction(ctx, getter)) {\n                    new_getter = JS_VALUE_GET_OBJ(getter);\n                } else {\n                    new_getter = NULL;\n                }\n                if (JS_IsFunction(ctx, setter)) {\n                    new_setter = JS_VALUE_GET_OBJ(setter);\n                } else {\n                    new_setter = NULL;\n                }\n\n                if ((prs->flags & JS_PROP_TMASK) != JS_PROP_GETSET) {\n                    if (js_shape_prepare_update(ctx, p, &prs))\n                        return -1;\n                    /* convert to getset */\n                    if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n                        free_var_ref(ctx->rt, pr->u.var_ref);\n                    } else {\n                        JS_FreeValue(ctx, pr->u.value);\n                    }\n                    prs->flags = (prs->flags &\n                                  (JS_PROP_CONFIGURABLE | JS_PROP_ENUMERABLE)) |\n                        JS_PROP_GETSET;\n                    pr->u.getset.getter = NULL;\n                    pr->u.getset.setter = NULL;\n                } else {\n                    if (!(prs->flags & JS_PROP_CONFIGURABLE)) {\n                        if ((flags & JS_PROP_HAS_GET) &&\n                            new_getter != pr->u.getset.getter) {\n                            goto not_configurable;\n                        }\n                        if ((flags & JS_PROP_HAS_SET) &&\n                            new_setter != pr->u.getset.setter) {\n                            goto not_configurable;\n                        }\n                    }\n                }\n                if (flags & JS_PROP_HAS_GET) {\n                    if (pr->u.getset.getter)\n                        JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter));\n                    if (new_getter)\n                        JS_DupValue(ctx, getter);\n                    pr->u.getset.getter = new_getter;\n                }\n                if (flags & JS_PROP_HAS_SET) {\n                    if (pr->u.getset.setter)\n                        JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter));\n                    if (new_setter)\n                        JS_DupValue(ctx, setter);\n                    pr->u.getset.setter = new_setter;\n                }\n            } else {\n                if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {\n                    /* convert to data descriptor */\n                    if (js_shape_prepare_update(ctx, p, &prs))\n                        return -1;\n                    if (pr->u.getset.getter)\n                        JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter));\n                    if (pr->u.getset.setter)\n                        JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter));\n                    prs->flags &= ~(JS_PROP_TMASK | JS_PROP_WRITABLE);\n                    pr->u.value = JS_UNDEFINED;\n                } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n                    /* Note: JS_PROP_VARREF is always writable */\n                } else {\n                    if ((prs->flags & (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) == 0 &&\n                        (flags & JS_PROP_HAS_VALUE)) {\n                        if (!js_same_value(ctx, val, pr->u.value)) {\n                            goto not_configurable;\n                        } else {\n                            return TRUE;\n                        }\n                    }\n                }\n                if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n                    if (flags & JS_PROP_HAS_VALUE) {\n                        if (p->class_id == JS_CLASS_MODULE_NS) {\n                            /* JS_PROP_WRITABLE is always true for variable\n                               references, but they are write protected in module name\n                               spaces. */\n                            if (!js_same_value(ctx, val, *pr->u.var_ref->pvalue))\n                                goto not_configurable;\n                        }\n                        /* update the reference */\n                        set_value(ctx, pr->u.var_ref->pvalue,\n                                  JS_DupValue(ctx, val));\n                    }\n                    /* if writable is set to false, no longer a\n                       reference (for mapped arguments) */\n                    if ((flags & (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) == JS_PROP_HAS_WRITABLE) {\n                        JSValue val1;\n                        if (js_shape_prepare_update(ctx, p, &prs))\n                            return -1;\n                        val1 = JS_DupValue(ctx, *pr->u.var_ref->pvalue);\n                        free_var_ref(ctx->rt, pr->u.var_ref);\n                        pr->u.value = val1;\n                        prs->flags &= ~(JS_PROP_TMASK | JS_PROP_WRITABLE);\n                    }\n                } else if (prs->flags & JS_PROP_LENGTH) {\n                    if (flags & JS_PROP_HAS_VALUE) {\n                        /* Note: no JS code is executable because\n                           'val' is guaranted to be a Uint32 */\n                        res = set_array_length(ctx, p, JS_DupValue(ctx, val),\n                                               flags);\n                    } else {\n                        res = TRUE;\n                    }\n                    /* still need to reset the writable flag if\n                       needed.  The JS_PROP_LENGTH is kept because the\n                       Uint32 test is still done if the length\n                       property is read-only. */\n                    if ((flags & (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) ==\n                        JS_PROP_HAS_WRITABLE) {\n                        prs = get_shape_prop(p->shape);\n                        if (js_update_property_flags(ctx, p, &prs,\n                                                     prs->flags & ~JS_PROP_WRITABLE))\n                            return -1;\n                    }\n                    return res;\n                } else {\n                    if (flags & JS_PROP_HAS_VALUE) {\n                        JS_FreeValue(ctx, pr->u.value);\n                        pr->u.value = JS_DupValue(ctx, val);\n                    }\n                    if (flags & JS_PROP_HAS_WRITABLE) {\n                        if (js_update_property_flags(ctx, p, &prs,\n                                                     (prs->flags & ~JS_PROP_WRITABLE) |\n                                                     (flags & JS_PROP_WRITABLE)))\n                            return -1;\n                    }\n                }\n            }\n        }\n        mask = 0;\n        if (flags & JS_PROP_HAS_CONFIGURABLE)\n            mask |= JS_PROP_CONFIGURABLE;\n        if (flags & JS_PROP_HAS_ENUMERABLE)\n            mask |= JS_PROP_ENUMERABLE;\n        if (js_update_property_flags(ctx, p, &prs,\n                                     (prs->flags & ~mask) | (flags & mask)))\n            return -1;\n        return TRUE;\n    }\n\n    /* handle modification of fast array elements */\n    if (p->fast_array) {\n        uint32_t idx;\n        uint32_t prop_flags;\n        if (p->class_id == JS_CLASS_ARRAY) {\n            if (__JS_AtomIsTaggedInt(prop)) {\n                idx = __JS_AtomToUInt32(prop);\n                if (idx < p->u.array.count) {\n                    prop_flags = get_prop_flags(flags, JS_PROP_C_W_E);\n                    if (prop_flags != JS_PROP_C_W_E)\n                        goto convert_to_slow_array;\n                    if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {\n                    convert_to_slow_array:\n                        if (convert_fast_array_to_array(ctx, p))\n                            return -1;\n                        else\n                            goto redo_prop_update;\n                    }\n                    if (flags & JS_PROP_HAS_VALUE) {\n                        set_value(ctx, &p->u.array.u.values[idx], JS_DupValue(ctx, val));\n                    }\n                    return TRUE;\n                }\n            }\n        } else if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n                   p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n            JSValue num;\n            int ret;\n\n            if (!__JS_AtomIsTaggedInt(prop)) {\n                /* slow path with to handle all numeric indexes */\n                num = JS_AtomIsNumericIndex1(ctx, prop);\n                if (JS_IsUndefined(num))\n                    goto typed_array_done;\n                if (JS_IsException(num))\n                    return -1;\n                ret = JS_NumberIsInteger(ctx, num);\n                if (ret < 0) {\n                    JS_FreeValue(ctx, num);\n                    return -1;\n                }\n                if (!ret) {\n                    JS_FreeValue(ctx, num);\n                    return JS_ThrowTypeErrorOrFalse(ctx, flags, \"non integer index in typed array\");\n                }\n                ret = JS_NumberIsNegativeOrMinusZero(ctx, num);\n                JS_FreeValue(ctx, num);\n                if (ret) {\n                    return JS_ThrowTypeErrorOrFalse(ctx, flags, \"negative index in typed array\");\n                }\n                if (!__JS_AtomIsTaggedInt(prop))\n                    goto typed_array_oob;\n            }\n            idx = __JS_AtomToUInt32(prop);\n            /* if the typed array is detached, p->u.array.count = 0 */\n            if (idx >= typed_array_get_length(ctx, p)) {\n            typed_array_oob:\n                return JS_ThrowTypeErrorOrFalse(ctx, flags, \"out-of-bound index in typed array\");\n            }\n            prop_flags = get_prop_flags(flags, JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n            if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET) ||\n                prop_flags != (JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE)) {\n                return JS_ThrowTypeErrorOrFalse(ctx, flags, \"invalid descriptor flags\");\n            }\n            if (flags & JS_PROP_HAS_VALUE) {\n                return JS_SetPropertyValue(ctx, this_obj, JS_NewInt32(ctx, idx), JS_DupValue(ctx, val), flags);\n            }\n            return TRUE;\n        typed_array_done: ;\n        }\n    }\n\n    return JS_CreateProperty(ctx, p, prop, val, getter, setter, flags);\n}\n\nstatic int JS_DefineAutoInitProperty(JSContext *ctx, JSValueConst this_obj,\n                                     JSAtom prop, JSAutoInitIDEnum id,\n                                     void *opaque, int flags)\n{\n    JSObject *p;\n    JSProperty *pr;\n\n    if (JS_VALUE_GET_TAG(this_obj) != JS_TAG_OBJECT)\n        return FALSE;\n\n    p = JS_VALUE_GET_OBJ(this_obj);\n\n    if (find_own_property(&pr, p, prop)) {\n        /* property already exists */\n        abort();\n        return FALSE;\n    }\n\n    /* Specialized CreateProperty */\n    pr = add_property(ctx, p, prop, (flags & JS_PROP_C_W_E) | JS_PROP_AUTOINIT);\n    if (unlikely(!pr))\n        return -1;\n    pr->u.init.realm_and_id = (uintptr_t)JS_DupContext(ctx);\n    assert((pr->u.init.realm_and_id & 3) == 0);\n    assert(id <= 3);\n    pr->u.init.realm_and_id |= id;\n    pr->u.init.opaque = opaque;\n    return TRUE;\n}\n\n/* shortcut to add or redefine a new property value */\nint JS_DefinePropertyValue(JSContext *ctx, JSValueConst this_obj,\n                           JSAtom prop, JSValue val, int flags)\n{\n    int ret;\n    ret = JS_DefineProperty(ctx, this_obj, prop, val, JS_UNDEFINED, JS_UNDEFINED,\n                            flags | JS_PROP_HAS_VALUE | JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_WRITABLE | JS_PROP_HAS_ENUMERABLE);\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nint JS_DefinePropertyValueValue(JSContext *ctx, JSValueConst this_obj,\n                                JSValue prop, JSValue val, int flags)\n{\n    JSAtom atom;\n    int ret;\n    atom = JS_ValueToAtom(ctx, prop);\n    JS_FreeValue(ctx, prop);\n    if (unlikely(atom == JS_ATOM_NULL)) {\n        JS_FreeValue(ctx, val);\n        return -1;\n    }\n    ret = JS_DefinePropertyValue(ctx, this_obj, atom, val, flags);\n    JS_FreeAtom(ctx, atom);\n    return ret;\n}\n\nint JS_DefinePropertyValueUint32(JSContext *ctx, JSValueConst this_obj,\n                                 uint32_t idx, JSValue val, int flags)\n{\n    return JS_DefinePropertyValueValue(ctx, this_obj, JS_NewUint32(ctx, idx),\n                                       val, flags);\n}\n\nint JS_DefinePropertyValueInt64(JSContext *ctx, JSValueConst this_obj,\n                                int64_t idx, JSValue val, int flags)\n{\n    return JS_DefinePropertyValueValue(ctx, this_obj, JS_NewInt64(ctx, idx),\n                                       val, flags);\n}\n\nint JS_DefinePropertyValueStr(JSContext *ctx, JSValueConst this_obj,\n                              const char *prop, JSValue val, int flags)\n{\n    JSAtom atom;\n    int ret;\n    atom = JS_NewAtom(ctx, prop);\n    ret = JS_DefinePropertyValue(ctx, this_obj, atom, val, flags);\n    JS_FreeAtom(ctx, atom);\n    return ret;\n}\n\n/* shortcut to add getter & setter */\nint JS_DefinePropertyGetSet(JSContext *ctx, JSValueConst this_obj,\n                            JSAtom prop, JSValue getter, JSValue setter,\n                            int flags)\n{\n    int ret;\n    ret = JS_DefineProperty(ctx, this_obj, prop, JS_UNDEFINED, getter, setter,\n                            flags | JS_PROP_HAS_GET | JS_PROP_HAS_SET |\n                            JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_ENUMERABLE);\n    JS_FreeValue(ctx, getter);\n    JS_FreeValue(ctx, setter);\n    return ret;\n}\n\nstatic int JS_CreateDataPropertyUint32(JSContext *ctx, JSValueConst this_obj,\n                                       int64_t idx, JSValue val, int flags)\n{\n    return JS_DefinePropertyValueValue(ctx, this_obj, JS_NewInt64(ctx, idx),\n                                       val, flags | JS_PROP_CONFIGURABLE |\n                                       JS_PROP_ENUMERABLE | JS_PROP_WRITABLE);\n}\n\n\n/* return TRUE if 'obj' has a non empty 'name' string */\nstatic BOOL js_object_has_name(JSContext *ctx, JSValueConst obj)\n{\n    JSProperty *pr;\n    JSShapeProperty *prs;\n    JSValueConst val;\n    JSString *p;\n    \n    prs = find_own_property(&pr, JS_VALUE_GET_OBJ(obj), JS_ATOM_name);\n    if (!prs)\n        return FALSE;\n    if ((prs->flags & JS_PROP_TMASK) != JS_PROP_NORMAL)\n        return TRUE;\n    val = pr->u.value;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_STRING)\n        return TRUE;\n    p = JS_VALUE_GET_STRING(val);\n    return (p->len != 0);\n}\n\nstatic int JS_DefineObjectName(JSContext *ctx, JSValueConst obj,\n                               JSAtom name, int flags)\n{\n    if (name != JS_ATOM_NULL\n    &&  JS_IsObject(obj)\n    &&  !js_object_has_name(ctx, obj)\n    &&  JS_DefinePropertyValue(ctx, obj, JS_ATOM_name, JS_AtomToString(ctx, name), flags) < 0) {\n        return -1;\n    }\n    return 0;\n}\n\nstatic int JS_DefineObjectNameComputed(JSContext *ctx, JSValueConst obj,\n                                       JSValueConst str, int flags)\n{\n    if (JS_IsObject(obj) &&\n        !js_object_has_name(ctx, obj)) {\n        JSAtom prop;\n        JSValue name_str;\n        prop = JS_ValueToAtom(ctx, str);\n        if (prop == JS_ATOM_NULL)\n            return -1;\n        name_str = js_get_function_name(ctx, prop);\n        JS_FreeAtom(ctx, prop);\n        if (JS_IsException(name_str))\n            return -1;\n        if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_name, name_str, flags) < 0)\n            return -1;\n    }\n    return 0;\n}\n\n#define DEFINE_GLOBAL_LEX_VAR (1 << 7)\n#define DEFINE_GLOBAL_FUNC_VAR (1 << 6)\n\nstatic JSValue JS_ThrowSyntaxErrorVarRedeclaration(JSContext *ctx, JSAtom prop)\n{\n    return JS_ThrowSyntaxErrorAtom(ctx, \"redeclaration of '%s'\", prop);\n}\n\n/* flags is 0, DEFINE_GLOBAL_LEX_VAR or DEFINE_GLOBAL_FUNC_VAR */\n/* XXX: could support exotic global object. */\nstatic int JS_CheckDefineGlobalVar(JSContext *ctx, JSAtom prop, int flags)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n\n    p = JS_VALUE_GET_OBJ(ctx->global_obj);\n    prs = find_own_property1(p, prop);\n    /* XXX: should handle JS_PROP_AUTOINIT */\n    if (flags & DEFINE_GLOBAL_LEX_VAR) {\n        if (prs && !(prs->flags & JS_PROP_CONFIGURABLE))\n            goto fail_redeclaration;\n    } else {\n        if (!prs && !p->extensible)\n            goto define_error;\n        if (flags & DEFINE_GLOBAL_FUNC_VAR) {\n            if (prs) {\n                if (!(prs->flags & JS_PROP_CONFIGURABLE) &&\n                    ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET ||\n                     ((prs->flags & (JS_PROP_WRITABLE | JS_PROP_ENUMERABLE)) !=\n                      (JS_PROP_WRITABLE | JS_PROP_ENUMERABLE)))) {\n                define_error:\n                    JS_ThrowTypeErrorAtom(ctx, \"cannot define variable '%s'\",\n                                          prop);\n                    return -1;\n                }\n            }\n        }\n    }\n    /* check if there already is a lexical declaration */\n    p = JS_VALUE_GET_OBJ(ctx->global_var_obj);\n    prs = find_own_property1(p, prop);\n    if (prs) {\n    fail_redeclaration:\n        JS_ThrowSyntaxErrorVarRedeclaration(ctx, prop);\n        return -1;\n    }\n    return 0;\n}\n\n/* def_flags is (0, DEFINE_GLOBAL_LEX_VAR) |\n   JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE */\n/* XXX: could support exotic global object. */\nstatic int JS_DefineGlobalVar(JSContext *ctx, JSAtom prop, int def_flags)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    JSValue val;\n    int flags;\n\n    if (def_flags & DEFINE_GLOBAL_LEX_VAR) {\n        p = JS_VALUE_GET_OBJ(ctx->global_var_obj);\n        flags = JS_PROP_ENUMERABLE | (def_flags & JS_PROP_WRITABLE) |\n            JS_PROP_CONFIGURABLE;\n        val = JS_UNINITIALIZED;\n    } else {\n        p = JS_VALUE_GET_OBJ(ctx->global_obj);\n        flags = JS_PROP_ENUMERABLE | JS_PROP_WRITABLE |\n            (def_flags & JS_PROP_CONFIGURABLE);\n        val = JS_UNDEFINED;\n    }\n    prs = find_own_property1(p, prop);\n    if (prs)\n        return 0;\n    if (!p->extensible)\n        return 0;\n    pr = add_property(ctx, p, prop, flags);\n    if (unlikely(!pr))\n        return -1;\n    pr->u.value = val;\n    return 0;\n}\n\n/* 'def_flags' is 0 or JS_PROP_CONFIGURABLE. */\n/* XXX: could support exotic global object. */\nstatic int JS_DefineGlobalFunction(JSContext *ctx, JSAtom prop,\n                                   JSValueConst func, int def_flags)\n{\n\n    JSObject *p;\n    JSShapeProperty *prs;\n    int flags;\n\n    p = JS_VALUE_GET_OBJ(ctx->global_obj);\n    prs = find_own_property1(p, prop);\n    flags = JS_PROP_HAS_VALUE | JS_PROP_THROW;\n    if (!prs || (prs->flags & JS_PROP_CONFIGURABLE)) {\n        flags |= JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | def_flags |\n            JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_WRITABLE | JS_PROP_HAS_ENUMERABLE;\n    }\n    if (JS_DefineProperty(ctx, ctx->global_obj, prop, func,\n                          JS_UNDEFINED, JS_UNDEFINED, flags) < 0)\n        return -1;\n    return 0;\n}\n\nstatic JSValue JS_GetGlobalVar(JSContext *ctx, JSAtom prop,\n                               BOOL throw_ref_error)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n\n    /* no exotic behavior is possible in global_var_obj */\n    p = JS_VALUE_GET_OBJ(ctx->global_var_obj);\n    prs = find_own_property(&pr, p, prop);\n    if (prs) {\n        /* XXX: should handle JS_PROP_TMASK properties */\n        if (unlikely(JS_IsUninitialized(pr->u.value)))\n            return JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);\n        return JS_DupValue(ctx, pr->u.value);\n    }\n    return JS_GetPropertyInternal(ctx, ctx->global_obj, prop,\n                                 ctx->global_obj, throw_ref_error);\n}\n\n/* construct a reference to a global variable */\nstatic int JS_GetGlobalVarRef(JSContext *ctx, JSAtom prop, JSValue *sp)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n\n    /* no exotic behavior is possible in global_var_obj */\n    p = JS_VALUE_GET_OBJ(ctx->global_var_obj);\n    prs = find_own_property(&pr, p, prop);\n    if (prs) {\n        /* XXX: should handle JS_PROP_AUTOINIT properties? */\n        /* XXX: conformance: do these tests in\n           OP_put_var_ref/OP_get_var_ref ? */\n        if (unlikely(JS_IsUninitialized(pr->u.value))) {\n            JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);\n            return -1;\n        }\n        if (unlikely(!(prs->flags & JS_PROP_WRITABLE))) {\n            return JS_ThrowTypeErrorReadOnly(ctx, JS_PROP_THROW, prop);\n        }\n        sp[0] = JS_DupValue(ctx, ctx->global_var_obj);\n    } else {\n        int ret;\n        ret = JS_HasProperty(ctx, ctx->global_obj, prop);\n        if (ret < 0)\n            return -1;\n        if (ret) {\n            sp[0] = JS_DupValue(ctx, ctx->global_obj);\n        } else {\n            sp[0] = JS_UNDEFINED;\n        }\n    }\n    sp[1] = JS_AtomToValue(ctx, prop);\n    return 0;\n}\n\n/* use for strict variable access: test if the variable exists */\nstatic int JS_CheckGlobalVar(JSContext *ctx, JSAtom prop)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    int ret;\n\n    /* no exotic behavior is possible in global_var_obj */\n    p = JS_VALUE_GET_OBJ(ctx->global_var_obj);\n    prs = find_own_property1(p, prop);\n    if (prs) {\n        ret = TRUE;\n    } else {\n        ret = JS_HasProperty(ctx, ctx->global_obj, prop);\n        if (ret < 0)\n            return -1;\n    }\n    return ret;\n}\n\n/* flag = 0: normal variable write\n   flag = 1: initialize lexical variable\n   flag = 2: normal variable write, strict check was done before\n*/\nstatic int JS_SetGlobalVar(JSContext *ctx, JSAtom prop, JSValue val,\n                           int flag)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    int flags;\n\n    /* no exotic behavior is possible in global_var_obj */\n    p = JS_VALUE_GET_OBJ(ctx->global_var_obj);\n    prs = find_own_property(&pr, p, prop);\n    if (prs) {\n        /* XXX: should handle JS_PROP_AUTOINIT properties? */\n        if (flag != 1) {\n            if (unlikely(JS_IsUninitialized(pr->u.value))) {\n                JS_FreeValue(ctx, val);\n                JS_ThrowReferenceErrorUninitialized(ctx, prs->atom);\n                return -1;\n            }\n            if (unlikely(!(prs->flags & JS_PROP_WRITABLE))) {\n                JS_FreeValue(ctx, val);\n                return JS_ThrowTypeErrorReadOnly(ctx, JS_PROP_THROW, prop);\n            }\n        }\n        set_value(ctx, &pr->u.value, val);\n        return 0;\n    }\n    flags = JS_PROP_THROW_STRICT;\n    if (is_strict_mode(ctx)) \n        flags |= JS_PROP_NO_ADD;\n    return JS_SetPropertyInternal(ctx, ctx->global_obj, prop, val, flags);\n}\n\n/* return -1, FALSE or TRUE. return FALSE if not configurable or\n   invalid object. return -1 in case of exception.\n   flags can be 0, JS_PROP_THROW or JS_PROP_THROW_STRICT */\nint JS_DeleteProperty(JSContext *ctx, JSValueConst obj, JSAtom prop, int flags)\n{\n    JSValue obj1;\n    JSObject *p;\n    int res;\n    \n    obj1 = JS_ToObject(ctx, obj);\n    if (JS_IsException(obj1))\n        return -1;\n    p = JS_VALUE_GET_OBJ(obj1);\n    res = delete_property(ctx, p, prop);\n    JS_FreeValue(ctx, obj1);\n    if (res != FALSE)\n        return res;\n    if ((flags & JS_PROP_THROW) ||\n        ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) {\n        JS_ThrowTypeError(ctx, \"could not delete property\");\n        return -1;\n    }\n    return FALSE;\n}\n\nint JS_DeletePropertyInt64(JSContext *ctx, JSValueConst obj, int64_t idx, int flags)\n{\n    JSAtom prop;\n    int res;\n\n    if ((uint64_t)idx <= JS_ATOM_MAX_INT) {\n        /* fast path for fast arrays */\n        return JS_DeleteProperty(ctx, obj, __JS_AtomFromUInt32(idx), flags);\n    }\n    prop = JS_NewAtomInt64(ctx, idx);\n    if (prop == JS_ATOM_NULL)\n        return -1;\n    res = JS_DeleteProperty(ctx, obj, prop, flags);\n    JS_FreeAtom(ctx, prop);\n    return res;\n}\n\nBOOL JS_IsFunction(JSContext *ctx, JSValueConst val)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(val);\n    switch(p->class_id) {\n    case JS_CLASS_BYTECODE_FUNCTION:\n        return TRUE;\n    case JS_CLASS_PROXY:\n        return p->u.proxy_data->is_func;\n    default:\n        return (ctx->rt->class_array[p->class_id].call != NULL);\n    }\n}\n\nBOOL JS_IsCFunction(JSContext *ctx, JSValueConst val, JSCFunction *func, int magic)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(val);\n    if (p->class_id == JS_CLASS_C_FUNCTION)\n        return (p->u.cfunc.c_function.generic == func && p->u.cfunc.magic == magic);\n    else\n        return FALSE;\n}\n\nBOOL JS_IsConstructor(JSContext *ctx, JSValueConst val)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(val);\n    return p->is_constructor;\n}\n\nBOOL JS_SetConstructorBit(JSContext *ctx, JSValueConst func_obj, BOOL val)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT)\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(func_obj);\n    p->is_constructor = val;\n    return TRUE;\n}\n\nBOOL JS_IsError(JSContext *ctx, JSValueConst val)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(val);\n    return (p->class_id == JS_CLASS_ERROR);\n}\n\n/* used to avoid catching interrupt exceptions */\nBOOL JS_IsUncatchableError(JSContext *ctx, JSValueConst val)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(val);\n    return p->class_id == JS_CLASS_ERROR && p->is_uncatchable_error;\n}\n\nvoid JS_SetUncatchableError(JSContext *ctx, JSValueConst val, BOOL flag)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return;\n    p = JS_VALUE_GET_OBJ(val);\n    if (p->class_id == JS_CLASS_ERROR)\n        p->is_uncatchable_error = flag;\n}\n\nvoid JS_ResetUncatchableError(JSContext *ctx)\n{\n    JS_SetUncatchableError(ctx, ctx->rt->current_exception, FALSE);\n}\n\nvoid JS_SetOpaque(JSValue obj, void *opaque)\n{\n   JSObject *p;\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        p = JS_VALUE_GET_OBJ(obj);\n        p->u.opaque = opaque;\n    }\n}\n\n/* return NULL if not an object of class class_id */\nvoid *JS_GetOpaque(JSValueConst obj, JSClassID class_id)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return NULL;\n    p = JS_VALUE_GET_OBJ(obj);\n    if (p->class_id != class_id)\n        return NULL;\n    return p->u.opaque;\n}\n\nvoid *JS_GetOpaque2(JSContext *ctx, JSValueConst obj, JSClassID class_id)\n{\n    void *p = JS_GetOpaque(obj, class_id);\n    if (unlikely(!p)) {\n        JS_ThrowTypeErrorInvalidClass(ctx, class_id);\n    }\n    return p;\n}\n\n#define HINT_STRING  0\n#define HINT_NUMBER  1\n#define HINT_NONE    2\n/* don't try Symbol.toPrimitive */\n#define HINT_FORCE_ORDINARY (1 << 4)\n\nstatic JSValue JS_ToPrimitiveFree(JSContext *ctx, JSValue val, int hint)\n{\n    int i;\n    BOOL force_ordinary;\n\n    JSAtom method_name;\n    JSValue method, ret;\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT)\n        return val;\n    force_ordinary = hint & HINT_FORCE_ORDINARY;\n    hint &= ~HINT_FORCE_ORDINARY;\n    if (!force_ordinary) {\n        method = JS_GetProperty(ctx, val, JS_ATOM_Symbol_toPrimitive);\n        if (JS_IsException(method))\n            goto exception;\n        /* ECMA says *If exoticToPrim is not undefined* but tests in\n           test262 use null as a non callable converter */\n        if (!JS_IsUndefined(method) && !JS_IsNull(method)) {\n            JSAtom atom;\n            JSValue arg;\n            switch(hint) {\n            case HINT_STRING:\n                atom = JS_ATOM_string;\n                break;\n            case HINT_NUMBER:\n                atom = JS_ATOM_number;\n                break;\n            default:\n            case HINT_NONE:\n                atom = JS_ATOM_default;\n                break;\n            }\n            arg = JS_AtomToString(ctx, atom);\n            ret = JS_CallFree(ctx, method, val, 1, (JSValueConst *)&arg);\n            JS_FreeValue(ctx, arg);\n            if (JS_IsException(ret))\n                goto exception;\n            JS_FreeValue(ctx, val);\n            if (JS_VALUE_GET_TAG(ret) != JS_TAG_OBJECT)\n                return ret;\n            JS_FreeValue(ctx, ret);\n            return JS_ThrowTypeError(ctx, \"toPrimitive\");\n        }\n    }\n    if (hint != HINT_STRING)\n        hint = HINT_NUMBER;\n    for(i = 0; i < 2; i++) {\n        if ((i ^ hint) == 0) {\n            method_name = JS_ATOM_toString;\n        } else {\n            method_name = JS_ATOM_valueOf;\n        }\n        method = JS_GetProperty(ctx, val, method_name);\n        if (JS_IsException(method))\n            goto exception;\n        if (JS_IsFunction(ctx, method)) {\n            ret = JS_CallFree(ctx, method, val, 0, NULL);\n            if (JS_IsException(ret))\n                goto exception;\n            if (JS_VALUE_GET_TAG(ret) != JS_TAG_OBJECT) {\n                JS_FreeValue(ctx, val);\n                return ret;\n            }\n            JS_FreeValue(ctx, ret);\n        } else {\n            JS_FreeValue(ctx, method);\n        }\n    }\n    JS_ThrowTypeError(ctx, \"toPrimitive\");\nexception:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ToPrimitive(JSContext *ctx, JSValueConst val, int hint)\n{\n    return JS_ToPrimitiveFree(ctx, JS_DupValue(ctx, val), hint);\n}\n\nvoid JS_SetIsHTMLDDA(JSContext *ctx, JSValueConst obj)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return;\n    p = JS_VALUE_GET_OBJ(obj);\n    p->is_HTMLDDA = TRUE;\n}\n\nstatic inline BOOL JS_IsHTMLDDA(JSContext *ctx, JSValueConst obj)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return FALSE;\n    p = JS_VALUE_GET_OBJ(obj);\n    return p->is_HTMLDDA;\n}\n                         \nstatic int JS_ToBoolFree(JSContext *ctx, JSValue val)\n{\n    uint32_t tag = JS_VALUE_GET_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n        return JS_VALUE_GET_INT(val) != 0;\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        return JS_VALUE_GET_INT(val);\n    case JS_TAG_EXCEPTION:\n        return -1;\n    case JS_TAG_STRING:\n        {\n            BOOL ret = JS_VALUE_GET_STRING(val)->len != 0;\n            JS_FreeValue(ctx, val);\n            return ret;\n        }\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            BOOL ret;\n            ret = p->num.expn != BF_EXP_ZERO && p->num.expn != BF_EXP_NAN;\n            JS_FreeValue(ctx, val);\n            return ret;\n        }\n    case JS_TAG_BIG_DECIMAL:\n        {\n            JSBigDecimal *p = JS_VALUE_GET_PTR(val);\n            BOOL ret;\n            ret = p->num.expn != BF_EXP_ZERO && p->num.expn != BF_EXP_NAN;\n            JS_FreeValue(ctx, val);\n            return ret;\n        }\n#endif\n    case JS_TAG_OBJECT:\n        {\n            JSObject *p = JS_VALUE_GET_OBJ(val);\n            BOOL ret;\n            ret = !p->is_HTMLDDA;\n            JS_FreeValue(ctx, val);\n            return ret;\n        }\n        break;\n    default:\n        if (JS_TAG_IS_FLOAT64(tag)) {\n            double d = JS_VALUE_GET_FLOAT64(val);\n            return !isnan(d) && d != 0;\n        } else {\n            JS_FreeValue(ctx, val);\n            return TRUE;\n        }\n    }\n}\n\nint JS_ToBool(JSContext *ctx, JSValueConst val)\n{\n    return JS_ToBoolFree(ctx, JS_DupValue(ctx, val));\n}\n\nstatic int skip_spaces(const char *pc)\n{\n    const uint8_t *p, *p_next, *p_start;\n    uint32_t c;\n\n    p = p_start = (const uint8_t *)pc;\n    for (;;) {\n        c = *p;\n        if (c < 128) {\n            if (!((c >= 0x09 && c <= 0x0d) || (c == 0x20)))\n                break;\n            p++;\n        } else {\n            c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p_next);\n            if (!lre_is_space(c))\n                break;\n            p = p_next;\n        }\n    }\n    return p - p_start;\n}\n\nstatic inline int to_digit(int c)\n{\n    if (c >= '0' && c <= '9')\n        return c - '0';\n    else if (c >= 'A' && c <= 'Z')\n        return c - 'A' + 10;\n    else if (c >= 'a' && c <= 'z')\n        return c - 'a' + 10;\n    else\n        return 36;\n}\n\n/* XXX: remove */\nstatic double js_strtod(const char *p, int radix, BOOL is_float)\n{\n    double d;\n    int c;\n    \n    if (!is_float || radix != 10) {\n        uint64_t n_max, n;\n        int int_exp, is_neg;\n        \n        is_neg = 0;\n        if (*p == '-') {\n            is_neg = 1;\n            p++;\n        }\n\n        /* skip leading zeros */\n        while (*p == '0')\n            p++;\n        n = 0;\n        if (radix == 10)\n            n_max = ((uint64_t)-1 - 9) / 10; /* most common case */\n        else\n            n_max = ((uint64_t)-1 - (radix - 1)) / radix;\n        /* XXX: could be more precise */\n        int_exp = 0;\n        while (*p != '\\0') {\n            c = to_digit((uint8_t)*p);\n            if (c >= radix)\n                break;\n            if (n <= n_max) {\n                n = n * radix + c;\n            } else {\n                int_exp++;\n            }\n            p++;\n        }\n        d = n;\n        if (int_exp != 0) {\n            d *= pow(radix, int_exp);\n        }\n        if (is_neg)\n            d = -d;\n    } else {\n        d = strtod(p, NULL);\n    }\n    return d;\n}\n\n#define ATOD_INT_ONLY        (1 << 0)\n/* accept Oo and Ob prefixes in addition to 0x prefix if radix = 0 */\n#define ATOD_ACCEPT_BIN_OCT  (1 << 2)\n/* accept O prefix as octal if radix == 0 and properly formed (Annex B) */\n#define ATOD_ACCEPT_LEGACY_OCTAL  (1 << 4)\n/* accept _ between digits as a digit separator */\n#define ATOD_ACCEPT_UNDERSCORES  (1 << 5)\n/* allow a suffix to override the type */\n#define ATOD_ACCEPT_SUFFIX    (1 << 6) \n/* default type */\n#define ATOD_TYPE_MASK        (3 << 7)\n#define ATOD_TYPE_FLOAT64     (0 << 7)\n#define ATOD_TYPE_BIG_INT     (1 << 7)\n#define ATOD_TYPE_BIG_FLOAT   (2 << 7)\n#define ATOD_TYPE_BIG_DECIMAL (3 << 7)\n/* assume bigint mode: floats are parsed as integers if no decimal\n   point nor exponent */\n#define ATOD_MODE_BIGINT      (1 << 9) \n/* accept -0x1 */\n#define ATOD_ACCEPT_PREFIX_AFTER_SIGN (1 << 10)\n\n#ifdef CONFIG_BIGNUM\nstatic JSValue js_string_to_bigint(JSContext *ctx, const char *buf,\n                                   int radix, int flags, slimb_t *pexponent)\n{\n    bf_t a_s, *a = &a_s;\n    int ret;\n    JSValue val;\n    val = JS_NewBigInt(ctx);\n    if (JS_IsException(val))\n        return val;\n    a = JS_GetBigInt(val);\n    ret = bf_atof(a, buf, NULL, radix, BF_PREC_INF, BF_RNDZ);\n    if (ret & BF_ST_MEM_ERROR) {\n        JS_FreeValue(ctx, val);\n        return JS_ThrowOutOfMemory(ctx);\n    }\n    val = JS_CompactBigInt1(ctx, val, (flags & ATOD_MODE_BIGINT) != 0);\n    return val;\n}\n\nstatic JSValue js_string_to_bigfloat(JSContext *ctx, const char *buf,\n                                     int radix, int flags, slimb_t *pexponent)\n{\n    bf_t *a;\n    int ret;\n    JSValue val;\n    \n    val = JS_NewBigFloat(ctx);\n    if (JS_IsException(val))\n        return val;\n    a = JS_GetBigFloat(val);\n    if (flags & ATOD_ACCEPT_SUFFIX) {\n        /* return the exponent to get infinite precision */\n        ret = bf_atof2(a, pexponent, buf, NULL, radix, BF_PREC_INF,\n                       BF_RNDZ | BF_ATOF_EXPONENT);\n    } else {\n        ret = bf_atof(a, buf, NULL, radix, ctx->fp_env.prec,\n                      ctx->fp_env.flags);\n    }\n    if (ret & BF_ST_MEM_ERROR) {\n        JS_FreeValue(ctx, val);\n        return JS_ThrowOutOfMemory(ctx);\n    }\n    return val;\n}\n\nstatic JSValue js_string_to_bigdecimal(JSContext *ctx, const char *buf,\n                                       int radix, int flags, slimb_t *pexponent)\n{\n    bfdec_t *a;\n    int ret;\n    JSValue val;\n    \n    val = JS_NewBigDecimal(ctx);\n    if (JS_IsException(val))\n        return val;\n    a = JS_GetBigDecimal(val);\n    ret = bfdec_atof(a, buf, NULL, BF_PREC_INF,\n                     BF_RNDZ | BF_ATOF_NO_NAN_INF);\n    if (ret & BF_ST_MEM_ERROR) {\n        JS_FreeValue(ctx, val);\n        return JS_ThrowOutOfMemory(ctx);\n    }\n    return val;\n}\n\n#endif\n\n/* return an exception in case of memory error. Return JS_NAN if\n   invalid syntax */\n#ifdef CONFIG_BIGNUM\nstatic JSValue js_atof2(JSContext *ctx, const char *str, const char **pp,\n                        int radix, int flags, slimb_t *pexponent)\n#else\nstatic JSValue js_atof(JSContext *ctx, const char *str, const char **pp,\n                       int radix, int flags)\n#endif\n{\n    const char *p, *p_start;\n    int sep, is_neg;\n    BOOL is_float, has_legacy_octal;\n    int atod_type = flags & ATOD_TYPE_MASK;\n    char buf1[64], *buf;\n    int i, j, len;\n    BOOL buf_allocated = FALSE;\n    JSValue val;\n    \n    /* optional separator between digits */\n    sep = (flags & ATOD_ACCEPT_UNDERSCORES) ? '_' : 256;\n    has_legacy_octal = FALSE;\n    \n    p = str;\n    p_start = p;\n    is_neg = 0;\n    if (p[0] == '+') {\n        p++;\n        p_start++;\n        if (!(flags & ATOD_ACCEPT_PREFIX_AFTER_SIGN))\n            goto no_radix_prefix;\n    } else if (p[0] == '-') {\n        p++;\n        p_start++;\n        is_neg = 1;\n        if (!(flags & ATOD_ACCEPT_PREFIX_AFTER_SIGN))\n            goto no_radix_prefix;\n    }\n    if (p[0] == '0') {\n        if ((p[1] == 'x' || p[1] == 'X') &&\n            (radix == 0 || radix == 16)) {\n            p += 2;\n            radix = 16;\n        } else if ((p[1] == 'o' || p[1] == 'O') &&\n                   radix == 0 && (flags & ATOD_ACCEPT_BIN_OCT)) {\n            p += 2;\n            radix = 8;\n        } else if ((p[1] == 'b' || p[1] == 'B') &&\n                   radix == 0 && (flags & ATOD_ACCEPT_BIN_OCT)) {\n            p += 2;\n            radix = 2;\n        } else if ((p[1] >= '0' && p[1] <= '9') &&\n                   radix == 0 && (flags & ATOD_ACCEPT_LEGACY_OCTAL)) {\n            int i;\n            has_legacy_octal = TRUE;\n            sep = 256;\n            for (i = 1; (p[i] >= '0' && p[i] <= '7'); i++)\n                continue;\n            if (p[i] == '8' || p[i] == '9')\n                goto no_prefix;\n            p += 1;\n            radix = 8;\n        } else {\n            goto no_prefix;\n        }\n        /* there must be a digit after the prefix */\n        if (to_digit((uint8_t)*p) >= radix)\n            goto fail;\n    no_prefix: ;\n    } else {\n no_radix_prefix:\n        if (!(flags & ATOD_INT_ONLY) &&\n            (atod_type == ATOD_TYPE_FLOAT64 ||\n             atod_type == ATOD_TYPE_BIG_FLOAT) &&\n            strstart(p, \"Infinity\", &p)) {\n#ifdef CONFIG_BIGNUM\n            if (atod_type == ATOD_TYPE_BIG_FLOAT) {\n                bf_t *a;\n                val = JS_NewBigFloat(ctx);\n                if (JS_IsException(val))\n                    goto done;\n                a = JS_GetBigFloat(val);\n                bf_set_inf(a, is_neg);\n            } else\n#endif\n            {\n#ifdef _MSC_VER\n                double d = INFINITY;\n#else\n                double d = 1.0 / 0.0;\n#endif\n                if (is_neg)\n                    d = -d;\n                val = JS_NewFloat64(ctx, d);\n            }\n            goto done;\n        }\n    }\n    if (radix == 0)\n        radix = 10;\n    is_float = FALSE;\n    p_start = p;\n    while (to_digit((uint8_t)*p) < radix\n           ||  (*p == sep && (radix != 10 ||\n                              p != p_start + 1 || p[-1] != '0') &&\n                to_digit((uint8_t)p[1]) < radix)) {\n        p++;\n    }\n    if (!(flags & ATOD_INT_ONLY)) {\n        if (*p == '.' && (p > p_start || to_digit((uint8_t)p[1]) < radix)) {\n            is_float = TRUE;\n            p++;\n            if (*p == sep)\n                goto fail;\n            while (to_digit((uint8_t)*p) < radix ||\n                   (*p == sep && to_digit((uint8_t)p[1]) < radix))\n                p++;\n        }\n        if (p > p_start &&\n            (((*p == 'e' || *p == 'E') && radix == 10) ||\n             ((*p == 'p' || *p == 'P') && (radix == 2 || radix == 8 || radix == 16)))) {\n            const char *p1 = p + 1;\n            is_float = TRUE;\n            if (*p1 == '+') {\n                p1++;\n            } else if (*p1 == '-') {\n                p1++;\n            }\n            if (is_digit((uint8_t)*p1)) {\n                p = p1 + 1;\n                while (is_digit((uint8_t)*p) || (*p == sep && is_digit((uint8_t)p[1])))\n                    p++;\n            }\n        }\n    }\n    if (p == p_start)\n        goto fail;\n\n    buf = buf1;\n    buf_allocated = FALSE;\n    len = p - p_start;\n    if (unlikely((len + 2) > sizeof(buf1))) {\n        buf = js_malloc_rt(ctx->rt, len + 2); /* no exception raised */\n        if (!buf)\n            goto mem_error;\n        buf_allocated = TRUE;\n    }\n    /* remove the separators and the radix prefixes */\n    j = 0;\n    if (is_neg)\n        buf[j++] = '-';\n    for (i = 0; i < len; i++) {\n        if (p_start[i] != '_')\n            buf[j++] = p_start[i];\n    }\n    buf[j] = '\\0';\n\n#ifdef CONFIG_BIGNUM\n    if (flags & ATOD_ACCEPT_SUFFIX) {\n        if (*p == 'n') {\n            p++;\n            atod_type = ATOD_TYPE_BIG_INT;\n        } else if (*p == 'l') {\n            p++;\n            atod_type = ATOD_TYPE_BIG_FLOAT;\n        } else if (*p == 'm') {\n            p++;\n            atod_type = ATOD_TYPE_BIG_DECIMAL;\n        } else {\n            if (flags & ATOD_MODE_BIGINT) {\n                if (!is_float)\n                    atod_type = ATOD_TYPE_BIG_INT;\n                if (has_legacy_octal)\n                    goto fail;\n            } else {\n                if (is_float && radix != 10)\n                    goto fail;\n            }\n        }\n    } else {\n        if (atod_type == ATOD_TYPE_FLOAT64) {\n            if (flags & ATOD_MODE_BIGINT) {\n                if (!is_float)\n                    atod_type = ATOD_TYPE_BIG_INT;\n                if (has_legacy_octal)\n                    goto fail;\n            } else {\n                if (is_float && radix != 10)\n                    goto fail;\n            }\n        }\n    }\n\n    switch(atod_type) {\n    case ATOD_TYPE_FLOAT64:\n        {\n            double d;\n            d = js_strtod(buf, radix, is_float);\n            /* return int or float64 */\n            val = JS_NewFloat64(ctx, d);\n        }\n        break;\n    case ATOD_TYPE_BIG_INT:\n        if (has_legacy_octal || is_float)\n            goto fail;\n        val = ctx->rt->bigint_ops.from_string(ctx, buf, radix, flags, NULL);\n        break;\n    case ATOD_TYPE_BIG_FLOAT:\n        if (has_legacy_octal)\n            goto fail;\n        val = ctx->rt->bigfloat_ops.from_string(ctx, buf, radix, flags,\n                                                pexponent);\n        break;\n    case ATOD_TYPE_BIG_DECIMAL:\n        if (radix != 10)\n            goto fail;\n        val = ctx->rt->bigdecimal_ops.from_string(ctx, buf, radix, flags, NULL);\n        break;\n    default:\n        abort();\n    }\n#else\n    {\n        double d;\n        (void)has_legacy_octal;\n        if (is_float && radix != 10)\n            goto fail;\n        d = js_strtod(buf, radix, is_float);\n        val = JS_NewFloat64(ctx, d);\n    }\n#endif\n    \ndone:\n    if (buf_allocated)\n        js_free_rt(ctx->rt, buf);\n    if (pp)\n        *pp = p;\n    return val;\n fail:\n    val = JS_NAN;\n    goto done;\n mem_error:\n    val = JS_ThrowOutOfMemory(ctx);\n    goto done;\n}\n\n#ifdef CONFIG_BIGNUM\nstatic JSValue js_atof(JSContext *ctx, const char *str, const char **pp,\n                       int radix, int flags)\n{\n    return js_atof2(ctx, str, pp, radix, flags, NULL);\n}\n#endif\n\ntypedef enum JSToNumberHintEnum {\n    TON_FLAG_NUMBER,\n    TON_FLAG_NUMERIC,\n} JSToNumberHintEnum;\n\nstatic JSValue JS_ToNumberHintFree(JSContext *ctx, JSValue val,\n                                   JSToNumberHintEnum flag)\n{\n    uint32_t tag;\n    JSValue ret;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_DECIMAL:\n        if (flag != TON_FLAG_NUMERIC) {\n            JS_FreeValue(ctx, val);\n            return JS_ThrowTypeError(ctx, \"cannot convert bigdecimal to number\");\n        }\n        ret = val;\n        break;\n    case JS_TAG_BIG_INT:\n        if (flag != TON_FLAG_NUMERIC) {\n            JS_FreeValue(ctx, val);\n            return JS_ThrowTypeError(ctx, \"cannot convert bigint to number\");\n        }\n        ret = val;\n        break;\n    case JS_TAG_BIG_FLOAT:\n        if (flag != TON_FLAG_NUMERIC) {\n            JS_FreeValue(ctx, val);\n            return JS_ThrowTypeError(ctx, \"cannot convert bigfloat to number\");\n        }\n        ret = val;\n        break;\n#endif\n    case JS_TAG_FLOAT64:\n    case JS_TAG_INT:\n    case JS_TAG_EXCEPTION:\n        ret = val;\n        break;\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n        ret = JS_NewInt32(ctx, JS_VALUE_GET_INT(val));\n        break;\n    case JS_TAG_UNDEFINED:\n        ret = JS_NAN;\n        break;\n    case JS_TAG_OBJECT:\n        val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER);\n        if (JS_IsException(val))\n            return JS_EXCEPTION;\n        goto redo;\n    case JS_TAG_STRING:\n        {\n            const char *str;\n            const char *p;\n            size_t len;\n            \n            str = JS_ToCStringLen(ctx, &len, val);\n            JS_FreeValue(ctx, val);\n            if (!str)\n                return JS_EXCEPTION;\n            p = str;\n            p += skip_spaces(p);\n            if ((p - str) == len) {\n                ret = JS_NewInt32(ctx, 0);\n            } else {\n                int flags = ATOD_ACCEPT_BIN_OCT;\n                ret = js_atof(ctx, p, &p, 0, flags);\n                if (!JS_IsException(ret)) {\n                    p += skip_spaces(p);\n                    if ((p - str) != len) {\n                        JS_FreeValue(ctx, ret);\n                        ret = JS_NAN;\n                    }\n                }\n            }\n            JS_FreeCString(ctx, str);\n        }\n        break;\n    case JS_TAG_SYMBOL:\n        JS_FreeValue(ctx, val);\n        return JS_ThrowTypeError(ctx, \"cannot convert symbol to number\");\n    default:\n        JS_FreeValue(ctx, val);\n        ret = JS_NAN;\n        break;\n    }\n    return ret;\n}\n\nstatic JSValue JS_ToNumberFree(JSContext *ctx, JSValue val)\n{\n    return JS_ToNumberHintFree(ctx, val, TON_FLAG_NUMBER);\n}\n\nstatic JSValue JS_ToNumericFree(JSContext *ctx, JSValue val)\n{\n    return JS_ToNumberHintFree(ctx, val, TON_FLAG_NUMERIC);\n}\n\nstatic JSValue JS_ToNumeric(JSContext *ctx, JSValueConst val)\n{\n    return JS_ToNumericFree(ctx, JS_DupValue(ctx, val));\n}\n\nstatic __exception int __JS_ToFloat64Free(JSContext *ctx, double *pres,\n                                          JSValue val)\n{\n    double d;\n    uint32_t tag;\n\n    val = JS_ToNumberFree(ctx, val);\n    if (JS_IsException(val)) {\n        *pres = JS_FLOAT64_NAN;\n        return -1;\n    }\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n        d = JS_VALUE_GET_INT(val);\n        break;\n    case JS_TAG_FLOAT64:\n        d = JS_VALUE_GET_FLOAT64(val);\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            /* XXX: there can be a double rounding issue with some\n               primitives (such as JS_ToUint8ClampFree()), but it is\n               not critical to fix it. */\n            bf_get_float64(&p->num, &d, BF_RNDN);\n            JS_FreeValue(ctx, val);\n        }\n        break;\n#endif\n    default:\n        abort();\n    }\n    *pres = d;\n    return 0;\n}\n\nstatic inline int JS_ToFloat64Free(JSContext *ctx, double *pres, JSValue val)\n{\n    uint32_t tag;\n\n    tag = JS_VALUE_GET_TAG(val);\n    if (tag <= JS_TAG_NULL) {\n        *pres = JS_VALUE_GET_INT(val);\n        return 0;\n    } else if (JS_TAG_IS_FLOAT64(tag)) {\n        *pres = JS_VALUE_GET_FLOAT64(val);\n        return 0;\n    } else {\n        return __JS_ToFloat64Free(ctx, pres, val);\n    }\n}\n\nint JS_ToFloat64(JSContext *ctx, double *pres, JSValueConst val)\n{\n    return JS_ToFloat64Free(ctx, pres, JS_DupValue(ctx, val));\n}\n\nstatic JSValue JS_ToNumber(JSContext *ctx, JSValueConst val)\n{\n    return JS_ToNumberFree(ctx, JS_DupValue(ctx, val));\n}\n\n/* same as JS_ToNumber() but return 0 in case of NaN/Undefined */\nstatic __maybe_unused JSValue JS_ToIntegerFree(JSContext *ctx, JSValue val)\n{\n    uint32_t tag;\n    JSValue ret;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        ret = JS_NewInt32(ctx, JS_VALUE_GET_INT(val));\n        break;\n    case JS_TAG_FLOAT64:\n        {\n            double d = JS_VALUE_GET_FLOAT64(val);\n            if (isnan(d)) {\n                ret = JS_NewInt32(ctx, 0);\n            } else {\n                /* convert -0 to +0 */\n                d = trunc(d) + 0.0;\n                ret = JS_NewFloat64(ctx, d);\n            }\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_FLOAT:\n        {\n            bf_t a_s, *a, r_s, *r = &r_s;\n            BOOL is_nan;\n\n            a = JS_ToBigFloat(ctx, &a_s, val);\n            if (!bf_is_finite(a)) {\n                is_nan = bf_is_nan(a);\n                if (is_nan)\n                    ret = JS_NewInt32(ctx, 0);\n                else\n                    ret = JS_DupValue(ctx, val);\n            } else {\n                ret = JS_NewBigInt(ctx);\n                if (!JS_IsException(ret)) {\n                    r = JS_GetBigInt(ret);\n                    bf_set(r, a);\n                    bf_rint(r, BF_RNDZ);\n                    ret = JS_CompactBigInt(ctx, ret);\n                }\n            }\n            if (a == &a_s)\n                bf_delete(a);\n            JS_FreeValue(ctx, val);\n        }\n        break;\n#endif\n    default:\n        val = JS_ToNumberFree(ctx, val);\n        if (JS_IsException(val))\n            return val;\n        goto redo;\n    }\n    return ret;\n}\n\n/* Note: the integer value is satured to 32 bits */\nstatic int JS_ToInt32SatFree(JSContext *ctx, int *pres, JSValue val)\n{\n    uint32_t tag;\n    int ret;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        ret = JS_VALUE_GET_INT(val);\n        break;\n    case JS_TAG_EXCEPTION:\n        *pres = 0;\n        return -1;\n    case JS_TAG_FLOAT64:\n        {\n            double d = JS_VALUE_GET_FLOAT64(val);\n            if (isnan(d)) {\n                ret = 0;\n            } else {\n                if (d < INT32_MIN)\n                    ret = INT32_MIN;\n                else if (d > INT32_MAX)\n                    ret = INT32_MAX;\n                else\n                    ret = (int)d;\n            }\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            bf_get_int32(&ret, &p->num, 0);\n            JS_FreeValue(ctx, val);\n        }\n        break;\n#endif\n    default:\n        val = JS_ToNumberFree(ctx, val);\n        if (JS_IsException(val)) {\n            *pres = 0;\n            return -1;\n        }\n        goto redo;\n    }\n    *pres = ret;\n    return 0;\n}\n\nint JS_ToInt32Sat(JSContext *ctx, int *pres, JSValueConst val)\n{\n    return JS_ToInt32SatFree(ctx, pres, JS_DupValue(ctx, val));\n}\n\nint JS_ToInt32Clamp(JSContext *ctx, int *pres, JSValueConst val,\n                    int min, int max, int min_offset)\n{\n    int res = JS_ToInt32SatFree(ctx, pres, JS_DupValue(ctx, val));\n    if (res == 0) {\n        if (*pres < min) {\n            *pres += min_offset;\n            if (*pres < min)\n                *pres = min;\n        } else {\n            if (*pres > max)\n                *pres = max;\n        }\n    }\n    return res;\n}\n\nstatic int JS_ToInt64SatFree(JSContext *ctx, int64_t *pres, JSValue val)\n{\n    uint32_t tag;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        *pres = JS_VALUE_GET_INT(val);\n        return 0;\n    case JS_TAG_EXCEPTION:\n        *pres = 0;\n        return -1;\n    case JS_TAG_FLOAT64:\n        {\n            double d = JS_VALUE_GET_FLOAT64(val);\n            if (isnan(d)) {\n                *pres = 0;\n            } else {\n                if (d < INT64_MIN)\n                    *pres = INT64_MIN;\n                else if (d > INT64_MAX)\n                    *pres = INT64_MAX;\n                else\n                    *pres = (int64_t)d;\n            }\n        }\n        return 0;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            bf_get_int64(pres, &p->num, 0);\n            JS_FreeValue(ctx, val);\n        }\n        return 0;\n#endif\n    default:\n        val = JS_ToNumberFree(ctx, val);\n        if (JS_IsException(val)) {\n            *pres = 0;\n            return -1;\n        }\n        goto redo;\n    }\n}\n\nint JS_ToInt64Sat(JSContext *ctx, int64_t *pres, JSValueConst val)\n{\n    return JS_ToInt64SatFree(ctx, pres, JS_DupValue(ctx, val));\n}\n\nint JS_ToInt64Clamp(JSContext *ctx, int64_t *pres, JSValueConst val,\n                    int64_t min, int64_t max, int64_t neg_offset)\n{\n    int res = JS_ToInt64SatFree(ctx, pres, JS_DupValue(ctx, val));\n    if (res == 0) {\n        if (*pres < 0)\n            *pres += neg_offset;\n        if (*pres < min)\n            *pres = min;\n        else if (*pres > max)\n            *pres = max;\n    }\n    return res;\n}\n\n/* Same as JS_ToInt32Free() but with a 64 bit result. Return (<0, 0)\n   in case of exception */\nstatic int JS_ToInt64Free(JSContext *ctx, int64_t *pres, JSValue val)\n{\n    uint32_t tag;\n    int64_t ret;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        ret = JS_VALUE_GET_INT(val);\n        break;\n    case JS_TAG_FLOAT64:\n        {\n            JSFloat64Union u;\n            double d;\n            int e;\n            d = JS_VALUE_GET_FLOAT64(val);\n            u.d = d;\n            /* we avoid doing fmod(x, 2^64) */\n            e = (u.u64 >> 52) & 0x7ff;\n            if (likely(e <= (1023 + 62))) {\n                /* fast case */\n                ret = (int64_t)d;\n            } else if (e <= (1023 + 62 + 53)) {\n                uint64_t v;\n                /* remainder modulo 2^64 */\n                v = (u.u64 & (((uint64_t)1 << 52) - 1)) | ((uint64_t)1 << 52);\n                ret = v << ((e - 1023) - 52);\n                /* take the sign into account */\n                if (u.u64 >> 63)\n                    ret = -ret;\n            } else {\n                ret = 0; /* also handles NaN and +inf */\n            }\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            bf_get_int64(&ret, &p->num, BF_GET_INT_MOD);\n            JS_FreeValue(ctx, val);\n        }\n        break;\n#endif\n    default:\n        val = JS_ToNumberFree(ctx, val);\n        if (JS_IsException(val)) {\n            *pres = 0;\n            return -1;\n        }\n        goto redo;\n    }\n    *pres = ret;\n    return 0;\n}\n\nint JS_ToInt64(JSContext *ctx, int64_t *pres, JSValueConst val)\n{\n    return JS_ToInt64Free(ctx, pres, JS_DupValue(ctx, val));\n}\n\nint JS_ToInt64Ext(JSContext *ctx, int64_t *pres, JSValueConst val)\n{\n    if (JS_IsBigInt(ctx, val))\n        return JS_ToBigInt64(ctx, pres, val);\n    else\n        return JS_ToInt64(ctx, pres, val);\n}\n\n/* return (<0, 0) in case of exception */\nstatic int JS_ToInt32Free(JSContext *ctx, int32_t *pres, JSValue val)\n{\n    uint32_t tag;\n    int32_t ret;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        ret = JS_VALUE_GET_INT(val);\n        break;\n    case JS_TAG_FLOAT64:\n        {\n            JSFloat64Union u;\n            double d;\n            int e;\n            d = JS_VALUE_GET_FLOAT64(val);\n            u.d = d;\n            /* we avoid doing fmod(x, 2^32) */\n            e = (u.u64 >> 52) & 0x7ff;\n            if (likely(e <= (1023 + 30))) {\n                /* fast case */\n                ret = (int32_t)d;\n            } else if (e <= (1023 + 30 + 53)) {\n                uint64_t v;\n                /* remainder modulo 2^32 */\n                v = (u.u64 & (((uint64_t)1 << 52) - 1)) | ((uint64_t)1 << 52);\n                v = v << ((e - 1023) - 52 + 32);\n                ret = v >> 32;\n                /* take the sign into account */\n                if (u.u64 >> 63)\n                    ret = -ret;\n            } else {\n                ret = 0; /* also handles NaN and +inf */\n            }\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            bf_get_int32(&ret, &p->num, BF_GET_INT_MOD);\n            JS_FreeValue(ctx, val);\n        }\n        break;\n#endif\n    default:\n        val = JS_ToNumberFree(ctx, val);\n        if (JS_IsException(val)) {\n            *pres = 0;\n            return -1;\n        }\n        goto redo;\n    }\n    *pres = ret;\n    return 0;\n}\n\nint JS_ToInt32(JSContext *ctx, int32_t *pres, JSValueConst val)\n{\n    return JS_ToInt32Free(ctx, pres, JS_DupValue(ctx, val));\n}\n\nstatic inline int JS_ToUint32Free(JSContext *ctx, uint32_t *pres, JSValue val)\n{\n    return JS_ToInt32Free(ctx, (int32_t *)pres, val);\n}\n\nstatic int JS_ToUint8ClampFree(JSContext *ctx, int32_t *pres, JSValue val)\n{\n    uint32_t tag;\n    int res;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        res = JS_VALUE_GET_INT(val);\n#ifdef CONFIG_BIGNUM\n    int_clamp:\n#endif\n        res = max_int(0, min_int(255, res));\n        break;\n    case JS_TAG_FLOAT64:\n        {\n            double d = JS_VALUE_GET_FLOAT64(val);\n            if (isnan(d)) {\n                res = 0;\n            } else {\n                if (d < 0)\n                    res = 0;\n                else if (d > 255)\n                    res = 255;\n                else\n                    res = lrint(d);\n            }\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            bf_t r_s, *r = &r_s;\n            bf_init(ctx->bf_ctx, r);\n            bf_set(r, &p->num);\n            bf_rint(r, BF_RNDN);\n            bf_get_int32(&res, r, 0);\n            bf_delete(r);\n            JS_FreeValue(ctx, val);\n        }\n        goto int_clamp;\n#endif\n    default:\n        val = JS_ToNumberFree(ctx, val);\n        if (JS_IsException(val)) {\n            *pres = 0;\n            return -1;\n        }\n        goto redo;\n    }\n    *pres = res;\n    return 0;\n}\n\nstatic __exception int JS_ToArrayLengthFree(JSContext *ctx, uint32_t *plen,\n                                            JSValue val, BOOL is_array_ctor)\n{\n    uint32_t tag, len;\n\n    tag = JS_VALUE_GET_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n        {\n            int v;\n            v = JS_VALUE_GET_INT(val);\n            if (v < 0)\n                goto fail;\n            len = v;\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            bf_t a;\n            BOOL res;\n            bf_get_int32((int32_t *)&len, &p->num, BF_GET_INT_MOD);\n            bf_init(ctx->bf_ctx, &a);\n            bf_set_ui(&a, len);\n            res = bf_cmp_eq(&a, &p->num);\n            bf_delete(&a);\n            JS_FreeValue(ctx, val);\n            if (!res)\n                goto fail;\n        }\n        break;\n#endif\n    default:\n        if (JS_TAG_IS_FLOAT64(tag)) {\n            double d;\n            d = JS_VALUE_GET_FLOAT64(val);\n            len = (uint32_t)d;\n            if (len != d)\n                goto fail;\n        } else {\n            uint32_t len1;\n\n            if (is_array_ctor) {\n                val = JS_ToNumberFree(ctx, val);\n                if (JS_IsException(val))\n                    return -1;\n                /* cannot recurse because val is a number */\n                if (JS_ToArrayLengthFree(ctx, &len, val, TRUE))\n                    return -1;\n            } else {\n                /* legacy behavior: must do the conversion twice and compare */\n                if (JS_ToUint32(ctx, &len, val)) {\n                    JS_FreeValue(ctx, val);\n                    return -1;\n                }\n                val = JS_ToNumberFree(ctx, val);\n                if (JS_IsException(val))\n                    return -1;\n                /* cannot recurse because val is a number */\n                if (JS_ToArrayLengthFree(ctx, &len1, val, FALSE))\n                    return -1;\n                if (len1 != len) {\n                fail:\n                    JS_ThrowRangeError(ctx, \"invalid array length\");\n                    return -1;\n                }\n            }\n        }\n        break;\n    }\n    *plen = len;\n    return 0;\n}\n\n#define MAX_SAFE_INTEGER (((int64_t)1 << 53) - 1)\n\nstatic BOOL is_safe_integer(double d)\n{\n    return isfinite(d) && floor(d) == d &&\n        fabs(d) <= (double)MAX_SAFE_INTEGER;\n}\n\nint JS_ToIndex(JSContext *ctx, uint64_t *plen, JSValueConst val)\n{\n    int64_t v;\n    if (JS_ToInt64Sat(ctx, &v, val))\n        return -1;\n    if (v < 0 || v > MAX_SAFE_INTEGER) {\n        JS_ThrowRangeError(ctx, \"invalid array index\");\n        *plen = 0;\n        return -1;\n    }\n    *plen = v;\n    return 0;\n}\n\n/* convert a value to a length between 0 and MAX_SAFE_INTEGER.\n   return -1 for exception */\nstatic __exception int JS_ToLengthFree(JSContext *ctx, int64_t *plen,\n                                       JSValue val)\n{\n    int res = JS_ToInt64Clamp(ctx, plen, val, 0, MAX_SAFE_INTEGER, 0);\n    JS_FreeValue(ctx, val);\n    return res;\n}\n\n/* Note: can return an exception */\nstatic int JS_NumberIsInteger(JSContext *ctx, JSValueConst val)\n{\n    double d;\n    if (!JS_IsNumber(val))\n        return FALSE;\n    if (unlikely(JS_ToFloat64(ctx, &d, val)))\n        return -1;\n    return isfinite(d) && floor(d) == d;\n}\n\nstatic BOOL JS_NumberIsNegativeOrMinusZero(JSContext *ctx, JSValueConst val)\n{\n    uint32_t tag;\n\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n        {\n            int v;\n            v = JS_VALUE_GET_INT(val);\n            return (v < 0);\n        }\n    case JS_TAG_FLOAT64:\n        {\n            JSFloat64Union u;\n            u.d = JS_VALUE_GET_FLOAT64(val);\n            return (u.u64 >> 63);\n        }\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            /* Note: integer zeros are not necessarily positive */\n            return p->num.sign && !bf_is_zero(&p->num);\n        }\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            return p->num.sign;\n        }\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        {\n            JSBigDecimal *p = JS_VALUE_GET_PTR(val);\n            return p->num.sign;\n        }\n        break;\n#endif\n    default:\n        return FALSE;\n    }\n}\n\n#ifdef CONFIG_BIGNUM\n\nstatic JSValue js_bigint_to_string1(JSContext *ctx, JSValueConst val, int radix)\n{\n    JSValue ret;\n    bf_t a_s, *a;\n    char *str;\n    int saved_sign;\n\n    a = JS_ToBigInt(ctx, &a_s, val);\n    if (!a)\n        return JS_EXCEPTION;\n    saved_sign = a->sign;\n    if (a->expn == BF_EXP_ZERO)\n        a->sign = 0;\n    str = bf_ftoa(NULL, a, radix, 0, BF_RNDZ | BF_FTOA_FORMAT_FRAC |\n                  BF_FTOA_JS_QUIRKS);\n    a->sign = saved_sign;\n    JS_FreeBigInt(ctx, a, &a_s);\n    if (!str)\n        return JS_ThrowOutOfMemory(ctx);\n    ret = JS_NewString(ctx, str);\n    bf_free(ctx->bf_ctx, str);\n    return ret;\n}\n\nstatic JSValue js_bigint_to_string(JSContext *ctx, JSValueConst val)\n{\n    return js_bigint_to_string1(ctx, val, 10);\n}\n\nstatic JSValue js_ftoa(JSContext *ctx, JSValueConst val1, int radix,\n                       limb_t prec, bf_flags_t flags)\n{\n    JSValue val, ret;\n    bf_t a_s, *a;\n    char *str;\n    int saved_sign;\n\n    val = JS_ToNumeric(ctx, val1);\n    if (JS_IsException(val))\n        return val;\n    a = JS_ToBigFloat(ctx, &a_s, val);\n    saved_sign = a->sign;\n    if (a->expn == BF_EXP_ZERO)\n        a->sign = 0;\n    flags |= BF_FTOA_JS_QUIRKS;\n    if ((flags & BF_FTOA_FORMAT_MASK) == BF_FTOA_FORMAT_FREE_MIN) {\n        /* Note: for floating point numbers with a radix which is not\n           a power of two, the current precision is used to compute\n           the number of digits. */\n        if ((radix & (radix - 1)) != 0) {\n            bf_t r_s, *r = &r_s;\n            int prec, flags1;\n            /* must round first */\n            if (JS_VALUE_GET_TAG(val) == JS_TAG_BIG_FLOAT) {\n                prec = ctx->fp_env.prec;\n                flags1 = ctx->fp_env.flags &\n                    (BF_FLAG_SUBNORMAL | (BF_EXP_BITS_MASK << BF_EXP_BITS_SHIFT));\n            } else {\n                prec = 53;\n                flags1 = bf_set_exp_bits(11) | BF_FLAG_SUBNORMAL;\n            }\n            bf_init(ctx->bf_ctx, r);\n            bf_set(r, a);\n            bf_round(r, prec, flags1 | BF_RNDN);\n            str = bf_ftoa(NULL, r, radix, prec, flags1 | flags);\n            bf_delete(r);\n        } else {\n            str = bf_ftoa(NULL, a, radix, BF_PREC_INF, flags);\n        }\n    } else {\n        str = bf_ftoa(NULL, a, radix, prec, flags);\n    }\n    a->sign = saved_sign;\n    if (a == &a_s)\n        bf_delete(a);\n    JS_FreeValue(ctx, val);\n    if (!str)\n        return JS_ThrowOutOfMemory(ctx);\n    ret = JS_NewString(ctx, str);\n    bf_free(ctx->bf_ctx, str);\n    return ret;\n}\n\nstatic JSValue js_bigfloat_to_string(JSContext *ctx, JSValueConst val)\n{\n    return js_ftoa(ctx, val, 10, 0, BF_RNDN | BF_FTOA_FORMAT_FREE_MIN);\n}\n\nstatic JSValue js_bigdecimal_to_string1(JSContext *ctx, JSValueConst val,\n                                        limb_t prec, int flags)\n{\n    JSValue ret;\n    bfdec_t *a;\n    char *str;\n    int saved_sign;\n\n    a = JS_ToBigDecimal(ctx, val);\n    saved_sign = a->sign;\n    if (a->expn == BF_EXP_ZERO)\n        a->sign = 0;\n    str = bfdec_ftoa(NULL, a, prec, flags | BF_FTOA_JS_QUIRKS);\n    a->sign = saved_sign;\n    if (!str)\n        return JS_ThrowOutOfMemory(ctx);\n    ret = JS_NewString(ctx, str);\n    bf_free(ctx->bf_ctx, str);\n    return ret;\n}\n\nstatic JSValue js_bigdecimal_to_string(JSContext *ctx, JSValueConst val)\n{\n    return js_bigdecimal_to_string1(ctx, val, 0,\n                                    BF_RNDZ | BF_FTOA_FORMAT_FREE);\n}\n\n#endif /* CONFIG_BIGNUM */\n\n/* 2 <= base <= 36 */\nstatic char *i64toa(char *buf_end, int64_t n, unsigned int base)\n{\n    char *q = buf_end;\n    int digit, is_neg;\n\n    is_neg = 0;\n    if (n < 0) {\n        is_neg = 1;\n        n = -n;\n    }\n    *--q = '\\0';\n    do {\n        digit = (uint64_t)n % base;\n        n = (uint64_t)n / base;\n        if (digit < 10)\n            digit += '0';\n        else\n            digit += 'a' - 10;\n        *--q = digit;\n    } while (n != 0);\n    if (is_neg)\n        *--q = '-';\n    return q;\n}\n\n/* buf1 contains the printf result */\nstatic void js_ecvt1(double d, int n_digits, int *decpt, int *sign, char *buf,\n                     int rounding_mode, char *buf1, int buf1_size)\n{\n    if (rounding_mode != FE_TONEAREST)\n        fesetround(rounding_mode);\n    snprintf(buf1, buf1_size, \"%+.*e\", n_digits - 1, d);\n    if (rounding_mode != FE_TONEAREST)\n        fesetround(FE_TONEAREST);\n    *sign = (buf1[0] == '-');\n    /* mantissa */\n    buf[0] = buf1[1];\n    if (n_digits > 1)\n        memcpy(buf + 1, buf1 + 3, n_digits - 1);\n    buf[n_digits] = '\\0';\n    /* exponent */\n    *decpt = atoi(buf1 + n_digits + 2 + (n_digits > 1)) + 1;\n}\n\n/* maximum buffer size for js_dtoa */\n#define JS_DTOA_BUF_SIZE 128\n\n/* needed because ecvt usually limits the number of digits to\n   17. Return the number of digits. */\nstatic int js_ecvt(double d, int n_digits, int *decpt, int *sign, char *buf,\n                   BOOL is_fixed)\n{\n    int rounding_mode;\n    char buf_tmp[JS_DTOA_BUF_SIZE];\n\n    if (!is_fixed) {\n        unsigned int n_digits_min, n_digits_max;\n        /* find the minimum amount of digits (XXX: inefficient but simple) */\n        n_digits_min = 1;\n        n_digits_max = 17;\n        while (n_digits_min < n_digits_max) {\n            n_digits = (n_digits_min + n_digits_max) / 2;\n            js_ecvt1(d, n_digits, decpt, sign, buf, FE_TONEAREST,\n                     buf_tmp, sizeof(buf_tmp));\n            if (strtod(buf_tmp, NULL) == d) {\n                /* no need to keep the trailing zeros */\n                while (n_digits >= 2 && buf[n_digits - 1] == '0')\n                    n_digits--;\n                n_digits_max = n_digits;\n            } else {\n                n_digits_min = n_digits + 1;\n            }\n        }\n        n_digits = n_digits_max;\n        rounding_mode = FE_TONEAREST;\n    } else {\n        rounding_mode = FE_TONEAREST;\n#ifdef CONFIG_PRINTF_RNDN\n        {\n            char buf1[JS_DTOA_BUF_SIZE], buf2[JS_DTOA_BUF_SIZE];\n            int decpt1, sign1, decpt2, sign2;\n            /* The JS rounding is specified as round to nearest ties away\n               from zero (RNDNA), but in printf the \"ties\" case is not\n               specified (for example it is RNDN for glibc, RNDNA for\n               Windows), so we must round manually. */\n            js_ecvt1(d, n_digits + 1, &decpt1, &sign1, buf1, FE_TONEAREST,\n                     buf_tmp, sizeof(buf_tmp));\n            /* XXX: could use 2 digits to reduce the average running time */\n            if (buf1[n_digits] == '5') {\n                js_ecvt1(d, n_digits + 1, &decpt1, &sign1, buf1, FE_DOWNWARD,\n                         buf_tmp, sizeof(buf_tmp));\n                js_ecvt1(d, n_digits + 1, &decpt2, &sign2, buf2, FE_UPWARD,\n                         buf_tmp, sizeof(buf_tmp));\n                if (memcmp(buf1, buf2, n_digits + 1) == 0 && decpt1 == decpt2) {\n                    /* exact result: round away from zero */\n                    if (sign1)\n                        rounding_mode = FE_DOWNWARD;\n                    else\n                        rounding_mode = FE_UPWARD;\n                }\n            }\n        }\n#endif /* CONFIG_PRINTF_RNDN */\n    }\n    js_ecvt1(d, n_digits, decpt, sign, buf, rounding_mode,\n             buf_tmp, sizeof(buf_tmp));\n    return n_digits;\n}\n\nstatic int js_fcvt1(char *buf, int buf_size, double d, int n_digits,\n                    int rounding_mode)\n{\n    int n;\n    if (rounding_mode != FE_TONEAREST)\n        fesetround(rounding_mode);\n    n = snprintf(buf, buf_size, \"%.*f\", n_digits, d);\n    if (rounding_mode != FE_TONEAREST)\n        fesetround(FE_TONEAREST);\n    assert(n < buf_size);\n    return n;\n}\n\nstatic void js_fcvt(char *buf, int buf_size, double d, int n_digits)\n{\n    int rounding_mode;\n    rounding_mode = FE_TONEAREST;\n#ifdef CONFIG_PRINTF_RNDN\n    {\n        int n1, n2;\n        char buf1[JS_DTOA_BUF_SIZE];\n        char buf2[JS_DTOA_BUF_SIZE];\n\n        /* The JS rounding is specified as round to nearest ties away from\n           zero (RNDNA), but in printf the \"ties\" case is not specified\n           (for example it is RNDN for glibc, RNDNA for Windows), so we\n           must round manually. */\n        n1 = js_fcvt1(buf1, sizeof(buf1), d, n_digits + 1, FE_TONEAREST);\n        rounding_mode = FE_TONEAREST;\n        /* XXX: could use 2 digits to reduce the average running time */\n        if (buf1[n1 - 1] == '5') {\n            n1 = js_fcvt1(buf1, sizeof(buf1), d, n_digits + 1, FE_DOWNWARD);\n            n2 = js_fcvt1(buf2, sizeof(buf2), d, n_digits + 1, FE_UPWARD);\n            if (n1 == n2 && memcmp(buf1, buf2, n1) == 0) {\n                /* exact result: round away from zero */\n                if (buf1[0] == '-')\n                    rounding_mode = FE_DOWNWARD;\n                else\n                    rounding_mode = FE_UPWARD;\n            }\n        }\n    }\n#endif /* CONFIG_PRINTF_RNDN */\n    js_fcvt1(buf, buf_size, d, n_digits, rounding_mode);\n}\n\n/* radix != 10 is only supported with flags = JS_DTOA_VAR_FORMAT */\n/* use as many digits as necessary */\n#define JS_DTOA_VAR_FORMAT   (0 << 0)\n/* use n_digits significant digits (1 <= n_digits <= 101) */\n#define JS_DTOA_FIXED_FORMAT (1 << 0)\n/* force fractional format: [-]dd.dd with n_digits fractional digits */\n#define JS_DTOA_FRAC_FORMAT  (2 << 0)\n/* force exponential notation either in fixed or variable format */\n#define JS_DTOA_FORCE_EXP    (1 << 2)\n\n/* XXX: slow and maybe not fully correct. Use libbf when it is fast enough.\n   XXX: radix != 10 is only supported for small integers\n*/\nstatic void js_dtoa1(char *buf, double d, int radix, int n_digits, int flags)\n{\n    char *q;\n\n    if (!isfinite(d)) {\n        if (isnan(d)) {\n            strcpy(buf, \"NaN\");\n        } else {\n            q = buf;\n            if (d < 0)\n                *q++ = '-';\n            strcpy(q, \"Infinity\");\n        }\n    } else if (flags == JS_DTOA_VAR_FORMAT) {\n        int64_t i64;\n        char buf1[70], *ptr;\n        i64 = (int64_t)d;\n        if (d != i64 || i64 > MAX_SAFE_INTEGER || i64 < -MAX_SAFE_INTEGER)\n            goto generic_conv;\n        /* fast path for integers */\n        ptr = i64toa(buf1 + sizeof(buf1), i64, radix);\n        strcpy(buf, ptr);\n    } else {\n        if (d == 0.0)\n            d = 0.0; /* convert -0 to 0 */\n        if (flags == JS_DTOA_FRAC_FORMAT) {\n            js_fcvt(buf, JS_DTOA_BUF_SIZE, d, n_digits);\n        } else {\n            char buf1[JS_DTOA_BUF_SIZE];\n            int sign, decpt, k, n, i, p, n_max;\n            BOOL is_fixed;\n        generic_conv:\n            is_fixed = ((flags & 3) == JS_DTOA_FIXED_FORMAT);\n            if (is_fixed) {\n                n_max = n_digits;\n            } else {\n                n_max = 21;\n            }\n            /* the number has k digits (k >= 1) */\n            k = js_ecvt(d, n_digits, &decpt, &sign, buf1, is_fixed);\n            n = decpt; /* d=10^(n-k)*(buf1) i.e. d= < x.yyyy 10^(n-1) */\n            q = buf;\n            if (sign)\n                *q++ = '-';\n            if (flags & JS_DTOA_FORCE_EXP)\n                goto force_exp;\n            if (n >= 1 && n <= n_max) {\n                if (k <= n) {\n                    memcpy(q, buf1, k);\n                    q += k;\n                    for(i = 0; i < (n - k); i++)\n                        *q++ = '0';\n                    *q = '\\0';\n                } else {\n                    /* k > n */\n                    memcpy(q, buf1, n);\n                    q += n;\n                    *q++ = '.';\n                    for(i = 0; i < (k - n); i++)\n                        *q++ = buf1[n + i];\n                    *q = '\\0';\n                }\n            } else if (n >= -5 && n <= 0) {\n                *q++ = '0';\n                *q++ = '.';\n                for(i = 0; i < -n; i++)\n                    *q++ = '0';\n                memcpy(q, buf1, k);\n                q += k;\n                *q = '\\0';\n            } else {\n            force_exp:\n                /* exponential notation */\n                *q++ = buf1[0];\n                if (k > 1) {\n                    *q++ = '.';\n                    for(i = 1; i < k; i++)\n                        *q++ = buf1[i];\n                }\n                *q++ = 'e';\n                p = n - 1;\n                if (p >= 0)\n                    *q++ = '+';\n                sprintf(q, \"%d\", p);\n            }\n        }\n    }\n}\n\nstatic JSValue js_dtoa(JSContext *ctx,\n                       double d, int radix, int n_digits, int flags)\n{\n    char buf[JS_DTOA_BUF_SIZE];\n    js_dtoa1(buf, d, radix, n_digits, flags);\n    return JS_NewString(ctx, buf);\n}\n\nJSValue JS_ToStringInternal(JSContext *ctx, JSValueConst val, BOOL is_ToPropertyKey)\n{\n    uint32_t tag;\n    const char *str;\n    char buf[32];\n\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_STRING:\n        return JS_DupValue(ctx, val);\n    case JS_TAG_INT:\n        snprintf(buf, sizeof(buf), \"%d\", JS_VALUE_GET_INT(val));\n        str = buf;\n        goto new_string;\n    case JS_TAG_BOOL:\n        return JS_AtomToString(ctx, JS_VALUE_GET_BOOL(val) ?\n                          JS_ATOM_true : JS_ATOM_false);\n    case JS_TAG_NULL:\n        return JS_AtomToString(ctx, JS_ATOM_null);\n    case JS_TAG_UNDEFINED:\n        return JS_AtomToString(ctx, JS_ATOM_undefined);\n    case JS_TAG_EXCEPTION:\n        return JS_EXCEPTION;\n    case JS_TAG_OBJECT:\n        {\n            JSValue val1, ret;\n            val1 = JS_ToPrimitive(ctx, val, HINT_STRING);\n            if (JS_IsException(val1))\n                return val1;\n            ret = JS_ToStringInternal(ctx, val1, is_ToPropertyKey);\n            JS_FreeValue(ctx, val1);\n            return ret;\n        }\n        break;\n    case JS_TAG_FUNCTION_BYTECODE:\n        str = \"[function bytecode]\";\n        goto new_string;\n    case JS_TAG_SYMBOL:\n        if (is_ToPropertyKey) {\n            return JS_DupValue(ctx, val);\n        } else {\n            return JS_ThrowTypeError(ctx, \"cannot convert symbol to string\");\n        }\n    case JS_TAG_FLOAT64:\n        return js_dtoa(ctx, JS_VALUE_GET_FLOAT64(val), 10, 0,\n                       JS_DTOA_VAR_FORMAT);\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n        return ctx->rt->bigint_ops.to_string(ctx, val);\n    case JS_TAG_BIG_FLOAT:\n        return ctx->rt->bigfloat_ops.to_string(ctx, val);\n    case JS_TAG_BIG_DECIMAL:\n        return ctx->rt->bigdecimal_ops.to_string(ctx, val);\n#endif\n    default:\n        str = \"[unsupported type]\";\n    new_string:\n        return JS_NewString(ctx, str);\n    }\n}\n\nJSValue JS_ToString(JSContext *ctx, JSValueConst val)\n{\n    return JS_ToStringInternal(ctx, val, FALSE);\n}\n\nstatic JSValue JS_ToStringFree(JSContext *ctx, JSValue val)\n{\n    JSValue ret;\n    ret = JS_ToString(ctx, val);\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nstatic JSValue JS_ToLocaleStringFree(JSContext *ctx, JSValue val)\n{\n    if (JS_IsUndefined(val) || JS_IsNull(val))\n        return JS_ToStringFree(ctx, val);\n    return JS_InvokeFree(ctx, val, JS_ATOM_toLocaleString, 0, NULL);\n}\n\nJSValue JS_ToPropertyKey(JSContext *ctx, JSValueConst val)\n{\n    return JS_ToStringInternal(ctx, val, TRUE);\n}\n\nstatic JSValue JS_ToStringCheckObject(JSContext *ctx, JSValueConst val)\n{\n    uint32_t tag = JS_VALUE_GET_TAG(val);\n    if (tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED)\n        return JS_ThrowTypeError(ctx, \"null or undefined are forbidden\");\n    return JS_ToString(ctx, val);\n}\n\nstatic JSValue JS_ToQuotedString(JSContext *ctx, JSValueConst val1)\n{\n    JSValue val;\n    JSString *p;\n    int i;\n    uint32_t c;\n    StringBuffer b_s, *b = &b_s;\n    char buf[16];\n\n    val = JS_ToStringCheckObject(ctx, val1);\n    if (JS_IsException(val))\n        return val;\n    p = JS_VALUE_GET_STRING(val);\n\n    if (string_buffer_init(ctx, b, p->len + 2))\n        goto fail;\n\n    if (string_buffer_putc8(b, '\\\"'))\n        goto fail;\n    for(i = 0; i < p->len; ) {\n        c = string_getc(p, &i);\n        switch(c) {\n        case '\\t':\n            c = 't';\n            goto quote;\n        case '\\r':\n            c = 'r';\n            goto quote;\n        case '\\n':\n            c = 'n';\n            goto quote;\n        case '\\b':\n            c = 'b';\n            goto quote;\n        case '\\f':\n            c = 'f';\n            goto quote;\n        case '\\\"':\n        case '\\\\':\n        quote:\n            if (string_buffer_putc8(b, '\\\\'))\n                goto fail;\n            if (string_buffer_putc8(b, c))\n                goto fail;\n            break;\n        default:\n            if (c < 32 || (c >= 0xd800 && c < 0xe000)) {\n                snprintf(buf, sizeof(buf), \"\\\\u%04x\", c);\n                if (string_buffer_puts8(b, buf))\n                    goto fail;\n            } else {\n                if (string_buffer_putc(b, c))\n                    goto fail;\n            }\n            break;\n        }\n    }\n    if (string_buffer_putc8(b, '\\\"'))\n        goto fail;\n    JS_FreeValue(ctx, val);\n    return string_buffer_end(b);\n fail:\n    JS_FreeValue(ctx, val);\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nstatic __maybe_unused void JS_DumpObjectHeader(JSRuntime *rt)\n{\n    printf(\"%14s %4s %4s %14s %10s %s\\n\",\n           \"ADDRESS\", \"REFS\", \"SHRF\", \"PROTO\", \"CLASS\", \"PROPS\");\n}\n\n/* for debug only: dump an object without side effect */\nstatic __maybe_unused void JS_DumpObject(JSRuntime *rt, JSObject *p)\n{\n    uint32_t i;\n    char atom_buf[ATOM_GET_STR_BUF_SIZE];\n    JSShape *sh;\n    JSShapeProperty *prs;\n    JSProperty *pr;\n    BOOL is_first = TRUE;\n\n    /* XXX: should encode atoms with special characters */\n    sh = p->shape; /* the shape can be NULL while freeing an object */\n    printf(\"%14p %4d \",\n           (void *)p,\n           p->header.ref_count);\n    if (sh) {\n        printf(\"%3d%c %14p \",\n               sh->header.ref_count,\n               \" *\"[sh->is_hashed],\n               (void *)sh->proto);\n    } else {\n        printf(\"%3s  %14s \", \"-\", \"-\");\n    }\n    printf(\"%10s \",\n           JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), rt->class_array[p->class_id].class_name));\n    if (p->is_exotic && p->fast_array) {\n        printf(\"[ \");\n        for(i = 0; i < p->u.array.count; i++) {\n            if (i != 0)\n                printf(\", \");\n            switch (p->class_id) {\n            case JS_CLASS_ARRAY:\n            case JS_CLASS_ARGUMENTS:\n                JS_DumpValueShort(rt, p->u.array.u.values[i]);\n                break;\n            case JS_CLASS_UINT8C_ARRAY:\n            case JS_CLASS_INT8_ARRAY:\n            case JS_CLASS_UINT8_ARRAY:\n            case JS_CLASS_INT16_ARRAY:\n            case JS_CLASS_UINT16_ARRAY:\n            case JS_CLASS_INT32_ARRAY:\n            case JS_CLASS_UINT32_ARRAY:\n#ifdef CONFIG_BIGNUM\n            case JS_CLASS_BIG_INT64_ARRAY:\n            case JS_CLASS_BIG_UINT64_ARRAY:\n#endif\n            case JS_CLASS_FLOAT32_ARRAY:\n            case JS_CLASS_FLOAT64_ARRAY:\n                {\n                    int size = 1 << typed_array_size_log2(p->class_id);\n                    const uint8_t *b = p->u.array.u.uint8_ptr + i * size;\n                    while (size-- > 0)\n                        printf(\"%02X\", *b++);\n                }\n                break;\n            }\n        }\n        printf(\" ] \");\n    }\n\n    if (sh) {\n        printf(\"{ \");\n        for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) {\n            if (prs->atom != JS_ATOM_NULL) {\n                pr = &p->prop[i];\n                if (!is_first)\n                    printf(\", \");\n                printf(\"%s: \",\n                       JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), prs->atom));\n                if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) {\n                    printf(\"[getset %p %p]\", (void *)pr->u.getset.getter,\n                           (void *)pr->u.getset.setter);\n                } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {\n                    printf(\"[varref %p]\", (void *)pr->u.var_ref);\n                } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) {\n                    printf(\"[autoinit %p %d %p]\",\n                           (void *)js_autoinit_get_realm(pr),\n                           js_autoinit_get_id(pr),\n                           (void *)pr->u.init.opaque);\n                } else {\n                    JS_DumpValueShort(rt, pr->u.value);\n                }\n                is_first = FALSE;\n            }\n        }\n        printf(\" }\");\n    }\n    \n    if (js_class_has_bytecode(p->class_id)) {\n        JSFunctionBytecode *b = p->u.func.function_bytecode;\n        JSVarRef **var_refs;\n        if (b->closure_var_count) {\n            var_refs = p->u.func.var_refs;\n            printf(\" Closure:\");\n            for(i = 0; i < b->closure_var_count; i++) {\n                printf(\" \");\n                JS_DumpValueShort(rt, var_refs[i]->value);\n            }\n            if (p->u.func.home_object) {\n                printf(\" HomeObject: \");\n                JS_DumpValueShort(rt, JS_MKPTR(JS_TAG_OBJECT, p->u.func.home_object));\n            }\n        }\n    }\n    printf(\"\\n\");\n}\n\nstatic __maybe_unused void JS_DumpGCObject(JSRuntime *rt, JSGCObjectHeader *p)\n{\n    if (p->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT) {\n        JS_DumpObject(rt, (JSObject *)p);\n    } else {\n        printf(\"%14p %4d \",\n               (void *)p,\n               p->ref_count);\n        switch(p->gc_obj_type) {\n        case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE:\n            printf(\"[function bytecode]\");\n            break;\n        case JS_GC_OBJ_TYPE_SHAPE:\n            printf(\"[shape]\");\n            break;\n        case JS_GC_OBJ_TYPE_VAR_REF:\n            printf(\"[var_ref]\");\n            break;\n        case JS_GC_OBJ_TYPE_ASYNC_FUNCTION:\n            printf(\"[async_function]\");\n            break;\n        case JS_GC_OBJ_TYPE_JS_CONTEXT:\n            printf(\"[js_context]\");\n            break;\n        default:\n            printf(\"[unknown %d]\", p->gc_obj_type);\n            break;\n        }\n        printf(\"\\n\");\n    }\n}\n\nstatic __maybe_unused void JS_DumpValueShort(JSRuntime *rt,\n                                                      JSValueConst val)\n{\n    uint32_t tag = JS_VALUE_GET_NORM_TAG(val);\n    const char *str;\n\n    switch(tag) {\n    case JS_TAG_INT:\n        printf(\"%d\", JS_VALUE_GET_INT(val));\n        break;\n    case JS_TAG_BOOL:\n        if (JS_VALUE_GET_BOOL(val))\n            str = \"true\";\n        else\n            str = \"false\";\n        goto print_str;\n    case JS_TAG_NULL:\n        str = \"null\";\n        goto print_str;\n    case JS_TAG_EXCEPTION:\n        str = \"exception\";\n        goto print_str;\n    case JS_TAG_UNINITIALIZED:\n        str = \"uninitialized\";\n        goto print_str;\n    case JS_TAG_UNDEFINED:\n        str = \"undefined\";\n    print_str:\n        printf(\"%s\", str);\n        break;\n    case JS_TAG_FLOAT64:\n        printf(\"%.14g\", JS_VALUE_GET_FLOAT64(val));\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            char *str;\n            str = bf_ftoa(NULL, &p->num, 10, 0,\n                          BF_RNDZ | BF_FTOA_FORMAT_FRAC);\n            printf(\"%sn\", str);\n            bf_realloc(&rt->bf_ctx, str, 0);\n        }\n        break;\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            char *str;\n            str = bf_ftoa(NULL, &p->num, 16, BF_PREC_INF,\n                          BF_RNDZ | BF_FTOA_FORMAT_FREE | BF_FTOA_ADD_PREFIX);\n            printf(\"%sl\", str);\n            bf_free(&rt->bf_ctx, str);\n        }\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        {\n            JSBigDecimal *p = JS_VALUE_GET_PTR(val);\n            char *str;\n            str = bfdec_ftoa(NULL, &p->num, BF_PREC_INF,\n                             BF_RNDZ | BF_FTOA_FORMAT_FREE);\n            printf(\"%sm\", str);\n            bf_free(&rt->bf_ctx, str);\n        }\n        break;\n#endif\n    case JS_TAG_STRING:\n        {\n            JSString *p;\n            p = JS_VALUE_GET_STRING(val);\n            JS_DumpString(rt, p);\n        }\n        break;\n    case JS_TAG_FUNCTION_BYTECODE:\n        {\n            JSFunctionBytecode *b = JS_VALUE_GET_PTR(val);\n            char buf[ATOM_GET_STR_BUF_SIZE];\n            printf(\"[bytecode %s]\", JS_AtomGetStrRT(rt, buf, sizeof(buf), b->func_name));\n        }\n        break;\n    case JS_TAG_OBJECT:\n        {\n            JSObject *p = JS_VALUE_GET_OBJ(val);\n            JSAtom atom = rt->class_array[p->class_id].class_name;\n            char atom_buf[ATOM_GET_STR_BUF_SIZE];\n            printf(\"[%s %p]\",\n                   JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), atom), (void *)p);\n        }\n        break;\n    case JS_TAG_SYMBOL:\n        {\n            JSAtomStruct *p = JS_VALUE_GET_PTR(val);\n            char atom_buf[ATOM_GET_STR_BUF_SIZE];\n            printf(\"Symbol(%s)\",\n                   JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), js_get_atom_index(rt, p)));\n        }\n        break;\n    case JS_TAG_MODULE:\n        printf(\"[module]\");\n        break;\n    default:\n        printf(\"[unknown tag %d]\", tag);\n        break;\n    }\n}\n\nstatic __maybe_unused void JS_DumpValue(JSContext *ctx,\n                                                 JSValueConst val)\n{\n    JS_DumpValueShort(ctx->rt, val);\n}\n\nstatic __maybe_unused void JS_PrintValue(JSContext *ctx,\n                                                  const char *str,\n                                                  JSValueConst val)\n{\n    printf(\"%s=\", str);\n    JS_DumpValueShort(ctx->rt, val);\n    printf(\"\\n\");\n}\n\n/* return -1 if exception (proxy case) or TRUE/FALSE */\nint JS_IsArray(JSContext *ctx, JSValueConst val)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(val) == JS_TAG_OBJECT) {\n        p = JS_VALUE_GET_OBJ(val);\n        if (unlikely(p->class_id == JS_CLASS_PROXY))\n            return js_proxy_isArray(ctx, val);\n        else\n            return p->class_id == JS_CLASS_ARRAY;\n    } else {\n        return FALSE;\n    }\n}\n\nstatic double js_pow(double a, double b)\n{\n    if (unlikely(!isfinite(b)) && fabs(a) == 1) {\n        /* not compatible with IEEE 754 */\n        return JS_FLOAT64_NAN;\n    } else {\n        return pow(a, b);\n    }\n}\n\n#ifdef CONFIG_BIGNUM\n\nJSValue JS_NewBigInt64_1(JSContext *ctx, int64_t v)\n{\n    JSValue val;\n    bf_t *a;\n    val = JS_NewBigInt(ctx);\n    if (JS_IsException(val))\n        return val;\n    a = JS_GetBigInt(val);\n    if (bf_set_si(a, v)) {\n        JS_FreeValue(ctx, val);\n        return JS_ThrowOutOfMemory(ctx);\n    }\n    return val;\n}\n\nJSValue JS_NewBigInt64(JSContext *ctx, int64_t v)\n{\n    if (is_math_mode(ctx) &&\n        v >= -MAX_SAFE_INTEGER && v <= MAX_SAFE_INTEGER) {\n        return JS_NewInt64(ctx, v);\n    } else {\n        return JS_NewBigInt64_1(ctx, v);\n    }\n}\n\nJSValue JS_NewBigUint64(JSContext *ctx, uint64_t v)\n{\n    JSValue val;\n    if (is_math_mode(ctx) && v <= MAX_SAFE_INTEGER) {\n        val = JS_NewInt64(ctx, v);\n    } else {\n        bf_t *a;\n        val = JS_NewBigInt(ctx);\n        if (JS_IsException(val))\n            return val;\n        a = JS_GetBigInt(val);\n        if (bf_set_ui(a, v)) {\n            JS_FreeValue(ctx, val);\n            return JS_ThrowOutOfMemory(ctx);\n        }\n    }\n    return val;\n}\n\n/* if the returned bigfloat is allocated it is equal to\n   'buf'. Otherwise it is a pointer to the bigfloat in 'val'. Return\n   NULL in case of error. */\nstatic bf_t *JS_ToBigFloat(JSContext *ctx, bf_t *buf, JSValueConst val)\n{\n    uint32_t tag;\n    bf_t *r;\n    JSBigFloat *p;\n\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n        r = buf;\n        bf_init(ctx->bf_ctx, r);\n        if (bf_set_si(r, JS_VALUE_GET_INT(val)))\n            goto fail;\n        break;\n    case JS_TAG_FLOAT64:\n        r = buf;\n        bf_init(ctx->bf_ctx, r);\n        if (bf_set_float64(r, JS_VALUE_GET_FLOAT64(val))) {\n        fail:\n            bf_delete(r);\n            return NULL;\n        }\n        break;\n    case JS_TAG_BIG_INT:\n    case JS_TAG_BIG_FLOAT:\n        p = JS_VALUE_GET_PTR(val);\n        r = &p->num;\n        break;\n    case JS_TAG_UNDEFINED:\n    default:\n        r = buf;\n        bf_init(ctx->bf_ctx, r);\n        bf_set_nan(r);\n        break;\n    }\n    return r;\n}\n\n/* return NULL if invalid type */\nstatic bfdec_t *JS_ToBigDecimal(JSContext *ctx, JSValueConst val)\n{\n    uint32_t tag;\n    JSBigDecimal *p;\n    bfdec_t *r;\n    \n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_BIG_DECIMAL:\n        p = JS_VALUE_GET_PTR(val);\n        r = &p->num;\n        break;\n    default:\n        JS_ThrowTypeError(ctx, \"bigdecimal expected\");\n        r = NULL;\n        break;\n    }\n    return r;\n}\n\n/* return NaN if bad bigint literal */\nstatic JSValue JS_StringToBigInt(JSContext *ctx, JSValue val)\n{\n    const char *str, *p;\n    size_t len;\n    int flags;\n    \n    str = JS_ToCStringLen(ctx, &len, val);\n    JS_FreeValue(ctx, val);\n    if (!str)\n        return JS_EXCEPTION;\n    p = str;\n    p += skip_spaces(p);\n    if ((p - str) == len) {\n        val = JS_NewBigInt64(ctx, 0);\n    } else {\n        flags = ATOD_INT_ONLY | ATOD_ACCEPT_BIN_OCT | ATOD_TYPE_BIG_INT;\n        if (is_math_mode(ctx))\n            flags |= ATOD_MODE_BIGINT;\n        val = js_atof(ctx, p, &p, 0, flags);\n        p += skip_spaces(p);\n        if (!JS_IsException(val)) {\n            if ((p - str) != len) {\n                JS_FreeValue(ctx, val);\n                val = JS_NAN;\n            }\n        }\n    }\n    JS_FreeCString(ctx, str);\n    return val;\n}\n\nstatic JSValue JS_StringToBigIntErr(JSContext *ctx, JSValue val)\n{\n    val = JS_StringToBigInt(ctx, val);\n    if (JS_VALUE_IS_NAN(val))\n        return JS_ThrowSyntaxError(ctx, \"invalid bigint literal\");\n    return val;\n}\n\n/* if the returned bigfloat is allocated it is equal to\n   'buf'. Otherwise it is a pointer to the bigfloat in 'val'. */\nstatic bf_t *JS_ToBigIntFree(JSContext *ctx, bf_t *buf, JSValue val)\n{\n    uint32_t tag;\n    bf_t *r;\n    JSBigFloat *p;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        if (!is_math_mode(ctx))\n            goto fail;\n        /* fall tru */\n    case JS_TAG_BOOL:\n        r = buf;\n        bf_init(ctx->bf_ctx, r);\n        bf_set_si(r, JS_VALUE_GET_INT(val));\n        break;\n    case JS_TAG_FLOAT64:\n        {\n            double d = JS_VALUE_GET_FLOAT64(val);\n            if (!is_math_mode(ctx))\n                goto fail;\n            if (!isfinite(d))\n                goto fail;\n            r = buf;\n            bf_init(ctx->bf_ctx, r);\n            d = trunc(d);\n            bf_set_float64(r, d);\n        }\n        break;\n    case JS_TAG_BIG_INT:\n        p = JS_VALUE_GET_PTR(val);\n        r = &p->num;\n        break;\n    case JS_TAG_BIG_FLOAT:\n        if (!is_math_mode(ctx))\n            goto fail;\n        p = JS_VALUE_GET_PTR(val);\n        if (!bf_is_finite(&p->num))\n            goto fail;\n        r = buf;\n        bf_init(ctx->bf_ctx, r);\n        bf_set(r, &p->num);\n        bf_rint(r, BF_RNDZ);\n        JS_FreeValue(ctx, val);\n        break;\n    case JS_TAG_STRING:\n        val = JS_StringToBigIntErr(ctx, val);\n        if (JS_IsException(val))\n            return NULL;\n        goto redo;\n    case JS_TAG_OBJECT:\n        val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER);\n        if (JS_IsException(val))\n            return NULL;\n        goto redo;\n    default:\n    fail:\n        JS_FreeValue(ctx, val);\n        JS_ThrowTypeError(ctx, \"cannot convert to bigint\");\n        return NULL;\n    }\n    return r;\n}\n\nstatic bf_t *JS_ToBigInt(JSContext *ctx, bf_t *buf, JSValueConst val)\n{\n    return JS_ToBigIntFree(ctx, buf, JS_DupValue(ctx, val));\n}\n\nstatic __maybe_unused JSValue JS_ToBigIntValueFree(JSContext *ctx, JSValue val)\n{\n    if (JS_VALUE_GET_TAG(val) == JS_TAG_BIG_INT) {\n        return val;\n    } else {\n        bf_t a_s, *a, *r;\n        int ret;\n        JSValue res; \n\n        res = JS_NewBigInt(ctx);\n        if (JS_IsException(res))\n            return JS_EXCEPTION;\n        a = JS_ToBigIntFree(ctx, &a_s, val);\n        if (!a) {\n            JS_FreeValue(ctx, res);\n            return JS_EXCEPTION;\n        }\n        r = JS_GetBigInt(res);\n        ret = bf_set(r, a);\n        JS_FreeBigInt(ctx, a, &a_s);\n        if (ret) {\n            JS_FreeValue(ctx, res);\n            return JS_ThrowOutOfMemory(ctx);\n        }\n        return JS_CompactBigInt(ctx, res);\n    }\n}\n\n/* free the bf_t allocated by JS_ToBigInt */\nstatic void JS_FreeBigInt(JSContext *ctx, bf_t *a, bf_t *buf)\n{\n    if (a == buf) {\n        bf_delete(a);\n    } else {\n        JSBigFloat *p = (JSBigFloat *)((uint8_t *)a -\n                                       offsetof(JSBigFloat, num));\n        JS_FreeValue(ctx, JS_MKPTR(JS_TAG_BIG_FLOAT, p));\n    }\n}\n\n/* XXX: merge with JS_ToInt64Free with a specific flag */\nstatic int JS_ToBigInt64Free(JSContext *ctx, int64_t *pres, JSValue val)\n{\n    bf_t a_s, *a;\n\n    a = JS_ToBigIntFree(ctx, &a_s, val);\n    if (!a) {\n        *pres = 0;\n        return -1;\n    }\n    bf_get_int64(pres, a, BF_GET_INT_MOD);\n    JS_FreeBigInt(ctx, a, &a_s);\n    return 0;\n}\n\nint JS_ToBigInt64(JSContext *ctx, int64_t *pres, JSValueConst val)\n{\n    return JS_ToBigInt64Free(ctx, pres, JS_DupValue(ctx, val));\n}\n\nstatic JSBigFloat *js_new_bf(JSContext *ctx)\n{\n    JSBigFloat *p;\n    p = js_malloc(ctx, sizeof(*p));\n    if (!p)\n        return NULL;\n    p->header.ref_count = 1;\n    bf_init(ctx->bf_ctx, &p->num);\n    return p;\n}\n\nstatic JSValue JS_NewBigFloat(JSContext *ctx)\n{\n    JSBigFloat *p;\n    p = js_malloc(ctx, sizeof(*p));\n    if (!p)\n        return JS_EXCEPTION;\n    p->header.ref_count = 1;\n    bf_init(ctx->bf_ctx, &p->num);\n    return JS_MKPTR(JS_TAG_BIG_FLOAT, p);\n}\n\nstatic JSValue JS_NewBigDecimal(JSContext *ctx)\n{\n    JSBigDecimal *p;\n    p = js_malloc(ctx, sizeof(*p));\n    if (!p)\n        return JS_EXCEPTION;\n    p->header.ref_count = 1;\n    bfdec_init(ctx->bf_ctx, &p->num);\n    return JS_MKPTR(JS_TAG_BIG_DECIMAL, p);\n}\n\nstatic JSValue JS_NewBigInt(JSContext *ctx)\n{\n    JSBigFloat *p;\n    p = js_malloc(ctx, sizeof(*p));\n    if (!p)\n        return JS_EXCEPTION;\n    p->header.ref_count = 1;\n    bf_init(ctx->bf_ctx, &p->num);\n    return JS_MKPTR(JS_TAG_BIG_INT, p);\n}\n\nstatic JSValue JS_CompactBigInt1(JSContext *ctx, JSValue val,\n                                 BOOL convert_to_safe_integer)\n{\n    int64_t v;\n    bf_t *a;\n    \n    if (JS_VALUE_GET_TAG(val) != JS_TAG_BIG_INT)\n        return val; /* fail safe */\n    a = JS_GetBigInt(val);\n    if (convert_to_safe_integer && bf_get_int64(&v, a, 0) == 0 &&\n        v >= -MAX_SAFE_INTEGER && v <= MAX_SAFE_INTEGER) {\n        JS_FreeValue(ctx, val);\n        return JS_NewInt64(ctx, v);\n    } else if (a->expn == BF_EXP_ZERO && a->sign) {\n        JSBigFloat *p = JS_VALUE_GET_PTR(val);\n        assert(p->header.ref_count == 1);\n        a->sign = 0;\n    }\n    return val;\n}\n\n/* Convert the big int to a safe integer if in math mode. normalize\n   the zero representation. Could also be used to convert the bigint\n   to a short bigint value. The reference count of the value must be\n   1. Cannot fail */\nstatic JSValue JS_CompactBigInt(JSContext *ctx, JSValue val)\n{\n    return JS_CompactBigInt1(ctx, val, is_math_mode(ctx));\n}\n\n/* must be kept in sync with JSOverloadableOperatorEnum */\n/* XXX: use atoms ? */\nstatic const char js_overloadable_operator_names[JS_OVOP_COUNT][4] = {\n    \"+\",\n    \"-\",\n    \"*\",\n    \"/\",\n    \"%\",\n    \"**\",\n    \"|\",\n    \"&\",\n    \"^\",\n    \"<<\",\n    \">>\",\n    \">>>\",\n    \"==\",\n    \"<\",\n    \"pos\",\n    \"neg\",\n    \"++\",\n    \"--\",\n    \"~\",\n};\n\nstatic int get_ovop_from_opcode(OPCodeEnum op)\n{\n    switch(op) {\n    case OP_add:\n        return JS_OVOP_ADD;\n    case OP_sub:\n        return JS_OVOP_SUB;\n    case OP_mul:\n        return JS_OVOP_MUL;\n    case OP_div:\n        return JS_OVOP_DIV;\n    case OP_mod:\n    case OP_math_mod:\n        return JS_OVOP_MOD;\n    case OP_pow:\n        return JS_OVOP_POW;\n    case OP_or:\n        return JS_OVOP_OR;\n    case OP_and:\n        return JS_OVOP_AND;\n    case OP_xor:\n        return JS_OVOP_XOR;\n    case OP_shl:\n        return JS_OVOP_SHL;\n    case OP_sar:\n        return JS_OVOP_SAR;\n    case OP_shr:\n        return JS_OVOP_SHR;\n    case OP_eq:\n    case OP_neq:\n        return JS_OVOP_EQ;\n    case OP_lt:\n    case OP_lte:\n    case OP_gt:\n    case OP_gte:\n        return JS_OVOP_LESS;\n    case OP_plus:\n        return JS_OVOP_POS;\n    case OP_neg:\n        return JS_OVOP_NEG;\n    case OP_inc:\n        return JS_OVOP_INC;\n    case OP_dec:\n        return JS_OVOP_DEC;\n    default:\n        abort();\n    }\n}\n\n/* return NULL if not present */\nstatic JSObject *find_binary_op(JSBinaryOperatorDef *def,\n                                uint32_t operator_index,\n                                JSOverloadableOperatorEnum op)\n{\n    JSBinaryOperatorDefEntry *ent;\n    int i;\n    for(i = 0; i < def->count; i++) {\n        ent = &def->tab[i];\n        if (ent->operator_index == operator_index)\n            return ent->ops[op];\n    }\n    return NULL;\n}\n\n/* return -1 if exception, 0 if no operator overloading, 1 if\n   overloaded operator called */\nstatic __exception int js_call_binary_op_fallback(JSContext *ctx,\n                                                  JSValue *pret,\n                                                  JSValueConst op1,\n                                                  JSValueConst op2,\n                                                  OPCodeEnum op,\n                                                  BOOL is_numeric,\n                                                  int hint)\n{\n    JSValue opset1_obj, opset2_obj, method, ret, new_op1, new_op2;\n    JSOperatorSetData *opset1, *opset2;\n    JSOverloadableOperatorEnum ovop;\n    JSObject *p;\n    JSValueConst args[2];\n    \n    if (!ctx->allow_operator_overloading)\n        return 0;\n    \n    opset2_obj = JS_UNDEFINED;\n    opset1_obj = JS_GetProperty(ctx, op1, JS_ATOM_Symbol_operatorSet);\n    if (JS_IsException(opset1_obj))\n        goto exception;\n    if (JS_IsUndefined(opset1_obj))\n        return 0;\n    opset1 = JS_GetOpaque2(ctx, opset1_obj, JS_CLASS_OPERATOR_SET);\n    if (!opset1)\n        goto exception;\n\n    opset2_obj = JS_GetProperty(ctx, op2, JS_ATOM_Symbol_operatorSet);\n    if (JS_IsException(opset2_obj))\n        goto exception;\n    if (JS_IsUndefined(opset2_obj)) {\n        JS_FreeValue(ctx, opset1_obj);\n        return 0;\n    }\n    opset2 = JS_GetOpaque2(ctx, opset2_obj, JS_CLASS_OPERATOR_SET);\n    if (!opset2)\n        goto exception;\n\n    if (opset1->is_primitive && opset2->is_primitive) {\n        JS_FreeValue(ctx, opset1_obj);\n        JS_FreeValue(ctx, opset2_obj);\n        return 0;\n    }\n\n    ovop = get_ovop_from_opcode(op);\n    \n    if (opset1->operator_counter == opset2->operator_counter) {\n        p = opset1->self_ops[ovop];\n    } else if (opset1->operator_counter > opset2->operator_counter) {\n        p = find_binary_op(&opset1->left, opset2->operator_counter, ovop);\n    } else {\n        p = find_binary_op(&opset2->right, opset1->operator_counter, ovop);\n    }\n    if (!p) {\n        JS_ThrowTypeError(ctx, \"operator %s: no function defined\",\n                          js_overloadable_operator_names[ovop]);\n        goto exception;\n    }\n\n    if (opset1->is_primitive) {\n        if (is_numeric) {\n            new_op1 = JS_ToNumeric(ctx, op1);\n        } else {\n            new_op1 = JS_ToPrimitive(ctx, op1, hint);\n        }\n        if (JS_IsException(new_op1))\n            goto exception;\n    } else {\n        new_op1 = JS_DupValue(ctx, op1);\n    }\n    \n    if (opset2->is_primitive) {\n        if (is_numeric) {\n            new_op2 = JS_ToNumeric(ctx, op2);\n        } else {\n            new_op2 = JS_ToPrimitive(ctx, op2, hint);\n        }\n        if (JS_IsException(new_op2)) {\n            JS_FreeValue(ctx, new_op1);\n            goto exception;\n        }\n    } else {\n        new_op2 = JS_DupValue(ctx, op2);\n    }\n\n    /* XXX: could apply JS_ToPrimitive() if primitive type so that the\n       operator function does not get a value object */\n    \n    method = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n    if (ovop == JS_OVOP_LESS && (op == OP_lte || op == OP_gt)) {\n        args[0] = new_op2;\n        args[1] = new_op1;\n    } else {\n        args[0] = new_op1;\n        args[1] = new_op2;\n    }\n    ret = JS_CallFree(ctx, method, JS_UNDEFINED, 2, args);\n    JS_FreeValue(ctx, new_op1);\n    JS_FreeValue(ctx, new_op2);\n    if (JS_IsException(ret))\n        goto exception;\n    if (ovop == JS_OVOP_EQ) {\n        BOOL res = JS_ToBoolFree(ctx, ret);\n        if (op == OP_neq)\n            res ^= 1;\n        ret = JS_NewBool(ctx, res);\n    } else if (ovop == JS_OVOP_LESS) {\n        if (JS_IsUndefined(ret)) {\n            ret = JS_FALSE;\n        } else {\n            BOOL res = JS_ToBoolFree(ctx, ret);\n            if (op == OP_lte || op == OP_gte)\n                res ^= 1;\n            ret = JS_NewBool(ctx, res);\n        }\n    }\n    JS_FreeValue(ctx, opset1_obj);\n    JS_FreeValue(ctx, opset2_obj);\n    *pret = ret;\n    return 1;\n exception:\n    JS_FreeValue(ctx, opset1_obj);\n    JS_FreeValue(ctx, opset2_obj);\n    *pret = JS_UNDEFINED;\n    return -1;\n}\n\n/* try to call the operation on the operatorSet field of 'obj'. Only\n   used for \"/\" and \"**\" on the BigInt prototype in math mode */\nstatic __exception int js_call_binary_op_simple(JSContext *ctx,\n                                                JSValue *pret,\n                                                JSValueConst obj,\n                                                JSValueConst op1,\n                                                JSValueConst op2,\n                                                OPCodeEnum op)\n{\n    JSValue opset1_obj, method, ret, new_op1, new_op2;\n    JSOperatorSetData *opset1;\n    JSOverloadableOperatorEnum ovop;\n    JSObject *p;\n    JSValueConst args[2];\n\n    opset1_obj = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_operatorSet);\n    if (JS_IsException(opset1_obj))\n        goto exception;\n    if (JS_IsUndefined(opset1_obj))\n        return 0;\n    opset1 = JS_GetOpaque2(ctx, opset1_obj, JS_CLASS_OPERATOR_SET);\n    if (!opset1)\n        goto exception;\n    ovop = get_ovop_from_opcode(op);\n\n    p = opset1->self_ops[ovop];\n    if (!p) {\n        JS_FreeValue(ctx, opset1_obj);\n        return 0;\n    }\n\n    new_op1 = JS_ToNumeric(ctx, op1);\n    if (JS_IsException(new_op1))\n        goto exception;\n    new_op2 = JS_ToNumeric(ctx, op2);\n    if (JS_IsException(new_op2)) {\n        JS_FreeValue(ctx, new_op1);\n        goto exception;\n    }\n\n    method = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n    args[0] = new_op1;\n    args[1] = new_op2;\n    ret = JS_CallFree(ctx, method, JS_UNDEFINED, 2, args);\n    JS_FreeValue(ctx, new_op1);\n    JS_FreeValue(ctx, new_op2);\n    if (JS_IsException(ret))\n        goto exception;\n    JS_FreeValue(ctx, opset1_obj);\n    *pret = ret;\n    return 1;\n exception:\n    JS_FreeValue(ctx, opset1_obj);\n    *pret = JS_UNDEFINED;\n    return -1;\n}\n\n/* return -1 if exception, 0 if no operator overloading, 1 if\n   overloaded operator called */\nstatic __exception int js_call_unary_op_fallback(JSContext *ctx,\n                                                 JSValue *pret,\n                                                 JSValueConst op1,\n                                                 OPCodeEnum op)\n{\n    JSValue opset1_obj, method, ret;\n    JSOperatorSetData *opset1;\n    JSOverloadableOperatorEnum ovop;\n    JSObject *p;\n\n    if (!ctx->allow_operator_overloading)\n        return 0;\n    \n    opset1_obj = JS_GetProperty(ctx, op1, JS_ATOM_Symbol_operatorSet);\n    if (JS_IsException(opset1_obj))\n        goto exception;\n    if (JS_IsUndefined(opset1_obj))\n        return 0;\n    opset1 = JS_GetOpaque2(ctx, opset1_obj, JS_CLASS_OPERATOR_SET);\n    if (!opset1)\n        goto exception;\n    if (opset1->is_primitive) {\n        JS_FreeValue(ctx, opset1_obj);\n        return 0;\n    }\n\n    ovop = get_ovop_from_opcode(op);\n\n    p = opset1->self_ops[ovop];\n    if (!p) {\n        JS_ThrowTypeError(ctx, \"no overloaded operator %s\",\n                          js_overloadable_operator_names[ovop]);\n        goto exception;\n    }\n    method = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p));\n    ret = JS_CallFree(ctx, method, JS_UNDEFINED, 1, &op1);\n    if (JS_IsException(ret))\n        goto exception;\n    JS_FreeValue(ctx, opset1_obj);\n    *pret = ret;\n    return 1;\n exception:\n    JS_FreeValue(ctx, opset1_obj);\n    *pret = JS_UNDEFINED;\n    return -1;\n}\n\nstatic JSValue throw_bf_exception(JSContext *ctx, int status)\n{\n    const char *str;\n    if (status & BF_ST_MEM_ERROR)\n        return JS_ThrowOutOfMemory(ctx);\n    if (status & BF_ST_DIVIDE_ZERO) {\n        str = \"division by zero\";\n    } else if (status & BF_ST_INVALID_OP) {\n        str = \"invalid operation\";\n    } else {\n        str = \"integer overflow\";\n    }\n    return JS_ThrowRangeError(ctx, \"%s\", str);\n}\n\nstatic int js_unary_arith_bigint(JSContext *ctx,\n                                 JSValue *pres, OPCodeEnum op, JSValue op1)\n{\n    bf_t a_s, *r, *a;\n    int ret, v;\n    JSValue res;\n    \n    if (op == OP_plus && !is_math_mode(ctx)) {\n        JS_ThrowTypeError(ctx, \"bigint argument with unary +\");\n        JS_FreeValue(ctx, op1);\n        return -1;\n    }\n    res = JS_NewBigInt(ctx);\n    if (JS_IsException(res)) {\n        JS_FreeValue(ctx, op1);\n        return -1;\n    }\n    r = JS_GetBigInt(res);\n    a = JS_ToBigInt(ctx, &a_s, op1);\n    ret = 0;\n    switch(op) {\n    case OP_inc:\n    case OP_dec:\n        v = 2 * (op - OP_dec) - 1;\n        ret = bf_add_si(r, a, v, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_plus:\n        ret = bf_set(r, a);\n        break;\n    case OP_neg:\n        ret = bf_set(r, a);\n        bf_neg(r);\n        break;\n    case OP_not:\n        ret = bf_add_si(r, a, 1, BF_PREC_INF, BF_RNDZ);\n        bf_neg(r);\n        break;\n    default:\n        abort();\n    }\n    JS_FreeBigInt(ctx, a, &a_s);\n    JS_FreeValue(ctx, op1);\n    if (unlikely(ret)) {\n        JS_FreeValue(ctx, res);\n        throw_bf_exception(ctx, ret);\n        return -1;\n    }\n    res = JS_CompactBigInt(ctx, res);\n    *pres = res;\n    return 0;\n}\n\nstatic int js_unary_arith_bigfloat(JSContext *ctx,\n                                   JSValue *pres, OPCodeEnum op, JSValue op1)\n{\n    bf_t a_s, *r, *a;\n    int ret, v;\n    JSValue res;\n    \n    if (op == OP_plus && !is_math_mode(ctx)) {\n        JS_ThrowTypeError(ctx, \"bigfloat argument with unary +\");\n        JS_FreeValue(ctx, op1);\n        return -1;\n    }\n\n    res = JS_NewBigFloat(ctx);\n    if (JS_IsException(res)) {\n        JS_FreeValue(ctx, op1);\n        return -1;\n    }\n    r = JS_GetBigFloat(res);\n    a = JS_ToBigFloat(ctx, &a_s, op1);\n    ret = 0;\n    switch(op) {\n    case OP_inc:\n    case OP_dec:\n        v = 2 * (op - OP_dec) - 1;\n        ret = bf_add_si(r, a, v, ctx->fp_env.prec, ctx->fp_env.flags);\n        break;\n    case OP_plus:\n        ret = bf_set(r, a);\n        break;\n    case OP_neg:\n        ret = bf_set(r, a);\n        bf_neg(r);\n        break;\n    default:\n        abort();\n    }\n    if (a == &a_s)\n        bf_delete(a);\n    JS_FreeValue(ctx, op1);\n    if (unlikely(ret & BF_ST_MEM_ERROR)) {\n        JS_FreeValue(ctx, res);\n        throw_bf_exception(ctx, ret);\n        return -1;\n    }\n    *pres = res;\n    return 0;\n}\n\nstatic int js_unary_arith_bigdecimal(JSContext *ctx,\n                                     JSValue *pres, OPCodeEnum op, JSValue op1)\n{\n    bfdec_t *r, *a;\n    int ret, v;\n    JSValue res;\n    \n    if (op == OP_plus && !is_math_mode(ctx)) {\n        JS_ThrowTypeError(ctx, \"bigdecimal argument with unary +\");\n        JS_FreeValue(ctx, op1);\n        return -1;\n    }\n\n    res = JS_NewBigDecimal(ctx);\n    if (JS_IsException(res)) {\n        JS_FreeValue(ctx, op1);\n        return -1;\n    }\n    r = JS_GetBigDecimal(res);\n    a = JS_ToBigDecimal(ctx, op1);\n    ret = 0;\n    switch(op) {\n    case OP_inc:\n    case OP_dec:\n        v = 2 * (op - OP_dec) - 1;\n        ret = bfdec_add_si(r, a, v, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_plus:\n        ret = bfdec_set(r, a);\n        break;\n    case OP_neg:\n        ret = bfdec_set(r, a);\n        bfdec_neg(r);\n        break;\n    default:\n        abort();\n    }\n    JS_FreeValue(ctx, op1);\n    if (unlikely(ret)) {\n        JS_FreeValue(ctx, res);\n        throw_bf_exception(ctx, ret);\n        return -1;\n    }\n    *pres = res;\n    return 0;\n}\n\nstatic no_inline __exception int js_unary_arith_slow(JSContext *ctx,\n                                                     JSValue *sp,\n                                                     OPCodeEnum op)\n{\n    JSValue op1, val;\n    int v, ret;\n    uint32_t tag;\n\n    op1 = sp[-1];\n    /* fast path for float64 */\n    if (JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(op1)))\n        goto handle_float64;\n    if (JS_IsObject(op1)) {\n        ret = js_call_unary_op_fallback(ctx, &val, op1, op);\n        if (ret < 0)\n            return -1;\n        if (ret) {\n            JS_FreeValue(ctx, op1);\n            sp[-1] = val;\n            return 0;\n        }\n    }\n\n    op1 = JS_ToNumericFree(ctx, op1);\n    if (JS_IsException(op1))\n        goto exception;\n    tag = JS_VALUE_GET_TAG(op1);\n    switch(tag) {\n    case JS_TAG_INT:\n        {\n            int64_t v64;\n            v64 = JS_VALUE_GET_INT(op1);\n            switch(op) {\n            case OP_inc:\n            case OP_dec:\n                v = 2 * (op - OP_dec) - 1;\n                v64 += v;\n                break;\n            case OP_plus:\n                break;\n            case OP_neg:\n                if (v64 == 0) {\n                    sp[-1] = __JS_NewFloat64(ctx, -0.0);\n                    return 0;\n                } else {\n                    v64 = -v64;\n                }\n                break;\n            default:\n                abort();\n            }\n            sp[-1] = JS_NewInt64(ctx, v64);\n        }\n        break;\n    case JS_TAG_BIG_INT:\n    handle_bigint:\n        if (ctx->rt->bigint_ops.unary_arith(ctx, sp - 1, op, op1))\n            goto exception;\n        break;\n    case JS_TAG_BIG_FLOAT:\n        if (ctx->rt->bigfloat_ops.unary_arith(ctx, sp - 1, op, op1))\n            goto exception;\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        if (ctx->rt->bigdecimal_ops.unary_arith(ctx, sp - 1, op, op1))\n            goto exception;\n        break;\n    default:\n    handle_float64:\n        {\n            double d;\n            if (is_math_mode(ctx))\n                goto handle_bigint;\n            d = JS_VALUE_GET_FLOAT64(op1);\n            switch(op) {\n            case OP_inc:\n            case OP_dec:\n                v = 2 * (op - OP_dec) - 1;\n                d += v;\n                break;\n            case OP_plus:\n                break;\n            case OP_neg:\n                d = -d;\n                break;\n            default:\n                abort();\n            }\n            sp[-1] = __JS_NewFloat64(ctx, d);\n        }\n        break;\n    }\n    return 0;\n exception:\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic __exception int js_post_inc_slow(JSContext *ctx,\n                                        JSValue *sp, OPCodeEnum op)\n{\n    JSValue op1;\n\n    /* XXX: allow custom operators */\n    op1 = sp[-1];\n    op1 = JS_ToNumericFree(ctx, op1);\n    if (JS_IsException(op1)) {\n        sp[-1] = JS_UNDEFINED;\n        return -1;\n    }\n    sp[-1] = op1;\n    sp[0] = JS_DupValue(ctx, op1);\n    return js_unary_arith_slow(ctx, sp + 1, op - OP_post_dec + OP_dec);\n}\n\nstatic no_inline int js_not_slow(JSContext *ctx, JSValue *sp)\n{\n    JSValue op1, val;\n    int ret;\n    \n    op1 = sp[-1];\n    if (JS_IsObject(op1)) {\n        ret = js_call_unary_op_fallback(ctx, &val, op1, OP_not);\n        if (ret < 0)\n            return -1;\n        if (ret) {\n            JS_FreeValue(ctx, op1);\n            sp[-1] = val;\n            return 0;\n        }\n    }\n\n    op1 = JS_ToNumericFree(ctx, op1);\n    if (JS_IsException(op1))\n        goto exception;\n    if (is_math_mode(ctx) || JS_VALUE_GET_TAG(op1) == JS_TAG_BIG_INT) {\n        if (ctx->rt->bigint_ops.unary_arith(ctx, sp - 1, OP_not, op1))\n            goto exception;\n    } else {\n        int32_t v1;\n        if (unlikely(JS_ToInt32Free(ctx, &v1, op1)))\n            goto exception;\n        sp[-1] = JS_NewInt32(ctx, ~v1);\n    }\n    return 0;\n exception:\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic int js_binary_arith_bigfloat(JSContext *ctx, OPCodeEnum op,\n                                    JSValue *pres, JSValue op1, JSValue op2)\n{\n    bf_t a_s, b_s, *r, *a, *b;\n    int ret;\n    JSValue res;\n    \n    res = JS_NewBigFloat(ctx);\n    if (JS_IsException(res)) {\n        JS_FreeValue(ctx, op1);\n        JS_FreeValue(ctx, op2);\n        return -1;\n    }\n    r = JS_GetBigFloat(res);\n    a = JS_ToBigFloat(ctx, &a_s, op1);\n    b = JS_ToBigFloat(ctx, &b_s, op2);\n    bf_init(ctx->bf_ctx, r);\n    switch(op) {\n    case OP_add:\n        ret = bf_add(r, a, b, ctx->fp_env.prec, ctx->fp_env.flags);\n        break;\n    case OP_sub:\n        ret = bf_sub(r, a, b, ctx->fp_env.prec, ctx->fp_env.flags);\n        break;\n    case OP_mul:\n        ret = bf_mul(r, a, b, ctx->fp_env.prec, ctx->fp_env.flags);\n        break;\n    case OP_div:\n        ret = bf_div(r, a, b, ctx->fp_env.prec, ctx->fp_env.flags);\n        break;\n    case OP_math_mod:\n        /* Euclidian remainder */\n        ret = bf_rem(r, a, b, ctx->fp_env.prec, ctx->fp_env.flags,\n                     BF_DIVREM_EUCLIDIAN);\n        break;\n    case OP_mod:\n        ret = bf_rem(r, a, b, ctx->fp_env.prec, ctx->fp_env.flags,\n                     BF_RNDZ);\n        break;\n    case OP_pow:\n        ret = bf_pow(r, a, b, ctx->fp_env.prec,\n                     ctx->fp_env.flags | BF_POW_JS_QUIRKS);\n        break;\n    default:\n        abort();\n    }\n    if (a == &a_s)\n        bf_delete(a);\n    if (b == &b_s)\n        bf_delete(b);\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    if (unlikely(ret & BF_ST_MEM_ERROR)) {\n        JS_FreeValue(ctx, res);\n        throw_bf_exception(ctx, ret);\n        return -1;\n    }\n    *pres = res;\n    return 0;\n}\n\nstatic int js_binary_arith_bigint(JSContext *ctx, OPCodeEnum op,\n                                  JSValue *pres, JSValue op1, JSValue op2)\n{\n    bf_t a_s, b_s, *r, *a, *b;\n    int ret;\n    JSValue res;\n    \n    res = JS_NewBigInt(ctx);\n    if (JS_IsException(res))\n        goto fail;\n    a = JS_ToBigInt(ctx, &a_s, op1);\n    if (!a)\n        goto fail;\n    b = JS_ToBigInt(ctx, &b_s, op2);\n    if (!b) {\n        JS_FreeBigInt(ctx, a, &a_s);\n        goto fail;\n    }\n    r = JS_GetBigInt(res);\n    ret = 0;\n    switch(op) {\n    case OP_add:\n        ret = bf_add(r, a, b, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_sub:\n        ret = bf_sub(r, a, b, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_mul:\n        ret = bf_mul(r, a, b, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_div:\n        if (!is_math_mode(ctx)) {\n            bf_t rem_s, *rem = &rem_s;\n            bf_init(ctx->bf_ctx, rem);\n            ret = bf_divrem(r, rem, a, b, BF_PREC_INF, BF_RNDZ,\n                            BF_RNDZ);\n            bf_delete(rem);\n        } else {\n            goto math_mode_div_pow;\n        }\n        break;\n    case OP_math_mod:\n        /* Euclidian remainder */\n        ret = bf_rem(r, a, b, BF_PREC_INF, BF_RNDZ,\n                     BF_DIVREM_EUCLIDIAN) & BF_ST_INVALID_OP;\n        break;\n    case OP_mod:\n        ret = bf_rem(r, a, b, BF_PREC_INF, BF_RNDZ,\n                     BF_RNDZ) & BF_ST_INVALID_OP;\n        break;\n    case OP_pow:\n        if (b->sign) {\n            if (!is_math_mode(ctx)) {\n                ret = BF_ST_INVALID_OP;\n            } else {\n            math_mode_div_pow:\n                JS_FreeValue(ctx, res);\n                ret = js_call_binary_op_simple(ctx, &res, ctx->class_proto[JS_CLASS_BIG_INT], op1, op2, op);\n                if (ret != 0) {\n                    JS_FreeBigInt(ctx, a, &a_s);\n                    JS_FreeBigInt(ctx, b, &b_s);\n                    JS_FreeValue(ctx, op1);\n                    JS_FreeValue(ctx, op2);\n                    if (ret < 0) {\n                        return -1;\n                    } else {\n                        *pres = res;\n                        return 0;\n                    }\n                }\n                /* if no BigInt power operator defined, return a\n                   bigfloat */\n                res = JS_NewBigFloat(ctx);\n                if (JS_IsException(res)) {\n                    JS_FreeBigInt(ctx, a, &a_s);\n                    JS_FreeBigInt(ctx, b, &b_s);\n                    goto fail;\n                }\n                r = JS_GetBigFloat(res);\n                if (op == OP_div) {\n                    ret = bf_div(r, a, b, ctx->fp_env.prec, ctx->fp_env.flags) & BF_ST_MEM_ERROR;\n                } else {\n                    ret = bf_pow(r, a, b, ctx->fp_env.prec,\n                                 ctx->fp_env.flags | BF_POW_JS_QUIRKS) & BF_ST_MEM_ERROR;\n                }\n                JS_FreeBigInt(ctx, a, &a_s);\n                JS_FreeBigInt(ctx, b, &b_s);\n                JS_FreeValue(ctx, op1);\n                JS_FreeValue(ctx, op2);\n                if (unlikely(ret)) {\n                    JS_FreeValue(ctx, res);\n                    throw_bf_exception(ctx, ret);\n                    return -1;\n                }\n                *pres = res;\n                return 0;\n            }\n        } else {\n            ret = bf_pow(r, a, b, BF_PREC_INF, BF_RNDZ | BF_POW_JS_QUIRKS);\n        }\n        break;\n\n        /* logical operations */\n    case OP_shl:\n    case OP_sar:\n        {\n            slimb_t v2;\n#if LIMB_BITS == 32\n            bf_get_int32(&v2, b, 0);\n            if (v2 == INT32_MIN)\n                v2 = INT32_MIN + 1;\n#else\n            bf_get_int64(&v2, b, 0);\n            if (v2 == INT64_MIN)\n                v2 = INT64_MIN + 1;\n#endif\n            if (op == OP_sar)\n                v2 = -v2;\n            ret = bf_set(r, a);\n            ret |= bf_mul_2exp(r, v2, BF_PREC_INF, BF_RNDZ);\n            if (v2 < 0) {\n                ret |= bf_rint(r, BF_RNDD) & (BF_ST_OVERFLOW | BF_ST_MEM_ERROR);\n            }\n        }\n        break;\n    case OP_and:\n        ret = bf_logic_and(r, a, b);\n        break;\n    case OP_or:\n        ret = bf_logic_or(r, a, b);\n        break;\n    case OP_xor:\n        ret = bf_logic_xor(r, a, b);\n        break;\n    default:\n        abort();\n    }\n    JS_FreeBigInt(ctx, a, &a_s);\n    JS_FreeBigInt(ctx, b, &b_s);\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    if (unlikely(ret)) {\n        JS_FreeValue(ctx, res);\n        throw_bf_exception(ctx, ret);\n        return -1;\n    }\n    *pres = JS_CompactBigInt(ctx, res);\n    return 0;\n fail:\n    JS_FreeValue(ctx, res);\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    return -1;\n}\n\n/* b must be a positive integer */\nstatic int js_bfdec_pow(bfdec_t *r, const bfdec_t *a, const bfdec_t *b)\n{\n    bfdec_t b1;\n    int32_t b2;\n    int ret;\n\n    bfdec_init(b->ctx, &b1);\n    ret = bfdec_set(&b1, b);\n    if (ret) {\n        bfdec_delete(&b1);\n        return ret;\n    }\n    ret = bfdec_rint(&b1, BF_RNDZ);\n    if (ret) {\n        bfdec_delete(&b1);\n        return BF_ST_INVALID_OP; /* must be an integer */\n    }\n    ret = bfdec_get_int32(&b2, &b1);\n    bfdec_delete(&b1);\n    if (ret)\n        return ret; /* overflow */\n    if (b2 < 0)\n        return BF_ST_INVALID_OP; /* must be positive */\n    return bfdec_pow_ui(r, a, b2);\n}\n\nstatic int js_binary_arith_bigdecimal(JSContext *ctx, OPCodeEnum op,\n                                      JSValue *pres, JSValue op1, JSValue op2)\n{\n    bfdec_t *r, *a, *b;\n    int ret;\n    JSValue res;\n\n    res = JS_NewBigDecimal(ctx);\n    if (JS_IsException(res))\n        goto fail;\n    r = JS_GetBigDecimal(res);\n    \n    a = JS_ToBigDecimal(ctx, op1);\n    if (!a)\n        goto fail;\n    b = JS_ToBigDecimal(ctx, op2);\n    if (!b)\n        goto fail;\n    switch(op) {\n    case OP_add:\n        ret = bfdec_add(r, a, b, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_sub:\n        ret = bfdec_sub(r, a, b, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_mul:\n        ret = bfdec_mul(r, a, b, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_div:\n        ret = bfdec_div(r, a, b, BF_PREC_INF, BF_RNDZ);\n        break;\n    case OP_math_mod:\n        /* Euclidian remainder */\n        ret = bfdec_rem(r, a, b, BF_PREC_INF, BF_RNDZ, BF_DIVREM_EUCLIDIAN);\n        break;\n    case OP_mod:\n        ret = bfdec_rem(r, a, b, BF_PREC_INF, BF_RNDZ, BF_RNDZ);\n        break;\n    case OP_pow:\n        ret = js_bfdec_pow(r, a, b);\n        break;\n    default:\n        abort();\n    }\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    if (unlikely(ret)) {\n        JS_FreeValue(ctx, res);\n        throw_bf_exception(ctx, ret);\n        return -1;\n    }\n    *pres = res;\n    return 0;\n fail:\n    JS_FreeValue(ctx, res);\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    return -1;\n}\n\nstatic no_inline __exception int js_binary_arith_slow(JSContext *ctx, JSValue *sp,\n                                                      OPCodeEnum op)\n{\n    JSValue op1, op2, res;\n    uint32_t tag1, tag2;\n    int ret;\n    double d1, d2;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n    /* fast path for float operations */\n    if (tag1 == JS_TAG_FLOAT64 && tag2 == JS_TAG_FLOAT64) {\n        d1 = JS_VALUE_GET_FLOAT64(op1);\n        d2 = JS_VALUE_GET_FLOAT64(op2);\n        goto handle_float64;\n    }\n\n    /* try to call an overloaded operator */\n    if ((tag1 == JS_TAG_OBJECT &&\n         (tag2 != JS_TAG_NULL && tag2 != JS_TAG_UNDEFINED)) ||\n        (tag2 == JS_TAG_OBJECT &&\n         (tag1 != JS_TAG_NULL && tag1 != JS_TAG_UNDEFINED))) {\n        ret = js_call_binary_op_fallback(ctx, &res, op1, op2, op, TRUE, 0);\n        if (ret != 0) {\n            JS_FreeValue(ctx, op1);\n            JS_FreeValue(ctx, op2);\n            if (ret < 0) {\n                goto exception;\n            } else {\n                sp[-2] = res;\n                return 0;\n            }\n        }\n    }\n\n    op1 = JS_ToNumericFree(ctx, op1);\n    if (JS_IsException(op1)) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    op2 = JS_ToNumericFree(ctx, op2);\n    if (JS_IsException(op2)) {\n        JS_FreeValue(ctx, op1);\n        goto exception;\n    }\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n\n    if (tag1 == JS_TAG_INT && tag2 == JS_TAG_INT) {\n        int32_t v1, v2;\n        int64_t v;\n        v1 = JS_VALUE_GET_INT(op1);\n        v2 = JS_VALUE_GET_INT(op2);\n        switch(op) {\n        case OP_sub:\n            v = (int64_t)v1 - (int64_t)v2;\n            break;\n        case OP_mul:\n            v = (int64_t)v1 * (int64_t)v2;\n            if (is_math_mode(ctx) &&\n                (v < -MAX_SAFE_INTEGER || v > MAX_SAFE_INTEGER))\n                goto handle_bigint;\n            if (v == 0 && (v1 | v2) < 0) {\n                sp[-2] = __JS_NewFloat64(ctx, -0.0);\n                return 0;\n            }\n            break;\n        case OP_div:\n            if (is_math_mode(ctx))\n                goto handle_bigint;\n            sp[-2] = __JS_NewFloat64(ctx, (double)v1 / (double)v2);\n            return 0;\n        case OP_math_mod:\n            if (unlikely(v2 == 0)) {\n                throw_bf_exception(ctx, BF_ST_DIVIDE_ZERO);\n                goto exception;\n            }\n            v = (int64_t)v1 % (int64_t)v2;\n            if (v < 0) {\n                if (v2 < 0)\n                    v -= v2;\n                else\n                    v += v2;\n            }\n            break;\n        case OP_mod:\n            if (v1 < 0 || v2 <= 0) {\n                sp[-2] = JS_NewFloat64(ctx, fmod(v1, v2));\n                return 0;\n            } else {\n                v = (int64_t)v1 % (int64_t)v2;\n            }\n            break;\n        case OP_pow:\n            if (!is_math_mode(ctx)) {\n                sp[-2] = JS_NewFloat64(ctx, js_pow(v1, v2));\n                return 0;\n            } else {\n                goto handle_bigint;\n            }\n            break;\n        default:\n            abort();\n        }\n        sp[-2] = JS_NewInt64(ctx, v);\n    } else if (tag1 == JS_TAG_BIG_DECIMAL || tag2 == JS_TAG_BIG_DECIMAL) {\n        if (ctx->rt->bigdecimal_ops.binary_arith(ctx, op, sp - 2, op1, op2))\n            goto exception;\n    } else if (tag1 == JS_TAG_BIG_FLOAT || tag2 == JS_TAG_BIG_FLOAT) {\n        if (ctx->rt->bigfloat_ops.binary_arith(ctx, op, sp - 2, op1, op2))\n            goto exception;\n    } else if (tag1 == JS_TAG_BIG_INT || tag2 == JS_TAG_BIG_INT) {\n    handle_bigint:\n        if (ctx->rt->bigint_ops.binary_arith(ctx, op, sp - 2, op1, op2))\n            goto exception;\n    } else {\n        double dr;\n        /* float64 result */\n        if (JS_ToFloat64Free(ctx, &d1, op1)) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n        if (JS_ToFloat64Free(ctx, &d2, op2))\n            goto exception;\n    handle_float64:\n        if (is_math_mode(ctx) && is_safe_integer(d1) && is_safe_integer(d2))\n            goto handle_bigint;\n        switch(op) {\n        case OP_sub:\n            dr = d1 - d2;\n            break;\n        case OP_mul:\n            dr = d1 * d2;\n            break;\n        case OP_div:\n            dr = d1 / d2;\n            break;\n        case OP_mod:\n            dr = fmod(d1, d2);\n            break;\n        case OP_math_mod:\n            d2 = fabs(d2);\n            dr = fmod(d1, d2);\n            /* XXX: loss of accuracy if dr < 0 */\n            if (dr < 0)\n                dr += d2;\n            break;\n        case OP_pow:\n            dr = js_pow(d1, d2);\n            break;\n        default:\n            abort();\n        }\n        sp[-2] = __JS_NewFloat64(ctx, dr);\n    }\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic no_inline __exception int js_add_slow(JSContext *ctx, JSValue *sp)\n{\n    JSValue op1, op2, res;\n    uint32_t tag1, tag2;\n    int ret;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n    /* fast path for float64 */\n    if (tag1 == JS_TAG_FLOAT64 && tag2 == JS_TAG_FLOAT64) {\n        double d1, d2;\n        d1 = JS_VALUE_GET_FLOAT64(op1);\n        d2 = JS_VALUE_GET_FLOAT64(op2);\n        sp[-2] = __JS_NewFloat64(ctx, d1 + d2);\n        return 0;\n    }\n\n    if (tag1 == JS_TAG_OBJECT || tag2 == JS_TAG_OBJECT) {\n        /* try to call an overloaded operator */\n        if ((tag1 == JS_TAG_OBJECT &&\n             (tag2 != JS_TAG_NULL && tag2 != JS_TAG_UNDEFINED &&\n              tag2 != JS_TAG_STRING)) ||\n            (tag2 == JS_TAG_OBJECT &&\n             (tag1 != JS_TAG_NULL && tag1 != JS_TAG_UNDEFINED &&\n              tag1 != JS_TAG_STRING))) {\n            ret = js_call_binary_op_fallback(ctx, &res, op1, op2, OP_add,\n                                             FALSE, HINT_NONE);\n            if (ret != 0) {\n                JS_FreeValue(ctx, op1);\n                JS_FreeValue(ctx, op2);\n                if (ret < 0) {\n                    goto exception;\n                } else {\n                    sp[-2] = res;\n                    return 0;\n                }\n            }\n        }\n\n        op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE);\n        if (JS_IsException(op1)) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n\n        op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NONE);\n        if (JS_IsException(op2)) {\n            JS_FreeValue(ctx, op1);\n            goto exception;\n        }\n        tag1 = JS_VALUE_GET_NORM_TAG(op1);\n        tag2 = JS_VALUE_GET_NORM_TAG(op2);\n    }\n\n    if (tag1 == JS_TAG_STRING || tag2 == JS_TAG_STRING) {\n        sp[-2] = JS_ConcatString(ctx, op1, op2);\n        if (JS_IsException(sp[-2]))\n            goto exception;\n        return 0;\n    }\n\n    op1 = JS_ToNumericFree(ctx, op1);\n    if (JS_IsException(op1)) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    op2 = JS_ToNumericFree(ctx, op2);\n    if (JS_IsException(op2)) {\n        JS_FreeValue(ctx, op1);\n        goto exception;\n    }\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n\n    if (tag1 == JS_TAG_INT && tag2 == JS_TAG_INT) {\n        int32_t v1, v2;\n        int64_t v;\n        v1 = JS_VALUE_GET_INT(op1);\n        v2 = JS_VALUE_GET_INT(op2);\n        v = (int64_t)v1 + (int64_t)v2;\n        sp[-2] = JS_NewInt64(ctx, v);\n    } else if (tag1 == JS_TAG_BIG_DECIMAL || tag2 == JS_TAG_BIG_DECIMAL) {\n        if (ctx->rt->bigdecimal_ops.binary_arith(ctx, OP_add, sp - 2, op1, op2))\n            goto exception;\n    } else if (tag1 == JS_TAG_BIG_FLOAT || tag2 == JS_TAG_BIG_FLOAT) {\n        if (ctx->rt->bigfloat_ops.binary_arith(ctx, OP_add, sp - 2, op1, op2))\n            goto exception;\n    } else if (tag1 == JS_TAG_BIG_INT || tag2 == JS_TAG_BIG_INT) {\n    handle_bigint:\n        if (ctx->rt->bigint_ops.binary_arith(ctx, OP_add, sp - 2, op1, op2))\n            goto exception;\n    } else {\n        double d1, d2;\n        /* float64 result */\n        if (JS_ToFloat64Free(ctx, &d1, op1)) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n        if (JS_ToFloat64Free(ctx, &d2, op2))\n            goto exception;\n        if (is_math_mode(ctx) && is_safe_integer(d1) && is_safe_integer(d2))\n            goto handle_bigint;\n        sp[-2] = __JS_NewFloat64(ctx, d1 + d2);\n    }\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic no_inline __exception int js_binary_logic_slow(JSContext *ctx,\n                                                      JSValue *sp,\n                                                      OPCodeEnum op)\n{\n    JSValue op1, op2, res;\n    int ret;\n    uint32_t tag1, tag2;\n    uint32_t v1, v2, r;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n\n    /* try to call an overloaded operator */\n    if ((tag1 == JS_TAG_OBJECT &&\n         (tag2 != JS_TAG_NULL && tag2 != JS_TAG_UNDEFINED)) ||\n        (tag2 == JS_TAG_OBJECT &&\n         (tag1 != JS_TAG_NULL && tag1 != JS_TAG_UNDEFINED))) {\n        ret = js_call_binary_op_fallback(ctx, &res, op1, op2, op, TRUE, 0);\n        if (ret != 0) {\n            JS_FreeValue(ctx, op1);\n            JS_FreeValue(ctx, op2);\n            if (ret < 0) {\n                goto exception;\n            } else {\n                sp[-2] = res;\n                return 0;\n            }\n        }\n    }\n\n    op1 = JS_ToNumericFree(ctx, op1);\n    if (JS_IsException(op1)) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    op2 = JS_ToNumericFree(ctx, op2);\n    if (JS_IsException(op2)) {\n        JS_FreeValue(ctx, op1);\n        goto exception;\n    }\n\n    if (is_math_mode(ctx))\n        goto bigint_op;\n\n    tag1 = JS_VALUE_GET_TAG(op1);\n    tag2 = JS_VALUE_GET_TAG(op2);\n    if (tag1 == JS_TAG_BIG_INT || tag2 == JS_TAG_BIG_INT) {\n        if (tag1 != tag2) {\n            JS_FreeValue(ctx, op1);\n            JS_FreeValue(ctx, op2);\n            JS_ThrowTypeError(ctx, \"both operands must be bigint\");\n            goto exception;\n        } else {\n        bigint_op:\n            if (ctx->rt->bigint_ops.binary_arith(ctx, op, sp - 2, op1, op2))\n                goto exception;\n        }\n    } else {\n        if (unlikely(JS_ToInt32Free(ctx, (int32_t *)&v1, op1))) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n        if (unlikely(JS_ToInt32Free(ctx, (int32_t *)&v2, op2)))\n            goto exception;\n        switch(op) {\n        case OP_shl:\n            r = v1 << (v2 & 0x1f);\n            break;\n        case OP_sar:\n            r = (int)v1 >> (v2 & 0x1f);\n            break;\n        case OP_and:\n            r = v1 & v2;\n            break;\n        case OP_or:\n            r = v1 | v2;\n            break;\n        case OP_xor:\n            r = v1 ^ v2;\n            break;\n        default:\n            abort();\n        }\n        sp[-2] = JS_NewInt32(ctx, r);\n    }\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\n/* Note: also used for bigint */\nstatic int js_compare_bigfloat(JSContext *ctx, OPCodeEnum op,\n                               JSValue op1, JSValue op2)\n{\n    bf_t a_s, b_s, *a, *b;\n    int res;\n    \n    a = JS_ToBigFloat(ctx, &a_s, op1);\n    if (!a) {\n        JS_FreeValue(ctx, op2);\n        return -1;\n    }\n    b = JS_ToBigFloat(ctx, &b_s, op2);\n    if (!b) {\n        if (a == &a_s)\n            bf_delete(a);\n        JS_FreeValue(ctx, op1);\n        return -1;\n    }\n    switch(op) {\n    case OP_lt:\n        res = bf_cmp_lt(a, b); /* if NaN return false */\n        break;\n    case OP_lte:\n        res = bf_cmp_le(a, b); /* if NaN return false */\n        break;\n    case OP_gt:\n        res = bf_cmp_lt(b, a); /* if NaN return false */\n        break;\n    case OP_gte:\n        res = bf_cmp_le(b, a); /* if NaN return false */\n        break;\n    case OP_eq:\n        res = bf_cmp_eq(a, b); /* if NaN return false */\n        break;\n    default:\n        abort();\n    }\n    if (a == &a_s)\n        bf_delete(a);\n    if (b == &b_s)\n        bf_delete(b);\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    return res;\n}\n\nstatic int js_compare_bigdecimal(JSContext *ctx, OPCodeEnum op,\n                                 JSValue op1, JSValue op2)\n{\n    bfdec_t *a, *b;\n    int res;\n\n    /* Note: binary floats are converted to bigdecimal with\n       toString(). It is not mathematically correct but is consistent\n       with the BigDecimal() constructor behavior */\n    op1 = JS_ToBigDecimalFree(ctx, op1, TRUE);\n    if (JS_IsException(op1)) {\n        JS_FreeValue(ctx, op2);\n        return -1;\n    }\n    op2 = JS_ToBigDecimalFree(ctx, op2, TRUE);\n    if (JS_IsException(op2)) {\n        JS_FreeValue(ctx, op1);\n        return -1;\n    }\n    a = JS_ToBigDecimal(ctx, op1);\n    b = JS_ToBigDecimal(ctx, op2);\n    \n    switch(op) {\n    case OP_lt:\n        res = bfdec_cmp_lt(a, b); /* if NaN return false */\n        break;\n    case OP_lte:\n        res = bfdec_cmp_le(a, b); /* if NaN return false */\n        break;\n    case OP_gt:\n        res = bfdec_cmp_lt(b, a); /* if NaN return false */\n        break;\n    case OP_gte:\n        res = bfdec_cmp_le(b, a); /* if NaN return false */\n        break;\n    case OP_eq:\n        res = bfdec_cmp_eq(a, b); /* if NaN return false */\n        break;\n    default:\n        abort();\n    }\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    return res;\n}\n\nstatic no_inline int js_relational_slow(JSContext *ctx, JSValue *sp,\n                                        OPCodeEnum op)\n{\n    JSValue op1, op2, ret;\n    int res;\n    uint32_t tag1, tag2;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n    /* try to call an overloaded operator */\n    if ((tag1 == JS_TAG_OBJECT &&\n         (tag2 != JS_TAG_NULL && tag2 != JS_TAG_UNDEFINED)) ||\n        (tag2 == JS_TAG_OBJECT &&\n         (tag1 != JS_TAG_NULL && tag1 != JS_TAG_UNDEFINED))) {\n        res = js_call_binary_op_fallback(ctx, &ret, op1, op2, op,\n                                         FALSE, HINT_NUMBER);\n        if (res != 0) {\n            JS_FreeValue(ctx, op1);\n            JS_FreeValue(ctx, op2);\n            if (res < 0) {\n                goto exception;\n            } else {\n                sp[-2] = ret;\n                return 0;\n            }\n        }\n    }\n    op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NUMBER);\n    if (JS_IsException(op1)) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NUMBER);\n    if (JS_IsException(op2)) {\n        JS_FreeValue(ctx, op1);\n        goto exception;\n    }\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n\n    if (tag1 == JS_TAG_STRING && tag2 == JS_TAG_STRING) {\n        JSString *p1, *p2;\n        p1 = JS_VALUE_GET_STRING(op1);\n        p2 = JS_VALUE_GET_STRING(op2);\n        res = js_string_compare(ctx, p1, p2);\n        switch(op) {\n        case OP_lt:\n            res = (res < 0);\n            break;\n        case OP_lte:\n            res = (res <= 0);\n            break;\n        case OP_gt:\n            res = (res > 0);\n            break;\n        default:\n        case OP_gte:\n            res = (res >= 0);\n            break;\n        }\n        JS_FreeValue(ctx, op1);\n        JS_FreeValue(ctx, op2);\n    } else if ((tag1 <= JS_TAG_NULL || tag1 == JS_TAG_FLOAT64) &&\n               (tag2 <= JS_TAG_NULL || tag2 == JS_TAG_FLOAT64)) {\n        /* fast path for float64/int */\n        goto float64_compare;\n    } else {\n        if (((tag1 == JS_TAG_BIG_INT && tag2 == JS_TAG_STRING) ||\n             (tag2 == JS_TAG_BIG_INT && tag1 == JS_TAG_STRING)) &&\n            !is_math_mode(ctx)) {\n            if (tag1 == JS_TAG_STRING) {\n                op1 = JS_StringToBigInt(ctx, op1);\n                if (JS_VALUE_GET_TAG(op1) != JS_TAG_BIG_INT)\n                    goto invalid_bigint_string;\n            }\n            if (tag2 == JS_TAG_STRING) {\n                op2 = JS_StringToBigInt(ctx, op2);\n                if (JS_VALUE_GET_TAG(op2) != JS_TAG_BIG_INT) {\n                invalid_bigint_string:\n                    JS_FreeValue(ctx, op1);\n                    JS_FreeValue(ctx, op2);\n                    res = FALSE;\n                    goto done;\n                }\n            }\n        } else {\n            op1 = JS_ToNumericFree(ctx, op1);\n            if (JS_IsException(op1)) {\n                JS_FreeValue(ctx, op2);\n                goto exception;\n            }\n            op2 = JS_ToNumericFree(ctx, op2);\n            if (JS_IsException(op2)) {\n                JS_FreeValue(ctx, op1);\n                goto exception;\n            }\n        }\n\n        tag1 = JS_VALUE_GET_NORM_TAG(op1);\n        tag2 = JS_VALUE_GET_NORM_TAG(op2);\n\n        if (tag1 == JS_TAG_BIG_DECIMAL || tag2 == JS_TAG_BIG_DECIMAL) {\n            res = ctx->rt->bigdecimal_ops.compare(ctx, op, op1, op2);\n            if (res < 0)\n                goto exception;\n        } else if (tag1 == JS_TAG_BIG_FLOAT || tag2 == JS_TAG_BIG_FLOAT) {\n            res = ctx->rt->bigfloat_ops.compare(ctx, op, op1, op2);\n            if (res < 0)\n                goto exception;\n        } else if (tag1 == JS_TAG_BIG_INT || tag2 == JS_TAG_BIG_INT) {\n            res = ctx->rt->bigint_ops.compare(ctx, op, op1, op2);\n            if (res < 0)\n                goto exception;\n        } else {\n            double d1, d2;\n\n        float64_compare:\n            /* can use floating point comparison */\n            if (tag1 == JS_TAG_FLOAT64) {\n                d1 = JS_VALUE_GET_FLOAT64(op1);\n            } else {\n                d1 = JS_VALUE_GET_INT(op1);\n            }\n            if (tag2 == JS_TAG_FLOAT64) {\n                d2 = JS_VALUE_GET_FLOAT64(op2);\n            } else {\n                d2 = JS_VALUE_GET_INT(op2);\n            }\n            switch(op) {\n            case OP_lt:\n                res = (d1 < d2); /* if NaN return false */\n                break;\n            case OP_lte:\n                res = (d1 <= d2); /* if NaN return false */\n                break;\n            case OP_gt:\n                res = (d1 > d2); /* if NaN return false */\n                break;\n            default:\n            case OP_gte:\n                res = (d1 >= d2); /* if NaN return false */\n                break;\n            }\n        }\n    }\n done:\n    sp[-2] = JS_NewBool(ctx, res);\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic BOOL tag_is_number(uint32_t tag)\n{\n    return (tag == JS_TAG_INT || tag == JS_TAG_BIG_INT ||\n            tag == JS_TAG_FLOAT64 || tag == JS_TAG_BIG_FLOAT ||\n            tag == JS_TAG_BIG_DECIMAL);\n}\n\nstatic no_inline __exception int js_eq_slow(JSContext *ctx, JSValue *sp,\n                                            BOOL is_neq)\n{\n    JSValue op1, op2, ret;\n    int res;\n    uint32_t tag1, tag2;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n redo:\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n    if (tag_is_number(tag1) && tag_is_number(tag2)) {\n        if (tag1 == JS_TAG_INT && tag2 == JS_TAG_INT) {\n            res = JS_VALUE_GET_INT(op1) == JS_VALUE_GET_INT(op2);\n        } else if ((tag1 == JS_TAG_FLOAT64 &&\n                    (tag2 == JS_TAG_INT || tag2 == JS_TAG_FLOAT64)) ||\n                   (tag2 == JS_TAG_FLOAT64 &&\n                    (tag1 == JS_TAG_INT || tag1 == JS_TAG_FLOAT64))) {\n            double d1, d2;\n            if (tag1 == JS_TAG_FLOAT64) {\n                d1 = JS_VALUE_GET_FLOAT64(op1);\n            } else {\n                d1 = JS_VALUE_GET_INT(op1);\n            }\n            if (tag2 == JS_TAG_FLOAT64) {\n                d2 = JS_VALUE_GET_FLOAT64(op2);\n            } else {\n                d2 = JS_VALUE_GET_INT(op2);\n            }\n            res = (d1 == d2);\n        } else if (tag1 == JS_TAG_BIG_DECIMAL || tag2 == JS_TAG_BIG_DECIMAL) {\n            res = ctx->rt->bigdecimal_ops.compare(ctx, OP_eq, op1, op2);\n            if (res < 0)\n                goto exception;\n        } else if (tag1 == JS_TAG_BIG_FLOAT || tag2 == JS_TAG_BIG_FLOAT) {\n            res = ctx->rt->bigfloat_ops.compare(ctx, OP_eq, op1, op2);\n            if (res < 0)\n                goto exception;\n        } else {\n            res = ctx->rt->bigint_ops.compare(ctx, OP_eq, op1, op2);\n            if (res < 0)\n                goto exception;\n        }\n    } else if (tag1 == tag2) {\n        if (tag1 == JS_TAG_OBJECT) {\n            /* try the fallback operator */\n            res = js_call_binary_op_fallback(ctx, &ret, op1, op2,\n                                             is_neq ? OP_neq : OP_eq,\n                                             FALSE, HINT_NONE);\n            if (res != 0) {\n                JS_FreeValue(ctx, op1);\n                JS_FreeValue(ctx, op2);\n                if (res < 0) {\n                    goto exception;\n                } else {\n                    sp[-2] = ret;\n                    return 0;\n                }\n            }\n        }\n        res = js_strict_eq2(ctx, op1, op2, JS_EQ_STRICT);\n    } else if ((tag1 == JS_TAG_NULL && tag2 == JS_TAG_UNDEFINED) ||\n               (tag2 == JS_TAG_NULL && tag1 == JS_TAG_UNDEFINED)) {\n        res = TRUE;\n    } else if ((tag1 == JS_TAG_STRING && tag_is_number(tag2)) ||\n               (tag2 == JS_TAG_STRING && tag_is_number(tag1))) {\n\n        if ((tag1 == JS_TAG_BIG_INT || tag2 == JS_TAG_BIG_INT) &&\n            !is_math_mode(ctx)) {\n            if (tag1 == JS_TAG_STRING) {\n                op1 = JS_StringToBigInt(ctx, op1);\n                if (JS_VALUE_GET_TAG(op1) != JS_TAG_BIG_INT)\n                    goto invalid_bigint_string;\n            }\n            if (tag2 == JS_TAG_STRING) {\n                op2 = JS_StringToBigInt(ctx, op2);\n                if (JS_VALUE_GET_TAG(op2) != JS_TAG_BIG_INT) {\n                invalid_bigint_string:\n                    JS_FreeValue(ctx, op1);\n                    JS_FreeValue(ctx, op2);\n                    res = FALSE;\n                    goto done;\n                }\n            }\n        } else {\n            op1 = JS_ToNumericFree(ctx, op1);\n            if (JS_IsException(op1)) {\n                JS_FreeValue(ctx, op2);\n                goto exception;\n            }\n            op2 = JS_ToNumericFree(ctx, op2);\n            if (JS_IsException(op2)) {\n                JS_FreeValue(ctx, op1);\n                goto exception;\n            }\n        }\n        res = js_strict_eq(ctx, op1, op2);\n    } else if (tag1 == JS_TAG_BOOL) {\n        op1 = JS_NewInt32(ctx, JS_VALUE_GET_INT(op1));\n        goto redo;\n    } else if (tag2 == JS_TAG_BOOL) {\n        op2 = JS_NewInt32(ctx, JS_VALUE_GET_INT(op2));\n        goto redo;\n    } else if ((tag1 == JS_TAG_OBJECT &&\n                (tag_is_number(tag2) || tag2 == JS_TAG_STRING || tag2 == JS_TAG_SYMBOL)) ||\n               (tag2 == JS_TAG_OBJECT &&\n                (tag_is_number(tag1) || tag1 == JS_TAG_STRING || tag1 == JS_TAG_SYMBOL))) {\n\n        /* try the fallback operator */\n        res = js_call_binary_op_fallback(ctx, &ret, op1, op2,\n                                         is_neq ? OP_neq : OP_eq,\n                                         FALSE, HINT_NONE);\n        if (res != 0) {\n            JS_FreeValue(ctx, op1);\n            JS_FreeValue(ctx, op2);\n            if (res < 0) {\n                goto exception;\n            } else {\n                sp[-2] = ret;\n                return 0;\n            }\n        }\n\n        op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE);\n        if (JS_IsException(op1)) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n        op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NONE);\n        if (JS_IsException(op2)) {\n            JS_FreeValue(ctx, op1);\n            goto exception;\n        }\n        goto redo;\n    } else {\n        /* IsHTMLDDA object is equivalent to undefined for '==' and '!=' */\n        if ((JS_IsHTMLDDA(ctx, op1) &&\n             (tag2 == JS_TAG_NULL || tag2 == JS_TAG_UNDEFINED)) ||\n            (JS_IsHTMLDDA(ctx, op2) &&\n             (tag1 == JS_TAG_NULL || tag1 == JS_TAG_UNDEFINED))) {\n            res = TRUE;\n        } else {\n            res = FALSE;\n        }\n        JS_FreeValue(ctx, op1);\n        JS_FreeValue(ctx, op2);\n    }\n done:\n    sp[-2] = JS_NewBool(ctx, res ^ is_neq);\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic no_inline int js_shr_slow(JSContext *ctx, JSValue *sp)\n{\n    JSValue op1, op2;\n    uint32_t v1, v2, r;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    op1 = JS_ToNumericFree(ctx, op1);\n    if (JS_IsException(op1)) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    op2 = JS_ToNumericFree(ctx, op2);\n    if (JS_IsException(op2)) {\n        JS_FreeValue(ctx, op1);\n        goto exception;\n    }\n    /* XXX: could forbid >>> in bignum mode */\n    if (!is_math_mode(ctx) &&\n        (JS_VALUE_GET_TAG(op1) == JS_TAG_BIG_INT ||\n         JS_VALUE_GET_TAG(op2) == JS_TAG_BIG_INT)) {\n        JS_ThrowTypeError(ctx, \"bigint operands are forbidden for >>>\");\n        JS_FreeValue(ctx, op1);\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    /* cannot give an exception */\n    JS_ToUint32Free(ctx, &v1, op1);\n    JS_ToUint32Free(ctx, &v2, op2);\n    r = v1 >> (v2 & 0x1f);\n    sp[-2] = JS_NewUint32(ctx, r);\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic JSValue js_mul_pow10_to_float64(JSContext *ctx, const bf_t *a,\n                                       int64_t exponent)\n{\n    bf_t r_s, *r = &r_s;\n    double d;\n    int ret;\n    \n    /* always convert to Float64 */\n    bf_init(ctx->bf_ctx, r);\n    ret = bf_mul_pow_radix(r, a, 10, exponent,\n                           53, bf_set_exp_bits(11) | BF_RNDN |\n                           BF_FLAG_SUBNORMAL);\n    bf_get_float64(r, &d, BF_RNDN);\n    bf_delete(r);\n    if (ret & BF_ST_MEM_ERROR)\n        return JS_ThrowOutOfMemory(ctx);\n    else\n        return __JS_NewFloat64(ctx, d);\n}\n\nstatic no_inline int js_mul_pow10(JSContext *ctx, JSValue *sp)\n{\n    bf_t a_s, *a, *r;\n    JSValue op1, op2, res;\n    int64_t e;\n    int ret;\n\n    res = JS_NewBigFloat(ctx);\n    if (JS_IsException(res))\n        return -1;\n    r = JS_GetBigFloat(res);\n    op1 = sp[-2];\n    op2 = sp[-1];\n    a = JS_ToBigFloat(ctx, &a_s, op1);\n    if (!a)\n        return -1;\n    if (JS_IsBigInt(ctx, op2)) {\n        ret = JS_ToBigInt64(ctx, &e, op2);\n    } else {\n        ret = JS_ToInt64(ctx, &e, op2);\n    }\n    if (ret) {\n        if (a == &a_s)\n            bf_delete(a);\n        JS_FreeValue(ctx, res);\n        return -1;\n    }\n\n    bf_mul_pow_radix(r, a, 10, e, ctx->fp_env.prec, ctx->fp_env.flags);\n    if (a == &a_s)\n        bf_delete(a);\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    sp[-2] = res;\n    return 0;\n}\n\n#else /* !CONFIG_BIGNUM */\n\nstatic JSValue JS_ThrowUnsupportedBigint(JSContext *ctx)\n{\n    return JS_ThrowTypeError(ctx, \"bigint is not supported\");\n}\n\nJSValue JS_NewBigInt64(JSContext *ctx, int64_t v)\n{\n    return JS_ThrowUnsupportedBigint(ctx);\n}\n\nJSValue JS_NewBigUint64(JSContext *ctx, uint64_t v)\n{\n    return JS_ThrowUnsupportedBigint(ctx);\n}\n\nint JS_ToBigInt64(JSContext *ctx, int64_t *pres, JSValueConst val)\n{\n    JS_ThrowUnsupportedBigint(ctx);\n    *pres = 0;\n    return -1;\n}\n\nstatic no_inline __exception int js_unary_arith_slow(JSContext *ctx,\n                                                     JSValue *sp,\n                                                     OPCodeEnum op)\n{\n    JSValue op1;\n    double d;\n\n    op1 = sp[-1];\n    if (unlikely(JS_ToFloat64Free(ctx, &d, op1))) {\n        sp[-1] = JS_UNDEFINED;\n        return -1;\n    }\n    switch(op) {\n    case OP_inc:\n        d++;\n        break;\n    case OP_dec:\n        d--;\n        break;\n    case OP_plus:\n        break;\n    case OP_neg:\n        d = -d;\n        break;\n    default:\n        abort();\n    }\n    sp[-1] = JS_NewFloat64(ctx, d);\n    return 0;\n}\n\n/* specific case necessary for correct return value semantics */\nstatic __exception int js_post_inc_slow(JSContext *ctx,\n                                        JSValue *sp, OPCodeEnum op)\n{\n    JSValue op1;\n    double d, r;\n\n    op1 = sp[-1];\n    if (unlikely(JS_ToFloat64Free(ctx, &d, op1))) {\n        sp[-1] = JS_UNDEFINED;\n        return -1;\n    }\n    r = d + 2 * (op - OP_post_dec) - 1;\n    sp[0] = JS_NewFloat64(ctx, r);\n    sp[-1] = JS_NewFloat64(ctx, d);\n    return 0;\n}\n\nstatic no_inline __exception int js_binary_arith_slow(JSContext *ctx, JSValue *sp,\n                                                      OPCodeEnum op)\n{\n    JSValue op1, op2;\n    double d1, d2, r;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    if (unlikely(JS_ToFloat64Free(ctx, &d1, op1))) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    if (unlikely(JS_ToFloat64Free(ctx, &d2, op2))) {\n        goto exception;\n    }\n    switch(op) {\n    case OP_sub:\n        r = d1 - d2;\n        break;\n    case OP_mul:\n        r = d1 * d2;\n        break;\n    case OP_div:\n        r = d1 / d2;\n        break;\n    case OP_mod:\n        r = fmod(d1, d2);\n        break;\n    case OP_pow:\n        r = js_pow(d1, d2);\n        break;\n    default:\n        abort();\n    }\n    sp[-2] = JS_NewFloat64(ctx, r);\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic no_inline __exception int js_add_slow(JSContext *ctx, JSValue *sp)\n{\n    JSValue op1, op2;\n    uint32_t tag1, tag2;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    tag1 = JS_VALUE_GET_TAG(op1);\n    tag2 = JS_VALUE_GET_TAG(op2);\n    if ((tag1 == JS_TAG_INT || JS_TAG_IS_FLOAT64(tag1)) &&\n        (tag2 == JS_TAG_INT || JS_TAG_IS_FLOAT64(tag2))) {\n        goto add_numbers;\n    } else {\n        op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE);\n        if (JS_IsException(op1)) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n        op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NONE);\n        if (JS_IsException(op2)) {\n            JS_FreeValue(ctx, op1);\n            goto exception;\n        }\n        tag1 = JS_VALUE_GET_TAG(op1);\n        tag2 = JS_VALUE_GET_TAG(op2);\n        if (tag1 == JS_TAG_STRING || tag2 == JS_TAG_STRING) {\n            sp[-2] = JS_ConcatString(ctx, op1, op2);\n            if (JS_IsException(sp[-2]))\n                goto exception;\n        } else {\n            double d1, d2;\n        add_numbers:\n            if (JS_ToFloat64Free(ctx, &d1, op1)) {\n                JS_FreeValue(ctx, op2);\n                goto exception;\n            }\n            if (JS_ToFloat64Free(ctx, &d2, op2))\n                goto exception;\n            sp[-2] = JS_NewFloat64(ctx, d1 + d2);\n        }\n    }\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic no_inline __exception int js_binary_logic_slow(JSContext *ctx,\n                                                      JSValue *sp,\n                                                      OPCodeEnum op)\n{\n    JSValue op1, op2;\n    uint32_t v1, v2, r;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    if (unlikely(JS_ToInt32Free(ctx, (int32_t *)&v1, op1))) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    if (unlikely(JS_ToInt32Free(ctx, (int32_t *)&v2, op2)))\n        goto exception;\n    switch(op) {\n    case OP_shl:\n        r = v1 << (v2 & 0x1f);\n        break;\n    case OP_sar:\n        r = (int)v1 >> (v2 & 0x1f);\n        break;\n    case OP_and:\n        r = v1 & v2;\n        break;\n    case OP_or:\n        r = v1 | v2;\n        break;\n    case OP_xor:\n        r = v1 ^ v2;\n        break;\n    default:\n        abort();\n    }\n    sp[-2] = JS_NewInt32(ctx, r);\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic no_inline int js_not_slow(JSContext *ctx, JSValue *sp)\n{\n    int32_t v1;\n\n    if (unlikely(JS_ToInt32Free(ctx, &v1, sp[-1]))) {\n        sp[-1] = JS_UNDEFINED;\n        return -1;\n    }\n    sp[-1] = JS_NewInt32(ctx, ~v1);\n    return 0;\n}\n\nstatic no_inline int js_relational_slow(JSContext *ctx, JSValue *sp,\n                                        OPCodeEnum op)\n{\n    JSValue op1, op2;\n    int res;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NUMBER);\n    if (JS_IsException(op1)) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NUMBER);\n    if (JS_IsException(op2)) {\n        JS_FreeValue(ctx, op1);\n        goto exception;\n    }\n    if (JS_VALUE_GET_TAG(op1) == JS_TAG_STRING &&\n        JS_VALUE_GET_TAG(op2) == JS_TAG_STRING) {\n        JSString *p1, *p2;\n        p1 = JS_VALUE_GET_STRING(op1);\n        p2 = JS_VALUE_GET_STRING(op2);\n        res = js_string_compare(ctx, p1, p2);\n        JS_FreeValue(ctx, op1);\n        JS_FreeValue(ctx, op2);\n        switch(op) {\n        case OP_lt:\n            res = (res < 0);\n            break;\n        case OP_lte:\n            res = (res <= 0);\n            break;\n        case OP_gt:\n            res = (res > 0);\n            break;\n        default:\n        case OP_gte:\n            res = (res >= 0);\n            break;\n        }\n    } else {\n        double d1, d2;\n        if (JS_ToFloat64Free(ctx, &d1, op1)) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n        if (JS_ToFloat64Free(ctx, &d2, op2))\n            goto exception;\n        switch(op) {\n        case OP_lt:\n            res = (d1 < d2); /* if NaN return false */\n            break;\n        case OP_lte:\n            res = (d1 <= d2); /* if NaN return false */\n            break;\n        case OP_gt:\n            res = (d1 > d2); /* if NaN return false */\n            break;\n        default:\n        case OP_gte:\n            res = (d1 >= d2); /* if NaN return false */\n            break;\n        }\n    }\n    sp[-2] = JS_NewBool(ctx, res);\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic no_inline __exception int js_eq_slow(JSContext *ctx, JSValue *sp,\n                                            BOOL is_neq)\n{\n    JSValue op1, op2;\n    int tag1, tag2;\n    BOOL res;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n redo:\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n    if (tag1 == tag2 ||\n        (tag1 == JS_TAG_INT && tag2 == JS_TAG_FLOAT64) ||\n        (tag2 == JS_TAG_INT && tag1 == JS_TAG_FLOAT64)) {\n        res = js_strict_eq(ctx, op1, op2);\n    } else if ((tag1 == JS_TAG_NULL && tag2 == JS_TAG_UNDEFINED) ||\n               (tag2 == JS_TAG_NULL && tag1 == JS_TAG_UNDEFINED)) {\n        res = TRUE;\n    } else if ((tag1 == JS_TAG_STRING && (tag2 == JS_TAG_INT ||\n                                   tag2 == JS_TAG_FLOAT64)) ||\n        (tag2 == JS_TAG_STRING && (tag1 == JS_TAG_INT ||\n                                   tag1 == JS_TAG_FLOAT64))) {\n        double d1;\n        double d2;\n        if (JS_ToFloat64Free(ctx, &d1, op1)) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n        if (JS_ToFloat64Free(ctx, &d2, op2))\n            goto exception;\n        res = (d1 == d2);\n    } else if (tag1 == JS_TAG_BOOL) {\n        op1 = JS_NewInt32(ctx, JS_VALUE_GET_INT(op1));\n        goto redo;\n    } else if (tag2 == JS_TAG_BOOL) {\n        op2 = JS_NewInt32(ctx, JS_VALUE_GET_INT(op2));\n        goto redo;\n    } else if (tag1 == JS_TAG_OBJECT &&\n               (tag2 == JS_TAG_INT || tag2 == JS_TAG_FLOAT64 || tag2 == JS_TAG_STRING || tag2 == JS_TAG_SYMBOL)) {\n        op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE);\n        if (JS_IsException(op1)) {\n            JS_FreeValue(ctx, op2);\n            goto exception;\n        }\n        goto redo;\n    } else if (tag2 == JS_TAG_OBJECT &&\n               (tag1 == JS_TAG_INT || tag1 == JS_TAG_FLOAT64 || tag1 == JS_TAG_STRING || tag1 == JS_TAG_SYMBOL)) {\n        op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NONE);\n        if (JS_IsException(op2)) {\n            JS_FreeValue(ctx, op1);\n            goto exception;\n        }\n        goto redo;\n    } else {\n        /* IsHTMLDDA object is equivalent to undefined for '==' and '!=' */\n        if ((JS_IsHTMLDDA(ctx, op1) &&\n             (tag2 == JS_TAG_NULL || tag2 == JS_TAG_UNDEFINED)) ||\n            (JS_IsHTMLDDA(ctx, op2) &&\n             (tag1 == JS_TAG_NULL || tag1 == JS_TAG_UNDEFINED))) {\n            res = TRUE;\n        } else {\n            res = FALSE;\n        }\n        JS_FreeValue(ctx, op1);\n        JS_FreeValue(ctx, op2);\n    }\n    sp[-2] = JS_NewBool(ctx, res ^ is_neq);\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic no_inline int js_shr_slow(JSContext *ctx, JSValue *sp)\n{\n    JSValue op1, op2;\n    uint32_t v1, v2, r;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    if (unlikely(JS_ToUint32Free(ctx, &v1, op1))) {\n        JS_FreeValue(ctx, op2);\n        goto exception;\n    }\n    if (unlikely(JS_ToUint32Free(ctx, &v2, op2)))\n        goto exception;\n    r = v1 >> (v2 & 0x1f);\n    sp[-2] = JS_NewUint32(ctx, r);\n    return 0;\n exception:\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\n#endif /* !CONFIG_BIGNUM */\n\n/* XXX: Should take JSValueConst arguments */\nstatic BOOL js_strict_eq2(JSContext *ctx, JSValue op1, JSValue op2,\n                          JSStrictEqModeEnum eq_mode)\n{\n    BOOL res;\n    int tag1, tag2;\n    double d1, d2;\n\n    tag1 = JS_VALUE_GET_NORM_TAG(op1);\n    tag2 = JS_VALUE_GET_NORM_TAG(op2);\n    switch(tag1) {\n    case JS_TAG_BOOL:\n        if (tag1 != tag2) {\n            res = FALSE;\n        } else {\n            res = JS_VALUE_GET_INT(op1) == JS_VALUE_GET_INT(op2);\n            goto done_no_free;\n        }\n        break;\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        res = (tag1 == tag2);\n        break;\n    case JS_TAG_STRING:\n        {\n            JSString *p1, *p2;\n            if (tag1 != tag2) {\n                res = FALSE;\n            } else {\n                p1 = JS_VALUE_GET_STRING(op1);\n                p2 = JS_VALUE_GET_STRING(op2);\n                res = (js_string_compare(ctx, p1, p2) == 0);\n            }\n        }\n        break;\n    case JS_TAG_SYMBOL:\n        {\n            JSAtomStruct *p1, *p2;\n            if (tag1 != tag2) {\n                res = FALSE;\n            } else {\n                p1 = JS_VALUE_GET_PTR(op1);\n                p2 = JS_VALUE_GET_PTR(op2);\n                res = (p1 == p2);\n            }\n        }\n        break;\n    case JS_TAG_OBJECT:\n        if (tag1 != tag2)\n            res = FALSE;\n        else\n            res = JS_VALUE_GET_OBJ(op1) == JS_VALUE_GET_OBJ(op2);\n        break;\n    case JS_TAG_INT:\n        d1 = JS_VALUE_GET_INT(op1);\n        if (tag2 == JS_TAG_INT) {\n            d2 = JS_VALUE_GET_INT(op2);\n            goto number_test;\n        } else if (tag2 == JS_TAG_FLOAT64) {\n            d2 = JS_VALUE_GET_FLOAT64(op2);\n            goto number_test;\n        } else {\n            res = FALSE;\n        }\n        break;\n    case JS_TAG_FLOAT64:\n        d1 = JS_VALUE_GET_FLOAT64(op1);\n        if (tag2 == JS_TAG_FLOAT64) {\n            d2 = JS_VALUE_GET_FLOAT64(op2);\n        } else if (tag2 == JS_TAG_INT) {\n            d2 = JS_VALUE_GET_INT(op2);\n        } else {\n            res = FALSE;\n            break;\n        }\n    number_test:\n        if (unlikely(eq_mode >= JS_EQ_SAME_VALUE)) {\n            JSFloat64Union u1, u2;\n            /* NaN is not always normalized, so this test is necessary */\n            if (isnan(d1) || isnan(d2)) {\n                res = isnan(d1) == isnan(d2);\n            } else if (eq_mode == JS_EQ_SAME_VALUE_ZERO) {\n                res = (d1 == d2); /* +0 == -0 */\n            } else {\n                u1.d = d1;\n                u2.d = d2;\n                res = (u1.u64 == u2.u64); /* +0 != -0 */\n            }\n        } else {\n            res = (d1 == d2); /* if NaN return false and +0 == -0 */\n        }\n        goto done_no_free;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n        {\n            bf_t a_s, *a, b_s, *b;\n            if (tag1 != tag2) {\n                res = FALSE;\n                break;\n            }\n            a = JS_ToBigFloat(ctx, &a_s, op1);\n            b = JS_ToBigFloat(ctx, &b_s, op2);\n            res = bf_cmp_eq(a, b);\n            if (a == &a_s)\n                bf_delete(a);\n            if (b == &b_s)\n                bf_delete(b);\n        }\n        break;\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p1, *p2;\n            const bf_t *a, *b;\n            if (tag1 != tag2) {\n                res = FALSE;\n                break;\n            }\n            p1 = JS_VALUE_GET_PTR(op1);\n            p2 = JS_VALUE_GET_PTR(op2);\n            a = &p1->num;\n            b = &p2->num;\n            if (unlikely(eq_mode >= JS_EQ_SAME_VALUE)) {\n                if (eq_mode == JS_EQ_SAME_VALUE_ZERO &&\n                           a->expn == BF_EXP_ZERO && b->expn == BF_EXP_ZERO) {\n                    res = TRUE;\n                } else {\n                    res = (bf_cmp_full(a, b) == 0);\n                }\n            } else {\n                res = bf_cmp_eq(a, b);\n            }\n        }\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        {\n            JSBigDecimal *p1, *p2;\n            const bfdec_t *a, *b;\n            if (tag1 != tag2) {\n                res = FALSE;\n                break;\n            }\n            p1 = JS_VALUE_GET_PTR(op1);\n            p2 = JS_VALUE_GET_PTR(op2);\n            a = &p1->num;\n            b = &p2->num;\n            res = bfdec_cmp_eq(a, b);\n        }\n        break;\n#endif\n    default:\n        res = FALSE;\n        break;\n    }\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n done_no_free:\n    return res;\n}\n\nstatic BOOL js_strict_eq(JSContext *ctx, JSValue op1, JSValue op2)\n{\n    return js_strict_eq2(ctx, op1, op2, JS_EQ_STRICT);\n}\n\nstatic BOOL js_same_value(JSContext *ctx, JSValueConst op1, JSValueConst op2)\n{\n    return js_strict_eq2(ctx,\n                         JS_DupValue(ctx, op1), JS_DupValue(ctx, op2),\n                         JS_EQ_SAME_VALUE);\n}\n\nstatic BOOL js_same_value_zero(JSContext *ctx, JSValueConst op1, JSValueConst op2)\n{\n    return js_strict_eq2(ctx,\n                         JS_DupValue(ctx, op1), JS_DupValue(ctx, op2),\n                         JS_EQ_SAME_VALUE_ZERO);\n}\n\nstatic no_inline int js_strict_eq_slow(JSContext *ctx, JSValue *sp,\n                                       BOOL is_neq)\n{\n    BOOL res;\n    res = js_strict_eq(ctx, sp[-2], sp[-1]);\n    sp[-2] = JS_NewBool(ctx, res ^ is_neq);\n    return 0;\n}\n\nstatic __exception int js_operator_in(JSContext *ctx, JSValue *sp)\n{\n    JSValue op1, op2;\n    JSAtom atom;\n    int ret;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n\n    if (JS_VALUE_GET_TAG(op2) != JS_TAG_OBJECT) {\n        JS_ThrowTypeError(ctx, \"invalid 'in' operand\");\n        return -1;\n    }\n    atom = JS_ValueToAtom(ctx, op1);\n    if (unlikely(atom == JS_ATOM_NULL))\n        return -1;\n    ret = JS_HasProperty(ctx, op2, atom);\n    JS_FreeAtom(ctx, atom);\n    if (ret < 0)\n        return -1;\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    sp[-2] = JS_NewBool(ctx, ret);\n    return 0;\n}\n\nstatic __exception int js_has_unscopable(JSContext *ctx, JSValueConst obj,\n                                         JSAtom atom)\n{\n    JSValue arr, val;\n    int ret;\n\n    arr = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_unscopables);\n    if (JS_IsException(arr))\n        return -1;\n    ret = 0;\n    if (JS_IsObject(arr)) {\n        val = JS_GetProperty(ctx, arr, atom);\n        ret = JS_ToBoolFree(ctx, val);\n    }\n    JS_FreeValue(ctx, arr);\n    return ret;\n}\n\nstatic __exception int js_operator_instanceof(JSContext *ctx, JSValue *sp)\n{\n    JSValue op1, op2;\n    BOOL ret;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    ret = JS_IsInstanceOf(ctx, op1, op2);\n    if (ret < 0)\n        return ret;\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    sp[-2] = JS_NewBool(ctx, ret);\n    return 0;\n}\n\nstatic __exception int js_operator_typeof(JSContext *ctx, JSValueConst op1)\n{\n    JSAtom atom;\n    uint32_t tag;\n\n    tag = JS_VALUE_GET_NORM_TAG(op1);\n    switch(tag) {\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n        atom = JS_ATOM_bigint;\n        break;\n    case JS_TAG_BIG_FLOAT:\n        atom = JS_ATOM_bigfloat;\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        atom = JS_ATOM_bigdecimal;\n        break;\n#endif\n    case JS_TAG_INT:\n    case JS_TAG_FLOAT64:\n        atom = JS_ATOM_number;\n        break;\n    case JS_TAG_UNDEFINED:\n        atom = JS_ATOM_undefined;\n        break;\n    case JS_TAG_BOOL:\n        atom = JS_ATOM_boolean;\n        break;\n    case JS_TAG_STRING:\n        atom = JS_ATOM_string;\n        break;\n    case JS_TAG_OBJECT:\n        {\n            JSObject *p;\n            p = JS_VALUE_GET_OBJ(op1);\n            if (unlikely(p->is_HTMLDDA)) \n                atom = JS_ATOM_undefined;\n            else if (JS_IsFunction(ctx, op1))\n                atom = JS_ATOM_function;\n            else\n                goto obj_type;\n        }\n        break;\n    case JS_TAG_NULL:\n    obj_type:\n        atom = JS_ATOM_object;\n        break;\n    case JS_TAG_SYMBOL:\n        atom = JS_ATOM_symbol;\n        break;\n    default:\n        atom = JS_ATOM_unknown;\n        break;\n    }\n    return atom;\n}\n\nstatic __exception int js_operator_delete(JSContext *ctx, JSValue *sp)\n{\n    JSValue op1, op2;\n    JSAtom atom;\n    int ret;\n\n    op1 = sp[-2];\n    op2 = sp[-1];\n    atom = JS_ValueToAtom(ctx, op2);\n    if (unlikely(atom == JS_ATOM_NULL))\n        return -1;\n    ret = JS_DeleteProperty(ctx, op1, atom, JS_PROP_THROW_STRICT);\n    JS_FreeAtom(ctx, atom);\n    if (unlikely(ret < 0))\n        return -1;\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    sp[-2] = JS_NewBool(ctx, ret);\n    return 0;\n}\n\nstatic JSValue js_throw_type_error(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    return JS_ThrowTypeError(ctx, \"invalid property access\");\n}\n\n/* XXX: not 100% compatible, but mozilla seems to use a similar\n   implementation to ensure that caller in non strict mode does not\n   throw (ES5 compatibility) */\nstatic JSValue js_function_proto_caller(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv)\n{\n    JSFunctionBytecode *b = JS_GetFunctionBytecode(this_val);\n    if (!b || (b->js_mode & JS_MODE_STRICT) || !b->has_prototype) {\n        return js_throw_type_error(ctx, this_val, 0, NULL);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_function_proto_fileName(JSContext *ctx,\n                                          JSValueConst this_val)\n{\n    JSFunctionBytecode *b = JS_GetFunctionBytecode(this_val);\n    if (b && b->has_debug) {\n        return JS_AtomToString(ctx, b->debug.filename);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_function_proto_lineNumber(JSContext *ctx,\n                                            JSValueConst this_val)\n{\n    JSFunctionBytecode *b = JS_GetFunctionBytecode(this_val);\n    if (b && b->has_debug) {\n        return JS_NewInt32(ctx, b->debug.line_num);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic int js_arguments_define_own_property(JSContext *ctx,\n                                            JSValueConst this_obj,\n                                            JSAtom prop, JSValueConst val,\n                                            JSValueConst getter, JSValueConst setter, int flags)\n{\n    JSObject *p;\n    uint32_t idx;\n    p = JS_VALUE_GET_OBJ(this_obj);\n    /* convert to normal array when redefining an existing numeric field */\n    if (p->fast_array && JS_AtomIsArrayIndex(ctx, &idx, prop) &&\n        idx < p->u.array.count) {\n        if (convert_fast_array_to_array(ctx, p))\n            return -1;\n    }\n    /* run the default define own property */\n    return JS_DefineProperty(ctx, this_obj, prop, val, getter, setter,\n                             flags | JS_PROP_NO_EXOTIC);\n}\n\nstatic const JSClassExoticMethods js_arguments_exotic_methods = {\n    .define_own_property = js_arguments_define_own_property,\n};\n\nstatic JSValue js_build_arguments(JSContext *ctx, int argc, JSValueConst *argv)\n{\n    JSValue val, *tab;\n    JSProperty *pr;\n    JSObject *p;\n    int i;\n\n    val = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],\n                                 JS_CLASS_ARGUMENTS);\n    if (JS_IsException(val))\n        return val;\n    p = JS_VALUE_GET_OBJ(val);\n\n    /* add the length field (cannot fail) */\n    pr = add_property(ctx, p, JS_ATOM_length,\n                      JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    pr->u.value = JS_NewInt32(ctx, argc);\n\n    /* initialize the fast array part */\n    tab = NULL;\n    if (argc > 0) {\n        tab = js_malloc(ctx, sizeof(tab[0]) * argc);\n        if (!tab) {\n            JS_FreeValue(ctx, val);\n            return JS_EXCEPTION;\n        }\n        for(i = 0; i < argc; i++) {\n            tab[i] = JS_DupValue(ctx, argv[i]);\n        }\n    }\n    p->u.array.u.values = tab;\n    p->u.array.count = argc;\n\n    JS_DefinePropertyValue(ctx, val, JS_ATOM_Symbol_iterator,\n                           JS_DupValue(ctx, ctx->array_proto_values),\n                           JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE);\n    /* add callee property to throw a TypeError in strict mode */\n    JS_DefineProperty(ctx, val, JS_ATOM_callee, JS_UNDEFINED,\n                      ctx->throw_type_error, ctx->throw_type_error,\n                      JS_PROP_HAS_GET | JS_PROP_HAS_SET);\n    return val;\n}\n\n#define GLOBAL_VAR_OFFSET 0x40000000\n#define ARGUMENT_VAR_OFFSET 0x20000000\n\n/* legacy arguments object: add references to the function arguments */\nstatic JSValue js_build_mapped_arguments(JSContext *ctx, int argc,\n                                         JSValueConst *argv,\n                                         JSStackFrame *sf, int arg_count)\n{\n    JSValue val;\n    JSProperty *pr;\n    JSObject *p;\n    int i;\n\n    val = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],\n                                 JS_CLASS_MAPPED_ARGUMENTS);\n    if (JS_IsException(val))\n        return val;\n    p = JS_VALUE_GET_OBJ(val);\n\n    /* add the length field (cannot fail) */\n    pr = add_property(ctx, p, JS_ATOM_length,\n                      JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    pr->u.value = JS_NewInt32(ctx, argc);\n\n    for(i = 0; i < arg_count; i++) {\n        JSVarRef *var_ref;\n        var_ref = get_var_ref(ctx, sf, i, TRUE);\n        if (!var_ref)\n            goto fail;\n        pr = add_property(ctx, p, __JS_AtomFromUInt32(i), JS_PROP_C_W_E | JS_PROP_VARREF);\n        if (!pr) {\n            free_var_ref(ctx->rt, var_ref);\n            goto fail;\n        }\n        pr->u.var_ref = var_ref;\n    }\n\n    /* the arguments not mapped to the arguments of the function can\n       be normal properties */\n    for(i = arg_count; i < argc; i++) {\n        if (JS_DefinePropertyValueUint32(ctx, val, i,\n                                         JS_DupValue(ctx, argv[i]),\n                                         JS_PROP_C_W_E) < 0)\n            goto fail;\n    }\n\n    JS_DefinePropertyValue(ctx, val, JS_ATOM_Symbol_iterator,\n                           JS_DupValue(ctx, ctx->array_proto_values),\n                           JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE);\n    /* callee returns this function in non strict mode */\n    JS_DefinePropertyValue(ctx, val, JS_ATOM_callee,\n                           JS_DupValue(ctx, ctx->rt->current_stack_frame->cur_func),\n                           JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE);\n    return val;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_build_rest(JSContext *ctx, int first, int argc, JSValueConst *argv)\n{\n    JSValue val;\n    int i, ret;\n\n    val = JS_NewArray(ctx);\n    if (JS_IsException(val))\n        return val;\n    for (i = first; i < argc; i++) {\n        ret = JS_DefinePropertyValueUint32(ctx, val, i - first,\n                                           JS_DupValue(ctx, argv[i]),\n                                           JS_PROP_C_W_E);\n        if (ret < 0) {\n            JS_FreeValue(ctx, val);\n            return JS_EXCEPTION;\n        }\n    }\n    return val;\n}\n\nstatic JSValue build_for_in_iterator(JSContext *ctx, JSValue obj)\n{\n    JSObject *p;\n    JSPropertyEnum *tab_atom;\n    int i;\n    JSValue enum_obj, obj1;\n    JSForInIterator *it;\n    uint32_t tag, tab_atom_count;\n\n    tag = JS_VALUE_GET_TAG(obj);\n    if (tag != JS_TAG_OBJECT && tag != JS_TAG_NULL && tag != JS_TAG_UNDEFINED) {\n        obj = JS_ToObjectFree(ctx, obj);\n    }\n\n    it = js_malloc(ctx, sizeof(*it));\n    if (!it) {\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    enum_obj = JS_NewObjectProtoClass(ctx, JS_NULL, JS_CLASS_FOR_IN_ITERATOR);\n    if (JS_IsException(enum_obj)) {\n        js_free(ctx, it);\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    it->is_array = FALSE;\n    it->obj = obj;\n    it->idx = 0;\n    p = JS_VALUE_GET_OBJ(enum_obj);\n    p->u.for_in_iterator = it;\n\n    if (tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED)\n        return enum_obj;\n\n    /* fast path: assume no enumerable properties in the prototype chain */\n    obj1 = JS_DupValue(ctx, obj);\n    for(;;) {\n        obj1 = JS_GetPrototypeFree(ctx, obj1);\n        if (JS_IsNull(obj1))\n            break;\n        if (JS_IsException(obj1))\n            goto fail;\n        if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count,\n                                           JS_VALUE_GET_OBJ(obj1),\n                                           JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY)) {\n            JS_FreeValue(ctx, obj1);\n            goto fail;\n        }\n        js_free_prop_enum(ctx, tab_atom, tab_atom_count);\n        if (tab_atom_count != 0) {\n            JS_FreeValue(ctx, obj1);\n            goto slow_path;\n        }\n        /* must check for timeout to avoid infinite loop */\n        if (js_poll_interrupts(ctx)) {\n            JS_FreeValue(ctx, obj1);\n            goto fail;\n        }\n    }\n\n    p = JS_VALUE_GET_OBJ(obj);\n\n    if (p->fast_array) {\n        JSShape *sh;\n        JSShapeProperty *prs;\n        /* check that there are no enumerable normal fields */\n        sh = p->shape;\n        for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) {\n            if (prs->flags & JS_PROP_ENUMERABLE)\n                goto normal_case;\n        }\n        /* for fast arrays, we only store the number of elements */\n        it->is_array = TRUE;\n        it->array_length = p->u.array.count;\n    } else {\n    normal_case:\n        if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count, p,\n                                   JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY))\n            goto fail;\n        for(i = 0; i < tab_atom_count; i++) {\n            JS_SetPropertyInternal(ctx, enum_obj, tab_atom[i].atom, JS_NULL, 0);\n        }\n        js_free_prop_enum(ctx, tab_atom, tab_atom_count);\n    }\n    return enum_obj;\n\n slow_path:\n    /* non enumerable properties hide the enumerables ones in the\n       prototype chain */\n    obj1 = JS_DupValue(ctx, obj);\n    for(;;) {\n        if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count,\n                                           JS_VALUE_GET_OBJ(obj1),\n                                           JS_GPN_STRING_MASK | JS_GPN_SET_ENUM)) {\n            JS_FreeValue(ctx, obj1);\n            goto fail;\n        }\n        for(i = 0; i < tab_atom_count; i++) {\n            JS_DefinePropertyValue(ctx, enum_obj, tab_atom[i].atom, JS_NULL,\n                                   (tab_atom[i].is_enumerable ?\n                                    JS_PROP_ENUMERABLE : 0));\n        }\n        js_free_prop_enum(ctx, tab_atom, tab_atom_count);\n        obj1 = JS_GetPrototypeFree(ctx, obj1);\n        if (JS_IsNull(obj1))\n            break;\n        if (JS_IsException(obj1))\n            goto fail;\n        /* must check for timeout to avoid infinite loop */\n        if (js_poll_interrupts(ctx)) {\n            JS_FreeValue(ctx, obj1);\n            goto fail;\n        }\n    }\n    return enum_obj;\n\n fail:\n    JS_FreeValue(ctx, enum_obj);\n    return JS_EXCEPTION;\n}\n\n/* obj -> enum_obj */\nstatic __exception int js_for_in_start(JSContext *ctx, JSValue *sp)\n{\n    sp[-1] = build_for_in_iterator(ctx, sp[-1]);\n    if (JS_IsException(sp[-1]))\n        return -1;\n    return 0;\n}\n\n/* enum_obj -> enum_obj value done */\nstatic __exception int js_for_in_next(JSContext *ctx, JSValue *sp)\n{\n    JSValueConst enum_obj;\n    JSObject *p;\n    JSAtom prop;\n    JSForInIterator *it;\n    int ret;\n\n    enum_obj = sp[-1];\n    /* fail safe */\n    if (JS_VALUE_GET_TAG(enum_obj) != JS_TAG_OBJECT)\n        goto done;\n    p = JS_VALUE_GET_OBJ(enum_obj);\n    if (p->class_id != JS_CLASS_FOR_IN_ITERATOR)\n        goto done;\n    it = p->u.for_in_iterator;\n\n    for(;;) {\n        if (it->is_array) {\n            if (it->idx >= it->array_length)\n                goto done;\n            prop = __JS_AtomFromUInt32(it->idx);\n            it->idx++;\n        } else {\n            JSShape *sh = p->shape;\n            JSShapeProperty *prs;\n            if (it->idx >= sh->prop_count)\n                goto done;\n            prs = get_shape_prop(sh) + it->idx;\n            prop = prs->atom;\n            it->idx++;\n            if (prop == JS_ATOM_NULL || !(prs->flags & JS_PROP_ENUMERABLE))\n                continue;\n        }\n        /* check if the property was deleted */\n        ret = JS_HasProperty(ctx, it->obj, prop);\n        if (ret < 0)\n            return ret;\n        if (ret)\n            break;\n    }\n    /* return the property */\n    sp[0] = JS_AtomToValue(ctx, prop);\n    sp[1] = JS_FALSE;\n    return 0;\n done:\n    /* return the end */\n    sp[0] = JS_UNDEFINED;\n    sp[1] = JS_TRUE;\n    return 0;\n}\n\nstatic JSValue JS_GetIterator2(JSContext *ctx, JSValueConst obj,\n                               JSValueConst method)\n{\n    JSValue enum_obj;\n\n    enum_obj = JS_Call(ctx, method, obj, 0, NULL);\n    if (JS_IsException(enum_obj))\n        return enum_obj;\n    if (!JS_IsObject(enum_obj)) {\n        JS_FreeValue(ctx, enum_obj);\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    }\n    return enum_obj;\n}\n\nstatic JSValue JS_GetIterator(JSContext *ctx, JSValueConst obj, BOOL is_async)\n{\n    JSValue method, ret, sync_iter;\n\n    if (is_async) {\n        method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_asyncIterator);\n        if (JS_IsException(method))\n            return method;\n        if (JS_IsUndefined(method) || JS_IsNull(method)) {\n            method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_iterator);\n            if (JS_IsException(method))\n                return method;\n            sync_iter = JS_GetIterator2(ctx, obj, method);\n            JS_FreeValue(ctx, method);\n            if (JS_IsException(sync_iter))\n                return sync_iter;\n            ret = JS_CreateAsyncFromSyncIterator(ctx, sync_iter);\n            JS_FreeValue(ctx, sync_iter);\n            return ret;\n        }\n    } else {\n        method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_iterator);\n        if (JS_IsException(method))\n            return method;\n    }\n    if (!JS_IsFunction(ctx, method)) {\n        JS_FreeValue(ctx, method);\n        return JS_ThrowTypeError(ctx, \"value is not iterable\");\n    }\n    ret = JS_GetIterator2(ctx, obj, method);\n    JS_FreeValue(ctx, method);\n    return ret;\n}\n\n/* return *pdone = 2 if the iterator object is not parsed */\nstatic JSValue JS_IteratorNext2(JSContext *ctx, JSValueConst enum_obj,\n                                JSValueConst method,\n                                int argc, JSValueConst *argv, int *pdone)\n{\n    JSValue obj;\n\n    /* fast path for the built-in iterators (avoid creating the\n       intermediate result object) */\n    if (JS_IsObject(method)) {\n        JSObject *p = JS_VALUE_GET_OBJ(method);\n        if (p->class_id == JS_CLASS_C_FUNCTION &&\n            p->u.cfunc.cproto == JS_CFUNC_iterator_next) {\n            JSCFunctionType func;\n            JSValueConst args[1];\n\n            /* in case the function expects one argument */\n            if (argc == 0) {\n                args[0] = JS_UNDEFINED;\n                argv = args;\n            }\n            func = p->u.cfunc.c_function;\n            return func.iterator_next(ctx, enum_obj, argc, argv,\n                                      pdone, p->u.cfunc.magic);\n        }\n    }\n    obj = JS_Call(ctx, method, enum_obj, argc, argv);\n    if (JS_IsException(obj))\n        goto fail;\n    if (!JS_IsObject(obj)) {\n        JS_FreeValue(ctx, obj);\n        JS_ThrowTypeError(ctx, \"iterator must return an object\");\n        goto fail;\n    }\n    *pdone = 2;\n    return obj;\n fail:\n    *pdone = FALSE;\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_IteratorNext(JSContext *ctx, JSValueConst enum_obj,\n                               JSValueConst method,\n                               int argc, JSValueConst *argv, BOOL *pdone)\n{\n    JSValue obj, value, done_val;\n    int done;\n\n    obj = JS_IteratorNext2(ctx, enum_obj, method, argc, argv, &done);\n    if (JS_IsException(obj))\n        goto fail;\n    if (done != 2) {\n        *pdone = done;\n        return obj;\n    } else {\n        done_val = JS_GetProperty(ctx, obj, JS_ATOM_done);\n        if (JS_IsException(done_val))\n            goto fail;\n        *pdone = JS_ToBoolFree(ctx, done_val);\n        value = JS_UNDEFINED;\n        if (!*pdone) {\n            value = JS_GetProperty(ctx, obj, JS_ATOM_value);\n        }\n        JS_FreeValue(ctx, obj);\n        return value;\n    }\n fail:\n    JS_FreeValue(ctx, obj);\n    *pdone = FALSE;\n    return JS_EXCEPTION;\n}\n\n/* return < 0 in case of exception */\nstatic int JS_IteratorClose(JSContext *ctx, JSValueConst enum_obj,\n                            BOOL is_exception_pending)\n{\n    JSValue method, ret, ex_obj;\n    int res;\n\n    if (is_exception_pending) {\n        ex_obj = ctx->rt->current_exception;\n        ctx->rt->current_exception = JS_NULL;\n        res = -1;\n    } else {\n        ex_obj = JS_UNDEFINED;\n        res = 0;\n    }\n    method = JS_GetProperty(ctx, enum_obj, JS_ATOM_return);\n    if (JS_IsException(method)) {\n        res = -1;\n        goto done;\n    }\n    if (JS_IsUndefined(method) || JS_IsNull(method)) {\n        goto done;\n    }\n    ret = JS_CallFree(ctx, method, enum_obj, 0, NULL);\n    if (!is_exception_pending) {\n        if (JS_IsException(ret)) {\n            res = -1;\n        } else if (!JS_IsObject(ret)) {\n            JS_ThrowTypeErrorNotAnObject(ctx);\n            res = -1;\n        }\n    }\n    JS_FreeValue(ctx, ret);\n done:\n    if (is_exception_pending) {\n        JS_Throw(ctx, ex_obj);\n    }\n    return res;\n}\n\n/* obj -> enum_rec (3 slots) */\nstatic __exception int js_for_of_start(JSContext *ctx, JSValue *sp,\n                                       BOOL is_async)\n{\n    JSValue op1, obj, method;\n    op1 = sp[-1];\n    obj = JS_GetIterator(ctx, op1, is_async);\n    if (JS_IsException(obj))\n        return -1;\n    JS_FreeValue(ctx, op1);\n    sp[-1] = obj;\n    method = JS_GetProperty(ctx, obj, JS_ATOM_next);\n    if (JS_IsException(method))\n        return -1;\n    sp[0] = method;\n    return 0;\n}\n\n/* enum_rec [objs] -> enum_rec [objs] value done. There are 'offset'\n   objs. If 'done' is true or in case of exception, 'enum_rec' is set\n   to undefined. If 'done' is true, 'value' is always set to\n   undefined. */\nstatic __exception int js_for_of_next(JSContext *ctx, JSValue *sp, int offset)\n{\n    JSValue value = JS_UNDEFINED;\n    int done = 1;\n\n    if (likely(!JS_IsUndefined(sp[offset]))) {\n        value = JS_IteratorNext(ctx, sp[offset], sp[offset + 1], 0, NULL, &done);\n        if (JS_IsException(value))\n            done = -1;\n        if (done) {\n            /* value is JS_UNDEFINED or JS_EXCEPTION */\n            /* replace the iteration object with undefined */\n            JS_FreeValue(ctx, sp[offset]);\n            sp[offset] = JS_UNDEFINED;\n            if (done < 0) {\n                return -1;\n            } else {\n                JS_FreeValue(ctx, value);\n                value = JS_UNDEFINED;\n            }\n        }\n    }\n    sp[0] = value;\n    sp[1] = JS_NewBool(ctx, done);\n    return 0;\n}\n\nstatic JSValue JS_IteratorGetCompleteValue(JSContext *ctx, JSValueConst obj,\n                                           BOOL *pdone)\n{\n    JSValue done_val, value;\n    BOOL done;\n    done_val = JS_GetProperty(ctx, obj, JS_ATOM_done);\n    if (JS_IsException(done_val))\n        goto fail;\n    done = JS_ToBoolFree(ctx, done_val);\n    value = JS_GetProperty(ctx, obj, JS_ATOM_value);\n    if (JS_IsException(value))\n        goto fail;\n    *pdone = done;\n    return value;\n fail:\n    *pdone = FALSE;\n    return JS_EXCEPTION;\n}\n\nstatic __exception int js_iterator_get_value_done(JSContext *ctx, JSValue *sp)\n{\n    JSValue obj, value;\n    BOOL done;\n    obj = sp[-1];\n    if (!JS_IsObject(obj)) {\n        JS_ThrowTypeError(ctx, \"iterator must return an object\");\n        return -1;\n    }\n    value = JS_IteratorGetCompleteValue(ctx, obj, &done);\n    if (JS_IsException(value))\n        return -1;\n    JS_FreeValue(ctx, obj);\n    sp[-1] = value;\n    sp[0] = JS_NewBool(ctx, done);\n    return 0;\n}\n\nstatic JSValue js_create_iterator_result(JSContext *ctx,\n                                         JSValue val,\n                                         BOOL done)\n{\n    JSValue obj;\n    obj = JS_NewObject(ctx);\n    if (JS_IsException(obj)) {\n        JS_FreeValue(ctx, val);\n        return obj;\n    }\n    if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_value,\n                               val, JS_PROP_C_W_E) < 0) {\n        goto fail;\n    }\n    if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_done,\n                               JS_NewBool(ctx, done), JS_PROP_C_W_E) < 0) {\n    fail:\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    return obj;\n}\n\nstatic JSValue js_array_iterator_next(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv,\n                                      BOOL *pdone, int magic);\n\nstatic JSValue js_create_array_iterator(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv, int magic);\n\nstatic BOOL js_is_fast_array(JSContext *ctx, JSValueConst obj)\n{\n    /* Try and handle fast arrays explicitly */\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(obj);\n        if (p->class_id == JS_CLASS_ARRAY && p->fast_array) {\n            return TRUE;\n        }\n    }\n    return FALSE;\n}\n\n/* Access an Array's internal JSValue array if available */\nstatic BOOL js_get_fast_array(JSContext *ctx, JSValueConst obj,\n                              JSValue **arrpp, uint32_t *countp)\n{\n    /* Try and handle fast arrays explicitly */\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(obj);\n        if (p->class_id == JS_CLASS_ARRAY && p->fast_array) {\n            *countp = p->u.array.count;\n            *arrpp = p->u.array.u.values;\n            return TRUE;\n        }\n    }\n    return FALSE;\n}\n\nstatic __exception int js_append_enumerate(JSContext *ctx, JSValue *sp)\n{\n    JSValue iterator, enumobj, method, value;\n    int is_array_iterator;\n    JSValue *arrp;\n    uint32_t i, count32, pos;\n    \n    if (JS_VALUE_GET_TAG(sp[-2]) != JS_TAG_INT) {\n        JS_ThrowInternalError(ctx, \"invalid index for append\");\n        return -1;\n    }\n\n    pos = JS_VALUE_GET_INT(sp[-2]);\n\n    /* XXX: further optimisations:\n       - use ctx->array_proto_values?\n       - check if array_iterator_prototype next method is built-in and\n         avoid constructing actual iterator object?\n       - build this into js_for_of_start and use in all `for (x of o)` loops\n     */\n    iterator = JS_GetProperty(ctx, sp[-1], JS_ATOM_Symbol_iterator);\n    if (JS_IsException(iterator))\n        return -1;\n    is_array_iterator = JS_IsCFunction(ctx, iterator,\n                                       (JSCFunction *)js_create_array_iterator,\n                                       JS_ITERATOR_KIND_VALUE);\n    JS_FreeValue(ctx, iterator);\n\n    enumobj = JS_GetIterator(ctx, sp[-1], FALSE);\n    if (JS_IsException(enumobj))\n        return -1;\n    method = JS_GetProperty(ctx, enumobj, JS_ATOM_next);\n    if (JS_IsException(method)) {\n        JS_FreeValue(ctx, enumobj);\n        return -1;\n    }\n    if (is_array_iterator\n    &&  JS_IsCFunction(ctx, method, (JSCFunction *)js_array_iterator_next, 0)\n    &&  js_get_fast_array(ctx, sp[-1], &arrp, &count32)) {\n        uint32_t len;\n        if (js_get_length32(ctx, &len, sp[-1]))\n            goto exception;\n        /* if len > count32, the elements >= count32 might be read in\n           the prototypes and might have side effects */\n        if (len != count32)\n            goto general_case;\n        /* Handle fast arrays explicitly */\n        for (i = 0; i < count32; i++) {\n            if (JS_DefinePropertyValueUint32(ctx, sp[-3], pos++,\n                                             JS_DupValue(ctx, arrp[i]), JS_PROP_C_W_E) < 0)\n                goto exception;\n        }\n    } else {\n    general_case:\n        for (;;) {\n            BOOL done;\n            value = JS_IteratorNext(ctx, enumobj, method, 0, NULL, &done);\n            if (JS_IsException(value))\n                goto exception;\n            if (done) {\n                /* value is JS_UNDEFINED */\n                break;\n            }\n            if (JS_DefinePropertyValueUint32(ctx, sp[-3], pos++, value, JS_PROP_C_W_E) < 0)\n                goto exception;\n        }\n    }\n    /* Note: could raise an error if too many elements */\n    sp[-2] = JS_NewInt32(ctx, pos);\n    JS_FreeValue(ctx, enumobj);\n    JS_FreeValue(ctx, method);\n    return 0;\n\nexception:\n    JS_IteratorClose(ctx, enumobj, TRUE);\n    JS_FreeValue(ctx, enumobj);\n    JS_FreeValue(ctx, method);\n    return -1;\n}\n\nstatic __exception int JS_CopyDataProperties(JSContext *ctx,\n                                             JSValueConst target,\n                                             JSValueConst source,\n                                             JSValueConst excluded,\n                                             BOOL setprop)\n{\n    JSPropertyEnum *tab_atom;\n    JSValue val;\n    uint32_t i, tab_atom_count;\n    JSObject *p;\n    JSObject *pexcl = NULL;\n    int ret, gpn_flags;\n    JSPropertyDescriptor desc;\n    BOOL is_enumerable;\n    \n    if (JS_VALUE_GET_TAG(source) != JS_TAG_OBJECT)\n        return 0;\n\n    if (JS_VALUE_GET_TAG(excluded) == JS_TAG_OBJECT)\n        pexcl = JS_VALUE_GET_OBJ(excluded);\n\n    p = JS_VALUE_GET_OBJ(source);\n\n    gpn_flags = JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK | JS_GPN_ENUM_ONLY;\n    if (p->is_exotic) {\n        const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic;\n        /* cannot use JS_GPN_ENUM_ONLY with e.g. proxies because it\n           introduces a visible change */\n        if (em && em->get_own_property_names) {\n            gpn_flags &= ~JS_GPN_ENUM_ONLY;\n        }\n    }\n    if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count, p,\n                                       gpn_flags))\n        return -1;\n    \n    for (i = 0; i < tab_atom_count; i++) {\n        if (pexcl) {\n            ret = JS_GetOwnPropertyInternal(ctx, NULL, pexcl, tab_atom[i].atom);\n            if (ret) {\n                if (ret < 0)\n                    goto exception;\n                continue;\n            }\n        }\n        if (!(gpn_flags & JS_GPN_ENUM_ONLY)) {\n            /* test if the property is enumerable */\n            ret = JS_GetOwnPropertyInternal(ctx, &desc, p, tab_atom[i].atom);\n            if (ret < 0)\n                goto exception;\n            if (!ret)\n                continue;\n            is_enumerable = (desc.flags & JS_PROP_ENUMERABLE) != 0;\n            js_free_desc(ctx, &desc);\n            if (!is_enumerable)\n                continue;\n        }\n        val = JS_GetProperty(ctx, source, tab_atom[i].atom);\n        if (JS_IsException(val))\n            goto exception;\n        if (setprop)\n            ret = JS_SetProperty(ctx, target, tab_atom[i].atom, val);\n        else\n            ret = JS_DefinePropertyValue(ctx, target, tab_atom[i].atom, val,\n                                         JS_PROP_C_W_E);\n        if (ret < 0)\n            goto exception;\n    }\n    js_free_prop_enum(ctx, tab_atom, tab_atom_count);\n    return 0;\n exception:\n    js_free_prop_enum(ctx, tab_atom, tab_atom_count);\n    return -1;\n}\n\n/* only valid inside C functions */\nJSValueConst JS_GetActiveFunction(JSContext *ctx)\n{\n    return ctx->rt->current_stack_frame->cur_func;\n}\n\nstatic JSVarRef *get_var_ref(JSContext *ctx, JSStackFrame *sf,\n                             int var_idx, BOOL is_arg)\n{\n    JSVarRef *var_ref;\n    struct list_head *el;\n\n    list_for_each(el, &sf->var_ref_list) {\n        var_ref = list_entry(el, JSVarRef, header.link);\n        if (var_ref->var_idx == var_idx && var_ref->is_arg == is_arg) {\n            var_ref->header.ref_count++;\n            return var_ref;\n        }\n    }\n    /* create a new one */\n    var_ref = js_malloc(ctx, sizeof(JSVarRef));\n    if (!var_ref)\n        return NULL;\n    var_ref->header.ref_count = 1;\n    var_ref->is_detached = FALSE;\n    var_ref->is_arg = is_arg;\n    var_ref->var_idx = var_idx;\n    list_add_tail(&var_ref->header.link, &sf->var_ref_list);\n    if (is_arg)\n        var_ref->pvalue = &sf->arg_buf[var_idx];\n    else\n        var_ref->pvalue = &sf->var_buf[var_idx];\n    var_ref->value = JS_UNDEFINED;\n    return var_ref;\n}\n\nstatic JSValue js_closure2(JSContext *ctx, JSValue func_obj,\n                           JSFunctionBytecode *b,\n                           JSVarRef **cur_var_refs,\n                           JSStackFrame *sf)\n{\n    JSObject *p;\n    JSVarRef **var_refs;\n    int i;\n\n    p = JS_VALUE_GET_OBJ(func_obj);\n    p->u.func.function_bytecode = b;\n    p->u.func.home_object = NULL;\n    p->u.func.var_refs = NULL;\n    if (b->closure_var_count) {\n        var_refs = js_mallocz(ctx, sizeof(var_refs[0]) * b->closure_var_count);\n        if (!var_refs)\n            goto fail;\n        p->u.func.var_refs = var_refs;\n        for(i = 0; i < b->closure_var_count; i++) {\n            JSClosureVar *cv = &b->closure_var[i];\n            JSVarRef *var_ref;\n            if (cv->is_local) {\n                /* reuse the existing variable reference if it already exists */\n                var_ref = get_var_ref(ctx, sf, cv->var_idx, cv->is_arg);\n                if (!var_ref)\n                    goto fail;\n            } else {\n                var_ref = cur_var_refs[cv->var_idx];\n                var_ref->header.ref_count++;\n            }\n            var_refs[i] = var_ref;\n        }\n    }\n    return func_obj;\n fail:\n    /* bfunc is freed when func_obj is freed */\n    JS_FreeValue(ctx, func_obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_instantiate_prototype(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque)\n{\n    JSValue obj, this_val;\n    int ret;\n\n    this_val = JS_MKPTR(JS_TAG_OBJECT, p);\n    obj = JS_NewObject(ctx);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    set_cycle_flag(ctx, obj);\n    set_cycle_flag(ctx, this_val);\n    ret = JS_DefinePropertyValue(ctx, obj, JS_ATOM_constructor,\n                                 JS_DupValue(ctx, this_val),\n                                 JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    if (ret < 0) {\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    return obj;\n}\n\nstatic const uint16_t func_kind_to_class_id[] = {\n    [JS_FUNC_NORMAL] = JS_CLASS_BYTECODE_FUNCTION,\n    [JS_FUNC_GENERATOR] = JS_CLASS_GENERATOR_FUNCTION,\n    [JS_FUNC_ASYNC] = JS_CLASS_ASYNC_FUNCTION,\n    [JS_FUNC_ASYNC_GENERATOR] = JS_CLASS_ASYNC_GENERATOR_FUNCTION,\n};\n\nstatic JSValue js_closure(JSContext *ctx, JSValue bfunc,\n                          JSVarRef **cur_var_refs,\n                          JSStackFrame *sf)\n{\n    JSFunctionBytecode *b;\n    JSValue func_obj;\n    JSAtom name_atom;\n\n    b = JS_VALUE_GET_PTR(bfunc);\n    func_obj = JS_NewObjectClass(ctx, func_kind_to_class_id[b->func_kind]);\n    if (JS_IsException(func_obj)) {\n        JS_FreeValue(ctx, bfunc);\n        return JS_EXCEPTION;\n    }\n    func_obj = js_closure2(ctx, func_obj, b, cur_var_refs, sf);\n    if (JS_IsException(func_obj)) {\n        /* bfunc has been freed */\n        goto fail;\n    }\n    name_atom = b->func_name;\n    if (name_atom == JS_ATOM_NULL)\n        name_atom = JS_ATOM_empty_string;\n    js_function_set_properties(ctx, func_obj, name_atom,\n                               b->defined_arg_count);\n\n    if (b->func_kind & JS_FUNC_GENERATOR) {\n        JSValue proto;\n        int proto_class_id;\n        /* generators have a prototype field which is used as\n           prototype for the generator object */\n        if (b->func_kind == JS_FUNC_ASYNC_GENERATOR)\n            proto_class_id = JS_CLASS_ASYNC_GENERATOR;\n        else\n            proto_class_id = JS_CLASS_GENERATOR;\n        proto = JS_NewObjectProto(ctx, ctx->class_proto[proto_class_id]);\n        if (JS_IsException(proto))\n            goto fail;\n        JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_prototype, proto,\n                               JS_PROP_WRITABLE);\n    } else if (b->has_prototype) {\n        /* add the 'prototype' property: delay instantiation to avoid\n           creating cycles for every javascript function. The prototype\n           object is created on the fly when first accessed */\n        JS_SetConstructorBit(ctx, func_obj, TRUE);\n        JS_DefineAutoInitProperty(ctx, func_obj, JS_ATOM_prototype,\n                                  JS_AUTOINIT_ID_PROTOTYPE, NULL,\n                                  JS_PROP_WRITABLE);\n    }\n    return func_obj;\n fail:\n    /* bfunc is freed when func_obj is freed */\n    JS_FreeValue(ctx, func_obj);\n    return JS_EXCEPTION;\n}\n\n#define JS_DEFINE_CLASS_HAS_HERITAGE     (1 << 0)\n\nstatic int js_op_define_class(JSContext *ctx, JSValue *sp,\n                              JSAtom class_name, int class_flags,\n                              JSVarRef **cur_var_refs,\n                              JSStackFrame *sf, BOOL is_computed_name)\n{\n    JSValue bfunc, parent_class, proto = JS_UNDEFINED;\n    JSValue ctor = JS_UNDEFINED, parent_proto = JS_UNDEFINED;\n    JSFunctionBytecode *b;\n\n    parent_class = sp[-2];\n    bfunc = sp[-1];\n\n    if (class_flags & JS_DEFINE_CLASS_HAS_HERITAGE) {\n        if (JS_IsNull(parent_class)) {\n            parent_proto = JS_NULL;\n            parent_class = JS_DupValue(ctx, ctx->function_proto);\n        } else {\n            if (!JS_IsConstructor(ctx, parent_class)) {\n                JS_ThrowTypeError(ctx, \"parent class must be constructor\");\n                goto fail;\n            }\n            parent_proto = JS_GetProperty(ctx, parent_class, JS_ATOM_prototype);\n            if (JS_IsException(parent_proto))\n                goto fail;\n            if (!JS_IsNull(parent_proto) && !JS_IsObject(parent_proto)) {\n                JS_ThrowTypeError(ctx, \"parent prototype must be an object or null\");\n                goto fail;\n            }\n        }\n    } else {\n        /* parent_class is JS_UNDEFINED in this case */\n        parent_proto = JS_DupValue(ctx, ctx->class_proto[JS_CLASS_OBJECT]);\n        parent_class = JS_DupValue(ctx, ctx->function_proto);\n    }\n    proto = JS_NewObjectProto(ctx, parent_proto);\n    if (JS_IsException(proto))\n        goto fail;\n\n    b = JS_VALUE_GET_PTR(bfunc);\n    assert(b->func_kind == JS_FUNC_NORMAL);\n    ctor = JS_NewObjectProtoClass(ctx, parent_class,\n                                  JS_CLASS_BYTECODE_FUNCTION);\n    if (JS_IsException(ctor))\n        goto fail;\n    ctor = js_closure2(ctx, ctor, b, cur_var_refs, sf);\n    bfunc = JS_UNDEFINED;\n    if (JS_IsException(ctor))\n        goto fail;\n    js_method_set_home_object(ctx, ctor, proto);\n    JS_SetConstructorBit(ctx, ctor, TRUE);\n\n    JS_DefinePropertyValue(ctx, ctor, JS_ATOM_length,\n                           JS_NewInt32(ctx, b->defined_arg_count),\n                           JS_PROP_CONFIGURABLE);\n\n    if (is_computed_name) {\n        if (JS_DefineObjectNameComputed(ctx, ctor, sp[-3],\n                                        JS_PROP_CONFIGURABLE) < 0)\n            goto fail;\n    } else {\n        if (JS_DefineObjectName(ctx, ctor, class_name, JS_PROP_CONFIGURABLE) < 0)\n            goto fail;\n    }\n\n    /* the constructor property must be first. It can be overriden by\n       computed property names */\n    if (JS_DefinePropertyValue(ctx, proto, JS_ATOM_constructor,\n                               JS_DupValue(ctx, ctor),\n                               JS_PROP_CONFIGURABLE |\n                               JS_PROP_WRITABLE | JS_PROP_THROW) < 0)\n        goto fail;\n    /* set the prototype property */\n    if (JS_DefinePropertyValue(ctx, ctor, JS_ATOM_prototype,\n                               JS_DupValue(ctx, proto), JS_PROP_THROW) < 0)\n        goto fail;\n    set_cycle_flag(ctx, ctor);\n    set_cycle_flag(ctx, proto);\n\n    JS_FreeValue(ctx, parent_proto);\n    JS_FreeValue(ctx, parent_class);\n\n    sp[-2] = ctor;\n    sp[-1] = proto;\n    return 0;\n fail:\n    JS_FreeValue(ctx, parent_class);\n    JS_FreeValue(ctx, parent_proto);\n    JS_FreeValue(ctx, bfunc);\n    JS_FreeValue(ctx, proto);\n    JS_FreeValue(ctx, ctor);\n    sp[-2] = JS_UNDEFINED;\n    sp[-1] = JS_UNDEFINED;\n    return -1;\n}\n\nstatic void close_var_refs(JSRuntime *rt, JSStackFrame *sf)\n{\n    struct list_head *el, *el1;\n    JSVarRef *var_ref;\n    int var_idx;\n\n    list_for_each_safe(el, el1, &sf->var_ref_list) {\n        var_ref = list_entry(el, JSVarRef, header.link);\n        var_idx = var_ref->var_idx;\n        if (var_ref->is_arg)\n            var_ref->value = JS_DupValueRT(rt, sf->arg_buf[var_idx]);\n        else\n            var_ref->value = JS_DupValueRT(rt, sf->var_buf[var_idx]);\n        var_ref->pvalue = &var_ref->value;\n        /* the reference is no longer to a local variable */\n        var_ref->is_detached = TRUE;\n        add_gc_object(rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF);\n    }\n}\n\nstatic void close_lexical_var(JSContext *ctx, JSStackFrame *sf, int idx, int is_arg)\n{\n    struct list_head *el, *el1;\n    JSVarRef *var_ref;\n    int var_idx = idx;\n\n    list_for_each_safe(el, el1, &sf->var_ref_list) {\n        var_ref = list_entry(el, JSVarRef, header.link);\n        if (var_idx == var_ref->var_idx && var_ref->is_arg == is_arg) {\n            var_ref->value = JS_DupValue(ctx, sf->var_buf[var_idx]);\n            var_ref->pvalue = &var_ref->value;\n            list_del(&var_ref->header.link);\n            /* the reference is no longer to a local variable */\n            var_ref->is_detached = TRUE;\n            add_gc_object(ctx->rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF);\n        }\n    }\n}\n\n#define JS_CALL_FLAG_COPY_ARGV   (1 << 1)\n#define JS_CALL_FLAG_GENERATOR   (1 << 2)\n\nstatic JSValue js_call_c_function(JSContext *ctx, JSValueConst func_obj,\n                                  JSValueConst this_obj,\n                                  int argc, JSValueConst *argv, int flags)\n{\n    JSRuntime *rt = ctx->rt;\n    JSCFunctionType func;\n    JSObject *p;\n    JSStackFrame sf_s, *sf = &sf_s, *prev_sf;\n    JSValue ret_val;\n    JSValueConst *arg_buf;\n    int arg_count, i;\n    JSCFunctionEnum cproto;\n\n    p = JS_VALUE_GET_OBJ(func_obj);\n    cproto = p->u.cfunc.cproto;\n    arg_count = p->u.cfunc.length;\n\n    /* better to always check stack overflow */\n    if (js_check_stack_overflow(rt, sizeof(arg_buf[0]) * arg_count))\n        return JS_ThrowStackOverflow(ctx);\n\n    prev_sf = rt->current_stack_frame;\n    sf->prev_frame = prev_sf;\n    rt->current_stack_frame = sf;\n    ctx = p->u.cfunc.realm; /* change the current realm */\n    \n#ifdef CONFIG_BIGNUM\n    /* we only propagate the bignum mode as some runtime functions\n       test it */\n    if (prev_sf)\n        sf->js_mode = prev_sf->js_mode & JS_MODE_MATH;\n    else\n        sf->js_mode = 0;\n#else\n    sf->js_mode = 0;\n#endif\n    sf->cur_func = func_obj;\n    sf->arg_count = argc;\n    arg_buf = argv;\n\n    if (unlikely(argc < arg_count)) {\n        /* ensure that at least argc_count arguments are readable */\n        arg_buf = alloca(sizeof(arg_buf[0]) * arg_count);\n        for(i = 0; i < argc; i++)\n            arg_buf[i] = argv[i];\n        for(i = argc; i < arg_count; i++)\n            arg_buf[i] = JS_UNDEFINED;\n        sf->arg_count = arg_count;\n    }\n    sf->arg_buf = (JSValue*)arg_buf;\n\n    func = p->u.cfunc.c_function;\n    switch(cproto) {\n    case JS_CFUNC_constructor:\n    case JS_CFUNC_constructor_or_func:\n        if (!(flags & JS_CALL_FLAG_CONSTRUCTOR)) {\n            if (cproto == JS_CFUNC_constructor) {\n            not_a_constructor:\n                ret_val = JS_ThrowTypeError(ctx, \"must be called with new\");\n                break;\n            } else {\n                this_obj = JS_UNDEFINED;\n            }\n        }\n        /* here this_obj is new_target */\n        /* fall thru */\n    case JS_CFUNC_generic:\n        ret_val = func.generic(ctx, this_obj, argc, arg_buf);\n        break;\n    case JS_CFUNC_constructor_magic:\n    case JS_CFUNC_constructor_or_func_magic:\n        if (!(flags & JS_CALL_FLAG_CONSTRUCTOR)) {\n            if (cproto == JS_CFUNC_constructor_magic) {\n                goto not_a_constructor;\n            } else {\n                this_obj = JS_UNDEFINED;\n            }\n        }\n        /* fall thru */\n    case JS_CFUNC_generic_magic:\n        ret_val = func.generic_magic(ctx, this_obj, argc, arg_buf,\n                                     p->u.cfunc.magic);\n        break;\n    case JS_CFUNC_getter:\n        ret_val = func.getter(ctx, this_obj);\n        break;\n    case JS_CFUNC_setter:\n        ret_val = func.setter(ctx, this_obj, arg_buf[0]);\n        break;\n    case JS_CFUNC_getter_magic:\n        ret_val = func.getter_magic(ctx, this_obj, p->u.cfunc.magic);\n        break;\n    case JS_CFUNC_setter_magic:\n        ret_val = func.setter_magic(ctx, this_obj, arg_buf[0], p->u.cfunc.magic);\n        break;\n    case JS_CFUNC_f_f:\n        {\n            double d1;\n\n            if (unlikely(JS_ToFloat64(ctx, &d1, arg_buf[0]))) {\n                ret_val = JS_EXCEPTION;\n                break;\n            }\n            ret_val = JS_NewFloat64(ctx, func.f_f(d1));\n        }\n        break;\n    case JS_CFUNC_f_f_f:\n        {\n            double d1, d2;\n\n            if (unlikely(JS_ToFloat64(ctx, &d1, arg_buf[0]))) {\n                ret_val = JS_EXCEPTION;\n                break;\n            }\n            if (unlikely(JS_ToFloat64(ctx, &d2, arg_buf[1]))) {\n                ret_val = JS_EXCEPTION;\n                break;\n            }\n            ret_val = JS_NewFloat64(ctx, func.f_f_f(d1, d2));\n        }\n        break;\n    case JS_CFUNC_iterator_next:\n        {\n            int done;\n            ret_val = func.iterator_next(ctx, this_obj, argc, arg_buf,\n                                         &done, p->u.cfunc.magic);\n            if (!JS_IsException(ret_val) && done != 2) {\n                ret_val = js_create_iterator_result(ctx, ret_val, done);\n            }\n        }\n        break;\n    default:\n        abort();\n    }\n\n    rt->current_stack_frame = sf->prev_frame;\n    return ret_val;\n}\n\nstatic JSValue js_call_bound_function(JSContext *ctx, JSValueConst func_obj,\n                                      JSValueConst this_obj,\n                                      int argc, JSValueConst *argv, int flags)\n{\n    JSObject *p;\n    JSBoundFunction *bf;\n    JSValueConst *arg_buf, new_target;\n    int arg_count, i;\n\n    p = JS_VALUE_GET_OBJ(func_obj);\n    bf = p->u.bound_function;\n    arg_count = bf->argc + argc;\n    if (js_check_stack_overflow(ctx->rt, sizeof(JSValue) * arg_count))\n        return JS_ThrowStackOverflow(ctx);\n    arg_buf = alloca(sizeof(JSValue) * arg_count);\n    for(i = 0; i < bf->argc; i++) {\n        arg_buf[i] = bf->argv[i];\n    }\n    for(i = 0; i < argc; i++) {\n        arg_buf[bf->argc + i] = argv[i];\n    }\n    if (flags & JS_CALL_FLAG_CONSTRUCTOR) {\n        new_target = this_obj;\n        if (js_same_value(ctx, func_obj, new_target))\n            new_target = bf->func_obj;\n        return JS_CallConstructor2(ctx, bf->func_obj, new_target,\n                                   arg_count, arg_buf);\n    } else {\n        return JS_Call(ctx, bf->func_obj, bf->this_val,\n                       arg_count, arg_buf);\n    }\n}\n\n/* argument of OP_special_object */\ntypedef enum {\n    OP_SPECIAL_OBJECT_ARGUMENTS,\n    OP_SPECIAL_OBJECT_MAPPED_ARGUMENTS,\n    OP_SPECIAL_OBJECT_THIS_FUNC,\n    OP_SPECIAL_OBJECT_NEW_TARGET,\n    OP_SPECIAL_OBJECT_HOME_OBJECT,\n    OP_SPECIAL_OBJECT_VAR_OBJECT,\n    OP_SPECIAL_OBJECT_IMPORT_META,\n} OPSpecialObjectEnum;\n\n#define FUNC_RET_AWAIT      0\n#define FUNC_RET_YIELD      1\n#define FUNC_RET_YIELD_STAR 2\n\n/* argv[] is modified if (flags & JS_CALL_FLAG_COPY_ARGV) = 0. */\nstatic JSValue JS_CallInternal(JSContext *caller_ctx, JSValueConst func_obj,\n                               JSValueConst this_obj, JSValueConst new_target,\n                               int argc, JSValue *argv, int flags)\n{\n    JSRuntime *rt = caller_ctx->rt;\n    JSContext *ctx;\n    JSObject *p;\n    JSFunctionBytecode *b;\n    JSStackFrame sf_s, *sf = &sf_s;\n    const uint8_t *pc;\n    int opcode, arg_allocated_size, i;\n    JSValue *local_buf, *stack_buf, *var_buf, *arg_buf, *sp, ret_val, *pval;\n    JSVarRef **var_refs;\n    size_t alloca_size;\n\n#if !DIRECT_DISPATCH\n#define SWITCH(pc)      switch (opcode = *pc++)\n#define CASE(op)        case op\n#define DEFAULT         default\n#define BREAK           break\n#else\n    static const void * const dispatch_table[256] = {\n#define DEF(id, size, n_pop, n_push, f) && case_OP_ ## id,\n#if SHORT_OPCODES\n#define def(id, size, n_pop, n_push, f)\n#else                                                     \n#define def(id, size, n_pop, n_push, f) && case_default,\n#endif\n#include \"quickjs-opcode.h\"\n        [ OP_COUNT ... 255 ] = &&case_default\n    };\n#define SWITCH(pc)      goto *dispatch_table[opcode = *pc++];\n#define CASE(op)        case_ ## op\n#define DEFAULT         case_default\n#define BREAK           SWITCH(pc)\n#endif\n\n    if (js_poll_interrupts(caller_ctx))\n        return JS_EXCEPTION;\n    if (unlikely(JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT)) {\n        if (flags & JS_CALL_FLAG_GENERATOR) {\n            JSAsyncFunctionState *s = JS_VALUE_GET_PTR(func_obj);\n            /* func_obj get contains a pointer to JSFuncAsyncState */\n            /* the stack frame is already allocated */\n            sf = &s->frame;\n            p = JS_VALUE_GET_OBJ(sf->cur_func);\n            b = p->u.func.function_bytecode;\n            ctx = b->realm;\n            var_refs = p->u.func.var_refs;\n            local_buf = arg_buf = sf->arg_buf;\n            var_buf = sf->var_buf;\n            stack_buf = sf->var_buf + b->var_count;\n            sp = sf->cur_sp;\n            sf->cur_sp = NULL; /* cur_sp is NULL if the function is running */\n            pc = sf->cur_pc;\n            sf->prev_frame = rt->current_stack_frame;\n            rt->current_stack_frame = sf;\n            if (s->throw_flag)\n                goto exception;\n            else\n                goto restart;\n        } else {\n            goto not_a_function;\n        }\n    }\n    p = JS_VALUE_GET_OBJ(func_obj);\n    if (unlikely(p->class_id != JS_CLASS_BYTECODE_FUNCTION)) {\n        JSClassCall *call_func;\n        call_func = rt->class_array[p->class_id].call;\n        if (!call_func) {\n        not_a_function:\n            return JS_ThrowTypeError(caller_ctx, \"not a function\");\n        }\n        return call_func(caller_ctx, func_obj, this_obj, argc,\n                         (JSValueConst *)argv, flags);\n    }\n    b = p->u.func.function_bytecode;\n\n    if (unlikely(argc < b->arg_count || (flags & JS_CALL_FLAG_COPY_ARGV))) {\n        arg_allocated_size = b->arg_count;\n    } else {\n        arg_allocated_size = 0;\n    }\n\n    alloca_size = sizeof(JSValue) * (arg_allocated_size + b->var_count +\n                                     b->stack_size);\n    if (js_check_stack_overflow(rt, alloca_size))\n        return JS_ThrowStackOverflow(caller_ctx);\n\n    sf->js_mode = b->js_mode;\n    arg_buf = argv;\n    sf->arg_count = argc;\n    sf->cur_func = func_obj;\n    init_list_head(&sf->var_ref_list);\n    var_refs = p->u.func.var_refs;\n\n    local_buf = alloca(alloca_size);\n    if (unlikely(arg_allocated_size)) {\n        int n = min_int(argc, b->arg_count);\n        arg_buf = local_buf;\n        for(i = 0; i < n; i++)\n            arg_buf[i] = JS_DupValue(caller_ctx, argv[i]);\n        for(; i < b->arg_count; i++)\n            arg_buf[i] = JS_UNDEFINED;\n        sf->arg_count = b->arg_count;\n    }\n    var_buf = local_buf + arg_allocated_size;\n    sf->var_buf = var_buf;\n    sf->arg_buf = arg_buf;\n\n    for(i = 0; i < b->var_count; i++)\n        var_buf[i] = JS_UNDEFINED;\n\n    stack_buf = var_buf + b->var_count;\n    sp = stack_buf;\n    pc = b->byte_code_buf;\n    sf->prev_frame = rt->current_stack_frame;\n    rt->current_stack_frame = sf;\n    ctx = b->realm; /* set the current realm */\n    \n restart:\n    for(;;) {\n        int call_argc;\n        JSValue *call_argv;\n\n        SWITCH(pc) {\n        CASE(OP_push_i32):\n            *sp++ = JS_NewInt32(ctx, get_u32(pc));\n            pc += 4;\n            BREAK;\n        CASE(OP_push_const):\n            *sp++ = JS_DupValue(ctx, b->cpool[get_u32(pc)]);\n            pc += 4;\n            BREAK;\n#if SHORT_OPCODES\n        CASE(OP_push_minus1):\n        CASE(OP_push_0):\n        CASE(OP_push_1):\n        CASE(OP_push_2):\n        CASE(OP_push_3):\n        CASE(OP_push_4):\n        CASE(OP_push_5):\n        CASE(OP_push_6):\n        CASE(OP_push_7):\n            *sp++ = JS_NewInt32(ctx, opcode - OP_push_0);\n            BREAK;\n        CASE(OP_push_i8):\n            *sp++ = JS_NewInt32(ctx, get_i8(pc));\n            pc += 1;\n            BREAK;\n        CASE(OP_push_i16):\n            *sp++ = JS_NewInt32(ctx, get_i16(pc));\n            pc += 2;\n            BREAK;\n        CASE(OP_push_const8):\n            *sp++ = JS_DupValue(ctx, b->cpool[*pc++]);\n            BREAK;\n        CASE(OP_fclosure8):\n            *sp++ = js_closure(ctx, JS_DupValue(ctx, b->cpool[*pc++]), var_refs, sf);\n            if (unlikely(JS_IsException(sp[-1])))\n                goto exception;\n            BREAK;\n        CASE(OP_push_empty_string):\n            *sp++ = JS_AtomToString(ctx, JS_ATOM_empty_string);\n            BREAK;\n        CASE(OP_get_length):\n            {\n                JSValue val;\n\n                val = JS_GetProperty(ctx, sp[-1], JS_ATOM_length);\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = val;\n            }\n            BREAK;\n#endif\n        CASE(OP_push_atom_value):\n            *sp++ = JS_AtomToValue(ctx, get_u32(pc));\n            pc += 4;\n            BREAK;\n        CASE(OP_undefined):\n            *sp++ = JS_UNDEFINED;\n            BREAK;\n        CASE(OP_null):\n            *sp++ = JS_NULL;\n            BREAK;\n        CASE(OP_push_this):\n            /* OP_push_this is only called at the start of a function */\n            {\n                JSValue val;\n                if (!(b->js_mode & JS_MODE_STRICT)) {\n                    uint32_t tag = JS_VALUE_GET_TAG(this_obj);\n                    if (likely(tag == JS_TAG_OBJECT))\n                        goto normal_this;\n                    if (tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED) {\n                        val = JS_DupValue(ctx, ctx->global_obj);\n                    } else {\n                        val = JS_ToObject(ctx, this_obj);\n                        if (JS_IsException(val))\n                            goto exception;\n                    }\n                } else {\n                normal_this:\n                    val = JS_DupValue(ctx, this_obj);\n                }\n                *sp++ = val;\n            }\n            BREAK;\n        CASE(OP_push_false):\n            *sp++ = JS_FALSE;\n            BREAK;\n        CASE(OP_push_true):\n            *sp++ = JS_TRUE;\n            BREAK;\n        CASE(OP_object):\n            *sp++ = JS_NewObject(ctx);\n            if (unlikely(JS_IsException(sp[-1])))\n                goto exception;\n            BREAK;\n        CASE(OP_special_object):\n            {\n                int arg = *pc++;\n                switch(arg) {\n                case OP_SPECIAL_OBJECT_ARGUMENTS:\n                    *sp++ = js_build_arguments(ctx, argc, (JSValueConst *)argv);\n                    if (unlikely(JS_IsException(sp[-1])))\n                        goto exception;\n                    break;\n                case OP_SPECIAL_OBJECT_MAPPED_ARGUMENTS:\n                    *sp++ = js_build_mapped_arguments(ctx, argc, (JSValueConst *)argv,\n                                                      sf, min_int(argc, b->arg_count));\n                    if (unlikely(JS_IsException(sp[-1])))\n                        goto exception;\n                    break;\n                case OP_SPECIAL_OBJECT_THIS_FUNC:\n                    *sp++ = JS_DupValue(ctx, sf->cur_func);\n                    break;\n                case OP_SPECIAL_OBJECT_NEW_TARGET:\n                    *sp++ = JS_DupValue(ctx, new_target);\n                    break;\n                case OP_SPECIAL_OBJECT_HOME_OBJECT:\n                    {\n                        JSObject *p1;\n                        p1 = p->u.func.home_object;\n                        if (unlikely(!p1))\n                            *sp++ = JS_UNDEFINED;\n                        else\n                            *sp++ = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p1));\n                    }\n                    break;\n                case OP_SPECIAL_OBJECT_VAR_OBJECT:\n                    *sp++ = JS_NewObjectProto(ctx, JS_NULL);\n                    if (unlikely(JS_IsException(sp[-1])))\n                        goto exception;\n                    break;\n                case OP_SPECIAL_OBJECT_IMPORT_META:\n                    *sp++ = js_import_meta(ctx);\n                    if (unlikely(JS_IsException(sp[-1])))\n                        goto exception;\n                    break;\n                default:\n                    abort();\n                }\n            }\n            BREAK;\n        CASE(OP_rest):\n            {\n                int first = get_u16(pc);\n                pc += 2;\n                *sp++ = js_build_rest(ctx, first, argc, (JSValueConst *)argv);\n                if (unlikely(JS_IsException(sp[-1])))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_drop):\n            JS_FreeValue(ctx, sp[-1]);\n            sp--;\n            BREAK;\n        CASE(OP_nip):\n            JS_FreeValue(ctx, sp[-2]);\n            sp[-2] = sp[-1];\n            sp--;\n            BREAK;\n        CASE(OP_nip1): /* a b c -> b c */\n            JS_FreeValue(ctx, sp[-3]);\n            sp[-3] = sp[-2];\n            sp[-2] = sp[-1];\n            sp--;\n            BREAK;\n        CASE(OP_dup):\n            sp[0] = JS_DupValue(ctx, sp[-1]);\n            sp++;\n            BREAK;\n        CASE(OP_dup2): /* a b -> a b a b */\n            sp[0] = JS_DupValue(ctx, sp[-2]);\n            sp[1] = JS_DupValue(ctx, sp[-1]);\n            sp += 2;\n            BREAK;\n        CASE(OP_dup3): /* a b c -> a b c a b c */\n            sp[0] = JS_DupValue(ctx, sp[-3]);\n            sp[1] = JS_DupValue(ctx, sp[-2]);\n            sp[2] = JS_DupValue(ctx, sp[-1]);\n            sp += 3;\n            BREAK;\n        CASE(OP_dup1): /* a b -> a a b */\n            sp[0] = sp[-1];\n            sp[-1] = JS_DupValue(ctx, sp[-2]);\n            sp++;\n            BREAK;\n        CASE(OP_insert2): /* obj a -> a obj a (dup_x1) */\n            sp[0] = sp[-1];\n            sp[-1] = sp[-2];\n            sp[-2] = JS_DupValue(ctx, sp[0]);\n            sp++;\n            BREAK;\n        CASE(OP_insert3): /* obj prop a -> a obj prop a (dup_x2) */\n            sp[0] = sp[-1];\n            sp[-1] = sp[-2];\n            sp[-2] = sp[-3];\n            sp[-3] = JS_DupValue(ctx, sp[0]);\n            sp++;\n            BREAK;\n        CASE(OP_insert4): /* this obj prop a -> a this obj prop a */\n            sp[0] = sp[-1];\n            sp[-1] = sp[-2];\n            sp[-2] = sp[-3];\n            sp[-3] = sp[-4];\n            sp[-4] = JS_DupValue(ctx, sp[0]);\n            sp++;\n            BREAK;\n        CASE(OP_perm3): /* obj a b -> a obj b (213) */\n            {\n                JSValue tmp;\n                tmp = sp[-2];\n                sp[-2] = sp[-3];\n                sp[-3] = tmp;\n            }\n            BREAK;\n        CASE(OP_rot3l): /* x a b -> a b x (231) */\n            {\n                JSValue tmp;\n                tmp = sp[-3];\n                sp[-3] = sp[-2];\n                sp[-2] = sp[-1];\n                sp[-1] = tmp;\n            }\n            BREAK;\n        CASE(OP_rot4l): /* x a b c -> a b c x */\n            {\n                JSValue tmp;\n                tmp = sp[-4];\n                sp[-4] = sp[-3];\n                sp[-3] = sp[-2];\n                sp[-2] = sp[-1];\n                sp[-1] = tmp;\n            }\n            BREAK;\n        CASE(OP_rot5l): /* x a b c d -> a b c d x */\n            {\n                JSValue tmp;\n                tmp = sp[-5];\n                sp[-5] = sp[-4];\n                sp[-4] = sp[-3];\n                sp[-3] = sp[-2];\n                sp[-2] = sp[-1];\n                sp[-1] = tmp;\n            }\n            BREAK;\n        CASE(OP_rot3r): /* a b x -> x a b (312) */\n            {\n                JSValue tmp;\n                tmp = sp[-1];\n                sp[-1] = sp[-2];\n                sp[-2] = sp[-3];\n                sp[-3] = tmp;\n            }\n            BREAK;\n        CASE(OP_perm4): /* obj prop a b -> a obj prop b */\n            {\n                JSValue tmp;\n                tmp = sp[-2];\n                sp[-2] = sp[-3];\n                sp[-3] = sp[-4];\n                sp[-4] = tmp;\n            }\n            BREAK;\n        CASE(OP_perm5): /* this obj prop a b -> a this obj prop b */\n            {\n                JSValue tmp;\n                tmp = sp[-2];\n                sp[-2] = sp[-3];\n                sp[-3] = sp[-4];\n                sp[-4] = sp[-5];\n                sp[-5] = tmp;\n            }\n            BREAK;\n        CASE(OP_swap): /* a b -> b a */\n            {\n                JSValue tmp;\n                tmp = sp[-2];\n                sp[-2] = sp[-1];\n                sp[-1] = tmp;\n            }\n            BREAK;\n        CASE(OP_swap2): /* a b c d -> c d a b */\n            {\n                JSValue tmp1, tmp2;\n                tmp1 = sp[-4];\n                tmp2 = sp[-3];\n                sp[-4] = sp[-2];\n                sp[-3] = sp[-1];\n                sp[-2] = tmp1;\n                sp[-1] = tmp2;\n            }\n            BREAK;\n\n        CASE(OP_fclosure):\n            {\n                JSValue bfunc = JS_DupValue(ctx, b->cpool[get_u32(pc)]);\n                pc += 4;\n                *sp++ = js_closure(ctx, bfunc, var_refs, sf);\n                if (unlikely(JS_IsException(sp[-1])))\n                    goto exception;\n            }\n            BREAK;\n#if SHORT_OPCODES\n        CASE(OP_call0):\n        CASE(OP_call1):\n        CASE(OP_call2):\n        CASE(OP_call3):\n            call_argc = opcode - OP_call0;\n            goto has_call_argc;\n#endif\n        CASE(OP_call):\n        CASE(OP_tail_call):\n            {\n                call_argc = get_u16(pc);\n                pc += 2;\n                goto has_call_argc;\n            has_call_argc:\n                call_argv = sp - call_argc;\n                sf->cur_pc = pc;\n                ret_val = JS_CallInternal(ctx, call_argv[-1], JS_UNDEFINED,\n                                          JS_UNDEFINED, call_argc, call_argv, 0);\n                if (unlikely(JS_IsException(ret_val)))\n                    goto exception;\n                if (opcode == OP_tail_call)\n                    goto done;\n                for(i = -1; i < call_argc; i++)\n                    JS_FreeValue(ctx, call_argv[i]);\n                sp -= call_argc + 1;\n                *sp++ = ret_val;\n            }\n            BREAK;\n        CASE(OP_call_constructor):\n            {\n                call_argc = get_u16(pc);\n                pc += 2;\n                call_argv = sp - call_argc;\n                sf->cur_pc = pc;\n                ret_val = JS_CallConstructorInternal(ctx, call_argv[-2],\n                                                     call_argv[-1],\n                                                     call_argc, call_argv, 0);\n                if (unlikely(JS_IsException(ret_val)))\n                    goto exception;\n                for(i = -2; i < call_argc; i++)\n                    JS_FreeValue(ctx, call_argv[i]);\n                sp -= call_argc + 2;\n                *sp++ = ret_val;\n            }\n            BREAK;\n        CASE(OP_call_method):\n        CASE(OP_tail_call_method):\n            {\n                call_argc = get_u16(pc);\n                pc += 2;\n                call_argv = sp - call_argc;\n                sf->cur_pc = pc;\n                ret_val = JS_CallInternal(ctx, call_argv[-1], call_argv[-2],\n                                          JS_UNDEFINED, call_argc, call_argv, 0);\n                if (unlikely(JS_IsException(ret_val)))\n                    goto exception;\n                if (opcode == OP_tail_call_method)\n                    goto done;\n                for(i = -2; i < call_argc; i++)\n                    JS_FreeValue(ctx, call_argv[i]);\n                sp -= call_argc + 2;\n                *sp++ = ret_val;\n            }\n            BREAK;\n        CASE(OP_array_from):\n            {\n                int i, ret;\n\n                call_argc = get_u16(pc);\n                pc += 2;\n                ret_val = JS_NewArray(ctx);\n                if (unlikely(JS_IsException(ret_val)))\n                    goto exception;\n                call_argv = sp - call_argc;\n                for(i = 0; i < call_argc; i++) {\n                    ret = JS_DefinePropertyValue(ctx, ret_val, __JS_AtomFromUInt32(i), call_argv[i],\n                                                 JS_PROP_C_W_E | JS_PROP_THROW);\n                    call_argv[i] = JS_UNDEFINED;\n                    if (ret < 0) {\n                        JS_FreeValue(ctx, ret_val);\n                        goto exception;\n                    }\n                }\n                sp -= call_argc;\n                *sp++ = ret_val;\n            }\n            BREAK;\n\n        CASE(OP_apply):\n            {\n                int magic;\n                magic = get_u16(pc);\n                pc += 2;\n\n                ret_val = js_function_apply(ctx, sp[-3], 2, (JSValueConst *)&sp[-2], magic);\n                if (unlikely(JS_IsException(ret_val)))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-3]);\n                JS_FreeValue(ctx, sp[-2]);\n                JS_FreeValue(ctx, sp[-1]);\n                sp -= 3;\n                *sp++ = ret_val;\n            }\n            BREAK;\n        CASE(OP_return):\n            ret_val = *--sp;\n            goto done;\n        CASE(OP_return_undef):\n            ret_val = JS_UNDEFINED;\n            goto done;\n\n        CASE(OP_check_ctor_return):\n            /* return TRUE if 'this' should be returned */\n            if (!JS_IsObject(sp[-1])) {\n                if (!JS_IsUndefined(sp[-1])) {\n                    JS_ThrowTypeError(caller_ctx, \"derived class constructor must return an object or undefined\");\n                    goto exception;\n                }\n                sp[0] = JS_TRUE;\n            } else {\n                sp[0] = JS_FALSE;\n            }\n            sp++;\n            BREAK;\n        CASE(OP_check_ctor):\n            if (JS_IsUndefined(new_target)) {\n                JS_ThrowTypeError(ctx, \"class constructors must be invoked with 'new'\");\n                goto exception;\n            }\n            BREAK;\n        CASE(OP_check_brand):\n            if (JS_CheckBrand(ctx, sp[-2], sp[-1]) < 0)\n                goto exception;\n            BREAK;\n        CASE(OP_add_brand):\n            if (JS_AddBrand(ctx, sp[-2], sp[-1]) < 0)\n                goto exception;\n            JS_FreeValue(ctx, sp[-2]);\n            JS_FreeValue(ctx, sp[-1]);\n            sp -= 2;\n            BREAK;\n            \n        CASE(OP_throw):\n            JS_Throw(ctx, *--sp);\n            goto exception;\n\n        CASE(OP_throw_error):\n#define JS_THROW_VAR_RO             0\n#define JS_THROW_VAR_REDECL         1\n#define JS_THROW_VAR_UNINITIALIZED  2\n#define JS_THROW_ERROR_DELETE_SUPER   3\n#define JS_THROW_ERROR_ITERATOR_THROW 4\n            {\n                JSAtom atom;\n                int type;\n                atom = get_u32(pc);\n                type = pc[4];\n                pc += 5;\n                if (type == JS_THROW_VAR_RO)\n                    JS_ThrowTypeErrorReadOnly(ctx, JS_PROP_THROW, atom);\n                else\n                if (type == JS_THROW_VAR_REDECL)\n                    JS_ThrowSyntaxErrorVarRedeclaration(ctx, atom);\n                else\n                if (type == JS_THROW_VAR_UNINITIALIZED)\n                    JS_ThrowReferenceErrorUninitialized(ctx, atom);\n                else\n                if (type == JS_THROW_ERROR_DELETE_SUPER)\n                    JS_ThrowReferenceError(ctx, \"unsupported reference to 'super'\");\n                else\n                if (type == JS_THROW_ERROR_ITERATOR_THROW)\n                    JS_ThrowTypeError(ctx, \"iterator does not have a throw method\");\n                else\n                    JS_ThrowInternalError(ctx, \"invalid throw var type %d\", type);\n            }\n            goto exception;\n\n        CASE(OP_eval):\n            {\n                JSValueConst obj;\n                int scope_idx;\n                call_argc = get_u16(pc);\n                scope_idx = get_u16(pc + 2) - 1;\n                pc += 4;\n                call_argv = sp - call_argc;\n                sf->cur_pc = pc;\n                if (js_same_value(ctx, call_argv[-1], ctx->eval_obj)) {\n                    if (call_argc >= 1)\n                        obj = call_argv[0];\n                    else\n                        obj = JS_UNDEFINED;\n                    ret_val = JS_EvalObject(ctx, JS_UNDEFINED, obj,\n                                            JS_EVAL_TYPE_DIRECT, scope_idx);\n                } else {\n                    ret_val = JS_CallInternal(ctx, call_argv[-1], JS_UNDEFINED,\n                                              JS_UNDEFINED, call_argc, call_argv, 0);\n                }\n                if (unlikely(JS_IsException(ret_val)))\n                    goto exception;\n                for(i = -1; i < call_argc; i++)\n                    JS_FreeValue(ctx, call_argv[i]);\n                sp -= call_argc + 1;\n                *sp++ = ret_val;\n            }\n            BREAK;\n            /* could merge with OP_apply */\n        CASE(OP_apply_eval):\n            {\n                int scope_idx;\n                uint32_t len;\n                JSValue *tab;\n                JSValueConst obj;\n\n                scope_idx = get_u16(pc) - 1;\n                pc += 2;\n                tab = build_arg_list(ctx, &len, sp[-1]);\n                if (!tab)\n                    goto exception;\n                if (js_same_value(ctx, sp[-2], ctx->eval_obj)) {\n                    if (len >= 1)\n                        obj = tab[0];\n                    else\n                        obj = JS_UNDEFINED;\n                    ret_val = JS_EvalObject(ctx, JS_UNDEFINED, obj,\n                                            JS_EVAL_TYPE_DIRECT, scope_idx);\n                } else {\n                    ret_val = JS_Call(ctx, sp[-2], JS_UNDEFINED, len,\n                                      (JSValueConst *)tab);\n                }\n                free_arg_list(ctx, tab, len);\n                if (unlikely(JS_IsException(ret_val)))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-2]);\n                JS_FreeValue(ctx, sp[-1]);\n                sp -= 2;\n                *sp++ = ret_val;\n            }\n            BREAK;\n\n        CASE(OP_regexp):\n            {\n                sp[-2] = js_regexp_constructor_internal(ctx, JS_UNDEFINED,\n                                                        sp[-2], sp[-1]);\n                sp--;\n            }\n            BREAK;\n\n        CASE(OP_get_super):\n            {\n                JSValue proto;\n                proto = JS_GetPrototype(ctx, sp[-1]);\n                if (JS_IsException(proto))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = proto;\n            }\n            BREAK;\n\n        CASE(OP_import):\n            {\n                JSValue val;\n                val = js_dynamic_import(ctx, sp[-1]);\n                if (JS_IsException(val))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = val;\n            }\n            BREAK;\n\n        CASE(OP_check_var):\n            {\n                int ret;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                ret = JS_CheckGlobalVar(ctx, atom);\n                if (ret < 0)\n                    goto exception;\n                *sp++ = JS_NewBool(ctx, ret);\n            }\n            BREAK;\n\n        CASE(OP_get_var_undef):\n        CASE(OP_get_var):\n            {\n                JSValue val;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                val = JS_GetGlobalVar(ctx, atom, opcode - OP_get_var_undef);\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n                *sp++ = val;\n            }\n            BREAK;\n\n        CASE(OP_put_var):\n        CASE(OP_put_var_init):\n            {\n                int ret;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                ret = JS_SetGlobalVar(ctx, atom, sp[-1], opcode - OP_put_var);\n                sp--;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_put_var_strict):\n            {\n                int ret;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                /* sp[-2] is JS_TRUE or JS_FALSE */\n                if (unlikely(!JS_VALUE_GET_INT(sp[-2]))) {\n                    JS_ThrowReferenceErrorNotDefined(ctx, atom);\n                    goto exception;\n                }\n                ret = JS_SetGlobalVar(ctx, atom, sp[-1], 2);\n                sp -= 2;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_check_define_var):\n            {\n                JSAtom atom;\n                int flags;\n                atom = get_u32(pc);\n                flags = pc[4];\n                pc += 5;\n                if (JS_CheckDefineGlobalVar(ctx, atom, flags))\n                    goto exception;\n            }\n            BREAK;\n        CASE(OP_define_var):\n            {\n                JSAtom atom;\n                int flags;\n                atom = get_u32(pc);\n                flags = pc[4];\n                pc += 5;\n                if (JS_DefineGlobalVar(ctx, atom, flags))\n                    goto exception;\n            }\n            BREAK;\n        CASE(OP_define_func):\n            {\n                JSAtom atom;\n                int flags;\n                atom = get_u32(pc);\n                flags = pc[4];\n                pc += 5;\n                if (JS_DefineGlobalFunction(ctx, atom, sp[-1], flags))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp--;\n            }\n            BREAK;\n\n        CASE(OP_get_loc):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                sp[0] = JS_DupValue(ctx, var_buf[idx]);\n                sp++;\n            }\n            BREAK;\n        CASE(OP_put_loc):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                set_value(ctx, &var_buf[idx], sp[-1]);\n                sp--;\n            }\n            BREAK;\n        CASE(OP_set_loc):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                set_value(ctx, &var_buf[idx], JS_DupValue(ctx, sp[-1]));\n            }\n            BREAK;\n        CASE(OP_get_arg):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                sp[0] = JS_DupValue(ctx, arg_buf[idx]);\n                sp++;\n            }\n            BREAK;\n        CASE(OP_put_arg):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                set_value(ctx, &arg_buf[idx], sp[-1]);\n                sp--;\n            }\n            BREAK;\n        CASE(OP_set_arg):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                set_value(ctx, &arg_buf[idx], JS_DupValue(ctx, sp[-1]));\n            }\n            BREAK;\n\n#if SHORT_OPCODES\n        CASE(OP_get_loc8): *sp++ = JS_DupValue(ctx, var_buf[*pc++]); BREAK;\n        CASE(OP_put_loc8): set_value(ctx, &var_buf[*pc++], *--sp); BREAK;\n        CASE(OP_set_loc8): set_value(ctx, &var_buf[*pc++], JS_DupValue(ctx, sp[-1])); BREAK;\n\n        CASE(OP_get_loc0): *sp++ = JS_DupValue(ctx, var_buf[0]); BREAK;\n        CASE(OP_get_loc1): *sp++ = JS_DupValue(ctx, var_buf[1]); BREAK;\n        CASE(OP_get_loc2): *sp++ = JS_DupValue(ctx, var_buf[2]); BREAK;\n        CASE(OP_get_loc3): *sp++ = JS_DupValue(ctx, var_buf[3]); BREAK;\n        CASE(OP_put_loc0): set_value(ctx, &var_buf[0], *--sp); BREAK;\n        CASE(OP_put_loc1): set_value(ctx, &var_buf[1], *--sp); BREAK;\n        CASE(OP_put_loc2): set_value(ctx, &var_buf[2], *--sp); BREAK;\n        CASE(OP_put_loc3): set_value(ctx, &var_buf[3], *--sp); BREAK;\n        CASE(OP_set_loc0): set_value(ctx, &var_buf[0], JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_loc1): set_value(ctx, &var_buf[1], JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_loc2): set_value(ctx, &var_buf[2], JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_loc3): set_value(ctx, &var_buf[3], JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_get_arg0): *sp++ = JS_DupValue(ctx, arg_buf[0]); BREAK;\n        CASE(OP_get_arg1): *sp++ = JS_DupValue(ctx, arg_buf[1]); BREAK;\n        CASE(OP_get_arg2): *sp++ = JS_DupValue(ctx, arg_buf[2]); BREAK;\n        CASE(OP_get_arg3): *sp++ = JS_DupValue(ctx, arg_buf[3]); BREAK;\n        CASE(OP_put_arg0): set_value(ctx, &arg_buf[0], *--sp); BREAK;\n        CASE(OP_put_arg1): set_value(ctx, &arg_buf[1], *--sp); BREAK;\n        CASE(OP_put_arg2): set_value(ctx, &arg_buf[2], *--sp); BREAK;\n        CASE(OP_put_arg3): set_value(ctx, &arg_buf[3], *--sp); BREAK;\n        CASE(OP_set_arg0): set_value(ctx, &arg_buf[0], JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_arg1): set_value(ctx, &arg_buf[1], JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_arg2): set_value(ctx, &arg_buf[2], JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_arg3): set_value(ctx, &arg_buf[3], JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_get_var_ref0): *sp++ = JS_DupValue(ctx, *var_refs[0]->pvalue); BREAK;\n        CASE(OP_get_var_ref1): *sp++ = JS_DupValue(ctx, *var_refs[1]->pvalue); BREAK;\n        CASE(OP_get_var_ref2): *sp++ = JS_DupValue(ctx, *var_refs[2]->pvalue); BREAK;\n        CASE(OP_get_var_ref3): *sp++ = JS_DupValue(ctx, *var_refs[3]->pvalue); BREAK;\n        CASE(OP_put_var_ref0): set_value(ctx, var_refs[0]->pvalue, *--sp); BREAK;\n        CASE(OP_put_var_ref1): set_value(ctx, var_refs[1]->pvalue, *--sp); BREAK;\n        CASE(OP_put_var_ref2): set_value(ctx, var_refs[2]->pvalue, *--sp); BREAK;\n        CASE(OP_put_var_ref3): set_value(ctx, var_refs[3]->pvalue, *--sp); BREAK;\n        CASE(OP_set_var_ref0): set_value(ctx, var_refs[0]->pvalue, JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_var_ref1): set_value(ctx, var_refs[1]->pvalue, JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_var_ref2): set_value(ctx, var_refs[2]->pvalue, JS_DupValue(ctx, sp[-1])); BREAK;\n        CASE(OP_set_var_ref3): set_value(ctx, var_refs[3]->pvalue, JS_DupValue(ctx, sp[-1])); BREAK;\n#endif\n\n        CASE(OP_get_var_ref):\n            {\n                int idx;\n                JSValue val;\n                idx = get_u16(pc);\n                pc += 2;\n                val = *var_refs[idx]->pvalue;\n                sp[0] = JS_DupValue(ctx, val);\n                sp++;\n            }\n            BREAK;\n        CASE(OP_put_var_ref):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                set_value(ctx, var_refs[idx]->pvalue, sp[-1]);\n                sp--;\n            }\n            BREAK;\n        CASE(OP_set_var_ref):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                set_value(ctx, var_refs[idx]->pvalue, JS_DupValue(ctx, sp[-1]));\n            }\n            BREAK;\n        CASE(OP_get_var_ref_check):\n            {\n                int idx;\n                JSValue val;\n                idx = get_u16(pc);\n                pc += 2;\n                val = *var_refs[idx]->pvalue;\n                if (unlikely(JS_IsUninitialized(val))) {\n                    JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, TRUE);\n                    goto exception;\n                }\n                sp[0] = JS_DupValue(ctx, val);\n                sp++;\n            }\n            BREAK;\n        CASE(OP_put_var_ref_check):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                if (unlikely(JS_IsUninitialized(*var_refs[idx]->pvalue))) {\n                    JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, TRUE);\n                    goto exception;\n                }\n                set_value(ctx, var_refs[idx]->pvalue, sp[-1]);\n                sp--;\n            }\n            BREAK;\n        CASE(OP_put_var_ref_check_init):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                if (unlikely(!JS_IsUninitialized(*var_refs[idx]->pvalue))) {\n                    JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, TRUE);\n                    goto exception;\n                }\n                set_value(ctx, var_refs[idx]->pvalue, sp[-1]);\n                sp--;\n            }\n            BREAK;\n        CASE(OP_set_loc_uninitialized):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                set_value(ctx, &var_buf[idx], JS_UNINITIALIZED);\n            }\n            BREAK;\n        CASE(OP_get_loc_check):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                if (unlikely(JS_IsUninitialized(var_buf[idx]))) {\n                    JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, FALSE);\n                    goto exception;\n                }\n                sp[0] = JS_DupValue(ctx, var_buf[idx]);\n                sp++;\n            }\n            BREAK;\n        CASE(OP_put_loc_check):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                if (unlikely(JS_IsUninitialized(var_buf[idx]))) {\n                    JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, FALSE);\n                    goto exception;\n                }\n                set_value(ctx, &var_buf[idx], sp[-1]);\n                sp--;\n            }\n            BREAK;\n        CASE(OP_put_loc_check_init):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                if (unlikely(!JS_IsUninitialized(var_buf[idx]))) {\n                    JS_ThrowReferenceError(ctx, \"'this' can be initialized only once\");\n                    goto exception;\n                }\n                set_value(ctx, &var_buf[idx], sp[-1]);\n                sp--;\n            }\n            BREAK;\n        CASE(OP_close_loc):\n            {\n                int idx;\n                idx = get_u16(pc);\n                pc += 2;\n                close_lexical_var(ctx, sf, idx, FALSE);\n            }\n            BREAK;\n\n        CASE(OP_make_loc_ref):\n        CASE(OP_make_arg_ref):\n        CASE(OP_make_var_ref_ref):\n            {\n                JSVarRef *var_ref;\n                JSProperty *pr;\n                JSAtom atom;\n                int idx;\n                atom = get_u32(pc);\n                idx = get_u16(pc + 4);\n                pc += 6;\n                *sp++ = JS_NewObjectProto(ctx, JS_NULL);\n                if (unlikely(JS_IsException(sp[-1])))\n                    goto exception;\n                if (opcode == OP_make_var_ref_ref) {\n                    var_ref = var_refs[idx];\n                    var_ref->header.ref_count++;\n                } else {\n                    var_ref = get_var_ref(ctx, sf, idx, opcode == OP_make_arg_ref);\n                    if (!var_ref)\n                        goto exception;\n                }\n                pr = add_property(ctx, JS_VALUE_GET_OBJ(sp[-1]), atom,\n                                  JS_PROP_WRITABLE | JS_PROP_VARREF);\n                if (!pr) {\n                    free_var_ref(rt, var_ref);\n                    goto exception;\n                }\n                pr->u.var_ref = var_ref;\n                *sp++ = JS_AtomToValue(ctx, atom);\n            }\n            BREAK;\n        CASE(OP_make_var_ref):\n            {\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                if (JS_GetGlobalVarRef(ctx, atom, sp))\n                    goto exception;\n                sp += 2;\n            }\n            BREAK;\n\n        CASE(OP_goto):\n            pc += (int32_t)get_u32(pc);\n            if (unlikely(js_poll_interrupts(ctx)))\n                goto exception;\n            BREAK;\n#if SHORT_OPCODES\n        CASE(OP_goto16):\n            pc += (int16_t)get_u16(pc);\n            if (unlikely(js_poll_interrupts(ctx)))\n                goto exception;\n            BREAK;\n        CASE(OP_goto8):\n            pc += (int8_t)pc[0];\n            if (unlikely(js_poll_interrupts(ctx)))\n                goto exception;\n            BREAK;\n#endif\n        CASE(OP_if_true):\n            {\n                int res;\n                JSValue op1;\n\n                op1 = sp[-1];\n                pc += 4;\n                if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) {\n                    res = JS_VALUE_GET_INT(op1);\n                } else {\n                    res = JS_ToBoolFree(ctx, op1);\n                }\n                sp--;\n                if (res) {\n                    pc += (int32_t)get_u32(pc - 4) - 4;\n                }\n                if (unlikely(js_poll_interrupts(ctx)))\n                    goto exception;\n            }\n            BREAK;\n        CASE(OP_if_false):\n            {\n                int res;\n                JSValue op1;\n\n                op1 = sp[-1];\n                pc += 4;\n                if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) {\n                    res = JS_VALUE_GET_INT(op1);\n                } else {\n                    res = JS_ToBoolFree(ctx, op1);\n                }\n                sp--;\n                if (!res) {\n                    pc += (int32_t)get_u32(pc - 4) - 4;\n                }\n                if (unlikely(js_poll_interrupts(ctx)))\n                    goto exception;\n            }\n            BREAK;\n#if SHORT_OPCODES\n        CASE(OP_if_true8):\n            {\n                int res;\n                JSValue op1;\n\n                op1 = sp[-1];\n                pc += 1;\n                if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) {\n                    res = JS_VALUE_GET_INT(op1);\n                } else {\n                    res = JS_ToBoolFree(ctx, op1);\n                }\n                sp--;\n                if (res) {\n                    pc += (int8_t)pc[-1] - 1;\n                }\n                if (unlikely(js_poll_interrupts(ctx)))\n                    goto exception;\n            }\n            BREAK;\n        CASE(OP_if_false8):\n            {\n                int res;\n                JSValue op1;\n\n                op1 = sp[-1];\n                pc += 1;\n                if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) {\n                    res = JS_VALUE_GET_INT(op1);\n                } else {\n                    res = JS_ToBoolFree(ctx, op1);\n                }\n                sp--;\n                if (!res) {\n                    pc += (int8_t)pc[-1] - 1;\n                }\n                if (unlikely(js_poll_interrupts(ctx)))\n                    goto exception;\n            }\n            BREAK;\n#endif\n        CASE(OP_catch):\n            {\n                int32_t diff;\n                diff = get_u32(pc);\n                sp[0] = JS_NewCatchOffset(ctx, pc + diff - b->byte_code_buf);\n                sp++;\n                pc += 4;\n            }\n            BREAK;\n        CASE(OP_gosub):\n            {\n                int32_t diff;\n                diff = get_u32(pc);\n                /* XXX: should have a different tag to avoid security flaw */\n                sp[0] = JS_NewInt32(ctx, pc + 4 - b->byte_code_buf);\n                sp++;\n                pc += diff;\n            }\n            BREAK;\n        CASE(OP_ret):\n            {\n                JSValue op1;\n                uint32_t pos;\n                op1 = sp[-1];\n                if (unlikely(JS_VALUE_GET_TAG(op1) != JS_TAG_INT))\n                    goto ret_fail;\n                pos = JS_VALUE_GET_INT(op1);\n                if (unlikely(pos >= b->byte_code_len)) {\n                ret_fail:\n                    JS_ThrowInternalError(ctx, \"invalid ret value\");\n                    goto exception;\n                }\n                sp--;\n                pc = b->byte_code_buf + pos;\n            }\n            BREAK;\n\n        CASE(OP_for_in_start):\n            if (js_for_in_start(ctx, sp))\n                goto exception;\n            BREAK;\n        CASE(OP_for_in_next):\n            if (js_for_in_next(ctx, sp))\n                goto exception;\n            sp += 2;\n            BREAK;\n        CASE(OP_for_of_start):\n            if (js_for_of_start(ctx, sp, FALSE))\n                goto exception;\n            sp += 1;\n            *sp++ = JS_NewCatchOffset(ctx, 0);\n            BREAK;\n        CASE(OP_for_of_next):\n            {\n                int offset = -3 - pc[0];\n                pc += 1;\n                if (js_for_of_next(ctx, sp, offset))\n                    goto exception;\n                sp += 2;\n            }\n            BREAK;\n        CASE(OP_for_await_of_start):\n            if (js_for_of_start(ctx, sp, TRUE))\n                goto exception;\n            sp += 1;\n            *sp++ = JS_NewCatchOffset(ctx, 0);\n            BREAK;\n        CASE(OP_iterator_get_value_done):\n            if (js_iterator_get_value_done(ctx, sp))\n                goto exception;\n            sp += 1;\n            BREAK;\n        CASE(OP_iterator_check_object):\n            if (unlikely(!JS_IsObject(sp[-1]))) {\n                JS_ThrowTypeError(ctx, \"iterator must return an object\");\n                goto exception;\n            }\n            BREAK;\n\n        CASE(OP_iterator_close):\n            /* iter_obj next catch_offset -> */\n            sp--; /* drop the catch offset to avoid getting caught by exception */\n            JS_FreeValue(ctx, sp[-1]); /* drop the next method */\n            sp--;\n            if (!JS_IsUndefined(sp[-1])) {\n                if (JS_IteratorClose(ctx, sp[-1], FALSE))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n            }\n            sp--;\n            BREAK;\n        CASE(OP_iterator_close_return):\n            {\n                JSValue ret_val;\n                /* iter_obj next catch_offset ... ret_val ->\n                   ret_eval iter_obj next catch_offset */\n                ret_val = *--sp;\n                while (sp > stack_buf &&\n                       JS_VALUE_GET_TAG(sp[-1]) != JS_TAG_CATCH_OFFSET) {\n                    JS_FreeValue(ctx, *--sp);\n                }\n                if (unlikely(sp < stack_buf + 3)) {\n                    JS_ThrowInternalError(ctx, \"iterator_close_return\");\n                    JS_FreeValue(ctx, ret_val);\n                    goto exception;\n                }\n                sp[0] = sp[-1];\n                sp[-1] = sp[-2];\n                sp[-2] = sp[-3];\n                sp[-3] = ret_val;\n                sp++;\n            }\n            BREAK;\n\n        CASE(OP_iterator_next):\n            /* stack: iter_obj next catch_offset val */\n            {\n                JSValue ret;\n                ret = JS_Call(ctx, sp[-3], sp[-4],\n                              1, (JSValueConst *)(sp - 1));\n                if (JS_IsException(ret))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = ret;\n            }\n            BREAK;\n\n        CASE(OP_iterator_call):\n            /* stack: iter_obj next catch_offset val */\n            {\n                JSValue method, ret;\n                BOOL ret_flag;\n                int flags;\n                flags = *pc++;\n                method = JS_GetProperty(ctx, sp[-4], (flags & 1) ?\n                                        JS_ATOM_throw : JS_ATOM_return);\n                if (JS_IsException(method))\n                    goto exception;\n                if (JS_IsUndefined(method) || JS_IsNull(method)) {\n                    ret_flag = TRUE;\n                } else {\n                    if (flags & 2) {\n                        /* no argument */\n                        ret = JS_CallFree(ctx, method, sp[-4],\n                                          0, NULL);\n                    } else {\n                        ret = JS_CallFree(ctx, method, sp[-4],\n                                          1, (JSValueConst *)(sp - 1));\n                    }\n                    if (JS_IsException(ret))\n                        goto exception;\n                    JS_FreeValue(ctx, sp[-1]);\n                    sp[-1] = ret;\n                    ret_flag = FALSE;\n                }\n                sp[0] = JS_NewBool(ctx, ret_flag);\n                sp += 1;\n            }\n            BREAK;\n\n        CASE(OP_lnot):\n            {\n                int res;\n                JSValue op1;\n\n                op1 = sp[-1];\n                if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) {\n                    res = JS_VALUE_GET_INT(op1) != 0;\n                } else {\n                    res = JS_ToBoolFree(ctx, op1);\n                }\n                sp[-1] = JS_NewBool(ctx, !res);\n            }\n            BREAK;\n\n        CASE(OP_get_field):\n            {\n                JSValue val;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                val = JS_GetProperty(ctx, sp[-1], atom);\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = val;\n            }\n            BREAK;\n\n        CASE(OP_get_field2):\n            {\n                JSValue val;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                val = JS_GetProperty(ctx, sp[-1], atom);\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n                *sp++ = val;\n            }\n            BREAK;\n\n        CASE(OP_put_field):\n            {\n                int ret;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                ret = JS_SetPropertyInternal(ctx, sp[-2], atom, sp[-1],\n                                             JS_PROP_THROW_STRICT);\n                JS_FreeValue(ctx, sp[-2]);\n                sp -= 2;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_private_symbol):\n            {\n                JSAtom atom;\n                JSValue val;\n                \n                atom = get_u32(pc);\n                pc += 4;\n                val = JS_NewSymbolFromAtom(ctx, atom, JS_ATOM_TYPE_PRIVATE);\n                if (JS_IsException(val))\n                    goto exception;\n                *sp++ = val;\n            }\n            BREAK;\n            \n        CASE(OP_get_private_field):\n            {\n                JSValue val;\n\n                val = JS_GetPrivateField(ctx, sp[-2], sp[-1]);\n                JS_FreeValue(ctx, sp[-1]);\n                JS_FreeValue(ctx, sp[-2]);\n                sp[-2] = val;\n                sp--;\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_put_private_field):\n            {\n                int ret;\n                ret = JS_SetPrivateField(ctx, sp[-3], sp[-1], sp[-2]);\n                JS_FreeValue(ctx, sp[-3]);\n                JS_FreeValue(ctx, sp[-1]);\n                sp -= 3;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_define_private_field):\n            {\n                int ret;\n                ret = JS_DefinePrivateField(ctx, sp[-3], sp[-2], sp[-1]);\n                JS_FreeValue(ctx, sp[-2]);\n                sp -= 2;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_define_field):\n            {\n                int ret;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                ret = JS_DefinePropertyValue(ctx, sp[-2], atom, sp[-1],\n                                             JS_PROP_C_W_E | JS_PROP_THROW);\n                sp--;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_set_name):\n            {\n                int ret;\n                JSAtom atom;\n                atom = get_u32(pc);\n                pc += 4;\n\n                ret = JS_DefineObjectName(ctx, sp[-1], atom, JS_PROP_CONFIGURABLE);\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n        CASE(OP_set_name_computed):\n            {\n                int ret;\n                ret = JS_DefineObjectNameComputed(ctx, sp[-1], sp[-2], JS_PROP_CONFIGURABLE);\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n        CASE(OP_set_proto):\n            {\n                JSValue proto;\n                proto = sp[-1];\n                if (JS_IsObject(proto) || JS_IsNull(proto)) {\n                    if (JS_SetPrototypeInternal(ctx, sp[-2], proto, TRUE) < 0)\n                        goto exception;\n                }\n                JS_FreeValue(ctx, proto);\n                sp--;\n            }\n            BREAK;\n        CASE(OP_set_home_object):\n            js_method_set_home_object(ctx, sp[-1], sp[-2]);\n            BREAK;\n        CASE(OP_define_method):\n        CASE(OP_define_method_computed):\n            {\n                JSValue getter, setter, value;\n                JSValueConst obj;\n                JSAtom atom;\n                int flags, ret, op_flags;\n                BOOL is_computed;\n#define OP_DEFINE_METHOD_METHOD 0\n#define OP_DEFINE_METHOD_GETTER 1\n#define OP_DEFINE_METHOD_SETTER 2\n#define OP_DEFINE_METHOD_ENUMERABLE 4\n\n                is_computed = (opcode == OP_define_method_computed);\n                if (is_computed) {\n                    atom = JS_ValueToAtom(ctx, sp[-2]);\n                    if (unlikely(atom == JS_ATOM_NULL))\n                        goto exception;\n                    opcode += OP_define_method - OP_define_method_computed;\n                } else {\n                    atom = get_u32(pc);\n                    pc += 4;\n                }\n                op_flags = *pc++;\n\n                obj = sp[-2 - is_computed];\n                flags = JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE |\n                    JS_PROP_HAS_ENUMERABLE | JS_PROP_THROW;\n                if (op_flags & OP_DEFINE_METHOD_ENUMERABLE)\n                    flags |= JS_PROP_ENUMERABLE;\n                op_flags &= 3;\n                value = JS_UNDEFINED;\n                getter = JS_UNDEFINED;\n                setter = JS_UNDEFINED;\n                if (op_flags == OP_DEFINE_METHOD_METHOD) {\n                    value = sp[-1];\n                    flags |= JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE;\n                } else if (op_flags == OP_DEFINE_METHOD_GETTER) {\n                    getter = sp[-1];\n                    flags |= JS_PROP_HAS_GET;\n                } else {\n                    setter = sp[-1];\n                    flags |= JS_PROP_HAS_SET;\n                }\n                ret = js_method_set_properties(ctx, sp[-1], atom, flags, obj);\n                if (ret >= 0) {\n                    ret = JS_DefineProperty(ctx, obj, atom, value,\n                                            getter, setter, flags);\n                }\n                JS_FreeValue(ctx, sp[-1]);\n                if (is_computed) {\n                    JS_FreeAtom(ctx, atom);\n                    JS_FreeValue(ctx, sp[-2]);\n                }\n                sp -= 1 + is_computed;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_define_class):\n        CASE(OP_define_class_computed):\n            {\n                int class_flags;\n                JSAtom atom;\n                \n                atom = get_u32(pc);\n                class_flags = pc[4];\n                pc += 5;\n                if (js_op_define_class(ctx, sp, atom, class_flags,\n                                       var_refs, sf,\n                                       (opcode == OP_define_class_computed)) < 0)\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_get_array_el):\n            {\n                JSValue val;\n\n                val = JS_GetPropertyValue(ctx, sp[-2], sp[-1]);\n                JS_FreeValue(ctx, sp[-2]);\n                sp[-2] = val;\n                sp--;\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_get_array_el2):\n            {\n                JSValue val;\n\n                val = JS_GetPropertyValue(ctx, sp[-2], sp[-1]);\n                sp[-1] = val;\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_get_ref_value):\n            {\n                JSValue val;\n                if (unlikely(JS_IsUndefined(sp[-2]))) {\n                    JSAtom atom = JS_ValueToAtom(ctx, sp[-1]);\n                    if (atom != JS_ATOM_NULL) {\n                        JS_ThrowReferenceErrorNotDefined(ctx, atom);\n                        JS_FreeAtom(ctx, atom);\n                    }\n                    goto exception;\n                }\n                val = JS_GetPropertyValue(ctx, sp[-2],\n                                          JS_DupValue(ctx, sp[-1]));\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n                sp[0] = val;\n                sp++;\n            }\n            BREAK;\n\n        CASE(OP_get_super_value):\n            {\n                JSValue val;\n                JSAtom atom;\n                atom = JS_ValueToAtom(ctx, sp[-1]);\n                if (unlikely(atom == JS_ATOM_NULL))\n                    goto exception;\n                val = JS_GetPropertyInternal(ctx, sp[-2], atom, sp[-3], FALSE);\n                JS_FreeAtom(ctx, atom);\n                if (unlikely(JS_IsException(val)))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                JS_FreeValue(ctx, sp[-2]);\n                JS_FreeValue(ctx, sp[-3]);\n                sp[-3] = val;\n                sp -= 2;\n            }\n            BREAK;\n\n        CASE(OP_put_array_el):\n            {\n                int ret;\n\n                ret = JS_SetPropertyValue(ctx, sp[-3], sp[-2], sp[-1], JS_PROP_THROW_STRICT);\n                JS_FreeValue(ctx, sp[-3]);\n                sp -= 3;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_put_ref_value):\n            {\n                int ret, flags;\n                flags = JS_PROP_THROW_STRICT;\n                if (unlikely(JS_IsUndefined(sp[-3]))) {\n                    if (is_strict_mode(ctx)) {\n                        JSAtom atom = JS_ValueToAtom(ctx, sp[-2]);\n                        if (atom != JS_ATOM_NULL) {\n                            JS_ThrowReferenceErrorNotDefined(ctx, atom);\n                            JS_FreeAtom(ctx, atom);\n                        }\n                        goto exception;\n                    } else {\n                        sp[-3] = JS_DupValue(ctx, ctx->global_obj);\n                    }\n                } else {\n                    if (is_strict_mode(ctx))\n                        flags |= JS_PROP_NO_ADD;\n                }\n                ret = JS_SetPropertyValue(ctx, sp[-3], sp[-2], sp[-1], flags);\n                JS_FreeValue(ctx, sp[-3]);\n                sp -= 3;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_put_super_value):\n            {\n                int ret;\n                JSAtom atom;\n                if (JS_VALUE_GET_TAG(sp[-3]) != JS_TAG_OBJECT) {\n                    JS_ThrowTypeErrorNotAnObject(ctx);\n                    goto exception;\n                }\n                atom = JS_ValueToAtom(ctx, sp[-2]);\n                if (unlikely(atom == JS_ATOM_NULL))\n                    goto exception;\n                ret = JS_SetPropertyGeneric(ctx, sp[-3], atom, sp[-1], sp[-4],\n                                            JS_PROP_THROW_STRICT);\n                JS_FreeAtom(ctx, atom);\n                JS_FreeValue(ctx, sp[-4]);\n                JS_FreeValue(ctx, sp[-3]);\n                JS_FreeValue(ctx, sp[-2]);\n                sp -= 4;\n                if (ret < 0)\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_define_array_el):\n            {\n                int ret;\n                ret = JS_DefinePropertyValueValue(ctx, sp[-3], JS_DupValue(ctx, sp[-2]), sp[-1],\n                                                  JS_PROP_C_W_E | JS_PROP_THROW);\n                sp -= 1;\n                if (unlikely(ret < 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_append):    /* array pos enumobj -- array pos */\n            {\n                if (js_append_enumerate(ctx, sp))\n                    goto exception;\n                JS_FreeValue(ctx, *--sp);\n            }\n            BREAK;\n\n        CASE(OP_copy_data_properties):    /* target source excludeList */\n            {\n                /* stack offsets (-1 based):\n                   2 bits for target,\n                   3 bits for source,\n                   2 bits for exclusionList */\n                int mask;\n\n                mask = *pc++;\n                if (JS_CopyDataProperties(ctx, sp[-1 - (mask & 3)],\n                                          sp[-1 - ((mask >> 2) & 7)],\n                                          sp[-1 - ((mask >> 5) & 7)], 0))\n                    goto exception;\n            }\n            BREAK;\n\n        CASE(OP_add):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    int64_t r;\n                    r = (int64_t)JS_VALUE_GET_INT(op1) + JS_VALUE_GET_INT(op2);\n                    if (unlikely((int)r != r))\n                        goto add_slow;\n                    sp[-2] = JS_NewInt32(ctx, r);\n                    sp--;\n                } else if (JS_VALUE_IS_BOTH_FLOAT(op1, op2)) {\n                    sp[-2] = __JS_NewFloat64(ctx, JS_VALUE_GET_FLOAT64(op1) +\n                                             JS_VALUE_GET_FLOAT64(op2));\n                    sp--;\n                } else {\n                add_slow:\n                    if (js_add_slow(ctx, sp))\n                        goto exception;\n                    sp--;\n                }\n            }\n            BREAK;\n        CASE(OP_add_loc):\n            {\n                JSValue *pv;\n                int idx;\n                idx = *pc;\n                pc += 1;\n\n                pv = &var_buf[idx];\n                if (likely(JS_VALUE_IS_BOTH_INT(*pv, sp[-1]))) {\n                    int64_t r;\n                    r = (int64_t)JS_VALUE_GET_INT(*pv) +\n                        JS_VALUE_GET_INT(sp[-1]);\n                    if (unlikely((int)r != r))\n                        goto add_loc_slow;\n                    *pv = JS_NewInt32(ctx, r);\n                    sp--;\n                } else if (JS_VALUE_GET_TAG(*pv) == JS_TAG_STRING) {\n                    JSValue op1;\n                    op1 = sp[-1];\n                    sp--;\n                    op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE);\n                    if (JS_IsException(op1))\n                        goto exception;\n                    op1 = JS_ConcatString(ctx, JS_DupValue(ctx, *pv), op1);\n                    if (JS_IsException(op1))\n                        goto exception;\n                    set_value(ctx, pv, op1);\n                } else {\n                    JSValue ops[2];\n                add_loc_slow:\n                    /* In case of exception, js_add_slow frees ops[0]\n                       and ops[1], so we must duplicate *pv */\n                    ops[0] = JS_DupValue(ctx, *pv);\n                    ops[1] = sp[-1];\n                    sp--;\n                    if (js_add_slow(ctx, ops + 2))\n                        goto exception;\n                    set_value(ctx, pv, ops[0]);\n                }\n            }\n            BREAK;\n        CASE(OP_sub):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    int64_t r;\n                    r = (int64_t)JS_VALUE_GET_INT(op1) - JS_VALUE_GET_INT(op2);\n                    if (unlikely((int)r != r))\n                        goto binary_arith_slow;\n                    sp[-2] = JS_NewInt32(ctx, r);\n                    sp--;\n                } else if (JS_VALUE_IS_BOTH_FLOAT(op1, op2)) {\n                    sp[-2] = __JS_NewFloat64(ctx, JS_VALUE_GET_FLOAT64(op1) -\n                                             JS_VALUE_GET_FLOAT64(op2));\n                    sp--;\n                } else {\n                    goto binary_arith_slow;\n                }\n            }\n            BREAK;\n        CASE(OP_mul):\n            {\n                JSValue op1, op2;\n                double d;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    int32_t v1, v2;\n                    int64_t r;\n                    v1 = JS_VALUE_GET_INT(op1);\n                    v2 = JS_VALUE_GET_INT(op2);\n                    r = (int64_t)v1 * v2;\n                    if (unlikely((int)r != r)) {\n#ifdef CONFIG_BIGNUM\n                        if (unlikely(sf->js_mode & JS_MODE_MATH) &&\n                            (r < -MAX_SAFE_INTEGER || r > MAX_SAFE_INTEGER))\n                            goto binary_arith_slow;\n#endif\n                        d = (double)r;\n                        goto mul_fp_res;\n                    }\n                    /* need to test zero case for -0 result */\n                    if (unlikely(r == 0 && (v1 | v2) < 0)) {\n                        d = -0.0;\n                        goto mul_fp_res;\n                    }\n                    sp[-2] = JS_NewInt32(ctx, r);\n                    sp--;\n                } else if (JS_VALUE_IS_BOTH_FLOAT(op1, op2)) {\n#ifdef CONFIG_BIGNUM\n                    if (unlikely(sf->js_mode & JS_MODE_MATH))\n                        goto binary_arith_slow;\n#endif\n                    d = JS_VALUE_GET_FLOAT64(op1) * JS_VALUE_GET_FLOAT64(op2);\n                mul_fp_res:\n                    sp[-2] = __JS_NewFloat64(ctx, d);\n                    sp--;\n                } else {\n                    goto binary_arith_slow;\n                }\n            }\n            BREAK;\n        CASE(OP_div):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    int v1, v2;\n                    if (unlikely(sf->js_mode & JS_MODE_MATH))\n                        goto binary_arith_slow;\n                    v1 = JS_VALUE_GET_INT(op1);\n                    v2 = JS_VALUE_GET_INT(op2);\n                    sp[-2] = JS_NewFloat64(ctx, (double)v1 / (double)v2);\n                    sp--;\n                } else {\n                    goto binary_arith_slow;\n                }\n            }\n            BREAK;\n        CASE(OP_mod):\n#ifdef CONFIG_BIGNUM\n        CASE(OP_math_mod):\n#endif\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    int v1, v2, r;\n                    v1 = JS_VALUE_GET_INT(op1);\n                    v2 = JS_VALUE_GET_INT(op2);\n                    /* We must avoid v2 = 0, v1 = INT32_MIN and v2 =\n                       -1 and the cases where the result is -0. */\n                    if (unlikely(v1 < 0 || v2 <= 0))\n                        goto binary_arith_slow;\n                    r = v1 % v2;\n                    sp[-2] = JS_NewInt32(ctx, r);\n                    sp--;\n                } else {\n                    goto binary_arith_slow;\n                }\n            }\n            BREAK;\n        CASE(OP_pow):\n        binary_arith_slow:\n            if (js_binary_arith_slow(ctx, sp, opcode))\n                goto exception;\n            sp--;\n            BREAK;\n\n        CASE(OP_plus):\n            {\n                JSValue op1;\n                uint32_t tag;\n                op1 = sp[-1];\n                tag = JS_VALUE_GET_TAG(op1);\n                if (tag == JS_TAG_INT || JS_TAG_IS_FLOAT64(tag)) {\n                } else {\n                    if (js_unary_arith_slow(ctx, sp, opcode))\n                        goto exception;\n                }\n            }\n            BREAK;\n        CASE(OP_neg):\n            {\n                JSValue op1;\n                uint32_t tag;\n                int val;\n                double d;\n                op1 = sp[-1];\n                tag = JS_VALUE_GET_TAG(op1);\n                if (tag == JS_TAG_INT) {\n                    val = JS_VALUE_GET_INT(op1);\n                    /* Note: -0 cannot be expressed as integer */\n                    if (unlikely(val == 0)) {\n                        d = -0.0;\n                        goto neg_fp_res;\n                    }\n                    if (unlikely(val == INT32_MIN)) {\n                        d = -(double)val;\n                        goto neg_fp_res;\n                    }\n                    sp[-1] = JS_NewInt32(ctx, -val);\n                } else if (JS_TAG_IS_FLOAT64(tag)) {\n                    d = -JS_VALUE_GET_FLOAT64(op1);\n                neg_fp_res:\n                    sp[-1] = __JS_NewFloat64(ctx, d);\n                } else {\n                    if (js_unary_arith_slow(ctx, sp, opcode))\n                        goto exception;\n                }\n            }\n            BREAK;\n        CASE(OP_inc):\n            {\n                JSValue op1;\n                int val;\n                op1 = sp[-1];\n                if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) {\n                    val = JS_VALUE_GET_INT(op1);\n                    if (unlikely(val == INT32_MAX))\n                        goto inc_slow;\n                    sp[-1] = JS_NewInt32(ctx, val + 1);\n                } else {\n                inc_slow:\n                    if (js_unary_arith_slow(ctx, sp, opcode))\n                        goto exception;\n                }\n            }\n            BREAK;\n        CASE(OP_dec):\n            {\n                JSValue op1;\n                int val;\n                op1 = sp[-1];\n                if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) {\n                    val = JS_VALUE_GET_INT(op1);\n                    if (unlikely(val == INT32_MIN))\n                        goto dec_slow;\n                    sp[-1] = JS_NewInt32(ctx, val - 1);\n                } else {\n                dec_slow:\n                    if (js_unary_arith_slow(ctx, sp, opcode))\n                        goto exception;\n                }\n            }\n            BREAK;\n        CASE(OP_post_inc):\n        CASE(OP_post_dec):\n            if (js_post_inc_slow(ctx, sp, opcode))\n                goto exception;\n            sp++;\n            BREAK;\n        CASE(OP_inc_loc):\n            {\n                JSValue op1;\n                int val;\n                int idx;\n                idx = *pc;\n                pc += 1;\n\n                op1 = var_buf[idx];\n                if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) {\n                    val = JS_VALUE_GET_INT(op1);\n                    if (unlikely(val == INT32_MAX))\n                        goto inc_loc_slow;\n                    var_buf[idx] = JS_NewInt32(ctx, val + 1);\n                } else {\n                inc_loc_slow:\n                    /* must duplicate otherwise the variable value may\n                       be destroyed before JS code accesses it */\n                    op1 = JS_DupValue(ctx, op1);\n                    if (js_unary_arith_slow(ctx, &op1 + 1, OP_inc))\n                        goto exception;\n                    set_value(ctx, &var_buf[idx], op1);\n                }\n            }\n            BREAK;\n        CASE(OP_dec_loc):\n            {\n                JSValue op1;\n                int val;\n                int idx;\n                idx = *pc;\n                pc += 1;\n\n                op1 = var_buf[idx];\n                if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) {\n                    val = JS_VALUE_GET_INT(op1);\n                    if (unlikely(val == INT32_MIN))\n                        goto dec_loc_slow;\n                    var_buf[idx] = JS_NewInt32(ctx, val - 1);\n                } else {\n                dec_loc_slow:\n                    /* must duplicate otherwise the variable value may\n                       be destroyed before JS code accesses it */\n                    op1 = JS_DupValue(ctx, op1);\n                    if (js_unary_arith_slow(ctx, &op1 + 1, OP_dec))\n                        goto exception;\n                    set_value(ctx, &var_buf[idx], op1);\n                }\n            }\n            BREAK;\n        CASE(OP_not):\n            {\n                JSValue op1;\n                op1 = sp[-1];\n                if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) {\n                    sp[-1] = JS_NewInt32(ctx, ~JS_VALUE_GET_INT(op1));\n                } else {\n                    if (js_not_slow(ctx, sp))\n                        goto exception;\n                }\n            }\n            BREAK;\n\n        CASE(OP_shl):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    uint32_t v1, v2;\n                    v1 = JS_VALUE_GET_INT(op1);\n                    v2 = JS_VALUE_GET_INT(op2);\n#ifdef CONFIG_BIGNUM\n                    {\n                        int64_t r;\n                        if (unlikely(sf->js_mode & JS_MODE_MATH)) {\n                            if (v2 > 0x1f)\n                                goto shl_slow;\n                            r = (int64_t)v1 << v2;\n                            if ((int)r != r)\n                                goto shl_slow;\n                        } else {\n                            v2 &= 0x1f;\n                        }\n                    }\n#else\n                    v2 &= 0x1f;\n#endif\n                    sp[-2] = JS_NewInt32(ctx, v1 << v2);\n                    sp--;\n                } else {\n#ifdef CONFIG_BIGNUM\n                shl_slow:\n#endif\n                    if (js_binary_logic_slow(ctx, sp, opcode))\n                        goto exception;\n                    sp--;\n                }\n            }\n            BREAK;\n        CASE(OP_shr):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    uint32_t v2;\n                    v2 = JS_VALUE_GET_INT(op2);\n                    /* v1 >>> v2 retains its JS semantics if CONFIG_BIGNUM */\n                    v2 &= 0x1f;\n                    sp[-2] = JS_NewUint32(ctx,\n                                          (uint32_t)JS_VALUE_GET_INT(op1) >>\n                                          v2);\n                    sp--;\n                } else {\n                    if (js_shr_slow(ctx, sp))\n                        goto exception;\n                    sp--;\n                }\n            }\n            BREAK;\n        CASE(OP_sar):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    uint32_t v2;\n                    v2 = JS_VALUE_GET_INT(op2);\n#ifdef CONFIG_BIGNUM\n                    if (unlikely(v2 > 0x1f)) {\n                        if (unlikely(sf->js_mode & JS_MODE_MATH))\n                            goto sar_slow;\n                        else\n                            v2 &= 0x1f;\n                    }\n#else\n                    v2 &= 0x1f;\n#endif\n                    sp[-2] = JS_NewInt32(ctx,\n                                          (int)JS_VALUE_GET_INT(op1) >> v2);\n                    sp--;\n                } else {\n#ifdef CONFIG_BIGNUM\n                sar_slow:\n#endif\n                    if (js_binary_logic_slow(ctx, sp, opcode))\n                        goto exception;\n                    sp--;\n                }\n            }\n            BREAK;\n        CASE(OP_and):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    sp[-2] = JS_NewInt32(ctx,\n                                         JS_VALUE_GET_INT(op1) &\n                                         JS_VALUE_GET_INT(op2));\n                    sp--;\n                } else {\n                    if (js_binary_logic_slow(ctx, sp, opcode))\n                        goto exception;\n                    sp--;\n                }\n            }\n            BREAK;\n        CASE(OP_or):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    sp[-2] = JS_NewInt32(ctx,\n                                         JS_VALUE_GET_INT(op1) |\n                                         JS_VALUE_GET_INT(op2));\n                    sp--;\n                } else {\n                    if (js_binary_logic_slow(ctx, sp, opcode))\n                        goto exception;\n                    sp--;\n                }\n            }\n            BREAK;\n        CASE(OP_xor):\n            {\n                JSValue op1, op2;\n                op1 = sp[-2];\n                op2 = sp[-1];\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {\n                    sp[-2] = JS_NewInt32(ctx,\n                                         JS_VALUE_GET_INT(op1) ^\n                                         JS_VALUE_GET_INT(op2));\n                    sp--;\n                } else {\n                    if (js_binary_logic_slow(ctx, sp, opcode))\n                        goto exception;\n                    sp--;\n                }\n            }\n            BREAK;\n\n\n#define OP_CMP(opcode, binary_op, slow_call)              \\\n            CASE(opcode):                                 \\\n                {                                         \\\n                JSValue op1, op2;                         \\\n                op1 = sp[-2];                             \\\n                op2 = sp[-1];                                   \\\n                if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) {           \\\n                    sp[-2] = JS_NewBool(ctx, JS_VALUE_GET_INT(op1) binary_op JS_VALUE_GET_INT(op2)); \\\n                    sp--;                                               \\\n                } else {                                                \\\n                    if (slow_call)                                      \\\n                        goto exception;                                 \\\n                    sp--;                                               \\\n                }                                                       \\\n                }                                                       \\\n            BREAK\n\n            OP_CMP(OP_lt, <, js_relational_slow(ctx, sp, opcode));\n            OP_CMP(OP_lte, <=, js_relational_slow(ctx, sp, opcode));\n            OP_CMP(OP_gt, >, js_relational_slow(ctx, sp, opcode));\n            OP_CMP(OP_gte, >=, js_relational_slow(ctx, sp, opcode));\n            OP_CMP(OP_eq, ==, js_eq_slow(ctx, sp, 0));\n            OP_CMP(OP_neq, !=, js_eq_slow(ctx, sp, 1));\n            OP_CMP(OP_strict_eq, ==, js_strict_eq_slow(ctx, sp, 0));\n            OP_CMP(OP_strict_neq, !=, js_strict_eq_slow(ctx, sp, 1));\n\n#ifdef CONFIG_BIGNUM\n        CASE(OP_mul_pow10):\n            if (rt->bigfloat_ops.mul_pow10(ctx, sp))\n                goto exception;\n            sp--;\n            BREAK;\n#endif\n        CASE(OP_in):\n            if (js_operator_in(ctx, sp))\n                goto exception;\n            sp--;\n            BREAK;\n        CASE(OP_instanceof):\n            if (js_operator_instanceof(ctx, sp))\n                goto exception;\n            sp--;\n            BREAK;\n        CASE(OP_typeof):\n            {\n                JSValue op1;\n                JSAtom atom;\n\n                op1 = sp[-1];\n                atom = js_operator_typeof(ctx, op1);\n                JS_FreeValue(ctx, op1);\n                sp[-1] = JS_AtomToString(ctx, atom);\n            }\n            BREAK;\n        CASE(OP_delete):\n            if (js_operator_delete(ctx, sp))\n                goto exception;\n            sp--;\n            BREAK;\n        CASE(OP_delete_var):\n            {\n                JSAtom atom;\n                int ret;\n\n                atom = get_u32(pc);\n                pc += 4;\n\n                ret = JS_DeleteProperty(ctx, ctx->global_obj, atom, 0);\n                if (unlikely(ret < 0))\n                    goto exception;\n                *sp++ = JS_NewBool(ctx, ret);\n            }\n            BREAK;\n\n        CASE(OP_to_object):\n            if (JS_VALUE_GET_TAG(sp[-1]) != JS_TAG_OBJECT) {\n                ret_val = JS_ToObject(ctx, sp[-1]);\n                if (JS_IsException(ret_val))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = ret_val;\n            }\n            BREAK;\n\n        CASE(OP_to_propkey):\n            switch (JS_VALUE_GET_TAG(sp[-1])) {\n            case JS_TAG_INT:\n            case JS_TAG_STRING:\n            case JS_TAG_SYMBOL:\n                break;\n            default:\n                ret_val = JS_ToPropertyKey(ctx, sp[-1]);\n                if (JS_IsException(ret_val))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = ret_val;\n                break;\n            }\n            BREAK;\n\n        CASE(OP_to_propkey2):\n            /* must be tested first */\n            if (unlikely(JS_IsUndefined(sp[-2]) || JS_IsNull(sp[-2]))) {\n                JS_ThrowTypeError(ctx, \"value has no property\");\n                goto exception;\n            }\n            switch (JS_VALUE_GET_TAG(sp[-1])) {\n            case JS_TAG_INT:\n            case JS_TAG_STRING:\n            case JS_TAG_SYMBOL:\n                break;\n            default:\n                ret_val = JS_ToPropertyKey(ctx, sp[-1]);\n                if (JS_IsException(ret_val))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = ret_val;\n                break;\n            }\n            BREAK;\n#if 0\n        CASE(OP_to_string):\n            if (JS_VALUE_GET_TAG(sp[-1]) != JS_TAG_STRING) {\n                ret_val = JS_ToString(ctx, sp[-1]);\n                if (JS_IsException(ret_val))\n                    goto exception;\n                JS_FreeValue(ctx, sp[-1]);\n                sp[-1] = ret_val;\n            }\n            BREAK;\n#endif\n        CASE(OP_with_get_var):\n        CASE(OP_with_put_var):\n        CASE(OP_with_delete_var):\n        CASE(OP_with_make_ref):\n        CASE(OP_with_get_ref):\n        CASE(OP_with_get_ref_undef):\n            {\n                JSAtom atom;\n                int32_t diff;\n                JSValue obj, val;\n                int ret, is_with;\n                atom = get_u32(pc);\n                diff = get_u32(pc + 4);\n                is_with = pc[8];\n                pc += 9;\n\n                obj = sp[-1];\n                ret = JS_HasProperty(ctx, obj, atom);\n                if (unlikely(ret < 0))\n                    goto exception;\n                if (ret) {\n                    if (is_with) {\n                        ret = js_has_unscopable(ctx, obj, atom);\n                        if (unlikely(ret < 0))\n                            goto exception;\n                        if (ret)\n                            goto no_with;\n                    }\n                    switch (opcode) {\n                    case OP_with_get_var:\n                        val = JS_GetProperty(ctx, obj, atom);\n                        if (unlikely(JS_IsException(val)))\n                            goto exception;\n                        set_value(ctx, &sp[-1], val);\n                        break;\n                    case OP_with_put_var:\n                        /* XXX: check if strict mode */\n                        ret = JS_SetPropertyInternal(ctx, obj, atom, sp[-2],\n                                                     JS_PROP_THROW_STRICT);\n                        JS_FreeValue(ctx, sp[-1]);\n                        sp -= 2;\n                        if (unlikely(ret < 0))\n                            goto exception;\n                        break;\n                    case OP_with_delete_var:\n                        ret = JS_DeleteProperty(ctx, obj, atom, 0);\n                        if (unlikely(ret < 0))\n                            goto exception;\n                        JS_FreeValue(ctx, sp[-1]);\n                        sp[-1] = JS_NewBool(ctx, ret);\n                        break;\n                    case OP_with_make_ref:\n                        /* produce a pair object/propname on the stack */\n                        *sp++ = JS_AtomToValue(ctx, atom);\n                        break;\n                    case OP_with_get_ref:\n                        /* produce a pair object/method on the stack */\n                        val = JS_GetProperty(ctx, obj, atom);\n                        if (unlikely(JS_IsException(val)))\n                            goto exception;\n                        *sp++ = val;\n                        break;\n                    case OP_with_get_ref_undef:\n                        /* produce a pair undefined/function on the stack */\n                        val = JS_GetProperty(ctx, obj, atom);\n                        if (unlikely(JS_IsException(val)))\n                            goto exception;\n                        JS_FreeValue(ctx, sp[-1]);\n                        sp[-1] = JS_UNDEFINED;\n                        *sp++ = val;\n                        break;\n                    }\n                    pc += diff - 5;\n                } else {\n                no_with:\n                    /* if not jumping, drop the object argument */\n                    JS_FreeValue(ctx, sp[-1]);\n                    sp--;\n                }\n            }\n            BREAK;\n\n        CASE(OP_await):\n            ret_val = JS_NewInt32(ctx, FUNC_RET_AWAIT);\n            goto done_generator;\n        CASE(OP_yield):\n            ret_val = JS_NewInt32(ctx, FUNC_RET_YIELD);\n            goto done_generator;\n        CASE(OP_yield_star):\n        CASE(OP_async_yield_star):\n            ret_val = JS_NewInt32(ctx, FUNC_RET_YIELD_STAR);\n            goto done_generator;\n        CASE(OP_return_async):\n        CASE(OP_initial_yield):\n            ret_val = JS_UNDEFINED;\n            goto done_generator;\n\n        CASE(OP_nop):\n            BREAK;\n        CASE(OP_is_undefined_or_null):\n            if (JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_UNDEFINED ||\n                JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_NULL) {\n                goto set_true;\n            } else {\n                goto free_and_set_false;\n            }\n#if SHORT_OPCODES\n        CASE(OP_is_undefined):\n            if (JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_UNDEFINED) {\n                goto set_true;\n            } else {\n                goto free_and_set_false;\n            }\n        CASE(OP_is_null):\n            if (JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_NULL) {\n                goto set_true;\n            } else {\n                goto free_and_set_false;\n            }\n            /* XXX: could merge to a single opcode */\n        CASE(OP_typeof_is_undefined):\n            /* different from OP_is_undefined because of isHTMLDDA */\n            if (js_operator_typeof(ctx, sp[-1]) == JS_ATOM_undefined) {\n                goto free_and_set_true;\n            } else {\n                goto free_and_set_false;\n            }\n        CASE(OP_typeof_is_function):\n            if (js_operator_typeof(ctx, sp[-1]) == JS_ATOM_function) {\n                goto free_and_set_true;\n            } else {\n                goto free_and_set_false;\n            }\n        free_and_set_true:\n            JS_FreeValue(ctx, sp[-1]);\n#endif\n        set_true:\n            sp[-1] = JS_TRUE;\n            BREAK;\n        free_and_set_false:\n            JS_FreeValue(ctx, sp[-1]);\n            sp[-1] = JS_FALSE;\n            BREAK;\n        CASE(OP_invalid):\n        DEFAULT:\n            JS_ThrowInternalError(ctx, \"invalid opcode: pc=%u opcode=0x%02x\",\n                                  (int)(pc - b->byte_code_buf - 1), opcode);\n            goto exception;\n        }\n    }\n exception:\n    if (is_backtrace_needed(ctx, rt->current_exception)) {\n        /* add the backtrace information now (it is not done\n           before if the exception happens in a bytecode\n           operation */\n        sf->cur_pc = pc;\n        build_backtrace(ctx, rt->current_exception, NULL, 0, 0);\n    }\n    if (!JS_IsUncatchableError(ctx, rt->current_exception)) {\n        while (sp > stack_buf) {\n            JSValue val = *--sp;\n            JS_FreeValue(ctx, val);\n            if (JS_VALUE_GET_TAG(val) == JS_TAG_CATCH_OFFSET) {\n                int pos = JS_VALUE_GET_INT(val);\n                if (pos == 0) {\n                    /* enumerator: close it with a throw */\n                    JS_FreeValue(ctx, sp[-1]); /* drop the next method */\n                    sp--;\n                    JS_IteratorClose(ctx, sp[-1], TRUE);\n                } else {\n                    *sp++ = rt->current_exception;\n                    rt->current_exception = JS_NULL;\n                    pc = b->byte_code_buf + pos;\n                    goto restart;\n                }\n            }\n        }\n    }\n    ret_val = JS_EXCEPTION;\n    /* the local variables are freed by the caller in the generator\n       case. Hence the label 'done' should never be reached in a\n       generator function. */\n    if (b->func_kind != JS_FUNC_NORMAL) {\n    done_generator:\n        sf->cur_pc = pc;\n        sf->cur_sp = sp;\n    } else {\n    done:\n        if (unlikely(!list_empty(&sf->var_ref_list))) {\n            /* variable references reference the stack: must close them */\n            close_var_refs(rt, sf);\n        }\n        /* free the local variables and stack */\n        for(pval = local_buf; pval < sp; pval++) {\n            JS_FreeValue(ctx, *pval);\n        }\n    }\n    rt->current_stack_frame = sf->prev_frame;\n    return ret_val;\n}\n\nJSValue JS_Call(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj,\n                int argc, JSValueConst *argv)\n{\n    return JS_CallInternal(ctx, func_obj, this_obj, JS_UNDEFINED,\n                           argc, (JSValue *)argv, JS_CALL_FLAG_COPY_ARGV);\n}\n\nstatic JSValue JS_CallFree(JSContext *ctx, JSValue func_obj, JSValueConst this_obj,\n                           int argc, JSValueConst *argv)\n{\n    JSValue res = JS_CallInternal(ctx, func_obj, this_obj, JS_UNDEFINED,\n                                  argc, (JSValue *)argv, JS_CALL_FLAG_COPY_ARGV);\n    JS_FreeValue(ctx, func_obj);\n    return res;\n}\n\n/* warning: the refcount of the context is not incremented. Return\n   NULL in case of exception (case of revoked proxy only) */\nstatic JSContext *JS_GetFunctionRealm(JSContext *ctx, JSValueConst func_obj)\n{\n    JSObject *p;\n    JSContext *realm;\n    \n    if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT)\n        return ctx;\n    p = JS_VALUE_GET_OBJ(func_obj);\n    switch(p->class_id) {\n    case JS_CLASS_C_FUNCTION:\n        realm = p->u.cfunc.realm;\n        break;\n    case JS_CLASS_BYTECODE_FUNCTION:\n    case JS_CLASS_GENERATOR_FUNCTION:\n    case JS_CLASS_ASYNC_FUNCTION:\n    case JS_CLASS_ASYNC_GENERATOR_FUNCTION:\n        {\n            JSFunctionBytecode *b;\n            b = p->u.func.function_bytecode;\n            realm = b->realm;\n        }\n        break;\n    case JS_CLASS_PROXY:\n        {\n            JSProxyData *s = p->u.opaque;\n            if (!s)\n                return ctx;\n            if (s->is_revoked) {\n                JS_ThrowTypeErrorRevokedProxy(ctx);\n                return NULL;\n            } else {\n                realm = JS_GetFunctionRealm(ctx, s->target);\n            }\n        }\n        break;\n    case JS_CLASS_BOUND_FUNCTION:\n        {\n            JSBoundFunction *bf = p->u.bound_function;\n            realm = JS_GetFunctionRealm(ctx, bf->func_obj);\n        }\n        break;\n    default:\n        realm = ctx;\n        break;\n    }\n    return realm;\n}\n\nstatic JSValue js_create_from_ctor(JSContext *ctx, JSValueConst ctor,\n                                   int class_id)\n{\n    JSValue proto, obj;\n    JSContext *realm;\n    \n    if (JS_IsUndefined(ctor)) {\n        proto = JS_DupValue(ctx, ctx->class_proto[class_id]);\n    } else {\n        proto = JS_GetProperty(ctx, ctor, JS_ATOM_prototype);\n        if (JS_IsException(proto))\n            return proto;\n        if (!JS_IsObject(proto)) {\n            JS_FreeValue(ctx, proto);\n            realm = JS_GetFunctionRealm(ctx, ctor);\n            if (!realm)\n                return JS_EXCEPTION;\n            proto = JS_DupValue(ctx, realm->class_proto[class_id]);\n        }\n    }\n    obj = JS_NewObjectProtoClass(ctx, proto, class_id);\n    JS_FreeValue(ctx, proto);\n    return obj;\n}\n\n/* argv[] is modified if (flags & JS_CALL_FLAG_COPY_ARGV) = 0. */\nstatic JSValue JS_CallConstructorInternal(JSContext *ctx,\n                                          JSValueConst func_obj,\n                                          JSValueConst new_target,\n                                          int argc, JSValue *argv, int flags)\n{\n    JSObject *p;\n    JSFunctionBytecode *b;\n\n    if (js_poll_interrupts(ctx))\n        return JS_EXCEPTION;\n    flags |= JS_CALL_FLAG_CONSTRUCTOR;\n    if (unlikely(JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT))\n        goto not_a_function;\n    p = JS_VALUE_GET_OBJ(func_obj);\n    if (unlikely(!p->is_constructor))\n        return JS_ThrowTypeError(ctx, \"not a constructor\");\n    if (unlikely(p->class_id != JS_CLASS_BYTECODE_FUNCTION)) {\n        JSClassCall *call_func;\n        call_func = ctx->rt->class_array[p->class_id].call;\n        if (!call_func) {\n        not_a_function:\n            return JS_ThrowTypeError(ctx, \"not a function\");\n        }\n        return call_func(ctx, func_obj, new_target, argc,\n                         (JSValueConst *)argv, flags);\n    }\n\n    b = p->u.func.function_bytecode;\n    if (b->is_derived_class_constructor) {\n        return JS_CallInternal(ctx, func_obj, JS_UNDEFINED, new_target, argc, argv, flags);\n    } else {\n        JSValue obj, ret;\n        /* legacy constructor behavior */\n        obj = js_create_from_ctor(ctx, new_target, JS_CLASS_OBJECT);\n        if (JS_IsException(obj))\n            return JS_EXCEPTION;\n        ret = JS_CallInternal(ctx, func_obj, obj, new_target, argc, argv, flags);\n        if (JS_VALUE_GET_TAG(ret) == JS_TAG_OBJECT ||\n            JS_IsException(ret)) {\n            JS_FreeValue(ctx, obj);\n            return ret;\n        } else {\n            JS_FreeValue(ctx, ret);\n            return obj;\n        }\n    }\n}\n\nJSValue JS_CallConstructor2(JSContext *ctx, JSValueConst func_obj,\n                            JSValueConst new_target,\n                            int argc, JSValueConst *argv)\n{\n    return JS_CallConstructorInternal(ctx, func_obj, new_target,\n                                      argc, (JSValue *)argv,\n                                      JS_CALL_FLAG_COPY_ARGV);\n}\n\nJSValue JS_CallConstructor(JSContext *ctx, JSValueConst func_obj,\n                           int argc, JSValueConst *argv)\n{\n    return JS_CallConstructorInternal(ctx, func_obj, func_obj,\n                                      argc, (JSValue *)argv,\n                                      JS_CALL_FLAG_COPY_ARGV);\n}\n\nJSValue JS_Invoke(JSContext *ctx, JSValueConst this_val, JSAtom atom,\n                  int argc, JSValueConst *argv)\n{\n    JSValue func_obj;\n    func_obj = JS_GetProperty(ctx, this_val, atom);\n    if (JS_IsException(func_obj))\n        return func_obj;\n    return JS_CallFree(ctx, func_obj, this_val, argc, argv);\n}\n\nstatic JSValue JS_InvokeFree(JSContext *ctx, JSValue this_val, JSAtom atom,\n                             int argc, JSValueConst *argv)\n{\n    JSValue res = JS_Invoke(ctx, this_val, atom, argc, argv);\n    JS_FreeValue(ctx, this_val);\n    return res;\n}\n\n/* JSAsyncFunctionState (used by generator and async functions) */\nstatic __exception int async_func_init(JSContext *ctx, JSAsyncFunctionState *s,\n                                       JSValueConst func_obj, JSValueConst this_obj,\n                                       int argc, JSValueConst *argv)\n{\n    JSObject *p;\n    JSFunctionBytecode *b;\n    JSStackFrame *sf;\n    int local_count, i, arg_buf_len, n;\n\n    sf = &s->frame;\n    init_list_head(&sf->var_ref_list);\n    p = JS_VALUE_GET_OBJ(func_obj);\n    b = p->u.func.function_bytecode;\n    sf->js_mode = b->js_mode;\n    sf->cur_pc = b->byte_code_buf;\n    arg_buf_len = max_int(b->arg_count, argc);\n    local_count = arg_buf_len + b->var_count + b->stack_size;\n    sf->arg_buf = js_malloc(ctx, sizeof(JSValue) * max_int(local_count, 1));\n    if (!sf->arg_buf)\n        return -1;\n    sf->cur_func = JS_DupValue(ctx, func_obj);\n    s->this_val = JS_DupValue(ctx, this_obj);\n    s->argc = argc;\n    sf->arg_count = arg_buf_len;\n    sf->var_buf = sf->arg_buf + arg_buf_len;\n    sf->cur_sp = sf->var_buf + b->var_count;\n    for(i = 0; i < argc; i++)\n        sf->arg_buf[i] = JS_DupValue(ctx, argv[i]);\n    n = arg_buf_len + b->var_count;\n    for(i = argc; i < n; i++)\n        sf->arg_buf[i] = JS_UNDEFINED;\n    return 0;\n}\n\nstatic void async_func_mark(JSRuntime *rt, JSAsyncFunctionState *s,\n                            JS_MarkFunc *mark_func)\n{\n    JSStackFrame *sf;\n    JSValue *sp;\n\n    sf = &s->frame;\n    JS_MarkValue(rt, sf->cur_func, mark_func);\n    JS_MarkValue(rt, s->this_val, mark_func);\n    if (sf->cur_sp) {\n        /* if the function is running, cur_sp is not known so we\n           cannot mark the stack. Marking the variables is not needed\n           because a running function cannot be part of a removable\n           cycle */\n        for(sp = sf->arg_buf; sp < sf->cur_sp; sp++)\n            JS_MarkValue(rt, *sp, mark_func);\n    }\n}\n\nstatic void async_func_free(JSRuntime *rt, JSAsyncFunctionState *s)\n{\n    JSStackFrame *sf;\n    JSValue *sp;\n\n    sf = &s->frame;\n\n    /* close the closure variables. */\n    close_var_refs(rt, sf);\n    \n    if (sf->arg_buf) {\n        /* cannot free the function if it is running */\n        assert(sf->cur_sp != NULL);\n        for(sp = sf->arg_buf; sp < sf->cur_sp; sp++) {\n            JS_FreeValueRT(rt, *sp);\n        }\n        js_free_rt(rt, sf->arg_buf);\n    }\n    JS_FreeValueRT(rt, sf->cur_func);\n    JS_FreeValueRT(rt, s->this_val);\n}\n\nstatic JSValue async_func_resume(JSContext *ctx, JSAsyncFunctionState *s)\n{\n    JSValue func_obj;\n\n    if (js_check_stack_overflow(ctx->rt, 0))\n        return JS_ThrowStackOverflow(ctx);\n\n    /* the tag does not matter provided it is not an object */\n    func_obj = JS_MKPTR(JS_TAG_INT, s);\n    return JS_CallInternal(ctx, func_obj, s->this_val, JS_UNDEFINED,\n                           s->argc, s->frame.arg_buf, JS_CALL_FLAG_GENERATOR);\n}\n\n\n/* Generators */\n\ntypedef enum JSGeneratorStateEnum {\n    JS_GENERATOR_STATE_SUSPENDED_START,\n    JS_GENERATOR_STATE_SUSPENDED_YIELD,\n    JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR,\n    JS_GENERATOR_STATE_EXECUTING,\n    JS_GENERATOR_STATE_COMPLETED,\n} JSGeneratorStateEnum;\n\ntypedef struct JSGeneratorData {\n    JSGeneratorStateEnum state;\n    JSAsyncFunctionState func_state;\n} JSGeneratorData;\n\nstatic void free_generator_stack_rt(JSRuntime *rt, JSGeneratorData *s)\n{\n    if (s->state == JS_GENERATOR_STATE_COMPLETED)\n        return;\n    async_func_free(rt, &s->func_state);\n    s->state = JS_GENERATOR_STATE_COMPLETED;\n}\n\nstatic void js_generator_finalizer(JSRuntime *rt, JSValue obj)\n{\n    JSGeneratorData *s = JS_GetOpaque(obj, JS_CLASS_GENERATOR);\n\n    if (s) {\n        free_generator_stack_rt(rt, s);\n        js_free_rt(rt, s);\n    }\n}\n\nstatic void free_generator_stack(JSContext *ctx, JSGeneratorData *s)\n{\n    free_generator_stack_rt(ctx->rt, s);\n}\n\nstatic void js_generator_mark(JSRuntime *rt, JSValueConst val,\n                              JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSGeneratorData *s = p->u.generator_data;\n\n    if (!s || s->state == JS_GENERATOR_STATE_COMPLETED)\n        return;\n    async_func_mark(rt, &s->func_state, mark_func);\n}\n\n/* XXX: use enum */\n#define GEN_MAGIC_NEXT   0\n#define GEN_MAGIC_RETURN 1\n#define GEN_MAGIC_THROW  2\n\nstatic JSValue js_generator_next(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv,\n                                 BOOL *pdone, int magic)\n{\n    JSGeneratorData *s = JS_GetOpaque(this_val, JS_CLASS_GENERATOR);\n    JSStackFrame *sf;\n    JSValue ret, func_ret;\n\n    *pdone = TRUE;\n    if (!s)\n        return JS_ThrowTypeError(ctx, \"not a generator\");\n    sf = &s->func_state.frame;\n    switch(s->state) {\n    default:\n    case JS_GENERATOR_STATE_SUSPENDED_START:\n        if (magic == GEN_MAGIC_NEXT) {\n            goto exec_no_arg;\n        } else {\n            free_generator_stack(ctx, s);\n            goto done;\n        }\n        break;\n    case JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR:\n    case JS_GENERATOR_STATE_SUSPENDED_YIELD:\n        /* cur_sp[-1] was set to JS_UNDEFINED in the previous call */\n        ret = JS_DupValue(ctx, argv[0]);\n        if (magic == GEN_MAGIC_THROW &&\n            s->state == JS_GENERATOR_STATE_SUSPENDED_YIELD) {\n            JS_Throw(ctx, ret);\n            s->func_state.throw_flag = TRUE;\n        } else {\n            sf->cur_sp[-1] = ret;\n            sf->cur_sp[0] = JS_NewInt32(ctx, magic);\n            sf->cur_sp++;\n        exec_no_arg:\n            s->func_state.throw_flag = FALSE;\n        }\n        s->state = JS_GENERATOR_STATE_EXECUTING;\n        func_ret = async_func_resume(ctx, &s->func_state);\n        s->state = JS_GENERATOR_STATE_SUSPENDED_YIELD;\n        if (JS_IsException(func_ret)) {\n            /* finalize the execution in case of exception */\n            free_generator_stack(ctx, s);\n            return func_ret;\n        }\n        if (JS_VALUE_GET_TAG(func_ret) == JS_TAG_INT) {\n            /* get the returned yield value at the top of the stack */\n            ret = sf->cur_sp[-1];\n            sf->cur_sp[-1] = JS_UNDEFINED;\n            if (JS_VALUE_GET_INT(func_ret) == FUNC_RET_YIELD_STAR) {\n                s->state = JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR;\n                /* return (value, done) object */\n                *pdone = 2;\n            } else {\n                *pdone = FALSE;\n            }\n        } else {\n            /* end of iterator */\n            ret = sf->cur_sp[-1];\n            sf->cur_sp[-1] = JS_UNDEFINED;\n            JS_FreeValue(ctx, func_ret);\n            free_generator_stack(ctx, s);\n        }\n        break;\n    case JS_GENERATOR_STATE_COMPLETED:\n    done:\n        /* execution is finished */\n        switch(magic) {\n        default:\n        case GEN_MAGIC_NEXT:\n            ret = JS_UNDEFINED;\n            break;\n        case GEN_MAGIC_RETURN:\n            ret = JS_DupValue(ctx, argv[0]);\n            break;\n        case GEN_MAGIC_THROW:\n            ret = JS_Throw(ctx, JS_DupValue(ctx, argv[0]));\n            break;\n        }\n        break;\n    case JS_GENERATOR_STATE_EXECUTING:\n        ret = JS_ThrowTypeError(ctx, \"cannot invoke a running generator\");\n        break;\n    }\n    return ret;\n}\n\nstatic JSValue js_generator_function_call(JSContext *ctx, JSValueConst func_obj,\n                                          JSValueConst this_obj,\n                                          int argc, JSValueConst *argv,\n                                          int flags)\n{\n    JSValue obj, func_ret;\n    JSGeneratorData *s;\n\n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s)\n        return JS_EXCEPTION;\n    s->state = JS_GENERATOR_STATE_SUSPENDED_START;\n    if (async_func_init(ctx, &s->func_state, func_obj, this_obj, argc, argv)) {\n        s->state = JS_GENERATOR_STATE_COMPLETED;\n        goto fail;\n    }\n\n    /* execute the function up to 'OP_initial_yield' */\n    func_ret = async_func_resume(ctx, &s->func_state);\n    if (JS_IsException(func_ret))\n        goto fail;\n    JS_FreeValue(ctx, func_ret);\n\n    obj = js_create_from_ctor(ctx, func_obj, JS_CLASS_GENERATOR);\n    if (JS_IsException(obj))\n        goto fail;\n    JS_SetOpaque(obj, s);\n    return obj;\n fail:\n    free_generator_stack_rt(ctx->rt, s);\n    js_free(ctx, s);\n    return JS_EXCEPTION;\n}\n\n/* AsyncFunction */\n\nstatic void js_async_function_terminate(JSRuntime *rt, JSAsyncFunctionData *s)\n{\n    if (s->is_active) {\n        async_func_free(rt, &s->func_state);\n        s->is_active = FALSE;\n    }\n}\n\nstatic void js_async_function_free0(JSRuntime *rt, JSAsyncFunctionData *s)\n{\n    js_async_function_terminate(rt, s);\n    JS_FreeValueRT(rt, s->resolving_funcs[0]);\n    JS_FreeValueRT(rt, s->resolving_funcs[1]);\n    remove_gc_object(&s->header);\n    js_free_rt(rt, s);\n}\n\nstatic void js_async_function_free(JSRuntime *rt, JSAsyncFunctionData *s)\n{\n    if (--s->header.ref_count == 0) {\n        js_async_function_free0(rt, s);\n    }\n}\n\nstatic void js_async_function_resolve_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSAsyncFunctionData *s = p->u.async_function_data;\n    if (s) {\n        js_async_function_free(rt, s);\n    }\n}\n\nstatic void js_async_function_resolve_mark(JSRuntime *rt, JSValueConst val,\n                                           JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSAsyncFunctionData *s = p->u.async_function_data;\n    if (s) {\n        mark_func(rt, &s->header);\n    }\n}\n\nstatic int js_async_function_resolve_create(JSContext *ctx,\n                                            JSAsyncFunctionData *s,\n                                            JSValue *resolving_funcs)\n{\n    int i;\n    JSObject *p;\n\n    for(i = 0; i < 2; i++) {\n        resolving_funcs[i] =\n            JS_NewObjectProtoClass(ctx, ctx->function_proto,\n                                   JS_CLASS_ASYNC_FUNCTION_RESOLVE + i);\n        if (JS_IsException(resolving_funcs[i])) {\n            if (i == 1)\n                JS_FreeValue(ctx, resolving_funcs[0]);\n            return -1;\n        }\n        p = JS_VALUE_GET_OBJ(resolving_funcs[i]);\n        s->header.ref_count++;\n        p->u.async_function_data = s;\n    }\n    return 0;\n}\n\nstatic void js_async_function_resume(JSContext *ctx, JSAsyncFunctionData *s)\n{\n    JSValue func_ret, ret2;\n\n    func_ret = async_func_resume(ctx, &s->func_state);\n    if (JS_IsException(func_ret)) {\n        JSValue error;\n    fail:\n        error = JS_GetException(ctx);\n        ret2 = JS_Call(ctx, s->resolving_funcs[1], JS_UNDEFINED,\n                       1, (JSValueConst *)&error);\n        JS_FreeValue(ctx, error);\n        js_async_function_terminate(ctx->rt, s);\n        JS_FreeValue(ctx, ret2); /* XXX: what to do if exception ? */\n    } else {\n        JSValue value;\n        value = s->func_state.frame.cur_sp[-1];\n        s->func_state.frame.cur_sp[-1] = JS_UNDEFINED;\n        if (JS_IsUndefined(func_ret)) {\n            /* function returned */\n            ret2 = JS_Call(ctx, s->resolving_funcs[0], JS_UNDEFINED,\n                           1, (JSValueConst *)&value);\n            JS_FreeValue(ctx, ret2); /* XXX: what to do if exception ? */\n            JS_FreeValue(ctx, value);\n            js_async_function_terminate(ctx->rt, s);\n        } else {\n            JSValue promise, resolving_funcs[2], resolving_funcs1[2];\n            int i, res;\n\n            /* await */\n            JS_FreeValue(ctx, func_ret); /* not used */\n            promise = js_promise_resolve(ctx, ctx->promise_ctor,\n                                         1, (JSValueConst *)&value, 0);\n            JS_FreeValue(ctx, value);\n            if (JS_IsException(promise))\n                goto fail;\n            if (js_async_function_resolve_create(ctx, s, resolving_funcs)) {\n                JS_FreeValue(ctx, promise);\n                goto fail;\n            }\n\n            /* Note: no need to create 'thrownawayCapability' as in\n               the spec */\n            for(i = 0; i < 2; i++)\n                resolving_funcs1[i] = JS_UNDEFINED;\n            res = perform_promise_then(ctx, promise,\n                                       (JSValueConst *)resolving_funcs,\n                                       (JSValueConst *)resolving_funcs1);\n            JS_FreeValue(ctx, promise);\n            for(i = 0; i < 2; i++)\n                JS_FreeValue(ctx, resolving_funcs[i]);\n            if (res)\n                goto fail;\n        }\n    }\n}\n\nstatic JSValue js_async_function_resolve_call(JSContext *ctx,\n                                              JSValueConst func_obj,\n                                              JSValueConst this_obj,\n                                              int argc, JSValueConst *argv,\n                                              int flags)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(func_obj);\n    JSAsyncFunctionData *s = p->u.async_function_data;\n    BOOL is_reject = p->class_id - JS_CLASS_ASYNC_FUNCTION_RESOLVE;\n    JSValueConst arg;\n\n    if (argc > 0)\n        arg = argv[0];\n    else\n        arg = JS_UNDEFINED;\n    s->func_state.throw_flag = is_reject;\n    if (is_reject) {\n        JS_Throw(ctx, JS_DupValue(ctx, arg));\n    } else {\n        /* return value of await */\n        s->func_state.frame.cur_sp[-1] = JS_DupValue(ctx, arg);\n    }\n    js_async_function_resume(ctx, s);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_async_function_call(JSContext *ctx, JSValueConst func_obj,\n                                      JSValueConst this_obj,\n                                      int argc, JSValueConst *argv, int flags)\n{\n    JSValue promise;\n    JSAsyncFunctionData *s;\n\n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s)\n        return JS_EXCEPTION;\n    s->header.ref_count = 1;\n    add_gc_object(ctx->rt, &s->header, JS_GC_OBJ_TYPE_ASYNC_FUNCTION);\n    s->is_active = FALSE;\n    s->resolving_funcs[0] = JS_UNDEFINED;\n    s->resolving_funcs[1] = JS_UNDEFINED;\n\n    promise = JS_NewPromiseCapability(ctx, s->resolving_funcs);\n    if (JS_IsException(promise))\n        goto fail;\n\n    if (async_func_init(ctx, &s->func_state, func_obj, this_obj, argc, argv)) {\n    fail:\n        JS_FreeValue(ctx, promise);\n        js_async_function_free(ctx->rt, s);\n        return JS_EXCEPTION;\n    }\n    s->is_active = TRUE;\n\n    js_async_function_resume(ctx, s);\n\n    js_async_function_free(ctx->rt, s);\n\n    return promise;\n}\n\n/* AsyncGenerator */\n\ntypedef enum JSAsyncGeneratorStateEnum {\n    JS_ASYNC_GENERATOR_STATE_SUSPENDED_START,\n    JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD,\n    JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD_STAR,\n    JS_ASYNC_GENERATOR_STATE_EXECUTING,\n    JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN,\n    JS_ASYNC_GENERATOR_STATE_COMPLETED,\n} JSAsyncGeneratorStateEnum;\n\ntypedef struct JSAsyncGeneratorRequest {\n    struct list_head link;\n    /* completion */\n    int completion_type; /* GEN_MAGIC_x */\n    JSValue result;\n    /* promise capability */\n    JSValue promise;\n    JSValue resolving_funcs[2];\n} JSAsyncGeneratorRequest;\n\ntypedef struct JSAsyncGeneratorData {\n    JSObject *generator; /* back pointer to the object (const) */\n    JSAsyncGeneratorStateEnum state;\n    JSAsyncFunctionState func_state;\n    struct list_head queue; /* list of JSAsyncGeneratorRequest.link */\n} JSAsyncGeneratorData;\n\nstatic void js_async_generator_free(JSRuntime *rt,\n                                    JSAsyncGeneratorData *s)\n{\n    struct list_head *el, *el1;\n    JSAsyncGeneratorRequest *req;\n\n    list_for_each_safe(el, el1, &s->queue) {\n        req = list_entry(el, JSAsyncGeneratorRequest, link);\n        JS_FreeValueRT(rt, req->result);\n        JS_FreeValueRT(rt, req->promise);\n        JS_FreeValueRT(rt, req->resolving_funcs[0]);\n        JS_FreeValueRT(rt, req->resolving_funcs[1]);\n        js_free_rt(rt, req);\n    }\n    if (s->state != JS_ASYNC_GENERATOR_STATE_COMPLETED &&\n        s->state != JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN) {\n        async_func_free(rt, &s->func_state);\n    }\n    js_free_rt(rt, s);\n}\n\nstatic void js_async_generator_finalizer(JSRuntime *rt, JSValue obj)\n{\n    JSAsyncGeneratorData *s = JS_GetOpaque(obj, JS_CLASS_ASYNC_GENERATOR);\n\n    if (s) {\n        js_async_generator_free(rt, s);\n    }\n}\n\nstatic void js_async_generator_mark(JSRuntime *rt, JSValueConst val,\n                                    JS_MarkFunc *mark_func)\n{\n    JSAsyncGeneratorData *s = JS_GetOpaque(val, JS_CLASS_ASYNC_GENERATOR);\n    struct list_head *el;\n    JSAsyncGeneratorRequest *req;\n    if (s) {\n        list_for_each(el, &s->queue) {\n            req = list_entry(el, JSAsyncGeneratorRequest, link);\n            JS_MarkValue(rt, req->result, mark_func);\n            JS_MarkValue(rt, req->promise, mark_func);\n            JS_MarkValue(rt, req->resolving_funcs[0], mark_func);\n            JS_MarkValue(rt, req->resolving_funcs[1], mark_func);\n        }\n        if (s->state != JS_ASYNC_GENERATOR_STATE_COMPLETED &&\n            s->state != JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN) {\n            async_func_mark(rt, &s->func_state, mark_func);\n        }\n    }\n}\n\nstatic JSValue js_async_generator_resolve_function(JSContext *ctx,\n                                          JSValueConst this_obj,\n                                          int argc, JSValueConst *argv,\n                                          int magic, JSValue *func_data);\n\nstatic int js_async_generator_resolve_function_create(JSContext *ctx,\n                                                      JSValueConst generator,\n                                                      JSValue *resolving_funcs,\n                                                      BOOL is_resume_next)\n{\n    int i;\n    JSValue func;\n\n    for(i = 0; i < 2; i++) {\n        func = JS_NewCFunctionData(ctx, js_async_generator_resolve_function, 1,\n                                   i + is_resume_next * 2, 1, &generator);\n        if (JS_IsException(func)) {\n            if (i == 1)\n                JS_FreeValue(ctx, resolving_funcs[0]);\n            return -1;\n        }\n        resolving_funcs[i] = func;\n    }\n    return 0;\n}\n\nstatic int js_async_generator_await(JSContext *ctx,\n                                    JSAsyncGeneratorData *s,\n                                    JSValueConst value)\n{\n    JSValue promise, resolving_funcs[2], resolving_funcs1[2];\n    int i, res;\n\n    promise = js_promise_resolve(ctx, ctx->promise_ctor,\n                                 1, &value, 0);\n    if (JS_IsException(promise))\n        goto fail;\n\n    if (js_async_generator_resolve_function_create(ctx, JS_MKPTR(JS_TAG_OBJECT, s->generator),\n                                                   resolving_funcs, FALSE)) {\n        JS_FreeValue(ctx, promise);\n        goto fail;\n    }\n\n    /* Note: no need to create 'thrownawayCapability' as in\n       the spec */\n    for(i = 0; i < 2; i++)\n        resolving_funcs1[i] = JS_UNDEFINED;\n    res = perform_promise_then(ctx, promise,\n                               (JSValueConst *)resolving_funcs,\n                               (JSValueConst *)resolving_funcs1);\n    JS_FreeValue(ctx, promise);\n    for(i = 0; i < 2; i++)\n        JS_FreeValue(ctx, resolving_funcs[i]);\n    if (res)\n        goto fail;\n    return 0;\n fail:\n    return -1;\n}\n\nstatic void js_async_generator_resolve_or_reject(JSContext *ctx,\n                                                 JSAsyncGeneratorData *s,\n                                                 JSValueConst result,\n                                                 int is_reject)\n{\n    JSAsyncGeneratorRequest *next;\n    JSValue ret;\n\n    next = list_entry(s->queue.next, JSAsyncGeneratorRequest, link);\n    list_del(&next->link);\n    ret = JS_Call(ctx, next->resolving_funcs[is_reject], JS_UNDEFINED, 1,\n                  &result);\n    JS_FreeValue(ctx, ret);\n    JS_FreeValue(ctx, next->result);\n    JS_FreeValue(ctx, next->promise);\n    JS_FreeValue(ctx, next->resolving_funcs[0]);\n    JS_FreeValue(ctx, next->resolving_funcs[1]);\n    js_free(ctx, next);\n}\n\nstatic void js_async_generator_resolve(JSContext *ctx,\n                                       JSAsyncGeneratorData *s,\n                                       JSValueConst value,\n                                       BOOL done)\n{\n    JSValue result;\n    result = js_create_iterator_result(ctx, JS_DupValue(ctx, value), done);\n    /* XXX: better exception handling ? */\n    js_async_generator_resolve_or_reject(ctx, s, result, 0);\n    JS_FreeValue(ctx, result);\n }\n\nstatic void js_async_generator_reject(JSContext *ctx,\n                                       JSAsyncGeneratorData *s,\n                                       JSValueConst exception)\n{\n    js_async_generator_resolve_or_reject(ctx, s, exception, 1);\n}\n\nstatic void js_async_generator_complete(JSContext *ctx,\n                                        JSAsyncGeneratorData *s)\n{\n    if (s->state != JS_ASYNC_GENERATOR_STATE_COMPLETED) {\n        s->state = JS_ASYNC_GENERATOR_STATE_COMPLETED;\n        async_func_free(ctx->rt, &s->func_state);\n    }\n}\n\nstatic int js_async_generator_completed_return(JSContext *ctx,\n                                               JSAsyncGeneratorData *s,\n                                               JSValueConst value)\n{\n    JSValue promise, resolving_funcs[2], resolving_funcs1[2];\n    int res;\n\n    promise = js_promise_resolve(ctx, ctx->promise_ctor,\n                                 1, (JSValueConst *)&value, 0);\n    if (JS_IsException(promise))\n        return -1;\n    if (js_async_generator_resolve_function_create(ctx,\n                                                   JS_MKPTR(JS_TAG_OBJECT, s->generator),\n                                                   resolving_funcs1,\n                                                   TRUE)) {\n        JS_FreeValue(ctx, promise);\n        return -1;\n    }\n    resolving_funcs[0] = JS_UNDEFINED;\n    resolving_funcs[1] = JS_UNDEFINED;\n    res = perform_promise_then(ctx, promise,\n                               (JSValueConst *)resolving_funcs1,\n                               (JSValueConst *)resolving_funcs);\n    JS_FreeValue(ctx, resolving_funcs1[0]);\n    JS_FreeValue(ctx, resolving_funcs1[1]);\n    JS_FreeValue(ctx, promise);\n    return res;\n}\n\nstatic void js_async_generator_resume_next(JSContext *ctx,\n                                           JSAsyncGeneratorData *s)\n{\n    JSAsyncGeneratorRequest *next;\n    JSValue func_ret, value;\n\n    for(;;) {\n        if (list_empty(&s->queue))\n            break;\n        next = list_entry(s->queue.next, JSAsyncGeneratorRequest, link);\n        switch(s->state) {\n        case JS_ASYNC_GENERATOR_STATE_EXECUTING:\n            /* only happens when restarting execution after await() */\n            goto resume_exec;\n        case JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN:\n            goto done;\n        case JS_ASYNC_GENERATOR_STATE_SUSPENDED_START:\n            if (next->completion_type == GEN_MAGIC_NEXT) {\n                goto exec_no_arg;\n            } else {\n                js_async_generator_complete(ctx, s);\n            }\n            break;\n        case JS_ASYNC_GENERATOR_STATE_COMPLETED:\n            if (next->completion_type == GEN_MAGIC_NEXT) {\n                js_async_generator_resolve(ctx, s, JS_UNDEFINED, TRUE);\n            } else if (next->completion_type == GEN_MAGIC_RETURN) {\n                s->state = JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN;\n                js_async_generator_completed_return(ctx, s, next->result);\n                goto done;\n            } else {\n                js_async_generator_reject(ctx, s, next->result);\n            }\n            goto done;\n        case JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD:\n        case JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD_STAR:\n            value = JS_DupValue(ctx, next->result);\n            if (next->completion_type == GEN_MAGIC_THROW &&\n                s->state == JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD) {\n                JS_Throw(ctx, value);\n                s->func_state.throw_flag = TRUE;\n            } else {\n                /* 'yield' returns a value. 'yield *' also returns a value\n                   in case the 'throw' method is called */\n                s->func_state.frame.cur_sp[-1] = value;\n                s->func_state.frame.cur_sp[0] =\n                    JS_NewInt32(ctx, next->completion_type);\n                s->func_state.frame.cur_sp++;\n            exec_no_arg:\n                s->func_state.throw_flag = FALSE;\n            }\n            s->state = JS_ASYNC_GENERATOR_STATE_EXECUTING;\n        resume_exec:\n            func_ret = async_func_resume(ctx, &s->func_state);\n            if (JS_IsException(func_ret)) {\n                value = JS_GetException(ctx);\n                js_async_generator_complete(ctx, s);\n                js_async_generator_reject(ctx, s, value);\n                JS_FreeValue(ctx, value);\n            } else if (JS_VALUE_GET_TAG(func_ret) == JS_TAG_INT) {\n                int func_ret_code;\n                value = s->func_state.frame.cur_sp[-1];\n                s->func_state.frame.cur_sp[-1] = JS_UNDEFINED;\n                func_ret_code = JS_VALUE_GET_INT(func_ret);\n                switch(func_ret_code) {\n                case FUNC_RET_YIELD:\n                case FUNC_RET_YIELD_STAR:\n                    if (func_ret_code == FUNC_RET_YIELD_STAR)\n                        s->state = JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD_STAR;\n                    else\n                        s->state = JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD;\n                    js_async_generator_resolve(ctx, s, value, FALSE);\n                    JS_FreeValue(ctx, value);\n                    break;\n                case FUNC_RET_AWAIT:\n                    js_async_generator_await(ctx, s, value);\n                    JS_FreeValue(ctx, value);\n                    goto done;\n                default:\n                    abort();\n                }\n            } else {\n                assert(JS_IsUndefined(func_ret));\n                /* end of function */\n                value = s->func_state.frame.cur_sp[-1];\n                s->func_state.frame.cur_sp[-1] = JS_UNDEFINED;\n                js_async_generator_complete(ctx, s);\n                js_async_generator_resolve(ctx, s, value, TRUE);\n                JS_FreeValue(ctx, value);\n            }\n            break;\n        default:\n            abort();\n        }\n    }\n done: ;\n}\n\nstatic JSValue js_async_generator_resolve_function(JSContext *ctx,\n                                                   JSValueConst this_obj,\n                                                   int argc, JSValueConst *argv,\n                                                   int magic, JSValue *func_data)\n{\n    BOOL is_reject = magic & 1;\n    JSAsyncGeneratorData *s = JS_GetOpaque(func_data[0], JS_CLASS_ASYNC_GENERATOR);\n    JSValueConst arg = argv[0];\n\n    /* XXX: what if s == NULL */\n\n    if (magic >= 2) {\n        /* resume next case in AWAITING_RETURN state */\n        assert(s->state == JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN ||\n               s->state == JS_ASYNC_GENERATOR_STATE_COMPLETED);\n        s->state = JS_ASYNC_GENERATOR_STATE_COMPLETED;\n        if (is_reject) {\n            js_async_generator_reject(ctx, s, arg);\n        } else {\n            js_async_generator_resolve(ctx, s, arg, TRUE);\n        }\n    } else {\n        /* restart function execution after await() */\n        assert(s->state == JS_ASYNC_GENERATOR_STATE_EXECUTING);\n        s->func_state.throw_flag = is_reject;\n        if (is_reject) {\n            JS_Throw(ctx, JS_DupValue(ctx, arg));\n        } else {\n            /* return value of await */\n            s->func_state.frame.cur_sp[-1] = JS_DupValue(ctx, arg);\n        }\n        js_async_generator_resume_next(ctx, s);\n    }\n    return JS_UNDEFINED;\n}\n\n/* magic = GEN_MAGIC_x */\nstatic JSValue js_async_generator_next(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv,\n                                       int magic)\n{\n    JSAsyncGeneratorData *s = JS_GetOpaque(this_val, JS_CLASS_ASYNC_GENERATOR);\n    JSValue promise, resolving_funcs[2];\n    JSAsyncGeneratorRequest *req;\n\n    promise = JS_NewPromiseCapability(ctx, resolving_funcs);\n    if (JS_IsException(promise))\n        return JS_EXCEPTION;\n    if (!s) {\n        JSValue err, res2;\n        JS_ThrowTypeError(ctx, \"not an AsyncGenerator object\");\n        err = JS_GetException(ctx);\n        res2 = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED,\n                       1, (JSValueConst *)&err);\n        JS_FreeValue(ctx, err);\n        JS_FreeValue(ctx, res2);\n        JS_FreeValue(ctx, resolving_funcs[0]);\n        JS_FreeValue(ctx, resolving_funcs[1]);\n        return promise;\n    }\n    req = js_mallocz(ctx, sizeof(*req));\n    if (!req)\n        goto fail;\n    req->completion_type = magic;\n    req->result = JS_DupValue(ctx, argv[0]);\n    req->promise = JS_DupValue(ctx, promise);\n    req->resolving_funcs[0] = resolving_funcs[0];\n    req->resolving_funcs[1] = resolving_funcs[1];\n    list_add_tail(&req->link, &s->queue);\n    if (s->state != JS_ASYNC_GENERATOR_STATE_EXECUTING) {\n        js_async_generator_resume_next(ctx, s);\n    }\n    return promise;\n fail:\n    JS_FreeValue(ctx, resolving_funcs[0]);\n    JS_FreeValue(ctx, resolving_funcs[1]);\n    JS_FreeValue(ctx, promise);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_async_generator_function_call(JSContext *ctx, JSValueConst func_obj,\n                                                JSValueConst this_obj,\n                                                int argc, JSValueConst *argv,\n                                                int flags)\n{\n    JSValue obj, func_ret;\n    JSAsyncGeneratorData *s;\n\n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s)\n        return JS_EXCEPTION;\n    s->state = JS_ASYNC_GENERATOR_STATE_SUSPENDED_START;\n    init_list_head(&s->queue);\n    if (async_func_init(ctx, &s->func_state, func_obj, this_obj, argc, argv)) {\n        s->state = JS_ASYNC_GENERATOR_STATE_COMPLETED;\n        goto fail;\n    }\n\n    /* execute the function up to 'OP_initial_yield' (no yield nor\n       await are possible) */\n    func_ret = async_func_resume(ctx, &s->func_state);\n    if (JS_IsException(func_ret))\n        goto fail;\n    JS_FreeValue(ctx, func_ret);\n\n    obj = js_create_from_ctor(ctx, func_obj, JS_CLASS_ASYNC_GENERATOR);\n    if (JS_IsException(obj))\n        goto fail;\n    s->generator = JS_VALUE_GET_OBJ(obj);\n    JS_SetOpaque(obj, s);\n    return obj;\n fail:\n    js_async_generator_free(ctx->rt, s);\n    return JS_EXCEPTION;\n}\n\n/* JS parser */\n\nenum {\n    TOK_NUMBER = -128,\n    TOK_STRING,\n    TOK_TEMPLATE,\n    TOK_IDENT,\n    TOK_REGEXP,\n    /* warning: order matters (see js_parse_assign_expr) */\n    TOK_MUL_ASSIGN,\n    TOK_DIV_ASSIGN,\n    TOK_MOD_ASSIGN,\n    TOK_PLUS_ASSIGN,\n    TOK_MINUS_ASSIGN,\n    TOK_SHL_ASSIGN,\n    TOK_SAR_ASSIGN,\n    TOK_SHR_ASSIGN,\n    TOK_AND_ASSIGN,\n    TOK_XOR_ASSIGN,\n    TOK_OR_ASSIGN,\n#ifdef CONFIG_BIGNUM\n    TOK_MATH_POW_ASSIGN,\n#endif\n    TOK_POW_ASSIGN,\n    TOK_LAND_ASSIGN,\n    TOK_LOR_ASSIGN,\n    TOK_DOUBLE_QUESTION_MARK_ASSIGN,\n    TOK_DEC,\n    TOK_INC,\n    TOK_SHL,\n    TOK_SAR,\n    TOK_SHR,\n    TOK_LT,\n    TOK_LTE,\n    TOK_GT,\n    TOK_GTE,\n    TOK_EQ,\n    TOK_STRICT_EQ,\n    TOK_NEQ,\n    TOK_STRICT_NEQ,\n    TOK_LAND,\n    TOK_LOR,\n#ifdef CONFIG_BIGNUM\n    TOK_MATH_POW,\n#endif\n    TOK_POW,\n    TOK_ARROW,\n    TOK_ELLIPSIS,\n    TOK_DOUBLE_QUESTION_MARK,\n    TOK_QUESTION_MARK_DOT,\n    TOK_ERROR,\n    TOK_PRIVATE_NAME,\n    TOK_EOF,\n    /* keywords: WARNING: same order as atoms */\n    TOK_NULL, /* must be first */\n    TOK_FALSE,\n    TOK_TRUE,\n    TOK_IF,\n    TOK_ELSE,\n    TOK_RETURN,\n    TOK_VAR,\n    TOK_THIS,\n    TOK_DELETE,\n    TOK_VOID,\n    TOK_TYPEOF,\n    TOK_NEW,\n    TOK_IN,\n    TOK_INSTANCEOF,\n    TOK_DO,\n    TOK_WHILE,\n    TOK_FOR,\n    TOK_BREAK,\n    TOK_CONTINUE,\n    TOK_SWITCH,\n    TOK_CASE,\n    TOK_DEFAULT,\n    TOK_THROW,\n    TOK_TRY,\n    TOK_CATCH,\n    TOK_FINALLY,\n    TOK_FUNCTION,\n    TOK_DEBUGGER,\n    TOK_WITH,\n    /* FutureReservedWord */\n    TOK_CLASS,\n    TOK_CONST,\n    TOK_ENUM,\n    TOK_EXPORT,\n    TOK_EXTENDS,\n    TOK_IMPORT,\n    TOK_SUPER,\n    /* FutureReservedWords when parsing strict mode code */\n    TOK_IMPLEMENTS,\n    TOK_INTERFACE,\n    TOK_LET,\n    TOK_PACKAGE,\n    TOK_PRIVATE,\n    TOK_PROTECTED,\n    TOK_PUBLIC,\n    TOK_STATIC,\n    TOK_YIELD,\n    TOK_AWAIT, /* must be last */\n    TOK_OF,     /* only used for js_parse_skip_parens_token() */\n};\n\n#define TOK_FIRST_KEYWORD   TOK_NULL\n#define TOK_LAST_KEYWORD    TOK_AWAIT\n\n/* unicode code points */\n#define CP_NBSP 0x00a0\n#define CP_BOM  0xfeff\n\n#define CP_LS   0x2028\n#define CP_PS   0x2029\n\ntypedef struct BlockEnv {\n    struct BlockEnv *prev;\n    JSAtom label_name; /* JS_ATOM_NULL if none */\n    int label_break; /* -1 if none */\n    int label_cont; /* -1 if none */\n    int drop_count; /* number of stack elements to drop */\n    int label_finally; /* -1 if none */\n    int scope_level;\n    int has_iterator;\n} BlockEnv;\n\ntypedef struct JSGlobalVar {\n    int cpool_idx; /* if >= 0, index in the constant pool for hoisted\n                      function defintion*/\n    uint8_t force_init : 1; /* force initialization to undefined */\n    uint8_t is_lexical : 1; /* global let/const definition */\n    uint8_t is_const   : 1; /* const definition */\n    int scope_level;    /* scope of definition */\n    JSAtom var_name;  /* variable name */\n} JSGlobalVar;\n\ntypedef struct RelocEntry {\n    struct RelocEntry *next;\n    uint32_t addr; /* address to patch */\n    int size;   /* address size: 1, 2 or 4 bytes */\n} RelocEntry;\n\ntypedef struct JumpSlot {\n    int op;\n    int size;\n    int pos;\n    int label;\n} JumpSlot;\n\ntypedef struct LabelSlot {\n    int ref_count;\n    int pos;    /* phase 1 address, -1 means not resolved yet */\n    int pos2;   /* phase 2 address, -1 means not resolved yet */\n    int addr;   /* phase 3 address, -1 means not resolved yet */\n    RelocEntry *first_reloc;\n} LabelSlot;\n\ntypedef struct LineNumberSlot {\n    uint32_t pc;\n    int line_num;\n} LineNumberSlot;\n\ntypedef enum JSParseFunctionEnum {\n    JS_PARSE_FUNC_STATEMENT,\n    JS_PARSE_FUNC_VAR,\n    JS_PARSE_FUNC_EXPR,\n    JS_PARSE_FUNC_ARROW,\n    JS_PARSE_FUNC_GETTER,\n    JS_PARSE_FUNC_SETTER,\n    JS_PARSE_FUNC_METHOD,\n    JS_PARSE_FUNC_CLASS_CONSTRUCTOR,\n    JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR,\n} JSParseFunctionEnum;\n\ntypedef enum JSParseExportEnum {\n    JS_PARSE_EXPORT_NONE,\n    JS_PARSE_EXPORT_NAMED,\n    JS_PARSE_EXPORT_DEFAULT,\n} JSParseExportEnum;\n\ntypedef struct JSFunctionDef {\n    JSContext *ctx;\n    struct JSFunctionDef *parent;\n    int parent_cpool_idx; /* index in the constant pool of the parent\n                             or -1 if none */\n    int parent_scope_level; /* scope level in parent at point of definition */\n    struct list_head child_list; /* list of JSFunctionDef.link */\n    struct list_head link;\n\n    BOOL is_eval; /* TRUE if eval code */\n    int eval_type; /* only valid if is_eval = TRUE */\n    BOOL is_global_var; /* TRUE if variables are not defined locally:\n                           eval global, eval module or non strict eval */\n    BOOL is_func_expr; /* TRUE if function expression */\n    BOOL has_home_object; /* TRUE if the home object is available */\n    BOOL has_prototype; /* true if a prototype field is necessary */\n    BOOL has_simple_parameter_list;\n    BOOL has_parameter_expressions; /* if true, an argument scope is created */\n    BOOL has_use_strict; /* to reject directive in special cases */\n    BOOL has_eval_call; /* true if the function contains a call to eval() */\n    BOOL has_arguments_binding; /* true if the 'arguments' binding is\n                                   available in the function */\n    BOOL has_this_binding; /* true if the 'this' and new.target binding are\n                              available in the function */\n    BOOL new_target_allowed; /* true if the 'new.target' does not\n                                throw a syntax error */\n    BOOL super_call_allowed; /* true if super() is allowed */\n    BOOL super_allowed; /* true if super. or super[] is allowed */\n    BOOL arguments_allowed; /* true if the 'arguments' identifier is allowed */\n    BOOL is_derived_class_constructor;\n    BOOL in_function_body;\n    BOOL backtrace_barrier;\n    JSFunctionKindEnum func_kind : 8;\n    JSParseFunctionEnum func_type : 8;\n    uint8_t js_mode; /* bitmap of JS_MODE_x */\n    JSAtom func_name; /* JS_ATOM_NULL if no name */\n\n    JSVarDef *vars;\n    int var_size; /* allocated size for vars[] */\n    int var_count;\n    JSVarDef *args;\n    int arg_size; /* allocated size for args[] */\n    int arg_count; /* number of arguments */\n    int defined_arg_count;\n    int var_object_idx; /* -1 if none */\n    int arg_var_object_idx; /* -1 if none (var object for the argument scope) */\n    int arguments_var_idx; /* -1 if none */\n    int arguments_arg_idx; /* argument variable definition in argument scope, \n                              -1 if none */\n    int func_var_idx; /* variable containing the current function (-1\n                         if none, only used if is_func_expr is true) */\n    int eval_ret_idx; /* variable containing the return value of the eval, -1 if none */\n    int this_var_idx; /* variable containg the 'this' value, -1 if none */\n    int new_target_var_idx; /* variable containg the 'new.target' value, -1 if none */\n    int this_active_func_var_idx; /* variable containg the 'this.active_func' value, -1 if none */\n    int home_object_var_idx;\n    BOOL need_home_object;\n    \n    int scope_level;    /* index into fd->scopes if the current lexical scope */\n    int scope_first;    /* index into vd->vars of first lexically scoped variable */\n    int scope_size;     /* allocated size of fd->scopes array */\n    int scope_count;    /* number of entries used in the fd->scopes array */\n    JSVarScope *scopes;\n    JSVarScope def_scope_array[4];\n    int body_scope; /* scope of the body of the function or eval */\n\n    int global_var_count;\n    int global_var_size;\n    JSGlobalVar *global_vars;\n\n    DynBuf byte_code;\n    int last_opcode_pos; /* -1 if no last opcode */\n    int last_opcode_line_num;\n    BOOL use_short_opcodes; /* true if short opcodes are used in byte_code */\n    \n    LabelSlot *label_slots;\n    int label_size; /* allocated size for label_slots[] */\n    int label_count;\n    BlockEnv *top_break; /* break/continue label stack */\n\n    /* constant pool (strings, functions, numbers) */\n    JSValue *cpool;\n    int cpool_count;\n    int cpool_size;\n\n    /* list of variables in the closure */\n    int closure_var_count;\n    int closure_var_size;\n    JSClosureVar *closure_var;\n\n    JumpSlot *jump_slots;\n    int jump_size;\n    int jump_count;\n\n    LineNumberSlot *line_number_slots;\n    int line_number_size;\n    int line_number_count;\n    int line_number_last;\n    int line_number_last_pc;\n\n    /* pc2line table */\n    JSAtom filename;\n    int line_num;\n    DynBuf pc2line;\n\n    char *source;  /* raw source, utf-8 encoded */\n    int source_len;\n\n    JSModuleDef *module; /* != NULL when parsing a module */\n} JSFunctionDef;\n\ntypedef struct JSToken {\n    int val;\n    int line_num;   /* line number of token start */\n    const uint8_t *ptr;\n    union {\n        struct {\n            JSValue str;\n            int sep;\n        } str;\n        struct {\n            JSValue val;\n#ifdef CONFIG_BIGNUM\n            slimb_t exponent; /* may be != 0 only if val is a float */\n#endif\n        } num;\n        struct {\n            JSAtom atom;\n            BOOL has_escape;\n            BOOL is_reserved;\n        } ident;\n        struct {\n            JSValue body;\n            JSValue flags;\n        } regexp;\n    } u;\n} JSToken;\n\ntypedef struct JSParseState {\n    JSContext *ctx;\n    int last_line_num;  /* line number of last token */\n    int line_num;       /* line number of current offset */\n    const char *filename;\n    JSToken token;\n    BOOL got_lf; /* true if got line feed before the current token */\n    const uint8_t *last_ptr;\n    const uint8_t *buf_ptr;\n    const uint8_t *buf_end;\n\n    /* current function code */\n    JSFunctionDef *cur_func;\n    BOOL is_module; /* parsing a module */\n    BOOL allow_html_comments;\n    BOOL ext_json; /* true if accepting JSON superset */\n} JSParseState;\n\ntypedef struct JSOpCode {\n#ifdef DUMP_BYTECODE\n    const char *name;\n#endif\n    uint8_t size; /* in bytes */\n    /* the opcodes remove n_pop items from the top of the stack, then\n       pushes n_push items */\n    uint8_t n_pop;\n    uint8_t n_push;\n    uint8_t fmt;\n} JSOpCode;\n\nstatic const JSOpCode opcode_info[OP_COUNT + (OP_TEMP_END - OP_TEMP_START)] = {\n#define FMT(f)\n#ifdef DUMP_BYTECODE\n#define DEF(id, size, n_pop, n_push, f) { #id, size, n_pop, n_push, OP_FMT_ ## f },\n#else\n#define DEF(id, size, n_pop, n_push, f) { size, n_pop, n_push, OP_FMT_ ## f },\n#endif\n#include \"quickjs-opcode.h\"\n#undef DEF\n#undef FMT\n};\n\n#if SHORT_OPCODES\n/* After the final compilation pass, short opcodes are used. Their\n   opcodes overlap with the temporary opcodes which cannot appear in\n   the final bytecode. Their description is after the temporary\n   opcodes in opcode_info[]. */\n#define short_opcode_info(op)           \\\n    opcode_info[(op) >= OP_TEMP_START ? \\\n                (op) + (OP_TEMP_END - OP_TEMP_START) : (op)]\n#else\n#define short_opcode_info(op) opcode_info[op]\n#endif\n\nstatic __exception int next_token(JSParseState *s);\n\nstatic void free_token(JSParseState *s, JSToken *token)\n{\n    switch(token->val) {\n#ifdef CONFIG_BIGNUM\n    case TOK_NUMBER:\n        JS_FreeValue(s->ctx, token->u.num.val);\n        break;\n#endif\n    case TOK_STRING:\n    case TOK_TEMPLATE:\n        JS_FreeValue(s->ctx, token->u.str.str);\n        break;\n    case TOK_REGEXP:\n        JS_FreeValue(s->ctx, token->u.regexp.body);\n        JS_FreeValue(s->ctx, token->u.regexp.flags);\n        break;\n    case TOK_IDENT:\n    case TOK_PRIVATE_NAME:\n        JS_FreeAtom(s->ctx, token->u.ident.atom);\n        break;\n    default:\n        if (token->val >= TOK_FIRST_KEYWORD &&\n            token->val <= TOK_LAST_KEYWORD) {\n            JS_FreeAtom(s->ctx, token->u.ident.atom);\n        }\n        break;\n    }\n}\n\nstatic void __attribute((unused)) dump_token(JSParseState *s,\n                                             const JSToken *token)\n{\n    switch(token->val) {\n    case TOK_NUMBER:\n        {\n            double d;\n            JS_ToFloat64(s->ctx, &d, token->u.num.val);  /* no exception possible */\n            printf(\"number: %.14g\\n\", d);\n        }\n        break;\n    case TOK_IDENT:\n    dump_atom:\n        {\n            char buf[ATOM_GET_STR_BUF_SIZE];\n            printf(\"ident: '%s'\\n\",\n                   JS_AtomGetStr(s->ctx, buf, sizeof(buf), token->u.ident.atom));\n        }\n        break;\n    case TOK_STRING:\n        {\n            const char *str;\n            /* XXX: quote the string */\n            str = JS_ToCString(s->ctx, token->u.str.str);\n            printf(\"string: '%s'\\n\", str);\n            JS_FreeCString(s->ctx, str);\n        }\n        break;\n    case TOK_TEMPLATE:\n        {\n            const char *str;\n            str = JS_ToCString(s->ctx, token->u.str.str);\n            printf(\"template: `%s`\\n\", str);\n            JS_FreeCString(s->ctx, str);\n        }\n        break;\n    case TOK_REGEXP:\n        {\n            const char *str, *str2;\n            str = JS_ToCString(s->ctx, token->u.regexp.body);\n            str2 = JS_ToCString(s->ctx, token->u.regexp.flags);\n            printf(\"regexp: '%s' '%s'\\n\", str, str2);\n            JS_FreeCString(s->ctx, str);\n            JS_FreeCString(s->ctx, str2);\n        }\n        break;\n    case TOK_EOF:\n        printf(\"eof\\n\");\n        break;\n    default:\n        if (s->token.val >= TOK_NULL && s->token.val <= TOK_LAST_KEYWORD) {\n            goto dump_atom;\n        } else if (s->token.val >= 256) {\n            printf(\"token: %d\\n\", token->val);\n        } else {\n            printf(\"token: '%c'\\n\", token->val);\n        }\n        break;\n    }\n}\n\nint __attribute__((format(printf, 2, 3))) js_parse_error(JSParseState *s, const char *fmt, ...)\n{\n    JSContext *ctx = s->ctx;\n    va_list ap;\n    int backtrace_flags;\n    \n    va_start(ap, fmt);\n    JS_ThrowError2(ctx, JS_SYNTAX_ERROR, fmt, ap, FALSE);\n    va_end(ap);\n    backtrace_flags = 0;\n    if (s->cur_func && s->cur_func->backtrace_barrier)\n        backtrace_flags = JS_BACKTRACE_FLAG_SINGLE_LEVEL;\n    build_backtrace(ctx, ctx->rt->current_exception, s->filename, s->line_num,\n                    backtrace_flags);\n    return -1;\n}\n\nstatic int js_parse_expect(JSParseState *s, int tok)\n{\n    if (s->token.val != tok) {\n        /* XXX: dump token correctly in all cases */\n        return js_parse_error(s, \"expecting '%c'\", tok);\n    }\n    return next_token(s);\n}\n\nstatic int js_parse_expect_semi(JSParseState *s)\n{\n    if (s->token.val != ';') {\n        /* automatic insertion of ';' */\n        if (s->token.val == TOK_EOF || s->token.val == '}' || s->got_lf) {\n            return 0;\n        }\n        return js_parse_error(s, \"expecting '%c'\", ';');\n    }\n    return next_token(s);\n}\n\nstatic int js_parse_error_reserved_identifier(JSParseState *s)\n{\n    char buf1[ATOM_GET_STR_BUF_SIZE];\n    return js_parse_error(s, \"'%s' is a reserved identifier\",\n                          JS_AtomGetStr(s->ctx, buf1, sizeof(buf1),\n                                        s->token.u.ident.atom));\n}\n\nstatic __exception int js_parse_template_part(JSParseState *s, const uint8_t *p)\n{\n    uint32_t c;\n    StringBuffer b_s, *b = &b_s;\n\n    /* p points to the first byte of the template part */\n    if (string_buffer_init(s->ctx, b, 32))\n        goto fail;\n    for(;;) {\n        if (p >= s->buf_end)\n            goto unexpected_eof;\n        c = *p++;\n        if (c == '`') {\n            /* template end part */\n            break;\n        }\n        if (c == '$' && *p == '{') {\n            /* template start or middle part */\n            p++;\n            break;\n        }\n        if (c == '\\\\') {\n            if (string_buffer_putc8(b, c))\n                goto fail;\n            if (p >= s->buf_end)\n                goto unexpected_eof;\n            c = *p++;\n        }\n        /* newline sequences are normalized as single '\\n' bytes */\n        if (c == '\\r') {\n            if (*p == '\\n')\n                p++;\n            c = '\\n';\n        }\n        if (c == '\\n') {\n            s->line_num++;\n        } else if (c >= 0x80) {\n            const uint8_t *p_next;\n            c = unicode_from_utf8(p - 1, UTF8_CHAR_LEN_MAX, &p_next);\n            if (c > 0x10FFFF) {\n                js_parse_error(s, \"invalid UTF-8 sequence\");\n                goto fail;\n            }\n            p = p_next;\n        }\n        if (string_buffer_putc(b, c))\n            goto fail;\n    }\n    s->token.val = TOK_TEMPLATE;\n    s->token.u.str.sep = c;\n    s->token.u.str.str = string_buffer_end(b);\n    s->buf_ptr = p;\n    return 0;\n\n unexpected_eof:\n    js_parse_error(s, \"unexpected end of string\");\n fail:\n    string_buffer_free(b);\n    return -1;\n}\n\nstatic __exception int js_parse_string(JSParseState *s, int sep,\n                                       BOOL do_throw, const uint8_t *p,\n                                       JSToken *token, const uint8_t **pp)\n{\n    int ret;\n    uint32_t c;\n    StringBuffer b_s, *b = &b_s;\n\n    /* string */\n    if (string_buffer_init(s->ctx, b, 32))\n        goto fail;\n    for(;;) {\n        if (p >= s->buf_end)\n            goto invalid_char;\n        c = *p;\n        if (c < 0x20) {\n            if (!s->cur_func) {\n                if (do_throw)\n                    js_parse_error(s, \"invalid character in a JSON string\");\n                goto fail;\n            }\n            if (sep == '`') {\n                if (c == '\\r') {\n                    if (p[1] == '\\n')\n                        p++;\n                    c = '\\n';\n                }\n                /* do not update s->line_num */\n            } else if (c == '\\n' || c == '\\r')\n                goto invalid_char;\n        }\n        p++;\n        if (c == sep)\n            break;\n        if (c == '$' && *p == '{' && sep == '`') {\n            /* template start or middle part */\n            p++;\n            break;\n        }\n        if (c == '\\\\') {\n            c = *p;\n            /* XXX: need a specific JSON case to avoid\n               accepting invalid escapes */\n            switch(c) {\n            case '\\0':\n                if (p >= s->buf_end)\n                    goto invalid_char;\n                p++;\n                break;\n            case '\\'':\n            case '\\\"':\n            case '\\\\':\n                p++;\n                break;\n            case '\\r':  /* accept DOS and MAC newline sequences */\n                if (p[1] == '\\n') {\n                    p++;\n                }\n                /* fall thru */\n            case '\\n':\n                /* ignore escaped newline sequence */\n                p++;\n                if (sep != '`')\n                    s->line_num++;\n                continue;\n            default:\n                if (c >= '0' && c <= '9') {\n                    if (!s->cur_func)\n                        goto invalid_escape; /* JSON case */\n                    if (!(s->cur_func->js_mode & JS_MODE_STRICT) && sep != '`')\n                        goto parse_escape;\n                    if (c == '0' && !(p[1] >= '0' && p[1] <= '9')) {\n                        p++;\n                        c = '\\0';\n                    } else {\n                        if (c >= '8' || sep == '`') {\n                            /* Note: according to ES2021, \\8 and \\9 are not\n                               accepted in strict mode or in templates. */\n                            goto invalid_escape;\n                        } else {\n                            if (do_throw)\n                                js_parse_error(s, \"octal escape sequences are not allowed in strict mode\");\n                        }\n                        goto fail;\n                    }\n                } else if (c >= 0x80) {\n                    const uint8_t *p_next;\n                    c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p_next);\n                    if (c > 0x10FFFF) {\n                        goto invalid_utf8;\n                    }\n                    p = p_next;\n                    /* LS or PS are skipped */\n                    if (c == CP_LS || c == CP_PS)\n                        continue;\n                } else {\n                parse_escape:\n                    ret = lre_parse_escape(&p, TRUE);\n                    if (ret == -1) {\n                    invalid_escape:\n                        if (do_throw)\n                            js_parse_error(s, \"malformed escape sequence in string literal\");\n                        goto fail;\n                    } else if (ret < 0) {\n                        /* ignore the '\\' (could output a warning) */\n                        p++;\n                    } else {\n                        c = ret;\n                    }\n                }\n                break;\n            }\n        } else if (c >= 0x80) {\n            const uint8_t *p_next;\n            c = unicode_from_utf8(p - 1, UTF8_CHAR_LEN_MAX, &p_next);\n            if (c > 0x10FFFF)\n                goto invalid_utf8;\n            p = p_next;\n        }\n        if (string_buffer_putc(b, c))\n            goto fail;\n    }\n    token->val = TOK_STRING;\n    token->u.str.sep = c;\n    token->u.str.str = string_buffer_end(b);\n    *pp = p;\n    return 0;\n\n invalid_utf8:\n    if (do_throw)\n        js_parse_error(s, \"invalid UTF-8 sequence\");\n    goto fail;\n invalid_char:\n    if (do_throw)\n        js_parse_error(s, \"unexpected end of string\");\n fail:\n    string_buffer_free(b);\n    return -1;\n}\n\nstatic inline BOOL token_is_pseudo_keyword(JSParseState *s, JSAtom atom) {\n    return s->token.val == TOK_IDENT && s->token.u.ident.atom == atom &&\n        !s->token.u.ident.has_escape;\n}\n\nstatic __exception int js_parse_regexp(JSParseState *s)\n{\n    const uint8_t *p;\n    BOOL in_class;\n    StringBuffer b_s, *b = &b_s;\n    StringBuffer b2_s, *b2 = &b2_s;\n    uint32_t c;\n\n    p = s->buf_ptr;\n    p++;\n    in_class = FALSE;\n    if (string_buffer_init(s->ctx, b, 32))\n        return -1;\n    if (string_buffer_init(s->ctx, b2, 1))\n        goto fail;\n    for(;;) {\n        if (p >= s->buf_end) {\n        eof_error:\n            js_parse_error(s, \"unexpected end of regexp\");\n            goto fail;\n        }\n        c = *p++;\n        if (c == '\\n' || c == '\\r') {\n            goto eol_error;\n        } else if (c == '/') {\n            if (!in_class)\n                break;\n        } else if (c == '[') {\n            in_class = TRUE;\n        } else if (c == ']') {\n            /* XXX: incorrect as the first character in a class */\n            in_class = FALSE;\n        } else if (c == '\\\\') {\n            if (string_buffer_putc8(b, c))\n                goto fail;\n            c = *p++;\n            if (c == '\\n' || c == '\\r')\n                goto eol_error;\n            else if (c == '\\0' && p >= s->buf_end)\n                goto eof_error;\n            else if (c >= 0x80) {\n                const uint8_t *p_next;\n                c = unicode_from_utf8(p - 1, UTF8_CHAR_LEN_MAX, &p_next);\n                if (c > 0x10FFFF) {\n                    goto invalid_utf8;\n                }\n                p = p_next;\n                if (c == CP_LS || c == CP_PS)\n                    goto eol_error;\n            }\n        } else if (c >= 0x80) {\n            const uint8_t *p_next;\n            c = unicode_from_utf8(p - 1, UTF8_CHAR_LEN_MAX, &p_next);\n            if (c > 0x10FFFF) {\n            invalid_utf8:\n                js_parse_error(s, \"invalid UTF-8 sequence\");\n                goto fail;\n            }\n            p = p_next;\n            /* LS or PS are considered as line terminator */\n            if (c == CP_LS || c == CP_PS) {\n            eol_error:\n                js_parse_error(s, \"unexpected line terminator in regexp\");\n                goto fail;\n            }\n        }\n        if (string_buffer_putc(b, c))\n            goto fail;\n    }\n\n    /* flags */\n    for(;;) {\n        const uint8_t *p_next = p;\n        c = *p_next++;\n        if (c >= 0x80) {\n            c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p_next);\n            if (c > 0x10FFFF) {\n                goto invalid_utf8;\n            }\n        }\n        if (!lre_js_is_ident_next(c))\n            break;\n        if (string_buffer_putc(b2, c))\n            goto fail;\n        p = p_next;\n    }\n\n    s->token.val = TOK_REGEXP;\n    s->token.u.regexp.body = string_buffer_end(b);\n    s->token.u.regexp.flags = string_buffer_end(b2);\n    s->buf_ptr = p;\n    return 0;\n fail:\n    string_buffer_free(b);\n    string_buffer_free(b2);\n    return -1;\n}\n\nstatic __exception int ident_realloc(JSContext *ctx, char **pbuf, size_t *psize,\n                                     char *static_buf)\n{\n    char *buf, *new_buf;\n    size_t size, new_size;\n    \n    buf = *pbuf;\n    size = *psize;\n    if (size >= (SIZE_MAX / 3) * 2)\n        new_size = SIZE_MAX;\n    else\n        new_size = size + (size >> 1);\n    if (buf == static_buf) {\n        new_buf = js_malloc(ctx, new_size);\n        if (!new_buf)\n            return -1;\n        memcpy(new_buf, buf, size);\n    } else {\n        new_buf = js_realloc(ctx, buf, new_size);\n        if (!new_buf)\n            return -1;\n    }\n    *pbuf = new_buf;\n    *psize = new_size;\n    return 0;\n}\n\n/* 'c' is the first character. Return JS_ATOM_NULL in case of error */\nstatic JSAtom parse_ident(JSParseState *s, const uint8_t **pp,\n                          BOOL *pident_has_escape, int c, BOOL is_private)\n{\n    const uint8_t *p, *p1;\n    char ident_buf[128], *buf;\n    size_t ident_size, ident_pos;\n    JSAtom atom;\n    \n    p = *pp;\n    buf = ident_buf;\n    ident_size = sizeof(ident_buf);\n    ident_pos = 0;\n    if (is_private)\n        buf[ident_pos++] = '#';\n    for(;;) {\n        p1 = p;\n        \n        if (c < 128) {\n            buf[ident_pos++] = c;\n        } else {\n            ident_pos += unicode_to_utf8((uint8_t*)buf + ident_pos, c);\n        }\n        c = *p1++;\n        if (c == '\\\\' && *p1 == 'u') {\n            c = lre_parse_escape(&p1, TRUE);\n            *pident_has_escape = TRUE;\n        } else if (c >= 128) {\n            c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p1);\n        }\n        if (!lre_js_is_ident_next(c))\n            break;\n        p = p1;\n        if (unlikely(ident_pos >= ident_size - UTF8_CHAR_LEN_MAX)) {\n            if (ident_realloc(s->ctx, &buf, &ident_size, ident_buf)) {\n                atom = JS_ATOM_NULL;\n                goto done;\n            }\n        }\n    }\n    atom = JS_NewAtomLen(s->ctx, buf, ident_pos);\n done:\n    if (unlikely(buf != ident_buf))\n        js_free(s->ctx, buf);\n    *pp = p;\n    return atom;\n}\n\n\nstatic __exception int next_token(JSParseState *s)\n{\n    const uint8_t *p;\n    int c;\n    BOOL ident_has_escape;\n    JSAtom atom;\n    \n    if (js_check_stack_overflow(s->ctx->rt, 0)) {\n        return js_parse_error(s, \"stack overflow\");\n    }\n    \n    free_token(s, &s->token);\n\n    p = s->last_ptr = s->buf_ptr;\n    s->got_lf = FALSE;\n    s->last_line_num = s->token.line_num;\n redo:\n    s->token.line_num = s->line_num;\n    s->token.ptr = p;\n    c = *p;\n    switch(c) {\n    case 0:\n        if (p >= s->buf_end) {\n            s->token.val = TOK_EOF;\n        } else {\n            goto def_token;\n        }\n        break;\n    case '`':\n        if (js_parse_template_part(s, p + 1))\n            goto fail;\n        p = s->buf_ptr;\n        break;\n    case '\\'':\n    case '\\\"':\n        if (js_parse_string(s, c, TRUE, p + 1, &s->token, &p))\n            goto fail;\n        break;\n    case '\\r':  /* accept DOS and MAC newline sequences */\n        if (p[1] == '\\n') {\n            p++;\n        }\n        /* fall thru */\n    case '\\n':\n        p++;\n    line_terminator:\n        s->got_lf = TRUE;\n        s->line_num++;\n        goto redo;\n    case '\\f':\n    case '\\v':\n    case ' ':\n    case '\\t':\n        p++;\n        goto redo;\n    case '/':\n        if (p[1] == '*') {\n            /* comment */\n            p += 2;\n            for(;;) {\n                if (*p == '\\0' && p >= s->buf_end) {\n                    js_parse_error(s, \"unexpected end of comment\");\n                    goto fail;\n                }\n                if (p[0] == '*' && p[1] == '/') {\n                    p += 2;\n                    break;\n                }\n                if (*p == '\\n') {\n                    s->line_num++;\n                    s->got_lf = TRUE; /* considered as LF for ASI */\n                    p++;\n                } else if (*p == '\\r') {\n                    s->got_lf = TRUE; /* considered as LF for ASI */\n                    p++;\n                } else if (*p >= 0x80) {\n                    c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);\n                    if (c == CP_LS || c == CP_PS) {\n                        s->got_lf = TRUE; /* considered as LF for ASI */\n                    } else if (c == -1) {\n                        p++; /* skip invalid UTF-8 */\n                    }\n                } else {\n                    p++;\n                }\n            }\n            goto redo;\n        } else if (p[1] == '/') {\n            /* line comment */\n            p += 2;\n        skip_line_comment:\n            for(;;) {\n                if (*p == '\\0' && p >= s->buf_end)\n                    break;\n                if (*p == '\\r' || *p == '\\n')\n                    break;\n                if (*p >= 0x80) {\n                    c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);\n                    /* LS or PS are considered as line terminator */\n                    if (c == CP_LS || c == CP_PS) {\n                        break;\n                    } else if (c == -1) {\n                        p++; /* skip invalid UTF-8 */\n                    }\n                } else {\n                    p++;\n                }\n            }\n            goto redo;\n        } else if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_DIV_ASSIGN;\n        } else {\n            p++;\n            s->token.val = c;\n        }\n        break;\n    case '\\\\':\n        if (p[1] == 'u') {\n            const uint8_t *p1 = p + 1;\n            int c1 = lre_parse_escape(&p1, TRUE);\n            if (c1 >= 0 && lre_js_is_ident_first(c1)) {\n                c = c1;\n                p = p1;\n                ident_has_escape = TRUE;\n                goto has_ident;\n            } else {\n                /* XXX: syntax error? */\n            }\n        }\n        goto def_token;\n    case 'a': case 'b': case 'c': case 'd':\n    case 'e': case 'f': case 'g': case 'h':\n    case 'i': case 'j': case 'k': case 'l':\n    case 'm': case 'n': case 'o': case 'p':\n    case 'q': case 'r': case 's': case 't':\n    case 'u': case 'v': case 'w': case 'x':\n    case 'y': case 'z': \n    case 'A': case 'B': case 'C': case 'D':\n    case 'E': case 'F': case 'G': case 'H':\n    case 'I': case 'J': case 'K': case 'L':\n    case 'M': case 'N': case 'O': case 'P':\n    case 'Q': case 'R': case 'S': case 'T':\n    case 'U': case 'V': case 'W': case 'X':\n    case 'Y': case 'Z': \n    case '_':\n    case '$':\n        /* identifier */\n        p++;\n        ident_has_escape = FALSE;\n    has_ident:\n        atom = parse_ident(s, &p, &ident_has_escape, c, FALSE);\n        if (atom == JS_ATOM_NULL)\n            goto fail;\n        s->token.u.ident.atom = atom;\n        s->token.u.ident.has_escape = ident_has_escape;\n        s->token.u.ident.is_reserved = FALSE;\n        if (s->token.u.ident.atom <= JS_ATOM_LAST_KEYWORD ||\n            (s->token.u.ident.atom <= JS_ATOM_LAST_STRICT_KEYWORD &&\n             (s->cur_func->js_mode & JS_MODE_STRICT)) ||\n            (s->token.u.ident.atom == JS_ATOM_yield &&\n             ((s->cur_func->func_kind & JS_FUNC_GENERATOR) ||\n              (s->cur_func->func_type == JS_PARSE_FUNC_ARROW &&\n               !s->cur_func->in_function_body && s->cur_func->parent &&\n               (s->cur_func->parent->func_kind & JS_FUNC_GENERATOR)))) ||\n            (s->token.u.ident.atom == JS_ATOM_await &&\n             (s->is_module ||\n              (((s->cur_func->func_kind & JS_FUNC_ASYNC) ||\n                (s->cur_func->func_type == JS_PARSE_FUNC_ARROW &&\n                 !s->cur_func->in_function_body && s->cur_func->parent &&\n                 (s->cur_func->parent->func_kind & JS_FUNC_ASYNC))))))) {\n                  if (ident_has_escape) {\n                      s->token.u.ident.is_reserved = TRUE;\n                      s->token.val = TOK_IDENT;\n                  } else {\n                      /* The keywords atoms are pre allocated */\n                      s->token.val = s->token.u.ident.atom - 1 + TOK_FIRST_KEYWORD;\n                  }\n        } else {\n            s->token.val = TOK_IDENT;\n        }\n        break;\n    case '#':\n        /* private name */\n        {\n            const uint8_t *p1;\n            p++;\n            p1 = p;\n            c = *p1++;\n            if (c == '\\\\' && *p1 == 'u') {\n                c = lre_parse_escape(&p1, TRUE);\n            } else if (c >= 128) {\n                c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p1);\n            }\n            if (!lre_js_is_ident_first(c)) {\n                js_parse_error(s, \"invalid first character of private name\");\n                goto fail;\n            }\n            p = p1;\n            ident_has_escape = FALSE; /* not used */\n            atom = parse_ident(s, &p, &ident_has_escape, c, TRUE);\n            if (atom == JS_ATOM_NULL)\n                goto fail;\n            s->token.u.ident.atom = atom;\n            s->token.val = TOK_PRIVATE_NAME;\n        }\n        break;\n    case '.':\n        if (p[1] == '.' && p[2] == '.') {\n            p += 3;\n            s->token.val = TOK_ELLIPSIS;\n            break;\n        }\n        if (p[1] >= '0' && p[1] <= '9') {\n            goto parse_number;\n        } else {\n            goto def_token;\n        }\n        break;\n    case '0':\n        /* in strict mode, octal literals are not accepted */\n        if (is_digit(p[1]) && (s->cur_func->js_mode & JS_MODE_STRICT)) {\n            js_parse_error(s, \"octal literals are deprecated in strict mode\");\n            goto fail;\n        }\n        goto parse_number;\n    case '1': case '2': case '3': case '4':\n    case '5': case '6': case '7': case '8':\n    case '9': \n        /* number */\n    parse_number:\n        {\n            JSValue ret;\n            const uint8_t *p1;\n            int flags, radix;\n            flags = ATOD_ACCEPT_BIN_OCT | ATOD_ACCEPT_LEGACY_OCTAL |\n                ATOD_ACCEPT_UNDERSCORES;\n#ifdef CONFIG_BIGNUM\n            flags |= ATOD_ACCEPT_SUFFIX;\n            if (s->cur_func->js_mode & JS_MODE_MATH) {\n                flags |= ATOD_MODE_BIGINT;\n                if (s->cur_func->js_mode & JS_MODE_MATH)\n                    flags |= ATOD_TYPE_BIG_FLOAT;\n            }\n#endif\n            radix = 0;\n#ifdef CONFIG_BIGNUM\n            s->token.u.num.exponent = 0;\n            ret = js_atof2(s->ctx, (const char *)p, (const char **)&p, radix,\n                           flags, &s->token.u.num.exponent);\n#else\n            ret = js_atof(s->ctx, (const char *)p, (const char **)&p, radix,\n                          flags);\n#endif\n            if (JS_IsException(ret))\n                goto fail;\n            /* reject `10instanceof Number` */\n            if (JS_VALUE_IS_NAN(ret) ||\n                lre_js_is_ident_next(unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p1))) {\n                JS_FreeValue(s->ctx, ret);\n                js_parse_error(s, \"invalid number literal\");\n                goto fail;\n            }\n            s->token.val = TOK_NUMBER;\n            s->token.u.num.val = ret;\n        }\n        break;\n    case '*':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_MUL_ASSIGN;\n        } else if (p[1] == '*') {\n            if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_POW_ASSIGN;\n            } else {\n                p += 2;\n                s->token.val = TOK_POW;\n            }\n        } else {\n            goto def_token;\n        }\n        break;\n    case '%':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_MOD_ASSIGN;\n        } else {\n            goto def_token;\n        }\n        break;\n    case '+':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_PLUS_ASSIGN;\n        } else if (p[1] == '+') {\n            p += 2;\n            s->token.val = TOK_INC;\n        } else {\n            goto def_token;\n        }\n        break;\n    case '-':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_MINUS_ASSIGN;\n        } else if (p[1] == '-') {\n            if (s->allow_html_comments &&\n                p[2] == '>' && s->last_line_num != s->line_num) {\n                /* Annex B: `-->` at beginning of line is an html comment end.\n                   It extends to the end of the line.\n                 */\n                goto skip_line_comment;\n            }\n            p += 2;\n            s->token.val = TOK_DEC;\n        } else {\n            goto def_token;\n        }\n        break;\n    case '<':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_LTE;\n        } else if (p[1] == '<') {\n            if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_SHL_ASSIGN;\n            } else {\n                p += 2;\n                s->token.val = TOK_SHL;\n            }\n        } else if (s->allow_html_comments &&\n                   p[1] == '!' && p[2] == '-' && p[3] == '-') {\n            /* Annex B: handle `<!--` single line html comments */\n            goto skip_line_comment;\n        } else {\n            goto def_token;\n        }\n        break;\n    case '>':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_GTE;\n        } else if (p[1] == '>') {\n            if (p[2] == '>') {\n                if (p[3] == '=') {\n                    p += 4;\n                    s->token.val = TOK_SHR_ASSIGN;\n                } else {\n                    p += 3;\n                    s->token.val = TOK_SHR;\n                }\n            } else if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_SAR_ASSIGN;\n            } else {\n                p += 2;\n                s->token.val = TOK_SAR;\n            }\n        } else {\n            goto def_token;\n        }\n        break;\n    case '=':\n        if (p[1] == '=') {\n            if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_STRICT_EQ;\n            } else {\n                p += 2;\n                s->token.val = TOK_EQ;\n            }\n        } else if (p[1] == '>') {\n            p += 2;\n            s->token.val = TOK_ARROW;\n        } else {\n            goto def_token;\n        }\n        break;\n    case '!':\n        if (p[1] == '=') {\n            if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_STRICT_NEQ;\n            } else {\n                p += 2;\n                s->token.val = TOK_NEQ;\n            }\n        } else {\n            goto def_token;\n        }\n        break;\n    case '&':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_AND_ASSIGN;\n        } else if (p[1] == '&') {\n            if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_LAND_ASSIGN;\n            } else {\n                p += 2;\n                s->token.val = TOK_LAND;\n            }\n        } else {\n            goto def_token;\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n        /* in math mode, '^' is the power operator. '^^' is always the\n           xor operator and '**' is always the power operator */\n    case '^':\n        if (p[1] == '=') {\n            p += 2;\n            if (s->cur_func->js_mode & JS_MODE_MATH)\n                s->token.val = TOK_MATH_POW_ASSIGN;\n            else\n                s->token.val = TOK_XOR_ASSIGN;\n        } else if (p[1] == '^') {\n            if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_XOR_ASSIGN;\n            } else {\n                p += 2;\n                s->token.val = '^';\n            }\n        } else {\n            p++;\n            if (s->cur_func->js_mode & JS_MODE_MATH)\n                s->token.val = TOK_MATH_POW;\n            else\n                s->token.val = '^';\n        }\n        break;\n#else\n    case '^':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_XOR_ASSIGN;\n        } else {\n            goto def_token;\n        }\n        break;\n#endif\n    case '|':\n        if (p[1] == '=') {\n            p += 2;\n            s->token.val = TOK_OR_ASSIGN;\n        } else if (p[1] == '|') {\n            if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_LOR_ASSIGN;\n            } else {\n                p += 2;\n                s->token.val = TOK_LOR;\n            }\n        } else {\n            goto def_token;\n        }\n        break;\n    case '?':\n        if (p[1] == '?') {\n            if (p[2] == '=') {\n                p += 3;\n                s->token.val = TOK_DOUBLE_QUESTION_MARK_ASSIGN;\n            } else {\n                p += 2;\n                s->token.val = TOK_DOUBLE_QUESTION_MARK;\n            }\n        } else if (p[1] == '.' && !(p[2] >= '0' && p[2] <= '9')) {\n            p += 2;\n            s->token.val = TOK_QUESTION_MARK_DOT;\n        } else {\n            goto def_token;\n        }\n        break;\n    default:\n        if (c >= 128) {\n            /* unicode value */\n            c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);\n            switch(c) {\n            case CP_PS:\n            case CP_LS:\n                /* XXX: should avoid incrementing line_number, but\n                   needed to handle HTML comments */\n                goto line_terminator; \n            default:\n                if (lre_is_space(c)) {\n                    goto redo;\n                } else if (lre_js_is_ident_first(c)) {\n                    ident_has_escape = FALSE;\n                    goto has_ident;\n                } else {\n                    js_parse_error(s, \"unexpected character\");\n                    goto fail;\n                }\n            }\n        }\n    def_token:\n        s->token.val = c;\n        p++;\n        break;\n    }\n    s->buf_ptr = p;\n\n    //    dump_token(s, &s->token);\n    return 0;\n\n fail:\n    s->token.val = TOK_ERROR;\n    return -1;\n}\n\n/* 'c' is the first character. Return JS_ATOM_NULL in case of error */\nstatic JSAtom json_parse_ident(JSParseState *s, const uint8_t **pp, int c)\n{\n    const uint8_t *p;\n    char ident_buf[128], *buf;\n    size_t ident_size, ident_pos;\n    JSAtom atom;\n    \n    p = *pp;\n    buf = ident_buf;\n    ident_size = sizeof(ident_buf);\n    ident_pos = 0;\n    for(;;) {\n        buf[ident_pos++] = c;\n        c = *p;\n        if (c >= 128 ||\n            !((lre_id_continue_table_ascii[c >> 5] >> (c & 31)) & 1))\n            break;\n        p++;\n        if (unlikely(ident_pos >= ident_size - UTF8_CHAR_LEN_MAX)) {\n            if (ident_realloc(s->ctx, &buf, &ident_size, ident_buf)) {\n                atom = JS_ATOM_NULL;\n                goto done;\n            }\n        }\n    }\n    atom = JS_NewAtomLen(s->ctx, buf, ident_pos);\n done:\n    if (unlikely(buf != ident_buf))\n        js_free(s->ctx, buf);\n    *pp = p;\n    return atom;\n}\n\nstatic __exception int json_next_token(JSParseState *s)\n{\n    const uint8_t *p;\n    int c;\n    JSAtom atom;\n    \n    if (js_check_stack_overflow(s->ctx->rt, 0)) {\n        return js_parse_error(s, \"stack overflow\");\n    }\n    \n    free_token(s, &s->token);\n\n    p = s->last_ptr = s->buf_ptr;\n    s->last_line_num = s->token.line_num;\n redo:\n    s->token.line_num = s->line_num;\n    s->token.ptr = p;\n    c = *p;\n    switch(c) {\n    case 0:\n        if (p >= s->buf_end) {\n            s->token.val = TOK_EOF;\n        } else {\n            goto def_token;\n        }\n        break;\n    case '\\'':\n        if (!s->ext_json) {\n            /* JSON does not accept single quoted strings */\n            goto def_token;\n        }\n        /* fall through */\n    case '\\\"':\n        if (js_parse_string(s, c, TRUE, p + 1, &s->token, &p))\n            goto fail;\n        break;\n    case '\\r':  /* accept DOS and MAC newline sequences */\n        if (p[1] == '\\n') {\n            p++;\n        }\n        /* fall thru */\n    case '\\n':\n        p++;\n        s->line_num++;\n        goto redo;\n    case '\\f':\n    case '\\v':\n        if (!s->ext_json) {\n            /* JSONWhitespace does not match <VT>, nor <FF> */\n            goto def_token;\n        }\n        /* fall through */\n    case ' ':\n    case '\\t':\n        p++;\n        goto redo;\n    case '/':\n        if (!s->ext_json) {\n            /* JSON does not accept comments */\n            goto def_token;\n        }\n        if (p[1] == '*') {\n            /* comment */\n            p += 2;\n            for(;;) {\n                if (*p == '\\0' && p >= s->buf_end) {\n                    js_parse_error(s, \"unexpected end of comment\");\n                    goto fail;\n                }\n                if (p[0] == '*' && p[1] == '/') {\n                    p += 2;\n                    break;\n                }\n                if (*p == '\\n') {\n                    s->line_num++;\n                    p++;\n                } else if (*p == '\\r') {\n                    p++;\n                } else if (*p >= 0x80) {\n                    c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);\n                    if (c == -1) {\n                        p++; /* skip invalid UTF-8 */\n                    }\n                } else {\n                    p++;\n                }\n            }\n            goto redo;\n        } else if (p[1] == '/') {\n            /* line comment */\n            p += 2;\n            for(;;) {\n                if (*p == '\\0' && p >= s->buf_end)\n                    break;\n                if (*p == '\\r' || *p == '\\n')\n                    break;\n                if (*p >= 0x80) {\n                    c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);\n                    /* LS or PS are considered as line terminator */\n                    if (c == CP_LS || c == CP_PS) {\n                        break;\n                    } else if (c == -1) {\n                        p++; /* skip invalid UTF-8 */\n                    }\n                } else {\n                    p++;\n                }\n            }\n            goto redo;\n        } else {\n            goto def_token;\n        }\n        break;\n    case 'a': case 'b': case 'c': case 'd':\n    case 'e': case 'f': case 'g': case 'h':\n    case 'i': case 'j': case 'k': case 'l':\n    case 'm': case 'n': case 'o': case 'p':\n    case 'q': case 'r': case 's': case 't':\n    case 'u': case 'v': case 'w': case 'x':\n    case 'y': case 'z': \n    case 'A': case 'B': case 'C': case 'D':\n    case 'E': case 'F': case 'G': case 'H':\n    case 'I': case 'J': case 'K': case 'L':\n    case 'M': case 'N': case 'O': case 'P':\n    case 'Q': case 'R': case 'S': case 'T':\n    case 'U': case 'V': case 'W': case 'X':\n    case 'Y': case 'Z': \n    case '_':\n    case '$':\n        /* identifier : only pure ascii characters are accepted */\n        p++;\n        atom = json_parse_ident(s, &p, c);\n        if (atom == JS_ATOM_NULL)\n            goto fail;\n        s->token.u.ident.atom = atom;\n        s->token.u.ident.has_escape = FALSE;\n        s->token.u.ident.is_reserved = FALSE;\n        s->token.val = TOK_IDENT;\n        break;\n    case '+':\n        if (!s->ext_json || !is_digit(p[1]))\n            goto def_token;\n        goto parse_number;\n    case '0':\n        if (is_digit(p[1]))\n            goto def_token;\n        goto parse_number;\n    case '-':\n        if (!is_digit(p[1]))\n            goto def_token;\n        goto parse_number;\n    case '1': case '2': case '3': case '4':\n    case '5': case '6': case '7': case '8':\n    case '9': \n        /* number */\n    parse_number:\n        {\n            JSValue ret;\n            int flags, radix;\n            if (!s->ext_json) {\n                flags = 0;\n                radix = 10;\n            } else {\n                flags = ATOD_ACCEPT_BIN_OCT;\n                radix = 0;\n            }\n            ret = js_atof(s->ctx, (const char *)p, (const char **)&p, radix,\n                          flags);\n            if (JS_IsException(ret))\n                goto fail;\n            s->token.val = TOK_NUMBER;\n            s->token.u.num.val = ret;\n        }\n        break;\n    default:\n        if (c >= 128) {\n            js_parse_error(s, \"unexpected character\");\n            goto fail;\n        }\n    def_token:\n        s->token.val = c;\n        p++;\n        break;\n    }\n    s->buf_ptr = p;\n\n    //    dump_token(s, &s->token);\n    return 0;\n\n fail:\n    s->token.val = TOK_ERROR;\n    return -1;\n}\n\n/* only used for ':' and '=>', 'let' or 'function' look-ahead. *pp is\n   only set if TOK_IMPORT is returned */\n/* XXX: handle all unicode cases */\nstatic int simple_next_token(const uint8_t **pp, BOOL no_line_terminator)\n{\n    const uint8_t *p;\n    uint32_t c;\n    \n    /* skip spaces and comments */\n    p = *pp;\n    for (;;) {\n        switch(c = *p++) {\n        case '\\r':\n        case '\\n':\n            if (no_line_terminator)\n                return '\\n';\n            continue;\n        case ' ':\n        case '\\t':\n        case '\\v':\n        case '\\f':\n            continue;\n        case '/':\n            if (*p == '/') {\n                if (no_line_terminator)\n                    return '\\n';\n                while (*p && *p != '\\r' && *p != '\\n')\n                    p++;\n                continue;\n            }\n            if (*p == '*') {\n                while (*++p) {\n                    if ((*p == '\\r' || *p == '\\n') && no_line_terminator)\n                        return '\\n';\n                    if (*p == '*' && p[1] == '/') {\n                        p += 2;\n                        break;\n                    }\n                }\n                continue;\n            }\n            break;\n        case '=':\n            if (*p == '>')\n                return TOK_ARROW;\n            break;\n        default:\n            if (lre_js_is_ident_first(c)) {\n                if (c == 'i') {\n                    if (p[0] == 'n' && !lre_js_is_ident_next(p[1])) {\n                        return TOK_IN;\n                    }\n                    if (p[0] == 'm' && p[1] == 'p' && p[2] == 'o' &&\n                        p[3] == 'r' && p[4] == 't' &&\n                        !lre_js_is_ident_next(p[5])) {\n                        *pp = p + 5;\n                        return TOK_IMPORT;\n                    }\n                } else if (c == 'o' && *p == 'f' && !lre_js_is_ident_next(p[1])) {\n                    return TOK_OF;\n                } else if (c == 'e' &&\n                           p[0] == 'x' && p[1] == 'p' && p[2] == 'o' &&\n                           p[3] == 'r' && p[4] == 't' &&\n                           !lre_js_is_ident_next(p[5])) {\n                    *pp = p + 5;\n                    return TOK_EXPORT;\n                } else if (c == 'f' && p[0] == 'u' && p[1] == 'n' &&\n                         p[2] == 'c' && p[3] == 't' && p[4] == 'i' &&\n                         p[5] == 'o' && p[6] == 'n' && !lre_js_is_ident_next(p[7])) {\n                    return TOK_FUNCTION;\n                }\n                return TOK_IDENT;\n            }\n            break;\n        }\n        return c;\n    }\n}\n\nstatic int peek_token(JSParseState *s, BOOL no_line_terminator)\n{\n    const uint8_t *p = s->buf_ptr;\n    return simple_next_token(&p, no_line_terminator);\n}\n\n/* return true if 'input' contains the source of a module\n   (heuristic). 'input' must be a zero terminated.\n\n   Heuristic: skip comments and expect 'import' keyword not followed\n   by '(' or '.' or export keyword.\n*/\nBOOL JS_DetectModule(const char *input, size_t input_len)\n{\n    const uint8_t *p = (const uint8_t *)input;\n    int tok;\n    switch(simple_next_token(&p, FALSE)) {\n    case TOK_IMPORT:\n        tok = simple_next_token(&p, FALSE);\n        return (tok != '.' && tok != '(');\n    case TOK_EXPORT:\n        return TRUE;\n    default:\n        return FALSE;\n    }\n}\n\nstatic inline int get_prev_opcode(JSFunctionDef *fd) {\n    if (fd->last_opcode_pos < 0)\n        return OP_invalid;\n    else\n        return fd->byte_code.buf[fd->last_opcode_pos];\n}\n\nstatic BOOL js_is_live_code(JSParseState *s) {\n    switch (get_prev_opcode(s->cur_func)) {\n    case OP_tail_call:\n    case OP_tail_call_method:\n    case OP_return:\n    case OP_return_undef:\n    case OP_return_async:\n    case OP_throw:\n    case OP_throw_error:\n    case OP_goto:\n#if SHORT_OPCODES\n    case OP_goto8:\n    case OP_goto16:\n#endif\n    case OP_ret:\n        return FALSE;\n    default:\n        return TRUE;\n    }\n}\n\nstatic void emit_u8(JSParseState *s, uint8_t val)\n{\n    dbuf_putc(&s->cur_func->byte_code, val);\n}\n\nstatic void emit_u16(JSParseState *s, uint16_t val)\n{\n    dbuf_put_u16(&s->cur_func->byte_code, val);\n}\n\nstatic void emit_u32(JSParseState *s, uint32_t val)\n{\n    dbuf_put_u32(&s->cur_func->byte_code, val);\n}\n\nstatic void emit_op(JSParseState *s, uint8_t val)\n{\n    JSFunctionDef *fd = s->cur_func;\n    DynBuf *bc = &fd->byte_code;\n\n    /* Use the line number of the last token used, not the next token,\n       nor the current offset in the source file.\n     */\n    if (unlikely(fd->last_opcode_line_num != s->last_line_num)) {\n        dbuf_putc(bc, OP_line_num);\n        dbuf_put_u32(bc, s->last_line_num);\n        fd->last_opcode_line_num = s->last_line_num;\n    }\n    fd->last_opcode_pos = bc->size;\n    dbuf_putc(bc, val);\n}\n\nstatic void emit_atom(JSParseState *s, JSAtom name)\n{\n    emit_u32(s, JS_DupAtom(s->ctx, name));\n}\n\nstatic int update_label(JSFunctionDef *s, int label, int delta)\n{\n    LabelSlot *ls;\n\n    assert(label >= 0 && label < s->label_count);\n    ls = &s->label_slots[label];\n    ls->ref_count += delta;\n    assert(ls->ref_count >= 0);\n    return ls->ref_count;\n}\n\nstatic int new_label_fd(JSFunctionDef *fd, int label)\n{\n    LabelSlot *ls;\n\n    if (label < 0) {\n        if (js_resize_array(fd->ctx, (void *)&fd->label_slots,\n                            sizeof(fd->label_slots[0]),\n                            &fd->label_size, fd->label_count + 1))\n            return -1;\n        label = fd->label_count++;\n        ls = &fd->label_slots[label];\n        ls->ref_count = 0;\n        ls->pos = -1;\n        ls->pos2 = -1;\n        ls->addr = -1;\n        ls->first_reloc = NULL;\n    }\n    return label;\n}\n\nstatic int new_label(JSParseState *s)\n{\n    return new_label_fd(s->cur_func, -1);\n}\n\n/* return the label ID offset */\nstatic int emit_label(JSParseState *s, int label)\n{\n    if (label >= 0) {\n        emit_op(s, OP_label);\n        emit_u32(s, label);\n        s->cur_func->label_slots[label].pos = s->cur_func->byte_code.size;\n        return s->cur_func->byte_code.size - 4;\n    } else {\n        return -1;\n    }\n}\n\n/* return label or -1 if dead code */\nstatic int emit_goto(JSParseState *s, int opcode, int label)\n{\n    if (js_is_live_code(s)) {\n        if (label < 0)\n            label = new_label(s);\n        emit_op(s, opcode);\n        emit_u32(s, label);\n        s->cur_func->label_slots[label].ref_count++;\n        return label;\n    }\n    return -1;\n}\n\n/* return the constant pool index. 'val' is not duplicated. */\nstatic int cpool_add(JSParseState *s, JSValue val)\n{\n    JSFunctionDef *fd = s->cur_func;\n    \n    if (js_resize_array(s->ctx, (void *)&fd->cpool, sizeof(fd->cpool[0]),\n                        &fd->cpool_size, fd->cpool_count + 1))\n        return -1;\n    fd->cpool[fd->cpool_count++] = val;\n    return fd->cpool_count - 1;\n}\n\nstatic __exception int emit_push_const(JSParseState *s, JSValueConst val,\n                                       BOOL as_atom)\n{\n    int idx;\n\n    if (JS_VALUE_GET_TAG(val) == JS_TAG_STRING && as_atom) {\n        JSAtom atom;\n        /* warning: JS_NewAtomStr frees the string value */\n        JS_DupValue(s->ctx, val);\n        atom = JS_NewAtomStr(s->ctx, JS_VALUE_GET_STRING(val));\n        if (atom != JS_ATOM_NULL && !__JS_AtomIsTaggedInt(atom)) {\n            emit_op(s, OP_push_atom_value);\n            emit_u32(s, atom);\n            return 0;\n        }\n    }\n\n    idx = cpool_add(s, JS_DupValue(s->ctx, val));\n    if (idx < 0)\n        return -1;\n    emit_op(s, OP_push_const);\n    emit_u32(s, idx);\n    return 0;\n}\n\n/* return the variable index or -1 if not found,\n   add ARGUMENT_VAR_OFFSET for argument variables */\nstatic int find_arg(JSContext *ctx, JSFunctionDef *fd, JSAtom name)\n{\n    int i;\n    for(i = fd->arg_count; i-- > 0;) {\n        if (fd->args[i].var_name == name)\n            return i | ARGUMENT_VAR_OFFSET;\n    }\n    return -1;\n}\n\nstatic int find_var(JSContext *ctx, JSFunctionDef *fd, JSAtom name)\n{\n    int i;\n    for(i = fd->var_count; i-- > 0;) {\n        if (fd->vars[i].var_name == name && fd->vars[i].scope_level == 0)\n            return i;\n    }\n    return find_arg(ctx, fd, name);\n}\n\n/* find a variable declaration in a given scope */\nstatic int find_var_in_scope(JSContext *ctx, JSFunctionDef *fd,\n                             JSAtom name, int scope_level)\n{\n    int scope_idx;\n    for(scope_idx = fd->scopes[scope_level].first; scope_idx >= 0;\n        scope_idx = fd->vars[scope_idx].scope_next) {\n        if (fd->vars[scope_idx].scope_level != scope_level)\n            break;\n        if (fd->vars[scope_idx].var_name == name)\n            return scope_idx;\n    }\n    return -1;\n}\n\n/* return true if scope == parent_scope or if scope is a child of\n   parent_scope */\nstatic BOOL is_child_scope(JSContext *ctx, JSFunctionDef *fd,\n                           int scope, int parent_scope)\n{\n    while (scope >= 0) {\n        if (scope == parent_scope)\n            return TRUE;\n        scope = fd->scopes[scope].parent;\n    }\n    return FALSE;\n}\n\n/* find a 'var' declaration in the same scope or a child scope */\nstatic int find_var_in_child_scope(JSContext *ctx, JSFunctionDef *fd,\n                                   JSAtom name, int scope_level)\n{\n    int i;\n    for(i = 0; i < fd->var_count; i++) {\n        JSVarDef *vd = &fd->vars[i];\n        if (vd->var_name == name && vd->scope_level == 0) {\n            if (is_child_scope(ctx, fd, vd->scope_next,\n                               scope_level))\n                return i;\n        }\n    }\n    return -1;\n}\n\n\nstatic JSGlobalVar *find_global_var(JSFunctionDef *fd, JSAtom name)\n{\n    int i;\n    for(i = 0; i < fd->global_var_count; i++) {\n        JSGlobalVar *hf = &fd->global_vars[i];\n        if (hf->var_name == name)\n            return hf;\n    }\n    return NULL;\n\n}\n\nstatic JSGlobalVar *find_lexical_global_var(JSFunctionDef *fd, JSAtom name)\n{\n    JSGlobalVar *hf = find_global_var(fd, name);\n    if (hf && hf->is_lexical)\n        return hf;\n    else\n        return NULL;\n}\n\nstatic int find_lexical_decl(JSContext *ctx, JSFunctionDef *fd, JSAtom name,\n                             int scope_idx, BOOL check_catch_var)\n{\n    while (scope_idx >= 0) {\n        JSVarDef *vd = &fd->vars[scope_idx];\n        if (vd->var_name == name &&\n            (vd->is_lexical || (vd->var_kind == JS_VAR_CATCH &&\n                                check_catch_var)))\n            return scope_idx;\n        scope_idx = vd->scope_next;\n    }\n\n    if (fd->is_eval && fd->eval_type == JS_EVAL_TYPE_GLOBAL) {\n        if (find_lexical_global_var(fd, name))\n            return GLOBAL_VAR_OFFSET;\n    }\n    return -1;\n}\n\nstatic int push_scope(JSParseState *s) {\n    if (s->cur_func) {\n        JSFunctionDef *fd = s->cur_func;\n        int scope = fd->scope_count;\n        /* XXX: should check for scope overflow */\n        if ((fd->scope_count + 1) > fd->scope_size) {\n            int new_size;\n            size_t slack;\n            JSVarScope *new_buf;\n            /* XXX: potential arithmetic overflow */\n            new_size = max_int(fd->scope_count + 1, fd->scope_size * 3 / 2);\n            if (fd->scopes == fd->def_scope_array) {\n                new_buf = js_realloc2(s->ctx, NULL, new_size * sizeof(*fd->scopes), &slack);\n                if (!new_buf)\n                    return -1;\n                memcpy(new_buf, fd->scopes, fd->scope_count * sizeof(*fd->scopes));\n            } else {\n                new_buf = js_realloc2(s->ctx, fd->scopes, new_size * sizeof(*fd->scopes), &slack);\n                if (!new_buf)\n                    return -1;\n            }\n            new_size += slack / sizeof(*new_buf);\n            fd->scopes = new_buf;\n            fd->scope_size = new_size;\n        }\n        fd->scope_count++;\n        fd->scopes[scope].parent = fd->scope_level;\n        fd->scopes[scope].first = fd->scope_first;\n        emit_op(s, OP_enter_scope);\n        emit_u16(s, scope);\n        return fd->scope_level = scope;\n    }\n    return 0;\n}\n\nstatic int get_first_lexical_var(JSFunctionDef *fd, int scope)\n{\n    while (scope >= 0) {\n        int scope_idx = fd->scopes[scope].first;\n        if (scope_idx >= 0)\n            return scope_idx;\n        scope = fd->scopes[scope].parent;\n    }\n    return -1;\n}\n\nstatic void pop_scope(JSParseState *s) {\n    if (s->cur_func) {\n        /* disable scoped variables */\n        JSFunctionDef *fd = s->cur_func;\n        int scope = fd->scope_level;\n        emit_op(s, OP_leave_scope);\n        emit_u16(s, scope);\n        fd->scope_level = fd->scopes[scope].parent;\n        fd->scope_first = get_first_lexical_var(fd, fd->scope_level);\n    }\n}\n\nstatic void close_scopes(JSParseState *s, int scope, int scope_stop)\n{\n    while (scope > scope_stop) {\n        emit_op(s, OP_leave_scope);\n        emit_u16(s, scope);\n        scope = s->cur_func->scopes[scope].parent;\n    }\n}\n\n/* return the variable index or -1 if error */\nstatic int add_var(JSContext *ctx, JSFunctionDef *fd, JSAtom name)\n{\n    JSVarDef *vd;\n\n    /* the local variable indexes are currently stored on 16 bits */\n    if (fd->var_count >= JS_MAX_LOCAL_VARS) {\n        JS_ThrowInternalError(ctx, \"too many local variables\");\n        return -1;\n    }\n    if (js_resize_array(ctx, (void **)&fd->vars, sizeof(fd->vars[0]),\n                        &fd->var_size, fd->var_count + 1))\n        return -1;\n    vd = &fd->vars[fd->var_count++];\n    memset(vd, 0, sizeof(*vd));\n    vd->var_name = JS_DupAtom(ctx, name);\n    vd->func_pool_idx = -1;\n    return fd->var_count - 1;\n}\n\nstatic int add_scope_var(JSContext *ctx, JSFunctionDef *fd, JSAtom name,\n                         JSVarKindEnum var_kind)\n{\n    int idx = add_var(ctx, fd, name);\n    if (idx >= 0) {\n        JSVarDef *vd = &fd->vars[idx];\n        vd->var_kind = var_kind;\n        vd->scope_level = fd->scope_level;\n        vd->scope_next = fd->scope_first;\n        fd->scopes[fd->scope_level].first = idx;\n        fd->scope_first = idx;\n    }\n    return idx;\n}\n\nstatic int add_func_var(JSContext *ctx, JSFunctionDef *fd, JSAtom name)\n{\n    int idx = fd->func_var_idx;\n    if (idx < 0 && (idx = add_var(ctx, fd, name)) >= 0) {\n        fd->func_var_idx = idx;\n        fd->vars[idx].var_kind = JS_VAR_FUNCTION_NAME;\n        if (fd->js_mode & JS_MODE_STRICT)\n            fd->vars[idx].is_const = TRUE;\n    }\n    return idx;\n}\n\nstatic int add_arguments_var(JSContext *ctx, JSFunctionDef *fd)\n{\n    int idx = fd->arguments_var_idx;\n    if (idx < 0 && (idx = add_var(ctx, fd, JS_ATOM_arguments)) >= 0) {\n        fd->arguments_var_idx = idx;\n    }\n    return idx;\n}\n\n/* add an argument definition in the argument scope. Only needed when\n   \"eval()\" may be called in the argument scope. Return 0 if OK. */\nstatic int add_arguments_arg(JSContext *ctx, JSFunctionDef *fd)\n{\n    int idx;\n    if (fd->arguments_arg_idx < 0) {\n        idx = find_var_in_scope(ctx, fd, JS_ATOM_arguments, ARG_SCOPE_INDEX);\n        if (idx < 0) {\n            /* XXX: the scope links are not fully updated. May be an\n               issue if there are child scopes of the argument\n               scope */\n            idx = add_var(ctx, fd, JS_ATOM_arguments);\n            if (idx < 0)\n                return -1;\n            fd->vars[idx].scope_next = fd->scopes[ARG_SCOPE_INDEX].first;\n            fd->scopes[ARG_SCOPE_INDEX].first = idx;\n            fd->vars[idx].scope_level = ARG_SCOPE_INDEX;\n            fd->vars[idx].is_lexical = TRUE;\n\n            fd->arguments_arg_idx = idx;\n        }\n    }\n    return 0;\n}\n\nstatic int add_arg(JSContext *ctx, JSFunctionDef *fd, JSAtom name)\n{\n    JSVarDef *vd;\n\n    /* the local variable indexes are currently stored on 16 bits */\n    if (fd->arg_count >= JS_MAX_LOCAL_VARS) {\n        JS_ThrowInternalError(ctx, \"too many arguments\");\n        return -1;\n    }\n    if (js_resize_array(ctx, (void **)&fd->args, sizeof(fd->args[0]),\n                        &fd->arg_size, fd->arg_count + 1))\n        return -1;\n    vd = &fd->args[fd->arg_count++];\n    memset(vd, 0, sizeof(*vd));\n    vd->var_name = JS_DupAtom(ctx, name);\n    vd->func_pool_idx = -1;\n    return fd->arg_count - 1;\n}\n\n/* add a global variable definition */\nstatic JSGlobalVar *add_global_var(JSContext *ctx, JSFunctionDef *s,\n                                     JSAtom name)\n{\n    JSGlobalVar *hf;\n\n    if (js_resize_array(ctx, (void **)&s->global_vars,\n                        sizeof(s->global_vars[0]),\n                        &s->global_var_size, s->global_var_count + 1))\n        return NULL;\n    hf = &s->global_vars[s->global_var_count++];\n    hf->cpool_idx = -1;\n    hf->force_init = FALSE;\n    hf->is_lexical = FALSE;\n    hf->is_const = FALSE;\n    hf->scope_level = s->scope_level;\n    hf->var_name = JS_DupAtom(ctx, name);\n    return hf;\n}\n\ntypedef enum {\n    JS_VAR_DEF_WITH,\n    JS_VAR_DEF_LET,\n    JS_VAR_DEF_CONST,\n    JS_VAR_DEF_FUNCTION_DECL, /* function declaration */\n    JS_VAR_DEF_NEW_FUNCTION_DECL, /* async/generator function declaration */\n    JS_VAR_DEF_CATCH,\n    JS_VAR_DEF_VAR,\n} JSVarDefEnum;\n\nstatic int define_var(JSParseState *s, JSFunctionDef *fd, JSAtom name,\n                      JSVarDefEnum var_def_type)\n{\n    JSContext *ctx = s->ctx;\n    JSVarDef *vd;\n    int idx;\n\n    switch (var_def_type) {\n    case JS_VAR_DEF_WITH:\n        idx = add_scope_var(ctx, fd, name, JS_VAR_NORMAL);\n        break;\n\n    case JS_VAR_DEF_LET:\n    case JS_VAR_DEF_CONST:\n    case JS_VAR_DEF_FUNCTION_DECL:\n    case JS_VAR_DEF_NEW_FUNCTION_DECL:\n        idx = find_lexical_decl(ctx, fd, name, fd->scope_first, TRUE);\n        if (idx >= 0) {\n            if (idx < GLOBAL_VAR_OFFSET) {\n                if (fd->vars[idx].scope_level == fd->scope_level) {\n                    /* same scope: in non strict mode, functions\n                       can be redefined (annex B.3.3.4). */\n                    if (!(!(fd->js_mode & JS_MODE_STRICT) &&\n                          var_def_type == JS_VAR_DEF_FUNCTION_DECL &&\n                          fd->vars[idx].var_kind == JS_VAR_FUNCTION_DECL)) {\n                        goto redef_lex_error;\n                    }\n                } else if (fd->vars[idx].var_kind == JS_VAR_CATCH && (fd->vars[idx].scope_level + 2) == fd->scope_level) {\n                    goto redef_lex_error;\n                }\n            } else {\n                if (fd->scope_level == fd->body_scope) {\n                redef_lex_error:\n                    /* redefining a scoped var in the same scope: error */\n                    return js_parse_error(s, \"invalid redefinition of lexical identifier\");\n                }\n            }\n        }\n        if (var_def_type != JS_VAR_DEF_FUNCTION_DECL &&\n            var_def_type != JS_VAR_DEF_NEW_FUNCTION_DECL &&\n            fd->scope_level == fd->body_scope &&\n            find_arg(ctx, fd, name) >= 0) {\n            /* lexical variable redefines a parameter name */\n            return js_parse_error(s, \"invalid redefinition of parameter name\");\n        }\n\n        if (find_var_in_child_scope(ctx, fd, name, fd->scope_level) >= 0) {\n            return js_parse_error(s, \"invalid redefinition of a variable\");\n        }\n        \n        if (fd->is_global_var) {\n            JSGlobalVar *hf;\n            hf = find_global_var(fd, name);\n            if (hf && is_child_scope(ctx, fd, hf->scope_level,\n                                     fd->scope_level)) {\n                return js_parse_error(s, \"invalid redefinition of global identifier\");\n            }\n        }\n        \n        if (fd->is_eval &&\n            (fd->eval_type == JS_EVAL_TYPE_GLOBAL ||\n             fd->eval_type == JS_EVAL_TYPE_MODULE) &&\n            fd->scope_level == fd->body_scope) {\n            JSGlobalVar *hf;\n            hf = add_global_var(s->ctx, fd, name);\n            if (!hf)\n                return -1;\n            hf->is_lexical = TRUE;\n            hf->is_const = (var_def_type == JS_VAR_DEF_CONST);\n            idx = GLOBAL_VAR_OFFSET;\n        } else {\n            JSVarKindEnum var_kind;\n            if (var_def_type == JS_VAR_DEF_FUNCTION_DECL)\n                var_kind = JS_VAR_FUNCTION_DECL;\n            else if (var_def_type == JS_VAR_DEF_NEW_FUNCTION_DECL)\n                var_kind = JS_VAR_NEW_FUNCTION_DECL;\n            else\n                var_kind = JS_VAR_NORMAL;\n            idx = add_scope_var(ctx, fd, name, var_kind);\n            if (idx >= 0) {\n                vd = &fd->vars[idx];\n                vd->is_lexical = 1;\n                vd->is_const = (var_def_type == JS_VAR_DEF_CONST);\n            }\n        }\n        break;\n\n    case JS_VAR_DEF_CATCH:\n        idx = add_scope_var(ctx, fd, name, JS_VAR_CATCH);\n        break;\n\n    case JS_VAR_DEF_VAR:\n        if (find_lexical_decl(ctx, fd, name, fd->scope_first,\n                              FALSE) >= 0) {\n       invalid_lexical_redefinition:\n            /* error to redefine a var that inside a lexical scope */\n            return js_parse_error(s, \"invalid redefinition of lexical identifier\");\n        }\n        if (fd->is_global_var) {\n            JSGlobalVar *hf;\n            hf = find_global_var(fd, name);\n            if (hf && hf->is_lexical && hf->scope_level == fd->scope_level &&\n                fd->eval_type == JS_EVAL_TYPE_MODULE) {\n                goto invalid_lexical_redefinition;\n            }\n            hf = add_global_var(s->ctx, fd, name);\n            if (!hf)\n                return -1;\n            idx = GLOBAL_VAR_OFFSET;\n        } else {\n            /* if the variable already exists, don't add it again  */\n            idx = find_var(ctx, fd, name);\n            if (idx >= 0)\n                break;\n            idx = add_var(ctx, fd, name);\n            if (idx >= 0) {\n                if (name == JS_ATOM_arguments && fd->has_arguments_binding)\n                    fd->arguments_var_idx = idx;\n                fd->vars[idx].scope_next = fd->scope_level;\n            }\n        }\n        break;\n    default:\n        abort();\n    }\n    return idx;\n}\n\n/* add a private field variable in the current scope */\nstatic int add_private_class_field(JSParseState *s, JSFunctionDef *fd,\n                                   JSAtom name, JSVarKindEnum var_kind)\n{\n    JSContext *ctx = s->ctx;\n    JSVarDef *vd;\n    int idx;\n\n    idx = add_scope_var(ctx, fd, name, var_kind);\n    if (idx < 0)\n        return idx;\n    vd = &fd->vars[idx];\n    vd->is_lexical = 1;\n    vd->is_const = 1;\n    return idx;\n}\n\nstatic __exception int js_parse_expr(JSParseState *s);\nstatic __exception int js_parse_function_decl(JSParseState *s,\n                                              JSParseFunctionEnum func_type,\n                                              JSFunctionKindEnum func_kind,\n                                              JSAtom func_name, const uint8_t *ptr,\n                                              int start_line);\nstatic JSFunctionDef *js_parse_function_class_fields_init(JSParseState *s);\nstatic __exception int js_parse_function_decl2(JSParseState *s,\n                                               JSParseFunctionEnum func_type,\n                                               JSFunctionKindEnum func_kind,\n                                               JSAtom func_name,\n                                               const uint8_t *ptr,\n                                               int function_line_num,\n                                               JSParseExportEnum export_flag,\n                                               JSFunctionDef **pfd);\nstatic __exception int js_parse_assign_expr2(JSParseState *s, int parse_flags);\nstatic __exception int js_parse_assign_expr(JSParseState *s);\nstatic __exception int js_parse_unary(JSParseState *s, int parse_flags);\nstatic void push_break_entry(JSFunctionDef *fd, BlockEnv *be,\n                             JSAtom label_name,\n                             int label_break, int label_cont,\n                             int drop_count);\nstatic void pop_break_entry(JSFunctionDef *fd);\nstatic JSExportEntry *add_export_entry(JSParseState *s, JSModuleDef *m,\n                                       JSAtom local_name, JSAtom export_name,\n                                       JSExportTypeEnum export_type);\n\n/* Note: all the fields are already sealed except length */\nstatic int seal_template_obj(JSContext *ctx, JSValueConst obj)\n{\n    JSObject *p;\n    JSShapeProperty *prs;\n\n    p = JS_VALUE_GET_OBJ(obj);\n    prs = find_own_property1(p, JS_ATOM_length);\n    if (prs) {\n        if (js_update_property_flags(ctx, p, &prs,\n                                     prs->flags & ~(JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)))\n            return -1;\n    }\n    p->extensible = FALSE;\n    return 0;\n}\n\nstatic __exception int js_parse_template(JSParseState *s, int call, int *argc)\n{\n    JSContext *ctx = s->ctx;\n    JSValue raw_array, template_object;\n    JSToken cooked;\n    int depth, ret;\n\n    raw_array = JS_UNDEFINED; /* avoid warning */\n    template_object = JS_UNDEFINED; /* avoid warning */\n    if (call) {\n        /* Create a template object: an array of cooked strings */\n        /* Create an array of raw strings and store it to the raw property */\n        template_object = JS_NewArray(ctx);\n        if (JS_IsException(template_object))\n            return -1;\n        //        pool_idx = s->cur_func->cpool_count;\n        ret = emit_push_const(s, template_object, 0);\n        JS_FreeValue(ctx, template_object);\n        if (ret)\n            return -1;\n        raw_array = JS_NewArray(ctx);\n        if (JS_IsException(raw_array))\n            return -1;\n        if (JS_DefinePropertyValue(ctx, template_object, JS_ATOM_raw,\n                                   raw_array, JS_PROP_THROW) < 0) {\n            return -1;\n        }\n    }\n\n    depth = 0;\n    while (s->token.val == TOK_TEMPLATE) {\n        const uint8_t *p = s->token.ptr + 1;\n        cooked = s->token;\n        if (call) {\n            if (JS_DefinePropertyValueUint32(ctx, raw_array, depth,\n                                             JS_DupValue(ctx, s->token.u.str.str),\n                                             JS_PROP_ENUMERABLE | JS_PROP_THROW) < 0) {\n                return -1;\n            }\n            /* re-parse the string with escape sequences but do not throw a\n               syntax error if it contains invalid sequences\n             */\n            if (js_parse_string(s, '`', FALSE, p, &cooked, &p)) {\n                cooked.u.str.str = JS_UNDEFINED;\n            }\n            if (JS_DefinePropertyValueUint32(ctx, template_object, depth,\n                                             cooked.u.str.str,\n                                             JS_PROP_ENUMERABLE | JS_PROP_THROW) < 0) {\n                return -1;\n            }\n        } else {\n            JSString *str;\n            /* re-parse the string with escape sequences and throw a\n               syntax error if it contains invalid sequences\n             */\n            JS_FreeValue(ctx, s->token.u.str.str);\n            s->token.u.str.str = JS_UNDEFINED;\n            if (js_parse_string(s, '`', TRUE, p, &cooked, &p))\n                return -1;\n            str = JS_VALUE_GET_STRING(cooked.u.str.str);\n            if (str->len != 0 || depth == 0) {\n                ret = emit_push_const(s, cooked.u.str.str, 1);\n                JS_FreeValue(s->ctx, cooked.u.str.str);\n                if (ret)\n                    return -1;\n                if (depth == 0) {\n                    if (s->token.u.str.sep == '`')\n                        goto done1;\n                    emit_op(s, OP_get_field2);\n                    emit_atom(s, JS_ATOM_concat);\n                }\n                depth++;\n            } else {\n                JS_FreeValue(s->ctx, cooked.u.str.str);\n            }\n        }\n        if (s->token.u.str.sep == '`')\n            goto done;\n        if (next_token(s))\n            return -1;\n        if (js_parse_expr(s))\n            return -1;\n        depth++;\n        if (s->token.val != '}') {\n            return js_parse_error(s, \"expected '}' after template expression\");\n        }\n        /* XXX: should convert to string at this stage? */\n        free_token(s, &s->token);\n        /* Resume TOK_TEMPLATE parsing (s->token.line_num and\n         * s->token.ptr are OK) */\n        s->got_lf = FALSE;\n        s->last_line_num = s->token.line_num;\n        if (js_parse_template_part(s, s->buf_ptr))\n            return -1;\n    }\n    return js_parse_expect(s, TOK_TEMPLATE);\n\n done:\n    if (call) {\n        /* Seal the objects */\n        seal_template_obj(ctx, raw_array);\n        seal_template_obj(ctx, template_object);\n        *argc = depth + 1;\n    } else {\n        emit_op(s, OP_call_method);\n        emit_u16(s, depth - 1);\n    }\n done1:\n    return next_token(s);\n}\n\n\n#define PROP_TYPE_IDENT 0\n#define PROP_TYPE_VAR   1\n#define PROP_TYPE_GET   2\n#define PROP_TYPE_SET   3\n#define PROP_TYPE_STAR  4\n#define PROP_TYPE_ASYNC 5\n#define PROP_TYPE_ASYNC_STAR 6\n\n#define PROP_TYPE_PRIVATE (1 << 4)\n\nstatic BOOL token_is_ident(int tok)\n{\n    /* Accept keywords and reserved words as property names */\n    return (tok == TOK_IDENT ||\n            (tok >= TOK_FIRST_KEYWORD &&\n             tok <= TOK_LAST_KEYWORD));\n}\n\n/* if the property is an expression, name = JS_ATOM_NULL */\nstatic int __exception js_parse_property_name(JSParseState *s,\n                                              JSAtom *pname,\n                                              BOOL allow_method, BOOL allow_var,\n                                              BOOL allow_private)\n{\n    int is_private = 0;\n    BOOL is_non_reserved_ident;\n    JSAtom name;\n    int prop_type;\n    \n    prop_type = PROP_TYPE_IDENT;\n    if (allow_method) {\n        if (token_is_pseudo_keyword(s, JS_ATOM_get)\n        ||  token_is_pseudo_keyword(s, JS_ATOM_set)) {\n            /* get x(), set x() */\n            name = JS_DupAtom(s->ctx, s->token.u.ident.atom);\n            if (next_token(s))\n                goto fail1;\n            if (s->token.val == ':' || s->token.val == ',' ||\n                s->token.val == '}' || s->token.val == '(') {\n                is_non_reserved_ident = TRUE;\n                goto ident_found;\n            }\n            prop_type = PROP_TYPE_GET + (name == JS_ATOM_set);\n            JS_FreeAtom(s->ctx, name);\n        } else if (s->token.val == '*') {\n            if (next_token(s))\n                goto fail;\n            prop_type = PROP_TYPE_STAR;\n        } else if (token_is_pseudo_keyword(s, JS_ATOM_async) &&\n                   peek_token(s, TRUE) != '\\n') {\n            name = JS_DupAtom(s->ctx, s->token.u.ident.atom);\n            if (next_token(s))\n                goto fail1;\n            if (s->token.val == ':' || s->token.val == ',' ||\n                s->token.val == '}' || s->token.val == '(') {\n                is_non_reserved_ident = TRUE;\n                goto ident_found;\n            }\n            JS_FreeAtom(s->ctx, name);\n            if (s->token.val == '*') {\n                if (next_token(s))\n                    goto fail;\n                prop_type = PROP_TYPE_ASYNC_STAR;\n            } else {\n                prop_type = PROP_TYPE_ASYNC;\n            }\n        }\n    }\n\n    if (token_is_ident(s->token.val)) {\n        /* variable can only be a non-reserved identifier */\n        is_non_reserved_ident =\n            (s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved);\n        /* keywords and reserved words have a valid atom */\n        name = JS_DupAtom(s->ctx, s->token.u.ident.atom);\n        if (next_token(s))\n            goto fail1;\n    ident_found:\n        if (is_non_reserved_ident &&\n            prop_type == PROP_TYPE_IDENT && allow_var) {\n            if (!(s->token.val == ':' ||\n                  (s->token.val == '(' && allow_method))) {\n                prop_type = PROP_TYPE_VAR;\n            }\n        }\n    } else if (s->token.val == TOK_STRING) {\n        name = JS_ValueToAtom(s->ctx, s->token.u.str.str);\n        if (name == JS_ATOM_NULL)\n            goto fail;\n        if (next_token(s))\n            goto fail1;\n    } else if (s->token.val == TOK_NUMBER) {\n        JSValue val;\n        val = s->token.u.num.val;\n#ifdef CONFIG_BIGNUM\n        if (JS_VALUE_GET_TAG(val) == JS_TAG_BIG_FLOAT) {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            val = s->ctx->rt->bigfloat_ops.\n                mul_pow10_to_float64(s->ctx, &p->num,\n                                     s->token.u.num.exponent);\n            if (JS_IsException(val))\n                goto fail;\n            name = JS_ValueToAtom(s->ctx, val);\n            JS_FreeValue(s->ctx, val);\n        } else\n#endif\n        {\n            name = JS_ValueToAtom(s->ctx, val);\n        }\n        if (name == JS_ATOM_NULL)\n            goto fail;\n        if (next_token(s))\n            goto fail1;\n    } else if (s->token.val == '[') {\n        if (next_token(s))\n            goto fail;\n        if (js_parse_expr(s))\n            goto fail;\n        if (js_parse_expect(s, ']'))\n            goto fail;\n        name = JS_ATOM_NULL;\n    } else if (s->token.val == TOK_PRIVATE_NAME && allow_private) {\n        name = JS_DupAtom(s->ctx, s->token.u.ident.atom);\n        if (next_token(s))\n            goto fail1;\n        is_private = PROP_TYPE_PRIVATE;\n    } else {\n        goto invalid_prop;\n    }\n    if (prop_type != PROP_TYPE_IDENT && prop_type != PROP_TYPE_VAR &&\n        s->token.val != '(') {\n        JS_FreeAtom(s->ctx, name);\n    invalid_prop:\n        js_parse_error(s, \"invalid property name\");\n        goto fail;\n    }\n    *pname = name;\n    return prop_type | is_private;\n fail1:\n    JS_FreeAtom(s->ctx, name);\n fail:\n    *pname = JS_ATOM_NULL;\n    return -1;\n}\n\ntypedef struct JSParsePos {\n    int last_line_num;\n    int line_num;\n    BOOL got_lf;\n    const uint8_t *ptr;\n} JSParsePos;\n\nstatic int js_parse_get_pos(JSParseState *s, JSParsePos *sp)\n{\n    sp->last_line_num = s->last_line_num;\n    sp->line_num = s->token.line_num;\n    sp->ptr = s->token.ptr;\n    sp->got_lf = s->got_lf;\n    return 0;\n}\n\nstatic __exception int js_parse_seek_token(JSParseState *s, const JSParsePos *sp)\n{\n    s->token.line_num = sp->last_line_num;\n    s->line_num = sp->line_num;\n    s->buf_ptr = sp->ptr;\n    s->got_lf = sp->got_lf;\n    return next_token(s);\n}\n\n/* return TRUE if a regexp literal is allowed after this token */\nstatic BOOL is_regexp_allowed(int tok)\n{\n    switch (tok) {\n    case TOK_NUMBER:\n    case TOK_STRING:\n    case TOK_REGEXP:\n    case TOK_DEC:\n    case TOK_INC:\n    case TOK_NULL:\n    case TOK_FALSE:\n    case TOK_TRUE:\n    case TOK_THIS:\n    case ')':\n    case ']':\n    case '}': /* XXX: regexp may occur after */\n    case TOK_IDENT:\n        return FALSE;\n    default:\n        return TRUE;\n    }\n}\n\n#define SKIP_HAS_SEMI       (1 << 0)\n#define SKIP_HAS_ELLIPSIS   (1 << 1)\n#define SKIP_HAS_ASSIGNMENT (1 << 2)\n\n/* XXX: improve speed with early bailout */\n/* XXX: no longer works if regexps are present. Could use previous\n   regexp parsing heuristics to handle most cases */\nstatic int js_parse_skip_parens_token(JSParseState *s, int *pbits, BOOL no_line_terminator)\n{\n    char state[256];\n    size_t level = 0;\n    JSParsePos pos;\n    int last_tok, tok = TOK_EOF;\n    int c, tok_len, bits = 0;\n\n    /* protect from underflow */\n    state[level++] = 0;\n\n    js_parse_get_pos(s, &pos);\n    last_tok = 0;\n    for (;;) {\n        switch(s->token.val) {\n        case '(':\n        case '[':\n        case '{':\n            if (level >= sizeof(state))\n                goto done;\n            state[level++] = s->token.val;\n            break;\n        case ')':\n            if (state[--level] != '(')\n                goto done;\n            break;\n        case ']':\n            if (state[--level] != '[')\n                goto done;\n            break;\n        case '}':\n            c = state[--level];\n            if (c == '`') {\n                /* continue the parsing of the template */\n                free_token(s, &s->token);\n                /* Resume TOK_TEMPLATE parsing (s->token.line_num and\n                 * s->token.ptr are OK) */\n                s->got_lf = FALSE;\n                s->last_line_num = s->token.line_num;\n                if (js_parse_template_part(s, s->buf_ptr))\n                    goto done;\n                goto handle_template;\n            } else if (c != '{') {\n                goto done;\n            }\n            break;\n        case TOK_TEMPLATE:\n        handle_template:\n            if (s->token.u.str.sep != '`') {\n                /* '${' inside the template : closing '}' and continue\n                   parsing the template */\n                if (level >= sizeof(state))\n                    goto done;\n                state[level++] = '`';\n            } \n            break;\n        case TOK_EOF:\n            goto done;\n        case ';':\n            if (level == 2) {\n                bits |= SKIP_HAS_SEMI;\n            }\n            break;\n        case TOK_ELLIPSIS:\n            if (level == 2) {\n                bits |= SKIP_HAS_ELLIPSIS;\n            }\n            break;\n        case '=':\n            bits |= SKIP_HAS_ASSIGNMENT;\n            break;\n            \n        case TOK_DIV_ASSIGN:\n            tok_len = 2;\n            goto parse_regexp;\n        case '/':\n            tok_len = 1;\n        parse_regexp:\n            if (is_regexp_allowed(last_tok)) {\n                s->buf_ptr -= tok_len;\n                if (js_parse_regexp(s)) {\n                    /* XXX: should clear the exception */\n                    goto done;\n                }\n            }\n            break;\n        }\n        /* last_tok is only used to recognize regexps */\n        if (s->token.val == TOK_IDENT &&\n            (token_is_pseudo_keyword(s, JS_ATOM_of) ||\n             token_is_pseudo_keyword(s, JS_ATOM_yield))) {\n            last_tok = TOK_OF;\n        } else {\n            last_tok = s->token.val;\n        }\n        if (next_token(s)) {\n            /* XXX: should clear the exception generated by next_token() */\n            break;\n        }\n        if (level <= 1) {\n            tok = s->token.val;\n            if (token_is_pseudo_keyword(s, JS_ATOM_of))\n                tok = TOK_OF;\n            if (no_line_terminator && s->last_line_num != s->token.line_num)\n                tok = '\\n';\n            break;\n        }\n    }\n done:\n    if (pbits) {\n        *pbits = bits;\n    }\n    if (js_parse_seek_token(s, &pos))\n        return -1;\n    return tok;\n}\n\nstatic void set_object_name(JSParseState *s, JSAtom name)\n{\n    JSFunctionDef *fd = s->cur_func;\n    int opcode;\n\n    opcode = get_prev_opcode(fd);\n    if (opcode == OP_set_name) {\n        /* XXX: should free atom after OP_set_name? */\n        fd->byte_code.size = fd->last_opcode_pos;\n        fd->last_opcode_pos = -1;\n        emit_op(s, OP_set_name);\n        emit_atom(s, name);\n    } else if (opcode == OP_set_class_name) {\n        int define_class_pos;\n        JSAtom atom;\n        define_class_pos = fd->last_opcode_pos + 1 -\n            get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);\n        assert(fd->byte_code.buf[define_class_pos] == OP_define_class);\n        /* for consistency we free the previous atom which is\n           JS_ATOM_empty_string */\n        atom = get_u32(fd->byte_code.buf + define_class_pos + 1);\n        JS_FreeAtom(s->ctx, atom);\n        put_u32(fd->byte_code.buf + define_class_pos + 1,\n                JS_DupAtom(s->ctx, name));\n        fd->last_opcode_pos = -1;\n    }\n}\n\nstatic void set_object_name_computed(JSParseState *s)\n{\n    JSFunctionDef *fd = s->cur_func;\n    int opcode;\n\n    opcode = get_prev_opcode(fd);\n    if (opcode == OP_set_name) {\n        /* XXX: should free atom after OP_set_name? */\n        fd->byte_code.size = fd->last_opcode_pos;\n        fd->last_opcode_pos = -1;\n        emit_op(s, OP_set_name_computed);\n    } else if (opcode == OP_set_class_name) {\n        int define_class_pos;\n        define_class_pos = fd->last_opcode_pos + 1 -\n            get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);\n        assert(fd->byte_code.buf[define_class_pos] == OP_define_class);\n        fd->byte_code.buf[define_class_pos] = OP_define_class_computed;\n        fd->last_opcode_pos = -1;\n    }\n}\n\nstatic __exception int js_parse_object_literal(JSParseState *s)\n{\n    JSAtom name = JS_ATOM_NULL;\n    const uint8_t *start_ptr;\n    int start_line, prop_type;\n    BOOL has_proto;\n\n    if (next_token(s))\n        goto fail;\n    /* XXX: add an initial length that will be patched back */\n    emit_op(s, OP_object);\n    has_proto = FALSE;\n    while (s->token.val != '}') {\n        /* specific case for getter/setter */\n        start_ptr = s->token.ptr;\n        start_line = s->token.line_num;\n\n        if (s->token.val == TOK_ELLIPSIS) {\n            if (next_token(s))\n                return -1;\n            if (js_parse_assign_expr(s))\n                return -1;\n            emit_op(s, OP_null);  /* dummy excludeList */\n            emit_op(s, OP_copy_data_properties);\n            emit_u8(s, 2 | (1 << 2) | (0 << 5));\n            emit_op(s, OP_drop); /* pop excludeList */\n            emit_op(s, OP_drop); /* pop src object */\n            goto next;\n        }\n\n        prop_type = js_parse_property_name(s, &name, TRUE, TRUE, FALSE);\n        if (prop_type < 0)\n            goto fail;\n\n        if (prop_type == PROP_TYPE_VAR) {\n            /* shortcut for x: x */\n            emit_op(s, OP_scope_get_var);\n            emit_atom(s, name);\n            emit_u16(s, s->cur_func->scope_level);\n            emit_op(s, OP_define_field);\n            emit_atom(s, name);\n        } else if (s->token.val == '(') {\n            BOOL is_getset = (prop_type == PROP_TYPE_GET ||\n                              prop_type == PROP_TYPE_SET);\n            JSParseFunctionEnum func_type;\n            JSFunctionKindEnum func_kind;\n            int op_flags;\n\n            func_kind = JS_FUNC_NORMAL;\n            if (is_getset) {\n                func_type = JS_PARSE_FUNC_GETTER + prop_type - PROP_TYPE_GET;\n            } else {\n                func_type = JS_PARSE_FUNC_METHOD;\n                if (prop_type == PROP_TYPE_STAR)\n                    func_kind = JS_FUNC_GENERATOR;\n                else if (prop_type == PROP_TYPE_ASYNC)\n                    func_kind = JS_FUNC_ASYNC;\n                else if (prop_type == PROP_TYPE_ASYNC_STAR)\n                    func_kind = JS_FUNC_ASYNC_GENERATOR;\n            }\n            if (js_parse_function_decl(s, func_type, func_kind, JS_ATOM_NULL,\n                                       start_ptr, start_line))\n                goto fail;\n            if (name == JS_ATOM_NULL) {\n                emit_op(s, OP_define_method_computed);\n            } else {\n                emit_op(s, OP_define_method);\n                emit_atom(s, name);\n            }\n            if (is_getset) {\n                op_flags = OP_DEFINE_METHOD_GETTER +\n                    prop_type - PROP_TYPE_GET;\n            } else {\n                op_flags = OP_DEFINE_METHOD_METHOD;\n            }\n            emit_u8(s, op_flags | OP_DEFINE_METHOD_ENUMERABLE);\n        } else {\n            if (js_parse_expect(s, ':'))\n                goto fail;\n            if (js_parse_assign_expr(s))\n                goto fail;\n            if (name == JS_ATOM_NULL) {\n                set_object_name_computed(s);\n                emit_op(s, OP_define_array_el);\n                emit_op(s, OP_drop);\n            } else if (name == JS_ATOM___proto__) {\n                if (has_proto) {\n                    js_parse_error(s, \"duplicate __proto__ property name\");\n                    goto fail;\n                }\n                emit_op(s, OP_set_proto);\n                has_proto = TRUE;\n            } else {\n                set_object_name(s, name);\n                emit_op(s, OP_define_field);\n                emit_atom(s, name);\n            }\n        }\n        JS_FreeAtom(s->ctx, name);\n    next:\n        name = JS_ATOM_NULL;\n        if (s->token.val != ',')\n            break;\n        if (next_token(s))\n            goto fail;\n    }\n    if (js_parse_expect(s, '}'))\n        goto fail;\n    return 0;\n fail:\n    JS_FreeAtom(s->ctx, name);\n    return -1;\n}\n\n/* allow the 'in' binary operator */\n#define PF_IN_ACCEPTED  (1 << 0) \n/* allow function calls parsing in js_parse_postfix_expr() */\n#define PF_POSTFIX_CALL (1 << 1) \n/* allow arrow functions parsing in js_parse_postfix_expr() */\n#define PF_ARROW_FUNC   (1 << 2) \n/* allow the exponentiation operator in js_parse_unary() */\n#define PF_POW_ALLOWED  (1 << 3) \n/* forbid the exponentiation operator in js_parse_unary() */\n#define PF_POW_FORBIDDEN (1 << 4) \n\nstatic __exception int js_parse_postfix_expr(JSParseState *s, int parse_flags);\n\nstatic __exception int js_parse_left_hand_side_expr(JSParseState *s)\n{\n    return js_parse_postfix_expr(s, PF_POSTFIX_CALL);\n}\n\n/* XXX: could generate specific bytecode */\nstatic __exception int js_parse_class_default_ctor(JSParseState *s,\n                                                   BOOL has_super,\n                                                   JSFunctionDef **pfd)\n{\n    JSParsePos pos;\n    const char *str;\n    int ret, line_num;\n    JSParseFunctionEnum func_type;\n    const uint8_t *saved_buf_end;\n    \n    js_parse_get_pos(s, &pos);\n    if (has_super) {\n        /* spec change: no argument evaluation */\n        str = \"(){super(...arguments);}\";\n        func_type = JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR;\n    } else {\n        str = \"(){}\";\n        func_type = JS_PARSE_FUNC_CLASS_CONSTRUCTOR;\n    }\n    line_num = s->token.line_num;\n    saved_buf_end = s->buf_end;\n    s->buf_ptr = (uint8_t *)str;\n    s->buf_end = (uint8_t *)(str + strlen(str));\n    ret = next_token(s);\n    if (!ret) {\n        ret = js_parse_function_decl2(s, func_type, JS_FUNC_NORMAL,\n                                      JS_ATOM_NULL, (uint8_t *)str,\n                                      line_num, JS_PARSE_EXPORT_NONE, pfd);\n    }\n    s->buf_end = saved_buf_end;\n    ret |= js_parse_seek_token(s, &pos);\n    return ret;\n}\n\n/* find field in the current scope */\nstatic int find_private_class_field(JSContext *ctx, JSFunctionDef *fd,\n                                    JSAtom name, int scope_level)\n{\n    int idx;\n    idx = fd->scopes[scope_level].first;\n    while (idx != -1) {\n        if (fd->vars[idx].scope_level != scope_level)\n            break;\n        if (fd->vars[idx].var_name == name)\n            return idx;\n        idx = fd->vars[idx].scope_next;\n    }\n    return -1;\n}\n\n/* initialize the class fields, called by the constructor. Note:\n   super() can be called in an arrow function, so <this> and\n   <class_fields_init> can be variable references */\nstatic void emit_class_field_init(JSParseState *s)\n{\n    int label_next;\n    \n    emit_op(s, OP_scope_get_var);\n    emit_atom(s, JS_ATOM_class_fields_init);\n    emit_u16(s, s->cur_func->scope_level);\n\n    /* no need to call the class field initializer if not defined */\n    emit_op(s, OP_dup);\n    label_next = emit_goto(s, OP_if_false, -1);\n    \n    emit_op(s, OP_scope_get_var);\n    emit_atom(s, JS_ATOM_this);\n    emit_u16(s, 0);\n    \n    emit_op(s, OP_swap);\n    \n    emit_op(s, OP_call_method);\n    emit_u16(s, 0);\n\n    emit_label(s, label_next);\n    emit_op(s, OP_drop);\n}\n\n/* build a private setter function name from the private getter name */\nstatic JSAtom get_private_setter_name(JSContext *ctx, JSAtom name)\n{\n    return js_atom_concat_str(ctx, name, \"<set>\");\n}\n\ntypedef struct {\n    JSFunctionDef *fields_init_fd;\n    int computed_fields_count;\n    BOOL has_brand;\n    int brand_push_pos;\n} ClassFieldsDef;\n\nstatic __exception int emit_class_init_start(JSParseState *s,\n                                             ClassFieldsDef *cf)\n{\n    int label_add_brand;\n    \n    cf->fields_init_fd = js_parse_function_class_fields_init(s);\n    if (!cf->fields_init_fd)\n        return -1;\n\n    s->cur_func = cf->fields_init_fd;\n    \n    /* XXX: would be better to add the code only if needed, maybe in a\n       later pass */\n    emit_op(s, OP_push_false); /* will be patched later */\n    cf->brand_push_pos = cf->fields_init_fd->last_opcode_pos;\n    label_add_brand = emit_goto(s, OP_if_false, -1);\n    \n    emit_op(s, OP_scope_get_var);\n    emit_atom(s, JS_ATOM_this);\n    emit_u16(s, 0);\n    \n    emit_op(s, OP_scope_get_var);\n    emit_atom(s, JS_ATOM_home_object);\n    emit_u16(s, 0);\n    \n    emit_op(s, OP_add_brand);\n    \n    emit_label(s, label_add_brand);\n\n    s->cur_func = s->cur_func->parent;\n    return 0;\n}\n\nstatic __exception int add_brand(JSParseState *s, ClassFieldsDef *cf)\n{\n    if (!cf->has_brand) {\n        /* define the brand field in 'this' of the initializer */\n        if (!cf->fields_init_fd) {\n            if (emit_class_init_start(s, cf))\n                return -1;\n        }\n        /* patch the start of the function to enable the OP_add_brand code */\n        cf->fields_init_fd->byte_code.buf[cf->brand_push_pos] = OP_push_true;\n        \n        cf->has_brand = TRUE;\n    }\n    return 0;\n}\n\nstatic void emit_class_init_end(JSParseState *s, ClassFieldsDef *cf)\n{\n    int cpool_idx;\n        \n    s->cur_func = cf->fields_init_fd;\n    emit_op(s, OP_return_undef);\n    s->cur_func = s->cur_func->parent;\n    \n    cpool_idx = cpool_add(s, JS_NULL);\n    cf->fields_init_fd->parent_cpool_idx = cpool_idx;\n    emit_op(s, OP_fclosure);\n    emit_u32(s, cpool_idx);\n    emit_op(s, OP_set_home_object);\n}\n\n\nstatic __exception int js_parse_class(JSParseState *s, BOOL is_class_expr,\n                                      JSParseExportEnum export_flag)\n{\n    JSContext *ctx = s->ctx;\n    JSFunctionDef *fd = s->cur_func;\n    JSAtom name = JS_ATOM_NULL, class_name = JS_ATOM_NULL, class_name1;\n    JSAtom class_var_name = JS_ATOM_NULL;\n    JSFunctionDef *method_fd, *ctor_fd;\n    int saved_js_mode, class_name_var_idx, prop_type, ctor_cpool_offset;\n    int class_flags = 0, i, define_class_offset;\n    BOOL is_static, is_private;\n    const uint8_t *class_start_ptr = s->token.ptr;\n    const uint8_t *start_ptr;\n    ClassFieldsDef class_fields[2];\n        \n    /* classes are parsed and executed in strict mode */\n    saved_js_mode = fd->js_mode;\n    fd->js_mode |= JS_MODE_STRICT;\n    if (next_token(s))\n        goto fail;\n    if (s->token.val == TOK_IDENT) {\n        if (s->token.u.ident.is_reserved) {\n            js_parse_error_reserved_identifier(s);\n            goto fail;\n        }\n        class_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n        if (next_token(s))\n            goto fail;\n    } else if (!is_class_expr && export_flag != JS_PARSE_EXPORT_DEFAULT) {\n        js_parse_error(s, \"class statement requires a name\");\n        goto fail;\n    }\n    if (!is_class_expr) {\n        if (class_name == JS_ATOM_NULL)\n            class_var_name = JS_ATOM__default_; /* export default */\n        else\n            class_var_name = class_name;\n        class_var_name = JS_DupAtom(ctx, class_var_name);\n    }\n\n    push_scope(s);\n\n    if (s->token.val == TOK_EXTENDS) {\n        class_flags = JS_DEFINE_CLASS_HAS_HERITAGE;\n        if (next_token(s))\n            goto fail;\n        if (js_parse_left_hand_side_expr(s))\n            goto fail;\n    } else {\n        emit_op(s, OP_undefined);\n    }\n\n    /* add a 'const' definition for the class name */\n    if (class_name != JS_ATOM_NULL) {\n        class_name_var_idx = define_var(s, fd, class_name, JS_VAR_DEF_CONST);\n        if (class_name_var_idx < 0)\n            goto fail;\n    }\n\n    if (js_parse_expect(s, '{'))\n        goto fail;\n\n    /* this scope contains the private fields */\n    push_scope(s);\n\n    emit_op(s, OP_push_const);\n    ctor_cpool_offset = fd->byte_code.size;\n    emit_u32(s, 0); /* will be patched at the end of the class parsing */\n\n    if (class_name == JS_ATOM_NULL) {\n        if (class_var_name != JS_ATOM_NULL)\n            class_name1 = JS_ATOM_default;\n        else\n            class_name1 = JS_ATOM_empty_string;\n    } else {\n        class_name1 = class_name;\n    }\n    \n    emit_op(s, OP_define_class);\n    emit_atom(s, class_name1);\n    emit_u8(s, class_flags);\n    define_class_offset = fd->last_opcode_pos;\n\n    for(i = 0; i < 2; i++) {\n        ClassFieldsDef *cf = &class_fields[i];\n        cf->fields_init_fd = NULL;\n        cf->computed_fields_count = 0;\n        cf->has_brand = FALSE;\n    }\n    \n    ctor_fd = NULL;\n    while (s->token.val != '}') {\n        if (s->token.val == ';') {\n            if (next_token(s))\n                goto fail;\n            continue;\n        }\n        is_static = (s->token.val == TOK_STATIC);\n        prop_type = -1;\n        if (is_static) {\n            if (next_token(s))\n                goto fail;\n            /* allow \"static\" field name */\n            if (s->token.val == ';' || s->token.val == '=') {\n                is_static = FALSE;\n                name = JS_DupAtom(ctx, JS_ATOM_static);\n                prop_type = PROP_TYPE_IDENT;\n            }\n        }\n        if (is_static)\n            emit_op(s, OP_swap);\n        start_ptr = s->token.ptr;\n        if (prop_type < 0) {\n            prop_type = js_parse_property_name(s, &name, TRUE, FALSE, TRUE);\n            if (prop_type < 0)\n                goto fail;\n        }\n        is_private = prop_type & PROP_TYPE_PRIVATE;\n        prop_type &= ~PROP_TYPE_PRIVATE;\n        \n        if ((name == JS_ATOM_constructor && !is_static &&\n             prop_type != PROP_TYPE_IDENT) ||\n            (name == JS_ATOM_prototype && is_static) ||\n            name == JS_ATOM_hash_constructor) {\n            js_parse_error(s, \"invalid method name\");\n            goto fail;\n        }\n        if (prop_type == PROP_TYPE_GET || prop_type == PROP_TYPE_SET) {\n            BOOL is_set = prop_type - PROP_TYPE_GET;\n            JSFunctionDef *method_fd;\n\n            if (is_private) {\n                int idx, var_kind;\n                idx = find_private_class_field(ctx, fd, name, fd->scope_level);\n                if (idx >= 0) {\n                    var_kind = fd->vars[idx].var_kind;\n                    if (var_kind == JS_VAR_PRIVATE_FIELD ||\n                        var_kind == JS_VAR_PRIVATE_METHOD ||\n                        var_kind == JS_VAR_PRIVATE_GETTER_SETTER ||\n                        var_kind == (JS_VAR_PRIVATE_GETTER + is_set)) {\n                        goto private_field_already_defined;\n                    }\n                    fd->vars[idx].var_kind = JS_VAR_PRIVATE_GETTER_SETTER;\n                } else {\n                    if (add_private_class_field(s, fd, name,\n                                                JS_VAR_PRIVATE_GETTER + is_set) < 0)\n                        goto fail;\n                }\n                if (add_brand(s, &class_fields[is_static]) < 0)\n                    goto fail;\n            }\n\n            if (js_parse_function_decl2(s, JS_PARSE_FUNC_GETTER + is_set,\n                                        JS_FUNC_NORMAL, JS_ATOM_NULL,\n                                        start_ptr, s->token.line_num,\n                                        JS_PARSE_EXPORT_NONE, &method_fd))\n                goto fail;\n            if (is_private) {\n                method_fd->need_home_object = TRUE; /* needed for brand check */\n                emit_op(s, OP_set_home_object);\n                /* XXX: missing function name */\n                emit_op(s, OP_scope_put_var_init);\n                if (is_set) {\n                    JSAtom setter_name;\n                    int ret;\n                    \n                    setter_name = get_private_setter_name(ctx, name);\n                    if (setter_name == JS_ATOM_NULL)\n                        goto fail;\n                    emit_atom(s, setter_name);\n                    ret = add_private_class_field(s, fd, setter_name,\n                                                  JS_VAR_PRIVATE_SETTER);\n                    JS_FreeAtom(ctx, setter_name);\n                    if (ret < 0)\n                        goto fail;\n                } else {\n                    emit_atom(s, name);\n                }\n                emit_u16(s, s->cur_func->scope_level);\n            } else {\n                if (name == JS_ATOM_NULL) {\n                    emit_op(s, OP_define_method_computed);\n                } else {\n                    emit_op(s, OP_define_method);\n                    emit_atom(s, name);\n                }\n                emit_u8(s, OP_DEFINE_METHOD_GETTER + is_set);\n            }\n        } else if (prop_type == PROP_TYPE_IDENT && s->token.val != '(') {\n            ClassFieldsDef *cf = &class_fields[is_static];\n            JSAtom field_var_name = JS_ATOM_NULL;\n            \n            /* class field */\n\n            /* XXX: spec: not consistent with method name checks */\n            if (name == JS_ATOM_constructor || name == JS_ATOM_prototype) {\n                js_parse_error(s, \"invalid field name\");\n                goto fail;\n            }\n            \n            if (is_private) {\n                if (find_private_class_field(ctx, fd, name,\n                                             fd->scope_level) >= 0) {\n                    goto private_field_already_defined;\n                }\n                if (add_private_class_field(s, fd, name,\n                                            JS_VAR_PRIVATE_FIELD) < 0)\n                    goto fail;\n                emit_op(s, OP_private_symbol);\n                emit_atom(s, name);\n                emit_op(s, OP_scope_put_var_init);\n                emit_atom(s, name);\n                emit_u16(s, s->cur_func->scope_level);\n            }\n\n            if (!cf->fields_init_fd) {\n                if (emit_class_init_start(s, cf))\n                    goto fail;\n            }\n            if (name == JS_ATOM_NULL ) {\n                /* save the computed field name into a variable */\n                field_var_name = js_atom_concat_num(ctx, JS_ATOM_computed_field + is_static, cf->computed_fields_count);\n                if (field_var_name == JS_ATOM_NULL)\n                    goto fail;\n                if (define_var(s, fd, field_var_name, JS_VAR_DEF_CONST) < 0) {\n                    JS_FreeAtom(ctx, field_var_name);\n                    goto fail;\n                }\n                emit_op(s, OP_to_propkey);\n                emit_op(s, OP_scope_put_var_init);\n                emit_atom(s, field_var_name);\n                emit_u16(s, s->cur_func->scope_level);\n            }\n            s->cur_func = cf->fields_init_fd;\n            emit_op(s, OP_scope_get_var);\n            emit_atom(s, JS_ATOM_this);\n            emit_u16(s, 0);\n\n            if (name == JS_ATOM_NULL) {\n                emit_op(s, OP_scope_get_var);\n                emit_atom(s, field_var_name);\n                emit_u16(s, s->cur_func->scope_level);\n                cf->computed_fields_count++;\n                JS_FreeAtom(ctx, field_var_name);\n            } else if (is_private) {\n                emit_op(s, OP_scope_get_var);\n                emit_atom(s, name);\n                emit_u16(s, s->cur_func->scope_level);\n            }\n            \n            if (s->token.val == '=') {\n                if (next_token(s))\n                    goto fail;\n                if (js_parse_assign_expr(s))\n                    goto fail;\n            } else {\n                emit_op(s, OP_undefined);\n            }\n            if (is_private) {\n                set_object_name_computed(s);\n                emit_op(s, OP_define_private_field);\n            } else if (name == JS_ATOM_NULL) {\n                set_object_name_computed(s);\n                emit_op(s, OP_define_array_el);\n                emit_op(s, OP_drop);\n            } else {\n                set_object_name(s, name);\n                emit_op(s, OP_define_field);\n                emit_atom(s, name);\n            }\n            s->cur_func = s->cur_func->parent;\n            if (js_parse_expect_semi(s))\n                goto fail;\n        } else {\n            JSParseFunctionEnum func_type;\n            JSFunctionKindEnum func_kind;\n            \n            func_type = JS_PARSE_FUNC_METHOD;\n            func_kind = JS_FUNC_NORMAL;\n            if (prop_type == PROP_TYPE_STAR) {\n                func_kind = JS_FUNC_GENERATOR;\n            } else if (prop_type == PROP_TYPE_ASYNC) {\n                func_kind = JS_FUNC_ASYNC;\n            } else if (prop_type == PROP_TYPE_ASYNC_STAR) {\n                func_kind = JS_FUNC_ASYNC_GENERATOR;\n            } else if (name == JS_ATOM_constructor && !is_static) {\n                if (ctor_fd) {\n                    js_parse_error(s, \"property constructor appears more than once\");\n                    goto fail;\n                }\n                if (class_flags & JS_DEFINE_CLASS_HAS_HERITAGE)\n                    func_type = JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR;\n                else\n                    func_type = JS_PARSE_FUNC_CLASS_CONSTRUCTOR;\n            }\n            if (is_private) {\n                if (add_brand(s, &class_fields[is_static]) < 0)\n                    goto fail;\n            }\n            if (js_parse_function_decl2(s, func_type, func_kind, JS_ATOM_NULL, start_ptr, s->token.line_num, JS_PARSE_EXPORT_NONE, &method_fd))\n                goto fail;\n            if (func_type == JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR ||\n                func_type == JS_PARSE_FUNC_CLASS_CONSTRUCTOR) {\n                ctor_fd = method_fd;\n            } else if (is_private) {\n                method_fd->need_home_object = TRUE; /* needed for brand check */\n                if (find_private_class_field(ctx, fd, name,\n                                             fd->scope_level) >= 0) {\n                private_field_already_defined:\n                    js_parse_error(s, \"private class field is already defined\");\n                    goto fail;\n                }\n                if (add_private_class_field(s, fd, name,\n                                            JS_VAR_PRIVATE_METHOD) < 0)\n                    goto fail;\n                emit_op(s, OP_set_home_object);\n                emit_op(s, OP_set_name);\n                emit_atom(s, name);\n                emit_op(s, OP_scope_put_var_init);\n                emit_atom(s, name);\n                emit_u16(s, s->cur_func->scope_level);\n            } else {\n                if (name == JS_ATOM_NULL) {\n                    emit_op(s, OP_define_method_computed);\n                } else {\n                    emit_op(s, OP_define_method);\n                    emit_atom(s, name);\n                }\n                emit_u8(s, OP_DEFINE_METHOD_METHOD);\n            }\n        }\n        if (is_static)\n            emit_op(s, OP_swap);\n        JS_FreeAtom(ctx, name);\n        name = JS_ATOM_NULL;\n    }\n\n    if (s->token.val != '}') {\n        js_parse_error(s, \"expecting '%c'\", '}');\n        goto fail;\n    }\n\n    if (!ctor_fd) {\n        if (js_parse_class_default_ctor(s, class_flags & JS_DEFINE_CLASS_HAS_HERITAGE, &ctor_fd))\n            goto fail;\n    }\n    /* patch the constant pool index for the constructor */\n    put_u32(fd->byte_code.buf + ctor_cpool_offset, ctor_fd->parent_cpool_idx);\n\n    /* store the class source code in the constructor. */\n    if (!(fd->js_mode & JS_MODE_STRIP)) {\n        js_free(ctx, ctor_fd->source);\n        ctor_fd->source_len = s->buf_ptr - class_start_ptr;\n        ctor_fd->source = js_strndup(ctx, (const char *)class_start_ptr,\n                                     ctor_fd->source_len);\n        if (!ctor_fd->source)\n            goto fail;\n    }\n\n    /* consume the '}' */\n    if (next_token(s))\n        goto fail;\n\n    /* store the function to initialize the fields to that it can be\n       referenced by the constructor */\n    {\n        ClassFieldsDef *cf = &class_fields[0];\n        int var_idx;\n        \n        var_idx = define_var(s, fd, JS_ATOM_class_fields_init,\n                             JS_VAR_DEF_CONST);\n        if (var_idx < 0)\n            goto fail;\n        if (cf->fields_init_fd) {\n            emit_class_init_end(s, cf);\n        } else {\n            emit_op(s, OP_undefined);\n        }\n        emit_op(s, OP_scope_put_var_init);\n        emit_atom(s, JS_ATOM_class_fields_init);\n        emit_u16(s, s->cur_func->scope_level);\n    }\n\n    /* drop the prototype */\n    emit_op(s, OP_drop);\n\n    /* initialize the static fields */\n    if (class_fields[1].fields_init_fd != NULL) {\n        ClassFieldsDef *cf = &class_fields[1];\n        emit_op(s, OP_dup);\n        emit_class_init_end(s, cf);\n        emit_op(s, OP_call_method);\n        emit_u16(s, 0);\n        emit_op(s, OP_drop);\n    }\n    \n    if (class_name != JS_ATOM_NULL) {\n        /* store the class name in the scoped class name variable (it\n           is independent from the class statement variable\n           definition) */\n        emit_op(s, OP_dup);\n        emit_op(s, OP_scope_put_var_init);\n        emit_atom(s, class_name);\n        emit_u16(s, fd->scope_level);\n    }\n    pop_scope(s);\n    pop_scope(s);\n\n    /* the class statements have a block level scope */\n    if (class_var_name != JS_ATOM_NULL) {\n        if (define_var(s, fd, class_var_name, JS_VAR_DEF_LET) < 0)\n            goto fail;\n        emit_op(s, OP_scope_put_var_init);\n        emit_atom(s, class_var_name);\n        emit_u16(s, fd->scope_level);\n    } else {\n        if (class_name == JS_ATOM_NULL) {\n            /* cannot use OP_set_name because the name of the class\n               must be defined before the static initializers are\n               executed */\n            emit_op(s, OP_set_class_name);\n            emit_u32(s, fd->last_opcode_pos + 1 - define_class_offset);\n        }\n    }\n\n    if (export_flag != JS_PARSE_EXPORT_NONE) {\n        if (!add_export_entry(s, fd->module,\n                              class_var_name,\n                              export_flag == JS_PARSE_EXPORT_NAMED ? class_var_name : JS_ATOM_default,\n                              JS_EXPORT_TYPE_LOCAL))\n            goto fail;\n    }\n\n    JS_FreeAtom(ctx, class_name);\n    JS_FreeAtom(ctx, class_var_name);\n    fd->js_mode = saved_js_mode;\n    return 0;\n fail:\n    JS_FreeAtom(ctx, name);\n    JS_FreeAtom(ctx, class_name);\n    JS_FreeAtom(ctx, class_var_name);\n    fd->js_mode = saved_js_mode;\n    return -1;\n}\n\nstatic __exception int js_parse_array_literal(JSParseState *s)\n{\n    uint32_t idx;\n    BOOL need_length;\n\n    if (next_token(s))\n        return -1;\n    /* small regular arrays are created on the stack */\n    idx = 0;\n    while (s->token.val != ']' && idx < 32) {\n        if (s->token.val == ',' || s->token.val == TOK_ELLIPSIS)\n            break;\n        if (js_parse_assign_expr(s))\n            return -1;\n        idx++;\n        /* accept trailing comma */\n        if (s->token.val == ',') {\n            if (next_token(s))\n                return -1;\n        } else\n        if (s->token.val != ']')\n            goto done;\n    }\n    emit_op(s, OP_array_from);\n    emit_u16(s, idx);\n\n    /* larger arrays and holes are handled with explicit indices */\n    need_length = FALSE;\n    while (s->token.val != ']' && idx < 0x7fffffff) {\n        if (s->token.val == TOK_ELLIPSIS)\n            break;\n        need_length = TRUE;\n        if (s->token.val != ',') {\n            if (js_parse_assign_expr(s))\n                return -1;\n            emit_op(s, OP_define_field);\n            emit_u32(s, __JS_AtomFromUInt32(idx));\n            need_length = FALSE;\n        }\n        idx++;\n        /* accept trailing comma */\n        if (s->token.val == ',') {\n            if (next_token(s))\n                return -1;\n        }\n    }\n    if (s->token.val == ']') {\n        if (need_length) {\n            /* Set the length: Cannot use OP_define_field because\n               length is not configurable */\n            emit_op(s, OP_dup);\n            emit_op(s, OP_push_i32);\n            emit_u32(s, idx);\n            emit_op(s, OP_put_field);\n            emit_atom(s, JS_ATOM_length);\n        }\n        goto done;\n    }\n\n    /* huge arrays and spread elements require a dynamic index on the stack */\n    emit_op(s, OP_push_i32);\n    emit_u32(s, idx);\n\n    /* stack has array, index */\n    while (s->token.val != ']') {\n        if (s->token.val == TOK_ELLIPSIS) {\n            if (next_token(s))\n                return -1;\n            if (js_parse_assign_expr(s))\n                return -1;\n#if 1\n            emit_op(s, OP_append);\n#else\n            int label_next, label_done;\n            label_next = new_label(s);\n            label_done = new_label(s);\n            /* enumerate object */\n            emit_op(s, OP_for_of_start);\n            emit_op(s, OP_rot5l);\n            emit_op(s, OP_rot5l);\n            emit_label(s, label_next);\n            /* on stack: enum_rec array idx */\n            emit_op(s, OP_for_of_next);\n            emit_u8(s, 2);\n            emit_goto(s, OP_if_true, label_done);\n            /* append element */\n            /* enum_rec array idx val -> enum_rec array new_idx */\n            emit_op(s, OP_define_array_el);\n            emit_op(s, OP_inc);\n            emit_goto(s, OP_goto, label_next);\n            emit_label(s, label_done);\n            /* close enumeration */\n            emit_op(s, OP_drop); /* drop undef val */\n            emit_op(s, OP_nip1); /* drop enum_rec */\n            emit_op(s, OP_nip1);\n            emit_op(s, OP_nip1);\n#endif\n        } else {\n            need_length = TRUE;\n            if (s->token.val != ',') {\n                if (js_parse_assign_expr(s))\n                    return -1;\n                /* a idx val */\n                emit_op(s, OP_define_array_el);\n                need_length = FALSE;\n            }\n            emit_op(s, OP_inc);\n        }\n        if (s->token.val != ',')\n            break;\n        if (next_token(s))\n            return -1;\n    }\n    if (need_length) {\n        /* Set the length: cannot use OP_define_field because\n           length is not configurable */\n        emit_op(s, OP_dup1);    /* array length - array array length */\n        emit_op(s, OP_put_field);\n        emit_atom(s, JS_ATOM_length);\n    } else {\n        emit_op(s, OP_drop);    /* array length - array */\n    }\ndone:\n    return js_parse_expect(s, ']');\n}\n\n/* XXX: remove */\nstatic BOOL has_with_scope(JSFunctionDef *s, int scope_level)\n{\n    /* check if scope chain contains a with statement */\n    while (s) {\n        int scope_idx = s->scopes[scope_level].first;\n        while (scope_idx >= 0) {\n            JSVarDef *vd = &s->vars[scope_idx];\n\n            if (vd->var_name == JS_ATOM__with_)\n                return TRUE;\n            scope_idx = vd->scope_next;\n        }\n        /* check parent scopes */\n        scope_level = s->parent_scope_level;\n        s = s->parent;\n    }\n    return FALSE;\n}\n\nstatic __exception int get_lvalue(JSParseState *s, int *popcode, int *pscope,\n                                  JSAtom *pname, int *plabel, int *pdepth, BOOL keep,\n                                  int tok)\n{\n    JSFunctionDef *fd;\n    int opcode, scope, label, depth;\n    JSAtom name;\n\n    /* we check the last opcode to get the lvalue type */\n    fd = s->cur_func;\n    scope = 0;\n    name = JS_ATOM_NULL;\n    label = -1;\n    depth = 0;\n    switch(opcode = get_prev_opcode(fd)) {\n    case OP_scope_get_var:\n        name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);\n        scope = get_u16(fd->byte_code.buf + fd->last_opcode_pos + 5);\n        if ((name == JS_ATOM_arguments || name == JS_ATOM_eval) &&\n            (fd->js_mode & JS_MODE_STRICT)) {\n            return js_parse_error(s, \"invalid lvalue in strict mode\");\n        }\n        if (name == JS_ATOM_this || name == JS_ATOM_new_target)\n            goto invalid_lvalue;\n        depth = 2;  /* will generate OP_get_ref_value */\n        break;\n    case OP_get_field:\n        name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);\n        depth = 1;\n        break;\n    case OP_scope_get_private_field:\n        name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);\n        scope = get_u16(fd->byte_code.buf + fd->last_opcode_pos + 5);\n        depth = 1;\n        break;\n    case OP_get_array_el:\n        depth = 2;\n        break;\n    case OP_get_super_value:\n        depth = 3;\n        break;\n    default:\n    invalid_lvalue:\n        if (tok == TOK_FOR) {\n            return js_parse_error(s, \"invalid for in/of left hand-side\");\n        } else if (tok == TOK_INC || tok == TOK_DEC) {\n            return js_parse_error(s, \"invalid increment/decrement operand\");\n        } else if (tok == '[' || tok == '{') {\n            return js_parse_error(s, \"invalid destructuring target\");\n        } else {\n            return js_parse_error(s, \"invalid assignment left-hand side\");\n        }\n    }\n    /* remove the last opcode */\n    fd->byte_code.size = fd->last_opcode_pos;\n    fd->last_opcode_pos = -1;\n\n    if (keep) {\n        /* get the value but keep the object/fields on the stack */\n        switch(opcode) {\n        case OP_scope_get_var:\n            label = new_label(s);\n            emit_op(s, OP_scope_make_ref);\n            emit_atom(s, name);\n            emit_u32(s, label);\n            emit_u16(s, scope);\n            update_label(fd, label, 1);\n            emit_op(s, OP_get_ref_value);\n            opcode = OP_get_ref_value;\n            break;\n        case OP_get_field:\n            emit_op(s, OP_get_field2);\n            emit_atom(s, name);\n            break;\n        case OP_scope_get_private_field:\n            emit_op(s, OP_scope_get_private_field2);\n            emit_atom(s, name);\n            emit_u16(s, scope);\n            break;\n        case OP_get_array_el:\n            /* XXX: replace by a single opcode ? */\n            emit_op(s, OP_to_propkey2);\n            emit_op(s, OP_dup2);\n            emit_op(s, OP_get_array_el);\n            break;\n        case OP_get_super_value:\n            emit_op(s, OP_to_propkey);\n            emit_op(s, OP_dup3);\n            emit_op(s, OP_get_super_value);\n            break;\n        default:\n            abort();\n        }\n    } else {\n        switch(opcode) {\n        case OP_scope_get_var:\n            label = new_label(s);\n            emit_op(s, OP_scope_make_ref);\n            emit_atom(s, name);\n            emit_u32(s, label);\n            emit_u16(s, scope);\n            update_label(fd, label, 1);\n            opcode = OP_get_ref_value;\n            break;\n        case OP_get_array_el:\n            emit_op(s, OP_to_propkey2);\n            break;\n        case OP_get_super_value:\n            emit_op(s, OP_to_propkey);\n            break;\n        }\n    }\n\n    *popcode = opcode;\n    *pscope = scope;\n    /* name has refcount for OP_get_field and OP_get_ref_value,\n       and JS_ATOM_NULL for other opcodes */\n    *pname = name;\n    *plabel = label;\n    if (pdepth)\n        *pdepth = depth;\n    return 0;\n}\n\ntypedef enum {\n    PUT_LVALUE_NOKEEP, /* [depth] v -> */\n    PUT_LVALUE_NOKEEP_DEPTH, /* [depth] v -> , keep depth (currently\n                                just disable optimizations) */\n    PUT_LVALUE_KEEP_TOP,  /* [depth] v -> v */\n    PUT_LVALUE_KEEP_SECOND, /* [depth] v0 v -> v0 */\n    PUT_LVALUE_NOKEEP_BOTTOM, /* v [depth] -> */\n} PutLValueEnum;\n\n/* name has a live reference. 'is_let' is only used with opcode =\n   OP_scope_get_var which is never generated by get_lvalue(). */\nstatic void put_lvalue(JSParseState *s, int opcode, int scope,\n                       JSAtom name, int label, PutLValueEnum special,\n                       BOOL is_let)\n{\n    switch(opcode) {\n    case OP_get_field:\n    case OP_scope_get_private_field:\n        /* depth = 1 */\n        switch(special) {\n        case PUT_LVALUE_NOKEEP:\n        case PUT_LVALUE_NOKEEP_DEPTH:\n            break;\n        case PUT_LVALUE_KEEP_TOP:\n            emit_op(s, OP_insert2); /* obj v -> v obj v */\n            break;\n        case PUT_LVALUE_KEEP_SECOND:\n            emit_op(s, OP_perm3); /* obj v0 v -> v0 obj v */\n            break;\n        case PUT_LVALUE_NOKEEP_BOTTOM:\n            emit_op(s, OP_swap);\n            break;\n        default:\n            abort();\n        }\n        break;\n    case OP_get_array_el:\n    case OP_get_ref_value:\n        /* depth = 2 */\n        if (opcode == OP_get_ref_value) {\n            JS_FreeAtom(s->ctx, name);\n            emit_label(s, label);\n        }\n        switch(special) {\n        case PUT_LVALUE_NOKEEP:\n            emit_op(s, OP_nop); /* will trigger optimization */\n            break;\n        case PUT_LVALUE_NOKEEP_DEPTH:\n            break;\n        case PUT_LVALUE_KEEP_TOP:\n            emit_op(s, OP_insert3); /* obj prop v -> v obj prop v */\n            break;\n        case PUT_LVALUE_KEEP_SECOND:\n            emit_op(s, OP_perm4); /* obj prop v0 v -> v0 obj prop v */\n            break;\n        case PUT_LVALUE_NOKEEP_BOTTOM:\n            emit_op(s, OP_rot3l);\n            break;\n        default:\n            abort();\n        }\n        break;\n    case OP_get_super_value:\n        /* depth = 3 */\n        switch(special) {\n        case PUT_LVALUE_NOKEEP:\n        case PUT_LVALUE_NOKEEP_DEPTH:\n            break;\n        case PUT_LVALUE_KEEP_TOP:\n            emit_op(s, OP_insert4); /* this obj prop v -> v this obj prop v */\n            break;\n        case PUT_LVALUE_KEEP_SECOND:\n            emit_op(s, OP_perm5); /* this obj prop v0 v -> v0 this obj prop v */\n            break;\n        case PUT_LVALUE_NOKEEP_BOTTOM:\n            emit_op(s, OP_rot4l);\n            break;\n        default:\n            abort();\n        }\n        break;\n    default:\n        break;\n    }\n    \n    switch(opcode) {\n    case OP_scope_get_var:  /* val -- */\n        assert(special == PUT_LVALUE_NOKEEP ||\n               special == PUT_LVALUE_NOKEEP_DEPTH);\n        emit_op(s, is_let ? OP_scope_put_var_init : OP_scope_put_var);\n        emit_u32(s, name);  /* has refcount */\n        emit_u16(s, scope);\n        break;\n    case OP_get_field:\n        emit_op(s, OP_put_field);\n        emit_u32(s, name);  /* name has refcount */\n        break;\n    case OP_scope_get_private_field:\n        emit_op(s, OP_scope_put_private_field);\n        emit_u32(s, name);  /* name has refcount */\n        emit_u16(s, scope);\n        break;\n    case OP_get_array_el:\n        emit_op(s, OP_put_array_el);\n        break;\n    case OP_get_ref_value:\n        emit_op(s, OP_put_ref_value);\n        break;\n    case OP_get_super_value:\n        emit_op(s, OP_put_super_value);\n        break;\n    default:\n        abort();\n    }\n}\n\nstatic __exception int js_parse_expr_paren(JSParseState *s)\n{\n    if (js_parse_expect(s, '('))\n        return -1;\n    if (js_parse_expr(s))\n        return -1;\n    if (js_parse_expect(s, ')'))\n        return -1;\n    return 0;\n}\n\nstatic int js_unsupported_keyword(JSParseState *s, JSAtom atom)\n{\n    char buf[ATOM_GET_STR_BUF_SIZE];\n    return js_parse_error(s, \"unsupported keyword: %s\",\n                          JS_AtomGetStr(s->ctx, buf, sizeof(buf), atom));\n}\n\nstatic __exception int js_define_var(JSParseState *s, JSAtom name, int tok)\n{\n    JSFunctionDef *fd = s->cur_func;\n    JSVarDefEnum var_def_type;\n    \n    if (name == JS_ATOM_yield && fd->func_kind == JS_FUNC_GENERATOR) {\n        return js_parse_error(s, \"yield is a reserved identifier\");\n    }\n    if ((name == JS_ATOM_arguments || name == JS_ATOM_eval)\n    &&  (fd->js_mode & JS_MODE_STRICT)) {\n        return js_parse_error(s, \"invalid variable name in strict mode\");\n    }\n    if ((name == JS_ATOM_let || name == JS_ATOM_undefined)\n    &&  (tok == TOK_LET || tok == TOK_CONST)) {\n        return js_parse_error(s, \"invalid lexical variable name\");\n    }\n    switch(tok) {\n    case TOK_LET:\n        var_def_type = JS_VAR_DEF_LET;\n        break;\n    case TOK_CONST:\n        var_def_type = JS_VAR_DEF_CONST;\n        break;\n    case TOK_VAR:\n        var_def_type = JS_VAR_DEF_VAR;\n        break;\n    case TOK_CATCH:\n        var_def_type = JS_VAR_DEF_CATCH;\n        break;\n    default:\n        abort();\n    }\n    if (define_var(s, fd, name, var_def_type) < 0)\n        return -1;\n    return 0;\n}\n\nstatic void js_emit_spread_code(JSParseState *s, int depth)\n{\n    int label_rest_next, label_rest_done;\n\n    /* XXX: could check if enum object is an actual array and optimize\n       slice extraction. enumeration record and target array are in a\n       different order from OP_append case. */\n    /* enum_rec xxx -- enum_rec xxx array 0 */\n    emit_op(s, OP_array_from);\n    emit_u16(s, 0);\n    emit_op(s, OP_push_i32);\n    emit_u32(s, 0);\n    emit_label(s, label_rest_next = new_label(s));\n    emit_op(s, OP_for_of_next);\n    emit_u8(s, 2 + depth);\n    label_rest_done = emit_goto(s, OP_if_true, -1);\n    /* array idx val -- array idx */\n    emit_op(s, OP_define_array_el);\n    emit_op(s, OP_inc);\n    emit_goto(s, OP_goto, label_rest_next);\n    emit_label(s, label_rest_done);\n    /* enum_rec xxx array idx undef -- enum_rec xxx array */\n    emit_op(s, OP_drop);\n    emit_op(s, OP_drop);\n}\n\nstatic int js_parse_check_duplicate_parameter(JSParseState *s, JSAtom name)\n{\n    /* Check for duplicate parameter names */\n    JSFunctionDef *fd = s->cur_func;\n    int i;\n    for (i = 0; i < fd->arg_count; i++) {\n        if (fd->args[i].var_name == name)\n            goto duplicate;\n    }\n    for (i = 0; i < fd->var_count; i++) {\n        if (fd->vars[i].var_name == name)\n            goto duplicate;\n    }\n    return 0;\n\nduplicate:\n    return js_parse_error(s, \"duplicate parameter names not allowed in this context\");\n}\n\nstatic JSAtom js_parse_destructuring_var(JSParseState *s, int tok, int is_arg)\n{\n    JSAtom name;\n\n    if (!(s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved)\n    ||  ((s->cur_func->js_mode & JS_MODE_STRICT) &&\n         (s->token.u.ident.atom == JS_ATOM_eval || s->token.u.ident.atom == JS_ATOM_arguments))) {\n        js_parse_error(s, \"invalid destructuring target\");\n        return JS_ATOM_NULL;\n    }\n    name = JS_DupAtom(s->ctx, s->token.u.ident.atom);\n    if (is_arg && js_parse_check_duplicate_parameter(s, name))\n        goto fail;\n    if (next_token(s))\n        goto fail;\n\n    return name;\nfail:\n    JS_FreeAtom(s->ctx, name);\n    return JS_ATOM_NULL;\n}\n\n/* Return -1 if error, 0 if no initializer, 1 if an initializer is\n   present at the top level. */\nstatic int js_parse_destructuring_element(JSParseState *s, int tok, int is_arg,\n                                        int hasval, int has_ellipsis,\n                                        BOOL allow_initializer)\n{\n    int label_parse, label_assign, label_done, label_lvalue, depth_lvalue;\n    int start_addr, assign_addr;\n    JSAtom prop_name, var_name;\n    int opcode, scope, tok1, skip_bits;\n    BOOL has_initializer;\n    \n    if (has_ellipsis < 0) {\n        /* pre-parse destructuration target for spread detection */\n        js_parse_skip_parens_token(s, &skip_bits, FALSE);\n        has_ellipsis = skip_bits & SKIP_HAS_ELLIPSIS;\n    }\n\n    label_parse = new_label(s);\n    label_assign = new_label(s);\n\n    start_addr = s->cur_func->byte_code.size;\n    if (hasval) {\n        /* consume value from the stack */\n        emit_op(s, OP_dup);\n        emit_op(s, OP_undefined);\n        emit_op(s, OP_strict_eq);\n        emit_goto(s, OP_if_true, label_parse);\n        emit_label(s, label_assign);\n    } else {\n        emit_goto(s, OP_goto, label_parse);\n        emit_label(s, label_assign);\n        /* leave value on the stack */\n        emit_op(s, OP_dup);\n    }\n    assign_addr = s->cur_func->byte_code.size;\n    if (s->token.val == '{') {\n        if (next_token(s))\n            return -1;\n        /* throw an exception if the value cannot be converted to an object */\n        emit_op(s, OP_to_object);\n        if (has_ellipsis) {\n            /* add excludeList on stack just below src object */\n            emit_op(s, OP_object);\n            emit_op(s, OP_swap);\n        }\n        while (s->token.val != '}') {\n            int prop_type;\n            if (s->token.val == TOK_ELLIPSIS) {\n                if (!has_ellipsis) {\n                    JS_ThrowInternalError(s->ctx, \"unexpected ellipsis token\");\n                    return -1;\n                }\n                if (next_token(s))\n                    return -1;\n                if (tok) {\n                    var_name = js_parse_destructuring_var(s, tok, is_arg);\n                    if (var_name == JS_ATOM_NULL)\n                        return -1;\n                    opcode = OP_scope_get_var;\n                    scope = s->cur_func->scope_level;\n                    label_lvalue = -1;\n                    depth_lvalue = 0;\n                } else {\n                    if (js_parse_left_hand_side_expr(s))\n                        return -1;\n\n                    if (get_lvalue(s, &opcode, &scope, &var_name,\n                                   &label_lvalue, &depth_lvalue, FALSE, '{'))\n                        return -1;\n                }\n                if (s->token.val != '}') {\n                    js_parse_error(s, \"assignment rest property must be last\");\n                    goto var_error;\n                }\n                emit_op(s, OP_object);  /* target */\n                emit_op(s, OP_copy_data_properties);\n                emit_u8(s, 0 | ((depth_lvalue + 1) << 2) | ((depth_lvalue + 2) << 5));\n                goto set_val;\n            }\n            prop_type = js_parse_property_name(s, &prop_name, FALSE, TRUE, FALSE);\n            if (prop_type < 0)\n                return -1;\n            var_name = JS_ATOM_NULL;\n            opcode = OP_scope_get_var;\n            scope = s->cur_func->scope_level;\n            label_lvalue = -1;\n            depth_lvalue = 0;\n            if (prop_type == PROP_TYPE_IDENT) {\n                if (next_token(s))\n                    goto prop_error;\n                if ((s->token.val == '[' || s->token.val == '{')\n                    &&  ((tok1 = js_parse_skip_parens_token(s, &skip_bits, FALSE)) == ',' ||\n                         tok1 == '=' || tok1 == '}')) {\n                    if (prop_name == JS_ATOM_NULL) {\n                        /* computed property name on stack */\n                        if (has_ellipsis) {\n                            /* define the property in excludeList */\n                            emit_op(s, OP_to_propkey); /* avoid calling ToString twice */\n                            emit_op(s, OP_perm3); /* TOS: src excludeList prop */\n                            emit_op(s, OP_null); /* TOS: src excludeList prop null */\n                            emit_op(s, OP_define_array_el); /* TOS: src excludeList prop */\n                            emit_op(s, OP_perm3); /* TOS: excludeList src prop */\n                        }\n                        /* get the computed property from the source object */\n                        emit_op(s, OP_get_array_el2);\n                    } else {\n                        /* named property */\n                        if (has_ellipsis) {\n                            /* define the property in excludeList */\n                            emit_op(s, OP_swap); /* TOS: src excludeList */\n                            emit_op(s, OP_null); /* TOS: src excludeList null */\n                            emit_op(s, OP_define_field); /* TOS: src excludeList */\n                            emit_atom(s, prop_name);\n                            emit_op(s, OP_swap); /* TOS: excludeList src */\n                        }\n                        /* get the named property from the source object */\n                        emit_op(s, OP_get_field2);\n                        emit_u32(s, prop_name);\n                    }\n                    if (js_parse_destructuring_element(s, tok, is_arg, TRUE, -1, TRUE) < 0)\n                        return -1;\n                    if (s->token.val == '}')\n                        break;\n                    /* accept a trailing comma before the '}' */\n                    if (js_parse_expect(s, ','))\n                        return -1;\n                    continue;\n                }\n                if (prop_name == JS_ATOM_NULL) {\n                    emit_op(s, OP_to_propkey2);\n                    if (has_ellipsis) {\n                        /* define the property in excludeList */\n                        emit_op(s, OP_perm3);\n                        emit_op(s, OP_null);\n                        emit_op(s, OP_define_array_el);\n                        emit_op(s, OP_perm3);\n                    }\n                    /* source prop -- source source prop */\n                    emit_op(s, OP_dup1);\n                } else {\n                    if (has_ellipsis) {\n                        /* define the property in excludeList */\n                        emit_op(s, OP_swap);\n                        emit_op(s, OP_null);\n                        emit_op(s, OP_define_field);\n                        emit_atom(s, prop_name);\n                        emit_op(s, OP_swap);\n                    }\n                    /* source -- source source */\n                    emit_op(s, OP_dup);\n                }\n                if (tok) {\n                    var_name = js_parse_destructuring_var(s, tok, is_arg);\n                    if (var_name == JS_ATOM_NULL)\n                        goto prop_error;\n                } else {\n                    if (js_parse_left_hand_side_expr(s))\n                        goto prop_error;\n                lvalue:\n                    if (get_lvalue(s, &opcode, &scope, &var_name,\n                                   &label_lvalue, &depth_lvalue, FALSE, '{'))\n                        goto prop_error;\n                    /* swap ref and lvalue object if any */\n                    if (prop_name == JS_ATOM_NULL) {\n                        switch(depth_lvalue) {\n                        case 1:\n                            /* source prop x -> x source prop */\n                            emit_op(s, OP_rot3r);\n                            break;\n                        case 2:\n                            /* source prop x y -> x y source prop */\n                            emit_op(s, OP_swap2);   /* t p2 s p1 */\n                            break;\n                        case 3:\n                            /* source prop x y z -> x y z source prop */\n                            emit_op(s, OP_rot5l);\n                            emit_op(s, OP_rot5l);\n                            break;\n                        }\n                    } else {\n                        switch(depth_lvalue) {\n                        case 1:\n                            /* source x -> x source */\n                            emit_op(s, OP_swap);\n                            break;\n                        case 2:\n                            /* source x y -> x y source */\n                            emit_op(s, OP_rot3l);\n                            break;\n                        case 3:\n                            /* source x y z -> x y z source */\n                            emit_op(s, OP_rot4l);\n                            break;\n                        }\n                    }\n                }\n                if (prop_name == JS_ATOM_NULL) {\n                    /* computed property name on stack */\n                    /* XXX: should have OP_get_array_el2x with depth */\n                    /* source prop -- val */\n                    emit_op(s, OP_get_array_el);\n                } else {\n                    /* named property */\n                    /* XXX: should have OP_get_field2x with depth */\n                    /* source -- val */\n                    emit_op(s, OP_get_field);\n                    emit_u32(s, prop_name);\n                }\n            } else {\n                /* prop_type = PROP_TYPE_VAR, cannot be a computed property */\n                if (is_arg && js_parse_check_duplicate_parameter(s, prop_name))\n                    goto prop_error;\n                if ((s->cur_func->js_mode & JS_MODE_STRICT) &&\n                    (prop_name == JS_ATOM_eval || prop_name == JS_ATOM_arguments)) {\n                    js_parse_error(s, \"invalid destructuring target\");\n                    goto prop_error;\n                }\n                if (has_ellipsis) {\n                    /* define the property in excludeList */\n                    emit_op(s, OP_swap);\n                    emit_op(s, OP_null);\n                    emit_op(s, OP_define_field);\n                    emit_atom(s, prop_name);\n                    emit_op(s, OP_swap);\n                }\n                if (!tok || tok == TOK_VAR) {\n                    /* generate reference */\n                    /* source -- source source */\n                    emit_op(s, OP_dup);\n                    emit_op(s, OP_scope_get_var);\n                    emit_atom(s, prop_name);\n                    emit_u16(s, s->cur_func->scope_level);\n                    goto lvalue;\n                }\n                var_name = JS_DupAtom(s->ctx, prop_name);\n                /* source -- source val */\n                emit_op(s, OP_get_field2);\n                emit_u32(s, prop_name);\n            }\n        set_val:\n            if (tok) {\n                if (js_define_var(s, var_name, tok))\n                    goto var_error;\n                scope = s->cur_func->scope_level;\n            }\n            if (s->token.val == '=') {  /* handle optional default value */\n                int label_hasval;\n                emit_op(s, OP_dup);\n                emit_op(s, OP_undefined);\n                emit_op(s, OP_strict_eq);\n                label_hasval = emit_goto(s, OP_if_false, -1);\n                if (next_token(s))\n                    goto var_error;\n                emit_op(s, OP_drop);\n                if (js_parse_assign_expr(s))\n                    goto var_error;\n                if (opcode == OP_scope_get_var || opcode == OP_get_ref_value)\n                    set_object_name(s, var_name);\n                emit_label(s, label_hasval);\n            }\n            /* store value into lvalue object */\n            put_lvalue(s, opcode, scope, var_name, label_lvalue,\n                       PUT_LVALUE_NOKEEP_DEPTH,\n                       (tok == TOK_CONST || tok == TOK_LET));\n            if (s->token.val == '}')\n                break;\n            /* accept a trailing comma before the '}' */\n            if (js_parse_expect(s, ','))\n                return -1;\n        }\n        /* drop the source object */\n        emit_op(s, OP_drop);\n        if (has_ellipsis) {\n            emit_op(s, OP_drop); /* pop excludeList */\n        }\n        if (next_token(s))\n            return -1;\n    } else if (s->token.val == '[') {\n        BOOL has_spread;\n        int enum_depth;\n        BlockEnv block_env;\n\n        if (next_token(s))\n            return -1;\n        /* the block environment is only needed in generators in case\n           'yield' triggers a 'return' */\n        push_break_entry(s->cur_func, &block_env,\n                         JS_ATOM_NULL, -1, -1, 2);\n        block_env.has_iterator = TRUE;\n        emit_op(s, OP_for_of_start);\n        has_spread = FALSE;\n        while (s->token.val != ']') {\n            /* get the next value */\n            if (s->token.val == TOK_ELLIPSIS) {\n                if (next_token(s))\n                    return -1;\n                if (s->token.val == ',' || s->token.val == ']')\n                    return js_parse_error(s, \"missing binding pattern...\");\n                has_spread = TRUE;\n            }\n            if (s->token.val == ',') {\n                /* do nothing, skip the value, has_spread is false */\n                emit_op(s, OP_for_of_next);\n                emit_u8(s, 0);\n                emit_op(s, OP_drop);\n                emit_op(s, OP_drop);\n            } else if ((s->token.val == '[' || s->token.val == '{')\n                   &&  ((tok1 = js_parse_skip_parens_token(s, &skip_bits, FALSE)) == ',' ||\n                        tok1 == '=' || tok1 == ']')) {\n                if (has_spread) {\n                    if (tok1 == '=')\n                        return js_parse_error(s, \"rest element cannot have a default value\");\n                    js_emit_spread_code(s, 0);\n                } else {\n                    emit_op(s, OP_for_of_next);\n                    emit_u8(s, 0);\n                    emit_op(s, OP_drop);\n                }\n                if (js_parse_destructuring_element(s, tok, is_arg, TRUE, skip_bits & SKIP_HAS_ELLIPSIS, TRUE) < 0)\n                    return -1;\n            } else {\n                var_name = JS_ATOM_NULL;\n                enum_depth = 0;\n                if (tok) {\n                    var_name = js_parse_destructuring_var(s, tok, is_arg);\n                    if (var_name == JS_ATOM_NULL)\n                        goto var_error;\n                    if (js_define_var(s, var_name, tok))\n                        goto var_error;\n                    opcode = OP_scope_get_var;\n                    scope = s->cur_func->scope_level;\n                } else {\n                    if (js_parse_left_hand_side_expr(s))\n                        return -1;\n                    if (get_lvalue(s, &opcode, &scope, &var_name,\n                                   &label_lvalue, &enum_depth, FALSE, '[')) {\n                        return -1;\n                    }\n                }\n                if (has_spread) {\n                    js_emit_spread_code(s, enum_depth);\n                } else {\n                    emit_op(s, OP_for_of_next);\n                    emit_u8(s, enum_depth);\n                    emit_op(s, OP_drop);\n                }\n                if (s->token.val == '=' && !has_spread) {\n                    /* handle optional default value */\n                    int label_hasval;\n                    emit_op(s, OP_dup);\n                    emit_op(s, OP_undefined);\n                    emit_op(s, OP_strict_eq);\n                    label_hasval = emit_goto(s, OP_if_false, -1);\n                    if (next_token(s))\n                        goto var_error;\n                    emit_op(s, OP_drop);\n                    if (js_parse_assign_expr(s))\n                        goto var_error;\n                    if (opcode == OP_scope_get_var || opcode == OP_get_ref_value)\n                        set_object_name(s, var_name);\n                    emit_label(s, label_hasval);\n                }\n                /* store value into lvalue object */\n                put_lvalue(s, opcode, scope, var_name,\n                           label_lvalue, PUT_LVALUE_NOKEEP_DEPTH,\n                           (tok == TOK_CONST || tok == TOK_LET));\n            }\n            if (s->token.val == ']')\n                break;\n            if (has_spread)\n                return js_parse_error(s, \"rest element must be the last one\");\n            /* accept a trailing comma before the ']' */\n            if (js_parse_expect(s, ','))\n                return -1;\n        }\n        /* close iterator object:\n           if completed, enum_obj has been replaced by undefined */\n        emit_op(s, OP_iterator_close);\n        pop_break_entry(s->cur_func);\n        if (next_token(s))\n            return -1;\n    } else {\n        return js_parse_error(s, \"invalid assignment syntax\");\n    }\n    if (s->token.val == '=' && allow_initializer) {\n        label_done = emit_goto(s, OP_goto, -1);\n        if (next_token(s))\n            return -1;\n        emit_label(s, label_parse);\n        if (hasval)\n            emit_op(s, OP_drop);\n        if (js_parse_assign_expr(s))\n            return -1;\n        emit_goto(s, OP_goto, label_assign);\n        emit_label(s, label_done);\n        has_initializer = TRUE;\n    } else {\n        /* normally hasval is true except if\n           js_parse_skip_parens_token() was wrong in the parsing */\n        //        assert(hasval);\n        if (!hasval) {\n            js_parse_error(s, \"too complicated destructuring expression\");\n            return -1;\n        }\n        /* remove test and decrement label ref count */\n        memset(s->cur_func->byte_code.buf + start_addr, OP_nop,\n               assign_addr - start_addr);\n        s->cur_func->label_slots[label_parse].ref_count--;\n        has_initializer = FALSE;\n    }\n    return has_initializer;\n\n prop_error:\n    JS_FreeAtom(s->ctx, prop_name);\n var_error:\n    JS_FreeAtom(s->ctx, var_name);\n    return -1;\n}\n\ntypedef enum FuncCallType {\n    FUNC_CALL_NORMAL,\n    FUNC_CALL_NEW,\n    FUNC_CALL_SUPER_CTOR,\n    FUNC_CALL_TEMPLATE,\n} FuncCallType;\n\nstatic void optional_chain_test(JSParseState *s, int *poptional_chaining_label,\n                                int drop_count)\n{\n    int label_next, i;\n    if (*poptional_chaining_label < 0)\n        *poptional_chaining_label = new_label(s);\n   /* XXX: could be more efficient with a specific opcode */\n    emit_op(s, OP_dup);\n    emit_op(s, OP_is_undefined_or_null);\n    label_next = emit_goto(s, OP_if_false, -1);\n    for(i = 0; i < drop_count; i++)\n        emit_op(s, OP_drop);\n    emit_op(s, OP_undefined);\n    emit_goto(s, OP_goto, *poptional_chaining_label);\n    emit_label(s, label_next);\n}\n\n/* allowed parse_flags: PF_POSTFIX_CALL, PF_ARROW_FUNC */\nstatic __exception int js_parse_postfix_expr(JSParseState *s, int parse_flags)\n{\n    FuncCallType call_type;\n    int optional_chaining_label;\n    BOOL accept_lparen = (parse_flags & PF_POSTFIX_CALL) != 0;\n    \n    call_type = FUNC_CALL_NORMAL;\n    switch(s->token.val) {\n    case TOK_NUMBER:\n        {\n            JSValue val;\n            val = s->token.u.num.val;\n\n            if (JS_VALUE_GET_TAG(val) == JS_TAG_INT) {\n                emit_op(s, OP_push_i32);\n                emit_u32(s, JS_VALUE_GET_INT(val));\n            } else\n#ifdef CONFIG_BIGNUM\n            if (JS_VALUE_GET_TAG(val) == JS_TAG_BIG_FLOAT) {\n                slimb_t e;\n                int ret;\n\n                /* need a runtime conversion */\n                /* XXX: could add a cache and/or do it once at\n                   the start of the function */\n                if (emit_push_const(s, val, 0) < 0)\n                    return -1;\n                e = s->token.u.num.exponent;\n                if (e == (int32_t)e) {\n                    emit_op(s, OP_push_i32);\n                    emit_u32(s, e);\n                } else {\n                    val = JS_NewBigInt64_1(s->ctx, e);\n                    if (JS_IsException(val))\n                        return -1;\n                    ret = emit_push_const(s, val, 0);\n                    JS_FreeValue(s->ctx, val);\n                    if (ret < 0)\n                        return -1;\n                }\n                emit_op(s, OP_mul_pow10);\n            } else\n#endif\n            {\n                if (emit_push_const(s, val, 0) < 0)\n                    return -1;\n            }\n        }\n        if (next_token(s))\n            return -1;\n        break;\n    case TOK_TEMPLATE:\n        if (js_parse_template(s, 0, NULL))\n            return -1;\n        break;\n    case TOK_STRING:\n        if (emit_push_const(s, s->token.u.str.str, 1))\n            return -1;\n        if (next_token(s))\n            return -1;\n        break;\n        \n    case TOK_DIV_ASSIGN:\n        s->buf_ptr -= 2;\n        goto parse_regexp;\n    case '/':\n        s->buf_ptr--;\n    parse_regexp:\n        {\n            JSValue str;\n            int ret, backtrace_flags;\n            if (!s->ctx->compile_regexp)\n                return js_parse_error(s, \"RegExp are not supported\");\n            /* the previous token is '/' or '/=', so no need to free */\n            if (js_parse_regexp(s))\n                return -1;\n            ret = emit_push_const(s, s->token.u.regexp.body, 0);\n            str = s->ctx->compile_regexp(s->ctx, s->token.u.regexp.body,\n                                         s->token.u.regexp.flags);\n            if (JS_IsException(str)) {\n                /* add the line number info */\n                backtrace_flags = 0;\n                if (s->cur_func && s->cur_func->backtrace_barrier)\n                    backtrace_flags = JS_BACKTRACE_FLAG_SINGLE_LEVEL;\n                build_backtrace(s->ctx, s->ctx->rt->current_exception,\n                                s->filename, s->token.line_num,\n                                backtrace_flags);\n                return -1;\n            }\n            ret = emit_push_const(s, str, 0);\n            JS_FreeValue(s->ctx, str);\n            if (ret)\n                return -1;\n            /* we use a specific opcode to be sure the correct\n               function is called (otherwise the bytecode would have\n               to be verified by the RegExp constructor) */\n            emit_op(s, OP_regexp);\n            if (next_token(s))\n                return -1;\n        }\n        break;\n    case '(':\n        if ((parse_flags & PF_ARROW_FUNC) &&\n            js_parse_skip_parens_token(s, NULL, TRUE) == TOK_ARROW) {\n            if (js_parse_function_decl(s, JS_PARSE_FUNC_ARROW,\n                                       JS_FUNC_NORMAL, JS_ATOM_NULL,\n                                       s->token.ptr, s->token.line_num))\n                return -1;\n        } else {\n            if (js_parse_expr_paren(s))\n                return -1;\n        }\n        break;\n    case TOK_FUNCTION:\n        if (js_parse_function_decl(s, JS_PARSE_FUNC_EXPR,\n                                   JS_FUNC_NORMAL, JS_ATOM_NULL,\n                                   s->token.ptr, s->token.line_num))\n            return -1;\n        break;\n    case TOK_CLASS:\n        if (js_parse_class(s, TRUE, JS_PARSE_EXPORT_NONE))\n            return -1;\n        break;\n    case TOK_NULL:\n        if (next_token(s))\n            return -1;\n        emit_op(s, OP_null);\n        break;\n    case TOK_THIS:\n        if (next_token(s))\n            return -1;\n        emit_op(s, OP_scope_get_var);\n        emit_atom(s, JS_ATOM_this);\n        emit_u16(s, 0);\n        break;\n    case TOK_FALSE:\n        if (next_token(s))\n            return -1;\n        emit_op(s, OP_push_false);\n        break;\n    case TOK_TRUE:\n        if (next_token(s))\n            return -1;\n        emit_op(s, OP_push_true);\n        break;\n    case TOK_IDENT:\n        {\n            JSAtom name;\n            if (s->token.u.ident.is_reserved) {\n                return js_parse_error_reserved_identifier(s);\n            }\n            if ((parse_flags & PF_ARROW_FUNC) &&\n                peek_token(s, TRUE) == TOK_ARROW) {\n                if (js_parse_function_decl(s, JS_PARSE_FUNC_ARROW,\n                                           JS_FUNC_NORMAL, JS_ATOM_NULL,\n                                           s->token.ptr, s->token.line_num))\n                    return -1;\n            } else if (token_is_pseudo_keyword(s, JS_ATOM_async) &&\n                       peek_token(s, TRUE) != '\\n') {\n                const uint8_t *source_ptr;\n                int source_line_num;\n\n                source_ptr = s->token.ptr;\n                source_line_num = s->token.line_num;\n                if (next_token(s))\n                    return -1;\n                if (s->token.val == TOK_FUNCTION) {\n                    if (js_parse_function_decl(s, JS_PARSE_FUNC_EXPR,\n                                               JS_FUNC_ASYNC, JS_ATOM_NULL,\n                                               source_ptr, source_line_num))\n                        return -1;\n                } else if ((parse_flags & PF_ARROW_FUNC) &&\n                           ((s->token.val == '(' &&\n                             js_parse_skip_parens_token(s, NULL, TRUE) == TOK_ARROW) ||\n                            (s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved &&\n                             peek_token(s, TRUE) == TOK_ARROW))) {\n                    if (js_parse_function_decl(s, JS_PARSE_FUNC_ARROW,\n                                               JS_FUNC_ASYNC, JS_ATOM_NULL,\n                                               source_ptr, source_line_num))\n                        return -1;\n                } else {\n                    name = JS_DupAtom(s->ctx, JS_ATOM_async);\n                    goto do_get_var;\n                }\n            } else {\n                if (s->token.u.ident.atom == JS_ATOM_arguments &&\n                    !s->cur_func->arguments_allowed) {\n                    js_parse_error(s, \"'arguments' identifier is not allowed in class field initializer\");\n                    return -1;\n                }\n                name = JS_DupAtom(s->ctx, s->token.u.ident.atom);\n                if (next_token(s))  /* update line number before emitting code */\n                    return -1;\n            do_get_var:\n                emit_op(s, OP_scope_get_var);\n                emit_u32(s, name);\n                emit_u16(s, s->cur_func->scope_level);\n            }\n        }\n        break;\n    case '{':\n    case '[':\n        {\n            int skip_bits;\n            if (js_parse_skip_parens_token(s, &skip_bits, FALSE) == '=') {\n                if (js_parse_destructuring_element(s, 0, 0, FALSE, skip_bits & SKIP_HAS_ELLIPSIS, TRUE) < 0)\n                    return -1;\n            } else {\n                if (s->token.val == '{') {\n                    if (js_parse_object_literal(s))\n                        return -1;\n                } else {\n                    if (js_parse_array_literal(s))\n                        return -1;\n                }\n            }\n        }\n        break;\n    case TOK_NEW:\n        if (next_token(s))\n            return -1;\n        if (s->token.val == '.') {\n            if (next_token(s))\n                return -1;\n            if (!token_is_pseudo_keyword(s, JS_ATOM_target))\n                return js_parse_error(s, \"expecting target\");\n            if (!s->cur_func->new_target_allowed)\n                return js_parse_error(s, \"new.target only allowed within functions\");\n            if (next_token(s))\n                return -1;\n            emit_op(s, OP_scope_get_var);\n            emit_atom(s, JS_ATOM_new_target);\n            emit_u16(s, 0);\n        } else {\n            if (js_parse_postfix_expr(s, 0))\n                return -1;\n            accept_lparen = TRUE;\n            if (s->token.val != '(') {\n                /* new operator on an object */\n                emit_op(s, OP_dup);\n                emit_op(s, OP_call_constructor);\n                emit_u16(s, 0);\n            } else {\n                call_type = FUNC_CALL_NEW;\n            }\n        }\n        break;\n    case TOK_SUPER:\n        if (next_token(s))\n            return -1;\n        if (s->token.val == '(') {\n            if (!s->cur_func->super_call_allowed)\n                return js_parse_error(s, \"super() is only valid in a derived class constructor\");\n            call_type = FUNC_CALL_SUPER_CTOR;\n        } else if (s->token.val == '.' || s->token.val == '[') {\n            if (!s->cur_func->super_allowed)\n                return js_parse_error(s, \"'super' is only valid in a method\");\n            emit_op(s, OP_scope_get_var);\n            emit_atom(s, JS_ATOM_this);\n            emit_u16(s, 0);\n            emit_op(s, OP_scope_get_var);\n            emit_atom(s, JS_ATOM_home_object);\n            emit_u16(s, 0);\n            emit_op(s, OP_get_super);\n        } else {\n            return js_parse_error(s, \"invalid use of 'super'\");\n        }\n        break;\n    case TOK_IMPORT:\n        if (next_token(s))\n            return -1;\n        if (s->token.val == '.') {\n            if (next_token(s))\n                return -1;\n            if (!token_is_pseudo_keyword(s, JS_ATOM_meta))\n                return js_parse_error(s, \"meta expected\");\n            if (!s->is_module)\n                return js_parse_error(s, \"import.meta only valid in module code\");\n            if (next_token(s))\n                return -1;\n            emit_op(s, OP_special_object);\n            emit_u8(s, OP_SPECIAL_OBJECT_IMPORT_META);\n        } else {\n            if (js_parse_expect(s, '('))\n                return -1;\n            if (!accept_lparen)\n                return js_parse_error(s, \"invalid use of 'import()'\");\n            if (js_parse_assign_expr(s))\n                return -1;\n            if (js_parse_expect(s, ')'))\n                return -1;\n            emit_op(s, OP_import);\n        }\n        break;\n    default:\n        return js_parse_error(s, \"unexpected token in expression: '%.*s'\",\n                              (int)(s->buf_ptr - s->token.ptr), s->token.ptr);\n    }\n\n    optional_chaining_label = -1;\n    for(;;) {\n        JSFunctionDef *fd = s->cur_func;\n        BOOL has_optional_chain = FALSE;\n        \n        if (s->token.val == TOK_QUESTION_MARK_DOT) {\n            /* optional chaining */\n            if (next_token(s))\n                return -1;\n            has_optional_chain = TRUE;\n            if (s->token.val == '(' && accept_lparen) {\n                goto parse_func_call;\n            } else if (s->token.val == '[') {\n                goto parse_array_access;\n            } else {\n                goto parse_property;\n            }\n        } else if (s->token.val == TOK_TEMPLATE &&\n                   call_type == FUNC_CALL_NORMAL) {\n            if (optional_chaining_label >= 0) {\n                return js_parse_error(s, \"template literal cannot appear in an optional chain\");\n            }\n            call_type = FUNC_CALL_TEMPLATE;\n            goto parse_func_call2;\n        } else if (s->token.val == '(' && accept_lparen) {\n            int opcode, arg_count, drop_count;\n\n            /* function call */\n        parse_func_call:\n            if (next_token(s))\n                return -1;\n\n            if (call_type == FUNC_CALL_NORMAL) {\n            parse_func_call2:\n                switch(opcode = get_prev_opcode(fd)) {\n                case OP_get_field:\n                    /* keep the object on the stack */\n                    fd->byte_code.buf[fd->last_opcode_pos] = OP_get_field2;\n                    drop_count = 2;\n                    break;\n                case OP_scope_get_private_field:\n                    /* keep the object on the stack */\n                    fd->byte_code.buf[fd->last_opcode_pos] = OP_scope_get_private_field2;\n                    drop_count = 2;\n                    break;\n                case OP_get_array_el:\n                    /* keep the object on the stack */\n                    fd->byte_code.buf[fd->last_opcode_pos] = OP_get_array_el2;\n                    drop_count = 2;\n                    break;\n                case OP_scope_get_var:\n                    {\n                        JSAtom name;\n                        int scope;\n                        name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);\n                        scope = get_u16(fd->byte_code.buf + fd->last_opcode_pos + 5);\n                        if (name == JS_ATOM_eval && call_type == FUNC_CALL_NORMAL && !has_optional_chain) {\n                            /* direct 'eval' */\n                            opcode = OP_eval;\n                        } else {\n                            /* verify if function name resolves to a simple\n                               get_loc/get_arg: a function call inside a `with`\n                               statement can resolve to a method call of the\n                               `with` context object\n                             */\n                            /* XXX: always generate the OP_scope_get_ref\n                               and remove it in variable resolution\n                               pass ? */\n                            if (has_with_scope(fd, scope)) {\n                                opcode = OP_scope_get_ref;\n                                fd->byte_code.buf[fd->last_opcode_pos] = opcode;\n                            }\n                        }\n                        drop_count = 1;\n                    }\n                    break;\n                case OP_get_super_value:\n                    fd->byte_code.buf[fd->last_opcode_pos] = OP_get_array_el;\n                    /* on stack: this func_obj */\n                    opcode = OP_get_array_el;\n                    drop_count = 2;\n                    break;\n                default:\n                    opcode = OP_invalid;\n                    drop_count = 1;\n                    break;\n                }\n                if (has_optional_chain) {\n                    optional_chain_test(s, &optional_chaining_label,\n                                        drop_count);\n                }\n            } else {\n                opcode = OP_invalid;\n            }\n\n            if (call_type == FUNC_CALL_TEMPLATE) {\n                if (js_parse_template(s, 1, &arg_count))\n                    return -1;\n                goto emit_func_call;\n            } else if (call_type == FUNC_CALL_SUPER_CTOR) {\n                emit_op(s, OP_scope_get_var);\n                emit_atom(s, JS_ATOM_this_active_func);\n                emit_u16(s, 0);\n\n                emit_op(s, OP_get_super);\n\n                emit_op(s, OP_scope_get_var);\n                emit_atom(s, JS_ATOM_new_target);\n                emit_u16(s, 0);\n            } else if (call_type == FUNC_CALL_NEW) {\n                emit_op(s, OP_dup); /* new.target = function */\n            }\n\n            /* parse arguments */\n            arg_count = 0;\n            while (s->token.val != ')') {\n                if (arg_count >= 65535) {\n                    return js_parse_error(s, \"Too many call arguments\");\n                }\n                if (s->token.val == TOK_ELLIPSIS)\n                    break;\n                if (js_parse_assign_expr(s))\n                    return -1;\n                arg_count++;\n                if (s->token.val == ')')\n                    break;\n                /* accept a trailing comma before the ')' */\n                if (js_parse_expect(s, ','))\n                    return -1;\n            }\n            if (s->token.val == TOK_ELLIPSIS) {\n                emit_op(s, OP_array_from);\n                emit_u16(s, arg_count);\n                emit_op(s, OP_push_i32);\n                emit_u32(s, arg_count);\n\n                /* on stack: array idx */\n                while (s->token.val != ')') {\n                    if (s->token.val == TOK_ELLIPSIS) {\n                        if (next_token(s))\n                            return -1;\n                        if (js_parse_assign_expr(s))\n                            return -1;\n#if 1\n                        /* XXX: could pass is_last indicator? */\n                        emit_op(s, OP_append);\n#else\n                        int label_next, label_done;\n                        label_next = new_label(s);\n                        label_done = new_label(s);\n                        /* push enumerate object below array/idx pair */\n                        emit_op(s, OP_for_of_start);\n                        emit_op(s, OP_rot5l);\n                        emit_op(s, OP_rot5l);\n                        emit_label(s, label_next);\n                        /* on stack: enum_rec array idx */\n                        emit_op(s, OP_for_of_next);\n                        emit_u8(s, 2);\n                        emit_goto(s, OP_if_true, label_done);\n                        /* append element */\n                        /* enum_rec array idx val -> enum_rec array new_idx */\n                        emit_op(s, OP_define_array_el);\n                        emit_op(s, OP_inc);\n                        emit_goto(s, OP_goto, label_next);\n                        emit_label(s, label_done);\n                        /* close enumeration, drop enum_rec and idx */\n                        emit_op(s, OP_drop); /* drop undef */\n                        emit_op(s, OP_nip1); /* drop enum_rec */\n                        emit_op(s, OP_nip1);\n                        emit_op(s, OP_nip1);\n#endif\n                    } else {\n                        if (js_parse_assign_expr(s))\n                            return -1;\n                        /* array idx val */\n                        emit_op(s, OP_define_array_el);\n                        emit_op(s, OP_inc);\n                    }\n                    if (s->token.val == ')')\n                        break;\n                    /* accept a trailing comma before the ')' */\n                    if (js_parse_expect(s, ','))\n                        return -1;\n                }\n                if (next_token(s))\n                    return -1;\n                /* drop the index */\n                emit_op(s, OP_drop);\n\n                /* apply function call */\n                switch(opcode) {\n                case OP_get_field:\n                case OP_scope_get_private_field:\n                case OP_get_array_el:\n                case OP_scope_get_ref:\n                    /* obj func array -> func obj array */\n                    emit_op(s, OP_perm3);\n                    emit_op(s, OP_apply);\n                    emit_u16(s, call_type == FUNC_CALL_NEW);\n                    break;\n                case OP_eval:\n                    emit_op(s, OP_apply_eval);\n                    emit_u16(s, fd->scope_level);\n                    fd->has_eval_call = TRUE;\n                    break;\n                default:\n                    if (call_type == FUNC_CALL_SUPER_CTOR) {\n                        emit_op(s, OP_apply);\n                        emit_u16(s, 1);\n                        /* set the 'this' value */\n                        emit_op(s, OP_dup);\n                        emit_op(s, OP_scope_put_var_init);\n                        emit_atom(s, JS_ATOM_this);\n                        emit_u16(s, 0);\n\n                        emit_class_field_init(s);\n                    } else if (call_type == FUNC_CALL_NEW) {\n                        /* obj func array -> func obj array */\n                        emit_op(s, OP_perm3);\n                        emit_op(s, OP_apply);\n                        emit_u16(s, 1);\n                    } else {\n                        /* func array -> func undef array */\n                        emit_op(s, OP_undefined);\n                        emit_op(s, OP_swap);\n                        emit_op(s, OP_apply);\n                        emit_u16(s, 0);\n                    }\n                    break;\n                }\n            } else {\n                if (next_token(s))\n                    return -1;\n            emit_func_call:\n                switch(opcode) {\n                case OP_get_field:\n                case OP_scope_get_private_field:\n                case OP_get_array_el:\n                case OP_scope_get_ref:\n                    emit_op(s, OP_call_method);\n                    emit_u16(s, arg_count);\n                    break;\n                case OP_eval:\n                    emit_op(s, OP_eval);\n                    emit_u16(s, arg_count);\n                    emit_u16(s, fd->scope_level);\n                    fd->has_eval_call = TRUE;\n                    break;\n                default:\n                    if (call_type == FUNC_CALL_SUPER_CTOR) {\n                        emit_op(s, OP_call_constructor);\n                        emit_u16(s, arg_count);\n\n                        /* set the 'this' value */\n                        emit_op(s, OP_dup);\n                        emit_op(s, OP_scope_put_var_init);\n                        emit_atom(s, JS_ATOM_this);\n                        emit_u16(s, 0);\n\n                        emit_class_field_init(s);\n                    } else if (call_type == FUNC_CALL_NEW) {\n                        emit_op(s, OP_call_constructor);\n                        emit_u16(s, arg_count);\n                    } else {\n                        emit_op(s, OP_call);\n                        emit_u16(s, arg_count);\n                    }\n                    break;\n                }\n            }\n            call_type = FUNC_CALL_NORMAL;\n        } else if (s->token.val == '.') {\n            if (next_token(s))\n                return -1;\n        parse_property:\n            if (s->token.val == TOK_PRIVATE_NAME) {\n                /* private class field */\n                if (get_prev_opcode(fd) == OP_get_super) {\n                    return js_parse_error(s, \"private class field forbidden after super\");\n                }\n                if (has_optional_chain) {\n                    optional_chain_test(s, &optional_chaining_label, 1);\n                }\n                emit_op(s, OP_scope_get_private_field);\n                emit_atom(s, s->token.u.ident.atom);\n                emit_u16(s, s->cur_func->scope_level);\n            } else {\n                if (!token_is_ident(s->token.val)) {\n                    return js_parse_error(s, \"expecting field name\");\n                }\n                if (get_prev_opcode(fd) == OP_get_super) {\n                    JSValue val;\n                    int ret;\n                    val = JS_AtomToValue(s->ctx, s->token.u.ident.atom);\n                    ret = emit_push_const(s, val, 1);\n                    JS_FreeValue(s->ctx, val);\n                    if (ret)\n                        return -1;\n                    emit_op(s, OP_get_super_value);\n                } else {\n                    if (has_optional_chain) {\n                        optional_chain_test(s, &optional_chaining_label, 1);\n                    }\n                    emit_op(s, OP_get_field);\n                    emit_atom(s, s->token.u.ident.atom);\n                }\n            }\n            if (next_token(s))\n                return -1;\n        } else if (s->token.val == '[') {\n            int prev_op;\n\n        parse_array_access:\n            prev_op = get_prev_opcode(fd);\n            if (has_optional_chain) {\n                optional_chain_test(s, &optional_chaining_label, 1);\n            }\n            if (next_token(s))\n                return -1;\n            if (js_parse_expr(s))\n                return -1;\n            if (js_parse_expect(s, ']'))\n                return -1;\n            if (prev_op == OP_get_super) {\n                emit_op(s, OP_get_super_value);\n            } else {\n                emit_op(s, OP_get_array_el);\n            }\n        } else {\n            break;\n        }\n    }\n    if (optional_chaining_label >= 0)\n        emit_label(s, optional_chaining_label);\n    return 0;\n}\n\nstatic __exception int js_parse_delete(JSParseState *s)\n{\n    JSFunctionDef *fd = s->cur_func;\n    JSAtom name;\n    int opcode;\n\n    if (next_token(s))\n        return -1;\n    if (js_parse_unary(s, PF_POW_FORBIDDEN))\n        return -1;\n    switch(opcode = get_prev_opcode(fd)) {\n    case OP_get_field:\n        {\n            JSValue val;\n            int ret;\n\n            name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);\n            fd->byte_code.size = fd->last_opcode_pos;\n            fd->last_opcode_pos = -1;\n            val = JS_AtomToValue(s->ctx, name);\n            ret = emit_push_const(s, val, 1);\n            JS_FreeValue(s->ctx, val);\n            JS_FreeAtom(s->ctx, name);\n            if (ret)\n                return ret;\n        }\n        goto do_delete;\n    case OP_get_array_el:\n        fd->byte_code.size = fd->last_opcode_pos;\n        fd->last_opcode_pos = -1;\n    do_delete:\n        emit_op(s, OP_delete);\n        break;\n    case OP_scope_get_var:\n        /* 'delete this': this is not a reference */\n        name = get_u32(fd->byte_code.buf + fd->last_opcode_pos + 1);\n        if (name == JS_ATOM_this || name == JS_ATOM_new_target)\n            goto ret_true;\n        if (fd->js_mode & JS_MODE_STRICT) {\n            return js_parse_error(s, \"cannot delete a direct reference in strict mode\");\n        } else {\n            fd->byte_code.buf[fd->last_opcode_pos] = OP_scope_delete_var;\n        }\n        break;\n    case OP_scope_get_private_field:\n        return js_parse_error(s, \"cannot delete a private class field\");\n    case OP_get_super_value:\n        emit_op(s, OP_throw_error);\n        emit_atom(s, JS_ATOM_NULL);\n        emit_u8(s, JS_THROW_ERROR_DELETE_SUPER);\n        break;\n    default:\n    ret_true:\n        emit_op(s, OP_drop);\n        emit_op(s, OP_push_true);\n        break;\n    }\n    return 0;\n}\n\n/* allowed parse_flags: PF_ARROW_FUNC, PF_POW_ALLOWED, PF_POW_FORBIDDEN */\nstatic __exception int js_parse_unary(JSParseState *s, int parse_flags)\n{\n    int op;\n\n    switch(s->token.val) {\n    case '+':\n    case '-':\n    case '!':\n    case '~':\n    case TOK_VOID:\n        op = s->token.val;\n        if (next_token(s))\n            return -1;\n        if (js_parse_unary(s, PF_POW_FORBIDDEN))\n            return -1;\n        switch(op) {\n        case '-':\n            emit_op(s, OP_neg);\n            break;\n        case '+':\n            emit_op(s, OP_plus);\n            break;\n        case '!':\n            emit_op(s, OP_lnot);\n            break;\n        case '~':\n            emit_op(s, OP_not);\n            break;\n        case TOK_VOID:\n            emit_op(s, OP_drop);\n            emit_op(s, OP_undefined);\n            break;\n        default:\n            abort();\n        }\n        parse_flags = 0;\n        break;\n    case TOK_DEC:\n    case TOK_INC:\n        {\n            int opcode, op, scope, label;\n            JSAtom name;\n            op = s->token.val;\n            if (next_token(s))\n                return -1;\n            if (js_parse_unary(s, 0))\n                return -1;\n            if (get_lvalue(s, &opcode, &scope, &name, &label, NULL, TRUE, op))\n                return -1;\n            emit_op(s, OP_dec + op - TOK_DEC);\n            put_lvalue(s, opcode, scope, name, label, PUT_LVALUE_KEEP_TOP,\n                       FALSE);\n        }\n        break;\n    case TOK_TYPEOF:\n        {\n            JSFunctionDef *fd;\n            if (next_token(s))\n                return -1;\n            if (js_parse_unary(s, PF_POW_FORBIDDEN))\n                return -1;\n            /* reference access should not return an exception, so we\n               patch the get_var */\n            fd = s->cur_func;\n            if (get_prev_opcode(fd) == OP_scope_get_var) {\n                fd->byte_code.buf[fd->last_opcode_pos] = OP_scope_get_var_undef;\n            }\n            emit_op(s, OP_typeof);\n            parse_flags = 0;\n        }\n        break;\n    case TOK_DELETE:\n        if (js_parse_delete(s))\n            return -1;\n        parse_flags = 0;\n        break;\n    case TOK_AWAIT:\n        if (!(s->cur_func->func_kind & JS_FUNC_ASYNC))\n            return js_parse_error(s, \"unexpected 'await' keyword\");\n        if (!s->cur_func->in_function_body)\n            return js_parse_error(s, \"await in default expression\");\n        if (next_token(s))\n            return -1;\n        if (js_parse_unary(s, PF_POW_FORBIDDEN))\n            return -1;\n        emit_op(s, OP_await);\n        parse_flags = 0;\n        break;\n    default:\n        if (js_parse_postfix_expr(s, (parse_flags & PF_ARROW_FUNC) |\n                                  PF_POSTFIX_CALL))\n            return -1;\n        if (!s->got_lf &&\n            (s->token.val == TOK_DEC || s->token.val == TOK_INC)) {\n            int opcode, op, scope, label;\n            JSAtom name;\n            op = s->token.val;\n            if (get_lvalue(s, &opcode, &scope, &name, &label, NULL, TRUE, op))\n                return -1;\n            emit_op(s, OP_post_dec + op - TOK_DEC);\n            put_lvalue(s, opcode, scope, name, label, PUT_LVALUE_KEEP_SECOND,\n                       FALSE);\n            if (next_token(s))\n                return -1;        \n        }\n        break;\n    }\n    if (parse_flags & (PF_POW_ALLOWED | PF_POW_FORBIDDEN)) {\n#ifdef CONFIG_BIGNUM\n        if (s->token.val == TOK_POW || s->token.val == TOK_MATH_POW) {\n            /* Extended exponentiation syntax rules: we extend the ES7\n               grammar in order to have more intuitive semantics:\n               -2**2 evaluates to -4. */\n            if (!(s->cur_func->js_mode & JS_MODE_MATH)) {\n                if (parse_flags & PF_POW_FORBIDDEN) {\n                    JS_ThrowSyntaxError(s->ctx, \"unparenthesized unary expression can't appear on the left-hand side of '**'\");\n                    return -1;\n                }\n            }\n            if (next_token(s))\n                return -1;\n            if (js_parse_unary(s, PF_POW_ALLOWED))\n                return -1;\n            emit_op(s, OP_pow);\n        }\n#else\n        if (s->token.val == TOK_POW) {\n            /* Strict ES7 exponentiation syntax rules: To solve\n               conficting semantics between different implementations\n               regarding the precedence of prefix operators and the\n               postifx exponential, ES7 specifies that -2**2 is a\n               syntax error. */\n            if (parse_flags & PF_POW_FORBIDDEN) {\n                JS_ThrowSyntaxError(s->ctx, \"unparenthesized unary expression can't appear on the left-hand side of '**'\");\n                return -1;\n            }\n            if (next_token(s))\n                return -1;\n            if (js_parse_unary(s, PF_POW_ALLOWED))\n                return -1;\n            emit_op(s, OP_pow);\n        }\n#endif\n    }\n    return 0;\n}\n\n/* allowed parse_flags: PF_ARROW_FUNC, PF_IN_ACCEPTED */\nstatic __exception int js_parse_expr_binary(JSParseState *s, int level,\n                                            int parse_flags)\n{\n    int op, opcode;\n\n    if (level == 0) {\n        return js_parse_unary(s, (parse_flags & PF_ARROW_FUNC) |\n                              PF_POW_ALLOWED);\n    }\n    if (js_parse_expr_binary(s, level - 1, parse_flags))\n        return -1;\n    for(;;) {\n        op = s->token.val;\n        switch(level) {\n        case 1:\n            switch(op) {\n            case '*':\n                opcode = OP_mul;\n                break;\n            case '/':\n                opcode = OP_div;\n                break;\n            case '%':\n#ifdef CONFIG_BIGNUM\n                if (s->cur_func->js_mode & JS_MODE_MATH)\n                    opcode = OP_math_mod;\n                else\n#endif\n                    opcode = OP_mod;\n                break;\n            default:\n                return 0;\n            }\n            break;\n        case 2:\n            switch(op) {\n            case '+':\n                opcode = OP_add;\n                break;\n            case '-':\n                opcode = OP_sub;\n                break;\n            default:\n                return 0;\n            }\n            break;\n        case 3:\n            switch(op) {\n            case TOK_SHL:\n                opcode = OP_shl;\n                break;\n            case TOK_SAR:\n                opcode = OP_sar;\n                break;\n            case TOK_SHR:\n                opcode = OP_shr;\n                break;\n            default:\n                return 0;\n            }\n            break;\n        case 4:\n            switch(op) {\n            case '<':\n                opcode = OP_lt;\n                break;\n            case '>':\n                opcode = OP_gt;\n                break;\n            case TOK_LTE:\n                opcode = OP_lte;\n                break;\n            case TOK_GTE:\n                opcode = OP_gte;\n                break;\n            case TOK_INSTANCEOF:\n                opcode = OP_instanceof;\n                break;\n            case TOK_IN:\n                if (parse_flags & PF_IN_ACCEPTED) {\n                    opcode = OP_in;\n                } else {\n                    return 0;\n                }\n                break;\n            default:\n                return 0;\n            }\n            break;\n        case 5:\n            switch(op) {\n            case TOK_EQ:\n                opcode = OP_eq;\n                break;\n            case TOK_NEQ:\n                opcode = OP_neq;\n                break;\n            case TOK_STRICT_EQ:\n                opcode = OP_strict_eq;\n                break;\n            case TOK_STRICT_NEQ:\n                opcode = OP_strict_neq;\n                break;\n            default:\n                return 0;\n            }\n            break;\n        case 6:\n            switch(op) {\n            case '&':\n                opcode = OP_and;\n                break;\n            default:\n                return 0;\n            }\n            break;\n        case 7:\n            switch(op) {\n            case '^':\n                opcode = OP_xor;\n                break;\n            default:\n                return 0;\n            }\n            break;\n        case 8:\n            switch(op) {\n            case '|':\n                opcode = OP_or;\n                break;\n            default:\n                return 0;\n            }\n            break;\n        default:\n            abort();\n        }\n        if (next_token(s))\n            return -1;\n        if (js_parse_expr_binary(s, level - 1, parse_flags & ~PF_ARROW_FUNC))\n            return -1;\n        emit_op(s, opcode);\n    }\n    return 0;\n}\n\n/* allowed parse_flags: PF_ARROW_FUNC, PF_IN_ACCEPTED */\nstatic __exception int js_parse_logical_and_or(JSParseState *s, int op,\n                                               int parse_flags)\n{\n    int label1;\n\n    if (op == TOK_LAND) {\n        if (js_parse_expr_binary(s, 8, parse_flags))\n            return -1;\n    } else {\n        if (js_parse_logical_and_or(s, TOK_LAND, parse_flags))\n            return -1;\n    }\n    if (s->token.val == op) {\n        label1 = new_label(s);\n\n        for(;;) {\n            if (next_token(s))\n                return -1;\n            emit_op(s, OP_dup);\n            emit_goto(s, op == TOK_LAND ? OP_if_false : OP_if_true, label1);\n            emit_op(s, OP_drop);\n\n            if (op == TOK_LAND) {\n                if (js_parse_expr_binary(s, 8, parse_flags & ~PF_ARROW_FUNC))\n                    return -1;\n            } else {\n                if (js_parse_logical_and_or(s, TOK_LAND,\n                                            parse_flags & ~PF_ARROW_FUNC))\n                    return -1;\n            }\n            if (s->token.val != op) {\n                if (s->token.val == TOK_DOUBLE_QUESTION_MARK)\n                    return js_parse_error(s, \"cannot mix ?? with && or ||\");\n                break;\n            }\n        }\n\n        emit_label(s, label1);\n    }\n    return 0;\n}\n\nstatic __exception int js_parse_coalesce_expr(JSParseState *s, int parse_flags)\n{\n    int label1;\n    \n    if (js_parse_logical_and_or(s, TOK_LOR, parse_flags))\n        return -1;\n    if (s->token.val == TOK_DOUBLE_QUESTION_MARK) {\n        label1 = new_label(s);\n        for(;;) {\n            if (next_token(s))\n                return -1;\n            \n            emit_op(s, OP_dup);\n            emit_op(s, OP_is_undefined_or_null);\n            emit_goto(s, OP_if_false, label1);\n            emit_op(s, OP_drop);\n            \n            if (js_parse_expr_binary(s, 8, parse_flags & ~PF_ARROW_FUNC))\n                return -1;\n            if (s->token.val != TOK_DOUBLE_QUESTION_MARK)\n                break;\n        }\n        emit_label(s, label1);\n    }\n    return 0;\n}\n\n/* allowed parse_flags: PF_ARROW_FUNC, PF_IN_ACCEPTED */\nstatic __exception int js_parse_cond_expr(JSParseState *s, int parse_flags)\n{\n    int label1, label2;\n\n    if (js_parse_coalesce_expr(s, parse_flags))\n        return -1;\n    if (s->token.val == '?') {\n        if (next_token(s))\n            return -1;\n        label1 = emit_goto(s, OP_if_false, -1);\n\n        if (js_parse_assign_expr(s))\n            return -1;\n        if (js_parse_expect(s, ':'))\n            return -1;\n\n        label2 = emit_goto(s, OP_goto, -1);\n\n        emit_label(s, label1);\n\n        if (js_parse_assign_expr2(s, parse_flags & PF_IN_ACCEPTED))\n            return -1;\n\n        emit_label(s, label2);\n    }\n    return 0;\n}\n\nstatic void emit_return(JSParseState *s, BOOL hasval);\n\n/* allowed parse_flags: PF_IN_ACCEPTED */\nstatic __exception int js_parse_assign_expr2(JSParseState *s, int parse_flags)\n{\n    int opcode, op, scope;\n    JSAtom name0 = JS_ATOM_NULL;\n    JSAtom name;\n\n    if (s->token.val == TOK_YIELD) {\n        BOOL is_star = FALSE, is_async;\n        \n        if (!(s->cur_func->func_kind & JS_FUNC_GENERATOR))\n            return js_parse_error(s, \"unexpected 'yield' keyword\");\n        if (!s->cur_func->in_function_body)\n            return js_parse_error(s, \"yield in default expression\");\n        if (next_token(s))\n            return -1;\n        /* XXX: is there a better method to detect 'yield' without\n           parameters ? */\n        if (s->token.val != ';' && s->token.val != ')' &&\n            s->token.val != ']' && s->token.val != '}' &&\n            s->token.val != ',' && s->token.val != ':' && !s->got_lf) {\n            if (s->token.val == '*') {\n                is_star = TRUE;\n                if (next_token(s))\n                    return -1;\n            }\n            if (js_parse_assign_expr2(s, parse_flags))\n                return -1;\n        } else {\n            emit_op(s, OP_undefined);\n        }\n        is_async = (s->cur_func->func_kind == JS_FUNC_ASYNC_GENERATOR);\n\n        if (is_star) {\n            int label_loop, label_return, label_next;\n            int label_return1, label_yield, label_throw, label_throw1;\n            int label_throw2;\n\n            label_loop = new_label(s);\n            label_yield = new_label(s);\n\n            emit_op(s, is_async ? OP_for_await_of_start : OP_for_of_start);\n\n            /* remove the catch offset (XXX: could avoid pushing back\n               undefined) */\n            emit_op(s, OP_drop);\n            emit_op(s, OP_undefined);\n            \n            emit_op(s, OP_undefined); /* initial value */\n            \n            emit_label(s, label_loop);\n            emit_op(s, OP_iterator_next);\n            if (is_async)\n                emit_op(s, OP_await);\n            emit_op(s, OP_iterator_check_object);\n            emit_op(s, OP_get_field2);\n            emit_atom(s, JS_ATOM_done);\n            label_next = emit_goto(s, OP_if_true, -1); /* end of loop */\n            emit_label(s, label_yield);\n            if (is_async) {\n                /* OP_async_yield_star takes the value as parameter */\n                emit_op(s, OP_get_field);\n                emit_atom(s, JS_ATOM_value);\n                emit_op(s, OP_await);\n                emit_op(s, OP_async_yield_star);\n            } else {\n                /* OP_yield_star takes (value, done) as parameter */\n                emit_op(s, OP_yield_star);\n            }\n            emit_op(s, OP_dup);\n            label_return = emit_goto(s, OP_if_true, -1);\n            emit_op(s, OP_drop);\n            emit_goto(s, OP_goto, label_loop);\n            \n            emit_label(s, label_return);\n            emit_op(s, OP_push_i32);\n            emit_u32(s, 2);\n            emit_op(s, OP_strict_eq);\n            label_throw = emit_goto(s, OP_if_true, -1);\n            \n            /* return handling */\n            if (is_async)\n                emit_op(s, OP_await);\n            emit_op(s, OP_iterator_call);\n            emit_u8(s, 0);\n            label_return1 = emit_goto(s, OP_if_true, -1);\n            if (is_async)\n                emit_op(s, OP_await);\n            emit_op(s, OP_iterator_check_object);\n            emit_op(s, OP_get_field2);\n            emit_atom(s, JS_ATOM_done);\n            emit_goto(s, OP_if_false, label_yield);\n\n            emit_op(s, OP_get_field);\n            emit_atom(s, JS_ATOM_value);\n            \n            emit_label(s, label_return1);\n            emit_op(s, OP_nip);\n            emit_op(s, OP_nip);\n            emit_op(s, OP_nip);\n            emit_return(s, TRUE);\n            \n            /* throw handling */\n            emit_label(s, label_throw);\n            emit_op(s, OP_iterator_call);\n            emit_u8(s, 1);\n            label_throw1 = emit_goto(s, OP_if_true, -1);\n            if (is_async)\n                emit_op(s, OP_await);\n            emit_op(s, OP_iterator_check_object);\n            emit_op(s, OP_get_field2);\n            emit_atom(s, JS_ATOM_done);\n            emit_goto(s, OP_if_false, label_yield);\n            emit_goto(s, OP_goto, label_next);\n            /* close the iterator and throw a type error exception */\n            emit_label(s, label_throw1);\n            emit_op(s, OP_iterator_call);\n            emit_u8(s, 2);\n            label_throw2 = emit_goto(s, OP_if_true, -1);\n            if (is_async)\n                emit_op(s, OP_await);\n            emit_label(s, label_throw2);\n\n            emit_op(s, OP_throw_error);\n            emit_atom(s, JS_ATOM_NULL);\n            emit_u8(s, JS_THROW_ERROR_ITERATOR_THROW);\n            \n            emit_label(s, label_next);\n            emit_op(s, OP_get_field);\n            emit_atom(s, JS_ATOM_value);\n            emit_op(s, OP_nip); /* keep the value associated with\n                                   done = true */\n            emit_op(s, OP_nip);\n            emit_op(s, OP_nip);\n        } else {\n            int label_next;\n            \n            if (is_async)\n                emit_op(s, OP_await);\n            emit_op(s, OP_yield);\n            label_next = emit_goto(s, OP_if_false, -1);\n            emit_return(s, TRUE);\n            emit_label(s, label_next);\n        }\n        return 0;\n    }\n    if (s->token.val == TOK_IDENT) {\n        /* name0 is used to check for OP_set_name pattern, not duplicated */\n        name0 = s->token.u.ident.atom;\n    }\n    if (js_parse_cond_expr(s, parse_flags | PF_ARROW_FUNC))\n        return -1;\n\n    op = s->token.val;\n    if (op == '=' || (op >= TOK_MUL_ASSIGN && op <= TOK_POW_ASSIGN)) {\n        int label;\n        if (next_token(s))\n            return -1;\n        if (get_lvalue(s, &opcode, &scope, &name, &label, NULL, (op != '='), op) < 0)\n            return -1;\n\n        if (js_parse_assign_expr2(s, parse_flags)) {\n            JS_FreeAtom(s->ctx, name);\n            return -1;\n        }\n\n        if (op == '=') {\n            if (opcode == OP_get_ref_value && name == name0) {\n                set_object_name(s, name);\n            }\n        } else {\n            static const uint8_t assign_opcodes[] = {\n                OP_mul, OP_div, OP_mod, OP_add, OP_sub,\n                OP_shl, OP_sar, OP_shr, OP_and, OP_xor, OP_or,\n#ifdef CONFIG_BIGNUM\n                OP_pow,\n#endif\n                OP_pow,\n            };\n            op = assign_opcodes[op - TOK_MUL_ASSIGN];\n#ifdef CONFIG_BIGNUM\n            if (s->cur_func->js_mode & JS_MODE_MATH) {\n                if (op == OP_mod)\n                    op = OP_math_mod;\n            }\n#endif\n            emit_op(s, op);\n        }\n        put_lvalue(s, opcode, scope, name, label, PUT_LVALUE_KEEP_TOP, FALSE);\n    } else if (op >= TOK_LAND_ASSIGN && op <= TOK_DOUBLE_QUESTION_MARK_ASSIGN) {\n        int label, label1, depth_lvalue, label2;\n        \n        if (next_token(s))\n            return -1;\n        if (get_lvalue(s, &opcode, &scope, &name, &label,\n                       &depth_lvalue, TRUE, op) < 0)\n            return -1;\n\n        emit_op(s, OP_dup);\n        if (op == TOK_DOUBLE_QUESTION_MARK_ASSIGN)\n            emit_op(s, OP_is_undefined_or_null);\n        label1 = emit_goto(s, op == TOK_LOR_ASSIGN ? OP_if_true : OP_if_false,\n                           -1);\n        emit_op(s, OP_drop);\n        \n        if (js_parse_assign_expr2(s, parse_flags)) {\n            JS_FreeAtom(s->ctx, name);\n            return -1;\n        }\n\n        if (opcode == OP_get_ref_value && name == name0) {\n            set_object_name(s, name);\n        }\n        \n        switch(depth_lvalue) {\n        case 1:\n            emit_op(s, OP_insert2);\n            break;\n        case 2:\n            emit_op(s, OP_insert3);\n            break;\n        case 3:\n            emit_op(s, OP_insert4);\n            break;\n        default:\n            abort();\n        }\n\n        /* XXX: we disable the OP_put_ref_value optimization by not\n           using put_lvalue() otherwise depth_lvalue is not correct */\n        put_lvalue(s, opcode, scope, name, label, PUT_LVALUE_NOKEEP_DEPTH,\n                   FALSE);\n        label2 = emit_goto(s, OP_goto, -1);\n        \n        emit_label(s, label1);\n\n        /* remove the lvalue stack entries */\n        while (depth_lvalue != 0) {\n            emit_op(s, OP_nip);\n            depth_lvalue--;\n        }\n\n        emit_label(s, label2);\n    }\n    return 0;\n}\n\nstatic __exception int js_parse_assign_expr(JSParseState *s)\n{\n    return js_parse_assign_expr2(s, PF_IN_ACCEPTED);\n}\n\n/* allowed parse_flags: PF_IN_ACCEPTED */\nstatic __exception int js_parse_expr2(JSParseState *s, int parse_flags)\n{\n    BOOL comma = FALSE;\n    for(;;) {\n        if (js_parse_assign_expr2(s, parse_flags))\n            return -1;\n        if (comma) {\n            /* prevent get_lvalue from using the last expression\n               as an lvalue. This also prevents the conversion of\n               of get_var to get_ref for method lookup in function\n               call inside `with` statement.\n             */\n            s->cur_func->last_opcode_pos = -1;\n        }\n        if (s->token.val != ',')\n            break;\n        comma = TRUE;\n        if (next_token(s))\n            return -1;\n        emit_op(s, OP_drop);\n    }\n    return 0;\n}\n\nstatic __exception int js_parse_expr(JSParseState *s)\n{\n    return js_parse_expr2(s, PF_IN_ACCEPTED);\n}\n\nstatic void push_break_entry(JSFunctionDef *fd, BlockEnv *be,\n                             JSAtom label_name,\n                             int label_break, int label_cont,\n                             int drop_count)\n{\n    be->prev = fd->top_break;\n    fd->top_break = be;\n    be->label_name = label_name;\n    be->label_break = label_break;\n    be->label_cont = label_cont;\n    be->drop_count = drop_count;\n    be->label_finally = -1;\n    be->scope_level = fd->scope_level;\n    be->has_iterator = FALSE;\n}\n\nstatic void pop_break_entry(JSFunctionDef *fd)\n{\n    BlockEnv *be;\n    be = fd->top_break;\n    fd->top_break = be->prev;\n}\n\nstatic __exception int emit_break(JSParseState *s, JSAtom name, int is_cont)\n{\n    BlockEnv *top;\n    int i, scope_level;\n\n    scope_level = s->cur_func->scope_level;\n    top = s->cur_func->top_break;\n    while (top != NULL) {\n        close_scopes(s, scope_level, top->scope_level);\n        scope_level = top->scope_level;\n        if (is_cont &&\n            top->label_cont != -1 &&\n            (name == JS_ATOM_NULL || top->label_name == name)) {\n            /* continue stays inside the same block */\n            emit_goto(s, OP_goto, top->label_cont);\n            return 0;\n        }\n        if (!is_cont &&\n            top->label_break != -1 &&\n            (name == JS_ATOM_NULL || top->label_name == name)) {\n            emit_goto(s, OP_goto, top->label_break);\n            return 0;\n        }\n        i = 0;\n        if (top->has_iterator) {\n            emit_op(s, OP_iterator_close);\n            i += 3;\n        }\n        for(; i < top->drop_count; i++)\n            emit_op(s, OP_drop);\n        if (top->label_finally != -1) {\n            /* must push dummy value to keep same stack depth */\n            emit_op(s, OP_undefined);\n            emit_goto(s, OP_gosub, top->label_finally);\n            emit_op(s, OP_drop);\n        }\n        top = top->prev;\n    }\n    if (name == JS_ATOM_NULL) {\n        if (is_cont)\n            return js_parse_error(s, \"continue must be inside loop\");\n        else\n            return js_parse_error(s, \"break must be inside loop or switch\");\n    } else {\n        return js_parse_error(s, \"break/continue label not found\");\n    }\n}\n\n/* execute the finally blocks before return */\nstatic void emit_return(JSParseState *s, BOOL hasval)\n{\n    BlockEnv *top;\n    int drop_count;\n\n    drop_count = 0;\n    top = s->cur_func->top_break;\n    while (top != NULL) {\n        /* XXX: emit the appropriate OP_leave_scope opcodes? Probably not\n           required as all local variables will be closed upon returning\n           from JS_CallInternal, but not in the same order. */\n        if (top->has_iterator) {\n            /* with 'yield', the exact number of OP_drop to emit is\n               unknown, so we use a specific operation to look for\n               the catch offset */\n            if (!hasval) {\n                emit_op(s, OP_undefined);\n                hasval = TRUE;\n            }\n            emit_op(s, OP_iterator_close_return);\n            if (s->cur_func->func_kind == JS_FUNC_ASYNC_GENERATOR) {\n                int label_next, label_next2;\n\n                emit_op(s, OP_drop); /* catch offset */\n                emit_op(s, OP_drop); /* next */\n                emit_op(s, OP_get_field2);\n                emit_atom(s, JS_ATOM_return);\n                /* stack: iter_obj return_func */\n                emit_op(s, OP_dup);\n                emit_op(s, OP_is_undefined_or_null);\n                label_next = emit_goto(s, OP_if_true, -1);\n                emit_op(s, OP_call_method);\n                emit_u16(s, 0);\n                emit_op(s, OP_iterator_check_object);\n                emit_op(s, OP_await);\n                label_next2 = emit_goto(s, OP_goto, -1);\n                emit_label(s, label_next);\n                emit_op(s, OP_drop);\n                emit_label(s, label_next2);\n                emit_op(s, OP_drop);\n            } else {\n                emit_op(s, OP_iterator_close);\n            }\n            drop_count = -3;\n        }\n        drop_count += top->drop_count;\n        if (top->label_finally != -1) {\n            while(drop_count) {\n                /* must keep the stack top if hasval */\n                emit_op(s, hasval ? OP_nip : OP_drop);\n                drop_count--;\n            }\n            if (!hasval) {\n                /* must push return value to keep same stack size */\n                emit_op(s, OP_undefined);\n                hasval = TRUE;\n            }\n            emit_goto(s, OP_gosub, top->label_finally);\n        }\n        top = top->prev;\n    }\n    if (s->cur_func->is_derived_class_constructor) {\n        int label_return;\n\n        /* 'this' can be uninitialized, so it may be accessed only if\n           the derived class constructor does not return an object */\n        if (hasval) {\n            emit_op(s, OP_check_ctor_return);\n            label_return = emit_goto(s, OP_if_false, -1);\n            emit_op(s, OP_drop);\n        } else {\n            label_return = -1;\n        }\n\n        /* XXX: if this is not initialized, should throw the\n           ReferenceError in the caller realm */\n        emit_op(s, OP_scope_get_var);\n        emit_atom(s, JS_ATOM_this);\n        emit_u16(s, 0);\n\n        emit_label(s, label_return);\n        emit_op(s, OP_return);\n    } else if (s->cur_func->func_kind != JS_FUNC_NORMAL) {\n        if (!hasval) {\n            emit_op(s, OP_undefined);\n        } else if (s->cur_func->func_kind == JS_FUNC_ASYNC_GENERATOR) {\n            emit_op(s, OP_await);\n        }\n        emit_op(s, OP_return_async);\n    } else {\n        emit_op(s, hasval ? OP_return : OP_return_undef);\n    }\n}\n\n#define DECL_MASK_FUNC  (1 << 0) /* allow normal function declaration */\n/* ored with DECL_MASK_FUNC if function declarations are allowed with a label */\n#define DECL_MASK_FUNC_WITH_LABEL (1 << 1)\n#define DECL_MASK_OTHER (1 << 2) /* all other declarations */\n#define DECL_MASK_ALL   (DECL_MASK_FUNC | DECL_MASK_FUNC_WITH_LABEL | DECL_MASK_OTHER)\n\nstatic __exception int js_parse_statement_or_decl(JSParseState *s,\n                                                  int decl_mask);\n\nstatic __exception int js_parse_statement(JSParseState *s)\n{\n    return js_parse_statement_or_decl(s, 0);\n}\n\nstatic __exception int js_parse_block(JSParseState *s)\n{\n    if (js_parse_expect(s, '{'))\n        return -1;\n    if (s->token.val != '}') {\n        push_scope(s);\n        for(;;) {\n            if (js_parse_statement_or_decl(s, DECL_MASK_ALL))\n                return -1;\n            if (s->token.val == '}')\n                break;\n        }\n        pop_scope(s);\n    }\n    if (next_token(s))\n        return -1;\n    return 0;\n}\n\n/* allowed parse_flags: PF_IN_ACCEPTED */\nstatic __exception int js_parse_var(JSParseState *s, int parse_flags, int tok,\n                                    BOOL export_flag)\n{\n    JSContext *ctx = s->ctx;\n    JSFunctionDef *fd = s->cur_func;\n    JSAtom name = JS_ATOM_NULL;\n\n    for (;;) {\n        if (s->token.val == TOK_IDENT) {\n            if (s->token.u.ident.is_reserved) {\n                return js_parse_error_reserved_identifier(s);\n            }\n            name = JS_DupAtom(ctx, s->token.u.ident.atom);\n            if (name == JS_ATOM_let && (tok == TOK_LET || tok == TOK_CONST)) {\n                js_parse_error(s, \"'let' is not a valid lexical identifier\");\n                goto var_error;\n            }\n            if (next_token(s))\n                goto var_error;\n            if (js_define_var(s, name, tok))\n                goto var_error;\n            if (export_flag) {\n                if (!add_export_entry(s, s->cur_func->module, name, name,\n                                      JS_EXPORT_TYPE_LOCAL))\n                    goto var_error;\n            }\n\n            if (s->token.val == '=') {\n                if (next_token(s))\n                    goto var_error;\n                if (tok == TOK_VAR) {\n                    /* Must make a reference for proper `with` semantics */\n                    int opcode, scope, label;\n                    JSAtom name1;\n\n                    emit_op(s, OP_scope_get_var);\n                    emit_atom(s, name);\n                    emit_u16(s, fd->scope_level);\n                    if (get_lvalue(s, &opcode, &scope, &name1, &label, NULL, FALSE, '=') < 0)\n                        goto var_error;\n                    if (js_parse_assign_expr2(s, parse_flags)) {\n                        JS_FreeAtom(ctx, name1);\n                        goto var_error;\n                    }\n                    set_object_name(s, name);\n                    put_lvalue(s, opcode, scope, name1, label,\n                               PUT_LVALUE_NOKEEP, FALSE);\n                } else {\n                    if (js_parse_assign_expr2(s, parse_flags))\n                        goto var_error;\n                    set_object_name(s, name);\n                    emit_op(s, (tok == TOK_CONST || tok == TOK_LET) ?\n                        OP_scope_put_var_init : OP_scope_put_var);\n                    emit_atom(s, name);\n                    emit_u16(s, fd->scope_level);\n                }\n            } else {\n                if (tok == TOK_CONST) {\n                    js_parse_error(s, \"missing initializer for const variable\");\n                    goto var_error;\n                }\n                if (tok == TOK_LET) {\n                    /* initialize lexical variable upon entering its scope */\n                    emit_op(s, OP_undefined);\n                    emit_op(s, OP_scope_put_var_init);\n                    emit_atom(s, name);\n                    emit_u16(s, fd->scope_level);\n                }\n            }\n            JS_FreeAtom(ctx, name);\n        } else {\n            int skip_bits;\n            if ((s->token.val == '[' || s->token.val == '{')\n            &&  js_parse_skip_parens_token(s, &skip_bits, FALSE) == '=') {\n                emit_op(s, OP_undefined);\n                if (js_parse_destructuring_element(s, tok, 0, TRUE, skip_bits & SKIP_HAS_ELLIPSIS, TRUE) < 0)\n                    return -1;\n            } else {\n                return js_parse_error(s, \"variable name expected\");\n            }\n        }\n        if (s->token.val != ',')\n            break;\n        if (next_token(s))\n            return -1;\n    }\n    return 0;\n\n var_error:\n    JS_FreeAtom(ctx, name);\n    return -1;\n}\n\n/* test if the current token is a label. Use simplistic look-ahead scanner */\nstatic BOOL is_label(JSParseState *s)\n{\n    return (s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved &&\n            peek_token(s, FALSE) == ':');\n}\n\n/* test if the current token is a let keyword. Use simplistic look-ahead scanner */\nstatic int is_let(JSParseState *s, int decl_mask)\n{\n    int res = FALSE;\n\n    if (token_is_pseudo_keyword(s, JS_ATOM_let)) {\n#if 1\n        JSParsePos pos;\n        js_parse_get_pos(s, &pos);\n        for (;;) {\n            if (next_token(s)) {\n                res = -1;\n                break;\n            }\n            if (s->token.val == '[') {\n                /* let [ is a syntax restriction:\n                   it never introduces an ExpressionStatement */\n                res = TRUE;\n                break;\n            }\n            if (s->token.val == '{' ||\n                (s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved) ||\n                s->token.val == TOK_LET ||\n                s->token.val == TOK_YIELD ||\n                s->token.val == TOK_AWAIT) {\n                /* Check for possible ASI if not scanning for Declaration */\n                /* XXX: should also check that `{` introduces a BindingPattern,\n                   but Firefox does not and rejects eval(\"let=1;let\\n{if(1)2;}\") */\n                if (s->last_line_num == s->token.line_num || (decl_mask & DECL_MASK_OTHER)) {\n                    res = TRUE;\n                    break;\n                }\n                break;\n            }\n            break;\n        }\n        if (js_parse_seek_token(s, &pos)) {\n            res = -1;\n        }\n#else\n        int tok = peek_token(s, TRUE);\n        if (tok == '{' || tok == TOK_IDENT || peek_token(s, FALSE) == '[') {\n            res = TRUE;\n        }\n#endif\n    }\n    return res;\n}\n\n/* XXX: handle IteratorClose when exiting the loop before the\n   enumeration is done */\nstatic __exception int js_parse_for_in_of(JSParseState *s, int label_name,\n                                          BOOL is_async)\n{\n    JSContext *ctx = s->ctx;\n    JSFunctionDef *fd = s->cur_func;\n    JSAtom var_name;\n    BOOL has_initializer, is_for_of, has_destructuring;\n    int tok, tok1, opcode, scope, block_scope_level;\n    int label_next, label_expr, label_cont, label_body, label_break;\n    int pos_next, pos_expr;\n    BlockEnv break_entry;\n\n    has_initializer = FALSE;\n    has_destructuring = FALSE;\n    is_for_of = FALSE;\n    block_scope_level = fd->scope_level;\n    label_cont = new_label(s);\n    label_body = new_label(s);\n    label_break = new_label(s);\n    label_next = new_label(s);\n\n    /* create scope for the lexical variables declared in the enumeration\n       expressions. XXX: Not completely correct because of weird capturing\n       semantics in `for (i of o) a.push(function(){return i})` */\n    push_scope(s);\n\n    /* local for_in scope starts here so individual elements\n       can be closed in statement. */\n    push_break_entry(s->cur_func, &break_entry,\n                     label_name, label_break, label_cont, 1);\n    break_entry.scope_level = block_scope_level;\n\n    label_expr = emit_goto(s, OP_goto, -1);\n\n    pos_next = s->cur_func->byte_code.size;\n    emit_label(s, label_next);\n\n    tok = s->token.val;\n    switch (is_let(s, DECL_MASK_OTHER)) {\n    case TRUE:\n        tok = TOK_LET;\n        break;\n    case FALSE:\n        break;\n    default:\n        return -1;\n    }\n    if (tok == TOK_VAR || tok == TOK_LET || tok == TOK_CONST) {\n        if (next_token(s))\n            return -1;\n\n        if (!(s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved)) {\n            if (s->token.val == '[' || s->token.val == '{') {\n                if (js_parse_destructuring_element(s, tok, 0, TRUE, -1, FALSE) < 0)\n                    return -1;\n                has_destructuring = TRUE;\n            } else {\n                return js_parse_error(s, \"variable name expected\");\n            }\n            var_name = JS_ATOM_NULL;\n        } else {\n            var_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n            if (next_token(s)) {\n                JS_FreeAtom(s->ctx, var_name);\n                return -1;\n            }\n            if (js_define_var(s, var_name, tok)) {\n                JS_FreeAtom(s->ctx, var_name);\n                return -1;\n            }\n            emit_op(s, (tok == TOK_CONST || tok == TOK_LET) ?\n                    OP_scope_put_var_init : OP_scope_put_var);\n            emit_atom(s, var_name);\n            emit_u16(s, fd->scope_level);\n        }\n    } else {\n        int skip_bits;\n        if ((s->token.val == '[' || s->token.val == '{')\n        &&  ((tok1 = js_parse_skip_parens_token(s, &skip_bits, FALSE)) == TOK_IN || tok1 == TOK_OF)) {\n            if (js_parse_destructuring_element(s, 0, 0, TRUE, skip_bits & SKIP_HAS_ELLIPSIS, TRUE) < 0)\n                return -1;\n        } else {\n            int lvalue_label;\n            if (js_parse_left_hand_side_expr(s))\n                return -1;\n            if (get_lvalue(s, &opcode, &scope, &var_name, &lvalue_label,\n                           NULL, FALSE, TOK_FOR))\n                return -1;\n            put_lvalue(s, opcode, scope, var_name, lvalue_label,\n                       PUT_LVALUE_NOKEEP_BOTTOM, FALSE);\n        }\n        var_name = JS_ATOM_NULL;\n    }\n    emit_goto(s, OP_goto, label_body);\n\n    pos_expr = s->cur_func->byte_code.size;\n    emit_label(s, label_expr);\n    if (s->token.val == '=') {\n        /* XXX: potential scoping issue if inside `with` statement */\n        has_initializer = TRUE;\n        /* parse and evaluate initializer prior to evaluating the\n           object (only used with \"for in\" with a non lexical variable\n           in non strict mode */\n        if (next_token(s) || js_parse_assign_expr2(s, 0)) {\n            JS_FreeAtom(ctx, var_name);\n            return -1;\n        }\n        if (var_name != JS_ATOM_NULL) {\n            emit_op(s, OP_scope_put_var);\n            emit_atom(s, var_name);\n            emit_u16(s, fd->scope_level);\n        }\n    }\n    JS_FreeAtom(ctx, var_name);\n\n    if (token_is_pseudo_keyword(s, JS_ATOM_of)) {\n        break_entry.has_iterator = is_for_of = TRUE;\n        break_entry.drop_count += 2;\n        if (has_initializer)\n            goto initializer_error;\n    } else if (s->token.val == TOK_IN) {\n        if (is_async)\n            return js_parse_error(s, \"'for await' loop should be used with 'of'\");\n        if (has_initializer &&\n            (tok != TOK_VAR || (fd->js_mode & JS_MODE_STRICT) ||\n             has_destructuring)) {\n        initializer_error:\n            return js_parse_error(s, \"a declaration in the head of a for-%s loop can't have an initializer\",\n                                  is_for_of ? \"of\" : \"in\");\n        }\n    } else {\n        return js_parse_error(s, \"expected 'of' or 'in' in for control expression\");\n    }\n    if (next_token(s))\n        return -1;\n    if (is_for_of) {\n        if (js_parse_assign_expr(s))\n            return -1;\n    } else {\n        if (js_parse_expr(s))\n            return -1;\n    }\n    /* close the scope after having evaluated the expression so that\n       the TDZ values are in the closures */\n    close_scopes(s, s->cur_func->scope_level, block_scope_level);\n    if (is_for_of) {\n        if (is_async)\n            emit_op(s, OP_for_await_of_start);\n        else\n            emit_op(s, OP_for_of_start);\n        /* on stack: enum_rec */\n    } else {\n        emit_op(s, OP_for_in_start);\n        /* on stack: enum_obj */\n    }\n    emit_goto(s, OP_goto, label_cont);\n\n    if (js_parse_expect(s, ')'))\n        return -1;\n\n    if (OPTIMIZE) {\n        /* move the `next` code here */\n        DynBuf *bc = &s->cur_func->byte_code;\n        int chunk_size = pos_expr - pos_next;\n        int offset = bc->size - pos_next;\n        int i;\n        dbuf_realloc(bc, bc->size + chunk_size);\n        dbuf_put(bc, bc->buf + pos_next, chunk_size);\n        memset(bc->buf + pos_next, OP_nop, chunk_size);\n        /* `next` part ends with a goto */\n        s->cur_func->last_opcode_pos = bc->size - 5;\n        /* relocate labels */\n        for (i = label_cont; i < s->cur_func->label_count; i++) {\n            LabelSlot *ls = &s->cur_func->label_slots[i];\n            if (ls->pos >= pos_next && ls->pos < pos_expr)\n                ls->pos += offset;\n        }\n    }\n\n    emit_label(s, label_body);\n    if (js_parse_statement(s))\n        return -1;\n\n    close_scopes(s, s->cur_func->scope_level, block_scope_level);\n\n    emit_label(s, label_cont);\n    if (is_for_of) {\n        if (is_async) {\n            /* call the next method */\n            /* stack: iter_obj next catch_offset */\n            emit_op(s, OP_dup3);\n            emit_op(s, OP_drop);\n            emit_op(s, OP_call_method);\n            emit_u16(s, 0);\n            /* get the result of the promise */\n            emit_op(s, OP_await);\n            /* unwrap the value and done values */\n            emit_op(s, OP_iterator_get_value_done);\n        } else {\n            emit_op(s, OP_for_of_next);\n            emit_u8(s, 0);\n        }\n    } else {\n        emit_op(s, OP_for_in_next);\n    }\n    /* on stack: enum_rec / enum_obj value bool */\n    emit_goto(s, OP_if_false, label_next);\n    /* drop the undefined value from for_xx_next */\n    emit_op(s, OP_drop);\n\n    emit_label(s, label_break);\n    if (is_for_of) {\n        /* close and drop enum_rec */\n        emit_op(s, OP_iterator_close);\n    } else {\n        emit_op(s, OP_drop);\n    }\n    pop_break_entry(s->cur_func);\n    pop_scope(s);\n    return 0;\n}\n\nstatic void set_eval_ret_undefined(JSParseState *s)\n{\n    if (s->cur_func->eval_ret_idx >= 0) {\n        emit_op(s, OP_undefined);\n        emit_op(s, OP_put_loc);\n        emit_u16(s, s->cur_func->eval_ret_idx);\n    }\n}\n\nstatic __exception int js_parse_statement_or_decl(JSParseState *s,\n                                                  int decl_mask)\n{\n    JSContext *ctx = s->ctx;\n    JSAtom label_name;\n    int tok;\n\n    /* specific label handling */\n    /* XXX: support multiple labels on loop statements */\n    label_name = JS_ATOM_NULL;\n    if (is_label(s)) {\n        BlockEnv *be;\n\n        label_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n\n        for (be = s->cur_func->top_break; be; be = be->prev) {\n            if (be->label_name == label_name) {\n                js_parse_error(s, \"duplicate label name\");\n                goto fail;\n            }\n        }\n\n        if (next_token(s))\n            goto fail;\n        if (js_parse_expect(s, ':'))\n            goto fail;\n        if (s->token.val != TOK_FOR\n        &&  s->token.val != TOK_DO\n        &&  s->token.val != TOK_WHILE) {\n            /* labelled regular statement */\n            int label_break, mask;\n            BlockEnv break_entry;\n\n            label_break = new_label(s);\n            push_break_entry(s->cur_func, &break_entry,\n                             label_name, label_break, -1, 0);\n            if (!(s->cur_func->js_mode & JS_MODE_STRICT) &&\n                (decl_mask & DECL_MASK_FUNC_WITH_LABEL)) {\n                mask = DECL_MASK_FUNC | DECL_MASK_FUNC_WITH_LABEL;\n            } else {\n                mask = 0;\n            }\n            if (js_parse_statement_or_decl(s, mask))\n                goto fail;\n            emit_label(s, label_break);\n            pop_break_entry(s->cur_func);\n            goto done;\n        }\n    }\n\n    switch(tok = s->token.val) {\n    case '{':\n        if (js_parse_block(s))\n            goto fail;\n        break;\n    case TOK_RETURN:\n        if (s->cur_func->is_eval) {\n            js_parse_error(s, \"return not in a function\");\n            goto fail;\n        }\n        if (next_token(s))\n            goto fail;\n        if (s->token.val != ';' && s->token.val != '}' && !s->got_lf) {\n            if (js_parse_expr(s))\n                goto fail;\n            emit_return(s, TRUE);\n        } else {\n            emit_return(s, FALSE);\n        }\n        if (js_parse_expect_semi(s))\n            goto fail;\n        break;\n    case TOK_THROW:\n        if (next_token(s))\n            goto fail;\n        if (s->got_lf) {\n            js_parse_error(s, \"line terminator not allowed after throw\");\n            goto fail;\n        }\n        if (js_parse_expr(s))\n            goto fail;\n        emit_op(s, OP_throw);\n        if (js_parse_expect_semi(s))\n            goto fail;\n        break;\n    case TOK_LET:\n    case TOK_CONST:\n    haslet:\n        if (!(decl_mask & DECL_MASK_OTHER)) {\n            js_parse_error(s, \"lexical declarations can't appear in single-statement context\");\n            goto fail;\n        }\n        /* fall thru */\n    case TOK_VAR:\n        if (next_token(s))\n            goto fail;\n        if (js_parse_var(s, TRUE, tok, FALSE))\n            goto fail;\n        if (js_parse_expect_semi(s))\n            goto fail;\n        break;\n    case TOK_IF:\n        {\n            int label1, label2, mask;\n            if (next_token(s))\n                goto fail;\n            /* create a new scope for `let f;if(1) function f(){}` */\n            push_scope(s);\n            set_eval_ret_undefined(s);\n            if (js_parse_expr_paren(s))\n                goto fail;\n            label1 = emit_goto(s, OP_if_false, -1);\n            if (s->cur_func->js_mode & JS_MODE_STRICT)\n                mask = 0;\n            else\n                mask = DECL_MASK_FUNC; /* Annex B.3.4 */\n\n            if (js_parse_statement_or_decl(s, mask))\n                goto fail;\n\n            if (s->token.val == TOK_ELSE) {\n                label2 = emit_goto(s, OP_goto, -1);\n                if (next_token(s))\n                    goto fail;\n\n                emit_label(s, label1);\n                if (js_parse_statement_or_decl(s, mask))\n                    goto fail;\n\n                label1 = label2;\n            }\n            emit_label(s, label1);\n            pop_scope(s);\n        }\n        break;\n    case TOK_WHILE:\n        {\n            int label_cont, label_break;\n            BlockEnv break_entry;\n\n            label_cont = new_label(s);\n            label_break = new_label(s);\n\n            push_break_entry(s->cur_func, &break_entry,\n                             label_name, label_break, label_cont, 0);\n\n            if (next_token(s))\n                goto fail;\n\n            set_eval_ret_undefined(s);\n\n            emit_label(s, label_cont);\n            if (js_parse_expr_paren(s))\n                goto fail;\n            emit_goto(s, OP_if_false, label_break);\n\n            if (js_parse_statement(s))\n                goto fail;\n            emit_goto(s, OP_goto, label_cont);\n\n            emit_label(s, label_break);\n\n            pop_break_entry(s->cur_func);\n        }\n        break;\n    case TOK_DO:\n        {\n            int label_cont, label_break, label1;\n            BlockEnv break_entry;\n\n            label_cont = new_label(s);\n            label_break = new_label(s);\n            label1 = new_label(s);\n\n            push_break_entry(s->cur_func, &break_entry,\n                             label_name, label_break, label_cont, 0);\n\n            if (next_token(s))\n                goto fail;\n\n            emit_label(s, label1);\n\n            set_eval_ret_undefined(s);\n\n            if (js_parse_statement(s))\n                goto fail;\n\n            emit_label(s, label_cont);\n            if (js_parse_expect(s, TOK_WHILE))\n                goto fail;\n            if (js_parse_expr_paren(s))\n                goto fail;\n            /* Insert semicolon if missing */\n            if (s->token.val == ';') {\n                if (next_token(s))\n                    goto fail;\n            }\n            emit_goto(s, OP_if_true, label1);\n\n            emit_label(s, label_break);\n\n            pop_break_entry(s->cur_func);\n        }\n        break;\n    case TOK_FOR:\n        {\n            int label_cont, label_break, label_body, label_test;\n            int pos_cont, pos_body, block_scope_level;\n            BlockEnv break_entry;\n            int tok, bits;\n            BOOL is_async;\n\n            if (next_token(s))\n                goto fail;\n\n            set_eval_ret_undefined(s);\n            bits = 0;\n            is_async = FALSE;\n            if (s->token.val == '(') {\n                js_parse_skip_parens_token(s, &bits, FALSE);\n            } else if (s->token.val == TOK_AWAIT) {\n                if (!(s->cur_func->func_kind & JS_FUNC_ASYNC)) {\n                    js_parse_error(s, \"for await is only valid in asynchronous functions\");\n                    goto fail;\n                }\n                is_async = TRUE;\n                if (next_token(s))\n                    goto fail;\n            }\n            if (js_parse_expect(s, '('))\n                goto fail;\n\n            if (!(bits & SKIP_HAS_SEMI)) {\n                /* parse for/in or for/of */\n                if (js_parse_for_in_of(s, label_name, is_async))\n                    goto fail;\n                break;\n            }\n            block_scope_level = s->cur_func->scope_level;\n\n            /* create scope for the lexical variables declared in the initial,\n               test and increment expressions */\n            push_scope(s);\n            /* initial expression */\n            tok = s->token.val;\n            if (tok != ';') {\n                switch (is_let(s, DECL_MASK_OTHER)) {\n                case TRUE:\n                    tok = TOK_LET;\n                    break;\n                case FALSE:\n                    break;\n                default:\n                    goto fail;\n                }\n                if (tok == TOK_VAR || tok == TOK_LET || tok == TOK_CONST) {\n                    if (next_token(s))\n                        goto fail;\n                    if (js_parse_var(s, FALSE, tok, FALSE))\n                        goto fail;\n                } else {\n                    if (js_parse_expr2(s, FALSE))\n                        goto fail;\n                    emit_op(s, OP_drop);\n                }\n\n                /* close the closures before the first iteration */\n                close_scopes(s, s->cur_func->scope_level, block_scope_level);\n            }\n            if (js_parse_expect(s, ';'))\n                goto fail;\n\n            label_test = new_label(s);\n            label_cont = new_label(s);\n            label_body = new_label(s);\n            label_break = new_label(s);\n\n            push_break_entry(s->cur_func, &break_entry,\n                             label_name, label_break, label_cont, 0);\n\n            /* test expression */\n            if (s->token.val == ';') {\n                /* no test expression */\n                label_test = label_body;\n            } else {\n                emit_label(s, label_test);\n                if (js_parse_expr(s))\n                    goto fail;\n                emit_goto(s, OP_if_false, label_break);\n            }\n            if (js_parse_expect(s, ';'))\n                goto fail;\n\n            if (s->token.val == ')') {\n                /* no end expression */\n                break_entry.label_cont = label_cont = label_test;\n                pos_cont = 0; /* avoid warning */\n            } else {\n                /* skip the end expression */\n                emit_goto(s, OP_goto, label_body);\n\n                pos_cont = s->cur_func->byte_code.size;\n                emit_label(s, label_cont);\n                if (js_parse_expr(s))\n                    goto fail;\n                emit_op(s, OP_drop);\n                if (label_test != label_body)\n                    emit_goto(s, OP_goto, label_test);\n            }\n            if (js_parse_expect(s, ')'))\n                goto fail;\n\n            pos_body = s->cur_func->byte_code.size;\n            emit_label(s, label_body);\n            if (js_parse_statement(s))\n                goto fail;\n\n            /* close the closures before the next iteration */\n            /* XXX: check continue case */\n            close_scopes(s, s->cur_func->scope_level, block_scope_level);\n\n            if (OPTIMIZE && label_test != label_body && label_cont != label_test) {\n                /* move the increment code here */\n                DynBuf *bc = &s->cur_func->byte_code;\n                int chunk_size = pos_body - pos_cont;\n                int offset = bc->size - pos_cont;\n                int i;\n                dbuf_realloc(bc, bc->size + chunk_size);\n                dbuf_put(bc, bc->buf + pos_cont, chunk_size);\n                memset(bc->buf + pos_cont, OP_nop, chunk_size);\n                /* increment part ends with a goto */\n                s->cur_func->last_opcode_pos = bc->size - 5;\n                /* relocate labels */\n                for (i = label_cont; i < s->cur_func->label_count; i++) {\n                    LabelSlot *ls = &s->cur_func->label_slots[i];\n                    if (ls->pos >= pos_cont && ls->pos < pos_body)\n                        ls->pos += offset;\n                }\n            } else {\n                emit_goto(s, OP_goto, label_cont);\n            }\n\n            emit_label(s, label_break);\n\n            pop_break_entry(s->cur_func);\n            pop_scope(s);\n        }\n        break;\n    case TOK_BREAK:\n    case TOK_CONTINUE:\n        {\n            int is_cont = s->token.val - TOK_BREAK;\n            int label;\n\n            if (next_token(s))\n                goto fail;\n            if (!s->got_lf && s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved)\n                label = s->token.u.ident.atom;\n            else\n                label = JS_ATOM_NULL;\n            if (emit_break(s, label, is_cont))\n                goto fail;\n            if (label != JS_ATOM_NULL) {\n                if (next_token(s))\n                    goto fail;\n            }\n            if (js_parse_expect_semi(s))\n                goto fail;\n        }\n        break;\n    case TOK_SWITCH:\n        {\n            int label_case, label_break, label1;\n            int default_label_pos;\n            BlockEnv break_entry;\n\n            if (next_token(s))\n                goto fail;\n\n            set_eval_ret_undefined(s);\n            if (js_parse_expr_paren(s))\n                goto fail;\n\n            push_scope(s);\n            label_break = new_label(s);\n            push_break_entry(s->cur_func, &break_entry,\n                             label_name, label_break, -1, 1);\n\n            if (js_parse_expect(s, '{'))\n                goto fail;\n\n            default_label_pos = -1;\n            label_case = -1;\n            while (s->token.val != '}') {\n                if (s->token.val == TOK_CASE) {\n                    label1 = -1;\n                    if (label_case >= 0) {\n                        /* skip the case if needed */\n                        label1 = emit_goto(s, OP_goto, -1);\n                    }\n                    emit_label(s, label_case);\n                    label_case = -1;\n                    for (;;) {\n                        /* parse a sequence of case clauses */\n                        if (next_token(s))\n                            goto fail;\n                        emit_op(s, OP_dup);\n                        if (js_parse_expr(s))\n                            goto fail;\n                        if (js_parse_expect(s, ':'))\n                            goto fail;\n                        emit_op(s, OP_strict_eq);\n                        if (s->token.val == TOK_CASE) {\n                            label1 = emit_goto(s, OP_if_true, label1);\n                        } else {\n                            label_case = emit_goto(s, OP_if_false, -1);\n                            emit_label(s, label1);\n                            break;\n                        }\n                    }\n                } else if (s->token.val == TOK_DEFAULT) {\n                    if (next_token(s))\n                        goto fail;\n                    if (js_parse_expect(s, ':'))\n                        goto fail;\n                    if (default_label_pos >= 0) {\n                        js_parse_error(s, \"duplicate default\");\n                        goto fail;\n                    }\n                    if (label_case < 0) {\n                        /* falling thru direct from switch expression */\n                        label_case = emit_goto(s, OP_goto, -1);\n                    }\n                    /* Emit a dummy label opcode. Label will be patched after\n                       the end of the switch body. Do not use emit_label(s, 0)\n                       because it would clobber label 0 address, preventing\n                       proper optimizer operation.\n                     */\n                    emit_op(s, OP_label);\n                    emit_u32(s, 0);\n                    default_label_pos = s->cur_func->byte_code.size - 4;\n                } else {\n                    if (label_case < 0) {\n                        /* falling thru direct from switch expression */\n                        js_parse_error(s, \"invalid switch statement\");\n                        goto fail;\n                    }\n                    if (js_parse_statement_or_decl(s, DECL_MASK_ALL))\n                        goto fail;\n                }\n            }\n            if (js_parse_expect(s, '}'))\n                goto fail;\n            if (default_label_pos >= 0) {\n                /* Ugly patch for the the `default` label, shameful and risky */\n                put_u32(s->cur_func->byte_code.buf + default_label_pos,\n                        label_case);\n                s->cur_func->label_slots[label_case].pos = default_label_pos + 4;\n            } else {\n                emit_label(s, label_case);\n            }\n            emit_label(s, label_break);\n            emit_op(s, OP_drop); /* drop the switch expression */\n\n            pop_break_entry(s->cur_func);\n            pop_scope(s);\n        }\n        break;\n    case TOK_TRY:\n        {\n            int label_catch, label_catch2, label_finally, label_end;\n            JSAtom name;\n            BlockEnv block_env;\n\n            set_eval_ret_undefined(s);\n            if (next_token(s))\n                goto fail;\n            label_catch = new_label(s);\n            label_catch2 = new_label(s);\n            label_finally = new_label(s);\n            label_end = new_label(s);\n\n            emit_goto(s, OP_catch, label_catch);\n\n            push_break_entry(s->cur_func, &block_env,\n                             JS_ATOM_NULL, -1, -1, 1);\n            block_env.label_finally = label_finally;\n\n            if (js_parse_block(s))\n                goto fail;\n\n            pop_break_entry(s->cur_func);\n\n            if (js_is_live_code(s)) {\n                /* drop the catch offset */\n                emit_op(s, OP_drop);\n                /* must push dummy value to keep same stack size */\n                emit_op(s, OP_undefined);\n                emit_goto(s, OP_gosub, label_finally);\n                emit_op(s, OP_drop);\n\n                emit_goto(s, OP_goto, label_end);\n            }\n\n            if (s->token.val == TOK_CATCH) {\n                if (next_token(s))\n                    goto fail;\n\n                push_scope(s);  /* catch variable */\n                emit_label(s, label_catch);\n\n                if (s->token.val == '{') {\n                    /* support optional-catch-binding feature */\n                    emit_op(s, OP_drop);    /* pop the exception object */\n                } else {\n                    if (js_parse_expect(s, '('))\n                        goto fail;\n                    if (!(s->token.val == TOK_IDENT && !s->token.u.ident.is_reserved)) {\n                        if (s->token.val == '[' || s->token.val == '{') {\n                            /* XXX: TOK_LET is not completely correct */\n                            if (js_parse_destructuring_element(s, TOK_LET, 0, TRUE, -1, TRUE) < 0)\n                                goto fail;\n                        } else {\n                            js_parse_error(s, \"identifier expected\");\n                            goto fail;\n                        }\n                    } else {\n                        name = JS_DupAtom(ctx, s->token.u.ident.atom);\n                        if (next_token(s)\n                        ||  js_define_var(s, name, TOK_CATCH) < 0) {\n                            JS_FreeAtom(ctx, name);\n                            goto fail;\n                        }\n                        /* store the exception value in the catch variable */\n                        emit_op(s, OP_scope_put_var);\n                        emit_u32(s, name);\n                        emit_u16(s, s->cur_func->scope_level);\n                    }\n                    if (js_parse_expect(s, ')'))\n                        goto fail;\n                }\n                /* XXX: should keep the address to nop it out if there is no finally block */\n                emit_goto(s, OP_catch, label_catch2);\n\n                push_scope(s);  /* catch block */\n                push_break_entry(s->cur_func, &block_env, JS_ATOM_NULL,\n                                 -1, -1, 1);\n                block_env.label_finally = label_finally;\n\n                if (js_parse_block(s))\n                    goto fail;\n\n                pop_break_entry(s->cur_func);\n                pop_scope(s);  /* catch block */\n                pop_scope(s);  /* catch variable */\n\n                if (js_is_live_code(s)) {\n                    /* drop the catch2 offset */\n                    emit_op(s, OP_drop);\n                    /* XXX: should keep the address to nop it out if there is no finally block */\n                    /* must push dummy value to keep same stack size */\n                    emit_op(s, OP_undefined);\n                    emit_goto(s, OP_gosub, label_finally);\n                    emit_op(s, OP_drop);\n                    emit_goto(s, OP_goto, label_end);\n                }\n                /* catch exceptions thrown in the catch block to execute the\n                 * finally clause and rethrow the exception */\n                emit_label(s, label_catch2);\n                /* catch value is at TOS, no need to push undefined */\n                emit_goto(s, OP_gosub, label_finally);\n                emit_op(s, OP_throw);\n\n            } else if (s->token.val == TOK_FINALLY) {\n                /* finally without catch : execute the finally clause\n                 * and rethrow the exception */\n                emit_label(s, label_catch);\n                /* catch value is at TOS, no need to push undefined */\n                emit_goto(s, OP_gosub, label_finally);\n                emit_op(s, OP_throw);\n            } else {\n                js_parse_error(s, \"expecting catch or finally\");\n                goto fail;\n            }\n            emit_label(s, label_finally);\n            if (s->token.val == TOK_FINALLY) {\n                int saved_eval_ret_idx = 0; /* avoid warning */\n                \n                if (next_token(s))\n                    goto fail;\n                /* on the stack: ret_value gosub_ret_value */\n                push_break_entry(s->cur_func, &block_env, JS_ATOM_NULL,\n                                 -1, -1, 2);\n\n                if (s->cur_func->eval_ret_idx >= 0) {\n                    /* 'finally' updates eval_ret only if not a normal\n                       termination */\n                    saved_eval_ret_idx =\n                        add_var(s->ctx, s->cur_func, JS_ATOM__ret_);\n                    if (saved_eval_ret_idx < 0)\n                        goto fail;\n                    emit_op(s, OP_get_loc);\n                    emit_u16(s, s->cur_func->eval_ret_idx);\n                    emit_op(s, OP_put_loc);\n                    emit_u16(s, saved_eval_ret_idx);\n                    set_eval_ret_undefined(s);\n                }\n                \n                if (js_parse_block(s))\n                    goto fail;\n\n                if (s->cur_func->eval_ret_idx >= 0) {\n                    emit_op(s, OP_get_loc);\n                    emit_u16(s, saved_eval_ret_idx);\n                    emit_op(s, OP_put_loc);\n                    emit_u16(s, s->cur_func->eval_ret_idx);\n                }\n                pop_break_entry(s->cur_func);\n            }\n            emit_op(s, OP_ret);\n            emit_label(s, label_end);\n        }\n        break;\n    case ';':\n        /* empty statement */\n        if (next_token(s))\n            goto fail;\n        break;\n    case TOK_WITH:\n        if (s->cur_func->js_mode & JS_MODE_STRICT) {\n            js_parse_error(s, \"invalid keyword: with\");\n            goto fail;\n        } else {\n            int with_idx;\n\n            if (next_token(s))\n                goto fail;\n\n            if (js_parse_expr_paren(s))\n                goto fail;\n\n            push_scope(s);\n            with_idx = define_var(s, s->cur_func, JS_ATOM__with_,\n                                  JS_VAR_DEF_WITH);\n            if (with_idx < 0)\n                goto fail;\n            emit_op(s, OP_to_object);\n            emit_op(s, OP_put_loc);\n            emit_u16(s, with_idx);\n\n            set_eval_ret_undefined(s);\n            if (js_parse_statement(s))\n                goto fail;\n\n            /* Popping scope drops lexical context for the with object variable */\n            pop_scope(s);\n        }\n        break;\n    case TOK_FUNCTION:\n        /* ES6 Annex B.3.2 and B.3.3 semantics */\n        if (!(decl_mask & DECL_MASK_FUNC))\n            goto func_decl_error;\n        if (!(decl_mask & DECL_MASK_OTHER) && peek_token(s, FALSE) == '*')\n            goto func_decl_error;\n        goto parse_func_var;\n    case TOK_IDENT:\n        if (s->token.u.ident.is_reserved) {\n            js_parse_error_reserved_identifier(s);\n            goto fail;\n        }\n        /* Determine if `let` introduces a Declaration or an ExpressionStatement */\n        switch (is_let(s, decl_mask)) {\n        case TRUE:\n            tok = TOK_LET;\n            goto haslet;\n        case FALSE:\n            break;\n        default:\n            goto fail;\n        }\n        if (token_is_pseudo_keyword(s, JS_ATOM_async) &&\n            peek_token(s, TRUE) == TOK_FUNCTION) {\n            if (!(decl_mask & DECL_MASK_OTHER)) {\n            func_decl_error:\n                js_parse_error(s, \"function declarations can't appear in single-statement context\");\n                goto fail;\n            }\n        parse_func_var:\n            if (js_parse_function_decl(s, JS_PARSE_FUNC_VAR,\n                                       JS_FUNC_NORMAL, JS_ATOM_NULL,\n                                       s->token.ptr, s->token.line_num))\n                goto fail;\n            break;\n        }\n        goto hasexpr;\n\n    case TOK_CLASS:\n        if (!(decl_mask & DECL_MASK_OTHER)) {\n            js_parse_error(s, \"class declarations can't appear in single-statement context\");\n            goto fail;\n        }\n        if (js_parse_class(s, FALSE, JS_PARSE_EXPORT_NONE))\n            return -1;\n        break;\n\n    case TOK_DEBUGGER:\n        /* currently no debugger, so just skip the keyword */\n        if (next_token(s))\n            goto fail;\n        if (js_parse_expect_semi(s))\n            goto fail;\n        break;\n        \n    case TOK_ENUM:\n    case TOK_EXPORT:\n    case TOK_EXTENDS:\n        js_unsupported_keyword(s, s->token.u.ident.atom);\n        goto fail;\n\n    default:\n    hasexpr:\n        if (js_parse_expr(s))\n            goto fail;\n        if (s->cur_func->eval_ret_idx >= 0) {\n            /* store the expression value so that it can be returned\n               by eval() */\n            emit_op(s, OP_put_loc);\n            emit_u16(s, s->cur_func->eval_ret_idx);\n        } else {\n            emit_op(s, OP_drop); /* drop the result */\n        }\n        if (js_parse_expect_semi(s))\n            goto fail;\n        break;\n    }\ndone:\n    JS_FreeAtom(ctx, label_name);\n    return 0;\nfail:\n    JS_FreeAtom(ctx, label_name);\n    return -1;\n}\n\n/* 'name' is freed */\nstatic JSModuleDef *js_new_module_def(JSContext *ctx, JSAtom name)\n{\n    JSModuleDef *m;\n    m = js_mallocz(ctx, sizeof(*m));\n    if (!m) {\n        JS_FreeAtom(ctx, name);\n        return NULL;\n    }\n    m->header.ref_count = 1;\n    m->module_name = name;\n    m->module_ns = JS_UNDEFINED;\n    m->func_obj = JS_UNDEFINED;\n    m->eval_exception = JS_UNDEFINED;\n    m->meta_obj = JS_UNDEFINED;\n    list_add_tail(&m->link, &ctx->loaded_modules);\n    return m;\n}\n\nstatic void js_mark_module_def(JSRuntime *rt, JSModuleDef *m,\n                               JS_MarkFunc *mark_func)\n{\n    int i;\n\n    for(i = 0; i < m->export_entries_count; i++) {\n        JSExportEntry *me = &m->export_entries[i];\n        if (me->export_type == JS_EXPORT_TYPE_LOCAL &&\n            me->u.local.var_ref) {\n            mark_func(rt, &me->u.local.var_ref->header);\n        }\n    }\n\n    JS_MarkValue(rt, m->module_ns, mark_func);\n    JS_MarkValue(rt, m->func_obj, mark_func);\n    JS_MarkValue(rt, m->eval_exception, mark_func);\n    JS_MarkValue(rt, m->meta_obj, mark_func);\n}\n\nstatic void js_free_module_def(JSContext *ctx, JSModuleDef *m)\n{\n    int i;\n\n    JS_FreeAtom(ctx, m->module_name);\n\n    for(i = 0; i < m->req_module_entries_count; i++) {\n        JSReqModuleEntry *rme = &m->req_module_entries[i];\n        JS_FreeAtom(ctx, rme->module_name);\n    }\n    js_free(ctx, m->req_module_entries);\n\n    for(i = 0; i < m->export_entries_count; i++) {\n        JSExportEntry *me = &m->export_entries[i];\n        if (me->export_type == JS_EXPORT_TYPE_LOCAL)\n            free_var_ref(ctx->rt, me->u.local.var_ref);\n        JS_FreeAtom(ctx, me->export_name);\n        JS_FreeAtom(ctx, me->local_name);\n    }\n    js_free(ctx, m->export_entries);\n\n    js_free(ctx, m->star_export_entries);\n\n    for(i = 0; i < m->import_entries_count; i++) {\n        JSImportEntry *mi = &m->import_entries[i];\n        JS_FreeAtom(ctx, mi->import_name);\n    }\n    js_free(ctx, m->import_entries);\n\n    JS_FreeValue(ctx, m->module_ns);\n    JS_FreeValue(ctx, m->func_obj);\n    JS_FreeValue(ctx, m->eval_exception);\n    JS_FreeValue(ctx, m->meta_obj);\n    list_del(&m->link);\n    js_free(ctx, m);\n}\n\nstatic int add_req_module_entry(JSContext *ctx, JSModuleDef *m,\n                                JSAtom module_name)\n{\n    JSReqModuleEntry *rme;\n    int i;\n\n    /* no need to add the module request if it is already present */\n    for(i = 0; i < m->req_module_entries_count; i++) {\n        rme = &m->req_module_entries[i];\n        if (rme->module_name == module_name)\n            return i;\n    }\n\n    if (js_resize_array(ctx, (void **)&m->req_module_entries,\n                        sizeof(JSReqModuleEntry),\n                        &m->req_module_entries_size,\n                        m->req_module_entries_count + 1))\n        return -1;\n    rme = &m->req_module_entries[m->req_module_entries_count++];\n    rme->module_name = JS_DupAtom(ctx, module_name);\n    rme->module = NULL;\n    return i;\n}\n\nstatic JSExportEntry *find_export_entry(JSContext *ctx, JSModuleDef *m,\n                                        JSAtom export_name)\n{\n    JSExportEntry *me;\n    int i;\n    for(i = 0; i < m->export_entries_count; i++) {\n        me = &m->export_entries[i];\n        if (me->export_name == export_name)\n            return me;\n    }\n    return NULL;\n}\n\nstatic JSExportEntry *add_export_entry2(JSContext *ctx,\n                                        JSParseState *s, JSModuleDef *m,\n                                       JSAtom local_name, JSAtom export_name,\n                                       JSExportTypeEnum export_type)\n{\n    JSExportEntry *me;\n\n    if (find_export_entry(ctx, m, export_name)) {\n        char buf1[ATOM_GET_STR_BUF_SIZE];\n        if (s) {\n            js_parse_error(s, \"duplicate exported name '%s'\",\n                           JS_AtomGetStr(ctx, buf1, sizeof(buf1), export_name));\n        } else {\n            JS_ThrowSyntaxErrorAtom(ctx, \"duplicate exported name '%s'\", export_name);\n        }\n        return NULL;\n    }\n\n    if (js_resize_array(ctx, (void **)&m->export_entries,\n                        sizeof(JSExportEntry),\n                        &m->export_entries_size,\n                        m->export_entries_count + 1))\n        return NULL;\n    me = &m->export_entries[m->export_entries_count++];\n    memset(me, 0, sizeof(*me));\n    me->local_name = JS_DupAtom(ctx, local_name);\n    me->export_name = JS_DupAtom(ctx, export_name);\n    me->export_type = export_type;\n    return me;\n}\n\nstatic JSExportEntry *add_export_entry(JSParseState *s, JSModuleDef *m,\n                                       JSAtom local_name, JSAtom export_name,\n                                       JSExportTypeEnum export_type)\n{\n    return add_export_entry2(s->ctx, s, m, local_name, export_name,\n                             export_type);\n}\n\nstatic int add_star_export_entry(JSContext *ctx, JSModuleDef *m,\n                                 int req_module_idx)\n{\n    JSStarExportEntry *se;\n\n    if (js_resize_array(ctx, (void **)&m->star_export_entries,\n                        sizeof(JSStarExportEntry),\n                        &m->star_export_entries_size,\n                        m->star_export_entries_count + 1))\n        return -1;\n    se = &m->star_export_entries[m->star_export_entries_count++];\n    se->req_module_idx = req_module_idx;\n    return 0;\n}\n\n/* create a C module */\nJSModuleDef *JS_NewCModule(JSContext *ctx, const char *name_str,\n                           JSModuleInitFunc *func)\n{\n    JSModuleDef *m;\n    JSAtom name;\n    name = JS_NewAtom(ctx, name_str);\n    if (name == JS_ATOM_NULL)\n        return NULL;\n    m = js_new_module_def(ctx, name);\n    m->init_func = func;\n    return m;\n}\n\nint JS_AddModuleExport(JSContext *ctx, JSModuleDef *m, const char *export_name)\n{\n    JSExportEntry *me;\n    JSAtom name;\n    name = JS_NewAtom(ctx, export_name);\n    if (name == JS_ATOM_NULL)\n        return -1;\n    me = add_export_entry2(ctx, NULL, m, JS_ATOM_NULL, name,\n                           JS_EXPORT_TYPE_LOCAL);\n    JS_FreeAtom(ctx, name);\n    if (!me)\n        return -1;\n    else\n        return 0;\n}\n\nint JS_SetModuleExport(JSContext *ctx, JSModuleDef *m, const char *export_name,\n                       JSValue val)\n{\n    JSExportEntry *me;\n    JSAtom name;\n    name = JS_NewAtom(ctx, export_name);\n    if (name == JS_ATOM_NULL)\n        goto fail;\n    me = find_export_entry(ctx, m, name);\n    JS_FreeAtom(ctx, name);\n    if (!me)\n        goto fail;\n    set_value(ctx, me->u.local.var_ref->pvalue, val);\n    return 0;\n fail:\n    JS_FreeValue(ctx, val);\n    return -1;\n}\n\nvoid JS_SetModuleLoaderFunc(JSRuntime *rt,\n                            JSModuleNormalizeFunc *module_normalize,\n                            JSModuleLoaderFunc *module_loader, void *opaque)\n{\n    rt->module_normalize_func = module_normalize;\n    rt->module_loader_func = module_loader;\n    rt->module_loader_opaque = opaque;\n}\n\n/* default module filename normalizer */\nstatic char *js_default_module_normalize_name(JSContext *ctx,\n                                              const char *base_name,\n                                              const char *name)\n{\n    char *filename, *p;\n    const char *r;\n    int len;\n\n    if (name[0] != '.') {\n        /* if no initial dot, the module name is not modified */\n        return js_strdup(ctx, name);\n    }\n\n    p = strrchr(base_name, '/');\n    if (p)\n        len = p - base_name;\n    else\n        len = 0;\n\n    filename = js_malloc(ctx, len + strlen(name) + 1 + 1);\n    if (!filename)\n        return NULL;\n    memcpy(filename, base_name, len);\n    filename[len] = '\\0';\n\n    /* we only normalize the leading '..' or '.' */\n    r = name;\n    for(;;) {\n        if (r[0] == '.' && r[1] == '/') {\n            r += 2;\n        } else if (r[0] == '.' && r[1] == '.' && r[2] == '/') {\n            /* remove the last path element of filename, except if \".\"\n               or \"..\" */\n            if (filename[0] == '\\0')\n                break;\n            p = strrchr(filename, '/');\n            if (!p)\n                p = filename;\n            else\n                p++;\n            if (!strcmp(p, \".\") || !strcmp(p, \"..\"))\n                break;\n            if (p > filename)\n                p--;\n            *p = '\\0';\n            r += 3;\n        } else {\n            break;\n        }\n    }\n    if (filename[0] != '\\0')\n        strcat(filename, \"/\");\n    strcat(filename, r);\n    //    printf(\"normalize: %s %s -> %s\\n\", base_name, name, filename);\n    return filename;\n}\n\nstatic JSModuleDef *js_find_loaded_module(JSContext *ctx, JSAtom name)\n{\n    struct list_head *el;\n    JSModuleDef *m;\n    \n    /* first look at the loaded modules */\n    list_for_each(el, &ctx->loaded_modules) {\n        m = list_entry(el, JSModuleDef, link);\n        if (m->module_name == name)\n            return m;\n    }\n    return NULL;\n}\n\n/* return NULL in case of exception (e.g. module could not be loaded) */\nstatic JSModuleDef *js_host_resolve_imported_module(JSContext *ctx,\n                                                    const char *base_cname,\n                                                    const char *cname1)\n{\n    JSRuntime *rt = ctx->rt;\n    JSModuleDef *m;\n    char *cname;\n    JSAtom module_name;\n\n    if (!rt->module_normalize_func) {\n        cname = js_default_module_normalize_name(ctx, base_cname, cname1);\n    } else {\n        cname = rt->module_normalize_func(ctx, base_cname, cname1,\n                                          rt->module_loader_opaque);\n    }\n    if (!cname)\n        return NULL;\n\n    module_name = JS_NewAtom(ctx, cname);\n    if (module_name == JS_ATOM_NULL) {\n        js_free(ctx, cname);\n        return NULL;\n    }\n\n    /* first look at the loaded modules */\n    m = js_find_loaded_module(ctx, module_name);\n    if (m) {\n        js_free(ctx, cname);\n        JS_FreeAtom(ctx, module_name);\n        return m;\n    }\n\n    JS_FreeAtom(ctx, module_name);\n\n    /* load the module */\n    if (!rt->module_loader_func) {\n        /* XXX: use a syntax error ? */\n        JS_ThrowReferenceError(ctx, \"could not load module '%s'\",\n                               cname);\n        js_free(ctx, cname);\n        return NULL;\n    }\n\n    m = rt->module_loader_func(ctx, cname, rt->module_loader_opaque);\n    js_free(ctx, cname);\n    return m;\n}\n\nstatic JSModuleDef *js_host_resolve_imported_module_atom(JSContext *ctx,\n                                                    JSAtom base_module_name,\n                                                    JSAtom module_name1)\n{\n    const char *base_cname, *cname;\n    JSModuleDef *m;\n    \n    base_cname = JS_AtomToCString(ctx, base_module_name);\n    if (!base_cname)\n        return NULL;\n    cname = JS_AtomToCString(ctx, module_name1);\n    if (!cname) {\n        JS_FreeCString(ctx, base_cname);\n        return NULL;\n    }\n    m = js_host_resolve_imported_module(ctx, base_cname, cname);\n    JS_FreeCString(ctx, base_cname);\n    JS_FreeCString(ctx, cname);\n    return m;\n}\n\ntypedef struct JSResolveEntry {\n    JSModuleDef *module;\n    JSAtom name;\n} JSResolveEntry;\n\ntypedef struct JSResolveState {\n    JSResolveEntry *array;\n    int size;\n    int count;\n} JSResolveState;\n\nstatic int find_resolve_entry(JSResolveState *s,\n                              JSModuleDef *m, JSAtom name)\n{\n    int i;\n    for(i = 0; i < s->count; i++) {\n        JSResolveEntry *re = &s->array[i];\n        if (re->module == m && re->name == name)\n            return i;\n    }\n    return -1;\n}\n\nstatic int add_resolve_entry(JSContext *ctx, JSResolveState *s,\n                             JSModuleDef *m, JSAtom name)\n{\n    JSResolveEntry *re;\n\n    if (js_resize_array(ctx, (void **)&s->array,\n                        sizeof(JSResolveEntry),\n                        &s->size, s->count + 1))\n        return -1;\n    re = &s->array[s->count++];\n    re->module = m;\n    re->name = JS_DupAtom(ctx, name);\n    return 0;\n}\n\ntypedef enum JSResolveResultEnum {\n    JS_RESOLVE_RES_EXCEPTION = -1, /* memory alloc error */\n    JS_RESOLVE_RES_FOUND = 0,\n    JS_RESOLVE_RES_NOT_FOUND,\n    JS_RESOLVE_RES_CIRCULAR,\n    JS_RESOLVE_RES_AMBIGUOUS,\n} JSResolveResultEnum;\n\nstatic JSResolveResultEnum js_resolve_export1(JSContext *ctx,\n                                              JSModuleDef **pmodule,\n                                              JSExportEntry **pme,\n                                              JSModuleDef *m,\n                                              JSAtom export_name,\n                                              JSResolveState *s)\n{\n    JSExportEntry *me;\n\n    *pmodule = NULL;\n    *pme = NULL;\n    if (find_resolve_entry(s, m, export_name) >= 0)\n        return JS_RESOLVE_RES_CIRCULAR;\n    if (add_resolve_entry(ctx, s, m, export_name) < 0)\n        return JS_RESOLVE_RES_EXCEPTION;\n    me = find_export_entry(ctx, m, export_name);\n    if (me) {\n        if (me->export_type == JS_EXPORT_TYPE_LOCAL) {\n            /* local export */\n            *pmodule = m;\n            *pme = me;\n            return JS_RESOLVE_RES_FOUND;\n        } else {\n            /* indirect export */\n            JSModuleDef *m1;\n            m1 = m->req_module_entries[me->u.req_module_idx].module;\n            if (me->local_name == JS_ATOM__star_) {\n                /* export ns from */\n                *pmodule = m;\n                *pme = me;\n                return JS_RESOLVE_RES_FOUND;\n            } else {\n                return js_resolve_export1(ctx, pmodule, pme, m1,\n                                          me->local_name, s);\n            }\n        }\n    } else {\n        if (export_name != JS_ATOM_default) {\n            /* not found in direct or indirect exports: try star exports */\n            int i;\n\n            for(i = 0; i < m->star_export_entries_count; i++) {\n                JSStarExportEntry *se = &m->star_export_entries[i];\n                JSModuleDef *m1, *res_m;\n                JSExportEntry *res_me;\n                JSResolveResultEnum ret;\n\n                m1 = m->req_module_entries[se->req_module_idx].module;\n                ret = js_resolve_export1(ctx, &res_m, &res_me, m1,\n                                         export_name, s);\n                if (ret == JS_RESOLVE_RES_AMBIGUOUS ||\n                    ret == JS_RESOLVE_RES_EXCEPTION) {\n                    return ret;\n                } else if (ret == JS_RESOLVE_RES_FOUND) {\n                    if (*pme != NULL) {\n                        if (*pmodule != res_m ||\n                            res_me->local_name != (*pme)->local_name) {\n                            *pmodule = NULL;\n                            *pme = NULL;\n                            return JS_RESOLVE_RES_AMBIGUOUS;\n                        }\n                    } else {\n                        *pmodule = res_m;\n                        *pme = res_me;\n                    }\n                }\n            }\n            if (*pme != NULL)\n                return JS_RESOLVE_RES_FOUND;\n        }\n        return JS_RESOLVE_RES_NOT_FOUND;\n    }\n}\n\n/* If the return value is JS_RESOLVE_RES_FOUND, return the module\n  (*pmodule) and the corresponding local export entry\n  (*pme). Otherwise return (NULL, NULL) */\nstatic JSResolveResultEnum js_resolve_export(JSContext *ctx,\n                                             JSModuleDef **pmodule,\n                                             JSExportEntry **pme,\n                                             JSModuleDef *m,\n                                             JSAtom export_name)\n{\n    JSResolveState ss, *s = &ss;\n    int i;\n    JSResolveResultEnum ret;\n\n    s->array = NULL;\n    s->size = 0;\n    s->count = 0;\n\n    ret = js_resolve_export1(ctx, pmodule, pme, m, export_name, s);\n\n    for(i = 0; i < s->count; i++)\n        JS_FreeAtom(ctx, s->array[i].name);\n    js_free(ctx, s->array);\n\n    return ret;\n}\n\nstatic void js_resolve_export_throw_error(JSContext *ctx,\n                                          JSResolveResultEnum res,\n                                          JSModuleDef *m, JSAtom export_name)\n{\n    char buf1[ATOM_GET_STR_BUF_SIZE];\n    char buf2[ATOM_GET_STR_BUF_SIZE];\n    switch(res) {\n    case JS_RESOLVE_RES_EXCEPTION:\n        break;\n    default:\n    case JS_RESOLVE_RES_NOT_FOUND:\n        JS_ThrowSyntaxError(ctx, \"Could not find export '%s' in module '%s'\",\n                            JS_AtomGetStr(ctx, buf1, sizeof(buf1), export_name),\n                            JS_AtomGetStr(ctx, buf2, sizeof(buf2), m->module_name));\n        break;\n    case JS_RESOLVE_RES_CIRCULAR:\n        JS_ThrowSyntaxError(ctx, \"circular reference when looking for export '%s' in module '%s'\",\n                            JS_AtomGetStr(ctx, buf1, sizeof(buf1), export_name),\n                            JS_AtomGetStr(ctx, buf2, sizeof(buf2), m->module_name));\n        break;\n    case JS_RESOLVE_RES_AMBIGUOUS:\n        JS_ThrowSyntaxError(ctx, \"export '%s' in module '%s' is ambiguous\",\n                            JS_AtomGetStr(ctx, buf1, sizeof(buf1), export_name),\n                            JS_AtomGetStr(ctx, buf2, sizeof(buf2), m->module_name));\n        break;\n    }\n}\n\n\ntypedef enum {\n    EXPORTED_NAME_AMBIGUOUS,\n    EXPORTED_NAME_NORMAL,\n    EXPORTED_NAME_NS,\n} ExportedNameEntryEnum;\n\ntypedef struct ExportedNameEntry {\n    JSAtom export_name;\n    ExportedNameEntryEnum export_type;\n    union {\n        JSExportEntry *me; /* using when the list is built */\n        JSVarRef *var_ref; /* EXPORTED_NAME_NORMAL */\n        JSModuleDef *module; /* for EXPORTED_NAME_NS */\n    } u;\n} ExportedNameEntry;\n\ntypedef struct GetExportNamesState {\n    JSModuleDef **modules;\n    int modules_size;\n    int modules_count;\n\n    ExportedNameEntry *exported_names;\n    int exported_names_size;\n    int exported_names_count;\n} GetExportNamesState;\n\nstatic int find_exported_name(GetExportNamesState *s, JSAtom name)\n{\n    int i;\n    for(i = 0; i < s->exported_names_count; i++) {\n        if (s->exported_names[i].export_name == name)\n            return i;\n    }\n    return -1;\n}\n\nstatic __exception int get_exported_names(JSContext *ctx,\n                                          GetExportNamesState *s,\n                                          JSModuleDef *m, BOOL from_star)\n{\n    ExportedNameEntry *en;\n    int i, j;\n\n    /* check circular reference */\n    for(i = 0; i < s->modules_count; i++) {\n        if (s->modules[i] == m)\n            return 0;\n    }\n    if (js_resize_array(ctx, (void **)&s->modules, sizeof(s->modules[0]),\n                        &s->modules_size, s->modules_count + 1))\n        return -1;\n    s->modules[s->modules_count++] = m;\n\n    for(i = 0; i < m->export_entries_count; i++) {\n        JSExportEntry *me = &m->export_entries[i];\n        if (from_star && me->export_name == JS_ATOM_default)\n            continue;\n        j = find_exported_name(s, me->export_name);\n        if (j < 0) {\n            if (js_resize_array(ctx, (void **)&s->exported_names, sizeof(s->exported_names[0]),\n                                &s->exported_names_size,\n                                s->exported_names_count + 1))\n                return -1;\n            en = &s->exported_names[s->exported_names_count++];\n            en->export_name = me->export_name;\n            /* avoid a second lookup for simple module exports */\n            if (from_star || me->export_type != JS_EXPORT_TYPE_LOCAL)\n                en->u.me = NULL;\n            else\n                en->u.me = me;\n        } else {\n            en = &s->exported_names[j];\n            en->u.me = NULL;\n        }\n    }\n    for(i = 0; i < m->star_export_entries_count; i++) {\n        JSStarExportEntry *se = &m->star_export_entries[i];\n        JSModuleDef *m1;\n        m1 = m->req_module_entries[se->req_module_idx].module;\n        if (get_exported_names(ctx, s, m1, TRUE))\n            return -1;\n    }\n    return 0;\n}\n\n/* Unfortunately, the spec gives a different behavior from GetOwnProperty ! */\nstatic int js_module_ns_has(JSContext *ctx, JSValueConst obj, JSAtom atom)\n{\n    return (find_own_property1(JS_VALUE_GET_OBJ(obj), atom) != NULL);\n}\n\nstatic const JSClassExoticMethods js_module_ns_exotic_methods = {\n    .has_property = js_module_ns_has,\n};\n\nstatic int exported_names_cmp(const void *p1, const void *p2, void *opaque)\n{\n    JSContext *ctx = opaque;\n    const ExportedNameEntry *me1 = p1;\n    const ExportedNameEntry *me2 = p2;\n    JSValue str1, str2;\n    int ret;\n\n    /* XXX: should avoid allocation memory in atom comparison */\n    str1 = JS_AtomToString(ctx, me1->export_name);\n    str2 = JS_AtomToString(ctx, me2->export_name);\n    if (JS_IsException(str1) || JS_IsException(str2)) {\n        /* XXX: raise an error ? */\n        ret = 0;\n    } else {\n        ret = js_string_compare(ctx, JS_VALUE_GET_STRING(str1),\n                                JS_VALUE_GET_STRING(str2));\n    }\n    JS_FreeValue(ctx, str1);\n    JS_FreeValue(ctx, str2);\n    return ret;\n}\n\nstatic JSValue js_get_module_ns(JSContext *ctx, JSModuleDef *m);\n\nstatic JSValue js_module_ns_autoinit(JSContext *ctx, JSObject *p, JSAtom atom,\n                                     void *opaque)\n{\n    JSModuleDef *m = opaque;\n    return js_get_module_ns(ctx, m);\n}\n\nstatic JSValue js_build_module_ns(JSContext *ctx, JSModuleDef *m)\n{\n    JSValue obj;\n    JSObject *p;\n    GetExportNamesState s_s, *s = &s_s;\n    int i, ret;\n    JSProperty *pr;\n\n    obj = JS_NewObjectClass(ctx, JS_CLASS_MODULE_NS);\n    if (JS_IsException(obj))\n        return obj;\n    p = JS_VALUE_GET_OBJ(obj);\n\n    memset(s, 0, sizeof(*s));\n    ret = get_exported_names(ctx, s, m, FALSE);\n    js_free(ctx, s->modules);\n    if (ret)\n        goto fail;\n\n    /* Resolve the exported names. The ambiguous exports are removed */\n    for(i = 0; i < s->exported_names_count; i++) {\n        ExportedNameEntry *en = &s->exported_names[i];\n        JSResolveResultEnum res;\n        JSExportEntry *res_me;\n        JSModuleDef *res_m;\n\n        if (en->u.me) {\n            res_me = en->u.me; /* fast case: no resolution needed */\n            res_m = m;\n            res = JS_RESOLVE_RES_FOUND;\n        } else {\n            res = js_resolve_export(ctx, &res_m, &res_me, m,\n                                    en->export_name);\n        }\n        if (res != JS_RESOLVE_RES_FOUND) {\n            if (res != JS_RESOLVE_RES_AMBIGUOUS) {\n                js_resolve_export_throw_error(ctx, res, m, en->export_name);\n                goto fail;\n            }\n            en->export_type = EXPORTED_NAME_AMBIGUOUS;\n        } else {\n            if (res_me->local_name == JS_ATOM__star_) {\n                en->export_type = EXPORTED_NAME_NS;\n                en->u.module = res_m->req_module_entries[res_me->u.req_module_idx].module;\n            } else {\n                en->export_type = EXPORTED_NAME_NORMAL;\n                if (res_me->u.local.var_ref) {\n                    en->u.var_ref = res_me->u.local.var_ref;\n                } else {\n                    JSObject *p1 = JS_VALUE_GET_OBJ(res_m->func_obj);\n                    p1 = JS_VALUE_GET_OBJ(res_m->func_obj);\n                    en->u.var_ref = p1->u.func.var_refs[res_me->u.local.var_idx];\n                }\n            }\n        }\n    }\n\n    /* sort the exported names */\n    rqsort(s->exported_names, s->exported_names_count,\n           sizeof(s->exported_names[0]), exported_names_cmp, ctx);\n\n    for(i = 0; i < s->exported_names_count; i++) {\n        ExportedNameEntry *en = &s->exported_names[i];\n        switch(en->export_type) {\n        case EXPORTED_NAME_NORMAL:\n            {\n                JSVarRef *var_ref = en->u.var_ref;\n                pr = add_property(ctx, p, en->export_name,\n                                  JS_PROP_ENUMERABLE | JS_PROP_WRITABLE |\n                                  JS_PROP_VARREF);\n                if (!pr)\n                    goto fail;\n                var_ref->header.ref_count++;\n                pr->u.var_ref = var_ref;\n            }\n            break;\n        case EXPORTED_NAME_NS:\n            /* the exported namespace must be created on demand */\n            if (JS_DefineAutoInitProperty(ctx, obj,\n                                          en->export_name,\n                                          JS_AUTOINIT_ID_MODULE_NS,\n                                          en->u.module, JS_PROP_ENUMERABLE | JS_PROP_WRITABLE) < 0)\n                goto fail;\n            break;\n        default:\n            break;\n        }\n    }\n\n    js_free(ctx, s->exported_names);\n\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_Symbol_toStringTag,\n                           JS_AtomToString(ctx, JS_ATOM_Module),\n                           0);\n\n    p->extensible = FALSE;\n    return obj;\n fail:\n    js_free(ctx, s->exported_names);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_get_module_ns(JSContext *ctx, JSModuleDef *m)\n{\n    if (JS_IsUndefined(m->module_ns)) {\n        JSValue val;\n        val = js_build_module_ns(ctx, m);\n        if (JS_IsException(val))\n            return JS_EXCEPTION;\n        m->module_ns = val;\n    }\n    return JS_DupValue(ctx, m->module_ns);\n}\n\n/* Load all the required modules for module 'm' */\nstatic int js_resolve_module(JSContext *ctx, JSModuleDef *m)\n{\n    int i;\n    JSModuleDef *m1;\n\n    if (m->resolved)\n        return 0;\n#ifdef DUMP_MODULE_RESOLVE\n    {\n        char buf1[ATOM_GET_STR_BUF_SIZE];\n        printf(\"resolving module '%s':\\n\", JS_AtomGetStr(ctx, buf1, sizeof(buf1), m->module_name));\n    }\n#endif\n    m->resolved = TRUE;\n    /* resolve each requested module */\n    for(i = 0; i < m->req_module_entries_count; i++) {\n        JSReqModuleEntry *rme = &m->req_module_entries[i];\n        m1 = js_host_resolve_imported_module_atom(ctx, m->module_name,\n                                                  rme->module_name);\n        if (!m1)\n            return -1;\n        rme->module = m1;\n        /* already done in js_host_resolve_imported_module() except if\n           the module was loaded with JS_EvalBinary() */\n        if (js_resolve_module(ctx, m1) < 0)\n            return -1;\n    }\n    return 0;\n}\n\nstatic JSVarRef *js_create_module_var(JSContext *ctx, BOOL is_lexical)\n{\n    JSVarRef *var_ref;\n    var_ref = js_malloc(ctx, sizeof(JSVarRef));\n    if (!var_ref)\n        return NULL;\n    var_ref->header.ref_count = 1;\n    if (is_lexical)\n        var_ref->value = JS_UNINITIALIZED;\n    else\n        var_ref->value = JS_UNDEFINED;\n    var_ref->pvalue = &var_ref->value;\n    var_ref->is_detached = TRUE;\n    add_gc_object(ctx->rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF);\n    return var_ref;\n}\n\n/* Create the <eval> function associated with the module */\nstatic int js_create_module_bytecode_function(JSContext *ctx, JSModuleDef *m)\n{\n    JSFunctionBytecode *b;\n    int i;\n    JSVarRef **var_refs;\n    JSValue func_obj, bfunc;\n    JSObject *p;\n\n    bfunc = m->func_obj;\n    func_obj = JS_NewObjectProtoClass(ctx, ctx->function_proto,\n                                      JS_CLASS_BYTECODE_FUNCTION);\n\n    if (JS_IsException(func_obj))\n        return -1;\n    b = JS_VALUE_GET_PTR(bfunc);\n\n    p = JS_VALUE_GET_OBJ(func_obj);\n    p->u.func.function_bytecode = b;\n    b->header.ref_count++;\n    p->u.func.home_object = NULL;\n    p->u.func.var_refs = NULL;\n    if (b->closure_var_count) {\n        var_refs = js_mallocz(ctx, sizeof(var_refs[0]) * b->closure_var_count);\n        if (!var_refs)\n            goto fail;\n        p->u.func.var_refs = var_refs;\n\n        /* create the global variables. The other variables are\n           imported from other modules */\n        for(i = 0; i < b->closure_var_count; i++) {\n            JSClosureVar *cv = &b->closure_var[i];\n            JSVarRef *var_ref;\n            if (cv->is_local) {\n                var_ref = js_create_module_var(ctx, cv->is_lexical);\n                if (!var_ref)\n                    goto fail;\n#ifdef DUMP_MODULE_RESOLVE\n                printf(\"local %d: %p\\n\", i, var_ref);\n#endif\n                var_refs[i] = var_ref;\n            }\n        }\n    }\n    m->func_obj = func_obj;\n    JS_FreeValue(ctx, bfunc);\n    return 0;\n fail:\n    JS_FreeValue(ctx, func_obj);\n    return -1;\n}\n\n/* must be done before js_link_module() because of cyclic references */\nstatic int js_create_module_function(JSContext *ctx, JSModuleDef *m)\n{\n    BOOL is_c_module;\n    int i;\n    JSVarRef *var_ref;\n    \n    if (m->func_created)\n        return 0;\n\n    is_c_module = (m->init_func != NULL);\n\n    if (is_c_module) {\n        /* initialize the exported variables */\n        for(i = 0; i < m->export_entries_count; i++) {\n            JSExportEntry *me = &m->export_entries[i];\n            if (me->export_type == JS_EXPORT_TYPE_LOCAL) {\n                var_ref = js_create_module_var(ctx, FALSE);\n                if (!var_ref)\n                    return -1;\n                me->u.local.var_ref = var_ref;\n            }\n        }\n    } else {\n        if (js_create_module_bytecode_function(ctx, m))\n            return -1;\n    }\n    m->func_created = TRUE;\n\n    /* do it on the dependencies */\n    \n    for(i = 0; i < m->req_module_entries_count; i++) {\n        JSReqModuleEntry *rme = &m->req_module_entries[i];\n        if (js_create_module_function(ctx, rme->module) < 0)\n            return -1;\n    }\n\n    return 0;\n}    \n\n    \n/* Prepare a module to be executed by resolving all the imported\n   variables. */\nstatic int js_link_module(JSContext *ctx, JSModuleDef *m)\n{\n    int i;\n    JSImportEntry *mi;\n    JSModuleDef *m1;\n    JSVarRef **var_refs, *var_ref;\n    JSObject *p;\n    BOOL is_c_module;\n    JSValue ret_val;\n    \n    if (m->instantiated)\n        return 0;\n    m->instantiated = TRUE;\n\n#ifdef DUMP_MODULE_RESOLVE\n    {\n        char buf1[ATOM_GET_STR_BUF_SIZE];\n        printf(\"start instantiating module '%s':\\n\", JS_AtomGetStr(ctx, buf1, sizeof(buf1), m->module_name));\n    }\n#endif\n\n    for(i = 0; i < m->req_module_entries_count; i++) {\n        JSReqModuleEntry *rme = &m->req_module_entries[i];\n        if (js_link_module(ctx, rme->module) < 0)\n            goto fail;\n    }\n\n#ifdef DUMP_MODULE_RESOLVE\n    {\n        char buf1[ATOM_GET_STR_BUF_SIZE];\n        printf(\"instantiating module '%s':\\n\", JS_AtomGetStr(ctx, buf1, sizeof(buf1), m->module_name));\n    }\n#endif\n    /* check the indirect exports */\n    for(i = 0; i < m->export_entries_count; i++) {\n        JSExportEntry *me = &m->export_entries[i];\n        if (me->export_type == JS_EXPORT_TYPE_INDIRECT &&\n            me->local_name != JS_ATOM__star_) {\n            JSResolveResultEnum ret;\n            JSExportEntry *res_me;\n            JSModuleDef *res_m, *m1;\n            m1 = m->req_module_entries[me->u.req_module_idx].module;\n            ret = js_resolve_export(ctx, &res_m, &res_me, m1, me->local_name);\n            if (ret != JS_RESOLVE_RES_FOUND) {\n                js_resolve_export_throw_error(ctx, ret, m, me->export_name);\n                goto fail;\n            }\n        }\n    }\n\n#ifdef DUMP_MODULE_RESOLVE\n    {\n        printf(\"exported bindings:\\n\");\n        for(i = 0; i < m->export_entries_count; i++) {\n            JSExportEntry *me = &m->export_entries[i];\n            printf(\" name=\"); print_atom(ctx, me->export_name);\n            printf(\" local=\"); print_atom(ctx, me->local_name);\n            printf(\" type=%d idx=%d\\n\", me->export_type, me->u.local.var_idx);\n        }\n    }\n#endif\n\n    is_c_module = (m->init_func != NULL);\n\n    if (!is_c_module) {\n        p = JS_VALUE_GET_OBJ(m->func_obj);\n        var_refs = p->u.func.var_refs;\n\n        for(i = 0; i < m->import_entries_count; i++) {\n            mi = &m->import_entries[i];\n#ifdef DUMP_MODULE_RESOLVE\n            printf(\"import var_idx=%d name=\", mi->var_idx);\n            print_atom(ctx, mi->import_name);\n            printf(\": \");\n#endif\n            m1 = m->req_module_entries[mi->req_module_idx].module;\n            if (mi->import_name == JS_ATOM__star_) {\n                JSValue val;\n                /* name space import */\n                val = js_get_module_ns(ctx, m1);\n                if (JS_IsException(val))\n                    goto fail;\n                set_value(ctx, &var_refs[mi->var_idx]->value, val);\n#ifdef DUMP_MODULE_RESOLVE\n                printf(\"namespace\\n\");\n#endif\n            } else {\n                JSResolveResultEnum ret;\n                JSExportEntry *res_me;\n                JSModuleDef *res_m;\n                JSObject *p1;\n\n                ret = js_resolve_export(ctx, &res_m,\n                                        &res_me, m1, mi->import_name);\n                if (ret != JS_RESOLVE_RES_FOUND) {\n                    js_resolve_export_throw_error(ctx, ret, m1, mi->import_name);\n                    goto fail;\n                }\n                if (res_me->local_name == JS_ATOM__star_) {\n                    JSValue val;\n                    JSModuleDef *m2;\n                    /* name space import from */\n                    m2 = res_m->req_module_entries[res_me->u.req_module_idx].module;\n                    val = js_get_module_ns(ctx, m2);\n                    if (JS_IsException(val))\n                        goto fail;\n                    var_ref = js_create_module_var(ctx, TRUE);\n                    if (!var_ref) {\n                        JS_FreeValue(ctx, val);\n                        goto fail;\n                    }\n                    set_value(ctx, &var_ref->value, val);\n                    var_refs[mi->var_idx] = var_ref;\n#ifdef DUMP_MODULE_RESOLVE\n                    printf(\"namespace from\\n\");\n#endif\n                } else {\n                    var_ref = res_me->u.local.var_ref;\n                    if (!var_ref) {\n                        p1 = JS_VALUE_GET_OBJ(res_m->func_obj);\n                        var_ref = p1->u.func.var_refs[res_me->u.local.var_idx];\n                    }\n                    var_ref->header.ref_count++;\n                    var_refs[mi->var_idx] = var_ref;\n#ifdef DUMP_MODULE_RESOLVE\n                    printf(\"local export (var_ref=%p)\\n\", var_ref);\n#endif\n                }\n            }\n        }\n\n        /* keep the exported variables in the module export entries (they\n           are used when the eval function is deleted and cannot be\n           initialized before in case imports are exported) */\n        for(i = 0; i < m->export_entries_count; i++) {\n            JSExportEntry *me = &m->export_entries[i];\n            if (me->export_type == JS_EXPORT_TYPE_LOCAL) {\n                var_ref = var_refs[me->u.local.var_idx];\n                var_ref->header.ref_count++;\n                me->u.local.var_ref = var_ref;\n            }\n        }\n\n        /* initialize the global variables */\n        ret_val = JS_Call(ctx, m->func_obj, JS_TRUE, 0, NULL);\n        if (JS_IsException(ret_val))\n            goto fail;\n        JS_FreeValue(ctx, ret_val);\n    }\n\n#ifdef DUMP_MODULE_RESOLVE\n    printf(\"done instantiate\\n\");\n#endif\n    return 0;\n fail:\n    return -1;\n}\n\n/* return JS_ATOM_NULL if the name cannot be found. Only works with\n   not striped bytecode functions. */\nJSAtom JS_GetScriptOrModuleName(JSContext *ctx, int n_stack_levels)\n{\n    JSStackFrame *sf;\n    JSFunctionBytecode *b;\n    JSObject *p;\n    /* XXX: currently we just use the filename of the englobing\n       function. It does not work for eval(). Need to add a\n       ScriptOrModule info in JSFunctionBytecode */\n    sf = ctx->rt->current_stack_frame;\n    if (!sf)\n        return JS_ATOM_NULL;\n    while (n_stack_levels-- > 0) {\n        sf = sf->prev_frame;\n        if (!sf)\n            return JS_ATOM_NULL;\n    }\n    if (JS_VALUE_GET_TAG(sf->cur_func) != JS_TAG_OBJECT)\n        return JS_ATOM_NULL;\n    p = JS_VALUE_GET_OBJ(sf->cur_func);\n    if (!js_class_has_bytecode(p->class_id))\n        return JS_ATOM_NULL;\n    b = p->u.func.function_bytecode;\n    if (!b->has_debug)\n        return JS_ATOM_NULL;\n    return JS_DupAtom(ctx, b->debug.filename);\n}\n\nJSAtom JS_GetModuleName(JSContext *ctx, JSModuleDef *m)\n{\n    return JS_DupAtom(ctx, m->module_name);\n}\n\nJSValue JS_GetImportMeta(JSContext *ctx, JSModuleDef *m)\n{\n    JSValue obj;\n    /* allocate meta_obj only if requested to save memory */\n    obj = m->meta_obj;\n    if (JS_IsUndefined(obj)) {\n        obj = JS_NewObjectProto(ctx, JS_NULL);\n        if (JS_IsException(obj))\n            return JS_EXCEPTION;\n        m->meta_obj = obj;\n    }\n    return JS_DupValue(ctx, obj);\n}\n\nstatic JSValue js_import_meta(JSContext *ctx)\n{\n    JSAtom filename;\n    JSModuleDef *m;\n    \n    filename = JS_GetScriptOrModuleName(ctx, 0);\n    if (filename == JS_ATOM_NULL)\n        goto fail;\n\n    /* XXX: inefficient, need to add a module or script pointer in\n       JSFunctionBytecode */\n    m = js_find_loaded_module(ctx, filename);\n    JS_FreeAtom(ctx, filename);\n    if (!m) {\n    fail:\n        JS_ThrowTypeError(ctx, \"import.meta not supported in this context\");\n        return JS_EXCEPTION;\n    }\n    return JS_GetImportMeta(ctx, m);\n}\n\n/* used by os.Worker() and import() */\nJSModuleDef *JS_RunModule(JSContext *ctx, const char *basename,\n                          const char *filename)\n{\n    JSModuleDef *m;\n    JSValue ret, func_obj;\n    \n    m = js_host_resolve_imported_module(ctx, basename, filename);\n    if (!m)\n        return NULL;\n    \n    if (js_resolve_module(ctx, m) < 0) {\n        js_free_modules(ctx, JS_FREE_MODULE_NOT_RESOLVED);\n        return NULL;\n    }\n\n    /* Evaluate the module code */\n    func_obj = JS_DupValue(ctx, JS_MKPTR(JS_TAG_MODULE, m));\n    ret = JS_EvalFunction(ctx, func_obj);\n    if (JS_IsException(ret))\n        return NULL;\n    JS_FreeValue(ctx, ret);\n    return m;\n}\n\nstatic JSValue js_dynamic_import_job(JSContext *ctx,\n                                     int argc, JSValueConst *argv)\n{\n    JSValueConst *resolving_funcs = argv;\n    JSValueConst basename_val = argv[2];\n    JSValueConst specifier = argv[3];\n    JSModuleDef *m;\n    const char *basename = NULL, *filename;\n    JSValue ret, err, ns;\n\n    if (!JS_IsString(basename_val)) {\n        JS_ThrowTypeError(ctx, \"no function filename for import()\");\n        goto exception;\n    }\n    basename = JS_ToCString(ctx, basename_val);\n    if (!basename)\n        goto exception;\n\n    filename = JS_ToCString(ctx, specifier);\n    if (!filename)\n        goto exception;\n                     \n    m = JS_RunModule(ctx, basename, filename);\n    JS_FreeCString(ctx, filename);\n    if (!m)\n        goto exception;\n\n    /* return the module namespace */\n    ns = js_get_module_ns(ctx, m);\n    if (JS_IsException(ns))\n        goto exception;\n\n    ret = JS_Call(ctx, resolving_funcs[0], JS_UNDEFINED,\n                   1, (JSValueConst *)&ns);\n    JS_FreeValue(ctx, ret); /* XXX: what to do if exception ? */\n    JS_FreeValue(ctx, ns);\n    JS_FreeCString(ctx, basename);\n    return JS_UNDEFINED;\n exception:\n\n    err = JS_GetException(ctx);\n    ret = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED,\n                   1, (JSValueConst *)&err);\n    JS_FreeValue(ctx, ret); /* XXX: what to do if exception ? */\n    JS_FreeValue(ctx, err);\n    JS_FreeCString(ctx, basename);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_dynamic_import(JSContext *ctx, JSValueConst specifier)\n{\n    JSAtom basename;\n    JSValue promise, resolving_funcs[2], basename_val;\n    JSValueConst args[4];\n\n    basename = JS_GetScriptOrModuleName(ctx, 0);\n    if (basename == JS_ATOM_NULL)\n        basename_val = JS_NULL;\n    else\n        basename_val = JS_AtomToValue(ctx, basename);\n    JS_FreeAtom(ctx, basename);\n    if (JS_IsException(basename_val))\n        return basename_val;\n    \n    promise = JS_NewPromiseCapability(ctx, resolving_funcs);\n    if (JS_IsException(promise)) {\n        JS_FreeValue(ctx, basename_val);\n        return promise;\n    }\n\n    args[0] = resolving_funcs[0];\n    args[1] = resolving_funcs[1];\n    args[2] = basename_val;\n    args[3] = specifier;\n    \n    JS_EnqueueJob(ctx, js_dynamic_import_job, 4, args);\n\n    JS_FreeValue(ctx, basename_val);\n    JS_FreeValue(ctx, resolving_funcs[0]);\n    JS_FreeValue(ctx, resolving_funcs[1]);\n    return promise;\n}\n\n/* Run the <eval> function of the module and of all its requested\n   modules. */\nstatic JSValue js_evaluate_module(JSContext *ctx, JSModuleDef *m)\n{\n    JSModuleDef *m1;\n    int i;\n    JSValue ret_val;\n\n    if (m->eval_mark)\n        return JS_UNDEFINED; /* avoid cycles */\n\n    if (m->evaluated) {\n        /* if the module was already evaluated, rethrow the exception\n           it raised */\n        if (m->eval_has_exception) {\n            return JS_Throw(ctx, JS_DupValue(ctx, m->eval_exception));\n        } else {\n            return JS_UNDEFINED;\n        }\n    }\n\n    m->eval_mark = TRUE;\n\n    for(i = 0; i < m->req_module_entries_count; i++) {\n        JSReqModuleEntry *rme = &m->req_module_entries[i];\n        m1 = rme->module;\n        if (!m1->eval_mark) {\n            ret_val = js_evaluate_module(ctx, m1);\n            if (JS_IsException(ret_val)) {\n                m->eval_mark = FALSE;\n                return ret_val;\n            }\n            JS_FreeValue(ctx, ret_val);\n        }\n    }\n\n    if (m->init_func) {\n        /* C module init */\n        if (m->init_func(ctx, m) < 0)\n            ret_val = JS_EXCEPTION;\n        else\n            ret_val = JS_UNDEFINED;\n    } else {\n        ret_val = JS_CallFree(ctx, m->func_obj, JS_UNDEFINED, 0, NULL);\n        m->func_obj = JS_UNDEFINED;\n    }\n    if (JS_IsException(ret_val)) {\n        /* save the thrown exception value */\n        m->eval_has_exception = TRUE;\n        m->eval_exception = JS_DupValue(ctx, ctx->rt->current_exception);\n    }\n    m->eval_mark = FALSE;\n    m->evaluated = TRUE;\n    return ret_val;\n}\n\nstatic __exception JSAtom js_parse_from_clause(JSParseState *s)\n{\n    JSAtom module_name;\n    if (!token_is_pseudo_keyword(s, JS_ATOM_from)) {\n        js_parse_error(s, \"from clause expected\");\n        return JS_ATOM_NULL;\n    }\n    if (next_token(s))\n        return JS_ATOM_NULL;\n    if (s->token.val != TOK_STRING) {\n        js_parse_error(s, \"string expected\");\n        return JS_ATOM_NULL;\n    }\n    module_name = JS_ValueToAtom(s->ctx, s->token.u.str.str);\n    if (module_name == JS_ATOM_NULL)\n        return JS_ATOM_NULL;\n    if (next_token(s)) {\n        JS_FreeAtom(s->ctx, module_name);\n        return JS_ATOM_NULL;\n    }\n    return module_name;\n}\n\nstatic __exception int js_parse_export(JSParseState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSModuleDef *m = s->cur_func->module;\n    JSAtom local_name, export_name;\n    int first_export, idx, i, tok;\n    JSAtom module_name;\n    JSExportEntry *me;\n\n    if (next_token(s))\n        return -1;\n\n    tok = s->token.val;\n    if (tok == TOK_CLASS) {\n        return js_parse_class(s, FALSE, JS_PARSE_EXPORT_NAMED);\n    } else if (tok == TOK_FUNCTION ||\n               (token_is_pseudo_keyword(s, JS_ATOM_async) &&\n                peek_token(s, TRUE) == TOK_FUNCTION)) {\n        return js_parse_function_decl2(s, JS_PARSE_FUNC_STATEMENT,\n                                       JS_FUNC_NORMAL, JS_ATOM_NULL,\n                                       s->token.ptr, s->token.line_num,\n                                       JS_PARSE_EXPORT_NAMED, NULL);\n    }\n\n    if (next_token(s))\n        return -1;\n\n    switch(tok) {\n    case '{':\n        first_export = m->export_entries_count;\n        while (s->token.val != '}') {\n            if (!token_is_ident(s->token.val)) {\n                js_parse_error(s, \"identifier expected\");\n                return -1;\n            }\n            local_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n            export_name = JS_ATOM_NULL;\n            if (next_token(s))\n                goto fail;\n            if (token_is_pseudo_keyword(s, JS_ATOM_as)) {\n                if (next_token(s))\n                    goto fail;\n                if (!token_is_ident(s->token.val)) {\n                    js_parse_error(s, \"identifier expected\");\n                    goto fail;\n                }\n                export_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n                if (next_token(s)) {\n                fail:\n                    JS_FreeAtom(ctx, local_name);\n                fail1:\n                    JS_FreeAtom(ctx, export_name);\n                    return -1;\n                }\n            } else {\n                export_name = JS_DupAtom(ctx, local_name);\n            }\n            me = add_export_entry(s, m, local_name, export_name,\n                                  JS_EXPORT_TYPE_LOCAL);\n            JS_FreeAtom(ctx, local_name);\n            JS_FreeAtom(ctx, export_name);\n            if (!me)\n                return -1;\n            if (s->token.val != ',')\n                break;\n            if (next_token(s))\n                return -1;\n        }\n        if (js_parse_expect(s, '}'))\n            return -1;\n        if (token_is_pseudo_keyword(s, JS_ATOM_from)) {\n            module_name = js_parse_from_clause(s);\n            if (module_name == JS_ATOM_NULL)\n                return -1;\n            idx = add_req_module_entry(ctx, m, module_name);\n            JS_FreeAtom(ctx, module_name);\n            if (idx < 0)\n                return -1;\n            for(i = first_export; i < m->export_entries_count; i++) {\n                me = &m->export_entries[i];\n                me->export_type = JS_EXPORT_TYPE_INDIRECT;\n                me->u.req_module_idx = idx;\n            }\n        }\n        break;\n    case '*':\n        if (token_is_pseudo_keyword(s, JS_ATOM_as)) {\n            /* export ns from */\n            if (next_token(s))\n                return -1;\n            if (!token_is_ident(s->token.val)) {\n                js_parse_error(s, \"identifier expected\");\n                return -1;\n            }\n            export_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n            if (next_token(s))\n                goto fail1;\n            module_name = js_parse_from_clause(s);\n            if (module_name == JS_ATOM_NULL)\n                goto fail1;\n            idx = add_req_module_entry(ctx, m, module_name);\n            JS_FreeAtom(ctx, module_name);\n            if (idx < 0)\n                goto fail1;\n            me = add_export_entry(s, m, JS_ATOM__star_, export_name,\n                                  JS_EXPORT_TYPE_INDIRECT);\n            JS_FreeAtom(ctx, export_name);\n            if (!me)\n                return -1;\n            me->u.req_module_idx = idx;\n        } else {\n            module_name = js_parse_from_clause(s);\n            if (module_name == JS_ATOM_NULL)\n                return -1;\n            idx = add_req_module_entry(ctx, m, module_name);\n            JS_FreeAtom(ctx, module_name);\n            if (idx < 0)\n                return -1;\n            if (add_star_export_entry(ctx, m, idx) < 0)\n                return -1;\n        }\n        break;\n    case TOK_DEFAULT:\n        if (s->token.val == TOK_CLASS) {\n            return js_parse_class(s, FALSE, JS_PARSE_EXPORT_DEFAULT);\n        } else if (s->token.val == TOK_FUNCTION ||\n                   (token_is_pseudo_keyword(s, JS_ATOM_async) &&\n                    peek_token(s, TRUE) == TOK_FUNCTION)) {\n            return js_parse_function_decl2(s, JS_PARSE_FUNC_STATEMENT,\n                                           JS_FUNC_NORMAL, JS_ATOM_NULL,\n                                           s->token.ptr, s->token.line_num,\n                                           JS_PARSE_EXPORT_DEFAULT, NULL);\n        } else {\n            if (js_parse_assign_expr(s))\n                return -1;\n        }\n        /* set the name of anonymous functions */\n        set_object_name(s, JS_ATOM_default);\n\n        /* store the value in the _default_ global variable and export\n           it */\n        local_name = JS_ATOM__default_;\n        if (define_var(s, s->cur_func, local_name, JS_VAR_DEF_LET) < 0)\n            return -1;\n        emit_op(s, OP_scope_put_var_init);\n        emit_atom(s, local_name);\n        emit_u16(s, 0);\n\n        if (!add_export_entry(s, m, local_name, JS_ATOM_default,\n                              JS_EXPORT_TYPE_LOCAL))\n            return -1;\n        break;\n    case TOK_VAR:\n    case TOK_LET:\n    case TOK_CONST:\n        return js_parse_var(s, TRUE, tok, TRUE);\n    default:\n        return js_parse_error(s, \"invalid export syntax\");\n    }\n    return js_parse_expect_semi(s);\n}\n\nstatic int add_closure_var(JSContext *ctx, JSFunctionDef *s,\n                           BOOL is_local, BOOL is_arg,\n                           int var_idx, JSAtom var_name,\n                           BOOL is_const, BOOL is_lexical,\n                           JSVarKindEnum var_kind);\n\nstatic int add_import(JSParseState *s, JSModuleDef *m,\n                      JSAtom local_name, JSAtom import_name)\n{\n    JSContext *ctx = s->ctx;\n    int i, var_idx;\n    JSImportEntry *mi;\n    BOOL is_local;\n\n    if (local_name == JS_ATOM_arguments || local_name == JS_ATOM_eval)\n        return js_parse_error(s, \"invalid import binding\");\n\n    if (local_name != JS_ATOM_default) {\n        for (i = 0; i < s->cur_func->closure_var_count; i++) {\n            if (s->cur_func->closure_var[i].var_name == local_name)\n                return js_parse_error(s, \"duplicate import binding\");\n        }\n    }\n\n    is_local = (import_name == JS_ATOM__star_);\n    var_idx = add_closure_var(ctx, s->cur_func, is_local, FALSE,\n                              m->import_entries_count,\n                              local_name, TRUE, TRUE, FALSE);\n    if (var_idx < 0)\n        return -1;\n    if (js_resize_array(ctx, (void **)&m->import_entries,\n                        sizeof(JSImportEntry),\n                        &m->import_entries_size,\n                        m->import_entries_count + 1))\n        return -1;\n    mi = &m->import_entries[m->import_entries_count++];\n    mi->import_name = JS_DupAtom(ctx, import_name);\n    mi->var_idx = var_idx;\n    return 0;\n}\n\nstatic __exception int js_parse_import(JSParseState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSModuleDef *m = s->cur_func->module;\n    JSAtom local_name, import_name, module_name;\n    int first_import, i, idx;\n\n    if (next_token(s))\n        return -1;\n\n    first_import = m->import_entries_count;\n    if (s->token.val == TOK_STRING) {\n        module_name = JS_ValueToAtom(ctx, s->token.u.str.str);\n        if (module_name == JS_ATOM_NULL)\n            return -1;\n        if (next_token(s)) {\n            JS_FreeAtom(ctx, module_name);\n            return -1;\n        }\n    } else {\n        if (s->token.val == TOK_IDENT) {\n            if (s->token.u.ident.is_reserved) {\n                return js_parse_error_reserved_identifier(s);\n            }\n            /* \"default\" import */\n            local_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n            import_name = JS_ATOM_default;\n            if (next_token(s))\n                goto fail;\n            if (add_import(s, m, local_name, import_name))\n                goto fail;\n            JS_FreeAtom(ctx, local_name);\n\n            if (s->token.val != ',')\n                goto end_import_clause;\n            if (next_token(s))\n                return -1;\n        }\n\n        if (s->token.val == '*') {\n            /* name space import */\n            if (next_token(s))\n                return -1;\n            if (!token_is_pseudo_keyword(s, JS_ATOM_as))\n                return js_parse_error(s, \"expecting 'as'\");\n            if (next_token(s))\n                return -1;\n            if (!token_is_ident(s->token.val)) {\n                js_parse_error(s, \"identifier expected\");\n                return -1;\n            }\n            local_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n            import_name = JS_ATOM__star_;\n            if (next_token(s))\n                goto fail;\n            if (add_import(s, m, local_name, import_name))\n                goto fail;\n            JS_FreeAtom(ctx, local_name);\n        } else if (s->token.val == '{') {\n            if (next_token(s))\n                return -1;\n\n            while (s->token.val != '}') {\n                if (!token_is_ident(s->token.val)) {\n                    js_parse_error(s, \"identifier expected\");\n                    return -1;\n                }\n                import_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n                local_name = JS_ATOM_NULL;\n                if (next_token(s))\n                    goto fail;\n                if (token_is_pseudo_keyword(s, JS_ATOM_as)) {\n                    if (next_token(s))\n                        goto fail;\n                    if (!token_is_ident(s->token.val)) {\n                        js_parse_error(s, \"identifier expected\");\n                        goto fail;\n                    }\n                    local_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n                    if (next_token(s)) {\n                    fail:\n                        JS_FreeAtom(ctx, local_name);\n                        JS_FreeAtom(ctx, import_name);\n                        return -1;\n                    }\n                } else {\n                    local_name = JS_DupAtom(ctx, import_name);\n                }\n                if (add_import(s, m, local_name, import_name))\n                    goto fail;\n                JS_FreeAtom(ctx, local_name);\n                JS_FreeAtom(ctx, import_name);\n                if (s->token.val != ',')\n                    break;\n                if (next_token(s))\n                    return -1;\n            }\n            if (js_parse_expect(s, '}'))\n                return -1;\n        }\n    end_import_clause:\n        module_name = js_parse_from_clause(s);\n        if (module_name == JS_ATOM_NULL)\n            return -1;\n    }\n    idx = add_req_module_entry(ctx, m, module_name);\n    JS_FreeAtom(ctx, module_name);\n    if (idx < 0)\n        return -1;\n    for(i = first_import; i < m->import_entries_count; i++)\n        m->import_entries[i].req_module_idx = idx;\n\n    return js_parse_expect_semi(s);\n}\n\nstatic __exception int js_parse_source_element(JSParseState *s)\n{\n    JSFunctionDef *fd = s->cur_func;\n    int tok;\n    \n    if (s->token.val == TOK_FUNCTION ||\n        (token_is_pseudo_keyword(s, JS_ATOM_async) &&\n         peek_token(s, TRUE) == TOK_FUNCTION)) {\n        if (js_parse_function_decl(s, JS_PARSE_FUNC_STATEMENT,\n                                   JS_FUNC_NORMAL, JS_ATOM_NULL,\n                                   s->token.ptr, s->token.line_num))\n            return -1;\n    } else if (s->token.val == TOK_EXPORT && fd->module) {\n        if (js_parse_export(s))\n            return -1;\n    } else if (s->token.val == TOK_IMPORT && fd->module &&\n               ((tok = peek_token(s, FALSE)) != '(' && tok != '.'))  {\n        /* the peek_token is needed to avoid confusion with ImportCall\n           (dynamic import) or import.meta */\n        if (js_parse_import(s))\n            return -1;\n    } else {\n        if (js_parse_statement_or_decl(s, DECL_MASK_ALL))\n            return -1;\n    }\n    return 0;\n}\n\nstatic JSFunctionDef *js_new_function_def(JSContext *ctx,\n                                          JSFunctionDef *parent,\n                                          BOOL is_eval,\n                                          BOOL is_func_expr,\n                                          const char *filename, int line_num)\n{\n    JSFunctionDef *fd;\n\n    fd = js_mallocz(ctx, sizeof(*fd));\n    if (!fd)\n        return NULL;\n\n    fd->ctx = ctx;\n    init_list_head(&fd->child_list);\n\n    /* insert in parent list */\n    fd->parent = parent;\n    fd->parent_cpool_idx = -1;\n    if (parent) {\n        list_add_tail(&fd->link, &parent->child_list);\n        fd->js_mode = parent->js_mode;\n        fd->parent_scope_level = parent->scope_level;\n    }\n\n    fd->is_eval = is_eval;\n    fd->is_func_expr = is_func_expr;\n    js_dbuf_init(ctx, &fd->byte_code);\n    fd->last_opcode_pos = -1;\n    fd->func_name = JS_ATOM_NULL;\n    fd->var_object_idx = -1;\n    fd->arg_var_object_idx = -1;\n    fd->arguments_var_idx = -1;\n    fd->arguments_arg_idx = -1;\n    fd->func_var_idx = -1;\n    fd->eval_ret_idx = -1;\n    fd->this_var_idx = -1;\n    fd->new_target_var_idx = -1;\n    fd->this_active_func_var_idx = -1;\n    fd->home_object_var_idx = -1;\n\n    /* XXX: should distinguish arg, var and var object and body scopes */\n    fd->scopes = fd->def_scope_array;\n    fd->scope_size = countof(fd->def_scope_array);\n    fd->scope_count = 1;\n    fd->scopes[0].first = -1;\n    fd->scopes[0].parent = -1;\n    fd->scope_level = 0;  /* 0: var/arg scope */\n    fd->scope_first = -1;\n    fd->body_scope = -1;\n\n    fd->filename = JS_NewAtom(ctx, filename);\n    fd->line_num = line_num;\n\n    js_dbuf_init(ctx, &fd->pc2line);\n    //fd->pc2line_last_line_num = line_num;\n    //fd->pc2line_last_pc = 0;\n    fd->last_opcode_line_num = line_num;\n\n    return fd;\n}\n\nstatic void free_bytecode_atoms(JSRuntime *rt,\n                                const uint8_t *bc_buf, int bc_len,\n                                BOOL use_short_opcodes)\n{\n    int pos, len, op;\n    JSAtom atom;\n    const JSOpCode *oi;\n    \n    pos = 0;\n    while (pos < bc_len) {\n        op = bc_buf[pos];\n        if (use_short_opcodes)\n            oi = &short_opcode_info(op);\n        else\n            oi = &opcode_info[op];\n            \n        len = oi->size;\n        switch(oi->fmt) {\n        case OP_FMT_atom:\n        case OP_FMT_atom_u8:\n        case OP_FMT_atom_u16:\n        case OP_FMT_atom_label_u8:\n        case OP_FMT_atom_label_u16:\n            atom = get_u32(bc_buf + pos + 1);\n            JS_FreeAtomRT(rt, atom);\n            break;\n        default:\n            break;\n        }\n        pos += len;\n    }\n}\n\nstatic void js_free_function_def(JSContext *ctx, JSFunctionDef *fd)\n{\n    int i;\n    struct list_head *el, *el1;\n\n    /* free the child functions */\n    list_for_each_safe(el, el1, &fd->child_list) {\n        JSFunctionDef *fd1;\n        fd1 = list_entry(el, JSFunctionDef, link);\n        js_free_function_def(ctx, fd1);\n    }\n\n    free_bytecode_atoms(ctx->rt, fd->byte_code.buf, fd->byte_code.size,\n                        fd->use_short_opcodes);\n    dbuf_free(&fd->byte_code);\n    js_free(ctx, fd->jump_slots);\n    js_free(ctx, fd->label_slots);\n    js_free(ctx, fd->line_number_slots);\n\n    for(i = 0; i < fd->cpool_count; i++) {\n        JS_FreeValue(ctx, fd->cpool[i]);\n    }\n    js_free(ctx, fd->cpool);\n\n    JS_FreeAtom(ctx, fd->func_name);\n\n    for(i = 0; i < fd->var_count; i++) {\n        JS_FreeAtom(ctx, fd->vars[i].var_name);\n    }\n    js_free(ctx, fd->vars);\n    for(i = 0; i < fd->arg_count; i++) {\n        JS_FreeAtom(ctx, fd->args[i].var_name);\n    }\n    js_free(ctx, fd->args);\n\n    for(i = 0; i < fd->global_var_count; i++) {\n        JS_FreeAtom(ctx, fd->global_vars[i].var_name);\n    }\n    js_free(ctx, fd->global_vars);\n\n    for(i = 0; i < fd->closure_var_count; i++) {\n        JSClosureVar *cv = &fd->closure_var[i];\n        JS_FreeAtom(ctx, cv->var_name);\n    }\n    js_free(ctx, fd->closure_var);\n\n    if (fd->scopes != fd->def_scope_array)\n        js_free(ctx, fd->scopes);\n\n    JS_FreeAtom(ctx, fd->filename);\n    dbuf_free(&fd->pc2line);\n\n    js_free(ctx, fd->source);\n\n    if (fd->parent) {\n        /* remove in parent list */\n        list_del(&fd->link);\n    }\n    js_free(ctx, fd);\n}\n\n#ifdef DUMP_BYTECODE\nstatic const char *skip_lines(const char *p, int n) {\n    while (n-- > 0 && *p) {\n        while (*p && *p++ != '\\n')\n            continue;\n    }\n    return p;\n}\n\nstatic void print_lines(const char *source, int line, int line1) {\n    const char *s = source;\n    const char *p = skip_lines(s, line);\n    if (*p) {\n        while (line++ < line1) {\n            p = skip_lines(s = p, 1);\n            printf(\";; %.*s\", (int)(p - s), s);\n            if (!*p) {\n                if (p[-1] != '\\n')\n                    printf(\"\\n\");\n                break;\n            }\n        }\n    }\n}\n\nstatic void dump_byte_code(JSContext *ctx, int pass,\n                           const uint8_t *tab, int len,\n                           const JSVarDef *args, int arg_count,\n                           const JSVarDef *vars, int var_count,\n                           const JSClosureVar *closure_var, int closure_var_count,\n                           const JSValue *cpool, uint32_t cpool_count,\n                           const char *source, int line_num,\n                           const LabelSlot *label_slots, JSFunctionBytecode *b)\n{\n    const JSOpCode *oi;\n    int pos, pos_next, op, size, idx, addr, line, line1, in_source;\n    uint8_t *bits = js_mallocz(ctx, len * sizeof(*bits));\n    BOOL use_short_opcodes = (b != NULL);\n\n    /* scan for jump targets */\n    for (pos = 0; pos < len; pos = pos_next) {\n        op = tab[pos];\n        if (use_short_opcodes)\n            oi = &short_opcode_info(op);\n        else\n            oi = &opcode_info[op];\n        pos_next = pos + oi->size;\n        if (op < OP_COUNT) {\n            switch (oi->fmt) {\n#if SHORT_OPCODES\n            case OP_FMT_label8:\n                pos++;\n                addr = (int8_t)tab[pos];\n                goto has_addr;\n            case OP_FMT_label16:\n                pos++;\n                addr = (int16_t)get_u16(tab + pos);\n                goto has_addr;\n#endif\n            case OP_FMT_atom_label_u8:\n            case OP_FMT_atom_label_u16:\n                pos += 4;\n                /* fall thru */\n            case OP_FMT_label:\n            case OP_FMT_label_u16:\n                pos++;\n                addr = get_u32(tab + pos);\n                goto has_addr;\n            has_addr:\n                if (pass == 1)\n                    addr = label_slots[addr].pos;\n                if (pass == 2)\n                    addr = label_slots[addr].pos2;\n                if (pass == 3)\n                    addr += pos;\n                if (addr >= 0 && addr < len)\n                    bits[addr] |= 1;\n                break;\n            }\n        }\n    }\n    in_source = 0;\n    if (source) {\n        /* Always print first line: needed if single line */\n        print_lines(source, 0, 1);\n        in_source = 1;\n    }\n    line1 = line = 1;\n    pos = 0;\n    while (pos < len) {\n        op = tab[pos];\n        if (source) {\n            if (b) {\n                line1 = find_line_num(ctx, b, pos) - line_num + 1;\n            } else if (op == OP_line_num) {\n                line1 = get_u32(tab + pos + 1) - line_num + 1;\n            }\n            if (line1 > line) {\n                if (!in_source)\n                    printf(\"\\n\");\n                in_source = 1;\n                print_lines(source, line, line1);\n                line = line1;\n                //bits[pos] |= 2;\n            }\n        }\n        if (in_source)\n            printf(\"\\n\");\n        in_source = 0;\n        if (op >= OP_COUNT) {\n            printf(\"invalid opcode (0x%02x)\\n\", op);\n            pos++;\n            continue;\n        }\n        if (use_short_opcodes)\n            oi = &short_opcode_info(op);\n        else\n            oi = &opcode_info[op];\n        size = oi->size;\n        if (pos + size > len) {\n            printf(\"truncated opcode (0x%02x)\\n\", op);\n            break;\n        }\n#if defined(DUMP_BYTECODE) && (DUMP_BYTECODE & 16)\n        {\n            int i, x, x0;\n            x = x0 = printf(\"%5d \", pos);\n            for (i = 0; i < size; i++) {\n                if (i == 6) {\n                    printf(\"\\n%*s\", x = x0, \"\");\n                }\n                x += printf(\" %02X\", tab[pos + i]);\n            }\n            printf(\"%*s\", x0 + 20 - x, \"\");\n        }\n#endif\n        if (bits[pos]) {\n            printf(\"%5d:  \", pos);\n        } else {\n            printf(\"        \");\n        }\n        printf(\"%s\", oi->name);\n        pos++;\n        switch(oi->fmt) {\n        case OP_FMT_none_int:\n            printf(\" %d\", op - OP_push_0);\n            break;\n        case OP_FMT_npopx:\n            printf(\" %d\", op - OP_call0);\n            break;\n        case OP_FMT_u8:\n            printf(\" %u\", get_u8(tab + pos));\n            break;\n        case OP_FMT_i8:\n            printf(\" %d\", get_i8(tab + pos));\n            break;\n        case OP_FMT_u16:\n        case OP_FMT_npop:\n            printf(\" %u\", get_u16(tab + pos));\n            break;\n        case OP_FMT_npop_u16:\n            printf(\" %u,%u\", get_u16(tab + pos), get_u16(tab + pos + 2));\n            break;\n        case OP_FMT_i16:\n            printf(\" %d\", get_i16(tab + pos));\n            break;\n        case OP_FMT_i32:\n            printf(\" %d\", get_i32(tab + pos));\n            break;\n        case OP_FMT_u32:\n            printf(\" %u\", get_u32(tab + pos));\n            break;\n#if SHORT_OPCODES\n        case OP_FMT_label8:\n            addr = get_i8(tab + pos);\n            goto has_addr1;\n        case OP_FMT_label16:\n            addr = get_i16(tab + pos);\n            goto has_addr1;\n#endif\n        case OP_FMT_label:\n            addr = get_u32(tab + pos);\n            goto has_addr1;\n        has_addr1:\n            if (pass == 1)\n                printf(\" %u:%u\", addr, label_slots[addr].pos);\n            if (pass == 2)\n                printf(\" %u:%u\", addr, label_slots[addr].pos2);\n            if (pass == 3)\n                printf(\" %u\", addr + pos);\n            break;\n        case OP_FMT_label_u16:\n            addr = get_u32(tab + pos);\n            if (pass == 1)\n                printf(\" %u:%u\", addr, label_slots[addr].pos);\n            if (pass == 2)\n                printf(\" %u:%u\", addr, label_slots[addr].pos2);\n            if (pass == 3)\n                printf(\" %u\", addr + pos);\n            printf(\",%u\", get_u16(tab + pos + 4));\n            break;\n#if SHORT_OPCODES\n        case OP_FMT_const8:\n            idx = get_u8(tab + pos);\n            goto has_pool_idx;\n#endif\n        case OP_FMT_const:\n            idx = get_u32(tab + pos);\n            goto has_pool_idx;\n        has_pool_idx:\n            printf(\" %u: \", idx);\n            if (idx < cpool_count) {\n                JS_DumpValue(ctx, cpool[idx]);\n            }\n            break;\n        case OP_FMT_atom:\n            printf(\" \");\n            print_atom(ctx, get_u32(tab + pos));\n            break;\n        case OP_FMT_atom_u8:\n            printf(\" \");\n            print_atom(ctx, get_u32(tab + pos));\n            printf(\",%d\", get_u8(tab + pos + 4));\n            break;\n        case OP_FMT_atom_u16:\n            printf(\" \");\n            print_atom(ctx, get_u32(tab + pos));\n            printf(\",%d\", get_u16(tab + pos + 4));\n            break;\n        case OP_FMT_atom_label_u8:\n        case OP_FMT_atom_label_u16:\n            printf(\" \");\n            print_atom(ctx, get_u32(tab + pos));\n            addr = get_u32(tab + pos + 4);\n            if (pass == 1)\n                printf(\",%u:%u\", addr, label_slots[addr].pos);\n            if (pass == 2)\n                printf(\",%u:%u\", addr, label_slots[addr].pos2);\n            if (pass == 3)\n                printf(\",%u\", addr + pos + 4);\n            if (oi->fmt == OP_FMT_atom_label_u8)\n                printf(\",%u\", get_u8(tab + pos + 8));\n            else\n                printf(\",%u\", get_u16(tab + pos + 8));\n            break;\n        case OP_FMT_none_loc:\n            idx = (op - OP_get_loc0) % 4;\n            goto has_loc;\n        case OP_FMT_loc8:\n            idx = get_u8(tab + pos);\n            goto has_loc;\n        case OP_FMT_loc:\n            idx = get_u16(tab + pos);\n        has_loc:\n            printf(\" %d: \", idx);\n            if (idx < var_count) {\n                print_atom(ctx, vars[idx].var_name);\n            }\n            break;\n        case OP_FMT_none_arg:\n            idx = (op - OP_get_arg0) % 4;\n            goto has_arg;\n        case OP_FMT_arg:\n            idx = get_u16(tab + pos);\n        has_arg:\n            printf(\" %d: \", idx);\n            if (idx < arg_count) {\n                print_atom(ctx, args[idx].var_name);\n            }\n            break;\n        case OP_FMT_none_var_ref:\n            idx = (op - OP_get_var_ref0) % 4;\n            goto has_var_ref;\n        case OP_FMT_var_ref:\n            idx = get_u16(tab + pos);\n        has_var_ref:\n            printf(\" %d: \", idx);\n            if (idx < closure_var_count) {\n                print_atom(ctx, closure_var[idx].var_name);\n            }\n            break;\n        default:\n            break;\n        }\n        printf(\"\\n\");\n        pos += oi->size - 1;\n    }\n    if (source) {\n        if (!in_source)\n            printf(\"\\n\");\n        print_lines(source, line, INT32_MAX);\n    }\n    js_free(ctx, bits);\n}\n\nstatic __maybe_unused void dump_pc2line(JSContext *ctx, const uint8_t *buf, int len,\n                                                 int line_num)\n{\n    const uint8_t *p_end, *p_next, *p;\n    int pc, v;\n    unsigned int op;\n\n    if (len <= 0)\n        return;\n\n    printf(\"%5s %5s\\n\", \"PC\", \"LINE\");\n\n    p = buf;\n    p_end = buf + len;\n    pc = 0;\n    while (p < p_end) {\n        op = *p++;\n        if (op == 0) {\n            v = unicode_from_utf8(p, p_end - p, &p_next);\n            if (v < 0)\n                goto fail;\n            pc += v;\n            p = p_next;\n            v = unicode_from_utf8(p, p_end - p, &p_next);\n            if (v < 0) {\n            fail:\n                printf(\"invalid pc2line encode pos=%d\\n\", (int)(p - buf));\n                return;\n            }\n            if (!(v & 1)) {\n                v = v >> 1;\n            } else {\n                v = -(v >> 1) - 1;\n            }\n            line_num += v;\n            p = p_next;\n        } else {\n            op -= PC2LINE_OP_FIRST;\n            pc += (op / PC2LINE_RANGE);\n            line_num += (op % PC2LINE_RANGE) + PC2LINE_BASE;\n        }\n        printf(\"%5d %5d\\n\", pc, line_num);\n    }\n}\n\nstatic __maybe_unused void js_dump_function_bytecode(JSContext *ctx, JSFunctionBytecode *b)\n{\n    int i;\n    char atom_buf[ATOM_GET_STR_BUF_SIZE];\n    const char *str;\n\n    if (b->has_debug && b->debug.filename != JS_ATOM_NULL) {\n        str = JS_AtomGetStr(ctx, atom_buf, sizeof(atom_buf), b->debug.filename);\n        printf(\"%s:%d: \", str, b->debug.line_num);\n    }\n\n    str = JS_AtomGetStr(ctx, atom_buf, sizeof(atom_buf), b->func_name);\n    printf(\"function: %s%s\\n\", &\"*\"[b->func_kind != JS_FUNC_GENERATOR], str);\n    if (b->js_mode) {\n        printf(\"  mode:\");\n        if (b->js_mode & JS_MODE_STRICT)\n            printf(\" strict\");\n#ifdef CONFIG_BIGNUM\n        if (b->js_mode & JS_MODE_MATH)\n            printf(\" math\");\n#endif\n        printf(\"\\n\");\n    }\n    if (b->arg_count && b->vardefs) {\n        printf(\"  args:\");\n        for(i = 0; i < b->arg_count; i++) {\n            printf(\" %s\", JS_AtomGetStr(ctx, atom_buf, sizeof(atom_buf),\n                                        b->vardefs[i].var_name));\n        }\n        printf(\"\\n\");\n    }\n    if (b->var_count && b->vardefs) {\n        printf(\"  locals:\\n\");\n        for(i = 0; i < b->var_count; i++) {\n            JSVarDef *vd = &b->vardefs[b->arg_count + i];\n            printf(\"%5d: %s %s\", i,\n                   vd->var_kind == JS_VAR_CATCH ? \"catch\" :\n                   (vd->var_kind == JS_VAR_FUNCTION_DECL ||\n                    vd->var_kind == JS_VAR_NEW_FUNCTION_DECL) ? \"function\" :\n                   vd->is_const ? \"const\" :\n                   vd->is_lexical ? \"let\" : \"var\",\n                   JS_AtomGetStr(ctx, atom_buf, sizeof(atom_buf), vd->var_name));\n            if (vd->scope_level)\n                printf(\" [level:%d next:%d]\", vd->scope_level, vd->scope_next);\n            printf(\"\\n\");\n        }\n    }\n    if (b->closure_var_count) {\n        printf(\"  closure vars:\\n\");\n        for(i = 0; i < b->closure_var_count; i++) {\n            JSClosureVar *cv = &b->closure_var[i];\n            printf(\"%5d: %s %s:%s%d %s\\n\", i,\n                   JS_AtomGetStr(ctx, atom_buf, sizeof(atom_buf), cv->var_name),\n                   cv->is_local ? \"local\" : \"parent\",\n                   cv->is_arg ? \"arg\" : \"loc\", cv->var_idx,\n                   cv->is_const ? \"const\" :\n                   cv->is_lexical ? \"let\" : \"var\");\n        }\n    }\n    printf(\"  stack_size: %d\\n\", b->stack_size);\n    printf(\"  opcodes:\\n\");\n    dump_byte_code(ctx, 3, b->byte_code_buf, b->byte_code_len,\n                   b->vardefs, b->arg_count,\n                   b->vardefs ? b->vardefs + b->arg_count : NULL, b->var_count,\n                   b->closure_var, b->closure_var_count,\n                   b->cpool, b->cpool_count,\n                   b->has_debug ? b->debug.source : NULL,\n                   b->has_debug ? b->debug.line_num : -1, NULL, b);\n#if defined(DUMP_BYTECODE) && (DUMP_BYTECODE & 32)\n    if (b->has_debug)\n        dump_pc2line(ctx, b->debug.pc2line_buf, b->debug.pc2line_len, b->debug.line_num);\n#endif\n    printf(\"\\n\");\n}\n#endif\n\nstatic int add_closure_var(JSContext *ctx, JSFunctionDef *s,\n                           BOOL is_local, BOOL is_arg,\n                           int var_idx, JSAtom var_name,\n                           BOOL is_const, BOOL is_lexical,\n                           JSVarKindEnum var_kind)\n{\n    JSClosureVar *cv;\n\n    /* the closure variable indexes are currently stored on 16 bits */\n    if (s->closure_var_count >= JS_MAX_LOCAL_VARS) {\n        JS_ThrowInternalError(ctx, \"too many closure variables\");\n        return -1;\n    }\n\n    if (js_resize_array(ctx, (void **)&s->closure_var,\n                        sizeof(s->closure_var[0]),\n                        &s->closure_var_size, s->closure_var_count + 1))\n        return -1;\n    cv = &s->closure_var[s->closure_var_count++];\n    cv->is_local = is_local;\n    cv->is_arg = is_arg;\n    cv->is_const = is_const;\n    cv->is_lexical = is_lexical;\n    cv->var_kind = var_kind;\n    cv->var_idx = var_idx;\n    cv->var_name = JS_DupAtom(ctx, var_name);\n    return s->closure_var_count - 1;\n}\n\nstatic int find_closure_var(JSContext *ctx, JSFunctionDef *s,\n                            JSAtom var_name)\n{\n    int i;\n    for(i = 0; i < s->closure_var_count; i++) {\n        JSClosureVar *cv = &s->closure_var[i];\n        if (cv->var_name == var_name)\n            return i;\n    }\n    return -1;\n}\n\n/* 'fd' must be a parent of 's'. Create in 's' a closure referencing a\n   local variable (is_local = TRUE) or a closure (is_local = FALSE) in\n   'fd' */\nstatic int get_closure_var2(JSContext *ctx, JSFunctionDef *s,\n                            JSFunctionDef *fd, BOOL is_local,\n                            BOOL is_arg, int var_idx, JSAtom var_name,\n                            BOOL is_const, BOOL is_lexical,\n                            JSVarKindEnum var_kind)\n{\n    int i;\n\n    if (fd != s->parent) {\n        var_idx = get_closure_var2(ctx, s->parent, fd, is_local,\n                                   is_arg, var_idx, var_name,\n                                   is_const, is_lexical, var_kind);\n        if (var_idx < 0)\n            return -1;\n        is_local = FALSE;\n    }\n    for(i = 0; i < s->closure_var_count; i++) {\n        JSClosureVar *cv = &s->closure_var[i];\n        if (cv->var_idx == var_idx && cv->is_arg == is_arg &&\n            cv->is_local == is_local)\n            return i;\n    }\n    return add_closure_var(ctx, s, is_local, is_arg, var_idx, var_name,\n                           is_const, is_lexical, var_kind);\n}\n\nstatic int get_closure_var(JSContext *ctx, JSFunctionDef *s,\n                           JSFunctionDef *fd, BOOL is_arg,\n                           int var_idx, JSAtom var_name,\n                           BOOL is_const, BOOL is_lexical,\n                           JSVarKindEnum var_kind)\n{\n    return get_closure_var2(ctx, s, fd, TRUE, is_arg,\n                            var_idx, var_name, is_const, is_lexical,\n                            var_kind);\n}\n\nstatic int get_with_scope_opcode(int op)\n{\n    if (op == OP_scope_get_var_undef)\n        return OP_with_get_var;\n    else\n        return OP_with_get_var + (op - OP_scope_get_var);\n}\n\nstatic BOOL can_opt_put_ref_value(const uint8_t *bc_buf, int pos)\n{\n    int opcode = bc_buf[pos];\n    return (bc_buf[pos + 1] == OP_put_ref_value &&\n            (opcode == OP_insert3 ||\n             opcode == OP_perm4 ||\n             opcode == OP_nop ||\n             opcode == OP_rot3l));\n}\n\nstatic BOOL can_opt_put_global_ref_value(const uint8_t *bc_buf, int pos)\n{\n    int opcode = bc_buf[pos];\n    return (bc_buf[pos + 1] == OP_put_ref_value &&\n            (opcode == OP_insert3 ||\n             opcode == OP_perm4 ||\n             opcode == OP_nop ||\n             opcode == OP_rot3l));\n}\n\nstatic int optimize_scope_make_ref(JSContext *ctx, JSFunctionDef *s,\n                                   DynBuf *bc, uint8_t *bc_buf,\n                                   LabelSlot *ls, int pos_next,\n                                   int get_op, int var_idx)\n{\n    int label_pos, end_pos, pos;\n\n    /* XXX: should optimize `loc(a) += expr` as `expr add_loc(a)`\n       but only if expr does not modify `a`.\n       should scan the code between pos_next and label_pos\n       for operations that can potentially change `a`:\n       OP_scope_make_ref(a), function calls, jumps and gosub.\n     */\n    /* replace the reference get/put with normal variable\n       accesses */\n    if (bc_buf[pos_next] == OP_get_ref_value) {\n        dbuf_putc(bc, get_op);\n        dbuf_put_u16(bc, var_idx);\n        pos_next++;\n    }\n    /* remove the OP_label to make room for replacement */\n    /* label should have a refcount of 0 anyway */\n    /* XXX: should avoid this patch by inserting nops in phase 1 */\n    label_pos = ls->pos;\n    pos = label_pos - 5;\n    assert(bc_buf[pos] == OP_label);\n    /* label points to an instruction pair:\n       - insert3 / put_ref_value\n       - perm4 / put_ref_value\n       - rot3l / put_ref_value\n       - nop / put_ref_value\n     */\n    end_pos = label_pos + 2;\n    if (bc_buf[label_pos] == OP_insert3)\n        bc_buf[pos++] = OP_dup;\n    bc_buf[pos] = get_op + 1;\n    put_u16(bc_buf + pos + 1, var_idx);\n    pos += 3;\n    /* pad with OP_nop */\n    while (pos < end_pos)\n        bc_buf[pos++] = OP_nop;\n    return pos_next;\n}\n\nstatic int optimize_scope_make_global_ref(JSContext *ctx, JSFunctionDef *s,\n                                          DynBuf *bc, uint8_t *bc_buf,\n                                          LabelSlot *ls, int pos_next,\n                                          JSAtom var_name)\n{\n    int label_pos, end_pos, pos, op;\n    BOOL is_strict;\n    is_strict = ((s->js_mode & JS_MODE_STRICT) != 0);\n\n    /* replace the reference get/put with normal variable\n       accesses */\n    if (is_strict) {\n        /* need to check if the variable exists before evaluating the right\n           expression */\n        /* XXX: need an extra OP_true if destructuring an array */\n        dbuf_putc(bc, OP_check_var);\n        dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n    } else {\n        /* XXX: need 2 extra OP_true if destructuring an array */\n    }\n    if (bc_buf[pos_next] == OP_get_ref_value) {\n        dbuf_putc(bc, OP_get_var);\n        dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n        pos_next++;\n    }\n    /* remove the OP_label to make room for replacement */\n    /* label should have a refcount of 0 anyway */\n    /* XXX: should have emitted several OP_nop to avoid this kludge */\n    label_pos = ls->pos;\n    pos = label_pos - 5;\n    assert(bc_buf[pos] == OP_label);\n    end_pos = label_pos + 2;\n    op = bc_buf[label_pos];\n    if (is_strict) {\n        if (op != OP_nop) {\n            switch(op) {\n            case OP_insert3:\n                op = OP_insert2;\n                break;\n            case OP_perm4:\n                op = OP_perm3;\n                break;\n            case OP_rot3l:\n                op = OP_swap;\n                break;\n            default:\n                abort();\n            }\n            bc_buf[pos++] = op;\n        }\n    } else {\n        if (op == OP_insert3)\n            bc_buf[pos++] = OP_dup;\n    }\n    if (is_strict) {\n        bc_buf[pos] = OP_put_var_strict;\n        /* XXX: need 1 extra OP_drop if destructuring an array */\n    } else {\n        bc_buf[pos] = OP_put_var;\n        /* XXX: need 2 extra OP_drop if destructuring an array */\n    }\n    put_u32(bc_buf + pos + 1, JS_DupAtom(ctx, var_name));\n    pos += 5;\n    /* pad with OP_nop */\n    while (pos < end_pos)\n        bc_buf[pos++] = OP_nop;\n    return pos_next;\n}\n\nstatic int add_var_this(JSContext *ctx, JSFunctionDef *fd)\n{\n    int idx;\n    idx = add_var(ctx, fd, JS_ATOM_this);\n    if (idx >= 0 && fd->is_derived_class_constructor) {\n        JSVarDef *vd = &fd->vars[idx];\n        /* XXX: should have is_this flag or var type */\n        vd->is_lexical = 1; /* used to trigger 'uninitialized' checks\n                               in a derived class constructor */\n    }\n    return idx;\n}\n\nstatic int resolve_pseudo_var(JSContext *ctx, JSFunctionDef *s,\n                               JSAtom var_name)\n{\n    int var_idx;\n\n    if (!s->has_this_binding)\n        return -1;\n    switch(var_name) {\n    case JS_ATOM_home_object:\n        /* 'home_object' pseudo variable */\n        if (s->home_object_var_idx < 0)\n            s->home_object_var_idx = add_var(ctx, s, var_name);\n        var_idx = s->home_object_var_idx;\n        break;\n    case JS_ATOM_this_active_func:\n        /* 'this.active_func' pseudo variable */\n        if (s->this_active_func_var_idx < 0)\n            s->this_active_func_var_idx = add_var(ctx, s, var_name);\n        var_idx = s->this_active_func_var_idx;\n        break;\n    case JS_ATOM_new_target:\n        /* 'new.target' pseudo variable */\n        if (s->new_target_var_idx < 0)\n            s->new_target_var_idx = add_var(ctx, s, var_name);\n        var_idx = s->new_target_var_idx;\n        break;\n    case JS_ATOM_this:\n        /* 'this' pseudo variable */\n        if (s->this_var_idx < 0)\n            s->this_var_idx = add_var_this(ctx, s);\n        var_idx = s->this_var_idx;\n        break;\n    default:\n        var_idx = -1;\n        break;\n    }\n    return var_idx;\n}\n\n/* test if 'var_name' is in the variable object on the stack. If is it\n   the case, handle it and jump to 'label_done' */\nstatic void var_object_test(JSContext *ctx, JSFunctionDef *s,\n                            JSAtom var_name, int op, DynBuf *bc,\n                            int *plabel_done, BOOL is_with)\n{\n    dbuf_putc(bc, get_with_scope_opcode(op));\n    dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n    *plabel_done = new_label_fd(s, *plabel_done);\n    dbuf_put_u32(bc, *plabel_done);\n    dbuf_putc(bc, is_with);\n    update_label(s, *plabel_done, 1);\n    s->jump_size++;\n}\n    \n/* return the position of the next opcode */\nstatic int resolve_scope_var(JSContext *ctx, JSFunctionDef *s,\n                             JSAtom var_name, int scope_level, int op,\n                             DynBuf *bc, uint8_t *bc_buf,\n                             LabelSlot *ls, int pos_next)\n{\n    int idx, var_idx, is_put;\n    int label_done;\n    JSFunctionDef *fd;\n    JSVarDef *vd;\n    BOOL is_pseudo_var, is_arg_scope;\n\n    label_done = -1;\n\n    /* XXX: could be simpler to use a specific function to\n       resolve the pseudo variables */\n    is_pseudo_var = (var_name == JS_ATOM_home_object ||\n                     var_name == JS_ATOM_this_active_func ||\n                     var_name == JS_ATOM_new_target ||\n                     var_name == JS_ATOM_this);\n\n    /* resolve local scoped variables */\n    var_idx = -1;\n    for (idx = s->scopes[scope_level].first; idx >= 0;) {\n        vd = &s->vars[idx];\n        if (vd->var_name == var_name) {\n            if (op == OP_scope_put_var || op == OP_scope_make_ref) {\n                if (vd->is_const) {\n                    dbuf_putc(bc, OP_throw_error);\n                    dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                    dbuf_putc(bc, JS_THROW_VAR_RO);\n                    goto done;\n                }\n            }\n            var_idx = idx;\n            break;\n        } else\n        if (vd->var_name == JS_ATOM__with_ && !is_pseudo_var) {\n            dbuf_putc(bc, OP_get_loc);\n            dbuf_put_u16(bc, idx);\n            var_object_test(ctx, s, var_name, op, bc, &label_done, 1);\n        }\n        idx = vd->scope_next;\n    }\n    is_arg_scope = (idx == ARG_SCOPE_END);\n    if (var_idx < 0) {\n        /* argument scope: variables are not visible but pseudo\n           variables are visible */\n        if (!is_arg_scope) {\n            var_idx = find_var(ctx, s, var_name);\n        }\n\n        if (var_idx < 0 && is_pseudo_var)\n            var_idx = resolve_pseudo_var(ctx, s, var_name);\n\n        if (var_idx < 0 && var_name == JS_ATOM_arguments &&\n            s->has_arguments_binding) {\n            /* 'arguments' pseudo variable */\n            var_idx = add_arguments_var(ctx, s);\n        }\n        if (var_idx < 0 && s->is_func_expr && var_name == s->func_name) {\n            /* add a new variable with the function name */\n            var_idx = add_func_var(ctx, s, var_name);\n        }\n    }\n    if (var_idx >= 0) {\n        if ((op == OP_scope_put_var || op == OP_scope_make_ref) &&\n            !(var_idx & ARGUMENT_VAR_OFFSET) &&\n            s->vars[var_idx].is_const) {\n            /* only happens when assigning a function expression name\n               in strict mode */\n            dbuf_putc(bc, OP_throw_error);\n            dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n            dbuf_putc(bc, JS_THROW_VAR_RO);\n            goto done;\n        }\n        /* OP_scope_put_var_init is only used to initialize a\n           lexical variable, so it is never used in a with or var object. It\n           can be used with a closure (module global variable case). */\n        switch (op) {\n        case OP_scope_make_ref:\n            if (!(var_idx & ARGUMENT_VAR_OFFSET) &&\n                s->vars[var_idx].var_kind == JS_VAR_FUNCTION_NAME) {\n                /* Create a dummy object reference for the func_var */\n                dbuf_putc(bc, OP_object);\n                dbuf_putc(bc, OP_get_loc);\n                dbuf_put_u16(bc, var_idx);\n                dbuf_putc(bc, OP_define_field);\n                dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                dbuf_putc(bc, OP_push_atom_value);\n                dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n            } else\n            if (label_done == -1 && can_opt_put_ref_value(bc_buf, ls->pos)) {\n                int get_op;\n                if (var_idx & ARGUMENT_VAR_OFFSET) {\n                    get_op = OP_get_arg;\n                    var_idx -= ARGUMENT_VAR_OFFSET;\n                } else {\n                    if (s->vars[var_idx].is_lexical)\n                        get_op = OP_get_loc_check;\n                    else\n                        get_op = OP_get_loc;\n                }\n                pos_next = optimize_scope_make_ref(ctx, s, bc, bc_buf, ls,\n                                                   pos_next, get_op, var_idx);\n            } else {\n                /* Create a dummy object with a named slot that is\n                   a reference to the local variable */\n                if (var_idx & ARGUMENT_VAR_OFFSET) {\n                    dbuf_putc(bc, OP_make_arg_ref);\n                    dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                    dbuf_put_u16(bc, var_idx - ARGUMENT_VAR_OFFSET);\n                } else {\n                    dbuf_putc(bc, OP_make_loc_ref);\n                    dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                    dbuf_put_u16(bc, var_idx);\n                }\n            }\n            break;\n        case OP_scope_get_ref:\n            dbuf_putc(bc, OP_undefined);\n            /* fall thru */\n        case OP_scope_get_var_undef:\n        case OP_scope_get_var:\n        case OP_scope_put_var:\n        case OP_scope_put_var_init:\n            is_put = (op == OP_scope_put_var || op == OP_scope_put_var_init);\n            if (var_idx & ARGUMENT_VAR_OFFSET) {\n                dbuf_putc(bc, OP_get_arg + is_put);\n                dbuf_put_u16(bc, var_idx - ARGUMENT_VAR_OFFSET);\n            } else {\n                if (is_put) {\n                    if (s->vars[var_idx].is_lexical) {\n                        if (op == OP_scope_put_var_init) {\n                            /* 'this' can only be initialized once */\n                            if (var_name == JS_ATOM_this)\n                                dbuf_putc(bc, OP_put_loc_check_init);\n                            else\n                                dbuf_putc(bc, OP_put_loc);\n                        } else {\n                            dbuf_putc(bc, OP_put_loc_check);\n                        }\n                    } else {\n                        dbuf_putc(bc, OP_put_loc);\n                    }\n                } else {\n                    if (s->vars[var_idx].is_lexical) {\n                        dbuf_putc(bc, OP_get_loc_check);\n                    } else {\n                        dbuf_putc(bc, OP_get_loc);\n                    }\n                }\n                dbuf_put_u16(bc, var_idx);\n            }\n            break;\n        case OP_scope_delete_var:\n            dbuf_putc(bc, OP_push_false);\n            break;\n        }\n        goto done;\n    }\n    /* check eval object */\n    if (!is_arg_scope && s->var_object_idx >= 0 && !is_pseudo_var) {\n        dbuf_putc(bc, OP_get_loc);\n        dbuf_put_u16(bc, s->var_object_idx);\n        var_object_test(ctx, s, var_name, op, bc, &label_done, 0);\n    }\n    /* check eval object in argument scope */\n    if (s->arg_var_object_idx >= 0 && !is_pseudo_var) {\n        dbuf_putc(bc, OP_get_loc);\n        dbuf_put_u16(bc, s->arg_var_object_idx);\n        var_object_test(ctx, s, var_name, op, bc, &label_done, 0);\n    }\n\n    /* check parent scopes */\n    for (fd = s; fd->parent;) {\n        scope_level = fd->parent_scope_level;\n        fd = fd->parent;\n        for (idx = fd->scopes[scope_level].first; idx >= 0;) {\n            vd = &fd->vars[idx];\n            if (vd->var_name == var_name) {\n                if (op == OP_scope_put_var || op == OP_scope_make_ref) {\n                    if (vd->is_const) {\n                        dbuf_putc(bc, OP_throw_error);\n                        dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                        dbuf_putc(bc, JS_THROW_VAR_RO);\n                        goto done;\n                    }\n                }\n                var_idx = idx;\n                break;\n            } else if (vd->var_name == JS_ATOM__with_ && !is_pseudo_var) {\n                vd->is_captured = 1;\n                idx = get_closure_var(ctx, s, fd, FALSE, idx, vd->var_name, FALSE, FALSE, JS_VAR_NORMAL);\n                if (idx >= 0) {\n                    dbuf_putc(bc, OP_get_var_ref);\n                    dbuf_put_u16(bc, idx);\n                    var_object_test(ctx, s, var_name, op, bc, &label_done, 1);\n                }\n            }\n            idx = vd->scope_next;\n        }\n        is_arg_scope = (idx == ARG_SCOPE_END);\n        if (var_idx >= 0)\n            break;\n        \n        if (!is_arg_scope) {\n            var_idx = find_var(ctx, fd, var_name);\n            if (var_idx >= 0)\n                break;\n        }\n        if (is_pseudo_var) {\n            var_idx = resolve_pseudo_var(ctx, fd, var_name);\n            if (var_idx >= 0)\n                break;\n        }\n        if (var_name == JS_ATOM_arguments && fd->has_arguments_binding) {\n            var_idx = add_arguments_var(ctx, fd);\n            break;\n        }\n        if (fd->is_func_expr && fd->func_name == var_name) {\n            /* add a new variable with the function name */\n            var_idx = add_func_var(ctx, fd, var_name);\n            break;\n        }\n\n        /* check eval object */\n        if (!is_arg_scope && fd->var_object_idx >= 0 && !is_pseudo_var) {\n            vd = &fd->vars[fd->var_object_idx];\n            vd->is_captured = 1;\n            idx = get_closure_var(ctx, s, fd, FALSE,\n                                  fd->var_object_idx, vd->var_name,\n                                  FALSE, FALSE, JS_VAR_NORMAL);\n            dbuf_putc(bc, OP_get_var_ref);\n            dbuf_put_u16(bc, idx);\n            var_object_test(ctx, s, var_name, op, bc, &label_done, 0);\n        }\n\n        /* check eval object in argument scope */\n        if (fd->arg_var_object_idx >= 0 && !is_pseudo_var) {\n            vd = &fd->vars[fd->arg_var_object_idx];\n            vd->is_captured = 1;\n            idx = get_closure_var(ctx, s, fd, FALSE,\n                                  fd->arg_var_object_idx, vd->var_name,\n                                  FALSE, FALSE, JS_VAR_NORMAL);\n            dbuf_putc(bc, OP_get_var_ref);\n            dbuf_put_u16(bc, idx);\n            var_object_test(ctx, s, var_name, op, bc, &label_done, 0);\n        }\n        \n        if (fd->is_eval)\n            break; /* it it necessarily the top level function */\n    }\n\n    /* check direct eval scope (in the closure of the eval function\n       which is necessarily at the top level) */\n    if (!fd)\n        fd = s;\n    if (var_idx < 0 && fd->is_eval) {\n        int idx1;\n        for (idx1 = 0; idx1 < fd->closure_var_count; idx1++) {\n            JSClosureVar *cv = &fd->closure_var[idx1];\n            if (var_name == cv->var_name) {\n                if (fd != s) {\n                    idx = get_closure_var2(ctx, s, fd,\n                                           FALSE,\n                                           cv->is_arg, idx1,\n                                           cv->var_name, cv->is_const,\n                                           cv->is_lexical, cv->var_kind);\n                } else {\n                    idx = idx1;\n                }\n                goto has_idx;\n            } else if ((cv->var_name == JS_ATOM__var_ ||\n                        cv->var_name == JS_ATOM__arg_var_ ||\n                        cv->var_name == JS_ATOM__with_) && !is_pseudo_var) {\n                int is_with = (cv->var_name == JS_ATOM__with_);\n                if (fd != s) {\n                    idx = get_closure_var2(ctx, s, fd,\n                                           FALSE,\n                                           cv->is_arg, idx1,\n                                           cv->var_name, FALSE, FALSE,\n                                           JS_VAR_NORMAL);\n                } else {\n                    idx = idx1;\n                }\n                dbuf_putc(bc, OP_get_var_ref);\n                dbuf_put_u16(bc, idx);\n                var_object_test(ctx, s, var_name, op, bc, &label_done, is_with);\n            }\n        }\n    }\n\n    if (var_idx >= 0) {\n        /* find the corresponding closure variable */\n        if (var_idx & ARGUMENT_VAR_OFFSET) {\n            fd->args[var_idx - ARGUMENT_VAR_OFFSET].is_captured = 1;\n            idx = get_closure_var(ctx, s, fd,\n                                  TRUE, var_idx - ARGUMENT_VAR_OFFSET,\n                                  var_name, FALSE, FALSE, JS_VAR_NORMAL);\n        } else {\n            fd->vars[var_idx].is_captured = 1;\n            idx = get_closure_var(ctx, s, fd,\n                                  FALSE, var_idx,\n                                  var_name,\n                                  fd->vars[var_idx].is_const,\n                                  fd->vars[var_idx].is_lexical,\n                                  fd->vars[var_idx].var_kind);\n        }\n        if (idx >= 0) {\n        has_idx:\n            if ((op == OP_scope_put_var || op == OP_scope_make_ref) &&\n                s->closure_var[idx].is_const) {\n                dbuf_putc(bc, OP_throw_error);\n                dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                dbuf_putc(bc, JS_THROW_VAR_RO);\n                goto done;\n            }\n            switch (op) {\n            case OP_scope_make_ref:\n                if (s->closure_var[idx].var_kind == JS_VAR_FUNCTION_NAME) {\n                    /* Create a dummy object reference for the func_var */\n                    dbuf_putc(bc, OP_object);\n                    dbuf_putc(bc, OP_get_var_ref);\n                    dbuf_put_u16(bc, idx);\n                    dbuf_putc(bc, OP_define_field);\n                    dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                    dbuf_putc(bc, OP_push_atom_value);\n                    dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                } else\n                if (label_done == -1 &&\n                    can_opt_put_ref_value(bc_buf, ls->pos)) {\n                    int get_op;\n                    if (s->closure_var[idx].is_lexical)\n                        get_op = OP_get_var_ref_check;\n                    else\n                        get_op = OP_get_var_ref;\n                    pos_next = optimize_scope_make_ref(ctx, s, bc, bc_buf, ls,\n                                                       pos_next,\n                                                       get_op, idx);\n                } else {\n                    /* Create a dummy object with a named slot that is\n                       a reference to the closure variable */\n                    dbuf_putc(bc, OP_make_var_ref_ref);\n                    dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n                    dbuf_put_u16(bc, idx);\n                }\n                break;\n            case OP_scope_get_ref:\n                /* XXX: should create a dummy object with a named slot that is\n                   a reference to the closure variable */\n                dbuf_putc(bc, OP_undefined);\n                /* fall thru */\n            case OP_scope_get_var_undef:\n            case OP_scope_get_var:\n            case OP_scope_put_var:\n            case OP_scope_put_var_init:\n                is_put = (op == OP_scope_put_var ||\n                          op == OP_scope_put_var_init);\n                if (is_put) {\n                    if (s->closure_var[idx].is_lexical) {\n                        if (op == OP_scope_put_var_init) {\n                            /* 'this' can only be initialized once */\n                            if (var_name == JS_ATOM_this)\n                                dbuf_putc(bc, OP_put_var_ref_check_init);\n                            else\n                                dbuf_putc(bc, OP_put_var_ref);\n                        } else {\n                            dbuf_putc(bc, OP_put_var_ref_check);\n                        }\n                    } else {\n                        dbuf_putc(bc, OP_put_var_ref);\n                    }\n                } else {\n                    if (s->closure_var[idx].is_lexical) {\n                        dbuf_putc(bc, OP_get_var_ref_check);\n                    } else {\n                        dbuf_putc(bc, OP_get_var_ref);\n                    }\n                }\n                dbuf_put_u16(bc, idx);\n                break;\n            case OP_scope_delete_var:\n                dbuf_putc(bc, OP_push_false);\n                break;\n            }\n            goto done;\n        }\n    }\n\n    /* global variable access */\n\n    switch (op) {\n    case OP_scope_make_ref:\n        if (label_done == -1 && can_opt_put_global_ref_value(bc_buf, ls->pos)) {\n            pos_next = optimize_scope_make_global_ref(ctx, s, bc, bc_buf, ls,\n                                                      pos_next, var_name);\n        } else {\n            dbuf_putc(bc, OP_make_var_ref);\n            dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n        }\n        break;\n    case OP_scope_get_ref:\n        /* XXX: should create a dummy object with a named slot that is\n           a reference to the global variable */\n        dbuf_putc(bc, OP_undefined);\n        dbuf_putc(bc, OP_get_var);\n        dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n        break;\n    case OP_scope_get_var_undef:\n    case OP_scope_get_var:\n    case OP_scope_put_var:\n        dbuf_putc(bc, OP_get_var_undef + (op - OP_scope_get_var_undef));\n        dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n        break;\n    case OP_scope_put_var_init:\n        dbuf_putc(bc, OP_put_var_init);\n        dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n        break;\n    case OP_scope_delete_var:\n        dbuf_putc(bc, OP_delete_var);\n        dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n        break;\n    }\ndone:\n    if (label_done >= 0) {\n        dbuf_putc(bc, OP_label);\n        dbuf_put_u32(bc, label_done);\n        s->label_slots[label_done].pos2 = bc->size;\n    }\n    return pos_next;\n}\n\n/* search in all scopes */\nstatic int find_private_class_field_all(JSContext *ctx, JSFunctionDef *fd,\n                                        JSAtom name, int scope_level)\n{\n    int idx;\n\n    idx = fd->scopes[scope_level].first;\n    while (idx >= 0) {\n        if (fd->vars[idx].var_name == name)\n            return idx;\n        idx = fd->vars[idx].scope_next;\n    }\n    return -1;\n}\n\nstatic void get_loc_or_ref(DynBuf *bc, BOOL is_ref, int idx)\n{\n    /* if the field is not initialized, the error is catched when\n       accessing it */\n    if (is_ref) \n        dbuf_putc(bc, OP_get_var_ref);\n    else\n        dbuf_putc(bc, OP_get_loc);\n    dbuf_put_u16(bc, idx);\n}\n\nstatic int resolve_scope_private_field1(JSContext *ctx,\n                                        BOOL *pis_ref, int *pvar_kind,\n                                        JSFunctionDef *s,\n                                        JSAtom var_name, int scope_level)\n{\n    int idx, var_kind;\n    JSFunctionDef *fd;\n    BOOL is_ref;\n    \n    fd = s;\n    is_ref = FALSE;\n    for(;;) {\n        idx = find_private_class_field_all(ctx, fd, var_name, scope_level);\n        if (idx >= 0) {\n            var_kind = fd->vars[idx].var_kind;\n            if (is_ref) {\n                idx = get_closure_var(ctx, s, fd, FALSE, idx, var_name,\n                                      TRUE, TRUE, JS_VAR_NORMAL);\n                if (idx < 0)\n                    return -1;\n            }\n            break;\n        }\n        scope_level = fd->parent_scope_level;\n        if (!fd->parent) {\n            if (fd->is_eval) {\n                /* closure of the eval function (top level) */\n                for (idx = 0; idx < fd->closure_var_count; idx++) {\n                    JSClosureVar *cv = &fd->closure_var[idx];\n                    if (cv->var_name == var_name) {\n                        var_kind = cv->var_kind;\n                        is_ref = TRUE;\n                        if (fd != s) {\n                            idx = get_closure_var2(ctx, s, fd,\n                                                   FALSE,\n                                                   cv->is_arg, idx,\n                                                   cv->var_name, cv->is_const,\n                                                   cv->is_lexical,\n                                                   cv->var_kind);\n                            if (idx < 0)\n                                return -1;\n                        }\n                        goto done;\n                    }\n                }\n            }\n            /* XXX: no line number info */\n            JS_ThrowSyntaxErrorAtom(ctx, \"undefined private field '%s'\",\n                                    var_name);\n            return -1;\n        } else {\n            fd = fd->parent;\n        }\n        is_ref = TRUE;\n    }\n done:\n    *pis_ref = is_ref;\n    *pvar_kind = var_kind;\n    return idx;\n}\n\n/* return 0 if OK or -1 if the private field could not be resolved */\nstatic int resolve_scope_private_field(JSContext *ctx, JSFunctionDef *s,\n                                       JSAtom var_name, int scope_level, int op,\n                                       DynBuf *bc)\n{\n    int idx, var_kind;\n    BOOL is_ref;\n\n    idx = resolve_scope_private_field1(ctx, &is_ref, &var_kind, s,\n                                       var_name, scope_level);\n    if (idx < 0)\n        return -1;\n    assert(var_kind != JS_VAR_NORMAL);\n    switch (op) {\n    case OP_scope_get_private_field:\n    case OP_scope_get_private_field2:\n        switch(var_kind) {\n        case JS_VAR_PRIVATE_FIELD:\n            if (op == OP_scope_get_private_field2)\n                dbuf_putc(bc, OP_dup);\n            get_loc_or_ref(bc, is_ref, idx);\n            dbuf_putc(bc, OP_get_private_field);\n            break;\n        case JS_VAR_PRIVATE_METHOD:\n            get_loc_or_ref(bc, is_ref, idx);\n            dbuf_putc(bc, OP_check_brand);\n            if (op != OP_scope_get_private_field2)\n                dbuf_putc(bc, OP_nip);\n            break;\n        case JS_VAR_PRIVATE_GETTER:\n        case JS_VAR_PRIVATE_GETTER_SETTER:\n            if (op == OP_scope_get_private_field2)\n                dbuf_putc(bc, OP_dup);\n            get_loc_or_ref(bc, is_ref, idx);\n            dbuf_putc(bc, OP_check_brand);\n            dbuf_putc(bc, OP_call_method);\n            dbuf_put_u16(bc, 0);\n            break;\n        case JS_VAR_PRIVATE_SETTER:\n            /* XXX: add clearer error message */\n            dbuf_putc(bc, OP_throw_error);\n            dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n            dbuf_putc(bc, JS_THROW_VAR_RO);\n            break;\n        default:\n            abort();\n        }\n        break;\n    case OP_scope_put_private_field:\n        switch(var_kind) {\n        case JS_VAR_PRIVATE_FIELD:\n            get_loc_or_ref(bc, is_ref, idx);\n            dbuf_putc(bc, OP_put_private_field);\n            break;\n        case JS_VAR_PRIVATE_METHOD:\n        case JS_VAR_PRIVATE_GETTER:\n            /* XXX: add clearer error message */\n            dbuf_putc(bc, OP_throw_error);\n            dbuf_put_u32(bc, JS_DupAtom(ctx, var_name));\n            dbuf_putc(bc, JS_THROW_VAR_RO);\n            break;\n        case JS_VAR_PRIVATE_SETTER:\n        case JS_VAR_PRIVATE_GETTER_SETTER:\n            {\n                JSAtom setter_name = get_private_setter_name(ctx, var_name);\n                if (setter_name == JS_ATOM_NULL)\n                    return -1;\n                idx = resolve_scope_private_field1(ctx, &is_ref,\n                                                   &var_kind, s,\n                                                   setter_name, scope_level);\n                JS_FreeAtom(ctx, setter_name);\n                if (idx < 0)\n                    return -1;\n                assert(var_kind == JS_VAR_PRIVATE_SETTER);\n                get_loc_or_ref(bc, is_ref, idx);\n                dbuf_putc(bc, OP_swap);\n                /* obj func value */\n                dbuf_putc(bc, OP_rot3r);\n                /* value obj func */\n                dbuf_putc(bc, OP_check_brand);\n                dbuf_putc(bc, OP_rot3l);\n                /* obj func value */\n                dbuf_putc(bc, OP_call_method);\n                dbuf_put_u16(bc, 1);\n            }\n            break;\n        default:\n            abort();\n        }\n        break;\n    default:\n        abort();\n    }\n    return 0;\n}\n\nstatic void mark_eval_captured_variables(JSContext *ctx, JSFunctionDef *s,\n                                         int scope_level)\n{\n    int idx;\n    JSVarDef *vd;\n\n    for (idx = s->scopes[scope_level].first; idx >= 0;) {\n        vd = &s->vars[idx];\n        vd->is_captured = 1;\n        idx = vd->scope_next;\n    }\n}\n\n/* XXX: should handle the argument scope generically */\nstatic BOOL is_var_in_arg_scope(const JSVarDef *vd)\n{\n    return (vd->var_name == JS_ATOM_home_object ||\n            vd->var_name == JS_ATOM_this_active_func ||\n            vd->var_name == JS_ATOM_new_target ||\n            vd->var_name == JS_ATOM_this ||\n            vd->var_name == JS_ATOM__arg_var_ ||\n            vd->var_kind == JS_VAR_FUNCTION_NAME);\n}\n\nstatic void add_eval_variables(JSContext *ctx, JSFunctionDef *s)\n{\n    JSFunctionDef *fd;\n    JSVarDef *vd;\n    int i, scope_level, scope_idx;\n    BOOL has_arguments_binding, has_this_binding, is_arg_scope;\n\n    /* in non strict mode, variables are created in the caller's\n       environment object */\n    if (!s->is_eval && !(s->js_mode & JS_MODE_STRICT)) {\n        s->var_object_idx = add_var(ctx, s, JS_ATOM__var_);\n        if (s->has_parameter_expressions) {\n            /* an additional variable object is needed for the\n               argument scope */\n            s->arg_var_object_idx = add_var(ctx, s, JS_ATOM__arg_var_);\n        }\n    }\n\n    /* eval can potentially use 'arguments' so we must define it */\n    has_this_binding = s->has_this_binding;\n    if (has_this_binding) {\n        if (s->this_var_idx < 0)\n            s->this_var_idx = add_var_this(ctx, s);\n        if (s->new_target_var_idx < 0)\n            s->new_target_var_idx = add_var(ctx, s, JS_ATOM_new_target);\n        if (s->is_derived_class_constructor && s->this_active_func_var_idx < 0)\n            s->this_active_func_var_idx = add_var(ctx, s, JS_ATOM_this_active_func);\n        if (s->has_home_object && s->home_object_var_idx < 0)\n            s->home_object_var_idx = add_var(ctx, s, JS_ATOM_home_object);\n    }\n    has_arguments_binding = s->has_arguments_binding;\n    if (has_arguments_binding) {\n        add_arguments_var(ctx, s);\n        /* also add an arguments binding in the argument scope to\n           raise an error if a direct eval in the argument scope tries\n           to redefine it */\n        if (s->has_parameter_expressions && !(s->js_mode & JS_MODE_STRICT))\n            add_arguments_arg(ctx, s);\n    }\n    if (s->is_func_expr && s->func_name != JS_ATOM_NULL)\n        add_func_var(ctx, s, s->func_name);\n\n    /* eval can use all the variables of the enclosing functions, so\n       they must be all put in the closure. The closure variables are\n       ordered by scope. It works only because no closure are created\n       before. */\n    assert(s->is_eval || s->closure_var_count == 0);\n\n    /* XXX: inefficient, but eval performance is less critical */\n    fd = s;\n    for(;;) {\n        scope_level = fd->parent_scope_level;\n        fd = fd->parent;\n        if (!fd)\n            break;\n        /* add 'this' if it was not previously added */\n        if (!has_this_binding && fd->has_this_binding) {\n            if (fd->this_var_idx < 0)\n                fd->this_var_idx = add_var_this(ctx, fd);\n            if (fd->new_target_var_idx < 0)\n                fd->new_target_var_idx = add_var(ctx, fd, JS_ATOM_new_target);\n            if (fd->is_derived_class_constructor && fd->this_active_func_var_idx < 0)\n                fd->this_active_func_var_idx = add_var(ctx, fd, JS_ATOM_this_active_func);\n            if (fd->has_home_object && fd->home_object_var_idx < 0)\n                fd->home_object_var_idx = add_var(ctx, fd, JS_ATOM_home_object);\n            has_this_binding = TRUE;\n        }\n        /* add 'arguments' if it was not previously added */\n        if (!has_arguments_binding && fd->has_arguments_binding) {\n            add_arguments_var(ctx, fd);\n            has_arguments_binding = TRUE;\n        }\n        /* add function name */\n        if (fd->is_func_expr && fd->func_name != JS_ATOM_NULL)\n            add_func_var(ctx, fd, fd->func_name);\n\n        /* add lexical variables */\n        scope_idx = fd->scopes[scope_level].first;\n        while (scope_idx >= 0) {\n            vd = &fd->vars[scope_idx];\n            vd->is_captured = 1;\n            get_closure_var(ctx, s, fd, FALSE, scope_idx,\n                            vd->var_name, vd->is_const, vd->is_lexical, vd->var_kind);\n            scope_idx = vd->scope_next;\n        }\n        is_arg_scope = (scope_idx == ARG_SCOPE_END);\n        if (!is_arg_scope) {\n            /* add unscoped variables */\n            for(i = 0; i < fd->arg_count; i++) {\n                vd = &fd->args[i];\n                if (vd->var_name != JS_ATOM_NULL) {\n                    get_closure_var(ctx, s, fd,\n                                    TRUE, i, vd->var_name, FALSE, FALSE,\n                                    JS_VAR_NORMAL);\n                }\n            }\n            for(i = 0; i < fd->var_count; i++) {\n                vd = &fd->vars[i];\n                /* do not close top level last result */\n                if (vd->scope_level == 0 &&\n                    vd->var_name != JS_ATOM__ret_ &&\n                    vd->var_name != JS_ATOM_NULL) {\n                    get_closure_var(ctx, s, fd,\n                                    FALSE, i, vd->var_name, FALSE, FALSE,\n                                    JS_VAR_NORMAL);\n                }\n            }\n        } else {\n            for(i = 0; i < fd->var_count; i++) {\n                vd = &fd->vars[i];\n                /* do not close top level last result */\n                if (vd->scope_level == 0 && is_var_in_arg_scope(vd)) {\n                    get_closure_var(ctx, s, fd,\n                                    FALSE, i, vd->var_name, FALSE, FALSE,\n                                    JS_VAR_NORMAL);\n                }\n            }\n        }\n        if (fd->is_eval) {\n            int idx;\n            /* add direct eval variables (we are necessarily at the\n               top level) */\n            for (idx = 0; idx < fd->closure_var_count; idx++) {\n                JSClosureVar *cv = &fd->closure_var[idx];\n                get_closure_var2(ctx, s, fd,\n                                 FALSE, cv->is_arg,\n                                 idx, cv->var_name, cv->is_const,\n                                 cv->is_lexical, cv->var_kind);\n            }\n        }\n    }\n}\n\nstatic void set_closure_from_var(JSContext *ctx, JSClosureVar *cv,\n                                 JSVarDef *vd, int var_idx)\n{\n    cv->is_local = TRUE;\n    cv->is_arg = FALSE;\n    cv->is_const = vd->is_const;\n    cv->is_lexical = vd->is_lexical;\n    cv->var_kind = vd->var_kind;\n    cv->var_idx = var_idx;\n    cv->var_name = JS_DupAtom(ctx, vd->var_name);\n}\n\n/* for direct eval compilation: add references to the variables of the\n   calling function */\nstatic __exception int add_closure_variables(JSContext *ctx, JSFunctionDef *s,\n                                             JSFunctionBytecode *b, int scope_idx)\n{\n    int i, count;\n    JSVarDef *vd;\n    BOOL is_arg_scope;\n    \n    count = b->arg_count + b->var_count + b->closure_var_count;\n    s->closure_var = NULL;\n    s->closure_var_count = 0;\n    s->closure_var_size = count;\n    if (count == 0)\n        return 0;\n    s->closure_var = js_malloc(ctx, sizeof(s->closure_var[0]) * count);\n    if (!s->closure_var)\n        return -1;\n    /* Add lexical variables in scope at the point of evaluation */\n    for (i = scope_idx; i >= 0;) {\n        vd = &b->vardefs[b->arg_count + i];\n        if (vd->scope_level > 0) {\n            JSClosureVar *cv = &s->closure_var[s->closure_var_count++];\n            set_closure_from_var(ctx, cv, vd, i);\n        }\n        i = vd->scope_next;\n    }\n    is_arg_scope = (i == ARG_SCOPE_END);\n    if (!is_arg_scope) {\n        /* Add argument variables */\n        for(i = 0; i < b->arg_count; i++) {\n            JSClosureVar *cv = &s->closure_var[s->closure_var_count++];\n            vd = &b->vardefs[i];\n            cv->is_local = TRUE;\n            cv->is_arg = TRUE;\n            cv->is_const = FALSE;\n            cv->is_lexical = FALSE;\n            cv->var_kind = JS_VAR_NORMAL;\n            cv->var_idx = i;\n            cv->var_name = JS_DupAtom(ctx, vd->var_name);\n        }\n        /* Add local non lexical variables */\n        for(i = 0; i < b->var_count; i++) {\n            vd = &b->vardefs[b->arg_count + i];\n            if (vd->scope_level == 0 && vd->var_name != JS_ATOM__ret_) {\n                JSClosureVar *cv = &s->closure_var[s->closure_var_count++];\n                set_closure_from_var(ctx, cv, vd, i);\n            }\n        }\n    } else {\n        /* only add pseudo variables */\n        for(i = 0; i < b->var_count; i++) {\n            vd = &b->vardefs[b->arg_count + i];\n            if (vd->scope_level == 0 && is_var_in_arg_scope(vd)) {\n                JSClosureVar *cv = &s->closure_var[s->closure_var_count++];\n                set_closure_from_var(ctx, cv, vd, i);\n            }\n        }\n    }\n    for(i = 0; i < b->closure_var_count; i++) {\n        JSClosureVar *cv0 = &b->closure_var[i];\n        JSClosureVar *cv = &s->closure_var[s->closure_var_count++];\n        cv->is_local = FALSE;\n        cv->is_arg = cv0->is_arg;\n        cv->is_const = cv0->is_const;\n        cv->is_lexical = cv0->is_lexical;\n        cv->var_kind = cv0->var_kind;\n        cv->var_idx = i;\n        cv->var_name = JS_DupAtom(ctx, cv0->var_name);\n    }\n    return 0;\n}\n\ntypedef struct CodeContext {\n    const uint8_t *bc_buf; /* code buffer */\n    int bc_len;   /* length of the code buffer */\n    int pos;      /* position past the matched code pattern */\n    int line_num; /* last visited OP_line_num parameter or -1 */\n    int op;\n    int idx;\n    int label;\n    int val;\n    JSAtom atom;\n} CodeContext;\n\n#define M2(op1, op2)            ((op1) | ((op2) << 8))\n#define M3(op1, op2, op3)       ((op1) | ((op2) << 8) | ((op3) << 16))\n#define M4(op1, op2, op3, op4)  ((op1) | ((op2) << 8) | ((op3) << 16) | ((op4) << 24))\n\nstatic BOOL code_match(CodeContext *s, int pos, ...)\n{\n    const uint8_t *tab = s->bc_buf;\n    int op, len, op1, line_num, pos_next;\n    va_list ap;\n    BOOL ret = FALSE;\n\n    line_num = -1;\n    va_start(ap, pos);\n\n    for(;;) {\n        op1 = va_arg(ap, int);\n        if (op1 == -1) {\n            s->pos = pos;\n            s->line_num = line_num;\n            ret = TRUE;\n            break;\n        }\n        for (;;) {\n            if (pos >= s->bc_len)\n                goto done;\n            op = tab[pos];\n            len = opcode_info[op].size;\n            pos_next = pos + len;\n            if (pos_next > s->bc_len)\n                goto done;\n            if (op == OP_line_num) {\n                line_num = get_u32(tab + pos + 1);\n                pos = pos_next;\n            } else {\n                break;\n            }\n        }\n        if (op != op1) {\n            if (op1 == (uint8_t)op1 || !op)\n                break;\n            if (op != (uint8_t)op1\n            &&  op != (uint8_t)(op1 >> 8)\n            &&  op != (uint8_t)(op1 >> 16)\n            &&  op != (uint8_t)(op1 >> 24)) {\n                break;\n            }\n            s->op = op;\n        }\n\n        pos++;\n        switch(opcode_info[op].fmt) {\n        case OP_FMT_loc8:\n        case OP_FMT_u8:\n            {\n                int idx = tab[pos];\n                int arg = va_arg(ap, int);\n                if (arg == -1) {\n                    s->idx = idx;\n                } else {\n                    if (arg != idx)\n                        goto done;\n                }\n                break;\n            }\n        case OP_FMT_u16:\n        case OP_FMT_npop:\n        case OP_FMT_loc:\n        case OP_FMT_arg:\n        case OP_FMT_var_ref:\n            {\n                int idx = get_u16(tab + pos);\n                int arg = va_arg(ap, int);\n                if (arg == -1) {\n                    s->idx = idx;\n                } else {\n                    if (arg != idx)\n                        goto done;\n                }\n                break;\n            }\n        case OP_FMT_i32:\n        case OP_FMT_u32:\n        case OP_FMT_label:\n        case OP_FMT_const:\n            {\n                s->label = get_u32(tab + pos);\n                break;\n            }\n        case OP_FMT_label_u16:\n            {\n                s->label = get_u32(tab + pos);\n                s->val = get_u16(tab + pos + 4);\n                break;\n            }\n        case OP_FMT_atom:\n            {\n                s->atom = get_u32(tab + pos);\n                break;\n            }\n        case OP_FMT_atom_u8:\n            {\n                s->atom = get_u32(tab + pos);\n                s->val = get_u8(tab + pos + 4);\n                break;\n            }\n        case OP_FMT_atom_u16:\n            {\n                s->atom = get_u32(tab + pos);\n                s->val = get_u16(tab + pos + 4);\n                break;\n            }\n        case OP_FMT_atom_label_u8:\n            {\n                s->atom = get_u32(tab + pos);\n                s->label = get_u32(tab + pos + 4);\n                s->val = get_u8(tab + pos + 8);\n                break;\n            }\n        default:\n            break;\n        }\n        pos = pos_next;\n    }\n done:\n    va_end(ap);\n    return ret;\n}\n\nstatic void instantiate_hoisted_definitions(JSContext *ctx, JSFunctionDef *s, DynBuf *bc)\n{\n    int i, idx, label_next = -1;\n\n    /* add the hoisted functions in arguments and local variables */\n    for(i = 0; i < s->arg_count; i++) {\n        JSVarDef *vd = &s->args[i];\n        if (vd->func_pool_idx >= 0) {\n            dbuf_putc(bc, OP_fclosure);\n            dbuf_put_u32(bc, vd->func_pool_idx);\n            dbuf_putc(bc, OP_put_arg);\n            dbuf_put_u16(bc, i);\n        }\n    }\n    for(i = 0; i < s->var_count; i++) {\n        JSVarDef *vd = &s->vars[i];\n        if (vd->scope_level == 0 && vd->func_pool_idx >= 0) {\n            dbuf_putc(bc, OP_fclosure);\n            dbuf_put_u32(bc, vd->func_pool_idx);\n            dbuf_putc(bc, OP_put_loc);\n            dbuf_put_u16(bc, i);\n        }\n    }\n\n    /* the module global variables must be initialized before\n       evaluating the module so that the exported functions are\n       visible if there are cyclic module references */\n    if (s->module) {\n        label_next = new_label_fd(s, -1);\n        \n        /* if 'this' is true, initialize the global variables and return */\n        dbuf_putc(bc, OP_push_this);\n        dbuf_putc(bc, OP_if_false);\n        dbuf_put_u32(bc, label_next);\n        update_label(s, label_next, 1);\n        s->jump_size++;\n    }\n    \n    /* add the global variables (only happens if s->is_global_var is\n       true) */\n    for(i = 0; i < s->global_var_count; i++) {\n        JSGlobalVar *hf = &s->global_vars[i];\n        int has_closure = 0;\n        BOOL force_init = hf->force_init;\n        /* we are in an eval, so the closure contains all the\n           enclosing variables */\n        /* If the outer function has a variable environment,\n           create a property for the variable there */\n        for(idx = 0; idx < s->closure_var_count; idx++) {\n            JSClosureVar *cv = &s->closure_var[idx];\n            if (cv->var_name == hf->var_name) {\n                has_closure = 2;\n                force_init = FALSE;\n                break;\n            }\n            if (cv->var_name == JS_ATOM__var_ ||\n                cv->var_name == JS_ATOM__arg_var_) {\n                dbuf_putc(bc, OP_get_var_ref);\n                dbuf_put_u16(bc, idx);\n                has_closure = 1;\n                force_init = TRUE;\n                break;\n            }\n        }\n        if (!has_closure) {\n            int flags;\n            \n            flags = 0;\n            if (s->eval_type != JS_EVAL_TYPE_GLOBAL)\n                flags |= JS_PROP_CONFIGURABLE;\n            if (hf->cpool_idx >= 0 && !hf->is_lexical) {\n                /* global function definitions need a specific handling */\n                dbuf_putc(bc, OP_fclosure);\n                dbuf_put_u32(bc, hf->cpool_idx);\n                \n                dbuf_putc(bc, OP_define_func);\n                dbuf_put_u32(bc, JS_DupAtom(ctx, hf->var_name));\n                dbuf_putc(bc, flags);\n                \n                goto done_global_var;\n            } else {\n                if (hf->is_lexical) {\n                    flags |= DEFINE_GLOBAL_LEX_VAR;\n                    if (!hf->is_const)\n                        flags |= JS_PROP_WRITABLE;\n                }\n                dbuf_putc(bc, OP_define_var);\n                dbuf_put_u32(bc, JS_DupAtom(ctx, hf->var_name));\n                dbuf_putc(bc, flags);\n            }\n        }\n        if (hf->cpool_idx >= 0 || force_init) {\n            if (hf->cpool_idx >= 0) {\n                dbuf_putc(bc, OP_fclosure);\n                dbuf_put_u32(bc, hf->cpool_idx);\n                if (hf->var_name == JS_ATOM__default_) {\n                    /* set default export function name */\n                    dbuf_putc(bc, OP_set_name);\n                    dbuf_put_u32(bc, JS_DupAtom(ctx, JS_ATOM_default));\n                }\n            } else {\n                dbuf_putc(bc, OP_undefined);\n            }\n            if (has_closure == 2) {\n                dbuf_putc(bc, OP_put_var_ref);\n                dbuf_put_u16(bc, idx);\n            } else if (has_closure == 1) {\n                dbuf_putc(bc, OP_define_field);\n                dbuf_put_u32(bc, JS_DupAtom(ctx, hf->var_name));\n                dbuf_putc(bc, OP_drop);\n            } else {\n                /* XXX: Check if variable is writable and enumerable */\n                dbuf_putc(bc, OP_put_var);\n                dbuf_put_u32(bc, JS_DupAtom(ctx, hf->var_name));\n            }\n        }\n    done_global_var:\n        JS_FreeAtom(ctx, hf->var_name);\n    }\n\n    if (s->module) {\n        dbuf_putc(bc, OP_return_undef);\n        \n        dbuf_putc(bc, OP_label);\n        dbuf_put_u32(bc, label_next);\n        s->label_slots[label_next].pos2 = bc->size;\n    }\n\n    js_free(ctx, s->global_vars);\n    s->global_vars = NULL;\n    s->global_var_count = 0;\n    s->global_var_size = 0;\n}\n\nstatic int skip_dead_code(JSFunctionDef *s, const uint8_t *bc_buf, int bc_len,\n                          int pos, int *linep)\n{\n    int op, len, label;\n\n    for (; pos < bc_len; pos += len) {\n        op = bc_buf[pos];\n        len = opcode_info[op].size;\n        if (op == OP_line_num) {\n            *linep = get_u32(bc_buf + pos + 1);\n        } else\n        if (op == OP_label) {\n            label = get_u32(bc_buf + pos + 1);\n            if (update_label(s, label, 0) > 0)\n                break;\n#if 0\n            if (s->label_slots[label].first_reloc) {\n                printf(\"line %d: unreferenced label %d:%d has relocations\\n\",\n                       *linep, label, s->label_slots[label].pos2);\n            }\n#endif\n            assert(s->label_slots[label].first_reloc == NULL);\n        } else {\n            /* XXX: output a warning for unreachable code? */\n            JSAtom atom;\n            switch(opcode_info[op].fmt) {\n            case OP_FMT_label:\n            case OP_FMT_label_u16:\n                label = get_u32(bc_buf + pos + 1);\n                update_label(s, label, -1);\n                break;\n            case OP_FMT_atom_label_u8:\n            case OP_FMT_atom_label_u16:\n                label = get_u32(bc_buf + pos + 5);\n                update_label(s, label, -1);\n                /* fall thru */\n            case OP_FMT_atom:\n            case OP_FMT_atom_u8:\n            case OP_FMT_atom_u16:\n                atom = get_u32(bc_buf + pos + 1);\n                JS_FreeAtom(s->ctx, atom);\n                break;\n            default:\n                break;\n            }\n        }\n    }\n    return pos;\n}\n\nstatic int get_label_pos(JSFunctionDef *s, int label)\n{\n    int i, pos;\n    for (i = 0; i < 20; i++) {\n        pos = s->label_slots[label].pos;\n        for (;;) {\n            switch (s->byte_code.buf[pos]) {\n            case OP_line_num:\n            case OP_label:\n                pos += 5;\n                continue;\n            case OP_goto:\n                label = get_u32(s->byte_code.buf + pos + 1);\n                break;\n            default:\n                return pos;\n            }\n            break;\n        }\n    }\n    return pos;\n}\n\n/* convert global variable accesses to local variables or closure\n   variables when necessary */\nstatic __exception int resolve_variables(JSContext *ctx, JSFunctionDef *s)\n{\n    int pos, pos_next, bc_len, op, len, i, idx, line_num;\n    uint8_t *bc_buf;\n    JSAtom var_name;\n    DynBuf bc_out;\n    CodeContext cc;\n    int scope;\n\n    cc.bc_buf = bc_buf = s->byte_code.buf;\n    cc.bc_len = bc_len = s->byte_code.size;\n    js_dbuf_init(ctx, &bc_out);\n\n    /* first pass for runtime checks (must be done before the\n       variables are created) */\n    for(i = 0; i < s->global_var_count; i++) {\n        JSGlobalVar *hf = &s->global_vars[i];\n        int flags;\n        \n        /* check if global variable (XXX: simplify) */\n        for(idx = 0; idx < s->closure_var_count; idx++) {\n            JSClosureVar *cv = &s->closure_var[idx];\n            if (cv->var_name == hf->var_name) {\n                if (s->eval_type == JS_EVAL_TYPE_DIRECT &&\n                    cv->is_lexical) {\n                    /* Check if a lexical variable is\n                       redefined as 'var'. XXX: Could abort\n                       compilation here, but for consistency\n                       with the other checks, we delay the\n                       error generation. */\n                    dbuf_putc(&bc_out, OP_throw_error);\n                    dbuf_put_u32(&bc_out, JS_DupAtom(ctx, hf->var_name));\n                    dbuf_putc(&bc_out, JS_THROW_VAR_REDECL);\n                }\n                goto next;\n            }\n            if (cv->var_name == JS_ATOM__var_ ||\n                cv->var_name == JS_ATOM__arg_var_)\n                goto next;\n        }\n        \n        dbuf_putc(&bc_out, OP_check_define_var);\n        dbuf_put_u32(&bc_out, JS_DupAtom(ctx, hf->var_name));\n        flags = 0;\n        if (hf->is_lexical)\n            flags |= DEFINE_GLOBAL_LEX_VAR;\n        if (hf->cpool_idx >= 0)\n            flags |= DEFINE_GLOBAL_FUNC_VAR;\n        dbuf_putc(&bc_out, flags);\n    next: ;\n    }\n\n    line_num = 0; /* avoid warning */\n    for (pos = 0; pos < bc_len; pos = pos_next) {\n        op = bc_buf[pos];\n        len = opcode_info[op].size;\n        pos_next = pos + len;\n        switch(op) {\n        case OP_line_num:\n            line_num = get_u32(bc_buf + pos + 1);\n            s->line_number_size++;\n            goto no_change;\n\n        case OP_eval: /* convert scope index to adjusted variable index */\n            {\n                int call_argc = get_u16(bc_buf + pos + 1);\n                scope = get_u16(bc_buf + pos + 1 + 2);\n                mark_eval_captured_variables(ctx, s, scope);\n                dbuf_putc(&bc_out, op);\n                dbuf_put_u16(&bc_out, call_argc);\n                dbuf_put_u16(&bc_out, s->scopes[scope].first + 1);\n            }\n            break;\n        case OP_apply_eval: /* convert scope index to adjusted variable index */\n            scope = get_u16(bc_buf + pos + 1);\n            mark_eval_captured_variables(ctx, s, scope);\n            dbuf_putc(&bc_out, op);\n            dbuf_put_u16(&bc_out, s->scopes[scope].first + 1);\n            break;\n        case OP_scope_get_var_undef:\n        case OP_scope_get_var:\n        case OP_scope_put_var:\n        case OP_scope_delete_var:\n        case OP_scope_get_ref:\n        case OP_scope_put_var_init:\n            var_name = get_u32(bc_buf + pos + 1);\n            scope = get_u16(bc_buf + pos + 5);\n            pos_next = resolve_scope_var(ctx, s, var_name, scope, op, &bc_out,\n                                         NULL, NULL, pos_next);\n            JS_FreeAtom(ctx, var_name);\n            break;\n        case OP_scope_make_ref:\n            {\n                int label;\n                LabelSlot *ls;\n                var_name = get_u32(bc_buf + pos + 1);\n                label = get_u32(bc_buf + pos + 5);\n                scope = get_u16(bc_buf + pos + 9);\n                ls = &s->label_slots[label];\n                ls->ref_count--;  /* always remove label reference */\n                pos_next = resolve_scope_var(ctx, s, var_name, scope, op, &bc_out,\n                                             bc_buf, ls, pos_next);\n                JS_FreeAtom(ctx, var_name);\n            }\n            break;\n        case OP_scope_get_private_field:\n        case OP_scope_get_private_field2:\n        case OP_scope_put_private_field:\n            {\n                int ret;\n                var_name = get_u32(bc_buf + pos + 1);\n                scope = get_u16(bc_buf + pos + 5);\n                ret = resolve_scope_private_field(ctx, s, var_name, scope, op, &bc_out);\n                if (ret < 0)\n                    goto fail;\n                JS_FreeAtom(ctx, var_name);\n            }\n            break;\n        case OP_gosub:\n            s->jump_size++;\n            if (OPTIMIZE) {\n                /* remove calls to empty finalizers  */\n                int label;\n                LabelSlot *ls;\n\n                label = get_u32(bc_buf + pos + 1);\n                assert(label >= 0 && label < s->label_count);\n                ls = &s->label_slots[label];\n                if (code_match(&cc, ls->pos, OP_ret, -1)) {\n                    ls->ref_count--;\n                    break;\n                }\n            }\n            goto no_change;\n        case OP_drop:\n            if (0) {\n                /* remove drops before return_undef */\n                /* do not perform this optimization in pass2 because\n                   it breaks patterns recognised in resolve_labels */\n                int pos1 = pos_next;\n                int line1 = line_num;\n                while (code_match(&cc, pos1, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line1 = cc.line_num;\n                    pos1 = cc.pos;\n                }\n                if (code_match(&cc, pos1, OP_return_undef, -1)) {\n                    pos_next = pos1;\n                    if (line1 != -1 && line1 != line_num) {\n                        line_num = line1;\n                        s->line_number_size++;\n                        dbuf_putc(&bc_out, OP_line_num);\n                        dbuf_put_u32(&bc_out, line_num);\n                    }\n                    break;\n                }\n            }\n            goto no_change;\n        case OP_insert3:\n            if (OPTIMIZE) {\n                /* Transformation: insert3 put_array_el|put_ref_value drop -> put_array_el|put_ref_value */\n                if (code_match(&cc, pos_next, M2(OP_put_array_el, OP_put_ref_value), OP_drop, -1)) {\n                    dbuf_putc(&bc_out, cc.op);\n                    pos_next = cc.pos;\n                    if (cc.line_num != -1 && cc.line_num != line_num) {\n                        line_num = cc.line_num;\n                        s->line_number_size++;\n                        dbuf_putc(&bc_out, OP_line_num);\n                        dbuf_put_u32(&bc_out, line_num);\n                    }\n                    break;\n                }\n            }\n            goto no_change;\n\n        case OP_goto:\n            s->jump_size++;\n            /* fall thru */\n        case OP_tail_call:\n        case OP_tail_call_method:\n        case OP_return:\n        case OP_return_undef:\n        case OP_throw:\n        case OP_throw_error:\n        case OP_ret:\n            if (OPTIMIZE) {\n                /* remove dead code */\n                int line = -1;\n                dbuf_put(&bc_out, bc_buf + pos, len);\n                pos = skip_dead_code(s, bc_buf, bc_len, pos + len, &line);\n                pos_next = pos;\n                if (pos < bc_len && line >= 0 && line_num != line) {\n                    line_num = line;\n                    s->line_number_size++;\n                    dbuf_putc(&bc_out, OP_line_num);\n                    dbuf_put_u32(&bc_out, line_num);\n                }\n                break;\n            }\n            goto no_change;\n\n        case OP_label:\n            {\n                int label;\n                LabelSlot *ls;\n\n                label = get_u32(bc_buf + pos + 1);\n                assert(label >= 0 && label < s->label_count);\n                ls = &s->label_slots[label];\n                ls->pos2 = bc_out.size + opcode_info[op].size;\n            }\n            goto no_change;\n\n        case OP_enter_scope:\n            {\n                int scope_idx, scope = get_u16(bc_buf + pos + 1);\n\n                if (scope == s->body_scope) {\n                    instantiate_hoisted_definitions(ctx, s, &bc_out);\n                }\n\n                for(scope_idx = s->scopes[scope].first; scope_idx >= 0;) {\n                    JSVarDef *vd = &s->vars[scope_idx];\n                    if (vd->scope_level == scope) {\n                        if (scope_idx != s->arguments_arg_idx) {\n                            if (vd->var_kind == JS_VAR_FUNCTION_DECL ||\n                                vd->var_kind == JS_VAR_NEW_FUNCTION_DECL) {\n                                /* Initialize lexical variable upon entering scope */\n                                dbuf_putc(&bc_out, OP_fclosure);\n                                dbuf_put_u32(&bc_out, vd->func_pool_idx);\n                                dbuf_putc(&bc_out, OP_put_loc);\n                                dbuf_put_u16(&bc_out, scope_idx);\n                            } else {\n                                /* XXX: should check if variable can be used\n                                   before initialization */\n                                dbuf_putc(&bc_out, OP_set_loc_uninitialized);\n                                dbuf_put_u16(&bc_out, scope_idx);\n                            }\n                        }\n                        scope_idx = vd->scope_next;\n                    } else {\n                        break;\n                    }\n                }\n            }\n            break;\n\n        case OP_leave_scope:\n            {\n                int scope_idx, scope = get_u16(bc_buf + pos + 1);\n\n                for(scope_idx = s->scopes[scope].first; scope_idx >= 0;) {\n                    JSVarDef *vd = &s->vars[scope_idx];\n                    if (vd->scope_level == scope) {\n                        if (vd->is_captured) {\n                            dbuf_putc(&bc_out, OP_close_loc);\n                            dbuf_put_u16(&bc_out, scope_idx);\n                        }\n                        scope_idx = vd->scope_next;\n                    } else {\n                        break;\n                    }\n                }\n            }\n            break;\n\n        case OP_set_name:\n            {\n                /* remove dummy set_name opcodes */\n                JSAtom name = get_u32(bc_buf + pos + 1);\n                if (name == JS_ATOM_NULL)\n                    break;\n            }\n            goto no_change;\n\n        case OP_if_false:\n        case OP_if_true:\n        case OP_catch:\n            s->jump_size++;\n            goto no_change;\n\n        case OP_dup:\n            if (OPTIMIZE) {\n                /* Transformation: dup if_false(l1) drop, l1: if_false(l2) -> if_false(l2) */\n                /* Transformation: dup if_true(l1) drop, l1: if_true(l2) -> if_true(l2) */\n                if (code_match(&cc, pos_next, M2(OP_if_false, OP_if_true), OP_drop, -1)) {\n                    int lab0, lab1, op1, pos1, line1, pos2;\n                    lab0 = lab1 = cc.label;\n                    assert(lab1 >= 0 && lab1 < s->label_count);\n                    op1 = cc.op;\n                    pos1 = cc.pos;\n                    line1 = cc.line_num;\n                    while (code_match(&cc, (pos2 = get_label_pos(s, lab1)), OP_dup, op1, OP_drop, -1)) {\n                        lab1 = cc.label;\n                    }\n                    if (code_match(&cc, pos2, op1, -1)) {\n                        s->jump_size++;\n                        update_label(s, lab0, -1);\n                        update_label(s, cc.label, +1);\n                        dbuf_putc(&bc_out, op1);\n                        dbuf_put_u32(&bc_out, cc.label);\n                        pos_next = pos1;\n                        if (line1 != -1 && line1 != line_num) {\n                            line_num = line1;\n                            s->line_number_size++;\n                            dbuf_putc(&bc_out, OP_line_num);\n                            dbuf_put_u32(&bc_out, line_num);\n                        }\n                        break;\n                    }\n                }\n            }\n            goto no_change;\n\n        case OP_nop:\n            /* remove erased code */\n            break;\n        case OP_set_class_name:\n            /* only used during parsing */\n            break;\n            \n        default:\n        no_change:\n            dbuf_put(&bc_out, bc_buf + pos, len);\n            break;\n        }\n    }\n\n    /* set the new byte code */\n    dbuf_free(&s->byte_code);\n    s->byte_code = bc_out;\n    if (dbuf_error(&s->byte_code)) {\n        JS_ThrowOutOfMemory(ctx);\n        return -1;\n    }\n    return 0;\n fail:\n    /* continue the copy to keep the atom refcounts consistent */\n    /* XXX: find a better solution ? */\n    for (; pos < bc_len; pos = pos_next) {\n        op = bc_buf[pos];\n        len = opcode_info[op].size;\n        pos_next = pos + len;\n        dbuf_put(&bc_out, bc_buf + pos, len);\n    }\n    dbuf_free(&s->byte_code);\n    s->byte_code = bc_out;\n    return -1;\n}\n\n/* the pc2line table gives a line number for each PC value */\nstatic void add_pc2line_info(JSFunctionDef *s, uint32_t pc, int line_num)\n{\n    if (s->line_number_slots != NULL\n    &&  s->line_number_count < s->line_number_size\n    &&  pc >= s->line_number_last_pc\n    &&  line_num != s->line_number_last) {\n        s->line_number_slots[s->line_number_count].pc = pc;\n        s->line_number_slots[s->line_number_count].line_num = line_num;\n        s->line_number_count++;\n        s->line_number_last_pc = pc;\n        s->line_number_last = line_num;\n    }\n}\n\nstatic void compute_pc2line_info(JSFunctionDef *s)\n{\n    if (!(s->js_mode & JS_MODE_STRIP) && s->line_number_slots) {\n        int last_line_num = s->line_num;\n        uint32_t last_pc = 0;\n        int i;\n\n        js_dbuf_init(s->ctx, &s->pc2line);\n        for (i = 0; i < s->line_number_count; i++) {\n            uint32_t pc = s->line_number_slots[i].pc;\n            int line_num = s->line_number_slots[i].line_num;\n            int diff_pc, diff_line;\n\n            if (line_num < 0)\n                continue;\n\n            diff_pc = pc - last_pc;\n            diff_line = line_num - last_line_num;\n            if (diff_line == 0 || diff_pc < 0)\n                continue;\n\n            if (diff_line >= PC2LINE_BASE &&\n                diff_line < PC2LINE_BASE + PC2LINE_RANGE &&\n                diff_pc <= PC2LINE_DIFF_PC_MAX) {\n                dbuf_putc(&s->pc2line, (diff_line - PC2LINE_BASE) +\n                          diff_pc * PC2LINE_RANGE + PC2LINE_OP_FIRST);\n            } else {\n                /* longer encoding */\n                dbuf_putc(&s->pc2line, 0);\n                dbuf_put_leb128(&s->pc2line, diff_pc);\n                dbuf_put_sleb128(&s->pc2line, diff_line);\n            }\n            last_pc = pc;\n            last_line_num = line_num;\n        }\n    }\n}\n\nstatic RelocEntry *add_reloc(JSContext *ctx, LabelSlot *ls, uint32_t addr, int size)\n{\n    RelocEntry *re;\n    re = js_malloc(ctx, sizeof(*re));\n    if (!re)\n        return NULL;\n    re->addr = addr;\n    re->size = size;\n    re->next = ls->first_reloc;\n    ls->first_reloc = re;\n    return re;\n}\n\nstatic BOOL code_has_label(CodeContext *s, int pos, int label)\n{\n    while (pos < s->bc_len) {\n        int op = s->bc_buf[pos];\n        if (op == OP_line_num) {\n            pos += 5;\n            continue;\n        }\n        if (op == OP_label) {\n            int lab = get_u32(s->bc_buf + pos + 1);\n            if (lab == label)\n                return TRUE;\n            pos += 5;\n            continue;\n        }\n        if (op == OP_goto) {\n            int lab = get_u32(s->bc_buf + pos + 1);\n            if (lab == label)\n                return TRUE;\n        }\n        break;\n    }\n    return FALSE;\n}\n\n/* return the target label, following the OP_goto jumps\n   the first opcode at destination is stored in *pop\n */\nstatic int find_jump_target(JSFunctionDef *s, int label, int *pop, int *pline)\n{\n    int i, pos, op;\n\n    update_label(s, label, -1);\n    for (i = 0; i < 10; i++) {\n        assert(label >= 0 && label < s->label_count);\n        pos = s->label_slots[label].pos2;\n        for (;;) {\n            switch(op = s->byte_code.buf[pos]) {\n            case OP_line_num:\n                if (pline)\n                    *pline = get_u32(s->byte_code.buf + pos + 1);\n                /* fall thru */\n            case OP_label:\n                pos += opcode_info[op].size;\n                continue;\n            case OP_goto:\n                label = get_u32(s->byte_code.buf + pos + 1);\n                break;\n            case OP_drop:\n                /* ignore drop opcodes if followed by OP_return_undef */\n                while (s->byte_code.buf[++pos] == OP_drop)\n                    continue;\n                if (s->byte_code.buf[pos] == OP_return_undef)\n                    op = OP_return_undef;\n                /* fall thru */\n            default:\n                goto done;\n            }\n            break;\n        }\n    }\n    /* cycle detected, could issue a warning */\n done:\n    *pop = op;\n    update_label(s, label, +1);\n    return label;\n}\n\nstatic void push_short_int(DynBuf *bc_out, int val)\n{\n#if SHORT_OPCODES\n    if (val >= -1 && val <= 7) {\n        dbuf_putc(bc_out, OP_push_0 + val);\n        return;\n    }\n    if (val == (int8_t)val) {\n        dbuf_putc(bc_out, OP_push_i8);\n        dbuf_putc(bc_out, val);\n        return;\n    }\n    if (val == (int16_t)val) {\n        dbuf_putc(bc_out, OP_push_i16);\n        dbuf_put_u16(bc_out, val);\n        return;\n    }\n#endif\n    dbuf_putc(bc_out, OP_push_i32);\n    dbuf_put_u32(bc_out, val);\n}\n\nstatic void put_short_code(DynBuf *bc_out, int op, int idx)\n{\n#if SHORT_OPCODES\n    if (idx < 4) {\n        switch (op) {\n        case OP_get_loc:\n            dbuf_putc(bc_out, OP_get_loc0 + idx);\n            return;\n        case OP_put_loc:\n            dbuf_putc(bc_out, OP_put_loc0 + idx);\n            return;\n        case OP_set_loc:\n            dbuf_putc(bc_out, OP_set_loc0 + idx);\n            return;\n        case OP_get_arg:\n            dbuf_putc(bc_out, OP_get_arg0 + idx);\n            return;\n        case OP_put_arg:\n            dbuf_putc(bc_out, OP_put_arg0 + idx);\n            return;\n        case OP_set_arg:\n            dbuf_putc(bc_out, OP_set_arg0 + idx);\n            return;\n        case OP_get_var_ref:\n            dbuf_putc(bc_out, OP_get_var_ref0 + idx);\n            return;\n        case OP_put_var_ref:\n            dbuf_putc(bc_out, OP_put_var_ref0 + idx);\n            return;\n        case OP_set_var_ref:\n            dbuf_putc(bc_out, OP_set_var_ref0 + idx);\n            return;\n        case OP_call:\n            dbuf_putc(bc_out, OP_call0 + idx);\n            return;\n        }\n    }\n    if (idx < 256) {\n        switch (op) {\n        case OP_get_loc:\n            dbuf_putc(bc_out, OP_get_loc8);\n            dbuf_putc(bc_out, idx);\n            return;\n        case OP_put_loc:\n            dbuf_putc(bc_out, OP_put_loc8);\n            dbuf_putc(bc_out, idx);\n            return;\n        case OP_set_loc:\n            dbuf_putc(bc_out, OP_set_loc8);\n            dbuf_putc(bc_out, idx);\n            return;\n        }\n    }\n#endif\n    dbuf_putc(bc_out, op);\n    dbuf_put_u16(bc_out, idx);\n}\n\n/* peephole optimizations and resolve goto/labels */\nstatic __exception int resolve_labels(JSContext *ctx, JSFunctionDef *s)\n{\n    int pos, pos_next, bc_len, op, op1, len, i, line_num;\n    const uint8_t *bc_buf;\n    DynBuf bc_out;\n    LabelSlot *label_slots, *ls;\n    RelocEntry *re, *re_next;\n    CodeContext cc;\n    int label;\n#if SHORT_OPCODES\n    JumpSlot *jp;\n#endif\n\n    label_slots = s->label_slots;\n\n    line_num = s->line_num;\n\n    cc.bc_buf = bc_buf = s->byte_code.buf;\n    cc.bc_len = bc_len = s->byte_code.size;\n    js_dbuf_init(ctx, &bc_out);\n\n#if SHORT_OPCODES\n    if (s->jump_size) {\n        s->jump_slots = js_mallocz(s->ctx, sizeof(*s->jump_slots) * s->jump_size);\n        if (s->jump_slots == NULL)\n            return -1;\n    }\n#endif\n    /* XXX: Should skip this phase if not generating SHORT_OPCODES */\n    if (s->line_number_size && !(s->js_mode & JS_MODE_STRIP)) {\n        s->line_number_slots = js_mallocz(s->ctx, sizeof(*s->line_number_slots) * s->line_number_size);\n        if (s->line_number_slots == NULL)\n            return -1;\n        s->line_number_last = s->line_num;\n        s->line_number_last_pc = 0;\n    }\n\n    /* initialize the 'home_object' variable if needed */\n    if (s->home_object_var_idx >= 0) {\n        dbuf_putc(&bc_out, OP_special_object);\n        dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_HOME_OBJECT);\n        put_short_code(&bc_out, OP_put_loc, s->home_object_var_idx);\n    }\n    /* initialize the 'this.active_func' variable if needed */\n    if (s->this_active_func_var_idx >= 0) {\n        dbuf_putc(&bc_out, OP_special_object);\n        dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_THIS_FUNC);\n        put_short_code(&bc_out, OP_put_loc, s->this_active_func_var_idx);\n    }\n    /* initialize the 'new.target' variable if needed */\n    if (s->new_target_var_idx >= 0) {\n        dbuf_putc(&bc_out, OP_special_object);\n        dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_NEW_TARGET);\n        put_short_code(&bc_out, OP_put_loc, s->new_target_var_idx);\n    }\n    /* initialize the 'this' variable if needed. In a derived class\n       constructor, this is initially uninitialized. */\n    if (s->this_var_idx >= 0) {\n        if (s->is_derived_class_constructor) {\n            dbuf_putc(&bc_out, OP_set_loc_uninitialized);\n            dbuf_put_u16(&bc_out, s->this_var_idx);\n        } else {\n            dbuf_putc(&bc_out, OP_push_this);\n            put_short_code(&bc_out, OP_put_loc, s->this_var_idx);\n        }\n    }\n    /* initialize the 'arguments' variable if needed */\n    if (s->arguments_var_idx >= 0) {\n        if ((s->js_mode & JS_MODE_STRICT) || !s->has_simple_parameter_list) {\n            dbuf_putc(&bc_out, OP_special_object);\n            dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_ARGUMENTS);\n        } else {\n            dbuf_putc(&bc_out, OP_special_object);\n            dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_MAPPED_ARGUMENTS);\n        }\n        if (s->arguments_arg_idx >= 0)\n            put_short_code(&bc_out, OP_set_loc, s->arguments_arg_idx);\n        put_short_code(&bc_out, OP_put_loc, s->arguments_var_idx);\n    }\n    /* initialize a reference to the current function if needed */\n    if (s->func_var_idx >= 0) {\n        dbuf_putc(&bc_out, OP_special_object);\n        dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_THIS_FUNC);\n        put_short_code(&bc_out, OP_put_loc, s->func_var_idx);\n    }\n    /* initialize the variable environment object if needed */\n    if (s->var_object_idx >= 0) {\n        dbuf_putc(&bc_out, OP_special_object);\n        dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_VAR_OBJECT);\n        put_short_code(&bc_out, OP_put_loc, s->var_object_idx);\n    }\n    if (s->arg_var_object_idx >= 0) {\n        dbuf_putc(&bc_out, OP_special_object);\n        dbuf_putc(&bc_out, OP_SPECIAL_OBJECT_VAR_OBJECT);\n        put_short_code(&bc_out, OP_put_loc, s->arg_var_object_idx);\n    }\n\n    for (pos = 0; pos < bc_len; pos = pos_next) {\n        int val;\n        op = bc_buf[pos];\n        len = opcode_info[op].size;\n        pos_next = pos + len;\n        switch(op) {\n        case OP_line_num:\n            /* line number info (for debug). We put it in a separate\n               compressed table to reduce memory usage and get better\n               performance */\n            line_num = get_u32(bc_buf + pos + 1);\n            break;\n\n        case OP_label:\n            {\n                label = get_u32(bc_buf + pos + 1);\n                assert(label >= 0 && label < s->label_count);\n                ls = &label_slots[label];\n                assert(ls->addr == -1);\n                ls->addr = bc_out.size;\n                /* resolve the relocation entries */\n                for(re = ls->first_reloc; re != NULL; re = re_next) {\n                    int diff = ls->addr - re->addr;\n                    re_next = re->next;\n                    switch (re->size) {\n                    case 4:\n                        put_u32(bc_out.buf + re->addr, diff);\n                        break;\n                    case 2:\n                        assert(diff == (int16_t)diff);\n                        put_u16(bc_out.buf + re->addr, diff);\n                        break;\n                    case 1:\n                        assert(diff == (int8_t)diff);\n                        put_u8(bc_out.buf + re->addr, diff);\n                        break;\n                    }\n                    js_free(ctx, re);\n                }\n                ls->first_reloc = NULL;\n            }\n            break;\n\n        case OP_call:\n        case OP_call_method:\n            {\n                /* detect and transform tail calls */\n                int argc;\n                argc = get_u16(bc_buf + pos + 1);\n                if (code_match(&cc, pos_next, OP_return, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    put_short_code(&bc_out, op + 1, argc);\n                    pos_next = skip_dead_code(s, bc_buf, bc_len, cc.pos, &line_num);\n                    break;\n                }\n                add_pc2line_info(s, bc_out.size, line_num);\n                put_short_code(&bc_out, op, argc);\n                break;\n            }\n            goto no_change;\n\n        case OP_return:\n        case OP_return_undef:\n        case OP_return_async:\n        case OP_throw:\n        case OP_throw_error:\n            pos_next = skip_dead_code(s, bc_buf, bc_len, pos_next, &line_num);\n            goto no_change;\n\n        case OP_goto:\n            label = get_u32(bc_buf + pos + 1);\n        has_goto:\n            if (OPTIMIZE) {\n                int line1 = -1;\n                /* Use custom matcher because multiple labels can follow */\n                label = find_jump_target(s, label, &op1, &line1);\n                if (code_has_label(&cc, pos_next, label)) {\n                    /* jump to next instruction: remove jump */\n                    update_label(s, label, -1);\n                    break;\n                }\n                if (op1 == OP_return || op1 == OP_return_undef || op1 == OP_throw) {\n                    /* jump to return/throw: remove jump, append return/throw */\n                    /* updating the line number obfuscates assembly listing */\n                    //if (line1 >= 0) line_num = line1;\n                    update_label(s, label, -1);\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, op1);\n                    pos_next = skip_dead_code(s, bc_buf, bc_len, pos_next, &line_num);\n                    break;\n                }\n                /* XXX: should duplicate single instructions followed by goto or return */\n                /* For example, can match one of these followed by return:\n                   push_i32 / push_const / push_atom_value / get_var /\n                   undefined / null / push_false / push_true / get_ref_value /\n                   get_loc / get_arg / get_var_ref\n                 */\n            }\n            goto has_label;\n\n        case OP_gosub:\n            label = get_u32(bc_buf + pos + 1);\n            if (0 && OPTIMIZE) {\n                label = find_jump_target(s, label, &op1, NULL);\n                if (op1 == OP_ret) {\n                    update_label(s, label, -1);\n                    /* empty finally clause: remove gosub */\n                    break;\n                }\n            }\n            goto has_label;\n\n        case OP_catch:\n            label = get_u32(bc_buf + pos + 1);\n            goto has_label;\n\n        case OP_if_true:\n        case OP_if_false:\n            label = get_u32(bc_buf + pos + 1);\n            if (OPTIMIZE) {\n                label = find_jump_target(s, label, &op1, NULL);\n                /* transform if_false/if_true(l1) label(l1) -> drop label(l1) */\n                if (code_has_label(&cc, pos_next, label)) {\n                    update_label(s, label, -1);\n                    dbuf_putc(&bc_out, OP_drop);\n                    break;\n                }\n                /* transform if_false(l1) goto(l2) label(l1) -> if_false(l2) label(l1) */\n                if (code_match(&cc, pos_next, OP_goto, -1)) {\n                    int pos1 = cc.pos;\n                    int line1 = cc.line_num;\n                    if (code_has_label(&cc, pos1, label)) {\n                        if (line1 >= 0) line_num = line1;\n                        pos_next = pos1;\n                        update_label(s, label, -1);\n                        label = cc.label;\n                        op ^= OP_if_true ^ OP_if_false;\n                    }\n                }\n            }\n        has_label:\n            add_pc2line_info(s, bc_out.size, line_num);\n            if (op == OP_goto) {\n                pos_next = skip_dead_code(s, bc_buf, bc_len, pos_next, &line_num);\n            }\n            assert(label >= 0 && label < s->label_count);\n            ls = &label_slots[label];\n#if SHORT_OPCODES\n            jp = &s->jump_slots[s->jump_count++];\n            jp->op = op;\n            jp->size = 4;\n            jp->pos = bc_out.size + 1;\n            jp->label = label;\n\n            if (ls->addr == -1) {\n                int diff = ls->pos2 - pos - 1;\n                if (diff < 128 && (op == OP_if_false || op == OP_if_true || op == OP_goto)) {\n                    jp->size = 1;\n                    jp->op = OP_if_false8 + (op - OP_if_false);\n                    dbuf_putc(&bc_out, OP_if_false8 + (op - OP_if_false));\n                    dbuf_putc(&bc_out, 0);\n                    if (!add_reloc(ctx, ls, bc_out.size - 1, 1))\n                        goto fail;\n                    break;\n                }\n                if (diff < 32768 && op == OP_goto) {\n                    jp->size = 2;\n                    jp->op = OP_goto16;\n                    dbuf_putc(&bc_out, OP_goto16);\n                    dbuf_put_u16(&bc_out, 0);\n                    if (!add_reloc(ctx, ls, bc_out.size - 2, 2))\n                        goto fail;\n                    break;\n                }\n            } else {\n                int diff = ls->addr - bc_out.size - 1;\n                if (diff == (int8_t)diff && (op == OP_if_false || op == OP_if_true || op == OP_goto)) {\n                    jp->size = 1;\n                    jp->op = OP_if_false8 + (op - OP_if_false);\n                    dbuf_putc(&bc_out, OP_if_false8 + (op - OP_if_false));\n                    dbuf_putc(&bc_out, diff);\n                    break;\n                }\n                if (diff == (int16_t)diff && op == OP_goto) {\n                    jp->size = 2;\n                    jp->op = OP_goto16;\n                    dbuf_putc(&bc_out, OP_goto16);\n                    dbuf_put_u16(&bc_out, diff);\n                    break;\n                }\n            }\n#endif\n            dbuf_putc(&bc_out, op);\n            dbuf_put_u32(&bc_out, ls->addr - bc_out.size);\n            if (ls->addr == -1) {\n                /* unresolved yet: create a new relocation entry */\n                if (!add_reloc(ctx, ls, bc_out.size - 4, 4))\n                    goto fail;\n            }\n            break;\n        case OP_with_get_var:\n        case OP_with_put_var:\n        case OP_with_delete_var:\n        case OP_with_make_ref:\n        case OP_with_get_ref:\n        case OP_with_get_ref_undef:\n            {\n                JSAtom atom;\n                int is_with;\n\n                atom = get_u32(bc_buf + pos + 1);\n                label = get_u32(bc_buf + pos + 5);\n                is_with = bc_buf[pos + 9];\n                if (OPTIMIZE) {\n                    label = find_jump_target(s, label, &op1, NULL);\n                }\n                assert(label >= 0 && label < s->label_count);\n                ls = &label_slots[label];\n                add_pc2line_info(s, bc_out.size, line_num);\n#if SHORT_OPCODES\n                jp = &s->jump_slots[s->jump_count++];\n                jp->op = op;\n                jp->size = 4;\n                jp->pos = bc_out.size + 5;\n                jp->label = label;\n#endif\n                dbuf_putc(&bc_out, op);\n                dbuf_put_u32(&bc_out, atom);\n                dbuf_put_u32(&bc_out, ls->addr - bc_out.size);\n                if (ls->addr == -1) {\n                    /* unresolved yet: create a new relocation entry */\n                    if (!add_reloc(ctx, ls, bc_out.size - 4, 4))\n                        goto fail;\n                }\n                dbuf_putc(&bc_out, is_with);\n            }\n            break;\n\n        case OP_drop:\n            if (OPTIMIZE) {\n                /* remove useless drops before return */\n                if (code_match(&cc, pos_next, OP_return_undef, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    break;\n                }\n            }\n            goto no_change;\n\n        case OP_null:\n#if SHORT_OPCODES\n            if (OPTIMIZE) {\n                /* transform null strict_eq into is_null */\n                if (code_match(&cc, pos_next, OP_strict_eq, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_is_null);\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* transform null strict_neq if_false/if_true -> is_null if_true/if_false */\n                if (code_match(&cc, pos_next, OP_strict_neq, M2(OP_if_false, OP_if_true), -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_is_null);\n                    pos_next = cc.pos;\n                    label = cc.label;\n                    op = cc.op ^ OP_if_false ^ OP_if_true;\n                    goto has_label;\n                }\n            }\n#endif\n            /* fall thru */\n        case OP_push_false:\n        case OP_push_true:\n            if (OPTIMIZE) {\n                val = (op == OP_push_true);\n                if (code_match(&cc, pos_next, M2(OP_if_false, OP_if_true), -1)) {\n                has_constant_test:\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    if (val == cc.op - OP_if_false) {\n                        /* transform null if_false(l1) -> goto l1 */\n                        /* transform false if_false(l1) -> goto l1 */\n                        /* transform true if_true(l1) -> goto l1 */\n                        pos_next = cc.pos;\n                        op = OP_goto;\n                        label = cc.label;\n                        goto has_goto;\n                    } else {\n                        /* transform null if_true(l1) -> nop */\n                        /* transform false if_true(l1) -> nop */\n                        /* transform true if_false(l1) -> nop */\n                        pos_next = cc.pos;\n                        update_label(s, cc.label, -1);\n                        break;\n                    }\n                }\n            }\n            goto no_change;\n\n        case OP_push_i32:\n            if (OPTIMIZE) {\n                /* transform i32(val) neg -> i32(-val) */\n                val = get_i32(bc_buf + pos + 1);\n                if ((val != INT32_MIN && val != 0)\n                &&  code_match(&cc, pos_next, OP_neg, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    if (code_match(&cc, cc.pos, OP_drop, -1)) {\n                        if (cc.line_num >= 0) line_num = cc.line_num;\n                    } else {\n                        add_pc2line_info(s, bc_out.size, line_num);\n                        push_short_int(&bc_out, -val);\n                    }\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* remove push/drop pairs generated by the parser */\n                if (code_match(&cc, pos_next, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* Optimize constant tests: `if (0)`, `if (1)`, `if (!0)`... */\n                if (code_match(&cc, pos_next, M2(OP_if_false, OP_if_true), -1)) {\n                    val = (val != 0);\n                    goto has_constant_test;\n                }\n                add_pc2line_info(s, bc_out.size, line_num);\n                push_short_int(&bc_out, val);\n                break;\n            }\n            goto no_change;\n\n#if SHORT_OPCODES\n        case OP_push_const:\n        case OP_fclosure:\n            if (OPTIMIZE) {\n                int idx = get_u32(bc_buf + pos + 1);\n                if (idx < 256) {\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_push_const8 + op - OP_push_const);\n                    dbuf_putc(&bc_out, idx);\n                    break;\n                }\n            }\n            goto no_change;\n\n        case OP_get_field:\n            if (OPTIMIZE) {\n                JSAtom atom = get_u32(bc_buf + pos + 1);\n                if (atom == JS_ATOM_length) {\n                    JS_FreeAtom(ctx, atom);\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_get_length);\n                    break;\n                }\n            }\n            goto no_change;\n#endif\n        case OP_push_atom_value:\n            if (OPTIMIZE) {\n                JSAtom atom = get_u32(bc_buf + pos + 1);\n                /* remove push/drop pairs generated by the parser */\n                if (code_match(&cc, pos_next, OP_drop, -1)) {\n                    JS_FreeAtom(ctx, atom);\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    pos_next = cc.pos;\n                    break;\n                }\n#if SHORT_OPCODES\n                if (atom == JS_ATOM_empty_string) {\n                    JS_FreeAtom(ctx, atom);\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_push_empty_string);\n                    break;\n                }\n#endif\n            }\n            goto no_change;\n\n        case OP_to_propkey:\n        case OP_to_propkey2:\n            if (OPTIMIZE) {\n                /* remove redundant to_propkey/to_propkey2 opcodes when storing simple data */\n                if (code_match(&cc, pos_next, M3(OP_get_loc, OP_get_arg, OP_get_var_ref), -1, OP_put_array_el, -1)\n                ||  code_match(&cc, pos_next, M3(OP_push_i32, OP_push_const, OP_push_atom_value), OP_put_array_el, -1)\n                ||  code_match(&cc, pos_next, M4(OP_undefined, OP_null, OP_push_true, OP_push_false), OP_put_array_el, -1)) {\n                    break;\n                }\n            }\n            goto no_change;\n\n        case OP_undefined:\n            if (OPTIMIZE) {\n                /* remove push/drop pairs generated by the parser */\n                if (code_match(&cc, pos_next, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* transform undefined return -> return_undefined */\n                if (code_match(&cc, pos_next, OP_return, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_return_undef);\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* transform undefined if_true(l1)/if_false(l1) -> nop/goto(l1) */\n                if (code_match(&cc, pos_next, M2(OP_if_false, OP_if_true), -1)) {\n                    val = 0;\n                    goto has_constant_test;\n                }\n#if SHORT_OPCODES\n                /* transform undefined strict_eq -> is_undefined */\n                if (code_match(&cc, pos_next, OP_strict_eq, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_is_undefined);\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* transform undefined strict_neq if_false/if_true -> is_undefined if_true/if_false */\n                if (code_match(&cc, pos_next, OP_strict_neq, M2(OP_if_false, OP_if_true), -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_is_undefined);\n                    pos_next = cc.pos;\n                    label = cc.label;\n                    op = cc.op ^ OP_if_false ^ OP_if_true;\n                    goto has_label;\n                }\n#endif\n            }\n            goto no_change;\n\n        case OP_insert2:\n            if (OPTIMIZE) {\n                /* Transformation:\n                   insert2 put_field(a) drop -> put_field(a)\n                   insert2 put_var_strict(a) drop -> put_var_strict(a)\n                */\n                if (code_match(&cc, pos_next, M2(OP_put_field, OP_put_var_strict), OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, cc.op);\n                    dbuf_put_u32(&bc_out, cc.atom);\n                    pos_next = cc.pos;\n                    break;\n                }\n            }\n            goto no_change;\n\n        case OP_dup:\n            if (OPTIMIZE) {\n                /* Transformation: dup put_x(n) drop -> put_x(n) */\n                int op1, line2 = -1;\n                /* Transformation: dup put_x(n) -> set_x(n) */\n                if (code_match(&cc, pos_next, M3(OP_put_loc, OP_put_arg, OP_put_var_ref), -1, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    op1 = cc.op + 1;  /* put_x -> set_x */\n                    pos_next = cc.pos;\n                    if (code_match(&cc, cc.pos, OP_drop, -1)) {\n                        if (cc.line_num >= 0) line_num = cc.line_num;\n                        op1 -= 1; /* set_x drop -> put_x */\n                        pos_next = cc.pos;\n                        if (code_match(&cc, cc.pos, op1 - 1, cc.idx, -1)) {\n                            line2 = cc.line_num; /* delay line number update */\n                            op1 += 1;   /* put_x(n) get_x(n) -> set_x(n) */\n                            pos_next = cc.pos;\n                        }\n                    }\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    put_short_code(&bc_out, op1, cc.idx);\n                    if (line2 >= 0) line_num = line2;\n                    break;\n                }\n            }\n            goto no_change;\n\n        case OP_get_loc:\n            if (OPTIMIZE) {\n                /* transformation:\n                   get_loc(n) post_dec put_loc(n) drop -> dec_loc(n)\n                   get_loc(n) post_inc put_loc(n) drop -> inc_loc(n)\n                   get_loc(n) dec dup put_loc(n) drop -> dec_loc(n)\n                   get_loc(n) inc dup put_loc(n) drop -> inc_loc(n)\n                 */\n                int idx;\n                idx = get_u16(bc_buf + pos + 1);\n                if (idx >= 256)\n                    goto no_change;\n                if (code_match(&cc, pos_next, M2(OP_post_dec, OP_post_inc), OP_put_loc, idx, OP_drop, -1) ||\n                    code_match(&cc, pos_next, M2(OP_dec, OP_inc), OP_dup, OP_put_loc, idx, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, (cc.op == OP_inc || cc.op == OP_post_inc) ? OP_inc_loc : OP_dec_loc);\n                    dbuf_putc(&bc_out, idx);\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* transformation:\n                   get_loc(n) push_atom_value(x) add dup put_loc(n) drop -> push_atom_value(x) add_loc(n)\n                 */\n                if (code_match(&cc, pos_next, OP_push_atom_value, OP_add, OP_dup, OP_put_loc, idx, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n#if SHORT_OPCODES\n                    if (cc.atom == JS_ATOM_empty_string) {\n                        JS_FreeAtom(ctx, cc.atom);\n                        dbuf_putc(&bc_out, OP_push_empty_string);\n                    } else\n#endif\n                    {\n                        dbuf_putc(&bc_out, OP_push_atom_value);\n                        dbuf_put_u32(&bc_out, cc.atom);\n                    }\n                    dbuf_putc(&bc_out, OP_add_loc);\n                    dbuf_putc(&bc_out, idx);\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* transformation:\n                   get_loc(n) push_i32(x) add dup put_loc(n) drop -> push_i32(x) add_loc(n)\n                 */\n                if (code_match(&cc, pos_next, OP_push_i32, OP_add, OP_dup, OP_put_loc, idx, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    push_short_int(&bc_out, cc.label);\n                    dbuf_putc(&bc_out, OP_add_loc);\n                    dbuf_putc(&bc_out, idx);\n                    pos_next = cc.pos;\n                    break;\n                }\n                /* transformation: XXX: also do these:\n                   get_loc(n) get_loc(x) add dup put_loc(n) drop -> get_loc(x) add_loc(n)\n                   get_loc(n) get_arg(x) add dup put_loc(n) drop -> get_arg(x) add_loc(n)\n                   get_loc(n) get_var_ref(x) add dup put_loc(n) drop -> get_var_ref(x) add_loc(n)\n                 */\n                if (code_match(&cc, pos_next, M3(OP_get_loc, OP_get_arg, OP_get_var_ref), -1, OP_add, OP_dup, OP_put_loc, idx, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    put_short_code(&bc_out, cc.op, cc.idx);\n                    dbuf_putc(&bc_out, OP_add_loc);\n                    dbuf_putc(&bc_out, idx);\n                    pos_next = cc.pos;\n                    break;\n                }\n                add_pc2line_info(s, bc_out.size, line_num);\n                put_short_code(&bc_out, op, idx);\n                break;\n            }\n            goto no_change;\n#if SHORT_OPCODES\n        case OP_get_arg:\n        case OP_get_var_ref:\n            if (OPTIMIZE) {\n                int idx;\n                idx = get_u16(bc_buf + pos + 1);\n                add_pc2line_info(s, bc_out.size, line_num);\n                put_short_code(&bc_out, op, idx);\n                break;\n            }\n            goto no_change;\n#endif\n        case OP_put_loc:\n        case OP_put_arg:\n        case OP_put_var_ref:\n            if (OPTIMIZE) {\n                /* transformation: put_x(n) get_x(n) -> set_x(n) */\n                int idx;\n                idx = get_u16(bc_buf + pos + 1);\n                if (code_match(&cc, pos_next, op - 1, idx, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    put_short_code(&bc_out, op + 1, idx);\n                    pos_next = cc.pos;\n                    break;\n                }\n                add_pc2line_info(s, bc_out.size, line_num);\n                put_short_code(&bc_out, op, idx);\n                break;\n            }\n            goto no_change;\n\n        case OP_post_inc:\n        case OP_post_dec:\n            if (OPTIMIZE) {\n                /* transformation:\n                   post_inc put_x drop -> inc put_x\n                   post_inc perm3 put_field drop -> inc put_field\n                   post_inc perm3 put_var_strict drop -> inc put_var_strict\n                   post_inc perm4 put_array_el drop -> inc put_array_el\n                 */\n                int op1, idx;\n                if (code_match(&cc, pos_next, M3(OP_put_loc, OP_put_arg, OP_put_var_ref), -1, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    op1 = cc.op;\n                    idx = cc.idx;\n                    pos_next = cc.pos;\n                    if (code_match(&cc, cc.pos, op1 - 1, idx, -1)) {\n                        if (cc.line_num >= 0) line_num = cc.line_num;\n                        op1 += 1;   /* put_x(n) get_x(n) -> set_x(n) */\n                        pos_next = cc.pos;\n                    }\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_dec + (op - OP_post_dec));\n                    put_short_code(&bc_out, op1, idx);\n                    break;\n                }\n                if (code_match(&cc, pos_next, OP_perm3, M2(OP_put_field, OP_put_var_strict), OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_dec + (op - OP_post_dec));\n                    dbuf_putc(&bc_out, cc.op);\n                    dbuf_put_u32(&bc_out, cc.atom);\n                    pos_next = cc.pos;\n                    break;\n                }\n                if (code_match(&cc, pos_next, OP_perm4, OP_put_array_el, OP_drop, -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    add_pc2line_info(s, bc_out.size, line_num);\n                    dbuf_putc(&bc_out, OP_dec + (op - OP_post_dec));\n                    dbuf_putc(&bc_out, OP_put_array_el);\n                    pos_next = cc.pos;\n                    break;\n                }\n            }\n            goto no_change;\n\n#if SHORT_OPCODES\n        case OP_typeof:\n            if (OPTIMIZE) {\n                /* simplify typeof tests */\n                if (code_match(&cc, pos_next, OP_push_atom_value, M4(OP_strict_eq, OP_strict_neq, OP_eq, OP_neq), -1)) {\n                    if (cc.line_num >= 0) line_num = cc.line_num;\n                    int op1 = (cc.op == OP_strict_eq || cc.op == OP_eq) ? OP_strict_eq : OP_strict_neq;\n                    int op2 = -1;\n                    switch (cc.atom) {\n                    case JS_ATOM_undefined:\n                        op2 = OP_typeof_is_undefined;\n                        break;\n                    case JS_ATOM_function:\n                        op2 = OP_typeof_is_function;\n                        break;\n                    }\n                    if (op2 >= 0) {\n                        /* transform typeof(s) == \"<type>\" into is_<type> */\n                        if (op1 == OP_strict_eq) {\n                            add_pc2line_info(s, bc_out.size, line_num);\n                            dbuf_putc(&bc_out, op2);\n                            JS_FreeAtom(ctx, cc.atom);\n                            pos_next = cc.pos;\n                            break;\n                        }\n                        if (op1 == OP_strict_neq && code_match(&cc, cc.pos, OP_if_false, -1)) {\n                            /* transform typeof(s) != \"<type>\" if_false into is_<type> if_true */\n                            if (cc.line_num >= 0) line_num = cc.line_num;\n                            add_pc2line_info(s, bc_out.size, line_num);\n                            dbuf_putc(&bc_out, op2);\n                            JS_FreeAtom(ctx, cc.atom);\n                            pos_next = cc.pos;\n                            label = cc.label;\n                            op = OP_if_true;\n                            goto has_label;\n                        }\n                    }\n                }\n            }\n            goto no_change;\n#endif\n\n        default:\n        no_change:\n            add_pc2line_info(s, bc_out.size, line_num);\n            dbuf_put(&bc_out, bc_buf + pos, len);\n            break;\n        }\n    }\n\n    /* check that there were no missing labels */\n    for(i = 0; i < s->label_count; i++) {\n        assert(label_slots[i].first_reloc == NULL);\n    }\n#if SHORT_OPCODES\n    if (OPTIMIZE) {\n        /* more jump optimizations */\n        int patch_offsets = 0;\n        for (i = 0, jp = s->jump_slots; i < s->jump_count; i++, jp++) {\n            LabelSlot *ls;\n            JumpSlot *jp1;\n            int j, pos, diff, delta;\n\n            delta = 3;\n            switch (op = jp->op) {\n            case OP_goto16:\n                delta = 1;\n                /* fall thru */\n            case OP_if_false:\n            case OP_if_true:\n            case OP_goto:\n                pos = jp->pos;\n                diff = s->label_slots[jp->label].addr - pos;\n                if (diff >= -128 && diff <= 127 + delta) {\n                    //put_u8(bc_out.buf + pos, diff);\n                    jp->size = 1;\n                    if (op == OP_goto16) {\n                        bc_out.buf[pos - 1] = jp->op = OP_goto8;\n                    } else {\n                        bc_out.buf[pos - 1] = jp->op = OP_if_false8 + (op - OP_if_false);\n                    }\n                    goto shrink;\n                } else\n                if (diff == (int16_t)diff && op == OP_goto) {\n                    //put_u16(bc_out.buf + pos, diff);\n                    jp->size = 2;\n                    delta = 2;\n                    bc_out.buf[pos - 1] = jp->op = OP_goto16;\n                shrink:\n                    /* XXX: should reduce complexity, using 2 finger copy scheme */\n                    memmove(bc_out.buf + pos + jp->size, bc_out.buf + pos + jp->size + delta,\n                            bc_out.size - pos - jp->size - delta);\n                    bc_out.size -= delta;\n                    patch_offsets++;\n                    for (j = 0, ls = s->label_slots; j < s->label_count; j++, ls++) {\n                        if (ls->addr > pos)\n                            ls->addr -= delta;\n                    }\n                    for (j = i + 1, jp1 = jp + 1; j < s->jump_count; j++, jp1++) {\n                        if (jp1->pos > pos)\n                            jp1->pos -= delta;\n                    }\n                    for (j = 0; j < s->line_number_count; j++) {\n                        if (s->line_number_slots[j].pc > pos)\n                            s->line_number_slots[j].pc -= delta;\n                    }\n                    continue;\n                }\n                break;\n            }\n        }\n        if (patch_offsets) {\n            JumpSlot *jp1;\n            int j;\n            for (j = 0, jp1 = s->jump_slots; j < s->jump_count; j++, jp1++) {\n                int diff1 = s->label_slots[jp1->label].addr - jp1->pos;\n                switch (jp1->size) {\n                case 1:\n                    put_u8(bc_out.buf + jp1->pos, diff1);\n                    break;\n                case 2:\n                    put_u16(bc_out.buf + jp1->pos, diff1);\n                    break;\n                case 4:\n                    put_u32(bc_out.buf + jp1->pos, diff1);\n                    break;\n                }\n            }\n        }\n    }\n    js_free(ctx, s->jump_slots);\n    s->jump_slots = NULL;\n#endif\n    js_free(ctx, s->label_slots);\n    s->label_slots = NULL;\n    /* XXX: should delay until copying to runtime bytecode function */\n    compute_pc2line_info(s);\n    js_free(ctx, s->line_number_slots);\n    s->line_number_slots = NULL;\n    /* set the new byte code */\n    dbuf_free(&s->byte_code);\n    s->byte_code = bc_out;\n    s->use_short_opcodes = TRUE;\n    if (dbuf_error(&s->byte_code)) {\n        JS_ThrowOutOfMemory(ctx);\n        return -1;\n    }\n    return 0;\n fail:\n    /* XXX: not safe */\n    dbuf_free(&bc_out);\n    return -1;\n}\n\n/* compute the maximum stack size needed by the function */\n\ntypedef struct StackSizeState {\n    int bc_len;\n    int stack_len_max;\n    uint16_t *stack_level_tab;\n    int *pc_stack;\n    int pc_stack_len;\n    int pc_stack_size;\n} StackSizeState;\n\n/* 'op' is only used for error indication */\nstatic __exception int ss_check(JSContext *ctx, StackSizeState *s,\n                                int pos, int op, int stack_len)\n{\n    if ((unsigned)pos >= s->bc_len) {\n        JS_ThrowInternalError(ctx, \"bytecode buffer overflow (op=%d, pc=%d)\", op, pos);\n        return -1;\n    }\n    if (stack_len > s->stack_len_max) {\n        s->stack_len_max = stack_len;\n        if (s->stack_len_max > JS_STACK_SIZE_MAX) {\n            JS_ThrowInternalError(ctx, \"stack overflow (op=%d, pc=%d)\", op, pos);\n            return -1;\n        }\n    }\n    if (s->stack_level_tab[pos] != 0xffff) {\n        /* already explored: check that the stack size is consistent */\n        if (s->stack_level_tab[pos] != stack_len) {\n            JS_ThrowInternalError(ctx, \"unconsistent stack size: %d %d (pc=%d)\",\n                                  s->stack_level_tab[pos], stack_len, pos);\n            return -1;\n        } else {\n            return 0;\n        }\n    }\n\n    /* mark as explored and store the stack size */\n    s->stack_level_tab[pos] = stack_len;\n\n    /* queue the new PC to explore */\n    if (js_resize_array(ctx, (void **)&s->pc_stack, sizeof(s->pc_stack[0]),\n                        &s->pc_stack_size, s->pc_stack_len + 1))\n        return -1;\n    s->pc_stack[s->pc_stack_len++] = pos;\n    return 0;\n}\n\nstatic __exception int compute_stack_size(JSContext *ctx,\n                                          JSFunctionDef *fd,\n                                          int *pstack_size)\n{\n    StackSizeState s_s, *s = &s_s;\n    int i, diff, n_pop, pos_next, stack_len, pos, op;\n    const JSOpCode *oi;\n    const uint8_t *bc_buf;\n\n    bc_buf = fd->byte_code.buf;\n    s->bc_len = fd->byte_code.size;\n    /* bc_len > 0 */\n    s->stack_level_tab = js_malloc(ctx, sizeof(s->stack_level_tab[0]) *\n                                   s->bc_len);\n    if (!s->stack_level_tab)\n        return -1;\n    for(i = 0; i < s->bc_len; i++)\n        s->stack_level_tab[i] = 0xffff;\n    s->stack_len_max = 0;\n    s->pc_stack = NULL;\n    s->pc_stack_len = 0;\n    s->pc_stack_size = 0;\n\n    /* breadth-first graph exploration */\n    if (ss_check(ctx, s, 0, OP_invalid, 0))\n        goto fail;\n\n    while (s->pc_stack_len > 0) {\n        pos = s->pc_stack[--s->pc_stack_len];\n        stack_len = s->stack_level_tab[pos];\n        op = bc_buf[pos];\n        if (op == 0 || op >= OP_COUNT) {\n            JS_ThrowInternalError(ctx, \"invalid opcode (op=%d, pc=%d)\", op, pos);\n            goto fail;\n        }\n        oi = &short_opcode_info(op);\n        pos_next = pos + oi->size;\n        if (pos_next > s->bc_len) {\n            JS_ThrowInternalError(ctx, \"bytecode buffer overflow (op=%d, pc=%d)\", op, pos);\n            goto fail;\n        }\n        n_pop = oi->n_pop;\n        /* call pops a variable number of arguments */\n        if (oi->fmt == OP_FMT_npop || oi->fmt == OP_FMT_npop_u16) {\n            n_pop += get_u16(bc_buf + pos + 1);\n        } else {\n#if SHORT_OPCODES\n            if (oi->fmt == OP_FMT_npopx) {\n                n_pop += op - OP_call0;\n            }\n#endif\n        }\n\n        if (stack_len < n_pop) {\n            JS_ThrowInternalError(ctx, \"stack underflow (op=%d, pc=%d)\", op, pos);\n            goto fail;\n        }\n        stack_len += oi->n_push - n_pop;\n        if (stack_len > s->stack_len_max) {\n            s->stack_len_max = stack_len;\n            if (s->stack_len_max > JS_STACK_SIZE_MAX) {\n                JS_ThrowInternalError(ctx, \"stack overflow (op=%d, pc=%d)\", op, pos);\n                goto fail;\n            }\n        }\n        switch(op) {\n        case OP_tail_call:\n        case OP_tail_call_method:\n        case OP_return:\n        case OP_return_undef:\n        case OP_return_async:\n        case OP_throw:\n        case OP_throw_error:\n        case OP_ret:\n            goto done_insn;\n        case OP_goto:\n            diff = get_u32(bc_buf + pos + 1);\n            pos_next = pos + 1 + diff;\n            break;\n#if SHORT_OPCODES\n        case OP_goto16:\n            diff = (int16_t)get_u16(bc_buf + pos + 1);\n            pos_next = pos + 1 + diff;\n            break;\n        case OP_goto8:\n            diff = (int8_t)bc_buf[pos + 1];\n            pos_next = pos + 1 + diff;\n            break;\n        case OP_if_true8:\n        case OP_if_false8:\n            diff = (int8_t)bc_buf[pos + 1];\n            if (ss_check(ctx, s, pos + 1 + diff, op, stack_len))\n                goto fail;\n            break;\n#endif\n        case OP_if_true:\n        case OP_if_false:\n        case OP_catch:\n            diff = get_u32(bc_buf + pos + 1);\n            if (ss_check(ctx, s, pos + 1 + diff, op, stack_len))\n                goto fail;\n            break;\n        case OP_gosub:\n            diff = get_u32(bc_buf + pos + 1);\n            if (ss_check(ctx, s, pos + 1 + diff, op, stack_len + 1))\n                goto fail;\n            break;\n        case OP_with_get_var:\n        case OP_with_delete_var:\n            diff = get_u32(bc_buf + pos + 5);\n            if (ss_check(ctx, s, pos + 5 + diff, op, stack_len + 1))\n                goto fail;\n            break;\n        case OP_with_make_ref:\n        case OP_with_get_ref:\n        case OP_with_get_ref_undef:\n            diff = get_u32(bc_buf + pos + 5);\n            if (ss_check(ctx, s, pos + 5 + diff, op, stack_len + 2))\n                goto fail;\n            break;\n        case OP_with_put_var:\n            diff = get_u32(bc_buf + pos + 5);\n            if (ss_check(ctx, s, pos + 5 + diff, op, stack_len - 1))\n                goto fail;\n            break;\n\n        default:\n            break;\n        }\n        if (ss_check(ctx, s, pos_next, op, stack_len))\n            goto fail;\n    done_insn: ;\n    }\n    js_free(ctx, s->stack_level_tab);\n    js_free(ctx, s->pc_stack);\n    *pstack_size = s->stack_len_max;\n    return 0;\n fail:\n    js_free(ctx, s->stack_level_tab);\n    js_free(ctx, s->pc_stack);\n    *pstack_size = 0;\n    return -1;\n}\n\nstatic int add_module_variables(JSContext *ctx, JSFunctionDef *fd)\n{\n    int i, idx;\n    JSModuleDef *m = fd->module;\n    JSExportEntry *me;\n    JSGlobalVar *hf;\n\n    /* The imported global variables were added as closure variables\n       in js_parse_import(). We add here the module global\n       variables. */\n\n    for(i = 0; i < fd->global_var_count; i++) {\n        hf = &fd->global_vars[i];\n        if (add_closure_var(ctx, fd, TRUE, FALSE, i, hf->var_name, hf->is_const,\n                            hf->is_lexical, FALSE) < 0)\n            return -1;\n    }\n\n    /* resolve the variable names of the local exports */\n    for(i = 0; i < m->export_entries_count; i++) {\n        me = &m->export_entries[i];\n        if (me->export_type == JS_EXPORT_TYPE_LOCAL) {\n            idx = find_closure_var(ctx, fd, me->local_name);\n            if (idx < 0) {\n                JS_ThrowSyntaxErrorAtom(ctx, \"exported variable '%s' does not exist\",\n                                        me->local_name);\n                return -1;\n            }\n            me->u.local.var_idx = idx;\n        }\n    }\n    return 0;\n}\n\n/* create a function object from a function definition. The function\n   definition is freed. All the child functions are also created. It\n   must be done this way to resolve all the variables. */\nstatic JSValue js_create_function(JSContext *ctx, JSFunctionDef *fd)\n{\n    JSValue func_obj;\n    JSFunctionBytecode *b;\n    struct list_head *el, *el1;\n    int stack_size, scope, idx;\n    int function_size, byte_code_offset, cpool_offset;\n    int closure_var_offset, vardefs_offset;\n\n    /* recompute scope linkage */\n    for (scope = 0; scope < fd->scope_count; scope++) {\n        fd->scopes[scope].first = -1;\n    }\n    if (fd->has_parameter_expressions) {\n        /* special end of variable list marker for the argument scope */\n        fd->scopes[ARG_SCOPE_INDEX].first = ARG_SCOPE_END;\n    }\n    for (idx = 0; idx < fd->var_count; idx++) {\n        JSVarDef *vd = &fd->vars[idx];\n        vd->scope_next = fd->scopes[vd->scope_level].first;\n        fd->scopes[vd->scope_level].first = idx;\n    }\n    for (scope = 2; scope < fd->scope_count; scope++) {\n        JSVarScope *sd = &fd->scopes[scope];\n        if (sd->first < 0)\n            sd->first = fd->scopes[sd->parent].first;\n    }\n    for (idx = 0; idx < fd->var_count; idx++) {\n        JSVarDef *vd = &fd->vars[idx];\n        if (vd->scope_next < 0 && vd->scope_level > 1) {\n            scope = fd->scopes[vd->scope_level].parent;\n            vd->scope_next = fd->scopes[scope].first;\n        }\n    }\n\n    /* if the function contains an eval call, the closure variables\n       are used to compile the eval and they must be ordered by scope,\n       so it is necessary to create the closure variables before any\n       other variable lookup is done. */\n    if (fd->has_eval_call)\n        add_eval_variables(ctx, fd);\n\n    /* add the module global variables in the closure */\n    if (fd->module) {\n        if (add_module_variables(ctx, fd))\n            goto fail;\n    }\n\n    /* first create all the child functions */\n    list_for_each_safe(el, el1, &fd->child_list) {\n        JSFunctionDef *fd1;\n        int cpool_idx;\n\n        fd1 = list_entry(el, JSFunctionDef, link);\n        cpool_idx = fd1->parent_cpool_idx;\n        func_obj = js_create_function(ctx, fd1);\n        if (JS_IsException(func_obj))\n            goto fail;\n        /* save it in the constant pool */\n        assert(cpool_idx >= 0);\n        fd->cpool[cpool_idx] = func_obj;\n    }\n\n#if defined(DUMP_BYTECODE) && (DUMP_BYTECODE & 4)\n    if (!(fd->js_mode & JS_MODE_STRIP)) {\n        printf(\"pass 1\\n\");\n        dump_byte_code(ctx, 1, fd->byte_code.buf, fd->byte_code.size,\n                       fd->args, fd->arg_count, fd->vars, fd->var_count,\n                       fd->closure_var, fd->closure_var_count,\n                       fd->cpool, fd->cpool_count, fd->source, fd->line_num,\n                       fd->label_slots, NULL);\n        printf(\"\\n\");\n    }\n#endif\n\n    if (resolve_variables(ctx, fd))\n        goto fail;\n\n#if defined(DUMP_BYTECODE) && (DUMP_BYTECODE & 2)\n    if (!(fd->js_mode & JS_MODE_STRIP)) {\n        printf(\"pass 2\\n\");\n        dump_byte_code(ctx, 2, fd->byte_code.buf, fd->byte_code.size,\n                       fd->args, fd->arg_count, fd->vars, fd->var_count,\n                       fd->closure_var, fd->closure_var_count,\n                       fd->cpool, fd->cpool_count, fd->source, fd->line_num,\n                       fd->label_slots, NULL);\n        printf(\"\\n\");\n    }\n#endif\n\n    if (resolve_labels(ctx, fd))\n        goto fail;\n\n    if (compute_stack_size(ctx, fd, &stack_size) < 0)\n        goto fail;\n\n    if (fd->js_mode & JS_MODE_STRIP) {\n        function_size = offsetof(JSFunctionBytecode, debug);\n    } else {\n        function_size = sizeof(*b);\n    }\n    cpool_offset = function_size;\n    function_size += fd->cpool_count * sizeof(*fd->cpool);\n    vardefs_offset = function_size;\n    if (!(fd->js_mode & JS_MODE_STRIP) || fd->has_eval_call) {\n        function_size += (fd->arg_count + fd->var_count) * sizeof(*b->vardefs);\n    }\n    closure_var_offset = function_size;\n    function_size += fd->closure_var_count * sizeof(*fd->closure_var);\n    byte_code_offset = function_size;\n    function_size += fd->byte_code.size;\n\n    b = js_mallocz(ctx, function_size);\n    if (!b)\n        goto fail;\n    b->header.ref_count = 1;\n\n    b->byte_code_buf = (void *)((uint8_t*)b + byte_code_offset);\n    b->byte_code_len = fd->byte_code.size;\n    memcpy(b->byte_code_buf, fd->byte_code.buf, fd->byte_code.size);\n    js_free(ctx, fd->byte_code.buf);\n    fd->byte_code.buf = NULL;\n\n    b->func_name = fd->func_name;\n    if (fd->arg_count + fd->var_count > 0) {\n        if ((fd->js_mode & JS_MODE_STRIP) && !fd->has_eval_call) {\n            /* Strip variable definitions not needed at runtime */\n            int i;\n            for(i = 0; i < fd->var_count; i++) {\n                JS_FreeAtom(ctx, fd->vars[i].var_name);\n            }\n            for(i = 0; i < fd->arg_count; i++) {\n                JS_FreeAtom(ctx, fd->args[i].var_name);\n            }\n            for(i = 0; i < fd->closure_var_count; i++) {\n                JS_FreeAtom(ctx, fd->closure_var[i].var_name);\n                fd->closure_var[i].var_name = JS_ATOM_NULL;\n            }\n        } else {\n            b->vardefs = (void *)((uint8_t*)b + vardefs_offset);\n            memcpy(b->vardefs, fd->args, fd->arg_count * sizeof(fd->args[0]));\n            memcpy(b->vardefs + fd->arg_count, fd->vars, fd->var_count * sizeof(fd->vars[0]));\n        }\n        b->var_count = fd->var_count;\n        b->arg_count = fd->arg_count;\n        b->defined_arg_count = fd->defined_arg_count;\n        js_free(ctx, fd->args);\n        js_free(ctx, fd->vars);\n    }\n    b->cpool_count = fd->cpool_count;\n    if (b->cpool_count) {\n        b->cpool = (void *)((uint8_t*)b + cpool_offset);\n        memcpy(b->cpool, fd->cpool, b->cpool_count * sizeof(*b->cpool));\n    }\n    js_free(ctx, fd->cpool);\n    fd->cpool = NULL;\n\n    b->stack_size = stack_size;\n\n    if (fd->js_mode & JS_MODE_STRIP) {\n        JS_FreeAtom(ctx, fd->filename);\n        dbuf_free(&fd->pc2line);    // probably useless\n    } else {\n        /* XXX: source and pc2line info should be packed at the end of the\n           JSFunctionBytecode structure, avoiding allocation overhead\n         */\n        b->has_debug = 1;\n        b->debug.filename = fd->filename;\n        b->debug.line_num = fd->line_num;\n\n        //DynBuf pc2line;\n        //compute_pc2line_info(fd, &pc2line);\n        //js_free(ctx, fd->line_number_slots)\n        b->debug.pc2line_buf = js_realloc(ctx, fd->pc2line.buf, fd->pc2line.size);\n        if (!b->debug.pc2line_buf)\n            b->debug.pc2line_buf = fd->pc2line.buf;\n        b->debug.pc2line_len = fd->pc2line.size;\n        b->debug.source = fd->source;\n        b->debug.source_len = fd->source_len;\n    }\n    if (fd->scopes != fd->def_scope_array)\n        js_free(ctx, fd->scopes);\n\n    b->closure_var_count = fd->closure_var_count;\n    if (b->closure_var_count) {\n        b->closure_var = (void *)((uint8_t*)b + closure_var_offset);\n        memcpy(b->closure_var, fd->closure_var, b->closure_var_count * sizeof(*b->closure_var));\n    }\n    js_free(ctx, fd->closure_var);\n    fd->closure_var = NULL;\n\n    b->has_prototype = fd->has_prototype;\n    b->has_simple_parameter_list = fd->has_simple_parameter_list;\n    b->js_mode = fd->js_mode;\n    b->is_derived_class_constructor = fd->is_derived_class_constructor;\n    b->func_kind = fd->func_kind;\n    b->need_home_object = (fd->home_object_var_idx >= 0 ||\n                           fd->need_home_object);\n    b->new_target_allowed = fd->new_target_allowed;\n    b->super_call_allowed = fd->super_call_allowed;\n    b->super_allowed = fd->super_allowed;\n    b->arguments_allowed = fd->arguments_allowed;\n    b->backtrace_barrier = fd->backtrace_barrier;\n    b->realm = JS_DupContext(ctx);\n\n    add_gc_object(ctx->rt, &b->header, JS_GC_OBJ_TYPE_FUNCTION_BYTECODE);\n    \n#if defined(DUMP_BYTECODE) && (DUMP_BYTECODE & 1)\n    if (!(fd->js_mode & JS_MODE_STRIP)) {\n        js_dump_function_bytecode(ctx, b);\n    }\n#endif\n\n    if (fd->parent) {\n        /* remove from parent list */\n        list_del(&fd->link);\n    }\n\n    js_free(ctx, fd);\n    return JS_MKPTR(JS_TAG_FUNCTION_BYTECODE, b);\n fail:\n    js_free_function_def(ctx, fd);\n    return JS_EXCEPTION;\n}\n\nstatic void free_function_bytecode(JSRuntime *rt, JSFunctionBytecode *b)\n{\n    int i;\n\n#if 0\n    {\n        char buf[ATOM_GET_STR_BUF_SIZE];\n        printf(\"freeing %s\\n\",\n               JS_AtomGetStrRT(rt, buf, sizeof(buf), b->func_name));\n    }\n#endif\n    free_bytecode_atoms(rt, b->byte_code_buf, b->byte_code_len, TRUE);\n\n    if (b->vardefs) {\n        for(i = 0; i < b->arg_count + b->var_count; i++) {\n            JS_FreeAtomRT(rt, b->vardefs[i].var_name);\n        }\n    }\n    for(i = 0; i < b->cpool_count; i++)\n        JS_FreeValueRT(rt, b->cpool[i]);\n\n    for(i = 0; i < b->closure_var_count; i++) {\n        JSClosureVar *cv = &b->closure_var[i];\n        JS_FreeAtomRT(rt, cv->var_name);\n    }\n    if (b->realm)\n        JS_FreeContext(b->realm);\n\n    JS_FreeAtomRT(rt, b->func_name);\n    if (b->has_debug) {\n        JS_FreeAtomRT(rt, b->debug.filename);\n        js_free_rt(rt, b->debug.pc2line_buf);\n        js_free_rt(rt, b->debug.source);\n    }\n\n    remove_gc_object(&b->header);\n    if (rt->gc_phase == JS_GC_PHASE_REMOVE_CYCLES && b->header.ref_count != 0) {\n        list_add_tail(&b->header.link, &rt->gc_zero_ref_count_list);\n    } else {\n        js_free_rt(rt, b);\n    }\n}\n\nstatic __exception int js_parse_directives(JSParseState *s)\n{\n    char str[20];\n    JSParsePos pos;\n    BOOL has_semi;\n\n    if (s->token.val != TOK_STRING)\n        return 0;\n\n    js_parse_get_pos(s, &pos);\n\n    while(s->token.val == TOK_STRING) {\n        /* Copy actual source string representation */\n        snprintf(str, sizeof str, \"%.*s\",\n                 (int)(s->buf_ptr - s->token.ptr - 2), s->token.ptr + 1);\n\n        if (next_token(s))\n            return -1;\n\n        has_semi = FALSE;\n        switch (s->token.val) {\n        case ';':\n            if (next_token(s))\n                return -1;\n            has_semi = TRUE;\n            break;\n        case '}':\n        case TOK_EOF:\n            has_semi = TRUE;\n            break;\n        case TOK_NUMBER:\n        case TOK_STRING:\n        case TOK_TEMPLATE:\n        case TOK_IDENT:\n        case TOK_REGEXP:\n        case TOK_DEC:\n        case TOK_INC:\n        case TOK_NULL:\n        case TOK_FALSE:\n        case TOK_TRUE:\n        case TOK_IF:\n        case TOK_RETURN:\n        case TOK_VAR:\n        case TOK_THIS:\n        case TOK_DELETE:\n        case TOK_TYPEOF:\n        case TOK_NEW:\n        case TOK_DO:\n        case TOK_WHILE:\n        case TOK_FOR:\n        case TOK_SWITCH:\n        case TOK_THROW:\n        case TOK_TRY:\n        case TOK_FUNCTION:\n        case TOK_DEBUGGER:\n        case TOK_WITH:\n        case TOK_CLASS:\n        case TOK_CONST:\n        case TOK_ENUM:\n        case TOK_EXPORT:\n        case TOK_IMPORT:\n        case TOK_SUPER:\n        case TOK_INTERFACE:\n        case TOK_LET:\n        case TOK_PACKAGE:\n        case TOK_PRIVATE:\n        case TOK_PROTECTED:\n        case TOK_PUBLIC:\n        case TOK_STATIC:\n            /* automatic insertion of ';' */\n            if (s->got_lf)\n                has_semi = TRUE;\n            break;\n        default:\n            break;\n        }\n        if (!has_semi)\n            break;\n        if (!strcmp(str, \"use strict\")) {\n            s->cur_func->has_use_strict = TRUE;\n            s->cur_func->js_mode |= JS_MODE_STRICT;\n        }\n#if !defined(DUMP_BYTECODE) || !(DUMP_BYTECODE & 8)\n        else if (!strcmp(str, \"use strip\")) {\n            s->cur_func->js_mode |= JS_MODE_STRIP;\n        }\n#endif\n#ifdef CONFIG_BIGNUM\n        else if (s->ctx->bignum_ext && !strcmp(str, \"use math\")) {\n            s->cur_func->js_mode |= JS_MODE_MATH;\n        }\n#endif\n    }\n    return js_parse_seek_token(s, &pos);\n}\n\nstatic int js_parse_function_check_names(JSParseState *s, JSFunctionDef *fd,\n                                         JSAtom func_name)\n{\n    JSAtom name;\n    int i, idx;\n\n    if (fd->js_mode & JS_MODE_STRICT) {\n        if (!fd->has_simple_parameter_list && fd->has_use_strict) {\n            return js_parse_error(s, \"\\\"use strict\\\" not allowed in function with default or destructuring parameter\");\n        }\n        if (func_name == JS_ATOM_eval || func_name == JS_ATOM_arguments) {\n            return js_parse_error(s, \"invalid function name in strict code\");\n        }\n        for (idx = 0; idx < fd->arg_count; idx++) {\n            name = fd->args[idx].var_name;\n\n            if (name == JS_ATOM_eval || name == JS_ATOM_arguments) {\n                return js_parse_error(s, \"invalid argument name in strict code\");\n            }\n        }\n    }\n    /* check async_generator case */\n    if ((fd->js_mode & JS_MODE_STRICT)\n    ||  !fd->has_simple_parameter_list\n    ||  (fd->func_type == JS_PARSE_FUNC_METHOD && fd->func_kind == JS_FUNC_ASYNC)\n    ||  fd->func_type == JS_PARSE_FUNC_ARROW\n    ||  fd->func_type == JS_PARSE_FUNC_METHOD) {\n        for (idx = 0; idx < fd->arg_count; idx++) {\n            name = fd->args[idx].var_name;\n            if (name != JS_ATOM_NULL) {\n                for (i = 0; i < idx; i++) {\n                    if (fd->args[i].var_name == name)\n                        goto duplicate;\n                }\n                /* Check if argument name duplicates a destructuring parameter */\n                /* XXX: should have a flag for such variables */\n                for (i = 0; i < fd->var_count; i++) {\n                    if (fd->vars[i].var_name == name &&\n                        fd->vars[i].scope_level == 0)\n                        goto duplicate;\n                }\n            }\n        }\n    }\n    return 0;\n\nduplicate:\n    return js_parse_error(s, \"duplicate argument names not allowed in this context\");\n}\n\n/* create a function to initialize class fields */\nstatic JSFunctionDef *js_parse_function_class_fields_init(JSParseState *s)\n{\n    JSFunctionDef *fd;\n    \n    fd = js_new_function_def(s->ctx, s->cur_func, FALSE, FALSE,\n                             s->filename, 0);\n    if (!fd)\n        return NULL;\n    fd->func_name = JS_ATOM_NULL;\n    fd->has_prototype = FALSE;\n    fd->has_home_object = TRUE;\n    \n    fd->has_arguments_binding = FALSE;\n    fd->has_this_binding = TRUE;\n    fd->is_derived_class_constructor = FALSE;\n    fd->new_target_allowed = TRUE;\n    fd->super_call_allowed = FALSE;\n    fd->super_allowed = fd->has_home_object;\n    fd->arguments_allowed = FALSE;\n    \n    fd->func_kind = JS_FUNC_NORMAL;\n    fd->func_type = JS_PARSE_FUNC_METHOD;\n    return fd;\n}\n\n/* func_name must be JS_ATOM_NULL for JS_PARSE_FUNC_STATEMENT and\n   JS_PARSE_FUNC_EXPR, JS_PARSE_FUNC_ARROW and JS_PARSE_FUNC_VAR */\nstatic __exception int js_parse_function_decl2(JSParseState *s,\n                                               JSParseFunctionEnum func_type,\n                                               JSFunctionKindEnum func_kind,\n                                               JSAtom func_name,\n                                               const uint8_t *ptr,\n                                               int function_line_num,\n                                               JSParseExportEnum export_flag,\n                                               JSFunctionDef **pfd)\n{\n    JSContext *ctx = s->ctx;\n    JSFunctionDef *fd = s->cur_func;\n    BOOL is_expr;\n    int func_idx, lexical_func_idx = -1;\n    BOOL has_opt_arg;\n    BOOL create_func_var = FALSE;\n\n    is_expr = (func_type != JS_PARSE_FUNC_STATEMENT &&\n               func_type != JS_PARSE_FUNC_VAR);\n\n    if (func_type == JS_PARSE_FUNC_STATEMENT ||\n        func_type == JS_PARSE_FUNC_VAR ||\n        func_type == JS_PARSE_FUNC_EXPR) {\n        if (func_kind == JS_FUNC_NORMAL &&\n            token_is_pseudo_keyword(s, JS_ATOM_async) &&\n            peek_token(s, TRUE) != '\\n') {\n            if (next_token(s))\n                return -1;\n            func_kind = JS_FUNC_ASYNC;\n        }\n        if (next_token(s))\n            return -1;\n        if (s->token.val == '*') {\n            if (next_token(s))\n                return -1;\n            func_kind |= JS_FUNC_GENERATOR;\n        }\n\n        if (s->token.val == TOK_IDENT) {\n            if (s->token.u.ident.is_reserved ||\n                (s->token.u.ident.atom == JS_ATOM_yield &&\n                 func_type == JS_PARSE_FUNC_EXPR &&\n                 (func_kind & JS_FUNC_GENERATOR)) ||\n                (s->token.u.ident.atom == JS_ATOM_await &&\n                 func_type == JS_PARSE_FUNC_EXPR &&\n                 (func_kind & JS_FUNC_ASYNC))) {\n                return js_parse_error_reserved_identifier(s);\n            }\n        }\n        if (s->token.val == TOK_IDENT ||\n            (((s->token.val == TOK_YIELD && !(fd->js_mode & JS_MODE_STRICT)) ||\n             (s->token.val == TOK_AWAIT && !s->is_module)) &&\n             func_type == JS_PARSE_FUNC_EXPR)) {\n            func_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n            if (next_token(s)) {\n                JS_FreeAtom(ctx, func_name);\n                return -1;\n            }\n        } else {\n            if (func_type != JS_PARSE_FUNC_EXPR &&\n                export_flag != JS_PARSE_EXPORT_DEFAULT) {\n                return js_parse_error(s, \"function name expected\");\n            }\n        }\n    } else if (func_type != JS_PARSE_FUNC_ARROW) {\n        func_name = JS_DupAtom(ctx, func_name);\n    }\n\n    if (fd->is_eval && fd->eval_type == JS_EVAL_TYPE_MODULE &&\n        (func_type == JS_PARSE_FUNC_STATEMENT || func_type == JS_PARSE_FUNC_VAR)) {\n        JSGlobalVar *hf;\n        hf = find_global_var(fd, func_name);\n        /* XXX: should check scope chain */\n        if (hf && hf->scope_level == fd->scope_level) {\n            js_parse_error(s, \"invalid redefinition of global identifier in module code\");\n            JS_FreeAtom(ctx, func_name);\n            return -1;\n        }\n    }\n\n    if (func_type == JS_PARSE_FUNC_VAR) {\n        if (!(fd->js_mode & JS_MODE_STRICT)\n        && func_kind == JS_FUNC_NORMAL\n        &&  find_lexical_decl(ctx, fd, func_name, fd->scope_first, FALSE) < 0\n        &&  !((func_idx = find_var(ctx, fd, func_name)) >= 0 && (func_idx & ARGUMENT_VAR_OFFSET))\n        &&  !(func_name == JS_ATOM_arguments && fd->has_arguments_binding)) {\n            create_func_var = TRUE;\n        }\n        /* Create the lexical name here so that the function closure\n           contains it */\n        if (fd->is_eval &&\n            (fd->eval_type == JS_EVAL_TYPE_GLOBAL ||\n             fd->eval_type == JS_EVAL_TYPE_MODULE) &&\n            fd->scope_level == fd->body_scope) {\n            /* avoid creating a lexical variable in the global\n               scope. XXX: check annex B */\n            JSGlobalVar *hf;\n            hf = find_global_var(fd, func_name);\n            /* XXX: should check scope chain */\n            if (hf && hf->scope_level == fd->scope_level) {\n                js_parse_error(s, \"invalid redefinition of global identifier\");\n                JS_FreeAtom(ctx, func_name);\n                return -1;\n            }\n        } else {\n            /* Always create a lexical name, fail if at the same scope as\n               existing name */\n            /* Lexical variable will be initialized upon entering scope */\n            lexical_func_idx = define_var(s, fd, func_name,\n                                          func_kind != JS_FUNC_NORMAL ?\n                                          JS_VAR_DEF_NEW_FUNCTION_DECL :\n                                          JS_VAR_DEF_FUNCTION_DECL);\n            if (lexical_func_idx < 0) {\n                JS_FreeAtom(ctx, func_name);\n                return -1;\n            }\n        }\n    }\n\n    fd = js_new_function_def(ctx, fd, FALSE, is_expr,\n                             s->filename, function_line_num);\n    if (!fd) {\n        JS_FreeAtom(ctx, func_name);\n        return -1;\n    }\n    if (pfd)\n        *pfd = fd;\n    s->cur_func = fd;\n    fd->func_name = func_name;\n    /* XXX: test !fd->is_generator is always false */\n    fd->has_prototype = (func_type == JS_PARSE_FUNC_STATEMENT ||\n                         func_type == JS_PARSE_FUNC_VAR ||\n                         func_type == JS_PARSE_FUNC_EXPR) &&\n                        func_kind == JS_FUNC_NORMAL;\n    fd->has_home_object = (func_type == JS_PARSE_FUNC_METHOD ||\n                           func_type == JS_PARSE_FUNC_GETTER ||\n                           func_type == JS_PARSE_FUNC_SETTER ||\n                           func_type == JS_PARSE_FUNC_CLASS_CONSTRUCTOR ||\n                           func_type == JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR);\n    fd->has_arguments_binding = (func_type != JS_PARSE_FUNC_ARROW);\n    fd->has_this_binding = fd->has_arguments_binding;\n    fd->is_derived_class_constructor = (func_type == JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR);\n    if (func_type == JS_PARSE_FUNC_ARROW) {\n        fd->new_target_allowed = fd->parent->new_target_allowed;\n        fd->super_call_allowed = fd->parent->super_call_allowed;\n        fd->super_allowed = fd->parent->super_allowed;\n        fd->arguments_allowed = fd->parent->arguments_allowed;\n    } else {\n        fd->new_target_allowed = TRUE;\n        fd->super_call_allowed = fd->is_derived_class_constructor;\n        fd->super_allowed = fd->has_home_object;\n        fd->arguments_allowed = TRUE;\n    }\n\n    /* fd->in_function_body == FALSE prevents yield/await during the parsing\n       of the arguments in generator/async functions. They are parsed as\n       regular identifiers for other function kinds. */\n    fd->func_kind = func_kind;\n    fd->func_type = func_type;\n\n    if (func_type == JS_PARSE_FUNC_CLASS_CONSTRUCTOR ||\n        func_type == JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR) {\n        /* error if not invoked as a constructor */\n        emit_op(s, OP_check_ctor);\n    }\n\n    if (func_type == JS_PARSE_FUNC_CLASS_CONSTRUCTOR) {\n        emit_class_field_init(s);\n    }\n    \n    /* parse arguments */\n    fd->has_simple_parameter_list = TRUE;\n    fd->has_parameter_expressions = FALSE;\n    has_opt_arg = FALSE;\n    if (func_type == JS_PARSE_FUNC_ARROW && s->token.val == TOK_IDENT) {\n        JSAtom name;\n        if (s->token.u.ident.is_reserved) {\n            js_parse_error_reserved_identifier(s);\n            goto fail;\n        }\n        name = s->token.u.ident.atom;\n        if (add_arg(ctx, fd, name) < 0)\n            goto fail;\n        fd->defined_arg_count = 1;\n    } else {\n        if (s->token.val == '(') {\n            int skip_bits;\n            /* if there is an '=' inside the parameter list, we\n               consider there is a parameter expression inside */\n            js_parse_skip_parens_token(s, &skip_bits, FALSE);\n            if (skip_bits & SKIP_HAS_ASSIGNMENT)\n                fd->has_parameter_expressions = TRUE;\n            if (next_token(s))\n                goto fail;\n        } else {\n            if (js_parse_expect(s, '('))\n                goto fail;\n        }\n\n        if (fd->has_parameter_expressions) {\n            fd->scope_level = -1; /* force no parent scope */\n            if (push_scope(s) < 0)\n                return -1;\n        }\n        \n        while (s->token.val != ')') {\n            JSAtom name;\n            BOOL rest = FALSE;\n            int idx, has_initializer;\n\n            if (s->token.val == TOK_ELLIPSIS) {\n                fd->has_simple_parameter_list = FALSE;\n                rest = TRUE;\n                if (next_token(s))\n                    goto fail;\n            }\n            if (s->token.val == '[' || s->token.val == '{') {\n                fd->has_simple_parameter_list = FALSE;\n                if (rest) {\n                    emit_op(s, OP_rest);\n                    emit_u16(s, fd->arg_count);\n                } else {\n                    /* unnamed arg for destructuring */\n                    idx = add_arg(ctx, fd, JS_ATOM_NULL);\n                    emit_op(s, OP_get_arg);\n                    emit_u16(s, idx);\n                }\n                has_initializer = js_parse_destructuring_element(s, fd->has_parameter_expressions ? TOK_LET : TOK_VAR, 1, TRUE, -1, TRUE);\n                if (has_initializer < 0)\n                    goto fail;\n                if (has_initializer)\n                    has_opt_arg = TRUE;\n                if (!has_opt_arg)\n                    fd->defined_arg_count++;\n            } else if (s->token.val == TOK_IDENT) {\n                if (s->token.u.ident.is_reserved) {\n                    js_parse_error_reserved_identifier(s);\n                    goto fail;\n                }\n                name = s->token.u.ident.atom;\n                if (name == JS_ATOM_yield && fd->func_kind == JS_FUNC_GENERATOR) {\n                    js_parse_error_reserved_identifier(s);\n                    goto fail;\n                }\n                if (fd->has_parameter_expressions) {\n                    if (define_var(s, fd, name, JS_VAR_DEF_LET) < 0)\n                        goto fail;\n                }\n                /* XXX: could avoid allocating an argument if rest is true */\n                idx = add_arg(ctx, fd, name);\n                if (idx < 0)\n                    goto fail;\n                if (next_token(s))\n                    goto fail;\n                if (rest) {\n                    emit_op(s, OP_rest);\n                    emit_u16(s, idx);\n                    if (fd->has_parameter_expressions) {\n                        emit_op(s, OP_dup);\n                        emit_op(s, OP_scope_put_var_init);\n                        emit_atom(s, name);\n                        emit_u16(s, fd->scope_level);\n                    }\n                    emit_op(s, OP_put_arg);\n                    emit_u16(s, idx);\n                    fd->has_simple_parameter_list = FALSE;\n                    has_opt_arg = TRUE;\n                } else if (s->token.val == '=') {\n                    int label;\n                    \n                    fd->has_simple_parameter_list = FALSE;\n                    has_opt_arg = TRUE;\n\n                    if (next_token(s))\n                        goto fail;\n\n                    label = new_label(s);\n                    emit_op(s, OP_get_arg);\n                    emit_u16(s, idx);\n                    emit_op(s, OP_dup);\n                    emit_op(s, OP_undefined);\n                    emit_op(s, OP_strict_eq);\n                    emit_goto(s, OP_if_false, label);\n                    emit_op(s, OP_drop);\n                    if (js_parse_assign_expr(s))\n                        goto fail;\n                    set_object_name(s, name);\n                    emit_op(s, OP_dup);\n                    emit_op(s, OP_put_arg);\n                    emit_u16(s, idx);\n                    emit_label(s, label);\n                    emit_op(s, OP_scope_put_var_init);\n                    emit_atom(s, name);\n                    emit_u16(s, fd->scope_level);\n                } else {\n                    if (!has_opt_arg) {\n                        fd->defined_arg_count++;\n                    }\n                    if (fd->has_parameter_expressions) {\n                        /* copy the argument to the argument scope */\n                        emit_op(s, OP_get_arg);\n                        emit_u16(s, idx);\n                        emit_op(s, OP_scope_put_var_init);\n                        emit_atom(s, name);\n                        emit_u16(s, fd->scope_level);\n                    }\n                }\n            } else {\n                js_parse_error(s, \"missing formal parameter\");\n                goto fail;\n            }\n            if (rest && s->token.val != ')') {\n                js_parse_expect(s, ')');\n                goto fail;\n            }\n            if (s->token.val == ')')\n                break;\n            if (js_parse_expect(s, ','))\n                goto fail;\n        }\n        if ((func_type == JS_PARSE_FUNC_GETTER && fd->arg_count != 0) ||\n            (func_type == JS_PARSE_FUNC_SETTER && fd->arg_count != 1)) {\n            js_parse_error(s, \"invalid number of arguments for getter or setter\");\n            goto fail;\n        }\n    }\n\n    if (fd->has_parameter_expressions) {\n        int idx;\n\n        /* Copy the variables in the argument scope to the variable\n           scope (see FunctionDeclarationInstantiation() in spec). The\n           normal arguments are already present, so no need to copy\n           them. */\n        idx = fd->scopes[fd->scope_level].first;\n        while (idx >= 0) {\n            JSVarDef *vd = &fd->vars[idx];\n            if (vd->scope_level != fd->scope_level)\n                break;\n            if (find_var(ctx, fd, vd->var_name) < 0) {\n                if (add_var(ctx, fd, vd->var_name) < 0)\n                    goto fail;\n                vd = &fd->vars[idx]; /* fd->vars may have been reallocated */\n                emit_op(s, OP_scope_get_var);\n                emit_atom(s, vd->var_name);\n                emit_u16(s, fd->scope_level);\n                emit_op(s, OP_scope_put_var);\n                emit_atom(s, vd->var_name);\n                emit_u16(s, 0);\n            }\n            idx = vd->scope_next;\n        }\n        \n        /* the argument scope has no parent, hence we don't use pop_scope(s) */\n        emit_op(s, OP_leave_scope);\n        emit_u16(s, fd->scope_level);\n\n        /* set the variable scope as the current scope */\n        fd->scope_level = 0;\n        fd->scope_first = fd->scopes[fd->scope_level].first;\n    }\n    \n    if (next_token(s))\n        goto fail;\n\n    /* generator function: yield after the parameters are evaluated */\n    if (func_kind == JS_FUNC_GENERATOR ||\n        func_kind == JS_FUNC_ASYNC_GENERATOR)\n        emit_op(s, OP_initial_yield);\n\n    /* in generators, yield expression is forbidden during the parsing\n       of the arguments */\n    fd->in_function_body = TRUE;\n    push_scope(s);  /* enter body scope */\n    fd->body_scope = fd->scope_level;\n\n    if (s->token.val == TOK_ARROW) {\n        if (next_token(s))\n            goto fail;\n\n        if (s->token.val != '{') {\n            if (js_parse_function_check_names(s, fd, func_name))\n                goto fail;\n\n            if (js_parse_assign_expr(s))\n                goto fail;\n\n            if (func_kind != JS_FUNC_NORMAL)\n                emit_op(s, OP_return_async);\n            else\n                emit_op(s, OP_return);\n\n            if (!(fd->js_mode & JS_MODE_STRIP)) {\n                /* save the function source code */\n                /* the end of the function source code is after the last\n                   token of the function source stored into s->last_ptr */\n                fd->source_len = s->last_ptr - ptr;\n                fd->source = js_strndup(ctx, (const char *)ptr, fd->source_len);\n                if (!fd->source)\n                    goto fail;\n            }\n            goto done;\n        }\n    }\n\n    if (js_parse_expect(s, '{'))\n        goto fail;\n\n    if (js_parse_directives(s))\n        goto fail;\n\n    /* in strict_mode, check function and argument names */\n    if (js_parse_function_check_names(s, fd, func_name))\n        goto fail;\n\n    while (s->token.val != '}') {\n        if (js_parse_source_element(s))\n            goto fail;\n    }\n    if (!(fd->js_mode & JS_MODE_STRIP)) {\n        /* save the function source code */\n        fd->source_len = s->buf_ptr - ptr;\n        fd->source = js_strndup(ctx, (const char *)ptr, fd->source_len);\n        if (!fd->source)\n            goto fail;\n    }\n\n    if (next_token(s)) {\n        /* consume the '}' */\n        goto fail;\n    }\n\n    /* in case there is no return, add one */\n    if (js_is_live_code(s)) {\n        emit_return(s, FALSE);\n    }\ndone:\n    s->cur_func = fd->parent;\n\n    /* create the function object */\n    {\n        int idx;\n        JSAtom func_name = fd->func_name;\n\n        /* the real object will be set at the end of the compilation */\n        idx = cpool_add(s, JS_NULL);\n        fd->parent_cpool_idx = idx;\n\n        if (is_expr) {\n            /* for constructors, no code needs to be generated here */\n            if (func_type != JS_PARSE_FUNC_CLASS_CONSTRUCTOR &&\n                func_type != JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR) {\n                /* OP_fclosure creates the function object from the bytecode\n                   and adds the scope information */\n                emit_op(s, OP_fclosure);\n                emit_u32(s, idx);\n                if (func_name == JS_ATOM_NULL) {\n                    emit_op(s, OP_set_name);\n                    emit_u32(s, JS_ATOM_NULL);\n                }\n            }\n        } else if (func_type == JS_PARSE_FUNC_VAR) {\n            emit_op(s, OP_fclosure);\n            emit_u32(s, idx);\n            if (create_func_var) {\n                if (s->cur_func->is_global_var) {\n                    JSGlobalVar *hf;\n                    /* the global variable must be defined at the start of the\n                       function */\n                    hf = add_global_var(ctx, s->cur_func, func_name);\n                    if (!hf)\n                        goto fail;\n                    /* it is considered as defined at the top level\n                       (needed for annex B.3.3.4 and B.3.3.5\n                       checks) */\n                    hf->scope_level = 0; \n                    hf->force_init = ((s->cur_func->js_mode & JS_MODE_STRICT) != 0);\n                    /* store directly into global var, bypass lexical scope */\n                    emit_op(s, OP_dup);\n                    emit_op(s, OP_scope_put_var);\n                    emit_atom(s, func_name);\n                    emit_u16(s, 0);\n                } else {\n                    /* do not call define_var to bypass lexical scope check */\n                    func_idx = find_var(ctx, s->cur_func, func_name);\n                    if (func_idx < 0) {\n                        func_idx = add_var(ctx, s->cur_func, func_name);\n                        if (func_idx < 0)\n                            goto fail;\n                    }\n                    /* store directly into local var, bypass lexical catch scope */\n                    emit_op(s, OP_dup);\n                    emit_op(s, OP_scope_put_var);\n                    emit_atom(s, func_name);\n                    emit_u16(s, 0);\n                }\n            }\n            if (lexical_func_idx >= 0) {\n                /* lexical variable will be initialized upon entering scope */\n                s->cur_func->vars[lexical_func_idx].func_pool_idx = idx;\n                emit_op(s, OP_drop);\n            } else {\n                /* store function object into its lexical name */\n                /* XXX: could use OP_put_loc directly */\n                emit_op(s, OP_scope_put_var_init);\n                emit_atom(s, func_name);\n                emit_u16(s, s->cur_func->scope_level);\n            }\n        } else {\n            if (!s->cur_func->is_global_var) {\n                int var_idx = define_var(s, s->cur_func, func_name, JS_VAR_DEF_VAR);\n\n                if (var_idx < 0)\n                    goto fail;\n                /* the variable will be assigned at the top of the function */\n                if (var_idx & ARGUMENT_VAR_OFFSET) {\n                    s->cur_func->args[var_idx - ARGUMENT_VAR_OFFSET].func_pool_idx = idx;\n                } else {\n                    s->cur_func->vars[var_idx].func_pool_idx = idx;\n                }\n            } else {\n                JSAtom func_var_name;\n                JSGlobalVar *hf;\n                if (func_name == JS_ATOM_NULL)\n                    func_var_name = JS_ATOM__default_; /* export default */\n                else\n                    func_var_name = func_name;\n                /* the variable will be assigned at the top of the function */\n                hf = add_global_var(ctx, s->cur_func, func_var_name);\n                if (!hf)\n                    goto fail;\n                hf->cpool_idx = idx;\n                if (export_flag != JS_PARSE_EXPORT_NONE) {\n                    if (!add_export_entry(s, s->cur_func->module, func_var_name,\n                                          export_flag == JS_PARSE_EXPORT_NAMED ? func_var_name : JS_ATOM_default, JS_EXPORT_TYPE_LOCAL))\n                        goto fail;\n                }\n            }\n        }\n    }\n    return 0;\n fail:\n    s->cur_func = fd->parent;\n    js_free_function_def(ctx, fd);\n    if (pfd)\n        *pfd = NULL;\n    return -1;\n}\n\nstatic __exception int js_parse_function_decl(JSParseState *s,\n                                              JSParseFunctionEnum func_type,\n                                              JSFunctionKindEnum func_kind,\n                                              JSAtom func_name,\n                                              const uint8_t *ptr,\n                                              int function_line_num)\n{\n    return js_parse_function_decl2(s, func_type, func_kind, func_name, ptr,\n                                   function_line_num, JS_PARSE_EXPORT_NONE,\n                                   NULL);\n}\n\nstatic __exception int js_parse_program(JSParseState *s)\n{\n    JSFunctionDef *fd = s->cur_func;\n    int idx;\n\n    if (next_token(s))\n        return -1;\n\n    if (js_parse_directives(s))\n        return -1;\n\n    fd->is_global_var = (fd->eval_type == JS_EVAL_TYPE_GLOBAL) ||\n        (fd->eval_type == JS_EVAL_TYPE_MODULE) ||\n        !(fd->js_mode & JS_MODE_STRICT);\n\n    if (!s->is_module) {\n        /* hidden variable for the return value */\n        fd->eval_ret_idx = idx = add_var(s->ctx, fd, JS_ATOM__ret_);\n        if (idx < 0)\n            return -1;\n    }\n\n    while (s->token.val != TOK_EOF) {\n        if (js_parse_source_element(s))\n            return -1;\n    }\n\n    if (!s->is_module) {\n        /* return the value of the hidden variable eval_ret_idx  */\n        emit_op(s, OP_get_loc);\n        emit_u16(s, fd->eval_ret_idx);\n\n        emit_op(s, OP_return);\n    } else {\n        emit_op(s, OP_return_undef);\n    }\n\n    return 0;\n}\n\nstatic void js_parse_init(JSContext *ctx, JSParseState *s,\n                          const char *input, size_t input_len,\n                          const char *filename)\n{\n    memset(s, 0, sizeof(*s));\n    s->ctx = ctx;\n    s->filename = filename;\n    s->line_num = 1;\n    s->buf_ptr = (const uint8_t *)input;\n    s->buf_end = s->buf_ptr + input_len;\n    s->token.val = ' ';\n    s->token.line_num = 1;\n}\n\nstatic JSValue JS_EvalFunctionInternal(JSContext *ctx, JSValue fun_obj,\n                                       JSValueConst this_obj,\n                                       JSVarRef **var_refs, JSStackFrame *sf)\n{\n    JSValue ret_val;\n    uint32_t tag;\n\n    tag = JS_VALUE_GET_TAG(fun_obj);\n    if (tag == JS_TAG_FUNCTION_BYTECODE) {\n        fun_obj = js_closure(ctx, fun_obj, var_refs, sf);\n        ret_val = JS_CallFree(ctx, fun_obj, this_obj, 0, NULL);\n    } else if (tag == JS_TAG_MODULE) {\n        JSModuleDef *m;\n        m = JS_VALUE_GET_PTR(fun_obj);\n        /* the module refcount should be >= 2 */\n        JS_FreeValue(ctx, fun_obj);\n        if (js_create_module_function(ctx, m) < 0)\n            goto fail;\n        if (js_link_module(ctx, m) < 0)\n            goto fail;\n        ret_val = js_evaluate_module(ctx, m);\n        if (JS_IsException(ret_val)) {\n        fail:\n            js_free_modules(ctx, JS_FREE_MODULE_NOT_EVALUATED);\n            return JS_EXCEPTION;\n        }\n    } else {\n        JS_FreeValue(ctx, fun_obj);\n        ret_val = JS_ThrowTypeError(ctx, \"bytecode function expected\");\n    }\n    return ret_val;\n}\n\nJSValue JS_EvalFunction(JSContext *ctx, JSValue fun_obj)\n{\n    return JS_EvalFunctionInternal(ctx, fun_obj, ctx->global_obj, NULL, NULL);\n}\n\nstatic void skip_shebang(JSParseState *s)\n{\n    const uint8_t *p = s->buf_ptr;\n    int c;\n\n    if (p[0] == '#' && p[1] == '!') {\n        p += 2;\n        while (p < s->buf_end) {\n            if (*p == '\\n' || *p == '\\r') {\n                break;\n            } else if (*p >= 0x80) {\n                c = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p);\n                if (c == CP_LS || c == CP_PS) {\n                    break;\n                } else if (c == -1) {\n                    p++; /* skip invalid UTF-8 */\n                }\n            } else {\n                p++;\n            }\n        }\n        s->buf_ptr = p;\n    }\n}\n\n/* 'input' must be zero terminated i.e. input[input_len] = '\\0'. */\nstatic JSValue __JS_EvalInternal(JSContext *ctx, JSValueConst this_obj,\n                                 const char *input, size_t input_len,\n                                 const char *filename, int flags, int scope_idx)\n{\n    JSParseState s1, *s = &s1;\n    int err, js_mode, eval_type;\n    JSValue fun_obj, ret_val;\n    JSStackFrame *sf;\n    JSVarRef **var_refs;\n    JSFunctionBytecode *b;\n    JSFunctionDef *fd;\n    JSModuleDef *m;\n\n    js_parse_init(ctx, s, input, input_len, filename);\n    skip_shebang(s);\n\n    eval_type = flags & JS_EVAL_TYPE_MASK;\n    m = NULL;\n    if (eval_type == JS_EVAL_TYPE_DIRECT) {\n        JSObject *p;\n        sf = ctx->rt->current_stack_frame;\n        assert(sf != NULL);\n        assert(JS_VALUE_GET_TAG(sf->cur_func) == JS_TAG_OBJECT);\n        p = JS_VALUE_GET_OBJ(sf->cur_func);\n        assert(js_class_has_bytecode(p->class_id));\n        b = p->u.func.function_bytecode;\n        var_refs = p->u.func.var_refs;\n        js_mode = b->js_mode;\n    } else {\n        sf = NULL;\n        b = NULL;\n        var_refs = NULL;\n        js_mode = 0;\n        if (flags & JS_EVAL_FLAG_STRICT)\n            js_mode |= JS_MODE_STRICT;\n        if (flags & JS_EVAL_FLAG_STRIP)\n            js_mode |= JS_MODE_STRIP;\n        if (eval_type == JS_EVAL_TYPE_MODULE) {\n            JSAtom module_name = JS_NewAtom(ctx, filename);\n            if (module_name == JS_ATOM_NULL)\n                return JS_EXCEPTION;\n            m = js_new_module_def(ctx, module_name);\n            if (!m)\n                return JS_EXCEPTION;\n            js_mode |= JS_MODE_STRICT;\n        }\n    }\n    fd = js_new_function_def(ctx, NULL, TRUE, FALSE, filename, 1);\n    if (!fd)\n        goto fail1;\n    s->cur_func = fd;\n    fd->eval_type = eval_type;\n    fd->has_this_binding = (eval_type != JS_EVAL_TYPE_DIRECT);\n    fd->backtrace_barrier = ((flags & JS_EVAL_FLAG_BACKTRACE_BARRIER) != 0);\n    if (eval_type == JS_EVAL_TYPE_DIRECT) {\n        fd->new_target_allowed = b->new_target_allowed;\n        fd->super_call_allowed = b->super_call_allowed;\n        fd->super_allowed = b->super_allowed;\n        fd->arguments_allowed = b->arguments_allowed;\n    } else {\n        fd->new_target_allowed = FALSE;\n        fd->super_call_allowed = FALSE;\n        fd->super_allowed = FALSE;\n        fd->arguments_allowed = TRUE;\n    }\n    fd->js_mode = js_mode;\n    fd->func_name = JS_DupAtom(ctx, JS_ATOM__eval_);\n    if (b) {\n        if (add_closure_variables(ctx, fd, b, scope_idx))\n            goto fail;\n    }\n    fd->module = m;\n    s->is_module = (m != NULL);\n    s->allow_html_comments = !s->is_module;\n\n    push_scope(s); /* body scope */\n    fd->body_scope = fd->scope_level;\n    \n    err = js_parse_program(s);\n    if (err) {\n    fail:\n        free_token(s, &s->token);\n        js_free_function_def(ctx, fd);\n        goto fail1;\n    }\n\n    /* create the function object and all the enclosed functions */\n    fun_obj = js_create_function(ctx, fd);\n    if (JS_IsException(fun_obj))\n        goto fail1;\n    /* Could add a flag to avoid resolution if necessary */\n    if (m) {\n        m->func_obj = fun_obj;\n        if (js_resolve_module(ctx, m) < 0)\n            goto fail1;\n        fun_obj = JS_DupValue(ctx, JS_MKPTR(JS_TAG_MODULE, m));\n    }\n    if (flags & JS_EVAL_FLAG_COMPILE_ONLY) {\n        ret_val = fun_obj;\n    } else {\n        ret_val = JS_EvalFunctionInternal(ctx, fun_obj, this_obj, var_refs, sf);\n    }\n    return ret_val;\n fail1:\n    /* XXX: should free all the unresolved dependencies */\n    if (m)\n        js_free_module_def(ctx, m);\n    return JS_EXCEPTION;\n}\n\n/* the indirection is needed to make 'eval' optional */\nstatic JSValue JS_EvalInternal(JSContext *ctx, JSValueConst this_obj,\n                               const char *input, size_t input_len,\n                               const char *filename, int flags, int scope_idx)\n{\n    if (unlikely(!ctx->eval_internal)) {\n        return JS_ThrowTypeError(ctx, \"eval is not supported\");\n    }\n    return ctx->eval_internal(ctx, this_obj, input, input_len, filename,\n                              flags, scope_idx);\n}\n\nstatic JSValue JS_EvalObject(JSContext *ctx, JSValueConst this_obj,\n                             JSValueConst val, int flags, int scope_idx)\n{\n    JSValue ret;\n    const char *str;\n    size_t len;\n\n    if (!JS_IsString(val))\n        return JS_DupValue(ctx, val);\n    str = JS_ToCStringLen(ctx, &len, val);\n    if (!str)\n        return JS_EXCEPTION;\n    ret = JS_EvalInternal(ctx, this_obj, str, len, \"<input>\", flags, scope_idx);\n    JS_FreeCString(ctx, str);\n    return ret;\n\n}\n\nJSValue JS_EvalThis(JSContext *ctx, JSValueConst this_obj,\n                    const char *input, size_t input_len,\n                    const char *filename, int eval_flags)\n{\n    int eval_type = eval_flags & JS_EVAL_TYPE_MASK;\n    JSValue ret;\n\n    assert(eval_type == JS_EVAL_TYPE_GLOBAL ||\n           eval_type == JS_EVAL_TYPE_MODULE);\n    ret = JS_EvalInternal(ctx, this_obj, input, input_len, filename,\n                          eval_flags, -1);\n    return ret;\n}\n\nJSValue JS_Eval(JSContext *ctx, const char *input, size_t input_len,\n                const char *filename, int eval_flags)\n{\n    return JS_EvalThis(ctx, ctx->global_obj, input, input_len, filename,\n                       eval_flags);\n}\n\nint JS_ResolveModule(JSContext *ctx, JSValueConst obj)\n{\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) {\n        JSModuleDef *m = JS_VALUE_GET_PTR(obj);\n        if (js_resolve_module(ctx, m) < 0) {\n            js_free_modules(ctx, JS_FREE_MODULE_NOT_RESOLVED);\n            return -1;\n        }\n    }\n    return 0;\n}\n\n/*******************************************************************/\n/* object list */\n\ntypedef struct {\n    JSObject *obj;\n    uint32_t hash_next; /* -1 if no next entry */\n} JSObjectListEntry;\n\n/* XXX: reuse it to optimize weak references */\ntypedef struct {\n    JSObjectListEntry *object_tab;\n    int object_count;\n    int object_size;\n    uint32_t *hash_table;\n    uint32_t hash_size;\n} JSObjectList;\n\nstatic void js_object_list_init(JSObjectList *s)\n{\n    memset(s, 0, sizeof(*s));\n}\n\nstatic uint32_t js_object_list_get_hash(JSObject *p, uint32_t hash_size)\n{\n    return ((uintptr_t)p * 3163) & (hash_size - 1);\n}\n\nstatic int js_object_list_resize_hash(JSContext *ctx, JSObjectList *s,\n                                 uint32_t new_hash_size)\n{\n    JSObjectListEntry *e;\n    uint32_t i, h, *new_hash_table;\n\n    new_hash_table = js_malloc(ctx, sizeof(new_hash_table[0]) * new_hash_size);\n    if (!new_hash_table)\n        return -1;\n    js_free(ctx, s->hash_table);\n    s->hash_table = new_hash_table;\n    s->hash_size = new_hash_size;\n    \n    for(i = 0; i < s->hash_size; i++) {\n        s->hash_table[i] = -1;\n    }\n    for(i = 0; i < s->object_count; i++) {\n        e = &s->object_tab[i];\n        h = js_object_list_get_hash(e->obj, s->hash_size); \n        e->hash_next = s->hash_table[h];\n        s->hash_table[h] = i;\n    }\n    return 0;\n}\n\n/* the reference count of 'obj' is not modified. Return 0 if OK, -1 if\n   memory error */\nstatic int js_object_list_add(JSContext *ctx, JSObjectList *s, JSObject *obj)\n{\n    JSObjectListEntry *e;\n    uint32_t h, new_hash_size;\n    \n    if (js_resize_array(ctx, (void *)&s->object_tab,\n                        sizeof(s->object_tab[0]),\n                        &s->object_size, s->object_count + 1))\n        return -1;\n    if (unlikely((s->object_count + 1) >= s->hash_size)) {\n        new_hash_size = max_uint32(s->hash_size, 4);\n        while (new_hash_size <= s->object_count)\n            new_hash_size *= 2;\n        if (js_object_list_resize_hash(ctx, s, new_hash_size))\n            return -1;\n    }\n    e = &s->object_tab[s->object_count++];\n    h = js_object_list_get_hash(obj, s->hash_size); \n    e->obj = obj;\n    e->hash_next = s->hash_table[h];\n    s->hash_table[h] = s->object_count - 1;\n    return 0;\n}\n\n/* return -1 if not present or the object index */\nstatic int js_object_list_find(JSContext *ctx, JSObjectList *s, JSObject *obj)\n{\n    JSObjectListEntry *e;\n    uint32_t h, p;\n\n    /* must test empty size because there is no hash table */\n    if (s->object_count == 0)\n        return -1;\n    h = js_object_list_get_hash(obj, s->hash_size); \n    p = s->hash_table[h];\n    while (p != -1) {\n        e = &s->object_tab[p];\n        if (e->obj == obj)\n            return p;\n        p = e->hash_next;\n    }\n    return -1;\n}\n\nstatic void js_object_list_end(JSContext *ctx, JSObjectList *s)\n{\n    js_free(ctx, s->object_tab);\n    js_free(ctx, s->hash_table);\n}\n\n/*******************************************************************/\n/* binary object writer & reader */\n\ntypedef enum BCTagEnum {\n    BC_TAG_NULL = 1,\n    BC_TAG_UNDEFINED,\n    BC_TAG_BOOL_FALSE,\n    BC_TAG_BOOL_TRUE,\n    BC_TAG_INT32,\n    BC_TAG_FLOAT64,\n    BC_TAG_STRING,\n    BC_TAG_OBJECT,\n    BC_TAG_ARRAY,\n    BC_TAG_BIG_INT,\n    BC_TAG_BIG_FLOAT,\n    BC_TAG_BIG_DECIMAL,\n    BC_TAG_TEMPLATE_OBJECT,\n    BC_TAG_FUNCTION_BYTECODE,\n    BC_TAG_MODULE,\n    BC_TAG_TYPED_ARRAY,\n    BC_TAG_ARRAY_BUFFER,\n    BC_TAG_SHARED_ARRAY_BUFFER,\n    BC_TAG_DATE,\n    BC_TAG_OBJECT_VALUE,\n    BC_TAG_OBJECT_REFERENCE,\n} BCTagEnum;\n\n#ifdef CONFIG_BIGNUM\n#define BC_BASE_VERSION 2\n#else\n#define BC_BASE_VERSION 1\n#endif\n#define BC_BE_VERSION 0x40\n#ifdef WORDS_BIGENDIAN\n#define BC_VERSION (BC_BASE_VERSION | BC_BE_VERSION)\n#else\n#define BC_VERSION BC_BASE_VERSION\n#endif\n\ntypedef struct BCWriterState {\n    JSContext *ctx;\n    DynBuf dbuf;\n    BOOL byte_swap : 8;\n    BOOL allow_bytecode : 8;\n    BOOL allow_sab : 8;\n    BOOL allow_reference : 8;\n    uint32_t first_atom;\n    uint32_t *atom_to_idx;\n    int atom_to_idx_size;\n    JSAtom *idx_to_atom;\n    int idx_to_atom_count;\n    int idx_to_atom_size;\n    uint8_t **sab_tab;\n    int sab_tab_len;\n    int sab_tab_size;\n    /* list of referenced objects (used if allow_reference = TRUE) */\n    JSObjectList object_list;\n} BCWriterState;\n\n#ifdef DUMP_READ_OBJECT\nstatic const char * const bc_tag_str[] = {\n    \"invalid\",\n    \"null\",\n    \"undefined\",\n    \"false\",\n    \"true\",\n    \"int32\",\n    \"float64\",\n    \"string\",\n    \"object\",\n    \"array\",\n    \"bigint\",\n    \"bigfloat\",\n    \"bigdecimal\",\n    \"template\",\n    \"function\",\n    \"module\",\n    \"TypedArray\",\n    \"ArrayBuffer\",\n    \"SharedArrayBuffer\",\n    \"Date\",\n    \"ObjectValue\",\n    \"ObjectReference\",\n};\n#endif\n\nstatic void bc_put_u8(BCWriterState *s, uint8_t v)\n{\n    dbuf_putc(&s->dbuf, v);\n}\n\nstatic void bc_put_u16(BCWriterState *s, uint16_t v)\n{\n    if (s->byte_swap)\n        v = bswap16(v);\n    dbuf_put_u16(&s->dbuf, v);\n}\n\nstatic __maybe_unused void bc_put_u32(BCWriterState *s, uint32_t v)\n{\n    if (s->byte_swap)\n        v = bswap32(v);\n    dbuf_put_u32(&s->dbuf, v);\n}\n\nstatic void bc_put_u64(BCWriterState *s, uint64_t v)\n{\n    if (s->byte_swap)\n        v = bswap64(v);\n    dbuf_put(&s->dbuf, (uint8_t *)&v, sizeof(v));\n}\n\nstatic void bc_put_leb128(BCWriterState *s, uint32_t v)\n{\n    dbuf_put_leb128(&s->dbuf, v);\n}\n\nstatic void bc_put_sleb128(BCWriterState *s, int32_t v)\n{\n    dbuf_put_sleb128(&s->dbuf, v);\n}\n\nstatic void bc_set_flags(uint32_t *pflags, int *pidx, uint32_t val, int n)\n{\n    *pflags = *pflags | (val << *pidx);\n    *pidx += n;\n}\n\nstatic int bc_atom_to_idx(BCWriterState *s, uint32_t *pres, JSAtom atom)\n{\n    uint32_t v;\n\n    if (atom < s->first_atom || __JS_AtomIsTaggedInt(atom)) {\n        *pres = atom;\n        return 0;\n    }\n    atom -= s->first_atom;\n    if (atom < s->atom_to_idx_size && s->atom_to_idx[atom] != 0) {\n        *pres = s->atom_to_idx[atom];\n        return 0;\n    }\n    if (atom >= s->atom_to_idx_size) {\n        int old_size, i;\n        old_size = s->atom_to_idx_size;\n        if (js_resize_array(s->ctx, (void **)&s->atom_to_idx,\n                            sizeof(s->atom_to_idx[0]), &s->atom_to_idx_size,\n                            atom + 1))\n            return -1;\n        /* XXX: could add a specific js_resize_array() function to do it */\n        for(i = old_size; i < s->atom_to_idx_size; i++)\n            s->atom_to_idx[i] = 0;\n    }\n    if (js_resize_array(s->ctx, (void **)&s->idx_to_atom,\n                        sizeof(s->idx_to_atom[0]),\n                        &s->idx_to_atom_size, s->idx_to_atom_count + 1))\n        goto fail;\n\n    v = s->idx_to_atom_count++;\n    s->idx_to_atom[v] = atom + s->first_atom;\n    v += s->first_atom;\n    s->atom_to_idx[atom] = v;\n    *pres = v;\n    return 0;\n fail:\n    *pres = 0;\n    return -1;\n}\n\nstatic int bc_put_atom(BCWriterState *s, JSAtom atom)\n{\n    uint32_t v;\n\n    if (__JS_AtomIsTaggedInt(atom)) {\n        v = (__JS_AtomToUInt32(atom) << 1) | 1;\n    } else {\n        if (bc_atom_to_idx(s, &v, atom))\n            return -1;\n        v <<= 1;\n    }\n    bc_put_leb128(s, v);\n    return 0;\n}\n\nstatic void bc_byte_swap(uint8_t *bc_buf, int bc_len)\n{\n    int pos, len, op, fmt;\n\n    pos = 0;\n    while (pos < bc_len) {\n        op = bc_buf[pos];\n        len = short_opcode_info(op).size;\n        fmt = short_opcode_info(op).fmt;\n        switch(fmt) {\n        case OP_FMT_u16:\n        case OP_FMT_i16:\n        case OP_FMT_label16:\n        case OP_FMT_npop:\n        case OP_FMT_loc:\n        case OP_FMT_arg:\n        case OP_FMT_var_ref:\n            put_u16(bc_buf + pos + 1,\n                    bswap16(get_u16(bc_buf + pos + 1)));\n            break;\n        case OP_FMT_i32:\n        case OP_FMT_u32:\n        case OP_FMT_const:\n        case OP_FMT_label:\n        case OP_FMT_atom:\n        case OP_FMT_atom_u8:\n            put_u32(bc_buf + pos + 1,\n                    bswap32(get_u32(bc_buf + pos + 1)));\n            break;\n        case OP_FMT_atom_u16:\n        case OP_FMT_label_u16:\n            put_u32(bc_buf + pos + 1,\n                    bswap32(get_u32(bc_buf + pos + 1)));\n            put_u16(bc_buf + pos + 1 + 4,\n                    bswap16(get_u16(bc_buf + pos + 1 + 4)));\n            break;\n        case OP_FMT_atom_label_u8:\n        case OP_FMT_atom_label_u16:\n            put_u32(bc_buf + pos + 1,\n                    bswap32(get_u32(bc_buf + pos + 1)));\n            put_u32(bc_buf + pos + 1 + 4,\n                    bswap32(get_u32(bc_buf + pos + 1 + 4)));\n            if (fmt == OP_FMT_atom_label_u16) {\n                put_u16(bc_buf + pos + 1 + 4 + 4,\n                        bswap16(get_u16(bc_buf + pos + 1 + 4 + 4)));\n            }\n            break;\n        case OP_FMT_npop_u16:\n            put_u16(bc_buf + pos + 1,\n                    bswap16(get_u16(bc_buf + pos + 1)));\n            put_u16(bc_buf + pos + 1 + 2,\n                    bswap16(get_u16(bc_buf + pos + 1 + 2)));\n            break;\n        default:\n            break;\n        }\n        pos += len;\n    }\n}\n\nstatic int JS_WriteFunctionBytecode(BCWriterState *s,\n                                    const uint8_t *bc_buf1, int bc_len)\n{\n    int pos, len, op;\n    JSAtom atom;\n    uint8_t *bc_buf;\n    uint32_t val;\n\n    bc_buf = js_malloc(s->ctx, bc_len);\n    if (!bc_buf)\n        return -1;\n    memcpy(bc_buf, bc_buf1, bc_len);\n\n    pos = 0;\n    while (pos < bc_len) {\n        op = bc_buf[pos];\n        len = short_opcode_info(op).size;\n        switch(short_opcode_info(op).fmt) {\n        case OP_FMT_atom:\n        case OP_FMT_atom_u8:\n        case OP_FMT_atom_u16:\n        case OP_FMT_atom_label_u8:\n        case OP_FMT_atom_label_u16:\n            atom = get_u32(bc_buf + pos + 1);\n            if (bc_atom_to_idx(s, &val, atom))\n                goto fail;\n            put_u32(bc_buf + pos + 1, val);\n            break;\n        default:\n            break;\n        }\n        pos += len;\n    }\n\n    if (s->byte_swap)\n        bc_byte_swap(bc_buf, bc_len);\n\n    dbuf_put(&s->dbuf, bc_buf, bc_len);\n\n    js_free(s->ctx, bc_buf);\n    return 0;\n fail:\n    js_free(s->ctx, bc_buf);\n    return -1;\n}\n\nstatic void JS_WriteString(BCWriterState *s, JSString *p)\n{\n    int i;\n    bc_put_leb128(s, ((uint32_t)p->len << 1) | p->is_wide_char);\n    if (p->is_wide_char) {\n        for(i = 0; i < p->len; i++)\n            bc_put_u16(s, p->u.str16[i]);\n    } else {\n        dbuf_put(&s->dbuf, p->u.str8, p->len);\n    }\n}\n\n#ifdef CONFIG_BIGNUM\nstatic int JS_WriteBigNum(BCWriterState *s, JSValueConst obj)\n{\n    uint32_t tag, tag1;\n    int64_t e;\n    JSBigFloat *bf = JS_VALUE_GET_PTR(obj);\n    bf_t *a = &bf->num;\n    size_t len, i, n1, j;\n    limb_t v;\n\n    tag = JS_VALUE_GET_TAG(obj);\n    switch(tag) {\n    case JS_TAG_BIG_INT:\n        tag1 = BC_TAG_BIG_INT;\n        break;\n    case JS_TAG_BIG_FLOAT:\n        tag1 = BC_TAG_BIG_FLOAT;\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        tag1 = BC_TAG_BIG_DECIMAL;\n        break;\n    default:\n        abort();\n    }\n    bc_put_u8(s, tag1);\n\n    /* sign + exponent */\n    if (a->expn == BF_EXP_ZERO)\n        e = 0;\n    else if (a->expn == BF_EXP_INF)\n        e = 1;\n    else if (a->expn == BF_EXP_NAN)\n        e = 2;\n    else if (a->expn >= 0)\n        e = a->expn + 3;\n    else\n        e = a->expn;\n    e = (e << 1) | a->sign;\n    if (e < INT32_MIN || e > INT32_MAX) {\n        JS_ThrowInternalError(s->ctx, \"bignum exponent is too large\");\n        return -1;\n    }\n    bc_put_sleb128(s, e);\n\n    /* mantissa */\n    if (a->len != 0) {\n        if (tag != JS_TAG_BIG_DECIMAL) {\n            i = 0;\n            while (i < a->len && a->tab[i] == 0)\n                i++;\n            assert(i < a->len);\n            v = a->tab[i];\n            n1 = sizeof(limb_t);\n            while ((v & 0xff) == 0) {\n                n1--;\n                v >>= 8;\n            }\n            i++;\n            len = (a->len - i) * sizeof(limb_t) + n1;\n            if (len > INT32_MAX) {\n                JS_ThrowInternalError(s->ctx, \"bignum is too large\");\n                return -1;\n            }\n            bc_put_leb128(s, len);\n            /* always saved in byte based little endian representation */\n            for(j = 0; j < n1; j++) {\n                dbuf_putc(&s->dbuf, v >> (j * 8));\n            }\n            for(; i < a->len; i++) {\n                limb_t v = a->tab[i];\n#if LIMB_BITS == 32\n#ifdef WORDS_BIGENDIAN\n                v = bswap32(v);\n#endif\n                dbuf_put_u32(&s->dbuf, v);\n#else\n#ifdef WORDS_BIGENDIAN\n                v = bswap64(v);\n#endif\n                dbuf_put_u64(&s->dbuf, v);\n#endif\n            }\n        } else {\n            int bpos, d;\n            uint8_t v8;\n            size_t i0;\n            \n            /* little endian BCD */\n            i = 0;\n            while (i < a->len && a->tab[i] == 0)\n                i++;\n            assert(i < a->len);\n            len = a->len * LIMB_DIGITS;\n            v = a->tab[i];\n            j = 0;\n            while ((v % 10) == 0) {\n                j++;\n                v /= 10;\n            }\n            len -= j;\n            assert(len > 0);\n            if (len > INT32_MAX) {\n                JS_ThrowInternalError(s->ctx, \"bignum is too large\");\n                return -1;\n            }\n            bc_put_leb128(s, len);\n            \n            bpos = 0;\n            v8 = 0;\n            i0 = i;\n            for(; i < a->len; i++) {\n                if (i != i0) {\n                    v = a->tab[i];\n                    j = 0;\n                }\n                for(; j < LIMB_DIGITS; j++) {\n                    d = v % 10;\n                    v /= 10;\n                    if (bpos == 0) {\n                        v8 = d;\n                        bpos = 1;\n                    } else {\n                        dbuf_putc(&s->dbuf, v8 | (d << 4));\n                        bpos = 0;\n                    }\n                }\n            }\n            /* flush the last digit */\n            if (bpos) {\n                dbuf_putc(&s->dbuf, v8);\n            }\n        }\n    }\n    return 0;\n}\n#endif /* CONFIG_BIGNUM */\n\nstatic int JS_WriteObjectRec(BCWriterState *s, JSValueConst obj);\n\nstatic int JS_WriteFunctionTag(BCWriterState *s, JSValueConst obj)\n{\n    JSFunctionBytecode *b = JS_VALUE_GET_PTR(obj);\n    uint32_t flags;\n    int idx, i;\n    \n    bc_put_u8(s, BC_TAG_FUNCTION_BYTECODE);\n    flags = idx = 0;\n    bc_set_flags(&flags, &idx, b->has_prototype, 1);\n    bc_set_flags(&flags, &idx, b->has_simple_parameter_list, 1);\n    bc_set_flags(&flags, &idx, b->is_derived_class_constructor, 1);\n    bc_set_flags(&flags, &idx, b->need_home_object, 1);\n    bc_set_flags(&flags, &idx, b->func_kind, 2);\n    bc_set_flags(&flags, &idx, b->new_target_allowed, 1);\n    bc_set_flags(&flags, &idx, b->super_call_allowed, 1);\n    bc_set_flags(&flags, &idx, b->super_allowed, 1);\n    bc_set_flags(&flags, &idx, b->arguments_allowed, 1);\n    bc_set_flags(&flags, &idx, b->has_debug, 1);\n    bc_set_flags(&flags, &idx, b->backtrace_barrier, 1);\n    assert(idx <= 16);\n    bc_put_u16(s, flags);\n    bc_put_u8(s, b->js_mode);\n    bc_put_atom(s, b->func_name);\n    \n    bc_put_leb128(s, b->arg_count);\n    bc_put_leb128(s, b->var_count);\n    bc_put_leb128(s, b->defined_arg_count);\n    bc_put_leb128(s, b->stack_size);\n    bc_put_leb128(s, b->closure_var_count);\n    bc_put_leb128(s, b->cpool_count);\n    bc_put_leb128(s, b->byte_code_len);\n    if (b->vardefs) {\n        /* XXX: this field is redundant */\n        bc_put_leb128(s, b->arg_count + b->var_count);\n        for(i = 0; i < b->arg_count + b->var_count; i++) {\n            JSVarDef *vd = &b->vardefs[i];\n            bc_put_atom(s, vd->var_name);\n            bc_put_leb128(s, vd->scope_level);\n            bc_put_leb128(s, vd->scope_next + 1);\n            flags = idx = 0;\n            bc_set_flags(&flags, &idx, vd->var_kind, 4);\n            bc_set_flags(&flags, &idx, vd->is_const, 1);\n            bc_set_flags(&flags, &idx, vd->is_lexical, 1);\n            bc_set_flags(&flags, &idx, vd->is_captured, 1);\n            assert(idx <= 8);\n            bc_put_u8(s, flags);\n        }\n    } else {\n        bc_put_leb128(s, 0);\n    }\n    \n    for(i = 0; i < b->closure_var_count; i++) {\n        JSClosureVar *cv = &b->closure_var[i];\n        bc_put_atom(s, cv->var_name);\n        bc_put_leb128(s, cv->var_idx);\n        flags = idx = 0;\n        bc_set_flags(&flags, &idx, cv->is_local, 1);\n        bc_set_flags(&flags, &idx, cv->is_arg, 1);\n        bc_set_flags(&flags, &idx, cv->is_const, 1);\n        bc_set_flags(&flags, &idx, cv->is_lexical, 1);\n        bc_set_flags(&flags, &idx, cv->var_kind, 4);\n        assert(idx <= 8);\n        bc_put_u8(s, flags);\n    }\n    \n    if (JS_WriteFunctionBytecode(s, b->byte_code_buf, b->byte_code_len))\n        goto fail;\n    \n    if (b->has_debug) {\n        bc_put_atom(s, b->debug.filename);\n        bc_put_leb128(s, b->debug.line_num);\n        bc_put_leb128(s, b->debug.pc2line_len);\n        dbuf_put(&s->dbuf, b->debug.pc2line_buf, b->debug.pc2line_len);\n    }\n    \n    for(i = 0; i < b->cpool_count; i++) {\n        if (JS_WriteObjectRec(s, b->cpool[i]))\n            goto fail;\n    }\n    return 0;\n fail:\n    return -1;\n}\n\nstatic int JS_WriteModule(BCWriterState *s, JSValueConst obj)\n{\n    JSModuleDef *m = JS_VALUE_GET_PTR(obj);\n    int i;\n    \n    bc_put_u8(s, BC_TAG_MODULE);\n    bc_put_atom(s, m->module_name);\n    \n    bc_put_leb128(s, m->req_module_entries_count);\n    for(i = 0; i < m->req_module_entries_count; i++) {\n        JSReqModuleEntry *rme = &m->req_module_entries[i];\n        bc_put_atom(s, rme->module_name);\n    }\n    \n    bc_put_leb128(s, m->export_entries_count);\n    for(i = 0; i < m->export_entries_count; i++) {\n        JSExportEntry *me = &m->export_entries[i];\n        bc_put_u8(s, me->export_type);\n        if (me->export_type == JS_EXPORT_TYPE_LOCAL) {\n            bc_put_leb128(s, me->u.local.var_idx);\n        } else {\n            bc_put_leb128(s, me->u.req_module_idx);\n            bc_put_atom(s, me->local_name);\n        }\n        bc_put_atom(s, me->export_name);\n    }\n    \n    bc_put_leb128(s, m->star_export_entries_count);\n    for(i = 0; i < m->star_export_entries_count; i++) {\n        JSStarExportEntry *se = &m->star_export_entries[i];\n        bc_put_leb128(s, se->req_module_idx);\n    }\n    \n    bc_put_leb128(s, m->import_entries_count);\n    for(i = 0; i < m->import_entries_count; i++) {\n        JSImportEntry *mi = &m->import_entries[i];\n        bc_put_leb128(s, mi->var_idx);\n        bc_put_atom(s, mi->import_name);\n        bc_put_leb128(s, mi->req_module_idx);\n    }\n    \n    if (JS_WriteObjectRec(s, m->func_obj))\n        goto fail;\n    return 0;\n fail:\n    return -1;\n}\n\nstatic int JS_WriteArray(BCWriterState *s, JSValueConst obj)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(obj);\n    uint32_t i, len;\n    JSValue val;\n    int ret;\n    BOOL is_template;\n    \n    if (s->allow_bytecode && !p->extensible) {\n        /* not extensible array: we consider it is a\n           template when we are saving bytecode */\n        bc_put_u8(s, BC_TAG_TEMPLATE_OBJECT);\n        is_template = TRUE;\n    } else {\n        bc_put_u8(s, BC_TAG_ARRAY);\n        is_template = FALSE;\n    }\n    if (js_get_length32(s->ctx, &len, obj))\n        goto fail1;\n    bc_put_leb128(s, len);\n    for(i = 0; i < len; i++) {\n        val = JS_GetPropertyUint32(s->ctx, obj, i);\n        if (JS_IsException(val))\n            goto fail1;\n        ret = JS_WriteObjectRec(s, val);\n        JS_FreeValue(s->ctx, val);\n        if (ret)\n            goto fail1;\n    }\n    if (is_template) {\n        val = JS_GetProperty(s->ctx, obj, JS_ATOM_raw);\n        if (JS_IsException(val))\n            goto fail1;\n        ret = JS_WriteObjectRec(s, val);\n        JS_FreeValue(s->ctx, val);\n        if (ret)\n            goto fail1;\n    }\n    return 0;\n fail1:\n    return -1;\n}\n\nstatic int JS_WriteObjectTag(BCWriterState *s, JSValueConst obj)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(obj);\n    uint32_t i, prop_count;\n    JSShape *sh;\n    JSShapeProperty *pr;\n    int pass;\n    JSAtom atom;\n\n    bc_put_u8(s, BC_TAG_OBJECT);\n    prop_count = 0;\n    sh = p->shape;\n    for(pass = 0; pass < 2; pass++) {\n        if (pass == 1)\n            bc_put_leb128(s, prop_count);\n        for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count; i++, pr++) {\n            atom = pr->atom;\n            if (atom != JS_ATOM_NULL &&\n                JS_AtomIsString(s->ctx, atom) &&\n                (pr->flags & JS_PROP_ENUMERABLE)) {\n                if (pr->flags & JS_PROP_TMASK) {\n                    JS_ThrowTypeError(s->ctx, \"only value properties are supported\");\n                    goto fail;\n                }\n                if (pass == 0) {\n                    prop_count++;\n                } else {\n                    bc_put_atom(s, atom);\n                    if (JS_WriteObjectRec(s, p->prop[i].u.value))\n                        goto fail;\n                }\n            }\n        }\n    }\n    return 0;\n fail:\n    return -1;\n}\n\nstatic int JS_WriteTypedArray(BCWriterState *s, JSValueConst obj)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(obj);\n    JSTypedArray *ta = p->u.typed_array;\n\n    bc_put_u8(s, BC_TAG_TYPED_ARRAY);\n    bc_put_u8(s, p->class_id - JS_CLASS_UINT8C_ARRAY);\n    bc_put_leb128(s, p->u.array.count);\n    bc_put_leb128(s, ta->offset);\n    if (JS_WriteObjectRec(s, JS_MKPTR(JS_TAG_OBJECT, ta->buffer)))\n        return -1;\n    return 0;\n}\n\nstatic int JS_WriteArrayBuffer(BCWriterState *s, JSValueConst obj)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(obj);\n    JSArrayBuffer *abuf = p->u.array_buffer;\n    if (abuf->detached) {\n        JS_ThrowTypeErrorDetachedArrayBuffer(s->ctx);\n        return -1;\n    }\n    bc_put_u8(s, BC_TAG_ARRAY_BUFFER);\n    bc_put_leb128(s, abuf->byte_length);\n    dbuf_put(&s->dbuf, abuf->data, abuf->byte_length);\n    return 0;\n}\n\nstatic int JS_WriteSharedArrayBuffer(BCWriterState *s, JSValueConst obj)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(obj);\n    JSArrayBuffer *abuf = p->u.array_buffer;\n    assert(!abuf->detached); /* SharedArrayBuffer are never detached */\n    bc_put_u8(s, BC_TAG_SHARED_ARRAY_BUFFER);\n    bc_put_leb128(s, abuf->byte_length);\n    bc_put_u64(s, (uintptr_t)abuf->data);\n    if (js_resize_array(s->ctx, (void **)&s->sab_tab, sizeof(s->sab_tab[0]),\n                        &s->sab_tab_size, s->sab_tab_len + 1))\n        return -1;\n    /* keep the SAB pointer so that the user can clone it or free it */\n    s->sab_tab[s->sab_tab_len++] = abuf->data;\n    return 0;\n}\n\nstatic int JS_WriteObjectRec(BCWriterState *s, JSValueConst obj)\n{\n    uint32_t tag;\n\n    if (js_check_stack_overflow(s->ctx->rt, 0)) {\n        JS_ThrowStackOverflow(s->ctx);\n        return -1;\n    }\n\n    tag = JS_VALUE_GET_NORM_TAG(obj);\n    switch(tag) {\n    case JS_TAG_NULL:\n        bc_put_u8(s, BC_TAG_NULL);\n        break;\n    case JS_TAG_UNDEFINED:\n        bc_put_u8(s, BC_TAG_UNDEFINED);\n        break;\n    case JS_TAG_BOOL:\n        bc_put_u8(s, BC_TAG_BOOL_FALSE + JS_VALUE_GET_INT(obj));\n        break;\n    case JS_TAG_INT:\n        bc_put_u8(s, BC_TAG_INT32);\n        bc_put_sleb128(s, JS_VALUE_GET_INT(obj));\n        break;\n    case JS_TAG_FLOAT64:\n        {\n            JSFloat64Union u;\n            bc_put_u8(s, BC_TAG_FLOAT64);\n            u.d = JS_VALUE_GET_FLOAT64(obj);\n            bc_put_u64(s, u.u64);\n        }\n        break;\n    case JS_TAG_STRING:\n        {\n            JSString *p = JS_VALUE_GET_STRING(obj);\n            bc_put_u8(s, BC_TAG_STRING);\n            JS_WriteString(s, p);\n        }\n        break;\n    case JS_TAG_FUNCTION_BYTECODE:\n        if (!s->allow_bytecode)\n            goto invalid_tag;\n        if (JS_WriteFunctionTag(s, obj))\n            goto fail;\n        break;\n    case JS_TAG_MODULE:\n        if (!s->allow_bytecode)\n            goto invalid_tag;\n        if (JS_WriteModule(s, obj))\n            goto fail;\n        break;\n    case JS_TAG_OBJECT:\n        {\n            JSObject *p = JS_VALUE_GET_OBJ(obj);\n            int ret, idx;\n            \n            if (s->allow_reference) {\n                idx = js_object_list_find(s->ctx, &s->object_list, p);\n                if (idx >= 0) {\n                    bc_put_u8(s, BC_TAG_OBJECT_REFERENCE);\n                    bc_put_leb128(s, idx);\n                    break;\n                } else {\n                    if (js_object_list_add(s->ctx, &s->object_list, p))\n                        goto fail;\n                }\n            } else {\n                if (p->tmp_mark) {\n                    JS_ThrowTypeError(s->ctx, \"circular reference\");\n                    goto fail;\n                }\n                p->tmp_mark = 1;\n            }\n            switch(p->class_id) {\n            case JS_CLASS_ARRAY:\n                ret = JS_WriteArray(s, obj);\n                break;\n            case JS_CLASS_OBJECT:\n                ret = JS_WriteObjectTag(s, obj);\n                break;\n            case JS_CLASS_ARRAY_BUFFER:\n                ret = JS_WriteArrayBuffer(s, obj);\n                break;\n            case JS_CLASS_SHARED_ARRAY_BUFFER:\n                if (!s->allow_sab)\n                    goto invalid_tag;\n                ret = JS_WriteSharedArrayBuffer(s, obj);\n                break;\n            case JS_CLASS_DATE:\n                bc_put_u8(s, BC_TAG_DATE);\n                ret = JS_WriteObjectRec(s, p->u.object_data);\n                break;\n            case JS_CLASS_NUMBER:\n            case JS_CLASS_STRING:\n            case JS_CLASS_BOOLEAN:\n#ifdef CONFIG_BIGNUM\n            case JS_CLASS_BIG_INT:\n            case JS_CLASS_BIG_FLOAT:\n            case JS_CLASS_BIG_DECIMAL:\n#endif\n                bc_put_u8(s, BC_TAG_OBJECT_VALUE);\n                ret = JS_WriteObjectRec(s, p->u.object_data);\n                break;\n            default:\n                if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n                    p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n                    ret = JS_WriteTypedArray(s, obj);\n                } else {\n                    JS_ThrowTypeError(s->ctx, \"unsupported object class\");\n                    ret = -1;\n                }\n                break;\n            }\n            p->tmp_mark = 0;\n            if (ret)\n                goto fail;\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n    case JS_TAG_BIG_FLOAT:\n    case JS_TAG_BIG_DECIMAL:\n        if (JS_WriteBigNum(s, obj))\n            goto fail;\n        break;\n#endif\n    default:\n    invalid_tag:\n        JS_ThrowInternalError(s->ctx, \"unsupported tag (%d)\", tag);\n        goto fail;\n    }\n    return 0;\n\n fail:\n    return -1;\n}\n\n/* create the atom table */\nstatic int JS_WriteObjectAtoms(BCWriterState *s)\n{\n    JSRuntime *rt = s->ctx->rt;\n    DynBuf dbuf1;\n    int i, atoms_size;\n    uint8_t version;\n\n    dbuf1 = s->dbuf;\n    js_dbuf_init(s->ctx, &s->dbuf);\n\n    version = BC_VERSION;\n    if (s->byte_swap)\n        version ^= BC_BE_VERSION;\n    bc_put_u8(s, version);\n\n    bc_put_leb128(s, s->idx_to_atom_count);\n    for(i = 0; i < s->idx_to_atom_count; i++) {\n        JSAtomStruct *p = rt->atom_array[s->idx_to_atom[i]];\n        JS_WriteString(s, p);\n    }\n    /* XXX: should check for OOM in above phase */\n\n    /* move the atoms at the start */\n    /* XXX: could just append dbuf1 data, but it uses more memory if\n       dbuf1 is larger than dbuf */\n    atoms_size = s->dbuf.size;\n    if (dbuf_realloc(&dbuf1, dbuf1.size + atoms_size))\n        goto fail;\n    memmove(dbuf1.buf + atoms_size, dbuf1.buf, dbuf1.size);\n    memcpy(dbuf1.buf, s->dbuf.buf, atoms_size);\n    dbuf1.size += atoms_size;\n    dbuf_free(&s->dbuf);\n    s->dbuf = dbuf1;\n    return 0;\n fail:\n    dbuf_free(&dbuf1);\n    return -1;\n}\n\nuint8_t *JS_WriteObject2(JSContext *ctx, size_t *psize, JSValueConst obj,\n                         int flags, uint8_t ***psab_tab, size_t *psab_tab_len)\n{\n    BCWriterState ss, *s = &ss;\n\n    memset(s, 0, sizeof(*s));\n    s->ctx = ctx;\n    /* XXX: byte swapped output is untested */\n    s->byte_swap = ((flags & JS_WRITE_OBJ_BSWAP) != 0);\n    s->allow_bytecode = ((flags & JS_WRITE_OBJ_BYTECODE) != 0);\n    s->allow_sab = ((flags & JS_WRITE_OBJ_SAB) != 0);\n    s->allow_reference = ((flags & JS_WRITE_OBJ_REFERENCE) != 0);\n    /* XXX: could use a different version when bytecode is included */\n    if (s->allow_bytecode)\n        s->first_atom = JS_ATOM_END;\n    else\n        s->first_atom = 1;\n    js_dbuf_init(ctx, &s->dbuf);\n    js_object_list_init(&s->object_list);\n    \n    if (JS_WriteObjectRec(s, obj))\n        goto fail;\n    if (JS_WriteObjectAtoms(s))\n        goto fail;\n    js_object_list_end(ctx, &s->object_list);\n    js_free(ctx, s->atom_to_idx);\n    js_free(ctx, s->idx_to_atom);\n    *psize = s->dbuf.size;\n    if (psab_tab)\n        *psab_tab = s->sab_tab;\n    if (psab_tab_len)\n        *psab_tab_len = s->sab_tab_len;\n    return s->dbuf.buf;\n fail:\n    js_object_list_end(ctx, &s->object_list);\n    js_free(ctx, s->atom_to_idx);\n    js_free(ctx, s->idx_to_atom);\n    dbuf_free(&s->dbuf);\n    *psize = 0;\n    if (psab_tab)\n        *psab_tab = NULL;\n    if (psab_tab_len)\n        *psab_tab_len = 0;\n    return NULL;\n}\n\nuint8_t *JS_WriteObject(JSContext *ctx, size_t *psize, JSValueConst obj,\n                        int flags)\n{\n    return JS_WriteObject2(ctx, psize, obj, flags, NULL, NULL);\n}\n\ntypedef struct BCReaderState {\n    JSContext *ctx;\n    const uint8_t *buf_start, *ptr, *buf_end;\n    uint32_t first_atom;\n    uint32_t idx_to_atom_count;\n    JSAtom *idx_to_atom;\n    int error_state;\n    BOOL allow_sab : 8;\n    BOOL allow_bytecode : 8;\n    BOOL is_rom_data : 8;\n    BOOL allow_reference : 8;\n    /* object references */\n    JSObject **objects;\n    int objects_count;\n    int objects_size;\n    \n#ifdef DUMP_READ_OBJECT\n    const uint8_t *ptr_last;\n    int level;\n#endif\n} BCReaderState;\n\n#ifdef DUMP_READ_OBJECT\nstatic void __attribute__((format(printf, 2, 3))) bc_read_trace(BCReaderState *s, const char *fmt, ...) {\n    va_list ap;\n    int i, n, n0;\n\n    if (!s->ptr_last)\n        s->ptr_last = s->buf_start;\n\n    n = n0 = 0;\n    if (s->ptr > s->ptr_last || s->ptr == s->buf_start) {\n        n0 = printf(\"%04x: \", (int)(s->ptr_last - s->buf_start));\n        n += n0;\n    }\n    for (i = 0; s->ptr_last < s->ptr; i++) {\n        if ((i & 7) == 0 && i > 0) {\n            printf(\"\\n%*s\", n0, \"\");\n            n = n0;\n        }\n        n += printf(\" %02x\", *s->ptr_last++);\n    }\n    if (*fmt == '}')\n        s->level--;\n    if (n < 32 + s->level * 2) {\n        printf(\"%*s\", 32 + s->level * 2 - n, \"\");\n    }\n    va_start(ap, fmt);\n    vfprintf(stdout, fmt, ap);\n    va_end(ap);\n    if (strchr(fmt, '{'))\n        s->level++;\n}\n#else\n#define bc_read_trace(...)\n#endif\n\nstatic int bc_read_error_end(BCReaderState *s)\n{\n    if (!s->error_state) {\n        JS_ThrowSyntaxError(s->ctx, \"read after the end of the buffer\");\n    }\n    return s->error_state = -1;\n}\n\nstatic int bc_get_u8(BCReaderState *s, uint8_t *pval)\n{\n    if (unlikely(s->buf_end - s->ptr < 1)) {\n        *pval = 0; /* avoid warning */\n        return bc_read_error_end(s);\n    }\n    *pval = *s->ptr++;\n    return 0;\n}\n\nstatic int bc_get_u16(BCReaderState *s, uint16_t *pval)\n{\n    if (unlikely(s->buf_end - s->ptr < 2)) {\n        *pval = 0; /* avoid warning */\n        return bc_read_error_end(s);\n    }\n    *pval = get_u16(s->ptr);\n    s->ptr += 2;\n    return 0;\n}\n\nstatic __maybe_unused int bc_get_u32(BCReaderState *s, uint32_t *pval)\n{\n    if (unlikely(s->buf_end - s->ptr < 4)) {\n        *pval = 0; /* avoid warning */\n        return bc_read_error_end(s);\n    }\n    *pval = get_u32(s->ptr);\n    s->ptr += 4;\n    return 0;\n}\n\nstatic int bc_get_u64(BCReaderState *s, uint64_t *pval)\n{\n    if (unlikely(s->buf_end - s->ptr < 8)) {\n        *pval = 0; /* avoid warning */\n        return bc_read_error_end(s);\n    }\n    *pval = get_u64(s->ptr);\n    s->ptr += 8;\n    return 0;\n}\n\nstatic int bc_get_leb128(BCReaderState *s, uint32_t *pval)\n{\n    int ret;\n    ret = get_leb128(pval, s->ptr, s->buf_end);\n    if (unlikely(ret < 0))\n        return bc_read_error_end(s);\n    s->ptr += ret;\n    return 0;\n}\n\nstatic int bc_get_sleb128(BCReaderState *s, int32_t *pval)\n{\n    int ret;\n    ret = get_sleb128(pval, s->ptr, s->buf_end);\n    if (unlikely(ret < 0))\n        return bc_read_error_end(s);\n    s->ptr += ret;\n    return 0;\n}\n\n/* XXX: used to read an `int` with a positive value */\nstatic int bc_get_leb128_int(BCReaderState *s, int *pval)\n{\n    return bc_get_leb128(s, (uint32_t *)pval);\n}\n\nstatic int bc_get_leb128_u16(BCReaderState *s, uint16_t *pval)\n{\n    uint32_t val;\n    if (bc_get_leb128(s, &val)) {\n        *pval = 0;\n        return -1;\n    }\n    *pval = val;\n    return 0;\n}\n\nstatic int bc_get_buf(BCReaderState *s, uint8_t *buf, uint32_t buf_len)\n{\n    if (buf_len != 0) {\n        if (unlikely(!buf || s->buf_end - s->ptr < buf_len))\n            return bc_read_error_end(s);\n        memcpy(buf, s->ptr, buf_len);\n        s->ptr += buf_len;\n    }\n    return 0;\n}\n\nstatic int bc_idx_to_atom(BCReaderState *s, JSAtom *patom, uint32_t idx)\n{\n    JSAtom atom;\n\n    if (__JS_AtomIsTaggedInt(idx)) {\n        atom = idx;\n    } else if (idx < s->first_atom) {\n        atom = JS_DupAtom(s->ctx, idx);\n    } else {\n        idx -= s->first_atom;\n        if (idx >= s->idx_to_atom_count) {\n            JS_ThrowSyntaxError(s->ctx, \"invalid atom index (pos=%u)\",\n                                (unsigned int)(s->ptr - s->buf_start));\n            *patom = JS_ATOM_NULL;\n            return s->error_state = -1;\n        }\n        atom = JS_DupAtom(s->ctx, s->idx_to_atom[idx]);\n    }\n    *patom = atom;\n    return 0;\n}\n\nstatic int bc_get_atom(BCReaderState *s, JSAtom *patom)\n{\n    uint32_t v;\n    if (bc_get_leb128(s, &v))\n        return -1;\n    if (v & 1) {\n        *patom = __JS_AtomFromUInt32(v >> 1);\n        return 0;\n    } else {\n        return bc_idx_to_atom(s, patom, v >> 1);\n    }\n}\n\nstatic JSString *JS_ReadString(BCReaderState *s)\n{\n    uint32_t len;\n    size_t size;\n    BOOL is_wide_char;\n    JSString *p;\n\n    if (bc_get_leb128(s, &len))\n        return NULL;\n    is_wide_char = len & 1;\n    len >>= 1;\n    p = js_alloc_string(s->ctx, len, is_wide_char);\n    if (!p) {\n        s->error_state = -1;\n        return NULL;\n    }\n    size = (size_t)len << is_wide_char;\n    if ((s->buf_end - s->ptr) < size) {\n        bc_read_error_end(s);\n        js_free_string(s->ctx->rt, p);\n        return NULL;\n    }\n    memcpy(p->u.str8, s->ptr, size);\n    s->ptr += size;\n    if (!is_wide_char) {\n        p->u.str8[size] = '\\0'; /* add the trailing zero for 8 bit strings */\n    }\n#ifdef DUMP_READ_OBJECT\n    JS_DumpString(s->ctx->rt, p); printf(\"\\n\");\n#endif\n    return p;\n}\n\nstatic uint32_t bc_get_flags(uint32_t flags, int *pidx, int n)\n{\n    uint32_t val;\n    /* XXX: this does not work for n == 32 */\n    val = (flags >> *pidx) & ((1U << n) - 1);\n    *pidx += n;\n    return val;\n}\n\nstatic int JS_ReadFunctionBytecode(BCReaderState *s, JSFunctionBytecode *b,\n                                   int byte_code_offset, uint32_t bc_len)\n{\n    uint8_t *bc_buf;\n    int pos, len, op;\n    JSAtom atom;\n    uint32_t idx;\n\n    if (s->is_rom_data) {\n        /* directly use the input buffer */\n        if (unlikely(s->buf_end - s->ptr < bc_len))\n            return bc_read_error_end(s);\n        bc_buf = (uint8_t *)s->ptr;\n        s->ptr += bc_len;\n    } else {\n        bc_buf = (void *)((uint8_t*)b + byte_code_offset);\n        if (bc_get_buf(s, bc_buf, bc_len))\n            return -1;\n    }\n    b->byte_code_buf = bc_buf;\n\n    pos = 0;\n    while (pos < bc_len) {\n        op = bc_buf[pos];\n        len = short_opcode_info(op).size;\n        switch(short_opcode_info(op).fmt) {\n        case OP_FMT_atom:\n        case OP_FMT_atom_u8:\n        case OP_FMT_atom_u16:\n        case OP_FMT_atom_label_u8:\n        case OP_FMT_atom_label_u16:\n            idx = get_u32(bc_buf + pos + 1);\n            if (s->is_rom_data) {\n                /* just increment the reference count of the atom */\n                JS_DupAtom(s->ctx, (JSAtom)idx);\n            } else {\n                if (bc_idx_to_atom(s, &atom, idx)) {\n                    /* Note: the atoms will be freed up to this position */\n                    b->byte_code_len = pos;\n                    return -1;\n                }\n                put_u32(bc_buf + pos + 1, atom);\n#ifdef DUMP_READ_OBJECT\n                bc_read_trace(s, \"at %d, fixup atom: \", pos + 1); print_atom(s->ctx, atom); printf(\"\\n\");\n#endif\n            }\n            break;\n        default:\n            break;\n        }\n        pos += len;\n    }\n    return 0;\n}\n\n#ifdef CONFIG_BIGNUM\nstatic JSValue JS_ReadBigNum(BCReaderState *s, int tag)\n{\n    JSValue obj = JS_UNDEFINED;\n    uint8_t v8;\n    int32_t e;\n    uint32_t len;\n    limb_t l, i, n, j;\n    JSBigFloat *p;\n    limb_t v;\n    bf_t *a;\n    int bpos, d;\n    \n    p = js_new_bf(s->ctx);\n    if (!p)\n        goto fail;\n    switch(tag) {\n    case BC_TAG_BIG_INT:\n        obj = JS_MKPTR(JS_TAG_BIG_INT, p);\n        break;\n    case BC_TAG_BIG_FLOAT:\n        obj = JS_MKPTR(JS_TAG_BIG_FLOAT, p);\n        break;\n    case BC_TAG_BIG_DECIMAL:\n        obj = JS_MKPTR(JS_TAG_BIG_DECIMAL, p);\n        break;\n    default:\n        abort();\n    }\n\n    /* sign + exponent */\n    if (bc_get_sleb128(s, &e))\n        goto fail;\n\n    a = &p->num;\n    a->sign = e & 1;\n    e >>= 1;\n    if (e == 0)\n        a->expn = BF_EXP_ZERO;\n    else if (e == 1)\n        a->expn = BF_EXP_INF;\n    else if (e == 2)\n        a->expn = BF_EXP_NAN;\n    else if (e >= 3)\n        a->expn = e - 3;\n    else\n        a->expn = e;\n\n    /* mantissa */\n    if (a->expn != BF_EXP_ZERO &&\n        a->expn != BF_EXP_INF &&\n        a->expn != BF_EXP_NAN) {\n        if (bc_get_leb128(s, &len))\n            goto fail;\n        bc_read_trace(s, \"len=%\" PRId64 \"\\n\", (int64_t)len);\n        if (len == 0) {\n            JS_ThrowInternalError(s->ctx, \"invalid bignum length\");\n            goto fail;\n        }\n        if (tag != BC_TAG_BIG_DECIMAL)\n            l = (len + sizeof(limb_t) - 1) / sizeof(limb_t);\n        else\n            l = (len + LIMB_DIGITS - 1) / LIMB_DIGITS;\n        if (bf_resize(a, l)) {\n            JS_ThrowOutOfMemory(s->ctx);\n            goto fail;\n        }\n        if (tag != BC_TAG_BIG_DECIMAL) {\n            n = len & (sizeof(limb_t) - 1);\n            if (n != 0) {\n                v = 0;\n                for(i = 0; i < n; i++) {\n                    if (bc_get_u8(s, &v8))\n                        goto fail;\n                    v |= (limb_t)v8 << ((sizeof(limb_t) - n + i) * 8);\n                }\n                a->tab[0] = v;\n                i = 1;\n            } else {\n                i = 0;\n            }\n            for(; i < l; i++) {\n#if LIMB_BITS == 32\n                if (bc_get_u32(s, &v))\n                    goto fail;\n#ifdef WORDS_BIGENDIAN\n                v = bswap32(v);\n#endif\n#else\n                if (bc_get_u64(s, &v))\n                    goto fail;\n#ifdef WORDS_BIGENDIAN\n                v = bswap64(v);\n#endif\n#endif\n                a->tab[i] = v;\n            }\n        } else {\n            bpos = 0;\n            for(i = 0; i < l; i++) {\n                if (i == 0 && (n = len % LIMB_DIGITS) != 0) {\n                    j = LIMB_DIGITS - n;\n                } else {\n                    j = 0;\n                }\n                v = 0;\n                for(; j < LIMB_DIGITS; j++) {\n                    if (bpos == 0) {\n                        if (bc_get_u8(s, &v8))\n                            goto fail;\n                        d = v8 & 0xf;\n                        bpos = 1;\n                    } else {\n                        d = v8 >> 4;\n                        bpos = 0;\n                    }\n                    if (d >= 10) {\n                        JS_ThrowInternalError(s->ctx, \"invalid digit\");\n                        goto fail;\n                    }\n                    v += mp_pow_dec[j] * d;\n                }\n                a->tab[i] = v;\n            }\n        }\n    }\n    bc_read_trace(s, \"}\\n\");\n    return obj;\n fail:\n    JS_FreeValue(s->ctx, obj);\n    return JS_EXCEPTION;\n}\n#endif /* CONFIG_BIGNUM */\n\nstatic JSValue JS_ReadObjectRec(BCReaderState *s);\n\nstatic int BC_add_object_ref1(BCReaderState *s, JSObject *p)\n{\n    if (s->allow_reference) {\n        if (js_resize_array(s->ctx, (void *)&s->objects,\n                            sizeof(s->objects[0]),\n                            &s->objects_size, s->objects_count + 1))\n            return -1;\n        s->objects[s->objects_count++] = p;\n    }\n    return 0;\n}\n\nstatic int BC_add_object_ref(BCReaderState *s, JSValueConst obj)\n{\n    return BC_add_object_ref1(s, JS_VALUE_GET_OBJ(obj));\n}\n\nstatic JSValue JS_ReadFunctionTag(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSFunctionBytecode bc, *b;\n    JSValue obj = JS_UNDEFINED;\n    uint16_t v16;\n    uint8_t v8;\n    int idx, i, local_count;\n    int function_size, cpool_offset, byte_code_offset;\n    int closure_var_offset, vardefs_offset;\n\n    memset(&bc, 0, sizeof(bc));\n    bc.header.ref_count = 1;\n    //bc.gc_header.mark = 0;\n\n    if (bc_get_u16(s, &v16))\n        goto fail;\n    idx = 0;\n    bc.has_prototype = bc_get_flags(v16, &idx, 1);\n    bc.has_simple_parameter_list = bc_get_flags(v16, &idx, 1);\n    bc.is_derived_class_constructor = bc_get_flags(v16, &idx, 1);\n    bc.need_home_object = bc_get_flags(v16, &idx, 1);\n    bc.func_kind = bc_get_flags(v16, &idx, 2);\n    bc.new_target_allowed = bc_get_flags(v16, &idx, 1);\n    bc.super_call_allowed = bc_get_flags(v16, &idx, 1);\n    bc.super_allowed = bc_get_flags(v16, &idx, 1);\n    bc.arguments_allowed = bc_get_flags(v16, &idx, 1);\n    bc.has_debug = bc_get_flags(v16, &idx, 1);\n    bc.backtrace_barrier = bc_get_flags(v16, &idx, 1);\n    bc.read_only_bytecode = s->is_rom_data;\n    if (bc_get_u8(s, &v8))\n        goto fail;\n    bc.js_mode = v8;\n    if (bc_get_atom(s, &bc.func_name))  //@ atom leak if failure\n        goto fail;\n    if (bc_get_leb128_u16(s, &bc.arg_count))\n        goto fail;\n    if (bc_get_leb128_u16(s, &bc.var_count))\n        goto fail;\n    if (bc_get_leb128_u16(s, &bc.defined_arg_count))\n        goto fail;\n    if (bc_get_leb128_u16(s, &bc.stack_size))\n        goto fail;\n    if (bc_get_leb128_int(s, &bc.closure_var_count))\n        goto fail;\n    if (bc_get_leb128_int(s, &bc.cpool_count))\n        goto fail;\n    if (bc_get_leb128_int(s, &bc.byte_code_len))\n        goto fail;\n    if (bc_get_leb128_int(s, &local_count))\n        goto fail;\n\n    if (bc.has_debug) {\n        function_size = sizeof(*b);\n    } else {\n        function_size = offsetof(JSFunctionBytecode, debug);\n    }\n    cpool_offset = function_size;\n    function_size += bc.cpool_count * sizeof(*bc.cpool);\n    vardefs_offset = function_size;\n    function_size += local_count * sizeof(*bc.vardefs);\n    closure_var_offset = function_size;\n    function_size += bc.closure_var_count * sizeof(*bc.closure_var);\n    byte_code_offset = function_size;\n    if (!bc.read_only_bytecode) {\n        function_size += bc.byte_code_len;\n    }\n\n    b = js_mallocz(ctx, function_size);\n    if (!b)\n        return JS_EXCEPTION;\n            \n    memcpy(b, &bc, offsetof(JSFunctionBytecode, debug));\n    b->header.ref_count = 1;\n    if (local_count != 0) {\n        b->vardefs = (void *)((uint8_t*)b + vardefs_offset);\n    }\n    if (b->closure_var_count != 0) {\n        b->closure_var = (void *)((uint8_t*)b + closure_var_offset);\n    }\n    if (b->cpool_count != 0) {\n        b->cpool = (void *)((uint8_t*)b + cpool_offset);\n    }\n    \n    add_gc_object(ctx->rt, &b->header, JS_GC_OBJ_TYPE_FUNCTION_BYTECODE);\n            \n    obj = JS_MKPTR(JS_TAG_FUNCTION_BYTECODE, b);\n\n#ifdef DUMP_READ_OBJECT\n    bc_read_trace(s, \"name: \"); print_atom(s->ctx, b->func_name); printf(\"\\n\");\n#endif\n    bc_read_trace(s, \"args=%d vars=%d defargs=%d closures=%d cpool=%d\\n\",\n                  b->arg_count, b->var_count, b->defined_arg_count,\n                  b->closure_var_count, b->cpool_count);\n    bc_read_trace(s, \"stack=%d bclen=%d locals=%d\\n\",\n                  b->stack_size, b->byte_code_len, local_count);\n\n    if (local_count != 0) {\n        bc_read_trace(s, \"vars {\\n\");\n        for(i = 0; i < local_count; i++) {\n            JSVarDef *vd = &b->vardefs[i];\n            if (bc_get_atom(s, &vd->var_name))\n                goto fail;\n            if (bc_get_leb128_int(s, &vd->scope_level))\n                goto fail;\n            if (bc_get_leb128_int(s, &vd->scope_next))\n                goto fail;\n            vd->scope_next--;\n            if (bc_get_u8(s, &v8))\n                goto fail;\n            idx = 0;\n            vd->var_kind = bc_get_flags(v8, &idx, 4);\n            vd->is_const = bc_get_flags(v8, &idx, 1);\n            vd->is_lexical = bc_get_flags(v8, &idx, 1);\n            vd->is_captured = bc_get_flags(v8, &idx, 1);\n#ifdef DUMP_READ_OBJECT\n            bc_read_trace(s, \"name: \"); print_atom(s->ctx, vd->var_name); printf(\"\\n\");\n#endif\n        }\n        bc_read_trace(s, \"}\\n\");\n    }\n    if (b->closure_var_count != 0) {\n        bc_read_trace(s, \"closure vars {\\n\");\n        for(i = 0; i < b->closure_var_count; i++) {\n            JSClosureVar *cv = &b->closure_var[i];\n            int var_idx;\n            if (bc_get_atom(s, &cv->var_name))\n                goto fail;\n            if (bc_get_leb128_int(s, &var_idx))\n                goto fail;\n            cv->var_idx = var_idx;\n            if (bc_get_u8(s, &v8))\n                goto fail;\n            idx = 0;\n            cv->is_local = bc_get_flags(v8, &idx, 1);\n            cv->is_arg = bc_get_flags(v8, &idx, 1);\n            cv->is_const = bc_get_flags(v8, &idx, 1);\n            cv->is_lexical = bc_get_flags(v8, &idx, 1);\n            cv->var_kind = bc_get_flags(v8, &idx, 4);\n#ifdef DUMP_READ_OBJECT\n            bc_read_trace(s, \"name: \"); print_atom(s->ctx, cv->var_name); printf(\"\\n\");\n#endif\n        }\n        bc_read_trace(s, \"}\\n\");\n    }\n    {\n        bc_read_trace(s, \"bytecode {\\n\");\n        if (JS_ReadFunctionBytecode(s, b, byte_code_offset, b->byte_code_len))\n            goto fail;\n        bc_read_trace(s, \"}\\n\");\n    }\n    if (b->has_debug) {\n        /* read optional debug information */\n        bc_read_trace(s, \"debug {\\n\");\n        if (bc_get_atom(s, &b->debug.filename))\n            goto fail;\n        if (bc_get_leb128_int(s, &b->debug.line_num))\n            goto fail;\n        if (bc_get_leb128_int(s, &b->debug.pc2line_len))\n            goto fail;\n        if (b->debug.pc2line_len) {\n            b->debug.pc2line_buf = js_mallocz(ctx, b->debug.pc2line_len);\n            if (!b->debug.pc2line_buf)\n                goto fail;\n            if (bc_get_buf(s, b->debug.pc2line_buf, b->debug.pc2line_len))\n                goto fail;\n        }\n#ifdef DUMP_READ_OBJECT\n        bc_read_trace(s, \"filename: \"); print_atom(s->ctx, b->debug.filename); printf(\"\\n\");\n#endif\n        bc_read_trace(s, \"}\\n\");\n    }\n    if (b->cpool_count != 0) {\n        bc_read_trace(s, \"cpool {\\n\");\n        for(i = 0; i < b->cpool_count; i++) {\n            JSValue val;\n            val = JS_ReadObjectRec(s);\n            if (JS_IsException(val))\n                goto fail;\n            b->cpool[i] = val;\n        }\n        bc_read_trace(s, \"}\\n\");\n    }\n    b->realm = JS_DupContext(ctx);\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadModule(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSValue obj;\n    JSModuleDef *m = NULL;\n    JSAtom module_name;\n    int i;\n    uint8_t v8;\n    \n    if (bc_get_atom(s, &module_name))\n        goto fail;\n#ifdef DUMP_READ_OBJECT\n    bc_read_trace(s, \"name: \"); print_atom(s->ctx, module_name); printf(\"\\n\");\n#endif\n    m = js_new_module_def(ctx, module_name);\n    if (!m)\n        goto fail;\n    obj = JS_DupValue(ctx, JS_MKPTR(JS_TAG_MODULE, m));\n    if (bc_get_leb128_int(s, &m->req_module_entries_count))\n        goto fail;\n    if (m->req_module_entries_count != 0) {\n        m->req_module_entries_size = m->req_module_entries_count;\n        m->req_module_entries = js_mallocz(ctx, sizeof(m->req_module_entries[0]) * m->req_module_entries_size);\n        if (!m->req_module_entries)\n            goto fail;\n        for(i = 0; i < m->req_module_entries_count; i++) {\n            JSReqModuleEntry *rme = &m->req_module_entries[i];\n            if (bc_get_atom(s, &rme->module_name))\n                goto fail;\n        }\n    }\n\n    if (bc_get_leb128_int(s, &m->export_entries_count))\n        goto fail;\n    if (m->export_entries_count != 0) {\n        m->export_entries_size = m->export_entries_count;\n        m->export_entries = js_mallocz(ctx, sizeof(m->export_entries[0]) * m->export_entries_size);\n        if (!m->export_entries)\n            goto fail;\n        for(i = 0; i < m->export_entries_count; i++) {\n            JSExportEntry *me = &m->export_entries[i];\n            if (bc_get_u8(s, &v8))\n                goto fail;\n            me->export_type = v8;\n            if (me->export_type == JS_EXPORT_TYPE_LOCAL) {\n                if (bc_get_leb128_int(s, &me->u.local.var_idx))\n                    goto fail;\n            } else {\n                if (bc_get_leb128_int(s, &me->u.req_module_idx))\n                    goto fail;\n                if (bc_get_atom(s, &me->local_name))\n                    goto fail;\n            }\n            if (bc_get_atom(s, &me->export_name))\n                goto fail;\n        }\n    }\n\n    if (bc_get_leb128_int(s, &m->star_export_entries_count))\n        goto fail;\n    if (m->star_export_entries_count != 0) {\n        m->star_export_entries_size = m->star_export_entries_count;\n        m->star_export_entries = js_mallocz(ctx, sizeof(m->star_export_entries[0]) * m->star_export_entries_size);\n        if (!m->star_export_entries)\n            goto fail;\n        for(i = 0; i < m->star_export_entries_count; i++) {\n            JSStarExportEntry *se = &m->star_export_entries[i];\n            if (bc_get_leb128_int(s, &se->req_module_idx))\n                goto fail;\n        }\n    }\n\n    if (bc_get_leb128_int(s, &m->import_entries_count))\n        goto fail;\n    if (m->import_entries_count != 0) {\n        m->import_entries_size = m->import_entries_count;\n        m->import_entries = js_mallocz(ctx, sizeof(m->import_entries[0]) * m->import_entries_size);\n        if (!m->import_entries)\n            goto fail;\n        for(i = 0; i < m->import_entries_count; i++) {\n            JSImportEntry *mi = &m->import_entries[i];\n            if (bc_get_leb128_int(s, &mi->var_idx))\n                goto fail;\n            if (bc_get_atom(s, &mi->import_name))\n                goto fail;\n            if (bc_get_leb128_int(s, &mi->req_module_idx))\n                goto fail;\n        }\n    }\n\n    m->func_obj = JS_ReadObjectRec(s);\n    if (JS_IsException(m->func_obj))\n        goto fail;\n    return obj;\n fail:\n    if (m) {\n        js_free_module_def(ctx, m);\n    }\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadObjectTag(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSValue obj;\n    uint32_t prop_count, i;\n    JSAtom atom;\n    JSValue val;\n    int ret;\n    \n    obj = JS_NewObject(ctx);\n    if (BC_add_object_ref(s, obj))\n        goto fail;\n    if (bc_get_leb128(s, &prop_count))\n        goto fail;\n    for(i = 0; i < prop_count; i++) {\n        if (bc_get_atom(s, &atom))\n            goto fail;\n#ifdef DUMP_READ_OBJECT\n        bc_read_trace(s, \"propname: \"); print_atom(s->ctx, atom); printf(\"\\n\");\n#endif\n        val = JS_ReadObjectRec(s);\n        if (JS_IsException(val)) {\n            JS_FreeAtom(ctx, atom);\n            goto fail;\n        }\n        ret = JS_DefinePropertyValue(ctx, obj, atom, val, JS_PROP_C_W_E);\n        JS_FreeAtom(ctx, atom);\n        if (ret < 0)\n            goto fail;\n    }\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadArray(BCReaderState *s, int tag)\n{\n    JSContext *ctx = s->ctx;\n    JSValue obj;\n    uint32_t len, i;\n    JSValue val;\n    int ret, prop_flags;\n    BOOL is_template;\n\n    obj = JS_NewArray(ctx);\n    if (BC_add_object_ref(s, obj))\n        goto fail;\n    is_template = (tag == BC_TAG_TEMPLATE_OBJECT);\n    if (bc_get_leb128(s, &len))\n        goto fail;\n    for(i = 0; i < len; i++) {\n        val = JS_ReadObjectRec(s);\n        if (JS_IsException(val))\n            goto fail;\n        if (is_template)\n            prop_flags = JS_PROP_ENUMERABLE;\n        else\n            prop_flags = JS_PROP_C_W_E;\n        ret = JS_DefinePropertyValueUint32(ctx, obj, i, val,\n                                           prop_flags);\n        if (ret < 0)\n            goto fail;\n    }\n    if (is_template) {\n        val = JS_ReadObjectRec(s);\n        if (JS_IsException(val))\n            goto fail;\n        if (!JS_IsUndefined(val)) {\n            ret = JS_DefinePropertyValue(ctx, obj, JS_ATOM_raw, val, 0);\n            if (ret < 0)\n                goto fail;\n        }\n        JS_PreventExtensions(ctx, obj);\n    }\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadTypedArray(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSValue obj = JS_UNDEFINED, array_buffer = JS_UNDEFINED;\n    uint8_t array_tag;\n    JSValueConst args[3];\n    uint32_t offset, len, idx;\n    \n    if (bc_get_u8(s, &array_tag))\n        return JS_EXCEPTION;\n    if (array_tag >= JS_TYPED_ARRAY_COUNT)\n        return JS_ThrowTypeError(ctx, \"invalid typed array\");\n    if (bc_get_leb128(s, &len))\n        return JS_EXCEPTION;\n    if (bc_get_leb128(s, &offset))\n        return JS_EXCEPTION;\n    /* XXX: this hack could be avoided if the typed array could be\n       created before the array buffer */\n    idx = s->objects_count;\n    if (BC_add_object_ref1(s, NULL))\n        goto fail;\n    array_buffer = JS_ReadObjectRec(s);\n    if (JS_IsException(array_buffer))\n        return JS_EXCEPTION;\n    if (!js_get_array_buffer(ctx, array_buffer)) {\n        JS_FreeValue(ctx, array_buffer);\n        return JS_EXCEPTION;\n    }\n    args[0] = array_buffer;\n    args[1] = JS_NewInt64(ctx, offset);\n    args[2] = JS_NewInt64(ctx, len);\n    obj = js_typed_array_constructor(ctx, JS_UNDEFINED,\n                                     3, args,\n                                     JS_CLASS_UINT8C_ARRAY + array_tag);\n    if (JS_IsException(obj))\n        goto fail;\n    if (s->allow_reference) {\n        s->objects[idx] = JS_VALUE_GET_OBJ(obj);\n    }\n    JS_FreeValue(ctx, array_buffer);\n    return obj;\n fail:\n    JS_FreeValue(ctx, array_buffer);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadArrayBuffer(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    uint32_t byte_length;\n    JSValue obj;\n    \n    if (bc_get_leb128(s, &byte_length))\n        return JS_EXCEPTION;\n    if (unlikely(s->buf_end - s->ptr < byte_length)) {\n        bc_read_error_end(s);\n        return JS_EXCEPTION;\n    }\n    obj = JS_NewArrayBufferCopy(ctx, s->ptr, byte_length);\n    if (JS_IsException(obj))\n        goto fail;\n    if (BC_add_object_ref(s, obj))\n        goto fail;\n    s->ptr += byte_length;\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadSharedArrayBuffer(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    uint32_t byte_length;\n    uint8_t *data_ptr;\n    JSValue obj;\n    uint64_t u64;\n    \n    if (bc_get_leb128(s, &byte_length))\n        return JS_EXCEPTION;\n    if (bc_get_u64(s, &u64))\n        return JS_EXCEPTION;\n    data_ptr = (uint8_t *)(uintptr_t)u64;\n    /* the SharedArrayBuffer is cloned */\n    obj = js_array_buffer_constructor3(ctx, JS_UNDEFINED, byte_length,\n                                       JS_CLASS_SHARED_ARRAY_BUFFER,\n                                       data_ptr,\n                                       NULL, NULL, FALSE);\n    if (JS_IsException(obj))\n        goto fail;\n    if (BC_add_object_ref(s, obj))\n        goto fail;\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadDate(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSValue val, obj = JS_UNDEFINED;\n\n    val = JS_ReadObjectRec(s);\n    if (JS_IsException(val))\n        goto fail;\n    if (!JS_IsNumber(val)) {\n        JS_ThrowTypeError(ctx, \"Number tag expected for date\");\n        goto fail;\n    }\n    obj = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_DATE],\n                                 JS_CLASS_DATE);\n    if (JS_IsException(obj))\n        goto fail;\n    if (BC_add_object_ref(s, obj))\n        goto fail;\n    JS_SetObjectData(ctx, obj, val);\n    return obj;\n fail:\n    JS_FreeValue(ctx, val);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadObjectValue(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSValue val, obj = JS_UNDEFINED;\n\n    val = JS_ReadObjectRec(s);\n    if (JS_IsException(val))\n        goto fail;\n    obj = JS_ToObject(ctx, val);\n    if (JS_IsException(obj))\n        goto fail;\n    if (BC_add_object_ref(s, obj))\n        goto fail;\n    JS_FreeValue(ctx, val);\n    return obj;\n fail:\n    JS_FreeValue(ctx, val);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_ReadObjectRec(BCReaderState *s)\n{\n    JSContext *ctx = s->ctx;\n    uint8_t tag;\n    JSValue obj = JS_UNDEFINED;\n\n    if (js_check_stack_overflow(ctx->rt, 0))\n        return JS_ThrowStackOverflow(ctx);\n\n    if (bc_get_u8(s, &tag))\n        return JS_EXCEPTION;\n\n    bc_read_trace(s, \"%s {\\n\", bc_tag_str[tag]);\n\n    switch(tag) {\n    case BC_TAG_NULL:\n        obj = JS_NULL;\n        break;\n    case BC_TAG_UNDEFINED:\n        obj = JS_UNDEFINED;\n        break;\n    case BC_TAG_BOOL_FALSE:\n    case BC_TAG_BOOL_TRUE:\n        obj = JS_NewBool(ctx, tag - BC_TAG_BOOL_FALSE);\n        break;\n    case BC_TAG_INT32:\n        {\n            int32_t val;\n            if (bc_get_sleb128(s, &val))\n                return JS_EXCEPTION;\n            bc_read_trace(s, \"%d\\n\", val);\n            obj = JS_NewInt32(ctx, val);\n        }\n        break;\n    case BC_TAG_FLOAT64:\n        {\n            JSFloat64Union u;\n            if (bc_get_u64(s, &u.u64))\n                return JS_EXCEPTION;\n            bc_read_trace(s, \"%g\\n\", u.d);\n            obj = __JS_NewFloat64(ctx, u.d);\n        }\n        break;\n    case BC_TAG_STRING:\n        {\n            JSString *p;\n            p = JS_ReadString(s);\n            if (!p)\n                return JS_EXCEPTION;\n            obj = JS_MKPTR(JS_TAG_STRING, p);\n        }\n        break;\n    case BC_TAG_FUNCTION_BYTECODE:\n        if (!s->allow_bytecode)\n            goto invalid_tag;\n        obj = JS_ReadFunctionTag(s);\n        break;\n    case BC_TAG_MODULE:\n        if (!s->allow_bytecode)\n            goto invalid_tag;\n        obj = JS_ReadModule(s);\n        break;\n    case BC_TAG_OBJECT:\n        obj = JS_ReadObjectTag(s);\n        break;\n    case BC_TAG_ARRAY:\n    case BC_TAG_TEMPLATE_OBJECT:\n        obj = JS_ReadArray(s, tag);\n        break;\n    case BC_TAG_TYPED_ARRAY:\n        obj = JS_ReadTypedArray(s);\n        break;\n    case BC_TAG_ARRAY_BUFFER:\n        obj = JS_ReadArrayBuffer(s);\n        break;\n    case BC_TAG_SHARED_ARRAY_BUFFER:\n        if (!s->allow_sab || !ctx->rt->sab_funcs.sab_dup)\n            goto invalid_tag;\n        obj = JS_ReadSharedArrayBuffer(s);\n        break;\n    case BC_TAG_DATE:\n        obj = JS_ReadDate(s);\n        break;\n    case BC_TAG_OBJECT_VALUE:\n        obj = JS_ReadObjectValue(s);\n        break;\n#ifdef CONFIG_BIGNUM\n    case BC_TAG_BIG_INT:\n    case BC_TAG_BIG_FLOAT:\n    case BC_TAG_BIG_DECIMAL:\n        obj = JS_ReadBigNum(s, tag);\n        break;\n#endif\n    case BC_TAG_OBJECT_REFERENCE:\n        {\n            uint32_t val;\n            if (!s->allow_reference)\n                return JS_ThrowSyntaxError(ctx, \"object references are not allowed\");\n            if (bc_get_leb128(s, &val))\n                return JS_EXCEPTION;\n            bc_read_trace(s, \"%u\\n\", val);\n            if (val >= s->objects_count) {\n                return JS_ThrowSyntaxError(ctx, \"invalid object reference (%u >= %u)\",\n                                           val, s->objects_count);\n            }\n            obj = JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, s->objects[val]));\n        }\n        break;\n    default:\n    invalid_tag:\n        return JS_ThrowSyntaxError(ctx, \"invalid tag (tag=%d pos=%u)\",\n                                   tag, (unsigned int)(s->ptr - s->buf_start));\n    }\n    bc_read_trace(s, \"}\\n\");\n    return obj;\n}\n\nstatic int JS_ReadObjectAtoms(BCReaderState *s)\n{\n    uint8_t v8;\n    JSString *p;\n    int i;\n    JSAtom atom;\n\n    if (bc_get_u8(s, &v8))\n        return -1;\n    /* XXX: could support byte swapped input */\n    if (v8 != BC_VERSION) {\n        JS_ThrowSyntaxError(s->ctx, \"invalid version (%d expected=%d)\",\n                            v8, BC_VERSION);\n        return -1;\n    }\n    if (bc_get_leb128(s, &s->idx_to_atom_count))\n        return -1;\n\n    bc_read_trace(s, \"%d atom indexes {\\n\", s->idx_to_atom_count);\n\n    if (s->idx_to_atom_count != 0) {\n        s->idx_to_atom = js_mallocz(s->ctx, s->idx_to_atom_count *\n                                    sizeof(s->idx_to_atom[0]));\n        if (!s->idx_to_atom)\n            return s->error_state = -1;\n    }\n    for(i = 0; i < s->idx_to_atom_count; i++) {\n        p = JS_ReadString(s);\n        if (!p)\n            return -1;\n        atom = JS_NewAtomStr(s->ctx, p);\n        if (atom == JS_ATOM_NULL)\n            return s->error_state = -1;\n        s->idx_to_atom[i] = atom;\n        if (s->is_rom_data && (atom != (i + s->first_atom)))\n            s->is_rom_data = FALSE; /* atoms must be relocated */\n    }\n    bc_read_trace(s, \"}\\n\");\n    return 0;\n}\n\nstatic void bc_reader_free(BCReaderState *s)\n{\n    int i;\n    if (s->idx_to_atom) {\n        for(i = 0; i < s->idx_to_atom_count; i++) {\n            JS_FreeAtom(s->ctx, s->idx_to_atom[i]);\n        }\n        js_free(s->ctx, s->idx_to_atom);\n    }\n    js_free(s->ctx, s->objects);\n}\n\nJSValue JS_ReadObject(JSContext *ctx, const uint8_t *buf, size_t buf_len,\n                       int flags)\n{\n    BCReaderState ss, *s = &ss;\n    JSValue obj;\n\n    ctx->binary_object_count += 1;\n    ctx->binary_object_size += buf_len;\n\n    memset(s, 0, sizeof(*s));\n    s->ctx = ctx;\n    s->buf_start = buf;\n    s->buf_end = buf + buf_len;\n    s->ptr = buf;\n    s->allow_bytecode = ((flags & JS_READ_OBJ_BYTECODE) != 0);\n    s->is_rom_data = ((flags & JS_READ_OBJ_ROM_DATA) != 0);\n    s->allow_sab = ((flags & JS_READ_OBJ_SAB) != 0);\n    s->allow_reference = ((flags & JS_READ_OBJ_REFERENCE) != 0);\n    if (s->allow_bytecode)\n        s->first_atom = JS_ATOM_END;\n    else\n        s->first_atom = 1;\n    if (JS_ReadObjectAtoms(s)) {\n        obj = JS_EXCEPTION;\n    } else {\n        obj = JS_ReadObjectRec(s);\n    }\n    bc_reader_free(s);\n    return obj;\n}\n\n/*******************************************************************/\n/* runtime functions & objects */\n\nstatic JSValue js_string_constructor(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv);\nstatic JSValue js_boolean_constructor(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv);\nstatic JSValue js_number_constructor(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv);\n\nstatic int check_function(JSContext *ctx, JSValueConst obj)\n{\n    if (likely(JS_IsFunction(ctx, obj)))\n        return 0;\n    JS_ThrowTypeError(ctx, \"not a function\");\n    return -1;\n}\n\nstatic int check_exception_free(JSContext *ctx, JSValue obj)\n{\n    JS_FreeValue(ctx, obj);\n    return JS_IsException(obj);\n}\n\nstatic JSAtom find_atom(JSContext *ctx, const char *name)\n{\n    JSAtom atom;\n    int len;\n\n    if (*name == '[') {\n        name++;\n        len = strlen(name) - 1;\n        /* We assume 8 bit non null strings, which is the case for these\n           symbols */\n        for(atom = JS_ATOM_Symbol_toPrimitive; atom < JS_ATOM_END; atom++) {\n            JSAtomStruct *p = ctx->rt->atom_array[atom];\n            JSString *str = p;\n            if (str->len == len && !memcmp(str->u.str8, name, len))\n                return JS_DupAtom(ctx, atom);\n        }\n        abort();\n    } else {\n        atom = JS_NewAtom(ctx, name);\n    }\n    return atom;\n}\n\nstatic JSValue JS_InstantiateFunctionListItem2(JSContext *ctx, JSObject *p,\n                                               JSAtom atom, void *opaque)\n{\n    const JSCFunctionListEntry *e = opaque;\n    JSValue val;\n\n    switch(e->def_type) {\n    case JS_DEF_CFUNC:\n        val = JS_NewCFunction2(ctx, e->u.func.cfunc.generic,\n                               e->name, e->u.func.length, e->u.func.cproto, e->magic);\n        break;\n    case JS_DEF_PROP_STRING:\n        val = JS_NewAtomString(ctx, e->u.str);\n        break;\n    case JS_DEF_OBJECT:\n        val = JS_NewObject(ctx);\n        JS_SetPropertyFunctionList(ctx, val, e->u.prop_list.tab, e->u.prop_list.len);\n        break;\n    default:\n        abort();\n    }\n    return val;\n}\n\nstatic int JS_InstantiateFunctionListItem(JSContext *ctx, JSValueConst obj,\n                                          JSAtom atom,\n                                          const JSCFunctionListEntry *e)\n{\n    JSValue val;\n    int prop_flags = e->prop_flags;\n\n    switch(e->def_type) {\n    case JS_DEF_ALIAS: /* using autoinit for aliases is not safe */\n        {\n            JSAtom atom1 = find_atom(ctx, e->u.alias.name);\n            switch (e->u.alias.base) {\n            case -1:\n                val = JS_GetProperty(ctx, obj, atom1);\n                break;\n            case 0:\n                val = JS_GetProperty(ctx, ctx->global_obj, atom1);\n                break;\n            case 1:\n                val = JS_GetProperty(ctx, ctx->class_proto[JS_CLASS_ARRAY], atom1);\n                break;\n            default:\n                abort();\n            }\n            JS_FreeAtom(ctx, atom1);\n            if (atom == JS_ATOM_Symbol_toPrimitive) {\n                /* Symbol.toPrimitive functions are not writable */\n                prop_flags = JS_PROP_CONFIGURABLE;\n            } else if (atom == JS_ATOM_Symbol_hasInstance) {\n                /* Function.prototype[Symbol.hasInstance] is not writable nor configurable */\n                prop_flags = 0;\n            }\n        }\n        break;\n    case JS_DEF_CFUNC:\n        if (atom == JS_ATOM_Symbol_toPrimitive) {\n            /* Symbol.toPrimitive functions are not writable */\n            prop_flags = JS_PROP_CONFIGURABLE;\n        } else if (atom == JS_ATOM_Symbol_hasInstance) {\n            /* Function.prototype[Symbol.hasInstance] is not writable nor configurable */\n            prop_flags = 0;\n        }\n        JS_DefineAutoInitProperty(ctx, obj, atom, JS_AUTOINIT_ID_PROP,\n                                  (void *)e, prop_flags);\n        return 0;\n    case JS_DEF_CGETSET: /* XXX: use autoinit again ? */\n    case JS_DEF_CGETSET_MAGIC:\n        {\n            JSValue getter, setter;\n            char buf[64];\n\n            getter = JS_UNDEFINED;\n            if (e->u.getset.get.generic) {\n                snprintf(buf, sizeof(buf), \"get %s\", e->name);\n                getter = JS_NewCFunction2(ctx, e->u.getset.get.generic,\n                                          buf, 0, e->def_type == JS_DEF_CGETSET_MAGIC ? JS_CFUNC_getter_magic : JS_CFUNC_getter,\n                                          e->magic);\n            }\n            setter = JS_UNDEFINED;\n            if (e->u.getset.set.generic) {\n                snprintf(buf, sizeof(buf), \"set %s\", e->name);\n                setter = JS_NewCFunction2(ctx, e->u.getset.set.generic,\n                                          buf, 1, e->def_type == JS_DEF_CGETSET_MAGIC ? JS_CFUNC_setter_magic : JS_CFUNC_setter,\n                                          e->magic);\n            }\n            JS_DefinePropertyGetSet(ctx, obj, atom, getter, setter, prop_flags);\n            return 0;\n        }\n        break;\n    case JS_DEF_PROP_INT32:\n        val = JS_NewInt32(ctx, e->u.i32);\n        break;\n    case JS_DEF_PROP_INT64:\n        val = JS_NewInt64(ctx, e->u.i64);\n        break;\n    case JS_DEF_PROP_DOUBLE:\n        val = __JS_NewFloat64(ctx, e->u.f64);\n        break;\n    case JS_DEF_PROP_UNDEFINED:\n        val = JS_UNDEFINED;\n        break;\n    case JS_DEF_PROP_STRING:\n    case JS_DEF_OBJECT:\n        JS_DefineAutoInitProperty(ctx, obj, atom, JS_AUTOINIT_ID_PROP,\n                                  (void *)e, prop_flags);\n        return 0;\n    default:\n        abort();\n    }\n    JS_DefinePropertyValue(ctx, obj, atom, val, prop_flags);\n    return 0;\n}\n\nvoid JS_SetPropertyFunctionList(JSContext *ctx, JSValueConst obj,\n                                const JSCFunctionListEntry *tab, int len)\n{\n    int i;\n\n    for (i = 0; i < len; i++) {\n        const JSCFunctionListEntry *e = &tab[i];\n        JSAtom atom = find_atom(ctx, e->name);\n        JS_InstantiateFunctionListItem(ctx, obj, atom, e);\n        JS_FreeAtom(ctx, atom);\n    }\n}\n\nint JS_AddModuleExportList(JSContext *ctx, JSModuleDef *m,\n                           const JSCFunctionListEntry *tab, int len)\n{\n    int i;\n    for(i = 0; i < len; i++) {\n        if (JS_AddModuleExport(ctx, m, tab[i].name))\n            return -1;\n    }\n    return 0;\n}\n\nint JS_SetModuleExportList(JSContext *ctx, JSModuleDef *m,\n                           const JSCFunctionListEntry *tab, int len)\n{\n    int i;\n    JSValue val;\n\n    for(i = 0; i < len; i++) {\n        const JSCFunctionListEntry *e = &tab[i];\n        switch(e->def_type) {\n        case JS_DEF_CFUNC:\n            val = JS_NewCFunction2(ctx, e->u.func.cfunc.generic,\n                                   e->name, e->u.func.length, e->u.func.cproto, e->magic);\n            break;\n        case JS_DEF_PROP_STRING:\n            val = JS_NewString(ctx, e->u.str);\n            break;\n        case JS_DEF_PROP_INT32:\n            val = JS_NewInt32(ctx, e->u.i32);\n            break;\n        case JS_DEF_PROP_INT64:\n            val = JS_NewInt64(ctx, e->u.i64);\n            break;\n        case JS_DEF_PROP_DOUBLE:\n            val = __JS_NewFloat64(ctx, e->u.f64);\n            break;\n        case JS_DEF_OBJECT:\n            val = JS_NewObject(ctx);\n            JS_SetPropertyFunctionList(ctx, val, e->u.prop_list.tab, e->u.prop_list.len);\n            break;\n        default:\n            abort();\n        }\n        if (JS_SetModuleExport(ctx, m, e->name, val))\n            return -1;\n    }\n    return 0;\n}\n\n/* Note: 'func_obj' is not necessarily a constructor */\nstatic void JS_SetConstructor2(JSContext *ctx,\n                               JSValueConst func_obj,\n                               JSValueConst proto,\n                               int proto_flags, int ctor_flags)\n{\n    JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_prototype,\n                           JS_DupValue(ctx, proto), proto_flags);\n    JS_DefinePropertyValue(ctx, proto, JS_ATOM_constructor,\n                           JS_DupValue(ctx, func_obj),\n                           ctor_flags);\n    set_cycle_flag(ctx, func_obj);\n    set_cycle_flag(ctx, proto);\n}\n\nvoid JS_SetConstructor(JSContext *ctx, JSValueConst func_obj, \n                       JSValueConst proto)\n{\n    JS_SetConstructor2(ctx, func_obj, proto,\n                       0, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n}\n\nstatic void JS_NewGlobalCConstructor2(JSContext *ctx,\n                                      JSValue func_obj,\n                                      const char *name,\n                                      JSValueConst proto)\n{\n    JS_DefinePropertyValueStr(ctx, ctx->global_obj, name,\n                           JS_DupValue(ctx, func_obj),\n                           JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    JS_SetConstructor(ctx, func_obj, proto);\n    JS_FreeValue(ctx, func_obj);\n}\n\nstatic JSValueConst JS_NewGlobalCConstructor(JSContext *ctx, const char *name,\n                                             JSCFunction *func, int length,\n                                             JSValueConst proto)\n{\n    JSValue func_obj;\n    func_obj = JS_NewCFunction2(ctx, func, name, length, JS_CFUNC_constructor_or_func, 0);\n    JS_NewGlobalCConstructor2(ctx, func_obj, name, proto);\n    return func_obj;\n}\n\nstatic JSValueConst JS_NewGlobalCConstructorOnly(JSContext *ctx, const char *name,\n                                                 JSCFunction *func, int length,\n                                                 JSValueConst proto)\n{\n    JSValue func_obj;\n    func_obj = JS_NewCFunction2(ctx, func, name, length, JS_CFUNC_constructor, 0);\n    JS_NewGlobalCConstructor2(ctx, func_obj, name, proto);\n    return func_obj;\n}\n\nstatic JSValue js_global_eval(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    return JS_EvalObject(ctx, ctx->global_obj, argv[0], JS_EVAL_TYPE_INDIRECT, -1);\n}\n\nstatic JSValue js_global_isNaN(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    double d;\n\n    /* XXX: does this work for bigfloat? */\n    if (unlikely(JS_ToFloat64(ctx, &d, argv[0])))\n        return JS_EXCEPTION;\n    return JS_NewBool(ctx, isnan(d));\n}\n\nstatic JSValue js_global_isFinite(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    BOOL res;\n    double d;\n    if (unlikely(JS_ToFloat64(ctx, &d, argv[0])))\n        return JS_EXCEPTION;\n    res = isfinite(d);\n    return JS_NewBool(ctx, res);\n}\n\n/* Object class */\n\nstatic JSValue JS_ToObject(JSContext *ctx, JSValueConst val)\n{\n    int tag = JS_VALUE_GET_NORM_TAG(val);\n    JSValue obj;\n\n    switch(tag) {\n    default:\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n        return JS_ThrowTypeError(ctx, \"cannot convert to object\");\n    case JS_TAG_OBJECT:\n    case JS_TAG_EXCEPTION:\n        return JS_DupValue(ctx, val);\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n        obj = JS_NewObjectClass(ctx, JS_CLASS_BIG_INT);\n        goto set_value;\n    case JS_TAG_BIG_FLOAT:\n        obj = JS_NewObjectClass(ctx, JS_CLASS_BIG_FLOAT);\n        goto set_value;\n    case JS_TAG_BIG_DECIMAL:\n        obj = JS_NewObjectClass(ctx, JS_CLASS_BIG_DECIMAL);\n        goto set_value;\n#endif\n    case JS_TAG_INT:\n    case JS_TAG_FLOAT64:\n        obj = JS_NewObjectClass(ctx, JS_CLASS_NUMBER);\n        goto set_value;\n    case JS_TAG_STRING:\n        /* XXX: should call the string constructor */\n        {\n            JSString *p1 = JS_VALUE_GET_STRING(val);\n            obj = JS_NewObjectClass(ctx, JS_CLASS_STRING);\n            JS_DefinePropertyValue(ctx, obj, JS_ATOM_length, JS_NewInt32(ctx, p1->len), 0);\n        }\n        goto set_value;\n    case JS_TAG_BOOL:\n        obj = JS_NewObjectClass(ctx, JS_CLASS_BOOLEAN);\n        goto set_value;\n    case JS_TAG_SYMBOL:\n        obj = JS_NewObjectClass(ctx, JS_CLASS_SYMBOL);\n    set_value:\n        if (!JS_IsException(obj))\n            JS_SetObjectData(ctx, obj, JS_DupValue(ctx, val));\n        return obj;\n    }\n}\n\nstatic JSValue JS_ToObjectFree(JSContext *ctx, JSValue val)\n{\n    JSValue obj = JS_ToObject(ctx, val);\n    JS_FreeValue(ctx, val);\n    return obj;\n}\n\nstatic int js_obj_to_desc(JSContext *ctx, JSPropertyDescriptor *d,\n                          JSValueConst desc)\n{\n    JSValue val, getter, setter;\n    int flags;\n\n    if (!JS_IsObject(desc)) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        return -1;\n    }\n    flags = 0;\n    val = JS_UNDEFINED;\n    getter = JS_UNDEFINED;\n    setter = JS_UNDEFINED;\n    if (JS_HasProperty(ctx, desc, JS_ATOM_configurable)) {\n        JSValue prop = JS_GetProperty(ctx, desc, JS_ATOM_configurable);\n        if (JS_IsException(prop))\n            goto fail;\n        flags |= JS_PROP_HAS_CONFIGURABLE;\n        if (JS_ToBoolFree(ctx, prop))\n            flags |= JS_PROP_CONFIGURABLE;\n    }\n    if (JS_HasProperty(ctx, desc, JS_ATOM_writable)) {\n        JSValue prop = JS_GetProperty(ctx, desc, JS_ATOM_writable);\n        if (JS_IsException(prop))\n            goto fail;\n        flags |= JS_PROP_HAS_WRITABLE;\n        if (JS_ToBoolFree(ctx, prop))\n            flags |= JS_PROP_WRITABLE;\n    }\n    if (JS_HasProperty(ctx, desc, JS_ATOM_enumerable)) {\n        JSValue prop = JS_GetProperty(ctx, desc, JS_ATOM_enumerable);\n        if (JS_IsException(prop))\n            goto fail;\n        flags |= JS_PROP_HAS_ENUMERABLE;\n        if (JS_ToBoolFree(ctx, prop))\n            flags |= JS_PROP_ENUMERABLE;\n    }\n    if (JS_HasProperty(ctx, desc, JS_ATOM_value)) {\n        flags |= JS_PROP_HAS_VALUE;\n        val = JS_GetProperty(ctx, desc, JS_ATOM_value);\n        if (JS_IsException(val))\n            goto fail;\n    }\n    if (JS_HasProperty(ctx, desc, JS_ATOM_get)) {\n        flags |= JS_PROP_HAS_GET;\n        getter = JS_GetProperty(ctx, desc, JS_ATOM_get);\n        if (JS_IsException(getter) ||\n            !(JS_IsUndefined(getter) || JS_IsFunction(ctx, getter))) {\n            JS_ThrowTypeError(ctx, \"invalid getter\");\n            goto fail;\n        }\n    }\n    if (JS_HasProperty(ctx, desc, JS_ATOM_set)) {\n        flags |= JS_PROP_HAS_SET;\n        setter = JS_GetProperty(ctx, desc, JS_ATOM_set);\n        if (JS_IsException(setter) ||\n            !(JS_IsUndefined(setter) || JS_IsFunction(ctx, setter))) {\n            JS_ThrowTypeError(ctx, \"invalid setter\");\n            goto fail;\n        }\n    }\n    if ((flags & (JS_PROP_HAS_SET | JS_PROP_HAS_GET)) &&\n        (flags & (JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE))) {\n        JS_ThrowTypeError(ctx, \"cannot have setter/getter and value or writable\");\n        goto fail;\n    }\n    d->flags = flags;\n    d->value = val;\n    d->getter = getter;\n    d->setter = setter;\n    return 0;\n fail:\n    JS_FreeValue(ctx, val);\n    JS_FreeValue(ctx, getter);\n    JS_FreeValue(ctx, setter);\n    return -1;\n}\n\nstatic __exception int JS_DefinePropertyDesc(JSContext *ctx, JSValueConst obj,\n                                             JSAtom prop, JSValueConst desc,\n                                             int flags)\n{\n    JSPropertyDescriptor d;\n    int ret;\n\n    if (js_obj_to_desc(ctx, &d, desc) < 0)\n        return -1;\n\n    ret = JS_DefineProperty(ctx, obj, prop,\n                            d.value, d.getter, d.setter, d.flags | flags);\n    js_free_desc(ctx, &d);\n    return ret;\n}\n\nstatic __exception int JS_ObjectDefineProperties(JSContext *ctx,\n                                                 JSValueConst obj,\n                                                 JSValueConst properties)\n{\n    JSValue props, desc;\n    JSObject *p;\n    JSPropertyEnum *atoms;\n    uint32_t len, i;\n    int ret = -1;\n\n    if (!JS_IsObject(obj)) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        return -1;\n    }\n    desc = JS_UNDEFINED;\n    props = JS_ToObject(ctx, properties);\n    if (JS_IsException(props))\n        return -1;\n    p = JS_VALUE_GET_OBJ(props);\n    if (JS_GetOwnPropertyNamesInternal(ctx, &atoms, &len, p, JS_GPN_ENUM_ONLY | JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK) < 0)\n        goto exception;\n    for(i = 0; i < len; i++) {\n        JS_FreeValue(ctx, desc);\n        desc = JS_GetProperty(ctx, props, atoms[i].atom);\n        if (JS_IsException(desc))\n            goto exception;\n        if (JS_DefinePropertyDesc(ctx, obj, atoms[i].atom, desc, JS_PROP_THROW) < 0)\n            goto exception;\n    }\n    ret = 0;\n\nexception:\n    js_free_prop_enum(ctx, atoms, len);\n    JS_FreeValue(ctx, props);\n    JS_FreeValue(ctx, desc);\n    return ret;\n}\n\nstatic JSValue js_object_constructor(JSContext *ctx, JSValueConst new_target,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue ret;\n    if (!JS_IsUndefined(new_target) &&\n        JS_VALUE_GET_OBJ(new_target) !=\n        JS_VALUE_GET_OBJ(JS_GetActiveFunction(ctx))) {\n        ret = js_create_from_ctor(ctx, new_target, JS_CLASS_OBJECT);\n    } else {\n        int tag = JS_VALUE_GET_NORM_TAG(argv[0]);\n        switch(tag) {\n        case JS_TAG_NULL:\n        case JS_TAG_UNDEFINED:\n            ret = JS_NewObject(ctx);\n            break;\n        default:\n            ret = JS_ToObject(ctx, argv[0]);\n            break;\n        }\n    }\n    return ret;\n}\n\nstatic JSValue js_object_create(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValueConst proto, props;\n    JSValue obj;\n\n    proto = argv[0];\n    if (!JS_IsObject(proto) && !JS_IsNull(proto))\n        return JS_ThrowTypeError(ctx, \"not a prototype\");\n    obj = JS_NewObjectProto(ctx, proto);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    props = argv[1];\n    if (!JS_IsUndefined(props)) {\n        if (JS_ObjectDefineProperties(ctx, obj, props)) {\n            JS_FreeValue(ctx, obj);\n            return JS_EXCEPTION;\n        }\n    }\n    return obj;\n}\n\nstatic JSValue js_object_getPrototypeOf(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv, int magic)\n{\n    JSValueConst val;\n\n    val = argv[0];\n    if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) {\n        /* ES6 feature non compatible with ES5.1: primitive types are\n           accepted */\n        if (magic || JS_VALUE_GET_TAG(val) == JS_TAG_NULL ||\n            JS_VALUE_GET_TAG(val) == JS_TAG_UNDEFINED)\n            return JS_ThrowTypeErrorNotAnObject(ctx);\n    }\n    return JS_GetPrototype(ctx, val);\n}\n\nstatic JSValue js_object_setPrototypeOf(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv)\n{\n    JSValueConst obj;\n    obj = argv[0];\n    if (JS_SetPrototypeInternal(ctx, obj, argv[1], TRUE) < 0)\n        return JS_EXCEPTION;\n    return JS_DupValue(ctx, obj);\n}\n\n/* magic = 1 if called as Reflect.defineProperty */\nstatic JSValue js_object_defineProperty(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv, int magic)\n{\n    JSValueConst obj, prop, desc;\n    int ret, flags;\n    JSAtom atom;\n\n    obj = argv[0];\n    prop = argv[1];\n    desc = argv[2];\n\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    atom = JS_ValueToAtom(ctx, prop);\n    if (unlikely(atom == JS_ATOM_NULL))\n        return JS_EXCEPTION;\n    flags = 0;\n    if (!magic)\n        flags |= JS_PROP_THROW;\n    ret = JS_DefinePropertyDesc(ctx, obj, atom, desc, flags);\n    JS_FreeAtom(ctx, atom);\n    if (ret < 0) {\n        return JS_EXCEPTION;\n    } else if (magic) {\n        return JS_NewBool(ctx, ret);\n    } else {\n        return JS_DupValue(ctx, obj);\n    }\n}\n\nstatic JSValue js_object_defineProperties(JSContext *ctx, JSValueConst this_val,\n                                          int argc, JSValueConst *argv)\n{\n    // defineProperties(obj, properties)\n    JSValueConst obj = argv[0];\n\n    if (JS_ObjectDefineProperties(ctx, obj, argv[1]))\n        return JS_EXCEPTION;\n    else\n        return JS_DupValue(ctx, obj);\n}\n\n/* magic = 1 if called as __defineSetter__ */\nstatic JSValue js_object___defineGetter__(JSContext *ctx, JSValueConst this_val,\n                                          int argc, JSValueConst *argv, int magic)\n{\n    JSValue obj;\n    JSValueConst prop, value, get, set;\n    int ret, flags;\n    JSAtom atom;\n\n    prop = argv[0];\n    value = argv[1];\n\n    obj = JS_ToObject(ctx, this_val);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n\n    if (check_function(ctx, value)) {\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    atom = JS_ValueToAtom(ctx, prop);\n    if (unlikely(atom == JS_ATOM_NULL)) {\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    flags = JS_PROP_THROW |\n        JS_PROP_HAS_ENUMERABLE | JS_PROP_ENUMERABLE |\n        JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE;\n    if (magic) {\n        get = JS_UNDEFINED;\n        set = value;\n        flags |= JS_PROP_HAS_SET;\n    } else {\n        get = value;\n        set = JS_UNDEFINED;\n        flags |= JS_PROP_HAS_GET;\n    }\n    ret = JS_DefineProperty(ctx, obj, atom, JS_UNDEFINED, get, set, flags);\n    JS_FreeValue(ctx, obj);\n    JS_FreeAtom(ctx, atom);\n    if (ret < 0) {\n        return JS_EXCEPTION;\n    } else {\n        return JS_UNDEFINED;\n    }\n}\n\nstatic JSValue js_object_getOwnPropertyDescriptor(JSContext *ctx, JSValueConst this_val,\n                                                  int argc, JSValueConst *argv, int magic)\n{\n    JSValueConst prop;\n    JSAtom atom;\n    JSValue ret, obj;\n    JSPropertyDescriptor desc;\n    int res, flags;\n\n    if (magic) {\n        /* Reflect.getOwnPropertyDescriptor case */\n        if (JS_VALUE_GET_TAG(argv[0]) != JS_TAG_OBJECT)\n            return JS_ThrowTypeErrorNotAnObject(ctx);\n        obj = JS_DupValue(ctx, argv[0]);\n    } else {\n        obj = JS_ToObject(ctx, argv[0]);\n        if (JS_IsException(obj))\n            return obj;\n    }\n    prop = argv[1];\n    atom = JS_ValueToAtom(ctx, prop);\n    if (unlikely(atom == JS_ATOM_NULL))\n        goto exception;\n    ret = JS_UNDEFINED;\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        res = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(obj), atom);\n        if (res < 0)\n            goto exception;\n        if (res) {\n            ret = JS_NewObject(ctx);\n            if (JS_IsException(ret))\n                goto exception1;\n            flags = JS_PROP_C_W_E | JS_PROP_THROW;\n            if (desc.flags & JS_PROP_GETSET) {\n                if (JS_DefinePropertyValue(ctx, ret, JS_ATOM_get, JS_DupValue(ctx, desc.getter), flags) < 0\n                ||  JS_DefinePropertyValue(ctx, ret, JS_ATOM_set, JS_DupValue(ctx, desc.setter), flags) < 0)\n                    goto exception1;\n            } else {\n                if (JS_DefinePropertyValue(ctx, ret, JS_ATOM_value, JS_DupValue(ctx, desc.value), flags) < 0\n                ||  JS_DefinePropertyValue(ctx, ret, JS_ATOM_writable,\n                                           JS_NewBool(ctx, (desc.flags & JS_PROP_WRITABLE) != 0), flags) < 0)\n                    goto exception1;\n            }\n            if (JS_DefinePropertyValue(ctx, ret, JS_ATOM_enumerable,\n                                       JS_NewBool(ctx, (desc.flags & JS_PROP_ENUMERABLE) != 0), flags) < 0\n            ||  JS_DefinePropertyValue(ctx, ret, JS_ATOM_configurable,\n                                       JS_NewBool(ctx, (desc.flags & JS_PROP_CONFIGURABLE) != 0), flags) < 0)\n                goto exception1;\n            js_free_desc(ctx, &desc);\n        }\n    }\n    JS_FreeAtom(ctx, atom);\n    JS_FreeValue(ctx, obj);\n    return ret;\n\nexception1:\n    js_free_desc(ctx, &desc);\n    JS_FreeValue(ctx, ret);\nexception:\n    JS_FreeAtom(ctx, atom);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_object_getOwnPropertyDescriptors(JSContext *ctx, JSValueConst this_val,\n                                                   int argc, JSValueConst *argv)\n{\n    //getOwnPropertyDescriptors(obj)\n    JSValue obj, r;\n    JSObject *p;\n    JSPropertyEnum *props;\n    uint32_t len, i;\n\n    r = JS_UNDEFINED;\n    obj = JS_ToObject(ctx, argv[0]);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n\n    p = JS_VALUE_GET_OBJ(obj);\n    if (JS_GetOwnPropertyNamesInternal(ctx, &props, &len, p,\n                               JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK))\n        goto exception;\n    r = JS_NewObject(ctx);\n    if (JS_IsException(r))\n        goto exception;\n    for(i = 0; i < len; i++) {\n        JSValue atomValue, desc;\n        JSValueConst args[2];\n\n        atomValue = JS_AtomToValue(ctx, props[i].atom);\n        if (JS_IsException(atomValue))\n            goto exception;\n        args[0] = obj;\n        args[1] = atomValue;\n        desc = js_object_getOwnPropertyDescriptor(ctx, JS_UNDEFINED, 2, args, 0);\n        JS_FreeValue(ctx, atomValue);\n        if (JS_IsException(desc))\n            goto exception;\n        if (!JS_IsUndefined(desc)) {\n            if (JS_DefinePropertyValue(ctx, r, props[i].atom, desc,\n                                       JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                goto exception;\n        }\n    }\n    js_free_prop_enum(ctx, props, len);\n    JS_FreeValue(ctx, obj);\n    return r;\n\nexception:\n    js_free_prop_enum(ctx, props, len);\n    JS_FreeValue(ctx, obj);\n    JS_FreeValue(ctx, r);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_GetOwnPropertyNames2(JSContext *ctx, JSValueConst obj1,\n                                       int flags, int kind)\n{\n    JSValue obj, r, val, key, value;\n    JSObject *p;\n    JSPropertyEnum *atoms;\n    uint32_t len, i, j;\n\n    r = JS_UNDEFINED;\n    val = JS_UNDEFINED;\n    obj = JS_ToObject(ctx, obj1);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    p = JS_VALUE_GET_OBJ(obj);\n    if (JS_GetOwnPropertyNamesInternal(ctx, &atoms, &len, p, flags & ~JS_GPN_ENUM_ONLY))\n        goto exception;\n    r = JS_NewArray(ctx);\n    if (JS_IsException(r))\n        goto exception;\n    for(j = i = 0; i < len; i++) {\n        JSAtom atom = atoms[i].atom;\n        if (flags & JS_GPN_ENUM_ONLY) {\n            JSPropertyDescriptor desc;\n            int res;\n\n            /* Check if property is still enumerable */\n            res = JS_GetOwnPropertyInternal(ctx, &desc, p, atom);\n            if (res < 0)\n                goto exception;\n            if (!res)\n                continue;\n            js_free_desc(ctx, &desc);\n            if (!(desc.flags & JS_PROP_ENUMERABLE))\n                continue;\n        }\n        switch(kind) {\n        default:\n        case JS_ITERATOR_KIND_KEY:\n            val = JS_AtomToValue(ctx, atom);\n            if (JS_IsException(val))\n                goto exception;\n            break;\n        case JS_ITERATOR_KIND_VALUE:\n            val = JS_GetProperty(ctx, obj, atom);\n            if (JS_IsException(val))\n                goto exception;\n            break;\n        case JS_ITERATOR_KIND_KEY_AND_VALUE:\n            val = JS_NewArray(ctx);\n            if (JS_IsException(val))\n                goto exception;\n            key = JS_AtomToValue(ctx, atom);\n            if (JS_IsException(key))\n                goto exception1;\n            if (JS_CreateDataPropertyUint32(ctx, val, 0, key, JS_PROP_THROW) < 0)\n                goto exception1;\n            value = JS_GetProperty(ctx, obj, atom);\n            if (JS_IsException(value))\n                goto exception1;\n            if (JS_CreateDataPropertyUint32(ctx, val, 1, value, JS_PROP_THROW) < 0)\n                goto exception1;\n            break;\n        }\n        if (JS_CreateDataPropertyUint32(ctx, r, j++, val, 0) < 0)\n            goto exception;\n    }\n    goto done;\n\nexception1:\n    JS_FreeValue(ctx, val);\nexception:\n    JS_FreeValue(ctx, r);\n    r = JS_EXCEPTION;\ndone:\n    js_free_prop_enum(ctx, atoms, len);\n    JS_FreeValue(ctx, obj);\n    return r;\n}\n\nstatic JSValue js_object_getOwnPropertyNames(JSContext *ctx, JSValueConst this_val,\n                                             int argc, JSValueConst *argv)\n{\n    return JS_GetOwnPropertyNames2(ctx, argv[0],\n                                   JS_GPN_STRING_MASK, JS_ITERATOR_KIND_KEY);\n}\n\nstatic JSValue js_object_getOwnPropertySymbols(JSContext *ctx, JSValueConst this_val,\n                                             int argc, JSValueConst *argv)\n{\n    return JS_GetOwnPropertyNames2(ctx, argv[0],\n                                   JS_GPN_SYMBOL_MASK, JS_ITERATOR_KIND_KEY);\n}\n\nstatic JSValue js_object_keys(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int kind)\n{\n    return JS_GetOwnPropertyNames2(ctx, argv[0],\n                                   JS_GPN_ENUM_ONLY | JS_GPN_STRING_MASK, kind);\n}\n\nstatic JSValue js_object_isExtensible(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv, int reflect)\n{\n    JSValueConst obj;\n    int ret;\n\n    obj = argv[0];\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) {\n        if (reflect)\n            return JS_ThrowTypeErrorNotAnObject(ctx);\n        else\n            return JS_FALSE;\n    }\n    ret = JS_IsExtensible(ctx, obj);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_object_preventExtensions(JSContext *ctx, JSValueConst this_val,\n                                           int argc, JSValueConst *argv, int reflect)\n{\n    JSValueConst obj;\n    int ret;\n\n    obj = argv[0];\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) {\n        if (reflect)\n            return JS_ThrowTypeErrorNotAnObject(ctx);\n        else\n            return JS_DupValue(ctx, obj);\n    }\n    ret = JS_PreventExtensions(ctx, obj);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    if (reflect) {\n        return JS_NewBool(ctx, ret);\n    } else {\n        if (!ret)\n            return JS_ThrowTypeError(ctx, \"proxy preventExtensions handler returned false\");\n        return JS_DupValue(ctx, obj);\n    }\n}\n\nstatic JSValue js_object_hasOwnProperty(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv)\n{\n    JSValue obj;\n    JSAtom atom;\n    JSObject *p;\n    BOOL ret;\n\n    atom = JS_ValueToAtom(ctx, argv[0]); /* must be done first */\n    if (unlikely(atom == JS_ATOM_NULL))\n        return JS_EXCEPTION;\n    obj = JS_ToObject(ctx, this_val);\n    if (JS_IsException(obj)) {\n        JS_FreeAtom(ctx, atom);\n        return obj;\n    }\n    p = JS_VALUE_GET_OBJ(obj);\n    ret = JS_GetOwnPropertyInternal(ctx, NULL, p, atom);\n    JS_FreeAtom(ctx, atom);\n    JS_FreeValue(ctx, obj);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_object_valueOf(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    return JS_ToObject(ctx, this_val);\n}\n\nstatic JSValue js_object_toString(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    JSValue obj, tag;\n    int is_array;\n    JSAtom atom;\n    JSObject *p;\n\n    if (JS_IsNull(this_val)) {\n        tag = JS_NewString(ctx, \"Null\");\n    } else if (JS_IsUndefined(this_val)) {\n        tag = JS_NewString(ctx, \"Undefined\");\n    } else {\n        obj = JS_ToObject(ctx, this_val);\n        if (JS_IsException(obj))\n            return obj;\n        is_array = JS_IsArray(ctx, obj);\n        if (is_array < 0) {\n            JS_FreeValue(ctx, obj);\n            return JS_EXCEPTION;\n        }\n        if (is_array) {\n            atom = JS_ATOM_Array;\n        } else if (JS_IsFunction(ctx, obj)) {\n            atom = JS_ATOM_Function;\n        } else {\n            p = JS_VALUE_GET_OBJ(obj);\n            switch(p->class_id) {\n            case JS_CLASS_STRING:\n            case JS_CLASS_ARGUMENTS:\n            case JS_CLASS_MAPPED_ARGUMENTS:\n            case JS_CLASS_ERROR:\n            case JS_CLASS_BOOLEAN:\n            case JS_CLASS_NUMBER:\n            case JS_CLASS_DATE:\n            case JS_CLASS_REGEXP:\n                atom = ctx->rt->class_array[p->class_id].class_name;\n                break;\n            default:\n                atom = JS_ATOM_Object;\n                break;\n            }\n        }\n        tag = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_toStringTag);\n        JS_FreeValue(ctx, obj);\n        if (JS_IsException(tag))\n            return JS_EXCEPTION;\n        if (!JS_IsString(tag)) {\n            JS_FreeValue(ctx, tag);\n            tag = JS_AtomToString(ctx, atom);\n        }\n    }\n    return JS_ConcatString3(ctx, \"[object \", tag, \"]\");\n}\n\nstatic JSValue js_object_toLocaleString(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv)\n{\n    return JS_Invoke(ctx, this_val, JS_ATOM_toString, 0, NULL);\n}\n\nstatic JSValue js_object_assign(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    // Object.assign(obj, source1)\n    JSValue obj, s;\n    int i;\n\n    s = JS_UNDEFINED;\n    obj = JS_ToObject(ctx, argv[0]);\n    if (JS_IsException(obj))\n        goto exception;\n    for (i = 1; i < argc; i++) {\n        if (!JS_IsNull(argv[i]) && !JS_IsUndefined(argv[i])) {\n            s = JS_ToObject(ctx, argv[i]);\n            if (JS_IsException(s))\n                goto exception;\n            if (JS_CopyDataProperties(ctx, obj, s, JS_UNDEFINED, TRUE))\n                goto exception;\n            JS_FreeValue(ctx, s);\n        }\n    }\n    return obj;\nexception:\n    JS_FreeValue(ctx, obj);\n    JS_FreeValue(ctx, s);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_object_seal(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int freeze_flag)\n{\n    JSValueConst obj = argv[0];\n    JSObject *p;\n    JSPropertyEnum *props;\n    uint32_t len, i;\n    int flags, desc_flags, res;\n\n    if (!JS_IsObject(obj))\n        return JS_DupValue(ctx, obj);\n\n    res = JS_PreventExtensions(ctx, obj);\n    if (res < 0)\n        return JS_EXCEPTION;\n    if (!res) {\n        return JS_ThrowTypeError(ctx, \"proxy preventExtensions handler returned false\");\n    }\n    \n    p = JS_VALUE_GET_OBJ(obj);\n    flags = JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK;\n    if (JS_GetOwnPropertyNamesInternal(ctx, &props, &len, p, flags))\n        return JS_EXCEPTION;\n\n    for(i = 0; i < len; i++) {\n        JSPropertyDescriptor desc;\n        JSAtom prop = props[i].atom;\n\n        desc_flags = JS_PROP_THROW | JS_PROP_HAS_CONFIGURABLE;\n        if (freeze_flag) {\n            res = JS_GetOwnPropertyInternal(ctx, &desc, p, prop);\n            if (res < 0)\n                goto exception;\n            if (res) {\n                if (desc.flags & JS_PROP_WRITABLE)\n                    desc_flags |= JS_PROP_HAS_WRITABLE;\n                js_free_desc(ctx, &desc);\n            }\n        }\n        if (JS_DefineProperty(ctx, obj, prop, JS_UNDEFINED,\n                              JS_UNDEFINED, JS_UNDEFINED, desc_flags) < 0)\n            goto exception;\n    }\n    js_free_prop_enum(ctx, props, len);\n    return JS_DupValue(ctx, obj);\n\n exception:\n    js_free_prop_enum(ctx, props, len);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_object_isSealed(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv, int is_frozen)\n{\n    JSValueConst obj = argv[0];\n    JSObject *p;\n    JSPropertyEnum *props;\n    uint32_t len, i;\n    int flags, res;\n    \n    if (!JS_IsObject(obj))\n        return JS_TRUE;\n\n    p = JS_VALUE_GET_OBJ(obj);\n    flags = JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK;\n    if (JS_GetOwnPropertyNamesInternal(ctx, &props, &len, p, flags))\n        return JS_EXCEPTION;\n\n    for(i = 0; i < len; i++) {\n        JSPropertyDescriptor desc;\n        JSAtom prop = props[i].atom;\n\n        res = JS_GetOwnPropertyInternal(ctx, &desc, p, prop);\n        if (res < 0)\n            goto exception;\n        if (res) {\n            js_free_desc(ctx, &desc);\n            if ((desc.flags & JS_PROP_CONFIGURABLE)\n            ||  (is_frozen && (desc.flags & JS_PROP_WRITABLE))) {\n                res = FALSE;\n                goto done;\n            }\n        }\n    }\n    res = JS_IsExtensible(ctx, obj);\n    if (res < 0)\n        return JS_EXCEPTION;\n    res ^= 1;\ndone:        \n    js_free_prop_enum(ctx, props, len);\n    return JS_NewBool(ctx, res);\n\nexception:\n    js_free_prop_enum(ctx, props, len);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_object_fromEntries(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue obj, iter, next_method = JS_UNDEFINED;\n    JSValueConst iterable;\n    BOOL done;\n\n    /*  RequireObjectCoercible() not necessary because it is tested in\n        JS_GetIterator() by JS_GetProperty() */\n    iterable = argv[0];\n\n    obj = JS_NewObject(ctx);\n    if (JS_IsException(obj))\n        return obj;\n    \n    iter = JS_GetIterator(ctx, iterable, FALSE);\n    if (JS_IsException(iter))\n        goto fail;\n    next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);\n    if (JS_IsException(next_method))\n        goto fail;\n    \n    for(;;) {\n        JSValue key, value, item;\n        item = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);\n        if (JS_IsException(item))\n            goto fail;\n        if (done) {\n            JS_FreeValue(ctx, item);\n            break;\n        }\n        \n        key = JS_UNDEFINED;\n        value = JS_UNDEFINED;\n        if (!JS_IsObject(item)) {\n            JS_ThrowTypeErrorNotAnObject(ctx);\n            goto fail1;\n        }\n        key = JS_GetPropertyUint32(ctx, item, 0);\n        if (JS_IsException(key))\n            goto fail1;\n        value = JS_GetPropertyUint32(ctx, item, 1);\n        if (JS_IsException(value)) {\n            JS_FreeValue(ctx, key);\n            goto fail1;\n        }\n        if (JS_DefinePropertyValueValue(ctx, obj, key, value,\n                                        JS_PROP_C_W_E | JS_PROP_THROW) < 0) {\n        fail1:\n            JS_FreeValue(ctx, item);\n            goto fail;\n        }\n        JS_FreeValue(ctx, item);\n    }\n    JS_FreeValue(ctx, next_method);\n    JS_FreeValue(ctx, iter);\n    return obj;\n fail:\n    if (JS_IsObject(iter)) {\n        /* close the iterator object, preserving pending exception */\n        JS_IteratorClose(ctx, iter, TRUE);\n    }\n    JS_FreeValue(ctx, next_method);\n    JS_FreeValue(ctx, iter);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\n#if 0\n/* Note: corresponds to ECMA spec: CreateDataPropertyOrThrow() */\nstatic JSValue js_object___setOwnProperty(JSContext *ctx, JSValueConst this_val,\n                                          int argc, JSValueConst *argv)\n{\n    int ret;\n    ret = JS_DefinePropertyValueValue(ctx, argv[0], JS_DupValue(ctx, argv[1]),\n                                      JS_DupValue(ctx, argv[2]),\n                                      JS_PROP_C_W_E | JS_PROP_THROW);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_object___toObject(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    return JS_ToObject(ctx, argv[0]);\n}\n\nstatic JSValue js_object___toPrimitive(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    int hint = HINT_NONE;\n\n    if (JS_VALUE_GET_TAG(argv[1]) == JS_TAG_INT)\n        hint = JS_VALUE_GET_INT(argv[1]);\n\n    return JS_ToPrimitive(ctx, argv[0], hint);\n}\n#endif\n\n/* return an empty string if not an object */\nstatic JSValue js_object___getClass(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSAtom atom;\n    JSObject *p;\n    uint32_t tag;\n    int class_id;\n\n    tag = JS_VALUE_GET_NORM_TAG(argv[0]);\n    if (tag == JS_TAG_OBJECT) {\n        p = JS_VALUE_GET_OBJ(argv[0]);\n        class_id = p->class_id;\n        if (class_id == JS_CLASS_PROXY && JS_IsFunction(ctx, argv[0]))\n            class_id = JS_CLASS_BYTECODE_FUNCTION;\n        atom = ctx->rt->class_array[class_id].class_name;\n    } else {\n        atom = JS_ATOM_empty_string;\n    }\n    return JS_AtomToString(ctx, atom);\n}\n\nstatic JSValue js_object_is(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv)\n{\n    return JS_NewBool(ctx, js_same_value(ctx, argv[0], argv[1]));\n}\n\n#if 0\nstatic JSValue js_object___getObjectData(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    return JS_GetObjectData(ctx, argv[0]);\n}\n\nstatic JSValue js_object___setObjectData(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    if (JS_SetObjectData(ctx, argv[0], JS_DupValue(ctx, argv[1])))\n        return JS_EXCEPTION;\n    return JS_DupValue(ctx, argv[1]);\n}\n\nstatic JSValue js_object___toPropertyKey(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    return JS_ToPropertyKey(ctx, argv[0]);\n}\n\nstatic JSValue js_object___isObject(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    return JS_NewBool(ctx, JS_IsObject(argv[0]));\n}\n\nstatic JSValue js_object___isSameValueZero(JSContext *ctx, JSValueConst this_val,\n                                           int argc, JSValueConst *argv)\n{\n    return JS_NewBool(ctx, js_same_value_zero(ctx, argv[0], argv[1]));\n}\n\nstatic JSValue js_object___isConstructor(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    return JS_NewBool(ctx, JS_IsConstructor(ctx, argv[0]));\n}\n#endif\n\nstatic JSValue JS_SpeciesConstructor(JSContext *ctx, JSValueConst obj,\n                                     JSValueConst defaultConstructor)\n{\n    JSValue ctor, species;\n\n    if (!JS_IsObject(obj))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    ctor = JS_GetProperty(ctx, obj, JS_ATOM_constructor);\n    if (JS_IsException(ctor))\n        return ctor;\n    if (JS_IsUndefined(ctor))\n        return JS_DupValue(ctx, defaultConstructor);\n    if (!JS_IsObject(ctor)) {\n        JS_FreeValue(ctx, ctor);\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    }\n    species = JS_GetProperty(ctx, ctor, JS_ATOM_Symbol_species);\n    JS_FreeValue(ctx, ctor);\n    if (JS_IsException(species))\n        return species;\n    if (JS_IsUndefined(species) || JS_IsNull(species))\n        return JS_DupValue(ctx, defaultConstructor);\n    if (!JS_IsConstructor(ctx, species)) {\n        JS_FreeValue(ctx, species);\n        return JS_ThrowTypeError(ctx, \"not a constructor\");\n    }\n    return species;\n}\n\n#if 0\nstatic JSValue js_object___speciesConstructor(JSContext *ctx, JSValueConst this_val,\n                                              int argc, JSValueConst *argv)\n{\n    return JS_SpeciesConstructor(ctx, argv[0], argv[1]);\n}\n#endif\n\nstatic JSValue js_object_get___proto__(JSContext *ctx, JSValueConst this_val)\n{\n    JSValue val, ret;\n\n    val = JS_ToObject(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    ret = JS_GetPrototype(ctx, val);\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nstatic JSValue js_object_set___proto__(JSContext *ctx, JSValueConst this_val,\n                                       JSValueConst proto)\n{\n    if (JS_IsUndefined(this_val) || JS_IsNull(this_val))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    if (!JS_IsObject(proto) && !JS_IsNull(proto))\n        return JS_UNDEFINED;\n    if (JS_SetPrototypeInternal(ctx, this_val, proto, TRUE) < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_UNDEFINED;\n}\n\nstatic JSValue js_object_isPrototypeOf(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    JSValue obj, v1;\n    JSValueConst v;\n    int res;\n\n    v = argv[0];\n    if (!JS_IsObject(v))\n        return JS_FALSE;\n    obj = JS_ToObject(ctx, this_val);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    v1 = JS_DupValue(ctx, v);\n    for(;;) {\n        v1 = JS_GetPrototypeFree(ctx, v1);\n        if (JS_IsException(v1))\n            goto exception;\n        if (JS_IsNull(v1)) {\n            res = FALSE;\n            break;\n        }\n        if (JS_VALUE_GET_OBJ(obj) == JS_VALUE_GET_OBJ(v1)) {\n            res = TRUE;\n            break;\n        }\n        /* avoid infinite loop (possible with proxies) */\n        if (js_poll_interrupts(ctx))\n            goto exception;\n    }\n    JS_FreeValue(ctx, v1);\n    JS_FreeValue(ctx, obj);\n    return JS_NewBool(ctx, res);\n\nexception:\n    JS_FreeValue(ctx, v1);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_object_propertyIsEnumerable(JSContext *ctx, JSValueConst this_val,\n                                              int argc, JSValueConst *argv)\n{\n    JSValue obj, res = JS_EXCEPTION;\n    JSAtom prop = JS_ATOM_NULL;\n    JSPropertyDescriptor desc;\n    int has_prop;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (JS_IsException(obj))\n        goto exception;\n    prop = JS_ValueToAtom(ctx, argv[0]);\n    if (unlikely(prop == JS_ATOM_NULL))\n        goto exception;\n\n    has_prop = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(obj), prop);\n    if (has_prop < 0)\n        goto exception;\n    if (has_prop) {\n        res = JS_NewBool(ctx, (desc.flags & JS_PROP_ENUMERABLE) != 0);\n        js_free_desc(ctx, &desc);\n    } else {\n        res = JS_FALSE;\n    }\n\nexception:\n    JS_FreeAtom(ctx, prop);\n    JS_FreeValue(ctx, obj);\n    return res;\n}\n\nstatic JSValue js_object___lookupGetter__(JSContext *ctx, JSValueConst this_val,\n                                          int argc, JSValueConst *argv, int setter)\n{\n    JSValue obj, res = JS_EXCEPTION;\n    JSAtom prop = JS_ATOM_NULL;\n    JSPropertyDescriptor desc;\n    int has_prop;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (JS_IsException(obj))\n        goto exception;\n    prop = JS_ValueToAtom(ctx, argv[0]);\n    if (unlikely(prop == JS_ATOM_NULL))\n        goto exception;\n\n    for (;;) {\n        has_prop = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(obj), prop);\n        if (has_prop < 0)\n            goto exception;\n        if (has_prop) {\n            if (desc.flags & JS_PROP_GETSET)\n                res = JS_DupValue(ctx, setter ? desc.setter : desc.getter);\n            else\n                res = JS_UNDEFINED;\n            js_free_desc(ctx, &desc);\n            break;\n        }\n        obj = JS_GetPrototypeFree(ctx, obj);\n        if (JS_IsException(obj))\n            goto exception;\n        if (JS_IsNull(obj)) {\n            res = JS_UNDEFINED;\n            break;\n        }\n        /* avoid infinite loop (possible with proxies) */\n        if (js_poll_interrupts(ctx))\n            goto exception;\n    }\n\nexception:\n    JS_FreeAtom(ctx, prop);\n    JS_FreeValue(ctx, obj);\n    return res;\n}\n\nstatic const JSCFunctionListEntry js_object_funcs[] = {\n    JS_CFUNC_DEF(\"create\", 2, js_object_create ),\n    JS_CFUNC_MAGIC_DEF(\"getPrototypeOf\", 1, js_object_getPrototypeOf, 0 ),\n    JS_CFUNC_DEF(\"setPrototypeOf\", 2, js_object_setPrototypeOf ),\n    JS_CFUNC_MAGIC_DEF(\"defineProperty\", 3, js_object_defineProperty, 0 ),\n    JS_CFUNC_DEF(\"defineProperties\", 2, js_object_defineProperties ),\n    JS_CFUNC_DEF(\"getOwnPropertyNames\", 1, js_object_getOwnPropertyNames ),\n    JS_CFUNC_DEF(\"getOwnPropertySymbols\", 1, js_object_getOwnPropertySymbols ),\n    JS_CFUNC_MAGIC_DEF(\"keys\", 1, js_object_keys, JS_ITERATOR_KIND_KEY ),\n    JS_CFUNC_MAGIC_DEF(\"values\", 1, js_object_keys, JS_ITERATOR_KIND_VALUE ),\n    JS_CFUNC_MAGIC_DEF(\"entries\", 1, js_object_keys, JS_ITERATOR_KIND_KEY_AND_VALUE ),\n    JS_CFUNC_MAGIC_DEF(\"isExtensible\", 1, js_object_isExtensible, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"preventExtensions\", 1, js_object_preventExtensions, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"getOwnPropertyDescriptor\", 2, js_object_getOwnPropertyDescriptor, 0 ),\n    JS_CFUNC_DEF(\"getOwnPropertyDescriptors\", 1, js_object_getOwnPropertyDescriptors ),\n    JS_CFUNC_DEF(\"is\", 2, js_object_is ),\n    JS_CFUNC_DEF(\"assign\", 2, js_object_assign ),\n    JS_CFUNC_MAGIC_DEF(\"seal\", 1, js_object_seal, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"freeze\", 1, js_object_seal, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"isSealed\", 1, js_object_isSealed, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"isFrozen\", 1, js_object_isSealed, 1 ),\n    JS_CFUNC_DEF(\"__getClass\", 1, js_object___getClass ),\n    //JS_CFUNC_DEF(\"__isObject\", 1, js_object___isObject ),\n    //JS_CFUNC_DEF(\"__isConstructor\", 1, js_object___isConstructor ),\n    //JS_CFUNC_DEF(\"__toObject\", 1, js_object___toObject ),\n    //JS_CFUNC_DEF(\"__setOwnProperty\", 3, js_object___setOwnProperty ),\n    //JS_CFUNC_DEF(\"__toPrimitive\", 2, js_object___toPrimitive ),\n    //JS_CFUNC_DEF(\"__toPropertyKey\", 1, js_object___toPropertyKey ),\n    //JS_CFUNC_DEF(\"__speciesConstructor\", 2, js_object___speciesConstructor ),\n    //JS_CFUNC_DEF(\"__isSameValueZero\", 2, js_object___isSameValueZero ),\n    //JS_CFUNC_DEF(\"__getObjectData\", 1, js_object___getObjectData ),\n    //JS_CFUNC_DEF(\"__setObjectData\", 2, js_object___setObjectData ),\n    JS_CFUNC_DEF(\"fromEntries\", 1, js_object_fromEntries ),\n};\n\nstatic const JSCFunctionListEntry js_object_proto_funcs[] = {\n    JS_CFUNC_DEF(\"toString\", 0, js_object_toString ),\n    JS_CFUNC_DEF(\"toLocaleString\", 0, js_object_toLocaleString ),\n    JS_CFUNC_DEF(\"valueOf\", 0, js_object_valueOf ),\n    JS_CFUNC_DEF(\"hasOwnProperty\", 1, js_object_hasOwnProperty ),\n    JS_CFUNC_DEF(\"isPrototypeOf\", 1, js_object_isPrototypeOf ),\n    JS_CFUNC_DEF(\"propertyIsEnumerable\", 1, js_object_propertyIsEnumerable ),\n    JS_CGETSET_DEF(\"__proto__\", js_object_get___proto__, js_object_set___proto__ ),\n    JS_CFUNC_MAGIC_DEF(\"__defineGetter__\", 2, js_object___defineGetter__, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"__defineSetter__\", 2, js_object___defineGetter__, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"__lookupGetter__\", 1, js_object___lookupGetter__, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"__lookupSetter__\", 1, js_object___lookupGetter__, 1 ),\n};\n\n/* Function class */\n\nstatic JSValue js_function_proto(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    return JS_UNDEFINED;\n}\n\n/* XXX: add a specific eval mode so that Function(\"}), ({\") is rejected */\nstatic JSValue js_function_constructor(JSContext *ctx, JSValueConst new_target,\n                                       int argc, JSValueConst *argv, int magic)\n{\n    JSFunctionKindEnum func_kind = magic;\n    int i, n, ret;\n    JSValue s, proto, obj = JS_UNDEFINED;\n    StringBuffer b_s, *b = &b_s;\n\n    string_buffer_init(ctx, b, 0);\n    string_buffer_putc8(b, '(');\n    \n    if (func_kind == JS_FUNC_ASYNC || func_kind == JS_FUNC_ASYNC_GENERATOR) {\n        string_buffer_puts8(b, \"async \");\n    }\n    string_buffer_puts8(b, \"function\");\n\n    if (func_kind == JS_FUNC_GENERATOR || func_kind == JS_FUNC_ASYNC_GENERATOR) {\n        string_buffer_putc8(b, '*');\n    }\n    string_buffer_puts8(b, \" anonymous(\");\n\n    n = argc - 1;\n    for(i = 0; i < n; i++) {\n        if (i != 0) {\n            string_buffer_putc8(b, ',');\n        }\n        if (string_buffer_concat_value(b, argv[i]))\n            goto fail;\n    }\n    string_buffer_puts8(b, \"\\n) {\\n\");\n    if (n >= 0) {\n        if (string_buffer_concat_value(b, argv[n]))\n            goto fail;\n    }\n    string_buffer_puts8(b, \"\\n})\");\n    s = string_buffer_end(b);\n    if (JS_IsException(s))\n        goto fail1;\n\n    obj = JS_EvalObject(ctx, ctx->global_obj, s, JS_EVAL_TYPE_INDIRECT, -1);\n    JS_FreeValue(ctx, s);\n    if (JS_IsException(obj))\n        goto fail1;\n    if (!JS_IsUndefined(new_target)) {\n        /* set the prototype */\n        proto = JS_GetProperty(ctx, new_target, JS_ATOM_prototype);\n        if (JS_IsException(proto))\n            goto fail1;\n        if (!JS_IsObject(proto)) {\n            JSContext *realm;\n            JS_FreeValue(ctx, proto);\n            realm = JS_GetFunctionRealm(ctx, new_target);\n            if (!realm)\n                goto fail1;\n            proto = JS_DupValue(ctx, realm->class_proto[func_kind_to_class_id[func_kind]]);\n        }\n        ret = JS_SetPrototypeInternal(ctx, obj, proto, TRUE);\n        JS_FreeValue(ctx, proto);\n        if (ret < 0)\n            goto fail1;\n    }\n    return obj;\n\n fail:\n    string_buffer_free(b);\n fail1:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic __exception int js_get_length32(JSContext *ctx, uint32_t *pres,\n                                       JSValueConst obj)\n{\n    JSValue len_val;\n    len_val = JS_GetProperty(ctx, obj, JS_ATOM_length);\n    if (JS_IsException(len_val)) {\n        *pres = 0;\n        return -1;\n    }\n    return JS_ToUint32Free(ctx, pres, len_val);\n}\n\nstatic __exception int js_get_length64(JSContext *ctx, int64_t *pres,\n                                       JSValueConst obj)\n{\n    JSValue len_val;\n    len_val = JS_GetProperty(ctx, obj, JS_ATOM_length);\n    if (JS_IsException(len_val)) {\n        *pres = 0;\n        return -1;\n    }\n    return JS_ToLengthFree(ctx, pres, len_val);\n}\n\nstatic void free_arg_list(JSContext *ctx, JSValue *tab, uint32_t len)\n{\n    uint32_t i;\n    for(i = 0; i < len; i++) {\n        JS_FreeValue(ctx, tab[i]);\n    }\n    js_free(ctx, tab);\n}\n\n/* XXX: should use ValueArray */\nstatic JSValue *build_arg_list(JSContext *ctx, uint32_t *plen,\n                               JSValueConst array_arg)\n{\n    uint32_t len, i;\n    JSValue *tab, ret;\n    JSObject *p;\n\n    if (JS_VALUE_GET_TAG(array_arg) != JS_TAG_OBJECT) {\n        JS_ThrowTypeError(ctx, \"not a object\");\n        return NULL;\n    }\n    if (js_get_length32(ctx, &len, array_arg))\n        return NULL;\n    if (len > JS_MAX_LOCAL_VARS) {\n        JS_ThrowInternalError(ctx, \"too many arguments\");\n        return NULL;\n    }\n    /* avoid allocating 0 bytes */\n    tab = js_mallocz(ctx, sizeof(tab[0]) * max_uint32(1, len));\n    if (!tab)\n        return NULL;\n    p = JS_VALUE_GET_OBJ(array_arg);\n    if ((p->class_id == JS_CLASS_ARRAY || p->class_id == JS_CLASS_ARGUMENTS) &&\n        p->fast_array &&\n        len == p->u.array.count) {\n        for(i = 0; i < len; i++) {\n            tab[i] = JS_DupValue(ctx, p->u.array.u.values[i]);\n        }\n    } else {\n        for(i = 0; i < len; i++) {\n            ret = JS_GetPropertyUint32(ctx, array_arg, i);\n            if (JS_IsException(ret)) {\n                free_arg_list(ctx, tab, i);\n                return NULL;\n            }\n            tab[i] = ret;\n        }\n    }\n    *plen = len;\n    return tab;\n}\n\n/* magic value: 0 = normal apply, 1 = apply for constructor, 2 =\n   Reflect.apply */\nstatic JSValue js_function_apply(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv, int magic)\n{\n    JSValueConst this_arg, array_arg;\n    uint32_t len;\n    JSValue *tab, ret;\n\n    if (check_function(ctx, this_val))\n        return JS_EXCEPTION;\n    this_arg = argv[0];\n    array_arg = argv[1];\n    if ((JS_VALUE_GET_TAG(array_arg) == JS_TAG_UNDEFINED ||\n         JS_VALUE_GET_TAG(array_arg) == JS_TAG_NULL) && magic != 2) {\n        return JS_Call(ctx, this_val, this_arg, 0, NULL);\n    }\n    tab = build_arg_list(ctx, &len, array_arg);\n    if (!tab)\n        return JS_EXCEPTION;\n    if (magic & 1) {\n        ret = JS_CallConstructor2(ctx, this_val, this_arg, len, (JSValueConst *)tab);\n    } else {\n        ret = JS_Call(ctx, this_val, this_arg, len, (JSValueConst *)tab);\n    }\n    free_arg_list(ctx, tab, len);\n    return ret;\n}\n\nstatic JSValue js_function_call(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    if (argc <= 0) {\n        return JS_Call(ctx, this_val, JS_UNDEFINED, 0, NULL);\n    } else {\n        return JS_Call(ctx, this_val, argv[0], argc - 1, argv + 1);\n    }\n}\n\nstatic JSValue js_function_bind(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSBoundFunction *bf;\n    JSValue func_obj, name1, len_val;\n    JSObject *p;\n    int arg_count, i, ret;\n\n    if (check_function(ctx, this_val))\n        return JS_EXCEPTION;\n\n    func_obj = JS_NewObjectProtoClass(ctx, ctx->function_proto,\n                                 JS_CLASS_BOUND_FUNCTION);\n    if (JS_IsException(func_obj))\n        return JS_EXCEPTION;\n    p = JS_VALUE_GET_OBJ(func_obj);\n    p->is_constructor = JS_IsConstructor(ctx, this_val);\n    arg_count = max_int(0, argc - 1);\n    bf = js_malloc(ctx, sizeof(*bf) + arg_count * sizeof(JSValue));\n    if (!bf)\n        goto exception;\n    bf->func_obj = JS_DupValue(ctx, this_val);\n    bf->this_val = JS_DupValue(ctx, argv[0]);\n    bf->argc = arg_count;\n    for(i = 0; i < arg_count; i++) {\n        bf->argv[i] = JS_DupValue(ctx, argv[i + 1]);\n    }\n    p->u.bound_function = bf;\n\n    /* XXX: the spec could be simpler by only using GetOwnProperty */\n    ret = JS_GetOwnProperty(ctx, NULL, this_val, JS_ATOM_length);\n    if (ret < 0)\n        goto exception;\n    if (!ret) {\n        len_val = JS_NewInt32(ctx, 0);\n    } else {\n        len_val = JS_GetProperty(ctx, this_val, JS_ATOM_length);\n        if (JS_IsException(len_val))\n            goto exception;\n        if (JS_VALUE_GET_TAG(len_val) == JS_TAG_INT) {\n            /* most common case */\n            int len1 = JS_VALUE_GET_INT(len_val);\n            if (len1 <= arg_count)\n                len1 = 0;\n            else\n                len1 -= arg_count;\n            len_val = JS_NewInt32(ctx, len1);\n        } else if (JS_VALUE_GET_NORM_TAG(len_val) == JS_TAG_FLOAT64) {\n            double d = JS_VALUE_GET_FLOAT64(len_val);\n            if (isnan(d)) {\n                d = 0.0;\n            } else {\n                d = trunc(d);\n                if (d <= (double)arg_count)\n                    d = 0.0;\n                else\n                    d -= (double)arg_count; /* also converts -0 to +0 */\n            }\n            len_val = JS_NewFloat64(ctx, d);\n        } else {\n            JS_FreeValue(ctx, len_val);\n            len_val = JS_NewInt32(ctx, 0);\n        }\n    }\n    JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_length,\n                           len_val, JS_PROP_CONFIGURABLE);\n\n    name1 = JS_GetProperty(ctx, this_val, JS_ATOM_name);\n    if (JS_IsException(name1))\n        goto exception;\n    if (!JS_IsString(name1)) {\n        JS_FreeValue(ctx, name1);\n        name1 = JS_AtomToString(ctx, JS_ATOM_empty_string);\n    }\n    name1 = JS_ConcatString3(ctx, \"bound \", name1, \"\");\n    if (JS_IsException(name1))\n        goto exception;\n    JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_name, name1,\n                           JS_PROP_CONFIGURABLE);\n    return func_obj;\n exception:\n    JS_FreeValue(ctx, func_obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_function_toString(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSObject *p;\n    JSFunctionKindEnum func_kind = JS_FUNC_NORMAL;\n\n    if (check_function(ctx, this_val))\n        return JS_EXCEPTION;\n\n    p = JS_VALUE_GET_OBJ(this_val);\n    if (js_class_has_bytecode(p->class_id)) {\n        JSFunctionBytecode *b = p->u.func.function_bytecode;\n        if (b->has_debug && b->debug.source) {\n            return JS_NewStringLen(ctx, b->debug.source, b->debug.source_len);\n        }\n        func_kind = b->func_kind;\n    }\n    {\n        JSValue name;\n        const char *pref, *suff;\n\n        switch(func_kind) {\n        default:\n        case JS_FUNC_NORMAL:\n            pref = \"function \";\n            break;\n        case JS_FUNC_GENERATOR:\n            pref = \"function *\";\n            break;\n        case JS_FUNC_ASYNC:\n            pref = \"async function \";\n            break;\n        case JS_FUNC_ASYNC_GENERATOR:\n            pref = \"async function *\";\n            break;\n        }\n        suff = \"() {\\n    [native code]\\n}\";\n        name = JS_GetProperty(ctx, this_val, JS_ATOM_name);\n        if (JS_IsUndefined(name))\n            name = JS_AtomToString(ctx, JS_ATOM_empty_string);\n        return JS_ConcatString3(ctx, pref, name, suff);\n    }\n}\n\nstatic JSValue js_function_hasInstance(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    int ret;\n    ret = JS_OrdinaryIsInstanceOf(ctx, argv[0], this_val);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic const JSCFunctionListEntry js_function_proto_funcs[] = {\n    JS_CFUNC_DEF(\"call\", 1, js_function_call ),\n    JS_CFUNC_MAGIC_DEF(\"apply\", 2, js_function_apply, 0 ),\n    JS_CFUNC_DEF(\"bind\", 1, js_function_bind ),\n    JS_CFUNC_DEF(\"toString\", 0, js_function_toString ),\n    JS_CFUNC_DEF(\"[Symbol.hasInstance]\", 1, js_function_hasInstance ),\n    JS_CGETSET_DEF(\"fileName\", js_function_proto_fileName, NULL ),\n    JS_CGETSET_DEF(\"lineNumber\", js_function_proto_lineNumber, NULL ),\n};\n\n/* Error class */\n\nstatic JSValue iterator_to_array(JSContext *ctx, JSValueConst items)\n{\n    JSValue iter, next_method = JS_UNDEFINED;\n    JSValue v, r = JS_UNDEFINED;\n    int64_t k;\n    BOOL done;\n    \n    iter = JS_GetIterator(ctx, items, FALSE);\n    if (JS_IsException(iter))\n        goto exception;\n    next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);\n    if (JS_IsException(next_method))\n        goto exception;\n    r = JS_NewArray(ctx);\n    if (JS_IsException(r))\n        goto exception;\n    for (k = 0;; k++) {\n        v = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);\n        if (JS_IsException(v))\n            goto exception_close;\n        if (done)\n            break;\n        if (JS_DefinePropertyValueInt64(ctx, r, k, v,\n                                        JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n            goto exception_close;\n    }\n done:\n    JS_FreeValue(ctx, next_method);\n    JS_FreeValue(ctx, iter);\n    return r;\n exception_close:\n    JS_IteratorClose(ctx, iter, TRUE);\n exception:\n    JS_FreeValue(ctx, r);\n    r = JS_EXCEPTION;\n    goto done;\n}\n\nstatic JSValue js_error_constructor(JSContext *ctx, JSValueConst new_target,\n                                    int argc, JSValueConst *argv, int magic)\n{\n    JSValue obj, msg, proto;\n    JSValueConst message;\n\n    if (JS_IsUndefined(new_target))\n        new_target = JS_GetActiveFunction(ctx);\n    proto = JS_GetProperty(ctx, new_target, JS_ATOM_prototype);\n    if (JS_IsException(proto))\n        return proto;\n    if (!JS_IsObject(proto)) {\n        JSContext *realm;\n        JSValueConst proto1;\n        \n        JS_FreeValue(ctx, proto);\n        realm = JS_GetFunctionRealm(ctx, new_target);\n        if (!realm)\n            return JS_EXCEPTION;\n        if (magic < 0) {\n            proto1 = realm->class_proto[JS_CLASS_ERROR];\n        } else {\n            proto1 = realm->native_error_proto[magic];\n        }\n        proto = JS_DupValue(ctx, proto1);\n    }\n    obj = JS_NewObjectProtoClass(ctx, proto, JS_CLASS_ERROR);\n    JS_FreeValue(ctx, proto);\n    if (JS_IsException(obj))\n        return obj;\n    if (magic == JS_AGGREGATE_ERROR) {\n        message = argv[1];\n    } else {\n        message = argv[0];\n    }\n\n    if (!JS_IsUndefined(message)) {\n        msg = JS_ToString(ctx, message);\n        if (unlikely(JS_IsException(msg)))\n            goto exception;\n        JS_DefinePropertyValue(ctx, obj, JS_ATOM_message, msg,\n                               JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    }\n\n    if (magic == JS_AGGREGATE_ERROR) {\n        JSValue error_list = iterator_to_array(ctx, argv[0]);\n        if (JS_IsException(error_list))\n            goto exception;\n        JS_DefinePropertyValue(ctx, obj, JS_ATOM_errors, error_list,\n                               JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    }\n\n    /* skip the Error() function in the backtrace */\n    build_backtrace(ctx, obj, NULL, 0, JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL);\n    return obj;\n exception:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_error_toString(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValue name, msg;\n\n    if (!JS_IsObject(this_val))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    name = JS_GetProperty(ctx, this_val, JS_ATOM_name);\n    if (JS_IsUndefined(name))\n        name = JS_AtomToString(ctx, JS_ATOM_Error);\n    else\n        name = JS_ToStringFree(ctx, name);\n    if (JS_IsException(name))\n        return JS_EXCEPTION;\n\n    msg = JS_GetProperty(ctx, this_val, JS_ATOM_message);\n    if (JS_IsUndefined(msg))\n        msg = JS_AtomToString(ctx, JS_ATOM_empty_string);\n    else\n        msg = JS_ToStringFree(ctx, msg);\n    if (JS_IsException(msg)) {\n        JS_FreeValue(ctx, name);\n        return JS_EXCEPTION;\n    }\n    if (!JS_IsEmptyString(name) && !JS_IsEmptyString(msg))\n        name = JS_ConcatString3(ctx, \"\", name, \": \");\n    return JS_ConcatString(ctx, name, msg);\n}\n\nstatic const JSCFunctionListEntry js_error_proto_funcs[] = {\n    JS_CFUNC_DEF(\"toString\", 0, js_error_toString ),\n    JS_PROP_STRING_DEF(\"name\", \"Error\", JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),\n    JS_PROP_STRING_DEF(\"message\", \"\", JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),\n};\n\n/* AggregateError */\n\n/* used by C code. */\nstatic JSValue js_aggregate_error_constructor(JSContext *ctx,\n                                              JSValueConst errors)\n{\n    JSValue obj;\n    \n    obj = JS_NewObjectProtoClass(ctx,\n                                 ctx->native_error_proto[JS_AGGREGATE_ERROR],\n                                 JS_CLASS_ERROR);\n    if (JS_IsException(obj))\n        return obj;\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_errors, JS_DupValue(ctx, errors),\n                           JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    return obj;\n}\n\n/* Array */\n\nstatic int JS_CopySubArray(JSContext *ctx,\n                           JSValueConst obj, int64_t to_pos,\n                           int64_t from_pos, int64_t count, int dir)\n{\n    int64_t i, from, to;\n    JSValue val;\n    int fromPresent;\n\n    /* XXX: should special case fast arrays */\n    for (i = 0; i < count; i++) {\n        if (dir < 0) {\n            from = from_pos + count - i - 1;\n            to = to_pos + count - i - 1;\n        } else {\n            from = from_pos + i;\n            to = to_pos + i;\n        }\n        fromPresent = JS_TryGetPropertyInt64(ctx, obj, from, &val);\n        if (fromPresent < 0)\n            goto exception;\n\n        if (fromPresent) {\n            if (JS_SetPropertyInt64(ctx, obj, to, val) < 0)\n                goto exception;\n        } else {\n            if (JS_DeletePropertyInt64(ctx, obj, to, JS_PROP_THROW) < 0)\n                goto exception;\n        }\n    }\n    return 0;\n\n exception:\n    return -1;\n}\n\nstatic JSValue js_array_constructor(JSContext *ctx, JSValueConst new_target,\n                                    int argc, JSValueConst *argv)\n{\n    JSValue obj;\n    int i;\n\n    obj = js_create_from_ctor(ctx, new_target, JS_CLASS_ARRAY);\n    if (JS_IsException(obj))\n        return obj;\n    if (argc == 1 && JS_IsNumber(argv[0])) {\n        uint32_t len;\n        if (JS_ToArrayLengthFree(ctx, &len, JS_DupValue(ctx, argv[0]), TRUE))\n            goto fail;\n        if (JS_SetProperty(ctx, obj, JS_ATOM_length, JS_NewUint32(ctx, len)) < 0)\n            goto fail;\n    } else {\n        for(i = 0; i < argc; i++) {\n            if (JS_SetPropertyUint32(ctx, obj, i, JS_DupValue(ctx, argv[i])) < 0)\n                goto fail;\n        }\n    }\n    return obj;\nfail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_from(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    // from(items, mapfn = void 0, this_arg = void 0)\n    JSValueConst items = argv[0], mapfn, this_arg;\n    JSValueConst args[2];\n    JSValue stack[2];\n    JSValue iter, r, v, v2, arrayLike;\n    int64_t k, len;\n    int done, mapping;\n\n    mapping = FALSE;\n    mapfn = JS_UNDEFINED;\n    this_arg = JS_UNDEFINED;\n    r = JS_UNDEFINED;\n    arrayLike = JS_UNDEFINED;\n    stack[0] = JS_UNDEFINED;\n    stack[1] = JS_UNDEFINED;\n\n    if (argc > 1) {\n        mapfn = argv[1];\n        if (!JS_IsUndefined(mapfn)) {\n            if (check_function(ctx, mapfn))\n                goto exception;\n            mapping = 1;\n            if (argc > 2)\n                this_arg = argv[2];\n        }\n    }\n    iter = JS_GetProperty(ctx, items, JS_ATOM_Symbol_iterator);\n    if (JS_IsException(iter))\n        goto exception;\n    if (!JS_IsUndefined(iter)) {\n        JS_FreeValue(ctx, iter);\n        if (JS_IsConstructor(ctx, this_val))\n            r = JS_CallConstructor(ctx, this_val, 0, NULL);\n        else\n            r = JS_NewArray(ctx);\n        if (JS_IsException(r))\n            goto exception;\n        stack[0] = JS_DupValue(ctx, items);\n        if (js_for_of_start(ctx, &stack[1], FALSE))\n            goto exception;\n        for (k = 0;; k++) {\n            v = JS_IteratorNext(ctx, stack[0], stack[1], 0, NULL, &done);\n            if (JS_IsException(v))\n                goto exception_close;\n            if (done)\n                break;\n            if (mapping) {\n                args[0] = v;\n                args[1] = JS_NewInt32(ctx, k);\n                v2 = JS_Call(ctx, mapfn, this_arg, 2, args);\n                JS_FreeValue(ctx, v);\n                v = v2;\n                if (JS_IsException(v))\n                    goto exception_close;\n            }\n            if (JS_DefinePropertyValueInt64(ctx, r, k, v,\n                                            JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                goto exception_close;\n        }\n    } else {\n        arrayLike = JS_ToObject(ctx, items);\n        if (JS_IsException(arrayLike))\n            goto exception;\n        if (js_get_length64(ctx, &len, arrayLike) < 0)\n            goto exception;\n        v = JS_NewInt64(ctx, len);\n        args[0] = v;\n        if (JS_IsConstructor(ctx, this_val)) {\n            r = JS_CallConstructor(ctx, this_val, 1, args);\n        } else {\n            r = js_array_constructor(ctx, JS_UNDEFINED, 1, args);\n        }\n        JS_FreeValue(ctx, v);\n        if (JS_IsException(r))\n            goto exception;\n        for(k = 0; k < len; k++) {\n            v = JS_GetPropertyInt64(ctx, arrayLike, k);\n            if (JS_IsException(v))\n                goto exception;\n            if (mapping) {\n                args[0] = v;\n                args[1] = JS_NewInt32(ctx, k);\n                v2 = JS_Call(ctx, mapfn, this_arg, 2, args);\n                JS_FreeValue(ctx, v);\n                v = v2;\n                if (JS_IsException(v))\n                    goto exception;\n            }\n            if (JS_DefinePropertyValueInt64(ctx, r, k, v,\n                                            JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                goto exception;\n        }\n    }\n    if (JS_SetProperty(ctx, r, JS_ATOM_length, JS_NewUint32(ctx, k)) < 0)\n        goto exception;\n    goto done;\n\n exception_close:\n    if (!JS_IsUndefined(stack[0]))\n        JS_IteratorClose(ctx, stack[0], TRUE);\n exception:\n    JS_FreeValue(ctx, r);\n    r = JS_EXCEPTION;\n done:\n    JS_FreeValue(ctx, arrayLike);\n    JS_FreeValue(ctx, stack[0]);\n    JS_FreeValue(ctx, stack[1]);\n    return r;\n}\n\nstatic JSValue js_array_of(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    JSValue obj, args[1];\n    int i;\n\n    if (JS_IsConstructor(ctx, this_val)) {\n        args[0] = JS_NewInt32(ctx, argc);\n        obj = JS_CallConstructor(ctx, this_val, 1, (JSValueConst *)args);\n    } else {\n        obj = JS_NewArray(ctx);\n    }\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    for(i = 0; i < argc; i++) {\n        if (JS_CreateDataPropertyUint32(ctx, obj, i, JS_DupValue(ctx, argv[i]),\n                                        JS_PROP_THROW) < 0) {\n            goto fail;\n        }\n    }\n    if (JS_SetProperty(ctx, obj, JS_ATOM_length, JS_NewUint32(ctx, argc)) < 0) {\n    fail:\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    return obj;\n}\n\nstatic JSValue js_array_isArray(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    int ret;\n    ret = JS_IsArray(ctx, argv[0]);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_get_this(JSContext *ctx,\n                           JSValueConst this_val)\n{\n    return JS_DupValue(ctx, this_val);\n}\n\nstatic JSValue JS_ArraySpeciesCreate(JSContext *ctx, JSValueConst obj,\n                                     JSValueConst len_val)\n{\n    JSValue ctor, ret, species;\n    int res;\n    JSContext *realm;\n    \n    res = JS_IsArray(ctx, obj);\n    if (res < 0)\n        return JS_EXCEPTION;\n    if (!res)\n        return js_array_constructor(ctx, JS_UNDEFINED, 1, &len_val);\n    ctor = JS_GetProperty(ctx, obj, JS_ATOM_constructor);\n    if (JS_IsException(ctor))\n        return ctor;\n    if (JS_IsConstructor(ctx, ctor)) {\n        /* legacy web compatibility */\n        realm = JS_GetFunctionRealm(ctx, ctor);\n        if (!realm) {\n            JS_FreeValue(ctx, ctor);\n            return JS_EXCEPTION;\n        }\n        if (realm != ctx &&\n            js_same_value(ctx, ctor, realm->array_ctor)) {\n            JS_FreeValue(ctx, ctor);\n            ctor = JS_UNDEFINED;\n        }\n    }\n    if (JS_IsObject(ctor)) {\n        species = JS_GetProperty(ctx, ctor, JS_ATOM_Symbol_species);\n        JS_FreeValue(ctx, ctor);\n        if (JS_IsException(species))\n            return species;\n        ctor = species;\n        if (JS_IsNull(ctor))\n            ctor = JS_UNDEFINED;\n    }\n    if (JS_IsUndefined(ctor)) {\n        return js_array_constructor(ctx, JS_UNDEFINED, 1, &len_val);\n    } else {\n        ret = JS_CallConstructor(ctx, ctor, 1, &len_val);\n        JS_FreeValue(ctx, ctor);\n        return ret;\n    }\n}\n\nstatic const JSCFunctionListEntry js_array_funcs[] = {\n    JS_CFUNC_DEF(\"isArray\", 1, js_array_isArray ),\n    JS_CFUNC_DEF(\"from\", 1, js_array_from ),\n    JS_CFUNC_DEF(\"of\", 0, js_array_of ),\n    JS_CGETSET_DEF(\"[Symbol.species]\", js_get_this, NULL ),\n};\n\nstatic int JS_isConcatSpreadable(JSContext *ctx, JSValueConst obj)\n{\n    JSValue val;\n\n    if (!JS_IsObject(obj))\n        return FALSE;\n    val = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_isConcatSpreadable);\n    if (JS_IsException(val))\n        return -1;\n    if (!JS_IsUndefined(val))\n        return JS_ToBoolFree(ctx, val);\n    return JS_IsArray(ctx, obj);\n}\n\nstatic JSValue js_array_concat(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    JSValue obj, arr, val;\n    JSValueConst e;\n    int64_t len, k, n;\n    int i, res;\n\n    arr = JS_UNDEFINED;\n    obj = JS_ToObject(ctx, this_val);\n    if (JS_IsException(obj))\n        goto exception;\n\n    arr = JS_ArraySpeciesCreate(ctx, obj, JS_NewInt32(ctx, 0));\n    if (JS_IsException(arr))\n        goto exception;\n    n = 0;\n    for (i = -1; i < argc; i++) {\n        if (i < 0)\n            e = obj;\n        else\n            e = argv[i];\n\n        res = JS_isConcatSpreadable(ctx, e);\n        if (res < 0)\n            goto exception;\n        if (res) {\n            if (js_get_length64(ctx, &len, e))\n                goto exception;\n            if (n + len > MAX_SAFE_INTEGER) {\n                JS_ThrowTypeError(ctx, \"Array loo long\");\n                goto exception;\n            }\n            for (k = 0; k < len; k++, n++) {\n                res = JS_TryGetPropertyInt64(ctx, e, k, &val);\n                if (res < 0)\n                    goto exception;\n                if (res) {\n                    if (JS_DefinePropertyValueInt64(ctx, arr, n, val,\n                                                    JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                        goto exception;\n                }\n            }\n        } else {\n            if (n >= MAX_SAFE_INTEGER) {\n                JS_ThrowTypeError(ctx, \"Array loo long\");\n                goto exception;\n            }\n            if (JS_DefinePropertyValueInt64(ctx, arr, n, JS_DupValue(ctx, e),\n                                            JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                goto exception;\n            n++;\n        }\n    }\n    if (JS_SetProperty(ctx, arr, JS_ATOM_length, JS_NewInt64(ctx, n)) < 0)\n        goto exception;\n\n    JS_FreeValue(ctx, obj);\n    return arr;\n\nexception:\n    JS_FreeValue(ctx, arr);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\n#define special_every    0\n#define special_some     1\n#define special_forEach  2\n#define special_map      3\n#define special_filter   4\n#define special_TA       8\n\nstatic int js_typed_array_get_length_internal(JSContext *ctx, JSValueConst obj);\n\nstatic JSValue js_typed_array___speciesCreate(JSContext *ctx,\n                                              JSValueConst this_val,\n                                              int argc, JSValueConst *argv);\n\nstatic JSValue js_array_every(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int special)\n{\n    JSValue obj, val, index_val, res, ret;\n    JSValueConst args[3];\n    JSValueConst func, this_arg;\n    int64_t len, k, n;\n    int present;\n\n    ret = JS_UNDEFINED;\n    val = JS_UNDEFINED;\n    if (special & special_TA) {\n        obj = JS_DupValue(ctx, this_val);\n        len = js_typed_array_get_length_internal(ctx, obj);\n        if (len < 0)\n            goto exception;\n    } else {\n        obj = JS_ToObject(ctx, this_val);\n        if (js_get_length64(ctx, &len, obj))\n            goto exception;\n    }\n    func = argv[0];\n    this_arg = JS_UNDEFINED;\n    if (argc > 1)\n        this_arg = argv[1];\n        \n    if (check_function(ctx, func))\n        goto exception;\n\n    switch (special) {\n    case special_every:\n    case special_every | special_TA:\n        ret = JS_TRUE;\n        break;\n    case special_some:\n    case special_some | special_TA:\n        ret = JS_FALSE;\n        break;\n    case special_map:\n        /* XXX: JS_ArraySpeciesCreate should take int64_t */\n        ret = JS_ArraySpeciesCreate(ctx, obj, JS_NewInt64(ctx, len));\n        if (JS_IsException(ret))\n            goto exception;\n        break;\n    case special_filter:\n        ret = JS_ArraySpeciesCreate(ctx, obj, JS_NewInt32(ctx, 0));\n        if (JS_IsException(ret))\n            goto exception;\n        break;\n    case special_map | special_TA:\n        args[0] = obj;\n        args[1] = JS_NewInt32(ctx, len);\n        ret = js_typed_array___speciesCreate(ctx, JS_UNDEFINED, 2, args);\n        if (JS_IsException(ret))\n            goto exception;\n        break;\n    case special_filter | special_TA:\n        ret = JS_NewArray(ctx);\n        if (JS_IsException(ret))\n            goto exception;\n        break;\n    }\n    n = 0;\n\n    for(k = 0; k < len; k++) {\n        if (special & special_TA) {\n            val = JS_GetPropertyInt64(ctx, obj, k);\n            if (JS_IsException(val))\n                goto exception;\n            present = TRUE;\n        } else {\n            present = JS_TryGetPropertyInt64(ctx, obj, k, &val);\n            if (present < 0)\n                goto exception;\n        }\n        if (present) {\n            index_val = JS_NewInt64(ctx, k);\n            if (JS_IsException(index_val))\n                goto exception;\n            args[0] = val;\n            args[1] = index_val;\n            args[2] = obj;\n            res = JS_Call(ctx, func, this_arg, 3, args);\n            JS_FreeValue(ctx, index_val);\n            if (JS_IsException(res))\n                goto exception;\n            switch (special) {\n            case special_every:\n            case special_every | special_TA:\n                if (!JS_ToBoolFree(ctx, res)) {\n                    ret = JS_FALSE;\n                    goto done;\n                }\n                break;\n            case special_some:\n            case special_some | special_TA:\n                if (JS_ToBoolFree(ctx, res)) {\n                    ret = JS_TRUE;\n                    goto done;\n                }\n                break;\n            case special_map:\n                if (JS_DefinePropertyValueInt64(ctx, ret, k, res,\n                                                JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                    goto exception;\n                break;\n            case special_map | special_TA:\n                if (JS_SetPropertyValue(ctx, ret, JS_NewInt32(ctx, k), res, JS_PROP_THROW) < 0)\n                    goto exception;\n                break;\n            case special_filter:\n            case special_filter | special_TA:\n                if (JS_ToBoolFree(ctx, res)) {\n                    if (JS_DefinePropertyValueInt64(ctx, ret, n++, JS_DupValue(ctx, val),\n                                                    JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                        goto exception;\n                }\n                break;\n            default:\n                JS_FreeValue(ctx, res);\n                break;\n            }\n            JS_FreeValue(ctx, val);\n            val = JS_UNDEFINED;\n        }\n    }\ndone:\n    if (special == (special_filter | special_TA)) {\n        JSValue arr;\n        args[0] = obj;\n        args[1] = JS_NewInt32(ctx, n);\n        arr = js_typed_array___speciesCreate(ctx, JS_UNDEFINED, 2, args);\n        if (JS_IsException(arr))\n            goto exception;\n        args[0] = ret;\n        res = JS_Invoke(ctx, arr, JS_ATOM_set, 1, args);\n        if (check_exception_free(ctx, res))\n            goto exception;\n        JS_FreeValue(ctx, ret);\n        ret = arr;\n    }\n    JS_FreeValue(ctx, val);\n    JS_FreeValue(ctx, obj);\n    return ret;\n\nexception:\n    JS_FreeValue(ctx, ret);\n    JS_FreeValue(ctx, val);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\n#define special_reduce       0\n#define special_reduceRight  1\n\nstatic JSValue js_array_reduce(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv, int special)\n{\n    JSValue obj, val, index_val, acc, acc1;\n    JSValueConst args[4];\n    JSValueConst func;\n    int64_t len, k, k1;\n    int present;\n\n    acc = JS_UNDEFINED;\n    val = JS_UNDEFINED;\n    if (special & special_TA) {\n        obj = JS_DupValue(ctx, this_val);\n        len = js_typed_array_get_length_internal(ctx, obj);\n        if (len < 0)\n            goto exception;\n    } else {\n        obj = JS_ToObject(ctx, this_val);\n        if (js_get_length64(ctx, &len, obj))\n            goto exception;\n    }\n    func = argv[0];\n\n    if (check_function(ctx, func))\n        goto exception;\n\n    k = 0;\n    if (argc > 1) {\n        acc = JS_DupValue(ctx, argv[1]);\n    } else {\n        for(;;) {\n            if (k >= len) {\n                JS_ThrowTypeError(ctx, \"empty array\");\n                goto exception;\n            }\n            k1 = (special & special_reduceRight) ? len - k - 1 : k;\n            k++;\n            if (special & special_TA) {\n                acc = JS_GetPropertyInt64(ctx, obj, k1);\n                if (JS_IsException(acc))\n                    goto exception;\n                break;\n            } else {\n                present = JS_TryGetPropertyInt64(ctx, obj, k1, &acc);\n                if (present < 0)\n                    goto exception;\n                if (present)\n                    break;\n            }\n        }\n    }\n    for (; k < len; k++) {\n        k1 = (special & special_reduceRight) ? len - k - 1 : k;\n        if (special & special_TA) {\n            val = JS_GetPropertyInt64(ctx, obj, k1);\n            if (JS_IsException(val))\n                goto exception;\n            present = TRUE;\n        } else {\n            present = JS_TryGetPropertyInt64(ctx, obj, k1, &val);\n            if (present < 0)\n                goto exception;\n        }\n        if (present) {\n            index_val = JS_NewInt64(ctx, k1);\n            if (JS_IsException(index_val))\n                goto exception;\n            args[0] = acc;\n            args[1] = val;\n            args[2] = index_val;\n            args[3] = obj;\n            acc1 = JS_Call(ctx, func, JS_UNDEFINED, 4, args);\n            JS_FreeValue(ctx, index_val);\n            JS_FreeValue(ctx, val);\n            val = JS_UNDEFINED;\n            if (JS_IsException(acc1))\n                goto exception;\n            JS_FreeValue(ctx, acc);\n            acc = acc1;\n        }\n    }\n    JS_FreeValue(ctx, obj);\n    return acc;\n\nexception:\n    JS_FreeValue(ctx, acc);\n    JS_FreeValue(ctx, val);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_fill(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    JSValue obj;\n    int64_t len, start, end;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    start = 0;\n    if (argc > 1 && !JS_IsUndefined(argv[1])) {\n        if (JS_ToInt64Clamp(ctx, &start, argv[1], 0, len, len))\n            goto exception;\n    }\n\n    end = len;\n    if (argc > 2 && !JS_IsUndefined(argv[2])) {\n        if (JS_ToInt64Clamp(ctx, &end, argv[2], 0, len, len))\n            goto exception;\n    }\n\n    /* XXX: should special case fast arrays */\n    while (start < end) {\n        if (JS_SetPropertyInt64(ctx, obj, start,\n                                JS_DupValue(ctx, argv[0])) < 0)\n            goto exception;\n        start++;\n    }\n    return obj;\n\n exception:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_includes(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValue obj, val;\n    int64_t len, n, res;\n    JSValue *arrp;\n    uint32_t count;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    res = FALSE;\n    if (len > 0) {\n        n = 0;\n        if (argc > 1) {\n            if (JS_ToInt64Clamp(ctx, &n, argv[1], 0, len, len))\n                goto exception;\n        }\n        if (js_get_fast_array(ctx, obj, &arrp, &count)) {\n            for (; n < count; n++) {\n                if (js_strict_eq2(ctx, JS_DupValue(ctx, argv[0]),\n                                  JS_DupValue(ctx, arrp[n]),\n                                  JS_EQ_SAME_VALUE_ZERO)) {\n                    res = TRUE;\n                    goto done;\n                }\n            }\n        }\n        for (; n < len; n++) {\n            val = JS_GetPropertyInt64(ctx, obj, n);\n            if (JS_IsException(val))\n                goto exception;\n            if (js_strict_eq2(ctx, JS_DupValue(ctx, argv[0]), val,\n                              JS_EQ_SAME_VALUE_ZERO)) {\n                res = TRUE;\n                break;\n            }\n        }\n    }\n done:\n    JS_FreeValue(ctx, obj);\n    return JS_NewBool(ctx, res);\n\n exception:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_indexOf(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValue obj, val;\n    int64_t len, n, res;\n    JSValue *arrp;\n    uint32_t count;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    res = -1;\n    if (len > 0) {\n        n = 0;\n        if (argc > 1) {\n            if (JS_ToInt64Clamp(ctx, &n, argv[1], 0, len, len))\n                goto exception;\n        }\n        if (js_get_fast_array(ctx, obj, &arrp, &count)) {\n            for (; n < count; n++) {\n                if (js_strict_eq2(ctx, JS_DupValue(ctx, argv[0]),\n                                  JS_DupValue(ctx, arrp[n]), JS_EQ_STRICT)) {\n                    res = n;\n                    goto done;\n                }\n            }\n        }\n        for (; n < len; n++) {\n            int present = JS_TryGetPropertyInt64(ctx, obj, n, &val);\n            if (present < 0)\n                goto exception;\n            if (present) {\n                if (js_strict_eq2(ctx, JS_DupValue(ctx, argv[0]), val, JS_EQ_STRICT)) {\n                    res = n;\n                    break;\n                }\n            }\n        }\n    }\n done:\n    JS_FreeValue(ctx, obj);\n    return JS_NewInt64(ctx, res);\n\n exception:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_lastIndexOf(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSValue obj, val;\n    int64_t len, n, res;\n    int present;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    res = -1;\n    if (len > 0) {\n        n = len - 1;\n        if (argc > 1) {\n            if (JS_ToInt64Clamp(ctx, &n, argv[1], -1, len - 1, len))\n                goto exception;\n        }\n        /* XXX: should special case fast arrays */\n        for (; n >= 0; n--) {\n            present = JS_TryGetPropertyInt64(ctx, obj, n, &val);\n            if (present < 0)\n                goto exception;\n            if (present) {\n                if (js_strict_eq2(ctx, JS_DupValue(ctx, argv[0]), val, JS_EQ_STRICT)) {\n                    res = n;\n                    break;\n                }\n            }\n        }\n    }\n    JS_FreeValue(ctx, obj);\n    return JS_NewInt64(ctx, res);\n\n exception:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_find(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv, int findIndex)\n{\n    JSValueConst func, this_arg;\n    JSValueConst args[3];\n    JSValue obj, val, index_val, res;\n    int64_t len, k;\n\n    index_val = JS_UNDEFINED;\n    val = JS_UNDEFINED;\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    func = argv[0];\n    if (check_function(ctx, func))\n        goto exception;\n\n    this_arg = JS_UNDEFINED;\n    if (argc > 1)\n        this_arg = argv[1];\n\n    for(k = 0; k < len; k++) {\n        index_val = JS_NewInt64(ctx, k);\n        if (JS_IsException(index_val))\n            goto exception;\n        val = JS_GetPropertyValue(ctx, obj, index_val);\n        if (JS_IsException(val))\n            goto exception;\n        args[0] = val;\n        args[1] = index_val;\n        args[2] = this_val;\n        res = JS_Call(ctx, func, this_arg, 3, args);\n        if (JS_IsException(res))\n            goto exception;\n        if (JS_ToBoolFree(ctx, res)) {\n            if (findIndex) {\n                JS_FreeValue(ctx, val);\n                JS_FreeValue(ctx, obj);\n                return index_val;\n            } else {\n                JS_FreeValue(ctx, index_val);\n                JS_FreeValue(ctx, obj);\n                return val;\n            }\n        }\n        JS_FreeValue(ctx, val);\n        JS_FreeValue(ctx, index_val);\n    }\n    JS_FreeValue(ctx, obj);\n    if (findIndex)\n        return JS_NewInt32(ctx, -1);\n    else\n        return JS_UNDEFINED;\n\nexception:\n    JS_FreeValue(ctx, index_val);\n    JS_FreeValue(ctx, val);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_toString(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValue obj, method, ret;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    method = JS_GetProperty(ctx, obj, JS_ATOM_join);\n    if (JS_IsException(method)) {\n        ret = JS_EXCEPTION;\n    } else\n    if (!JS_IsFunction(ctx, method)) {\n        /* Use intrinsic Object.prototype.toString */\n        JS_FreeValue(ctx, method);\n        ret = js_object_toString(ctx, obj, 0, NULL);\n    } else {\n        ret = JS_CallFree(ctx, method, obj, 0, NULL);\n    }\n    JS_FreeValue(ctx, obj);\n    return ret;\n}\n\nstatic JSValue js_array_join(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv, int toLocaleString)\n{\n    JSValue obj, sep = JS_UNDEFINED, el;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p = NULL;\n    int64_t i, n;\n    int c;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &n, obj))\n        goto exception;\n\n    c = ',';    /* default separator */\n    if (!toLocaleString && argc > 0 && !JS_IsUndefined(argv[0])) {\n        sep = JS_ToString(ctx, argv[0]);\n        if (JS_IsException(sep))\n            goto exception;\n        p = JS_VALUE_GET_STRING(sep);\n        if (p->len == 1 && !p->is_wide_char)\n            c = p->u.str8[0];\n        else\n            c = -1;\n    }\n    string_buffer_init(ctx, b, 0);\n\n    for(i = 0; i < n; i++) {\n        if (i > 0) {\n            if (c >= 0) {\n                string_buffer_putc8(b, c);\n            } else {\n                string_buffer_concat(b, p, 0, p->len);\n            }\n        }\n        el = JS_GetPropertyUint32(ctx, obj, i);\n        if (JS_IsException(el))\n            goto fail;\n        if (!JS_IsNull(el) && !JS_IsUndefined(el)) {\n            if (toLocaleString) {\n                el = JS_ToLocaleStringFree(ctx, el);\n            }\n            if (string_buffer_concat_value_free(b, el))\n                goto fail;\n        }\n    }\n    JS_FreeValue(ctx, sep);\n    JS_FreeValue(ctx, obj);\n    return string_buffer_end(b);\n\nfail:\n    string_buffer_free(b);\n    JS_FreeValue(ctx, sep);\nexception:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_pop(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv, int shift)\n{\n    JSValue obj, res = JS_UNDEFINED;\n    int64_t len, newLen;\n    JSValue *arrp;\n    uint32_t count32;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n    newLen = 0;\n    if (len > 0) {\n        newLen = len - 1;\n        /* Special case fast arrays */\n        if (js_get_fast_array(ctx, obj, &arrp, &count32) && count32 == len) {\n            JSObject *p = JS_VALUE_GET_OBJ(obj);\n            if (shift) {\n                res = arrp[0];\n                memmove(arrp, arrp + 1, (count32 - 1) * sizeof(*arrp));\n                p->u.array.count--;\n            } else {\n                res = arrp[count32 - 1];\n                p->u.array.count--;\n            }\n        } else {\n            if (shift) {\n                res = JS_GetPropertyInt64(ctx, obj, 0);\n                if (JS_IsException(res))\n                    goto exception;\n                if (JS_CopySubArray(ctx, obj, 0, 1, len - 1, +1))\n                    goto exception;\n            } else {\n                res = JS_GetPropertyInt64(ctx, obj, newLen);\n                if (JS_IsException(res))\n                    goto exception;\n            }\n            if (JS_DeletePropertyInt64(ctx, obj, newLen, JS_PROP_THROW) < 0)\n                goto exception;\n        }\n    }\n    if (JS_SetProperty(ctx, obj, JS_ATOM_length, JS_NewInt64(ctx, newLen)) < 0)\n        goto exception;\n\n    JS_FreeValue(ctx, obj);\n    return res;\n\n exception:\n    JS_FreeValue(ctx, res);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_push(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv, int unshift)\n{\n    JSValue obj;\n    int i;\n    int64_t len, from, newLen;\n\n    obj = JS_ToObject(ctx, this_val);\n\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(obj);\n        if (p->class_id != JS_CLASS_ARRAY ||\n            !p->fast_array || !p->extensible)\n            goto generic_case;\n        /* length must be writable */\n        if (unlikely(!(get_shape_prop(p->shape)->flags & JS_PROP_WRITABLE)))\n            goto generic_case;\n        /* check the length */\n        if (unlikely(JS_VALUE_GET_TAG(p->prop[0].u.value) != JS_TAG_INT))\n            goto generic_case;\n        len = JS_VALUE_GET_INT(p->prop[0].u.value);\n        /* we don't support holes */\n        if (unlikely(len != p->u.array.count))\n            goto generic_case;\n        newLen = len + argc;\n        if (unlikely(newLen > INT32_MAX))\n            goto generic_case;\n        if (newLen > p->u.array.u1.size) {\n            if (expand_fast_array(ctx, p, newLen))\n                goto exception;\n        }\n        if (unshift && argc > 0) {\n            memmove(p->u.array.u.values + argc, p->u.array.u.values,\n                    len * sizeof(p->u.array.u.values[0]));\n            from = 0;\n        } else {\n            from = len;\n        }\n        for(i = 0; i < argc; i++) {\n            p->u.array.u.values[from + i] = JS_DupValue(ctx, argv[i]);\n        }\n        p->u.array.count = newLen;\n        p->prop[0].u.value = JS_NewInt32(ctx, newLen);\n    } else {\n    generic_case:\n        if (js_get_length64(ctx, &len, obj))\n            goto exception;\n        newLen = len + argc;\n        if (newLen > MAX_SAFE_INTEGER) {\n            JS_ThrowTypeError(ctx, \"Array loo long\");\n            goto exception;\n        }\n        from = len;\n        if (unshift && argc > 0) {\n            if (JS_CopySubArray(ctx, obj, argc, 0, len, -1))\n                goto exception;\n            from = 0;\n        }\n        for(i = 0; i < argc; i++) {\n            if (JS_SetPropertyInt64(ctx, obj, from + i,\n                                    JS_DupValue(ctx, argv[i])) < 0)\n                goto exception;\n        }\n        if (JS_SetProperty(ctx, obj, JS_ATOM_length, JS_NewInt64(ctx, newLen)) < 0)\n            goto exception;\n    }\n    JS_FreeValue(ctx, obj);\n    return JS_NewInt64(ctx, newLen);\n\n exception:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_reverse(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValue obj, lval, hval;\n    JSValue *arrp;\n    int64_t len, l, h;\n    int l_present, h_present;\n    uint32_t count32;\n\n    lval = JS_UNDEFINED;\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    /* Special case fast arrays */\n    if (js_get_fast_array(ctx, obj, &arrp, &count32) && count32 == len) {\n        uint32_t ll, hh;\n\n        if (count32 > 1) {\n            for (ll = 0, hh = count32 - 1; ll < hh; ll++, hh--) {\n                lval = arrp[ll];\n                arrp[ll] = arrp[hh];\n                arrp[hh] = lval;\n            }\n        }\n        return obj;\n    }\n\n    for (l = 0, h = len - 1; l < h; l++, h--) {\n        l_present = JS_TryGetPropertyInt64(ctx, obj, l, &lval);\n        if (l_present < 0)\n            goto exception;\n        h_present = JS_TryGetPropertyInt64(ctx, obj, h, &hval);\n        if (h_present < 0)\n            goto exception;\n        if (h_present) {\n            if (JS_SetPropertyInt64(ctx, obj, l, hval) < 0)\n                goto exception;\n\n            if (l_present) {\n                if (JS_SetPropertyInt64(ctx, obj, h, lval) < 0) {\n                    lval = JS_UNDEFINED;\n                    goto exception;\n                }\n                lval = JS_UNDEFINED;\n            } else {\n                if (JS_DeletePropertyInt64(ctx, obj, h, JS_PROP_THROW) < 0)\n                    goto exception;\n            }\n        } else {\n            if (l_present) {\n                if (JS_DeletePropertyInt64(ctx, obj, l, JS_PROP_THROW) < 0)\n                    goto exception;\n                if (JS_SetPropertyInt64(ctx, obj, h, lval) < 0) {\n                    lval = JS_UNDEFINED;\n                    goto exception;\n                }\n                lval = JS_UNDEFINED;\n            }\n        }\n    }\n    return obj;\n\n exception:\n    JS_FreeValue(ctx, lval);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_slice(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int splice)\n{\n    JSValue obj, arr, val, len_val;\n    int64_t len, start, k, final, n, count, del_count, new_len;\n    int kPresent;\n    JSValue *arrp;\n    uint32_t count32, i, item_count;\n\n    arr = JS_UNDEFINED;\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    if (JS_ToInt64Clamp(ctx, &start, argv[0], 0, len, len))\n        goto exception;\n\n    if (splice) {\n        if (argc == 0) {\n            item_count = 0;\n            del_count = 0;\n        } else\n        if (argc == 1) {\n            item_count = 0;\n            del_count = len - start;\n        } else {\n            item_count = argc - 2;\n            if (JS_ToInt64Clamp(ctx, &del_count, argv[1], 0, len - start, 0))\n                goto exception;\n        }\n        if (len + item_count - del_count > MAX_SAFE_INTEGER) {\n            JS_ThrowTypeError(ctx, \"Array loo long\");\n            goto exception;\n        }\n        count = del_count;\n    } else {\n        item_count = 0; /* avoid warning */\n        final = len;\n        if (!JS_IsUndefined(argv[1])) {\n            if (JS_ToInt64Clamp(ctx, &final, argv[1], 0, len, len))\n                goto exception;\n        }\n        count = max_int64(final - start, 0);\n    }\n    len_val = JS_NewInt64(ctx, count);\n    arr = JS_ArraySpeciesCreate(ctx, obj, len_val);\n    JS_FreeValue(ctx, len_val);\n    if (JS_IsException(arr))\n        goto exception;\n\n    k = start;\n    final = start + count;\n    n = 0;\n    /* The fast array test on arr ensures that\n       JS_CreateDataPropertyUint32() won't modify obj in case arr is\n       an exotic object */\n    /* Special case fast arrays */\n    if (js_get_fast_array(ctx, obj, &arrp, &count32) &&\n        js_is_fast_array(ctx, arr)) {\n        /* XXX: should share code with fast array constructor */\n        for (; k < final && k < count32; k++, n++) {\n            if (JS_CreateDataPropertyUint32(ctx, arr, n, JS_DupValue(ctx, arrp[k]), JS_PROP_THROW) < 0)\n                goto exception;\n        }\n    }\n    /* Copy the remaining elements if any (handle case of inherited properties) */\n    for (; k < final; k++, n++) {\n        kPresent = JS_TryGetPropertyInt64(ctx, obj, k, &val);\n        if (kPresent < 0)\n            goto exception;\n        if (kPresent) {\n            if (JS_CreateDataPropertyUint32(ctx, arr, n, val, JS_PROP_THROW) < 0)\n                goto exception;\n        }\n    }\n    if (JS_SetProperty(ctx, arr, JS_ATOM_length, JS_NewInt64(ctx, n)) < 0)\n        goto exception;\n\n    if (splice) {\n        new_len = len + item_count - del_count;\n        if (item_count != del_count) {\n            if (JS_CopySubArray(ctx, obj, start + item_count,\n                                start + del_count, len - (start + del_count),\n                                item_count <= del_count ? +1 : -1) < 0)\n                goto exception;\n\n            for (k = len; k-- > new_len; ) {\n                if (JS_DeletePropertyInt64(ctx, obj, k, JS_PROP_THROW) < 0)\n                    goto exception;\n            }\n        }\n        for (i = 0; i < item_count; i++) {\n            if (JS_SetPropertyInt64(ctx, obj, start + i, JS_DupValue(ctx, argv[i + 2])) < 0)\n                goto exception;\n        }\n        if (JS_SetProperty(ctx, obj, JS_ATOM_length, JS_NewInt64(ctx, new_len)) < 0)\n            goto exception;\n    }\n    JS_FreeValue(ctx, obj);\n    return arr;\n\n exception:\n    JS_FreeValue(ctx, obj);\n    JS_FreeValue(ctx, arr);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_copyWithin(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    JSValue obj;\n    int64_t len, from, to, final, count;\n\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    if (JS_ToInt64Clamp(ctx, &to, argv[0], 0, len, len))\n        goto exception;\n\n    if (JS_ToInt64Clamp(ctx, &from, argv[1], 0, len, len))\n        goto exception;\n\n    final = len;\n    if (argc > 2 && !JS_IsUndefined(argv[2])) {\n        if (JS_ToInt64Clamp(ctx, &final, argv[2], 0, len, len))\n            goto exception;\n    }\n\n    count = min_int64(final - from, len - to);\n\n    if (JS_CopySubArray(ctx, obj, to, from, count,\n                        (from < to && to < from + count) ? -1 : +1))\n        goto exception;\n\n    return obj;\n\n exception:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic int64_t JS_FlattenIntoArray(JSContext *ctx, JSValueConst target,\n                                   JSValueConst source, int64_t sourceLen,\n                                   int64_t targetIndex, int depth,\n                                   JSValueConst mapperFunction,\n                                   JSValueConst thisArg)\n{\n    JSValue element;\n    int64_t sourceIndex, elementLen;\n    int present, is_array;\n\n    if (js_check_stack_overflow(ctx->rt, 0)) {\n        JS_ThrowStackOverflow(ctx);\n        return -1;\n    }\n\n    for (sourceIndex = 0; sourceIndex < sourceLen; sourceIndex++) {\n        present = JS_TryGetPropertyInt64(ctx, source, sourceIndex, &element);\n        if (present < 0)\n            return -1;\n        if (!present)\n            continue;\n        if (!JS_IsUndefined(mapperFunction)) {\n            JSValueConst args[3] = { element, JS_NewInt64(ctx, sourceIndex), source };\n            element = JS_Call(ctx, mapperFunction, thisArg, 3, args);\n            JS_FreeValue(ctx, args[0]);\n            JS_FreeValue(ctx, args[1]);\n            if (JS_IsException(element))\n                return -1;\n        }\n        if (depth > 0) {\n            is_array = JS_IsArray(ctx, element);\n            if (is_array < 0)\n                goto fail;\n            if (is_array) {\n                if (js_get_length64(ctx, &elementLen, element) < 0)\n                    goto fail;\n                targetIndex = JS_FlattenIntoArray(ctx, target, element,\n                                                  elementLen, targetIndex,\n                                                  depth - 1,\n                                                  JS_UNDEFINED, JS_UNDEFINED);\n                if (targetIndex < 0)\n                    goto fail;\n                JS_FreeValue(ctx, element);\n                continue;\n            }\n        }\n        if (targetIndex >= MAX_SAFE_INTEGER) {\n            JS_ThrowTypeError(ctx, \"Array too long\");\n            goto fail;\n        }\n        if (JS_DefinePropertyValueInt64(ctx, target, targetIndex, element,\n                                        JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n            return -1;\n        targetIndex++;\n    }\n    return targetIndex;\n\nfail:\n    JS_FreeValue(ctx, element);\n    return -1;\n}\n\nstatic JSValue js_array_flatten(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv, int map)\n{\n    JSValue obj, arr;\n    JSValueConst mapperFunction, thisArg;\n    int64_t sourceLen;\n    int depthNum;\n\n    arr = JS_UNDEFINED;\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &sourceLen, obj))\n        goto exception;\n\n    depthNum = 1;\n    mapperFunction = JS_UNDEFINED;\n    thisArg = JS_UNDEFINED;\n    if (map) {\n        mapperFunction = argv[0];\n        if (argc > 1) {\n            thisArg = argv[1];\n        }\n        if (check_function(ctx, mapperFunction))\n            goto exception;\n    } else {\n        if (argc > 0 && !JS_IsUndefined(argv[0])) {\n            if (JS_ToInt32Sat(ctx, &depthNum, argv[0]) < 0)\n                goto exception;\n        }\n    }\n    arr = JS_ArraySpeciesCreate(ctx, obj, JS_NewInt32(ctx, 0));\n    if (JS_IsException(arr))\n        goto exception;\n    if (JS_FlattenIntoArray(ctx, arr, obj, sourceLen, 0, depthNum,\n                            mapperFunction, thisArg) < 0)\n        goto exception;\n    JS_FreeValue(ctx, obj);\n    return arr;\n\nexception:\n    JS_FreeValue(ctx, obj);\n    JS_FreeValue(ctx, arr);\n    return JS_EXCEPTION;\n}\n\n/* Array sort */\n\ntypedef struct ValueSlot {\n    JSValue val;\n    JSString *str;\n    int64_t pos;\n} ValueSlot;\n\nstruct array_sort_context {\n    JSContext *ctx;\n    int exception;\n    int has_method;\n    JSValueConst method;\n};\n\nstatic int js_array_cmp_generic(const void *a, const void *b, void *opaque) {\n    struct array_sort_context *psc = opaque;\n    JSContext *ctx = psc->ctx;\n    JSValueConst argv[2];\n    JSValue res;\n    ValueSlot *ap = (ValueSlot *)(void *)a;\n    ValueSlot *bp = (ValueSlot *)(void *)b;\n    int cmp;\n\n    if (psc->exception)\n        return 0;\n\n    if (psc->has_method) {\n        /* custom sort function is specified as returning 0 for identical\n         * objects: avoid method call overhead.\n         */\n        if (!memcmp(&ap->val, &bp->val, sizeof(ap->val)))\n            goto cmp_same;\n        argv[0] = ap->val;\n        argv[1] = bp->val;\n        res = JS_Call(ctx, psc->method, JS_UNDEFINED, 2, argv);\n        if (JS_IsException(res))\n            goto exception;\n        if (JS_VALUE_GET_TAG(res) == JS_TAG_INT) {\n            int val = JS_VALUE_GET_INT(res);\n            cmp = (val > 0) - (val < 0);\n        } else {\n            double val;\n            if (JS_ToFloat64Free(ctx, &val, res) < 0)\n                goto exception;\n            cmp = (val > 0) - (val < 0);\n        }\n    } else {\n        /* Not supposed to bypass ToString even for identical objects as\n         * tested in test262/test/built-ins/Array/prototype/sort/bug_596_1.js\n         */\n        if (!ap->str) {\n            JSValue str = JS_ToString(ctx, ap->val);\n            if (JS_IsException(str))\n                goto exception;\n            ap->str = JS_VALUE_GET_STRING(str);\n        }\n        if (!bp->str) {\n            JSValue str = JS_ToString(ctx, bp->val);\n            if (JS_IsException(str))\n                goto exception;\n            bp->str = JS_VALUE_GET_STRING(str);\n        }\n        cmp = js_string_compare(ctx, ap->str, bp->str);\n    }\n    if (cmp != 0)\n        return cmp;\ncmp_same:\n    /* make sort stable: compare array offsets */\n    return (ap->pos > bp->pos) - (ap->pos < bp->pos);\n\nexception:\n    psc->exception = 1;\n    return 0;\n}\n\nstatic JSValue js_array_sort(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    struct array_sort_context asc = { ctx, 0, 0, argv[0] };\n    JSValue obj = JS_UNDEFINED;\n    ValueSlot *array = NULL;\n    size_t array_size = 0, pos = 0, n = 0;\n    int64_t i, len, undefined_count = 0;\n    int present;\n\n    if (!JS_IsUndefined(asc.method)) {\n        if (check_function(ctx, asc.method))\n            goto exception;\n        asc.has_method = 1;\n    }\n    obj = JS_ToObject(ctx, this_val);\n    if (js_get_length64(ctx, &len, obj))\n        goto exception;\n\n    /* XXX: should special case fast arrays */\n    for (i = 0; i < len; i++) {\n        if (pos >= array_size) {\n            size_t new_size, slack;\n            ValueSlot *new_array;\n            new_size = (array_size + (array_size >> 1) + 31) & ~15;\n            new_array = js_realloc2(ctx, array, new_size * sizeof(*array), &slack);\n            if (new_array == NULL)\n                goto exception;\n            new_size += slack / sizeof(*new_array);\n            array = new_array;\n            array_size = new_size;\n        }\n        present = JS_TryGetPropertyInt64(ctx, obj, i, &array[pos].val);\n        if (present < 0)\n            goto exception;\n        if (present == 0)\n            continue;\n        if (JS_IsUndefined(array[pos].val)) {\n            undefined_count++;\n            continue;\n        }\n        array[pos].str = NULL;\n        array[pos].pos = i;\n        pos++;\n    }\n    rqsort(array, pos, sizeof(*array), js_array_cmp_generic, &asc);\n    if (asc.exception)\n        goto exception;\n\n    /* XXX: should special case fast arrays */\n    while (n < pos) {\n        if (array[n].str)\n            JS_FreeValue(ctx, JS_MKPTR(JS_TAG_STRING, array[n].str));\n        if (array[n].pos == n) {\n            JS_FreeValue(ctx, array[n].val);\n        } else {\n            if (JS_SetPropertyInt64(ctx, obj, n, array[n].val) < 0) {\n                n++;\n                goto exception;\n            }\n        }\n        n++;\n    }\n    js_free(ctx, array);\n    for (i = n; undefined_count-- > 0; i++) {\n        if (JS_SetPropertyInt64(ctx, obj, i, JS_UNDEFINED) < 0)\n            goto fail;\n    }\n    for (; i < len; i++) {\n        if (JS_DeletePropertyInt64(ctx, obj, i, JS_PROP_THROW) < 0)\n            goto fail;\n    }\n    return obj;\n\nexception:\n    for (; n < pos; n++) {\n        JS_FreeValue(ctx, array[n].val);\n        if (array[n].str)\n            JS_FreeValue(ctx, JS_MKPTR(JS_TAG_STRING, array[n].str));\n    }\n    js_free(ctx, array);\nfail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\ntypedef struct JSArrayIteratorData {\n    JSValue obj;\n    JSIteratorKindEnum kind;\n    uint32_t idx;\n} JSArrayIteratorData;\n\nstatic void js_array_iterator_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSArrayIteratorData *it = p->u.array_iterator_data;\n    if (it) {\n        JS_FreeValueRT(rt, it->obj);\n        js_free_rt(rt, it);\n    }\n}\n\nstatic void js_array_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                   JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSArrayIteratorData *it = p->u.array_iterator_data;\n    if (it) {\n        JS_MarkValue(rt, it->obj, mark_func);\n    }\n}\n\nstatic JSValue js_create_array(JSContext *ctx, int len, JSValueConst *tab)\n{\n    JSValue obj;\n    int i;\n\n    obj = JS_NewArray(ctx);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    for(i = 0; i < len; i++) {\n        if (JS_CreateDataPropertyUint32(ctx, obj, i, JS_DupValue(ctx, tab[i]), 0) < 0) {\n            JS_FreeValue(ctx, obj);\n            return JS_EXCEPTION;\n        }\n    }\n    return obj;\n}\n\nstatic JSValue js_create_array_iterator(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv, int magic)\n{\n    JSValue enum_obj, arr;\n    JSArrayIteratorData *it;\n    JSIteratorKindEnum kind;\n    int class_id;\n\n    kind = magic & 3;\n    if (magic & 4) {\n        /* string iterator case */\n        arr = JS_ToStringCheckObject(ctx, this_val);\n        class_id = JS_CLASS_STRING_ITERATOR;\n    } else {\n        arr = JS_ToObject(ctx, this_val);\n        class_id = JS_CLASS_ARRAY_ITERATOR;\n    }\n    if (JS_IsException(arr))\n        goto fail;\n    enum_obj = JS_NewObjectClass(ctx, class_id);\n    if (JS_IsException(enum_obj))\n        goto fail;\n    it = js_malloc(ctx, sizeof(*it));\n    if (!it)\n        goto fail1;\n    it->obj = arr;\n    it->kind = kind;\n    it->idx = 0;\n    JS_SetOpaque(enum_obj, it);\n    return enum_obj;\n fail1:\n    JS_FreeValue(ctx, enum_obj);\n fail:\n    JS_FreeValue(ctx, arr);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_array_iterator_next(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv,\n                                      BOOL *pdone, int magic)\n{\n    JSArrayIteratorData *it;\n    uint32_t len, idx;\n    JSValue val, obj;\n    JSObject *p;\n\n    it = JS_GetOpaque2(ctx, this_val, JS_CLASS_ARRAY_ITERATOR);\n    if (!it)\n        goto fail1;\n    if (JS_IsUndefined(it->obj))\n        goto done;\n    p = JS_VALUE_GET_OBJ(it->obj);\n    if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n        p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n        if (typed_array_is_detached(ctx, p)) {\n            JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n            goto fail1;\n        }\n        len = p->u.array.count;\n    } else {\n        if (js_get_length32(ctx, &len, it->obj)) {\n        fail1:\n            *pdone = FALSE;\n            return JS_EXCEPTION;\n        }\n    }\n    idx = it->idx;\n    if (idx >= len) {\n        JS_FreeValue(ctx, it->obj);\n        it->obj = JS_UNDEFINED;\n    done:\n        *pdone = TRUE;\n        return JS_UNDEFINED;\n    }\n    it->idx = idx + 1;\n    *pdone = FALSE;\n    if (it->kind == JS_ITERATOR_KIND_KEY) {\n        return JS_NewUint32(ctx, idx);\n    } else {\n        val = JS_GetPropertyUint32(ctx, it->obj, idx);\n        if (JS_IsException(val))\n            return JS_EXCEPTION;\n        if (it->kind == JS_ITERATOR_KIND_VALUE) {\n            return val;\n        } else {\n            JSValueConst args[2];\n            JSValue num;\n            num = JS_NewUint32(ctx, idx);\n            args[0] = num;\n            args[1] = val;\n            obj = js_create_array(ctx, 2, args);\n            JS_FreeValue(ctx, val);\n            JS_FreeValue(ctx, num);\n            return obj;\n        }\n    }\n}\n\nstatic JSValue js_iterator_proto_iterator(JSContext *ctx, JSValueConst this_val,\n                                          int argc, JSValueConst *argv)\n{\n    return JS_DupValue(ctx, this_val);\n}\n\nstatic const JSCFunctionListEntry js_iterator_proto_funcs[] = {\n    JS_CFUNC_DEF(\"[Symbol.iterator]\", 0, js_iterator_proto_iterator ),\n};\n\nstatic const JSCFunctionListEntry js_array_proto_funcs[] = {\n    JS_CFUNC_DEF(\"concat\", 1, js_array_concat ),\n    JS_CFUNC_MAGIC_DEF(\"every\", 1, js_array_every, special_every ),\n    JS_CFUNC_MAGIC_DEF(\"some\", 1, js_array_every, special_some ),\n    JS_CFUNC_MAGIC_DEF(\"forEach\", 1, js_array_every, special_forEach ),\n    JS_CFUNC_MAGIC_DEF(\"map\", 1, js_array_every, special_map ),\n    JS_CFUNC_MAGIC_DEF(\"filter\", 1, js_array_every, special_filter ),\n    JS_CFUNC_MAGIC_DEF(\"reduce\", 1, js_array_reduce, special_reduce ),\n    JS_CFUNC_MAGIC_DEF(\"reduceRight\", 1, js_array_reduce, special_reduceRight ),\n    JS_CFUNC_DEF(\"fill\", 1, js_array_fill ),\n    JS_CFUNC_MAGIC_DEF(\"find\", 1, js_array_find, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"findIndex\", 1, js_array_find, 1 ),\n    JS_CFUNC_DEF(\"indexOf\", 1, js_array_indexOf ),\n    JS_CFUNC_DEF(\"lastIndexOf\", 1, js_array_lastIndexOf ),\n    JS_CFUNC_DEF(\"includes\", 1, js_array_includes ),\n    JS_CFUNC_MAGIC_DEF(\"join\", 1, js_array_join, 0 ),\n    JS_CFUNC_DEF(\"toString\", 0, js_array_toString ),\n    JS_CFUNC_MAGIC_DEF(\"toLocaleString\", 0, js_array_join, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"pop\", 0, js_array_pop, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"push\", 1, js_array_push, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"shift\", 0, js_array_pop, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"unshift\", 1, js_array_push, 1 ),\n    JS_CFUNC_DEF(\"reverse\", 0, js_array_reverse ),\n    JS_CFUNC_DEF(\"sort\", 1, js_array_sort ),\n    JS_CFUNC_MAGIC_DEF(\"slice\", 2, js_array_slice, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"splice\", 2, js_array_slice, 1 ),\n    JS_CFUNC_DEF(\"copyWithin\", 2, js_array_copyWithin ),\n    JS_CFUNC_MAGIC_DEF(\"flatMap\", 1, js_array_flatten, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"flat\", 0, js_array_flatten, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"values\", 0, js_create_array_iterator, JS_ITERATOR_KIND_VALUE ),\n    JS_ALIAS_DEF(\"[Symbol.iterator]\", \"values\" ),\n    JS_CFUNC_MAGIC_DEF(\"keys\", 0, js_create_array_iterator, JS_ITERATOR_KIND_KEY ),\n    JS_CFUNC_MAGIC_DEF(\"entries\", 0, js_create_array_iterator, JS_ITERATOR_KIND_KEY_AND_VALUE ),\n};\n\nstatic const JSCFunctionListEntry js_array_iterator_proto_funcs[] = {\n    JS_ITERATOR_NEXT_DEF(\"next\", 0, js_array_iterator_next, 0 ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Array Iterator\", JS_PROP_CONFIGURABLE ),\n};\n\n/* Number */\n\nstatic JSValue js_number_constructor(JSContext *ctx, JSValueConst new_target,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue val, obj;\n    if (argc == 0) {\n        val = JS_NewInt32(ctx, 0);\n    } else {\n        val = JS_ToNumeric(ctx, argv[0]);\n        if (JS_IsException(val))\n            return val;\n        switch(JS_VALUE_GET_TAG(val)) {\n#ifdef CONFIG_BIGNUM\n        case JS_TAG_BIG_INT:\n        case JS_TAG_BIG_FLOAT:\n            {\n                JSBigFloat *p = JS_VALUE_GET_PTR(val);\n                double d;\n                bf_get_float64(&p->num, &d, BF_RNDN);\n                JS_FreeValue(ctx, val);\n                val = __JS_NewFloat64(ctx, d);\n            }\n            break;\n        case JS_TAG_BIG_DECIMAL:\n            val = JS_ToStringFree(ctx, val);\n            if (JS_IsException(val))\n                return val;\n            val = JS_ToNumberFree(ctx, val);\n            if (JS_IsException(val))\n                return val;\n            break;\n#endif\n        default:\n            break;\n        }\n    }\n    if (!JS_IsUndefined(new_target)) {\n        obj = js_create_from_ctor(ctx, new_target, JS_CLASS_NUMBER);\n        if (!JS_IsException(obj))\n            JS_SetObjectData(ctx, obj, val);\n        return obj;\n    } else {\n        return val;\n    }\n}\n\n#if 0\nstatic JSValue js_number___toInteger(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    return JS_ToIntegerFree(ctx, JS_DupValue(ctx, argv[0]));\n}\n\nstatic JSValue js_number___toLength(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    int64_t v;\n    if (JS_ToLengthFree(ctx, &v, JS_DupValue(ctx, argv[0])))\n        return JS_EXCEPTION;\n    return JS_NewInt64(ctx, v);\n}\n#endif\n\nstatic JSValue js_number_isNaN(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    if (!JS_IsNumber(argv[0]))\n        return JS_FALSE;\n    return js_global_isNaN(ctx, this_val, argc, argv);\n}\n\nstatic JSValue js_number_isFinite(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    if (!JS_IsNumber(argv[0]))\n        return JS_FALSE;\n    return js_global_isFinite(ctx, this_val, argc, argv);\n}\n\nstatic JSValue js_number_isInteger(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    int ret;\n    ret = JS_NumberIsInteger(ctx, argv[0]);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_number_isSafeInteger(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    double d;\n    if (!JS_IsNumber(argv[0]))\n        return JS_FALSE;\n    if (unlikely(JS_ToFloat64(ctx, &d, argv[0])))\n        return JS_EXCEPTION;\n    return JS_NewBool(ctx, is_safe_integer(d));\n}\n\nstatic const JSCFunctionListEntry js_number_funcs[] = {\n    /* global ParseInt and parseFloat should be defined already or delayed */\n    JS_ALIAS_BASE_DEF(\"parseInt\", \"parseInt\", 0 ),\n    JS_ALIAS_BASE_DEF(\"parseFloat\", \"parseFloat\", 0 ),\n    JS_CFUNC_DEF(\"isNaN\", 1, js_number_isNaN ),\n    JS_CFUNC_DEF(\"isFinite\", 1, js_number_isFinite ),\n    JS_CFUNC_DEF(\"isInteger\", 1, js_number_isInteger ),\n    JS_CFUNC_DEF(\"isSafeInteger\", 1, js_number_isSafeInteger ),\n    JS_PROP_DOUBLE_DEF(\"MAX_VALUE\", 1.7976931348623157e+308, 0 ),\n    JS_PROP_DOUBLE_DEF(\"MIN_VALUE\", 5e-324, 0 ),\n    JS_PROP_DOUBLE_DEF(\"NaN\", NAN, 0 ),\n    JS_PROP_DOUBLE_DEF(\"NEGATIVE_INFINITY\", -INFINITY, 0 ),\n    JS_PROP_DOUBLE_DEF(\"POSITIVE_INFINITY\", INFINITY, 0 ),\n    JS_PROP_DOUBLE_DEF(\"EPSILON\", 2.220446049250313e-16, 0 ), /* ES6 */\n    JS_PROP_DOUBLE_DEF(\"MAX_SAFE_INTEGER\", 9007199254740991.0, 0 ), /* ES6 */\n    JS_PROP_DOUBLE_DEF(\"MIN_SAFE_INTEGER\", -9007199254740991.0, 0 ), /* ES6 */\n    //JS_CFUNC_DEF(\"__toInteger\", 1, js_number___toInteger ),\n    //JS_CFUNC_DEF(\"__toLength\", 1, js_number___toLength ),\n};\n\nstatic JSValue js_thisNumberValue(JSContext *ctx, JSValueConst this_val)\n{\n    if (JS_IsNumber(this_val))\n        return JS_DupValue(ctx, this_val);\n\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_NUMBER) {\n            if (JS_IsNumber(p->u.object_data))\n                return JS_DupValue(ctx, p->u.object_data);\n        }\n    }\n    return JS_ThrowTypeError(ctx, \"not a number\");\n}\n\nstatic JSValue js_number_valueOf(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    return js_thisNumberValue(ctx, this_val);\n}\n\nstatic int js_get_radix(JSContext *ctx, JSValueConst val)\n{\n    int radix;\n    if (JS_ToInt32Sat(ctx, &radix, val))\n        return -1;\n    if (radix < 2 || radix > 36) {\n        JS_ThrowRangeError(ctx, \"radix must be between 2 and 36\");\n        return -1;\n    }\n    return radix;\n}\n\nstatic JSValue js_number_toString(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv, int magic)\n{\n    JSValue val;\n    int base;\n    double d;\n\n    val = js_thisNumberValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (magic || JS_IsUndefined(argv[0])) {\n        base = 10;\n    } else {\n        base = js_get_radix(ctx, argv[0]);\n        if (base < 0)\n            goto fail;\n    }\n    if (JS_ToFloat64Free(ctx, &d, val))\n        return JS_EXCEPTION;\n    return js_dtoa(ctx, d, base, 0, JS_DTOA_VAR_FORMAT);\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_number_toFixed(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValue val;\n    int f;\n    double d;\n\n    val = js_thisNumberValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_ToFloat64Free(ctx, &d, val))\n        return JS_EXCEPTION;\n    if (JS_ToInt32Sat(ctx, &f, argv[0]))\n        return JS_EXCEPTION;\n    if (f < 0 || f > 100)\n        return JS_ThrowRangeError(ctx, \"invalid number of digits\");\n    if (fabs(d) >= 1e21) {\n        return JS_ToStringFree(ctx, __JS_NewFloat64(ctx, d));\n    } else {\n        return js_dtoa(ctx, d, 10, f, JS_DTOA_FRAC_FORMAT);\n    }\n}\n\nstatic JSValue js_number_toExponential(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    JSValue val;\n    int f, flags;\n    double d;\n\n    val = js_thisNumberValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_ToFloat64Free(ctx, &d, val))\n        return JS_EXCEPTION;\n    if (JS_ToInt32Sat(ctx, &f, argv[0]))\n        return JS_EXCEPTION;\n    if (!isfinite(d)) {\n        return JS_ToStringFree(ctx,  __JS_NewFloat64(ctx, d));\n    }\n    if (JS_IsUndefined(argv[0])) {\n        flags = 0;\n        f = 0;\n    } else {\n        if (f < 0 || f > 100)\n            return JS_ThrowRangeError(ctx, \"invalid number of digits\");\n        f++;\n        flags = JS_DTOA_FIXED_FORMAT;\n    }\n    return js_dtoa(ctx, d, 10, f, flags | JS_DTOA_FORCE_EXP);\n}\n\nstatic JSValue js_number_toPrecision(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue val;\n    int p;\n    double d;\n\n    val = js_thisNumberValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_ToFloat64Free(ctx, &d, val))\n        return JS_EXCEPTION;\n    if (JS_IsUndefined(argv[0]))\n        goto to_string;\n    if (JS_ToInt32Sat(ctx, &p, argv[0]))\n        return JS_EXCEPTION;\n    if (!isfinite(d)) {\n    to_string:\n        return JS_ToStringFree(ctx,  __JS_NewFloat64(ctx, d));\n    }\n    if (p < 1 || p > 100)\n        return JS_ThrowRangeError(ctx, \"invalid number of digits\");\n    return js_dtoa(ctx, d, 10, p, JS_DTOA_FIXED_FORMAT);\n}\n\nstatic const JSCFunctionListEntry js_number_proto_funcs[] = {\n    JS_CFUNC_DEF(\"toExponential\", 1, js_number_toExponential ),\n    JS_CFUNC_DEF(\"toFixed\", 1, js_number_toFixed ),\n    JS_CFUNC_DEF(\"toPrecision\", 1, js_number_toPrecision ),\n    JS_CFUNC_MAGIC_DEF(\"toString\", 1, js_number_toString, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"toLocaleString\", 0, js_number_toString, 1 ),\n    JS_CFUNC_DEF(\"valueOf\", 0, js_number_valueOf ),\n};\n\nstatic JSValue js_parseInt(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    const char *str, *p;\n    int radix, flags;\n    JSValue ret;\n\n    str = JS_ToCString(ctx, argv[0]);\n    if (!str)\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &radix, argv[1])) {\n        JS_FreeCString(ctx, str);\n        return JS_EXCEPTION;\n    }\n    if (radix != 0 && (radix < 2 || radix > 36)) {\n        ret = JS_NAN;\n    } else {\n        p = str;\n        p += skip_spaces(p);\n        flags = ATOD_INT_ONLY | ATOD_ACCEPT_PREFIX_AFTER_SIGN;\n        ret = js_atof(ctx, p, NULL, radix, flags);\n    }\n    JS_FreeCString(ctx, str);\n    return ret;\n}\n\nstatic JSValue js_parseFloat(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    const char *str, *p;\n    JSValue ret;\n\n    str = JS_ToCString(ctx, argv[0]);\n    if (!str)\n        return JS_EXCEPTION;\n    p = str;\n    p += skip_spaces(p);\n    ret = js_atof(ctx, p, NULL, 10, 0);\n    JS_FreeCString(ctx, str);\n    return ret;\n}\n\n/* Boolean */\nstatic JSValue js_boolean_constructor(JSContext *ctx, JSValueConst new_target,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue val, obj;\n    val = JS_NewBool(ctx, JS_ToBool(ctx, argv[0]));\n    if (!JS_IsUndefined(new_target)) {\n        obj = js_create_from_ctor(ctx, new_target, JS_CLASS_BOOLEAN);\n        if (!JS_IsException(obj))\n            JS_SetObjectData(ctx, obj, val);\n        return obj;\n    } else {\n        return val;\n    }\n}\n\nstatic JSValue js_thisBooleanValue(JSContext *ctx, JSValueConst this_val)\n{\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_BOOL)\n        return JS_DupValue(ctx, this_val);\n\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_BOOLEAN) {\n            if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_BOOL)\n                return p->u.object_data;\n        }\n    }\n    return JS_ThrowTypeError(ctx, \"not a boolean\");\n}\n\nstatic JSValue js_boolean_toString(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    JSValue val = js_thisBooleanValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    return JS_AtomToString(ctx, JS_VALUE_GET_BOOL(val) ?\n                       JS_ATOM_true : JS_ATOM_false);\n}\n\nstatic JSValue js_boolean_valueOf(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    return js_thisBooleanValue(ctx, this_val);\n}\n\nstatic const JSCFunctionListEntry js_boolean_proto_funcs[] = {\n    JS_CFUNC_DEF(\"toString\", 0, js_boolean_toString ),\n    JS_CFUNC_DEF(\"valueOf\", 0, js_boolean_valueOf ),\n};\n\n/* String */\n\nstatic int js_string_get_own_property(JSContext *ctx,\n                                      JSPropertyDescriptor *desc,\n                                      JSValueConst obj, JSAtom prop)\n{\n    JSObject *p;\n    JSString *p1;\n    uint32_t idx, ch;\n\n    /* This is a class exotic method: obj class_id is JS_CLASS_STRING */\n    if (__JS_AtomIsTaggedInt(prop)) {\n        p = JS_VALUE_GET_OBJ(obj);\n        if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_STRING) {\n            p1 = JS_VALUE_GET_STRING(p->u.object_data);\n            idx = __JS_AtomToUInt32(prop);\n            if (idx < p1->len) {\n                if (desc) {\n                    if (p1->is_wide_char)\n                        ch = p1->u.str16[idx];\n                    else\n                        ch = p1->u.str8[idx];\n                    desc->flags = JS_PROP_ENUMERABLE;\n                    desc->value = js_new_string_char(ctx, ch);\n                    desc->getter = JS_UNDEFINED;\n                    desc->setter = JS_UNDEFINED;\n                }\n                return TRUE;\n            }\n        }\n    }\n    return FALSE;\n}\n\nstatic int js_string_define_own_property(JSContext *ctx,\n                                         JSValueConst this_obj,\n                                         JSAtom prop, JSValueConst val,\n                                         JSValueConst getter,\n                                         JSValueConst setter, int flags)\n{\n    uint32_t idx;\n    JSObject *p;\n    JSString *p1, *p2;\n    \n    if (__JS_AtomIsTaggedInt(prop)) {\n        idx = __JS_AtomToUInt32(prop);\n        p = JS_VALUE_GET_OBJ(this_obj);\n        if (JS_VALUE_GET_TAG(p->u.object_data) != JS_TAG_STRING)\n            goto def;\n        p1 = JS_VALUE_GET_STRING(p->u.object_data);\n        if (idx >= p1->len)\n            goto def;\n        if (!check_define_prop_flags(JS_PROP_ENUMERABLE, flags))\n            goto fail;\n        /* check that the same value is configured */\n        if (flags & JS_PROP_HAS_VALUE) {\n            if (JS_VALUE_GET_TAG(val) != JS_TAG_STRING)\n                goto fail;\n            p2 = JS_VALUE_GET_STRING(val);\n            if (p2->len != 1)\n                goto fail;\n            if (string_get(p1, idx) != string_get(p2, 0)) {\n            fail:\n                return JS_ThrowTypeErrorOrFalse(ctx, flags, \"property is not configurable\");\n            }\n        }\n        return TRUE;\n    } else {\n    def:\n        return JS_DefineProperty(ctx, this_obj, prop, val, getter, setter,\n                                 flags | JS_PROP_NO_EXOTIC);\n    }\n}\n\nstatic int js_string_delete_property(JSContext *ctx,\n                                     JSValueConst obj, JSAtom prop)\n{\n    uint32_t idx;\n\n    if (__JS_AtomIsTaggedInt(prop)) {\n        idx = __JS_AtomToUInt32(prop);\n        if (idx < js_string_obj_get_length(ctx, obj)) {\n            return FALSE;\n        }\n    }\n    return TRUE;\n}\n\nstatic const JSClassExoticMethods js_string_exotic_methods = {\n    .get_own_property = js_string_get_own_property,\n    .define_own_property = js_string_define_own_property,\n    .delete_property = js_string_delete_property,\n};\n\nstatic JSValue js_string_constructor(JSContext *ctx, JSValueConst new_target,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue val, obj;\n    if (argc == 0) {\n        val = JS_AtomToString(ctx, JS_ATOM_empty_string);\n    } else {\n        if (JS_IsUndefined(new_target) && JS_IsSymbol(argv[0])) {\n            JSAtomStruct *p = JS_VALUE_GET_PTR(argv[0]);\n            val = JS_ConcatString3(ctx, \"Symbol(\", JS_AtomToString(ctx, js_get_atom_index(ctx->rt, p)), \")\");\n        } else {\n            val = JS_ToString(ctx, argv[0]);\n        }\n        if (JS_IsException(val))\n            return val;\n    }\n    if (!JS_IsUndefined(new_target)) {\n        JSString *p1 = JS_VALUE_GET_STRING(val);\n\n        obj = js_create_from_ctor(ctx, new_target, JS_CLASS_STRING);\n        if (!JS_IsException(obj)) {\n            JS_SetObjectData(ctx, obj, val);\n            JS_DefinePropertyValue(ctx, obj, JS_ATOM_length, JS_NewInt32(ctx, p1->len), 0);\n        }\n        return obj;\n    } else {\n        return val;\n    }\n}\n\nstatic JSValue js_thisStringValue(JSContext *ctx, JSValueConst this_val)\n{\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_STRING)\n        return JS_DupValue(ctx, this_val);\n\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_STRING) {\n            if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_STRING)\n                return JS_DupValue(ctx, p->u.object_data);\n        }\n    }\n    return JS_ThrowTypeError(ctx, \"not a string\");\n}\n\nstatic JSValue js_string_fromCharCode(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv)\n{\n    int i;\n    StringBuffer b_s, *b = &b_s;\n\n    string_buffer_init(ctx, b, argc);\n\n    for(i = 0; i < argc; i++) {\n        int32_t c;\n        if (JS_ToInt32(ctx, &c, argv[i]) || string_buffer_putc16(b, c & 0xffff)) {\n            string_buffer_free(b);\n            return JS_EXCEPTION;\n        }\n    }\n    return string_buffer_end(b);\n}\n\nstatic JSValue js_string_fromCodePoint(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    double d;\n    int i, c;\n    StringBuffer b_s, *b = &b_s;\n\n    /* XXX: could pre-compute string length if all arguments are JS_TAG_INT */\n\n    if (string_buffer_init(ctx, b, argc))\n        goto fail;\n    for(i = 0; i < argc; i++) {\n        if (JS_VALUE_GET_TAG(argv[i]) == JS_TAG_INT) {\n            c = JS_VALUE_GET_INT(argv[i]);\n            if (c < 0 || c > 0x10ffff)\n                goto range_error;\n        } else {\n            if (JS_ToFloat64(ctx, &d, argv[i]))\n                goto fail;\n            if (d < 0 || d > 0x10ffff || (c = (int)d) != d)\n                goto range_error;\n        }\n        if (string_buffer_putc(b, c))\n            goto fail;\n    }\n    return string_buffer_end(b);\n\n range_error:\n    JS_ThrowRangeError(ctx, \"invalid code point\");\n fail:\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_string_raw(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    // raw(temp,...a)\n    JSValue cooked, val, raw;\n    StringBuffer b_s, *b = &b_s;\n    int64_t i, n;\n\n    string_buffer_init(ctx, b, 0);\n    raw = JS_UNDEFINED;\n    cooked = JS_ToObject(ctx, argv[0]);\n    if (JS_IsException(cooked))\n        goto exception;\n    raw = JS_ToObjectFree(ctx, JS_GetProperty(ctx, cooked, JS_ATOM_raw));\n    if (JS_IsException(raw))\n        goto exception;\n    if (js_get_length64(ctx, &n, raw) < 0)\n        goto exception;\n        \n    for (i = 0; i < n; i++) {\n        val = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, raw, i));\n        if (JS_IsException(val))\n            goto exception;\n        string_buffer_concat_value_free(b, val);\n        if (i < n - 1 && i + 1 < argc) {\n            if (string_buffer_concat_value(b, argv[i + 1]))\n                goto exception;\n        }\n    }\n    JS_FreeValue(ctx, cooked);\n    JS_FreeValue(ctx, raw);\n    return string_buffer_end(b);\n\nexception:\n    JS_FreeValue(ctx, cooked);\n    JS_FreeValue(ctx, raw);\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\n/* only used in test262 */\nJSValue js_string_codePointRange(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    uint32_t start, end, i, n;\n    StringBuffer b_s, *b = &b_s;\n\n    if (JS_ToUint32(ctx, &start, argv[0]) ||\n        JS_ToUint32(ctx, &end, argv[1]))\n        return JS_EXCEPTION;\n    end = min_uint32(end, 0x10ffff + 1);\n\n    if (start > end) {\n        start = end;\n    }\n    n = end - start;\n    if (end > 0x10000) {\n        n += end - max_uint32(start, 0x10000);\n    }\n    if (string_buffer_init2(ctx, b, n, end >= 0x100))\n        return JS_EXCEPTION;\n    for(i = start; i < end; i++) {\n        string_buffer_putc(b, i);\n    }\n    return string_buffer_end(b);\n}\n\n#if 0\nstatic JSValue js_string___isSpace(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    int c;\n    if (JS_ToInt32(ctx, &c, argv[0]))\n        return JS_EXCEPTION;\n    return JS_NewBool(ctx, lre_is_space(c));\n}\n#endif\n\nstatic JSValue js_string_charCodeAt(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    JSString *p;\n    int idx, c;\n\n    val = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    p = JS_VALUE_GET_STRING(val);\n    if (JS_ToInt32Sat(ctx, &idx, argv[0])) {\n        JS_FreeValue(ctx, val);\n        return JS_EXCEPTION;\n    }\n    if (idx < 0 || idx >= p->len) {\n        ret = JS_NAN;\n    } else {\n        if (p->is_wide_char)\n            c = p->u.str16[idx];\n        else\n            c = p->u.str8[idx];\n        ret = JS_NewInt32(ctx, c);\n    }\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nstatic JSValue js_string_charAt(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    JSString *p;\n    int idx, c;\n\n    val = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    p = JS_VALUE_GET_STRING(val);\n    if (JS_ToInt32Sat(ctx, &idx, argv[0])) {\n        JS_FreeValue(ctx, val);\n        return JS_EXCEPTION;\n    }\n    if (idx < 0 || idx >= p->len) {\n        ret = js_new_string8(ctx, NULL, 0);\n    } else {\n        if (p->is_wide_char)\n            c = p->u.str16[idx];\n        else\n            c = p->u.str8[idx];\n        ret = js_new_string_char(ctx, c);\n    }\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nstatic JSValue js_string_codePointAt(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    JSString *p;\n    int idx, c;\n\n    val = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    p = JS_VALUE_GET_STRING(val);\n    if (JS_ToInt32Sat(ctx, &idx, argv[0])) {\n        JS_FreeValue(ctx, val);\n        return JS_EXCEPTION;\n    }\n    if (idx < 0 || idx >= p->len) {\n        ret = JS_UNDEFINED;\n    } else {\n        c = string_getc(p, &idx);\n        ret = JS_NewInt32(ctx, c);\n    }\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nstatic JSValue js_string_concat(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValue r;\n    int i;\n\n    /* XXX: Use more efficient method */\n    /* XXX: This method is OK if r has a single refcount */\n    /* XXX: should use string_buffer? */\n    r = JS_ToStringCheckObject(ctx, this_val);\n    for (i = 0; i < argc; i++) {\n        if (JS_IsException(r))\n            break;\n        r = JS_ConcatString(ctx, r, JS_DupValue(ctx, argv[i]));\n    }\n    return r;\n}\n\nstatic int string_cmp(JSString *p1, JSString *p2, int x1, int x2, int len)\n{\n    int i, c1, c2;\n    for (i = 0; i < len; i++) {\n        if ((c1 = string_get(p1, x1 + i)) != (c2 = string_get(p2, x2 + i)))\n            return c1 - c2;\n    }\n    return 0;\n}\n\nstatic int string_indexof_char(JSString *p, int c, int from)\n{\n    /* assuming 0 <= from <= p->len */\n    int i, len = p->len;\n    if (p->is_wide_char) {\n        for (i = from; i < len; i++) {\n            if (p->u.str16[i] == c)\n                return i;\n        }\n    } else {\n        if ((c & ~0xff) == 0) {\n            for (i = from; i < len; i++) {\n                if (p->u.str8[i] == (uint8_t)c)\n                    return i;\n            }\n        }\n    }\n    return -1;\n}\n\nstatic int string_indexof(JSString *p1, JSString *p2, int from)\n{\n    /* assuming 0 <= from <= p1->len */\n    int c, i, j, len1 = p1->len, len2 = p2->len;\n    if (len2 == 0)\n        return from;\n    for (i = from, c = string_get(p2, 0); i + len2 <= len1; i = j + 1) {\n        j = string_indexof_char(p1, c, i);\n        if (j < 0 || j + len2 > len1)\n            break;\n        if (!string_cmp(p1, p2, j + 1, 1, len2 - 1))\n            return j;\n    }\n    return -1;\n}\n\nstatic int64_t string_advance_index(JSString *p, int64_t index, BOOL unicode)\n{\n    if (!unicode || index >= p->len || !p->is_wide_char) {\n        index++;\n    } else {\n        int index32 = (int)index;\n        string_getc(p, &index32);\n        index = index32;\n    }\n    return index;\n}\n\nstatic JSValue js_string_indexOf(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv, int lastIndexOf)\n{\n    JSValue str, v;\n    int i, len, v_len, pos, start, stop, ret, inc;\n    JSString *p;\n    JSString *p1;\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        return str;\n    v = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(v))\n        goto fail;\n    p = JS_VALUE_GET_STRING(str);\n    p1 = JS_VALUE_GET_STRING(v);\n    len = p->len;\n    v_len = p1->len;\n    if (lastIndexOf) {\n        pos = len - v_len;\n        if (argc > 1) {\n            double d;\n            if (JS_ToFloat64(ctx, &d, argv[1]))\n                goto fail;\n            if (!isnan(d)) {\n                if (d <= 0)\n                    pos = 0;\n                else if (d < pos)\n                    pos = d;\n            }\n        }\n        start = pos;\n        stop = 0;\n        inc = -1;\n    } else {\n        pos = 0;\n        if (argc > 1) {\n            if (JS_ToInt32Clamp(ctx, &pos, argv[1], 0, len, 0))\n                goto fail;\n        }\n        start = pos;\n        stop = len - v_len;\n        inc = 1;\n    }\n    ret = -1;\n    if (len >= v_len && inc * (stop - start) >= 0) {\n        for (i = start;; i += inc) {\n            if (!string_cmp(p, p1, i, 0, v_len)) {\n                ret = i;\n                break;\n            }\n            if (i == stop)\n                break;\n        }\n    }\n    JS_FreeValue(ctx, str);\n    JS_FreeValue(ctx, v);\n    return JS_NewInt32(ctx, ret);\n\nfail:\n    JS_FreeValue(ctx, str);\n    JS_FreeValue(ctx, v);\n    return JS_EXCEPTION;\n}\n\n/* return < 0 if exception or TRUE/FALSE */\nstatic int js_is_regexp(JSContext *ctx, JSValueConst obj);\n\nstatic JSValue js_string_includes(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv, int magic)\n{\n    JSValue str, v = JS_UNDEFINED;\n    int i, len, v_len, pos, start, stop, ret;\n    JSString *p;\n    JSString *p1;\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        return str;\n    ret = js_is_regexp(ctx, argv[0]);\n    if (ret) {\n        if (ret > 0)\n            JS_ThrowTypeError(ctx, \"regex not supported\");\n        goto fail;\n    }\n    v = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(v))\n        goto fail;\n    p = JS_VALUE_GET_STRING(str);\n    p1 = JS_VALUE_GET_STRING(v);\n    len = p->len;\n    v_len = p1->len;\n    pos = (magic == 2) ? len : 0;\n    if (argc > 1 && !JS_IsUndefined(argv[1])) {\n        if (JS_ToInt32Clamp(ctx, &pos, argv[1], 0, len, 0))\n            goto fail;\n    }\n    len -= v_len;\n    ret = 0;\n    if (magic == 0) {\n        start = pos;\n        stop = len;\n    } else {\n        if (magic == 1) {\n            if (pos > len)\n                goto done;\n        } else {\n            pos -= v_len;\n        }\n        start = stop = pos;\n    }\n    if (start >= 0 && start <= stop) {\n        for (i = start;; i++) {\n            if (!string_cmp(p, p1, i, 0, v_len)) {\n                ret = 1;\n                break;\n            }\n            if (i == stop)\n                break;\n        }\n    }\n done:\n    JS_FreeValue(ctx, str);\n    JS_FreeValue(ctx, v);\n    return JS_NewBool(ctx, ret);\n\nfail:\n    JS_FreeValue(ctx, str);\n    JS_FreeValue(ctx, v);\n    return JS_EXCEPTION;\n}\n\nstatic int check_regexp_g_flag(JSContext *ctx, JSValueConst regexp)\n{\n    int ret;\n    JSValue flags;\n    \n    ret = js_is_regexp(ctx, regexp);\n    if (ret < 0)\n        return -1;\n    if (ret) {\n        flags = JS_GetProperty(ctx, regexp, JS_ATOM_flags);\n        if (JS_IsException(flags))\n            return -1;\n        if (JS_IsUndefined(flags) || JS_IsNull(flags)) {\n            JS_ThrowTypeError(ctx, \"cannot convert to object\");\n            return -1;\n        }\n        flags = JS_ToStringFree(ctx, flags);\n        if (JS_IsException(flags))\n            return -1;\n        ret = string_indexof_char(JS_VALUE_GET_STRING(flags), 'g', 0);\n        JS_FreeValue(ctx, flags);\n        if (ret < 0) {\n            JS_ThrowTypeError(ctx, \"regexp must have the 'g' flag\");\n            return -1;\n        }\n    }\n    return 0;\n}\n\nstatic JSValue js_string_match(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv, int atom)\n{\n    // match(rx), search(rx), matchAll(rx)\n    // atom is JS_ATOM_Symbol_match, JS_ATOM_Symbol_search, or JS_ATOM_Symbol_matchAll\n    JSValueConst O = this_val, regexp = argv[0], args[2];\n    JSValue matcher, S, rx, result, str;\n    int args_len;\n\n    if (JS_IsUndefined(O) || JS_IsNull(O))\n        return JS_ThrowTypeError(ctx, \"cannot convert to object\");\n\n    if (!JS_IsUndefined(regexp) && !JS_IsNull(regexp)) {\n        matcher = JS_GetProperty(ctx, regexp, atom);\n        if (JS_IsException(matcher))\n            return JS_EXCEPTION;\n        if (atom == JS_ATOM_Symbol_matchAll) {\n            if (check_regexp_g_flag(ctx, regexp) < 0) {\n                JS_FreeValue(ctx, matcher);\n                return JS_EXCEPTION;\n            }\n        }\n        if (!JS_IsUndefined(matcher) && !JS_IsNull(matcher)) {\n            return JS_CallFree(ctx, matcher, regexp, 1, &O);\n        }\n    }\n    S = JS_ToString(ctx, O);\n    if (JS_IsException(S))\n        return JS_EXCEPTION;\n    args_len = 1;\n    args[0] = regexp;\n    str = JS_UNDEFINED;\n    if (atom == JS_ATOM_Symbol_matchAll) {\n        str = JS_NewString(ctx, \"g\");\n        if (JS_IsException(str))\n            goto fail;\n        args[args_len++] = str;\n    }\n    rx = JS_CallConstructor(ctx, ctx->regexp_ctor, args_len, args);\n    JS_FreeValue(ctx, str);\n    if (JS_IsException(rx)) {\n    fail:\n        JS_FreeValue(ctx, S);\n        return JS_EXCEPTION;\n    }\n    result = JS_InvokeFree(ctx, rx, atom, 1, (JSValueConst *)&S);\n    JS_FreeValue(ctx, S);\n    return result;\n}\n\nstatic JSValue js_string___GetSubstitution(JSContext *ctx, JSValueConst this_val,\n                                           int argc, JSValueConst *argv)\n{\n    // GetSubstitution(matched, str, position, captures, namedCaptures, rep)\n    JSValueConst matched, str, captures, namedCaptures, rep;\n    JSValue capture, name, s;\n    uint32_t position, len, matched_len, captures_len;\n    int i, j, j0, k, k1;\n    int c, c1;\n    StringBuffer b_s, *b = &b_s;\n    JSString *sp, *rp;\n\n    matched = argv[0];\n    str = argv[1];\n    captures = argv[3];\n    namedCaptures = argv[4];\n    rep = argv[5];\n\n    if (!JS_IsString(rep) || !JS_IsString(str))\n        return JS_ThrowTypeError(ctx, \"not a string\");\n\n    sp = JS_VALUE_GET_STRING(str);\n    rp = JS_VALUE_GET_STRING(rep);\n\n    string_buffer_init(ctx, b, 0);\n\n    captures_len = 0;\n    if (!JS_IsUndefined(captures)) {\n        if (js_get_length32(ctx, &captures_len, captures))\n            goto exception;\n    }\n    if (js_get_length32(ctx, &matched_len, matched))\n        goto exception;\n    if (JS_ToUint32(ctx, &position, argv[2]) < 0)\n        goto exception;\n\n    len = rp->len;\n    i = 0;\n    for(;;) {\n        j = string_indexof_char(rp, '$', i);\n        if (j < 0 || j + 1 >= len)\n            break;\n        string_buffer_concat(b, rp, i, j);\n        j0 = j++;\n        c = string_get(rp, j++);\n        if (c == '$') {\n            string_buffer_putc8(b, '$');\n        } else if (c == '&') {\n            if (string_buffer_concat_value(b, matched))\n                goto exception;\n        } else if (c == '`') {\n            string_buffer_concat(b, sp, 0, position);\n        } else if (c == '\\'') {\n            string_buffer_concat(b, sp, position + matched_len, sp->len);\n        } else if (c >= '0' && c <= '9') {\n            k = c - '0';\n            if (j < len) {\n                c1 = string_get(rp, j);\n                if (c1 >= '0' && c1 <= '9') {\n                    /* This behavior is specified in ES6 and refined in ECMA 2019 */\n                    /* ECMA 2019 does not have the extra test, but\n                       Test262 S15.5.4.11_A3_T1..3 require this behavior */\n                    k1 = k * 10 + c1 - '0';\n                    if (k1 >= 1 && k1 < captures_len) {\n                        k = k1;\n                        j++;\n                    }\n                }\n            }\n            if (k >= 1 && k < captures_len) {\n                s = JS_GetPropertyInt64(ctx, captures, k);\n                if (JS_IsException(s))\n                    goto exception;\n                if (!JS_IsUndefined(s)) {\n                    if (string_buffer_concat_value_free(b, s))\n                        goto exception;\n                }\n            } else {\n                goto norep;\n            }\n        } else if (c == '<' && !JS_IsUndefined(namedCaptures)) {\n            k = string_indexof_char(rp, '>', j);\n            if (k < 0)\n                goto norep;\n            name = js_sub_string(ctx, rp, j, k);\n            if (JS_IsException(name))\n                goto exception;\n            capture = JS_GetPropertyValue(ctx, namedCaptures, name);\n            if (JS_IsException(capture))\n                goto exception;\n            if (!JS_IsUndefined(capture)) {\n                if (string_buffer_concat_value_free(b, capture))\n                    goto exception;\n            }\n            j = k + 1;\n        } else {\n        norep:\n            string_buffer_concat(b, rp, j0, j);\n        }\n        i = j;\n    }\n    string_buffer_concat(b, rp, i, rp->len);\n    return string_buffer_end(b);\nexception:\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_string_replace(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv,\n                                 int is_replaceAll)\n{\n    // replace(rx, rep)\n    JSValueConst O = this_val, searchValue = argv[0], replaceValue = argv[1];\n    JSValueConst args[6];\n    JSValue str, search_str, replaceValue_str, repl_str;\n    JSString *sp, *searchp;\n    StringBuffer b_s, *b = &b_s;\n    int pos, functionalReplace, endOfLastMatch;\n    BOOL is_first;\n\n    if (JS_IsUndefined(O) || JS_IsNull(O))\n        return JS_ThrowTypeError(ctx, \"cannot convert to object\");\n\n    search_str = JS_UNDEFINED;\n    replaceValue_str = JS_UNDEFINED;\n    repl_str = JS_UNDEFINED;\n\n    if (!JS_IsUndefined(searchValue) && !JS_IsNull(searchValue)) {\n        JSValue replacer;\n        if (is_replaceAll) {\n            if (check_regexp_g_flag(ctx, searchValue) < 0)\n                return JS_EXCEPTION;\n        }\n        replacer = JS_GetProperty(ctx, searchValue, JS_ATOM_Symbol_replace);\n        if (JS_IsException(replacer))\n            return JS_EXCEPTION;\n        if (!JS_IsUndefined(replacer) && !JS_IsNull(replacer)) {\n            args[0] = O;\n            args[1] = replaceValue;\n            return JS_CallFree(ctx, replacer, searchValue, 2, args);\n        }\n    }\n    string_buffer_init(ctx, b, 0);\n\n    str = JS_ToString(ctx, O);\n    if (JS_IsException(str))\n        goto exception;\n    search_str = JS_ToString(ctx, searchValue);\n    if (JS_IsException(search_str))\n        goto exception;\n    functionalReplace = JS_IsFunction(ctx, replaceValue);\n    if (!functionalReplace) {\n        replaceValue_str = JS_ToString(ctx, replaceValue);\n        if (JS_IsException(replaceValue_str))\n            goto exception;\n    }\n\n    sp = JS_VALUE_GET_STRING(str);\n    searchp = JS_VALUE_GET_STRING(search_str);\n    endOfLastMatch = 0;\n    is_first = TRUE;\n    for(;;) {\n        if (unlikely(searchp->len == 0)) {\n            if (is_first)\n                pos = 0;\n            else if (endOfLastMatch >= sp->len)\n                pos = -1;\n            else\n                pos = endOfLastMatch + 1;\n        } else {\n            pos = string_indexof(sp, searchp, endOfLastMatch);\n        }\n        if (pos < 0) {\n            if (is_first) {\n                string_buffer_free(b);\n                JS_FreeValue(ctx, search_str);\n                JS_FreeValue(ctx, replaceValue_str);\n                return str;\n            } else {\n                break;\n            }\n        }\n        if (functionalReplace) {\n            args[0] = search_str;\n            args[1] = JS_NewInt32(ctx, pos);\n            args[2] = str;\n            repl_str = JS_ToStringFree(ctx, JS_Call(ctx, replaceValue, JS_UNDEFINED, 3, args));\n        } else {\n            args[0] = search_str;\n            args[1] = str;\n            args[2] = JS_NewInt32(ctx, pos);\n            args[3] = JS_UNDEFINED;\n            args[4] = JS_UNDEFINED;\n            args[5] = replaceValue_str;\n            repl_str = js_string___GetSubstitution(ctx, JS_UNDEFINED, 6, args);\n        }\n        if (JS_IsException(repl_str))\n            goto exception;\n        \n        string_buffer_concat(b, sp, endOfLastMatch, pos);\n        string_buffer_concat_value_free(b, repl_str);\n        endOfLastMatch = pos + searchp->len;\n        is_first = FALSE;\n        if (!is_replaceAll)\n            break;\n    }\n    string_buffer_concat(b, sp, endOfLastMatch, sp->len);\n    JS_FreeValue(ctx, search_str);\n    JS_FreeValue(ctx, replaceValue_str);\n    JS_FreeValue(ctx, str);\n    return string_buffer_end(b);\n\nexception:\n    string_buffer_free(b);\n    JS_FreeValue(ctx, search_str);\n    JS_FreeValue(ctx, replaceValue_str);\n    JS_FreeValue(ctx, str);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_string_split(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    // split(sep, limit)\n    JSValueConst O = this_val, separator = argv[0], limit = argv[1];\n    JSValueConst args[2];\n    JSValue S, A, R, T;\n    uint32_t lim, lengthA;\n    int64_t p, q, s, r, e;\n    JSString *sp, *rp;\n\n    if (JS_IsUndefined(O) || JS_IsNull(O))\n        return JS_ThrowTypeError(ctx, \"cannot convert to object\");\n\n    S = JS_UNDEFINED;\n    A = JS_UNDEFINED;\n    R = JS_UNDEFINED;\n\n    if (!JS_IsUndefined(separator) && !JS_IsNull(separator)) {\n        JSValue splitter;\n        splitter = JS_GetProperty(ctx, separator, JS_ATOM_Symbol_split);\n        if (JS_IsException(splitter))\n            return JS_EXCEPTION;\n        if (!JS_IsUndefined(splitter) && !JS_IsNull(splitter)) {\n            args[0] = O;\n            args[1] = limit;\n            return JS_CallFree(ctx, splitter, separator, 2, args);\n        }\n    }\n    S = JS_ToString(ctx, O);\n    if (JS_IsException(S))\n        goto exception;\n    A = JS_NewArray(ctx);\n    if (JS_IsException(A))\n        goto exception;\n    lengthA = 0;\n    if (JS_IsUndefined(limit)) {\n        lim = 0xffffffff;\n    } else {\n        if (JS_ToUint32(ctx, &lim, limit) < 0)\n            goto exception;\n    }\n    sp = JS_VALUE_GET_STRING(S);\n    s = sp->len;\n    R = JS_ToString(ctx, separator);\n    if (JS_IsException(R))\n        goto exception;\n    rp = JS_VALUE_GET_STRING(R);\n    r = rp->len;\n    p = 0;\n    if (lim == 0)\n        goto done;\n    if (JS_IsUndefined(separator))\n        goto add_tail;\n    if (s == 0) {\n        if (r != 0)\n            goto add_tail;\n        goto done;\n    }\n    q = p;\n    for (q = p; (q += !r) <= s - r - !r; q = p = e + r) {\n        e = string_indexof(sp, rp, q);\n        if (e < 0)\n            break;\n        T = js_sub_string(ctx, sp, p, e);\n        if (JS_IsException(T))\n            goto exception;\n        if (JS_CreateDataPropertyUint32(ctx, A, lengthA++, T, 0) < 0)\n            goto exception;\n        if (lengthA == lim)\n            goto done;\n    }\nadd_tail:\n    T = js_sub_string(ctx, sp, p, s);\n    if (JS_IsException(T))\n        goto exception;\n    if (JS_CreateDataPropertyUint32(ctx, A, lengthA++, T,0 ) < 0)\n        goto exception;\ndone:\n    JS_FreeValue(ctx, S);\n    JS_FreeValue(ctx, R);\n    return A;\n\nexception:\n    JS_FreeValue(ctx, A);\n    JS_FreeValue(ctx, S);\n    JS_FreeValue(ctx, R);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_string_substring(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    JSValue str, ret;\n    int a, b, start, end;\n    JSString *p;\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        return str;\n    p = JS_VALUE_GET_STRING(str);\n    if (JS_ToInt32Clamp(ctx, &a, argv[0], 0, p->len, 0)) {\n        JS_FreeValue(ctx, str);\n        return JS_EXCEPTION;\n    }\n    b = p->len;\n    if (!JS_IsUndefined(argv[1])) {\n        if (JS_ToInt32Clamp(ctx, &b, argv[1], 0, p->len, 0)) {\n            JS_FreeValue(ctx, str);\n            return JS_EXCEPTION;\n        }\n    }\n    if (a < b) {\n        start = a;\n        end = b;\n    } else {\n        start = b;\n        end = a;\n    }\n    ret = js_sub_string(ctx, p, start, end);\n    JS_FreeValue(ctx, str);\n    return ret;\n}\n\nstatic JSValue js_string_substr(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValue str, ret;\n    int a, len, n;\n    JSString *p;\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        return str;\n    p = JS_VALUE_GET_STRING(str);\n    len = p->len;\n    if (JS_ToInt32Clamp(ctx, &a, argv[0], 0, len, len)) {\n        JS_FreeValue(ctx, str);\n        return JS_EXCEPTION;\n    }\n    n = len - a;\n    if (!JS_IsUndefined(argv[1])) {\n        if (JS_ToInt32Clamp(ctx, &n, argv[1], 0, len - a, 0)) {\n            JS_FreeValue(ctx, str);\n            return JS_EXCEPTION;\n        }\n    }\n    ret = js_sub_string(ctx, p, a, a + n);\n    JS_FreeValue(ctx, str);\n    return ret;\n}\n\nstatic JSValue js_string_slice(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    JSValue str, ret;\n    int len, start, end;\n    JSString *p;\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        return str;\n    p = JS_VALUE_GET_STRING(str);\n    len = p->len;\n    if (JS_ToInt32Clamp(ctx, &start, argv[0], 0, len, len)) {\n        JS_FreeValue(ctx, str);\n        return JS_EXCEPTION;\n    }\n    end = len;\n    if (!JS_IsUndefined(argv[1])) {\n        if (JS_ToInt32Clamp(ctx, &end, argv[1], 0, len, len)) {\n            JS_FreeValue(ctx, str);\n            return JS_EXCEPTION;\n        }\n    }\n    ret = js_sub_string(ctx, p, start, max_int(end, start));\n    JS_FreeValue(ctx, str);\n    return ret;\n}\n\nstatic JSValue js_string_pad(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv, int padEnd)\n{\n    JSValue str, v = JS_UNDEFINED;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p, *p1 = NULL;\n    int n, len, c = ' ';\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        goto fail1;\n    if (JS_ToInt32Sat(ctx, &n, argv[0]))\n        goto fail2;\n    p = JS_VALUE_GET_STRING(str);\n    len = p->len;\n    if (len >= n)\n        return str;\n    if (argc > 1 && !JS_IsUndefined(argv[1])) {\n        v = JS_ToString(ctx, argv[1]);\n        if (JS_IsException(v))\n            goto fail2;\n        p1 = JS_VALUE_GET_STRING(v);\n        if (p1->len == 0) {\n            JS_FreeValue(ctx, v);\n            return str;\n        }\n        if (p1->len == 1) {\n            c = string_get(p1, 0);\n            p1 = NULL;\n        }\n    }\n    if (n > JS_STRING_LEN_MAX) {\n        JS_ThrowInternalError(ctx, \"string too long\");\n        goto fail2;\n    }\n    if (string_buffer_init(ctx, b, n))\n        goto fail3;\n    n -= len;\n    if (padEnd) {\n        if (string_buffer_concat(b, p, 0, len))\n            goto fail;\n    }\n    if (p1) {\n        while (n > 0) {\n            int chunk = min_int(n, p1->len);\n            if (string_buffer_concat(b, p1, 0, chunk))\n                goto fail;\n            n -= chunk;\n        }\n    } else {\n        if (string_buffer_fill(b, c, n))\n            goto fail;\n    }\n    if (!padEnd) {\n        if (string_buffer_concat(b, p, 0, len))\n            goto fail;\n    }\n    JS_FreeValue(ctx, v);\n    JS_FreeValue(ctx, str);\n    return string_buffer_end(b);\n\nfail:\n    string_buffer_free(b);\nfail3:\n    JS_FreeValue(ctx, v);\nfail2:\n    JS_FreeValue(ctx, str);\nfail1:\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_string_repeat(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValue str;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p;\n    int64_t val;\n    int n, len;\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        goto fail;\n    if (JS_ToInt64Sat(ctx, &val, argv[0]))\n        goto fail;\n    if (val < 0 || val > 2147483647) {\n        JS_ThrowRangeError(ctx, \"invalid repeat count\");\n        goto fail;\n    }\n    n = val;\n    p = JS_VALUE_GET_STRING(str);\n    len = p->len;\n    if (len == 0 || n == 1)\n        return str;\n    if (val * len > JS_STRING_LEN_MAX) {\n        JS_ThrowInternalError(ctx, \"string too long\");\n        goto fail;\n    }\n    if (string_buffer_init2(ctx, b, n * len, p->is_wide_char))\n        goto fail;\n    if (len == 1) {\n        string_buffer_fill(b, string_get(p, 0), n);\n    } else {\n        while (n-- > 0) {\n            string_buffer_concat(b, p, 0, len);\n        }\n    }\n    JS_FreeValue(ctx, str);\n    return string_buffer_end(b);\n\nfail:\n    JS_FreeValue(ctx, str);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_string_trim(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int magic)\n{\n    JSValue str, ret;\n    int a, b, len;\n    JSString *p;\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        return str;\n    p = JS_VALUE_GET_STRING(str);\n    a = 0;\n    b = len = p->len;\n    if (magic & 1) {\n        while (a < len && lre_is_space(string_get(p, a)))\n            a++;\n    }\n    if (magic & 2) {\n        while (b > a && lre_is_space(string_get(p, b - 1)))\n            b--;\n    }\n    ret = js_sub_string(ctx, p, a, b);\n    JS_FreeValue(ctx, str);\n    return ret;\n}\n\nstatic JSValue js_string___quote(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    return JS_ToQuotedString(ctx, this_val);\n}\n\n/* return 0 if before the first char */\nstatic int string_prevc(JSString *p, int *pidx)\n{\n    int idx, c, c1;\n\n    idx = *pidx;\n    if (idx <= 0)\n        return 0;\n    idx--;\n    if (p->is_wide_char) {\n        c = p->u.str16[idx];\n        if (c >= 0xdc00 && c < 0xe000 && idx > 0) {\n            c1 = p->u.str16[idx - 1];\n            if (c1 >= 0xd800 && c1 <= 0xdc00) {\n                c = (((c1 & 0x3ff) << 10) | (c & 0x3ff)) + 0x10000;\n                idx--;\n            }\n        }\n    } else {\n        c = p->u.str8[idx];\n    }\n    *pidx = idx;\n    return c;\n}\n\nstatic BOOL test_final_sigma(JSString *p, int sigma_pos)\n{\n    int k, c1;\n\n    /* before C: skip case ignorable chars and check there is\n       a cased letter */\n    k = sigma_pos;\n    for(;;) {\n        c1 = string_prevc(p, &k);\n        if (!lre_is_case_ignorable(c1))\n            break;\n    }\n    if (!lre_is_cased(c1))\n        return FALSE;\n\n    /* after C: skip case ignorable chars and check there is\n       no cased letter */\n    k = sigma_pos + 1;\n    for(;;) {\n        if (k >= p->len)\n            return TRUE;\n        c1 = string_getc(p, &k);\n        if (!lre_is_case_ignorable(c1))\n            break;\n    }\n    return !lre_is_cased(c1);\n}\n\nstatic JSValue js_string_localeCompare(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    JSValue a, b;\n    int cmp;\n\n    a = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(a))\n        return JS_EXCEPTION;\n    b = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(b)) {\n        JS_FreeValue(ctx, a);\n        return JS_EXCEPTION;\n    }\n    cmp = js_string_compare(ctx, JS_VALUE_GET_STRING(a), JS_VALUE_GET_STRING(b));\n    JS_FreeValue(ctx, a);\n    JS_FreeValue(ctx, b);\n    return JS_NewInt32(ctx, cmp);\n}\n\nstatic JSValue js_string_toLowerCase(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv, int to_lower)\n{\n    JSValue val;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p;\n    int i, c, j, l;\n    uint32_t res[LRE_CC_RES_LEN_MAX];\n\n    val = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    p = JS_VALUE_GET_STRING(val);\n    if (p->len == 0)\n        return val;\n    if (string_buffer_init(ctx, b, p->len))\n        goto fail;\n    for(i = 0; i < p->len;) {\n        c = string_getc(p, &i);\n        if (c == 0x3a3 && to_lower && test_final_sigma(p, i - 1)) {\n            res[0] = 0x3c2; /* final sigma */\n            l = 1;\n        } else {\n            l = lre_case_conv(res, c, to_lower);\n        }\n        for(j = 0; j < l; j++) {\n            if (string_buffer_putc(b, res[j]))\n                goto fail;\n        }\n    }\n    JS_FreeValue(ctx, val);\n    return string_buffer_end(b);\n fail:\n    JS_FreeValue(ctx, val);\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\n#ifdef CONFIG_ALL_UNICODE\n\n/* return (-1, NULL) if exception, otherwise (len, buf) */\nstatic int JS_ToUTF32String(JSContext *ctx, uint32_t **pbuf, JSValueConst val1)\n{\n    JSValue val;\n    JSString *p;\n    uint32_t *buf;\n    int i, j, len;\n\n    val = JS_ToString(ctx, val1);\n    if (JS_IsException(val))\n        return -1;\n    p = JS_VALUE_GET_STRING(val);\n    len = p->len;\n    /* UTF32 buffer length is len minus the number of correct surrogates pairs */\n    buf = js_malloc(ctx, sizeof(buf[0]) * max_int(len, 1));\n    if (!buf) {\n        JS_FreeValue(ctx, val);\n        goto fail;\n    }\n    for(i = j = 0; i < len;)\n        buf[j++] = string_getc(p, &i);\n    JS_FreeValue(ctx, val);\n    *pbuf = buf;\n    return j;\n fail:\n    *pbuf = NULL;\n    return -1;\n}\n\nstatic JSValue JS_NewUTF32String(JSContext *ctx, const uint32_t *buf, int len)\n{\n    int i;\n    StringBuffer b_s, *b = &b_s;\n    if (string_buffer_init(ctx, b, len))\n        return JS_EXCEPTION;\n    for(i = 0; i < len; i++) {\n        if (string_buffer_putc(b, buf[i]))\n            goto fail;\n    }\n    return string_buffer_end(b);\n fail:\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_string_normalize(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    const char *form, *p;\n    size_t form_len;\n    int is_compat, buf_len, out_len;\n    UnicodeNormalizationEnum n_type;\n    JSValue val;\n    uint32_t *buf, *out_buf;\n\n    val = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    buf_len = JS_ToUTF32String(ctx, &buf, val);\n    JS_FreeValue(ctx, val);\n    if (buf_len < 0)\n        return JS_EXCEPTION;\n\n    if (argc == 0 || JS_IsUndefined(argv[0])) {\n        n_type = UNICODE_NFC;\n    } else {\n        form = JS_ToCStringLen(ctx, &form_len, argv[0]);\n        if (!form)\n            goto fail1;\n        p = form;\n        if (p[0] != 'N' || p[1] != 'F')\n            goto bad_form;\n        p += 2;\n        is_compat = FALSE;\n        if (*p == 'K') {\n            is_compat = TRUE;\n            p++;\n        }\n        if (*p == 'C' || *p == 'D') {\n            n_type = UNICODE_NFC + is_compat * 2 + (*p - 'C');\n            if ((p + 1 - form) != form_len)\n                goto bad_form;\n        } else {\n        bad_form:\n            JS_FreeCString(ctx, form);\n            JS_ThrowRangeError(ctx, \"bad normalization form\");\n        fail1:\n            js_free(ctx, buf);\n            return JS_EXCEPTION;\n        }\n        JS_FreeCString(ctx, form);\n    }\n\n    out_len = unicode_normalize(&out_buf, buf, buf_len, n_type,\n                                ctx->rt, (DynBufReallocFunc *)js_realloc_rt);\n    js_free(ctx, buf);\n    if (out_len < 0)\n        return JS_EXCEPTION;\n    val = JS_NewUTF32String(ctx, out_buf, out_len);\n    js_free(ctx, out_buf);\n    return val;\n}\n#endif /* CONFIG_ALL_UNICODE */\n\n/* also used for String.prototype.valueOf */\nstatic JSValue js_string_toString(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    return js_thisStringValue(ctx, this_val);\n}\n\n#if 0\nstatic JSValue js_string___toStringCheckObject(JSContext *ctx, JSValueConst this_val,\n                                               int argc, JSValueConst *argv)\n{\n    return JS_ToStringCheckObject(ctx, argv[0]);\n}\n\nstatic JSValue js_string___toString(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    return JS_ToString(ctx, argv[0]);\n}\n\nstatic JSValue js_string___advanceStringIndex(JSContext *ctx, JSValueConst\n                                              this_val,\n                                              int argc, JSValueConst *argv)\n{\n    JSValue str;\n    int idx;\n    BOOL is_unicode;\n    JSString *p;\n\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        return str;\n    if (JS_ToInt32Sat(ctx, &idx, argv[1])) {\n        JS_FreeValue(ctx, str);\n        return JS_EXCEPTION;\n    }\n    is_unicode = JS_ToBool(ctx, argv[2]);\n    p = JS_VALUE_GET_STRING(str);\n    if (!is_unicode || (unsigned)idx >= p->len || !p->is_wide_char) {\n        idx++;\n    } else {\n        string_getc(p, &idx);\n    }\n    JS_FreeValue(ctx, str);\n    return JS_NewInt32(ctx, idx);\n}\n#endif\n\n/* String Iterator */\n\nstatic JSValue js_string_iterator_next(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv,\n                                       BOOL *pdone, int magic)\n{\n    JSArrayIteratorData *it;\n    uint32_t idx, c, start;\n    JSString *p;\n\n    it = JS_GetOpaque2(ctx, this_val, JS_CLASS_STRING_ITERATOR);\n    if (!it) {\n        *pdone = FALSE;\n        return JS_EXCEPTION;\n    }\n    if (JS_IsUndefined(it->obj))\n        goto done;\n    p = JS_VALUE_GET_STRING(it->obj);\n    idx = it->idx;\n    if (idx >= p->len) {\n        JS_FreeValue(ctx, it->obj);\n        it->obj = JS_UNDEFINED;\n    done:\n        *pdone = TRUE;\n        return JS_UNDEFINED;\n    }\n\n    start = idx;\n    c = string_getc(p, (int *)&idx);\n    it->idx = idx;\n    *pdone = FALSE;\n    if (c <= 0xffff) {\n        return js_new_string_char(ctx, c);\n    } else {\n        return js_new_string16(ctx, p->u.str16 + start, 2);\n    }\n}\n\n/* ES6 Annex B 2.3.2 etc. */\nenum {\n    magic_string_anchor,\n    magic_string_big,\n    magic_string_blink,\n    magic_string_bold,\n    magic_string_fixed,\n    magic_string_fontcolor,\n    magic_string_fontsize,\n    magic_string_italics,\n    magic_string_link,\n    magic_string_small,\n    magic_string_strike,\n    magic_string_sub,\n    magic_string_sup,\n};\n\nstatic JSValue js_string_CreateHTML(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv, int magic)\n{\n    JSValue str;\n    const JSString *p;\n    StringBuffer b_s, *b = &b_s;\n    static struct { const char *tag, *attr; } const defs[] = {\n        { \"a\", \"name\" }, { \"big\", NULL }, { \"blink\", NULL }, { \"b\", NULL },\n        { \"tt\", NULL }, { \"font\", \"color\" }, { \"font\", \"size\" }, { \"i\", NULL },\n        { \"a\", \"href\" }, { \"small\", NULL }, { \"strike\", NULL }, \n        { \"sub\", NULL }, { \"sup\", NULL },\n    };\n\n    str = JS_ToStringCheckObject(ctx, this_val);\n    if (JS_IsException(str))\n        return JS_EXCEPTION;\n    string_buffer_init(ctx, b, 7);\n    string_buffer_putc8(b, '<');\n    string_buffer_puts8(b, defs[magic].tag);\n    if (defs[magic].attr) {\n        // r += \" \" + attr + \"=\\\"\" + value + \"\\\"\";\n        JSValue value;\n        int i;\n\n        string_buffer_putc8(b, ' ');\n        string_buffer_puts8(b, defs[magic].attr);\n        string_buffer_puts8(b, \"=\\\"\");\n        value = JS_ToStringCheckObject(ctx, argv[0]);\n        if (JS_IsException(value)) {\n            JS_FreeValue(ctx, str);\n            string_buffer_free(b);\n            return JS_EXCEPTION;\n        }\n        p = JS_VALUE_GET_STRING(value);\n        for (i = 0; i < p->len; i++) {\n            int c = string_get(p, i);\n            if (c == '\"') {\n                string_buffer_puts8(b, \"&quot;\");\n            } else {\n                string_buffer_putc16(b, c);\n            }\n        }\n        JS_FreeValue(ctx, value);\n        string_buffer_putc8(b, '\\\"');\n    }\n    // return r + \">\" + str + \"</\" + tag + \">\";\n    string_buffer_putc8(b, '>');\n    string_buffer_concat_value_free(b, str);\n    string_buffer_puts8(b, \"</\");\n    string_buffer_puts8(b, defs[magic].tag);\n    string_buffer_putc8(b, '>');\n    return string_buffer_end(b);\n}\n\nstatic const JSCFunctionListEntry js_string_funcs[] = {\n    JS_CFUNC_DEF(\"fromCharCode\", 1, js_string_fromCharCode ),\n    JS_CFUNC_DEF(\"fromCodePoint\", 1, js_string_fromCodePoint ),\n    JS_CFUNC_DEF(\"raw\", 1, js_string_raw ),\n    //JS_CFUNC_DEF(\"__toString\", 1, js_string___toString ),\n    //JS_CFUNC_DEF(\"__isSpace\", 1, js_string___isSpace ),\n    //JS_CFUNC_DEF(\"__toStringCheckObject\", 1, js_string___toStringCheckObject ),\n    //JS_CFUNC_DEF(\"__advanceStringIndex\", 3, js_string___advanceStringIndex ),\n    //JS_CFUNC_DEF(\"__GetSubstitution\", 6, js_string___GetSubstitution ),\n};\n\nstatic const JSCFunctionListEntry js_string_proto_funcs[] = {\n    JS_PROP_INT32_DEF(\"length\", 0, JS_PROP_CONFIGURABLE ),\n    JS_CFUNC_DEF(\"charCodeAt\", 1, js_string_charCodeAt ),\n    JS_CFUNC_DEF(\"charAt\", 1, js_string_charAt ),\n    JS_CFUNC_DEF(\"concat\", 1, js_string_concat ),\n    JS_CFUNC_DEF(\"codePointAt\", 1, js_string_codePointAt ),\n    JS_CFUNC_MAGIC_DEF(\"indexOf\", 1, js_string_indexOf, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"lastIndexOf\", 1, js_string_indexOf, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"includes\", 1, js_string_includes, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"endsWith\", 1, js_string_includes, 2 ),\n    JS_CFUNC_MAGIC_DEF(\"startsWith\", 1, js_string_includes, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"match\", 1, js_string_match, JS_ATOM_Symbol_match ),\n    JS_CFUNC_MAGIC_DEF(\"matchAll\", 1, js_string_match, JS_ATOM_Symbol_matchAll ),\n    JS_CFUNC_MAGIC_DEF(\"search\", 1, js_string_match, JS_ATOM_Symbol_search ),\n    JS_CFUNC_DEF(\"split\", 2, js_string_split ),\n    JS_CFUNC_DEF(\"substring\", 2, js_string_substring ),\n    JS_CFUNC_DEF(\"substr\", 2, js_string_substr ),\n    JS_CFUNC_DEF(\"slice\", 2, js_string_slice ),\n    JS_CFUNC_DEF(\"repeat\", 1, js_string_repeat ),\n    JS_CFUNC_MAGIC_DEF(\"replace\", 2, js_string_replace, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"replaceAll\", 2, js_string_replace, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"padEnd\", 1, js_string_pad, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"padStart\", 1, js_string_pad, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"trim\", 0, js_string_trim, 3 ),\n    JS_CFUNC_MAGIC_DEF(\"trimEnd\", 0, js_string_trim, 2 ),\n    JS_ALIAS_DEF(\"trimRight\", \"trimEnd\" ),\n    JS_CFUNC_MAGIC_DEF(\"trimStart\", 0, js_string_trim, 1 ),\n    JS_ALIAS_DEF(\"trimLeft\", \"trimStart\" ),\n    JS_CFUNC_DEF(\"toString\", 0, js_string_toString ),\n    JS_CFUNC_DEF(\"valueOf\", 0, js_string_toString ),\n    JS_CFUNC_DEF(\"__quote\", 1, js_string___quote ),\n    JS_CFUNC_DEF(\"localeCompare\", 1, js_string_localeCompare ),\n    JS_CFUNC_MAGIC_DEF(\"toLowerCase\", 0, js_string_toLowerCase, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"toUpperCase\", 0, js_string_toLowerCase, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"toLocaleLowerCase\", 0, js_string_toLowerCase, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"toLocaleUpperCase\", 0, js_string_toLowerCase, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"[Symbol.iterator]\", 0, js_create_array_iterator, JS_ITERATOR_KIND_VALUE | 4 ),\n    /* ES6 Annex B 2.3.2 etc. */\n    JS_CFUNC_MAGIC_DEF(\"anchor\", 1, js_string_CreateHTML, magic_string_anchor ),\n    JS_CFUNC_MAGIC_DEF(\"big\", 0, js_string_CreateHTML, magic_string_big ),\n    JS_CFUNC_MAGIC_DEF(\"blink\", 0, js_string_CreateHTML, magic_string_blink ),\n    JS_CFUNC_MAGIC_DEF(\"bold\", 0, js_string_CreateHTML, magic_string_bold ),\n    JS_CFUNC_MAGIC_DEF(\"fixed\", 0, js_string_CreateHTML, magic_string_fixed ),\n    JS_CFUNC_MAGIC_DEF(\"fontcolor\", 1, js_string_CreateHTML, magic_string_fontcolor ),\n    JS_CFUNC_MAGIC_DEF(\"fontsize\", 1, js_string_CreateHTML, magic_string_fontsize ),\n    JS_CFUNC_MAGIC_DEF(\"italics\", 0, js_string_CreateHTML, magic_string_italics ),\n    JS_CFUNC_MAGIC_DEF(\"link\", 1, js_string_CreateHTML, magic_string_link ),\n    JS_CFUNC_MAGIC_DEF(\"small\", 0, js_string_CreateHTML, magic_string_small ),\n    JS_CFUNC_MAGIC_DEF(\"strike\", 0, js_string_CreateHTML, magic_string_strike ),\n    JS_CFUNC_MAGIC_DEF(\"sub\", 0, js_string_CreateHTML, magic_string_sub ),\n    JS_CFUNC_MAGIC_DEF(\"sup\", 0, js_string_CreateHTML, magic_string_sup ),\n};\n\nstatic const JSCFunctionListEntry js_string_iterator_proto_funcs[] = {\n    JS_ITERATOR_NEXT_DEF(\"next\", 0, js_string_iterator_next, 0 ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"String Iterator\", JS_PROP_CONFIGURABLE ),\n};\n\n#ifdef CONFIG_ALL_UNICODE\nstatic const JSCFunctionListEntry js_string_proto_normalize[] = {\n    JS_CFUNC_DEF(\"normalize\", 0, js_string_normalize ),\n};\n#endif\n\nvoid JS_AddIntrinsicStringNormalize(JSContext *ctx)\n{\n#ifdef CONFIG_ALL_UNICODE\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_STRING], js_string_proto_normalize,\n                               countof(js_string_proto_normalize));\n#endif\n}\n\n/* Math */\n\n/* precondition: a and b are not NaN */\nstatic double js_fmin(double a, double b)\n{\n    if (a == 0 && b == 0) {\n        JSFloat64Union a1, b1;\n        a1.d = a;\n        b1.d = b;\n        a1.u64 |= b1.u64;\n        return a1.d;\n    } else {\n        return fmin(a, b);\n    }\n}\n\n/* precondition: a and b are not NaN */\nstatic double js_fmax(double a, double b)\n{\n    if (a == 0 && b == 0) {\n        JSFloat64Union a1, b1;\n        a1.d = a;\n        b1.d = b;\n        a1.u64 &= b1.u64;\n        return a1.d;\n    } else {\n        return fmax(a, b);\n    }\n}\n\nstatic JSValue js_math_min_max(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv, int magic)\n{\n    BOOL is_max = magic;\n    double r, a;\n    int i;\n    uint32_t tag;\n\n    if (unlikely(argc == 0)) {\n#ifdef _MSC_VER\n        return __JS_NewFloat64(ctx, is_max ? -INFINITY : INFINITY);\n#else\n        return __JS_NewFloat64(ctx, is_max ? -1.0 / 0.0 : 1.0 / 0.0);\n#endif\n    }\n\n    tag = JS_VALUE_GET_TAG(argv[0]);\n    if (tag == JS_TAG_INT) {\n        int a1, r1 = JS_VALUE_GET_INT(argv[0]);\n        for(i = 1; i < argc; i++) {\n            tag = JS_VALUE_GET_TAG(argv[i]);\n            if (tag != JS_TAG_INT) {\n                r = r1;\n                goto generic_case;\n            }\n            a1 = JS_VALUE_GET_INT(argv[i]);\n            if (is_max)\n                r1 = max_int(r1, a1);\n            else\n                r1 = min_int(r1, a1);\n\n        }\n        return JS_NewInt32(ctx, r1);\n    } else {\n        if (JS_ToFloat64(ctx, &r, argv[0]))\n            return JS_EXCEPTION;\n        i = 1;\n    generic_case:\n        while (i < argc) {\n            if (JS_ToFloat64(ctx, &a, argv[i]))\n                return JS_EXCEPTION;\n            if (!isnan(r)) {\n                if (isnan(a)) {\n                    r = a;\n                } else {\n                    if (is_max)\n                        r = js_fmax(r, a);\n                    else\n                        r = js_fmin(r, a);\n                }\n            }\n            i++;\n        }\n        return JS_NewFloat64(ctx, r);\n    }\n}\n\nstatic double js_math_sign(double a)\n{\n    if (isnan(a) || a == 0.0)\n        return a;\n    if (a < 0)\n        return -1;\n    else\n        return 1;\n}\n\nstatic double js_math_round(double a)\n{\n    JSFloat64Union u;\n    uint64_t frac_mask, one;\n    unsigned int e, s;\n\n    u.d = a;\n    e = (u.u64 >> 52) & 0x7ff;\n    if (e < 1023) {\n        /* abs(a) < 1 */\n        if (e == (1023 - 1) && u.u64 != 0xbfe0000000000000) {\n            /* abs(a) > 0.5 or a = 0.5: return +/-1.0 */\n            u.u64 = (u.u64 & ((uint64_t)1 << 63)) | ((uint64_t)1023 << 52);\n        } else {\n            /* return +/-0.0 */\n            u.u64 &= (uint64_t)1 << 63;\n        }\n    } else if (e < (1023 + 52)) {\n        s = u.u64 >> 63;\n        one = (uint64_t)1 << (52 - (e - 1023));\n        frac_mask = one - 1;\n        u.u64 += (one >> 1) - s;\n        u.u64 &= ~frac_mask; /* truncate to an integer */\n    }\n    /* otherwise: abs(a) >= 2^52, or NaN, +/-Infinity: no change */\n    return u.d;\n}\n\nstatic JSValue js_math_hypot(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    double r, a;\n    int i;\n\n    r = 0;\n    if (argc > 0) {\n        if (JS_ToFloat64(ctx, &r, argv[0]))\n            return JS_EXCEPTION;\n        if (argc == 1) {\n            r = fabs(r);\n        } else {\n            /* use the built-in function to minimize precision loss */\n            for (i = 1; i < argc; i++) {\n                if (JS_ToFloat64(ctx, &a, argv[i]))\n                    return JS_EXCEPTION;\n                r = hypot(r, a);\n            }\n        }\n    }\n    return JS_NewFloat64(ctx, r);\n}\n\nstatic double js_math_fround(double a)\n{\n    return (float)a;\n}\n\nstatic JSValue js_math_imul(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv)\n{\n    int a, b;\n\n    if (JS_ToInt32(ctx, &a, argv[0]))\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &b, argv[1]))\n        return JS_EXCEPTION;\n    /* purposely ignoring overflow */\n    return JS_NewInt32(ctx, a * b);\n}\n\nstatic JSValue js_math_clz32(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    uint32_t a, r;\n\n    if (JS_ToUint32(ctx, &a, argv[0]))\n        return JS_EXCEPTION;\n    if (a == 0)\n        r = 32;\n    else\n        r = clz32(a);\n    return JS_NewInt32(ctx, r);\n}\n\n/* xorshift* random number generator by Marsaglia */\nstatic uint64_t xorshift64star(uint64_t *pstate)\n{\n    uint64_t x;\n    x = *pstate;\n    x ^= x >> 12;\n    x ^= x << 25;\n    x ^= x >> 27;\n    *pstate = x;\n    return x * 0x2545F4914F6CDD1D;\n}\n\nstatic void js_random_init(JSContext *ctx)\n{\n    struct timeval tv;\n    gettimeofday(&tv, NULL);\n    ctx->random_state = ((int64_t)tv.tv_sec * 1000000) + tv.tv_usec;\n    /* the state must be non zero */\n    if (ctx->random_state == 0)\n        ctx->random_state = 1;\n}\n\nstatic JSValue js_math_random(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    JSFloat64Union u;\n    uint64_t v;\n\n    v = xorshift64star(&ctx->random_state);\n    /* 1.0 <= u.d < 2 */\n    u.u64 = ((uint64_t)0x3ff << 52) | (v >> 12);\n    return __JS_NewFloat64(ctx, u.d - 1.0);\n}\n\nstatic const JSCFunctionListEntry js_math_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"min\", 2, js_math_min_max, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"max\", 2, js_math_min_max, 1 ),\n    JS_CFUNC_SPECIAL_DEF(\"abs\", 1, f_f, fabs ),\n    //JS_CFUNC_SPECIAL_DEF(\"floor\", 1, f_f, floor ),\n    //JS_CFUNC_SPECIAL_DEF(\"ceil\", 1, f_f, ceil ),\n    JS_CFUNC_SPECIAL_DEF(\"round\", 1, f_f, js_math_round ),\n    JS_CFUNC_SPECIAL_DEF(\"sqrt\", 1, f_f, sqrt ),\n\n    JS_CFUNC_SPECIAL_DEF(\"acos\", 1, f_f, acos ),\n    JS_CFUNC_SPECIAL_DEF(\"asin\", 1, f_f, asin ),\n    JS_CFUNC_SPECIAL_DEF(\"atan\", 1, f_f, atan ),\n    JS_CFUNC_SPECIAL_DEF(\"atan2\", 2, f_f_f, atan2 ),\n    JS_CFUNC_SPECIAL_DEF(\"cos\", 1, f_f, cos ),\n    JS_CFUNC_SPECIAL_DEF(\"exp\", 1, f_f, exp ),\n    JS_CFUNC_SPECIAL_DEF(\"log\", 1, f_f, log ),\n    JS_CFUNC_SPECIAL_DEF(\"pow\", 2, f_f_f, js_pow ),\n    JS_CFUNC_SPECIAL_DEF(\"sin\", 1, f_f, sin ),\n    JS_CFUNC_SPECIAL_DEF(\"tan\", 1, f_f, tan ),\n    /* ES6 */\n    JS_CFUNC_SPECIAL_DEF(\"trunc\", 1, f_f, trunc ),\n    JS_CFUNC_SPECIAL_DEF(\"sign\", 1, f_f, js_math_sign ),\n    JS_CFUNC_SPECIAL_DEF(\"cosh\", 1, f_f, cosh ),\n    JS_CFUNC_SPECIAL_DEF(\"sinh\", 1, f_f, sinh ),\n    JS_CFUNC_SPECIAL_DEF(\"tanh\", 1, f_f, tanh ),\n    JS_CFUNC_SPECIAL_DEF(\"acosh\", 1, f_f, acosh ),\n    JS_CFUNC_SPECIAL_DEF(\"asinh\", 1, f_f, asinh ),\n    JS_CFUNC_SPECIAL_DEF(\"atanh\", 1, f_f, atanh ),\n    JS_CFUNC_SPECIAL_DEF(\"expm1\", 1, f_f, expm1 ),\n    JS_CFUNC_SPECIAL_DEF(\"log1p\", 1, f_f, log1p ),\n    JS_CFUNC_SPECIAL_DEF(\"log2\", 1, f_f, log2 ),\n    JS_CFUNC_SPECIAL_DEF(\"log10\", 1, f_f, log10 ),\n    JS_CFUNC_SPECIAL_DEF(\"cbrt\", 1, f_f, cbrt ),\n    JS_CFUNC_DEF(\"hypot\", 2, js_math_hypot ),\n    JS_CFUNC_DEF(\"random\", 0, js_math_random ),\n    JS_CFUNC_SPECIAL_DEF(\"fround\", 1, f_f, js_math_fround ),\n    JS_CFUNC_DEF(\"imul\", 2, js_math_imul ),\n    JS_CFUNC_DEF(\"clz32\", 1, js_math_clz32 ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Math\", JS_PROP_CONFIGURABLE ),\n    JS_PROP_DOUBLE_DEF(\"E\", 2.718281828459045, 0 ),\n    JS_PROP_DOUBLE_DEF(\"LN10\", 2.302585092994046, 0 ),\n    JS_PROP_DOUBLE_DEF(\"LN2\", 0.6931471805599453, 0 ),\n    JS_PROP_DOUBLE_DEF(\"LOG2E\", 1.4426950408889634, 0 ),\n    JS_PROP_DOUBLE_DEF(\"LOG10E\", 0.4342944819032518, 0 ),\n    JS_PROP_DOUBLE_DEF(\"PI\", 3.141592653589793, 0 ),\n    JS_PROP_DOUBLE_DEF(\"SQRT1_2\", 0.7071067811865476, 0 ),\n    JS_PROP_DOUBLE_DEF(\"SQRT2\", 1.4142135623730951, 0 ),\n};\n\nstatic const JSCFunctionListEntry js_math_obj[] = {\n    JS_OBJECT_DEF(\"Math\", js_math_funcs, countof(js_math_funcs), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),\n};\n\n/* Date */\n\n#if 0\n/* OS dependent: return the UTC time in ms since 1970. */\nstatic JSValue js___date_now(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    int64_t d;\n    struct timeval tv;\n    gettimeofday(&tv, NULL);\n    d = (int64_t)tv.tv_sec * 1000 + (tv.tv_usec / 1000);\n    return JS_NewInt64(ctx, d);\n}\n#endif\n\n/* OS dependent: return the UTC time in microseconds since 1970. */\nstatic JSValue js___date_clock(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    int64_t d;\n    struct timeval tv;\n    gettimeofday(&tv, NULL);\n    d = (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;\n    return JS_NewInt64(ctx, d);\n}\n\n/* OS dependent. d = argv[0] is in ms from 1970. Return the difference\n   between UTC time and local time 'd' in minutes */\nstatic int getTimezoneOffset(int64_t time) {\n#if defined(_WIN32)\n    /* XXX: TODO */\n    return 0;\n#else\n    time_t ti;\n    struct tm tm;\n\n    time /= 1000; /* convert to seconds */\n    if (sizeof(time_t) == 4) {\n        /* on 32-bit systems, we need to clamp the time value to the\n           range of `time_t`. This is better than truncating values to\n           32 bits and hopefully provides the same result as 64-bit\n           implementation of localtime_r.\n         */\n        if ((time_t)-1 < 0) {\n            if (time < INT32_MIN) {\n                time = INT32_MIN;\n            } else if (time > INT32_MAX) {\n                time = INT32_MAX;\n            }\n        } else {\n            if (time < 0) {\n                time = 0;\n            } else if (time > UINT32_MAX) {\n                time = UINT32_MAX;\n            }\n        }\n    }\n    ti = time;\n    localtime_r(&ti, &tm);\n    return -tm.tm_gmtoff / 60;\n#endif\n}\n\n#if 0\nstatic JSValue js___date_getTimezoneOffset(JSContext *ctx, JSValueConst this_val,\n                                           int argc, JSValueConst *argv)\n{\n    double dd;\n\n    if (JS_ToFloat64(ctx, &dd, argv[0]))\n        return JS_EXCEPTION;\n    if (isnan(dd))\n        return __JS_NewFloat64(ctx, dd);\n    else\n        return JS_NewInt32(ctx, getTimezoneOffset((int64_t)dd));\n}\n\nstatic JSValue js_get_prototype_from_ctor(JSContext *ctx, JSValueConst ctor,\n                                          JSValueConst def_proto)\n{\n    JSValue proto;\n    proto = JS_GetProperty(ctx, ctor, JS_ATOM_prototype);\n    if (JS_IsException(proto))\n        return proto;\n    if (!JS_IsObject(proto)) {\n        JS_FreeValue(ctx, proto);\n        proto = JS_DupValue(ctx, def_proto);\n    }\n    return proto;\n}\n\n/* create a new date object */\nstatic JSValue js___date_create(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValue obj, proto;\n    proto = js_get_prototype_from_ctor(ctx, argv[0], argv[1]);\n    if (JS_IsException(proto))\n        return proto;\n    obj = JS_NewObjectProtoClass(ctx, proto, JS_CLASS_DATE);\n    JS_FreeValue(ctx, proto);\n    if (!JS_IsException(obj))\n        JS_SetObjectData(ctx, obj, JS_DupValue(ctx, argv[2]));\n    return obj;\n}\n#endif\n\n/* RegExp */\n\nstatic void js_regexp_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSRegExp *re = &p->u.regexp;\n    JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_STRING, re->bytecode));\n    JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_STRING, re->pattern));\n}\n\n/* create a string containing the RegExp bytecode */\nstatic JSValue js_compile_regexp(JSContext *ctx, JSValueConst pattern,\n                                 JSValueConst flags)\n{\n    const char *str;\n    int re_flags, mask;\n    uint8_t *re_bytecode_buf;\n    size_t i, len;\n    int re_bytecode_len;\n    JSValue ret;\n    char error_msg[64];\n\n    re_flags = 0;\n    if (!JS_IsUndefined(flags)) {\n        str = JS_ToCStringLen(ctx, &len, flags);\n        if (!str)\n            return JS_EXCEPTION;\n        /* XXX: re_flags = LRE_FLAG_OCTAL unless strict mode? */\n        for (i = 0; i < len; i++) {\n            switch(str[i]) {\n            case 'g':\n                mask = LRE_FLAG_GLOBAL;\n                break;\n            case 'i':\n                mask = LRE_FLAG_IGNORECASE;\n                break;\n            case 'm':\n                mask = LRE_FLAG_MULTILINE;\n                break;\n            case 's':\n                mask = LRE_FLAG_DOTALL;\n                break;\n            case 'u':\n                mask = LRE_FLAG_UTF16;\n                break;\n            case 'y':\n                mask = LRE_FLAG_STICKY;\n                break;\n            default:\n                goto bad_flags;\n            }\n            if ((re_flags & mask) != 0) {\n            bad_flags:\n                JS_FreeCString(ctx, str);\n                return JS_ThrowSyntaxError(ctx, \"invalid regular expression flags\");\n            }\n            re_flags |= mask;\n        }\n        JS_FreeCString(ctx, str);\n    }\n\n    str = JS_ToCStringLen2(ctx, &len, pattern, !(re_flags & LRE_FLAG_UTF16));\n    if (!str)\n        return JS_EXCEPTION;\n    re_bytecode_buf = lre_compile(&re_bytecode_len, error_msg,\n                                  sizeof(error_msg), str, len, re_flags, ctx);\n    JS_FreeCString(ctx, str);\n    if (!re_bytecode_buf) {\n        JS_ThrowSyntaxError(ctx, \"%s\", error_msg);\n        return JS_EXCEPTION;\n    }\n\n    ret = js_new_string8(ctx, re_bytecode_buf, re_bytecode_len);\n    js_free(ctx, re_bytecode_buf);\n    return ret;\n}\n\n/* create a RegExp object from a string containing the RegExp bytecode\n   and the source pattern */\nstatic JSValue js_regexp_constructor_internal(JSContext *ctx, JSValueConst ctor,\n                                              JSValue pattern, JSValue bc)\n{\n    JSValue obj;\n    JSObject *p;\n    JSRegExp *re;\n\n    /* sanity check */\n    if (JS_VALUE_GET_TAG(bc) != JS_TAG_STRING ||\n        JS_VALUE_GET_TAG(pattern) != JS_TAG_STRING) {\n        JS_ThrowTypeError(ctx, \"string expected\");\n    fail:\n        JS_FreeValue(ctx, bc);\n        JS_FreeValue(ctx, pattern);\n        return JS_EXCEPTION;\n    }\n\n    obj = js_create_from_ctor(ctx, ctor, JS_CLASS_REGEXP);\n    if (JS_IsException(obj))\n        goto fail;\n    p = JS_VALUE_GET_OBJ(obj);\n    re = &p->u.regexp;\n    re->pattern = JS_VALUE_GET_STRING(pattern);\n    re->bytecode = JS_VALUE_GET_STRING(bc);\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_lastIndex, JS_NewInt32(ctx, 0),\n                           JS_PROP_WRITABLE);\n    return obj;\n}\n\nstatic JSRegExp *js_get_regexp(JSContext *ctx, JSValueConst obj, BOOL throw_error)\n{\n    if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(obj);\n        if (p->class_id == JS_CLASS_REGEXP)\n            return &p->u.regexp;\n    }\n    if (throw_error) {\n        JS_ThrowTypeErrorInvalidClass(ctx, JS_CLASS_REGEXP);\n    }\n    return NULL;\n}\n\n/* return < 0 if exception or TRUE/FALSE */\nstatic int js_is_regexp(JSContext *ctx, JSValueConst obj)\n{\n    JSValue m;\n\n    if (!JS_IsObject(obj))\n        return FALSE;\n    m = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_match);\n    if (JS_IsException(m))\n        return -1;\n    if (!JS_IsUndefined(m))\n        return JS_ToBoolFree(ctx, m);\n    return js_get_regexp(ctx, obj, FALSE) != NULL;\n}\n\nstatic JSValue js_regexp_constructor(JSContext *ctx, JSValueConst new_target,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue pattern, flags, bc, val;\n    JSValueConst pat, flags1;\n    JSRegExp *re;\n    int pat_is_regexp;\n\n    pat = argv[0];\n    flags1 = argv[1];\n    pat_is_regexp = js_is_regexp(ctx, pat);\n    if (pat_is_regexp < 0)\n        return JS_EXCEPTION;\n    if (JS_IsUndefined(new_target)) {\n        /* called as a function */\n        new_target = JS_GetActiveFunction(ctx);\n        if (pat_is_regexp && JS_IsUndefined(flags1)) {\n            JSValue ctor;\n            BOOL res;\n            ctor = JS_GetProperty(ctx, pat, JS_ATOM_constructor);\n            if (JS_IsException(ctor))\n                return ctor;\n            res = js_same_value(ctx, ctor, new_target);\n            JS_FreeValue(ctx, ctor);\n            if (res)\n                return JS_DupValue(ctx, pat);\n        }\n    }\n    re = js_get_regexp(ctx, pat, FALSE);\n    if (re) {\n        pattern = JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, re->pattern));\n        if (JS_IsUndefined(flags1)) {\n            bc = JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, re->bytecode));\n            goto no_compilation;\n        } else {\n            flags = JS_ToString(ctx, flags1);\n            if (JS_IsException(flags))\n                goto fail;\n        }\n    } else {\n        flags = JS_UNDEFINED;\n        if (pat_is_regexp) {\n            pattern = JS_GetProperty(ctx, pat, JS_ATOM_source);\n            if (JS_IsException(pattern))\n                goto fail;\n            if (JS_IsUndefined(flags1)) {\n                flags = JS_GetProperty(ctx, pat, JS_ATOM_flags);\n                if (JS_IsException(flags))\n                    goto fail;\n            } else {\n                flags = JS_DupValue(ctx, flags1);\n            }\n        } else {\n            pattern = JS_DupValue(ctx, pat);\n            flags = JS_DupValue(ctx, flags1);\n        }\n        if (JS_IsUndefined(pattern)) {\n            pattern = JS_AtomToString(ctx, JS_ATOM_empty_string);\n        } else {\n            val = pattern;\n            pattern = JS_ToString(ctx, val);\n            JS_FreeValue(ctx, val);\n            if (JS_IsException(pattern))\n                goto fail;\n        }\n    }\n    bc = js_compile_regexp(ctx, pattern, flags);\n    if (JS_IsException(bc))\n        goto fail;\n    JS_FreeValue(ctx, flags);\n no_compilation:\n    return js_regexp_constructor_internal(ctx, new_target, pattern, bc);\n fail:\n    JS_FreeValue(ctx, pattern);\n    JS_FreeValue(ctx, flags);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_regexp_compile(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSRegExp *re1, *re;\n    JSValueConst pattern1, flags1;\n    JSValue bc, pattern;\n\n    re = js_get_regexp(ctx, this_val, TRUE);\n    if (!re)\n        return JS_EXCEPTION;\n    pattern1 = argv[0];\n    flags1 = argv[1];\n    re1 = js_get_regexp(ctx, pattern1, FALSE);\n    if (re1) {\n        if (!JS_IsUndefined(flags1))\n            return JS_ThrowTypeError(ctx, \"flags must be undefined\");\n        pattern = JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, re1->pattern));\n        bc = JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, re1->bytecode));\n    } else {\n        bc = JS_UNDEFINED;\n        if (JS_IsUndefined(pattern1))\n            pattern = JS_AtomToString(ctx, JS_ATOM_empty_string);\n        else\n            pattern = JS_ToString(ctx, pattern1);\n        if (JS_IsException(pattern))\n            goto fail;\n        bc = js_compile_regexp(ctx, pattern, flags1);\n        if (JS_IsException(bc))\n            goto fail;\n    }\n    JS_FreeValue(ctx, JS_MKPTR(JS_TAG_STRING, re->pattern));\n    JS_FreeValue(ctx, JS_MKPTR(JS_TAG_STRING, re->bytecode));\n    re->pattern = JS_VALUE_GET_STRING(pattern);\n    re->bytecode = JS_VALUE_GET_STRING(bc);\n    if (JS_SetProperty(ctx, this_val, JS_ATOM_lastIndex,\n                       JS_NewInt32(ctx, 0)) < 0)\n        return JS_EXCEPTION;\n    return JS_DupValue(ctx, this_val);\n fail:\n    JS_FreeValue(ctx, pattern);\n    JS_FreeValue(ctx, bc);\n    return JS_EXCEPTION;\n}\n\n#if 0\nstatic JSValue js_regexp_get___source(JSContext *ctx, JSValueConst this_val)\n{\n    JSRegExp *re = js_get_regexp(ctx, this_val, TRUE);\n    if (!re)\n        return JS_EXCEPTION;\n    return JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, re->pattern));\n}\n\nstatic JSValue js_regexp_get___flags(JSContext *ctx, JSValueConst this_val)\n{\n    JSRegExp *re = js_get_regexp(ctx, this_val, TRUE);\n    int flags;\n\n    if (!re)\n        return JS_EXCEPTION;\n    flags = lre_get_flags(re->bytecode->u.str8);\n    return JS_NewInt32(ctx, flags);\n}\n#endif\n\nstatic JSValue js_regexp_get_source(JSContext *ctx, JSValueConst this_val)\n{\n    JSRegExp *re;\n    JSString *p;\n    StringBuffer b_s, *b = &b_s;\n    int i, n, c, c2, bra;\n\n    if (JS_VALUE_GET_TAG(this_val) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    if (js_same_value(ctx, this_val, ctx->class_proto[JS_CLASS_REGEXP]))\n        goto empty_regex;\n\n    re = js_get_regexp(ctx, this_val, TRUE);\n    if (!re)\n        return JS_EXCEPTION;\n\n    p = re->pattern;\n\n    if (p->len == 0) {\n    empty_regex:\n        return JS_NewString(ctx, \"(?:)\");\n    }    \n    string_buffer_init2(ctx, b, p->len, p->is_wide_char);\n\n    /* Escape '/' and newline sequences as needed */\n    bra = 0;\n    for (i = 0, n = p->len; i < n;) {\n        c2 = -1;\n        switch (c = string_get(p, i++)) {\n        case '\\\\':\n            if (i < n)\n                c2 = string_get(p, i++);\n            break;\n        case ']':\n            bra = 0;\n            break;\n        case '[':\n            if (!bra) {\n                if (i < n && string_get(p, i) == ']')\n                    c2 = string_get(p, i++);\n                bra = 1;\n            }\n            break;\n        case '\\n':\n            c = '\\\\';\n            c2 = 'n';\n            break;\n        case '\\r':\n            c = '\\\\';\n            c2 = 'r';\n            break;\n        case '/':\n            if (!bra) {\n                c = '\\\\';\n                c2 = '/';\n            }\n            break;\n        }\n        string_buffer_putc16(b, c);\n        if (c2 >= 0)\n            string_buffer_putc16(b, c2);\n    }\n    return string_buffer_end(b);\n}\n\nstatic JSValue js_regexp_get_flag(JSContext *ctx, JSValueConst this_val, int mask)\n{\n    JSRegExp *re;\n    int flags;\n\n    if (JS_VALUE_GET_TAG(this_val) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    re = js_get_regexp(ctx, this_val, FALSE);\n    if (!re) {\n        if (js_same_value(ctx, this_val, ctx->class_proto[JS_CLASS_REGEXP]))\n            return JS_UNDEFINED;\n        else\n            return JS_ThrowTypeErrorInvalidClass(ctx, JS_CLASS_REGEXP);\n    }\n    \n    flags = lre_get_flags(re->bytecode->u.str8);\n    return JS_NewBool(ctx, (flags & mask) != 0);\n}\n\nstatic JSValue js_regexp_get_flags(JSContext *ctx, JSValueConst this_val)\n{\n    char str[8], *p = str;\n    int res;\n\n    if (JS_VALUE_GET_TAG(this_val) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    res = JS_ToBoolFree(ctx, JS_GetProperty(ctx, this_val, JS_ATOM_global));\n    if (res < 0)\n        goto exception;\n    if (res)\n        *p++ = 'g';\n    res = JS_ToBoolFree(ctx, JS_GetPropertyStr(ctx, this_val, \"ignoreCase\"));\n    if (res < 0)\n        goto exception;\n    if (res)\n        *p++ = 'i';\n    res = JS_ToBoolFree(ctx, JS_GetPropertyStr(ctx, this_val, \"multiline\"));\n    if (res < 0)\n        goto exception;\n    if (res)\n        *p++ = 'm';\n    res = JS_ToBoolFree(ctx, JS_GetPropertyStr(ctx, this_val, \"dotAll\"));\n    if (res < 0)\n        goto exception;\n    if (res)\n        *p++ = 's';\n    res = JS_ToBoolFree(ctx, JS_GetProperty(ctx, this_val, JS_ATOM_unicode));\n    if (res < 0)\n        goto exception;\n    if (res)\n        *p++ = 'u';\n    res = JS_ToBoolFree(ctx, JS_GetPropertyStr(ctx, this_val, \"sticky\"));\n    if (res < 0)\n        goto exception;\n    if (res)\n        *p++ = 'y';\n    return JS_NewStringLen(ctx, str, p - str);\n\nexception:\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_regexp_toString(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    JSValue pattern, flags;\n    StringBuffer b_s, *b = &b_s;\n\n    if (!JS_IsObject(this_val))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    string_buffer_init(ctx, b, 0);\n    string_buffer_putc8(b, '/');\n    pattern = JS_GetProperty(ctx, this_val, JS_ATOM_source);\n    if (string_buffer_concat_value_free(b, pattern))\n        goto fail;\n    string_buffer_putc8(b, '/');\n    flags = JS_GetProperty(ctx, this_val, JS_ATOM_flags);\n    if (string_buffer_concat_value_free(b, flags))\n        goto fail;\n    return string_buffer_end(b);\n\nfail:\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nBOOL lre_check_stack_overflow(void *opaque, size_t alloca_size)\n{\n    JSContext *ctx = opaque;\n    return js_check_stack_overflow(ctx->rt, alloca_size);\n}\n\nvoid *lre_realloc(void *opaque, void *ptr, size_t size)\n{\n    JSContext *ctx = opaque;\n    /* No JS exception is raised here */\n    return js_realloc_rt(ctx->rt, ptr, size);\n}\n\nstatic JSValue js_regexp_exec(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    JSRegExp *re = js_get_regexp(ctx, this_val, TRUE);\n    JSString *str;\n    JSValue str_val, obj, val, groups = JS_UNDEFINED;\n    uint8_t *re_bytecode;\n    int ret;\n    uint8_t **capture, *str_buf;\n    int capture_count, shift, i, re_flags;\n    int64_t last_index;\n    const char *group_name_ptr;\n\n    if (!re)\n        return JS_EXCEPTION;\n    str_val = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str_val))\n        return str_val;\n    val = JS_GetProperty(ctx, this_val, JS_ATOM_lastIndex);\n    if (JS_IsException(val) ||\n        JS_ToLengthFree(ctx, &last_index, val)) {\n        JS_FreeValue(ctx, str_val);\n        return JS_EXCEPTION;\n    }\n    re_bytecode = re->bytecode->u.str8;\n    re_flags = lre_get_flags(re_bytecode);\n    if ((re_flags & (LRE_FLAG_GLOBAL | LRE_FLAG_STICKY)) == 0) {\n        last_index = 0;\n    }\n    str = JS_VALUE_GET_STRING(str_val);\n    capture_count = lre_get_capture_count(re_bytecode);\n    capture = NULL;\n    if (capture_count > 0) {\n        capture = js_malloc(ctx, sizeof(capture[0]) * capture_count * 2);\n        if (!capture) {\n            JS_FreeValue(ctx, str_val);\n            return JS_EXCEPTION;\n        }\n    }\n    shift = str->is_wide_char;\n    str_buf = str->u.str8;\n    if (last_index > str->len) {\n        ret = 2;\n    } else {\n        ret = lre_exec(capture, re_bytecode,\n                       str_buf, last_index, str->len,\n                       shift, ctx);\n    }\n    obj = JS_NULL;\n    if (ret != 1) {\n        if (ret >= 0) {\n            if (ret == 2 || (re_flags & (LRE_FLAG_GLOBAL | LRE_FLAG_STICKY))) {\n                if (JS_SetProperty(ctx, this_val, JS_ATOM_lastIndex,\n                                   JS_NewInt32(ctx, 0)) < 0)\n                    goto fail;\n            }\n        } else {\n            JS_ThrowInternalError(ctx, \"out of memory in regexp execution\");\n            goto fail;\n        }\n        JS_FreeValue(ctx, str_val);\n    } else {\n        int prop_flags;\n        if (re_flags & (LRE_FLAG_GLOBAL | LRE_FLAG_STICKY)) {\n            if (JS_SetProperty(ctx, this_val, JS_ATOM_lastIndex,\n                               JS_NewInt32(ctx, (capture[1] - str_buf) >> shift)) < 0)\n                goto fail;\n        }\n        obj = JS_NewArray(ctx);\n        if (JS_IsException(obj))\n            goto fail;\n        prop_flags = JS_PROP_C_W_E | JS_PROP_THROW;\n        group_name_ptr = lre_get_groupnames(re_bytecode);\n        if (group_name_ptr) {\n            groups = JS_NewObjectProto(ctx, JS_NULL);\n            if (JS_IsException(groups))\n                goto fail;\n        }\n\n        for(i = 0; i < capture_count; i++) {\n            int start, end;\n            JSValue val;\n            if (capture[2 * i] == NULL ||\n                capture[2 * i + 1] == NULL) {\n                val = JS_UNDEFINED;\n            } else {\n                start = (capture[2 * i] - str_buf) >> shift;\n                end = (capture[2 * i + 1] - str_buf) >> shift;\n                val = js_sub_string(ctx, str, start, end);\n                if (JS_IsException(val))\n                    goto fail;\n            }\n            if (group_name_ptr && i > 0) {\n                if (*group_name_ptr) {\n                    if (JS_DefinePropertyValueStr(ctx, groups, group_name_ptr,\n                                                  JS_DupValue(ctx, val),\n                                                  prop_flags) < 0) {\n                        JS_FreeValue(ctx, val);\n                        goto fail;\n                    }\n                }\n                group_name_ptr += strlen(group_name_ptr) + 1;\n            }\n            if (JS_DefinePropertyValueUint32(ctx, obj, i, val, prop_flags) < 0)\n                goto fail;\n        }\n        if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_groups,\n                                   groups, prop_flags) < 0)\n            goto fail;\n        if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_index,\n                                   JS_NewInt32(ctx, (capture[0] - str_buf) >> shift), prop_flags) < 0)\n            goto fail;\n        if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_input, str_val, prop_flags) < 0)\n            goto fail1;\n    }\n    js_free(ctx, capture);\n    return obj;\nfail:\n    JS_FreeValue(ctx, groups);\n    JS_FreeValue(ctx, str_val);\nfail1:\n    JS_FreeValue(ctx, obj);\n    js_free(ctx, capture);\n    return JS_EXCEPTION;\n}\n\n/* delete portions of a string that match a given regex */\nstatic JSValue JS_RegExpDelete(JSContext *ctx, JSValueConst this_val, JSValueConst arg)\n{\n    JSRegExp *re = js_get_regexp(ctx, this_val, TRUE);\n    JSString *str;\n    JSValue str_val, val;\n    uint8_t *re_bytecode;\n    int ret;\n    uint8_t **capture, *str_buf;\n    int capture_count, shift, re_flags;\n    int next_src_pos, start, end;\n    int64_t last_index;\n    StringBuffer b_s, *b = &b_s;\n\n    if (!re)\n        return JS_EXCEPTION;\n\n    string_buffer_init(ctx, b, 0);\n\n    capture = NULL;\n    str_val = JS_ToString(ctx, arg);\n    if (JS_IsException(str_val))\n        goto fail;\n    str = JS_VALUE_GET_STRING(str_val);\n    re_bytecode = re->bytecode->u.str8;\n    re_flags = lre_get_flags(re_bytecode);\n    if ((re_flags & (LRE_FLAG_GLOBAL | LRE_FLAG_STICKY)) == 0) {\n        last_index = 0;\n    } else {\n        val = JS_GetProperty(ctx, this_val, JS_ATOM_lastIndex);\n        if (JS_IsException(val) || JS_ToLengthFree(ctx, &last_index, val))\n            goto fail;\n    }\n    capture_count = lre_get_capture_count(re_bytecode);\n    if (capture_count > 0) {\n        capture = js_malloc(ctx, sizeof(capture[0]) * capture_count * 2);\n        if (!capture)\n            goto fail;\n    }\n    shift = str->is_wide_char;\n    str_buf = str->u.str8;\n    next_src_pos = 0;\n    for (;;) {\n        if (last_index > str->len)\n            break;\n\n        ret = lre_exec(capture, re_bytecode,\n                       str_buf, last_index, str->len, shift, ctx);\n        if (ret != 1) {\n            if (ret >= 0) {\n                if (ret == 2 || (re_flags & (LRE_FLAG_GLOBAL | LRE_FLAG_STICKY))) {\n                    if (JS_SetProperty(ctx, this_val, JS_ATOM_lastIndex,\n                                       JS_NewInt32(ctx, 0)) < 0)\n                        goto fail;\n                }\n            } else {\n                JS_ThrowInternalError(ctx, \"out of memory in regexp execution\");\n                goto fail;\n            }\n            break;\n        }\n        start = (capture[0] - str_buf) >> shift;\n        end = (capture[1] - str_buf) >> shift;\n        last_index = end;\n        if (next_src_pos < start) {\n            if (string_buffer_concat(b, str, next_src_pos, start))\n                goto fail;\n        }\n        next_src_pos = end;\n        if (!(re_flags & LRE_FLAG_GLOBAL)) {\n            if (JS_SetProperty(ctx, this_val, JS_ATOM_lastIndex,\n                               JS_NewInt32(ctx, end)) < 0)\n                goto fail;\n            break;\n        }\n        if (end == start) {\n            if (!(re_flags & LRE_FLAG_UTF16) || (unsigned)end >= str->len || !str->is_wide_char) {\n                end++;\n            } else {\n                string_getc(str, &end);\n            }\n        }\n        last_index = end;\n    }\n    if (string_buffer_concat(b, str, next_src_pos, str->len))\n        goto fail;\n    JS_FreeValue(ctx, str_val);\n    js_free(ctx, capture);\n    return string_buffer_end(b);\nfail:\n    JS_FreeValue(ctx, str_val);\n    js_free(ctx, capture);\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue JS_RegExpExec(JSContext *ctx, JSValueConst r, JSValueConst s)\n{\n    JSValue method, ret;\n\n    method = JS_GetProperty(ctx, r, JS_ATOM_exec);\n    if (JS_IsException(method))\n        return method;\n    if (JS_IsFunction(ctx, method)) {\n        ret = JS_CallFree(ctx, method, r, 1, &s);\n        if (JS_IsException(ret))\n            return ret;\n        if (!JS_IsObject(ret) && !JS_IsNull(ret)) {\n            JS_FreeValue(ctx, ret);\n            return JS_ThrowTypeError(ctx, \"RegExp exec method must return an object or null\");\n        }\n        return ret;\n    }\n    JS_FreeValue(ctx, method);\n    return js_regexp_exec(ctx, r, 1, &s);\n}\n\n#if 0\nstatic JSValue js_regexp___RegExpExec(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv)\n{\n    return JS_RegExpExec(ctx, argv[0], argv[1]);\n}\nstatic JSValue js_regexp___RegExpDelete(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv)\n{\n    return JS_RegExpDelete(ctx, argv[0], argv[1]);\n}\n#endif\n\nstatic JSValue js_regexp_test(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    JSValue val;\n    BOOL ret;\n\n    val = JS_RegExpExec(ctx, this_val, argv[0]);\n    if (JS_IsException(val))\n        return JS_EXCEPTION;\n    ret = !JS_IsNull(val);\n    JS_FreeValue(ctx, val);\n    return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_regexp_Symbol_match(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv)\n{\n    // [Symbol.match](str)\n    JSValueConst rx = this_val;\n    JSValue A, S, result, matchStr;\n    int global, n, fullUnicode, isEmpty;\n    JSString *p;\n\n    if (!JS_IsObject(rx))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    A = JS_UNDEFINED;\n    result = JS_UNDEFINED;\n    matchStr = JS_UNDEFINED;\n    S = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(S))\n        goto exception;\n\n    global = JS_ToBoolFree(ctx, JS_GetProperty(ctx, rx, JS_ATOM_global));\n    if (global < 0)\n        goto exception;\n\n    if (!global) {\n        A = JS_RegExpExec(ctx, rx, S);\n    } else {\n        fullUnicode = JS_ToBoolFree(ctx, JS_GetProperty(ctx, rx, JS_ATOM_unicode));\n        if (fullUnicode < 0)\n            goto exception;\n\n        if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, JS_NewInt32(ctx, 0)) < 0)\n            goto exception;\n        A = JS_NewArray(ctx);\n        if (JS_IsException(A))\n            goto exception;\n        n = 0;\n        for(;;) {\n            JS_FreeValue(ctx, result);\n            result = JS_RegExpExec(ctx, rx, S);\n            if (JS_IsException(result))\n                goto exception;\n            if (JS_IsNull(result))\n                break;\n            matchStr = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, result, 0));\n            if (JS_IsException(matchStr))\n                goto exception;\n            isEmpty = JS_IsEmptyString(matchStr);\n            if (JS_SetPropertyInt64(ctx, A, n++, matchStr) < 0)\n                goto exception;\n            if (isEmpty) {\n                int64_t thisIndex, nextIndex;\n                if (JS_ToLengthFree(ctx, &thisIndex,\n                                    JS_GetProperty(ctx, rx, JS_ATOM_lastIndex)) < 0)\n                    goto exception;\n                p = JS_VALUE_GET_STRING(S);\n                nextIndex = string_advance_index(p, thisIndex, fullUnicode);\n                if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, JS_NewInt64(ctx, nextIndex)) < 0)\n                    goto exception;\n            }\n        }\n        if (n == 0) {\n            JS_FreeValue(ctx, A);\n            A = JS_NULL;\n        }\n    }\n    JS_FreeValue(ctx, result);\n    JS_FreeValue(ctx, S);\n    return A;\n\nexception:\n    JS_FreeValue(ctx, A);\n    JS_FreeValue(ctx, result);\n    JS_FreeValue(ctx, S);\n    return JS_EXCEPTION;\n}\n\ntypedef struct JSRegExpStringIteratorData {\n    JSValue iterating_regexp;\n    JSValue iterated_string;\n    BOOL global;\n    BOOL unicode;\n    BOOL done;\n} JSRegExpStringIteratorData;\n\nstatic void js_regexp_string_iterator_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSRegExpStringIteratorData *it = p->u.regexp_string_iterator_data;\n    if (it) {\n        JS_FreeValueRT(rt, it->iterating_regexp);\n        JS_FreeValueRT(rt, it->iterated_string);\n        js_free_rt(rt, it);\n    }\n}\n\nstatic void js_regexp_string_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                           JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSRegExpStringIteratorData *it = p->u.regexp_string_iterator_data;\n    if (it) {\n        JS_MarkValue(rt, it->iterating_regexp, mark_func);\n        JS_MarkValue(rt, it->iterated_string, mark_func);\n    }\n}\n\nstatic JSValue js_regexp_string_iterator_next(JSContext *ctx,\n                                              JSValueConst this_val,\n                                              int argc, JSValueConst *argv,\n                                              BOOL *pdone, int magic)\n{\n    JSRegExpStringIteratorData *it;\n    JSValueConst R, S;\n    JSValue matchStr = JS_UNDEFINED, match = JS_UNDEFINED;\n    JSString *sp;\n\n    it = JS_GetOpaque2(ctx, this_val, JS_CLASS_REGEXP_STRING_ITERATOR);\n    if (!it)\n        goto exception;\n    if (it->done) {\n        *pdone = TRUE;\n        return JS_UNDEFINED;\n    }\n    R = it->iterating_regexp;\n    S = it->iterated_string;\n    match = JS_RegExpExec(ctx, R, S);\n    if (JS_IsException(match))\n        goto exception;\n    if (JS_IsNull(match)) {\n        it->done = TRUE;\n        *pdone = TRUE;\n        return JS_UNDEFINED;\n    } else if (it->global) {\n        matchStr = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, match, 0));\n        if (JS_IsException(matchStr))\n            goto exception;\n        if (JS_IsEmptyString(matchStr)) {\n            int64_t thisIndex, nextIndex;\n            if (JS_ToLengthFree(ctx, &thisIndex,\n                                JS_GetProperty(ctx, R, JS_ATOM_lastIndex)) < 0)\n                goto exception;\n            sp = JS_VALUE_GET_STRING(S);\n            nextIndex = string_advance_index(sp, thisIndex, it->unicode);\n            if (JS_SetProperty(ctx, R, JS_ATOM_lastIndex,\n                               JS_NewInt64(ctx, nextIndex)) < 0)\n                goto exception;\n        }\n        JS_FreeValue(ctx, matchStr);\n    } else {\n        it->done = TRUE;\n    }\n    *pdone = FALSE;\n    return match;\n exception:\n    JS_FreeValue(ctx, match);\n    JS_FreeValue(ctx, matchStr);\n    *pdone = FALSE;\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_regexp_Symbol_matchAll(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    // [Symbol.matchAll](str)\n    JSValueConst R = this_val;\n    JSValue S, C, flags, matcher, iter;\n    JSValueConst args[2];\n    JSString *strp;\n    int64_t lastIndex;\n    JSRegExpStringIteratorData *it;\n    \n    if (!JS_IsObject(R))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    C = JS_UNDEFINED;\n    flags = JS_UNDEFINED;\n    matcher = JS_UNDEFINED;\n    iter = JS_UNDEFINED;\n    \n    S = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(S))\n        goto exception;\n    C = JS_SpeciesConstructor(ctx, R, ctx->regexp_ctor);\n    if (JS_IsException(C))\n        goto exception;\n    flags = JS_ToStringFree(ctx, JS_GetProperty(ctx, R, JS_ATOM_flags));\n    if (JS_IsException(flags))\n        goto exception;\n    args[0] = R;\n    args[1] = flags;\n    matcher = JS_CallConstructor(ctx, C, 2, args);\n    if (JS_IsException(matcher))\n        goto exception;\n    if (JS_ToLengthFree(ctx, &lastIndex,\n                        JS_GetProperty(ctx, R, JS_ATOM_lastIndex)))\n        goto exception;\n    if (JS_SetProperty(ctx, matcher, JS_ATOM_lastIndex,\n                       JS_NewInt64(ctx, lastIndex)) < 0)\n        goto exception;\n    \n    iter = JS_NewObjectClass(ctx, JS_CLASS_REGEXP_STRING_ITERATOR);\n    if (JS_IsException(iter))\n        goto exception;\n    it = js_malloc(ctx, sizeof(*it));\n    if (!it)\n        goto exception;\n    it->iterating_regexp = matcher;\n    it->iterated_string = S;\n    strp = JS_VALUE_GET_STRING(flags);\n    it->global = string_indexof_char(strp, 'g', 0) >= 0;\n    it->unicode = string_indexof_char(strp, 'u', 0) >= 0;\n    it->done = FALSE;\n    JS_SetOpaque(iter, it);\n\n    JS_FreeValue(ctx, C);\n    JS_FreeValue(ctx, flags);\n    return iter;\n exception:\n    JS_FreeValue(ctx, S);\n    JS_FreeValue(ctx, C);\n    JS_FreeValue(ctx, flags);\n    JS_FreeValue(ctx, matcher);\n    JS_FreeValue(ctx, iter);\n    return JS_EXCEPTION;\n}\n\ntypedef struct ValueBuffer {\n    JSContext *ctx;\n    JSValue *arr;\n    JSValue def[4];\n    int len;\n    int size;\n    int error_status;\n} ValueBuffer;\n\nstatic int value_buffer_init(JSContext *ctx, ValueBuffer *b)\n{\n    b->ctx = ctx;\n    b->len = 0;\n    b->size = 4;\n    b->error_status = 0;\n    b->arr = b->def;\n    return 0;\n}\n\nstatic void value_buffer_free(ValueBuffer *b)\n{\n    while (b->len > 0)\n        JS_FreeValue(b->ctx, b->arr[--b->len]);\n    if (b->arr != b->def)\n        js_free(b->ctx, b->arr);\n    b->arr = b->def;\n    b->size = 4;\n}\n\nstatic int value_buffer_append(ValueBuffer *b, JSValue val)\n{\n    if (b->error_status)\n        return -1;\n\n    if (b->len >= b->size) {\n        int new_size = (b->len + (b->len >> 1) + 31) & ~16;\n        size_t slack;\n        JSValue *new_arr;\n\n        if (b->arr == b->def) {\n            new_arr = js_realloc2(b->ctx, NULL, sizeof(*b->arr) * new_size, &slack);\n            if (new_arr)\n                memcpy(new_arr, b->def, sizeof b->def);\n        } else {\n            new_arr = js_realloc2(b->ctx, b->arr, sizeof(*b->arr) * new_size, &slack);\n        }\n        if (!new_arr) {\n            value_buffer_free(b);\n            JS_FreeValue(b->ctx, val);\n            b->error_status = -1;\n            return -1;\n        }\n        new_size += slack / sizeof(*new_arr);\n        b->arr = new_arr;\n        b->size = new_size;\n    }\n    b->arr[b->len++] = val;\n    return 0;\n}\n\nstatic int js_is_standard_regexp(JSContext *ctx, JSValueConst rx)\n{\n    JSValue val;\n    int res;\n\n    val = JS_GetProperty(ctx, rx, JS_ATOM_constructor);\n    if (JS_IsException(val))\n        return -1;\n    // rx.constructor === RegExp\n    res = js_same_value(ctx, val, ctx->regexp_ctor);\n    JS_FreeValue(ctx, val);\n    if (res) {\n        val = JS_GetProperty(ctx, rx, JS_ATOM_exec);\n        if (JS_IsException(val))\n            return -1;\n        // rx.exec === RE_exec\n        res = JS_IsCFunction(ctx, val, js_regexp_exec, 0);\n        JS_FreeValue(ctx, val);\n    }\n    return res;\n}\n\nstatic JSValue js_regexp_Symbol_replace(JSContext *ctx, JSValueConst this_val,\n                                        int argc, JSValueConst *argv)\n{\n    // [Symbol.replace](str, rep)\n    JSValueConst rx = this_val, rep = argv[1];\n    JSValueConst args[6];\n    JSValue str, rep_val, matched, tab, rep_str, namedCaptures, res;\n    JSString *sp, *rp;\n    StringBuffer b_s, *b = &b_s;\n    ValueBuffer v_b, *results = &v_b;\n    int nextSourcePosition, n, j, functionalReplace, is_global, fullUnicode;\n    uint32_t nCaptures;\n    int64_t position;\n\n    if (!JS_IsObject(rx))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    string_buffer_init(ctx, b, 0);\n    value_buffer_init(ctx, results);\n\n    rep_val = JS_UNDEFINED;\n    matched = JS_UNDEFINED;\n    tab = JS_UNDEFINED;\n    rep_str = JS_UNDEFINED;\n    namedCaptures = JS_UNDEFINED;\n\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        goto exception;\n        \n    sp = JS_VALUE_GET_STRING(str);\n    rp = NULL;\n    functionalReplace = JS_IsFunction(ctx, rep);\n    if (!functionalReplace) {\n        rep_val = JS_ToString(ctx, rep);\n        if (JS_IsException(rep_val))\n            goto exception;\n        rp = JS_VALUE_GET_STRING(rep_val);\n    }\n    fullUnicode = 0;\n    is_global = JS_ToBoolFree(ctx, JS_GetProperty(ctx, rx, JS_ATOM_global));\n    if (is_global < 0)\n        goto exception;\n    if (is_global) {\n        fullUnicode = JS_ToBoolFree(ctx, JS_GetProperty(ctx, rx, JS_ATOM_unicode));\n        if (fullUnicode < 0)\n            goto exception;\n        if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, JS_NewInt32(ctx, 0)) < 0)\n            goto exception;\n    }\n\n    if (rp && rp->len == 0 && is_global && js_is_standard_regexp(ctx, rx)) {\n        /* use faster version for simple cases */\n        res = JS_RegExpDelete(ctx, rx, str);\n        goto done;\n    }\n    for(;;) {\n        JSValue result;\n        result = JS_RegExpExec(ctx, rx, str);\n        if (JS_IsException(result))\n            goto exception;\n        if (JS_IsNull(result))\n            break;\n        if (value_buffer_append(results, result) < 0)\n            goto exception;\n        if (!is_global)\n            break;\n        JS_FreeValue(ctx, matched);\n        matched = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, result, 0));\n        if (JS_IsException(matched))\n            goto exception;\n        if (JS_IsEmptyString(matched)) {\n            /* always advance of at least one char */\n            int64_t thisIndex, nextIndex;\n            if (JS_ToLengthFree(ctx, &thisIndex, JS_GetProperty(ctx, rx, JS_ATOM_lastIndex)) < 0)\n                goto exception;\n            nextIndex = string_advance_index(sp, thisIndex, fullUnicode);\n            if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, JS_NewInt64(ctx, nextIndex)) < 0)\n                goto exception;\n        }\n    }\n    nextSourcePosition = 0;\n    for(j = 0; j < results->len; j++) {\n        JSValueConst result;\n        result = results->arr[j];\n        if (js_get_length32(ctx, &nCaptures, result) < 0)\n            goto exception;\n        JS_FreeValue(ctx, matched);\n        matched = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, result, 0));\n        if (JS_IsException(matched))\n            goto exception;\n        if (JS_ToLengthFree(ctx, &position, JS_GetProperty(ctx, result, JS_ATOM_index)))\n            goto exception;\n        if (position > sp->len)\n            position = sp->len;\n        else if (position < 0)\n            position = 0;\n        /* ignore substition if going backward (can happen\n           with custom regexp object) */\n        JS_FreeValue(ctx, tab);\n        tab = JS_NewArray(ctx);\n        if (JS_IsException(tab))\n            goto exception;\n        if (JS_DefinePropertyValueInt64(ctx, tab, 0, JS_DupValue(ctx, matched),\n                                        JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n            goto exception;\n        for(n = 1; n < nCaptures; n++) {\n            JSValue capN;\n            capN = JS_GetPropertyInt64(ctx, result, n);\n            if (JS_IsException(capN))\n                goto exception;\n            if (!JS_IsUndefined(capN)) {\n                capN = JS_ToStringFree(ctx, capN);\n                if (JS_IsException(capN))\n                    goto exception;\n            }\n            if (JS_DefinePropertyValueInt64(ctx, tab, n, capN,\n                                            JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                goto exception;\n        }\n        JS_FreeValue(ctx, namedCaptures);\n        namedCaptures = JS_GetProperty(ctx, result, JS_ATOM_groups);\n        if (JS_IsException(namedCaptures))\n            goto exception;\n        if (functionalReplace) {\n            if (JS_DefinePropertyValueInt64(ctx, tab, n++, JS_NewInt32(ctx, position), JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                goto exception;\n            if (JS_DefinePropertyValueInt64(ctx, tab, n++, JS_DupValue(ctx, str), JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                goto exception;\n            if (!JS_IsUndefined(namedCaptures)) {\n                if (JS_DefinePropertyValueInt64(ctx, tab, n++, JS_DupValue(ctx, namedCaptures), JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                    goto exception;\n            }\n            args[0] = JS_UNDEFINED;\n            args[1] = tab;\n            JS_FreeValue(ctx, rep_str);\n            rep_str = JS_ToStringFree(ctx, js_function_apply(ctx, rep, 2, args, 0));\n        } else {\n            JSValue namedCaptures1;\n            if (!JS_IsUndefined(namedCaptures)) {\n                namedCaptures1 = JS_ToObject(ctx, namedCaptures);\n                if (JS_IsException(namedCaptures1))\n                    goto exception;\n            } else {\n                namedCaptures1 = JS_UNDEFINED;\n            }\n            args[0] = matched;\n            args[1] = str;\n            args[2] = JS_NewInt32(ctx, position);\n            args[3] = tab;\n            args[4] = namedCaptures1;\n            args[5] = rep_val;\n            JS_FreeValue(ctx, rep_str);\n            rep_str = js_string___GetSubstitution(ctx, JS_UNDEFINED, 6, args);\n            JS_FreeValue(ctx, namedCaptures1);\n        }\n        if (JS_IsException(rep_str))\n            goto exception;\n        if (position >= nextSourcePosition) {\n            string_buffer_concat(b, sp, nextSourcePosition, position);\n            string_buffer_concat_value(b, rep_str);\n            nextSourcePosition = position + JS_VALUE_GET_STRING(matched)->len;\n        }\n    }\n    string_buffer_concat(b, sp, nextSourcePosition, sp->len);\n    res = string_buffer_end(b);\n    goto done1;\n\nexception:\n    res = JS_EXCEPTION;\ndone:\n    string_buffer_free(b);\ndone1:\n    value_buffer_free(results);\n    JS_FreeValue(ctx, rep_val);\n    JS_FreeValue(ctx, matched);\n    JS_FreeValue(ctx, tab);\n    JS_FreeValue(ctx, rep_str);\n    JS_FreeValue(ctx, namedCaptures);\n    JS_FreeValue(ctx, str);\n    return res;\n}\n\nstatic JSValue js_regexp_Symbol_search(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    JSValueConst rx = this_val;\n    JSValue str, previousLastIndex, currentLastIndex, result, index;\n\n    if (!JS_IsObject(rx))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    result = JS_UNDEFINED;\n    currentLastIndex = JS_UNDEFINED;\n    previousLastIndex = JS_UNDEFINED;\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        goto exception;\n\n    previousLastIndex = JS_GetProperty(ctx, rx, JS_ATOM_lastIndex);\n    if (JS_IsException(previousLastIndex))\n        goto exception;\n\n    if (!js_same_value(ctx, previousLastIndex, JS_NewInt32(ctx, 0))) {\n        if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, JS_NewInt32(ctx, 0)) < 0) {\n            goto exception;\n        }\n    }\n    result = JS_RegExpExec(ctx, rx, str);\n    if (JS_IsException(result))\n        goto exception;\n    currentLastIndex = JS_GetProperty(ctx, rx, JS_ATOM_lastIndex);\n    if (JS_IsException(currentLastIndex))\n        goto exception;\n    if (js_same_value(ctx, currentLastIndex, previousLastIndex)) {\n        JS_FreeValue(ctx, previousLastIndex);\n    } else {\n        if (JS_SetProperty(ctx, rx, JS_ATOM_lastIndex, previousLastIndex) < 0) {\n            previousLastIndex = JS_UNDEFINED;\n            goto exception;\n        }\n    }\n    JS_FreeValue(ctx, str);\n    JS_FreeValue(ctx, currentLastIndex);\n\n    if (JS_IsNull(result)) {\n        return JS_NewInt32(ctx, -1);\n    } else {\n        index = JS_GetProperty(ctx, result, JS_ATOM_index);\n        JS_FreeValue(ctx, result);\n        return index;\n    }\n\nexception:\n    JS_FreeValue(ctx, result);\n    JS_FreeValue(ctx, str);\n    JS_FreeValue(ctx, currentLastIndex);\n    JS_FreeValue(ctx, previousLastIndex);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_regexp_Symbol_split(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    // [Symbol.split](str, limit)\n    JSValueConst rx = this_val;\n    JSValueConst args[2];\n    JSValue str, ctor, splitter, A, flags, z, sub;\n    JSString *strp;\n    uint32_t lim, size, p, q;\n    int unicodeMatching;\n    int64_t lengthA, e, numberOfCaptures, i;\n\n    if (!JS_IsObject(rx))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    ctor = JS_UNDEFINED;\n    splitter = JS_UNDEFINED;\n    A = JS_UNDEFINED;\n    flags = JS_UNDEFINED;\n    z = JS_UNDEFINED;\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        goto exception;\n    ctor = JS_SpeciesConstructor(ctx, rx, ctx->regexp_ctor);\n    if (JS_IsException(ctor))\n        goto exception;\n    flags = JS_ToStringFree(ctx, JS_GetProperty(ctx, rx, JS_ATOM_flags));\n    if (JS_IsException(flags))\n        goto exception;\n    strp = JS_VALUE_GET_STRING(flags);\n    unicodeMatching = string_indexof_char(strp, 'u', 0) >= 0;\n    if (string_indexof_char(strp, 'y', 0) < 0) {\n        flags = JS_ConcatString3(ctx, \"\", flags, \"y\");\n        if (JS_IsException(flags))\n            goto exception;\n    }\n    args[0] = rx;\n    args[1] = flags;\n    splitter = JS_CallConstructor(ctx, ctor, 2, args);\n    if (JS_IsException(splitter))\n        goto exception;\n    A = JS_NewArray(ctx);\n    if (JS_IsException(A))\n        goto exception;\n    lengthA = 0;\n    if (JS_IsUndefined(argv[1])) {\n        lim = 0xffffffff;\n    } else {\n        if (JS_ToUint32(ctx, &lim, argv[1]) < 0)\n            goto exception;\n        if (lim == 0)\n            goto done;\n    }\n    strp = JS_VALUE_GET_STRING(str);\n    p = q = 0;\n    size = strp->len;\n    if (size == 0) {\n        z = JS_RegExpExec(ctx, splitter, str);\n        if (JS_IsException(z))\n            goto exception;\n        if (JS_IsNull(z))\n            goto add_tail;\n        goto done;\n    }\n    while (q < size) {\n        if (JS_SetProperty(ctx, splitter, JS_ATOM_lastIndex, JS_NewInt32(ctx, q)) < 0)\n            goto exception;\n        JS_FreeValue(ctx, z);    \n        z = JS_RegExpExec(ctx, splitter, str);\n        if (JS_IsException(z))\n            goto exception;\n        if (JS_IsNull(z)) {\n            q = string_advance_index(strp, q, unicodeMatching);\n        } else {\n            if (JS_ToLengthFree(ctx, &e, JS_GetProperty(ctx, splitter, JS_ATOM_lastIndex)))\n                goto exception;\n            if (e > size)\n                e = size;\n            if (e == p) {\n                q = string_advance_index(strp, q, unicodeMatching);\n            } else {\n                sub = js_sub_string(ctx, strp, p, q);\n                if (JS_IsException(sub))\n                    goto exception;\n                if (JS_DefinePropertyValueInt64(ctx, A, lengthA++, sub,\n                                                JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                    goto exception;\n                if (lengthA == lim)\n                    goto done;\n                p = e;\n                if (js_get_length64(ctx, &numberOfCaptures, z))\n                    goto exception;\n                for(i = 1; i < numberOfCaptures; i++) {\n                    sub = JS_ToStringFree(ctx, JS_GetPropertyInt64(ctx, z, i));\n                    if (JS_IsException(sub))\n                        goto exception;\n                    if (JS_DefinePropertyValueInt64(ctx, A, lengthA++, sub, JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                        goto exception;\n                    if (lengthA == lim)\n                        goto done;\n                }\n                q = p;\n            }\n        }\n    }\nadd_tail:\n    if (p > size)\n        p = size;\n    sub = js_sub_string(ctx, strp, p, size);\n    if (JS_IsException(sub))\n        goto exception;\n    if (JS_DefinePropertyValueInt64(ctx, A, lengthA++, sub, JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n        goto exception;\n    goto done;\nexception:\n    JS_FreeValue(ctx, A);\n    A = JS_EXCEPTION;\ndone:\n    JS_FreeValue(ctx, str);\n    JS_FreeValue(ctx, ctor);\n    JS_FreeValue(ctx, splitter);\n    JS_FreeValue(ctx, flags);\n    JS_FreeValue(ctx, z);    \n    return A;\n}\n\nstatic const JSCFunctionListEntry js_regexp_funcs[] = {\n    JS_CGETSET_DEF(\"[Symbol.species]\", js_get_this, NULL ),\n    //JS_CFUNC_DEF(\"__RegExpExec\", 2, js_regexp___RegExpExec ),\n    //JS_CFUNC_DEF(\"__RegExpDelete\", 2, js_regexp___RegExpDelete ),\n};\n\nstatic const JSCFunctionListEntry js_regexp_proto_funcs[] = {\n    JS_CGETSET_DEF(\"flags\", js_regexp_get_flags, NULL ),\n    JS_CGETSET_DEF(\"source\", js_regexp_get_source, NULL ),\n    JS_CGETSET_MAGIC_DEF(\"global\", js_regexp_get_flag, NULL, 1 ),\n    JS_CGETSET_MAGIC_DEF(\"ignoreCase\", js_regexp_get_flag, NULL, 2 ),\n    JS_CGETSET_MAGIC_DEF(\"multiline\", js_regexp_get_flag, NULL, 4 ),\n    JS_CGETSET_MAGIC_DEF(\"dotAll\", js_regexp_get_flag, NULL, 8 ),\n    JS_CGETSET_MAGIC_DEF(\"unicode\", js_regexp_get_flag, NULL, 16 ),\n    JS_CGETSET_MAGIC_DEF(\"sticky\", js_regexp_get_flag, NULL, 32 ),\n    JS_CFUNC_DEF(\"exec\", 1, js_regexp_exec ),\n    JS_CFUNC_DEF(\"compile\", 2, js_regexp_compile ),\n    JS_CFUNC_DEF(\"test\", 1, js_regexp_test ),\n    JS_CFUNC_DEF(\"toString\", 0, js_regexp_toString ),\n    JS_CFUNC_DEF(\"[Symbol.replace]\", 2, js_regexp_Symbol_replace ),\n    JS_CFUNC_DEF(\"[Symbol.match]\", 1, js_regexp_Symbol_match ),\n    JS_CFUNC_DEF(\"[Symbol.matchAll]\", 1, js_regexp_Symbol_matchAll ),\n    JS_CFUNC_DEF(\"[Symbol.search]\", 1, js_regexp_Symbol_search ),\n    JS_CFUNC_DEF(\"[Symbol.split]\", 2, js_regexp_Symbol_split ),\n    //JS_CGETSET_DEF(\"__source\", js_regexp_get___source, NULL ),\n    //JS_CGETSET_DEF(\"__flags\", js_regexp_get___flags, NULL ),\n};\n\nstatic const JSCFunctionListEntry js_regexp_string_iterator_proto_funcs[] = {\n    JS_ITERATOR_NEXT_DEF(\"next\", 0, js_regexp_string_iterator_next, 0 ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"RegExp String Iterator\", JS_PROP_CONFIGURABLE ),\n};\n\nvoid JS_AddIntrinsicRegExpCompiler(JSContext *ctx)\n{\n    ctx->compile_regexp = js_compile_regexp;\n}\n\nvoid JS_AddIntrinsicRegExp(JSContext *ctx)\n{\n    JSValueConst obj;\n\n    JS_AddIntrinsicRegExpCompiler(ctx);\n\n    ctx->class_proto[JS_CLASS_REGEXP] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_REGEXP], js_regexp_proto_funcs,\n                               countof(js_regexp_proto_funcs));\n    obj = JS_NewGlobalCConstructor(ctx, \"RegExp\", js_regexp_constructor, 2,\n                                   ctx->class_proto[JS_CLASS_REGEXP]);\n    ctx->regexp_ctor = JS_DupValue(ctx, obj);\n    JS_SetPropertyFunctionList(ctx, obj, js_regexp_funcs, countof(js_regexp_funcs));\n\n    ctx->class_proto[JS_CLASS_REGEXP_STRING_ITERATOR] =\n        JS_NewObjectProto(ctx, ctx->iterator_proto);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_REGEXP_STRING_ITERATOR],\n                               js_regexp_string_iterator_proto_funcs,\n                               countof(js_regexp_string_iterator_proto_funcs));\n}\n\n/* JSON */\n\nstatic int json_parse_expect(JSParseState *s, int tok)\n{\n    if (s->token.val != tok) {\n        /* XXX: dump token correctly in all cases */\n        return js_parse_error(s, \"expecting '%c'\", tok);\n    }\n    return json_next_token(s);\n}\n\nstatic JSValue json_parse_value(JSParseState *s)\n{\n    JSContext *ctx = s->ctx;\n    JSValue val = JS_NULL;\n    int ret;\n\n    switch(s->token.val) {\n    case '{':\n        {\n            JSValue prop_val;\n            JSAtom prop_name;\n            \n            if (json_next_token(s))\n                goto fail;\n            val = JS_NewObject(ctx);\n            if (JS_IsException(val))\n                goto fail;\n            if (s->token.val != '}') {\n                for(;;) {\n                    if (s->token.val == TOK_STRING) {\n                        prop_name = JS_ValueToAtom(ctx, s->token.u.str.str);\n                        if (prop_name == JS_ATOM_NULL)\n                            goto fail;\n                    } else if (s->ext_json && s->token.val == TOK_IDENT) {\n                        prop_name = JS_DupAtom(ctx, s->token.u.ident.atom);\n                    } else {\n                        js_parse_error(s, \"expecting property name\");\n                        goto fail;\n                    }\n                    if (json_next_token(s))\n                        goto fail1;\n                    if (json_parse_expect(s, ':'))\n                        goto fail1;\n                    prop_val = json_parse_value(s);\n                    if (JS_IsException(prop_val)) {\n                    fail1:\n                        JS_FreeAtom(ctx, prop_name);\n                        goto fail;\n                    }\n                    ret = JS_DefinePropertyValue(ctx, val, prop_name,\n                                                 prop_val, JS_PROP_C_W_E);\n                    JS_FreeAtom(ctx, prop_name);\n                    if (ret < 0)\n                        goto fail;\n\n                    if (s->token.val != ',')\n                        break;\n                    if (json_next_token(s))\n                        goto fail;\n                    if (s->ext_json && s->token.val == '}')\n                        break;\n                }\n            }\n            if (json_parse_expect(s, '}'))\n                goto fail;\n        }\n        break;\n    case '[':\n        {\n            JSValue el;\n            uint32_t idx;\n\n            if (json_next_token(s))\n                goto fail;\n            val = JS_NewArray(ctx);\n            if (JS_IsException(val))\n                goto fail;\n            if (s->token.val != ']') {\n                idx = 0;\n                for(;;) {\n                    el = json_parse_value(s);\n                    if (JS_IsException(el))\n                        goto fail;\n                    ret = JS_DefinePropertyValueUint32(ctx, val, idx, el, JS_PROP_C_W_E);\n                    if (ret < 0)\n                        goto fail;\n                    if (s->token.val != ',')\n                        break;\n                    if (json_next_token(s))\n                        goto fail;\n                    idx++;\n                    if (s->ext_json && s->token.val == ']')\n                        break;\n                }\n            }\n            if (json_parse_expect(s, ']'))\n                goto fail;\n        }\n        break;\n    case TOK_STRING:\n        val = JS_DupValue(ctx, s->token.u.str.str);\n        if (json_next_token(s))\n            goto fail;\n        break;\n    case TOK_NUMBER:\n        val = s->token.u.num.val;\n        if (json_next_token(s))\n            goto fail;\n        break;\n    case TOK_IDENT:\n        if (s->token.u.ident.atom == JS_ATOM_false ||\n            s->token.u.ident.atom == JS_ATOM_true) {\n            val = JS_NewBool(ctx, (s->token.u.ident.atom == JS_ATOM_true));\n        } else if (s->token.u.ident.atom == JS_ATOM_null) {\n            val = JS_NULL;\n        } else {\n            goto def_token;\n        }\n        if (json_next_token(s))\n            goto fail;\n        break;\n    default:\n    def_token:\n        if (s->token.val == TOK_EOF) {\n            js_parse_error(s, \"unexpected end of input\");\n        } else {\n            js_parse_error(s, \"unexpected token: '%.*s'\",\n                           (int)(s->buf_ptr - s->token.ptr), s->token.ptr);\n        }\n        goto fail;\n    }\n    return val;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nJSValue JS_ParseJSON2(JSContext *ctx, const char *buf, size_t buf_len,\n                      const char *filename, int flags)\n{\n    JSParseState s1, *s = &s1;\n    JSValue val = JS_UNDEFINED;\n\n    js_parse_init(ctx, s, buf, buf_len, filename);\n    s->ext_json = ((flags & JS_PARSE_JSON_EXT) != 0);\n    if (json_next_token(s))\n        goto fail;\n    val = json_parse_value(s);\n    if (JS_IsException(val))\n        goto fail;\n    if (s->token.val != TOK_EOF) {\n        if (js_parse_error(s, \"unexpected data at the end\"))\n            goto fail;\n    }\n    return val;\n fail:\n    JS_FreeValue(ctx, val);\n    free_token(s, &s->token);\n    return JS_EXCEPTION;\n}\n\nJSValue JS_ParseJSON(JSContext *ctx, const char *buf, size_t buf_len,\n                     const char *filename)\n{\n    return JS_ParseJSON2(ctx, buf, buf_len, filename, 0); \n}\n\nstatic JSValue internalize_json_property(JSContext *ctx, JSValueConst holder,\n                                         JSAtom name, JSValueConst reviver)\n{\n    JSValue val, new_el, name_val, res;\n    JSValueConst args[2];\n    int ret, is_array;\n    uint32_t i, len = 0;\n    JSAtom prop;\n    JSPropertyEnum *atoms = NULL;\n\n    if (js_check_stack_overflow(ctx->rt, 0)) {\n        return JS_ThrowStackOverflow(ctx);\n    }\n\n    val = JS_GetProperty(ctx, holder, name);\n    if (JS_IsException(val))\n        return val;\n    if (JS_IsObject(val)) {\n        is_array = JS_IsArray(ctx, val);\n        if (is_array < 0)\n            goto fail;\n        if (is_array) {\n            if (js_get_length32(ctx, &len, val))\n                goto fail;\n        } else {\n            ret = JS_GetOwnPropertyNamesInternal(ctx, &atoms, &len, JS_VALUE_GET_OBJ(val), JS_GPN_ENUM_ONLY | JS_GPN_STRING_MASK);\n            if (ret < 0)\n                goto fail;\n        }\n        for(i = 0; i < len; i++) {\n            if (is_array) {\n                prop = JS_NewAtomUInt32(ctx, i);\n                if (prop == JS_ATOM_NULL)\n                    goto fail;\n            } else {\n                prop = JS_DupAtom(ctx, atoms[i].atom);\n            }\n            new_el = internalize_json_property(ctx, val, prop, reviver);\n            if (JS_IsException(new_el)) {\n                JS_FreeAtom(ctx, prop);\n                goto fail;\n            }\n            if (JS_IsUndefined(new_el)) {\n                ret = JS_DeleteProperty(ctx, val, prop, 0);\n            } else {\n                ret = JS_DefinePropertyValue(ctx, val, prop, new_el, JS_PROP_C_W_E);\n            }\n            JS_FreeAtom(ctx, prop);\n            if (ret < 0)\n                goto fail;\n        }\n    }\n    js_free_prop_enum(ctx, atoms, len);\n    atoms = NULL;\n    name_val = JS_AtomToValue(ctx, name);\n    if (JS_IsException(name_val))\n        goto fail;\n    args[0] = name_val;\n    args[1] = val;\n    res = JS_Call(ctx, reviver, holder, 2, args);\n    JS_FreeValue(ctx, name_val);\n    JS_FreeValue(ctx, val);\n    return res;\n fail:\n    js_free_prop_enum(ctx, atoms, len);\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_json_parse(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    JSValue obj, root;\n    JSValueConst reviver;\n    const char *str;\n    size_t len;\n\n    str = JS_ToCStringLen(ctx, &len, argv[0]);\n    if (!str)\n        return JS_EXCEPTION;\n    obj = JS_ParseJSON(ctx, str, len, \"<input>\");\n    JS_FreeCString(ctx, str);\n    if (JS_IsException(obj))\n        return obj;\n    if (argc > 1 && JS_IsFunction(ctx, argv[1])) {\n        reviver = argv[1];\n        root = JS_NewObject(ctx);\n        if (JS_IsException(root)) {\n            JS_FreeValue(ctx, obj);\n            return JS_EXCEPTION;\n        }\n        if (JS_DefinePropertyValue(ctx, root, JS_ATOM_empty_string, obj,\n                                   JS_PROP_C_W_E) < 0) {\n            JS_FreeValue(ctx, root);\n            return JS_EXCEPTION;\n        }\n        obj = internalize_json_property(ctx, root, JS_ATOM_empty_string,\n                                        reviver);\n        JS_FreeValue(ctx, root);\n    }\n    return obj;\n}\n\ntypedef struct JSONStringifyContext {\n    JSValueConst replacer_func;\n    JSValue stack;\n    JSValue property_list;\n    JSValue gap;\n    JSValue empty;\n    StringBuffer *b;\n} JSONStringifyContext;\n\nstatic JSValue JS_ToQuotedStringFree(JSContext *ctx, JSValue val) {\n    JSValue r = JS_ToQuotedString(ctx, val);\n    JS_FreeValue(ctx, val);\n    return r;\n}\n\nstatic JSValue js_json_check(JSContext *ctx, JSONStringifyContext *jsc,\n                             JSValueConst holder, JSValue val, JSValueConst key)\n{\n    JSValue v;\n    JSValueConst args[2];\n\n    if (JS_IsObject(val)\n#ifdef CONFIG_BIGNUM\n    ||  JS_IsBigInt(ctx, val)   /* XXX: probably useless */\n#endif\n        ) {\n            JSValue f = JS_GetProperty(ctx, val, JS_ATOM_toJSON);\n            if (JS_IsException(f))\n                goto exception;\n            if (JS_IsFunction(ctx, f)) {\n                v = JS_CallFree(ctx, f, val, 1, &key);\n                JS_FreeValue(ctx, val);\n                val = v;\n                if (JS_IsException(val))\n                    goto exception;\n            } else {\n                JS_FreeValue(ctx, f);\n            }\n        }\n\n    if (!JS_IsUndefined(jsc->replacer_func)) {\n        args[0] = key;\n        args[1] = val;\n        v = JS_Call(ctx, jsc->replacer_func, holder, 2, args);\n        JS_FreeValue(ctx, val);\n        val = v;\n        if (JS_IsException(val))\n            goto exception;\n    }\n\n    switch (JS_VALUE_GET_NORM_TAG(val)) {\n    case JS_TAG_OBJECT:\n        if (JS_IsFunction(ctx, val))\n            break;\n    case JS_TAG_STRING:\n    case JS_TAG_INT:\n    case JS_TAG_FLOAT64:\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_FLOAT:\n#endif\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n#endif\n    case JS_TAG_EXCEPTION:\n        return val;\n    default:\n        break;\n    }\n    JS_FreeValue(ctx, val);\n    return JS_UNDEFINED;\n\nexception:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic int js_json_to_str(JSContext *ctx, JSONStringifyContext *jsc,\n                          JSValueConst holder, JSValue val,\n                          JSValueConst indent)\n{\n    JSValue indent1, sep, sep1, tab, v, prop;\n    JSObject *p;\n    int64_t i, len;\n    int cl, ret;\n    BOOL has_content;\n    \n    indent1 = JS_UNDEFINED;\n    sep = JS_UNDEFINED;\n    sep1 = JS_UNDEFINED;\n    tab = JS_UNDEFINED;\n    prop = JS_UNDEFINED;\n\n    switch (JS_VALUE_GET_NORM_TAG(val)) {\n    case JS_TAG_OBJECT:\n        p = JS_VALUE_GET_OBJ(val);\n        cl = p->class_id;\n        if (cl == JS_CLASS_STRING) {\n            val = JS_ToStringFree(ctx, val);\n            if (JS_IsException(val))\n                goto exception;\n            val = JS_ToQuotedStringFree(ctx, val);\n            if (JS_IsException(val))\n                goto exception;\n            return string_buffer_concat_value_free(jsc->b, val);\n        } else if (cl == JS_CLASS_NUMBER) {\n            val = JS_ToNumberFree(ctx, val);\n            if (JS_IsException(val))\n                goto exception;\n            return string_buffer_concat_value_free(jsc->b, val);\n        } else if (cl == JS_CLASS_BOOLEAN) {\n            ret = string_buffer_concat_value(jsc->b, p->u.object_data);\n            JS_FreeValue(ctx, val);\n            return ret;\n        }\n#ifdef CONFIG_BIGNUM\n        else if (cl == JS_CLASS_BIG_FLOAT) {\n            return string_buffer_concat_value_free(jsc->b, val);\n        } else if (cl == JS_CLASS_BIG_INT) {\n            JS_ThrowTypeError(ctx, \"bigint are forbidden in JSON.stringify\");\n            goto exception;\n        }\n#endif\n        v = js_array_includes(ctx, jsc->stack, 1, (JSValueConst *)&val);\n        if (JS_IsException(v))\n            goto exception;\n        if (JS_ToBoolFree(ctx, v)) {\n            JS_ThrowTypeError(ctx, \"circular reference\");\n            goto exception;\n        }\n        indent1 = JS_ConcatString(ctx, JS_DupValue(ctx, indent), JS_DupValue(ctx, jsc->gap));\n        if (JS_IsException(indent1))\n            goto exception;\n        if (!JS_IsEmptyString(jsc->gap)) {\n            sep = JS_ConcatString3(ctx, \"\\n\", JS_DupValue(ctx, indent1), \"\");\n            if (JS_IsException(sep))\n                goto exception;\n            sep1 = JS_NewString(ctx, \" \");\n            if (JS_IsException(sep1))\n                goto exception;\n        } else {\n            sep = JS_DupValue(ctx, jsc->empty);\n            sep1 = JS_DupValue(ctx, jsc->empty);\n        }\n        v = js_array_push(ctx, jsc->stack, 1, (JSValueConst *)&val, 0);\n        if (check_exception_free(ctx, v))\n            goto exception;\n        ret = JS_IsArray(ctx, val);\n        if (ret < 0)\n            goto exception;\n        if (ret) {\n            if (js_get_length64(ctx, &len, val))\n                goto exception;\n            string_buffer_putc8(jsc->b, '[');\n            for(i = 0; i < len; i++) {\n                if (i > 0)\n                    string_buffer_putc8(jsc->b, ',');\n                string_buffer_concat_value(jsc->b, sep);\n                v = JS_GetPropertyInt64(ctx, val, i);\n                if (JS_IsException(v))\n                    goto exception;\n                /* XXX: could do this string conversion only when needed */\n                prop = JS_ToStringFree(ctx, JS_NewInt64(ctx, i));\n                if (JS_IsException(prop))\n                    goto exception;\n                v = js_json_check(ctx, jsc, val, v, prop);\n                JS_FreeValue(ctx, prop);\n                prop = JS_UNDEFINED;\n                if (JS_IsException(v))\n                    goto exception;\n                if (JS_IsUndefined(v))\n                    v = JS_NULL;\n                if (js_json_to_str(ctx, jsc, val, v, indent1))\n                    goto exception;\n            }\n            if (len > 0 && !JS_IsEmptyString(jsc->gap)) {\n                string_buffer_putc8(jsc->b, '\\n');\n                string_buffer_concat_value(jsc->b, indent);\n            }\n            string_buffer_putc8(jsc->b, ']');\n        } else {\n            if (!JS_IsUndefined(jsc->property_list))\n                tab = JS_DupValue(ctx, jsc->property_list);\n            else\n                tab = js_object_keys(ctx, JS_UNDEFINED, 1, (JSValueConst *)&val, JS_ITERATOR_KIND_KEY);\n            if (JS_IsException(tab))\n                goto exception;\n            if (js_get_length64(ctx, &len, tab))\n                goto exception;\n            string_buffer_putc8(jsc->b, '{');\n            has_content = FALSE;\n            for(i = 0; i < len; i++) {\n                JS_FreeValue(ctx, prop);\n                prop = JS_GetPropertyInt64(ctx, tab, i);\n                if (JS_IsException(prop))\n                    goto exception;\n                v = JS_GetPropertyValue(ctx, val, JS_DupValue(ctx, prop));\n                if (JS_IsException(v))\n                    goto exception;\n                v = js_json_check(ctx, jsc, val, v, prop);\n                if (JS_IsException(v))\n                    goto exception;\n                if (!JS_IsUndefined(v)) {\n                    if (has_content)\n                        string_buffer_putc8(jsc->b, ',');\n                    prop = JS_ToQuotedStringFree(ctx, prop);\n                    if (JS_IsException(prop)) {\n                        JS_FreeValue(ctx, v);\n                        goto exception;\n                    }\n                    string_buffer_concat_value(jsc->b, sep);\n                    string_buffer_concat_value(jsc->b, prop);\n                    string_buffer_putc8(jsc->b, ':');\n                    string_buffer_concat_value(jsc->b, sep1);\n                    if (js_json_to_str(ctx, jsc, val, v, indent1))\n                        goto exception;\n                    has_content = TRUE;\n                }\n            }\n            if (has_content && JS_VALUE_GET_STRING(jsc->gap)->len != 0) {\n                string_buffer_putc8(jsc->b, '\\n');\n                string_buffer_concat_value(jsc->b, indent);\n            }\n            string_buffer_putc8(jsc->b, '}');\n        }\n        if (check_exception_free(ctx, js_array_pop(ctx, jsc->stack, 0, NULL, 0)))\n            goto exception;\n        JS_FreeValue(ctx, val);\n        JS_FreeValue(ctx, tab);\n        JS_FreeValue(ctx, sep);\n        JS_FreeValue(ctx, sep1);\n        JS_FreeValue(ctx, indent1);\n        JS_FreeValue(ctx, prop);\n        return 0;\n    case JS_TAG_STRING:\n        val = JS_ToQuotedStringFree(ctx, val);\n        if (JS_IsException(val))\n            goto exception;\n        goto concat_value;\n    case JS_TAG_FLOAT64:\n        if (!isfinite(JS_VALUE_GET_FLOAT64(val))) {\n            val = JS_NULL;\n        }\n        goto concat_value;\n    case JS_TAG_INT:\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_FLOAT:\n#endif\n    case JS_TAG_BOOL:\n    case JS_TAG_NULL:\n    concat_value:\n        return string_buffer_concat_value_free(jsc->b, val);\n#ifdef CONFIG_BIGNUM\n    case JS_TAG_BIG_INT:\n        JS_ThrowTypeError(ctx, \"bigint are forbidden in JSON.stringify\");\n        goto exception;\n#endif\n    default:\n        JS_FreeValue(ctx, val);\n        return 0;\n    }\n    \nexception:\n    JS_FreeValue(ctx, val);\n    JS_FreeValue(ctx, tab);\n    JS_FreeValue(ctx, sep);\n    JS_FreeValue(ctx, sep1);\n    JS_FreeValue(ctx, indent1);\n    JS_FreeValue(ctx, prop);\n    return -1;\n}\n\nJSValue JS_JSONStringify(JSContext *ctx, JSValueConst obj,\n                         JSValueConst replacer, JSValueConst space0)\n{\n    StringBuffer b_s;\n    JSONStringifyContext jsc_s, *jsc = &jsc_s;\n    JSValue val, v, space, ret, wrapper;\n    int res;\n    int64_t i, j, n;\n\n    jsc->replacer_func = JS_UNDEFINED;\n    jsc->stack = JS_UNDEFINED;\n    jsc->property_list = JS_UNDEFINED;\n    jsc->gap = JS_UNDEFINED;\n    jsc->b = &b_s;\n    jsc->empty = JS_AtomToString(ctx, JS_ATOM_empty_string);\n    ret = JS_UNDEFINED;\n    wrapper = JS_UNDEFINED;\n\n    string_buffer_init(ctx, jsc->b, 0);\n    jsc->stack = JS_NewArray(ctx);\n    if (JS_IsException(jsc->stack))\n        goto exception;\n    if (JS_IsFunction(ctx, replacer)) {\n        jsc->replacer_func = replacer;\n    } else {\n        res = JS_IsArray(ctx, replacer);\n        if (res < 0)\n            goto exception;\n        if (res) {\n            /* XXX: enumeration is not fully correct */\n            jsc->property_list = JS_NewArray(ctx);\n            if (JS_IsException(jsc->property_list))\n                goto exception;\n            if (js_get_length64(ctx, &n, replacer))\n                goto exception;\n            for (i = j = 0; i < n; i++) {\n                JSValue present;\n                v = JS_GetPropertyInt64(ctx, replacer, i);\n                if (JS_IsException(v))\n                    goto exception;\n                if (JS_IsObject(v)) {\n                    JSObject *p = JS_VALUE_GET_OBJ(v);\n                    if (p->class_id == JS_CLASS_STRING ||\n                        p->class_id == JS_CLASS_NUMBER) {\n                        v = JS_ToStringFree(ctx, v);\n                        if (JS_IsException(v))\n                            goto exception;\n                    } else {\n                        JS_FreeValue(ctx, v);\n                        continue;\n                    }\n                } else if (JS_IsNumber(v)) {\n                    v = JS_ToStringFree(ctx, v);\n                    if (JS_IsException(v))\n                        goto exception;\n                } else if (!JS_IsString(v)) {\n                    JS_FreeValue(ctx, v);\n                    continue;\n                }\n                present = js_array_includes(ctx, jsc->property_list,\n                                            1, (JSValueConst *)&v);\n                if (JS_IsException(present)) {\n                    JS_FreeValue(ctx, v);\n                    goto exception;\n                }\n                if (!JS_ToBoolFree(ctx, present)) {\n                    JS_SetPropertyInt64(ctx, jsc->property_list, j++, v);\n                } else {\n                    JS_FreeValue(ctx, v);\n                }\n            }\n        }\n    }\n    space = JS_DupValue(ctx, space0);\n    if (JS_IsObject(space)) {\n        JSObject *p = JS_VALUE_GET_OBJ(space);\n        if (p->class_id == JS_CLASS_NUMBER) {\n            space = JS_ToNumberFree(ctx, space);\n        } else if (p->class_id == JS_CLASS_STRING) {\n            space = JS_ToStringFree(ctx, space);\n        }\n        if (JS_IsException(space)) {\n            JS_FreeValue(ctx, space);\n            goto exception;\n        }\n    }\n    if (JS_IsNumber(space)) {\n        int n;\n        if (JS_ToInt32Clamp(ctx, &n, space, 0, 10, 0))\n            goto exception;\n        jsc->gap = JS_NewStringLen(ctx, \"          \", n);\n    } else if (JS_IsString(space)) {\n        JSString *p = JS_VALUE_GET_STRING(space);\n        jsc->gap = js_sub_string(ctx, p, 0, min_int(p->len, 10));\n    } else {\n        jsc->gap = JS_DupValue(ctx, jsc->empty);\n    }\n    JS_FreeValue(ctx, space);\n    if (JS_IsException(jsc->gap))\n        goto exception;\n    wrapper = JS_NewObject(ctx);\n    if (JS_IsException(wrapper))\n        goto exception;\n    if (JS_DefinePropertyValue(ctx, wrapper, JS_ATOM_empty_string,\n                               JS_DupValue(ctx, obj), JS_PROP_C_W_E) < 0)\n        goto exception;\n    val = JS_DupValue(ctx, obj);\n                           \n    val = js_json_check(ctx, jsc, wrapper, val, jsc->empty);\n    if (JS_IsException(val))\n        goto exception;\n    if (JS_IsUndefined(val)) {\n        ret = JS_UNDEFINED;\n        goto done1;\n    }\n    if (js_json_to_str(ctx, jsc, wrapper, val, jsc->empty))\n        goto exception;\n\n    ret = string_buffer_end(jsc->b);\n    goto done;\n\nexception:\n    ret = JS_EXCEPTION;\ndone1:\n    string_buffer_free(jsc->b);\ndone:\n    JS_FreeValue(ctx, wrapper);\n    JS_FreeValue(ctx, jsc->empty);\n    JS_FreeValue(ctx, jsc->gap);\n    JS_FreeValue(ctx, jsc->property_list);\n    JS_FreeValue(ctx, jsc->stack);\n    return ret;\n}\n\nstatic JSValue js_json_stringify(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    // stringify(val, replacer, space)\n    return JS_JSONStringify(ctx, argv[0], argv[1], argv[2]);\n}\n\nstatic const JSCFunctionListEntry js_json_funcs[] = {\n    JS_CFUNC_DEF(\"parse\", 2, js_json_parse ),\n    JS_CFUNC_DEF(\"stringify\", 3, js_json_stringify ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"JSON\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_json_obj[] = {\n    JS_OBJECT_DEF(\"JSON\", js_json_funcs, countof(js_json_funcs), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),\n};\n\nvoid JS_AddIntrinsicJSON(JSContext *ctx)\n{\n    /* add JSON as autoinit object */\n    JS_SetPropertyFunctionList(ctx, ctx->global_obj, js_json_obj, countof(js_json_obj));\n}\n\n/* Reflect */\n\nstatic JSValue js_reflect_apply(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    return js_function_apply(ctx, argv[0], max_int(0, argc - 1), argv + 1, 2);\n}\n\nstatic JSValue js_reflect_construct(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSValueConst func, array_arg, new_target;\n    JSValue *tab, ret;\n    uint32_t len;\n\n    func = argv[0];\n    array_arg = argv[1];\n    if (argc > 2) {\n        new_target = argv[2];\n        if (!JS_IsConstructor(ctx, new_target))\n            return JS_ThrowTypeError(ctx, \"not a constructor\");\n    } else {\n        new_target = func;\n    }\n    tab = build_arg_list(ctx, &len, array_arg);\n    if (!tab)\n        return JS_EXCEPTION;\n    ret = JS_CallConstructor2(ctx, func, new_target, len, (JSValueConst *)tab);\n    free_arg_list(ctx, tab, len);\n    return ret;\n}\n\nstatic JSValue js_reflect_deleteProperty(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    JSValueConst obj;\n    JSAtom atom;\n    int ret;\n\n    obj = argv[0];\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    atom = JS_ValueToAtom(ctx, argv[1]);\n    if (unlikely(atom == JS_ATOM_NULL))\n        return JS_EXCEPTION;\n    ret = JS_DeleteProperty(ctx, obj, atom, 0);\n    JS_FreeAtom(ctx, atom);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_reflect_get(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    JSValueConst obj, prop, receiver;\n    JSAtom atom;\n    JSValue ret;\n\n    obj = argv[0];\n    prop = argv[1];\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    if (argc > 2)\n        receiver = argv[2];\n    else\n        receiver = obj;\n    atom = JS_ValueToAtom(ctx, prop);\n    if (unlikely(atom == JS_ATOM_NULL))\n        return JS_EXCEPTION;\n    ret = JS_GetPropertyInternal(ctx, obj, atom, receiver, FALSE);\n    JS_FreeAtom(ctx, atom);\n    return ret;\n}\n\nstatic JSValue js_reflect_has(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    JSValueConst obj, prop;\n    JSAtom atom;\n    int ret;\n\n    obj = argv[0];\n    prop = argv[1];\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    atom = JS_ValueToAtom(ctx, prop);\n    if (unlikely(atom == JS_ATOM_NULL))\n        return JS_EXCEPTION;\n    ret = JS_HasProperty(ctx, obj, atom);\n    JS_FreeAtom(ctx, atom);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_reflect_set(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    JSValueConst obj, prop, val, receiver;\n    int ret;\n    JSAtom atom;\n\n    obj = argv[0];\n    prop = argv[1];\n    val = argv[2];\n    if (argc > 3)\n        receiver = argv[3];\n    else\n        receiver = obj;\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    atom = JS_ValueToAtom(ctx, prop);\n    if (unlikely(atom == JS_ATOM_NULL))\n        return JS_EXCEPTION;\n    ret = JS_SetPropertyGeneric(ctx, obj, atom,\n                                JS_DupValue(ctx, val), receiver, 0);\n    JS_FreeAtom(ctx, atom);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_reflect_setPrototypeOf(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    int ret;\n    ret = JS_SetPrototypeInternal(ctx, argv[0], argv[1], FALSE);\n    if (ret < 0)\n        return JS_EXCEPTION;\n    else\n        return JS_NewBool(ctx, ret);\n}\n\nstatic JSValue js_reflect_ownKeys(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    if (JS_VALUE_GET_TAG(argv[0]) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    return JS_GetOwnPropertyNames2(ctx, argv[0],\n                                   JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK,\n                                   JS_ITERATOR_KIND_KEY);\n}\n\nstatic const JSCFunctionListEntry js_reflect_funcs[] = {\n    JS_CFUNC_DEF(\"apply\", 3, js_reflect_apply ),\n    JS_CFUNC_DEF(\"construct\", 2, js_reflect_construct ),\n    JS_CFUNC_MAGIC_DEF(\"defineProperty\", 3, js_object_defineProperty, 1 ),\n    JS_CFUNC_DEF(\"deleteProperty\", 2, js_reflect_deleteProperty ),\n    JS_CFUNC_DEF(\"get\", 2, js_reflect_get ),\n    JS_CFUNC_MAGIC_DEF(\"getOwnPropertyDescriptor\", 2, js_object_getOwnPropertyDescriptor, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"getPrototypeOf\", 1, js_object_getPrototypeOf, 1 ),\n    JS_CFUNC_DEF(\"has\", 2, js_reflect_has ),\n    JS_CFUNC_MAGIC_DEF(\"isExtensible\", 1, js_object_isExtensible, 1 ),\n    JS_CFUNC_DEF(\"ownKeys\", 1, js_reflect_ownKeys ),\n    JS_CFUNC_MAGIC_DEF(\"preventExtensions\", 1, js_object_preventExtensions, 1 ),\n    JS_CFUNC_DEF(\"set\", 3, js_reflect_set ),\n    JS_CFUNC_DEF(\"setPrototypeOf\", 2, js_reflect_setPrototypeOf ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Reflect\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_reflect_obj[] = {\n    JS_OBJECT_DEF(\"Reflect\", js_reflect_funcs, countof(js_reflect_funcs), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),\n};\n\n/* Proxy */\n\nstatic void js_proxy_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSProxyData *s = JS_GetOpaque(val, JS_CLASS_PROXY);\n    if (s) {\n        JS_FreeValueRT(rt, s->target);\n        JS_FreeValueRT(rt, s->handler);\n        js_free_rt(rt, s);\n    }\n}\n\nstatic void js_proxy_mark(JSRuntime *rt, JSValueConst val,\n                          JS_MarkFunc *mark_func)\n{\n    JSProxyData *s = JS_GetOpaque(val, JS_CLASS_PROXY);\n    if (s) {\n        JS_MarkValue(rt, s->target, mark_func);\n        JS_MarkValue(rt, s->handler, mark_func);\n    }\n}\n\nstatic JSValue JS_ThrowTypeErrorRevokedProxy(JSContext *ctx)\n{\n    return JS_ThrowTypeError(ctx, \"revoked proxy\");\n}\n\nstatic JSProxyData *get_proxy_method(JSContext *ctx, JSValue *pmethod,\n                                     JSValueConst obj, JSAtom name)\n{\n    JSProxyData *s = JS_GetOpaque(obj, JS_CLASS_PROXY);\n    JSValue method;\n\n    /* safer to test recursion in all proxy methods */\n    if (js_check_stack_overflow(ctx->rt, 0)) {\n        JS_ThrowStackOverflow(ctx);\n        return NULL;\n    }\n    \n    /* 's' should never be NULL */\n    if (s->is_revoked) {\n        JS_ThrowTypeErrorRevokedProxy(ctx);\n        return NULL;\n    }\n    method = JS_GetProperty(ctx, s->handler, name);\n    if (JS_IsException(method))\n        return NULL;\n    if (JS_IsNull(method))\n        method = JS_UNDEFINED;\n    *pmethod = method;\n    return s;\n}\n\nstatic JSValue js_proxy_getPrototypeOf(JSContext *ctx, JSValueConst obj)\n{\n    JSProxyData *s;\n    JSValue method, ret, proto1;\n    int res;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_getPrototypeOf);\n    if (!s)\n        return JS_EXCEPTION;\n    if (JS_IsUndefined(method))\n        return JS_GetPrototype(ctx, s->target);\n    ret = JS_CallFree(ctx, method, s->handler, 1, (JSValueConst *)&s->target);\n    if (JS_IsException(ret))\n        return ret;\n    if (JS_VALUE_GET_TAG(ret) != JS_TAG_NULL &&\n        JS_VALUE_GET_TAG(ret) != JS_TAG_OBJECT) {\n        goto fail;\n    }\n    res = JS_IsExtensible(ctx, s->target);\n    if (res < 0) {\n        JS_FreeValue(ctx, ret);\n        return JS_EXCEPTION;\n    }\n    if (!res) {\n        /* check invariant */\n        proto1 = JS_GetPrototype(ctx, s->target);\n        if (JS_IsException(proto1)) {\n            JS_FreeValue(ctx, ret);\n            return JS_EXCEPTION;\n        }\n        if (JS_VALUE_GET_OBJ(proto1) != JS_VALUE_GET_OBJ(ret)) {\n            JS_FreeValue(ctx, proto1);\n        fail:\n            JS_FreeValue(ctx, ret);\n            return JS_ThrowTypeError(ctx, \"proxy: inconsistent prototype\");\n        }\n        JS_FreeValue(ctx, proto1);\n    }\n    return ret;\n}\n\nstatic int js_proxy_setPrototypeOf(JSContext *ctx, JSValueConst obj,\n                                   JSValueConst proto_val, BOOL throw_flag)\n{\n    JSProxyData *s;\n    JSValue method, ret, proto1;\n    JSValueConst args[2];\n    BOOL res;\n    int res2;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_setPrototypeOf);\n    if (!s)\n        return -1;\n    if (JS_IsUndefined(method))\n        return JS_SetPrototypeInternal(ctx, s->target, proto_val, throw_flag);\n    args[0] = s->target;\n    args[1] = proto_val;\n    ret = JS_CallFree(ctx, method, s->handler, 2, args);\n    if (JS_IsException(ret))\n        return -1;\n    res = JS_ToBoolFree(ctx, ret);\n    if (!res) {\n        if (throw_flag) {\n            JS_ThrowTypeError(ctx, \"proxy: bad prototype\");\n            return -1;\n        } else {\n            return FALSE;\n        }\n    }\n    res2 = JS_IsExtensible(ctx, s->target);\n    if (res2 < 0)\n        return -1;\n    if (!res2) {\n        proto1 = JS_GetPrototype(ctx, s->target);\n        if (JS_IsException(proto1))\n            return -1;\n        if (JS_VALUE_GET_OBJ(proto_val) != JS_VALUE_GET_OBJ(proto1)) {\n            JS_FreeValue(ctx, proto1);\n            JS_ThrowTypeError(ctx, \"proxy: inconsistent prototype\");\n            return -1;\n        }\n        JS_FreeValue(ctx, proto1);\n    }\n    return TRUE;\n}\n\nstatic int js_proxy_isExtensible(JSContext *ctx, JSValueConst obj)\n{\n    JSProxyData *s;\n    JSValue method, ret;\n    BOOL res;\n    int res2;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_isExtensible);\n    if (!s)\n        return -1;\n    if (JS_IsUndefined(method))\n        return JS_IsExtensible(ctx, s->target);\n    ret = JS_CallFree(ctx, method, s->handler, 1, (JSValueConst *)&s->target);\n    if (JS_IsException(ret))\n        return -1;\n    res = JS_ToBoolFree(ctx, ret);\n    res2 = JS_IsExtensible(ctx, s->target);\n    if (res2 < 0)\n        return res2;\n    if (res != res2) {\n        JS_ThrowTypeError(ctx, \"proxy: inconsistent isExtensible\");\n        return -1;\n    }\n    return res;\n}\n\nstatic int js_proxy_preventExtensions(JSContext *ctx, JSValueConst obj)\n{\n    JSProxyData *s;\n    JSValue method, ret;\n    BOOL res;\n    int res2;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_preventExtensions);\n    if (!s)\n        return -1;\n    if (JS_IsUndefined(method))\n        return JS_PreventExtensions(ctx, s->target);\n    ret = JS_CallFree(ctx, method, s->handler, 1, (JSValueConst *)&s->target);\n    if (JS_IsException(ret))\n        return -1;\n    res = JS_ToBoolFree(ctx, ret);\n    if (res) {\n        res2 = JS_IsExtensible(ctx, s->target);\n        if (res2 < 0)\n            return res2;\n        if (res2) {\n            JS_ThrowTypeError(ctx, \"proxy: inconsistent preventExtensions\");\n            return -1;\n        }\n    }\n    return res;\n}\n\nstatic int js_proxy_has(JSContext *ctx, JSValueConst obj, JSAtom atom)\n{\n    JSProxyData *s;\n    JSValue method, ret1, atom_val;\n    int ret, res;\n    JSObject *p;\n    JSValueConst args[2];\n    BOOL res2;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_has);\n    if (!s)\n        return -1;\n    if (JS_IsUndefined(method))\n        return JS_HasProperty(ctx, s->target, atom);\n    atom_val = JS_AtomToValue(ctx, atom);\n    if (JS_IsException(atom_val)) {\n        JS_FreeValue(ctx, method);\n        return -1;\n    }\n    args[0] = s->target;\n    args[1] = atom_val;\n    ret1 = JS_CallFree(ctx, method, s->handler, 2, args);\n    JS_FreeValue(ctx, atom_val);\n    if (JS_IsException(ret1))\n        return -1;\n    ret = JS_ToBoolFree(ctx, ret1);\n    if (!ret) {\n        JSPropertyDescriptor desc;\n        p = JS_VALUE_GET_OBJ(s->target);\n        res = JS_GetOwnPropertyInternal(ctx, &desc, p, atom);\n        if (res < 0)\n            return -1;\n        if (res) {\n            res2 = !(desc.flags & JS_PROP_CONFIGURABLE);\n            js_free_desc(ctx, &desc);\n            if (res2 || !p->extensible) {\n                JS_ThrowTypeError(ctx, \"proxy: inconsistent has\");\n                return -1;\n            }\n        }\n    }\n    return ret;\n}\n\nstatic JSValue js_proxy_get(JSContext *ctx, JSValueConst obj, JSAtom atom,\n                            JSValueConst receiver)\n{\n    JSProxyData *s;\n    JSValue method, ret, atom_val;\n    int res;\n    JSValueConst args[3];\n    JSPropertyDescriptor desc;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_get);\n    if (!s)\n        return JS_EXCEPTION;\n    /* Note: recursion is possible thru the prototype of s->target */\n    if (JS_IsUndefined(method))\n        return JS_GetPropertyInternal(ctx, s->target, atom, receiver, FALSE);\n    atom_val = JS_AtomToValue(ctx, atom);\n    if (JS_IsException(atom_val)) {\n        JS_FreeValue(ctx, method);\n        return JS_EXCEPTION;\n    }\n    args[0] = s->target;\n    args[1] = atom_val;\n    args[2] = receiver;\n    ret = JS_CallFree(ctx, method, s->handler, 3, args);\n    JS_FreeValue(ctx, atom_val);\n    if (JS_IsException(ret))\n        return JS_EXCEPTION;\n    res = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(s->target), atom);\n    if (res < 0)\n        return JS_EXCEPTION;\n    if (res) {\n        if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) == 0) {\n            if (!js_same_value(ctx, desc.value, ret)) {\n                goto fail;\n            }\n        } else if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE)) == JS_PROP_GETSET) {\n            if (JS_IsUndefined(desc.getter) && !JS_IsUndefined(ret)) {\n            fail:\n                js_free_desc(ctx, &desc);\n                JS_FreeValue(ctx, ret);\n                return JS_ThrowTypeError(ctx, \"proxy: inconsistent get\");\n            }\n        }\n        js_free_desc(ctx, &desc);\n    }\n    return ret;\n}\n\nstatic int js_proxy_set(JSContext *ctx, JSValueConst obj, JSAtom atom,\n                        JSValueConst value, JSValueConst receiver, int flags)\n{\n    JSProxyData *s;\n    JSValue method, ret1, atom_val;\n    int ret, res;\n    JSValueConst args[4];\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_set);\n    if (!s)\n        return -1;\n    if (JS_IsUndefined(method)) {\n        return JS_SetPropertyGeneric(ctx, s->target, atom,\n                                     JS_DupValue(ctx, value), receiver,\n                                     flags);\n    }\n    atom_val = JS_AtomToValue(ctx, atom);\n    if (JS_IsException(atom_val)) {\n        JS_FreeValue(ctx, method);\n        return -1;\n    }\n    args[0] = s->target;\n    args[1] = atom_val;\n    args[2] = value;\n    args[3] = receiver;\n    ret1 = JS_CallFree(ctx, method, s->handler, 4, args);\n    JS_FreeValue(ctx, atom_val);\n    if (JS_IsException(ret1))\n        return -1;\n    ret = JS_ToBoolFree(ctx, ret1);\n    if (ret) {\n        JSPropertyDescriptor desc;\n        res = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(s->target), atom);\n        if (res < 0)\n            return -1;\n        if (res) {\n            if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) == 0) {\n                if (!js_same_value(ctx, desc.value, value)) {\n                    goto fail;\n                }\n            } else if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE)) == JS_PROP_GETSET && JS_IsUndefined(desc.setter)) {\n                fail:\n                    js_free_desc(ctx, &desc);\n                    JS_ThrowTypeError(ctx, \"proxy: inconsistent set\");\n                    return -1;\n            }\n            js_free_desc(ctx, &desc);\n        }\n    } else {\n        if ((flags & JS_PROP_THROW) ||\n            ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) {\n            JS_ThrowTypeError(ctx, \"proxy: cannot set property\");\n            return -1;\n        }\n    }\n    return ret;\n}\n\nstatic JSValue js_create_desc(JSContext *ctx, JSValueConst val,\n                              JSValueConst getter, JSValueConst setter,\n                              int flags)\n{\n    JSValue ret;\n    ret = JS_NewObject(ctx);\n    if (JS_IsException(ret))\n        return ret;\n    if (flags & JS_PROP_HAS_GET) {\n        JS_DefinePropertyValue(ctx, ret, JS_ATOM_get, JS_DupValue(ctx, getter),\n                               JS_PROP_C_W_E);\n    }\n    if (flags & JS_PROP_HAS_SET) {\n        JS_DefinePropertyValue(ctx, ret, JS_ATOM_set, JS_DupValue(ctx, setter),\n                               JS_PROP_C_W_E);\n    }\n    if (flags & JS_PROP_HAS_VALUE) {\n        JS_DefinePropertyValue(ctx, ret, JS_ATOM_value, JS_DupValue(ctx, val),\n                               JS_PROP_C_W_E);\n    }\n    if (flags & JS_PROP_HAS_WRITABLE) {\n        JS_DefinePropertyValue(ctx, ret, JS_ATOM_writable,\n                               JS_NewBool(ctx, (flags & JS_PROP_WRITABLE) != 0),\n                               JS_PROP_C_W_E);\n    }\n    if (flags & JS_PROP_HAS_ENUMERABLE) {\n        JS_DefinePropertyValue(ctx, ret, JS_ATOM_enumerable,\n                               JS_NewBool(ctx, (flags & JS_PROP_ENUMERABLE) != 0),\n                               JS_PROP_C_W_E);\n    }\n    if (flags & JS_PROP_HAS_CONFIGURABLE) {\n        JS_DefinePropertyValue(ctx, ret, JS_ATOM_configurable,\n                               JS_NewBool(ctx, (flags & JS_PROP_CONFIGURABLE) != 0),\n                               JS_PROP_C_W_E);\n    }\n    return ret;\n}\n\nstatic int js_proxy_get_own_property(JSContext *ctx, JSPropertyDescriptor *pdesc,\n                                     JSValueConst obj, JSAtom prop)\n{\n    JSProxyData *s;\n    JSValue method, trap_result_obj, prop_val;\n    int res, target_desc_ret, ret;\n    JSObject *p;\n    JSValueConst args[2];\n    JSPropertyDescriptor result_desc, target_desc;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_getOwnPropertyDescriptor);\n    if (!s)\n        return -1;\n    p = JS_VALUE_GET_OBJ(s->target);\n    if (JS_IsUndefined(method)) {\n        return JS_GetOwnPropertyInternal(ctx, pdesc, p, prop);\n    }\n    prop_val = JS_AtomToValue(ctx, prop);\n    if (JS_IsException(prop_val)) {\n        JS_FreeValue(ctx, method);\n        return -1;\n    }\n    args[0] = s->target;\n    args[1] = prop_val;\n    trap_result_obj = JS_CallFree(ctx, method, s->handler, 2, args);\n    JS_FreeValue(ctx, prop_val);\n    if (JS_IsException(trap_result_obj))\n        return -1;\n    if (!JS_IsObject(trap_result_obj) && !JS_IsUndefined(trap_result_obj)) {\n        JS_FreeValue(ctx, trap_result_obj);\n        goto fail;\n    }\n    target_desc_ret = JS_GetOwnPropertyInternal(ctx, &target_desc, p, prop);\n    if (target_desc_ret < 0) {\n        JS_FreeValue(ctx, trap_result_obj);\n        return -1;\n    }\n    if (target_desc_ret)\n        js_free_desc(ctx, &target_desc);\n    if (JS_IsUndefined(trap_result_obj)) {\n        if (target_desc_ret) {\n            if (!(target_desc.flags & JS_PROP_CONFIGURABLE) || !p->extensible)\n                goto fail;\n        }\n        ret = FALSE;\n    } else {\n        int flags1, extensible_target;\n        extensible_target = JS_IsExtensible(ctx, s->target);\n        if (extensible_target < 0) {\n            JS_FreeValue(ctx, trap_result_obj);\n            return -1;\n        }\n        res = js_obj_to_desc(ctx, &result_desc, trap_result_obj);\n        JS_FreeValue(ctx, trap_result_obj);\n        if (res < 0)\n            return -1;\n        \n        if (target_desc_ret) {\n            /* convert result_desc.flags to defineProperty flags */\n            flags1 = result_desc.flags | JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_ENUMERABLE;\n            if (result_desc.flags & JS_PROP_GETSET)\n                flags1 |= JS_PROP_HAS_GET | JS_PROP_HAS_SET;\n            else\n                flags1 |= JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE;\n            /* XXX: not complete check: need to compare value &\n               getter/setter as in defineproperty */\n            if (!check_define_prop_flags(target_desc.flags, flags1))\n                goto fail1;\n        } else {\n            if (!extensible_target)\n                goto fail1;\n        }\n        if (!(result_desc.flags & JS_PROP_CONFIGURABLE)) {\n            if (!target_desc_ret || (target_desc.flags & JS_PROP_CONFIGURABLE))\n                goto fail1;\n            if ((result_desc.flags &\n                 (JS_PROP_GETSET | JS_PROP_WRITABLE)) == 0 &&\n                target_desc_ret &&\n                (target_desc.flags & JS_PROP_WRITABLE) != 0) {\n                /* proxy-missing-checks */\n            fail1:\n                js_free_desc(ctx, &result_desc);\n            fail:\n                JS_ThrowTypeError(ctx, \"proxy: inconsistent getOwnPropertyDescriptor\");\n                return -1;\n            }\n        }\n        ret = TRUE;\n        if (pdesc) {\n            *pdesc = result_desc;\n        } else {\n            js_free_desc(ctx, &result_desc);\n        }\n    }\n    return ret;\n}\n\nstatic int js_proxy_define_own_property(JSContext *ctx, JSValueConst obj,\n                                        JSAtom prop, JSValueConst val,\n                                        JSValueConst getter, JSValueConst setter,\n                                        int flags)\n{\n    JSProxyData *s;\n    JSValue method, ret1, prop_val, desc_val;\n    int res, ret;\n    JSObject *p;\n    JSValueConst args[3];\n    JSPropertyDescriptor desc;\n    BOOL setting_not_configurable;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_defineProperty);\n    if (!s)\n        return -1;\n    if (JS_IsUndefined(method)) {\n        return JS_DefineProperty(ctx, s->target, prop, val, getter, setter, flags);\n    }\n    prop_val = JS_AtomToValue(ctx, prop);\n    if (JS_IsException(prop_val)) {\n        JS_FreeValue(ctx, method);\n        return -1;\n    }\n    desc_val = js_create_desc(ctx, val, getter, setter, flags);\n    if (JS_IsException(desc_val)) {\n        JS_FreeValue(ctx, prop_val);\n        JS_FreeValue(ctx, method);\n        return -1;\n    }\n    args[0] = s->target;\n    args[1] = prop_val;\n    args[2] = desc_val;\n    ret1 = JS_CallFree(ctx, method, s->handler, 3, args);\n    JS_FreeValue(ctx, prop_val);\n    JS_FreeValue(ctx, desc_val);\n    if (JS_IsException(ret1))\n        return -1;\n    ret = JS_ToBoolFree(ctx, ret1);\n    if (!ret) {\n        if (flags & JS_PROP_THROW) {\n            JS_ThrowTypeError(ctx, \"proxy: defineProperty exception\");\n            return -1;\n        } else {\n            return 0;\n        }\n    }\n    p = JS_VALUE_GET_OBJ(s->target);\n    res = JS_GetOwnPropertyInternal(ctx, &desc, p, prop);\n    if (res < 0)\n        return -1;\n    setting_not_configurable = ((flags & (JS_PROP_HAS_CONFIGURABLE |\n                                          JS_PROP_CONFIGURABLE)) ==\n                                JS_PROP_HAS_CONFIGURABLE);\n    if (!res) {\n        if (!p->extensible || setting_not_configurable)\n            goto fail;\n    } else {\n        if (!check_define_prop_flags(desc.flags, flags) ||\n            ((desc.flags & JS_PROP_CONFIGURABLE) && setting_not_configurable)) {\n            goto fail1;\n        }\n        if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) {\n            if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE)) ==\n                JS_PROP_GETSET) {\n                if ((flags & JS_PROP_HAS_GET) &&\n                    !js_same_value(ctx, getter, desc.getter)) {\n                    goto fail1;\n                }\n                if ((flags & JS_PROP_HAS_SET) &&\n                    !js_same_value(ctx, setter, desc.setter)) {\n                    goto fail1;\n                }\n            }\n        } else if (flags & JS_PROP_HAS_VALUE) {\n            if ((desc.flags & (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) ==\n                JS_PROP_WRITABLE && !(flags & JS_PROP_WRITABLE)) {\n                /* missing-proxy-check feature */\n                goto fail1;\n            } else if ((desc.flags & (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) == 0 &&\n                !js_same_value(ctx, val, desc.value)) {\n                goto fail1;\n            }\n        }\n        if (flags & JS_PROP_HAS_WRITABLE) {\n            if ((desc.flags & (JS_PROP_GETSET | JS_PROP_CONFIGURABLE |\n                               JS_PROP_WRITABLE)) == JS_PROP_WRITABLE) {\n                /* proxy-missing-checks */\n            fail1:\n                js_free_desc(ctx, &desc);\n            fail:\n                JS_ThrowTypeError(ctx, \"proxy: inconsistent defineProperty\");\n                return -1;\n            }\n        }\n        js_free_desc(ctx, &desc);\n    }\n    return 1;\n}\n\nstatic int js_proxy_delete_property(JSContext *ctx, JSValueConst obj,\n                                    JSAtom atom)\n{\n    JSProxyData *s;\n    JSValue method, ret, atom_val;\n    int res, res2, is_extensible;\n    JSValueConst args[2];\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_deleteProperty);\n    if (!s)\n        return -1;\n    if (JS_IsUndefined(method)) {\n        return JS_DeleteProperty(ctx, s->target, atom, 0);\n    }\n    atom_val = JS_AtomToValue(ctx, atom);;\n    if (JS_IsException(atom_val)) {\n        JS_FreeValue(ctx, method);\n        return -1;\n    }\n    args[0] = s->target;\n    args[1] = atom_val;\n    ret = JS_CallFree(ctx, method, s->handler, 2, args);\n    JS_FreeValue(ctx, atom_val);\n    if (JS_IsException(ret))\n        return -1;\n    res = JS_ToBoolFree(ctx, ret);\n    if (res) {\n        JSPropertyDescriptor desc;\n        res2 = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(s->target), atom);\n        if (res2 < 0)\n            return -1;\n        if (res2) {\n            if (!(desc.flags & JS_PROP_CONFIGURABLE))\n                goto fail;\n            is_extensible = JS_IsExtensible(ctx, s->target);\n            if (is_extensible < 0)\n                goto fail1;\n            if (!is_extensible) {\n                /* proxy-missing-checks */\n            fail:\n                JS_ThrowTypeError(ctx, \"proxy: inconsistent deleteProperty\");\n            fail1:\n                js_free_desc(ctx, &desc);\n                return -1;\n            }\n            js_free_desc(ctx, &desc);\n        }\n    }\n    return res;\n}\n\n/* return the index of the property or -1 if not found */\nstatic int find_prop_key(const JSPropertyEnum *tab, int n, JSAtom atom)\n{\n    int i;\n    for(i = 0; i < n; i++) {\n        if (tab[i].atom == atom)\n            return i;\n    }\n    return -1;\n}\n\nstatic int js_proxy_get_own_property_names(JSContext *ctx,\n                                           JSPropertyEnum **ptab,\n                                           uint32_t *plen,\n                                           JSValueConst obj)\n{\n    JSProxyData *s;\n    JSValue method, prop_array, val;\n    uint32_t len, i, len2;\n    JSPropertyEnum *tab, *tab2;\n    JSAtom atom;\n    JSPropertyDescriptor desc;\n    int res, is_extensible, idx;\n\n    s = get_proxy_method(ctx, &method, obj, JS_ATOM_ownKeys);\n    if (!s)\n        return -1;\n    if (JS_IsUndefined(method)) {\n        return JS_GetOwnPropertyNamesInternal(ctx, ptab, plen,\n                                      JS_VALUE_GET_OBJ(s->target),\n                                      JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK);\n    }\n    prop_array = JS_CallFree(ctx, method, s->handler, 1, (JSValueConst *)&s->target);\n    if (JS_IsException(prop_array))\n        return -1;\n    tab = NULL;\n    len = 0;\n    tab2 = NULL;\n    len2 = 0;\n    if (js_get_length32(ctx, &len, prop_array))\n        goto fail;\n    if (len > 0) {\n        tab = js_mallocz(ctx, sizeof(tab[0]) * len);\n        if (!tab)\n            goto fail;\n    }\n    for(i = 0; i < len; i++) {\n        val = JS_GetPropertyUint32(ctx, prop_array, i);\n        if (JS_IsException(val))\n            goto fail;\n        if (!JS_IsString(val) && !JS_IsSymbol(val)) {\n            JS_FreeValue(ctx, val);\n            JS_ThrowTypeError(ctx, \"proxy: properties must be strings or symbols\");\n            goto fail;\n        }\n        atom = JS_ValueToAtom(ctx, val);\n        JS_FreeValue(ctx, val);\n        if (atom == JS_ATOM_NULL)\n            goto fail;\n        tab[i].atom = atom;\n        tab[i].is_enumerable = FALSE; /* XXX: redundant? */\n    }\n\n    /* check duplicate properties (XXX: inefficient, could store the\n     * properties an a temporary object to use the hash) */\n    for(i = 1; i < len; i++) {\n        if (find_prop_key(tab, i, tab[i].atom) >= 0) {\n            JS_ThrowTypeError(ctx, \"proxy: duplicate property\");\n            goto fail;\n        }\n    }\n\n    is_extensible = JS_IsExtensible(ctx, s->target);\n    if (is_extensible < 0)\n        goto fail;\n\n    /* check if there are non configurable properties */\n    if (s->is_revoked) {\n        JS_ThrowTypeErrorRevokedProxy(ctx);\n        goto fail;\n    }\n    if (JS_GetOwnPropertyNamesInternal(ctx, &tab2, &len2, JS_VALUE_GET_OBJ(s->target),\n                               JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK))\n        goto fail;\n    for(i = 0; i < len2; i++) {\n        if (s->is_revoked) {\n            JS_ThrowTypeErrorRevokedProxy(ctx);\n            goto fail;\n        }\n        res = JS_GetOwnPropertyInternal(ctx, &desc, JS_VALUE_GET_OBJ(s->target),\n                                tab2[i].atom);\n        if (res < 0)\n            goto fail;\n        if (res) {  /* safety, property should be found */\n            js_free_desc(ctx, &desc);\n            if (!(desc.flags & JS_PROP_CONFIGURABLE) || !is_extensible) {\n                idx = find_prop_key(tab, len, tab2[i].atom);\n                if (idx < 0) {\n                    JS_ThrowTypeError(ctx, \"proxy: target property must be present in proxy ownKeys\");\n                    goto fail;\n                }\n                /* mark the property as found */\n                if (!is_extensible)\n                    tab[idx].is_enumerable = TRUE;\n            }\n        }\n    }\n    if (!is_extensible) {\n        /* check that all property in 'tab' were checked */\n        for(i = 0; i < len; i++) {\n            if (!tab[i].is_enumerable) {\n                JS_ThrowTypeError(ctx, \"proxy: property not present in target were returned by non extensible proxy\");\n                goto fail;\n            }\n        }\n    }\n\n    js_free_prop_enum(ctx, tab2, len2);\n    JS_FreeValue(ctx, prop_array);\n    *ptab = tab;\n    *plen = len;\n    return 0;\n fail:\n    js_free_prop_enum(ctx, tab2, len2);\n    js_free_prop_enum(ctx, tab, len);\n    JS_FreeValue(ctx, prop_array);\n    return -1;\n}\n\nstatic JSValue js_proxy_call_constructor(JSContext *ctx, JSValueConst func_obj,\n                                         JSValueConst new_target,\n                                         int argc, JSValueConst *argv)\n{\n    JSProxyData *s;\n    JSValue method, arg_array, ret;\n    JSValueConst args[3];\n\n    s = get_proxy_method(ctx, &method, func_obj, JS_ATOM_construct);\n    if (!s)\n        return JS_EXCEPTION;\n    if (!JS_IsConstructor(ctx, s->target))\n        return JS_ThrowTypeError(ctx, \"not a constructor\");\n    if (JS_IsUndefined(method))\n        return JS_CallConstructor2(ctx, s->target, new_target, argc, argv);\n    arg_array = js_create_array(ctx, argc, argv);\n    if (JS_IsException(arg_array)) {\n        ret = JS_EXCEPTION;\n        goto fail;\n    }\n    args[0] = s->target;\n    args[1] = arg_array;\n    args[2] = new_target;\n    ret = JS_Call(ctx, method, s->handler, 3, args);\n    if (!JS_IsException(ret) && JS_VALUE_GET_TAG(ret) != JS_TAG_OBJECT) {\n        JS_FreeValue(ctx, ret);\n        ret = JS_ThrowTypeErrorNotAnObject(ctx);\n    }\n fail:\n    JS_FreeValue(ctx, method);\n    JS_FreeValue(ctx, arg_array);\n    return ret;\n}\n\nstatic JSValue js_proxy_call(JSContext *ctx, JSValueConst func_obj,\n                             JSValueConst this_obj,\n                             int argc, JSValueConst *argv, int flags)\n{\n    JSProxyData *s;\n    JSValue method, arg_array, ret;\n    JSValueConst args[3];\n\n    if (flags & JS_CALL_FLAG_CONSTRUCTOR)\n        return js_proxy_call_constructor(ctx, func_obj, this_obj, argc, argv);\n    \n    s = get_proxy_method(ctx, &method, func_obj, JS_ATOM_apply);\n    if (!s)\n        return JS_EXCEPTION;\n    if (!s->is_func) {\n        JS_FreeValue(ctx, method);\n        return JS_ThrowTypeError(ctx, \"not a function\");\n    }\n    if (JS_IsUndefined(method))\n        return JS_Call(ctx, s->target, this_obj, argc, argv);\n    arg_array = js_create_array(ctx, argc, argv);\n    if (JS_IsException(arg_array)) {\n        ret = JS_EXCEPTION;\n        goto fail;\n    }\n    args[0] = s->target;\n    args[1] = this_obj;\n    args[2] = arg_array;\n    ret = JS_Call(ctx, method, s->handler, 3, args);\n fail:\n    JS_FreeValue(ctx, method);\n    JS_FreeValue(ctx, arg_array);\n    return ret;\n}\n\nstatic int js_proxy_isArray(JSContext *ctx, JSValueConst obj)\n{\n    JSProxyData *s = JS_GetOpaque(obj, JS_CLASS_PROXY);\n    if (!s)\n        return FALSE;\n    if (s->is_revoked) {\n        JS_ThrowTypeErrorRevokedProxy(ctx);\n        return -1;\n    }\n    return JS_IsArray(ctx, s->target);\n}\n\nstatic const JSClassExoticMethods js_proxy_exotic_methods = {\n    .get_own_property = js_proxy_get_own_property,\n    .define_own_property = js_proxy_define_own_property,\n    .delete_property = js_proxy_delete_property,\n    .get_own_property_names = js_proxy_get_own_property_names,\n    .has_property = js_proxy_has,\n    .get_property = js_proxy_get,\n    .set_property = js_proxy_set,\n};\n\nstatic JSValue js_proxy_constructor(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSValueConst target, handler;\n    JSValue obj;\n    JSProxyData *s;\n\n    target = argv[0];\n    handler = argv[1];\n    if (JS_VALUE_GET_TAG(target) != JS_TAG_OBJECT ||\n        JS_VALUE_GET_TAG(handler) != JS_TAG_OBJECT)\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    obj = JS_NewObjectProtoClass(ctx, JS_NULL, JS_CLASS_PROXY);\n    if (JS_IsException(obj))\n        return obj;\n    s = js_malloc(ctx, sizeof(JSProxyData));\n    if (!s) {\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    s->target = JS_DupValue(ctx, target);\n    s->handler = JS_DupValue(ctx, handler);\n    s->is_func = JS_IsFunction(ctx, target);\n    s->is_revoked = FALSE;\n    JS_SetOpaque(obj, s);\n    JS_SetConstructorBit(ctx, obj, JS_IsConstructor(ctx, target));\n    return obj;\n}\n\nstatic JSValue js_proxy_revoke(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv, int magic,\n                               JSValue *func_data)\n{\n    JSProxyData *s = JS_GetOpaque(func_data[0], JS_CLASS_PROXY);\n    if (s) {\n        /* We do not free the handler and target in case they are\n           referenced as constants in the C call stack */\n        s->is_revoked = TRUE;\n        JS_FreeValue(ctx, func_data[0]);\n        func_data[0] = JS_NULL;\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_proxy_revoke_constructor(JSContext *ctx,\n                                           JSValueConst proxy_obj)\n{\n    return JS_NewCFunctionData(ctx, js_proxy_revoke, 0, 0, 1, &proxy_obj);\n}\n\nstatic JSValue js_proxy_revocable(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValue proxy_obj, revoke_obj = JS_UNDEFINED, obj;\n\n    proxy_obj = js_proxy_constructor(ctx, JS_UNDEFINED, argc, argv);\n    if (JS_IsException(proxy_obj))\n        goto fail;\n    revoke_obj = js_proxy_revoke_constructor(ctx, proxy_obj);\n    if (JS_IsException(revoke_obj))\n        goto fail;\n    obj = JS_NewObject(ctx);\n    if (JS_IsException(obj))\n        goto fail;\n    // XXX: exceptions?\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_proxy, proxy_obj, JS_PROP_C_W_E);\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_revoke, revoke_obj, JS_PROP_C_W_E);\n    return obj;\n fail:\n    JS_FreeValue(ctx, proxy_obj);\n    JS_FreeValue(ctx, revoke_obj);\n    return JS_EXCEPTION;\n}\n\nstatic const JSCFunctionListEntry js_proxy_funcs[] = {\n    JS_CFUNC_DEF(\"revocable\", 2, js_proxy_revocable ),\n};\n\nstatic const JSClassShortDef js_proxy_class_def[] = {\n    { JS_ATOM_Object, js_proxy_finalizer, js_proxy_mark }, /* JS_CLASS_PROXY */\n};\n\nvoid JS_AddIntrinsicProxy(JSContext *ctx)\n{\n    JSRuntime *rt = ctx->rt;\n    JSValue obj1;\n\n    if (!JS_IsRegisteredClass(rt, JS_CLASS_PROXY)) {\n        init_class_range(rt, js_proxy_class_def, JS_CLASS_PROXY,\n                         countof(js_proxy_class_def));\n        rt->class_array[JS_CLASS_PROXY].exotic = &js_proxy_exotic_methods;\n        rt->class_array[JS_CLASS_PROXY].call = js_proxy_call;\n    }\n\n    obj1 = JS_NewCFunction2(ctx, js_proxy_constructor, \"Proxy\", 2,\n                            JS_CFUNC_constructor, 0);\n    JS_SetConstructorBit(ctx, obj1, TRUE);\n    JS_SetPropertyFunctionList(ctx, obj1, js_proxy_funcs,\n                               countof(js_proxy_funcs));\n    JS_DefinePropertyValueStr(ctx, ctx->global_obj, \"Proxy\",\n                              obj1, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n}\n\n/* Symbol */\n\nstatic JSValue js_symbol_constructor(JSContext *ctx, JSValueConst new_target,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue str;\n    JSString *p;\n\n    if (!JS_IsUndefined(new_target))\n        return JS_ThrowTypeError(ctx, \"not a constructor\");\n    if (argc == 0 || JS_IsUndefined(argv[0])) {\n        p = NULL;\n    } else {\n        str = JS_ToString(ctx, argv[0]);\n        if (JS_IsException(str))\n            return JS_EXCEPTION;\n        p = JS_VALUE_GET_STRING(str);\n    }\n    return JS_NewSymbol(ctx, p, JS_ATOM_TYPE_SYMBOL);\n}\n\nstatic JSValue js_thisSymbolValue(JSContext *ctx, JSValueConst this_val)\n{\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_SYMBOL)\n        return JS_DupValue(ctx, this_val);\n\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_SYMBOL) {\n            if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_SYMBOL)\n                return JS_DupValue(ctx, p->u.object_data);\n        }\n    }\n    return JS_ThrowTypeError(ctx, \"not a symbol\");\n}\n\nstatic JSValue js_symbol_toString(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    val = js_thisSymbolValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    /* XXX: use JS_ToStringInternal() with a flags */\n    ret = js_string_constructor(ctx, JS_UNDEFINED, 1, (JSValueConst *)&val);\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nstatic JSValue js_symbol_valueOf(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    return js_thisSymbolValue(ctx, this_val);\n}\n\nstatic JSValue js_symbol_get_description(JSContext *ctx, JSValueConst this_val)\n{\n    JSValue val, ret;\n    JSAtomStruct *p;\n\n    val = js_thisSymbolValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    p = JS_VALUE_GET_PTR(val);\n    if (p->len == 0 && p->is_wide_char != 0) {\n        ret = JS_UNDEFINED;\n    } else {\n        ret = JS_AtomToString(ctx, js_get_atom_index(ctx->rt, p));\n    }\n    JS_FreeValue(ctx, val);\n    return ret;\n}\n\nstatic const JSCFunctionListEntry js_symbol_proto_funcs[] = {\n    JS_CFUNC_DEF(\"toString\", 0, js_symbol_toString ),\n    JS_CFUNC_DEF(\"valueOf\", 0, js_symbol_valueOf ),\n    // XXX: should have writable: false\n    JS_CFUNC_DEF(\"[Symbol.toPrimitive]\", 1, js_symbol_valueOf ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Symbol\", JS_PROP_CONFIGURABLE ),\n    JS_CGETSET_DEF(\"description\", js_symbol_get_description, NULL ),\n};\n\nstatic JSValue js_symbol_for(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    JSValue str;\n\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        return JS_EXCEPTION;\n    return JS_NewSymbol(ctx, JS_VALUE_GET_STRING(str), JS_ATOM_TYPE_GLOBAL_SYMBOL);\n}\n\nstatic JSValue js_symbol_keyFor(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSAtomStruct *p;\n\n    if (!JS_IsSymbol(argv[0]))\n        return JS_ThrowTypeError(ctx, \"not a symbol\");\n    p = JS_VALUE_GET_PTR(argv[0]);\n    if (p->atom_type != JS_ATOM_TYPE_GLOBAL_SYMBOL)\n        return JS_UNDEFINED;\n    return JS_DupValue(ctx, JS_MKPTR(JS_TAG_STRING, p));\n}\n\nstatic const JSCFunctionListEntry js_symbol_funcs[] = {\n    JS_CFUNC_DEF(\"for\", 1, js_symbol_for ),\n    JS_CFUNC_DEF(\"keyFor\", 1, js_symbol_keyFor ),\n};\n\n/* Set/Map/WeakSet/WeakMap */\n\ntypedef struct JSMapRecord {\n    int ref_count; /* used during enumeration to avoid freeing the record */\n    BOOL empty; /* TRUE if the record is deleted */\n    struct JSMapState *map;\n    struct JSMapRecord *next_weak_ref;\n    struct list_head link;\n    struct list_head hash_link;\n    JSValue key;\n    JSValue value;\n} JSMapRecord;\n\ntypedef struct JSMapState {\n    BOOL is_weak; /* TRUE if WeakSet/WeakMap */\n    struct list_head records; /* list of JSMapRecord.link */\n    uint32_t record_count;\n    struct list_head *hash_table;\n    uint32_t hash_size; /* must be a power of two */\n    uint32_t record_count_threshold; /* count at which a hash table\n                                        resize is needed */\n} JSMapState;\n\n#define MAGIC_SET (1 << 0)\n#define MAGIC_WEAK (1 << 1)\n\nstatic JSValue js_map_constructor(JSContext *ctx, JSValueConst new_target,\n                                  int argc, JSValueConst *argv, int magic)\n{\n    JSMapState *s;\n    JSValue obj, adder = JS_UNDEFINED, iter = JS_UNDEFINED, next_method = JS_UNDEFINED;\n    JSValueConst arr;\n    BOOL is_set, is_weak;\n\n    is_set = magic & MAGIC_SET;\n    is_weak = ((magic & MAGIC_WEAK) != 0);\n    obj = js_create_from_ctor(ctx, new_target, JS_CLASS_MAP + magic);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s)\n        goto fail;\n    init_list_head(&s->records);\n    s->is_weak = is_weak;\n    JS_SetOpaque(obj, s);\n    s->hash_size = 1;\n    s->hash_table = js_malloc(ctx, sizeof(s->hash_table[0]) * s->hash_size);\n    if (!s->hash_table)\n        goto fail;\n    init_list_head(&s->hash_table[0]);\n    s->record_count_threshold = 4;\n\n    arr = JS_UNDEFINED;\n    if (argc > 0)\n        arr = argv[0];\n    if (!JS_IsUndefined(arr) && !JS_IsNull(arr)) {\n        JSValue item, ret;\n        BOOL done;\n\n        adder = JS_GetProperty(ctx, obj, is_set ? JS_ATOM_add : JS_ATOM_set);\n        if (JS_IsException(adder))\n            goto fail;\n        if (!JS_IsFunction(ctx, adder)) {\n            JS_ThrowTypeError(ctx, \"set/add is not a function\");\n            goto fail;\n        }\n\n        iter = JS_GetIterator(ctx, arr, FALSE);\n        if (JS_IsException(iter))\n            goto fail;\n        next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);\n        if (JS_IsException(next_method))\n            goto fail;\n\n        for(;;) {\n            item = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);\n            if (JS_IsException(item))\n                goto fail;\n            if (done) {\n                JS_FreeValue(ctx, item);\n                break;\n            }\n            if (is_set) {\n                ret = JS_Call(ctx, adder, obj, 1, (JSValueConst *)&item);\n                if (JS_IsException(ret)) {\n                    JS_FreeValue(ctx, item);\n                    goto fail;\n                }\n            } else {\n                JSValue key, value;\n                JSValueConst args[2];\n                key = JS_UNDEFINED;\n                value = JS_UNDEFINED;\n                if (!JS_IsObject(item)) {\n                    JS_ThrowTypeErrorNotAnObject(ctx);\n                    goto fail1;\n                }\n                key = JS_GetPropertyUint32(ctx, item, 0);\n                if (JS_IsException(key))\n                    goto fail1;\n                value = JS_GetPropertyUint32(ctx, item, 1);\n                if (JS_IsException(value))\n                    goto fail1;\n                args[0] = key;\n                args[1] = value;\n                ret = JS_Call(ctx, adder, obj, 2, args);\n                if (JS_IsException(ret)) {\n                fail1:\n                    JS_FreeValue(ctx, item);\n                    JS_FreeValue(ctx, key);\n                    JS_FreeValue(ctx, value);\n                    goto fail;\n                }\n                JS_FreeValue(ctx, key);\n                JS_FreeValue(ctx, value);\n            }\n            JS_FreeValue(ctx, ret);\n            JS_FreeValue(ctx, item);\n        }\n        JS_FreeValue(ctx, next_method);\n        JS_FreeValue(ctx, iter);\n        JS_FreeValue(ctx, adder);\n    }\n    return obj;\n fail:\n    if (JS_IsObject(iter)) {\n        /* close the iterator object, preserving pending exception */\n        JS_IteratorClose(ctx, iter, TRUE);\n    }\n    JS_FreeValue(ctx, next_method);\n    JS_FreeValue(ctx, iter);\n    JS_FreeValue(ctx, adder);\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\n/* XXX: could normalize strings to speed up comparison */\nstatic JSValueConst map_normalize_key(JSContext *ctx, JSValueConst key)\n{\n    uint32_t tag = JS_VALUE_GET_TAG(key);\n    /* convert -0.0 to +0.0 */\n    if (JS_TAG_IS_FLOAT64(tag) && JS_VALUE_GET_FLOAT64(key) == 0.0) {\n        key = JS_NewInt32(ctx, 0);\n    }\n    return key;\n}\n\n/* XXX: better hash ? */\nstatic uint32_t map_hash_key(JSContext *ctx, JSValueConst key)\n{\n    uint32_t tag = JS_VALUE_GET_NORM_TAG(key);\n    uint32_t h;\n    double d;\n    JSFloat64Union u;\n\n    switch(tag) {\n    case JS_TAG_BOOL:\n        h = JS_VALUE_GET_INT(key);\n        break;\n    case JS_TAG_STRING:\n        h = hash_string(JS_VALUE_GET_STRING(key), 0);\n        break;\n    case JS_TAG_OBJECT:\n    case JS_TAG_SYMBOL:\n        h = (uintptr_t)JS_VALUE_GET_PTR(key) * 3163;\n        break;\n    case JS_TAG_INT:\n        d = JS_VALUE_GET_INT(key) * 3163;\n        goto hash_float64;\n    case JS_TAG_FLOAT64:\n        d = JS_VALUE_GET_FLOAT64(key);\n        /* normalize the NaN */\n        if (isnan(d))\n            d = JS_FLOAT64_NAN;\n    hash_float64:\n        u.d = d;\n        h = (u.u32[0] ^ u.u32[1]) * 3163;\n        break;\n    default:\n        h = 0; /* XXX: bignum support */\n        break;\n    }\n    h ^= tag;\n    return h;\n}\n\nstatic JSMapRecord *map_find_record(JSContext *ctx, JSMapState *s,\n                                    JSValueConst key)\n{\n    struct list_head *el;\n    JSMapRecord *mr;\n    uint32_t h;\n    h = map_hash_key(ctx, key) & (s->hash_size - 1);\n    list_for_each(el, &s->hash_table[h]) {\n        mr = list_entry(el, JSMapRecord, hash_link);\n        if (js_same_value_zero(ctx, mr->key, key))\n            return mr;\n    }\n    return NULL;\n}\n\nstatic void map_hash_resize(JSContext *ctx, JSMapState *s)\n{\n    uint32_t new_hash_size, i, h;\n    size_t slack;\n    struct list_head *new_hash_table, *el;\n    JSMapRecord *mr;\n\n    /* XXX: no reporting of memory allocation failure */\n    if (s->hash_size == 1)\n        new_hash_size = 4;\n    else\n        new_hash_size = s->hash_size * 2;\n    new_hash_table = js_realloc2(ctx, s->hash_table,\n                                 sizeof(new_hash_table[0]) * new_hash_size, &slack);\n    if (!new_hash_table)\n        return;\n    new_hash_size += slack / sizeof(*new_hash_table);\n\n    for(i = 0; i < new_hash_size; i++)\n        init_list_head(&new_hash_table[i]);\n\n    list_for_each(el, &s->records) {\n        mr = list_entry(el, JSMapRecord, link);\n        if (!mr->empty) {\n            h = map_hash_key(ctx, mr->key) & (new_hash_size - 1);\n            list_add_tail(&mr->hash_link, &new_hash_table[h]);\n        }\n    }\n    s->hash_table = new_hash_table;\n    s->hash_size = new_hash_size;\n    s->record_count_threshold = new_hash_size * 2;\n}\n\nstatic JSMapRecord *map_add_record(JSContext *ctx, JSMapState *s,\n                                   JSValueConst key)\n{\n    uint32_t h;\n    JSMapRecord *mr;\n\n    mr = js_malloc(ctx, sizeof(*mr));\n    if (!mr)\n        return NULL;\n    mr->ref_count = 1;\n    mr->map = s;\n    mr->empty = FALSE;\n    if (s->is_weak) {\n        JSObject *p = JS_VALUE_GET_OBJ(key);\n        /* Add the weak reference */\n        mr->next_weak_ref = p->first_weak_ref;\n        p->first_weak_ref = mr;\n    } else {\n        JS_DupValue(ctx, key);\n    }\n    mr->key = key;\n    h = map_hash_key(ctx, key) & (s->hash_size - 1);\n    list_add_tail(&mr->hash_link, &s->hash_table[h]);\n    list_add_tail(&mr->link, &s->records);\n    s->record_count++;\n    if (s->record_count >= s->record_count_threshold) {\n        map_hash_resize(ctx, s);\n    }\n    return mr;\n}\n\n/* Remove the weak reference from the object weak\n   reference list. we don't use a doubly linked list to\n   save space, assuming a given object has few weak\n       references to it */\nstatic void delete_weak_ref(JSRuntime *rt, JSMapRecord *mr)\n{\n    JSMapRecord **pmr, *mr1;\n    JSObject *p;\n\n    p = JS_VALUE_GET_OBJ(mr->key);\n    pmr = &p->first_weak_ref;\n    for(;;) {\n        mr1 = *pmr;\n        assert(mr1 != NULL);\n        if (mr1 == mr)\n            break;\n        pmr = &mr1->next_weak_ref;\n    }\n    *pmr = mr1->next_weak_ref;\n}\n\nstatic void map_delete_record(JSRuntime *rt, JSMapState *s, JSMapRecord *mr)\n{\n    if (mr->empty)\n        return;\n    list_del(&mr->hash_link);\n    if (s->is_weak) {\n        delete_weak_ref(rt, mr);\n    } else {\n        JS_FreeValueRT(rt, mr->key);\n    }\n    JS_FreeValueRT(rt, mr->value);\n    if (--mr->ref_count == 0) {\n        list_del(&mr->link);\n        js_free_rt(rt, mr);\n    } else {\n        /* keep a zombie record for iterators */\n        mr->empty = TRUE;\n        mr->key = JS_UNDEFINED;\n        mr->value = JS_UNDEFINED;\n    }\n    s->record_count--;\n}\n\nstatic void map_decref_record(JSRuntime *rt, JSMapRecord *mr)\n{\n    if (--mr->ref_count == 0) {\n        /* the record can be safely removed */\n        assert(mr->empty);\n        list_del(&mr->link);\n        js_free_rt(rt, mr);\n    }\n}\n\nstatic void reset_weak_ref(JSRuntime *rt, JSObject *p)\n{\n    JSMapRecord *mr, *mr_next;\n    JSMapState *s;\n    \n    /* first pass to remove the records from the WeakMap/WeakSet\n       lists */\n    for(mr = p->first_weak_ref; mr != NULL; mr = mr->next_weak_ref) {\n        s = mr->map;\n        assert(s->is_weak);\n        assert(!mr->empty); /* no iterator on WeakMap/WeakSet */\n        list_del(&mr->hash_link);\n        list_del(&mr->link);\n    }\n    \n    /* second pass to free the values to avoid modifying the weak\n       reference list while traversing it. */\n    for(mr = p->first_weak_ref; mr != NULL; mr = mr_next) {\n        mr_next = mr->next_weak_ref;\n        JS_FreeValueRT(rt, mr->value);\n        js_free_rt(rt, mr);\n    }\n\n    p->first_weak_ref = NULL; /* fail safe */\n}\n\nstatic JSValue js_map_set(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv, int magic)\n{\n    JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);\n    JSMapRecord *mr;\n    JSValueConst key, value;\n\n    if (!s)\n        return JS_EXCEPTION;\n    key = map_normalize_key(ctx, argv[0]);\n    if (s->is_weak && !JS_IsObject(key))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    if (magic & MAGIC_SET)\n        value = JS_UNDEFINED;\n    else\n        value = argv[1];\n    mr = map_find_record(ctx, s, key);\n    if (mr) {\n        JS_FreeValue(ctx, mr->value);\n    } else {\n        mr = map_add_record(ctx, s, key);\n        if (!mr)\n            return JS_EXCEPTION;\n    }\n    mr->value = JS_DupValue(ctx, value);\n    return JS_DupValue(ctx, this_val);\n}\n\nstatic JSValue js_map_get(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv, int magic)\n{\n    JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);\n    JSMapRecord *mr;\n    JSValueConst key;\n\n    if (!s)\n        return JS_EXCEPTION;\n    key = map_normalize_key(ctx, argv[0]);\n    mr = map_find_record(ctx, s, key);\n    if (!mr)\n        return JS_UNDEFINED;\n    else\n        return JS_DupValue(ctx, mr->value);\n}\n\nstatic JSValue js_map_has(JSContext *ctx, JSValueConst this_val,\n                          int argc, JSValueConst *argv, int magic)\n{\n    JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);\n    JSMapRecord *mr;\n    JSValueConst key;\n\n    if (!s)\n        return JS_EXCEPTION;\n    key = map_normalize_key(ctx, argv[0]);\n    mr = map_find_record(ctx, s, key);\n    return JS_NewBool(ctx, (mr != NULL));\n}\n\nstatic JSValue js_map_delete(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv, int magic)\n{\n    JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);\n    JSMapRecord *mr;\n    JSValueConst key;\n\n    if (!s)\n        return JS_EXCEPTION;\n    key = map_normalize_key(ctx, argv[0]);\n    mr = map_find_record(ctx, s, key);\n    if (!mr)\n        return JS_FALSE;\n    map_delete_record(ctx->rt, s, mr);\n    return JS_TRUE;\n}\n\nstatic JSValue js_map_clear(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv, int magic)\n{\n    JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);\n    struct list_head *el, *el1;\n    JSMapRecord *mr;\n\n    if (!s)\n        return JS_EXCEPTION;\n    list_for_each_safe(el, el1, &s->records) {\n        mr = list_entry(el, JSMapRecord, link);\n        map_delete_record(ctx->rt, s, mr);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_map_get_size(JSContext *ctx, JSValueConst this_val, int magic)\n{\n    JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);\n    if (!s)\n        return JS_EXCEPTION;\n    return JS_NewUint32(ctx, s->record_count);\n}\n\nstatic JSValue js_map_forEach(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int magic)\n{\n    JSMapState *s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);\n    JSValueConst func, this_arg;\n    JSValue ret, args[3];\n    struct list_head *el;\n    JSMapRecord *mr;\n\n    if (!s)\n        return JS_EXCEPTION;\n    func = argv[0];\n    if (argc > 1)\n        this_arg = argv[1];\n    else\n        this_arg = JS_UNDEFINED;\n    if (check_function(ctx, func))\n        return JS_EXCEPTION;\n    /* Note: the list can be modified while traversing it, but the\n       current element is locked */\n    el = s->records.next;\n    while (el != &s->records) {\n        mr = list_entry(el, JSMapRecord, link);\n        if (!mr->empty) {\n            mr->ref_count++;\n            /* must duplicate in case the record is deleted */\n            args[1] = JS_DupValue(ctx, mr->key);\n            if (magic)\n                args[0] = args[1];\n            else\n                args[0] = JS_DupValue(ctx, mr->value);\n            args[2] = this_val;\n            ret = JS_Call(ctx, func, this_arg, 3, (JSValueConst *)args);\n            JS_FreeValue(ctx, args[0]);\n            if (!magic)\n                JS_FreeValue(ctx, args[1]);\n            el = el->next;\n            map_decref_record(ctx->rt, mr);\n            if (JS_IsException(ret))\n                return ret;\n            JS_FreeValue(ctx, ret);\n        } else {\n            el = el->next;\n        }\n    }\n    return JS_UNDEFINED;\n}\n\nstatic void js_map_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p;\n    JSMapState *s;\n    struct list_head *el, *el1;\n    JSMapRecord *mr;\n\n    p = JS_VALUE_GET_OBJ(val);\n    s = p->u.map_state;\n    if (s) {\n        /* if the object is deleted we are sure that no iterator is\n           using it */\n        list_for_each_safe(el, el1, &s->records) {\n            mr = list_entry(el, JSMapRecord, link);\n            if (!mr->empty) {\n                if (s->is_weak)\n                    delete_weak_ref(rt, mr);\n                else\n                    JS_FreeValueRT(rt, mr->key);\n                JS_FreeValueRT(rt, mr->value);\n            }\n            js_free_rt(rt, mr);\n        }\n        js_free_rt(rt, s->hash_table);\n        js_free_rt(rt, s);\n    }\n}\n\nstatic void js_map_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSMapState *s;\n    struct list_head *el;\n    JSMapRecord *mr;\n\n    s = p->u.map_state;\n    if (s) {\n        list_for_each(el, &s->records) {\n            mr = list_entry(el, JSMapRecord, link);\n            if (!s->is_weak)\n                JS_MarkValue(rt, mr->key, mark_func);\n            JS_MarkValue(rt, mr->value, mark_func);\n        }\n    }\n}\n\n/* Map Iterator */\n\ntypedef struct JSMapIteratorData {\n    JSValue obj;\n    JSIteratorKindEnum kind;\n    JSMapRecord *cur_record;\n} JSMapIteratorData;\n\nstatic void js_map_iterator_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p;\n    JSMapIteratorData *it;\n\n    p = JS_VALUE_GET_OBJ(val);\n    it = p->u.map_iterator_data;\n    if (it) {\n        /* During the GC sweep phase the Map finalizer may be\n           called before the Map iterator finalizer */\n        if (JS_IsLiveObject(rt, it->obj) && it->cur_record) {\n            map_decref_record(rt, it->cur_record);\n        }\n        JS_FreeValueRT(rt, it->obj);\n        js_free_rt(rt, it);\n    }\n}\n\nstatic void js_map_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                 JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSMapIteratorData *it;\n    it = p->u.map_iterator_data;\n    if (it) {\n        /* the record is already marked by the object */\n        JS_MarkValue(rt, it->obj, mark_func);\n    }\n}\n\nstatic JSValue js_create_map_iterator(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv, int magic)\n{\n    JSIteratorKindEnum kind;\n    JSMapState *s;\n    JSMapIteratorData *it;\n    JSValue enum_obj;\n\n    kind = magic >> 2;\n    magic &= 3;\n    s = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP + magic);\n    if (!s)\n        return JS_EXCEPTION;\n    enum_obj = JS_NewObjectClass(ctx, JS_CLASS_MAP_ITERATOR + magic);\n    if (JS_IsException(enum_obj))\n        goto fail;\n    it = js_malloc(ctx, sizeof(*it));\n    if (!it) {\n        JS_FreeValue(ctx, enum_obj);\n        goto fail;\n    }\n    it->obj = JS_DupValue(ctx, this_val);\n    it->kind = kind;\n    it->cur_record = NULL;\n    JS_SetOpaque(enum_obj, it);\n    return enum_obj;\n fail:\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_map_iterator_next(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv,\n                                    BOOL *pdone, int magic)\n{\n    JSMapIteratorData *it;\n    JSMapState *s;\n    JSMapRecord *mr;\n    struct list_head *el;\n\n    it = JS_GetOpaque2(ctx, this_val, JS_CLASS_MAP_ITERATOR + magic);\n    if (!it) {\n        *pdone = FALSE;\n        return JS_EXCEPTION;\n    }\n    if (JS_IsUndefined(it->obj))\n        goto done;\n    s = JS_GetOpaque(it->obj, JS_CLASS_MAP + magic);\n    assert(s != NULL);\n    if (!it->cur_record) {\n        el = s->records.next;\n    } else {\n        mr = it->cur_record;\n        el = mr->link.next;\n        map_decref_record(ctx->rt, mr); /* the record can be freed here */\n    }\n    for(;;) {\n        if (el == &s->records) {\n            /* no more record  */\n            it->cur_record = NULL;\n            JS_FreeValue(ctx, it->obj);\n            it->obj = JS_UNDEFINED;\n        done:\n            /* end of enumeration */\n            *pdone = TRUE;\n            return JS_UNDEFINED;\n        }\n        mr = list_entry(el, JSMapRecord, link);\n        if (!mr->empty)\n            break;\n        /* get the next record */\n        el = mr->link.next;\n    }\n\n    /* lock the record so that it won't be freed */\n    mr->ref_count++;\n    it->cur_record = mr;\n    *pdone = FALSE;\n\n    if (it->kind == JS_ITERATOR_KIND_KEY) {\n        return JS_DupValue(ctx, mr->key);\n    } else {\n        JSValueConst args[2];\n        args[0] = mr->key;\n        if (magic)\n            args[1] = mr->key;\n        else\n            args[1] = mr->value;\n        if (it->kind == JS_ITERATOR_KIND_VALUE) {\n            return JS_DupValue(ctx, args[1]);\n        } else {\n            return js_create_array(ctx, 2, args);\n        }\n    }\n}\n\nstatic const JSCFunctionListEntry js_map_funcs[] = {\n    JS_CGETSET_DEF(\"[Symbol.species]\", js_get_this, NULL ),\n};\n\nstatic const JSCFunctionListEntry js_map_proto_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"set\", 2, js_map_set, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"get\", 1, js_map_get, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"has\", 1, js_map_has, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"delete\", 1, js_map_delete, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"clear\", 0, js_map_clear, 0 ),\n    JS_CGETSET_MAGIC_DEF(\"size\", js_map_get_size, NULL, 0),\n    JS_CFUNC_MAGIC_DEF(\"forEach\", 1, js_map_forEach, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"values\", 0, js_create_map_iterator, (JS_ITERATOR_KIND_VALUE << 2) | 0 ),\n    JS_CFUNC_MAGIC_DEF(\"keys\", 0, js_create_map_iterator, (JS_ITERATOR_KIND_KEY << 2) | 0 ),\n    JS_CFUNC_MAGIC_DEF(\"entries\", 0, js_create_map_iterator, (JS_ITERATOR_KIND_KEY_AND_VALUE << 2) | 0 ),\n    JS_ALIAS_DEF(\"[Symbol.iterator]\", \"entries\" ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Map\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_map_iterator_proto_funcs[] = {\n    JS_ITERATOR_NEXT_DEF(\"next\", 0, js_map_iterator_next, 0 ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Map Iterator\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_set_proto_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"add\", 1, js_map_set, MAGIC_SET ),\n    JS_CFUNC_MAGIC_DEF(\"has\", 1, js_map_has, MAGIC_SET ),\n    JS_CFUNC_MAGIC_DEF(\"delete\", 1, js_map_delete, MAGIC_SET ),\n    JS_CFUNC_MAGIC_DEF(\"clear\", 0, js_map_clear, MAGIC_SET ),\n    JS_CGETSET_MAGIC_DEF(\"size\", js_map_get_size, NULL, MAGIC_SET ),\n    JS_CFUNC_MAGIC_DEF(\"forEach\", 1, js_map_forEach, MAGIC_SET ),\n    JS_CFUNC_MAGIC_DEF(\"values\", 0, js_create_map_iterator, (JS_ITERATOR_KIND_KEY << 2) | MAGIC_SET ),\n    JS_ALIAS_DEF(\"keys\", \"values\" ),\n    JS_ALIAS_DEF(\"[Symbol.iterator]\", \"values\" ),\n    JS_CFUNC_MAGIC_DEF(\"entries\", 0, js_create_map_iterator, (JS_ITERATOR_KIND_KEY_AND_VALUE << 2) | MAGIC_SET ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Set\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_set_iterator_proto_funcs[] = {\n    JS_ITERATOR_NEXT_DEF(\"next\", 0, js_map_iterator_next, MAGIC_SET ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Set Iterator\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_weak_map_proto_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"set\", 2, js_map_set, MAGIC_WEAK ),\n    JS_CFUNC_MAGIC_DEF(\"get\", 1, js_map_get, MAGIC_WEAK ),\n    JS_CFUNC_MAGIC_DEF(\"has\", 1, js_map_has, MAGIC_WEAK ),\n    JS_CFUNC_MAGIC_DEF(\"delete\", 1, js_map_delete, MAGIC_WEAK ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"WeakMap\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_weak_set_proto_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"add\", 1, js_map_set, MAGIC_SET | MAGIC_WEAK ),\n    JS_CFUNC_MAGIC_DEF(\"has\", 1, js_map_has, MAGIC_SET | MAGIC_WEAK ),\n    JS_CFUNC_MAGIC_DEF(\"delete\", 1, js_map_delete, MAGIC_SET | MAGIC_WEAK ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"WeakSet\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry * const js_map_proto_funcs_ptr[6] = {\n    js_map_proto_funcs,\n    js_set_proto_funcs,\n    js_weak_map_proto_funcs,\n    js_weak_set_proto_funcs,\n    js_map_iterator_proto_funcs,\n    js_set_iterator_proto_funcs,\n};\n\nstatic const uint8_t js_map_proto_funcs_count[6] = {\n    countof(js_map_proto_funcs),\n    countof(js_set_proto_funcs),\n    countof(js_weak_map_proto_funcs),\n    countof(js_weak_set_proto_funcs),\n    countof(js_map_iterator_proto_funcs),\n    countof(js_set_iterator_proto_funcs),\n};\n\nvoid JS_AddIntrinsicMapSet(JSContext *ctx)\n{\n    int i;\n    JSValue obj1;\n    char buf[ATOM_GET_STR_BUF_SIZE];\n\n    for(i = 0; i < 4; i++) {\n        const char *name = JS_AtomGetStr(ctx, buf, sizeof(buf),\n                                         JS_ATOM_Map + i);\n        ctx->class_proto[JS_CLASS_MAP + i] = JS_NewObject(ctx);\n        JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_MAP + i],\n                                   js_map_proto_funcs_ptr[i],\n                                   js_map_proto_funcs_count[i]);\n        obj1 = JS_NewCFunctionMagic(ctx, js_map_constructor, name, 0,\n                                    JS_CFUNC_constructor_magic, i);\n        if (i < 2) {\n            JS_SetPropertyFunctionList(ctx, obj1, js_map_funcs,\n                                       countof(js_map_funcs));\n        }\n        JS_NewGlobalCConstructor2(ctx, obj1, name, ctx->class_proto[JS_CLASS_MAP + i]);\n    }\n\n    for(i = 0; i < 2; i++) {\n        ctx->class_proto[JS_CLASS_MAP_ITERATOR + i] =\n            JS_NewObjectProto(ctx, ctx->iterator_proto);\n        JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_MAP_ITERATOR + i],\n                                   js_map_proto_funcs_ptr[i + 4],\n                                   js_map_proto_funcs_count[i + 4]);\n    }\n}\n\n/* Generator */\nstatic const JSCFunctionListEntry js_generator_function_proto_funcs[] = {\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"GeneratorFunction\", JS_PROP_CONFIGURABLE),\n};\n\nstatic const JSCFunctionListEntry js_generator_proto_funcs[] = {\n    JS_ITERATOR_NEXT_DEF(\"next\", 1, js_generator_next, GEN_MAGIC_NEXT ),\n    JS_ITERATOR_NEXT_DEF(\"return\", 1, js_generator_next, GEN_MAGIC_RETURN ),\n    JS_ITERATOR_NEXT_DEF(\"throw\", 1, js_generator_next, GEN_MAGIC_THROW ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Generator\", JS_PROP_CONFIGURABLE),\n};\n\n/* Promise */\n\ntypedef enum JSPromiseStateEnum {\n    JS_PROMISE_PENDING,\n    JS_PROMISE_FULFILLED,\n    JS_PROMISE_REJECTED,\n} JSPromiseStateEnum;\n\ntypedef struct JSPromiseData {\n    JSPromiseStateEnum promise_state;\n    /* 0=fulfill, 1=reject, list of JSPromiseReactionData.link */\n    struct list_head promise_reactions[2];\n    BOOL is_handled; /* Note: only useful to debug */\n    JSValue promise_result;\n} JSPromiseData;\n\ntypedef struct JSPromiseFunctionDataResolved {\n    int ref_count;\n    BOOL already_resolved;\n} JSPromiseFunctionDataResolved;\n\ntypedef struct JSPromiseFunctionData {\n    JSValue promise;\n    JSPromiseFunctionDataResolved *presolved;\n} JSPromiseFunctionData;\n\ntypedef struct JSPromiseReactionData {\n    struct list_head link; /* not used in promise_reaction_job */\n    JSValue resolving_funcs[2];\n    JSValue handler;\n} JSPromiseReactionData;\n\nstatic int js_create_resolving_functions(JSContext *ctx, JSValue *args,\n                                         JSValueConst promise);\n\nstatic void promise_reaction_data_free(JSRuntime *rt,\n                                       JSPromiseReactionData *rd)\n{\n    JS_FreeValueRT(rt, rd->resolving_funcs[0]);\n    JS_FreeValueRT(rt, rd->resolving_funcs[1]);\n    JS_FreeValueRT(rt, rd->handler);\n    js_free_rt(rt, rd);\n}\n\nstatic JSValue promise_reaction_job(JSContext *ctx, int argc,\n                                    JSValueConst *argv)\n{\n    JSValueConst handler, arg, func;\n    JSValue res, res2;\n    BOOL is_reject;\n\n    assert(argc == 5);\n    handler = argv[2];\n    is_reject = JS_ToBool(ctx, argv[3]);\n    arg = argv[4];\n#ifdef DUMP_PROMISE\n    printf(\"promise_reaction_job: is_reject=%d\\n\", is_reject);\n#endif\n\n    if (JS_IsUndefined(handler)) {\n        if (is_reject) {\n            res = JS_Throw(ctx, JS_DupValue(ctx, arg));\n        } else {\n            res = JS_DupValue(ctx, arg);\n        }\n    } else {\n        res = JS_Call(ctx, handler, JS_UNDEFINED, 1, &arg);\n    }\n    is_reject = JS_IsException(res);\n    if (is_reject)\n        res = JS_GetException(ctx);\n    func = argv[is_reject];\n    /* as an extension, we support undefined as value to avoid\n       creating a dummy promise in the 'await' implementation of async\n       functions */\n    if (!JS_IsUndefined(func)) {\n        res2 = JS_Call(ctx, func, JS_UNDEFINED,\n                       1, (JSValueConst *)&res);\n    } else {\n        res2 = JS_UNDEFINED;\n    }\n    JS_FreeValue(ctx, res);\n\n    return res2;\n}\n\nvoid JS_SetHostPromiseRejectionTracker(JSRuntime *rt,\n                                       JSHostPromiseRejectionTracker *cb,\n                                       void *opaque)\n{\n    rt->host_promise_rejection_tracker = cb;\n    rt->host_promise_rejection_tracker_opaque = opaque;\n}\n\nstatic void fulfill_or_reject_promise(JSContext *ctx, JSValueConst promise,\n                                      JSValueConst value, BOOL is_reject)\n{\n    JSPromiseData *s = JS_GetOpaque(promise, JS_CLASS_PROMISE);\n    struct list_head *el, *el1;\n    JSPromiseReactionData *rd;\n    JSValueConst args[5];\n\n    if (!s || s->promise_state != JS_PROMISE_PENDING)\n        return; /* should never happen */\n    set_value(ctx, &s->promise_result, JS_DupValue(ctx, value));\n    s->promise_state = JS_PROMISE_FULFILLED + is_reject;\n#ifdef DUMP_PROMISE\n    printf(\"fulfill_or_reject_promise: is_reject=%d\\n\", is_reject);\n#endif\n    if (s->promise_state == JS_PROMISE_REJECTED && !s->is_handled) {\n        JSRuntime *rt = ctx->rt;\n        if (rt->host_promise_rejection_tracker) {\n            rt->host_promise_rejection_tracker(ctx, promise, value, FALSE,\n                                               rt->host_promise_rejection_tracker_opaque);\n        }\n    }\n\n    list_for_each_safe(el, el1, &s->promise_reactions[is_reject]) {\n        rd = list_entry(el, JSPromiseReactionData, link);\n        args[0] = rd->resolving_funcs[0];\n        args[1] = rd->resolving_funcs[1];\n        args[2] = rd->handler;\n        args[3] = JS_NewBool(ctx, is_reject);\n        args[4] = value;\n        JS_EnqueueJob(ctx, promise_reaction_job, 5, args);\n        list_del(&rd->link);\n        promise_reaction_data_free(ctx->rt, rd);\n    }\n\n    list_for_each_safe(el, el1, &s->promise_reactions[1 - is_reject]) {\n        rd = list_entry(el, JSPromiseReactionData, link);\n        list_del(&rd->link);\n        promise_reaction_data_free(ctx->rt, rd);\n    }\n}\n\nstatic void reject_promise(JSContext *ctx, JSValueConst promise,\n                           JSValueConst value)\n{\n    fulfill_or_reject_promise(ctx, promise, value, TRUE);\n}\n\nstatic JSValue js_promise_resolve_thenable_job(JSContext *ctx,\n                                               int argc, JSValueConst *argv)\n{\n    JSValueConst promise, thenable, then;\n    JSValue args[2], res;\n\n#ifdef DUMP_PROMISE\n    printf(\"js_promise_resolve_thenable_job\\n\");\n#endif\n    assert(argc == 3);\n    promise = argv[0];\n    thenable = argv[1];\n    then = argv[2];\n    if (js_create_resolving_functions(ctx, args, promise) < 0)\n        return JS_EXCEPTION;\n    res = JS_Call(ctx, then, thenable, 2, (JSValueConst *)args);\n    if (JS_IsException(res)) {\n        JSValue error = JS_GetException(ctx);\n        res = JS_Call(ctx, args[1], JS_UNDEFINED, 1, (JSValueConst *)&error);\n        JS_FreeValue(ctx, error);\n    }\n    JS_FreeValue(ctx, args[0]);\n    JS_FreeValue(ctx, args[1]);\n    return res;\n}\n\nstatic void js_promise_resolve_function_free_resolved(JSRuntime *rt,\n                                                      JSPromiseFunctionDataResolved *sr)\n{\n    if (--sr->ref_count == 0) {\n        js_free_rt(rt, sr);\n    }\n}\n\nstatic int js_create_resolving_functions(JSContext *ctx,\n                                         JSValue *resolving_funcs,\n                                         JSValueConst promise)\n\n{\n    JSValue obj;\n    JSPromiseFunctionData *s;\n    JSPromiseFunctionDataResolved *sr;\n    int i, ret;\n\n    sr = js_malloc(ctx, sizeof(*sr));\n    if (!sr)\n        return -1;\n    sr->ref_count = 1;\n    sr->already_resolved = FALSE; /* must be shared between the two functions */\n    ret = 0;\n    for(i = 0; i < 2; i++) {\n        obj = JS_NewObjectProtoClass(ctx, ctx->function_proto,\n                                     JS_CLASS_PROMISE_RESOLVE_FUNCTION + i);\n        if (JS_IsException(obj))\n            goto fail;\n        s = js_malloc(ctx, sizeof(*s));\n        if (!s) {\n            JS_FreeValue(ctx, obj);\n        fail:\n\n            if (i != 0)\n                JS_FreeValue(ctx, resolving_funcs[0]);\n            ret = -1;\n            break;\n        }\n        sr->ref_count++;\n        s->presolved = sr;\n        s->promise = JS_DupValue(ctx, promise);\n        JS_SetOpaque(obj, s);\n        js_function_set_properties(ctx, obj, JS_ATOM_empty_string, 1);\n        resolving_funcs[i] = obj;\n    }\n    js_promise_resolve_function_free_resolved(ctx->rt, sr);\n    return ret;\n}\n\nstatic void js_promise_resolve_function_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSPromiseFunctionData *s = JS_VALUE_GET_OBJ(val)->u.promise_function_data;\n    if (s) {\n        js_promise_resolve_function_free_resolved(rt, s->presolved);\n        JS_FreeValueRT(rt, s->promise);\n        js_free_rt(rt, s);\n    }\n}\n\nstatic void js_promise_resolve_function_mark(JSRuntime *rt, JSValueConst val,\n                                             JS_MarkFunc *mark_func)\n{\n    JSPromiseFunctionData *s = JS_VALUE_GET_OBJ(val)->u.promise_function_data;\n    if (s) {\n        JS_MarkValue(rt, s->promise, mark_func);\n    }\n}\n\nstatic JSValue js_promise_resolve_function_call(JSContext *ctx,\n                                                JSValueConst func_obj,\n                                                JSValueConst this_val,\n                                                int argc, JSValueConst *argv,\n                                                int flags)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(func_obj);\n    JSPromiseFunctionData *s;\n    JSValueConst resolution, args[3];\n    JSValue then;\n    BOOL is_reject;\n\n    s = p->u.promise_function_data;\n    if (!s || s->presolved->already_resolved)\n        return JS_UNDEFINED;\n    s->presolved->already_resolved = TRUE;\n    is_reject = p->class_id - JS_CLASS_PROMISE_RESOLVE_FUNCTION;\n    if (argc > 0)\n        resolution = argv[0];\n    else\n        resolution = JS_UNDEFINED;\n#ifdef DUMP_PROMISE\n    printf(\"js_promise_resolving_function_call: is_reject=%d resolution=\", is_reject);\n    JS_DumpValue(ctx, resolution);\n    printf(\"\\n\");\n#endif\n    if (is_reject || !JS_IsObject(resolution)) {\n        goto done;\n    } else if (js_same_value(ctx, resolution, s->promise)) {\n        JS_ThrowTypeError(ctx, \"promise self resolution\");\n        goto fail_reject;\n    }\n    then = JS_GetProperty(ctx, resolution, JS_ATOM_then);\n    if (JS_IsException(then)) {\n        JSValue error;\n    fail_reject:\n        error = JS_GetException(ctx);\n        reject_promise(ctx, s->promise, error);\n        JS_FreeValue(ctx, error);\n    } else if (!JS_IsFunction(ctx, then)) {\n        JS_FreeValue(ctx, then);\n    done:\n        fulfill_or_reject_promise(ctx, s->promise, resolution, is_reject);\n    } else {\n        args[0] = s->promise;\n        args[1] = resolution;\n        args[2] = then;\n        JS_EnqueueJob(ctx, js_promise_resolve_thenable_job, 3, args);\n        JS_FreeValue(ctx, then);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic void js_promise_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSPromiseData *s = JS_GetOpaque(val, JS_CLASS_PROMISE);\n    struct list_head *el, *el1;\n    int i;\n\n    if (!s)\n        return;\n    for(i = 0; i < 2; i++) {\n        list_for_each_safe(el, el1, &s->promise_reactions[i]) {\n            JSPromiseReactionData *rd =\n                list_entry(el, JSPromiseReactionData, link);\n            promise_reaction_data_free(rt, rd);\n        }\n    }\n    JS_FreeValueRT(rt, s->promise_result);\n    js_free_rt(rt, s);\n}\n\nstatic void js_promise_mark(JSRuntime *rt, JSValueConst val,\n                            JS_MarkFunc *mark_func)\n{\n    JSPromiseData *s = JS_GetOpaque(val, JS_CLASS_PROMISE);\n    struct list_head *el;\n    int i;\n\n    if (!s)\n        return;\n    for(i = 0; i < 2; i++) {\n        list_for_each(el, &s->promise_reactions[i]) {\n            JSPromiseReactionData *rd =\n                list_entry(el, JSPromiseReactionData, link);\n            JS_MarkValue(rt, rd->resolving_funcs[0], mark_func);\n            JS_MarkValue(rt, rd->resolving_funcs[1], mark_func);\n            JS_MarkValue(rt, rd->handler, mark_func);\n        }\n    }\n    JS_MarkValue(rt, s->promise_result, mark_func);\n}\n\nstatic JSValue js_promise_constructor(JSContext *ctx, JSValueConst new_target,\n                                      int argc, JSValueConst *argv)\n{\n    JSValueConst executor;\n    JSValue obj;\n    JSPromiseData *s;\n    JSValue args[2], ret;\n    int i;\n\n    executor = argv[0];\n    if (check_function(ctx, executor))\n        return JS_EXCEPTION;\n    obj = js_create_from_ctor(ctx, new_target, JS_CLASS_PROMISE);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s)\n        goto fail;\n    s->promise_state = JS_PROMISE_PENDING;\n    s->is_handled = FALSE;\n    for(i = 0; i < 2; i++)\n        init_list_head(&s->promise_reactions[i]);\n    s->promise_result = JS_UNDEFINED;\n    JS_SetOpaque(obj, s);\n    if (js_create_resolving_functions(ctx, args, obj))\n        goto fail;\n    ret = JS_Call(ctx, executor, JS_UNDEFINED, 2, (JSValueConst *)args);\n    if (JS_IsException(ret)) {\n        JSValue ret2, error;\n        error = JS_GetException(ctx);\n        ret2 = JS_Call(ctx, args[1], JS_UNDEFINED, 1, (JSValueConst *)&error);\n        JS_FreeValue(ctx, error);\n        if (JS_IsException(ret2))\n            goto fail1;\n        JS_FreeValue(ctx, ret2);\n    }\n    JS_FreeValue(ctx, ret);\n    JS_FreeValue(ctx, args[0]);\n    JS_FreeValue(ctx, args[1]);\n    return obj;\n fail1:\n    JS_FreeValue(ctx, args[0]);\n    JS_FreeValue(ctx, args[1]);\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_promise_executor(JSContext *ctx,\n                                   JSValueConst this_val,\n                                   int argc, JSValueConst *argv,\n                                   int magic, JSValue *func_data)\n{\n    int i;\n\n    for(i = 0; i < 2; i++) {\n        if (!JS_IsUndefined(func_data[i]))\n            return JS_ThrowTypeError(ctx, \"resolving function already set\");\n        func_data[i] = JS_DupValue(ctx, argv[i]);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_promise_executor_new(JSContext *ctx)\n{\n    JSValueConst func_data[2];\n\n    func_data[0] = JS_UNDEFINED;\n    func_data[1] = JS_UNDEFINED;\n    return JS_NewCFunctionData(ctx, js_promise_executor, 2,\n                               0, 2, func_data);\n}\n\nstatic JSValue js_new_promise_capability(JSContext *ctx,\n                                         JSValue *resolving_funcs,\n                                         JSValueConst ctor)\n{\n    JSValue executor, result_promise;\n    JSCFunctionDataRecord *s;\n    int i;\n\n    executor = js_promise_executor_new(ctx);\n    if (JS_IsException(executor))\n        return executor;\n\n    if (JS_IsUndefined(ctor)) {\n        result_promise = js_promise_constructor(ctx, ctor, 1,\n                                                (JSValueConst *)&executor);\n    } else {\n        result_promise = JS_CallConstructor(ctx, ctor, 1,\n                                            (JSValueConst *)&executor);\n    }\n    if (JS_IsException(result_promise))\n        goto fail;\n    s = JS_GetOpaque(executor, JS_CLASS_C_FUNCTION_DATA);\n    for(i = 0; i < 2; i++) {\n        if (check_function(ctx, s->data[i]))\n            goto fail;\n    }\n    for(i = 0; i < 2; i++)\n        resolving_funcs[i] = JS_DupValue(ctx, s->data[i]);\n    JS_FreeValue(ctx, executor);\n    return result_promise;\n fail:\n    JS_FreeValue(ctx, executor);\n    JS_FreeValue(ctx, result_promise);\n    return JS_EXCEPTION;\n}\n\nJSValue JS_NewPromiseCapability(JSContext *ctx, JSValue *resolving_funcs)\n{\n    return js_new_promise_capability(ctx, resolving_funcs, JS_UNDEFINED);\n}\n\nstatic JSValue js_promise_resolve(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv, int magic)\n{\n    JSValue result_promise, resolving_funcs[2], ret;\n    BOOL is_reject = magic;\n\n    if (!JS_IsObject(this_val))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    if (!is_reject && JS_GetOpaque(argv[0], JS_CLASS_PROMISE)) {\n        JSValue ctor;\n        BOOL is_same;\n        ctor = JS_GetProperty(ctx, argv[0], JS_ATOM_constructor);\n        if (JS_IsException(ctor))\n            return ctor;\n        is_same = js_same_value(ctx, ctor, this_val);\n        JS_FreeValue(ctx, ctor);\n        if (is_same)\n            return JS_DupValue(ctx, argv[0]);\n    }\n    result_promise = js_new_promise_capability(ctx, resolving_funcs, this_val);\n    if (JS_IsException(result_promise))\n        return result_promise;\n    ret = JS_Call(ctx, resolving_funcs[is_reject], JS_UNDEFINED, 1, argv);\n    JS_FreeValue(ctx, resolving_funcs[0]);\n    JS_FreeValue(ctx, resolving_funcs[1]);\n    if (JS_IsException(ret)) {\n        JS_FreeValue(ctx, result_promise);\n        return ret;\n    }\n    JS_FreeValue(ctx, ret);\n    return result_promise;\n}\n\n#if 0\nstatic JSValue js_promise___newPromiseCapability(JSContext *ctx,\n                                                 JSValueConst this_val,\n                                                 int argc, JSValueConst *argv)\n{\n    JSValue result_promise, resolving_funcs[2], obj;\n    JSValueConst ctor;\n    ctor = argv[0];\n    if (!JS_IsObject(ctor))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    result_promise = js_new_promise_capability(ctx, resolving_funcs, ctor);\n    if (JS_IsException(result_promise))\n        return result_promise;\n    obj = JS_NewObject(ctx);\n    if (JS_IsException(obj)) {\n        JS_FreeValue(ctx, resolving_funcs[0]);\n        JS_FreeValue(ctx, resolving_funcs[1]);\n        JS_FreeValue(ctx, result_promise);\n        return JS_EXCEPTION;\n    }\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_promise, result_promise, JS_PROP_C_W_E);\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_resolve, resolving_funcs[0], JS_PROP_C_W_E);\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_reject, resolving_funcs[1], JS_PROP_C_W_E);\n    return obj;\n}\n#endif\n\nstatic __exception int remainingElementsCount_add(JSContext *ctx,\n                                                  JSValueConst resolve_element_env,\n                                                  int addend)\n{\n    JSValue val;\n    int remainingElementsCount;\n\n    val = JS_GetPropertyUint32(ctx, resolve_element_env, 0);\n    if (JS_IsException(val))\n        return -1;\n    if (JS_ToInt32Free(ctx, &remainingElementsCount, val))\n        return -1;\n    remainingElementsCount += addend;\n    if (JS_SetPropertyUint32(ctx, resolve_element_env, 0,\n                             JS_NewInt32(ctx, remainingElementsCount)) < 0)\n        return -1;\n    return (remainingElementsCount == 0);\n}\n\n#define PROMISE_MAGIC_all        0\n#define PROMISE_MAGIC_allSettled 1\n#define PROMISE_MAGIC_any        2\n\nstatic JSValue js_promise_all_resolve_element(JSContext *ctx,\n                                              JSValueConst this_val,\n                                              int argc, JSValueConst *argv,\n                                              int magic,\n                                              JSValue *func_data)\n{\n    int resolve_type = magic & 3;\n    int is_reject = magic & 4;\n    BOOL alreadyCalled = JS_ToBool(ctx, func_data[0]);\n    JSValueConst values = func_data[2];\n    JSValueConst resolve = func_data[3];\n    JSValueConst resolve_element_env = func_data[4];\n    JSValue ret, obj;\n    int is_zero, index;\n    \n    if (JS_ToInt32(ctx, &index, func_data[1]))\n        return JS_EXCEPTION;\n    if (alreadyCalled)\n        return JS_UNDEFINED;\n    func_data[0] = JS_NewBool(ctx, TRUE);\n\n    if (resolve_type == PROMISE_MAGIC_allSettled) {\n        JSValue str;\n        \n        obj = JS_NewObject(ctx);\n        if (JS_IsException(obj))\n            return JS_EXCEPTION;\n        str = JS_NewString(ctx, is_reject ? \"rejected\" : \"fulfilled\");\n        if (JS_IsException(str))\n            goto fail1;\n        if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_status,\n                                   str,\n                                   JS_PROP_C_W_E) < 0)\n            goto fail1;\n        if (JS_DefinePropertyValue(ctx, obj,\n                                   is_reject ? JS_ATOM_reason : JS_ATOM_value,\n                                   JS_DupValue(ctx, argv[0]),\n                                   JS_PROP_C_W_E) < 0) {\n        fail1:\n            JS_FreeValue(ctx, obj);\n            return JS_EXCEPTION;\n        }\n    } else {\n        obj = JS_DupValue(ctx, argv[0]);\n    }\n    if (JS_DefinePropertyValueUint32(ctx, values, index,\n                                     obj, JS_PROP_C_W_E) < 0)\n        return JS_EXCEPTION;\n    \n    is_zero = remainingElementsCount_add(ctx, resolve_element_env, -1);\n    if (is_zero < 0)\n        return JS_EXCEPTION;\n    if (is_zero) {\n        if (resolve_type == PROMISE_MAGIC_any) {\n            JSValue error;\n            error = js_aggregate_error_constructor(ctx, values);\n            if (JS_IsException(error))\n                return JS_EXCEPTION;\n            ret = JS_Call(ctx, resolve, JS_UNDEFINED, 1, (JSValueConst *)&error);\n            JS_FreeValue(ctx, error);\n        } else {\n            ret = JS_Call(ctx, resolve, JS_UNDEFINED, 1, (JSValueConst *)&values);\n        }\n        if (JS_IsException(ret))\n            return ret;\n        JS_FreeValue(ctx, ret);\n    }\n    return JS_UNDEFINED;\n}\n\n/* magic = 0: Promise.all 1: Promise.allSettled */\nstatic JSValue js_promise_all(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int magic)\n{\n    JSValue result_promise, resolving_funcs[2], item, next_promise, ret;\n    JSValue next_method = JS_UNDEFINED, values = JS_UNDEFINED;\n    JSValue resolve_element_env = JS_UNDEFINED, resolve_element, reject_element;\n    JSValue promise_resolve = JS_UNDEFINED, iter = JS_UNDEFINED;\n    JSValueConst then_args[2], resolve_element_data[5];\n    BOOL done;\n    int index, is_zero, is_promise_any = (magic == PROMISE_MAGIC_any);\n    \n    if (!JS_IsObject(this_val))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    result_promise = js_new_promise_capability(ctx, resolving_funcs, this_val);\n    if (JS_IsException(result_promise))\n        return result_promise;\n    promise_resolve = JS_GetProperty(ctx, this_val, JS_ATOM_resolve);\n    if (JS_IsException(promise_resolve) ||\n        check_function(ctx, promise_resolve))\n        goto fail_reject;\n    iter = JS_GetIterator(ctx, argv[0], FALSE);\n    if (JS_IsException(iter)) {\n        JSValue error;\n    fail_reject:\n        error = JS_GetException(ctx);\n        ret = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED, 1,\n                       (JSValueConst *)&error);\n        JS_FreeValue(ctx, error);\n        if (JS_IsException(ret))\n            goto fail;\n        JS_FreeValue(ctx, ret);\n    } else {\n        next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);\n        if (JS_IsException(next_method))\n            goto fail_reject;\n        values = JS_NewArray(ctx);\n        if (JS_IsException(values))\n            goto fail_reject;\n        resolve_element_env = JS_NewArray(ctx);\n        if (JS_IsException(resolve_element_env))\n            goto fail_reject;\n        /* remainingElementsCount field */\n        if (JS_DefinePropertyValueUint32(ctx, resolve_element_env, 0,\n                                         JS_NewInt32(ctx, 1),\n                                         JS_PROP_CONFIGURABLE | JS_PROP_ENUMERABLE | JS_PROP_WRITABLE) < 0)\n            goto fail_reject;\n        \n        index = 0;\n        for(;;) {\n            /* XXX: conformance: should close the iterator if error on 'done'\n               access, but not on 'value' access */\n            item = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);\n            if (JS_IsException(item))\n                goto fail_reject;\n            if (done)\n                break;\n            next_promise = JS_Call(ctx, promise_resolve, \n                                   this_val, 1, (JSValueConst *)&item);\n            JS_FreeValue(ctx, item);\n            if (JS_IsException(next_promise)) {\n            fail_reject1:\n                JS_IteratorClose(ctx, iter, TRUE);\n                goto fail_reject;\n            }\n            resolve_element_data[0] = JS_NewBool(ctx, FALSE);\n            resolve_element_data[1] = JS_NewInt32(ctx, index);\n            resolve_element_data[2] = values;\n            resolve_element_data[3] = resolving_funcs[is_promise_any];\n            resolve_element_data[4] = resolve_element_env;\n            resolve_element =\n                JS_NewCFunctionData(ctx, js_promise_all_resolve_element, 1,\n                                    magic, 5, resolve_element_data);\n            if (JS_IsException(resolve_element)) {\n                JS_FreeValue(ctx, next_promise);\n                goto fail_reject1;\n            }\n            \n            if (magic == PROMISE_MAGIC_allSettled) {\n                reject_element =\n                    JS_NewCFunctionData(ctx, js_promise_all_resolve_element, 1,\n                                        magic | 4, 5, resolve_element_data);\n                if (JS_IsException(reject_element)) {\n                    JS_FreeValue(ctx, next_promise);\n                    goto fail_reject1;\n                }\n            } else if (magic == PROMISE_MAGIC_any) {\n                if (JS_DefinePropertyValueUint32(ctx, values, index,\n                                                 JS_UNDEFINED, JS_PROP_C_W_E) < 0)\n                    goto fail_reject1;\n                reject_element = resolve_element;\n                resolve_element = JS_DupValue(ctx, resolving_funcs[0]);\n            } else {\n                reject_element = JS_DupValue(ctx, resolving_funcs[1]);\n            }\n\n            if (remainingElementsCount_add(ctx, resolve_element_env, 1) < 0) {\n                JS_FreeValue(ctx, next_promise);\n                JS_FreeValue(ctx, resolve_element);\n                JS_FreeValue(ctx, reject_element);\n                goto fail_reject1;\n            }\n\n            then_args[0] = resolve_element;\n            then_args[1] = reject_element;\n            ret = JS_InvokeFree(ctx, next_promise, JS_ATOM_then, 2, then_args);\n            JS_FreeValue(ctx, resolve_element);\n            JS_FreeValue(ctx, reject_element);\n            if (check_exception_free(ctx, ret))\n                goto fail_reject1;\n            index++;\n        }\n\n        is_zero = remainingElementsCount_add(ctx, resolve_element_env, -1);\n        if (is_zero < 0)\n            goto fail_reject;\n        if (is_zero) {\n            if (magic == PROMISE_MAGIC_any) {\n                JSValue error;\n                error = js_aggregate_error_constructor(ctx, values);\n                if (JS_IsException(error))\n                    goto fail_reject;\n                JS_FreeValue(ctx, values);\n                values = error;\n            }\n            ret = JS_Call(ctx, resolving_funcs[is_promise_any], JS_UNDEFINED,\n                          1, (JSValueConst *)&values);\n            if (check_exception_free(ctx, ret))\n                goto fail_reject;\n        }\n    }\n done:\n    JS_FreeValue(ctx, promise_resolve);\n    JS_FreeValue(ctx, resolve_element_env);\n    JS_FreeValue(ctx, values);\n    JS_FreeValue(ctx, next_method);\n    JS_FreeValue(ctx, iter);\n    JS_FreeValue(ctx, resolving_funcs[0]);\n    JS_FreeValue(ctx, resolving_funcs[1]);\n    return result_promise;\n fail:\n    JS_FreeValue(ctx, result_promise);\n    result_promise = JS_EXCEPTION;\n    goto done;\n}\n\nstatic JSValue js_promise_race(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    JSValue result_promise, resolving_funcs[2], item, next_promise, ret;\n    JSValue next_method = JS_UNDEFINED, iter = JS_UNDEFINED;\n    JSValue promise_resolve = JS_UNDEFINED;\n    BOOL done;\n\n    if (!JS_IsObject(this_val))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n    result_promise = js_new_promise_capability(ctx, resolving_funcs, this_val);\n    if (JS_IsException(result_promise))\n        return result_promise;\n    promise_resolve = JS_GetProperty(ctx, this_val, JS_ATOM_resolve);\n    if (JS_IsException(promise_resolve) ||\n        check_function(ctx, promise_resolve))\n        goto fail_reject;\n    iter = JS_GetIterator(ctx, argv[0], FALSE);\n    if (JS_IsException(iter)) {\n        JSValue error;\n    fail_reject:\n        error = JS_GetException(ctx);\n        ret = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED, 1,\n                       (JSValueConst *)&error);\n        JS_FreeValue(ctx, error);\n        if (JS_IsException(ret))\n            goto fail;\n        JS_FreeValue(ctx, ret);\n    } else {\n        next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);\n        if (JS_IsException(next_method))\n            goto fail_reject;\n\n        for(;;) {\n            /* XXX: conformance: should close the iterator if error on 'done'\n               access, but not on 'value' access */\n            item = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);\n            if (JS_IsException(item))\n                goto fail_reject;\n            if (done)\n                break;\n            next_promise = JS_Call(ctx, promise_resolve,\n                                   this_val, 1, (JSValueConst *)&item);\n            JS_FreeValue(ctx, item);\n            if (JS_IsException(next_promise)) {\n            fail_reject1:\n                JS_IteratorClose(ctx, iter, TRUE);\n                goto fail_reject;\n            }\n            ret = JS_InvokeFree(ctx, next_promise, JS_ATOM_then, 2,\n                                (JSValueConst *)resolving_funcs);\n            if (check_exception_free(ctx, ret))\n                goto fail_reject1;\n        }\n    }\n done:\n    JS_FreeValue(ctx, promise_resolve);\n    JS_FreeValue(ctx, next_method);\n    JS_FreeValue(ctx, iter);\n    JS_FreeValue(ctx, resolving_funcs[0]);\n    JS_FreeValue(ctx, resolving_funcs[1]);\n    return result_promise;\n fail:\n    //JS_FreeValue(ctx, next_method); // why not???\n    JS_FreeValue(ctx, result_promise);\n    result_promise = JS_EXCEPTION;\n    goto done;\n}\n\nstatic __exception int perform_promise_then(JSContext *ctx,\n                                            JSValueConst promise,\n                                            JSValueConst *resolve_reject,\n                                            JSValueConst *cap_resolving_funcs)\n{\n    JSPromiseData *s = JS_GetOpaque(promise, JS_CLASS_PROMISE);\n    JSPromiseReactionData *rd_array[2], *rd;\n    int i, j;\n\n    rd_array[0] = NULL;\n    rd_array[1] = NULL;\n    for(i = 0; i < 2; i++) {\n        JSValueConst handler;\n        rd = js_mallocz(ctx, sizeof(*rd));\n        if (!rd) {\n            if (i == 1)\n                promise_reaction_data_free(ctx->rt, rd_array[0]);\n            return -1;\n        }\n        for(j = 0; j < 2; j++)\n            rd->resolving_funcs[j] = JS_DupValue(ctx, cap_resolving_funcs[j]);\n        handler = resolve_reject[i];\n        if (!JS_IsFunction(ctx, handler))\n            handler = JS_UNDEFINED;\n        rd->handler = JS_DupValue(ctx, handler);\n        rd_array[i] = rd;\n    }\n\n    if (s->promise_state == JS_PROMISE_PENDING) {\n        for(i = 0; i < 2; i++)\n            list_add_tail(&rd_array[i]->link, &s->promise_reactions[i]);\n    } else {\n        JSValueConst args[5];\n        if (s->promise_state == JS_PROMISE_REJECTED && !s->is_handled) {\n            JSRuntime *rt = ctx->rt;\n            if (rt->host_promise_rejection_tracker) {\n                rt->host_promise_rejection_tracker(ctx, promise, s->promise_result,\n                                                   TRUE, rt->host_promise_rejection_tracker_opaque);\n            }\n        }\n        i = s->promise_state - JS_PROMISE_FULFILLED;\n        rd = rd_array[i];\n        args[0] = rd->resolving_funcs[0];\n        args[1] = rd->resolving_funcs[1];\n        args[2] = rd->handler;\n        args[3] = JS_NewBool(ctx, i);\n        args[4] = s->promise_result;\n        JS_EnqueueJob(ctx, promise_reaction_job, 5, args);\n        for(i = 0; i < 2; i++)\n            promise_reaction_data_free(ctx->rt, rd_array[i]);\n    }\n    s->is_handled = TRUE;\n    return 0;\n}\n\nstatic JSValue js_promise_then(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    JSValue ctor, result_promise, resolving_funcs[2];\n    JSPromiseData *s;\n    int i, ret;\n\n    s = JS_GetOpaque2(ctx, this_val, JS_CLASS_PROMISE);\n    if (!s)\n        return JS_EXCEPTION;\n\n    ctor = JS_SpeciesConstructor(ctx, this_val, JS_UNDEFINED);\n    if (JS_IsException(ctor))\n        return ctor;\n    result_promise = js_new_promise_capability(ctx, resolving_funcs, ctor);\n    JS_FreeValue(ctx, ctor);\n    if (JS_IsException(result_promise))\n        return result_promise;\n    ret = perform_promise_then(ctx, this_val, argv,\n                               (JSValueConst *)resolving_funcs);\n    for(i = 0; i < 2; i++)\n        JS_FreeValue(ctx, resolving_funcs[i]);\n    if (ret) {\n        JS_FreeValue(ctx, result_promise);\n        return JS_EXCEPTION;\n    }\n    return result_promise;\n}\n\nstatic JSValue js_promise_catch(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValueConst args[2];\n    args[0] = JS_UNDEFINED;\n    args[1] = argv[0];\n    return JS_Invoke(ctx, this_val, JS_ATOM_then, 2, args);\n}\n\nstatic JSValue js_promise_finally_value_thunk(JSContext *ctx, JSValueConst this_val,\n                                              int argc, JSValueConst *argv,\n                                              int magic, JSValue *func_data)\n{\n    return JS_DupValue(ctx, func_data[0]);\n}\n\nstatic JSValue js_promise_finally_thrower(JSContext *ctx, JSValueConst this_val,\n                                          int argc, JSValueConst *argv,\n                                          int magic, JSValue *func_data)\n{\n    return JS_Throw(ctx, JS_DupValue(ctx, func_data[0]));\n}\n\nstatic JSValue js_promise_then_finally_func(JSContext *ctx, JSValueConst this_val,\n                                            int argc, JSValueConst *argv,\n                                            int magic, JSValue *func_data)\n{\n    JSValueConst ctor = func_data[0];\n    JSValueConst onFinally = func_data[1];\n    JSValue res, promise, ret, then_func;\n\n    res = JS_Call(ctx, onFinally, JS_UNDEFINED, 0, NULL);\n    if (JS_IsException(res))\n        return res;\n    promise = js_promise_resolve(ctx, ctor, 1, (JSValueConst *)&res, 0);\n    JS_FreeValue(ctx, res);\n    if (JS_IsException(promise))\n        return promise;\n    if (magic == 0) {\n        then_func = JS_NewCFunctionData(ctx, js_promise_finally_value_thunk, 0,\n                                        0, 1, argv);\n    } else {\n        then_func = JS_NewCFunctionData(ctx, js_promise_finally_thrower, 0,\n                                        0, 1, argv);\n    }\n    if (JS_IsException(then_func)) {\n        JS_FreeValue(ctx, promise);\n        return then_func;\n    }\n    ret = JS_InvokeFree(ctx, promise, JS_ATOM_then, 1, (JSValueConst *)&then_func);\n    JS_FreeValue(ctx, then_func);\n    return ret;\n}\n\nstatic JSValue js_promise_finally(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    JSValueConst onFinally = argv[0];\n    JSValue ctor, ret;\n    JSValue then_funcs[2];\n    JSValueConst func_data[2];\n    int i;\n\n    ctor = JS_SpeciesConstructor(ctx, this_val, JS_UNDEFINED);\n    if (JS_IsException(ctor))\n        return ctor;\n    if (!JS_IsFunction(ctx, onFinally)) {\n        then_funcs[0] = JS_DupValue(ctx, onFinally);\n        then_funcs[1] = JS_DupValue(ctx, onFinally);\n    } else {\n        func_data[0] = ctor;\n        func_data[1] = onFinally;\n        for(i = 0; i < 2; i++) {\n            then_funcs[i] = JS_NewCFunctionData(ctx, js_promise_then_finally_func, 1, i, 2, func_data);\n            if (JS_IsException(then_funcs[i])) {\n                if (i == 1)\n                    JS_FreeValue(ctx, then_funcs[0]);\n                JS_FreeValue(ctx, ctor);\n                return JS_EXCEPTION;\n            }\n        }\n    }\n    JS_FreeValue(ctx, ctor);\n    ret = JS_Invoke(ctx, this_val, JS_ATOM_then, 2, (JSValueConst *)then_funcs);\n    JS_FreeValue(ctx, then_funcs[0]);\n    JS_FreeValue(ctx, then_funcs[1]);\n    return ret;\n}\n\nstatic const JSCFunctionListEntry js_promise_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"resolve\", 1, js_promise_resolve, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"reject\", 1, js_promise_resolve, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"all\", 1, js_promise_all, PROMISE_MAGIC_all ),\n    JS_CFUNC_MAGIC_DEF(\"allSettled\", 1, js_promise_all, PROMISE_MAGIC_allSettled ),\n    JS_CFUNC_MAGIC_DEF(\"any\", 1, js_promise_all, PROMISE_MAGIC_any ),\n    JS_CFUNC_DEF(\"race\", 1, js_promise_race ),\n    //JS_CFUNC_DEF(\"__newPromiseCapability\", 1, js_promise___newPromiseCapability ),\n    JS_CGETSET_DEF(\"[Symbol.species]\", js_get_this, NULL),\n};\n\nstatic const JSCFunctionListEntry js_promise_proto_funcs[] = {\n    JS_CFUNC_DEF(\"then\", 2, js_promise_then ),\n    JS_CFUNC_DEF(\"catch\", 1, js_promise_catch ),\n    JS_CFUNC_DEF(\"finally\", 1, js_promise_finally ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Promise\", JS_PROP_CONFIGURABLE ),\n};\n\n/* AsyncFunction */\nstatic const JSCFunctionListEntry js_async_function_proto_funcs[] = {\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"AsyncFunction\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic JSValue js_async_from_sync_iterator_unwrap(JSContext *ctx,\n                                                  JSValueConst this_val,\n                                                  int argc, JSValueConst *argv,\n                                                  int magic, JSValue *func_data)\n{\n    return js_create_iterator_result(ctx, JS_DupValue(ctx, argv[0]),\n                                     JS_ToBool(ctx, func_data[0]));\n}\n\nstatic JSValue js_async_from_sync_iterator_unwrap_func_create(JSContext *ctx,\n                                                              BOOL done)\n{\n    JSValueConst func_data[1];\n\n    func_data[0] = JS_NewBool(ctx, done);\n    return JS_NewCFunctionData(ctx, js_async_from_sync_iterator_unwrap,\n                               1, 0, 1, func_data);\n}\n\n/* AsyncIteratorPrototype */\n\nstatic const JSCFunctionListEntry js_async_iterator_proto_funcs[] = {\n    JS_CFUNC_DEF(\"[Symbol.asyncIterator]\", 0, js_iterator_proto_iterator ),\n};\n\n/* AsyncFromSyncIteratorPrototype */\n\ntypedef struct JSAsyncFromSyncIteratorData {\n    JSValue sync_iter;\n    JSValue next_method;\n} JSAsyncFromSyncIteratorData;\n\nstatic void js_async_from_sync_iterator_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSAsyncFromSyncIteratorData *s =\n        JS_GetOpaque(val, JS_CLASS_ASYNC_FROM_SYNC_ITERATOR);\n    if (s) {\n        JS_FreeValueRT(rt, s->sync_iter);\n        JS_FreeValueRT(rt, s->next_method);\n        js_free_rt(rt, s);\n    }\n}\n\nstatic void js_async_from_sync_iterator_mark(JSRuntime *rt, JSValueConst val,\n                                             JS_MarkFunc *mark_func)\n{\n    JSAsyncFromSyncIteratorData *s =\n        JS_GetOpaque(val, JS_CLASS_ASYNC_FROM_SYNC_ITERATOR);\n    if (s) {\n        JS_MarkValue(rt, s->sync_iter, mark_func);\n        JS_MarkValue(rt, s->next_method, mark_func);\n    }\n}\n\nstatic JSValue JS_CreateAsyncFromSyncIterator(JSContext *ctx,\n                                              JSValueConst sync_iter)\n{\n    JSValue async_iter, next_method;\n    JSAsyncFromSyncIteratorData *s;\n\n    next_method = JS_GetProperty(ctx, sync_iter, JS_ATOM_next);\n    if (JS_IsException(next_method))\n        return JS_EXCEPTION;\n    async_iter = JS_NewObjectClass(ctx, JS_CLASS_ASYNC_FROM_SYNC_ITERATOR);\n    if (JS_IsException(async_iter)) {\n        JS_FreeValue(ctx, next_method);\n        return async_iter;\n    }\n    s = js_mallocz(ctx, sizeof(*s));\n    if (!s) {\n        JS_FreeValue(ctx, async_iter);\n        JS_FreeValue(ctx, next_method);\n        return JS_EXCEPTION;\n    }\n    s->sync_iter = JS_DupValue(ctx, sync_iter);\n    s->next_method = next_method;\n    JS_SetOpaque(async_iter, s);\n    return async_iter;\n}\n\nstatic JSValue js_async_from_sync_iterator_next(JSContext *ctx, JSValueConst this_val,\n                                                int argc, JSValueConst *argv,\n                                                int magic)\n{\n    JSValue promise, resolving_funcs[2], value, err, method;\n    JSAsyncFromSyncIteratorData *s;\n    int done;\n    int is_reject;\n\n    promise = JS_NewPromiseCapability(ctx, resolving_funcs);\n    if (JS_IsException(promise))\n        return JS_EXCEPTION;\n    s = JS_GetOpaque(this_val, JS_CLASS_ASYNC_FROM_SYNC_ITERATOR);\n    if (!s) {\n        JS_ThrowTypeError(ctx, \"not an Async-from-Sync Iterator\");\n        goto reject;\n    }\n\n    if (magic == GEN_MAGIC_NEXT) {\n        method = JS_DupValue(ctx, s->next_method);\n    } else {\n        method = JS_GetProperty(ctx, s->sync_iter,\n                                magic == GEN_MAGIC_RETURN ? JS_ATOM_return :\n                                JS_ATOM_throw);\n        if (JS_IsException(method))\n            goto reject;\n        if (JS_IsUndefined(method) || JS_IsNull(method)) {\n            if (magic == GEN_MAGIC_RETURN) {\n                err = js_create_iterator_result(ctx, JS_DupValue(ctx, argv[0]), TRUE);\n                is_reject = 0;\n            } else {\n                err = JS_DupValue(ctx, argv[0]);\n                is_reject = 1;\n            }\n            goto done_resolve;\n        }\n    }\n    value = JS_IteratorNext2(ctx, s->sync_iter, method,\n                             argc >= 1 ? 1 : 0, argv, &done);\n    JS_FreeValue(ctx, method);\n    if (JS_IsException(value))\n        goto reject;\n    if (done == 2) {\n        JSValue obj = value;\n        value = JS_IteratorGetCompleteValue(ctx, obj, &done);\n        JS_FreeValue(ctx, obj);\n        if (JS_IsException(value))\n            goto reject;\n    }\n\n    if (JS_IsException(value)) {\n        JSValue res2;\n    reject:\n        err = JS_GetException(ctx);\n        is_reject = 1;\n    done_resolve:\n        res2 = JS_Call(ctx, resolving_funcs[is_reject], JS_UNDEFINED,\n                       1, (JSValueConst *)&err);\n        JS_FreeValue(ctx, err);\n        JS_FreeValue(ctx, res2);\n        JS_FreeValue(ctx, resolving_funcs[0]);\n        JS_FreeValue(ctx, resolving_funcs[1]);\n        return promise;\n    }\n    {\n        JSValue value_wrapper_promise, resolve_reject[2];\n        int res;\n\n        value_wrapper_promise = js_promise_resolve(ctx, ctx->promise_ctor,\n                                                   1, (JSValueConst *)&value, 0);\n        if (JS_IsException(value_wrapper_promise)) {\n            JS_FreeValue(ctx, value);\n            goto reject;\n        }\n\n        resolve_reject[0] =\n            js_async_from_sync_iterator_unwrap_func_create(ctx, done);\n        if (JS_IsException(resolve_reject[0])) {\n            JS_FreeValue(ctx, value_wrapper_promise);\n            goto fail;\n        }\n        JS_FreeValue(ctx, value);\n        resolve_reject[1] = JS_UNDEFINED;\n\n        res = perform_promise_then(ctx, value_wrapper_promise,\n                                   (JSValueConst *)resolve_reject,\n                                   (JSValueConst *)resolving_funcs);\n        JS_FreeValue(ctx, resolve_reject[0]);\n        JS_FreeValue(ctx, value_wrapper_promise);\n        JS_FreeValue(ctx, resolving_funcs[0]);\n        JS_FreeValue(ctx, resolving_funcs[1]);\n        if (res) {\n            JS_FreeValue(ctx, promise);\n            return JS_EXCEPTION;\n        }\n    }\n    return promise;\n fail:\n    JS_FreeValue(ctx, value);\n    JS_FreeValue(ctx, resolving_funcs[0]);\n    JS_FreeValue(ctx, resolving_funcs[1]);\n    JS_FreeValue(ctx, promise);\n    return JS_EXCEPTION;\n}\n\nstatic const JSCFunctionListEntry js_async_from_sync_iterator_proto_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"next\", 1, js_async_from_sync_iterator_next, GEN_MAGIC_NEXT ),\n    JS_CFUNC_MAGIC_DEF(\"return\", 1, js_async_from_sync_iterator_next, GEN_MAGIC_RETURN ),\n    JS_CFUNC_MAGIC_DEF(\"throw\", 1, js_async_from_sync_iterator_next, GEN_MAGIC_THROW ),\n};\n\n/* AsyncGeneratorFunction */\n\nstatic const JSCFunctionListEntry js_async_generator_function_proto_funcs[] = {\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"AsyncGeneratorFunction\", JS_PROP_CONFIGURABLE ),\n};\n\n/* AsyncGenerator prototype */\n\nstatic const JSCFunctionListEntry js_async_generator_proto_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"next\", 1, js_async_generator_next, GEN_MAGIC_NEXT ),\n    JS_CFUNC_MAGIC_DEF(\"return\", 1, js_async_generator_next, GEN_MAGIC_RETURN ),\n    JS_CFUNC_MAGIC_DEF(\"throw\", 1, js_async_generator_next, GEN_MAGIC_THROW ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"AsyncGenerator\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic JSClassShortDef const js_async_class_def[] = {\n    { JS_ATOM_Promise, js_promise_finalizer, js_promise_mark },                      /* JS_CLASS_PROMISE */\n    { JS_ATOM_PromiseResolveFunction, js_promise_resolve_function_finalizer, js_promise_resolve_function_mark }, /* JS_CLASS_PROMISE_RESOLVE_FUNCTION */\n    { JS_ATOM_PromiseRejectFunction, js_promise_resolve_function_finalizer, js_promise_resolve_function_mark }, /* JS_CLASS_PROMISE_REJECT_FUNCTION */\n    { JS_ATOM_AsyncFunction, js_bytecode_function_finalizer, js_bytecode_function_mark },  /* JS_CLASS_ASYNC_FUNCTION */\n    { JS_ATOM_AsyncFunctionResolve, js_async_function_resolve_finalizer, js_async_function_resolve_mark }, /* JS_CLASS_ASYNC_FUNCTION_RESOLVE */\n    { JS_ATOM_AsyncFunctionReject, js_async_function_resolve_finalizer, js_async_function_resolve_mark }, /* JS_CLASS_ASYNC_FUNCTION_REJECT */\n    { JS_ATOM_empty_string, js_async_from_sync_iterator_finalizer, js_async_from_sync_iterator_mark }, /* JS_CLASS_ASYNC_FROM_SYNC_ITERATOR */\n    { JS_ATOM_AsyncGeneratorFunction, js_bytecode_function_finalizer, js_bytecode_function_mark },  /* JS_CLASS_ASYNC_GENERATOR_FUNCTION */\n    { JS_ATOM_AsyncGenerator, js_async_generator_finalizer, js_async_generator_mark },  /* JS_CLASS_ASYNC_GENERATOR */\n};\n\nvoid JS_AddIntrinsicPromise(JSContext *ctx)\n{\n    JSRuntime *rt = ctx->rt;\n    JSValue obj1;\n\n    if (!JS_IsRegisteredClass(rt, JS_CLASS_PROMISE)) {\n        init_class_range(rt, js_async_class_def, JS_CLASS_PROMISE,\n                         countof(js_async_class_def));\n        rt->class_array[JS_CLASS_PROMISE_RESOLVE_FUNCTION].call = js_promise_resolve_function_call;\n        rt->class_array[JS_CLASS_PROMISE_REJECT_FUNCTION].call = js_promise_resolve_function_call;\n        rt->class_array[JS_CLASS_ASYNC_FUNCTION].call = js_async_function_call;\n        rt->class_array[JS_CLASS_ASYNC_FUNCTION_RESOLVE].call = js_async_function_resolve_call;\n        rt->class_array[JS_CLASS_ASYNC_FUNCTION_REJECT].call = js_async_function_resolve_call;\n        rt->class_array[JS_CLASS_ASYNC_GENERATOR_FUNCTION].call = js_async_generator_function_call;\n    }\n\n    /* Promise */\n    ctx->class_proto[JS_CLASS_PROMISE] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_PROMISE],\n                               js_promise_proto_funcs,\n                               countof(js_promise_proto_funcs));\n    obj1 = JS_NewCFunction2(ctx, js_promise_constructor, \"Promise\", 1,\n                            JS_CFUNC_constructor, 0);\n    ctx->promise_ctor = JS_DupValue(ctx, obj1);\n    JS_SetPropertyFunctionList(ctx, obj1,\n                               js_promise_funcs,\n                               countof(js_promise_funcs));\n    JS_NewGlobalCConstructor2(ctx, obj1, \"Promise\",\n                              ctx->class_proto[JS_CLASS_PROMISE]);\n\n    /* AsyncFunction */\n    ctx->class_proto[JS_CLASS_ASYNC_FUNCTION] = JS_NewObjectProto(ctx, ctx->function_proto);\n    obj1 = JS_NewCFunction3(ctx, (JSCFunction *)js_function_constructor,\n                            \"AsyncFunction\", 1,\n                            JS_CFUNC_constructor_or_func_magic, JS_FUNC_ASYNC,\n                            ctx->function_ctor);\n    JS_SetPropertyFunctionList(ctx,\n                               ctx->class_proto[JS_CLASS_ASYNC_FUNCTION],\n                               js_async_function_proto_funcs,\n                               countof(js_async_function_proto_funcs));\n    JS_SetConstructor2(ctx, obj1, ctx->class_proto[JS_CLASS_ASYNC_FUNCTION],\n                       0, JS_PROP_CONFIGURABLE);\n    JS_FreeValue(ctx, obj1);\n\n    /* AsyncIteratorPrototype */\n    ctx->async_iterator_proto = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->async_iterator_proto,\n                               js_async_iterator_proto_funcs,\n                               countof(js_async_iterator_proto_funcs));\n\n    /* AsyncFromSyncIteratorPrototype */\n    ctx->class_proto[JS_CLASS_ASYNC_FROM_SYNC_ITERATOR] =\n        JS_NewObjectProto(ctx, ctx->async_iterator_proto);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ASYNC_FROM_SYNC_ITERATOR],\n                               js_async_from_sync_iterator_proto_funcs,\n                               countof(js_async_from_sync_iterator_proto_funcs));\n\n    /* AsyncGeneratorPrototype */\n    ctx->class_proto[JS_CLASS_ASYNC_GENERATOR] =\n        JS_NewObjectProto(ctx, ctx->async_iterator_proto);\n    JS_SetPropertyFunctionList(ctx,\n                               ctx->class_proto[JS_CLASS_ASYNC_GENERATOR],\n                               js_async_generator_proto_funcs,\n                               countof(js_async_generator_proto_funcs));\n\n    /* AsyncGeneratorFunction */\n    ctx->class_proto[JS_CLASS_ASYNC_GENERATOR_FUNCTION] =\n        JS_NewObjectProto(ctx, ctx->function_proto);\n    obj1 = JS_NewCFunction3(ctx, (JSCFunction *)js_function_constructor,\n                            \"AsyncGeneratorFunction\", 1,\n                            JS_CFUNC_constructor_or_func_magic,\n                            JS_FUNC_ASYNC_GENERATOR,\n                            ctx->function_ctor);\n    JS_SetPropertyFunctionList(ctx,\n                               ctx->class_proto[JS_CLASS_ASYNC_GENERATOR_FUNCTION],\n                               js_async_generator_function_proto_funcs,\n                               countof(js_async_generator_function_proto_funcs));\n    JS_SetConstructor2(ctx, ctx->class_proto[JS_CLASS_ASYNC_GENERATOR_FUNCTION],\n                       ctx->class_proto[JS_CLASS_ASYNC_GENERATOR],\n                       JS_PROP_CONFIGURABLE, JS_PROP_CONFIGURABLE);\n    JS_SetConstructor2(ctx, obj1, ctx->class_proto[JS_CLASS_ASYNC_GENERATOR_FUNCTION],\n                       0, JS_PROP_CONFIGURABLE);\n    JS_FreeValue(ctx, obj1);\n}\n\n/* URI handling */\n\nstatic int string_get_hex(JSString *p, int k, int n) {\n    int c = 0, h;\n    while (n-- > 0) {\n        if ((h = from_hex(string_get(p, k++))) < 0)\n            return -1;\n        c = (c << 4) | h;\n    }\n    return c;\n}\n\nstatic int isURIReserved(int c) {\n    return c < 0x100 && memchr(\";/?:@&=+$,#\", c, sizeof(\";/?:@&=+$,#\") - 1) != NULL;\n}\n\nstatic int __attribute__((format(printf, 2, 3))) js_throw_URIError(JSContext *ctx, const char *fmt, ...)\n{\n    va_list ap;\n\n    va_start(ap, fmt);\n    JS_ThrowError(ctx, JS_URI_ERROR, fmt, ap);\n    va_end(ap);\n    return -1;\n}\n\nstatic int hex_decode(JSContext *ctx, JSString *p, int k) {\n    int c;\n\n    if (k >= p->len || string_get(p, k) != '%')\n        return js_throw_URIError(ctx, \"expecting %%\");\n    if (k + 2 >= p->len || (c = string_get_hex(p, k + 1, 2)) < 0)\n        return js_throw_URIError(ctx, \"expecting hex digit\");\n\n    return c;\n}\n\nstatic JSValue js_global_decodeURI(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv, int isComponent)\n{\n    JSValue str;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p;\n    int k, c, c1, n, c_min;\n\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        return str;\n\n    string_buffer_init(ctx, b, 0);\n\n    p = JS_VALUE_GET_STRING(str);\n    for (k = 0; k < p->len;) {\n        c = string_get(p, k);\n        if (c == '%') {\n            c = hex_decode(ctx, p, k);\n            if (c < 0)\n                goto fail;\n            k += 3;\n            if (c < 0x80) {\n                if (!isComponent && isURIReserved(c)) {\n                    c = '%';\n                    k -= 2;\n                }\n            } else {\n                /* Decode URI-encoded UTF-8 sequence */\n                if (c >= 0xc0 && c <= 0xdf) {\n                    n = 1;\n                    c_min = 0x80;\n                    c &= 0x1f;\n                } else if (c >= 0xe0 && c <= 0xef) {\n                    n = 2;\n                    c_min = 0x800;\n                    c &= 0xf;\n                } else if (c >= 0xf0 && c <= 0xf7) {\n                    n = 3;\n                    c_min = 0x10000;\n                    c &= 0x7;\n                } else {\n                    n = 0;\n                    c_min = 1;\n                    c = 0;\n                }\n                while (n-- > 0) {\n                    c1 = hex_decode(ctx, p, k);\n                    if (c1 < 0)\n                        goto fail;\n                    k += 3;\n                    if ((c1 & 0xc0) != 0x80) {\n                        c = 0;\n                        break;\n                    }\n                    c = (c << 6) | (c1 & 0x3f);\n                }\n                if (c < c_min || c > 0x10FFFF ||\n                    (c >= 0xd800 && c < 0xe000)) {\n                    js_throw_URIError(ctx, \"malformed UTF-8\");\n                    goto fail;\n                }\n            }\n        } else {\n            k++;\n        }\n        string_buffer_putc(b, c);\n    }\n    JS_FreeValue(ctx, str);\n    return string_buffer_end(b);\n\nfail:\n    JS_FreeValue(ctx, str);\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nstatic int isUnescaped(int c) {\n    static char const unescaped_chars[] =\n        \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n        \"abcdefghijklmnopqrstuvwxyz\"\n        \"0123456789\"\n        \"@*_+-./\";\n    return c < 0x100 &&\n        memchr(unescaped_chars, c, sizeof(unescaped_chars) - 1);\n}\n\nstatic int isURIUnescaped(int c, int isComponent) {\n    return c < 0x100 &&\n        ((c >= 0x61 && c <= 0x7a) ||\n         (c >= 0x41 && c <= 0x5a) ||\n         (c >= 0x30 && c <= 0x39) ||\n         memchr(\"-_.!~*'()\", c, sizeof(\"-_.!~*'()\") - 1) != NULL ||\n         (!isComponent && isURIReserved(c)));\n}\n\nstatic int encodeURI_hex(StringBuffer *b, int c) {\n    uint8_t buf[6];\n    int n = 0;\n    const char *hex = \"0123456789ABCDEF\";\n\n    buf[n++] = '%';\n    if (c >= 256) {\n        buf[n++] = 'u';\n        buf[n++] = hex[(c >> 12) & 15];\n        buf[n++] = hex[(c >>  8) & 15];\n    }\n    buf[n++] = hex[(c >> 4) & 15];\n    buf[n++] = hex[(c >> 0) & 15];\n    return string_buffer_write8(b, buf, n);\n}\n\nstatic JSValue js_global_encodeURI(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv,\n                                   int isComponent)\n{\n    JSValue str;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p;\n    int k, c, c1;\n\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        return str;\n\n    p = JS_VALUE_GET_STRING(str);\n    string_buffer_init(ctx, b, p->len);\n    for (k = 0; k < p->len;) {\n        c = string_get(p, k);\n        k++;\n        if (isURIUnescaped(c, isComponent)) {\n            string_buffer_putc16(b, c);\n        } else {\n            if (c >= 0xdc00 && c <= 0xdfff) {\n                js_throw_URIError(ctx, \"invalid character\");\n                goto fail;\n            } else if (c >= 0xd800 && c <= 0xdbff) {\n                if (k >= p->len) {\n                    js_throw_URIError(ctx, \"expecting surrogate pair\");\n                    goto fail;\n                }\n                c1 = string_get(p, k);\n                k++;\n                if (c1 < 0xdc00 || c1 > 0xdfff) {\n                    js_throw_URIError(ctx, \"expecting surrogate pair\");\n                    goto fail;\n                }\n                c = (((c & 0x3ff) << 10) | (c1 & 0x3ff)) + 0x10000;\n            }\n            if (c < 0x80) {\n                encodeURI_hex(b, c);\n            } else {\n                /* XXX: use C UTF-8 conversion ? */\n                if (c < 0x800) {\n                    encodeURI_hex(b, (c >> 6) | 0xc0);\n                } else {\n                    if (c < 0x10000) {\n                        encodeURI_hex(b, (c >> 12) | 0xe0);\n                    } else {\n                        encodeURI_hex(b, (c >> 18) | 0xf0);\n                        encodeURI_hex(b, ((c >> 12) & 0x3f) | 0x80);\n                    }\n                    encodeURI_hex(b, ((c >> 6) & 0x3f) | 0x80);\n                }\n                encodeURI_hex(b, (c & 0x3f) | 0x80);\n            }\n        }\n    }\n    JS_FreeValue(ctx, str);\n    return string_buffer_end(b);\n\nfail:\n    JS_FreeValue(ctx, str);\n    string_buffer_free(b);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_global_escape(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    JSValue str;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p;\n    int i, len, c;\n\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        return str;\n\n    p = JS_VALUE_GET_STRING(str);\n    string_buffer_init(ctx, b, p->len);\n    for (i = 0, len = p->len; i < len; i++) {\n        c = string_get(p, i);\n        if (isUnescaped(c)) {\n            string_buffer_putc16(b, c);\n        } else {\n            encodeURI_hex(b, c);\n        }\n    }\n    JS_FreeValue(ctx, str);\n    return string_buffer_end(b);\n}\n\nstatic JSValue js_global_unescape(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    JSValue str;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p;\n    int i, len, c, n;\n\n    str = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(str))\n        return str;\n\n    string_buffer_init(ctx, b, 0);\n    p = JS_VALUE_GET_STRING(str);\n    for (i = 0, len = p->len; i < len; i++) {\n        c = string_get(p, i);\n        if (c == '%') {\n            if (i + 6 <= len\n            &&  string_get(p, i + 1) == 'u'\n            &&  (n = string_get_hex(p, i + 2, 4)) >= 0) {\n                c = n;\n                i += 6 - 1;\n            } else\n            if (i + 3 <= len\n            &&  (n = string_get_hex(p, i + 1, 2)) >= 0) {\n                c = n;\n                i += 3 - 1;\n            }\n        }\n        string_buffer_putc16(b, c);\n    }\n    JS_FreeValue(ctx, str);\n    return string_buffer_end(b);\n}\n\n/* global object */\n\nstatic const JSCFunctionListEntry js_global_funcs[] = {\n    JS_CFUNC_DEF(\"parseInt\", 2, js_parseInt ),\n    JS_CFUNC_DEF(\"parseFloat\", 1, js_parseFloat ),\n    JS_CFUNC_DEF(\"isNaN\", 1, js_global_isNaN ),\n    JS_CFUNC_DEF(\"isFinite\", 1, js_global_isFinite ),\n\n    JS_CFUNC_MAGIC_DEF(\"decodeURI\", 1, js_global_decodeURI, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"decodeURIComponent\", 1, js_global_decodeURI, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"encodeURI\", 1, js_global_encodeURI, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"encodeURIComponent\", 1, js_global_encodeURI, 1 ),\n    JS_CFUNC_DEF(\"escape\", 1, js_global_escape ),\n    JS_CFUNC_DEF(\"unescape\", 1, js_global_unescape ),\n    JS_PROP_DOUBLE_DEF(\"Infinity\", INFINITY, 0 ),\n    JS_PROP_DOUBLE_DEF(\"NaN\", NAN, 0 ),\n    JS_PROP_UNDEFINED_DEF(\"undefined\", 0 ),\n\n    /* for the 'Date' implementation */\n    JS_CFUNC_DEF(\"__date_clock\", 0, js___date_clock ),\n    //JS_CFUNC_DEF(\"__date_now\", 0, js___date_now ),\n    //JS_CFUNC_DEF(\"__date_getTimezoneOffset\", 1, js___date_getTimezoneOffset ),\n    //JS_CFUNC_DEF(\"__date_create\", 3, js___date_create ),\n};\n\n/* Date */\n\nstatic int64_t math_mod(int64_t a, int64_t b) {\n    /* return positive modulo */\n    int64_t m = a % b;\n    return m + (m < 0) * b;\n}\n\nstatic int64_t floor_div(int64_t a, int64_t b) {\n    /* integer division rounding toward -Infinity */\n    int64_t m = a % b;\n    return (a - (m + (m < 0) * b)) / b;\n}\n\nstatic JSValue js_Date_parse(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv);\n\nstatic __exception int JS_ThisTimeValue(JSContext *ctx, double *valp, JSValueConst this_val)\n{\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_DATE && JS_IsNumber(p->u.object_data))\n            return JS_ToFloat64(ctx, valp, p->u.object_data);\n    }\n    JS_ThrowTypeError(ctx, \"not a Date object\");\n    return -1;\n}\n\nstatic JSValue JS_SetThisTimeValue(JSContext *ctx, JSValueConst this_val, double v)\n{\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_DATE) {\n            JS_FreeValue(ctx, p->u.object_data);\n            p->u.object_data = JS_NewFloat64(ctx, v);\n            return JS_DupValue(ctx, p->u.object_data);\n        }\n    }\n    return JS_ThrowTypeError(ctx, \"not a Date object\");\n}\n\nstatic int64_t days_from_year(int64_t y) {\n    return 365 * (y - 1970) + floor_div(y - 1969, 4) -\n        floor_div(y - 1901, 100) + floor_div(y - 1601, 400);\n}\n\nstatic int64_t days_in_year(int64_t y) {\n    return 365 + !(y % 4) - !(y % 100) + !(y % 400);\n}\n\n/* return the year, update days */\nstatic int64_t year_from_days(int64_t *days) {\n    int64_t y, d1, nd, d = *days;\n    y = floor_div(d * 10000, 3652425) + 1970;\n    /* the initial approximation is very good, so only a few\n       iterations are necessary */\n    for(;;) {\n        d1 = d - days_from_year(y);\n        if (d1 < 0) {\n            y--;\n            d1 += days_in_year(y);\n        } else {\n            nd = days_in_year(y);\n            if (d1 < nd)\n                break;\n            d1 -= nd;\n            y++;\n        }\n    }\n    *days = d1;\n    return y;\n}\n\nstatic int const month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\nstatic char const month_names[] = \"JanFebMarAprMayJunJulAugSepOctNovDec\";\nstatic char const day_names[] = \"SunMonTueWedThuFriSat\";\n\nstatic __exception int get_date_fields(JSContext *ctx, JSValueConst obj,\n                                       double fields[9], int is_local, int force)\n{\n    double dval;\n    int64_t d, days, wd, y, i, md, h, m, s, ms, tz = 0;\n\n    if (JS_ThisTimeValue(ctx, &dval, obj))\n        return -1;\n\n    if (isnan(dval)) {\n        if (!force)\n            return FALSE; /* NaN */\n        d = 0;        /* initialize all fields to 0 */\n    } else {\n        d = dval;\n        if (is_local) {\n            tz = -getTimezoneOffset(d);\n            d += tz * 60000;\n        }\n    }\n\n    /* result is >= 0, we can use % */\n    h = math_mod(d, 86400000);\n    days = (d - h) / 86400000;\n    ms = h % 1000;\n    h = (h - ms) / 1000;\n    s = h % 60;\n    h = (h - s) / 60;\n    m = h % 60;\n    h = (h - m) / 60;\n    wd = math_mod(days + 4, 7); /* week day */\n    y = year_from_days(&days);\n\n    for(i = 0; i < 11; i++) {\n        md = month_days[i];\n        if (i == 1)\n            md += days_in_year(y) - 365;\n        if (days < md)\n            break;\n        days -= md;\n    }\n    fields[0] = y;\n    fields[1] = i;\n    fields[2] = days + 1;\n    fields[3] = h;\n    fields[4] = m;\n    fields[5] = s;\n    fields[6] = ms;\n    fields[7] = wd;\n    fields[8] = tz;\n    return TRUE;\n}\n\nstatic double time_clip(double t) {\n    if (t >= -8.64e15 && t <= 8.64e15)\n        return trunc(t) + 0.0;  /* convert -0 to +0 */\n    else\n        return NAN;\n}\n\n/* The spec mandates the use of 'double' and it fixes the order\n   of the operations */\nstatic double set_date_fields(double fields[], int is_local) {\n    int64_t y;\n    double days, d, h, m1;\n    int i, m, md;\n    \n    m1 = fields[1];\n    m = fmod(m1, 12);\n    if (m < 0)\n        m += 12;\n    y = (int64_t)(fields[0] + floor(m1 / 12));\n    days = days_from_year(y);\n\n    for(i = 0; i < m; i++) {\n        md = month_days[i];\n        if (i == 1)\n            md += days_in_year(y) - 365;\n        days += md;\n    }\n    days += fields[2] - 1;\n    h = fields[3] * 3600000 + fields[4] * 60000 + \n        fields[5] * 1000 + fields[6];\n    d = days * 86400000 + h;\n    if (is_local)\n        d += getTimezoneOffset(d) * 60000;\n    return time_clip(d);\n}\n\nstatic JSValue get_date_field(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int magic)\n{\n    // get_date_field(obj, n, is_local)\n    double fields[9];\n    int res, n, is_local;\n\n    is_local = magic & 0x0F;\n    n = (magic >> 4) & 0x0F;\n    res = get_date_fields(ctx, this_val, fields, is_local, 0);\n    if (res < 0)\n        return JS_EXCEPTION;\n    if (!res)\n        return JS_NAN;\n\n    if (magic & 0x100) {    // getYear\n        fields[0] -= 1900;\n    }\n    return JS_NewFloat64(ctx, fields[n]);\n}\n\nstatic JSValue set_date_field(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv, int magic)\n{\n    // _field(obj, first_field, end_field, args, is_local)\n    double fields[9];\n    int res, first_field, end_field, is_local, i, n;\n    double d, a;\n\n    d = NAN;\n    first_field = (magic >> 8) & 0x0F;\n    end_field = (magic >> 4) & 0x0F;\n    is_local = magic & 0x0F;\n\n    res = get_date_fields(ctx, this_val, fields, is_local, first_field == 0);\n    if (res < 0)\n        return JS_EXCEPTION;\n    if (res && argc > 0) {\n        n = end_field - first_field;\n        if (argc < n)\n            n = argc;\n        for(i = 0; i < n; i++) {\n            if (JS_ToFloat64(ctx, &a, argv[i]))\n                return JS_EXCEPTION;\n            if (!isfinite(a))\n                goto done;\n            fields[first_field + i] = trunc(a);\n        }\n        d = set_date_fields(fields, is_local);\n    }\ndone:\n    return JS_SetThisTimeValue(ctx, this_val, d);\n}\n\n/* fmt:\n   0: toUTCString: \"Tue, 02 Jan 2018 23:04:46 GMT\"\n   1: toString: \"Wed Jan 03 2018 00:05:22 GMT+0100 (CET)\"\n   2: toISOString: \"2018-01-02T23:02:56.927Z\"\n   3: toLocaleString: \"1/2/2018, 11:40:40 PM\"\n   part: 1=date, 2=time 3=all\n   XXX: should use a variant of strftime().\n */\nstatic JSValue get_date_string(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv, int magic)\n{\n    // _string(obj, fmt, part)\n    char buf[64];\n    double fields[9];\n    int res, fmt, part, pos;\n    int y, mon, d, h, m, s, ms, wd, tz;\n\n    fmt = (magic >> 4) & 0x0F;\n    part = magic & 0x0F;\n\n    res = get_date_fields(ctx, this_val, fields, fmt & 1, 0);\n    if (res < 0)\n        return JS_EXCEPTION;\n    if (!res) {\n        if (fmt == 2)\n            return JS_ThrowRangeError(ctx, \"Date value is NaN\");\n        else\n            return JS_NewString(ctx, \"Invalid Date\");\n    }\n\n    y = fields[0];\n    mon = fields[1];\n    d = fields[2];\n    h = fields[3];\n    m = fields[4];\n    s = fields[5];\n    ms = fields[6];\n    wd = fields[7];\n    tz = fields[8];\n\n    pos = 0;\n\n    if (part & 1) { /* date part */\n        switch(fmt) {\n        case 0:\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"%.3s, %02d %.3s %0*d \",\n                            day_names + wd * 3, d,\n                            month_names + mon * 3, 4 + (y < 0), y);\n            break;\n        case 1:\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"%.3s %.3s %02d %0*d\",\n                            day_names + wd * 3,\n                            month_names + mon * 3, d, 4 + (y < 0), y);\n            if (part == 3) {\n                buf[pos++] = ' ';\n            }\n            break;\n        case 2:\n            if (y >= 0 && y <= 9999) {\n                pos += snprintf(buf + pos, sizeof(buf) - pos,\n                                \"%04d\", y);\n            } else {\n                pos += snprintf(buf + pos, sizeof(buf) - pos,\n                                \"%+07d\", y);\n            }\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"-%02d-%02dT\", mon + 1, d);\n            break;\n        case 3:\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"%02d/%02d/%0*d\", mon + 1, d, 4 + (y < 0), y);\n            if (part == 3) {\n                buf[pos++] = ',';\n                buf[pos++] = ' ';\n            }\n            break;\n        }\n    }\n    if (part & 2) { /* time part */\n        switch(fmt) {\n        case 0:\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"%02d:%02d:%02d GMT\", h, m, s);\n            break;\n        case 1:\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"%02d:%02d:%02d GMT\", h, m, s);\n            if (tz < 0) {\n                buf[pos++] = '-';\n                tz = -tz;\n            } else {\n                buf[pos++] = '+';\n            }\n            /* tz is >= 0, can use % */\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"%02d%02d\", tz / 60, tz % 60);\n            /* XXX: tack the time zone code? */\n            break;\n        case 2:\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"%02d:%02d:%02d.%03dZ\", h, m, s, ms);\n            break;\n        case 3:\n            pos += snprintf(buf + pos, sizeof(buf) - pos,\n                            \"%02d:%02d:%02d %cM\", (h + 1) % 12 - 1, m, s,\n                            (h < 12) ? 'A' : 'P');\n            break;\n        }\n    }\n    return JS_NewStringLen(ctx, buf, pos);\n}\n\n/* OS dependent: return the UTC time in ms since 1970. */\nstatic int64_t date_now(void) {\n    struct timeval tv;\n    gettimeofday(&tv, NULL);\n    return (int64_t)tv.tv_sec * 1000 + (tv.tv_usec / 1000);\n}\n\nstatic JSValue js_date_constructor(JSContext *ctx, JSValueConst new_target,\n                                   int argc, JSValueConst *argv)\n{\n    // Date(y, mon, d, h, m, s, ms)\n    JSValue rv;\n    int i, n;\n    double a, val;\n\n    if (JS_IsUndefined(new_target)) {\n        /* invoked as function */\n        argc = 0;\n    }\n    n = argc;\n    if (n == 0) {\n        val = date_now();\n    } else if (n == 1) {\n        JSValue v, dv;\n        if (JS_VALUE_GET_TAG(argv[0]) == JS_TAG_OBJECT) {\n            JSObject *p = JS_VALUE_GET_OBJ(argv[0]);\n            if (p->class_id == JS_CLASS_DATE && JS_IsNumber(p->u.object_data)) {\n                if (JS_ToFloat64(ctx, &val, p->u.object_data))\n                    return JS_EXCEPTION;\n                val = time_clip(val);\n                goto has_val;\n            }\n        }\n        v = JS_ToPrimitive(ctx, argv[0], HINT_NONE);\n        if (JS_IsString(v)) {\n            dv = js_Date_parse(ctx, JS_UNDEFINED, 1, (JSValueConst *)&v);\n            JS_FreeValue(ctx, v);\n            if (JS_IsException(dv))\n                return JS_EXCEPTION;\n            if (JS_ToFloat64Free(ctx, &val, dv))\n                return JS_EXCEPTION;\n        } else {\n            if (JS_ToFloat64Free(ctx, &val, v))\n                return JS_EXCEPTION;\n        }\n        val = time_clip(val);\n    } else {\n        double fields[] = { 0, 0, 1, 0, 0, 0, 0 };\n        if (n > 7)\n            n = 7;\n        for(i = 0; i < n; i++) {\n            if (JS_ToFloat64(ctx, &a, argv[i]))\n                return JS_EXCEPTION;\n            if (!isfinite(a))\n                break;\n            fields[i] = trunc(a);\n            if (i == 0 && fields[0] >= 0 && fields[0] < 100)\n                fields[0] += 1900;\n        }\n        val = (i == n) ? set_date_fields(fields, 1) : NAN;\n    }\nhas_val:\n#if 0\n    JSValueConst args[3];\n    args[0] = new_target;\n    args[1] = ctx->class_proto[JS_CLASS_DATE];\n    args[2] = JS_NewFloat64(ctx, val);\n    rv = js___date_create(ctx, JS_UNDEFINED, 3, args);\n#else\n    rv = js_create_from_ctor(ctx, new_target, JS_CLASS_DATE);\n    if (!JS_IsException(rv))\n        JS_SetObjectData(ctx, rv, JS_NewFloat64(ctx, val));\n#endif\n    if (!JS_IsException(rv) && JS_IsUndefined(new_target)) {\n        /* invoked as a function, return (new Date()).toString(); */\n        JSValue s;\n        s = get_date_string(ctx, rv, 0, NULL, 0x13);\n        JS_FreeValue(ctx, rv);\n        rv = s;\n    }\n    return rv;\n}\n\nstatic JSValue js_Date_UTC(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    // UTC(y, mon, d, h, m, s, ms)\n    double fields[] = { 0, 0, 1, 0, 0, 0, 0 };\n    int i, n;\n    double a;\n\n    n = argc;\n    if (n == 0)\n        return JS_NAN;\n    if (n > 7)\n        n = 7;\n    for(i = 0; i < n; i++) {\n        if (JS_ToFloat64(ctx, &a, argv[i]))\n            return JS_EXCEPTION;\n        if (!isfinite(a))\n            return JS_NAN;\n        fields[i] = trunc(a);\n        if (i == 0 && fields[0] >= 0 && fields[0] < 100)\n            fields[0] += 1900;\n    }\n    return JS_NewFloat64(ctx, set_date_fields(fields, 0));\n}\n\nstatic void string_skip_spaces(JSString *sp, int *pp) {\n    while (*pp < sp->len && string_get(sp, *pp) == ' ')\n        *pp += 1;\n}\n\nstatic void string_skip_non_spaces(JSString *sp, int *pp) {\n    while (*pp < sp->len && string_get(sp, *pp) != ' ')\n        *pp += 1;\n}\n\n/* parse a numeric field with an optional sign if accept_sign is TRUE */\nstatic int string_get_digits(JSString *sp, int *pp, int64_t *pval) {\n    int64_t v = 0;\n    int c, p = *pp, p_start;\n    \n    if (p >= sp->len)\n        return -1;\n    p_start = p;\n    while (p < sp->len) {\n        c = string_get(sp, p);\n        if (!(c >= '0' && c <= '9')) {\n            if (p == p_start)\n                return -1;\n            else\n                break;\n        }\n        v = v * 10 + c - '0';\n        p++;\n    }\n    *pval = v;\n    *pp = p;\n    return 0;\n}\n\nstatic int string_get_signed_digits(JSString *sp, int *pp, int64_t *pval) {\n    int res, sgn, p = *pp;\n    \n    if (p >= sp->len)\n        return -1;\n\n    sgn = string_get(sp, p);\n    if (sgn == '-' || sgn == '+')\n        p++;\n \n    res = string_get_digits(sp, &p, pval);\n    if (res == 0 && sgn == '-')\n        *pval = -*pval;\n    *pp = p;\n    return res;\n}\n\n/* parse a fixed width numeric field */\nstatic int string_get_fixed_width_digits(JSString *sp, int *pp, int n, int64_t *pval) {\n    int64_t v = 0;\n    int i, c, p = *pp;\n\n    for(i = 0; i < n; i++) {\n        if (p >= sp->len)\n            return -1;\n        c = string_get(sp, p);\n        if (!(c >= '0' && c <= '9'))\n            return -1;\n        v = v * 10 + c - '0';\n        p++;\n    }\n    *pval = v;\n    *pp = p;\n    return 0;\n}\n\nstatic int string_get_milliseconds(JSString *sp, int *pp, int64_t *pval) {\n    /* parse milliseconds as a fractional part, round to nearest */\n    /* XXX: the spec does not indicate which rounding should be used */\n    int mul = 1000, ms = 0, p = *pp, c, p_start;\n    if (p >= sp->len)\n        return -1;\n    p_start = p;\n    while (p < sp->len) {\n        c = string_get(sp, p);\n        if (!(c >= '0' && c <= '9')) {\n            if (p == p_start)\n                return -1;\n            else\n                break;\n        }\n        if (mul == 1 && c >= '5')\n            ms += 1;\n        ms += (c - '0') * (mul /= 10);\n        p++;\n    }\n    *pval = ms;\n    *pp = p;\n    return 0;\n}\n\n\nstatic int find_abbrev(JSString *sp, int p, const char *list, int count) {\n    int n, i;\n\n    if (p + 3 <= sp->len) {\n        for (n = 0; n < count; n++) {\n            for (i = 0; i < 3; i++) {\n                if (string_get(sp, p + i) != month_names[n * 3 + i])\n                    goto next;\n            }\n            return n;\n        next:;\n        }\n    }\n    return -1;\n}\n\nstatic int string_get_month(JSString *sp, int *pp, int64_t *pval) {\n    int n;\n\n    string_skip_spaces(sp, pp);\n    n = find_abbrev(sp, *pp, month_names, 12);\n    if (n < 0)\n        return -1;\n\n    *pval = n;\n    *pp += 3;\n    return 0;\n}\n\nstatic JSValue js_Date_parse(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    // parse(s)\n    JSValue s, rv;\n    int64_t fields[] = { 0, 1, 1, 0, 0, 0, 0 };\n    double fields1[7];\n    int64_t tz, hh, mm;\n    double d;\n    int p, i, c, sgn, l;\n    JSString *sp;\n    BOOL is_local;\n    \n    rv = JS_NAN;\n\n    s = JS_ToString(ctx, argv[0]);\n    if (JS_IsException(s))\n        return JS_EXCEPTION;\n    \n    sp = JS_VALUE_GET_STRING(s);\n    p = 0;\n    if (p < sp->len && (((c = string_get(sp, p)) >= '0' && c <= '9') || c == '+' || c == '-')) {\n        /* ISO format */\n        /* year field can be negative */\n        if (string_get_signed_digits(sp, &p, &fields[0]))\n            goto done;\n\n        for (i = 1; i < 7; i++) {\n            if (p >= sp->len)\n                break;\n            switch(i) {\n            case 1:\n            case 2:\n                c = '-';\n                break;\n            case 3:\n                c = 'T';\n                break;\n            case 4:\n            case 5:\n                c = ':';\n                break;\n            case 6:\n                c = '.';\n                break;\n            }\n            if (string_get(sp, p) != c)\n                break;\n            p++;\n            if (i == 6) {\n                if (string_get_milliseconds(sp, &p, &fields[i]))\n                    goto done;\n            } else {\n                if (string_get_digits(sp, &p, &fields[i]))\n                    goto done;\n            }\n        }\n        /* no time: UTC by default */\n        is_local = (i > 3);\n        fields[1] -= 1;\n\n        /* parse the time zone offset if present: [+-]HH:mm or [+-]HHmm */\n        tz = 0;\n        if (p < sp->len) {\n            sgn = string_get(sp, p);\n            if (sgn == '+' || sgn == '-') {\n                p++;\n                l = sp->len - p;\n                if (l != 4 && l != 5)\n                    goto done;\n                if (string_get_fixed_width_digits(sp, &p, 2, &hh))\n                    goto done;\n                if (l == 5) {\n                    if (string_get(sp, p) != ':')\n                        goto done;\n                    p++;\n                }\n                if (string_get_fixed_width_digits(sp, &p, 2, &mm))\n                    goto done;\n                tz = hh * 60 + mm;\n                if (sgn == '-')\n                    tz = -tz;\n                is_local = FALSE;\n            } else if (sgn == 'Z') {\n                p++;\n                is_local = FALSE;\n            } else {\n                goto done;\n            }\n            /* error if extraneous characters */\n            if (p != sp->len)\n                goto done;\n        }\n    } else {\n        /* toString or toUTCString format */\n        /* skip the day of the week */\n        string_skip_non_spaces(sp, &p);\n        string_skip_spaces(sp, &p);\n        if (p >= sp->len)\n            goto done;\n        c = string_get(sp, p);\n        if (c >= '0' && c <= '9') {\n            /* day of month first */\n            if (string_get_digits(sp, &p, &fields[2]))\n                goto done;\n            if (string_get_month(sp, &p, &fields[1]))\n                goto done;\n        } else {\n            /* month first */\n            if (string_get_month(sp, &p, &fields[1]))\n                goto done;\n            string_skip_spaces(sp, &p);\n            if (string_get_digits(sp, &p, &fields[2]))\n                goto done;\n        }\n        /* year */\n        string_skip_spaces(sp, &p);\n        if (string_get_signed_digits(sp, &p, &fields[0]))\n            goto done;\n\n        /* hour, min, seconds */\n        string_skip_spaces(sp, &p);\n        for(i = 0; i < 3; i++) {\n            if (i == 1 || i == 2) {\n                if (p >= sp->len)\n                    goto done;\n                if (string_get(sp, p) != ':')\n                    goto done;\n                p++;\n            }\n            if (string_get_digits(sp, &p, &fields[3 + i]))\n                goto done;\n        }\n        // XXX: parse optional milliseconds?\n\n        /* parse the time zone offset if present: [+-]HHmm */\n        is_local = FALSE;\n        tz = 0;\n        for (tz = 0; p < sp->len; p++) {\n            sgn = string_get(sp, p);\n            if (sgn == '+' || sgn == '-') {\n                p++;\n                if (string_get_fixed_width_digits(sp, &p, 2, &hh))\n                    goto done;\n                if (string_get_fixed_width_digits(sp, &p, 2, &mm))\n                    goto done;\n                tz = hh * 60 + mm;\n                if (sgn == '-')\n                    tz = -tz;\n                break;\n            }\n        }\n    }\n    for(i = 0; i < 7; i++)\n        fields1[i] = fields[i];\n    d = set_date_fields(fields1, is_local) - tz * 60000;\n    rv = JS_NewFloat64(ctx, d);\n\ndone:\n    JS_FreeValue(ctx, s);\n    return rv;\n}\n\nstatic JSValue js_Date_now(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv)\n{\n    // now()\n    return JS_NewInt64(ctx, date_now());\n}\n\nstatic JSValue js_date_Symbol_toPrimitive(JSContext *ctx, JSValueConst this_val,\n                                          int argc, JSValueConst *argv)\n{\n    // Symbol_toPrimitive(hint)\n    JSValueConst obj = this_val;\n    JSAtom hint = JS_ATOM_NULL;\n    int hint_num;\n\n    if (!JS_IsObject(obj))\n        return JS_ThrowTypeErrorNotAnObject(ctx);\n\n    if (JS_IsString(argv[0])) {\n        hint = JS_ValueToAtom(ctx, argv[0]);\n        if (hint == JS_ATOM_NULL)\n            return JS_EXCEPTION;\n        JS_FreeAtom(ctx, hint);\n    }\n    switch (hint) {\n    case JS_ATOM_number:\n#ifdef CONFIG_BIGNUM\n    case JS_ATOM_integer:\n#endif\n        hint_num = HINT_NUMBER;\n        break;\n    case JS_ATOM_string:\n    case JS_ATOM_default:\n        hint_num = HINT_STRING;\n        break;\n    default:\n        return JS_ThrowTypeError(ctx, \"invalid hint\");\n    }\n    return JS_ToPrimitive(ctx, obj, hint_num | HINT_FORCE_ORDINARY);\n}\n\nstatic JSValue js_date_getTimezoneOffset(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    // getTimezoneOffset()\n    double v;\n\n    if (JS_ThisTimeValue(ctx, &v, this_val))\n        return JS_EXCEPTION;\n    if (isnan(v))\n        return JS_NAN;\n    else\n        return JS_NewInt64(ctx, getTimezoneOffset((int64_t)trunc(v)));\n}\n\nstatic JSValue js_date_getTime(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    // getTime()\n    double v;\n\n    if (JS_ThisTimeValue(ctx, &v, this_val))\n        return JS_EXCEPTION;\n    return JS_NewFloat64(ctx, v);\n}\n\nstatic JSValue js_date_setTime(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    // setTime(v)\n    double v;\n\n    if (JS_ThisTimeValue(ctx, &v, this_val) || JS_ToFloat64(ctx, &v, argv[0]))\n        return JS_EXCEPTION;\n    return JS_SetThisTimeValue(ctx, this_val, time_clip(v));\n}\n\nstatic JSValue js_date_setYear(JSContext *ctx, JSValueConst this_val,\n                               int argc, JSValueConst *argv)\n{\n    // setYear(y)\n    double y;\n    JSValueConst args[1];\n\n    if (JS_ThisTimeValue(ctx, &y, this_val) || JS_ToFloat64(ctx, &y, argv[0]))\n        return JS_EXCEPTION;\n    y = +y;\n    if (isfinite(y)) {\n        y = trunc(y);\n        if (y >= 0 && y < 100)\n            y += 1900;\n    }\n    args[0] = JS_NewFloat64(ctx, y);\n    return set_date_field(ctx, this_val, 1, args, 0x011);\n}\n\nstatic JSValue js_date_toJSON(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    // toJSON(key)\n    JSValue obj, tv, method, rv;\n    double d;\n\n    rv = JS_EXCEPTION;\n    tv = JS_UNDEFINED;\n\n    obj = JS_ToObject(ctx, this_val);\n    tv = JS_ToPrimitive(ctx, obj, HINT_NUMBER);\n    if (JS_IsException(tv))\n        goto exception;\n    if (JS_IsNumber(tv)) {\n        if (JS_ToFloat64(ctx, &d, tv) < 0)\n            goto exception;\n        if (!isfinite(d)) {\n            rv = JS_NULL;\n            goto done;\n        }\n    }\n    method = JS_GetPropertyStr(ctx, obj, \"toISOString\");\n    if (JS_IsException(method))\n        goto exception;\n    if (!JS_IsFunction(ctx, method)) {\n        JS_ThrowTypeError(ctx, \"object needs toISOString method\");\n        JS_FreeValue(ctx, method);\n        goto exception;\n    }\n    rv = JS_CallFree(ctx, method, obj, 0, NULL);\nexception:\ndone:\n    JS_FreeValue(ctx, obj);\n    JS_FreeValue(ctx, tv);\n    return rv;\n}\n\nstatic const JSCFunctionListEntry js_date_funcs[] = {\n    JS_CFUNC_DEF(\"now\", 0, js_Date_now ),\n    JS_CFUNC_DEF(\"parse\", 1, js_Date_parse ),\n    JS_CFUNC_DEF(\"UTC\", 7, js_Date_UTC ),\n};\n\nstatic const JSCFunctionListEntry js_date_proto_funcs[] = {\n    JS_CFUNC_DEF(\"valueOf\", 0, js_date_getTime ),\n    JS_CFUNC_MAGIC_DEF(\"toString\", 0, get_date_string, 0x13 ),\n    JS_CFUNC_DEF(\"[Symbol.toPrimitive]\", 1, js_date_Symbol_toPrimitive ),\n    JS_CFUNC_MAGIC_DEF(\"toUTCString\", 0, get_date_string, 0x03 ),\n    JS_ALIAS_DEF(\"toGMTString\", \"toUTCString\" ),\n    JS_CFUNC_MAGIC_DEF(\"toISOString\", 0, get_date_string, 0x23 ),\n    JS_CFUNC_MAGIC_DEF(\"toDateString\", 0, get_date_string, 0x11 ),\n    JS_CFUNC_MAGIC_DEF(\"toTimeString\", 0, get_date_string, 0x12 ),\n    JS_CFUNC_MAGIC_DEF(\"toLocaleString\", 0, get_date_string, 0x33 ),\n    JS_CFUNC_MAGIC_DEF(\"toLocaleDateString\", 0, get_date_string, 0x31 ),\n    JS_CFUNC_MAGIC_DEF(\"toLocaleTimeString\", 0, get_date_string, 0x32 ),\n    JS_CFUNC_DEF(\"getTimezoneOffset\", 0, js_date_getTimezoneOffset ),\n    JS_CFUNC_DEF(\"getTime\", 0, js_date_getTime ),\n    JS_CFUNC_MAGIC_DEF(\"getYear\", 0, get_date_field, 0x101 ),\n    JS_CFUNC_MAGIC_DEF(\"getFullYear\", 0, get_date_field, 0x01 ),\n    JS_CFUNC_MAGIC_DEF(\"getUTCFullYear\", 0, get_date_field, 0x00 ),\n    JS_CFUNC_MAGIC_DEF(\"getMonth\", 0, get_date_field, 0x11 ),\n    JS_CFUNC_MAGIC_DEF(\"getUTCMonth\", 0, get_date_field, 0x10 ),\n    JS_CFUNC_MAGIC_DEF(\"getDate\", 0, get_date_field, 0x21 ),\n    JS_CFUNC_MAGIC_DEF(\"getUTCDate\", 0, get_date_field, 0x20 ),\n    JS_CFUNC_MAGIC_DEF(\"getHours\", 0, get_date_field, 0x31 ),\n    JS_CFUNC_MAGIC_DEF(\"getUTCHours\", 0, get_date_field, 0x30 ),\n    JS_CFUNC_MAGIC_DEF(\"getMinutes\", 0, get_date_field, 0x41 ),\n    JS_CFUNC_MAGIC_DEF(\"getUTCMinutes\", 0, get_date_field, 0x40 ),\n    JS_CFUNC_MAGIC_DEF(\"getSeconds\", 0, get_date_field, 0x51 ),\n    JS_CFUNC_MAGIC_DEF(\"getUTCSeconds\", 0, get_date_field, 0x50 ),\n    JS_CFUNC_MAGIC_DEF(\"getMilliseconds\", 0, get_date_field, 0x61 ),\n    JS_CFUNC_MAGIC_DEF(\"getUTCMilliseconds\", 0, get_date_field, 0x60 ),\n    JS_CFUNC_MAGIC_DEF(\"getDay\", 0, get_date_field, 0x71 ),\n    JS_CFUNC_MAGIC_DEF(\"getUTCDay\", 0, get_date_field, 0x70 ),\n    JS_CFUNC_DEF(\"setTime\", 1, js_date_setTime ),\n    JS_CFUNC_MAGIC_DEF(\"setMilliseconds\", 1, set_date_field, 0x671 ),\n    JS_CFUNC_MAGIC_DEF(\"setUTCMilliseconds\", 1, set_date_field, 0x670 ),\n    JS_CFUNC_MAGIC_DEF(\"setSeconds\", 2, set_date_field, 0x571 ),\n    JS_CFUNC_MAGIC_DEF(\"setUTCSeconds\", 2, set_date_field, 0x570 ),\n    JS_CFUNC_MAGIC_DEF(\"setMinutes\", 3, set_date_field, 0x471 ),\n    JS_CFUNC_MAGIC_DEF(\"setUTCMinutes\", 3, set_date_field, 0x470 ),\n    JS_CFUNC_MAGIC_DEF(\"setHours\", 4, set_date_field, 0x371 ),\n    JS_CFUNC_MAGIC_DEF(\"setUTCHours\", 4, set_date_field, 0x370 ),\n    JS_CFUNC_MAGIC_DEF(\"setDate\", 1, set_date_field, 0x231 ),\n    JS_CFUNC_MAGIC_DEF(\"setUTCDate\", 1, set_date_field, 0x230 ),\n    JS_CFUNC_MAGIC_DEF(\"setMonth\", 2, set_date_field, 0x131 ),\n    JS_CFUNC_MAGIC_DEF(\"setUTCMonth\", 2, set_date_field, 0x130 ),\n    JS_CFUNC_DEF(\"setYear\", 1, js_date_setYear ),\n    JS_CFUNC_MAGIC_DEF(\"setFullYear\", 3, set_date_field, 0x031 ),\n    JS_CFUNC_MAGIC_DEF(\"setUTCFullYear\", 3, set_date_field, 0x030 ),\n    JS_CFUNC_DEF(\"toJSON\", 1, js_date_toJSON ),\n};\n\nvoid JS_AddIntrinsicDate(JSContext *ctx)\n{\n    JSValueConst obj;\n\n    /* Date */\n    ctx->class_proto[JS_CLASS_DATE] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_DATE], js_date_proto_funcs,\n                               countof(js_date_proto_funcs));\n    obj = JS_NewGlobalCConstructor(ctx, \"Date\", js_date_constructor, 7,\n                                   ctx->class_proto[JS_CLASS_DATE]);\n    JS_SetPropertyFunctionList(ctx, obj, js_date_funcs, countof(js_date_funcs));\n}\n\n/* eval */\n\nvoid JS_AddIntrinsicEval(JSContext *ctx)\n{\n    ctx->eval_internal = __JS_EvalInternal;\n}\n\n#ifdef CONFIG_BIGNUM\n\n/* Operators */\n\nstatic void js_operator_set_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSOperatorSetData *opset = JS_GetOpaque(val, JS_CLASS_OPERATOR_SET);\n    int i, j;\n    JSBinaryOperatorDefEntry *ent;\n    \n    if (opset) {\n        for(i = 0; i < JS_OVOP_COUNT; i++) {\n            if (opset->self_ops[i])\n                JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, opset->self_ops[i]));\n        }\n        for(j = 0; j < opset->left.count; j++) {\n            ent = &opset->left.tab[j];\n            for(i = 0; i < JS_OVOP_BINARY_COUNT; i++) {\n                if (ent->ops[i])\n                    JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, ent->ops[i]));\n            }\n        }\n        js_free_rt(rt, opset->left.tab);\n        for(j = 0; j < opset->right.count; j++) {\n            ent = &opset->right.tab[j];\n            for(i = 0; i < JS_OVOP_BINARY_COUNT; i++) {\n                if (ent->ops[i])\n                    JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, ent->ops[i]));\n            }\n        }\n        js_free_rt(rt, opset->right.tab);\n        js_free_rt(rt, opset);\n    }\n}\n\nstatic void js_operator_set_mark(JSRuntime *rt, JSValueConst val,\n                                 JS_MarkFunc *mark_func)\n{\n    JSOperatorSetData *opset = JS_GetOpaque(val, JS_CLASS_OPERATOR_SET);\n    int i, j;\n    JSBinaryOperatorDefEntry *ent;\n    \n    if (opset) {\n        for(i = 0; i < JS_OVOP_COUNT; i++) {\n            if (opset->self_ops[i])\n                JS_MarkValue(rt, JS_MKPTR(JS_TAG_OBJECT, opset->self_ops[i]),\n                             mark_func);\n        }\n        for(j = 0; j < opset->left.count; j++) {\n            ent = &opset->left.tab[j];\n            for(i = 0; i < JS_OVOP_BINARY_COUNT; i++) {\n                if (ent->ops[i])\n                    JS_MarkValue(rt, JS_MKPTR(JS_TAG_OBJECT, ent->ops[i]),\n                                 mark_func);\n            }\n        }\n        for(j = 0; j < opset->right.count; j++) {\n            ent = &opset->right.tab[j];\n            for(i = 0; i < JS_OVOP_BINARY_COUNT; i++) {\n                if (ent->ops[i])\n                    JS_MarkValue(rt, JS_MKPTR(JS_TAG_OBJECT, ent->ops[i]),\n                                 mark_func);\n            }\n        }\n    }\n}\n\n\n/* create an OperatorSet object */\nstatic JSValue js_operators_create_internal(JSContext *ctx,\n                                            int argc, JSValueConst *argv,\n                                            BOOL is_primitive)\n{\n    JSValue opset_obj, prop, obj;\n    JSOperatorSetData *opset, *opset1;\n    JSBinaryOperatorDef *def;\n    JSValueConst arg;\n    int i, j;\n    JSBinaryOperatorDefEntry *new_tab;\n    JSBinaryOperatorDefEntry *ent;\n    uint32_t op_count;\n\n    if (ctx->rt->operator_count == UINT32_MAX) {\n        return JS_ThrowTypeError(ctx, \"too many operators\");\n    }\n    opset_obj = JS_NewObjectProtoClass(ctx, JS_NULL, JS_CLASS_OPERATOR_SET);\n    if (JS_IsException(opset_obj))\n        goto fail;\n    opset = js_mallocz(ctx, sizeof(*opset));\n    if (!opset)\n        goto fail;\n    JS_SetOpaque(opset_obj, opset);\n    if (argc >= 1) {\n        arg = argv[0];\n        /* self operators */\n        for(i = 0; i < JS_OVOP_COUNT; i++) {\n            prop = JS_GetPropertyStr(ctx, arg, js_overloadable_operator_names[i]);\n            if (JS_IsException(prop))\n                goto fail;\n            if (!JS_IsUndefined(prop)) {\n                if (check_function(ctx, prop)) {\n                    JS_FreeValue(ctx, prop);\n                    goto fail;\n                }\n                opset->self_ops[i] = JS_VALUE_GET_OBJ(prop);\n            }\n        }\n    }\n    /* left & right operators */\n    for(j = 1; j < argc; j++) {\n        arg = argv[j];\n        prop = JS_GetPropertyStr(ctx, arg, \"left\");\n        if (JS_IsException(prop))\n            goto fail;\n        def = &opset->right;\n        if (JS_IsUndefined(prop)) {\n            prop = JS_GetPropertyStr(ctx, arg, \"right\");\n            if (JS_IsException(prop))\n                goto fail;\n            if (JS_IsUndefined(prop)) {\n                JS_ThrowTypeError(ctx, \"left or right property must be present\");\n                goto fail;\n            }\n            def = &opset->left;\n        }\n        /* get the operator set */\n        obj = JS_GetProperty(ctx, prop, JS_ATOM_prototype);\n        JS_FreeValue(ctx, prop);\n        if (JS_IsException(obj))\n            goto fail;\n        prop = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_operatorSet);\n        JS_FreeValue(ctx, obj);\n        if (JS_IsException(prop))\n            goto fail;\n        opset1 = JS_GetOpaque2(ctx, prop, JS_CLASS_OPERATOR_SET);\n        if (!opset1) {\n            JS_FreeValue(ctx, prop);\n            goto fail;\n        }\n        op_count = opset1->operator_counter;\n        JS_FreeValue(ctx, prop);\n        \n        /* we assume there are few entries */\n        new_tab = js_realloc(ctx, def->tab,\n                             (def->count + 1) * sizeof(def->tab[0]));\n        if (!new_tab)\n            goto fail;\n        def->tab = new_tab;\n        def->count++;\n        ent = def->tab + def->count - 1;\n        memset(ent, 0, sizeof(def->tab[0]));\n        ent->operator_index = op_count;\n        \n        for(i = 0; i < JS_OVOP_BINARY_COUNT; i++) {\n            prop = JS_GetPropertyStr(ctx, arg,\n                                     js_overloadable_operator_names[i]);\n            if (JS_IsException(prop))\n                goto fail;\n            if (!JS_IsUndefined(prop)) {\n                if (check_function(ctx, prop)) {\n                    JS_FreeValue(ctx, prop);\n                    goto fail;\n                }\n                ent->ops[i] = JS_VALUE_GET_OBJ(prop);\n            }\n        }\n    }\n    opset->is_primitive = is_primitive;\n    opset->operator_counter = ctx->rt->operator_count++;\n    return opset_obj;\n fail:\n    JS_FreeValue(ctx, opset_obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_operators_create(JSContext *ctx, JSValueConst this_val,\n                                int argc, JSValueConst *argv)\n{\n    return js_operators_create_internal(ctx, argc, argv, FALSE);\n}\n\nstatic JSValue js_operators_updateBigIntOperators(JSContext *ctx, JSValueConst this_val,\n                                                  int argc, JSValueConst *argv)\n{\n    JSValue opset_obj, prop;\n    JSOperatorSetData *opset;\n    const JSOverloadableOperatorEnum ops[2] = { JS_OVOP_DIV, JS_OVOP_POW };\n    JSOverloadableOperatorEnum op;\n    int i;\n    \n    opset_obj = JS_GetProperty(ctx, ctx->class_proto[JS_CLASS_BIG_INT],\n                               JS_ATOM_Symbol_operatorSet);\n    if (JS_IsException(opset_obj))\n        goto fail;\n    opset = JS_GetOpaque2(ctx, opset_obj, JS_CLASS_OPERATOR_SET);\n    if (!opset)\n        goto fail;\n    for(i = 0; i < countof(ops); i++) {\n        op = ops[i];\n        prop = JS_GetPropertyStr(ctx, argv[0],\n                                 js_overloadable_operator_names[op]);\n        if (JS_IsException(prop))\n            goto fail;\n        if (!JS_IsUndefined(prop)) {\n            if (!JS_IsNull(prop) && check_function(ctx, prop)) {\n                JS_FreeValue(ctx, prop);\n                goto fail;\n            }\n            if (opset->self_ops[op])\n                JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, opset->self_ops[op]));\n            if (JS_IsNull(prop)) {\n                opset->self_ops[op] = NULL;\n            } else {\n                opset->self_ops[op] = JS_VALUE_GET_PTR(prop);\n            }\n        }\n    }\n    JS_FreeValue(ctx, opset_obj);\n    return JS_UNDEFINED;\n fail:\n    JS_FreeValue(ctx, opset_obj);\n    return JS_EXCEPTION;\n}\n\nstatic int js_operators_set_default(JSContext *ctx, JSValueConst obj)\n{\n    JSValue opset_obj;\n\n    if (!JS_IsObject(obj)) /* in case the prototype is not defined */\n        return 0;\n    opset_obj = js_operators_create_internal(ctx, 0, NULL, TRUE);\n    if (JS_IsException(opset_obj))\n        return -1;\n    /* cannot be modified by the user */\n    JS_DefinePropertyValue(ctx, obj, JS_ATOM_Symbol_operatorSet,\n                           opset_obj, 0);\n    return 0;\n}\n\nstatic JSValue js_dummy_operators_ctor(JSContext *ctx, JSValueConst new_target,\n                                       int argc, JSValueConst *argv)\n{\n    return js_create_from_ctor(ctx, new_target, JS_CLASS_OBJECT);\n}\n\nstatic JSValue js_global_operators(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    JSValue func_obj, proto, opset_obj;\n\n    func_obj = JS_UNDEFINED;\n    proto = JS_NewObject(ctx);\n    if (JS_IsException(proto))\n        return JS_EXCEPTION;\n    opset_obj = js_operators_create_internal(ctx, argc, argv, FALSE);\n    if (JS_IsException(opset_obj))\n        goto fail;\n    JS_DefinePropertyValue(ctx, proto, JS_ATOM_Symbol_operatorSet,\n                           opset_obj, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    func_obj = JS_NewCFunction2(ctx, js_dummy_operators_ctor, \"Operators\",\n                                0, JS_CFUNC_constructor, 0);\n    if (JS_IsException(func_obj))\n        goto fail;\n    JS_SetConstructor2(ctx, func_obj, proto,\n                       0, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    JS_FreeValue(ctx, proto);\n    return func_obj;\n fail:\n    JS_FreeValue(ctx, proto);\n    JS_FreeValue(ctx, func_obj);\n    return JS_EXCEPTION;\n}\n\nstatic const JSCFunctionListEntry js_operators_funcs[] = {\n    JS_CFUNC_DEF(\"create\", 1, js_operators_create ),\n    JS_CFUNC_DEF(\"updateBigIntOperators\", 2, js_operators_updateBigIntOperators ),\n};\n\n/* must be called after all overloadable base types are initialized */\nvoid JS_AddIntrinsicOperators(JSContext *ctx)\n{\n    JSValue obj;\n\n    ctx->allow_operator_overloading = TRUE;\n    obj = JS_NewCFunction(ctx, js_global_operators, \"Operators\", 1);\n    JS_SetPropertyFunctionList(ctx, obj,\n                               js_operators_funcs,\n                               countof(js_operators_funcs));\n    JS_DefinePropertyValue(ctx, ctx->global_obj, JS_ATOM_Operators,\n                           obj,\n                           JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    /* add default operatorSets */\n    js_operators_set_default(ctx, ctx->class_proto[JS_CLASS_BOOLEAN]);\n    js_operators_set_default(ctx, ctx->class_proto[JS_CLASS_NUMBER]);\n    js_operators_set_default(ctx, ctx->class_proto[JS_CLASS_STRING]);\n    js_operators_set_default(ctx, ctx->class_proto[JS_CLASS_BIG_INT]);\n    js_operators_set_default(ctx, ctx->class_proto[JS_CLASS_BIG_FLOAT]);\n    js_operators_set_default(ctx, ctx->class_proto[JS_CLASS_BIG_DECIMAL]);\n}\n\n/* BigInt */\n\nstatic JSValue JS_ToBigIntCtorFree(JSContext *ctx, JSValue val)\n{\n    uint32_t tag;\n\n redo:\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_INT:\n    case JS_TAG_BOOL:\n        val = JS_NewBigInt64(ctx, JS_VALUE_GET_INT(val));\n        break;\n    case JS_TAG_BIG_INT:\n        break;\n    case JS_TAG_FLOAT64:\n    case JS_TAG_BIG_FLOAT:\n        {\n            bf_t *a, a_s;\n            \n            a = JS_ToBigFloat(ctx, &a_s, val);\n            if (!bf_is_finite(a)) {\n                JS_FreeValue(ctx, val);\n                val = JS_ThrowRangeError(ctx, \"cannot convert NaN or Infinity to bigint\");\n            } else {\n                JSValue val1 = JS_NewBigInt(ctx);\n                bf_t *r;\n                int ret;\n                if (JS_IsException(val1)) {\n                    JS_FreeValue(ctx, val);\n                    return JS_EXCEPTION;\n                }\n                r = JS_GetBigInt(val1);\n                ret = bf_set(r, a);\n                ret |= bf_rint(r, BF_RNDZ);\n                JS_FreeValue(ctx, val);\n                if (ret & BF_ST_MEM_ERROR) {\n                    JS_FreeValue(ctx, val1);\n                    val = JS_ThrowOutOfMemory(ctx);\n                } else if (ret & BF_ST_INEXACT) {\n                    JS_FreeValue(ctx, val1);\n                    val = JS_ThrowRangeError(ctx, \"cannot convert to bigint: not an integer\");\n                } else {\n                    val = JS_CompactBigInt(ctx, val1);\n                }\n            }\n            if (a == &a_s)\n                bf_delete(a);\n        }\n        break;\n    case JS_TAG_BIG_DECIMAL:\n        val = JS_ToStringFree(ctx, val);\n         if (JS_IsException(val))\n            break;\n        goto redo;\n    case JS_TAG_STRING:\n        val = JS_StringToBigIntErr(ctx, val);\n        break;\n    case JS_TAG_OBJECT:\n        val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER);\n        if (JS_IsException(val))\n            break;\n        goto redo;\n    case JS_TAG_NULL:\n    case JS_TAG_UNDEFINED:\n    default:\n        JS_FreeValue(ctx, val);\n        return JS_ThrowTypeError(ctx, \"cannot convert to bigint\");\n    }\n    return val;\n}\n\nstatic JSValue js_bigint_constructor(JSContext *ctx,\n                                     JSValueConst new_target,\n                                     int argc, JSValueConst *argv)\n{\n    if (!JS_IsUndefined(new_target))\n        return JS_ThrowTypeError(ctx, \"not a constructor\");\n    return JS_ToBigIntCtorFree(ctx, JS_DupValue(ctx, argv[0]));\n}\n\nstatic JSValue js_thisBigIntValue(JSContext *ctx, JSValueConst this_val)\n{\n    if (JS_IsBigInt(ctx, this_val))\n        return JS_DupValue(ctx, this_val);\n\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_BIG_INT) {\n            if (JS_IsBigInt(ctx, p->u.object_data))\n                return JS_DupValue(ctx, p->u.object_data);\n        }\n    }\n    return JS_ThrowTypeError(ctx, \"not a bigint\");\n}\n\nstatic JSValue js_bigint_toString(JSContext *ctx, JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    JSValue val;\n    int base;\n    JSValue ret;\n\n    val = js_thisBigIntValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (argc == 0 || JS_IsUndefined(argv[0])) {\n        base = 10;\n    } else {\n        base = js_get_radix(ctx, argv[0]);\n        if (base < 0)\n            goto fail;\n    }\n    ret = js_bigint_to_string1(ctx, val, base);\n    JS_FreeValue(ctx, val);\n    return ret;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_bigint_valueOf(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    return js_thisBigIntValue(ctx, this_val);\n}\n\nstatic JSValue js_bigint_div(JSContext *ctx,\n                              JSValueConst this_val,\n                              int argc, JSValueConst *argv, int magic)\n{\n    bf_t a_s, b_s, *a, *b, *r, *q;\n    int status;\n    JSValue q_val, r_val;\n    \n    q_val = JS_NewBigInt(ctx);\n    if (JS_IsException(q_val))\n        return JS_EXCEPTION;\n    r_val = JS_NewBigInt(ctx);\n    if (JS_IsException(r_val))\n        goto fail;\n    b = NULL;\n    a = JS_ToBigInt(ctx, &a_s, argv[0]);\n    if (!a)\n        goto fail;\n    b = JS_ToBigInt(ctx, &b_s, argv[1]);\n    if (!b) {\n        JS_FreeBigInt(ctx, a, &a_s);\n        goto fail;\n    }\n    q = JS_GetBigInt(q_val);\n    r = JS_GetBigInt(r_val);\n    status = bf_divrem(q, r, a, b, BF_PREC_INF, BF_RNDZ, magic & 0xf);\n    JS_FreeBigInt(ctx, a, &a_s);\n    JS_FreeBigInt(ctx, b, &b_s);\n    if (unlikely(status)) {\n        throw_bf_exception(ctx, status);\n        goto fail;\n    }\n    q_val = JS_CompactBigInt(ctx, q_val);\n    if (magic & 0x10) {\n        JSValue ret;\n        ret = JS_NewArray(ctx);\n        if (JS_IsException(ret))\n            goto fail;\n        JS_SetPropertyUint32(ctx, ret, 0, q_val);\n        JS_SetPropertyUint32(ctx, ret, 1, JS_CompactBigInt(ctx, r_val));\n        return ret;\n    } else {\n        JS_FreeValue(ctx, r_val);\n        return q_val;\n    }\n fail:\n    JS_FreeValue(ctx, q_val);\n    JS_FreeValue(ctx, r_val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_bigint_sqrt(JSContext *ctx,\n                               JSValueConst this_val,\n                               int argc, JSValueConst *argv, int magic)\n{\n    bf_t a_s, *a, *r, *rem;\n    int status;\n    JSValue r_val, rem_val;\n    \n    r_val = JS_NewBigInt(ctx);\n    if (JS_IsException(r_val))\n        return JS_EXCEPTION;\n    rem_val = JS_NewBigInt(ctx);\n    if (JS_IsException(rem_val))\n        return JS_EXCEPTION;\n    r = JS_GetBigInt(r_val);\n    rem = JS_GetBigInt(rem_val);\n\n    a = JS_ToBigInt(ctx, &a_s, argv[0]);\n    if (!a)\n        goto fail;\n    status = bf_sqrtrem(r, rem, a);\n    JS_FreeBigInt(ctx, a, &a_s);\n    if (unlikely(status & ~BF_ST_INEXACT)) {\n        throw_bf_exception(ctx, status);\n        goto fail;\n    }\n    r_val = JS_CompactBigInt(ctx, r_val);\n    if (magic) {\n        JSValue ret;\n        ret = JS_NewArray(ctx);\n        if (JS_IsException(ret))\n            goto fail;\n        JS_SetPropertyUint32(ctx, ret, 0, r_val);\n        JS_SetPropertyUint32(ctx, ret, 1, JS_CompactBigInt(ctx, rem_val));\n        return ret;\n    } else {\n        JS_FreeValue(ctx, rem_val);\n        return r_val;\n    }\n fail:\n    JS_FreeValue(ctx, r_val);\n    JS_FreeValue(ctx, rem_val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_bigint_op1(JSContext *ctx,\n                              JSValueConst this_val,\n                              int argc, JSValueConst *argv,\n                              int magic)\n{\n    bf_t a_s, *a;\n    int64_t res;\n\n    a = JS_ToBigInt(ctx, &a_s, argv[0]);\n    if (!a)\n        return JS_EXCEPTION;\n    switch(magic) {\n    case 0: /* floorLog2 */\n        if (a->sign || a->expn <= 0) {\n            res = -1;\n        } else {\n            res = a->expn - 1;\n        }\n        break;\n    case 1: /* ctz */\n        if (bf_is_zero(a)) {\n            res = -1;\n        } else {\n            res = bf_get_exp_min(a);\n        }\n        break;\n    default:\n        abort();\n    }\n    JS_FreeBigInt(ctx, a, &a_s);\n    return JS_NewBigInt64(ctx, res);\n}\n\nstatic JSValue js_bigint_asUintN(JSContext *ctx,\n                                  JSValueConst this_val,\n                                  int argc, JSValueConst *argv, int asIntN)\n{\n    uint64_t bits;\n    bf_t a_s, *a = &a_s, *r, mask_s, *mask = &mask_s;\n    JSValue res;\n    \n    if (JS_ToIndex(ctx, &bits, argv[0]))\n        return JS_EXCEPTION;\n    res = JS_NewBigInt(ctx);\n    if (JS_IsException(res))\n        return JS_EXCEPTION;\n    r = JS_GetBigInt(res);\n    a = JS_ToBigInt(ctx, &a_s, argv[1]);\n    if (!a) {\n        JS_FreeValue(ctx, res);\n        return JS_EXCEPTION;\n    }\n    /* XXX: optimize */\n    r = JS_GetBigInt(res);\n    bf_init(ctx->bf_ctx, mask);\n    bf_set_ui(mask, 1);\n    bf_mul_2exp(mask, bits, BF_PREC_INF, BF_RNDZ);\n    bf_add_si(mask, mask, -1, BF_PREC_INF, BF_RNDZ);\n    bf_logic_and(r, a, mask);\n    if (asIntN && bits != 0) {\n        bf_set_ui(mask, 1);\n        bf_mul_2exp(mask, bits - 1, BF_PREC_INF, BF_RNDZ);\n        if (bf_cmpu(r, mask) >= 0) {\n            bf_set_ui(mask, 1);\n            bf_mul_2exp(mask, bits, BF_PREC_INF, BF_RNDZ);\n            bf_sub(r, r, mask, BF_PREC_INF, BF_RNDZ);\n        }\n    }\n    bf_delete(mask);\n    JS_FreeBigInt(ctx, a, &a_s);\n    return JS_CompactBigInt(ctx, res);\n}\n\nstatic const JSCFunctionListEntry js_bigint_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"asUintN\", 2, js_bigint_asUintN, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"asIntN\", 2, js_bigint_asUintN, 1 ),\n    /* QuickJS extensions */\n    JS_CFUNC_MAGIC_DEF(\"tdiv\", 2, js_bigint_div, BF_RNDZ ),\n    JS_CFUNC_MAGIC_DEF(\"fdiv\", 2, js_bigint_div, BF_RNDD ),\n    JS_CFUNC_MAGIC_DEF(\"cdiv\", 2, js_bigint_div, BF_RNDU ),\n    JS_CFUNC_MAGIC_DEF(\"ediv\", 2, js_bigint_div, BF_DIVREM_EUCLIDIAN ),\n    JS_CFUNC_MAGIC_DEF(\"tdivrem\", 2, js_bigint_div, BF_RNDZ | 0x10 ),\n    JS_CFUNC_MAGIC_DEF(\"fdivrem\", 2, js_bigint_div, BF_RNDD | 0x10 ),\n    JS_CFUNC_MAGIC_DEF(\"cdivrem\", 2, js_bigint_div, BF_RNDU | 0x10 ),\n    JS_CFUNC_MAGIC_DEF(\"edivrem\", 2, js_bigint_div, BF_DIVREM_EUCLIDIAN | 0x10 ),\n    JS_CFUNC_MAGIC_DEF(\"sqrt\", 1, js_bigint_sqrt, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"sqrtrem\", 1, js_bigint_sqrt, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"floorLog2\", 1, js_bigint_op1, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"ctz\", 1, js_bigint_op1, 1 ),\n};\n\nstatic const JSCFunctionListEntry js_bigint_proto_funcs[] = {\n    JS_CFUNC_DEF(\"toString\", 0, js_bigint_toString ),\n    JS_CFUNC_DEF(\"valueOf\", 0, js_bigint_valueOf ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"BigInt\", JS_PROP_CONFIGURABLE ),\n};\n\nvoid JS_AddIntrinsicBigInt(JSContext *ctx)\n{\n    JSRuntime *rt = ctx->rt;\n    JSValueConst obj1;\n\n    rt->bigint_ops.to_string = js_bigint_to_string;\n    rt->bigint_ops.from_string = js_string_to_bigint;\n    rt->bigint_ops.unary_arith = js_unary_arith_bigint;\n    rt->bigint_ops.binary_arith = js_binary_arith_bigint;\n    rt->bigint_ops.compare = js_compare_bigfloat;\n    \n    ctx->class_proto[JS_CLASS_BIG_INT] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_BIG_INT],\n                               js_bigint_proto_funcs,\n                               countof(js_bigint_proto_funcs));\n    obj1 = JS_NewGlobalCConstructor(ctx, \"BigInt\", js_bigint_constructor, 1,\n                                    ctx->class_proto[JS_CLASS_BIG_INT]);\n    JS_SetPropertyFunctionList(ctx, obj1, js_bigint_funcs,\n                               countof(js_bigint_funcs));\n}\n\n/* BigFloat */\n\nstatic JSValue js_thisBigFloatValue(JSContext *ctx, JSValueConst this_val)\n{\n    if (JS_IsBigFloat(this_val))\n        return JS_DupValue(ctx, this_val);\n\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_BIG_FLOAT) {\n            if (JS_IsBigFloat(p->u.object_data))\n                return JS_DupValue(ctx, p->u.object_data);\n        }\n    }\n    return JS_ThrowTypeError(ctx, \"not a bigfloat\");\n}\n\nstatic JSValue js_bigfloat_toString(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSValue val;\n    int base;\n    JSValue ret;\n\n    val = js_thisBigFloatValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (argc == 0 || JS_IsUndefined(argv[0])) {\n        base = 10;\n    } else {\n        base = js_get_radix(ctx, argv[0]);\n        if (base < 0)\n            goto fail;\n    }\n    ret = js_ftoa(ctx, val, base, 0, BF_RNDN | BF_FTOA_FORMAT_FREE_MIN);\n    JS_FreeValue(ctx, val);\n    return ret;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_bigfloat_valueOf(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    return js_thisBigFloatValue(ctx, this_val);\n}\n\nstatic int bigfloat_get_rnd_mode(JSContext *ctx, JSValueConst val)\n{\n    int rnd_mode;\n    if (JS_ToInt32Sat(ctx, &rnd_mode, val))\n        return -1;\n    if (rnd_mode < BF_RNDN || rnd_mode > BF_RNDF) {\n        JS_ThrowRangeError(ctx, \"invalid rounding mode\");\n        return -1;\n    }\n    return rnd_mode;\n}\n\nstatic JSValue js_bigfloat_toFixed(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    int64_t f;\n    int rnd_mode, radix;\n\n    val = js_thisBigFloatValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_ToInt64Sat(ctx, &f, argv[0]))\n        goto fail;\n    if (f < 0 || f > BF_PREC_MAX) {\n        JS_ThrowRangeError(ctx, \"invalid number of digits\");\n        goto fail;\n    }\n    rnd_mode = BF_RNDNA;\n    radix = 10;\n    /* XXX: swap parameter order for rounding mode and radix */\n    if (argc > 1) {\n        rnd_mode = bigfloat_get_rnd_mode(ctx, argv[1]);\n        if (rnd_mode < 0)\n            goto fail;\n    }\n    if (argc > 2) {\n        radix = js_get_radix(ctx, argv[2]);\n        if (radix < 0)\n            goto fail;\n    }\n    ret = js_ftoa(ctx, val, radix, f, rnd_mode | BF_FTOA_FORMAT_FRAC);\n    JS_FreeValue(ctx, val);\n    return ret;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic BOOL js_bigfloat_is_finite(JSContext *ctx, JSValueConst val)\n{\n    BOOL res;\n    uint32_t tag;\n\n    tag = JS_VALUE_GET_NORM_TAG(val);\n    switch(tag) {\n    case JS_TAG_BIG_FLOAT:\n        {\n            JSBigFloat *p = JS_VALUE_GET_PTR(val);\n            res = bf_is_finite(&p->num);\n        }\n        break;\n    default:\n        res = FALSE;\n        break;\n    }\n    return res;\n}\n\nstatic JSValue js_bigfloat_toExponential(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    int64_t f;\n    int rnd_mode, radix;\n\n    val = js_thisBigFloatValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_ToInt64Sat(ctx, &f, argv[0]))\n        goto fail;\n    if (!js_bigfloat_is_finite(ctx, val)) {\n        ret = JS_ToString(ctx, val);\n    } else if (JS_IsUndefined(argv[0])) {\n        ret = js_ftoa(ctx, val, 10, 0,\n                      BF_RNDN | BF_FTOA_FORMAT_FREE_MIN | BF_FTOA_FORCE_EXP);\n    } else {\n        if (f < 0 || f > BF_PREC_MAX) {\n            JS_ThrowRangeError(ctx, \"invalid number of digits\");\n            goto fail;\n        }\n        rnd_mode = BF_RNDNA;\n        radix = 10;\n        if (argc > 1) {\n            rnd_mode = bigfloat_get_rnd_mode(ctx, argv[1]);\n            if (rnd_mode < 0)\n                goto fail;\n        }\n        if (argc > 2) {\n            radix = js_get_radix(ctx, argv[2]);\n            if (radix < 0)\n                goto fail;\n        }\n        ret = js_ftoa(ctx, val, radix, f + 1,\n                      rnd_mode | BF_FTOA_FORMAT_FIXED | BF_FTOA_FORCE_EXP);\n    }\n    JS_FreeValue(ctx, val);\n    return ret;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_bigfloat_toPrecision(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    int64_t p;\n    int rnd_mode, radix;\n\n    val = js_thisBigFloatValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_IsUndefined(argv[0]))\n        goto to_string;\n    if (JS_ToInt64Sat(ctx, &p, argv[0]))\n        goto fail;\n    if (!js_bigfloat_is_finite(ctx, val)) {\n    to_string:\n        ret = JS_ToString(ctx, this_val);\n    } else {\n        if (p < 1 || p > BF_PREC_MAX) {\n            JS_ThrowRangeError(ctx, \"invalid number of digits\");\n            goto fail;\n        }\n        rnd_mode = BF_RNDNA;\n        radix = 10;\n        if (argc > 1) {\n            rnd_mode = bigfloat_get_rnd_mode(ctx, argv[1]);\n            if (rnd_mode < 0)\n                goto fail;\n        }\n        if (argc > 2) {\n            radix = js_get_radix(ctx, argv[2]);\n            if (radix < 0)\n                goto fail;\n        }\n        ret = js_ftoa(ctx, val, radix, p, rnd_mode | BF_FTOA_FORMAT_FIXED);\n    }\n    JS_FreeValue(ctx, val);\n    return ret;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic const JSCFunctionListEntry js_bigfloat_proto_funcs[] = {\n    JS_CFUNC_DEF(\"toString\", 0, js_bigfloat_toString ),\n    JS_CFUNC_DEF(\"valueOf\", 0, js_bigfloat_valueOf ),\n    JS_CFUNC_DEF(\"toPrecision\", 1, js_bigfloat_toPrecision ),\n    JS_CFUNC_DEF(\"toFixed\", 1, js_bigfloat_toFixed ),\n    JS_CFUNC_DEF(\"toExponential\", 1, js_bigfloat_toExponential ),\n};\n\nstatic JSValue js_bigfloat_constructor(JSContext *ctx,\n                                       JSValueConst new_target,\n                                       int argc, JSValueConst *argv)\n{\n    JSValue val;\n    if (!JS_IsUndefined(new_target))\n        return JS_ThrowTypeError(ctx, \"not a constructor\");\n    if (argc == 0) {\n        bf_t *r;\n        val = JS_NewBigFloat(ctx);\n        if (JS_IsException(val))\n            return val;\n        r = JS_GetBigFloat(val);\n        bf_set_zero(r, 0);\n    } else {\n        val = JS_DupValue(ctx, argv[0]);\n    redo:\n        switch(JS_VALUE_GET_NORM_TAG(val)) {\n        case JS_TAG_BIG_FLOAT:\n            break;\n        case JS_TAG_FLOAT64:\n            {\n                bf_t *r;\n                double d = JS_VALUE_GET_FLOAT64(val);\n                val = JS_NewBigFloat(ctx);\n                if (JS_IsException(val))\n                    break;\n                r = JS_GetBigFloat(val);\n                if (bf_set_float64(r, d))\n                    goto fail;\n            }\n            break;\n        case JS_TAG_INT:\n            {\n                bf_t *r;\n                int32_t v = JS_VALUE_GET_INT(val);\n                val = JS_NewBigFloat(ctx);\n                if (JS_IsException(val))\n                    break;\n                r = JS_GetBigFloat(val);\n                if (bf_set_si(r, v))\n                    goto fail;\n            }\n            break;\n        case JS_TAG_BIG_INT:\n            /* We keep the full precision of the integer */\n            {\n                JSBigFloat *p = JS_VALUE_GET_PTR(val);\n                val = JS_MKPTR(JS_TAG_BIG_FLOAT, p);\n            }\n            break;\n        case JS_TAG_BIG_DECIMAL:\n            val = JS_ToStringFree(ctx, val);\n            if (JS_IsException(val))\n                break;\n            goto redo;\n        case JS_TAG_STRING:\n            {\n                const char *str, *p;\n                size_t len;\n                int err;\n\n                str = JS_ToCStringLen(ctx, &len, val);\n                JS_FreeValue(ctx, val);\n                if (!str)\n                    return JS_EXCEPTION;\n                p = str;\n                p += skip_spaces(p);\n                if ((p - str) == len) {\n                    bf_t *r;\n                    val = JS_NewBigFloat(ctx);\n                    if (JS_IsException(val))\n                        break;\n                    r = JS_GetBigFloat(val);\n                    bf_set_zero(r, 0);\n                    err = 0;\n                } else {\n                    val = js_atof(ctx, p, &p, 0, ATOD_ACCEPT_BIN_OCT |\n                                  ATOD_TYPE_BIG_FLOAT |\n                                  ATOD_ACCEPT_PREFIX_AFTER_SIGN);\n                    if (JS_IsException(val)) {\n                        JS_FreeCString(ctx, str);\n                        return JS_EXCEPTION;\n                    }\n                    p += skip_spaces(p);\n                    err = ((p - str) != len);\n                }\n                JS_FreeCString(ctx, str);\n                if (err) {\n                    JS_FreeValue(ctx, val);\n                    return JS_ThrowSyntaxError(ctx, \"invalid bigfloat literal\");\n                }\n            }\n            break;\n        case JS_TAG_OBJECT:\n            val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER);\n            if (JS_IsException(val))\n                break;\n            goto redo;\n        case JS_TAG_NULL:\n        case JS_TAG_UNDEFINED:\n        default:\n            JS_FreeValue(ctx, val);\n            return JS_ThrowTypeError(ctx, \"cannot convert to bigfloat\");\n        }\n    }\n    return val;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_bigfloat_get_const(JSContext *ctx,\n                                     JSValueConst this_val, int magic)\n{\n    bf_t *r;\n    JSValue val;\n    val = JS_NewBigFloat(ctx);\n    if (JS_IsException(val))\n        return val;\n    r = JS_GetBigFloat(val);\n    switch(magic) {\n    case 0: /* PI */\n        bf_const_pi(r, ctx->fp_env.prec, ctx->fp_env.flags);\n        break;\n    case 1: /* LN2 */\n        bf_const_log2(r, ctx->fp_env.prec, ctx->fp_env.flags);\n        break;\n    case 2: /* MIN_VALUE */\n    case 3: /* MAX_VALUE */\n        {\n            slimb_t e_range, e;\n            e_range = (limb_t)1 << (bf_get_exp_bits(ctx->fp_env.flags) - 1);\n            bf_set_ui(r, 1);\n            if (magic == 2) {\n                e = -e_range + 2;\n                if (ctx->fp_env.flags & BF_FLAG_SUBNORMAL)\n                    e -= ctx->fp_env.prec - 1;\n                bf_mul_2exp(r, e, ctx->fp_env.prec, ctx->fp_env.flags);\n            } else {\n                bf_mul_2exp(r, ctx->fp_env.prec, ctx->fp_env.prec,\n                            ctx->fp_env.flags);\n                bf_add_si(r, r, -1, ctx->fp_env.prec, ctx->fp_env.flags);\n                bf_mul_2exp(r, e_range - ctx->fp_env.prec, ctx->fp_env.prec,\n                            ctx->fp_env.flags);\n            }\n        }\n        break;\n    case 4: /* EPSILON */\n        bf_set_ui(r, 1);\n        bf_mul_2exp(r, 1 - ctx->fp_env.prec,\n                    ctx->fp_env.prec, ctx->fp_env.flags);\n        break;\n    default:\n        abort();\n    }\n    return val;\n}\n\nstatic JSValue js_bigfloat_parseFloat(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv)\n{\n    bf_t *a;\n    const char *str;\n    JSValue ret;\n    int radix;\n    JSFloatEnv *fe;\n\n    str = JS_ToCString(ctx, argv[0]);\n    if (!str)\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &radix, argv[1])) {\n    fail:\n        JS_FreeCString(ctx, str);\n        return JS_EXCEPTION;\n    }\n    if (radix != 0 && (radix < 2 || radix > 36)) {\n        JS_ThrowRangeError(ctx, \"radix must be between 2 and 36\");\n        goto fail;\n    }\n    fe = &ctx->fp_env;\n    if (argc > 2) {\n        fe = JS_GetOpaque2(ctx, argv[2], JS_CLASS_FLOAT_ENV);\n        if (!fe)\n            goto fail;\n    }\n    ret = JS_NewBigFloat(ctx);\n    if (JS_IsException(ret))\n        goto done;\n    a = JS_GetBigFloat(ret);\n    /* XXX: use js_atof() */\n    bf_atof(a, str, NULL, radix, fe->prec, fe->flags);\n done:\n    JS_FreeCString(ctx, str);\n    return ret;\n}\n\nstatic JSValue js_bigfloat_isFinite(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSValueConst val = argv[0];\n    JSBigFloat *p;\n    \n    if (JS_VALUE_GET_NORM_TAG(val) != JS_TAG_BIG_FLOAT)\n        return JS_FALSE;\n    p = JS_VALUE_GET_PTR(val);\n    return JS_NewBool(ctx, bf_is_finite(&p->num));\n}\n\nstatic JSValue js_bigfloat_isNaN(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValueConst val = argv[0];\n    JSBigFloat *p;\n    \n    if (JS_VALUE_GET_NORM_TAG(val) != JS_TAG_BIG_FLOAT)\n        return JS_FALSE;\n    p = JS_VALUE_GET_PTR(val);\n    return JS_NewBool(ctx, bf_is_nan(&p->num));\n}\n\nenum {\n    MATH_OP_ABS,\n    MATH_OP_FLOOR,\n    MATH_OP_CEIL,\n    MATH_OP_ROUND,\n    MATH_OP_TRUNC,\n    MATH_OP_SQRT,\n    MATH_OP_FPROUND,\n    MATH_OP_ACOS,\n    MATH_OP_ASIN,\n    MATH_OP_ATAN,\n    MATH_OP_ATAN2,\n    MATH_OP_COS,\n    MATH_OP_EXP,\n    MATH_OP_LOG,\n    MATH_OP_POW,\n    MATH_OP_SIN,\n    MATH_OP_TAN,\n    MATH_OP_FMOD,\n    MATH_OP_REM,\n    MATH_OP_SIGN,\n\n    MATH_OP_ADD,\n    MATH_OP_SUB,\n    MATH_OP_MUL,\n    MATH_OP_DIV,\n};\n\nstatic JSValue js_bigfloat_fop(JSContext *ctx, JSValueConst this_val,\n                           int argc, JSValueConst *argv, int magic)\n{\n    bf_t a_s, *a, *r;\n    JSFloatEnv *fe;\n    int rnd_mode;\n    JSValue op1, res;\n\n    op1 = JS_ToNumeric(ctx, argv[0]);\n    if (JS_IsException(op1))\n        return op1;\n    a = JS_ToBigFloat(ctx, &a_s, op1);\n    fe = &ctx->fp_env;\n    if (argc > 1) {\n        fe = JS_GetOpaque2(ctx, argv[1], JS_CLASS_FLOAT_ENV);\n        if (!fe)\n            goto fail;\n    }\n    res = JS_NewBigFloat(ctx);\n    if (JS_IsException(res)) {\n    fail:\n        if (a == &a_s)\n            bf_delete(a);\n        JS_FreeValue(ctx, op1);\n        return JS_EXCEPTION;\n    }\n    r = JS_GetBigFloat(res);\n    switch (magic) {\n    case MATH_OP_ABS:\n        bf_set(r, a);\n        r->sign = 0;\n        break;\n    case MATH_OP_FLOOR:\n        rnd_mode = BF_RNDD;\n        goto rint;\n    case MATH_OP_CEIL:\n        rnd_mode = BF_RNDU;\n        goto rint;\n    case MATH_OP_ROUND:\n        rnd_mode = BF_RNDNA;\n        goto rint;\n    case MATH_OP_TRUNC:\n        rnd_mode = BF_RNDZ;\n    rint:\n        bf_set(r, a);\n        fe->status |= bf_rint(r, rnd_mode);\n        break;\n    case MATH_OP_SQRT:\n        fe->status |= bf_sqrt(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_FPROUND:\n        bf_set(r, a);\n        fe->status |= bf_round(r, fe->prec, fe->flags);\n        break;\n    case MATH_OP_ACOS:\n        fe->status |= bf_acos(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_ASIN:\n        fe->status |= bf_asin(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_ATAN:\n        fe->status |= bf_atan(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_COS:\n        fe->status |= bf_cos(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_EXP:\n        fe->status |= bf_exp(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_LOG:\n        fe->status |= bf_log(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_SIN:\n        fe->status |= bf_sin(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_TAN:\n        fe->status |= bf_tan(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_SIGN:\n        if (bf_is_nan(a) || bf_is_zero(a)) {\n            bf_set(r, a);\n        } else {\n            bf_set_si(r, 1 - 2 * a->sign);\n        }\n        break;\n    default:\n        abort();\n    }\n    if (a == &a_s)\n        bf_delete(a);\n    JS_FreeValue(ctx, op1);\n    return res;\n}\n\nstatic JSValue js_bigfloat_fop2(JSContext *ctx, JSValueConst this_val,\n                            int argc, JSValueConst *argv, int magic)\n{\n    bf_t a_s, *a, b_s, *b, r_s, *r = &r_s;\n    JSFloatEnv *fe;\n    JSValue op1, op2, res;\n\n    op1 = JS_ToNumeric(ctx, argv[0]);\n    if (JS_IsException(op1))\n        return op1;\n    op2 = JS_ToNumeric(ctx, argv[1]);\n    if (JS_IsException(op2)) {\n        JS_FreeValue(ctx, op1);\n        return op2;\n    }\n    a = JS_ToBigFloat(ctx, &a_s, op1);\n    b = JS_ToBigFloat(ctx, &b_s, op2);\n    fe = &ctx->fp_env;\n    if (argc > 2) {\n        fe = JS_GetOpaque2(ctx, argv[2], JS_CLASS_FLOAT_ENV);\n        if (!fe)\n            goto fail;\n    }\n    res = JS_NewBigFloat(ctx);\n    if (JS_IsException(res)) {\n    fail:\n        if (a == &a_s)\n            bf_delete(a);\n        if (b == &b_s)\n            bf_delete(b);\n        JS_FreeValue(ctx, op1);\n        JS_FreeValue(ctx, op2);\n        return JS_EXCEPTION;\n    }\n    r = JS_GetBigFloat(res);\n    switch (magic) {\n    case MATH_OP_ATAN2:\n        fe->status |= bf_atan2(r, a, b, fe->prec, fe->flags);\n        break;\n    case MATH_OP_POW:\n        fe->status |= bf_pow(r, a, b, fe->prec, fe->flags | BF_POW_JS_QUIRKS);\n        break;\n    case MATH_OP_FMOD:\n        fe->status |= bf_rem(r, a, b, fe->prec, fe->flags, BF_RNDZ);\n        break;\n    case MATH_OP_REM:\n        fe->status |= bf_rem(r, a, b, fe->prec, fe->flags, BF_RNDN);\n        break;\n    case MATH_OP_ADD:\n        fe->status |= bf_add(r, a, b, fe->prec, fe->flags);\n        break;\n    case MATH_OP_SUB:\n        fe->status |= bf_sub(r, a, b, fe->prec, fe->flags);\n        break;\n    case MATH_OP_MUL:\n        fe->status |= bf_mul(r, a, b, fe->prec, fe->flags);\n        break;\n    case MATH_OP_DIV:\n        fe->status |= bf_div(r, a, b, fe->prec, fe->flags);\n        break;\n    default:\n        abort();\n    }\n    if (a == &a_s)\n        bf_delete(a);\n    if (b == &b_s)\n        bf_delete(b);\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    return res;\n}\n\nstatic const JSCFunctionListEntry js_bigfloat_funcs[] = {\n    JS_CGETSET_MAGIC_DEF(\"PI\", js_bigfloat_get_const, NULL, 0 ),\n    JS_CGETSET_MAGIC_DEF(\"LN2\", js_bigfloat_get_const, NULL, 1 ),\n    JS_CGETSET_MAGIC_DEF(\"MIN_VALUE\", js_bigfloat_get_const, NULL, 2 ),\n    JS_CGETSET_MAGIC_DEF(\"MAX_VALUE\", js_bigfloat_get_const, NULL, 3 ),\n    JS_CGETSET_MAGIC_DEF(\"EPSILON\", js_bigfloat_get_const, NULL, 4 ),\n    JS_CFUNC_DEF(\"parseFloat\", 1, js_bigfloat_parseFloat ),\n    JS_CFUNC_DEF(\"isFinite\", 1, js_bigfloat_isFinite ),\n    JS_CFUNC_DEF(\"isNaN\", 1, js_bigfloat_isNaN ),\n    JS_CFUNC_MAGIC_DEF(\"abs\", 1, js_bigfloat_fop, MATH_OP_ABS ),\n    JS_CFUNC_MAGIC_DEF(\"fpRound\", 1, js_bigfloat_fop, MATH_OP_FPROUND ),\n    JS_CFUNC_MAGIC_DEF(\"floor\", 1, js_bigfloat_fop, MATH_OP_FLOOR ),\n    JS_CFUNC_MAGIC_DEF(\"ceil\", 1, js_bigfloat_fop, MATH_OP_CEIL ),\n    JS_CFUNC_MAGIC_DEF(\"round\", 1, js_bigfloat_fop, MATH_OP_ROUND ),\n    JS_CFUNC_MAGIC_DEF(\"trunc\", 1, js_bigfloat_fop, MATH_OP_TRUNC ),\n    JS_CFUNC_MAGIC_DEF(\"sqrt\", 1, js_bigfloat_fop, MATH_OP_SQRT ),\n    JS_CFUNC_MAGIC_DEF(\"acos\", 1, js_bigfloat_fop, MATH_OP_ACOS ),\n    JS_CFUNC_MAGIC_DEF(\"asin\", 1, js_bigfloat_fop, MATH_OP_ASIN ),\n    JS_CFUNC_MAGIC_DEF(\"atan\", 1, js_bigfloat_fop, MATH_OP_ATAN ),\n    JS_CFUNC_MAGIC_DEF(\"atan2\", 2, js_bigfloat_fop2, MATH_OP_ATAN2 ),\n    JS_CFUNC_MAGIC_DEF(\"cos\", 1, js_bigfloat_fop, MATH_OP_COS ),\n    JS_CFUNC_MAGIC_DEF(\"exp\", 1, js_bigfloat_fop, MATH_OP_EXP ),\n    JS_CFUNC_MAGIC_DEF(\"log\", 1, js_bigfloat_fop, MATH_OP_LOG ),\n    JS_CFUNC_MAGIC_DEF(\"pow\", 2, js_bigfloat_fop2, MATH_OP_POW ),\n    JS_CFUNC_MAGIC_DEF(\"sin\", 1, js_bigfloat_fop, MATH_OP_SIN ),\n    JS_CFUNC_MAGIC_DEF(\"tan\", 1, js_bigfloat_fop, MATH_OP_TAN ),\n    JS_CFUNC_MAGIC_DEF(\"sign\", 1, js_bigfloat_fop, MATH_OP_SIGN ),\n    JS_CFUNC_MAGIC_DEF(\"add\", 2, js_bigfloat_fop2, MATH_OP_ADD ),\n    JS_CFUNC_MAGIC_DEF(\"sub\", 2, js_bigfloat_fop2, MATH_OP_SUB ),\n    JS_CFUNC_MAGIC_DEF(\"mul\", 2, js_bigfloat_fop2, MATH_OP_MUL ),\n    JS_CFUNC_MAGIC_DEF(\"div\", 2, js_bigfloat_fop2, MATH_OP_DIV ),\n    JS_CFUNC_MAGIC_DEF(\"fmod\", 2, js_bigfloat_fop2, MATH_OP_FMOD ),\n    JS_CFUNC_MAGIC_DEF(\"remainder\", 2, js_bigfloat_fop2, MATH_OP_REM ),\n};\n\n/* FloatEnv */\n\nstatic JSValue js_float_env_constructor(JSContext *ctx,\n                                        JSValueConst new_target,\n                                        int argc, JSValueConst *argv)\n{\n    JSValue obj;\n    JSFloatEnv *fe;\n    int64_t prec;\n    int flags, rndmode;\n\n    prec = ctx->fp_env.prec;\n    flags = ctx->fp_env.flags;\n    if (!JS_IsUndefined(argv[0])) {\n        if (JS_ToInt64Sat(ctx, &prec, argv[0]))\n            return JS_EXCEPTION;\n        if (prec < BF_PREC_MIN || prec > BF_PREC_MAX)\n            return JS_ThrowRangeError(ctx, \"invalid precision\");\n        flags = BF_RNDN; /* RNDN, max exponent size, no subnormal */\n        if (argc > 1 && !JS_IsUndefined(argv[1])) {\n            if (JS_ToInt32Sat(ctx, &rndmode, argv[1]))\n                return JS_EXCEPTION;\n            if (rndmode < BF_RNDN || rndmode > BF_RNDF)\n                return JS_ThrowRangeError(ctx, \"invalid rounding mode\");\n            flags = rndmode;\n        }\n    }\n\n    obj = JS_NewObjectClass(ctx, JS_CLASS_FLOAT_ENV);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    fe = js_malloc(ctx, sizeof(*fe));\n    if (!fe)\n        return JS_EXCEPTION;\n    fe->prec = prec;\n    fe->flags = flags;\n    fe->status = 0;\n    JS_SetOpaque(obj, fe);\n    return obj;\n}\n\nstatic void js_float_env_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSFloatEnv *fe = JS_GetOpaque(val, JS_CLASS_FLOAT_ENV);\n    js_free_rt(rt, fe);\n}\n\nstatic JSValue js_float_env_get_prec(JSContext *ctx, JSValueConst this_val)\n{\n    return JS_NewInt64(ctx, ctx->fp_env.prec);\n}\n\nstatic JSValue js_float_env_get_expBits(JSContext *ctx, JSValueConst this_val)\n{\n    return JS_NewInt32(ctx, bf_get_exp_bits(ctx->fp_env.flags));\n}\n\nstatic JSValue js_float_env_setPrec(JSContext *ctx,\n                                    JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSValueConst func;\n    int exp_bits, flags, saved_flags;\n    JSValue ret;\n    limb_t saved_prec;\n    int64_t prec;\n\n    func = argv[0];\n    if (JS_ToInt64Sat(ctx, &prec, argv[1]))\n        return JS_EXCEPTION;\n    if (prec < BF_PREC_MIN || prec > BF_PREC_MAX)\n        return JS_ThrowRangeError(ctx, \"invalid precision\");\n    exp_bits = BF_EXP_BITS_MAX;\n\n    if (argc > 2 && !JS_IsUndefined(argv[2])) {\n        if (JS_ToInt32Sat(ctx, &exp_bits, argv[2]))\n            return JS_EXCEPTION;\n        if (exp_bits < BF_EXP_BITS_MIN || exp_bits > BF_EXP_BITS_MAX)\n            return JS_ThrowRangeError(ctx, \"invalid number of exponent bits\");\n    }\n\n    flags = BF_RNDN | BF_FLAG_SUBNORMAL | bf_set_exp_bits(exp_bits);\n\n    saved_prec = ctx->fp_env.prec;\n    saved_flags = ctx->fp_env.flags;\n\n    ctx->fp_env.prec = prec;\n    ctx->fp_env.flags = flags;\n\n    ret = JS_Call(ctx, func, JS_UNDEFINED, 0, NULL);\n    /* always restore the floating point precision */\n    ctx->fp_env.prec = saved_prec;\n    ctx->fp_env.flags = saved_flags;\n    return ret;\n}\n\n#define FE_PREC      (-1)\n#define FE_EXP       (-2)\n#define FE_RNDMODE   (-3)\n#define FE_SUBNORMAL (-4)\n\nstatic JSValue js_float_env_proto_get_status(JSContext *ctx, JSValueConst this_val, int magic)\n{\n    JSFloatEnv *fe;\n    fe = JS_GetOpaque2(ctx, this_val, JS_CLASS_FLOAT_ENV);\n    if (!fe)\n        return JS_EXCEPTION;\n    switch(magic) {\n    case FE_PREC:\n        return JS_NewInt64(ctx, fe->prec);\n    case FE_EXP:\n        return JS_NewInt32(ctx, bf_get_exp_bits(fe->flags));\n    case FE_RNDMODE:\n        return JS_NewInt32(ctx, fe->flags & BF_RND_MASK);\n    case FE_SUBNORMAL:\n        return JS_NewBool(ctx, (fe->flags & BF_FLAG_SUBNORMAL) != 0);\n    default:\n        return JS_NewBool(ctx, (fe->status & magic) != 0);\n    }\n}\n\nstatic JSValue js_float_env_proto_set_status(JSContext *ctx, JSValueConst this_val, JSValueConst val, int magic)\n{\n    JSFloatEnv *fe;\n    int b;\n    int64_t prec;\n\n    fe = JS_GetOpaque2(ctx, this_val, JS_CLASS_FLOAT_ENV);\n    if (!fe)\n        return JS_EXCEPTION;\n    switch(magic) {\n    case FE_PREC:\n        if (JS_ToInt64Sat(ctx, &prec, val))\n            return JS_EXCEPTION;\n        if (prec < BF_PREC_MIN || prec > BF_PREC_MAX)\n            return JS_ThrowRangeError(ctx, \"invalid precision\");\n        fe->prec = prec;\n        break;\n    case FE_EXP:\n        if (JS_ToInt32Sat(ctx, &b, val))\n            return JS_EXCEPTION;\n        if (b < BF_EXP_BITS_MIN || b > BF_EXP_BITS_MAX)\n            return JS_ThrowRangeError(ctx, \"invalid number of exponent bits\");\n        fe->flags = (fe->flags & ~(BF_EXP_BITS_MASK << BF_EXP_BITS_SHIFT)) |\n            bf_set_exp_bits(b);\n        break;\n    case FE_RNDMODE:\n        b = bigfloat_get_rnd_mode(ctx, val);\n        if (b < 0)\n            return JS_EXCEPTION;\n        fe->flags = (fe->flags & ~BF_RND_MASK) | b;\n        break;\n    case FE_SUBNORMAL:\n        b = JS_ToBool(ctx, val);\n        fe->flags = (fe->flags & ~BF_FLAG_SUBNORMAL) | (b ? BF_FLAG_SUBNORMAL: 0);\n        break;\n    default:\n        b = JS_ToBool(ctx, val);\n        fe->status = (fe->status & ~magic) & ((-b) & magic);\n        break;\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_float_env_clearStatus(JSContext *ctx,\n                                        JSValueConst this_val,\n                                        int argc, JSValueConst *argv)\n{\n    JSFloatEnv *fe = JS_GetOpaque2(ctx, this_val, JS_CLASS_FLOAT_ENV);\n    if (!fe)\n        return JS_EXCEPTION;\n    fe->status = 0;\n    return JS_UNDEFINED;\n}\n\nstatic const JSCFunctionListEntry js_float_env_funcs[] = {\n    JS_CGETSET_DEF(\"prec\", js_float_env_get_prec, NULL ),\n    JS_CGETSET_DEF(\"expBits\", js_float_env_get_expBits, NULL ),\n    JS_CFUNC_DEF(\"setPrec\", 2, js_float_env_setPrec ),\n    JS_PROP_INT32_DEF(\"RNDN\", BF_RNDN, 0 ),\n    JS_PROP_INT32_DEF(\"RNDZ\", BF_RNDZ, 0 ),\n    JS_PROP_INT32_DEF(\"RNDU\", BF_RNDU, 0 ),\n    JS_PROP_INT32_DEF(\"RNDD\", BF_RNDD, 0 ),\n    JS_PROP_INT32_DEF(\"RNDNA\", BF_RNDNA, 0 ),\n    JS_PROP_INT32_DEF(\"RNDA\", BF_RNDA, 0 ),\n    JS_PROP_INT32_DEF(\"RNDF\", BF_RNDF, 0 ),\n    JS_PROP_INT32_DEF(\"precMin\", BF_PREC_MIN, 0 ),\n    JS_PROP_INT64_DEF(\"precMax\", BF_PREC_MAX, 0 ),\n    JS_PROP_INT32_DEF(\"expBitsMin\", BF_EXP_BITS_MIN, 0 ),\n    JS_PROP_INT32_DEF(\"expBitsMax\", BF_EXP_BITS_MAX, 0 ),\n};\n\nstatic const JSCFunctionListEntry js_float_env_proto_funcs[] = {\n    JS_CGETSET_MAGIC_DEF(\"prec\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, FE_PREC ),\n    JS_CGETSET_MAGIC_DEF(\"expBits\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, FE_EXP ),\n    JS_CGETSET_MAGIC_DEF(\"rndMode\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, FE_RNDMODE ),\n    JS_CGETSET_MAGIC_DEF(\"subnormal\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, FE_SUBNORMAL ),\n    JS_CGETSET_MAGIC_DEF(\"invalidOperation\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, BF_ST_INVALID_OP ),\n    JS_CGETSET_MAGIC_DEF(\"divideByZero\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, BF_ST_DIVIDE_ZERO ),\n    JS_CGETSET_MAGIC_DEF(\"overflow\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, BF_ST_OVERFLOW ),\n    JS_CGETSET_MAGIC_DEF(\"underflow\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, BF_ST_UNDERFLOW ),\n    JS_CGETSET_MAGIC_DEF(\"inexact\", js_float_env_proto_get_status,\n                         js_float_env_proto_set_status, BF_ST_INEXACT ),\n    JS_CFUNC_DEF(\"clearStatus\", 0, js_float_env_clearStatus ),\n};\n\nvoid JS_AddIntrinsicBigFloat(JSContext *ctx)\n{\n    JSRuntime *rt = ctx->rt;\n    JSValueConst obj1;\n    \n    rt->bigfloat_ops.to_string = js_bigfloat_to_string;\n    rt->bigfloat_ops.from_string = js_string_to_bigfloat;\n    rt->bigfloat_ops.unary_arith = js_unary_arith_bigfloat;\n    rt->bigfloat_ops.binary_arith = js_binary_arith_bigfloat;\n    rt->bigfloat_ops.compare = js_compare_bigfloat;\n    rt->bigfloat_ops.mul_pow10_to_float64 = js_mul_pow10_to_float64;\n    rt->bigfloat_ops.mul_pow10 = js_mul_pow10;\n    \n    ctx->class_proto[JS_CLASS_BIG_FLOAT] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_BIG_FLOAT],\n                               js_bigfloat_proto_funcs,\n                               countof(js_bigfloat_proto_funcs));\n    obj1 = JS_NewGlobalCConstructor(ctx, \"BigFloat\", js_bigfloat_constructor, 1,\n                                    ctx->class_proto[JS_CLASS_BIG_FLOAT]);\n    JS_SetPropertyFunctionList(ctx, obj1, js_bigfloat_funcs,\n                               countof(js_bigfloat_funcs));\n\n    ctx->class_proto[JS_CLASS_FLOAT_ENV] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_FLOAT_ENV],\n                               js_float_env_proto_funcs,\n                               countof(js_float_env_proto_funcs));\n    obj1 = JS_NewGlobalCConstructorOnly(ctx, \"BigFloatEnv\",\n                                        js_float_env_constructor, 1,\n                                        ctx->class_proto[JS_CLASS_FLOAT_ENV]);\n    JS_SetPropertyFunctionList(ctx, obj1, js_float_env_funcs,\n                               countof(js_float_env_funcs));\n}\n\n/* BigDecimal */\n\nstatic JSValue JS_ToBigDecimalFree(JSContext *ctx, JSValue val,\n                                   BOOL allow_null_or_undefined)\n{\n redo:\n    switch(JS_VALUE_GET_NORM_TAG(val)) {\n    case JS_TAG_BIG_DECIMAL:\n        break;\n    case JS_TAG_NULL:\n        if (!allow_null_or_undefined)\n            goto fail;\n        /* fall thru */\n    case JS_TAG_BOOL:\n    case JS_TAG_INT:\n        {\n            bfdec_t *r;\n            int32_t v = JS_VALUE_GET_INT(val);\n\n            val = JS_NewBigDecimal(ctx);\n            if (JS_IsException(val))\n                break;\n            r = JS_GetBigDecimal(val);\n            if (bfdec_set_si(r, v)) {\n                JS_FreeValue(ctx, val);\n                val = JS_EXCEPTION;\n                break;\n            }\n        }\n        break;\n    case JS_TAG_FLOAT64:\n    case JS_TAG_BIG_INT:\n    case JS_TAG_BIG_FLOAT:\n        val = JS_ToStringFree(ctx, val);\n        if (JS_IsException(val))\n            break;\n        goto redo;\n    case JS_TAG_STRING:\n        {\n            const char *str, *p;\n            size_t len;\n            int err;\n\n            str = JS_ToCStringLen(ctx, &len, val);\n            JS_FreeValue(ctx, val);\n            if (!str)\n                return JS_EXCEPTION;\n            p = str;\n            p += skip_spaces(p);\n            if ((p - str) == len) {\n                bfdec_t *r;\n                val = JS_NewBigDecimal(ctx);\n                if (JS_IsException(val))\n                    break;\n                r = JS_GetBigDecimal(val);\n                bfdec_set_zero(r, 0);\n                err = 0;\n            } else {\n                val = js_atof(ctx, p, &p, 0, ATOD_TYPE_BIG_DECIMAL);\n                if (JS_IsException(val)) {\n                    JS_FreeCString(ctx, str);\n                    return JS_EXCEPTION;\n                }\n                p += skip_spaces(p);\n                err = ((p - str) != len);\n            }\n            JS_FreeCString(ctx, str);\n            if (err) {\n                JS_FreeValue(ctx, val);\n                return JS_ThrowSyntaxError(ctx, \"invalid bigdecimal literal\");\n            }\n        }\n        break;\n    case JS_TAG_OBJECT:\n        val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER);\n        if (JS_IsException(val))\n            break;\n        goto redo;\n    case JS_TAG_UNDEFINED:\n        {\n            bfdec_t *r;\n            if (!allow_null_or_undefined)\n                goto fail;\n            val = JS_NewBigDecimal(ctx);\n            if (JS_IsException(val))\n                break;\n            r = JS_GetBigDecimal(val);\n            bfdec_set_nan(r);\n        }\n        break;\n    default:\n    fail:\n        JS_FreeValue(ctx, val);\n        return JS_ThrowTypeError(ctx, \"cannot convert to bigdecimal\");\n    }\n    return val;\n}\n\nstatic JSValue js_bigdecimal_constructor(JSContext *ctx,\n                                         JSValueConst new_target,\n                                         int argc, JSValueConst *argv)\n{\n    JSValue val;\n    if (!JS_IsUndefined(new_target))\n        return JS_ThrowTypeError(ctx, \"not a constructor\");\n    if (argc == 0) {\n        bfdec_t *r;\n        val = JS_NewBigDecimal(ctx);\n        if (JS_IsException(val))\n            return val;\n        r = JS_GetBigDecimal(val);\n        bfdec_set_zero(r, 0);\n    } else {\n        val = JS_ToBigDecimalFree(ctx, JS_DupValue(ctx, argv[0]), FALSE);\n    }\n    return val;\n}\n\nstatic JSValue js_thisBigDecimalValue(JSContext *ctx, JSValueConst this_val)\n{\n    if (JS_IsBigDecimal(this_val))\n        return JS_DupValue(ctx, this_val);\n\n    if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {\n        JSObject *p = JS_VALUE_GET_OBJ(this_val);\n        if (p->class_id == JS_CLASS_BIG_DECIMAL) {\n            if (JS_IsBigDecimal(p->u.object_data))\n                return JS_DupValue(ctx, p->u.object_data);\n        }\n    }\n    return JS_ThrowTypeError(ctx, \"not a bigdecimal\");\n}\n\nstatic JSValue js_bigdecimal_toString(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv)\n{\n    JSValue val;\n\n    val = js_thisBigDecimalValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    return JS_ToStringFree(ctx, val);\n}\n\nstatic JSValue js_bigdecimal_valueOf(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    return js_thisBigDecimalValue(ctx, this_val);\n}\n\nstatic int js_bigdecimal_get_rnd_mode(JSContext *ctx, JSValueConst obj)\n{\n    const char *str;\n    size_t size;\n    int rnd_mode;\n    \n    str = JS_ToCStringLen(ctx, &size, obj);\n    if (!str)\n        return -1;\n    if (strlen(str) != size)\n        goto invalid_rounding_mode;\n    if (!strcmp(str, \"floor\")) {\n        rnd_mode = BF_RNDD;\n    } else if (!strcmp(str, \"ceiling\")) {\n        rnd_mode = BF_RNDU;\n    } else if (!strcmp(str, \"down\")) {\n        rnd_mode = BF_RNDZ;\n    } else if (!strcmp(str, \"up\")) {\n        rnd_mode = BF_RNDA;\n    } else if (!strcmp(str, \"half-even\")) {\n        rnd_mode = BF_RNDN;\n    } else if (!strcmp(str, \"half-up\")) {\n        rnd_mode = BF_RNDNA;\n    } else {\n    invalid_rounding_mode:\n        JS_FreeCString(ctx, str);\n        JS_ThrowTypeError(ctx, \"invalid rounding mode\");\n        return -1;\n    }\n    JS_FreeCString(ctx, str);\n    return rnd_mode;\n}\n\ntypedef struct {\n    int64_t prec;\n    bf_flags_t flags;\n} BigDecimalEnv;\n\nstatic int js_bigdecimal_get_env(JSContext *ctx, BigDecimalEnv *fe,\n                                 JSValueConst obj)\n{\n    JSValue prop;\n    int64_t val;\n    BOOL has_prec;\n    int rnd_mode;\n    \n    if (!JS_IsObject(obj)) {\n        JS_ThrowTypeErrorNotAnObject(ctx);\n        return -1;\n    }\n    prop = JS_GetProperty(ctx, obj, JS_ATOM_roundingMode);\n    if (JS_IsException(prop))\n        return -1;\n    rnd_mode = js_bigdecimal_get_rnd_mode(ctx, prop);\n    JS_FreeValue(ctx, prop);\n    if (rnd_mode < 0)\n        return -1;\n    fe->flags = rnd_mode;\n    \n    prop = JS_GetProperty(ctx, obj, JS_ATOM_maximumSignificantDigits);\n    if (JS_IsException(prop))\n        return -1;\n    has_prec = FALSE;\n    if (!JS_IsUndefined(prop)) {\n        if (JS_ToInt64SatFree(ctx, &val, prop))\n            return -1;\n        if (val < 1 || val > BF_PREC_MAX)\n            goto invalid_precision;\n        fe->prec = val;\n        has_prec = TRUE;\n    }\n\n    prop = JS_GetProperty(ctx, obj, JS_ATOM_maximumFractionDigits);\n    if (JS_IsException(prop))\n        return -1;\n    if (!JS_IsUndefined(prop)) {\n        if (has_prec) {\n            JS_FreeValue(ctx, prop);\n            JS_ThrowTypeError(ctx, \"cannot provide both maximumSignificantDigits and maximumFractionDigits\");\n            return -1;\n        }\n        if (JS_ToInt64SatFree(ctx, &val, prop))\n            return -1;\n        if (val < 0 || val > BF_PREC_MAX) {\n        invalid_precision:\n            JS_ThrowTypeError(ctx, \"invalid precision\");\n            return -1;\n        }\n        fe->prec = val;\n        fe->flags |= BF_FLAG_RADPNT_PREC;\n        has_prec = TRUE;\n    }\n    if (!has_prec) {\n        JS_ThrowTypeError(ctx, \"precision must be present\");\n        return -1;\n    }\n    return 0;\n}\n\n\nstatic JSValue js_bigdecimal_fop(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv, int magic)\n{\n    bfdec_t *a, *b, r_s, *r = &r_s;\n    JSValue op1, op2, res;\n    BigDecimalEnv fe_s, *fe = &fe_s;\n    int op_count, ret;\n\n    if (magic == MATH_OP_SQRT ||\n        magic == MATH_OP_ROUND)\n        op_count = 1;\n    else\n        op_count = 2;\n    \n    op1 = JS_ToNumeric(ctx, argv[0]);\n    if (JS_IsException(op1))\n        return op1;\n    a = JS_ToBigDecimal(ctx, op1);\n    if (!a) {\n        JS_FreeValue(ctx, op1);\n        return JS_EXCEPTION;\n    }\n    if (op_count >= 2) {\n        op2 = JS_ToNumeric(ctx, argv[1]);\n        if (JS_IsException(op2)) {\n            JS_FreeValue(ctx, op1);\n            return op2;\n        }\n        b = JS_ToBigDecimal(ctx, op2);\n        if (!b)\n            goto fail;\n    } else {\n        op2 = JS_UNDEFINED;\n        b = NULL;\n    }\n    fe->flags = BF_RNDZ;\n    fe->prec = BF_PREC_INF;\n    if (op_count < argc) {\n        if (js_bigdecimal_get_env(ctx, fe, argv[op_count]))\n            goto fail;\n    }\n\n    res = JS_NewBigDecimal(ctx);\n    if (JS_IsException(res)) {\n    fail:\n        JS_FreeValue(ctx, op1);\n        JS_FreeValue(ctx, op2);\n        return JS_EXCEPTION;\n    }\n    r = JS_GetBigDecimal(res);\n    switch (magic) {\n    case MATH_OP_ADD:\n        ret = bfdec_add(r, a, b, fe->prec, fe->flags);\n        break;\n    case MATH_OP_SUB:\n        ret = bfdec_sub(r, a, b, fe->prec, fe->flags);\n        break;\n    case MATH_OP_MUL:\n        ret = bfdec_mul(r, a, b, fe->prec, fe->flags);\n        break;\n    case MATH_OP_DIV:\n        ret = bfdec_div(r, a, b, fe->prec, fe->flags);\n        break;\n    case MATH_OP_FMOD:\n        ret = bfdec_rem(r, a, b, fe->prec, fe->flags, BF_RNDZ);\n        break;\n    case MATH_OP_SQRT:\n        ret = bfdec_sqrt(r, a, fe->prec, fe->flags);\n        break;\n    case MATH_OP_ROUND:\n        ret = bfdec_set(r, a);\n        if (!(ret & BF_ST_MEM_ERROR))\n            ret = bfdec_round(r, fe->prec, fe->flags);\n        break;\n    default:\n        abort();\n    }\n    JS_FreeValue(ctx, op1);\n    JS_FreeValue(ctx, op2);\n    ret &= BF_ST_MEM_ERROR | BF_ST_DIVIDE_ZERO | BF_ST_INVALID_OP |\n        BF_ST_OVERFLOW;\n    if (ret != 0) {\n        JS_FreeValue(ctx, res);\n        return throw_bf_exception(ctx, ret);\n    } else {\n        return res;\n    }\n}\n\nstatic JSValue js_bigdecimal_toFixed(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    int64_t f;\n    int rnd_mode;\n\n    val = js_thisBigDecimalValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_ToInt64Sat(ctx, &f, argv[0]))\n        goto fail;\n    if (f < 0 || f > BF_PREC_MAX) {\n        JS_ThrowRangeError(ctx, \"invalid number of digits\");\n        goto fail;\n    }\n    rnd_mode = BF_RNDNA;\n    if (argc > 1) {\n        rnd_mode = js_bigdecimal_get_rnd_mode(ctx, argv[1]);\n        if (rnd_mode < 0)\n            goto fail;\n    }\n    ret = js_bigdecimal_to_string1(ctx, val, f, rnd_mode | BF_FTOA_FORMAT_FRAC);\n    JS_FreeValue(ctx, val);\n    return ret;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_bigdecimal_toExponential(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    int64_t f;\n    int rnd_mode;\n\n    val = js_thisBigDecimalValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_ToInt64Sat(ctx, &f, argv[0]))\n        goto fail;\n    if (JS_IsUndefined(argv[0])) {\n        ret = js_bigdecimal_to_string1(ctx, val, 0,\n                  BF_RNDN | BF_FTOA_FORMAT_FREE_MIN | BF_FTOA_FORCE_EXP);\n    } else {\n        if (f < 0 || f > BF_PREC_MAX) {\n            JS_ThrowRangeError(ctx, \"invalid number of digits\");\n            goto fail;\n        }\n        rnd_mode = BF_RNDNA;\n        if (argc > 1) {\n            rnd_mode = js_bigdecimal_get_rnd_mode(ctx, argv[1]);\n            if (rnd_mode < 0)\n                goto fail;\n        }\n        ret = js_bigdecimal_to_string1(ctx, val, f + 1,\n                      rnd_mode | BF_FTOA_FORMAT_FIXED | BF_FTOA_FORCE_EXP);\n    }\n    JS_FreeValue(ctx, val);\n    return ret;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_bigdecimal_toPrecision(JSContext *ctx, JSValueConst this_val,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue val, ret;\n    int64_t p;\n    int rnd_mode;\n\n    val = js_thisBigDecimalValue(ctx, this_val);\n    if (JS_IsException(val))\n        return val;\n    if (JS_IsUndefined(argv[0])) {\n        return JS_ToStringFree(ctx, val);\n    }\n    if (JS_ToInt64Sat(ctx, &p, argv[0]))\n        goto fail;\n    if (p < 1 || p > BF_PREC_MAX) {\n        JS_ThrowRangeError(ctx, \"invalid number of digits\");\n        goto fail;\n    }\n    rnd_mode = BF_RNDNA;\n    if (argc > 1) {\n        rnd_mode = js_bigdecimal_get_rnd_mode(ctx, argv[1]);\n        if (rnd_mode < 0)\n            goto fail;\n    }\n    ret = js_bigdecimal_to_string1(ctx, val, p,\n                                   rnd_mode | BF_FTOA_FORMAT_FIXED);\n    JS_FreeValue(ctx, val);\n    return ret;\n fail:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\nstatic const JSCFunctionListEntry js_bigdecimal_proto_funcs[] = {\n    JS_CFUNC_DEF(\"toString\", 0, js_bigdecimal_toString ),\n    JS_CFUNC_DEF(\"valueOf\", 0, js_bigdecimal_valueOf ),\n    JS_CFUNC_DEF(\"toPrecision\", 1, js_bigdecimal_toPrecision ),\n    JS_CFUNC_DEF(\"toFixed\", 1, js_bigdecimal_toFixed ),\n    JS_CFUNC_DEF(\"toExponential\", 1, js_bigdecimal_toExponential ),\n};\n\nstatic const JSCFunctionListEntry js_bigdecimal_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"add\", 2, js_bigdecimal_fop, MATH_OP_ADD ),\n    JS_CFUNC_MAGIC_DEF(\"sub\", 2, js_bigdecimal_fop, MATH_OP_SUB ),\n    JS_CFUNC_MAGIC_DEF(\"mul\", 2, js_bigdecimal_fop, MATH_OP_MUL ),\n    JS_CFUNC_MAGIC_DEF(\"div\", 2, js_bigdecimal_fop, MATH_OP_DIV ),\n    JS_CFUNC_MAGIC_DEF(\"mod\", 2, js_bigdecimal_fop, MATH_OP_FMOD ),\n    JS_CFUNC_MAGIC_DEF(\"round\", 1, js_bigdecimal_fop, MATH_OP_ROUND ),\n    JS_CFUNC_MAGIC_DEF(\"sqrt\", 1, js_bigdecimal_fop, MATH_OP_SQRT ),\n};\n\nvoid JS_AddIntrinsicBigDecimal(JSContext *ctx)\n{\n    JSRuntime *rt = ctx->rt;\n    JSValueConst obj1;\n\n    rt->bigdecimal_ops.to_string = js_bigdecimal_to_string;\n    rt->bigdecimal_ops.from_string = js_string_to_bigdecimal;\n    rt->bigdecimal_ops.unary_arith = js_unary_arith_bigdecimal;\n    rt->bigdecimal_ops.binary_arith = js_binary_arith_bigdecimal;\n    rt->bigdecimal_ops.compare = js_compare_bigdecimal;\n\n    ctx->class_proto[JS_CLASS_BIG_DECIMAL] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_BIG_DECIMAL],\n                               js_bigdecimal_proto_funcs,\n                               countof(js_bigdecimal_proto_funcs));\n    obj1 = JS_NewGlobalCConstructor(ctx, \"BigDecimal\",\n                                    js_bigdecimal_constructor, 1,\n                                    ctx->class_proto[JS_CLASS_BIG_DECIMAL]);\n    JS_SetPropertyFunctionList(ctx, obj1, js_bigdecimal_funcs,\n                               countof(js_bigdecimal_funcs));\n}\n\nvoid JS_EnableBignumExt(JSContext *ctx, BOOL enable)\n{\n    ctx->bignum_ext = enable;\n}\n\n#endif /* CONFIG_BIGNUM */\n\nstatic const char * const native_error_name[JS_NATIVE_ERROR_COUNT] = {\n    \"EvalError\", \"RangeError\", \"ReferenceError\",\n    \"SyntaxError\", \"TypeError\", \"URIError\",\n    \"InternalError\", \"AggregateError\",\n};\n\n/* Minimum amount of objects to be able to compile code and display\n   error messages. No JSAtom should be allocated by this function. */\nstatic void JS_AddIntrinsicBasicObjects(JSContext *ctx)\n{\n    JSValue proto;\n    int i;\n\n    ctx->class_proto[JS_CLASS_OBJECT] = JS_NewObjectProto(ctx, JS_NULL);\n    ctx->function_proto = JS_NewCFunction3(ctx, js_function_proto, \"\", 0,\n                                           JS_CFUNC_generic, 0,\n                                           ctx->class_proto[JS_CLASS_OBJECT]);\n    ctx->class_proto[JS_CLASS_BYTECODE_FUNCTION] = JS_DupValue(ctx, ctx->function_proto);\n    ctx->class_proto[JS_CLASS_ERROR] = JS_NewObject(ctx);\n#if 0\n    /* these are auto-initialized from js_error_proto_funcs,\n       but delaying might be a problem */\n    JS_DefinePropertyValue(ctx, ctx->class_proto[JS_CLASS_ERROR], JS_ATOM_name,\n                           JS_AtomToString(ctx, JS_ATOM_Error),\n                           JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    JS_DefinePropertyValue(ctx, ctx->class_proto[JS_CLASS_ERROR], JS_ATOM_message,\n                           JS_AtomToString(ctx, JS_ATOM_empty_string),\n                           JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n#endif\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ERROR],\n                               js_error_proto_funcs,\n                               countof(js_error_proto_funcs));\n\n    for(i = 0; i < JS_NATIVE_ERROR_COUNT; i++) {\n        proto = JS_NewObjectProto(ctx, ctx->class_proto[JS_CLASS_ERROR]);\n        JS_DefinePropertyValue(ctx, proto, JS_ATOM_name,\n                               JS_NewAtomString(ctx, native_error_name[i]),\n                               JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n        JS_DefinePropertyValue(ctx, proto, JS_ATOM_message,\n                               JS_AtomToString(ctx, JS_ATOM_empty_string),\n                               JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n        ctx->native_error_proto[i] = proto;\n    }\n\n    /* the array prototype is an array */\n    ctx->class_proto[JS_CLASS_ARRAY] =\n        JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],\n                               JS_CLASS_ARRAY);\n\n    ctx->array_shape = js_new_shape2(ctx, get_proto_obj(ctx->class_proto[JS_CLASS_ARRAY]),\n                                     JS_PROP_INITIAL_HASH_SIZE, 1);\n    add_shape_property(ctx, &ctx->array_shape, NULL,\n                       JS_ATOM_length, JS_PROP_WRITABLE | JS_PROP_LENGTH);\n\n    /* XXX: could test it on first context creation to ensure that no\n       new atoms are created in JS_AddIntrinsicBasicObjects(). It is\n       necessary to avoid useless renumbering of atoms after\n       JS_EvalBinary() if it is done just after\n       JS_AddIntrinsicBasicObjects(). */\n    //    assert(ctx->rt->atom_count == JS_ATOM_END);\n}\n\nvoid JS_AddIntrinsicBaseObjects(JSContext *ctx)\n{\n    int i;\n    JSValueConst obj, number_obj;\n    JSValue obj1;\n\n    ctx->throw_type_error = JS_NewCFunction(ctx, js_throw_type_error, NULL, 0);\n\n    /* add caller and arguments properties to throw a TypeError */\n    obj1 = JS_NewCFunction(ctx, js_function_proto_caller, NULL, 0);\n    JS_DefineProperty(ctx, ctx->function_proto, JS_ATOM_caller, JS_UNDEFINED,\n                      obj1, ctx->throw_type_error,\n                      JS_PROP_HAS_GET | JS_PROP_HAS_SET |\n                      JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE);\n    JS_DefineProperty(ctx, ctx->function_proto, JS_ATOM_arguments, JS_UNDEFINED,\n                      obj1, ctx->throw_type_error,\n                      JS_PROP_HAS_GET | JS_PROP_HAS_SET |\n                      JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE);\n    JS_FreeValue(ctx, obj1);\n    JS_FreeValue(ctx, js_object_seal(ctx, JS_UNDEFINED, 1, (JSValueConst *)&ctx->throw_type_error, 1));\n\n    ctx->global_obj = JS_NewObject(ctx);\n    ctx->global_var_obj = JS_NewObjectProto(ctx, JS_NULL);\n\n    /* Object */\n    obj = JS_NewGlobalCConstructor(ctx, \"Object\", js_object_constructor, 1,\n                                   ctx->class_proto[JS_CLASS_OBJECT]);\n    JS_SetPropertyFunctionList(ctx, obj, js_object_funcs, countof(js_object_funcs));\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_OBJECT],\n                               js_object_proto_funcs, countof(js_object_proto_funcs));\n\n    /* Function */\n    JS_SetPropertyFunctionList(ctx, ctx->function_proto, js_function_proto_funcs, countof(js_function_proto_funcs));\n    ctx->function_ctor = JS_NewCFunctionMagic(ctx, js_function_constructor,\n                                              \"Function\", 1, JS_CFUNC_constructor_or_func_magic,\n                                              JS_FUNC_NORMAL);\n    JS_NewGlobalCConstructor2(ctx, JS_DupValue(ctx, ctx->function_ctor), \"Function\",\n                              ctx->function_proto);\n\n    /* Error */\n    obj1 = JS_NewCFunctionMagic(ctx, js_error_constructor,\n                                \"Error\", 1, JS_CFUNC_constructor_or_func_magic, -1);\n    JS_NewGlobalCConstructor2(ctx, obj1,\n                              \"Error\", ctx->class_proto[JS_CLASS_ERROR]);\n\n    for(i = 0; i < JS_NATIVE_ERROR_COUNT; i++) {\n        JSValue func_obj;\n        int n_args;\n        n_args = 1 + (i == JS_AGGREGATE_ERROR);\n        func_obj = JS_NewCFunction3(ctx, (JSCFunction *)js_error_constructor,\n                                    native_error_name[i], n_args,\n                                    JS_CFUNC_constructor_or_func_magic, i, obj1);\n        JS_NewGlobalCConstructor2(ctx, func_obj, native_error_name[i],\n                                  ctx->native_error_proto[i]);\n    }\n\n    /* Iterator prototype */\n    ctx->iterator_proto = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->iterator_proto,\n                               js_iterator_proto_funcs,\n                               countof(js_iterator_proto_funcs));\n\n    /* Array */\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ARRAY],\n                               js_array_proto_funcs,\n                               countof(js_array_proto_funcs));\n\n    obj = JS_NewGlobalCConstructor(ctx, \"Array\", js_array_constructor, 1,\n                                   ctx->class_proto[JS_CLASS_ARRAY]);\n    ctx->array_ctor = JS_DupValue(ctx, obj);\n    JS_SetPropertyFunctionList(ctx, obj, js_array_funcs,\n                               countof(js_array_funcs));\n\n    /* XXX: create auto_initializer */\n    {\n        /* initialize Array.prototype[Symbol.unscopables] */\n        char const unscopables[] = \"copyWithin\" \"\\0\" \"entries\" \"\\0\" \"fill\" \"\\0\" \"find\" \"\\0\"\n            \"findIndex\" \"\\0\" \"flat\" \"\\0\" \"flatMap\" \"\\0\" \"includes\" \"\\0\" \"keys\" \"\\0\" \"values\" \"\\0\";\n        const char *p = unscopables;\n        obj1 = JS_NewObjectProto(ctx, JS_NULL);\n        for(p = unscopables; *p; p += strlen(p) + 1) {\n            JS_DefinePropertyValueStr(ctx, obj1, p, JS_TRUE, JS_PROP_C_W_E);\n        }\n        JS_DefinePropertyValue(ctx, ctx->class_proto[JS_CLASS_ARRAY],\n                               JS_ATOM_Symbol_unscopables, obj1,\n                               JS_PROP_CONFIGURABLE);\n    }\n\n    /* needed to initialize arguments[Symbol.iterator] */\n    ctx->array_proto_values =\n        JS_GetProperty(ctx, ctx->class_proto[JS_CLASS_ARRAY], JS_ATOM_values);\n\n    ctx->class_proto[JS_CLASS_ARRAY_ITERATOR] = JS_NewObjectProto(ctx, ctx->iterator_proto);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ARRAY_ITERATOR],\n                               js_array_iterator_proto_funcs,\n                               countof(js_array_iterator_proto_funcs));\n\n    /* parseFloat and parseInteger must be defined before Number\n       because of the Number.parseFloat and Number.parseInteger\n       aliases */\n    JS_SetPropertyFunctionList(ctx, ctx->global_obj, js_global_funcs,\n                               countof(js_global_funcs));\n\n    /* Number */\n    ctx->class_proto[JS_CLASS_NUMBER] = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],\n                                                               JS_CLASS_NUMBER);\n    JS_SetObjectData(ctx, ctx->class_proto[JS_CLASS_NUMBER], JS_NewInt32(ctx, 0));\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_NUMBER],\n                               js_number_proto_funcs,\n                               countof(js_number_proto_funcs));\n    number_obj = JS_NewGlobalCConstructor(ctx, \"Number\", js_number_constructor, 1,\n                                          ctx->class_proto[JS_CLASS_NUMBER]);\n    JS_SetPropertyFunctionList(ctx, number_obj, js_number_funcs, countof(js_number_funcs));\n\n    /* Boolean */\n    ctx->class_proto[JS_CLASS_BOOLEAN] = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],\n                                                                JS_CLASS_BOOLEAN);\n    JS_SetObjectData(ctx, ctx->class_proto[JS_CLASS_BOOLEAN], JS_NewBool(ctx, FALSE));\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_BOOLEAN], js_boolean_proto_funcs,\n                               countof(js_boolean_proto_funcs));\n    JS_NewGlobalCConstructor(ctx, \"Boolean\", js_boolean_constructor, 1,\n                             ctx->class_proto[JS_CLASS_BOOLEAN]);\n\n    /* String */\n    ctx->class_proto[JS_CLASS_STRING] = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT],\n                                                               JS_CLASS_STRING);\n    JS_SetObjectData(ctx, ctx->class_proto[JS_CLASS_STRING], JS_AtomToString(ctx, JS_ATOM_empty_string));\n    obj = JS_NewGlobalCConstructor(ctx, \"String\", js_string_constructor, 1,\n                                   ctx->class_proto[JS_CLASS_STRING]);\n    JS_SetPropertyFunctionList(ctx, obj, js_string_funcs,\n                               countof(js_string_funcs));\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_STRING], js_string_proto_funcs,\n                               countof(js_string_proto_funcs));\n\n    ctx->class_proto[JS_CLASS_STRING_ITERATOR] = JS_NewObjectProto(ctx, ctx->iterator_proto);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_STRING_ITERATOR],\n                               js_string_iterator_proto_funcs,\n                               countof(js_string_iterator_proto_funcs));\n\n    /* Math: create as autoinit object */\n    js_random_init(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->global_obj, js_math_obj, countof(js_math_obj));\n\n    /* ES6 Reflect: create as autoinit object */\n    JS_SetPropertyFunctionList(ctx, ctx->global_obj, js_reflect_obj, countof(js_reflect_obj));\n\n    /* ES6 Symbol */\n    ctx->class_proto[JS_CLASS_SYMBOL] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_SYMBOL], js_symbol_proto_funcs,\n                               countof(js_symbol_proto_funcs));\n    obj = JS_NewGlobalCConstructor(ctx, \"Symbol\", js_symbol_constructor, 0,\n                                   ctx->class_proto[JS_CLASS_SYMBOL]);\n    JS_SetPropertyFunctionList(ctx, obj, js_symbol_funcs,\n                               countof(js_symbol_funcs));\n    for(i = JS_ATOM_Symbol_toPrimitive; i < JS_ATOM_END; i++) {\n        char buf[ATOM_GET_STR_BUF_SIZE];\n        const char *str, *p;\n        str = JS_AtomGetStr(ctx, buf, sizeof(buf), i);\n        /* skip \"Symbol.\" */\n        p = strchr(str, '.');\n        if (p)\n            str = p + 1;\n        JS_DefinePropertyValueStr(ctx, obj, str, JS_AtomToValue(ctx, i), 0);\n    }\n\n    /* ES6 Generator */\n    ctx->class_proto[JS_CLASS_GENERATOR] = JS_NewObjectProto(ctx, ctx->iterator_proto);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_GENERATOR],\n                               js_generator_proto_funcs,\n                               countof(js_generator_proto_funcs));\n\n    ctx->class_proto[JS_CLASS_GENERATOR_FUNCTION] = JS_NewObjectProto(ctx, ctx->function_proto);\n    obj1 = JS_NewCFunctionMagic(ctx, js_function_constructor,\n                                \"GeneratorFunction\", 1,\n                                JS_CFUNC_constructor_or_func_magic, JS_FUNC_GENERATOR);\n    JS_SetPropertyFunctionList(ctx,\n                               ctx->class_proto[JS_CLASS_GENERATOR_FUNCTION],\n                               js_generator_function_proto_funcs,\n                               countof(js_generator_function_proto_funcs));\n    JS_SetConstructor2(ctx, ctx->class_proto[JS_CLASS_GENERATOR_FUNCTION],\n                       ctx->class_proto[JS_CLASS_GENERATOR],\n                       JS_PROP_CONFIGURABLE, JS_PROP_CONFIGURABLE);\n    JS_SetConstructor2(ctx, obj1, ctx->class_proto[JS_CLASS_GENERATOR_FUNCTION],\n                       0, JS_PROP_CONFIGURABLE);\n    JS_FreeValue(ctx, obj1);\n\n    /* global properties */\n    ctx->eval_obj = JS_NewCFunction(ctx, js_global_eval, \"eval\", 1);\n    JS_DefinePropertyValue(ctx, ctx->global_obj, JS_ATOM_eval,\n                           JS_DupValue(ctx, ctx->eval_obj),\n                           JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n\n    JS_DefinePropertyValue(ctx, ctx->global_obj, JS_ATOM_globalThis,\n                           JS_DupValue(ctx, ctx->global_obj),\n                           JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE);\n}\n\n/* Typed Arrays */\n\nstatic uint8_t const typed_array_size_log2[JS_TYPED_ARRAY_COUNT] = {\n    0, 0, 0, 1, 1, 2, 2,\n#ifdef CONFIG_BIGNUM\n    3, 3, /* BigInt64Array, BigUint64Array */\n#endif\n    2, 3\n};\n\nstatic JSValue js_array_buffer_constructor3(JSContext *ctx,\n                                            JSValueConst new_target,\n                                            uint64_t len, JSClassID class_id,\n                                            uint8_t *buf,\n                                            JSFreeArrayBufferDataFunc *free_func,\n                                            void *opaque, BOOL alloc_flag)\n{\n    JSRuntime *rt = ctx->rt;\n    JSValue obj;\n    JSArrayBuffer *abuf = NULL;\n\n    obj = js_create_from_ctor(ctx, new_target, class_id);\n    if (JS_IsException(obj))\n        return obj;\n    /* XXX: we are currently limited to 2 GB */\n    if (len > INT32_MAX) {\n        JS_ThrowRangeError(ctx, \"invalid array buffer length\");\n        goto fail;\n    }\n    abuf = js_malloc(ctx, sizeof(*abuf));\n    if (!abuf)\n        goto fail;\n    abuf->byte_length = len;\n    if (alloc_flag) {\n        if (class_id == JS_CLASS_SHARED_ARRAY_BUFFER &&\n            rt->sab_funcs.sab_alloc) {\n            abuf->data = rt->sab_funcs.sab_alloc(rt->sab_funcs.sab_opaque,\n                                                 max_int(len, 1));\n            if (!abuf->data)\n                goto fail;\n            memset(abuf->data, 0, len);\n        } else {\n            /* the allocation must be done after the object creation */\n            abuf->data = js_mallocz(ctx, max_int(len, 1));\n            if (!abuf->data)\n                goto fail;\n        }\n    } else {\n        if (class_id == JS_CLASS_SHARED_ARRAY_BUFFER &&\n            rt->sab_funcs.sab_dup) {\n            rt->sab_funcs.sab_dup(rt->sab_funcs.sab_opaque, buf);\n        }\n        abuf->data = buf;\n    }\n    init_list_head(&abuf->array_list);\n    abuf->detached = FALSE;\n    abuf->shared = (class_id == JS_CLASS_SHARED_ARRAY_BUFFER);\n    abuf->opaque = opaque;\n    abuf->free_func = free_func;\n    if (alloc_flag && buf)\n        memcpy(abuf->data, buf, len);\n    JS_SetOpaque(obj, abuf);\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    js_free(ctx, abuf);\n    return JS_EXCEPTION;\n}\n\nstatic void js_array_buffer_free(JSRuntime *rt, void *opaque, void *ptr)\n{\n    js_free_rt(rt, ptr);\n}\n\nstatic JSValue js_array_buffer_constructor2(JSContext *ctx,\n                                            JSValueConst new_target,\n                                            uint64_t len, JSClassID class_id)\n{\n    return js_array_buffer_constructor3(ctx, new_target, len, class_id,\n                                        NULL, js_array_buffer_free, NULL,\n                                        TRUE);\n}\n\nstatic JSValue js_array_buffer_constructor1(JSContext *ctx,\n                                            JSValueConst new_target,\n                                            uint64_t len)\n{\n    return js_array_buffer_constructor2(ctx, new_target, len,\n                                        JS_CLASS_ARRAY_BUFFER);\n}\n\nJSValue JS_NewArrayBuffer(JSContext *ctx, uint8_t *buf, size_t len,\n                          JSFreeArrayBufferDataFunc *free_func, void *opaque,\n                          BOOL is_shared)\n{\n    return js_array_buffer_constructor3(ctx, JS_UNDEFINED, len,\n                                        is_shared ? JS_CLASS_SHARED_ARRAY_BUFFER : JS_CLASS_ARRAY_BUFFER,\n                                        buf, free_func, opaque, FALSE);\n}\n\n/* create a new ArrayBuffer of length 'len' and copy 'buf' to it */\nJSValue JS_NewArrayBufferCopy(JSContext *ctx, const uint8_t *buf, size_t len)\n{\n    return js_array_buffer_constructor3(ctx, JS_UNDEFINED, len,\n                                        JS_CLASS_ARRAY_BUFFER,\n                                        (uint8_t *)buf,\n                                        js_array_buffer_free, NULL,\n                                        TRUE);\n}\n\nstatic JSValue js_array_buffer_constructor(JSContext *ctx,\n                                           JSValueConst new_target,\n                                           int argc, JSValueConst *argv)\n{\n    uint64_t len;\n    if (JS_ToIndex(ctx, &len, argv[0]))\n        return JS_EXCEPTION;\n    return js_array_buffer_constructor1(ctx, new_target, len);\n}\n\nstatic JSValue js_shared_array_buffer_constructor(JSContext *ctx,\n                                                  JSValueConst new_target,\n                                                  int argc, JSValueConst *argv)\n{\n    uint64_t len;\n    if (JS_ToIndex(ctx, &len, argv[0]))\n        return JS_EXCEPTION;\n    return js_array_buffer_constructor2(ctx, new_target, len,\n                                        JS_CLASS_SHARED_ARRAY_BUFFER);\n}\n\n/* also used for SharedArrayBuffer */\nstatic void js_array_buffer_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSArrayBuffer *abuf = p->u.array_buffer;\n    if (abuf) {\n        /* The ArrayBuffer finalizer may be called before the typed\n           array finalizers using it, so abuf->array_list is not\n           necessarily empty. */\n        // assert(list_empty(&abuf->array_list));\n        if (abuf->shared && rt->sab_funcs.sab_free) {\n            rt->sab_funcs.sab_free(rt->sab_funcs.sab_opaque, abuf->data);\n        } else {\n            if (abuf->free_func)\n                abuf->free_func(rt, abuf->opaque, abuf->data);\n        }\n        js_free_rt(rt, abuf);\n    }\n}\n\nstatic JSValue js_array_buffer_isView(JSContext *ctx,\n                                      JSValueConst this_val,\n                                      int argc, JSValueConst *argv)\n{\n    JSObject *p;\n    BOOL res;\n    res = FALSE;\n    if (JS_VALUE_GET_TAG(argv[0]) == JS_TAG_OBJECT) {\n        p = JS_VALUE_GET_OBJ(argv[0]);\n        if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n            p->class_id <= JS_CLASS_DATAVIEW) {\n            res = TRUE;\n        }\n    }\n    return JS_NewBool(ctx, res);\n}\n\nstatic const JSCFunctionListEntry js_array_buffer_funcs[] = {\n    JS_CFUNC_DEF(\"isView\", 1, js_array_buffer_isView ),\n    JS_CGETSET_DEF(\"[Symbol.species]\", js_get_this, NULL ),\n};\n\nstatic JSValue JS_ThrowTypeErrorDetachedArrayBuffer(JSContext *ctx)\n{\n    return JS_ThrowTypeError(ctx, \"ArrayBuffer is detached\");\n}\n\nstatic JSValue js_array_buffer_get_byteLength(JSContext *ctx,\n                                              JSValueConst this_val,\n                                              int class_id)\n{\n    JSArrayBuffer *abuf = JS_GetOpaque2(ctx, this_val, class_id);\n    if (!abuf)\n        return JS_EXCEPTION;\n    /* return 0 if detached */\n    return JS_NewUint32(ctx, abuf->byte_length);\n}\n\nvoid JS_DetachArrayBuffer(JSContext *ctx, JSValueConst obj)\n{\n    JSArrayBuffer *abuf = JS_GetOpaque(obj, JS_CLASS_ARRAY_BUFFER);\n    struct list_head *el;\n\n    if (!abuf || abuf->detached)\n        return;\n    if (abuf->free_func)\n        abuf->free_func(ctx->rt, abuf->opaque, abuf->data);\n    abuf->data = NULL;\n    abuf->byte_length = 0;\n    abuf->detached = TRUE;\n\n    list_for_each(el, &abuf->array_list) {\n        JSTypedArray *ta;\n        JSObject *p;\n\n        ta = list_entry(el, JSTypedArray, link);\n        p = ta->obj;\n        /* Note: the typed array length and offset fields are not modified */\n        if (p->class_id != JS_CLASS_DATAVIEW) {\n            p->u.array.count = 0;\n            p->u.array.u.ptr = NULL;\n        }\n    }\n}\n\n/* get an ArrayBuffer or SharedArrayBuffer */\nstatic JSArrayBuffer *js_get_array_buffer(JSContext *ctx, JSValueConst obj)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        goto fail;\n    p = JS_VALUE_GET_OBJ(obj);\n    if (p->class_id != JS_CLASS_ARRAY_BUFFER &&\n        p->class_id != JS_CLASS_SHARED_ARRAY_BUFFER) {\n    fail:\n        JS_ThrowTypeErrorInvalidClass(ctx, JS_CLASS_ARRAY_BUFFER);\n        return NULL;\n    }\n    return p->u.array_buffer;\n}\n\n/* return NULL if exception. WARNING: any JS call can detach the\n   buffer and render the returned pointer invalid */\nuint8_t *JS_GetArrayBuffer(JSContext *ctx, size_t *psize, JSValueConst obj)\n{\n    JSArrayBuffer *abuf = js_get_array_buffer(ctx, obj);\n    if (!abuf)\n        goto fail;\n    if (abuf->detached) {\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        goto fail;\n    }\n    *psize = abuf->byte_length;\n    return abuf->data;\n fail:\n    *psize = 0;\n    return NULL;\n}\n\nstatic JSValue js_array_buffer_slice(JSContext *ctx,\n                                     JSValueConst this_val,\n                                     int argc, JSValueConst *argv, int class_id)\n{\n    JSArrayBuffer *abuf, *new_abuf;\n    int64_t len, start, end, new_len;\n    JSValue ctor, new_obj;\n\n    abuf = JS_GetOpaque2(ctx, this_val, class_id);\n    if (!abuf)\n        return JS_EXCEPTION;\n    if (abuf->detached)\n        return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n    len = abuf->byte_length;\n\n    if (JS_ToInt64Clamp(ctx, &start, argv[0], 0, len, len))\n        return JS_EXCEPTION;\n\n    end = len;\n    if (!JS_IsUndefined(argv[1])) {\n        if (JS_ToInt64Clamp(ctx, &end, argv[1], 0, len, len))\n            return JS_EXCEPTION;\n    }\n    new_len = max_int64(end - start, 0);\n    ctor = JS_SpeciesConstructor(ctx, this_val, JS_UNDEFINED);\n    if (JS_IsException(ctor))\n        return ctor;\n    if (JS_IsUndefined(ctor)) {\n        new_obj = js_array_buffer_constructor2(ctx, JS_UNDEFINED, new_len,\n                                               class_id);\n    } else {\n        JSValue args[1];\n        args[0] = JS_NewInt64(ctx, new_len);\n        new_obj = JS_CallConstructor(ctx, ctor, 1, (JSValueConst *)args);\n        JS_FreeValue(ctx, ctor);\n        JS_FreeValue(ctx, args[0]);\n    }\n    if (JS_IsException(new_obj))\n        return new_obj;\n    new_abuf = JS_GetOpaque2(ctx, new_obj, class_id);\n    if (!new_abuf)\n        goto fail;\n    if (js_same_value(ctx, new_obj, this_val)) {\n        JS_ThrowTypeError(ctx, \"cannot use identical ArrayBuffer\");\n        goto fail;\n    }\n    if (new_abuf->detached) {\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        goto fail;\n    }\n    if (new_abuf->byte_length < new_len) {\n        JS_ThrowTypeError(ctx, \"new ArrayBuffer is too small\");\n        goto fail;\n    }\n    /* must test again because of side effects */\n    if (abuf->detached) {\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        goto fail;\n    }\n    memcpy(new_abuf->data, abuf->data + start, new_len);\n    return new_obj;\n fail:\n    JS_FreeValue(ctx, new_obj);\n    return JS_EXCEPTION;\n}\n\nstatic const JSCFunctionListEntry js_array_buffer_proto_funcs[] = {\n    JS_CGETSET_MAGIC_DEF(\"byteLength\", js_array_buffer_get_byteLength, NULL, JS_CLASS_ARRAY_BUFFER ),\n    JS_CFUNC_MAGIC_DEF(\"slice\", 2, js_array_buffer_slice, JS_CLASS_ARRAY_BUFFER ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"ArrayBuffer\", JS_PROP_CONFIGURABLE ),\n};\n\n/* SharedArrayBuffer */\n\nstatic const JSCFunctionListEntry js_shared_array_buffer_funcs[] = {\n    JS_CGETSET_DEF(\"[Symbol.species]\", js_get_this, NULL ),\n};\n\nstatic const JSCFunctionListEntry js_shared_array_buffer_proto_funcs[] = {\n    JS_CGETSET_MAGIC_DEF(\"byteLength\", js_array_buffer_get_byteLength, NULL, JS_CLASS_SHARED_ARRAY_BUFFER ),\n    JS_CFUNC_MAGIC_DEF(\"slice\", 2, js_array_buffer_slice, JS_CLASS_SHARED_ARRAY_BUFFER ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"SharedArrayBuffer\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic JSObject *get_typed_array(JSContext *ctx,\n                                 JSValueConst this_val,\n                                 int is_dataview)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(this_val) != JS_TAG_OBJECT)\n        goto fail;\n    p = JS_VALUE_GET_OBJ(this_val);\n    if (is_dataview) {\n        if (p->class_id != JS_CLASS_DATAVIEW)\n            goto fail;\n    } else {\n        if (!(p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n              p->class_id <= JS_CLASS_FLOAT64_ARRAY)) {\n        fail:\n            JS_ThrowTypeError(ctx, \"not a %s\", is_dataview ? \"DataView\" : \"TypedArray\");\n            return NULL;\n        }\n    }\n    return p;\n}\n\n/* WARNING: 'p' must be a typed array */\nstatic BOOL typed_array_is_detached(JSContext *ctx, JSObject *p)\n{\n    JSTypedArray *ta = p->u.typed_array;\n    JSArrayBuffer *abuf = ta->buffer->u.array_buffer;\n    /* XXX: could simplify test by ensuring that\n       p->u.array.u.ptr is NULL iff it is detached */\n    return abuf->detached;\n}\n\n/* WARNING: 'p' must be a typed array. Works even if the array buffer\n   is detached */\nstatic uint32_t typed_array_get_length(JSContext *ctx, JSObject *p)\n{\n    JSTypedArray *ta = p->u.typed_array;\n    int size_log2 = typed_array_size_log2(p->class_id);\n    return ta->length >> size_log2;\n}\n\nstatic int validate_typed_array(JSContext *ctx, JSValueConst this_val)\n{\n    JSObject *p;\n    p = get_typed_array(ctx, this_val, 0);\n    if (!p)\n        return -1;\n    if (typed_array_is_detached(ctx, p)) {\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        return -1;\n    }\n    return 0;\n}\n\nstatic JSValue js_typed_array_get_length(JSContext *ctx,\n                                         JSValueConst this_val)\n{\n    JSObject *p;\n    p = get_typed_array(ctx, this_val, 0);\n    if (!p)\n        return JS_EXCEPTION;\n    return JS_NewInt32(ctx, p->u.array.count);\n}\n\nstatic JSValue js_typed_array_get_buffer(JSContext *ctx,\n                                         JSValueConst this_val, int is_dataview)\n{\n    JSObject *p;\n    JSTypedArray *ta;\n    p = get_typed_array(ctx, this_val, is_dataview);\n    if (!p)\n        return JS_EXCEPTION;\n    ta = p->u.typed_array;\n    return JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, ta->buffer));\n}\n\nstatic JSValue js_typed_array_get_byteLength(JSContext *ctx,\n                                             JSValueConst this_val,\n                                             int is_dataview)\n{\n    JSObject *p;\n    JSTypedArray *ta;\n    p = get_typed_array(ctx, this_val, is_dataview);\n    if (!p)\n        return JS_EXCEPTION;\n    if (typed_array_is_detached(ctx, p)) {\n        if (is_dataview) {\n            return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        } else {\n            return JS_NewInt32(ctx, 0);\n        }\n    }\n    ta = p->u.typed_array;\n    return JS_NewInt32(ctx, ta->length);\n}\n\nstatic JSValue js_typed_array_get_byteOffset(JSContext *ctx,\n                                             JSValueConst this_val,\n                                             int is_dataview)\n{\n    JSObject *p;\n    JSTypedArray *ta;\n    p = get_typed_array(ctx, this_val, is_dataview);\n    if (!p)\n        return JS_EXCEPTION;\n    if (typed_array_is_detached(ctx, p)) {\n        if (is_dataview) {\n            return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        } else {\n            return JS_NewInt32(ctx, 0);\n        }\n    }\n    ta = p->u.typed_array;\n    return JS_NewInt32(ctx, ta->offset);\n}\n\n/* Return the buffer associated to the typed array or an exception if\n   it is not a typed array or if the buffer is detached. pbyte_offset,\n   pbyte_length or pbytes_per_element can be NULL. */\nJSValue JS_GetTypedArrayBuffer(JSContext *ctx, JSValueConst obj,\n                               size_t *pbyte_offset,\n                               size_t *pbyte_length,\n                               size_t *pbytes_per_element)\n{\n    JSObject *p;\n    JSTypedArray *ta;\n    p = get_typed_array(ctx, obj, FALSE);\n    if (!p)\n        return JS_EXCEPTION;\n    if (typed_array_is_detached(ctx, p))\n        return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n    ta = p->u.typed_array;\n    if (pbyte_offset)\n        *pbyte_offset = ta->offset;\n    if (pbyte_length)\n        *pbyte_length = ta->length;\n    if (pbytes_per_element) {\n        *pbytes_per_element = 1 << typed_array_size_log2(p->class_id);\n    }\n    return JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, ta->buffer));\n}\n                               \nstatic JSValue js_typed_array_get_toStringTag(JSContext *ctx,\n                                              JSValueConst this_val)\n{\n    JSObject *p;\n    if (JS_VALUE_GET_TAG(this_val) != JS_TAG_OBJECT)\n        return JS_UNDEFINED;\n    p = JS_VALUE_GET_OBJ(this_val);\n    if (!(p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n          p->class_id <= JS_CLASS_FLOAT64_ARRAY))\n        return JS_UNDEFINED;\n    return JS_AtomToString(ctx, ctx->rt->class_array[p->class_id].class_name);\n}\n\nstatic JSValue js_typed_array_set_internal(JSContext *ctx,\n                                           JSValueConst dst,\n                                           JSValueConst src,\n                                           JSValueConst off)\n{\n    JSObject *p;\n    JSObject *src_p;\n    uint32_t i;\n    int64_t src_len, offset;\n    JSValue val, src_obj = JS_UNDEFINED;\n\n    p = get_typed_array(ctx, dst, 0);\n    if (!p)\n        goto fail;\n    if (JS_ToInt64Sat(ctx, &offset, off))\n        goto fail;\n    if (offset < 0)\n        goto range_error;\n    if (typed_array_is_detached(ctx, p)) {\n    detached:\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        goto fail;\n    }\n    src_obj = JS_ToObject(ctx, src);\n    if (JS_IsException(src_obj))\n        goto fail;\n    src_p = JS_VALUE_GET_OBJ(src_obj);\n    if (src_p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n        src_p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n        JSTypedArray *dest_ta = p->u.typed_array;\n        JSArrayBuffer *dest_abuf = dest_ta->buffer->u.array_buffer;\n        JSTypedArray *src_ta = src_p->u.typed_array;\n        JSArrayBuffer *src_abuf = src_ta->buffer->u.array_buffer;\n        int shift = typed_array_size_log2(p->class_id);\n\n        if (src_abuf->detached)\n            goto detached;\n\n        src_len = src_p->u.array.count;\n        if (offset > (int64_t)(p->u.array.count - src_len))\n            goto range_error;\n\n        /* copying between typed objects */\n        if (src_p->class_id == p->class_id) {\n            /* same type, use memmove */\n            memmove(dest_abuf->data + dest_ta->offset + (offset << shift),\n                    src_abuf->data + src_ta->offset, src_len << shift);\n            goto done;\n        }\n        if (dest_abuf->data == src_abuf->data) {\n            /* copying between the same buffer using different types of mappings\n               would require a temporary buffer */\n        }\n        /* otherwise, default behavior is slow but correct */\n    } else {\n        if (js_get_length64(ctx, &src_len, src_obj))\n            goto fail;\n        if (offset > (int64_t)(p->u.array.count - src_len)) {\n        range_error:\n            JS_ThrowRangeError(ctx, \"invalid array length\");\n            goto fail;\n        }\n    }\n    for(i = 0; i < src_len; i++) {\n        val = JS_GetPropertyUint32(ctx, src_obj, i);\n        if (JS_IsException(val))\n            goto fail;\n        if (JS_SetPropertyUint32(ctx, dst, offset + i, val) < 0)\n            goto fail;\n    }\ndone:\n    JS_FreeValue(ctx, src_obj);\n    return JS_UNDEFINED;\nfail:\n    JS_FreeValue(ctx, src_obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_typed_array_set(JSContext *ctx,\n                                  JSValueConst this_val,\n                                  int argc, JSValueConst *argv)\n{\n    JSValueConst offset = JS_UNDEFINED;\n    if (argc > 1) {\n        offset = argv[1];\n    }\n    return js_typed_array_set_internal(ctx, this_val, argv[0], offset);\n}\n\nstatic JSValue js_create_typed_array_iterator(JSContext *ctx, JSValueConst this_val,\n                                              int argc, JSValueConst *argv, int magic)\n{\n    if (validate_typed_array(ctx, this_val))\n        return JS_EXCEPTION;\n    return js_create_array_iterator(ctx, this_val, argc, argv, magic);\n}\n\n/* return < 0 if exception */\nstatic int js_typed_array_get_length_internal(JSContext *ctx,\n                                              JSValueConst obj)\n{\n    JSObject *p;\n    p = get_typed_array(ctx, obj, 0);\n    if (!p)\n        return -1;\n    if (typed_array_is_detached(ctx, p)) {\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        return -1;\n    }\n    return p->u.array.count;\n}\n\n#if 0\n/* validate a typed array and return its length */\nstatic JSValue js_typed_array___getLength(JSContext *ctx,\n                                          JSValueConst this_val,\n                                          int argc, JSValueConst *argv)\n{\n    BOOL ignore_detached = JS_ToBool(ctx, argv[1]);\n\n    if (ignore_detached) {\n        return js_typed_array_get_length(ctx, argv[0]);\n    } else {\n        int len;\n        len = js_typed_array_get_length_internal(ctx, argv[0]);\n        if (len < 0)\n            return JS_EXCEPTION;\n        return JS_NewInt32(ctx, len);\n    }\n}\n#endif\n\nstatic JSValue js_typed_array_create(JSContext *ctx, JSValueConst ctor,\n                                     int argc, JSValueConst *argv)\n{\n    JSValue ret;\n    int new_len;\n    int64_t len;\n\n    ret = JS_CallConstructor(ctx, ctor, argc, argv);\n    if (JS_IsException(ret))\n        return ret;\n    /* validate the typed array */\n    new_len = js_typed_array_get_length_internal(ctx, ret);\n    if (new_len < 0)\n        goto fail;\n    if (argc == 1) {\n        /* ensure that it is large enough */\n        if (JS_ToLengthFree(ctx, &len, JS_DupValue(ctx, argv[0])))\n            goto fail;\n        if (new_len < len) {\n            JS_ThrowTypeError(ctx, \"TypedArray length is too small\");\n        fail:\n            JS_FreeValue(ctx, ret);\n            return JS_EXCEPTION;\n        }\n    }\n    return ret;\n}\n\n#if 0\nstatic JSValue js_typed_array___create(JSContext *ctx,\n                                       JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    return js_typed_array_create(ctx, argv[0], max_int(argc - 1, 0), argv + 1);\n}\n#endif\n\nstatic JSValue js_typed_array___speciesCreate(JSContext *ctx,\n                                              JSValueConst this_val,\n                                              int argc, JSValueConst *argv)\n{\n    JSValueConst obj;\n    JSObject *p;\n    JSValue ctor, ret;\n    int argc1;\n\n    obj = argv[0];\n    p = get_typed_array(ctx, obj, 0);\n    if (!p)\n        return JS_EXCEPTION;\n    ctor = JS_SpeciesConstructor(ctx, obj, JS_UNDEFINED);\n    if (JS_IsException(ctor))\n        return ctor;\n    argc1 = max_int(argc - 1, 0);\n    if (JS_IsUndefined(ctor)) {\n        ret = js_typed_array_constructor(ctx, JS_UNDEFINED, argc1, argv + 1,\n                                         p->class_id);\n    } else {\n        ret = js_typed_array_create(ctx, ctor, argc1, argv + 1);\n        JS_FreeValue(ctx, ctor);\n    }\n    return ret;\n}\n\nstatic JSValue js_typed_array_from(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    // from(items, mapfn = void 0, this_arg = void 0)\n    JSValueConst items = argv[0], mapfn, this_arg;\n    JSValueConst args[2];\n    JSValue stack[2];\n    JSValue iter, arr, r, v, v2;\n    int64_t k, len;\n    int done, mapping;\n\n    mapping = FALSE;\n    mapfn = JS_UNDEFINED;\n    this_arg = JS_UNDEFINED;\n    r = JS_UNDEFINED;\n    arr = JS_UNDEFINED;\n    stack[0] = JS_UNDEFINED;\n    stack[1] = JS_UNDEFINED;\n\n    if (argc > 1) {\n        mapfn = argv[1];\n        if (!JS_IsUndefined(mapfn)) {\n            if (check_function(ctx, mapfn))\n                goto exception;\n            mapping = 1;\n            if (argc > 2)\n                this_arg = argv[2];\n        }\n    }\n    iter = JS_GetProperty(ctx, items, JS_ATOM_Symbol_iterator);\n    if (JS_IsException(iter))\n        goto exception;\n    if (!JS_IsUndefined(iter)) {\n        JS_FreeValue(ctx, iter);\n        arr = JS_NewArray(ctx);\n        if (JS_IsException(arr))\n            goto exception;\n        stack[0] = JS_DupValue(ctx, items);\n        if (js_for_of_start(ctx, &stack[1], FALSE))\n            goto exception;\n        for (k = 0;; k++) {\n            v = JS_IteratorNext(ctx, stack[0], stack[1], 0, NULL, &done);\n            if (JS_IsException(v))\n                goto exception_close;\n            if (done)\n                break;\n            if (JS_DefinePropertyValueInt64(ctx, arr, k, v, JS_PROP_C_W_E | JS_PROP_THROW) < 0)\n                goto exception_close;\n        }\n    } else {\n        arr = JS_ToObject(ctx, items);\n        if (JS_IsException(arr))\n            goto exception;\n    }\n    if (js_get_length64(ctx, &len, arr) < 0)\n        goto exception;\n    v = JS_NewInt64(ctx, len);\n    args[0] = v;\n    r = js_typed_array_create(ctx, this_val, 1, args);\n    JS_FreeValue(ctx, v);\n    if (JS_IsException(r))\n        goto exception;\n    for(k = 0; k < len; k++) {\n        v = JS_GetPropertyInt64(ctx, arr, k);\n        if (JS_IsException(v))\n            goto exception;\n        if (mapping) {\n            args[0] = v;\n            args[1] = JS_NewInt32(ctx, k);\n            v2 = JS_Call(ctx, mapfn, this_arg, 2, args);\n            JS_FreeValue(ctx, v);\n            v = v2;\n            if (JS_IsException(v))\n                goto exception;\n        }\n        if (JS_SetPropertyInt64(ctx, r, k, v) < 0)\n            goto exception;\n    }\n    goto done;\n\n exception_close:\n    if (!JS_IsUndefined(stack[0]))\n        JS_IteratorClose(ctx, stack[0], TRUE);\n exception:\n    JS_FreeValue(ctx, r);\n    r = JS_EXCEPTION;\n done:\n    JS_FreeValue(ctx, arr);\n    JS_FreeValue(ctx, stack[0]);\n    JS_FreeValue(ctx, stack[1]);\n    return r;\n}\n\nstatic JSValue js_typed_array_of(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv)\n{\n    JSValue obj;\n    JSValueConst args[1];\n    int i;\n\n    args[0] = JS_NewInt32(ctx, argc);\n    obj = js_typed_array_create(ctx, this_val, 1, args);\n    if (JS_IsException(obj))\n        return obj;\n\n    for(i = 0; i < argc; i++) {\n        if (JS_SetPropertyUint32(ctx, obj, i, JS_DupValue(ctx, argv[i])) < 0) {\n            JS_FreeValue(ctx, obj);\n            return JS_EXCEPTION;\n        }\n    }\n    return obj;\n}\n\nstatic JSValue js_typed_array_copyWithin(JSContext *ctx, JSValueConst this_val,\n                                         int argc, JSValueConst *argv)\n{\n    JSObject *p;\n    int len, to, from, final, count, shift;\n\n    len = js_typed_array_get_length_internal(ctx, this_val);\n    if (len < 0)\n        return JS_EXCEPTION;\n\n    if (JS_ToInt32Clamp(ctx, &to, argv[0], 0, len, len))\n        return JS_EXCEPTION;\n\n    if (JS_ToInt32Clamp(ctx, &from, argv[1], 0, len, len))\n        return JS_EXCEPTION;\n\n    final = len;\n    if (argc > 2 && !JS_IsUndefined(argv[2])) {\n        if (JS_ToInt32Clamp(ctx, &final, argv[2], 0, len, len))\n            return JS_EXCEPTION;\n    }\n\n    count = min_int(final - from, len - to);\n    if (count > 0) {\n        p = JS_VALUE_GET_OBJ(this_val);\n        if (typed_array_is_detached(ctx, p))\n            return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        shift = typed_array_size_log2(p->class_id);\n        memmove(p->u.array.u.uint8_ptr + (to << shift),\n                p->u.array.u.uint8_ptr + (from << shift),\n                count << shift);\n    }\n    return JS_DupValue(ctx, this_val);\n}\n\nstatic JSValue js_typed_array_fill(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    JSObject *p;\n    int len, k, final, shift;\n    uint64_t v64;\n\n    len = js_typed_array_get_length_internal(ctx, this_val);\n    if (len < 0)\n        return JS_EXCEPTION;\n    p = JS_VALUE_GET_OBJ(this_val);\n\n    if (p->class_id == JS_CLASS_UINT8C_ARRAY) {\n        int32_t v;\n        if (JS_ToUint8ClampFree(ctx, &v, JS_DupValue(ctx, argv[0])))\n            return JS_EXCEPTION;\n        v64 = v;\n    } else if (p->class_id <= JS_CLASS_UINT32_ARRAY) {\n        uint32_t v;\n        if (JS_ToUint32(ctx, &v, argv[0]))\n            return JS_EXCEPTION;\n        v64 = v;\n    } else\n#ifdef CONFIG_BIGNUM\n    if (p->class_id <= JS_CLASS_BIG_UINT64_ARRAY) {\n        if (JS_ToBigInt64(ctx, (int64_t *)&v64, argv[0]))\n            return JS_EXCEPTION;\n    } else\n#endif\n    {\n        double d;\n        if (JS_ToFloat64(ctx, &d, argv[0]))\n            return JS_EXCEPTION;\n        if (p->class_id == JS_CLASS_FLOAT32_ARRAY) {\n            union {\n                float f;\n                uint32_t u32;\n            } u;\n            u.f = d;\n            v64 = u.u32;\n        } else {\n            JSFloat64Union u;\n            u.d = d;\n            v64 = u.u64;\n        }\n    }\n\n    k = 0;\n    if (argc > 1) {\n        if (JS_ToInt32Clamp(ctx, &k, argv[1], 0, len, len))\n            return JS_EXCEPTION;\n    }\n\n    final = len;\n    if (argc > 2 && !JS_IsUndefined(argv[2])) {\n        if (JS_ToInt32Clamp(ctx, &final, argv[2], 0, len, len))\n            return JS_EXCEPTION;\n    }\n\n    if (typed_array_is_detached(ctx, p))\n        return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n    \n    shift = typed_array_size_log2(p->class_id);\n    switch(shift) {\n    case 0:\n        if (k < final) {\n            memset(p->u.array.u.uint8_ptr + k, v64, final - k);\n        }\n        break;\n    case 1:\n        for(; k < final; k++) {\n            p->u.array.u.uint16_ptr[k] = v64;\n        }\n        break;\n    case 2:\n        for(; k < final; k++) {\n            p->u.array.u.uint32_ptr[k] = v64;\n        }\n        break;\n    case 3:\n        for(; k < final; k++) {\n            p->u.array.u.uint64_ptr[k] = v64;\n        }\n        break;\n    default:\n        abort();\n    }\n    return JS_DupValue(ctx, this_val);\n}\n\nstatic JSValue js_typed_array_find(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv, int findIndex)\n{\n    JSValueConst func, this_arg;\n    JSValueConst args[3];\n    JSValue val, index_val, res;\n    int len, k;\n\n    val = JS_UNDEFINED;\n    len = js_typed_array_get_length_internal(ctx, this_val);\n    if (len < 0)\n        goto exception;\n\n    func = argv[0];\n    if (check_function(ctx, func))\n        goto exception;\n\n    this_arg = JS_UNDEFINED;\n    if (argc > 1)\n        this_arg = argv[1];\n\n    for(k = 0; k < len; k++) {\n        index_val = JS_NewInt32(ctx, k);\n        val = JS_GetPropertyValue(ctx, this_val, index_val);\n        if (JS_IsException(val))\n            goto exception;\n        args[0] = val;\n        args[1] = index_val;\n        args[2] = this_val;\n        res = JS_Call(ctx, func, this_arg, 3, args);\n        if (JS_IsException(res))\n            goto exception;\n        if (JS_ToBoolFree(ctx, res)) {\n            if (findIndex) {\n                JS_FreeValue(ctx, val);\n                return index_val;\n            } else {\n                return val;\n            }\n        }\n        JS_FreeValue(ctx, val);\n    }\n    if (findIndex)\n        return JS_NewInt32(ctx, -1);\n    else\n        return JS_UNDEFINED;\n\nexception:\n    JS_FreeValue(ctx, val);\n    return JS_EXCEPTION;\n}\n\n#define special_indexOf 0\n#define special_lastIndexOf 1\n#define special_includes -1\n\nstatic JSValue js_typed_array_indexOf(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv, int special)\n{\n    JSObject *p;\n    int len, tag, is_int, is_bigint, k, stop, inc, res = -1;\n    int64_t v64;\n    double d;\n    float f;\n\n    len = js_typed_array_get_length_internal(ctx, this_val);\n    if (len < 0)\n        goto exception;\n    if (len == 0)\n        goto done;\n\n    if (special == special_lastIndexOf) {\n        k = len - 1;\n        if (argc > 1) {\n            if (JS_ToFloat64(ctx, &d, argv[1]))\n                goto exception;\n            if (isnan(d)) {\n                k = 0;\n            } else {\n                if (d >= 0) {\n                    if (d < k) {\n                        k = d;\n                    }\n                } else {\n                    d += len;\n                    if (d < 0)\n                        goto done;\n                    k = d;\n                }\n            }\n        }\n        stop = -1;\n        inc = -1;\n    } else {\n        k = 0;\n        if (argc > 1) {\n            if (JS_ToInt32Clamp(ctx, &k, argv[1], 0, len, len))\n                goto exception;\n        }\n        stop = len;\n        inc = 1;\n    }\n\n    p = JS_VALUE_GET_OBJ(this_val);\n    /* if the array was detached, no need to go further (but no\n       exception is raised) */\n    if (typed_array_is_detached(ctx, p)) {\n        /* \"includes\" scans all the properties, so \"undefined\" can match */\n        if (special == special_includes && JS_IsUndefined(argv[0]) && len > 0)\n            res = 0;\n        goto done;\n    }\n    \n    is_bigint = 0;\n    is_int = 0; /* avoid warning */\n    v64 = 0; /* avoid warning */\n    tag = JS_VALUE_GET_NORM_TAG(argv[0]);\n    if (tag == JS_TAG_INT) {\n        is_int = 1;\n        v64 = JS_VALUE_GET_INT(argv[0]);\n        d = v64;\n    } else\n    if (tag == JS_TAG_FLOAT64) {\n        d = JS_VALUE_GET_FLOAT64(argv[0]);\n        v64 = d;\n        is_int = (v64 == d);\n    } else\n#ifdef CONFIG_BIGNUM\n    if (tag == JS_TAG_BIG_INT) {\n        JSBigFloat *p1 = JS_VALUE_GET_PTR(argv[0]);\n        \n        if (p->class_id == JS_CLASS_BIG_INT64_ARRAY) {\n            if (bf_get_int64(&v64, &p1->num, 0) != 0)\n                goto done;\n        } else if (p->class_id == JS_CLASS_BIG_UINT64_ARRAY) {\n            if (bf_get_uint64((uint64_t *)&v64, &p1->num) != 0)\n                goto done;\n        } else {\n            goto done;\n        }\n        d = 0;\n        is_bigint = 1;\n    } else\n#endif\n    {\n        goto done;\n    }\n\n    switch (p->class_id) {\n    case JS_CLASS_INT8_ARRAY:\n        if (is_int && (int8_t)v64 == v64)\n            goto scan8;\n        break;\n    case JS_CLASS_UINT8C_ARRAY:\n    case JS_CLASS_UINT8_ARRAY:\n        if (is_int && (uint8_t)v64 == v64) {\n            const uint8_t *pv, *pp;\n            uint16_t v;\n        scan8:\n            pv = p->u.array.u.uint8_ptr;\n            v = v64;\n            if (inc > 0) {\n                pp = memchr(pv + k, v, len - k);\n                if (pp)\n                    res = pp - pv;\n            } else {\n                for (; k != stop; k += inc) {\n                    if (pv[k] == v) {\n                        res = k;\n                        break;\n                    }\n                }\n            }\n        }\n        break;\n    case JS_CLASS_INT16_ARRAY:\n        if (is_int && (int16_t)v64 == v64)\n            goto scan16;\n        break;\n    case JS_CLASS_UINT16_ARRAY:\n        if (is_int && (uint16_t)v64 == v64) {\n            const uint16_t *pv;\n            uint16_t v;\n        scan16:\n            pv = p->u.array.u.uint16_ptr;\n            v = v64;\n            for (; k != stop; k += inc) {\n                if (pv[k] == v) {\n                    res = k;\n                    break;\n                }\n            }\n        }\n        break;\n    case JS_CLASS_INT32_ARRAY:\n        if (is_int && (int32_t)v64 == v64)\n            goto scan32;\n        break;\n    case JS_CLASS_UINT32_ARRAY:\n        if (is_int && (uint32_t)v64 == v64) {\n            const uint32_t *pv;\n            uint32_t v;\n        scan32:\n            pv = p->u.array.u.uint32_ptr;\n            v = v64;\n            for (; k != stop; k += inc) {\n                if (pv[k] == v) {\n                    res = k;\n                    break;\n                }\n            }\n        }\n        break;\n    case JS_CLASS_FLOAT32_ARRAY:\n        if (is_bigint)\n            break;\n        if (isnan(d)) {\n            const float *pv = p->u.array.u.float_ptr;\n            /* special case: indexOf returns -1, includes finds NaN */\n            if (special != special_includes)\n                goto done;\n            for (; k != stop; k += inc) {\n                if (isnan(pv[k])) {\n                    res = k;\n                    break;\n                }\n            }\n        } else if ((f = (float)d) == d) {\n            const float *pv = p->u.array.u.float_ptr;\n            for (; k != stop; k += inc) {\n                if (pv[k] == f) {\n                    res = k;\n                    break;\n                }\n            }\n        }\n        break;\n    case JS_CLASS_FLOAT64_ARRAY:\n        if (is_bigint)\n            break;\n        if (isnan(d)) {\n            const double *pv = p->u.array.u.double_ptr;\n            /* special case: indexOf returns -1, includes finds NaN */\n            if (special != special_includes)\n                goto done;\n            for (; k != stop; k += inc) {\n                if (isnan(pv[k])) {\n                    res = k;\n                    break;\n                }\n            }\n        } else {\n            const double *pv = p->u.array.u.double_ptr;\n            for (; k != stop; k += inc) {\n                if (pv[k] == d) {\n                    res = k;\n                    break;\n                }\n            }\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_CLASS_BIG_INT64_ARRAY:\n        if (is_bigint || (is_math_mode(ctx) && is_int &&\n                          v64 >= -MAX_SAFE_INTEGER &&\n                          v64 <= MAX_SAFE_INTEGER)) {\n            goto scan64;\n        }\n        break;\n    case JS_CLASS_BIG_UINT64_ARRAY:\n        if (is_bigint || (is_math_mode(ctx) && is_int &&\n                          v64 >= 0 && v64 <= MAX_SAFE_INTEGER)) {\n            const uint64_t *pv;\n            uint64_t v;\n        scan64:\n            pv = p->u.array.u.uint64_ptr;\n            v = v64;\n            for (; k != stop; k += inc) {\n                if (pv[k] == v) {\n                    res = k;\n                    break;\n                }\n            }\n        }\n        break;\n#endif\n    }\n\ndone:\n    if (special == special_includes)\n        return JS_NewBool(ctx, res >= 0);\n    else\n        return JS_NewInt32(ctx, res);\n\nexception:\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_typed_array_join(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv, int toLocaleString)\n{\n    JSValue sep = JS_UNDEFINED, el;\n    StringBuffer b_s, *b = &b_s;\n    JSString *p = NULL;\n    int i, n;\n    int c;\n\n    n = js_typed_array_get_length_internal(ctx, this_val);\n    if (n < 0)\n        goto exception;\n\n    c = ',';    /* default separator */\n    if (!toLocaleString && argc > 0 && !JS_IsUndefined(argv[0])) {\n        sep = JS_ToString(ctx, argv[0]);\n        if (JS_IsException(sep))\n            goto exception;\n        p = JS_VALUE_GET_STRING(sep);\n        if (p->len == 1 && !p->is_wide_char)\n            c = p->u.str8[0];\n        else\n            c = -1;\n    }\n    string_buffer_init(ctx, b, 0);\n\n    /* XXX: optimize with direct access */\n    for(i = 0; i < n; i++) {\n        if (i > 0) {\n            if (c >= 0) {\n                if (string_buffer_putc8(b, c))\n                    goto fail;\n            } else {\n                if (string_buffer_concat(b, p, 0, p->len))\n                    goto fail;\n            }\n        }\n        el = JS_GetPropertyUint32(ctx, this_val, i);\n        /* Can return undefined for example if the typed array is detached */\n        if (!JS_IsNull(el) && !JS_IsUndefined(el)) {\n            if (JS_IsException(el))\n                goto fail;\n            if (toLocaleString) {\n                el = JS_ToLocaleStringFree(ctx, el);\n            }\n            if (string_buffer_concat_value_free(b, el))\n                goto fail;\n        }\n    }\n    JS_FreeValue(ctx, sep);\n    return string_buffer_end(b);\n\nfail:\n    string_buffer_free(b);\n    JS_FreeValue(ctx, sep);\nexception:\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_typed_array_reverse(JSContext *ctx, JSValueConst this_val,\n                                      int argc, JSValueConst *argv)\n{\n    JSObject *p;\n    int len;\n\n    len = js_typed_array_get_length_internal(ctx, this_val);\n    if (len < 0)\n        return JS_EXCEPTION;\n    if (len > 0) {\n        p = JS_VALUE_GET_OBJ(this_val);\n        switch (typed_array_size_log2(p->class_id)) {\n        case 0:\n            {\n                uint8_t *p1 = p->u.array.u.uint8_ptr;\n                uint8_t *p2 = p1 + len - 1;\n                while (p1 < p2) {\n                    uint8_t v = *p1;\n                    *p1++ = *p2;\n                    *p2-- = v;\n                }\n            }\n            break;\n        case 1:\n            {\n                uint16_t *p1 = p->u.array.u.uint16_ptr;\n                uint16_t *p2 = p1 + len - 1;\n                while (p1 < p2) {\n                    uint16_t v = *p1;\n                    *p1++ = *p2;\n                    *p2-- = v;\n                }\n            }\n            break;\n        case 2:\n            {\n                uint32_t *p1 = p->u.array.u.uint32_ptr;\n                uint32_t *p2 = p1 + len - 1;\n                while (p1 < p2) {\n                    uint32_t v = *p1;\n                    *p1++ = *p2;\n                    *p2-- = v;\n                }\n            }\n            break;\n        case 3:\n            {\n                uint64_t *p1 = p->u.array.u.uint64_ptr;\n                uint64_t *p2 = p1 + len - 1;\n                while (p1 < p2) {\n                    uint64_t v = *p1;\n                    *p1++ = *p2;\n                    *p2-- = v;\n                }\n            }\n            break;\n        default:\n            abort();\n        }\n    }\n    return JS_DupValue(ctx, this_val);\n}\n\nstatic JSValue js_typed_array_slice(JSContext *ctx, JSValueConst this_val,\n                                    int argc, JSValueConst *argv)\n{\n    JSValueConst args[2];\n    JSValue arr, val;\n    JSObject *p, *p1;\n    int n, len, start, final, count, shift;\n\n    arr = JS_UNDEFINED;\n    len = js_typed_array_get_length_internal(ctx, this_val);\n    if (len < 0)\n        goto exception;\n\n    if (JS_ToInt32Clamp(ctx, &start, argv[0], 0, len, len))\n        goto exception;\n    final = len;\n    if (!JS_IsUndefined(argv[1])) {\n        if (JS_ToInt32Clamp(ctx, &final, argv[1], 0, len, len))\n            goto exception;\n    }\n    count = max_int(final - start, 0);\n\n    p = get_typed_array(ctx, this_val, 0);\n    if (p == NULL)\n        goto exception;\n    shift = typed_array_size_log2(p->class_id);\n\n    args[0] = this_val;\n    args[1] = JS_NewInt32(ctx, count);\n    arr = js_typed_array___speciesCreate(ctx, JS_UNDEFINED, 2, args);\n    if (JS_IsException(arr))\n        goto exception;\n\n    if (count > 0) {\n        if (validate_typed_array(ctx, this_val)\n        ||  validate_typed_array(ctx, arr))\n            goto exception;\n\n        p1 = get_typed_array(ctx, arr, 0);\n        if (p1 != NULL && p->class_id == p1->class_id &&\n            typed_array_get_length(ctx, p1) >= count &&\n            typed_array_get_length(ctx, p) >= start + count) {\n            memcpy(p1->u.array.u.uint8_ptr,\n                   p->u.array.u.uint8_ptr + (start << shift),\n                   count << shift);\n        } else {\n            for (n = 0; n < count; n++) {\n                val = JS_GetPropertyValue(ctx, this_val, JS_NewInt32(ctx, start + n));\n                if (JS_IsException(val))\n                    goto exception;\n                if (JS_SetPropertyValue(ctx, arr, JS_NewInt32(ctx, n), val,\n                                        JS_PROP_THROW) < 0)\n                    goto exception;\n            }\n        }\n    }\n    return arr;\n\n exception:\n    JS_FreeValue(ctx, arr);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_typed_array_subarray(JSContext *ctx, JSValueConst this_val,\n                                       int argc, JSValueConst *argv)\n{\n    JSValueConst args[4];\n    JSValue arr, byteOffset, ta_buffer;\n    JSObject *p;\n    int len, start, final, count, shift, offset;\n\n    p = get_typed_array(ctx, this_val, 0);\n    if (!p)\n        goto exception;\n    len = p->u.array.count;\n    if (JS_ToInt32Clamp(ctx, &start, argv[0], 0, len, len))\n        goto exception;\n\n    final = len;\n    if (!JS_IsUndefined(argv[1])) {\n        if (JS_ToInt32Clamp(ctx, &final, argv[1], 0, len, len))\n            goto exception;\n    }\n    count = max_int(final - start, 0);\n    byteOffset = js_typed_array_get_byteOffset(ctx, this_val, 0);\n    if (JS_IsException(byteOffset))\n        goto exception;\n    shift = typed_array_size_log2(p->class_id);\n    offset = JS_VALUE_GET_INT(byteOffset) + (start << shift);\n    JS_FreeValue(ctx, byteOffset);\n    ta_buffer = js_typed_array_get_buffer(ctx, this_val, 0);\n    if (JS_IsException(ta_buffer))\n        goto exception;\n    args[0] = this_val;\n    args[1] = ta_buffer;\n    args[2] = JS_NewInt32(ctx, offset);\n    args[3] = JS_NewInt32(ctx, count);\n    arr = js_typed_array___speciesCreate(ctx, JS_UNDEFINED, 4, args);\n    JS_FreeValue(ctx, ta_buffer);\n    return arr;\n\n exception:\n    return JS_EXCEPTION;\n}\n\n/* TypedArray.prototype.sort */\n\nstatic int js_cmp_doubles(double x, double y)\n{\n    if (isnan(x))    return isnan(y) ? 0 : +1;\n    if (isnan(y))    return -1;\n    if (x < y)       return -1;\n    if (x > y)       return 1;\n    if (x != 0)      return 0;\n    if (signbit(x))  return signbit(y) ? 0 : -1;\n    else             return signbit(y) ? 1 : 0;\n}\n\nstatic int js_TA_cmp_int8(const void *a, const void *b, void *opaque) {\n    return *(const int8_t *)a - *(const int8_t *)b;\n}\n\nstatic int js_TA_cmp_uint8(const void *a, const void *b, void *opaque) {\n    return *(const uint8_t *)a - *(const uint8_t *)b;\n}\n\nstatic int js_TA_cmp_int16(const void *a, const void *b, void *opaque) {\n    return *(const int16_t *)a - *(const int16_t *)b;\n}\n\nstatic int js_TA_cmp_uint16(const void *a, const void *b, void *opaque) {\n    return *(const uint16_t *)a - *(const uint16_t *)b;\n}\n\nstatic int js_TA_cmp_int32(const void *a, const void *b, void *opaque) {\n    int32_t x = *(const int32_t *)a;\n    int32_t y = *(const int32_t *)b;\n    return (y < x) - (y > x);\n}\n\nstatic int js_TA_cmp_uint32(const void *a, const void *b, void *opaque) {\n    uint32_t x = *(const uint32_t *)a;\n    uint32_t y = *(const uint32_t *)b;\n    return (y < x) - (y > x);\n}\n\n#ifdef CONFIG_BIGNUM\nstatic int js_TA_cmp_int64(const void *a, const void *b, void *opaque) {\n    int64_t x = *(const int64_t *)a;\n    int64_t y = *(const int64_t *)b;\n    return (y < x) - (y > x);\n}\n\nstatic int js_TA_cmp_uint64(const void *a, const void *b, void *opaque) {\n    uint64_t x = *(const uint64_t *)a;\n    uint64_t y = *(const uint64_t *)b;\n    return (y < x) - (y > x);\n}\n#endif\n\nstatic int js_TA_cmp_float32(const void *a, const void *b, void *opaque) {\n    return js_cmp_doubles(*(const float *)a, *(const float *)b);\n}\n\nstatic int js_TA_cmp_float64(const void *a, const void *b, void *opaque) {\n    return js_cmp_doubles(*(const double *)a, *(const double *)b);\n}\n\nstatic JSValue js_TA_get_int8(JSContext *ctx, const void *a) {\n    return JS_NewInt32(ctx, *(const int8_t *)a);\n}\n\nstatic JSValue js_TA_get_uint8(JSContext *ctx, const void *a) {\n    return JS_NewInt32(ctx, *(const uint8_t *)a);\n}\n\nstatic JSValue js_TA_get_int16(JSContext *ctx, const void *a) {\n    return JS_NewInt32(ctx, *(const int16_t *)a);\n}\n\nstatic JSValue js_TA_get_uint16(JSContext *ctx, const void *a) {\n    return JS_NewInt32(ctx, *(const uint16_t *)a);\n}\n\nstatic JSValue js_TA_get_int32(JSContext *ctx, const void *a) {\n    return JS_NewInt32(ctx, *(const int32_t *)a);\n}\n\nstatic JSValue js_TA_get_uint32(JSContext *ctx, const void *a) {\n    return JS_NewUint32(ctx, *(const uint32_t *)a);\n}\n\n#ifdef CONFIG_BIGNUM\nstatic JSValue js_TA_get_int64(JSContext *ctx, const void *a) {\n    return JS_NewBigInt64(ctx, *(int64_t *)a);\n}\n\nstatic JSValue js_TA_get_uint64(JSContext *ctx, const void *a) {\n    return JS_NewBigUint64(ctx, *(uint64_t *)a);\n}\n#endif\n\nstatic JSValue js_TA_get_float32(JSContext *ctx, const void *a) {\n    return __JS_NewFloat64(ctx, *(const float *)a);\n}\n\nstatic JSValue js_TA_get_float64(JSContext *ctx, const void *a) {\n    return __JS_NewFloat64(ctx, *(const double *)a);\n}\n\nstruct TA_sort_context {\n    JSContext *ctx;\n    int exception;\n    JSValueConst arr;\n    JSValueConst cmp;\n    JSValue (*getfun)(JSContext *ctx, const void *a);\n    uint8_t *array_ptr; /* cannot change unless the array is detached */\n    int elt_size;\n};\n\nstatic int js_TA_cmp_generic(const void *a, const void *b, void *opaque) {\n    struct TA_sort_context *psc = opaque;\n    JSContext *ctx = psc->ctx;\n    uint32_t a_idx, b_idx;\n    JSValueConst argv[2];\n    JSValue res;\n    int cmp;\n\n    cmp = 0;\n    if (!psc->exception) {\n        a_idx = *(uint32_t *)a;\n        b_idx = *(uint32_t *)b;\n        argv[0] = psc->getfun(ctx, psc->array_ptr +\n                              a_idx * (size_t)psc->elt_size);\n        argv[1] = psc->getfun(ctx, psc->array_ptr +\n                              b_idx * (size_t)(psc->elt_size));\n        res = JS_Call(ctx, psc->cmp, JS_UNDEFINED, 2, argv);\n        if (JS_IsException(res)) {\n            psc->exception = 1;\n            goto done;\n        }\n        if (JS_VALUE_GET_TAG(res) == JS_TAG_INT) {\n            int val = JS_VALUE_GET_INT(res);\n            cmp = (val > 0) - (val < 0);\n        } else {\n            double val;\n            if (JS_ToFloat64Free(ctx, &val, res) < 0) {\n                psc->exception = 1;\n                goto done;\n            } else {\n                cmp = (val > 0) - (val < 0);\n            }\n        }\n        if (cmp == 0) {\n            /* make sort stable: compare array offsets */\n            cmp = (a_idx > b_idx) - (a_idx < b_idx);\n        }\n        if (validate_typed_array(ctx, psc->arr) < 0) {\n            psc->exception = 1;\n        }\n    done:\n        JS_FreeValue(ctx, argv[0]);\n        JS_FreeValue(ctx, argv[1]);\n    }\n    return cmp;\n}\n\nstatic JSValue js_typed_array_sort(JSContext *ctx, JSValueConst this_val,\n                                   int argc, JSValueConst *argv)\n{\n    JSObject *p;\n    int len;\n    size_t elt_size;\n    struct TA_sort_context tsc;\n    void *array_ptr;\n    int (*cmpfun)(const void *a, const void *b, void *opaque);\n\n    tsc.ctx = ctx;\n    tsc.exception = 0;\n    tsc.arr = this_val;\n    tsc.cmp = argv[0];\n\n    len = js_typed_array_get_length_internal(ctx, this_val);\n    if (len < 0)\n        return JS_EXCEPTION;\n    if (!JS_IsUndefined(tsc.cmp) && check_function(ctx, tsc.cmp))\n        return JS_EXCEPTION;\n\n    if (len > 1) {\n        p = JS_VALUE_GET_OBJ(this_val);\n        switch (p->class_id) {\n        case JS_CLASS_INT8_ARRAY:\n            tsc.getfun = js_TA_get_int8;\n            cmpfun = js_TA_cmp_int8;\n            break;\n        case JS_CLASS_UINT8C_ARRAY:\n        case JS_CLASS_UINT8_ARRAY:\n            tsc.getfun = js_TA_get_uint8;\n            cmpfun = js_TA_cmp_uint8;\n            break;\n        case JS_CLASS_INT16_ARRAY:\n            tsc.getfun = js_TA_get_int16;\n            cmpfun = js_TA_cmp_int16;\n            break;\n        case JS_CLASS_UINT16_ARRAY:\n            tsc.getfun = js_TA_get_uint16;\n            cmpfun = js_TA_cmp_uint16;\n            break;\n        case JS_CLASS_INT32_ARRAY:\n            tsc.getfun = js_TA_get_int32;\n            cmpfun = js_TA_cmp_int32;\n            break;\n        case JS_CLASS_UINT32_ARRAY:\n            tsc.getfun = js_TA_get_uint32;\n            cmpfun = js_TA_cmp_uint32;\n            break;\n#ifdef CONFIG_BIGNUM\n        case JS_CLASS_BIG_INT64_ARRAY:\n            tsc.getfun = js_TA_get_int64;\n            cmpfun = js_TA_cmp_int64;\n            break;\n        case JS_CLASS_BIG_UINT64_ARRAY:\n            tsc.getfun = js_TA_get_uint64;\n            cmpfun = js_TA_cmp_uint64;\n            break;\n#endif\n        case JS_CLASS_FLOAT32_ARRAY:\n            tsc.getfun = js_TA_get_float32;\n            cmpfun = js_TA_cmp_float32;\n            break;\n        case JS_CLASS_FLOAT64_ARRAY:\n            tsc.getfun = js_TA_get_float64;\n            cmpfun = js_TA_cmp_float64;\n            break;\n        default:\n            abort();\n        }\n        array_ptr = p->u.array.u.ptr;\n        elt_size = 1 << typed_array_size_log2(p->class_id);\n        if (!JS_IsUndefined(tsc.cmp)) {\n            uint32_t *array_idx;\n            void *array_tmp;\n            size_t i, j;\n            \n            /* XXX: a stable sort would use less memory */\n            array_idx = js_malloc(ctx, len * sizeof(array_idx[0]));\n            if (!array_idx)\n                return JS_EXCEPTION;\n            for(i = 0; i < len; i++)\n                array_idx[i] = i;\n            tsc.array_ptr = array_ptr;\n            tsc.elt_size = elt_size;\n            rqsort(array_idx, len, sizeof(array_idx[0]),\n                   js_TA_cmp_generic, &tsc);\n            if (tsc.exception)\n                goto fail;\n            array_tmp = js_malloc(ctx, len * elt_size);\n            if (!array_tmp) {\n            fail:\n                js_free(ctx, array_idx);\n                return JS_EXCEPTION;\n            }\n            memcpy(array_tmp, array_ptr, len * elt_size);\n            switch(elt_size) {\n            case 1:\n                for(i = 0; i < len; i++) {\n                    j = array_idx[i];\n                    ((uint8_t *)array_ptr)[i] = ((uint8_t *)array_tmp)[j];\n                }\n                break;\n            case 2:\n                for(i = 0; i < len; i++) {\n                    j = array_idx[i];\n                    ((uint16_t *)array_ptr)[i] = ((uint16_t *)array_tmp)[j];\n                }\n                break;\n            case 4:\n                for(i = 0; i < len; i++) {\n                    j = array_idx[i];\n                    ((uint32_t *)array_ptr)[i] = ((uint32_t *)array_tmp)[j];\n                }\n                break;\n            case 8:\n                for(i = 0; i < len; i++) {\n                    j = array_idx[i];\n                    ((uint64_t *)array_ptr)[i] = ((uint64_t *)array_tmp)[j];\n                }\n                break;\n            default:\n                abort();\n            }\n            js_free(ctx, array_tmp);\n            js_free(ctx, array_idx);\n        } else {\n            rqsort(array_ptr, len, elt_size, cmpfun, &tsc);\n            if (tsc.exception)\n                return JS_EXCEPTION;\n        }\n    }\n    return JS_DupValue(ctx, this_val);\n}\n\nstatic const JSCFunctionListEntry js_typed_array_base_funcs[] = {\n    JS_CFUNC_DEF(\"from\", 1, js_typed_array_from ),\n    JS_CFUNC_DEF(\"of\", 0, js_typed_array_of ),\n    JS_CGETSET_DEF(\"[Symbol.species]\", js_get_this, NULL ),\n    //JS_CFUNC_DEF(\"__getLength\", 2, js_typed_array___getLength ),\n    //JS_CFUNC_DEF(\"__create\", 2, js_typed_array___create ),\n    //JS_CFUNC_DEF(\"__speciesCreate\", 2, js_typed_array___speciesCreate ),\n};\n\nstatic const JSCFunctionListEntry js_typed_array_base_proto_funcs[] = {\n    JS_CGETSET_DEF(\"length\", js_typed_array_get_length, NULL ),\n    JS_CGETSET_MAGIC_DEF(\"buffer\", js_typed_array_get_buffer, NULL, 0 ),\n    JS_CGETSET_MAGIC_DEF(\"byteLength\", js_typed_array_get_byteLength, NULL, 0 ),\n    JS_CGETSET_MAGIC_DEF(\"byteOffset\", js_typed_array_get_byteOffset, NULL, 0 ),\n    JS_CFUNC_DEF(\"set\", 1, js_typed_array_set ),\n    JS_CFUNC_MAGIC_DEF(\"values\", 0, js_create_typed_array_iterator, JS_ITERATOR_KIND_VALUE ),\n    JS_ALIAS_DEF(\"[Symbol.iterator]\", \"values\" ),\n    JS_CFUNC_MAGIC_DEF(\"keys\", 0, js_create_typed_array_iterator, JS_ITERATOR_KIND_KEY ),\n    JS_CFUNC_MAGIC_DEF(\"entries\", 0, js_create_typed_array_iterator, JS_ITERATOR_KIND_KEY_AND_VALUE ),\n    JS_CGETSET_DEF(\"[Symbol.toStringTag]\", js_typed_array_get_toStringTag, NULL ),\n    JS_CFUNC_DEF(\"copyWithin\", 2, js_typed_array_copyWithin ),\n    JS_CFUNC_MAGIC_DEF(\"every\", 1, js_array_every, special_every | special_TA ),\n    JS_CFUNC_MAGIC_DEF(\"some\", 1, js_array_every, special_some | special_TA ),\n    JS_CFUNC_MAGIC_DEF(\"forEach\", 1, js_array_every, special_forEach | special_TA ),\n    JS_CFUNC_MAGIC_DEF(\"map\", 1, js_array_every, special_map | special_TA ),\n    JS_CFUNC_MAGIC_DEF(\"filter\", 1, js_array_every, special_filter | special_TA ),\n    JS_CFUNC_MAGIC_DEF(\"reduce\", 1, js_array_reduce, special_reduce | special_TA ),\n    JS_CFUNC_MAGIC_DEF(\"reduceRight\", 1, js_array_reduce, special_reduceRight | special_TA ),\n    JS_CFUNC_DEF(\"fill\", 1, js_typed_array_fill ),\n    JS_CFUNC_MAGIC_DEF(\"find\", 1, js_typed_array_find, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"findIndex\", 1, js_typed_array_find, 1 ),\n    JS_CFUNC_DEF(\"reverse\", 0, js_typed_array_reverse ),\n    JS_CFUNC_DEF(\"slice\", 2, js_typed_array_slice ),\n    JS_CFUNC_DEF(\"subarray\", 2, js_typed_array_subarray ),\n    JS_CFUNC_DEF(\"sort\", 1, js_typed_array_sort ),\n    JS_CFUNC_MAGIC_DEF(\"join\", 1, js_typed_array_join, 0 ),\n    JS_CFUNC_MAGIC_DEF(\"toLocaleString\", 0, js_typed_array_join, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"indexOf\", 1, js_typed_array_indexOf, special_indexOf ),\n    JS_CFUNC_MAGIC_DEF(\"lastIndexOf\", 1, js_typed_array_indexOf, special_lastIndexOf ),\n    JS_CFUNC_MAGIC_DEF(\"includes\", 1, js_typed_array_indexOf, special_includes ),\n    //JS_ALIAS_BASE_DEF(\"toString\", \"toString\", 2 /* Array.prototype. */), @@@\n};\n\nstatic JSValue js_typed_array_base_constructor(JSContext *ctx,\n                                               JSValueConst this_val,\n                                               int argc, JSValueConst *argv)\n{\n    return JS_ThrowTypeError(ctx, \"cannot be called\");\n}\n\n/* 'obj' must be an allocated typed array object */\nstatic int typed_array_init(JSContext *ctx, JSValueConst obj,\n                            JSValue buffer, uint64_t offset, uint64_t len)\n{\n    JSTypedArray *ta;\n    JSObject *p, *pbuffer;\n    JSArrayBuffer *abuf;\n    int size_log2;\n\n    p = JS_VALUE_GET_OBJ(obj);\n    size_log2 = typed_array_size_log2(p->class_id);\n    ta = js_malloc(ctx, sizeof(*ta));\n    if (!ta) {\n        JS_FreeValue(ctx, buffer);\n        return -1;\n    }\n    pbuffer = JS_VALUE_GET_OBJ(buffer);\n    abuf = pbuffer->u.array_buffer;\n    ta->obj = p;\n    ta->buffer = pbuffer;\n    ta->offset = offset;\n    ta->length = len << size_log2;\n    list_add_tail(&ta->link, &abuf->array_list);\n    p->u.typed_array = ta;\n    p->u.array.count = len;\n    p->u.array.u.ptr = abuf->data + offset;\n    return 0;\n}\n\n\nstatic JSValue js_array_from_iterator(JSContext *ctx, uint32_t *plen,\n                                      JSValueConst obj, JSValueConst method)\n{\n    JSValue arr, iter, next_method = JS_UNDEFINED, val;\n    BOOL done;\n    uint32_t k;\n\n    *plen = 0;\n    arr = JS_NewArray(ctx);\n    if (JS_IsException(arr))\n        return arr;\n    iter = JS_GetIterator2(ctx, obj, method);\n    if (JS_IsException(iter))\n        goto fail;\n    next_method = JS_GetProperty(ctx, iter, JS_ATOM_next);\n    if (JS_IsException(next_method))\n        goto fail;\n    k = 0;\n    for(;;) {\n        val = JS_IteratorNext(ctx, iter, next_method, 0, NULL, &done);\n        if (JS_IsException(val))\n            goto fail;\n        if (done) {\n            JS_FreeValue(ctx, val);\n            break;\n        }\n        if (JS_CreateDataPropertyUint32(ctx, arr, k, val, JS_PROP_THROW) < 0)\n            goto fail;\n        k++;\n    }\n    JS_FreeValue(ctx, next_method);\n    JS_FreeValue(ctx, iter);\n    *plen = k;\n    return arr;\n fail:\n    JS_FreeValue(ctx, next_method);\n    JS_FreeValue(ctx, iter);\n    JS_FreeValue(ctx, arr);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_typed_array_constructor_obj(JSContext *ctx,\n                                              JSValueConst new_target,\n                                              JSValueConst obj,\n                                              int classid)\n{\n    JSValue iter, ret, arr = JS_UNDEFINED, val, buffer;\n    uint32_t i;\n    int size_log2;\n    int64_t len;\n\n    size_log2 = typed_array_size_log2(classid);\n    ret = js_create_from_ctor(ctx, new_target, classid);\n    if (JS_IsException(ret))\n        return JS_EXCEPTION;\n\n    iter = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_iterator);\n    if (JS_IsException(iter))\n        goto fail;\n    if (!JS_IsUndefined(iter) && !JS_IsNull(iter)) {\n        uint32_t len1;\n        arr = js_array_from_iterator(ctx, &len1, obj, iter);\n        JS_FreeValue(ctx, iter);\n        if (JS_IsException(arr))\n            goto fail;\n        len = len1;\n    } else {\n        if (js_get_length64(ctx, &len, obj))\n            goto fail;\n        arr = JS_DupValue(ctx, obj);\n    }\n\n    buffer = js_array_buffer_constructor1(ctx, JS_UNDEFINED,\n                                          len << size_log2);\n    if (JS_IsException(buffer))\n        goto fail;\n    if (typed_array_init(ctx, ret, buffer, 0, len))\n        goto fail;\n\n    for(i = 0; i < len; i++) {\n        val = JS_GetPropertyUint32(ctx, arr, i);\n        if (JS_IsException(val))\n            goto fail;\n        if (JS_SetPropertyUint32(ctx, ret, i, val) < 0)\n            goto fail;\n    }\n    JS_FreeValue(ctx, arr);\n    return ret;\n fail:\n    JS_FreeValue(ctx, arr);\n    JS_FreeValue(ctx, ret);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_typed_array_constructor_ta(JSContext *ctx,\n                                             JSValueConst new_target,\n                                             JSValueConst src_obj,\n                                             int classid)\n{\n    JSObject *p, *src_buffer;\n    JSTypedArray *ta;\n    JSValue ctor, obj, buffer;\n    uint32_t len, i;\n    int size_log2;\n    JSArrayBuffer *src_abuf, *abuf;\n\n    obj = js_create_from_ctor(ctx, new_target, classid);\n    if (JS_IsException(obj))\n        return obj;\n    p = JS_VALUE_GET_OBJ(src_obj);\n    if (typed_array_is_detached(ctx, p)) {\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        goto fail;\n    }\n    ta = p->u.typed_array;\n    len = p->u.array.count;\n    src_buffer = ta->buffer;\n    src_abuf = src_buffer->u.array_buffer;\n    if (!src_abuf->shared) {\n        ctor = JS_SpeciesConstructor(ctx, JS_MKPTR(JS_TAG_OBJECT, src_buffer),\n                                     JS_UNDEFINED);\n        if (JS_IsException(ctor))\n            goto fail;\n    } else {\n        /* force ArrayBuffer default constructor */\n        ctor = JS_UNDEFINED;\n    }\n    size_log2 = typed_array_size_log2(classid);\n    buffer = js_array_buffer_constructor1(ctx, ctor,\n                                          (uint64_t)len << size_log2);\n    JS_FreeValue(ctx, ctor);\n    if (JS_IsException(buffer))\n        goto fail;\n    /* necessary because it could have been detached */\n    if (typed_array_is_detached(ctx, p)) {\n        JS_FreeValue(ctx, buffer);\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        goto fail;\n    }\n    abuf = JS_GetOpaque(buffer, JS_CLASS_ARRAY_BUFFER);\n    if (typed_array_init(ctx, obj, buffer, 0, len))\n        goto fail;\n    if (p->class_id == classid) {\n        /* same type: copy the content */\n        memcpy(abuf->data, src_abuf->data + ta->offset, abuf->byte_length);\n    } else {\n        for(i = 0; i < len; i++) {\n            JSValue val;\n            val = JS_GetPropertyUint32(ctx, src_obj, i);\n            if (JS_IsException(val))\n                goto fail;\n            if (JS_SetPropertyUint32(ctx, obj, i, val) < 0)\n                goto fail;\n        }\n    }\n    return obj;\n fail:\n    JS_FreeValue(ctx, obj);\n    return JS_EXCEPTION;\n}\n\nstatic JSValue js_typed_array_constructor(JSContext *ctx,\n                                          JSValueConst new_target,\n                                          int argc, JSValueConst *argv,\n                                          int classid)\n{\n    JSValue buffer, obj;\n    JSArrayBuffer *abuf;\n    int size_log2;\n    uint64_t len, offset;\n\n    size_log2 = typed_array_size_log2(classid);\n    if (JS_VALUE_GET_TAG(argv[0]) != JS_TAG_OBJECT) {\n        if (JS_ToIndex(ctx, &len, argv[0]))\n            return JS_EXCEPTION;\n        buffer = js_array_buffer_constructor1(ctx, JS_UNDEFINED,\n                                              len << size_log2);\n        if (JS_IsException(buffer))\n            return JS_EXCEPTION;\n        offset = 0;\n    } else {\n        JSObject *p = JS_VALUE_GET_OBJ(argv[0]);\n        if (p->class_id == JS_CLASS_ARRAY_BUFFER ||\n            p->class_id == JS_CLASS_SHARED_ARRAY_BUFFER) {\n            abuf = p->u.array_buffer;\n            if (JS_ToIndex(ctx, &offset, argv[1]))\n                return JS_EXCEPTION;\n            if (abuf->detached)\n                return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n            if ((offset & ((1 << size_log2) - 1)) != 0 ||\n                offset > abuf->byte_length)\n                return JS_ThrowRangeError(ctx, \"invalid offset\");\n            if (JS_IsUndefined(argv[2])) {\n                if ((abuf->byte_length & ((1 << size_log2) - 1)) != 0)\n                    goto invalid_length;\n                len = (abuf->byte_length - offset) >> size_log2;\n            } else {\n                if (JS_ToIndex(ctx, &len, argv[2]))\n                    return JS_EXCEPTION;\n                if (abuf->detached)\n                    return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n                if ((offset + (len << size_log2)) > abuf->byte_length) {\n                invalid_length:\n                    return JS_ThrowRangeError(ctx, \"invalid length\");\n                }\n            }\n            buffer = JS_DupValue(ctx, argv[0]);\n        } else {\n            if (p->class_id >= JS_CLASS_UINT8C_ARRAY &&\n                p->class_id <= JS_CLASS_FLOAT64_ARRAY) {\n                return js_typed_array_constructor_ta(ctx, new_target, argv[0], classid);\n            } else {\n                return js_typed_array_constructor_obj(ctx, new_target, argv[0], classid);\n            }\n        }\n    }\n\n    obj = js_create_from_ctor(ctx, new_target, classid);\n    if (JS_IsException(obj)) {\n        JS_FreeValue(ctx, buffer);\n        return JS_EXCEPTION;\n    }\n    if (typed_array_init(ctx, obj, buffer, offset, len)) {\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    return obj;\n}\n\nstatic void js_typed_array_finalizer(JSRuntime *rt, JSValue val)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSTypedArray *ta = p->u.typed_array;\n    if (ta) {\n        /* during the GC the finalizers are called in an arbitrary\n           order so the ArrayBuffer finalizer may have been called */\n        if (JS_IsLiveObject(rt, JS_MKPTR(JS_TAG_OBJECT, ta->buffer))) {\n            list_del(&ta->link);\n        }\n        JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, ta->buffer));\n        js_free_rt(rt, ta);\n    }\n}\n\nstatic void js_typed_array_mark(JSRuntime *rt, JSValueConst val,\n                                JS_MarkFunc *mark_func)\n{\n    JSObject *p = JS_VALUE_GET_OBJ(val);\n    JSTypedArray *ta = p->u.typed_array;\n    if (ta) {\n        JS_MarkValue(rt, JS_MKPTR(JS_TAG_OBJECT, ta->buffer), mark_func);\n    }\n}\n\nstatic JSValue js_dataview_constructor(JSContext *ctx,\n                                       JSValueConst new_target,\n                                       int argc, JSValueConst *argv)\n{\n    JSArrayBuffer *abuf;\n    uint64_t offset;\n    uint32_t len;\n    JSValueConst buffer;\n    JSValue obj;\n    JSTypedArray *ta;\n    JSObject *p;\n\n    buffer = argv[0];\n    abuf = js_get_array_buffer(ctx, buffer);\n    if (!abuf)\n        return JS_EXCEPTION;\n    offset = 0;\n    if (argc > 1) {\n        if (JS_ToIndex(ctx, &offset, argv[1]))\n            return JS_EXCEPTION;\n    }\n    if (abuf->detached)\n        return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n    if (offset > abuf->byte_length)\n        return JS_ThrowRangeError(ctx, \"invalid byteOffset\");\n    len = abuf->byte_length - offset;\n    if (argc > 2 && !JS_IsUndefined(argv[2])) {\n        uint64_t l;\n        if (JS_ToIndex(ctx, &l, argv[2]))\n            return JS_EXCEPTION;\n        if (l > len)\n            return JS_ThrowRangeError(ctx, \"invalid byteLength\");\n        len = l;\n    }\n\n    obj = js_create_from_ctor(ctx, new_target, JS_CLASS_DATAVIEW);\n    if (JS_IsException(obj))\n        return JS_EXCEPTION;\n    if (abuf->detached) {\n        /* could have been detached in js_create_from_ctor() */\n        JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        goto fail;\n    }\n    ta = js_malloc(ctx, sizeof(*ta));\n    if (!ta) {\n    fail:\n        JS_FreeValue(ctx, obj);\n        return JS_EXCEPTION;\n    }\n    p = JS_VALUE_GET_OBJ(obj);\n    ta->obj = p;\n    ta->buffer = JS_VALUE_GET_OBJ(JS_DupValue(ctx, buffer));\n    ta->offset = offset;\n    ta->length = len;\n    list_add_tail(&ta->link, &abuf->array_list);\n    p->u.typed_array = ta;\n    return obj;\n}\n\nstatic JSValue js_dataview_getValue(JSContext *ctx,\n                                    JSValueConst this_obj,\n                                    int argc, JSValueConst *argv, int class_id)\n{\n    JSTypedArray *ta;\n    JSArrayBuffer *abuf;\n    int is_swap, size;\n    uint8_t *ptr;\n    uint32_t v;\n    uint64_t pos;\n\n    ta = JS_GetOpaque2(ctx, this_obj, JS_CLASS_DATAVIEW);\n    if (!ta)\n        return JS_EXCEPTION;\n    size = 1 << typed_array_size_log2(class_id);\n    if (JS_ToIndex(ctx, &pos, argv[0]))\n        return JS_EXCEPTION;\n    is_swap = FALSE;\n    if (argc > 1)\n        is_swap = JS_ToBool(ctx, argv[1]);\n#ifndef WORDS_BIGENDIAN\n    is_swap ^= 1;\n#endif\n    abuf = ta->buffer->u.array_buffer;\n    if (abuf->detached)\n        return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n    if ((pos + size) > ta->length)\n        return JS_ThrowRangeError(ctx, \"out of bound\");\n    ptr = abuf->data + ta->offset + pos;\n\n    switch(class_id) {\n    case JS_CLASS_INT8_ARRAY:\n        return JS_NewInt32(ctx, *(int8_t *)ptr);\n    case JS_CLASS_UINT8_ARRAY:\n        return JS_NewInt32(ctx, *(uint8_t *)ptr);\n    case JS_CLASS_INT16_ARRAY:\n        v = get_u16(ptr);\n        if (is_swap)\n            v = bswap16(v);\n        return JS_NewInt32(ctx, (int16_t)v);\n    case JS_CLASS_UINT16_ARRAY:\n        v = get_u16(ptr);\n        if (is_swap)\n            v = bswap16(v);\n        return JS_NewInt32(ctx, v);\n    case JS_CLASS_INT32_ARRAY:\n        v = get_u32(ptr);\n        if (is_swap)\n            v = bswap32(v);\n        return JS_NewInt32(ctx, v);\n    case JS_CLASS_UINT32_ARRAY:\n        v = get_u32(ptr);\n        if (is_swap)\n            v = bswap32(v);\n        return JS_NewUint32(ctx, v);\n#ifdef CONFIG_BIGNUM\n    case JS_CLASS_BIG_INT64_ARRAY:\n        {\n            uint64_t v;\n            v = get_u64(ptr);\n            if (is_swap)\n                v = bswap64(v);\n            return JS_NewBigInt64(ctx, v);\n        }\n        break;\n    case JS_CLASS_BIG_UINT64_ARRAY:\n        {\n            uint64_t v;\n            v = get_u64(ptr);\n            if (is_swap)\n                v = bswap64(v);\n            return JS_NewBigUint64(ctx, v);\n        }\n        break;\n#endif\n    case JS_CLASS_FLOAT32_ARRAY:\n        {\n            union {\n                float f;\n                uint32_t i;\n            } u;\n            v = get_u32(ptr);\n            if (is_swap)\n                v = bswap32(v);\n            u.i = v;\n            return __JS_NewFloat64(ctx, u.f);\n        }\n    case JS_CLASS_FLOAT64_ARRAY:\n        {\n            union {\n                double f;\n                uint64_t i;\n            } u;\n            u.i = get_u64(ptr);\n            if (is_swap)\n                u.i = bswap64(u.i);\n            return __JS_NewFloat64(ctx, u.f);\n        }\n    default:\n        abort();\n    }\n}\n\nstatic JSValue js_dataview_setValue(JSContext *ctx,\n                                    JSValueConst this_obj,\n                                    int argc, JSValueConst *argv, int class_id)\n{\n    JSTypedArray *ta;\n    JSArrayBuffer *abuf;\n    int is_swap, size;\n    uint8_t *ptr;\n    uint64_t v64;\n    uint32_t v;\n    uint64_t pos;\n    JSValueConst val;\n\n    ta = JS_GetOpaque2(ctx, this_obj, JS_CLASS_DATAVIEW);\n    if (!ta)\n        return JS_EXCEPTION;\n    size = 1 << typed_array_size_log2(class_id);\n    if (JS_ToIndex(ctx, &pos, argv[0]))\n        return JS_EXCEPTION;\n    val = argv[1];\n    v = 0; /* avoid warning */\n    v64 = 0; /* avoid warning */\n    if (class_id <= JS_CLASS_UINT32_ARRAY) {\n        if (JS_ToUint32(ctx, &v, val))\n            return JS_EXCEPTION;\n    } else\n#ifdef CONFIG_BIGNUM\n    if (class_id <= JS_CLASS_BIG_UINT64_ARRAY) {\n        if (JS_ToBigInt64(ctx, (int64_t *)&v64, val))\n            return JS_EXCEPTION;\n    } else\n#endif\n    {\n        double d;\n        if (JS_ToFloat64(ctx, &d, val))\n            return JS_EXCEPTION;\n        if (class_id == JS_CLASS_FLOAT32_ARRAY) {\n            union {\n                float f;\n                uint32_t i;\n            } u;\n            u.f = d;\n            v = u.i;\n        } else {\n            JSFloat64Union u;\n            u.d = d;\n            v64 = u.u64;\n        }\n    }\n    is_swap = FALSE;\n    if (argc > 2)\n        is_swap = JS_ToBool(ctx, argv[2]);\n#ifndef WORDS_BIGENDIAN\n    is_swap ^= 1;\n#endif\n    abuf = ta->buffer->u.array_buffer;\n    if (abuf->detached)\n        return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n    if ((pos + size) > ta->length)\n        return JS_ThrowRangeError(ctx, \"out of bound\");\n    ptr = abuf->data + ta->offset + pos;\n\n    switch(class_id) {\n    case JS_CLASS_INT8_ARRAY:\n    case JS_CLASS_UINT8_ARRAY:\n        *ptr = v;\n        break;\n    case JS_CLASS_INT16_ARRAY:\n    case JS_CLASS_UINT16_ARRAY:\n        if (is_swap)\n            v = bswap16(v);\n        put_u16(ptr, v);\n        break;\n    case JS_CLASS_INT32_ARRAY:\n    case JS_CLASS_UINT32_ARRAY:\n    case JS_CLASS_FLOAT32_ARRAY:\n        if (is_swap)\n            v = bswap32(v);\n        put_u32(ptr, v);\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_CLASS_BIG_INT64_ARRAY:\n    case JS_CLASS_BIG_UINT64_ARRAY:\n#endif\n    case JS_CLASS_FLOAT64_ARRAY:\n        if (is_swap)\n            v64 = bswap64(v64);\n        put_u64(ptr, v64);\n        break;\n    default:\n        abort();\n    }\n    return JS_UNDEFINED;\n}\n\nstatic const JSCFunctionListEntry js_dataview_proto_funcs[] = {\n    JS_CGETSET_MAGIC_DEF(\"buffer\", js_typed_array_get_buffer, NULL, 1 ),\n    JS_CGETSET_MAGIC_DEF(\"byteLength\", js_typed_array_get_byteLength, NULL, 1 ),\n    JS_CGETSET_MAGIC_DEF(\"byteOffset\", js_typed_array_get_byteOffset, NULL, 1 ),\n    JS_CFUNC_MAGIC_DEF(\"getInt8\", 1, js_dataview_getValue, JS_CLASS_INT8_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"getUint8\", 1, js_dataview_getValue, JS_CLASS_UINT8_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"getInt16\", 1, js_dataview_getValue, JS_CLASS_INT16_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"getUint16\", 1, js_dataview_getValue, JS_CLASS_UINT16_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"getInt32\", 1, js_dataview_getValue, JS_CLASS_INT32_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"getUint32\", 1, js_dataview_getValue, JS_CLASS_UINT32_ARRAY ),\n#ifdef CONFIG_BIGNUM\n    JS_CFUNC_MAGIC_DEF(\"getBigInt64\", 1, js_dataview_getValue, JS_CLASS_BIG_INT64_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"getBigUint64\", 1, js_dataview_getValue, JS_CLASS_BIG_UINT64_ARRAY ),\n#endif\n    JS_CFUNC_MAGIC_DEF(\"getFloat32\", 1, js_dataview_getValue, JS_CLASS_FLOAT32_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"getFloat64\", 1, js_dataview_getValue, JS_CLASS_FLOAT64_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"setInt8\", 2, js_dataview_setValue, JS_CLASS_INT8_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"setUint8\", 2, js_dataview_setValue, JS_CLASS_UINT8_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"setInt16\", 2, js_dataview_setValue, JS_CLASS_INT16_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"setUint16\", 2, js_dataview_setValue, JS_CLASS_UINT16_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"setInt32\", 2, js_dataview_setValue, JS_CLASS_INT32_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"setUint32\", 2, js_dataview_setValue, JS_CLASS_UINT32_ARRAY ),\n#ifdef CONFIG_BIGNUM\n    JS_CFUNC_MAGIC_DEF(\"setBigInt64\", 2, js_dataview_setValue, JS_CLASS_BIG_INT64_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"setBigUint64\", 2, js_dataview_setValue, JS_CLASS_BIG_UINT64_ARRAY ),\n#endif\n    JS_CFUNC_MAGIC_DEF(\"setFloat32\", 2, js_dataview_setValue, JS_CLASS_FLOAT32_ARRAY ),\n    JS_CFUNC_MAGIC_DEF(\"setFloat64\", 2, js_dataview_setValue, JS_CLASS_FLOAT64_ARRAY ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"DataView\", JS_PROP_CONFIGURABLE ),\n};\n\n/* Atomics */\n#ifdef CONFIG_ATOMICS\n\ntypedef enum AtomicsOpEnum {\n    ATOMICS_OP_ADD,\n    ATOMICS_OP_AND,\n    ATOMICS_OP_OR,\n    ATOMICS_OP_SUB,\n    ATOMICS_OP_XOR,\n    ATOMICS_OP_EXCHANGE,\n    ATOMICS_OP_COMPARE_EXCHANGE,\n    ATOMICS_OP_LOAD,\n} AtomicsOpEnum;\n\nstatic void *js_atomics_get_ptr(JSContext *ctx,\n                                JSArrayBuffer **pabuf,\n                                int *psize_log2, JSClassID *pclass_id,\n                                JSValueConst obj, JSValueConst idx_val,\n                                int is_waitable)\n{\n    JSObject *p;\n    JSTypedArray *ta;\n    JSArrayBuffer *abuf;\n    void *ptr;\n    uint64_t idx;\n    BOOL err;\n    int size_log2;\n\n    if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n        goto fail;\n    p = JS_VALUE_GET_OBJ(obj);\n#ifdef CONFIG_BIGNUM\n    if (is_waitable)\n        err = (p->class_id != JS_CLASS_INT32_ARRAY &&\n               p->class_id != JS_CLASS_BIG_INT64_ARRAY);\n    else\n        err = !(p->class_id >= JS_CLASS_INT8_ARRAY &&\n                p->class_id <= JS_CLASS_BIG_UINT64_ARRAY);\n#else\n    if (is_waitable)\n        err = (p->class_id != JS_CLASS_INT32_ARRAY);\n    else\n        err = !(p->class_id >= JS_CLASS_INT8_ARRAY &&\n                p->class_id <= JS_CLASS_UINT32_ARRAY);\n#endif\n    if (err) {\n    fail:\n        JS_ThrowTypeError(ctx, \"integer TypedArray expected\");\n        return NULL;\n    }\n    ta = p->u.typed_array;\n    abuf = ta->buffer->u.array_buffer;\n    if (!abuf->shared) {\n        if (is_waitable == 2) {\n            JS_ThrowTypeError(ctx, \"not a SharedArrayBuffer TypedArray\");\n            return NULL;\n        }\n        if (abuf->detached) {\n            JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n            return NULL;\n        }\n    }\n    if (JS_ToIndex(ctx, &idx, idx_val)) {\n        return NULL;\n    }\n    /* if the array buffer is detached, p->u.array.count = 0 */\n    if (idx >= p->u.array.count) {\n        JS_ThrowRangeError(ctx, \"out-of-bound access\");\n        return NULL;\n    }\n    size_log2 = typed_array_size_log2(p->class_id);\n    ptr = p->u.array.u.uint8_ptr + ((uintptr_t)idx << size_log2);\n    if (pabuf)\n        *pabuf = abuf;\n    if (psize_log2)\n        *psize_log2 = size_log2;\n    if (pclass_id)\n        *pclass_id = p->class_id;\n    return ptr;\n}\n\nstatic JSValue js_atomics_op(JSContext *ctx,\n                             JSValueConst this_obj,\n                             int argc, JSValueConst *argv, int op)\n{\n    int size_log2;\n#ifdef CONFIG_BIGNUM\n    uint64_t v, a, rep_val;\n#else\n    uint32_t v, a, rep_val;\n#endif\n    void *ptr;\n    JSValue ret;\n    JSClassID class_id;\n    JSArrayBuffer *abuf;\n\n    ptr = js_atomics_get_ptr(ctx, &abuf, &size_log2, &class_id,\n                             argv[0], argv[1], 0);\n    if (!ptr)\n        return JS_EXCEPTION;\n    rep_val = 0;\n    if (op == ATOMICS_OP_LOAD) {\n        v = 0;\n    } else {\n#ifdef CONFIG_BIGNUM\n        if (size_log2 == 3) {\n            int64_t v64;\n            if (JS_ToBigInt64(ctx, &v64, argv[2]))\n                return JS_EXCEPTION;\n            v = v64;\n            if (op == ATOMICS_OP_COMPARE_EXCHANGE) {\n                if (JS_ToBigInt64(ctx, &v64, argv[3]))\n                    return JS_EXCEPTION;\n                rep_val = v64;\n            }\n        } else\n#endif\n        {\n                uint32_t v32;\n                if (JS_ToUint32(ctx, &v32, argv[2]))\n                    return JS_EXCEPTION;\n                v = v32;\n                if (op == ATOMICS_OP_COMPARE_EXCHANGE) {\n                    if (JS_ToUint32(ctx, &v32, argv[3]))\n                        return JS_EXCEPTION;\n                    rep_val = v32;\n                }\n        }\n        if (abuf->detached)\n            return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n   }\n\n   switch(op | (size_log2 << 3)) {\n            \n#ifdef CONFIG_BIGNUM\n#define OP(op_name, func_name)                          \\\n    case ATOMICS_OP_ ## op_name | (0 << 3):             \\\n       a = func_name((_Atomic(uint8_t) *)ptr, v);       \\\n       break;                                           \\\n    case ATOMICS_OP_ ## op_name | (1 << 3):             \\\n        a = func_name((_Atomic(uint16_t) *)ptr, v);     \\\n        break;                                          \\\n    case ATOMICS_OP_ ## op_name | (2 << 3):             \\\n        a = func_name((_Atomic(uint32_t) *)ptr, v);     \\\n        break;                                          \\\n    case ATOMICS_OP_ ## op_name | (3 << 3):             \\\n        a = func_name((_Atomic(uint64_t) *)ptr, v);     \\\n        break;\n#else\n#define OP(op_name, func_name)                          \\\n    case ATOMICS_OP_ ## op_name | (0 << 3):             \\\n       a = func_name((_Atomic(uint8_t) *)ptr, v);       \\\n       break;                                           \\\n    case ATOMICS_OP_ ## op_name | (1 << 3):             \\\n        a = func_name((_Atomic(uint16_t) *)ptr, v);     \\\n        break;                                          \\\n    case ATOMICS_OP_ ## op_name | (2 << 3):             \\\n        a = func_name((_Atomic(uint32_t) *)ptr, v);     \\\n        break;\n#endif\n        OP(ADD, atomic_fetch_add)\n        OP(AND, atomic_fetch_and)\n        OP(OR, atomic_fetch_or)\n        OP(SUB, atomic_fetch_sub)\n        OP(XOR, atomic_fetch_xor)\n        OP(EXCHANGE, atomic_exchange)\n#undef OP\n\n    case ATOMICS_OP_LOAD | (0 << 3):\n        a = atomic_load((_Atomic(uint8_t) *)ptr);\n        break;\n    case ATOMICS_OP_LOAD | (1 << 3):\n        a = atomic_load((_Atomic(uint16_t) *)ptr);\n        break;\n    case ATOMICS_OP_LOAD | (2 << 3):\n        a = atomic_load((_Atomic(uint32_t) *)ptr);\n        break;\n#ifdef CONFIG_BIGNUM\n    case ATOMICS_OP_LOAD | (3 << 3):\n        a = atomic_load((_Atomic(uint64_t) *)ptr);\n        break;\n#endif\n        \n    case ATOMICS_OP_COMPARE_EXCHANGE | (0 << 3):\n        {\n            uint8_t v1 = v;\n            atomic_compare_exchange_strong((_Atomic(uint8_t) *)ptr, &v1, rep_val);\n            a = v1;\n        }\n        break;\n    case ATOMICS_OP_COMPARE_EXCHANGE | (1 << 3):\n        {\n            uint16_t v1 = v;\n            atomic_compare_exchange_strong((_Atomic(uint16_t) *)ptr, &v1, rep_val);\n            a = v1;\n        }\n        break;\n    case ATOMICS_OP_COMPARE_EXCHANGE | (2 << 3):\n        {\n            uint32_t v1 = v;\n            atomic_compare_exchange_strong((_Atomic(uint32_t) *)ptr, &v1, rep_val);\n            a = v1;\n        }\n        break;\n#ifdef CONFIG_BIGNUM\n    case ATOMICS_OP_COMPARE_EXCHANGE | (3 << 3):\n        {\n            uint64_t v1 = v;\n            atomic_compare_exchange_strong((_Atomic(uint64_t) *)ptr, &v1, rep_val);\n            a = v1;\n        }\n        break;\n#endif\n    default:\n        abort();\n    }\n\n    switch(class_id) {\n    case JS_CLASS_INT8_ARRAY:\n        a = (int8_t)a;\n        goto done;\n    case JS_CLASS_UINT8_ARRAY:\n        a = (uint8_t)a;\n        goto done;\n    case JS_CLASS_INT16_ARRAY:\n        a = (int16_t)a;\n        goto done;\n    case JS_CLASS_UINT16_ARRAY:\n        a = (uint16_t)a;\n        goto done;\n    case JS_CLASS_INT32_ARRAY:\n    done:\n        ret = JS_NewInt32(ctx, a);\n        break;\n    case JS_CLASS_UINT32_ARRAY:\n        ret = JS_NewUint32(ctx, a);\n        break;\n#ifdef CONFIG_BIGNUM\n    case JS_CLASS_BIG_INT64_ARRAY:\n        ret = JS_NewBigInt64(ctx, a);\n        break;\n    case JS_CLASS_BIG_UINT64_ARRAY:\n        ret = JS_NewBigUint64(ctx, a);\n        break;\n#endif\n    default:\n        abort();\n    }\n    return ret;\n}\n\nstatic JSValue js_atomics_store(JSContext *ctx,\n                                JSValueConst this_obj,\n                                int argc, JSValueConst *argv)\n{\n    int size_log2;\n    void *ptr;\n    JSValue ret;\n    JSArrayBuffer *abuf;\n\n    ptr = js_atomics_get_ptr(ctx, &abuf, &size_log2, NULL,\n                             argv[0], argv[1], 0);\n    if (!ptr)\n        return JS_EXCEPTION;\n#ifdef CONFIG_BIGNUM\n    if (size_log2 == 3) {\n        int64_t v64;\n        ret = JS_ToBigIntValueFree(ctx, JS_DupValue(ctx, argv[2]));\n        if (JS_IsException(ret))\n            return ret;\n        if (JS_ToBigInt64(ctx, &v64, ret)) {\n            JS_FreeValue(ctx, ret);\n            return JS_EXCEPTION;\n        }\n        if (abuf->detached)\n            return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        atomic_store((_Atomic(uint64_t) *)ptr, v64);\n    } else\n#endif\n    {\n        uint32_t v;\n        /* XXX: spec, would be simpler to return the written value */\n        ret = JS_ToIntegerFree(ctx, JS_DupValue(ctx, argv[2]));\n        if (JS_IsException(ret))\n            return ret;\n        if (JS_ToUint32(ctx, &v, ret)) {\n            JS_FreeValue(ctx, ret);\n            return JS_EXCEPTION;\n        }\n        if (abuf->detached)\n            return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n        switch(size_log2) {\n        case 0:\n            atomic_store((_Atomic(uint8_t) *)ptr, v);\n            break;\n        case 1:\n            atomic_store((_Atomic(uint16_t) *)ptr, v);\n            break;\n        case 2:\n            atomic_store((_Atomic(uint32_t) *)ptr, v);\n            break;\n        default:\n            abort();\n        }\n    }\n    return ret;\n}\n\nstatic JSValue js_atomics_isLockFree(JSContext *ctx,\n                                     JSValueConst this_obj,\n                                     int argc, JSValueConst *argv)\n{\n    int v, ret;\n    if (JS_ToInt32Sat(ctx, &v, argv[0]))\n        return JS_EXCEPTION;\n    ret = (v == 1 || v == 2 || v == 4\n#ifdef CONFIG_BIGNUM\n           || v == 8\n#endif\n           );\n    return JS_NewBool(ctx, ret);\n}\n\ntypedef struct JSAtomicsWaiter {\n    struct list_head link;\n    BOOL linked;\n    pthread_cond_t cond;\n    int32_t *ptr;\n} JSAtomicsWaiter;\n\nstatic pthread_mutex_t js_atomics_mutex = PTHREAD_MUTEX_INITIALIZER;\nstatic struct list_head js_atomics_waiter_list =\n    LIST_HEAD_INIT(js_atomics_waiter_list);\n\nstatic JSValue js_atomics_wait(JSContext *ctx,\n                               JSValueConst this_obj,\n                               int argc, JSValueConst *argv)\n{\n    int64_t v;\n    int32_t v32;\n    void *ptr;\n    int64_t timeout;\n    struct timespec ts;\n    JSAtomicsWaiter waiter_s, *waiter;\n    int ret, size_log2, res;\n    double d;\n\n    ptr = js_atomics_get_ptr(ctx, NULL, &size_log2, NULL,\n                             argv[0], argv[1], 2);\n    if (!ptr)\n        return JS_EXCEPTION;\n#ifdef CONFIG_BIGNUM\n    if (size_log2 == 3) {\n        if (JS_ToBigInt64(ctx, &v, argv[2]))\n            return JS_EXCEPTION;\n    } else\n#endif\n    {        \n        if (JS_ToInt32(ctx, &v32, argv[2]))\n            return JS_EXCEPTION;\n        v = v32;\n    }\n    if (JS_ToFloat64(ctx, &d, argv[3]))\n        return JS_EXCEPTION;\n    if (isnan(d) || d > INT64_MAX)\n        timeout = INT64_MAX;\n    else if (d < 0)\n        timeout = 0;\n    else\n        timeout = (int64_t)d;\n    if (!ctx->rt->can_block)\n        return JS_ThrowTypeError(ctx, \"cannot block in this thread\");\n\n    /* XXX: inefficient if large number of waiters, should hash on\n       'ptr' value */\n    /* XXX: use Linux futexes when available ? */\n    pthread_mutex_lock(&js_atomics_mutex);\n    if (size_log2 == 3) {\n        res = *(int64_t *)ptr != v;\n    } else {\n        res = *(int32_t *)ptr != v;\n    }\n    if (res) {\n        pthread_mutex_unlock(&js_atomics_mutex);\n        return JS_AtomToString(ctx, JS_ATOM_not_equal);\n    }\n\n    waiter = &waiter_s;\n    waiter->ptr = ptr;\n    pthread_cond_init(&waiter->cond, NULL);\n    waiter->linked = TRUE;\n    list_add_tail(&waiter->link, &js_atomics_waiter_list);\n\n    if (timeout == INT64_MAX) {\n        pthread_cond_wait(&waiter->cond, &js_atomics_mutex);\n        ret = 0;\n    } else {\n        /* XXX: use clock monotonic */\n        clock_gettime(CLOCK_REALTIME, &ts);\n        ts.tv_sec += timeout / 1000;\n        ts.tv_nsec += (timeout % 1000) * 1000000;\n        if (ts.tv_nsec >= 1000000000) {\n            ts.tv_nsec -= 1000000000;\n            ts.tv_sec++;\n        }\n        ret = pthread_cond_timedwait(&waiter->cond, &js_atomics_mutex,\n                                     &ts);\n    }\n    if (waiter->linked)\n        list_del(&waiter->link);\n    pthread_mutex_unlock(&js_atomics_mutex);\n    pthread_cond_destroy(&waiter->cond);\n    if (ret == ETIMEDOUT) {\n        return JS_AtomToString(ctx, JS_ATOM_timed_out);\n    } else {\n        return JS_AtomToString(ctx, JS_ATOM_ok);\n    }\n}\n\nstatic JSValue js_atomics_notify(JSContext *ctx,\n                                 JSValueConst this_obj,\n                                 int argc, JSValueConst *argv)\n{\n    struct list_head *el, *el1, waiter_list;\n    int32_t count, n;\n    void *ptr;\n    JSAtomicsWaiter *waiter;\n    JSArrayBuffer *abuf;\n\n    ptr = js_atomics_get_ptr(ctx, &abuf, NULL, NULL, argv[0], argv[1], 1);\n    if (!ptr)\n        return JS_EXCEPTION;\n\n    if (JS_IsUndefined(argv[2])) {\n        count = INT32_MAX;\n    } else {\n        if (JS_ToInt32Clamp(ctx, &count, argv[2], 0, INT32_MAX, 0))\n            return JS_EXCEPTION;\n    }\n    if (abuf->detached)\n        return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n\n    n = 0;\n    if (abuf->shared && count > 0) {\n        pthread_mutex_lock(&js_atomics_mutex);\n        init_list_head(&waiter_list);\n        list_for_each_safe(el, el1, &js_atomics_waiter_list) {\n            waiter = list_entry(el, JSAtomicsWaiter, link);\n            if (waiter->ptr == ptr) {\n                list_del(&waiter->link);\n                waiter->linked = FALSE;\n                list_add_tail(&waiter->link, &waiter_list);\n                n++;\n                if (n >= count)\n                    break;\n            }\n        }\n        list_for_each(el, &waiter_list) {\n            waiter = list_entry(el, JSAtomicsWaiter, link);\n            pthread_cond_signal(&waiter->cond);\n        }\n        pthread_mutex_unlock(&js_atomics_mutex);\n    }\n    return JS_NewInt32(ctx, n);\n}\n\nstatic const JSCFunctionListEntry js_atomics_funcs[] = {\n    JS_CFUNC_MAGIC_DEF(\"add\", 3, js_atomics_op, ATOMICS_OP_ADD ),\n    JS_CFUNC_MAGIC_DEF(\"and\", 3, js_atomics_op, ATOMICS_OP_AND ),\n    JS_CFUNC_MAGIC_DEF(\"or\", 3, js_atomics_op, ATOMICS_OP_OR ),\n    JS_CFUNC_MAGIC_DEF(\"sub\", 3, js_atomics_op, ATOMICS_OP_SUB ),\n    JS_CFUNC_MAGIC_DEF(\"xor\", 3, js_atomics_op, ATOMICS_OP_XOR ),\n    JS_CFUNC_MAGIC_DEF(\"exchange\", 3, js_atomics_op, ATOMICS_OP_EXCHANGE ),\n    JS_CFUNC_MAGIC_DEF(\"compareExchange\", 4, js_atomics_op, ATOMICS_OP_COMPARE_EXCHANGE ),\n    JS_CFUNC_MAGIC_DEF(\"load\", 2, js_atomics_op, ATOMICS_OP_LOAD ),\n    JS_CFUNC_DEF(\"store\", 3, js_atomics_store ),\n    JS_CFUNC_DEF(\"isLockFree\", 1, js_atomics_isLockFree ),\n    JS_CFUNC_DEF(\"wait\", 4, js_atomics_wait ),\n    JS_CFUNC_DEF(\"notify\", 3, js_atomics_notify ),\n    JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Atomics\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_atomics_obj[] = {\n    JS_OBJECT_DEF(\"Atomics\", js_atomics_funcs, countof(js_atomics_funcs), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),\n};\n\nvoid JS_AddIntrinsicAtomics(JSContext *ctx)\n{\n    /* add Atomics as autoinit object */\n    JS_SetPropertyFunctionList(ctx, ctx->global_obj, js_atomics_obj, countof(js_atomics_obj));\n}\n\n#endif /* CONFIG_ATOMICS */\n\nvoid JS_AddIntrinsicTypedArrays(JSContext *ctx)\n{\n    JSValue typed_array_base_proto, typed_array_base_func;\n    JSValueConst array_buffer_func, shared_array_buffer_func;\n    int i;\n\n    ctx->class_proto[JS_CLASS_ARRAY_BUFFER] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ARRAY_BUFFER],\n                               js_array_buffer_proto_funcs,\n                               countof(js_array_buffer_proto_funcs));\n\n    array_buffer_func = JS_NewGlobalCConstructorOnly(ctx, \"ArrayBuffer\",\n                                                 js_array_buffer_constructor, 1,\n                                                 ctx->class_proto[JS_CLASS_ARRAY_BUFFER]);\n    JS_SetPropertyFunctionList(ctx, array_buffer_func,\n                               js_array_buffer_funcs,\n                               countof(js_array_buffer_funcs));\n\n    ctx->class_proto[JS_CLASS_SHARED_ARRAY_BUFFER] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_SHARED_ARRAY_BUFFER],\n                               js_shared_array_buffer_proto_funcs,\n                               countof(js_shared_array_buffer_proto_funcs));\n\n    shared_array_buffer_func = JS_NewGlobalCConstructorOnly(ctx, \"SharedArrayBuffer\",\n                                                 js_shared_array_buffer_constructor, 1,\n                                                 ctx->class_proto[JS_CLASS_SHARED_ARRAY_BUFFER]);\n    JS_SetPropertyFunctionList(ctx, shared_array_buffer_func,\n                               js_shared_array_buffer_funcs,\n                               countof(js_shared_array_buffer_funcs));\n\n    typed_array_base_proto = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, typed_array_base_proto,\n                               js_typed_array_base_proto_funcs,\n                               countof(js_typed_array_base_proto_funcs));\n\n    /* TypedArray.prototype.toString must be the same object as Array.prototype.toString */\n    JSValue obj = JS_GetProperty(ctx, ctx->class_proto[JS_CLASS_ARRAY], JS_ATOM_toString);\n    /* XXX: should use alias method in JSCFunctionListEntry */ //@@@\n    JS_DefinePropertyValue(ctx, typed_array_base_proto, JS_ATOM_toString, obj,\n                           JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n\n    typed_array_base_func = JS_NewCFunction(ctx, js_typed_array_base_constructor,\n                                            \"TypedArray\", 0);\n    JS_SetPropertyFunctionList(ctx, typed_array_base_func,\n                               js_typed_array_base_funcs,\n                               countof(js_typed_array_base_funcs));\n    JS_SetConstructor(ctx, typed_array_base_func, typed_array_base_proto);\n\n    for(i = JS_CLASS_UINT8C_ARRAY; i < JS_CLASS_UINT8C_ARRAY + JS_TYPED_ARRAY_COUNT; i++) {\n        JSValue func_obj;\n        char buf[ATOM_GET_STR_BUF_SIZE];\n        const char *name;\n\n        ctx->class_proto[i] = JS_NewObjectProto(ctx, typed_array_base_proto);\n        JS_DefinePropertyValueStr(ctx, ctx->class_proto[i],\n                                  \"BYTES_PER_ELEMENT\",\n                                  JS_NewInt32(ctx, 1 << typed_array_size_log2(i)),\n                                  0);\n        name = JS_AtomGetStr(ctx, buf, sizeof(buf),\n                             JS_ATOM_Uint8ClampedArray + i - JS_CLASS_UINT8C_ARRAY);\n        func_obj = JS_NewCFunction3(ctx, (JSCFunction *)js_typed_array_constructor,\n                                    name, 3, JS_CFUNC_constructor_magic, i,\n                                    typed_array_base_func);\n        JS_NewGlobalCConstructor2(ctx, func_obj, name, ctx->class_proto[i]);\n        JS_DefinePropertyValueStr(ctx, func_obj,\n                                  \"BYTES_PER_ELEMENT\",\n                                  JS_NewInt32(ctx, 1 << typed_array_size_log2(i)),\n                                  0);\n    }\n    JS_FreeValue(ctx, typed_array_base_proto);\n    JS_FreeValue(ctx, typed_array_base_func);\n\n    /* DataView */\n    ctx->class_proto[JS_CLASS_DATAVIEW] = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_DATAVIEW],\n                               js_dataview_proto_funcs,\n                               countof(js_dataview_proto_funcs));\n    JS_NewGlobalCConstructorOnly(ctx, \"DataView\",\n                                 js_dataview_constructor, 1,\n                                 ctx->class_proto[JS_CLASS_DATAVIEW]);\n    /* Atomics */\n#ifdef CONFIG_ATOMICS\n    JS_AddIntrinsicAtomics(ctx);\n#endif\n}\n\nstatic JSValue JSB_ThrowError2(JSContext *ctx, JSErrorEnum error_num,\n                              const char *buf, size_t buf_len, BOOL add_backtrace)\n{\n    JSValue obj, ret;\n\n    obj = JS_NewObjectProtoClass(ctx, ctx->native_error_proto[error_num],\n                                 JS_CLASS_ERROR);\n    if (unlikely(JS_IsException(obj))) {\n        /* out of memory: throw JS_NULL to avoid recursing */\n        obj = JS_NULL;\n    } else {\n        JS_DefinePropertyValue(ctx, obj, JS_ATOM_message,\n                               JS_NewStringLen(ctx, buf, buf_len),\n                               JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n    }\n    if (add_backtrace) {\n        build_backtrace(ctx, obj, NULL, 0, 0);\n    }\n    ret = JS_Throw(ctx, obj);\n    return ret;\n}\n\nJSValue JSB_ThrowError(JSContext *ctx, const char *buf, size_t buf_len)\n{\n    JSRuntime *rt = ctx->rt;\n    JSStackFrame *sf;\n    BOOL add_backtrace;\n\n    /* the backtrace is added later if called from a bytecode function */\n    sf = rt->current_stack_frame;\n    add_backtrace = !rt->in_out_of_memory &&\n        (!sf || (JS_GetFunctionBytecode(sf->cur_func) == NULL));\n    return JSB_ThrowError2(ctx, JS_INTERNAL_ERROR, buf, buf_len, add_backtrace);\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/quickjs.h",
    "content": "/*\n * QuickJS Javascript Engine\n *\n * Copyright (c) 2017-2021 Fabrice Bellard\n * Copyright (c) 2017-2021 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#ifndef QUICKJS_H\n#define QUICKJS_H\n\n#define JS_EXPORT __declspec(dllexport)\n\n#include <stdio.h>\n#include <stdint.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifdef _MSC_VER\n#define __attribute(x)\n#define __attribute__(x)\n#endif\n\n#if defined(__GNUC__) || defined(__clang__)\n#define js_likely(x)          __builtin_expect(!!(x), 1)\n#define js_unlikely(x)        __builtin_expect(!!(x), 0)\n#define js_force_inline       inline __attribute__((always_inline))\n#define __js_printf_like(f, a)   __attribute__((format(printf, f, a)))\n#else\n#define js_likely(x)     (x)\n#define js_unlikely(x)   (x)\n#define js_force_inline  inline\n#define __js_printf_like(a, b)\n#endif\n\n#define JS_BOOL int\n\ntypedef struct JSRuntime JSRuntime;\ntypedef struct JSContext JSContext;\ntypedef struct JSObject JSObject;\ntypedef struct JSClass JSClass;\ntypedef uint32_t JSClassID;\ntypedef uint32_t JSAtom;\n\n#if INTPTR_MAX >= INT64_MAX\n#define JS_PTR64\n#define JS_PTR64_DEF(a) a\n#else\n#define JS_PTR64_DEF(a)\n#endif\n\n#ifndef JS_PTR64\n// #define JS_NAN_BOXING\n#endif\n\nenum {\n    /* all tags with a reference count are negative */\n    JS_TAG_FIRST       = -11, /* first negative tag */\n    JS_TAG_BIG_DECIMAL = -11,\n    JS_TAG_BIG_INT     = -10,\n    JS_TAG_BIG_FLOAT   = -9,\n    JS_TAG_SYMBOL      = -8,\n    JS_TAG_STRING      = -7,\n    JS_TAG_MODULE      = -3, /* used internally */\n    JS_TAG_FUNCTION_BYTECODE = -2, /* used internally */\n    JS_TAG_OBJECT      = -1,\n\n    JS_TAG_INT         = 0,\n    JS_TAG_BOOL        = 1,\n    JS_TAG_NULL        = 2,\n    JS_TAG_UNDEFINED   = 3,\n    JS_TAG_UNINITIALIZED = 4,\n    JS_TAG_CATCH_OFFSET = 5,\n    JS_TAG_EXCEPTION   = 6,\n    JS_TAG_FLOAT64     = 7,\n    /* any larger tag is FLOAT64 if JS_NAN_BOXING */\n};\n\ntypedef struct JSRefCountHeader {\n    int ref_count;\n} JSRefCountHeader;\n\n#define JS_FLOAT64_NAN NAN\n\n#ifdef CONFIG_CHECK_JSVALUE\n/* JSValue consistency : it is not possible to run the code in this\n   mode, but it is useful to detect simple reference counting\n   errors. It would be interesting to modify a static C analyzer to\n   handle specific annotations (clang has such annotations but only\n   for objective C) */\ntypedef struct __JSValue *JSValue;\ntypedef const struct __JSValue *JSValueConst;\n\n#define JS_VALUE_GET_TAG(v) (int)((uintptr_t)(v) & 0xf)\n/* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */\n#define JS_VALUE_GET_NORM_TAG(v) JS_VALUE_GET_TAG(v)\n#define JS_VALUE_GET_INT(v) (int)((intptr_t)(v) >> 4)\n#define JS_VALUE_GET_BOOL(v) JS_VALUE_GET_INT(v)\n#define JS_VALUE_GET_FLOAT64(v) (double)JS_VALUE_GET_INT(v)\n#define JS_VALUE_GET_PTR(v) (void *)((intptr_t)(v) & ~0xf)\n\n#define JS_MKVAL(tag, val) (JSValue)(intptr_t)(((val) << 4) | (tag))\n#define JS_MKPTR(tag, p) (JSValue)((intptr_t)(p) | (tag))\n\n#define JS_TAG_IS_FLOAT64(tag) ((unsigned)(tag) == JS_TAG_FLOAT64)\n\n#define JS_NAN JS_MKVAL(JS_TAG_FLOAT64, 1)\n\nstatic inline JSValue __JS_NewFloat64(JSContext *ctx, double d)\n{\n    return JS_MKVAL(JS_TAG_FLOAT64, (int)d);\n}\n\nstatic inline JS_BOOL JS_VALUE_IS_NAN(JSValue v)\n{\n    return 0;\n}\n    \n#elif defined(JS_NAN_BOXING)\n\ntypedef uint64_t JSValue;\n\n#define JSValueConst JSValue\n\n#define JS_VALUE_GET_TAG(v) (int)((v) >> 32)\n#define JS_VALUE_GET_INT(v) (int)(v)\n#define JS_VALUE_GET_BOOL(v) (int)(v)\n#define JS_VALUE_GET_PTR(v) (void *)(intptr_t)(v)\n\n#define JS_MKVAL(tag, val) (((uint64_t)(tag) << 32) | (uint32_t)(val))\n#define JS_MKPTR(tag, ptr) (((uint64_t)(tag) << 32) | (uintptr_t)(ptr))\n\n#define JS_FLOAT64_TAG_ADDEND (0x7ff80000 - JS_TAG_FIRST + 1) /* quiet NaN encoding */\n\nstatic inline double JS_VALUE_GET_FLOAT64(JSValue v)\n{\n    union {\n        JSValue v;\n        double d;\n    } u;\n    u.v = v;\n    u.v += (uint64_t)JS_FLOAT64_TAG_ADDEND << 32;\n    return u.d;\n}\n\n#define JS_NAN (0x7ff8000000000000 - ((uint64_t)JS_FLOAT64_TAG_ADDEND << 32))\n\nstatic inline JSValue __JS_NewFloat64(JSContext *ctx, double d)\n{\n    union {\n        double d;\n        uint64_t u64;\n    } u;\n    JSValue v;\n    u.d = d;\n    /* normalize NaN */\n    if (js_unlikely((u.u64 & 0x7fffffffffffffff) > 0x7ff0000000000000))\n        v = JS_NAN;\n    else\n        v = u.u64 - ((uint64_t)JS_FLOAT64_TAG_ADDEND << 32);\n    return v;\n}\n\n#define JS_TAG_IS_FLOAT64(tag) ((unsigned)((tag) - JS_TAG_FIRST) >= (JS_TAG_FLOAT64 - JS_TAG_FIRST))\n\n/* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */\nstatic inline int JS_VALUE_GET_NORM_TAG(JSValue v)\n{\n    uint32_t tag;\n    tag = JS_VALUE_GET_TAG(v);\n    if (JS_TAG_IS_FLOAT64(tag))\n        return JS_TAG_FLOAT64;\n    else\n        return tag;\n}\n\nstatic inline JS_BOOL JS_VALUE_IS_NAN(JSValue v)\n{\n    uint32_t tag;\n    tag = JS_VALUE_GET_TAG(v);\n    return tag == (JS_NAN >> 32);\n}\n    \n#else /* !JS_NAN_BOXING */\n\ntypedef union JSValueUnion {\n    int32_t int32;\n    double float64;\n    void *ptr;\n} JSValueUnion;\n\ntypedef struct JSValue {\n    JSValueUnion u;\n    int64_t tag;\n} JSValue;\n\n#define JSValueConst JSValue\n\n#define JS_VALUE_GET_TAG(v) ((int32_t)(v).tag)\n/* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */\n#define JS_VALUE_GET_NORM_TAG(v) JS_VALUE_GET_TAG(v)\n#define JS_VALUE_GET_INT(v) ((v).u.int32)\n#define JS_VALUE_GET_BOOL(v) ((v).u.int32)\n#define JS_VALUE_GET_FLOAT64(v) ((v).u.float64)\n#define JS_VALUE_GET_PTR(v) ((v).u.ptr)\n\n#define JS_MKVAL(tag, val) (JSValue){ (JSValueUnion){ .int32 = val }, tag }\n#define JS_MKPTR(tag, p) (JSValue){ (JSValueUnion){ .ptr = p }, tag }\n\n#define JS_TAG_IS_FLOAT64(tag) ((unsigned)(tag) == JS_TAG_FLOAT64)\n\n#define JS_NAN (JSValue){ .u.float64 = JS_FLOAT64_NAN, JS_TAG_FLOAT64 }\n\nstatic inline JSValue __JS_NewFloat64(JSContext *ctx, double d)\n{\n    JSValue v;\n    v.tag = JS_TAG_FLOAT64;\n    v.u.float64 = d;\n    return v;\n}\n\nstatic inline JS_BOOL JS_VALUE_IS_NAN(JSValue v)\n{\n    union {\n        double d;\n        uint64_t u64;\n    } u;\n    if (v.tag != JS_TAG_FLOAT64)\n        return 0;\n    u.d = v.u.float64;\n    return (u.u64 & 0x7fffffffffffffff) > 0x7ff0000000000000;\n}\n\n#endif /* !JS_NAN_BOXING */\n\n#define JS_VALUE_IS_BOTH_INT(v1, v2) ((JS_VALUE_GET_TAG(v1) | JS_VALUE_GET_TAG(v2)) == 0)\n#define JS_VALUE_IS_BOTH_FLOAT(v1, v2) (JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(v1)) && JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(v2)))\n\n#define JS_VALUE_GET_OBJ(v) ((JSObject *)JS_VALUE_GET_PTR(v))\n#define JS_VALUE_GET_STRING(v) ((JSString *)JS_VALUE_GET_PTR(v))\n#define JS_VALUE_HAS_REF_COUNT(v) ((unsigned)JS_VALUE_GET_TAG(v) >= (unsigned)JS_TAG_FIRST)\n\n/* special values */\n#define JS_NULL      JS_MKVAL(JS_TAG_NULL, 0)\n#define JS_UNDEFINED JS_MKVAL(JS_TAG_UNDEFINED, 0)\n#define JS_FALSE     JS_MKVAL(JS_TAG_BOOL, 0)\n#define JS_TRUE      JS_MKVAL(JS_TAG_BOOL, 1)\n#define JS_EXCEPTION JS_MKVAL(JS_TAG_EXCEPTION, 0)\n#define JS_UNINITIALIZED JS_MKVAL(JS_TAG_UNINITIALIZED, 0)\n\n/* flags for object properties */\n#define JS_PROP_CONFIGURABLE  (1 << 0)\n#define JS_PROP_WRITABLE      (1 << 1)\n#define JS_PROP_ENUMERABLE    (1 << 2)\n#define JS_PROP_C_W_E         (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE | JS_PROP_ENUMERABLE)\n#define JS_PROP_LENGTH        (1 << 3) /* used internally in Arrays */\n#define JS_PROP_TMASK         (3 << 4) /* mask for NORMAL, GETSET, VARREF, AUTOINIT */\n#define JS_PROP_NORMAL         (0 << 4)\n#define JS_PROP_GETSET         (1 << 4)\n#define JS_PROP_VARREF         (2 << 4) /* used internally */\n#define JS_PROP_AUTOINIT       (3 << 4) /* used internally */\n\n/* flags for JS_DefineProperty */\n#define JS_PROP_HAS_SHIFT        8\n#define JS_PROP_HAS_CONFIGURABLE (1 << 8)\n#define JS_PROP_HAS_WRITABLE     (1 << 9)\n#define JS_PROP_HAS_ENUMERABLE   (1 << 10)\n#define JS_PROP_HAS_GET          (1 << 11)\n#define JS_PROP_HAS_SET          (1 << 12)\n#define JS_PROP_HAS_VALUE        (1 << 13)\n\n/* throw an exception if false would be returned\n   (JS_DefineProperty/JS_SetProperty) */\n#define JS_PROP_THROW            (1 << 14)\n/* throw an exception if false would be returned in strict mode\n   (JS_SetProperty) */\n#define JS_PROP_THROW_STRICT     (1 << 15)\n\n#define JS_PROP_NO_ADD           (1 << 16) /* internal use */\n#define JS_PROP_NO_EXOTIC        (1 << 17) /* internal use */\n\n#define JS_DEFAULT_STACK_SIZE (256 * 1024)\n\n/* JS_Eval() flags */\n#define JS_EVAL_TYPE_GLOBAL   (0 << 0) /* global code (default) */\n#define JS_EVAL_TYPE_MODULE   (1 << 0) /* module code */\n#define JS_EVAL_TYPE_DIRECT   (2 << 0) /* direct call (internal use) */\n#define JS_EVAL_TYPE_INDIRECT (3 << 0) /* indirect call (internal use) */\n#define JS_EVAL_TYPE_MASK     (3 << 0)\n\n#define JS_EVAL_FLAG_STRICT   (1 << 3) /* force 'strict' mode */\n#define JS_EVAL_FLAG_STRIP    (1 << 4) /* force 'strip' mode */\n/* compile but do not run. The result is an object with a\n   JS_TAG_FUNCTION_BYTECODE or JS_TAG_MODULE tag. It can be executed\n   with JS_EvalFunction(). */\n#define JS_EVAL_FLAG_COMPILE_ONLY (1 << 5)\n/* don't include the stack frames before this eval in the Error() backtraces */\n#define JS_EVAL_FLAG_BACKTRACE_BARRIER (1 << 6)\n\ntypedef JSValue JSCFunction(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv);\ntypedef JSValue JSCFunctionMagic(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic);\ntypedef JSValue JSCFunctionData(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, JSValue *func_data);\n\ntypedef struct JSMallocState {\n    size_t malloc_count;\n    size_t malloc_size;\n    size_t malloc_limit;\n    void *opaque; /* user opaque */\n} JSMallocState;\n\ntypedef struct JSMallocFunctions {\n    void *(*js_malloc)(JSMallocState *s, size_t size);\n    void (*js_free)(JSMallocState *s, void *ptr);\n    void *(*js_realloc)(JSMallocState *s, void *ptr, size_t size);\n    size_t (*js_malloc_usable_size)(const void *ptr);\n} JSMallocFunctions;\n\ntypedef struct JSGCObjectHeader JSGCObjectHeader;\n\nJS_EXPORT JSRuntime *JS_NewRuntime(void);\n/* info lifetime must exceed that of rt */\nJS_EXPORT void JS_SetRuntimeInfo(JSRuntime *rt, const char *info);\nJS_EXPORT void JS_SetMemoryLimit(JSRuntime *rt, size_t limit);\nJS_EXPORT void JS_SetGCThreshold(JSRuntime *rt, size_t gc_threshold);\n/* use 0 to disable maximum stack size check */\nJS_EXPORT void JS_SetMaxStackSize(JSRuntime *rt, size_t stack_size);\n/* should be called when changing thread to update the stack top value\n   used to check stack overflow. */\nJS_EXPORT void JS_UpdateStackTop(JSRuntime *rt);\nJS_EXPORT JSRuntime *JS_NewRuntime2(const JSMallocFunctions *mf, void *opaque);\nJS_EXPORT int JS_FreeRuntime(JSRuntime *rt);\nJS_EXPORT void *JS_GetRuntimeOpaque(JSRuntime *rt);\nJS_EXPORT void JS_SetRuntimeOpaque(JSRuntime *rt, void *opaque);\ntypedef void JS_MarkFunc(JSRuntime *rt, JSGCObjectHeader *gp);\nJS_EXPORT void JS_MarkValue(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func);\nJS_EXPORT void JS_RunGC(JSRuntime *rt);\nJS_EXPORT JS_BOOL JS_IsLiveObject(JSRuntime *rt, JSValueConst obj);\n\nJS_EXPORT JSContext *JS_NewContext(JSRuntime *rt);\nJS_EXPORT void JS_FreeContext(JSContext *s);\nJS_EXPORT JSContext *JS_DupContext(JSContext *ctx);\nJS_EXPORT void *JS_GetContextOpaque(JSContext *ctx);\nJS_EXPORT void JS_SetContextOpaque(JSContext *ctx, void *opaque);\nJS_EXPORT JSRuntime *JS_GetRuntime(JSContext *ctx);\nJS_EXPORT void JS_SetClassProto(JSContext *ctx, JSClassID class_id, JSValue obj);\nJS_EXPORT JSValue JS_GetClassProto(JSContext *ctx, JSClassID class_id);\n\n/* the following functions are used to select the intrinsic object to\n   save memory */\nJS_EXPORT JSContext *JS_NewContextRaw(JSRuntime *rt);\nJS_EXPORT void JS_AddIntrinsicBaseObjects(JSContext *ctx);\nJS_EXPORT void JS_AddIntrinsicDate(JSContext *ctx);\nJS_EXPORT void JS_AddIntrinsicEval(JSContext *ctx);\nJS_EXPORT void JS_AddIntrinsicStringNormalize(JSContext *ctx);\nJS_EXPORT void JS_AddIntrinsicRegExpCompiler(JSContext *ctx);\nJS_EXPORT void JS_AddIntrinsicRegExp(JSContext *ctx);\nJS_EXPORT void JS_AddIntrinsicJSON(JSContext *ctx);\nJS_EXPORT void JS_AddIntrinsicProxy(JSContext *ctx);\nJS_EXPORT void JS_AddIntrinsicMapSet(JSContext *ctx);\nJS_EXPORT void JS_AddIntrinsicTypedArrays(JSContext *ctx);\nJS_EXPORT void JS_AddIntrinsicPromise(JSContext *ctx);\nJS_EXPORT void JS_AddIntrinsicBigInt(JSContext *ctx);\nJS_EXPORT void JS_AddIntrinsicBigFloat(JSContext *ctx);\nJS_EXPORT void JS_AddIntrinsicBigDecimal(JSContext *ctx);\n/* enable operator overloading */\nJS_EXPORT void JS_AddIntrinsicOperators(JSContext *ctx);\n/* enable \"use math\" */\nJS_EXPORT void JS_EnableBignumExt(JSContext *ctx, JS_BOOL enable);\n\nJS_EXPORT JSValue js_string_codePointRange(JSContext *ctx, JSValueConst this_val,\n                                 int argc, JSValueConst *argv);\n\nJS_EXPORT void *js_malloc_rt(JSRuntime *rt, size_t size);\nJS_EXPORT void js_free_rt(JSRuntime *rt, void *ptr);\nJS_EXPORT void *js_realloc_rt(JSRuntime *rt, void *ptr, size_t size);\nJS_EXPORT size_t js_malloc_usable_size_rt(JSRuntime *rt, const void *ptr);\nJS_EXPORT void *js_mallocz_rt(JSRuntime *rt, size_t size);\n\nJS_EXPORT void *js_malloc(JSContext *ctx, size_t size);\nJS_EXPORT void js_free(JSContext *ctx, void *ptr);\nJS_EXPORT void *js_realloc(JSContext *ctx, void *ptr, size_t size);\nJS_EXPORT size_t js_malloc_usable_size(JSContext *ctx, const void *ptr);\nJS_EXPORT void *js_realloc2(JSContext *ctx, void *ptr, size_t size, size_t *pslack);\nJS_EXPORT void *js_mallocz(JSContext *ctx, size_t size);\nJS_EXPORT char *js_strdup(JSContext *ctx, const char *str);\nJS_EXPORT char *js_strndup(JSContext *ctx, const char *s, size_t n);\n\ntypedef struct JSMemoryUsage {\n    int64_t malloc_size, malloc_limit, memory_used_size;\n    int64_t malloc_count;\n    int64_t memory_used_count;\n    int64_t atom_count, atom_size;\n    int64_t str_count, str_size;\n    int64_t obj_count, obj_size;\n    int64_t prop_count, prop_size;\n    int64_t shape_count, shape_size;\n    int64_t js_func_count, js_func_size, js_func_code_size;\n    int64_t js_func_pc2line_count, js_func_pc2line_size;\n    int64_t c_func_count, array_count;\n    int64_t fast_array_count, fast_array_elements;\n    int64_t binary_object_count, binary_object_size;\n} JSMemoryUsage;\n\nJS_EXPORT void JS_ComputeMemoryUsage(JSRuntime *rt, JSMemoryUsage *s);\nJS_EXPORT void JS_DumpMemoryUsage(FILE *fp, const JSMemoryUsage *s, JSRuntime *rt);\n\n/* atom support */\n#define JS_ATOM_NULL 0\n\nJS_EXPORT JSAtom JS_NewAtomLen(JSContext *ctx, const char *str, size_t len);\nJS_EXPORT JSAtom JS_NewAtom(JSContext *ctx, const char *str);\nJS_EXPORT JSAtom JS_NewAtomUInt32(JSContext *ctx, uint32_t n);\nJS_EXPORT JSAtom JS_DupAtom(JSContext *ctx, JSAtom v);\nJS_EXPORT void JS_FreeAtom(JSContext *ctx, JSAtom v);\nJS_EXPORT void JS_FreeAtomRT(JSRuntime *rt, JSAtom v);\nJS_EXPORT JSValue JS_AtomToValue(JSContext *ctx, JSAtom atom);\nJS_EXPORT JSValue JS_AtomToString(JSContext *ctx, JSAtom atom);\nJS_EXPORT const char *JS_AtomToCString(JSContext *ctx, JSAtom atom);\nJS_EXPORT JSAtom JS_ValueToAtom(JSContext *ctx, JSValueConst val);\n\n/* object class support */\n\ntypedef struct JSPropertyEnum {\n    JS_BOOL is_enumerable;\n    JSAtom atom;\n} JSPropertyEnum;\n\ntypedef struct JSPropertyDescriptor {\n    int flags;\n    JSValue value;\n    JSValue getter;\n    JSValue setter;\n} JSPropertyDescriptor;\n\ntypedef struct JSClassExoticMethods {\n    /* Return -1 if exception (can only happen in case of Proxy object),\n       FALSE if the property does not exists, TRUE if it exists. If 1 is\n       returned, the property descriptor 'desc' is filled if != NULL. */\n    int (*get_own_property)(JSContext *ctx, JSPropertyDescriptor *desc,\n                             JSValueConst obj, JSAtom prop);\n    /* '*ptab' should hold the '*plen' property keys. Return 0 if OK,\n       -1 if exception. The 'is_enumerable' field is ignored.\n    */\n    int (*get_own_property_names)(JSContext *ctx, JSPropertyEnum **ptab,\n                                  uint32_t *plen,\n                                  JSValueConst obj);\n    /* return < 0 if exception, or TRUE/FALSE */\n    int (*delete_property)(JSContext *ctx, JSValueConst obj, JSAtom prop);\n    /* return < 0 if exception or TRUE/FALSE */\n    int (*define_own_property)(JSContext *ctx, JSValueConst this_obj,\n                               JSAtom prop, JSValueConst val,\n                               JSValueConst getter, JSValueConst setter,\n                               int flags);\n    /* The following methods can be emulated with the previous ones,\n       so they are usually not needed */\n    /* return < 0 if exception or TRUE/FALSE */\n    int (*has_property)(JSContext *ctx, JSValueConst obj, JSAtom atom);\n    JSValue (*get_property)(JSContext *ctx, JSValueConst obj, JSAtom atom,\n                            JSValueConst receiver);\n    /* return < 0 if exception or TRUE/FALSE */\n    int (*set_property)(JSContext *ctx, JSValueConst obj, JSAtom atom,\n                        JSValueConst value, JSValueConst receiver, int flags);\n} JSClassExoticMethods;\n\ntypedef void JSClassFinalizer(JSRuntime *rt, JSValue val);\ntypedef void JSClassGCMark(JSRuntime *rt, JSValueConst val,\n                           JS_MarkFunc *mark_func);\n#define JS_CALL_FLAG_CONSTRUCTOR (1 << 0)\ntypedef JSValue JSClassCall(JSContext *ctx, JSValueConst func_obj,\n                            JSValueConst this_val, int argc, JSValueConst *argv,\n                            int flags);\n\ntypedef struct JSClassDef {\n    const char *class_name;\n    JSClassFinalizer *finalizer;\n    JSClassGCMark *gc_mark;\n    /* if call != NULL, the object is a function. If (flags &\n       JS_CALL_FLAG_CONSTRUCTOR) != 0, the function is called as a\n       constructor. In this case, 'this_val' is new.target. A\n       constructor call only happens if the object constructor bit is\n       set (see JS_SetConstructorBit()). */\n    JSClassCall *call;\n    /* XXX: suppress this indirection ? It is here only to save memory\n       because only a few classes need these methods */\n    JSClassExoticMethods *exotic;\n} JSClassDef;\n\nJS_EXPORT JSClassID JS_NewClassID(JSClassID *pclass_id);\nJS_EXPORT int JS_NewClass(JSRuntime *rt, JSClassID class_id, const JSClassDef *class_def);\nJS_EXPORT int JS_IsRegisteredClass(JSRuntime *rt, JSClassID class_id);\n\n/* value handling */\n\nstatic js_force_inline JSValue JS_NewBool(JSContext *ctx, JS_BOOL val)\n{\n    return JS_MKVAL(JS_TAG_BOOL, (val != 0));\n}\n\nstatic js_force_inline JSValue JS_NewInt32(JSContext *ctx, int32_t val)\n{\n    return JS_MKVAL(JS_TAG_INT, val);\n}\n\nstatic js_force_inline JSValue JS_NewCatchOffset(JSContext *ctx, int32_t val)\n{\n    return JS_MKVAL(JS_TAG_CATCH_OFFSET, val);\n}\n\nstatic js_force_inline JSValue JS_NewInt64(JSContext *ctx, int64_t val)\n{\n    JSValue v;\n    if (val == (int32_t)val) {\n        v = JS_NewInt32(ctx, val);\n    } else {\n        v = __JS_NewFloat64(ctx, val);\n    }\n    return v;\n}\n\nstatic js_force_inline JSValue JS_NewUint32(JSContext *ctx, uint32_t val)\n{\n    JSValue v;\n    if (val <= 0x7fffffff) {\n        v = JS_NewInt32(ctx, val);\n    } else {\n        v = __JS_NewFloat64(ctx, val);\n    }\n    return v;\n}\n\nJS_EXPORT JSValue JS_NewBigInt64(JSContext *ctx, int64_t v);\nJS_EXPORT JSValue JS_NewBigUint64(JSContext *ctx, uint64_t v);\n\nstatic js_force_inline JSValue JS_NewFloat64(JSContext *ctx, double d)\n{\n    JSValue v;\n    int32_t val;\n    union {\n        double d;\n        uint64_t u;\n    } u, t;\n    u.d = d;\n    val = (int32_t)d;\n    t.d = val;\n    /* -0 cannot be represented as integer, so we compare the bit\n        representation */\n    if (u.u == t.u) {\n        v = JS_MKVAL(JS_TAG_INT, val);\n    } else {\n        v = __JS_NewFloat64(ctx, d);\n    }\n    return v;\n}\n\nstatic inline JS_BOOL JS_IsNumber(JSValueConst v)\n{\n    int tag = JS_VALUE_GET_TAG(v);\n    return tag == JS_TAG_INT || JS_TAG_IS_FLOAT64(tag);\n}\n\nstatic inline JS_BOOL JS_IsBigInt(JSContext *ctx, JSValueConst v)\n{\n    int tag = JS_VALUE_GET_TAG(v);\n    return tag == JS_TAG_BIG_INT;\n}\n\nstatic inline JS_BOOL JS_IsBigFloat(JSValueConst v)\n{\n    int tag = JS_VALUE_GET_TAG(v);\n    return tag == JS_TAG_BIG_FLOAT;\n}\n\nstatic inline JS_BOOL JS_IsBigDecimal(JSValueConst v)\n{\n    int tag = JS_VALUE_GET_TAG(v);\n    return tag == JS_TAG_BIG_DECIMAL;\n}\n\nstatic inline JS_BOOL JS_IsBool(JSValueConst v)\n{\n    return JS_VALUE_GET_TAG(v) == JS_TAG_BOOL;\n}\n\nstatic inline JS_BOOL JS_IsNull(JSValueConst v)\n{\n    return JS_VALUE_GET_TAG(v) == JS_TAG_NULL;\n}\n\nstatic inline JS_BOOL JS_IsUndefined(JSValueConst v)\n{\n    return JS_VALUE_GET_TAG(v) == JS_TAG_UNDEFINED;\n}\n\nstatic inline JS_BOOL JS_IsException(JSValueConst v)\n{\n    return js_unlikely(JS_VALUE_GET_TAG(v) == JS_TAG_EXCEPTION);\n}\n\nstatic inline JS_BOOL JS_IsUninitialized(JSValueConst v)\n{\n    return js_unlikely(JS_VALUE_GET_TAG(v) == JS_TAG_UNINITIALIZED);\n}\n\nstatic inline JS_BOOL JS_IsString(JSValueConst v)\n{\n    return JS_VALUE_GET_TAG(v) == JS_TAG_STRING;\n}\n\nstatic inline JS_BOOL JS_IsSymbol(JSValueConst v)\n{\n    return JS_VALUE_GET_TAG(v) == JS_TAG_SYMBOL;\n}\n\nstatic inline JS_BOOL JS_IsObject(JSValueConst v)\n{\n    return JS_VALUE_GET_TAG(v) == JS_TAG_OBJECT;\n}\n\nJS_EXPORT JSValue JS_Throw(JSContext *ctx, JSValue obj);\nJS_EXPORT JSValue JS_GetException(JSContext *ctx);\nJS_EXPORT JS_BOOL JS_IsError(JSContext *ctx, JSValueConst val);\nJS_EXPORT void JS_ResetUncatchableError(JSContext *ctx);\nJS_EXPORT JSValue JS_NewError(JSContext *ctx);\nJS_EXPORT JSValue __js_printf_like(2, 3) JS_ThrowSyntaxError(JSContext *ctx, const char *fmt, ...);\nJS_EXPORT JSValue __js_printf_like(2, 3) JS_ThrowTypeError(JSContext *ctx, const char *fmt, ...);\nJS_EXPORT JSValue __js_printf_like(2, 3) JS_ThrowReferenceError(JSContext *ctx, const char *fmt, ...);\nJS_EXPORT JSValue __js_printf_like(2, 3) JS_ThrowRangeError(JSContext *ctx, const char *fmt, ...);\nJS_EXPORT JSValue __js_printf_like(2, 3) JS_ThrowInternalError(JSContext *ctx, const char *fmt, ...);\nJS_EXPORT JSValue JS_ThrowOutOfMemory(JSContext *ctx);\n\nJS_EXPORT void __JS_FreeValue(JSContext *ctx, JSValue v);\nstatic inline void JS_FreeValue(JSContext *ctx, JSValue v)\n{\n    if (JS_VALUE_HAS_REF_COUNT(v)) {\n        JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v);\n        if (--p->ref_count <= 0) {\n            __JS_FreeValue(ctx, v);\n        }\n    }\n}\nJS_EXPORT void __JS_FreeValueRT(JSRuntime *rt, JSValue v);\nstatic inline void JS_FreeValueRT(JSRuntime *rt, JSValue v)\n{\n    if (JS_VALUE_HAS_REF_COUNT(v)) {\n        JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v);\n        if (--p->ref_count <= 0) {\n            __JS_FreeValueRT(rt, v);\n        }\n    }\n}\n\nstatic inline JSValue JS_DupValue(JSContext *ctx, JSValueConst v)\n{\n    if (JS_VALUE_HAS_REF_COUNT(v)) {\n        JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v);\n        p->ref_count++;\n    }\n    return v;\n}\n\nstatic inline JSValue JS_DupValueRT(JSRuntime *rt, JSValueConst v)\n{\n    if (JS_VALUE_HAS_REF_COUNT(v)) {\n        JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v);\n        p->ref_count++;\n    }\n    return v;\n}\n\nJS_EXPORT int JS_ToBool(JSContext *ctx, JSValueConst val); /* return -1 for JS_EXCEPTION */\nJS_EXPORT int JS_ToInt32(JSContext *ctx, int32_t *pres, JSValueConst val);\nstatic inline int JS_ToUint32(JSContext *ctx, uint32_t *pres, JSValueConst val)\n{\n    return JS_ToInt32(ctx, (int32_t*)pres, val);\n}\nJS_EXPORT int JS_ToInt64(JSContext *ctx, int64_t *pres, JSValueConst val);\nJS_EXPORT int JS_ToIndex(JSContext *ctx, uint64_t *plen, JSValueConst val);\nJS_EXPORT int JS_ToFloat64(JSContext *ctx, double *pres, JSValueConst val);\n/* return an exception if 'val' is a Number */\nJS_EXPORT int JS_ToBigInt64(JSContext *ctx, int64_t *pres, JSValueConst val);\n/* same as JS_ToInt64() but allow BigInt */\nJS_EXPORT int JS_ToInt64Ext(JSContext *ctx, int64_t *pres, JSValueConst val);\n\nJS_EXPORT JSValue JS_NewStringLen(JSContext *ctx, const char *str1, size_t len1);\nJS_EXPORT JSValue JS_NewString(JSContext *ctx, const char *str);\nJS_EXPORT JSValue JS_NewAtomString(JSContext *ctx, const char *str);\nJS_EXPORT JSValue JS_ToString(JSContext *ctx, JSValueConst val);\nJS_EXPORT JSValue JS_ToPropertyKey(JSContext *ctx, JSValueConst val);\nJS_EXPORT const char *JS_ToCStringLen2(JSContext *ctx, size_t *plen, JSValueConst val1, JS_BOOL cesu8);\nstatic inline const char *JS_ToCStringLen(JSContext *ctx, size_t *plen, JSValueConst val1)\n{\n    return JS_ToCStringLen2(ctx, plen, val1, 0);\n}\nstatic inline const char *JS_ToCString(JSContext *ctx, JSValueConst val1)\n{\n    return JS_ToCStringLen2(ctx, NULL, val1, 0);\n}\nJS_EXPORT void JS_FreeCString(JSContext *ctx, const char *ptr);\n\nJS_EXPORT JSValue JS_NewObjectProtoClass(JSContext *ctx, JSValueConst proto, JSClassID class_id);\nJS_EXPORT JSValue JS_NewObjectClass(JSContext *ctx, int class_id);\nJS_EXPORT JSValue JS_NewObjectProto(JSContext *ctx, JSValueConst proto);\nJS_EXPORT JSValue JS_NewObject(JSContext *ctx);\n\nJS_EXPORT JS_BOOL JS_IsFunction(JSContext* ctx, JSValueConst val);\nJS_EXPORT JS_BOOL JS_IsConstructor(JSContext* ctx, JSValueConst val);\nJS_EXPORT JS_BOOL JS_SetConstructorBit(JSContext *ctx, JSValueConst func_obj, JS_BOOL val);\n\nJS_EXPORT JSValue JS_NewArray(JSContext *ctx);\nJS_EXPORT int JS_IsArray(JSContext *ctx, JSValueConst val);\n\nJS_EXPORT JSValue JS_GetPropertyInternal(JSContext *ctx, JSValueConst obj,\n                               JSAtom prop, JSValueConst receiver,\n                               JS_BOOL throw_ref_error);\nstatic js_force_inline JSValue JS_GetProperty(JSContext *ctx, JSValueConst this_obj,\n                                              JSAtom prop)\n{\n    return JS_GetPropertyInternal(ctx, this_obj, prop, this_obj, 0);\n}\nJS_EXPORT JSValue JS_GetPropertyStr(JSContext *ctx, JSValueConst this_obj,\n                          const char *prop);\nJS_EXPORT JSValue JS_GetPropertyUint32(JSContext *ctx, JSValueConst this_obj,\n                             uint32_t idx);\n\nJS_EXPORT int JS_SetPropertyInternal(JSContext *ctx, JSValueConst this_obj,\n                           JSAtom prop, JSValue val,\n                           int flags);\nstatic inline int JS_SetProperty(JSContext *ctx, JSValueConst this_obj,\n                                 JSAtom prop, JSValue val)\n{\n    return JS_SetPropertyInternal(ctx, this_obj, prop, val, JS_PROP_THROW);\n}\nJS_EXPORT int JS_SetPropertyUint32(JSContext *ctx, JSValueConst this_obj,\n                         uint32_t idx, JSValue val);\nJS_EXPORT int JS_SetPropertyInt64(JSContext *ctx, JSValueConst this_obj,\n                        int64_t idx, JSValue val);\nJS_EXPORT int JS_SetPropertyStr(JSContext *ctx, JSValueConst this_obj,\n                      const char *prop, JSValue val);\nJS_EXPORT int JS_HasProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop);\nJS_EXPORT int JS_IsExtensible(JSContext *ctx, JSValueConst obj);\nJS_EXPORT int JS_PreventExtensions(JSContext *ctx, JSValueConst obj);\nJS_EXPORT int JS_DeleteProperty(JSContext *ctx, JSValueConst obj, JSAtom prop, int flags);\nJS_EXPORT int JS_SetPrototype(JSContext *ctx, JSValueConst obj, JSValueConst proto_val);\nJS_EXPORT JSValue JS_GetPrototype(JSContext *ctx, JSValueConst val);\n\n#define JS_GPN_STRING_MASK  (1 << 0)\n#define JS_GPN_SYMBOL_MASK  (1 << 1)\n#define JS_GPN_PRIVATE_MASK (1 << 2)\n/* only include the enumerable properties */\n#define JS_GPN_ENUM_ONLY    (1 << 4)\n/* set theJSPropertyEnum.is_enumerable field */\n#define JS_GPN_SET_ENUM     (1 << 5)\n\nJS_EXPORT int JS_GetOwnPropertyNames(JSContext *ctx, JSPropertyEnum **ptab,\n                           uint32_t *plen, JSValueConst obj, int flags);\nJS_EXPORT int JS_GetOwnProperty(JSContext *ctx, JSPropertyDescriptor *desc,\n                      JSValueConst obj, JSAtom prop);\n\nJS_EXPORT JSValue JS_Call(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj,\n                int argc, JSValueConst *argv);\nJS_EXPORT JSValue JS_Invoke(JSContext *ctx, JSValueConst this_val, JSAtom atom,\n                  int argc, JSValueConst *argv);\nJS_EXPORT JSValue JS_CallConstructor(JSContext *ctx, JSValueConst func_obj,\n                           int argc, JSValueConst *argv);\nJS_EXPORT JSValue JS_CallConstructor2(JSContext *ctx, JSValueConst func_obj,\n                            JSValueConst new_target,\n                            int argc, JSValueConst *argv);\nJS_EXPORT JS_BOOL JS_DetectModule(const char *input, size_t input_len);\n/* 'input' must be zero terminated i.e. input[input_len] = '\\0'. */\nJS_EXPORT JSValue JS_Eval(JSContext *ctx, const char *input, size_t input_len,\n                const char *filename, int eval_flags);\n/* same as JS_Eval() but with an explicit 'this_obj' parameter */\nJS_EXPORT JSValue JS_EvalThis(JSContext *ctx, JSValueConst this_obj,\n                    const char *input, size_t input_len,\n                    const char *filename, int eval_flags);\nJS_EXPORT JSValue JS_GetGlobalObject(JSContext *ctx);\nJS_EXPORT int JS_IsInstanceOf(JSContext *ctx, JSValueConst val, JSValueConst obj);\nJS_EXPORT int JS_DefineProperty(JSContext *ctx, JSValueConst this_obj,\n                      JSAtom prop, JSValueConst val,\n                      JSValueConst getter, JSValueConst setter, int flags);\nJS_EXPORT int JS_DefinePropertyValue(JSContext *ctx, JSValueConst this_obj,\n                           JSAtom prop, JSValue val, int flags);\nJS_EXPORT int JS_DefinePropertyValueUint32(JSContext *ctx, JSValueConst this_obj,\n                                 uint32_t idx, JSValue val, int flags);\nJS_EXPORT int JS_DefinePropertyValueStr(JSContext *ctx, JSValueConst this_obj,\n                              const char *prop, JSValue val, int flags);\nJS_EXPORT int JS_DefinePropertyGetSet(JSContext *ctx, JSValueConst this_obj,\n                            JSAtom prop, JSValue getter, JSValue setter,\n                            int flags);\nJS_EXPORT void JS_SetOpaque(JSValue obj, void *opaque);\nJS_EXPORT void *JS_GetOpaque(JSValueConst obj, JSClassID class_id);\nJS_EXPORT void *JS_GetOpaque2(JSContext *ctx, JSValueConst obj, JSClassID class_id);\n\n/* 'buf' must be zero terminated i.e. buf[buf_len] = '\\0'. */\nJS_EXPORT JSValue JS_ParseJSON(JSContext *ctx, const char *buf, size_t buf_len,\n                     const char *filename);\n#define JS_PARSE_JSON_EXT (1 << 0) /* allow extended JSON */\nJS_EXPORT JSValue JS_ParseJSON2(JSContext *ctx, const char *buf, size_t buf_len,\n                      const char *filename, int flags);\nJS_EXPORT JSValue JS_JSONStringify(JSContext *ctx, JSValueConst obj,\n                         JSValueConst replacer, JSValueConst space0);\n\ntypedef void JSFreeArrayBufferDataFunc(JSRuntime *rt, void *opaque, void *ptr);\nJS_EXPORT JSValue JS_NewArrayBuffer(JSContext *ctx, uint8_t *buf, size_t len,\n                          JSFreeArrayBufferDataFunc *free_func, void *opaque,\n                          JS_BOOL is_shared);\nJS_EXPORT JSValue JS_NewArrayBufferCopy(JSContext *ctx, const uint8_t *buf, size_t len);\nJS_EXPORT void JS_DetachArrayBuffer(JSContext *ctx, JSValueConst obj);\nJS_EXPORT uint8_t *JS_GetArrayBuffer(JSContext *ctx, size_t *psize, JSValueConst obj);\nJS_EXPORT JSValue JS_GetTypedArrayBuffer(JSContext *ctx, JSValueConst obj,\n                               size_t *pbyte_offset,\n                               size_t *pbyte_length,\n                               size_t *pbytes_per_element);\ntypedef struct {\n    void *(*sab_alloc)(void *opaque, size_t size);\n    void (*sab_free)(void *opaque, void *ptr);\n    void (*sab_dup)(void *opaque, void *ptr);\n    void *sab_opaque;\n} JSSharedArrayBufferFunctions;\nJS_EXPORT void JS_SetSharedArrayBufferFunctions(JSRuntime *rt,\n                                      const JSSharedArrayBufferFunctions *sf);\n\nJS_EXPORT JSValue JS_NewPromiseCapability(JSContext *ctx, JSValue *resolving_funcs);\n\n/* is_handled = TRUE means that the rejection is handled */\ntypedef void JSHostPromiseRejectionTracker(JSContext *ctx, JSValueConst promise,\n                                           JSValueConst reason,\n                                           JS_BOOL is_handled, void *opaque);\nJS_EXPORT void JS_SetHostPromiseRejectionTracker(JSRuntime *rt, JSHostPromiseRejectionTracker *cb, void *opaque);\n\n/* return != 0 if the JS code needs to be interrupted */\ntypedef int JSInterruptHandler(JSRuntime *rt, void *opaque);\nJS_EXPORT void JS_SetInterruptHandler(JSRuntime *rt, JSInterruptHandler *cb, void *opaque);\n/* if can_block is TRUE, Atomics.wait() can be used */\nJS_EXPORT void JS_SetCanBlock(JSRuntime *rt, JS_BOOL can_block);\n/* set the [IsHTMLDDA] internal slot */\nJS_EXPORT void JS_SetIsHTMLDDA(JSContext *ctx, JSValueConst obj);\n\ntypedef struct JSModuleDef JSModuleDef;\n\n/* return the module specifier (allocated with js_malloc()) or NULL if\n   exception */\ntypedef char *JSModuleNormalizeFunc(JSContext *ctx,\n                                    const char *module_base_name,\n                                    const char *module_name, void *opaque);\ntypedef JSModuleDef *JSModuleLoaderFunc(JSContext *ctx,\n                                        const char *module_name, void *opaque);\n\n/* module_normalize = NULL is allowed and invokes the default module\n   filename normalizer */\nJS_EXPORT void JS_SetModuleLoaderFunc(JSRuntime *rt,\n                            JSModuleNormalizeFunc *module_normalize,\n                            JSModuleLoaderFunc *module_loader, void *opaque);\n/* return the import.meta object of a module */\nJS_EXPORT JSValue JS_GetImportMeta(JSContext *ctx, JSModuleDef *m);\nJS_EXPORT JSAtom JS_GetModuleName(JSContext *ctx, JSModuleDef *m);\n\n/* JS Job support */\n\ntypedef JSValue JSJobFunc(JSContext *ctx, int argc, JSValueConst *argv);\nJS_EXPORT int JS_EnqueueJob(JSContext *ctx, JSJobFunc *job_func, int argc, JSValueConst *argv);\n\nJS_EXPORT JS_BOOL JS_IsJobPending(JSRuntime *rt);\nJS_EXPORT int JS_ExecutePendingJob(JSRuntime *rt, JSContext **pctx);\n\n/* Object Writer/Reader (currently only used to handle precompiled code) */\n#define JS_WRITE_OBJ_BYTECODE  (1 << 0) /* allow function/module */\n#define JS_WRITE_OBJ_BSWAP     (1 << 1) /* byte swapped output */\n#define JS_WRITE_OBJ_SAB       (1 << 2) /* allow SharedArrayBuffer */\n#define JS_WRITE_OBJ_REFERENCE (1 << 3) /* allow object references to\n                                           encode arbitrary object\n                                           graph */\nJS_EXPORT uint8_t *JS_WriteObject(JSContext *ctx, size_t *psize, JSValueConst obj,\n                        int flags);\nJS_EXPORT uint8_t *JS_WriteObject2(JSContext *ctx, size_t *psize, JSValueConst obj,\n                         int flags, uint8_t ***psab_tab, size_t *psab_tab_len);\n\n#define JS_READ_OBJ_BYTECODE  (1 << 0) /* allow function/module */\n#define JS_READ_OBJ_ROM_DATA  (1 << 1) /* avoid duplicating 'buf' data */\n#define JS_READ_OBJ_SAB       (1 << 2) /* allow SharedArrayBuffer */\n#define JS_READ_OBJ_REFERENCE (1 << 3) /* allow object references */\nJS_EXPORT JSValue JS_ReadObject(JSContext *ctx, const uint8_t *buf, size_t buf_len,\n                      int flags);\n/* instantiate and evaluate a bytecode function. Only used when\n   reading a script or module with JS_ReadObject() */\nJS_EXPORT JSValue JS_EvalFunction(JSContext *ctx, JSValue fun_obj);\n/* load the dependencies of the module 'obj'. Useful when JS_ReadObject()\n   returns a module. */\nJS_EXPORT int JS_ResolveModule(JSContext *ctx, JSValueConst obj);\n\n/* only exported for os.Worker() */\nJS_EXPORT JSAtom JS_GetScriptOrModuleName(JSContext *ctx, int n_stack_levels);\n/* only exported for os.Worker() */\nJS_EXPORT JSModuleDef *JS_RunModule(JSContext *ctx, const char *basename,\n                          const char *filename);\n\n/* C function definition */\ntypedef enum JSCFunctionEnum {  /* XXX: should rename for namespace isolation */\n    JS_CFUNC_generic,\n    JS_CFUNC_generic_magic,\n    JS_CFUNC_constructor,\n    JS_CFUNC_constructor_magic,\n    JS_CFUNC_constructor_or_func,\n    JS_CFUNC_constructor_or_func_magic,\n    JS_CFUNC_f_f,\n    JS_CFUNC_f_f_f,\n    JS_CFUNC_getter,\n    JS_CFUNC_setter,\n    JS_CFUNC_getter_magic,\n    JS_CFUNC_setter_magic,\n    JS_CFUNC_iterator_next,\n} JSCFunctionEnum;\n\ntypedef union JSCFunctionType {\n    JSCFunction *generic;\n    JSValue (*generic_magic)(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic);\n    JSCFunction *constructor;\n    JSValue (*constructor_magic)(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv, int magic);\n    JSCFunction *constructor_or_func;\n    double (*f_f)(double);\n    double (*f_f_f)(double, double);\n    JSValue (*getter)(JSContext *ctx, JSValueConst this_val);\n    JSValue (*setter)(JSContext *ctx, JSValueConst this_val, JSValueConst val);\n    JSValue (*getter_magic)(JSContext *ctx, JSValueConst this_val, int magic);\n    JSValue (*setter_magic)(JSContext *ctx, JSValueConst this_val, JSValueConst val, int magic);\n    JSValue (*iterator_next)(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv, int *pdone, int magic);\n} JSCFunctionType;\n\nJS_EXPORT JSValue JS_NewCFunction2(JSContext *ctx, JSCFunction *func,\n                         const char *name,\n                         int length, JSCFunctionEnum cproto, int magic);\nJS_EXPORT JSValue JS_NewCFunctionData(JSContext *ctx, JSCFunctionData *func,\n                            int length, int magic, int data_len,\n                            JSValueConst *data);\n\nstatic inline JSValue JS_NewCFunction(JSContext *ctx, JSCFunction *func, const char *name,\n                                      int length)\n{\n    return JS_NewCFunction2(ctx, func, name, length, JS_CFUNC_generic, 0);\n}\n\nstatic inline JSValue JS_NewCFunctionMagic(JSContext *ctx, JSCFunctionMagic *func,\n                                           const char *name,\n                                           int length, JSCFunctionEnum cproto, int magic)\n{\n    return JS_NewCFunction2(ctx, (JSCFunction *)func, name, length, cproto, magic);\n}\nJS_EXPORT void JS_SetConstructor(JSContext *ctx, JSValueConst func_obj, \n                       JSValueConst proto);\n\n/* C property definition */\n\ntypedef struct JSCFunctionListEntry {\n    const char *name;\n    uint8_t prop_flags;\n    uint8_t def_type;\n    int16_t magic;\n    union {\n        struct {\n            uint8_t length; /* XXX: should move outside union */\n            uint8_t cproto; /* XXX: should move outside union */\n            JSCFunctionType cfunc;\n        } func;\n        struct {\n            JSCFunctionType get;\n            JSCFunctionType set;\n        } getset;\n        struct {\n            const char *name;\n            int base;\n        } alias;\n        struct {\n            const struct JSCFunctionListEntry *tab;\n            int len;\n        } prop_list;\n        const char *str;\n        int32_t i32;\n        int64_t i64;\n        double f64;\n    } u;\n} JSCFunctionListEntry;\n\n#define JS_DEF_CFUNC          0\n#define JS_DEF_CGETSET        1\n#define JS_DEF_CGETSET_MAGIC  2\n#define JS_DEF_PROP_STRING    3\n#define JS_DEF_PROP_INT32     4\n#define JS_DEF_PROP_INT64     5\n#define JS_DEF_PROP_DOUBLE    6\n#define JS_DEF_PROP_UNDEFINED 7\n#define JS_DEF_OBJECT         8\n#define JS_DEF_ALIAS          9\n\n/* Note: c++ does not like nested designators */\n#define JS_CFUNC_DEF(name, length, func1) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, 0, .u = { .func = { length, JS_CFUNC_generic, { .generic = func1 } } } }\n#define JS_CFUNC_MAGIC_DEF(name, length, func1, magic) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, magic, .u = { .func = { length, JS_CFUNC_generic_magic, { .generic_magic = func1 } } } }\n#define JS_CFUNC_SPECIAL_DEF(name, length, cproto, func1) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, 0, .u = { .func = { length, JS_CFUNC_ ## cproto, { .cproto = func1 } } } }\n#define JS_ITERATOR_NEXT_DEF(name, length, func1, magic) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, magic, .u = { .func = { length, JS_CFUNC_iterator_next, { .iterator_next = func1 } } } }\n#define JS_CGETSET_DEF(name, fgetter, fsetter) { name, JS_PROP_CONFIGURABLE, JS_DEF_CGETSET, 0, .u = { .getset = { .get = { .getter = fgetter }, .set = { .setter = fsetter } } } }\n#define JS_CGETSET_MAGIC_DEF(name, fgetter, fsetter, magic) { name, JS_PROP_CONFIGURABLE, JS_DEF_CGETSET_MAGIC, magic, .u = { .getset = { .get = { .getter_magic = fgetter }, .set = { .setter_magic = fsetter } } } }\n#define JS_PROP_STRING_DEF(name, cstr, prop_flags) { name, prop_flags, JS_DEF_PROP_STRING, 0, .u = { .str = cstr } }\n#define JS_PROP_INT32_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_INT32, 0, .u = { .i32 = val } }\n#define JS_PROP_INT64_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_INT64, 0, .u = { .i64 = val } }\n#define JS_PROP_DOUBLE_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_DOUBLE, 0, .u = { .f64 = val } }\n#define JS_PROP_UNDEFINED_DEF(name, prop_flags) { name, prop_flags, JS_DEF_PROP_UNDEFINED, 0, .u = { .i32 = 0 } }\n#define JS_OBJECT_DEF(name, tab, len, prop_flags) { name, prop_flags, JS_DEF_OBJECT, 0, .u = { .prop_list = { tab, len } } }\n#define JS_ALIAS_DEF(name, from) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_ALIAS, 0, .u = { .alias = { from, -1 } } }\n#define JS_ALIAS_BASE_DEF(name, from, base) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_ALIAS, 0, .u = { .alias = { from, base } } }\n\nJS_EXPORT void JS_SetPropertyFunctionList(JSContext *ctx, JSValueConst obj,\n                                const JSCFunctionListEntry *tab,\n                                int len);\n\n/* C module definition */\n\ntypedef int JSModuleInitFunc(JSContext *ctx, JSModuleDef *m);\n\nJS_EXPORT JSModuleDef *JS_NewCModule(JSContext *ctx, const char *name_str,\n                           JSModuleInitFunc *func);\n/* can only be called before the module is instantiated */\nJS_EXPORT int JS_AddModuleExport(JSContext *ctx, JSModuleDef *m, const char *name_str);\nJS_EXPORT int JS_AddModuleExportList(JSContext *ctx, JSModuleDef *m,\n                           const JSCFunctionListEntry *tab, int len);\n/* can only be called after the module is instantiated */\nJS_EXPORT int JS_SetModuleExport(JSContext *ctx, JSModuleDef *m, const char *export_name,\n                       JSValue val);\nJS_EXPORT int JS_SetModuleExportList(JSContext *ctx, JSModuleDef *m,\n                           const JSCFunctionListEntry *tab, int len);\nJS_EXPORT JSValueConst JS_GetActiveFunction(JSContext *ctx);\nJS_EXPORT JSValue JSB_ThrowError(JSContext *ctx, const char *buf, size_t buf_len);\n\n#undef js_unlikely\n#undef js_force_inline\n\n#ifdef __cplusplus\n} /* extern \"C\" { */\n#endif\n\n#endif /* QUICKJS_H */\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/readme.txt",
    "content": "The main documentation is in doc/quickjs.pdf or doc/quickjs.html.\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/release.sh",
    "content": "#!/bin/sh\n# Release the QuickJS source code\n\nset -e\n\nversion=`cat VERSION`\n\nif [ \"$1\" = \"-h\" ] ; then\n    echo \"release.sh [release_list]\"\n    echo \"\"\n    echo \"release_list: extras binary win_binary quickjs\"\n    \n    exit 1\nfi\n\nrelease_list=\"extras binary win_binary quickjs\"\n\nif [ \"$1\" != \"\" ] ; then\n    release_list=\"$1\"\nfi\n\n#################################################\"\n# extras\n\nif echo $release_list | grep -w -q extras ; then\n\nd=\"quickjs-${version}\"\nname=\"quickjs-extras-${version}\"\noutdir=\"/tmp/${d}\"\n\nrm -rf $outdir\nmkdir -p $outdir $outdir/unicode $outdir/tests \n\ncp unicode/* $outdir/unicode\ncp -a tests/bench-v8 $outdir/tests\n\n( cd /tmp && tar Jcvf /tmp/${name}.tar.xz ${d} )\n\nfi\n\n#################################################\"\n# Windows binary release\n\nif echo $release_list | grep -w -q win_binary ; then\n\n# win64\n\ndlldir=/usr/x86_64-w64-mingw32/sys-root/mingw/bin\ncross_prefix=\"x86_64-w64-mingw32-\"\nd=\"quickjs-win-x86_64-${version}\"\noutdir=\"/tmp/${d}\"\n\nrm -rf $outdir\nmkdir -p $outdir\n\nmake CONFIG_WIN32=y qjs.exe\ncp qjs.exe $outdir\n${cross_prefix}strip $outdir/qjs.exe\ncp $dlldir/libwinpthread-1.dll $outdir\n\n( cd /tmp/$d && rm -f ../${d}.zip && zip -r ../${d}.zip . )\n\nmake CONFIG_WIN32=y clean\n\n# win32\n\ndlldir=/usr/i686-w64-mingw32/sys-root/mingw/bin\ncross_prefix=\"i686-w64-mingw32-\"\nd=\"quickjs-win-i686-${version}\"\noutdir=\"/tmp/${d}\"\n\nrm -rf $outdir\nmkdir -p $outdir\n\nmake clean\nmake CONFIG_WIN32=y clean\n\nmake CONFIG_WIN32=y CONFIG_M32=y qjs.exe\ncp qjs.exe $outdir\n${cross_prefix}strip $outdir/qjs.exe\ncp $dlldir/libwinpthread-1.dll $outdir\n\n( cd /tmp/$d && rm -f ../${d}.zip && zip -r ../${d}.zip . )\n\nfi\n    \n#################################################\"\n# Linux binary release\n\nif echo $release_list | grep -w -q binary ; then\n\nmake clean\nmake CONFIG_WIN32=y clean\nmake -j4 qjs run-test262\nmake -j4 CONFIG_M32=y qjs32 run-test262-32\nstrip qjs run-test262 qjs32 run-test262-32\n\nd=\"quickjs-linux-x86_64-${version}\"\noutdir=\"/tmp/${d}\"\n\nrm -rf $outdir\nmkdir -p $outdir\n\ncp qjs run-test262 $outdir\n\n( cd /tmp/$d && rm -f ../${d}.zip && zip -r ../${d}.zip . )\n\nd=\"quickjs-linux-i686-${version}\"\noutdir=\"/tmp/${d}\"\n\nrm -rf $outdir\nmkdir -p $outdir\n\ncp qjs32 $outdir/qjs\ncp run-test262-32 $outdir/run-test262\n\n( cd /tmp/$d && rm -f ../${d}.zip && zip -r ../${d}.zip . )\n\nfi\n\n#################################################\"\n# quickjs\n\nif echo $release_list | grep -w -q quickjs ; then\n\nmake build_doc\n\nd=\"quickjs-${version}\"\noutdir=\"/tmp/${d}\"\n\nrm -rf $outdir\nmkdir -p $outdir $outdir/doc $outdir/tests $outdir/examples\n\ncp Makefile VERSION TODO Changelog readme.txt LICENSE \\\n   release.sh unicode_download.sh \\\n   qjs.c qjsc.c qjscalc.js repl.js \\\n   quickjs.c quickjs.h quickjs-atom.h \\\n   quickjs-libc.c quickjs-libc.h quickjs-opcode.h \\\n   cutils.c cutils.h list.h \\\n   libregexp.c libregexp.h libregexp-opcode.h \\\n   libunicode.c libunicode.h libunicode-table.h \\\n   libbf.c libbf.h \\\n   unicode_gen.c unicode_gen_def.h \\\n   run-test262.c test262o.conf test262.conf \\\n   test262o_errors.txt test262_errors.txt \\\n   $outdir\n\ncp tests/*.js tests/*.patch tests/bjson.c $outdir/tests\n\ncp examples/*.js examples/*.c $outdir/examples\n\ncp doc/quickjs.texi doc/quickjs.pdf doc/quickjs.html \\\n   doc/jsbignum.texi doc/jsbignum.html doc/jsbignum.pdf \\\n   $outdir/doc \n\n( cd /tmp && tar Jcvf /tmp/${d}.tar.xz ${d} )\n\nfi\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/repl.js",
    "content": "/*\n * QuickJS Read Eval Print Loop\n * \n * Copyright (c) 2017-2020 Fabrice Bellard\n * Copyright (c) 2017-2020 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\"use strip\";\n\nimport * as std from \"std\";\nimport * as os from \"os\";\n\n(function(g) {\n    /* add 'os' and 'std' bindings */\n    g.os = os;\n    g.std = std;\n    \n    /* close global objects */\n    var Object = g.Object;\n    var String = g.String;\n    var Array = g.Array;\n    var Date = g.Date;\n    var Math = g.Math;\n    var isFinite = g.isFinite;\n    var parseFloat = g.parseFloat;\n\n    /* XXX: use preprocessor ? */\n    var config_numcalc = (typeof os.open === \"undefined\");\n    var has_jscalc = (typeof Fraction === \"function\");\n    var has_bignum = (typeof BigFloat === \"function\");\n    \n    var colors = {\n        none:    \"\\x1b[0m\",\n        black:   \"\\x1b[30m\",\n        red:     \"\\x1b[31m\",\n        green:   \"\\x1b[32m\",\n        yellow:  \"\\x1b[33m\",\n        blue:    \"\\x1b[34m\",\n        magenta: \"\\x1b[35m\",\n        cyan:    \"\\x1b[36m\",\n        white:   \"\\x1b[37m\",\n        gray:    \"\\x1b[30;1m\",\n        grey:    \"\\x1b[30;1m\",\n        bright_red:     \"\\x1b[31;1m\",\n        bright_green:   \"\\x1b[32;1m\",\n        bright_yellow:  \"\\x1b[33;1m\",\n        bright_blue:    \"\\x1b[34;1m\",\n        bright_magenta: \"\\x1b[35;1m\",\n        bright_cyan:    \"\\x1b[36;1m\",\n        bright_white:   \"\\x1b[37;1m\",\n    };\n\n    var styles;\n    if (config_numcalc) {\n        styles = {\n            'default':    'black',\n            'comment':    'white',\n            'string':     'green',\n            'regex':      'cyan',\n            'number':     'green',\n            'keyword':    'blue',\n            'function':   'gray',\n            'type':       'bright_magenta',\n            'identifier': 'yellow',\n            'error':      'bright_red',\n            'result':     'black',\n            'error_msg':  'bright_red',\n        };\n    } else {\n        styles = {\n            'default':    'bright_green',\n            'comment':    'white',\n            'string':     'bright_cyan',\n            'regex':      'cyan',\n            'number':     'green',\n            'keyword':    'bright_white',\n            'function':   'bright_yellow',\n            'type':       'bright_magenta',\n            'identifier': 'bright_green',\n            'error':      'red',\n            'result':     'bright_white',\n            'error_msg':  'bright_red',\n        };\n    }\n\n    var history = [];\n    var clip_board = \"\";\n    var prec;\n    var expBits;\n    var log2_10;\n    \n    var pstate = \"\";\n    var prompt = \"\";\n    var plen = 0;\n    var ps1;\n    if (config_numcalc)\n        ps1 = \"> \";\n    else\n        ps1 = \"qjs > \";\n    var ps2 = \"  ... \";\n    var utf8 = true;\n    var show_time = false;\n    var show_colors = true;\n    var eval_time = 0;\n    \n    var mexpr = \"\";\n    var level = 0;\n    var cmd = \"\";\n    var cursor_pos = 0;\n    var last_cmd = \"\";\n    var last_cursor_pos = 0;\n    var history_index;\n    var this_fun, last_fun;\n    var quote_flag = false;\n\n    var utf8_state = 0;\n    var utf8_val = 0;\n\n    var term_fd;\n    var term_read_buf;\n    var term_width;\n    /* current X position of the cursor in the terminal */\n    var term_cursor_x = 0; \n    \n    function termInit() {\n        var tab;\n        term_fd = std.in.fileno();\n        \n        /* get the terminal size */\n        term_width = 80;\n        if (os.isatty(term_fd)) {\n            if (os.ttyGetWinSize) {\n                tab = os.ttyGetWinSize(term_fd);\n                if (tab)\n                    term_width = tab[0];\n            }\n            if (os.ttySetRaw) {\n                /* set the TTY to raw mode */\n                os.ttySetRaw(term_fd);\n            }\n        }\n\n        /* install a Ctrl-C signal handler */\n        os.signal(os.SIGINT, sigint_handler);\n\n        /* install a handler to read stdin */\n        term_read_buf = new Uint8Array(64);\n        os.setReadHandler(term_fd, term_read_handler);\n    }\n\n    function sigint_handler() {\n        /* send Ctrl-C to readline */\n        handle_byte(3);\n    }\n    \n    function term_read_handler() {\n        var l, i;\n        l = os.read(term_fd, term_read_buf.buffer, 0, term_read_buf.length);\n        for(i = 0; i < l; i++)\n            handle_byte(term_read_buf[i]);\n    }\n    \n    function handle_byte(c) {\n        if (!utf8) {\n            handle_char(c);\n        } else if (utf8_state !== 0 && (c >= 0x80 && c < 0xc0)) {\n            utf8_val = (utf8_val << 6) | (c & 0x3F);\n            utf8_state--;\n            if (utf8_state === 0) {\n                handle_char(utf8_val);\n            }\n        } else if (c >= 0xc0 && c < 0xf8) {\n            utf8_state = 1 + (c >= 0xe0) + (c >= 0xf0);\n            utf8_val = c & ((1 << (6 - utf8_state)) - 1);\n        } else {\n            utf8_state = 0;\n            handle_char(c);\n        }\n    }\n    \n    function is_alpha(c) {\n        return typeof c === \"string\" &&\n            ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'));\n    }\n    \n    function is_digit(c) {\n        return typeof c === \"string\" && (c >= '0' && c <= '9');\n    }\n\n    function is_word(c) {\n        return typeof c === \"string\" &&\n            (is_alpha(c) || is_digit(c) || c == '_' || c == '$');\n    }\n\n    function ucs_length(str) {\n        var len, c, i, str_len = str.length;\n        len = 0;\n        /* we never count the trailing surrogate to have the\n         following property: ucs_length(str) =\n         ucs_length(str.substring(0, a)) + ucs_length(str.substring(a,\n         str.length)) for 0 <= a <= str.length */\n        for(i = 0; i < str_len; i++) {\n            c = str.charCodeAt(i);\n            if (c < 0xdc00 || c >= 0xe000)\n                len++;\n        }\n        return len;\n    }\n\n    function is_trailing_surrogate(c)  {\n        var d;\n        if (typeof c !== \"string\")\n            return false;\n        d = c.codePointAt(0); /* can be NaN if empty string */\n        return d >= 0xdc00 && d < 0xe000;\n    }\n    \n    function is_balanced(a, b) {\n        switch (a + b) {\n        case \"()\":\n        case \"[]\":\n        case \"{}\":\n            return true;\n        }\n        return false;\n    }\n\n    function print_color_text(str, start, style_names) {\n        var i, j;\n        for (j = start; j < str.length;) {\n            var style = style_names[i = j];\n            while (++j < str.length && style_names[j] == style)\n                continue;\n            std.puts(colors[styles[style] || 'default']);\n            std.puts(str.substring(i, j));\n            std.puts(colors['none']);\n        }\n    }\n\n    function print_csi(n, code) {\n        std.puts(\"\\x1b[\" + ((n != 1) ? n : \"\") + code);\n    }\n\n    /* XXX: handle double-width characters */\n    function move_cursor(delta) {\n        var i, l;\n        if (delta > 0) {\n            while (delta != 0) {\n                if (term_cursor_x == (term_width - 1)) {\n                    std.puts(\"\\n\"); /* translated to CRLF */\n                    term_cursor_x = 0;\n                    delta--;\n                } else {\n                    l = Math.min(term_width - 1 - term_cursor_x, delta);\n                    print_csi(l, \"C\"); /* right */\n                    delta -= l; \n                    term_cursor_x += l;\n                }\n            }\n        } else {\n            delta = -delta;\n            while (delta != 0) {\n                if (term_cursor_x == 0) {\n                    print_csi(1, \"A\"); /* up */\n                    print_csi(term_width - 1, \"C\"); /* right */\n                    delta--;\n                    term_cursor_x = term_width - 1;\n                } else {\n                    l = Math.min(delta, term_cursor_x);\n                    print_csi(l, \"D\"); /* left */\n                    delta -= l;\n                    term_cursor_x -= l;\n                }\n            }\n        }\n    }\n\n    function update() {\n        var i, cmd_len;\n        /* cursor_pos is the position in 16 bit characters inside the\n           UTF-16 string 'cmd' */\n        if (cmd != last_cmd) {\n            if (!show_colors && last_cmd.substring(0, last_cursor_pos) == cmd.substring(0, last_cursor_pos)) {\n                /* optimize common case */\n                std.puts(cmd.substring(last_cursor_pos));\n            } else {\n                /* goto the start of the line */\n                move_cursor(-ucs_length(last_cmd.substring(0, last_cursor_pos)));\n                if (show_colors) {\n                    var str = mexpr ? mexpr + '\\n' + cmd : cmd;\n                    var start = str.length - cmd.length;\n                    var colorstate = colorize_js(str);\n                    print_color_text(str, start, colorstate[2]);\n                } else {\n                    std.puts(cmd);\n                }\n            }\n            term_cursor_x = (term_cursor_x + ucs_length(cmd)) % term_width;\n            if (term_cursor_x == 0) {\n                /* show the cursor on the next line */\n                std.puts(\" \\x08\");\n            }\n            /* remove the trailing characters */\n            std.puts(\"\\x1b[J\");\n            last_cmd = cmd;\n            last_cursor_pos = cmd.length;\n        }\n        if (cursor_pos > last_cursor_pos) {\n            move_cursor(ucs_length(cmd.substring(last_cursor_pos, cursor_pos)));\n        } else if (cursor_pos < last_cursor_pos) {\n            move_cursor(-ucs_length(cmd.substring(cursor_pos, last_cursor_pos)));\n        }\n        last_cursor_pos = cursor_pos;\n        std.out.flush();\n    }\n\n    /* editing commands */\n    function insert(str) {\n        if (str) {\n            cmd = cmd.substring(0, cursor_pos) + str + cmd.substring(cursor_pos);\n            cursor_pos += str.length;\n        }\n    }\n\n    function quoted_insert() {\n        quote_flag = true;\n    }\n\n    function abort() {\n        cmd = \"\";\n        cursor_pos = 0;\n        return -2;\n    }\n\n    function alert() {\n    }\n\n    function beginning_of_line() {\n        cursor_pos = 0;\n    }\n\n    function end_of_line() {\n        cursor_pos = cmd.length;\n    }\n\n    function forward_char() {\n        if (cursor_pos < cmd.length) {\n            cursor_pos++;\n            while (is_trailing_surrogate(cmd.charAt(cursor_pos)))\n                cursor_pos++;\n        }\n    }\n\n    function backward_char() {\n        if (cursor_pos > 0) {\n            cursor_pos--;\n            while (is_trailing_surrogate(cmd.charAt(cursor_pos)))\n                cursor_pos--;\n        }\n    }\n\n    function skip_word_forward(pos) {\n        while (pos < cmd.length && !is_word(cmd.charAt(pos)))\n            pos++;\n        while (pos < cmd.length && is_word(cmd.charAt(pos)))\n            pos++;\n        return pos;\n    }\n\n    function skip_word_backward(pos) {\n        while (pos > 0 && !is_word(cmd.charAt(pos - 1)))\n            pos--;\n        while (pos > 0 && is_word(cmd.charAt(pos - 1)))\n            pos--;\n        return pos;\n    }\n\n    function forward_word() {\n        cursor_pos = skip_word_forward(cursor_pos);\n    }\n\n    function backward_word() {\n        cursor_pos = skip_word_backward(cursor_pos);\n    }        \n\n    function accept_line() {\n        std.puts(\"\\n\");\n        history_add(cmd);\n        return -1;\n    }\n\n    function history_add(str) {\n        if (str) {\n            history.push(str);\n        }\n        history_index = history.length;\n    }\n\n    function previous_history() {\n        if (history_index > 0) {\n            if (history_index == history.length) {\n                history.push(cmd);\n            }\n            history_index--;\n            cmd = history[history_index];\n            cursor_pos = cmd.length;\n        }\n    }\n\n    function next_history() {\n        if (history_index < history.length - 1) {\n            history_index++;\n            cmd = history[history_index];\n            cursor_pos = cmd.length;\n        }\n    }\n\n    function history_search(dir) {\n        var pos = cursor_pos;\n        for (var i = 1; i <= history.length; i++) {\n            var index = (history.length + i * dir + history_index) % history.length;\n            if (history[index].substring(0, pos) == cmd.substring(0, pos)) {\n                history_index = index;\n                cmd = history[index];\n                return;\n            }\n        }\n    }\n\n    function history_search_backward() {\n        return history_search(-1);\n    }\n\n    function history_search_forward() {\n        return history_search(1);\n    }\n\n    function delete_char_dir(dir) {\n        var start, end;\n\n        start = cursor_pos;\n        if (dir < 0) {\n            start--;\n            while (is_trailing_surrogate(cmd.charAt(start)))\n                start--;\n        }\n        end = start + 1;\n        while (is_trailing_surrogate(cmd.charAt(end)))\n            end++;\n\n        if (start >= 0 && start < cmd.length) {\n            if (last_fun === kill_region) {\n                kill_region(start, end, dir);\n            } else {\n                cmd = cmd.substring(0, start) + cmd.substring(end);\n                cursor_pos = start;\n            }\n        }\n    }\n\n    function delete_char() {\n        delete_char_dir(1);\n    }\n\n    function control_d() {\n        if (cmd.length == 0) {\n            std.puts(\"\\n\");\n            return -3; /* exit read eval print loop */\n        } else {\n            delete_char_dir(1);\n        }\n    }\n\n    function backward_delete_char() {\n        delete_char_dir(-1);\n    }\n\n    function transpose_chars() {\n        var pos = cursor_pos;\n        if (cmd.length > 1 && pos > 0) {\n            if (pos == cmd.length)\n                pos--;\n            cmd = cmd.substring(0, pos - 1) + cmd.substring(pos, pos + 1) +\n                cmd.substring(pos - 1, pos) + cmd.substring(pos + 1);\n            cursor_pos = pos + 1;\n        }\n    }\n\n    function transpose_words() {\n        var p1 = skip_word_backward(cursor_pos);\n        var p2 = skip_word_forward(p1);\n        var p4 = skip_word_forward(cursor_pos);\n        var p3 = skip_word_backward(p4);\n\n        if (p1 < p2 && p2 <= cursor_pos && cursor_pos <= p3 && p3 < p4) {\n            cmd = cmd.substring(0, p1) + cmd.substring(p3, p4) +\n            cmd.substring(p2, p3) + cmd.substring(p1, p2);\n            cursor_pos = p4;\n        }\n    }\n\n    function upcase_word() {\n        var end = skip_word_forward(cursor_pos);\n        cmd = cmd.substring(0, cursor_pos) +\n            cmd.substring(cursor_pos, end).toUpperCase() +\n            cmd.substring(end);\n    }\n\n    function downcase_word() {\n        var end = skip_word_forward(cursor_pos);\n        cmd = cmd.substring(0, cursor_pos) +\n            cmd.substring(cursor_pos, end).toLowerCase() +\n            cmd.substring(end);\n    }\n\n    function kill_region(start, end, dir) {\n        var s = cmd.substring(start, end);\n        if (last_fun !== kill_region)\n            clip_board = s;\n        else if (dir < 0)\n            clip_board = s + clip_board;\n        else\n            clip_board = clip_board + s;\n\n        cmd = cmd.substring(0, start) + cmd.substring(end);\n        if (cursor_pos > end)\n            cursor_pos -= end - start;\n        else if (cursor_pos > start)\n            cursor_pos = start;\n        this_fun = kill_region;\n    }\n\n    function kill_line() {\n        kill_region(cursor_pos, cmd.length, 1);\n    }\n\n    function backward_kill_line() {\n        kill_region(0, cursor_pos, -1);\n    }\n\n    function kill_word() {\n        kill_region(cursor_pos, skip_word_forward(cursor_pos), 1);\n    }\n\n    function backward_kill_word() {\n        kill_region(skip_word_backward(cursor_pos), cursor_pos, -1);\n    }\n\n    function yank() {\n        insert(clip_board);\n    }\n\n    function control_c() {\n        if (last_fun === control_c) {\n            std.puts(\"\\n\");\n            std.exit(0);\n        } else {\n            std.puts(\"\\n(Press Ctrl-C again to quit)\\n\");\n            readline_print_prompt();\n        }\n    }\n    \n    function reset() {\n        cmd = \"\";\n        cursor_pos = 0;\n    }\n\n    function get_context_word(line, pos) {\n        var s = \"\";\n        while (pos > 0 && is_word(line[pos - 1])) {\n            pos--;\n            s = line[pos] + s;\n        }\n        return s;\n    }\n    function get_context_object(line, pos) {\n        var obj, base, c;\n        if (pos <= 0 || \" ~!%^&*(-+={[|:;,<>?/\".indexOf(line[pos - 1]) >= 0)\n            return g;\n        if (pos >= 2 && line[pos - 1] === \".\") {\n            pos--;\n            obj = {};\n            switch (c = line[pos - 1]) {\n            case '\\'':\n            case '\\\"':\n                return \"a\";\n            case ']':\n                return [];\n            case '}':\n                return {};\n            case '/':\n                return / /;\n            default:\n                if (is_word(c)) {\n                    base = get_context_word(line, pos);\n                    if ([\"true\", \"false\", \"null\", \"this\"].includes(base) || !isNaN(+base))\n                        return eval(base);\n                    obj = get_context_object(line, pos - base.length);\n                    if (obj === null || obj === void 0)\n                        return obj;\n                    if (obj === g && obj[base] === void 0)\n                        return eval(base);\n                    else\n                        return obj[base];\n                }\n                return {};\n            }\n        }\n        return void 0;\n    }\n\n    function get_completions(line, pos) {\n        var s, obj, ctx_obj, r, i, j, paren;\n\n        s = get_context_word(line, pos);\n        ctx_obj = get_context_object(line, pos - s.length);\n        r = [];\n        /* enumerate properties from object and its prototype chain,\n           add non-numeric regular properties with s as e prefix\n         */\n        for (i = 0, obj = ctx_obj; i < 10 && obj !== null && obj !== void 0; i++) {\n            var props = Object.getOwnPropertyNames(obj);\n            /* add non-numeric regular properties */\n            for (j = 0; j < props.length; j++) {\n                var prop = props[j];\n                if (typeof prop == \"string\" && \"\"+(+prop) != prop && prop.startsWith(s))\n                    r.push(prop);\n            }\n            obj = Object.getPrototypeOf(obj);\n        }\n        if (r.length > 1) {\n            /* sort list with internal names last and remove duplicates */\n            function symcmp(a, b) {\n                if (a[0] != b[0]) {\n                    if (a[0] == '_')\n                        return 1;\n                    if (b[0] == '_')\n                        return -1;\n                }\n                if (a < b)\n                    return -1;\n                if (a > b)\n                    return +1;\n                return 0;\n            }\n            r.sort(symcmp);\n            for(i = j = 1; i < r.length; i++) {\n                if (r[i] != r[i - 1])\n                    r[j++] = r[i];\n            }\n            r.length = j;\n        }\n        /* 'tab' = list of completions, 'pos' = cursor position inside\n           the completions */\n        return { tab: r, pos: s.length, ctx: ctx_obj };\n    }\n\n    function completion() {\n        var tab, res, s, i, j, len, t, max_width, col, n_cols, row, n_rows;\n        res = get_completions(cmd, cursor_pos);\n        tab = res.tab;\n        if (tab.length === 0)\n            return;\n        s = tab[0];\n        len = s.length;\n        /* add the chars which are identical in all the completions */\n        for(i = 1; i < tab.length; i++) {\n            t = tab[i];\n            for(j = 0; j < len; j++) {\n                if (t[j] !== s[j]) {\n                    len = j;\n                    break;\n                }\n            }\n        }\n        for(i = res.pos; i < len; i++) {\n            insert(s[i]);\n        }\n        if (last_fun === completion && tab.length == 1) {\n            /* append parentheses to function names */\n            var m = res.ctx[tab[0]];\n            if (typeof m == \"function\") {\n                insert('(');\n                if (m.length == 0)\n                    insert(')');\n            } else if (typeof m == \"object\") {\n                insert('.');\n            }\n        }\n        /* show the possible completions */\n        if (last_fun === completion && tab.length >= 2) {\n            max_width = 0;\n            for(i = 0; i < tab.length; i++)\n                max_width = Math.max(max_width, tab[i].length);\n            max_width += 2;\n            n_cols = Math.max(1, Math.floor((term_width + 1) / max_width));\n            n_rows = Math.ceil(tab.length / n_cols);\n            std.puts(\"\\n\");\n            /* display the sorted list column-wise */\n            for (row = 0; row < n_rows; row++) {\n                for (col = 0; col < n_cols; col++) {\n                    i = col * n_rows + row;\n                    if (i >= tab.length)\n                        break;\n                    s = tab[i];\n                    if (col != n_cols - 1)\n                        s = s.padEnd(max_width);\n                    std.puts(s);\n                }\n                std.puts(\"\\n\");\n            }\n            /* show a new prompt */\n            readline_print_prompt();\n        }\n    }\n    \n    var commands = {        /* command table */\n        \"\\x01\":     beginning_of_line,      /* ^A - bol */\n        \"\\x02\":     backward_char,          /* ^B - backward-char */\n        \"\\x03\":     control_c,              /* ^C - abort */\n        \"\\x04\":     control_d,              /* ^D - delete-char or exit */\n        \"\\x05\":     end_of_line,            /* ^E - eol */\n        \"\\x06\":     forward_char,           /* ^F - forward-char */\n        \"\\x07\":     abort,                  /* ^G - bell */\n        \"\\x08\":     backward_delete_char,   /* ^H - backspace */\n        \"\\x09\":     completion,             /* ^I - history-search-backward */\n        \"\\x0a\":     accept_line,            /* ^J - newline */\n        \"\\x0b\":     kill_line,              /* ^K - delete to end of line */\n        \"\\x0d\":     accept_line,            /* ^M - enter */\n        \"\\x0e\":     next_history,           /* ^N - down */\n        \"\\x10\":     previous_history,       /* ^P - up */\n        \"\\x11\":     quoted_insert,          /* ^Q - quoted-insert */\n        \"\\x12\":     alert,                  /* ^R - reverse-search */\n        \"\\x13\":     alert,                  /* ^S - search */\n        \"\\x14\":     transpose_chars,        /* ^T - transpose */\n        \"\\x18\":     reset,                  /* ^X - cancel */\n        \"\\x19\":     yank,                   /* ^Y - yank */\n        \"\\x1bOA\":   previous_history,       /* ^[OA - up */\n        \"\\x1bOB\":   next_history,           /* ^[OB - down */\n        \"\\x1bOC\":   forward_char,           /* ^[OC - right */\n        \"\\x1bOD\":   backward_char,          /* ^[OD - left */\n        \"\\x1bOF\":   forward_word,           /* ^[OF - ctrl-right */\n        \"\\x1bOH\":   backward_word,          /* ^[OH - ctrl-left */\n        \"\\x1b[1;5C\": forward_word,          /* ^[[1;5C - ctrl-right */\n        \"\\x1b[1;5D\": backward_word,         /* ^[[1;5D - ctrl-left */\n        \"\\x1b[1~\":  beginning_of_line,      /* ^[[1~ - bol */\n        \"\\x1b[3~\":  delete_char,            /* ^[[3~ - delete */\n        \"\\x1b[4~\":  end_of_line,            /* ^[[4~ - eol */\n        \"\\x1b[5~\":  history_search_backward,/* ^[[5~ - page up */\n        \"\\x1b[6~\":  history_search_forward, /* ^[[5~ - page down */\n        \"\\x1b[A\":   previous_history,       /* ^[[A - up */\n        \"\\x1b[B\":   next_history,           /* ^[[B - down */\n        \"\\x1b[C\":   forward_char,           /* ^[[C - right */\n        \"\\x1b[D\":   backward_char,          /* ^[[D - left */\n        \"\\x1b[F\":   end_of_line,            /* ^[[F - end */\n        \"\\x1b[H\":   beginning_of_line,      /* ^[[H - home */\n        \"\\x1b\\x7f\": backward_kill_word,     /* M-C-? - backward_kill_word */\n        \"\\x1bb\":    backward_word,          /* M-b - backward_word */\n        \"\\x1bd\":    kill_word,              /* M-d - kill_word */\n        \"\\x1bf\":    forward_word,           /* M-f - backward_word */\n        \"\\x1bk\":    backward_kill_line,     /* M-k - backward_kill_line */\n        \"\\x1bl\":    downcase_word,          /* M-l - downcase_word */\n        \"\\x1bt\":    transpose_words,        /* M-t - transpose_words */\n        \"\\x1bu\":    upcase_word,            /* M-u - upcase_word */\n        \"\\x7f\":     backward_delete_char,   /* ^? - delete */\n    };\n\n    function dupstr(str, count) {\n        var res = \"\";\n        while (count-- > 0)\n            res += str;\n        return res;\n    }\n\n    var readline_keys;\n    var readline_state;\n    var readline_cb;\n\n    function readline_print_prompt()\n    {\n        std.puts(prompt);\n        term_cursor_x = ucs_length(prompt) % term_width;\n        last_cmd = \"\";\n        last_cursor_pos = 0;\n    }\n\n    function readline_start(defstr, cb) {\n        cmd = defstr || \"\";\n        cursor_pos = cmd.length;\n        history_index = history.length;\n        readline_cb = cb;\n        \n        prompt = pstate;\n    \n        if (mexpr) {\n            prompt += dupstr(\" \", plen - prompt.length);\n            prompt += ps2;\n        } else {\n            if (show_time) {\n                var t = Math.round(eval_time) + \" \";\n                eval_time = 0;\n                t = dupstr(\"0\", 5 - t.length) + t;\n                prompt += t.substring(0, t.length - 4) + \".\" + t.substring(t.length - 4);\n            }\n            plen = prompt.length;\n            prompt += ps1;\n        }\n        readline_print_prompt();\n        update();\n        readline_state = 0;\n    }\n\n    function handle_char(c1) {\n        var c;\n        c = String.fromCodePoint(c1);\n        switch(readline_state) {\n        case 0:\n            if (c == '\\x1b') {  /* '^[' - ESC */\n                readline_keys = c;\n                readline_state = 1;\n            } else {\n                handle_key(c);\n            }\n            break;\n        case 1: /* '^[ */\n            readline_keys += c;\n            if (c == '[') {\n                readline_state = 2;\n            } else if (c == 'O') {\n                readline_state = 3;\n            } else {\n                handle_key(readline_keys);\n                readline_state = 0;\n            }\n            break;\n        case 2: /* '^[[' - CSI */\n            readline_keys += c;\n            if (!(c == ';' || (c >= '0' && c <= '9'))) {\n                handle_key(readline_keys);\n                readline_state = 0;\n            }\n            break;\n        case 3: /* '^[O' - ESC2 */\n            readline_keys += c;\n            handle_key(readline_keys);\n            readline_state = 0;\n            break;\n        }\n    }\n\n    function handle_key(keys) {\n        var fun;\n\n        if (quote_flag) {\n            if (ucs_length(keys) === 1)\n                insert(keys);\n            quote_flag = false;\n        } else if (fun = commands[keys]) {\n            this_fun = fun;\n            switch (fun(keys)) {\n            case -1:\n                readline_cb(cmd);\n                return;\n            case -2:\n                readline_cb(null);\n                return;\n            case -3:\n                /* uninstall a Ctrl-C signal handler */\n                os.signal(os.SIGINT, null);\n                /* uninstall the stdin read handler */\n                os.setReadHandler(term_fd, null);\n                return;\n            }\n            last_fun = this_fun;\n        } else if (ucs_length(keys) === 1 && keys >= ' ') {\n            insert(keys);\n            last_fun = insert;\n        } else {\n            alert(); /* beep! */\n        }\n        \n        cursor_pos = (cursor_pos < 0) ? 0 :\n            (cursor_pos > cmd.length) ? cmd.length : cursor_pos;\n        update();\n    }\n\n    var hex_mode = false;\n    var eval_mode = \"std\";\n\n    function number_to_string(a, radix) {\n        var s;\n        if (!isFinite(a)) {\n            /* NaN, Infinite */\n            return a.toString();\n        } else {\n            if (a == 0) {\n                if (1 / a < 0)\n                    s = \"-0\";\n                else\n                    s = \"0\";\n            } else {\n                if (radix == 16 && a === Math.floor(a)) {\n                    var s;\n                    if (a < 0) {\n                        a = -a;\n                        s = \"-\";\n                    } else {\n                        s = \"\";\n                    }\n                    s += \"0x\" + a.toString(16);\n                } else {\n                    s = a.toString();\n                }\n            }\n            return s;\n        }\n    }\n\n    function bigfloat_to_string(a, radix) {\n        var s;\n        if (!BigFloat.isFinite(a)) {\n            /* NaN, Infinite */\n            if (eval_mode !== \"math\") {\n                return \"BigFloat(\" + a.toString() + \")\";\n            } else {\n                return a.toString();\n            }\n        } else {\n            if (a == 0) {\n                if (1 / a < 0)\n                    s = \"-0\";\n                else\n                    s = \"0\";\n            } else {\n                if (radix == 16) {\n                    var s;\n                    if (a < 0) {\n                        a = -a;\n                        s = \"-\";\n                    } else {\n                        s = \"\";\n                    }\n                    s += \"0x\" + a.toString(16);\n                } else {\n                    s = a.toString();\n                }\n            }\n            if (typeof a === \"bigfloat\" && eval_mode !== \"math\") {\n                s += \"l\";\n            } else if (eval_mode !== \"std\" && s.indexOf(\".\") < 0 &&\n                ((radix == 16 && s.indexOf(\"p\") < 0) ||\n                 (radix == 10 && s.indexOf(\"e\") < 0))) {\n                /* add a decimal point so that the floating point type\n                   is visible */\n                s += \".0\";\n            }\n            return s;\n        }\n    }\n\n    function bigint_to_string(a, radix) {\n        var s;\n        if (radix == 16) {\n            var s;\n            if (a < 0) {\n                a = -a;\n                s = \"-\";\n            } else {\n                s = \"\";\n            }\n            s += \"0x\" + a.toString(16);\n        } else {\n            s = a.toString();\n        }\n        if (eval_mode === \"std\")\n            s += \"n\";\n        return s;\n    }\n    \n    function print(a) {\n        var stack = [];\n\n        function print_rec(a) {\n            var n, i, keys, key, type, s;\n            \n            type = typeof(a);\n            if (type === \"object\") {\n                if (a === null) {\n                    std.puts(a);\n                } else if (stack.indexOf(a) >= 0) {\n                    std.puts(\"[circular]\");\n                } else if (has_jscalc && (a instanceof Fraction ||\n                                        a instanceof Complex ||\n                                        a instanceof Mod ||\n                                        a instanceof Polynomial ||\n                                        a instanceof PolyMod ||\n                                        a instanceof RationalFunction ||\n                                        a instanceof Series)) {\n                    std.puts(a.toString());\n                } else {\n                    stack.push(a);\n                    if (Array.isArray(a)) {\n                        n = a.length;\n                        std.puts(\"[ \");\n                        for(i = 0; i < n; i++) {\n                            if (i !== 0)\n                                std.puts(\", \");\n                            if (i in a) {\n                                print_rec(a[i]);\n                            } else {\n                                std.puts(\"<empty>\");\n                            }\n                            if (i > 20) {\n                                std.puts(\"...\");\n                                break;\n                            }\n                        }\n                        std.puts(\" ]\");\n                    } else if (Object.__getClass(a) === \"RegExp\") {\n                        std.puts(a.toString());\n                    } else {\n                        keys = Object.keys(a);\n                        n = keys.length;\n                        std.puts(\"{ \");\n                        for(i = 0; i < n; i++) {\n                            if (i !== 0)\n                                std.puts(\", \");\n                            key = keys[i];\n                            std.puts(key, \": \");\n                            print_rec(a[key]);\n                        }\n                        std.puts(\" }\");\n                    }\n                    stack.pop(a);\n                }\n            } else if (type === \"string\") {\n                s = a.__quote();\n                if (s.length > 79)\n                    s = s.substring(0, 75) + \"...\\\"\";\n                std.puts(s);\n            } else if (type === \"number\") {\n                std.puts(number_to_string(a, hex_mode ? 16 : 10));\n            } else if (type === \"bigint\") {\n                std.puts(bigint_to_string(a, hex_mode ? 16 : 10));\n            } else if (type === \"bigfloat\") {\n                std.puts(bigfloat_to_string(a, hex_mode ? 16 : 10));\n            } else if (type === \"bigdecimal\") {\n                std.puts(a.toString() + \"m\");\n            } else if (type === \"symbol\") {\n                std.puts(String(a));\n            } else if (type === \"function\") {\n                std.puts(\"function \" + a.name + \"()\");\n            } else {\n                std.puts(a);\n            }\n        }\n        print_rec(a);\n    }\n    \n    function extract_directive(a) {\n        var pos;\n        if (a[0] !== '\\\\')\n            return \"\";\n        for (pos = 1; pos < a.length; pos++) {\n            if (!is_alpha(a[pos]))\n                break;\n        }\n        return a.substring(1, pos);\n    }\n\n    /* return true if the string after cmd can be evaluted as JS */\n    function handle_directive(cmd, expr) {\n        var param, prec1, expBits1;\n        \n        if (cmd === \"h\" || cmd === \"?\" || cmd == \"help\") {\n            help();\n        } else if (cmd === \"load\") {\n            var filename = expr.substring(cmd.length + 1).trim();\n            if (filename.lastIndexOf(\".\") <= filename.lastIndexOf(\"/\"))\n                filename += \".js\";\n            std.loadScript(filename);\n            return false;\n        } else if (cmd === \"x\") {\n            hex_mode = true;\n        } else if (cmd === \"d\") {\n            hex_mode = false;\n        } else if (cmd === \"t\") {\n            show_time = !show_time;\n        } else if (has_bignum && cmd === \"p\") {\n            param = expr.substring(cmd.length + 1).trim().split(\" \");\n            if (param.length === 1 && param[0] === \"\") {\n                std.puts(\"BigFloat precision=\" + prec + \" bits (~\" +\n                          Math.floor(prec / log2_10) +\n                          \" digits), exponent size=\" + expBits + \" bits\\n\");\n            } else if (param[0] === \"f16\") {\n                prec = 11;\n                expBits = 5;\n            } else if (param[0] === \"f32\") {\n                prec = 24;\n                expBits = 8;\n            } else if (param[0] === \"f64\") {\n                prec = 53;\n                expBits = 11;\n            } else if (param[0] === \"f128\") {\n                prec = 113;\n                expBits = 15;\n            } else {\n                prec1 = parseInt(param[0]);\n                if (param.length >= 2)\n                    expBits1 = parseInt(param[1]);\n                else\n                    expBits1 = BigFloatEnv.expBitsMax;\n                if (Number.isNaN(prec1) ||\n                    prec1 < BigFloatEnv.precMin ||\n                    prec1 > BigFloatEnv.precMax) {\n                    std.puts(\"Invalid precision\\n\");\n                    return false;\n                }\n                if (Number.isNaN(expBits1) ||\n                    expBits1 < BigFloatEnv.expBitsMin ||\n                    expBits1 > BigFloatEnv.expBitsMax) {\n                    std.puts(\"Invalid exponent bits\\n\");\n                    return false;\n                }\n                prec = prec1;\n                expBits = expBits1;\n            }\n            return false;\n        } else if (has_bignum && cmd === \"digits\") {\n            param = expr.substring(cmd.length + 1).trim();\n            prec1 = Math.ceil(parseFloat(param) * log2_10);\n            if (prec1 < BigFloatEnv.precMin ||\n                prec1 > BigFloatEnv.precMax) {\n                std.puts(\"Invalid precision\\n\");\n                return false;\n            }\n            prec = prec1;\n            expBits = BigFloatEnv.expBitsMax;\n            return false;\n        } else if (has_bignum && cmd === \"mode\") {\n            param = expr.substring(cmd.length + 1).trim();\n            if (param === \"\") {\n                std.puts(\"Running mode=\" + eval_mode + \"\\n\");\n            } else if (param === \"std\" || param === \"math\") {\n                eval_mode = param;\n            } else {\n                std.puts(\"Invalid mode\\n\");\n            }\n            return false;\n        } else if (cmd === \"clear\") {\n            std.puts(\"\\x1b[H\\x1b[J\");\n        } else if (cmd === \"q\") {\n            std.exit(0);\n        } else if (has_jscalc && cmd === \"a\") {\n            algebraicMode = true;\n        } else if (has_jscalc && cmd === \"n\") {\n            algebraicMode = false;\n        } else {\n            std.puts(\"Unknown directive: \" + cmd + \"\\n\");\n            return false;\n        }\n        return true;\n    }\n\n    if (config_numcalc) {\n        /* called by the GUI */\n        g.execCmd = function (cmd) {\n            switch(cmd) {\n            case \"dec\":\n                hex_mode = false;\n                break;\n            case \"hex\":\n                hex_mode = true;\n                break;\n            case \"num\":\n                algebraicMode = false;\n                break;\n            case \"alg\":\n                algebraicMode = true;\n                break;\n            }\n        }\n    }\n    \n    function help() {\n        function sel(n) {\n            return n ? \"*\": \" \";\n        }\n        std.puts(\"\\\\h          this help\\n\" +\n                 \"\\\\x         \" + sel(hex_mode) + \"hexadecimal number display\\n\" +\n                 \"\\\\d         \" + sel(!hex_mode) + \"decimal number display\\n\" +\n                 \"\\\\t         \" + sel(show_time) + \"toggle timing display\\n\" +\n                  \"\\\\clear      clear the terminal\\n\");\n        if (has_jscalc) {\n            std.puts(\"\\\\a         \" + sel(algebraicMode) + \"algebraic mode\\n\" +\n                     \"\\\\n         \" + sel(!algebraicMode) + \"numeric mode\\n\");\n        }\n        if (has_bignum) {\n            std.puts(\"\\\\p [m [e]]  set the BigFloat precision to 'm' bits\\n\" +\n                     \"\\\\digits n   set the BigFloat precision to 'ceil(n*log2(10))' bits\\n\");\n            if (!has_jscalc) {\n                std.puts(\"\\\\mode [std|math] change the running mode (current = \" + eval_mode + \")\\n\");\n            }\n        }\n        if (!config_numcalc) {\n            std.puts(\"\\\\q          exit\\n\");\n        }\n    }\n\n    function eval_and_print(expr) {\n        var result;\n        \n        try {\n            if (eval_mode === \"math\")\n                expr = '\"use math\"; void 0;' + expr;\n            var now = (new Date).getTime();\n            /* eval as a script */\n            result = std.evalScript(expr, { backtrace_barrier: true });\n            eval_time = (new Date).getTime() - now;\n            std.puts(colors[styles.result]);\n            print(result);\n            std.puts(\"\\n\");\n            std.puts(colors.none);\n            /* set the last result */\n            g._ = result;\n        } catch (error) {\n            std.puts(colors[styles.error_msg]);\n            if (error instanceof Error) {\n                console.log(error);\n                if (error.stack) {\n                    std.puts(error.stack);\n                }\n            } else {\n                std.puts(\"Throw: \");\n                console.log(error);\n            }\n            std.puts(colors.none);\n        }\n    }\n\n    function cmd_start() {\n        if (!config_numcalc) {\n            if (has_jscalc)\n                std.puts('QJSCalc - Type \"\\\\h\" for help\\n');\n            else\n                std.puts('QuickJS - Type \"\\\\h\" for help\\n');\n        }\n        if (has_bignum) {\n            log2_10 = Math.log(10) / Math.log(2);\n            prec = 113;\n            expBits = 15;\n            if (has_jscalc) {\n                eval_mode = \"math\";\n                /* XXX: numeric mode should always be the default ? */\n                g.algebraicMode = config_numcalc;\n            }\n        }\n\n        cmd_readline_start();\n    }\n\n    function cmd_readline_start() {\n        readline_start(dupstr(\"    \", level), readline_handle_cmd);\n    }\n    \n    function readline_handle_cmd(expr) {\n        handle_cmd(expr);\n        cmd_readline_start();\n    }\n\n    function handle_cmd(expr) {\n        var colorstate, cmd;\n        \n        if (expr === null) {\n            expr = \"\";\n            return;\n        }\n        if (expr === \"?\") {\n            help();\n            return;\n        }\n        cmd = extract_directive(expr);\n        if (cmd.length > 0) {\n            if (!handle_directive(cmd, expr))\n                return;\n            expr = expr.substring(cmd.length + 1);\n        }\n        if (expr === \"\")\n            return;\n        \n        if (mexpr)\n            expr = mexpr + '\\n' + expr;\n        colorstate = colorize_js(expr);\n        pstate = colorstate[0];\n        level = colorstate[1];\n        if (pstate) {\n            mexpr = expr;\n            return;\n        }\n        mexpr = \"\";\n        \n        if (has_bignum) {\n            BigFloatEnv.setPrec(eval_and_print.bind(null, expr),\n                                prec, expBits);\n        } else {\n            eval_and_print(expr);\n        }\n        level = 0;\n        \n        /* run the garbage collector after each command */\n        std.gc();\n    }\n\n    function colorize_js(str) {\n        var i, c, start, n = str.length;\n        var style, state = \"\", level = 0;\n        var primary, can_regex = 1;\n        var r = [];\n\n        function push_state(c) { state += c; }\n        function last_state(c) { return state.substring(state.length - 1); }\n        function pop_state(c) {\n            var c = last_state();\n            state = state.substring(0, state.length - 1);\n            return c;\n        }\n\n        function parse_block_comment() {\n            style = 'comment';\n            push_state('/');\n            for (i++; i < n - 1; i++) {\n                if (str[i] == '*' && str[i + 1] == '/') {\n                    i += 2;\n                    pop_state('/');\n                    break;\n                }\n            }\n        }\n\n        function parse_line_comment() {\n            style = 'comment';\n            for (i++; i < n; i++) {\n                if (str[i] == '\\n') {\n                    break;\n                }\n            }\n        }\n\n        function parse_string(delim) {\n            style = 'string';\n            push_state(delim);\n            while (i < n) {\n                c = str[i++];\n                if (c == '\\n') {\n                    style = 'error';\n                    continue;\n                }\n                if (c == '\\\\') {\n                    if (i >= n)\n                        break;\n                    i++;\n                } else\n                if (c == delim) {\n                    pop_state();\n                    break;\n                }\n            }\n        }\n\n        function parse_regex() {\n            style = 'regex';\n            push_state('/');\n            while (i < n) {\n                c = str[i++];\n                if (c == '\\n') {\n                    style = 'error';\n                    continue;\n                }\n                if (c == '\\\\') {\n                    if (i < n) {\n                        i++;\n                    }\n                    continue;\n                }\n                if (last_state() == '[') {\n                    if (c == ']') {\n                        pop_state()\n                    }\n                    // ECMA 5: ignore '/' inside char classes\n                    continue;\n                }\n                if (c == '[') {\n                    push_state('[');\n                    if (str[i] == '[' || str[i] == ']')\n                        i++;\n                    continue;\n                }\n                if (c == '/') {\n                    pop_state();\n                    while (i < n && is_word(str[i]))\n                        i++;\n                    break;\n                }\n            }\n        }\n\n        function parse_number() {\n            style = 'number';\n            while (i < n && (is_word(str[i]) || (str[i] == '.' && (i == n - 1 || str[i + 1] != '.')))) {\n                i++;\n            }\n        }\n\n        var js_keywords = \"|\" +\n            \"break|case|catch|continue|debugger|default|delete|do|\" +\n            \"else|finally|for|function|if|in|instanceof|new|\" +\n            \"return|switch|this|throw|try|typeof|while|with|\" +\n            \"class|const|enum|import|export|extends|super|\" +\n            \"implements|interface|let|package|private|protected|\" +\n            \"public|static|yield|\" +\n            \"undefined|null|true|false|Infinity|NaN|\" +\n            \"eval|arguments|\" +\n            \"await|\";\n\n        var js_no_regex = \"|this|super|undefined|null|true|false|Infinity|NaN|arguments|\";\n        var js_types = \"|void|var|\";\n\n        function parse_identifier() {\n            can_regex = 1;\n\n            while (i < n && is_word(str[i]))\n                i++;\n\n            var w = '|' + str.substring(start, i) + '|';\n\n            if (js_keywords.indexOf(w) >= 0) {\n                style = 'keyword';\n                if (js_no_regex.indexOf(w) >= 0)\n                    can_regex = 0;\n                return;\n            }\n\n            var i1 = i;\n            while (i1 < n && str[i1] == ' ')\n                i1++;\n\n            if (i1 < n && str[i1] == '(') {\n                style = 'function';\n                return;\n            }\n\n            if (js_types.indexOf(w) >= 0) {\n                style = 'type';\n                return;\n            }\n\n            style = 'identifier';\n            can_regex = 0;\n        }\n\n        function set_style(from, to) {\n            while (r.length < from)\n                r.push('default');\n            while (r.length < to)\n                r.push(style);\n        }\n\n        for (i = 0; i < n;) {\n            style = null;\n            start = i;\n            switch (c = str[i++]) {\n            case ' ':\n            case '\\t':\n            case '\\r':\n            case '\\n':\n                continue;\n            case '+':\n            case '-':\n                if (i < n && str[i] == c) {\n                    i++;\n                    continue;\n                }\n                can_regex = 1;\n                continue;\n            case '/':\n                if (i < n && str[i] == '*') { // block comment\n                    parse_block_comment();\n                    break;\n                }\n                if (i < n && str[i] == '/') { // line comment\n                    parse_line_comment();\n                    break;\n                }\n                if (can_regex) {\n                    parse_regex();\n                    can_regex = 0;\n                    break;\n                }\n                can_regex = 1;\n                continue;\n            case '\\'':\n            case '\\\"':\n            case '`':\n                parse_string(c);\n                can_regex = 0;\n                break;\n            case '(':\n            case '[':\n            case '{':\n                can_regex = 1;\n                level++;\n                push_state(c);\n                continue;\n            case ')':\n            case ']':\n            case '}':\n                can_regex = 0;\n                if (level > 0 && is_balanced(last_state(), c)) {\n                    level--;\n                    pop_state();\n                    continue;\n                }\n                style = 'error';\n                break;\n            default:\n                if (is_digit(c)) {\n                    parse_number();\n                    can_regex = 0;\n                    break;\n                }\n                if (is_word(c) || c == '$') {\n                    parse_identifier();\n                    break;\n                }\n                can_regex = 1;\n                continue;\n            }\n            if (style)\n                set_style(start, i);\n        }\n        set_style(n, n);\n        return [ state, level, r ];\n    }\n\n    termInit();\n    \n    cmd_start();\n\n})(globalThis);\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/run-test262.c",
    "content": "/*\n * ECMA Test 262 Runner for QuickJS\n * \n * Copyright (c) 2017-2021 Fabrice Bellard\n * Copyright (c) 2017-2021 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <inttypes.h>\n#include <string.h>\n#include <assert.h>\n#include <ctype.h>\n#include <unistd.h>\n#include <errno.h>\n#include <time.h>\n#include <dirent.h>\n#include <ftw.h>\n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"quickjs-libc.h\"\n\n/* enable test262 thread support to test SharedArrayBuffer and Atomics */\n#define CONFIG_AGENT\n\n#define CMD_NAME \"run-test262\"\n\ntypedef struct namelist_t {\n    char **array;\n    int count;\n    int size;\n    unsigned int sorted : 1;\n} namelist_t;\n\nnamelist_t test_list;\nnamelist_t exclude_list;\nnamelist_t exclude_dir_list;\n\nFILE *outfile;\nenum test_mode_t {\n    TEST_DEFAULT_NOSTRICT, /* run tests as nostrict unless test is flagged as strictonly */\n    TEST_DEFAULT_STRICT,   /* run tests as strict unless test is flagged as nostrict */\n    TEST_NOSTRICT,         /* run tests as nostrict, skip strictonly tests */\n    TEST_STRICT,           /* run tests as strict, skip nostrict tests */\n    TEST_ALL,              /* run tests in both strict and nostrict, unless restricted by spec */\n} test_mode = TEST_DEFAULT_NOSTRICT;\nint skip_async;\nint skip_module;\nint new_style;\nint dump_memory;\nint stats_count;\nJSMemoryUsage stats_all, stats_avg, stats_min, stats_max;\nchar *stats_min_filename;\nchar *stats_max_filename;\nint verbose;\nchar *harness_dir;\nchar *harness_exclude;\nchar *harness_features;\nchar *harness_skip_features;\nchar *error_filename;\nchar *error_file;\nFILE *error_out;\nchar *report_filename;\nint update_errors;\nint test_count, test_failed, test_index, test_skipped, test_excluded;\nint new_errors, changed_errors, fixed_errors;\nint async_done;\n\nvoid warning(const char *, ...) __attribute__((__format__(__printf__, 1, 2)));\nvoid fatal(int, const char *, ...) __attribute__((__format__(__printf__, 2, 3)));\n\nvoid warning(const char *fmt, ...)\n{\n    va_list ap;\n\n    fflush(stdout);\n    fprintf(stderr, \"%s: \", CMD_NAME);\n    va_start(ap, fmt);\n    vfprintf(stderr, fmt, ap);\n    va_end(ap);\n    fputc('\\n', stderr);\n}\n\nvoid fatal(int errcode, const char *fmt, ...)\n{\n    va_list ap;\n\n    fflush(stdout);\n    fprintf(stderr, \"%s: \", CMD_NAME);\n    va_start(ap, fmt);\n    vfprintf(stderr, fmt, ap);\n    va_end(ap);\n    fputc('\\n', stderr);\n\n    exit(errcode);\n}\n\nvoid perror_exit(int errcode, const char *s)\n{\n    fflush(stdout);\n    fprintf(stderr, \"%s: \", CMD_NAME);\n    perror(s);\n    exit(errcode);\n}\n\nchar *strdup_len(const char *str, int len)\n{\n    char *p = malloc(len + 1);\n    memcpy(p, str, len);\n    p[len] = '\\0';\n    return p;\n}\n\nstatic inline int str_equal(const char *a, const char *b) {\n    return !strcmp(a, b);\n}\n\nchar *str_append(char **pp, const char *sep, const char *str) {\n    char *res, *p;\n    size_t len = 0;\n    p = *pp;\n    if (p) {\n        len = strlen(p) + strlen(sep);\n    }\n    res = malloc(len + strlen(str) + 1);\n    if (p) {\n        strcpy(res, p);\n        strcat(res, sep);\n    }\n    strcpy(res + len, str);\n    free(p);\n    return *pp = res;\n}\n\nchar *str_strip(char *p)\n{\n    size_t len = strlen(p);\n    while (len > 0 && isspace((unsigned char)p[len - 1]))\n        p[--len] = '\\0';\n    while (isspace((unsigned char)*p))\n        p++;\n    return p;\n}\n\nint has_prefix(const char *str, const char *prefix)\n{\n    return !strncmp(str, prefix, strlen(prefix));\n}\n\nchar *skip_prefix(const char *str, const char *prefix)\n{\n    int i;\n    for (i = 0;; i++) {\n        if (prefix[i] == '\\0') {  /* skip the prefix */\n            str += i;\n            break;\n        }\n        if (str[i] != prefix[i])\n            break;\n    }\n    return (char *)str;\n}\n\nchar *get_basename(const char *filename)\n{\n    char *p;\n\n    p = strrchr(filename, '/');\n    if (!p)\n        return NULL;\n    return strdup_len(filename, p - filename);\n}\n\nchar *compose_path(const char *path, const char *name)\n{\n    int path_len, name_len;\n    char *d, *q;\n\n    if (!path || path[0] == '\\0' || *name == '/') {\n        d = strdup(name);\n    } else {\n        path_len = strlen(path);\n        name_len = strlen(name);\n        d = malloc(path_len + 1 + name_len + 1);\n        if (d) {\n            q = d;\n            memcpy(q, path, path_len);\n            q += path_len;\n            if (path[path_len - 1] != '/')\n                *q++ = '/';\n            memcpy(q, name, name_len + 1);\n        }\n    }\n    return d;\n}\n\nint namelist_cmp(const char *a, const char *b)\n{\n    /* compare strings in modified lexicographical order */\n    for (;;) {\n        int ca = (unsigned char)*a++;\n        int cb = (unsigned char)*b++;\n        if (isdigit(ca) && isdigit(cb)) {\n            int na = ca - '0';\n            int nb = cb - '0';\n            while (isdigit(ca = (unsigned char)*a++))\n                na = na * 10 + ca - '0';\n            while (isdigit(cb = (unsigned char)*b++))\n                nb = nb * 10 + cb - '0';\n            if (na < nb)\n                return -1;\n            if (na > nb)\n                return +1;\n        }\n        if (ca < cb)\n            return -1;\n        if (ca > cb)\n            return +1;\n        if (ca == '\\0')\n            return 0;\n    }\n}\n\nint namelist_cmp_indirect(const void *a, const void *b)\n{\n    return namelist_cmp(*(const char **)a, *(const char **)b);\n}\n\nvoid namelist_sort(namelist_t *lp)\n{\n    int i, count;\n    if (lp->count > 1) {\n        qsort(lp->array, lp->count, sizeof(*lp->array), namelist_cmp_indirect);\n        /* remove duplicates */\n        for (count = i = 1; i < lp->count; i++) {\n            if (namelist_cmp(lp->array[count - 1], lp->array[i]) == 0) {\n                free(lp->array[i]);\n            } else {\n                lp->array[count++] = lp->array[i];\n            }\n        }\n        lp->count = count;\n    }\n    lp->sorted = 1;\n}\n\nint namelist_find(namelist_t *lp, const char *name)\n{\n    int a, b, m, cmp;\n\n    if (!lp->sorted) {\n        namelist_sort(lp);\n    }\n    for (a = 0, b = lp->count; a < b;) {\n        m = a + (b - a) / 2;\n        cmp = namelist_cmp(lp->array[m], name);\n        if (cmp < 0)\n            a = m + 1;\n        else if (cmp > 0)\n            b = m;\n        else\n            return m;\n    }\n    return -1;\n}\n\nvoid namelist_add(namelist_t *lp, const char *base, const char *name)\n{\n    char *s;\n\n    s = compose_path(base, name);\n    if (!s)\n        goto fail;\n    if (lp->count == lp->size) {\n        size_t newsize = lp->size + (lp->size >> 1) + 4;\n        char **a = realloc(lp->array, sizeof(lp->array[0]) * newsize);\n        if (!a)\n            goto fail;\n        lp->array = a;\n        lp->size = newsize;\n    }\n    lp->array[lp->count] = s;\n    lp->count++;\n    return;\nfail:\n    fatal(1, \"allocation failure\\n\");\n}\n\nvoid namelist_load(namelist_t *lp, const char *filename)\n{\n    char buf[1024];\n    char *base_name;\n    FILE *f;\n\n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror_exit(1, filename);\n    }\n    base_name = get_basename(filename);\n\n    while (fgets(buf, sizeof(buf), f) != NULL) {\n        char *p = str_strip(buf);\n        if (*p == '#' || *p == ';' || *p == '\\0')\n            continue;  /* line comment */\n        \n        namelist_add(lp, base_name, p);\n    }\n    free(base_name);\n    fclose(f);\n}\n\nvoid namelist_add_from_error_file(namelist_t *lp, const char *file)\n{\n    const char *p, *p0;\n    char *pp;\n\n    for (p = file; (p = strstr(p, \".js:\")) != NULL; p++) {\n        for (p0 = p; p0 > file && p0[-1] != '\\n'; p0--)\n            continue;\n        pp = strdup_len(p0, p + 3 - p0);\n        namelist_add(lp, NULL, pp);\n        free(pp);\n    }\n}\n\nvoid namelist_free(namelist_t *lp)\n{\n    while (lp->count > 0) {\n        free(lp->array[--lp->count]);\n    }\n    free(lp->array);\n    lp->array = NULL;\n    lp->size = 0;\n}\n\nstatic int add_test_file(const char *filename, const struct stat *ptr, int flag)\n{\n    namelist_t *lp = &test_list;\n    if (has_suffix(filename, \".js\") && !has_suffix(filename, \"_FIXTURE.js\"))\n        namelist_add(lp, NULL, filename);\n    return 0;\n}\n\n/* find js files from the directory tree and sort the list */\nstatic void enumerate_tests(const char *path)\n{\n    namelist_t *lp = &test_list;\n    int start = lp->count;\n    ftw(path, add_test_file, 100);\n    qsort(lp->array + start, lp->count - start, sizeof(*lp->array),\n          namelist_cmp_indirect);\n}\n\nstatic JSValue js_print(JSContext *ctx, JSValueConst this_val,\n                        int argc, JSValueConst *argv)\n{\n    int i;\n    const char *str;\n\n    if (outfile) {\n        for (i = 0; i < argc; i++) {\n            if (i != 0)\n                fputc(' ', outfile);\n            str = JS_ToCString(ctx, argv[i]);\n            if (!str)\n                return JS_EXCEPTION;\n            if (!strcmp(str, \"Test262:AsyncTestComplete\")) {\n                async_done++;\n            } else if (strstart(str, \"Test262:AsyncTestFailure\", NULL)) {\n                async_done = 2; /* force an error */\n            }\n            fputs(str, outfile);\n            JS_FreeCString(ctx, str);\n        }\n        fputc('\\n', outfile);\n    }\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_detachArrayBuffer(JSContext *ctx, JSValue this_val,\n                                    int argc, JSValue *argv)\n{\n    JS_DetachArrayBuffer(ctx, argv[0]);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_evalScript(JSContext *ctx, JSValue this_val,\n                             int argc, JSValue *argv)\n{\n    const char *str;\n    size_t len;\n    JSValue ret;\n    str = JS_ToCStringLen(ctx, &len, argv[0]);\n    if (!str)\n        return JS_EXCEPTION;\n    ret = JS_Eval(ctx, str, len, \"<evalScript>\", JS_EVAL_TYPE_GLOBAL);\n    JS_FreeCString(ctx, str);\n    return ret;\n}\n\n#ifdef CONFIG_AGENT\n\n#include <pthread.h>\n\ntypedef struct {\n    struct list_head link;\n    pthread_t tid;\n    char *script;\n    JSValue broadcast_func;\n    BOOL broadcast_pending;\n    JSValue broadcast_sab; /* in the main context */\n    uint8_t *broadcast_sab_buf;\n    size_t broadcast_sab_size;\n    int32_t broadcast_val;\n} Test262Agent;\n\ntypedef struct {\n    struct list_head link;\n    char *str;\n} AgentReport;\n\nstatic JSValue add_helpers1(JSContext *ctx);\nstatic void add_helpers(JSContext *ctx);\n\nstatic pthread_mutex_t agent_mutex = PTHREAD_MUTEX_INITIALIZER;\nstatic pthread_cond_t agent_cond = PTHREAD_COND_INITIALIZER;\n/* list of Test262Agent.link */\nstatic struct list_head agent_list = LIST_HEAD_INIT(agent_list);\n\nstatic pthread_mutex_t report_mutex = PTHREAD_MUTEX_INITIALIZER;\n/* list of AgentReport.link */\nstatic struct list_head report_list = LIST_HEAD_INIT(report_list);\n\nstatic void *agent_start(void *arg)\n{\n    Test262Agent *agent = arg;\n    JSRuntime *rt;\n    JSContext *ctx;\n    JSValue ret_val;\n    int ret;\n    \n    rt = JS_NewRuntime();\n    if (rt == NULL) {\n        fatal(1, \"JS_NewRuntime failure\");\n    }        \n    ctx = JS_NewContext(rt);\n    if (ctx == NULL) {\n        JS_FreeRuntime(rt);\n        fatal(1, \"JS_NewContext failure\");\n    }\n    JS_SetContextOpaque(ctx, agent);\n    JS_SetRuntimeInfo(rt, \"agent\");\n    JS_SetCanBlock(rt, TRUE);\n    \n    add_helpers(ctx);\n    ret_val = JS_Eval(ctx, agent->script, strlen(agent->script),\n                      \"<evalScript>\", JS_EVAL_TYPE_GLOBAL);\n    free(agent->script);\n    agent->script = NULL;\n    if (JS_IsException(ret_val))\n        js_std_dump_error(ctx);\n    JS_FreeValue(ctx, ret_val);\n    \n    for(;;) {\n        JSContext *ctx1;\n        ret = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1);\n        if (ret < 0) {\n            js_std_dump_error(ctx);\n            break;\n        } else if (ret == 0) {\n            if (JS_IsUndefined(agent->broadcast_func)) {\n                break;\n            } else {\n                JSValue args[2];\n                \n                pthread_mutex_lock(&agent_mutex);\n                while (!agent->broadcast_pending) {\n                    pthread_cond_wait(&agent_cond, &agent_mutex);\n                }\n                \n                agent->broadcast_pending = FALSE;\n                pthread_cond_signal(&agent_cond);\n\n                pthread_mutex_unlock(&agent_mutex);\n\n                args[0] = JS_NewArrayBuffer(ctx, agent->broadcast_sab_buf,\n                                            agent->broadcast_sab_size,\n                                            NULL, NULL, TRUE);\n                args[1] = JS_NewInt32(ctx, agent->broadcast_val);\n                ret_val = JS_Call(ctx, agent->broadcast_func, JS_UNDEFINED,\n                                  2, (JSValueConst *)args);\n                JS_FreeValue(ctx, args[0]);\n                JS_FreeValue(ctx, args[1]);\n                if (JS_IsException(ret_val))\n                    js_std_dump_error(ctx);\n                JS_FreeValue(ctx, ret_val);\n                JS_FreeValue(ctx, agent->broadcast_func);\n                agent->broadcast_func = JS_UNDEFINED;\n            }\n        }\n    }\n    JS_FreeValue(ctx, agent->broadcast_func);\n\n    JS_FreeContext(ctx);\n    JS_FreeRuntime(rt);\n    return NULL;\n}\n\nstatic JSValue js_agent_start(JSContext *ctx, JSValue this_val,\n                              int argc, JSValue *argv)\n{\n    const char *script;\n    Test262Agent *agent;\n\n    if (JS_GetContextOpaque(ctx) != NULL)\n        return JS_ThrowTypeError(ctx, \"cannot be called inside an agent\");\n    \n    script = JS_ToCString(ctx, argv[0]);\n    if (!script)\n        return JS_EXCEPTION;\n    agent = malloc(sizeof(*agent));\n    memset(agent, 0, sizeof(*agent));\n    agent->broadcast_func = JS_UNDEFINED;\n    agent->broadcast_sab = JS_UNDEFINED;\n    agent->script = strdup(script);\n    JS_FreeCString(ctx, script);\n    list_add_tail(&agent->link, &agent_list);\n    pthread_create(&agent->tid, NULL, agent_start, agent);\n    return JS_UNDEFINED;\n}\n\nstatic void js_agent_free(JSContext *ctx)\n{\n    struct list_head *el, *el1;\n    Test262Agent *agent;\n    \n    list_for_each_safe(el, el1, &agent_list) {\n        agent = list_entry(el, Test262Agent, link);\n        pthread_join(agent->tid, NULL);\n        JS_FreeValue(ctx, agent->broadcast_sab);\n        list_del(&agent->link);\n        free(agent);\n    }\n}\n \nstatic JSValue js_agent_leaving(JSContext *ctx, JSValue this_val,\n                                int argc, JSValue *argv)\n{\n    Test262Agent *agent = JS_GetContextOpaque(ctx);\n    if (!agent)\n        return JS_ThrowTypeError(ctx, \"must be called inside an agent\");\n    /* nothing to do */\n    return JS_UNDEFINED;\n}\n\nstatic BOOL is_broadcast_pending(void)\n{\n    struct list_head *el;\n    Test262Agent *agent;\n    list_for_each(el, &agent_list) {\n        agent = list_entry(el, Test262Agent, link);\n        if (agent->broadcast_pending)\n            return TRUE;\n    }\n    return FALSE;\n}\n\nstatic JSValue js_agent_broadcast(JSContext *ctx, JSValue this_val,\n                                  int argc, JSValue *argv)\n{\n    JSValueConst sab = argv[0];\n    struct list_head *el;\n    Test262Agent *agent;\n    uint8_t *buf;\n    size_t buf_size;\n    int32_t val;\n    \n    if (JS_GetContextOpaque(ctx) != NULL)\n        return JS_ThrowTypeError(ctx, \"cannot be called inside an agent\");\n    \n    buf = JS_GetArrayBuffer(ctx, &buf_size, sab);\n    if (!buf)\n        return JS_EXCEPTION;\n    if (JS_ToInt32(ctx, &val, argv[1]))\n        return JS_EXCEPTION;\n    \n    /* broadcast the values and wait until all agents have started\n       calling their callbacks */\n    pthread_mutex_lock(&agent_mutex);\n    list_for_each(el, &agent_list) {\n        agent = list_entry(el, Test262Agent, link);\n        agent->broadcast_pending = TRUE;\n        /* the shared array buffer is used by the thread, so increment\n           its refcount */\n        agent->broadcast_sab = JS_DupValue(ctx, sab);\n        agent->broadcast_sab_buf = buf;\n        agent->broadcast_sab_size = buf_size;\n        agent->broadcast_val = val;\n    }\n    pthread_cond_broadcast(&agent_cond);\n\n    while (is_broadcast_pending()) {\n        pthread_cond_wait(&agent_cond, &agent_mutex);\n    }\n    pthread_mutex_unlock(&agent_mutex);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_agent_receiveBroadcast(JSContext *ctx, JSValue this_val,\n                                         int argc, JSValue *argv)\n{\n    Test262Agent *agent = JS_GetContextOpaque(ctx);\n    if (!agent)\n        return JS_ThrowTypeError(ctx, \"must be called inside an agent\");\n    if (!JS_IsFunction(ctx, argv[0]))\n        return JS_ThrowTypeError(ctx, \"expecting function\");\n    JS_FreeValue(ctx, agent->broadcast_func);\n    agent->broadcast_func = JS_DupValue(ctx, argv[0]);\n    return JS_UNDEFINED;\n}\n\nstatic JSValue js_agent_sleep(JSContext *ctx, JSValue this_val,\n                              int argc, JSValue *argv)\n{\n    uint32_t duration;\n    if (JS_ToUint32(ctx, &duration, argv[0]))\n        return JS_EXCEPTION;\n    usleep(duration * 1000);\n    return JS_UNDEFINED;\n}\n\nstatic int64_t get_clock_ms(void)\n{\n    struct timespec ts;\n    clock_gettime(CLOCK_MONOTONIC, &ts);\n    return (uint64_t)ts.tv_sec * 1000 + (ts.tv_nsec / 1000000);\n}\n\nstatic JSValue js_agent_monotonicNow(JSContext *ctx, JSValue this_val,\n                                     int argc, JSValue *argv)\n{\n    return JS_NewInt64(ctx, get_clock_ms());\n}\n\nstatic JSValue js_agent_getReport(JSContext *ctx, JSValue this_val,\n                                  int argc, JSValue *argv)\n{\n    AgentReport *rep;\n    JSValue ret;\n\n    pthread_mutex_lock(&report_mutex);\n    if (list_empty(&report_list)) {\n        rep = NULL;\n    } else {\n        rep = list_entry(report_list.next, AgentReport, link);\n        list_del(&rep->link);\n    }\n    pthread_mutex_unlock(&report_mutex);\n    if (rep) {\n        ret = JS_NewString(ctx, rep->str);\n        free(rep->str);\n        free(rep);\n    } else {\n        ret = JS_NULL;\n    }\n    return ret;\n}\n\nstatic JSValue js_agent_report(JSContext *ctx, JSValue this_val,\n                               int argc, JSValue *argv)\n{\n    const char *str;\n    AgentReport *rep;\n\n    str = JS_ToCString(ctx, argv[0]);\n    if (!str)\n        return JS_EXCEPTION;\n    rep = malloc(sizeof(*rep));\n    rep->str = strdup(str);\n    JS_FreeCString(ctx, str);\n    \n    pthread_mutex_lock(&report_mutex);\n    list_add_tail(&rep->link, &report_list);\n    pthread_mutex_unlock(&report_mutex);\n    return JS_UNDEFINED;\n}\n\nstatic const JSCFunctionListEntry js_agent_funcs[] = {\n    /* only in main */\n    JS_CFUNC_DEF(\"start\", 1, js_agent_start ),\n    JS_CFUNC_DEF(\"getReport\", 0, js_agent_getReport ),\n    JS_CFUNC_DEF(\"broadcast\", 2, js_agent_broadcast ),\n    /* only in agent */\n    JS_CFUNC_DEF(\"report\", 1, js_agent_report ),\n    JS_CFUNC_DEF(\"leaving\", 0, js_agent_leaving ),\n    JS_CFUNC_DEF(\"receiveBroadcast\", 1, js_agent_receiveBroadcast ),\n    /* in both */\n    JS_CFUNC_DEF(\"sleep\", 1, js_agent_sleep ),\n    JS_CFUNC_DEF(\"monotonicNow\", 0, js_agent_monotonicNow ),\n};\n    \nstatic JSValue js_new_agent(JSContext *ctx)\n{\n    JSValue agent;\n    agent = JS_NewObject(ctx);\n    JS_SetPropertyFunctionList(ctx, agent, js_agent_funcs,\n                               countof(js_agent_funcs));\n    return agent;\n}\n#endif\n\nstatic JSValue js_createRealm(JSContext *ctx, JSValue this_val,\n                              int argc, JSValue *argv)\n{\n    JSContext *ctx1;\n    JSValue ret;\n    \n    ctx1 = JS_NewContext(JS_GetRuntime(ctx));\n    if (!ctx1)\n        return JS_ThrowOutOfMemory(ctx);\n    ret = add_helpers1(ctx1);\n    /* ctx1 has a refcount so it stays alive */\n    JS_FreeContext(ctx1);\n    return ret;\n}\n\nstatic JSValue js_IsHTMLDDA(JSContext *ctx, JSValue this_val,\n                            int argc, JSValue *argv)\n{\n    return JS_NULL;\n}\n\nstatic JSValue add_helpers1(JSContext *ctx)\n{\n    JSValue global_obj;\n    JSValue obj262, obj;\n    \n    global_obj = JS_GetGlobalObject(ctx);\n\n    JS_SetPropertyStr(ctx, global_obj, \"print\",\n                      JS_NewCFunction(ctx, js_print, \"print\", 1));\n\n    /* $262 special object used by the tests */\n    obj262 = JS_NewObject(ctx);\n    JS_SetPropertyStr(ctx, obj262, \"detachArrayBuffer\",\n                      JS_NewCFunction(ctx, js_detachArrayBuffer,\n                                      \"detachArrayBuffer\", 1));\n    JS_SetPropertyStr(ctx, obj262, \"evalScript\",\n                      JS_NewCFunction(ctx, js_evalScript,\n                                      \"evalScript\", 1));\n    JS_SetPropertyStr(ctx, obj262, \"codePointRange\",\n                      JS_NewCFunction(ctx, js_string_codePointRange,\n                                      \"codePointRange\", 2));\n#ifdef CONFIG_AGENT\n    JS_SetPropertyStr(ctx, obj262, \"agent\", js_new_agent(ctx));\n#endif\n\n    JS_SetPropertyStr(ctx, obj262, \"global\",\n                      JS_DupValue(ctx, global_obj));\n    JS_SetPropertyStr(ctx, obj262, \"createRealm\",\n                      JS_NewCFunction(ctx, js_createRealm,\n                                      \"createRealm\", 0));\n    obj = JS_NewCFunction(ctx, js_IsHTMLDDA, \"IsHTMLDDA\", 0);\n    JS_SetIsHTMLDDA(ctx, obj);\n    JS_SetPropertyStr(ctx, obj262, \"IsHTMLDDA\", obj);\n\n    JS_SetPropertyStr(ctx, global_obj, \"$262\", JS_DupValue(ctx, obj262));\n    \n    JS_FreeValue(ctx, global_obj);\n    return obj262;\n}\n\nstatic void add_helpers(JSContext *ctx)\n{\n    JS_FreeValue(ctx, add_helpers1(ctx));\n}\n\nstatic char *load_file(const char *filename, size_t *lenp)\n{\n    char *buf;\n    size_t buf_len;\n    buf = (char *)js_load_file(NULL, &buf_len, filename);\n    if (!buf)\n        perror_exit(1, filename);\n    if (lenp)\n        *lenp = buf_len;\n    return buf;\n}\n\nstatic JSModuleDef *js_module_loader_test(JSContext *ctx,\n                                          const char *module_name, void *opaque)\n{\n    size_t buf_len;\n    uint8_t *buf;\n    JSModuleDef *m;\n    JSValue func_val;\n    \n    buf = js_load_file(ctx, &buf_len, module_name);\n    if (!buf) {\n        JS_ThrowReferenceError(ctx, \"could not load module filename '%s'\",\n                               module_name);\n        return NULL;\n    }\n    \n    /* compile the module */\n    func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name,\n                       JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);\n    js_free(ctx, buf);\n    if (JS_IsException(func_val))\n        return NULL;\n    /* the module is already referenced, so we must free it */\n    m = JS_VALUE_GET_PTR(func_val);\n    JS_FreeValue(ctx, func_val);\n    return m;\n}\n\nint is_line_sep(char c)\n{\n    return (c == '\\0' || c == '\\n' || c == '\\r');\n}\n\nchar *find_line(const char *str, const char *line)\n{\n    if (str) {\n        const char *p;\n        int len = strlen(line);\n        for (p = str; (p = strstr(p, line)) != NULL; p += len + 1) {\n            if ((p == str || is_line_sep(p[-1])) && is_line_sep(p[len]))\n                return (char *)p;\n        }\n    }\n    return NULL;\n}\n\nint is_word_sep(char c)\n{\n    return (c == '\\0' || isspace((unsigned char)c) || c == ',');\n}\n\nchar *find_word(const char *str, const char *word)\n{\n    const char *p;\n    int len = strlen(word);\n    if (str && len) {\n        for (p = str; (p = strstr(p, word)) != NULL; p += len) {\n            if ((p == str || is_word_sep(p[-1])) && is_word_sep(p[len]))\n                return (char *)p;\n        }\n    }\n    return NULL;\n}\n\n/* handle exclude directories */\nvoid update_exclude_dirs(void)\n{\n    namelist_t *lp = &test_list;\n    namelist_t *ep = &exclude_list;\n    namelist_t *dp = &exclude_dir_list;\n    char *name;\n    int i, j, count;\n\n    /* split directpries from exclude_list */\n    for (count = i = 0; i < ep->count; i++) {\n        name = ep->array[i];\n        if (has_suffix(name, \"/\")) {\n            namelist_add(dp, NULL, name);\n            free(name);\n        } else {\n            ep->array[count++] = name;\n        }\n    }\n    ep->count = count;\n\n    namelist_sort(dp);\n\n    /* filter out excluded directories */\n    for (count = i = 0; i < lp->count; i++) {\n        name = lp->array[i];\n        for (j = 0; j < dp->count; j++) {\n            if (has_prefix(name, dp->array[j])) {\n                test_excluded++;\n                free(name);\n                name = NULL;\n                break;\n            }\n        }\n        if (name) {\n            lp->array[count++] = name;\n        }\n    }\n    lp->count = count;\n}\n\nvoid load_config(const char *filename)\n{\n    char buf[1024];\n    FILE *f;\n    char *base_name;\n    enum {\n        SECTION_NONE = 0,\n        SECTION_CONFIG,\n        SECTION_EXCLUDE,\n        SECTION_FEATURES,\n        SECTION_TESTS,\n    } section = SECTION_NONE;\n    int lineno = 0;\n\n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror_exit(1, filename);\n    }\n    base_name = get_basename(filename);\n    \n    while (fgets(buf, sizeof(buf), f) != NULL) {\n        char *p, *q;\n        lineno++;\n        p = str_strip(buf);\n        if (*p == '#' || *p == ';' || *p == '\\0')\n            continue;  /* line comment */\n        \n        if (*p == \"[]\"[0]) {\n            /* new section */\n            p++;\n            p[strcspn(p, \"]\")] = '\\0';\n            if (str_equal(p, \"config\"))\n                section = SECTION_CONFIG;\n            else if (str_equal(p, \"exclude\"))\n                section = SECTION_EXCLUDE;\n            else if (str_equal(p, \"features\"))\n                section = SECTION_FEATURES;\n            else if (str_equal(p, \"tests\"))\n                section = SECTION_TESTS;\n            else\n                section = SECTION_NONE;\n            continue;\n        }\n        q = strchr(p, '=');\n        if (q) {\n            /* setting: name=value */\n            *q++ = '\\0';\n            q = str_strip(q);\n        }\n        switch (section) {\n        case SECTION_CONFIG:\n            if (!q) {\n                printf(\"%s:%d: syntax error\\n\", filename, lineno);\n                continue;\n            }\n            if (str_equal(p, \"style\")) {\n                new_style = str_equal(q, \"new\");\n                continue;\n            }\n            if (str_equal(p, \"testdir\")) {\n                char *testdir = compose_path(base_name, q);\n                enumerate_tests(testdir);\n                free(testdir);\n                continue;\n            }\n            if (str_equal(p, \"harnessdir\")) {\n                harness_dir = compose_path(base_name, q);\n                continue;\n            }\n            if (str_equal(p, \"harnessexclude\")) {\n                str_append(&harness_exclude, \" \", q);\n                continue;\n            }\n            if (str_equal(p, \"features\")) {\n                str_append(&harness_features, \" \", q);\n                continue;\n            }\n            if (str_equal(p, \"skip-features\")) {\n                str_append(&harness_skip_features, \" \", q);\n                continue;\n            }\n            if (str_equal(p, \"mode\")) {\n                if (str_equal(q, \"default\") || str_equal(q, \"default-nostrict\"))\n                    test_mode = TEST_DEFAULT_NOSTRICT;\n                else if (str_equal(q, \"default-strict\"))\n                    test_mode = TEST_DEFAULT_STRICT;\n                else if (str_equal(q, \"nostrict\"))\n                    test_mode = TEST_NOSTRICT;\n                else if (str_equal(q, \"strict\"))\n                    test_mode = TEST_STRICT;\n                else if (str_equal(q, \"all\") || str_equal(q, \"both\"))\n                    test_mode = TEST_ALL;\n                else \n                    fatal(2, \"unknown test mode: %s\", q);\n                continue;\n            }\n            if (str_equal(p, \"strict\")) {\n                if (str_equal(q, \"skip\") || str_equal(q, \"no\"))\n                    test_mode = TEST_NOSTRICT;\n                continue;\n            }\n            if (str_equal(p, \"nostrict\")) {\n                if (str_equal(q, \"skip\") || str_equal(q, \"no\"))\n                    test_mode = TEST_STRICT;\n                continue;\n            }\n            if (str_equal(p, \"async\")) {\n                skip_async = !str_equal(q, \"yes\");\n                continue;\n            }\n            if (str_equal(p, \"module\")) {\n                skip_module = !str_equal(q, \"yes\");\n                continue;\n            }\n            if (str_equal(p, \"verbose\")) {\n                verbose = str_equal(q, \"yes\");\n                continue;\n            }\n            if (str_equal(p, \"errorfile\")) {\n                error_filename = compose_path(base_name, q);\n                continue;\n            }\n            if (str_equal(p, \"excludefile\")) {\n                char *path = compose_path(base_name, q);\n                namelist_load(&exclude_list, path);\n                free(path);\n                continue;\n            }\n            if (str_equal(p, \"reportfile\")) {\n                report_filename = compose_path(base_name, q);\n                continue;\n            }\n        case SECTION_EXCLUDE:\n            namelist_add(&exclude_list, base_name, p);\n            break;\n        case SECTION_FEATURES:\n            if (!q || str_equal(q, \"yes\"))\n                str_append(&harness_features, \" \", p);\n            else\n                str_append(&harness_skip_features, \" \", p);\n            break;\n        case SECTION_TESTS:\n            namelist_add(&test_list, base_name, p);\n            break;\n        default:\n            /* ignore settings in other sections */\n            break;\n        }\n    }\n    fclose(f);\n    free(base_name);\n}\n\nchar *find_error(const char *filename, int *pline, int is_strict)\n{\n    if (error_file) {\n        size_t len = strlen(filename);\n        const char *p, *q, *r;\n        int line;\n\n        for (p = error_file; (p = strstr(p, filename)) != NULL; p += len) {\n            if ((p == error_file || p[-1] == '\\n' || p[-1] == '(') && p[len] == ':') {\n                q = p + len;\n                line = 1;\n                if (*q == ':') {\n                    line = strtol(q + 1, (char**)&q, 10);\n                    if (*q == ':')\n                        q++;\n                }\n                while (*q == ' ') {\n                    q++;\n                }\n                /* check strict mode indicator */\n                if (!strstart(q, \"strict mode: \", &q) != !is_strict)\n                    continue;\n                r = q = skip_prefix(q, \"unexpected error: \");\n                r += strcspn(r, \"\\n\");\n                while (r[0] == '\\n' && r[1] && strncmp(r + 1, filename, 8)) {\n                    r++;\n                    r += strcspn(r, \"\\n\");\n                }\n                if (pline)\n                    *pline = line;\n                return strdup_len(q, r - q);\n            }\n        }\n    }\n    return NULL;\n}\n\nint skip_comments(const char *str, int line, int *pline)\n{\n    const char *p;\n    int c;\n\n    p = str;\n    while ((c = (unsigned char)*p++) != '\\0') {\n        if (isspace(c)) {\n            if (c == '\\n')\n                line++;\n            continue;\n        }\n        if (c == '/' && *p == '/') {\n            while (*++p && *p != '\\n')\n                continue;\n            continue;\n        }\n        if (c == '/' && *p == '*') {\n            for (p += 1; *p; p++) {\n                if (*p == '\\n') {\n                    line++;\n                    continue;\n                }\n                if (*p == '*' && p[1] == '/') {\n                    p += 2;\n                    break;\n                }\n            }\n            continue;\n        }\n        break;\n    }\n    if (pline)\n        *pline = line;\n\n    return p - str;\n}\n\nint longest_match(const char *str, const char *find, int pos, int *ppos, int line, int *pline)\n{\n    int len, maxlen;\n\n    maxlen = 0;\n    \n    if (*find) {\n        const char *p;\n        for (p = str + pos; *p; p++) {\n            if (*p == *find) {\n                for (len = 1; p[len] && p[len] == find[len]; len++)\n                    continue;\n                if (len > maxlen) {\n                    maxlen = len;\n                    if (ppos)\n                        *ppos = p - str;\n                    if (pline)\n                        *pline = line;\n                    if (!find[len])\n                        break;\n                }\n            }\n            if (*p == '\\n')\n                line++;\n        }\n    }\n    return maxlen;\n}\n\nstatic int eval_buf(JSContext *ctx, const char *buf, size_t buf_len,\n                    const char *filename, int is_test, int is_negative,\n                    const char *error_type, FILE *outfile, int eval_flags,\n                    int is_async)\n{\n    JSValue res_val, exception_val;\n    int ret, error_line, pos, pos_line;\n    BOOL is_error, has_error_line;\n    const char *error_name;\n    \n    pos = skip_comments(buf, 1, &pos_line);\n    error_line = pos_line;\n    has_error_line = FALSE;\n    exception_val = JS_UNDEFINED;\n    error_name = NULL;\n\n    async_done = 0; /* counter of \"Test262:AsyncTestComplete\" messages */\n\n    res_val = JS_Eval(ctx, buf, buf_len, filename, eval_flags);\n\n    if (is_async && !JS_IsException(res_val)) {\n        JS_FreeValue(ctx, res_val);\n        for(;;) {\n            JSContext *ctx1;\n            ret = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1);\n            if (ret < 0) {\n                res_val = JS_EXCEPTION;\n                break;\n            } else if (ret == 0) {\n                /* test if the test called $DONE() once */\n                if (async_done != 1) {\n                    res_val = JS_ThrowTypeError(ctx, \"$DONE() not called\");\n                } else {\n                    res_val = JS_UNDEFINED;\n                }\n                break;\n            }\n        }\n    }\n\n    if (JS_IsException(res_val)) {\n        exception_val = JS_GetException(ctx);\n        is_error = JS_IsError(ctx, exception_val);\n        /* XXX: should get the filename and line number */\n        if (outfile) {\n            if (!is_error)\n                fprintf(outfile, \"%sThrow: \", (eval_flags & JS_EVAL_FLAG_STRICT) ?\n                        \"strict mode: \" : \"\");\n            js_print(ctx, JS_NULL, 1, &exception_val);\n        }\n        if (is_error) {\n            JSValue name, stack;\n            const char *stack_str;\n        \n            name = JS_GetPropertyStr(ctx, exception_val, \"name\");\n            error_name = JS_ToCString(ctx, name);\n            stack = JS_GetPropertyStr(ctx, exception_val, \"stack\");\n            if (!JS_IsUndefined(stack)) {\n                stack_str = JS_ToCString(ctx, stack);\n                if (stack_str) {\n                    const char *p;\n                    int len;\n                    \n                    if (outfile)\n                        fprintf(outfile, \"%s\", stack_str);\n                    \n                    len = strlen(filename);\n                    p = strstr(stack_str, filename);\n                    if (p != NULL && p[len] == ':') {\n                        error_line = atoi(p + len + 1);\n                        has_error_line = TRUE;\n                    }\n                    JS_FreeCString(ctx, stack_str);\n                }\n            }\n            JS_FreeValue(ctx, stack);\n            JS_FreeValue(ctx, name);\n        }\n        if (is_negative) {\n            ret = 0;\n            if (error_type) {\n                char *error_class;\n                const char *msg;\n            \n                msg = JS_ToCString(ctx, exception_val);\n                error_class = strdup_len(msg, strcspn(msg, \":\"));\n                if (!str_equal(error_class, error_type))\n                    ret = -1;\n                free(error_class);\n                JS_FreeCString(ctx, msg);\n            }\n        } else {\n            ret = -1;\n        }\n    } else {\n        if (is_negative)\n            ret = -1;\n        else\n            ret = 0;\n    }\n\n    if (verbose && is_test) {\n        JSValue msg_val = JS_UNDEFINED;\n        const char *msg = NULL;\n        int s_line;\n        char *s = find_error(filename, &s_line, eval_flags & JS_EVAL_FLAG_STRICT);\n        const char *strict_mode = (eval_flags & JS_EVAL_FLAG_STRICT) ? \"strict mode: \" : \"\";\n\n        if (!JS_IsUndefined(exception_val)) {\n            msg_val = JS_ToString(ctx, exception_val);\n            msg = JS_ToCString(ctx, msg_val);\n        }\n        if (is_negative) {  // expect error\n            if (ret == 0) {\n                if (msg && s &&\n                    (str_equal(s, \"expected error\") ||\n                     strstart(s, \"unexpected error type:\", NULL) ||\n                     str_equal(s, msg))) {     // did not have error yet\n                    if (!has_error_line) {\n                        longest_match(buf, msg, pos, &pos, pos_line, &error_line);\n                    }\n                    printf(\"%s:%d: %sOK, now has error %s\\n\",\n                           filename, error_line, strict_mode, msg);\n                    fixed_errors++;\n                }\n            } else {\n                if (!s) {   // not yet reported\n                    if (msg) {\n                        fprintf(error_out, \"%s:%d: %sunexpected error type: %s\\n\",\n                                filename, error_line, strict_mode, msg);\n                    } else {\n                        fprintf(error_out, \"%s:%d: %sexpected error\\n\",\n                                filename, error_line, strict_mode);\n                    }\n                    new_errors++;\n                }\n            }\n        } else {            // should not have error\n            if (msg) {\n                if (!s || !str_equal(s, msg)) {\n                    if (!has_error_line) {\n                        char *p = skip_prefix(msg, \"Test262 Error: \");\n                        if (strstr(p, \"Test case returned non-true value!\")) {\n                            longest_match(buf, \"runTestCase\", pos, &pos, pos_line, &error_line);\n                        } else {\n                            longest_match(buf, p, pos, &pos, pos_line, &error_line);\n                        }\n                    }\n                    fprintf(error_out, \"%s:%d: %s%s%s\\n\", filename, error_line, strict_mode,\n                            error_file ? \"unexpected error: \" : \"\", msg);\n\n                    if (s && (!str_equal(s, msg) || error_line != s_line)) {\n                        printf(\"%s:%d: %sprevious error: %s\\n\", filename, s_line, strict_mode, s);\n                        changed_errors++;\n                    } else {\n                        new_errors++;\n                    }\n                }\n            } else {\n                if (s) {\n                    printf(\"%s:%d: %sOK, fixed error: %s\\n\", filename, s_line, strict_mode, s);\n                    fixed_errors++;\n                }\n            }\n        }\n        JS_FreeValue(ctx, msg_val);\n        JS_FreeCString(ctx, msg);\n        free(s);\n    }\n    JS_FreeCString(ctx, error_name);\n    JS_FreeValue(ctx, exception_val);\n    JS_FreeValue(ctx, res_val);\n    return ret;\n}\n\nstatic int eval_file(JSContext *ctx, const char *base, const char *p,\n                     int eval_flags)\n{\n    char *buf;\n    size_t buf_len;\n    char *filename = compose_path(base, p);\n\n    buf = load_file(filename, &buf_len);\n    if (!buf) {\n        warning(\"cannot load %s\", filename);\n        goto fail;\n    }\n    if (eval_buf(ctx, buf, buf_len, filename, FALSE, FALSE, NULL, stderr,\n                 eval_flags, FALSE)) {\n        warning(\"error evaluating %s\", filename);\n        goto fail;\n    }\n    free(buf);\n    free(filename);\n    return 0;\n\nfail:\n    free(buf);\n    free(filename);\n    return 1;\n}\n\nchar *extract_desc(const char *buf, char style)\n{\n    const char *p, *desc_start;\n    char *desc;\n    int len;\n    \n    p = buf;\n    while (*p != '\\0') {\n        if (p[0] == '/' && p[1] == '*' && p[2] == style && p[3] != '/') {\n            p += 3;\n            desc_start = p;\n            while (*p != '\\0' && (p[0] != '*' || p[1] != '/'))\n                p++;\n            if (*p == '\\0') {\n                warning(\"Expecting end of desc comment\");\n                return NULL;\n            }\n            len = p - desc_start;\n            desc = malloc(len + 1);\n            memcpy(desc, desc_start, len);\n            desc[len] = '\\0';\n            return desc;\n        } else {\n            p++;\n        }\n    }\n    return NULL;\n}\n\nstatic char *find_tag(char *desc, const char *tag, int *state)\n{\n    char *p;\n    p = strstr(desc, tag);\n    if (p) {\n        p += strlen(tag);\n        *state = 0;\n    }\n    return p;\n}\n\nstatic char *get_option(char **pp, int *state)\n{\n    char *p, *p0, *option = NULL;\n    if (*pp) {\n        for (p = *pp;; p++) {\n            switch (*p) {\n            case '[':\n                *state += 1;\n                continue;\n            case ']':\n                *state -= 1;\n                if (*state > 0)\n                    continue;\n                p = NULL;\n                break;\n            case ' ':\n            case '\\t':\n            case '\\r':\n            case ',':\n            case '-':\n                continue;\n            case '\\n':\n                if (*state > 0 || p[1] == ' ')\n                    continue;\n                p = NULL;\n                break;\n            case '\\0':\n                p = NULL;\n                break;\n            default:\n                p0 = p;\n                p += strcspn(p0, \" \\t\\r\\n,]\");\n                option = strdup_len(p0, p - p0);\n                break;\n            }\n            break;\n        }\n        *pp = p;\n    }\n    return option;\n}\n\nvoid update_stats(JSRuntime *rt, const char *filename) {\n    JSMemoryUsage stats;\n    JS_ComputeMemoryUsage(rt, &stats);\n    if (stats_count++ == 0) {\n        stats_avg = stats_all = stats_min = stats_max = stats;\n        stats_min_filename = strdup(filename);\n        stats_max_filename = strdup(filename);\n    } else {\n        if (stats_max.malloc_size < stats.malloc_size) {\n            stats_max = stats;\n            free(stats_max_filename);\n            stats_max_filename = strdup(filename);\n        }\n        if (stats_min.malloc_size > stats.malloc_size) {\n            stats_min = stats;\n            free(stats_min_filename);\n            stats_min_filename = strdup(filename);\n        }\n\n#define update(f)  stats_avg.f = (stats_all.f += stats.f) / stats_count\n        update(malloc_count);\n        update(malloc_size);\n        update(memory_used_count);\n        update(memory_used_size);\n        update(atom_count);\n        update(atom_size);\n        update(str_count);\n        update(str_size);\n        update(obj_count);\n        update(obj_size);\n        update(prop_count);\n        update(prop_size);\n        update(shape_count);\n        update(shape_size);\n        update(js_func_count);\n        update(js_func_size);\n        update(js_func_code_size);\n        update(js_func_pc2line_count);\n        update(js_func_pc2line_size);\n        update(c_func_count);\n        update(array_count);\n        update(fast_array_count);\n        update(fast_array_elements);\n    }\n#undef update\n}\n\nint run_test_buf(const char *filename, char *harness, namelist_t *ip,\n                 char *buf, size_t buf_len, const char* error_type,\n                 int eval_flags, BOOL is_negative, BOOL is_async,\n                 BOOL can_block)\n{\n    JSRuntime *rt;\n    JSContext *ctx;\n    int i, ret;\n        \n    rt = JS_NewRuntime();\n    if (rt == NULL) {\n        fatal(1, \"JS_NewRuntime failure\");\n    }        \n    ctx = JS_NewContext(rt);\n    if (ctx == NULL) {\n        JS_FreeRuntime(rt);\n        fatal(1, \"JS_NewContext failure\");\n    }\n    JS_SetRuntimeInfo(rt, filename);\n\n    JS_SetCanBlock(rt, can_block);\n    \n    /* loader for ES6 modules */\n    JS_SetModuleLoaderFunc(rt, NULL, js_module_loader_test, NULL);\n        \n    add_helpers(ctx);\n\n    for (i = 0; i < ip->count; i++) {\n        if (eval_file(ctx, harness, ip->array[i],\n                      JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_STRIP)) {\n            fatal(1, \"error including %s for %s\", ip->array[i], filename);\n        }\n    }\n\n    ret = eval_buf(ctx, buf, buf_len, filename, TRUE, is_negative,\n                   error_type, outfile, eval_flags, is_async);\n    ret = (ret != 0);\n        \n    if (dump_memory) {\n        update_stats(rt, filename);\n    }\n#ifdef CONFIG_AGENT\n    js_agent_free(ctx);\n#endif\n    JS_FreeContext(ctx);\n    JS_FreeRuntime(rt);\n\n    test_count++;\n    if (ret) {\n        test_failed++;\n        if (outfile) {\n            /* do not output a failure number to minimize diff */\n            fprintf(outfile, \"  FAILED\\n\");\n        }\n    }\n    return ret;\n}\n\nint run_test(const char *filename, int index)\n{\n    char harnessbuf[1024];\n    char *harness;\n    char *buf;\n    size_t buf_len;\n    char *desc, *p;\n    char *error_type;\n    int ret, eval_flags, use_strict, use_nostrict;\n    BOOL is_negative, is_nostrict, is_onlystrict, is_async, is_module, skip;\n    BOOL can_block;\n    namelist_t include_list = { 0 }, *ip = &include_list;\n    \n    is_nostrict = is_onlystrict = is_negative = is_async = is_module = skip = FALSE;\n    can_block = TRUE;\n    error_type = NULL;\n    buf = load_file(filename, &buf_len);\n\n    harness = harness_dir;\n\n    if (new_style) {\n        if (!harness) {\n            p = strstr(filename, \"test/\");\n            if (p) {\n                snprintf(harnessbuf, sizeof(harnessbuf), \"%.*s%s\",\n                         (int)(p - filename), filename, \"harness\");\n            }\n            harness = harnessbuf;\n        }\n        namelist_add(ip, NULL, \"sta.js\");\n        namelist_add(ip, NULL, \"assert.js\");\n        /* extract the YAML frontmatter */\n        desc = extract_desc(buf, '-');\n        if (desc) {\n            char *ifile, *option;\n            int state;\n            p = find_tag(desc, \"includes:\", &state);\n            if (p) {\n                while ((ifile = get_option(&p, &state)) != NULL) {\n                    // skip unsupported harness files\n                    if (find_word(harness_exclude, ifile)) {\n                        skip |= 1;\n                    } else {\n                        namelist_add(ip, NULL, ifile);\n                    }\n                    free(ifile);\n                }\n            }\n            p = find_tag(desc, \"flags:\", &state);\n            if (p) {\n                while ((option = get_option(&p, &state)) != NULL) {\n                    if (str_equal(option, \"noStrict\") ||\n                        str_equal(option, \"raw\")) {\n                        is_nostrict = TRUE;\n                        skip |= (test_mode == TEST_STRICT);\n                    }\n                    else if (str_equal(option, \"onlyStrict\")) {\n                        is_onlystrict = TRUE;\n                        skip |= (test_mode == TEST_NOSTRICT);\n                    }\n                    else if (str_equal(option, \"async\")) {\n                        is_async = TRUE;\n                        skip |= skip_async;\n                    }\n                    else if (str_equal(option, \"module\")) {\n                        is_module = TRUE;\n                        skip |= skip_module;\n                    }\n                    else if (str_equal(option, \"CanBlockIsFalse\")) {\n                        can_block = FALSE;\n                    }\n                    free(option);\n                }\n            }\n            p = find_tag(desc, \"negative:\", &state);\n            if (p) {\n                /* XXX: should extract the phase */\n                char *q = find_tag(p, \"type:\", &state);\n                if (q) {\n                    while (isspace(*q))\n                        q++;\n                    error_type = strdup_len(q, strcspn(q, \" \\n\"));\n                }\n                is_negative = TRUE;\n            }\n            p = find_tag(desc, \"features:\", &state);\n            if (p) {\n                while ((option = get_option(&p, &state)) != NULL) {\n                    if (find_word(harness_features, option)) {\n                        /* feature is enabled */\n                    } else if (find_word(harness_skip_features, option)) {\n                        /* skip disabled feature */\n                        skip |= 1;\n                    } else {\n                        /* feature is not listed: skip and warn */\n                        printf(\"%s:%d: unknown feature: %s\\n\", filename, 1, option);\n                        skip |= 1;\n                    }\n                    free(option);\n                }\n            }\n            free(desc);\n        }\n        if (is_async)\n            namelist_add(ip, NULL, \"doneprintHandle.js\");\n    } else {\n        char *ifile;\n\n        if (!harness) {\n            p = strstr(filename, \"test/\");\n            if (p) {\n                snprintf(harnessbuf, sizeof(harnessbuf), \"%.*s%s\",\n                         (int)(p - filename), filename, \"test/harness\");\n            }\n            harness = harnessbuf;\n        }\n\n        namelist_add(ip, NULL, \"sta.js\");\n\n        /* include extra harness files */\n        for (p = buf; (p = strstr(p, \"$INCLUDE(\\\"\")) != NULL; p++) {\n            p += 10;\n            ifile = strdup_len(p, strcspn(p, \"\\\"\"));\n            // skip unsupported harness files\n            if (find_word(harness_exclude, ifile)) {\n                skip |= 1;\n            } else {\n                namelist_add(ip, NULL, ifile);\n            }\n            free(ifile);\n        }\n\n        /* locate the old style configuration comment */\n        desc = extract_desc(buf, '*');\n        if (desc) {\n            if (strstr(desc, \"@noStrict\")) {\n                is_nostrict = TRUE;\n                skip |= (test_mode == TEST_STRICT);\n            }\n            if (strstr(desc, \"@onlyStrict\")) {\n                is_onlystrict = TRUE;\n                skip |= (test_mode == TEST_NOSTRICT);\n            }\n            if (strstr(desc, \"@negative\")) {\n                /* XXX: should extract the regex to check error type */\n                is_negative = TRUE;\n            }\n            free(desc);\n        }\n    }\n\n    if (outfile && index >= 0) {\n        fprintf(outfile, \"%d: %s%s%s%s%s%s%s\\n\", index, filename,\n                is_nostrict ? \"  @noStrict\" : \"\",\n                is_onlystrict ? \"  @onlyStrict\" : \"\",\n                is_async ? \"  async\" : \"\",\n                is_module ? \"  module\" : \"\",\n                is_negative ? \"  @negative\" : \"\",\n                skip ? \"  SKIPPED\" : \"\");\n        fflush(outfile);\n    }\n\n    use_strict = use_nostrict = 0;\n    /* XXX: should remove 'test_mode' or simplify it just to force\n       strict or non strict mode for single file tests */\n    switch (test_mode) {\n    case TEST_DEFAULT_NOSTRICT:\n        if (is_onlystrict)\n            use_strict = 1;\n        else\n            use_nostrict = 1;\n        break;\n    case TEST_DEFAULT_STRICT:\n        if (is_nostrict)\n            use_nostrict = 1;\n        else\n            use_strict = 1;\n        break;\n    case TEST_NOSTRICT:\n        if (!is_onlystrict)\n            use_nostrict = 1;\n        break;\n    case TEST_STRICT:\n        if (!is_nostrict)\n            use_strict = 1;\n        break;\n    case TEST_ALL:\n        if (is_module) {\n            use_nostrict = 1;\n        } else {\n            if (!is_nostrict)\n                use_strict = 1;\n            if (!is_onlystrict)\n                use_nostrict = 1;\n        }\n        break;\n    }\n\n    if (skip || use_strict + use_nostrict == 0) {\n        test_skipped++;\n        ret = -2;\n    } else {\n        clock_t clocks;\n\n        if (is_module) {\n            eval_flags = JS_EVAL_TYPE_MODULE;\n        } else {\n            eval_flags = JS_EVAL_TYPE_GLOBAL;\n        }\n        clocks = clock();\n        ret = 0;\n        if (use_nostrict) {\n            ret = run_test_buf(filename, harness, ip, buf, buf_len,\n                               error_type, eval_flags, is_negative, is_async,\n                               can_block);\n        }\n        if (use_strict) {\n            ret |= run_test_buf(filename, harness, ip, buf, buf_len,\n                                error_type, eval_flags | JS_EVAL_FLAG_STRICT,\n                                is_negative, is_async, can_block);\n        }\n        clocks = clock() - clocks;\n        if (outfile && index >= 0 && clocks >= CLOCKS_PER_SEC / 10) {\n            /* output timings for tests that take more than 100 ms */\n            fprintf(outfile, \" time: %d ms\\n\", (int)(clocks * 1000LL / CLOCKS_PER_SEC));\n        }\n    }\n    namelist_free(&include_list);\n    free(error_type);\n    free(buf);\n\n    return ret;\n}\n\n/* run a test when called by test262-harness+eshost */\nint run_test262_harness_test(const char *filename, BOOL is_module)\n{\n    JSRuntime *rt;\n    JSContext *ctx;\n    char *buf;\n    size_t buf_len;\n    int eval_flags, ret_code, ret;\n    JSValue res_val;\n    BOOL can_block;\n    \n    outfile = stdout; /* for js_print */\n\n    rt = JS_NewRuntime();\n    if (rt == NULL) {\n        fatal(1, \"JS_NewRuntime failure\");\n    }        \n    ctx = JS_NewContext(rt);\n    if (ctx == NULL) {\n        JS_FreeRuntime(rt);\n        fatal(1, \"JS_NewContext failure\");\n    }\n    JS_SetRuntimeInfo(rt, filename);\n\n    can_block = TRUE;\n    JS_SetCanBlock(rt, can_block);\n    \n    /* loader for ES6 modules */\n    JS_SetModuleLoaderFunc(rt, NULL, js_module_loader_test, NULL);\n        \n    add_helpers(ctx);\n\n    buf = load_file(filename, &buf_len);\n\n    if (is_module) {\n      eval_flags = JS_EVAL_TYPE_MODULE;\n    } else {\n      eval_flags = JS_EVAL_TYPE_GLOBAL;\n    }\n    res_val = JS_Eval(ctx, buf, buf_len, filename, eval_flags);\n    ret_code = 0;\n    if (JS_IsException(res_val)) {\n       js_std_dump_error(ctx);\n       ret_code = 1;\n    } else {\n        JS_FreeValue(ctx, res_val);\n        for(;;) {\n            JSContext *ctx1;\n            ret = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1);\n            if (ret < 0) {\n\t      js_std_dump_error(ctx1);\n\t      ret_code = 1;\n            } else if (ret == 0) {\n\t      break;\n            }\n        }\n    }\n    free(buf);\n#ifdef CONFIG_AGENT\n    js_agent_free(ctx);\n#endif\n    JS_FreeContext(ctx);\n    JS_FreeRuntime(rt);\n    return ret_code;\n}\n\nclock_t last_clock;\n\nvoid show_progress(int force) {\n    clock_t t = clock();\n    if (force || !last_clock || (t - last_clock) > CLOCKS_PER_SEC / 20) {\n        last_clock = t;\n        /* output progress indicator: erase end of line and return to col 0 */\n        fprintf(stderr, \"%d/%d/%d\\033[K\\r\",\n                test_failed, test_count, test_skipped);\n        fflush(stderr);\n    }\n}\n\nstatic int slow_test_threshold;\n\nvoid run_test_dir_list(namelist_t *lp, int start_index, int stop_index)\n{\n    int i;\n\n    namelist_sort(lp);\n    for (i = 0; i < lp->count; i++) {\n        const char *p = lp->array[i];\n        if (namelist_find(&exclude_list, p) >= 0) {\n            test_excluded++;\n        } else if (test_index < start_index) {\n            test_skipped++;\n        } else if (stop_index >= 0 && test_index > stop_index) {\n            test_skipped++;\n        } else {\n            int ti;\n            if (slow_test_threshold != 0) {\n                ti = get_clock_ms();\n            } else {\n                ti = 0;\n            }\n            run_test(p, test_index);\n            if (slow_test_threshold != 0) {\n                ti = get_clock_ms() - ti;\n                if (ti >= slow_test_threshold)\n                    fprintf(stderr, \"\\n%s (%d ms)\\n\", p, ti);\n            }\n            show_progress(FALSE);\n        }\n        test_index++;\n    }\n    show_progress(TRUE);\n}\n\nvoid help(void)\n{\n    printf(\"run-test262 version \" CONFIG_VERSION \"\\n\"\n           \"usage: run-test262 [options] {-f file ... | [dir_list] [index range]}\\n\"\n           \"-h             help\\n\"\n           \"-a             run tests in strict and nostrict modes\\n\"\n           \"-m             print memory usage summary\\n\"\n           \"-n             use new style harness\\n\"\n           \"-N             run test prepared by test262-harness+eshost\\n\"\n           \"-s             run tests in strict mode, skip @nostrict tests\\n\"\n           \"-E             only run tests from the error file\\n\"\n           \"-u             update error file\\n\"\n           \"-v             verbose: output error messages\\n\"\n           \"-T duration    display tests taking more than 'duration' ms\\n\"\n           \"-c file        read configuration from 'file'\\n\"\n           \"-d dir         run all test files in directory tree 'dir'\\n\"\n           \"-e file        load the known errors from 'file'\\n\"\n           \"-f file        execute single test from 'file'\\n\"\n           \"-r file        set the report file name (default=none)\\n\"\n           \"-x file        exclude tests listed in 'file'\\n\");\n    exit(1);\n}\n\nchar *get_opt_arg(const char *option, char *arg)\n{\n    if (!arg) {\n        fatal(2, \"missing argument for option %s\", option);\n    }\n    return arg;\n}\n\nint main(int argc, char **argv)\n{\n    int optind, start_index, stop_index;\n    BOOL is_dir_list;\n    BOOL only_check_errors = FALSE;\n    const char *filename;\n    BOOL is_test262_harness = FALSE;\n    BOOL is_module = FALSE;\n\n#if !defined(_WIN32)\n    /* Date tests assume California local time */\n    setenv(\"TZ\", \"America/Los_Angeles\", 1);\n#endif\n\n    /* cannot use getopt because we want to pass the command line to\n       the script */\n    optind = 1;\n    is_dir_list = TRUE;\n    while (optind < argc) {\n        char *arg = argv[optind];\n        if (*arg != '-')\n            break;\n        optind++;\n        if (str_equal(arg, \"-h\")) {\n            help();\n        } else if (str_equal(arg, \"-m\")) {\n            dump_memory++;\n        } else if (str_equal(arg, \"-n\")) {\n            new_style++;\n        } else if (str_equal(arg, \"-s\")) {\n            test_mode = TEST_STRICT;\n        } else if (str_equal(arg, \"-a\")) {\n            test_mode = TEST_ALL;\n        } else if (str_equal(arg, \"-u\")) {\n            update_errors++;\n        } else if (str_equal(arg, \"-v\")) {\n            verbose++;\n        } else if (str_equal(arg, \"-c\")) {\n            load_config(get_opt_arg(arg, argv[optind++]));\n        } else if (str_equal(arg, \"-d\")) {\n            enumerate_tests(get_opt_arg(arg, argv[optind++]));\n        } else if (str_equal(arg, \"-e\")) {\n            error_filename = get_opt_arg(arg, argv[optind++]);\n        } else if (str_equal(arg, \"-x\")) {\n            namelist_load(&exclude_list, get_opt_arg(arg, argv[optind++]));\n        } else if (str_equal(arg, \"-f\")) {\n            is_dir_list = FALSE;\n        } else if (str_equal(arg, \"-r\")) {\n            report_filename = get_opt_arg(arg, argv[optind++]);\n        } else if (str_equal(arg, \"-E\")) {\n            only_check_errors = TRUE;\n        } else if (str_equal(arg, \"-T\")) {\n            slow_test_threshold = atoi(get_opt_arg(arg, argv[optind++]));\n        } else if (str_equal(arg, \"-N\")) {\n            is_test262_harness = TRUE;\n        } else if (str_equal(arg, \"--module\")) {\n            is_module = TRUE;\n        } else {\n            fatal(1, \"unknown option: %s\", arg);\n            break;\n        }\n    }\n    \n    if (optind >= argc && !test_list.count)\n        help();\n\n    if (is_test262_harness) {\n        return run_test262_harness_test(argv[optind], is_module);\n    }\n\t\t\t       \n    error_out = stdout;\n    if (error_filename) {\n        error_file = load_file(error_filename, NULL);\n        if (only_check_errors && error_file) {\n            namelist_free(&test_list);\n            namelist_add_from_error_file(&test_list, error_file);\n        }\n        if (update_errors) {\n            free(error_file);\n            error_file = NULL;\n            error_out = fopen(error_filename, \"w\");\n            if (!error_out) {\n                perror_exit(1, error_filename);\n            }\n        }\n    }\n\n    update_exclude_dirs();\n\n    if (is_dir_list) {\n        if (optind < argc && !isdigit(argv[optind][0])) {\n            filename = argv[optind++];\n            namelist_load(&test_list, filename);\n        }\n        start_index = 0;\n        stop_index = -1;\n        if (optind < argc) {\n            start_index = atoi(argv[optind++]);\n            if (optind < argc) {\n                stop_index = atoi(argv[optind++]);\n            }\n        }\n        if (!report_filename || str_equal(report_filename, \"none\")) {\n            outfile = NULL;\n        } else if (str_equal(report_filename, \"-\")) {\n            outfile = stdout;\n        } else {\n            outfile = fopen(report_filename, \"wb\");\n            if (!outfile) {\n                perror_exit(1, report_filename);\n            }\n        }\n        run_test_dir_list(&test_list, start_index, stop_index);\n\n        if (outfile && outfile != stdout) {\n            fclose(outfile);\n            outfile = NULL;\n        }\n    } else {\n        outfile = stdout;\n        while (optind < argc) {\n            run_test(argv[optind++], -1);\n        }\n    }\n\n    if (dump_memory) {\n        if (dump_memory > 1 && stats_count > 1) {\n            printf(\"\\nMininum memory statistics for %s:\\n\\n\", stats_min_filename);\n            JS_DumpMemoryUsage(stdout, &stats_min, NULL);\n            printf(\"\\nMaximum memory statistics for %s:\\n\\n\", stats_max_filename);\n            JS_DumpMemoryUsage(stdout, &stats_max, NULL);\n        }\n        printf(\"\\nAverage memory statistics for %d tests:\\n\\n\", stats_count);\n        JS_DumpMemoryUsage(stdout, &stats_avg, NULL);\n        printf(\"\\n\");\n    }\n\n    if (is_dir_list) {\n        fprintf(stderr, \"Result: %d/%d error%s\",\n                test_failed, test_count, test_count != 1 ? \"s\" : \"\");\n        if (test_excluded)\n            fprintf(stderr, \", %d excluded\", test_excluded);\n        if (test_skipped)\n            fprintf(stderr, \", %d skipped\", test_skipped);\n        if (error_file) {\n            if (new_errors)\n                fprintf(stderr, \", %d new\", new_errors);\n            if (changed_errors)\n                fprintf(stderr, \", %d changed\", changed_errors);\n            if (fixed_errors)\n                fprintf(stderr, \", %d fixed\", fixed_errors);\n        }\n        fprintf(stderr, \"\\n\");\n    }\n\n    if (error_out && error_out != stdout) {\n        fclose(error_out);\n        error_out = NULL;\n    }\n\n    namelist_free(&test_list);\n    namelist_free(&exclude_list);\n    namelist_free(&exclude_dir_list);\n    free(harness_dir);\n    free(harness_features);\n    free(harness_exclude);\n    free(error_file);\n\n    return 0;\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/test262.conf",
    "content": "[config]\n# general settings for test262 ES6 version\n\n# framework style: old, new\nstyle=new\n\n# handle tests tagged as [noStrict]: yes, no, skip\nnostrict=yes\n\n# handle tests tagged as [strictOnly]: yes, no, skip\nstrict=yes\n\n# test mode: default, default-nostrict, default-strict, strict, nostrict, both, all\nmode=default\n\n# handle tests flagged as [async]: yes, no, skip\n# for these, load 'harness/doneprintHandle.js' prior to test\n# and expect `print('Test262:AsyncTestComplete')` to be called for \n# successful termination\nasync=yes\n\n# handle tests flagged as [module]: yes, no, skip\nmodule=yes\n\n# output error messages: yes, no\nverbose=yes\n\n# load harness files from this directory\nharnessdir=test262/harness\n\n# names of harness include files to skip\n#harnessexclude=\n\n# name of the error file for known errors\nerrorfile=test262_errors.txt\n\n# exclude tests enumerated in this file (see also [exclude] section)\n#excludefile=test262_exclude.txt\n\n# report test results to this file\nreportfile=test262_report.txt\n\n# enumerate tests from this directory\ntestdir=test262/test\n\n[features]\n# Standard language features and proposed extensions\n# list the features that are included\n# skipped features are tagged as such to avoid warnings\n\nAggregateError\nalign-detached-buffer-semantics-with-web-reality\narbitrary-module-namespace-names=skip\nArray.prototype.at=skip\nArray.prototype.flat\nArray.prototype.flatMap\nArray.prototype.flatten\nArray.prototype.values\nArrayBuffer\narrow-function\nasync-functions\nasync-iteration\nAtomics\nAtomics.waitAsync=skip\nBigInt\ncaller\nclass\nclass-fields-private\nclass-fields-public\nclass-methods-private\nclass-static-fields-public\nclass-static-fields-private\nclass-static-methods-private\ncleanupSome=skip\ncoalesce-expression\ncomputed-property-names\nconst\ncross-realm\nDataView\nDataView.prototype.getFloat32\nDataView.prototype.getFloat64\nDataView.prototype.getInt16\nDataView.prototype.getInt32\nDataView.prototype.getInt8\nDataView.prototype.getUint16\nDataView.prototype.getUint32\nDataView.prototype.setUint8\ndefault-parameters\ndestructuring-assignment\ndestructuring-binding\ndynamic-import\nexport-star-as-namespace-from-module\nFinalizationGroup=skip\nFinalizationRegistry=skip\nFinalizationRegistry.prototype.cleanupSome=skip\nFloat32Array\nFloat64Array\nfor-in-order\nfor-of\ngenerators\nglobalThis\nhashbang\nhost-gc-required=skip\nimport.meta\nInt16Array\nInt32Array\nInt8Array\nIsHTMLDDA\njson-superset\nlegacy-regexp=skip\nlet\nlogical-assignment-operators\nMap\nnew.target\nnumeric-separator-literal\nobject-rest\nobject-spread\nObject.fromEntries\nObject.is\noptional-catch-binding\noptional-chaining\nPromise\nPromise.allSettled\nPromise.any\nPromise.prototype.finally\nProxy\nproxy-missing-checks\nReflect\nReflect.construct\nReflect.set\nReflect.setPrototypeOf\nregexp-dotall\nregexp-lookbehind\nregexp-match-indices=skip\nregexp-named-groups\nregexp-unicode-property-escapes\nrest-parameters\nSet\nSharedArrayBuffer\nstring-trimming\nString.fromCodePoint\nString.prototype.endsWith\nString.prototype.includes\nString.prototype.at=skip\nString.prototype.matchAll\nString.prototype.replaceAll\nString.prototype.trimEnd\nString.prototype.trimStart\nsuper\nSymbol\nSymbol.asyncIterator\nSymbol.hasInstance\nSymbol.isConcatSpreadable\nSymbol.iterator\nSymbol.match\nSymbol.matchAll\nSymbol.prototype.description\nSymbol.replace\nSymbol.search\nSymbol.species\nSymbol.split\nSymbol.toPrimitive\nSymbol.toStringTag\nSymbol.unscopables\ntail-call-optimization=skip\ntemplate\ntop-level-await=skip\nTypedArray\nTypedArray.prototype.at=skip\nu180e\nUint16Array\nUint32Array\nUint8Array\nUint8ClampedArray\nWeakMap\nWeakRef=skip\nWeakSet\nwell-formed-json-stringify\n__getter__\n__proto__\n__setter__\n\n[exclude]\n# list excluded tests and directories here\n\n# intl not supported\ntest262/test/intl402/\n\n# incompatible with the \"caller\" feature\ntest262/test/built-ins/Function/prototype/restricted-property-caller.js\ntest262/test/built-ins/Function/prototype/restricted-property-arguments.js\ntest262/test/built-ins/ThrowTypeError/unique-per-realm-function-proto.js\n\n# slow tests\n#test262/test/built-ins/RegExp/CharacterClassEscapes/\n#test262/test/built-ins/RegExp/property-escapes/\n\n[tests]\n# list test files or use config.testdir\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/test262_errors.txt",
    "content": "test262/test/built-ins/Function/internals/Construct/derived-this-uninitialized-realm.js:20: Test262Error: Expected a ReferenceError but got a ReferenceError\ntest262/test/built-ins/Function/internals/Construct/derived-this-uninitialized-realm.js:20: strict mode: Test262Error: Expected a ReferenceError but got a ReferenceError\ntest262/test/built-ins/RegExp/named-groups/non-unicode-property-names-valid.js:46: SyntaxError: invalid group name\ntest262/test/built-ins/RegExp/named-groups/non-unicode-property-names-valid.js:46: strict mode: SyntaxError: invalid group name\ntest262/test/built-ins/TypedArrayConstructors/internals/DefineOwnProperty/BigInt/detached-buffer.js:46: Test262Error:  (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/DefineOwnProperty/BigInt/detached-buffer.js:46: strict mode: Test262Error:  (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/DefineOwnProperty/detached-buffer.js:47: Test262Error:  (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/DefineOwnProperty/detached-buffer.js:47: strict mode: Test262Error:  (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/detached-buffer-realm.js:37: strict mode: TypeError: out-of-bound numeric index (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/detached-buffer.js:34: TypeError: cannot convert bigint to number (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/detached-buffer.js:32: strict mode: TypeError: out-of-bound numeric index (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/key-is-minus-zero.js:20: Test262Error: Reflect.set(\"new TA([42n])\", \"-0\", 1n) must return true Expected SameValue(«false», «true») to be true (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/key-is-minus-zero.js:20: strict mode: Test262Error: Reflect.set(\"new TA([42n])\", \"-0\", 1n) must return true Expected SameValue(«false», «true») to be true (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/key-is-not-integer.js:21: Test262Error: Reflect.set(\"new TA([42n])\", \"1.1\", 1n) must return true Expected SameValue(«false», «true») to be true (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/key-is-not-integer.js:21: strict mode: Test262Error: Reflect.set(\"new TA([42n])\", \"1.1\", 1n) must return true Expected SameValue(«false», «true») to be true (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/key-is-out-of-bounds.js:27: Test262Error: Reflect.set(\"new TA([42n])\", \"-1\", 1n) must return false Expected SameValue(«false», «true») to be true (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/key-is-out-of-bounds.js:27: strict mode: Test262Error: Reflect.set(\"new TA([42n])\", \"-1\", 1n) must return false Expected SameValue(«false», «true») to be true (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/tonumber-value-detached-buffer.js:24: Test262Error: Expected SameValue(«false», «true») to be true (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/BigInt/tonumber-value-detached-buffer.js:24: strict mode: Test262Error: Expected SameValue(«false», «true») to be true (Testing with BigInt64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/detached-buffer-realm.js:37: strict mode: TypeError: out-of-bound numeric index (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/detached-buffer.js:32: strict mode: TypeError: out-of-bound numeric index (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/key-is-minus-zero.js:22: Test262Error: Reflect.set(sample, \"-0\", 1) must return true Expected SameValue(«false», «true») to be true (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/key-is-minus-zero.js:22: strict mode: Test262Error: Reflect.set(sample, \"-0\", 1) must return true Expected SameValue(«false», «true») to be true (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/key-is-not-integer.js:22: Test262Error: Reflect.set(sample, \"1.1\", 1) must return true Expected SameValue(«false», «true») to be true (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/key-is-not-integer.js:22: strict mode: Test262Error: Reflect.set(sample, \"1.1\", 1) must return true Expected SameValue(«false», «true») to be true (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/key-is-out-of-bounds.js:22: Test262Error: Reflect.set(sample, \"-1\", 1) must return true Expected SameValue(«false», «true») to be true (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/key-is-out-of-bounds.js:22: strict mode: Test262Error: Reflect.set(sample, \"-1\", 1) must return true Expected SameValue(«false», «true») to be true (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/tonumber-value-detached-buffer.js:39: Test262Error: Expected SameValue(«false», «true») to be true (Testing with Float64Array.)\ntest262/test/built-ins/TypedArrayConstructors/internals/Set/tonumber-value-detached-buffer.js:39: strict mode: Test262Error: Expected SameValue(«false», «true») to be true (Testing with Float64Array.)\ntest262/test/language/expressions/dynamic-import/usage-from-eval.js:26: TypeError: $DONE() not called\ntest262/test/language/expressions/dynamic-import/usage-from-eval.js:26: strict mode: TypeError: $DONE() not called\ntest262/test/language/expressions/optional-chaining/optional-call-preserves-this.js:21: TypeError: cannot read property 'c' of undefined\ntest262/test/language/expressions/optional-chaining/optional-call-preserves-this.js:15: strict mode: TypeError: cannot read property '_b' of undefined\ntest262/test/language/statements/for-of/head-lhs-async-invalid.js:14: unexpected error type: Test262: This statement should not be evaluated.\ntest262/test/language/statements/for-of/head-lhs-async-invalid.js:14: strict mode: unexpected error type: Test262: This statement should not be evaluated.\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/test262o.conf",
    "content": "[config]\n# general settings for test262 ES5 version\n\n# framework style: old, new\nstyle=old\n\n# handle tests tagged as @noStrict: yes, no, skip\nnostrict=yes\n\n# handle tests tagged as @strictOnly: yes, no, skip\nstrict=yes\n\n# test mode: default, default-nostrict, default-strict, strict, nostrict, both, all\nmode=default\n\n# output error messages: yes, no\nverbose=yes\n\n# load harness files this directory\nharnessdir=test262o/test/harness\n\n# name of the error file for known errors\nerrorfile=test262o_errors.txt\n\n# exclude tests enumerated in this file\n#excludefile=test262o_excluded.txt\n\n# report test results to this file\nreportfile=test262o_report.txt\n\n# enumerate tests from this directory\ntestdir=test262o/test/suite\n\n[exclude]\n# list excluded tests and directories here\n\n# intl not supported\ntest262o/test/suite/intl402/\n\n# ES6 != ES5: block scoped function definitions allowed in strict mode\ntest262o/test/suite/bestPractice/Sbp_A1_T1.js\ntest262o/test/suite/bestPractice/Sbp_A2_T1.js\ntest262o/test/suite/bestPractice/Sbp_A2_T2.js\ntest262o/test/suite/bestPractice/Sbp_A3_T1.js\ntest262o/test/suite/bestPractice/Sbp_A3_T2.js\ntest262o/test/suite/bestPractice/Sbp_A4_T1.js\ntest262o/test/suite/bestPractice/Sbp_A4_T2.js\ntest262o/test/suite/bestPractice/Sbp_A5_T2.js\n\n# ES6 != ES5: `y={x};` is shorthand for `y={x:x}`\ntest262o/test/suite/ch12/12.1/S12.1_A4_T2.js\ntest262o/test/suite/ch12/12.6/12.6.4/S12.6.4_A15.js\n\n# ES6 != ES5: function length property is configurable\ntest262o/test/suite/ch11/11.4/11.4.1/11.4.1-5-a-28-s.js\ntest262o/test/suite/ch13/13.2/13.2-15-1.js\ntest262o/test/suite/ch15/15.1/15.1.2/15.1.2.1/S15.1.2.1_A4.2.js\ntest262o/test/suite/ch15/15.1/15.1.2/15.1.2.2/S15.1.2.2_A9.2.js\ntest262o/test/suite/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A7.2.js\ntest262o/test/suite/ch15/15.1/15.1.2/15.1.2.4/S15.1.2.4_A2.2.js\ntest262o/test/suite/ch15/15.1/15.1.2/15.1.2.5/S15.1.2.5_A2.2.js\ntest262o/test/suite/ch15/15.1/15.1.3/15.1.3.1/S15.1.3.1_A5.2.js\ntest262o/test/suite/ch15/15.1/15.1.3/15.1.3.2/S15.1.3.2_A5.2.js\ntest262o/test/suite/ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A5.2.js\ntest262o/test/suite/ch15/15.1/15.1.3/15.1.3.4/S15.1.3.4_A5.2.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-186.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-187.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-191.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-194.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-201.js\ntest262o/test/suite/ch15/15.2/15.2.4/15.2.4.2/S15.2.4.2_A9.js\ntest262o/test/suite/ch15/15.2/15.2.4/15.2.4.3/S15.2.4.3_A9.js\ntest262o/test/suite/ch15/15.2/15.2.4/15.2.4.4/S15.2.4.4_A9.js\ntest262o/test/suite/ch15/15.2/15.2.4/15.2.4.5/S15.2.4.5_A9.js\ntest262o/test/suite/ch15/15.2/15.2.4/15.2.4.6/S15.2.4.6_A9.js\ntest262o/test/suite/ch15/15.2/15.2.4/15.2.4.7/S15.2.4.7_A9.js\ntest262o/test/suite/ch15/15.3/15.3.3/15.3.3.2/15.3.3.2-1.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.2/S15.3.4.2_A9.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.3/S15.3.4.3_A9.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A9.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-15-2.js\ntest262o/test/suite/ch15/15.3/15.3.5/S15.3.5.1_A2_T1.js\ntest262o/test/suite/ch15/15.3/15.3.5/S15.3.5.1_A2_T2.js\ntest262o/test/suite/ch15/15.3/15.3.5/S15.3.5.1_A2_T3.js\ntest262o/test/suite/ch15/15.4/15.4.3/S15.4.3_A2.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.2/S15.4.4.2_A4.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.3/S15.4.4.3_A4.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.4/S15.4.4.4_A4.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.5/S15.4.4.5_A6.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.6/S15.4.4.6_A5.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.7/S15.4.4.7_A6.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.8/S15.4.4.8_A5.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.9/S15.4.4.9_A5.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.10/S15.4.4.10_A5.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.11/S15.4.4.11_A7.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A5.2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.13/S15.4.4.13_A5.2.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.4/S15.5.4.4_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.5/S15.5.4.5_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.6/S15.5.4.6_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.8/S15.5.4.8_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.9/S15.5.4.9_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.11/S15.5.4.11_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.12/S15.5.4.12_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.14/S15.5.4.14_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.16/S15.5.4.16_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.17/S15.5.4.17_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.18/S15.5.4.18_A9.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.19/S15.5.4.19_A9.js\ntest262o/test/suite/ch15/15.9/15.9.4/15.9.4.2/S15.9.4.2_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.4/15.9.4.3/S15.9.4.3_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.1/S15.9.5.1_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.2/S15.9.5.2_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.3/S15.9.5.3_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.4/S15.9.5.4_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.5/S15.9.5.5_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.6/S15.9.5.6_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.7/S15.9.5.7_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.8/S15.9.5.8_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.9/S15.9.5.9_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.10/S15.9.5.10_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.11/S15.9.5.11_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.12/S15.9.5.12_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.13/S15.9.5.13_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.14/S15.9.5.14_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.15/S15.9.5.15_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.16/S15.9.5.16_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.17/S15.9.5.17_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.18/S15.9.5.18_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.19/S15.9.5.19_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.20/S15.9.5.20_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.21/S15.9.5.21_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.22/S15.9.5.22_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.23/S15.9.5.23_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.24/S15.9.5.24_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.25/S15.9.5.25_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.26/S15.9.5.26_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.27/S15.9.5.27_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.28/S15.9.5.28_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.29/S15.9.5.29_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.30/S15.9.5.30_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.31/S15.9.5.31_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.32/S15.9.5.32_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.33/S15.9.5.33_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.34/S15.9.5.34_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.35/S15.9.5.35_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.36/S15.9.5.36_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.37/S15.9.5.37_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.38/S15.9.5.38_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.39/S15.9.5.39_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.40/S15.9.5.40_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.41/S15.9.5.41_A3_T2.js\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.42/S15.9.5.42_A3_T2.js\ntest262o/test/suite/ch15/15.10/15.10.6/15.10.6.2/S15.10.6.2_A9.js\ntest262o/test/suite/ch15/15.10/15.10.6/15.10.6.3/S15.10.6.3_A9.js\ntest262o/test/suite/ch15/15.10/15.10.6/15.10.6.4/S15.10.6.4_A9.js\n\n# ES6 != ES5: object literals may have duplicates\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5-4-4-a-1-s.js\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5_4-4-b-1.js\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5_4-4-b-2.js\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5_4-4-c-1.js\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5_4-4-c-2.js\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5_4-4-d-1.js\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5_4-4-d-2.js\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5_4-4-d-3.js\ntest262o/test/suite/ch11/11.1/11.1.5/11.1.5_4-4-d-4.js\n\n# ES6 != ES5: Date.prototype is no longer an instance of Date\ntest262o/test/suite/ch15/15.9/15.9.5/15.9.5.40/15.9.5.40_1.js\n\n# ES6 != ES5: Object.getPrototypeOf converts argument to object\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-1-3.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-1-4.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-1.js\n\n# ES6 != ES5: Object.getPrototypeOf(NativeError)\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-12.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-13.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-14.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-15.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-16.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-17.js\n\n# ES6 != ES5: Object.getOwnPropertyDescriptor converts argument to object\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-1-3.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-1-4.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-1.js\n\n# ES6 != ES5: Object.getOwnPropertyNames converts argument to object\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.4/15.2.3.4-1-4.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.4/15.2.3.4-1-5.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.4/15.2.3.4-1.js\n\n# ES6 != ES5: Object.seal accepts all types\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.8/15.2.3.8-1-1.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.8/15.2.3.8-1-2.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.8/15.2.3.8-1-3.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.8/15.2.3.8-1-4.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.8/15.2.3.8-1.js\n\n# ES6 != ES5: Object.freeze accepts all types\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.9/15.2.3.9-1-1.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.9/15.2.3.9-1-2.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.9/15.2.3.9-1-3.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.9/15.2.3.9-1-4.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.9/15.2.3.9-1.js\n\n# ES6 != ES5: Object.preventExtensions accepts all types\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.10/15.2.3.10-1-1.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.10/15.2.3.10-1-2.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.10/15.2.3.10-1-3.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.10/15.2.3.10-1-4.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.10/15.2.3.10-1.js\n\n# ES6 != ES5: Object.isSealed accepts all types\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-1.js\n\n# ES6 != ES5: Object.isFrozen accepts all types\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.12/15.2.3.12-1-1.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.12/15.2.3.12-1-2.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.12/15.2.3.12-1-3.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.12/15.2.3.12-1-4.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.12/15.2.3.12-1.js\n\n# ES6 != ES5: Object.isExtensible accepts all types\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-1-1.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-1-2.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-1-3.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-1-4.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-1.js\n\n# ES6 != ES5: Object.keys converts argument to object\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.14/15.2.3.14-1-1.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.14/15.2.3.14-1-2.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.14/15.2.3.14-1-3.js\n\n# ES6 != ES5: source and other properties of RegExp.prototype are not own properties\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-212.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-213.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-214.js\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-215.js\n\n# ES6 != ES5: String numeric object properties are enumerated first\ntest262o/test/suite/ch15/15.2/15.2.3/15.2.3.4/15.2.3.4-4-44.js\n\n# ES6: new RegExp(regex, flags) is valid\ntest262o/test/suite/ch15/15.10/15.10.3/S15.10.3.1_A2_T1.js\ntest262o/test/suite/ch15/15.10/15.10.3/S15.10.3.1_A2_T2.js\ntest262o/test/suite/ch15/15.10/15.10.4/15.10.4.1/15.10.4.1-1.js\ntest262o/test/suite/ch15/15.10/15.10.4/S15.10.4.1_A2_T1.js\ntest262o/test/suite/ch15/15.10/15.10.4/S15.10.4.1_A2_T2.js\n\n# ES6 != ES5: RegExp.prototype.test behavior\ntest262o/test/suite/ch15/15.10/15.10.6/15.10.6.2/S15.10.6.2_A5_T3.js\n\n# ES6 != ES5: source, global, ignoreCase, multiline, lastIndex are not data properties\n# of RegExp objects and RegExp.prototype is not a RegExp object\ntest262o/test/suite/ch15/15.10/15.10.6/15.10.6.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.1/15.10.7.1-1.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.1/15.10.7.1-2.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.1/S15.10.7.1_A8.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.1/S15.10.7.1_A9.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.1/S15.10.7.1_A10.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.2/15.10.7.2-1.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.2/15.10.7.2-2.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.2/S15.10.7.2_A8.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.2/S15.10.7.2_A9.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.2/S15.10.7.2_A10.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.3/15.10.7.3-1.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.3/15.10.7.3-2.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.3/S15.10.7.3_A8.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.3/S15.10.7.3_A9.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.3/S15.10.7.3_A10.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.4/15.10.7.4-1.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.4/15.10.7.4-2.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.4/S15.10.7.4_A8.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.4/S15.10.7.4_A9.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.4/S15.10.7.4_A10.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.5/15.10.7.5-1.js\ntest262o/test/suite/ch15/15.10/15.10.7/15.10.7.5/15.10.7.5-2.js\n\n# ES6 != ES5: Error.prototype is a normal object\ntest262o/test/suite/ch15/15.11/15.11.4/S15.11.4_A2.js\n\n# ES6 different ToLength() semantics\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.5/S15.4.4.5_A4_T3.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.6/S15.4.4.6_A2_T2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.6/S15.4.4.6_A3_T1.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.6/S15.4.4.6_A3_T2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.6/S15.4.4.6_A3_T3.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.7/S15.4.4.7_A2_T2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.7/S15.4.4.7_A4_T1.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.7/S15.4.4.7_A4_T3.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.8/S15.4.4.8_A3_T3.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.9/S15.4.4.9_A3_T3.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.10/S15.4.4.10_A3_T1.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.10/S15.4.4.10_A3_T2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.10/S15.4.4.10_A3_T3.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.11/S15.4.4.11_A4_T3.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A3_T1.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.12/S15.4.4.12_A3_T3.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.13/S15.4.4.13_A3_T2.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-8.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-14.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-25.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-28.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.14/15.4.4.14-3-29.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.15/15.4.4.15-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.15/15.4.4.15-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.15/15.4.4.15-3-25.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.15/15.4.4.15-3-28.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-8.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-14.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-25.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-3-29.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-3-8.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-3-14.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-3-25.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-3-28.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-3-29.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-25.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-3-8.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-3-14.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-3-25.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-3-28.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-3-29.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.20/15.4.4.20-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.20/15.4.4.20-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.20/15.4.4.20-3-25.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-25.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.22/15.4.4.22-3-7.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.22/15.4.4.22-3-12.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.22/15.4.4.22-3-25.js\n\n# ES6 different ToLength() semantics causes near infinite runtime\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.15/15.4.4.15-3-14.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-14.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.20/15.4.4.20-3-14.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-14.js\ntest262o/test/suite/ch15/15.4/15.4.4/15.4.4.22/15.4.4.22-3-14.js\n\n# ES6 arguments/caller changes\ntest262o/test/suite/ch10/10.6/10.6-13-b-1-s.js\ntest262o/test/suite/ch10/10.6/10.6-13-b-2-s.js\ntest262o/test/suite/ch10/10.6/10.6-13-b-3-s.js\ntest262o/test/suite/ch10/10.6/10.6-14-1-s.js\ntest262o/test/suite/ch10/10.6/10.6-14-b-1-s.js\ntest262o/test/suite/ch10/10.6/10.6-14-b-4-s.js\ntest262o/test/suite/ch13/13.2/13.2-29-s.js\ntest262o/test/suite/ch13/13.2/13.2-30-s.js\ntest262o/test/suite/ch13/13.2/13.2-31-s.js\ntest262o/test/suite/ch13/13.2/13.2-32-s.js\ntest262o/test/suite/ch13/13.2/13.2-33-s.js\ntest262o/test/suite/ch13/13.2/13.2-34-s.js\ntest262o/test/suite/ch13/13.2/13.2-35-s.js\ntest262o/test/suite/ch13/13.2/13.2-36-s.js\ntest262o/test/suite/ch13/13.2/S13.2.3_A1.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-20-1.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-20-4.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-20-5.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-21-1.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-21-4.js\ntest262o/test/suite/ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-21-5.js\n\n# u180e is no longer considered as a space\ntest262o/test/suite/ch09/9.3/9.3.1/S9.3.1_A2.js\ntest262o/test/suite/ch09/9.3/9.3.1/S9.3.1_A3_T1.js\ntest262o/test/suite/ch09/9.3/9.3.1/S9.3.1_A3_T2.js\ntest262o/test/suite/ch15/15.1/15.1.2/15.1.2.2/S15.1.2.2_A2_T10.js\ntest262o/test/suite/ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A2_T10.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.20/15.5.4.20-3-2.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.20/15.5.4.20-3-3.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.20/15.5.4.20-3-4.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.20/15.5.4.20-3-5.js\ntest262o/test/suite/ch15/15.5/15.5.4/15.5.4.20/15.5.4.20-3-6.js\ntest262o/test/suite/ch15/15.10/15.10.2/15.10.2.12/S15.10.2.12_A1_T1.js\ntest262o/test/suite/ch15/15.10/15.10.2/15.10.2.12/S15.10.2.12_A2_T1.js\n\n# E6 eval return value is different\ntest262o/test/suite/ch12/12.6/12.6.3/S12.6.3_A9.js\ntest262o/test/suite/ch12/12.6/12.6.3/S12.6.3_A9.1.js\n\n# ECMA 2019 optional-catch-binding feature allows try{}catch{}\ntest262o/test/suite/ch12/12.14/S12.14_A16_T4.js\n\n# Syntax error instead of ReferenceError in ES2020\ntest262o/test/suite/ch11/11.13/11.13.1/11.13.1-1-1.js\ntest262o/test/suite/ch11/11.13/11.13.1/11.13.1-1-2.js\ntest262o/test/suite/ch11/11.13/11.13.1/11.13.1-1-3.js\ntest262o/test/suite/ch11/11.13/11.13.1/11.13.1-1-4.js\n\n[tests]\n# list test files or use config.testdir\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/test262o_errors.txt",
    "content": ""
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/tests/bjson.c",
    "content": "/*\n * QuickJS: binary JSON module (test only)\n * \n * Copyright (c) 2017-2019 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \"../quickjs-libc.h\"\n#include \"../cutils.h\"\n\nstatic JSValue js_bjson_read(JSContext *ctx, JSValueConst this_val,\n                             int argc, JSValueConst *argv)\n{\n    uint8_t *buf;\n    uint64_t pos, len;\n    JSValue obj;\n    size_t size;\n    int flags;\n    \n    if (JS_ToIndex(ctx, &pos, argv[1]))\n        return JS_EXCEPTION;\n    if (JS_ToIndex(ctx, &len, argv[2]))\n        return JS_EXCEPTION;\n    buf = JS_GetArrayBuffer(ctx, &size, argv[0]);\n    if (!buf)\n        return JS_EXCEPTION;\n    if (pos + len > size)\n        return JS_ThrowRangeError(ctx, \"array buffer overflow\");\n    flags = 0;\n    if (JS_ToBool(ctx, argv[3]))\n        flags |= JS_READ_OBJ_REFERENCE;\n    obj = JS_ReadObject(ctx, buf + pos, len, flags);\n    return obj;\n}\n\nstatic JSValue js_bjson_write(JSContext *ctx, JSValueConst this_val,\n                              int argc, JSValueConst *argv)\n{\n    size_t len;\n    uint8_t *buf;\n    JSValue array;\n    int flags;\n    \n    flags = 0;\n    if (JS_ToBool(ctx, argv[1]))\n        flags |= JS_WRITE_OBJ_REFERENCE;\n    buf = JS_WriteObject(ctx, &len, argv[0], flags);\n    if (!buf)\n        return JS_EXCEPTION;\n    array = JS_NewArrayBufferCopy(ctx, buf, len);\n    js_free(ctx, buf);\n    return array;\n}\n\nstatic const JSCFunctionListEntry js_bjson_funcs[] = {\n    JS_CFUNC_DEF(\"read\", 4, js_bjson_read ),\n    JS_CFUNC_DEF(\"write\", 2, js_bjson_write ),\n};\n\nstatic int js_bjson_init(JSContext *ctx, JSModuleDef *m)\n{\n    return JS_SetModuleExportList(ctx, m, js_bjson_funcs,\n                                  countof(js_bjson_funcs));\n}\n\n#ifdef JS_SHARED_LIBRARY\n#define JS_INIT_MODULE js_init_module\n#else\n#define JS_INIT_MODULE js_init_module_bjson\n#endif\n\nJSModuleDef *JS_INIT_MODULE(JSContext *ctx, const char *module_name)\n{\n    JSModuleDef *m;\n    m = JS_NewCModule(ctx, module_name, js_bjson_init);\n    if (!m)\n        return NULL;\n    JS_AddModuleExportList(ctx, m, js_bjson_funcs, countof(js_bjson_funcs));\n    return m;\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/tests/microbench.js",
    "content": "/*\n * Javascript Micro benchmark\n *\n * Copyright (c) 2017-2019 Fabrice Bellard\n * Copyright (c) 2017-2019 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\nimport * as std from \"std\";\n\nfunction pad(str, n) {\n    str += \"\";\n    while (str.length < n)\n        str += \" \";\n    return str;\n}\n\nfunction pad_left(str, n) {\n    str += \"\";\n    while (str.length < n)\n        str = \" \" + str;\n    return str;\n}\n\nfunction pad_center(str, n) {\n    str += \"\";\n    while (str.length < n) {\n        if ((n - str.length) & 1)\n            str = str + \" \";\n        else\n            str = \" \" + str;\n    }\n    return str;\n}\n\nfunction toPrec(n, prec) {\n    var i, s;\n    for (i = 0; i < prec; i++)\n        n *= 10;\n    s = \"\" + Math.round(n);\n    for (i = s.length - prec; i <= 0; i++)\n        s = \"0\" + s;\n    if (prec > 0)\n        s = s.substring(0, i) + \".\" + s.substring(i);\n    return s;\n}\n                \nvar ref_data;\nvar log_data;\n\nvar heads  = [ \"TEST\", \"N\", \"TIME (ns)\", \"REF (ns)\", \"SCORE (%)\" ];\nvar widths = [    22,   10,          9,     9,       9 ];\nvar precs  = [     0,   0,           2,     2,       2 ];\nvar total  = [     0,   0,           0,     0,       0 ];\nvar total_score = 0;\nvar total_scale = 0;\n\nif (typeof console == \"undefined\") {\n    var console = { log: print };\n}\n\nfunction log_line() {\n    var i, n, s, a;\n    s = \"\";\n    for (i = 0, n = arguments.length; i < n; i++) {\n        if (i > 0)\n            s += \" \";\n        a = arguments[i];\n        if (typeof a == \"number\") {\n            total[i] += a;\n            a = toPrec(a, precs[i]);\n            s += pad_left(a, widths[i]);\n        } else {\n            s += pad_left(a, widths[i]);\n        }\n    }\n    console.log(s);\n}\n\nvar clocks_per_sec = 1000000;\nvar max_iterations = 100;\nvar clock_threshold = 2000;  /* favoring short measuring spans */\nvar min_n_argument = 1;\nvar get_clock;\n\nif (typeof globalThis.__date_clock != \"function\") {\n    console.log(\"using fallback millisecond clock\");\n    clocks_per_sec = 1000;\n    max_iterations = 10;\n    clock_threshold = 100;\n    get_clock = Date.now;\n} else {\n    get_clock = globalThis.__date_clock;\n}\n\nfunction log_one(text, n, ti) {\n    var ref;\n\n    if (ref_data)\n        ref = ref_data[text];\n    else\n        ref = null;\n\n    ti = Math.round(ti * 100) / 100;\n    log_data[text] = ti;\n    if (typeof ref === \"number\") {\n        log_line(text, n, ti, ref, ti * 100 / ref);\n        total_score += ti * 100 / ref;\n        total_scale += 100;\n    } else {\n        log_line(text, n, ti);\n        total_score += 100;\n        total_scale += 100;\n    }\n}\n\nfunction bench(f, text)\n{\n    var i, j, n, t, t1, ti, nb_its, ref, ti_n, ti_n1, min_ti;\n\n    nb_its = n = 1;\n    if (f.bench) {\n        ti_n = f(text);\n    } else {\n        ti_n = 1000000000;\n        min_ti = clock_threshold / 10;\n        for(i = 0; i < 30; i++) {\n            ti = 1000000000;\n            for (j = 0; j < max_iterations; j++) {\n                t = get_clock();\n                while ((t1 = get_clock()) == t)\n                    continue;\n                nb_its = f(n);\n                if (nb_its < 0)\n                    return; // test failure\n                t1 = get_clock() - t1;\n                if (ti > t1)\n                    ti = t1;\n            }\n            if (ti >= min_ti) {\n                ti_n1 = ti / nb_its;\n                if (ti_n > ti_n1)\n                    ti_n = ti_n1;\n            }\n            if (ti >= clock_threshold && n >= min_n_argument)\n                break;\n\n            n = n * [ 2, 2.5, 2 ][i % 3];\n        }\n        // to use only the best timing from the last loop, uncomment below\n        //ti_n = ti / nb_its;\n    }\n    /* nano seconds per iteration */\n    log_one(text, n, ti_n * 1e9 / clocks_per_sec);\n}\n\nvar global_res; /* to be sure the code is not optimized */\n\nfunction empty_loop(n) {\n    var j;\n    for(j = 0; j < n; j++) {\n    }\n    return n;\n}\n\nfunction date_now(n) {\n    var j;\n    for(j = 0; j < n; j++) {\n        Date.now();\n    }\n    return n;\n}\n\nfunction prop_read(n)\n{\n    var obj, sum, j;\n    obj = {a: 1, b: 2, c:3, d:4 };\n    sum = 0;\n    for(j = 0; j < n; j++) {\n        sum += obj.a;\n        sum += obj.b;\n        sum += obj.c;\n        sum += obj.d;\n    }\n    global_res = sum;\n    return n * 4;\n}\n\nfunction prop_write(n)\n{\n    var obj, j;\n    obj = {a: 1, b: 2, c:3, d:4 };\n    for(j = 0; j < n; j++) {\n        obj.a = j;\n        obj.b = j;\n        obj.c = j;\n        obj.d = j;\n    }\n    return n * 4;\n}\n\nfunction prop_create(n)\n{\n    var obj, j;\n    for(j = 0; j < n; j++) {\n        obj = new Object();\n        obj.a = 1;\n        obj.b = 2;\n        obj.c = 3;\n        obj.d = 4;\n    }\n    return n * 4;\n}\n\nfunction prop_delete(n)\n{\n    var obj, j;\n    obj = {};\n    for(j = 0; j < n; j++) {\n        obj[j] = 1;\n    }\n    for(j = 0; j < n; j++) {\n        delete obj[j];\n    }\n    return n;\n}\n\nfunction array_read(n)\n{\n    var tab, len, sum, i, j;\n    tab = [];\n    len = 10;\n    for(i = 0; i < len; i++)\n        tab[i] = i;\n    sum = 0;\n    for(j = 0; j < n; j++) {\n        sum += tab[0];\n        sum += tab[1];\n        sum += tab[2];\n        sum += tab[3];\n        sum += tab[4];\n        sum += tab[5];\n        sum += tab[6];\n        sum += tab[7];\n        sum += tab[8];\n        sum += tab[9];\n    }\n    global_res = sum;\n    return len * n;\n}\n\nfunction array_write(n)\n{\n    var tab, len, i, j;\n    tab = [];\n    len = 10;\n    for(i = 0; i < len; i++)\n        tab[i] = i;\n    for(j = 0; j < n; j++) {\n        tab[0] = j;\n        tab[1] = j;\n        tab[2] = j;\n        tab[3] = j;\n        tab[4] = j;\n        tab[5] = j;\n        tab[6] = j;\n        tab[7] = j;\n        tab[8] = j;\n        tab[9] = j;\n    }\n    return len * n;\n}\n\nfunction array_prop_create(n)\n{\n    var tab, i, j, len;\n    len = 1000;\n    for(j = 0; j < n; j++) {\n        tab = [];\n        for(i = 0; i < len; i++)\n            tab[i] = i;\n    }\n    return len * n;\n}\n\nfunction array_length_decr(n)\n{\n    var tab, i, j, len;\n    len = 1000;\n    tab = [];\n    for(i = 0; i < len; i++)\n        tab[i] = i;\n    for(j = 0; j < n; j++) {\n        for(i = len - 1; i >= 0; i--)\n            tab.length = i;\n    }\n    return len * n;\n}\n\nfunction array_hole_length_decr(n)\n{\n    var tab, i, j, len;\n    len = 1000;\n    tab = [];\n    for(i = 0; i < len; i++) {\n        if (i != 3)\n            tab[i] = i;\n    }\n    for(j = 0; j < n; j++) {\n        for(i = len - 1; i >= 0; i--)\n            tab.length = i;\n    }\n    return len * n;\n}\n\nfunction array_push(n)\n{\n    var tab, i, j, len;\n    len = 500;\n    for(j = 0; j < n; j++) {\n        tab = [];\n        for(i = 0; i < len; i++)\n            tab.push(i);\n    }\n    return len * n;\n}\n\nfunction array_pop(n)\n{\n    var tab, i, j, len, sum;\n    len = 500;\n    for(j = 0; j < n; j++) {\n        tab = [];\n        for(i = 0; i < len; i++)\n            tab[i] = i;\n        sum = 0;\n        for(i = 0; i < len; i++)\n            sum += tab.pop();\n        global_res = sum;\n    }\n    return len * n;\n}\n\nfunction typed_array_read(n)\n{\n    var tab, len, sum, i, j;\n    len = 10;\n    tab = new Int32Array(len);\n    for(i = 0; i < len; i++)\n        tab[i] = i;\n    sum = 0;\n    for(j = 0; j < n; j++) {\n        sum += tab[0];\n        sum += tab[1];\n        sum += tab[2];\n        sum += tab[3];\n        sum += tab[4];\n        sum += tab[5];\n        sum += tab[6];\n        sum += tab[7];\n        sum += tab[8];\n        sum += tab[9];\n    }\n    global_res = sum;\n    return len * n;\n}\n\nfunction typed_array_write(n)\n{\n    var tab, len, i, j;\n    len = 10;\n    tab = new Int32Array(len);\n    for(i = 0; i < len; i++)\n        tab[i] = i;\n    for(j = 0; j < n; j++) {\n        tab[0] = j;\n        tab[1] = j;\n        tab[2] = j;\n        tab[3] = j;\n        tab[4] = j;\n        tab[5] = j;\n        tab[6] = j;\n        tab[7] = j;\n        tab[8] = j;\n        tab[9] = j;\n    }\n    return len * n;\n}\n\nvar global_var0;\n\nfunction global_read(n)\n{\n    var sum, j;\n    global_var0 = 0;\n    sum = 0;\n    for(j = 0; j < n; j++) {\n        sum += global_var0;\n        sum += global_var0;\n        sum += global_var0;\n        sum += global_var0;\n    }\n    global_res = sum;\n    return n * 4;\n}\n\nvar global_write =\n    (1, eval)(`(function global_write(n)\n           {\n               var j;\n               for(j = 0; j < n; j++) {\n                   global_var0 = j;\n                   global_var0 = j;\n                   global_var0 = j;\n                   global_var0 = j;\n               }\n               return n * 4;\n           })`);\n\nfunction global_write_strict(n)\n{\n    var j;\n    for(j = 0; j < n; j++) {\n        global_var0 = j;\n        global_var0 = j;\n        global_var0 = j;\n        global_var0 = j;\n    }\n    return n * 4;\n}\n\nfunction local_destruct(n)\n{\n    var j, v1, v2, v3, v4;\n    var array = [ 1, 2, 3, 4, 5];\n    var o = { a:1, b:2, c:3, d:4 };\n    var a, b, c, d;\n    for(j = 0; j < n; j++) {\n        [ v1, v2,, v3, ...v4] = array;\n        ({ a, b, c, d } = o);\n        ({ a: a, b: b, c: c, d: d } = o);\n    }\n    return n * 12;\n}\n\nvar global_v1, global_v2, global_v3, global_v4;\nvar global_a, global_b, global_c, global_d;\n\nvar global_destruct =\n    (1, eval)(`(function global_destruct(n)\n           {\n               var j, v1, v2, v3, v4;\n               var array = [ 1, 2, 3, 4, 5 ];\n               var o = { a:1, b:2, c:3, d:4 };\n               var a, b, c, d;\n               for(j = 0; j < n; j++) {\n                   [ global_v1, global_v2,, global_v3, ...global_v4] = array;\n                   ({ a: global_a, b: global_b, c: global_c, d: global_d } = o);\n               }\n               return n * 8;\n          })`);\n\nfunction global_destruct_strict(n)\n{\n    var j, v1, v2, v3, v4;\n    var array = [ 1, 2, 3, 4, 5 ];\n    var o = { a:1, b:2, c:3, d:4 };\n    var a, b, c, d;\n    for(j = 0; j < n; j++) {\n        [ global_v1, global_v2,, global_v3, ...global_v4] = array;\n        ({ a: global_a, b: global_b, c: global_c, d: global_d } = o);\n    }\n    return n * 8;\n}\n\nfunction func_call(n)\n{\n    function f(a)\n    {\n        return 1;\n    }\n\n    var j, sum;\n    sum = 0;\n    for(j = 0; j < n; j++) {\n        sum += f(j);\n        sum += f(j);\n        sum += f(j);\n        sum += f(j);\n    }\n    global_res = sum;\n    return n * 4;\n}\n\nfunction closure_var(n)\n{\n    function f(a)\n    {\n        sum++;\n    }\n\n    var j, sum;\n    sum = 0;\n    for(j = 0; j < n; j++) {\n        f(j);\n        f(j);\n        f(j);\n        f(j);\n    }\n    global_res = sum;\n    return n * 4;\n}\n\nfunction int_arith(n)\n{\n    var i, j, sum;\n    global_res = 0;\n    for(j = 0; j < n; j++) {\n        sum = 0;\n        for(i = 0; i < 1000; i++) {\n            sum += i * i;\n        }\n        global_res += sum;\n    }\n    return n * 1000;\n}\n\nfunction float_arith(n)\n{\n    var i, j, sum, a, incr, a0;\n    global_res = 0;\n    a0 = 0.1;\n    incr = 1.1;\n    for(j = 0; j < n; j++) {\n        sum = 0;\n        a = a0;\n        for(i = 0; i < 1000; i++) {\n            sum += a * a;\n            a += incr;\n        }\n        global_res += sum;\n    }\n    return n * 1000;\n}\n\nfunction bigfloat_arith(n)\n{\n    var i, j, sum, a, incr, a0;\n    global_res = 0;\n    a0 = BigFloat(\"0.1\");\n    incr = BigFloat(\"1.1\");\n    for(j = 0; j < n; j++) {\n        sum = 0;\n        a = a0;\n        for(i = 0; i < 1000; i++) {\n            sum += a * a;\n            a += incr;\n        }\n        global_res += sum;\n    }\n    return n * 1000;\n}\n\nfunction float256_arith(n)\n{\n    return BigFloatEnv.setPrec(bigfloat_arith.bind(null, n), 237, 19);\n}\n\nfunction bigint_arith(n, bits)\n{\n    var i, j, sum, a, incr, a0, sum0;\n    sum0 = global_res = BigInt(0);\n    a0 = BigInt(1) << BigInt(Math.floor((bits - 10) * 0.5));\n    incr = BigInt(1);\n    for(j = 0; j < n; j++) {\n        sum = sum0;\n        a = a0;\n        for(i = 0; i < 1000; i++) {\n            sum += a * a;\n            a += incr;\n        }\n        global_res += sum;\n    }\n    return n * 1000;\n}\n\nfunction bigint64_arith(n)\n{\n    return bigint_arith(n, 64);\n}\n\nfunction bigint256_arith(n)\n{\n    return bigint_arith(n, 256);\n}\n\nfunction set_collection_add(n)\n{\n    var s, i, j, len = 100;\n    s = new Set();\n    for(j = 0; j < n; j++) {\n        for(i = 0; i < len; i++) {\n            s.add(String(i), i);\n        }\n        for(i = 0; i < len; i++) {\n            if (!s.has(String(i)))\n                throw Error(\"bug in Set\");\n        }\n    }\n    return n * len;\n}\n\nfunction array_for(n)\n{\n    var r, i, j, sum;\n    r = [];\n    for(i = 0; i < 100; i++)\n        r[i] = i;\n    for(j = 0; j < n; j++) {\n        sum = 0;\n        for(i = 0; i < 100; i++) {\n            sum += r[i];\n        }\n        global_res = sum;\n    }\n    return n * 100;\n}\n\nfunction array_for_in(n)\n{\n    var r, i, j, sum;\n    r = [];\n    for(i = 0; i < 100; i++)\n        r[i] = i;\n    for(j = 0; j < n; j++) {\n        sum = 0;\n        for(i in r) {\n            sum += r[i];\n        }\n        global_res = sum;\n    }\n    return n * 100;\n}\n\nfunction array_for_of(n)\n{\n    var r, i, j, sum;\n    r = [];\n    for(i = 0; i < 100; i++)\n        r[i] = i;\n    for(j = 0; j < n; j++) {\n        sum = 0;\n        for(i of r) {\n            sum += i;\n        }\n        global_res = sum;\n    }\n    return n * 100;\n}\n\nfunction math_min(n)\n{\n    var i, j, r;\n    r = 0;\n    for(j = 0; j < n; j++) {\n        for(i = 0; i < 1000; i++)\n            r = Math.min(i, 500);\n        global_res = r;\n    }\n    return n * 1000;\n}\n\n/* incremental string contruction as local var */\nfunction string_build1(n)\n{\n    var i, j, r;\n    r = \"\";\n    for(j = 0; j < n; j++) {\n        for(i = 0; i < 100; i++)\n            r += \"x\";\n        global_res = r;\n    }\n    return n * 100;\n}\n\n/* incremental string contruction as arg */\nfunction string_build2(n, r)\n{\n    var i, j;\n    r = \"\";\n    for(j = 0; j < n; j++) {\n        for(i = 0; i < 100; i++)\n            r += \"x\";\n        global_res = r;\n    }\n    return n * 100;\n}\n\n/* incremental string contruction by prepending */\nfunction string_build3(n, r)\n{\n    var i, j;\n    r = \"\";\n    for(j = 0; j < n; j++) {\n        for(i = 0; i < 100; i++)\n            r = \"x\" + r;\n        global_res = r;\n    }\n    return n * 100;\n}\n\n/* incremental string contruction with multiple reference */\nfunction string_build4(n)\n{\n    var i, j, r, s;\n    r = \"\";\n    for(j = 0; j < n; j++) {\n        for(i = 0; i < 100; i++) {\n            s = r;\n            r += \"x\";\n        }\n        global_res = r;\n    }\n    return n * 100;\n}\n\n/* sort bench */\n\nfunction sort_bench(text) {\n    function random(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[(Math.random() * n) >> 0];\n    }\n    function random8(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[(Math.random() * 256) >> 0];\n    }\n    function random1(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[(Math.random() * 2) >> 0];\n    }\n    function hill(arr, n, def) {\n        var mid = n >> 1;\n        for (var i = 0; i < mid; i++)\n            arr[i] = def[i];\n        for (var i = mid; i < n; i++)\n            arr[i] = def[n - i];\n    }\n    function comb(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[(i & 1) * i];\n    }\n    function crisscross(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[(i & 1) ? n - i : i];\n    }\n    function zero(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[0];\n    }\n    function increasing(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[i];\n    }\n    function decreasing(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[n - 1 - i];\n    }\n    function alternate(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[i ^ 1];\n    }\n    function jigsaw(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[i % (n >> 4)];\n    }\n    function incbutone(arr, n, def) {\n        for (var i = 0; i < n; i++)\n            arr[i] = def[i];\n        if (n > 0)\n            arr[n >> 2] = def[n];\n    }\n    function incbutfirst(arr, n, def) {\n        if (n > 0)\n            arr[0] = def[n];\n        for (var i = 1; i < n; i++)\n            arr[i] = def[i];\n    }\n    function incbutlast(arr, n, def) {\n        for (var i = 0; i < n - 1; i++)\n            arr[i] = def[i + 1];\n        if (n > 0)\n            arr[n - 1] = def[0];\n    }\n\n    var sort_cases = [ random, random8, random1, jigsaw, hill, comb,\n                      crisscross, zero, increasing, decreasing, alternate,\n                      incbutone, incbutlast, incbutfirst ];\n\n    var n = sort_bench.array_size || 10000;\n    var array_type = sort_bench.array_type || Array;\n    var def, arr;\n    var i, j, x, y;\n    var total = 0;\n\n    var save_total_score = total_score;\n    var save_total_scale = total_scale;\n\n    // initialize default sorted array (n + 1 elements)\n    def = new array_type(n + 1);\n    if (array_type == Array) {\n        for (i = 0; i <= n; i++) {\n            def[i] = i + \"\";\n        }\n    } else {\n        for (i = 0; i <= n; i++) {\n            def[i] = i;\n        }\n    }\n    def.sort();\n    for (var f of sort_cases) {\n        var ti = 0, tx = 0;\n        for (j = 0; j < 100; j++) {\n            arr = new array_type(n);\n            f(arr, n, def);\n            var t1 = get_clock();\n            arr.sort();\n            t1 = get_clock() - t1;\n            tx += t1;\n            if (!ti || ti > t1)\n                ti = t1;\n            if (tx >= clocks_per_sec)\n                break;\n        }\n        total += ti;\n\n        i = 0;\n        x = arr[0];\n        if (x !== void 0) {\n            for (i = 1; i < n; i++) {\n                y = arr[i];\n                if (y === void 0)\n                    break;\n                if (x > y)\n                    break;\n                x = y;\n            }\n        }\n        while (i < n && arr[i] === void 0)\n            i++;\n        if (i < n) {\n            console.log(\"sort_bench: out of order error for \" + f.name +\n                        \" at offset \" + (i - 1) +\n                        \": \" + arr[i - 1] + \" > \" + arr[i]);\n        }\n        if (sort_bench.verbose)\n            log_one(\"sort_\" + f.name, n, ti, n * 100);\n    }\n    total_score = save_total_score;\n    total_scale = save_total_scale;\n    return total / n / 1000;\n}\nsort_bench.bench = true;\nsort_bench.verbose = false;\n\nfunction int_to_string(n)\n{\n    var s, r, j;\n    r = 0;\n    for(j = 0; j < n; j++) {\n        s = (j + 1).toString();\n    }\n    return n;\n}\n\nfunction float_to_string(n)\n{\n    var s, r, j;\n    r = 0;\n    for(j = 0; j < n; j++) {\n        s = (j + 0.1).toString();\n    }\n    return n;\n}\n\nfunction string_to_int(n)\n{\n    var s, r, j;\n    r = 0;\n    s = \"12345\";\n    r = 0;\n    for(j = 0; j < n; j++) {\n        r += (s | 0);\n    }\n    global_res = r;\n    return n;\n}\n\nfunction string_to_float(n)\n{\n    var s, r, j;\n    r = 0;\n    s = \"12345.6\";\n    r = 0;\n    for(j = 0; j < n; j++) {\n        r -= s;\n    }\n    global_res = r;\n    return n;\n}\n\nfunction load_result(filename)\n{\n    var f, str, res;\n    if (typeof std === \"undefined\")\n        return null;\n    f = std.open(filename, \"r\");\n    if (!f)\n        return null;\n    str = f.readAsString();\n    res = JSON.parse(str);\n    f.close();\n    return res;\n}\n\nfunction save_result(filename, obj)\n{\n    var f;\n    if (typeof std === \"undefined\")\n        return;\n    f = std.open(filename, \"w\");\n    f.puts(JSON.stringify(obj, null, 2));\n    f.puts(\"\\n\");\n    f.close();\n}\n\nfunction main(argc, argv, g)\n{\n    var test_list = [\n        empty_loop,\n        date_now,\n        prop_read,\n        prop_write,\n        prop_create,\n        prop_delete,\n        array_read,\n        array_write,\n        array_prop_create,\n        array_length_decr,\n        array_hole_length_decr,\n        array_push,\n        array_pop,\n        typed_array_read,\n        typed_array_write,\n        global_read,\n        global_write,\n        global_write_strict,\n        local_destruct,\n        global_destruct,\n        global_destruct_strict,\n        func_call,\n        closure_var,\n        int_arith,\n        float_arith,\n        set_collection_add,\n        array_for,\n        array_for_in,\n        array_for_of,\n        math_min,\n        string_build1,\n        string_build2,\n        //string_build3,\n        //string_build4,\n        sort_bench,\n        int_to_string,\n        float_to_string,\n        string_to_int,\n        string_to_float,\n    ];\n    var tests = [];\n    var i, j, n, f, name;\n    \n    if (typeof BigInt == \"function\") {\n        /* BigInt test */\n        test_list.push(bigint64_arith);\n        test_list.push(bigint256_arith);\n    }\n    if (typeof BigFloat == \"function\") {\n        /* BigFloat test */\n        test_list.push(float256_arith);\n    }\n    \n    for (i = 1; i < argc;) {\n        name = argv[i++];\n        if (name == \"-a\") {\n            sort_bench.verbose = true;\n            continue;\n        }\n        if (name == \"-t\") {\n            name = argv[i++];\n            sort_bench.array_type = g[name];\n            if (typeof sort_bench.array_type != \"function\") {\n                console.log(\"unknown array type: \" + name);\n                return 1;\n            }\n            continue;\n        }\n        if (name == \"-n\") {\n            sort_bench.array_size = +argv[i++];\n            continue;\n        }\n        for (j = 0; j < test_list.length; j++) {\n            f = test_list[j];\n            if (name === f.name) {\n                tests.push(f);\n                break;\n            }\n        }\n        if (j == test_list.length) {\n            console.log(\"unknown benchmark: \" + name);\n            return 1;\n        }\n    }\n    if (tests.length == 0)\n        tests = test_list;\n\n    ref_data = load_result(\"microbench.txt\");\n    log_data = {};\n    log_line.apply(null, heads);\n    n = 0;\n\n    for(i = 0; i < tests.length; i++) {\n        f = tests[i];\n        bench(f, f.name, ref_data, log_data);\n        if (ref_data && ref_data[f.name])\n            n++;\n    }\n    if (ref_data)\n        log_line(\"total\", \"\", total[2], total[3], total_score * 100 / total_scale);\n    else\n        log_line(\"total\", \"\", total[2]);\n        \n    if (tests == test_list)\n        save_result(\"microbench-new.txt\", log_data);\n}\n\nif (!scriptArgs)\n    scriptArgs = [];\nmain(scriptArgs.length, scriptArgs, this);\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/tests/test262.patch",
    "content": "diff --git a/harness/atomicsHelper.js b/harness/atomicsHelper.js\nindex 9c1217351e..3c24755558 100644\n--- a/harness/atomicsHelper.js\n+++ b/harness/atomicsHelper.js\n@@ -227,10 +227,14 @@ $262.agent.waitUntil = function(typedArray, index, expected) {\n  *   }\n  */\n $262.agent.timeouts = {\n-  yield: 100,\n-  small: 200,\n-  long: 1000,\n-  huge: 10000,\n+//  yield: 100,\n+//  small: 200,\n+//  long: 1000,\n+//  huge: 10000,\n+  yield: 20,\n+  small: 20,\n+  long: 100,\n+  huge: 1000,\n };\n \n /**\ndiff --git a/harness/regExpUtils.js b/harness/regExpUtils.js\nindex be7039fda0..7b38abf8df 100644\n--- a/harness/regExpUtils.js\n+++ b/harness/regExpUtils.js\n@@ -6,24 +6,27 @@ description: |\n defines: [buildString, testPropertyEscapes, matchValidator]\n ---*/\n \n+if ($262 && typeof $262.codePointRange === \"function\") {\n+    /* use C function to build the codePointRange (much faster with\n+       slow JS engines) */\n+    codePointRange = $262.codePointRange;\n+} else {\n+    codePointRange = function codePointRange(start, end) {\n+        const codePoints = [];\n+        let length = 0;\n+        for (codePoint = start; codePoint < end; codePoint++) {\n+            codePoints[length++] = codePoint;\n+        }\n+        return String.fromCodePoint.apply(null, codePoints);\n+    }\n+}\n+\n function buildString({ loneCodePoints, ranges }) {\n-  const CHUNK_SIZE = 10000;\n-  let result = Reflect.apply(String.fromCodePoint, null, loneCodePoints);\n-  for (let i = 0; i < ranges.length; i++) {\n-    const range = ranges[i];\n-    const start = range[0];\n-    const end = range[1];\n-    const codePoints = [];\n-    for (let length = 0, codePoint = start; codePoint <= end; codePoint++) {\n-      codePoints[length++] = codePoint;\n-      if (length === CHUNK_SIZE) {\n-        result += Reflect.apply(String.fromCodePoint, null, codePoints);\n-        codePoints.length = length = 0;\n-      }\n+    let result = String.fromCodePoint.apply(null, loneCodePoints);\n+    for (const [start, end] of ranges) {\n+        result += codePointRange(start, end + 1);\n     }\n-    result += Reflect.apply(String.fromCodePoint, null, codePoints);\n-  }\n-  return result;\n+    return result;\n }\n \n function testPropertyEscapes(regex, string, expression) {\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/tests/test_bignum.js",
    "content": "\"use strict\";\n\nfunction assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\nfunction assertThrows(err, func)\n{\n    var ex;\n    ex = false;\n    try {\n        func();\n    } catch(e) {\n        ex = true;\n        assert(e instanceof err);\n    }\n    assert(ex, true, \"exception expected\");\n}\n\n// load more elaborate version of assert if available\ntry { __loadScript(\"test_assert.js\"); } catch(e) {}\n\n/*----------------*/\n\nfunction bigint_pow(a, n)\n{\n    var r, i;\n    r = 1n;\n    for(i = 0n; i < n; i++)\n        r *= a;\n    return r;\n}\n\n/* a must be < b */\nfunction test_less(a, b)\n{\n    assert(a < b);\n    assert(!(b < a));\n    assert(a <= b);\n    assert(!(b <= a));\n    assert(b > a);\n    assert(!(a > b));\n    assert(b >= a);\n    assert(!(a >= b));\n    assert(a != b);\n    assert(!(a == b));\n}\n\n/* a must be numerically equal to b */\nfunction test_eq(a, b)\n{\n    assert(a == b);\n    assert(b == a);\n    assert(!(a != b));\n    assert(!(b != a));\n    assert(a <= b);\n    assert(b <= a);\n    assert(!(a < b));\n    assert(a >= b);\n    assert(b >= a);\n    assert(!(a > b));\n}\n\nfunction test_bigint1()\n{\n    var a, r;\n\n    test_less(2n, 3n);\n    test_eq(3n, 3n);\n\n    test_less(2, 3n);\n    test_eq(3, 3n);\n\n    test_less(2.1, 3n);\n    test_eq(Math.sqrt(4), 2n);\n\n    a = bigint_pow(3n, 100n);\n    assert((a - 1n) != a);\n    assert(a == 515377520732011331036461129765621272702107522001n);\n    assert(a == 0x5a4653ca673768565b41f775d6947d55cf3813d1n);\n\n    r = 1n << 31n;\n    assert(r, 2147483648n, \"1 << 31n === 2147483648n\");\n    \n    r = 1n << 32n;\n    assert(r, 4294967296n, \"1 << 32n === 4294967296n\");\n}\n\nfunction test_bigint2()\n{\n    assert(BigInt(\"\"), 0n);\n    assert(BigInt(\"  123\"), 123n);\n    assert(BigInt(\"  123   \"), 123n);\n    assertThrows(SyntaxError, () => { BigInt(\"+\") } );\n    assertThrows(SyntaxError, () => { BigInt(\"-\") } );\n    assertThrows(SyntaxError, () => { BigInt(\"\\x00a\") } );\n    assertThrows(SyntaxError, () => { BigInt(\"  123  r\") } );\n}\n\nfunction test_divrem(div1, a, b, q)\n{\n    var div, divrem, t;\n    div = BigInt[div1];\n    divrem = BigInt[div1 + \"rem\"];\n    assert(div(a, b) == q);\n    t = divrem(a, b);\n    assert(t[0] == q);\n    assert(a == b * q + t[1]);\n}\n\nfunction test_idiv1(div, a, b, r)\n{\n    test_divrem(div, a, b, r[0]);\n    test_divrem(div, -a, b, r[1]);\n    test_divrem(div, a, -b, r[2]);\n    test_divrem(div, -a, -b, r[3]);\n}\n\n/* QuickJS BigInt extensions */\nfunction test_bigint_ext()\n{\n    var r;\n    assert(BigInt.floorLog2(0n) === -1n);\n    assert(BigInt.floorLog2(7n) === 2n);\n\n    assert(BigInt.sqrt(0xffffffc000000000000000n) === 17592185913343n);\n    r = BigInt.sqrtrem(0xffffffc000000000000000n);\n    assert(r[0] === 17592185913343n);\n    assert(r[1] === 35167191957503n);\n\n    test_idiv1(\"tdiv\", 3n, 2n, [1n, -1n, -1n, 1n]);\n    test_idiv1(\"fdiv\", 3n, 2n, [1n, -2n, -2n, 1n]);\n    test_idiv1(\"cdiv\", 3n, 2n, [2n, -1n, -1n, 2n]);\n    test_idiv1(\"ediv\", 3n, 2n, [1n, -2n, -1n, 2n]);\n}\n\nfunction test_bigfloat()\n{\n    var e, a, b, sqrt2;\n    \n    assert(typeof 1n === \"bigint\");\n    assert(typeof 1l === \"bigfloat\");\n    assert(1 == 1.0l);\n    assert(1 !== 1.0l);\n\n    test_less(2l, 3l);\n    test_eq(3l, 3l);\n\n    test_less(2, 3l);\n    test_eq(3, 3l);\n\n    test_less(2.1, 3l);\n    test_eq(Math.sqrt(9), 3l);\n    \n    test_less(2n, 3l);\n    test_eq(3n, 3l);\n\n    e = new BigFloatEnv(128);\n    assert(e.prec == 128);\n    a = BigFloat.sqrt(2l, e);\n    assert(a === BigFloat.parseFloat(\"0x1.6a09e667f3bcc908b2fb1366ea957d3e\", 0, e));\n    assert(e.inexact === true);\n    assert(BigFloat.fpRound(a) == 0x1.6a09e667f3bcc908b2fb1366ea95l);\n    \n    b = BigFloatEnv.setPrec(BigFloat.sqrt.bind(null, 2), 128);\n    assert(a === b);\n\n    assert(BigFloat.isNaN(BigFloat(NaN)));\n    assert(BigFloat.isFinite(1l));\n    assert(!BigFloat.isFinite(1l/0l));\n\n    assert(BigFloat.abs(-3l) === 3l);\n    assert(BigFloat.sign(-3l) === -1l);\n\n    assert(BigFloat.exp(0.2l) === 1.2214027581601698339210719946396742l);\n    assert(BigFloat.log(3l) === 1.0986122886681096913952452369225256l);\n    assert(BigFloat.pow(2.1l, 1.6l) === 3.277561666451861947162828744873745l);\n    \n    assert(BigFloat.sin(-1l) === -0.841470984807896506652502321630299l);\n    assert(BigFloat.cos(1l) === 0.5403023058681397174009366074429766l);\n    assert(BigFloat.tan(0.1l) === 0.10033467208545054505808004578111154l);\n\n    assert(BigFloat.asin(0.3l) === 0.30469265401539750797200296122752915l);\n    assert(BigFloat.acos(0.4l) === 1.1592794807274085998465837940224159l);\n    assert(BigFloat.atan(0.7l) === 0.610725964389208616543758876490236l);\n    assert(BigFloat.atan2(7.1l, -5.1l) === 2.1937053809751415549388104628759813l);\n\n    assert(BigFloat.floor(2.5l) === 2l);\n    assert(BigFloat.ceil(2.5l) === 3l);\n    assert(BigFloat.trunc(-2.5l) === -2l);\n    assert(BigFloat.round(2.5l) === 3l);\n\n    assert(BigFloat.fmod(3l,2l) === 1l);\n    assert(BigFloat.remainder(3l,2l) === -1l);\n\n    /* string conversion */\n    assert((1234.125l).toString(), \"1234.125\");\n    assert((1234.125l).toFixed(2), \"1234.13\");\n    assert((1234.125l).toFixed(2, \"down\"), \"1234.12\");\n    assert((1234.125l).toExponential(), \"1.234125e+3\");\n    assert((1234.125l).toExponential(5), \"1.23413e+3\");\n    assert((1234.125l).toExponential(5, BigFloatEnv.RNDZ), \"1.23412e+3\");\n    assert((1234.125l).toPrecision(6), \"1234.13\");\n    assert((1234.125l).toPrecision(6, BigFloatEnv.RNDZ), \"1234.12\");\n\n    /* string conversion with binary base */\n    assert((0x123.438l).toString(16), \"123.438\");\n    assert((0x323.438l).toString(16), \"323.438\");\n    assert((0x723.438l).toString(16), \"723.438\");\n    assert((0xf23.438l).toString(16), \"f23.438\");\n    assert((0x123.438l).toFixed(2, BigFloatEnv.RNDNA, 16), \"123.44\");\n    assert((0x323.438l).toFixed(2, BigFloatEnv.RNDNA, 16), \"323.44\");\n    assert((0x723.438l).toFixed(2, BigFloatEnv.RNDNA, 16), \"723.44\");\n    assert((0xf23.438l).toFixed(2, BigFloatEnv.RNDNA, 16), \"f23.44\");\n    assert((0x0.0000438l).toFixed(6, BigFloatEnv.RNDNA, 16), \"0.000044\");\n    assert((0x1230000000l).toFixed(1, BigFloatEnv.RNDNA, 16), \"1230000000.0\");\n    assert((0x123.438l).toPrecision(5, BigFloatEnv.RNDNA, 16), \"123.44\");\n    assert((0x123.438l).toPrecision(5, BigFloatEnv.RNDZ, 16), \"123.43\");\n    assert((0x323.438l).toPrecision(5, BigFloatEnv.RNDNA, 16), \"323.44\");\n    assert((0x723.438l).toPrecision(5, BigFloatEnv.RNDNA, 16), \"723.44\");\n    assert((-0xf23.438l).toPrecision(5, BigFloatEnv.RNDD, 16), \"-f23.44\");\n    assert((0x123.438l).toExponential(4, BigFloatEnv.RNDNA, 16), \"1.2344p+8\");\n}\n\nfunction test_bigdecimal()\n{\n    assert(1m === 1m);\n    assert(1m !== 2m);\n    test_less(1m, 2m);\n    test_eq(2m, 2m);\n    \n    test_less(1, 2m);\n    test_eq(2, 2m);\n\n    test_less(1.1, 2m);\n    test_eq(Math.sqrt(4), 2m);\n    \n    test_less(2n, 3m);\n    test_eq(3n, 3m);\n    \n    assert(BigDecimal(\"1234.1\") === 1234.1m);\n    assert(BigDecimal(\"    1234.1\") === 1234.1m);\n    assert(BigDecimal(\"    1234.1  \") === 1234.1m);\n\n    assert(BigDecimal(0.1) === 0.1m);\n    assert(BigDecimal(123) === 123m);\n    assert(BigDecimal(true) === 1m);\n\n    assert(123m + 1m === 124m);\n    assert(123m - 1m === 122m);\n\n    assert(3.2m * 3m === 9.6m);\n    assert(10m / 2m === 5m);\n    assertThrows(RangeError, () => { 10m / 3m } );\n\n    assert(10m % 3m === 1m);\n    assert(-10m % 3m === -1m);\n\n    assert(1234.5m ** 3m === 1881365963.625m);\n    assertThrows(RangeError, () => { 2m ** 3.1m } );\n    assertThrows(RangeError, () => { 2m ** -3m } );\n    \n    assert(BigDecimal.sqrt(2m,\n                       { roundingMode: \"half-even\",\n                         maximumSignificantDigits: 4 }) === 1.414m);\n    assert(BigDecimal.sqrt(101m,\n                       { roundingMode: \"half-even\",\n                         maximumFractionDigits: 3 }) === 10.050m);\n    assert(BigDecimal.sqrt(0.002m,\n                       { roundingMode: \"half-even\",\n                         maximumFractionDigits: 3 }) === 0.045m);\n    \n    assert(BigDecimal.round(3.14159m,\n                       { roundingMode: \"half-even\",\n                         maximumFractionDigits: 3 }) === 3.142m);\n\n    assert(BigDecimal.add(3.14159m, 0.31212m,\n                          { roundingMode: \"half-even\",\n                            maximumFractionDigits: 2 }) === 3.45m);\n    assert(BigDecimal.sub(3.14159m, 0.31212m,\n                          { roundingMode: \"down\",\n                            maximumFractionDigits: 2 }) === 2.82m);\n    assert(BigDecimal.mul(3.14159m, 0.31212m,\n                          { roundingMode: \"half-even\",\n                            maximumFractionDigits: 3 }) === 0.981m);\n    assert(BigDecimal.mod(3.14159m, 0.31211m,\n                          { roundingMode: \"half-even\",\n                            maximumFractionDigits: 4 }) === 0.0205m);\n    assert(BigDecimal.div(20m, 3m,\n                       { roundingMode: \"half-even\",\n                         maximumSignificantDigits: 3 }) === 6.67m);\n    assert(BigDecimal.div(20m, 3m,\n                       { roundingMode: \"half-even\",\n                         maximumFractionDigits: 50 }) ===\n           6.66666666666666666666666666666666666666666666666667m);\n\n    /* string conversion */\n    assert((1234.125m).toString(), \"1234.125\");\n    assert((1234.125m).toFixed(2), \"1234.13\");\n    assert((1234.125m).toFixed(2, \"down\"), \"1234.12\");\n    assert((1234.125m).toExponential(), \"1.234125e+3\");\n    assert((1234.125m).toExponential(5), \"1.23413e+3\");\n    assert((1234.125m).toExponential(5, \"down\"), \"1.23412e+3\");\n    assert((1234.125m).toPrecision(6), \"1234.13\");\n    assert((1234.125m).toPrecision(6, \"down\"), \"1234.12\");\n    assert((-1234.125m).toPrecision(6, \"floor\"), \"-1234.13\");\n}\n\ntest_bigint1();\ntest_bigint2();\ntest_bigint_ext();\ntest_bigfloat();\ntest_bigdecimal();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/tests/test_bjson.js",
    "content": "import * as bjson from \"./bjson.so\";\n\nfunction assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\nfunction toHex(a)\n{\n    var i, s = \"\", tab, v;\n    tab = new Uint8Array(a);\n    for(i = 0; i < tab.length; i++) {\n        v = tab[i].toString(16);\n        if (v.length < 2)\n            v = \"0\" + v;\n        if (i !== 0)\n            s += \" \";\n        s += v;\n    }\n    return s;\n}\n\nfunction isArrayLike(a)\n{\n    return Array.isArray(a) || \n        (a instanceof Uint8ClampedArray) ||\n        (a instanceof Uint8Array) ||\n        (a instanceof Uint16Array) ||\n        (a instanceof Uint32Array) ||\n        (a instanceof Int8Array) ||\n        (a instanceof Int16Array) ||\n        (a instanceof Int32Array) ||\n        (a instanceof Float32Array) ||\n        (a instanceof Float64Array);\n}\n\nfunction toStr(a)\n{\n    var s, i, props, prop;\n\n    switch(typeof(a)) {\n    case \"object\":\n        if (a === null)\n            return \"null\";\n        if (a instanceof Date) {\n            s = \"Date(\" + toStr(a.valueOf()) + \")\";\n        } else if (a instanceof Number) {\n            s = \"Number(\" + toStr(a.valueOf()) + \")\";\n        } else if (a instanceof String) {\n            s = \"String(\" + toStr(a.valueOf()) + \")\";\n        } else if (a instanceof Boolean) {\n            s = \"Boolean(\" + toStr(a.valueOf()) + \")\";\n        } else if (isArrayLike(a)) {\n            s = \"[\";\n            for(i = 0; i < a.length; i++) {\n                if (i != 0)\n                    s += \",\";\n                s += toStr(a[i]);\n            }\n            s += \"]\";\n        } else {\n            props = Object.keys(a);\n            s = \"{\";\n            for(i = 0; i < props.length; i++) {\n                if (i != 0)\n                    s += \",\";\n                prop = props[i];\n                s += prop + \":\" + toStr(a[prop]);\n            }\n            s += \"}\";\n        }\n        return s;\n    case \"undefined\":\n        return \"undefined\";\n    case \"string\":\n        return a.__quote();\n    case \"number\":\n    case \"bigfloat\":\n        if (a == 0 && 1 / a < 0)\n            return \"-0\";\n        else\n            return a.toString();\n        break;\n    default:\n        return a.toString();\n    }\n}\n\nfunction bjson_test(a)\n{\n    var buf, r, a_str, r_str;\n    a_str = toStr(a);\n    buf = bjson.write(a);\n    if (0) {\n        print(a_str, \"->\", toHex(buf));\n    }\n    r = bjson.read(buf, 0, buf.byteLength);\n    r_str = toStr(r);\n    if (a_str != r_str) {\n        print(a_str);\n        print(r_str);\n        assert(false);\n    }\n}\n\n/* test multiple references to an object including circular\n   references */\nfunction bjson_test_reference()\n{\n    var array, buf, i, n, array_buffer;\n    n = 16;\n    array = [];\n    for(i = 0; i < n; i++)\n        array[i] = {};\n    array_buffer = new ArrayBuffer(n);\n    for(i = 0; i < n; i++) {\n        array[i].next = array[(i + 1) % n];\n        array[i].idx = i;\n        array[i].typed_array = new Uint8Array(array_buffer, i, 1);\n    }\n    buf = bjson.write(array, true);\n\n    array = bjson.read(buf, 0, buf.byteLength, true);\n\n    /* check the result */\n    for(i = 0; i < n; i++) {\n        assert(array[i].next, array[(i + 1) % n]);\n        assert(array[i].idx, i);\n        assert(array[i].typed_array.buffer, array_buffer);\n        assert(array[i].typed_array.length, 1);\n        assert(array[i].typed_array.byteOffset, i);\n    }\n}\n\nfunction bjson_test_all()\n{\n    var obj;\n    \n    bjson_test({x:1, y:2, if:3});\n    bjson_test([1, 2, 3]);\n    bjson_test([1.0, \"aa\", true, false, undefined, null, NaN, -Infinity, -0.0]);\n    if (typeof BigInt !== \"undefined\") {\n        bjson_test([BigInt(\"1\"), -BigInt(\"0x123456789\"),\n               BigInt(\"0x123456789abcdef123456789abcdef\")]);\n    }\n    if (typeof BigFloat !== \"undefined\") {\n        BigFloatEnv.setPrec(function () {\n            bjson_test([BigFloat(\"0.1\"), BigFloat(\"-1e30\"), BigFloat(\"0\"),\n                   BigFloat(\"-0\"), BigFloat(\"Infinity\"), BigFloat(\"-Infinity\"),\n                   0.0 / BigFloat(\"0\"), BigFloat.MAX_VALUE,\n                   BigFloat.MIN_VALUE]);\n        }, 113, 15);\n    }\n    if (typeof BigDecimal !== \"undefined\") {\n        bjson_test([BigDecimal(\"0\"),\n                    BigDecimal(\"0.8\"), BigDecimal(\"123321312321321e100\"),\n                    BigDecimal(\"-1233213123213214332333223332e100\"),\n                    BigDecimal(\"1.233e-1000\")]);\n    }\n\n    bjson_test([new Date(1234), new String(\"abc\"), new Number(-12.1), new Boolean(true)]);\n\n    bjson_test(new Int32Array([123123, 222111, -32222]));\n    bjson_test(new Float64Array([123123, 222111.5]));\n    \n    /* tested with a circular reference */\n    obj = {};\n    obj.x = obj;\n    try {\n        bjson.write(obj);\n        assert(false);\n    } catch(e) {\n        assert(e instanceof TypeError);\n    }\n\n    bjson_test_reference();\n}\n\nbjson_test_all();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/tests/test_builtin.js",
    "content": "\"use strict\";\n\nfunction assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\nfunction assert_throws(expected_error, func)\n{\n    var err = false;\n    try {\n        func();\n    } catch(e) {\n        err = true;\n        if (!(e instanceof expected_error)) {\n            throw Error(\"unexpected exception type\");\n        }\n    }\n    if (!err) {\n        throw Error(\"expected exception\");\n    }\n}\n\n// load more elaborate version of assert if available\ntry { __loadScript(\"test_assert.js\"); } catch(e) {}\n\n/*----------------*/\n\nfunction my_func(a, b)\n{\n    return a + b;\n}\n\nfunction test_function()\n{\n    function f(a, b) {\n        var i, tab = [];\n        tab.push(this);\n        for(i = 0; i < arguments.length; i++)\n            tab.push(arguments[i]);\n        return tab;\n    }\n    function constructor1(a) {\n        this.x = a;\n    }\n\n    var r, g;\n    \n    r = my_func.call(null, 1, 2);\n    assert(r, 3, \"call\");\n\n    r = my_func.apply(null, [1, 2]);\n    assert(r, 3, \"apply\");\n\n    r = (function () { return 1; }).apply(null, undefined);\n    assert(r, 1);\n\n    assert_throws(TypeError, (function() {\n        Reflect.apply((function () { return 1; }), null, undefined);\n    }));\n    \n    r = new Function(\"a\", \"b\", \"return a + b;\");\n    assert(r(2,3), 5, \"function\");\n    \n    g = f.bind(1, 2);\n    assert(g.length, 1);\n    assert(g.name, \"bound f\");\n    assert(g(3), [1,2,3]);\n\n    g = constructor1.bind(null, 1);\n    r = new g();\n    assert(r.x, 1);\n}\n\nfunction test()\n{\n    var r, a, b, c, err;\n\n    r = Error(\"hello\");\n    assert(r.message, \"hello\", \"Error\");\n\n    a = new Object();\n    a.x = 1;\n    assert(a.x, 1, \"Object\");\n\n    assert(Object.getPrototypeOf(a), Object.prototype, \"getPrototypeOf\");\n    Object.defineProperty(a, \"y\", { value: 3, writable: true, configurable: true, enumerable: true });\n    assert(a.y, 3, \"defineProperty\");\n\n    Object.defineProperty(a, \"z\", { get: function () { return 4; }, set: function(val) { this.z_val = val; }, configurable: true, enumerable: true });\n    assert(a.z, 4, \"get\");\n    a.z = 5;\n    assert(a.z_val, 5, \"set\");\n    \n    a = { get z() { return 4; }, set z(val) { this.z_val = val; } };\n    assert(a.z, 4, \"get\");\n    a.z = 5;\n    assert(a.z_val, 5, \"set\");\n\n    b = Object.create(a);\n    assert(Object.getPrototypeOf(b), a, \"create\");\n    c = {u:2};\n    /* XXX: refcount bug in 'b' instead of 'a' */\n    Object.setPrototypeOf(a, c);\n    assert(Object.getPrototypeOf(a), c, \"setPrototypeOf\");\n\n    a = {};\n    assert(a.toString(), \"[object Object]\", \"toString\");\n\n    a = {x:1};\n    assert(Object.isExtensible(a), true, \"extensible\");\n    Object.preventExtensions(a);\n\n    err = false;\n    try {\n        a.y = 2;\n    } catch(e) {\n        err = true;\n    }\n    assert(Object.isExtensible(a), false, \"extensible\");\n    assert(typeof a.y, \"undefined\", \"extensible\");\n    assert(err, true, \"extensible\");\n}\n\nfunction test_enum()\n{\n    var a, tab;\n    a = {x:1,\n         \"18014398509481984\": 1,\n         \"9007199254740992\": 1,\n         \"9007199254740991\": 1,\n         \"4294967296\": 1,\n         \"4294967295\": 1,\n         y:1,\n         \"4294967294\": 1,\n         \"1\": 2};\n    tab = Object.keys(a);\n//    console.log(\"tab=\" + tab.toString());\n    assert(tab, [\"1\",\"4294967294\",\"x\",\"18014398509481984\",\"9007199254740992\",\"9007199254740991\",\"4294967296\",\"4294967295\",\"y\"], \"keys\");\n}\n\nfunction test_array()\n{\n    var a, err;\n\n    a = [1, 2, 3];\n    assert(a.length, 3, \"array\");\n    assert(a[2], 3, \"array1\");\n\n    a = new Array(10);\n    assert(a.length, 10, \"array2\");\n\n    a = new Array(1, 2);\n    assert(a.length === 2 && a[0] === 1 && a[1] === 2, true, \"array3\");\n\n    a = [1, 2, 3];\n    a.length = 2;\n    assert(a.length === 2 && a[0] === 1 && a[1] === 2, true, \"array4\");\n\n    a = [];\n    a[1] = 10;\n    a[4] = 3;\n    assert(a.length, 5);\n\n    a = [1,2];\n    a.length = 5;\n    a[4] = 1;\n    a.length = 4;\n    assert(a[4] !== 1, true, \"array5\");\n\n    a = [1,2];\n    a.push(3,4);\n    assert(a.join(), \"1,2,3,4\", \"join\");\n\n    a = [1,2,3,4,5];\n    Object.defineProperty(a, \"3\", { configurable: false });\n    err = false;\n    try {\n        a.length = 2;\n    } catch(e) {\n        err = true;\n    }\n    assert(err && a.toString() === \"1,2,3,4\");\n}\n\nfunction test_string()\n{\n    var a;\n    a = String(\"abc\");\n    assert(a.length, 3, \"string\");\n    assert(a[1], \"b\", \"string\");\n    assert(a.charCodeAt(1), 0x62, \"string\");\n    assert(String.fromCharCode(65), \"A\", \"string\");\n    assert(String.fromCharCode.apply(null, [65, 66, 67]), \"ABC\", \"string\");\n    assert(a.charAt(1), \"b\");\n    assert(a.charAt(-1), \"\");\n    assert(a.charAt(3), \"\");\n    \n    a = \"abcd\";\n    assert(a.substring(1, 3), \"bc\", \"substring\");\n    a = String.fromCharCode(0x20ac);\n    assert(a.charCodeAt(0), 0x20ac, \"unicode\");\n    assert(a, \"€\", \"unicode\");\n    assert(a, \"\\u20ac\", \"unicode\");\n    assert(a, \"\\u{20ac}\", \"unicode\");\n    assert(\"a\", \"\\x61\", \"unicode\");\n        \n    a = \"\\u{10ffff}\";\n    assert(a.length, 2, \"unicode\");\n    assert(a, \"\\u{dbff}\\u{dfff}\", \"unicode\");\n    assert(a.codePointAt(0), 0x10ffff);\n    assert(String.fromCodePoint(0x10ffff), a);\n\n    assert(\"a\".concat(\"b\", \"c\"), \"abc\");\n\n    assert(\"abcabc\".indexOf(\"cab\"), 2);\n    assert(\"abcabc\".indexOf(\"cab2\"), -1);\n    assert(\"abc\".indexOf(\"c\"), 2);\n\n    assert(\"aaa\".indexOf(\"a\"), 0);\n    assert(\"aaa\".indexOf(\"a\", NaN), 0);\n    assert(\"aaa\".indexOf(\"a\", -Infinity), 0);\n    assert(\"aaa\".indexOf(\"a\", -1), 0);\n    assert(\"aaa\".indexOf(\"a\", -0), 0);\n    assert(\"aaa\".indexOf(\"a\", 0), 0);\n    assert(\"aaa\".indexOf(\"a\", 1), 1);\n    assert(\"aaa\".indexOf(\"a\", 2), 2);\n    assert(\"aaa\".indexOf(\"a\", 3), -1);\n    assert(\"aaa\".indexOf(\"a\", 4), -1);\n    assert(\"aaa\".indexOf(\"a\", Infinity), -1);\n\n    assert(\"aaa\".indexOf(\"\"), 0);\n    assert(\"aaa\".indexOf(\"\", NaN), 0);\n    assert(\"aaa\".indexOf(\"\", -Infinity), 0);\n    assert(\"aaa\".indexOf(\"\", -1), 0);\n    assert(\"aaa\".indexOf(\"\", -0), 0);\n    assert(\"aaa\".indexOf(\"\", 0), 0);\n    assert(\"aaa\".indexOf(\"\", 1), 1);\n    assert(\"aaa\".indexOf(\"\", 2), 2);\n    assert(\"aaa\".indexOf(\"\", 3), 3);\n    assert(\"aaa\".indexOf(\"\", 4), 3);\n    assert(\"aaa\".indexOf(\"\", Infinity), 3);\n\n    assert(\"aaa\".lastIndexOf(\"a\"), 2);\n    assert(\"aaa\".lastIndexOf(\"a\", NaN), 2);\n    assert(\"aaa\".lastIndexOf(\"a\", -Infinity), 0);\n    assert(\"aaa\".lastIndexOf(\"a\", -1), 0);\n    assert(\"aaa\".lastIndexOf(\"a\", -0), 0);\n    assert(\"aaa\".lastIndexOf(\"a\", 0), 0);\n    assert(\"aaa\".lastIndexOf(\"a\", 1), 1);\n    assert(\"aaa\".lastIndexOf(\"a\", 2), 2);\n    assert(\"aaa\".lastIndexOf(\"a\", 3), 2);\n    assert(\"aaa\".lastIndexOf(\"a\", 4), 2);\n    assert(\"aaa\".lastIndexOf(\"a\", Infinity), 2);\n\n    assert(\"aaa\".lastIndexOf(\"\"), 3);\n    assert(\"aaa\".lastIndexOf(\"\", NaN), 3);\n    assert(\"aaa\".lastIndexOf(\"\", -Infinity), 0);\n    assert(\"aaa\".lastIndexOf(\"\", -1), 0);\n    assert(\"aaa\".lastIndexOf(\"\", -0), 0);\n    assert(\"aaa\".lastIndexOf(\"\", 0), 0);\n    assert(\"aaa\".lastIndexOf(\"\", 1), 1);\n    assert(\"aaa\".lastIndexOf(\"\", 2), 2);\n    assert(\"aaa\".lastIndexOf(\"\", 3), 3);\n    assert(\"aaa\".lastIndexOf(\"\", 4), 3);\n    assert(\"aaa\".lastIndexOf(\"\", Infinity), 3);\n\n    assert(\"a,b,c\".split(\",\"), [\"a\",\"b\",\"c\"]);\n    assert(\",b,c\".split(\",\"), [\"\",\"b\",\"c\"]);\n    assert(\"a,b,\".split(\",\"), [\"a\",\"b\",\"\"]);\n\n    assert(\"aaaa\".split(), [ \"aaaa\" ]);\n    assert(\"aaaa\".split(undefined, 0), [ ]);\n    assert(\"aaaa\".split(\"\"), [ \"a\", \"a\", \"a\", \"a\" ]);\n    assert(\"aaaa\".split(\"\", 0), [ ]);\n    assert(\"aaaa\".split(\"\", 1), [ \"a\" ]);\n    assert(\"aaaa\".split(\"\", 2), [ \"a\", \"a\" ]);\n    assert(\"aaaa\".split(\"a\"), [ \"\", \"\", \"\", \"\", \"\" ]);\n    assert(\"aaaa\".split(\"a\", 2), [ \"\", \"\" ]);\n    assert(\"aaaa\".split(\"aa\"), [ \"\", \"\", \"\" ]);\n    assert(\"aaaa\".split(\"aa\", 0), [ ]);\n    assert(\"aaaa\".split(\"aa\", 1), [ \"\" ]);\n    assert(\"aaaa\".split(\"aa\", 2), [ \"\", \"\" ]);\n    assert(\"aaaa\".split(\"aaa\"), [ \"\", \"a\" ]);\n    assert(\"aaaa\".split(\"aaaa\"), [ \"\", \"\" ]);\n    assert(\"aaaa\".split(\"aaaaa\"), [ \"aaaa\" ]);\n    assert(\"aaaa\".split(\"aaaaa\", 0), [  ]);\n    assert(\"aaaa\".split(\"aaaaa\", 1), [ \"aaaa\" ]);\n\n    assert(eval('\"\\0\"'), \"\\0\");\n\n    assert(\"abc\".padStart(Infinity, \"\"), \"abc\");\n}\n\nfunction test_math()\n{\n    var a;\n    a = 1.4;\n    assert(Math.floor(a), 1);\n    assert(Math.ceil(a), 2);\n    assert(Math.imul(0x12345678, 123), -1088058456);\n    assert(Math.fround(0.1), 0.10000000149011612);\n    assert(Math.hypot() == 0);\n    assert(Math.hypot(-2) == 2);\n    assert(Math.hypot(3, 4) == 5);\n    assert(Math.abs(Math.hypot(3, 4, 5) - 7.0710678118654755) <= 1e-15);\n}\n\nfunction test_number()\n{\n    assert(parseInt(\"123\"), 123);\n    assert(parseInt(\"  123r\"), 123);\n    assert(parseInt(\"0x123\"), 0x123);\n    assert(parseInt(\"0o123\"), 0);\n    assert(+\"  123   \", 123);\n    assert(+\"0b111\", 7);\n    assert(+\"0o123\", 83);\n    assert(parseFloat(\"0x1234\"), 0);\n    assert(parseFloat(\"Infinity\"), Infinity);\n    assert(parseFloat(\"-Infinity\"), -Infinity);\n    assert(parseFloat(\"123.2\"), 123.2);\n    assert(parseFloat(\"123.2e3\"), 123200);\n    assert(Number.isNaN(Number(\"+\")));\n    assert(Number.isNaN(Number(\"-\")));\n    assert(Number.isNaN(Number(\"\\x00a\")));\n\n    assert((25).toExponential(0), \"3e+1\");\n    assert((-25).toExponential(0), \"-3e+1\");\n    assert((2.5).toPrecision(1), \"3\");\n    assert((-2.5).toPrecision(1), \"-3\");\n    assert((1.125).toFixed(2), \"1.13\");\n    assert((-1.125).toFixed(2), \"-1.13\");\n}\n\nfunction test_eval2()\n{\n    var g_call_count = 0;\n    /* force non strict mode for f1 and f2 */\n    var f1 = new Function(\"eval\", \"eval(1, 2)\");\n    var f2 = new Function(\"eval\", \"eval(...[1, 2])\");\n    function g(a, b) {\n        assert(a, 1);\n        assert(b, 2);\n        g_call_count++;\n    }\n    f1(g);\n    f2(g);\n    assert(g_call_count, 2);\n}\n\nfunction test_eval()\n{\n    function f(b) {\n        var x = 1;\n        return eval(b);\n    }\n    var r, a;\n\n    r = eval(\"1+1;\");\n    assert(r, 2, \"eval\");\n\n    r = eval(\"var my_var=2; my_var;\");\n    assert(r, 2, \"eval\");\n    assert(typeof my_var, \"undefined\");\n\n    assert(eval(\"if (1) 2; else 3;\"), 2);\n    assert(eval(\"if (0) 2; else 3;\"), 3);\n\n    assert(f.call(1, \"this\"), 1);\n    \n    a = 2;\n    assert(eval(\"a\"), 2);\n\n    eval(\"a = 3\");\n    assert(a, 3);\n\n    assert(f(\"arguments.length\", 1), 2);\n    assert(f(\"arguments[1]\", 1), 1);\n\n    a = 4;\n    assert(f(\"a\"), 4);\n    f(\"a=3\");\n    assert(a, 3);\n\n    test_eval2();\n}\n\nfunction test_typed_array()\n{\n    var buffer, a, i, str;\n\n    a = new Uint8Array(4);\n    assert(a.length, 4);\n    for(i = 0; i < a.length; i++)\n        a[i] = i;\n    assert(a.join(\",\"), \"0,1,2,3\");\n    a[0] = -1;\n    assert(a[0], 255);\n\n    a = new Int8Array(3);\n    a[0] = 255;\n    assert(a[0], -1);\n\n    a = new Int32Array(3);\n    a[0] = Math.pow(2, 32) - 1;\n    assert(a[0], -1);\n    assert(a.BYTES_PER_ELEMENT, 4);\n\n    a = new Uint8ClampedArray(4);\n    a[0] = -100;\n    a[1] = 1.5;\n    a[2] = 0.5;\n    a[3] = 1233.5;\n    assert(a.toString(), \"0,2,0,255\");\n    \n    buffer = new ArrayBuffer(16);\n    assert(buffer.byteLength, 16);\n    a = new Uint32Array(buffer, 12, 1);\n    assert(a.length, 1);\n    a[0] = -1;\n\n    a = new Uint16Array(buffer, 2);\n    a[0] = -1;\n\n    a = new Float32Array(buffer, 8, 1);\n    a[0] = 1;\n    \n    a = new Uint8Array(buffer);\n\n    str = a.toString();\n    /* test little and big endian cases */\n    if (str !== \"0,0,255,255,0,0,0,0,0,0,128,63,255,255,255,255\" &&\n        str !== \"0,0,255,255,0,0,0,0,63,128,0,0,255,255,255,255\") {\n        assert(false);\n    }\n\n    assert(a.buffer, buffer);\n\n    a = new Uint8Array([1, 2, 3, 4]);\n    assert(a.toString(), \"1,2,3,4\");\n    a.set([10, 11], 2);\n    assert(a.toString(), \"1,2,10,11\");\n}\n\nfunction test_json()\n{\n    var a, s;\n    s = '{\"x\":1,\"y\":true,\"z\":null,\"a\":[1,2,3],\"s\":\"str\"}';\n    a = JSON.parse(s);\n    assert(a.x, 1);\n    assert(a.y, true);\n    assert(a.z, null);\n    assert(JSON.stringify(a), s);\n\n    /* indentation test */\n    assert(JSON.stringify([[{x:1,y:{},z:[]},2,3]],undefined,1),\n`[\n [\n  {\n   \"x\": 1,\n   \"y\": {},\n   \"z\": []\n  },\n  2,\n  3\n ]\n]`);\n}\n\nfunction test_date()\n{\n    var d = new Date(1506098258091), a, s;\n    assert(d.toISOString(), \"2017-09-22T16:37:38.091Z\");\n    d.setUTCHours(18, 10, 11);\n    assert(d.toISOString(), \"2017-09-22T18:10:11.091Z\");\n    a = Date.parse(d.toISOString());\n    assert((new Date(a)).toISOString(), d.toISOString());\n    s = new Date(\"2020-01-01T01:01:01.1Z\").toISOString();\n    assert(s ==  \"2020-01-01T01:01:01.100Z\");\n    s = new Date(\"2020-01-01T01:01:01.12Z\").toISOString();\n    assert(s ==  \"2020-01-01T01:01:01.120Z\");\n    s = new Date(\"2020-01-01T01:01:01.123Z\").toISOString();\n    assert(s ==  \"2020-01-01T01:01:01.123Z\");\n    s = new Date(\"2020-01-01T01:01:01.1234Z\").toISOString();\n    assert(s ==  \"2020-01-01T01:01:01.123Z\");\n    s = new Date(\"2020-01-01T01:01:01.12345Z\").toISOString();\n    assert(s ==  \"2020-01-01T01:01:01.123Z\");\n    s = new Date(\"2020-01-01T01:01:01.1235Z\").toISOString();\n    assert(s ==  \"2020-01-01T01:01:01.124Z\");\n    s = new Date(\"2020-01-01T01:01:01.9999Z\").toISOString();\n    assert(s ==  \"2020-01-01T01:01:02.000Z\");\n}\n\nfunction test_regexp()\n{\n    var a, str;\n    str = \"abbbbbc\";\n    a = /(b+)c/.exec(str);\n    assert(a[0], \"bbbbbc\");\n    assert(a[1], \"bbbbb\");\n    assert(a.index, 1);\n    assert(a.input, str);\n    a = /(b+)c/.test(str);\n    assert(a, true);\n    assert(/\\x61/.exec(\"a\")[0], \"a\");\n    assert(/\\u0061/.exec(\"a\")[0], \"a\");\n    assert(/\\ca/.exec(\"\\x01\")[0], \"\\x01\");\n    assert(/\\\\a/.exec(\"\\\\a\")[0], \"\\\\a\");\n    assert(/\\c0/.exec(\"\\\\c0\")[0], \"\\\\c0\");\n\n    a = /(\\.(?=com|org)|\\/)/.exec(\"ah.com\");\n    assert(a.index === 2 && a[0] === \".\");\n\n    a = /(\\.(?!com|org)|\\/)/.exec(\"ah.com\");\n    assert(a, null);\n    \n    a = /(?=(a+))/.exec(\"baaabac\");\n    assert(a.index === 1 && a[0] === \"\" && a[1] === \"aaa\");\n\n    a = /(z)((a+)?(b+)?(c))*/.exec(\"zaacbbbcac\");\n    assert(a, [\"zaacbbbcac\",\"z\",\"ac\",\"a\",,\"c\"]);\n\n    a = eval(\"/\\0a/\");\n    assert(a.toString(), \"/\\0a/\");\n    assert(a.exec(\"\\0a\")[0], \"\\0a\");\n\n    assert(/{1a}/.toString(), \"/{1a}/\");\n    a = /a{1+/.exec(\"a{11\");\n    assert(a, [\"a{11\"] );\n}\n\nfunction test_symbol()\n{\n    var a, b, obj, c;\n    a = Symbol(\"abc\");\n    obj = {};\n    obj[a] = 2;\n    assert(obj[a], 2);\n    assert(typeof obj[\"abc\"], \"undefined\");\n    assert(String(a), \"Symbol(abc)\");\n    b = Symbol(\"abc\");\n    assert(a == a);\n    assert(a === a);\n    assert(a != b);\n    assert(a !== b);\n\n    b = Symbol.for(\"abc\");\n    c = Symbol.for(\"abc\");\n    assert(b === c);\n    assert(b !== a);\n\n    assert(Symbol.keyFor(b), \"abc\");\n    assert(Symbol.keyFor(a), undefined);\n\n    a = Symbol(\"aaa\");\n    assert(a.valueOf(), a);\n    assert(a.toString(), \"Symbol(aaa)\");\n\n    b = Object(a);\n    assert(b.valueOf(), a);\n    assert(b.toString(), \"Symbol(aaa)\");\n}\n\nfunction test_map()\n{\n    var a, i, n, tab, o, v;\n    n = 1000;\n    a = new Map();\n    tab = [];\n    for(i = 0; i < n; i++) {\n        v = { };\n        o = { id: i };\n        tab[i] = [o, v];\n        a.set(o, v);\n    }\n\n    assert(a.size, n);\n    for(i = 0; i < n; i++) {\n        assert(a.get(tab[i][0]), tab[i][1]);\n    }\n\n    i = 0;\n    a.forEach(function (v, o) { \n        assert(o, tab[i++][0]);\n        assert(a.has(o));\n        assert(a.delete(o));\n        assert(!a.has(o));\n    });\n\n    assert(a.size, 0);\n}\n\nfunction test_weak_map()\n{\n    var a, i, n, tab, o, v, n2;\n    a = new WeakMap();\n    n = 10;\n    tab = [];\n    for(i = 0; i < n; i++) {\n        v = { };\n        o = { id: i };\n        tab[i] = [o, v];\n        a.set(o, v);\n    }\n    o = null;\n    \n    n2 = n >> 1;\n    for(i = 0; i < n2; i++) {\n        a.delete(tab[i][0]);\n    }\n    for(i = n2; i < n; i++) {\n        tab[i][0] = null; /* should remove the object from the WeakMap too */\n    }\n    /* the WeakMap should be empty here */\n}\n\nfunction test_generator()\n{\n    function *f() {\n        var ret;\n        yield 1;\n        ret = yield 2;\n        assert(ret, \"next_arg\");\n        return 3;\n    }\n    function *f2() {\n        yield 1;\n        yield 2;\n        return \"ret_val\";\n    }\n    function *f1() {\n        var ret = yield *f2();\n        assert(ret, \"ret_val\");\n        return 3;\n    }\n    var g, v;\n    g = f();\n    v = g.next();\n    assert(v.value === 1 && v.done === false);\n    v = g.next();\n    assert(v.value === 2 && v.done === false);\n    v = g.next(\"next_arg\");\n    assert(v.value === 3 && v.done === true);\n    v = g.next();\n    assert(v.value === undefined && v.done === true);\n\n    g = f1();\n    v = g.next();\n    assert(v.value === 1 && v.done === false);\n    v = g.next();\n    assert(v.value === 2 && v.done === false);\n    v = g.next();\n    assert(v.value === 3 && v.done === true);\n    v = g.next();\n    assert(v.value === undefined && v.done === true);\n}\n\ntest();\ntest_function();\ntest_enum();\ntest_array();\ntest_string();\ntest_math();\ntest_number();\ntest_eval();\ntest_typed_array();\ntest_json();\ntest_date();\ntest_regexp();\ntest_symbol();\ntest_map();\ntest_weak_map();\ntest_generator();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/tests/test_closure.js",
    "content": "function assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\n// load more elaborate version of assert if available\ntry { __loadScript(\"test_assert.js\"); } catch(e) {}\n\n/*----------------*/\n\nvar log_str = \"\";\n\nfunction log(str)\n{\n    log_str += str + \",\";\n}\n\nfunction f(a, b, c)\n{\n    var x = 10;\n    log(\"a=\"+a);\n    function g(d) {\n        function h() {\n            log(\"d=\" + d);\n            log(\"x=\" + x);\n        }\n        log(\"b=\" + b);\n        log(\"c=\" + c);\n        h();\n    }\n    g(4);\n    return g;\n}\n\nvar g1 = f(1, 2, 3);\ng1(5);\n\nassert(log_str, \"a=1,b=2,c=3,d=4,x=10,b=2,c=3,d=5,x=10,\", \"closure1\");\n\nfunction test_closure1()\n{\n    function f2()\n    {\n        var val = 1;\n        \n        function set(a) {\n            val = a;\n        }\n        function get(a) {\n            return val;\n        }\n        return { \"set\": set, \"get\": get };\n    }\n    \n    var obj = f2();\n    obj.set(10);\n    var r;\n    r = obj.get();\n    assert(r, 10, \"closure2\");\n}\n\nfunction test_closure2()\n{\n    var expr_func = function myfunc1(n) {\n        function myfunc2(n) {\n            return myfunc1(n - 1);\n        }\n        if (n == 0)\n            return 0;\n        else\n            return myfunc2(n);\n    };\n    var r;\n    r = expr_func(1);\n    assert(r, 0, \"expr_func\");\n}\n\nfunction test_closure3()\n{\n    function fib(n)\n    {\n        if (n <= 0)\n            return 0;\n        else if (n == 1)\n            return 1;\n        else\n            return fib(n - 1) + fib(n - 2);\n    }\n\n    var fib_func = function fib1(n)\n    {\n        if (n <= 0)\n            return 0;\n        else if (n == 1)\n            return 1;\n        else\n            return fib1(n - 1) + fib1(n - 2);\n    };\n\n    assert(fib(6), 8, \"fib\");\n    assert(fib_func(6), 8, \"fib_func\");\n}\n\nfunction test_arrow_function()\n{\n    \"use strict\";\n\n    function f1() {\n        return (() => arguments)();\n    }\n    function f2() {\n        return (() => this)();\n    }\n    function f3() {\n        return (() => eval(\"this\"))();\n    }\n    function f4() {\n        return (() => eval(\"new.target\"))();\n    }\n    var a;\n\n    a = f1(1, 2);\n    assert(a.length, 2);\n    assert(a[0] === 1 && a[1] === 2);\n\n    assert(f2.call(\"this_val\") === \"this_val\");\n    assert(f3.call(\"this_val\") === \"this_val\");\n    assert(new f4() === f4);\n\n    var o1 = { f() { return this; } };\n    var o2 = { f() {\n        return (() => eval(\"super.f()\"))();\n    } };\n    o2.__proto__ = o1;\n\n    assert(o2.f() === o2);\n}\n\nfunction test_with()\n{\n    var o1 = { x: \"o1\", y: \"o1\" };\n    var x = \"local\";\n    eval('var z=\"var_obj\";');\n    assert(z === \"var_obj\");\n    with (o1) {\n        assert(x === \"o1\");\n        assert(eval(\"x\") === \"o1\");\n        var f = function () {\n            o2 = { x: \"o2\" };\n            with (o2) {\n                assert(x === \"o2\");\n                assert(y === \"o1\");\n                assert(z === \"var_obj\");\n                assert(eval(\"x\") === \"o2\");\n                assert(eval(\"y\") === \"o1\");\n                assert(eval(\"z\") === \"var_obj\");\n                assert(eval('eval(\"x\")') === \"o2\");\n            }\n        };\n        f();\n    }\n}\n\nfunction test_eval_closure()\n{\n    var tab;\n\n    tab = [];\n    for(let i = 0; i < 3; i++) {\n        eval(\"tab.push(function g1() { return i; })\");\n    }\n    for(let i = 0; i < 3; i++) {\n        assert(tab[i]() === i);\n    }\n\n    tab = [];\n    for(let i = 0; i < 3; i++) {\n        let f = function f() {\n            eval(\"tab.push(function g2() { return i; })\");\n        };\n        f();\n    }\n    for(let i = 0; i < 3; i++) {\n        assert(tab[i]() === i);\n    }\n}\n\nfunction test_eval_const()\n{\n    const a = 1;\n    var success = false;\n    var f = function () {\n        eval(\"a = 1\");\n    };\n    try {\n        f();\n    } catch(e) {\n        success = (e instanceof TypeError);\n    }\n    assert(success);\n}\n\ntest_closure1();\ntest_closure2();\ntest_closure3();\ntest_arrow_function();\ntest_with();\ntest_eval_closure();\ntest_eval_const();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/tests/test_language.js",
    "content": "function assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\nfunction assert_throws(expected_error, func)\n{\n    var err = false;\n    try {\n        func();\n    } catch(e) {\n        err = true;\n        if (!(e instanceof expected_error)) {\n            throw Error(\"unexpected exception type\");\n        }\n    }\n    if (!err) {\n        throw Error(\"expected exception\");\n    }\n}\n\n// load more elaborate version of assert if available\ntry { __loadScript(\"test_assert.js\"); } catch(e) {}\n\n/*----------------*/\n\nfunction test_op1()\n{\n    var r, a;\n    r = 1 + 2;\n    assert(r, 3, \"1 + 2 === 3\");\n\n    r = 1 - 2;\n    assert(r, -1, \"1 - 2 === -1\");\n\n    r = -1;\n    assert(r, -1, \"-1 === -1\");\n\n    r = +2;\n    assert(r, 2, \"+2 === 2\");\n\n    r = 2 * 3;\n    assert(r, 6, \"2 * 3 === 6\");\n\n    r = 4 / 2;\n    assert(r, 2, \"4 / 2 === 2\");\n\n    r = 4 % 3;\n    assert(r, 1, \"4 % 3 === 3\");\n\n    r = 4 << 2;\n    assert(r, 16, \"4 << 2 === 16\");\n\n    r = 1 << 0;\n    assert(r, 1, \"1 << 0 === 1\");\n\n    r = 1 << 31;\n    assert(r, -2147483648, \"1 << 31 === -2147483648\");\n    \n    r = 1 << 32;\n    assert(r, 1, \"1 << 32 === 1\");\n    \n    r = (1 << 31) < 0;\n    assert(r, true, \"(1 << 31) < 0 === true\");\n\n    r = -4 >> 1;\n    assert(r, -2, \"-4 >> 1 === -2\");\n\n    r = -4 >>> 1;\n    assert(r, 0x7ffffffe, \"-4 >>> 1 === 0x7ffffffe\");\n\n    r = 1 & 1;\n    assert(r, 1, \"1 & 1 === 1\");\n\n    r = 0 | 1;\n    assert(r, 1, \"0 | 1 === 1\");\n\n    r = 1 ^ 1;\n    assert(r, 0, \"1 ^ 1 === 0\");\n\n    r = ~1;\n    assert(r, -2, \"~1 === -2\");\n\n    r = !1;\n    assert(r, false, \"!1 === false\");\n\n    assert((1 < 2), true, \"(1 < 2) === true\");\n\n    assert((2 > 1), true, \"(2 > 1) === true\");\n\n    assert(('b' > 'a'), true, \"('b' > 'a') === true\");\n\n    assert(2 ** 8, 256, \"2 ** 8 === 256\");\n}\n\nfunction test_cvt()\n{\n    assert((NaN | 0) === 0);\n    assert((Infinity | 0) === 0);\n    assert(((-Infinity) | 0) === 0);\n    assert((\"12345\" | 0) === 12345);\n    assert((\"0x12345\" | 0) === 0x12345);\n    assert(((4294967296 * 3 - 4) | 0) === -4);\n    \n    assert((\"12345\" >>> 0) === 12345);\n    assert((\"0x12345\" >>> 0) === 0x12345);\n    assert((NaN >>> 0) === 0);\n    assert((Infinity >>> 0) === 0);\n    assert(((-Infinity) >>> 0) === 0);\n    assert(((4294967296 * 3 - 4) >>> 0) === (4294967296 - 4));\n}\n\nfunction test_eq()\n{\n    assert(null == undefined);\n    assert(undefined == null);\n    assert(true == 1);\n    assert(0 == false);\n    assert(\"\" == 0);\n    assert(\"123\" == 123);\n    assert(\"122\" != 123);\n    assert((new Number(1)) == 1);\n    assert(2 == (new Number(2)));\n    assert((new String(\"abc\")) == \"abc\");\n    assert({} != \"abc\");\n}\n\nfunction test_inc_dec()\n{\n    var a, r;\n    \n    a = 1;\n    r = a++;\n    assert(r === 1 && a === 2, true, \"++\");\n\n    a = 1;\n    r = ++a;\n    assert(r === 2 && a === 2, true, \"++\");\n\n    a = 1;\n    r = a--;\n    assert(r === 1 && a === 0, true, \"--\");\n\n    a = 1;\n    r = --a;\n    assert(r === 0 && a === 0, true, \"--\");\n\n    a = {x:true};\n    a.x++;\n    assert(a.x, 2, \"++\");\n\n    a = {x:true};\n    a.x--;\n    assert(a.x, 0, \"--\");\n\n    a = [true];\n    a[0]++;\n    assert(a[0], 2, \"++\");\n    \n    a = {x:true};\n    r = a.x++;\n    assert(r === 1 && a.x === 2, true, \"++\");\n    \n    a = {x:true};\n    r = a.x--;\n    assert(r === 1 && a.x === 0, true, \"--\");\n    \n    a = [true];\n    r = a[0]++;\n    assert(r === 1 && a[0] === 2, true, \"++\");\n    \n    a = [true];\n    r = a[0]--;\n    assert(r === 1 && a[0] === 0, true, \"--\");\n}\n\nfunction F(x)\n{\n    this.x = x;\n}\n\nfunction test_op2()\n{\n    var a, b;\n    a = new Object;\n    a.x = 1;\n    assert(a.x, 1, \"new\");\n    b = new F(2);\n    assert(b.x, 2, \"new\");\n\n    a = {x : 2};\n    assert((\"x\" in a), true, \"in\");\n    assert((\"y\" in a), false, \"in\");\n\n    a = {};\n    assert((a instanceof Object), true, \"instanceof\");\n    assert((a instanceof String), false, \"instanceof\");\n\n    assert((typeof 1), \"number\", \"typeof\");\n    assert((typeof Object), \"function\", \"typeof\");\n    assert((typeof null), \"object\", \"typeof\");\n    assert((typeof unknown_var), \"undefined\", \"typeof\");\n    \n    a = {x: 1, if: 2, async: 3};\n    assert(a.if === 2);\n    assert(a.async === 3);\n}\n\nfunction test_delete()\n{\n    var a, err;\n\n    a = {x: 1, y: 1};\n    assert((delete a.x), true, \"delete\");\n    assert((\"x\" in a), false, \"delete\");\n    \n    /* the following are not tested by test262 */\n    assert(delete \"abc\"[100], true);\n\n    err = false;\n    try {\n        delete null.a;\n    } catch(e) {\n        err = (e instanceof TypeError);\n    }\n    assert(err, true, \"delete\");\n\n    err = false;\n    try {\n        a = { f() { delete super.a; } };\n        a.f();\n    } catch(e) {\n        err = (e instanceof ReferenceError);\n    }\n    assert(err, true, \"delete\");\n}\n\nfunction test_prototype()\n{\n    var f = function f() { };\n    assert(f.prototype.constructor, f, \"prototype\");\n\n    var g = function g() { };\n    /* QuickJS bug */\n    Object.defineProperty(g, \"prototype\", { writable: false });\n    assert(g.prototype.constructor, g, \"prototype\");\n}\n\nfunction test_arguments()\n{\n    function f2() {\n        assert(arguments.length, 2, \"arguments\");\n        assert(arguments[0], 1, \"arguments\");\n        assert(arguments[1], 3, \"arguments\");\n    }\n    f2(1, 3);\n}\n\nfunction test_class()\n{\n    var o;\n    class C {\n        constructor() {\n            this.x = 10;\n        }\n        f() {\n            return 1;\n        }\n        static F() {\n            return -1;\n        }\n        get y() {\n            return 12;\n        }\n    };\n    class D extends C {\n        constructor() {\n            super();\n            this.z = 20;\n        }\n        g() {\n            return 2;\n        }\n        static G() {\n            return -2;\n        }\n        h() {\n            return super.f();\n        }\n        static H() {\n            return super[\"F\"]();\n        }\n    }\n\n    assert(C.F() === -1);\n    assert(Object.getOwnPropertyDescriptor(C.prototype, \"y\").get.name === \"get y\");\n\n    o = new C();\n    assert(o.f() === 1);\n    assert(o.x === 10);\n    \n    assert(D.F() === -1);\n    assert(D.G() === -2);\n    assert(D.H() === -1);\n\n    o = new D();\n    assert(o.f() === 1);\n    assert(o.g() === 2);\n    assert(o.x === 10);\n    assert(o.z === 20);\n    assert(o.h() === 1);\n\n    /* test class name scope */\n    var E1 = class E { static F() { return E; } };\n    assert(E1 === E1.F());\n};\n\nfunction test_template()\n{\n    var a, b;\n    b = 123;\n    a = `abc${b}d`;\n    assert(a, \"abc123d\");\n\n    a = String.raw `abc${b}d`;\n    assert(a, \"abc123d\");\n\n    a = \"aaa\";\n    b = \"bbb\";\n    assert(`aaa${a, b}ccc`, \"aaabbbccc\");\n}\n\nfunction test_template_skip()\n{\n    var a = \"Bar\";\n    var { b = `${a + `a${a}` }baz` } = {};\n    assert(b, \"BaraBarbaz\");\n}\n\nfunction test_object_literal()\n{\n    var x = 0, get = 1, set = 2; async = 3;\n    a = { get: 2, set: 3, async: 4 };\n    assert(JSON.stringify(a), '{\"get\":2,\"set\":3,\"async\":4}');\n\n    a = { x, get, set, async };\n    assert(JSON.stringify(a), '{\"x\":0,\"get\":1,\"set\":2,\"async\":3}');\n}\n\nfunction test_regexp_skip()\n{\n    var a, b;\n    [a, b = /abc\\(/] = [1];\n    assert(a === 1);\n    \n    [a, b =/abc\\(/] = [2];\n    assert(a === 2);\n}\n\nfunction test_labels()\n{\n    do x: { break x; } while(0);\n    if (1)\n        x: { break x; }\n    else\n        x: { break x; }\n    with ({}) x: { break x; };\n    while (0) x: { break x; };\n}\n\nfunction test_destructuring()\n{\n    function * g () { return 0; };\n    var [x] = g();\n    assert(x, void 0);\n}\n\nfunction test_spread()\n{\n    var x;\n    x = [1, 2, ...[3, 4]];\n    assert(x.toString(), \"1,2,3,4\");\n\n    x = [ ...[ , ] ];\n    assert(Object.getOwnPropertyNames(x).toString(), \"0,length\");\n}\n\nfunction test_function_length()\n{\n    assert( ((a, b = 1, c) => {}).length, 1);\n    assert( (([a,b]) => {}).length, 1);\n    assert( (({a,b}) => {}).length, 1);\n    assert( ((c, [a,b] = 1, d) => {}).length, 1);\n}\n\nfunction test_argument_scope()\n{\n    var f;\n    var c = \"global\";\n    \n    f = function(a = eval(\"var arguments\")) {};\n    assert_throws(SyntaxError, f);\n\n    f = function(a = eval(\"1\"), b = arguments[0]) { return b; };\n    assert(f(12), 12);\n\n    f = function(a, b = arguments[0]) { return b; };\n    assert(f(12), 12);\n\n    f = function(a, b = () => arguments) { return b; };\n    assert(f(12)()[0], 12);\n\n    f = function(a = eval(\"1\"), b = () => arguments) { return b; };\n    assert(f(12)()[0], 12);\n\n    (function() {\n        \"use strict\";\n        f = function(a = this) { return a; };\n        assert(f.call(123), 123);\n\n        f = function f(a = f) { return a; };\n        assert(f(), f);\n\n        f = function f(a = eval(\"f\")) { return a; };\n        assert(f(), f);\n    })();\n\n    f = (a = eval(\"var c = 1\"), probe = () => c) => {\n        var c = 2;\n        assert(c, 2);\n        assert(probe(), 1);\n    }\n    f();\n\n    f = (a = eval(\"var arguments = 1\"), probe = () => arguments) => {\n        var arguments = 2;\n        assert(arguments, 2);\n        assert(probe(), 1);\n    }\n    f();\n\n    f = function f(a = eval(\"var c = 1\"), b = c, probe = () => c) {\n        assert(b, 1);\n        assert(c, 1);\n        assert(probe(), 1)\n    }\n    f();\n\n    assert(c, \"global\");\n    f = function f(a, b = c, probe = () => c) {\n        eval(\"var c = 1\");\n        assert(c, 1);\n        assert(b, \"global\");\n        assert(probe(), \"global\")\n    }\n    f();\n    assert(c, \"global\");\n\n    f = function f(a = eval(\"var c = 1\"), probe = (d = eval(\"c\")) => d) {\n        assert(probe(), 1)\n    }\n    f();\n}\n\nfunction test_function_expr_name()\n{\n    var f;\n\n    /* non strict mode test : assignment to the function name silently\n       fails */\n    \n    f = function myfunc() {\n        myfunc = 1;\n        return myfunc;\n    };\n    assert(f(), f);\n\n    f = function myfunc() {\n        myfunc = 1;\n        (() => {\n            myfunc = 1;\n        })();\n        return myfunc;\n    };\n    assert(f(), f);\n\n    f = function myfunc() {\n        eval(\"myfunc = 1\");\n        return myfunc;\n    };\n    assert(f(), f);\n    \n    /* strict mode test : assignment to the function name raises a\n       TypeError exception */\n\n    f = function myfunc() {\n        \"use strict\";\n        myfunc = 1;\n    };\n    assert_throws(TypeError, f);\n\n    f = function myfunc() {\n        \"use strict\";\n        (() => {\n            myfunc = 1;\n        })();\n    };\n    assert_throws(TypeError, f);\n\n    f = function myfunc() {\n        \"use strict\";\n        eval(\"myfunc = 1\");\n    };\n    assert_throws(TypeError, f);\n}\n\ntest_op1();\ntest_cvt();\ntest_eq();\ntest_inc_dec();\ntest_op2();\ntest_delete();\ntest_prototype();\ntest_arguments();\ntest_class();\ntest_template();\ntest_template_skip();\ntest_object_literal();\ntest_regexp_skip();\ntest_labels();\ntest_destructuring();\ntest_spread();\ntest_function_length();\ntest_argument_scope();\ntest_function_expr_name();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/tests/test_loop.js",
    "content": "function assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\n// load more elaborate version of assert if available\ntry { __loadScript(\"test_assert.js\"); } catch(e) {}\n\n/*----------------*/\n\nfunction test_while()\n{\n    var i, c;\n    i = 0;\n    c = 0;\n    while (i < 3) {\n        c++;\n        i++;\n    }\n    assert(c === 3);\n}\n\nfunction test_while_break()\n{\n    var i, c;\n    i = 0;\n    c = 0;\n    while (i < 3) {\n        c++;\n        if (i == 1)\n            break;\n        i++;\n    }\n    assert(c === 2 && i === 1);\n}\n\nfunction test_do_while()\n{\n    var i, c;\n    i = 0;\n    c = 0;\n    do {\n        c++;\n        i++;\n    } while (i < 3);\n    assert(c === 3 && i === 3);\n}\n\nfunction test_for()\n{\n    var i, c;\n    c = 0;\n    for(i = 0; i < 3; i++) {\n        c++;\n    }\n    assert(c === 3 && i === 3);\n\n    c = 0;\n    for(var j = 0; j < 3; j++) {\n        c++;\n    }\n    assert(c === 3 && j === 3);\n}\n\nfunction test_for_in()\n{\n    var i, tab, a, b;\n\n    tab = [];\n    for(i in {x:1, y: 2}) {\n        tab.push(i);\n    }\n    assert(tab.toString(), \"x,y\", \"for_in\");\n\n    /* prototype chain test */\n    a = {x:2, y: 2, \"1\": 3};\n    b = {\"4\" : 3 };\n    Object.setPrototypeOf(a, b);\n    tab = [];\n    for(i in a) {\n        tab.push(i);\n    }\n    assert(tab.toString(), \"1,x,y,4\", \"for_in\");\n\n    /* non enumerable properties hide enumerables ones in the\n       prototype chain */\n    a = {y: 2, \"1\": 3};\n    Object.defineProperty(a, \"x\", { value: 1 });\n    b = {\"x\" : 3 };\n    Object.setPrototypeOf(a, b);\n    tab = [];\n    for(i in a) {\n        tab.push(i);\n    }\n    assert(tab.toString(), \"1,y\", \"for_in\");\n\n    /* array optimization */\n    a = [];\n    for(i = 0; i < 10; i++)\n        a.push(i);\n    tab = [];\n    for(i in a) {\n        tab.push(i);\n    }\n    assert(tab.toString(), \"0,1,2,3,4,5,6,7,8,9\", \"for_in\");\n\n    /* iterate with a field */\n    a={x:0};\n    tab = [];\n    for(a.x in {x:1, y: 2}) {\n        tab.push(a.x);\n    }\n    assert(tab.toString(), \"x,y\", \"for_in\");\n\n    /* iterate with a variable field */\n    a=[0];\n    tab = [];\n    for(a[0] in {x:1, y: 2}) {\n        tab.push(a[0]);\n    }\n    assert(tab.toString(), \"x,y\", \"for_in\");\n\n    /* variable definition in the for in */\n    tab = [];\n    for(var j in {x:1, y: 2}) {\n        tab.push(j);\n    }\n    assert(tab.toString(), \"x,y\", \"for_in\");\n\n    /* variable assigment in the for in */\n    tab = [];\n    for(var k = 2 in {x:1, y: 2}) {\n        tab.push(k);\n    }\n    assert(tab.toString(), \"x,y\", \"for_in\");\n}\n\nfunction test_for_in2()\n{\n    var i;\n    tab = [];\n    for(i in {x:1, y: 2, z:3}) {\n        if (i === \"y\")\n            continue;\n        tab.push(i);\n    }\n    assert(tab.toString() == \"x,z\");\n\n    tab = [];\n    for(i in {x:1, y: 2, z:3}) {\n        if (i === \"z\")\n            break;\n        tab.push(i);\n    }\n    assert(tab.toString() == \"x,y\");\n}\n\nfunction test_for_break()\n{\n    var i, c;\n    c = 0;\n    L1: for(i = 0; i < 3; i++) {\n        c++;\n        if (i == 0)\n            continue;\n        while (1) {\n            break L1;\n        }\n    }\n    assert(c === 2 && i === 1);\n}\n\nfunction test_switch1()\n{\n    var i, a, s;\n    s = \"\";\n    for(i = 0; i < 3; i++) {\n        a = \"?\";\n        switch(i) {\n        case 0:\n            a = \"a\";\n            break;\n        case 1:\n            a = \"b\";\n            break;\n        default:\n            a = \"c\";\n            break;\n        }\n        s += a;\n    }\n    assert(s === \"abc\" && i === 3);\n}\n\nfunction test_switch2()\n{\n    var i, a, s;\n    s = \"\";\n    for(i = 0; i < 4; i++) {\n        a = \"?\";\n        switch(i) {\n        case 0:\n            a = \"a\";\n            break;\n        case 1:\n            a = \"b\";\n            break;\n        case 2:\n            continue;\n        default:\n            a = \"\" + i;\n            break;\n        }\n        s += a;\n    }\n    assert(s === \"ab3\" && i === 4);\n}\n\nfunction test_try_catch1()\n{\n    try {\n        throw \"hello\";\n    } catch (e) {\n        assert(e, \"hello\", \"catch\");\n        return;\n    }\n    assert(false, \"catch\");\n}\n\nfunction test_try_catch2()\n{\n    var a;\n    try {\n        a = 1;\n    } catch (e) {\n        a = 2;\n    }\n    assert(a, 1, \"catch\");\n}\n\nfunction test_try_catch3()\n{\n    var s;\n    s = \"\";\n    try {\n        s += \"t\";\n    } catch (e) {\n        s += \"c\";\n    } finally {\n        s += \"f\";\n    }\n    assert(s, \"tf\", \"catch\");\n}\n\nfunction test_try_catch4()\n{\n    var s;\n    s = \"\";\n    try {\n        s += \"t\";\n        throw \"c\";\n    } catch (e) {\n        s += e;\n    } finally {\n        s += \"f\";\n    }\n    assert(s, \"tcf\", \"catch\");\n}\n\nfunction test_try_catch5()\n{\n    var s;\n    s = \"\";\n    for(;;) {\n        try {\n            s += \"t\";\n            break;\n            s += \"b\";\n        } finally {\n            s += \"f\";\n        }\n    }\n    assert(s, \"tf\", \"catch\");\n}\n\nfunction test_try_catch6()\n{\n    function f() {\n        try {\n            s += 't';\n            return 1;\n        } finally {\n            s += \"f\";\n        }\n    }\n    var s = \"\";\n    assert(f() === 1);\n    assert(s, \"tf\", \"catch6\");\n}\n\nfunction test_try_catch7()\n{\n    var s;\n    s = \"\";\n\n    try {\n        try {\n            s += \"t\";\n            throw \"a\";\n        } finally {\n            s += \"f\";\n        }\n    } catch(e) {\n        s += e;\n    } finally {\n        s += \"g\";\n    }\n    assert(s, \"tfag\", \"catch\");\n}\n\nfunction test_try_catch8()\n{\n    var i, s;\n    \n    s = \"\";\n    for(var i in {x:1, y:2}) {\n        try {\n            s += i;\n            throw \"a\";\n        } catch (e) {\n            s += e;\n        } finally {\n            s += \"f\";\n        }\n    }\n    assert(s === \"xafyaf\");\n}\n\ntest_while();\ntest_while_break();\ntest_do_while();\ntest_for();\ntest_for_break();\ntest_switch1();\ntest_switch2();\ntest_for_in();\ntest_for_in2();\n\ntest_try_catch1();\ntest_try_catch2();\ntest_try_catch3();\ntest_try_catch4();\ntest_try_catch5();\ntest_try_catch6();\ntest_try_catch7();\ntest_try_catch8();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/tests/test_op_overloading.js",
    "content": "\"use strict\";\n\nfunction assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\n/* operators overloading with Operators.create() */\nfunction test_operators_create() {\n    class Vec2\n    {\n        constructor(x, y) {\n            this.x = x;\n            this.y = y;\n        }\n        static mul_scalar(p1, a) {\n            var r = new Vec2();\n            r.x = p1.x * a;\n            r.y = p1.y * a;\n            return r;\n        }\n        toString() {\n            return \"Vec2(\" + this.x + \",\" + this.y + \")\";\n        }\n    }\n    \n    Vec2.prototype[Symbol.operatorSet] = Operators.create(\n    {\n        \"+\"(p1, p2) {\n            var r = new Vec2();\n            r.x = p1.x + p2.x;\n            r.y = p1.y + p2.y;\n            return r;\n        },\n        \"-\"(p1, p2) {\n            var r = new Vec2();\n            r.x = p1.x - p2.x;\n            r.y = p1.y - p2.y;\n            return r;\n        },\n        \"==\"(a, b) {\n            return a.x == b.x && a.y == b.y;\n        },\n        \"<\"(a, b) {\n            var r;\n            /* lexicographic order */\n            if (a.x == b.x)\n                r = (a.y < b.y);\n            else\n                r = (a.x < b.x);\n            return r;\n        },\n        \"++\"(a) {\n            var r = new Vec2();\n            r.x = a.x + 1;\n            r.y = a.y + 1;\n            return r;\n        }\n    },\n    {\n        left: Number,\n        \"*\"(a, b) {\n            return Vec2.mul_scalar(b, a);\n        }\n    },\n    {\n        right: Number,\n        \"*\"(a, b) {\n            return Vec2.mul_scalar(a, b);\n        }\n    });\n\n    var a = new Vec2(1, 2);\n    var b = new Vec2(3, 4);\n    var r;\n\n    r = a * 2 + 3 * b;\n    assert(r.x === 11 && r.y === 16);\n    assert(a == a, true);\n    assert(a == b, false);\n    assert(a != a, false);\n    assert(a < b, true);\n    assert(a <= b, true);\n    assert(b < a, false);\n    assert(b <= a, false);\n    assert(a <= a, true);\n    assert(a >= a, true);\n    a++;\n    assert(a.x === 2 && a.y === 3);\n    r = ++a;\n    assert(a.x === 3 && a.y === 4);\n    assert(r === a);\n}\n\n/* operators overloading thru inheritance */\nfunction test_operators()\n{\n    var Vec2;\n\n    function mul_scalar(p1, a) {\n        var r = new Vec2();\n        r.x = p1.x * a;\n        r.y = p1.y * a;\n        return r;\n    }\n\n    var vec2_ops = Operators({\n        \"+\"(p1, p2) {\n            var r = new Vec2();\n            r.x = p1.x + p2.x;\n            r.y = p1.y + p2.y;\n            return r;\n        },\n        \"-\"(p1, p2) {\n            var r = new Vec2();\n            r.x = p1.x - p2.x;\n            r.y = p1.y - p2.y;\n            return r;\n        },\n        \"==\"(a, b) {\n            return a.x == b.x && a.y == b.y;\n        },\n        \"<\"(a, b) {\n            var r;\n            /* lexicographic order */\n            if (a.x == b.x)\n                r = (a.y < b.y);\n            else\n                r = (a.x < b.x);\n            return r;\n        },\n        \"++\"(a) {\n            var r = new Vec2();\n            r.x = a.x + 1;\n            r.y = a.y + 1;\n            return r;\n        }\n    },\n    {\n        left: Number,\n        \"*\"(a, b) {\n            return mul_scalar(b, a);\n        }\n    },\n    {\n        right: Number,\n        \"*\"(a, b) {\n            return mul_scalar(a, b);\n        }\n    });\n\n    Vec2 = class Vec2 extends vec2_ops\n    {\n        constructor(x, y) {\n            super();\n            this.x = x;\n            this.y = y;\n        }\n        toString() {\n            return \"Vec2(\" + this.x + \",\" + this.y + \")\";\n        }\n    }\n    \n    var a = new Vec2(1, 2);\n    var b = new Vec2(3, 4);\n    var r;\n\n    r = a * 2 + 3 * b;\n    assert(r.x === 11 && r.y === 16);\n    assert(a == a, true);\n    assert(a == b, false);\n    assert(a != a, false);\n    assert(a < b, true);\n    assert(a <= b, true);\n    assert(b < a, false);\n    assert(b <= a, false);\n    assert(a <= a, true);\n    assert(a >= a, true);\n    a++;\n    assert(a.x === 2 && a.y === 3);\n    r = ++a;\n    assert(a.x === 3 && a.y === 4);\n    assert(r === a);\n}\n\nfunction test_default_op()\n{\n    assert(Object(1) + 2, 3);\n    assert(Object(1) + true, 2);\n    assert(-Object(1), -1);\n}\n\ntest_operators_create();\ntest_operators();\ntest_default_op();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/tests/test_qjscalc.js",
    "content": "\"use math\";\n\"use strict\";\n\nfunction assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\nfunction assertThrows(err, func)\n{\n    var ex;\n    ex = false;\n    try {\n        func();\n    } catch(e) {\n        ex = true;\n        assert(e instanceof err);\n    }\n    assert(ex, true, \"exception expected\");\n}\n\n// load more elaborate version of assert if available\ntry { __loadScript(\"test_assert.js\"); } catch(e) {}\n\n/*----------------*/\n\nfunction pow(a, n)\n{\n    var r, i;\n    r = 1;\n    for(i = 0; i < n; i++)\n        r *= a;\n    return r;\n}\n\nfunction test_integer()\n{\n    var a, r;\n    a = pow(3, 100);\n    assert((a - 1) != a);\n    assert(a == 515377520732011331036461129765621272702107522001);\n    assert(a == 0x5a4653ca673768565b41f775d6947d55cf3813d1);\n    assert(Integer.isInteger(1) === true);\n    assert(Integer.isInteger(1.0) === false);\n\n    assert(Integer.floorLog2(0) === -1);\n    assert(Integer.floorLog2(7) === 2);\n\n    r = 1 << 31;\n    assert(r, 2147483648, \"1 << 31 === 2147483648\");\n    \n    r = 1 << 32;\n    assert(r, 4294967296, \"1 << 32 === 4294967296\");\n    \n    r = (1 << 31) < 0;\n    assert(r, false, \"(1 << 31) < 0 === false\");\n\n    assert(typeof 1 === \"number\");\n    assert(typeof 9007199254740991 === \"number\");\n    assert(typeof 9007199254740992 === \"bigint\");\n}\n\nfunction test_float()\n{\n    assert(typeof 1.0 === \"bigfloat\");\n    assert(1 == 1.0);\n    assert(1 !== 1.0);\n}\n\n/* jscalc tests */\n\nfunction test_modulo()\n{\n    var i, p, a, b;\n\n    /* Euclidian modulo operator */\n    assert((-3) % 2 == 1);\n    assert(3 % (-2) == 1);\n\n    p = 101;\n    for(i = 1; i < p; i++) {\n        a = Integer.invmod(i, p);\n        assert(a >= 0 && a < p);\n        assert((i * a) % p == 1);\n    }\n\n    assert(Integer.isPrime(2^107-1));\n    assert(!Integer.isPrime((2^107-1) * (2^89-1)));\n    a = Integer.factor((2^89-1)*2^3*11*13^2*1009);\n    assert(a == [ 2,2,2,11,13,13,1009,618970019642690137449562111 ]);\n}\n\nfunction test_fraction()\n{\n    assert((1/3 + 1).toString(), \"4/3\")\n    assert((2/3)^30, 1073741824/205891132094649);\n    assert(1/3 < 2/3);\n    assert(1/3 < 1);\n    assert(1/3 == 1.0/3);\n    assert(1.0/3 < 2/3);\n}\n\nfunction test_mod()\n{\n    var a, b, p;\n    \n    a = Mod(3, 101);\n    b = Mod(-1, 101);\n    assert((a + b) == Mod(2, 101));\n    assert(a ^ 100 == Mod(1, 101));\n\n    p = 2 ^ 607 - 1; /* mersenne prime */\n    a = Mod(3, p) ^ (p - 1);\n    assert(a == Mod(1, p));\n}\n\nfunction test_polynomial()\n{\n    var a, b, q, r, t, i;\n    a = (1 + X) ^ 4;\n    assert(a == X^4+4*X^3+6*X^2+4*X+1);\n    \n    r = (1 + X);\n    q = (1+X+X^2);\n    b = (1 - X^2);\n    a = q * b + r;\n    t = Polynomial.divrem(a, b);\n    assert(t[0] == q);\n    assert(t[1] == r);\n\n    a = 1 + 2*X + 3*X^2;\n    assert(a.apply(0.1) == 1.23);\n\n    a = 1-2*X^2+2*X^3;\n    assert(deriv(a) == (6*X^2-4*X));\n    assert(deriv(integ(a)) == a);\n\n    a = (X-1)*(X-2)*(X-3)*(X-4)*(X-0.1);\n    r = polroots(a);\n    for(i = 0; i < r.length; i++) {\n        b = abs(a.apply(r[i]));\n        assert(b <= 1e-13);\n    }\n}\n\nfunction test_poly_mod()\n{\n    var a, p;\n\n    /* modulo using polynomials */\n    p = X^2 + X + 1;\n    a = PolyMod(3+X, p) ^ 10;\n    assert(a == PolyMod(-3725*X-18357, p));\n\n    a = PolyMod(1/X, 1+X^2);\n    assert(a == PolyMod(-X, X^2+1));\n}\n\nfunction test_rfunc()\n{\n    var a;\n    a = (X+1)/((X+1)*(X-1));\n    assert(a == 1/(X-1));\n    a = (X + 2) / (X - 2);\n    assert(a.apply(1/3) == -7/5);\n\n    assert(deriv((X^2-X+1)/(X-1)) == (X^2-2*X)/(X^2-2*X+1));\n}\n\nfunction test_series()\n{\n    var a, b;\n    a = 1+X+O(X^5);\n    b = a.inverse();\n    assert(b == 1-X+X^2-X^3+X^4+O(X^5));\n    assert(deriv(b) == -1+2*X-3*X^2+4*X^3+O(X^4));\n    assert(deriv(integ(b)) == b);\n\n    a = Series(1/(1-X), 5);\n    assert(a == 1+X+X^2+X^3+X^4+O(X^5));\n    b = a.apply(0.1);\n    assert(b == 1.1111);\n\n    assert(exp(3*X^2+O(X^10)) == 1+3*X^2+9/2*X^4+9/2*X^6+27/8*X^8+O(X^10));\n    assert(sin(X+O(X^6)) == X-1/6*X^3+1/120*X^5+O(X^6));\n    assert(cos(X+O(X^6)) == 1-1/2*X^2+1/24*X^4+O(X^6));\n    assert(tan(X+O(X^8)) == X+1/3*X^3+2/15*X^5+17/315*X^7+O(X^8));\n        assert((1+X+O(X^6))^(2+X) == 1+2*X+2*X^2+3/2*X^3+5/6*X^4+5/12*X^5+O(X^6));\n}\n\nfunction test_matrix()\n{\n    var a, b, r;\n    a = [[1, 2],[3, 4]];\n    b = [3, 4];\n    r = a * b;\n    assert(r == [11, 25]);\n    r = (a^-1) * 2;\n    assert(r == [[-4, 2],[3, -1]]);\n\n    assert(norm2([1,2,3]) == 14);\n\n    assert(diag([1,2,3]) == [ [ 1, 0, 0 ], [ 0, 2, 0 ], [ 0, 0, 3 ] ]);\n    assert(trans(a) == [ [ 1, 3 ], [ 2, 4 ] ]);\n    assert(trans([1,2,3]) == [[1,2,3]]);\n    assert(trace(a) == 5);\n\n    assert(charpoly(Matrix.hilbert(4)) == X^4-176/105*X^3+3341/12600*X^2-41/23625*X+1/6048000);\n    assert(det(Matrix.hilbert(4)) == 1/6048000);\n\n    a = [[1,2,1],[-2,-3,1],[3,5,0]];\n    assert(rank(a) == 2);\n    assert(ker(a) == [ [ 5 ], [ -3 ], [ 1 ] ]);\n\n    assert(dp([1, 2, 3], [3, -4, -7]) === -26);\n    assert(cp([1, 2, 3], [3, -4, -7]) == [ -2, 16, -10 ]);\n}\n\nfunction assert_eq(a, ref)\n{\n    assert(abs(a / ref - 1.0) <= 1e-15);\n}\n\nfunction test_trig()\n{\n    assert_eq(sin(1/2), 0.479425538604203);\n    assert_eq(sin(2+3*I), 9.154499146911428-4.168906959966565*I);\n    assert_eq(cos(2+3*I), -4.189625690968807-9.109227893755337*I);\n    assert_eq((2+0.5*I)^(1.1-0.5*I), 2.494363021357619-0.23076804554558092*I);\n    assert_eq(sqrt(2*I), 1 + I);\n}\n\ntest_integer();\ntest_float();\n\ntest_modulo();\ntest_fraction();\ntest_mod();\ntest_polynomial();\ntest_poly_mod();\ntest_rfunc();\ntest_series();\ntest_matrix();\ntest_trig();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/tests/test_std.js",
    "content": "import * as std from \"std\";\nimport * as os from \"os\";\n\nfunction assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\n// load more elaborate version of assert if available\ntry { std.loadScript(\"test_assert.js\"); } catch(e) {}\n\n/*----------------*/\n\nfunction test_printf()\n{\n    assert(std.sprintf(\"a=%d s=%s\", 123, \"abc\"), \"a=123 s=abc\");\n    assert(std.sprintf(\"%010d\", 123), \"0000000123\");\n    assert(std.sprintf(\"%x\", -2), \"fffffffe\");\n    assert(std.sprintf(\"%lx\", -2), \"fffffffffffffffe\");\n    assert(std.sprintf(\"%10.1f\", 2.1), \"       2.1\");\n    assert(std.sprintf(\"%*.*f\", 10, 2, -2.13), \"     -2.13\");\n    assert(std.sprintf(\"%#lx\", 0x7fffffffffffffffn), \"0x7fffffffffffffff\");\n}\n\nfunction test_file1()\n{\n    var f, len, str, size, buf, ret, i, str1;\n\n    f = std.tmpfile();\n    str = \"hello world\\n\";\n    f.puts(str);\n\n    f.seek(0, std.SEEK_SET);\n    str1 = f.readAsString();\n    assert(str1 === str);\n    \n    f.seek(0, std.SEEK_END);\n    size = f.tell();\n    assert(size === str.length);\n\n    f.seek(0, std.SEEK_SET);\n\n    buf = new Uint8Array(size);\n    ret = f.read(buf.buffer, 0, size);\n    assert(ret === size);\n    for(i = 0; i < size; i++)\n        assert(buf[i] === str.charCodeAt(i));\n\n    f.close();\n}\n\nfunction test_file2()\n{\n    var f, str, i, size;\n    f = std.tmpfile();\n    str = \"hello world\\n\";\n    size = str.length;\n    for(i = 0; i < size; i++)\n        f.putByte(str.charCodeAt(i));\n    f.seek(0, std.SEEK_SET);\n    for(i = 0; i < size; i++) {\n        assert(str.charCodeAt(i) === f.getByte());\n    }\n    assert(f.getByte() === -1);\n    f.close();\n}\n\nfunction test_getline()\n{\n    var f, line, line_count, lines, i;\n    \n    lines = [\"hello world\", \"line 1\", \"line 2\" ];\n    f = std.tmpfile();\n    for(i = 0; i < lines.length; i++) {\n        f.puts(lines[i], \"\\n\");\n    }\n\n    f.seek(0, std.SEEK_SET);\n    assert(!f.eof());\n    line_count = 0;\n    for(;;) {\n        line = f.getline();\n        if (line === null)\n            break;\n        assert(line == lines[line_count]);\n        line_count++;\n    }\n    assert(f.eof());\n    assert(line_count === lines.length);\n\n    f.close();\n}\n \nfunction test_popen()\n{\n    var str, f, fname = \"tmp_file.txt\";\n    var content = \"hello world\";\n\n    f = std.open(fname, \"w\");\n    f.puts(content);\n    f.close();\n\n    /* test loadFile */\n    assert(std.loadFile(fname), content);\n    \n    /* execute the 'cat' shell command */\n    f = std.popen(\"cat \" + fname, \"r\");\n    str = f.readAsString();\n    f.close();\n\n    assert(str, content);\n\n    os.remove(fname);\n}\n\nfunction test_ext_json()\n{\n    var expected, input, obj;\n    expected = '{\"x\":false,\"y\":true,\"z2\":null,\"a\":[1,8,160],\"s\":\"str\"}';\n    input = `{ \"x\":false, /*comments are allowed */\n               \"y\":true,  // also a comment\n               z2:null, // unquoted property names\n               \"a\":[+1,0o10,0xa0,], // plus prefix, octal, hexadecimal\n               \"s\":\"str\",} // trailing comma in objects and arrays\n            `;\n    obj = std.parseExtJSON(input);\n    assert(JSON.stringify(obj), expected);\n}\n\nfunction test_os()\n{\n    var fd, fpath, fname, fdir, buf, buf2, i, files, err, fdate, st, link_path;\n\n    assert(os.isatty(0));\n\n    fdir = \"test_tmp_dir\";\n    fname = \"tmp_file.txt\";\n    fpath = fdir + \"/\" + fname;\n    link_path = fdir + \"/test_link\";\n    \n    os.remove(link_path);\n    os.remove(fpath);\n    os.remove(fdir);\n\n    err = os.mkdir(fdir, 0o755);\n    assert(err === 0);\n    \n    fd = os.open(fpath, os.O_RDWR | os.O_CREAT | os.O_TRUNC);\n    assert(fd >= 0);\n    \n    buf = new Uint8Array(10);\n    for(i = 0; i < buf.length; i++)\n        buf[i] = i;\n    assert(os.write(fd, buf.buffer, 0, buf.length) === buf.length);\n\n    assert(os.seek(fd, 0, std.SEEK_SET) === 0);\n    buf2 = new Uint8Array(buf.length);\n    assert(os.read(fd, buf2.buffer, 0, buf2.length) === buf2.length);\n    \n    for(i = 0; i < buf.length; i++)\n        assert(buf[i] == buf2[i]);\n    \n    if (typeof BigInt !== \"undefined\") {\n        assert(os.seek(fd, BigInt(6), std.SEEK_SET), BigInt(6));\n        assert(os.read(fd, buf2.buffer, 0, 1) === 1);\n        assert(buf[6] == buf2[0]);\n    }\n    \n    assert(os.close(fd) === 0);\n\n    [files, err] = os.readdir(fdir);\n    assert(err, 0);\n    assert(files.indexOf(fname) >= 0);\n\n    fdate = 10000;\n\n    err = os.utimes(fpath, fdate, fdate);\n    assert(err, 0);\n    \n    [st, err] = os.stat(fpath);\n    assert(err, 0);\n    assert(st.mode & os.S_IFMT, os.S_IFREG);\n    assert(st.mtime, fdate);\n\n    err = os.symlink(fname, link_path);\n    assert(err === 0);\n    \n    [st, err] = os.lstat(link_path);\n    assert(err, 0);\n    assert(st.mode & os.S_IFMT, os.S_IFLNK);\n\n    [buf, err] = os.readlink(link_path);\n    assert(err, 0);\n    assert(buf, fname);\n    \n    assert(os.remove(link_path) === 0);\n\n    [buf, err] = os.getcwd();\n    assert(err, 0);\n\n    [buf2, err] = os.realpath(\".\");\n    assert(err, 0);\n\n    assert(buf, buf2);\n    \n    assert(os.remove(fpath) === 0);\n\n    fd = os.open(fpath, os.O_RDONLY);\n    assert(fd < 0);\n\n    assert(os.remove(fdir) === 0);\n}\n\nfunction test_os_exec()\n{\n    var ret, fds, pid, f, status;\n\n    ret = os.exec([\"true\"]);\n    assert(ret, 0);\n\n    ret = os.exec([\"/bin/sh\", \"-c\", \"exit 1\"], { usePath: false });\n    assert(ret, 1);\n    \n    fds = os.pipe();\n    pid = os.exec([\"sh\", \"-c\", \"echo $FOO\"], {\n        stdout: fds[1],\n        block: false,\n        env: { FOO: \"hello\" },\n    } );\n    assert(pid >= 0);\n    os.close(fds[1]); /* close the write end (as it is only in the child)  */\n    f = std.fdopen(fds[0], \"r\");\n    assert(f.getline(), \"hello\");\n    assert(f.getline(), null);\n    f.close();\n    [ret, status] = os.waitpid(pid, 0);\n    assert(ret, pid);\n    assert(status & 0x7f, 0); /* exited */\n    assert(status >> 8, 0); /* exit code */\n\n    pid = os.exec([\"cat\"], { block: false } );\n    assert(pid >= 0);\n    os.kill(pid, os.SIGQUIT);\n    [ret, status] = os.waitpid(pid, 0);\n    assert(ret, pid);\n    assert(status & 0x7f, os.SIGQUIT);\n}\n\nfunction test_timer()\n{\n    var th, i;\n\n    /* just test that a timer can be inserted and removed */\n    th = [];\n    for(i = 0; i < 3; i++)\n        th[i] = os.setTimeout(function () { }, 1000);\n    for(i = 0; i < 3; i++)\n        os.clearTimeout(th[i]);\n}\n\ntest_printf();\ntest_file1();\ntest_file2();\ntest_getline();\ntest_popen();\ntest_os();\ntest_os_exec();\ntest_timer();\ntest_ext_json();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/tests/test_worker.js",
    "content": "/* os.Worker API test */\nimport * as std from \"std\";\nimport * as os from \"os\";\n\nfunction assert(actual, expected, message) {\n    if (arguments.length == 1)\n        expected = true;\n\n    if (actual === expected)\n        return;\n\n    if (actual !== null && expected !== null\n    &&  typeof actual == 'object' && typeof expected == 'object'\n    &&  actual.toString() === expected.toString())\n        return;\n\n    throw Error(\"assertion failed: got |\" + actual + \"|\" +\n                \", expected |\" + expected + \"|\" +\n                (message ? \" (\" + message + \")\" : \"\"));\n}\n\nvar worker;\n\nfunction test_worker()\n{\n    var counter;\n\n    worker = new os.Worker(\"./test_worker_module.js\");\n\n    counter = 0;\n    worker.onmessage = function (e) {\n        var ev = e.data;\n//        print(\"recv\", JSON.stringify(ev));\n        switch(ev.type) {\n        case \"num\":\n            assert(ev.num, counter);\n            counter++;\n            if (counter == 10) {\n                /* test SharedArrayBuffer modification */\n                let sab = new SharedArrayBuffer(10);\n                let buf = new Uint8Array(sab);\n                worker.postMessage({ type: \"sab\", buf: buf });\n            }\n            break;\n        case \"sab_done\":\n            {\n                let buf = ev.buf;\n                /* check that the SharedArrayBuffer was modified */\n                assert(buf[2], 10);\n                worker.postMessage({ type: \"abort\" });\n            }\n            break;\n        case \"done\":\n            /* terminate */\n            worker.onmessage = null;\n            break;\n        }\n    };\n}\n\n\ntest_worker();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/tests/test_worker_module.js",
    "content": "/* Worker code for test_worker.js */\nimport * as std from \"std\";\nimport * as os from \"os\";\n\nvar parent = os.Worker.parent;\n\nfunction handle_msg(e) {\n    var ev = e.data;\n    //          print(\"child_recv\", JSON.stringify(ev));\n    switch(ev.type) {\n    case \"abort\":\n        parent.postMessage({ type: \"done\" });\n        break;\n    case \"sab\":\n        /* modify the SharedArrayBuffer */\n        ev.buf[2] = 10;\n        parent.postMessage({ type: \"sab_done\", buf: ev.buf });\n        break;\n    }\n}\n\nfunction worker_main() {\n    var i;\n    \n    parent.onmessage = handle_msg;\n    for(i = 0; i < 10; i++) {\n        parent.postMessage({ type: \"num\", num: i }); \n    }\n}\n\nworker_main();\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/unicode_download.sh",
    "content": "#!/bin/sh\nset -e\n\nurl=\"ftp://ftp.unicode.org/Public/13.0.0/ucd\"\nemoji_url=\"${url}/emoji/emoji-data.txt\"\n\nfiles=\"CaseFolding.txt DerivedNormalizationProps.txt PropList.txt \\\nSpecialCasing.txt CompositionExclusions.txt ScriptExtensions.txt \\\nUnicodeData.txt DerivedCoreProperties.txt NormalizationTest.txt Scripts.txt \\\nPropertyValueAliases.txt\"\n\nmkdir -p unicode\n\n#for f in $files; do\n#    g=\"${url}/${f}\"\n#    wget $g -O unicode/$f\n#done\n    \nwget $emoji_url -O unicode/emoji-data.txt\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/unicode_gen.c",
    "content": "/*\n * Generation of Unicode tables\n * \n * Copyright (c) 2017-2018 Fabrice Bellard\n * Copyright (c) 2017-2018 Charlie Gordon\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <inttypes.h>\n#include <string.h>\n#include <assert.h>\n#include <ctype.h>\n#include <time.h>\n\n#include \"cutils.h\"\n\n/* define it to be able to test unicode.c */\n//#define USE_TEST\n/* profile tests */\n//#define PROFILE\n\n//#define DUMP_CASE_CONV_TABLE\n//#define DUMP_TABLE_SIZE\n//#define DUMP_CC_TABLE\n//#define DUMP_DECOMP_TABLE\n\n/* Ideas:\n   - Generalize run length encoding + index for all tables\n   - remove redundant tables for ID_start, ID_continue, Case_Ignorable, Cased\n\n   Case conversion:\n   - use a single entry for consecutive U/LF runs\n   - allow EXT runs of length > 1\n\n   Decomposition:\n   - Greek lower case (+1f10/1f10) ?\n   - allow holes in B runs\n   - suppress more upper / lower case redundancy\n*/\n\n#ifdef USE_TEST\n#include \"libunicode.c\"\n#endif\n\n#define CHARCODE_MAX 0x10ffff\n#define CC_LEN_MAX 3\n\nvoid *mallocz(size_t size)\n{\n    void *ptr;\n    ptr = malloc(size);\n    memset(ptr, 0, size);\n    return ptr;\n}\n\nconst char *get_field(const char *p, int n)\n{\n    int i;\n    for(i = 0; i < n; i++) {\n        while (*p != ';' && *p != '\\0')\n            p++;\n        if (*p == '\\0')\n            return NULL;\n        p++;\n    }\n    return p;\n}\n\nconst char *get_field_buf(char *buf, size_t buf_size, const char *p, int n)\n{\n    char *q;\n    p = get_field(p, n);\n    q = buf;\n    while (*p != ';' && *p != '\\0') {\n        if ((q - buf) < buf_size - 1)\n            *q++ = *p;\n        p++;\n    }\n    *q = '\\0';\n    return buf;\n}\n\nvoid add_char(int **pbuf, int *psize, int *plen, int c)\n{\n    int len, size, *buf;\n    buf = *pbuf;\n    size = *psize;\n    len = *plen;\n    if (len >= size) {\n        size = *psize;\n        size = max_int(len + 1, size * 3 / 2);\n        buf = realloc(buf, sizeof(buf[0]) * size);\n        *pbuf = buf;\n        *psize = size;\n    }\n    buf[len++] = c;\n    *plen = len;\n}\n\nint *get_field_str(int *plen, const char *str, int n)\n{\n    const char *p;\n    int *buf, len, size;\n    p = get_field(str, n);\n    if (!p) {\n        *plen = 0;\n        return NULL;\n    }\n    len = 0;\n    size = 0;\n    buf = NULL;\n    for(;;) {\n        while (isspace(*p))\n            p++;\n        if (!isxdigit(*p))\n            break;\n        add_char(&buf, &size, &len, strtoul(p, (char **)&p, 16));\n    }\n    *plen = len;\n    return buf;\n}\n\nchar *get_line(char *buf, int buf_size, FILE *f)\n{\n    int len;\n    if (!fgets(buf, buf_size, f))\n        return NULL;\n    len = strlen(buf);\n    if (len > 0 && buf[len - 1] == '\\n')\n        buf[len - 1] = '\\0';\n    return buf;\n}\n\n#define UNICODE_GENERAL_CATEGORY\n\ntypedef enum {\n#define DEF(id, str) GCAT_ ## id,\n#include \"unicode_gen_def.h\"\n#undef DEF\n    GCAT_COUNT,\n} UnicodeGCEnum1;\n\nstatic const char *unicode_gc_name[] = {\n#define DEF(id, str) #id,\n#include \"unicode_gen_def.h\"\n#undef DEF\n};\n\nstatic const char *unicode_gc_short_name[] = {\n#define DEF(id, str) str,\n#include \"unicode_gen_def.h\"\n#undef DEF\n};\n\n#undef UNICODE_GENERAL_CATEGORY\n\n#define UNICODE_SCRIPT\n\ntypedef enum {\n#define DEF(id, str) SCRIPT_ ## id,\n#include \"unicode_gen_def.h\"\n#undef DEF\n    SCRIPT_COUNT,\n} UnicodeScriptEnum1;\n\nstatic const char *unicode_script_name[] = {\n#define DEF(id, str) #id,\n#include \"unicode_gen_def.h\"\n#undef DEF\n};\n\nconst char *unicode_script_short_name[] = {\n#define DEF(id, str) str,\n#include \"unicode_gen_def.h\"\n#undef DEF\n};\n\n#undef UNICODE_SCRIPT\n\n#define UNICODE_PROP_LIST\n\ntypedef enum {\n#define DEF(id, str) PROP_ ## id,\n#include \"unicode_gen_def.h\"\n#undef DEF\n    PROP_COUNT,\n} UnicodePropEnum1;\n\nstatic const char *unicode_prop_name[] = {\n#define DEF(id, str) #id,\n#include \"unicode_gen_def.h\"\n#undef DEF\n};\n\nstatic const char *unicode_prop_short_name[] = {\n#define DEF(id, str) str,\n#include \"unicode_gen_def.h\"\n#undef DEF\n};\n\n#undef UNICODE_SPROP_LIST\n\ntypedef struct {\n    /* case conv */\n    uint8_t u_len;\n    uint8_t l_len;\n    int u_data[CC_LEN_MAX];\n    int l_data[CC_LEN_MAX];\n    int f_code;\n\n    uint8_t combining_class;\n    uint8_t is_compat:1;\n    uint8_t is_excluded:1;\n    uint8_t general_category;\n    uint8_t script;\n    uint8_t script_ext_len;\n    uint8_t *script_ext;\n    uint32_t prop_bitmap_tab[3];\n    /* decomposition */\n    int decomp_len;\n    int *decomp_data;\n} CCInfo;\n\nCCInfo *unicode_db;\n\nint find_name(const char **tab, int tab_len, const char *name)\n{\n    int i, len, name_len;\n    const char *p, *r;\n\n    name_len = strlen(name);\n    for(i = 0; i < tab_len; i++) {\n        p = tab[i];\n        for(;;) {\n            r = strchr(p, ',');\n            if (!r)\n                len = strlen(p);\n            else\n                len = r - p;\n            if (len == name_len && memcmp(p, name, len) == 0)\n                return i;\n            if (!r)\n                break;\n            p = r + 1;\n        }\n    }\n    return -1;\n}\n\nstatic int get_prop(uint32_t c, int prop_idx)\n{\n    return (unicode_db[c].prop_bitmap_tab[prop_idx >> 5] >> (prop_idx & 0x1f)) & 1;\n}\n\nstatic void set_prop(uint32_t c, int prop_idx, int val)\n{\n    uint32_t mask;\n    mask = 1U << (prop_idx & 0x1f);\n    if (val)\n        unicode_db[c].prop_bitmap_tab[prop_idx >> 5] |= mask;\n    else\n        unicode_db[c].prop_bitmap_tab[prop_idx >> 5]  &= ~mask;\n}\n\nvoid parse_unicode_data(const char *filename)\n{\n    FILE *f;\n    char line[1024];\n    char buf1[256];\n    const char *p;\n    int code, lc, uc, last_code;\n    CCInfo *ci, *tab = unicode_db;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    last_code = 0;\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#')\n            continue;\n\n        p = get_field(line, 0);\n        if (!p)\n            continue;\n        code = strtoul(p, NULL, 16);\n        lc = 0;\n        uc = 0;\n        \n        p = get_field(line, 12);\n        if (p && *p != ';') {\n            uc = strtoul(p, NULL, 16);\n        }\n\n        p = get_field(line, 13);\n        if (p && *p != ';') {\n            lc = strtoul(p, NULL, 16);\n        }\n        ci = &tab[code];\n        if (uc > 0 || lc > 0) {\n            assert(code <= CHARCODE_MAX);\n            if (uc > 0) {\n                assert(ci->u_len == 0);\n                ci->u_len = 1;\n                ci->u_data[0] = uc;\n            }\n            if (lc > 0) {\n                assert(ci->l_len == 0);\n                ci->l_len = 1;\n                ci->l_data[0] = lc;\n            }\n        }\n\n        {\n            int i;\n            get_field_buf(buf1, sizeof(buf1), line, 2);\n            i = find_name(unicode_gc_name, countof(unicode_gc_name), buf1);\n            if (i < 0) {\n                fprintf(stderr, \"General category '%s' not found\\n\",\n                        buf1);\n                exit(1);\n            }\n            ci->general_category = i;\n        }\n        \n        p = get_field(line, 3);\n        if (p && *p != ';' && *p != '\\0') {\n            int cc;\n            cc = strtoul(p, NULL, 0);\n            if (cc != 0) {\n                assert(code <= CHARCODE_MAX);\n                ci->combining_class = cc;\n                //                printf(\"%05x: %d\\n\", code, ci->combining_class);\n            }\n        }\n\n        p = get_field(line, 5);\n        if (p && *p != ';' && *p != '\\0') {\n            int size;\n            assert(code <= CHARCODE_MAX);\n            ci->is_compat = 0;\n            if (*p == '<') {\n                while (*p != '\\0' && *p != '>')\n                    p++;\n                if (*p == '>')\n                    p++;\n                ci->is_compat = 1;\n            }\n            size = 0;\n            for(;;) {\n                while (isspace(*p))\n                    p++;\n                if (!isxdigit(*p))\n                    break;\n                add_char(&ci->decomp_data, &size, &ci->decomp_len, strtoul(p, (char **)&p, 16));\n            }\n#if 0\n            {\n                int i;\n                static int count, d_count;\n\n                printf(\"%05x: %c\", code, ci->is_compat ? 'C': ' ');\n                for(i = 0; i < ci->decomp_len; i++)\n                    printf(\" %05x\", ci->decomp_data[i]);\n                printf(\"\\n\");\n                count++;\n                d_count += ci->decomp_len;\n                //                printf(\"%d %d\\n\", count, d_count);\n            }\n#endif\n        }\n\n        p = get_field(line, 9);\n        if (p && *p == 'Y') {\n            set_prop(code, PROP_Bidi_Mirrored, 1);\n        }\n        \n        /* handle ranges */\n        get_field_buf(buf1, sizeof(buf1), line, 1);\n        if (strstr(buf1, \" Last>\")) {\n            int i;\n            //            printf(\"range: 0x%x-%0x\\n\", last_code, code);\n            assert(ci->decomp_len == 0);\n            assert(ci->script_ext_len == 0);\n            for(i = last_code + 1; i < code; i++) {\n                unicode_db[i] = *ci;\n            }\n        }\n        last_code = code;\n    }\n        \n    fclose(f);\n}\n\nvoid parse_special_casing(CCInfo *tab, const char *filename)\n{\n    FILE *f;\n    char line[1024];\n    const char *p;\n    int code;\n    CCInfo *ci;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#')\n            continue;\n\n        p = get_field(line, 0);\n        if (!p)\n            continue;\n        code = strtoul(p, NULL, 16);\n        assert(code <= CHARCODE_MAX);\n        ci = &tab[code];\n\n        p = get_field(line, 4);\n        if (p) {\n            /* locale dependent casing */\n            while (isspace(*p))\n                p++;\n            if (*p != '#' && *p != '\\0')\n                continue;\n        }\n            \n        \n        p = get_field(line, 1);\n        if (p && *p != ';') {\n            ci->l_len = 0;\n            for(;;) {\n                while (isspace(*p))\n                    p++;\n                if (*p == ';')\n                    break;\n                assert(ci->l_len < CC_LEN_MAX);\n                ci->l_data[ci->l_len++] = strtoul(p, (char **)&p, 16);\n            }\n\n            if (ci->l_len == 1 && ci->l_data[0] == code)\n                ci->l_len = 0;\n        }\n\n        p = get_field(line, 3);\n        if (p && *p != ';') {\n            ci->u_len = 0;\n            for(;;) {\n                while (isspace(*p))\n                    p++;\n                if (*p == ';')\n                    break;\n                assert(ci->u_len < CC_LEN_MAX);\n                ci->u_data[ci->u_len++] = strtoul(p, (char **)&p, 16);\n            }\n\n            if (ci->u_len == 1 && ci->u_data[0] == code)\n                ci->u_len = 0;\n        }\n    }\n        \n    fclose(f);\n}\n\nvoid parse_case_folding(CCInfo *tab, const char *filename)\n{\n    FILE *f;\n    char line[1024];\n    const char *p;\n    int code;\n    CCInfo *ci;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#')\n            continue;\n\n        p = get_field(line, 0);\n        if (!p)\n            continue;\n        code = strtoul(p, NULL, 16);\n        assert(code <= CHARCODE_MAX);\n        ci = &tab[code];\n\n        p = get_field(line, 1);\n        if (!p)\n            continue;\n        /* locale dependent casing */\n        while (isspace(*p))\n            p++;\n        if (*p != 'C' && *p != 'S')\n            continue;\n        \n        p = get_field(line, 2);\n        assert(p != 0);\n        assert(ci->f_code == 0);\n        ci->f_code = strtoul(p, NULL, 16);\n        assert(ci->f_code != 0 && ci->f_code != code);\n    }\n        \n    fclose(f);\n}\n\nvoid parse_composition_exclusions(const char *filename)\n{\n    FILE *f;\n    char line[4096], *p;\n    uint32_t c0;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#' || *p == '@' || *p == '\\0')\n            continue;\n        c0 = strtoul(p, (char **)&p, 16);\n        assert(c0 > 0 && c0 <= CHARCODE_MAX);\n        unicode_db[c0].is_excluded = TRUE;\n    }\n    fclose(f);\n}\n\nvoid parse_derived_core_properties(const char *filename)\n{\n    FILE *f;\n    char line[4096], *p, buf[256], *q;\n    uint32_t c0, c1, c;\n    int i;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#' || *p == '@' || *p == '\\0')\n            continue;\n        c0 = strtoul(p, (char **)&p, 16);\n        if (*p == '.' && p[1] == '.') {\n            p += 2;\n            c1 = strtoul(p, (char **)&p, 16);\n        } else {\n            c1 = c0;\n        }\n        assert(c1 <= CHARCODE_MAX);\n        p += strspn(p, \" \\t\");\n        if (*p == ';') {\n            p++;\n            p += strspn(p, \" \\t\");\n            q = buf;\n            while (*p != '\\0' && *p != ' ' && *p != '#' && *p != '\\t') {\n                if ((q - buf) < sizeof(buf) - 1)\n                    *q++ = *p;\n                p++;\n            }\n            *q = '\\0';\n            i = find_name(unicode_prop_name,\n                          countof(unicode_prop_name), buf);\n            if (i < 0) {\n                if (!strcmp(buf, \"Grapheme_Link\"))\n                    goto next;\n                fprintf(stderr, \"Property not found: %s\\n\", buf);\n                exit(1);\n            }\n            for(c = c0; c <= c1; c++) {\n                set_prop(c, i, 1);\n            }\nnext: ;\n        }\n    }\n    fclose(f);\n}\n\nvoid parse_derived_norm_properties(const char *filename)\n{\n    FILE *f;\n    char line[4096], *p, buf[256], *q;\n    uint32_t c0, c1, c;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#' || *p == '@' || *p == '\\0')\n            continue;\n        c0 = strtoul(p, (char **)&p, 16);\n        if (*p == '.' && p[1] == '.') {\n            p += 2;\n            c1 = strtoul(p, (char **)&p, 16);\n        } else {\n            c1 = c0;\n        }\n        assert(c1 <= CHARCODE_MAX);\n        p += strspn(p, \" \\t\");\n        if (*p == ';') {\n            p++;\n            p += strspn(p, \" \\t\");\n            q = buf;\n            while (*p != '\\0' && *p != ' ' && *p != '#' && *p != '\\t') {\n                if ((q - buf) < sizeof(buf) - 1)\n                    *q++ = *p;\n                p++;\n            }\n            *q = '\\0';\n            if (!strcmp(buf, \"Changes_When_NFKC_Casefolded\")) {\n                for(c = c0; c <= c1; c++) {\n                    set_prop(c, PROP_Changes_When_NFKC_Casefolded, 1);\n                }\n            }\n        }\n    }\n    fclose(f);\n}\n\nvoid parse_prop_list(const char *filename)\n{\n    FILE *f;\n    char line[4096], *p, buf[256], *q;\n    uint32_t c0, c1, c;\n    int i;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#' || *p == '@' || *p == '\\0')\n            continue;\n        c0 = strtoul(p, (char **)&p, 16);\n        if (*p == '.' && p[1] == '.') {\n            p += 2;\n            c1 = strtoul(p, (char **)&p, 16);\n        } else {\n            c1 = c0;\n        }\n        assert(c1 <= CHARCODE_MAX);\n        p += strspn(p, \" \\t\");\n        if (*p == ';') {\n            p++;\n            p += strspn(p, \" \\t\");\n            q = buf;\n            while (*p != '\\0' && *p != ' ' && *p != '#' && *p != '\\t') {\n                if ((q - buf) < sizeof(buf) - 1)\n                    *q++ = *p;\n                p++;\n            }\n            *q = '\\0';\n            i = find_name(unicode_prop_name,\n                          countof(unicode_prop_name), buf);\n            if (i < 0) {\n                fprintf(stderr, \"Property not found: %s\\n\", buf);\n                exit(1);\n            }\n            for(c = c0; c <= c1; c++) {\n                set_prop(c, i, 1);\n            }\n        }\n    }\n    fclose(f);\n}\n\nvoid parse_scripts(const char *filename)\n{\n    FILE *f;\n    char line[4096], *p, buf[256], *q;\n    uint32_t c0, c1, c;\n    int i;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#' || *p == '@' || *p == '\\0')\n            continue;\n        c0 = strtoul(p, (char **)&p, 16);\n        if (*p == '.' && p[1] == '.') {\n            p += 2;\n            c1 = strtoul(p, (char **)&p, 16);\n        } else {\n            c1 = c0;\n        }\n        assert(c1 <= CHARCODE_MAX);\n        p += strspn(p, \" \\t\");\n        if (*p == ';') {\n            p++;\n            p += strspn(p, \" \\t\");\n            q = buf;\n            while (*p != '\\0' && *p != ' ' && *p != '#' && *p != '\\t') {\n                if ((q - buf) < sizeof(buf) - 1)\n                    *q++ = *p;\n                p++;\n            }\n            *q = '\\0';\n            i = find_name(unicode_script_name,\n                          countof(unicode_script_name), buf);\n            if (i < 0) {\n                fprintf(stderr, \"Unknown script: '%s'\\n\", buf);\n                exit(1);\n            }\n            for(c = c0; c <= c1; c++)\n                unicode_db[c].script = i;\n        }\n    }\n    fclose(f);\n}\n\nvoid parse_script_extensions(const char *filename)\n{\n    FILE *f;\n    char line[4096], *p, buf[256], *q;\n    uint32_t c0, c1, c;\n    int i;\n    uint8_t script_ext[255];\n    int script_ext_len;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#' || *p == '@' || *p == '\\0')\n            continue;\n        c0 = strtoul(p, (char **)&p, 16);\n        if (*p == '.' && p[1] == '.') {\n            p += 2;\n            c1 = strtoul(p, (char **)&p, 16);\n        } else {\n            c1 = c0;\n        }\n        assert(c1 <= CHARCODE_MAX);\n        p += strspn(p, \" \\t\");\n        script_ext_len = 0;\n        if (*p == ';') {\n            p++;\n            for(;;) {\n                p += strspn(p, \" \\t\");\n                q = buf;\n                while (*p != '\\0' && *p != ' ' && *p != '#' && *p != '\\t') {\n                    if ((q - buf) < sizeof(buf) - 1)\n                        *q++ = *p;\n                    p++;\n                }\n                *q = '\\0';\n                if (buf[0] == '\\0')\n                    break;\n                i = find_name(unicode_script_short_name,\n                              countof(unicode_script_short_name), buf);\n                if (i < 0) {\n                    fprintf(stderr, \"Script not found: %s\\n\", buf);\n                    exit(1);\n                }\n                assert(script_ext_len < sizeof(script_ext));\n                script_ext[script_ext_len++] = i;\n            }\n            for(c = c0; c <= c1; c++) {\n                CCInfo *ci = &unicode_db[c];\n                ci->script_ext_len = script_ext_len;\n                ci->script_ext = malloc(sizeof(ci->script_ext[0]) * script_ext_len);\n                for(i = 0; i < script_ext_len; i++)\n                    ci->script_ext[i] = script_ext[i];\n            }\n        }\n    }\n    fclose(f);\n}\n\nvoid dump_cc_info(CCInfo *ci, int i)\n{\n    int j;\n    printf(\"%05x:\", i);\n    if (ci->u_len != 0) {\n        printf(\" U:\");\n        for(j = 0; j < ci->u_len; j++)\n            printf(\" %05x\", ci->u_data[j]);\n    }\n    if (ci->l_len != 0) {\n        printf(\" L:\");\n        for(j = 0; j < ci->l_len; j++)\n            printf(\" %05x\", ci->l_data[j]);\n    }\n    if (ci->f_code != 0) {\n        printf(\" F: %05x\", ci->f_code);\n    }\n    printf(\"\\n\");\n}\n\nvoid dump_data(CCInfo *tab)\n{\n    int i;\n    CCInfo *ci;\n    for(i = 0; i <= CHARCODE_MAX; i++) {\n        ci = &tab[i];\n        if (ci->u_len != 0 || ci->l_len != 0 || ci->f_code != 0) {\n            dump_cc_info(ci, i);\n        }\n    }\n}\n\nBOOL is_complicated_case(const CCInfo *ci)\n{\n    return (ci->u_len > 1 || ci->l_len > 1 ||\n            (ci->u_len > 0 && ci->l_len > 0) ||\n            (ci->f_code != 0) != ci->l_len ||\n            (ci->f_code != 0 && ci->l_data[0] != ci->f_code));\n}\n\n#ifndef USE_TEST\nenum {\n    RUN_TYPE_U,\n    RUN_TYPE_L,\n    RUN_TYPE_UF,\n    RUN_TYPE_LF,\n    RUN_TYPE_UL,\n    RUN_TYPE_LSU,\n    RUN_TYPE_U2L_399_EXT2,\n    RUN_TYPE_UF_D20,\n    RUN_TYPE_UF_D1_EXT,\n    RUN_TYPE_U_EXT,\n    RUN_TYPE_LF_EXT,\n    RUN_TYPE_U_EXT2,\n    RUN_TYPE_L_EXT2,\n    RUN_TYPE_U_EXT3,\n};\n#endif\n\nconst char *run_type_str[] = {\n    \"U\",\n    \"L\",\n    \"UF\",\n    \"LF\",\n    \"UL\",\n    \"LSU\",\n    \"U2L_399_EXT2\",\n    \"UF_D20\",\n    \"UF_D1_EXT\",\n    \"U_EXT\",\n    \"LF_EXT\",\n    \"U_EXT2\",\n    \"L_EXT2\",\n    \"U_EXT3\",\n};\n\ntypedef struct {\n    int code;\n    int len;\n    int type;\n    int data;\n    int ext_len;\n    int ext_data[3];\n    int data_index; /* 'data' coming from the table */\n} TableEntry;\n\n/* code (17), len (7), type (4) */\n\nvoid find_run_type(TableEntry *te, CCInfo *tab, int code)\n{\n    int is_lower, len;\n    CCInfo *ci, *ci1, *ci2;\n\n    ci = &tab[code];\n    ci1 = &tab[code + 1];\n    ci2 = &tab[code + 2];\n    te->code = code;\n    \n    if (ci->l_len == 1 && ci->l_data[0] == code + 2 &&\n        ci->f_code == ci->l_data[0] &&\n        ci->u_len == 0 &&\n\n        ci1->l_len == 1 && ci1->l_data[0] == code + 2 &&\n        ci1->f_code == ci1->l_data[0] &&\n        ci1->u_len == 1 && ci1->u_data[0] == code &&\n\n        ci2->l_len == 0 &&\n        ci2->f_code == 0 &&\n        ci2->u_len == 1 && ci2->u_data[0] == code) {\n        te->len = 3;\n        te->data = 0;\n        te->type = RUN_TYPE_LSU;\n        return;\n    }\n\n    if (is_complicated_case(ci)) {\n        len = 1;\n        while (code + len <= CHARCODE_MAX) {\n            ci1 = &tab[code + len];\n            if (ci1->u_len != 1 ||\n                ci1->u_data[0] != ci->u_data[0] + len ||\n                ci1->l_len != 0 ||\n                ci1->f_code != ci1->u_data[0])\n                break;\n            len++;\n        }\n        if (len > 1) {\n            te->len = len;\n            te->type = RUN_TYPE_UF;\n            te->data = ci->u_data[0];\n            return;\n        }\n\n        if (ci->u_len == 2 && ci->u_data[1] == 0x399 &&\n            ci->f_code == 0 && ci->l_len == 0) {\n            len = 1;\n            while (code + len <= CHARCODE_MAX) {\n                ci1 = &tab[code + len];\n                if (!(ci1->u_len == 2 &&\n                    ci1->u_data[1] == 0x399 &&\n                      ci1->u_data[0] == ci->u_data[0] + len &&\n                      ci1->f_code == 0 &&\n                      ci1->l_len == 0))\n                    break;\n                len++;\n            }\n            te->len = len;\n            te->type = RUN_TYPE_U_EXT2;\n            te->ext_data[0] = ci->u_data[0];\n            te->ext_data[1] = ci->u_data[1];\n            te->ext_len = 2;\n            return;\n        }\n\n        if (ci->u_len == 2 && ci->u_data[1] == 0x399 &&\n            ci->l_len == 1 && ci->f_code == ci->l_data[0]) {\n            len = 1;\n            while (code + len <= CHARCODE_MAX) {\n                ci1 = &tab[code + len];\n                if (!(ci1->u_len == 2 &&\n                      ci1->u_data[1] == 0x399 &&\n                      ci1->u_data[0] == ci->u_data[0] + len &&\n                      ci1->l_len == 1 &&\n                      ci1->l_data[0] == ci->l_data[0] + len &&\n                      ci1->f_code == ci1->l_data[0]))\n                    break;\n                len++;\n            }\n            te->len = len;\n            te->type = RUN_TYPE_U2L_399_EXT2;\n            te->ext_data[0] = ci->u_data[0];\n            te->ext_data[1] = ci->l_data[0];\n            te->ext_len = 2;\n            return;\n        }\n\n        if (ci->l_len == 1 && ci->u_len == 0 && ci->f_code == 0) {\n            len = 1;\n            while (code + len <= CHARCODE_MAX) {\n                ci1 = &tab[code + len];\n                if (!(ci1->l_len == 1 &&\n                      ci1->l_data[0] == ci->l_data[0] + len &&\n                      ci1->u_len == 0 && ci1->f_code == 0))\n                    break;\n                len++;\n            }\n            te->len = len;\n            te->type = RUN_TYPE_L;\n            te->data = ci->l_data[0];\n            return;\n        }\n\n        if (ci->l_len == 0 &&\n            ci->u_len == 1 &&\n            ci->u_data[0] < 0x1000 &&\n            ci->f_code == ci->u_data[0] + 0x20) {\n            te->len = 1;\n            te->type = RUN_TYPE_UF_D20;\n            te->data = ci->u_data[0];\n        } else if (ci->l_len == 0 &&\n            ci->u_len == 1 &&\n            ci->f_code == ci->u_data[0] + 1) {\n            te->len = 1;\n            te->type = RUN_TYPE_UF_D1_EXT;\n            te->ext_data[0] = ci->u_data[0];\n            te->ext_len = 1;\n        } else if (ci->l_len == 2 && ci->u_len == 0 && ci->f_code == 0) {\n            te->len = 1;\n            te->type = RUN_TYPE_L_EXT2;\n            te->ext_data[0] = ci->l_data[0];\n            te->ext_data[1] = ci->l_data[1];\n            te->ext_len = 2;\n        } else if (ci->u_len == 2 && ci->l_len == 0 && ci->f_code == 0) {\n            te->len = 1;\n            te->type = RUN_TYPE_U_EXT2;\n            te->ext_data[0] = ci->u_data[0];\n            te->ext_data[1] = ci->u_data[1];\n            te->ext_len = 2;\n        } else if (ci->u_len == 3 && ci->l_len == 0 && ci->f_code == 0) {\n            te->len = 1;\n            te->type = RUN_TYPE_U_EXT3;\n            te->ext_data[0] = ci->u_data[0];\n            te->ext_data[1] = ci->u_data[1];\n            te->ext_data[2] = ci->u_data[2];\n            te->ext_len = 3;\n        } else {\n            printf(\"unsupported encoding case:\\n\");\n            dump_cc_info(ci, code);\n            abort();\n        }\n    } else {\n        /* look for a run of identical conversions */\n        len = 0;\n        for(;;) {\n            if (code >= CHARCODE_MAX || len >= 126)\n                break;\n            ci = &tab[code + len];\n            ci1 = &tab[code + len + 1];\n            if (is_complicated_case(ci) || is_complicated_case(ci1)) {\n                break;\n            }\n            if (ci->l_len != 1 || ci->l_data[0] != code + len + 1)\n                break;\n            if (ci1->u_len != 1 || ci1->u_data[0] != code + len)\n                break;\n            len += 2;\n        }\n        if (len > 0) {\n            te->len = len;\n            te->type = RUN_TYPE_UL;\n            te->data = 0;\n            return;\n        }\n        \n        ci = &tab[code];\n        is_lower = ci->l_len > 0;\n        len = 1;\n        while (code + len <= CHARCODE_MAX) {\n            ci1 = &tab[code + len];\n            if (is_complicated_case(ci1))\n                break;\n            if (is_lower) {\n                if (ci1->l_len != 1 ||\n                    ci1->l_data[0] != ci->l_data[0] + len)\n                    break;\n            } else {\n                if (ci1->u_len != 1 ||\n                    ci1->u_data[0] != ci->u_data[0] + len)\n                    break;\n            }\n            len++;\n        }\n        te->len = len;\n        if (is_lower) {\n            te->type = RUN_TYPE_LF;\n            te->data = ci->l_data[0];\n        } else {\n            te->type = RUN_TYPE_U;\n            te->data = ci->u_data[0];\n        }\n    }\n}\n\nTableEntry conv_table[1000];\nint conv_table_len;\nint ext_data[1000];\nint ext_data_len;\n\nvoid dump_case_conv_table1(void)\n{\n    int i, j;\n    const TableEntry *te;\n\n    for(i = 0; i < conv_table_len; i++) {\n        te = &conv_table[i];\n        printf(\"%05x %02x %-10s %05x\",\n               te->code, te->len, run_type_str[te->type], te->data);\n        for(j = 0; j < te->ext_len; j++) {\n            printf(\" %05x\", te->ext_data[j]);\n        }\n        printf(\"\\n\");\n    }\n    printf(\"table_len=%d ext_len=%d\\n\", conv_table_len, ext_data_len);\n}\n\nint find_data_index(const TableEntry *conv_table, int len, int data)\n{\n    int i;\n    const TableEntry *te;\n    for(i = 0; i < len; i++) {\n        te = &conv_table[i];\n        if (te->code == data)\n            return i;\n    }\n    return -1;\n}\n\nint find_ext_data_index(int data)\n{\n    int i;\n    for(i = 0; i < ext_data_len; i++) {\n        if (ext_data[i] == data)\n            return i;\n    }\n    assert(ext_data_len < countof(ext_data));\n    ext_data[ext_data_len++] = data;\n    return ext_data_len - 1;\n}\n\nvoid build_conv_table(CCInfo *tab)\n{\n    int code, i, j;\n    CCInfo *ci;\n    TableEntry *te;\n                          \n    te = conv_table;\n    for(code = 0; code <= CHARCODE_MAX; code++) {\n        ci = &tab[code];\n        if (ci->u_len == 0 && ci->l_len == 0 && ci->f_code == 0)\n            continue;\n        assert(te - conv_table < countof(conv_table));\n        find_run_type(te, tab, code);\n#if 0\n        if (te->type == RUN_TYPE_TODO) {\n            printf(\"TODO: \");\n            dump_cc_info(ci, code);\n        }\n#endif\n        assert(te->len <= 127);\n        code += te->len - 1;\n        te++;\n    }\n    conv_table_len = te - conv_table;\n\n    /* find the data index */\n    for(i = 0; i < conv_table_len; i++) {\n        int data_index;\n        te = &conv_table[i];\n        \n        switch(te->type) {\n        case RUN_TYPE_U:\n        case RUN_TYPE_L:\n        case RUN_TYPE_UF:\n        case RUN_TYPE_LF:\n            data_index = find_data_index(conv_table, conv_table_len, te->data);\n            if (data_index < 0) {\n                switch(te->type) {\n                case RUN_TYPE_U:\n                    te->type = RUN_TYPE_U_EXT;\n                    te->ext_len = 1;\n                    te->ext_data[0] = te->data;\n                    break;\n                case RUN_TYPE_LF:\n                    te->type = RUN_TYPE_LF_EXT;\n                    te->ext_len = 1;\n                    te->ext_data[0] = te->data;\n                    break;\n                default:\n                    printf(\"%05x: index not found\\n\", te->code);\n                    exit(1);\n                }\n            } else {\n                te->data_index = data_index;\n            }\n            break;\n        case RUN_TYPE_UF_D20:\n            te->data_index = te->data;\n            break;\n        }\n    }\n\n    /* find the data index for ext_data */\n    for(i = 0; i < conv_table_len; i++) {\n        te = &conv_table[i];\n        if (te->type == RUN_TYPE_U_EXT3) {\n            int p, v;\n            v = 0;\n            for(j = 0; j < 3; j++) {\n                p = find_ext_data_index(te->ext_data[j]);\n                assert(p < 16);\n                v = (v << 4) | p;\n            }\n            te->data_index = v;\n        }\n    }\n\n    for(i = 0; i < conv_table_len; i++) {\n        te = &conv_table[i];\n        if (te->type == RUN_TYPE_L_EXT2 ||\n            te->type == RUN_TYPE_U_EXT2 ||\n            te->type == RUN_TYPE_U2L_399_EXT2) {\n            int p, v;\n            v = 0;\n            for(j = 0; j < 2; j++) {\n                p = find_ext_data_index(te->ext_data[j]);\n                assert(p < 64);\n                v = (v << 6) | p;\n            }\n            te->data_index = v;\n        }\n    }\n\n    for(i = 0; i < conv_table_len; i++) {\n        te = &conv_table[i];\n        if (te->type == RUN_TYPE_UF_D1_EXT ||\n            te->type == RUN_TYPE_U_EXT ||\n            te->type == RUN_TYPE_LF_EXT) {\n            te->data_index = find_ext_data_index(te->ext_data[0]);\n        }\n    }\n#ifdef DUMP_CASE_CONV_TABLE\n    dump_case_conv_table1();\n#endif\n}\n\nvoid dump_case_conv_table(FILE *f)\n{\n    int i;\n    uint32_t v;\n    const TableEntry *te;\n\n    fprintf(f, \"static const uint32_t case_conv_table1[%u] = {\", conv_table_len);\n    for(i = 0; i < conv_table_len; i++) {\n        if (i % 4 == 0)\n            fprintf(f, \"\\n   \");\n        te = &conv_table[i];\n        v = te->code << (32 - 17);\n        v |= te->len << (32 - 17 - 7);\n        v |= te->type << (32 - 17 - 7 - 4);\n        v |= te->data_index >> 8;\n        fprintf(f, \" 0x%08x,\", v);\n    }\n    fprintf(f, \"\\n};\\n\\n\");\n\n    fprintf(f, \"static const uint8_t case_conv_table2[%u] = {\", conv_table_len);\n    for(i = 0; i < conv_table_len; i++) {\n        if (i % 8 == 0)\n            fprintf(f, \"\\n   \");\n        te = &conv_table[i];\n        fprintf(f, \" 0x%02x,\", te->data_index & 0xff);\n    }\n    fprintf(f, \"\\n};\\n\\n\");\n\n    fprintf(f, \"static const uint16_t case_conv_ext[%u] = {\", ext_data_len);\n    for(i = 0; i < ext_data_len; i++) {\n        if (i % 8 == 0)\n            fprintf(f, \"\\n   \");\n        fprintf(f, \" 0x%04x,\", ext_data[i]);\n    }\n    fprintf(f, \"\\n};\\n\\n\");\n}\n\nint tabcmp(const int *tab1, const int *tab2, int n)\n{\n    int i;\n    for(i = 0; i < n; i++) {\n        if (tab1[i] != tab2[i])\n            return -1;\n    }\n    return 0;\n}\n\nvoid dump_str(const char *str, const int *buf, int len)\n{\n    int i;\n    printf(\"%s=\", str);\n    for(i = 0; i < len; i++)\n        printf(\" %05x\", buf[i]);\n    printf(\"\\n\");\n}\n\nvoid compute_internal_props(void)\n{\n    int i;\n    BOOL has_ul;\n\n    for(i = 0; i <= CHARCODE_MAX; i++) {\n        CCInfo *ci = &unicode_db[i];\n        has_ul = (ci->u_len != 0 || ci->l_len != 0 || ci->f_code != 0);\n        if (has_ul) {\n            assert(get_prop(i, PROP_Cased));\n        } else {\n            set_prop(i, PROP_Cased1, get_prop(i, PROP_Cased));\n        }\n        set_prop(i, PROP_ID_Continue1,\n                 get_prop(i, PROP_ID_Continue) & (get_prop(i, PROP_ID_Start) ^ 1));\n        set_prop(i, PROP_XID_Start1,\n                 get_prop(i, PROP_ID_Start) ^ get_prop(i, PROP_XID_Start));\n        set_prop(i, PROP_XID_Continue1,\n                 get_prop(i, PROP_ID_Continue) ^ get_prop(i, PROP_XID_Continue));\n        set_prop(i, PROP_Changes_When_Titlecased1,\n                 get_prop(i, PROP_Changes_When_Titlecased) ^ (ci->u_len != 0));\n        set_prop(i, PROP_Changes_When_Casefolded1,\n                 get_prop(i, PROP_Changes_When_Casefolded) ^ (ci->f_code != 0));\n        /* XXX: reduce table size (438 bytes) */\n        set_prop(i, PROP_Changes_When_NFKC_Casefolded1,\n                 get_prop(i, PROP_Changes_When_NFKC_Casefolded) ^ (ci->f_code != 0));\n#if 0\n        /* TEST */\n#define M(x) (1U << GCAT_ ## x)\n        {\n            int b;\n            b = ((M(Mn) | M(Cf) | M(Lm) | M(Sk)) >>\n                 unicode_db[i].general_category) & 1;\n            set_prop(i, PROP_Cased1,\n                     get_prop(i, PROP_Case_Ignorable) ^ b);\n        }\n#undef M\n#endif\n    }\n}\n\nvoid dump_byte_table(FILE *f, const char *cname, const uint8_t *tab, int len)\n{\n    int i;\n    fprintf(f, \"static const uint8_t %s[%d] = {\", cname, len);\n    for(i = 0; i < len; i++) {\n        if (i % 8 == 0)\n            fprintf(f, \"\\n   \");\n        fprintf(f, \" 0x%02x,\", tab[i]);\n    }\n    fprintf(f, \"\\n};\\n\\n\");\n}\n\n#define PROP_BLOCK_LEN 32\n\nvoid build_prop_table(FILE *f, int prop_index, BOOL add_index)\n{\n    int i, j, n, v, offset, code;\n    DynBuf dbuf_s, *dbuf = &dbuf_s;\n    DynBuf dbuf1_s, *dbuf1 = &dbuf1_s;\n    DynBuf dbuf2_s, *dbuf2 = &dbuf2_s;\n    const uint32_t *buf;\n    int buf_len, block_end_pos, bit;\n    char cname[128];\n    \n    dbuf_init(dbuf1);\n\n    for(i = 0; i <= CHARCODE_MAX;) {\n        v = get_prop(i, prop_index);\n        j = i + 1;\n        while (j <= CHARCODE_MAX && get_prop(j, prop_index) == v) {\n            j++;\n        }\n        n = j - i;\n        if (j == (CHARCODE_MAX + 1) && v == 0)\n            break; /* no need to encode last zero run */\n        //printf(\"%05x: %d %d\\n\", i, n, v);\n        dbuf_put_u32(dbuf1, n - 1);\n        i += n;\n    }\n    \n    dbuf_init(dbuf);\n    dbuf_init(dbuf2);\n    buf = (uint32_t *)dbuf1->buf;\n    buf_len = dbuf1->size / sizeof(buf[0]);\n    \n    /* the first value is assumed to be 0 */\n    assert(get_prop(0, prop_index) == 0);\n    \n    block_end_pos = PROP_BLOCK_LEN;\n    i = 0;\n    code = 0;\n    bit = 0;\n    while (i < buf_len) {\n        if (add_index && dbuf->size >= block_end_pos && bit == 0) {\n            offset = (dbuf->size - block_end_pos);\n            /* XXX: offset could be larger in case of runs of small\n               lengths. Could add code to change the encoding to\n               prevent it at the expense of one byte loss */\n            assert(offset <= 7);\n            v = code | (offset << 21);\n            dbuf_putc(dbuf2, v);\n            dbuf_putc(dbuf2, v >> 8);\n            dbuf_putc(dbuf2, v >> 16);\n            block_end_pos += PROP_BLOCK_LEN;\n        }\n\n        v = buf[i];\n        code += v + 1;\n        bit ^= 1;\n        if (v < 8 && (i + 1) < buf_len && buf[i + 1] < 8) {\n            code += buf[i + 1] + 1;\n            bit ^= 1;\n            dbuf_putc(dbuf, (v << 3) | buf[i + 1]);\n            i += 2;\n        } else if (v < 128) {\n            dbuf_putc(dbuf, 0x80 + v);\n            i++;\n        } else if (v < (1 << 13)) {\n            dbuf_putc(dbuf, 0x40 + (v >> 8));\n            dbuf_putc(dbuf, v);\n            i++;\n        } else {\n            assert(v < (1 << 21));\n            dbuf_putc(dbuf, 0x60 + (v >> 16));\n            dbuf_putc(dbuf, v >> 8);\n            dbuf_putc(dbuf, v);\n            i++;\n        }\n    }\n\n    if (add_index) {\n        /* last index entry */\n        v = code;\n        dbuf_putc(dbuf2, v);\n        dbuf_putc(dbuf2, v >> 8);\n        dbuf_putc(dbuf2, v >> 16);\n    }\n\n#ifdef DUMP_TABLE_SIZE\n    printf(\"prop %s: length=%d bytes\\n\", unicode_prop_name[prop_index],\n           (int)(dbuf->size + dbuf2->size));\n#endif\n    snprintf(cname, sizeof(cname), \"unicode_prop_%s_table\", unicode_prop_name[prop_index]);\n    dump_byte_table(f, cname, dbuf->buf, dbuf->size);\n    if (add_index) {\n        snprintf(cname, sizeof(cname), \"unicode_prop_%s_index\", unicode_prop_name[prop_index]);\n        dump_byte_table(f, cname, dbuf2->buf, dbuf2->size);\n    }\n    \n    dbuf_free(dbuf);\n    dbuf_free(dbuf1);\n    dbuf_free(dbuf2);\n}\n\nvoid build_flags_tables(FILE *f)\n{\n    build_prop_table(f, PROP_Cased1, TRUE);\n    build_prop_table(f, PROP_Case_Ignorable, TRUE);\n    build_prop_table(f, PROP_ID_Start, TRUE);\n    build_prop_table(f, PROP_ID_Continue1, TRUE);\n}\n\nvoid dump_name_table(FILE *f, const char *cname, const char **tab_name, int len,\n                     const char **tab_short_name)\n{\n    int i, w, maxw;\n\n    maxw = 0;\n    for(i = 0; i < len; i++) {\n        w = strlen(tab_name[i]);\n        if (tab_short_name[i][0] != '\\0') {\n            w += 1 + strlen(tab_short_name[i]);\n        }\n        if (maxw < w)\n            maxw = w;\n    }\n\n    /* generate a sequence of strings terminated by an empty string */\n    fprintf(f, \"static const char %s[] =\\n\", cname);\n    for(i = 0; i < len; i++) {\n        fprintf(f, \"    \\\"\");\n        w = fprintf(f, \"%s\", tab_name[i]);\n        if (tab_short_name[i][0] != '\\0') {\n            w += fprintf(f, \",%s\", tab_short_name[i]);\n        }\n        fprintf(f, \"\\\"%*s\\\"\\\\0\\\"\\n\", 1 + maxw - w, \"\");\n    }\n    fprintf(f, \";\\n\\n\");\n}\n\nvoid build_general_category_table(FILE *f)\n{\n    int i, v, j, n, n1;\n    DynBuf dbuf_s, *dbuf = &dbuf_s;\n    int cw_count, cw_len_count[4], cw_start;\n\n    fprintf(f, \"typedef enum {\\n\");\n    for(i = 0; i < GCAT_COUNT; i++)\n        fprintf(f, \"    UNICODE_GC_%s,\\n\", unicode_gc_name[i]);\n    fprintf(f, \"    UNICODE_GC_COUNT,\\n\");\n    fprintf(f, \"} UnicodeGCEnum;\\n\\n\");\n\n    dump_name_table(f, \"unicode_gc_name_table\",\n                    unicode_gc_name, GCAT_COUNT,\n                    unicode_gc_short_name);\n\n\n    dbuf_init(dbuf);\n    cw_count = 0;\n    for(i = 0; i < 4; i++)\n        cw_len_count[i] = 0;\n    for(i = 0; i <= CHARCODE_MAX;) {\n        v = unicode_db[i].general_category;\n        j = i + 1;\n        while (j <= CHARCODE_MAX && unicode_db[j].general_category == v)\n            j++;\n        n = j - i;\n        /* compress Lu/Ll runs */\n        if (v == GCAT_Lu) {\n            n1 = 1;\n            while ((i + n1) <= CHARCODE_MAX && unicode_db[i + n1].general_category == (v + (n1 & 1))) {\n                n1++;\n            }\n            if (n1 > n) {\n                v = 31;\n                n = n1;\n            }\n        }\n        //        printf(\"%05x %05x %d\\n\", i, n, v);\n        cw_count++;\n        n--;\n        cw_start = dbuf->size;\n        if (n < 7) {\n            dbuf_putc(dbuf, (n << 5) | v);\n        } else if (n < 7 + 128) {\n            n1 = n - 7;\n            assert(n1 < 128);\n            dbuf_putc(dbuf, (0xf << 5) | v);\n            dbuf_putc(dbuf, n1);\n        } else if (n < 7 + 128 + (1 << 14)) {\n            n1 = n - (7 + 128);\n            assert(n1 < (1 << 14));\n            dbuf_putc(dbuf, (0xf << 5) | v);\n            dbuf_putc(dbuf, (n1 >> 8) + 128);\n            dbuf_putc(dbuf, n1);\n        } else {\n            n1 = n - (7 + 128 + (1 << 14));\n            assert(n1 < (1 << 22));\n            dbuf_putc(dbuf, (0xf << 5) | v);\n            dbuf_putc(dbuf, (n1 >> 16) + 128 + 64);\n            dbuf_putc(dbuf, n1 >> 8);\n            dbuf_putc(dbuf, n1);\n        }\n        cw_len_count[dbuf->size - cw_start - 1]++;\n        i += n + 1;\n    }\n#ifdef DUMP_TABLE_SIZE\n    printf(\"general category: %d entries [\",\n           cw_count);\n    for(i = 0; i < 4; i++)\n        printf(\" %d\", cw_len_count[i]);\n    printf(\" ], length=%d bytes\\n\", (int)dbuf->size);\n#endif\n    \n    dump_byte_table(f, \"unicode_gc_table\", dbuf->buf, dbuf->size);\n\n    dbuf_free(dbuf);\n}\n\nvoid build_script_table(FILE *f)\n{\n    int i, v, j, n, n1, type;\n    DynBuf dbuf_s, *dbuf = &dbuf_s;\n    int cw_count, cw_len_count[4], cw_start;\n\n    fprintf(f, \"typedef enum {\\n\");\n    for(i = 0; i < SCRIPT_COUNT; i++)\n        fprintf(f, \"    UNICODE_SCRIPT_%s,\\n\", unicode_script_name[i]);\n    fprintf(f, \"    UNICODE_SCRIPT_COUNT,\\n\");\n    fprintf(f, \"} UnicodeScriptEnum;\\n\\n\");\n\n    i = 1;\n    dump_name_table(f, \"unicode_script_name_table\",\n                    unicode_script_name + i, SCRIPT_COUNT - i,\n                    unicode_script_short_name + i);\n\n    dbuf_init(dbuf);\n    cw_count = 0;\n    for(i = 0; i < 4; i++)\n        cw_len_count[i] = 0;\n    for(i = 0; i <= CHARCODE_MAX;) {\n        v = unicode_db[i].script;\n        j = i + 1;\n        while (j <= CHARCODE_MAX && unicode_db[j].script == v)\n            j++;\n        n = j - i;\n        if (v == 0 && j == (CHARCODE_MAX + 1))\n            break;\n        //        printf(\"%05x %05x %d\\n\", i, n, v);\n        cw_count++;\n        n--;\n        cw_start = dbuf->size;\n        if (v == 0)\n            type = 0;\n        else\n            type = 1;\n        if (n < 96) {\n            dbuf_putc(dbuf, n | (type << 7));\n        } else if (n < 96 + (1 << 12)) {\n            n1 = n - 96;\n            assert(n1 < (1 << 12));\n            dbuf_putc(dbuf, ((n1 >> 8) + 96) | (type << 7));\n            dbuf_putc(dbuf, n1);\n        } else {\n            n1 = n - (96 + (1 << 12));\n            assert(n1 < (1 << 20));\n            dbuf_putc(dbuf, ((n1 >> 16) + 112) | (type << 7));\n            dbuf_putc(dbuf, n1 >> 8);\n            dbuf_putc(dbuf, n1);\n        }\n        if (type != 0)\n            dbuf_putc(dbuf, v);\n\n        cw_len_count[dbuf->size - cw_start - 1]++;\n        i += n + 1;\n    }\n#if defined(DUMP_TABLE_SIZE)\n    printf(\"script: %d entries [\",\n           cw_count);\n    for(i = 0; i < 4; i++)\n        printf(\" %d\", cw_len_count[i]);\n    printf(\" ], length=%d bytes\\n\", (int)dbuf->size);\n#endif\n    \n    dump_byte_table(f, \"unicode_script_table\", dbuf->buf, dbuf->size);\n\n    dbuf_free(dbuf);\n}\n\nvoid build_script_ext_table(FILE *f)\n{\n    int i, j, n, n1, script_ext_len;\n    DynBuf dbuf_s, *dbuf = &dbuf_s;\n    int cw_count;\n\n    dbuf_init(dbuf);\n    cw_count = 0;\n    for(i = 0; i <= CHARCODE_MAX;) {\n        script_ext_len = unicode_db[i].script_ext_len;\n        j = i + 1;\n        while (j <= CHARCODE_MAX &&\n               unicode_db[j].script_ext_len == script_ext_len &&\n               !memcmp(unicode_db[j].script_ext, unicode_db[i].script_ext,\n                       script_ext_len)) {\n            j++;\n        }\n        n = j - i;\n        cw_count++;\n        n--;\n        if (n < 128) {\n            dbuf_putc(dbuf, n);\n        } else if (n < 128 + (1 << 14)) {\n            n1 = n - 128;\n            assert(n1 < (1 << 14));\n            dbuf_putc(dbuf, (n1 >> 8) + 128);\n            dbuf_putc(dbuf, n1);\n        } else {\n            n1 = n - (128 + (1 << 14));\n            assert(n1 < (1 << 22));\n            dbuf_putc(dbuf, (n1 >> 16) + 128 + 64);\n            dbuf_putc(dbuf, n1 >> 8);\n            dbuf_putc(dbuf, n1);\n        }\n        dbuf_putc(dbuf, script_ext_len);\n        for(j = 0; j < script_ext_len; j++)\n            dbuf_putc(dbuf, unicode_db[i].script_ext[j]);\n        i += n + 1;\n    }\n#ifdef DUMP_TABLE_SIZE\n    printf(\"script_ext: %d entries\",\n           cw_count);\n    printf(\", length=%d bytes\\n\", (int)dbuf->size);\n#endif\n    \n    dump_byte_table(f, \"unicode_script_ext_table\", dbuf->buf, dbuf->size);\n\n    dbuf_free(dbuf);\n}\n\n/* the following properties are synthetized so no table is necessary */\n#define PROP_TABLE_COUNT PROP_ASCII\n\nvoid build_prop_list_table(FILE *f)\n{\n    int i;\n    \n    for(i = 0; i < PROP_TABLE_COUNT; i++) {\n        if (i == PROP_ID_Start ||\n            i == PROP_Case_Ignorable ||\n            i == PROP_ID_Continue1) {\n            /* already generated */\n        } else {\n            build_prop_table(f, i, FALSE);\n        }\n    }\n    \n    fprintf(f, \"typedef enum {\\n\");\n    for(i = 0; i < PROP_COUNT; i++)\n        fprintf(f, \"    UNICODE_PROP_%s,\\n\", unicode_prop_name[i]);\n    fprintf(f, \"    UNICODE_PROP_COUNT,\\n\");\n    fprintf(f, \"} UnicodePropertyEnum;\\n\\n\");\n\n    i = PROP_ASCII_Hex_Digit;\n    dump_name_table(f, \"unicode_prop_name_table\",\n                    unicode_prop_name + i, PROP_XID_Start - i + 1,\n                    unicode_prop_short_name + i);\n\n    fprintf(f, \"static const uint8_t * const unicode_prop_table[] = {\\n\");\n    for(i = 0; i < PROP_TABLE_COUNT; i++) {\n        fprintf(f, \"    unicode_prop_%s_table,\\n\", unicode_prop_name[i]);\n    }\n    fprintf(f, \"};\\n\\n\");\n\n    fprintf(f, \"static const uint16_t unicode_prop_len_table[] = {\\n\");\n    for(i = 0; i < PROP_TABLE_COUNT; i++) {\n        fprintf(f, \"    countof(unicode_prop_%s_table),\\n\", unicode_prop_name[i]);\n    }\n    fprintf(f, \"};\\n\\n\");\n}\n\n#ifdef USE_TEST\nint check_conv(uint32_t *res, uint32_t c, int conv_type)\n{\n    return lre_case_conv(res, c, conv_type);\n}\n\nvoid check_case_conv(void)\n{\n    CCInfo *tab = unicode_db;\n    uint32_t res[3];\n    int l, error;\n    CCInfo ci_s, *ci1, *ci = &ci_s;\n    int code;\n    \n    for(code = 0; code <= CHARCODE_MAX; code++) {\n        ci1 = &tab[code];\n        *ci = *ci1;\n        if (ci->l_len == 0) {\n            ci->l_len = 1;\n            ci->l_data[0] = code;\n        }\n        if (ci->u_len == 0) {\n            ci->u_len = 1;\n            ci->u_data[0] = code;\n        }\n        if (ci->f_code == 0)\n            ci->f_code = code;\n\n        error = 0;\n        l = check_conv(res, code, 0);\n        if (l != ci->u_len || tabcmp((int *)res, ci->u_data, l)) {\n            printf(\"ERROR: L\\n\");\n            error++;\n        }\n        l = check_conv(res, code, 1);\n        if (l != ci->l_len || tabcmp((int *)res, ci->l_data, l)) {\n            printf(\"ERROR: U\\n\");\n            error++;\n        }\n        l = check_conv(res, code, 2);\n        if (l != 1 || res[0] != ci->f_code) {\n            printf(\"ERROR: F\\n\");\n            error++;\n        }\n        if (error) {\n            dump_cc_info(ci, code);\n            exit(1);\n        }\n    }\n}\n\n#ifdef PROFILE\nstatic int64_t get_time_ns(void)\n{\n    struct timespec ts;\n    clock_gettime(CLOCK_MONOTONIC, &ts);\n    return (int64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;\n}\n#endif\n\n\nvoid check_flags(void)\n{\n    int c;\n    BOOL flag_ref, flag;\n    for(c = 0; c <= CHARCODE_MAX; c++) {\n        flag_ref = get_prop(c, PROP_Cased);\n        flag = lre_is_cased(c);\n        if (flag != flag_ref) {\n            printf(\"ERROR: c=%05x cased=%d ref=%d\\n\",\n                   c, flag, flag_ref);\n            exit(1);\n        }\n\n        flag_ref = get_prop(c, PROP_Case_Ignorable);\n        flag = lre_is_case_ignorable(c);\n        if (flag != flag_ref) {\n            printf(\"ERROR: c=%05x case_ignorable=%d ref=%d\\n\",\n                   c, flag, flag_ref);\n            exit(1);\n        }\n\n        flag_ref = get_prop(c, PROP_ID_Start);\n        flag = lre_is_id_start(c);\n        if (flag != flag_ref) {\n            printf(\"ERROR: c=%05x id_start=%d ref=%d\\n\",\n                   c, flag, flag_ref);\n            exit(1);\n        }\n\n        flag_ref = get_prop(c, PROP_ID_Continue);\n        flag = lre_is_id_continue(c);\n        if (flag != flag_ref) {\n            printf(\"ERROR: c=%05x id_cont=%d ref=%d\\n\",\n                   c, flag, flag_ref);\n            exit(1);\n        }\n    }\n#ifdef PROFILE\n    {\n        int64_t ti, count;\n        ti = get_time_ns();\n        count = 0;\n        for(c = 0x20; c <= 0xffff; c++) {\n            flag_ref = get_prop(c, PROP_ID_Start);\n            flag = lre_is_id_start(c);\n            assert(flag == flag_ref);\n            count++;\n        }\n        ti = get_time_ns() - ti;\n        printf(\"flags time=%0.1f ns/char\\n\",\n               (double)ti / count);\n    }\n#endif\n}\n\n#endif\n\n#define CC_BLOCK_LEN 32\n\nvoid build_cc_table(FILE *f)\n{\n    int i, cc, n, cc_table_len, type, n1;\n    DynBuf dbuf_s, *dbuf = &dbuf_s;\n    DynBuf dbuf1_s, *dbuf1 = &dbuf1_s;\n    int cw_len_tab[3], cw_start, block_end_pos;\n    uint32_t v;\n    \n    dbuf_init(dbuf);\n    dbuf_init(dbuf1);\n    cc_table_len = 0;\n    for(i = 0; i < countof(cw_len_tab); i++)\n        cw_len_tab[i] = 0;\n    block_end_pos = CC_BLOCK_LEN;\n    for(i = 0; i <= CHARCODE_MAX;) {\n        cc = unicode_db[i].combining_class;\n        assert(cc <= 255);\n        /* check increasing values */\n        n = 1;\n        while ((i + n) <= CHARCODE_MAX &&\n               unicode_db[i + n].combining_class == (cc + n))\n            n++;\n        if (n >= 2) {\n            type = 1;\n        } else {\n            type = 0;\n            n = 1;\n            while ((i + n) <= CHARCODE_MAX &&\n                   unicode_db[i + n].combining_class == cc)\n                n++;\n        }\n        /* no need to encode the last run */\n        if (cc == 0 && (i + n - 1) == CHARCODE_MAX)\n            break;\n#ifdef DUMP_CC_TABLE\n        printf(\"%05x %6d %d %d\\n\", i, n, type, cc);\n#endif\n        if (type == 0) {\n            if (cc == 0)\n                type = 2;\n            else if (cc == 230)\n                type = 3;\n        }\n        n1 = n - 1;\n\n        /* add an entry to the index if necessary */\n        if (dbuf->size >= block_end_pos) {\n            v = i | ((dbuf->size - block_end_pos) << 21);\n            dbuf_putc(dbuf1, v);\n            dbuf_putc(dbuf1, v >> 8);\n            dbuf_putc(dbuf1, v >> 16);\n            block_end_pos += CC_BLOCK_LEN;\n        }\n        cw_start = dbuf->size;\n        if (n1 < 48) {\n            dbuf_putc(dbuf, n1 | (type << 6));\n        } else if (n1 < 48 + (1 << 11)) {\n            n1 -= 48;\n            dbuf_putc(dbuf, ((n1 >> 8) + 48) | (type << 6));\n            dbuf_putc(dbuf, n1);\n        } else {\n            n1 -= 48 + (1 << 11);\n            assert(n1 < (1 << 20));\n            dbuf_putc(dbuf, ((n1 >> 16) + 56) | (type << 6));\n            dbuf_putc(dbuf, n1 >> 8);\n            dbuf_putc(dbuf, n1);\n        }\n        cw_len_tab[dbuf->size - cw_start - 1]++;\n        if (type == 0 || type == 1)\n            dbuf_putc(dbuf, cc);\n        cc_table_len++;\n        i += n;\n    }\n\n    /* last index entry */\n    v = i;\n    dbuf_putc(dbuf1, v);\n    dbuf_putc(dbuf1, v >> 8);\n    dbuf_putc(dbuf1, v >> 16);\n    \n    dump_byte_table(f, \"unicode_cc_table\", dbuf->buf, dbuf->size);\n    dump_byte_table(f, \"unicode_cc_index\", dbuf1->buf, dbuf1->size);\n\n#if defined(DUMP_CC_TABLE) || defined(DUMP_TABLE_SIZE)\n    printf(\"CC table: size=%d (%d entries) [\",\n           (int)(dbuf->size + dbuf1->size),\n           cc_table_len);\n    for(i = 0; i < countof(cw_len_tab); i++)\n        printf(\" %d\", cw_len_tab[i]);\n    printf(\" ]\\n\");\n#endif\n    dbuf_free(dbuf);\n    dbuf_free(dbuf1);\n}\n\n/* maximum length of decomposition: 18 chars (1), then 8 */\n#ifndef USE_TEST\ntypedef enum {\n    DECOMP_TYPE_C1, /* 16 bit char */\n    DECOMP_TYPE_L1, /* 16 bit char table */\n    DECOMP_TYPE_L2,\n    DECOMP_TYPE_L3,\n    DECOMP_TYPE_L4,\n    DECOMP_TYPE_L5, /* XXX: not used */\n    DECOMP_TYPE_L6, /* XXX: could remove */\n    DECOMP_TYPE_L7, /* XXX: could remove */\n    DECOMP_TYPE_LL1, /* 18 bit char table */\n    DECOMP_TYPE_LL2,\n    DECOMP_TYPE_S1, /* 8 bit char table */\n    DECOMP_TYPE_S2,\n    DECOMP_TYPE_S3,\n    DECOMP_TYPE_S4,\n    DECOMP_TYPE_S5,\n    DECOMP_TYPE_I1, /* increment 16 bit char value */\n    DECOMP_TYPE_I2_0,\n    DECOMP_TYPE_I2_1,\n    DECOMP_TYPE_I3_1,\n    DECOMP_TYPE_I3_2,\n    DECOMP_TYPE_I4_1,\n    DECOMP_TYPE_I4_2,\n    DECOMP_TYPE_B1, /* 16 bit base + 8 bit offset */\n    DECOMP_TYPE_B2,\n    DECOMP_TYPE_B3,\n    DECOMP_TYPE_B4,\n    DECOMP_TYPE_B5,\n    DECOMP_TYPE_B6,\n    DECOMP_TYPE_B7,\n    DECOMP_TYPE_B8,\n    DECOMP_TYPE_B18,\n    DECOMP_TYPE_LS2,\n    DECOMP_TYPE_PAT3,\n    DECOMP_TYPE_S2_UL,\n    DECOMP_TYPE_LS2_UL,\n} DecompTypeEnum;\n#endif\n\nconst char *decomp_type_str[] = {\n    \"C1\",\n    \"L1\",\n    \"L2\",\n    \"L3\",\n    \"L4\",\n    \"L5\",\n    \"L6\",\n    \"L7\",\n    \"LL1\",\n    \"LL2\",\n    \"S1\",\n    \"S2\",\n    \"S3\",\n    \"S4\",\n    \"S5\",\n    \"I1\",\n    \"I2_0\",\n    \"I2_1\",\n    \"I3_1\",\n    \"I3_2\",\n    \"I4_1\",\n    \"I4_2\",\n    \"B1\",\n    \"B2\",\n    \"B3\",\n    \"B4\",\n    \"B5\",\n    \"B6\",\n    \"B7\",\n    \"B8\",\n    \"B18\",\n    \"LS2\",\n    \"PAT3\",\n    \"S2_UL\",\n    \"LS2_UL\",\n};\n\nconst int decomp_incr_tab[4][4] = {\n    { DECOMP_TYPE_I1, 0, -1 },\n    { DECOMP_TYPE_I2_0, 0, 1, -1 },\n    { DECOMP_TYPE_I3_1, 1, 2, -1 },\n    { DECOMP_TYPE_I4_1, 1, 2, -1 },\n};\n\n/*\n  entry size:\n  type   bits\n  code   18 \n  len    7\n  compat 1\n  type   5\n  index  16\n  total  47\n*/\n\ntypedef struct {\n    int code;\n    uint8_t len;\n    uint8_t type;\n    uint8_t c_len;\n    uint16_t c_min;\n    uint16_t data_index;\n    int cost; /* size in bytes from this entry to the end */\n} DecompEntry;\n\nint get_decomp_run_size(const DecompEntry *de)\n{\n    int s;\n    s = 6;\n    if (de->type <= DECOMP_TYPE_C1) {\n        /* nothing more */\n    } else if (de->type <= DECOMP_TYPE_L7) {\n        s += de->len * de->c_len * 2;\n    } else if (de->type <= DECOMP_TYPE_LL2) {\n        /* 18 bits per char */\n        s += (de->len * de->c_len * 18 + 7) / 8;\n    } else if (de->type <= DECOMP_TYPE_S5) {\n        s += de->len * de->c_len;\n    } else if (de->type <= DECOMP_TYPE_I4_2) {\n        s += de->c_len * 2;\n    } else if (de->type <= DECOMP_TYPE_B18) {\n        s += 2 + de->len * de->c_len;\n    } else if (de->type <= DECOMP_TYPE_LS2) {\n        s += de->len * 3;\n    } else if (de->type <= DECOMP_TYPE_PAT3) {\n        s += 4 + de->len * 2;\n    } else if (de->type <= DECOMP_TYPE_S2_UL) {\n        s += de->len;\n    } else if (de->type <= DECOMP_TYPE_LS2_UL) {\n        s += (de->len / 2) * 3;\n    } else {\n        abort();\n    }\n    return s;\n}\n\nstatic const uint16_t unicode_short_table[2] = { 0x2044, 0x2215 };\n\n/* return -1 if not found */\nint get_short_code(int c)\n{\n    int i;\n    if (c < 0x80) {\n        return c;\n    } else if (c >= 0x300 && c < 0x350) {\n        return c - 0x300 + 0x80;\n    } else {\n        for(i = 0; i < countof(unicode_short_table); i++) {\n            if (c == unicode_short_table[i])\n                return i + 0x80 + 0x50;\n        }\n        return -1;\n    }\n}\n\nstatic BOOL is_short(int code)\n{\n    return get_short_code(code) >= 0;\n}\n\nstatic BOOL is_short_tab(const int *tab, int len)\n{\n    int i;\n    for(i = 0; i < len; i++) {\n        if (!is_short(tab[i]))\n            return FALSE;\n    }\n    return TRUE;\n}\n\nstatic BOOL is_16bit(const int *tab, int len)\n{\n    int i;\n    for(i = 0; i < len; i++) {\n        if (tab[i] > 0xffff)\n            return FALSE;\n    }\n    return TRUE;\n}\n\nstatic uint32_t to_lower_simple(uint32_t c)\n{\n    /* Latin1 and Cyrillic */\n    if (c < 0x100 || (c >= 0x410 && c <= 0x42f))\n        c += 0x20;\n    else\n        c++;\n    return c;\n}\n\n/* select best encoding with dynamic programming */\nvoid find_decomp_run(DecompEntry *tab_de, int i)\n{\n    DecompEntry de_s, *de = &de_s;\n    CCInfo *ci, *ci1, *ci2;\n    int l, j, n, len_max;\n    \n    ci = &unicode_db[i];\n    l = ci->decomp_len;\n    if (l == 0) {\n        tab_de[i].cost = tab_de[i + 1].cost;\n        return;\n    }\n\n    /* the offset for the compose table has only 6 bits, so we must\n       limit if it can be used by the compose table */\n    if (!ci->is_compat && !ci->is_excluded && l == 2)\n        len_max = 64; \n    else\n        len_max = 127;\n    \n    tab_de[i].cost = 0x7fffffff;\n    \n    if (!is_16bit(ci->decomp_data, l)) {\n        assert(l <= 2);\n\n        n = 1;\n        for(;;) {\n            de->code = i;\n            de->len = n;\n            de->type = DECOMP_TYPE_LL1 + l - 1;\n            de->c_len = l;\n            de->cost = get_decomp_run_size(de) + tab_de[i + n].cost;\n            if (de->cost < tab_de[i].cost) {\n                tab_de[i] = *de;\n            }\n            if (!((i + n) <= CHARCODE_MAX && n < len_max))\n                break;\n            ci1 = &unicode_db[i + n];\n            /* Note: we accept a hole */\n            if (!(ci1->decomp_len == 0 ||\n                  (ci1->decomp_len == l &&\n                   ci1->is_compat == ci->is_compat)))\n                break;\n            n++;\n        }\n        return;\n    }\n\n    if (l <= 7) {\n        n = 1;\n        for(;;) {\n            de->code = i;\n            de->len = n;\n            if (l == 1 && n == 1) {\n                de->type = DECOMP_TYPE_C1;\n            } else {\n                assert(l <= 8);\n                de->type = DECOMP_TYPE_L1 + l - 1;\n            }\n            de->c_len = l;\n            de->cost = get_decomp_run_size(de) + tab_de[i + n].cost;\n            if (de->cost < tab_de[i].cost) {\n                tab_de[i] = *de;\n            }\n            \n            if (!((i + n) <= CHARCODE_MAX && n < len_max))\n                break;\n            ci1 = &unicode_db[i + n];\n            /* Note: we accept a hole */\n            if (!(ci1->decomp_len == 0 ||\n                  (ci1->decomp_len == l &&\n                   ci1->is_compat == ci->is_compat &&\n                   is_16bit(ci1->decomp_data, l))))\n                break;\n            n++;\n        }\n    }\n    \n    if (l <= 8 || l == 18) {\n        int c_min, c_max, c;\n        c_min = c_max = -1;\n        n = 1;\n        for(;;) {\n            ci1 = &unicode_db[i + n - 1];\n            for(j = 0; j < l; j++) {\n                c = ci1->decomp_data[j];\n                if (c == 0x20) {\n                    /* we accept space for Arabic */\n                } else if (c_min == -1) {\n                    c_min = c_max = c;\n                } else {\n                    c_min = min_int(c_min, c);\n                    c_max = max_int(c_max, c);\n                }\n            }\n            if ((c_max - c_min) > 254)\n                break;\n            de->code = i;\n            de->len = n;\n            if (l == 18)\n                de->type = DECOMP_TYPE_B18;\n            else\n                de->type = DECOMP_TYPE_B1 + l - 1;\n            de->c_len = l;\n            de->c_min = c_min;\n            de->cost = get_decomp_run_size(de) + tab_de[i + n].cost;\n            if (de->cost < tab_de[i].cost) {\n                tab_de[i] = *de;\n            }\n            if (!((i + n) <= CHARCODE_MAX && n < len_max))\n                break;\n            ci1 = &unicode_db[i + n];\n            if (!(ci1->decomp_len == l &&\n                  ci1->is_compat == ci->is_compat))\n                break;\n            n++;\n        }\n    }\n\n    /* find an ascii run */\n    if (l <= 5 && is_short_tab(ci->decomp_data, l)) {\n        n = 1;\n        for(;;) {\n            de->code = i;\n            de->len = n;\n            de->type = DECOMP_TYPE_S1 + l - 1;\n            de->c_len = l;\n            de->cost = get_decomp_run_size(de) + tab_de[i + n].cost;\n            if (de->cost < tab_de[i].cost) {\n                tab_de[i] = *de;\n            }\n\n            if (!((i + n) <= CHARCODE_MAX && n < len_max))\n                break;\n            ci1 = &unicode_db[i + n];\n            /* Note: we accept a hole */\n            if (!(ci1->decomp_len == 0 ||\n                  (ci1->decomp_len == l &&\n                   ci1->is_compat == ci->is_compat &&\n                   is_short_tab(ci1->decomp_data, l))))\n                break;\n            n++;\n        }\n    }\n\n    /* check if a single char is increasing */\n    if (l <= 4) {\n        int idx1, idx;\n        \n        for(idx1 = 1; (idx = decomp_incr_tab[l - 1][idx1]) >= 0; idx1++) {\n            n = 1;\n            for(;;) {\n                de->code = i;\n                de->len = n;\n                de->type = decomp_incr_tab[l - 1][0] + idx1 - 1;\n                de->c_len = l;\n                de->cost = get_decomp_run_size(de) + tab_de[i + n].cost;\n                if (de->cost < tab_de[i].cost) {\n                    tab_de[i] = *de;\n                }\n\n                if (!((i + n) <= CHARCODE_MAX && n < len_max))\n                    break;\n                ci1 = &unicode_db[i + n];\n                if (!(ci1->decomp_len == l &&\n                      ci1->is_compat == ci->is_compat))\n                    goto next1;\n                for(j = 0; j < l; j++) {\n                    if (j == idx) {\n                        if (ci1->decomp_data[j] != ci->decomp_data[j] + n)\n                            goto next1;\n                    } else {\n                        if (ci1->decomp_data[j] != ci->decomp_data[j])\n                            goto next1;\n                    }\n                }\n                n++;\n            }\n        next1: ;\n        }\n    }\n\n    if (l == 3) {\n        n = 1;\n        for(;;) {\n            de->code = i;\n            de->len = n;\n            de->type = DECOMP_TYPE_PAT3;\n            de->c_len = l;\n            de->cost = get_decomp_run_size(de) + tab_de[i + n].cost;\n            if (de->cost < tab_de[i].cost) {\n                tab_de[i] = *de;\n            }\n            if (!((i + n) <= CHARCODE_MAX && n < len_max))\n                break;\n            ci1 = &unicode_db[i + n];\n            if (!(ci1->decomp_len == l &&\n                  ci1->is_compat == ci->is_compat &&\n                  ci1->decomp_data[1] <= 0xffff &&\n                  ci1->decomp_data[0] == ci->decomp_data[0] &&\n                  ci1->decomp_data[l - 1] == ci->decomp_data[l - 1]))\n                break;\n            n++;\n        }\n    }\n\n    if (l == 2 && is_short(ci->decomp_data[1])) {\n        n = 1;\n        for(;;) {\n            de->code = i;\n            de->len = n;\n            de->type = DECOMP_TYPE_LS2;\n            de->c_len = l;\n            de->cost = get_decomp_run_size(de) + tab_de[i + n].cost;\n            if (de->cost < tab_de[i].cost) {\n                tab_de[i] = *de;\n            }\n            if (!((i + n) <= CHARCODE_MAX && n < len_max))\n                break;\n            ci1 = &unicode_db[i + n];\n            if (!(ci1->decomp_len == 0 ||\n                  (ci1->decomp_len == l &&\n                   ci1->is_compat == ci->is_compat &&\n                   ci1->decomp_data[0] <= 0xffff &&\n                   is_short(ci1->decomp_data[1]))))\n                break;\n            n++;\n        }\n    }\n\n    if (l == 2) {\n        BOOL is_16bit;\n        \n        n = 0;\n        is_16bit = FALSE;\n        for(;;) {\n            if (!((i + n + 1) <= CHARCODE_MAX && n + 2 <= len_max))\n                break;\n            ci1 = &unicode_db[i + n];\n            if (!(ci1->decomp_len == l &&\n                  ci1->is_compat == ci->is_compat &&\n                  is_short(ci1->decomp_data[1])))\n                break;\n            if (!is_16bit && !is_short(ci1->decomp_data[0]))\n                is_16bit = TRUE;\n            ci2 = &unicode_db[i + n + 1];\n            if (!(ci2->decomp_len == l &&\n                  ci2->is_compat == ci->is_compat &&\n                  ci2->decomp_data[0] == to_lower_simple(ci1->decomp_data[0])  &&\n                  ci2->decomp_data[1] == ci1->decomp_data[1]))\n                break;\n            n += 2;\n            de->code = i;\n            de->len = n;\n            de->type = DECOMP_TYPE_S2_UL + is_16bit;\n            de->c_len = l;\n            de->cost = get_decomp_run_size(de) + tab_de[i + n].cost;\n            if (de->cost < tab_de[i].cost) {\n                tab_de[i] = *de;\n            }\n        }\n    }\n}\n\nvoid put16(uint8_t *data_buf, int *pidx, uint16_t c)\n{\n    int idx;\n    idx = *pidx;\n    data_buf[idx++] = c;\n    data_buf[idx++] = c >> 8;\n    *pidx = idx;\n}\n\nvoid add_decomp_data(uint8_t *data_buf, int *pidx, DecompEntry *de)\n{\n    int i, j, idx, c;\n    CCInfo *ci;\n    \n    idx = *pidx;\n    de->data_index = idx;\n    if (de->type <= DECOMP_TYPE_C1) {\n        ci = &unicode_db[de->code];\n        assert(ci->decomp_len == 1);\n        de->data_index = ci->decomp_data[0];\n    } else if (de->type <= DECOMP_TYPE_L7) {\n        for(i = 0; i < de->len; i++) {\n            ci = &unicode_db[de->code + i];\n            for(j = 0; j < de->c_len; j++) {\n                if (ci->decomp_len == 0)\n                    c = 0;\n                else\n                    c = ci->decomp_data[j];\n                put16(data_buf, &idx,  c);\n            }\n        }\n    } else if (de->type <= DECOMP_TYPE_LL2) {\n        int n, p, k;\n        n = (de->len * de->c_len * 18 + 7) / 8;\n        p = de->len * de->c_len * 2;\n        memset(data_buf + idx, 0, n);\n        k = 0;\n        for(i = 0; i < de->len; i++) {\n            ci = &unicode_db[de->code + i];\n            for(j = 0; j < de->c_len; j++) {\n                if (ci->decomp_len == 0)\n                    c = 0;\n                else\n                    c = ci->decomp_data[j];\n                data_buf[idx + k * 2] = c;\n                data_buf[idx + k * 2 + 1] = c >> 8;\n                data_buf[idx + p + (k / 4)] |= (c >> 16) << ((k % 4) * 2);\n                k++;\n            }\n        }\n        idx += n;\n    } else if (de->type <= DECOMP_TYPE_S5) {\n        for(i = 0; i < de->len; i++) {\n            ci = &unicode_db[de->code + i];\n            for(j = 0; j < de->c_len; j++) {\n                if (ci->decomp_len == 0)\n                    c = 0;\n                else\n                    c = ci->decomp_data[j];\n                c = get_short_code(c);\n                assert(c >= 0);\n                data_buf[idx++] = c;\n            }\n        }\n    } else if (de->type <= DECOMP_TYPE_I4_2) {\n        ci = &unicode_db[de->code];\n        assert(ci->decomp_len == de->c_len);\n        for(j = 0; j < de->c_len; j++)\n            put16(data_buf, &idx, ci->decomp_data[j]);\n    } else if (de->type <= DECOMP_TYPE_B18) {\n        c = de->c_min;\n        data_buf[idx++] = c;\n        data_buf[idx++] = c >> 8;\n        for(i = 0; i < de->len; i++) {\n            ci = &unicode_db[de->code + i];\n            for(j = 0; j < de->c_len; j++) {\n                assert(ci->decomp_len == de->c_len);\n                c = ci->decomp_data[j];\n                if (c == 0x20) {\n                    c = 0xff;\n                } else {\n                    c -= de->c_min;\n                    assert((uint32_t)c <= 254);\n                }\n                data_buf[idx++] = c;\n            }\n        }\n    } else if (de->type <= DECOMP_TYPE_LS2) {\n        assert(de->c_len == 2);\n        for(i = 0; i < de->len; i++) {\n            ci = &unicode_db[de->code + i];\n            if (ci->decomp_len == 0)\n                c = 0;\n            else\n                c = ci->decomp_data[0];\n            put16(data_buf, &idx,  c);\n\n            if (ci->decomp_len == 0)\n                c = 0;\n            else\n                c = ci->decomp_data[1];\n            c = get_short_code(c);\n            assert(c >= 0);\n            data_buf[idx++] = c;\n        }\n    } else if (de->type <= DECOMP_TYPE_PAT3) {\n        ci = &unicode_db[de->code];\n        assert(ci->decomp_len == 3);\n        put16(data_buf, &idx,  ci->decomp_data[0]);\n        put16(data_buf, &idx,  ci->decomp_data[2]);\n        for(i = 0; i < de->len; i++) {\n            ci = &unicode_db[de->code + i];\n            assert(ci->decomp_len == 3);\n            put16(data_buf, &idx,  ci->decomp_data[1]);\n        }\n    } else if (de->type <= DECOMP_TYPE_S2_UL) {\n        for(i = 0; i < de->len; i += 2) {\n            ci = &unicode_db[de->code + i];\n            c = ci->decomp_data[0];\n            c = get_short_code(c);\n            assert(c >= 0);\n            data_buf[idx++] = c;\n            c = ci->decomp_data[1];\n            c = get_short_code(c);\n            assert(c >= 0);\n            data_buf[idx++] = c;\n        }\n    } else if (de->type <= DECOMP_TYPE_LS2_UL) {\n        for(i = 0; i < de->len; i += 2) {\n            ci = &unicode_db[de->code + i];\n            c = ci->decomp_data[0];\n            put16(data_buf, &idx,  c);\n            c = ci->decomp_data[1];\n            c = get_short_code(c);\n            assert(c >= 0);\n            data_buf[idx++] = c;\n        }\n    } else {\n        abort();\n    }\n    *pidx = idx;\n}\n\n#if 0\nvoid dump_large_char(void)\n{\n    int i, j;\n    for(i = 0; i <= CHARCODE_MAX; i++) {\n        CCInfo *ci = &unicode_db[i];\n        for(j = 0; j < ci->decomp_len; j++) {\n            if (ci->decomp_data[j] > 0xffff)\n                printf(\"%05x\\n\", ci->decomp_data[j]);\n        }\n    }\n}\n#endif\n\nvoid build_compose_table(FILE *f, const DecompEntry *tab_de);\n\nvoid build_decompose_table(FILE *f)\n{\n    int i, array_len, code_max, data_len, count;\n    DecompEntry *tab_de, de_s, *de = &de_s;\n    uint8_t *data_buf;\n    \n    code_max = CHARCODE_MAX;\n    \n    tab_de = mallocz((code_max + 2) * sizeof(*tab_de));\n\n    for(i = code_max; i >= 0; i--) {\n        find_decomp_run(tab_de, i);\n    }\n\n    /* build the data buffer */\n    data_buf = malloc(100000);\n    data_len = 0;\n    array_len = 0;\n    for(i = 0; i <= code_max; i++) {\n        de = &tab_de[i];\n        if (de->len != 0) {\n            add_decomp_data(data_buf, &data_len, de);\n            i += de->len - 1;\n            array_len++;\n        }\n    }\n\n#ifdef DUMP_DECOMP_TABLE\n    /* dump */\n    {\n        int size, size1;\n        \n        printf(\"START LEN   TYPE  L C SIZE\\n\");\n        size = 0;\n        for(i = 0; i <= code_max; i++) {\n            de = &tab_de[i];\n            if (de->len != 0) {\n                size1 = get_decomp_run_size(de);\n                printf(\"%05x %3d %6s %2d %1d %4d\\n\", i, de->len,\n                       decomp_type_str[de->type], de->c_len,\n                       unicode_db[i].is_compat, size1);\n                i += de->len - 1;\n                size += size1;\n            }\n        }\n        \n        printf(\"array_len=%d estimated size=%d bytes actual=%d bytes\\n\",\n               array_len, size, array_len * 6 + data_len);\n    }\n#endif\n\n    fprintf(f, \"static const uint32_t unicode_decomp_table1[%u] = {\",\n            array_len);\n    count = 0;\n    for(i = 0; i <= code_max; i++) {\n        de = &tab_de[i];\n        if (de->len != 0) {\n            uint32_t v;\n            if (count++ % 4 == 0)\n                fprintf(f, \"\\n   \");\n            v = (de->code << (32 - 18)) |\n                (de->len << (32 - 18 - 7)) |\n                (de->type << (32 - 18 - 7 - 6)) |\n                unicode_db[de->code].is_compat;\n            fprintf(f, \" 0x%08x,\", v);\n            i += de->len - 1;\n        }\n    }\n    fprintf(f, \"\\n};\\n\\n\");\n\n    fprintf(f, \"static const uint16_t unicode_decomp_table2[%u] = {\",\n            array_len);\n    count = 0;\n    for(i = 0; i <= code_max; i++) {\n        de = &tab_de[i];\n        if (de->len != 0) {\n            if (count++ % 8 == 0)\n                fprintf(f, \"\\n   \");\n            fprintf(f, \" 0x%04x,\", de->data_index);\n            i += de->len - 1;\n        }\n    }\n    fprintf(f, \"\\n};\\n\\n\");\n    \n    fprintf(f, \"static const uint8_t unicode_decomp_data[%u] = {\",\n            data_len);\n    for(i = 0; i < data_len; i++) {\n        if (i % 8 == 0)\n            fprintf(f, \"\\n   \");\n        fprintf(f, \" 0x%02x,\", data_buf[i]);\n    }\n    fprintf(f, \"\\n};\\n\\n\");\n\n    build_compose_table(f, tab_de);\n\n    free(data_buf);\n    \n    free(tab_de);\n}\n\ntypedef struct {\n    uint32_t c[2];\n    uint32_t p;\n} ComposeEntry;\n\n#define COMPOSE_LEN_MAX 10000\n\nstatic int ce_cmp(const void *p1, const void *p2)\n{\n    const ComposeEntry *ce1 = p1;\n    const ComposeEntry *ce2 = p2;\n    int i;\n\n    for(i = 0; i < 2; i++) {\n        if (ce1->c[i] < ce2->c[i])\n            return -1;\n        else if (ce1->c[i] > ce2->c[i])\n            return 1;\n    }\n    return 0;\n}\n\n\nstatic int get_decomp_pos(const DecompEntry *tab_de, int c)\n{\n    int i, v, k;\n    const DecompEntry *de;\n    \n    k = 0;\n    for(i = 0; i <= CHARCODE_MAX; i++) {\n        de = &tab_de[i];\n        if (de->len != 0) {\n            if (c >= de->code && c < de->code + de->len) {\n                v = c - de->code;\n                assert(v < 64);\n                v |= k << 6;\n                assert(v < 65536);\n                return v;\n            }\n            i += de->len - 1;\n            k++;\n        }\n    }\n    return -1;\n}\n\nvoid build_compose_table(FILE *f, const DecompEntry *tab_de)\n{\n    int i, v, tab_ce_len;\n    ComposeEntry *ce, *tab_ce;\n    \n    tab_ce = malloc(sizeof(*tab_ce) * COMPOSE_LEN_MAX);\n    tab_ce_len = 0;\n    for(i = 0; i <= CHARCODE_MAX; i++) {\n        CCInfo *ci = &unicode_db[i];\n        if (ci->decomp_len == 2 && !ci->is_compat &&\n            !ci->is_excluded) {\n            assert(tab_ce_len < COMPOSE_LEN_MAX); \n            ce = &tab_ce[tab_ce_len++];\n            ce->c[0] = ci->decomp_data[0];\n            ce->c[1] = ci->decomp_data[1];\n            ce->p = i;\n        }\n    }\n    qsort(tab_ce, tab_ce_len, sizeof(*tab_ce), ce_cmp);\n\n#if 0\n    {\n        printf(\"tab_ce_len=%d\\n\", tab_ce_len);\n        for(i = 0; i < tab_ce_len; i++) {\n            ce = &tab_ce[i];\n            printf(\"%05x %05x %05x\\n\", ce->c[0], ce->c[1], ce->p);\n        }\n    }\n#endif\n    \n    fprintf(f, \"static const uint16_t unicode_comp_table[%u] = {\",\n            tab_ce_len);\n    for(i = 0; i < tab_ce_len; i++) {\n        if (i % 8 == 0)\n            fprintf(f, \"\\n   \");\n        v = get_decomp_pos(tab_de, tab_ce[i].p);\n        if (v < 0) {\n            printf(\"ERROR: entry for c=%04x not found\\n\",\n                   tab_ce[i].p);\n            exit(1);\n        }\n        fprintf(f, \" 0x%04x,\", v);\n    }\n    fprintf(f, \"\\n};\\n\\n\");\n    \n    free(tab_ce);\n}\n\n#ifdef USE_TEST\nvoid check_decompose_table(void)\n{\n    int c;\n    CCInfo *ci;\n    int res[UNICODE_DECOMP_LEN_MAX], *ref;\n    int len, ref_len, is_compat;\n\n    for(is_compat = 0; is_compat <= 1; is_compat++) {\n        for(c = 0; c < CHARCODE_MAX; c++) {\n            ci = &unicode_db[c];\n            ref_len = ci->decomp_len;\n            ref = ci->decomp_data;\n            if (!is_compat && ci->is_compat) {\n                ref_len = 0;\n            }\n            len = unicode_decomp_char((uint32_t *)res, c, is_compat);\n            if (len != ref_len ||\n                tabcmp(res, ref, ref_len) != 0) {\n                printf(\"ERROR c=%05x compat=%d\\n\", c, is_compat);\n                dump_str(\"res\", res, len);\n                dump_str(\"ref\", ref, ref_len);\n                exit(1);\n            }\n        }\n    }\n}\n\nvoid check_compose_table(void)\n{\n    int i, p;\n    /* XXX: we don't test all the cases */\n\n    for(i = 0; i <= CHARCODE_MAX; i++) {\n        CCInfo *ci = &unicode_db[i];\n        if (ci->decomp_len == 2 && !ci->is_compat &&\n            !ci->is_excluded) {\n            p = unicode_compose_pair(ci->decomp_data[0], ci->decomp_data[1]);\n            if (p != i) {\n                printf(\"ERROR compose: c=%05x %05x -> %05x ref=%05x\\n\",\n                       ci->decomp_data[0], ci->decomp_data[1], p, i);\n                exit(1);\n            }\n        }\n    }\n    \n\n\n}\n\n#endif\n\n\n\n#ifdef USE_TEST\n\nvoid check_str(const char *msg, int num, const int *in_buf, int in_len,\n               const int *buf1, int len1,\n               const int *buf2, int len2)\n{\n    if (len1 != len2 || tabcmp(buf1, buf2, len1) != 0) {\n        printf(\"%d: ERROR %s:\\n\", num, msg);\n        dump_str(\" in\", in_buf, in_len);\n        dump_str(\"res\", buf1, len1);\n        dump_str(\"ref\", buf2, len2);\n        exit(1);\n    }\n}\n\nvoid check_cc_table(void)\n{\n    int cc, cc_ref, c;\n\n    for(c = 0; c <= CHARCODE_MAX; c++) {\n        cc_ref = unicode_db[c].combining_class;\n        cc = unicode_get_cc(c);\n        if (cc != cc_ref) {\n            printf(\"ERROR: c=%04x cc=%d cc_ref=%d\\n\",\n                   c, cc, cc_ref);\n            exit(1);\n        }\n    }\n#ifdef PROFILE\n    {\n        int64_t ti, count;\n    \n        ti = get_time_ns();\n        count = 0;\n        /* only do it on meaningful chars */\n        for(c = 0x20; c <= 0xffff; c++) {\n            cc_ref = unicode_db[c].combining_class;\n            cc = unicode_get_cc(c);\n            count++;\n        }\n        ti = get_time_ns() - ti;\n        printf(\"cc time=%0.1f ns/char\\n\",\n               (double)ti / count);\n    }\n#endif\n}\n\nvoid normalization_test(const char *filename)\n{\n    FILE *f;\n    char line[4096], *p;\n    int *in_str, *nfc_str, *nfd_str, *nfkc_str, *nfkd_str;\n    int in_len, nfc_len, nfd_len, nfkc_len, nfkd_len;\n    int *buf, buf_len, pos;\n    \n    f = fopen(filename, \"rb\");\n    if (!f) {\n        perror(filename);\n        exit(1);\n    }\n    pos = 0;\n    for(;;) {\n        if (!get_line(line, sizeof(line), f))\n            break;\n        pos++;\n        p = line;\n        while (isspace(*p))\n            p++;\n        if (*p == '#' || *p == '@')\n            continue;\n        in_str = get_field_str(&in_len, p, 0);\n        nfc_str = get_field_str(&nfc_len, p, 1);\n        nfd_str = get_field_str(&nfd_len, p, 2);\n        nfkc_str = get_field_str(&nfkc_len, p, 3);\n        nfkd_str = get_field_str(&nfkd_len, p, 4);\n\n        //        dump_str(\"in\", in_str, in_len);\n\n        buf_len = unicode_normalize((uint32_t **)&buf, (uint32_t *)in_str, in_len, UNICODE_NFD, NULL, NULL);\n        check_str(\"nfd\", pos, in_str, in_len, buf, buf_len, nfd_str, nfd_len);\n        free(buf);\n\n        buf_len = unicode_normalize((uint32_t **)&buf, (uint32_t *)in_str, in_len, UNICODE_NFKD, NULL, NULL);\n        check_str(\"nfkd\", pos, in_str, in_len, buf, buf_len, nfkd_str, nfkd_len);\n        free(buf);\n        \n        buf_len = unicode_normalize((uint32_t **)&buf, (uint32_t *)in_str, in_len, UNICODE_NFC, NULL, NULL);\n        check_str(\"nfc\", pos, in_str, in_len, buf, buf_len, nfc_str, nfc_len);\n        free(buf);\n\n        buf_len = unicode_normalize((uint32_t **)&buf, (uint32_t *)in_str, in_len, UNICODE_NFKC, NULL, NULL);\n        check_str(\"nfkc\", pos, in_str, in_len, buf, buf_len, nfkc_str, nfkc_len);\n        free(buf);\n\n        free(in_str);\n        free(nfc_str);\n        free(nfd_str);\n        free(nfkc_str);\n        free(nfkd_str);\n    }\n    fclose(f);\n}\n#endif\n\nint main(int argc, char **argv)\n{\n    const char *unicode_db_path, *outfilename;\n    char filename[1024];\n    \n    if (argc < 2) {\n        printf(\"usage: %s unicode_db_path [output_file]\\n\"\n               \"\\n\"\n               \"If no output_file is given, a self test is done using the current unicode library\\n\",\n               argv[0]);\n        exit(1);\n    }\n    unicode_db_path = argv[1];\n    outfilename = NULL;\n    if (argc >= 3)\n        outfilename = argv[2];\n\n    unicode_db = mallocz(sizeof(unicode_db[0]) * (CHARCODE_MAX + 1));\n\n    snprintf(filename, sizeof(filename), \"%s/UnicodeData.txt\", unicode_db_path);\n\n    parse_unicode_data(filename);\n\n    snprintf(filename, sizeof(filename), \"%s/SpecialCasing.txt\", unicode_db_path);\n    parse_special_casing(unicode_db, filename);\n    \n    snprintf(filename, sizeof(filename), \"%s/CaseFolding.txt\", unicode_db_path);\n    parse_case_folding(unicode_db, filename);\n\n    snprintf(filename, sizeof(filename), \"%s/CompositionExclusions.txt\", unicode_db_path);\n    parse_composition_exclusions(filename);\n    \n    snprintf(filename, sizeof(filename), \"%s/DerivedCoreProperties.txt\", unicode_db_path);\n    parse_derived_core_properties(filename);\n\n    snprintf(filename, sizeof(filename), \"%s/DerivedNormalizationProps.txt\", unicode_db_path);\n    parse_derived_norm_properties(filename);\n\n    snprintf(filename, sizeof(filename), \"%s/PropList.txt\", unicode_db_path);\n    parse_prop_list(filename);\n\n    snprintf(filename, sizeof(filename), \"%s/Scripts.txt\", unicode_db_path);\n    parse_scripts(filename);\n\n    snprintf(filename, sizeof(filename), \"%s/ScriptExtensions.txt\",\n             unicode_db_path);\n    parse_script_extensions(filename);\n                        \n    snprintf(filename, sizeof(filename), \"%s/emoji-data.txt\",\n             unicode_db_path);\n    parse_prop_list(filename);\n\n    //    dump_data(unicode_db);\n\n    build_conv_table(unicode_db);\n    \n    //    dump_table();\n\n    if (!outfilename) {\n#ifdef USE_TEST\n        check_case_conv();\n        check_flags();\n        check_decompose_table();\n        check_compose_table();\n        check_cc_table();\n        snprintf(filename, sizeof(filename), \"%s/NormalizationTest.txt\", unicode_db_path);\n        normalization_test(filename);\n#else\n        fprintf(stderr, \"Tests are not compiled\\n\");\n        exit(1);\n#endif\n    } else\n    {\n        FILE *fo = fopen(outfilename, \"wb\");\n        \n        if (!fo) {\n            perror(outfilename);\n            exit(1);\n        }\n        fprintf(fo,\n                \"/* Compressed unicode tables */\\n\"\n                \"/* Automatically generated file - do not edit */\\n\"\n                \"\\n\"\n                \"#include <stdint.h>\\n\"\n                \"\\n\");\n        dump_case_conv_table(fo);\n        compute_internal_props();\n        build_flags_tables(fo);\n        fprintf(fo, \"#ifdef CONFIG_ALL_UNICODE\\n\\n\");\n        build_cc_table(fo);\n        build_decompose_table(fo);\n        build_general_category_table(fo);\n        build_script_table(fo);\n        build_script_ext_table(fo);\n        build_prop_list_table(fo);\n        fprintf(fo, \"#endif /* CONFIG_ALL_UNICODE */\\n\");\n        fclose(fo);\n    }\n    return 0;\n}\n"
  },
  {
    "path": "jsb_build/quickjs/quickjs-wsa/unicode_gen_def.h",
    "content": "#ifdef UNICODE_GENERAL_CATEGORY\nDEF(Cn, \"Unassigned\") /* must be zero */\nDEF(Lu, \"Uppercase_Letter\")\nDEF(Ll, \"Lowercase_Letter\")\nDEF(Lt, \"Titlecase_Letter\")\nDEF(Lm, \"Modifier_Letter\")\nDEF(Lo, \"Other_Letter\")\nDEF(Mn, \"Nonspacing_Mark\")\nDEF(Mc, \"Spacing_Mark\")\nDEF(Me, \"Enclosing_Mark\")\nDEF(Nd, \"Decimal_Number,digit\")\nDEF(Nl, \"Letter_Number\")\nDEF(No, \"Other_Number\")\nDEF(Sm, \"Math_Symbol\")\nDEF(Sc, \"Currency_Symbol\")\nDEF(Sk, \"Modifier_Symbol\")\nDEF(So, \"Other_Symbol\")\nDEF(Pc, \"Connector_Punctuation\")\nDEF(Pd, \"Dash_Punctuation\")\nDEF(Ps, \"Open_Punctuation\")\nDEF(Pe, \"Close_Punctuation\")\nDEF(Pi, \"Initial_Punctuation\")\nDEF(Pf, \"Final_Punctuation\")\nDEF(Po, \"Other_Punctuation\")\nDEF(Zs, \"Space_Separator\")\nDEF(Zl, \"Line_Separator\")\nDEF(Zp, \"Paragraph_Separator\")\nDEF(Cc, \"Control,cntrl\")\nDEF(Cf, \"Format\")\nDEF(Cs, \"Surrogate\")\nDEF(Co, \"Private_Use\")\n/* synthetic properties */\nDEF(LC, \"Cased_Letter\")\nDEF(L, \"Letter\")\nDEF(M, \"Mark,Combining_Mark\")\nDEF(N, \"Number\")\nDEF(S, \"Symbol\")\nDEF(P, \"Punctuation,punct\")\nDEF(Z, \"Separator\")\nDEF(C, \"Other\")\n#endif\n\n#ifdef UNICODE_SCRIPT\n/* scripts aliases names in PropertyValueAliases.txt */\nDEF(Unknown, \"Zzzz\")\nDEF(Adlam, \"Adlm\")\nDEF(Ahom, \"Ahom\")\nDEF(Anatolian_Hieroglyphs, \"Hluw\")\nDEF(Arabic, \"Arab\")\nDEF(Armenian, \"Armn\")\nDEF(Avestan, \"Avst\")\nDEF(Balinese, \"Bali\")\nDEF(Bamum, \"Bamu\")\nDEF(Bassa_Vah, \"Bass\")\nDEF(Batak, \"Batk\")\nDEF(Bengali, \"Beng\")\nDEF(Bhaiksuki, \"Bhks\")\nDEF(Bopomofo, \"Bopo\")\nDEF(Brahmi, \"Brah\")\nDEF(Braille, \"Brai\")\nDEF(Buginese, \"Bugi\")\nDEF(Buhid, \"Buhd\")\nDEF(Canadian_Aboriginal, \"Cans\")\nDEF(Carian, \"Cari\")\nDEF(Caucasian_Albanian, \"Aghb\")\nDEF(Chakma, \"Cakm\")\nDEF(Cham, \"Cham\")\nDEF(Cherokee, \"Cher\")\nDEF(Chorasmian, \"Chrs\")\nDEF(Common, \"Zyyy\")\nDEF(Coptic, \"Copt,Qaac\")\nDEF(Cuneiform, \"Xsux\")\nDEF(Cypriot, \"Cprt\")\nDEF(Cyrillic, \"Cyrl\")\nDEF(Deseret, \"Dsrt\")\nDEF(Devanagari, \"Deva\")\nDEF(Dives_Akuru, \"Diak\")\nDEF(Dogra, \"Dogr\")\nDEF(Duployan, \"Dupl\")\nDEF(Egyptian_Hieroglyphs, \"Egyp\")\nDEF(Elbasan, \"Elba\")\nDEF(Elymaic, \"Elym\")\nDEF(Ethiopic, \"Ethi\")\nDEF(Georgian, \"Geor\")\nDEF(Glagolitic, \"Glag\")\nDEF(Gothic, \"Goth\")\nDEF(Grantha, \"Gran\")\nDEF(Greek, \"Grek\")\nDEF(Gujarati, \"Gujr\")\nDEF(Gunjala_Gondi, \"Gong\")\nDEF(Gurmukhi, \"Guru\")\nDEF(Han, \"Hani\")\nDEF(Hangul, \"Hang\")\nDEF(Hanifi_Rohingya, \"Rohg\")\nDEF(Hanunoo, \"Hano\")\nDEF(Hatran, \"Hatr\")\nDEF(Hebrew, \"Hebr\")\nDEF(Hiragana, \"Hira\")\nDEF(Imperial_Aramaic, \"Armi\")\nDEF(Inherited, \"Zinh,Qaai\")\nDEF(Inscriptional_Pahlavi, \"Phli\")\nDEF(Inscriptional_Parthian, \"Prti\")\nDEF(Javanese, \"Java\")\nDEF(Kaithi, \"Kthi\")\nDEF(Kannada, \"Knda\")\nDEF(Katakana, \"Kana\")\nDEF(Kayah_Li, \"Kali\")\nDEF(Kharoshthi, \"Khar\")\nDEF(Khmer, \"Khmr\")\nDEF(Khojki, \"Khoj\")\nDEF(Khitan_Small_Script, \"Kits\")\nDEF(Khudawadi, \"Sind\")\nDEF(Lao, \"Laoo\")\nDEF(Latin, \"Latn\")\nDEF(Lepcha, \"Lepc\")\nDEF(Limbu, \"Limb\")\nDEF(Linear_A, \"Lina\")\nDEF(Linear_B, \"Linb\")\nDEF(Lisu, \"Lisu\")\nDEF(Lycian, \"Lyci\")\nDEF(Lydian, \"Lydi\")\nDEF(Makasar, \"Maka\")\nDEF(Mahajani, \"Mahj\")\nDEF(Malayalam, \"Mlym\")\nDEF(Mandaic, \"Mand\")\nDEF(Manichaean, \"Mani\")\nDEF(Marchen, \"Marc\")\nDEF(Masaram_Gondi, \"Gonm\")\nDEF(Medefaidrin, \"Medf\")\nDEF(Meetei_Mayek, \"Mtei\")\nDEF(Mende_Kikakui, \"Mend\")\nDEF(Meroitic_Cursive, \"Merc\")\nDEF(Meroitic_Hieroglyphs, \"Mero\")\nDEF(Miao, \"Plrd\")\nDEF(Modi, \"Modi\")\nDEF(Mongolian, \"Mong\")\nDEF(Mro, \"Mroo\")\nDEF(Multani, \"Mult\")\nDEF(Myanmar, \"Mymr\")\nDEF(Nabataean, \"Nbat\")\nDEF(Nandinagari, \"Nand\")\nDEF(New_Tai_Lue, \"Talu\")\nDEF(Newa, \"Newa\")\nDEF(Nko, \"Nkoo\")\nDEF(Nushu, \"Nshu\")\nDEF(Nyiakeng_Puachue_Hmong, \"Hmnp\")\nDEF(Ogham, \"Ogam\")\nDEF(Ol_Chiki, \"Olck\")\nDEF(Old_Hungarian, \"Hung\")\nDEF(Old_Italic, \"Ital\")\nDEF(Old_North_Arabian, \"Narb\")\nDEF(Old_Permic, \"Perm\")\nDEF(Old_Persian, \"Xpeo\")\nDEF(Old_Sogdian, \"Sogo\")\nDEF(Old_South_Arabian, \"Sarb\")\nDEF(Old_Turkic, \"Orkh\")\nDEF(Oriya, \"Orya\")\nDEF(Osage, \"Osge\")\nDEF(Osmanya, \"Osma\")\nDEF(Pahawh_Hmong, \"Hmng\")\nDEF(Palmyrene, \"Palm\")\nDEF(Pau_Cin_Hau, \"Pauc\")\nDEF(Phags_Pa, \"Phag\")\nDEF(Phoenician, \"Phnx\")\nDEF(Psalter_Pahlavi, \"Phlp\")\nDEF(Rejang, \"Rjng\")\nDEF(Runic, \"Runr\")\nDEF(Samaritan, \"Samr\")\nDEF(Saurashtra, \"Saur\")\nDEF(Sharada, \"Shrd\")\nDEF(Shavian, \"Shaw\")\nDEF(Siddham, \"Sidd\")\nDEF(SignWriting, \"Sgnw\")\nDEF(Sinhala, \"Sinh\")\nDEF(Sogdian, \"Sogd\")\nDEF(Sora_Sompeng, \"Sora\")\nDEF(Soyombo, \"Soyo\")\nDEF(Sundanese, \"Sund\")\nDEF(Syloti_Nagri, \"Sylo\")\nDEF(Syriac, \"Syrc\")\nDEF(Tagalog, \"Tglg\")\nDEF(Tagbanwa, \"Tagb\")\nDEF(Tai_Le, \"Tale\")\nDEF(Tai_Tham, \"Lana\")\nDEF(Tai_Viet, \"Tavt\")\nDEF(Takri, \"Takr\")\nDEF(Tamil, \"Taml\")\nDEF(Tangut, \"Tang\")\nDEF(Telugu, \"Telu\")\nDEF(Thaana, \"Thaa\")\nDEF(Thai, \"Thai\")\nDEF(Tibetan, \"Tibt\")\nDEF(Tifinagh, \"Tfng\")\nDEF(Tirhuta, \"Tirh\")\nDEF(Ugaritic, \"Ugar\")\nDEF(Vai, \"Vaii\")\nDEF(Wancho, \"Wcho\")\nDEF(Warang_Citi, \"Wara\")\nDEF(Yezidi, \"Yezi\")\nDEF(Yi, \"Yiii\")\nDEF(Zanabazar_Square, \"Zanb\")\n#endif\n\n#ifdef UNICODE_PROP_LIST\n/* Prop list not exported to regexp */\nDEF(Hyphen, \"\")\nDEF(Other_Math, \"\")\nDEF(Other_Alphabetic, \"\")\nDEF(Other_Lowercase, \"\")\nDEF(Other_Uppercase, \"\")\nDEF(Other_Grapheme_Extend, \"\")\nDEF(Other_Default_Ignorable_Code_Point, \"\")\nDEF(Other_ID_Start, \"\")\nDEF(Other_ID_Continue, \"\")\nDEF(Prepended_Concatenation_Mark, \"\")\n/* additional computed properties for smaller tables */\nDEF(ID_Continue1, \"\")\nDEF(XID_Start1, \"\")\nDEF(XID_Continue1, \"\")\nDEF(Changes_When_Titlecased1, \"\")\nDEF(Changes_When_Casefolded1, \"\")\nDEF(Changes_When_NFKC_Casefolded1, \"\")\n\n/* Prop list exported to JS */\nDEF(ASCII_Hex_Digit, \"AHex\")\nDEF(Bidi_Control, \"Bidi_C\")\nDEF(Dash, \"\")\nDEF(Deprecated, \"Dep\")\nDEF(Diacritic, \"Dia\")\nDEF(Extender, \"Ext\")\nDEF(Hex_Digit, \"Hex\")\nDEF(IDS_Binary_Operator, \"IDSB\")\nDEF(IDS_Trinary_Operator, \"IDST\")\nDEF(Ideographic, \"Ideo\")\nDEF(Join_Control, \"Join_C\")\nDEF(Logical_Order_Exception, \"LOE\")\nDEF(Noncharacter_Code_Point, \"NChar\")\nDEF(Pattern_Syntax, \"Pat_Syn\")\nDEF(Pattern_White_Space, \"Pat_WS\")\nDEF(Quotation_Mark, \"QMark\")\nDEF(Radical, \"\")\nDEF(Regional_Indicator, \"RI\")\nDEF(Sentence_Terminal, \"STerm\")\nDEF(Soft_Dotted, \"SD\")\nDEF(Terminal_Punctuation, \"Term\")\nDEF(Unified_Ideograph, \"UIdeo\")\nDEF(Variation_Selector, \"VS\")\nDEF(White_Space, \"space\")\nDEF(Bidi_Mirrored, \"Bidi_M\")\nDEF(Emoji, \"\")\nDEF(Emoji_Component, \"EComp\")\nDEF(Emoji_Modifier, \"EMod\")\nDEF(Emoji_Modifier_Base, \"EBase\")\nDEF(Emoji_Presentation, \"EPres\")\nDEF(Extended_Pictographic, \"ExtPict\")\nDEF(Default_Ignorable_Code_Point, \"DI\")\nDEF(ID_Start, \"IDS\")\nDEF(Case_Ignorable, \"CI\")\n\n/* other binary properties */\nDEF(ASCII,\"\")\nDEF(Alphabetic, \"Alpha\")\nDEF(Any, \"\")\nDEF(Assigned,\"\")\nDEF(Cased, \"\")\nDEF(Changes_When_Casefolded, \"CWCF\")\nDEF(Changes_When_Casemapped, \"CWCM\")\nDEF(Changes_When_Lowercased, \"CWL\")\nDEF(Changes_When_NFKC_Casefolded, \"CWKCF\")\nDEF(Changes_When_Titlecased, \"CWT\")\nDEF(Changes_When_Uppercased, \"CWU\")\nDEF(Grapheme_Base, \"Gr_Base\")\nDEF(Grapheme_Extend, \"Gr_Ext\")\nDEF(ID_Continue, \"IDC\")\nDEF(Lowercase, \"Lower\")\nDEF(Math, \"\")\nDEF(Uppercase, \"Upper\")\nDEF(XID_Continue, \"XIDC\")\nDEF(XID_Start, \"XIDS\")\n\n/* internal tables with index */\nDEF(Cased1, \"\")\n\n#endif\n"
  },
  {
    "path": "jsb_build/quickjs/unity_ext.c",
    "content": "\r\nJS_EXPORT JSValue jsb_crossbind_constructor(JSContext *ctx, JSValue new_target)\r\n{\r\n    JSValue proto = JS_GetProperty(ctx, new_target, JS_ATOM_prototype);\r\n    if (!JS_IsException(proto))\r\n    {\r\n        JSValue val = JS_NewObjectProtoClass(ctx, proto, js_bridge_class_id);\r\n        JS_FreeValue(ctx, proto);\r\n        return val;\r\n    }\r\n\r\n    return proto;\r\n}\r\n\r\nJS_EXPORT JSValue jsb_construct_bridge_object(JSContext *ctx, JSValue proto, int32_t object_id)\r\n{\r\n    JSValue obj = JS_CallConstructor(ctx, proto, 0, NULL);\r\n    if (!JS_IsException(obj))\r\n    {\r\n        JSPayload *sv = (JSPayload *)js_malloc(ctx, sizeof(JSPayloadHeader));\r\n        sv->header.type_id = JS_BO_OBJECT;\r\n        sv->header.value = object_id;\r\n        JSB_SetOpaque(ctx, obj, sv);\r\n    }\r\n\r\n    return obj;\r\n}\r\n\r\nJS_EXPORT JSValue jsb_new_bridge_object(JSContext *ctx, JSValue proto, int32_t object_id/*, int32_t type_id = JS_BO_OBJECT */)\r\n{\r\n    JSValue obj = JS_NewObjectProtoClass(ctx, proto, js_bridge_class_id);\r\n    if (!JS_IsException(obj))\r\n    {\r\n        JSPayload *sv = (JSPayload *)js_malloc(ctx, sizeof(JSPayloadHeader));\r\n        sv->header.type_id = JS_BO_OBJECT;\r\n        sv->header.value = object_id;\r\n        JSB_SetOpaque(ctx, obj, sv);\r\n    }\r\n\r\n    return obj;\r\n}\r\n\r\n// for constructor new_target\r\nJS_EXPORT JSValue JSB_NewBridgeClassObject(JSContext *ctx, JSValue new_target, int32_t object_id/*, int32_t type_id = JS_BO_OBJECT */)\r\n{\r\n    JSValue proto = JS_GetProperty(ctx, new_target, JS_ATOM_prototype);\r\n    if (!JS_IsException(proto))\r\n    {\r\n        JSValue obj = jsb_new_bridge_object(ctx, proto, object_id/*, type_id*/);\r\n        JS_FreeValue(ctx, proto);\r\n        return obj;\r\n    }\r\n\r\n    return proto;\r\n}\r\n\r\nJS_EXPORT JSValue jsb_new_bridge_value(JSContext *ctx, JSValue proto, int32_t size)\r\n{\r\n    JSValue obj = JS_NewObjectProtoClass(ctx, proto, js_bridge_class_id);\r\n    if (!JS_IsException(obj))\r\n    {\r\n        JSPayload *sv = (JSPayload *)js_mallocz(ctx, sizeof(JSPayloadHeader) + size);\r\n        sv->header.type_id = JS_BO_VALUE;\r\n        sv->header.value = size;\r\n        JSB_SetOpaque(ctx, obj, sv);\r\n    }\r\n\r\n    return obj;\r\n}\r\n\r\nJS_EXPORT JSValue JSB_NewBridgeClassValue(JSContext *ctx, JSValue new_target, int32_t size)\r\n{\r\n    JSValue proto = JS_GetProperty(ctx, new_target, JS_ATOM_prototype);\r\n    if (!JS_IsException(proto))\r\n    {\r\n        JSValue obj = jsb_new_bridge_value(ctx, proto, size);\r\n        JS_FreeValue(ctx, proto);\r\n        return obj;\r\n    }\r\n\r\n    return proto;\r\n}\r\n\r\nJS_EXPORT JSPayloadHeader jsb_get_payload_header(JSContext *ctx, JSValue val)\r\n{\r\n    JSPayloadHeader *sv = (JSPayloadHeader *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv)\r\n    {\r\n        return *sv;\r\n    }\r\n    return _null_payload;\r\n}\r\n\r\nJS_EXPORT JSPayload *jsb_get_payload(JSContext *ctx, JSValue val)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv)\r\n    {\r\n        return sv;\r\n    }\r\n    return 0;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_floats(JSContext *ctx, JSValue val, int n, float *v0)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(float) * n)\r\n    {\r\n        float *ptr = (float *)&(sv->data[0]);\r\n        for (int i = 0; i < n; ++i)\r\n        {\r\n            *(v0 + i) = ptr[i];\r\n        }\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_floats(JSContext *ctx, JSValue val, int n, float *v0)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(float) * n)\r\n    {\r\n        float *ptr = (float *)&(sv->data[0]);\r\n        for (int i = 0; i < n; ++i)\r\n        {\r\n            ptr[i] = *(v0 + i);\r\n        }\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_float_2(JSContext *ctx, JSValue val, float *v0, float *v1)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(float) * 2)\r\n    {\r\n        float *ptr = (float *)&(sv->data[0]);\r\n        *v0 = ptr[0];\r\n        *v1 = ptr[1];\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_float_2(JSContext *ctx, JSValue val, float v0, float v1)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(float) * 2)\r\n    {\r\n        float *ptr = (float *)&(sv->data[0]);\r\n        ptr[0] = v0;\r\n        ptr[1] = v1;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_float_3(JSContext *ctx, JSValue val, float *v0, float *v1, float *v2)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(float) * 3)\r\n    {\r\n        float *ptr = (float *)&(sv->data[0]);\r\n        *v0 = ptr[0];\r\n        *v1 = ptr[1];\r\n        *v2 = ptr[2];\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_float_3(JSContext *ctx, JSValue val, float v0, float v1, float v2)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(float) * 3)\r\n    {\r\n        float *ptr = (float *)&(sv->data[0]);\r\n        ptr[0] = v0;\r\n        ptr[1] = v1;\r\n        ptr[2] = v2;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_float_4(JSContext *ctx, JSValue val, float *v0, float *v1, float *v2, float *v3)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(float) * 4)\r\n    {\r\n        float *ptr = (float *)&(sv->data[0]);\r\n        *v0 = ptr[0];\r\n        *v1 = ptr[1];\r\n        *v2 = ptr[2];\r\n        *v3 = ptr[3];\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_float_4(JSContext *ctx, JSValue val, float v0, float v1, float v2, float v3)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(float) * 4)\r\n    {\r\n        float *ptr = (float *)&(sv->data[0]);\r\n        ptr[0] = v0;\r\n        ptr[1] = v1;\r\n        ptr[2] = v2;\r\n        ptr[3] = v3;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_ints(JSContext *ctx, JSValue val, int n, int *v0)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int) * n)\r\n    {\r\n        int *ptr = (int *)&(sv->data[0]);\r\n        for (int i = 0; i < n; ++i)\r\n        {\r\n            *(v0 + i) = ptr[i];\r\n        }\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_ints(JSContext *ctx, JSValue val, int n, int *v0)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int) * n)\r\n    {\r\n        int *ptr = (int *)&(sv->data[0]);\r\n        for (int i = 0; i < n; ++i)\r\n        {\r\n            ptr[i] = *(v0 + i);\r\n        }\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_int_1(JSContext *ctx, JSValue val, int *v0)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int))\r\n    {\r\n        int *ptr = (int *)&(sv->data[0]);\r\n        *v0 = ptr[0];\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_int_1(JSContext *ctx, JSValue val, int v0)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int))\r\n    {\r\n        int *ptr = (int *)&(sv->data[0]);\r\n        ptr[0] = v0;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_int_2(JSContext *ctx, JSValue val, int *v0, int *v1)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int) * 2)\r\n    {\r\n        int *ptr = (int *)&(sv->data[0]);\r\n        *v0 = ptr[0];\r\n        *v1 = ptr[1];\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_int_2(JSContext *ctx, JSValue val, int v0, int v1)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int) * 2)\r\n    {\r\n        int *ptr = (int *)&(sv->data[0]);\r\n        ptr[0] = v0;\r\n        ptr[1] = v1;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_int_3(JSContext *ctx, JSValue val, int *v0, int *v1, int *v2)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int) * 3)\r\n    {\r\n        int *ptr = (int *)&(sv->data[0]);\r\n        *v0 = ptr[0];\r\n        *v1 = ptr[1];\r\n        *v2 = ptr[2];\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_int_3(JSContext *ctx, JSValue val, int v0, int v1, int v2)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int) * 3)\r\n    {\r\n        int *ptr = (int *)&(sv->data[0]);\r\n        ptr[0] = v0;\r\n        ptr[1] = v1;\r\n        ptr[2] = v2;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_int_4(JSContext *ctx, JSValue val, int *v0, int *v1, int *v2, int *v3)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int) * 4)\r\n    {\r\n        int *ptr = (int *)&(sv->data[0]);\r\n        *v0 = ptr[0];\r\n        *v1 = ptr[1];\r\n        *v2 = ptr[2];\r\n        *v3 = ptr[3];\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_int_4(JSContext *ctx, JSValue val, int v0, int v1, int v2, int v3)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int) * 4)\r\n    {\r\n        int *ptr = (int *)&(sv->data[0]);\r\n        ptr[0] = v0;\r\n        ptr[1] = v1;\r\n        ptr[2] = v2;\r\n        ptr[3] = v3;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_bytes(JSContext *ctx, JSValue val, int n, byte *v0)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(byte) * n)\r\n    {\r\n        byte *ptr = (byte *)&(sv->data[0]);\r\n        for (int i = 0; i < n; ++i)\r\n        {\r\n            *(v0 + i) = ptr[i];\r\n        }\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_bytes(JSContext *ctx, JSValue val, int n, byte *v0)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(byte) * n)\r\n    {\r\n        byte *ptr = (byte *)&(sv->data[0]);\r\n        for (int i = 0; i < n; ++i)\r\n        {\r\n            ptr[i] = *(v0 + i);\r\n        }\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_byte_4(JSContext *ctx, JSValue val, byte *v0, byte *v1, byte *v2, byte *v3)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(byte) * 4)\r\n    {\r\n        byte *ptr = (byte *)&(sv->data[0]);\r\n        *v0 = ptr[0];\r\n        *v1 = ptr[1];\r\n        *v2 = ptr[2];\r\n        *v3 = ptr[3];\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_byte_4(JSContext *ctx, JSValue val, byte v0, byte v1, byte v2, byte v3)\r\n{\r\n    JSPayload *sv = (JSPayload *)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(byte) * 4)\r\n    {\r\n        byte *ptr = (byte *)&(sv->data[0]);\r\n        ptr[0] = v0;\r\n        ptr[1] = v1;\r\n        ptr[2] = v2;\r\n        ptr[3] = v3;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n"
  },
  {
    "path": "jsb_build/quickjs/unity_qjs.c",
    "content": "/*\r\nvim /etc/apt/sources.list\r\ndeb http://us.archive.ubuntu.com/ubuntu trusty main universe\r\nsudo apt-get update\r\nsudo apt-get install mingw32\r\n    sudo apt-get install mingw-w64\r\n./configure --host=i686-w64-mingw32\r\n    ./configure --host=x86_64-w64-mingw32\r\nmake\r\n*/\r\n\r\n#ifndef UNITY_WEBGL\r\n#include \"quickjs.h\"\r\n#endif\r\n\r\n#ifndef JS_EXPORT\r\n#define JS_EXPORT\r\n#endif\r\n\r\n#ifndef EMSCRIPTEN\r\n#ifndef CONFIG_ATOMICS\r\n#define CONFIG_ATOMICS\r\n#endif\r\n#endif\r\n\r\n#define byte unsigned char\r\n// #define JS_HIDDEN_PROP(s) (\"\\xFF\" s)\r\n\r\n#ifndef UNITY_WEBGL\r\n\r\n#ifndef FALSE\r\nenum\r\n{\r\n    FALSE = 0,\r\n    TRUE = 1,\r\n};\r\n#endif // !FALSE\r\n\r\nenum\r\n{\r\n    __JS_ATOM_NULL = JS_ATOM_NULL,\r\n#define DEF(name, str) JS_ATOM_##name,\r\n#define SSR\r\n#include \"quickjs-atom.h\"\r\n#undef DEF\r\n    JS_ATOM_END,\r\n};\r\n\r\n#define DEF(name, str) \\\r\n    JS_EXPORT JSAtom JSB_ATOM_##name() { return JS_ATOM_##name; }\r\n#include \"quickjs-atom.h\"\r\n#undef DEF\r\n\r\n#endif // !UNITY_WEBGL\r\n\r\nstatic JSClassID js_class_id_begin = 0;\r\nstatic JSClassID js_bridge_class_id = 0;\r\n\r\n// quickjs 内置 class id 之后的第一个可用 id\r\nJS_EXPORT JSClassID JSB_GetClassID()\r\n{\r\n    return js_class_id_begin;\r\n}\r\n\r\nJS_EXPORT JSClassID JSB_GetBridgeClassID()\r\n{\r\n    return js_bridge_class_id;\r\n}\r\n\r\n#define JS_BO_TYPE 1\r\n#define JS_BO_OBJECT 2\r\n#define JS_BO_VALUE 3\r\n// #define JS_BO_STRICT_OBJECT 4\r\n\r\ntypedef struct JSPayloadHeader\r\n{\r\n    int32_t type_id; // JS_BO_*\r\n    int32_t value;\r\n} JSPayloadHeader;\r\n\r\nstatic JSPayloadHeader _null_payload = {.type_id = 0, .value = 0};\r\n\r\ntypedef struct JSPayload\r\n{\r\n    JSPayloadHeader header;\r\n    char data[1];\r\n} JSPayload;\r\n\r\nJS_EXPORT JSValue JSB_NewEmptyString(JSContext *ctx)\r\n{\r\n    return JS_NewStringLen(ctx, \"\", 0);\r\n}\r\n\r\nJS_EXPORT JSValue JSB_NewInt64(JSContext *ctx, int64_t val)\r\n{\r\n    return JS_NewInt64(ctx, val);\r\n}\r\n\r\n/* return 0 for success, otherwise -1 in case of exception */\r\nJS_EXPORT int JSB_ToUint32(JSContext *ctx, uint32_t *pres, JSValueConst val)\r\n{\r\n    return JS_ToInt32(ctx, (int32_t *)pres, val);\r\n}\r\n\r\nJS_EXPORT JSValue JSB_NewFloat64(JSContext *ctx, double d)\r\n{\r\n    return JS_NewFloat64(ctx, d);\r\n}\r\n\r\nJS_EXPORT JSValue JSB_ThrowTypeError(JSContext *ctx, const char *msg)\r\n{\r\n    return JS_ThrowTypeError(ctx, \"%s\", msg);\r\n}\r\n\r\nJS_EXPORT JSValue JSB_ThrowInternalError(JSContext *ctx, const char *msg)\r\n{\r\n    return JS_ThrowInternalError(ctx, \"%s\", msg);\r\n}\r\n\r\nJS_EXPORT JSValue JSB_ThrowRangeError(JSContext *ctx, const char *msg)\r\n{\r\n    return JS_ThrowRangeError(ctx, \"%s\", msg);\r\n}\r\n\r\nJS_EXPORT JSValue JSB_ThrowReferenceError(JSContext *ctx, const char *msg)\r\n{\r\n    return JS_ThrowReferenceError(ctx, \"%s\", msg);\r\n}\r\n\r\nJS_EXPORT void JSB_FreeValue(JSContext *ctx, JSValue v)\r\n{\r\n    JS_FreeValue(ctx, v);\r\n}\r\n\r\nJS_EXPORT void JSB_FreeValueRT(JSRuntime *rt, JSValue v)\r\n{\r\n    JS_FreeValueRT(rt, v);\r\n}\r\n\r\nJS_EXPORT JSValue JSB_DupValue(JSContext *ctx, JSValueConst v)\r\n{\r\n    return JS_DupValue(ctx, v);\r\n}\r\n\r\nJS_EXPORT JSValue JSB_Eval(JSContext *ctx, const char *input, int input_len,\r\n                 const char *filename, int eval_flags)\r\n{\r\n    return JS_Eval(ctx, input, input_len, filename, eval_flags);\r\n}\r\n\r\nJS_EXPORT JSValue JSB_NewCFunction(JSContext *ctx, JSCFunction *func, JSAtom atom, int length, JSCFunctionEnum cproto, int magic)\r\n{\r\n    const char *name = JS_AtomToCString(ctx, atom);\r\n    if (!name)\r\n    {\r\n        return JS_ThrowInternalError(ctx, \"no such atom: %d\", atom);\r\n    }\r\n    JSValue funcVal = JS_NewCFunction2(ctx, func, name, length, cproto, magic);\r\n    JS_FreeCString(ctx, name);\r\n    return funcVal;\r\n}\r\n\r\nJS_EXPORT JSValue JSB_NewCFunctionMagic(JSContext *ctx, JSCFunctionMagic *func, JSAtom atom, int length, JSCFunctionEnum cproto, int magic)\r\n{\r\n    const char *name = JS_AtomToCString(ctx, atom);\r\n    if (!name)\r\n    {\r\n        return JS_ThrowInternalError(ctx, \"no such atom: %d\", atom);\r\n    }\r\n    JSValue funcVal = JS_NewCFunction2(ctx, (JSCFunction *)func, name, length, cproto, magic);\r\n    JS_FreeCString(ctx, name);\r\n    return funcVal;\r\n}\r\n\r\ntypedef void JSGCObjectFinalizer(JSRuntime* rt, JSPayloadHeader header);\r\n\r\ntypedef struct JSBRuntimePayload {\r\n    void* opaque;\r\n    JSGCObjectFinalizer* finalizer;\r\n} JSBRuntimePayload;\r\n\r\n// 释放数据, 返回头信息副本\r\nJS_EXPORT JSPayloadHeader JSB_FreePayload(JSContext *ctx, JSValue val)\r\n{\r\n    void *sv = JS_GetOpaque(val, js_bridge_class_id);\r\n    if (sv)\r\n    {\r\n        JSPayloadHeader header = *(JSPayloadHeader *)sv;\r\n        JS_SetOpaque(val, NULL);\r\n        js_free(ctx, sv);\r\n        return header;\r\n    }\r\n    return _null_payload;\r\n}\r\n\r\nstatic void _JSBClass_Finalizer(JSRuntime* rt, JSValue obj) \r\n{\r\n    void *sv = JS_GetOpaque(obj, js_bridge_class_id);\r\n    if (sv)\r\n    {\r\n        JSPayloadHeader header = *(JSPayloadHeader *)sv;\r\n        JS_SetOpaque(obj, NULL);\r\n        js_free_rt(rt, sv);\r\n        JSBRuntimePayload* rt_payload = (JSBRuntimePayload*)JS_GetRuntimeOpaque(rt);\r\n        if (rt_payload && rt_payload->finalizer)\r\n        {\r\n            rt_payload->finalizer(rt, header);\r\n        }\r\n    }\r\n}\r\n\r\nJS_EXPORT JSRuntime* JSB_NewRuntime(JSGCObjectFinalizer* finalizer)\r\n{\r\n    JSRuntime* rt = JS_NewRuntime();\r\n    JSBRuntimePayload* payload = js_malloc_rt(rt, sizeof(JSBRuntimePayload));\r\n    payload->opaque = 0;\r\n    payload->finalizer = finalizer;\r\n    JS_SetRuntimeOpaque(rt, payload);\r\n    \r\n    JSClassDef cls_def;\r\n\r\n    cls_def.class_name = \"CSharpClass\";\r\n    cls_def.finalizer = _JSBClass_Finalizer;\r\n    cls_def.exotic = NULL;\r\n    cls_def.gc_mark = NULL;\r\n    cls_def.call = NULL;\r\n\r\n    JS_NewClassID(&js_bridge_class_id);\r\n    JS_NewClass(rt, js_bridge_class_id, &cls_def);\r\n\r\n    return rt;\r\n}\r\n\r\nJS_EXPORT int JSB_FreeRuntime(JSRuntime* rt)\r\n{\r\n    void* payload = JS_GetRuntimeOpaque(rt);\r\n    if (payload)\r\n    {\r\n        JS_SetRuntimeOpaque(rt, 0);\r\n        js_free_rt(rt, payload);\r\n    }\r\n    return JS_FreeRuntime(rt);\r\n}\r\n\r\nJS_EXPORT void* JSB_GetRuntimeOpaque(JSRuntime* rt)\r\n{\r\n    JSBRuntimePayload* payload = (JSBRuntimePayload*)JS_GetRuntimeOpaque(rt);\r\n    return payload ? payload->opaque : 0;\r\n}\r\n\r\nJS_EXPORT void JSB_SetRuntimeOpaque(JSRuntime* rt, void* opaque)\r\n{\r\n    JSBRuntimePayload* payload = (JSBRuntimePayload*)JS_GetRuntimeOpaque(rt);\r\n    if (payload) \r\n    {\r\n        payload->opaque = opaque;\r\n    }\r\n}\r\n\r\n#define JSB_SetOpaque(ctx, obj, opaque) JS_SetOpaque((obj), (opaque))\r\n#define JSB_GetOpaque(ctx, val, class_id) JS_GetOpaque((val), (class_id))\r\n\r\nJS_EXPORT int JSB_Init()\r\n{\r\n    if (js_class_id_begin == 0)\r\n    {\r\n        JS_NewClassID(&js_bridge_class_id);\r\n        JS_NewClassID(&js_class_id_begin);\r\n    }\r\n\r\n    // 2020-12-02\r\n    return 0xa; // version tag for unity_qjs.c\r\n}\r\n\r\n#include \"unity_ext.c\"\r\n"
  },
  {
    "path": "jsb_build/sqlite3/CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.7.2)\r\nproject(sqlite3)\r\n\r\nset(TOP_DIR ${CMAKE_CURRENT_SOURCE_DIR})\r\nset(OUT_DIR ${TOP_DIR}/build)\r\n\r\nset(LIBSQLITE3_DIR ${TOP_DIR}/sqlite-amalgamation-3320300)\r\n\r\ninclude_directories(${LIBSQLITE3_DIR})\r\ninclude_directories(${TOP_DIR})\r\n\r\nset(LIBSQLITE3_SRCS\r\n    ${TOP_DIR}/unity_sqlite.c\r\n)\r\n\r\nif (MSVC)\r\n\t# Turn off security warnings.\r\n\tadd_definitions(-D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE)\r\nendif (MSVC)\r\n\r\nif (APPLE) \r\n    if (IOS)\r\n        add_library(sqlite3 STATIC ${LIBSQLITE3_SRCS})\r\n        set(CMAKE_OSX_ARCHITECTURES \"$(ARCHS_STANDARD)\")\r\n        set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -fembed-bitcode\")\r\n        set(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -fembed-bitcode\")\r\n        set_xcode_property (sqlite3 IPHONEOS_DEPLOYMENT_TARGET \"7.0\" \"all\")\r\n    else ()\r\n        add_library(sqlite3 MODULE ${LIBSQLITE3_SRCS})\r\n        set(CMAKE_OSX_ARCHITECTURES \"$(ARCHS_STANDARD_64_BIT)\")\r\n        set_target_properties(sqlite3 PROPERTIES MACOSX_BUNDLE TRUE)\r\n        set_target_properties(sqlite3 PROPERTIES BUNDLE TRUE)\r\n    endif ()\r\nelse ()\r\n    if (WIN32)\r\n        add_library(sqlite3 SHARED ${LIBSQLITE3_SRCS})\r\n    else ()\r\n        add_library(sqlite3 SHARED ${LIBSQLITE3_SRCS})\r\n    endif ()\r\nendif ()\r\n\r\n#target_link_libraries(sqlite3 librws_static.lib)\r\n"
  },
  {
    "path": "jsb_build/sqlite3/make_sqlite3_windows.bat",
    "content": "@echo off\r\n\r\nSET BASE_PATH=%~dp0\r\nSET BUILD_PATH=%~dp0..\\out\\sqlite3\r\necho %BUILD_PATH%\r\nREM cmake -G \"Visual Studio 15 2017 Win64\" ..\\..\\..\r\n\r\nmkdir %BUILD_PATH% 2>nul\r\ncd %BUILD_PATH%\r\n\r\nREM rd /s /q x64_Debug 2>nul\r\nREM echo building x64_Debug\r\nREM mkdir x64_Debug\r\nREM cd x64_Debug\r\nREM cmake -G \"Visual Studio 16 2019\" -A x64 ..\\..\\..\\sqlite3\r\nREM cd %BUILD_PATH%\r\nREM cmake --build x64_Debug --config Debug\r\nREM mkdir ..\\..\\prebuilt\\Plugins\\x64\\\r\nREM xcopy /Y .\\x64_Debug\\Debug\\sqlite3.dll ..\\..\\prebuilt\\Plugins\\x64\\\r\n\r\nrd /s /q x64_release 2>nul\r\necho building x64_release\r\nmkdir x64_release\r\ncd x64_release\r\ncmake -G \"Visual Studio 16 2019\" -A x64 ..\\..\\..\\sqlite3\r\ncd %BUILD_PATH%\r\ncmake --build x64_release --config Release\r\nmkdir ..\\..\\prebuilt\\Plugins\\x64\\\r\nxcopy /Y .\\x64_release\\Release\\sqlite3.dll ..\\..\\prebuilt\\Plugins\\x64\\\r\n\r\nrd /s /q x86_release 2>nul\r\necho building x86_release\r\nmkdir x86_release\r\ncd x86_release\r\ncmake -G \"Visual Studio 16 2019\" -A Win32 ..\\..\\..\\sqlite3\r\ncd %BUILD_PATH%\r\ncmake --build x86_release --config Release\r\nmkdir ..\\..\\prebuilt\\Plugins\\x86\\\r\nxcopy /Y .\\x86_release\\Release\\sqlite3.dll ..\\..\\prebuilt\\Plugins\\x86\\\r\n\r\ncd %BASE_PATH%\r\n"
  },
  {
    "path": "jsb_build/sqlite3/sqlite-amalgamation-3320300/shell.c",
    "content": "/* DO NOT EDIT!\n** This file is automatically generated by the script in the canonical\n** SQLite source tree at tool/mkshellc.tcl.  That script combines source\n** code from various constituent source files of SQLite into this single\n** \"shell.c\" file used to implement the SQLite command-line shell.\n**\n** Most of the code found below comes from the \"src/shell.c.in\" file in\n** the canonical SQLite source tree.  That main file contains \"INCLUDE\"\n** lines that specify other files in the canonical source tree that are\n** inserted to getnerate this complete program source file.\n**\n** The code from multiple files is combined into this single \"shell.c\"\n** source file to help make the command-line program easier to compile.\n**\n** To modify this program, get a copy of the canonical SQLite source tree,\n** edit the src/shell.c.in\" and/or some of the other files that are included\n** by \"src/shell.c.in\", then rerun the tool/mkshellc.tcl script.\n*/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code to implement the \"sqlite\" command line\n** utility for accessing SQLite databases.\n*/\n#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)\n/* This needs to come before any includes for MSVC compiler */\n#define _CRT_SECURE_NO_WARNINGS\n#endif\n\n/*\n** Determine if we are dealing with WinRT, which provides only a subset of\n** the full Win32 API.\n*/\n#if !defined(SQLITE_OS_WINRT)\n# define SQLITE_OS_WINRT 0\n#endif\n\n/*\n** Warning pragmas copied from msvc.h in the core.\n*/\n#if defined(_MSC_VER)\n#pragma warning(disable : 4054)\n#pragma warning(disable : 4055)\n#pragma warning(disable : 4100)\n#pragma warning(disable : 4127)\n#pragma warning(disable : 4130)\n#pragma warning(disable : 4152)\n#pragma warning(disable : 4189)\n#pragma warning(disable : 4206)\n#pragma warning(disable : 4210)\n#pragma warning(disable : 4232)\n#pragma warning(disable : 4244)\n#pragma warning(disable : 4305)\n#pragma warning(disable : 4306)\n#pragma warning(disable : 4702)\n#pragma warning(disable : 4706)\n#endif /* defined(_MSC_VER) */\n\n/*\n** No support for loadable extensions in VxWorks.\n*/\n#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION\n# define SQLITE_OMIT_LOAD_EXTENSION 1\n#endif\n\n/*\n** Enable large-file support for fopen() and friends on unix.\n*/\n#ifndef SQLITE_DISABLE_LFS\n# define _LARGE_FILE       1\n# ifndef _FILE_OFFSET_BITS\n#   define _FILE_OFFSET_BITS 64\n# endif\n# define _LARGEFILE_SOURCE 1\n#endif\n\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <assert.h>\n#include \"sqlite3.h\"\ntypedef sqlite3_int64 i64;\ntypedef sqlite3_uint64 u64;\ntypedef unsigned char u8;\n#if SQLITE_USER_AUTHENTICATION\n# include \"sqlite3userauth.h\"\n#endif\n#include <ctype.h>\n#include <stdarg.h>\n\n#if !defined(_WIN32) && !defined(WIN32)\n# include <signal.h>\n# if !defined(__RTP__) && !defined(_WRS_KERNEL)\n#  include <pwd.h>\n# endif\n#endif\n#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)\n# include <unistd.h>\n# include <dirent.h>\n# define GETPID getpid\n# if defined(__MINGW32__)\n#  define DIRENT dirent\n#  ifndef S_ISLNK\n#   define S_ISLNK(mode) (0)\n#  endif\n# endif\n#else\n# define GETPID (int)GetCurrentProcessId\n#endif\n#include <sys/types.h>\n#include <sys/stat.h>\n\n#if HAVE_READLINE\n# include <readline/readline.h>\n# include <readline/history.h>\n#endif\n\n#if HAVE_EDITLINE\n# include <editline/readline.h>\n#endif\n\n#if HAVE_EDITLINE || HAVE_READLINE\n\n# define shell_add_history(X) add_history(X)\n# define shell_read_history(X) read_history(X)\n# define shell_write_history(X) write_history(X)\n# define shell_stifle_history(X) stifle_history(X)\n# define shell_readline(X) readline(X)\n\n#elif HAVE_LINENOISE\n\n# include \"linenoise.h\"\n# define shell_add_history(X) linenoiseHistoryAdd(X)\n# define shell_read_history(X) linenoiseHistoryLoad(X)\n# define shell_write_history(X) linenoiseHistorySave(X)\n# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)\n# define shell_readline(X) linenoise(X)\n\n#else\n\n# define shell_read_history(X)\n# define shell_write_history(X)\n# define shell_stifle_history(X)\n\n# define SHELL_USE_LOCAL_GETLINE 1\n#endif\n\n\n#if defined(_WIN32) || defined(WIN32)\n# if SQLITE_OS_WINRT\n#  define SQLITE_OMIT_POPEN 1\n# else\n#  include <io.h>\n#  include <fcntl.h>\n#  define isatty(h) _isatty(h)\n#  ifndef access\n#   define access(f,m) _access((f),(m))\n#  endif\n#  ifndef unlink\n#   define unlink _unlink\n#  endif\n#  ifndef strdup\n#   define strdup _strdup\n#  endif\n#  undef popen\n#  define popen _popen\n#  undef pclose\n#  define pclose _pclose\n# endif\n#else\n /* Make sure isatty() has a prototype. */\n extern int isatty(int);\n\n# if !defined(__RTP__) && !defined(_WRS_KERNEL)\n  /* popen and pclose are not C89 functions and so are\n  ** sometimes omitted from the <stdio.h> header */\n   extern FILE *popen(const char*,const char*);\n   extern int pclose(FILE*);\n# else\n#  define SQLITE_OMIT_POPEN 1\n# endif\n#endif\n\n#if defined(_WIN32_WCE)\n/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()\n * thus we always assume that we have a console. That can be\n * overridden with the -batch command line option.\n */\n#define isatty(x) 1\n#endif\n\n/* ctype macros that work with signed characters */\n#define IsSpace(X)  isspace((unsigned char)X)\n#define IsDigit(X)  isdigit((unsigned char)X)\n#define ToLower(X)  (char)tolower((unsigned char)X)\n\n#if defined(_WIN32) || defined(WIN32)\n#if SQLITE_OS_WINRT\n#include <intrin.h>\n#endif\n#include <windows.h>\n\n/* string conversion routines only needed on Win32 */\nextern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);\nextern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);\nextern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);\nextern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);\n#endif\n\n/* On Windows, we normally run with output mode of TEXT so that \\n characters\n** are automatically translated into \\r\\n.  However, this behavior needs\n** to be disabled in some cases (ex: when generating CSV output and when\n** rendering quoted strings that contain \\n characters).  The following\n** routines take care of that.\n*/\n#if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT\nstatic void setBinaryMode(FILE *file, int isOutput){\n  if( isOutput ) fflush(file);\n  _setmode(_fileno(file), _O_BINARY);\n}\nstatic void setTextMode(FILE *file, int isOutput){\n  if( isOutput ) fflush(file);\n  _setmode(_fileno(file), _O_TEXT);\n}\n#else\n# define setBinaryMode(X,Y)\n# define setTextMode(X,Y)\n#endif\n\n\n/* True if the timer is enabled */\nstatic int enableTimer = 0;\n\n/* Return the current wall-clock time */\nstatic sqlite3_int64 timeOfDay(void){\n  static sqlite3_vfs *clockVfs = 0;\n  sqlite3_int64 t;\n  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);\n  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){\n    clockVfs->xCurrentTimeInt64(clockVfs, &t);\n  }else{\n    double r;\n    clockVfs->xCurrentTime(clockVfs, &r);\n    t = (sqlite3_int64)(r*86400000.0);\n  }\n  return t;\n}\n\n#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)\n#include <sys/time.h>\n#include <sys/resource.h>\n\n/* VxWorks does not support getrusage() as far as we can determine */\n#if defined(_WRS_KERNEL) || defined(__RTP__)\nstruct rusage {\n  struct timeval ru_utime; /* user CPU time used */\n  struct timeval ru_stime; /* system CPU time used */\n};\n#define getrusage(A,B) memset(B,0,sizeof(*B))\n#endif\n\n/* Saved resource information for the beginning of an operation */\nstatic struct rusage sBegin;  /* CPU time at start */\nstatic sqlite3_int64 iBegin;  /* Wall-clock time at start */\n\n/*\n** Begin timing an operation\n*/\nstatic void beginTimer(void){\n  if( enableTimer ){\n    getrusage(RUSAGE_SELF, &sBegin);\n    iBegin = timeOfDay();\n  }\n}\n\n/* Return the difference of two time_structs in seconds */\nstatic double timeDiff(struct timeval *pStart, struct timeval *pEnd){\n  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +\n         (double)(pEnd->tv_sec - pStart->tv_sec);\n}\n\n/*\n** Print the timing results.\n*/\nstatic void endTimer(void){\n  if( enableTimer ){\n    sqlite3_int64 iEnd = timeOfDay();\n    struct rusage sEnd;\n    getrusage(RUSAGE_SELF, &sEnd);\n    printf(\"Run Time: real %.3f user %f sys %f\\n\",\n       (iEnd - iBegin)*0.001,\n       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),\n       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));\n  }\n}\n\n#define BEGIN_TIMER beginTimer()\n#define END_TIMER endTimer()\n#define HAS_TIMER 1\n\n#elif (defined(_WIN32) || defined(WIN32))\n\n/* Saved resource information for the beginning of an operation */\nstatic HANDLE hProcess;\nstatic FILETIME ftKernelBegin;\nstatic FILETIME ftUserBegin;\nstatic sqlite3_int64 ftWallBegin;\ntypedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,\n                                    LPFILETIME, LPFILETIME);\nstatic GETPROCTIMES getProcessTimesAddr = NULL;\n\n/*\n** Check to see if we have timer support.  Return 1 if necessary\n** support found (or found previously).\n*/\nstatic int hasTimer(void){\n  if( getProcessTimesAddr ){\n    return 1;\n  } else {\n#if !SQLITE_OS_WINRT\n    /* GetProcessTimes() isn't supported in WIN95 and some other Windows\n    ** versions. See if the version we are running on has it, and if it\n    ** does, save off a pointer to it and the current process handle.\n    */\n    hProcess = GetCurrentProcess();\n    if( hProcess ){\n      HINSTANCE hinstLib = LoadLibrary(TEXT(\"Kernel32.dll\"));\n      if( NULL != hinstLib ){\n        getProcessTimesAddr =\n            (GETPROCTIMES) GetProcAddress(hinstLib, \"GetProcessTimes\");\n        if( NULL != getProcessTimesAddr ){\n          return 1;\n        }\n        FreeLibrary(hinstLib);\n      }\n    }\n#endif\n  }\n  return 0;\n}\n\n/*\n** Begin timing an operation\n*/\nstatic void beginTimer(void){\n  if( enableTimer && getProcessTimesAddr ){\n    FILETIME ftCreation, ftExit;\n    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,\n                        &ftKernelBegin,&ftUserBegin);\n    ftWallBegin = timeOfDay();\n  }\n}\n\n/* Return the difference of two FILETIME structs in seconds */\nstatic double timeDiff(FILETIME *pStart, FILETIME *pEnd){\n  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);\n  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);\n  return (double) ((i64End - i64Start) / 10000000.0);\n}\n\n/*\n** Print the timing results.\n*/\nstatic void endTimer(void){\n  if( enableTimer && getProcessTimesAddr){\n    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;\n    sqlite3_int64 ftWallEnd = timeOfDay();\n    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);\n    printf(\"Run Time: real %.3f user %f sys %f\\n\",\n       (ftWallEnd - ftWallBegin)*0.001,\n       timeDiff(&ftUserBegin, &ftUserEnd),\n       timeDiff(&ftKernelBegin, &ftKernelEnd));\n  }\n}\n\n#define BEGIN_TIMER beginTimer()\n#define END_TIMER endTimer()\n#define HAS_TIMER hasTimer()\n\n#else\n#define BEGIN_TIMER\n#define END_TIMER\n#define HAS_TIMER 0\n#endif\n\n/*\n** Used to prevent warnings about unused parameters\n*/\n#define UNUSED_PARAMETER(x) (void)(x)\n\n/*\n** Number of elements in an array\n*/\n#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))\n\n/*\n** If the following flag is set, then command execution stops\n** at an error if we are not interactive.\n*/\nstatic int bail_on_error = 0;\n\n/*\n** Threat stdin as an interactive input if the following variable\n** is true.  Otherwise, assume stdin is connected to a file or pipe.\n*/\nstatic int stdin_is_interactive = 1;\n\n/*\n** On Windows systems we have to know if standard output is a console\n** in order to translate UTF-8 into MBCS.  The following variable is\n** true if translation is required.\n*/\nstatic int stdout_is_console = 1;\n\n/*\n** The following is the open SQLite database.  We make a pointer\n** to this database a static variable so that it can be accessed\n** by the SIGINT handler to interrupt database processing.\n*/\nstatic sqlite3 *globalDb = 0;\n\n/*\n** True if an interrupt (Control-C) has been received.\n*/\nstatic volatile int seenInterrupt = 0;\n\n#ifdef SQLITE_DEBUG\n/*\n** Out-of-memory simulator variables\n*/\nstatic unsigned int oomCounter = 0;    /* Simulate OOM when equals 1 */\nstatic unsigned int oomRepeat = 0;     /* Number of OOMs in a row */\nstatic void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */\n#endif /* SQLITE_DEBUG */\n\n/*\n** This is the name of our program. It is set in main(), used\n** in a number of other places, mostly for error messages.\n*/\nstatic char *Argv0;\n\n/*\n** Prompt strings. Initialized in main. Settable with\n**   .prompt main continue\n*/\nstatic char mainPrompt[20];     /* First line prompt. default: \"sqlite> \"*/\nstatic char continuePrompt[20]; /* Continuation prompt. default: \"   ...> \" */\n\n/*\n** Render output like fprintf().  Except, if the output is going to the\n** console and if this is running on a Windows machine, translate the\n** output from UTF-8 into MBCS.\n*/\n#if defined(_WIN32) || defined(WIN32)\nvoid utf8_printf(FILE *out, const char *zFormat, ...){\n  va_list ap;\n  va_start(ap, zFormat);\n  if( stdout_is_console && (out==stdout || out==stderr) ){\n    char *z1 = sqlite3_vmprintf(zFormat, ap);\n    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);\n    sqlite3_free(z1);\n    fputs(z2, out);\n    sqlite3_free(z2);\n  }else{\n    vfprintf(out, zFormat, ap);\n  }\n  va_end(ap);\n}\n#elif !defined(utf8_printf)\n# define utf8_printf fprintf\n#endif\n\n/*\n** Render output like fprintf().  This should not be used on anything that\n** includes string formatting (e.g. \"%s\").\n*/\n#if !defined(raw_printf)\n# define raw_printf fprintf\n#endif\n\n/* Indicate out-of-memory and exit. */\nstatic void shell_out_of_memory(void){\n  raw_printf(stderr,\"Error: out of memory\\n\");\n  exit(1);\n}\n\n#ifdef SQLITE_DEBUG\n/* This routine is called when a simulated OOM occurs.  It is broken\n** out as a separate routine to make it easy to set a breakpoint on\n** the OOM\n*/\nvoid shellOomFault(void){\n  if( oomRepeat>0 ){\n    oomRepeat--;\n  }else{\n    oomCounter--;\n  }\n}\n#endif /* SQLITE_DEBUG */\n\n#ifdef SQLITE_DEBUG\n/* This routine is a replacement malloc() that is used to simulate\n** Out-Of-Memory (OOM) errors for testing purposes.\n*/\nstatic void *oomMalloc(int nByte){\n  if( oomCounter ){\n    if( oomCounter==1 ){\n      shellOomFault();\n      return 0;\n    }else{\n      oomCounter--;\n    }\n  }\n  return defaultMalloc(nByte);\n}\n#endif /* SQLITE_DEBUG */\n\n#ifdef SQLITE_DEBUG\n/* Register the OOM simulator.  This must occur before any memory\n** allocations */\nstatic void registerOomSimulator(void){\n  sqlite3_mem_methods mem;\n  sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);\n  defaultMalloc = mem.xMalloc;\n  mem.xMalloc = oomMalloc;\n  sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);\n}\n#endif\n\n/*\n** Write I/O traces to the following stream.\n*/\n#ifdef SQLITE_ENABLE_IOTRACE\nstatic FILE *iotrace = 0;\n#endif\n\n/*\n** This routine works like printf in that its first argument is a\n** format string and subsequent arguments are values to be substituted\n** in place of % fields.  The result of formatting this string\n** is written to iotrace.\n*/\n#ifdef SQLITE_ENABLE_IOTRACE\nstatic void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){\n  va_list ap;\n  char *z;\n  if( iotrace==0 ) return;\n  va_start(ap, zFormat);\n  z = sqlite3_vmprintf(zFormat, ap);\n  va_end(ap);\n  utf8_printf(iotrace, \"%s\", z);\n  sqlite3_free(z);\n}\n#endif\n\n/*\n** Output string zUtf to stream pOut as w characters.  If w is negative,\n** then right-justify the text.  W is the width in UTF-8 characters, not\n** in bytes.  This is different from the %*.*s specification in printf\n** since with %*.*s the width is measured in bytes, not characters.\n*/\nstatic void utf8_width_print(FILE *pOut, int w, const char *zUtf){\n  int i;\n  int n;\n  int aw = w<0 ? -w : w;\n  char zBuf[1000];\n  if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;\n  for(i=n=0; zUtf[i]; i++){\n    if( (zUtf[i]&0xc0)!=0x80 ){\n      n++;\n      if( n==aw ){\n        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );\n        break;\n      }\n    }\n  }\n  if( n>=aw ){\n    utf8_printf(pOut, \"%.*s\", i, zUtf);\n  }else if( w<0 ){\n    utf8_printf(pOut, \"%*s%s\", aw-n, \"\", zUtf);\n  }else{\n    utf8_printf(pOut, \"%s%*s\", zUtf, aw-n, \"\");\n  }\n}\n\n\n/*\n** Determines if a string is a number of not.\n*/\nstatic int isNumber(const char *z, int *realnum){\n  if( *z=='-' || *z=='+' ) z++;\n  if( !IsDigit(*z) ){\n    return 0;\n  }\n  z++;\n  if( realnum ) *realnum = 0;\n  while( IsDigit(*z) ){ z++; }\n  if( *z=='.' ){\n    z++;\n    if( !IsDigit(*z) ) return 0;\n    while( IsDigit(*z) ){ z++; }\n    if( realnum ) *realnum = 1;\n  }\n  if( *z=='e' || *z=='E' ){\n    z++;\n    if( *z=='+' || *z=='-' ) z++;\n    if( !IsDigit(*z) ) return 0;\n    while( IsDigit(*z) ){ z++; }\n    if( realnum ) *realnum = 1;\n  }\n  return *z==0;\n}\n\n/*\n** Compute a string length that is limited to what can be stored in\n** lower 30 bits of a 32-bit signed integer.\n*/\nstatic int strlen30(const char *z){\n  const char *z2 = z;\n  while( *z2 ){ z2++; }\n  return 0x3fffffff & (int)(z2 - z);\n}\n\n/*\n** Return the length of a string in characters.  Multibyte UTF8 characters\n** count as a single character.\n*/\nstatic int strlenChar(const char *z){\n  int n = 0;\n  while( *z ){\n    if( (0xc0&*(z++))!=0x80 ) n++;\n  }\n  return n;\n}\n\n/*\n** This routine reads a line of text from FILE in, stores\n** the text in memory obtained from malloc() and returns a pointer\n** to the text.  NULL is returned at end of file, or if malloc()\n** fails.\n**\n** If zLine is not NULL then it is a malloced buffer returned from\n** a previous call to this routine that may be reused.\n*/\nstatic char *local_getline(char *zLine, FILE *in){\n  int nLine = zLine==0 ? 0 : 100;\n  int n = 0;\n\n  while( 1 ){\n    if( n+100>nLine ){\n      nLine = nLine*2 + 100;\n      zLine = realloc(zLine, nLine);\n      if( zLine==0 ) shell_out_of_memory();\n    }\n    if( fgets(&zLine[n], nLine - n, in)==0 ){\n      if( n==0 ){\n        free(zLine);\n        return 0;\n      }\n      zLine[n] = 0;\n      break;\n    }\n    while( zLine[n] ) n++;\n    if( n>0 && zLine[n-1]=='\\n' ){\n      n--;\n      if( n>0 && zLine[n-1]=='\\r' ) n--;\n      zLine[n] = 0;\n      break;\n    }\n  }\n#if defined(_WIN32) || defined(WIN32)\n  /* For interactive input on Windows systems, translate the\n  ** multi-byte characterset characters into UTF-8. */\n  if( stdin_is_interactive && in==stdin ){\n    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);\n    if( zTrans ){\n      int nTrans = strlen30(zTrans)+1;\n      if( nTrans>nLine ){\n        zLine = realloc(zLine, nTrans);\n        if( zLine==0 ) shell_out_of_memory();\n      }\n      memcpy(zLine, zTrans, nTrans);\n      sqlite3_free(zTrans);\n    }\n  }\n#endif /* defined(_WIN32) || defined(WIN32) */\n  return zLine;\n}\n\n/*\n** Retrieve a single line of input text.\n**\n** If in==0 then read from standard input and prompt before each line.\n** If isContinuation is true, then a continuation prompt is appropriate.\n** If isContinuation is zero, then the main prompt should be used.\n**\n** If zPrior is not NULL then it is a buffer from a prior call to this\n** routine that can be reused.\n**\n** The result is stored in space obtained from malloc() and must either\n** be freed by the caller or else passed back into this routine via the\n** zPrior argument for reuse.\n*/\nstatic char *one_input_line(FILE *in, char *zPrior, int isContinuation){\n  char *zPrompt;\n  char *zResult;\n  if( in!=0 ){\n    zResult = local_getline(zPrior, in);\n  }else{\n    zPrompt = isContinuation ? continuePrompt : mainPrompt;\n#if SHELL_USE_LOCAL_GETLINE\n    printf(\"%s\", zPrompt);\n    fflush(stdout);\n    zResult = local_getline(zPrior, stdin);\n#else\n    free(zPrior);\n    zResult = shell_readline(zPrompt);\n    if( zResult && *zResult ) shell_add_history(zResult);\n#endif\n  }\n  return zResult;\n}\n\n\n/*\n** Return the value of a hexadecimal digit.  Return -1 if the input\n** is not a hex digit.\n*/\nstatic int hexDigitValue(char c){\n  if( c>='0' && c<='9' ) return c - '0';\n  if( c>='a' && c<='f' ) return c - 'a' + 10;\n  if( c>='A' && c<='F' ) return c - 'A' + 10;\n  return -1;\n}\n\n/*\n** Interpret zArg as an integer value, possibly with suffixes.\n*/\nstatic sqlite3_int64 integerValue(const char *zArg){\n  sqlite3_int64 v = 0;\n  static const struct { char *zSuffix; int iMult; } aMult[] = {\n    { \"KiB\", 1024 },\n    { \"MiB\", 1024*1024 },\n    { \"GiB\", 1024*1024*1024 },\n    { \"KB\",  1000 },\n    { \"MB\",  1000000 },\n    { \"GB\",  1000000000 },\n    { \"K\",   1000 },\n    { \"M\",   1000000 },\n    { \"G\",   1000000000 },\n  };\n  int i;\n  int isNeg = 0;\n  if( zArg[0]=='-' ){\n    isNeg = 1;\n    zArg++;\n  }else if( zArg[0]=='+' ){\n    zArg++;\n  }\n  if( zArg[0]=='0' && zArg[1]=='x' ){\n    int x;\n    zArg += 2;\n    while( (x = hexDigitValue(zArg[0]))>=0 ){\n      v = (v<<4) + x;\n      zArg++;\n    }\n  }else{\n    while( IsDigit(zArg[0]) ){\n      v = v*10 + zArg[0] - '0';\n      zArg++;\n    }\n  }\n  for(i=0; i<ArraySize(aMult); i++){\n    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){\n      v *= aMult[i].iMult;\n      break;\n    }\n  }\n  return isNeg? -v : v;\n}\n\n/*\n** A variable length string to which one can append text.\n*/\ntypedef struct ShellText ShellText;\nstruct ShellText {\n  char *z;\n  int n;\n  int nAlloc;\n};\n\n/*\n** Initialize and destroy a ShellText object\n*/\nstatic void initText(ShellText *p){\n  memset(p, 0, sizeof(*p));\n}\nstatic void freeText(ShellText *p){\n  free(p->z);\n  initText(p);\n}\n\n/* zIn is either a pointer to a NULL-terminated string in memory obtained\n** from malloc(), or a NULL pointer. The string pointed to by zAppend is\n** added to zIn, and the result returned in memory obtained from malloc().\n** zIn, if it was not NULL, is freed.\n**\n** If the third argument, quote, is not '\\0', then it is used as a\n** quote character for zAppend.\n*/\nstatic void appendText(ShellText *p, char const *zAppend, char quote){\n  int len;\n  int i;\n  int nAppend = strlen30(zAppend);\n\n  len = nAppend+p->n+1;\n  if( quote ){\n    len += 2;\n    for(i=0; i<nAppend; i++){\n      if( zAppend[i]==quote ) len++;\n    }\n  }\n\n  if( p->n+len>=p->nAlloc ){\n    p->nAlloc = p->nAlloc*2 + len + 20;\n    p->z = realloc(p->z, p->nAlloc);\n    if( p->z==0 ) shell_out_of_memory();\n  }\n\n  if( quote ){\n    char *zCsr = p->z+p->n;\n    *zCsr++ = quote;\n    for(i=0; i<nAppend; i++){\n      *zCsr++ = zAppend[i];\n      if( zAppend[i]==quote ) *zCsr++ = quote;\n    }\n    *zCsr++ = quote;\n    p->n = (int)(zCsr - p->z);\n    *zCsr = '\\0';\n  }else{\n    memcpy(p->z+p->n, zAppend, nAppend);\n    p->n += nAppend;\n    p->z[p->n] = '\\0';\n  }\n}\n\n/*\n** Attempt to determine if identifier zName needs to be quoted, either\n** because it contains non-alphanumeric characters, or because it is an\n** SQLite keyword.  Be conservative in this estimate:  When in doubt assume\n** that quoting is required.\n**\n** Return '\"' if quoting is required.  Return 0 if no quoting is required.\n*/\nstatic char quoteChar(const char *zName){\n  int i;\n  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '\"';\n  for(i=0; zName[i]; i++){\n    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '\"';\n  }\n  return sqlite3_keyword_check(zName, i) ? '\"' : 0;\n}\n\n/*\n** Construct a fake object name and column list to describe the structure\n** of the view, virtual table, or table valued function zSchema.zName.\n*/\nstatic char *shellFakeSchema(\n  sqlite3 *db,            /* The database connection containing the vtab */\n  const char *zSchema,    /* Schema of the database holding the vtab */\n  const char *zName       /* The name of the virtual table */\n){\n  sqlite3_stmt *pStmt = 0;\n  char *zSql;\n  ShellText s;\n  char cQuote;\n  char *zDiv = \"(\";\n  int nRow = 0;\n\n  zSql = sqlite3_mprintf(\"PRAGMA \\\"%w\\\".table_info=%Q;\",\n                         zSchema ? zSchema : \"main\", zName);\n  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);\n  sqlite3_free(zSql);\n  initText(&s);\n  if( zSchema ){\n    cQuote = quoteChar(zSchema);\n    if( cQuote && sqlite3_stricmp(zSchema,\"temp\")==0 ) cQuote = 0;\n    appendText(&s, zSchema, cQuote);\n    appendText(&s, \".\", 0);\n  }\n  cQuote = quoteChar(zName);\n  appendText(&s, zName, cQuote);\n  while( sqlite3_step(pStmt)==SQLITE_ROW ){\n    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);\n    nRow++;\n    appendText(&s, zDiv, 0);\n    zDiv = \",\";\n    cQuote = quoteChar(zCol);\n    appendText(&s, zCol, cQuote);\n  }\n  appendText(&s, \")\", 0);\n  sqlite3_finalize(pStmt);\n  if( nRow==0 ){\n    freeText(&s);\n    s.z = 0;\n  }\n  return s.z;\n}\n\n/*\n** SQL function:  shell_module_schema(X)\n**\n** Return a fake schema for the table-valued function or eponymous virtual\n** table X.\n*/\nstatic void shellModuleSchema(\n  sqlite3_context *pCtx,\n  int nVal,\n  sqlite3_value **apVal\n){\n  const char *zName = (const char*)sqlite3_value_text(apVal[0]);\n  char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);\n  UNUSED_PARAMETER(nVal);\n  if( zFake ){\n    sqlite3_result_text(pCtx, sqlite3_mprintf(\"/* %s */\", zFake),\n                        -1, sqlite3_free);\n    free(zFake);\n  }\n}\n\n/*\n** SQL function:  shell_add_schema(S,X)\n**\n** Add the schema name X to the CREATE statement in S and return the result.\n** Examples:\n**\n**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);\n**\n** Also works on\n**\n**    CREATE INDEX\n**    CREATE UNIQUE INDEX\n**    CREATE VIEW\n**    CREATE TRIGGER\n**    CREATE VIRTUAL TABLE\n**\n** This UDF is used by the .schema command to insert the schema name of\n** attached databases into the middle of the sqlite_master.sql field.\n*/\nstatic void shellAddSchemaName(\n  sqlite3_context *pCtx,\n  int nVal,\n  sqlite3_value **apVal\n){\n  static const char *aPrefix[] = {\n     \"TABLE\",\n     \"INDEX\",\n     \"UNIQUE INDEX\",\n     \"VIEW\",\n     \"TRIGGER\",\n     \"VIRTUAL TABLE\"\n  };\n  int i = 0;\n  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);\n  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);\n  const char *zName = (const char*)sqlite3_value_text(apVal[2]);\n  sqlite3 *db = sqlite3_context_db_handle(pCtx);\n  UNUSED_PARAMETER(nVal);\n  if( zIn!=0 && strncmp(zIn, \"CREATE \", 7)==0 ){\n    for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){\n      int n = strlen30(aPrefix[i]);\n      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){\n        char *z = 0;\n        char *zFake = 0;\n        if( zSchema ){\n          char cQuote = quoteChar(zSchema);\n          if( cQuote && sqlite3_stricmp(zSchema,\"temp\")!=0 ){\n            z = sqlite3_mprintf(\"%.*s \\\"%w\\\".%s\", n+7, zIn, zSchema, zIn+n+8);\n          }else{\n            z = sqlite3_mprintf(\"%.*s %s.%s\", n+7, zIn, zSchema, zIn+n+8);\n          }\n        }\n        if( zName\n         && aPrefix[i][0]=='V'\n         && (zFake = shellFakeSchema(db, zSchema, zName))!=0\n        ){\n          if( z==0 ){\n            z = sqlite3_mprintf(\"%s\\n/* %s */\", zIn, zFake);\n          }else{\n            z = sqlite3_mprintf(\"%z\\n/* %s */\", z, zFake);\n          }\n          free(zFake);\n        }\n        if( z ){\n          sqlite3_result_text(pCtx, z, -1, sqlite3_free);\n          return;\n        }\n      }\n    }\n  }\n  sqlite3_result_value(pCtx, apVal[0]);\n}\n\n/*\n** The source code for several run-time loadable extensions is inserted\n** below by the ../tool/mkshellc.tcl script.  Before processing that included\n** code, we need to override some macros to make the included program code\n** work here in the middle of this regular program.\n*/\n#define SQLITE_EXTENSION_INIT1\n#define SQLITE_EXTENSION_INIT2(X) (void)(X)\n\n#if defined(_WIN32) && defined(_MSC_VER)\n/************************* Begin test_windirent.h ******************/\n/*\n** 2015 November 30\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains declarations for most of the opendir() family of\n** POSIX functions on Win32 using the MSVCRT.\n*/\n\n#if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)\n#define SQLITE_WINDIRENT_H\n\n/*\n** We need several data types from the Windows SDK header.\n*/\n\n#ifndef WIN32_LEAN_AND_MEAN\n#define WIN32_LEAN_AND_MEAN\n#endif\n\n#include \"windows.h\"\n\n/*\n** We need several support functions from the SQLite core.\n*/\n\n/* #include \"sqlite3.h\" */\n\n/*\n** We need several things from the ANSI and MSVCRT headers.\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <io.h>\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n/*\n** We may need several defines that should have been in \"sys/stat.h\".\n*/\n\n#ifndef S_ISREG\n#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)\n#endif\n\n#ifndef S_ISDIR\n#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)\n#endif\n\n#ifndef S_ISLNK\n#define S_ISLNK(mode) (0)\n#endif\n\n/*\n** We may need to provide the \"mode_t\" type.\n*/\n\n#ifndef MODE_T_DEFINED\n  #define MODE_T_DEFINED\n  typedef unsigned short mode_t;\n#endif\n\n/*\n** We may need to provide the \"ino_t\" type.\n*/\n\n#ifndef INO_T_DEFINED\n  #define INO_T_DEFINED\n  typedef unsigned short ino_t;\n#endif\n\n/*\n** We need to define \"NAME_MAX\" if it was not present in \"limits.h\".\n*/\n\n#ifndef NAME_MAX\n#  ifdef FILENAME_MAX\n#    define NAME_MAX (FILENAME_MAX)\n#  else\n#    define NAME_MAX (260)\n#  endif\n#endif\n\n/*\n** We need to define \"NULL_INTPTR_T\" and \"BAD_INTPTR_T\".\n*/\n\n#ifndef NULL_INTPTR_T\n#  define NULL_INTPTR_T ((intptr_t)(0))\n#endif\n\n#ifndef BAD_INTPTR_T\n#  define BAD_INTPTR_T ((intptr_t)(-1))\n#endif\n\n/*\n** We need to provide the necessary structures and related types.\n*/\n\n#ifndef DIRENT_DEFINED\n#define DIRENT_DEFINED\ntypedef struct DIRENT DIRENT;\ntypedef DIRENT *LPDIRENT;\nstruct DIRENT {\n  ino_t d_ino;               /* Sequence number, do not use. */\n  unsigned d_attributes;     /* Win32 file attributes. */\n  char d_name[NAME_MAX + 1]; /* Name within the directory. */\n};\n#endif\n\n#ifndef DIR_DEFINED\n#define DIR_DEFINED\ntypedef struct DIR DIR;\ntypedef DIR *LPDIR;\nstruct DIR {\n  intptr_t d_handle; /* Value returned by \"_findfirst\". */\n  DIRENT d_first;    /* DIRENT constructed based on \"_findfirst\". */\n  DIRENT d_next;     /* DIRENT constructed based on \"_findnext\". */\n};\n#endif\n\n/*\n** Provide a macro, for use by the implementation, to determine if a\n** particular directory entry should be skipped over when searching for\n** the next directory entry that should be returned by the readdir() or\n** readdir_r() functions.\n*/\n\n#ifndef is_filtered\n#  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))\n#endif\n\n/*\n** Provide the function prototype for the POSIX compatiable getenv()\n** function.  This function is not thread-safe.\n*/\n\nextern const char *windirent_getenv(const char *name);\n\n/*\n** Finally, we can provide the function prototypes for the opendir(),\n** readdir(), readdir_r(), and closedir() POSIX functions.\n*/\n\nextern LPDIR opendir(const char *dirname);\nextern LPDIRENT readdir(LPDIR dirp);\nextern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);\nextern INT closedir(LPDIR dirp);\n\n#endif /* defined(WIN32) && defined(_MSC_VER) */\n\n/************************* End test_windirent.h ********************/\n/************************* Begin test_windirent.c ******************/\n/*\n** 2015 November 30\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code to implement most of the opendir() family of\n** POSIX functions on Win32 using the MSVCRT.\n*/\n\n#if defined(_WIN32) && defined(_MSC_VER)\n/* #include \"test_windirent.h\" */\n\n/*\n** Implementation of the POSIX getenv() function using the Win32 API.\n** This function is not thread-safe.\n*/\nconst char *windirent_getenv(\n  const char *name\n){\n  static char value[32768]; /* Maximum length, per MSDN */\n  DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */\n  DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */\n\n  memset(value, 0, sizeof(value));\n  dwRet = GetEnvironmentVariableA(name, value, dwSize);\n  if( dwRet==0 || dwRet>dwSize ){\n    /*\n    ** The function call to GetEnvironmentVariableA() failed -OR-\n    ** the buffer is not large enough.  Either way, return NULL.\n    */\n    return 0;\n  }else{\n    /*\n    ** The function call to GetEnvironmentVariableA() succeeded\n    ** -AND- the buffer contains the entire value.\n    */\n    return value;\n  }\n}\n\n/*\n** Implementation of the POSIX opendir() function using the MSVCRT.\n*/\nLPDIR opendir(\n  const char *dirname\n){\n  struct _finddata_t data;\n  LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));\n  SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);\n\n  if( dirp==NULL ) return NULL;\n  memset(dirp, 0, sizeof(DIR));\n\n  /* TODO: Remove this if Unix-style root paths are not used. */\n  if( sqlite3_stricmp(dirname, \"/\")==0 ){\n    dirname = windirent_getenv(\"SystemDrive\");\n  }\n\n  memset(&data, 0, sizeof(struct _finddata_t));\n  _snprintf(data.name, namesize, \"%s\\\\*\", dirname);\n  dirp->d_handle = _findfirst(data.name, &data);\n\n  if( dirp->d_handle==BAD_INTPTR_T ){\n    closedir(dirp);\n    return NULL;\n  }\n\n  /* TODO: Remove this block to allow hidden and/or system files. */\n  if( is_filtered(data) ){\nnext:\n\n    memset(&data, 0, sizeof(struct _finddata_t));\n    if( _findnext(dirp->d_handle, &data)==-1 ){\n      closedir(dirp);\n      return NULL;\n    }\n\n    /* TODO: Remove this block to allow hidden and/or system files. */\n    if( is_filtered(data) ) goto next;\n  }\n\n  dirp->d_first.d_attributes = data.attrib;\n  strncpy(dirp->d_first.d_name, data.name, NAME_MAX);\n  dirp->d_first.d_name[NAME_MAX] = '\\0';\n\n  return dirp;\n}\n\n/*\n** Implementation of the POSIX readdir() function using the MSVCRT.\n*/\nLPDIRENT readdir(\n  LPDIR dirp\n){\n  struct _finddata_t data;\n\n  if( dirp==NULL ) return NULL;\n\n  if( dirp->d_first.d_ino==0 ){\n    dirp->d_first.d_ino++;\n    dirp->d_next.d_ino++;\n\n    return &dirp->d_first;\n  }\n\nnext:\n\n  memset(&data, 0, sizeof(struct _finddata_t));\n  if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;\n\n  /* TODO: Remove this block to allow hidden and/or system files. */\n  if( is_filtered(data) ) goto next;\n\n  dirp->d_next.d_ino++;\n  dirp->d_next.d_attributes = data.attrib;\n  strncpy(dirp->d_next.d_name, data.name, NAME_MAX);\n  dirp->d_next.d_name[NAME_MAX] = '\\0';\n\n  return &dirp->d_next;\n}\n\n/*\n** Implementation of the POSIX readdir_r() function using the MSVCRT.\n*/\nINT readdir_r(\n  LPDIR dirp,\n  LPDIRENT entry,\n  LPDIRENT *result\n){\n  struct _finddata_t data;\n\n  if( dirp==NULL ) return EBADF;\n\n  if( dirp->d_first.d_ino==0 ){\n    dirp->d_first.d_ino++;\n    dirp->d_next.d_ino++;\n\n    entry->d_ino = dirp->d_first.d_ino;\n    entry->d_attributes = dirp->d_first.d_attributes;\n    strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);\n    entry->d_name[NAME_MAX] = '\\0';\n\n    *result = entry;\n    return 0;\n  }\n\nnext:\n\n  memset(&data, 0, sizeof(struct _finddata_t));\n  if( _findnext(dirp->d_handle, &data)==-1 ){\n    *result = NULL;\n    return ENOENT;\n  }\n\n  /* TODO: Remove this block to allow hidden and/or system files. */\n  if( is_filtered(data) ) goto next;\n\n  entry->d_ino = (ino_t)-1; /* not available */\n  entry->d_attributes = data.attrib;\n  strncpy(entry->d_name, data.name, NAME_MAX);\n  entry->d_name[NAME_MAX] = '\\0';\n\n  *result = entry;\n  return 0;\n}\n\n/*\n** Implementation of the POSIX closedir() function using the MSVCRT.\n*/\nINT closedir(\n  LPDIR dirp\n){\n  INT result = 0;\n\n  if( dirp==NULL ) return EINVAL;\n\n  if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){\n    result = _findclose(dirp->d_handle);\n  }\n\n  sqlite3_free(dirp);\n  return result;\n}\n\n#endif /* defined(WIN32) && defined(_MSC_VER) */\n\n/************************* End test_windirent.c ********************/\n#define dirent DIRENT\n#endif\n/************************* Begin ../ext/misc/shathree.c ******************/\n/*\n** 2017-03-08\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This SQLite extension implements functions that compute SHA3 hashes.\n** Two SQL functions are implemented:\n**\n**     sha3(X,SIZE)\n**     sha3_query(Y,SIZE)\n**\n** The sha3(X) function computes the SHA3 hash of the input X, or NULL if\n** X is NULL.\n**\n** The sha3_query(Y) function evalutes all queries in the SQL statements of Y\n** and returns a hash of their results.\n**\n** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm\n** is used.  If SIZE is included it must be one of the integers 224, 256,\n** 384, or 512, to determine SHA3 hash variant that is computed.\n*/\n/* #include \"sqlite3ext.h\" */\nSQLITE_EXTENSION_INIT1\n#include <assert.h>\n#include <string.h>\n#include <stdarg.h>\n/* typedef sqlite3_uint64 u64; */\n\n/******************************************************************************\n** The Hash Engine\n*/\n/*\n** Macros to determine whether the machine is big or little endian,\n** and whether or not that determination is run-time or compile-time.\n**\n** For best performance, an attempt is made to guess at the byte-order\n** using C-preprocessor macros.  If that is unsuccessful, or if\n** -DSHA3_BYTEORDER=0 is set, then byte-order is determined\n** at run-time.\n*/\n#ifndef SHA3_BYTEORDER\n# if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \\\n     defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \\\n     defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \\\n     defined(__arm__)\n#   define SHA3_BYTEORDER    1234\n# elif defined(sparc)    || defined(__ppc__)\n#   define SHA3_BYTEORDER    4321\n# else\n#   define SHA3_BYTEORDER 0\n# endif\n#endif\n\n\n/*\n** State structure for a SHA3 hash in progress\n*/\ntypedef struct SHA3Context SHA3Context;\nstruct SHA3Context {\n  union {\n    u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */\n    unsigned char x[1600];    /* ... or 1600 bytes */\n  } u;\n  unsigned nRate;        /* Bytes of input accepted per Keccak iteration */\n  unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */\n  unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */\n};\n\n/*\n** A single step of the Keccak mixing function for a 1600-bit state\n*/\nstatic void KeccakF1600Step(SHA3Context *p){\n  int i;\n  u64 b0, b1, b2, b3, b4;\n  u64 c0, c1, c2, c3, c4;\n  u64 d0, d1, d2, d3, d4;\n  static const u64 RC[] = {\n    0x0000000000000001ULL,  0x0000000000008082ULL,\n    0x800000000000808aULL,  0x8000000080008000ULL,\n    0x000000000000808bULL,  0x0000000080000001ULL,\n    0x8000000080008081ULL,  0x8000000000008009ULL,\n    0x000000000000008aULL,  0x0000000000000088ULL,\n    0x0000000080008009ULL,  0x000000008000000aULL,\n    0x000000008000808bULL,  0x800000000000008bULL,\n    0x8000000000008089ULL,  0x8000000000008003ULL,\n    0x8000000000008002ULL,  0x8000000000000080ULL,\n    0x000000000000800aULL,  0x800000008000000aULL,\n    0x8000000080008081ULL,  0x8000000000008080ULL,\n    0x0000000080000001ULL,  0x8000000080008008ULL\n  };\n# define a00 (p->u.s[0])\n# define a01 (p->u.s[1])\n# define a02 (p->u.s[2])\n# define a03 (p->u.s[3])\n# define a04 (p->u.s[4])\n# define a10 (p->u.s[5])\n# define a11 (p->u.s[6])\n# define a12 (p->u.s[7])\n# define a13 (p->u.s[8])\n# define a14 (p->u.s[9])\n# define a20 (p->u.s[10])\n# define a21 (p->u.s[11])\n# define a22 (p->u.s[12])\n# define a23 (p->u.s[13])\n# define a24 (p->u.s[14])\n# define a30 (p->u.s[15])\n# define a31 (p->u.s[16])\n# define a32 (p->u.s[17])\n# define a33 (p->u.s[18])\n# define a34 (p->u.s[19])\n# define a40 (p->u.s[20])\n# define a41 (p->u.s[21])\n# define a42 (p->u.s[22])\n# define a43 (p->u.s[23])\n# define a44 (p->u.s[24])\n# define ROL64(a,x) ((a<<x)|(a>>(64-x)))\n\n  for(i=0; i<24; i+=4){\n    c0 = a00^a10^a20^a30^a40;\n    c1 = a01^a11^a21^a31^a41;\n    c2 = a02^a12^a22^a32^a42;\n    c3 = a03^a13^a23^a33^a43;\n    c4 = a04^a14^a24^a34^a44;\n    d0 = c4^ROL64(c1, 1);\n    d1 = c0^ROL64(c2, 1);\n    d2 = c1^ROL64(c3, 1);\n    d3 = c2^ROL64(c4, 1);\n    d4 = c3^ROL64(c0, 1);\n\n    b0 = (a00^d0);\n    b1 = ROL64((a11^d1), 44);\n    b2 = ROL64((a22^d2), 43);\n    b3 = ROL64((a33^d3), 21);\n    b4 = ROL64((a44^d4), 14);\n    a00 =   b0 ^((~b1)&  b2 );\n    a00 ^= RC[i];\n    a11 =   b1 ^((~b2)&  b3 );\n    a22 =   b2 ^((~b3)&  b4 );\n    a33 =   b3 ^((~b4)&  b0 );\n    a44 =   b4 ^((~b0)&  b1 );\n\n    b2 = ROL64((a20^d0), 3);\n    b3 = ROL64((a31^d1), 45);\n    b4 = ROL64((a42^d2), 61);\n    b0 = ROL64((a03^d3), 28);\n    b1 = ROL64((a14^d4), 20);\n    a20 =   b0 ^((~b1)&  b2 );\n    a31 =   b1 ^((~b2)&  b3 );\n    a42 =   b2 ^((~b3)&  b4 );\n    a03 =   b3 ^((~b4)&  b0 );\n    a14 =   b4 ^((~b0)&  b1 );\n\n    b4 = ROL64((a40^d0), 18);\n    b0 = ROL64((a01^d1), 1);\n    b1 = ROL64((a12^d2), 6);\n    b2 = ROL64((a23^d3), 25);\n    b3 = ROL64((a34^d4), 8);\n    a40 =   b0 ^((~b1)&  b2 );\n    a01 =   b1 ^((~b2)&  b3 );\n    a12 =   b2 ^((~b3)&  b4 );\n    a23 =   b3 ^((~b4)&  b0 );\n    a34 =   b4 ^((~b0)&  b1 );\n\n    b1 = ROL64((a10^d0), 36);\n    b2 = ROL64((a21^d1), 10);\n    b3 = ROL64((a32^d2), 15);\n    b4 = ROL64((a43^d3), 56);\n    b0 = ROL64((a04^d4), 27);\n    a10 =   b0 ^((~b1)&  b2 );\n    a21 =   b1 ^((~b2)&  b3 );\n    a32 =   b2 ^((~b3)&  b4 );\n    a43 =   b3 ^((~b4)&  b0 );\n    a04 =   b4 ^((~b0)&  b1 );\n\n    b3 = ROL64((a30^d0), 41);\n    b4 = ROL64((a41^d1), 2);\n    b0 = ROL64((a02^d2), 62);\n    b1 = ROL64((a13^d3), 55);\n    b2 = ROL64((a24^d4), 39);\n    a30 =   b0 ^((~b1)&  b2 );\n    a41 =   b1 ^((~b2)&  b3 );\n    a02 =   b2 ^((~b3)&  b4 );\n    a13 =   b3 ^((~b4)&  b0 );\n    a24 =   b4 ^((~b0)&  b1 );\n\n    c0 = a00^a20^a40^a10^a30;\n    c1 = a11^a31^a01^a21^a41;\n    c2 = a22^a42^a12^a32^a02;\n    c3 = a33^a03^a23^a43^a13;\n    c4 = a44^a14^a34^a04^a24;\n    d0 = c4^ROL64(c1, 1);\n    d1 = c0^ROL64(c2, 1);\n    d2 = c1^ROL64(c3, 1);\n    d3 = c2^ROL64(c4, 1);\n    d4 = c3^ROL64(c0, 1);\n\n    b0 = (a00^d0);\n    b1 = ROL64((a31^d1), 44);\n    b2 = ROL64((a12^d2), 43);\n    b3 = ROL64((a43^d3), 21);\n    b4 = ROL64((a24^d4), 14);\n    a00 =   b0 ^((~b1)&  b2 );\n    a00 ^= RC[i+1];\n    a31 =   b1 ^((~b2)&  b3 );\n    a12 =   b2 ^((~b3)&  b4 );\n    a43 =   b3 ^((~b4)&  b0 );\n    a24 =   b4 ^((~b0)&  b1 );\n\n    b2 = ROL64((a40^d0), 3);\n    b3 = ROL64((a21^d1), 45);\n    b4 = ROL64((a02^d2), 61);\n    b0 = ROL64((a33^d3), 28);\n    b1 = ROL64((a14^d4), 20);\n    a40 =   b0 ^((~b1)&  b2 );\n    a21 =   b1 ^((~b2)&  b3 );\n    a02 =   b2 ^((~b3)&  b4 );\n    a33 =   b3 ^((~b4)&  b0 );\n    a14 =   b4 ^((~b0)&  b1 );\n\n    b4 = ROL64((a30^d0), 18);\n    b0 = ROL64((a11^d1), 1);\n    b1 = ROL64((a42^d2), 6);\n    b2 = ROL64((a23^d3), 25);\n    b3 = ROL64((a04^d4), 8);\n    a30 =   b0 ^((~b1)&  b2 );\n    a11 =   b1 ^((~b2)&  b3 );\n    a42 =   b2 ^((~b3)&  b4 );\n    a23 =   b3 ^((~b4)&  b0 );\n    a04 =   b4 ^((~b0)&  b1 );\n\n    b1 = ROL64((a20^d0), 36);\n    b2 = ROL64((a01^d1), 10);\n    b3 = ROL64((a32^d2), 15);\n    b4 = ROL64((a13^d3), 56);\n    b0 = ROL64((a44^d4), 27);\n    a20 =   b0 ^((~b1)&  b2 );\n    a01 =   b1 ^((~b2)&  b3 );\n    a32 =   b2 ^((~b3)&  b4 );\n    a13 =   b3 ^((~b4)&  b0 );\n    a44 =   b4 ^((~b0)&  b1 );\n\n    b3 = ROL64((a10^d0), 41);\n    b4 = ROL64((a41^d1), 2);\n    b0 = ROL64((a22^d2), 62);\n    b1 = ROL64((a03^d3), 55);\n    b2 = ROL64((a34^d4), 39);\n    a10 =   b0 ^((~b1)&  b2 );\n    a41 =   b1 ^((~b2)&  b3 );\n    a22 =   b2 ^((~b3)&  b4 );\n    a03 =   b3 ^((~b4)&  b0 );\n    a34 =   b4 ^((~b0)&  b1 );\n\n    c0 = a00^a40^a30^a20^a10;\n    c1 = a31^a21^a11^a01^a41;\n    c2 = a12^a02^a42^a32^a22;\n    c3 = a43^a33^a23^a13^a03;\n    c4 = a24^a14^a04^a44^a34;\n    d0 = c4^ROL64(c1, 1);\n    d1 = c0^ROL64(c2, 1);\n    d2 = c1^ROL64(c3, 1);\n    d3 = c2^ROL64(c4, 1);\n    d4 = c3^ROL64(c0, 1);\n\n    b0 = (a00^d0);\n    b1 = ROL64((a21^d1), 44);\n    b2 = ROL64((a42^d2), 43);\n    b3 = ROL64((a13^d3), 21);\n    b4 = ROL64((a34^d4), 14);\n    a00 =   b0 ^((~b1)&  b2 );\n    a00 ^= RC[i+2];\n    a21 =   b1 ^((~b2)&  b3 );\n    a42 =   b2 ^((~b3)&  b4 );\n    a13 =   b3 ^((~b4)&  b0 );\n    a34 =   b4 ^((~b0)&  b1 );\n\n    b2 = ROL64((a30^d0), 3);\n    b3 = ROL64((a01^d1), 45);\n    b4 = ROL64((a22^d2), 61);\n    b0 = ROL64((a43^d3), 28);\n    b1 = ROL64((a14^d4), 20);\n    a30 =   b0 ^((~b1)&  b2 );\n    a01 =   b1 ^((~b2)&  b3 );\n    a22 =   b2 ^((~b3)&  b4 );\n    a43 =   b3 ^((~b4)&  b0 );\n    a14 =   b4 ^((~b0)&  b1 );\n\n    b4 = ROL64((a10^d0), 18);\n    b0 = ROL64((a31^d1), 1);\n    b1 = ROL64((a02^d2), 6);\n    b2 = ROL64((a23^d3), 25);\n    b3 = ROL64((a44^d4), 8);\n    a10 =   b0 ^((~b1)&  b2 );\n    a31 =   b1 ^((~b2)&  b3 );\n    a02 =   b2 ^((~b3)&  b4 );\n    a23 =   b3 ^((~b4)&  b0 );\n    a44 =   b4 ^((~b0)&  b1 );\n\n    b1 = ROL64((a40^d0), 36);\n    b2 = ROL64((a11^d1), 10);\n    b3 = ROL64((a32^d2), 15);\n    b4 = ROL64((a03^d3), 56);\n    b0 = ROL64((a24^d4), 27);\n    a40 =   b0 ^((~b1)&  b2 );\n    a11 =   b1 ^((~b2)&  b3 );\n    a32 =   b2 ^((~b3)&  b4 );\n    a03 =   b3 ^((~b4)&  b0 );\n    a24 =   b4 ^((~b0)&  b1 );\n\n    b3 = ROL64((a20^d0), 41);\n    b4 = ROL64((a41^d1), 2);\n    b0 = ROL64((a12^d2), 62);\n    b1 = ROL64((a33^d3), 55);\n    b2 = ROL64((a04^d4), 39);\n    a20 =   b0 ^((~b1)&  b2 );\n    a41 =   b1 ^((~b2)&  b3 );\n    a12 =   b2 ^((~b3)&  b4 );\n    a33 =   b3 ^((~b4)&  b0 );\n    a04 =   b4 ^((~b0)&  b1 );\n\n    c0 = a00^a30^a10^a40^a20;\n    c1 = a21^a01^a31^a11^a41;\n    c2 = a42^a22^a02^a32^a12;\n    c3 = a13^a43^a23^a03^a33;\n    c4 = a34^a14^a44^a24^a04;\n    d0 = c4^ROL64(c1, 1);\n    d1 = c0^ROL64(c2, 1);\n    d2 = c1^ROL64(c3, 1);\n    d3 = c2^ROL64(c4, 1);\n    d4 = c3^ROL64(c0, 1);\n\n    b0 = (a00^d0);\n    b1 = ROL64((a01^d1), 44);\n    b2 = ROL64((a02^d2), 43);\n    b3 = ROL64((a03^d3), 21);\n    b4 = ROL64((a04^d4), 14);\n    a00 =   b0 ^((~b1)&  b2 );\n    a00 ^= RC[i+3];\n    a01 =   b1 ^((~b2)&  b3 );\n    a02 =   b2 ^((~b3)&  b4 );\n    a03 =   b3 ^((~b4)&  b0 );\n    a04 =   b4 ^((~b0)&  b1 );\n\n    b2 = ROL64((a10^d0), 3);\n    b3 = ROL64((a11^d1), 45);\n    b4 = ROL64((a12^d2), 61);\n    b0 = ROL64((a13^d3), 28);\n    b1 = ROL64((a14^d4), 20);\n    a10 =   b0 ^((~b1)&  b2 );\n    a11 =   b1 ^((~b2)&  b3 );\n    a12 =   b2 ^((~b3)&  b4 );\n    a13 =   b3 ^((~b4)&  b0 );\n    a14 =   b4 ^((~b0)&  b1 );\n\n    b4 = ROL64((a20^d0), 18);\n    b0 = ROL64((a21^d1), 1);\n    b1 = ROL64((a22^d2), 6);\n    b2 = ROL64((a23^d3), 25);\n    b3 = ROL64((a24^d4), 8);\n    a20 =   b0 ^((~b1)&  b2 );\n    a21 =   b1 ^((~b2)&  b3 );\n    a22 =   b2 ^((~b3)&  b4 );\n    a23 =   b3 ^((~b4)&  b0 );\n    a24 =   b4 ^((~b0)&  b1 );\n\n    b1 = ROL64((a30^d0), 36);\n    b2 = ROL64((a31^d1), 10);\n    b3 = ROL64((a32^d2), 15);\n    b4 = ROL64((a33^d3), 56);\n    b0 = ROL64((a34^d4), 27);\n    a30 =   b0 ^((~b1)&  b2 );\n    a31 =   b1 ^((~b2)&  b3 );\n    a32 =   b2 ^((~b3)&  b4 );\n    a33 =   b3 ^((~b4)&  b0 );\n    a34 =   b4 ^((~b0)&  b1 );\n\n    b3 = ROL64((a40^d0), 41);\n    b4 = ROL64((a41^d1), 2);\n    b0 = ROL64((a42^d2), 62);\n    b1 = ROL64((a43^d3), 55);\n    b2 = ROL64((a44^d4), 39);\n    a40 =   b0 ^((~b1)&  b2 );\n    a41 =   b1 ^((~b2)&  b3 );\n    a42 =   b2 ^((~b3)&  b4 );\n    a43 =   b3 ^((~b4)&  b0 );\n    a44 =   b4 ^((~b0)&  b1 );\n  }\n}\n\n/*\n** Initialize a new hash.  iSize determines the size of the hash\n** in bits and should be one of 224, 256, 384, or 512.  Or iSize\n** can be zero to use the default hash size of 256 bits.\n*/\nstatic void SHA3Init(SHA3Context *p, int iSize){\n  memset(p, 0, sizeof(*p));\n  if( iSize>=128 && iSize<=512 ){\n    p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;\n  }else{\n    p->nRate = (1600 - 2*256)/8;\n  }\n#if SHA3_BYTEORDER==1234\n  /* Known to be little-endian at compile-time. No-op */\n#elif SHA3_BYTEORDER==4321\n  p->ixMask = 7;  /* Big-endian */\n#else\n  {\n    static unsigned int one = 1;\n    if( 1==*(unsigned char*)&one ){\n      /* Little endian.  No byte swapping. */\n      p->ixMask = 0;\n    }else{\n      /* Big endian.  Byte swap. */\n      p->ixMask = 7;\n    }\n  }\n#endif\n}\n\n/*\n** Make consecutive calls to the SHA3Update function to add new content\n** to the hash\n*/\nstatic void SHA3Update(\n  SHA3Context *p,\n  const unsigned char *aData,\n  unsigned int nData\n){\n  unsigned int i = 0;\n#if SHA3_BYTEORDER==1234\n  if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){\n    for(; i+7<nData; i+=8){\n      p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];\n      p->nLoaded += 8;\n      if( p->nLoaded>=p->nRate ){\n        KeccakF1600Step(p);\n        p->nLoaded = 0;\n      }\n    }\n  }\n#endif\n  for(; i<nData; i++){\n#if SHA3_BYTEORDER==1234\n    p->u.x[p->nLoaded] ^= aData[i];\n#elif SHA3_BYTEORDER==4321\n    p->u.x[p->nLoaded^0x07] ^= aData[i];\n#else\n    p->u.x[p->nLoaded^p->ixMask] ^= aData[i];\n#endif\n    p->nLoaded++;\n    if( p->nLoaded==p->nRate ){\n      KeccakF1600Step(p);\n      p->nLoaded = 0;\n    }\n  }\n}\n\n/*\n** After all content has been added, invoke SHA3Final() to compute\n** the final hash.  The function returns a pointer to the binary\n** hash value.\n*/\nstatic unsigned char *SHA3Final(SHA3Context *p){\n  unsigned int i;\n  if( p->nLoaded==p->nRate-1 ){\n    const unsigned char c1 = 0x86;\n    SHA3Update(p, &c1, 1);\n  }else{\n    const unsigned char c2 = 0x06;\n    const unsigned char c3 = 0x80;\n    SHA3Update(p, &c2, 1);\n    p->nLoaded = p->nRate - 1;\n    SHA3Update(p, &c3, 1);\n  }\n  for(i=0; i<p->nRate; i++){\n    p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];\n  }\n  return &p->u.x[p->nRate];\n}\n/* End of the hashing logic\n*****************************************************************************/\n\n/*\n** Implementation of the sha3(X,SIZE) function.\n**\n** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default\n** size is 256.  If X is a BLOB, it is hashed as is.  \n** For all other non-NULL types of input, X is converted into a UTF-8 string\n** and the string is hashed without the trailing 0x00 terminator.  The hash\n** of a NULL value is NULL.\n*/\nstatic void sha3Func(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  SHA3Context cx;\n  int eType = sqlite3_value_type(argv[0]);\n  int nByte = sqlite3_value_bytes(argv[0]);\n  int iSize;\n  if( argc==1 ){\n    iSize = 256;\n  }else{\n    iSize = sqlite3_value_int(argv[1]);\n    if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){\n      sqlite3_result_error(context, \"SHA3 size should be one of: 224 256 \"\n                                    \"384 512\", -1);\n      return;\n    }\n  }\n  if( eType==SQLITE_NULL ) return;\n  SHA3Init(&cx, iSize);\n  if( eType==SQLITE_BLOB ){\n    SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);\n  }else{\n    SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);\n  }\n  sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);\n}\n\n/* Compute a string using sqlite3_vsnprintf() with a maximum length\n** of 50 bytes and add it to the hash.\n*/\nstatic void hash_step_vformat(\n  SHA3Context *p,                 /* Add content to this context */\n  const char *zFormat,\n  ...\n){\n  va_list ap;\n  int n;\n  char zBuf[50];\n  va_start(ap, zFormat);\n  sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);\n  va_end(ap);\n  n = (int)strlen(zBuf);\n  SHA3Update(p, (unsigned char*)zBuf, n);\n}\n\n/*\n** Implementation of the sha3_query(SQL,SIZE) function.\n**\n** This function compiles and runs the SQL statement(s) given in the\n** argument. The results are hashed using a SIZE-bit SHA3.  The default\n** size is 256.\n**\n** The format of the byte stream that is hashed is summarized as follows:\n**\n**       S<n>:<sql>\n**       R\n**       N\n**       I<int>\n**       F<ieee-float>\n**       B<size>:<bytes>\n**       T<size>:<text>\n**\n** <sql> is the original SQL text for each statement run and <n> is\n** the size of that text.  The SQL text is UTF-8.  A single R character\n** occurs before the start of each row.  N means a NULL value.\n** I mean an 8-byte little-endian integer <int>.  F is a floating point\n** number with an 8-byte little-endian IEEE floating point value <ieee-float>.\n** B means blobs of <size> bytes.  T means text rendered as <size>\n** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII\n** text integers.\n**\n** For each SQL statement in the X input, there is one S segment.  Each\n** S segment is followed by zero or more R segments, one for each row in the\n** result set.  After each R, there are one or more N, I, F, B, or T segments,\n** one for each column in the result set.  Segments are concatentated directly\n** with no delimiters of any kind.\n*/\nstatic void sha3QueryFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  const char *zSql = (const char*)sqlite3_value_text(argv[0]);\n  sqlite3_stmt *pStmt = 0;\n  int nCol;                   /* Number of columns in the result set */\n  int i;                      /* Loop counter */\n  int rc;\n  int n;\n  const char *z;\n  SHA3Context cx;\n  int iSize;\n\n  if( argc==1 ){\n    iSize = 256;\n  }else{\n    iSize = sqlite3_value_int(argv[1]);\n    if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){\n      sqlite3_result_error(context, \"SHA3 size should be one of: 224 256 \"\n                                    \"384 512\", -1);\n      return;\n    }\n  }\n  if( zSql==0 ) return;\n  SHA3Init(&cx, iSize);\n  while( zSql[0] ){\n    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);\n    if( rc ){\n      char *zMsg = sqlite3_mprintf(\"error SQL statement [%s]: %s\",\n                                   zSql, sqlite3_errmsg(db));\n      sqlite3_finalize(pStmt);\n      sqlite3_result_error(context, zMsg, -1);\n      sqlite3_free(zMsg);\n      return;\n    }\n    if( !sqlite3_stmt_readonly(pStmt) ){\n      char *zMsg = sqlite3_mprintf(\"non-query: [%s]\", sqlite3_sql(pStmt));\n      sqlite3_finalize(pStmt);\n      sqlite3_result_error(context, zMsg, -1);\n      sqlite3_free(zMsg);\n      return;\n    }\n    nCol = sqlite3_column_count(pStmt);\n    z = sqlite3_sql(pStmt);\n    n = (int)strlen(z);\n    hash_step_vformat(&cx,\"S%d:\",n);\n    SHA3Update(&cx,(unsigned char*)z,n);\n\n    /* Compute a hash over the result of the query */\n    while( SQLITE_ROW==sqlite3_step(pStmt) ){\n      SHA3Update(&cx,(const unsigned char*)\"R\",1);\n      for(i=0; i<nCol; i++){\n        switch( sqlite3_column_type(pStmt,i) ){\n          case SQLITE_NULL: {\n            SHA3Update(&cx, (const unsigned char*)\"N\",1);\n            break;\n          }\n          case SQLITE_INTEGER: {\n            sqlite3_uint64 u;\n            int j;\n            unsigned char x[9];\n            sqlite3_int64 v = sqlite3_column_int64(pStmt,i);\n            memcpy(&u, &v, 8);\n            for(j=8; j>=1; j--){\n              x[j] = u & 0xff;\n              u >>= 8;\n            }\n            x[0] = 'I';\n            SHA3Update(&cx, x, 9);\n            break;\n          }\n          case SQLITE_FLOAT: {\n            sqlite3_uint64 u;\n            int j;\n            unsigned char x[9];\n            double r = sqlite3_column_double(pStmt,i);\n            memcpy(&u, &r, 8);\n            for(j=8; j>=1; j--){\n              x[j] = u & 0xff;\n              u >>= 8;\n            }\n            x[0] = 'F';\n            SHA3Update(&cx,x,9);\n            break;\n          }\n          case SQLITE_TEXT: {\n            int n2 = sqlite3_column_bytes(pStmt, i);\n            const unsigned char *z2 = sqlite3_column_text(pStmt, i);\n            hash_step_vformat(&cx,\"T%d:\",n2);\n            SHA3Update(&cx, z2, n2);\n            break;\n          }\n          case SQLITE_BLOB: {\n            int n2 = sqlite3_column_bytes(pStmt, i);\n            const unsigned char *z2 = sqlite3_column_blob(pStmt, i);\n            hash_step_vformat(&cx,\"B%d:\",n2);\n            SHA3Update(&cx, z2, n2);\n            break;\n          }\n        }\n      }\n    }\n    sqlite3_finalize(pStmt);\n  }\n  sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);\n}\n\n\n#ifdef _WIN32\n\n#endif\nint sqlite3_shathree_init(\n  sqlite3 *db,\n  char **pzErrMsg,\n  const sqlite3_api_routines *pApi\n){\n  int rc = SQLITE_OK;\n  SQLITE_EXTENSION_INIT2(pApi);\n  (void)pzErrMsg;  /* Unused parameter */\n  rc = sqlite3_create_function(db, \"sha3\", 1,\n                      SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,\n                      0, sha3Func, 0, 0);\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_function(db, \"sha3\", 2,\n                      SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,\n                      0, sha3Func, 0, 0);\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_function(db, \"sha3_query\", 1,\n                      SQLITE_UTF8 | SQLITE_DIRECTONLY,\n                      0, sha3QueryFunc, 0, 0);\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_function(db, \"sha3_query\", 2,\n                      SQLITE_UTF8 | SQLITE_DIRECTONLY,\n                      0, sha3QueryFunc, 0, 0);\n  }\n  return rc;\n}\n\n/************************* End ../ext/misc/shathree.c ********************/\n/************************* Begin ../ext/misc/fileio.c ******************/\n/*\n** 2014-06-13\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This SQLite extension implements SQL functions readfile() and\n** writefile(), and eponymous virtual type \"fsdir\".\n**\n** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):\n**\n**   If neither of the optional arguments is present, then this UDF\n**   function writes blob DATA to file FILE. If successful, the number\n**   of bytes written is returned. If an error occurs, NULL is returned.\n**\n**   If the first option argument - MODE - is present, then it must\n**   be passed an integer value that corresponds to a POSIX mode\n**   value (file type + permissions, as returned in the stat.st_mode\n**   field by the stat() system call). Three types of files may\n**   be written/created:\n**\n**     regular files:  (mode & 0170000)==0100000\n**     symbolic links: (mode & 0170000)==0120000\n**     directories:    (mode & 0170000)==0040000\n**\n**   For a directory, the DATA is ignored. For a symbolic link, it is\n**   interpreted as text and used as the target of the link. For a\n**   regular file, it is interpreted as a blob and written into the\n**   named file. Regardless of the type of file, its permissions are\n**   set to (mode & 0777) before returning.\n**\n**   If the optional MTIME argument is present, then it is interpreted\n**   as an integer - the number of seconds since the unix epoch. The\n**   modification-time of the target file is set to this value before\n**   returning.\n**\n**   If three or more arguments are passed to this function and an\n**   error is encountered, an exception is raised.\n**\n** READFILE(FILE):\n**\n**   Read and return the contents of file FILE (type blob) from disk.\n**\n** FSDIR:\n**\n**   Used as follows:\n**\n**     SELECT * FROM fsdir($path [, $dir]);\n**\n**   Parameter $path is an absolute or relative pathname. If the file that it\n**   refers to does not exist, it is an error. If the path refers to a regular\n**   file or symbolic link, it returns a single row. Or, if the path refers\n**   to a directory, it returns one row for the directory, and one row for each\n**   file within the hierarchy rooted at $path.\n**\n**   Each row has the following columns:\n**\n**     name:  Path to file or directory (text value).\n**     mode:  Value of stat.st_mode for directory entry (an integer).\n**     mtime: Value of stat.st_mtime for directory entry (an integer).\n**     data:  For a regular file, a blob containing the file data. For a\n**            symlink, a text value containing the text of the link. For a\n**            directory, NULL.\n**\n**   If a non-NULL value is specified for the optional $dir parameter and\n**   $path is a relative path, then $path is interpreted relative to $dir. \n**   And the paths returned in the \"name\" column of the table are also \n**   relative to directory $dir.\n*/\n/* #include \"sqlite3ext.h\" */\nSQLITE_EXTENSION_INIT1\n#include <stdio.h>\n#include <string.h>\n#include <assert.h>\n\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#if !defined(_WIN32) && !defined(WIN32)\n#  include <unistd.h>\n#  include <dirent.h>\n#  include <utime.h>\n#  include <sys/time.h>\n#else\n#  include \"windows.h\"\n#  include <io.h>\n#  include <direct.h>\n/* #  include \"test_windirent.h\" */\n#  define dirent DIRENT\n#  ifndef chmod\n#    define chmod _chmod\n#  endif\n#  ifndef stat\n#    define stat _stat\n#  endif\n#  define mkdir(path,mode) _mkdir(path)\n#  define lstat(path,buf) stat(path,buf)\n#endif\n#include <time.h>\n#include <errno.h>\n\n\n/*\n** Structure of the fsdir() table-valued function\n*/\n                 /*    0    1    2     3    4           5             */\n#define FSDIR_SCHEMA \"(name,mode,mtime,data,path HIDDEN,dir HIDDEN)\"\n#define FSDIR_COLUMN_NAME     0     /* Name of the file */\n#define FSDIR_COLUMN_MODE     1     /* Access mode */\n#define FSDIR_COLUMN_MTIME    2     /* Last modification time */\n#define FSDIR_COLUMN_DATA     3     /* File content */\n#define FSDIR_COLUMN_PATH     4     /* Path to top of search */\n#define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */\n\n\n/*\n** Set the result stored by context ctx to a blob containing the \n** contents of file zName.  Or, leave the result unchanged (NULL)\n** if the file does not exist or is unreadable.\n**\n** If the file exceeds the SQLite blob size limit, through an\n** SQLITE_TOOBIG error.\n**\n** Throw an SQLITE_IOERR if there are difficulties pulling the file\n** off of disk.\n*/\nstatic void readFileContents(sqlite3_context *ctx, const char *zName){\n  FILE *in;\n  sqlite3_int64 nIn;\n  void *pBuf;\n  sqlite3 *db;\n  int mxBlob;\n\n  in = fopen(zName, \"rb\");\n  if( in==0 ){\n    /* File does not exist or is unreadable. Leave the result set to NULL. */\n    return;\n  }\n  fseek(in, 0, SEEK_END);\n  nIn = ftell(in);\n  rewind(in);\n  db = sqlite3_context_db_handle(ctx);\n  mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);\n  if( nIn>mxBlob ){\n    sqlite3_result_error_code(ctx, SQLITE_TOOBIG);\n    fclose(in);\n    return;\n  }\n  pBuf = sqlite3_malloc64( nIn ? nIn : 1 );\n  if( pBuf==0 ){\n    sqlite3_result_error_nomem(ctx);\n    fclose(in);\n    return;\n  }\n  if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){\n    sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);\n  }else{\n    sqlite3_result_error_code(ctx, SQLITE_IOERR);\n    sqlite3_free(pBuf);\n  }\n  fclose(in);\n}\n\n/*\n** Implementation of the \"readfile(X)\" SQL function.  The entire content\n** of the file named X is read and returned as a BLOB.  NULL is returned\n** if the file does not exist or is unreadable.\n*/\nstatic void readfileFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  const char *zName;\n  (void)(argc);  /* Unused parameter */\n  zName = (const char*)sqlite3_value_text(argv[0]);\n  if( zName==0 ) return;\n  readFileContents(context, zName);\n}\n\n/*\n** Set the error message contained in context ctx to the results of\n** vprintf(zFmt, ...).\n*/\nstatic void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){\n  char *zMsg = 0;\n  va_list ap;\n  va_start(ap, zFmt);\n  zMsg = sqlite3_vmprintf(zFmt, ap);\n  sqlite3_result_error(ctx, zMsg, -1);\n  sqlite3_free(zMsg);\n  va_end(ap);\n}\n\n#if defined(_WIN32)\n/*\n** This function is designed to convert a Win32 FILETIME structure into the\n** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).\n*/\nstatic sqlite3_uint64 fileTimeToUnixTime(\n  LPFILETIME pFileTime\n){\n  SYSTEMTIME epochSystemTime;\n  ULARGE_INTEGER epochIntervals;\n  FILETIME epochFileTime;\n  ULARGE_INTEGER fileIntervals;\n\n  memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));\n  epochSystemTime.wYear = 1970;\n  epochSystemTime.wMonth = 1;\n  epochSystemTime.wDay = 1;\n  SystemTimeToFileTime(&epochSystemTime, &epochFileTime);\n  epochIntervals.LowPart = epochFileTime.dwLowDateTime;\n  epochIntervals.HighPart = epochFileTime.dwHighDateTime;\n\n  fileIntervals.LowPart = pFileTime->dwLowDateTime;\n  fileIntervals.HighPart = pFileTime->dwHighDateTime;\n\n  return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;\n}\n\n/*\n** This function attempts to normalize the time values found in the stat()\n** buffer to UTC.  This is necessary on Win32, where the runtime library\n** appears to return these values as local times.\n*/\nstatic void statTimesToUtc(\n  const char *zPath,\n  struct stat *pStatBuf\n){\n  HANDLE hFindFile;\n  WIN32_FIND_DATAW fd;\n  LPWSTR zUnicodeName;\n  extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);\n  zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);\n  if( zUnicodeName ){\n    memset(&fd, 0, sizeof(WIN32_FIND_DATAW));\n    hFindFile = FindFirstFileW(zUnicodeName, &fd);\n    if( hFindFile!=NULL ){\n      pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);\n      pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);\n      pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);\n      FindClose(hFindFile);\n    }\n    sqlite3_free(zUnicodeName);\n  }\n}\n#endif\n\n/*\n** This function is used in place of stat().  On Windows, special handling\n** is required in order for the included time to be returned as UTC.  On all\n** other systems, this function simply calls stat().\n*/\nstatic int fileStat(\n  const char *zPath,\n  struct stat *pStatBuf\n){\n#if defined(_WIN32)\n  int rc = stat(zPath, pStatBuf);\n  if( rc==0 ) statTimesToUtc(zPath, pStatBuf);\n  return rc;\n#else\n  return stat(zPath, pStatBuf);\n#endif\n}\n\n/*\n** This function is used in place of lstat().  On Windows, special handling\n** is required in order for the included time to be returned as UTC.  On all\n** other systems, this function simply calls lstat().\n*/\nstatic int fileLinkStat(\n  const char *zPath,\n  struct stat *pStatBuf\n){\n#if defined(_WIN32)\n  int rc = lstat(zPath, pStatBuf);\n  if( rc==0 ) statTimesToUtc(zPath, pStatBuf);\n  return rc;\n#else\n  return lstat(zPath, pStatBuf);\n#endif\n}\n\n/*\n** Argument zFile is the name of a file that will be created and/or written\n** by SQL function writefile(). This function ensures that the directory\n** zFile will be written to exists, creating it if required. The permissions\n** for any path components created by this function are set in accordance\n** with the current umask.\n**\n** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,\n** SQLITE_OK is returned if the directory is successfully created, or\n** SQLITE_ERROR otherwise.\n*/\nstatic int makeDirectory(\n  const char *zFile\n){\n  char *zCopy = sqlite3_mprintf(\"%s\", zFile);\n  int rc = SQLITE_OK;\n\n  if( zCopy==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    int nCopy = (int)strlen(zCopy);\n    int i = 1;\n\n    while( rc==SQLITE_OK ){\n      struct stat sStat;\n      int rc2;\n\n      for(; zCopy[i]!='/' && i<nCopy; i++);\n      if( i==nCopy ) break;\n      zCopy[i] = '\\0';\n\n      rc2 = fileStat(zCopy, &sStat);\n      if( rc2!=0 ){\n        if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;\n      }else{\n        if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;\n      }\n      zCopy[i] = '/';\n      i++;\n    }\n\n    sqlite3_free(zCopy);\n  }\n\n  return rc;\n}\n\n/*\n** This function does the work for the writefile() UDF. Refer to \n** header comments at the top of this file for details.\n*/\nstatic int writeFile(\n  sqlite3_context *pCtx,          /* Context to return bytes written in */\n  const char *zFile,              /* File to write */\n  sqlite3_value *pData,           /* Data to write */\n  mode_t mode,                    /* MODE parameter passed to writefile() */\n  sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */\n){\n#if !defined(_WIN32) && !defined(WIN32)\n  if( S_ISLNK(mode) ){\n    const char *zTo = (const char*)sqlite3_value_text(pData);\n    if( symlink(zTo, zFile)<0 ) return 1;\n  }else\n#endif\n  {\n    if( S_ISDIR(mode) ){\n      if( mkdir(zFile, mode) ){\n        /* The mkdir() call to create the directory failed. This might not\n        ** be an error though - if there is already a directory at the same\n        ** path and either the permissions already match or can be changed\n        ** to do so using chmod(), it is not an error.  */\n        struct stat sStat;\n        if( errno!=EEXIST\n         || 0!=fileStat(zFile, &sStat)\n         || !S_ISDIR(sStat.st_mode)\n         || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))\n        ){\n          return 1;\n        }\n      }\n    }else{\n      sqlite3_int64 nWrite = 0;\n      const char *z;\n      int rc = 0;\n      FILE *out = fopen(zFile, \"wb\");\n      if( out==0 ) return 1;\n      z = (const char*)sqlite3_value_blob(pData);\n      if( z ){\n        sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);\n        nWrite = sqlite3_value_bytes(pData);\n        if( nWrite!=n ){\n          rc = 1;\n        }\n      }\n      fclose(out);\n      if( rc==0 && mode && chmod(zFile, mode & 0777) ){\n        rc = 1;\n      }\n      if( rc ) return 2;\n      sqlite3_result_int64(pCtx, nWrite);\n    }\n  }\n\n  if( mtime>=0 ){\n#if defined(_WIN32)\n#if !SQLITE_OS_WINRT\n    /* Windows */\n    FILETIME lastAccess;\n    FILETIME lastWrite;\n    SYSTEMTIME currentTime;\n    LONGLONG intervals;\n    HANDLE hFile;\n    LPWSTR zUnicodeName;\n    extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);\n\n    GetSystemTime(&currentTime);\n    SystemTimeToFileTime(&currentTime, &lastAccess);\n    intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;\n    lastWrite.dwLowDateTime = (DWORD)intervals;\n    lastWrite.dwHighDateTime = intervals >> 32;\n    zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);\n    if( zUnicodeName==0 ){\n      return 1;\n    }\n    hFile = CreateFileW(\n      zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,\n      FILE_FLAG_BACKUP_SEMANTICS, NULL\n    );\n    sqlite3_free(zUnicodeName);\n    if( hFile!=INVALID_HANDLE_VALUE ){\n      BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);\n      CloseHandle(hFile);\n      return !bResult;\n    }else{\n      return 1;\n    }\n#endif\n#elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */\n    /* Recent unix */\n    struct timespec times[2];\n    times[0].tv_nsec = times[1].tv_nsec = 0;\n    times[0].tv_sec = time(0);\n    times[1].tv_sec = mtime;\n    if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){\n      return 1;\n    }\n#else\n    /* Legacy unix */\n    struct timeval times[2];\n    times[0].tv_usec = times[1].tv_usec = 0;\n    times[0].tv_sec = time(0);\n    times[1].tv_sec = mtime;\n    if( utimes(zFile, times) ){\n      return 1;\n    }\n#endif\n  }\n\n  return 0;\n}\n\n/*\n** Implementation of the \"writefile(W,X[,Y[,Z]]])\" SQL function.  \n** Refer to header comments at the top of this file for details.\n*/\nstatic void writefileFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  const char *zFile;\n  mode_t mode = 0;\n  int res;\n  sqlite3_int64 mtime = -1;\n\n  if( argc<2 || argc>4 ){\n    sqlite3_result_error(context, \n        \"wrong number of arguments to function writefile()\", -1\n    );\n    return;\n  }\n\n  zFile = (const char*)sqlite3_value_text(argv[0]);\n  if( zFile==0 ) return;\n  if( argc>=3 ){\n    mode = (mode_t)sqlite3_value_int(argv[2]);\n  }\n  if( argc==4 ){\n    mtime = sqlite3_value_int64(argv[3]);\n  }\n\n  res = writeFile(context, zFile, argv[1], mode, mtime);\n  if( res==1 && errno==ENOENT ){\n    if( makeDirectory(zFile)==SQLITE_OK ){\n      res = writeFile(context, zFile, argv[1], mode, mtime);\n    }\n  }\n\n  if( argc>2 && res!=0 ){\n    if( S_ISLNK(mode) ){\n      ctxErrorMsg(context, \"failed to create symlink: %s\", zFile);\n    }else if( S_ISDIR(mode) ){\n      ctxErrorMsg(context, \"failed to create directory: %s\", zFile);\n    }else{\n      ctxErrorMsg(context, \"failed to write file: %s\", zFile);\n    }\n  }\n}\n\n/*\n** SQL function:   lsmode(MODE)\n**\n** Given a numberic st_mode from stat(), convert it into a human-readable\n** text string in the style of \"ls -l\".\n*/\nstatic void lsModeFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  int i;\n  int iMode = sqlite3_value_int(argv[0]);\n  char z[16];\n  (void)argc;\n  if( S_ISLNK(iMode) ){\n    z[0] = 'l';\n  }else if( S_ISREG(iMode) ){\n    z[0] = '-';\n  }else if( S_ISDIR(iMode) ){\n    z[0] = 'd';\n  }else{\n    z[0] = '?';\n  }\n  for(i=0; i<3; i++){\n    int m = (iMode >> ((2-i)*3));\n    char *a = &z[1 + i*3];\n    a[0] = (m & 0x4) ? 'r' : '-';\n    a[1] = (m & 0x2) ? 'w' : '-';\n    a[2] = (m & 0x1) ? 'x' : '-';\n  }\n  z[10] = '\\0';\n  sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);\n}\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n\n/* \n** Cursor type for recursively iterating through a directory structure.\n*/\ntypedef struct fsdir_cursor fsdir_cursor;\ntypedef struct FsdirLevel FsdirLevel;\n\nstruct FsdirLevel {\n  DIR *pDir;                 /* From opendir() */\n  char *zDir;                /* Name of directory (nul-terminated) */\n};\n\nstruct fsdir_cursor {\n  sqlite3_vtab_cursor base;  /* Base class - must be first */\n\n  int nLvl;                  /* Number of entries in aLvl[] array */\n  int iLvl;                  /* Index of current entry */\n  FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */\n\n  const char *zBase;\n  int nBase;\n\n  struct stat sStat;         /* Current lstat() results */\n  char *zPath;               /* Path to current entry */\n  sqlite3_int64 iRowid;      /* Current rowid */\n};\n\ntypedef struct fsdir_tab fsdir_tab;\nstruct fsdir_tab {\n  sqlite3_vtab base;         /* Base class - must be first */\n};\n\n/*\n** Construct a new fsdir virtual table object.\n*/\nstatic int fsdirConnect(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  fsdir_tab *pNew = 0;\n  int rc;\n  (void)pAux;\n  (void)argc;\n  (void)argv;\n  (void)pzErr;\n  rc = sqlite3_declare_vtab(db, \"CREATE TABLE x\" FSDIR_SCHEMA);\n  if( rc==SQLITE_OK ){\n    pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );\n    if( pNew==0 ) return SQLITE_NOMEM;\n    memset(pNew, 0, sizeof(*pNew));\n    sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);\n  }\n  *ppVtab = (sqlite3_vtab*)pNew;\n  return rc;\n}\n\n/*\n** This method is the destructor for fsdir vtab objects.\n*/\nstatic int fsdirDisconnect(sqlite3_vtab *pVtab){\n  sqlite3_free(pVtab);\n  return SQLITE_OK;\n}\n\n/*\n** Constructor for a new fsdir_cursor object.\n*/\nstatic int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){\n  fsdir_cursor *pCur;\n  (void)p;\n  pCur = sqlite3_malloc( sizeof(*pCur) );\n  if( pCur==0 ) return SQLITE_NOMEM;\n  memset(pCur, 0, sizeof(*pCur));\n  pCur->iLvl = -1;\n  *ppCursor = &pCur->base;\n  return SQLITE_OK;\n}\n\n/*\n** Reset a cursor back to the state it was in when first returned\n** by fsdirOpen().\n*/\nstatic void fsdirResetCursor(fsdir_cursor *pCur){\n  int i;\n  for(i=0; i<=pCur->iLvl; i++){\n    FsdirLevel *pLvl = &pCur->aLvl[i];\n    if( pLvl->pDir ) closedir(pLvl->pDir);\n    sqlite3_free(pLvl->zDir);\n  }\n  sqlite3_free(pCur->zPath);\n  sqlite3_free(pCur->aLvl);\n  pCur->aLvl = 0;\n  pCur->zPath = 0;\n  pCur->zBase = 0;\n  pCur->nBase = 0;\n  pCur->nLvl = 0;\n  pCur->iLvl = -1;\n  pCur->iRowid = 1;\n}\n\n/*\n** Destructor for an fsdir_cursor.\n*/\nstatic int fsdirClose(sqlite3_vtab_cursor *cur){\n  fsdir_cursor *pCur = (fsdir_cursor*)cur;\n\n  fsdirResetCursor(pCur);\n  sqlite3_free(pCur);\n  return SQLITE_OK;\n}\n\n/*\n** Set the error message for the virtual table associated with cursor\n** pCur to the results of vprintf(zFmt, ...).\n*/\nstatic void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){\n  va_list ap;\n  va_start(ap, zFmt);\n  pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);\n  va_end(ap);\n}\n\n\n/*\n** Advance an fsdir_cursor to its next row of output.\n*/\nstatic int fsdirNext(sqlite3_vtab_cursor *cur){\n  fsdir_cursor *pCur = (fsdir_cursor*)cur;\n  mode_t m = pCur->sStat.st_mode;\n\n  pCur->iRowid++;\n  if( S_ISDIR(m) ){\n    /* Descend into this directory */\n    int iNew = pCur->iLvl + 1;\n    FsdirLevel *pLvl;\n    if( iNew>=pCur->nLvl ){\n      int nNew = iNew+1;\n      sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);\n      FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);\n      if( aNew==0 ) return SQLITE_NOMEM;\n      memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));\n      pCur->aLvl = aNew;\n      pCur->nLvl = nNew;\n    }\n    pCur->iLvl = iNew;\n    pLvl = &pCur->aLvl[iNew];\n    \n    pLvl->zDir = pCur->zPath;\n    pCur->zPath = 0;\n    pLvl->pDir = opendir(pLvl->zDir);\n    if( pLvl->pDir==0 ){\n      fsdirSetErrmsg(pCur, \"cannot read directory: %s\", pCur->zPath);\n      return SQLITE_ERROR;\n    }\n  }\n\n  while( pCur->iLvl>=0 ){\n    FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];\n    struct dirent *pEntry = readdir(pLvl->pDir);\n    if( pEntry ){\n      if( pEntry->d_name[0]=='.' ){\n       if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\\0' ) continue;\n       if( pEntry->d_name[1]=='\\0' ) continue;\n      }\n      sqlite3_free(pCur->zPath);\n      pCur->zPath = sqlite3_mprintf(\"%s/%s\", pLvl->zDir, pEntry->d_name);\n      if( pCur->zPath==0 ) return SQLITE_NOMEM;\n      if( fileLinkStat(pCur->zPath, &pCur->sStat) ){\n        fsdirSetErrmsg(pCur, \"cannot stat file: %s\", pCur->zPath);\n        return SQLITE_ERROR;\n      }\n      return SQLITE_OK;\n    }\n    closedir(pLvl->pDir);\n    sqlite3_free(pLvl->zDir);\n    pLvl->pDir = 0;\n    pLvl->zDir = 0;\n    pCur->iLvl--;\n  }\n\n  /* EOF */\n  sqlite3_free(pCur->zPath);\n  pCur->zPath = 0;\n  return SQLITE_OK;\n}\n\n/*\n** Return values of columns for the row at which the series_cursor\n** is currently pointing.\n*/\nstatic int fsdirColumn(\n  sqlite3_vtab_cursor *cur,   /* The cursor */\n  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */\n  int i                       /* Which column to return */\n){\n  fsdir_cursor *pCur = (fsdir_cursor*)cur;\n  switch( i ){\n    case FSDIR_COLUMN_NAME: {\n      sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);\n      break;\n    }\n\n    case FSDIR_COLUMN_MODE:\n      sqlite3_result_int64(ctx, pCur->sStat.st_mode);\n      break;\n\n    case FSDIR_COLUMN_MTIME:\n      sqlite3_result_int64(ctx, pCur->sStat.st_mtime);\n      break;\n\n    case FSDIR_COLUMN_DATA: {\n      mode_t m = pCur->sStat.st_mode;\n      if( S_ISDIR(m) ){\n        sqlite3_result_null(ctx);\n#if !defined(_WIN32) && !defined(WIN32)\n      }else if( S_ISLNK(m) ){\n        char aStatic[64];\n        char *aBuf = aStatic;\n        sqlite3_int64 nBuf = 64;\n        int n;\n\n        while( 1 ){\n          n = readlink(pCur->zPath, aBuf, nBuf);\n          if( n<nBuf ) break;\n          if( aBuf!=aStatic ) sqlite3_free(aBuf);\n          nBuf = nBuf*2;\n          aBuf = sqlite3_malloc64(nBuf);\n          if( aBuf==0 ){\n            sqlite3_result_error_nomem(ctx);\n            return SQLITE_NOMEM;\n          }\n        }\n\n        sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);\n        if( aBuf!=aStatic ) sqlite3_free(aBuf);\n#endif\n      }else{\n        readFileContents(ctx, pCur->zPath);\n      }\n    }\n    case FSDIR_COLUMN_PATH:\n    default: {\n      /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.\n      ** always return their values as NULL */\n      break;\n    }\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Return the rowid for the current row. In this implementation, the\n** first row returned is assigned rowid value 1, and each subsequent\n** row a value 1 more than that of the previous.\n*/\nstatic int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){\n  fsdir_cursor *pCur = (fsdir_cursor*)cur;\n  *pRowid = pCur->iRowid;\n  return SQLITE_OK;\n}\n\n/*\n** Return TRUE if the cursor has been moved off of the last\n** row of output.\n*/\nstatic int fsdirEof(sqlite3_vtab_cursor *cur){\n  fsdir_cursor *pCur = (fsdir_cursor*)cur;\n  return (pCur->zPath==0);\n}\n\n/*\n** xFilter callback.\n**\n** idxNum==1   PATH parameter only\n** idxNum==2   Both PATH and DIR supplied\n*/\nstatic int fsdirFilter(\n  sqlite3_vtab_cursor *cur, \n  int idxNum, const char *idxStr,\n  int argc, sqlite3_value **argv\n){\n  const char *zDir = 0;\n  fsdir_cursor *pCur = (fsdir_cursor*)cur;\n  (void)idxStr;\n  fsdirResetCursor(pCur);\n\n  if( idxNum==0 ){\n    fsdirSetErrmsg(pCur, \"table function fsdir requires an argument\");\n    return SQLITE_ERROR;\n  }\n\n  assert( argc==idxNum && (argc==1 || argc==2) );\n  zDir = (const char*)sqlite3_value_text(argv[0]);\n  if( zDir==0 ){\n    fsdirSetErrmsg(pCur, \"table function fsdir requires a non-NULL argument\");\n    return SQLITE_ERROR;\n  }\n  if( argc==2 ){\n    pCur->zBase = (const char*)sqlite3_value_text(argv[1]);\n  }\n  if( pCur->zBase ){\n    pCur->nBase = (int)strlen(pCur->zBase)+1;\n    pCur->zPath = sqlite3_mprintf(\"%s/%s\", pCur->zBase, zDir);\n  }else{\n    pCur->zPath = sqlite3_mprintf(\"%s\", zDir);\n  }\n\n  if( pCur->zPath==0 ){\n    return SQLITE_NOMEM;\n  }\n  if( fileLinkStat(pCur->zPath, &pCur->sStat) ){\n    fsdirSetErrmsg(pCur, \"cannot stat file: %s\", pCur->zPath);\n    return SQLITE_ERROR;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** SQLite will invoke this method one or more times while planning a query\n** that uses the generate_series virtual table.  This routine needs to create\n** a query plan for each invocation and compute an estimated cost for that\n** plan.\n**\n** In this implementation idxNum is used to represent the\n** query plan.  idxStr is unused.\n**\n** The query plan is represented by values of idxNum:\n**\n**  (1)  The path value is supplied by argv[0]\n**  (2)  Path is in argv[0] and dir is in argv[1]\n*/\nstatic int fsdirBestIndex(\n  sqlite3_vtab *tab,\n  sqlite3_index_info *pIdxInfo\n){\n  int i;                 /* Loop over constraints */\n  int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */\n  int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */\n  int seenPath = 0;      /* True if an unusable PATH= constraint is seen */\n  int seenDir = 0;       /* True if an unusable DIR= constraint is seen */\n  const struct sqlite3_index_constraint *pConstraint;\n\n  (void)tab;\n  pConstraint = pIdxInfo->aConstraint;\n  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){\n    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;\n    switch( pConstraint->iColumn ){\n      case FSDIR_COLUMN_PATH: {\n        if( pConstraint->usable ){\n          idxPath = i;\n          seenPath = 0;\n        }else if( idxPath<0 ){\n          seenPath = 1;\n        }\n        break;\n      }\n      case FSDIR_COLUMN_DIR: {\n        if( pConstraint->usable ){\n          idxDir = i;\n          seenDir = 0;\n        }else if( idxDir<0 ){\n          seenDir = 1;\n        }\n        break;\n      }\n    } \n  }\n  if( seenPath || seenDir ){\n    /* If input parameters are unusable, disallow this plan */\n    return SQLITE_CONSTRAINT;\n  }\n\n  if( idxPath<0 ){\n    pIdxInfo->idxNum = 0;\n    /* The pIdxInfo->estimatedCost should have been initialized to a huge\n    ** number.  Leave it unchanged. */\n    pIdxInfo->estimatedRows = 0x7fffffff;\n  }else{\n    pIdxInfo->aConstraintUsage[idxPath].omit = 1;\n    pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;\n    if( idxDir>=0 ){\n      pIdxInfo->aConstraintUsage[idxDir].omit = 1;\n      pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;\n      pIdxInfo->idxNum = 2;\n      pIdxInfo->estimatedCost = 10.0;\n    }else{\n      pIdxInfo->idxNum = 1;\n      pIdxInfo->estimatedCost = 100.0;\n    }\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Register the \"fsdir\" virtual table.\n*/\nstatic int fsdirRegister(sqlite3 *db){\n  static sqlite3_module fsdirModule = {\n    0,                         /* iVersion */\n    0,                         /* xCreate */\n    fsdirConnect,              /* xConnect */\n    fsdirBestIndex,            /* xBestIndex */\n    fsdirDisconnect,           /* xDisconnect */\n    0,                         /* xDestroy */\n    fsdirOpen,                 /* xOpen - open a cursor */\n    fsdirClose,                /* xClose - close a cursor */\n    fsdirFilter,               /* xFilter - configure scan constraints */\n    fsdirNext,                 /* xNext - advance a cursor */\n    fsdirEof,                  /* xEof - check for end of scan */\n    fsdirColumn,               /* xColumn - read data */\n    fsdirRowid,                /* xRowid - read data */\n    0,                         /* xUpdate */\n    0,                         /* xBegin */\n    0,                         /* xSync */\n    0,                         /* xCommit */\n    0,                         /* xRollback */\n    0,                         /* xFindMethod */\n    0,                         /* xRename */\n    0,                         /* xSavepoint */\n    0,                         /* xRelease */\n    0,                         /* xRollbackTo */\n    0,                         /* xShadowName */\n  };\n\n  int rc = sqlite3_create_module(db, \"fsdir\", &fsdirModule, 0);\n  return rc;\n}\n#else         /* SQLITE_OMIT_VIRTUALTABLE */\n# define fsdirRegister(x) SQLITE_OK\n#endif\n\n#ifdef _WIN32\n\n#endif\nint sqlite3_fileio_init(\n  sqlite3 *db, \n  char **pzErrMsg, \n  const sqlite3_api_routines *pApi\n){\n  int rc = SQLITE_OK;\n  SQLITE_EXTENSION_INIT2(pApi);\n  (void)pzErrMsg;  /* Unused parameter */\n  rc = sqlite3_create_function(db, \"readfile\", 1, \n                               SQLITE_UTF8|SQLITE_DIRECTONLY, 0,\n                               readfileFunc, 0, 0);\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_function(db, \"writefile\", -1,\n                                 SQLITE_UTF8|SQLITE_DIRECTONLY, 0,\n                                 writefileFunc, 0, 0);\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_function(db, \"lsmode\", 1, SQLITE_UTF8, 0,\n                                 lsModeFunc, 0, 0);\n  }\n  if( rc==SQLITE_OK ){\n    rc = fsdirRegister(db);\n  }\n  return rc;\n}\n\n/************************* End ../ext/misc/fileio.c ********************/\n/************************* Begin ../ext/misc/completion.c ******************/\n/*\n** 2017-07-10\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file implements an eponymous virtual table that returns suggested\n** completions for a partial SQL input.\n**\n** Suggested usage:\n**\n**     SELECT DISTINCT candidate COLLATE nocase\n**       FROM completion($prefix,$wholeline)\n**      ORDER BY 1;\n**\n** The two query parameters are optional.  $prefix is the text of the\n** current word being typed and that is to be completed.  $wholeline is\n** the complete input line, used for context.\n**\n** The raw completion() table might return the same candidate multiple\n** times, for example if the same column name is used to two or more\n** tables.  And the candidates are returned in an arbitrary order.  Hence,\n** the DISTINCT and ORDER BY are recommended.\n**\n** This virtual table operates at the speed of human typing, and so there\n** is no attempt to make it fast.  Even a slow implementation will be much\n** faster than any human can type.\n**\n*/\n/* #include \"sqlite3ext.h\" */\nSQLITE_EXTENSION_INIT1\n#include <assert.h>\n#include <string.h>\n#include <ctype.h>\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n\n/* completion_vtab is a subclass of sqlite3_vtab which will\n** serve as the underlying representation of a completion virtual table\n*/\ntypedef struct completion_vtab completion_vtab;\nstruct completion_vtab {\n  sqlite3_vtab base;  /* Base class - must be first */\n  sqlite3 *db;        /* Database connection for this completion vtab */\n};\n\n/* completion_cursor is a subclass of sqlite3_vtab_cursor which will\n** serve as the underlying representation of a cursor that scans\n** over rows of the result\n*/\ntypedef struct completion_cursor completion_cursor;\nstruct completion_cursor {\n  sqlite3_vtab_cursor base;  /* Base class - must be first */\n  sqlite3 *db;               /* Database connection for this cursor */\n  int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */\n  char *zPrefix;             /* The prefix for the word we want to complete */\n  char *zLine;               /* The whole that we want to complete */\n  const char *zCurrentRow;   /* Current output row */\n  int szRow;                 /* Length of the zCurrentRow string */\n  sqlite3_stmt *pStmt;       /* Current statement */\n  sqlite3_int64 iRowid;      /* The rowid */\n  int ePhase;                /* Current phase */\n  int j;                     /* inter-phase counter */\n};\n\n/* Values for ePhase:\n*/\n#define COMPLETION_FIRST_PHASE   1\n#define COMPLETION_KEYWORDS      1\n#define COMPLETION_PRAGMAS       2\n#define COMPLETION_FUNCTIONS     3\n#define COMPLETION_COLLATIONS    4\n#define COMPLETION_INDEXES       5\n#define COMPLETION_TRIGGERS      6\n#define COMPLETION_DATABASES     7\n#define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */\n#define COMPLETION_COLUMNS       9\n#define COMPLETION_MODULES       10\n#define COMPLETION_EOF           11\n\n/*\n** The completionConnect() method is invoked to create a new\n** completion_vtab that describes the completion virtual table.\n**\n** Think of this routine as the constructor for completion_vtab objects.\n**\n** All this routine needs to do is:\n**\n**    (1) Allocate the completion_vtab object and initialize all fields.\n**\n**    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the\n**        result set of queries against completion will look like.\n*/\nstatic int completionConnect(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  completion_vtab *pNew;\n  int rc;\n\n  (void)(pAux);    /* Unused parameter */\n  (void)(argc);    /* Unused parameter */\n  (void)(argv);    /* Unused parameter */\n  (void)(pzErr);   /* Unused parameter */\n\n/* Column numbers */\n#define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */\n#define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */\n#define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */\n#define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */\n\n  sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);\n  rc = sqlite3_declare_vtab(db,\n      \"CREATE TABLE x(\"\n      \"  candidate TEXT,\"\n      \"  prefix TEXT HIDDEN,\"\n      \"  wholeline TEXT HIDDEN,\"\n      \"  phase INT HIDDEN\"        /* Used for debugging only */\n      \")\");\n  if( rc==SQLITE_OK ){\n    pNew = sqlite3_malloc( sizeof(*pNew) );\n    *ppVtab = (sqlite3_vtab*)pNew;\n    if( pNew==0 ) return SQLITE_NOMEM;\n    memset(pNew, 0, sizeof(*pNew));\n    pNew->db = db;\n  }\n  return rc;\n}\n\n/*\n** This method is the destructor for completion_cursor objects.\n*/\nstatic int completionDisconnect(sqlite3_vtab *pVtab){\n  sqlite3_free(pVtab);\n  return SQLITE_OK;\n}\n\n/*\n** Constructor for a new completion_cursor object.\n*/\nstatic int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){\n  completion_cursor *pCur;\n  pCur = sqlite3_malloc( sizeof(*pCur) );\n  if( pCur==0 ) return SQLITE_NOMEM;\n  memset(pCur, 0, sizeof(*pCur));\n  pCur->db = ((completion_vtab*)p)->db;\n  *ppCursor = &pCur->base;\n  return SQLITE_OK;\n}\n\n/*\n** Reset the completion_cursor.\n*/\nstatic void completionCursorReset(completion_cursor *pCur){\n  sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;\n  sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;\n  sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;\n  pCur->j = 0;\n}\n\n/*\n** Destructor for a completion_cursor.\n*/\nstatic int completionClose(sqlite3_vtab_cursor *cur){\n  completionCursorReset((completion_cursor*)cur);\n  sqlite3_free(cur);\n  return SQLITE_OK;\n}\n\n/*\n** Advance a completion_cursor to its next row of output.\n**\n** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object\n** record the current state of the scan.  This routine sets ->zCurrentRow\n** to the current row of output and then returns.  If no more rows remain,\n** then ->ePhase is set to COMPLETION_EOF which will signal the virtual\n** table that has reached the end of its scan.\n**\n** The current implementation just lists potential identifiers and\n** keywords and filters them by zPrefix.  Future enhancements should\n** take zLine into account to try to restrict the set of identifiers and\n** keywords based on what would be legal at the current point of input.\n*/\nstatic int completionNext(sqlite3_vtab_cursor *cur){\n  completion_cursor *pCur = (completion_cursor*)cur;\n  int eNextPhase = 0;  /* Next phase to try if current phase reaches end */\n  int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */\n  pCur->iRowid++;\n  while( pCur->ePhase!=COMPLETION_EOF ){\n    switch( pCur->ePhase ){\n      case COMPLETION_KEYWORDS: {\n        if( pCur->j >= sqlite3_keyword_count() ){\n          pCur->zCurrentRow = 0;\n          pCur->ePhase = COMPLETION_DATABASES;\n        }else{\n          sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);\n        }\n        iCol = -1;\n        break;\n      }\n      case COMPLETION_DATABASES: {\n        if( pCur->pStmt==0 ){\n          sqlite3_prepare_v2(pCur->db, \"PRAGMA database_list\", -1,\n                             &pCur->pStmt, 0);\n        }\n        iCol = 1;\n        eNextPhase = COMPLETION_TABLES;\n        break;\n      }\n      case COMPLETION_TABLES: {\n        if( pCur->pStmt==0 ){\n          sqlite3_stmt *pS2;\n          char *zSql = 0;\n          const char *zSep = \"\";\n          sqlite3_prepare_v2(pCur->db, \"PRAGMA database_list\", -1, &pS2, 0);\n          while( sqlite3_step(pS2)==SQLITE_ROW ){\n            const char *zDb = (const char*)sqlite3_column_text(pS2, 1);\n            zSql = sqlite3_mprintf(\n               \"%z%s\"\n               \"SELECT name FROM \\\"%w\\\".sqlite_master\",\n               zSql, zSep, zDb\n            );\n            if( zSql==0 ) return SQLITE_NOMEM;\n            zSep = \" UNION \";\n          }\n          sqlite3_finalize(pS2);\n          sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);\n          sqlite3_free(zSql);\n        }\n        iCol = 0;\n        eNextPhase = COMPLETION_COLUMNS;\n        break;\n      }\n      case COMPLETION_COLUMNS: {\n        if( pCur->pStmt==0 ){\n          sqlite3_stmt *pS2;\n          char *zSql = 0;\n          const char *zSep = \"\";\n          sqlite3_prepare_v2(pCur->db, \"PRAGMA database_list\", -1, &pS2, 0);\n          while( sqlite3_step(pS2)==SQLITE_ROW ){\n            const char *zDb = (const char*)sqlite3_column_text(pS2, 1);\n            zSql = sqlite3_mprintf(\n               \"%z%s\"\n               \"SELECT pti.name FROM \\\"%w\\\".sqlite_master AS sm\"\n                       \" JOIN pragma_table_info(sm.name,%Q) AS pti\"\n               \" WHERE sm.type='table'\",\n               zSql, zSep, zDb, zDb\n            );\n            if( zSql==0 ) return SQLITE_NOMEM;\n            zSep = \" UNION \";\n          }\n          sqlite3_finalize(pS2);\n          sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);\n          sqlite3_free(zSql);\n        }\n        iCol = 0;\n        eNextPhase = COMPLETION_EOF;\n        break;\n      }\n    }\n    if( iCol<0 ){\n      /* This case is when the phase presets zCurrentRow */\n      if( pCur->zCurrentRow==0 ) continue;\n    }else{\n      if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){\n        /* Extract the next row of content */\n        pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);\n        pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);\n      }else{\n        /* When all rows are finished, advance to the next phase */\n        sqlite3_finalize(pCur->pStmt);\n        pCur->pStmt = 0;\n        pCur->ePhase = eNextPhase;\n        continue;\n      }\n    }\n    if( pCur->nPrefix==0 ) break;\n    if( pCur->nPrefix<=pCur->szRow\n     && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0\n    ){\n      break;\n    }\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Return values of columns for the row at which the completion_cursor\n** is currently pointing.\n*/\nstatic int completionColumn(\n  sqlite3_vtab_cursor *cur,   /* The cursor */\n  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */\n  int i                       /* Which column to return */\n){\n  completion_cursor *pCur = (completion_cursor*)cur;\n  switch( i ){\n    case COMPLETION_COLUMN_CANDIDATE: {\n      sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);\n      break;\n    }\n    case COMPLETION_COLUMN_PREFIX: {\n      sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);\n      break;\n    }\n    case COMPLETION_COLUMN_WHOLELINE: {\n      sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);\n      break;\n    }\n    case COMPLETION_COLUMN_PHASE: {\n      sqlite3_result_int(ctx, pCur->ePhase);\n      break;\n    }\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Return the rowid for the current row.  In this implementation, the\n** rowid is the same as the output value.\n*/\nstatic int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){\n  completion_cursor *pCur = (completion_cursor*)cur;\n  *pRowid = pCur->iRowid;\n  return SQLITE_OK;\n}\n\n/*\n** Return TRUE if the cursor has been moved off of the last\n** row of output.\n*/\nstatic int completionEof(sqlite3_vtab_cursor *cur){\n  completion_cursor *pCur = (completion_cursor*)cur;\n  return pCur->ePhase >= COMPLETION_EOF;\n}\n\n/*\n** This method is called to \"rewind\" the completion_cursor object back\n** to the first row of output.  This method is always called at least\n** once prior to any call to completionColumn() or completionRowid() or \n** completionEof().\n*/\nstatic int completionFilter(\n  sqlite3_vtab_cursor *pVtabCursor, \n  int idxNum, const char *idxStr,\n  int argc, sqlite3_value **argv\n){\n  completion_cursor *pCur = (completion_cursor *)pVtabCursor;\n  int iArg = 0;\n  (void)(idxStr);   /* Unused parameter */\n  (void)(argc);     /* Unused parameter */\n  completionCursorReset(pCur);\n  if( idxNum & 1 ){\n    pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);\n    if( pCur->nPrefix>0 ){\n      pCur->zPrefix = sqlite3_mprintf(\"%s\", sqlite3_value_text(argv[iArg]));\n      if( pCur->zPrefix==0 ) return SQLITE_NOMEM;\n    }\n    iArg = 1;\n  }\n  if( idxNum & 2 ){\n    pCur->nLine = sqlite3_value_bytes(argv[iArg]);\n    if( pCur->nLine>0 ){\n      pCur->zLine = sqlite3_mprintf(\"%s\", sqlite3_value_text(argv[iArg]));\n      if( pCur->zLine==0 ) return SQLITE_NOMEM;\n    }\n  }\n  if( pCur->zLine!=0 && pCur->zPrefix==0 ){\n    int i = pCur->nLine;\n    while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){\n      i--;\n    }\n    pCur->nPrefix = pCur->nLine - i;\n    if( pCur->nPrefix>0 ){\n      pCur->zPrefix = sqlite3_mprintf(\"%.*s\", pCur->nPrefix, pCur->zLine + i);\n      if( pCur->zPrefix==0 ) return SQLITE_NOMEM;\n    }\n  }\n  pCur->iRowid = 0;\n  pCur->ePhase = COMPLETION_FIRST_PHASE;\n  return completionNext(pVtabCursor);\n}\n\n/*\n** SQLite will invoke this method one or more times while planning a query\n** that uses the completion virtual table.  This routine needs to create\n** a query plan for each invocation and compute an estimated cost for that\n** plan.\n**\n** There are two hidden parameters that act as arguments to the table-valued\n** function:  \"prefix\" and \"wholeline\".  Bit 0 of idxNum is set if \"prefix\"\n** is available and bit 1 is set if \"wholeline\" is available.\n*/\nstatic int completionBestIndex(\n  sqlite3_vtab *tab,\n  sqlite3_index_info *pIdxInfo\n){\n  int i;                 /* Loop over constraints */\n  int idxNum = 0;        /* The query plan bitmask */\n  int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */\n  int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */\n  int nArg = 0;          /* Number of arguments that completeFilter() expects */\n  const struct sqlite3_index_constraint *pConstraint;\n\n  (void)(tab);    /* Unused parameter */\n  pConstraint = pIdxInfo->aConstraint;\n  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){\n    if( pConstraint->usable==0 ) continue;\n    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;\n    switch( pConstraint->iColumn ){\n      case COMPLETION_COLUMN_PREFIX:\n        prefixIdx = i;\n        idxNum |= 1;\n        break;\n      case COMPLETION_COLUMN_WHOLELINE:\n        wholelineIdx = i;\n        idxNum |= 2;\n        break;\n    }\n  }\n  if( prefixIdx>=0 ){\n    pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;\n    pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;\n  }\n  if( wholelineIdx>=0 ){\n    pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;\n    pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;\n  }\n  pIdxInfo->idxNum = idxNum;\n  pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;\n  pIdxInfo->estimatedRows = 500 - 100*nArg;\n  return SQLITE_OK;\n}\n\n/*\n** This following structure defines all the methods for the \n** completion virtual table.\n*/\nstatic sqlite3_module completionModule = {\n  0,                         /* iVersion */\n  0,                         /* xCreate */\n  completionConnect,         /* xConnect */\n  completionBestIndex,       /* xBestIndex */\n  completionDisconnect,      /* xDisconnect */\n  0,                         /* xDestroy */\n  completionOpen,            /* xOpen - open a cursor */\n  completionClose,           /* xClose - close a cursor */\n  completionFilter,          /* xFilter - configure scan constraints */\n  completionNext,            /* xNext - advance a cursor */\n  completionEof,             /* xEof - check for end of scan */\n  completionColumn,          /* xColumn - read data */\n  completionRowid,           /* xRowid - read data */\n  0,                         /* xUpdate */\n  0,                         /* xBegin */\n  0,                         /* xSync */\n  0,                         /* xCommit */\n  0,                         /* xRollback */\n  0,                         /* xFindMethod */\n  0,                         /* xRename */\n  0,                         /* xSavepoint */\n  0,                         /* xRelease */\n  0,                         /* xRollbackTo */\n  0                          /* xShadowName */\n};\n\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\nint sqlite3CompletionVtabInit(sqlite3 *db){\n  int rc = SQLITE_OK;\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  rc = sqlite3_create_module(db, \"completion\", &completionModule, 0);\n#endif\n  return rc;\n}\n\n#ifdef _WIN32\n\n#endif\nint sqlite3_completion_init(\n  sqlite3 *db, \n  char **pzErrMsg, \n  const sqlite3_api_routines *pApi\n){\n  int rc = SQLITE_OK;\n  SQLITE_EXTENSION_INIT2(pApi);\n  (void)(pzErrMsg);  /* Unused parameter */\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  rc = sqlite3CompletionVtabInit(db);\n#endif\n  return rc;\n}\n\n/************************* End ../ext/misc/completion.c ********************/\n/************************* Begin ../ext/misc/appendvfs.c ******************/\n/*\n** 2017-10-20\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file implements a VFS shim that allows an SQLite database to be\n** appended onto the end of some other file, such as an executable.\n**\n** A special record must appear at the end of the file that identifies the\n** file as an appended database and provides an offset to page 1.  For\n** best performance page 1 should be located at a disk page boundary, though\n** that is not required.\n**\n** When opening a database using this VFS, the connection might treat\n** the file as an ordinary SQLite database, or it might treat is as a\n** database appended onto some other file.  Here are the rules:\n**\n**  (1)  When opening a new empty file, that file is treated as an ordinary\n**       database.\n**\n**  (2)  When opening a file that begins with the standard SQLite prefix\n**       string \"SQLite format 3\", that file is treated as an ordinary\n**       database.\n**\n**  (3)  When opening a file that ends with the appendvfs trailer string\n**       \"Start-Of-SQLite3-NNNNNNNN\" that file is treated as an appended\n**       database.\n**\n**  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is\n**       set, then a new database is appended to the already existing file.\n**\n**  (5)  Otherwise, SQLITE_CANTOPEN is returned.\n**\n** To avoid unnecessary complications with the PENDING_BYTE, the size of\n** the file containing the database is limited to 1GB.  This VFS will refuse\n** to read or write past the 1GB mark.  This restriction might be lifted in\n** future versions.  For now, if you need a large database, then keep the\n** database in a separate file.\n**\n** If the file being opened is not an appended database, then this shim is\n** a pass-through into the default underlying VFS.\n**/\n/* #include \"sqlite3ext.h\" */\nSQLITE_EXTENSION_INIT1\n#include <string.h>\n#include <assert.h>\n\n/* The append mark at the end of the database is:\n**\n**     Start-Of-SQLite3-NNNNNNNN\n**     123456789 123456789 12345\n**\n** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is\n** the offset to page 1.\n*/\n#define APND_MARK_PREFIX     \"Start-Of-SQLite3-\"\n#define APND_MARK_PREFIX_SZ  17\n#define APND_MARK_SIZE       25\n\n/*\n** Maximum size of the combined prefix + database + append-mark.  This\n** must be less than 0x40000000 to avoid locking issues on Windows.\n*/\n#define APND_MAX_SIZE  (65536*15259)\n\n/*\n** Forward declaration of objects used by this utility\n*/\ntypedef struct sqlite3_vfs ApndVfs;\ntypedef struct ApndFile ApndFile;\n\n/* Access to a lower-level VFS that (might) implement dynamic loading,\n** access to randomness, etc.\n*/\n#define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))\n#define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))\n\n/* An open file */\nstruct ApndFile {\n  sqlite3_file base;              /* IO methods */\n  sqlite3_int64 iPgOne;           /* File offset to page 1 */\n  sqlite3_int64 iMark;            /* Start of the append-mark */\n};\n\n/*\n** Methods for ApndFile\n*/\nstatic int apndClose(sqlite3_file*);\nstatic int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);\nstatic int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);\nstatic int apndTruncate(sqlite3_file*, sqlite3_int64 size);\nstatic int apndSync(sqlite3_file*, int flags);\nstatic int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);\nstatic int apndLock(sqlite3_file*, int);\nstatic int apndUnlock(sqlite3_file*, int);\nstatic int apndCheckReservedLock(sqlite3_file*, int *pResOut);\nstatic int apndFileControl(sqlite3_file*, int op, void *pArg);\nstatic int apndSectorSize(sqlite3_file*);\nstatic int apndDeviceCharacteristics(sqlite3_file*);\nstatic int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);\nstatic int apndShmLock(sqlite3_file*, int offset, int n, int flags);\nstatic void apndShmBarrier(sqlite3_file*);\nstatic int apndShmUnmap(sqlite3_file*, int deleteFlag);\nstatic int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);\nstatic int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);\n\n/*\n** Methods for ApndVfs\n*/\nstatic int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);\nstatic int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);\nstatic int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);\nstatic int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);\nstatic void *apndDlOpen(sqlite3_vfs*, const char *zFilename);\nstatic void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);\nstatic void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);\nstatic void apndDlClose(sqlite3_vfs*, void*);\nstatic int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);\nstatic int apndSleep(sqlite3_vfs*, int microseconds);\nstatic int apndCurrentTime(sqlite3_vfs*, double*);\nstatic int apndGetLastError(sqlite3_vfs*, int, char *);\nstatic int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);\nstatic int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);\nstatic sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);\nstatic const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);\n\nstatic sqlite3_vfs apnd_vfs = {\n  3,                            /* iVersion (set when registered) */\n  0,                            /* szOsFile (set when registered) */\n  1024,                         /* mxPathname */\n  0,                            /* pNext */\n  \"apndvfs\",                    /* zName */\n  0,                            /* pAppData (set when registered) */ \n  apndOpen,                     /* xOpen */\n  apndDelete,                   /* xDelete */\n  apndAccess,                   /* xAccess */\n  apndFullPathname,             /* xFullPathname */\n  apndDlOpen,                   /* xDlOpen */\n  apndDlError,                  /* xDlError */\n  apndDlSym,                    /* xDlSym */\n  apndDlClose,                  /* xDlClose */\n  apndRandomness,               /* xRandomness */\n  apndSleep,                    /* xSleep */\n  apndCurrentTime,              /* xCurrentTime */\n  apndGetLastError,             /* xGetLastError */\n  apndCurrentTimeInt64,         /* xCurrentTimeInt64 */\n  apndSetSystemCall,            /* xSetSystemCall */\n  apndGetSystemCall,            /* xGetSystemCall */\n  apndNextSystemCall            /* xNextSystemCall */\n};\n\nstatic const sqlite3_io_methods apnd_io_methods = {\n  3,                              /* iVersion */\n  apndClose,                      /* xClose */\n  apndRead,                       /* xRead */\n  apndWrite,                      /* xWrite */\n  apndTruncate,                   /* xTruncate */\n  apndSync,                       /* xSync */\n  apndFileSize,                   /* xFileSize */\n  apndLock,                       /* xLock */\n  apndUnlock,                     /* xUnlock */\n  apndCheckReservedLock,          /* xCheckReservedLock */\n  apndFileControl,                /* xFileControl */\n  apndSectorSize,                 /* xSectorSize */\n  apndDeviceCharacteristics,      /* xDeviceCharacteristics */\n  apndShmMap,                     /* xShmMap */\n  apndShmLock,                    /* xShmLock */\n  apndShmBarrier,                 /* xShmBarrier */\n  apndShmUnmap,                   /* xShmUnmap */\n  apndFetch,                      /* xFetch */\n  apndUnfetch                     /* xUnfetch */\n};\n\n\n\n/*\n** Close an apnd-file.\n*/\nstatic int apndClose(sqlite3_file *pFile){\n  pFile = ORIGFILE(pFile);\n  return pFile->pMethods->xClose(pFile);\n}\n\n/*\n** Read data from an apnd-file.\n*/\nstatic int apndRead(\n  sqlite3_file *pFile, \n  void *zBuf, \n  int iAmt, \n  sqlite_int64 iOfst\n){\n  ApndFile *p = (ApndFile *)pFile;\n  pFile = ORIGFILE(pFile);\n  return pFile->pMethods->xRead(pFile, zBuf, iAmt, iOfst+p->iPgOne);\n}\n\n/*\n** Add the append-mark onto the end of the file.\n*/\nstatic int apndWriteMark(ApndFile *p, sqlite3_file *pFile){\n  int i;\n  unsigned char a[APND_MARK_SIZE];\n  memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);\n  for(i=0; i<8; i++){\n    a[APND_MARK_PREFIX_SZ+i] = (p->iPgOne >> (56 - i*8)) & 0xff;\n  }\n  return pFile->pMethods->xWrite(pFile, a, APND_MARK_SIZE, p->iMark);\n}\n\n/*\n** Write data to an apnd-file.\n*/\nstatic int apndWrite(\n  sqlite3_file *pFile,\n  const void *zBuf,\n  int iAmt,\n  sqlite_int64 iOfst\n){\n  int rc;\n  ApndFile *p = (ApndFile *)pFile;\n  pFile = ORIGFILE(pFile);\n  if( iOfst+iAmt>=APND_MAX_SIZE ) return SQLITE_FULL;\n  rc = pFile->pMethods->xWrite(pFile, zBuf, iAmt, iOfst+p->iPgOne);\n  if( rc==SQLITE_OK &&  iOfst + iAmt + p->iPgOne > p->iMark ){\n    sqlite3_int64 sz = 0;\n    rc = pFile->pMethods->xFileSize(pFile, &sz);\n    if( rc==SQLITE_OK ){\n      p->iMark = sz - APND_MARK_SIZE;\n      if( iOfst + iAmt + p->iPgOne > p->iMark ){\n        p->iMark = p->iPgOne + iOfst + iAmt;\n        rc = apndWriteMark(p, pFile);\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** Truncate an apnd-file.\n*/\nstatic int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){\n  int rc;\n  ApndFile *p = (ApndFile *)pFile;\n  pFile = ORIGFILE(pFile);\n  rc = pFile->pMethods->xTruncate(pFile, size+p->iPgOne+APND_MARK_SIZE);\n  if( rc==SQLITE_OK ){\n    p->iMark = p->iPgOne+size;\n    rc = apndWriteMark(p, pFile);\n  }\n  return rc;\n}\n\n/*\n** Sync an apnd-file.\n*/\nstatic int apndSync(sqlite3_file *pFile, int flags){\n  pFile = ORIGFILE(pFile);\n  return pFile->pMethods->xSync(pFile, flags);\n}\n\n/*\n** Return the current file-size of an apnd-file.\n*/\nstatic int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){\n  ApndFile *p = (ApndFile *)pFile;\n  int rc;\n  pFile = ORIGFILE(p);\n  rc = pFile->pMethods->xFileSize(pFile, pSize);\n  if( rc==SQLITE_OK && p->iPgOne ){\n    *pSize -= p->iPgOne + APND_MARK_SIZE;\n  }\n  return rc;\n}\n\n/*\n** Lock an apnd-file.\n*/\nstatic int apndLock(sqlite3_file *pFile, int eLock){\n  pFile = ORIGFILE(pFile);\n  return pFile->pMethods->xLock(pFile, eLock);\n}\n\n/*\n** Unlock an apnd-file.\n*/\nstatic int apndUnlock(sqlite3_file *pFile, int eLock){\n  pFile = ORIGFILE(pFile);\n  return pFile->pMethods->xUnlock(pFile, eLock);\n}\n\n/*\n** Check if another file-handle holds a RESERVED lock on an apnd-file.\n*/\nstatic int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){\n  pFile = ORIGFILE(pFile);\n  return pFile->pMethods->xCheckReservedLock(pFile, pResOut);\n}\n\n/*\n** File control method. For custom operations on an apnd-file.\n*/\nstatic int apndFileControl(sqlite3_file *pFile, int op, void *pArg){\n  ApndFile *p = (ApndFile *)pFile;\n  int rc;\n  pFile = ORIGFILE(pFile);\n  rc = pFile->pMethods->xFileControl(pFile, op, pArg);\n  if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){\n    *(char**)pArg = sqlite3_mprintf(\"apnd(%lld)/%z\", p->iPgOne, *(char**)pArg);\n  }\n  return rc;\n}\n\n/*\n** Return the sector-size in bytes for an apnd-file.\n*/\nstatic int apndSectorSize(sqlite3_file *pFile){\n  pFile = ORIGFILE(pFile);\n  return pFile->pMethods->xSectorSize(pFile);\n}\n\n/*\n** Return the device characteristic flags supported by an apnd-file.\n*/\nstatic int apndDeviceCharacteristics(sqlite3_file *pFile){\n  pFile = ORIGFILE(pFile);\n  return pFile->pMethods->xDeviceCharacteristics(pFile);\n}\n\n/* Create a shared memory file mapping */\nstatic int apndShmMap(\n  sqlite3_file *pFile,\n  int iPg,\n  int pgsz,\n  int bExtend,\n  void volatile **pp\n){\n  pFile = ORIGFILE(pFile);\n  return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);\n}\n\n/* Perform locking on a shared-memory segment */\nstatic int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){\n  pFile = ORIGFILE(pFile);\n  return pFile->pMethods->xShmLock(pFile,offset,n,flags);\n}\n\n/* Memory barrier operation on shared memory */\nstatic void apndShmBarrier(sqlite3_file *pFile){\n  pFile = ORIGFILE(pFile);\n  pFile->pMethods->xShmBarrier(pFile);\n}\n\n/* Unmap a shared memory segment */\nstatic int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){\n  pFile = ORIGFILE(pFile);\n  return pFile->pMethods->xShmUnmap(pFile,deleteFlag);\n}\n\n/* Fetch a page of a memory-mapped file */\nstatic int apndFetch(\n  sqlite3_file *pFile,\n  sqlite3_int64 iOfst,\n  int iAmt,\n  void **pp\n){\n  ApndFile *p = (ApndFile *)pFile;\n  pFile = ORIGFILE(pFile);\n  return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);\n}\n\n/* Release a memory-mapped page */\nstatic int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){\n  ApndFile *p = (ApndFile *)pFile;\n  pFile = ORIGFILE(pFile);\n  return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);\n}\n\n/*\n** Check to see if the file is an ordinary SQLite database file.\n*/\nstatic int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){\n  int rc;\n  char zHdr[16];\n  static const char aSqliteHdr[] = \"SQLite format 3\";\n  if( sz<512 ) return 0;\n  rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0);\n  if( rc ) return 0;\n  return memcmp(zHdr, aSqliteHdr, sizeof(zHdr))==0;\n}\n\n/*\n** Try to read the append-mark off the end of a file.  Return the\n** start of the appended database if the append-mark is present.  If\n** there is no append-mark, return -1;\n*/\nstatic sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){\n  int rc, i;\n  sqlite3_int64 iMark;\n  unsigned char a[APND_MARK_SIZE];\n\n  if( sz<=APND_MARK_SIZE ) return -1;\n  rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);\n  if( rc ) return -1;\n  if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;\n  iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ]&0x7f))<<56;\n  for(i=1; i<8; i++){    \n    iMark += (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<(56-8*i);\n  }\n  return iMark;\n}\n\n/*\n** Open an apnd file handle.\n*/\nstatic int apndOpen(\n  sqlite3_vfs *pVfs,\n  const char *zName,\n  sqlite3_file *pFile,\n  int flags,\n  int *pOutFlags\n){\n  ApndFile *p;\n  sqlite3_file *pSubFile;\n  sqlite3_vfs *pSubVfs;\n  int rc;\n  sqlite3_int64 sz;\n  pSubVfs = ORIGVFS(pVfs);\n  if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){\n    return pSubVfs->xOpen(pSubVfs, zName, pFile, flags, pOutFlags);\n  }\n  p = (ApndFile*)pFile;\n  memset(p, 0, sizeof(*p));\n  pSubFile = ORIGFILE(pFile);\n  p->base.pMethods = &apnd_io_methods;\n  rc = pSubVfs->xOpen(pSubVfs, zName, pSubFile, flags, pOutFlags);\n  if( rc ) goto apnd_open_done;\n  rc = pSubFile->pMethods->xFileSize(pSubFile, &sz);\n  if( rc ){\n    pSubFile->pMethods->xClose(pSubFile);\n    goto apnd_open_done;\n  }\n  if( apndIsOrdinaryDatabaseFile(sz, pSubFile) ){\n    memmove(pFile, pSubFile, pSubVfs->szOsFile);\n    return SQLITE_OK;\n  }\n  p->iMark = 0;\n  p->iPgOne = apndReadMark(sz, pFile);\n  if( p->iPgOne>0 ){\n    return SQLITE_OK;\n  }\n  if( (flags & SQLITE_OPEN_CREATE)==0 ){\n    pSubFile->pMethods->xClose(pSubFile);\n    rc = SQLITE_CANTOPEN;\n  }\n  p->iPgOne = (sz+0xfff) & ~(sqlite3_int64)0xfff;\napnd_open_done:\n  if( rc ) pFile->pMethods = 0;\n  return rc;\n}\n\n/*\n** All other VFS methods are pass-thrus.\n*/\nstatic int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){\n  return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);\n}\nstatic int apndAccess(\n  sqlite3_vfs *pVfs, \n  const char *zPath, \n  int flags, \n  int *pResOut\n){\n  return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);\n}\nstatic int apndFullPathname(\n  sqlite3_vfs *pVfs, \n  const char *zPath, \n  int nOut, \n  char *zOut\n){\n  return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);\n}\nstatic void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){\n  return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);\n}\nstatic void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){\n  ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);\n}\nstatic void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){\n  return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);\n}\nstatic void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){\n  ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);\n}\nstatic int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){\n  return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);\n}\nstatic int apndSleep(sqlite3_vfs *pVfs, int nMicro){\n  return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);\n}\nstatic int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){\n  return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);\n}\nstatic int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){\n  return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);\n}\nstatic int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){\n  return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);\n}\nstatic int apndSetSystemCall(\n  sqlite3_vfs *pVfs,\n  const char *zName,\n  sqlite3_syscall_ptr pCall\n){\n  return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);\n}\nstatic sqlite3_syscall_ptr apndGetSystemCall(\n  sqlite3_vfs *pVfs,\n  const char *zName\n){\n  return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);\n}\nstatic const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){\n  return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);\n}\n\n  \n#ifdef _WIN32\n\n#endif\n/* \n** This routine is called when the extension is loaded.\n** Register the new VFS.\n*/\nint sqlite3_appendvfs_init(\n  sqlite3 *db, \n  char **pzErrMsg, \n  const sqlite3_api_routines *pApi\n){\n  int rc = SQLITE_OK;\n  sqlite3_vfs *pOrig;\n  SQLITE_EXTENSION_INIT2(pApi);\n  (void)pzErrMsg;\n  (void)db;\n  pOrig = sqlite3_vfs_find(0);\n  apnd_vfs.iVersion = pOrig->iVersion;\n  apnd_vfs.pAppData = pOrig;\n  apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);\n  rc = sqlite3_vfs_register(&apnd_vfs, 0);\n#ifdef APPENDVFS_TEST\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);\n  }\n#endif\n  if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;\n  return rc;\n}\n\n/************************* End ../ext/misc/appendvfs.c ********************/\n/************************* Begin ../ext/misc/memtrace.c ******************/\n/*\n** 2019-01-21\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file implements an extension that uses the SQLITE_CONFIG_MALLOC\n** mechanism to add a tracing layer on top of SQLite.  If this extension\n** is registered prior to sqlite3_initialize(), it will cause all memory\n** allocation activities to be logged on standard output, or to some other\n** FILE specified by the initializer.\n**\n** This file needs to be compiled into the application that uses it.\n**\n** This extension is used to implement the --memtrace option of the\n** command-line shell.\n*/\n#include <assert.h>\n#include <string.h>\n#include <stdio.h>\n\n/* The original memory allocation routines */\nstatic sqlite3_mem_methods memtraceBase;\nstatic FILE *memtraceOut;\n\n/* Methods that trace memory allocations */\nstatic void *memtraceMalloc(int n){\n  if( memtraceOut ){\n    fprintf(memtraceOut, \"MEMTRACE: allocate %d bytes\\n\", \n            memtraceBase.xRoundup(n));\n  }\n  return memtraceBase.xMalloc(n);\n}\nstatic void memtraceFree(void *p){\n  if( p==0 ) return;\n  if( memtraceOut ){\n    fprintf(memtraceOut, \"MEMTRACE: free %d bytes\\n\", memtraceBase.xSize(p));\n  }\n  memtraceBase.xFree(p);\n}\nstatic void *memtraceRealloc(void *p, int n){\n  if( p==0 ) return memtraceMalloc(n);\n  if( n==0 ){\n    memtraceFree(p);\n    return 0;\n  }\n  if( memtraceOut ){\n    fprintf(memtraceOut, \"MEMTRACE: resize %d -> %d bytes\\n\",\n            memtraceBase.xSize(p), memtraceBase.xRoundup(n));\n  }\n  return memtraceBase.xRealloc(p, n);\n}\nstatic int memtraceSize(void *p){\n  return memtraceBase.xSize(p);\n}\nstatic int memtraceRoundup(int n){\n  return memtraceBase.xRoundup(n);\n}\nstatic int memtraceInit(void *p){\n  return memtraceBase.xInit(p);\n}\nstatic void memtraceShutdown(void *p){\n  memtraceBase.xShutdown(p);\n}\n\n/* The substitute memory allocator */\nstatic sqlite3_mem_methods ersaztMethods = {\n  memtraceMalloc,\n  memtraceFree,\n  memtraceRealloc,\n  memtraceSize,\n  memtraceRoundup,\n  memtraceInit,\n  memtraceShutdown,\n  0\n};\n\n/* Begin tracing memory allocations to out. */\nint sqlite3MemTraceActivate(FILE *out){\n  int rc = SQLITE_OK;\n  if( memtraceBase.xMalloc==0 ){\n    rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);\n    if( rc==SQLITE_OK ){\n      rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);\n    }\n  }\n  memtraceOut = out;\n  return rc;\n}\n\n/* Deactivate memory tracing */\nint sqlite3MemTraceDeactivate(void){\n  int rc = SQLITE_OK;\n  if( memtraceBase.xMalloc!=0 ){\n    rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);\n    if( rc==SQLITE_OK ){\n      memset(&memtraceBase, 0, sizeof(memtraceBase));\n    }\n  }\n  memtraceOut = 0;\n  return rc;\n}\n\n/************************* End ../ext/misc/memtrace.c ********************/\n/************************* Begin ../ext/misc/uint.c ******************/\n/*\n** 2020-04-14\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This SQLite extension implements the UINT collating sequence.\n**\n** UINT works like BINARY for text, except that embedded strings\n** of digits compare in numeric order.\n**\n**     *   Leading zeros are handled properly, in the sense that\n**         they do not mess of the maginitude comparison of embedded\n**         strings of digits.  \"x00123y\" is equal to \"x123y\".\n**\n**     *   Only unsigned integers are recognized.  Plus and minus\n**         signs are ignored.  Decimal points and exponential notation\n**         are ignored.\n**\n**     *   Embedded integers can be of arbitrary length.  Comparison\n**         is *not* limited integers that can be expressed as a\n**         64-bit machine integer.\n*/\n/* #include \"sqlite3ext.h\" */\nSQLITE_EXTENSION_INIT1\n#include <assert.h>\n#include <string.h>\n#include <ctype.h>\n\n/*\n** Compare text in lexicographic order, except strings of digits\n** compare in numeric order.\n*/\nstatic int uintCollFunc(\n  void *notUsed,\n  int nKey1, const void *pKey1,\n  int nKey2, const void *pKey2\n){\n  const unsigned char *zA = (const unsigned char*)pKey1;\n  const unsigned char *zB = (const unsigned char*)pKey2;\n  int i=0, j=0, x;\n  (void)notUsed;\n  while( i<nKey1 && j<nKey2 ){\n    x = zA[i] - zB[j];\n    if( isdigit(zA[i]) ){\n      int k;\n      if( !isdigit(zB[j]) ) return x;\n      while( i<nKey1 && zA[i]=='0' ){ i++; }\n      while( j<nKey2 && zB[j]=='0' ){ j++; }\n      k = 0;\n      while( i+k<nKey1 && isdigit(zA[i+k])\n             && j+k<nKey2 && isdigit(zB[j+k]) ){\n        k++;\n      }\n      if( i+k<nKey1 && isdigit(zA[i+k]) ){\n        return +1;\n      }else if( j+k<nKey2 && isdigit(zB[j+k]) ){\n        return -1;\n      }else{\n        x = memcmp(zA+i, zB+j, k);\n        if( x ) return x;\n        i += k;\n        j += k;\n      }\n    }else if( x ){\n      return x;\n    }else{\n      i++;\n      j++;\n    }\n  }\n  return (nKey1 - i) - (nKey2 - j);\n}\n\n#ifdef _WIN32\n\n#endif\nint sqlite3_uint_init(\n  sqlite3 *db, \n  char **pzErrMsg, \n  const sqlite3_api_routines *pApi\n){\n  SQLITE_EXTENSION_INIT2(pApi);\n  (void)pzErrMsg;  /* Unused parameter */\n  return sqlite3_create_collation(db, \"uint\", SQLITE_UTF8, 0, uintCollFunc);\n}\n\n/************************* End ../ext/misc/uint.c ********************/\n#ifdef SQLITE_HAVE_ZLIB\n/************************* Begin ../ext/misc/zipfile.c ******************/\n/*\n** 2017-12-26\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file implements a virtual table for reading and writing ZIP archive\n** files.\n**\n** Usage example:\n**\n**     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);\n**\n** Current limitations:\n**\n**    *  No support for encryption\n**    *  No support for ZIP archives spanning multiple files\n**    *  No support for zip64 extensions\n**    *  Only the \"inflate/deflate\" (zlib) compression method is supported\n*/\n/* #include \"sqlite3ext.h\" */\nSQLITE_EXTENSION_INIT1\n#include <stdio.h>\n#include <string.h>\n#include <assert.h>\n\n#include <zlib.h>\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n\n#ifndef SQLITE_AMALGAMATION\n\n/* typedef sqlite3_int64 i64; */\n/* typedef unsigned char u8; */\ntypedef unsigned short u16;\ntypedef unsigned long u32;\n#define MIN(a,b) ((a)<(b) ? (a) : (b))\n\n#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)\n# define ALWAYS(X)      (1)\n# define NEVER(X)       (0)\n#elif !defined(NDEBUG)\n# define ALWAYS(X)      ((X)?1:(assert(0),0))\n# define NEVER(X)       ((X)?(assert(0),1):0)\n#else\n# define ALWAYS(X)      (X)\n# define NEVER(X)       (X)\n#endif\n\n#endif   /* SQLITE_AMALGAMATION */\n\n/*\n** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.\n**\n** In some ways it would be better to obtain these values from system \n** header files. But, the dependency is undesirable and (a) these\n** have been stable for decades, (b) the values are part of POSIX and\n** are also made explicit in [man stat], and (c) are part of the \n** file format for zip archives.\n*/\n#ifndef S_IFDIR\n# define S_IFDIR 0040000\n#endif\n#ifndef S_IFREG\n# define S_IFREG 0100000\n#endif\n#ifndef S_IFLNK\n# define S_IFLNK 0120000\n#endif\n\nstatic const char ZIPFILE_SCHEMA[] = \n  \"CREATE TABLE y(\"\n    \"name PRIMARY KEY,\"  /* 0: Name of file in zip archive */\n    \"mode,\"              /* 1: POSIX mode for file */\n    \"mtime,\"             /* 2: Last modification time (secs since 1970)*/\n    \"sz,\"                /* 3: Size of object */\n    \"rawdata,\"           /* 4: Raw data */\n    \"data,\"              /* 5: Uncompressed data */\n    \"method,\"            /* 6: Compression method (integer) */\n    \"z HIDDEN\"           /* 7: Name of zip file */\n  \") WITHOUT ROWID;\";\n\n#define ZIPFILE_F_COLUMN_IDX 7    /* Index of column \"file\" in the above */\n#define ZIPFILE_BUFFER_SIZE (64*1024)\n\n\n/*\n** Magic numbers used to read and write zip files.\n**\n** ZIPFILE_NEWENTRY_MADEBY:\n**   Use this value for the \"version-made-by\" field in new zip file\n**   entries. The upper byte indicates \"unix\", and the lower byte \n**   indicates that the zip file matches pkzip specification 3.0. \n**   This is what info-zip seems to do.\n**\n** ZIPFILE_NEWENTRY_REQUIRED:\n**   Value for \"version-required-to-extract\" field of new entries.\n**   Version 2.0 is required to support folders and deflate compression.\n**\n** ZIPFILE_NEWENTRY_FLAGS:\n**   Value for \"general-purpose-bit-flags\" field of new entries. Bit\n**   11 means \"utf-8 filename and comment\".\n**\n** ZIPFILE_SIGNATURE_CDS:\n**   First 4 bytes of a valid CDS record.\n**\n** ZIPFILE_SIGNATURE_LFH:\n**   First 4 bytes of a valid LFH record.\n**\n** ZIPFILE_SIGNATURE_EOCD\n**   First 4 bytes of a valid EOCD record.\n*/\n#define ZIPFILE_EXTRA_TIMESTAMP   0x5455\n#define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)\n#define ZIPFILE_NEWENTRY_REQUIRED 20\n#define ZIPFILE_NEWENTRY_FLAGS    0x800\n#define ZIPFILE_SIGNATURE_CDS     0x02014b50\n#define ZIPFILE_SIGNATURE_LFH     0x04034b50\n#define ZIPFILE_SIGNATURE_EOCD    0x06054b50\n\n/*\n** The sizes of the fixed-size part of each of the three main data \n** structures in a zip archive.\n*/\n#define ZIPFILE_LFH_FIXED_SZ      30\n#define ZIPFILE_EOCD_FIXED_SZ     22\n#define ZIPFILE_CDS_FIXED_SZ      46\n\n/*\n*** 4.3.16  End of central directory record:\n***\n***   end of central dir signature    4 bytes  (0x06054b50)\n***   number of this disk             2 bytes\n***   number of the disk with the\n***   start of the central directory  2 bytes\n***   total number of entries in the\n***   central directory on this disk  2 bytes\n***   total number of entries in\n***   the central directory           2 bytes\n***   size of the central directory   4 bytes\n***   offset of start of central\n***   directory with respect to\n***   the starting disk number        4 bytes\n***   .ZIP file comment length        2 bytes\n***   .ZIP file comment       (variable size)\n*/\ntypedef struct ZipfileEOCD ZipfileEOCD;\nstruct ZipfileEOCD {\n  u16 iDisk;\n  u16 iFirstDisk;\n  u16 nEntry;\n  u16 nEntryTotal;\n  u32 nSize;\n  u32 iOffset;\n};\n\n/*\n*** 4.3.12  Central directory structure:\n***\n*** ...\n***\n***   central file header signature   4 bytes  (0x02014b50)\n***   version made by                 2 bytes\n***   version needed to extract       2 bytes\n***   general purpose bit flag        2 bytes\n***   compression method              2 bytes\n***   last mod file time              2 bytes\n***   last mod file date              2 bytes\n***   crc-32                          4 bytes\n***   compressed size                 4 bytes\n***   uncompressed size               4 bytes\n***   file name length                2 bytes\n***   extra field length              2 bytes\n***   file comment length             2 bytes\n***   disk number start               2 bytes\n***   internal file attributes        2 bytes\n***   external file attributes        4 bytes\n***   relative offset of local header 4 bytes\n*/\ntypedef struct ZipfileCDS ZipfileCDS;\nstruct ZipfileCDS {\n  u16 iVersionMadeBy;\n  u16 iVersionExtract;\n  u16 flags;\n  u16 iCompression;\n  u16 mTime;\n  u16 mDate;\n  u32 crc32;\n  u32 szCompressed;\n  u32 szUncompressed;\n  u16 nFile;\n  u16 nExtra;\n  u16 nComment;\n  u16 iDiskStart;\n  u16 iInternalAttr;\n  u32 iExternalAttr;\n  u32 iOffset;\n  char *zFile;                    /* Filename (sqlite3_malloc()) */\n};\n\n/*\n*** 4.3.7  Local file header:\n***\n***   local file header signature     4 bytes  (0x04034b50)\n***   version needed to extract       2 bytes\n***   general purpose bit flag        2 bytes\n***   compression method              2 bytes\n***   last mod file time              2 bytes\n***   last mod file date              2 bytes\n***   crc-32                          4 bytes\n***   compressed size                 4 bytes\n***   uncompressed size               4 bytes\n***   file name length                2 bytes\n***   extra field length              2 bytes\n***   \n*/\ntypedef struct ZipfileLFH ZipfileLFH;\nstruct ZipfileLFH {\n  u16 iVersionExtract;\n  u16 flags;\n  u16 iCompression;\n  u16 mTime;\n  u16 mDate;\n  u32 crc32;\n  u32 szCompressed;\n  u32 szUncompressed;\n  u16 nFile;\n  u16 nExtra;\n};\n\ntypedef struct ZipfileEntry ZipfileEntry;\nstruct ZipfileEntry {\n  ZipfileCDS cds;            /* Parsed CDS record */\n  u32 mUnixTime;             /* Modification time, in UNIX format */\n  u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */\n  i64 iDataOff;              /* Offset to data in file (if aData==0) */\n  u8 *aData;                 /* cds.szCompressed bytes of compressed data */\n  ZipfileEntry *pNext;       /* Next element in in-memory CDS */\n};\n\n/* \n** Cursor type for zipfile tables.\n*/\ntypedef struct ZipfileCsr ZipfileCsr;\nstruct ZipfileCsr {\n  sqlite3_vtab_cursor base;  /* Base class - must be first */\n  i64 iId;                   /* Cursor ID */\n  u8 bEof;                   /* True when at EOF */\n  u8 bNoop;                  /* If next xNext() call is no-op */\n\n  /* Used outside of write transactions */\n  FILE *pFile;               /* Zip file */\n  i64 iNextOff;              /* Offset of next record in central directory */\n  ZipfileEOCD eocd;          /* Parse of central directory record */\n\n  ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */\n  ZipfileEntry *pCurrent;    /* Current entry */\n  ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */\n};\n\ntypedef struct ZipfileTab ZipfileTab;\nstruct ZipfileTab {\n  sqlite3_vtab base;         /* Base class - must be first */\n  char *zFile;               /* Zip file this table accesses (may be NULL) */\n  sqlite3 *db;               /* Host database connection */\n  u8 *aBuffer;               /* Temporary buffer used for various tasks */\n\n  ZipfileCsr *pCsrList;      /* List of cursors */\n  i64 iNextCsrid;\n\n  /* The following are used by write transactions only */\n  ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */\n  ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */\n  FILE *pWriteFd;            /* File handle open on zip archive */\n  i64 szCurrent;             /* Current size of zip archive */\n  i64 szOrig;                /* Size of archive at start of transaction */\n};\n\n/*\n** Set the error message contained in context ctx to the results of\n** vprintf(zFmt, ...).\n*/\nstatic void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){\n  char *zMsg = 0;\n  va_list ap;\n  va_start(ap, zFmt);\n  zMsg = sqlite3_vmprintf(zFmt, ap);\n  sqlite3_result_error(ctx, zMsg, -1);\n  sqlite3_free(zMsg);\n  va_end(ap);\n}\n\n/*\n** If string zIn is quoted, dequote it in place. Otherwise, if the string\n** is not quoted, do nothing.\n*/\nstatic void zipfileDequote(char *zIn){\n  char q = zIn[0];\n  if( q=='\"' || q=='\\'' || q=='`' || q=='[' ){\n    int iIn = 1;\n    int iOut = 0;\n    if( q=='[' ) q = ']';\n    while( ALWAYS(zIn[iIn]) ){\n      char c = zIn[iIn++];\n      if( c==q && zIn[iIn++]!=q ) break;\n      zIn[iOut++] = c;\n    }\n    zIn[iOut] = '\\0';\n  }\n}\n\n/*\n** Construct a new ZipfileTab virtual table object.\n** \n**   argv[0]   -> module name  (\"zipfile\")\n**   argv[1]   -> database name\n**   argv[2]   -> table name\n**   argv[...] -> \"column name\" and other module argument fields.\n*/\nstatic int zipfileConnect(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;\n  int nFile = 0;\n  const char *zFile = 0;\n  ZipfileTab *pNew = 0;\n  int rc;\n\n  /* If the table name is not \"zipfile\", require that the argument be\n  ** specified. This stops zipfile tables from being created as:\n  **\n  **   CREATE VIRTUAL TABLE zzz USING zipfile();\n  **\n  ** It does not prevent:\n  **\n  **   CREATE VIRTUAL TABLE zipfile USING zipfile();\n  */\n  assert( 0==sqlite3_stricmp(argv[0], \"zipfile\") );\n  if( (0!=sqlite3_stricmp(argv[2], \"zipfile\") && argc<4) || argc>4 ){\n    *pzErr = sqlite3_mprintf(\"zipfile constructor requires one argument\");\n    return SQLITE_ERROR;\n  }\n\n  if( argc>3 ){\n    zFile = argv[3];\n    nFile = (int)strlen(zFile)+1;\n  }\n\n  rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);\n  if( rc==SQLITE_OK ){\n    pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);\n    if( pNew==0 ) return SQLITE_NOMEM;\n    memset(pNew, 0, nByte+nFile);\n    pNew->db = db;\n    pNew->aBuffer = (u8*)&pNew[1];\n    if( zFile ){\n      pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];\n      memcpy(pNew->zFile, zFile, nFile);\n      zipfileDequote(pNew->zFile);\n    }\n  }\n  sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);\n  *ppVtab = (sqlite3_vtab*)pNew;\n  return rc;\n}\n\n/*\n** Free the ZipfileEntry structure indicated by the only argument.\n*/\nstatic void zipfileEntryFree(ZipfileEntry *p){\n  if( p ){\n    sqlite3_free(p->cds.zFile);\n    sqlite3_free(p);\n  }\n}\n\n/*\n** Release resources that should be freed at the end of a write \n** transaction.\n*/\nstatic void zipfileCleanupTransaction(ZipfileTab *pTab){\n  ZipfileEntry *pEntry;\n  ZipfileEntry *pNext;\n\n  if( pTab->pWriteFd ){\n    fclose(pTab->pWriteFd);\n    pTab->pWriteFd = 0;\n  }\n  for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){\n    pNext = pEntry->pNext;\n    zipfileEntryFree(pEntry);\n  }\n  pTab->pFirstEntry = 0;\n  pTab->pLastEntry = 0;\n  pTab->szCurrent = 0;\n  pTab->szOrig = 0;\n}\n\n/*\n** This method is the destructor for zipfile vtab objects.\n*/\nstatic int zipfileDisconnect(sqlite3_vtab *pVtab){\n  zipfileCleanupTransaction((ZipfileTab*)pVtab);\n  sqlite3_free(pVtab);\n  return SQLITE_OK;\n}\n\n/*\n** Constructor for a new ZipfileCsr object.\n*/\nstatic int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){\n  ZipfileTab *pTab = (ZipfileTab*)p;\n  ZipfileCsr *pCsr;\n  pCsr = sqlite3_malloc(sizeof(*pCsr));\n  *ppCsr = (sqlite3_vtab_cursor*)pCsr;\n  if( pCsr==0 ){\n    return SQLITE_NOMEM;\n  }\n  memset(pCsr, 0, sizeof(*pCsr));\n  pCsr->iId = ++pTab->iNextCsrid;\n  pCsr->pCsrNext = pTab->pCsrList;\n  pTab->pCsrList = pCsr;\n  return SQLITE_OK;\n}\n\n/*\n** Reset a cursor back to the state it was in when first returned\n** by zipfileOpen().\n*/\nstatic void zipfileResetCursor(ZipfileCsr *pCsr){\n  ZipfileEntry *p;\n  ZipfileEntry *pNext;\n\n  pCsr->bEof = 0;\n  if( pCsr->pFile ){\n    fclose(pCsr->pFile);\n    pCsr->pFile = 0;\n    zipfileEntryFree(pCsr->pCurrent);\n    pCsr->pCurrent = 0;\n  }\n\n  for(p=pCsr->pFreeEntry; p; p=pNext){\n    pNext = p->pNext;\n    zipfileEntryFree(p);\n  }\n}\n\n/*\n** Destructor for an ZipfileCsr.\n*/\nstatic int zipfileClose(sqlite3_vtab_cursor *cur){\n  ZipfileCsr *pCsr = (ZipfileCsr*)cur;\n  ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);\n  ZipfileCsr **pp;\n  zipfileResetCursor(pCsr);\n\n  /* Remove this cursor from the ZipfileTab.pCsrList list. */\n  for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));\n  *pp = pCsr->pCsrNext;\n\n  sqlite3_free(pCsr);\n  return SQLITE_OK;\n}\n\n/*\n** Set the error message for the virtual table associated with cursor\n** pCsr to the results of vprintf(zFmt, ...).\n*/\nstatic void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){\n  va_list ap;\n  va_start(ap, zFmt);\n  sqlite3_free(pTab->base.zErrMsg);\n  pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);\n  va_end(ap);\n}\nstatic void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){\n  va_list ap;\n  va_start(ap, zFmt);\n  sqlite3_free(pCsr->base.pVtab->zErrMsg);\n  pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);\n  va_end(ap);\n}\n\n/*\n** Read nRead bytes of data from offset iOff of file pFile into buffer\n** aRead[]. Return SQLITE_OK if successful, or an SQLite error code\n** otherwise. \n**\n** If an error does occur, output variable (*pzErrmsg) may be set to point\n** to an English language error message. It is the responsibility of the\n** caller to eventually free this buffer using\n** sqlite3_free().\n*/\nstatic int zipfileReadData(\n  FILE *pFile,                    /* Read from this file */\n  u8 *aRead,                      /* Read into this buffer */\n  int nRead,                      /* Number of bytes to read */\n  i64 iOff,                       /* Offset to read from */\n  char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */\n){\n  size_t n;\n  fseek(pFile, (long)iOff, SEEK_SET);\n  n = fread(aRead, 1, nRead, pFile);\n  if( (int)n!=nRead ){\n    *pzErrmsg = sqlite3_mprintf(\"error in fread()\");\n    return SQLITE_ERROR;\n  }\n  return SQLITE_OK;\n}\n\nstatic int zipfileAppendData(\n  ZipfileTab *pTab,\n  const u8 *aWrite,\n  int nWrite\n){\n  size_t n;\n  fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);\n  n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);\n  if( (int)n!=nWrite ){\n    pTab->base.zErrMsg = sqlite3_mprintf(\"error in fwrite()\");\n    return SQLITE_ERROR;\n  }\n  pTab->szCurrent += nWrite;\n  return SQLITE_OK;\n}\n\n/*\n** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.\n*/\nstatic u16 zipfileGetU16(const u8 *aBuf){\n  return (aBuf[1] << 8) + aBuf[0];\n}\n\n/*\n** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.\n*/\nstatic u32 zipfileGetU32(const u8 *aBuf){\n  return ((u32)(aBuf[3]) << 24)\n       + ((u32)(aBuf[2]) << 16)\n       + ((u32)(aBuf[1]) <<  8)\n       + ((u32)(aBuf[0]) <<  0);\n}\n\n/*\n** Write a 16-bit little endiate integer into buffer aBuf.\n*/\nstatic void zipfilePutU16(u8 *aBuf, u16 val){\n  aBuf[0] = val & 0xFF;\n  aBuf[1] = (val>>8) & 0xFF;\n}\n\n/*\n** Write a 32-bit little endiate integer into buffer aBuf.\n*/\nstatic void zipfilePutU32(u8 *aBuf, u32 val){\n  aBuf[0] = val & 0xFF;\n  aBuf[1] = (val>>8) & 0xFF;\n  aBuf[2] = (val>>16) & 0xFF;\n  aBuf[3] = (val>>24) & 0xFF;\n}\n\n#define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )\n#define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )\n\n#define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }\n#define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }\n\n/*\n** Magic numbers used to read CDS records.\n*/\n#define ZIPFILE_CDS_NFILE_OFF        28\n#define ZIPFILE_CDS_SZCOMPRESSED_OFF 20\n\n/*\n** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR\n** if the record is not well-formed, or SQLITE_OK otherwise.\n*/\nstatic int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){\n  u8 *aRead = aBuf;\n  u32 sig = zipfileRead32(aRead);\n  int rc = SQLITE_OK;\n  if( sig!=ZIPFILE_SIGNATURE_CDS ){\n    rc = SQLITE_ERROR;\n  }else{\n    pCDS->iVersionMadeBy = zipfileRead16(aRead);\n    pCDS->iVersionExtract = zipfileRead16(aRead);\n    pCDS->flags = zipfileRead16(aRead);\n    pCDS->iCompression = zipfileRead16(aRead);\n    pCDS->mTime = zipfileRead16(aRead);\n    pCDS->mDate = zipfileRead16(aRead);\n    pCDS->crc32 = zipfileRead32(aRead);\n    pCDS->szCompressed = zipfileRead32(aRead);\n    pCDS->szUncompressed = zipfileRead32(aRead);\n    assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );\n    pCDS->nFile = zipfileRead16(aRead);\n    pCDS->nExtra = zipfileRead16(aRead);\n    pCDS->nComment = zipfileRead16(aRead);\n    pCDS->iDiskStart = zipfileRead16(aRead);\n    pCDS->iInternalAttr = zipfileRead16(aRead);\n    pCDS->iExternalAttr = zipfileRead32(aRead);\n    pCDS->iOffset = zipfileRead32(aRead);\n    assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );\n  }\n\n  return rc;\n}\n\n/*\n** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR\n** if the record is not well-formed, or SQLITE_OK otherwise.\n*/\nstatic int zipfileReadLFH(\n  u8 *aBuffer,\n  ZipfileLFH *pLFH\n){\n  u8 *aRead = aBuffer;\n  int rc = SQLITE_OK;\n\n  u32 sig = zipfileRead32(aRead);\n  if( sig!=ZIPFILE_SIGNATURE_LFH ){\n    rc = SQLITE_ERROR;\n  }else{\n    pLFH->iVersionExtract = zipfileRead16(aRead);\n    pLFH->flags = zipfileRead16(aRead);\n    pLFH->iCompression = zipfileRead16(aRead);\n    pLFH->mTime = zipfileRead16(aRead);\n    pLFH->mDate = zipfileRead16(aRead);\n    pLFH->crc32 = zipfileRead32(aRead);\n    pLFH->szCompressed = zipfileRead32(aRead);\n    pLFH->szUncompressed = zipfileRead32(aRead);\n    pLFH->nFile = zipfileRead16(aRead);\n    pLFH->nExtra = zipfileRead16(aRead);\n  }\n  return rc;\n}\n\n\n/*\n** Buffer aExtra (size nExtra bytes) contains zip archive \"extra\" fields.\n** Scan through this buffer to find an \"extra-timestamp\" field. If one\n** exists, extract the 32-bit modification-timestamp from it and store\n** the value in output parameter *pmTime.\n**\n** Zero is returned if no extra-timestamp record could be found (and so\n** *pmTime is left unchanged), or non-zero otherwise.\n**\n** The general format of an extra field is:\n**\n**   Header ID    2 bytes\n**   Data Size    2 bytes\n**   Data         N bytes\n*/\nstatic int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){\n  int ret = 0;\n  u8 *p = aExtra;\n  u8 *pEnd = &aExtra[nExtra];\n\n  while( p<pEnd ){\n    u16 id = zipfileRead16(p);\n    u16 nByte = zipfileRead16(p);\n\n    switch( id ){\n      case ZIPFILE_EXTRA_TIMESTAMP: {\n        u8 b = p[0];\n        if( b & 0x01 ){     /* 0x01 -> modtime is present */\n          *pmTime = zipfileGetU32(&p[1]);\n          ret = 1;\n        }\n        break;\n      }\n    }\n\n    p += nByte;\n  }\n  return ret;\n}\n\n/*\n** Convert the standard MS-DOS timestamp stored in the mTime and mDate\n** fields of the CDS structure passed as the only argument to a 32-bit\n** UNIX seconds-since-the-epoch timestamp. Return the result.\n**\n** \"Standard\" MS-DOS time format:\n**\n**   File modification time:\n**     Bits 00-04: seconds divided by 2\n**     Bits 05-10: minute\n**     Bits 11-15: hour\n**   File modification date:\n**     Bits 00-04: day\n**     Bits 05-08: month (1-12)\n**     Bits 09-15: years from 1980 \n**\n** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx\n*/\nstatic u32 zipfileMtime(ZipfileCDS *pCDS){\n  int Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));\n  int M = ((pCDS->mDate >> 5) & 0x0F);\n  int D = (pCDS->mDate & 0x1F);\n  int B = -13;\n\n  int sec = (pCDS->mTime & 0x1F)*2;\n  int min = (pCDS->mTime >> 5) & 0x3F;\n  int hr = (pCDS->mTime >> 11) & 0x1F;\n  i64 JD;\n\n  /* JD = INT(365.25 * (Y+4716)) + INT(30.6001 * (M+1)) + D + B - 1524.5 */\n\n  /* Calculate the JD in seconds for noon on the day in question */\n  if( M<3 ){\n    Y = Y-1;\n    M = M+12;\n  }\n  JD = (i64)(24*60*60) * (\n      (int)(365.25 * (Y + 4716))\n    + (int)(30.6001 * (M + 1))\n    + D + B - 1524\n  );\n\n  /* Correct the JD for the time within the day */\n  JD += (hr-12) * 3600 + min * 60 + sec;\n\n  /* Convert JD to unix timestamp (the JD epoch is 2440587.5) */\n  return (u32)(JD - (i64)(24405875) * 24*60*6);\n}\n\n/*\n** The opposite of zipfileMtime(). This function populates the mTime and\n** mDate fields of the CDS structure passed as the first argument according\n** to the UNIX timestamp value passed as the second.\n*/\nstatic void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){\n  /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */\n  i64 JD = (i64)2440588 + mUnixTime / (24*60*60);\n\n  int A, B, C, D, E;\n  int yr, mon, day;\n  int hr, min, sec;\n\n  A = (int)((JD - 1867216.25)/36524.25);\n  A = (int)(JD + 1 + A - (A/4));\n  B = A + 1524;\n  C = (int)((B - 122.1)/365.25);\n  D = (36525*(C&32767))/100;\n  E = (int)((B-D)/30.6001);\n\n  day = B - D - (int)(30.6001*E);\n  mon = (E<14 ? E-1 : E-13);\n  yr = mon>2 ? C-4716 : C-4715;\n\n  hr = (mUnixTime % (24*60*60)) / (60*60);\n  min = (mUnixTime % (60*60)) / 60;\n  sec = (mUnixTime % 60);\n\n  if( yr>=1980 ){\n    pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));\n    pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));\n  }else{\n    pCds->mDate = pCds->mTime = 0;\n  }\n\n  assert( mUnixTime<315507600 \n       || mUnixTime==zipfileMtime(pCds) \n       || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) \n       /* || (mUnixTime % 2) */\n  );\n}\n\n/*\n** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in\n** size) containing an entire zip archive image. Or, if aBlob is NULL,\n** then pFile is a file-handle open on a zip file. In either case, this\n** function creates a ZipfileEntry object based on the zip archive entry\n** for which the CDS record is at offset iOff.\n**\n** If successful, SQLITE_OK is returned and (*ppEntry) set to point to\n** the new object. Otherwise, an SQLite error code is returned and the\n** final value of (*ppEntry) undefined.\n*/\nstatic int zipfileGetEntry(\n  ZipfileTab *pTab,               /* Store any error message here */\n  const u8 *aBlob,                /* Pointer to in-memory file image */\n  int nBlob,                      /* Size of aBlob[] in bytes */\n  FILE *pFile,                    /* If aBlob==0, read from this file */\n  i64 iOff,                       /* Offset of CDS record */\n  ZipfileEntry **ppEntry          /* OUT: Pointer to new object */\n){\n  u8 *aRead;\n  char **pzErr = &pTab->base.zErrMsg;\n  int rc = SQLITE_OK;\n\n  if( aBlob==0 ){\n    aRead = pTab->aBuffer;\n    rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);\n  }else{\n    aRead = (u8*)&aBlob[iOff];\n  }\n\n  if( rc==SQLITE_OK ){\n    sqlite3_int64 nAlloc;\n    ZipfileEntry *pNew;\n\n    int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);\n    int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);\n    nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);\n\n    nAlloc = sizeof(ZipfileEntry) + nExtra;\n    if( aBlob ){\n      nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);\n    }\n\n    pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);\n    if( pNew==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      memset(pNew, 0, sizeof(ZipfileEntry));\n      rc = zipfileReadCDS(aRead, &pNew->cds);\n      if( rc!=SQLITE_OK ){\n        *pzErr = sqlite3_mprintf(\"failed to read CDS at offset %lld\", iOff);\n      }else if( aBlob==0 ){\n        rc = zipfileReadData(\n            pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr\n        );\n      }else{\n        aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];\n      }\n    }\n\n    if( rc==SQLITE_OK ){\n      u32 *pt = &pNew->mUnixTime;\n      pNew->cds.zFile = sqlite3_mprintf(\"%.*s\", nFile, aRead); \n      pNew->aExtra = (u8*)&pNew[1];\n      memcpy(pNew->aExtra, &aRead[nFile], nExtra);\n      if( pNew->cds.zFile==0 ){\n        rc = SQLITE_NOMEM;\n      }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){\n        pNew->mUnixTime = zipfileMtime(&pNew->cds);\n      }\n    }\n\n    if( rc==SQLITE_OK ){\n      static const int szFix = ZIPFILE_LFH_FIXED_SZ;\n      ZipfileLFH lfh;\n      if( pFile ){\n        rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);\n      }else{\n        aRead = (u8*)&aBlob[pNew->cds.iOffset];\n      }\n\n      rc = zipfileReadLFH(aRead, &lfh);\n      if( rc==SQLITE_OK ){\n        pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;\n        pNew->iDataOff += lfh.nFile + lfh.nExtra;\n        if( aBlob && pNew->cds.szCompressed ){\n          pNew->aData = &pNew->aExtra[nExtra];\n          memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);\n        }\n      }else{\n        *pzErr = sqlite3_mprintf(\"failed to read LFH at offset %d\", \n            (int)pNew->cds.iOffset\n        );\n      }\n    }\n\n    if( rc!=SQLITE_OK ){\n      zipfileEntryFree(pNew);\n    }else{\n      *ppEntry = pNew;\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Advance an ZipfileCsr to its next row of output.\n*/\nstatic int zipfileNext(sqlite3_vtab_cursor *cur){\n  ZipfileCsr *pCsr = (ZipfileCsr*)cur;\n  int rc = SQLITE_OK;\n\n  if( pCsr->pFile ){\n    i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;\n    zipfileEntryFree(pCsr->pCurrent);\n    pCsr->pCurrent = 0;\n    if( pCsr->iNextOff>=iEof ){\n      pCsr->bEof = 1;\n    }else{\n      ZipfileEntry *p = 0;\n      ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);\n      rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);\n      if( rc==SQLITE_OK ){\n        pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;\n        pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;\n      }\n      pCsr->pCurrent = p;\n    }\n  }else{\n    if( !pCsr->bNoop ){\n      pCsr->pCurrent = pCsr->pCurrent->pNext;\n    }\n    if( pCsr->pCurrent==0 ){\n      pCsr->bEof = 1;\n    }\n  }\n\n  pCsr->bNoop = 0;\n  return rc;\n}\n\nstatic void zipfileFree(void *p) { \n  sqlite3_free(p); \n}\n\n/*\n** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the\n** size is nOut bytes. This function uncompresses the data and sets the\n** return value in context pCtx to the result (a blob).\n**\n** If an error occurs, an error code is left in pCtx instead.\n*/\nstatic void zipfileInflate(\n  sqlite3_context *pCtx,          /* Store result here */\n  const u8 *aIn,                  /* Compressed data */\n  int nIn,                        /* Size of buffer aIn[] in bytes */\n  int nOut                        /* Expected output size */\n){\n  u8 *aRes = sqlite3_malloc(nOut);\n  if( aRes==0 ){\n    sqlite3_result_error_nomem(pCtx);\n  }else{\n    int err;\n    z_stream str;\n    memset(&str, 0, sizeof(str));\n\n    str.next_in = (Byte*)aIn;\n    str.avail_in = nIn;\n    str.next_out = (Byte*)aRes;\n    str.avail_out = nOut;\n\n    err = inflateInit2(&str, -15);\n    if( err!=Z_OK ){\n      zipfileCtxErrorMsg(pCtx, \"inflateInit2() failed (%d)\", err);\n    }else{\n      err = inflate(&str, Z_NO_FLUSH);\n      if( err!=Z_STREAM_END ){\n        zipfileCtxErrorMsg(pCtx, \"inflate() failed (%d)\", err);\n      }else{\n        sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);\n        aRes = 0;\n      }\n    }\n    sqlite3_free(aRes);\n    inflateEnd(&str);\n  }\n}\n\n/*\n** Buffer aIn (size nIn bytes) contains uncompressed data. This function\n** compresses it and sets (*ppOut) to point to a buffer containing the\n** compressed data. The caller is responsible for eventually calling\n** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut) \n** is set to the size of buffer (*ppOut) in bytes.\n**\n** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error\n** code is returned and an error message left in virtual-table handle\n** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this\n** case.\n*/\nstatic int zipfileDeflate(\n  const u8 *aIn, int nIn,         /* Input */\n  u8 **ppOut, int *pnOut,         /* Output */\n  char **pzErr                    /* OUT: Error message */\n){\n  int rc = SQLITE_OK;\n  sqlite3_int64 nAlloc;\n  z_stream str;\n  u8 *aOut;\n\n  memset(&str, 0, sizeof(str));\n  str.next_in = (Bytef*)aIn;\n  str.avail_in = nIn;\n  deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);\n\n  nAlloc = deflateBound(&str, nIn);\n  aOut = (u8*)sqlite3_malloc64(nAlloc);\n  if( aOut==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    int res;\n    str.next_out = aOut;\n    str.avail_out = nAlloc;\n    res = deflate(&str, Z_FINISH);\n    if( res==Z_STREAM_END ){\n      *ppOut = aOut;\n      *pnOut = (int)str.total_out;\n    }else{\n      sqlite3_free(aOut);\n      *pzErr = sqlite3_mprintf(\"zipfile: deflate() error\");\n      rc = SQLITE_ERROR;\n    }\n    deflateEnd(&str);\n  }\n\n  return rc;\n}\n\n\n/*\n** Return values of columns for the row at which the series_cursor\n** is currently pointing.\n*/\nstatic int zipfileColumn(\n  sqlite3_vtab_cursor *cur,   /* The cursor */\n  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */\n  int i                       /* Which column to return */\n){\n  ZipfileCsr *pCsr = (ZipfileCsr*)cur;\n  ZipfileCDS *pCDS = &pCsr->pCurrent->cds;\n  int rc = SQLITE_OK;\n  switch( i ){\n    case 0:   /* name */\n      sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);\n      break;\n    case 1:   /* mode */\n      /* TODO: Whether or not the following is correct surely depends on\n      ** the platform on which the archive was created.  */\n      sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);\n      break;\n    case 2: { /* mtime */\n      sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);\n      break;\n    }\n    case 3: { /* sz */\n      if( sqlite3_vtab_nochange(ctx)==0 ){\n        sqlite3_result_int64(ctx, pCDS->szUncompressed);\n      }\n      break;\n    }\n    case 4:   /* rawdata */\n      if( sqlite3_vtab_nochange(ctx) ) break;\n    case 5: { /* data */\n      if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){\n        int sz = pCDS->szCompressed;\n        int szFinal = pCDS->szUncompressed;\n        if( szFinal>0 ){\n          u8 *aBuf;\n          u8 *aFree = 0;\n          if( pCsr->pCurrent->aData ){\n            aBuf = pCsr->pCurrent->aData;\n          }else{\n            aBuf = aFree = sqlite3_malloc64(sz);\n            if( aBuf==0 ){\n              rc = SQLITE_NOMEM;\n            }else{\n              FILE *pFile = pCsr->pFile;\n              if( pFile==0 ){\n                pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;\n              }\n              rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,\n                  &pCsr->base.pVtab->zErrMsg\n              );\n            }\n          }\n          if( rc==SQLITE_OK ){\n            if( i==5 && pCDS->iCompression ){\n              zipfileInflate(ctx, aBuf, sz, szFinal);\n            }else{\n              sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);\n            }\n          }\n          sqlite3_free(aFree);\n        }else{\n          /* Figure out if this is a directory or a zero-sized file. Consider\n          ** it to be a directory either if the mode suggests so, or if\n          ** the final character in the name is '/'.  */\n          u32 mode = pCDS->iExternalAttr >> 16;\n          if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){\n            sqlite3_result_blob(ctx, \"\", 0, SQLITE_STATIC);\n          }\n        }\n      }\n      break;\n    }\n    case 6:   /* method */\n      sqlite3_result_int(ctx, pCDS->iCompression);\n      break;\n    default:  /* z */\n      assert( i==7 );\n      sqlite3_result_int64(ctx, pCsr->iId);\n      break;\n  }\n\n  return rc;\n}\n\n/*\n** Return TRUE if the cursor is at EOF.\n*/\nstatic int zipfileEof(sqlite3_vtab_cursor *cur){\n  ZipfileCsr *pCsr = (ZipfileCsr*)cur;\n  return pCsr->bEof;\n}\n\n/*\n** If aBlob is not NULL, then it points to a buffer nBlob bytes in size\n** containing an entire zip archive image. Or, if aBlob is NULL, then pFile\n** is guaranteed to be a file-handle open on a zip file.\n**\n** This function attempts to locate the EOCD record within the zip archive\n** and populate *pEOCD with the results of decoding it. SQLITE_OK is\n** returned if successful. Otherwise, an SQLite error code is returned and\n** an English language error message may be left in virtual-table pTab.\n*/\nstatic int zipfileReadEOCD(\n  ZipfileTab *pTab,               /* Return errors here */\n  const u8 *aBlob,                /* Pointer to in-memory file image */\n  int nBlob,                      /* Size of aBlob[] in bytes */\n  FILE *pFile,                    /* Read from this file if aBlob==0 */\n  ZipfileEOCD *pEOCD              /* Object to populate */\n){\n  u8 *aRead = pTab->aBuffer;      /* Temporary buffer */\n  int nRead;                      /* Bytes to read from file */\n  int rc = SQLITE_OK;\n\n  if( aBlob==0 ){\n    i64 iOff;                     /* Offset to read from */\n    i64 szFile;                   /* Total size of file in bytes */\n    fseek(pFile, 0, SEEK_END);\n    szFile = (i64)ftell(pFile);\n    if( szFile==0 ){\n      memset(pEOCD, 0, sizeof(ZipfileEOCD));\n      return SQLITE_OK;\n    }\n    nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));\n    iOff = szFile - nRead;\n    rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);\n  }else{\n    nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));\n    aRead = (u8*)&aBlob[nBlob-nRead];\n  }\n\n  if( rc==SQLITE_OK ){\n    int i;\n\n    /* Scan backwards looking for the signature bytes */\n    for(i=nRead-20; i>=0; i--){\n      if( aRead[i]==0x50 && aRead[i+1]==0x4b \n       && aRead[i+2]==0x05 && aRead[i+3]==0x06 \n      ){\n        break;\n      }\n    }\n    if( i<0 ){\n      pTab->base.zErrMsg = sqlite3_mprintf(\n          \"cannot find end of central directory record\"\n      );\n      return SQLITE_ERROR;\n    }\n\n    aRead += i+4;\n    pEOCD->iDisk = zipfileRead16(aRead);\n    pEOCD->iFirstDisk = zipfileRead16(aRead);\n    pEOCD->nEntry = zipfileRead16(aRead);\n    pEOCD->nEntryTotal = zipfileRead16(aRead);\n    pEOCD->nSize = zipfileRead32(aRead);\n    pEOCD->iOffset = zipfileRead32(aRead);\n  }\n\n  return rc;\n}\n\n/*\n** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry \n** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added\n** to the end of the list. Otherwise, it is added to the list immediately\n** before pBefore (which is guaranteed to be a part of said list).\n*/\nstatic void zipfileAddEntry(\n  ZipfileTab *pTab, \n  ZipfileEntry *pBefore, \n  ZipfileEntry *pNew\n){\n  assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );\n  assert( pNew->pNext==0 );\n  if( pBefore==0 ){\n    if( pTab->pFirstEntry==0 ){\n      pTab->pFirstEntry = pTab->pLastEntry = pNew;\n    }else{\n      assert( pTab->pLastEntry->pNext==0 );\n      pTab->pLastEntry->pNext = pNew;\n      pTab->pLastEntry = pNew;\n    }\n  }else{\n    ZipfileEntry **pp;\n    for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));\n    pNew->pNext = pBefore;\n    *pp = pNew;\n  }\n}\n\nstatic int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){\n  ZipfileEOCD eocd;\n  int rc;\n  int i;\n  i64 iOff;\n\n  rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);\n  iOff = eocd.iOffset;\n  for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){\n    ZipfileEntry *pNew = 0;\n    rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);\n\n    if( rc==SQLITE_OK ){\n      zipfileAddEntry(pTab, 0, pNew);\n      iOff += ZIPFILE_CDS_FIXED_SZ;\n      iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;\n    }\n  }\n  return rc;\n}\n\n/*\n** xFilter callback.\n*/\nstatic int zipfileFilter(\n  sqlite3_vtab_cursor *cur, \n  int idxNum, const char *idxStr,\n  int argc, sqlite3_value **argv\n){\n  ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;\n  ZipfileCsr *pCsr = (ZipfileCsr*)cur;\n  const char *zFile = 0;          /* Zip file to scan */\n  int rc = SQLITE_OK;             /* Return Code */\n  int bInMemory = 0;              /* True for an in-memory zipfile */\n\n  zipfileResetCursor(pCsr);\n\n  if( pTab->zFile ){\n    zFile = pTab->zFile;\n  }else if( idxNum==0 ){\n    zipfileCursorErr(pCsr, \"zipfile() function requires an argument\");\n    return SQLITE_ERROR;\n  }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){\n    const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);\n    int nBlob = sqlite3_value_bytes(argv[0]);\n    assert( pTab->pFirstEntry==0 );\n    rc = zipfileLoadDirectory(pTab, aBlob, nBlob);\n    pCsr->pFreeEntry = pTab->pFirstEntry;\n    pTab->pFirstEntry = pTab->pLastEntry = 0;\n    if( rc!=SQLITE_OK ) return rc;\n    bInMemory = 1;\n  }else{\n    zFile = (const char*)sqlite3_value_text(argv[0]);\n  }\n\n  if( 0==pTab->pWriteFd && 0==bInMemory ){\n    pCsr->pFile = fopen(zFile, \"rb\");\n    if( pCsr->pFile==0 ){\n      zipfileCursorErr(pCsr, \"cannot open file: %s\", zFile);\n      rc = SQLITE_ERROR;\n    }else{\n      rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);\n      if( rc==SQLITE_OK ){\n        if( pCsr->eocd.nEntry==0 ){\n          pCsr->bEof = 1;\n        }else{\n          pCsr->iNextOff = pCsr->eocd.iOffset;\n          rc = zipfileNext(cur);\n        }\n      }\n    }\n  }else{\n    pCsr->bNoop = 1;\n    pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;\n    rc = zipfileNext(cur);\n  }\n\n  return rc;\n}\n\n/*\n** xBestIndex callback.\n*/\nstatic int zipfileBestIndex(\n  sqlite3_vtab *tab,\n  sqlite3_index_info *pIdxInfo\n){\n  int i;\n  int idx = -1;\n  int unusable = 0;\n\n  for(i=0; i<pIdxInfo->nConstraint; i++){\n    const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];\n    if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;\n    if( pCons->usable==0 ){\n      unusable = 1;\n    }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){\n      idx = i;\n    }\n  }\n  pIdxInfo->estimatedCost = 1000.0;\n  if( idx>=0 ){\n    pIdxInfo->aConstraintUsage[idx].argvIndex = 1;\n    pIdxInfo->aConstraintUsage[idx].omit = 1;\n    pIdxInfo->idxNum = 1;\n  }else if( unusable ){\n    return SQLITE_CONSTRAINT;\n  }\n  return SQLITE_OK;\n}\n\nstatic ZipfileEntry *zipfileNewEntry(const char *zPath){\n  ZipfileEntry *pNew;\n  pNew = sqlite3_malloc(sizeof(ZipfileEntry));\n  if( pNew ){\n    memset(pNew, 0, sizeof(ZipfileEntry));\n    pNew->cds.zFile = sqlite3_mprintf(\"%s\", zPath);\n    if( pNew->cds.zFile==0 ){\n      sqlite3_free(pNew);\n      pNew = 0;\n    }\n  }\n  return pNew;\n}\n\nstatic int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){\n  ZipfileCDS *pCds = &pEntry->cds;\n  u8 *a = aBuf;\n\n  pCds->nExtra = 9;\n\n  /* Write the LFH itself */\n  zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);\n  zipfileWrite16(a, pCds->iVersionExtract);\n  zipfileWrite16(a, pCds->flags);\n  zipfileWrite16(a, pCds->iCompression);\n  zipfileWrite16(a, pCds->mTime);\n  zipfileWrite16(a, pCds->mDate);\n  zipfileWrite32(a, pCds->crc32);\n  zipfileWrite32(a, pCds->szCompressed);\n  zipfileWrite32(a, pCds->szUncompressed);\n  zipfileWrite16(a, (u16)pCds->nFile);\n  zipfileWrite16(a, pCds->nExtra);\n  assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );\n\n  /* Add the file name */\n  memcpy(a, pCds->zFile, (int)pCds->nFile);\n  a += (int)pCds->nFile;\n\n  /* The \"extra\" data */\n  zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);\n  zipfileWrite16(a, 5);\n  *a++ = 0x01;\n  zipfileWrite32(a, pEntry->mUnixTime);\n\n  return a-aBuf;\n}\n\nstatic int zipfileAppendEntry(\n  ZipfileTab *pTab,\n  ZipfileEntry *pEntry,\n  const u8 *pData,\n  int nData\n){\n  u8 *aBuf = pTab->aBuffer;\n  int nBuf;\n  int rc;\n\n  nBuf = zipfileSerializeLFH(pEntry, aBuf);\n  rc = zipfileAppendData(pTab, aBuf, nBuf);\n  if( rc==SQLITE_OK ){\n    pEntry->iDataOff = pTab->szCurrent;\n    rc = zipfileAppendData(pTab, pData, nData);\n  }\n\n  return rc;\n}\n\nstatic int zipfileGetMode(\n  sqlite3_value *pVal, \n  int bIsDir,                     /* If true, default to directory */\n  u32 *pMode,                     /* OUT: Mode value */\n  char **pzErr                    /* OUT: Error message */\n){\n  const char *z = (const char*)sqlite3_value_text(pVal);\n  u32 mode = 0;\n  if( z==0 ){\n    mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));\n  }else if( z[0]>='0' && z[0]<='9' ){\n    mode = (unsigned int)sqlite3_value_int(pVal);\n  }else{\n    const char zTemplate[11] = \"-rwxrwxrwx\";\n    int i;\n    if( strlen(z)!=10 ) goto parse_error;\n    switch( z[0] ){\n      case '-': mode |= S_IFREG; break;\n      case 'd': mode |= S_IFDIR; break;\n      case 'l': mode |= S_IFLNK; break;\n      default: goto parse_error;\n    }\n    for(i=1; i<10; i++){\n      if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);\n      else if( z[i]!='-' ) goto parse_error;\n    }\n  }\n  if( ((mode & S_IFDIR)==0)==bIsDir ){\n    /* The \"mode\" attribute is a directory, but data has been specified.\n    ** Or vice-versa - no data but \"mode\" is a file or symlink.  */\n    *pzErr = sqlite3_mprintf(\"zipfile: mode does not match data\");\n    return SQLITE_CONSTRAINT;\n  }\n  *pMode = mode;\n  return SQLITE_OK;\n\n parse_error:\n  *pzErr = sqlite3_mprintf(\"zipfile: parse error in mode: %s\", z);\n  return SQLITE_ERROR;\n}\n\n/*\n** Both (const char*) arguments point to nul-terminated strings. Argument\n** nB is the value of strlen(zB). This function returns 0 if the strings are\n** identical, ignoring any trailing '/' character in either path.  */\nstatic int zipfileComparePath(const char *zA, const char *zB, int nB){\n  int nA = (int)strlen(zA);\n  if( nA>0 && zA[nA-1]=='/' ) nA--;\n  if( nB>0 && zB[nB-1]=='/' ) nB--;\n  if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;\n  return 1;\n}\n\nstatic int zipfileBegin(sqlite3_vtab *pVtab){\n  ZipfileTab *pTab = (ZipfileTab*)pVtab;\n  int rc = SQLITE_OK;\n\n  assert( pTab->pWriteFd==0 );\n  if( pTab->zFile==0 || pTab->zFile[0]==0 ){\n    pTab->base.zErrMsg = sqlite3_mprintf(\"zipfile: missing filename\");\n    return SQLITE_ERROR;\n  }\n\n  /* Open a write fd on the file. Also load the entire central directory\n  ** structure into memory. During the transaction any new file data is \n  ** appended to the archive file, but the central directory is accumulated\n  ** in main-memory until the transaction is committed.  */\n  pTab->pWriteFd = fopen(pTab->zFile, \"ab+\");\n  if( pTab->pWriteFd==0 ){\n    pTab->base.zErrMsg = sqlite3_mprintf(\n        \"zipfile: failed to open file %s for writing\", pTab->zFile\n        );\n    rc = SQLITE_ERROR;\n  }else{\n    fseek(pTab->pWriteFd, 0, SEEK_END);\n    pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);\n    rc = zipfileLoadDirectory(pTab, 0, 0);\n  }\n\n  if( rc!=SQLITE_OK ){\n    zipfileCleanupTransaction(pTab);\n  }\n\n  return rc;\n}\n\n/*\n** Return the current time as a 32-bit timestamp in UNIX epoch format (like\n** time(2)).\n*/\nstatic u32 zipfileTime(void){\n  sqlite3_vfs *pVfs = sqlite3_vfs_find(0);\n  u32 ret;\n  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){\n    i64 ms;\n    pVfs->xCurrentTimeInt64(pVfs, &ms);\n    ret = (u32)((ms/1000) - ((i64)24405875 * 8640));\n  }else{\n    double day;\n    pVfs->xCurrentTime(pVfs, &day);\n    ret = (u32)((day - 2440587.5) * 86400);\n  }\n  return ret;\n}\n\n/*\n** Return a 32-bit timestamp in UNIX epoch format.\n**\n** If the value passed as the only argument is either NULL or an SQL NULL,\n** return the current time. Otherwise, return the value stored in (*pVal)\n** cast to a 32-bit unsigned integer.\n*/\nstatic u32 zipfileGetTime(sqlite3_value *pVal){\n  if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){\n    return zipfileTime();\n  }\n  return (u32)sqlite3_value_int64(pVal);\n}\n\n/*\n** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry\n** linked list.  Remove it from the list and free the object.\n*/\nstatic void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){\n  if( pOld ){\n    ZipfileEntry **pp;\n    for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));\n    *pp = (*pp)->pNext;\n    zipfileEntryFree(pOld);\n  }\n}\n\n/*\n** xUpdate method.\n*/\nstatic int zipfileUpdate(\n  sqlite3_vtab *pVtab, \n  int nVal, \n  sqlite3_value **apVal, \n  sqlite_int64 *pRowid\n){\n  ZipfileTab *pTab = (ZipfileTab*)pVtab;\n  int rc = SQLITE_OK;             /* Return Code */\n  ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */\n\n  u32 mode = 0;                   /* Mode for new entry */\n  u32 mTime = 0;                  /* Modification time for new entry */\n  i64 sz = 0;                     /* Uncompressed size */\n  const char *zPath = 0;          /* Path for new entry */\n  int nPath = 0;                  /* strlen(zPath) */\n  const u8 *pData = 0;            /* Pointer to buffer containing content */\n  int nData = 0;                  /* Size of pData buffer in bytes */\n  int iMethod = 0;                /* Compression method for new entry */\n  u8 *pFree = 0;                  /* Free this */\n  char *zFree = 0;                /* Also free this */\n  ZipfileEntry *pOld = 0;\n  ZipfileEntry *pOld2 = 0;\n  int bUpdate = 0;                /* True for an update that modifies \"name\" */\n  int bIsDir = 0;\n  u32 iCrc32 = 0;\n\n  if( pTab->pWriteFd==0 ){\n    rc = zipfileBegin(pVtab);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n\n  /* If this is a DELETE or UPDATE, find the archive entry to delete. */\n  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){\n    const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);\n    int nDelete = (int)strlen(zDelete);\n    if( nVal>1 ){\n      const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);\n      if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){\n        bUpdate = 1;\n      }\n    }\n    for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){\n      if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){\n        break;\n      }\n      assert( pOld->pNext );\n    }\n  }\n\n  if( nVal>1 ){\n    /* Check that \"sz\" and \"rawdata\" are both NULL: */\n    if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){\n      zipfileTableErr(pTab, \"sz must be NULL\");\n      rc = SQLITE_CONSTRAINT;\n    }\n    if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){\n      zipfileTableErr(pTab, \"rawdata must be NULL\"); \n      rc = SQLITE_CONSTRAINT;\n    }\n\n    if( rc==SQLITE_OK ){\n      if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){\n        /* data=NULL. A directory */\n        bIsDir = 1;\n      }else{\n        /* Value specified for \"data\", and possibly \"method\". This must be\n        ** a regular file or a symlink. */\n        const u8 *aIn = sqlite3_value_blob(apVal[7]);\n        int nIn = sqlite3_value_bytes(apVal[7]);\n        int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;\n\n        iMethod = sqlite3_value_int(apVal[8]);\n        sz = nIn;\n        pData = aIn;\n        nData = nIn;\n        if( iMethod!=0 && iMethod!=8 ){\n          zipfileTableErr(pTab, \"unknown compression method: %d\", iMethod);\n          rc = SQLITE_CONSTRAINT;\n        }else{\n          if( bAuto || iMethod ){\n            int nCmp;\n            rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);\n            if( rc==SQLITE_OK ){\n              if( iMethod || nCmp<nIn ){\n                iMethod = 8;\n                pData = pFree;\n                nData = nCmp;\n              }\n            }\n          }\n          iCrc32 = crc32(0, aIn, nIn);\n        }\n      }\n    }\n\n    if( rc==SQLITE_OK ){\n      rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);\n    }\n\n    if( rc==SQLITE_OK ){\n      zPath = (const char*)sqlite3_value_text(apVal[2]);\n      if( zPath==0 ) zPath = \"\";\n      nPath = (int)strlen(zPath);\n      mTime = zipfileGetTime(apVal[4]);\n    }\n\n    if( rc==SQLITE_OK && bIsDir ){\n      /* For a directory, check that the last character in the path is a\n      ** '/'. This appears to be required for compatibility with info-zip\n      ** (the unzip command on unix). It does not create directories\n      ** otherwise.  */\n      if( nPath<=0 || zPath[nPath-1]!='/' ){\n        zFree = sqlite3_mprintf(\"%s/\", zPath);\n        zPath = (const char*)zFree;\n        if( zFree==0 ){\n          rc = SQLITE_NOMEM;\n          nPath = 0;\n        }else{\n          nPath = (int)strlen(zPath);\n        }\n      }\n    }\n\n    /* Check that we're not inserting a duplicate entry -OR- updating an\n    ** entry with a path, thereby making it into a duplicate. */\n    if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){\n      ZipfileEntry *p;\n      for(p=pTab->pFirstEntry; p; p=p->pNext){\n        if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){\n          switch( sqlite3_vtab_on_conflict(pTab->db) ){\n            case SQLITE_IGNORE: {\n              goto zipfile_update_done;\n            }\n            case SQLITE_REPLACE: {\n              pOld2 = p;\n              break;\n            }\n            default: {\n              zipfileTableErr(pTab, \"duplicate name: \\\"%s\\\"\", zPath);\n              rc = SQLITE_CONSTRAINT;\n              break;\n            }\n          }\n          break;\n        }\n      }\n    }\n\n    if( rc==SQLITE_OK ){\n      /* Create the new CDS record. */\n      pNew = zipfileNewEntry(zPath);\n      if( pNew==0 ){\n        rc = SQLITE_NOMEM;\n      }else{\n        pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;\n        pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;\n        pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;\n        pNew->cds.iCompression = (u16)iMethod;\n        zipfileMtimeToDos(&pNew->cds, mTime);\n        pNew->cds.crc32 = iCrc32;\n        pNew->cds.szCompressed = nData;\n        pNew->cds.szUncompressed = (u32)sz;\n        pNew->cds.iExternalAttr = (mode<<16);\n        pNew->cds.iOffset = (u32)pTab->szCurrent;\n        pNew->cds.nFile = (u16)nPath;\n        pNew->mUnixTime = (u32)mTime;\n        rc = zipfileAppendEntry(pTab, pNew, pData, nData);\n        zipfileAddEntry(pTab, pOld, pNew);\n      }\n    }\n  }\n\n  if( rc==SQLITE_OK && (pOld || pOld2) ){\n    ZipfileCsr *pCsr;\n    for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){\n      if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){\n        pCsr->pCurrent = pCsr->pCurrent->pNext;\n        pCsr->bNoop = 1;\n      }\n    }\n\n    zipfileRemoveEntryFromList(pTab, pOld);\n    zipfileRemoveEntryFromList(pTab, pOld2);\n  }\n\nzipfile_update_done:\n  sqlite3_free(pFree);\n  sqlite3_free(zFree);\n  return rc;\n}\n\nstatic int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){\n  u8 *a = aBuf;\n  zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);\n  zipfileWrite16(a, p->iDisk);\n  zipfileWrite16(a, p->iFirstDisk);\n  zipfileWrite16(a, p->nEntry);\n  zipfileWrite16(a, p->nEntryTotal);\n  zipfileWrite32(a, p->nSize);\n  zipfileWrite32(a, p->iOffset);\n  zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/\n\n  return a-aBuf;\n}\n\nstatic int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){\n  int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);\n  assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );\n  return zipfileAppendData(pTab, pTab->aBuffer, nBuf);\n}\n\n/*\n** Serialize the CDS structure into buffer aBuf[]. Return the number\n** of bytes written.\n*/\nstatic int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){\n  u8 *a = aBuf;\n  ZipfileCDS *pCDS = &pEntry->cds;\n\n  if( pEntry->aExtra==0 ){\n    pCDS->nExtra = 9;\n  }\n\n  zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);\n  zipfileWrite16(a, pCDS->iVersionMadeBy);\n  zipfileWrite16(a, pCDS->iVersionExtract);\n  zipfileWrite16(a, pCDS->flags);\n  zipfileWrite16(a, pCDS->iCompression);\n  zipfileWrite16(a, pCDS->mTime);\n  zipfileWrite16(a, pCDS->mDate);\n  zipfileWrite32(a, pCDS->crc32);\n  zipfileWrite32(a, pCDS->szCompressed);\n  zipfileWrite32(a, pCDS->szUncompressed);\n  assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );\n  zipfileWrite16(a, pCDS->nFile);\n  zipfileWrite16(a, pCDS->nExtra);\n  zipfileWrite16(a, pCDS->nComment);\n  zipfileWrite16(a, pCDS->iDiskStart);\n  zipfileWrite16(a, pCDS->iInternalAttr);\n  zipfileWrite32(a, pCDS->iExternalAttr);\n  zipfileWrite32(a, pCDS->iOffset);\n\n  memcpy(a, pCDS->zFile, pCDS->nFile);\n  a += pCDS->nFile;\n\n  if( pEntry->aExtra ){\n    int n = (int)pCDS->nExtra + (int)pCDS->nComment;\n    memcpy(a, pEntry->aExtra, n);\n    a += n;\n  }else{\n    assert( pCDS->nExtra==9 );\n    zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);\n    zipfileWrite16(a, 5);\n    *a++ = 0x01;\n    zipfileWrite32(a, pEntry->mUnixTime);\n  }\n\n  return a-aBuf;\n}\n\nstatic int zipfileCommit(sqlite3_vtab *pVtab){\n  ZipfileTab *pTab = (ZipfileTab*)pVtab;\n  int rc = SQLITE_OK;\n  if( pTab->pWriteFd ){\n    i64 iOffset = pTab->szCurrent;\n    ZipfileEntry *p;\n    ZipfileEOCD eocd;\n    int nEntry = 0;\n\n    /* Write out all entries */\n    for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){\n      int n = zipfileSerializeCDS(p, pTab->aBuffer);\n      rc = zipfileAppendData(pTab, pTab->aBuffer, n);\n      nEntry++;\n    }\n\n    /* Write out the EOCD record */\n    eocd.iDisk = 0;\n    eocd.iFirstDisk = 0;\n    eocd.nEntry = (u16)nEntry;\n    eocd.nEntryTotal = (u16)nEntry;\n    eocd.nSize = (u32)(pTab->szCurrent - iOffset);\n    eocd.iOffset = (u32)iOffset;\n    rc = zipfileAppendEOCD(pTab, &eocd);\n\n    zipfileCleanupTransaction(pTab);\n  }\n  return rc;\n}\n\nstatic int zipfileRollback(sqlite3_vtab *pVtab){\n  return zipfileCommit(pVtab);\n}\n\nstatic ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){\n  ZipfileCsr *pCsr;\n  for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){\n    if( iId==pCsr->iId ) break;\n  }\n  return pCsr;\n}\n\nstatic void zipfileFunctionCds(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  ZipfileCsr *pCsr;\n  ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);\n  assert( argc>0 );\n\n  pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));\n  if( pCsr ){\n    ZipfileCDS *p = &pCsr->pCurrent->cds;\n    char *zRes = sqlite3_mprintf(\"{\"\n        \"\\\"version-made-by\\\" : %u, \"\n        \"\\\"version-to-extract\\\" : %u, \"\n        \"\\\"flags\\\" : %u, \"\n        \"\\\"compression\\\" : %u, \"\n        \"\\\"time\\\" : %u, \"\n        \"\\\"date\\\" : %u, \"\n        \"\\\"crc32\\\" : %u, \"\n        \"\\\"compressed-size\\\" : %u, \"\n        \"\\\"uncompressed-size\\\" : %u, \"\n        \"\\\"file-name-length\\\" : %u, \"\n        \"\\\"extra-field-length\\\" : %u, \"\n        \"\\\"file-comment-length\\\" : %u, \"\n        \"\\\"disk-number-start\\\" : %u, \"\n        \"\\\"internal-attr\\\" : %u, \"\n        \"\\\"external-attr\\\" : %u, \"\n        \"\\\"offset\\\" : %u }\",\n        (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,\n        (u32)p->flags, (u32)p->iCompression,\n        (u32)p->mTime, (u32)p->mDate,\n        (u32)p->crc32, (u32)p->szCompressed,\n        (u32)p->szUncompressed, (u32)p->nFile,\n        (u32)p->nExtra, (u32)p->nComment,\n        (u32)p->iDiskStart, (u32)p->iInternalAttr,\n        (u32)p->iExternalAttr, (u32)p->iOffset\n    );\n\n    if( zRes==0 ){\n      sqlite3_result_error_nomem(context);\n    }else{\n      sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);\n      sqlite3_free(zRes);\n    }\n  }\n}\n\n/*\n** xFindFunction method.\n*/\nstatic int zipfileFindFunction(\n  sqlite3_vtab *pVtab,            /* Virtual table handle */\n  int nArg,                       /* Number of SQL function arguments */\n  const char *zName,              /* Name of SQL function */\n  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */\n  void **ppArg                    /* OUT: User data for *pxFunc */\n){\n  if( sqlite3_stricmp(\"zipfile_cds\", zName)==0 ){\n    *pxFunc = zipfileFunctionCds;\n    *ppArg = (void*)pVtab;\n    return 1;\n  }\n  return 0;\n}\n\ntypedef struct ZipfileBuffer ZipfileBuffer;\nstruct ZipfileBuffer {\n  u8 *a;                          /* Pointer to buffer */\n  int n;                          /* Size of buffer in bytes */\n  int nAlloc;                     /* Byte allocated at a[] */\n};\n\ntypedef struct ZipfileCtx ZipfileCtx;\nstruct ZipfileCtx {\n  int nEntry;\n  ZipfileBuffer body;\n  ZipfileBuffer cds;\n};\n\nstatic int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){\n  if( pBuf->n+nByte>pBuf->nAlloc ){\n    u8 *aNew;\n    sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;\n    int nReq = pBuf->n + nByte;\n\n    while( nNew<nReq ) nNew = nNew*2;\n    aNew = sqlite3_realloc64(pBuf->a, nNew);\n    if( aNew==0 ) return SQLITE_NOMEM;\n    pBuf->a = aNew;\n    pBuf->nAlloc = (int)nNew;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** xStep() callback for the zipfile() aggregate. This can be called in\n** any of the following ways:\n**\n**   SELECT zipfile(name,data) ...\n**   SELECT zipfile(name,mode,mtime,data) ...\n**   SELECT zipfile(name,mode,mtime,data,method) ...\n*/\nvoid zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){\n  ZipfileCtx *p;                  /* Aggregate function context */\n  ZipfileEntry e;                 /* New entry to add to zip archive */\n\n  sqlite3_value *pName = 0;\n  sqlite3_value *pMode = 0;\n  sqlite3_value *pMtime = 0;\n  sqlite3_value *pData = 0;\n  sqlite3_value *pMethod = 0;\n\n  int bIsDir = 0;\n  u32 mode;\n  int rc = SQLITE_OK;\n  char *zErr = 0;\n\n  int iMethod = -1;               /* Compression method to use (0 or 8) */\n\n  const u8 *aData = 0;            /* Possibly compressed data for new entry */\n  int nData = 0;                  /* Size of aData[] in bytes */\n  int szUncompressed = 0;         /* Size of data before compression */\n  u8 *aFree = 0;                  /* Free this before returning */\n  u32 iCrc32 = 0;                 /* crc32 of uncompressed data */\n\n  char *zName = 0;                /* Path (name) of new entry */\n  int nName = 0;                  /* Size of zName in bytes */\n  char *zFree = 0;                /* Free this before returning */\n  int nByte;\n\n  memset(&e, 0, sizeof(e));\n  p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));\n  if( p==0 ) return;\n\n  /* Martial the arguments into stack variables */\n  if( nVal!=2 && nVal!=4 && nVal!=5 ){\n    zErr = sqlite3_mprintf(\"wrong number of arguments to function zipfile()\");\n    rc = SQLITE_ERROR;\n    goto zipfile_step_out;\n  }\n  pName = apVal[0];\n  if( nVal==2 ){\n    pData = apVal[1];\n  }else{\n    pMode = apVal[1];\n    pMtime = apVal[2];\n    pData = apVal[3];\n    if( nVal==5 ){\n      pMethod = apVal[4];\n    }\n  }\n\n  /* Check that the 'name' parameter looks ok. */\n  zName = (char*)sqlite3_value_text(pName);\n  nName = sqlite3_value_bytes(pName);\n  if( zName==0 ){\n    zErr = sqlite3_mprintf(\"first argument to zipfile() must be non-NULL\");\n    rc = SQLITE_ERROR;\n    goto zipfile_step_out;\n  }\n\n  /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use\n  ** deflate compression) or NULL (choose automatically).  */\n  if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){\n    iMethod = (int)sqlite3_value_int64(pMethod);\n    if( iMethod!=0 && iMethod!=8 ){\n      zErr = sqlite3_mprintf(\"illegal method value: %d\", iMethod);\n      rc = SQLITE_ERROR;\n      goto zipfile_step_out;\n    }\n  }\n\n  /* Now inspect the data. If this is NULL, then the new entry must be a\n  ** directory.  Otherwise, figure out whether or not the data should\n  ** be deflated or simply stored in the zip archive. */\n  if( sqlite3_value_type(pData)==SQLITE_NULL ){\n    bIsDir = 1;\n    iMethod = 0;\n  }else{\n    aData = sqlite3_value_blob(pData);\n    szUncompressed = nData = sqlite3_value_bytes(pData);\n    iCrc32 = crc32(0, aData, nData);\n    if( iMethod<0 || iMethod==8 ){\n      int nOut = 0;\n      rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);\n      if( rc!=SQLITE_OK ){\n        goto zipfile_step_out;\n      }\n      if( iMethod==8 || nOut<nData ){\n        aData = aFree;\n        nData = nOut;\n        iMethod = 8;\n      }else{\n        iMethod = 0;\n      }\n    }\n  }\n\n  /* Decode the \"mode\" argument. */\n  rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);\n  if( rc ) goto zipfile_step_out;\n\n  /* Decode the \"mtime\" argument. */\n  e.mUnixTime = zipfileGetTime(pMtime);\n\n  /* If this is a directory entry, ensure that there is exactly one '/'\n  ** at the end of the path. Or, if this is not a directory and the path\n  ** ends in '/' it is an error. */\n  if( bIsDir==0 ){\n    if( nName>0 && zName[nName-1]=='/' ){\n      zErr = sqlite3_mprintf(\"non-directory name must not end with /\");\n      rc = SQLITE_ERROR;\n      goto zipfile_step_out;\n    }\n  }else{\n    if( nName==0 || zName[nName-1]!='/' ){\n      zName = zFree = sqlite3_mprintf(\"%s/\", zName);\n      if( zName==0 ){\n        rc = SQLITE_NOMEM;\n        goto zipfile_step_out;\n      }\n      nName = (int)strlen(zName);\n    }else{\n      while( nName>1 && zName[nName-2]=='/' ) nName--;\n    }\n  }\n\n  /* Assemble the ZipfileEntry object for the new zip archive entry */\n  e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;\n  e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;\n  e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;\n  e.cds.iCompression = (u16)iMethod;\n  zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);\n  e.cds.crc32 = iCrc32;\n  e.cds.szCompressed = nData;\n  e.cds.szUncompressed = szUncompressed;\n  e.cds.iExternalAttr = (mode<<16);\n  e.cds.iOffset = p->body.n;\n  e.cds.nFile = (u16)nName;\n  e.cds.zFile = zName;\n\n  /* Append the LFH to the body of the new archive */\n  nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;\n  if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;\n  p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);\n\n  /* Append the data to the body of the new archive */\n  if( nData>0 ){\n    if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;\n    memcpy(&p->body.a[p->body.n], aData, nData);\n    p->body.n += nData;\n  }\n\n  /* Append the CDS record to the directory of the new archive */\n  nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;\n  if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;\n  p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);\n\n  /* Increment the count of entries in the archive */\n  p->nEntry++;\n\n zipfile_step_out:\n  sqlite3_free(aFree);\n  sqlite3_free(zFree);\n  if( rc ){\n    if( zErr ){\n      sqlite3_result_error(pCtx, zErr, -1);\n    }else{\n      sqlite3_result_error_code(pCtx, rc);\n    }\n  }\n  sqlite3_free(zErr);\n}\n\n/*\n** xFinalize() callback for zipfile aggregate function.\n*/\nvoid zipfileFinal(sqlite3_context *pCtx){\n  ZipfileCtx *p;\n  ZipfileEOCD eocd;\n  sqlite3_int64 nZip;\n  u8 *aZip;\n\n  p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));\n  if( p==0 ) return;\n  if( p->nEntry>0 ){\n    memset(&eocd, 0, sizeof(eocd));\n    eocd.nEntry = (u16)p->nEntry;\n    eocd.nEntryTotal = (u16)p->nEntry;\n    eocd.nSize = p->cds.n;\n    eocd.iOffset = p->body.n;\n\n    nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;\n    aZip = (u8*)sqlite3_malloc64(nZip);\n    if( aZip==0 ){\n      sqlite3_result_error_nomem(pCtx);\n    }else{\n      memcpy(aZip, p->body.a, p->body.n);\n      memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);\n      zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);\n      sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);\n    }\n  }\n\n  sqlite3_free(p->body.a);\n  sqlite3_free(p->cds.a);\n}\n\n\n/*\n** Register the \"zipfile\" virtual table.\n*/\nstatic int zipfileRegister(sqlite3 *db){\n  static sqlite3_module zipfileModule = {\n    1,                         /* iVersion */\n    zipfileConnect,            /* xCreate */\n    zipfileConnect,            /* xConnect */\n    zipfileBestIndex,          /* xBestIndex */\n    zipfileDisconnect,         /* xDisconnect */\n    zipfileDisconnect,         /* xDestroy */\n    zipfileOpen,               /* xOpen - open a cursor */\n    zipfileClose,              /* xClose - close a cursor */\n    zipfileFilter,             /* xFilter - configure scan constraints */\n    zipfileNext,               /* xNext - advance a cursor */\n    zipfileEof,                /* xEof - check for end of scan */\n    zipfileColumn,             /* xColumn - read data */\n    0,                         /* xRowid - read data */\n    zipfileUpdate,             /* xUpdate */\n    zipfileBegin,              /* xBegin */\n    0,                         /* xSync */\n    zipfileCommit,             /* xCommit */\n    zipfileRollback,           /* xRollback */\n    zipfileFindFunction,       /* xFindMethod */\n    0,                         /* xRename */\n  };\n\n  int rc = sqlite3_create_module(db, \"zipfile\"  , &zipfileModule, 0);\n  if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, \"zipfile_cds\", -1);\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_function(db, \"zipfile\", -1, SQLITE_UTF8, 0, 0, \n        zipfileStep, zipfileFinal\n    );\n  }\n  return rc;\n}\n#else         /* SQLITE_OMIT_VIRTUALTABLE */\n# define zipfileRegister(x) SQLITE_OK\n#endif\n\n#ifdef _WIN32\n\n#endif\nint sqlite3_zipfile_init(\n  sqlite3 *db, \n  char **pzErrMsg, \n  const sqlite3_api_routines *pApi\n){\n  SQLITE_EXTENSION_INIT2(pApi);\n  (void)pzErrMsg;  /* Unused parameter */\n  return zipfileRegister(db);\n}\n\n/************************* End ../ext/misc/zipfile.c ********************/\n/************************* Begin ../ext/misc/sqlar.c ******************/\n/*\n** 2017-12-17\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** Utility functions sqlar_compress() and sqlar_uncompress(). Useful\n** for working with sqlar archives and used by the shell tool's built-in\n** sqlar support.\n*/\n/* #include \"sqlite3ext.h\" */\nSQLITE_EXTENSION_INIT1\n#include <zlib.h>\n#include <assert.h>\n\n/*\n** Implementation of the \"sqlar_compress(X)\" SQL function.\n**\n** If the type of X is SQLITE_BLOB, and compressing that blob using\n** zlib utility function compress() yields a smaller blob, return the\n** compressed blob. Otherwise, return a copy of X.\n**\n** SQLar uses the \"zlib format\" for compressed content.  The zlib format\n** contains a two-byte identification header and a four-byte checksum at\n** the end.  This is different from ZIP which uses the raw deflate format.\n**\n** Future enhancements to SQLar might add support for new compression formats.\n** If so, those new formats will be identified by alternative headers in the\n** compressed data.\n*/\nstatic void sqlarCompressFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  assert( argc==1 );\n  if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){\n    const Bytef *pData = sqlite3_value_blob(argv[0]);\n    uLong nData = sqlite3_value_bytes(argv[0]);\n    uLongf nOut = compressBound(nData);\n    Bytef *pOut;\n\n    pOut = (Bytef*)sqlite3_malloc(nOut);\n    if( pOut==0 ){\n      sqlite3_result_error_nomem(context);\n      return;\n    }else{\n      if( Z_OK!=compress(pOut, &nOut, pData, nData) ){\n        sqlite3_result_error(context, \"error in compress()\", -1);\n      }else if( nOut<nData ){\n        sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);\n      }else{\n        sqlite3_result_value(context, argv[0]);\n      }\n      sqlite3_free(pOut);\n    }\n  }else{\n    sqlite3_result_value(context, argv[0]);\n  }\n}\n\n/*\n** Implementation of the \"sqlar_uncompress(X,SZ)\" SQL function\n**\n** Parameter SZ is interpreted as an integer. If it is less than or\n** equal to zero, then this function returns a copy of X. Or, if\n** SZ is equal to the size of X when interpreted as a blob, also\n** return a copy of X. Otherwise, decompress blob X using zlib\n** utility function uncompress() and return the results (another\n** blob).\n*/\nstatic void sqlarUncompressFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  uLong nData;\n  uLongf sz;\n\n  assert( argc==2 );\n  sz = sqlite3_value_int(argv[1]);\n\n  if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){\n    sqlite3_result_value(context, argv[0]);\n  }else{\n    const Bytef *pData= sqlite3_value_blob(argv[0]);\n    Bytef *pOut = sqlite3_malloc(sz);\n    if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){\n      sqlite3_result_error(context, \"error in uncompress()\", -1);\n    }else{\n      sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);\n    }\n    sqlite3_free(pOut);\n  }\n}\n\n\n#ifdef _WIN32\n\n#endif\nint sqlite3_sqlar_init(\n  sqlite3 *db, \n  char **pzErrMsg, \n  const sqlite3_api_routines *pApi\n){\n  int rc = SQLITE_OK;\n  SQLITE_EXTENSION_INIT2(pApi);\n  (void)pzErrMsg;  /* Unused parameter */\n  rc = sqlite3_create_function(db, \"sqlar_compress\", 1, \n                               SQLITE_UTF8|SQLITE_INNOCUOUS, 0,\n                               sqlarCompressFunc, 0, 0);\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_function(db, \"sqlar_uncompress\", 2,\n                                 SQLITE_UTF8|SQLITE_INNOCUOUS, 0,\n                                 sqlarUncompressFunc, 0, 0);\n  }\n  return rc;\n}\n\n/************************* End ../ext/misc/sqlar.c ********************/\n#endif\n/************************* Begin ../ext/expert/sqlite3expert.h ******************/\n/*\n** 2017 April 07\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n*/\n#if !defined(SQLITEEXPERT_H)\n#define SQLITEEXPERT_H 1\n/* #include \"sqlite3.h\" */\n\ntypedef struct sqlite3expert sqlite3expert;\n\n/*\n** Create a new sqlite3expert object.\n**\n** If successful, a pointer to the new object is returned and (*pzErr) set\n** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to\n** an English-language error message. In this case it is the responsibility\n** of the caller to eventually free the error message buffer using\n** sqlite3_free().\n*/\nsqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);\n\n/*\n** Configure an sqlite3expert object.\n**\n** EXPERT_CONFIG_SAMPLE:\n**   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for\n**   each candidate index. This involves scanning and sorting the entire\n**   contents of each user database table once for each candidate index\n**   associated with the table. For large databases, this can be \n**   prohibitively slow. This option allows the sqlite3expert object to\n**   be configured so that sqlite_stat1 data is instead generated based on a\n**   subset of each table, or so that no sqlite_stat1 data is used at all.\n**\n**   A single integer argument is passed to this option. If the value is less\n**   than or equal to zero, then no sqlite_stat1 data is generated or used by\n**   the analysis - indexes are recommended based on the database schema only.\n**   Or, if the value is 100 or greater, complete sqlite_stat1 data is\n**   generated for each candidate index (this is the default). Finally, if the\n**   value falls between 0 and 100, then it represents the percentage of user\n**   table rows that should be considered when generating sqlite_stat1 data.\n**\n**   Examples:\n**\n**     // Do not generate any sqlite_stat1 data\n**     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);\n**\n**     // Generate sqlite_stat1 data based on 10% of the rows in each table.\n**     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);\n*/\nint sqlite3_expert_config(sqlite3expert *p, int op, ...);\n\n#define EXPERT_CONFIG_SAMPLE 1    /* int */\n\n/*\n** Specify zero or more SQL statements to be included in the analysis.\n**\n** Buffer zSql must contain zero or more complete SQL statements. This\n** function parses all statements contained in the buffer and adds them\n** to the internal list of statements to analyze. If successful, SQLITE_OK\n** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example\n** due to a error in the SQL - an SQLite error code is returned and (*pzErr)\n** may be set to point to an English language error message. In this case\n** the caller is responsible for eventually freeing the error message buffer\n** using sqlite3_free().\n**\n** If an error does occur while processing one of the statements in the\n** buffer passed as the second argument, none of the statements in the\n** buffer are added to the analysis.\n**\n** This function must be called before sqlite3_expert_analyze(). If a call\n** to this function is made on an sqlite3expert object that has already\n** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned\n** immediately and no statements are added to the analysis.\n*/\nint sqlite3_expert_sql(\n  sqlite3expert *p,               /* From a successful sqlite3_expert_new() */\n  const char *zSql,               /* SQL statement(s) to add */\n  char **pzErr                    /* OUT: Error message (if any) */\n);\n\n\n/*\n** This function is called after the sqlite3expert object has been configured\n** with all SQL statements using sqlite3_expert_sql() to actually perform\n** the analysis. Once this function has been called, it is not possible to\n** add further SQL statements to the analysis.\n**\n** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if\n** an error occurs, an SQLite error code is returned and (*pzErr) set to \n** point to a buffer containing an English language error message. In this\n** case it is the responsibility of the caller to eventually free the buffer\n** using sqlite3_free().\n**\n** If an error does occur within this function, the sqlite3expert object\n** is no longer useful for any purpose. At that point it is no longer\n** possible to add further SQL statements to the object or to re-attempt\n** the analysis. The sqlite3expert object must still be freed using a call\n** sqlite3_expert_destroy().\n*/\nint sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);\n\n/*\n** Return the total number of statements loaded using sqlite3_expert_sql().\n** The total number of SQL statements may be different from the total number\n** to calls to sqlite3_expert_sql().\n*/\nint sqlite3_expert_count(sqlite3expert*);\n\n/*\n** Return a component of the report.\n**\n** This function is called after sqlite3_expert_analyze() to extract the\n** results of the analysis. Each call to this function returns either a\n** NULL pointer or a pointer to a buffer containing a nul-terminated string.\n** The value passed as the third argument must be one of the EXPERT_REPORT_*\n** #define constants defined below.\n**\n** For some EXPERT_REPORT_* parameters, the buffer returned contains \n** information relating to a specific SQL statement. In these cases that\n** SQL statement is identified by the value passed as the second argument.\n** SQL statements are numbered from 0 in the order in which they are parsed.\n** If an out-of-range value (less than zero or equal to or greater than the\n** value returned by sqlite3_expert_count()) is passed as the second argument\n** along with such an EXPERT_REPORT_* parameter, NULL is always returned.\n**\n** EXPERT_REPORT_SQL:\n**   Return the text of SQL statement iStmt.\n**\n** EXPERT_REPORT_INDEXES:\n**   Return a buffer containing the CREATE INDEX statements for all recommended\n**   indexes for statement iStmt. If there are no new recommeded indexes, NULL \n**   is returned.\n**\n** EXPERT_REPORT_PLAN:\n**   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query\n**   iStmt after the proposed indexes have been added to the database schema.\n**\n** EXPERT_REPORT_CANDIDATES:\n**   Return a pointer to a buffer containing the CREATE INDEX statements \n**   for all indexes that were tested (for all SQL statements). The iStmt\n**   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.\n*/\nconst char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);\n\n/*\n** Values for the third argument passed to sqlite3_expert_report().\n*/\n#define EXPERT_REPORT_SQL        1\n#define EXPERT_REPORT_INDEXES    2\n#define EXPERT_REPORT_PLAN       3\n#define EXPERT_REPORT_CANDIDATES 4\n\n/*\n** Free an (sqlite3expert*) handle and all associated resources. There \n** should be one call to this function for each successful call to \n** sqlite3-expert_new().\n*/\nvoid sqlite3_expert_destroy(sqlite3expert*);\n\n#endif  /* !defined(SQLITEEXPERT_H) */\n\n/************************* End ../ext/expert/sqlite3expert.h ********************/\n/************************* Begin ../ext/expert/sqlite3expert.c ******************/\n/*\n** 2017 April 09\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n*/\n/* #include \"sqlite3expert.h\" */\n#include <assert.h>\n#include <string.h>\n#include <stdio.h>\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE \n\n/* typedef sqlite3_int64 i64; */\n/* typedef sqlite3_uint64 u64; */\n\ntypedef struct IdxColumn IdxColumn;\ntypedef struct IdxConstraint IdxConstraint;\ntypedef struct IdxScan IdxScan;\ntypedef struct IdxStatement IdxStatement;\ntypedef struct IdxTable IdxTable;\ntypedef struct IdxWrite IdxWrite;\n\n#define STRLEN  (int)strlen\n\n/*\n** A temp table name that we assume no user database will actually use.\n** If this assumption proves incorrect triggers on the table with the\n** conflicting name will be ignored.\n*/\n#define UNIQUE_TABLE_NAME \"t592690916721053953805701627921227776\"\n\n/*\n** A single constraint. Equivalent to either \"col = ?\" or \"col < ?\" (or\n** any other type of single-ended range constraint on a column).\n**\n** pLink:\n**   Used to temporarily link IdxConstraint objects into lists while\n**   creating candidate indexes.\n*/\nstruct IdxConstraint {\n  char *zColl;                    /* Collation sequence */\n  int bRange;                     /* True for range, false for eq */\n  int iCol;                       /* Constrained table column */\n  int bFlag;                      /* Used by idxFindCompatible() */\n  int bDesc;                      /* True if ORDER BY <expr> DESC */\n  IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */\n  IdxConstraint *pLink;           /* See above */\n};\n\n/*\n** A single scan of a single table.\n*/\nstruct IdxScan {\n  IdxTable *pTab;                 /* Associated table object */\n  int iDb;                        /* Database containing table zTable */\n  i64 covering;                   /* Mask of columns required for cov. index */\n  IdxConstraint *pOrder;          /* ORDER BY columns */\n  IdxConstraint *pEq;             /* List of == constraints */\n  IdxConstraint *pRange;          /* List of < constraints */\n  IdxScan *pNextScan;             /* Next IdxScan object for same analysis */\n};\n\n/*\n** Information regarding a single database table. Extracted from \n** \"PRAGMA table_info\" by function idxGetTableInfo().\n*/\nstruct IdxColumn {\n  char *zName;\n  char *zColl;\n  int iPk;\n};\nstruct IdxTable {\n  int nCol;\n  char *zName;                    /* Table name */\n  IdxColumn *aCol;\n  IdxTable *pNext;                /* Next table in linked list of all tables */\n};\n\n/*\n** An object of the following type is created for each unique table/write-op\n** seen. The objects are stored in a singly-linked list beginning at\n** sqlite3expert.pWrite.\n*/\nstruct IdxWrite {\n  IdxTable *pTab;\n  int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */\n  IdxWrite *pNext;\n};\n\n/*\n** Each statement being analyzed is represented by an instance of this\n** structure.\n*/\nstruct IdxStatement {\n  int iId;                        /* Statement number */\n  char *zSql;                     /* SQL statement */\n  char *zIdx;                     /* Indexes */\n  char *zEQP;                     /* Plan */\n  IdxStatement *pNext;\n};\n\n\n/*\n** A hash table for storing strings. With space for a payload string\n** with each entry. Methods are:\n**\n**   idxHashInit()\n**   idxHashClear()\n**   idxHashAdd()\n**   idxHashSearch()\n*/\n#define IDX_HASH_SIZE 1023\ntypedef struct IdxHashEntry IdxHashEntry;\ntypedef struct IdxHash IdxHash;\nstruct IdxHashEntry {\n  char *zKey;                     /* nul-terminated key */\n  char *zVal;                     /* nul-terminated value string */\n  char *zVal2;                    /* nul-terminated value string 2 */\n  IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */\n  IdxHashEntry *pNext;            /* Next entry in hash */\n};\nstruct IdxHash {\n  IdxHashEntry *pFirst;\n  IdxHashEntry *aHash[IDX_HASH_SIZE];\n};\n\n/*\n** sqlite3expert object.\n*/\nstruct sqlite3expert {\n  int iSample;                    /* Percentage of tables to sample for stat1 */\n  sqlite3 *db;                    /* User database */\n  sqlite3 *dbm;                   /* In-memory db for this analysis */\n  sqlite3 *dbv;                   /* Vtab schema for this analysis */\n  IdxTable *pTable;               /* List of all IdxTable objects */\n  IdxScan *pScan;                 /* List of scan objects */\n  IdxWrite *pWrite;               /* List of write objects */\n  IdxStatement *pStatement;       /* List of IdxStatement objects */\n  int bRun;                       /* True once analysis has run */\n  char **pzErrmsg;\n  int rc;                         /* Error code from whereinfo hook */\n  IdxHash hIdx;                   /* Hash containing all candidate indexes */\n  char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */\n};\n\n\n/*\n** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc(). \n** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.\n*/\nstatic void *idxMalloc(int *pRc, int nByte){\n  void *pRet;\n  assert( *pRc==SQLITE_OK );\n  assert( nByte>0 );\n  pRet = sqlite3_malloc(nByte);\n  if( pRet ){\n    memset(pRet, 0, nByte);\n  }else{\n    *pRc = SQLITE_NOMEM;\n  }\n  return pRet;\n}\n\n/*\n** Initialize an IdxHash hash table.\n*/\nstatic void idxHashInit(IdxHash *pHash){\n  memset(pHash, 0, sizeof(IdxHash));\n}\n\n/*\n** Reset an IdxHash hash table.\n*/\nstatic void idxHashClear(IdxHash *pHash){\n  int i;\n  for(i=0; i<IDX_HASH_SIZE; i++){\n    IdxHashEntry *pEntry;\n    IdxHashEntry *pNext;\n    for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){\n      pNext = pEntry->pHashNext;\n      sqlite3_free(pEntry->zVal2);\n      sqlite3_free(pEntry);\n    }\n  }\n  memset(pHash, 0, sizeof(IdxHash));\n}\n\n/*\n** Return the index of the hash bucket that the string specified by the\n** arguments to this function belongs.\n*/\nstatic int idxHashString(const char *z, int n){\n  unsigned int ret = 0;\n  int i;\n  for(i=0; i<n; i++){\n    ret += (ret<<3) + (unsigned char)(z[i]);\n  }\n  return (int)(ret % IDX_HASH_SIZE);\n}\n\n/*\n** If zKey is already present in the hash table, return non-zero and do\n** nothing. Otherwise, add an entry with key zKey and payload string zVal to\n** the hash table passed as the second argument. \n*/\nstatic int idxHashAdd(\n  int *pRc, \n  IdxHash *pHash, \n  const char *zKey,\n  const char *zVal\n){\n  int nKey = STRLEN(zKey);\n  int iHash = idxHashString(zKey, nKey);\n  int nVal = (zVal ? STRLEN(zVal) : 0);\n  IdxHashEntry *pEntry;\n  assert( iHash>=0 );\n  for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){\n    if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){\n      return 1;\n    }\n  }\n  pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);\n  if( pEntry ){\n    pEntry->zKey = (char*)&pEntry[1];\n    memcpy(pEntry->zKey, zKey, nKey);\n    if( zVal ){\n      pEntry->zVal = &pEntry->zKey[nKey+1];\n      memcpy(pEntry->zVal, zVal, nVal);\n    }\n    pEntry->pHashNext = pHash->aHash[iHash];\n    pHash->aHash[iHash] = pEntry;\n\n    pEntry->pNext = pHash->pFirst;\n    pHash->pFirst = pEntry;\n  }\n  return 0;\n}\n\n/*\n** If zKey/nKey is present in the hash table, return a pointer to the \n** hash-entry object.\n*/\nstatic IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){\n  int iHash;\n  IdxHashEntry *pEntry;\n  if( nKey<0 ) nKey = STRLEN(zKey);\n  iHash = idxHashString(zKey, nKey);\n  assert( iHash>=0 );\n  for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){\n    if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){\n      return pEntry;\n    }\n  }\n  return 0;\n}\n\n/*\n** If the hash table contains an entry with a key equal to the string\n** passed as the final two arguments to this function, return a pointer\n** to the payload string. Otherwise, if zKey/nKey is not present in the\n** hash table, return NULL.\n*/\nstatic const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){\n  IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);\n  if( pEntry ) return pEntry->zVal;\n  return 0;\n}\n\n/*\n** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl\n** variable to point to a copy of nul-terminated string zColl.\n*/\nstatic IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){\n  IdxConstraint *pNew;\n  int nColl = STRLEN(zColl);\n\n  assert( *pRc==SQLITE_OK );\n  pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);\n  if( pNew ){\n    pNew->zColl = (char*)&pNew[1];\n    memcpy(pNew->zColl, zColl, nColl+1);\n  }\n  return pNew;\n}\n\n/*\n** An error associated with database handle db has just occurred. Pass\n** the error message to callback function xOut.\n*/\nstatic void idxDatabaseError(\n  sqlite3 *db,                    /* Database handle */\n  char **pzErrmsg                 /* Write error here */\n){\n  *pzErrmsg = sqlite3_mprintf(\"%s\", sqlite3_errmsg(db));\n}\n\n/*\n** Prepare an SQL statement.\n*/\nstatic int idxPrepareStmt(\n  sqlite3 *db,                    /* Database handle to compile against */\n  sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */\n  char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */\n  const char *zSql                /* SQL statement to compile */\n){\n  int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);\n  if( rc!=SQLITE_OK ){\n    *ppStmt = 0;\n    idxDatabaseError(db, pzErrmsg);\n  }\n  return rc;\n}\n\n/*\n** Prepare an SQL statement using the results of a printf() formatting.\n*/\nstatic int idxPrintfPrepareStmt(\n  sqlite3 *db,                    /* Database handle to compile against */\n  sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */\n  char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */\n  const char *zFmt,               /* printf() format of SQL statement */\n  ...                             /* Trailing printf() arguments */\n){\n  va_list ap;\n  int rc;\n  char *zSql;\n  va_start(ap, zFmt);\n  zSql = sqlite3_vmprintf(zFmt, ap);\n  if( zSql==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);\n    sqlite3_free(zSql);\n  }\n  va_end(ap);\n  return rc;\n}\n\n\n/*************************************************************************\n** Beginning of virtual table implementation.\n*/\ntypedef struct ExpertVtab ExpertVtab;\nstruct ExpertVtab {\n  sqlite3_vtab base;\n  IdxTable *pTab;\n  sqlite3expert *pExpert;\n};\n\ntypedef struct ExpertCsr ExpertCsr;\nstruct ExpertCsr {\n  sqlite3_vtab_cursor base;\n  sqlite3_stmt *pData;\n};\n\nstatic char *expertDequote(const char *zIn){\n  int n = STRLEN(zIn);\n  char *zRet = sqlite3_malloc(n);\n\n  assert( zIn[0]=='\\'' );\n  assert( zIn[n-1]=='\\'' );\n\n  if( zRet ){\n    int iOut = 0;\n    int iIn = 0;\n    for(iIn=1; iIn<(n-1); iIn++){\n      if( zIn[iIn]=='\\'' ){\n        assert( zIn[iIn+1]=='\\'' );\n        iIn++;\n      }\n      zRet[iOut++] = zIn[iIn];\n    }\n    zRet[iOut] = '\\0';\n  }\n\n  return zRet;\n}\n\n/* \n** This function is the implementation of both the xConnect and xCreate\n** methods of the r-tree virtual table.\n**\n**   argv[0]   -> module name\n**   argv[1]   -> database name\n**   argv[2]   -> table name\n**   argv[...] -> column names...\n*/\nstatic int expertConnect(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  sqlite3expert *pExpert = (sqlite3expert*)pAux;\n  ExpertVtab *p = 0;\n  int rc;\n\n  if( argc!=4 ){\n    *pzErr = sqlite3_mprintf(\"internal error!\");\n    rc = SQLITE_ERROR;\n  }else{\n    char *zCreateTable = expertDequote(argv[3]);\n    if( zCreateTable ){\n      rc = sqlite3_declare_vtab(db, zCreateTable);\n      if( rc==SQLITE_OK ){\n        p = idxMalloc(&rc, sizeof(ExpertVtab));\n      }\n      if( rc==SQLITE_OK ){\n        p->pExpert = pExpert;\n        p->pTab = pExpert->pTable;\n        assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );\n      }\n      sqlite3_free(zCreateTable);\n    }else{\n      rc = SQLITE_NOMEM;\n    }\n  }\n\n  *ppVtab = (sqlite3_vtab*)p;\n  return rc;\n}\n\nstatic int expertDisconnect(sqlite3_vtab *pVtab){\n  ExpertVtab *p = (ExpertVtab*)pVtab;\n  sqlite3_free(p);\n  return SQLITE_OK;\n}\n\nstatic int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){\n  ExpertVtab *p = (ExpertVtab*)pVtab;\n  int rc = SQLITE_OK;\n  int n = 0;\n  IdxScan *pScan;\n  const int opmask = \n    SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |\n    SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |\n    SQLITE_INDEX_CONSTRAINT_LE;\n\n  pScan = idxMalloc(&rc, sizeof(IdxScan));\n  if( pScan ){\n    int i;\n\n    /* Link the new scan object into the list */\n    pScan->pTab = p->pTab;\n    pScan->pNextScan = p->pExpert->pScan;\n    p->pExpert->pScan = pScan;\n\n    /* Add the constraints to the IdxScan object */\n    for(i=0; i<pIdxInfo->nConstraint; i++){\n      struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];\n      if( pCons->usable \n       && pCons->iColumn>=0 \n       && p->pTab->aCol[pCons->iColumn].iPk==0\n       && (pCons->op & opmask) \n      ){\n        IdxConstraint *pNew;\n        const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);\n        pNew = idxNewConstraint(&rc, zColl);\n        if( pNew ){\n          pNew->iCol = pCons->iColumn;\n          if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){\n            pNew->pNext = pScan->pEq;\n            pScan->pEq = pNew;\n          }else{\n            pNew->bRange = 1;\n            pNew->pNext = pScan->pRange;\n            pScan->pRange = pNew;\n          }\n        }\n        n++;\n        pIdxInfo->aConstraintUsage[i].argvIndex = n;\n      }\n    }\n\n    /* Add the ORDER BY to the IdxScan object */\n    for(i=pIdxInfo->nOrderBy-1; i>=0; i--){\n      int iCol = pIdxInfo->aOrderBy[i].iColumn;\n      if( iCol>=0 ){\n        IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);\n        if( pNew ){\n          pNew->iCol = iCol;\n          pNew->bDesc = pIdxInfo->aOrderBy[i].desc;\n          pNew->pNext = pScan->pOrder;\n          pNew->pLink = pScan->pOrder;\n          pScan->pOrder = pNew;\n          n++;\n        }\n      }\n    }\n  }\n\n  pIdxInfo->estimatedCost = 1000000.0 / (n+1);\n  return rc;\n}\n\nstatic int expertUpdate(\n  sqlite3_vtab *pVtab, \n  int nData, \n  sqlite3_value **azData, \n  sqlite_int64 *pRowid\n){\n  (void)pVtab;\n  (void)nData;\n  (void)azData;\n  (void)pRowid;\n  return SQLITE_OK;\n}\n\n/* \n** Virtual table module xOpen method.\n*/\nstatic int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){\n  int rc = SQLITE_OK;\n  ExpertCsr *pCsr;\n  (void)pVTab;\n  pCsr = idxMalloc(&rc, sizeof(ExpertCsr));\n  *ppCursor = (sqlite3_vtab_cursor*)pCsr;\n  return rc;\n}\n\n/* \n** Virtual table module xClose method.\n*/\nstatic int expertClose(sqlite3_vtab_cursor *cur){\n  ExpertCsr *pCsr = (ExpertCsr*)cur;\n  sqlite3_finalize(pCsr->pData);\n  sqlite3_free(pCsr);\n  return SQLITE_OK;\n}\n\n/*\n** Virtual table module xEof method.\n**\n** Return non-zero if the cursor does not currently point to a valid \n** record (i.e if the scan has finished), or zero otherwise.\n*/\nstatic int expertEof(sqlite3_vtab_cursor *cur){\n  ExpertCsr *pCsr = (ExpertCsr*)cur;\n  return pCsr->pData==0;\n}\n\n/* \n** Virtual table module xNext method.\n*/\nstatic int expertNext(sqlite3_vtab_cursor *cur){\n  ExpertCsr *pCsr = (ExpertCsr*)cur;\n  int rc = SQLITE_OK;\n\n  assert( pCsr->pData );\n  rc = sqlite3_step(pCsr->pData);\n  if( rc!=SQLITE_ROW ){\n    rc = sqlite3_finalize(pCsr->pData);\n    pCsr->pData = 0;\n  }else{\n    rc = SQLITE_OK;\n  }\n\n  return rc;\n}\n\n/* \n** Virtual table module xRowid method.\n*/\nstatic int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){\n  (void)cur;\n  *pRowid = 0;\n  return SQLITE_OK;\n}\n\n/* \n** Virtual table module xColumn method.\n*/\nstatic int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){\n  ExpertCsr *pCsr = (ExpertCsr*)cur;\n  sqlite3_value *pVal;\n  pVal = sqlite3_column_value(pCsr->pData, i);\n  if( pVal ){\n    sqlite3_result_value(ctx, pVal);\n  }\n  return SQLITE_OK;\n}\n\n/* \n** Virtual table module xFilter method.\n*/\nstatic int expertFilter(\n  sqlite3_vtab_cursor *cur, \n  int idxNum, const char *idxStr,\n  int argc, sqlite3_value **argv\n){\n  ExpertCsr *pCsr = (ExpertCsr*)cur;\n  ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);\n  sqlite3expert *pExpert = pVtab->pExpert;\n  int rc;\n\n  (void)idxNum;\n  (void)idxStr;\n  (void)argc;\n  (void)argv;\n  rc = sqlite3_finalize(pCsr->pData);\n  pCsr->pData = 0;\n  if( rc==SQLITE_OK ){\n    rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,\n        \"SELECT * FROM main.%Q WHERE sample()\", pVtab->pTab->zName\n    );\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = expertNext(cur);\n  }\n  return rc;\n}\n\nstatic int idxRegisterVtab(sqlite3expert *p){\n  static sqlite3_module expertModule = {\n    2,                            /* iVersion */\n    expertConnect,                /* xCreate - create a table */\n    expertConnect,                /* xConnect - connect to an existing table */\n    expertBestIndex,              /* xBestIndex - Determine search strategy */\n    expertDisconnect,             /* xDisconnect - Disconnect from a table */\n    expertDisconnect,             /* xDestroy - Drop a table */\n    expertOpen,                   /* xOpen - open a cursor */\n    expertClose,                  /* xClose - close a cursor */\n    expertFilter,                 /* xFilter - configure scan constraints */\n    expertNext,                   /* xNext - advance a cursor */\n    expertEof,                    /* xEof */\n    expertColumn,                 /* xColumn - read data */\n    expertRowid,                  /* xRowid - read data */\n    expertUpdate,                 /* xUpdate - write data */\n    0,                            /* xBegin - begin transaction */\n    0,                            /* xSync - sync transaction */\n    0,                            /* xCommit - commit transaction */\n    0,                            /* xRollback - rollback transaction */\n    0,                            /* xFindFunction - function overloading */\n    0,                            /* xRename - rename the table */\n    0,                            /* xSavepoint */\n    0,                            /* xRelease */\n    0,                            /* xRollbackTo */\n    0,                            /* xShadowName */\n  };\n\n  return sqlite3_create_module(p->dbv, \"expert\", &expertModule, (void*)p);\n}\n/*\n** End of virtual table implementation.\n*************************************************************************/\n/*\n** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function\n** is called, set it to the return value of sqlite3_finalize() before\n** returning. Otherwise, discard the sqlite3_finalize() return value.\n*/\nstatic void idxFinalize(int *pRc, sqlite3_stmt *pStmt){\n  int rc = sqlite3_finalize(pStmt);\n  if( *pRc==SQLITE_OK ) *pRc = rc;\n}\n\n/*\n** Attempt to allocate an IdxTable structure corresponding to table zTab\n** in the main database of connection db. If successful, set (*ppOut) to\n** point to the new object and return SQLITE_OK. Otherwise, return an\n** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be\n** set to point to an error string.\n**\n** It is the responsibility of the caller to eventually free either the\n** IdxTable object or error message using sqlite3_free().\n*/\nstatic int idxGetTableInfo(\n  sqlite3 *db,                    /* Database connection to read details from */\n  const char *zTab,               /* Table name */\n  IdxTable **ppOut,               /* OUT: New object (if successful) */\n  char **pzErrmsg                 /* OUT: Error message (if not) */\n){\n  sqlite3_stmt *p1 = 0;\n  int nCol = 0;\n  int nTab = STRLEN(zTab);\n  int nByte = sizeof(IdxTable) + nTab + 1;\n  IdxTable *pNew = 0;\n  int rc, rc2;\n  char *pCsr = 0;\n\n  rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, \"PRAGMA table_info=%Q\", zTab);\n  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){\n    const char *zCol = (const char*)sqlite3_column_text(p1, 1);\n    nByte += 1 + STRLEN(zCol);\n    rc = sqlite3_table_column_metadata(\n        db, \"main\", zTab, zCol, 0, &zCol, 0, 0, 0\n    );\n    nByte += 1 + STRLEN(zCol);\n    nCol++;\n  }\n  rc2 = sqlite3_reset(p1);\n  if( rc==SQLITE_OK ) rc = rc2;\n\n  nByte += sizeof(IdxColumn) * nCol;\n  if( rc==SQLITE_OK ){\n    pNew = idxMalloc(&rc, nByte);\n  }\n  if( rc==SQLITE_OK ){\n    pNew->aCol = (IdxColumn*)&pNew[1];\n    pNew->nCol = nCol;\n    pCsr = (char*)&pNew->aCol[nCol];\n  }\n\n  nCol = 0;\n  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){\n    const char *zCol = (const char*)sqlite3_column_text(p1, 1);\n    int nCopy = STRLEN(zCol) + 1;\n    pNew->aCol[nCol].zName = pCsr;\n    pNew->aCol[nCol].iPk = sqlite3_column_int(p1, 5);\n    memcpy(pCsr, zCol, nCopy);\n    pCsr += nCopy;\n\n    rc = sqlite3_table_column_metadata(\n        db, \"main\", zTab, zCol, 0, &zCol, 0, 0, 0\n    );\n    if( rc==SQLITE_OK ){\n      nCopy = STRLEN(zCol) + 1;\n      pNew->aCol[nCol].zColl = pCsr;\n      memcpy(pCsr, zCol, nCopy);\n      pCsr += nCopy;\n    }\n\n    nCol++;\n  }\n  idxFinalize(&rc, p1);\n\n  if( rc!=SQLITE_OK ){\n    sqlite3_free(pNew);\n    pNew = 0;\n  }else{\n    pNew->zName = pCsr;\n    memcpy(pNew->zName, zTab, nTab+1);\n  }\n\n  *ppOut = pNew;\n  return rc;\n}\n\n/*\n** This function is a no-op if *pRc is set to anything other than \n** SQLITE_OK when it is called.\n**\n** If *pRc is initially set to SQLITE_OK, then the text specified by\n** the printf() style arguments is appended to zIn and the result returned\n** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on\n** zIn before returning.\n*/\nstatic char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){\n  va_list ap;\n  char *zAppend = 0;\n  char *zRet = 0;\n  int nIn = zIn ? STRLEN(zIn) : 0;\n  int nAppend = 0;\n  va_start(ap, zFmt);\n  if( *pRc==SQLITE_OK ){\n    zAppend = sqlite3_vmprintf(zFmt, ap);\n    if( zAppend ){\n      nAppend = STRLEN(zAppend);\n      zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);\n    }\n    if( zAppend && zRet ){\n      if( nIn ) memcpy(zRet, zIn, nIn);\n      memcpy(&zRet[nIn], zAppend, nAppend+1);\n    }else{\n      sqlite3_free(zRet);\n      zRet = 0;\n      *pRc = SQLITE_NOMEM;\n    }\n    sqlite3_free(zAppend);\n    sqlite3_free(zIn);\n  }\n  va_end(ap);\n  return zRet;\n}\n\n/*\n** Return true if zId must be quoted in order to use it as an SQL\n** identifier, or false otherwise.\n*/\nstatic int idxIdentifierRequiresQuotes(const char *zId){\n  int i;\n  for(i=0; zId[i]; i++){\n    if( !(zId[i]=='_')\n     && !(zId[i]>='0' && zId[i]<='9')\n     && !(zId[i]>='a' && zId[i]<='z')\n     && !(zId[i]>='A' && zId[i]<='Z')\n    ){\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/*\n** This function appends an index column definition suitable for constraint\n** pCons to the string passed as zIn and returns the result.\n*/\nstatic char *idxAppendColDefn(\n  int *pRc,                       /* IN/OUT: Error code */\n  char *zIn,                      /* Column defn accumulated so far */\n  IdxTable *pTab,                 /* Table index will be created on */\n  IdxConstraint *pCons\n){\n  char *zRet = zIn;\n  IdxColumn *p = &pTab->aCol[pCons->iCol];\n  if( zRet ) zRet = idxAppendText(pRc, zRet, \", \");\n\n  if( idxIdentifierRequiresQuotes(p->zName) ){\n    zRet = idxAppendText(pRc, zRet, \"%Q\", p->zName);\n  }else{\n    zRet = idxAppendText(pRc, zRet, \"%s\", p->zName);\n  }\n\n  if( sqlite3_stricmp(p->zColl, pCons->zColl) ){\n    if( idxIdentifierRequiresQuotes(pCons->zColl) ){\n      zRet = idxAppendText(pRc, zRet, \" COLLATE %Q\", pCons->zColl);\n    }else{\n      zRet = idxAppendText(pRc, zRet, \" COLLATE %s\", pCons->zColl);\n    }\n  }\n\n  if( pCons->bDesc ){\n    zRet = idxAppendText(pRc, zRet, \" DESC\");\n  }\n  return zRet;\n}\n\n/*\n** Search database dbm for an index compatible with the one idxCreateFromCons()\n** would create from arguments pScan, pEq and pTail. If no error occurs and \n** such an index is found, return non-zero. Or, if no such index is found,\n** return zero.\n**\n** If an error occurs, set *pRc to an SQLite error code and return zero.\n*/\nstatic int idxFindCompatible(\n  int *pRc,                       /* OUT: Error code */\n  sqlite3* dbm,                   /* Database to search */\n  IdxScan *pScan,                 /* Scan for table to search for index on */\n  IdxConstraint *pEq,             /* List of == constraints */\n  IdxConstraint *pTail            /* List of range constraints */\n){\n  const char *zTbl = pScan->pTab->zName;\n  sqlite3_stmt *pIdxList = 0;\n  IdxConstraint *pIter;\n  int nEq = 0;                    /* Number of elements in pEq */\n  int rc;\n\n  /* Count the elements in list pEq */\n  for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;\n\n  rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, \"PRAGMA index_list=%Q\", zTbl);\n  while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){\n    int bMatch = 1;\n    IdxConstraint *pT = pTail;\n    sqlite3_stmt *pInfo = 0;\n    const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);\n\n    /* Zero the IdxConstraint.bFlag values in the pEq list */\n    for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;\n\n    rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, \"PRAGMA index_xInfo=%Q\", zIdx);\n    while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){\n      int iIdx = sqlite3_column_int(pInfo, 0);\n      int iCol = sqlite3_column_int(pInfo, 1);\n      const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);\n\n      if( iIdx<nEq ){\n        for(pIter=pEq; pIter; pIter=pIter->pLink){\n          if( pIter->bFlag ) continue;\n          if( pIter->iCol!=iCol ) continue;\n          if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;\n          pIter->bFlag = 1;\n          break;\n        }\n        if( pIter==0 ){\n          bMatch = 0;\n          break;\n        }\n      }else{\n        if( pT ){\n          if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){\n            bMatch = 0;\n            break;\n          }\n          pT = pT->pLink;\n        }\n      }\n    }\n    idxFinalize(&rc, pInfo);\n\n    if( rc==SQLITE_OK && bMatch ){\n      sqlite3_finalize(pIdxList);\n      return 1;\n    }\n  }\n  idxFinalize(&rc, pIdxList);\n\n  *pRc = rc;\n  return 0;\n}\n\nstatic int idxCreateFromCons(\n  sqlite3expert *p,\n  IdxScan *pScan,\n  IdxConstraint *pEq, \n  IdxConstraint *pTail\n){\n  sqlite3 *dbm = p->dbm;\n  int rc = SQLITE_OK;\n  if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){\n    IdxTable *pTab = pScan->pTab;\n    char *zCols = 0;\n    char *zIdx = 0;\n    IdxConstraint *pCons;\n    unsigned int h = 0;\n    const char *zFmt;\n\n    for(pCons=pEq; pCons; pCons=pCons->pLink){\n      zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);\n    }\n    for(pCons=pTail; pCons; pCons=pCons->pLink){\n      zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);\n    }\n\n    if( rc==SQLITE_OK ){\n      /* Hash the list of columns to come up with a name for the index */\n      const char *zTable = pScan->pTab->zName;\n      char *zName;                /* Index name */\n      int i;\n      for(i=0; zCols[i]; i++){\n        h += ((h<<3) + zCols[i]);\n      }\n      zName = sqlite3_mprintf(\"%s_idx_%08x\", zTable, h);\n      if( zName==0 ){ \n        rc = SQLITE_NOMEM;\n      }else{\n        if( idxIdentifierRequiresQuotes(zTable) ){\n          zFmt = \"CREATE INDEX '%q' ON %Q(%s)\";\n        }else{\n          zFmt = \"CREATE INDEX %s ON %s(%s)\";\n        }\n        zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);\n        if( !zIdx ){\n          rc = SQLITE_NOMEM;\n        }else{\n          rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);\n          idxHashAdd(&rc, &p->hIdx, zName, zIdx);\n        }\n        sqlite3_free(zName);\n        sqlite3_free(zIdx);\n      }\n    }\n\n    sqlite3_free(zCols);\n  }\n  return rc;\n}\n\n/*\n** Return true if list pList (linked by IdxConstraint.pLink) contains\n** a constraint compatible with *p. Otherwise return false.\n*/\nstatic int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){\n  IdxConstraint *pCmp;\n  for(pCmp=pList; pCmp; pCmp=pCmp->pLink){\n    if( p->iCol==pCmp->iCol ) return 1;\n  }\n  return 0;\n}\n\nstatic int idxCreateFromWhere(\n  sqlite3expert *p, \n  IdxScan *pScan,                 /* Create indexes for this scan */\n  IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */\n){\n  IdxConstraint *p1 = 0;\n  IdxConstraint *pCon;\n  int rc;\n\n  /* Gather up all the == constraints. */\n  for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){\n    if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){\n      pCon->pLink = p1;\n      p1 = pCon;\n    }\n  }\n\n  /* Create an index using the == constraints collected above. And the\n  ** range constraint/ORDER BY terms passed in by the caller, if any. */\n  rc = idxCreateFromCons(p, pScan, p1, pTail);\n\n  /* If no range/ORDER BY passed by the caller, create a version of the\n  ** index for each range constraint.  */\n  if( pTail==0 ){\n    for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){\n      assert( pCon->pLink==0 );\n      if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){\n        rc = idxCreateFromCons(p, pScan, p1, pCon);\n      }\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Create candidate indexes in database [dbm] based on the data in \n** linked-list pScan.\n*/\nstatic int idxCreateCandidates(sqlite3expert *p){\n  int rc = SQLITE_OK;\n  IdxScan *pIter;\n\n  for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){\n    rc = idxCreateFromWhere(p, pIter, 0);\n    if( rc==SQLITE_OK && pIter->pOrder ){\n      rc = idxCreateFromWhere(p, pIter, pIter->pOrder);\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Free all elements of the linked list starting at pConstraint.\n*/\nstatic void idxConstraintFree(IdxConstraint *pConstraint){\n  IdxConstraint *pNext;\n  IdxConstraint *p;\n\n  for(p=pConstraint; p; p=pNext){\n    pNext = p->pNext;\n    sqlite3_free(p);\n  }\n}\n\n/*\n** Free all elements of the linked list starting from pScan up until pLast\n** (pLast is not freed).\n*/\nstatic void idxScanFree(IdxScan *pScan, IdxScan *pLast){\n  IdxScan *p;\n  IdxScan *pNext;\n  for(p=pScan; p!=pLast; p=pNext){\n    pNext = p->pNextScan;\n    idxConstraintFree(p->pOrder);\n    idxConstraintFree(p->pEq);\n    idxConstraintFree(p->pRange);\n    sqlite3_free(p);\n  }\n}\n\n/*\n** Free all elements of the linked list starting from pStatement up \n** until pLast (pLast is not freed).\n*/\nstatic void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){\n  IdxStatement *p;\n  IdxStatement *pNext;\n  for(p=pStatement; p!=pLast; p=pNext){\n    pNext = p->pNext;\n    sqlite3_free(p->zEQP);\n    sqlite3_free(p->zIdx);\n    sqlite3_free(p);\n  }\n}\n\n/*\n** Free the linked list of IdxTable objects starting at pTab.\n*/\nstatic void idxTableFree(IdxTable *pTab){\n  IdxTable *pIter;\n  IdxTable *pNext;\n  for(pIter=pTab; pIter; pIter=pNext){\n    pNext = pIter->pNext;\n    sqlite3_free(pIter);\n  }\n}\n\n/*\n** Free the linked list of IdxWrite objects starting at pTab.\n*/\nstatic void idxWriteFree(IdxWrite *pTab){\n  IdxWrite *pIter;\n  IdxWrite *pNext;\n  for(pIter=pTab; pIter; pIter=pNext){\n    pNext = pIter->pNext;\n    sqlite3_free(pIter);\n  }\n}\n\n\n\n/*\n** This function is called after candidate indexes have been created. It\n** runs all the queries to see which indexes they prefer, and populates\n** IdxStatement.zIdx and IdxStatement.zEQP with the results.\n*/\nint idxFindIndexes(\n  sqlite3expert *p,\n  char **pzErr                         /* OUT: Error message (sqlite3_malloc) */\n){\n  IdxStatement *pStmt;\n  sqlite3 *dbm = p->dbm;\n  int rc = SQLITE_OK;\n\n  IdxHash hIdx;\n  idxHashInit(&hIdx);\n\n  for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){\n    IdxHashEntry *pEntry;\n    sqlite3_stmt *pExplain = 0;\n    idxHashClear(&hIdx);\n    rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,\n        \"EXPLAIN QUERY PLAN %s\", pStmt->zSql\n    );\n    while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){\n      /* int iId = sqlite3_column_int(pExplain, 0); */\n      /* int iParent = sqlite3_column_int(pExplain, 1); */\n      /* int iNotUsed = sqlite3_column_int(pExplain, 2); */\n      const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);\n      int nDetail;\n      int i;\n\n      if( !zDetail ) continue;\n      nDetail = STRLEN(zDetail);\n\n      for(i=0; i<nDetail; i++){\n        const char *zIdx = 0;\n        if( i+13<nDetail && memcmp(&zDetail[i], \" USING INDEX \", 13)==0 ){\n          zIdx = &zDetail[i+13];\n        }else if( i+22<nDetail \n            && memcmp(&zDetail[i], \" USING COVERING INDEX \", 22)==0 \n        ){\n          zIdx = &zDetail[i+22];\n        }\n        if( zIdx ){\n          const char *zSql;\n          int nIdx = 0;\n          while( zIdx[nIdx]!='\\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){\n            nIdx++;\n          }\n          zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);\n          if( zSql ){\n            idxHashAdd(&rc, &hIdx, zSql, 0);\n            if( rc ) goto find_indexes_out;\n          }\n          break;\n        }\n      }\n\n      if( zDetail[0]!='-' ){\n        pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, \"%s\\n\", zDetail);\n      }\n    }\n\n    for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){\n      pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, \"%s;\\n\", pEntry->zKey);\n    }\n\n    idxFinalize(&rc, pExplain);\n  }\n\n find_indexes_out:\n  idxHashClear(&hIdx);\n  return rc;\n}\n\nstatic int idxAuthCallback(\n  void *pCtx,\n  int eOp,\n  const char *z3,\n  const char *z4,\n  const char *zDb,\n  const char *zTrigger\n){\n  int rc = SQLITE_OK;\n  (void)z4;\n  (void)zTrigger;\n  if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){\n    if( sqlite3_stricmp(zDb, \"main\")==0 ){\n      sqlite3expert *p = (sqlite3expert*)pCtx;\n      IdxTable *pTab;\n      for(pTab=p->pTable; pTab; pTab=pTab->pNext){\n        if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;\n      }\n      if( pTab ){\n        IdxWrite *pWrite;\n        for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){\n          if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;\n        }\n        if( pWrite==0 ){\n          pWrite = idxMalloc(&rc, sizeof(IdxWrite));\n          if( rc==SQLITE_OK ){\n            pWrite->pTab = pTab;\n            pWrite->eOp = eOp;\n            pWrite->pNext = p->pWrite;\n            p->pWrite = pWrite;\n          }\n        }\n      }\n    }\n  }\n  return rc;\n}\n\nstatic int idxProcessOneTrigger(\n  sqlite3expert *p, \n  IdxWrite *pWrite, \n  char **pzErr\n){\n  static const char *zInt = UNIQUE_TABLE_NAME;\n  static const char *zDrop = \"DROP TABLE \" UNIQUE_TABLE_NAME;\n  IdxTable *pTab = pWrite->pTab;\n  const char *zTab = pTab->zName;\n  const char *zSql = \n    \"SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_master \"\n    \"WHERE tbl_name = %Q AND type IN ('table', 'trigger') \"\n    \"ORDER BY type;\";\n  sqlite3_stmt *pSelect = 0;\n  int rc = SQLITE_OK;\n  char *zWrite = 0;\n\n  /* Create the table and its triggers in the temp schema */\n  rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);\n  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){\n    const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);\n    rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);\n  }\n  idxFinalize(&rc, pSelect);\n\n  /* Rename the table in the temp schema to zInt */\n  if( rc==SQLITE_OK ){\n    char *z = sqlite3_mprintf(\"ALTER TABLE temp.%Q RENAME TO %Q\", zTab, zInt);\n    if( z==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);\n      sqlite3_free(z);\n    }\n  }\n\n  switch( pWrite->eOp ){\n    case SQLITE_INSERT: {\n      int i;\n      zWrite = idxAppendText(&rc, zWrite, \"INSERT INTO %Q VALUES(\", zInt);\n      for(i=0; i<pTab->nCol; i++){\n        zWrite = idxAppendText(&rc, zWrite, \"%s?\", i==0 ? \"\" : \", \");\n      }\n      zWrite = idxAppendText(&rc, zWrite, \")\");\n      break;\n    }\n    case SQLITE_UPDATE: {\n      int i;\n      zWrite = idxAppendText(&rc, zWrite, \"UPDATE %Q SET \", zInt);\n      for(i=0; i<pTab->nCol; i++){\n        zWrite = idxAppendText(&rc, zWrite, \"%s%Q=?\", i==0 ? \"\" : \", \", \n            pTab->aCol[i].zName\n        );\n      }\n      break;\n    }\n    default: {\n      assert( pWrite->eOp==SQLITE_DELETE );\n      if( rc==SQLITE_OK ){\n        zWrite = sqlite3_mprintf(\"DELETE FROM %Q\", zInt);\n        if( zWrite==0 ) rc = SQLITE_NOMEM;\n      }\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    sqlite3_stmt *pX = 0;\n    rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);\n    idxFinalize(&rc, pX);\n    if( rc!=SQLITE_OK ){\n      idxDatabaseError(p->dbv, pzErr);\n    }\n  }\n  sqlite3_free(zWrite);\n\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);\n  }\n\n  return rc;\n}\n\nstatic int idxProcessTriggers(sqlite3expert *p, char **pzErr){\n  int rc = SQLITE_OK;\n  IdxWrite *pEnd = 0;\n  IdxWrite *pFirst = p->pWrite;\n\n  while( rc==SQLITE_OK && pFirst!=pEnd ){\n    IdxWrite *pIter;\n    for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){\n      rc = idxProcessOneTrigger(p, pIter, pzErr);\n    }\n    pEnd = pFirst;\n    pFirst = p->pWrite;\n  }\n\n  return rc;\n}\n\n\nstatic int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){\n  int rc = idxRegisterVtab(p);\n  sqlite3_stmt *pSchema = 0;\n\n  /* For each table in the main db schema:\n  **\n  **   1) Add an entry to the p->pTable list, and\n  **   2) Create the equivalent virtual table in dbv.\n  */\n  rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,\n      \"SELECT type, name, sql, 1 FROM sqlite_master \"\n      \"WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' \"\n      \" UNION ALL \"\n      \"SELECT type, name, sql, 2 FROM sqlite_master \"\n      \"WHERE type = 'trigger'\"\n      \"  AND tbl_name IN(SELECT name FROM sqlite_master WHERE type = 'view') \"\n      \"ORDER BY 4, 1\"\n  );\n  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){\n    const char *zType = (const char*)sqlite3_column_text(pSchema, 0);\n    const char *zName = (const char*)sqlite3_column_text(pSchema, 1);\n    const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);\n\n    if( zType[0]=='v' || zType[1]=='r' ){\n      rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);\n    }else{\n      IdxTable *pTab;\n      rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);\n      if( rc==SQLITE_OK ){\n        int i;\n        char *zInner = 0;\n        char *zOuter = 0;\n        pTab->pNext = p->pTable;\n        p->pTable = pTab;\n\n        /* The statement the vtab will pass to sqlite3_declare_vtab() */\n        zInner = idxAppendText(&rc, 0, \"CREATE TABLE x(\");\n        for(i=0; i<pTab->nCol; i++){\n          zInner = idxAppendText(&rc, zInner, \"%s%Q COLLATE %s\", \n              (i==0 ? \"\" : \", \"), pTab->aCol[i].zName, pTab->aCol[i].zColl\n          );\n        }\n        zInner = idxAppendText(&rc, zInner, \")\");\n\n        /* The CVT statement to create the vtab */\n        zOuter = idxAppendText(&rc, 0, \n            \"CREATE VIRTUAL TABLE %Q USING expert(%Q)\", zName, zInner\n        );\n        if( rc==SQLITE_OK ){\n          rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);\n        }\n        sqlite3_free(zInner);\n        sqlite3_free(zOuter);\n      }\n    }\n  }\n  idxFinalize(&rc, pSchema);\n  return rc;\n}\n\nstruct IdxSampleCtx {\n  int iTarget;\n  double target;                  /* Target nRet/nRow value */\n  double nRow;                    /* Number of rows seen */\n  double nRet;                    /* Number of rows returned */\n};\n\nstatic void idxSampleFunc(\n  sqlite3_context *pCtx,\n  int argc,\n  sqlite3_value **argv\n){\n  struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);\n  int bRet;\n\n  (void)argv;\n  assert( argc==0 );\n  if( p->nRow==0.0 ){\n    bRet = 1;\n  }else{\n    bRet = (p->nRet / p->nRow) <= p->target;\n    if( bRet==0 ){\n      unsigned short rnd;\n      sqlite3_randomness(2, (void*)&rnd);\n      bRet = ((int)rnd % 100) <= p->iTarget;\n    }\n  }\n\n  sqlite3_result_int(pCtx, bRet);\n  p->nRow += 1.0;\n  p->nRet += (double)bRet;\n}\n\nstruct IdxRemCtx {\n  int nSlot;\n  struct IdxRemSlot {\n    int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */\n    i64 iVal;                     /* SQLITE_INTEGER value */\n    double rVal;                  /* SQLITE_FLOAT value */\n    int nByte;                    /* Bytes of space allocated at z */\n    int n;                        /* Size of buffer z */\n    char *z;                      /* SQLITE_TEXT/BLOB value */\n  } aSlot[1];\n};\n\n/*\n** Implementation of scalar function rem().\n*/\nstatic void idxRemFunc(\n  sqlite3_context *pCtx,\n  int argc,\n  sqlite3_value **argv\n){\n  struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);\n  struct IdxRemSlot *pSlot;\n  int iSlot;\n  assert( argc==2 );\n\n  iSlot = sqlite3_value_int(argv[0]);\n  assert( iSlot<=p->nSlot );\n  pSlot = &p->aSlot[iSlot];\n\n  switch( pSlot->eType ){\n    case SQLITE_NULL:\n      /* no-op */\n      break;\n\n    case SQLITE_INTEGER:\n      sqlite3_result_int64(pCtx, pSlot->iVal);\n      break;\n\n    case SQLITE_FLOAT:\n      sqlite3_result_double(pCtx, pSlot->rVal);\n      break;\n\n    case SQLITE_BLOB:\n      sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);\n      break;\n\n    case SQLITE_TEXT:\n      sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);\n      break;\n  }\n\n  pSlot->eType = sqlite3_value_type(argv[1]);\n  switch( pSlot->eType ){\n    case SQLITE_NULL:\n      /* no-op */\n      break;\n\n    case SQLITE_INTEGER:\n      pSlot->iVal = sqlite3_value_int64(argv[1]);\n      break;\n\n    case SQLITE_FLOAT:\n      pSlot->rVal = sqlite3_value_double(argv[1]);\n      break;\n\n    case SQLITE_BLOB:\n    case SQLITE_TEXT: {\n      int nByte = sqlite3_value_bytes(argv[1]);\n      if( nByte>pSlot->nByte ){\n        char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);\n        if( zNew==0 ){\n          sqlite3_result_error_nomem(pCtx);\n          return;\n        }\n        pSlot->nByte = nByte*2;\n        pSlot->z = zNew;\n      }\n      pSlot->n = nByte;\n      if( pSlot->eType==SQLITE_BLOB ){\n        memcpy(pSlot->z, sqlite3_value_blob(argv[1]), nByte);\n      }else{\n        memcpy(pSlot->z, sqlite3_value_text(argv[1]), nByte);\n      }\n      break;\n    }\n  }\n}\n\nstatic int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){\n  int rc = SQLITE_OK;\n  const char *zMax = \n    \"SELECT max(i.seqno) FROM \"\n    \"  sqlite_master AS s, \"\n    \"  pragma_index_list(s.name) AS l, \"\n    \"  pragma_index_info(l.name) AS i \"\n    \"WHERE s.type = 'table'\";\n  sqlite3_stmt *pMax = 0;\n\n  *pnMax = 0;\n  rc = idxPrepareStmt(db, &pMax, pzErr, zMax);\n  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){\n    *pnMax = sqlite3_column_int(pMax, 0) + 1;\n  }\n  idxFinalize(&rc, pMax);\n\n  return rc;\n}\n\nstatic int idxPopulateOneStat1(\n  sqlite3expert *p,\n  sqlite3_stmt *pIndexXInfo,\n  sqlite3_stmt *pWriteStat,\n  const char *zTab,\n  const char *zIdx,\n  char **pzErr\n){\n  char *zCols = 0;\n  char *zOrder = 0;\n  char *zQuery = 0;\n  int nCol = 0;\n  int i;\n  sqlite3_stmt *pQuery = 0;\n  int *aStat = 0;\n  int rc = SQLITE_OK;\n\n  assert( p->iSample>0 );\n\n  /* Formulate the query text */\n  sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);\n  while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){\n    const char *zComma = zCols==0 ? \"\" : \", \";\n    const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);\n    const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);\n    zCols = idxAppendText(&rc, zCols, \n        \"%sx.%Q IS rem(%d, x.%Q) COLLATE %s\", zComma, zName, nCol, zName, zColl\n    );\n    zOrder = idxAppendText(&rc, zOrder, \"%s%d\", zComma, ++nCol);\n  }\n  sqlite3_reset(pIndexXInfo);\n  if( rc==SQLITE_OK ){\n    if( p->iSample==100 ){\n      zQuery = sqlite3_mprintf(\n          \"SELECT %s FROM %Q x ORDER BY %s\", zCols, zTab, zOrder\n      );\n    }else{\n      zQuery = sqlite3_mprintf(\n          \"SELECT %s FROM temp.\"UNIQUE_TABLE_NAME\" x ORDER BY %s\", zCols, zOrder\n      );\n    }\n  }\n  sqlite3_free(zCols);\n  sqlite3_free(zOrder);\n\n  /* Formulate the query text */\n  if( rc==SQLITE_OK ){\n    sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);\n    rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);\n  }\n  sqlite3_free(zQuery);\n\n  if( rc==SQLITE_OK ){\n    aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));\n  }\n  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){\n    IdxHashEntry *pEntry;\n    char *zStat = 0;\n    for(i=0; i<=nCol; i++) aStat[i] = 1;\n    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){\n      aStat[0]++;\n      for(i=0; i<nCol; i++){\n        if( sqlite3_column_int(pQuery, i)==0 ) break;\n      }\n      for(/*no-op*/; i<nCol; i++){\n        aStat[i+1]++;\n      }\n    }\n\n    if( rc==SQLITE_OK ){\n      int s0 = aStat[0];\n      zStat = sqlite3_mprintf(\"%d\", s0);\n      if( zStat==0 ) rc = SQLITE_NOMEM;\n      for(i=1; rc==SQLITE_OK && i<=nCol; i++){\n        zStat = idxAppendText(&rc, zStat, \" %d\", (s0+aStat[i]/2) / aStat[i]);\n      }\n    }\n\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);\n      sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);\n      sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);\n      sqlite3_step(pWriteStat);\n      rc = sqlite3_reset(pWriteStat);\n    }\n\n    pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));\n    if( pEntry ){\n      assert( pEntry->zVal2==0 );\n      pEntry->zVal2 = zStat;\n    }else{\n      sqlite3_free(zStat);\n    }\n  }\n  sqlite3_free(aStat);\n  idxFinalize(&rc, pQuery);\n\n  return rc;\n}\n\nstatic int idxBuildSampleTable(sqlite3expert *p, const char *zTab){\n  int rc;\n  char *zSql;\n\n  rc = sqlite3_exec(p->dbv,\"DROP TABLE IF EXISTS temp.\"UNIQUE_TABLE_NAME,0,0,0);\n  if( rc!=SQLITE_OK ) return rc;\n\n  zSql = sqlite3_mprintf(\n      \"CREATE TABLE temp.\" UNIQUE_TABLE_NAME \" AS SELECT * FROM %Q\", zTab\n  );\n  if( zSql==0 ) return SQLITE_NOMEM;\n  rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);\n  sqlite3_free(zSql);\n\n  return rc;\n}\n\n/*\n** This function is called as part of sqlite3_expert_analyze(). Candidate\n** indexes have already been created in database sqlite3expert.dbm, this\n** function populates sqlite_stat1 table in the same database.\n**\n** The stat1 data is generated by querying the \n*/\nstatic int idxPopulateStat1(sqlite3expert *p, char **pzErr){\n  int rc = SQLITE_OK;\n  int nMax =0;\n  struct IdxRemCtx *pCtx = 0;\n  struct IdxSampleCtx samplectx; \n  int i;\n  i64 iPrev = -100000;\n  sqlite3_stmt *pAllIndex = 0;\n  sqlite3_stmt *pIndexXInfo = 0;\n  sqlite3_stmt *pWrite = 0;\n\n  const char *zAllIndex =\n    \"SELECT s.rowid, s.name, l.name FROM \"\n    \"  sqlite_master AS s, \"\n    \"  pragma_index_list(s.name) AS l \"\n    \"WHERE s.type = 'table'\";\n  const char *zIndexXInfo = \n    \"SELECT name, coll FROM pragma_index_xinfo(?) WHERE key\";\n  const char *zWrite = \"INSERT INTO sqlite_stat1 VALUES(?, ?, ?)\";\n\n  /* If iSample==0, no sqlite_stat1 data is required. */\n  if( p->iSample==0 ) return SQLITE_OK;\n\n  rc = idxLargestIndex(p->dbm, &nMax, pzErr);\n  if( nMax<=0 || rc!=SQLITE_OK ) return rc;\n\n  rc = sqlite3_exec(p->dbm, \"ANALYZE; PRAGMA writable_schema=1\", 0, 0, 0);\n\n  if( rc==SQLITE_OK ){\n    int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);\n    pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);\n  }\n\n  if( rc==SQLITE_OK ){\n    sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);\n    rc = sqlite3_create_function(\n        dbrem, \"rem\", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0\n    );\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_function(\n        p->db, \"sample\", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0\n    );\n  }\n\n  if( rc==SQLITE_OK ){\n    pCtx->nSlot = nMax+1;\n    rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);\n  }\n  if( rc==SQLITE_OK ){\n    rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);\n  }\n  if( rc==SQLITE_OK ){\n    rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);\n  }\n\n  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){\n    i64 iRowid = sqlite3_column_int64(pAllIndex, 0);\n    const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);\n    const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);\n    if( p->iSample<100 && iPrev!=iRowid ){\n      samplectx.target = (double)p->iSample / 100.0;\n      samplectx.iTarget = p->iSample;\n      samplectx.nRow = 0.0;\n      samplectx.nRet = 0.0;\n      rc = idxBuildSampleTable(p, zTab);\n      if( rc!=SQLITE_OK ) break;\n    }\n    rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);\n    iPrev = iRowid;\n  }\n  if( rc==SQLITE_OK && p->iSample<100 ){\n    rc = sqlite3_exec(p->dbv, \n        \"DROP TABLE IF EXISTS temp.\" UNIQUE_TABLE_NAME, 0,0,0\n    );\n  }\n\n  idxFinalize(&rc, pAllIndex);\n  idxFinalize(&rc, pIndexXInfo);\n  idxFinalize(&rc, pWrite);\n\n  for(i=0; i<pCtx->nSlot; i++){\n    sqlite3_free(pCtx->aSlot[i].z);\n  }\n  sqlite3_free(pCtx);\n\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_exec(p->dbm, \"ANALYZE sqlite_master\", 0, 0, 0);\n  }\n\n  sqlite3_exec(p->db, \"DROP TABLE IF EXISTS temp.\"UNIQUE_TABLE_NAME,0,0,0);\n  return rc;\n}\n\n/*\n** Allocate a new sqlite3expert object.\n*/\nsqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){\n  int rc = SQLITE_OK;\n  sqlite3expert *pNew;\n\n  pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));\n\n  /* Open two in-memory databases to work with. The \"vtab database\" (dbv)\n  ** will contain a virtual table corresponding to each real table in\n  ** the user database schema, and a copy of each view. It is used to\n  ** collect information regarding the WHERE, ORDER BY and other clauses\n  ** of the user's query.\n  */\n  if( rc==SQLITE_OK ){\n    pNew->db = db;\n    pNew->iSample = 100;\n    rc = sqlite3_open(\":memory:\", &pNew->dbv);\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_open(\":memory:\", &pNew->dbm);\n    if( rc==SQLITE_OK ){\n      sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);\n    }\n  }\n  \n\n  /* Copy the entire schema of database [db] into [dbm]. */\n  if( rc==SQLITE_OK ){\n    sqlite3_stmt *pSql;\n    rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg, \n        \"SELECT sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%%'\"\n        \" AND sql NOT LIKE 'CREATE VIRTUAL %%'\"\n    );\n    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){\n      const char *zSql = (const char*)sqlite3_column_text(pSql, 0);\n      rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);\n    }\n    idxFinalize(&rc, pSql);\n  }\n\n  /* Create the vtab schema */\n  if( rc==SQLITE_OK ){\n    rc = idxCreateVtabSchema(pNew, pzErrmsg);\n  }\n\n  /* Register the auth callback with dbv */\n  if( rc==SQLITE_OK ){\n    sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);\n  }\n\n  /* If an error has occurred, free the new object and reutrn NULL. Otherwise,\n  ** return the new sqlite3expert handle.  */\n  if( rc!=SQLITE_OK ){\n    sqlite3_expert_destroy(pNew);\n    pNew = 0;\n  }\n  return pNew;\n}\n\n/*\n** Configure an sqlite3expert object.\n*/\nint sqlite3_expert_config(sqlite3expert *p, int op, ...){\n  int rc = SQLITE_OK;\n  va_list ap;\n  va_start(ap, op);\n  switch( op ){\n    case EXPERT_CONFIG_SAMPLE: {\n      int iVal = va_arg(ap, int);\n      if( iVal<0 ) iVal = 0;\n      if( iVal>100 ) iVal = 100;\n      p->iSample = iVal;\n      break;\n    }\n    default:\n      rc = SQLITE_NOTFOUND;\n      break;\n  }\n\n  va_end(ap);\n  return rc;\n}\n\n/*\n** Add an SQL statement to the analysis.\n*/\nint sqlite3_expert_sql(\n  sqlite3expert *p,               /* From sqlite3_expert_new() */\n  const char *zSql,               /* SQL statement to add */\n  char **pzErr                    /* OUT: Error message (if any) */\n){\n  IdxScan *pScanOrig = p->pScan;\n  IdxStatement *pStmtOrig = p->pStatement;\n  int rc = SQLITE_OK;\n  const char *zStmt = zSql;\n\n  if( p->bRun ) return SQLITE_MISUSE;\n\n  while( rc==SQLITE_OK && zStmt && zStmt[0] ){\n    sqlite3_stmt *pStmt = 0;\n    rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);\n    if( rc==SQLITE_OK ){\n      if( pStmt ){\n        IdxStatement *pNew;\n        const char *z = sqlite3_sql(pStmt);\n        int n = STRLEN(z);\n        pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);\n        if( rc==SQLITE_OK ){\n          pNew->zSql = (char*)&pNew[1];\n          memcpy(pNew->zSql, z, n+1);\n          pNew->pNext = p->pStatement;\n          if( p->pStatement ) pNew->iId = p->pStatement->iId+1;\n          p->pStatement = pNew;\n        }\n        sqlite3_finalize(pStmt);\n      }\n    }else{\n      idxDatabaseError(p->dbv, pzErr);\n    }\n  }\n\n  if( rc!=SQLITE_OK ){\n    idxScanFree(p->pScan, pScanOrig);\n    idxStatementFree(p->pStatement, pStmtOrig);\n    p->pScan = pScanOrig;\n    p->pStatement = pStmtOrig;\n  }\n\n  return rc;\n}\n\nint sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){\n  int rc;\n  IdxHashEntry *pEntry;\n\n  /* Do trigger processing to collect any extra IdxScan structures */\n  rc = idxProcessTriggers(p, pzErr);\n\n  /* Create candidate indexes within the in-memory database file */\n  if( rc==SQLITE_OK ){\n    rc = idxCreateCandidates(p);\n  }\n\n  /* Generate the stat1 data */\n  if( rc==SQLITE_OK ){\n    rc = idxPopulateStat1(p, pzErr);\n  }\n\n  /* Formulate the EXPERT_REPORT_CANDIDATES text */\n  for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){\n    p->zCandidates = idxAppendText(&rc, p->zCandidates, \n        \"%s;%s%s\\n\", pEntry->zVal, \n        pEntry->zVal2 ? \" -- stat1: \" : \"\", pEntry->zVal2\n    );\n  }\n\n  /* Figure out which of the candidate indexes are preferred by the query\n  ** planner and report the results to the user.  */\n  if( rc==SQLITE_OK ){\n    rc = idxFindIndexes(p, pzErr);\n  }\n\n  if( rc==SQLITE_OK ){\n    p->bRun = 1;\n  }\n  return rc;\n}\n\n/*\n** Return the total number of statements that have been added to this\n** sqlite3expert using sqlite3_expert_sql().\n*/\nint sqlite3_expert_count(sqlite3expert *p){\n  int nRet = 0;\n  if( p->pStatement ) nRet = p->pStatement->iId+1;\n  return nRet;\n}\n\n/*\n** Return a component of the report.\n*/\nconst char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){\n  const char *zRet = 0;\n  IdxStatement *pStmt;\n\n  if( p->bRun==0 ) return 0;\n  for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);\n  switch( eReport ){\n    case EXPERT_REPORT_SQL:\n      if( pStmt ) zRet = pStmt->zSql;\n      break;\n    case EXPERT_REPORT_INDEXES:\n      if( pStmt ) zRet = pStmt->zIdx;\n      break;\n    case EXPERT_REPORT_PLAN:\n      if( pStmt ) zRet = pStmt->zEQP;\n      break;\n    case EXPERT_REPORT_CANDIDATES:\n      zRet = p->zCandidates;\n      break;\n  }\n  return zRet;\n}\n\n/*\n** Free an sqlite3expert object.\n*/\nvoid sqlite3_expert_destroy(sqlite3expert *p){\n  if( p ){\n    sqlite3_close(p->dbm);\n    sqlite3_close(p->dbv);\n    idxScanFree(p->pScan, 0);\n    idxStatementFree(p->pStatement, 0);\n    idxTableFree(p->pTable);\n    idxWriteFree(p->pWrite);\n    idxHashClear(&p->hIdx);\n    sqlite3_free(p->zCandidates);\n    sqlite3_free(p);\n  }\n}\n\n#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */\n\n/************************* End ../ext/expert/sqlite3expert.c ********************/\n\n#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)\n/************************* Begin ../ext/misc/dbdata.c ******************/\n/*\n** 2019-04-17\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains an implementation of two eponymous virtual tables,\n** \"sqlite_dbdata\" and \"sqlite_dbptr\". Both modules require that the\n** \"sqlite_dbpage\" eponymous virtual table be available.\n**\n** SQLITE_DBDATA:\n**   sqlite_dbdata is used to extract data directly from a database b-tree\n**   page and its associated overflow pages, bypassing the b-tree layer.\n**   The table schema is equivalent to:\n**\n**     CREATE TABLE sqlite_dbdata(\n**       pgno INTEGER,\n**       cell INTEGER,\n**       field INTEGER,\n**       value ANY,\n**       schema TEXT HIDDEN\n**     );\n**\n**   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE\n**   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN \"value\" AND\n**   \"schema\".\n**\n**   Each page of the database is inspected. If it cannot be interpreted as\n**   a b-tree page, or if it is a b-tree page containing 0 entries, the\n**   sqlite_dbdata table contains no rows for that page.  Otherwise, the\n**   table contains one row for each field in the record associated with\n**   each cell on the page. For intkey b-trees, the key value is stored in\n**   field -1.\n**\n**   For example, for the database:\n**\n**     CREATE TABLE t1(a, b);     -- root page is page 2\n**     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');\n**     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');\n**\n**   the sqlite_dbdata table contains, as well as from entries related to \n**   page 1, content equivalent to:\n**\n**     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES\n**         (2, 0, -1, 5     ),\n**         (2, 0,  0, 'v'   ),\n**         (2, 0,  1, 'five'),\n**         (2, 1, -1, 10    ),\n**         (2, 1,  0, 'x'   ),\n**         (2, 1,  1, 'ten' );\n**\n**   If database corruption is encountered, this module does not report an\n**   error. Instead, it attempts to extract as much data as possible and\n**   ignores the corruption.\n**\n** SQLITE_DBPTR:\n**   The sqlite_dbptr table has the following schema:\n**\n**     CREATE TABLE sqlite_dbptr(\n**       pgno INTEGER,\n**       child INTEGER,\n**       schema TEXT HIDDEN\n**     );\n**\n**   It contains one entry for each b-tree pointer between a parent and\n**   child page in the database.\n*/\n#if !defined(SQLITEINT_H) \n/* #include \"sqlite3ext.h\" */\n\n/* typedef unsigned char u8; */\n\n#endif\nSQLITE_EXTENSION_INIT1\n#include <string.h>\n#include <assert.h>\n\n#define DBDATA_PADDING_BYTES 100 \n\ntypedef struct DbdataTable DbdataTable;\ntypedef struct DbdataCursor DbdataCursor;\n\n/* Cursor object */\nstruct DbdataCursor {\n  sqlite3_vtab_cursor base;       /* Base class.  Must be first */\n  sqlite3_stmt *pStmt;            /* For fetching database pages */\n\n  int iPgno;                      /* Current page number */\n  u8 *aPage;                      /* Buffer containing page */\n  int nPage;                      /* Size of aPage[] in bytes */\n  int nCell;                      /* Number of cells on aPage[] */\n  int iCell;                      /* Current cell number */\n  int bOnePage;                   /* True to stop after one page */\n  int szDb;\n  sqlite3_int64 iRowid;\n\n  /* Only for the sqlite_dbdata table */\n  u8 *pRec;                       /* Buffer containing current record */\n  int nRec;                       /* Size of pRec[] in bytes */\n  int nHdr;                       /* Size of header in bytes */\n  int iField;                     /* Current field number */\n  u8 *pHdrPtr;\n  u8 *pPtr;\n  \n  sqlite3_int64 iIntkey;          /* Integer key value */\n};\n\n/* Table object */\nstruct DbdataTable {\n  sqlite3_vtab base;              /* Base class.  Must be first */\n  sqlite3 *db;                    /* The database connection */\n  sqlite3_stmt *pStmt;            /* For fetching database pages */\n  int bPtr;                       /* True for sqlite3_dbptr table */\n};\n\n/* Column and schema definitions for sqlite_dbdata */\n#define DBDATA_COLUMN_PGNO        0\n#define DBDATA_COLUMN_CELL        1\n#define DBDATA_COLUMN_FIELD       2\n#define DBDATA_COLUMN_VALUE       3\n#define DBDATA_COLUMN_SCHEMA      4\n#define DBDATA_SCHEMA             \\\n      \"CREATE TABLE x(\"           \\\n      \"  pgno INTEGER,\"           \\\n      \"  cell INTEGER,\"           \\\n      \"  field INTEGER,\"          \\\n      \"  value ANY,\"              \\\n      \"  schema TEXT HIDDEN\"      \\\n      \")\"\n\n/* Column and schema definitions for sqlite_dbptr */\n#define DBPTR_COLUMN_PGNO         0\n#define DBPTR_COLUMN_CHILD        1\n#define DBPTR_COLUMN_SCHEMA       2\n#define DBPTR_SCHEMA              \\\n      \"CREATE TABLE x(\"           \\\n      \"  pgno INTEGER,\"           \\\n      \"  child INTEGER,\"          \\\n      \"  schema TEXT HIDDEN\"      \\\n      \")\"\n\n/*\n** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual \n** table.\n*/\nstatic int dbdataConnect(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  DbdataTable *pTab = 0;\n  int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);\n\n  if( rc==SQLITE_OK ){\n    pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));\n    if( pTab==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      memset(pTab, 0, sizeof(DbdataTable));\n      pTab->db = db;\n      pTab->bPtr = (pAux!=0);\n    }\n  }\n\n  *ppVtab = (sqlite3_vtab*)pTab;\n  return rc;\n}\n\n/*\n** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.\n*/\nstatic int dbdataDisconnect(sqlite3_vtab *pVtab){\n  DbdataTable *pTab = (DbdataTable*)pVtab;\n  if( pTab ){\n    sqlite3_finalize(pTab->pStmt);\n    sqlite3_free(pVtab);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** This function interprets two types of constraints:\n**\n**       schema=?\n**       pgno=?\n**\n** If neither are present, idxNum is set to 0. If schema=? is present,\n** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit\n** in idxNum is set.\n**\n** If both parameters are present, schema is in position 0 and pgno in\n** position 1.\n*/\nstatic int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){\n  DbdataTable *pTab = (DbdataTable*)tab;\n  int i;\n  int iSchema = -1;\n  int iPgno = -1;\n  int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);\n\n  for(i=0; i<pIdx->nConstraint; i++){\n    struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];\n    if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){\n      if( p->iColumn==colSchema ){\n        if( p->usable==0 ) return SQLITE_CONSTRAINT;\n        iSchema = i;\n      }\n      if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){\n        iPgno = i;\n      }\n    }\n  }\n\n  if( iSchema>=0 ){\n    pIdx->aConstraintUsage[iSchema].argvIndex = 1;\n    pIdx->aConstraintUsage[iSchema].omit = 1;\n  }\n  if( iPgno>=0 ){\n    pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);\n    pIdx->aConstraintUsage[iPgno].omit = 1;\n    pIdx->estimatedCost = 100;\n    pIdx->estimatedRows =  50;\n\n    if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){\n      int iCol = pIdx->aOrderBy[0].iColumn;\n      if( pIdx->nOrderBy==1 ){\n        pIdx->orderByConsumed = (iCol==0 || iCol==1);\n      }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){\n        pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);\n      }\n    }\n\n  }else{\n    pIdx->estimatedCost = 100000000;\n    pIdx->estimatedRows = 1000000000;\n  }\n  pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);\n  return SQLITE_OK;\n}\n\n/*\n** Open a new sqlite_dbdata or sqlite_dbptr cursor.\n*/\nstatic int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){\n  DbdataCursor *pCsr;\n\n  pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));\n  if( pCsr==0 ){\n    return SQLITE_NOMEM;\n  }else{\n    memset(pCsr, 0, sizeof(DbdataCursor));\n    pCsr->base.pVtab = pVTab;\n  }\n\n  *ppCursor = (sqlite3_vtab_cursor *)pCsr;\n  return SQLITE_OK;\n}\n\n/*\n** Restore a cursor object to the state it was in when first allocated \n** by dbdataOpen().\n*/\nstatic void dbdataResetCursor(DbdataCursor *pCsr){\n  DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);\n  if( pTab->pStmt==0 ){\n    pTab->pStmt = pCsr->pStmt;\n  }else{\n    sqlite3_finalize(pCsr->pStmt);\n  }\n  pCsr->pStmt = 0;\n  pCsr->iPgno = 1;\n  pCsr->iCell = 0;\n  pCsr->iField = 0;\n  pCsr->bOnePage = 0;\n  sqlite3_free(pCsr->aPage);\n  sqlite3_free(pCsr->pRec);\n  pCsr->pRec = 0;\n  pCsr->aPage = 0;\n}\n\n/*\n** Close an sqlite_dbdata or sqlite_dbptr cursor.\n*/\nstatic int dbdataClose(sqlite3_vtab_cursor *pCursor){\n  DbdataCursor *pCsr = (DbdataCursor*)pCursor;\n  dbdataResetCursor(pCsr);\n  sqlite3_free(pCsr);\n  return SQLITE_OK;\n}\n\n/* \n** Utility methods to decode 16 and 32-bit big-endian unsigned integers. \n*/\nstatic unsigned int get_uint16(unsigned char *a){\n  return (a[0]<<8)|a[1];\n}\nstatic unsigned int get_uint32(unsigned char *a){\n  return ((unsigned int)a[0]<<24)\n       | ((unsigned int)a[1]<<16)\n       | ((unsigned int)a[2]<<8)\n       | ((unsigned int)a[3]);\n}\n\n/*\n** Load page pgno from the database via the sqlite_dbpage virtual table.\n** If successful, set (*ppPage) to point to a buffer containing the page\n** data, (*pnPage) to the size of that buffer in bytes and return\n** SQLITE_OK. In this case it is the responsibility of the caller to\n** eventually free the buffer using sqlite3_free().\n**\n** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and\n** return an SQLite error code.\n*/\nstatic int dbdataLoadPage(\n  DbdataCursor *pCsr,             /* Cursor object */\n  unsigned int pgno,              /* Page number of page to load */\n  u8 **ppPage,                    /* OUT: pointer to page buffer */\n  int *pnPage                     /* OUT: Size of (*ppPage) in bytes */\n){\n  int rc2;\n  int rc = SQLITE_OK;\n  sqlite3_stmt *pStmt = pCsr->pStmt;\n\n  *ppPage = 0;\n  *pnPage = 0;\n  sqlite3_bind_int64(pStmt, 2, pgno);\n  if( SQLITE_ROW==sqlite3_step(pStmt) ){\n    int nCopy = sqlite3_column_bytes(pStmt, 0);\n    if( nCopy>0 ){\n      u8 *pPage;\n      pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);\n      if( pPage==0 ){\n        rc = SQLITE_NOMEM;\n      }else{\n        const u8 *pCopy = sqlite3_column_blob(pStmt, 0);\n        memcpy(pPage, pCopy, nCopy);\n        memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);\n      }\n      *ppPage = pPage;\n      *pnPage = nCopy;\n    }\n  }\n  rc2 = sqlite3_reset(pStmt);\n  if( rc==SQLITE_OK ) rc = rc2;\n\n  return rc;\n}\n\n/*\n** Read a varint.  Put the value in *pVal and return the number of bytes.\n*/\nstatic int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){\n  sqlite3_int64 v = 0;\n  int i;\n  for(i=0; i<8; i++){\n    v = (v<<7) + (z[i]&0x7f);\n    if( (z[i]&0x80)==0 ){ *pVal = v; return i+1; }\n  }\n  v = (v<<8) + (z[i]&0xff);\n  *pVal = v;\n  return 9;\n}\n\n/*\n** Return the number of bytes of space used by an SQLite value of type\n** eType.\n*/\nstatic int dbdataValueBytes(int eType){\n  switch( eType ){\n    case 0: case 8: case 9:\n    case 10: case 11:\n      return 0;\n    case 1:\n      return 1;\n    case 2:\n      return 2;\n    case 3:\n      return 3;\n    case 4:\n      return 4;\n    case 5:\n      return 6;\n    case 6:\n    case 7:\n      return 8;\n    default:\n      if( eType>0 ){\n        return ((eType-12) / 2);\n      }\n      return 0;\n  }\n}\n\n/*\n** Load a value of type eType from buffer pData and use it to set the\n** result of context object pCtx.\n*/\nstatic void dbdataValue(\n  sqlite3_context *pCtx, \n  int eType, \n  u8 *pData,\n  int nData\n){\n  if( eType>=0 && dbdataValueBytes(eType)<=nData ){\n    switch( eType ){\n      case 0: \n      case 10: \n      case 11: \n        sqlite3_result_null(pCtx);\n        break;\n      \n      case 8: \n        sqlite3_result_int(pCtx, 0);\n        break;\n      case 9:\n        sqlite3_result_int(pCtx, 1);\n        break;\n  \n      case 1: case 2: case 3: case 4: case 5: case 6: case 7: {\n        sqlite3_uint64 v = (signed char)pData[0];\n        pData++;\n        switch( eType ){\n          case 7:\n          case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;\n          case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;\n          case 4:  v = (v<<8) + pData[0];  pData++;\n          case 3:  v = (v<<8) + pData[0];  pData++;\n          case 2:  v = (v<<8) + pData[0];  pData++;\n        }\n  \n        if( eType==7 ){\n          double r;\n          memcpy(&r, &v, sizeof(r));\n          sqlite3_result_double(pCtx, r);\n        }else{\n          sqlite3_result_int64(pCtx, (sqlite3_int64)v);\n        }\n        break;\n      }\n  \n      default: {\n        int n = ((eType-12) / 2);\n        if( eType % 2 ){\n          sqlite3_result_text(pCtx, (const char*)pData, n, SQLITE_TRANSIENT);\n        }else{\n          sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);\n        }\n      }\n    }\n  }\n}\n\n/*\n** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.\n*/\nstatic int dbdataNext(sqlite3_vtab_cursor *pCursor){\n  DbdataCursor *pCsr = (DbdataCursor*)pCursor;\n  DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;\n\n  pCsr->iRowid++;\n  while( 1 ){\n    int rc;\n    int iOff = (pCsr->iPgno==1 ? 100 : 0);\n    int bNextPage = 0;\n\n    if( pCsr->aPage==0 ){\n      while( 1 ){\n        if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;\n        rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);\n        if( rc!=SQLITE_OK ) return rc;\n        if( pCsr->aPage ) break;\n        pCsr->iPgno++;\n      }\n      pCsr->iCell = pTab->bPtr ? -2 : 0;\n      pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);\n    }\n\n    if( pTab->bPtr ){\n      if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){\n        pCsr->iCell = pCsr->nCell;\n      }\n      pCsr->iCell++;\n      if( pCsr->iCell>=pCsr->nCell ){\n        sqlite3_free(pCsr->aPage);\n        pCsr->aPage = 0;\n        if( pCsr->bOnePage ) return SQLITE_OK;\n        pCsr->iPgno++;\n      }else{\n        return SQLITE_OK;\n      }\n    }else{\n      /* If there is no record loaded, load it now. */\n      if( pCsr->pRec==0 ){\n        int bHasRowid = 0;\n        int nPointer = 0;\n        sqlite3_int64 nPayload = 0;\n        sqlite3_int64 nHdr = 0;\n        int iHdr;\n        int U, X;\n        int nLocal;\n  \n        switch( pCsr->aPage[iOff] ){\n          case 0x02:\n            nPointer = 4;\n            break;\n          case 0x0a:\n            break;\n          case 0x0d:\n            bHasRowid = 1;\n            break;\n          default:\n            /* This is not a b-tree page with records on it. Continue. */\n            pCsr->iCell = pCsr->nCell;\n            break;\n        }\n\n        if( pCsr->iCell>=pCsr->nCell ){\n          bNextPage = 1;\n        }else{\n  \n          iOff += 8 + nPointer + pCsr->iCell*2;\n          if( iOff>pCsr->nPage ){\n            bNextPage = 1;\n          }else{\n            iOff = get_uint16(&pCsr->aPage[iOff]);\n          }\n    \n          /* For an interior node cell, skip past the child-page number */\n          iOff += nPointer;\n    \n          /* Load the \"byte of payload including overflow\" field */\n          if( bNextPage || iOff>pCsr->nPage ){\n            bNextPage = 1;\n          }else{\n            iOff += dbdataGetVarint(&pCsr->aPage[iOff], &nPayload);\n          }\n    \n          /* If this is a leaf intkey cell, load the rowid */\n          if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){\n            iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);\n          }\n    \n          /* Figure out how much data to read from the local page */\n          U = pCsr->nPage;\n          if( bHasRowid ){\n            X = U-35;\n          }else{\n            X = ((U-12)*64/255)-23;\n          }\n          if( nPayload<=X ){\n            nLocal = nPayload;\n          }else{\n            int M, K;\n            M = ((U-12)*32/255)-23;\n            K = M+((nPayload-M)%(U-4));\n            if( K<=X ){\n              nLocal = K;\n            }else{\n              nLocal = M;\n            }\n          }\n\n          if( bNextPage || nLocal+iOff>pCsr->nPage ){\n            bNextPage = 1;\n          }else{\n\n            /* Allocate space for payload. And a bit more to catch small buffer\n            ** overruns caused by attempting to read a varint or similar from \n            ** near the end of a corrupt record.  */\n            pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);\n            if( pCsr->pRec==0 ) return SQLITE_NOMEM;\n            memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);\n            pCsr->nRec = nPayload;\n\n            /* Load the nLocal bytes of payload */\n            memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);\n            iOff += nLocal;\n\n            /* Load content from overflow pages */\n            if( nPayload>nLocal ){\n              sqlite3_int64 nRem = nPayload - nLocal;\n              unsigned int pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);\n              while( nRem>0 ){\n                u8 *aOvfl = 0;\n                int nOvfl = 0;\n                int nCopy;\n                rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);\n                assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );\n                if( rc!=SQLITE_OK ) return rc;\n                if( aOvfl==0 ) break;\n\n                nCopy = U-4;\n                if( nCopy>nRem ) nCopy = nRem;\n                memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);\n                nRem -= nCopy;\n\n                pgnoOvfl = get_uint32(aOvfl);\n                sqlite3_free(aOvfl);\n              }\n            }\n    \n            iHdr = dbdataGetVarint(pCsr->pRec, &nHdr);\n            pCsr->nHdr = nHdr;\n            pCsr->pHdrPtr = &pCsr->pRec[iHdr];\n            pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];\n            pCsr->iField = (bHasRowid ? -1 : 0);\n          }\n        }\n      }else{\n        pCsr->iField++;\n        if( pCsr->iField>0 ){\n          sqlite3_int64 iType;\n          if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){\n            bNextPage = 1;\n          }else{\n            pCsr->pHdrPtr += dbdataGetVarint(pCsr->pHdrPtr, &iType);\n            pCsr->pPtr += dbdataValueBytes(iType);\n          }\n        }\n      }\n\n      if( bNextPage ){\n        sqlite3_free(pCsr->aPage);\n        sqlite3_free(pCsr->pRec);\n        pCsr->aPage = 0;\n        pCsr->pRec = 0;\n        if( pCsr->bOnePage ) return SQLITE_OK;\n        pCsr->iPgno++;\n      }else{\n        if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){\n          return SQLITE_OK;\n        }\n\n        /* Advance to the next cell. The next iteration of the loop will load\n        ** the record and so on. */\n        sqlite3_free(pCsr->pRec);\n        pCsr->pRec = 0;\n        pCsr->iCell++;\n      }\n    }\n  }\n\n  assert( !\"can't get here\" );\n  return SQLITE_OK;\n}\n\n/* \n** Return true if the cursor is at EOF.\n*/\nstatic int dbdataEof(sqlite3_vtab_cursor *pCursor){\n  DbdataCursor *pCsr = (DbdataCursor*)pCursor;\n  return pCsr->aPage==0;\n}\n\n/* \n** Determine the size in pages of database zSchema (where zSchema is\n** \"main\", \"temp\" or the name of an attached database) and set \n** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,\n** an SQLite error code.\n*/\nstatic int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){\n  DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;\n  char *zSql = 0;\n  int rc, rc2;\n  sqlite3_stmt *pStmt = 0;\n\n  zSql = sqlite3_mprintf(\"PRAGMA %Q.page_count\", zSchema);\n  if( zSql==0 ) return SQLITE_NOMEM;\n  rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);\n  sqlite3_free(zSql);\n  if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){\n    pCsr->szDb = sqlite3_column_int(pStmt, 0);\n  }\n  rc2 = sqlite3_finalize(pStmt);\n  if( rc==SQLITE_OK ) rc = rc2;\n  return rc;\n}\n\n/* \n** xFilter method for sqlite_dbdata and sqlite_dbptr.\n*/\nstatic int dbdataFilter(\n  sqlite3_vtab_cursor *pCursor, \n  int idxNum, const char *idxStr,\n  int argc, sqlite3_value **argv\n){\n  DbdataCursor *pCsr = (DbdataCursor*)pCursor;\n  DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;\n  int rc = SQLITE_OK;\n  const char *zSchema = \"main\";\n\n  dbdataResetCursor(pCsr);\n  assert( pCsr->iPgno==1 );\n  if( idxNum & 0x01 ){\n    zSchema = (const char*)sqlite3_value_text(argv[0]);\n  }\n  if( idxNum & 0x02 ){\n    pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);\n    pCsr->bOnePage = 1;\n  }else{\n    pCsr->nPage = dbdataDbsize(pCsr, zSchema);\n    rc = dbdataDbsize(pCsr, zSchema);\n  }\n\n  if( rc==SQLITE_OK ){\n    if( pTab->pStmt ){\n      pCsr->pStmt = pTab->pStmt;\n      pTab->pStmt = 0;\n    }else{\n      rc = sqlite3_prepare_v2(pTab->db, \n          \"SELECT data FROM sqlite_dbpage(?) WHERE pgno=?\", -1,\n          &pCsr->pStmt, 0\n      );\n    }\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);\n  }else{\n    pTab->base.zErrMsg = sqlite3_mprintf(\"%s\", sqlite3_errmsg(pTab->db));\n  }\n  if( rc==SQLITE_OK ){\n    rc = dbdataNext(pCursor);\n  }\n  return rc;\n}\n\n/* \n** Return a column for the sqlite_dbdata or sqlite_dbptr table.\n*/\nstatic int dbdataColumn(\n  sqlite3_vtab_cursor *pCursor, \n  sqlite3_context *ctx, \n  int i\n){\n  DbdataCursor *pCsr = (DbdataCursor*)pCursor;\n  DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;\n  if( pTab->bPtr ){\n    switch( i ){\n      case DBPTR_COLUMN_PGNO:\n        sqlite3_result_int64(ctx, pCsr->iPgno);\n        break;\n      case DBPTR_COLUMN_CHILD: {\n        int iOff = pCsr->iPgno==1 ? 100 : 0;\n        if( pCsr->iCell<0 ){\n          iOff += 8;\n        }else{\n          iOff += 12 + pCsr->iCell*2;\n          if( iOff>pCsr->nPage ) return SQLITE_OK;\n          iOff = get_uint16(&pCsr->aPage[iOff]);\n        }\n        if( iOff<=pCsr->nPage ){\n          sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));\n        }\n        break;\n      }\n    }\n  }else{\n    switch( i ){\n      case DBDATA_COLUMN_PGNO:\n        sqlite3_result_int64(ctx, pCsr->iPgno);\n        break;\n      case DBDATA_COLUMN_CELL:\n        sqlite3_result_int(ctx, pCsr->iCell);\n        break;\n      case DBDATA_COLUMN_FIELD:\n        sqlite3_result_int(ctx, pCsr->iField);\n        break;\n      case DBDATA_COLUMN_VALUE: {\n        if( pCsr->iField<0 ){\n          sqlite3_result_int64(ctx, pCsr->iIntkey);\n        }else{\n          sqlite3_int64 iType;\n          dbdataGetVarint(pCsr->pHdrPtr, &iType);\n          dbdataValue(\n              ctx, iType, pCsr->pPtr, &pCsr->pRec[pCsr->nRec] - pCsr->pPtr\n          );\n        }\n        break;\n      }\n    }\n  }\n  return SQLITE_OK;\n}\n\n/* \n** Return the rowid for an sqlite_dbdata or sqlite_dptr table.\n*/\nstatic int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){\n  DbdataCursor *pCsr = (DbdataCursor*)pCursor;\n  *pRowid = pCsr->iRowid;\n  return SQLITE_OK;\n}\n\n\n/*\n** Invoke this routine to register the \"sqlite_dbdata\" virtual table module\n*/\nstatic int sqlite3DbdataRegister(sqlite3 *db){\n  static sqlite3_module dbdata_module = {\n    0,                            /* iVersion */\n    0,                            /* xCreate */\n    dbdataConnect,                /* xConnect */\n    dbdataBestIndex,              /* xBestIndex */\n    dbdataDisconnect,             /* xDisconnect */\n    0,                            /* xDestroy */\n    dbdataOpen,                   /* xOpen - open a cursor */\n    dbdataClose,                  /* xClose - close a cursor */\n    dbdataFilter,                 /* xFilter - configure scan constraints */\n    dbdataNext,                   /* xNext - advance a cursor */\n    dbdataEof,                    /* xEof - check for end of scan */\n    dbdataColumn,                 /* xColumn - read data */\n    dbdataRowid,                  /* xRowid - read data */\n    0,                            /* xUpdate */\n    0,                            /* xBegin */\n    0,                            /* xSync */\n    0,                            /* xCommit */\n    0,                            /* xRollback */\n    0,                            /* xFindMethod */\n    0,                            /* xRename */\n    0,                            /* xSavepoint */\n    0,                            /* xRelease */\n    0,                            /* xRollbackTo */\n    0                             /* xShadowName */\n  };\n\n  int rc = sqlite3_create_module(db, \"sqlite_dbdata\", &dbdata_module, 0);\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_module(db, \"sqlite_dbptr\", &dbdata_module, (void*)1);\n  }\n  return rc;\n}\n\n#ifdef _WIN32\n\n#endif\nint sqlite3_dbdata_init(\n  sqlite3 *db, \n  char **pzErrMsg, \n  const sqlite3_api_routines *pApi\n){\n  SQLITE_EXTENSION_INIT2(pApi);\n  return sqlite3DbdataRegister(db);\n}\n\n/************************* End ../ext/misc/dbdata.c ********************/\n#endif\n\n#if defined(SQLITE_ENABLE_SESSION)\n/*\n** State information for a single open session\n*/\ntypedef struct OpenSession OpenSession;\nstruct OpenSession {\n  char *zName;             /* Symbolic name for this session */\n  int nFilter;             /* Number of xFilter rejection GLOB patterns */\n  char **azFilter;         /* Array of xFilter rejection GLOB patterns */\n  sqlite3_session *p;      /* The open session */\n};\n#endif\n\n/*\n** Shell output mode information from before \".explain on\",\n** saved so that it can be restored by \".explain off\"\n*/\ntypedef struct SavedModeInfo SavedModeInfo;\nstruct SavedModeInfo {\n  int valid;          /* Is there legit data in here? */\n  int mode;           /* Mode prior to \".explain on\" */\n  int showHeader;     /* The \".header\" setting prior to \".explain on\" */\n  int colWidth[100];  /* Column widths prior to \".explain on\" */\n};\n\ntypedef struct ExpertInfo ExpertInfo;\nstruct ExpertInfo {\n  sqlite3expert *pExpert;\n  int bVerbose;\n};\n\n/* A single line in the EQP output */\ntypedef struct EQPGraphRow EQPGraphRow;\nstruct EQPGraphRow {\n  int iEqpId;           /* ID for this row */\n  int iParentId;        /* ID of the parent row */\n  EQPGraphRow *pNext;   /* Next row in sequence */\n  char zText[1];        /* Text to display for this row */\n};\n\n/* All EQP output is collected into an instance of the following */\ntypedef struct EQPGraph EQPGraph;\nstruct EQPGraph {\n  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */\n  EQPGraphRow *pLast;   /* Last element of the pRow list */\n  char zPrefix[100];    /* Graph prefix */\n};\n\n/*\n** State information about the database connection is contained in an\n** instance of the following structure.\n*/\ntypedef struct ShellState ShellState;\nstruct ShellState {\n  sqlite3 *db;           /* The database */\n  u8 autoExplain;        /* Automatically turn on .explain mode */\n  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */\n  u8 autoEQPtest;        /* autoEQP is in test mode */\n  u8 autoEQPtrace;       /* autoEQP is in trace mode */\n  u8 statsOn;            /* True to display memory stats before each finalize */\n  u8 scanstatsOn;        /* True to display scan stats before each finalize */\n  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */\n  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */\n  u8 nEqpLevel;          /* Depth of the EQP output graph */\n  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */\n  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */\n  int outCount;          /* Revert to stdout when reaching zero */\n  int cnt;               /* Number of records displayed so far */\n  int lineno;            /* Line number of last line read from in */\n  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */\n  FILE *in;              /* Read commands from this stream */\n  FILE *out;             /* Write results here */\n  FILE *traceOut;        /* Output for sqlite3_trace() */\n  int nErr;              /* Number of errors seen */\n  int mode;              /* An output mode setting */\n  int modePrior;         /* Saved mode */\n  int cMode;             /* temporary output mode for the current query */\n  int normalMode;        /* Output mode before \".explain on\" */\n  int writableSchema;    /* True if PRAGMA writable_schema=ON */\n  int showHeader;        /* True to show column names in List or Column mode */\n  int nCheck;            /* Number of \".check\" commands run */\n  unsigned nProgress;    /* Number of progress callbacks encountered */\n  unsigned mxProgress;   /* Maximum progress callbacks before failing */\n  unsigned flgProgress;  /* Flags for the progress callback */\n  unsigned shellFlgs;    /* Various flags */\n  unsigned priorShFlgs;  /* Saved copy of flags */\n  sqlite3_int64 szMax;   /* --maxsize argument to .open */\n  char *zDestTable;      /* Name of destination table when MODE_Insert */\n  char *zTempFile;       /* Temporary file that might need deleting */\n  char zTestcase[30];    /* Name of current test case */\n  char colSeparator[20]; /* Column separator character for several modes */\n  char rowSeparator[20]; /* Row separator character for MODE_Ascii */\n  char colSepPrior[20];  /* Saved column separator */\n  char rowSepPrior[20];  /* Saved row separator */\n  int colWidth[100];     /* Requested width of each column when in column mode*/\n  int actualWidth[100];  /* Actual width of each column */\n  char nullValue[20];    /* The text to print when a NULL comes back from\n                         ** the database */\n  char outfile[FILENAME_MAX]; /* Filename for *out */\n  const char *zDbFilename;    /* name of the database file */\n  char *zFreeOnClose;         /* Filename to free when closing */\n  const char *zVfs;           /* Name of VFS to use */\n  sqlite3_stmt *pStmt;   /* Current statement if any. */\n  FILE *pLog;            /* Write log output here */\n  int *aiIndent;         /* Array of indents used in MODE_Explain */\n  int nIndent;           /* Size of array aiIndent[] */\n  int iIndent;           /* Index of current op in aiIndent[] */\n  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */\n#if defined(SQLITE_ENABLE_SESSION)\n  int nSession;             /* Number of active sessions */\n  OpenSession aSession[4];  /* Array of sessions.  [0] is in focus. */\n#endif\n  ExpertInfo expert;        /* Valid if previous command was \".expert OPT...\" */\n};\n\n\n/* Allowed values for ShellState.autoEQP\n*/\n#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */\n#define AUTOEQP_on       1           /* Automatic EQP is on */\n#define AUTOEQP_trigger  2           /* On and also show plans for triggers */\n#define AUTOEQP_full     3           /* Show full EXPLAIN */\n\n/* Allowed values for ShellState.openMode\n*/\n#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */\n#define SHELL_OPEN_NORMAL      1      /* Normal database file */\n#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */\n#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */\n#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */\n#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */\n#define SHELL_OPEN_HEXDB       6      /* Use \"dbtotxt\" output as data source */\n\n/* Allowed values for ShellState.eTraceType\n*/\n#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */\n#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */\n#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */\n\n/* Bits in the ShellState.flgProgress variable */\n#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */\n#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres\n                                   ** callback limit is reached, and for each\n                                   ** top-level SQL statement */\n#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */\n\n/*\n** These are the allowed shellFlgs values\n*/\n#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */\n#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */\n#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */\n#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */\n#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */\n#define SHFLG_CountChanges   0x00000020 /* .changes setting */\n#define SHFLG_Echo           0x00000040 /* .echo or --echo setting */\n\n/*\n** Macros for testing and setting shellFlgs\n*/\n#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)\n#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))\n#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))\n\n/*\n** These are the allowed modes.\n*/\n#define MODE_Line     0  /* One column per line.  Blank line between records */\n#define MODE_Column   1  /* One record per line in neat columns */\n#define MODE_List     2  /* One record per line with a separator */\n#define MODE_Semi     3  /* Same as MODE_List but append \";\" to each line */\n#define MODE_Html     4  /* Generate an XHTML table */\n#define MODE_Insert   5  /* Generate SQL \"insert\" statements */\n#define MODE_Quote    6  /* Quote values as for SQL */\n#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */\n#define MODE_Csv      8  /* Quote strings, numbers are plain */\n#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */\n#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */\n#define MODE_Pretty  11  /* Pretty-print schemas */\n#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */\n\nstatic const char *modeDescr[] = {\n  \"line\",\n  \"column\",\n  \"list\",\n  \"semi\",\n  \"html\",\n  \"insert\",\n  \"quote\",\n  \"tcl\",\n  \"csv\",\n  \"explain\",\n  \"ascii\",\n  \"prettyprint\",\n  \"eqp\"\n};\n\n/*\n** These are the column/row/line separators used by the various\n** import/export modes.\n*/\n#define SEP_Column    \"|\"\n#define SEP_Row       \"\\n\"\n#define SEP_Tab       \"\\t\"\n#define SEP_Space     \" \"\n#define SEP_Comma     \",\"\n#define SEP_CrLf      \"\\r\\n\"\n#define SEP_Unit      \"\\x1F\"\n#define SEP_Record    \"\\x1E\"\n\n/*\n** A callback for the sqlite3_log() interface.\n*/\nstatic void shellLog(void *pArg, int iErrCode, const char *zMsg){\n  ShellState *p = (ShellState*)pArg;\n  if( p->pLog==0 ) return;\n  utf8_printf(p->pLog, \"(%d) %s\\n\", iErrCode, zMsg);\n  fflush(p->pLog);\n}\n\n/*\n** SQL function:  shell_putsnl(X)\n**\n** Write the text X to the screen (or whatever output is being directed)\n** adding a newline at the end, and then return X.\n*/\nstatic void shellPutsFunc(\n  sqlite3_context *pCtx,\n  int nVal,\n  sqlite3_value **apVal\n){\n  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);\n  (void)nVal;\n  utf8_printf(p->out, \"%s\\n\", sqlite3_value_text(apVal[0]));\n  sqlite3_result_value(pCtx, apVal[0]);\n}\n\n/*\n** SQL function:   edit(VALUE)\n**                 edit(VALUE,EDITOR)\n**\n** These steps:\n**\n**     (1) Write VALUE into a temporary file.\n**     (2) Run program EDITOR on that temporary file.\n**     (3) Read the temporary file back and return its content as the result.\n**     (4) Delete the temporary file\n**\n** If the EDITOR argument is omitted, use the value in the VISUAL\n** environment variable.  If still there is no EDITOR, through an error.\n**\n** Also throw an error if the EDITOR program returns a non-zero exit code.\n*/\n#ifndef SQLITE_NOHAVE_SYSTEM\nstatic void editFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  const char *zEditor;\n  char *zTempFile = 0;\n  sqlite3 *db;\n  char *zCmd = 0;\n  int bBin;\n  int rc;\n  int hasCRNL = 0;\n  FILE *f = 0;\n  sqlite3_int64 sz;\n  sqlite3_int64 x;\n  unsigned char *p = 0;\n\n  if( argc==2 ){\n    zEditor = (const char*)sqlite3_value_text(argv[1]);\n  }else{\n    zEditor = getenv(\"VISUAL\");\n  }\n  if( zEditor==0 ){\n    sqlite3_result_error(context, \"no editor for edit()\", -1);\n    return;\n  }\n  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){\n    sqlite3_result_error(context, \"NULL input to edit()\", -1);\n    return;\n  }\n  db = sqlite3_context_db_handle(context);\n  zTempFile = 0;\n  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);\n  if( zTempFile==0 ){\n    sqlite3_uint64 r = 0;\n    sqlite3_randomness(sizeof(r), &r);\n    zTempFile = sqlite3_mprintf(\"temp%llx\", r);\n    if( zTempFile==0 ){\n      sqlite3_result_error_nomem(context);\n      return;\n    }\n  }\n  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;\n  /* When writing the file to be edited, do \\n to \\r\\n conversions on systems\n  ** that want \\r\\n line endings */\n  f = fopen(zTempFile, bBin ? \"wb\" : \"w\");\n  if( f==0 ){\n    sqlite3_result_error(context, \"edit() cannot open temp file\", -1);\n    goto edit_func_end;\n  }\n  sz = sqlite3_value_bytes(argv[0]);\n  if( bBin ){\n    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);\n  }else{\n    const char *z = (const char*)sqlite3_value_text(argv[0]);\n    /* Remember whether or not the value originally contained \\r\\n */\n    if( z && strstr(z,\"\\r\\n\")!=0 ) hasCRNL = 1;\n    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);\n  }\n  fclose(f);\n  f = 0;\n  if( x!=sz ){\n    sqlite3_result_error(context, \"edit() could not write the whole file\", -1);\n    goto edit_func_end;\n  }\n  zCmd = sqlite3_mprintf(\"%s \\\"%s\\\"\", zEditor, zTempFile);\n  if( zCmd==0 ){\n    sqlite3_result_error_nomem(context);\n    goto edit_func_end;\n  }\n  rc = system(zCmd);\n  sqlite3_free(zCmd);\n  if( rc ){\n    sqlite3_result_error(context, \"EDITOR returned non-zero\", -1);\n    goto edit_func_end;\n  }\n  f = fopen(zTempFile, \"rb\");\n  if( f==0 ){\n    sqlite3_result_error(context,\n      \"edit() cannot reopen temp file after edit\", -1);\n    goto edit_func_end;\n  }\n  fseek(f, 0, SEEK_END);\n  sz = ftell(f);\n  rewind(f);\n  p = sqlite3_malloc64( sz+1 );\n  if( p==0 ){\n    sqlite3_result_error_nomem(context);\n    goto edit_func_end;\n  }\n  x = fread(p, 1, (size_t)sz, f);\n  fclose(f);\n  f = 0;\n  if( x!=sz ){\n    sqlite3_result_error(context, \"could not read back the whole file\", -1);\n    goto edit_func_end;\n  }\n  if( bBin ){\n    sqlite3_result_blob64(context, p, sz, sqlite3_free);\n  }else{\n    sqlite3_int64 i, j;\n    if( hasCRNL ){\n      /* If the original contains \\r\\n then do no conversions back to \\n */\n      j = sz;\n    }else{\n      /* If the file did not originally contain \\r\\n then convert any new\n      ** \\r\\n back into \\n */\n      for(i=j=0; i<sz; i++){\n        if( p[i]=='\\r' && p[i+1]=='\\n' ) i++;\n        p[j++] = p[i];\n      }\n      sz = j;\n      p[sz] = 0;\n    } \n    sqlite3_result_text64(context, (const char*)p, sz,\n                          sqlite3_free, SQLITE_UTF8);\n  }\n  p = 0;\n\nedit_func_end:\n  if( f ) fclose(f);\n  unlink(zTempFile);\n  sqlite3_free(zTempFile);\n  sqlite3_free(p);\n}\n#endif /* SQLITE_NOHAVE_SYSTEM */\n\n/*\n** Save or restore the current output mode\n*/\nstatic void outputModePush(ShellState *p){\n  p->modePrior = p->mode;\n  p->priorShFlgs = p->shellFlgs;\n  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));\n  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));\n}\nstatic void outputModePop(ShellState *p){\n  p->mode = p->modePrior;\n  p->shellFlgs = p->priorShFlgs;\n  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));\n  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));\n}\n\n/*\n** Output the given string as a hex-encoded blob (eg. X'1234' )\n*/\nstatic void output_hex_blob(FILE *out, const void *pBlob, int nBlob){\n  int i;\n  char *zBlob = (char *)pBlob;\n  raw_printf(out,\"X'\");\n  for(i=0; i<nBlob; i++){ raw_printf(out,\"%02x\",zBlob[i]&0xff); }\n  raw_printf(out,\"'\");\n}\n\n/*\n** Find a string that is not found anywhere in z[].  Return a pointer\n** to that string.\n**\n** Try to use zA and zB first.  If both of those are already found in z[]\n** then make up some string and store it in the buffer zBuf.\n*/\nstatic const char *unused_string(\n  const char *z,                    /* Result must not appear anywhere in z */\n  const char *zA, const char *zB,   /* Try these first */\n  char *zBuf                        /* Space to store a generated string */\n){\n  unsigned i = 0;\n  if( strstr(z, zA)==0 ) return zA;\n  if( strstr(z, zB)==0 ) return zB;\n  do{\n    sqlite3_snprintf(20,zBuf,\"(%s%u)\", zA, i++);\n  }while( strstr(z,zBuf)!=0 );\n  return zBuf;\n}\n\n/*\n** Output the given string as a quoted string using SQL quoting conventions.\n**\n** See also: output_quoted_escaped_string()\n*/\nstatic void output_quoted_string(FILE *out, const char *z){\n  int i;\n  char c;\n  setBinaryMode(out, 1);\n  for(i=0; (c = z[i])!=0 && c!='\\''; i++){}\n  if( c==0 ){\n    utf8_printf(out,\"'%s'\",z);\n  }else{\n    raw_printf(out, \"'\");\n    while( *z ){\n      for(i=0; (c = z[i])!=0 && c!='\\''; i++){}\n      if( c=='\\'' ) i++;\n      if( i ){\n        utf8_printf(out, \"%.*s\", i, z);\n        z += i;\n      }\n      if( c=='\\'' ){\n        raw_printf(out, \"'\");\n        continue;\n      }\n      if( c==0 ){\n        break;\n      }\n      z++;\n    }\n    raw_printf(out, \"'\");\n  }\n  setTextMode(out, 1);\n}\n\n/*\n** Output the given string as a quoted string using SQL quoting conventions.\n** Additionallly , escape the \"\\n\" and \"\\r\" characters so that they do not\n** get corrupted by end-of-line translation facilities in some operating\n** systems.\n**\n** This is like output_quoted_string() but with the addition of the \\r\\n\n** escape mechanism.\n*/\nstatic void output_quoted_escaped_string(FILE *out, const char *z){\n  int i;\n  char c;\n  setBinaryMode(out, 1);\n  for(i=0; (c = z[i])!=0 && c!='\\'' && c!='\\n' && c!='\\r'; i++){}\n  if( c==0 ){\n    utf8_printf(out,\"'%s'\",z);\n  }else{\n    const char *zNL = 0;\n    const char *zCR = 0;\n    int nNL = 0;\n    int nCR = 0;\n    char zBuf1[20], zBuf2[20];\n    for(i=0; z[i]; i++){\n      if( z[i]=='\\n' ) nNL++;\n      if( z[i]=='\\r' ) nCR++;\n    }\n    if( nNL ){\n      raw_printf(out, \"replace(\");\n      zNL = unused_string(z, \"\\\\n\", \"\\\\012\", zBuf1);\n    }\n    if( nCR ){\n      raw_printf(out, \"replace(\");\n      zCR = unused_string(z, \"\\\\r\", \"\\\\015\", zBuf2);\n    }\n    raw_printf(out, \"'\");\n    while( *z ){\n      for(i=0; (c = z[i])!=0 && c!='\\n' && c!='\\r' && c!='\\''; i++){}\n      if( c=='\\'' ) i++;\n      if( i ){\n        utf8_printf(out, \"%.*s\", i, z);\n        z += i;\n      }\n      if( c=='\\'' ){\n        raw_printf(out, \"'\");\n        continue;\n      }\n      if( c==0 ){\n        break;\n      }\n      z++;\n      if( c=='\\n' ){\n        raw_printf(out, \"%s\", zNL);\n        continue;\n      }\n      raw_printf(out, \"%s\", zCR);\n    }\n    raw_printf(out, \"'\");\n    if( nCR ){\n      raw_printf(out, \",'%s',char(13))\", zCR);\n    }\n    if( nNL ){\n      raw_printf(out, \",'%s',char(10))\", zNL);\n    }\n  }\n  setTextMode(out, 1);\n}\n\n/*\n** Output the given string as a quoted according to C or TCL quoting rules.\n*/\nstatic void output_c_string(FILE *out, const char *z){\n  unsigned int c;\n  fputc('\"', out);\n  while( (c = *(z++))!=0 ){\n    if( c=='\\\\' ){\n      fputc(c, out);\n      fputc(c, out);\n    }else if( c=='\"' ){\n      fputc('\\\\', out);\n      fputc('\"', out);\n    }else if( c=='\\t' ){\n      fputc('\\\\', out);\n      fputc('t', out);\n    }else if( c=='\\n' ){\n      fputc('\\\\', out);\n      fputc('n', out);\n    }else if( c=='\\r' ){\n      fputc('\\\\', out);\n      fputc('r', out);\n    }else if( !isprint(c&0xff) ){\n      raw_printf(out, \"\\\\%03o\", c&0xff);\n    }else{\n      fputc(c, out);\n    }\n  }\n  fputc('\"', out);\n}\n\n/*\n** Output the given string with characters that are special to\n** HTML escaped.\n*/\nstatic void output_html_string(FILE *out, const char *z){\n  int i;\n  if( z==0 ) z = \"\";\n  while( *z ){\n    for(i=0;   z[i]\n            && z[i]!='<'\n            && z[i]!='&'\n            && z[i]!='>'\n            && z[i]!='\\\"'\n            && z[i]!='\\'';\n        i++){}\n    if( i>0 ){\n      utf8_printf(out,\"%.*s\",i,z);\n    }\n    if( z[i]=='<' ){\n      raw_printf(out,\"&lt;\");\n    }else if( z[i]=='&' ){\n      raw_printf(out,\"&amp;\");\n    }else if( z[i]=='>' ){\n      raw_printf(out,\"&gt;\");\n    }else if( z[i]=='\\\"' ){\n      raw_printf(out,\"&quot;\");\n    }else if( z[i]=='\\'' ){\n      raw_printf(out,\"&#39;\");\n    }else{\n      break;\n    }\n    z += i + 1;\n  }\n}\n\n/*\n** If a field contains any character identified by a 1 in the following\n** array, then the string must be quoted for CSV.\n*/\nstatic const char needCsvQuote[] = {\n  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,\n  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,\n  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,\n  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,\n  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,\n  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,\n  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,\n  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,\n  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,\n  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,\n  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,\n};\n\n/*\n** Output a single term of CSV.  Actually, p->colSeparator is used for\n** the separator, which may or may not be a comma.  p->nullValue is\n** the null value.  Strings are quoted if necessary.  The separator\n** is only issued if bSep is true.\n*/\nstatic void output_csv(ShellState *p, const char *z, int bSep){\n  FILE *out = p->out;\n  if( z==0 ){\n    utf8_printf(out,\"%s\",p->nullValue);\n  }else{\n    int i;\n    int nSep = strlen30(p->colSeparator);\n    for(i=0; z[i]; i++){\n      if( needCsvQuote[((unsigned char*)z)[i]]\n         || (z[i]==p->colSeparator[0] &&\n             (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){\n        i = 0;\n        break;\n      }\n    }\n    if( i==0 ){\n      char *zQuoted = sqlite3_mprintf(\"\\\"%w\\\"\", z);\n      utf8_printf(out, \"%s\", zQuoted);\n      sqlite3_free(zQuoted);\n    }else{\n      utf8_printf(out, \"%s\", z);\n    }\n  }\n  if( bSep ){\n    utf8_printf(p->out, \"%s\", p->colSeparator);\n  }\n}\n\n/*\n** This routine runs when the user presses Ctrl-C\n*/\nstatic void interrupt_handler(int NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  seenInterrupt++;\n  if( seenInterrupt>2 ) exit(1);\n  if( globalDb ) sqlite3_interrupt(globalDb);\n}\n\n#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)\n/*\n** This routine runs for console events (e.g. Ctrl-C) on Win32\n*/\nstatic BOOL WINAPI ConsoleCtrlHandler(\n  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */\n){\n  if( dwCtrlType==CTRL_C_EVENT ){\n    interrupt_handler(0);\n    return TRUE;\n  }\n  return FALSE;\n}\n#endif\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n/*\n** When the \".auth ON\" is set, the following authorizer callback is\n** invoked.  It always returns SQLITE_OK.\n*/\nstatic int shellAuth(\n  void *pClientData,\n  int op,\n  const char *zA1,\n  const char *zA2,\n  const char *zA3,\n  const char *zA4\n){\n  ShellState *p = (ShellState*)pClientData;\n  static const char *azAction[] = { 0,\n     \"CREATE_INDEX\",         \"CREATE_TABLE\",         \"CREATE_TEMP_INDEX\",\n     \"CREATE_TEMP_TABLE\",    \"CREATE_TEMP_TRIGGER\",  \"CREATE_TEMP_VIEW\",\n     \"CREATE_TRIGGER\",       \"CREATE_VIEW\",          \"DELETE\",\n     \"DROP_INDEX\",           \"DROP_TABLE\",           \"DROP_TEMP_INDEX\",\n     \"DROP_TEMP_TABLE\",      \"DROP_TEMP_TRIGGER\",    \"DROP_TEMP_VIEW\",\n     \"DROP_TRIGGER\",         \"DROP_VIEW\",            \"INSERT\",\n     \"PRAGMA\",               \"READ\",                 \"SELECT\",\n     \"TRANSACTION\",          \"UPDATE\",               \"ATTACH\",\n     \"DETACH\",               \"ALTER_TABLE\",          \"REINDEX\",\n     \"ANALYZE\",              \"CREATE_VTABLE\",        \"DROP_VTABLE\",\n     \"FUNCTION\",             \"SAVEPOINT\",            \"RECURSIVE\"\n  };\n  int i;\n  const char *az[4];\n  az[0] = zA1;\n  az[1] = zA2;\n  az[2] = zA3;\n  az[3] = zA4;\n  utf8_printf(p->out, \"authorizer: %s\", azAction[op]);\n  for(i=0; i<4; i++){\n    raw_printf(p->out, \" \");\n    if( az[i] ){\n      output_c_string(p->out, az[i]);\n    }else{\n      raw_printf(p->out, \"NULL\");\n    }\n  }\n  raw_printf(p->out, \"\\n\");\n  return SQLITE_OK;\n}\n#endif\n\n/*\n** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.\n**\n** This routine converts some CREATE TABLE statements for shadow tables\n** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.\n*/\nstatic void printSchemaLine(FILE *out, const char *z, const char *zTail){\n  if( z==0 ) return;\n  if( zTail==0 ) return;\n  if( sqlite3_strglob(\"CREATE TABLE ['\\\"]*\", z)==0 ){\n    utf8_printf(out, \"CREATE TABLE IF NOT EXISTS %s%s\", z+13, zTail);\n  }else{\n    utf8_printf(out, \"%s%s\", z, zTail);\n  }\n}\nstatic void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){\n  char c = z[n];\n  z[n] = 0;\n  printSchemaLine(out, z, zTail);\n  z[n] = c;\n}\n\n/*\n** Return true if string z[] has nothing but whitespace and comments to the\n** end of the first line.\n*/\nstatic int wsToEol(const char *z){\n  int i;\n  for(i=0; z[i]; i++){\n    if( z[i]=='\\n' ) return 1;\n    if( IsSpace(z[i]) ) continue;\n    if( z[i]=='-' && z[i+1]=='-' ) return 1;\n    return 0;\n  }\n  return 1;\n}\n\n/*\n** Add a new entry to the EXPLAIN QUERY PLAN data\n*/\nstatic void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){\n  EQPGraphRow *pNew;\n  int nText = strlen30(zText);\n  if( p->autoEQPtest ){\n    utf8_printf(p->out, \"%d,%d,%s\\n\", iEqpId, p2, zText);\n  }\n  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );\n  if( pNew==0 ) shell_out_of_memory();\n  pNew->iEqpId = iEqpId;\n  pNew->iParentId = p2;\n  memcpy(pNew->zText, zText, nText+1);\n  pNew->pNext = 0;\n  if( p->sGraph.pLast ){\n    p->sGraph.pLast->pNext = pNew;\n  }else{\n    p->sGraph.pRow = pNew;\n  }\n  p->sGraph.pLast = pNew;\n}\n\n/*\n** Free and reset the EXPLAIN QUERY PLAN data that has been collected\n** in p->sGraph.\n*/\nstatic void eqp_reset(ShellState *p){\n  EQPGraphRow *pRow, *pNext;\n  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){\n    pNext = pRow->pNext;\n    sqlite3_free(pRow);\n  }\n  memset(&p->sGraph, 0, sizeof(p->sGraph));\n}\n\n/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after\n** pOld, or return the first such line if pOld is NULL\n*/\nstatic EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){\n  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;\n  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;\n  return pRow;\n}\n\n/* Render a single level of the graph that has iEqpId as its parent.  Called\n** recursively to render sublevels.\n*/\nstatic void eqp_render_level(ShellState *p, int iEqpId){\n  EQPGraphRow *pRow, *pNext;\n  int n = strlen30(p->sGraph.zPrefix);\n  char *z;\n  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){\n    pNext = eqp_next_row(p, iEqpId, pRow);\n    z = pRow->zText;\n    utf8_printf(p->out, \"%s%s%s\\n\", p->sGraph.zPrefix,\n                pNext ? \"|--\" : \"`--\", z);\n    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){\n      memcpy(&p->sGraph.zPrefix[n], pNext ? \"|  \" : \"   \", 4);\n      eqp_render_level(p, pRow->iEqpId);\n      p->sGraph.zPrefix[n] = 0;\n    }\n  }\n}\n\n/*\n** Display and reset the EXPLAIN QUERY PLAN data\n*/\nstatic void eqp_render(ShellState *p){\n  EQPGraphRow *pRow = p->sGraph.pRow;\n  if( pRow ){\n    if( pRow->zText[0]=='-' ){\n      if( pRow->pNext==0 ){\n        eqp_reset(p);\n        return;\n      }\n      utf8_printf(p->out, \"%s\\n\", pRow->zText+3);\n      p->sGraph.pRow = pRow->pNext;\n      sqlite3_free(pRow);\n    }else{\n      utf8_printf(p->out, \"QUERY PLAN\\n\");\n    }\n    p->sGraph.zPrefix[0] = 0;\n    eqp_render_level(p, 0);\n    eqp_reset(p);\n  }\n}\n\n#ifndef SQLITE_OMIT_PROGRESS_CALLBACK\n/*\n** Progress handler callback.\n*/\nstatic int progress_handler(void *pClientData) {\n  ShellState *p = (ShellState*)pClientData;\n  p->nProgress++;\n  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){\n    raw_printf(p->out, \"Progress limit reached (%u)\\n\", p->nProgress);\n    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;\n    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;\n    return 1;\n  }\n  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){\n    raw_printf(p->out, \"Progress %u\\n\", p->nProgress);\n  }\n  return 0;\n}\n#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */\n\n/*\n** This is the callback routine that the shell\n** invokes for each row of a query result.\n*/\nstatic int shell_callback(\n  void *pArg,\n  int nArg,        /* Number of result columns */\n  char **azArg,    /* Text of each result column */\n  char **azCol,    /* Column names */\n  int *aiType      /* Column types */\n){\n  int i;\n  ShellState *p = (ShellState*)pArg;\n\n  if( azArg==0 ) return 0;\n  switch( p->cMode ){\n    case MODE_Line: {\n      int w = 5;\n      if( azArg==0 ) break;\n      for(i=0; i<nArg; i++){\n        int len = strlen30(azCol[i] ? azCol[i] : \"\");\n        if( len>w ) w = len;\n      }\n      if( p->cnt++>0 ) utf8_printf(p->out, \"%s\", p->rowSeparator);\n      for(i=0; i<nArg; i++){\n        utf8_printf(p->out,\"%*s = %s%s\", w, azCol[i],\n                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);\n      }\n      break;\n    }\n    case MODE_Explain:\n    case MODE_Column: {\n      static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};\n      const int *colWidth;\n      int showHdr;\n      char *rowSep;\n      int nWidth;\n      if( p->cMode==MODE_Column ){\n        colWidth = p->colWidth;\n        nWidth = ArraySize(p->colWidth);\n        showHdr = p->showHeader;\n        rowSep = p->rowSeparator;\n      }else{\n        colWidth = aExplainWidths;\n        nWidth = ArraySize(aExplainWidths);\n        showHdr = 1;\n        rowSep = SEP_Row;\n      }\n      if( p->cnt++==0 ){\n        for(i=0; i<nArg; i++){\n          int w, n;\n          if( i<nWidth ){\n            w = colWidth[i];\n          }else{\n            w = 0;\n          }\n          if( w==0 ){\n            w = strlenChar(azCol[i] ? azCol[i] : \"\");\n            if( w<10 ) w = 10;\n            n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);\n            if( w<n ) w = n;\n          }\n          if( i<ArraySize(p->actualWidth) ){\n            p->actualWidth[i] = w;\n          }\n          if( showHdr ){\n            utf8_width_print(p->out, w, azCol[i]);\n            utf8_printf(p->out, \"%s\", i==nArg-1 ? rowSep : \"  \");\n          }\n        }\n        if( showHdr ){\n          for(i=0; i<nArg; i++){\n            int w;\n            if( i<ArraySize(p->actualWidth) ){\n               w = p->actualWidth[i];\n               if( w<0 ) w = -w;\n            }else{\n               w = 10;\n            }\n            utf8_printf(p->out,\"%-*.*s%s\",w,w,\n                   \"----------------------------------------------------------\"\n                   \"----------------------------------------------------------\",\n                    i==nArg-1 ? rowSep : \"  \");\n          }\n        }\n      }\n      if( azArg==0 ) break;\n      for(i=0; i<nArg; i++){\n        int w;\n        if( i<ArraySize(p->actualWidth) ){\n           w = p->actualWidth[i];\n        }else{\n           w = 10;\n        }\n        if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){\n          w = strlenChar(azArg[i]);\n        }\n        if( i==1 && p->aiIndent && p->pStmt ){\n          if( p->iIndent<p->nIndent ){\n            utf8_printf(p->out, \"%*.s\", p->aiIndent[p->iIndent], \"\");\n          }\n          p->iIndent++;\n        }\n        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);\n        utf8_printf(p->out, \"%s\", i==nArg-1 ? rowSep : \"  \");\n      }\n      break;\n    }\n    case MODE_Semi: {   /* .schema and .fullschema output */\n      printSchemaLine(p->out, azArg[0], \";\\n\");\n      break;\n    }\n    case MODE_Pretty: {  /* .schema and .fullschema with --indent */\n      char *z;\n      int j;\n      int nParen = 0;\n      char cEnd = 0;\n      char c;\n      int nLine = 0;\n      assert( nArg==1 );\n      if( azArg[0]==0 ) break;\n      if( sqlite3_strlike(\"CREATE VIEW%\", azArg[0], 0)==0\n       || sqlite3_strlike(\"CREATE TRIG%\", azArg[0], 0)==0\n      ){\n        utf8_printf(p->out, \"%s;\\n\", azArg[0]);\n        break;\n      }\n      z = sqlite3_mprintf(\"%s\", azArg[0]);\n      j = 0;\n      for(i=0; IsSpace(z[i]); i++){}\n      for(; (c = z[i])!=0; i++){\n        if( IsSpace(c) ){\n          if( z[j-1]=='\\r' ) z[j-1] = '\\n';\n          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;\n        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){\n          j--;\n        }\n        z[j++] = c;\n      }\n      while( j>0 && IsSpace(z[j-1]) ){ j--; }\n      z[j] = 0;\n      if( strlen30(z)>=79 ){\n        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */\n          if( c==cEnd ){\n            cEnd = 0;\n          }else if( c=='\"' || c=='\\'' || c=='`' ){\n            cEnd = c;\n          }else if( c=='[' ){\n            cEnd = ']';\n          }else if( c=='-' && z[i+1]=='-' ){\n            cEnd = '\\n';\n          }else if( c=='(' ){\n            nParen++;\n          }else if( c==')' ){\n            nParen--;\n            if( nLine>0 && nParen==0 && j>0 ){\n              printSchemaLineN(p->out, z, j, \"\\n\");\n              j = 0;\n            }\n          }\n          z[j++] = c;\n          if( nParen==1 && cEnd==0\n           && (c=='(' || c=='\\n' || (c==',' && !wsToEol(z+i+1)))\n          ){\n            if( c=='\\n' ) j--;\n            printSchemaLineN(p->out, z, j, \"\\n  \");\n            j = 0;\n            nLine++;\n            while( IsSpace(z[i+1]) ){ i++; }\n          }\n        }\n        z[j] = 0;\n      }\n      printSchemaLine(p->out, z, \";\\n\");\n      sqlite3_free(z);\n      break;\n    }\n    case MODE_List: {\n      if( p->cnt++==0 && p->showHeader ){\n        for(i=0; i<nArg; i++){\n          utf8_printf(p->out,\"%s%s\",azCol[i],\n                  i==nArg-1 ? p->rowSeparator : p->colSeparator);\n        }\n      }\n      if( azArg==0 ) break;\n      for(i=0; i<nArg; i++){\n        char *z = azArg[i];\n        if( z==0 ) z = p->nullValue;\n        utf8_printf(p->out, \"%s\", z);\n        if( i<nArg-1 ){\n          utf8_printf(p->out, \"%s\", p->colSeparator);\n        }else{\n          utf8_printf(p->out, \"%s\", p->rowSeparator);\n        }\n      }\n      break;\n    }\n    case MODE_Html: {\n      if( p->cnt++==0 && p->showHeader ){\n        raw_printf(p->out,\"<TR>\");\n        for(i=0; i<nArg; i++){\n          raw_printf(p->out,\"<TH>\");\n          output_html_string(p->out, azCol[i]);\n          raw_printf(p->out,\"</TH>\\n\");\n        }\n        raw_printf(p->out,\"</TR>\\n\");\n      }\n      if( azArg==0 ) break;\n      raw_printf(p->out,\"<TR>\");\n      for(i=0; i<nArg; i++){\n        raw_printf(p->out,\"<TD>\");\n        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);\n        raw_printf(p->out,\"</TD>\\n\");\n      }\n      raw_printf(p->out,\"</TR>\\n\");\n      break;\n    }\n    case MODE_Tcl: {\n      if( p->cnt++==0 && p->showHeader ){\n        for(i=0; i<nArg; i++){\n          output_c_string(p->out,azCol[i] ? azCol[i] : \"\");\n          if(i<nArg-1) utf8_printf(p->out, \"%s\", p->colSeparator);\n        }\n        utf8_printf(p->out, \"%s\", p->rowSeparator);\n      }\n      if( azArg==0 ) break;\n      for(i=0; i<nArg; i++){\n        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);\n        if(i<nArg-1) utf8_printf(p->out, \"%s\", p->colSeparator);\n      }\n      utf8_printf(p->out, \"%s\", p->rowSeparator);\n      break;\n    }\n    case MODE_Csv: {\n      setBinaryMode(p->out, 1);\n      if( p->cnt++==0 && p->showHeader ){\n        for(i=0; i<nArg; i++){\n          output_csv(p, azCol[i] ? azCol[i] : \"\", i<nArg-1);\n        }\n        utf8_printf(p->out, \"%s\", p->rowSeparator);\n      }\n      if( nArg>0 ){\n        for(i=0; i<nArg; i++){\n          output_csv(p, azArg[i], i<nArg-1);\n        }\n        utf8_printf(p->out, \"%s\", p->rowSeparator);\n      }\n      setTextMode(p->out, 1);\n      break;\n    }\n    case MODE_Insert: {\n      if( azArg==0 ) break;\n      utf8_printf(p->out,\"INSERT INTO %s\",p->zDestTable);\n      if( p->showHeader ){\n        raw_printf(p->out,\"(\");\n        for(i=0; i<nArg; i++){\n          if( i>0 ) raw_printf(p->out, \",\");\n          if( quoteChar(azCol[i]) ){\n            char *z = sqlite3_mprintf(\"\\\"%w\\\"\", azCol[i]);\n            utf8_printf(p->out, \"%s\", z);\n            sqlite3_free(z);\n          }else{\n            raw_printf(p->out, \"%s\", azCol[i]);\n          }\n        }\n        raw_printf(p->out,\")\");\n      }\n      p->cnt++;\n      for(i=0; i<nArg; i++){\n        raw_printf(p->out, i>0 ? \",\" : \" VALUES(\");\n        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){\n          utf8_printf(p->out,\"NULL\");\n        }else if( aiType && aiType[i]==SQLITE_TEXT ){\n          if( ShellHasFlag(p, SHFLG_Newlines) ){\n            output_quoted_string(p->out, azArg[i]);\n          }else{\n            output_quoted_escaped_string(p->out, azArg[i]);\n          }\n        }else if( aiType && aiType[i]==SQLITE_INTEGER ){\n          utf8_printf(p->out,\"%s\", azArg[i]);\n        }else if( aiType && aiType[i]==SQLITE_FLOAT ){\n          char z[50];\n          double r = sqlite3_column_double(p->pStmt, i);\n          sqlite3_uint64 ur;\n          memcpy(&ur,&r,sizeof(r));\n          if( ur==0x7ff0000000000000LL ){\n            raw_printf(p->out, \"1e999\");\n          }else if( ur==0xfff0000000000000LL ){\n            raw_printf(p->out, \"-1e999\");\n          }else{\n            sqlite3_snprintf(50,z,\"%!.20g\", r);\n            raw_printf(p->out, \"%s\", z);\n          }\n        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){\n          const void *pBlob = sqlite3_column_blob(p->pStmt, i);\n          int nBlob = sqlite3_column_bytes(p->pStmt, i);\n          output_hex_blob(p->out, pBlob, nBlob);\n        }else if( isNumber(azArg[i], 0) ){\n          utf8_printf(p->out,\"%s\", azArg[i]);\n        }else if( ShellHasFlag(p, SHFLG_Newlines) ){\n          output_quoted_string(p->out, azArg[i]);\n        }else{\n          output_quoted_escaped_string(p->out, azArg[i]);\n        }\n      }\n      raw_printf(p->out,\");\\n\");\n      break;\n    }\n    case MODE_Quote: {\n      if( azArg==0 ) break;\n      if( p->cnt==0 && p->showHeader ){\n        for(i=0; i<nArg; i++){\n          if( i>0 ) raw_printf(p->out, \",\");\n          output_quoted_string(p->out, azCol[i]);\n        }\n        raw_printf(p->out,\"\\n\");\n      }\n      p->cnt++;\n      for(i=0; i<nArg; i++){\n        if( i>0 ) raw_printf(p->out, \",\");\n        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){\n          utf8_printf(p->out,\"NULL\");\n        }else if( aiType && aiType[i]==SQLITE_TEXT ){\n          output_quoted_string(p->out, azArg[i]);\n        }else if( aiType && aiType[i]==SQLITE_INTEGER ){\n          utf8_printf(p->out,\"%s\", azArg[i]);\n        }else if( aiType && aiType[i]==SQLITE_FLOAT ){\n          char z[50];\n          double r = sqlite3_column_double(p->pStmt, i);\n          sqlite3_snprintf(50,z,\"%!.20g\", r);\n          raw_printf(p->out, \"%s\", z);\n        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){\n          const void *pBlob = sqlite3_column_blob(p->pStmt, i);\n          int nBlob = sqlite3_column_bytes(p->pStmt, i);\n          output_hex_blob(p->out, pBlob, nBlob);\n        }else if( isNumber(azArg[i], 0) ){\n          utf8_printf(p->out,\"%s\", azArg[i]);\n        }else{\n          output_quoted_string(p->out, azArg[i]);\n        }\n      }\n      raw_printf(p->out,\"\\n\");\n      break;\n    }\n    case MODE_Ascii: {\n      if( p->cnt++==0 && p->showHeader ){\n        for(i=0; i<nArg; i++){\n          if( i>0 ) utf8_printf(p->out, \"%s\", p->colSeparator);\n          utf8_printf(p->out,\"%s\",azCol[i] ? azCol[i] : \"\");\n        }\n        utf8_printf(p->out, \"%s\", p->rowSeparator);\n      }\n      if( azArg==0 ) break;\n      for(i=0; i<nArg; i++){\n        if( i>0 ) utf8_printf(p->out, \"%s\", p->colSeparator);\n        utf8_printf(p->out,\"%s\",azArg[i] ? azArg[i] : p->nullValue);\n      }\n      utf8_printf(p->out, \"%s\", p->rowSeparator);\n      break;\n    }\n    case MODE_EQP: {\n      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);\n      break;\n    }\n  }\n  return 0;\n}\n\n/*\n** This is the callback routine that the SQLite library\n** invokes for each row of a query result.\n*/\nstatic int callback(void *pArg, int nArg, char **azArg, char **azCol){\n  /* since we don't have type info, call the shell_callback with a NULL value */\n  return shell_callback(pArg, nArg, azArg, azCol, NULL);\n}\n\n/*\n** This is the callback routine from sqlite3_exec() that appends all\n** output onto the end of a ShellText object.\n*/\nstatic int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){\n  ShellText *p = (ShellText*)pArg;\n  int i;\n  UNUSED_PARAMETER(az);\n  if( azArg==0 ) return 0;\n  if( p->n ) appendText(p, \"|\", 0);\n  for(i=0; i<nArg; i++){\n    if( i ) appendText(p, \",\", 0);\n    if( azArg[i] ) appendText(p, azArg[i], 0);\n  }\n  return 0;\n}\n\n/*\n** Generate an appropriate SELFTEST table in the main database.\n*/\nstatic void createSelftestTable(ShellState *p){\n  char *zErrMsg = 0;\n  sqlite3_exec(p->db,\n    \"SAVEPOINT selftest_init;\\n\"\n    \"CREATE TABLE IF NOT EXISTS selftest(\\n\"\n    \"  tno INTEGER PRIMARY KEY,\\n\"   /* Test number */\n    \"  op TEXT,\\n\"                   /* Operator:  memo run */\n    \"  cmd TEXT,\\n\"                  /* Command text */\n    \"  ans TEXT\\n\"                   /* Desired answer */\n    \");\"\n    \"CREATE TEMP TABLE [_shell$self](op,cmd,ans);\\n\"\n    \"INSERT INTO [_shell$self](rowid,op,cmd)\\n\"\n    \"  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\\n\"\n    \"         'memo','Tests generated by --init');\\n\"\n    \"INSERT INTO [_shell$self]\\n\"\n    \"  SELECT 'run',\\n\"\n    \"    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql \"\n                                 \"FROM sqlite_master ORDER BY 2'',224))',\\n\"\n    \"    hex(sha3_query('SELECT type,name,tbl_name,sql \"\n                          \"FROM sqlite_master ORDER BY 2',224));\\n\"\n    \"INSERT INTO [_shell$self]\\n\"\n    \"  SELECT 'run',\"\n    \"    'SELECT hex(sha3_query(''SELECT * FROM \\\"' ||\"\n    \"        printf('%w',name) || '\\\" NOT INDEXED'',224))',\\n\"\n    \"    hex(sha3_query(printf('SELECT * FROM \\\"%w\\\" NOT INDEXED',name),224))\\n\"\n    \"  FROM (\\n\"\n    \"    SELECT name FROM sqlite_master\\n\"\n    \"     WHERE type='table'\\n\"\n    \"       AND name<>'selftest'\\n\"\n    \"       AND coalesce(rootpage,0)>0\\n\"\n    \"  )\\n\"\n    \" ORDER BY name;\\n\"\n    \"INSERT INTO [_shell$self]\\n\"\n    \"  VALUES('run','PRAGMA integrity_check','ok');\\n\"\n    \"INSERT INTO selftest(tno,op,cmd,ans)\"\n    \"  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\\n\"\n    \"DROP TABLE [_shell$self];\"\n    ,0,0,&zErrMsg);\n  if( zErrMsg ){\n    utf8_printf(stderr, \"SELFTEST initialization failure: %s\\n\", zErrMsg);\n    sqlite3_free(zErrMsg);\n  }\n  sqlite3_exec(p->db, \"RELEASE selftest_init\",0,0,0);\n}\n\n\n/*\n** Set the destination table field of the ShellState structure to\n** the name of the table given.  Escape any quote characters in the\n** table name.\n*/\nstatic void set_table_name(ShellState *p, const char *zName){\n  int i, n;\n  char cQuote;\n  char *z;\n\n  if( p->zDestTable ){\n    free(p->zDestTable);\n    p->zDestTable = 0;\n  }\n  if( zName==0 ) return;\n  cQuote = quoteChar(zName);\n  n = strlen30(zName);\n  if( cQuote ) n += n+2;\n  z = p->zDestTable = malloc( n+1 );\n  if( z==0 ) shell_out_of_memory();\n  n = 0;\n  if( cQuote ) z[n++] = cQuote;\n  for(i=0; zName[i]; i++){\n    z[n++] = zName[i];\n    if( zName[i]==cQuote ) z[n++] = cQuote;\n  }\n  if( cQuote ) z[n++] = cQuote;\n  z[n] = 0;\n}\n\n\n/*\n** Execute a query statement that will generate SQL output.  Print\n** the result columns, comma-separated, on a line and then add a\n** semicolon terminator to the end of that line.\n**\n** If the number of columns is 1 and that column contains text \"--\"\n** then write the semicolon on a separate line.  That way, if a\n** \"--\" comment occurs at the end of the statement, the comment\n** won't consume the semicolon terminator.\n*/\nstatic int run_table_dump_query(\n  ShellState *p,           /* Query context */\n  const char *zSelect      /* SELECT statement to extract content */\n){\n  sqlite3_stmt *pSelect;\n  int rc;\n  int nResult;\n  int i;\n  const char *z;\n  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);\n  if( rc!=SQLITE_OK || !pSelect ){\n    utf8_printf(p->out, \"/**** ERROR: (%d) %s *****/\\n\", rc,\n                sqlite3_errmsg(p->db));\n    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;\n    return rc;\n  }\n  rc = sqlite3_step(pSelect);\n  nResult = sqlite3_column_count(pSelect);\n  while( rc==SQLITE_ROW ){\n    z = (const char*)sqlite3_column_text(pSelect, 0);\n    utf8_printf(p->out, \"%s\", z);\n    for(i=1; i<nResult; i++){\n      utf8_printf(p->out, \",%s\", sqlite3_column_text(pSelect, i));\n    }\n    if( z==0 ) z = \"\";\n    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;\n    if( z[0] ){\n      raw_printf(p->out, \"\\n;\\n\");\n    }else{\n      raw_printf(p->out, \";\\n\");\n    }\n    rc = sqlite3_step(pSelect);\n  }\n  rc = sqlite3_finalize(pSelect);\n  if( rc!=SQLITE_OK ){\n    utf8_printf(p->out, \"/**** ERROR: (%d) %s *****/\\n\", rc,\n                sqlite3_errmsg(p->db));\n    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;\n  }\n  return rc;\n}\n\n/*\n** Allocate space and save off current error string.\n*/\nstatic char *save_err_msg(\n  sqlite3 *db            /* Database to query */\n){\n  int nErrMsg = 1+strlen30(sqlite3_errmsg(db));\n  char *zErrMsg = sqlite3_malloc64(nErrMsg);\n  if( zErrMsg ){\n    memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);\n  }\n  return zErrMsg;\n}\n\n#ifdef __linux__\n/*\n** Attempt to display I/O stats on Linux using /proc/PID/io\n*/\nstatic void displayLinuxIoStats(FILE *out){\n  FILE *in;\n  char z[200];\n  sqlite3_snprintf(sizeof(z), z, \"/proc/%d/io\", getpid());\n  in = fopen(z, \"rb\");\n  if( in==0 ) return;\n  while( fgets(z, sizeof(z), in)!=0 ){\n    static const struct {\n      const char *zPattern;\n      const char *zDesc;\n    } aTrans[] = {\n      { \"rchar: \",                  \"Bytes received by read():\" },\n      { \"wchar: \",                  \"Bytes sent to write():\"    },\n      { \"syscr: \",                  \"Read() system calls:\"      },\n      { \"syscw: \",                  \"Write() system calls:\"     },\n      { \"read_bytes: \",             \"Bytes read from storage:\"  },\n      { \"write_bytes: \",            \"Bytes written to storage:\" },\n      { \"cancelled_write_bytes: \",  \"Cancelled write bytes:\"    },\n    };\n    int i;\n    for(i=0; i<ArraySize(aTrans); i++){\n      int n = strlen30(aTrans[i].zPattern);\n      if( strncmp(aTrans[i].zPattern, z, n)==0 ){\n        utf8_printf(out, \"%-36s %s\", aTrans[i].zDesc, &z[n]);\n        break;\n      }\n    }\n  }\n  fclose(in);\n}\n#endif\n\n/*\n** Display a single line of status using 64-bit values.\n*/\nstatic void displayStatLine(\n  ShellState *p,            /* The shell context */\n  char *zLabel,             /* Label for this one line */\n  char *zFormat,            /* Format for the result */\n  int iStatusCtrl,          /* Which status to display */\n  int bReset                /* True to reset the stats */\n){\n  sqlite3_int64 iCur = -1;\n  sqlite3_int64 iHiwtr = -1;\n  int i, nPercent;\n  char zLine[200];\n  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);\n  for(i=0, nPercent=0; zFormat[i]; i++){\n    if( zFormat[i]=='%' ) nPercent++;\n  }\n  if( nPercent>1 ){\n    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);\n  }else{\n    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);\n  }\n  raw_printf(p->out, \"%-36s %s\\n\", zLabel, zLine);\n}\n\n/*\n** Display memory stats.\n*/\nstatic int display_stats(\n  sqlite3 *db,                /* Database to query */\n  ShellState *pArg,           /* Pointer to ShellState */\n  int bReset                  /* True to reset the stats */\n){\n  int iCur;\n  int iHiwtr;\n  FILE *out;\n  if( pArg==0 || pArg->out==0 ) return 0;\n  out = pArg->out;\n\n  if( pArg->pStmt && (pArg->statsOn & 2) ){\n    int nCol, i, x;\n    sqlite3_stmt *pStmt = pArg->pStmt;\n    char z[100];\n    nCol = sqlite3_column_count(pStmt);\n    raw_printf(out, \"%-36s %d\\n\", \"Number of output columns:\", nCol);\n    for(i=0; i<nCol; i++){\n      sqlite3_snprintf(sizeof(z),z,\"Column %d %nname:\", i, &x);\n      utf8_printf(out, \"%-36s %s\\n\", z, sqlite3_column_name(pStmt,i));\n#ifndef SQLITE_OMIT_DECLTYPE\n      sqlite3_snprintf(30, z+x, \"declared type:\");\n      utf8_printf(out, \"%-36s %s\\n\", z, sqlite3_column_decltype(pStmt, i));\n#endif\n#ifdef SQLITE_ENABLE_COLUMN_METADATA\n      sqlite3_snprintf(30, z+x, \"database name:\");\n      utf8_printf(out, \"%-36s %s\\n\", z, sqlite3_column_database_name(pStmt,i));\n      sqlite3_snprintf(30, z+x, \"table name:\");\n      utf8_printf(out, \"%-36s %s\\n\", z, sqlite3_column_table_name(pStmt,i));\n      sqlite3_snprintf(30, z+x, \"origin name:\");\n      utf8_printf(out, \"%-36s %s\\n\", z, sqlite3_column_origin_name(pStmt,i));\n#endif\n    }\n  }\n\n  displayStatLine(pArg, \"Memory Used:\",\n     \"%lld (max %lld) bytes\", SQLITE_STATUS_MEMORY_USED, bReset);\n  displayStatLine(pArg, \"Number of Outstanding Allocations:\",\n     \"%lld (max %lld)\", SQLITE_STATUS_MALLOC_COUNT, bReset);\n  if( pArg->shellFlgs & SHFLG_Pagecache ){\n    displayStatLine(pArg, \"Number of Pcache Pages Used:\",\n       \"%lld (max %lld) pages\", SQLITE_STATUS_PAGECACHE_USED, bReset);\n  }\n  displayStatLine(pArg, \"Number of Pcache Overflow Bytes:\",\n     \"%lld (max %lld) bytes\", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);\n  displayStatLine(pArg, \"Largest Allocation:\",\n     \"%lld bytes\", SQLITE_STATUS_MALLOC_SIZE, bReset);\n  displayStatLine(pArg, \"Largest Pcache Allocation:\",\n     \"%lld bytes\", SQLITE_STATUS_PAGECACHE_SIZE, bReset);\n#ifdef YYTRACKMAXSTACKDEPTH\n  displayStatLine(pArg, \"Deepest Parser Stack:\",\n     \"%lld (max %lld)\", SQLITE_STATUS_PARSER_STACK, bReset);\n#endif\n\n  if( db ){\n    if( pArg->shellFlgs & SHFLG_Lookaside ){\n      iHiwtr = iCur = -1;\n      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,\n                        &iCur, &iHiwtr, bReset);\n      raw_printf(pArg->out,\n              \"Lookaside Slots Used:                %d (max %d)\\n\",\n              iCur, iHiwtr);\n      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,\n                        &iCur, &iHiwtr, bReset);\n      raw_printf(pArg->out, \"Successful lookaside attempts:       %d\\n\",\n              iHiwtr);\n      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,\n                        &iCur, &iHiwtr, bReset);\n      raw_printf(pArg->out, \"Lookaside failures due to size:      %d\\n\",\n              iHiwtr);\n      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,\n                        &iCur, &iHiwtr, bReset);\n      raw_printf(pArg->out, \"Lookaside failures due to OOM:       %d\\n\",\n              iHiwtr);\n    }\n    iHiwtr = iCur = -1;\n    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);\n    raw_printf(pArg->out, \"Pager Heap Usage:                    %d bytes\\n\",\n            iCur);\n    iHiwtr = iCur = -1;\n    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);\n    raw_printf(pArg->out, \"Page cache hits:                     %d\\n\", iCur);\n    iHiwtr = iCur = -1;\n    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);\n    raw_printf(pArg->out, \"Page cache misses:                   %d\\n\", iCur);\n    iHiwtr = iCur = -1;\n    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);\n    raw_printf(pArg->out, \"Page cache writes:                   %d\\n\", iCur);\n    iHiwtr = iCur = -1;\n    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);\n    raw_printf(pArg->out, \"Page cache spills:                   %d\\n\", iCur);\n    iHiwtr = iCur = -1;\n    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);\n    raw_printf(pArg->out, \"Schema Heap Usage:                   %d bytes\\n\",\n            iCur);\n    iHiwtr = iCur = -1;\n    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);\n    raw_printf(pArg->out, \"Statement Heap/Lookaside Usage:      %d bytes\\n\",\n            iCur);\n  }\n\n  if( pArg->pStmt ){\n    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,\n                               bReset);\n    raw_printf(pArg->out, \"Fullscan Steps:                      %d\\n\", iCur);\n    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);\n    raw_printf(pArg->out, \"Sort Operations:                     %d\\n\", iCur);\n    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);\n    raw_printf(pArg->out, \"Autoindex Inserts:                   %d\\n\", iCur);\n    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);\n    raw_printf(pArg->out, \"Virtual Machine Steps:               %d\\n\", iCur);\n    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);\n    raw_printf(pArg->out, \"Reprepare operations:                %d\\n\", iCur);\n    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);\n    raw_printf(pArg->out, \"Number of times run:                 %d\\n\", iCur);\n    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);\n    raw_printf(pArg->out, \"Memory used by prepared stmt:        %d\\n\", iCur);\n  }\n\n#ifdef __linux__\n  displayLinuxIoStats(pArg->out);\n#endif\n\n  /* Do not remove this machine readable comment: extra-stats-output-here */\n\n  return 0;\n}\n\n/*\n** Display scan stats.\n*/\nstatic void display_scanstats(\n  sqlite3 *db,                    /* Database to query */\n  ShellState *pArg                /* Pointer to ShellState */\n){\n#ifndef SQLITE_ENABLE_STMT_SCANSTATUS\n  UNUSED_PARAMETER(db);\n  UNUSED_PARAMETER(pArg);\n#else\n  int i, k, n, mx;\n  raw_printf(pArg->out, \"-------- scanstats --------\\n\");\n  mx = 0;\n  for(k=0; k<=mx; k++){\n    double rEstLoop = 1.0;\n    for(i=n=0; 1; i++){\n      sqlite3_stmt *p = pArg->pStmt;\n      sqlite3_int64 nLoop, nVisit;\n      double rEst;\n      int iSid;\n      const char *zExplain;\n      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){\n        break;\n      }\n      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);\n      if( iSid>mx ) mx = iSid;\n      if( iSid!=k ) continue;\n      if( n==0 ){\n        rEstLoop = (double)nLoop;\n        if( k>0 ) raw_printf(pArg->out, \"-------- subquery %d -------\\n\", k);\n      }\n      n++;\n      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);\n      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);\n      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);\n      utf8_printf(pArg->out, \"Loop %2d: %s\\n\", n, zExplain);\n      rEstLoop *= rEst;\n      raw_printf(pArg->out,\n          \"         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\\n\",\n          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst\n      );\n    }\n  }\n  raw_printf(pArg->out, \"---------------------------\\n\");\n#endif\n}\n\n/*\n** Parameter azArray points to a zero-terminated array of strings. zStr\n** points to a single nul-terminated string. Return non-zero if zStr\n** is equal, according to strcmp(), to any of the strings in the array.\n** Otherwise, return zero.\n*/\nstatic int str_in_array(const char *zStr, const char **azArray){\n  int i;\n  for(i=0; azArray[i]; i++){\n    if( 0==strcmp(zStr, azArray[i]) ) return 1;\n  }\n  return 0;\n}\n\n/*\n** If compiled statement pSql appears to be an EXPLAIN statement, allocate\n** and populate the ShellState.aiIndent[] array with the number of\n** spaces each opcode should be indented before it is output.\n**\n** The indenting rules are:\n**\n**     * For each \"Next\", \"Prev\", \"VNext\" or \"VPrev\" instruction, indent\n**       all opcodes that occur between the p2 jump destination and the opcode\n**       itself by 2 spaces.\n**\n**     * For each \"Goto\", if the jump destination is earlier in the program\n**       and ends on one of:\n**          Yield  SeekGt  SeekLt  RowSetRead  Rewind\n**       or if the P1 parameter is one instead of zero,\n**       then indent all opcodes between the earlier instruction\n**       and \"Goto\" by 2 spaces.\n*/\nstatic void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){\n  const char *zSql;               /* The text of the SQL statement */\n  const char *z;                  /* Used to check if this is an EXPLAIN */\n  int *abYield = 0;               /* True if op is an OP_Yield */\n  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */\n  int iOp;                        /* Index of operation in p->aiIndent[] */\n\n  const char *azNext[] = { \"Next\", \"Prev\", \"VPrev\", \"VNext\", \"SorterNext\", 0 };\n  const char *azYield[] = { \"Yield\", \"SeekLT\", \"SeekGT\", \"RowSetRead\",\n                            \"Rewind\", 0 };\n  const char *azGoto[] = { \"Goto\", 0 };\n\n  /* Try to figure out if this is really an EXPLAIN statement. If this\n  ** cannot be verified, return early.  */\n  if( sqlite3_column_count(pSql)!=8 ){\n    p->cMode = p->mode;\n    return;\n  }\n  zSql = sqlite3_sql(pSql);\n  if( zSql==0 ) return;\n  for(z=zSql; *z==' ' || *z=='\\t' || *z=='\\n' || *z=='\\f' || *z=='\\r'; z++);\n  if( sqlite3_strnicmp(z, \"explain\", 7) ){\n    p->cMode = p->mode;\n    return;\n  }\n\n  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){\n    int i;\n    int iAddr = sqlite3_column_int(pSql, 0);\n    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);\n\n    /* Set p2 to the P2 field of the current opcode. Then, assuming that\n    ** p2 is an instruction address, set variable p2op to the index of that\n    ** instruction in the aiIndent[] array. p2 and p2op may be different if\n    ** the current instruction is part of a sub-program generated by an\n    ** SQL trigger or foreign key.  */\n    int p2 = sqlite3_column_int(pSql, 3);\n    int p2op = (p2 + (iOp-iAddr));\n\n    /* Grow the p->aiIndent array as required */\n    if( iOp>=nAlloc ){\n      if( iOp==0 ){\n        /* Do further verfication that this is explain output.  Abort if\n        ** it is not */\n        static const char *explainCols[] = {\n           \"addr\", \"opcode\", \"p1\", \"p2\", \"p3\", \"p4\", \"p5\", \"comment\" };\n        int jj;\n        for(jj=0; jj<ArraySize(explainCols); jj++){\n          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){\n            p->cMode = p->mode;\n            sqlite3_reset(pSql);\n            return;\n          }\n        }\n      }\n      nAlloc += 100;\n      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));\n      if( p->aiIndent==0 ) shell_out_of_memory();\n      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));\n      if( abYield==0 ) shell_out_of_memory();\n    }\n    abYield[iOp] = str_in_array(zOp, azYield);\n    p->aiIndent[iOp] = 0;\n    p->nIndent = iOp+1;\n\n    if( str_in_array(zOp, azNext) ){\n      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;\n    }\n    if( str_in_array(zOp, azGoto) && p2op<p->nIndent\n     && (abYield[p2op] || sqlite3_column_int(pSql, 2))\n    ){\n      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;\n    }\n  }\n\n  p->iIndent = 0;\n  sqlite3_free(abYield);\n  sqlite3_reset(pSql);\n}\n\n/*\n** Free the array allocated by explain_data_prepare().\n*/\nstatic void explain_data_delete(ShellState *p){\n  sqlite3_free(p->aiIndent);\n  p->aiIndent = 0;\n  p->nIndent = 0;\n  p->iIndent = 0;\n}\n\n/*\n** Disable and restore .wheretrace and .selecttrace settings.\n*/\n#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)\nextern int sqlite3SelectTrace;\nstatic int savedSelectTrace;\n#endif\n#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)\nextern int sqlite3WhereTrace;\nstatic int savedWhereTrace;\n#endif\nstatic void disable_debug_trace_modes(void){\n#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)\n  savedSelectTrace = sqlite3SelectTrace;\n  sqlite3SelectTrace = 0;\n#endif\n#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)\n  savedWhereTrace = sqlite3WhereTrace;\n  sqlite3WhereTrace = 0;\n#endif\n}\nstatic void restore_debug_trace_modes(void){\n#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)\n  sqlite3SelectTrace = savedSelectTrace;\n#endif\n#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)\n  sqlite3WhereTrace = savedWhereTrace;\n#endif\n}\n\n/* Create the TEMP table used to store parameter bindings */\nstatic void bind_table_init(ShellState *p){\n  int wrSchema = 0;\n  int defensiveMode = 0;\n  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);\n  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);\n  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);\n  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);\n  sqlite3_exec(p->db,\n    \"CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\\n\"\n    \"  key TEXT PRIMARY KEY,\\n\"\n    \"  value ANY\\n\"\n    \") WITHOUT ROWID;\",\n    0, 0, 0);\n  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);\n  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);\n}\n\n/*\n** Bind parameters on a prepared statement.\n**\n** Parameter bindings are taken from a TEMP table of the form:\n**\n**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)\n**    WITHOUT ROWID;\n**\n** No bindings occur if this table does not exist.  The name of the table\n** begins with \"sqlite_\" so that it will not collide with ordinary application\n** tables.  The table must be in the TEMP schema.\n*/\nstatic void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){\n  int nVar;\n  int i;\n  int rc;\n  sqlite3_stmt *pQ = 0;\n\n  nVar = sqlite3_bind_parameter_count(pStmt);\n  if( nVar==0 ) return;  /* Nothing to do */\n  if( sqlite3_table_column_metadata(pArg->db, \"TEMP\", \"sqlite_parameters\",\n                                    \"key\", 0, 0, 0, 0, 0)!=SQLITE_OK ){\n    return; /* Parameter table does not exist */\n  }\n  rc = sqlite3_prepare_v2(pArg->db,\n          \"SELECT value FROM temp.sqlite_parameters\"\n          \" WHERE key=?1\", -1, &pQ, 0);\n  if( rc || pQ==0 ) return;\n  for(i=1; i<=nVar; i++){\n    char zNum[30];\n    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);\n    if( zVar==0 ){\n      sqlite3_snprintf(sizeof(zNum),zNum,\"?%d\",i);\n      zVar = zNum;\n    }\n    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);\n    if( sqlite3_step(pQ)==SQLITE_ROW ){\n      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));\n    }else{\n      sqlite3_bind_null(pStmt, i);\n    }\n    sqlite3_reset(pQ);\n  }\n  sqlite3_finalize(pQ);\n}\n\n/*\n** Run a prepared statement\n*/\nstatic void exec_prepared_stmt(\n  ShellState *pArg,                                /* Pointer to ShellState */\n  sqlite3_stmt *pStmt                              /* Statment to run */\n){\n  int rc;\n\n  /* perform the first step.  this will tell us if we\n  ** have a result set or not and how wide it is.\n  */\n  rc = sqlite3_step(pStmt);\n  /* if we have a result set... */\n  if( SQLITE_ROW == rc ){\n    /* allocate space for col name ptr, value ptr, and type */\n    int nCol = sqlite3_column_count(pStmt);\n    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);\n    if( !pData ){\n      rc = SQLITE_NOMEM;\n    }else{\n      char **azCols = (char **)pData;      /* Names of result columns */\n      char **azVals = &azCols[nCol];       /* Results */\n      int *aiTypes = (int *)&azVals[nCol]; /* Result types */\n      int i, x;\n      assert(sizeof(int) <= sizeof(char *));\n      /* save off ptrs to column names */\n      for(i=0; i<nCol; i++){\n        azCols[i] = (char *)sqlite3_column_name(pStmt, i);\n      }\n      do{\n        /* extract the data and data types */\n        for(i=0; i<nCol; i++){\n          aiTypes[i] = x = sqlite3_column_type(pStmt, i);\n          if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){\n            azVals[i] = \"\";\n          }else{\n            azVals[i] = (char*)sqlite3_column_text(pStmt, i);\n          }\n          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){\n            rc = SQLITE_NOMEM;\n            break; /* from for */\n          }\n        } /* end for */\n\n        /* if data and types extracted successfully... */\n        if( SQLITE_ROW == rc ){\n          /* call the supplied callback with the result row data */\n          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){\n            rc = SQLITE_ABORT;\n          }else{\n            rc = sqlite3_step(pStmt);\n          }\n        }\n      } while( SQLITE_ROW == rc );\n      sqlite3_free(pData);\n    }\n  }\n}\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/*\n** This function is called to process SQL if the previous shell command\n** was \".expert\". It passes the SQL in the second argument directly to\n** the sqlite3expert object.\n**\n** If successful, SQLITE_OK is returned. Otherwise, an SQLite error\n** code. In this case, (*pzErr) may be set to point to a buffer containing\n** an English language error message. It is the responsibility of the\n** caller to eventually free this buffer using sqlite3_free().\n*/\nstatic int expertHandleSQL(\n  ShellState *pState, \n  const char *zSql, \n  char **pzErr\n){\n  assert( pState->expert.pExpert );\n  assert( pzErr==0 || *pzErr==0 );\n  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);\n}\n\n/*\n** This function is called either to silently clean up the object\n** created by the \".expert\" command (if bCancel==1), or to generate a \n** report from it and then clean it up (if bCancel==0).\n**\n** If successful, SQLITE_OK is returned. Otherwise, an SQLite error\n** code. In this case, (*pzErr) may be set to point to a buffer containing\n** an English language error message. It is the responsibility of the\n** caller to eventually free this buffer using sqlite3_free().\n*/\nstatic int expertFinish(\n  ShellState *pState,\n  int bCancel,\n  char **pzErr\n){\n  int rc = SQLITE_OK;\n  sqlite3expert *p = pState->expert.pExpert;\n  assert( p );\n  assert( bCancel || pzErr==0 || *pzErr==0 );\n  if( bCancel==0 ){\n    FILE *out = pState->out;\n    int bVerbose = pState->expert.bVerbose;\n\n    rc = sqlite3_expert_analyze(p, pzErr);\n    if( rc==SQLITE_OK ){\n      int nQuery = sqlite3_expert_count(p);\n      int i;\n\n      if( bVerbose ){\n        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);\n        raw_printf(out, \"-- Candidates -----------------------------\\n\");\n        raw_printf(out, \"%s\\n\", zCand);\n      }\n      for(i=0; i<nQuery; i++){\n        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);\n        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);\n        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);\n        if( zIdx==0 ) zIdx = \"(no new indexes)\\n\";\n        if( bVerbose ){\n          raw_printf(out, \"-- Query %d --------------------------------\\n\",i+1);\n          raw_printf(out, \"%s\\n\\n\", zSql);\n        }\n        raw_printf(out, \"%s\\n\", zIdx);\n        raw_printf(out, \"%s\\n\", zEQP);\n      }\n    }\n  }\n  sqlite3_expert_destroy(p);\n  pState->expert.pExpert = 0;\n  return rc;\n}\n\n/*\n** Implementation of \".expert\" dot command.\n*/\nstatic int expertDotCommand(\n  ShellState *pState,             /* Current shell tool state */\n  char **azArg,                   /* Array of arguments passed to dot command */\n  int nArg                        /* Number of entries in azArg[] */\n){\n  int rc = SQLITE_OK;\n  char *zErr = 0;\n  int i;\n  int iSample = 0;\n\n  assert( pState->expert.pExpert==0 );\n  memset(&pState->expert, 0, sizeof(ExpertInfo));\n\n  for(i=1; rc==SQLITE_OK && i<nArg; i++){\n    char *z = azArg[i];\n    int n;\n    if( z[0]=='-' && z[1]=='-' ) z++;\n    n = strlen30(z);\n    if( n>=2 && 0==strncmp(z, \"-verbose\", n) ){\n      pState->expert.bVerbose = 1;\n    }\n    else if( n>=2 && 0==strncmp(z, \"-sample\", n) ){\n      if( i==(nArg-1) ){\n        raw_printf(stderr, \"option requires an argument: %s\\n\", z);\n        rc = SQLITE_ERROR;\n      }else{\n        iSample = (int)integerValue(azArg[++i]);\n        if( iSample<0 || iSample>100 ){\n          raw_printf(stderr, \"value out of range: %s\\n\", azArg[i]);\n          rc = SQLITE_ERROR;\n        }\n      }\n    }\n    else{\n      raw_printf(stderr, \"unknown option: %s\\n\", z);\n      rc = SQLITE_ERROR;\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);\n    if( pState->expert.pExpert==0 ){\n      raw_printf(stderr, \"sqlite3_expert_new: %s\\n\", zErr);\n      rc = SQLITE_ERROR;\n    }else{\n      sqlite3_expert_config(\n          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample\n      );\n    }\n  }\n\n  return rc;\n}\n#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */\n\n/*\n** Execute a statement or set of statements.  Print\n** any result rows/columns depending on the current mode\n** set via the supplied callback.\n**\n** This is very similar to SQLite's built-in sqlite3_exec()\n** function except it takes a slightly different callback\n** and callback data argument.\n*/\nstatic int shell_exec(\n  ShellState *pArg,                         /* Pointer to ShellState */\n  const char *zSql,                         /* SQL to be evaluated */\n  char **pzErrMsg                           /* Error msg written here */\n){\n  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */\n  int rc = SQLITE_OK;             /* Return Code */\n  int rc2;\n  const char *zLeftover;          /* Tail of unprocessed SQL */\n  sqlite3 *db = pArg->db;\n\n  if( pzErrMsg ){\n    *pzErrMsg = NULL;\n  }\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( pArg->expert.pExpert ){\n    rc = expertHandleSQL(pArg, zSql, pzErrMsg);\n    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);\n  }\n#endif\n\n  while( zSql[0] && (SQLITE_OK == rc) ){\n    static const char *zStmtSql;\n    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);\n    if( SQLITE_OK != rc ){\n      if( pzErrMsg ){\n        *pzErrMsg = save_err_msg(db);\n      }\n    }else{\n      if( !pStmt ){\n        /* this happens for a comment or white-space */\n        zSql = zLeftover;\n        while( IsSpace(zSql[0]) ) zSql++;\n        continue;\n      }\n      zStmtSql = sqlite3_sql(pStmt);\n      if( zStmtSql==0 ) zStmtSql = \"\";\n      while( IsSpace(zStmtSql[0]) ) zStmtSql++;\n\n      /* save off the prepared statment handle and reset row count */\n      if( pArg ){\n        pArg->pStmt = pStmt;\n        pArg->cnt = 0;\n      }\n\n      /* echo the sql statement if echo on */\n      if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){\n        utf8_printf(pArg->out, \"%s\\n\", zStmtSql ? zStmtSql : zSql);\n      }\n\n      /* Show the EXPLAIN QUERY PLAN if .eqp is on */\n      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){\n        sqlite3_stmt *pExplain;\n        char *zEQP;\n        int triggerEQP = 0;\n        disable_debug_trace_modes();\n        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);\n        if( pArg->autoEQP>=AUTOEQP_trigger ){\n          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);\n        }\n        zEQP = sqlite3_mprintf(\"EXPLAIN QUERY PLAN %s\", zStmtSql);\n        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);\n        if( rc==SQLITE_OK ){\n          while( sqlite3_step(pExplain)==SQLITE_ROW ){\n            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);\n            int iEqpId = sqlite3_column_int(pExplain, 0);\n            int iParentId = sqlite3_column_int(pExplain, 1);\n            if( zEQPLine==0 ) zEQPLine = \"\";\n            if( zEQPLine[0]=='-' ) eqp_render(pArg);\n            eqp_append(pArg, iEqpId, iParentId, zEQPLine);\n          }\n          eqp_render(pArg);\n        }\n        sqlite3_finalize(pExplain);\n        sqlite3_free(zEQP);\n        if( pArg->autoEQP>=AUTOEQP_full ){\n          /* Also do an EXPLAIN for \".eqp full\" mode */\n          zEQP = sqlite3_mprintf(\"EXPLAIN %s\", zStmtSql);\n          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);\n          if( rc==SQLITE_OK ){\n            pArg->cMode = MODE_Explain;\n            explain_data_prepare(pArg, pExplain);\n            exec_prepared_stmt(pArg, pExplain);\n            explain_data_delete(pArg);\n          }\n          sqlite3_finalize(pExplain);\n          sqlite3_free(zEQP);\n        }\n        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){\n          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);\n          /* Reprepare pStmt before reactiving trace modes */\n          sqlite3_finalize(pStmt);\n          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);\n          if( pArg ) pArg->pStmt = pStmt;\n        }\n        restore_debug_trace_modes();\n      }\n\n      if( pArg ){\n        pArg->cMode = pArg->mode;\n        if( pArg->autoExplain ){\n          if( sqlite3_stmt_isexplain(pStmt)==1 ){\n            pArg->cMode = MODE_Explain;\n          }\n          if( sqlite3_stmt_isexplain(pStmt)==2 ){\n            pArg->cMode = MODE_EQP;\n          }\n        }\n\n        /* If the shell is currently in \".explain\" mode, gather the extra\n        ** data required to add indents to the output.*/\n        if( pArg->cMode==MODE_Explain ){\n          explain_data_prepare(pArg, pStmt);\n        }\n      }\n\n      bind_prepared_stmt(pArg, pStmt);\n      exec_prepared_stmt(pArg, pStmt);\n      explain_data_delete(pArg);\n      eqp_render(pArg);\n\n      /* print usage stats if stats on */\n      if( pArg && pArg->statsOn ){\n        display_stats(db, pArg, 0);\n      }\n\n      /* print loop-counters if required */\n      if( pArg && pArg->scanstatsOn ){\n        display_scanstats(db, pArg);\n      }\n\n      /* Finalize the statement just executed. If this fails, save a\n      ** copy of the error message. Otherwise, set zSql to point to the\n      ** next statement to execute. */\n      rc2 = sqlite3_finalize(pStmt);\n      if( rc!=SQLITE_NOMEM ) rc = rc2;\n      if( rc==SQLITE_OK ){\n        zSql = zLeftover;\n        while( IsSpace(zSql[0]) ) zSql++;\n      }else if( pzErrMsg ){\n        *pzErrMsg = save_err_msg(db);\n      }\n\n      /* clear saved stmt handle */\n      if( pArg ){\n        pArg->pStmt = NULL;\n      }\n    }\n  } /* end while */\n\n  return rc;\n}\n\n/*\n** Release memory previously allocated by tableColumnList().\n*/\nstatic void freeColumnList(char **azCol){\n  int i;\n  for(i=1; azCol[i]; i++){\n    sqlite3_free(azCol[i]);\n  }\n  /* azCol[0] is a static string */\n  sqlite3_free(azCol);\n}\n\n/*\n** Return a list of pointers to strings which are the names of all\n** columns in table zTab.   The memory to hold the names is dynamically\n** allocated and must be released by the caller using a subsequent call\n** to freeColumnList().\n**\n** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid\n** value that needs to be preserved, then azCol[0] is filled in with the\n** name of the rowid column.\n**\n** The first regular column in the table is azCol[1].  The list is terminated\n** by an entry with azCol[i]==0.\n*/\nstatic char **tableColumnList(ShellState *p, const char *zTab){\n  char **azCol = 0;\n  sqlite3_stmt *pStmt;\n  char *zSql;\n  int nCol = 0;\n  int nAlloc = 0;\n  int nPK = 0;       /* Number of PRIMARY KEY columns seen */\n  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */\n  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);\n  int rc;\n\n  zSql = sqlite3_mprintf(\"PRAGMA table_info=%Q\", zTab);\n  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);\n  sqlite3_free(zSql);\n  if( rc ) return 0;\n  while( sqlite3_step(pStmt)==SQLITE_ROW ){\n    if( nCol>=nAlloc-2 ){\n      nAlloc = nAlloc*2 + nCol + 10;\n      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));\n      if( azCol==0 ) shell_out_of_memory();\n    }\n    azCol[++nCol] = sqlite3_mprintf(\"%s\", sqlite3_column_text(pStmt, 1));\n    if( sqlite3_column_int(pStmt, 5) ){\n      nPK++;\n      if( nPK==1\n       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),\n                          \"INTEGER\")==0\n      ){\n        isIPK = 1;\n      }else{\n        isIPK = 0;\n      }\n    }\n  }\n  sqlite3_finalize(pStmt);\n  if( azCol==0 ) return 0;\n  azCol[0] = 0;\n  azCol[nCol+1] = 0;\n\n  /* The decision of whether or not a rowid really needs to be preserved\n  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table\n  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve\n  ** rowids on tables where the rowid is inaccessible because there are other\n  ** columns in the table named \"rowid\", \"_rowid_\", and \"oid\".\n  */\n  if( preserveRowid && isIPK ){\n    /* If a single PRIMARY KEY column with type INTEGER was seen, then it\n    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID\n    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are\n    ** ROWID aliases.  To distinguish these cases, check to see if\n    ** there is a \"pk\" entry in \"PRAGMA index_list\".  There will be\n    ** no \"pk\" index if the PRIMARY KEY really is an alias for the ROWID.\n    */\n    zSql = sqlite3_mprintf(\"SELECT 1 FROM pragma_index_list(%Q)\"\n                           \" WHERE origin='pk'\", zTab);\n    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);\n    sqlite3_free(zSql);\n    if( rc ){\n      freeColumnList(azCol);\n      return 0;\n    }\n    rc = sqlite3_step(pStmt);\n    sqlite3_finalize(pStmt);\n    preserveRowid = rc==SQLITE_ROW;\n  }\n  if( preserveRowid ){\n    /* Only preserve the rowid if we can find a name to use for the\n    ** rowid */\n    static char *azRowid[] = { \"rowid\", \"_rowid_\", \"oid\" };\n    int i, j;\n    for(j=0; j<3; j++){\n      for(i=1; i<=nCol; i++){\n        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;\n      }\n      if( i>nCol ){\n        /* At this point, we know that azRowid[j] is not the name of any\n        ** ordinary column in the table.  Verify that azRowid[j] is a valid\n        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID\n        ** tables will fail this last check */\n        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);\n        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];\n        break;\n      }\n    }\n  }\n  return azCol;\n}\n\n/*\n** Toggle the reverse_unordered_selects setting.\n*/\nstatic void toggleSelectOrder(sqlite3 *db){\n  sqlite3_stmt *pStmt = 0;\n  int iSetting = 0;\n  char zStmt[100];\n  sqlite3_prepare_v2(db, \"PRAGMA reverse_unordered_selects\", -1, &pStmt, 0);\n  if( sqlite3_step(pStmt)==SQLITE_ROW ){\n    iSetting = sqlite3_column_int(pStmt, 0);\n  }\n  sqlite3_finalize(pStmt);\n  sqlite3_snprintf(sizeof(zStmt), zStmt,\n       \"PRAGMA reverse_unordered_selects(%d)\", !iSetting);\n  sqlite3_exec(db, zStmt, 0, 0, 0);\n}\n\n/*\n** This is a different callback routine used for dumping the database.\n** Each row received by this callback consists of a table name,\n** the table type (\"index\" or \"table\") and SQL to create the table.\n** This routine should print text sufficient to recreate the table.\n*/\nstatic int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){\n  int rc;\n  const char *zTable;\n  const char *zType;\n  const char *zSql;\n  ShellState *p = (ShellState *)pArg;\n\n  UNUSED_PARAMETER(azNotUsed);\n  if( nArg!=3 || azArg==0 ) return 0;\n  zTable = azArg[0];\n  zType = azArg[1];\n  zSql = azArg[2];\n\n  if( strcmp(zTable, \"sqlite_sequence\")==0 ){\n    raw_printf(p->out, \"DELETE FROM sqlite_sequence;\\n\");\n  }else if( sqlite3_strglob(\"sqlite_stat?\", zTable)==0 ){\n    raw_printf(p->out, \"ANALYZE sqlite_master;\\n\");\n  }else if( strncmp(zTable, \"sqlite_\", 7)==0 ){\n    return 0;\n  }else if( strncmp(zSql, \"CREATE VIRTUAL TABLE\", 20)==0 ){\n    char *zIns;\n    if( !p->writableSchema ){\n      raw_printf(p->out, \"PRAGMA writable_schema=ON;\\n\");\n      p->writableSchema = 1;\n    }\n    zIns = sqlite3_mprintf(\n       \"INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)\"\n       \"VALUES('table','%q','%q',0,'%q');\",\n       zTable, zTable, zSql);\n    utf8_printf(p->out, \"%s\\n\", zIns);\n    sqlite3_free(zIns);\n    return 0;\n  }else{\n    printSchemaLine(p->out, zSql, \";\\n\");\n  }\n\n  if( strcmp(zType, \"table\")==0 ){\n    ShellText sSelect;\n    ShellText sTable;\n    char **azCol;\n    int i;\n    char *savedDestTable;\n    int savedMode;\n\n    azCol = tableColumnList(p, zTable);\n    if( azCol==0 ){\n      p->nErr++;\n      return 0;\n    }\n\n    /* Always quote the table name, even if it appears to be pure ascii,\n    ** in case it is a keyword. Ex:  INSERT INTO \"table\" ... */\n    initText(&sTable);\n    appendText(&sTable, zTable, quoteChar(zTable));\n    /* If preserving the rowid, add a column list after the table name.\n    ** In other words:  \"INSERT INTO tab(rowid,a,b,c,...) VALUES(...)\"\n    ** instead of the usual \"INSERT INTO tab VALUES(...)\".\n    */\n    if( azCol[0] ){\n      appendText(&sTable, \"(\", 0);\n      appendText(&sTable, azCol[0], 0);\n      for(i=1; azCol[i]; i++){\n        appendText(&sTable, \",\", 0);\n        appendText(&sTable, azCol[i], quoteChar(azCol[i]));\n      }\n      appendText(&sTable, \")\", 0);\n    }\n\n    /* Build an appropriate SELECT statement */\n    initText(&sSelect);\n    appendText(&sSelect, \"SELECT \", 0);\n    if( azCol[0] ){\n      appendText(&sSelect, azCol[0], 0);\n      appendText(&sSelect, \",\", 0);\n    }\n    for(i=1; azCol[i]; i++){\n      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));\n      if( azCol[i+1] ){\n        appendText(&sSelect, \",\", 0);\n      }\n    }\n    freeColumnList(azCol);\n    appendText(&sSelect, \" FROM \", 0);\n    appendText(&sSelect, zTable, quoteChar(zTable));\n\n    savedDestTable = p->zDestTable;\n    savedMode = p->mode;\n    p->zDestTable = sTable.z;\n    p->mode = p->cMode = MODE_Insert;\n    rc = shell_exec(p, sSelect.z, 0);\n    if( (rc&0xff)==SQLITE_CORRUPT ){\n      raw_printf(p->out, \"/****** CORRUPTION ERROR *******/\\n\");\n      toggleSelectOrder(p->db);\n      shell_exec(p, sSelect.z, 0);\n      toggleSelectOrder(p->db);\n    }\n    p->zDestTable = savedDestTable;\n    p->mode = savedMode;\n    freeText(&sTable);\n    freeText(&sSelect);\n    if( rc ) p->nErr++;\n  }\n  return 0;\n}\n\n/*\n** Run zQuery.  Use dump_callback() as the callback routine so that\n** the contents of the query are output as SQL statements.\n**\n** If we get a SQLITE_CORRUPT error, rerun the query after appending\n** \"ORDER BY rowid DESC\" to the end.\n*/\nstatic int run_schema_dump_query(\n  ShellState *p,\n  const char *zQuery\n){\n  int rc;\n  char *zErr = 0;\n  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);\n  if( rc==SQLITE_CORRUPT ){\n    char *zQ2;\n    int len = strlen30(zQuery);\n    raw_printf(p->out, \"/****** CORRUPTION ERROR *******/\\n\");\n    if( zErr ){\n      utf8_printf(p->out, \"/****** %s ******/\\n\", zErr);\n      sqlite3_free(zErr);\n      zErr = 0;\n    }\n    zQ2 = malloc( len+100 );\n    if( zQ2==0 ) return rc;\n    sqlite3_snprintf(len+100, zQ2, \"%s ORDER BY rowid DESC\", zQuery);\n    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);\n    if( rc ){\n      utf8_printf(p->out, \"/****** ERROR: %s ******/\\n\", zErr);\n    }else{\n      rc = SQLITE_CORRUPT;\n    }\n    sqlite3_free(zErr);\n    free(zQ2);\n  }\n  return rc;\n}\n\n/*\n** Text of help messages.\n**\n** The help text for each individual command begins with a line that starts\n** with \".\".  Subsequent lines are supplimental information.\n**\n** There must be two or more spaces between the end of the command and the\n** start of the description of what that command does.\n*/\nstatic const char *(azHelp[]) = {\n#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)\n  \".archive ...             Manage SQL archives\",\n  \"   Each command must have exactly one of the following options:\",\n  \"     -c, --create               Create a new archive\",\n  \"     -u, --update               Add or update files with changed mtime\",\n  \"     -i, --insert               Like -u but always add even if unchanged\",\n  \"     -t, --list                 List contents of archive\",\n  \"     -x, --extract              Extract files from archive\",\n  \"   Optional arguments:\",\n  \"     -v, --verbose              Print each filename as it is processed\",\n  \"     -f FILE, --file FILE       Use archive FILE (default is current db)\",\n  \"     -a FILE, --append FILE     Open FILE using the apndvfs VFS\",\n  \"     -C DIR, --directory DIR    Read/extract files from directory DIR\",\n  \"     -n, --dryrun               Show the SQL that would have occurred\",\n  \"   Examples:\",\n  \"     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar\",\n  \"     .ar -tf ARCHIVE          # List members of ARCHIVE\",\n  \"     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE\",\n  \"   See also:\",\n  \"      http://sqlite.org/cli.html#sqlar_archive_support\",\n#endif\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  \".auth ON|OFF             Show authorizer callbacks\",\n#endif\n  \".backup ?DB? FILE        Backup DB (default \\\"main\\\") to FILE\",\n  \"       --append            Use the appendvfs\",\n  \"       --async             Write to FILE without journal and fsync()\",\n  \".bail on|off             Stop after hitting an error.  Default OFF\",\n  \".binary on|off           Turn binary output on or off.  Default OFF\",\n  \".cd DIRECTORY            Change the working directory to DIRECTORY\",\n  \".changes on|off          Show number of rows changed by SQL\",\n  \".check GLOB              Fail if output since .testcase does not match\",\n  \".clone NEWDB             Clone data into NEWDB from the existing database\",\n  \".databases               List names and files of attached databases\",\n  \".dbconfig ?op? ?val?     List or change sqlite3_db_config() options\",\n  \".dbinfo ?DB?             Show status information about the database\",\n  \".dump ?TABLE?            Render database content as SQL\",\n  \"   Options:\",\n  \"     --preserve-rowids      Include ROWID values in the output\",\n  \"     --newlines             Allow unescaped newline characters in output\",\n  \"   TABLE is a LIKE pattern for the tables to dump\",\n  \"   Additional LIKE patterns can be given in subsequent arguments\",\n  \".echo on|off             Turn command echo on or off\",\n  \".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN\",\n  \"   Other Modes:\",\n#ifdef SQLITE_DEBUG\n  \"      test                  Show raw EXPLAIN QUERY PLAN output\",\n  \"      trace                 Like \\\"full\\\" but enable \\\"PRAGMA vdbe_trace\\\"\",\n#endif\n  \"      trigger               Like \\\"full\\\" but also show trigger bytecode\",\n  \".excel                   Display the output of next command in spreadsheet\",\n  \"   --bom                   Put a UTF8 byte-order mark on intermediate file\",\n  \".exit ?CODE?             Exit this program with return-code CODE\",\n  \".expert                  EXPERIMENTAL. Suggest indexes for queries\",\n  \".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto\",\n  \".filectrl CMD ...        Run various sqlite3_file_control() operations\",\n  \"   --schema SCHEMA         Use SCHEMA instead of \\\"main\\\"\",\n  \"   --help                  Show CMD details\",\n  \".fullschema ?--indent?   Show schema and the content of sqlite_stat tables\",\n  \".headers on|off          Turn display of headers on or off\",\n  \".help ?-all? ?PATTERN?   Show help text for PATTERN\",\n  \".import FILE TABLE       Import data from FILE into TABLE\",\n  \"   Options:\",\n  \"     --ascii               Use \\\\037 and \\\\036 as column and row separators\",\n  \"     --csv                 Use , and \\\\n as column and row separators\",\n  \"     --skip N              Skip the first N rows of input\",\n  \"     -v                    \\\"Verbose\\\" - increase auxiliary output\",\n  \"   Notes:\",\n  \"     *  If TABLE does not exist, it is created.  The first row of input\",\n  \"        determines the column names.\",\n  \"     *  If neither --csv or --ascii are used, the input mode is derived\",\n  \"        from the \\\".mode\\\" output mode\",\n  \"     *  If FILE begins with \\\"|\\\" then it is a command that generates the\",\n  \"        input text.\",\n#ifndef SQLITE_OMIT_TEST_CONTROL\n  \".imposter INDEX TABLE    Create imposter table TABLE on index INDEX\",\n#endif\n  \".indexes ?TABLE?         Show names of indexes\",\n  \"                           If TABLE is specified, only show indexes for\",\n  \"                           tables matching TABLE using the LIKE operator.\",\n#ifdef SQLITE_ENABLE_IOTRACE\n  \".iotrace FILE            Enable I/O diagnostic logging to FILE\",\n#endif\n  \".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT\",\n  \".lint OPTIONS            Report potential schema issues.\",\n  \"     Options:\",\n  \"        fkey-indexes     Find missing foreign key indexes\",\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\n  \".load FILE ?ENTRY?       Load an extension library\",\n#endif\n  \".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout\",\n  \".mode MODE ?TABLE?       Set output mode\",\n  \"   MODE is one of:\",\n  \"     ascii    Columns/rows delimited by 0x1F and 0x1E\",\n  \"     csv      Comma-separated values\",\n  \"     column   Left-aligned columns.  (See .width)\",\n  \"     html     HTML <table> code\",\n  \"     insert   SQL insert statements for TABLE\",\n  \"     line     One value per line\",\n  \"     list     Values delimited by \\\"|\\\"\",\n  \"     quote    Escape answers as for SQL\",\n  \"     tabs     Tab-separated values\",\n  \"     tcl      TCL list elements\",\n  \".nullvalue STRING        Use STRING in place of NULL values\",\n  \".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE\",\n  \"     If FILE begins with '|' then open as a pipe\",\n  \"       --bom  Put a UTF8 byte-order mark at the beginning\",\n  \"       -e     Send output to the system text editor\",\n  \"       -x     Send output as CSV to a spreadsheet (same as \\\".excel\\\")\",\n#ifdef SQLITE_DEBUG\n  \".oom [--repeat M] [N]    Simulate an OOM error on the N-th allocation\",\n#endif \n  \".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE\",\n  \"     Options:\",\n  \"        --append        Use appendvfs to append database to the end of FILE\",\n#ifdef SQLITE_ENABLE_DESERIALIZE\n  \"        --deserialize   Load into memory useing sqlite3_deserialize()\",\n  \"        --hexdb         Load the output of \\\"dbtotxt\\\" as an in-memory db\",\n  \"        --maxsize N     Maximum size for --hexdb or --deserialized database\",\n#endif\n  \"        --new           Initialize FILE to an empty database\",\n  \"        --nofollow      Do not follow symbolic links\",\n  \"        --readonly      Open FILE readonly\",\n  \"        --zip           FILE is a ZIP archive\",\n  \".output ?FILE?           Send output to FILE or stdout if FILE is omitted\",\n  \"   If FILE begins with '|' then open it as a pipe.\",\n  \"   Options:\",\n  \"     --bom                 Prefix output with a UTF8 byte-order mark\",\n  \"     -e                    Send output to the system text editor\",\n  \"     -x                    Send output as CSV to a spreadsheet\",\n  \".parameter CMD ...       Manage SQL parameter bindings\",\n  \"   clear                   Erase all bindings\",\n  \"   init                    Initialize the TEMP table that holds bindings\",\n  \"   list                    List the current parameter bindings\",\n  \"   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE\",\n  \"                           PARAMETER should start with one of: $ : @ ?\",\n  \"   unset PARAMETER         Remove PARAMETER from the binding table\",\n  \".print STRING...         Print literal STRING\",\n#ifndef SQLITE_OMIT_PROGRESS_CALLBACK\n  \".progress N              Invoke progress handler after every N opcodes\",\n  \"   --limit N                 Interrupt after N progress callbacks\",\n  \"   --once                    Do no more than one progress interrupt\",\n  \"   --quiet|-q                No output except at interrupts\",\n  \"   --reset                   Reset the count for each input and interrupt\",\n#endif\n  \".prompt MAIN CONTINUE    Replace the standard prompts\",\n  \".quit                    Exit this program\",\n  \".read FILE               Read input from FILE\",\n#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)\n  \".recover                 Recover as much data as possible from corrupt db.\",\n  \"   --freelist-corrupt       Assume the freelist is corrupt\",\n  \"   --recovery-db NAME       Store recovery metadata in database file NAME\",\n  \"   --lost-and-found TABLE   Alternative name for the lost-and-found table\",\n  \"   --no-rowids              Do not attempt to recover rowid values\",\n  \"                            that are not also INTEGER PRIMARY KEYs\",\n#endif\n  \".restore ?DB? FILE       Restore content of DB (default \\\"main\\\") from FILE\",\n  \".save FILE               Write in-memory database into FILE\",\n  \".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off\",\n  \".schema ?PATTERN?        Show the CREATE statements matching PATTERN\",\n  \"     Options:\",\n  \"         --indent            Try to pretty-print the schema\",\n  \".selftest ?OPTIONS?      Run tests defined in the SELFTEST table\",\n  \"    Options:\",\n  \"       --init               Create a new SELFTEST table\",\n  \"       -v                   Verbose output\",\n  \".separator COL ?ROW?     Change the column and row separators\",\n#if defined(SQLITE_ENABLE_SESSION)\n  \".session ?NAME? CMD ...  Create or control sessions\",\n  \"   Subcommands:\",\n  \"     attach TABLE             Attach TABLE\",\n  \"     changeset FILE           Write a changeset into FILE\",\n  \"     close                    Close one session\",\n  \"     enable ?BOOLEAN?         Set or query the enable bit\",\n  \"     filter GLOB...           Reject tables matching GLOBs\",\n  \"     indirect ?BOOLEAN?       Mark or query the indirect status\",\n  \"     isempty                  Query whether the session is empty\",\n  \"     list                     List currently open session names\",\n  \"     open DB NAME             Open a new session on DB\",\n  \"     patchset FILE            Write a patchset into FILE\",\n  \"   If ?NAME? is omitted, the first defined session is used.\",\n#endif\n  \".sha3sum ...             Compute a SHA3 hash of database content\",\n  \"    Options:\",\n  \"      --schema              Also hash the sqlite_master table\",\n  \"      --sha3-224            Use the sha3-224 algorithm\",\n  \"      --sha3-256            Use the sha3-256 algorithm (default)\",\n  \"      --sha3-384            Use the sha3-384 algorithm\",\n  \"      --sha3-512            Use the sha3-512 algorithm\",\n  \"    Any other argument is a LIKE pattern for tables to hash\",\n#ifndef SQLITE_NOHAVE_SYSTEM\n  \".shell CMD ARGS...       Run CMD ARGS... in a system shell\",\n#endif\n  \".show                    Show the current values for various settings\",\n  \".stats ?on|off?          Show stats or turn stats on or off\",\n#ifndef SQLITE_NOHAVE_SYSTEM\n  \".system CMD ARGS...      Run CMD ARGS... in a system shell\",\n#endif\n  \".tables ?TABLE?          List names of tables matching LIKE pattern TABLE\",\n  \".testcase NAME           Begin redirecting output to 'testcase-out.txt'\",\n  \".testctrl CMD ...        Run various sqlite3_test_control() operations\",\n  \"                           Run \\\".testctrl\\\" with no arguments for details\",\n  \".timeout MS              Try opening locked tables for MS milliseconds\",\n  \".timer on|off            Turn SQL timer on or off\",\n#ifndef SQLITE_OMIT_TRACE\n  \".trace ?OPTIONS?         Output each SQL statement as it is run\",\n  \"    FILE                    Send output to FILE\",\n  \"    stdout                  Send output to stdout\",\n  \"    stderr                  Send output to stderr\",\n  \"    off                     Disable tracing\",\n  \"    --expanded              Expand query parameters\",\n#ifdef SQLITE_ENABLE_NORMALIZE\n  \"    --normalized            Normal the SQL statements\",\n#endif\n  \"    --plain                 Show SQL as it is input\",\n  \"    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)\",\n  \"    --profile               Profile statements (SQLITE_TRACE_PROFILE)\",\n  \"    --row                   Trace each row (SQLITE_TRACE_ROW)\",\n  \"    --close                 Trace connection close (SQLITE_TRACE_CLOSE)\",\n#endif /* SQLITE_OMIT_TRACE */\n#ifdef SQLITE_DEBUG\n  \".unmodule NAME ...       Unregister virtual table modules\",\n  \"    --allexcept             Unregister everything except those named\",\n#endif\n  \".vfsinfo ?AUX?           Information about the top-level VFS\",\n  \".vfslist                 List all available VFSes\",\n  \".vfsname ?AUX?           Print the name of the VFS stack\",\n  \".width NUM1 NUM2 ...     Set column widths for \\\"column\\\" mode\",\n  \"     Negative values right-justify\",\n};\n\n/*\n** Output help text.\n**\n** zPattern describes the set of commands for which help text is provided.\n** If zPattern is NULL, then show all commands, but only give a one-line\n** description of each.\n**\n** Return the number of matches.\n*/\nstatic int showHelp(FILE *out, const char *zPattern){\n  int i = 0;\n  int j = 0;\n  int n = 0;\n  char *zPat;\n  if( zPattern==0\n   || zPattern[0]=='0'\n   || strcmp(zPattern,\"-a\")==0\n   || strcmp(zPattern,\"-all\")==0\n   || strcmp(zPattern,\"--all\")==0\n  ){\n    /* Show all commands, but only one line per command */\n    if( zPattern==0 ) zPattern = \"\";\n    for(i=0; i<ArraySize(azHelp); i++){\n      if( azHelp[i][0]=='.' || zPattern[0] ){\n        utf8_printf(out, \"%s\\n\", azHelp[i]);\n        n++;\n      }\n    }\n  }else{\n    /* Look for commands that for which zPattern is an exact prefix */\n    zPat = sqlite3_mprintf(\".%s*\", zPattern);\n    for(i=0; i<ArraySize(azHelp); i++){\n      if( sqlite3_strglob(zPat, azHelp[i])==0 ){\n        utf8_printf(out, \"%s\\n\", azHelp[i]);\n        j = i+1;\n        n++;\n      }\n    }\n    sqlite3_free(zPat);\n    if( n ){\n      if( n==1 ){\n        /* when zPattern is a prefix of exactly one command, then include the\n        ** details of that command, which should begin at offset j */\n        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){\n          utf8_printf(out, \"%s\\n\", azHelp[j]);\n          j++;\n        }\n      }\n      return n;\n    }\n    /* Look for commands that contain zPattern anywhere.  Show the complete\n    ** text of all commands that match. */\n    zPat = sqlite3_mprintf(\"%%%s%%\", zPattern);\n    for(i=0; i<ArraySize(azHelp); i++){\n      if( azHelp[i][0]=='.' ) j = i;\n      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){\n        utf8_printf(out, \"%s\\n\", azHelp[j]);\n        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){\n          j++;\n          utf8_printf(out, \"%s\\n\", azHelp[j]);\n        }\n        i = j;\n        n++;\n      }\n    }\n    sqlite3_free(zPat);\n  }\n  return n;\n}\n\n/* Forward reference */\nstatic int process_input(ShellState *p);\n\n/*\n** Read the content of file zName into memory obtained from sqlite3_malloc64()\n** and return a pointer to the buffer. The caller is responsible for freeing\n** the memory.\n**\n** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes\n** read.\n**\n** For convenience, a nul-terminator byte is always appended to the data read\n** from the file before the buffer is returned. This byte is not included in\n** the final value of (*pnByte), if applicable.\n**\n** NULL is returned if any error is encountered. The final value of *pnByte\n** is undefined in this case.\n*/\nstatic char *readFile(const char *zName, int *pnByte){\n  FILE *in = fopen(zName, \"rb\");\n  long nIn;\n  size_t nRead;\n  char *pBuf;\n  if( in==0 ) return 0;\n  fseek(in, 0, SEEK_END);\n  nIn = ftell(in);\n  rewind(in);\n  pBuf = sqlite3_malloc64( nIn+1 );\n  if( pBuf==0 ){ fclose(in); return 0; }\n  nRead = fread(pBuf, nIn, 1, in);\n  fclose(in);\n  if( nRead!=1 ){\n    sqlite3_free(pBuf);\n    return 0;\n  }\n  pBuf[nIn] = 0;\n  if( pnByte ) *pnByte = nIn;\n  return pBuf;\n}\n\n#if defined(SQLITE_ENABLE_SESSION)\n/*\n** Close a single OpenSession object and release all of its associated\n** resources.\n*/\nstatic void session_close(OpenSession *pSession){\n  int i;\n  sqlite3session_delete(pSession->p);\n  sqlite3_free(pSession->zName);\n  for(i=0; i<pSession->nFilter; i++){\n    sqlite3_free(pSession->azFilter[i]);\n  }\n  sqlite3_free(pSession->azFilter);\n  memset(pSession, 0, sizeof(OpenSession));\n}\n#endif\n\n/*\n** Close all OpenSession objects and release all associated resources.\n*/\n#if defined(SQLITE_ENABLE_SESSION)\nstatic void session_close_all(ShellState *p){\n  int i;\n  for(i=0; i<p->nSession; i++){\n    session_close(&p->aSession[i]);\n  }\n  p->nSession = 0;\n}\n#else\n# define session_close_all(X)\n#endif\n\n/*\n** Implementation of the xFilter function for an open session.  Omit\n** any tables named by \".session filter\" but let all other table through.\n*/\n#if defined(SQLITE_ENABLE_SESSION)\nstatic int session_filter(void *pCtx, const char *zTab){\n  OpenSession *pSession = (OpenSession*)pCtx;\n  int i;\n  for(i=0; i<pSession->nFilter; i++){\n    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;\n  }\n  return 1;\n}\n#endif\n\n/*\n** Try to deduce the type of file for zName based on its content.  Return\n** one of the SHELL_OPEN_* constants.\n**\n** If the file does not exist or is empty but its name looks like a ZIP\n** archive and the dfltZip flag is true, then assume it is a ZIP archive.\n** Otherwise, assume an ordinary database regardless of the filename if\n** the type cannot be determined from content.\n*/\nint deduceDatabaseType(const char *zName, int dfltZip){\n  FILE *f = fopen(zName, \"rb\");\n  size_t n;\n  int rc = SHELL_OPEN_UNSPEC;\n  char zBuf[100];\n  if( f==0 ){\n    if( dfltZip && sqlite3_strlike(\"%.zip\",zName,0)==0 ){\n       return SHELL_OPEN_ZIPFILE;\n    }else{\n       return SHELL_OPEN_NORMAL;\n    }\n  }\n  n = fread(zBuf, 16, 1, f);\n  if( n==1 && memcmp(zBuf, \"SQLite format 3\", 16)==0 ){\n    fclose(f);\n    return SHELL_OPEN_NORMAL;\n  }\n  fseek(f, -25, SEEK_END);\n  n = fread(zBuf, 25, 1, f);\n  if( n==1 && memcmp(zBuf, \"Start-Of-SQLite3-\", 17)==0 ){\n    rc = SHELL_OPEN_APPENDVFS;\n  }else{\n    fseek(f, -22, SEEK_END);\n    n = fread(zBuf, 22, 1, f);\n    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05\n       && zBuf[3]==0x06 ){\n      rc = SHELL_OPEN_ZIPFILE;\n    }else if( n==0 && dfltZip && sqlite3_strlike(\"%.zip\",zName,0)==0 ){\n      rc = SHELL_OPEN_ZIPFILE;\n    }\n  }\n  fclose(f);\n  return rc;  \n}\n\n#ifdef SQLITE_ENABLE_DESERIALIZE\n/*\n** Reconstruct an in-memory database using the output from the \"dbtotxt\"\n** program.  Read content from the file in p->zDbFilename.  If p->zDbFilename\n** is 0, then read from standard input.\n*/\nstatic unsigned char *readHexDb(ShellState *p, int *pnData){\n  unsigned char *a = 0;\n  int nLine;\n  int n = 0;\n  int pgsz = 0;\n  int iOffset = 0;\n  int j, k;\n  int rc;\n  FILE *in;\n  unsigned int x[16];\n  char zLine[1000];\n  if( p->zDbFilename ){\n    in = fopen(p->zDbFilename, \"r\");\n    if( in==0 ){\n      utf8_printf(stderr, \"cannot open \\\"%s\\\" for reading\\n\", p->zDbFilename);\n      return 0;\n    }\n    nLine = 0;\n  }else{\n    in = p->in;\n    nLine = p->lineno;\n    if( in==0 ) in = stdin;\n  }\n  *pnData = 0;\n  nLine++;\n  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;\n  rc = sscanf(zLine, \"| size %d pagesize %d\", &n, &pgsz);\n  if( rc!=2 ) goto readHexDb_error;\n  if( n<0 ) goto readHexDb_error;\n  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;\n  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */\n  a = sqlite3_malloc( n ? n : 1 );\n  if( a==0 ){\n    utf8_printf(stderr, \"Out of memory!\\n\");\n    goto readHexDb_error;\n  }\n  memset(a, 0, n);\n  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){\n    utf8_printf(stderr, \"invalid pagesize\\n\");\n    goto readHexDb_error;\n  }\n  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){\n    rc = sscanf(zLine, \"| page %d offset %d\", &j, &k);\n    if( rc==2 ){\n      iOffset = k;\n      continue;\n    }\n    if( strncmp(zLine, \"| end \", 6)==0 ){\n      break;\n    }\n    rc = sscanf(zLine,\"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x\",\n                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],\n                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);\n    if( rc==17 ){\n      k = iOffset+j;\n      if( k+16<=n ){\n        int ii;\n        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;\n      }\n    }\n  }\n  *pnData = n;\n  if( in!=p->in ){\n    fclose(in);\n  }else{\n    p->lineno = nLine;\n  }\n  return a;\n\nreadHexDb_error:\n  if( in!=p->in ){\n    fclose(in);\n  }else{\n    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){\n      nLine++;\n      if(strncmp(zLine, \"| end \", 6)==0 ) break;\n    }\n    p->lineno = nLine;\n  }\n  sqlite3_free(a);\n  utf8_printf(stderr,\"Error on line %d of --hexdb input\\n\", nLine);\n  return 0;\n}\n#endif /* SQLITE_ENABLE_DESERIALIZE */\n\n/*\n** Scalar function \"shell_int32\". The first argument to this function\n** must be a blob. The second a non-negative integer. This function\n** reads and returns a 32-bit big-endian integer from byte\n** offset (4*<arg2>) of the blob.\n*/\nstatic void shellInt32(\n  sqlite3_context *context, \n  int argc, \n  sqlite3_value **argv\n){\n  const unsigned char *pBlob;\n  int nBlob;\n  int iInt;\n\n  UNUSED_PARAMETER(argc);\n  nBlob = sqlite3_value_bytes(argv[0]);\n  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);\n  iInt = sqlite3_value_int(argv[1]);\n\n  if( iInt>=0 && (iInt+1)*4<=nBlob ){\n    const unsigned char *a = &pBlob[iInt*4];\n    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)\n                       + ((sqlite3_int64)a[1]<<16)\n                       + ((sqlite3_int64)a[2]<< 8)\n                       + ((sqlite3_int64)a[3]<< 0);\n    sqlite3_result_int64(context, iVal);\n  }\n}\n\n/*\n** Scalar function \"shell_idquote(X)\" returns string X quoted as an identifier,\n** using \"...\" with internal double-quote characters doubled.\n*/\nstatic void shellIdQuote(\n  sqlite3_context *context, \n  int argc, \n  sqlite3_value **argv\n){\n  const char *zName = (const char*)sqlite3_value_text(argv[0]);\n  UNUSED_PARAMETER(argc);\n  if( zName ){\n    char *z = sqlite3_mprintf(\"\\\"%w\\\"\", zName);\n    sqlite3_result_text(context, z, -1, sqlite3_free);\n  }\n}\n\n/*\n** Scalar function \"shell_escape_crnl\" used by the .recover command.\n** The argument passed to this function is the output of built-in\n** function quote(). If the first character of the input is \"'\", \n** indicating that the value passed to quote() was a text value,\n** then this function searches the input for \"\\n\" and \"\\r\" characters\n** and adds a wrapper similar to the following:\n**\n**   replace(replace(<input>, '\\n', char(10), '\\r', char(13));\n**\n** Or, if the first character of the input is not \"'\", then a copy\n** of the input is returned.\n*/\nstatic void shellEscapeCrnl(\n  sqlite3_context *context, \n  int argc, \n  sqlite3_value **argv\n){\n  const char *zText = (const char*)sqlite3_value_text(argv[0]);\n  UNUSED_PARAMETER(argc);\n  if( zText[0]=='\\'' ){\n    int nText = sqlite3_value_bytes(argv[0]);\n    int i;\n    char zBuf1[20];\n    char zBuf2[20];\n    const char *zNL = 0;\n    const char *zCR = 0;\n    int nCR = 0;\n    int nNL = 0;\n\n    for(i=0; zText[i]; i++){\n      if( zNL==0 && zText[i]=='\\n' ){\n        zNL = unused_string(zText, \"\\\\n\", \"\\\\012\", zBuf1);\n        nNL = (int)strlen(zNL);\n      }\n      if( zCR==0 && zText[i]=='\\r' ){\n        zCR = unused_string(zText, \"\\\\r\", \"\\\\015\", zBuf2);\n        nCR = (int)strlen(zCR);\n      }\n    }\n\n    if( zNL || zCR ){\n      int iOut = 0;\n      i64 nMax = (nNL > nCR) ? nNL : nCR;\n      i64 nAlloc = nMax * nText + (nMax+64)*2;\n      char *zOut = (char*)sqlite3_malloc64(nAlloc);\n      if( zOut==0 ){\n        sqlite3_result_error_nomem(context);\n        return;\n      }\n\n      if( zNL && zCR ){\n        memcpy(&zOut[iOut], \"replace(replace(\", 16);\n        iOut += 16;\n      }else{\n        memcpy(&zOut[iOut], \"replace(\", 8);\n        iOut += 8;\n      }\n      for(i=0; zText[i]; i++){\n        if( zText[i]=='\\n' ){\n          memcpy(&zOut[iOut], zNL, nNL);\n          iOut += nNL;\n        }else if( zText[i]=='\\r' ){\n          memcpy(&zOut[iOut], zCR, nCR);\n          iOut += nCR;\n        }else{\n          zOut[iOut] = zText[i];\n          iOut++;\n        }\n      }\n\n      if( zNL ){\n        memcpy(&zOut[iOut], \",'\", 2); iOut += 2;\n        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;\n        memcpy(&zOut[iOut], \"', char(10))\", 12); iOut += 12;\n      }\n      if( zCR ){\n        memcpy(&zOut[iOut], \",'\", 2); iOut += 2;\n        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;\n        memcpy(&zOut[iOut], \"', char(13))\", 12); iOut += 12;\n      }\n\n      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);\n      sqlite3_free(zOut);\n      return;\n    }\n  }\n\n  sqlite3_result_value(context, argv[0]);\n}\n\n/* Flags for open_db().\n**\n** The default behavior of open_db() is to exit(1) if the database fails to\n** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error\n** but still returns without calling exit.\n**\n** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a\n** ZIP archive if the file does not exist or is empty and its name matches\n** the *.zip pattern.\n*/\n#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */\n#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */\n\n/*\n** Make sure the database is open.  If it is not, then open it.  If\n** the database fails to open, print an error message and exit.\n*/\nstatic void open_db(ShellState *p, int openFlags){\n  if( p->db==0 ){\n    if( p->openMode==SHELL_OPEN_UNSPEC ){\n      if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){\n        p->openMode = SHELL_OPEN_NORMAL;\n      }else{\n        p->openMode = (u8)deduceDatabaseType(p->zDbFilename, \n                             (openFlags & OPEN_DB_ZIPFILE)!=0);\n      }\n    }\n    switch( p->openMode ){\n      case SHELL_OPEN_APPENDVFS: {\n        sqlite3_open_v2(p->zDbFilename, &p->db, \n           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, \"apndvfs\");\n        break;\n      }\n      case SHELL_OPEN_HEXDB:\n      case SHELL_OPEN_DESERIALIZE: {\n        sqlite3_open(0, &p->db);\n        break;\n      }\n      case SHELL_OPEN_ZIPFILE: {\n        sqlite3_open(\":memory:\", &p->db);\n        break;\n      }\n      case SHELL_OPEN_READONLY: {\n        sqlite3_open_v2(p->zDbFilename, &p->db,\n            SQLITE_OPEN_READONLY|p->openFlags, 0);\n        break;\n      }\n      case SHELL_OPEN_UNSPEC:\n      case SHELL_OPEN_NORMAL: {\n        sqlite3_open_v2(p->zDbFilename, &p->db,\n           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);\n        break;\n      }\n    }\n    globalDb = p->db;\n    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){\n      utf8_printf(stderr,\"Error: unable to open database \\\"%s\\\": %s\\n\",\n          p->zDbFilename, sqlite3_errmsg(p->db));\n      if( openFlags & OPEN_DB_KEEPALIVE ){\n        sqlite3_open(\":memory:\", &p->db);\n        return;\n      }\n      exit(1);\n    }\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\n    sqlite3_enable_load_extension(p->db, 1);\n#endif\n    sqlite3_fileio_init(p->db, 0, 0);\n    sqlite3_shathree_init(p->db, 0, 0);\n    sqlite3_completion_init(p->db, 0, 0);\n    sqlite3_uint_init(p->db, 0, 0);\n#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)\n    sqlite3_dbdata_init(p->db, 0, 0);\n#endif\n#ifdef SQLITE_HAVE_ZLIB\n    sqlite3_zipfile_init(p->db, 0, 0);\n    sqlite3_sqlar_init(p->db, 0, 0);\n#endif\n    sqlite3_create_function(p->db, \"shell_add_schema\", 3, SQLITE_UTF8, 0,\n                            shellAddSchemaName, 0, 0);\n    sqlite3_create_function(p->db, \"shell_module_schema\", 1, SQLITE_UTF8, 0,\n                            shellModuleSchema, 0, 0);\n    sqlite3_create_function(p->db, \"shell_putsnl\", 1, SQLITE_UTF8, p,\n                            shellPutsFunc, 0, 0);\n    sqlite3_create_function(p->db, \"shell_escape_crnl\", 1, SQLITE_UTF8, 0,\n                            shellEscapeCrnl, 0, 0);\n    sqlite3_create_function(p->db, \"shell_int32\", 2, SQLITE_UTF8, 0,\n                            shellInt32, 0, 0);\n    sqlite3_create_function(p->db, \"shell_idquote\", 1, SQLITE_UTF8, 0,\n                            shellIdQuote, 0, 0);\n#ifndef SQLITE_NOHAVE_SYSTEM\n    sqlite3_create_function(p->db, \"edit\", 1, SQLITE_UTF8, 0,\n                            editFunc, 0, 0);\n    sqlite3_create_function(p->db, \"edit\", 2, SQLITE_UTF8, 0,\n                            editFunc, 0, 0);\n#endif\n    if( p->openMode==SHELL_OPEN_ZIPFILE ){\n      char *zSql = sqlite3_mprintf(\n         \"CREATE VIRTUAL TABLE zip USING zipfile(%Q);\", p->zDbFilename);\n      sqlite3_exec(p->db, zSql, 0, 0, 0);\n      sqlite3_free(zSql);\n    }\n#ifdef SQLITE_ENABLE_DESERIALIZE\n    else\n    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){\n      int rc;\n      int nData = 0;\n      unsigned char *aData;\n      if( p->openMode==SHELL_OPEN_DESERIALIZE ){\n        aData = (unsigned char*)readFile(p->zDbFilename, &nData);\n      }else{\n        aData = readHexDb(p, &nData);\n        if( aData==0 ){\n          return;\n        }\n      }\n      rc = sqlite3_deserialize(p->db, \"main\", aData, nData, nData,\n                   SQLITE_DESERIALIZE_RESIZEABLE |\n                   SQLITE_DESERIALIZE_FREEONCLOSE);\n      if( rc ){\n        utf8_printf(stderr, \"Error: sqlite3_deserialize() returns %d\\n\", rc);\n      }\n      if( p->szMax>0 ){\n        sqlite3_file_control(p->db, \"main\", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);\n      }\n    }\n#endif\n  }\n}\n\n/*\n** Attempt to close the databaes connection.  Report errors.\n*/\nvoid close_db(sqlite3 *db){\n  int rc = sqlite3_close(db);\n  if( rc ){\n    utf8_printf(stderr, \"Error: sqlite3_close() returns %d: %s\\n\",\n        rc, sqlite3_errmsg(db));\n  } \n}\n\n#if HAVE_READLINE || HAVE_EDITLINE\n/*\n** Readline completion callbacks\n*/\nstatic char *readline_completion_generator(const char *text, int state){\n  static sqlite3_stmt *pStmt = 0;\n  char *zRet;\n  if( state==0 ){\n    char *zSql;\n    sqlite3_finalize(pStmt);\n    zSql = sqlite3_mprintf(\"SELECT DISTINCT candidate COLLATE nocase\"\n                           \"  FROM completion(%Q) ORDER BY 1\", text);\n    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);\n    sqlite3_free(zSql);\n  }\n  if( sqlite3_step(pStmt)==SQLITE_ROW ){\n    zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));\n  }else{\n    sqlite3_finalize(pStmt);\n    pStmt = 0;\n    zRet = 0;\n  }\n  return zRet;\n}\nstatic char **readline_completion(const char *zText, int iStart, int iEnd){\n  rl_attempted_completion_over = 1;\n  return rl_completion_matches(zText, readline_completion_generator);\n}\n\n#elif HAVE_LINENOISE\n/*\n** Linenoise completion callback\n*/\nstatic void linenoise_completion(const char *zLine, linenoiseCompletions *lc){\n  int nLine = strlen30(zLine);\n  int i, iStart;\n  sqlite3_stmt *pStmt = 0;\n  char *zSql;\n  char zBuf[1000];\n\n  if( nLine>sizeof(zBuf)-30 ) return;\n  if( zLine[0]=='.' || zLine[0]=='#') return;\n  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}\n  if( i==nLine-1 ) return;\n  iStart = i+1;\n  memcpy(zBuf, zLine, iStart);\n  zSql = sqlite3_mprintf(\"SELECT DISTINCT candidate COLLATE nocase\"\n                         \"  FROM completion(%Q,%Q) ORDER BY 1\",\n                         &zLine[iStart], zLine);\n  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);\n  sqlite3_free(zSql);\n  sqlite3_exec(globalDb, \"PRAGMA page_count\", 0, 0, 0); /* Load the schema */\n  while( sqlite3_step(pStmt)==SQLITE_ROW ){\n    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);\n    int nCompletion = sqlite3_column_bytes(pStmt, 0);\n    if( iStart+nCompletion < sizeof(zBuf)-1 ){\n      memcpy(zBuf+iStart, zCompletion, nCompletion+1);\n      linenoiseAddCompletion(lc, zBuf);\n    }\n  }\n  sqlite3_finalize(pStmt);\n}\n#endif\n\n/*\n** Do C-language style dequoting.\n**\n**    \\a    -> alarm\n**    \\b    -> backspace\n**    \\t    -> tab\n**    \\n    -> newline\n**    \\v    -> vertical tab\n**    \\f    -> form feed\n**    \\r    -> carriage return\n**    \\s    -> space\n**    \\\"    -> \"\n**    \\'    -> '\n**    \\\\    -> backslash\n**    \\NNN  -> ascii character NNN in octal\n*/\nstatic void resolve_backslashes(char *z){\n  int i, j;\n  char c;\n  while( *z && *z!='\\\\' ) z++;\n  for(i=j=0; (c = z[i])!=0; i++, j++){\n    if( c=='\\\\' && z[i+1]!=0 ){\n      c = z[++i];\n      if( c=='a' ){\n        c = '\\a';\n      }else if( c=='b' ){\n        c = '\\b';\n      }else if( c=='t' ){\n        c = '\\t';\n      }else if( c=='n' ){\n        c = '\\n';\n      }else if( c=='v' ){\n        c = '\\v';\n      }else if( c=='f' ){\n        c = '\\f';\n      }else if( c=='r' ){\n        c = '\\r';\n      }else if( c=='\"' ){\n        c = '\"';\n      }else if( c=='\\'' ){\n        c = '\\'';\n      }else if( c=='\\\\' ){\n        c = '\\\\';\n      }else if( c>='0' && c<='7' ){\n        c -= '0';\n        if( z[i+1]>='0' && z[i+1]<='7' ){\n          i++;\n          c = (c<<3) + z[i] - '0';\n          if( z[i+1]>='0' && z[i+1]<='7' ){\n            i++;\n            c = (c<<3) + z[i] - '0';\n          }\n        }\n      }\n    }\n    z[j] = c;\n  }\n  if( j<i ) z[j] = 0;\n}\n\n/*\n** Interpret zArg as either an integer or a boolean value.  Return 1 or 0\n** for TRUE and FALSE.  Return the integer value if appropriate.\n*/\nstatic int booleanValue(const char *zArg){\n  int i;\n  if( zArg[0]=='0' && zArg[1]=='x' ){\n    for(i=2; hexDigitValue(zArg[i])>=0; i++){}\n  }else{\n    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}\n  }\n  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);\n  if( sqlite3_stricmp(zArg, \"on\")==0 || sqlite3_stricmp(zArg,\"yes\")==0 ){\n    return 1;\n  }\n  if( sqlite3_stricmp(zArg, \"off\")==0 || sqlite3_stricmp(zArg,\"no\")==0 ){\n    return 0;\n  }\n  utf8_printf(stderr, \"ERROR: Not a boolean value: \\\"%s\\\". Assuming \\\"no\\\".\\n\",\n          zArg);\n  return 0;\n}\n\n/*\n** Set or clear a shell flag according to a boolean value.\n*/\nstatic void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){\n  if( booleanValue(zArg) ){\n    ShellSetFlag(p, mFlag);\n  }else{\n    ShellClearFlag(p, mFlag);\n  }\n}\n\n/*\n** Close an output file, assuming it is not stderr or stdout\n*/\nstatic void output_file_close(FILE *f){\n  if( f && f!=stdout && f!=stderr ) fclose(f);\n}\n\n/*\n** Try to open an output file.   The names \"stdout\" and \"stderr\" are\n** recognized and do the right thing.  NULL is returned if the output\n** filename is \"off\".\n*/\nstatic FILE *output_file_open(const char *zFile, int bTextMode){\n  FILE *f;\n  if( strcmp(zFile,\"stdout\")==0 ){\n    f = stdout;\n  }else if( strcmp(zFile, \"stderr\")==0 ){\n    f = stderr;\n  }else if( strcmp(zFile, \"off\")==0 ){\n    f = 0;\n  }else{\n    f = fopen(zFile, bTextMode ? \"w\" : \"wb\");\n    if( f==0 ){\n      utf8_printf(stderr, \"Error: cannot open \\\"%s\\\"\\n\", zFile);\n    }\n  }\n  return f;\n}\n\n#ifndef SQLITE_OMIT_TRACE\n/*\n** A routine for handling output from sqlite3_trace().\n*/\nstatic int sql_trace_callback(\n  unsigned mType,         /* The trace type */\n  void *pArg,             /* The ShellState pointer */\n  void *pP,               /* Usually a pointer to sqlite_stmt */\n  void *pX                /* Auxiliary output */\n){\n  ShellState *p = (ShellState*)pArg;\n  sqlite3_stmt *pStmt;\n  const char *zSql;\n  int nSql;\n  if( p->traceOut==0 ) return 0;\n  if( mType==SQLITE_TRACE_CLOSE ){\n    utf8_printf(p->traceOut, \"-- closing database connection\\n\");\n    return 0;\n  }\n  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){\n    zSql = (const char*)pX;\n  }else{\n    pStmt = (sqlite3_stmt*)pP;\n    switch( p->eTraceType ){\n      case SHELL_TRACE_EXPANDED: {\n        zSql = sqlite3_expanded_sql(pStmt);\n        break;\n      }\n#ifdef SQLITE_ENABLE_NORMALIZE\n      case SHELL_TRACE_NORMALIZED: {\n        zSql = sqlite3_normalized_sql(pStmt);\n        break;\n      }\n#endif\n      default: {\n        zSql = sqlite3_sql(pStmt);\n        break;\n      }\n    }\n  }\n  if( zSql==0 ) return 0;\n  nSql = strlen30(zSql);\n  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }\n  switch( mType ){\n    case SQLITE_TRACE_ROW:\n    case SQLITE_TRACE_STMT: {\n      utf8_printf(p->traceOut, \"%.*s;\\n\", nSql, zSql);\n      break;\n    }\n    case SQLITE_TRACE_PROFILE: {\n      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;\n      utf8_printf(p->traceOut, \"%.*s; -- %lld ns\\n\", nSql, zSql, nNanosec);\n      break;\n    }\n  }\n  return 0;\n}\n#endif\n\n/*\n** A no-op routine that runs with the \".breakpoint\" doc-command.  This is\n** a useful spot to set a debugger breakpoint.\n*/\nstatic void test_breakpoint(void){\n  static int nCall = 0;\n  nCall++;\n}\n\n/*\n** An object used to read a CSV and other files for import.\n*/\ntypedef struct ImportCtx ImportCtx;\nstruct ImportCtx {\n  const char *zFile;  /* Name of the input file */\n  FILE *in;           /* Read the CSV text from this input stream */\n  char *z;            /* Accumulated text for a field */\n  int n;              /* Number of bytes in z */\n  int nAlloc;         /* Space allocated for z[] */\n  int nLine;          /* Current line number */\n  int nRow;           /* Number of rows imported */\n  int nErr;           /* Number of errors encountered */\n  int bNotFirst;      /* True if one or more bytes already read */\n  int cTerm;          /* Character that terminated the most recent field */\n  int cColSep;        /* The column separator character.  (Usually \",\") */\n  int cRowSep;        /* The row separator character.  (Usually \"\\n\") */\n};\n\n/* Append a single byte to z[] */\nstatic void import_append_char(ImportCtx *p, int c){\n  if( p->n+1>=p->nAlloc ){\n    p->nAlloc += p->nAlloc + 100;\n    p->z = sqlite3_realloc64(p->z, p->nAlloc);\n    if( p->z==0 ) shell_out_of_memory();\n  }\n  p->z[p->n++] = (char)c;\n}\n\n/* Read a single field of CSV text.  Compatible with rfc4180 and extended\n** with the option of having a separator other than \",\".\n**\n**   +  Input comes from p->in.\n**   +  Store results in p->z of length p->n.  Space to hold p->z comes\n**      from sqlite3_malloc64().\n**   +  Use p->cSep as the column separator.  The default is \",\".\n**   +  Use p->rSep as the row separator.  The default is \"\\n\".\n**   +  Keep track of the line number in p->nLine.\n**   +  Store the character that terminates the field in p->cTerm.  Store\n**      EOF on end-of-file.\n**   +  Report syntax errors on stderr\n*/\nstatic char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){\n  int c;\n  int cSep = p->cColSep;\n  int rSep = p->cRowSep;\n  p->n = 0;\n  c = fgetc(p->in);\n  if( c==EOF || seenInterrupt ){\n    p->cTerm = EOF;\n    return 0;\n  }\n  if( c=='\"' ){\n    int pc, ppc;\n    int startLine = p->nLine;\n    int cQuote = c;\n    pc = ppc = 0;\n    while( 1 ){\n      c = fgetc(p->in);\n      if( c==rSep ) p->nLine++;\n      if( c==cQuote ){\n        if( pc==cQuote ){\n          pc = 0;\n          continue;\n        }\n      }\n      if( (c==cSep && pc==cQuote)\n       || (c==rSep && pc==cQuote)\n       || (c==rSep && pc=='\\r' && ppc==cQuote)\n       || (c==EOF && pc==cQuote)\n      ){\n        do{ p->n--; }while( p->z[p->n]!=cQuote );\n        p->cTerm = c;\n        break;\n      }\n      if( pc==cQuote && c!='\\r' ){\n        utf8_printf(stderr, \"%s:%d: unescaped %c character\\n\",\n                p->zFile, p->nLine, cQuote);\n      }\n      if( c==EOF ){\n        utf8_printf(stderr, \"%s:%d: unterminated %c-quoted field\\n\",\n                p->zFile, startLine, cQuote);\n        p->cTerm = c;\n        break;\n      }\n      import_append_char(p, c);\n      ppc = pc;\n      pc = c;\n    }\n  }else{\n    /* If this is the first field being parsed and it begins with the\n    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */\n    if( (c&0xff)==0xef && p->bNotFirst==0 ){\n      import_append_char(p, c);\n      c = fgetc(p->in);\n      if( (c&0xff)==0xbb ){\n        import_append_char(p, c);\n        c = fgetc(p->in);\n        if( (c&0xff)==0xbf ){\n          p->bNotFirst = 1;\n          p->n = 0;\n          return csv_read_one_field(p);\n        }\n      }\n    }\n    while( c!=EOF && c!=cSep && c!=rSep ){\n      import_append_char(p, c);\n      c = fgetc(p->in);\n    }\n    if( c==rSep ){\n      p->nLine++;\n      if( p->n>0 && p->z[p->n-1]=='\\r' ) p->n--;\n    }\n    p->cTerm = c;\n  }\n  if( p->z ) p->z[p->n] = 0;\n  p->bNotFirst = 1;\n  return p->z;\n}\n\n/* Read a single field of ASCII delimited text.\n**\n**   +  Input comes from p->in.\n**   +  Store results in p->z of length p->n.  Space to hold p->z comes\n**      from sqlite3_malloc64().\n**   +  Use p->cSep as the column separator.  The default is \"\\x1F\".\n**   +  Use p->rSep as the row separator.  The default is \"\\x1E\".\n**   +  Keep track of the row number in p->nLine.\n**   +  Store the character that terminates the field in p->cTerm.  Store\n**      EOF on end-of-file.\n**   +  Report syntax errors on stderr\n*/\nstatic char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){\n  int c;\n  int cSep = p->cColSep;\n  int rSep = p->cRowSep;\n  p->n = 0;\n  c = fgetc(p->in);\n  if( c==EOF || seenInterrupt ){\n    p->cTerm = EOF;\n    return 0;\n  }\n  while( c!=EOF && c!=cSep && c!=rSep ){\n    import_append_char(p, c);\n    c = fgetc(p->in);\n  }\n  if( c==rSep ){\n    p->nLine++;\n  }\n  p->cTerm = c;\n  if( p->z ) p->z[p->n] = 0;\n  return p->z;\n}\n\n/*\n** Try to transfer data for table zTable.  If an error is seen while\n** moving forward, try to go backwards.  The backwards movement won't\n** work for WITHOUT ROWID tables.\n*/\nstatic void tryToCloneData(\n  ShellState *p,\n  sqlite3 *newDb,\n  const char *zTable\n){\n  sqlite3_stmt *pQuery = 0;\n  sqlite3_stmt *pInsert = 0;\n  char *zQuery = 0;\n  char *zInsert = 0;\n  int rc;\n  int i, j, n;\n  int nTable = strlen30(zTable);\n  int k = 0;\n  int cnt = 0;\n  const int spinRate = 10000;\n\n  zQuery = sqlite3_mprintf(\"SELECT * FROM \\\"%w\\\"\", zTable);\n  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);\n  if( rc ){\n    utf8_printf(stderr, \"Error %d: %s on [%s]\\n\",\n            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),\n            zQuery);\n    goto end_data_xfer;\n  }\n  n = sqlite3_column_count(pQuery);\n  zInsert = sqlite3_malloc64(200 + nTable + n*3);\n  if( zInsert==0 ) shell_out_of_memory();\n  sqlite3_snprintf(200+nTable,zInsert,\n                   \"INSERT OR IGNORE INTO \\\"%s\\\" VALUES(?\", zTable);\n  i = strlen30(zInsert);\n  for(j=1; j<n; j++){\n    memcpy(zInsert+i, \",?\", 2);\n    i += 2;\n  }\n  memcpy(zInsert+i, \");\", 3);\n  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);\n  if( rc ){\n    utf8_printf(stderr, \"Error %d: %s on [%s]\\n\",\n            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),\n            zQuery);\n    goto end_data_xfer;\n  }\n  for(k=0; k<2; k++){\n    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){\n      for(i=0; i<n; i++){\n        switch( sqlite3_column_type(pQuery, i) ){\n          case SQLITE_NULL: {\n            sqlite3_bind_null(pInsert, i+1);\n            break;\n          }\n          case SQLITE_INTEGER: {\n            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));\n            break;\n          }\n          case SQLITE_FLOAT: {\n            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));\n            break;\n          }\n          case SQLITE_TEXT: {\n            sqlite3_bind_text(pInsert, i+1,\n                             (const char*)sqlite3_column_text(pQuery,i),\n                             -1, SQLITE_STATIC);\n            break;\n          }\n          case SQLITE_BLOB: {\n            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),\n                                            sqlite3_column_bytes(pQuery,i),\n                                            SQLITE_STATIC);\n            break;\n          }\n        }\n      } /* End for */\n      rc = sqlite3_step(pInsert);\n      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){\n        utf8_printf(stderr, \"Error %d: %s\\n\", sqlite3_extended_errcode(newDb),\n                        sqlite3_errmsg(newDb));\n      }\n      sqlite3_reset(pInsert);\n      cnt++;\n      if( (cnt%spinRate)==0 ){\n        printf(\"%c\\b\", \"|/-\\\\\"[(cnt/spinRate)%4]);\n        fflush(stdout);\n      }\n    } /* End while */\n    if( rc==SQLITE_DONE ) break;\n    sqlite3_finalize(pQuery);\n    sqlite3_free(zQuery);\n    zQuery = sqlite3_mprintf(\"SELECT * FROM \\\"%w\\\" ORDER BY rowid DESC;\",\n                             zTable);\n    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);\n    if( rc ){\n      utf8_printf(stderr, \"Warning: cannot step \\\"%s\\\" backwards\", zTable);\n      break;\n    }\n  } /* End for(k=0...) */\n\nend_data_xfer:\n  sqlite3_finalize(pQuery);\n  sqlite3_finalize(pInsert);\n  sqlite3_free(zQuery);\n  sqlite3_free(zInsert);\n}\n\n\n/*\n** Try to transfer all rows of the schema that match zWhere.  For\n** each row, invoke xForEach() on the object defined by that row.\n** If an error is encountered while moving forward through the\n** sqlite_master table, try again moving backwards.\n*/\nstatic void tryToCloneSchema(\n  ShellState *p,\n  sqlite3 *newDb,\n  const char *zWhere,\n  void (*xForEach)(ShellState*,sqlite3*,const char*)\n){\n  sqlite3_stmt *pQuery = 0;\n  char *zQuery = 0;\n  int rc;\n  const unsigned char *zName;\n  const unsigned char *zSql;\n  char *zErrMsg = 0;\n\n  zQuery = sqlite3_mprintf(\"SELECT name, sql FROM sqlite_master\"\n                           \" WHERE %s\", zWhere);\n  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);\n  if( rc ){\n    utf8_printf(stderr, \"Error: (%d) %s on [%s]\\n\",\n                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),\n                    zQuery);\n    goto end_schema_xfer;\n  }\n  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){\n    zName = sqlite3_column_text(pQuery, 0);\n    zSql = sqlite3_column_text(pQuery, 1);\n    printf(\"%s... \", zName); fflush(stdout);\n    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);\n    if( zErrMsg ){\n      utf8_printf(stderr, \"Error: %s\\nSQL: [%s]\\n\", zErrMsg, zSql);\n      sqlite3_free(zErrMsg);\n      zErrMsg = 0;\n    }\n    if( xForEach ){\n      xForEach(p, newDb, (const char*)zName);\n    }\n    printf(\"done\\n\");\n  }\n  if( rc!=SQLITE_DONE ){\n    sqlite3_finalize(pQuery);\n    sqlite3_free(zQuery);\n    zQuery = sqlite3_mprintf(\"SELECT name, sql FROM sqlite_master\"\n                             \" WHERE %s ORDER BY rowid DESC\", zWhere);\n    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);\n    if( rc ){\n      utf8_printf(stderr, \"Error: (%d) %s on [%s]\\n\",\n                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),\n                      zQuery);\n      goto end_schema_xfer;\n    }\n    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){\n      zName = sqlite3_column_text(pQuery, 0);\n      zSql = sqlite3_column_text(pQuery, 1);\n      printf(\"%s... \", zName); fflush(stdout);\n      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);\n      if( zErrMsg ){\n        utf8_printf(stderr, \"Error: %s\\nSQL: [%s]\\n\", zErrMsg, zSql);\n        sqlite3_free(zErrMsg);\n        zErrMsg = 0;\n      }\n      if( xForEach ){\n        xForEach(p, newDb, (const char*)zName);\n      }\n      printf(\"done\\n\");\n    }\n  }\nend_schema_xfer:\n  sqlite3_finalize(pQuery);\n  sqlite3_free(zQuery);\n}\n\n/*\n** Open a new database file named \"zNewDb\".  Try to recover as much information\n** as possible out of the main database (which might be corrupt) and write it\n** into zNewDb.\n*/\nstatic void tryToClone(ShellState *p, const char *zNewDb){\n  int rc;\n  sqlite3 *newDb = 0;\n  if( access(zNewDb,0)==0 ){\n    utf8_printf(stderr, \"File \\\"%s\\\" already exists.\\n\", zNewDb);\n    return;\n  }\n  rc = sqlite3_open(zNewDb, &newDb);\n  if( rc ){\n    utf8_printf(stderr, \"Cannot create output database: %s\\n\",\n            sqlite3_errmsg(newDb));\n  }else{\n    sqlite3_exec(p->db, \"PRAGMA writable_schema=ON;\", 0, 0, 0);\n    sqlite3_exec(newDb, \"BEGIN EXCLUSIVE;\", 0, 0, 0);\n    tryToCloneSchema(p, newDb, \"type='table'\", tryToCloneData);\n    tryToCloneSchema(p, newDb, \"type!='table'\", 0);\n    sqlite3_exec(newDb, \"COMMIT;\", 0, 0, 0);\n    sqlite3_exec(p->db, \"PRAGMA writable_schema=OFF;\", 0, 0, 0);\n  }\n  close_db(newDb);\n}\n\n/*\n** Change the output file back to stdout.\n**\n** If the p->doXdgOpen flag is set, that means the output was being\n** redirected to a temporary file named by p->zTempFile.  In that case,\n** launch start/open/xdg-open on that temporary file.\n*/\nstatic void output_reset(ShellState *p){\n  if( p->outfile[0]=='|' ){\n#ifndef SQLITE_OMIT_POPEN\n    pclose(p->out);\n#endif\n  }else{\n    output_file_close(p->out);\n#ifndef SQLITE_NOHAVE_SYSTEM\n    if( p->doXdgOpen ){\n      const char *zXdgOpenCmd =\n#if defined(_WIN32)\n      \"start\";\n#elif defined(__APPLE__)\n      \"open\";\n#else\n      \"xdg-open\";\n#endif\n      char *zCmd;\n      zCmd = sqlite3_mprintf(\"%s %s\", zXdgOpenCmd, p->zTempFile);\n      if( system(zCmd) ){\n        utf8_printf(stderr, \"Failed: [%s]\\n\", zCmd);\n      }else{\n        /* Give the start/open/xdg-open command some time to get\n        ** going before we continue, and potential delete the\n        ** p->zTempFile data file out from under it */\n        sqlite3_sleep(2000);\n      }\n      sqlite3_free(zCmd);\n      outputModePop(p);\n      p->doXdgOpen = 0;\n    }\n#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */\n  }\n  p->outfile[0] = 0;\n  p->out = stdout;\n}\n\n/*\n** Run an SQL command and return the single integer result.\n*/\nstatic int db_int(ShellState *p, const char *zSql){\n  sqlite3_stmt *pStmt;\n  int res = 0;\n  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);\n  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){\n    res = sqlite3_column_int(pStmt,0);\n  }\n  sqlite3_finalize(pStmt);\n  return res;\n}\n\n/*\n** Convert a 2-byte or 4-byte big-endian integer into a native integer\n*/\nstatic unsigned int get2byteInt(unsigned char *a){\n  return (a[0]<<8) + a[1];\n}\nstatic unsigned int get4byteInt(unsigned char *a){\n  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];\n}\n\n/*\n** Implementation of the \".dbinfo\" command.\n**\n** Return 1 on error, 2 to exit, and 0 otherwise.\n*/\nstatic int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){\n  static const struct { const char *zName; int ofst; } aField[] = {\n     { \"file change counter:\",  24  },\n     { \"database page count:\",  28  },\n     { \"freelist page count:\",  36  },\n     { \"schema cookie:\",        40  },\n     { \"schema format:\",        44  },\n     { \"default cache size:\",   48  },\n     { \"autovacuum top root:\",  52  },\n     { \"incremental vacuum:\",   64  },\n     { \"text encoding:\",        56  },\n     { \"user version:\",         60  },\n     { \"application id:\",       68  },\n     { \"software version:\",     96  },\n  };\n  static const struct { const char *zName; const char *zSql; } aQuery[] = {\n     { \"number of tables:\",\n       \"SELECT count(*) FROM %s WHERE type='table'\" },\n     { \"number of indexes:\",\n       \"SELECT count(*) FROM %s WHERE type='index'\" },\n     { \"number of triggers:\",\n       \"SELECT count(*) FROM %s WHERE type='trigger'\" },\n     { \"number of views:\",\n       \"SELECT count(*) FROM %s WHERE type='view'\" },\n     { \"schema size:\",\n       \"SELECT total(length(sql)) FROM %s\" },\n  };\n  int i, rc;\n  unsigned iDataVersion;\n  char *zSchemaTab;\n  char *zDb = nArg>=2 ? azArg[1] : \"main\";\n  sqlite3_stmt *pStmt = 0;\n  unsigned char aHdr[100];\n  open_db(p, 0);\n  if( p->db==0 ) return 1;\n  rc = sqlite3_prepare_v2(p->db,\n             \"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1\",\n             -1, &pStmt, 0);\n  if( rc ){\n    utf8_printf(stderr, \"error: %s\\n\", sqlite3_errmsg(p->db));\n    sqlite3_finalize(pStmt);\n    return 1;\n  }\n  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);\n  if( sqlite3_step(pStmt)==SQLITE_ROW\n   && sqlite3_column_bytes(pStmt,0)>100\n  ){\n    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);\n    sqlite3_finalize(pStmt);\n  }else{\n    raw_printf(stderr, \"unable to read database header\\n\");\n    sqlite3_finalize(pStmt);\n    return 1;\n  }\n  i = get2byteInt(aHdr+16);\n  if( i==1 ) i = 65536;\n  utf8_printf(p->out, \"%-20s %d\\n\", \"database page size:\", i);\n  utf8_printf(p->out, \"%-20s %d\\n\", \"write format:\", aHdr[18]);\n  utf8_printf(p->out, \"%-20s %d\\n\", \"read format:\", aHdr[19]);\n  utf8_printf(p->out, \"%-20s %d\\n\", \"reserved bytes:\", aHdr[20]);\n  for(i=0; i<ArraySize(aField); i++){\n    int ofst = aField[i].ofst;\n    unsigned int val = get4byteInt(aHdr + ofst);\n    utf8_printf(p->out, \"%-20s %u\", aField[i].zName, val);\n    switch( ofst ){\n      case 56: {\n        if( val==1 ) raw_printf(p->out, \" (utf8)\");\n        if( val==2 ) raw_printf(p->out, \" (utf16le)\");\n        if( val==3 ) raw_printf(p->out, \" (utf16be)\");\n      }\n    }\n    raw_printf(p->out, \"\\n\");\n  }\n  if( zDb==0 ){\n    zSchemaTab = sqlite3_mprintf(\"main.sqlite_master\");\n  }else if( strcmp(zDb,\"temp\")==0 ){\n    zSchemaTab = sqlite3_mprintf(\"%s\", \"sqlite_temp_master\");\n  }else{\n    zSchemaTab = sqlite3_mprintf(\"\\\"%w\\\".sqlite_master\", zDb);\n  }\n  for(i=0; i<ArraySize(aQuery); i++){\n    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);\n    int val = db_int(p, zSql);\n    sqlite3_free(zSql);\n    utf8_printf(p->out, \"%-20s %d\\n\", aQuery[i].zName, val);\n  }\n  sqlite3_free(zSchemaTab);\n  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);\n  utf8_printf(p->out, \"%-20s %u\\n\", \"data version\", iDataVersion);\n  return 0;\n}\n\n/*\n** Print the current sqlite3_errmsg() value to stderr and return 1.\n*/\nstatic int shellDatabaseError(sqlite3 *db){\n  const char *zErr = sqlite3_errmsg(db);\n  utf8_printf(stderr, \"Error: %s\\n\", zErr);\n  return 1;\n}\n\n/*\n** Compare the pattern in zGlob[] against the text in z[].  Return TRUE\n** if they match and FALSE (0) if they do not match.\n**\n** Globbing rules:\n**\n**      '*'       Matches any sequence of zero or more characters.\n**\n**      '?'       Matches exactly one character.\n**\n**     [...]      Matches one character from the enclosed list of\n**                characters.\n**\n**     [^...]     Matches one character not in the enclosed list.\n**\n**      '#'       Matches any sequence of one or more digits with an\n**                optional + or - sign in front\n**\n**      ' '       Any span of whitespace matches any other span of\n**                whitespace.\n**\n** Extra whitespace at the end of z[] is ignored.\n*/\nstatic int testcase_glob(const char *zGlob, const char *z){\n  int c, c2;\n  int invert;\n  int seen;\n\n  while( (c = (*(zGlob++)))!=0 ){\n    if( IsSpace(c) ){\n      if( !IsSpace(*z) ) return 0;\n      while( IsSpace(*zGlob) ) zGlob++;\n      while( IsSpace(*z) ) z++;\n    }else if( c=='*' ){\n      while( (c=(*(zGlob++))) == '*' || c=='?' ){\n        if( c=='?' && (*(z++))==0 ) return 0;\n      }\n      if( c==0 ){\n        return 1;\n      }else if( c=='[' ){\n        while( *z && testcase_glob(zGlob-1,z)==0 ){\n          z++;\n        }\n        return (*z)!=0;\n      }\n      while( (c2 = (*(z++)))!=0 ){\n        while( c2!=c ){\n          c2 = *(z++);\n          if( c2==0 ) return 0;\n        }\n        if( testcase_glob(zGlob,z) ) return 1;\n      }\n      return 0;\n    }else if( c=='?' ){\n      if( (*(z++))==0 ) return 0;\n    }else if( c=='[' ){\n      int prior_c = 0;\n      seen = 0;\n      invert = 0;\n      c = *(z++);\n      if( c==0 ) return 0;\n      c2 = *(zGlob++);\n      if( c2=='^' ){\n        invert = 1;\n        c2 = *(zGlob++);\n      }\n      if( c2==']' ){\n        if( c==']' ) seen = 1;\n        c2 = *(zGlob++);\n      }\n      while( c2 && c2!=']' ){\n        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){\n          c2 = *(zGlob++);\n          if( c>=prior_c && c<=c2 ) seen = 1;\n          prior_c = 0;\n        }else{\n          if( c==c2 ){\n            seen = 1;\n          }\n          prior_c = c2;\n        }\n        c2 = *(zGlob++);\n      }\n      if( c2==0 || (seen ^ invert)==0 ) return 0;\n    }else if( c=='#' ){\n      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;\n      if( !IsDigit(z[0]) ) return 0;\n      z++;\n      while( IsDigit(z[0]) ){ z++; }\n    }else{\n      if( c!=(*(z++)) ) return 0;\n    }\n  }\n  while( IsSpace(*z) ){ z++; }\n  return *z==0;\n}\n\n\n/*\n** Compare the string as a command-line option with either one or two\n** initial \"-\" characters.\n*/\nstatic int optionMatch(const char *zStr, const char *zOpt){\n  if( zStr[0]!='-' ) return 0;\n  zStr++;\n  if( zStr[0]=='-' ) zStr++;\n  return strcmp(zStr, zOpt)==0;\n}\n\n/*\n** Delete a file.\n*/\nint shellDeleteFile(const char *zFilename){\n  int rc;\n#ifdef _WIN32\n  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);\n  rc = _wunlink(z);\n  sqlite3_free(z);\n#else\n  rc = unlink(zFilename);\n#endif\n  return rc;\n}\n\n/*\n** Try to delete the temporary file (if there is one) and free the\n** memory used to hold the name of the temp file.\n*/\nstatic void clearTempFile(ShellState *p){\n  if( p->zTempFile==0 ) return;\n  if( p->doXdgOpen ) return;\n  if( shellDeleteFile(p->zTempFile) ) return;\n  sqlite3_free(p->zTempFile);\n  p->zTempFile = 0;\n}\n\n/*\n** Create a new temp file name with the given suffix.\n*/\nstatic void newTempFile(ShellState *p, const char *zSuffix){\n  clearTempFile(p);\n  sqlite3_free(p->zTempFile);\n  p->zTempFile = 0;\n  if( p->db ){\n    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);\n  }\n  if( p->zTempFile==0 ){\n    /* If p->db is an in-memory database then the TEMPFILENAME file-control\n    ** will not work and we will need to fallback to guessing */\n    char *zTemp;\n    sqlite3_uint64 r;\n    sqlite3_randomness(sizeof(r), &r);\n    zTemp = getenv(\"TEMP\");\n    if( zTemp==0 ) zTemp = getenv(\"TMP\");\n    if( zTemp==0 ){\n#ifdef _WIN32\n      zTemp = \"\\\\tmp\";\n#else\n      zTemp = \"/tmp\";\n#endif\n    }\n    p->zTempFile = sqlite3_mprintf(\"%s/temp%llx.%s\", zTemp, r, zSuffix);\n  }else{\n    p->zTempFile = sqlite3_mprintf(\"%z.%s\", p->zTempFile, zSuffix);\n  }\n  if( p->zTempFile==0 ){\n    raw_printf(stderr, \"out of memory\\n\");\n    exit(1);\n  }\n}\n\n\n/*\n** The implementation of SQL scalar function fkey_collate_clause(), used\n** by the \".lint fkey-indexes\" command. This scalar function is always\n** called with four arguments - the parent table name, the parent column name,\n** the child table name and the child column name.\n**\n**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')\n**\n** If either of the named tables or columns do not exist, this function\n** returns an empty string. An empty string is also returned if both tables\n** and columns exist but have the same default collation sequence. Or,\n** if both exist but the default collation sequences are different, this\n** function returns the string \" COLLATE <parent-collation>\", where\n** <parent-collation> is the default collation sequence of the parent column.\n*/\nstatic void shellFkeyCollateClause(\n  sqlite3_context *pCtx,\n  int nVal,\n  sqlite3_value **apVal\n){\n  sqlite3 *db = sqlite3_context_db_handle(pCtx);\n  const char *zParent;\n  const char *zParentCol;\n  const char *zParentSeq;\n  const char *zChild;\n  const char *zChildCol;\n  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */\n  int rc;\n\n  assert( nVal==4 );\n  zParent = (const char*)sqlite3_value_text(apVal[0]);\n  zParentCol = (const char*)sqlite3_value_text(apVal[1]);\n  zChild = (const char*)sqlite3_value_text(apVal[2]);\n  zChildCol = (const char*)sqlite3_value_text(apVal[3]);\n\n  sqlite3_result_text(pCtx, \"\", -1, SQLITE_STATIC);\n  rc = sqlite3_table_column_metadata(\n      db, \"main\", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0\n  );\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_table_column_metadata(\n        db, \"main\", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0\n    );\n  }\n\n  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){\n    char *z = sqlite3_mprintf(\" COLLATE %s\", zParentSeq);\n    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);\n    sqlite3_free(z);\n  }\n}\n\n\n/*\n** The implementation of dot-command \".lint fkey-indexes\".\n*/\nstatic int lintFkeyIndexes(\n  ShellState *pState,             /* Current shell tool state */\n  char **azArg,                   /* Array of arguments passed to dot command */\n  int nArg                        /* Number of entries in azArg[] */\n){\n  sqlite3 *db = pState->db;       /* Database handle to query \"main\" db of */\n  FILE *out = pState->out;        /* Stream to write non-error output to */\n  int bVerbose = 0;               /* If -verbose is present */\n  int bGroupByParent = 0;         /* If -groupbyparent is present */\n  int i;                          /* To iterate through azArg[] */\n  const char *zIndent = \"\";       /* How much to indent CREATE INDEX by */\n  int rc;                         /* Return code */\n  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */\n\n  /*\n  ** This SELECT statement returns one row for each foreign key constraint\n  ** in the schema of the main database. The column values are:\n  **\n  ** 0. The text of an SQL statement similar to:\n  **\n  **      \"EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?\"\n  **\n  **    This SELECT is similar to the one that the foreign keys implementation\n  **    needs to run internally on child tables. If there is an index that can\n  **    be used to optimize this query, then it can also be used by the FK\n  **    implementation to optimize DELETE or UPDATE statements on the parent\n  **    table.\n  **\n  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by\n  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema\n  **    contains an index that can be used to optimize the query.\n  **\n  ** 2. Human readable text that describes the child table and columns. e.g.\n  **\n  **       \"child_table(child_key1, child_key2)\"\n  **\n  ** 3. Human readable text that describes the parent table and columns. e.g.\n  **\n  **       \"parent_table(parent_key1, parent_key2)\"\n  **\n  ** 4. A full CREATE INDEX statement for an index that could be used to\n  **    optimize DELETE or UPDATE statements on the parent table. e.g.\n  **\n  **       \"CREATE INDEX child_table_child_key ON child_table(child_key)\"\n  **\n  ** 5. The name of the parent table.\n  **\n  ** These six values are used by the C logic below to generate the report.\n  */\n  const char *zSql =\n  \"SELECT \"\n    \"     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '\"\n    \"  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' \"\n    \"  || fkey_collate_clause(\"\n    \"       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')\"\n    \", \"\n    \"     'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('\"\n    \"  || group_concat('*=?', ' AND ') || ')'\"\n    \", \"\n    \"     s.name  || '(' || group_concat(f.[from],  ', ') || ')'\"\n    \", \"\n    \"     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'\"\n    \", \"\n    \"     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))\"\n    \"  || ' ON ' || quote(s.name) || '('\"\n    \"  || group_concat(quote(f.[from]) ||\"\n    \"        fkey_collate_clause(\"\n    \"          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')\"\n    \"  || ');'\"\n    \", \"\n    \"     f.[table] \"\n    \"FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f \"\n    \"LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) \"\n    \"GROUP BY s.name, f.id \"\n    \"ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)\"\n  ;\n  const char *zGlobIPK = \"SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)\";\n\n  for(i=2; i<nArg; i++){\n    int n = strlen30(azArg[i]);\n    if( n>1 && sqlite3_strnicmp(\"-verbose\", azArg[i], n)==0 ){\n      bVerbose = 1;\n    }\n    else if( n>1 && sqlite3_strnicmp(\"-groupbyparent\", azArg[i], n)==0 ){\n      bGroupByParent = 1;\n      zIndent = \"    \";\n    }\n    else{\n      raw_printf(stderr, \"Usage: %s %s ?-verbose? ?-groupbyparent?\\n\",\n          azArg[0], azArg[1]\n      );\n      return SQLITE_ERROR;\n    }\n  }\n\n  /* Register the fkey_collate_clause() SQL function */\n  rc = sqlite3_create_function(db, \"fkey_collate_clause\", 4, SQLITE_UTF8,\n      0, shellFkeyCollateClause, 0, 0\n  );\n\n\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);\n  }\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int(pSql, 1, bGroupByParent);\n  }\n\n  if( rc==SQLITE_OK ){\n    int rc2;\n    char *zPrev = 0;\n    while( SQLITE_ROW==sqlite3_step(pSql) ){\n      int res = -1;\n      sqlite3_stmt *pExplain = 0;\n      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);\n      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);\n      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);\n      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);\n      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);\n      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);\n\n      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);\n      if( rc!=SQLITE_OK ) break;\n      if( SQLITE_ROW==sqlite3_step(pExplain) ){\n        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);\n        res = (\n              0==sqlite3_strglob(zGlob, zPlan)\n           || 0==sqlite3_strglob(zGlobIPK, zPlan)\n        );\n      }\n      rc = sqlite3_finalize(pExplain);\n      if( rc!=SQLITE_OK ) break;\n\n      if( res<0 ){\n        raw_printf(stderr, \"Error: internal error\");\n        break;\n      }else{\n        if( bGroupByParent\n        && (bVerbose || res==0)\n        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))\n        ){\n          raw_printf(out, \"-- Parent table %s\\n\", zParent);\n          sqlite3_free(zPrev);\n          zPrev = sqlite3_mprintf(\"%s\", zParent);\n        }\n\n        if( res==0 ){\n          raw_printf(out, \"%s%s --> %s\\n\", zIndent, zCI, zTarget);\n        }else if( bVerbose ){\n          raw_printf(out, \"%s/* no extra indexes required for %s -> %s */\\n\",\n              zIndent, zFrom, zTarget\n          );\n        }\n      }\n    }\n    sqlite3_free(zPrev);\n\n    if( rc!=SQLITE_OK ){\n      raw_printf(stderr, \"%s\\n\", sqlite3_errmsg(db));\n    }\n\n    rc2 = sqlite3_finalize(pSql);\n    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){\n      rc = rc2;\n      raw_printf(stderr, \"%s\\n\", sqlite3_errmsg(db));\n    }\n  }else{\n    raw_printf(stderr, \"%s\\n\", sqlite3_errmsg(db));\n  }\n\n  return rc;\n}\n\n/*\n** Implementation of \".lint\" dot command.\n*/\nstatic int lintDotCommand(\n  ShellState *pState,             /* Current shell tool state */\n  char **azArg,                   /* Array of arguments passed to dot command */\n  int nArg                        /* Number of entries in azArg[] */\n){\n  int n;\n  n = (nArg>=2 ? strlen30(azArg[1]) : 0);\n  if( n<1 || sqlite3_strnicmp(azArg[1], \"fkey-indexes\", n) ) goto usage;\n  return lintFkeyIndexes(pState, azArg, nArg);\n\n usage:\n  raw_printf(stderr, \"Usage %s sub-command ?switches...?\\n\", azArg[0]);\n  raw_printf(stderr, \"Where sub-commands are:\\n\");\n  raw_printf(stderr, \"    fkey-indexes\\n\");\n  return SQLITE_ERROR;\n}\n\n#if !defined SQLITE_OMIT_VIRTUALTABLE\nstatic void shellPrepare(\n  sqlite3 *db, \n  int *pRc, \n  const char *zSql, \n  sqlite3_stmt **ppStmt\n){\n  *ppStmt = 0;\n  if( *pRc==SQLITE_OK ){\n    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);\n    if( rc!=SQLITE_OK ){\n      raw_printf(stderr, \"sql error: %s (%d)\\n\", \n          sqlite3_errmsg(db), sqlite3_errcode(db)\n      );\n      *pRc = rc;\n    }\n  }\n}\n\n/*\n** Create a prepared statement using printf-style arguments for the SQL.\n**\n** This routine is could be marked \"static\".  But it is not always used,\n** depending on compile-time options.  By omitting the \"static\", we avoid\n** nuisance compiler warnings about \"defined but not used\".\n*/\nvoid shellPreparePrintf(\n  sqlite3 *db, \n  int *pRc, \n  sqlite3_stmt **ppStmt,\n  const char *zFmt, \n  ...\n){\n  *ppStmt = 0;\n  if( *pRc==SQLITE_OK ){\n    va_list ap;\n    char *z;\n    va_start(ap, zFmt);\n    z = sqlite3_vmprintf(zFmt, ap);\n    va_end(ap);\n    if( z==0 ){\n      *pRc = SQLITE_NOMEM;\n    }else{\n      shellPrepare(db, pRc, z, ppStmt);\n      sqlite3_free(z);\n    }\n  }\n}\n\n/* Finalize the prepared statement created using shellPreparePrintf().\n**\n** This routine is could be marked \"static\".  But it is not always used,\n** depending on compile-time options.  By omitting the \"static\", we avoid\n** nuisance compiler warnings about \"defined but not used\".\n*/\nvoid shellFinalize(\n  int *pRc, \n  sqlite3_stmt *pStmt\n){\n  if( pStmt ){\n    sqlite3 *db = sqlite3_db_handle(pStmt);\n    int rc = sqlite3_finalize(pStmt);\n    if( *pRc==SQLITE_OK ){\n      if( rc!=SQLITE_OK ){\n        raw_printf(stderr, \"SQL error: %s\\n\", sqlite3_errmsg(db));\n      }\n      *pRc = rc;\n    }\n  }\n}\n\n/* Reset the prepared statement created using shellPreparePrintf().\n**\n** This routine is could be marked \"static\".  But it is not always used,\n** depending on compile-time options.  By omitting the \"static\", we avoid\n** nuisance compiler warnings about \"defined but not used\".\n*/\nvoid shellReset(\n  int *pRc, \n  sqlite3_stmt *pStmt\n){\n  int rc = sqlite3_reset(pStmt);\n  if( *pRc==SQLITE_OK ){\n    if( rc!=SQLITE_OK ){\n      sqlite3 *db = sqlite3_db_handle(pStmt);\n      raw_printf(stderr, \"SQL error: %s\\n\", sqlite3_errmsg(db));\n    }\n    *pRc = rc;\n  }\n}\n#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */\n\n#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)\n/******************************************************************************\n** The \".archive\" or \".ar\" command.\n*/\n/*\n** Structure representing a single \".ar\" command.\n*/\ntypedef struct ArCommand ArCommand;\nstruct ArCommand {\n  u8 eCmd;                        /* An AR_CMD_* value */\n  u8 bVerbose;                    /* True if --verbose */\n  u8 bZip;                        /* True if the archive is a ZIP */\n  u8 bDryRun;                     /* True if --dry-run */\n  u8 bAppend;                     /* True if --append */\n  u8 fromCmdLine;                 /* Run from -A instead of .archive */\n  int nArg;                       /* Number of command arguments */\n  char *zSrcTable;                /* \"sqlar\", \"zipfile($file)\" or \"zip\" */\n  const char *zFile;              /* --file argument, or NULL */\n  const char *zDir;               /* --directory argument, or NULL */\n  char **azArg;                   /* Array of command arguments */\n  ShellState *p;                  /* Shell state */\n  sqlite3 *db;                    /* Database containing the archive */\n};\n\n/*\n** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.\n*/\nstatic int arUsage(FILE *f){\n  showHelp(f,\"archive\");\n  return SQLITE_ERROR;\n}\n\n/*\n** Print an error message for the .ar command to stderr and return \n** SQLITE_ERROR.\n*/\nstatic int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){\n  va_list ap;\n  char *z;\n  va_start(ap, zFmt);\n  z = sqlite3_vmprintf(zFmt, ap);\n  va_end(ap);\n  utf8_printf(stderr, \"Error: %s\\n\", z);\n  if( pAr->fromCmdLine ){\n    utf8_printf(stderr, \"Use \\\"-A\\\" for more help\\n\");\n  }else{\n    utf8_printf(stderr, \"Use \\\".archive --help\\\" for more help\\n\");\n  }\n  sqlite3_free(z);\n  return SQLITE_ERROR;\n}\n\n/*\n** Values for ArCommand.eCmd.\n*/\n#define AR_CMD_CREATE       1\n#define AR_CMD_UPDATE       2\n#define AR_CMD_INSERT       3\n#define AR_CMD_EXTRACT      4\n#define AR_CMD_LIST         5\n#define AR_CMD_HELP         6\n\n/*\n** Other (non-command) switches.\n*/\n#define AR_SWITCH_VERBOSE     7\n#define AR_SWITCH_FILE        8\n#define AR_SWITCH_DIRECTORY   9\n#define AR_SWITCH_APPEND     10\n#define AR_SWITCH_DRYRUN     11\n\nstatic int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){\n  switch( eSwitch ){\n    case AR_CMD_CREATE:\n    case AR_CMD_EXTRACT:\n    case AR_CMD_LIST:\n    case AR_CMD_UPDATE:\n    case AR_CMD_INSERT:\n    case AR_CMD_HELP:\n      if( pAr->eCmd ){\n        return arErrorMsg(pAr, \"multiple command options\");\n      }\n      pAr->eCmd = eSwitch;\n      break;\n\n    case AR_SWITCH_DRYRUN:\n      pAr->bDryRun = 1;\n      break;\n    case AR_SWITCH_VERBOSE:\n      pAr->bVerbose = 1;\n      break;\n    case AR_SWITCH_APPEND:\n      pAr->bAppend = 1;\n      /* Fall thru into --file */\n    case AR_SWITCH_FILE:\n      pAr->zFile = zArg;\n      break;\n    case AR_SWITCH_DIRECTORY:\n      pAr->zDir = zArg;\n      break;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Parse the command line for an \".ar\" command. The results are written into\n** structure (*pAr). SQLITE_OK is returned if the command line is parsed\n** successfully, otherwise an error message is written to stderr and \n** SQLITE_ERROR returned.\n*/\nstatic int arParseCommand(\n  char **azArg,                   /* Array of arguments passed to dot command */\n  int nArg,                       /* Number of entries in azArg[] */\n  ArCommand *pAr                  /* Populate this object */\n){\n  struct ArSwitch {\n    const char *zLong;\n    char cShort;\n    u8 eSwitch;\n    u8 bArg;\n  } aSwitch[] = {\n    { \"create\",    'c', AR_CMD_CREATE,       0 },\n    { \"extract\",   'x', AR_CMD_EXTRACT,      0 },\n    { \"insert\",    'i', AR_CMD_INSERT,       0 },\n    { \"list\",      't', AR_CMD_LIST,         0 },\n    { \"update\",    'u', AR_CMD_UPDATE,       0 },\n    { \"help\",      'h', AR_CMD_HELP,         0 },\n    { \"verbose\",   'v', AR_SWITCH_VERBOSE,   0 },\n    { \"file\",      'f', AR_SWITCH_FILE,      1 },\n    { \"append\",    'a', AR_SWITCH_APPEND,    1 },\n    { \"directory\", 'C', AR_SWITCH_DIRECTORY, 1 },\n    { \"dryrun\",    'n', AR_SWITCH_DRYRUN,    0 },\n  };\n  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);\n  struct ArSwitch *pEnd = &aSwitch[nSwitch];\n\n  if( nArg<=1 ){\n    utf8_printf(stderr, \"Wrong number of arguments.  Usage:\\n\");\n    return arUsage(stderr);\n  }else{\n    char *z = azArg[1];\n    if( z[0]!='-' ){\n      /* Traditional style [tar] invocation */\n      int i;\n      int iArg = 2;\n      for(i=0; z[i]; i++){\n        const char *zArg = 0;\n        struct ArSwitch *pOpt;\n        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){\n          if( z[i]==pOpt->cShort ) break;\n        }\n        if( pOpt==pEnd ){\n          return arErrorMsg(pAr, \"unrecognized option: %c\", z[i]);\n        }\n        if( pOpt->bArg ){\n          if( iArg>=nArg ){\n            return arErrorMsg(pAr, \"option requires an argument: %c\",z[i]);\n          }\n          zArg = azArg[iArg++];\n        }\n        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;\n      }\n      pAr->nArg = nArg-iArg;\n      if( pAr->nArg>0 ){\n        pAr->azArg = &azArg[iArg];\n      }\n    }else{\n      /* Non-traditional invocation */\n      int iArg;\n      for(iArg=1; iArg<nArg; iArg++){\n        int n;\n        z = azArg[iArg];\n        if( z[0]!='-' ){\n          /* All remaining command line words are command arguments. */\n          pAr->azArg = &azArg[iArg];\n          pAr->nArg = nArg-iArg;\n          break;\n        }\n        n = strlen30(z);\n\n        if( z[1]!='-' ){\n          int i;\n          /* One or more short options */\n          for(i=1; i<n; i++){\n            const char *zArg = 0;\n            struct ArSwitch *pOpt;\n            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){\n              if( z[i]==pOpt->cShort ) break;\n            }\n            if( pOpt==pEnd ){\n              return arErrorMsg(pAr, \"unrecognized option: %c\", z[i]);\n            }\n            if( pOpt->bArg ){\n              if( i<(n-1) ){\n                zArg = &z[i+1];\n                i = n;\n              }else{\n                if( iArg>=(nArg-1) ){\n                  return arErrorMsg(pAr, \"option requires an argument: %c\",\n                                    z[i]);\n                }\n                zArg = azArg[++iArg];\n              }\n            }\n            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;\n          }\n        }else if( z[2]=='\\0' ){\n          /* A -- option, indicating that all remaining command line words\n          ** are command arguments.  */\n          pAr->azArg = &azArg[iArg+1];\n          pAr->nArg = nArg-iArg-1;\n          break;\n        }else{\n          /* A long option */\n          const char *zArg = 0;             /* Argument for option, if any */\n          struct ArSwitch *pMatch = 0;      /* Matching option */\n          struct ArSwitch *pOpt;            /* Iterator */\n          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){\n            const char *zLong = pOpt->zLong;\n            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){\n              if( pMatch ){\n                return arErrorMsg(pAr, \"ambiguous option: %s\",z);\n              }else{\n                pMatch = pOpt;\n              }\n            }\n          }\n\n          if( pMatch==0 ){\n            return arErrorMsg(pAr, \"unrecognized option: %s\", z);\n          }\n          if( pMatch->bArg ){\n            if( iArg>=(nArg-1) ){\n              return arErrorMsg(pAr, \"option requires an argument: %s\", z);\n            }\n            zArg = azArg[++iArg];\n          }\n          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;\n        }\n      }\n    }\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** This function assumes that all arguments within the ArCommand.azArg[]\n** array refer to archive members, as for the --extract or --list commands. \n** It checks that each of them are present. If any specified file is not\n** present in the archive, an error is printed to stderr and an error\n** code returned. Otherwise, if all specified arguments are present in\n** the archive, SQLITE_OK is returned.\n**\n** This function strips any trailing '/' characters from each argument.\n** This is consistent with the way the [tar] command seems to work on\n** Linux.\n*/\nstatic int arCheckEntries(ArCommand *pAr){\n  int rc = SQLITE_OK;\n  if( pAr->nArg ){\n    int i, j;\n    sqlite3_stmt *pTest = 0;\n\n    shellPreparePrintf(pAr->db, &rc, &pTest,\n        \"SELECT name FROM %s WHERE name=$name\", \n        pAr->zSrcTable\n    );\n    j = sqlite3_bind_parameter_index(pTest, \"$name\");\n    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){\n      char *z = pAr->azArg[i];\n      int n = strlen30(z);\n      int bOk = 0;\n      while( n>0 && z[n-1]=='/' ) n--;\n      z[n] = '\\0';\n      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);\n      if( SQLITE_ROW==sqlite3_step(pTest) ){\n        bOk = 1;\n      }\n      shellReset(&rc, pTest);\n      if( rc==SQLITE_OK && bOk==0 ){\n        utf8_printf(stderr, \"not found in archive: %s\\n\", z);\n        rc = SQLITE_ERROR;\n      }\n    }\n    shellFinalize(&rc, pTest);\n  }\n  return rc;\n}\n\n/*\n** Format a WHERE clause that can be used against the \"sqlar\" table to\n** identify all archive members that match the command arguments held\n** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.\n** The caller is responsible for eventually calling sqlite3_free() on\n** any non-NULL (*pzWhere) value.\n*/\nstatic void arWhereClause(\n  int *pRc, \n  ArCommand *pAr, \n  char **pzWhere                  /* OUT: New WHERE clause */\n){\n  char *zWhere = 0;\n  if( *pRc==SQLITE_OK ){\n    if( pAr->nArg==0 ){\n      zWhere = sqlite3_mprintf(\"1\");\n    }else{\n      int i;\n      const char *zSep = \"\";\n      for(i=0; i<pAr->nArg; i++){\n        const char *z = pAr->azArg[i];\n        zWhere = sqlite3_mprintf(\n          \"%z%s name = '%q' OR substr(name,1,%d) = '%q/'\", \n          zWhere, zSep, z, strlen30(z)+1, z\n        );\n        if( zWhere==0 ){\n          *pRc = SQLITE_NOMEM;\n          break;\n        }\n        zSep = \" OR \";\n      }\n    }\n  }\n  *pzWhere = zWhere;\n}\n\n/*\n** Implementation of .ar \"lisT\" command. \n*/\nstatic int arListCommand(ArCommand *pAr){\n  const char *zSql = \"SELECT %s FROM %s WHERE %s\"; \n  const char *azCols[] = {\n    \"name\",\n    \"lsmode(mode), sz, datetime(mtime, 'unixepoch'), name\"\n  };\n\n  char *zWhere = 0;\n  sqlite3_stmt *pSql = 0;\n  int rc;\n\n  rc = arCheckEntries(pAr);\n  arWhereClause(&rc, pAr, &zWhere);\n\n  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],\n                     pAr->zSrcTable, zWhere);\n  if( pAr->bDryRun ){\n    utf8_printf(pAr->p->out, \"%s\\n\", sqlite3_sql(pSql));\n  }else{\n    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){\n      if( pAr->bVerbose ){\n        utf8_printf(pAr->p->out, \"%s % 10d  %s  %s\\n\",\n            sqlite3_column_text(pSql, 0),\n            sqlite3_column_int(pSql, 1), \n            sqlite3_column_text(pSql, 2),\n            sqlite3_column_text(pSql, 3)\n        );\n      }else{\n        utf8_printf(pAr->p->out, \"%s\\n\", sqlite3_column_text(pSql, 0));\n      }\n    }\n  }\n  shellFinalize(&rc, pSql);\n  sqlite3_free(zWhere);\n  return rc;\n}\n\n\n/*\n** Implementation of .ar \"eXtract\" command. \n*/\nstatic int arExtractCommand(ArCommand *pAr){\n  const char *zSql1 = \n    \"SELECT \"\n    \" ($dir || name),\"\n    \" writefile(($dir || name), %s, mode, mtime) \"\n    \"FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)\"\n    \" AND name NOT GLOB '*..[/\\\\]*'\";\n\n  const char *azExtraArg[] = { \n    \"sqlar_uncompress(data, sz)\",\n    \"data\"\n  };\n\n  sqlite3_stmt *pSql = 0;\n  int rc = SQLITE_OK;\n  char *zDir = 0;\n  char *zWhere = 0;\n  int i, j;\n\n  /* If arguments are specified, check that they actually exist within\n  ** the archive before proceeding. And formulate a WHERE clause to\n  ** match them.  */\n  rc = arCheckEntries(pAr);\n  arWhereClause(&rc, pAr, &zWhere);\n\n  if( rc==SQLITE_OK ){\n    if( pAr->zDir ){\n      zDir = sqlite3_mprintf(\"%s/\", pAr->zDir);\n    }else{\n      zDir = sqlite3_mprintf(\"\");\n    }\n    if( zDir==0 ) rc = SQLITE_NOMEM;\n  }\n\n  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, \n      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere\n  );\n\n  if( rc==SQLITE_OK ){\n    j = sqlite3_bind_parameter_index(pSql, \"$dir\");\n    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);\n\n    /* Run the SELECT statement twice. The first time, writefile() is called\n    ** for all archive members that should be extracted. The second time,\n    ** only for the directories. This is because the timestamps for\n    ** extracted directories must be reset after they are populated (as\n    ** populating them changes the timestamp).  */\n    for(i=0; i<2; i++){\n      j = sqlite3_bind_parameter_index(pSql, \"$dirOnly\");\n      sqlite3_bind_int(pSql, j, i);\n      if( pAr->bDryRun ){\n        utf8_printf(pAr->p->out, \"%s\\n\", sqlite3_sql(pSql));\n      }else{\n        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){\n          if( i==0 && pAr->bVerbose ){\n            utf8_printf(pAr->p->out, \"%s\\n\", sqlite3_column_text(pSql, 0));\n          }\n        }\n      }\n      shellReset(&rc, pSql);\n    }\n    shellFinalize(&rc, pSql);\n  }\n\n  sqlite3_free(zDir);\n  sqlite3_free(zWhere);\n  return rc;\n}\n\n/*\n** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.\n*/\nstatic int arExecSql(ArCommand *pAr, const char *zSql){\n  int rc;\n  if( pAr->bDryRun ){\n    utf8_printf(pAr->p->out, \"%s\\n\", zSql);\n    rc = SQLITE_OK;\n  }else{\n    char *zErr = 0;\n    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);\n    if( zErr ){\n      utf8_printf(stdout, \"ERROR: %s\\n\", zErr);\n      sqlite3_free(zErr);\n    }\n  }\n  return rc;\n}\n\n\n/*\n** Implementation of .ar \"create\", \"insert\", and \"update\" commands.\n**\n**     create    ->     Create a new SQL archive\n**     insert    ->     Insert or reinsert all files listed\n**     update    ->     Insert files that have changed or that were not\n**                      previously in the archive\n**\n** Create the \"sqlar\" table in the database if it does not already exist.\n** Then add each file in the azFile[] array to the archive. Directories\n** are added recursively. If argument bVerbose is non-zero, a message is\n** printed on stdout for each file archived.\n**\n** The create command is the same as update, except that it drops\n** any existing \"sqlar\" table before beginning.  The \"insert\" command\n** always overwrites every file named on the command-line, where as\n** \"update\" only overwrites if the size or mtime or mode has changed.\n*/\nstatic int arCreateOrUpdateCommand(\n  ArCommand *pAr,                 /* Command arguments and options */\n  int bUpdate,                    /* true for a --create. */\n  int bOnlyIfChanged              /* Only update if file has changed */\n){\n  const char *zCreate = \n      \"CREATE TABLE IF NOT EXISTS sqlar(\\n\"\n      \"  name TEXT PRIMARY KEY,  -- name of the file\\n\"\n      \"  mode INT,               -- access permissions\\n\"\n      \"  mtime INT,              -- last modification time\\n\"\n      \"  sz INT,                 -- original file size\\n\"\n      \"  data BLOB               -- compressed content\\n\"\n      \")\";\n  const char *zDrop = \"DROP TABLE IF EXISTS sqlar\";\n  const char *zInsertFmt[2] = {\n     \"REPLACE INTO %s(name,mode,mtime,sz,data)\\n\"\n     \"  SELECT\\n\"\n     \"    %s,\\n\"\n     \"    mode,\\n\"\n     \"    mtime,\\n\"\n     \"    CASE substr(lsmode(mode),1,1)\\n\"\n     \"      WHEN '-' THEN length(data)\\n\"\n     \"      WHEN 'd' THEN 0\\n\"\n     \"      ELSE -1 END,\\n\"\n     \"    sqlar_compress(data)\\n\"\n     \"  FROM fsdir(%Q,%Q) AS disk\\n\"\n     \"  WHERE lsmode(mode) NOT LIKE '?%%'%s;\"\n     ,\n     \"REPLACE INTO %s(name,mode,mtime,data)\\n\"\n     \"  SELECT\\n\"\n     \"    %s,\\n\"\n     \"    mode,\\n\"\n     \"    mtime,\\n\"\n     \"    data\\n\"\n     \"  FROM fsdir(%Q,%Q) AS disk\\n\"\n     \"  WHERE lsmode(mode) NOT LIKE '?%%'%s;\"\n  };\n  int i;                          /* For iterating through azFile[] */\n  int rc;                         /* Return code */\n  const char *zTab = 0;           /* SQL table into which to insert */\n  char *zSql;\n  char zTemp[50];\n  char *zExists = 0;\n\n  arExecSql(pAr, \"PRAGMA page_size=512\");\n  rc = arExecSql(pAr, \"SAVEPOINT ar;\");\n  if( rc!=SQLITE_OK ) return rc;\n  zTemp[0] = 0; \n  if( pAr->bZip ){\n    /* Initialize the zipfile virtual table, if necessary */\n    if( pAr->zFile ){\n      sqlite3_uint64 r;\n      sqlite3_randomness(sizeof(r),&r);\n      sqlite3_snprintf(sizeof(zTemp),zTemp,\"zip%016llx\",r);\n      zTab = zTemp;\n      zSql = sqlite3_mprintf(\n         \"CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)\",\n         zTab, pAr->zFile\n      );\n      rc = arExecSql(pAr, zSql);\n      sqlite3_free(zSql);\n    }else{\n      zTab = \"zip\";\n    }\n  }else{\n    /* Initialize the table for an SQLAR */\n    zTab = \"sqlar\";\n    if( bUpdate==0 ){\n      rc = arExecSql(pAr, zDrop);\n      if( rc!=SQLITE_OK ) goto end_ar_transaction;\n    }\n    rc = arExecSql(pAr, zCreate);\n  }\n  if( bOnlyIfChanged ){\n    zExists = sqlite3_mprintf(\n      \" AND NOT EXISTS(\"\n          \"SELECT 1 FROM %s AS mem\"\n          \" WHERE mem.name=disk.name\"\n          \" AND mem.mtime=disk.mtime\"\n          \" AND mem.mode=disk.mode)\", zTab);\n  }else{\n    zExists = sqlite3_mprintf(\"\");\n  }\n  if( zExists==0 ) rc = SQLITE_NOMEM;\n  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){\n    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,\n        pAr->bVerbose ? \"shell_putsnl(name)\" : \"name\",\n        pAr->azArg[i], pAr->zDir, zExists);\n    rc = arExecSql(pAr, zSql2);\n    sqlite3_free(zSql2);\n  }\nend_ar_transaction:\n  if( rc!=SQLITE_OK ){\n    sqlite3_exec(pAr->db, \"ROLLBACK TO ar; RELEASE ar;\", 0, 0, 0);\n  }else{\n    rc = arExecSql(pAr, \"RELEASE ar;\");\n    if( pAr->bZip && pAr->zFile ){\n      zSql = sqlite3_mprintf(\"DROP TABLE %s\", zTemp);\n      arExecSql(pAr, zSql);\n      sqlite3_free(zSql);\n    }\n  }\n  sqlite3_free(zExists);\n  return rc;\n}\n\n/*\n** Implementation of \".ar\" dot command.\n*/\nstatic int arDotCommand(\n  ShellState *pState,          /* Current shell tool state */\n  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */\n  char **azArg,                /* Array of arguments passed to dot command */\n  int nArg                     /* Number of entries in azArg[] */\n){\n  ArCommand cmd;\n  int rc;\n  memset(&cmd, 0, sizeof(cmd));\n  cmd.fromCmdLine = fromCmdLine;\n  rc = arParseCommand(azArg, nArg, &cmd);\n  if( rc==SQLITE_OK ){\n    int eDbType = SHELL_OPEN_UNSPEC;\n    cmd.p = pState;\n    cmd.db = pState->db;\n    if( cmd.zFile ){\n      eDbType = deduceDatabaseType(cmd.zFile, 1);\n    }else{\n      eDbType = pState->openMode;\n    }\n    if( eDbType==SHELL_OPEN_ZIPFILE ){\n      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){\n        if( cmd.zFile==0 ){\n          cmd.zSrcTable = sqlite3_mprintf(\"zip\");\n        }else{\n          cmd.zSrcTable = sqlite3_mprintf(\"zipfile(%Q)\", cmd.zFile);\n        }\n      }\n      cmd.bZip = 1;\n    }else if( cmd.zFile ){\n      int flags;\n      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;\n      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT \n           || cmd.eCmd==AR_CMD_UPDATE ){\n        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;\n      }else{\n        flags = SQLITE_OPEN_READONLY;\n      }\n      cmd.db = 0;\n      if( cmd.bDryRun ){\n        utf8_printf(pState->out, \"-- open database '%s'%s\\n\", cmd.zFile,\n             eDbType==SHELL_OPEN_APPENDVFS ? \" using 'apndvfs'\" : \"\");\n      }\n      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, \n             eDbType==SHELL_OPEN_APPENDVFS ? \"apndvfs\" : 0);\n      if( rc!=SQLITE_OK ){\n        utf8_printf(stderr, \"cannot open file: %s (%s)\\n\", \n            cmd.zFile, sqlite3_errmsg(cmd.db)\n        );\n        goto end_ar_command;\n      }\n      sqlite3_fileio_init(cmd.db, 0, 0);\n      sqlite3_sqlar_init(cmd.db, 0, 0);\n      sqlite3_create_function(cmd.db, \"shell_putsnl\", 1, SQLITE_UTF8, cmd.p,\n                              shellPutsFunc, 0, 0);\n\n    }\n    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){\n      if( cmd.eCmd!=AR_CMD_CREATE\n       && sqlite3_table_column_metadata(cmd.db,0,\"sqlar\",\"name\",0,0,0,0,0)\n      ){\n        utf8_printf(stderr, \"database does not contain an 'sqlar' table\\n\");\n        rc = SQLITE_ERROR;\n        goto end_ar_command;\n      }\n      cmd.zSrcTable = sqlite3_mprintf(\"sqlar\");\n    }\n\n    switch( cmd.eCmd ){\n      case AR_CMD_CREATE:\n        rc = arCreateOrUpdateCommand(&cmd, 0, 0);\n        break;\n\n      case AR_CMD_EXTRACT:\n        rc = arExtractCommand(&cmd);\n        break;\n\n      case AR_CMD_LIST:\n        rc = arListCommand(&cmd);\n        break;\n\n      case AR_CMD_HELP:\n        arUsage(pState->out);\n        break;\n\n      case AR_CMD_INSERT:\n        rc = arCreateOrUpdateCommand(&cmd, 1, 0);\n        break;\n\n      default:\n        assert( cmd.eCmd==AR_CMD_UPDATE );\n        rc = arCreateOrUpdateCommand(&cmd, 1, 1);\n        break;\n    }\n  }\nend_ar_command:\n  if( cmd.db!=pState->db ){\n    close_db(cmd.db);\n  }\n  sqlite3_free(cmd.zSrcTable);\n\n  return rc;\n}\n/* End of the \".archive\" or \".ar\" command logic\n*******************************************************************************/\n#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */\n\n#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)\n/*\n** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.\n** Otherwise, the SQL statement or statements in zSql are executed using\n** database connection db and the error code written to *pRc before\n** this function returns.\n*/\nstatic void shellExec(sqlite3 *db, int *pRc, const char *zSql){\n  int rc = *pRc;\n  if( rc==SQLITE_OK ){\n    char *zErr = 0;\n    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);\n    if( rc!=SQLITE_OK ){\n      raw_printf(stderr, \"SQL error: %s\\n\", zErr);\n    }\n    *pRc = rc;\n  }\n}\n\n/*\n** Like shellExec(), except that zFmt is a printf() style format string.\n*/\nstatic void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){\n  char *z = 0;\n  if( *pRc==SQLITE_OK ){\n    va_list ap;\n    va_start(ap, zFmt);\n    z = sqlite3_vmprintf(zFmt, ap);\n    va_end(ap);\n    if( z==0 ){\n      *pRc = SQLITE_NOMEM;\n    }else{\n      shellExec(db, pRc, z);\n    }\n    sqlite3_free(z);\n  }\n}\n\n/*\n** If *pRc is not SQLITE_OK when this function is called, it is a no-op.\n** Otherwise, an attempt is made to allocate, zero and return a pointer\n** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set\n** to SQLITE_NOMEM and NULL returned.\n*/\nstatic void *shellMalloc(int *pRc, sqlite3_int64 nByte){\n  void *pRet = 0;\n  if( *pRc==SQLITE_OK ){\n    pRet = sqlite3_malloc64(nByte);\n    if( pRet==0 ){\n      *pRc = SQLITE_NOMEM;\n    }else{\n      memset(pRet, 0, nByte);\n    }\n  }\n  return pRet;\n}\n\n/*\n** If *pRc is not SQLITE_OK when this function is called, it is a no-op.\n** Otherwise, zFmt is treated as a printf() style string. The result of\n** formatting it along with any trailing arguments is written into a \n** buffer obtained from sqlite3_malloc(), and pointer to which is returned.\n** It is the responsibility of the caller to eventually free this buffer\n** using a call to sqlite3_free().\n** \n** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL \n** pointer returned.\n*/\nstatic char *shellMPrintf(int *pRc, const char *zFmt, ...){\n  char *z = 0;\n  if( *pRc==SQLITE_OK ){\n    va_list ap;\n    va_start(ap, zFmt);\n    z = sqlite3_vmprintf(zFmt, ap);\n    va_end(ap);\n    if( z==0 ){\n      *pRc = SQLITE_NOMEM;\n    }\n  }\n  return z;\n}\n\n/*\n** When running the \".recover\" command, each output table, and the special\n** orphaned row table if it is required, is represented by an instance\n** of the following struct.\n*/\ntypedef struct RecoverTable RecoverTable;\nstruct RecoverTable {\n  char *zQuoted;                  /* Quoted version of table name */\n  int nCol;                       /* Number of columns in table */\n  char **azlCol;                  /* Array of column lists */\n  int iPk;                        /* Index of IPK column */\n};\n\n/*\n** Free a RecoverTable object allocated by recoverFindTable() or\n** recoverOrphanTable().\n*/\nstatic void recoverFreeTable(RecoverTable *pTab){\n  if( pTab ){\n    sqlite3_free(pTab->zQuoted);\n    if( pTab->azlCol ){\n      int i;\n      for(i=0; i<=pTab->nCol; i++){\n        sqlite3_free(pTab->azlCol[i]);\n      }\n      sqlite3_free(pTab->azlCol);\n    }\n    sqlite3_free(pTab);\n  }\n}\n\n/*\n** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.\n** Otherwise, it allocates and returns a RecoverTable object based on the\n** final four arguments passed to this function. It is the responsibility\n** of the caller to eventually free the returned object using\n** recoverFreeTable().\n*/\nstatic RecoverTable *recoverNewTable(\n  int *pRc,                       /* IN/OUT: Error code */\n  const char *zName,              /* Name of table */\n  const char *zSql,               /* CREATE TABLE statement */\n  int bIntkey, \n  int nCol\n){\n  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */\n  int rc = *pRc;\n  RecoverTable *pTab = 0;\n\n  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));\n  if( rc==SQLITE_OK ){\n    int nSqlCol = 0;\n    int bSqlIntkey = 0;\n    sqlite3_stmt *pStmt = 0;\n    \n    rc = sqlite3_open(\"\", &dbtmp);\n    if( rc==SQLITE_OK ){\n      sqlite3_create_function(dbtmp, \"shell_idquote\", 1, SQLITE_UTF8, 0,\n                              shellIdQuote, 0, 0);\n    }\n    if( rc==SQLITE_OK ){\n      rc = sqlite3_exec(dbtmp, \"PRAGMA writable_schema = on\", 0, 0, 0);\n    }\n    if( rc==SQLITE_OK ){\n      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);\n      if( rc==SQLITE_ERROR ){\n        rc = SQLITE_OK;\n        goto finished;\n      }\n    }\n    shellPreparePrintf(dbtmp, &rc, &pStmt, \n        \"SELECT count(*) FROM pragma_table_info(%Q)\", zName\n    );\n    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){\n      nSqlCol = sqlite3_column_int(pStmt, 0);\n    }\n    shellFinalize(&rc, pStmt);\n\n    if( rc!=SQLITE_OK || nSqlCol<nCol ){\n      goto finished;\n    }\n\n    shellPreparePrintf(dbtmp, &rc, &pStmt, \n      \"SELECT (\"\n      \"  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage\"\n      \") FROM sqlite_master WHERE name = %Q\", zName\n    );\n    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){\n      bSqlIntkey = sqlite3_column_int(pStmt, 0);\n    }\n    shellFinalize(&rc, pStmt);\n\n    if( bIntkey==bSqlIntkey ){\n      int i;\n      const char *zPk = \"_rowid_\";\n      sqlite3_stmt *pPkFinder = 0;\n\n      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,\n      ** set zPk to the name of the PK column, and pTab->iPk to the index\n      ** of the column, where columns are 0-numbered from left to right.\n      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,\n      ** leave zPk as \"_rowid_\" and pTab->iPk at -2.  */\n      pTab->iPk = -2;\n      if( bIntkey ){\n        shellPreparePrintf(dbtmp, &rc, &pPkFinder, \n          \"SELECT cid, name FROM pragma_table_info(%Q) \"\n          \"  WHERE pk=1 AND type='integer' COLLATE nocase\"\n          \"  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)\"\n          , zName, zName\n        );\n        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){\n          pTab->iPk = sqlite3_column_int(pPkFinder, 0);\n          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);\n        }\n      }\n\n      pTab->zQuoted = shellMPrintf(&rc, \"\\\"%w\\\"\", zName);\n      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));\n      pTab->nCol = nSqlCol;\n\n      if( bIntkey ){\n        pTab->azlCol[0] = shellMPrintf(&rc, \"\\\"%w\\\"\", zPk);\n      }else{\n        pTab->azlCol[0] = shellMPrintf(&rc, \"\");\n      }\n      i = 1;\n      shellPreparePrintf(dbtmp, &rc, &pStmt, \n          \"SELECT %Q || group_concat(shell_idquote(name), ', ') \"\n          \"  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) \"\n          \"FROM pragma_table_info(%Q)\", \n          bIntkey ? \", \" : \"\", pTab->iPk, \n          bIntkey ? \"\" : \"(CASE WHEN pk=0 THEN 1000000 ELSE pk END), \",\n          zName\n      );\n      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){\n        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);\n        pTab->azlCol[i] = shellMPrintf(&rc, \"%s%s\", pTab->azlCol[0], zText);\n        i++;\n      }\n      shellFinalize(&rc, pStmt);\n\n      shellFinalize(&rc, pPkFinder);\n    }\n  }\n\n finished:\n  sqlite3_close(dbtmp);\n  *pRc = rc;\n  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){\n    recoverFreeTable(pTab);\n    pTab = 0;\n  }\n  return pTab;\n}\n\n/*\n** This function is called to search the schema recovered from the\n** sqlite_master table of the (possibly) corrupt database as part\n** of a \".recover\" command. Specifically, for a table with root page\n** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the\n** table must be a WITHOUT ROWID table, or if non-zero, not one of\n** those.\n**\n** If a table is found, a (RecoverTable*) object is returned. Or, if\n** no such table is found, but bIntkey is false and iRoot is the \n** root page of an index in the recovered schema, then (*pbNoop) is\n** set to true and NULL returned. Or, if there is no such table or\n** index, NULL is returned and (*pbNoop) set to 0, indicating that\n** the caller should write data to the orphans table.\n*/\nstatic RecoverTable *recoverFindTable(\n  ShellState *pState,             /* Shell state object */\n  int *pRc,                       /* IN/OUT: Error code */\n  int iRoot,                      /* Root page of table */\n  int bIntkey,                    /* True for an intkey table */\n  int nCol,                       /* Number of columns in table */\n  int *pbNoop                     /* OUT: True if iRoot is root of index */\n){\n  sqlite3_stmt *pStmt = 0;\n  RecoverTable *pRet = 0;\n  int bNoop = 0;\n  const char *zSql = 0;\n  const char *zName = 0;\n\n  /* Search the recovered schema for an object with root page iRoot. */\n  shellPreparePrintf(pState->db, pRc, &pStmt,\n      \"SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d\", iRoot\n  );\n  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){\n    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);\n    if( bIntkey==0 && sqlite3_stricmp(zType, \"index\")==0 ){\n      bNoop = 1;\n      break;\n    }\n    if( sqlite3_stricmp(zType, \"table\")==0 ){\n      zName = (const char*)sqlite3_column_text(pStmt, 1);\n      zSql = (const char*)sqlite3_column_text(pStmt, 2);\n      pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);\n      break;\n    }\n  }\n\n  shellFinalize(pRc, pStmt);\n  *pbNoop = bNoop;\n  return pRet;\n}\n\n/*\n** Return a RecoverTable object representing the orphans table.\n*/\nstatic RecoverTable *recoverOrphanTable(\n  ShellState *pState,             /* Shell state object */\n  int *pRc,                       /* IN/OUT: Error code */\n  const char *zLostAndFound,      /* Base name for orphans table */\n  int nCol                        /* Number of user data columns */\n){\n  RecoverTable *pTab = 0;\n  if( nCol>=0 && *pRc==SQLITE_OK ){\n    int i;\n\n    /* This block determines the name of the orphan table. The prefered\n    ** name is zLostAndFound. But if that clashes with another name\n    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1\n    ** and so on until a non-clashing name is found.  */\n    int iTab = 0;\n    char *zTab = shellMPrintf(pRc, \"%s\", zLostAndFound);\n    sqlite3_stmt *pTest = 0;\n    shellPrepare(pState->db, pRc,\n        \"SELECT 1 FROM recovery.schema WHERE name=?\", &pTest\n    );\n    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);\n    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){\n      shellReset(pRc, pTest);\n      sqlite3_free(zTab);\n      zTab = shellMPrintf(pRc, \"%s_%d\", zLostAndFound, iTab++);\n      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);\n    }\n    shellFinalize(pRc, pTest);\n\n    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));\n    if( pTab ){\n      pTab->zQuoted = shellMPrintf(pRc, \"\\\"%w\\\"\", zTab);\n      pTab->nCol = nCol;\n      pTab->iPk = -2;\n      if( nCol>0 ){\n        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));\n        if( pTab->azlCol ){\n          pTab->azlCol[nCol] = shellMPrintf(pRc, \"\");\n          for(i=nCol-1; i>=0; i--){\n            pTab->azlCol[i] = shellMPrintf(pRc, \"%s, NULL\", pTab->azlCol[i+1]);\n          }\n        }\n      }\n\n      if( *pRc!=SQLITE_OK ){\n        recoverFreeTable(pTab);\n        pTab = 0;\n      }else{\n        raw_printf(pState->out, \n            \"CREATE TABLE %s(rootpgno INTEGER, \"\n            \"pgno INTEGER, nfield INTEGER, id INTEGER\", pTab->zQuoted\n        );\n        for(i=0; i<nCol; i++){\n          raw_printf(pState->out, \", c%d\", i);\n        }\n        raw_printf(pState->out, \");\\n\");\n      }\n    }\n    sqlite3_free(zTab);\n  }\n  return pTab;\n}\n\n/*\n** This function is called to recover data from the database. A script\n** to construct a new database containing all recovered data is output\n** on stream pState->out.\n*/\nstatic int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){\n  int rc = SQLITE_OK;\n  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */\n  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */\n  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */\n  const char *zRecoveryDb = \"\";   /* Name of \"recovery\" database */\n  const char *zLostAndFound = \"lost_and_found\";\n  int i;\n  int nOrphan = -1;\n  RecoverTable *pOrphan = 0;\n\n  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */\n  int bRowids = 1;                /* 0 if --no-rowids */\n  for(i=1; i<nArg; i++){\n    char *z = azArg[i];\n    int n;\n    if( z[0]=='-' && z[1]=='-' ) z++;\n    n = strlen30(z);\n    if( n<=17 && memcmp(\"-freelist-corrupt\", z, n)==0 ){\n      bFreelist = 0;\n    }else\n    if( n<=12 && memcmp(\"-recovery-db\", z, n)==0 && i<(nArg-1) ){\n      i++;\n      zRecoveryDb = azArg[i];\n    }else\n    if( n<=15 && memcmp(\"-lost-and-found\", z, n)==0 && i<(nArg-1) ){\n      i++;\n      zLostAndFound = azArg[i];\n    }else\n    if( n<=10 && memcmp(\"-no-rowids\", z, n)==0 ){\n      bRowids = 0;\n    }\n    else{\n      utf8_printf(stderr, \"unexpected option: %s\\n\", azArg[i]); \n      showHelp(pState->out, azArg[0]);\n      return 1;\n    }\n  }\n\n  shellExecPrintf(pState->db, &rc,\n    /* Attach an in-memory database named 'recovery'. Create an indexed \n    ** cache of the sqlite_dbptr virtual table. */\n    \"PRAGMA writable_schema = on;\"\n    \"ATTACH %Q AS recovery;\"\n    \"DROP TABLE IF EXISTS recovery.dbptr;\"\n    \"DROP TABLE IF EXISTS recovery.freelist;\"\n    \"DROP TABLE IF EXISTS recovery.map;\"\n    \"DROP TABLE IF EXISTS recovery.schema;\"\n    \"CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);\", zRecoveryDb\n  );\n\n  if( bFreelist ){\n    shellExec(pState->db, &rc,\n      \"WITH trunk(pgno) AS (\"\n      \"  SELECT shell_int32(\"\n      \"      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x \"\n      \"      WHERE x>0\"\n      \"    UNION\"\n      \"  SELECT shell_int32(\"\n      \"      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x \"\n      \"      FROM trunk WHERE x>0\"\n      \"),\"\n      \"freelist(data, n, freepgno) AS (\"\n      \"  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno \"\n      \"      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno\"\n      \"    UNION ALL\"\n      \"  SELECT data, n-1, shell_int32(data, 2+n) \"\n      \"      FROM freelist WHERE n>=0\"\n      \")\"\n      \"REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;\"\n    );\n  }\n\n  /* If this is an auto-vacuum database, add all pointer-map pages to\n  ** the freelist table. Do this regardless of whether or not \n  ** --freelist-corrupt was specified.  */\n  shellExec(pState->db, &rc, \n    \"WITH ptrmap(pgno) AS (\"\n    \"  SELECT 2 WHERE shell_int32(\"\n    \"    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13\"\n    \"  )\"\n    \"    UNION ALL \"\n    \"  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp \"\n    \"  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)\"\n    \")\"\n    \"REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap\"\n  );\n\n  shellExec(pState->db, &rc, \n    \"CREATE TABLE recovery.dbptr(\"\n    \"      pgno, child, PRIMARY KEY(child, pgno)\"\n    \") WITHOUT ROWID;\"\n    \"INSERT OR IGNORE INTO recovery.dbptr(pgno, child) \"\n    \"    SELECT * FROM sqlite_dbptr\"\n    \"      WHERE pgno NOT IN freelist AND child NOT IN freelist;\"\n\n    /* Delete any pointer to page 1. This ensures that page 1 is considered\n    ** a root page, regardless of how corrupt the db is. */\n    \"DELETE FROM recovery.dbptr WHERE child = 1;\"\n\n    /* Delete all pointers to any pages that have more than one pointer\n    ** to them. Such pages will be treated as root pages when recovering\n    ** data.  */\n    \"DELETE FROM recovery.dbptr WHERE child IN (\"\n    \"  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1\"\n    \");\"\n\n    /* Create the \"map\" table that will (eventually) contain instructions\n    ** for dealing with each page in the db that contains one or more \n    ** records. */\n    \"CREATE TABLE recovery.map(\"\n      \"pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT\"\n    \");\"\n\n    /* Populate table [map]. If there are circular loops of pages in the\n    ** database, the following adds all pages in such a loop to the map\n    ** as individual root pages. This could be handled better.  */\n    \"WITH pages(i, maxlen) AS (\"\n    \"  SELECT page_count, (\"\n    \"    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count\"\n    \"  ) FROM pragma_page_count WHERE page_count>0\"\n    \"    UNION ALL\"\n    \"  SELECT i-1, (\"\n    \"    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1\"\n    \"  ) FROM pages WHERE i>=2\"\n    \")\"\n    \"INSERT INTO recovery.map(pgno, maxlen, intkey, root) \"\n    \"  SELECT i, maxlen, NULL, (\"\n    \"    WITH p(orig, pgno, parent) AS (\"\n    \"      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)\"\n    \"        UNION \"\n    \"      SELECT i, p.parent, \"\n    \"        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p\"\n    \"    )\"\n    \"    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)\"\n    \") \"\n    \"FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;\"\n    \"UPDATE recovery.map AS o SET intkey = (\"\n    \"  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno\"\n    \");\"\n\n    /* Extract data from page 1 and any linked pages into table\n    ** recovery.schema. With the same schema as an sqlite_master table.  */\n    \"CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);\"\n    \"INSERT INTO recovery.schema SELECT \"\n    \"  max(CASE WHEN field=0 THEN value ELSE NULL END),\"\n    \"  max(CASE WHEN field=1 THEN value ELSE NULL END),\"\n    \"  max(CASE WHEN field=2 THEN value ELSE NULL END),\"\n    \"  max(CASE WHEN field=3 THEN value ELSE NULL END),\"\n    \"  max(CASE WHEN field=4 THEN value ELSE NULL END)\"\n    \"FROM sqlite_dbdata WHERE pgno IN (\"\n    \"  SELECT pgno FROM recovery.map WHERE root=1\"\n    \")\"\n    \"GROUP BY pgno, cell;\"\n    \"CREATE INDEX recovery.schema_rootpage ON schema(rootpage);\"\n  );\n\n  /* Open a transaction, then print out all non-virtual, non-\"sqlite_%\" \n  ** CREATE TABLE statements that extracted from the existing schema.  */\n  if( rc==SQLITE_OK ){\n    sqlite3_stmt *pStmt = 0;\n    /* \".recover\" might output content in an order which causes immediate\n    ** foreign key constraints to be violated. So disable foreign-key\n    ** constraint enforcement to prevent problems when running the output\n    ** script. */\n    raw_printf(pState->out, \"PRAGMA foreign_keys=OFF;\\n\");\n    raw_printf(pState->out, \"BEGIN;\\n\");\n    raw_printf(pState->out, \"PRAGMA writable_schema = on;\\n\");\n    shellPrepare(pState->db, &rc,\n        \"SELECT sql FROM recovery.schema \"\n        \"WHERE type='table' AND sql LIKE 'create table%'\", &pStmt\n    );\n    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){\n      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);\n      raw_printf(pState->out, \"CREATE TABLE IF NOT EXISTS %s;\\n\", \n          &zCreateTable[12]\n      );\n    }\n    shellFinalize(&rc, pStmt);\n  }\n\n  /* Figure out if an orphan table will be required. And if so, how many\n  ** user columns it should contain */\n  shellPrepare(pState->db, &rc, \n      \"SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1\"\n      , &pLoop\n  );\n  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){\n    nOrphan = sqlite3_column_int(pLoop, 0);\n  }\n  shellFinalize(&rc, pLoop);\n  pLoop = 0;\n\n  shellPrepare(pState->db, &rc,\n      \"SELECT pgno FROM recovery.map WHERE root=?\", &pPages\n  );\n\n  shellPrepare(pState->db, &rc,\n      \"SELECT max(field), group_concat(shell_escape_crnl(quote\"\n      \"(case when (? AND field<0) then NULL else value end)\"\n      \"), ', ')\"\n      \", min(field) \"\n      \"FROM sqlite_dbdata WHERE pgno = ? AND field != ?\"\n      \"GROUP BY cell\", &pCells\n  );\n\n  /* Loop through each root page. */\n  shellPrepare(pState->db, &rc, \n      \"SELECT root, intkey, max(maxlen) FROM recovery.map\" \n      \" WHERE root>1 GROUP BY root, intkey ORDER BY root=(\"\n      \"  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'\"\n      \")\", &pLoop\n  );\n  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){\n    int iRoot = sqlite3_column_int(pLoop, 0);\n    int bIntkey = sqlite3_column_int(pLoop, 1);\n    int nCol = sqlite3_column_int(pLoop, 2);\n    int bNoop = 0;\n    RecoverTable *pTab;\n\n    assert( bIntkey==0 || bIntkey==1 );\n    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);\n    if( bNoop || rc ) continue;\n    if( pTab==0 ){\n      if( pOrphan==0 ){\n        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);\n      }\n      pTab = pOrphan;\n      if( pTab==0 ) break;\n    }\n\n    if( 0==sqlite3_stricmp(pTab->zQuoted, \"\\\"sqlite_sequence\\\"\") ){\n      raw_printf(pState->out, \"DELETE FROM sqlite_sequence;\\n\");\n    }\n    sqlite3_bind_int(pPages, 1, iRoot);\n    if( bRowids==0 && pTab->iPk<0 ){\n      sqlite3_bind_int(pCells, 1, 1);\n    }else{\n      sqlite3_bind_int(pCells, 1, 0);\n    }\n    sqlite3_bind_int(pCells, 3, pTab->iPk);\n\n    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){\n      int iPgno = sqlite3_column_int(pPages, 0);\n      sqlite3_bind_int(pCells, 2, iPgno);\n      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){\n        int nField = sqlite3_column_int(pCells, 0);\n        int iMin = sqlite3_column_int(pCells, 2);\n        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);\n\n        RecoverTable *pTab2 = pTab;\n        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){\n          if( pOrphan==0 ){\n            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);\n          }\n          pTab2 = pOrphan;\n          if( pTab2==0 ) break;\n        }\n\n        nField = nField+1;\n        if( pTab2==pOrphan ){\n          raw_printf(pState->out, \n              \"INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\\n\",\n              pTab2->zQuoted, iRoot, iPgno, nField,\n              iMin<0 ? \"\" : \"NULL, \", zVal, pTab2->azlCol[nField]\n          );\n        }else{\n          raw_printf(pState->out, \"INSERT INTO %s(%s) VALUES( %s );\\n\", \n              pTab2->zQuoted, pTab2->azlCol[nField], zVal\n          );\n        }\n      }\n      shellReset(&rc, pCells);\n    }\n    shellReset(&rc, pPages);\n    if( pTab!=pOrphan ) recoverFreeTable(pTab);\n  }\n  shellFinalize(&rc, pLoop);\n  shellFinalize(&rc, pPages);\n  shellFinalize(&rc, pCells);\n  recoverFreeTable(pOrphan);\n\n  /* The rest of the schema */\n  if( rc==SQLITE_OK ){\n    sqlite3_stmt *pStmt = 0;\n    shellPrepare(pState->db, &rc, \n        \"SELECT sql, name FROM recovery.schema \"\n        \"WHERE sql NOT LIKE 'create table%'\", &pStmt\n    );\n    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){\n      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);\n      if( sqlite3_strnicmp(zSql, \"create virt\", 11)==0 ){\n        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);\n        char *zPrint = shellMPrintf(&rc, \n          \"INSERT INTO sqlite_master VALUES('table', %Q, %Q, 0, %Q)\",\n          zName, zName, zSql\n        );\n        raw_printf(pState->out, \"%s;\\n\", zPrint);\n        sqlite3_free(zPrint);\n      }else{\n        raw_printf(pState->out, \"%s;\\n\", zSql);\n      }\n    }\n    shellFinalize(&rc, pStmt);\n  }\n\n  if( rc==SQLITE_OK ){\n    raw_printf(pState->out, \"PRAGMA writable_schema = off;\\n\");\n    raw_printf(pState->out, \"COMMIT;\\n\");\n  }\n  sqlite3_exec(pState->db, \"DETACH recovery\", 0, 0, 0);\n  return rc;\n}\n#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */\n\n\n/*\n** If an input line begins with \".\" then invoke this routine to\n** process that line.\n**\n** Return 1 on error, 2 to exit, and 0 otherwise.\n*/\nstatic int do_meta_command(char *zLine, ShellState *p){\n  int h = 1;\n  int nArg = 0;\n  int n, c;\n  int rc = 0;\n  char *azArg[52];\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( p->expert.pExpert ){\n    expertFinish(p, 1, 0);\n  }\n#endif\n\n  /* Parse the input line into tokens.\n  */\n  while( zLine[h] && nArg<ArraySize(azArg)-1 ){\n    while( IsSpace(zLine[h]) ){ h++; }\n    if( zLine[h]==0 ) break;\n    if( zLine[h]=='\\'' || zLine[h]=='\"' ){\n      int delim = zLine[h++];\n      azArg[nArg++] = &zLine[h];\n      while( zLine[h] && zLine[h]!=delim ){\n        if( zLine[h]=='\\\\' && delim=='\"' && zLine[h+1]!=0 ) h++;\n        h++;\n      }\n      if( zLine[h]==delim ){\n        zLine[h++] = 0;\n      }\n      if( delim=='\"' ) resolve_backslashes(azArg[nArg-1]);\n    }else{\n      azArg[nArg++] = &zLine[h];\n      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }\n      if( zLine[h] ) zLine[h++] = 0;\n      resolve_backslashes(azArg[nArg-1]);\n    }\n  }\n  azArg[nArg] = 0;\n\n  /* Process the input line.\n  */\n  if( nArg==0 ) return 0; /* no tokens, no error */\n  n = strlen30(azArg[0]);\n  c = azArg[0][0];\n  clearTempFile(p);\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  if( c=='a' && strncmp(azArg[0], \"auth\", n)==0 ){\n    if( nArg!=2 ){\n      raw_printf(stderr, \"Usage: .auth ON|OFF\\n\");\n      rc = 1;\n      goto meta_command_exit;\n    }\n    open_db(p, 0);\n    if( booleanValue(azArg[1]) ){\n      sqlite3_set_authorizer(p->db, shellAuth, p);\n    }else{\n      sqlite3_set_authorizer(p->db, 0, 0);\n    }\n  }else\n#endif\n\n#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)\n  if( c=='a' && strncmp(azArg[0], \"archive\", n)==0 ){\n    open_db(p, 0);\n    rc = arDotCommand(p, 0, azArg, nArg);\n  }else\n#endif\n\n  if( (c=='b' && n>=3 && strncmp(azArg[0], \"backup\", n)==0)\n   || (c=='s' && n>=3 && strncmp(azArg[0], \"save\", n)==0)\n  ){\n    const char *zDestFile = 0;\n    const char *zDb = 0;\n    sqlite3 *pDest;\n    sqlite3_backup *pBackup;\n    int j;\n    int bAsync = 0;\n    const char *zVfs = 0;\n    for(j=1; j<nArg; j++){\n      const char *z = azArg[j];\n      if( z[0]=='-' ){\n        if( z[1]=='-' ) z++;\n        if( strcmp(z, \"-append\")==0 ){\n          zVfs = \"apndvfs\";\n        }else\n        if( strcmp(z, \"-async\")==0 ){\n          bAsync = 1;\n        }else\n        {\n          utf8_printf(stderr, \"unknown option: %s\\n\", azArg[j]);\n          return 1;\n        }\n      }else if( zDestFile==0 ){\n        zDestFile = azArg[j];\n      }else if( zDb==0 ){\n        zDb = zDestFile;\n        zDestFile = azArg[j];\n      }else{\n        raw_printf(stderr, \"Usage: .backup ?DB? ?OPTIONS? FILENAME\\n\");\n        return 1;\n      }\n    }\n    if( zDestFile==0 ){\n      raw_printf(stderr, \"missing FILENAME argument on .backup\\n\");\n      return 1;\n    }\n    if( zDb==0 ) zDb = \"main\";\n    rc = sqlite3_open_v2(zDestFile, &pDest, \n                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);\n    if( rc!=SQLITE_OK ){\n      utf8_printf(stderr, \"Error: cannot open \\\"%s\\\"\\n\", zDestFile);\n      close_db(pDest);\n      return 1;\n    }\n    if( bAsync ){\n      sqlite3_exec(pDest, \"PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;\",\n                   0, 0, 0);\n    }\n    open_db(p, 0);\n    pBackup = sqlite3_backup_init(pDest, \"main\", p->db, zDb);\n    if( pBackup==0 ){\n      utf8_printf(stderr, \"Error: %s\\n\", sqlite3_errmsg(pDest));\n      close_db(pDest);\n      return 1;\n    }\n    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}\n    sqlite3_backup_finish(pBackup);\n    if( rc==SQLITE_DONE ){\n      rc = 0;\n    }else{\n      utf8_printf(stderr, \"Error: %s\\n\", sqlite3_errmsg(pDest));\n      rc = 1;\n    }\n    close_db(pDest);\n  }else\n\n  if( c=='b' && n>=3 && strncmp(azArg[0], \"bail\", n)==0 ){\n    if( nArg==2 ){\n      bail_on_error = booleanValue(azArg[1]);\n    }else{\n      raw_printf(stderr, \"Usage: .bail on|off\\n\");\n      rc = 1;\n    }\n  }else\n\n  if( c=='b' && n>=3 && strncmp(azArg[0], \"binary\", n)==0 ){\n    if( nArg==2 ){\n      if( booleanValue(azArg[1]) ){\n        setBinaryMode(p->out, 1);\n      }else{\n        setTextMode(p->out, 1);\n      }\n    }else{\n      raw_printf(stderr, \"Usage: .binary on|off\\n\");\n      rc = 1;\n    }\n  }else\n\n  if( c=='c' && strcmp(azArg[0],\"cd\")==0 ){\n    if( nArg==2 ){\n#if defined(_WIN32) || defined(WIN32)\n      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);\n      rc = !SetCurrentDirectoryW(z);\n      sqlite3_free(z);\n#else\n      rc = chdir(azArg[1]);\n#endif\n      if( rc ){\n        utf8_printf(stderr, \"Cannot change to directory \\\"%s\\\"\\n\", azArg[1]);\n        rc = 1;\n      }\n    }else{\n      raw_printf(stderr, \"Usage: .cd DIRECTORY\\n\");\n      rc = 1;\n    }\n  }else\n\n  /* The undocumented \".breakpoint\" command causes a call to the no-op\n  ** routine named test_breakpoint().\n  */\n  if( c=='b' && n>=3 && strncmp(azArg[0], \"breakpoint\", n)==0 ){\n    test_breakpoint();\n  }else\n\n  if( c=='c' && n>=3 && strncmp(azArg[0], \"changes\", n)==0 ){\n    if( nArg==2 ){\n      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);\n    }else{\n      raw_printf(stderr, \"Usage: .changes on|off\\n\");\n      rc = 1;\n    }\n  }else\n\n  /* Cancel output redirection, if it is currently set (by .testcase)\n  ** Then read the content of the testcase-out.txt file and compare against\n  ** azArg[1].  If there are differences, report an error and exit.\n  */\n  if( c=='c' && n>=3 && strncmp(azArg[0], \"check\", n)==0 ){\n    char *zRes = 0;\n    output_reset(p);\n    if( nArg!=2 ){\n      raw_printf(stderr, \"Usage: .check GLOB-PATTERN\\n\");\n      rc = 2;\n    }else if( (zRes = readFile(\"testcase-out.txt\", 0))==0 ){\n      raw_printf(stderr, \"Error: cannot read 'testcase-out.txt'\\n\");\n      rc = 2;\n    }else if( testcase_glob(azArg[1],zRes)==0 ){\n      utf8_printf(stderr,\n                 \"testcase-%s FAILED\\n Expected: [%s]\\n      Got: [%s]\\n\",\n                 p->zTestcase, azArg[1], zRes);\n      rc = 1;\n    }else{\n      utf8_printf(stdout, \"testcase-%s ok\\n\", p->zTestcase);\n      p->nCheck++;\n    }\n    sqlite3_free(zRes);\n  }else\n\n  if( c=='c' && strncmp(azArg[0], \"clone\", n)==0 ){\n    if( nArg==2 ){\n      tryToClone(p, azArg[1]);\n    }else{\n      raw_printf(stderr, \"Usage: .clone FILENAME\\n\");\n      rc = 1;\n    }\n  }else\n\n  if( c=='d' && n>1 && strncmp(azArg[0], \"databases\", n)==0 ){\n    ShellState data;\n    char *zErrMsg = 0;\n    open_db(p, 0);\n    memcpy(&data, p, sizeof(data));\n    data.showHeader = 0;\n    data.cMode = data.mode = MODE_List;\n    sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,\": \");\n    data.cnt = 0;\n    sqlite3_exec(p->db, \"SELECT name, file FROM pragma_database_list\",\n                 callback, &data, &zErrMsg);\n    if( zErrMsg ){\n      utf8_printf(stderr,\"Error: %s\\n\", zErrMsg);\n      sqlite3_free(zErrMsg);\n      rc = 1;\n    }\n  }else\n\n  if( c=='d' && n>=3 && strncmp(azArg[0], \"dbconfig\", n)==0 ){\n    static const struct DbConfigChoices {\n      const char *zName;\n      int op;\n    } aDbConfig[] = {\n        { \"defensive\",          SQLITE_DBCONFIG_DEFENSIVE             },\n        { \"dqs_ddl\",            SQLITE_DBCONFIG_DQS_DDL               },\n        { \"dqs_dml\",            SQLITE_DBCONFIG_DQS_DML               },\n        { \"enable_fkey\",        SQLITE_DBCONFIG_ENABLE_FKEY           },\n        { \"enable_qpsg\",        SQLITE_DBCONFIG_ENABLE_QPSG           },\n        { \"enable_trigger\",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },\n        { \"enable_view\",        SQLITE_DBCONFIG_ENABLE_VIEW           },\n        { \"fts3_tokenizer\",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },\n        { \"legacy_alter_table\", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },\n        { \"legacy_file_format\", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },\n        { \"load_extension\",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },\n        { \"no_ckpt_on_close\",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },\n        { \"reset_database\",     SQLITE_DBCONFIG_RESET_DATABASE        },\n        { \"trigger_eqp\",        SQLITE_DBCONFIG_TRIGGER_EQP           },\n        { \"trusted_schema\",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },\n        { \"writable_schema\",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },\n    };\n    int ii, v;\n    open_db(p, 0);\n    for(ii=0; ii<ArraySize(aDbConfig); ii++){\n      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;\n      if( nArg>=3 ){\n        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);\n      }\n      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);\n      utf8_printf(p->out, \"%19s %s\\n\", aDbConfig[ii].zName, v ? \"on\" : \"off\");\n      if( nArg>1 ) break;\n    }\n    if( nArg>1 && ii==ArraySize(aDbConfig) ){\n      utf8_printf(stderr, \"Error: unknown dbconfig \\\"%s\\\"\\n\", azArg[1]);\n      utf8_printf(stderr, \"Enter \\\".dbconfig\\\" with no arguments for a list\\n\");\n    }   \n  }else\n\n  if( c=='d' && n>=3 && strncmp(azArg[0], \"dbinfo\", n)==0 ){\n    rc = shell_dbinfo_command(p, nArg, azArg);\n  }else\n\n#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)\n  if( c=='r' && strncmp(azArg[0], \"recover\", n)==0 ){\n    open_db(p, 0);\n    rc = recoverDatabaseCmd(p, nArg, azArg);\n  }else\n#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */\n\n  if( c=='d' && strncmp(azArg[0], \"dump\", n)==0 ){\n    char *zLike = 0;\n    char *zSql;\n    int i;\n    int savedShowHeader = p->showHeader;\n    int savedShellFlags = p->shellFlgs;\n    ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);\n    for(i=1; i<nArg; i++){\n      if( azArg[i][0]=='-' ){\n        const char *z = azArg[i]+1;\n        if( z[0]=='-' ) z++;\n        if( strcmp(z,\"preserve-rowids\")==0 ){\n#ifdef SQLITE_OMIT_VIRTUALTABLE\n          raw_printf(stderr, \"The --preserve-rowids option is not compatible\"\n                             \" with SQLITE_OMIT_VIRTUALTABLE\\n\");\n          rc = 1;\n          goto meta_command_exit;\n#else\n          ShellSetFlag(p, SHFLG_PreserveRowid);\n#endif\n        }else\n        if( strcmp(z,\"newlines\")==0 ){\n          ShellSetFlag(p, SHFLG_Newlines);\n        }else\n        {\n          raw_printf(stderr, \"Unknown option \\\"%s\\\" on \\\".dump\\\"\\n\", azArg[i]);\n          rc = 1;\n          goto meta_command_exit;\n        }\n      }else if( zLike ){\n        zLike = sqlite3_mprintf(\"%z OR name LIKE %Q ESCAPE '\\\\'\",\n                zLike, azArg[i]);\n      }else{\n        zLike = sqlite3_mprintf(\"name LIKE %Q ESCAPE '\\\\'\", azArg[i]);\n      }\n    }\n\n    open_db(p, 0);\n\n    /* When playing back a \"dump\", the content might appear in an order\n    ** which causes immediate foreign key constraints to be violated.\n    ** So disable foreign-key constraint enforcement to prevent problems. */\n    raw_printf(p->out, \"PRAGMA foreign_keys=OFF;\\n\");\n    raw_printf(p->out, \"BEGIN TRANSACTION;\\n\");\n    p->writableSchema = 0;\n    p->showHeader = 0;\n    /* Set writable_schema=ON since doing so forces SQLite to initialize\n    ** as much of the schema as it can even if the sqlite_master table is\n    ** corrupt. */\n    sqlite3_exec(p->db, \"SAVEPOINT dump; PRAGMA writable_schema=ON\", 0, 0, 0);\n    p->nErr = 0;\n    if( zLike==0 ) zLike = sqlite3_mprintf(\"true\");\n    zSql = sqlite3_mprintf(\n      \"SELECT name, type, sql FROM sqlite_master \"\n      \"WHERE (%s) AND type=='table'\"\n      \"  AND sql NOT NULL\"\n      \" ORDER BY tbl_name='sqlite_sequence', rowid\",\n      zLike\n    );\n    run_schema_dump_query(p,zSql);\n    sqlite3_free(zSql);\n    zSql = sqlite3_mprintf(\n      \"SELECT sql FROM sqlite_master \"\n      \"WHERE (%s) AND sql NOT NULL\"\n      \"  AND type IN ('index','trigger','view')\",\n      zLike\n    );\n    run_table_dump_query(p, zSql);\n    sqlite3_free(zSql);\n    sqlite3_free(zLike);\n    if( p->writableSchema ){\n      raw_printf(p->out, \"PRAGMA writable_schema=OFF;\\n\");\n      p->writableSchema = 0;\n    }\n    sqlite3_exec(p->db, \"PRAGMA writable_schema=OFF;\", 0, 0, 0);\n    sqlite3_exec(p->db, \"RELEASE dump;\", 0, 0, 0);\n    raw_printf(p->out, p->nErr?\"ROLLBACK; -- due to errors\\n\":\"COMMIT;\\n\");\n    p->showHeader = savedShowHeader;\n    p->shellFlgs = savedShellFlags;\n  }else\n\n  if( c=='e' && strncmp(azArg[0], \"echo\", n)==0 ){\n    if( nArg==2 ){\n      setOrClearFlag(p, SHFLG_Echo, azArg[1]);\n    }else{\n      raw_printf(stderr, \"Usage: .echo on|off\\n\");\n      rc = 1;\n    }\n  }else\n\n  if( c=='e' && strncmp(azArg[0], \"eqp\", n)==0 ){\n    if( nArg==2 ){\n      p->autoEQPtest = 0;\n      if( p->autoEQPtrace ){\n        if( p->db ) sqlite3_exec(p->db, \"PRAGMA vdbe_trace=OFF;\", 0, 0, 0);\n        p->autoEQPtrace = 0;\n      }\n      if( strcmp(azArg[1],\"full\")==0 ){\n        p->autoEQP = AUTOEQP_full;\n      }else if( strcmp(azArg[1],\"trigger\")==0 ){\n        p->autoEQP = AUTOEQP_trigger;\n#ifdef SQLITE_DEBUG\n      }else if( strcmp(azArg[1],\"test\")==0 ){\n        p->autoEQP = AUTOEQP_on;\n        p->autoEQPtest = 1;\n      }else if( strcmp(azArg[1],\"trace\")==0 ){\n        p->autoEQP = AUTOEQP_full;\n        p->autoEQPtrace = 1;\n        open_db(p, 0);\n        sqlite3_exec(p->db, \"SELECT name FROM sqlite_master LIMIT 1\", 0, 0, 0);\n        sqlite3_exec(p->db, \"PRAGMA vdbe_trace=ON;\", 0, 0, 0);\n#endif\n      }else{\n        p->autoEQP = (u8)booleanValue(azArg[1]);\n      }\n    }else{\n      raw_printf(stderr, \"Usage: .eqp off|on|trace|trigger|full\\n\");\n      rc = 1;\n    }\n  }else\n\n  if( c=='e' && strncmp(azArg[0], \"exit\", n)==0 ){\n    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);\n    rc = 2;\n  }else\n\n  /* The \".explain\" command is automatic now.  It is largely pointless.  It\n  ** retained purely for backwards compatibility */\n  if( c=='e' && strncmp(azArg[0], \"explain\", n)==0 ){\n    int val = 1;\n    if( nArg>=2 ){\n      if( strcmp(azArg[1],\"auto\")==0 ){\n        val = 99;\n      }else{\n        val =  booleanValue(azArg[1]);\n      }\n    }\n    if( val==1 && p->mode!=MODE_Explain ){\n      p->normalMode = p->mode;\n      p->mode = MODE_Explain;\n      p->autoExplain = 0;\n    }else if( val==0 ){\n      if( p->mode==MODE_Explain ) p->mode = p->normalMode;\n      p->autoExplain = 0;\n    }else if( val==99 ){\n      if( p->mode==MODE_Explain ) p->mode = p->normalMode;\n      p->autoExplain = 1;\n    }\n  }else\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( c=='e' && strncmp(azArg[0], \"expert\", n)==0 ){\n    open_db(p, 0);\n    expertDotCommand(p, azArg, nArg);\n  }else\n#endif\n\n  if( c=='f' && strncmp(azArg[0], \"filectrl\", n)==0 ){\n    static const struct {\n       const char *zCtrlName;   /* Name of a test-control option */\n       int ctrlCode;            /* Integer code for that option */\n       const char *zUsage;      /* Usage notes */\n    } aCtrl[] = {\n      { \"size_limit\",     SQLITE_FCNTL_SIZE_LIMIT,      \"[LIMIT]\"        },\n      { \"chunk_size\",     SQLITE_FCNTL_CHUNK_SIZE,      \"SIZE\"           },\n   /* { \"win32_av_retry\", SQLITE_FCNTL_WIN32_AV_RETRY,  \"COUNT DELAY\"    },*/\n      { \"persist_wal\",    SQLITE_FCNTL_PERSIST_WAL,     \"[BOOLEAN]\"      },\n      { \"psow\",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, \"[BOOLEAN]\"      },\n   /* { \"pragma\",         SQLITE_FCNTL_PRAGMA,          \"NAME ARG\"       },*/\n      { \"tempfilename\",   SQLITE_FCNTL_TEMPFILENAME,    \"\"               },\n      { \"has_moved\",      SQLITE_FCNTL_HAS_MOVED,       \"\"               },  \n      { \"lock_timeout\",   SQLITE_FCNTL_LOCK_TIMEOUT,    \"MILLISEC\"       },\n      { \"reserve_bytes\",  SQLITE_FCNTL_RESERVE_BYTES,   \"[N]\"            },\n    };\n    int filectrl = -1;\n    int iCtrl = -1;\n    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */\n    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */\n    int n2, i;\n    const char *zCmd = 0;\n    const char *zSchema = 0;\n\n    open_db(p, 0);\n    zCmd = nArg>=2 ? azArg[1] : \"help\";\n\n    if( zCmd[0]=='-' \n     && (strcmp(zCmd,\"--schema\")==0 || strcmp(zCmd,\"-schema\")==0)\n     && nArg>=4\n    ){\n      zSchema = azArg[2];\n      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];\n      nArg -= 2;\n      zCmd = azArg[1];\n    }\n\n    /* The argument can optionally begin with \"-\" or \"--\" */\n    if( zCmd[0]=='-' && zCmd[1] ){\n      zCmd++;\n      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;\n    }\n\n    /* --help lists all file-controls */\n    if( strcmp(zCmd,\"help\")==0 ){\n      utf8_printf(p->out, \"Available file-controls:\\n\");\n      for(i=0; i<ArraySize(aCtrl); i++){\n        utf8_printf(p->out, \"  .filectrl %s %s\\n\",\n                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);\n      }\n      rc = 1;\n      goto meta_command_exit;\n    }\n\n    /* convert filectrl text option to value. allow any unique prefix\n    ** of the option name, or a numerical value. */\n    n2 = strlen30(zCmd);\n    for(i=0; i<ArraySize(aCtrl); i++){\n      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){\n        if( filectrl<0 ){\n          filectrl = aCtrl[i].ctrlCode;\n          iCtrl = i;\n        }else{\n          utf8_printf(stderr, \"Error: ambiguous file-control: \\\"%s\\\"\\n\"\n                              \"Use \\\".filectrl --help\\\" for help\\n\", zCmd);\n          rc = 1;\n          goto meta_command_exit;\n        }\n      }\n    }\n    if( filectrl<0 ){\n      utf8_printf(stderr,\"Error: unknown file-control: %s\\n\"\n                         \"Use \\\".filectrl --help\\\" for help\\n\", zCmd);\n    }else{\n      switch(filectrl){\n        case SQLITE_FCNTL_SIZE_LIMIT: {\n          if( nArg!=2 && nArg!=3 ) break;\n          iRes = nArg==3 ? integerValue(azArg[2]) : -1;\n          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);\n          isOk = 1;\n          break;\n        }\n        case SQLITE_FCNTL_LOCK_TIMEOUT:\n        case SQLITE_FCNTL_CHUNK_SIZE: {\n          int x;\n          if( nArg!=3 ) break;\n          x = (int)integerValue(azArg[2]);\n          sqlite3_file_control(p->db, zSchema, filectrl, &x);\n          isOk = 2;\n          break;\n        }\n        case SQLITE_FCNTL_PERSIST_WAL:\n        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {\n          int x;\n          if( nArg!=2 && nArg!=3 ) break;\n          x = nArg==3 ? booleanValue(azArg[2]) : -1;\n          sqlite3_file_control(p->db, zSchema, filectrl, &x);\n          iRes = x;\n          isOk = 1;\n          break;\n        }\n        case SQLITE_FCNTL_HAS_MOVED: {\n          int x;\n          if( nArg!=2 ) break;\n          sqlite3_file_control(p->db, zSchema, filectrl, &x);\n          iRes = x;\n          isOk = 1;\n          break;\n        }\n        case SQLITE_FCNTL_TEMPFILENAME: {\n          char *z = 0;\n          if( nArg!=2 ) break;\n          sqlite3_file_control(p->db, zSchema, filectrl, &z);\n          if( z ){\n            utf8_printf(p->out, \"%s\\n\", z);\n            sqlite3_free(z);\n          }\n          isOk = 2;\n          break;\n        }\n        case SQLITE_FCNTL_RESERVE_BYTES: {\n          int x;\n          if( nArg>=3 ){\n            x = atoi(azArg[2]);\n            sqlite3_file_control(p->db, zSchema, filectrl, &x);\n          }\n          x = -1;\n          sqlite3_file_control(p->db, zSchema, filectrl, &x);\n          utf8_printf(p->out,\"%d\\n\", x);\n          isOk = 2;\n          break;\n        }\n      }\n    }\n    if( isOk==0 && iCtrl>=0 ){\n      utf8_printf(p->out, \"Usage: .filectrl %s %s\\n\", zCmd,aCtrl[iCtrl].zUsage);\n      rc = 1;\n    }else if( isOk==1 ){\n      char zBuf[100];\n      sqlite3_snprintf(sizeof(zBuf), zBuf, \"%lld\", iRes);\n      raw_printf(p->out, \"%s\\n\", zBuf);\n    }\n  }else\n\n  if( c=='f' && strncmp(azArg[0], \"fullschema\", n)==0 ){\n    ShellState data;\n    char *zErrMsg = 0;\n    int doStats = 0;\n    memcpy(&data, p, sizeof(data));\n    data.showHeader = 0;\n    data.cMode = data.mode = MODE_Semi;\n    if( nArg==2 && optionMatch(azArg[1], \"indent\") ){\n      data.cMode = data.mode = MODE_Pretty;\n      nArg = 1;\n    }\n    if( nArg!=1 ){\n      raw_printf(stderr, \"Usage: .fullschema ?--indent?\\n\");\n      rc = 1;\n      goto meta_command_exit;\n    }\n    open_db(p, 0);\n    rc = sqlite3_exec(p->db,\n       \"SELECT sql FROM\"\n       \"  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x\"\n       \"     FROM sqlite_master UNION ALL\"\n       \"   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) \"\n       \"WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' \"\n       \"ORDER BY rowid\",\n       callback, &data, &zErrMsg\n    );\n    if( rc==SQLITE_OK ){\n      sqlite3_stmt *pStmt;\n      rc = sqlite3_prepare_v2(p->db,\n               \"SELECT rowid FROM sqlite_master\"\n               \" WHERE name GLOB 'sqlite_stat[134]'\",\n               -1, &pStmt, 0);\n      doStats = sqlite3_step(pStmt)==SQLITE_ROW;\n      sqlite3_finalize(pStmt);\n    }\n    if( doStats==0 ){\n      raw_printf(p->out, \"/* No STAT tables available */\\n\");\n    }else{\n      raw_printf(p->out, \"ANALYZE sqlite_master;\\n\");\n      sqlite3_exec(p->db, \"SELECT 'ANALYZE sqlite_master'\",\n                   callback, &data, &zErrMsg);\n      data.cMode = data.mode = MODE_Insert;\n      data.zDestTable = \"sqlite_stat1\";\n      shell_exec(&data, \"SELECT * FROM sqlite_stat1\", &zErrMsg);\n      data.zDestTable = \"sqlite_stat4\";\n      shell_exec(&data, \"SELECT * FROM sqlite_stat4\", &zErrMsg);\n      raw_printf(p->out, \"ANALYZE sqlite_master;\\n\");\n    }\n  }else\n\n  if( c=='h' && strncmp(azArg[0], \"headers\", n)==0 ){\n    if( nArg==2 ){\n      p->showHeader = booleanValue(azArg[1]);\n    }else{\n      raw_printf(stderr, \"Usage: .headers on|off\\n\");\n      rc = 1;\n    }\n  }else\n\n  if( c=='h' && strncmp(azArg[0], \"help\", n)==0 ){\n    if( nArg>=2 ){\n      n = showHelp(p->out, azArg[1]);\n      if( n==0 ){\n        utf8_printf(p->out, \"Nothing matches '%s'\\n\", azArg[1]);\n      }\n    }else{\n      showHelp(p->out, 0);\n    }\n  }else\n\n  if( c=='i' && strncmp(azArg[0], \"import\", n)==0 ){\n    char *zTable = 0;           /* Insert data into this table */\n    char *zFile = 0;            /* Name of file to extra content from */\n    sqlite3_stmt *pStmt = NULL; /* A statement */\n    int nCol;                   /* Number of columns in the table */\n    int nByte;                  /* Number of bytes in an SQL string */\n    int i, j;                   /* Loop counters */\n    int needCommit;             /* True to COMMIT or ROLLBACK at end */\n    int nSep;                   /* Number of bytes in p->colSeparator[] */\n    char *zSql;                 /* An SQL statement */\n    ImportCtx sCtx;             /* Reader context */\n    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */\n    int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close file */\n    int eVerbose = 0;           /* Larger for more console output */\n    int nSkip = 0;              /* Initial lines to skip */\n    int useOutputMode = 1;      /* Use output mode to determine separators */\n\n    memset(&sCtx, 0, sizeof(sCtx));\n    if( p->mode==MODE_Ascii ){\n      xRead = ascii_read_one_field;\n    }else{\n      xRead = csv_read_one_field;\n    }\n    for(i=1; i<nArg; i++){\n      char *z = azArg[i];\n      if( z[0]=='-' && z[1]=='-' ) z++;\n      if( z[0]!='-' ){\n        if( zFile==0 ){\n          zFile = z;\n        }else if( zTable==0 ){\n          zTable = z;\n        }else{\n          utf8_printf(p->out, \"ERROR: extra argument: \\\"%s\\\".  Usage:\\n\", z);\n          showHelp(p->out, \"import\");\n          rc = 1;\n          goto meta_command_exit;\n        }\n      }else if( strcmp(z,\"-v\")==0 ){\n        eVerbose++;\n      }else if( strcmp(z,\"-skip\")==0 && i<nArg-1 ){\n        nSkip = integerValue(azArg[++i]);\n      }else if( strcmp(z,\"-ascii\")==0 ){\n        sCtx.cColSep = SEP_Unit[0];\n        sCtx.cRowSep = SEP_Record[0];\n        xRead = ascii_read_one_field;\n        useOutputMode = 0;\n      }else if( strcmp(z,\"-csv\")==0 ){\n        sCtx.cColSep = ',';\n        sCtx.cRowSep = '\\n';\n        xRead = csv_read_one_field;\n        useOutputMode = 0;\n      }else{\n        utf8_printf(p->out, \"ERROR: unknown option: \\\"%s\\\".  Usage:\\n\", z);\n        showHelp(p->out, \"import\");\n        rc = 1;\n        goto meta_command_exit;\n      }\n    }\n    if( zTable==0 ){\n      utf8_printf(p->out, \"ERROR: missing %s argument. Usage:\\n\",\n                  zFile==0 ? \"FILE\" : \"TABLE\");\n      showHelp(p->out, \"import\");\n      rc = 1;\n      goto meta_command_exit;\n    }\n    seenInterrupt = 0;\n    open_db(p, 0);\n    if( useOutputMode ){\n      /* If neither the --csv or --ascii options are specified, then set\n      ** the column and row separator characters from the output mode. */\n      nSep = strlen30(p->colSeparator);\n      if( nSep==0 ){\n        raw_printf(stderr,\n                   \"Error: non-null column separator required for import\\n\");\n        rc = 1;\n        goto meta_command_exit;\n      }\n      if( nSep>1 ){\n        raw_printf(stderr, \n              \"Error: multi-character column separators not allowed\"\n              \" for import\\n\");\n        rc = 1;\n        goto meta_command_exit;\n      }\n      nSep = strlen30(p->rowSeparator);\n      if( nSep==0 ){\n        raw_printf(stderr,\n            \"Error: non-null row separator required for import\\n\");\n        rc = 1;\n        goto meta_command_exit;\n      }\n      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){\n        /* When importing CSV (only), if the row separator is set to the\n        ** default output row separator, change it to the default input\n        ** row separator.  This avoids having to maintain different input\n        ** and output row separators. */\n        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);\n        nSep = strlen30(p->rowSeparator);\n      }\n      if( nSep>1 ){\n        raw_printf(stderr, \"Error: multi-character row separators not allowed\"\n                           \" for import\\n\");\n        rc = 1;\n        goto meta_command_exit;\n      }\n      sCtx.cColSep = p->colSeparator[0];\n      sCtx.cRowSep = p->rowSeparator[0];\n    }\n    sCtx.zFile = zFile;\n    sCtx.nLine = 1;\n    if( sCtx.zFile[0]=='|' ){\n#ifdef SQLITE_OMIT_POPEN\n      raw_printf(stderr, \"Error: pipes are not supported in this OS\\n\");\n      rc = 1;\n      goto meta_command_exit;\n#else\n      sCtx.in = popen(sCtx.zFile+1, \"r\");\n      sCtx.zFile = \"<pipe>\";\n      xCloser = pclose;\n#endif\n    }else{\n      sCtx.in = fopen(sCtx.zFile, \"rb\");\n      xCloser = fclose;\n    }\n    if( sCtx.in==0 ){\n      utf8_printf(stderr, \"Error: cannot open \\\"%s\\\"\\n\", zFile);\n      rc = 1;\n      goto meta_command_exit;\n    }\n    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){\n      char zSep[2];\n      zSep[1] = 0;\n      zSep[0] = sCtx.cColSep;\n      utf8_printf(p->out, \"Column separator \");\n      output_c_string(p->out, zSep);\n      utf8_printf(p->out, \", row separator \");\n      zSep[0] = sCtx.cRowSep;\n      output_c_string(p->out, zSep);\n      utf8_printf(p->out, \"\\n\");\n    }\n    while( (nSkip--)>0 ){\n      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}\n      sCtx.nLine++;\n    }\n    zSql = sqlite3_mprintf(\"SELECT * FROM %s\", zTable);\n    if( zSql==0 ){\n      xCloser(sCtx.in);\n      shell_out_of_memory();\n    }\n    nByte = strlen30(zSql);\n    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);\n    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */\n    if( rc && sqlite3_strglob(\"no such table: *\", sqlite3_errmsg(p->db))==0 ){\n      char *zCreate = sqlite3_mprintf(\"CREATE TABLE %s\", zTable);\n      char cSep = '(';\n      while( xRead(&sCtx) ){\n        zCreate = sqlite3_mprintf(\"%z%c\\n  \\\"%w\\\" TEXT\", zCreate, cSep, sCtx.z);\n        cSep = ',';\n        if( sCtx.cTerm!=sCtx.cColSep ) break;\n      }\n      if( cSep=='(' ){\n        sqlite3_free(zCreate);\n        sqlite3_free(sCtx.z);\n        xCloser(sCtx.in);\n        utf8_printf(stderr,\"%s: empty file\\n\", sCtx.zFile);\n        rc = 1;\n        goto meta_command_exit;\n      }\n      zCreate = sqlite3_mprintf(\"%z\\n)\", zCreate);\n      if( eVerbose>=1 ){\n        utf8_printf(p->out, \"%s\\n\", zCreate);\n      }\n      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);\n      sqlite3_free(zCreate);\n      if( rc ){\n        utf8_printf(stderr, \"CREATE TABLE %s(...) failed: %s\\n\", zTable,\n                sqlite3_errmsg(p->db));\n        sqlite3_free(sCtx.z);\n        xCloser(sCtx.in);\n        rc = 1;\n        goto meta_command_exit;\n      }\n      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);\n    }\n    sqlite3_free(zSql);\n    if( rc ){\n      if (pStmt) sqlite3_finalize(pStmt);\n      utf8_printf(stderr,\"Error: %s\\n\", sqlite3_errmsg(p->db));\n      xCloser(sCtx.in);\n      rc = 1;\n      goto meta_command_exit;\n    }\n    nCol = sqlite3_column_count(pStmt);\n    sqlite3_finalize(pStmt);\n    pStmt = 0;\n    if( nCol==0 ) return 0; /* no columns, no error */\n    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );\n    if( zSql==0 ){\n      xCloser(sCtx.in);\n      shell_out_of_memory();\n    }\n    sqlite3_snprintf(nByte+20, zSql, \"INSERT INTO \\\"%w\\\" VALUES(?\", zTable);\n    j = strlen30(zSql);\n    for(i=1; i<nCol; i++){\n      zSql[j++] = ',';\n      zSql[j++] = '?';\n    }\n    zSql[j++] = ')';\n    zSql[j] = 0;\n    if( eVerbose>=2 ){\n      utf8_printf(p->out, \"Insert using: %s\\n\", zSql);\n    }\n    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);\n    sqlite3_free(zSql);\n    if( rc ){\n      utf8_printf(stderr, \"Error: %s\\n\", sqlite3_errmsg(p->db));\n      if (pStmt) sqlite3_finalize(pStmt);\n      xCloser(sCtx.in);\n      rc = 1;\n      goto meta_command_exit;\n    }\n    needCommit = sqlite3_get_autocommit(p->db);\n    if( needCommit ) sqlite3_exec(p->db, \"BEGIN\", 0, 0, 0);\n    do{\n      int startLine = sCtx.nLine;\n      for(i=0; i<nCol; i++){\n        char *z = xRead(&sCtx);\n        /*\n        ** Did we reach end-of-file before finding any columns?\n        ** If so, stop instead of NULL filling the remaining columns.\n        */\n        if( z==0 && i==0 ) break;\n        /*\n        ** Did we reach end-of-file OR end-of-line before finding any\n        ** columns in ASCII mode?  If so, stop instead of NULL filling\n        ** the remaining columns.\n        */\n        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;\n        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);\n        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){\n          utf8_printf(stderr, \"%s:%d: expected %d columns but found %d - \"\n                          \"filling the rest with NULL\\n\",\n                          sCtx.zFile, startLine, nCol, i+1);\n          i += 2;\n          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }\n        }\n      }\n      if( sCtx.cTerm==sCtx.cColSep ){\n        do{\n          xRead(&sCtx);\n          i++;\n        }while( sCtx.cTerm==sCtx.cColSep );\n        utf8_printf(stderr, \"%s:%d: expected %d columns but found %d - \"\n                        \"extras ignored\\n\",\n                        sCtx.zFile, startLine, nCol, i);\n      }\n      if( i>=nCol ){\n        sqlite3_step(pStmt);\n        rc = sqlite3_reset(pStmt);\n        if( rc!=SQLITE_OK ){\n          utf8_printf(stderr, \"%s:%d: INSERT failed: %s\\n\", sCtx.zFile,\n                      startLine, sqlite3_errmsg(p->db));\n          sCtx.nErr++;\n        }else{\n          sCtx.nRow++;\n        }\n      }\n    }while( sCtx.cTerm!=EOF );\n\n    xCloser(sCtx.in);\n    sqlite3_free(sCtx.z);\n    sqlite3_finalize(pStmt);\n    if( needCommit ) sqlite3_exec(p->db, \"COMMIT\", 0, 0, 0);\n    if( eVerbose>0 ){\n      utf8_printf(p->out,\n          \"Added %d rows with %d errors using %d lines of input\\n\",\n          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);\n    }\n  }else\n\n#ifndef SQLITE_UNTESTABLE\n  if( c=='i' && strncmp(azArg[0], \"imposter\", n)==0 ){\n    char *zSql;\n    char *zCollist = 0;\n    sqlite3_stmt *pStmt;\n    int tnum = 0;\n    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */\n    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */\n    int i;\n    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],\"off\")==0)) ){\n      utf8_printf(stderr, \"Usage: .imposter INDEX IMPOSTER\\n\"\n                          \"       .imposter off\\n\");\n      /* Also allowed, but not documented:\n      **\n      **    .imposter TABLE IMPOSTER\n      **\n      ** where TABLE is a WITHOUT ROWID table.  In that case, the\n      ** imposter is another WITHOUT ROWID table with the columns in\n      ** storage order. */\n      rc = 1;\n      goto meta_command_exit;\n    }\n    open_db(p, 0);\n    if( nArg==2 ){\n      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, \"main\", 0, 1);\n      goto meta_command_exit;\n    }\n    zSql = sqlite3_mprintf(\n      \"SELECT rootpage, 0 FROM sqlite_master\"\n      \" WHERE name='%q' AND type='index'\"\n      \"UNION ALL \"\n      \"SELECT rootpage, 1 FROM sqlite_master\"\n      \" WHERE name='%q' AND type='table'\"\n      \"   AND sql LIKE '%%without%%rowid%%'\",\n      azArg[1], azArg[1]\n    );\n    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);\n    sqlite3_free(zSql);\n    if( sqlite3_step(pStmt)==SQLITE_ROW ){\n      tnum = sqlite3_column_int(pStmt, 0);\n      isWO = sqlite3_column_int(pStmt, 1);\n    }\n    sqlite3_finalize(pStmt);\n    zSql = sqlite3_mprintf(\"PRAGMA index_xinfo='%q'\", azArg[1]);\n    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);\n    sqlite3_free(zSql);\n    i = 0;\n    while( sqlite3_step(pStmt)==SQLITE_ROW ){\n      char zLabel[20];\n      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);\n      i++;\n      if( zCol==0 ){\n        if( sqlite3_column_int(pStmt,1)==-1 ){\n          zCol = \"_ROWID_\";\n        }else{\n          sqlite3_snprintf(sizeof(zLabel),zLabel,\"expr%d\",i);\n          zCol = zLabel;\n        }\n      }\n      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){\n        lenPK = (int)strlen(zCollist);\n      }\n      if( zCollist==0 ){\n        zCollist = sqlite3_mprintf(\"\\\"%w\\\"\", zCol);\n      }else{\n        zCollist = sqlite3_mprintf(\"%z,\\\"%w\\\"\", zCollist, zCol);\n      }\n    }\n    sqlite3_finalize(pStmt);\n    if( i==0 || tnum==0 ){\n      utf8_printf(stderr, \"no such index: \\\"%s\\\"\\n\", azArg[1]);\n      rc = 1;\n      sqlite3_free(zCollist);\n      goto meta_command_exit;\n    }\n    if( lenPK==0 ) lenPK = 100000;\n    zSql = sqlite3_mprintf(\n          \"CREATE TABLE \\\"%w\\\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID\",\n          azArg[2], zCollist, lenPK, zCollist);\n    sqlite3_free(zCollist);\n    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, \"main\", 1, tnum);\n    if( rc==SQLITE_OK ){\n      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);\n      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, \"main\", 0, 0);\n      if( rc ){\n        utf8_printf(stderr, \"Error in [%s]: %s\\n\", zSql, sqlite3_errmsg(p->db));\n      }else{\n        utf8_printf(stdout, \"%s;\\n\", zSql);\n        raw_printf(stdout,\n          \"WARNING: writing to an imposter table will corrupt the \\\"%s\\\" %s!\\n\",\n          azArg[1], isWO ? \"table\" : \"index\"\n        );\n      }\n    }else{\n      raw_printf(stderr, \"SQLITE_TESTCTRL_IMPOSTER returns %d\\n\", rc);\n      rc = 1;\n    }\n    sqlite3_free(zSql);\n  }else\n#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */\n\n#ifdef SQLITE_ENABLE_IOTRACE\n  if( c=='i' && strncmp(azArg[0], \"iotrace\", n)==0 ){\n    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);\n    if( iotrace && iotrace!=stdout ) fclose(iotrace);\n    iotrace = 0;\n    if( nArg<2 ){\n      sqlite3IoTrace = 0;\n    }else if( strcmp(azArg[1], \"-\")==0 ){\n      sqlite3IoTrace = iotracePrintf;\n      iotrace = stdout;\n    }else{\n      iotrace = fopen(azArg[1], \"w\");\n      if( iotrace==0 ){\n        utf8_printf(stderr, \"Error: cannot open \\\"%s\\\"\\n\", azArg[1]);\n        sqlite3IoTrace = 0;\n        rc = 1;\n      }else{\n        sqlite3IoTrace = iotracePrintf;\n      }\n    }\n  }else\n#endif\n\n  if( c=='l' && n>=5 && strncmp(azArg[0], \"limits\", n)==0 ){\n    static const struct {\n       const char *zLimitName;   /* Name of a limit */\n       int limitCode;            /* Integer code for that limit */\n    } aLimit[] = {\n      { \"length\",                SQLITE_LIMIT_LENGTH                    },\n      { \"sql_length\",            SQLITE_LIMIT_SQL_LENGTH                },\n      { \"column\",                SQLITE_LIMIT_COLUMN                    },\n      { \"expr_depth\",            SQLITE_LIMIT_EXPR_DEPTH                },\n      { \"compound_select\",       SQLITE_LIMIT_COMPOUND_SELECT           },\n      { \"vdbe_op\",               SQLITE_LIMIT_VDBE_OP                   },\n      { \"function_arg\",          SQLITE_LIMIT_FUNCTION_ARG              },\n      { \"attached\",              SQLITE_LIMIT_ATTACHED                  },\n      { \"like_pattern_length\",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },\n      { \"variable_number\",       SQLITE_LIMIT_VARIABLE_NUMBER           },\n      { \"trigger_depth\",         SQLITE_LIMIT_TRIGGER_DEPTH             },\n      { \"worker_threads\",        SQLITE_LIMIT_WORKER_THREADS            },\n    };\n    int i, n2;\n    open_db(p, 0);\n    if( nArg==1 ){\n      for(i=0; i<ArraySize(aLimit); i++){\n        printf(\"%20s %d\\n\", aLimit[i].zLimitName,\n               sqlite3_limit(p->db, aLimit[i].limitCode, -1));\n      }\n    }else if( nArg>3 ){\n      raw_printf(stderr, \"Usage: .limit NAME ?NEW-VALUE?\\n\");\n      rc = 1;\n      goto meta_command_exit;\n    }else{\n      int iLimit = -1;\n      n2 = strlen30(azArg[1]);\n      for(i=0; i<ArraySize(aLimit); i++){\n        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){\n          if( iLimit<0 ){\n            iLimit = i;\n          }else{\n            utf8_printf(stderr, \"ambiguous limit: \\\"%s\\\"\\n\", azArg[1]);\n            rc = 1;\n            goto meta_command_exit;\n          }\n        }\n      }\n      if( iLimit<0 ){\n        utf8_printf(stderr, \"unknown limit: \\\"%s\\\"\\n\"\n                        \"enter \\\".limits\\\" with no arguments for a list.\\n\",\n                         azArg[1]);\n        rc = 1;\n        goto meta_command_exit;\n      }\n      if( nArg==3 ){\n        sqlite3_limit(p->db, aLimit[iLimit].limitCode,\n                      (int)integerValue(azArg[2]));\n      }\n      printf(\"%20s %d\\n\", aLimit[iLimit].zLimitName,\n             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));\n    }\n  }else\n\n  if( c=='l' && n>2 && strncmp(azArg[0], \"lint\", n)==0 ){\n    open_db(p, 0);\n    lintDotCommand(p, azArg, nArg);\n  }else\n\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\n  if( c=='l' && strncmp(azArg[0], \"load\", n)==0 ){\n    const char *zFile, *zProc;\n    char *zErrMsg = 0;\n    if( nArg<2 ){\n      raw_printf(stderr, \"Usage: .load FILE ?ENTRYPOINT?\\n\");\n      rc = 1;\n      goto meta_command_exit;\n    }\n    zFile = azArg[1];\n    zProc = nArg>=3 ? azArg[2] : 0;\n    open_db(p, 0);\n    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);\n    if( rc!=SQLITE_OK ){\n      utf8_printf(stderr, \"Error: %s\\n\", zErrMsg);\n      sqlite3_free(zErrMsg);\n      rc = 1;\n    }\n  }else\n#endif\n\n  if( c=='l' && strncmp(azArg[0], \"log\", n)==0 ){\n    if( nArg!=2 ){\n      raw_printf(stderr, \"Usage: .log FILENAME\\n\");\n      rc = 1;\n    }else{\n      const char *zFile = azArg[1];\n      output_file_close(p->pLog);\n      p->pLog = output_file_open(zFile, 0);\n    }\n  }else\n\n  if( c=='m' && strncmp(azArg[0], \"mode\", n)==0 ){\n    const char *zMode = nArg>=2 ? azArg[1] : \"\";\n    int n2 = strlen30(zMode);\n    int c2 = zMode[0];\n    if( c2=='l' && n2>2 && strncmp(azArg[1],\"lines\",n2)==0 ){\n      p->mode = MODE_Line;\n      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);\n    }else if( c2=='c' && strncmp(azArg[1],\"columns\",n2)==0 ){\n      p->mode = MODE_Column;\n      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);\n    }else if( c2=='l' && n2>2 && strncmp(azArg[1],\"list\",n2)==0 ){\n      p->mode = MODE_List;\n      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);\n      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);\n    }else if( c2=='h' && strncmp(azArg[1],\"html\",n2)==0 ){\n      p->mode = MODE_Html;\n    }else if( c2=='t' && strncmp(azArg[1],\"tcl\",n2)==0 ){\n      p->mode = MODE_Tcl;\n      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);\n      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);\n    }else if( c2=='c' && strncmp(azArg[1],\"csv\",n2)==0 ){\n      p->mode = MODE_Csv;\n      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);\n      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);\n    }else if( c2=='t' && strncmp(azArg[1],\"tabs\",n2)==0 ){\n      p->mode = MODE_List;\n      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);\n    }else if( c2=='i' && strncmp(azArg[1],\"insert\",n2)==0 ){\n      p->mode = MODE_Insert;\n      set_table_name(p, nArg>=3 ? azArg[2] : \"table\");\n    }else if( c2=='q' && strncmp(azArg[1],\"quote\",n2)==0 ){\n      p->mode = MODE_Quote;\n    }else if( c2=='a' && strncmp(azArg[1],\"ascii\",n2)==0 ){\n      p->mode = MODE_Ascii;\n      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);\n      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);\n    }else if( nArg==1 ){\n      raw_printf(p->out, \"current output mode: %s\\n\", modeDescr[p->mode]);\n    }else{\n      raw_printf(stderr, \"Error: mode should be one of: \"\n         \"ascii column csv html insert line list quote tabs tcl\\n\");\n      rc = 1;\n    }\n    p->cMode = p->mode;\n  }else\n\n  if( c=='n' && strncmp(azArg[0], \"nullvalue\", n)==0 ){\n    if( nArg==2 ){\n      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,\n                       \"%.*s\", (int)ArraySize(p->nullValue)-1, azArg[1]);\n    }else{\n      raw_printf(stderr, \"Usage: .nullvalue STRING\\n\");\n      rc = 1;\n    }\n  }else\n\n#ifdef SQLITE_DEBUG\n  if( c=='o' && strcmp(azArg[0],\"oom\")==0 ){\n    int i;\n    for(i=1; i<nArg; i++){\n      const char *z = azArg[i];\n      if( z[0]=='-' && z[1]=='-' ) z++;\n      if( strcmp(z,\"-repeat\")==0 ){\n        if( i==nArg-1 ){\n          raw_printf(p->out, \"missing argument on \\\"%s\\\"\\n\", azArg[i]);\n          rc = 1;\n        }else{\n          oomRepeat = (int)integerValue(azArg[++i]);\n        }\n      }else if( IsDigit(z[0]) ){\n        oomCounter = (int)integerValue(azArg[i]);\n      }else{\n        raw_printf(p->out, \"unknown argument: \\\"%s\\\"\\n\", azArg[i]);\n        raw_printf(p->out, \"Usage: .oom [--repeat N] [M]\\n\");\n        rc = 1;\n      }\n    }\n    if( rc==0 ){\n      raw_printf(p->out, \"oomCounter = %d\\n\", oomCounter);\n      raw_printf(p->out, \"oomRepeat  = %d\\n\", oomRepeat);\n    }\n  }else\n#endif /* SQLITE_DEBUG */\n\n  if( c=='o' && strncmp(azArg[0], \"open\", n)==0 && n>=2 ){\n    char *zNewFilename;  /* Name of the database file to open */\n    int iName = 1;       /* Index in azArg[] of the filename */\n    int newFlag = 0;     /* True to delete file before opening */\n    /* Close the existing database */\n    session_close_all(p);\n    close_db(p->db);\n    p->db = 0;\n    p->zDbFilename = 0;\n    sqlite3_free(p->zFreeOnClose);\n    p->zFreeOnClose = 0;\n    p->openMode = SHELL_OPEN_UNSPEC;\n    p->openFlags = 0;\n    p->szMax = 0;\n    /* Check for command-line arguments */\n    for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){\n      const char *z = azArg[iName];\n      if( optionMatch(z,\"new\") ){\n        newFlag = 1;\n#ifdef SQLITE_HAVE_ZLIB\n      }else if( optionMatch(z, \"zip\") ){\n        p->openMode = SHELL_OPEN_ZIPFILE;\n#endif\n      }else if( optionMatch(z, \"append\") ){\n        p->openMode = SHELL_OPEN_APPENDVFS;\n      }else if( optionMatch(z, \"readonly\") ){\n        p->openMode = SHELL_OPEN_READONLY;\n      }else if( optionMatch(z, \"nofollow\") ){\n        p->openFlags |= SQLITE_OPEN_NOFOLLOW;\n#ifdef SQLITE_ENABLE_DESERIALIZE\n      }else if( optionMatch(z, \"deserialize\") ){\n        p->openMode = SHELL_OPEN_DESERIALIZE;\n      }else if( optionMatch(z, \"hexdb\") ){\n        p->openMode = SHELL_OPEN_HEXDB;\n      }else if( optionMatch(z, \"maxsize\") && iName+1<nArg ){\n        p->szMax = integerValue(azArg[++iName]);\n#endif /* SQLITE_ENABLE_DESERIALIZE */\n      }else if( z[0]=='-' ){\n        utf8_printf(stderr, \"unknown option: %s\\n\", z);\n        rc = 1;\n        goto meta_command_exit;\n      }\n    }\n    /* If a filename is specified, try to open it first */\n    zNewFilename = nArg>iName ? sqlite3_mprintf(\"%s\", azArg[iName]) : 0;\n    if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){\n      if( newFlag ) shellDeleteFile(zNewFilename);\n      p->zDbFilename = zNewFilename;\n      open_db(p, OPEN_DB_KEEPALIVE);\n      if( p->db==0 ){\n        utf8_printf(stderr, \"Error: cannot open '%s'\\n\", zNewFilename);\n        sqlite3_free(zNewFilename);\n      }else{\n        p->zFreeOnClose = zNewFilename;\n      }\n    }\n    if( p->db==0 ){\n      /* As a fall-back open a TEMP database */\n      p->zDbFilename = 0;\n      open_db(p, 0);\n    }\n  }else\n\n  if( (c=='o'\n        && (strncmp(azArg[0], \"output\", n)==0||strncmp(azArg[0], \"once\", n)==0))\n   || (c=='e' && n==5 && strcmp(azArg[0],\"excel\")==0)\n  ){\n    const char *zFile = 0;\n    int bTxtMode = 0;\n    int i;\n    int eMode = 0;\n    int bBOM = 0;\n    int bOnce = 0;  /* 0: .output, 1: .once, 2: .excel */\n\n    if( c=='e' ){\n      eMode = 'x';\n      bOnce = 2;\n    }else if( strncmp(azArg[0],\"once\",n)==0 ){\n      bOnce = 1;\n    }\n    for(i=1; i<nArg; i++){\n      char *z = azArg[i];\n      if( z[0]=='-' ){\n        if( z[1]=='-' ) z++;\n        if( strcmp(z,\"-bom\")==0 ){\n          bBOM = 1;\n        }else if( c!='e' && strcmp(z,\"-x\")==0 ){\n          eMode = 'x';  /* spreadsheet */\n        }else if( c!='e' && strcmp(z,\"-e\")==0 ){\n          eMode = 'e';  /* text editor */\n        }else{\n          utf8_printf(p->out, \"ERROR: unknown option: \\\"%s\\\".  Usage:\\n\",\n                      azArg[i]);\n          showHelp(p->out, azArg[0]);\n          rc = 1;\n          goto meta_command_exit;\n        }\n      }else if( zFile==0 ){\n        zFile = z;\n      }else{\n        utf8_printf(p->out,\"ERROR: extra parameter: \\\"%s\\\".  Usage:\\n\",\n                    azArg[i]);\n        showHelp(p->out, azArg[0]);\n        rc = 1;\n        goto meta_command_exit;\n      }\n    }\n    if( zFile==0 ) zFile = \"stdout\";\n    if( bOnce ){\n      p->outCount = 2;\n    }else{\n      p->outCount = 0;\n    }\n    output_reset(p);\n#ifndef SQLITE_NOHAVE_SYSTEM\n    if( eMode=='e' || eMode=='x' ){\n      p->doXdgOpen = 1;\n      outputModePush(p);\n      if( eMode=='x' ){\n        /* spreadsheet mode.  Output as CSV. */\n        newTempFile(p, \"csv\");\n        ShellClearFlag(p, SHFLG_Echo);\n        p->mode = MODE_Csv;\n        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);\n        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);\n      }else{\n        /* text editor mode */\n        newTempFile(p, \"txt\");\n        bTxtMode = 1;\n      }\n      zFile = p->zTempFile;\n    }\n#endif /* SQLITE_NOHAVE_SYSTEM */\n    if( zFile[0]=='|' ){\n#ifdef SQLITE_OMIT_POPEN\n      raw_printf(stderr, \"Error: pipes are not supported in this OS\\n\");\n      rc = 1;\n      p->out = stdout;\n#else\n      p->out = popen(zFile + 1, \"w\");\n      if( p->out==0 ){\n        utf8_printf(stderr,\"Error: cannot open pipe \\\"%s\\\"\\n\", zFile + 1);\n        p->out = stdout;\n        rc = 1;\n      }else{\n        if( bBOM ) fprintf(p->out,\"\\357\\273\\277\");\n        sqlite3_snprintf(sizeof(p->outfile), p->outfile, \"%s\", zFile);\n      }\n#endif\n    }else{\n      p->out = output_file_open(zFile, bTxtMode);\n      if( p->out==0 ){\n        if( strcmp(zFile,\"off\")!=0 ){\n          utf8_printf(stderr,\"Error: cannot write to \\\"%s\\\"\\n\", zFile);\n        }\n        p->out = stdout;\n        rc = 1;\n      } else {\n        if( bBOM ) fprintf(p->out,\"\\357\\273\\277\");\n        sqlite3_snprintf(sizeof(p->outfile), p->outfile, \"%s\", zFile);\n      }\n    }\n  }else\n\n  if( c=='p' && n>=3 && strncmp(azArg[0], \"parameter\", n)==0 ){\n    open_db(p,0);\n    if( nArg<=1 ) goto parameter_syntax_error;\n\n    /* .parameter clear\n    ** Clear all bind parameters by dropping the TEMP table that holds them.\n    */\n    if( nArg==2 && strcmp(azArg[1],\"clear\")==0 ){\n      sqlite3_exec(p->db, \"DROP TABLE IF EXISTS temp.sqlite_parameters;\",\n                   0, 0, 0);\n    }else\n\n    /* .parameter list\n    ** List all bind parameters.\n    */\n    if( nArg==2 && strcmp(azArg[1],\"list\")==0 ){\n      sqlite3_stmt *pStmt = 0;\n      int rx;\n      int len = 0;\n      rx = sqlite3_prepare_v2(p->db,\n             \"SELECT max(length(key)) \"\n             \"FROM temp.sqlite_parameters;\", -1, &pStmt, 0);\n      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){\n        len = sqlite3_column_int(pStmt, 0);\n        if( len>40 ) len = 40;\n      }\n      sqlite3_finalize(pStmt);\n      pStmt = 0;\n      if( len ){\n        rx = sqlite3_prepare_v2(p->db,\n             \"SELECT key, quote(value) \"\n             \"FROM temp.sqlite_parameters;\", -1, &pStmt, 0);\n        while( sqlite3_step(pStmt)==SQLITE_ROW ){\n          utf8_printf(p->out, \"%-*s %s\\n\", len, sqlite3_column_text(pStmt,0),\n                      sqlite3_column_text(pStmt,1));\n        }\n        sqlite3_finalize(pStmt);\n      }\n    }else\n\n    /* .parameter init\n    ** Make sure the TEMP table used to hold bind parameters exists.\n    ** Create it if necessary.\n    */\n    if( nArg==2 && strcmp(azArg[1],\"init\")==0 ){\n      bind_table_init(p);\n    }else\n\n    /* .parameter set NAME VALUE\n    ** Set or reset a bind parameter.  NAME should be the full parameter\n    ** name exactly as it appears in the query.  (ex: $abc, @def).  The\n    ** VALUE can be in either SQL literal notation, or if not it will be\n    ** understood to be a text string.\n    */\n    if( nArg==4 && strcmp(azArg[1],\"set\")==0 ){\n      int rx;\n      char *zSql;\n      sqlite3_stmt *pStmt;\n      const char *zKey = azArg[2];\n      const char *zValue = azArg[3];\n      bind_table_init(p);\n      zSql = sqlite3_mprintf(\n                  \"REPLACE INTO temp.sqlite_parameters(key,value)\"\n                  \"VALUES(%Q,%s);\", zKey, zValue);\n      if( zSql==0 ) shell_out_of_memory();\n      pStmt = 0;\n      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);\n      sqlite3_free(zSql);\n      if( rx!=SQLITE_OK ){\n        sqlite3_finalize(pStmt);\n        pStmt = 0;\n        zSql = sqlite3_mprintf(\n                   \"REPLACE INTO temp.sqlite_parameters(key,value)\"\n                   \"VALUES(%Q,%Q);\", zKey, zValue);\n        if( zSql==0 ) shell_out_of_memory();\n        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);\n        sqlite3_free(zSql);\n        if( rx!=SQLITE_OK ){\n          utf8_printf(p->out, \"Error: %s\\n\", sqlite3_errmsg(p->db));\n          sqlite3_finalize(pStmt);\n          pStmt = 0;\n          rc = 1;\n        }\n      }\n      sqlite3_step(pStmt);\n      sqlite3_finalize(pStmt);\n    }else\n\n    /* .parameter unset NAME\n    ** Remove the NAME binding from the parameter binding table, if it\n    ** exists.\n    */\n    if( nArg==3 && strcmp(azArg[1],\"unset\")==0 ){\n      char *zSql = sqlite3_mprintf(\n          \"DELETE FROM temp.sqlite_parameters WHERE key=%Q\", azArg[2]);\n      if( zSql==0 ) shell_out_of_memory();\n      sqlite3_exec(p->db, zSql, 0, 0, 0);\n      sqlite3_free(zSql);\n    }else\n    /* If no command name matches, show a syntax error */\n    parameter_syntax_error:\n    showHelp(p->out, \"parameter\");\n  }else\n\n  if( c=='p' && n>=3 && strncmp(azArg[0], \"print\", n)==0 ){\n    int i;\n    for(i=1; i<nArg; i++){\n      if( i>1 ) raw_printf(p->out, \" \");\n      utf8_printf(p->out, \"%s\", azArg[i]);\n    }\n    raw_printf(p->out, \"\\n\");\n  }else\n\n#ifndef SQLITE_OMIT_PROGRESS_CALLBACK\n  if( c=='p' && n>=3 && strncmp(azArg[0], \"progress\", n)==0 ){\n    int i;\n    int nn = 0;\n    p->flgProgress = 0;\n    p->mxProgress = 0;\n    p->nProgress = 0;\n    for(i=1; i<nArg; i++){\n      const char *z = azArg[i];\n      if( z[0]=='-' ){\n        z++;\n        if( z[0]=='-' ) z++;\n        if( strcmp(z,\"quiet\")==0 || strcmp(z,\"q\")==0 ){\n          p->flgProgress |= SHELL_PROGRESS_QUIET;\n          continue;\n        }\n        if( strcmp(z,\"reset\")==0 ){\n          p->flgProgress |= SHELL_PROGRESS_RESET;\n          continue;\n        }\n        if( strcmp(z,\"once\")==0 ){\n          p->flgProgress |= SHELL_PROGRESS_ONCE;\n          continue;\n        }\n        if( strcmp(z,\"limit\")==0 ){\n          if( i+1>=nArg ){\n            utf8_printf(stderr, \"Error: missing argument on --limit\\n\");\n            rc = 1;\n            goto meta_command_exit;\n          }else{\n            p->mxProgress = (int)integerValue(azArg[++i]);\n          }\n          continue;\n        }\n        utf8_printf(stderr, \"Error: unknown option: \\\"%s\\\"\\n\", azArg[i]);\n        rc = 1;\n        goto meta_command_exit;\n      }else{\n        nn = (int)integerValue(z);\n      }\n    }\n    open_db(p, 0);\n    sqlite3_progress_handler(p->db, nn, progress_handler, p);\n  }else\n#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */\n\n  if( c=='p' && strncmp(azArg[0], \"prompt\", n)==0 ){\n    if( nArg >= 2) {\n      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);\n    }\n    if( nArg >= 3) {\n      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);\n    }\n  }else\n\n  if( c=='q' && strncmp(azArg[0], \"quit\", n)==0 ){\n    rc = 2;\n  }else\n\n  if( c=='r' && n>=3 && strncmp(azArg[0], \"read\", n)==0 ){\n    FILE *inSaved = p->in;\n    int savedLineno = p->lineno;\n    if( nArg!=2 ){\n      raw_printf(stderr, \"Usage: .read FILE\\n\");\n      rc = 1;\n      goto meta_command_exit;\n    }\n    p->in = fopen(azArg[1], \"rb\");\n    if( p->in==0 ){\n      utf8_printf(stderr,\"Error: cannot open \\\"%s\\\"\\n\", azArg[1]);\n      rc = 1;\n    }else{\n      rc = process_input(p);\n      fclose(p->in);\n    }\n    p->in = inSaved;\n    p->lineno = savedLineno;\n  }else\n\n  if( c=='r' && n>=3 && strncmp(azArg[0], \"restore\", n)==0 ){\n    const char *zSrcFile;\n    const char *zDb;\n    sqlite3 *pSrc;\n    sqlite3_backup *pBackup;\n    int nTimeout = 0;\n\n    if( nArg==2 ){\n      zSrcFile = azArg[1];\n      zDb = \"main\";\n    }else if( nArg==3 ){\n      zSrcFile = azArg[2];\n      zDb = azArg[1];\n    }else{\n      raw_printf(stderr, \"Usage: .restore ?DB? FILE\\n\");\n      rc = 1;\n      goto meta_command_exit;\n    }\n    rc = sqlite3_open(zSrcFile, &pSrc);\n    if( rc!=SQLITE_OK ){\n      utf8_printf(stderr, \"Error: cannot open \\\"%s\\\"\\n\", zSrcFile);\n      close_db(pSrc);\n      return 1;\n    }\n    open_db(p, 0);\n    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, \"main\");\n    if( pBackup==0 ){\n      utf8_printf(stderr, \"Error: %s\\n\", sqlite3_errmsg(p->db));\n      close_db(pSrc);\n      return 1;\n    }\n    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK\n          || rc==SQLITE_BUSY  ){\n      if( rc==SQLITE_BUSY ){\n        if( nTimeout++ >= 3 ) break;\n        sqlite3_sleep(100);\n      }\n    }\n    sqlite3_backup_finish(pBackup);\n    if( rc==SQLITE_DONE ){\n      rc = 0;\n    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){\n      raw_printf(stderr, \"Error: source database is busy\\n\");\n      rc = 1;\n    }else{\n      utf8_printf(stderr, \"Error: %s\\n\", sqlite3_errmsg(p->db));\n      rc = 1;\n    }\n    close_db(pSrc);\n  }else\n\n  if( c=='s' && strncmp(azArg[0], \"scanstats\", n)==0 ){\n    if( nArg==2 ){\n      p->scanstatsOn = (u8)booleanValue(azArg[1]);\n#ifndef SQLITE_ENABLE_STMT_SCANSTATUS\n      raw_printf(stderr, \"Warning: .scanstats not available in this build.\\n\");\n#endif\n    }else{\n      raw_printf(stderr, \"Usage: .scanstats on|off\\n\");\n      rc = 1;\n    }\n  }else\n\n  if( c=='s' && strncmp(azArg[0], \"schema\", n)==0 ){\n    ShellText sSelect;\n    ShellState data;\n    char *zErrMsg = 0;\n    const char *zDiv = \"(\";\n    const char *zName = 0;\n    int iSchema = 0;\n    int bDebug = 0;\n    int ii;\n\n    open_db(p, 0);\n    memcpy(&data, p, sizeof(data));\n    data.showHeader = 0;\n    data.cMode = data.mode = MODE_Semi;\n    initText(&sSelect);\n    for(ii=1; ii<nArg; ii++){\n      if( optionMatch(azArg[ii],\"indent\") ){\n        data.cMode = data.mode = MODE_Pretty;\n      }else if( optionMatch(azArg[ii],\"debug\") ){\n        bDebug = 1;\n      }else if( zName==0 ){\n        zName = azArg[ii];\n      }else{\n        raw_printf(stderr, \"Usage: .schema ?--indent? ?LIKE-PATTERN?\\n\");\n        rc = 1;\n        goto meta_command_exit;\n      }\n    }\n    if( zName!=0 ){\n      int isMaster = sqlite3_strlike(zName, \"sqlite_master\", '\\\\')==0;\n      if( isMaster || sqlite3_strlike(zName,\"sqlite_temp_master\", '\\\\')==0 ){\n        char *new_argv[2], *new_colv[2];\n        new_argv[0] = sqlite3_mprintf(\n                      \"CREATE TABLE %s (\\n\"\n                      \"  type text,\\n\"\n                      \"  name text,\\n\"\n                      \"  tbl_name text,\\n\"\n                      \"  rootpage integer,\\n\"\n                      \"  sql text\\n\"\n                      \")\", isMaster ? \"sqlite_master\" : \"sqlite_temp_master\");\n        new_argv[1] = 0;\n        new_colv[0] = \"sql\";\n        new_colv[1] = 0;\n        callback(&data, 1, new_argv, new_colv);\n        sqlite3_free(new_argv[0]);\n      }\n    }\n    if( zDiv ){\n      sqlite3_stmt *pStmt = 0;\n      rc = sqlite3_prepare_v2(p->db, \"SELECT name FROM pragma_database_list\",\n                              -1, &pStmt, 0);\n      if( rc ){\n        utf8_printf(stderr, \"Error: %s\\n\", sqlite3_errmsg(p->db));\n        sqlite3_finalize(pStmt);\n        rc = 1;\n        goto meta_command_exit;\n      }\n      appendText(&sSelect, \"SELECT sql FROM\", 0);\n      iSchema = 0;\n      while( sqlite3_step(pStmt)==SQLITE_ROW ){\n        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);\n        char zScNum[30];\n        sqlite3_snprintf(sizeof(zScNum), zScNum, \"%d\", ++iSchema);\n        appendText(&sSelect, zDiv, 0);\n        zDiv = \" UNION ALL \";\n        appendText(&sSelect, \"SELECT shell_add_schema(sql,\", 0);\n        if( sqlite3_stricmp(zDb, \"main\")!=0 ){\n          appendText(&sSelect, zDb, '\\'');\n        }else{\n          appendText(&sSelect, \"NULL\", 0);\n        }\n        appendText(&sSelect, \",name) AS sql, type, tbl_name, name, rowid,\", 0);\n        appendText(&sSelect, zScNum, 0);\n        appendText(&sSelect, \" AS snum, \", 0);\n        appendText(&sSelect, zDb, '\\'');\n        appendText(&sSelect, \" AS sname FROM \", 0);\n        appendText(&sSelect, zDb, quoteChar(zDb));\n        appendText(&sSelect, \".sqlite_master\", 0);\n      }\n      sqlite3_finalize(pStmt);\n#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS\n      if( zName ){\n        appendText(&sSelect,\n           \" UNION ALL SELECT shell_module_schema(name),\"\n           \" 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list\",\n        0);\n      }\n#endif\n      appendText(&sSelect, \") WHERE \", 0);\n      if( zName ){\n        char *zQarg = sqlite3_mprintf(\"%Q\", zName);\n        int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||\n                    strchr(zName, '[') != 0;\n        if( strchr(zName, '.') ){\n          appendText(&sSelect, \"lower(printf('%s.%s',sname,tbl_name))\", 0);\n        }else{\n          appendText(&sSelect, \"lower(tbl_name)\", 0);\n        }\n        appendText(&sSelect, bGlob ? \" GLOB \" : \" LIKE \", 0);\n        appendText(&sSelect, zQarg, 0);\n        if( !bGlob ){\n          appendText(&sSelect, \" ESCAPE '\\\\' \", 0);\n        }\n        appendText(&sSelect, \" AND \", 0);\n        sqlite3_free(zQarg);\n      }\n      appendText(&sSelect, \"type!='meta' AND sql IS NOT NULL\"\n                           \" ORDER BY snum, rowid\", 0);\n      if( bDebug ){\n        utf8_printf(p->out, \"SQL: %s;\\n\", sSelect.z);\n      }else{\n        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);\n      }\n      freeText(&sSelect);\n    }\n    if( zErrMsg ){\n      utf8_printf(stderr,\"Error: %s\\n\", zErrMsg);\n      sqlite3_free(zErrMsg);\n      rc = 1;\n    }else if( rc != SQLITE_OK ){\n      raw_printf(stderr,\"Error: querying schema information\\n\");\n      rc = 1;\n    }else{\n      rc = 0;\n    }\n  }else\n\n#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)\n  if( c=='s' && n==11 && strncmp(azArg[0], \"selecttrace\", n)==0 ){\n    sqlite3SelectTrace = (int)integerValue(azArg[1]);\n  }else\n#endif\n\n#if defined(SQLITE_ENABLE_SESSION)\n  if( c=='s' && strncmp(azArg[0],\"session\",n)==0 && n>=3 ){\n    OpenSession *pSession = &p->aSession[0];\n    char **azCmd = &azArg[1];\n    int iSes = 0;\n    int nCmd = nArg - 1;\n    int i;\n    if( nArg<=1 ) goto session_syntax_error;\n    open_db(p, 0);\n    if( nArg>=3 ){\n      for(iSes=0; iSes<p->nSession; iSes++){\n        if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;\n      }\n      if( iSes<p->nSession ){\n        pSession = &p->aSession[iSes];\n        azCmd++;\n        nCmd--;\n      }else{\n        pSession = &p->aSession[0];\n        iSes = 0;\n      }\n    }\n\n    /* .session attach TABLE\n    ** Invoke the sqlite3session_attach() interface to attach a particular\n    ** table so that it is never filtered.\n    */\n    if( strcmp(azCmd[0],\"attach\")==0 ){\n      if( nCmd!=2 ) goto session_syntax_error;\n      if( pSession->p==0 ){\n        session_not_open:\n        raw_printf(stderr, \"ERROR: No sessions are open\\n\");\n      }else{\n        rc = sqlite3session_attach(pSession->p, azCmd[1]);\n        if( rc ){\n          raw_printf(stderr, \"ERROR: sqlite3session_attach() returns %d\\n\", rc);\n          rc = 0;\n        }\n      }\n    }else\n\n    /* .session changeset FILE\n    ** .session patchset FILE\n    ** Write a changeset or patchset into a file.  The file is overwritten.\n    */\n    if( strcmp(azCmd[0],\"changeset\")==0 || strcmp(azCmd[0],\"patchset\")==0 ){\n      FILE *out = 0;\n      if( nCmd!=2 ) goto session_syntax_error;\n      if( pSession->p==0 ) goto session_not_open;\n      out = fopen(azCmd[1], \"wb\");\n      if( out==0 ){\n        utf8_printf(stderr, \"ERROR: cannot open \\\"%s\\\" for writing\\n\",\n                    azCmd[1]);\n      }else{\n        int szChng;\n        void *pChng;\n        if( azCmd[0][0]=='c' ){\n          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);\n        }else{\n          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);\n        }\n        if( rc ){\n          printf(\"Error: error code %d\\n\", rc);\n          rc = 0;\n        }\n        if( pChng\n          && fwrite(pChng, szChng, 1, out)!=1 ){\n          raw_printf(stderr, \"ERROR: Failed to write entire %d-byte output\\n\",\n                  szChng);\n        }\n        sqlite3_free(pChng);\n        fclose(out);\n      }\n    }else\n\n    /* .session close\n    ** Close the identified session\n    */\n    if( strcmp(azCmd[0], \"close\")==0 ){\n      if( nCmd!=1 ) goto session_syntax_error;\n      if( p->nSession ){\n        session_close(pSession);\n        p->aSession[iSes] = p->aSession[--p->nSession];\n      }\n    }else\n\n    /* .session enable ?BOOLEAN?\n    ** Query or set the enable flag\n    */\n    if( strcmp(azCmd[0], \"enable\")==0 ){\n      int ii;\n      if( nCmd>2 ) goto session_syntax_error;\n      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);\n      if( p->nSession ){\n        ii = sqlite3session_enable(pSession->p, ii);\n        utf8_printf(p->out, \"session %s enable flag = %d\\n\",\n                    pSession->zName, ii);\n      }\n    }else\n\n    /* .session filter GLOB ....\n    ** Set a list of GLOB patterns of table names to be excluded.\n    */\n    if( strcmp(azCmd[0], \"filter\")==0 ){\n      int ii, nByte;\n      if( nCmd<2 ) goto session_syntax_error;\n      if( p->nSession ){\n        for(ii=0; ii<pSession->nFilter; ii++){\n          sqlite3_free(pSession->azFilter[ii]);\n        }\n        sqlite3_free(pSession->azFilter);\n        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);\n        pSession->azFilter = sqlite3_malloc( nByte );\n        if( pSession->azFilter==0 ){\n          raw_printf(stderr, \"Error: out or memory\\n\");\n          exit(1);\n        }\n        for(ii=1; ii<nCmd; ii++){\n          pSession->azFilter[ii-1] = sqlite3_mprintf(\"%s\", azCmd[ii]);\n        }\n        pSession->nFilter = ii-1;\n      }\n    }else\n\n    /* .session indirect ?BOOLEAN?\n    ** Query or set the indirect flag\n    */\n    if( strcmp(azCmd[0], \"indirect\")==0 ){\n      int ii;\n      if( nCmd>2 ) goto session_syntax_error;\n      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);\n      if( p->nSession ){\n        ii = sqlite3session_indirect(pSession->p, ii);\n        utf8_printf(p->out, \"session %s indirect flag = %d\\n\",\n                    pSession->zName, ii);\n      }\n    }else\n\n    /* .session isempty\n    ** Determine if the session is empty\n    */\n    if( strcmp(azCmd[0], \"isempty\")==0 ){\n      int ii;\n      if( nCmd!=1 ) goto session_syntax_error;\n      if( p->nSession ){\n        ii = sqlite3session_isempty(pSession->p);\n        utf8_printf(p->out, \"session %s isempty flag = %d\\n\",\n                    pSession->zName, ii);\n      }\n    }else\n\n    /* .session list\n    ** List all currently open sessions\n    */\n    if( strcmp(azCmd[0],\"list\")==0 ){\n      for(i=0; i<p->nSession; i++){\n        utf8_printf(p->out, \"%d %s\\n\", i, p->aSession[i].zName);\n      }\n    }else\n\n    /* .session open DB NAME\n    ** Open a new session called NAME on the attached database DB.\n    ** DB is normally \"main\".\n    */\n    if( strcmp(azCmd[0],\"open\")==0 ){\n      char *zName;\n      if( nCmd!=3 ) goto session_syntax_error;\n      zName = azCmd[2];\n      if( zName[0]==0 ) goto session_syntax_error;\n      for(i=0; i<p->nSession; i++){\n        if( strcmp(p->aSession[i].zName,zName)==0 ){\n          utf8_printf(stderr, \"Session \\\"%s\\\" already exists\\n\", zName);\n          goto meta_command_exit;\n        }\n      }\n      if( p->nSession>=ArraySize(p->aSession) ){\n        raw_printf(stderr, \"Maximum of %d sessions\\n\", ArraySize(p->aSession));\n        goto meta_command_exit;\n      }\n      pSession = &p->aSession[p->nSession];\n      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);\n      if( rc ){\n        raw_printf(stderr, \"Cannot open session: error code=%d\\n\", rc);\n        rc = 0;\n        goto meta_command_exit;\n      }\n      pSession->nFilter = 0;\n      sqlite3session_table_filter(pSession->p, session_filter, pSession);\n      p->nSession++;\n      pSession->zName = sqlite3_mprintf(\"%s\", zName);\n    }else\n    /* If no command name matches, show a syntax error */\n    session_syntax_error:\n    showHelp(p->out, \"session\");\n  }else\n#endif\n\n#ifdef SQLITE_DEBUG\n  /* Undocumented commands for internal testing.  Subject to change\n  ** without notice. */\n  if( c=='s' && n>=10 && strncmp(azArg[0], \"selftest-\", 9)==0 ){\n    if( strncmp(azArg[0]+9, \"boolean\", n-9)==0 ){\n      int i, v;\n      for(i=1; i<nArg; i++){\n        v = booleanValue(azArg[i]);\n        utf8_printf(p->out, \"%s: %d 0x%x\\n\", azArg[i], v, v);\n      }\n    }\n    if( strncmp(azArg[0]+9, \"integer\", n-9)==0 ){\n      int i; sqlite3_int64 v;\n      for(i=1; i<nArg; i++){\n        char zBuf[200];\n        v = integerValue(azArg[i]);\n        sqlite3_snprintf(sizeof(zBuf),zBuf,\"%s: %lld 0x%llx\\n\", azArg[i],v,v);\n        utf8_printf(p->out, \"%s\", zBuf);\n      }\n    }\n  }else\n#endif\n\n  if( c=='s' && n>=4 && strncmp(azArg[0],\"selftest\",n)==0 ){\n    int bIsInit = 0;         /* True to initialize the SELFTEST table */\n    int bVerbose = 0;        /* Verbose output */\n    int bSelftestExists;     /* True if SELFTEST already exists */\n    int i, k;                /* Loop counters */\n    int nTest = 0;           /* Number of tests runs */\n    int nErr = 0;            /* Number of errors seen */\n    ShellText str;           /* Answer for a query */\n    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */\n\n    open_db(p,0);\n    for(i=1; i<nArg; i++){\n      const char *z = azArg[i];\n      if( z[0]=='-' && z[1]=='-' ) z++;\n      if( strcmp(z,\"-init\")==0 ){\n        bIsInit = 1;\n      }else\n      if( strcmp(z,\"-v\")==0 ){\n        bVerbose++;\n      }else\n      {\n        utf8_printf(stderr, \"Unknown option \\\"%s\\\" on \\\"%s\\\"\\n\",\n                    azArg[i], azArg[0]);\n        raw_printf(stderr, \"Should be one of: --init -v\\n\");\n        rc = 1;\n        goto meta_command_exit;\n      }\n    }\n    if( sqlite3_table_column_metadata(p->db,\"main\",\"selftest\",0,0,0,0,0,0)\n           != SQLITE_OK ){\n      bSelftestExists = 0;\n    }else{\n      bSelftestExists = 1;\n    }\n    if( bIsInit ){\n      createSelftestTable(p);\n      bSelftestExists = 1;\n    }\n    initText(&str);\n    appendText(&str, \"x\", 0);\n    for(k=bSelftestExists; k>=0; k--){\n      if( k==1 ){\n        rc = sqlite3_prepare_v2(p->db,\n            \"SELECT tno,op,cmd,ans FROM selftest ORDER BY tno\",\n            -1, &pStmt, 0);\n      }else{\n        rc = sqlite3_prepare_v2(p->db,\n          \"VALUES(0,'memo','Missing SELFTEST table - default checks only',''),\"\n          \"      (1,'run','PRAGMA integrity_check','ok')\",\n          -1, &pStmt, 0);\n      }\n      if( rc ){\n        raw_printf(stderr, \"Error querying the selftest table\\n\");\n        rc = 1;\n        sqlite3_finalize(pStmt);\n        goto meta_command_exit;\n      }\n      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){\n        int tno = sqlite3_column_int(pStmt, 0);\n        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);\n        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);\n        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);\n\n        k = 0;\n        if( bVerbose>0 ){\n          char *zQuote = sqlite3_mprintf(\"%q\", zSql);\n          printf(\"%d: %s %s\\n\", tno, zOp, zSql);\n          sqlite3_free(zQuote);\n        }\n        if( strcmp(zOp,\"memo\")==0 ){\n          utf8_printf(p->out, \"%s\\n\", zSql);\n        }else\n        if( strcmp(zOp,\"run\")==0 ){\n          char *zErrMsg = 0;\n          str.n = 0;\n          str.z[0] = 0;\n          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);\n          nTest++;\n          if( bVerbose ){\n            utf8_printf(p->out, \"Result: %s\\n\", str.z);\n          }\n          if( rc || zErrMsg ){\n            nErr++;\n            rc = 1;\n            utf8_printf(p->out, \"%d: error-code-%d: %s\\n\", tno, rc, zErrMsg);\n            sqlite3_free(zErrMsg);\n          }else if( strcmp(zAns,str.z)!=0 ){\n            nErr++;\n            rc = 1;\n            utf8_printf(p->out, \"%d: Expected: [%s]\\n\", tno, zAns);\n            utf8_printf(p->out, \"%d:      Got: [%s]\\n\", tno, str.z);\n          }\n        }else\n        {\n          utf8_printf(stderr,\n            \"Unknown operation \\\"%s\\\" on selftest line %d\\n\", zOp, tno);\n          rc = 1;\n          break;\n        }\n      } /* End loop over rows of content from SELFTEST */\n      sqlite3_finalize(pStmt);\n    } /* End loop over k */\n    freeText(&str);\n    utf8_printf(p->out, \"%d errors out of %d tests\\n\", nErr, nTest);\n  }else\n\n  if( c=='s' && strncmp(azArg[0], \"separator\", n)==0 ){\n    if( nArg<2 || nArg>3 ){\n      raw_printf(stderr, \"Usage: .separator COL ?ROW?\\n\");\n      rc = 1;\n    }\n    if( nArg>=2 ){\n      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,\n                       \"%.*s\", (int)ArraySize(p->colSeparator)-1, azArg[1]);\n    }\n    if( nArg>=3 ){\n      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,\n                       \"%.*s\", (int)ArraySize(p->rowSeparator)-1, azArg[2]);\n    }\n  }else\n\n  if( c=='s' && n>=4 && strncmp(azArg[0],\"sha3sum\",n)==0 ){\n    const char *zLike = 0;   /* Which table to checksum. 0 means everything */\n    int i;                   /* Loop counter */\n    int bSchema = 0;         /* Also hash the schema */\n    int bSeparate = 0;       /* Hash each table separately */\n    int iSize = 224;         /* Hash algorithm to use */\n    int bDebug = 0;          /* Only show the query that would have run */\n    sqlite3_stmt *pStmt;     /* For querying tables names */\n    char *zSql;              /* SQL to be run */\n    char *zSep;              /* Separator */\n    ShellText sSql;          /* Complete SQL for the query to run the hash */\n    ShellText sQuery;        /* Set of queries used to read all content */\n    open_db(p, 0);\n    for(i=1; i<nArg; i++){\n      const char *z = azArg[i];\n      if( z[0]=='-' ){\n        z++;\n        if( z[0]=='-' ) z++;\n        if( strcmp(z,\"schema\")==0 ){\n          bSchema = 1;\n        }else\n        if( strcmp(z,\"sha3-224\")==0 || strcmp(z,\"sha3-256\")==0\n         || strcmp(z,\"sha3-384\")==0 || strcmp(z,\"sha3-512\")==0\n        ){\n          iSize = atoi(&z[5]);\n        }else\n        if( strcmp(z,\"debug\")==0 ){\n          bDebug = 1;\n        }else\n        {\n          utf8_printf(stderr, \"Unknown option \\\"%s\\\" on \\\"%s\\\"\\n\",\n                      azArg[i], azArg[0]);\n          showHelp(p->out, azArg[0]);\n          rc = 1;\n          goto meta_command_exit;\n        }\n      }else if( zLike ){\n        raw_printf(stderr, \"Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\\n\");\n        rc = 1;\n        goto meta_command_exit;\n      }else{\n        zLike = z;\n        bSeparate = 1;\n        if( sqlite3_strlike(\"sqlite\\\\_%\", zLike, '\\\\')==0 ) bSchema = 1;\n      }\n    }\n    if( bSchema ){\n      zSql = \"SELECT lower(name) FROM sqlite_master\"\n             \" WHERE type='table' AND coalesce(rootpage,0)>1\"\n             \" UNION ALL SELECT 'sqlite_master'\"\n             \" ORDER BY 1 collate nocase\";\n    }else{\n      zSql = \"SELECT lower(name) FROM sqlite_master\"\n             \" WHERE type='table' AND coalesce(rootpage,0)>1\"\n             \" AND name NOT LIKE 'sqlite_%'\"\n             \" ORDER BY 1 collate nocase\";\n    }\n    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);\n    initText(&sQuery);\n    initText(&sSql);\n    appendText(&sSql, \"WITH [sha3sum$query](a,b) AS(\",0);\n    zSep = \"VALUES(\";\n    while( SQLITE_ROW==sqlite3_step(pStmt) ){\n      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);\n      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;\n      if( strncmp(zTab, \"sqlite_\",7)!=0 ){\n        appendText(&sQuery,\"SELECT * FROM \", 0);\n        appendText(&sQuery,zTab,'\"');\n        appendText(&sQuery,\" NOT INDEXED;\", 0);\n      }else if( strcmp(zTab, \"sqlite_master\")==0 ){\n        appendText(&sQuery,\"SELECT type,name,tbl_name,sql FROM sqlite_master\"\n                           \" ORDER BY name;\", 0);\n      }else if( strcmp(zTab, \"sqlite_sequence\")==0 ){\n        appendText(&sQuery,\"SELECT name,seq FROM sqlite_sequence\"\n                           \" ORDER BY name;\", 0);\n      }else if( strcmp(zTab, \"sqlite_stat1\")==0 ){\n        appendText(&sQuery,\"SELECT tbl,idx,stat FROM sqlite_stat1\"\n                           \" ORDER BY tbl,idx;\", 0);\n      }else if( strcmp(zTab, \"sqlite_stat4\")==0 ){\n        appendText(&sQuery, \"SELECT * FROM \", 0);\n        appendText(&sQuery, zTab, 0);\n        appendText(&sQuery, \" ORDER BY tbl, idx, rowid;\\n\", 0);\n      }\n      appendText(&sSql, zSep, 0);\n      appendText(&sSql, sQuery.z, '\\'');\n      sQuery.n = 0;\n      appendText(&sSql, \",\", 0);\n      appendText(&sSql, zTab, '\\'');\n      zSep = \"),(\";\n    }\n    sqlite3_finalize(pStmt);\n    if( bSeparate ){\n      zSql = sqlite3_mprintf(\n          \"%s))\"\n          \" SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label\"\n          \"   FROM [sha3sum$query]\",\n          sSql.z, iSize);\n    }else{\n      zSql = sqlite3_mprintf(\n          \"%s))\"\n          \" SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash\"\n          \"   FROM [sha3sum$query]\",\n          sSql.z, iSize);\n    }\n    freeText(&sQuery);\n    freeText(&sSql);\n    if( bDebug ){\n      utf8_printf(p->out, \"%s\\n\", zSql);\n    }else{\n      shell_exec(p, zSql, 0);\n    }\n    sqlite3_free(zSql);\n  }else\n\n#ifndef SQLITE_NOHAVE_SYSTEM\n  if( c=='s'\n   && (strncmp(azArg[0], \"shell\", n)==0 || strncmp(azArg[0],\"system\",n)==0)\n  ){\n    char *zCmd;\n    int i, x;\n    if( nArg<2 ){\n      raw_printf(stderr, \"Usage: .system COMMAND\\n\");\n      rc = 1;\n      goto meta_command_exit;\n    }\n    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?\"%s\":\"\\\"%s\\\"\", azArg[1]);\n    for(i=2; i<nArg; i++){\n      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?\"%z %s\":\"%z \\\"%s\\\"\",\n                             zCmd, azArg[i]);\n    }\n    x = system(zCmd);\n    sqlite3_free(zCmd);\n    if( x ) raw_printf(stderr, \"System command returns %d\\n\", x);\n  }else\n#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */\n\n  if( c=='s' && strncmp(azArg[0], \"show\", n)==0 ){\n    static const char *azBool[] = { \"off\", \"on\", \"trigger\", \"full\"};\n    int i;\n    if( nArg!=1 ){\n      raw_printf(stderr, \"Usage: .show\\n\");\n      rc = 1;\n      goto meta_command_exit;\n    }\n    utf8_printf(p->out, \"%12.12s: %s\\n\",\"echo\",\n                                  azBool[ShellHasFlag(p, SHFLG_Echo)]);\n    utf8_printf(p->out, \"%12.12s: %s\\n\",\"eqp\", azBool[p->autoEQP&3]);\n    utf8_printf(p->out, \"%12.12s: %s\\n\",\"explain\",\n         p->mode==MODE_Explain ? \"on\" : p->autoExplain ? \"auto\" : \"off\");\n    utf8_printf(p->out,\"%12.12s: %s\\n\",\"headers\", azBool[p->showHeader!=0]);\n    utf8_printf(p->out, \"%12.12s: %s\\n\",\"mode\", modeDescr[p->mode]);\n    utf8_printf(p->out, \"%12.12s: \", \"nullvalue\");\n      output_c_string(p->out, p->nullValue);\n      raw_printf(p->out, \"\\n\");\n    utf8_printf(p->out,\"%12.12s: %s\\n\",\"output\",\n            strlen30(p->outfile) ? p->outfile : \"stdout\");\n    utf8_printf(p->out,\"%12.12s: \", \"colseparator\");\n      output_c_string(p->out, p->colSeparator);\n      raw_printf(p->out, \"\\n\");\n    utf8_printf(p->out,\"%12.12s: \", \"rowseparator\");\n      output_c_string(p->out, p->rowSeparator);\n      raw_printf(p->out, \"\\n\");\n    utf8_printf(p->out, \"%12.12s: %s\\n\",\"stats\", azBool[p->statsOn!=0]);\n    utf8_printf(p->out, \"%12.12s: \", \"width\");\n    for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {\n      raw_printf(p->out, \"%d \", p->colWidth[i]);\n    }\n    raw_printf(p->out, \"\\n\");\n    utf8_printf(p->out, \"%12.12s: %s\\n\", \"filename\",\n                p->zDbFilename ? p->zDbFilename : \"\");\n  }else\n\n  if( c=='s' && strncmp(azArg[0], \"stats\", n)==0 ){\n    if( nArg==2 ){\n      p->statsOn = (u8)booleanValue(azArg[1]);\n    }else if( nArg==1 ){\n      display_stats(p->db, p, 0);\n    }else{\n      raw_printf(stderr, \"Usage: .stats ?on|off?\\n\");\n      rc = 1;\n    }\n  }else\n\n  if( (c=='t' && n>1 && strncmp(azArg[0], \"tables\", n)==0)\n   || (c=='i' && (strncmp(azArg[0], \"indices\", n)==0\n                 || strncmp(azArg[0], \"indexes\", n)==0) )\n  ){\n    sqlite3_stmt *pStmt;\n    char **azResult;\n    int nRow, nAlloc;\n    int ii;\n    ShellText s;\n    initText(&s);\n    open_db(p, 0);\n    rc = sqlite3_prepare_v2(p->db, \"PRAGMA database_list\", -1, &pStmt, 0);\n    if( rc ){\n      sqlite3_finalize(pStmt);\n      return shellDatabaseError(p->db);\n    }\n\n    if( nArg>2 && c=='i' ){\n      /* It is an historical accident that the .indexes command shows an error\n      ** when called with the wrong number of arguments whereas the .tables\n      ** command does not. */\n      raw_printf(stderr, \"Usage: .indexes ?LIKE-PATTERN?\\n\");\n      rc = 1;\n      sqlite3_finalize(pStmt);\n      goto meta_command_exit;\n    }\n    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){\n      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);\n      if( zDbName==0 ) continue;\n      if( s.z && s.z[0] ) appendText(&s, \" UNION ALL \", 0);\n      if( sqlite3_stricmp(zDbName, \"main\")==0 ){\n        appendText(&s, \"SELECT name FROM \", 0);\n      }else{\n        appendText(&s, \"SELECT \", 0);\n        appendText(&s, zDbName, '\\'');\n        appendText(&s, \"||'.'||name FROM \", 0);\n      }\n      appendText(&s, zDbName, '\"');\n      appendText(&s, \".sqlite_master \", 0);\n      if( c=='t' ){\n        appendText(&s,\" WHERE type IN ('table','view')\"\n                      \"   AND name NOT LIKE 'sqlite_%'\"\n                      \"   AND name LIKE ?1\", 0);\n      }else{\n        appendText(&s,\" WHERE type='index'\"\n                      \"   AND tbl_name LIKE ?1\", 0);\n      }\n    }\n    rc = sqlite3_finalize(pStmt);\n    appendText(&s, \" ORDER BY 1\", 0);\n    rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);\n    freeText(&s);\n    if( rc ) return shellDatabaseError(p->db);\n\n    /* Run the SQL statement prepared by the above block. Store the results\n    ** as an array of nul-terminated strings in azResult[].  */\n    nRow = nAlloc = 0;\n    azResult = 0;\n    if( nArg>1 ){\n      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);\n    }else{\n      sqlite3_bind_text(pStmt, 1, \"%\", -1, SQLITE_STATIC);\n    }\n    while( sqlite3_step(pStmt)==SQLITE_ROW ){\n      if( nRow>=nAlloc ){\n        char **azNew;\n        int n2 = nAlloc*2 + 10;\n        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);\n        if( azNew==0 ) shell_out_of_memory();\n        nAlloc = n2;\n        azResult = azNew;\n      }\n      azResult[nRow] = sqlite3_mprintf(\"%s\", sqlite3_column_text(pStmt, 0));\n      if( 0==azResult[nRow] ) shell_out_of_memory();\n      nRow++;\n    }\n    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){\n      rc = shellDatabaseError(p->db);\n    }\n\n    /* Pretty-print the contents of array azResult[] to the output */\n    if( rc==0 && nRow>0 ){\n      int len, maxlen = 0;\n      int i, j;\n      int nPrintCol, nPrintRow;\n      for(i=0; i<nRow; i++){\n        len = strlen30(azResult[i]);\n        if( len>maxlen ) maxlen = len;\n      }\n      nPrintCol = 80/(maxlen+2);\n      if( nPrintCol<1 ) nPrintCol = 1;\n      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;\n      for(i=0; i<nPrintRow; i++){\n        for(j=i; j<nRow; j+=nPrintRow){\n          char *zSp = j<nPrintRow ? \"\" : \"  \";\n          utf8_printf(p->out, \"%s%-*s\", zSp, maxlen,\n                      azResult[j] ? azResult[j]:\"\");\n        }\n        raw_printf(p->out, \"\\n\");\n      }\n    }\n\n    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);\n    sqlite3_free(azResult);\n  }else\n\n  /* Begin redirecting output to the file \"testcase-out.txt\" */\n  if( c=='t' && strcmp(azArg[0],\"testcase\")==0 ){\n    output_reset(p);\n    p->out = output_file_open(\"testcase-out.txt\", 0);\n    if( p->out==0 ){\n      raw_printf(stderr, \"Error: cannot open 'testcase-out.txt'\\n\");\n    }\n    if( nArg>=2 ){\n      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, \"%s\", azArg[1]);\n    }else{\n      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, \"?\");\n    }\n  }else\n\n#ifndef SQLITE_UNTESTABLE\n  if( c=='t' && n>=8 && strncmp(azArg[0], \"testctrl\", n)==0 ){\n    static const struct {\n       const char *zCtrlName;   /* Name of a test-control option */\n       int ctrlCode;            /* Integer code for that option */\n       const char *zUsage;      /* Usage notes */\n    } aCtrl[] = {\n      { \"always\",             SQLITE_TESTCTRL_ALWAYS,        \"BOOLEAN\"        },\n      { \"assert\",             SQLITE_TESTCTRL_ASSERT,        \"BOOLEAN\"        },\n    /*{ \"benign_malloc_hooks\",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, \"\"       },*/\n    /*{ \"bitvec_test\",        SQLITE_TESTCTRL_BITVEC_TEST,   \"\"             },*/\n      { \"byteorder\",          SQLITE_TESTCTRL_BYTEORDER,     \"\"               },\n      { \"extra_schema_checks\",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,\"BOOLEAN\"   },\n    /*{ \"fault_install\",      SQLITE_TESTCTRL_FAULT_INSTALL, \"\"             },*/\n      { \"imposter\",         SQLITE_TESTCTRL_IMPOSTER, \"SCHEMA ON/OFF ROOTPAGE\"},\n      { \"internal_functions\", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, \"\" },\n      { \"localtime_fault\",    SQLITE_TESTCTRL_LOCALTIME_FAULT,\"BOOLEAN\"       },\n      { \"never_corrupt\",      SQLITE_TESTCTRL_NEVER_CORRUPT, \"BOOLEAN\"        },\n      { \"optimizations\",      SQLITE_TESTCTRL_OPTIMIZATIONS, \"DISABLE-MASK\"   },\n#ifdef YYCOVERAGE\n      { \"parser_coverage\",    SQLITE_TESTCTRL_PARSER_COVERAGE, \"\"             },\n#endif\n      { \"pending_byte\",       SQLITE_TESTCTRL_PENDING_BYTE,  \"OFFSET  \"       },\n      { \"prng_restore\",       SQLITE_TESTCTRL_PRNG_RESTORE,  \"\"               },\n      { \"prng_save\",          SQLITE_TESTCTRL_PRNG_SAVE,     \"\"               },\n      { \"prng_seed\",          SQLITE_TESTCTRL_PRNG_SEED,     \"SEED ?db?\"      },\n    };\n    int testctrl = -1;\n    int iCtrl = -1;\n    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */\n    int isOk = 0;\n    int i, n2;\n    const char *zCmd = 0;\n\n    open_db(p, 0);\n    zCmd = nArg>=2 ? azArg[1] : \"help\";\n\n    /* The argument can optionally begin with \"-\" or \"--\" */\n    if( zCmd[0]=='-' && zCmd[1] ){\n      zCmd++;\n      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;\n    }\n\n    /* --help lists all test-controls */\n    if( strcmp(zCmd,\"help\")==0 ){\n      utf8_printf(p->out, \"Available test-controls:\\n\");\n      for(i=0; i<ArraySize(aCtrl); i++){\n        utf8_printf(p->out, \"  .testctrl %s %s\\n\",\n                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);\n      }\n      rc = 1;\n      goto meta_command_exit;\n    }\n\n    /* convert testctrl text option to value. allow any unique prefix\n    ** of the option name, or a numerical value. */\n    n2 = strlen30(zCmd);\n    for(i=0; i<ArraySize(aCtrl); i++){\n      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){\n        if( testctrl<0 ){\n          testctrl = aCtrl[i].ctrlCode;\n          iCtrl = i;\n        }else{\n          utf8_printf(stderr, \"Error: ambiguous test-control: \\\"%s\\\"\\n\"\n                              \"Use \\\".testctrl --help\\\" for help\\n\", zCmd);\n          rc = 1;\n          goto meta_command_exit;\n        }\n      }\n    }\n    if( testctrl<0 ){\n      utf8_printf(stderr,\"Error: unknown test-control: %s\\n\"\n                         \"Use \\\".testctrl --help\\\" for help\\n\", zCmd);\n    }else{\n      switch(testctrl){\n\n        /* sqlite3_test_control(int, db, int) */\n        case SQLITE_TESTCTRL_OPTIMIZATIONS:\n          if( nArg==3 ){\n            int opt = (int)strtol(azArg[2], 0, 0);\n            rc2 = sqlite3_test_control(testctrl, p->db, opt);\n            isOk = 3;\n          }\n          break;\n\n        /* sqlite3_test_control(int) */\n        case SQLITE_TESTCTRL_PRNG_SAVE:\n        case SQLITE_TESTCTRL_PRNG_RESTORE:\n        case SQLITE_TESTCTRL_PRNG_RESET:\n        case SQLITE_TESTCTRL_BYTEORDER:\n          if( nArg==2 ){\n            rc2 = sqlite3_test_control(testctrl);\n            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;\n          }\n          break;\n\n        /* sqlite3_test_control(int, uint) */\n        case SQLITE_TESTCTRL_PENDING_BYTE:\n          if( nArg==3 ){\n            unsigned int opt = (unsigned int)integerValue(azArg[2]);\n            rc2 = sqlite3_test_control(testctrl, opt);\n            isOk = 3;\n          }\n          break;\n\n        /* sqlite3_test_control(int, int, sqlite3*) */\n        case SQLITE_TESTCTRL_PRNG_SEED:\n          if( nArg==3 || nArg==4 ){\n            int ii = (int)integerValue(azArg[2]);\n            sqlite3 *db;\n            if( ii==0 && strcmp(azArg[2],\"random\")==0 ){\n              sqlite3_randomness(sizeof(ii),&ii);\n              printf(\"-- random seed: %d\\n\", ii);\n            }\n            if( nArg==3 ){\n              db = 0;\n            }else{\n              db = p->db;\n              /* Make sure the schema has been loaded */\n              sqlite3_table_column_metadata(db, 0, \"x\", 0, 0, 0, 0, 0, 0);\n            }\n            rc2 = sqlite3_test_control(testctrl, ii, db);\n            isOk = 3;\n          }\n          break;\n\n        /* sqlite3_test_control(int, int) */\n        case SQLITE_TESTCTRL_ASSERT:\n        case SQLITE_TESTCTRL_ALWAYS:\n          if( nArg==3 ){\n            int opt = booleanValue(azArg[2]);\n            rc2 = sqlite3_test_control(testctrl, opt);\n            isOk = 1;\n          }\n          break;\n\n        /* sqlite3_test_control(int, int) */\n        case SQLITE_TESTCTRL_LOCALTIME_FAULT:\n        case SQLITE_TESTCTRL_NEVER_CORRUPT:\n          if( nArg==3 ){\n            int opt = booleanValue(azArg[2]);\n            rc2 = sqlite3_test_control(testctrl, opt);\n            isOk = 3;\n          }\n          break;\n\n        /* sqlite3_test_control(sqlite3*) */\n        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:\n          rc2 = sqlite3_test_control(testctrl, p->db);\n          isOk = 3;\n          break;\n\n        case SQLITE_TESTCTRL_IMPOSTER:\n          if( nArg==5 ){\n            rc2 = sqlite3_test_control(testctrl, p->db,\n                          azArg[2],\n                          integerValue(azArg[3]),\n                          integerValue(azArg[4]));\n            isOk = 3;\n          }\n          break;\n\n#ifdef YYCOVERAGE\n        case SQLITE_TESTCTRL_PARSER_COVERAGE:\n          if( nArg==2 ){\n            sqlite3_test_control(testctrl, p->out);\n            isOk = 3;\n          }\n#endif\n      }\n    }\n    if( isOk==0 && iCtrl>=0 ){\n      utf8_printf(p->out, \"Usage: .testctrl %s %s\\n\", zCmd,aCtrl[iCtrl].zUsage);\n      rc = 1;\n    }else if( isOk==1 ){\n      raw_printf(p->out, \"%d\\n\", rc2);\n    }else if( isOk==2 ){\n      raw_printf(p->out, \"0x%08x\\n\", rc2);\n    }\n  }else\n#endif /* !defined(SQLITE_UNTESTABLE) */\n\n  if( c=='t' && n>4 && strncmp(azArg[0], \"timeout\", n)==0 ){\n    open_db(p, 0);\n    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);\n  }else\n\n  if( c=='t' && n>=5 && strncmp(azArg[0], \"timer\", n)==0 ){\n    if( nArg==2 ){\n      enableTimer = booleanValue(azArg[1]);\n      if( enableTimer && !HAS_TIMER ){\n        raw_printf(stderr, \"Error: timer not available on this system.\\n\");\n        enableTimer = 0;\n      }\n    }else{\n      raw_printf(stderr, \"Usage: .timer on|off\\n\");\n      rc = 1;\n    }\n  }else\n\n#ifndef SQLITE_OMIT_TRACE\n  if( c=='t' && strncmp(azArg[0], \"trace\", n)==0 ){\n    int mType = 0;\n    int jj;\n    open_db(p, 0);\n    for(jj=1; jj<nArg; jj++){\n      const char *z = azArg[jj];\n      if( z[0]=='-' ){\n        if( optionMatch(z, \"expanded\") ){\n          p->eTraceType = SHELL_TRACE_EXPANDED;\n        }\n#ifdef SQLITE_ENABLE_NORMALIZE\n        else if( optionMatch(z, \"normalized\") ){\n          p->eTraceType = SHELL_TRACE_NORMALIZED;\n        }\n#endif\n        else if( optionMatch(z, \"plain\") ){\n          p->eTraceType = SHELL_TRACE_PLAIN;\n        }\n        else if( optionMatch(z, \"profile\") ){\n          mType |= SQLITE_TRACE_PROFILE;\n        }\n        else if( optionMatch(z, \"row\") ){\n          mType |= SQLITE_TRACE_ROW;\n        }\n        else if( optionMatch(z, \"stmt\") ){\n          mType |= SQLITE_TRACE_STMT;\n        }\n        else if( optionMatch(z, \"close\") ){\n          mType |= SQLITE_TRACE_CLOSE;\n        }\n        else {\n          raw_printf(stderr, \"Unknown option \\\"%s\\\" on \\\".trace\\\"\\n\", z);\n          rc = 1;\n          goto meta_command_exit;\n        }\n      }else{\n        output_file_close(p->traceOut);\n        p->traceOut = output_file_open(azArg[1], 0);\n      }\n    }\n    if( p->traceOut==0 ){\n      sqlite3_trace_v2(p->db, 0, 0, 0);\n    }else{\n      if( mType==0 ) mType = SQLITE_TRACE_STMT;\n      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);\n    }\n  }else\n#endif /* !defined(SQLITE_OMIT_TRACE) */\n\n#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)\n  if( c=='u' && strncmp(azArg[0], \"unmodule\", n)==0 ){\n    int ii;\n    int lenOpt;\n    char *zOpt;\n    if( nArg<2 ){\n      raw_printf(stderr, \"Usage: .unmodule [--allexcept] NAME ...\\n\");\n      rc = 1;\n      goto meta_command_exit;\n    }\n    open_db(p, 0);\n    zOpt = azArg[1];\n    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;\n    lenOpt = (int)strlen(zOpt);\n    if( lenOpt>=3 && strncmp(zOpt, \"-allexcept\",lenOpt)==0 ){\n      assert( azArg[nArg]==0 );\n      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);\n    }else{\n      for(ii=1; ii<nArg; ii++){\n        sqlite3_create_module(p->db, azArg[ii], 0, 0);\n      }\n    }\n  }else\n#endif\n\n#if SQLITE_USER_AUTHENTICATION\n  if( c=='u' && strncmp(azArg[0], \"user\", n)==0 ){\n    if( nArg<2 ){\n      raw_printf(stderr, \"Usage: .user SUBCOMMAND ...\\n\");\n      rc = 1;\n      goto meta_command_exit;\n    }\n    open_db(p, 0);\n    if( strcmp(azArg[1],\"login\")==0 ){\n      if( nArg!=4 ){\n        raw_printf(stderr, \"Usage: .user login USER PASSWORD\\n\");\n        rc = 1;\n        goto meta_command_exit;\n      }\n      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],\n                                     strlen30(azArg[3]));\n      if( rc ){\n        utf8_printf(stderr, \"Authentication failed for user %s\\n\", azArg[2]);\n        rc = 1;\n      }\n    }else if( strcmp(azArg[1],\"add\")==0 ){\n      if( nArg!=5 ){\n        raw_printf(stderr, \"Usage: .user add USER PASSWORD ISADMIN\\n\");\n        rc = 1;\n        goto meta_command_exit;\n      }\n      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),\n                            booleanValue(azArg[4]));\n      if( rc ){\n        raw_printf(stderr, \"User-Add failed: %d\\n\", rc);\n        rc = 1;\n      }\n    }else if( strcmp(azArg[1],\"edit\")==0 ){\n      if( nArg!=5 ){\n        raw_printf(stderr, \"Usage: .user edit USER PASSWORD ISADMIN\\n\");\n        rc = 1;\n        goto meta_command_exit;\n      }\n      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),\n                              booleanValue(azArg[4]));\n      if( rc ){\n        raw_printf(stderr, \"User-Edit failed: %d\\n\", rc);\n        rc = 1;\n      }\n    }else if( strcmp(azArg[1],\"delete\")==0 ){\n      if( nArg!=3 ){\n        raw_printf(stderr, \"Usage: .user delete USER\\n\");\n        rc = 1;\n        goto meta_command_exit;\n      }\n      rc = sqlite3_user_delete(p->db, azArg[2]);\n      if( rc ){\n        raw_printf(stderr, \"User-Delete failed: %d\\n\", rc);\n        rc = 1;\n      }\n    }else{\n      raw_printf(stderr, \"Usage: .user login|add|edit|delete ...\\n\");\n      rc = 1;\n      goto meta_command_exit;\n    }\n  }else\n#endif /* SQLITE_USER_AUTHENTICATION */\n\n  if( c=='v' && strncmp(azArg[0], \"version\", n)==0 ){\n    utf8_printf(p->out, \"SQLite %s %s\\n\" /*extra-version-info*/,\n        sqlite3_libversion(), sqlite3_sourceid());\n#if SQLITE_HAVE_ZLIB\n    utf8_printf(p->out, \"zlib version %s\\n\", zlibVersion());\n#endif\n#define CTIMEOPT_VAL_(opt) #opt\n#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)\n#if defined(__clang__) && defined(__clang_major__)\n    utf8_printf(p->out, \"clang-\" CTIMEOPT_VAL(__clang_major__) \".\"\n                    CTIMEOPT_VAL(__clang_minor__) \".\"\n                    CTIMEOPT_VAL(__clang_patchlevel__) \"\\n\");\n#elif defined(_MSC_VER)\n    utf8_printf(p->out, \"msvc-\" CTIMEOPT_VAL(_MSC_VER) \"\\n\");\n#elif defined(__GNUC__) && defined(__VERSION__)\n    utf8_printf(p->out, \"gcc-\" __VERSION__ \"\\n\");\n#endif\n  }else\n\n  if( c=='v' && strncmp(azArg[0], \"vfsinfo\", n)==0 ){\n    const char *zDbName = nArg==2 ? azArg[1] : \"main\";\n    sqlite3_vfs *pVfs = 0;\n    if( p->db ){\n      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);\n      if( pVfs ){\n        utf8_printf(p->out, \"vfs.zName      = \\\"%s\\\"\\n\", pVfs->zName);\n        raw_printf(p->out, \"vfs.iVersion   = %d\\n\", pVfs->iVersion);\n        raw_printf(p->out, \"vfs.szOsFile   = %d\\n\", pVfs->szOsFile);\n        raw_printf(p->out, \"vfs.mxPathname = %d\\n\", pVfs->mxPathname);\n      }\n    }\n  }else\n\n  if( c=='v' && strncmp(azArg[0], \"vfslist\", n)==0 ){\n    sqlite3_vfs *pVfs;\n    sqlite3_vfs *pCurrent = 0;\n    if( p->db ){\n      sqlite3_file_control(p->db, \"main\", SQLITE_FCNTL_VFS_POINTER, &pCurrent);\n    }\n    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){\n      utf8_printf(p->out, \"vfs.zName      = \\\"%s\\\"%s\\n\", pVfs->zName,\n           pVfs==pCurrent ? \"  <--- CURRENT\" : \"\");\n      raw_printf(p->out, \"vfs.iVersion   = %d\\n\", pVfs->iVersion);\n      raw_printf(p->out, \"vfs.szOsFile   = %d\\n\", pVfs->szOsFile);\n      raw_printf(p->out, \"vfs.mxPathname = %d\\n\", pVfs->mxPathname);\n      if( pVfs->pNext ){\n        raw_printf(p->out, \"-----------------------------------\\n\");\n      }\n    }\n  }else\n\n  if( c=='v' && strncmp(azArg[0], \"vfsname\", n)==0 ){\n    const char *zDbName = nArg==2 ? azArg[1] : \"main\";\n    char *zVfsName = 0;\n    if( p->db ){\n      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);\n      if( zVfsName ){\n        utf8_printf(p->out, \"%s\\n\", zVfsName);\n        sqlite3_free(zVfsName);\n      }\n    }\n  }else\n\n#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)\n  if( c=='w' && strncmp(azArg[0], \"wheretrace\", n)==0 ){\n    sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;\n  }else\n#endif\n\n  if( c=='w' && strncmp(azArg[0], \"width\", n)==0 ){\n    int j;\n    assert( nArg<=ArraySize(azArg) );\n    for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){\n      p->colWidth[j-1] = (int)integerValue(azArg[j]);\n    }\n  }else\n\n  {\n    utf8_printf(stderr, \"Error: unknown command or invalid arguments: \"\n      \" \\\"%s\\\". Enter \\\".help\\\" for help\\n\", azArg[0]);\n    rc = 1;\n  }\n\nmeta_command_exit:\n  if( p->outCount ){\n    p->outCount--;\n    if( p->outCount==0 ) output_reset(p);\n  }\n  return rc;\n}\n\n/*\n** Return TRUE if a semicolon occurs anywhere in the first N characters\n** of string z[].\n*/\nstatic int line_contains_semicolon(const char *z, int N){\n  int i;\n  for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }\n  return 0;\n}\n\n/*\n** Test to see if a line consists entirely of whitespace.\n*/\nstatic int _all_whitespace(const char *z){\n  for(; *z; z++){\n    if( IsSpace(z[0]) ) continue;\n    if( *z=='/' && z[1]=='*' ){\n      z += 2;\n      while( *z && (*z!='*' || z[1]!='/') ){ z++; }\n      if( *z==0 ) return 0;\n      z++;\n      continue;\n    }\n    if( *z=='-' && z[1]=='-' ){\n      z += 2;\n      while( *z && *z!='\\n' ){ z++; }\n      if( *z==0 ) return 1;\n      continue;\n    }\n    return 0;\n  }\n  return 1;\n}\n\n/*\n** Return TRUE if the line typed in is an SQL command terminator other\n** than a semi-colon.  The SQL Server style \"go\" command is understood\n** as is the Oracle \"/\".\n*/\nstatic int line_is_command_terminator(const char *zLine){\n  while( IsSpace(zLine[0]) ){ zLine++; };\n  if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){\n    return 1;  /* Oracle */\n  }\n  if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'\n         && _all_whitespace(&zLine[2]) ){\n    return 1;  /* SQL Server */\n  }\n  return 0;\n}\n\n/*\n** We need a default sqlite3_complete() implementation to use in case\n** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes\n** any arbitrary text is a complete SQL statement.  This is not very\n** user-friendly, but it does seem to work.\n*/\n#ifdef SQLITE_OMIT_COMPLETE\n#define sqlite3_complete(x) 1\n#endif\n\n/*\n** Return true if zSql is a complete SQL statement.  Return false if it\n** ends in the middle of a string literal or C-style comment.\n*/\nstatic int line_is_complete(char *zSql, int nSql){\n  int rc;\n  if( zSql==0 ) return 1;\n  zSql[nSql] = ';';\n  zSql[nSql+1] = 0;\n  rc = sqlite3_complete(zSql);\n  zSql[nSql] = 0;\n  return rc;\n}\n\n/*\n** Run a single line of SQL.  Return the number of errors.\n*/\nstatic int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){\n  int rc;\n  char *zErrMsg = 0;\n\n  open_db(p, 0);\n  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);\n  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;\n  BEGIN_TIMER;\n  rc = shell_exec(p, zSql, &zErrMsg);\n  END_TIMER;\n  if( rc || zErrMsg ){\n    char zPrefix[100];\n    if( in!=0 || !stdin_is_interactive ){\n      sqlite3_snprintf(sizeof(zPrefix), zPrefix,\n                       \"Error: near line %d:\", startline);\n    }else{\n      sqlite3_snprintf(sizeof(zPrefix), zPrefix, \"Error:\");\n    }\n    if( zErrMsg!=0 ){\n      utf8_printf(stderr, \"%s %s\\n\", zPrefix, zErrMsg);\n      sqlite3_free(zErrMsg);\n      zErrMsg = 0;\n    }else{\n      utf8_printf(stderr, \"%s %s\\n\", zPrefix, sqlite3_errmsg(p->db));\n    }\n    return 1;\n  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){\n    raw_printf(p->out, \"changes: %3d   total_changes: %d\\n\",\n            sqlite3_changes(p->db), sqlite3_total_changes(p->db));\n  }\n  return 0;\n}\n\n\n/*\n** Read input from *in and process it.  If *in==0 then input\n** is interactive - the user is typing it it.  Otherwise, input\n** is coming from a file or device.  A prompt is issued and history\n** is saved only if input is interactive.  An interrupt signal will\n** cause this routine to exit immediately, unless input is interactive.\n**\n** Return the number of errors.\n*/\nstatic int process_input(ShellState *p){\n  char *zLine = 0;          /* A single input line */\n  char *zSql = 0;           /* Accumulated SQL text */\n  int nLine;                /* Length of current line */\n  int nSql = 0;             /* Bytes of zSql[] used */\n  int nAlloc = 0;           /* Allocated zSql[] space */\n  int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */\n  int rc;                   /* Error code */\n  int errCnt = 0;           /* Number of errors seen */\n  int startline = 0;        /* Line number for start of current input */\n\n  p->lineno = 0;\n  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){\n    fflush(p->out);\n    zLine = one_input_line(p->in, zLine, nSql>0);\n    if( zLine==0 ){\n      /* End of input */\n      if( p->in==0 && stdin_is_interactive ) printf(\"\\n\");\n      break;\n    }\n    if( seenInterrupt ){\n      if( p->in!=0 ) break;\n      seenInterrupt = 0;\n    }\n    p->lineno++;\n    if( nSql==0 && _all_whitespace(zLine) ){\n      if( ShellHasFlag(p, SHFLG_Echo) ) printf(\"%s\\n\", zLine);\n      continue;\n    }\n    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){\n      if( ShellHasFlag(p, SHFLG_Echo) ) printf(\"%s\\n\", zLine);\n      if( zLine[0]=='.' ){\n        rc = do_meta_command(zLine, p);\n        if( rc==2 ){ /* exit requested */\n          break;\n        }else if( rc ){\n          errCnt++;\n        }\n      }\n      continue;\n    }\n    if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){\n      memcpy(zLine,\";\",2);\n    }\n    nLine = strlen30(zLine);\n    if( nSql+nLine+2>=nAlloc ){\n      nAlloc = nSql+nLine+100;\n      zSql = realloc(zSql, nAlloc);\n      if( zSql==0 ) shell_out_of_memory();\n    }\n    nSqlPrior = nSql;\n    if( nSql==0 ){\n      int i;\n      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}\n      assert( nAlloc>0 && zSql!=0 );\n      memcpy(zSql, zLine+i, nLine+1-i);\n      startline = p->lineno;\n      nSql = nLine-i;\n    }else{\n      zSql[nSql++] = '\\n';\n      memcpy(zSql+nSql, zLine, nLine+1);\n      nSql += nLine;\n    }\n    if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)\n                && sqlite3_complete(zSql) ){\n      errCnt += runOneSqlLine(p, zSql, p->in, startline);\n      nSql = 0;\n      if( p->outCount ){\n        output_reset(p);\n        p->outCount = 0;\n      }else{\n        clearTempFile(p);\n      }\n    }else if( nSql && _all_whitespace(zSql) ){\n      if( ShellHasFlag(p, SHFLG_Echo) ) printf(\"%s\\n\", zSql);\n      nSql = 0;\n    }\n  }\n  if( nSql && !_all_whitespace(zSql) ){\n    errCnt += runOneSqlLine(p, zSql, p->in, startline);\n  }\n  free(zSql);\n  free(zLine);\n  return errCnt>0;\n}\n\n/*\n** Return a pathname which is the user's home directory.  A\n** 0 return indicates an error of some kind.\n*/\nstatic char *find_home_dir(int clearFlag){\n  static char *home_dir = NULL;\n  if( clearFlag ){\n    free(home_dir);\n    home_dir = 0;\n    return 0;\n  }\n  if( home_dir ) return home_dir;\n\n#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \\\n     && !defined(__RTP__) && !defined(_WRS_KERNEL)\n  {\n    struct passwd *pwent;\n    uid_t uid = getuid();\n    if( (pwent=getpwuid(uid)) != NULL) {\n      home_dir = pwent->pw_dir;\n    }\n  }\n#endif\n\n#if defined(_WIN32_WCE)\n  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()\n   */\n  home_dir = \"/\";\n#else\n\n#if defined(_WIN32) || defined(WIN32)\n  if (!home_dir) {\n    home_dir = getenv(\"USERPROFILE\");\n  }\n#endif\n\n  if (!home_dir) {\n    home_dir = getenv(\"HOME\");\n  }\n\n#if defined(_WIN32) || defined(WIN32)\n  if (!home_dir) {\n    char *zDrive, *zPath;\n    int n;\n    zDrive = getenv(\"HOMEDRIVE\");\n    zPath = getenv(\"HOMEPATH\");\n    if( zDrive && zPath ){\n      n = strlen30(zDrive) + strlen30(zPath) + 1;\n      home_dir = malloc( n );\n      if( home_dir==0 ) return 0;\n      sqlite3_snprintf(n, home_dir, \"%s%s\", zDrive, zPath);\n      return home_dir;\n    }\n    home_dir = \"c:\\\\\";\n  }\n#endif\n\n#endif /* !_WIN32_WCE */\n\n  if( home_dir ){\n    int n = strlen30(home_dir) + 1;\n    char *z = malloc( n );\n    if( z ) memcpy(z, home_dir, n);\n    home_dir = z;\n  }\n\n  return home_dir;\n}\n\n/*\n** Read input from the file given by sqliterc_override.  Or if that\n** parameter is NULL, take input from ~/.sqliterc\n**\n** Returns the number of errors.\n*/\nstatic void process_sqliterc(\n  ShellState *p,                  /* Configuration data */\n  const char *sqliterc_override   /* Name of config file. NULL to use default */\n){\n  char *home_dir = NULL;\n  const char *sqliterc = sqliterc_override;\n  char *zBuf = 0;\n  FILE *inSaved = p->in;\n  int savedLineno = p->lineno;\n\n  if (sqliterc == NULL) {\n    home_dir = find_home_dir(0);\n    if( home_dir==0 ){\n      raw_printf(stderr, \"-- warning: cannot find home directory;\"\n                      \" cannot read ~/.sqliterc\\n\");\n      return;\n    }\n    zBuf = sqlite3_mprintf(\"%s/.sqliterc\",home_dir);\n    sqliterc = zBuf;\n  }\n  p->in = fopen(sqliterc,\"rb\");\n  if( p->in ){\n    if( stdin_is_interactive ){\n      utf8_printf(stderr,\"-- Loading resources from %s\\n\",sqliterc);\n    }\n    process_input(p);\n    fclose(p->in);\n  }\n  p->in = inSaved;\n  p->lineno = savedLineno;\n  sqlite3_free(zBuf);\n}\n\n/*\n** Show available command line options\n*/\nstatic const char zOptions[] =\n#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)\n  \"   -A ARGS...           run \\\".archive ARGS\\\" and exit\\n\"\n#endif\n  \"   -append              append the database to the end of the file\\n\"\n  \"   -ascii               set output mode to 'ascii'\\n\"\n  \"   -bail                stop after hitting an error\\n\"\n  \"   -batch               force batch I/O\\n\"\n  \"   -column              set output mode to 'column'\\n\"\n  \"   -cmd COMMAND         run \\\"COMMAND\\\" before reading stdin\\n\"\n  \"   -csv                 set output mode to 'csv'\\n\"\n#if defined(SQLITE_ENABLE_DESERIALIZE)\n  \"   -deserialize         open the database using sqlite3_deserialize()\\n\"\n#endif\n  \"   -echo                print commands before execution\\n\"\n  \"   -init FILENAME       read/process named file\\n\"\n  \"   -[no]header          turn headers on or off\\n\"\n#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)\n  \"   -heap SIZE           Size of heap for memsys3 or memsys5\\n\"\n#endif\n  \"   -help                show this message\\n\"\n  \"   -html                set output mode to HTML\\n\"\n  \"   -interactive         force interactive I/O\\n\"\n  \"   -line                set output mode to 'line'\\n\"\n  \"   -list                set output mode to 'list'\\n\"\n  \"   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\\n\"\n#if defined(SQLITE_ENABLE_DESERIALIZE)\n  \"   -maxsize N           maximum size for a --deserialize database\\n\"\n#endif\n  \"   -memtrace            trace all memory allocations and deallocations\\n\"\n  \"   -mmap N              default mmap size set to N\\n\"\n#ifdef SQLITE_ENABLE_MULTIPLEX\n  \"   -multiplex           enable the multiplexor VFS\\n\"\n#endif\n  \"   -newline SEP         set output row separator. Default: '\\\\n'\\n\"\n  \"   -nofollow            refuse to open symbolic links to database files\\n\"\n  \"   -nullvalue TEXT      set text string for NULL values. Default ''\\n\"\n  \"   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\\n\"\n  \"   -quote               set output mode to 'quote'\\n\"\n  \"   -readonly            open the database read-only\\n\"\n  \"   -separator SEP       set output column separator. Default: '|'\\n\"\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n  \"   -sorterref SIZE      sorter references threshold size\\n\"\n#endif\n  \"   -stats               print memory stats before each finalize\\n\"\n  \"   -version             show SQLite version\\n\"\n  \"   -vfs NAME            use NAME as the default VFS\\n\"\n#ifdef SQLITE_ENABLE_VFSTRACE\n  \"   -vfstrace            enable tracing of all VFS calls\\n\"\n#endif\n#ifdef SQLITE_HAVE_ZLIB\n  \"   -zip                 open the file as a ZIP Archive\\n\"\n#endif\n;\nstatic void usage(int showDetail){\n  utf8_printf(stderr,\n      \"Usage: %s [OPTIONS] FILENAME [SQL]\\n\"\n      \"FILENAME is the name of an SQLite database. A new database is created\\n\"\n      \"if the file does not previously exist.\\n\", Argv0);\n  if( showDetail ){\n    utf8_printf(stderr, \"OPTIONS include:\\n%s\", zOptions);\n  }else{\n    raw_printf(stderr, \"Use the -help option for additional information\\n\");\n  }\n  exit(1);\n}\n\n/*\n** Internal check:  Verify that the SQLite is uninitialized.  Print a\n** error message if it is initialized.\n*/\nstatic void verify_uninitialized(void){\n  if( sqlite3_config(-1)==SQLITE_MISUSE ){\n    utf8_printf(stdout, \"WARNING: attempt to configure SQLite after\"\n                        \" initialization.\\n\");\n  }\n}\n\n/*\n** Initialize the state information in data\n*/\nstatic void main_init(ShellState *data) {\n  memset(data, 0, sizeof(*data));\n  data->normalMode = data->cMode = data->mode = MODE_List;\n  data->autoExplain = 1;\n  memcpy(data->colSeparator,SEP_Column, 2);\n  memcpy(data->rowSeparator,SEP_Row, 2);\n  data->showHeader = 0;\n  data->shellFlgs = SHFLG_Lookaside;\n  verify_uninitialized();\n  sqlite3_config(SQLITE_CONFIG_URI, 1);\n  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);\n  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);\n  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,\"sqlite> \");\n  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,\"   ...> \");\n}\n\n/*\n** Output text to the console in a font that attracts extra attention.\n*/\n#ifdef _WIN32\nstatic void printBold(const char *zText){\n#if !SQLITE_OS_WINRT\n  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);\n  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;\n  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);\n  SetConsoleTextAttribute(out,\n         FOREGROUND_RED|FOREGROUND_INTENSITY\n  );\n#endif\n  printf(\"%s\", zText);\n#if !SQLITE_OS_WINRT\n  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);\n#endif\n}\n#else\nstatic void printBold(const char *zText){\n  printf(\"\\033[1m%s\\033[0m\", zText);\n}\n#endif\n\n/*\n** Get the argument to an --option.  Throw an error and die if no argument\n** is available.\n*/\nstatic char *cmdline_option_value(int argc, char **argv, int i){\n  if( i==argc ){\n    utf8_printf(stderr, \"%s: Error: missing argument to %s\\n\",\n            argv[0], argv[argc-1]);\n    exit(1);\n  }\n  return argv[i];\n}\n\n#ifndef SQLITE_SHELL_IS_UTF8\n#  if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)\n#    define SQLITE_SHELL_IS_UTF8          (0)\n#  else\n#    define SQLITE_SHELL_IS_UTF8          (1)\n#  endif\n#endif\n\n#if SQLITE_SHELL_IS_UTF8\nint SQLITE_CDECL main(int argc, char **argv){\n#else\nint SQLITE_CDECL wmain(int argc, wchar_t **wargv){\n  char **argv;\n#endif\n  char *zErrMsg = 0;\n  ShellState data;\n  const char *zInitFile = 0;\n  int i;\n  int rc = 0;\n  int warnInmemoryDb = 0;\n  int readStdin = 1;\n  int nCmd = 0;\n  char **azCmd = 0;\n  const char *zVfs = 0;           /* Value of -vfs command-line option */\n#if !SQLITE_SHELL_IS_UTF8\n  char **argvToFree = 0;\n  int argcToFree = 0;\n#endif\n\n  setBinaryMode(stdin, 0);\n  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */\n  stdin_is_interactive = isatty(0);\n  stdout_is_console = isatty(1);\n\n#ifdef SQLITE_DEBUG\n  registerOomSimulator();\n#endif\n\n#if !defined(_WIN32_WCE)\n  if( getenv(\"SQLITE_DEBUG_BREAK\") ){\n    if( isatty(0) && isatty(2) ){\n      fprintf(stderr,\n          \"attach debugger to process %d and press any key to continue.\\n\",\n          GETPID());\n      fgetc(stdin);\n    }else{\n#if defined(_WIN32) || defined(WIN32)\n#if SQLITE_OS_WINRT\n      __debugbreak();\n#else\n      DebugBreak();\n#endif\n#elif defined(SIGTRAP)\n      raise(SIGTRAP);\n#endif\n    }\n  }\n#endif\n\n#if USE_SYSTEM_SQLITE+0!=1\n  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){\n    utf8_printf(stderr, \"SQLite header and source version mismatch\\n%s\\n%s\\n\",\n            sqlite3_sourceid(), SQLITE_SOURCE_ID);\n    exit(1);\n  }\n#endif\n  main_init(&data);\n\n  /* On Windows, we must translate command-line arguments into UTF-8.\n  ** The SQLite memory allocator subsystem has to be enabled in order to\n  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that\n  ** subsequent sqlite3_config() calls will work.  So copy all results into\n  ** memory that does not come from the SQLite memory allocator.\n  */\n#if !SQLITE_SHELL_IS_UTF8\n  sqlite3_initialize();\n  argvToFree = malloc(sizeof(argv[0])*argc*2);\n  argcToFree = argc;\n  argv = argvToFree + argc;\n  if( argv==0 ) shell_out_of_memory();\n  for(i=0; i<argc; i++){\n    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);\n    int n;\n    if( z==0 ) shell_out_of_memory();\n    n = (int)strlen(z);\n    argv[i] = malloc( n+1 );\n    if( argv[i]==0 ) shell_out_of_memory();\n    memcpy(argv[i], z, n+1);\n    argvToFree[i] = argv[i];\n    sqlite3_free(z);\n  }\n  sqlite3_shutdown();\n#endif\n\n  assert( argc>=1 && argv && argv[0] );\n  Argv0 = argv[0];\n\n  /* Make sure we have a valid signal handler early, before anything\n  ** else is done.\n  */\n#ifdef SIGINT\n  signal(SIGINT, interrupt_handler);\n#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)\n  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);\n#endif\n\n#ifdef SQLITE_SHELL_DBNAME_PROC\n  {\n    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name\n    ** of a C-function that will provide the name of the database file.  Use\n    ** this compile-time option to embed this shell program in larger\n    ** applications. */\n    extern void SQLITE_SHELL_DBNAME_PROC(const char**);\n    SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);\n    warnInmemoryDb = 0;\n  }\n#endif\n\n  /* Do an initial pass through the command-line argument to locate\n  ** the name of the database file, the name of the initialization file,\n  ** the size of the alternative malloc heap,\n  ** and the first command to execute.\n  */\n  verify_uninitialized();\n  for(i=1; i<argc; i++){\n    char *z;\n    z = argv[i];\n    if( z[0]!='-' ){\n      if( data.zDbFilename==0 ){\n        data.zDbFilename = z;\n      }else{\n        /* Excesss arguments are interpreted as SQL (or dot-commands) and\n        ** mean that nothing is read from stdin */\n        readStdin = 0;\n        nCmd++;\n        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);\n        if( azCmd==0 ) shell_out_of_memory();\n        azCmd[nCmd-1] = z;\n      }\n    }\n    if( z[1]=='-' ) z++;\n    if( strcmp(z,\"-separator\")==0\n     || strcmp(z,\"-nullvalue\")==0\n     || strcmp(z,\"-newline\")==0\n     || strcmp(z,\"-cmd\")==0\n    ){\n      (void)cmdline_option_value(argc, argv, ++i);\n    }else if( strcmp(z,\"-init\")==0 ){\n      zInitFile = cmdline_option_value(argc, argv, ++i);\n    }else if( strcmp(z,\"-batch\")==0 ){\n      /* Need to check for batch mode here to so we can avoid printing\n      ** informational messages (like from process_sqliterc) before\n      ** we do the actual processing of arguments later in a second pass.\n      */\n      stdin_is_interactive = 0;\n    }else if( strcmp(z,\"-heap\")==0 ){\n#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)\n      const char *zSize;\n      sqlite3_int64 szHeap;\n\n      zSize = cmdline_option_value(argc, argv, ++i);\n      szHeap = integerValue(zSize);\n      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;\n      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);\n#else\n      (void)cmdline_option_value(argc, argv, ++i);\n#endif\n    }else if( strcmp(z,\"-pagecache\")==0 ){\n      int n, sz;\n      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));\n      if( sz>70000 ) sz = 70000;\n      if( sz<0 ) sz = 0;\n      n = (int)integerValue(cmdline_option_value(argc,argv,++i));\n      sqlite3_config(SQLITE_CONFIG_PAGECACHE,\n                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);\n      data.shellFlgs |= SHFLG_Pagecache;\n    }else if( strcmp(z,\"-lookaside\")==0 ){\n      int n, sz;\n      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));\n      if( sz<0 ) sz = 0;\n      n = (int)integerValue(cmdline_option_value(argc,argv,++i));\n      if( n<0 ) n = 0;\n      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);\n      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;\n#ifdef SQLITE_ENABLE_VFSTRACE\n    }else if( strcmp(z,\"-vfstrace\")==0 ){\n      extern int vfstrace_register(\n         const char *zTraceName,\n         const char *zOldVfsName,\n         int (*xOut)(const char*,void*),\n         void *pOutArg,\n         int makeDefault\n      );\n      vfstrace_register(\"trace\",0,(int(*)(const char*,void*))fputs,stderr,1);\n#endif\n#ifdef SQLITE_ENABLE_MULTIPLEX\n    }else if( strcmp(z,\"-multiplex\")==0 ){\n      extern int sqlite3_multiple_initialize(const char*,int);\n      sqlite3_multiplex_initialize(0, 1);\n#endif\n    }else if( strcmp(z,\"-mmap\")==0 ){\n      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));\n      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n    }else if( strcmp(z,\"-sorterref\")==0 ){\n      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));\n      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);\n#endif\n    }else if( strcmp(z,\"-vfs\")==0 ){\n      zVfs = cmdline_option_value(argc, argv, ++i);\n#ifdef SQLITE_HAVE_ZLIB\n    }else if( strcmp(z,\"-zip\")==0 ){\n      data.openMode = SHELL_OPEN_ZIPFILE;\n#endif\n    }else if( strcmp(z,\"-append\")==0 ){\n      data.openMode = SHELL_OPEN_APPENDVFS;\n#ifdef SQLITE_ENABLE_DESERIALIZE\n    }else if( strcmp(z,\"-deserialize\")==0 ){\n      data.openMode = SHELL_OPEN_DESERIALIZE;\n    }else if( strcmp(z,\"-maxsize\")==0 && i+1<argc ){\n      data.szMax = integerValue(argv[++i]);\n#endif\n    }else if( strcmp(z,\"-readonly\")==0 ){\n      data.openMode = SHELL_OPEN_READONLY;\n    }else if( strcmp(z,\"-nofollow\")==0 ){\n      data.openFlags = SQLITE_OPEN_NOFOLLOW;\n#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)\n    }else if( strncmp(z, \"-A\",2)==0 ){\n      /* All remaining command-line arguments are passed to the \".archive\"\n      ** command, so ignore them */\n      break;\n#endif\n    }else if( strcmp(z, \"-memtrace\")==0 ){\n      sqlite3MemTraceActivate(stderr);\n    }\n  }\n  verify_uninitialized();\n\n\n#ifdef SQLITE_SHELL_INIT_PROC\n  {\n    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name\n    ** of a C-function that will perform initialization actions on SQLite that\n    ** occur just before or after sqlite3_initialize(). Use this compile-time\n    ** option to embed this shell program in larger applications. */\n    extern void SQLITE_SHELL_INIT_PROC(void);\n    SQLITE_SHELL_INIT_PROC();\n  }\n#else\n  /* All the sqlite3_config() calls have now been made. So it is safe\n  ** to call sqlite3_initialize() and process any command line -vfs option. */\n  sqlite3_initialize();\n#endif\n\n  if( zVfs ){\n    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);\n    if( pVfs ){\n      sqlite3_vfs_register(pVfs, 1);\n    }else{\n      utf8_printf(stderr, \"no such VFS: \\\"%s\\\"\\n\", argv[i]);\n      exit(1);\n    }\n  }\n\n  if( data.zDbFilename==0 ){\n#ifndef SQLITE_OMIT_MEMORYDB\n    data.zDbFilename = \":memory:\";\n    warnInmemoryDb = argc==1;\n#else\n    utf8_printf(stderr,\"%s: Error: no database filename specified\\n\", Argv0);\n    return 1;\n#endif\n  }\n  data.out = stdout;\n  sqlite3_appendvfs_init(0,0,0);\n\n  /* Go ahead and open the database file if it already exists.  If the\n  ** file does not exist, delay opening it.  This prevents empty database\n  ** files from being created if a user mistypes the database name argument\n  ** to the sqlite command-line tool.\n  */\n  if( access(data.zDbFilename, 0)==0 ){\n    open_db(&data, 0);\n  }\n\n  /* Process the initialization file if there is one.  If no -init option\n  ** is given on the command line, look for a file named ~/.sqliterc and\n  ** try to process it.\n  */\n  process_sqliterc(&data,zInitFile);\n\n  /* Make a second pass through the command-line argument and set\n  ** options.  This second pass is delayed until after the initialization\n  ** file is processed so that the command-line arguments will override\n  ** settings in the initialization file.\n  */\n  for(i=1; i<argc; i++){\n    char *z = argv[i];\n    if( z[0]!='-' ) continue;\n    if( z[1]=='-' ){ z++; }\n    if( strcmp(z,\"-init\")==0 ){\n      i++;\n    }else if( strcmp(z,\"-html\")==0 ){\n      data.mode = MODE_Html;\n    }else if( strcmp(z,\"-list\")==0 ){\n      data.mode = MODE_List;\n    }else if( strcmp(z,\"-quote\")==0 ){\n      data.mode = MODE_Quote;\n    }else if( strcmp(z,\"-line\")==0 ){\n      data.mode = MODE_Line;\n    }else if( strcmp(z,\"-column\")==0 ){\n      data.mode = MODE_Column;\n    }else if( strcmp(z,\"-csv\")==0 ){\n      data.mode = MODE_Csv;\n      memcpy(data.colSeparator,\",\",2);\n#ifdef SQLITE_HAVE_ZLIB\n    }else if( strcmp(z,\"-zip\")==0 ){\n      data.openMode = SHELL_OPEN_ZIPFILE;\n#endif\n    }else if( strcmp(z,\"-append\")==0 ){\n      data.openMode = SHELL_OPEN_APPENDVFS;\n#ifdef SQLITE_ENABLE_DESERIALIZE\n    }else if( strcmp(z,\"-deserialize\")==0 ){\n      data.openMode = SHELL_OPEN_DESERIALIZE;\n    }else if( strcmp(z,\"-maxsize\")==0 && i+1<argc ){\n      data.szMax = integerValue(argv[++i]);\n#endif\n    }else if( strcmp(z,\"-readonly\")==0 ){\n      data.openMode = SHELL_OPEN_READONLY;\n    }else if( strcmp(z,\"-nofollow\")==0 ){\n      data.openFlags |= SQLITE_OPEN_NOFOLLOW;\n    }else if( strcmp(z,\"-ascii\")==0 ){\n      data.mode = MODE_Ascii;\n      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,\n                       SEP_Unit);\n      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,\n                       SEP_Record);\n    }else if( strcmp(z,\"-separator\")==0 ){\n      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,\n                       \"%s\",cmdline_option_value(argc,argv,++i));\n    }else if( strcmp(z,\"-newline\")==0 ){\n      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,\n                       \"%s\",cmdline_option_value(argc,argv,++i));\n    }else if( strcmp(z,\"-nullvalue\")==0 ){\n      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,\n                       \"%s\",cmdline_option_value(argc,argv,++i));\n    }else if( strcmp(z,\"-header\")==0 ){\n      data.showHeader = 1;\n    }else if( strcmp(z,\"-noheader\")==0 ){\n      data.showHeader = 0;\n    }else if( strcmp(z,\"-echo\")==0 ){\n      ShellSetFlag(&data, SHFLG_Echo);\n    }else if( strcmp(z,\"-eqp\")==0 ){\n      data.autoEQP = AUTOEQP_on;\n    }else if( strcmp(z,\"-eqpfull\")==0 ){\n      data.autoEQP = AUTOEQP_full;\n    }else if( strcmp(z,\"-stats\")==0 ){\n      data.statsOn = 1;\n    }else if( strcmp(z,\"-scanstats\")==0 ){\n      data.scanstatsOn = 1;\n    }else if( strcmp(z,\"-backslash\")==0 ){\n      /* Undocumented command-line option: -backslash\n      ** Causes C-style backslash escapes to be evaluated in SQL statements\n      ** prior to sending the SQL into SQLite.  Useful for injecting\n      ** crazy bytes in the middle of SQL statements for testing and debugging.\n      */\n      ShellSetFlag(&data, SHFLG_Backslash);\n    }else if( strcmp(z,\"-bail\")==0 ){\n      bail_on_error = 1;\n    }else if( strcmp(z,\"-version\")==0 ){\n      printf(\"%s %s\\n\", sqlite3_libversion(), sqlite3_sourceid());\n      return 0;\n    }else if( strcmp(z,\"-interactive\")==0 ){\n      stdin_is_interactive = 1;\n    }else if( strcmp(z,\"-batch\")==0 ){\n      stdin_is_interactive = 0;\n    }else if( strcmp(z,\"-heap\")==0 ){\n      i++;\n    }else if( strcmp(z,\"-pagecache\")==0 ){\n      i+=2;\n    }else if( strcmp(z,\"-lookaside\")==0 ){\n      i+=2;\n    }else if( strcmp(z,\"-mmap\")==0 ){\n      i++;\n    }else if( strcmp(z,\"-memtrace\")==0 ){\n      i++;\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n    }else if( strcmp(z,\"-sorterref\")==0 ){\n      i++;\n#endif\n    }else if( strcmp(z,\"-vfs\")==0 ){\n      i++;\n#ifdef SQLITE_ENABLE_VFSTRACE\n    }else if( strcmp(z,\"-vfstrace\")==0 ){\n      i++;\n#endif\n#ifdef SQLITE_ENABLE_MULTIPLEX\n    }else if( strcmp(z,\"-multiplex\")==0 ){\n      i++;\n#endif\n    }else if( strcmp(z,\"-help\")==0 ){\n      usage(1);\n    }else if( strcmp(z,\"-cmd\")==0 ){\n      /* Run commands that follow -cmd first and separately from commands\n      ** that simply appear on the command-line.  This seems goofy.  It would\n      ** be better if all commands ran in the order that they appear.  But\n      ** we retain the goofy behavior for historical compatibility. */\n      if( i==argc-1 ) break;\n      z = cmdline_option_value(argc,argv,++i);\n      if( z[0]=='.' ){\n        rc = do_meta_command(z, &data);\n        if( rc && bail_on_error ) return rc==2 ? 0 : rc;\n      }else{\n        open_db(&data, 0);\n        rc = shell_exec(&data, z, &zErrMsg);\n        if( zErrMsg!=0 ){\n          utf8_printf(stderr,\"Error: %s\\n\", zErrMsg);\n          if( bail_on_error ) return rc!=0 ? rc : 1;\n        }else if( rc!=0 ){\n          utf8_printf(stderr,\"Error: unable to process SQL \\\"%s\\\"\\n\", z);\n          if( bail_on_error ) return rc;\n        }\n      }\n#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)\n    }else if( strncmp(z, \"-A\", 2)==0 ){\n      if( nCmd>0 ){\n        utf8_printf(stderr, \"Error: cannot mix regular SQL or dot-commands\"\n                            \" with \\\"%s\\\"\\n\", z);\n        return 1;\n      }\n      open_db(&data, OPEN_DB_ZIPFILE);\n      if( z[2] ){\n        argv[i] = &z[2];\n        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));\n      }else{\n        arDotCommand(&data, 1, argv+i, argc-i);\n      }\n      readStdin = 0;\n      break;\n#endif\n    }else{\n      utf8_printf(stderr,\"%s: Error: unknown option: %s\\n\", Argv0, z);\n      raw_printf(stderr,\"Use -help for a list of options.\\n\");\n      return 1;\n    }\n    data.cMode = data.mode;\n  }\n\n  if( !readStdin ){\n    /* Run all arguments that do not begin with '-' as if they were separate\n    ** command-line inputs, except for the argToSkip argument which contains\n    ** the database filename.\n    */\n    for(i=0; i<nCmd; i++){\n      if( azCmd[i][0]=='.' ){\n        rc = do_meta_command(azCmd[i], &data);\n        if( rc ) return rc==2 ? 0 : rc;\n      }else{\n        open_db(&data, 0);\n        rc = shell_exec(&data, azCmd[i], &zErrMsg);\n        if( zErrMsg!=0 ){\n          utf8_printf(stderr,\"Error: %s\\n\", zErrMsg);\n          return rc!=0 ? rc : 1;\n        }else if( rc!=0 ){\n          utf8_printf(stderr,\"Error: unable to process SQL: %s\\n\", azCmd[i]);\n          return rc;\n        }\n      }\n    }\n    free(azCmd);\n  }else{\n    /* Run commands received from standard input\n    */\n    if( stdin_is_interactive ){\n      char *zHome;\n      char *zHistory;\n      int nHistory;\n      printf(\n        \"SQLite version %s %.19s\\n\" /*extra-version-info*/\n        \"Enter \\\".help\\\" for usage hints.\\n\",\n        sqlite3_libversion(), sqlite3_sourceid()\n      );\n      if( warnInmemoryDb ){\n        printf(\"Connected to a \");\n        printBold(\"transient in-memory database\");\n        printf(\".\\nUse \\\".open FILENAME\\\" to reopen on a \"\n               \"persistent database.\\n\");\n      }\n      zHistory = getenv(\"SQLITE_HISTORY\");\n      if( zHistory ){\n        zHistory = strdup(zHistory);\n      }else if( (zHome = find_home_dir(0))!=0 ){\n        nHistory = strlen30(zHome) + 20;\n        if( (zHistory = malloc(nHistory))!=0 ){\n          sqlite3_snprintf(nHistory, zHistory,\"%s/.sqlite_history\", zHome);\n        }\n      }\n      if( zHistory ){ shell_read_history(zHistory); }\n#if HAVE_READLINE || HAVE_EDITLINE\n      rl_attempted_completion_function = readline_completion;\n#elif HAVE_LINENOISE\n      linenoiseSetCompletionCallback(linenoise_completion);\n#endif\n      data.in = 0;\n      rc = process_input(&data);\n      if( zHistory ){\n        shell_stifle_history(2000);\n        shell_write_history(zHistory);\n        free(zHistory);\n      }\n    }else{\n      data.in = stdin;\n      rc = process_input(&data);\n    }\n  }\n  set_table_name(&data, 0);\n  if( data.db ){\n    session_close_all(&data);\n    close_db(data.db);\n  }\n  sqlite3_free(data.zFreeOnClose);\n  find_home_dir(1);\n  output_reset(&data);\n  data.doXdgOpen = 0;\n  clearTempFile(&data);\n#if !SQLITE_SHELL_IS_UTF8\n  for(i=0; i<argcToFree; i++) free(argvToFree[i]);\n  free(argvToFree);\n#endif\n  /* Clear the global data structure so that valgrind will detect memory\n  ** leaks */\n  memset(&data, 0, sizeof(data));\n  return rc;\n}\n"
  },
  {
    "path": "jsb_build/sqlite3/sqlite-amalgamation-3320300/sqlite3.c",
    "content": "/******************************************************************************\n** This file is an amalgamation of many separate C source files from SQLite\n** version 3.32.3.  By combining all the individual C code files into this\n** single large file, the entire code can be compiled as a single translation\n** unit.  This allows many compilers to do optimizations that would not be\n** possible if the files were compiled separately.  Performance improvements\n** of 5% or more are commonly seen when SQLite is compiled as a single\n** translation unit.\n**\n** This file is all you need to compile SQLite.  To use SQLite in other\n** programs, you need this file and the \"sqlite3.h\" header file that defines\n** the programming interface to the SQLite library.  (If you do not have\n** the \"sqlite3.h\" header file at hand, you will find a copy embedded within\n** the text of this file.  Search for \"Begin file sqlite3.h\" to find the start\n** of the embedded sqlite3.h header file.) Additional code files may be needed\n** if you want a wrapper to interface SQLite with your choice of programming\n** language. The code for the \"sqlite3\" command-line shell is also in a\n** separate file. This file contains only code for the core SQLite library.\n*/\n#define SQLITE_CORE 1\n#define SQLITE_AMALGAMATION 1\n#ifndef SQLITE_PRIVATE\n# define SQLITE_PRIVATE static\n#endif\n/************** Begin file ctime.c *******************************************/\n/*\n** 2010 February 23\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file implements routines used to report what compile-time options\n** SQLite was built with.\n*/\n\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* IMP: R-16824-07538 */\n\n/*\n** Include the configuration header output by 'configure' if we're using the\n** autoconf-based build\n*/\n#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)\n#include \"config.h\"\n#define SQLITECONFIG_H 1\n#endif\n\n/* These macros are provided to \"stringify\" the value of the define\n** for those options in which the value is meaningful. */\n#define CTIMEOPT_VAL_(opt) #opt\n#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)\n\n/* Like CTIMEOPT_VAL, but especially for SQLITE_DEFAULT_LOOKASIDE. This\n** option requires a separate macro because legal values contain a single\n** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE=\"100,100\") */\n#define CTIMEOPT_VAL2_(opt1,opt2) #opt1 \",\" #opt2\n#define CTIMEOPT_VAL2(opt) CTIMEOPT_VAL2_(opt)\n\n/*\n** An array of names of all compile-time options.  This array should \n** be sorted A-Z.\n**\n** This array looks large, but in a typical installation actually uses\n** only a handful of compile-time options, so most times this array is usually\n** rather short and uses little memory space.\n*/\nstatic const char * const sqlite3azCompileOpt[] = {\n\n/* \n** BEGIN CODE GENERATED BY tool/mkctime.tcl \n*/\n#if SQLITE_32BIT_ROWID\n  \"32BIT_ROWID\",\n#endif\n#if SQLITE_4_BYTE_ALIGNED_MALLOC\n  \"4_BYTE_ALIGNED_MALLOC\",\n#endif\n#if SQLITE_64BIT_STATS\n  \"64BIT_STATS\",\n#endif\n#if SQLITE_ALLOW_COVERING_INDEX_SCAN\n  \"ALLOW_COVERING_INDEX_SCAN\",\n#endif\n#if SQLITE_ALLOW_URI_AUTHORITY\n  \"ALLOW_URI_AUTHORITY\",\n#endif\n#ifdef SQLITE_BITMASK_TYPE\n  \"BITMASK_TYPE=\" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),\n#endif\n#if SQLITE_BUG_COMPATIBLE_20160819\n  \"BUG_COMPATIBLE_20160819\",\n#endif\n#if SQLITE_CASE_SENSITIVE_LIKE\n  \"CASE_SENSITIVE_LIKE\",\n#endif\n#if SQLITE_CHECK_PAGES\n  \"CHECK_PAGES\",\n#endif\n#if defined(__clang__) && defined(__clang_major__)\n  \"COMPILER=clang-\" CTIMEOPT_VAL(__clang_major__) \".\"\n                    CTIMEOPT_VAL(__clang_minor__) \".\"\n                    CTIMEOPT_VAL(__clang_patchlevel__),\n#elif defined(_MSC_VER)\n  \"COMPILER=msvc-\" CTIMEOPT_VAL(_MSC_VER),\n#elif defined(__GNUC__) && defined(__VERSION__)\n  \"COMPILER=gcc-\" __VERSION__,\n#endif\n#if SQLITE_COVERAGE_TEST\n  \"COVERAGE_TEST\",\n#endif\n#if SQLITE_DEBUG\n  \"DEBUG\",\n#endif\n#if SQLITE_DEFAULT_AUTOMATIC_INDEX\n  \"DEFAULT_AUTOMATIC_INDEX\",\n#endif\n#if SQLITE_DEFAULT_AUTOVACUUM\n  \"DEFAULT_AUTOVACUUM\",\n#endif\n#ifdef SQLITE_DEFAULT_CACHE_SIZE\n  \"DEFAULT_CACHE_SIZE=\" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),\n#endif\n#if SQLITE_DEFAULT_CKPTFULLFSYNC\n  \"DEFAULT_CKPTFULLFSYNC\",\n#endif\n#ifdef SQLITE_DEFAULT_FILE_FORMAT\n  \"DEFAULT_FILE_FORMAT=\" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),\n#endif\n#ifdef SQLITE_DEFAULT_FILE_PERMISSIONS\n  \"DEFAULT_FILE_PERMISSIONS=\" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),\n#endif\n#if SQLITE_DEFAULT_FOREIGN_KEYS\n  \"DEFAULT_FOREIGN_KEYS\",\n#endif\n#ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT\n  \"DEFAULT_JOURNAL_SIZE_LIMIT=\" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),\n#endif\n#ifdef SQLITE_DEFAULT_LOCKING_MODE\n  \"DEFAULT_LOCKING_MODE=\" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),\n#endif\n#ifdef SQLITE_DEFAULT_LOOKASIDE\n  \"DEFAULT_LOOKASIDE=\" CTIMEOPT_VAL2(SQLITE_DEFAULT_LOOKASIDE),\n#endif\n#if SQLITE_DEFAULT_MEMSTATUS\n  \"DEFAULT_MEMSTATUS\",\n#endif\n#ifdef SQLITE_DEFAULT_MMAP_SIZE\n  \"DEFAULT_MMAP_SIZE=\" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),\n#endif\n#ifdef SQLITE_DEFAULT_PAGE_SIZE\n  \"DEFAULT_PAGE_SIZE=\" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),\n#endif\n#ifdef SQLITE_DEFAULT_PCACHE_INITSZ\n  \"DEFAULT_PCACHE_INITSZ=\" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),\n#endif\n#ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS\n  \"DEFAULT_PROXYDIR_PERMISSIONS=\" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),\n#endif\n#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS\n  \"DEFAULT_RECURSIVE_TRIGGERS\",\n#endif\n#ifdef SQLITE_DEFAULT_ROWEST\n  \"DEFAULT_ROWEST=\" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),\n#endif\n#ifdef SQLITE_DEFAULT_SECTOR_SIZE\n  \"DEFAULT_SECTOR_SIZE=\" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),\n#endif\n#ifdef SQLITE_DEFAULT_SYNCHRONOUS\n  \"DEFAULT_SYNCHRONOUS=\" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),\n#endif\n#ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT\n  \"DEFAULT_WAL_AUTOCHECKPOINT=\" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),\n#endif\n#ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS\n  \"DEFAULT_WAL_SYNCHRONOUS=\" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),\n#endif\n#ifdef SQLITE_DEFAULT_WORKER_THREADS\n  \"DEFAULT_WORKER_THREADS=\" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),\n#endif\n#if SQLITE_DIRECT_OVERFLOW_READ\n  \"DIRECT_OVERFLOW_READ\",\n#endif\n#if SQLITE_DISABLE_DIRSYNC\n  \"DISABLE_DIRSYNC\",\n#endif\n#if SQLITE_DISABLE_FTS3_UNICODE\n  \"DISABLE_FTS3_UNICODE\",\n#endif\n#if SQLITE_DISABLE_FTS4_DEFERRED\n  \"DISABLE_FTS4_DEFERRED\",\n#endif\n#if SQLITE_DISABLE_INTRINSIC\n  \"DISABLE_INTRINSIC\",\n#endif\n#if SQLITE_DISABLE_LFS\n  \"DISABLE_LFS\",\n#endif\n#if SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS\n  \"DISABLE_PAGECACHE_OVERFLOW_STATS\",\n#endif\n#if SQLITE_DISABLE_SKIPAHEAD_DISTINCT\n  \"DISABLE_SKIPAHEAD_DISTINCT\",\n#endif\n#ifdef SQLITE_ENABLE_8_3_NAMES\n  \"ENABLE_8_3_NAMES=\" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),\n#endif\n#if SQLITE_ENABLE_API_ARMOR\n  \"ENABLE_API_ARMOR\",\n#endif\n#if SQLITE_ENABLE_ATOMIC_WRITE\n  \"ENABLE_ATOMIC_WRITE\",\n#endif\n#if SQLITE_ENABLE_BATCH_ATOMIC_WRITE\n  \"ENABLE_BATCH_ATOMIC_WRITE\",\n#endif\n#if SQLITE_ENABLE_BYTECODE_VTAB\n  \"ENABLE_BYTECODE_VTAB\",\n#endif\n#if SQLITE_ENABLE_CEROD\n  \"ENABLE_CEROD=\" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD),\n#endif\n#if SQLITE_ENABLE_COLUMN_METADATA\n  \"ENABLE_COLUMN_METADATA\",\n#endif\n#if SQLITE_ENABLE_COLUMN_USED_MASK\n  \"ENABLE_COLUMN_USED_MASK\",\n#endif\n#if SQLITE_ENABLE_COSTMULT\n  \"ENABLE_COSTMULT\",\n#endif\n#if SQLITE_ENABLE_CURSOR_HINTS\n  \"ENABLE_CURSOR_HINTS\",\n#endif\n#if SQLITE_ENABLE_DBSTAT_VTAB\n  \"ENABLE_DBSTAT_VTAB\",\n#endif\n#if SQLITE_ENABLE_EXPENSIVE_ASSERT\n  \"ENABLE_EXPENSIVE_ASSERT\",\n#endif\n#if SQLITE_ENABLE_FTS1\n  \"ENABLE_FTS1\",\n#endif\n#if SQLITE_ENABLE_FTS2\n  \"ENABLE_FTS2\",\n#endif\n#if SQLITE_ENABLE_FTS3\n  \"ENABLE_FTS3\",\n#endif\n#if SQLITE_ENABLE_FTS3_PARENTHESIS\n  \"ENABLE_FTS3_PARENTHESIS\",\n#endif\n#if SQLITE_ENABLE_FTS3_TOKENIZER\n  \"ENABLE_FTS3_TOKENIZER\",\n#endif\n#if SQLITE_ENABLE_FTS4\n  \"ENABLE_FTS4\",\n#endif\n#if SQLITE_ENABLE_FTS5\n  \"ENABLE_FTS5\",\n#endif\n#if SQLITE_ENABLE_GEOPOLY\n  \"ENABLE_GEOPOLY\",\n#endif\n#if SQLITE_ENABLE_HIDDEN_COLUMNS\n  \"ENABLE_HIDDEN_COLUMNS\",\n#endif\n#if SQLITE_ENABLE_ICU\n  \"ENABLE_ICU\",\n#endif\n#if SQLITE_ENABLE_IOTRACE\n  \"ENABLE_IOTRACE\",\n#endif\n#if SQLITE_ENABLE_JSON1\n  \"ENABLE_JSON1\",\n#endif\n#if SQLITE_ENABLE_LOAD_EXTENSION\n  \"ENABLE_LOAD_EXTENSION\",\n#endif\n#ifdef SQLITE_ENABLE_LOCKING_STYLE\n  \"ENABLE_LOCKING_STYLE=\" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),\n#endif\n#if SQLITE_ENABLE_MEMORY_MANAGEMENT\n  \"ENABLE_MEMORY_MANAGEMENT\",\n#endif\n#if SQLITE_ENABLE_MEMSYS3\n  \"ENABLE_MEMSYS3\",\n#endif\n#if SQLITE_ENABLE_MEMSYS5\n  \"ENABLE_MEMSYS5\",\n#endif\n#if SQLITE_ENABLE_MULTIPLEX\n  \"ENABLE_MULTIPLEX\",\n#endif\n#if SQLITE_ENABLE_NORMALIZE\n  \"ENABLE_NORMALIZE\",\n#endif\n#if SQLITE_ENABLE_NULL_TRIM\n  \"ENABLE_NULL_TRIM\",\n#endif\n#if SQLITE_ENABLE_OVERSIZE_CELL_CHECK\n  \"ENABLE_OVERSIZE_CELL_CHECK\",\n#endif\n#if SQLITE_ENABLE_PREUPDATE_HOOK\n  \"ENABLE_PREUPDATE_HOOK\",\n#endif\n#if SQLITE_ENABLE_QPSG\n  \"ENABLE_QPSG\",\n#endif\n#if SQLITE_ENABLE_RBU\n  \"ENABLE_RBU\",\n#endif\n#if SQLITE_ENABLE_RTREE\n  \"ENABLE_RTREE\",\n#endif\n#if SQLITE_ENABLE_SELECTTRACE\n  \"ENABLE_SELECTTRACE\",\n#endif\n#if SQLITE_ENABLE_SESSION\n  \"ENABLE_SESSION\",\n#endif\n#if SQLITE_ENABLE_SNAPSHOT\n  \"ENABLE_SNAPSHOT\",\n#endif\n#if SQLITE_ENABLE_SORTER_REFERENCES\n  \"ENABLE_SORTER_REFERENCES\",\n#endif\n#if SQLITE_ENABLE_SQLLOG\n  \"ENABLE_SQLLOG\",\n#endif\n#if defined(SQLITE_ENABLE_STAT4)\n  \"ENABLE_STAT4\",\n#endif\n#if SQLITE_ENABLE_STMTVTAB\n  \"ENABLE_STMTVTAB\",\n#endif\n#if SQLITE_ENABLE_STMT_SCANSTATUS\n  \"ENABLE_STMT_SCANSTATUS\",\n#endif\n#if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION\n  \"ENABLE_UNKNOWN_SQL_FUNCTION\",\n#endif\n#if SQLITE_ENABLE_UNLOCK_NOTIFY\n  \"ENABLE_UNLOCK_NOTIFY\",\n#endif\n#if SQLITE_ENABLE_UPDATE_DELETE_LIMIT\n  \"ENABLE_UPDATE_DELETE_LIMIT\",\n#endif\n#if SQLITE_ENABLE_URI_00_ERROR\n  \"ENABLE_URI_00_ERROR\",\n#endif\n#if SQLITE_ENABLE_VFSTRACE\n  \"ENABLE_VFSTRACE\",\n#endif\n#if SQLITE_ENABLE_WHERETRACE\n  \"ENABLE_WHERETRACE\",\n#endif\n#if SQLITE_ENABLE_ZIPVFS\n  \"ENABLE_ZIPVFS\",\n#endif\n#if SQLITE_EXPLAIN_ESTIMATED_ROWS\n  \"EXPLAIN_ESTIMATED_ROWS\",\n#endif\n#if SQLITE_EXTRA_IFNULLROW\n  \"EXTRA_IFNULLROW\",\n#endif\n#ifdef SQLITE_EXTRA_INIT\n  \"EXTRA_INIT=\" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),\n#endif\n#ifdef SQLITE_EXTRA_SHUTDOWN\n  \"EXTRA_SHUTDOWN=\" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),\n#endif\n#ifdef SQLITE_FTS3_MAX_EXPR_DEPTH\n  \"FTS3_MAX_EXPR_DEPTH=\" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),\n#endif\n#if SQLITE_FTS5_ENABLE_TEST_MI\n  \"FTS5_ENABLE_TEST_MI\",\n#endif\n#if SQLITE_FTS5_NO_WITHOUT_ROWID\n  \"FTS5_NO_WITHOUT_ROWID\",\n#endif\n#if HAVE_ISNAN || SQLITE_HAVE_ISNAN\n  \"HAVE_ISNAN\",\n#endif\n#if SQLITE_HOMEGROWN_RECURSIVE_MUTEX\n  \"HOMEGROWN_RECURSIVE_MUTEX\",\n#endif\n#if SQLITE_IGNORE_AFP_LOCK_ERRORS\n  \"IGNORE_AFP_LOCK_ERRORS\",\n#endif\n#if SQLITE_IGNORE_FLOCK_LOCK_ERRORS\n  \"IGNORE_FLOCK_LOCK_ERRORS\",\n#endif\n#if SQLITE_INLINE_MEMCPY\n  \"INLINE_MEMCPY\",\n#endif\n#if SQLITE_INT64_TYPE\n  \"INT64_TYPE\",\n#endif\n#ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX\n  \"INTEGRITY_CHECK_ERROR_MAX=\" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),\n#endif\n#if SQLITE_LIKE_DOESNT_MATCH_BLOBS\n  \"LIKE_DOESNT_MATCH_BLOBS\",\n#endif\n#if SQLITE_LOCK_TRACE\n  \"LOCK_TRACE\",\n#endif\n#if SQLITE_LOG_CACHE_SPILL\n  \"LOG_CACHE_SPILL\",\n#endif\n#ifdef SQLITE_MALLOC_SOFT_LIMIT\n  \"MALLOC_SOFT_LIMIT=\" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),\n#endif\n#ifdef SQLITE_MAX_ATTACHED\n  \"MAX_ATTACHED=\" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),\n#endif\n#ifdef SQLITE_MAX_COLUMN\n  \"MAX_COLUMN=\" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),\n#endif\n#ifdef SQLITE_MAX_COMPOUND_SELECT\n  \"MAX_COMPOUND_SELECT=\" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),\n#endif\n#ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE\n  \"MAX_DEFAULT_PAGE_SIZE=\" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),\n#endif\n#ifdef SQLITE_MAX_EXPR_DEPTH\n  \"MAX_EXPR_DEPTH=\" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),\n#endif\n#ifdef SQLITE_MAX_FUNCTION_ARG\n  \"MAX_FUNCTION_ARG=\" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),\n#endif\n#ifdef SQLITE_MAX_LENGTH\n  \"MAX_LENGTH=\" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),\n#endif\n#ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH\n  \"MAX_LIKE_PATTERN_LENGTH=\" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),\n#endif\n#ifdef SQLITE_MAX_MEMORY\n  \"MAX_MEMORY=\" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),\n#endif\n#ifdef SQLITE_MAX_MMAP_SIZE\n  \"MAX_MMAP_SIZE=\" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),\n#endif\n#ifdef SQLITE_MAX_MMAP_SIZE_\n  \"MAX_MMAP_SIZE_=\" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),\n#endif\n#ifdef SQLITE_MAX_PAGE_COUNT\n  \"MAX_PAGE_COUNT=\" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),\n#endif\n#ifdef SQLITE_MAX_PAGE_SIZE\n  \"MAX_PAGE_SIZE=\" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),\n#endif\n#ifdef SQLITE_MAX_SCHEMA_RETRY\n  \"MAX_SCHEMA_RETRY=\" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),\n#endif\n#ifdef SQLITE_MAX_SQL_LENGTH\n  \"MAX_SQL_LENGTH=\" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),\n#endif\n#ifdef SQLITE_MAX_TRIGGER_DEPTH\n  \"MAX_TRIGGER_DEPTH=\" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),\n#endif\n#ifdef SQLITE_MAX_VARIABLE_NUMBER\n  \"MAX_VARIABLE_NUMBER=\" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),\n#endif\n#ifdef SQLITE_MAX_VDBE_OP\n  \"MAX_VDBE_OP=\" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),\n#endif\n#ifdef SQLITE_MAX_WORKER_THREADS\n  \"MAX_WORKER_THREADS=\" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),\n#endif\n#if SQLITE_MEMDEBUG\n  \"MEMDEBUG\",\n#endif\n#if SQLITE_MIXED_ENDIAN_64BIT_FLOAT\n  \"MIXED_ENDIAN_64BIT_FLOAT\",\n#endif\n#if SQLITE_MMAP_READWRITE\n  \"MMAP_READWRITE\",\n#endif\n#if SQLITE_MUTEX_NOOP\n  \"MUTEX_NOOP\",\n#endif\n#if SQLITE_MUTEX_NREF\n  \"MUTEX_NREF\",\n#endif\n#if SQLITE_MUTEX_OMIT\n  \"MUTEX_OMIT\",\n#endif\n#if SQLITE_MUTEX_PTHREADS\n  \"MUTEX_PTHREADS\",\n#endif\n#if SQLITE_MUTEX_W32\n  \"MUTEX_W32\",\n#endif\n#if SQLITE_NEED_ERR_NAME\n  \"NEED_ERR_NAME\",\n#endif\n#if SQLITE_NOINLINE\n  \"NOINLINE\",\n#endif\n#if SQLITE_NO_SYNC\n  \"NO_SYNC\",\n#endif\n#if SQLITE_OMIT_ALTERTABLE\n  \"OMIT_ALTERTABLE\",\n#endif\n#if SQLITE_OMIT_ANALYZE\n  \"OMIT_ANALYZE\",\n#endif\n#if SQLITE_OMIT_ATTACH\n  \"OMIT_ATTACH\",\n#endif\n#if SQLITE_OMIT_AUTHORIZATION\n  \"OMIT_AUTHORIZATION\",\n#endif\n#if SQLITE_OMIT_AUTOINCREMENT\n  \"OMIT_AUTOINCREMENT\",\n#endif\n#if SQLITE_OMIT_AUTOINIT\n  \"OMIT_AUTOINIT\",\n#endif\n#if SQLITE_OMIT_AUTOMATIC_INDEX\n  \"OMIT_AUTOMATIC_INDEX\",\n#endif\n#if SQLITE_OMIT_AUTORESET\n  \"OMIT_AUTORESET\",\n#endif\n#if SQLITE_OMIT_AUTOVACUUM\n  \"OMIT_AUTOVACUUM\",\n#endif\n#if SQLITE_OMIT_BETWEEN_OPTIMIZATION\n  \"OMIT_BETWEEN_OPTIMIZATION\",\n#endif\n#if SQLITE_OMIT_BLOB_LITERAL\n  \"OMIT_BLOB_LITERAL\",\n#endif\n#if SQLITE_OMIT_CAST\n  \"OMIT_CAST\",\n#endif\n#if SQLITE_OMIT_CHECK\n  \"OMIT_CHECK\",\n#endif\n#if SQLITE_OMIT_COMPLETE\n  \"OMIT_COMPLETE\",\n#endif\n#if SQLITE_OMIT_COMPOUND_SELECT\n  \"OMIT_COMPOUND_SELECT\",\n#endif\n#if SQLITE_OMIT_CONFLICT_CLAUSE\n  \"OMIT_CONFLICT_CLAUSE\",\n#endif\n#if SQLITE_OMIT_CTE\n  \"OMIT_CTE\",\n#endif\n#if SQLITE_OMIT_DATETIME_FUNCS\n  \"OMIT_DATETIME_FUNCS\",\n#endif\n#if SQLITE_OMIT_DECLTYPE\n  \"OMIT_DECLTYPE\",\n#endif\n#if SQLITE_OMIT_DEPRECATED\n  \"OMIT_DEPRECATED\",\n#endif\n#if SQLITE_OMIT_DISKIO\n  \"OMIT_DISKIO\",\n#endif\n#if SQLITE_OMIT_EXPLAIN\n  \"OMIT_EXPLAIN\",\n#endif\n#if SQLITE_OMIT_FLAG_PRAGMAS\n  \"OMIT_FLAG_PRAGMAS\",\n#endif\n#if SQLITE_OMIT_FLOATING_POINT\n  \"OMIT_FLOATING_POINT\",\n#endif\n#if SQLITE_OMIT_FOREIGN_KEY\n  \"OMIT_FOREIGN_KEY\",\n#endif\n#if SQLITE_OMIT_GET_TABLE\n  \"OMIT_GET_TABLE\",\n#endif\n#if SQLITE_OMIT_HEX_INTEGER\n  \"OMIT_HEX_INTEGER\",\n#endif\n#if SQLITE_OMIT_INCRBLOB\n  \"OMIT_INCRBLOB\",\n#endif\n#if SQLITE_OMIT_INTEGRITY_CHECK\n  \"OMIT_INTEGRITY_CHECK\",\n#endif\n#if SQLITE_OMIT_LIKE_OPTIMIZATION\n  \"OMIT_LIKE_OPTIMIZATION\",\n#endif\n#if SQLITE_OMIT_LOAD_EXTENSION\n  \"OMIT_LOAD_EXTENSION\",\n#endif\n#if SQLITE_OMIT_LOCALTIME\n  \"OMIT_LOCALTIME\",\n#endif\n#if SQLITE_OMIT_LOOKASIDE\n  \"OMIT_LOOKASIDE\",\n#endif\n#if SQLITE_OMIT_MEMORYDB\n  \"OMIT_MEMORYDB\",\n#endif\n#if SQLITE_OMIT_OR_OPTIMIZATION\n  \"OMIT_OR_OPTIMIZATION\",\n#endif\n#if SQLITE_OMIT_PAGER_PRAGMAS\n  \"OMIT_PAGER_PRAGMAS\",\n#endif\n#if SQLITE_OMIT_PARSER_TRACE\n  \"OMIT_PARSER_TRACE\",\n#endif\n#if SQLITE_OMIT_POPEN\n  \"OMIT_POPEN\",\n#endif\n#if SQLITE_OMIT_PRAGMA\n  \"OMIT_PRAGMA\",\n#endif\n#if SQLITE_OMIT_PROGRESS_CALLBACK\n  \"OMIT_PROGRESS_CALLBACK\",\n#endif\n#if SQLITE_OMIT_QUICKBALANCE\n  \"OMIT_QUICKBALANCE\",\n#endif\n#if SQLITE_OMIT_REINDEX\n  \"OMIT_REINDEX\",\n#endif\n#if SQLITE_OMIT_SCHEMA_PRAGMAS\n  \"OMIT_SCHEMA_PRAGMAS\",\n#endif\n#if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS\n  \"OMIT_SCHEMA_VERSION_PRAGMAS\",\n#endif\n#if SQLITE_OMIT_SHARED_CACHE\n  \"OMIT_SHARED_CACHE\",\n#endif\n#if SQLITE_OMIT_SHUTDOWN_DIRECTORIES\n  \"OMIT_SHUTDOWN_DIRECTORIES\",\n#endif\n#if SQLITE_OMIT_SUBQUERY\n  \"OMIT_SUBQUERY\",\n#endif\n#if SQLITE_OMIT_TCL_VARIABLE\n  \"OMIT_TCL_VARIABLE\",\n#endif\n#if SQLITE_OMIT_TEMPDB\n  \"OMIT_TEMPDB\",\n#endif\n#if SQLITE_OMIT_TEST_CONTROL\n  \"OMIT_TEST_CONTROL\",\n#endif\n#if SQLITE_OMIT_TRACE\n  \"OMIT_TRACE\",\n#endif\n#if SQLITE_OMIT_TRIGGER\n  \"OMIT_TRIGGER\",\n#endif\n#if SQLITE_OMIT_TRUNCATE_OPTIMIZATION\n  \"OMIT_TRUNCATE_OPTIMIZATION\",\n#endif\n#if SQLITE_OMIT_UTF16\n  \"OMIT_UTF16\",\n#endif\n#if SQLITE_OMIT_VACUUM\n  \"OMIT_VACUUM\",\n#endif\n#if SQLITE_OMIT_VIEW\n  \"OMIT_VIEW\",\n#endif\n#if SQLITE_OMIT_VIRTUALTABLE\n  \"OMIT_VIRTUALTABLE\",\n#endif\n#if SQLITE_OMIT_WAL\n  \"OMIT_WAL\",\n#endif\n#if SQLITE_OMIT_WSD\n  \"OMIT_WSD\",\n#endif\n#if SQLITE_OMIT_XFER_OPT\n  \"OMIT_XFER_OPT\",\n#endif\n#if SQLITE_PCACHE_SEPARATE_HEADER\n  \"PCACHE_SEPARATE_HEADER\",\n#endif\n#if SQLITE_PERFORMANCE_TRACE\n  \"PERFORMANCE_TRACE\",\n#endif\n#if SQLITE_POWERSAFE_OVERWRITE\n  \"POWERSAFE_OVERWRITE\",\n#endif\n#if SQLITE_PREFER_PROXY_LOCKING\n  \"PREFER_PROXY_LOCKING\",\n#endif\n#if SQLITE_PROXY_DEBUG\n  \"PROXY_DEBUG\",\n#endif\n#if SQLITE_REVERSE_UNORDERED_SELECTS\n  \"REVERSE_UNORDERED_SELECTS\",\n#endif\n#if SQLITE_RTREE_INT_ONLY\n  \"RTREE_INT_ONLY\",\n#endif\n#if SQLITE_SECURE_DELETE\n  \"SECURE_DELETE\",\n#endif\n#if SQLITE_SMALL_STACK\n  \"SMALL_STACK\",\n#endif\n#ifdef SQLITE_SORTER_PMASZ\n  \"SORTER_PMASZ=\" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),\n#endif\n#if SQLITE_SOUNDEX\n  \"SOUNDEX\",\n#endif\n#ifdef SQLITE_STAT4_SAMPLES\n  \"STAT4_SAMPLES=\" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),\n#endif\n#ifdef SQLITE_STMTJRNL_SPILL\n  \"STMTJRNL_SPILL=\" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),\n#endif\n#if SQLITE_SUBSTR_COMPATIBILITY\n  \"SUBSTR_COMPATIBILITY\",\n#endif\n#if SQLITE_SYSTEM_MALLOC\n  \"SYSTEM_MALLOC\",\n#endif\n#if SQLITE_TCL\n  \"TCL\",\n#endif\n#ifdef SQLITE_TEMP_STORE\n  \"TEMP_STORE=\" CTIMEOPT_VAL(SQLITE_TEMP_STORE),\n#endif\n#if SQLITE_TEST\n  \"TEST\",\n#endif\n#if defined(SQLITE_THREADSAFE)\n  \"THREADSAFE=\" CTIMEOPT_VAL(SQLITE_THREADSAFE),\n#elif defined(THREADSAFE)\n  \"THREADSAFE=\" CTIMEOPT_VAL(THREADSAFE),\n#else\n  \"THREADSAFE=1\",\n#endif\n#if SQLITE_UNLINK_AFTER_CLOSE\n  \"UNLINK_AFTER_CLOSE\",\n#endif\n#if SQLITE_UNTESTABLE\n  \"UNTESTABLE\",\n#endif\n#if SQLITE_USER_AUTHENTICATION\n  \"USER_AUTHENTICATION\",\n#endif\n#if SQLITE_USE_ALLOCA\n  \"USE_ALLOCA\",\n#endif\n#if SQLITE_USE_FCNTL_TRACE\n  \"USE_FCNTL_TRACE\",\n#endif\n#if SQLITE_USE_URI\n  \"USE_URI\",\n#endif\n#if SQLITE_VDBE_COVERAGE\n  \"VDBE_COVERAGE\",\n#endif\n#if SQLITE_WIN32_MALLOC\n  \"WIN32_MALLOC\",\n#endif\n#if SQLITE_ZERO_MALLOC\n  \"ZERO_MALLOC\",\n#endif\n/* \n** END CODE GENERATED BY tool/mkctime.tcl \n*/\n};\n\nSQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){\n  *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);\n  return (const char**)sqlite3azCompileOpt;\n}\n\n#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */\n\n/************** End of ctime.c ***********************************************/\n/************** Begin file sqliteInt.h ***************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** Internal interface definitions for SQLite.\n**\n*/\n#ifndef SQLITEINT_H\n#define SQLITEINT_H\n\n/* Special Comments:\n**\n** Some comments have special meaning to the tools that measure test\n** coverage:\n**\n**    NO_TEST                     - The branches on this line are not\n**                                  measured by branch coverage.  This is\n**                                  used on lines of code that actually\n**                                  implement parts of coverage testing.\n**\n**    OPTIMIZATION-IF-TRUE        - This branch is allowed to alway be false\n**                                  and the correct answer is still obtained,\n**                                  though perhaps more slowly.\n**\n**    OPTIMIZATION-IF-FALSE       - This branch is allowed to alway be true\n**                                  and the correct answer is still obtained,\n**                                  though perhaps more slowly.\n**\n**    PREVENTS-HARMLESS-OVERREAD  - This branch prevents a buffer overread\n**                                  that would be harmless and undetectable\n**                                  if it did occur.  \n**\n** In all cases, the special comment must be enclosed in the usual\n** slash-asterisk...asterisk-slash comment marks, with no spaces between the \n** asterisks and the comment text.\n*/\n\n/*\n** Make sure the Tcl calling convention macro is defined.  This macro is\n** only used by test code and Tcl integration code.\n*/\n#ifndef SQLITE_TCLAPI\n#  define SQLITE_TCLAPI\n#endif\n\n/*\n** Include the header file used to customize the compiler options for MSVC.\n** This should be done first so that it can successfully prevent spurious\n** compiler warnings due to subsequent content in this file and other files\n** that are included by this file.\n*/\n/************** Include msvc.h in the middle of sqliteInt.h ******************/\n/************** Begin file msvc.h ********************************************/\n/*\n** 2015 January 12\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains code that is specific to MSVC.\n*/\n#ifndef SQLITE_MSVC_H\n#define SQLITE_MSVC_H\n\n#if defined(_MSC_VER)\n#pragma warning(disable : 4054)\n#pragma warning(disable : 4055)\n#pragma warning(disable : 4100)\n#pragma warning(disable : 4127)\n#pragma warning(disable : 4130)\n#pragma warning(disable : 4152)\n#pragma warning(disable : 4189)\n#pragma warning(disable : 4206)\n#pragma warning(disable : 4210)\n#pragma warning(disable : 4232)\n#pragma warning(disable : 4244)\n#pragma warning(disable : 4305)\n#pragma warning(disable : 4306)\n#pragma warning(disable : 4702)\n#pragma warning(disable : 4706)\n#endif /* defined(_MSC_VER) */\n\n#if defined(_MSC_VER) && !defined(_WIN64)\n#undef SQLITE_4_BYTE_ALIGNED_MALLOC\n#define SQLITE_4_BYTE_ALIGNED_MALLOC\n#endif /* defined(_MSC_VER) && !defined(_WIN64) */\n\n#endif /* SQLITE_MSVC_H */\n\n/************** End of msvc.h ************************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n\n/*\n** Special setup for VxWorks\n*/\n/************** Include vxworks.h in the middle of sqliteInt.h ***************/\n/************** Begin file vxworks.h *****************************************/\n/*\n** 2015-03-02\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains code that is specific to Wind River's VxWorks\n*/\n#if defined(__RTP__) || defined(_WRS_KERNEL)\n/* This is VxWorks.  Set up things specially for that OS\n*/\n#include <vxWorks.h>\n#include <pthread.h>  /* amalgamator: dontcache */\n#define OS_VXWORKS 1\n#define SQLITE_OS_OTHER 0\n#define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1\n#define SQLITE_OMIT_LOAD_EXTENSION 1\n#define SQLITE_ENABLE_LOCKING_STYLE 0\n#define HAVE_UTIME 1\n#else\n/* This is not VxWorks. */\n#define OS_VXWORKS 0\n#define HAVE_FCHOWN 1\n#define HAVE_READLINK 1\n#define HAVE_LSTAT 1\n#endif /* defined(_WRS_KERNEL) */\n\n/************** End of vxworks.h *********************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n\n/*\n** These #defines should enable >2GB file support on POSIX if the\n** underlying operating system supports it.  If the OS lacks\n** large file support, or if the OS is windows, these should be no-ops.\n**\n** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any\n** system #includes.  Hence, this block of code must be the very first\n** code in all source files.\n**\n** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch\n** on the compiler command line.  This is necessary if you are compiling\n** on a recent machine (ex: Red Hat 7.2) but you want your code to work\n** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2\n** without this option, LFS is enable.  But LFS does not exist in the kernel\n** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary\n** portability you should omit LFS.\n**\n** The previous paragraph was written in 2005.  (This paragraph is written\n** on 2008-11-28.) These days, all Linux kernels support large files, so\n** you should probably leave LFS enabled.  But some embedded platforms might\n** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.\n**\n** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.\n*/\n#ifndef SQLITE_DISABLE_LFS\n# define _LARGE_FILE       1\n# ifndef _FILE_OFFSET_BITS\n#   define _FILE_OFFSET_BITS 64\n# endif\n# define _LARGEFILE_SOURCE 1\n#endif\n\n/* The GCC_VERSION and MSVC_VERSION macros are used to\n** conditionally include optimizations for each of these compilers.  A\n** value of 0 means that compiler is not being used.  The\n** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific\n** optimizations, and hence set all compiler macros to 0\n**\n** There was once also a CLANG_VERSION macro.  However, we learn that the\n** version numbers in clang are for \"marketing\" only and are inconsistent\n** and unreliable.  Fortunately, all versions of clang also recognize the\n** gcc version numbers and have reasonable settings for gcc version numbers,\n** so the GCC_VERSION macro will be set to a correct non-zero value even\n** when compiling with clang.\n*/\n#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)\n# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)\n#else\n# define GCC_VERSION 0\n#endif\n#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)\n# define MSVC_VERSION _MSC_VER\n#else\n# define MSVC_VERSION 0\n#endif\n\n/* Needed for various definitions... */\n#if defined(__GNUC__) && !defined(_GNU_SOURCE)\n# define _GNU_SOURCE\n#endif\n\n#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)\n# define _BSD_SOURCE\n#endif\n\n/*\n** For MinGW, check to see if we can include the header file containing its\n** version information, among other things.  Normally, this internal MinGW\n** header file would [only] be included automatically by other MinGW header\n** files; however, the contained version information is now required by this\n** header file to work around binary compatibility issues (see below) and\n** this is the only known way to reliably obtain it.  This entire #if block\n** would be completely unnecessary if there was any other way of detecting\n** MinGW via their preprocessor (e.g. if they customized their GCC to define\n** some MinGW-specific macros).  When compiling for MinGW, either the\n** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be\n** defined; otherwise, detection of conditions specific to MinGW will be\n** disabled.\n*/\n#if defined(_HAVE_MINGW_H)\n# include \"mingw.h\"\n#elif defined(_HAVE__MINGW_H)\n# include \"_mingw.h\"\n#endif\n\n/*\n** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T\n** define is required to maintain binary compatibility with the MSVC runtime\n** library in use (e.g. for Windows XP).\n*/\n#if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \\\n    defined(_WIN32) && !defined(_WIN64) && \\\n    defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \\\n    defined(__MSVCRT__)\n# define _USE_32BIT_TIME_T\n#endif\n\n/* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear\n** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for\n** MinGW.\n*/\n/************** Include sqlite3.h in the middle of sqliteInt.h ***************/\n/************** Begin file sqlite3.h *****************************************/\n/*\n** 2001-09-15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This header file defines the interface that the SQLite library\n** presents to client programs.  If a C-function, structure, datatype,\n** or constant definition does not appear in this file, then it is\n** not a published API of SQLite, is subject to change without\n** notice, and should not be referenced by programs that use SQLite.\n**\n** Some of the definitions that are in this file are marked as\n** \"experimental\".  Experimental interfaces are normally new\n** features recently added to SQLite.  We do not anticipate changes\n** to experimental interfaces but reserve the right to make minor changes\n** if experience from use \"in the wild\" suggest such changes are prudent.\n**\n** The official C-language API documentation for SQLite is derived\n** from comments in this file.  This file is the authoritative source\n** on how SQLite interfaces are supposed to operate.\n**\n** The name of this file under configuration management is \"sqlite.h.in\".\n** The makefile makes some minor changes to this file (such as inserting\n** the version number) and changes its name to \"sqlite3.h\" as\n** part of the build process.\n*/\n#ifndef SQLITE3_H\n#define SQLITE3_H\n#include <stdarg.h>     /* Needed for the definition of va_list */\n\n/*\n** Make sure we can call this stuff from C++.\n*/\n#if 0\nextern \"C\" {\n#endif\n\n\n/*\n** Provide the ability to override linkage features of the interface.\n*/\n#ifndef SQLITE_EXTERN\n# define SQLITE_EXTERN extern\n#endif\n#ifndef SQLITE_API\n# define SQLITE_API\n#endif\n#ifndef SQLITE_CDECL\n# define SQLITE_CDECL\n#endif\n#ifndef SQLITE_APICALL\n# define SQLITE_APICALL\n#endif\n#ifndef SQLITE_STDCALL\n# define SQLITE_STDCALL SQLITE_APICALL\n#endif\n#ifndef SQLITE_CALLBACK\n# define SQLITE_CALLBACK\n#endif\n#ifndef SQLITE_SYSAPI\n# define SQLITE_SYSAPI\n#endif\n\n/*\n** These no-op macros are used in front of interfaces to mark those\n** interfaces as either deprecated or experimental.  New applications\n** should not use deprecated interfaces - they are supported for backwards\n** compatibility only.  Application writers should be aware that\n** experimental interfaces are subject to change in point releases.\n**\n** These macros used to resolve to various kinds of compiler magic that\n** would generate warning messages when they were used.  But that\n** compiler magic ended up generating such a flurry of bug reports\n** that we have taken it all out and gone back to using simple\n** noop macros.\n*/\n#define SQLITE_DEPRECATED\n#define SQLITE_EXPERIMENTAL\n\n/*\n** Ensure these symbols were not defined by some previous header file.\n*/\n#ifdef SQLITE_VERSION\n# undef SQLITE_VERSION\n#endif\n#ifdef SQLITE_VERSION_NUMBER\n# undef SQLITE_VERSION_NUMBER\n#endif\n\n/*\n** CAPI3REF: Compile-Time Library Version Numbers\n**\n** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header\n** evaluates to a string literal that is the SQLite version in the\n** format \"X.Y.Z\" where X is the major version number (always 3 for\n** SQLite3) and Y is the minor version number and Z is the release number.)^\n** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer\n** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same\n** numbers used in [SQLITE_VERSION].)^\n** The SQLITE_VERSION_NUMBER for any given release of SQLite will also\n** be larger than the release from which it is derived.  Either Y will\n** be held constant and Z will be incremented or else Y will be incremented\n** and Z will be reset to zero.\n**\n** Since [version 3.6.18] ([dateof:3.6.18]), \n** SQLite source code has been stored in the\n** <a href=\"http://www.fossil-scm.org/\">Fossil configuration management\n** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to\n** a string which identifies a particular check-in of SQLite\n** within its configuration management system.  ^The SQLITE_SOURCE_ID\n** string contains the date and time of the check-in (UTC) and a SHA1\n** or SHA3-256 hash of the entire source tree.  If the source code has\n** been edited in any way since it was last checked in, then the last\n** four hexadecimal digits of the hash may be modified.\n**\n** See also: [sqlite3_libversion()],\n** [sqlite3_libversion_number()], [sqlite3_sourceid()],\n** [sqlite_version()] and [sqlite_source_id()].\n*/\n#define SQLITE_VERSION        \"3.32.3\"\n#define SQLITE_VERSION_NUMBER 3032003\n#define SQLITE_SOURCE_ID      \"2020-06-18 14:00:33 7ebdfa80be8e8e73324b8d66b3460222eb74c7e9dfd655b48d6ca7e1933cc8fd\"\n\n/*\n** CAPI3REF: Run-Time Library Version Numbers\n** KEYWORDS: sqlite3_version sqlite3_sourceid\n**\n** These interfaces provide the same information as the [SQLITE_VERSION],\n** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros\n** but are associated with the library instead of the header file.  ^(Cautious\n** programmers might include assert() statements in their application to\n** verify that values returned by these interfaces match the macros in\n** the header, and thus ensure that the application is\n** compiled with matching library and header files.\n**\n** <blockquote><pre>\n** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );\n** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );\n** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );\n** </pre></blockquote>)^\n**\n** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]\n** macro.  ^The sqlite3_libversion() function returns a pointer to the\n** to the sqlite3_version[] string constant.  The sqlite3_libversion()\n** function is provided for use in DLLs since DLL users usually do not have\n** direct access to string constants within the DLL.  ^The\n** sqlite3_libversion_number() function returns an integer equal to\n** [SQLITE_VERSION_NUMBER].  ^(The sqlite3_sourceid() function returns \n** a pointer to a string constant whose value is the same as the \n** [SQLITE_SOURCE_ID] C preprocessor macro.  Except if SQLite is built\n** using an edited copy of [the amalgamation], then the last four characters\n** of the hash might be different from [SQLITE_SOURCE_ID].)^\n**\n** See also: [sqlite_version()] and [sqlite_source_id()].\n*/\nSQLITE_API const char sqlite3_version[] = SQLITE_VERSION;\nSQLITE_API const char *sqlite3_libversion(void);\nSQLITE_API const char *sqlite3_sourceid(void);\nSQLITE_API int sqlite3_libversion_number(void);\n\n/*\n** CAPI3REF: Run-Time Library Compilation Options Diagnostics\n**\n** ^The sqlite3_compileoption_used() function returns 0 or 1 \n** indicating whether the specified option was defined at \n** compile time.  ^The SQLITE_ prefix may be omitted from the \n** option name passed to sqlite3_compileoption_used().  \n**\n** ^The sqlite3_compileoption_get() function allows iterating\n** over the list of options that were defined at compile time by\n** returning the N-th compile time option string.  ^If N is out of range,\n** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ \n** prefix is omitted from any strings returned by \n** sqlite3_compileoption_get().\n**\n** ^Support for the diagnostic functions sqlite3_compileoption_used()\n** and sqlite3_compileoption_get() may be omitted by specifying the \n** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.\n**\n** See also: SQL functions [sqlite_compileoption_used()] and\n** [sqlite_compileoption_get()] and the [compile_options pragma].\n*/\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\nSQLITE_API int sqlite3_compileoption_used(const char *zOptName);\nSQLITE_API const char *sqlite3_compileoption_get(int N);\n#else\n# define sqlite3_compileoption_used(X) 0\n# define sqlite3_compileoption_get(X)  ((void*)0)\n#endif\n\n/*\n** CAPI3REF: Test To See If The Library Is Threadsafe\n**\n** ^The sqlite3_threadsafe() function returns zero if and only if\n** SQLite was compiled with mutexing code omitted due to the\n** [SQLITE_THREADSAFE] compile-time option being set to 0.\n**\n** SQLite can be compiled with or without mutexes.  When\n** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes\n** are enabled and SQLite is threadsafe.  When the\n** [SQLITE_THREADSAFE] macro is 0, \n** the mutexes are omitted.  Without the mutexes, it is not safe\n** to use SQLite concurrently from more than one thread.\n**\n** Enabling mutexes incurs a measurable performance penalty.\n** So if speed is of utmost importance, it makes sense to disable\n** the mutexes.  But for maximum safety, mutexes should be enabled.\n** ^The default behavior is for mutexes to be enabled.\n**\n** This interface can be used by an application to make sure that the\n** version of SQLite that it is linking against was compiled with\n** the desired setting of the [SQLITE_THREADSAFE] macro.\n**\n** This interface only reports on the compile-time mutex setting\n** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with\n** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but\n** can be fully or partially disabled using a call to [sqlite3_config()]\n** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],\n** or [SQLITE_CONFIG_SERIALIZED].  ^(The return value of the\n** sqlite3_threadsafe() function shows only the compile-time setting of\n** thread safety, not any run-time changes to that setting made by\n** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()\n** is unchanged by calls to sqlite3_config().)^\n**\n** See the [threading mode] documentation for additional information.\n*/\nSQLITE_API int sqlite3_threadsafe(void);\n\n/*\n** CAPI3REF: Database Connection Handle\n** KEYWORDS: {database connection} {database connections}\n**\n** Each open SQLite database is represented by a pointer to an instance of\n** the opaque structure named \"sqlite3\".  It is useful to think of an sqlite3\n** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and\n** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]\n** and [sqlite3_close_v2()] are its destructors.  There are many other\n** interfaces (such as\n** [sqlite3_prepare_v2()], [sqlite3_create_function()], and\n** [sqlite3_busy_timeout()] to name but three) that are methods on an\n** sqlite3 object.\n*/\ntypedef struct sqlite3 sqlite3;\n\n/*\n** CAPI3REF: 64-Bit Integer Types\n** KEYWORDS: sqlite_int64 sqlite_uint64\n**\n** Because there is no cross-platform way to specify 64-bit integer types\n** SQLite includes typedefs for 64-bit signed and unsigned integers.\n**\n** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.\n** The sqlite_int64 and sqlite_uint64 types are supported for backwards\n** compatibility only.\n**\n** ^The sqlite3_int64 and sqlite_int64 types can store integer values\n** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The\n** sqlite3_uint64 and sqlite_uint64 types can store integer values \n** between 0 and +18446744073709551615 inclusive.\n*/\n#ifdef SQLITE_INT64_TYPE\n  typedef SQLITE_INT64_TYPE sqlite_int64;\n# ifdef SQLITE_UINT64_TYPE\n    typedef SQLITE_UINT64_TYPE sqlite_uint64;\n# else  \n    typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;\n# endif\n#elif defined(_MSC_VER) || defined(__BORLANDC__)\n  typedef __int64 sqlite_int64;\n  typedef unsigned __int64 sqlite_uint64;\n#else\n  typedef long long int sqlite_int64;\n  typedef unsigned long long int sqlite_uint64;\n#endif\ntypedef sqlite_int64 sqlite3_int64;\ntypedef sqlite_uint64 sqlite3_uint64;\n\n/*\n** If compiling for a processor that lacks floating point support,\n** substitute integer for floating-point.\n*/\n#ifdef SQLITE_OMIT_FLOATING_POINT\n# define double sqlite3_int64\n#endif\n\n/*\n** CAPI3REF: Closing A Database Connection\n** DESTRUCTOR: sqlite3\n**\n** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors\n** for the [sqlite3] object.\n** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if\n** the [sqlite3] object is successfully destroyed and all associated\n** resources are deallocated.\n**\n** Ideally, applications should [sqlite3_finalize | finalize] all\n** [prepared statements], [sqlite3_blob_close | close] all [BLOB handles], and \n** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated\n** with the [sqlite3] object prior to attempting to close the object.\n** ^If the database connection is associated with unfinalized prepared\n** statements, BLOB handlers, and/or unfinished sqlite3_backup objects then\n** sqlite3_close() will leave the database connection open and return\n** [SQLITE_BUSY]. ^If sqlite3_close_v2() is called with unfinalized prepared\n** statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups,\n** it returns [SQLITE_OK] regardless, but instead of deallocating the database\n** connection immediately, it marks the database connection as an unusable\n** \"zombie\" and makes arrangements to automatically deallocate the database\n** connection after all prepared statements are finalized, all BLOB handles\n** are closed, and all backups have finished. The sqlite3_close_v2() interface\n** is intended for use with host languages that are garbage collected, and\n** where the order in which destructors are called is arbitrary.\n**\n** ^If an [sqlite3] object is destroyed while a transaction is open,\n** the transaction is automatically rolled back.\n**\n** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]\n** must be either a NULL\n** pointer or an [sqlite3] object pointer obtained\n** from [sqlite3_open()], [sqlite3_open16()], or\n** [sqlite3_open_v2()], and not previously closed.\n** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer\n** argument is a harmless no-op.\n*/\nSQLITE_API int sqlite3_close(sqlite3*);\nSQLITE_API int sqlite3_close_v2(sqlite3*);\n\n/*\n** The type for a callback function.\n** This is legacy and deprecated.  It is included for historical\n** compatibility and is not documented.\n*/\ntypedef int (*sqlite3_callback)(void*,int,char**, char**);\n\n/*\n** CAPI3REF: One-Step Query Execution Interface\n** METHOD: sqlite3\n**\n** The sqlite3_exec() interface is a convenience wrapper around\n** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],\n** that allows an application to run multiple statements of SQL\n** without having to use a lot of C code. \n**\n** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,\n** semicolon-separate SQL statements passed into its 2nd argument,\n** in the context of the [database connection] passed in as its 1st\n** argument.  ^If the callback function of the 3rd argument to\n** sqlite3_exec() is not NULL, then it is invoked for each result row\n** coming out of the evaluated SQL statements.  ^The 4th argument to\n** sqlite3_exec() is relayed through to the 1st argument of each\n** callback invocation.  ^If the callback pointer to sqlite3_exec()\n** is NULL, then no callback is ever invoked and result rows are\n** ignored.\n**\n** ^If an error occurs while evaluating the SQL statements passed into\n** sqlite3_exec(), then execution of the current statement stops and\n** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()\n** is not NULL then any error message is written into memory obtained\n** from [sqlite3_malloc()] and passed back through the 5th parameter.\n** To avoid memory leaks, the application should invoke [sqlite3_free()]\n** on error message strings returned through the 5th parameter of\n** sqlite3_exec() after the error message string is no longer needed.\n** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors\n** occur, then sqlite3_exec() sets the pointer in its 5th parameter to\n** NULL before returning.\n**\n** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()\n** routine returns SQLITE_ABORT without invoking the callback again and\n** without running any subsequent SQL statements.\n**\n** ^The 2nd argument to the sqlite3_exec() callback function is the\n** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()\n** callback is an array of pointers to strings obtained as if from\n** [sqlite3_column_text()], one for each column.  ^If an element of a\n** result row is NULL then the corresponding string pointer for the\n** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the\n** sqlite3_exec() callback is an array of pointers to strings where each\n** entry represents the name of corresponding result column as obtained\n** from [sqlite3_column_name()].\n**\n** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer\n** to an empty string, or a pointer that contains only whitespace and/or \n** SQL comments, then no SQL statements are evaluated and the database\n** is not changed.\n**\n** Restrictions:\n**\n** <ul>\n** <li> The application must ensure that the 1st parameter to sqlite3_exec()\n**      is a valid and open [database connection].\n** <li> The application must not close the [database connection] specified by\n**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.\n** <li> The application must not modify the SQL statement text passed into\n**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.\n** </ul>\n*/\nSQLITE_API int sqlite3_exec(\n  sqlite3*,                                  /* An open database */\n  const char *sql,                           /* SQL to be evaluated */\n  int (*callback)(void*,int,char**,char**),  /* Callback function */\n  void *,                                    /* 1st argument to callback */\n  char **errmsg                              /* Error msg written here */\n);\n\n/*\n** CAPI3REF: Result Codes\n** KEYWORDS: {result code definitions}\n**\n** Many SQLite functions return an integer result code from the set shown\n** here in order to indicate success or failure.\n**\n** New error codes may be added in future versions of SQLite.\n**\n** See also: [extended result code definitions]\n*/\n#define SQLITE_OK           0   /* Successful result */\n/* beginning-of-error-codes */\n#define SQLITE_ERROR        1   /* Generic error */\n#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */\n#define SQLITE_PERM         3   /* Access permission denied */\n#define SQLITE_ABORT        4   /* Callback routine requested an abort */\n#define SQLITE_BUSY         5   /* The database file is locked */\n#define SQLITE_LOCKED       6   /* A table in the database is locked */\n#define SQLITE_NOMEM        7   /* A malloc() failed */\n#define SQLITE_READONLY     8   /* Attempt to write a readonly database */\n#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/\n#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */\n#define SQLITE_CORRUPT     11   /* The database disk image is malformed */\n#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */\n#define SQLITE_FULL        13   /* Insertion failed because database is full */\n#define SQLITE_CANTOPEN    14   /* Unable to open the database file */\n#define SQLITE_PROTOCOL    15   /* Database lock protocol error */\n#define SQLITE_EMPTY       16   /* Internal use only */\n#define SQLITE_SCHEMA      17   /* The database schema changed */\n#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */\n#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */\n#define SQLITE_MISMATCH    20   /* Data type mismatch */\n#define SQLITE_MISUSE      21   /* Library used incorrectly */\n#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */\n#define SQLITE_AUTH        23   /* Authorization denied */\n#define SQLITE_FORMAT      24   /* Not used */\n#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */\n#define SQLITE_NOTADB      26   /* File opened that is not a database file */\n#define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */\n#define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */\n#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */\n#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */\n/* end-of-error-codes */\n\n/*\n** CAPI3REF: Extended Result Codes\n** KEYWORDS: {extended result code definitions}\n**\n** In its default configuration, SQLite API routines return one of 30 integer\n** [result codes].  However, experience has shown that many of\n** these result codes are too coarse-grained.  They do not provide as\n** much information about problems as programmers might like.  In an effort to\n** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]\n** and later) include\n** support for additional result codes that provide more detailed information\n** about errors. These [extended result codes] are enabled or disabled\n** on a per database connection basis using the\n** [sqlite3_extended_result_codes()] API.  Or, the extended code for\n** the most recent error can be obtained using\n** [sqlite3_extended_errcode()].\n*/\n#define SQLITE_ERROR_MISSING_COLLSEQ   (SQLITE_ERROR | (1<<8))\n#define SQLITE_ERROR_RETRY             (SQLITE_ERROR | (2<<8))\n#define SQLITE_ERROR_SNAPSHOT          (SQLITE_ERROR | (3<<8))\n#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))\n#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))\n#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))\n#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))\n#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))\n#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))\n#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))\n#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))\n#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))\n#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))\n#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))\n#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))\n#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))\n#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))\n#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))\n#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))\n#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))\n#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))\n#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))\n#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))\n#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))\n#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))\n#define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))\n#define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))\n#define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))\n#define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))\n#define SQLITE_IOERR_VNODE             (SQLITE_IOERR | (27<<8))\n#define SQLITE_IOERR_AUTH              (SQLITE_IOERR | (28<<8))\n#define SQLITE_IOERR_BEGIN_ATOMIC      (SQLITE_IOERR | (29<<8))\n#define SQLITE_IOERR_COMMIT_ATOMIC     (SQLITE_IOERR | (30<<8))\n#define SQLITE_IOERR_ROLLBACK_ATOMIC   (SQLITE_IOERR | (31<<8))\n#define SQLITE_IOERR_DATA              (SQLITE_IOERR | (32<<8))\n#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))\n#define SQLITE_LOCKED_VTAB             (SQLITE_LOCKED |  (2<<8))\n#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))\n#define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))\n#define SQLITE_BUSY_TIMEOUT            (SQLITE_BUSY   |  (3<<8))\n#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))\n#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))\n#define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))\n#define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))\n#define SQLITE_CANTOPEN_DIRTYWAL       (SQLITE_CANTOPEN | (5<<8)) /* Not Used */\n#define SQLITE_CANTOPEN_SYMLINK        (SQLITE_CANTOPEN | (6<<8))\n#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))\n#define SQLITE_CORRUPT_SEQUENCE        (SQLITE_CORRUPT | (2<<8))\n#define SQLITE_CORRUPT_INDEX           (SQLITE_CORRUPT | (3<<8))\n#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))\n#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))\n#define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))\n#define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))\n#define SQLITE_READONLY_CANTINIT       (SQLITE_READONLY | (5<<8))\n#define SQLITE_READONLY_DIRECTORY      (SQLITE_READONLY | (6<<8))\n#define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))\n#define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))\n#define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))\n#define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))\n#define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))\n#define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))\n#define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))\n#define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))\n#define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))\n#define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))\n#define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))\n#define SQLITE_CONSTRAINT_PINNED       (SQLITE_CONSTRAINT |(11<<8))\n#define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))\n#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))\n#define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))\n#define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))\n#define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))\n#define SQLITE_OK_SYMLINK              (SQLITE_OK | (2<<8))\n\n/*\n** CAPI3REF: Flags For File Open Operations\n**\n** These bit values are intended for use in the\n** 3rd parameter to the [sqlite3_open_v2()] interface and\n** in the 4th parameter to the [sqlite3_vfs.xOpen] method.\n*/\n#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */\n#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */\n#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */\n#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */\n#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */\n#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */\n#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */\n#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */\n#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */\n#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */\n#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */\n#define SQLITE_OPEN_NOFOLLOW         0x01000000  /* Ok for sqlite3_open_v2() */\n\n/* Reserved:                         0x00F00000 */\n\n/*\n** CAPI3REF: Device Characteristics\n**\n** The xDeviceCharacteristics method of the [sqlite3_io_methods]\n** object returns an integer which is a vector of these\n** bit values expressing I/O characteristics of the mass storage\n** device that holds the file that the [sqlite3_io_methods]\n** refers to.\n**\n** The SQLITE_IOCAP_ATOMIC property means that all writes of\n** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values\n** mean that writes of blocks that are nnn bytes in size and\n** are aligned to an address which is an integer multiple of\n** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means\n** that when data is appended to a file, the data is appended\n** first then the size of the file is extended, never the other\n** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that\n** information is written to disk in the same order as calls\n** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that\n** after reboot following a crash or power loss, the only bytes in a\n** file that were written at the application level might have changed\n** and that adjacent bytes, even bytes within the same sector are\n** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN\n** flag indicates that a file cannot be deleted when open.  The\n** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on\n** read-only media and cannot be changed even by processes with\n** elevated privileges.\n**\n** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying\n** filesystem supports doing multiple write operations atomically when those\n** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and\n** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].\n*/\n#define SQLITE_IOCAP_ATOMIC                 0x00000001\n#define SQLITE_IOCAP_ATOMIC512              0x00000002\n#define SQLITE_IOCAP_ATOMIC1K               0x00000004\n#define SQLITE_IOCAP_ATOMIC2K               0x00000008\n#define SQLITE_IOCAP_ATOMIC4K               0x00000010\n#define SQLITE_IOCAP_ATOMIC8K               0x00000020\n#define SQLITE_IOCAP_ATOMIC16K              0x00000040\n#define SQLITE_IOCAP_ATOMIC32K              0x00000080\n#define SQLITE_IOCAP_ATOMIC64K              0x00000100\n#define SQLITE_IOCAP_SAFE_APPEND            0x00000200\n#define SQLITE_IOCAP_SEQUENTIAL             0x00000400\n#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800\n#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000\n#define SQLITE_IOCAP_IMMUTABLE              0x00002000\n#define SQLITE_IOCAP_BATCH_ATOMIC           0x00004000\n\n/*\n** CAPI3REF: File Locking Levels\n**\n** SQLite uses one of these integer values as the second\n** argument to calls it makes to the xLock() and xUnlock() methods\n** of an [sqlite3_io_methods] object.\n*/\n#define SQLITE_LOCK_NONE          0\n#define SQLITE_LOCK_SHARED        1\n#define SQLITE_LOCK_RESERVED      2\n#define SQLITE_LOCK_PENDING       3\n#define SQLITE_LOCK_EXCLUSIVE     4\n\n/*\n** CAPI3REF: Synchronization Type Flags\n**\n** When SQLite invokes the xSync() method of an\n** [sqlite3_io_methods] object it uses a combination of\n** these integer values as the second argument.\n**\n** When the SQLITE_SYNC_DATAONLY flag is used, it means that the\n** sync operation only needs to flush data to mass storage.  Inode\n** information need not be flushed. If the lower four bits of the flag\n** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.\n** If the lower four bits equal SQLITE_SYNC_FULL, that means\n** to use Mac OS X style fullsync instead of fsync().\n**\n** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags\n** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL\n** settings.  The [synchronous pragma] determines when calls to the\n** xSync VFS method occur and applies uniformly across all platforms.\n** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how\n** energetic or rigorous or forceful the sync operations are and\n** only make a difference on Mac OSX for the default SQLite code.\n** (Third-party VFS implementations might also make the distinction\n** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the\n** operating systems natively supported by SQLite, only Mac OSX\n** cares about the difference.)\n*/\n#define SQLITE_SYNC_NORMAL        0x00002\n#define SQLITE_SYNC_FULL          0x00003\n#define SQLITE_SYNC_DATAONLY      0x00010\n\n/*\n** CAPI3REF: OS Interface Open File Handle\n**\n** An [sqlite3_file] object represents an open file in the \n** [sqlite3_vfs | OS interface layer].  Individual OS interface\n** implementations will\n** want to subclass this object by appending additional fields\n** for their own use.  The pMethods entry is a pointer to an\n** [sqlite3_io_methods] object that defines methods for performing\n** I/O operations on the open file.\n*/\ntypedef struct sqlite3_file sqlite3_file;\nstruct sqlite3_file {\n  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */\n};\n\n/*\n** CAPI3REF: OS Interface File Virtual Methods Object\n**\n** Every file opened by the [sqlite3_vfs.xOpen] method populates an\n** [sqlite3_file] object (or, more commonly, a subclass of the\n** [sqlite3_file] object) with a pointer to an instance of this object.\n** This object defines the methods used to perform various operations\n** against the open file represented by the [sqlite3_file] object.\n**\n** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element \n** to a non-NULL pointer, then the sqlite3_io_methods.xClose method\n** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The\n** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]\n** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element\n** to NULL.\n**\n** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or\n** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().\n** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]\n** flag may be ORed in to indicate that only the data of the file\n** and not its inode needs to be synced.\n**\n** The integer values to xLock() and xUnlock() are one of\n** <ul>\n** <li> [SQLITE_LOCK_NONE],\n** <li> [SQLITE_LOCK_SHARED],\n** <li> [SQLITE_LOCK_RESERVED],\n** <li> [SQLITE_LOCK_PENDING], or\n** <li> [SQLITE_LOCK_EXCLUSIVE].\n** </ul>\n** xLock() increases the lock. xUnlock() decreases the lock.\n** The xCheckReservedLock() method checks whether any database connection,\n** either in this process or in some other process, is holding a RESERVED,\n** PENDING, or EXCLUSIVE lock on the file.  It returns true\n** if such a lock exists and false otherwise.\n**\n** The xFileControl() method is a generic interface that allows custom\n** VFS implementations to directly control an open file using the\n** [sqlite3_file_control()] interface.  The second \"op\" argument is an\n** integer opcode.  The third argument is a generic pointer intended to\n** point to a structure that may contain arguments or space in which to\n** write return values.  Potential uses for xFileControl() might be\n** functions to enable blocking locks with timeouts, to change the\n** locking strategy (for example to use dot-file locks), to inquire\n** about the status of a lock, or to break stale locks.  The SQLite\n** core reserves all opcodes less than 100 for its own use.\n** A [file control opcodes | list of opcodes] less than 100 is available.\n** Applications that define a custom xFileControl method should use opcodes\n** greater than 100 to avoid conflicts.  VFS implementations should\n** return [SQLITE_NOTFOUND] for file control opcodes that they do not\n** recognize.\n**\n** The xSectorSize() method returns the sector size of the\n** device that underlies the file.  The sector size is the\n** minimum write that can be performed without disturbing\n** other bytes in the file.  The xDeviceCharacteristics()\n** method returns a bit vector describing behaviors of the\n** underlying device:\n**\n** <ul>\n** <li> [SQLITE_IOCAP_ATOMIC]\n** <li> [SQLITE_IOCAP_ATOMIC512]\n** <li> [SQLITE_IOCAP_ATOMIC1K]\n** <li> [SQLITE_IOCAP_ATOMIC2K]\n** <li> [SQLITE_IOCAP_ATOMIC4K]\n** <li> [SQLITE_IOCAP_ATOMIC8K]\n** <li> [SQLITE_IOCAP_ATOMIC16K]\n** <li> [SQLITE_IOCAP_ATOMIC32K]\n** <li> [SQLITE_IOCAP_ATOMIC64K]\n** <li> [SQLITE_IOCAP_SAFE_APPEND]\n** <li> [SQLITE_IOCAP_SEQUENTIAL]\n** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]\n** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]\n** <li> [SQLITE_IOCAP_IMMUTABLE]\n** <li> [SQLITE_IOCAP_BATCH_ATOMIC]\n** </ul>\n**\n** The SQLITE_IOCAP_ATOMIC property means that all writes of\n** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values\n** mean that writes of blocks that are nnn bytes in size and\n** are aligned to an address which is an integer multiple of\n** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means\n** that when data is appended to a file, the data is appended\n** first then the size of the file is extended, never the other\n** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that\n** information is written to disk in the same order as calls\n** to xWrite().\n**\n** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill\n** in the unread portions of the buffer with zeros.  A VFS that\n** fails to zero-fill short reads might seem to work.  However,\n** failure to zero-fill short reads will eventually lead to\n** database corruption.\n*/\ntypedef struct sqlite3_io_methods sqlite3_io_methods;\nstruct sqlite3_io_methods {\n  int iVersion;\n  int (*xClose)(sqlite3_file*);\n  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);\n  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);\n  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);\n  int (*xSync)(sqlite3_file*, int flags);\n  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);\n  int (*xLock)(sqlite3_file*, int);\n  int (*xUnlock)(sqlite3_file*, int);\n  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);\n  int (*xFileControl)(sqlite3_file*, int op, void *pArg);\n  int (*xSectorSize)(sqlite3_file*);\n  int (*xDeviceCharacteristics)(sqlite3_file*);\n  /* Methods above are valid for version 1 */\n  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);\n  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);\n  void (*xShmBarrier)(sqlite3_file*);\n  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);\n  /* Methods above are valid for version 2 */\n  int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);\n  int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);\n  /* Methods above are valid for version 3 */\n  /* Additional methods may be added in future releases */\n};\n\n/*\n** CAPI3REF: Standard File Control Opcodes\n** KEYWORDS: {file control opcodes} {file control opcode}\n**\n** These integer constants are opcodes for the xFileControl method\n** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]\n** interface.\n**\n** <ul>\n** <li>[[SQLITE_FCNTL_LOCKSTATE]]\n** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This\n** opcode causes the xFileControl method to write the current state of\n** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],\n** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])\n** into an integer that the pArg argument points to. This capability\n** is used during testing and is only available when the SQLITE_TEST\n** compile-time option is used.\n**\n** <li>[[SQLITE_FCNTL_SIZE_HINT]]\n** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS\n** layer a hint of how large the database file will grow to be during the\n** current transaction.  This hint is not guaranteed to be accurate but it\n** is often close.  The underlying VFS might choose to preallocate database\n** file space based on this hint in order to help writes to the database\n** file run faster.\n**\n** <li>[[SQLITE_FCNTL_SIZE_LIMIT]]\n** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that\n** implements [sqlite3_deserialize()] to set an upper bound on the size\n** of the in-memory database.  The argument is a pointer to a [sqlite3_int64].\n** If the integer pointed to is negative, then it is filled in with the\n** current limit.  Otherwise the limit is set to the larger of the value\n** of the integer pointed to and the current database size.  The integer\n** pointed to is set to the new limit.\n**\n** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]\n** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS\n** extends and truncates the database file in chunks of a size specified\n** by the user. The fourth argument to [sqlite3_file_control()] should \n** point to an integer (type int) containing the new chunk-size to use\n** for the nominated database. Allocating database file space in large\n** chunks (say 1MB at a time), may reduce file-system fragmentation and\n** improve performance on some systems.\n**\n** <li>[[SQLITE_FCNTL_FILE_POINTER]]\n** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer\n** to the [sqlite3_file] object associated with a particular database\n** connection.  See also [SQLITE_FCNTL_JOURNAL_POINTER].\n**\n** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]\n** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer\n** to the [sqlite3_file] object associated with the journal file (either\n** the [rollback journal] or the [write-ahead log]) for a particular database\n** connection.  See also [SQLITE_FCNTL_FILE_POINTER].\n**\n** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]\n** No longer in use.\n**\n** <li>[[SQLITE_FCNTL_SYNC]]\n** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and\n** sent to the VFS immediately before the xSync method is invoked on a\n** database file descriptor. Or, if the xSync method is not invoked \n** because the user has configured SQLite with \n** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place \n** of the xSync method. In most cases, the pointer argument passed with\n** this file-control is NULL. However, if the database file is being synced\n** as part of a multi-database commit, the argument points to a nul-terminated\n** string containing the transactions master-journal file name. VFSes that \n** do not need this signal should silently ignore this opcode. Applications \n** should not call [sqlite3_file_control()] with this opcode as doing so may \n** disrupt the operation of the specialized VFSes that do require it.  \n**\n** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]\n** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite\n** and sent to the VFS after a transaction has been committed immediately\n** but before the database is unlocked. VFSes that do not need this signal\n** should silently ignore this opcode. Applications should not call\n** [sqlite3_file_control()] with this opcode as doing so may disrupt the \n** operation of the specialized VFSes that do require it.  \n**\n** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]\n** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic\n** retry counts and intervals for certain disk I/O operations for the\n** windows [VFS] in order to provide robustness in the presence of\n** anti-virus programs.  By default, the windows VFS will retry file read,\n** file write, and file delete operations up to 10 times, with a delay\n** of 25 milliseconds before the first retry and with the delay increasing\n** by an additional 25 milliseconds with each subsequent retry.  This\n** opcode allows these two values (10 retries and 25 milliseconds of delay)\n** to be adjusted.  The values are changed for all database connections\n** within the same process.  The argument is a pointer to an array of two\n** integers where the first integer is the new retry count and the second\n** integer is the delay.  If either integer is negative, then the setting\n** is not changed but instead the prior value of that setting is written\n** into the array entry, allowing the current retry settings to be\n** interrogated.  The zDbName parameter is ignored.\n**\n** <li>[[SQLITE_FCNTL_PERSIST_WAL]]\n** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the\n** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary\n** write ahead log ([WAL file]) and shared memory\n** files used for transaction control\n** are automatically deleted when the latest connection to the database\n** closes.  Setting persistent WAL mode causes those files to persist after\n** close.  Persisting the files is useful when other processes that do not\n** have write permission on the directory containing the database file want\n** to read the database file, as the WAL and shared memory files must exist\n** in order for the database to be readable.  The fourth parameter to\n** [sqlite3_file_control()] for this opcode should be a pointer to an integer.\n** That integer is 0 to disable persistent WAL mode or 1 to enable persistent\n** WAL mode.  If the integer is -1, then it is overwritten with the current\n** WAL persistence setting.\n**\n** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]\n** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the\n** persistent \"powersafe-overwrite\" or \"PSOW\" setting.  The PSOW setting\n** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the\n** xDeviceCharacteristics methods. The fourth parameter to\n** [sqlite3_file_control()] for this opcode should be a pointer to an integer.\n** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage\n** mode.  If the integer is -1, then it is overwritten with the current\n** zero-damage mode setting.\n**\n** <li>[[SQLITE_FCNTL_OVERWRITE]]\n** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening\n** a write transaction to indicate that, unless it is rolled back for some\n** reason, the entire database file will be overwritten by the current \n** transaction. This is used by VACUUM operations.\n**\n** <li>[[SQLITE_FCNTL_VFSNAME]]\n** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of\n** all [VFSes] in the VFS stack.  The names are of all VFS shims and the\n** final bottom-level VFS are written into memory obtained from \n** [sqlite3_malloc()] and the result is stored in the char* variable\n** that the fourth parameter of [sqlite3_file_control()] points to.\n** The caller is responsible for freeing the memory when done.  As with\n** all file-control actions, there is no guarantee that this will actually\n** do anything.  Callers should initialize the char* variable to a NULL\n** pointer in case this file-control is not implemented.  This file-control\n** is intended for diagnostic use only.\n**\n** <li>[[SQLITE_FCNTL_VFS_POINTER]]\n** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level\n** [VFSes] currently in use.  ^(The argument X in\n** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be\n** of type \"[sqlite3_vfs] **\".  This opcodes will set *X\n** to a pointer to the top-level VFS.)^\n** ^When there are multiple VFS shims in the stack, this opcode finds the\n** upper-most shim only.\n**\n** <li>[[SQLITE_FCNTL_PRAGMA]]\n** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] \n** file control is sent to the open [sqlite3_file] object corresponding\n** to the database file to which the pragma statement refers. ^The argument\n** to the [SQLITE_FCNTL_PRAGMA] file control is an array of\n** pointers to strings (char**) in which the second element of the array\n** is the name of the pragma and the third element is the argument to the\n** pragma or NULL if the pragma has no argument.  ^The handler for an\n** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element\n** of the char** argument point to a string obtained from [sqlite3_mprintf()]\n** or the equivalent and that string will become the result of the pragma or\n** the error message if the pragma fails. ^If the\n** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal \n** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]\n** file control returns [SQLITE_OK], then the parser assumes that the\n** VFS has handled the PRAGMA itself and the parser generates a no-op\n** prepared statement if result string is NULL, or that returns a copy\n** of the result string if the string is non-NULL.\n** ^If the [SQLITE_FCNTL_PRAGMA] file control returns\n** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means\n** that the VFS encountered an error while handling the [PRAGMA] and the\n** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]\n** file control occurs at the beginning of pragma statement analysis and so\n** it is able to override built-in [PRAGMA] statements.\n**\n** <li>[[SQLITE_FCNTL_BUSYHANDLER]]\n** ^The [SQLITE_FCNTL_BUSYHANDLER]\n** file-control may be invoked by SQLite on the database file handle\n** shortly after it is opened in order to provide a custom VFS with access\n** to the connection's busy-handler callback. The argument is of type (void**)\n** - an array of two (void *) values. The first (void *) actually points\n** to a function of type (int (*)(void *)). In order to invoke the connection's\n** busy-handler, this function should be invoked with the second (void *) in\n** the array as the only argument. If it returns non-zero, then the operation\n** should be retried. If it returns zero, the custom VFS should abandon the\n** current operation.\n**\n** <li>[[SQLITE_FCNTL_TEMPFILENAME]]\n** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control\n** to have SQLite generate a\n** temporary filename using the same algorithm that is followed to generate\n** temporary filenames for TEMP tables and other internal uses.  The\n** argument should be a char** which will be filled with the filename\n** written into memory obtained from [sqlite3_malloc()].  The caller should\n** invoke [sqlite3_free()] on the result to avoid a memory leak.\n**\n** <li>[[SQLITE_FCNTL_MMAP_SIZE]]\n** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the\n** maximum number of bytes that will be used for memory-mapped I/O.\n** The argument is a pointer to a value of type sqlite3_int64 that\n** is an advisory maximum number of bytes in the file to memory map.  The\n** pointer is overwritten with the old value.  The limit is not changed if\n** the value originally pointed to is negative, and so the current limit \n** can be queried by passing in a pointer to a negative number.  This\n** file-control is used internally to implement [PRAGMA mmap_size].\n**\n** <li>[[SQLITE_FCNTL_TRACE]]\n** The [SQLITE_FCNTL_TRACE] file control provides advisory information\n** to the VFS about what the higher layers of the SQLite stack are doing.\n** This file control is used by some VFS activity tracing [shims].\n** The argument is a zero-terminated string.  Higher layers in the\n** SQLite stack may generate instances of this file control if\n** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.\n**\n** <li>[[SQLITE_FCNTL_HAS_MOVED]]\n** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a\n** pointer to an integer and it writes a boolean into that integer depending\n** on whether or not the file has been renamed, moved, or deleted since it\n** was first opened.\n**\n** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]\n** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the\n** underlying native file handle associated with a file handle.  This file\n** control interprets its argument as a pointer to a native file handle and\n** writes the resulting value there.\n**\n** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]\n** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging.  This\n** opcode causes the xFileControl method to swap the file handle with the one\n** pointed to by the pArg argument.  This capability is used during testing\n** and only needs to be supported when SQLITE_TEST is defined.\n**\n** <li>[[SQLITE_FCNTL_WAL_BLOCK]]\n** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might\n** be advantageous to block on the next WAL lock if the lock is not immediately\n** available.  The WAL subsystem issues this signal during rare\n** circumstances in order to fix a problem with priority inversion.\n** Applications should <em>not</em> use this file-control.\n**\n** <li>[[SQLITE_FCNTL_ZIPVFS]]\n** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other\n** VFS should return SQLITE_NOTFOUND for this opcode.\n**\n** <li>[[SQLITE_FCNTL_RBU]]\n** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by\n** the RBU extension only.  All other VFS should return SQLITE_NOTFOUND for\n** this opcode.  \n**\n** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]\n** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then\n** the file descriptor is placed in \"batch write mode\", which\n** means all subsequent write operations will be deferred and done\n** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].  Systems\n** that do not support batch atomic writes will return SQLITE_NOTFOUND.\n** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to\n** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or\n** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make\n** no VFS interface calls on the same [sqlite3_file] file descriptor\n** except for calls to the xWrite method and the xFileControl method\n** with [SQLITE_FCNTL_SIZE_HINT].\n**\n** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]\n** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write\n** operations since the previous successful call to \n** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.\n** This file control returns [SQLITE_OK] if and only if the writes were\n** all performed successfully and have been committed to persistent storage.\n** ^Regardless of whether or not it is successful, this file control takes\n** the file descriptor out of batch write mode so that all subsequent\n** write operations are independent.\n** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without\n** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].\n**\n** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]\n** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write\n** operations since the previous successful call to \n** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.\n** ^This file control takes the file descriptor out of batch write mode\n** so that all subsequent write operations are independent.\n** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without\n** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].\n**\n** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]\n** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode is used to configure a VFS\n** to block for up to M milliseconds before failing when attempting to \n** obtain a file lock using the xLock or xShmLock methods of the VFS. \n** The parameter is a pointer to a 32-bit signed integer that contains\n** the value that M is to be set to. Before returning, the 32-bit signed\n** integer is overwritten with the previous value of M.\n**\n** <li>[[SQLITE_FCNTL_DATA_VERSION]]\n** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to\n** a database file.  The argument is a pointer to a 32-bit unsigned integer.\n** The \"data version\" for the pager is written into the pointer.  The\n** \"data version\" changes whenever any change occurs to the corresponding\n** database file, either through SQL statements on the same database\n** connection or through transactions committed by separate database\n** connections possibly in other processes. The [sqlite3_total_changes()]\n** interface can be used to find if any database on the connection has changed,\n** but that interface responds to changes on TEMP as well as MAIN and does\n** not provide a mechanism to detect changes to MAIN only.  Also, the\n** [sqlite3_total_changes()] interface responds to internal changes only and\n** omits changes made by other database connections.  The\n** [PRAGMA data_version] command provides a mechanism to detect changes to\n** a single attached database that occur due to other database connections,\n** but omits changes implemented by the database connection on which it is\n** called.  This file control is the only mechanism to detect changes that\n** happen either internally or externally and that are associated with\n** a particular attached database.\n**\n** <li>[[SQLITE_FCNTL_CKPT_START]]\n** The [SQLITE_FCNTL_CKPT_START] opcode is invoked from within a checkpoint\n** in wal mode before the client starts to copy pages from the wal\n** file to the database file.\n**\n** <li>[[SQLITE_FCNTL_CKPT_DONE]]\n** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint\n** in wal mode after the client has finished copying pages from the wal\n** file to the database file, but before the *-shm file is updated to\n** record the fact that the pages have been checkpointed.\n** </ul>\n*/\n#define SQLITE_FCNTL_LOCKSTATE               1\n#define SQLITE_FCNTL_GET_LOCKPROXYFILE       2\n#define SQLITE_FCNTL_SET_LOCKPROXYFILE       3\n#define SQLITE_FCNTL_LAST_ERRNO              4\n#define SQLITE_FCNTL_SIZE_HINT               5\n#define SQLITE_FCNTL_CHUNK_SIZE              6\n#define SQLITE_FCNTL_FILE_POINTER            7\n#define SQLITE_FCNTL_SYNC_OMITTED            8\n#define SQLITE_FCNTL_WIN32_AV_RETRY          9\n#define SQLITE_FCNTL_PERSIST_WAL            10\n#define SQLITE_FCNTL_OVERWRITE              11\n#define SQLITE_FCNTL_VFSNAME                12\n#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13\n#define SQLITE_FCNTL_PRAGMA                 14\n#define SQLITE_FCNTL_BUSYHANDLER            15\n#define SQLITE_FCNTL_TEMPFILENAME           16\n#define SQLITE_FCNTL_MMAP_SIZE              18\n#define SQLITE_FCNTL_TRACE                  19\n#define SQLITE_FCNTL_HAS_MOVED              20\n#define SQLITE_FCNTL_SYNC                   21\n#define SQLITE_FCNTL_COMMIT_PHASETWO        22\n#define SQLITE_FCNTL_WIN32_SET_HANDLE       23\n#define SQLITE_FCNTL_WAL_BLOCK              24\n#define SQLITE_FCNTL_ZIPVFS                 25\n#define SQLITE_FCNTL_RBU                    26\n#define SQLITE_FCNTL_VFS_POINTER            27\n#define SQLITE_FCNTL_JOURNAL_POINTER        28\n#define SQLITE_FCNTL_WIN32_GET_HANDLE       29\n#define SQLITE_FCNTL_PDB                    30\n#define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE     31\n#define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE    32\n#define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE  33\n#define SQLITE_FCNTL_LOCK_TIMEOUT           34\n#define SQLITE_FCNTL_DATA_VERSION           35\n#define SQLITE_FCNTL_SIZE_LIMIT             36\n#define SQLITE_FCNTL_CKPT_DONE              37\n#define SQLITE_FCNTL_RESERVE_BYTES          38\n#define SQLITE_FCNTL_CKPT_START             39\n\n/* deprecated names */\n#define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE\n#define SQLITE_SET_LOCKPROXYFILE      SQLITE_FCNTL_SET_LOCKPROXYFILE\n#define SQLITE_LAST_ERRNO             SQLITE_FCNTL_LAST_ERRNO\n\n\n/*\n** CAPI3REF: Mutex Handle\n**\n** The mutex module within SQLite defines [sqlite3_mutex] to be an\n** abstract type for a mutex object.  The SQLite core never looks\n** at the internal representation of an [sqlite3_mutex].  It only\n** deals with pointers to the [sqlite3_mutex] object.\n**\n** Mutexes are created using [sqlite3_mutex_alloc()].\n*/\ntypedef struct sqlite3_mutex sqlite3_mutex;\n\n/*\n** CAPI3REF: Loadable Extension Thunk\n**\n** A pointer to the opaque sqlite3_api_routines structure is passed as\n** the third parameter to entry points of [loadable extensions].  This\n** structure must be typedefed in order to work around compiler warnings\n** on some platforms.\n*/\ntypedef struct sqlite3_api_routines sqlite3_api_routines;\n\n/*\n** CAPI3REF: OS Interface Object\n**\n** An instance of the sqlite3_vfs object defines the interface between\n** the SQLite core and the underlying operating system.  The \"vfs\"\n** in the name of the object stands for \"virtual file system\".  See\n** the [VFS | VFS documentation] for further information.\n**\n** The VFS interface is sometimes extended by adding new methods onto\n** the end.  Each time such an extension occurs, the iVersion field\n** is incremented.  The iVersion value started out as 1 in\n** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2\n** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased\n** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6].  Additional fields\n** may be appended to the sqlite3_vfs object and the iVersion value\n** may increase again in future versions of SQLite.\n** Note that due to an oversight, the structure\n** of the sqlite3_vfs object changed in the transition from\n** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]\n** and yet the iVersion field was not increased.\n**\n** The szOsFile field is the size of the subclassed [sqlite3_file]\n** structure used by this VFS.  mxPathname is the maximum length of\n** a pathname in this VFS.\n**\n** Registered sqlite3_vfs objects are kept on a linked list formed by\n** the pNext pointer.  The [sqlite3_vfs_register()]\n** and [sqlite3_vfs_unregister()] interfaces manage this list\n** in a thread-safe way.  The [sqlite3_vfs_find()] interface\n** searches the list.  Neither the application code nor the VFS\n** implementation should use the pNext pointer.\n**\n** The pNext field is the only field in the sqlite3_vfs\n** structure that SQLite will ever modify.  SQLite will only access\n** or modify this field while holding a particular static mutex.\n** The application should never modify anything within the sqlite3_vfs\n** object once the object has been registered.\n**\n** The zName field holds the name of the VFS module.  The name must\n** be unique across all VFS modules.\n**\n** [[sqlite3_vfs.xOpen]]\n** ^SQLite guarantees that the zFilename parameter to xOpen\n** is either a NULL pointer or string obtained\n** from xFullPathname() with an optional suffix added.\n** ^If a suffix is added to the zFilename parameter, it will\n** consist of a single \"-\" character followed by no more than\n** 11 alphanumeric and/or \"-\" characters.\n** ^SQLite further guarantees that\n** the string will be valid and unchanged until xClose() is\n** called. Because of the previous sentence,\n** the [sqlite3_file] can safely store a pointer to the\n** filename if it needs to remember the filename for some reason.\n** If the zFilename parameter to xOpen is a NULL pointer then xOpen\n** must invent its own temporary name for the file.  ^Whenever the \n** xFilename parameter is NULL it will also be the case that the\n** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].\n**\n** The flags argument to xOpen() includes all bits set in\n** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]\n** or [sqlite3_open16()] is used, then flags includes at least\n** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. \n** If xOpen() opens a file read-only then it sets *pOutFlags to\n** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.\n**\n** ^(SQLite will also add one of the following flags to the xOpen()\n** call, depending on the object being opened:\n**\n** <ul>\n** <li>  [SQLITE_OPEN_MAIN_DB]\n** <li>  [SQLITE_OPEN_MAIN_JOURNAL]\n** <li>  [SQLITE_OPEN_TEMP_DB]\n** <li>  [SQLITE_OPEN_TEMP_JOURNAL]\n** <li>  [SQLITE_OPEN_TRANSIENT_DB]\n** <li>  [SQLITE_OPEN_SUBJOURNAL]\n** <li>  [SQLITE_OPEN_MASTER_JOURNAL]\n** <li>  [SQLITE_OPEN_WAL]\n** </ul>)^\n**\n** The file I/O implementation can use the object type flags to\n** change the way it deals with files.  For example, an application\n** that does not care about crash recovery or rollback might make\n** the open of a journal file a no-op.  Writes to this journal would\n** also be no-ops, and any attempt to read the journal would return\n** SQLITE_IOERR.  Or the implementation might recognize that a database\n** file will be doing page-aligned sector reads and writes in a random\n** order and set up its I/O subsystem accordingly.\n**\n** SQLite might also add one of the following flags to the xOpen method:\n**\n** <ul>\n** <li> [SQLITE_OPEN_DELETEONCLOSE]\n** <li> [SQLITE_OPEN_EXCLUSIVE]\n** </ul>\n**\n** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be\n** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]\n** will be set for TEMP databases and their journals, transient\n** databases, and subjournals.\n**\n** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction\n** with the [SQLITE_OPEN_CREATE] flag, which are both directly\n** analogous to the O_EXCL and O_CREAT flags of the POSIX open()\n** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the \n** SQLITE_OPEN_CREATE, is used to indicate that file should always\n** be created, and that it is an error if it already exists.\n** It is <i>not</i> used to indicate the file should be opened \n** for exclusive access.\n**\n** ^At least szOsFile bytes of memory are allocated by SQLite\n** to hold the [sqlite3_file] structure passed as the third\n** argument to xOpen.  The xOpen method does not have to\n** allocate the structure; it should just fill it in.  Note that\n** the xOpen method must set the sqlite3_file.pMethods to either\n** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do\n** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods\n** element will be valid after xOpen returns regardless of the success\n** or failure of the xOpen call.\n**\n** [[sqlite3_vfs.xAccess]]\n** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]\n** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to\n** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]\n** to test whether a file is at least readable.  The SQLITE_ACCESS_READ\n** flag is never actually used and is not implemented in the built-in\n** VFSes of SQLite.  The file is named by the second argument and can be a\n** directory. The xAccess method returns [SQLITE_OK] on success or some\n** non-zero error code if there is an I/O error or if the name of\n** the file given in the second argument is illegal.  If SQLITE_OK\n** is returned, then non-zero or zero is written into *pResOut to indicate\n** whether or not the file is accessible.  \n**\n** ^SQLite will always allocate at least mxPathname+1 bytes for the\n** output buffer xFullPathname.  The exact size of the output buffer\n** is also passed as a parameter to both  methods. If the output buffer\n** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is\n** handled as a fatal error by SQLite, vfs implementations should endeavor\n** to prevent this by setting mxPathname to a sufficiently large value.\n**\n** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()\n** interfaces are not strictly a part of the filesystem, but they are\n** included in the VFS structure for completeness.\n** The xRandomness() function attempts to return nBytes bytes\n** of good-quality randomness into zOut.  The return value is\n** the actual number of bytes of randomness obtained.\n** The xSleep() method causes the calling thread to sleep for at\n** least the number of microseconds given.  ^The xCurrentTime()\n** method returns a Julian Day Number for the current date and time as\n** a floating point value.\n** ^The xCurrentTimeInt64() method returns, as an integer, the Julian\n** Day Number multiplied by 86400000 (the number of milliseconds in \n** a 24-hour day).  \n** ^SQLite will use the xCurrentTimeInt64() method to get the current\n** date and time if that method is available (if iVersion is 2 or \n** greater and the function pointer is not NULL) and will fall back\n** to xCurrentTime() if xCurrentTimeInt64() is unavailable.\n**\n** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces\n** are not used by the SQLite core.  These optional interfaces are provided\n** by some VFSes to facilitate testing of the VFS code. By overriding \n** system calls with functions under its control, a test program can\n** simulate faults and error conditions that would otherwise be difficult\n** or impossible to induce.  The set of system calls that can be overridden\n** varies from one VFS to another, and from one version of the same VFS to the\n** next.  Applications that use these interfaces must be prepared for any\n** or all of these interfaces to be NULL or for their behavior to change\n** from one release to the next.  Applications must not attempt to access\n** any of these methods if the iVersion of the VFS is less than 3.\n*/\ntypedef struct sqlite3_vfs sqlite3_vfs;\ntypedef void (*sqlite3_syscall_ptr)(void);\nstruct sqlite3_vfs {\n  int iVersion;            /* Structure version number (currently 3) */\n  int szOsFile;            /* Size of subclassed sqlite3_file */\n  int mxPathname;          /* Maximum file pathname length */\n  sqlite3_vfs *pNext;      /* Next registered VFS */\n  const char *zName;       /* Name of this virtual file system */\n  void *pAppData;          /* Pointer to application-specific data */\n  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,\n               int flags, int *pOutFlags);\n  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);\n  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);\n  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);\n  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);\n  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);\n  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);\n  void (*xDlClose)(sqlite3_vfs*, void*);\n  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);\n  int (*xSleep)(sqlite3_vfs*, int microseconds);\n  int (*xCurrentTime)(sqlite3_vfs*, double*);\n  int (*xGetLastError)(sqlite3_vfs*, int, char *);\n  /*\n  ** The methods above are in version 1 of the sqlite_vfs object\n  ** definition.  Those that follow are added in version 2 or later\n  */\n  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);\n  /*\n  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.\n  ** Those below are for version 3 and greater.\n  */\n  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);\n  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);\n  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);\n  /*\n  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.\n  ** New fields may be appended in future versions.  The iVersion\n  ** value will increment whenever this happens. \n  */\n};\n\n/*\n** CAPI3REF: Flags for the xAccess VFS method\n**\n** These integer constants can be used as the third parameter to\n** the xAccess method of an [sqlite3_vfs] object.  They determine\n** what kind of permissions the xAccess method is looking for.\n** With SQLITE_ACCESS_EXISTS, the xAccess method\n** simply checks whether the file exists.\n** With SQLITE_ACCESS_READWRITE, the xAccess method\n** checks whether the named directory is both readable and writable\n** (in other words, if files can be added, removed, and renamed within\n** the directory).\n** The SQLITE_ACCESS_READWRITE constant is currently used only by the\n** [temp_store_directory pragma], though this could change in a future\n** release of SQLite.\n** With SQLITE_ACCESS_READ, the xAccess method\n** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is\n** currently unused, though it might be used in a future release of\n** SQLite.\n*/\n#define SQLITE_ACCESS_EXISTS    0\n#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */\n#define SQLITE_ACCESS_READ      2   /* Unused */\n\n/*\n** CAPI3REF: Flags for the xShmLock VFS method\n**\n** These integer constants define the various locking operations\n** allowed by the xShmLock method of [sqlite3_io_methods].  The\n** following are the only legal combinations of flags to the\n** xShmLock method:\n**\n** <ul>\n** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED\n** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE\n** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED\n** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE\n** </ul>\n**\n** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as\n** was given on the corresponding lock.  \n**\n** The xShmLock method can transition between unlocked and SHARED or\n** between unlocked and EXCLUSIVE.  It cannot transition between SHARED\n** and EXCLUSIVE.\n*/\n#define SQLITE_SHM_UNLOCK       1\n#define SQLITE_SHM_LOCK         2\n#define SQLITE_SHM_SHARED       4\n#define SQLITE_SHM_EXCLUSIVE    8\n\n/*\n** CAPI3REF: Maximum xShmLock index\n**\n** The xShmLock method on [sqlite3_io_methods] may use values\n** between 0 and this upper bound as its \"offset\" argument.\n** The SQLite core will never attempt to acquire or release a\n** lock outside of this range\n*/\n#define SQLITE_SHM_NLOCK        8\n\n\n/*\n** CAPI3REF: Initialize The SQLite Library\n**\n** ^The sqlite3_initialize() routine initializes the\n** SQLite library.  ^The sqlite3_shutdown() routine\n** deallocates any resources that were allocated by sqlite3_initialize().\n** These routines are designed to aid in process initialization and\n** shutdown on embedded systems.  Workstation applications using\n** SQLite normally do not need to invoke either of these routines.\n**\n** A call to sqlite3_initialize() is an \"effective\" call if it is\n** the first time sqlite3_initialize() is invoked during the lifetime of\n** the process, or if it is the first time sqlite3_initialize() is invoked\n** following a call to sqlite3_shutdown().  ^(Only an effective call\n** of sqlite3_initialize() does any initialization.  All other calls\n** are harmless no-ops.)^\n**\n** A call to sqlite3_shutdown() is an \"effective\" call if it is the first\n** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only\n** an effective call to sqlite3_shutdown() does any deinitialization.\n** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^\n**\n** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()\n** is not.  The sqlite3_shutdown() interface must only be called from a\n** single thread.  All open [database connections] must be closed and all\n** other SQLite resources must be deallocated prior to invoking\n** sqlite3_shutdown().\n**\n** Among other things, ^sqlite3_initialize() will invoke\n** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()\n** will invoke sqlite3_os_end().\n**\n** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.\n** ^If for some reason, sqlite3_initialize() is unable to initialize\n** the library (perhaps it is unable to allocate a needed resource such\n** as a mutex) it returns an [error code] other than [SQLITE_OK].\n**\n** ^The sqlite3_initialize() routine is called internally by many other\n** SQLite interfaces so that an application usually does not need to\n** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]\n** calls sqlite3_initialize() so the SQLite library will be automatically\n** initialized when [sqlite3_open()] is called if it has not be initialized\n** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]\n** compile-time option, then the automatic calls to sqlite3_initialize()\n** are omitted and the application must call sqlite3_initialize() directly\n** prior to using any other SQLite interface.  For maximum portability,\n** it is recommended that applications always invoke sqlite3_initialize()\n** directly prior to using any other SQLite interface.  Future releases\n** of SQLite may require this.  In other words, the behavior exhibited\n** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the\n** default behavior in some future release of SQLite.\n**\n** The sqlite3_os_init() routine does operating-system specific\n** initialization of the SQLite library.  The sqlite3_os_end()\n** routine undoes the effect of sqlite3_os_init().  Typical tasks\n** performed by these routines include allocation or deallocation\n** of static resources, initialization of global variables,\n** setting up a default [sqlite3_vfs] module, or setting up\n** a default configuration using [sqlite3_config()].\n**\n** The application should never invoke either sqlite3_os_init()\n** or sqlite3_os_end() directly.  The application should only invoke\n** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()\n** interface is called automatically by sqlite3_initialize() and\n** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate\n** implementations for sqlite3_os_init() and sqlite3_os_end()\n** are built into SQLite when it is compiled for Unix, Windows, or OS/2.\n** When [custom builds | built for other platforms]\n** (using the [SQLITE_OS_OTHER=1] compile-time\n** option) the application must supply a suitable implementation for\n** sqlite3_os_init() and sqlite3_os_end().  An application-supplied\n** implementation of sqlite3_os_init() or sqlite3_os_end()\n** must return [SQLITE_OK] on success and some other [error code] upon\n** failure.\n*/\nSQLITE_API int sqlite3_initialize(void);\nSQLITE_API int sqlite3_shutdown(void);\nSQLITE_API int sqlite3_os_init(void);\nSQLITE_API int sqlite3_os_end(void);\n\n/*\n** CAPI3REF: Configuring The SQLite Library\n**\n** The sqlite3_config() interface is used to make global configuration\n** changes to SQLite in order to tune SQLite to the specific needs of\n** the application.  The default configuration is recommended for most\n** applications and so this routine is usually not necessary.  It is\n** provided to support rare applications with unusual needs.\n**\n** <b>The sqlite3_config() interface is not threadsafe. The application\n** must ensure that no other SQLite interfaces are invoked by other\n** threads while sqlite3_config() is running.</b>\n**\n** The sqlite3_config() interface\n** may only be invoked prior to library initialization using\n** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].\n** ^If sqlite3_config() is called after [sqlite3_initialize()] and before\n** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.\n** Note, however, that ^sqlite3_config() can be called as part of the\n** implementation of an application-defined [sqlite3_os_init()].\n**\n** The first argument to sqlite3_config() is an integer\n** [configuration option] that determines\n** what property of SQLite is to be configured.  Subsequent arguments\n** vary depending on the [configuration option]\n** in the first argument.\n**\n** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].\n** ^If the option is unknown or SQLite is unable to set the option\n** then this routine returns a non-zero [error code].\n*/\nSQLITE_API int sqlite3_config(int, ...);\n\n/*\n** CAPI3REF: Configure database connections\n** METHOD: sqlite3\n**\n** The sqlite3_db_config() interface is used to make configuration\n** changes to a [database connection].  The interface is similar to\n** [sqlite3_config()] except that the changes apply to a single\n** [database connection] (specified in the first argument).\n**\n** The second argument to sqlite3_db_config(D,V,...)  is the\n** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code \n** that indicates what aspect of the [database connection] is being configured.\n** Subsequent arguments vary depending on the configuration verb.\n**\n** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if\n** the call is considered successful.\n*/\nSQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);\n\n/*\n** CAPI3REF: Memory Allocation Routines\n**\n** An instance of this object defines the interface between SQLite\n** and low-level memory allocation routines.\n**\n** This object is used in only one place in the SQLite interface.\n** A pointer to an instance of this object is the argument to\n** [sqlite3_config()] when the configuration option is\n** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  \n** By creating an instance of this object\n** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])\n** during configuration, an application can specify an alternative\n** memory allocation subsystem for SQLite to use for all of its\n** dynamic memory needs.\n**\n** Note that SQLite comes with several [built-in memory allocators]\n** that are perfectly adequate for the overwhelming majority of applications\n** and that this object is only useful to a tiny minority of applications\n** with specialized memory allocation requirements.  This object is\n** also used during testing of SQLite in order to specify an alternative\n** memory allocator that simulates memory out-of-memory conditions in\n** order to verify that SQLite recovers gracefully from such\n** conditions.\n**\n** The xMalloc, xRealloc, and xFree methods must work like the\n** malloc(), realloc() and free() functions from the standard C library.\n** ^SQLite guarantees that the second argument to\n** xRealloc is always a value returned by a prior call to xRoundup.\n**\n** xSize should return the allocated size of a memory allocation\n** previously obtained from xMalloc or xRealloc.  The allocated size\n** is always at least as big as the requested size but may be larger.\n**\n** The xRoundup method returns what would be the allocated size of\n** a memory allocation given a particular requested size.  Most memory\n** allocators round up memory allocations at least to the next multiple\n** of 8.  Some allocators round up to a larger multiple or to a power of 2.\n** Every memory allocation request coming in through [sqlite3_malloc()]\n** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, \n** that causes the corresponding memory allocation to fail.\n**\n** The xInit method initializes the memory allocator.  For example,\n** it might allocate any required mutexes or initialize internal data\n** structures.  The xShutdown method is invoked (indirectly) by\n** [sqlite3_shutdown()] and should deallocate any resources acquired\n** by xInit.  The pAppData pointer is used as the only parameter to\n** xInit and xShutdown.\n**\n** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes\n** the xInit method, so the xInit method need not be threadsafe.  The\n** xShutdown method is only called from [sqlite3_shutdown()] so it does\n** not need to be threadsafe either.  For all other methods, SQLite\n** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the\n** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which\n** it is by default) and so the methods are automatically serialized.\n** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other\n** methods must be threadsafe or else make their own arrangements for\n** serialization.\n**\n** SQLite will never invoke xInit() more than once without an intervening\n** call to xShutdown().\n*/\ntypedef struct sqlite3_mem_methods sqlite3_mem_methods;\nstruct sqlite3_mem_methods {\n  void *(*xMalloc)(int);         /* Memory allocation function */\n  void (*xFree)(void*);          /* Free a prior allocation */\n  void *(*xRealloc)(void*,int);  /* Resize an allocation */\n  int (*xSize)(void*);           /* Return the size of an allocation */\n  int (*xRoundup)(int);          /* Round up request size to allocation size */\n  int (*xInit)(void*);           /* Initialize the memory allocator */\n  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */\n  void *pAppData;                /* Argument to xInit() and xShutdown() */\n};\n\n/*\n** CAPI3REF: Configuration Options\n** KEYWORDS: {configuration option}\n**\n** These constants are the available integer configuration options that\n** can be passed as the first argument to the [sqlite3_config()] interface.\n**\n** New configuration options may be added in future releases of SQLite.\n** Existing configuration options might be discontinued.  Applications\n** should check the return code from [sqlite3_config()] to make sure that\n** the call worked.  The [sqlite3_config()] interface will return a\n** non-zero [error code] if a discontinued or unsupported configuration option\n** is invoked.\n**\n** <dl>\n** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>\n** <dd>There are no arguments to this option.  ^This option sets the\n** [threading mode] to Single-thread.  In other words, it disables\n** all mutexing and puts SQLite into a mode where it can only be used\n** by a single thread.   ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** it is not possible to change the [threading mode] from its default\n** value of Single-thread and so [sqlite3_config()] will return \n** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD\n** configuration option.</dd>\n**\n** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>\n** <dd>There are no arguments to this option.  ^This option sets the\n** [threading mode] to Multi-thread.  In other words, it disables\n** mutexing on [database connection] and [prepared statement] objects.\n** The application is responsible for serializing access to\n** [database connections] and [prepared statements].  But other mutexes\n** are enabled so that SQLite will be safe to use in a multi-threaded\n** environment as long as no two threads attempt to use the same\n** [database connection] at the same time.  ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** it is not possible to set the Multi-thread [threading mode] and\n** [sqlite3_config()] will return [SQLITE_ERROR] if called with the\n** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>\n**\n** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>\n** <dd>There are no arguments to this option.  ^This option sets the\n** [threading mode] to Serialized. In other words, this option enables\n** all mutexes including the recursive\n** mutexes on [database connection] and [prepared statement] objects.\n** In this mode (which is the default when SQLite is compiled with\n** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access\n** to [database connections] and [prepared statements] so that the\n** application is free to use the same [database connection] or the\n** same [prepared statement] in different threads at the same time.\n** ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** it is not possible to set the Serialized [threading mode] and\n** [sqlite3_config()] will return [SQLITE_ERROR] if called with the\n** SQLITE_CONFIG_SERIALIZED configuration option.</dd>\n**\n** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>\n** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is \n** a pointer to an instance of the [sqlite3_mem_methods] structure.\n** The argument specifies\n** alternative low-level memory allocation routines to be used in place of\n** the memory allocation routines built into SQLite.)^ ^SQLite makes\n** its own private copy of the content of the [sqlite3_mem_methods] structure\n** before the [sqlite3_config()] call returns.</dd>\n**\n** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>\n** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which\n** is a pointer to an instance of the [sqlite3_mem_methods] structure.\n** The [sqlite3_mem_methods]\n** structure is filled with the currently defined memory allocation routines.)^\n** This option can be used to overload the default memory allocation\n** routines with a wrapper that simulations memory allocation failure or\n** tracks memory usage, for example. </dd>\n**\n** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>\n** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of\n** type int, interpreted as a boolean, which if true provides a hint to\n** SQLite that it should avoid large memory allocations if possible.\n** SQLite will run faster if it is free to make large memory allocations,\n** but some application might prefer to run slower in exchange for\n** guarantees about memory fragmentation that are possible if large\n** allocations are avoided.  This hint is normally off.\n** </dd>\n**\n** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>\n** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,\n** interpreted as a boolean, which enables or disables the collection of\n** memory allocation statistics. ^(When memory allocation statistics are\n** disabled, the following SQLite interfaces become non-operational:\n**   <ul>\n**   <li> [sqlite3_hard_heap_limit64()]\n**   <li> [sqlite3_memory_used()]\n**   <li> [sqlite3_memory_highwater()]\n**   <li> [sqlite3_soft_heap_limit64()]\n**   <li> [sqlite3_status64()]\n**   </ul>)^\n** ^Memory allocation statistics are enabled by default unless SQLite is\n** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory\n** allocation statistics are disabled by default.\n** </dd>\n**\n** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>\n** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.\n** </dd>\n**\n** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>\n** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool\n** that SQLite can use for the database page cache with the default page\n** cache implementation.  \n** This configuration option is a no-op if an application-defined page\n** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].\n** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to\n** 8-byte aligned memory (pMem), the size of each page cache line (sz),\n** and the number of cache lines (N).\n** The sz argument should be the size of the largest database page\n** (a power of two between 512 and 65536) plus some extra bytes for each\n** page header.  ^The number of extra bytes needed by the page header\n** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].\n** ^It is harmless, apart from the wasted memory,\n** for the sz parameter to be larger than necessary.  The pMem\n** argument must be either a NULL pointer or a pointer to an 8-byte\n** aligned block of memory of at least sz*N bytes, otherwise\n** subsequent behavior is undefined.\n** ^When pMem is not NULL, SQLite will strive to use the memory provided\n** to satisfy page cache needs, falling back to [sqlite3_malloc()] if\n** a page cache line is larger than sz bytes or if all of the pMem buffer\n** is exhausted.\n** ^If pMem is NULL and N is non-zero, then each database connection\n** does an initial bulk allocation for page cache memory\n** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or\n** of -1024*N bytes if N is negative, . ^If additional\n** page cache memory is needed beyond what is provided by the initial\n** allocation, then SQLite goes to [sqlite3_malloc()] separately for each\n** additional cache line. </dd>\n**\n** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>\n** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer \n** that SQLite will use for all of its dynamic memory allocation needs\n** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].\n** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled\n** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns\n** [SQLITE_ERROR] if invoked otherwise.\n** ^There are three arguments to SQLITE_CONFIG_HEAP:\n** An 8-byte aligned pointer to the memory,\n** the number of bytes in the memory buffer, and the minimum allocation size.\n** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts\n** to using its default memory allocator (the system malloc() implementation),\n** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the\n** memory pointer is not NULL then the alternative memory\n** allocator is engaged to handle all of SQLites memory allocation needs.\n** The first pointer (the memory pointer) must be aligned to an 8-byte\n** boundary or subsequent behavior of SQLite will be undefined.\n** The minimum allocation size is capped at 2**12. Reasonable values\n** for the minimum allocation size are 2**5 through 2**8.</dd>\n**\n** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>\n** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a\n** pointer to an instance of the [sqlite3_mutex_methods] structure.\n** The argument specifies alternative low-level mutex routines to be used\n** in place the mutex routines built into SQLite.)^  ^SQLite makes a copy of\n** the content of the [sqlite3_mutex_methods] structure before the call to\n** [sqlite3_config()] returns. ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** the entire mutexing subsystem is omitted from the build and hence calls to\n** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will\n** return [SQLITE_ERROR].</dd>\n**\n** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>\n** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which\n** is a pointer to an instance of the [sqlite3_mutex_methods] structure.  The\n** [sqlite3_mutex_methods]\n** structure is filled with the currently defined mutex routines.)^\n** This option can be used to overload the default mutex allocation\n** routines with a wrapper used to track mutex usage for performance\n** profiling or testing, for example.   ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** the entire mutexing subsystem is omitted from the build and hence calls to\n** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will\n** return [SQLITE_ERROR].</dd>\n**\n** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>\n** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine\n** the default size of lookaside memory on each [database connection].\n** The first argument is the\n** size of each lookaside buffer slot and the second is the number of\n** slots allocated to each database connection.)^  ^(SQLITE_CONFIG_LOOKASIDE\n** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]\n** option to [sqlite3_db_config()] can be used to change the lookaside\n** configuration on individual connections.)^ </dd>\n**\n** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>\n** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is \n** a pointer to an [sqlite3_pcache_methods2] object.  This object specifies\n** the interface to a custom page cache implementation.)^\n** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>\n**\n** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>\n** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which\n** is a pointer to an [sqlite3_pcache_methods2] object.  SQLite copies of\n** the current page cache implementation into that object.)^ </dd>\n**\n** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>\n** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite\n** global [error log].\n** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a\n** function with a call signature of void(*)(void*,int,const char*), \n** and a pointer to void. ^If the function pointer is not NULL, it is\n** invoked by [sqlite3_log()] to process each logging event.  ^If the\n** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.\n** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is\n** passed through as the first parameter to the application-defined logger\n** function whenever that function is invoked.  ^The second parameter to\n** the logger function is a copy of the first parameter to the corresponding\n** [sqlite3_log()] call and is intended to be a [result code] or an\n** [extended result code].  ^The third parameter passed to the logger is\n** log message after formatting via [sqlite3_snprintf()].\n** The SQLite logging interface is not reentrant; the logger function\n** supplied by the application must not invoke any SQLite interface.\n** In a multi-threaded application, the application-defined logger\n** function must be threadsafe. </dd>\n**\n** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI\n** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.\n** If non-zero, then URI handling is globally enabled. If the parameter is zero,\n** then URI handling is globally disabled.)^ ^If URI handling is globally\n** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],\n** [sqlite3_open16()] or\n** specified as part of [ATTACH] commands are interpreted as URIs, regardless\n** of whether or not the [SQLITE_OPEN_URI] flag is set when the database\n** connection is opened. ^If it is globally disabled, filenames are\n** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the\n** database connection is opened. ^(By default, URI handling is globally\n** disabled. The default value may be changed by compiling with the\n** [SQLITE_USE_URI] symbol defined.)^\n**\n** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN\n** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer\n** argument which is interpreted as a boolean in order to enable or disable\n** the use of covering indices for full table scans in the query optimizer.\n** ^The default setting is determined\n** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is \"on\"\n** if that compile-time option is omitted.\n** The ability to disable the use of covering indices for full table scans\n** is because some incorrectly coded legacy applications might malfunction\n** when the optimization is enabled.  Providing the ability to\n** disable the optimization allows the older, buggy application code to work\n** without change even with newer versions of SQLite.\n**\n** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]\n** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE\n** <dd> These options are obsolete and should not be used by new code.\n** They are retained for backwards compatibility but are now no-ops.\n** </dd>\n**\n** [[SQLITE_CONFIG_SQLLOG]]\n** <dt>SQLITE_CONFIG_SQLLOG\n** <dd>This option is only available if sqlite is compiled with the\n** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should\n** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).\n** The second should be of type (void*). The callback is invoked by the library\n** in three separate circumstances, identified by the value passed as the\n** fourth parameter. If the fourth parameter is 0, then the database connection\n** passed as the second argument has just been opened. The third argument\n** points to a buffer containing the name of the main database file. If the\n** fourth parameter is 1, then the SQL statement that the third parameter\n** points to has just been executed. Or, if the fourth parameter is 2, then\n** the connection being passed as the second parameter is being closed. The\n** third parameter is passed NULL In this case.  An example of using this\n** configuration option can be seen in the \"test_sqllog.c\" source file in\n** the canonical SQLite source tree.</dd>\n**\n** [[SQLITE_CONFIG_MMAP_SIZE]]\n** <dt>SQLITE_CONFIG_MMAP_SIZE\n** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values\n** that are the default mmap size limit (the default setting for\n** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.\n** ^The default setting can be overridden by each database connection using\n** either the [PRAGMA mmap_size] command, or by using the\n** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size\n** will be silently truncated if necessary so that it does not exceed the\n** compile-time maximum mmap size set by the\n** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^\n** ^If either argument to this option is negative, then that argument is\n** changed to its compile-time default.\n**\n** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]\n** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE\n** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is\n** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro\n** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value\n** that specifies the maximum size of the created heap.\n**\n** [[SQLITE_CONFIG_PCACHE_HDRSZ]]\n** <dt>SQLITE_CONFIG_PCACHE_HDRSZ\n** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which\n** is a pointer to an integer and writes into that integer the number of extra\n** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].\n** The amount of extra space required can change depending on the compiler,\n** target platform, and SQLite version.\n**\n** [[SQLITE_CONFIG_PMASZ]]\n** <dt>SQLITE_CONFIG_PMASZ\n** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which\n** is an unsigned integer and sets the \"Minimum PMA Size\" for the multithreaded\n** sorter to that integer.  The default minimum PMA Size is set by the\n** [SQLITE_SORTER_PMASZ] compile-time option.  New threads are launched\n** to help with sort operations when multithreaded sorting\n** is enabled (using the [PRAGMA threads] command) and the amount of content\n** to be sorted exceeds the page size times the minimum of the\n** [PRAGMA cache_size] setting and this value.\n**\n** [[SQLITE_CONFIG_STMTJRNL_SPILL]]\n** <dt>SQLITE_CONFIG_STMTJRNL_SPILL\n** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which\n** becomes the [statement journal] spill-to-disk threshold.  \n** [Statement journals] are held in memory until their size (in bytes)\n** exceeds this threshold, at which point they are written to disk.\n** Or if the threshold is -1, statement journals are always held\n** exclusively in memory.\n** Since many statement journals never become large, setting the spill\n** threshold to a value such as 64KiB can greatly reduce the amount of\n** I/O required to support statement rollback.\n** The default value for this setting is controlled by the\n** [SQLITE_STMTJRNL_SPILL] compile-time option.\n**\n** [[SQLITE_CONFIG_SORTERREF_SIZE]]\n** <dt>SQLITE_CONFIG_SORTERREF_SIZE\n** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter\n** of type (int) - the new value of the sorter-reference size threshold.\n** Usually, when SQLite uses an external sort to order records according\n** to an ORDER BY clause, all fields required by the caller are present in the\n** sorted records. However, if SQLite determines based on the declared type\n** of a table column that its values are likely to be very large - larger\n** than the configured sorter-reference size threshold - then a reference\n** is stored in each sorted record and the required column values loaded\n** from the database as records are returned in sorted order. The default\n** value for this option is to never use this optimization. Specifying a \n** negative value for this option restores the default behaviour.\n** This option is only available if SQLite is compiled with the\n** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.\n**\n** [[SQLITE_CONFIG_MEMDB_MAXSIZE]]\n** <dt>SQLITE_CONFIG_MEMDB_MAXSIZE\n** <dd>The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter\n** [sqlite3_int64] parameter which is the default maximum size for an in-memory\n** database created using [sqlite3_deserialize()].  This default maximum\n** size can be adjusted up or down for individual databases using the\n** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control].  If this\n** configuration setting is never used, then the default maximum is determined\n** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option.  If that\n** compile-time option is not set, then the default maximum is 1073741824.\n** </dl>\n*/\n#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */\n#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */\n#define SQLITE_CONFIG_SERIALIZED    3  /* nil */\n#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */\n#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */\n#define SQLITE_CONFIG_SCRATCH       6  /* No longer used */\n#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */\n#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */\n#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */\n#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */\n#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */\n/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ \n#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */\n#define SQLITE_CONFIG_PCACHE       14  /* no-op */\n#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */\n#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */\n#define SQLITE_CONFIG_URI          17  /* int */\n#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */\n#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */\n#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */\n#define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */\n#define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */\n#define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */\n#define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */\n#define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */\n#define SQLITE_CONFIG_STMTJRNL_SPILL      26  /* int nByte */\n#define SQLITE_CONFIG_SMALL_MALLOC        27  /* boolean */\n#define SQLITE_CONFIG_SORTERREF_SIZE      28  /* int nByte */\n#define SQLITE_CONFIG_MEMDB_MAXSIZE       29  /* sqlite3_int64 */\n\n/*\n** CAPI3REF: Database Connection Configuration Options\n**\n** These constants are the available integer configuration options that\n** can be passed as the second argument to the [sqlite3_db_config()] interface.\n**\n** New configuration options may be added in future releases of SQLite.\n** Existing configuration options might be discontinued.  Applications\n** should check the return code from [sqlite3_db_config()] to make sure that\n** the call worked.  ^The [sqlite3_db_config()] interface will return a\n** non-zero [error code] if a discontinued or unsupported configuration option\n** is invoked.\n**\n** <dl>\n** [[SQLITE_DBCONFIG_LOOKASIDE]]\n** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>\n** <dd> ^This option takes three additional arguments that determine the \n** [lookaside memory allocator] configuration for the [database connection].\n** ^The first argument (the third parameter to [sqlite3_db_config()] is a\n** pointer to a memory buffer to use for lookaside memory.\n** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb\n** may be NULL in which case SQLite will allocate the\n** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the\n** size of each lookaside buffer slot.  ^The third argument is the number of\n** slots.  The size of the buffer in the first argument must be greater than\n** or equal to the product of the second and third arguments.  The buffer\n** must be aligned to an 8-byte boundary.  ^If the second argument to\n** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally\n** rounded down to the next smaller multiple of 8.  ^(The lookaside memory\n** configuration for a database connection can only be changed when that\n** connection is not currently using lookaside memory, or in other words\n** when the \"current value\" returned by\n** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.\n** Any attempt to change the lookaside memory configuration when lookaside\n** memory is in use leaves the configuration unchanged and returns \n** [SQLITE_BUSY].)^</dd>\n**\n** [[SQLITE_DBCONFIG_ENABLE_FKEY]]\n** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>\n** <dd> ^This option is used to enable or disable the enforcement of\n** [foreign key constraints].  There should be two additional arguments.\n** The first argument is an integer which is 0 to disable FK enforcement,\n** positive to enable FK enforcement or negative to leave FK enforcement\n** unchanged.  The second parameter is a pointer to an integer into which\n** is written 0 or 1 to indicate whether FK enforcement is off or on\n** following this call.  The second parameter may be a NULL pointer, in\n** which case the FK enforcement setting is not reported back. </dd>\n**\n** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]]\n** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>\n** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].\n** There should be two additional arguments.\n** The first argument is an integer which is 0 to disable triggers,\n** positive to enable triggers or negative to leave the setting unchanged.\n** The second parameter is a pointer to an integer into which\n** is written 0 or 1 to indicate whether triggers are disabled or enabled\n** following this call.  The second parameter may be a NULL pointer, in\n** which case the trigger setting is not reported back. </dd>\n**\n** [[SQLITE_DBCONFIG_ENABLE_VIEW]]\n** <dt>SQLITE_DBCONFIG_ENABLE_VIEW</dt>\n** <dd> ^This option is used to enable or disable [CREATE VIEW | views].\n** There should be two additional arguments.\n** The first argument is an integer which is 0 to disable views,\n** positive to enable views or negative to leave the setting unchanged.\n** The second parameter is a pointer to an integer into which\n** is written 0 or 1 to indicate whether views are disabled or enabled\n** following this call.  The second parameter may be a NULL pointer, in\n** which case the view setting is not reported back. </dd>\n**\n** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]\n** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>\n** <dd> ^This option is used to enable or disable the\n** [fts3_tokenizer()] function which is part of the\n** [FTS3] full-text search engine extension.\n** There should be two additional arguments.\n** The first argument is an integer which is 0 to disable fts3_tokenizer() or\n** positive to enable fts3_tokenizer() or negative to leave the setting\n** unchanged.\n** The second parameter is a pointer to an integer into which\n** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled\n** following this call.  The second parameter may be a NULL pointer, in\n** which case the new setting is not reported back. </dd>\n**\n** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]\n** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>\n** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]\n** interface independently of the [load_extension()] SQL function.\n** The [sqlite3_enable_load_extension()] API enables or disables both the\n** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].\n** There should be two additional arguments.\n** When the first argument to this interface is 1, then only the C-API is\n** enabled and the SQL function remains disabled.  If the first argument to\n** this interface is 0, then both the C-API and the SQL function are disabled.\n** If the first argument is -1, then no changes are made to state of either the\n** C-API or the SQL function.\n** The second parameter is a pointer to an integer into which\n** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface\n** is disabled or enabled following this call.  The second parameter may\n** be a NULL pointer, in which case the new setting is not reported back.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>\n** <dd> ^This option is used to change the name of the \"main\" database\n** schema.  ^The sole argument is a pointer to a constant UTF8 string\n** which will become the new schema name in place of \"main\".  ^SQLite\n** does not make a copy of the new main schema name string, so the application\n** must ensure that the argument passed into this DBCONFIG option is unchanged\n** until after the database connection closes.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]] \n** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>\n** <dd> Usually, when a database in wal mode is closed or detached from a \n** database handle, SQLite checks if this will mean that there are now no \n** connections at all to the database. If so, it performs a checkpoint \n** operation before closing the connection. This option may be used to\n** override this behaviour. The first parameter passed to this operation\n** is an integer - positive to disable checkpoints-on-close, or zero (the\n** default) to enable them, and negative to leave the setting unchanged.\n** The second parameter is a pointer to an integer\n** into which is written 0 or 1 to indicate whether checkpoints-on-close\n** have been disabled - 0 if they are not disabled, 1 if they are.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>\n** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates\n** the [query planner stability guarantee] (QPSG).  When the QPSG is active,\n** a single SQL query statement will always use the same algorithm regardless\n** of values of [bound parameters].)^ The QPSG disables some query optimizations\n** that look at the values of bound parameters, which can make some queries\n** slower.  But the QPSG has the advantage of more predictable behavior.  With\n** the QPSG active, SQLite will always use the same query plan in the field as\n** was used during testing in the lab.\n** The first argument to this setting is an integer which is 0 to disable \n** the QPSG, positive to enable QPSG, or negative to leave the setting\n** unchanged. The second parameter is a pointer to an integer into which\n** is written 0 or 1 to indicate whether the QPSG is disabled or enabled\n** following this call.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>\n** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not \n** include output for any operations performed by trigger programs. This\n** option is used to set or clear (the default) a flag that governs this\n** behavior. The first parameter passed to this operation is an integer -\n** positive to enable output for trigger programs, or zero to disable it,\n** or negative to leave the setting unchanged.\n** The second parameter is a pointer to an integer into which is written \n** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if \n** it is not disabled, 1 if it is.  \n** </dd>\n**\n** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>\n** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run\n** [VACUUM] in order to reset a database back to an empty database\n** with no schema and no content. The following process works even for\n** a badly corrupted database file:\n** <ol>\n** <li> If the database connection is newly opened, make sure it has read the\n**      database schema by preparing then discarding some query against the\n**      database, or calling sqlite3_table_column_metadata(), ignoring any\n**      errors.  This step is only necessary if the application desires to keep\n**      the database in WAL mode after the reset if it was in WAL mode before\n**      the reset.  \n** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);\n** <li> [sqlite3_exec](db, \"[VACUUM]\", 0, 0, 0);\n** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);\n** </ol>\n** Because resetting a database is destructive and irreversible, the\n** process requires the use of this obscure API and multiple steps to help\n** ensure that it does not happen by accident.\n**\n** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt>\n** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the\n** \"defensive\" flag for a database connection.  When the defensive\n** flag is enabled, language features that allow ordinary SQL to \n** deliberately corrupt the database file are disabled.  The disabled\n** features include but are not limited to the following:\n** <ul>\n** <li> The [PRAGMA writable_schema=ON] statement.\n** <li> The [PRAGMA journal_mode=OFF] statement.\n** <li> Writes to the [sqlite_dbpage] virtual table.\n** <li> Direct writes to [shadow tables].\n** </ul>\n** </dd>\n**\n** [[SQLITE_DBCONFIG_WRITABLE_SCHEMA]] <dt>SQLITE_DBCONFIG_WRITABLE_SCHEMA</dt>\n** <dd>The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the\n** \"writable_schema\" flag. This has the same effect and is logically equivalent\n** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF].\n** The first argument to this setting is an integer which is 0 to disable \n** the writable_schema, positive to enable writable_schema, or negative to\n** leave the setting unchanged. The second parameter is a pointer to an\n** integer into which is written 0 or 1 to indicate whether the writable_schema\n** is enabled or disabled following this call.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]]\n** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt>\n** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates\n** the legacy behavior of the [ALTER TABLE RENAME] command such it\n** behaves as it did prior to [version 3.24.0] (2018-06-04).  See the\n** \"Compatibility Notice\" on the [ALTER TABLE RENAME documentation] for\n** additional information. This feature can also be turned on and off\n** using the [PRAGMA legacy_alter_table] statement.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_DQS_DML]]\n** <dt>SQLITE_DBCONFIG_DQS_DML</td>\n** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates\n** the legacy [double-quoted string literal] misfeature for DML statements\n** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The\n** default value of this setting is determined by the [-DSQLITE_DQS]\n** compile-time option.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_DQS_DDL]]\n** <dt>SQLITE_DBCONFIG_DQS_DDL</td>\n** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates\n** the legacy [double-quoted string literal] misfeature for DDL statements,\n** such as CREATE TABLE and CREATE INDEX. The\n** default value of this setting is determined by the [-DSQLITE_DQS]\n** compile-time option.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]]\n** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</td>\n** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to\n** assume that database schemas (the contents of the [sqlite_master] tables)\n** are untainted by malicious content.\n** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite\n** takes additional defensive steps to protect the application from harm\n** including:\n** <ul>\n** <li> Prohibit the use of SQL functions inside triggers, views,\n** CHECK constraints, DEFAULT clauses, expression indexes, \n** partial indexes, or generated columns\n** unless those functions are tagged with [SQLITE_INNOCUOUS].\n** <li> Prohibit the use of virtual tables inside of triggers or views\n** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS].\n** </ul>\n** This setting defaults to \"on\" for legacy compatibility, however\n** all applications are advised to turn it off if possible. This setting\n** can also be controlled using the [PRAGMA trusted_schema] statement.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]]\n** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</td>\n** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates\n** the legacy file format flag.  When activated, this flag causes all newly\n** created database file to have a schema format version number (the 4-byte\n** integer found at offset 44 into the database header) of 1.  This in turn\n** means that the resulting database file will be readable and writable by\n** any SQLite version back to 3.0.0 ([dateof:3.0.0]).  Without this setting,\n** newly created databases are generally not understandable by SQLite versions\n** prior to 3.3.0 ([dateof:3.3.0]).  As these words are written, there\n** is now scarcely any need to generated database files that are compatible \n** all the way back to version 3.0.0, and so this setting is of little\n** practical use, but is provided so that SQLite can continue to claim the\n** ability to generate new database files that are compatible with  version\n** 3.0.0.\n** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on,\n** the [VACUUM] command will fail with an obscure error when attempting to\n** process a table with generated columns and a descending index.  This is\n** not considered a bug since SQLite versions 3.3.0 and earlier do not support\n** either generated columns or decending indexes.\n** </dd>\n** </dl>\n*/\n#define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */\n#define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */\n#define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */\n#define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */\n#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */\n#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */\n#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      1006 /* int int* */\n#define SQLITE_DBCONFIG_ENABLE_QPSG           1007 /* int int* */\n#define SQLITE_DBCONFIG_TRIGGER_EQP           1008 /* int int* */\n#define SQLITE_DBCONFIG_RESET_DATABASE        1009 /* int int* */\n#define SQLITE_DBCONFIG_DEFENSIVE             1010 /* int int* */\n#define SQLITE_DBCONFIG_WRITABLE_SCHEMA       1011 /* int int* */\n#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    1012 /* int int* */\n#define SQLITE_DBCONFIG_DQS_DML               1013 /* int int* */\n#define SQLITE_DBCONFIG_DQS_DDL               1014 /* int int* */\n#define SQLITE_DBCONFIG_ENABLE_VIEW           1015 /* int int* */\n#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    1016 /* int int* */\n#define SQLITE_DBCONFIG_TRUSTED_SCHEMA        1017 /* int int* */\n#define SQLITE_DBCONFIG_MAX                   1017 /* Largest DBCONFIG */\n\n/*\n** CAPI3REF: Enable Or Disable Extended Result Codes\n** METHOD: sqlite3\n**\n** ^The sqlite3_extended_result_codes() routine enables or disables the\n** [extended result codes] feature of SQLite. ^The extended result\n** codes are disabled by default for historical compatibility.\n*/\nSQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);\n\n/*\n** CAPI3REF: Last Insert Rowid\n** METHOD: sqlite3\n**\n** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)\n** has a unique 64-bit signed\n** integer key called the [ROWID | \"rowid\"]. ^The rowid is always available\n** as an undeclared column named ROWID, OID, or _ROWID_ as long as those\n** names are not also used by explicitly declared columns. ^If\n** the table has a column of type [INTEGER PRIMARY KEY] then that column\n** is another alias for the rowid.\n**\n** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of\n** the most recent successful [INSERT] into a rowid table or [virtual table]\n** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not\n** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred \n** on the database connection D, then sqlite3_last_insert_rowid(D) returns \n** zero.\n**\n** As well as being set automatically as rows are inserted into database\n** tables, the value returned by this function may be set explicitly by\n** [sqlite3_set_last_insert_rowid()]\n**\n** Some virtual table implementations may INSERT rows into rowid tables as\n** part of committing a transaction (e.g. to flush data accumulated in memory\n** to disk). In this case subsequent calls to this function return the rowid\n** associated with these internal INSERT operations, which leads to \n** unintuitive results. Virtual table implementations that do write to rowid\n** tables in this way can avoid this problem by restoring the original \n** rowid value using [sqlite3_set_last_insert_rowid()] before returning \n** control to the user.\n**\n** ^(If an [INSERT] occurs within a trigger then this routine will \n** return the [rowid] of the inserted row as long as the trigger is \n** running. Once the trigger program ends, the value returned \n** by this routine reverts to what it was before the trigger was fired.)^\n**\n** ^An [INSERT] that fails due to a constraint violation is not a\n** successful [INSERT] and does not change the value returned by this\n** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,\n** and INSERT OR ABORT make no changes to the return value of this\n** routine when their insertion fails.  ^(When INSERT OR REPLACE\n** encounters a constraint violation, it does not fail.  The\n** INSERT continues to completion after deleting rows that caused\n** the constraint problem so INSERT OR REPLACE will always change\n** the return value of this interface.)^\n**\n** ^For the purposes of this routine, an [INSERT] is considered to\n** be successful even if it is subsequently rolled back.\n**\n** This function is accessible to SQL statements via the\n** [last_insert_rowid() SQL function].\n**\n** If a separate thread performs a new [INSERT] on the same\n** database connection while the [sqlite3_last_insert_rowid()]\n** function is running and thus changes the last insert [rowid],\n** then the value returned by [sqlite3_last_insert_rowid()] is\n** unpredictable and might not equal either the old or the new\n** last insert [rowid].\n*/\nSQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);\n\n/*\n** CAPI3REF: Set the Last Insert Rowid value.\n** METHOD: sqlite3\n**\n** The sqlite3_set_last_insert_rowid(D, R) method allows the application to\n** set the value returned by calling sqlite3_last_insert_rowid(D) to R \n** without inserting a row into the database.\n*/\nSQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);\n\n/*\n** CAPI3REF: Count The Number Of Rows Modified\n** METHOD: sqlite3\n**\n** ^This function returns the number of rows modified, inserted or\n** deleted by the most recently completed INSERT, UPDATE or DELETE\n** statement on the database connection specified by the only parameter.\n** ^Executing any other type of SQL statement does not modify the value\n** returned by this function.\n**\n** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are\n** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], \n** [foreign key actions] or [REPLACE] constraint resolution are not counted.\n** \n** Changes to a view that are intercepted by \n** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value \n** returned by sqlite3_changes() immediately after an INSERT, UPDATE or \n** DELETE statement run on a view is always zero. Only changes made to real \n** tables are counted.\n**\n** Things are more complicated if the sqlite3_changes() function is\n** executed while a trigger program is running. This may happen if the\n** program uses the [changes() SQL function], or if some other callback\n** function invokes sqlite3_changes() directly. Essentially:\n** \n** <ul>\n**   <li> ^(Before entering a trigger program the value returned by\n**        sqlite3_changes() function is saved. After the trigger program \n**        has finished, the original value is restored.)^\n** \n**   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE \n**        statement sets the value returned by sqlite3_changes() \n**        upon completion as normal. Of course, this value will not include \n**        any changes performed by sub-triggers, as the sqlite3_changes() \n**        value will be saved and restored after each sub-trigger has run.)^\n** </ul>\n** \n** ^This means that if the changes() SQL function (or similar) is used\n** by the first INSERT, UPDATE or DELETE statement within a trigger, it \n** returns the value as set when the calling statement began executing.\n** ^If it is used by the second or subsequent such statement within a trigger \n** program, the value returned reflects the number of rows modified by the \n** previous INSERT, UPDATE or DELETE statement within the same trigger.\n**\n** If a separate thread makes changes on the same database connection\n** while [sqlite3_changes()] is running then the value returned\n** is unpredictable and not meaningful.\n**\n** See also:\n** <ul>\n** <li> the [sqlite3_total_changes()] interface\n** <li> the [count_changes pragma]\n** <li> the [changes() SQL function]\n** <li> the [data_version pragma]\n** </ul>\n*/\nSQLITE_API int sqlite3_changes(sqlite3*);\n\n/*\n** CAPI3REF: Total Number Of Rows Modified\n** METHOD: sqlite3\n**\n** ^This function returns the total number of rows inserted, modified or\n** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed\n** since the database connection was opened, including those executed as\n** part of trigger programs. ^Executing any other type of SQL statement\n** does not affect the value returned by sqlite3_total_changes().\n** \n** ^Changes made as part of [foreign key actions] are included in the\n** count, but those made as part of REPLACE constraint resolution are\n** not. ^Changes to a view that are intercepted by INSTEAD OF triggers \n** are not counted.\n**\n** The [sqlite3_total_changes(D)] interface only reports the number\n** of rows that changed due to SQL statement run against database\n** connection D.  Any changes by other database connections are ignored.\n** To detect changes against a database file from other database\n** connections use the [PRAGMA data_version] command or the\n** [SQLITE_FCNTL_DATA_VERSION] [file control].\n** \n** If a separate thread makes changes on the same database connection\n** while [sqlite3_total_changes()] is running then the value\n** returned is unpredictable and not meaningful.\n**\n** See also:\n** <ul>\n** <li> the [sqlite3_changes()] interface\n** <li> the [count_changes pragma]\n** <li> the [changes() SQL function]\n** <li> the [data_version pragma]\n** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control]\n** </ul>\n*/\nSQLITE_API int sqlite3_total_changes(sqlite3*);\n\n/*\n** CAPI3REF: Interrupt A Long-Running Query\n** METHOD: sqlite3\n**\n** ^This function causes any pending database operation to abort and\n** return at its earliest opportunity. This routine is typically\n** called in response to a user action such as pressing \"Cancel\"\n** or Ctrl-C where the user wants a long query operation to halt\n** immediately.\n**\n** ^It is safe to call this routine from a thread different from the\n** thread that is currently running the database operation.  But it\n** is not safe to call this routine with a [database connection] that\n** is closed or might close before sqlite3_interrupt() returns.\n**\n** ^If an SQL operation is very nearly finished at the time when\n** sqlite3_interrupt() is called, then it might not have an opportunity\n** to be interrupted and might continue to completion.\n**\n** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].\n** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE\n** that is inside an explicit transaction, then the entire transaction\n** will be rolled back automatically.\n**\n** ^The sqlite3_interrupt(D) call is in effect until all currently running\n** SQL statements on [database connection] D complete.  ^Any new SQL statements\n** that are started after the sqlite3_interrupt() call and before the \n** running statement count reaches zero are interrupted as if they had been\n** running prior to the sqlite3_interrupt() call.  ^New SQL statements\n** that are started after the running statement count reaches zero are\n** not effected by the sqlite3_interrupt().\n** ^A call to sqlite3_interrupt(D) that occurs when there are no running\n** SQL statements is a no-op and has no effect on SQL statements\n** that are started after the sqlite3_interrupt() call returns.\n*/\nSQLITE_API void sqlite3_interrupt(sqlite3*);\n\n/*\n** CAPI3REF: Determine If An SQL Statement Is Complete\n**\n** These routines are useful during command-line input to determine if the\n** currently entered text seems to form a complete SQL statement or\n** if additional input is needed before sending the text into\n** SQLite for parsing.  ^These routines return 1 if the input string\n** appears to be a complete SQL statement.  ^A statement is judged to be\n** complete if it ends with a semicolon token and is not a prefix of a\n** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within\n** string literals or quoted identifier names or comments are not\n** independent tokens (they are part of the token in which they are\n** embedded) and thus do not count as a statement terminator.  ^Whitespace\n** and comments that follow the final semicolon are ignored.\n**\n** ^These routines return 0 if the statement is incomplete.  ^If a\n** memory allocation fails, then SQLITE_NOMEM is returned.\n**\n** ^These routines do not parse the SQL statements thus\n** will not detect syntactically incorrect SQL.\n**\n** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior \n** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked\n** automatically by sqlite3_complete16().  If that initialization fails,\n** then the return value from sqlite3_complete16() will be non-zero\n** regardless of whether or not the input SQL is complete.)^\n**\n** The input to [sqlite3_complete()] must be a zero-terminated\n** UTF-8 string.\n**\n** The input to [sqlite3_complete16()] must be a zero-terminated\n** UTF-16 string in native byte order.\n*/\nSQLITE_API int sqlite3_complete(const char *sql);\nSQLITE_API int sqlite3_complete16(const void *sql);\n\n/*\n** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors\n** KEYWORDS: {busy-handler callback} {busy handler}\n** METHOD: sqlite3\n**\n** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X\n** that might be invoked with argument P whenever\n** an attempt is made to access a database table associated with\n** [database connection] D when another thread\n** or process has the table locked.\n** The sqlite3_busy_handler() interface is used to implement\n** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].\n**\n** ^If the busy callback is NULL, then [SQLITE_BUSY]\n** is returned immediately upon encountering the lock.  ^If the busy callback\n** is not NULL, then the callback might be invoked with two arguments.\n**\n** ^The first argument to the busy handler is a copy of the void* pointer which\n** is the third argument to sqlite3_busy_handler().  ^The second argument to\n** the busy handler callback is the number of times that the busy handler has\n** been invoked previously for the same locking event.  ^If the\n** busy callback returns 0, then no additional attempts are made to\n** access the database and [SQLITE_BUSY] is returned\n** to the application.\n** ^If the callback returns non-zero, then another attempt\n** is made to access the database and the cycle repeats.\n**\n** The presence of a busy handler does not guarantee that it will be invoked\n** when there is lock contention. ^If SQLite determines that invoking the busy\n** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]\n** to the application instead of invoking the \n** busy handler.\n** Consider a scenario where one process is holding a read lock that\n** it is trying to promote to a reserved lock and\n** a second process is holding a reserved lock that it is trying\n** to promote to an exclusive lock.  The first process cannot proceed\n** because it is blocked by the second and the second process cannot\n** proceed because it is blocked by the first.  If both processes\n** invoke the busy handlers, neither will make any progress.  Therefore,\n** SQLite returns [SQLITE_BUSY] for the first process, hoping that this\n** will induce the first process to release its read lock and allow\n** the second process to proceed.\n**\n** ^The default busy callback is NULL.\n**\n** ^(There can only be a single busy handler defined for each\n** [database connection].  Setting a new busy handler clears any\n** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]\n** or evaluating [PRAGMA busy_timeout=N] will change the\n** busy handler and thus clear any previously set busy handler.\n**\n** The busy callback should not take any actions which modify the\n** database connection that invoked the busy handler.  In other words,\n** the busy handler is not reentrant.  Any such actions\n** result in undefined behavior.\n** \n** A busy handler must not close the database connection\n** or [prepared statement] that invoked the busy handler.\n*/\nSQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);\n\n/*\n** CAPI3REF: Set A Busy Timeout\n** METHOD: sqlite3\n**\n** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps\n** for a specified amount of time when a table is locked.  ^The handler\n** will sleep multiple times until at least \"ms\" milliseconds of sleeping\n** have accumulated.  ^After at least \"ms\" milliseconds of sleeping,\n** the handler returns 0 which causes [sqlite3_step()] to return\n** [SQLITE_BUSY].\n**\n** ^Calling this routine with an argument less than or equal to zero\n** turns off all busy handlers.\n**\n** ^(There can only be a single busy handler for a particular\n** [database connection] at any given moment.  If another busy handler\n** was defined  (using [sqlite3_busy_handler()]) prior to calling\n** this routine, that other busy handler is cleared.)^\n**\n** See also:  [PRAGMA busy_timeout]\n*/\nSQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);\n\n/*\n** CAPI3REF: Convenience Routines For Running Queries\n** METHOD: sqlite3\n**\n** This is a legacy interface that is preserved for backwards compatibility.\n** Use of this interface is not recommended.\n**\n** Definition: A <b>result table</b> is memory data structure created by the\n** [sqlite3_get_table()] interface.  A result table records the\n** complete query results from one or more queries.\n**\n** The table conceptually has a number of rows and columns.  But\n** these numbers are not part of the result table itself.  These\n** numbers are obtained separately.  Let N be the number of rows\n** and M be the number of columns.\n**\n** A result table is an array of pointers to zero-terminated UTF-8 strings.\n** There are (N+1)*M elements in the array.  The first M pointers point\n** to zero-terminated strings that  contain the names of the columns.\n** The remaining entries all point to query results.  NULL values result\n** in NULL pointers.  All other values are in their UTF-8 zero-terminated\n** string representation as returned by [sqlite3_column_text()].\n**\n** A result table might consist of one or more memory allocations.\n** It is not safe to pass a result table directly to [sqlite3_free()].\n** A result table should be deallocated using [sqlite3_free_table()].\n**\n** ^(As an example of the result table format, suppose a query result\n** is as follows:\n**\n** <blockquote><pre>\n**        Name        | Age\n**        -----------------------\n**        Alice       | 43\n**        Bob         | 28\n**        Cindy       | 21\n** </pre></blockquote>\n**\n** There are two columns (M==2) and three rows (N==3).  Thus the\n** result table has 8 entries.  Suppose the result table is stored\n** in an array named azResult.  Then azResult holds this content:\n**\n** <blockquote><pre>\n**        azResult&#91;0] = \"Name\";\n**        azResult&#91;1] = \"Age\";\n**        azResult&#91;2] = \"Alice\";\n**        azResult&#91;3] = \"43\";\n**        azResult&#91;4] = \"Bob\";\n**        azResult&#91;5] = \"28\";\n**        azResult&#91;6] = \"Cindy\";\n**        azResult&#91;7] = \"21\";\n** </pre></blockquote>)^\n**\n** ^The sqlite3_get_table() function evaluates one or more\n** semicolon-separated SQL statements in the zero-terminated UTF-8\n** string of its 2nd parameter and returns a result table to the\n** pointer given in its 3rd parameter.\n**\n** After the application has finished with the result from sqlite3_get_table(),\n** it must pass the result table pointer to sqlite3_free_table() in order to\n** release the memory that was malloced.  Because of the way the\n** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling\n** function must not try to call [sqlite3_free()] directly.  Only\n** [sqlite3_free_table()] is able to release the memory properly and safely.\n**\n** The sqlite3_get_table() interface is implemented as a wrapper around\n** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access\n** to any internal data structures of SQLite.  It uses only the public\n** interface defined here.  As a consequence, errors that occur in the\n** wrapper layer outside of the internal [sqlite3_exec()] call are not\n** reflected in subsequent calls to [sqlite3_errcode()] or\n** [sqlite3_errmsg()].\n*/\nSQLITE_API int sqlite3_get_table(\n  sqlite3 *db,          /* An open database */\n  const char *zSql,     /* SQL to be evaluated */\n  char ***pazResult,    /* Results of the query */\n  int *pnRow,           /* Number of result rows written here */\n  int *pnColumn,        /* Number of result columns written here */\n  char **pzErrmsg       /* Error msg written here */\n);\nSQLITE_API void sqlite3_free_table(char **result);\n\n/*\n** CAPI3REF: Formatted String Printing Functions\n**\n** These routines are work-alikes of the \"printf()\" family of functions\n** from the standard C library.\n** These routines understand most of the common formatting options from\n** the standard library printf() \n** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).\n** See the [built-in printf()] documentation for details.\n**\n** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their\n** results into memory obtained from [sqlite3_malloc64()].\n** The strings returned by these two routines should be\n** released by [sqlite3_free()].  ^Both routines return a\n** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough\n** memory to hold the resulting string.\n**\n** ^(The sqlite3_snprintf() routine is similar to \"snprintf()\" from\n** the standard C library.  The result is written into the\n** buffer supplied as the second parameter whose size is given by\n** the first parameter. Note that the order of the\n** first two parameters is reversed from snprintf().)^  This is an\n** historical accident that cannot be fixed without breaking\n** backwards compatibility.  ^(Note also that sqlite3_snprintf()\n** returns a pointer to its buffer instead of the number of\n** characters actually written into the buffer.)^  We admit that\n** the number of characters written would be a more useful return\n** value but we cannot change the implementation of sqlite3_snprintf()\n** now without breaking compatibility.\n**\n** ^As long as the buffer size is greater than zero, sqlite3_snprintf()\n** guarantees that the buffer is always zero-terminated.  ^The first\n** parameter \"n\" is the total size of the buffer, including space for\n** the zero terminator.  So the longest string that can be completely\n** written will be n-1 characters.\n**\n** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().\n**\n** See also:  [built-in printf()], [printf() SQL function]\n*/\nSQLITE_API char *sqlite3_mprintf(const char*,...);\nSQLITE_API char *sqlite3_vmprintf(const char*, va_list);\nSQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);\nSQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);\n\n/*\n** CAPI3REF: Memory Allocation Subsystem\n**\n** The SQLite core uses these three routines for all of its own\n** internal memory allocation needs. \"Core\" in the previous sentence\n** does not include operating-system specific [VFS] implementation.  The\n** Windows VFS uses native malloc() and free() for some operations.\n**\n** ^The sqlite3_malloc() routine returns a pointer to a block\n** of memory at least N bytes in length, where N is the parameter.\n** ^If sqlite3_malloc() is unable to obtain sufficient free\n** memory, it returns a NULL pointer.  ^If the parameter N to\n** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns\n** a NULL pointer.\n**\n** ^The sqlite3_malloc64(N) routine works just like\n** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead\n** of a signed 32-bit integer.\n**\n** ^Calling sqlite3_free() with a pointer previously returned\n** by sqlite3_malloc() or sqlite3_realloc() releases that memory so\n** that it might be reused.  ^The sqlite3_free() routine is\n** a no-op if is called with a NULL pointer.  Passing a NULL pointer\n** to sqlite3_free() is harmless.  After being freed, memory\n** should neither be read nor written.  Even reading previously freed\n** memory might result in a segmentation fault or other severe error.\n** Memory corruption, a segmentation fault, or other severe error\n** might result if sqlite3_free() is called with a non-NULL pointer that\n** was not obtained from sqlite3_malloc() or sqlite3_realloc().\n**\n** ^The sqlite3_realloc(X,N) interface attempts to resize a\n** prior memory allocation X to be at least N bytes.\n** ^If the X parameter to sqlite3_realloc(X,N)\n** is a NULL pointer then its behavior is identical to calling\n** sqlite3_malloc(N).\n** ^If the N parameter to sqlite3_realloc(X,N) is zero or\n** negative then the behavior is exactly the same as calling\n** sqlite3_free(X).\n** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation\n** of at least N bytes in size or NULL if insufficient memory is available.\n** ^If M is the size of the prior allocation, then min(N,M) bytes\n** of the prior allocation are copied into the beginning of buffer returned\n** by sqlite3_realloc(X,N) and the prior allocation is freed.\n** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the\n** prior allocation is not freed.\n**\n** ^The sqlite3_realloc64(X,N) interfaces works the same as\n** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead\n** of a 32-bit signed integer.\n**\n** ^If X is a memory allocation previously obtained from sqlite3_malloc(),\n** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then\n** sqlite3_msize(X) returns the size of that memory allocation in bytes.\n** ^The value returned by sqlite3_msize(X) might be larger than the number\n** of bytes requested when X was allocated.  ^If X is a NULL pointer then\n** sqlite3_msize(X) returns zero.  If X points to something that is not\n** the beginning of memory allocation, or if it points to a formerly\n** valid memory allocation that has now been freed, then the behavior\n** of sqlite3_msize(X) is undefined and possibly harmful.\n**\n** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),\n** sqlite3_malloc64(), and sqlite3_realloc64()\n** is always aligned to at least an 8 byte boundary, or to a\n** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time\n** option is used.\n**\n** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]\n** must be either NULL or else pointers obtained from a prior\n** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have\n** not yet been released.\n**\n** The application must not read or write any part of\n** a block of memory after it has been released using\n** [sqlite3_free()] or [sqlite3_realloc()].\n*/\nSQLITE_API void *sqlite3_malloc(int);\nSQLITE_API void *sqlite3_malloc64(sqlite3_uint64);\nSQLITE_API void *sqlite3_realloc(void*, int);\nSQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);\nSQLITE_API void sqlite3_free(void*);\nSQLITE_API sqlite3_uint64 sqlite3_msize(void*);\n\n/*\n** CAPI3REF: Memory Allocator Statistics\n**\n** SQLite provides these two interfaces for reporting on the status\n** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]\n** routines, which form the built-in memory allocation subsystem.\n**\n** ^The [sqlite3_memory_used()] routine returns the number of bytes\n** of memory currently outstanding (malloced but not freed).\n** ^The [sqlite3_memory_highwater()] routine returns the maximum\n** value of [sqlite3_memory_used()] since the high-water mark\n** was last reset.  ^The values returned by [sqlite3_memory_used()] and\n** [sqlite3_memory_highwater()] include any overhead\n** added by SQLite in its implementation of [sqlite3_malloc()],\n** but not overhead added by the any underlying system library\n** routines that [sqlite3_malloc()] may call.\n**\n** ^The memory high-water mark is reset to the current value of\n** [sqlite3_memory_used()] if and only if the parameter to\n** [sqlite3_memory_highwater()] is true.  ^The value returned\n** by [sqlite3_memory_highwater(1)] is the high-water mark\n** prior to the reset.\n*/\nSQLITE_API sqlite3_int64 sqlite3_memory_used(void);\nSQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);\n\n/*\n** CAPI3REF: Pseudo-Random Number Generator\n**\n** SQLite contains a high-quality pseudo-random number generator (PRNG) used to\n** select random [ROWID | ROWIDs] when inserting new records into a table that\n** already uses the largest possible [ROWID].  The PRNG is also used for\n** the built-in random() and randomblob() SQL functions.  This interface allows\n** applications to access the same PRNG for other purposes.\n**\n** ^A call to this routine stores N bytes of randomness into buffer P.\n** ^The P parameter can be a NULL pointer.\n**\n** ^If this routine has not been previously called or if the previous\n** call had N less than one or a NULL pointer for P, then the PRNG is\n** seeded using randomness obtained from the xRandomness method of\n** the default [sqlite3_vfs] object.\n** ^If the previous call to this routine had an N of 1 or more and a\n** non-NULL P then the pseudo-randomness is generated\n** internally and without recourse to the [sqlite3_vfs] xRandomness\n** method.\n*/\nSQLITE_API void sqlite3_randomness(int N, void *P);\n\n/*\n** CAPI3REF: Compile-Time Authorization Callbacks\n** METHOD: sqlite3\n** KEYWORDS: {authorizer callback}\n**\n** ^This routine registers an authorizer callback with a particular\n** [database connection], supplied in the first argument.\n** ^The authorizer callback is invoked as SQL statements are being compiled\n** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],\n** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],\n** and [sqlite3_prepare16_v3()].  ^At various\n** points during the compilation process, as logic is being created\n** to perform various actions, the authorizer callback is invoked to\n** see if those actions are allowed.  ^The authorizer callback should\n** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the\n** specific action but allow the SQL statement to continue to be\n** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be\n** rejected with an error.  ^If the authorizer callback returns\n** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]\n** then the [sqlite3_prepare_v2()] or equivalent call that triggered\n** the authorizer will fail with an error message.\n**\n** When the callback returns [SQLITE_OK], that means the operation\n** requested is ok.  ^When the callback returns [SQLITE_DENY], the\n** [sqlite3_prepare_v2()] or equivalent call that triggered the\n** authorizer will fail with an error message explaining that\n** access is denied. \n**\n** ^The first parameter to the authorizer callback is a copy of the third\n** parameter to the sqlite3_set_authorizer() interface. ^The second parameter\n** to the callback is an integer [SQLITE_COPY | action code] that specifies\n** the particular action to be authorized. ^The third through sixth parameters\n** to the callback are either NULL pointers or zero-terminated strings\n** that contain additional details about the action to be authorized.\n** Applications must always be prepared to encounter a NULL pointer in any\n** of the third through the sixth parameters of the authorization callback.\n**\n** ^If the action code is [SQLITE_READ]\n** and the callback returns [SQLITE_IGNORE] then the\n** [prepared statement] statement is constructed to substitute\n** a NULL value in place of the table column that would have\n** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]\n** return can be used to deny an untrusted user access to individual\n** columns of a table.\n** ^When a table is referenced by a [SELECT] but no column values are\n** extracted from that table (for example in a query like\n** \"SELECT count(*) FROM tab\") then the [SQLITE_READ] authorizer callback\n** is invoked once for that table with a column name that is an empty string.\n** ^If the action code is [SQLITE_DELETE] and the callback returns\n** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the\n** [truncate optimization] is disabled and all rows are deleted individually.\n**\n** An authorizer is used when [sqlite3_prepare | preparing]\n** SQL statements from an untrusted source, to ensure that the SQL statements\n** do not try to access data they are not allowed to see, or that they do not\n** try to execute malicious statements that damage the database.  For\n** example, an application may allow a user to enter arbitrary\n** SQL queries for evaluation by a database.  But the application does\n** not want the user to be able to make arbitrary changes to the\n** database.  An authorizer could then be put in place while the\n** user-entered SQL is being [sqlite3_prepare | prepared] that\n** disallows everything except [SELECT] statements.\n**\n** Applications that need to process SQL from untrusted sources\n** might also consider lowering resource limits using [sqlite3_limit()]\n** and limiting database size using the [max_page_count] [PRAGMA]\n** in addition to using an authorizer.\n**\n** ^(Only a single authorizer can be in place on a database connection\n** at a time.  Each call to sqlite3_set_authorizer overrides the\n** previous call.)^  ^Disable the authorizer by installing a NULL callback.\n** The authorizer is disabled by default.\n**\n** The authorizer callback must not do anything that will modify\n** the database connection that invoked the authorizer callback.\n** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their\n** database connections for the meaning of \"modify\" in this paragraph.\n**\n** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the\n** statement might be re-prepared during [sqlite3_step()] due to a \n** schema change.  Hence, the application should ensure that the\n** correct authorizer callback remains in place during the [sqlite3_step()].\n**\n** ^Note that the authorizer callback is invoked only during\n** [sqlite3_prepare()] or its variants.  Authorization is not\n** performed during statement evaluation in [sqlite3_step()], unless\n** as stated in the previous paragraph, sqlite3_step() invokes\n** sqlite3_prepare_v2() to reprepare a statement after a schema change.\n*/\nSQLITE_API int sqlite3_set_authorizer(\n  sqlite3*,\n  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),\n  void *pUserData\n);\n\n/*\n** CAPI3REF: Authorizer Return Codes\n**\n** The [sqlite3_set_authorizer | authorizer callback function] must\n** return either [SQLITE_OK] or one of these two constants in order\n** to signal SQLite whether or not the action is permitted.  See the\n** [sqlite3_set_authorizer | authorizer documentation] for additional\n** information.\n**\n** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]\n** returned from the [sqlite3_vtab_on_conflict()] interface.\n*/\n#define SQLITE_DENY   1   /* Abort the SQL statement with an error */\n#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */\n\n/*\n** CAPI3REF: Authorizer Action Codes\n**\n** The [sqlite3_set_authorizer()] interface registers a callback function\n** that is invoked to authorize certain SQL statement actions.  The\n** second parameter to the callback is an integer code that specifies\n** what action is being authorized.  These are the integer action codes that\n** the authorizer callback may be passed.\n**\n** These action code values signify what kind of operation is to be\n** authorized.  The 3rd and 4th parameters to the authorization\n** callback function will be parameters or NULL depending on which of these\n** codes is used as the second parameter.  ^(The 5th parameter to the\n** authorizer callback is the name of the database (\"main\", \"temp\",\n** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback\n** is the name of the inner-most trigger or view that is responsible for\n** the access attempt or NULL if this access attempt is directly from\n** top-level SQL code.\n*/\n/******************************************* 3rd ************ 4th ***********/\n#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */\n#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */\n#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */\n#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */\n#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */\n#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */\n#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */\n#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */\n#define SQLITE_DELETE                9   /* Table Name      NULL            */\n#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */\n#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */\n#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */\n#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */\n#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */\n#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */\n#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */\n#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */\n#define SQLITE_INSERT               18   /* Table Name      NULL            */\n#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */\n#define SQLITE_READ                 20   /* Table Name      Column Name     */\n#define SQLITE_SELECT               21   /* NULL            NULL            */\n#define SQLITE_TRANSACTION          22   /* Operation       NULL            */\n#define SQLITE_UPDATE               23   /* Table Name      Column Name     */\n#define SQLITE_ATTACH               24   /* Filename        NULL            */\n#define SQLITE_DETACH               25   /* Database Name   NULL            */\n#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */\n#define SQLITE_REINDEX              27   /* Index Name      NULL            */\n#define SQLITE_ANALYZE              28   /* Table Name      NULL            */\n#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */\n#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */\n#define SQLITE_FUNCTION             31   /* NULL            Function Name   */\n#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */\n#define SQLITE_COPY                  0   /* No longer used */\n#define SQLITE_RECURSIVE            33   /* NULL            NULL            */\n\n/*\n** CAPI3REF: Tracing And Profiling Functions\n** METHOD: sqlite3\n**\n** These routines are deprecated. Use the [sqlite3_trace_v2()] interface\n** instead of the routines described here.\n**\n** These routines register callback functions that can be used for\n** tracing and profiling the execution of SQL statements.\n**\n** ^The callback function registered by sqlite3_trace() is invoked at\n** various times when an SQL statement is being run by [sqlite3_step()].\n** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the\n** SQL statement text as the statement first begins executing.\n** ^(Additional sqlite3_trace() callbacks might occur\n** as each triggered subprogram is entered.  The callbacks for triggers\n** contain a UTF-8 SQL comment that identifies the trigger.)^\n**\n** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit\n** the length of [bound parameter] expansion in the output of sqlite3_trace().\n**\n** ^The callback function registered by sqlite3_profile() is invoked\n** as each SQL statement finishes.  ^The profile callback contains\n** the original statement text and an estimate of wall-clock time\n** of how long that statement took to run.  ^The profile callback\n** time is in units of nanoseconds, however the current implementation\n** is only capable of millisecond resolution so the six least significant\n** digits in the time are meaningless.  Future versions of SQLite\n** might provide greater resolution on the profiler callback.  Invoking\n** either [sqlite3_trace()] or [sqlite3_trace_v2()] will cancel the\n** profile callback.\n*/\nSQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,\n   void(*xTrace)(void*,const char*), void*);\nSQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,\n   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);\n\n/*\n** CAPI3REF: SQL Trace Event Codes\n** KEYWORDS: SQLITE_TRACE\n**\n** These constants identify classes of events that can be monitored\n** using the [sqlite3_trace_v2()] tracing logic.  The M argument\n** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of\n** the following constants.  ^The first argument to the trace callback\n** is one of the following constants.\n**\n** New tracing constants may be added in future releases.\n**\n** ^A trace callback has four arguments: xCallback(T,C,P,X).\n** ^The T argument is one of the integer type codes above.\n** ^The C argument is a copy of the context pointer passed in as the\n** fourth argument to [sqlite3_trace_v2()].\n** The P and X arguments are pointers whose meanings depend on T.\n**\n** <dl>\n** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>\n** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement\n** first begins running and possibly at other times during the\n** execution of the prepared statement, such as at the start of each\n** trigger subprogram. ^The P argument is a pointer to the\n** [prepared statement]. ^The X argument is a pointer to a string which\n** is the unexpanded SQL text of the prepared statement or an SQL comment \n** that indicates the invocation of a trigger.  ^The callback can compute\n** the same text that would have been returned by the legacy [sqlite3_trace()]\n** interface by using the X argument when X begins with \"--\" and invoking\n** [sqlite3_expanded_sql(P)] otherwise.\n**\n** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>\n** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same\n** information as is provided by the [sqlite3_profile()] callback.\n** ^The P argument is a pointer to the [prepared statement] and the\n** X argument points to a 64-bit integer which is the estimated of\n** the number of nanosecond that the prepared statement took to run.\n** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.\n**\n** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>\n** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared\n** statement generates a single row of result.  \n** ^The P argument is a pointer to the [prepared statement] and the\n** X argument is unused.\n**\n** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>\n** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database\n** connection closes.\n** ^The P argument is a pointer to the [database connection] object\n** and the X argument is unused.\n** </dl>\n*/\n#define SQLITE_TRACE_STMT       0x01\n#define SQLITE_TRACE_PROFILE    0x02\n#define SQLITE_TRACE_ROW        0x04\n#define SQLITE_TRACE_CLOSE      0x08\n\n/*\n** CAPI3REF: SQL Trace Hook\n** METHOD: sqlite3\n**\n** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback\n** function X against [database connection] D, using property mask M\n** and context pointer P.  ^If the X callback is\n** NULL or if the M mask is zero, then tracing is disabled.  The\n** M argument should be the bitwise OR-ed combination of\n** zero or more [SQLITE_TRACE] constants.\n**\n** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides \n** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().\n**\n** ^The X callback is invoked whenever any of the events identified by \n** mask M occur.  ^The integer return value from the callback is currently\n** ignored, though this may change in future releases.  Callback\n** implementations should return zero to ensure future compatibility.\n**\n** ^A trace callback is invoked with four arguments: callback(T,C,P,X).\n** ^The T argument is one of the [SQLITE_TRACE]\n** constants to indicate why the callback was invoked.\n** ^The C argument is a copy of the context pointer.\n** The P and X arguments are pointers whose meanings depend on T.\n**\n** The sqlite3_trace_v2() interface is intended to replace the legacy\n** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which\n** are deprecated.\n*/\nSQLITE_API int sqlite3_trace_v2(\n  sqlite3*,\n  unsigned uMask,\n  int(*xCallback)(unsigned,void*,void*,void*),\n  void *pCtx\n);\n\n/*\n** CAPI3REF: Query Progress Callbacks\n** METHOD: sqlite3\n**\n** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback\n** function X to be invoked periodically during long running calls to\n** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for\n** database connection D.  An example use for this\n** interface is to keep a GUI updated during a large query.\n**\n** ^The parameter P is passed through as the only parameter to the \n** callback function X.  ^The parameter N is the approximate number of \n** [virtual machine instructions] that are evaluated between successive\n** invocations of the callback X.  ^If N is less than one then the progress\n** handler is disabled.\n**\n** ^Only a single progress handler may be defined at one time per\n** [database connection]; setting a new progress handler cancels the\n** old one.  ^Setting parameter X to NULL disables the progress handler.\n** ^The progress handler is also disabled by setting N to a value less\n** than 1.\n**\n** ^If the progress callback returns non-zero, the operation is\n** interrupted.  This feature can be used to implement a\n** \"Cancel\" button on a GUI progress dialog box.\n**\n** The progress handler callback must not do anything that will modify\n** the database connection that invoked the progress handler.\n** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their\n** database connections for the meaning of \"modify\" in this paragraph.\n**\n*/\nSQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);\n\n/*\n** CAPI3REF: Opening A New Database Connection\n** CONSTRUCTOR: sqlite3\n**\n** ^These routines open an SQLite database file as specified by the \n** filename argument. ^The filename argument is interpreted as UTF-8 for\n** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte\n** order for sqlite3_open16(). ^(A [database connection] handle is usually\n** returned in *ppDb, even if an error occurs.  The only exception is that\n** if SQLite is unable to allocate memory to hold the [sqlite3] object,\n** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]\n** object.)^ ^(If the database is opened (and/or created) successfully, then\n** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The\n** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain\n** an English language description of the error following a failure of any\n** of the sqlite3_open() routines.\n**\n** ^The default encoding will be UTF-8 for databases created using\n** sqlite3_open() or sqlite3_open_v2().  ^The default encoding for databases\n** created using sqlite3_open16() will be UTF-16 in the native byte order.\n**\n** Whether or not an error occurs when it is opened, resources\n** associated with the [database connection] handle should be released by\n** passing it to [sqlite3_close()] when it is no longer required.\n**\n** The sqlite3_open_v2() interface works like sqlite3_open()\n** except that it accepts two additional parameters for additional control\n** over the new database connection.  ^(The flags parameter to\n** sqlite3_open_v2() must include, at a minimum, one of the following\n** three flag combinations:)^\n**\n** <dl>\n** ^(<dt>[SQLITE_OPEN_READONLY]</dt>\n** <dd>The database is opened in read-only mode.  If the database does not\n** already exist, an error is returned.</dd>)^\n**\n** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>\n** <dd>The database is opened for reading and writing if possible, or reading\n** only if the file is write protected by the operating system.  In either\n** case the database must already exist, otherwise an error is returned.</dd>)^\n**\n** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>\n** <dd>The database is opened for reading and writing, and is created if\n** it does not already exist. This is the behavior that is always used for\n** sqlite3_open() and sqlite3_open16().</dd>)^\n** </dl>\n**\n** In addition to the required flags, the following optional flags are\n** also supported:\n**\n** <dl>\n** ^(<dt>[SQLITE_OPEN_URI]</dt>\n** <dd>The filename can be interpreted as a URI if this flag is set.</dd>)^\n**\n** ^(<dt>[SQLITE_OPEN_MEMORY]</dt>\n** <dd>The database will be opened as an in-memory database.  The database\n** is named by the \"filename\" argument for the purposes of cache-sharing,\n** if shared cache mode is enabled, but the \"filename\" is otherwise ignored.\n** </dd>)^\n**\n** ^(<dt>[SQLITE_OPEN_NOMUTEX]</dt>\n** <dd>The new database connection will use the \"multi-thread\"\n** [threading mode].)^  This means that separate threads are allowed\n** to use SQLite at the same time, as long as each thread is using\n** a different [database connection].\n**\n** ^(<dt>[SQLITE_OPEN_FULLMUTEX]</dt>\n** <dd>The new database connection will use the \"serialized\"\n** [threading mode].)^  This means the multiple threads can safely\n** attempt to use the same database connection at the same time.\n** (Mutexes will block any actual concurrency, but in this mode\n** there is no harm in trying.)\n**\n** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt>\n** <dd>The database is opened [shared cache] enabled, overriding\n** the default shared cache setting provided by\n** [sqlite3_enable_shared_cache()].)^\n**\n** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>\n** <dd>The database is opened [shared cache] disabled, overriding\n** the default shared cache setting provided by\n** [sqlite3_enable_shared_cache()].)^\n**\n** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>\n** <dd>The database filename is not allowed to be a symbolic link</dd>\n** </dl>)^\n**\n** If the 3rd parameter to sqlite3_open_v2() is not one of the\n** required combinations shown above optionally combined with other\n** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]\n** then the behavior is undefined.\n**\n** ^The fourth parameter to sqlite3_open_v2() is the name of the\n** [sqlite3_vfs] object that defines the operating system interface that\n** the new database connection should use.  ^If the fourth parameter is\n** a NULL pointer then the default [sqlite3_vfs] object is used.\n**\n** ^If the filename is \":memory:\", then a private, temporary in-memory database\n** is created for the connection.  ^This in-memory database will vanish when\n** the database connection is closed.  Future versions of SQLite might\n** make use of additional special filenames that begin with the \":\" character.\n** It is recommended that when a database filename actually does begin with\n** a \":\" character you should prefix the filename with a pathname such as\n** \"./\" to avoid ambiguity.\n**\n** ^If the filename is an empty string, then a private, temporary\n** on-disk database will be created.  ^This private database will be\n** automatically deleted as soon as the database connection is closed.\n**\n** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>\n**\n** ^If [URI filename] interpretation is enabled, and the filename argument\n** begins with \"file:\", then the filename is interpreted as a URI. ^URI\n** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is\n** set in the third argument to sqlite3_open_v2(), or if it has\n** been enabled globally using the [SQLITE_CONFIG_URI] option with the\n** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.\n** URI filename interpretation is turned off\n** by default, but future releases of SQLite might enable URI filename\n** interpretation by default.  See \"[URI filenames]\" for additional\n** information.\n**\n** URI filenames are parsed according to RFC 3986. ^If the URI contains an\n** authority, then it must be either an empty string or the string \n** \"localhost\". ^If the authority is not an empty string or \"localhost\", an \n** error is returned to the caller. ^The fragment component of a URI, if \n** present, is ignored.\n**\n** ^SQLite uses the path component of the URI as the name of the disk file\n** which contains the database. ^If the path begins with a '/' character, \n** then it is interpreted as an absolute path. ^If the path does not begin \n** with a '/' (meaning that the authority section is omitted from the URI)\n** then the path is interpreted as a relative path. \n** ^(On windows, the first component of an absolute path \n** is a drive specification (e.g. \"C:\").)^\n**\n** [[core URI query parameters]]\n** The query component of a URI may contain parameters that are interpreted\n** either by SQLite itself, or by a [VFS | custom VFS implementation].\n** SQLite and its built-in [VFSes] interpret the\n** following query parameters:\n**\n** <ul>\n**   <li> <b>vfs</b>: ^The \"vfs\" parameter may be used to specify the name of\n**     a VFS object that provides the operating system interface that should\n**     be used to access the database file on disk. ^If this option is set to\n**     an empty string the default VFS object is used. ^Specifying an unknown\n**     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is\n**     present, then the VFS specified by the option takes precedence over\n**     the value passed as the fourth parameter to sqlite3_open_v2().\n**\n**   <li> <b>mode</b>: ^(The mode parameter may be set to either \"ro\", \"rw\",\n**     \"rwc\", or \"memory\". Attempting to set it to any other value is\n**     an error)^. \n**     ^If \"ro\" is specified, then the database is opened for read-only \n**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the \n**     third argument to sqlite3_open_v2(). ^If the mode option is set to \n**     \"rw\", then the database is opened for read-write (but not create) \n**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had \n**     been set. ^Value \"rwc\" is equivalent to setting both \n**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is\n**     set to \"memory\" then a pure [in-memory database] that never reads\n**     or writes from disk is used. ^It is an error to specify a value for\n**     the mode parameter that is less restrictive than that specified by\n**     the flags passed in the third parameter to sqlite3_open_v2().\n**\n**   <li> <b>cache</b>: ^The cache parameter may be set to either \"shared\" or\n**     \"private\". ^Setting it to \"shared\" is equivalent to setting the\n**     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to\n**     sqlite3_open_v2(). ^Setting the cache parameter to \"private\" is \n**     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.\n**     ^If sqlite3_open_v2() is used and the \"cache\" parameter is present in\n**     a URI filename, its value overrides any behavior requested by setting\n**     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.\n**\n**  <li> <b>psow</b>: ^The psow parameter indicates whether or not the\n**     [powersafe overwrite] property does or does not apply to the\n**     storage media on which the database file resides.\n**\n**  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter\n**     which if set disables file locking in rollback journal modes.  This\n**     is useful for accessing a database on a filesystem that does not\n**     support locking.  Caution:  Database corruption might result if two\n**     or more processes write to the same database and any one of those\n**     processes uses nolock=1.\n**\n**  <li> <b>immutable</b>: ^The immutable parameter is a boolean query\n**     parameter that indicates that the database file is stored on\n**     read-only media.  ^When immutable is set, SQLite assumes that the\n**     database file cannot be changed, even by a process with higher\n**     privilege, and so the database is opened read-only and all locking\n**     and change detection is disabled.  Caution: Setting the immutable\n**     property on a database file that does in fact change can result\n**     in incorrect query results and/or [SQLITE_CORRUPT] errors.\n**     See also: [SQLITE_IOCAP_IMMUTABLE].\n**       \n** </ul>\n**\n** ^Specifying an unknown parameter in the query component of a URI is not an\n** error.  Future versions of SQLite might understand additional query\n** parameters.  See \"[query parameters with special meaning to SQLite]\" for\n** additional information.\n**\n** [[URI filename examples]] <h3>URI filename examples</h3>\n**\n** <table border=\"1\" align=center cellpadding=5>\n** <tr><th> URI filenames <th> Results\n** <tr><td> file:data.db <td> \n**          Open the file \"data.db\" in the current directory.\n** <tr><td> file:/home/fred/data.db<br>\n**          file:///home/fred/data.db <br> \n**          file://localhost/home/fred/data.db <br> <td> \n**          Open the database file \"/home/fred/data.db\".\n** <tr><td> file://darkstar/home/fred/data.db <td> \n**          An error. \"darkstar\" is not a recognized authority.\n** <tr><td style=\"white-space:nowrap\"> \n**          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db\n**     <td> Windows only: Open the file \"data.db\" on fred's desktop on drive\n**          C:. Note that the %20 escaping in this example is not strictly \n**          necessary - space characters can be used literally\n**          in URI filenames.\n** <tr><td> file:data.db?mode=ro&cache=private <td> \n**          Open file \"data.db\" in the current directory for read-only access.\n**          Regardless of whether or not shared-cache mode is enabled by\n**          default, use a private cache.\n** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>\n**          Open file \"/home/fred/data.db\". Use the special VFS \"unix-dotfile\"\n**          that uses dot-files in place of posix advisory locking.\n** <tr><td> file:data.db?mode=readonly <td> \n**          An error. \"readonly\" is not a valid option for the \"mode\" parameter.\n** </table>\n**\n** ^URI hexadecimal escape sequences (%HH) are supported within the path and\n** query components of a URI. A hexadecimal escape sequence consists of a\n** percent sign - \"%\" - followed by exactly two hexadecimal digits \n** specifying an octet value. ^Before the path or query components of a\n** URI filename are interpreted, they are encoded using UTF-8 and all \n** hexadecimal escape sequences replaced by a single byte containing the\n** corresponding octet. If this process generates an invalid UTF-8 encoding,\n** the results are undefined.\n**\n** <b>Note to Windows users:</b>  The encoding used for the filename argument\n** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever\n** codepage is currently defined.  Filenames containing international\n** characters must be converted to UTF-8 prior to passing them into\n** sqlite3_open() or sqlite3_open_v2().\n**\n** <b>Note to Windows Runtime users:</b>  The temporary directory must be set\n** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various\n** features that require the use of temporary files may fail.\n**\n** See also: [sqlite3_temp_directory]\n*/\nSQLITE_API int sqlite3_open(\n  const char *filename,   /* Database filename (UTF-8) */\n  sqlite3 **ppDb          /* OUT: SQLite db handle */\n);\nSQLITE_API int sqlite3_open16(\n  const void *filename,   /* Database filename (UTF-16) */\n  sqlite3 **ppDb          /* OUT: SQLite db handle */\n);\nSQLITE_API int sqlite3_open_v2(\n  const char *filename,   /* Database filename (UTF-8) */\n  sqlite3 **ppDb,         /* OUT: SQLite db handle */\n  int flags,              /* Flags */\n  const char *zVfs        /* Name of VFS module to use */\n);\n\n/*\n** CAPI3REF: Obtain Values For URI Parameters\n**\n** These are utility routines, useful to [VFS|custom VFS implementations],\n** that check if a database file was a URI that contained a specific query \n** parameter, and if so obtains the value of that query parameter.\n**\n** The first parameter to these interfaces (hereafter referred to\n** as F) must be one of:\n** <ul>\n** <li> A database filename pointer created by the SQLite core and\n** passed into the xOpen() method of a VFS implemention, or\n** <li> A filename obtained from [sqlite3_db_filename()], or\n** <li> A new filename constructed using [sqlite3_create_filename()].\n** </ul>\n** If the F parameter is not one of the above, then the behavior is\n** undefined and probably undesirable.  Older versions of SQLite were\n** more tolerant of invalid F parameters than newer versions.\n**\n** If F is a suitable filename (as described in the previous paragraph)\n** and if P is the name of the query parameter, then\n** sqlite3_uri_parameter(F,P) returns the value of the P\n** parameter if it exists or a NULL pointer if P does not appear as a \n** query parameter on F.  If P is a query parameter of F and it\n** has no explicit value, then sqlite3_uri_parameter(F,P) returns\n** a pointer to an empty string.\n**\n** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean\n** parameter and returns true (1) or false (0) according to the value\n** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the\n** value of query parameter P is one of \"yes\", \"true\", or \"on\" in any\n** case or if the value begins with a non-zero number.  The \n** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of\n** query parameter P is one of \"no\", \"false\", or \"off\" in any case or\n** if the value begins with a numeric zero.  If P is not a query\n** parameter on F or if the value of P does not match any of the\n** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).\n**\n** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a\n** 64-bit signed integer and returns that integer, or D if P does not\n** exist.  If the value of P is something other than an integer, then\n** zero is returned.\n**\n** The sqlite3_uri_key(F,N) returns a pointer to the name (not\n** the value) of the N-th query parameter for filename F, or a NULL\n** pointer if N is less than zero or greater than the number of query\n** parameters minus 1.  The N value is zero-based so N should be 0 to obtain\n** the name of the first query parameter, 1 for the second parameter, and\n** so forth.\n** \n** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and\n** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and\n** is not a database file pathname pointer that the SQLite core passed\n** into the xOpen VFS method, then the behavior of this routine is undefined\n** and probably undesirable.\n**\n** Beginning with SQLite [version 3.31.0] ([dateof:3.31.0]) the input F\n** parameter can also be the name of a rollback journal file or WAL file\n** in addition to the main database file.  Prior to version 3.31.0, these\n** routines would only work if F was the name of the main database file.\n** When the F parameter is the name of the rollback journal or WAL file,\n** it has access to all the same query parameters as were found on the\n** main database file.\n**\n** See the [URI filename] documentation for additional information.\n*/\nSQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);\nSQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);\nSQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);\nSQLITE_API const char *sqlite3_uri_key(const char *zFilename, int N);\n\n/*\n** CAPI3REF:  Translate filenames\n**\n** These routines are available to [VFS|custom VFS implementations] for\n** translating filenames between the main database file, the journal file,\n** and the WAL file.\n**\n** If F is the name of an sqlite database file, journal file, or WAL file\n** passed by the SQLite core into the VFS, then sqlite3_filename_database(F)\n** returns the name of the corresponding database file.\n**\n** If F is the name of an sqlite database file, journal file, or WAL file\n** passed by the SQLite core into the VFS, or if F is a database filename\n** obtained from [sqlite3_db_filename()], then sqlite3_filename_journal(F)\n** returns the name of the corresponding rollback journal file.\n**\n** If F is the name of an sqlite database file, journal file, or WAL file\n** that was passed by the SQLite core into the VFS, or if F is a database\n** filename obtained from [sqlite3_db_filename()], then\n** sqlite3_filename_wal(F) returns the name of the corresponding\n** WAL file.\n**\n** In all of the above, if F is not the name of a database, journal or WAL\n** filename passed into the VFS from the SQLite core and F is not the\n** return value from [sqlite3_db_filename()], then the result is\n** undefined and is likely a memory access violation.\n*/\nSQLITE_API const char *sqlite3_filename_database(const char*);\nSQLITE_API const char *sqlite3_filename_journal(const char*);\nSQLITE_API const char *sqlite3_filename_wal(const char*);\n\n/*\n** CAPI3REF:  Database File Corresponding To A Journal\n**\n** ^If X is the name of a rollback or WAL-mode journal file that is\n** passed into the xOpen method of [sqlite3_vfs], then \n** sqlite3_database_file_object(X) returns a pointer to the [sqlite3_file]\n** object that represents the main database file.\n**\n** This routine is intended for use in custom [VFS] implementations\n** only.  It is not a general-purpose interface.\n** The argument sqlite3_file_object(X) must be a filename pointer that\n** has been passed into [sqlite3_vfs].xOpen method where the \n** flags parameter to xOpen contains one of the bits\n** [SQLITE_OPEN_MAIN_JOURNAL] or [SQLITE_OPEN_WAL].  Any other use\n** of this routine results in undefined and probably undesirable\n** behavior.\n*/\nSQLITE_API sqlite3_file *sqlite3_database_file_object(const char*);\n\n/*\n** CAPI3REF: Create and Destroy VFS Filenames\n**\n** These interfces are provided for use by [VFS shim] implementations and\n** are not useful outside of that context.\n**\n** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of\n** database filename D with corresponding journal file J and WAL file W and\n** with N URI parameters key/values pairs in the array P.  The result from\n** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that\n** is safe to pass to routines like:\n** <ul>\n** <li> [sqlite3_uri_parameter()],\n** <li> [sqlite3_uri_boolean()],\n** <li> [sqlite3_uri_int64()],\n** <li> [sqlite3_uri_key()], \n** <li> [sqlite3_filename_database()],\n** <li> [sqlite3_filename_journal()], or\n** <li> [sqlite3_filename_wal()].\n** </ul>\n** If a memory allocation error occurs, sqlite3_create_filename() might\n** return a NULL pointer.  The memory obtained from sqlite3_create_filename(X)\n** must be released by a corresponding call to sqlite3_free_filename(Y).\n**\n** The P parameter in sqlite3_create_filename(D,J,W,N,P) should be an array\n** of 2*N pointers to strings.  Each pair of pointers in this array corresponds\n** to a key and value for a query parameter.  The P parameter may be a NULL\n** pointer if N is zero.  None of the 2*N pointers in the P array may be\n** NULL pointers and key pointers should not be empty strings.\n** None of the D, J, or W parameters to sqlite3_create_filename(D,J,W,N,P) may\n** be NULL pointers, though they can be empty strings.\n**\n** The sqlite3_free_filename(Y) routine releases a memory allocation\n** previously obtained from sqlite3_create_filename().  Invoking\n** sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op.\n**\n** If the Y parameter to sqlite3_free_filename(Y) is anything other\n** than a NULL pointer or a pointer previously acquired from\n** sqlite3_create_filename(), then bad things such as heap\n** corruption or segfaults may occur. The value Y should be \n** used again after sqlite3_free_filename(Y) has been called.  This means\n** that if the [sqlite3_vfs.xOpen()] method of a VFS has been called using Y,\n** then the corresponding [sqlite3_module.xClose() method should also be\n** invoked prior to calling sqlite3_free_filename(Y).\n*/\nSQLITE_API char *sqlite3_create_filename(\n  const char *zDatabase,\n  const char *zJournal,\n  const char *zWal,\n  int nParam,\n  const char **azParam\n);\nSQLITE_API void sqlite3_free_filename(char*);\n\n/*\n** CAPI3REF: Error Codes And Messages\n** METHOD: sqlite3\n**\n** ^If the most recent sqlite3_* API call associated with \n** [database connection] D failed, then the sqlite3_errcode(D) interface\n** returns the numeric [result code] or [extended result code] for that\n** API call.\n** ^The sqlite3_extended_errcode()\n** interface is the same except that it always returns the \n** [extended result code] even when extended result codes are\n** disabled.\n**\n** The values returned by sqlite3_errcode() and/or\n** sqlite3_extended_errcode() might change with each API call.\n** Except, there are some interfaces that are guaranteed to never\n** change the value of the error code.  The error-code preserving\n** interfaces are:\n**\n** <ul>\n** <li> sqlite3_errcode()\n** <li> sqlite3_extended_errcode()\n** <li> sqlite3_errmsg()\n** <li> sqlite3_errmsg16()\n** </ul>\n**\n** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language\n** text that describes the error, as either UTF-8 or UTF-16 respectively.\n** ^(Memory to hold the error message string is managed internally.\n** The application does not need to worry about freeing the result.\n** However, the error string might be overwritten or deallocated by\n** subsequent calls to other SQLite interface functions.)^\n**\n** ^The sqlite3_errstr() interface returns the English-language text\n** that describes the [result code], as UTF-8.\n** ^(Memory to hold the error message string is managed internally\n** and must not be freed by the application)^.\n**\n** When the serialized [threading mode] is in use, it might be the\n** case that a second error occurs on a separate thread in between\n** the time of the first error and the call to these interfaces.\n** When that happens, the second error will be reported since these\n** interfaces always report the most recent result.  To avoid\n** this, each thread can obtain exclusive use of the [database connection] D\n** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning\n** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after\n** all calls to the interfaces listed here are completed.\n**\n** If an interface fails with SQLITE_MISUSE, that means the interface\n** was invoked incorrectly by the application.  In that case, the\n** error code and message may or may not be set.\n*/\nSQLITE_API int sqlite3_errcode(sqlite3 *db);\nSQLITE_API int sqlite3_extended_errcode(sqlite3 *db);\nSQLITE_API const char *sqlite3_errmsg(sqlite3*);\nSQLITE_API const void *sqlite3_errmsg16(sqlite3*);\nSQLITE_API const char *sqlite3_errstr(int);\n\n/*\n** CAPI3REF: Prepared Statement Object\n** KEYWORDS: {prepared statement} {prepared statements}\n**\n** An instance of this object represents a single SQL statement that\n** has been compiled into binary form and is ready to be evaluated.\n**\n** Think of each SQL statement as a separate computer program.  The\n** original SQL text is source code.  A prepared statement object \n** is the compiled object code.  All SQL must be converted into a\n** prepared statement before it can be run.\n**\n** The life-cycle of a prepared statement object usually goes like this:\n**\n** <ol>\n** <li> Create the prepared statement object using [sqlite3_prepare_v2()].\n** <li> Bind values to [parameters] using the sqlite3_bind_*()\n**      interfaces.\n** <li> Run the SQL by calling [sqlite3_step()] one or more times.\n** <li> Reset the prepared statement using [sqlite3_reset()] then go back\n**      to step 2.  Do this zero or more times.\n** <li> Destroy the object using [sqlite3_finalize()].\n** </ol>\n*/\ntypedef struct sqlite3_stmt sqlite3_stmt;\n\n/*\n** CAPI3REF: Run-time Limits\n** METHOD: sqlite3\n**\n** ^(This interface allows the size of various constructs to be limited\n** on a connection by connection basis.  The first parameter is the\n** [database connection] whose limit is to be set or queried.  The\n** second parameter is one of the [limit categories] that define a\n** class of constructs to be size limited.  The third parameter is the\n** new limit for that construct.)^\n**\n** ^If the new limit is a negative number, the limit is unchanged.\n** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a \n** [limits | hard upper bound]\n** set at compile-time by a C preprocessor macro called\n** [limits | SQLITE_MAX_<i>NAME</i>].\n** (The \"_LIMIT_\" in the name is changed to \"_MAX_\".))^\n** ^Attempts to increase a limit above its hard upper bound are\n** silently truncated to the hard upper bound.\n**\n** ^Regardless of whether or not the limit was changed, the \n** [sqlite3_limit()] interface returns the prior value of the limit.\n** ^Hence, to find the current value of a limit without changing it,\n** simply invoke this interface with the third parameter set to -1.\n**\n** Run-time limits are intended for use in applications that manage\n** both their own internal database and also databases that are controlled\n** by untrusted external sources.  An example application might be a\n** web browser that has its own databases for storing history and\n** separate databases controlled by JavaScript applications downloaded\n** off the Internet.  The internal databases can be given the\n** large, default limits.  Databases managed by external sources can\n** be given much smaller limits designed to prevent a denial of service\n** attack.  Developers might also want to use the [sqlite3_set_authorizer()]\n** interface to further control untrusted SQL.  The size of the database\n** created by an untrusted script can be contained using the\n** [max_page_count] [PRAGMA].\n**\n** New run-time limit categories may be added in future releases.\n*/\nSQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);\n\n/*\n** CAPI3REF: Run-Time Limit Categories\n** KEYWORDS: {limit category} {*limit categories}\n**\n** These constants define various performance limits\n** that can be lowered at run-time using [sqlite3_limit()].\n** The synopsis of the meanings of the various limits is shown below.\n** Additional information is available at [limits | Limits in SQLite].\n**\n** <dl>\n** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>\n** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^\n**\n** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>\n** <dd>The maximum length of an SQL statement, in bytes.</dd>)^\n**\n** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>\n** <dd>The maximum number of columns in a table definition or in the\n** result set of a [SELECT] or the maximum number of columns in an index\n** or in an ORDER BY or GROUP BY clause.</dd>)^\n**\n** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>\n** <dd>The maximum depth of the parse tree on any expression.</dd>)^\n**\n** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>\n** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^\n**\n** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>\n** <dd>The maximum number of instructions in a virtual machine program\n** used to implement an SQL statement.  If [sqlite3_prepare_v2()] or\n** the equivalent tries to allocate space for more than this many opcodes\n** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^\n**\n** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>\n** <dd>The maximum number of arguments on a function.</dd>)^\n**\n** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>\n** <dd>The maximum number of [ATTACH | attached databases].)^</dd>\n**\n** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]\n** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>\n** <dd>The maximum length of the pattern argument to the [LIKE] or\n** [GLOB] operators.</dd>)^\n**\n** [[SQLITE_LIMIT_VARIABLE_NUMBER]]\n** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>\n** <dd>The maximum index number of any [parameter] in an SQL statement.)^\n**\n** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>\n** <dd>The maximum depth of recursion for triggers.</dd>)^\n**\n** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>\n** <dd>The maximum number of auxiliary worker threads that a single\n** [prepared statement] may start.</dd>)^\n** </dl>\n*/\n#define SQLITE_LIMIT_LENGTH                    0\n#define SQLITE_LIMIT_SQL_LENGTH                1\n#define SQLITE_LIMIT_COLUMN                    2\n#define SQLITE_LIMIT_EXPR_DEPTH                3\n#define SQLITE_LIMIT_COMPOUND_SELECT           4\n#define SQLITE_LIMIT_VDBE_OP                   5\n#define SQLITE_LIMIT_FUNCTION_ARG              6\n#define SQLITE_LIMIT_ATTACHED                  7\n#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8\n#define SQLITE_LIMIT_VARIABLE_NUMBER           9\n#define SQLITE_LIMIT_TRIGGER_DEPTH            10\n#define SQLITE_LIMIT_WORKER_THREADS           11\n\n/*\n** CAPI3REF: Prepare Flags\n**\n** These constants define various flags that can be passed into\n** \"prepFlags\" parameter of the [sqlite3_prepare_v3()] and\n** [sqlite3_prepare16_v3()] interfaces.\n**\n** New flags may be added in future releases of SQLite.\n**\n** <dl>\n** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>\n** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner\n** that the prepared statement will be retained for a long time and\n** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]\n** and [sqlite3_prepare16_v3()] assume that the prepared statement will \n** be used just once or at most a few times and then destroyed using\n** [sqlite3_finalize()] relatively soon. The current implementation acts\n** on this hint by avoiding the use of [lookaside memory] so as not to\n** deplete the limited store of lookaside memory. Future versions of\n** SQLite may act on this hint differently.\n**\n** [[SQLITE_PREPARE_NORMALIZE]] <dt>SQLITE_PREPARE_NORMALIZE</dt>\n** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used\n** to be required for any prepared statement that wanted to use the\n** [sqlite3_normalized_sql()] interface.  However, the\n** [sqlite3_normalized_sql()] interface is now available to all\n** prepared statements, regardless of whether or not they use this\n** flag.\n**\n** [[SQLITE_PREPARE_NO_VTAB]] <dt>SQLITE_PREPARE_NO_VTAB</dt>\n** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler\n** to return an error (error code SQLITE_ERROR) if the statement uses\n** any virtual tables.\n** </dl>\n*/\n#define SQLITE_PREPARE_PERSISTENT              0x01\n#define SQLITE_PREPARE_NORMALIZE               0x02\n#define SQLITE_PREPARE_NO_VTAB                 0x04\n\n/*\n** CAPI3REF: Compiling An SQL Statement\n** KEYWORDS: {SQL statement compiler}\n** METHOD: sqlite3\n** CONSTRUCTOR: sqlite3_stmt\n**\n** To execute an SQL statement, it must first be compiled into a byte-code\n** program using one of these routines.  Or, in other words, these routines\n** are constructors for the [prepared statement] object.\n**\n** The preferred routine to use is [sqlite3_prepare_v2()].  The\n** [sqlite3_prepare()] interface is legacy and should be avoided.\n** [sqlite3_prepare_v3()] has an extra \"prepFlags\" option that is used\n** for special purposes.\n**\n** The use of the UTF-8 interfaces is preferred, as SQLite currently\n** does all parsing using UTF-8.  The UTF-16 interfaces are provided\n** as a convenience.  The UTF-16 interfaces work by converting the\n** input text into UTF-8, then invoking the corresponding UTF-8 interface.\n**\n** The first argument, \"db\", is a [database connection] obtained from a\n** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or\n** [sqlite3_open16()].  The database connection must not have been closed.\n**\n** The second argument, \"zSql\", is the statement to be compiled, encoded\n** as either UTF-8 or UTF-16.  The sqlite3_prepare(), sqlite3_prepare_v2(),\n** and sqlite3_prepare_v3()\n** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),\n** and sqlite3_prepare16_v3() use UTF-16.\n**\n** ^If the nByte argument is negative, then zSql is read up to the\n** first zero terminator. ^If nByte is positive, then it is the\n** number of bytes read from zSql.  ^If nByte is zero, then no prepared\n** statement is generated.\n** If the caller knows that the supplied string is nul-terminated, then\n** there is a small performance advantage to passing an nByte parameter that\n** is the number of bytes in the input string <i>including</i>\n** the nul-terminator.\n**\n** ^If pzTail is not NULL then *pzTail is made to point to the first byte\n** past the end of the first SQL statement in zSql.  These routines only\n** compile the first statement in zSql, so *pzTail is left pointing to\n** what remains uncompiled.\n**\n** ^*ppStmt is left pointing to a compiled [prepared statement] that can be\n** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set\n** to NULL.  ^If the input text contains no SQL (if the input is an empty\n** string or a comment) then *ppStmt is set to NULL.\n** The calling procedure is responsible for deleting the compiled\n** SQL statement using [sqlite3_finalize()] after it has finished with it.\n** ppStmt may not be NULL.\n**\n** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];\n** otherwise an [error code] is returned.\n**\n** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),\n** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.\n** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())\n** are retained for backwards compatibility, but their use is discouraged.\n** ^In the \"vX\" interfaces, the prepared statement\n** that is returned (the [sqlite3_stmt] object) contains a copy of the\n** original SQL text. This causes the [sqlite3_step()] interface to\n** behave differently in three ways:\n**\n** <ol>\n** <li>\n** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it\n** always used to do, [sqlite3_step()] will automatically recompile the SQL\n** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]\n** retries will occur before sqlite3_step() gives up and returns an error.\n** </li>\n**\n** <li>\n** ^When an error occurs, [sqlite3_step()] will return one of the detailed\n** [error codes] or [extended error codes].  ^The legacy behavior was that\n** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code\n** and the application would have to make a second call to [sqlite3_reset()]\n** in order to find the underlying cause of the problem. With the \"v2\" prepare\n** interfaces, the underlying reason for the error is returned immediately.\n** </li>\n**\n** <li>\n** ^If the specific value bound to a [parameter | host parameter] in the \n** WHERE clause might influence the choice of query plan for a statement,\n** then the statement will be automatically recompiled, as if there had been \n** a schema change, on the first [sqlite3_step()] call following any change\n** to the [sqlite3_bind_text | bindings] of that [parameter]. \n** ^The specific value of a WHERE-clause [parameter] might influence the \n** choice of query plan if the parameter is the left-hand side of a [LIKE]\n** or [GLOB] operator or if the parameter is compared to an indexed column\n** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled.\n** </li>\n** </ol>\n**\n** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having\n** the extra prepFlags parameter, which is a bit array consisting of zero or\n** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags.  ^The\n** sqlite3_prepare_v2() interface works exactly the same as\n** sqlite3_prepare_v3() with a zero prepFlags parameter.\n*/\nSQLITE_API int sqlite3_prepare(\n  sqlite3 *db,            /* Database handle */\n  const char *zSql,       /* SQL statement, UTF-8 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const char **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\nSQLITE_API int sqlite3_prepare_v2(\n  sqlite3 *db,            /* Database handle */\n  const char *zSql,       /* SQL statement, UTF-8 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const char **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\nSQLITE_API int sqlite3_prepare_v3(\n  sqlite3 *db,            /* Database handle */\n  const char *zSql,       /* SQL statement, UTF-8 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const char **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\nSQLITE_API int sqlite3_prepare16(\n  sqlite3 *db,            /* Database handle */\n  const void *zSql,       /* SQL statement, UTF-16 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const void **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\nSQLITE_API int sqlite3_prepare16_v2(\n  sqlite3 *db,            /* Database handle */\n  const void *zSql,       /* SQL statement, UTF-16 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const void **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\nSQLITE_API int sqlite3_prepare16_v3(\n  sqlite3 *db,            /* Database handle */\n  const void *zSql,       /* SQL statement, UTF-16 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const void **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\n\n/*\n** CAPI3REF: Retrieving Statement SQL\n** METHOD: sqlite3_stmt\n**\n** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8\n** SQL text used to create [prepared statement] P if P was\n** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],\n** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].\n** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8\n** string containing the SQL text of prepared statement P with\n** [bound parameters] expanded.\n** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8\n** string containing the normalized SQL text of prepared statement P.  The\n** semantics used to normalize a SQL statement are unspecified and subject\n** to change.  At a minimum, literal values will be replaced with suitable\n** placeholders.\n**\n** ^(For example, if a prepared statement is created using the SQL\n** text \"SELECT $abc,:xyz\" and if parameter $abc is bound to integer 2345\n** and parameter :xyz is unbound, then sqlite3_sql() will return\n** the original string, \"SELECT $abc,:xyz\" but sqlite3_expanded_sql()\n** will return \"SELECT 2345,NULL\".)^\n**\n** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory\n** is available to hold the result, or if the result would exceed the\n** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].\n**\n** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of\n** bound parameter expansions.  ^The [SQLITE_OMIT_TRACE] compile-time\n** option causes sqlite3_expanded_sql() to always return NULL.\n**\n** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P)\n** are managed by SQLite and are automatically freed when the prepared\n** statement is finalized.\n** ^The string returned by sqlite3_expanded_sql(P), on the other hand,\n** is obtained from [sqlite3_malloc()] and must be free by the application\n** by passing it to [sqlite3_free()].\n*/\nSQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);\nSQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);\nSQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Determine If An SQL Statement Writes The Database\n** METHOD: sqlite3_stmt\n**\n** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if\n** and only if the [prepared statement] X makes no direct changes to\n** the content of the database file.\n**\n** Note that [application-defined SQL functions] or\n** [virtual tables] might change the database indirectly as a side effect.  \n** ^(For example, if an application defines a function \"eval()\" that \n** calls [sqlite3_exec()], then the following SQL statement would\n** change the database file through side-effects:\n**\n** <blockquote><pre>\n**    SELECT eval('DELETE FROM t1') FROM t2;\n** </pre></blockquote>\n**\n** But because the [SELECT] statement does not change the database file\n** directly, sqlite3_stmt_readonly() would still return true.)^\n**\n** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],\n** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,\n** since the statements themselves do not actually modify the database but\n** rather they control the timing of when other statements modify the \n** database.  ^The [ATTACH] and [DETACH] statements also cause\n** sqlite3_stmt_readonly() to return true since, while those statements\n** change the configuration of a database connection, they do not make \n** changes to the content of the database files on disk.\n** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since\n** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and\n** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so\n** sqlite3_stmt_readonly() returns false for those commands.\n*/\nSQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement\n** METHOD: sqlite3_stmt\n**\n** ^The sqlite3_stmt_isexplain(S) interface returns 1 if the\n** prepared statement S is an EXPLAIN statement, or 2 if the\n** statement S is an EXPLAIN QUERY PLAN.\n** ^The sqlite3_stmt_isexplain(S) interface returns 0 if S is\n** an ordinary statement or a NULL pointer.\n*/\nSQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Determine If A Prepared Statement Has Been Reset\n** METHOD: sqlite3_stmt\n**\n** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the\n** [prepared statement] S has been stepped at least once using \n** [sqlite3_step(S)] but has neither run to completion (returned\n** [SQLITE_DONE] from [sqlite3_step(S)]) nor\n** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)\n** interface returns false if S is a NULL pointer.  If S is not a \n** NULL pointer and is not a pointer to a valid [prepared statement]\n** object, then the behavior is undefined and probably undesirable.\n**\n** This interface can be used in combination [sqlite3_next_stmt()]\n** to locate all prepared statements associated with a database \n** connection that are in need of being reset.  This can be used,\n** for example, in diagnostic routines to search for prepared \n** statements that are holding a transaction open.\n*/\nSQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Dynamically Typed Value Object\n** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}\n**\n** SQLite uses the sqlite3_value object to represent all values\n** that can be stored in a database table. SQLite uses dynamic typing\n** for the values it stores.  ^Values stored in sqlite3_value objects\n** can be integers, floating point values, strings, BLOBs, or NULL.\n**\n** An sqlite3_value object may be either \"protected\" or \"unprotected\".\n** Some interfaces require a protected sqlite3_value.  Other interfaces\n** will accept either a protected or an unprotected sqlite3_value.\n** Every interface that accepts sqlite3_value arguments specifies\n** whether or not it requires a protected sqlite3_value.  The\n** [sqlite3_value_dup()] interface can be used to construct a new \n** protected sqlite3_value from an unprotected sqlite3_value.\n**\n** The terms \"protected\" and \"unprotected\" refer to whether or not\n** a mutex is held.  An internal mutex is held for a protected\n** sqlite3_value object but no mutex is held for an unprotected\n** sqlite3_value object.  If SQLite is compiled to be single-threaded\n** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)\n** or if SQLite is run in one of reduced mutex modes \n** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]\n** then there is no distinction between protected and unprotected\n** sqlite3_value objects and they can be used interchangeably.  However,\n** for maximum code portability it is recommended that applications\n** still make the distinction between protected and unprotected\n** sqlite3_value objects even when not strictly required.\n**\n** ^The sqlite3_value objects that are passed as parameters into the\n** implementation of [application-defined SQL functions] are protected.\n** ^The sqlite3_value object returned by\n** [sqlite3_column_value()] is unprotected.\n** Unprotected sqlite3_value objects may only be used as arguments\n** to [sqlite3_result_value()], [sqlite3_bind_value()], and\n** [sqlite3_value_dup()].\n** The [sqlite3_value_blob | sqlite3_value_type()] family of\n** interfaces require protected sqlite3_value objects.\n*/\ntypedef struct sqlite3_value sqlite3_value;\n\n/*\n** CAPI3REF: SQL Function Context Object\n**\n** The context in which an SQL function executes is stored in an\n** sqlite3_context object.  ^A pointer to an sqlite3_context object\n** is always first parameter to [application-defined SQL functions].\n** The application-defined SQL function implementation will pass this\n** pointer through into calls to [sqlite3_result_int | sqlite3_result()],\n** [sqlite3_aggregate_context()], [sqlite3_user_data()],\n** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],\n** and/or [sqlite3_set_auxdata()].\n*/\ntypedef struct sqlite3_context sqlite3_context;\n\n/*\n** CAPI3REF: Binding Values To Prepared Statements\n** KEYWORDS: {host parameter} {host parameters} {host parameter name}\n** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}\n** METHOD: sqlite3_stmt\n**\n** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,\n** literals may be replaced by a [parameter] that matches one of following\n** templates:\n**\n** <ul>\n** <li>  ?\n** <li>  ?NNN\n** <li>  :VVV\n** <li>  @VVV\n** <li>  $VVV\n** </ul>\n**\n** In the templates above, NNN represents an integer literal,\n** and VVV represents an alphanumeric identifier.)^  ^The values of these\n** parameters (also called \"host parameter names\" or \"SQL parameters\")\n** can be set using the sqlite3_bind_*() routines defined here.\n**\n** ^The first argument to the sqlite3_bind_*() routines is always\n** a pointer to the [sqlite3_stmt] object returned from\n** [sqlite3_prepare_v2()] or its variants.\n**\n** ^The second argument is the index of the SQL parameter to be set.\n** ^The leftmost SQL parameter has an index of 1.  ^When the same named\n** SQL parameter is used more than once, second and subsequent\n** occurrences have the same index as the first occurrence.\n** ^The index for named parameters can be looked up using the\n** [sqlite3_bind_parameter_index()] API if desired.  ^The index\n** for \"?NNN\" parameters is the value of NNN.\n** ^The NNN value must be between 1 and the [sqlite3_limit()]\n** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 32766).\n**\n** ^The third argument is the value to bind to the parameter.\n** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()\n** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter\n** is ignored and the end result is the same as sqlite3_bind_null().\n** ^If the third parameter to sqlite3_bind_text() is not NULL, then\n** it should be a pointer to well-formed UTF8 text.\n** ^If the third parameter to sqlite3_bind_text16() is not NULL, then\n** it should be a pointer to well-formed UTF16 text.\n** ^If the third parameter to sqlite3_bind_text64() is not NULL, then\n** it should be a pointer to a well-formed unicode string that is\n** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF16\n** otherwise.\n**\n** [[byte-order determination rules]] ^The byte-order of\n** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF)\n** found in first character, which is removed, or in the absence of a BOM\n** the byte order is the native byte order of the host\n** machine for sqlite3_bind_text16() or the byte order specified in\n** the 6th parameter for sqlite3_bind_text64().)^ \n** ^If UTF16 input text contains invalid unicode\n** characters, then SQLite might change those invalid characters\n** into the unicode replacement character: U+FFFD.\n**\n** ^(In those routines that have a fourth argument, its value is the\n** number of bytes in the parameter.  To be clear: the value is the\n** number of <u>bytes</u> in the value, not the number of characters.)^\n** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()\n** is negative, then the length of the string is\n** the number of bytes up to the first zero terminator.\n** If the fourth parameter to sqlite3_bind_blob() is negative, then\n** the behavior is undefined.\n** If a non-negative fourth parameter is provided to sqlite3_bind_text()\n** or sqlite3_bind_text16() or sqlite3_bind_text64() then\n** that parameter must be the byte offset\n** where the NUL terminator would occur assuming the string were NUL\n** terminated.  If any NUL characters occurs at byte offsets less than \n** the value of the fourth parameter then the resulting string value will\n** contain embedded NULs.  The result of expressions involving strings\n** with embedded NULs is undefined.\n**\n** ^The fifth argument to the BLOB and string binding interfaces\n** is a destructor used to dispose of the BLOB or\n** string after SQLite has finished with it.  ^The destructor is called\n** to dispose of the BLOB or string even if the call to the bind API fails,\n** except the destructor is not called if the third parameter is a NULL\n** pointer or the fourth parameter is negative.\n** ^If the fifth argument is\n** the special value [SQLITE_STATIC], then SQLite assumes that the\n** information is in static, unmanaged space and does not need to be freed.\n** ^If the fifth argument has the value [SQLITE_TRANSIENT], then\n** SQLite makes its own private copy of the data immediately, before\n** the sqlite3_bind_*() routine returns.\n**\n** ^The sixth argument to sqlite3_bind_text64() must be one of\n** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]\n** to specify the encoding of the text in the third parameter.  If\n** the sixth argument to sqlite3_bind_text64() is not one of the\n** allowed values shown above, or if the text encoding is different\n** from the encoding specified by the sixth parameter, then the behavior\n** is undefined.\n**\n** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that\n** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory\n** (just an integer to hold its size) while it is being processed.\n** Zeroblobs are intended to serve as placeholders for BLOBs whose\n** content is later written using\n** [sqlite3_blob_open | incremental BLOB I/O] routines.\n** ^A negative value for the zeroblob results in a zero-length BLOB.\n**\n** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in\n** [prepared statement] S to have an SQL value of NULL, but to also be\n** associated with the pointer P of type T.  ^D is either a NULL pointer or\n** a pointer to a destructor function for P. ^SQLite will invoke the\n** destructor D with a single argument of P when it is finished using\n** P.  The T parameter should be a static string, preferably a string\n** literal. The sqlite3_bind_pointer() routine is part of the\n** [pointer passing interface] added for SQLite 3.20.0.\n**\n** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer\n** for the [prepared statement] or with a prepared statement for which\n** [sqlite3_step()] has been called more recently than [sqlite3_reset()],\n** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()\n** routine is passed a [prepared statement] that has been finalized, the\n** result is undefined and probably harmful.\n**\n** ^Bindings are not cleared by the [sqlite3_reset()] routine.\n** ^Unbound parameters are interpreted as NULL.\n**\n** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an\n** [error code] if anything goes wrong.\n** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB\n** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or\n** [SQLITE_MAX_LENGTH].\n** ^[SQLITE_RANGE] is returned if the parameter\n** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.\n**\n** See also: [sqlite3_bind_parameter_count()],\n** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].\n*/\nSQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));\nSQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,\n                        void(*)(void*));\nSQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);\nSQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);\nSQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);\nSQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);\nSQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));\nSQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));\nSQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,\n                         void(*)(void*), unsigned char encoding);\nSQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);\nSQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));\nSQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);\nSQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);\n\n/*\n** CAPI3REF: Number Of SQL Parameters\n** METHOD: sqlite3_stmt\n**\n** ^This routine can be used to find the number of [SQL parameters]\n** in a [prepared statement].  SQL parameters are tokens of the\n** form \"?\", \"?NNN\", \":AAA\", \"$AAA\", or \"@AAA\" that serve as\n** placeholders for values that are [sqlite3_bind_blob | bound]\n** to the parameters at a later time.\n**\n** ^(This routine actually returns the index of the largest (rightmost)\n** parameter. For all forms except ?NNN, this will correspond to the\n** number of unique parameters.  If parameters of the ?NNN form are used,\n** there may be gaps in the list.)^\n**\n** See also: [sqlite3_bind_blob|sqlite3_bind()],\n** [sqlite3_bind_parameter_name()], and\n** [sqlite3_bind_parameter_index()].\n*/\nSQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Name Of A Host Parameter\n** METHOD: sqlite3_stmt\n**\n** ^The sqlite3_bind_parameter_name(P,N) interface returns\n** the name of the N-th [SQL parameter] in the [prepared statement] P.\n** ^(SQL parameters of the form \"?NNN\" or \":AAA\" or \"@AAA\" or \"$AAA\"\n** have a name which is the string \"?NNN\" or \":AAA\" or \"@AAA\" or \"$AAA\"\n** respectively.\n** In other words, the initial \":\" or \"$\" or \"@\" or \"?\"\n** is included as part of the name.)^\n** ^Parameters of the form \"?\" without a following integer have no name\n** and are referred to as \"nameless\" or \"anonymous parameters\".\n**\n** ^The first host parameter has an index of 1, not 0.\n**\n** ^If the value N is out of range or if the N-th parameter is\n** nameless, then NULL is returned.  ^The returned string is\n** always in UTF-8 encoding even if the named parameter was\n** originally specified as UTF-16 in [sqlite3_prepare16()],\n** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].\n**\n** See also: [sqlite3_bind_blob|sqlite3_bind()],\n** [sqlite3_bind_parameter_count()], and\n** [sqlite3_bind_parameter_index()].\n*/\nSQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);\n\n/*\n** CAPI3REF: Index Of A Parameter With A Given Name\n** METHOD: sqlite3_stmt\n**\n** ^Return the index of an SQL parameter given its name.  ^The\n** index value returned is suitable for use as the second\n** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero\n** is returned if no matching parameter is found.  ^The parameter\n** name must be given in UTF-8 even if the original statement\n** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or\n** [sqlite3_prepare16_v3()].\n**\n** See also: [sqlite3_bind_blob|sqlite3_bind()],\n** [sqlite3_bind_parameter_count()], and\n** [sqlite3_bind_parameter_name()].\n*/\nSQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);\n\n/*\n** CAPI3REF: Reset All Bindings On A Prepared Statement\n** METHOD: sqlite3_stmt\n**\n** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset\n** the [sqlite3_bind_blob | bindings] on a [prepared statement].\n** ^Use this routine to reset all host parameters to NULL.\n*/\nSQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Number Of Columns In A Result Set\n** METHOD: sqlite3_stmt\n**\n** ^Return the number of columns in the result set returned by the\n** [prepared statement]. ^If this routine returns 0, that means the \n** [prepared statement] returns no data (for example an [UPDATE]).\n** ^However, just because this routine returns a positive number does not\n** mean that one or more rows of data will be returned.  ^A SELECT statement\n** will always have a positive sqlite3_column_count() but depending on the\n** WHERE clause constraints and the table content, it might return no rows.\n**\n** See also: [sqlite3_data_count()]\n*/\nSQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Column Names In A Result Set\n** METHOD: sqlite3_stmt\n**\n** ^These routines return the name assigned to a particular column\n** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()\n** interface returns a pointer to a zero-terminated UTF-8 string\n** and sqlite3_column_name16() returns a pointer to a zero-terminated\n** UTF-16 string.  ^The first parameter is the [prepared statement]\n** that implements the [SELECT] statement. ^The second parameter is the\n** column number.  ^The leftmost column is number 0.\n**\n** ^The returned string pointer is valid until either the [prepared statement]\n** is destroyed by [sqlite3_finalize()] or until the statement is automatically\n** reprepared by the first call to [sqlite3_step()] for a particular run\n** or until the next call to\n** sqlite3_column_name() or sqlite3_column_name16() on the same column.\n**\n** ^If sqlite3_malloc() fails during the processing of either routine\n** (for example during a conversion from UTF-8 to UTF-16) then a\n** NULL pointer is returned.\n**\n** ^The name of a result column is the value of the \"AS\" clause for\n** that column, if there is an AS clause.  If there is no AS clause\n** then the name of the column is unspecified and may change from\n** one release of SQLite to the next.\n*/\nSQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);\nSQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);\n\n/*\n** CAPI3REF: Source Of Data In A Query Result\n** METHOD: sqlite3_stmt\n**\n** ^These routines provide a means to determine the database, table, and\n** table column that is the origin of a particular result column in\n** [SELECT] statement.\n** ^The name of the database or table or column can be returned as\n** either a UTF-8 or UTF-16 string.  ^The _database_ routines return\n** the database name, the _table_ routines return the table name, and\n** the origin_ routines return the column name.\n** ^The returned string is valid until the [prepared statement] is destroyed\n** using [sqlite3_finalize()] or until the statement is automatically\n** reprepared by the first call to [sqlite3_step()] for a particular run\n** or until the same information is requested\n** again in a different encoding.\n**\n** ^The names returned are the original un-aliased names of the\n** database, table, and column.\n**\n** ^The first argument to these interfaces is a [prepared statement].\n** ^These functions return information about the Nth result column returned by\n** the statement, where N is the second function argument.\n** ^The left-most column is column 0 for these routines.\n**\n** ^If the Nth column returned by the statement is an expression or\n** subquery and is not a column value, then all of these functions return\n** NULL.  ^These routines might also return NULL if a memory allocation error\n** occurs.  ^Otherwise, they return the name of the attached database, table,\n** or column that query result column was extracted from.\n**\n** ^As with all other SQLite APIs, those whose names end with \"16\" return\n** UTF-16 encoded strings and the other functions return UTF-8.\n**\n** ^These APIs are only available if the library was compiled with the\n** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.\n**\n** If two or more threads call one or more\n** [sqlite3_column_database_name | column metadata interfaces]\n** for the same [prepared statement] and result column\n** at the same time then the results are undefined.\n*/\nSQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);\nSQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);\nSQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);\nSQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);\nSQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);\nSQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);\n\n/*\n** CAPI3REF: Declared Datatype Of A Query Result\n** METHOD: sqlite3_stmt\n**\n** ^(The first parameter is a [prepared statement].\n** If this statement is a [SELECT] statement and the Nth column of the\n** returned result set of that [SELECT] is a table column (not an\n** expression or subquery) then the declared type of the table\n** column is returned.)^  ^If the Nth column of the result set is an\n** expression or subquery, then a NULL pointer is returned.\n** ^The returned string is always UTF-8 encoded.\n**\n** ^(For example, given the database schema:\n**\n** CREATE TABLE t1(c1 VARIANT);\n**\n** and the following statement to be compiled:\n**\n** SELECT c1 + 1, c1 FROM t1;\n**\n** this routine would return the string \"VARIANT\" for the second result\n** column (i==1), and a NULL pointer for the first result column (i==0).)^\n**\n** ^SQLite uses dynamic run-time typing.  ^So just because a column\n** is declared to contain a particular type does not mean that the\n** data stored in that column is of the declared type.  SQLite is\n** strongly typed, but the typing is dynamic not static.  ^Type\n** is associated with individual values, not with the containers\n** used to hold those values.\n*/\nSQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);\nSQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);\n\n/*\n** CAPI3REF: Evaluate An SQL Statement\n** METHOD: sqlite3_stmt\n**\n** After a [prepared statement] has been prepared using any of\n** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],\n** or [sqlite3_prepare16_v3()] or one of the legacy\n** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function\n** must be called one or more times to evaluate the statement.\n**\n** The details of the behavior of the sqlite3_step() interface depend\n** on whether the statement was prepared using the newer \"vX\" interfaces\n** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],\n** [sqlite3_prepare16_v2()] or the older legacy\n** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the\n** new \"vX\" interface is recommended for new applications but the legacy\n** interface will continue to be supported.\n**\n** ^In the legacy interface, the return value will be either [SQLITE_BUSY],\n** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].\n** ^With the \"v2\" interface, any of the other [result codes] or\n** [extended result codes] might be returned as well.\n**\n** ^[SQLITE_BUSY] means that the database engine was unable to acquire the\n** database locks it needs to do its job.  ^If the statement is a [COMMIT]\n** or occurs outside of an explicit transaction, then you can retry the\n** statement.  If the statement is not a [COMMIT] and occurs within an\n** explicit transaction then you should rollback the transaction before\n** continuing.\n**\n** ^[SQLITE_DONE] means that the statement has finished executing\n** successfully.  sqlite3_step() should not be called again on this virtual\n** machine without first calling [sqlite3_reset()] to reset the virtual\n** machine back to its initial state.\n**\n** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]\n** is returned each time a new row of data is ready for processing by the\n** caller. The values may be accessed using the [column access functions].\n** sqlite3_step() is called again to retrieve the next row of data.\n**\n** ^[SQLITE_ERROR] means that a run-time error (such as a constraint\n** violation) has occurred.  sqlite3_step() should not be called again on\n** the VM. More information may be found by calling [sqlite3_errmsg()].\n** ^With the legacy interface, a more specific error code (for example,\n** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)\n** can be obtained by calling [sqlite3_reset()] on the\n** [prepared statement].  ^In the \"v2\" interface,\n** the more specific error code is returned directly by sqlite3_step().\n**\n** [SQLITE_MISUSE] means that the this routine was called inappropriately.\n** Perhaps it was called on a [prepared statement] that has\n** already been [sqlite3_finalize | finalized] or on one that had\n** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could\n** be the case that the same database connection is being used by two or\n** more threads at the same moment in time.\n**\n** For all versions of SQLite up to and including 3.6.23.1, a call to\n** [sqlite3_reset()] was required after sqlite3_step() returned anything\n** other than [SQLITE_ROW] before any subsequent invocation of\n** sqlite3_step().  Failure to reset the prepared statement using \n** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from\n** sqlite3_step().  But after [version 3.6.23.1] ([dateof:3.6.23.1],\n** sqlite3_step() began\n** calling [sqlite3_reset()] automatically in this circumstance rather\n** than returning [SQLITE_MISUSE].  This is not considered a compatibility\n** break because any application that ever receives an SQLITE_MISUSE error\n** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option\n** can be used to restore the legacy behavior.\n**\n** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()\n** API always returns a generic error code, [SQLITE_ERROR], following any\n** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call\n** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the\n** specific [error codes] that better describes the error.\n** We admit that this is a goofy design.  The problem has been fixed\n** with the \"v2\" interface.  If you prepare all of your SQL statements\n** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]\n** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead\n** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,\n** then the more specific [error codes] are returned directly\n** by sqlite3_step().  The use of the \"vX\" interfaces is recommended.\n*/\nSQLITE_API int sqlite3_step(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Number of columns in a result set\n** METHOD: sqlite3_stmt\n**\n** ^The sqlite3_data_count(P) interface returns the number of columns in the\n** current row of the result set of [prepared statement] P.\n** ^If prepared statement P does not have results ready to return\n** (via calls to the [sqlite3_column_int | sqlite3_column()] family of\n** interfaces) then sqlite3_data_count(P) returns 0.\n** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.\n** ^The sqlite3_data_count(P) routine returns 0 if the previous call to\n** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)\n** will return non-zero if previous call to [sqlite3_step](P) returned\n** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]\n** where it always returns zero since each step of that multi-step\n** pragma returns 0 columns of data.\n**\n** See also: [sqlite3_column_count()]\n*/\nSQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Fundamental Datatypes\n** KEYWORDS: SQLITE_TEXT\n**\n** ^(Every value in SQLite has one of five fundamental datatypes:\n**\n** <ul>\n** <li> 64-bit signed integer\n** <li> 64-bit IEEE floating point number\n** <li> string\n** <li> BLOB\n** <li> NULL\n** </ul>)^\n**\n** These constants are codes for each of those types.\n**\n** Note that the SQLITE_TEXT constant was also used in SQLite version 2\n** for a completely different meaning.  Software that links against both\n** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not\n** SQLITE_TEXT.\n*/\n#define SQLITE_INTEGER  1\n#define SQLITE_FLOAT    2\n#define SQLITE_BLOB     4\n#define SQLITE_NULL     5\n#ifdef SQLITE_TEXT\n# undef SQLITE_TEXT\n#else\n# define SQLITE_TEXT     3\n#endif\n#define SQLITE3_TEXT     3\n\n/*\n** CAPI3REF: Result Values From A Query\n** KEYWORDS: {column access functions}\n** METHOD: sqlite3_stmt\n**\n** <b>Summary:</b>\n** <blockquote><table border=0 cellpadding=0 cellspacing=0>\n** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result\n** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result\n** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result\n** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result\n** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result\n** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result\n** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an \n** [sqlite3_value|unprotected sqlite3_value] object.\n** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;\n** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB\n** or a UTF-8 TEXT result in bytes\n** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>\n** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16\n** TEXT in bytes\n** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default\n** datatype of the result\n** </table></blockquote>\n**\n** <b>Details:</b>\n**\n** ^These routines return information about a single column of the current\n** result row of a query.  ^In every case the first argument is a pointer\n** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]\n** that was returned from [sqlite3_prepare_v2()] or one of its variants)\n** and the second argument is the index of the column for which information\n** should be returned. ^The leftmost column of the result set has the index 0.\n** ^The number of columns in the result can be determined using\n** [sqlite3_column_count()].\n**\n** If the SQL statement does not currently point to a valid row, or if the\n** column index is out of range, the result is undefined.\n** These routines may only be called when the most recent call to\n** [sqlite3_step()] has returned [SQLITE_ROW] and neither\n** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.\n** If any of these routines are called after [sqlite3_reset()] or\n** [sqlite3_finalize()] or after [sqlite3_step()] has returned\n** something other than [SQLITE_ROW], the results are undefined.\n** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]\n** are called from a different thread while any of these routines\n** are pending, then the results are undefined.\n**\n** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)\n** each return the value of a result column in a specific data format.  If\n** the result column is not initially in the requested format (for example,\n** if the query returns an integer but the sqlite3_column_text() interface\n** is used to extract the value) then an automatic type conversion is performed.\n**\n** ^The sqlite3_column_type() routine returns the\n** [SQLITE_INTEGER | datatype code] for the initial data type\n** of the result column.  ^The returned value is one of [SQLITE_INTEGER],\n** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].\n** The return value of sqlite3_column_type() can be used to decide which\n** of the first six interface should be used to extract the column value.\n** The value returned by sqlite3_column_type() is only meaningful if no\n** automatic type conversions have occurred for the value in question.  \n** After a type conversion, the result of calling sqlite3_column_type()\n** is undefined, though harmless.  Future\n** versions of SQLite may change the behavior of sqlite3_column_type()\n** following a type conversion.\n**\n** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()\n** or sqlite3_column_bytes16() interfaces can be used to determine the size\n** of that BLOB or string.\n**\n** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()\n** routine returns the number of bytes in that BLOB or string.\n** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts\n** the string to UTF-8 and then returns the number of bytes.\n** ^If the result is a numeric value then sqlite3_column_bytes() uses\n** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns\n** the number of bytes in that string.\n** ^If the result is NULL, then sqlite3_column_bytes() returns zero.\n**\n** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()\n** routine returns the number of bytes in that BLOB or string.\n** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts\n** the string to UTF-16 and then returns the number of bytes.\n** ^If the result is a numeric value then sqlite3_column_bytes16() uses\n** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns\n** the number of bytes in that string.\n** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.\n**\n** ^The values returned by [sqlite3_column_bytes()] and \n** [sqlite3_column_bytes16()] do not include the zero terminators at the end\n** of the string.  ^For clarity: the values returned by\n** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of\n** bytes in the string, not the number of characters.\n**\n** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),\n** even empty strings, are always zero-terminated.  ^The return\n** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.\n**\n** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an\n** [unprotected sqlite3_value] object.  In a multithreaded environment,\n** an unprotected sqlite3_value object may only be used safely with\n** [sqlite3_bind_value()] and [sqlite3_result_value()].\n** If the [unprotected sqlite3_value] object returned by\n** [sqlite3_column_value()] is used in any other way, including calls\n** to routines like [sqlite3_value_int()], [sqlite3_value_text()],\n** or [sqlite3_value_bytes()], the behavior is not threadsafe.\n** Hence, the sqlite3_column_value() interface\n** is normally only useful within the implementation of \n** [application-defined SQL functions] or [virtual tables], not within\n** top-level application code.\n**\n** The these routines may attempt to convert the datatype of the result.\n** ^For example, if the internal representation is FLOAT and a text result\n** is requested, [sqlite3_snprintf()] is used internally to perform the\n** conversion automatically.  ^(The following table details the conversions\n** that are applied:\n**\n** <blockquote>\n** <table border=\"1\">\n** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion\n**\n** <tr><td>  NULL    <td> INTEGER   <td> Result is 0\n** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0\n** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer\n** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer\n** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float\n** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer\n** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT\n** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER\n** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float\n** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB\n** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER\n** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL\n** <tr><td>  TEXT    <td>   BLOB    <td> No change\n** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER\n** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL\n** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed\n** </table>\n** </blockquote>)^\n**\n** Note that when type conversions occur, pointers returned by prior\n** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or\n** sqlite3_column_text16() may be invalidated.\n** Type conversions and pointer invalidations might occur\n** in the following cases:\n**\n** <ul>\n** <li> The initial content is a BLOB and sqlite3_column_text() or\n**      sqlite3_column_text16() is called.  A zero-terminator might\n**      need to be added to the string.</li>\n** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or\n**      sqlite3_column_text16() is called.  The content must be converted\n**      to UTF-16.</li>\n** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or\n**      sqlite3_column_text() is called.  The content must be converted\n**      to UTF-8.</li>\n** </ul>\n**\n** ^Conversions between UTF-16be and UTF-16le are always done in place and do\n** not invalidate a prior pointer, though of course the content of the buffer\n** that the prior pointer references will have been modified.  Other kinds\n** of conversion are done in place when it is possible, but sometimes they\n** are not possible and in those cases prior pointers are invalidated.\n**\n** The safest policy is to invoke these routines\n** in one of the following ways:\n**\n** <ul>\n**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>\n**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>\n**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>\n** </ul>\n**\n** In other words, you should call sqlite3_column_text(),\n** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result\n** into the desired format, then invoke sqlite3_column_bytes() or\n** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls\n** to sqlite3_column_text() or sqlite3_column_blob() with calls to\n** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()\n** with calls to sqlite3_column_bytes().\n**\n** ^The pointers returned are valid until a type conversion occurs as\n** described above, or until [sqlite3_step()] or [sqlite3_reset()] or\n** [sqlite3_finalize()] is called.  ^The memory space used to hold strings\n** and BLOBs is freed automatically.  Do not pass the pointers returned\n** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into\n** [sqlite3_free()].\n**\n** As long as the input parameters are correct, these routines will only\n** fail if an out-of-memory error occurs during a format conversion.\n** Only the following subset of interfaces are subject to out-of-memory\n** errors:\n**\n** <ul>\n** <li> sqlite3_column_blob()\n** <li> sqlite3_column_text()\n** <li> sqlite3_column_text16()\n** <li> sqlite3_column_bytes()\n** <li> sqlite3_column_bytes16()\n** </ul>\n**\n** If an out-of-memory error occurs, then the return value from these\n** routines is the same as if the column had contained an SQL NULL value.\n** Valid SQL NULL returns can be distinguished from out-of-memory errors\n** by invoking the [sqlite3_errcode()] immediately after the suspect\n** return value is obtained and before any\n** other SQLite interface is called on the same [database connection].\n*/\nSQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);\nSQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);\nSQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);\nSQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);\nSQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);\nSQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);\nSQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);\nSQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);\nSQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);\nSQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);\n\n/*\n** CAPI3REF: Destroy A Prepared Statement Object\n** DESTRUCTOR: sqlite3_stmt\n**\n** ^The sqlite3_finalize() function is called to delete a [prepared statement].\n** ^If the most recent evaluation of the statement encountered no errors\n** or if the statement is never been evaluated, then sqlite3_finalize() returns\n** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then\n** sqlite3_finalize(S) returns the appropriate [error code] or\n** [extended error code].\n**\n** ^The sqlite3_finalize(S) routine can be called at any point during\n** the life cycle of [prepared statement] S:\n** before statement S is ever evaluated, after\n** one or more calls to [sqlite3_reset()], or after any call\n** to [sqlite3_step()] regardless of whether or not the statement has\n** completed execution.\n**\n** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.\n**\n** The application must finalize every [prepared statement] in order to avoid\n** resource leaks.  It is a grievous error for the application to try to use\n** a prepared statement after it has been finalized.  Any use of a prepared\n** statement after it has been finalized can result in undefined and\n** undesirable behavior such as segfaults and heap corruption.\n*/\nSQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Reset A Prepared Statement Object\n** METHOD: sqlite3_stmt\n**\n** The sqlite3_reset() function is called to reset a [prepared statement]\n** object back to its initial state, ready to be re-executed.\n** ^Any SQL statement variables that had values bound to them using\n** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.\n** Use [sqlite3_clear_bindings()] to reset the bindings.\n**\n** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S\n** back to the beginning of its program.\n**\n** ^If the most recent call to [sqlite3_step(S)] for the\n** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],\n** or if [sqlite3_step(S)] has never before been called on S,\n** then [sqlite3_reset(S)] returns [SQLITE_OK].\n**\n** ^If the most recent call to [sqlite3_step(S)] for the\n** [prepared statement] S indicated an error, then\n** [sqlite3_reset(S)] returns an appropriate [error code].\n**\n** ^The [sqlite3_reset(S)] interface does not change the values\n** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.\n*/\nSQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Create Or Redefine SQL Functions\n** KEYWORDS: {function creation routines}\n** METHOD: sqlite3\n**\n** ^These functions (collectively known as \"function creation routines\")\n** are used to add SQL functions or aggregates or to redefine the behavior\n** of existing SQL functions or aggregates. The only differences between\n** the three \"sqlite3_create_function*\" routines are the text encoding \n** expected for the second parameter (the name of the function being \n** created) and the presence or absence of a destructor callback for\n** the application data pointer. Function sqlite3_create_window_function()\n** is similar, but allows the user to supply the extra callback functions\n** needed by [aggregate window functions].\n**\n** ^The first parameter is the [database connection] to which the SQL\n** function is to be added.  ^If an application uses more than one database\n** connection then application-defined SQL functions must be added\n** to each database connection separately.\n**\n** ^The second parameter is the name of the SQL function to be created or\n** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8\n** representation, exclusive of the zero-terminator.  ^Note that the name\n** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  \n** ^Any attempt to create a function with a longer name\n** will result in [SQLITE_MISUSE] being returned.\n**\n** ^The third parameter (nArg)\n** is the number of arguments that the SQL function or\n** aggregate takes. ^If this parameter is -1, then the SQL function or\n** aggregate may take any number of arguments between 0 and the limit\n** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third\n** parameter is less than -1 or greater than 127 then the behavior is\n** undefined.\n**\n** ^The fourth parameter, eTextRep, specifies what\n** [SQLITE_UTF8 | text encoding] this SQL function prefers for\n** its parameters.  The application should set this parameter to\n** [SQLITE_UTF16LE] if the function implementation invokes \n** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the\n** implementation invokes [sqlite3_value_text16be()] on an input, or\n** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]\n** otherwise.  ^The same SQL function may be registered multiple times using\n** different preferred text encodings, with different implementations for\n** each encoding.\n** ^When multiple implementations of the same function are available, SQLite\n** will pick the one that involves the least amount of data conversion.\n**\n** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]\n** to signal that the function will always return the same result given\n** the same inputs within a single SQL statement.  Most SQL functions are\n** deterministic.  The built-in [random()] SQL function is an example of a\n** function that is not deterministic.  The SQLite query planner is able to\n** perform additional optimizations on deterministic functions, so use\n** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.\n**\n** ^The fourth parameter may also optionally include the [SQLITE_DIRECTONLY]\n** flag, which if present prevents the function from being invoked from\n** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions,\n** index expressions, or the WHERE clause of partial indexes.\n**\n** <span style=\"background-color:#ffff90;\">\n** For best security, the [SQLITE_DIRECTONLY] flag is recommended for\n** all application-defined SQL functions that do not need to be\n** used inside of triggers, view, CHECK constraints, or other elements of\n** the database schema.  This flags is especially recommended for SQL \n** functions that have side effects or reveal internal application state.\n** Without this flag, an attacker might be able to modify the schema of\n** a database file to include invocations of the function with parameters\n** chosen by the attacker, which the application will then execute when\n** the database file is opened and read.\n** </span>\n**\n** ^(The fifth parameter is an arbitrary pointer.  The implementation of the\n** function can gain access to this pointer using [sqlite3_user_data()].)^\n**\n** ^The sixth, seventh and eighth parameters passed to the three\n** \"sqlite3_create_function*\" functions, xFunc, xStep and xFinal, are\n** pointers to C-language functions that implement the SQL function or\n** aggregate. ^A scalar SQL function requires an implementation of the xFunc\n** callback only; NULL pointers must be passed as the xStep and xFinal\n** parameters. ^An aggregate SQL function requires an implementation of xStep\n** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing\n** SQL function or aggregate, pass NULL pointers for all three function\n** callbacks.\n**\n** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue \n** and xInverse) passed to sqlite3_create_window_function are pointers to\n** C-language callbacks that implement the new function. xStep and xFinal\n** must both be non-NULL. xValue and xInverse may either both be NULL, in\n** which case a regular aggregate function is created, or must both be \n** non-NULL, in which case the new function may be used as either an aggregate\n** or aggregate window function. More details regarding the implementation\n** of aggregate window functions are \n** [user-defined window functions|available here].\n**\n** ^(If the final parameter to sqlite3_create_function_v2() or\n** sqlite3_create_window_function() is not NULL, then it is destructor for\n** the application data pointer. The destructor is invoked when the function \n** is deleted, either by being overloaded or when the database connection \n** closes.)^ ^The destructor is also invoked if the call to \n** sqlite3_create_function_v2() fails.  ^When the destructor callback is\n** invoked, it is passed a single argument which is a copy of the application\n** data pointer which was the fifth parameter to sqlite3_create_function_v2().\n**\n** ^It is permitted to register multiple implementations of the same\n** functions with the same name but with either differing numbers of\n** arguments or differing preferred text encodings.  ^SQLite will use\n** the implementation that most closely matches the way in which the\n** SQL function is used.  ^A function implementation with a non-negative\n** nArg parameter is a better match than a function implementation with\n** a negative nArg.  ^A function where the preferred text encoding\n** matches the database encoding is a better\n** match than a function where the encoding is different.  \n** ^A function where the encoding difference is between UTF16le and UTF16be\n** is a closer match than a function where the encoding difference is\n** between UTF8 and UTF16.\n**\n** ^Built-in functions may be overloaded by new application-defined functions.\n**\n** ^An application-defined function is permitted to call other\n** SQLite interfaces.  However, such calls must not\n** close the database connection nor finalize or reset the prepared\n** statement in which the function is running.\n*/\nSQLITE_API int sqlite3_create_function(\n  sqlite3 *db,\n  const char *zFunctionName,\n  int nArg,\n  int eTextRep,\n  void *pApp,\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*)\n);\nSQLITE_API int sqlite3_create_function16(\n  sqlite3 *db,\n  const void *zFunctionName,\n  int nArg,\n  int eTextRep,\n  void *pApp,\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*)\n);\nSQLITE_API int sqlite3_create_function_v2(\n  sqlite3 *db,\n  const char *zFunctionName,\n  int nArg,\n  int eTextRep,\n  void *pApp,\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*),\n  void(*xDestroy)(void*)\n);\nSQLITE_API int sqlite3_create_window_function(\n  sqlite3 *db,\n  const char *zFunctionName,\n  int nArg,\n  int eTextRep,\n  void *pApp,\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*),\n  void (*xValue)(sqlite3_context*),\n  void (*xInverse)(sqlite3_context*,int,sqlite3_value**),\n  void(*xDestroy)(void*)\n);\n\n/*\n** CAPI3REF: Text Encodings\n**\n** These constant define integer codes that represent the various\n** text encodings supported by SQLite.\n*/\n#define SQLITE_UTF8           1    /* IMP: R-37514-35566 */\n#define SQLITE_UTF16LE        2    /* IMP: R-03371-37637 */\n#define SQLITE_UTF16BE        3    /* IMP: R-51971-34154 */\n#define SQLITE_UTF16          4    /* Use native byte order */\n#define SQLITE_ANY            5    /* Deprecated */\n#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */\n\n/*\n** CAPI3REF: Function Flags\n**\n** These constants may be ORed together with the \n** [SQLITE_UTF8 | preferred text encoding] as the fourth argument\n** to [sqlite3_create_function()], [sqlite3_create_function16()], or\n** [sqlite3_create_function_v2()].\n**\n** <dl>\n** [[SQLITE_DETERMINISTIC]] <dt>SQLITE_DETERMINISTIC</dt><dd>\n** The SQLITE_DETERMINISTIC flag means that the new function always gives\n** the same output when the input parameters are the same.\n** The [abs|abs() function] is deterministic, for example, but\n** [randomblob|randomblob()] is not.  Functions must\n** be deterministic in order to be used in certain contexts such as\n** with the WHERE clause of [partial indexes] or in [generated columns].\n** SQLite might also optimize deterministic functions by factoring them\n** out of inner loops.\n** </dd>\n** \n** [[SQLITE_DIRECTONLY]] <dt>SQLITE_DIRECTONLY</dt><dd>\n** The SQLITE_DIRECTONLY flag means that the function may only be invoked\n** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in \n** schema structures such as [CHECK constraints], [DEFAULT clauses],\n** [expression indexes], [partial indexes], or [generated columns].\n** The SQLITE_DIRECTONLY flags is a security feature which is recommended\n** for all [application-defined SQL functions], and especially for functions\n** that have side-effects or that could potentially leak sensitive\n** information.\n** </dd>\n**\n** [[SQLITE_INNOCUOUS]] <dt>SQLITE_INNOCUOUS</dt><dd>\n** The SQLITE_INNOCUOUS flag means that the function is unlikely\n** to cause problems even if misused.  An innocuous function should have\n** no side effects and should not depend on any values other than its\n** input parameters. The [abs|abs() function] is an example of an\n** innocuous function.\n** The [load_extension() SQL function] is not innocuous because of its\n** side effects.\n** <p> SQLITE_INNOCUOUS is similar to SQLITE_DETERMINISTIC, but is not\n** exactly the same.  The [random|random() function] is an example of a\n** function that is innocuous but not deterministic.\n** <p>Some heightened security settings\n** ([SQLITE_DBCONFIG_TRUSTED_SCHEMA] and [PRAGMA trusted_schema=OFF])\n** disable the use of SQL functions inside views and triggers and in\n** schema structures such as [CHECK constraints], [DEFAULT clauses],\n** [expression indexes], [partial indexes], and [generated columns] unless\n** the function is tagged with SQLITE_INNOCUOUS.  Most built-in functions\n** are innocuous.  Developers are advised to avoid using the\n** SQLITE_INNOCUOUS flag for application-defined functions unless the\n** function has been carefully audited and found to be free of potentially\n** security-adverse side-effects and information-leaks.\n** </dd>\n**\n** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd>\n** The SQLITE_SUBTYPE flag indicates to SQLite that a function may call\n** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.\n** Specifying this flag makes no difference for scalar or aggregate user\n** functions. However, if it is not specified for a user-defined window\n** function, then any sub-types belonging to arguments passed to the window\n** function may be discarded before the window function is called (i.e.\n** sqlite3_value_subtype() will always return 0).\n** </dd>\n** </dl>\n*/\n#define SQLITE_DETERMINISTIC    0x000000800\n#define SQLITE_DIRECTONLY       0x000080000\n#define SQLITE_SUBTYPE          0x000100000\n#define SQLITE_INNOCUOUS        0x000200000\n\n/*\n** CAPI3REF: Deprecated Functions\n** DEPRECATED\n**\n** These functions are [deprecated].  In order to maintain\n** backwards compatibility with older code, these functions continue \n** to be supported.  However, new applications should avoid\n** the use of these functions.  To encourage programmers to avoid\n** these functions, we will not explain what they do.\n*/\n#ifndef SQLITE_OMIT_DEPRECATED\nSQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);\nSQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);\nSQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);\nSQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);\nSQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);\nSQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),\n                      void*,sqlite3_int64);\n#endif\n\n/*\n** CAPI3REF: Obtaining SQL Values\n** METHOD: sqlite3_value\n**\n** <b>Summary:</b>\n** <blockquote><table border=0 cellpadding=0 cellspacing=0>\n** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value\n** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value\n** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value\n** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value\n** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value\n** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value\n** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in\n** the native byteorder\n** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value\n** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value\n** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;\n** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB\n** or a UTF-8 TEXT in bytes\n** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>\n** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16\n** TEXT in bytes\n** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default\n** datatype of the value\n** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>\n** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value\n** <tr><td><b>sqlite3_value_nochange&nbsp;&nbsp;</b>\n** <td>&rarr;&nbsp;&nbsp;<td>True if the column is unchanged in an UPDATE\n** against a virtual table.\n** <tr><td><b>sqlite3_value_frombind&nbsp;&nbsp;</b>\n** <td>&rarr;&nbsp;&nbsp;<td>True if value originated from a [bound parameter]\n** </table></blockquote>\n**\n** <b>Details:</b>\n**\n** These routines extract type, size, and content information from\n** [protected sqlite3_value] objects.  Protected sqlite3_value objects\n** are used to pass parameter information into the functions that\n** implement [application-defined SQL functions] and [virtual tables].\n**\n** These routines work only with [protected sqlite3_value] objects.\n** Any attempt to use these routines on an [unprotected sqlite3_value]\n** is not threadsafe.\n**\n** ^These routines work just like the corresponding [column access functions]\n** except that these routines take a single [protected sqlite3_value] object\n** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.\n**\n** ^The sqlite3_value_text16() interface extracts a UTF-16 string\n** in the native byte-order of the host machine.  ^The\n** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces\n** extract UTF-16 strings as big-endian and little-endian respectively.\n**\n** ^If [sqlite3_value] object V was initialized \n** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]\n** and if X and Y are strings that compare equal according to strcmp(X,Y),\n** then sqlite3_value_pointer(V,Y) will return the pointer P.  ^Otherwise,\n** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer() \n** routine is part of the [pointer passing interface] added for SQLite 3.20.0.\n**\n** ^(The sqlite3_value_type(V) interface returns the\n** [SQLITE_INTEGER | datatype code] for the initial datatype of the\n** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],\n** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^\n** Other interfaces might change the datatype for an sqlite3_value object.\n** For example, if the datatype is initially SQLITE_INTEGER and\n** sqlite3_value_text(V) is called to extract a text value for that\n** integer, then subsequent calls to sqlite3_value_type(V) might return\n** SQLITE_TEXT.  Whether or not a persistent internal datatype conversion\n** occurs is undefined and may change from one release of SQLite to the next.\n**\n** ^(The sqlite3_value_numeric_type() interface attempts to apply\n** numeric affinity to the value.  This means that an attempt is\n** made to convert the value to an integer or floating point.  If\n** such a conversion is possible without loss of information (in other\n** words, if the value is a string that looks like a number)\n** then the conversion is performed.  Otherwise no conversion occurs.\n** The [SQLITE_INTEGER | datatype] after conversion is returned.)^\n**\n** ^Within the [xUpdate] method of a [virtual table], the\n** sqlite3_value_nochange(X) interface returns true if and only if\n** the column corresponding to X is unchanged by the UPDATE operation\n** that the xUpdate method call was invoked to implement and if\n** and the prior [xColumn] method call that was invoked to extracted\n** the value for that column returned without setting a result (probably\n** because it queried [sqlite3_vtab_nochange()] and found that the column\n** was unchanging).  ^Within an [xUpdate] method, any value for which\n** sqlite3_value_nochange(X) is true will in all other respects appear\n** to be a NULL value.  If sqlite3_value_nochange(X) is invoked anywhere other\n** than within an [xUpdate] method call for an UPDATE statement, then\n** the return value is arbitrary and meaningless.\n**\n** ^The sqlite3_value_frombind(X) interface returns non-zero if the\n** value X originated from one of the [sqlite3_bind_int|sqlite3_bind()]\n** interfaces.  ^If X comes from an SQL literal value, or a table column,\n** or an expression, then sqlite3_value_frombind(X) returns zero.\n**\n** Please pay particular attention to the fact that the pointer returned\n** from [sqlite3_value_blob()], [sqlite3_value_text()], or\n** [sqlite3_value_text16()] can be invalidated by a subsequent call to\n** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],\n** or [sqlite3_value_text16()].\n**\n** These routines must be called from the same thread as\n** the SQL function that supplied the [sqlite3_value*] parameters.\n**\n** As long as the input parameter is correct, these routines can only\n** fail if an out-of-memory error occurs during a format conversion.\n** Only the following subset of interfaces are subject to out-of-memory\n** errors:\n**\n** <ul>\n** <li> sqlite3_value_blob()\n** <li> sqlite3_value_text()\n** <li> sqlite3_value_text16()\n** <li> sqlite3_value_text16le()\n** <li> sqlite3_value_text16be()\n** <li> sqlite3_value_bytes()\n** <li> sqlite3_value_bytes16()\n** </ul>\n**\n** If an out-of-memory error occurs, then the return value from these\n** routines is the same as if the column had contained an SQL NULL value.\n** Valid SQL NULL returns can be distinguished from out-of-memory errors\n** by invoking the [sqlite3_errcode()] immediately after the suspect\n** return value is obtained and before any\n** other SQLite interface is called on the same [database connection].\n*/\nSQLITE_API const void *sqlite3_value_blob(sqlite3_value*);\nSQLITE_API double sqlite3_value_double(sqlite3_value*);\nSQLITE_API int sqlite3_value_int(sqlite3_value*);\nSQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);\nSQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);\nSQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);\nSQLITE_API const void *sqlite3_value_text16(sqlite3_value*);\nSQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);\nSQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);\nSQLITE_API int sqlite3_value_bytes(sqlite3_value*);\nSQLITE_API int sqlite3_value_bytes16(sqlite3_value*);\nSQLITE_API int sqlite3_value_type(sqlite3_value*);\nSQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);\nSQLITE_API int sqlite3_value_nochange(sqlite3_value*);\nSQLITE_API int sqlite3_value_frombind(sqlite3_value*);\n\n/*\n** CAPI3REF: Finding The Subtype Of SQL Values\n** METHOD: sqlite3_value\n**\n** The sqlite3_value_subtype(V) function returns the subtype for\n** an [application-defined SQL function] argument V.  The subtype\n** information can be used to pass a limited amount of context from\n** one SQL function to another.  Use the [sqlite3_result_subtype()]\n** routine to set the subtype for the return value of an SQL function.\n*/\nSQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);\n\n/*\n** CAPI3REF: Copy And Free SQL Values\n** METHOD: sqlite3_value\n**\n** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]\n** object D and returns a pointer to that copy.  ^The [sqlite3_value] returned\n** is a [protected sqlite3_value] object even if the input is not.\n** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a\n** memory allocation fails.\n**\n** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object\n** previously obtained from [sqlite3_value_dup()].  ^If V is a NULL pointer\n** then sqlite3_value_free(V) is a harmless no-op.\n*/\nSQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);\nSQLITE_API void sqlite3_value_free(sqlite3_value*);\n\n/*\n** CAPI3REF: Obtain Aggregate Function Context\n** METHOD: sqlite3_context\n**\n** Implementations of aggregate SQL functions use this\n** routine to allocate memory for storing their state.\n**\n** ^The first time the sqlite3_aggregate_context(C,N) routine is called \n** for a particular aggregate function, SQLite allocates\n** N bytes of memory, zeroes out that memory, and returns a pointer\n** to the new memory. ^On second and subsequent calls to\n** sqlite3_aggregate_context() for the same aggregate function instance,\n** the same buffer is returned.  Sqlite3_aggregate_context() is normally\n** called once for each invocation of the xStep callback and then one\n** last time when the xFinal callback is invoked.  ^(When no rows match\n** an aggregate query, the xStep() callback of the aggregate function\n** implementation is never called and xFinal() is called exactly once.\n** In those cases, sqlite3_aggregate_context() might be called for the\n** first time from within xFinal().)^\n**\n** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer \n** when first called if N is less than or equal to zero or if a memory\n** allocate error occurs.\n**\n** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is\n** determined by the N parameter on first successful call.  Changing the\n** value of N in any subsequent call to sqlite3_aggregate_context() within\n** the same aggregate function instance will not resize the memory\n** allocation.)^  Within the xFinal callback, it is customary to set\n** N=0 in calls to sqlite3_aggregate_context(C,N) so that no \n** pointless memory allocations occur.\n**\n** ^SQLite automatically frees the memory allocated by \n** sqlite3_aggregate_context() when the aggregate query concludes.\n**\n** The first parameter must be a copy of the\n** [sqlite3_context | SQL function context] that is the first parameter\n** to the xStep or xFinal callback routine that implements the aggregate\n** function.\n**\n** This routine must be called from the same thread in which\n** the aggregate SQL function is running.\n*/\nSQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);\n\n/*\n** CAPI3REF: User Data For Functions\n** METHOD: sqlite3_context\n**\n** ^The sqlite3_user_data() interface returns a copy of\n** the pointer that was the pUserData parameter (the 5th parameter)\n** of the [sqlite3_create_function()]\n** and [sqlite3_create_function16()] routines that originally\n** registered the application defined function.\n**\n** This routine must be called from the same thread in which\n** the application-defined function is running.\n*/\nSQLITE_API void *sqlite3_user_data(sqlite3_context*);\n\n/*\n** CAPI3REF: Database Connection For Functions\n** METHOD: sqlite3_context\n**\n** ^The sqlite3_context_db_handle() interface returns a copy of\n** the pointer to the [database connection] (the 1st parameter)\n** of the [sqlite3_create_function()]\n** and [sqlite3_create_function16()] routines that originally\n** registered the application defined function.\n*/\nSQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);\n\n/*\n** CAPI3REF: Function Auxiliary Data\n** METHOD: sqlite3_context\n**\n** These functions may be used by (non-aggregate) SQL functions to\n** associate metadata with argument values. If the same value is passed to\n** multiple invocations of the same SQL function during query execution, under\n** some circumstances the associated metadata may be preserved.  An example\n** of where this might be useful is in a regular-expression matching\n** function. The compiled version of the regular expression can be stored as\n** metadata associated with the pattern string.  \n** Then as long as the pattern string remains the same,\n** the compiled regular expression can be reused on multiple\n** invocations of the same function.\n**\n** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata\n** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument\n** value to the application-defined function.  ^N is zero for the left-most\n** function argument.  ^If there is no metadata\n** associated with the function argument, the sqlite3_get_auxdata(C,N) interface\n** returns a NULL pointer.\n**\n** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th\n** argument of the application-defined function.  ^Subsequent\n** calls to sqlite3_get_auxdata(C,N) return P from the most recent\n** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or\n** NULL if the metadata has been discarded.\n** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,\n** SQLite will invoke the destructor function X with parameter P exactly\n** once, when the metadata is discarded.\n** SQLite is free to discard the metadata at any time, including: <ul>\n** <li> ^(when the corresponding function parameter changes)^, or\n** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the\n**      SQL statement)^, or\n** <li> ^(when sqlite3_set_auxdata() is invoked again on the same\n**       parameter)^, or\n** <li> ^(during the original sqlite3_set_auxdata() call when a memory \n**      allocation error occurs.)^ </ul>\n**\n** Note the last bullet in particular.  The destructor X in \n** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the\n** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()\n** should be called near the end of the function implementation and the\n** function implementation should not make any use of P after\n** sqlite3_set_auxdata() has been called.\n**\n** ^(In practice, metadata is preserved between function calls for\n** function parameters that are compile-time constants, including literal\n** values and [parameters] and expressions composed from the same.)^\n**\n** The value of the N parameter to these interfaces should be non-negative.\n** Future enhancements may make use of negative N values to define new\n** kinds of function caching behavior.\n**\n** These routines must be called from the same thread in which\n** the SQL function is running.\n*/\nSQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);\nSQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));\n\n\n/*\n** CAPI3REF: Constants Defining Special Destructor Behavior\n**\n** These are special values for the destructor that is passed in as the\n** final argument to routines like [sqlite3_result_blob()].  ^If the destructor\n** argument is SQLITE_STATIC, it means that the content pointer is constant\n** and will never change.  It does not need to be destroyed.  ^The\n** SQLITE_TRANSIENT value means that the content will likely change in\n** the near future and that SQLite should make its own private copy of\n** the content before returning.\n**\n** The typedef is necessary to work around problems in certain\n** C++ compilers.\n*/\ntypedef void (*sqlite3_destructor_type)(void*);\n#define SQLITE_STATIC      ((sqlite3_destructor_type)0)\n#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)\n\n/*\n** CAPI3REF: Setting The Result Of An SQL Function\n** METHOD: sqlite3_context\n**\n** These routines are used by the xFunc or xFinal callbacks that\n** implement SQL functions and aggregates.  See\n** [sqlite3_create_function()] and [sqlite3_create_function16()]\n** for additional information.\n**\n** These functions work very much like the [parameter binding] family of\n** functions used to bind values to host parameters in prepared statements.\n** Refer to the [SQL parameter] documentation for additional information.\n**\n** ^The sqlite3_result_blob() interface sets the result from\n** an application-defined function to be the BLOB whose content is pointed\n** to by the second parameter and which is N bytes long where N is the\n** third parameter.\n**\n** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)\n** interfaces set the result of the application-defined function to be\n** a BLOB containing all zero bytes and N bytes in size.\n**\n** ^The sqlite3_result_double() interface sets the result from\n** an application-defined function to be a floating point value specified\n** by its 2nd argument.\n**\n** ^The sqlite3_result_error() and sqlite3_result_error16() functions\n** cause the implemented SQL function to throw an exception.\n** ^SQLite uses the string pointed to by the\n** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()\n** as the text of an error message.  ^SQLite interprets the error\n** message string from sqlite3_result_error() as UTF-8. ^SQLite\n** interprets the string from sqlite3_result_error16() as UTF-16 using\n** the same [byte-order determination rules] as [sqlite3_bind_text16()].\n** ^If the third parameter to sqlite3_result_error()\n** or sqlite3_result_error16() is negative then SQLite takes as the error\n** message all text up through the first zero character.\n** ^If the third parameter to sqlite3_result_error() or\n** sqlite3_result_error16() is non-negative then SQLite takes that many\n** bytes (not characters) from the 2nd parameter as the error message.\n** ^The sqlite3_result_error() and sqlite3_result_error16()\n** routines make a private copy of the error message text before\n** they return.  Hence, the calling function can deallocate or\n** modify the text after they return without harm.\n** ^The sqlite3_result_error_code() function changes the error code\n** returned by SQLite as a result of an error in a function.  ^By default,\n** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()\n** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.\n**\n** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an\n** error indicating that a string or BLOB is too long to represent.\n**\n** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an\n** error indicating that a memory allocation failed.\n**\n** ^The sqlite3_result_int() interface sets the return value\n** of the application-defined function to be the 32-bit signed integer\n** value given in the 2nd argument.\n** ^The sqlite3_result_int64() interface sets the return value\n** of the application-defined function to be the 64-bit signed integer\n** value given in the 2nd argument.\n**\n** ^The sqlite3_result_null() interface sets the return value\n** of the application-defined function to be NULL.\n**\n** ^The sqlite3_result_text(), sqlite3_result_text16(),\n** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces\n** set the return value of the application-defined function to be\n** a text string which is represented as UTF-8, UTF-16 native byte order,\n** UTF-16 little endian, or UTF-16 big endian, respectively.\n** ^The sqlite3_result_text64() interface sets the return value of an\n** application-defined function to be a text string in an encoding\n** specified by the fifth (and last) parameter, which must be one\n** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].\n** ^SQLite takes the text result from the application from\n** the 2nd parameter of the sqlite3_result_text* interfaces.\n** ^If the 3rd parameter to the sqlite3_result_text* interfaces\n** is negative, then SQLite takes result text from the 2nd parameter\n** through the first zero character.\n** ^If the 3rd parameter to the sqlite3_result_text* interfaces\n** is non-negative, then as many bytes (not characters) of the text\n** pointed to by the 2nd parameter are taken as the application-defined\n** function result.  If the 3rd parameter is non-negative, then it\n** must be the byte offset into the string where the NUL terminator would\n** appear if the string where NUL terminated.  If any NUL characters occur\n** in the string at a byte offset that is less than the value of the 3rd\n** parameter, then the resulting string will contain embedded NULs and the\n** result of expressions operating on strings with embedded NULs is undefined.\n** ^If the 4th parameter to the sqlite3_result_text* interfaces\n** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that\n** function as the destructor on the text or BLOB result when it has\n** finished using that result.\n** ^If the 4th parameter to the sqlite3_result_text* interfaces or to\n** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite\n** assumes that the text or BLOB result is in constant space and does not\n** copy the content of the parameter nor call a destructor on the content\n** when it has finished using that result.\n** ^If the 4th parameter to the sqlite3_result_text* interfaces\n** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT\n** then SQLite makes a copy of the result into space obtained\n** from [sqlite3_malloc()] before it returns.\n**\n** ^For the sqlite3_result_text16(), sqlite3_result_text16le(), and\n** sqlite3_result_text16be() routines, and for sqlite3_result_text64()\n** when the encoding is not UTF8, if the input UTF16 begins with a\n** byte-order mark (BOM, U+FEFF) then the BOM is removed from the\n** string and the rest of the string is interpreted according to the\n** byte-order specified by the BOM.  ^The byte-order specified by\n** the BOM at the beginning of the text overrides the byte-order\n** specified by the interface procedure.  ^So, for example, if\n** sqlite3_result_text16le() is invoked with text that begins\n** with bytes 0xfe, 0xff (a big-endian byte-order mark) then the\n** first two bytes of input are skipped and the remaining input\n** is interpreted as UTF16BE text.\n**\n** ^For UTF16 input text to the sqlite3_result_text16(),\n** sqlite3_result_text16be(), sqlite3_result_text16le(), and\n** sqlite3_result_text64() routines, if the text contains invalid\n** UTF16 characters, the invalid characters might be converted\n** into the unicode replacement character, U+FFFD.\n**\n** ^The sqlite3_result_value() interface sets the result of\n** the application-defined function to be a copy of the\n** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The\n** sqlite3_result_value() interface makes a copy of the [sqlite3_value]\n** so that the [sqlite3_value] specified in the parameter may change or\n** be deallocated after sqlite3_result_value() returns without harm.\n** ^A [protected sqlite3_value] object may always be used where an\n** [unprotected sqlite3_value] object is required, so either\n** kind of [sqlite3_value] object can be used with this interface.\n**\n** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an\n** SQL NULL value, just like [sqlite3_result_null(C)], except that it\n** also associates the host-language pointer P or type T with that \n** NULL value such that the pointer can be retrieved within an\n** [application-defined SQL function] using [sqlite3_value_pointer()].\n** ^If the D parameter is not NULL, then it is a pointer to a destructor\n** for the P parameter.  ^SQLite invokes D with P as its only argument\n** when SQLite is finished with P.  The T parameter should be a static\n** string and preferably a string literal. The sqlite3_result_pointer()\n** routine is part of the [pointer passing interface] added for SQLite 3.20.0.\n**\n** If these routines are called from within the different thread\n** than the one containing the application-defined function that received\n** the [sqlite3_context] pointer, the results are undefined.\n*/\nSQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));\nSQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,\n                           sqlite3_uint64,void(*)(void*));\nSQLITE_API void sqlite3_result_double(sqlite3_context*, double);\nSQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);\nSQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);\nSQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);\nSQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);\nSQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);\nSQLITE_API void sqlite3_result_int(sqlite3_context*, int);\nSQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);\nSQLITE_API void sqlite3_result_null(sqlite3_context*);\nSQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));\nSQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,\n                           void(*)(void*), unsigned char encoding);\nSQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));\nSQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));\nSQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));\nSQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);\nSQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));\nSQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);\nSQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);\n\n\n/*\n** CAPI3REF: Setting The Subtype Of An SQL Function\n** METHOD: sqlite3_context\n**\n** The sqlite3_result_subtype(C,T) function causes the subtype of\n** the result from the [application-defined SQL function] with \n** [sqlite3_context] C to be the value T.  Only the lower 8 bits \n** of the subtype T are preserved in current versions of SQLite;\n** higher order bits are discarded.\n** The number of subtype bytes preserved by SQLite might increase\n** in future releases of SQLite.\n*/\nSQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);\n\n/*\n** CAPI3REF: Define New Collating Sequences\n** METHOD: sqlite3\n**\n** ^These functions add, remove, or modify a [collation] associated\n** with the [database connection] specified as the first argument.\n**\n** ^The name of the collation is a UTF-8 string\n** for sqlite3_create_collation() and sqlite3_create_collation_v2()\n** and a UTF-16 string in native byte order for sqlite3_create_collation16().\n** ^Collation names that compare equal according to [sqlite3_strnicmp()] are\n** considered to be the same name.\n**\n** ^(The third argument (eTextRep) must be one of the constants:\n** <ul>\n** <li> [SQLITE_UTF8],\n** <li> [SQLITE_UTF16LE],\n** <li> [SQLITE_UTF16BE],\n** <li> [SQLITE_UTF16], or\n** <li> [SQLITE_UTF16_ALIGNED].\n** </ul>)^\n** ^The eTextRep argument determines the encoding of strings passed\n** to the collating function callback, xCompare.\n** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep\n** force strings to be UTF16 with native byte order.\n** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin\n** on an even byte address.\n**\n** ^The fourth argument, pArg, is an application data pointer that is passed\n** through as the first argument to the collating function callback.\n**\n** ^The fifth argument, xCompare, is a pointer to the collating function.\n** ^Multiple collating functions can be registered using the same name but\n** with different eTextRep parameters and SQLite will use whichever\n** function requires the least amount of data transformation.\n** ^If the xCompare argument is NULL then the collating function is\n** deleted.  ^When all collating functions having the same name are deleted,\n** that collation is no longer usable.\n**\n** ^The collating function callback is invoked with a copy of the pArg \n** application data pointer and with two strings in the encoding specified\n** by the eTextRep argument.  The two integer parameters to the collating\n** function callback are the length of the two strings, in bytes. The collating\n** function must return an integer that is negative, zero, or positive\n** if the first string is less than, equal to, or greater than the second,\n** respectively.  A collating function must always return the same answer\n** given the same inputs.  If two or more collating functions are registered\n** to the same collation name (using different eTextRep values) then all\n** must give an equivalent answer when invoked with equivalent strings.\n** The collating function must obey the following properties for all\n** strings A, B, and C:\n**\n** <ol>\n** <li> If A==B then B==A.\n** <li> If A==B and B==C then A==C.\n** <li> If A&lt;B THEN B&gt;A.\n** <li> If A&lt;B and B&lt;C then A&lt;C.\n** </ol>\n**\n** If a collating function fails any of the above constraints and that\n** collating function is registered and used, then the behavior of SQLite\n** is undefined.\n**\n** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()\n** with the addition that the xDestroy callback is invoked on pArg when\n** the collating function is deleted.\n** ^Collating functions are deleted when they are overridden by later\n** calls to the collation creation functions or when the\n** [database connection] is closed using [sqlite3_close()].\n**\n** ^The xDestroy callback is <u>not</u> called if the \n** sqlite3_create_collation_v2() function fails.  Applications that invoke\n** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should \n** check the return code and dispose of the application data pointer\n** themselves rather than expecting SQLite to deal with it for them.\n** This is different from every other SQLite interface.  The inconsistency \n** is unfortunate but cannot be changed without breaking backwards \n** compatibility.\n**\n** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].\n*/\nSQLITE_API int sqlite3_create_collation(\n  sqlite3*, \n  const char *zName, \n  int eTextRep, \n  void *pArg,\n  int(*xCompare)(void*,int,const void*,int,const void*)\n);\nSQLITE_API int sqlite3_create_collation_v2(\n  sqlite3*, \n  const char *zName, \n  int eTextRep, \n  void *pArg,\n  int(*xCompare)(void*,int,const void*,int,const void*),\n  void(*xDestroy)(void*)\n);\nSQLITE_API int sqlite3_create_collation16(\n  sqlite3*, \n  const void *zName,\n  int eTextRep, \n  void *pArg,\n  int(*xCompare)(void*,int,const void*,int,const void*)\n);\n\n/*\n** CAPI3REF: Collation Needed Callbacks\n** METHOD: sqlite3\n**\n** ^To avoid having to register all collation sequences before a database\n** can be used, a single callback function may be registered with the\n** [database connection] to be invoked whenever an undefined collation\n** sequence is required.\n**\n** ^If the function is registered using the sqlite3_collation_needed() API,\n** then it is passed the names of undefined collation sequences as strings\n** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,\n** the names are passed as UTF-16 in machine native byte order.\n** ^A call to either function replaces the existing collation-needed callback.\n**\n** ^(When the callback is invoked, the first argument passed is a copy\n** of the second argument to sqlite3_collation_needed() or\n** sqlite3_collation_needed16().  The second argument is the database\n** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],\n** or [SQLITE_UTF16LE], indicating the most desirable form of the collation\n** sequence function required.  The fourth parameter is the name of the\n** required collation sequence.)^\n**\n** The callback function should register the desired collation using\n** [sqlite3_create_collation()], [sqlite3_create_collation16()], or\n** [sqlite3_create_collation_v2()].\n*/\nSQLITE_API int sqlite3_collation_needed(\n  sqlite3*, \n  void*, \n  void(*)(void*,sqlite3*,int eTextRep,const char*)\n);\nSQLITE_API int sqlite3_collation_needed16(\n  sqlite3*, \n  void*,\n  void(*)(void*,sqlite3*,int eTextRep,const void*)\n);\n\n#ifdef SQLITE_ENABLE_CEROD\n/*\n** Specify the activation key for a CEROD database.  Unless \n** activated, none of the CEROD routines will work.\n*/\nSQLITE_API void sqlite3_activate_cerod(\n  const char *zPassPhrase        /* Activation phrase */\n);\n#endif\n\n/*\n** CAPI3REF: Suspend Execution For A Short Time\n**\n** The sqlite3_sleep() function causes the current thread to suspend execution\n** for at least a number of milliseconds specified in its parameter.\n**\n** If the operating system does not support sleep requests with\n** millisecond time resolution, then the time will be rounded up to\n** the nearest second. The number of milliseconds of sleep actually\n** requested from the operating system is returned.\n**\n** ^SQLite implements this interface by calling the xSleep()\n** method of the default [sqlite3_vfs] object.  If the xSleep() method\n** of the default VFS is not implemented correctly, or not implemented at\n** all, then the behavior of sqlite3_sleep() may deviate from the description\n** in the previous paragraphs.\n*/\nSQLITE_API int sqlite3_sleep(int);\n\n/*\n** CAPI3REF: Name Of The Folder Holding Temporary Files\n**\n** ^(If this global variable is made to point to a string which is\n** the name of a folder (a.k.a. directory), then all temporary files\n** created by SQLite when using a built-in [sqlite3_vfs | VFS]\n** will be placed in that directory.)^  ^If this variable\n** is a NULL pointer, then SQLite performs a search for an appropriate\n** temporary file directory.\n**\n** Applications are strongly discouraged from using this global variable.\n** It is required to set a temporary folder on Windows Runtime (WinRT).\n** But for all other platforms, it is highly recommended that applications\n** neither read nor write this variable.  This global variable is a relic\n** that exists for backwards compatibility of legacy applications and should\n** be avoided in new projects.\n**\n** It is not safe to read or modify this variable in more than one\n** thread at a time.  It is not safe to read or modify this variable\n** if a [database connection] is being used at the same time in a separate\n** thread.\n** It is intended that this variable be set once\n** as part of process initialization and before any SQLite interface\n** routines have been called and that this variable remain unchanged\n** thereafter.\n**\n** ^The [temp_store_directory pragma] may modify this variable and cause\n** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,\n** the [temp_store_directory pragma] always assumes that any string\n** that this variable points to is held in memory obtained from \n** [sqlite3_malloc] and the pragma may attempt to free that memory\n** using [sqlite3_free].\n** Hence, if this variable is modified directly, either it should be\n** made NULL or made to point to memory obtained from [sqlite3_malloc]\n** or else the use of the [temp_store_directory pragma] should be avoided.\n** Except when requested by the [temp_store_directory pragma], SQLite\n** does not free the memory that sqlite3_temp_directory points to.  If\n** the application wants that memory to be freed, it must do\n** so itself, taking care to only do so after all [database connection]\n** objects have been destroyed.\n**\n** <b>Note to Windows Runtime users:</b>  The temporary directory must be set\n** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various\n** features that require the use of temporary files may fail.  Here is an\n** example of how to do this using C++ with the Windows Runtime:\n**\n** <blockquote><pre>\n** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->\n** &nbsp;     TemporaryFolder->Path->Data();\n** char zPathBuf&#91;MAX_PATH + 1&#93;;\n** memset(zPathBuf, 0, sizeof(zPathBuf));\n** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),\n** &nbsp;     NULL, NULL);\n** sqlite3_temp_directory = sqlite3_mprintf(\"%s\", zPathBuf);\n** </pre></blockquote>\n*/\nSQLITE_API char *sqlite3_temp_directory;\n\n/*\n** CAPI3REF: Name Of The Folder Holding Database Files\n**\n** ^(If this global variable is made to point to a string which is\n** the name of a folder (a.k.a. directory), then all database files\n** specified with a relative pathname and created or accessed by\n** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed\n** to be relative to that directory.)^ ^If this variable is a NULL\n** pointer, then SQLite assumes that all database files specified\n** with a relative pathname are relative to the current directory\n** for the process.  Only the windows VFS makes use of this global\n** variable; it is ignored by the unix VFS.\n**\n** Changing the value of this variable while a database connection is\n** open can result in a corrupt database.\n**\n** It is not safe to read or modify this variable in more than one\n** thread at a time.  It is not safe to read or modify this variable\n** if a [database connection] is being used at the same time in a separate\n** thread.\n** It is intended that this variable be set once\n** as part of process initialization and before any SQLite interface\n** routines have been called and that this variable remain unchanged\n** thereafter.\n**\n** ^The [data_store_directory pragma] may modify this variable and cause\n** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,\n** the [data_store_directory pragma] always assumes that any string\n** that this variable points to is held in memory obtained from \n** [sqlite3_malloc] and the pragma may attempt to free that memory\n** using [sqlite3_free].\n** Hence, if this variable is modified directly, either it should be\n** made NULL or made to point to memory obtained from [sqlite3_malloc]\n** or else the use of the [data_store_directory pragma] should be avoided.\n*/\nSQLITE_API char *sqlite3_data_directory;\n\n/*\n** CAPI3REF: Win32 Specific Interface\n**\n** These interfaces are available only on Windows.  The\n** [sqlite3_win32_set_directory] interface is used to set the value associated\n** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to\n** zValue, depending on the value of the type parameter.  The zValue parameter\n** should be NULL to cause the previous value to be freed via [sqlite3_free];\n** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]\n** prior to being used.  The [sqlite3_win32_set_directory] interface returns\n** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,\n** or [SQLITE_NOMEM] if memory could not be allocated.  The value of the\n** [sqlite3_data_directory] variable is intended to act as a replacement for\n** the current directory on the sub-platforms of Win32 where that concept is\n** not present, e.g. WinRT and UWP.  The [sqlite3_win32_set_directory8] and\n** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the\n** sqlite3_win32_set_directory interface except the string parameter must be\n** UTF-8 or UTF-16, respectively.\n*/\nSQLITE_API int sqlite3_win32_set_directory(\n  unsigned long type, /* Identifier for directory being set or reset */\n  void *zValue        /* New value for directory being set or reset */\n);\nSQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);\nSQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);\n\n/*\n** CAPI3REF: Win32 Directory Types\n**\n** These macros are only available on Windows.  They define the allowed values\n** for the type argument to the [sqlite3_win32_set_directory] interface.\n*/\n#define SQLITE_WIN32_DATA_DIRECTORY_TYPE  1\n#define SQLITE_WIN32_TEMP_DIRECTORY_TYPE  2\n\n/*\n** CAPI3REF: Test For Auto-Commit Mode\n** KEYWORDS: {autocommit mode}\n** METHOD: sqlite3\n**\n** ^The sqlite3_get_autocommit() interface returns non-zero or\n** zero if the given database connection is or is not in autocommit mode,\n** respectively.  ^Autocommit mode is on by default.\n** ^Autocommit mode is disabled by a [BEGIN] statement.\n** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].\n**\n** If certain kinds of errors occur on a statement within a multi-statement\n** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],\n** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the\n** transaction might be rolled back automatically.  The only way to\n** find out whether SQLite automatically rolled back the transaction after\n** an error is to use this function.\n**\n** If another thread changes the autocommit status of the database\n** connection while this routine is running, then the return value\n** is undefined.\n*/\nSQLITE_API int sqlite3_get_autocommit(sqlite3*);\n\n/*\n** CAPI3REF: Find The Database Handle Of A Prepared Statement\n** METHOD: sqlite3_stmt\n**\n** ^The sqlite3_db_handle interface returns the [database connection] handle\n** to which a [prepared statement] belongs.  ^The [database connection]\n** returned by sqlite3_db_handle is the same [database connection]\n** that was the first argument\n** to the [sqlite3_prepare_v2()] call (or its variants) that was used to\n** create the statement in the first place.\n*/\nSQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Return The Filename For A Database Connection\n** METHOD: sqlite3\n**\n** ^The sqlite3_db_filename(D,N) interface returns a pointer to the filename\n** associated with database N of connection D.\n** ^If there is no attached database N on the database\n** connection D, or if database N is a temporary or in-memory database, then\n** this function will return either a NULL pointer or an empty string.\n**\n** ^The string value returned by this routine is owned and managed by\n** the database connection.  ^The value will be valid until the database N\n** is [DETACH]-ed or until the database connection closes.\n**\n** ^The filename returned by this function is the output of the\n** xFullPathname method of the [VFS].  ^In other words, the filename\n** will be an absolute pathname, even if the filename used\n** to open the database originally was a URI or relative pathname.\n**\n** If the filename pointer returned by this routine is not NULL, then it\n** can be used as the filename input parameter to these routines:\n** <ul>\n** <li> [sqlite3_uri_parameter()]\n** <li> [sqlite3_uri_boolean()]\n** <li> [sqlite3_uri_int64()]\n** <li> [sqlite3_filename_database()]\n** <li> [sqlite3_filename_journal()]\n** <li> [sqlite3_filename_wal()]\n** </ul>\n*/\nSQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);\n\n/*\n** CAPI3REF: Determine if a database is read-only\n** METHOD: sqlite3\n**\n** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N\n** of connection D is read-only, 0 if it is read/write, or -1 if N is not\n** the name of a database on connection D.\n*/\nSQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);\n\n/*\n** CAPI3REF: Find the next prepared statement\n** METHOD: sqlite3\n**\n** ^This interface returns a pointer to the next [prepared statement] after\n** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL\n** then this interface returns a pointer to the first prepared statement\n** associated with the database connection pDb.  ^If no prepared statement\n** satisfies the conditions of this routine, it returns NULL.\n**\n** The [database connection] pointer D in a call to\n** [sqlite3_next_stmt(D,S)] must refer to an open database\n** connection and in particular must not be a NULL pointer.\n*/\nSQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Commit And Rollback Notification Callbacks\n** METHOD: sqlite3\n**\n** ^The sqlite3_commit_hook() interface registers a callback\n** function to be invoked whenever a transaction is [COMMIT | committed].\n** ^Any callback set by a previous call to sqlite3_commit_hook()\n** for the same database connection is overridden.\n** ^The sqlite3_rollback_hook() interface registers a callback\n** function to be invoked whenever a transaction is [ROLLBACK | rolled back].\n** ^Any callback set by a previous call to sqlite3_rollback_hook()\n** for the same database connection is overridden.\n** ^The pArg argument is passed through to the callback.\n** ^If the callback on a commit hook function returns non-zero,\n** then the commit is converted into a rollback.\n**\n** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions\n** return the P argument from the previous call of the same function\n** on the same [database connection] D, or NULL for\n** the first call for each function on D.\n**\n** The commit and rollback hook callbacks are not reentrant.\n** The callback implementation must not do anything that will modify\n** the database connection that invoked the callback.  Any actions\n** to modify the database connection must be deferred until after the\n** completion of the [sqlite3_step()] call that triggered the commit\n** or rollback hook in the first place.\n** Note that running any other SQL statements, including SELECT statements,\n** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify\n** the database connections for the meaning of \"modify\" in this paragraph.\n**\n** ^Registering a NULL function disables the callback.\n**\n** ^When the commit hook callback routine returns zero, the [COMMIT]\n** operation is allowed to continue normally.  ^If the commit hook\n** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].\n** ^The rollback hook is invoked on a rollback that results from a commit\n** hook returning non-zero, just as it would be with any other rollback.\n**\n** ^For the purposes of this API, a transaction is said to have been\n** rolled back if an explicit \"ROLLBACK\" statement is executed, or\n** an error or constraint causes an implicit rollback to occur.\n** ^The rollback callback is not invoked if a transaction is\n** automatically rolled back because the database connection is closed.\n**\n** See also the [sqlite3_update_hook()] interface.\n*/\nSQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);\nSQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);\n\n/*\n** CAPI3REF: Data Change Notification Callbacks\n** METHOD: sqlite3\n**\n** ^The sqlite3_update_hook() interface registers a callback function\n** with the [database connection] identified by the first argument\n** to be invoked whenever a row is updated, inserted or deleted in\n** a [rowid table].\n** ^Any callback set by a previous call to this function\n** for the same database connection is overridden.\n**\n** ^The second argument is a pointer to the function to invoke when a\n** row is updated, inserted or deleted in a rowid table.\n** ^The first argument to the callback is a copy of the third argument\n** to sqlite3_update_hook().\n** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],\n** or [SQLITE_UPDATE], depending on the operation that caused the callback\n** to be invoked.\n** ^The third and fourth arguments to the callback contain pointers to the\n** database and table name containing the affected row.\n** ^The final callback parameter is the [rowid] of the row.\n** ^In the case of an update, this is the [rowid] after the update takes place.\n**\n** ^(The update hook is not invoked when internal system tables are\n** modified (i.e. sqlite_master and sqlite_sequence).)^\n** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.\n**\n** ^In the current implementation, the update hook\n** is not invoked when conflicting rows are deleted because of an\n** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook\n** invoked when rows are deleted using the [truncate optimization].\n** The exceptions defined in this paragraph might change in a future\n** release of SQLite.\n**\n** The update hook implementation must not do anything that will modify\n** the database connection that invoked the update hook.  Any actions\n** to modify the database connection must be deferred until after the\n** completion of the [sqlite3_step()] call that triggered the update hook.\n** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their\n** database connections for the meaning of \"modify\" in this paragraph.\n**\n** ^The sqlite3_update_hook(D,C,P) function\n** returns the P argument from the previous call\n** on the same [database connection] D, or NULL for\n** the first call on D.\n**\n** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],\n** and [sqlite3_preupdate_hook()] interfaces.\n*/\nSQLITE_API void *sqlite3_update_hook(\n  sqlite3*, \n  void(*)(void *,int ,char const *,char const *,sqlite3_int64),\n  void*\n);\n\n/*\n** CAPI3REF: Enable Or Disable Shared Pager Cache\n**\n** ^(This routine enables or disables the sharing of the database cache\n** and schema data structures between [database connection | connections]\n** to the same database. Sharing is enabled if the argument is true\n** and disabled if the argument is false.)^\n**\n** ^Cache sharing is enabled and disabled for an entire process.\n** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]). \n** In prior versions of SQLite,\n** sharing was enabled or disabled for each thread separately.\n**\n** ^(The cache sharing mode set by this interface effects all subsequent\n** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].\n** Existing database connections continue to use the sharing mode\n** that was in effect at the time they were opened.)^\n**\n** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled\n** successfully.  An [error code] is returned otherwise.)^\n**\n** ^Shared cache is disabled by default. It is recommended that it stay\n** that way.  In other words, do not use this routine.  This interface\n** continues to be provided for historical compatibility, but its use is\n** discouraged.  Any use of shared cache is discouraged.  If shared cache\n** must be used, it is recommended that shared cache only be enabled for\n** individual database connections using the [sqlite3_open_v2()] interface\n** with the [SQLITE_OPEN_SHAREDCACHE] flag.\n**\n** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0\n** and will always return SQLITE_MISUSE. On those systems, \n** shared cache mode should be enabled per-database connection via \n** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].\n**\n** This interface is threadsafe on processors where writing a\n** 32-bit integer is atomic.\n**\n** See Also:  [SQLite Shared-Cache Mode]\n*/\nSQLITE_API int sqlite3_enable_shared_cache(int);\n\n/*\n** CAPI3REF: Attempt To Free Heap Memory\n**\n** ^The sqlite3_release_memory() interface attempts to free N bytes\n** of heap memory by deallocating non-essential memory allocations\n** held by the database library.   Memory used to cache database\n** pages to improve performance is an example of non-essential memory.\n** ^sqlite3_release_memory() returns the number of bytes actually freed,\n** which might be more or less than the amount requested.\n** ^The sqlite3_release_memory() routine is a no-op returning zero\n** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].\n**\n** See also: [sqlite3_db_release_memory()]\n*/\nSQLITE_API int sqlite3_release_memory(int);\n\n/*\n** CAPI3REF: Free Memory Used By A Database Connection\n** METHOD: sqlite3\n**\n** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap\n** memory as possible from database connection D. Unlike the\n** [sqlite3_release_memory()] interface, this interface is in effect even\n** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is\n** omitted.\n**\n** See also: [sqlite3_release_memory()]\n*/\nSQLITE_API int sqlite3_db_release_memory(sqlite3*);\n\n/*\n** CAPI3REF: Impose A Limit On Heap Size\n**\n** These interfaces impose limits on the amount of heap memory that will be\n** by all database connections within a single process.\n**\n** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the\n** soft limit on the amount of heap memory that may be allocated by SQLite.\n** ^SQLite strives to keep heap memory utilization below the soft heap\n** limit by reducing the number of pages held in the page cache\n** as heap memory usages approaches the limit.\n** ^The soft heap limit is \"soft\" because even though SQLite strives to stay\n** below the limit, it will exceed the limit rather than generate\n** an [SQLITE_NOMEM] error.  In other words, the soft heap limit \n** is advisory only.\n**\n** ^The sqlite3_hard_heap_limit64(N) interface sets a hard upper bound of\n** N bytes on the amount of memory that will be allocated.  ^The\n** sqlite3_hard_heap_limit64(N) interface is similar to\n** sqlite3_soft_heap_limit64(N) except that memory allocations will fail\n** when the hard heap limit is reached.\n**\n** ^The return value from both sqlite3_soft_heap_limit64() and\n** sqlite3_hard_heap_limit64() is the size of\n** the heap limit prior to the call, or negative in the case of an\n** error.  ^If the argument N is negative\n** then no change is made to the heap limit.  Hence, the current\n** size of heap limits can be determined by invoking\n** sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1).\n**\n** ^Setting the heap limits to zero disables the heap limiter mechanism.\n**\n** ^The soft heap limit may not be greater than the hard heap limit.\n** ^If the hard heap limit is enabled and if sqlite3_soft_heap_limit(N)\n** is invoked with a value of N that is greater than the hard heap limit,\n** the the soft heap limit is set to the value of the hard heap limit.\n** ^The soft heap limit is automatically enabled whenever the hard heap\n** limit is enabled. ^When sqlite3_hard_heap_limit64(N) is invoked and\n** the soft heap limit is outside the range of 1..N, then the soft heap\n** limit is set to N.  ^Invoking sqlite3_soft_heap_limit64(0) when the\n** hard heap limit is enabled makes the soft heap limit equal to the\n** hard heap limit.\n**\n** The memory allocation limits can also be adjusted using\n** [PRAGMA soft_heap_limit] and [PRAGMA hard_heap_limit].\n**\n** ^(The heap limits are not enforced in the current implementation\n** if one or more of following conditions are true:\n**\n** <ul>\n** <li> The limit value is set to zero.\n** <li> Memory accounting is disabled using a combination of the\n**      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and\n**      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.\n** <li> An alternative page cache implementation is specified using\n**      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).\n** <li> The page cache allocates from its own memory pool supplied\n**      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than\n**      from the heap.\n** </ul>)^\n**\n** The circumstances under which SQLite will enforce the heap limits may\n** changes in future releases of SQLite.\n*/\nSQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);\nSQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N);\n\n/*\n** CAPI3REF: Deprecated Soft Heap Limit Interface\n** DEPRECATED\n**\n** This is a deprecated version of the [sqlite3_soft_heap_limit64()]\n** interface.  This routine is provided for historical compatibility\n** only.  All new applications should use the\n** [sqlite3_soft_heap_limit64()] interface rather than this one.\n*/\nSQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);\n\n\n/*\n** CAPI3REF: Extract Metadata About A Column Of A Table\n** METHOD: sqlite3\n**\n** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns\n** information about column C of table T in database D\n** on [database connection] X.)^  ^The sqlite3_table_column_metadata()\n** interface returns SQLITE_OK and fills in the non-NULL pointers in\n** the final five arguments with appropriate values if the specified\n** column exists.  ^The sqlite3_table_column_metadata() interface returns\n** SQLITE_ERROR if the specified column does not exist.\n** ^If the column-name parameter to sqlite3_table_column_metadata() is a\n** NULL pointer, then this routine simply checks for the existence of the\n** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it\n** does not.  If the table name parameter T in a call to\n** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is\n** undefined behavior.\n**\n** ^The column is identified by the second, third and fourth parameters to\n** this function. ^(The second parameter is either the name of the database\n** (i.e. \"main\", \"temp\", or an attached database) containing the specified\n** table or NULL.)^ ^If it is NULL, then all attached databases are searched\n** for the table using the same algorithm used by the database engine to\n** resolve unqualified table references.\n**\n** ^The third and fourth parameters to this function are the table and column\n** name of the desired column, respectively.\n**\n** ^Metadata is returned by writing to the memory locations passed as the 5th\n** and subsequent parameters to this function. ^Any of these arguments may be\n** NULL, in which case the corresponding element of metadata is omitted.\n**\n** ^(<blockquote>\n** <table border=\"1\">\n** <tr><th> Parameter <th> Output<br>Type <th>  Description\n**\n** <tr><td> 5th <td> const char* <td> Data type\n** <tr><td> 6th <td> const char* <td> Name of default collation sequence\n** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint\n** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY\n** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]\n** </table>\n** </blockquote>)^\n**\n** ^The memory pointed to by the character pointers returned for the\n** declaration type and collation sequence is valid until the next\n** call to any SQLite API function.\n**\n** ^If the specified table is actually a view, an [error code] is returned.\n**\n** ^If the specified column is \"rowid\", \"oid\" or \"_rowid_\" and the table \n** is not a [WITHOUT ROWID] table and an\n** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output\n** parameters are set for the explicitly declared column. ^(If there is no\n** [INTEGER PRIMARY KEY] column, then the outputs\n** for the [rowid] are set as follows:\n**\n** <pre>\n**     data type: \"INTEGER\"\n**     collation sequence: \"BINARY\"\n**     not null: 0\n**     primary key: 1\n**     auto increment: 0\n** </pre>)^\n**\n** ^This function causes all database schemas to be read from disk and\n** parsed, if that has not already been done, and returns an error if\n** any errors are encountered while loading the schema.\n*/\nSQLITE_API int sqlite3_table_column_metadata(\n  sqlite3 *db,                /* Connection handle */\n  const char *zDbName,        /* Database name or NULL */\n  const char *zTableName,     /* Table name */\n  const char *zColumnName,    /* Column name */\n  char const **pzDataType,    /* OUTPUT: Declared data type */\n  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */\n  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */\n  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */\n  int *pAutoinc               /* OUTPUT: True if column is auto-increment */\n);\n\n/*\n** CAPI3REF: Load An Extension\n** METHOD: sqlite3\n**\n** ^This interface loads an SQLite extension library from the named file.\n**\n** ^The sqlite3_load_extension() interface attempts to load an\n** [SQLite extension] library contained in the file zFile.  If\n** the file cannot be loaded directly, attempts are made to load\n** with various operating-system specific extensions added.\n** So for example, if \"samplelib\" cannot be loaded, then names like\n** \"samplelib.so\" or \"samplelib.dylib\" or \"samplelib.dll\" might\n** be tried also.\n**\n** ^The entry point is zProc.\n** ^(zProc may be 0, in which case SQLite will try to come up with an\n** entry point name on its own.  It first tries \"sqlite3_extension_init\".\n** If that does not work, it constructs a name \"sqlite3_X_init\" where the\n** X is consists of the lower-case equivalent of all ASCII alphabetic\n** characters in the filename from the last \"/\" to the first following\n** \".\" and omitting any initial \"lib\".)^\n** ^The sqlite3_load_extension() interface returns\n** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.\n** ^If an error occurs and pzErrMsg is not 0, then the\n** [sqlite3_load_extension()] interface shall attempt to\n** fill *pzErrMsg with error message text stored in memory\n** obtained from [sqlite3_malloc()]. The calling function\n** should free this memory by calling [sqlite3_free()].\n**\n** ^Extension loading must be enabled using\n** [sqlite3_enable_load_extension()] or\n** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)\n** prior to calling this API,\n** otherwise an error will be returned.\n**\n** <b>Security warning:</b> It is recommended that the \n** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this\n** interface.  The use of the [sqlite3_enable_load_extension()] interface\n** should be avoided.  This will keep the SQL function [load_extension()]\n** disabled and prevent SQL injections from giving attackers\n** access to extension loading capabilities.\n**\n** See also the [load_extension() SQL function].\n*/\nSQLITE_API int sqlite3_load_extension(\n  sqlite3 *db,          /* Load the extension into this database connection */\n  const char *zFile,    /* Name of the shared library containing extension */\n  const char *zProc,    /* Entry point.  Derived from zFile if 0 */\n  char **pzErrMsg       /* Put error message here if not 0 */\n);\n\n/*\n** CAPI3REF: Enable Or Disable Extension Loading\n** METHOD: sqlite3\n**\n** ^So as not to open security holes in older applications that are\n** unprepared to deal with [extension loading], and as a means of disabling\n** [extension loading] while evaluating user-entered SQL, the following API\n** is provided to turn the [sqlite3_load_extension()] mechanism on and off.\n**\n** ^Extension loading is off by default.\n** ^Call the sqlite3_enable_load_extension() routine with onoff==1\n** to turn extension loading on and call it with onoff==0 to turn\n** it back off again.\n**\n** ^This interface enables or disables both the C-API\n** [sqlite3_load_extension()] and the SQL function [load_extension()].\n** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)\n** to enable or disable only the C-API.)^\n**\n** <b>Security warning:</b> It is recommended that extension loading\n** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method\n** rather than this interface, so the [load_extension()] SQL function\n** remains disabled. This will prevent SQL injections from giving attackers\n** access to extension loading capabilities.\n*/\nSQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);\n\n/*\n** CAPI3REF: Automatically Load Statically Linked Extensions\n**\n** ^This interface causes the xEntryPoint() function to be invoked for\n** each new [database connection] that is created.  The idea here is that\n** xEntryPoint() is the entry point for a statically linked [SQLite extension]\n** that is to be automatically loaded into all new database connections.\n**\n** ^(Even though the function prototype shows that xEntryPoint() takes\n** no arguments and returns void, SQLite invokes xEntryPoint() with three\n** arguments and expects an integer result as if the signature of the\n** entry point where as follows:\n**\n** <blockquote><pre>\n** &nbsp;  int xEntryPoint(\n** &nbsp;    sqlite3 *db,\n** &nbsp;    const char **pzErrMsg,\n** &nbsp;    const struct sqlite3_api_routines *pThunk\n** &nbsp;  );\n** </pre></blockquote>)^\n**\n** If the xEntryPoint routine encounters an error, it should make *pzErrMsg\n** point to an appropriate error message (obtained from [sqlite3_mprintf()])\n** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg\n** is NULL before calling the xEntryPoint().  ^SQLite will invoke\n** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any\n** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],\n** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.\n**\n** ^Calling sqlite3_auto_extension(X) with an entry point X that is already\n** on the list of automatic extensions is a harmless no-op. ^No entry point\n** will be called more than once for each database connection that is opened.\n**\n** See also: [sqlite3_reset_auto_extension()]\n** and [sqlite3_cancel_auto_extension()]\n*/\nSQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));\n\n/*\n** CAPI3REF: Cancel Automatic Extension Loading\n**\n** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the\n** initialization routine X that was registered using a prior call to\n** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]\n** routine returns 1 if initialization routine X was successfully \n** unregistered and it returns 0 if X was not on the list of initialization\n** routines.\n*/\nSQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));\n\n/*\n** CAPI3REF: Reset Automatic Extension Loading\n**\n** ^This interface disables all automatic extensions previously\n** registered using [sqlite3_auto_extension()].\n*/\nSQLITE_API void sqlite3_reset_auto_extension(void);\n\n/*\n** The interface to the virtual-table mechanism is currently considered\n** to be experimental.  The interface might change in incompatible ways.\n** If this is a problem for you, do not use the interface at this time.\n**\n** When the virtual-table mechanism stabilizes, we will declare the\n** interface fixed, support it indefinitely, and remove this comment.\n*/\n\n/*\n** Structures used by the virtual table interface\n*/\ntypedef struct sqlite3_vtab sqlite3_vtab;\ntypedef struct sqlite3_index_info sqlite3_index_info;\ntypedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;\ntypedef struct sqlite3_module sqlite3_module;\n\n/*\n** CAPI3REF: Virtual Table Object\n** KEYWORDS: sqlite3_module {virtual table module}\n**\n** This structure, sometimes called a \"virtual table module\", \n** defines the implementation of a [virtual table].  \n** This structure consists mostly of methods for the module.\n**\n** ^A virtual table module is created by filling in a persistent\n** instance of this structure and passing a pointer to that instance\n** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].\n** ^The registration remains valid until it is replaced by a different\n** module or until the [database connection] closes.  The content\n** of this structure must not change while it is registered with\n** any database connection.\n*/\nstruct sqlite3_module {\n  int iVersion;\n  int (*xCreate)(sqlite3*, void *pAux,\n               int argc, const char *const*argv,\n               sqlite3_vtab **ppVTab, char**);\n  int (*xConnect)(sqlite3*, void *pAux,\n               int argc, const char *const*argv,\n               sqlite3_vtab **ppVTab, char**);\n  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);\n  int (*xDisconnect)(sqlite3_vtab *pVTab);\n  int (*xDestroy)(sqlite3_vtab *pVTab);\n  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);\n  int (*xClose)(sqlite3_vtab_cursor*);\n  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,\n                int argc, sqlite3_value **argv);\n  int (*xNext)(sqlite3_vtab_cursor*);\n  int (*xEof)(sqlite3_vtab_cursor*);\n  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);\n  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);\n  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);\n  int (*xBegin)(sqlite3_vtab *pVTab);\n  int (*xSync)(sqlite3_vtab *pVTab);\n  int (*xCommit)(sqlite3_vtab *pVTab);\n  int (*xRollback)(sqlite3_vtab *pVTab);\n  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,\n                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),\n                       void **ppArg);\n  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);\n  /* The methods above are in version 1 of the sqlite_module object. Those \n  ** below are for version 2 and greater. */\n  int (*xSavepoint)(sqlite3_vtab *pVTab, int);\n  int (*xRelease)(sqlite3_vtab *pVTab, int);\n  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);\n  /* The methods above are in versions 1 and 2 of the sqlite_module object.\n  ** Those below are for version 3 and greater. */\n  int (*xShadowName)(const char*);\n};\n\n/*\n** CAPI3REF: Virtual Table Indexing Information\n** KEYWORDS: sqlite3_index_info\n**\n** The sqlite3_index_info structure and its substructures is used as part\n** of the [virtual table] interface to\n** pass information into and receive the reply from the [xBestIndex]\n** method of a [virtual table module].  The fields under **Inputs** are the\n** inputs to xBestIndex and are read-only.  xBestIndex inserts its\n** results into the **Outputs** fields.\n**\n** ^(The aConstraint[] array records WHERE clause constraints of the form:\n**\n** <blockquote>column OP expr</blockquote>\n**\n** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is\n** stored in aConstraint[].op using one of the\n** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^\n** ^(The index of the column is stored in\n** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the\n** expr on the right-hand side can be evaluated (and thus the constraint\n** is usable) and false if it cannot.)^\n**\n** ^The optimizer automatically inverts terms of the form \"expr OP column\"\n** and makes other simplifications to the WHERE clause in an attempt to\n** get as many WHERE clause terms into the form shown above as possible.\n** ^The aConstraint[] array only reports WHERE clause terms that are\n** relevant to the particular virtual table being queried.\n**\n** ^Information about the ORDER BY clause is stored in aOrderBy[].\n** ^Each term of aOrderBy records a column of the ORDER BY clause.\n**\n** The colUsed field indicates which columns of the virtual table may be\n** required by the current scan. Virtual table columns are numbered from\n** zero in the order in which they appear within the CREATE TABLE statement\n** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),\n** the corresponding bit is set within the colUsed mask if the column may be\n** required by SQLite. If the table has at least 64 columns and any column\n** to the right of the first 63 is required, then bit 63 of colUsed is also\n** set. In other words, column iCol may be required if the expression\n** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to \n** non-zero.\n**\n** The [xBestIndex] method must fill aConstraintUsage[] with information\n** about what parameters to pass to xFilter.  ^If argvIndex>0 then\n** the right-hand side of the corresponding aConstraint[] is evaluated\n** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit\n** is true, then the constraint is assumed to be fully handled by the\n** virtual table and might not be checked again by the byte code.)^ ^(The\n** aConstraintUsage[].omit flag is an optimization hint. When the omit flag\n** is left in its default setting of false, the constraint will always be\n** checked separately in byte code.  If the omit flag is change to true, then\n** the constraint may or may not be checked in byte code.  In other words,\n** when the omit flag is true there is no guarantee that the constraint will\n** not be checked again using byte code.)^\n**\n** ^The idxNum and idxPtr values are recorded and passed into the\n** [xFilter] method.\n** ^[sqlite3_free()] is used to free idxPtr if and only if\n** needToFreeIdxPtr is true.\n**\n** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in\n** the correct order to satisfy the ORDER BY clause so that no separate\n** sorting step is required.\n**\n** ^The estimatedCost value is an estimate of the cost of a particular\n** strategy. A cost of N indicates that the cost of the strategy is similar\n** to a linear scan of an SQLite table with N rows. A cost of log(N) \n** indicates that the expense of the operation is similar to that of a\n** binary search on a unique indexed field of an SQLite table with N rows.\n**\n** ^The estimatedRows value is an estimate of the number of rows that\n** will be returned by the strategy.\n**\n** The xBestIndex method may optionally populate the idxFlags field with a \n** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -\n** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite\n** assumes that the strategy may visit at most one row. \n**\n** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then\n** SQLite also assumes that if a call to the xUpdate() method is made as\n** part of the same statement to delete or update a virtual table row and the\n** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback\n** any database changes. In other words, if the xUpdate() returns\n** SQLITE_CONSTRAINT, the database contents must be exactly as they were\n** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not\n** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by\n** the xUpdate method are automatically rolled back by SQLite.\n**\n** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info\n** structure for SQLite [version 3.8.2] ([dateof:3.8.2]). \n** If a virtual table extension is\n** used with an SQLite version earlier than 3.8.2, the results of attempting \n** to read or write the estimatedRows field are undefined (but are likely \n** to include crashing the application). The estimatedRows field should\n** therefore only be used if [sqlite3_libversion_number()] returns a\n** value greater than or equal to 3008002. Similarly, the idxFlags field\n** was added for [version 3.9.0] ([dateof:3.9.0]). \n** It may therefore only be used if\n** sqlite3_libversion_number() returns a value greater than or equal to\n** 3009000.\n*/\nstruct sqlite3_index_info {\n  /* Inputs */\n  int nConstraint;           /* Number of entries in aConstraint */\n  struct sqlite3_index_constraint {\n     int iColumn;              /* Column constrained.  -1 for ROWID */\n     unsigned char op;         /* Constraint operator */\n     unsigned char usable;     /* True if this constraint is usable */\n     int iTermOffset;          /* Used internally - xBestIndex should ignore */\n  } *aConstraint;            /* Table of WHERE clause constraints */\n  int nOrderBy;              /* Number of terms in the ORDER BY clause */\n  struct sqlite3_index_orderby {\n     int iColumn;              /* Column number */\n     unsigned char desc;       /* True for DESC.  False for ASC. */\n  } *aOrderBy;               /* The ORDER BY clause */\n  /* Outputs */\n  struct sqlite3_index_constraint_usage {\n    int argvIndex;           /* if >0, constraint is part of argv to xFilter */\n    unsigned char omit;      /* Do not code a test for this constraint */\n  } *aConstraintUsage;\n  int idxNum;                /* Number used to identify the index */\n  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */\n  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */\n  int orderByConsumed;       /* True if output is already ordered */\n  double estimatedCost;           /* Estimated cost of using this index */\n  /* Fields below are only available in SQLite 3.8.2 and later */\n  sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */\n  /* Fields below are only available in SQLite 3.9.0 and later */\n  int idxFlags;              /* Mask of SQLITE_INDEX_SCAN_* flags */\n  /* Fields below are only available in SQLite 3.10.0 and later */\n  sqlite3_uint64 colUsed;    /* Input: Mask of columns used by statement */\n};\n\n/*\n** CAPI3REF: Virtual Table Scan Flags\n**\n** Virtual table implementations are allowed to set the \n** [sqlite3_index_info].idxFlags field to some combination of\n** these bits.\n*/\n#define SQLITE_INDEX_SCAN_UNIQUE      1     /* Scan visits at most 1 row */\n\n/*\n** CAPI3REF: Virtual Table Constraint Operator Codes\n**\n** These macros define the allowed values for the\n** [sqlite3_index_info].aConstraint[].op field.  Each value represents\n** an operator that is part of a constraint term in the wHERE clause of\n** a query that uses a [virtual table].\n*/\n#define SQLITE_INDEX_CONSTRAINT_EQ         2\n#define SQLITE_INDEX_CONSTRAINT_GT         4\n#define SQLITE_INDEX_CONSTRAINT_LE         8\n#define SQLITE_INDEX_CONSTRAINT_LT        16\n#define SQLITE_INDEX_CONSTRAINT_GE        32\n#define SQLITE_INDEX_CONSTRAINT_MATCH     64\n#define SQLITE_INDEX_CONSTRAINT_LIKE      65\n#define SQLITE_INDEX_CONSTRAINT_GLOB      66\n#define SQLITE_INDEX_CONSTRAINT_REGEXP    67\n#define SQLITE_INDEX_CONSTRAINT_NE        68\n#define SQLITE_INDEX_CONSTRAINT_ISNOT     69\n#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70\n#define SQLITE_INDEX_CONSTRAINT_ISNULL    71\n#define SQLITE_INDEX_CONSTRAINT_IS        72\n#define SQLITE_INDEX_CONSTRAINT_FUNCTION 150\n\n/*\n** CAPI3REF: Register A Virtual Table Implementation\n** METHOD: sqlite3\n**\n** ^These routines are used to register a new [virtual table module] name.\n** ^Module names must be registered before\n** creating a new [virtual table] using the module and before using a\n** preexisting [virtual table] for the module.\n**\n** ^The module name is registered on the [database connection] specified\n** by the first parameter.  ^The name of the module is given by the \n** second parameter.  ^The third parameter is a pointer to\n** the implementation of the [virtual table module].   ^The fourth\n** parameter is an arbitrary client data pointer that is passed through\n** into the [xCreate] and [xConnect] methods of the virtual table module\n** when a new virtual table is be being created or reinitialized.\n**\n** ^The sqlite3_create_module_v2() interface has a fifth parameter which\n** is a pointer to a destructor for the pClientData.  ^SQLite will\n** invoke the destructor function (if it is not NULL) when SQLite\n** no longer needs the pClientData pointer.  ^The destructor will also\n** be invoked if the call to sqlite3_create_module_v2() fails.\n** ^The sqlite3_create_module()\n** interface is equivalent to sqlite3_create_module_v2() with a NULL\n** destructor.\n**\n** ^If the third parameter (the pointer to the sqlite3_module object) is\n** NULL then no new module is create and any existing modules with the\n** same name are dropped.\n**\n** See also: [sqlite3_drop_modules()]\n*/\nSQLITE_API int sqlite3_create_module(\n  sqlite3 *db,               /* SQLite connection to register module with */\n  const char *zName,         /* Name of the module */\n  const sqlite3_module *p,   /* Methods for the module */\n  void *pClientData          /* Client data for xCreate/xConnect */\n);\nSQLITE_API int sqlite3_create_module_v2(\n  sqlite3 *db,               /* SQLite connection to register module with */\n  const char *zName,         /* Name of the module */\n  const sqlite3_module *p,   /* Methods for the module */\n  void *pClientData,         /* Client data for xCreate/xConnect */\n  void(*xDestroy)(void*)     /* Module destructor function */\n);\n\n/*\n** CAPI3REF: Remove Unnecessary Virtual Table Implementations\n** METHOD: sqlite3\n**\n** ^The sqlite3_drop_modules(D,L) interface removes all virtual\n** table modules from database connection D except those named on list L.\n** The L parameter must be either NULL or a pointer to an array of pointers\n** to strings where the array is terminated by a single NULL pointer.\n** ^If the L parameter is NULL, then all virtual table modules are removed.\n**\n** See also: [sqlite3_create_module()]\n*/\nSQLITE_API int sqlite3_drop_modules(\n  sqlite3 *db,                /* Remove modules from this connection */\n  const char **azKeep         /* Except, do not remove the ones named here */\n);\n\n/*\n** CAPI3REF: Virtual Table Instance Object\n** KEYWORDS: sqlite3_vtab\n**\n** Every [virtual table module] implementation uses a subclass\n** of this object to describe a particular instance\n** of the [virtual table].  Each subclass will\n** be tailored to the specific needs of the module implementation.\n** The purpose of this superclass is to define certain fields that are\n** common to all module implementations.\n**\n** ^Virtual tables methods can set an error message by assigning a\n** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should\n** take care that any prior string is freed by a call to [sqlite3_free()]\n** prior to assigning a new string to zErrMsg.  ^After the error message\n** is delivered up to the client application, the string will be automatically\n** freed by sqlite3_free() and the zErrMsg field will be zeroed.\n*/\nstruct sqlite3_vtab {\n  const sqlite3_module *pModule;  /* The module for this virtual table */\n  int nRef;                       /* Number of open cursors */\n  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */\n  /* Virtual table implementations will typically add additional fields */\n};\n\n/*\n** CAPI3REF: Virtual Table Cursor Object\n** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}\n**\n** Every [virtual table module] implementation uses a subclass of the\n** following structure to describe cursors that point into the\n** [virtual table] and are used\n** to loop through the virtual table.  Cursors are created using the\n** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed\n** by the [sqlite3_module.xClose | xClose] method.  Cursors are used\n** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods\n** of the module.  Each module implementation will define\n** the content of a cursor structure to suit its own needs.\n**\n** This superclass exists in order to define fields of the cursor that\n** are common to all implementations.\n*/\nstruct sqlite3_vtab_cursor {\n  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */\n  /* Virtual table implementations will typically add additional fields */\n};\n\n/*\n** CAPI3REF: Declare The Schema Of A Virtual Table\n**\n** ^The [xCreate] and [xConnect] methods of a\n** [virtual table module] call this interface\n** to declare the format (the names and datatypes of the columns) of\n** the virtual tables they implement.\n*/\nSQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);\n\n/*\n** CAPI3REF: Overload A Function For A Virtual Table\n** METHOD: sqlite3\n**\n** ^(Virtual tables can provide alternative implementations of functions\n** using the [xFindFunction] method of the [virtual table module].  \n** But global versions of those functions\n** must exist in order to be overloaded.)^\n**\n** ^(This API makes sure a global version of a function with a particular\n** name and number of parameters exists.  If no such function exists\n** before this API is called, a new function is created.)^  ^The implementation\n** of the new function always causes an exception to be thrown.  So\n** the new function is not good for anything by itself.  Its only\n** purpose is to be a placeholder function that can be overloaded\n** by a [virtual table].\n*/\nSQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);\n\n/*\n** The interface to the virtual-table mechanism defined above (back up\n** to a comment remarkably similar to this one) is currently considered\n** to be experimental.  The interface might change in incompatible ways.\n** If this is a problem for you, do not use the interface at this time.\n**\n** When the virtual-table mechanism stabilizes, we will declare the\n** interface fixed, support it indefinitely, and remove this comment.\n*/\n\n/*\n** CAPI3REF: A Handle To An Open BLOB\n** KEYWORDS: {BLOB handle} {BLOB handles}\n**\n** An instance of this object represents an open BLOB on which\n** [sqlite3_blob_open | incremental BLOB I/O] can be performed.\n** ^Objects of this type are created by [sqlite3_blob_open()]\n** and destroyed by [sqlite3_blob_close()].\n** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces\n** can be used to read or write small subsections of the BLOB.\n** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.\n*/\ntypedef struct sqlite3_blob sqlite3_blob;\n\n/*\n** CAPI3REF: Open A BLOB For Incremental I/O\n** METHOD: sqlite3\n** CONSTRUCTOR: sqlite3_blob\n**\n** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located\n** in row iRow, column zColumn, table zTable in database zDb;\n** in other words, the same BLOB that would be selected by:\n**\n** <pre>\n**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;\n** </pre>)^\n**\n** ^(Parameter zDb is not the filename that contains the database, but \n** rather the symbolic name of the database. For attached databases, this is\n** the name that appears after the AS keyword in the [ATTACH] statement.\n** For the main database file, the database name is \"main\". For TEMP\n** tables, the database name is \"temp\".)^\n**\n** ^If the flags parameter is non-zero, then the BLOB is opened for read\n** and write access. ^If the flags parameter is zero, the BLOB is opened for\n** read-only access.\n**\n** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored\n** in *ppBlob. Otherwise an [error code] is returned and, unless the error\n** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided\n** the API is not misused, it is always safe to call [sqlite3_blob_close()] \n** on *ppBlob after this function it returns.\n**\n** This function fails with SQLITE_ERROR if any of the following are true:\n** <ul>\n**   <li> ^(Database zDb does not exist)^, \n**   <li> ^(Table zTable does not exist within database zDb)^, \n**   <li> ^(Table zTable is a WITHOUT ROWID table)^, \n**   <li> ^(Column zColumn does not exist)^,\n**   <li> ^(Row iRow is not present in the table)^,\n**   <li> ^(The specified column of row iRow contains a value that is not\n**         a TEXT or BLOB value)^,\n**   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE \n**         constraint and the blob is being opened for read/write access)^,\n**   <li> ^([foreign key constraints | Foreign key constraints] are enabled, \n**         column zColumn is part of a [child key] definition and the blob is\n**         being opened for read/write access)^.\n** </ul>\n**\n** ^Unless it returns SQLITE_MISUSE, this function sets the \n** [database connection] error code and message accessible via \n** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. \n**\n** A BLOB referenced by sqlite3_blob_open() may be read using the\n** [sqlite3_blob_read()] interface and modified by using\n** [sqlite3_blob_write()].  The [BLOB handle] can be moved to a\n** different row of the same table using the [sqlite3_blob_reopen()]\n** interface.  However, the column, table, or database of a [BLOB handle]\n** cannot be changed after the [BLOB handle] is opened.\n**\n** ^(If the row that a BLOB handle points to is modified by an\n** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects\n** then the BLOB handle is marked as \"expired\".\n** This is true if any column of the row is changed, even a column\n** other than the one the BLOB handle is open on.)^\n** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for\n** an expired BLOB handle fail with a return code of [SQLITE_ABORT].\n** ^(Changes written into a BLOB prior to the BLOB expiring are not\n** rolled back by the expiration of the BLOB.  Such changes will eventually\n** commit if the transaction continues to completion.)^\n**\n** ^Use the [sqlite3_blob_bytes()] interface to determine the size of\n** the opened blob.  ^The size of a blob may not be changed by this\n** interface.  Use the [UPDATE] SQL command to change the size of a\n** blob.\n**\n** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces\n** and the built-in [zeroblob] SQL function may be used to create a \n** zero-filled blob to read or write using the incremental-blob interface.\n**\n** To avoid a resource leak, every open [BLOB handle] should eventually\n** be released by a call to [sqlite3_blob_close()].\n**\n** See also: [sqlite3_blob_close()],\n** [sqlite3_blob_reopen()], [sqlite3_blob_read()],\n** [sqlite3_blob_bytes()], [sqlite3_blob_write()].\n*/\nSQLITE_API int sqlite3_blob_open(\n  sqlite3*,\n  const char *zDb,\n  const char *zTable,\n  const char *zColumn,\n  sqlite3_int64 iRow,\n  int flags,\n  sqlite3_blob **ppBlob\n);\n\n/*\n** CAPI3REF: Move a BLOB Handle to a New Row\n** METHOD: sqlite3_blob\n**\n** ^This function is used to move an existing [BLOB handle] so that it points\n** to a different row of the same database table. ^The new row is identified\n** by the rowid value passed as the second argument. Only the row can be\n** changed. ^The database, table and column on which the blob handle is open\n** remain the same. Moving an existing [BLOB handle] to a new row is\n** faster than closing the existing handle and opening a new one.\n**\n** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -\n** it must exist and there must be either a blob or text value stored in\n** the nominated column.)^ ^If the new row is not present in the table, or if\n** it does not contain a blob or text value, or if another error occurs, an\n** SQLite error code is returned and the blob handle is considered aborted.\n** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or\n** [sqlite3_blob_reopen()] on an aborted blob handle immediately return\n** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle\n** always returns zero.\n**\n** ^This function sets the database handle error code and message.\n*/\nSQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);\n\n/*\n** CAPI3REF: Close A BLOB Handle\n** DESTRUCTOR: sqlite3_blob\n**\n** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed\n** unconditionally.  Even if this routine returns an error code, the \n** handle is still closed.)^\n**\n** ^If the blob handle being closed was opened for read-write access, and if\n** the database is in auto-commit mode and there are no other open read-write\n** blob handles or active write statements, the current transaction is\n** committed. ^If an error occurs while committing the transaction, an error\n** code is returned and the transaction rolled back.\n**\n** Calling this function with an argument that is not a NULL pointer or an\n** open blob handle results in undefined behaviour. ^Calling this routine \n** with a null pointer (such as would be returned by a failed call to \n** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function\n** is passed a valid open blob handle, the values returned by the \n** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.\n*/\nSQLITE_API int sqlite3_blob_close(sqlite3_blob *);\n\n/*\n** CAPI3REF: Return The Size Of An Open BLOB\n** METHOD: sqlite3_blob\n**\n** ^Returns the size in bytes of the BLOB accessible via the \n** successfully opened [BLOB handle] in its only argument.  ^The\n** incremental blob I/O routines can only read or overwriting existing\n** blob content; they cannot change the size of a blob.\n**\n** This routine only works on a [BLOB handle] which has been created\n** by a prior successful call to [sqlite3_blob_open()] and which has not\n** been closed by [sqlite3_blob_close()].  Passing any other pointer in\n** to this routine results in undefined and probably undesirable behavior.\n*/\nSQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);\n\n/*\n** CAPI3REF: Read Data From A BLOB Incrementally\n** METHOD: sqlite3_blob\n**\n** ^(This function is used to read data from an open [BLOB handle] into a\n** caller-supplied buffer. N bytes of data are copied into buffer Z\n** from the open BLOB, starting at offset iOffset.)^\n**\n** ^If offset iOffset is less than N bytes from the end of the BLOB,\n** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is\n** less than zero, [SQLITE_ERROR] is returned and no data is read.\n** ^The size of the blob (and hence the maximum value of N+iOffset)\n** can be determined using the [sqlite3_blob_bytes()] interface.\n**\n** ^An attempt to read from an expired [BLOB handle] fails with an\n** error code of [SQLITE_ABORT].\n**\n** ^(On success, sqlite3_blob_read() returns SQLITE_OK.\n** Otherwise, an [error code] or an [extended error code] is returned.)^\n**\n** This routine only works on a [BLOB handle] which has been created\n** by a prior successful call to [sqlite3_blob_open()] and which has not\n** been closed by [sqlite3_blob_close()].  Passing any other pointer in\n** to this routine results in undefined and probably undesirable behavior.\n**\n** See also: [sqlite3_blob_write()].\n*/\nSQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);\n\n/*\n** CAPI3REF: Write Data Into A BLOB Incrementally\n** METHOD: sqlite3_blob\n**\n** ^(This function is used to write data into an open [BLOB handle] from a\n** caller-supplied buffer. N bytes of data are copied from the buffer Z\n** into the open BLOB, starting at offset iOffset.)^\n**\n** ^(On success, sqlite3_blob_write() returns SQLITE_OK.\n** Otherwise, an  [error code] or an [extended error code] is returned.)^\n** ^Unless SQLITE_MISUSE is returned, this function sets the \n** [database connection] error code and message accessible via \n** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. \n**\n** ^If the [BLOB handle] passed as the first argument was not opened for\n** writing (the flags parameter to [sqlite3_blob_open()] was zero),\n** this function returns [SQLITE_READONLY].\n**\n** This function may only modify the contents of the BLOB; it is\n** not possible to increase the size of a BLOB using this API.\n** ^If offset iOffset is less than N bytes from the end of the BLOB,\n** [SQLITE_ERROR] is returned and no data is written. The size of the \n** BLOB (and hence the maximum value of N+iOffset) can be determined \n** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less \n** than zero [SQLITE_ERROR] is returned and no data is written.\n**\n** ^An attempt to write to an expired [BLOB handle] fails with an\n** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred\n** before the [BLOB handle] expired are not rolled back by the\n** expiration of the handle, though of course those changes might\n** have been overwritten by the statement that expired the BLOB handle\n** or by other independent statements.\n**\n** This routine only works on a [BLOB handle] which has been created\n** by a prior successful call to [sqlite3_blob_open()] and which has not\n** been closed by [sqlite3_blob_close()].  Passing any other pointer in\n** to this routine results in undefined and probably undesirable behavior.\n**\n** See also: [sqlite3_blob_read()].\n*/\nSQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);\n\n/*\n** CAPI3REF: Virtual File System Objects\n**\n** A virtual filesystem (VFS) is an [sqlite3_vfs] object\n** that SQLite uses to interact\n** with the underlying operating system.  Most SQLite builds come with a\n** single default VFS that is appropriate for the host computer.\n** New VFSes can be registered and existing VFSes can be unregistered.\n** The following interfaces are provided.\n**\n** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.\n** ^Names are case sensitive.\n** ^Names are zero-terminated UTF-8 strings.\n** ^If there is no match, a NULL pointer is returned.\n** ^If zVfsName is NULL then the default VFS is returned.\n**\n** ^New VFSes are registered with sqlite3_vfs_register().\n** ^Each new VFS becomes the default VFS if the makeDflt flag is set.\n** ^The same VFS can be registered multiple times without injury.\n** ^To make an existing VFS into the default VFS, register it again\n** with the makeDflt flag set.  If two different VFSes with the\n** same name are registered, the behavior is undefined.  If a\n** VFS is registered with a name that is NULL or an empty string,\n** then the behavior is undefined.\n**\n** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.\n** ^(If the default VFS is unregistered, another VFS is chosen as\n** the default.  The choice for the new VFS is arbitrary.)^\n*/\nSQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);\nSQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);\nSQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);\n\n/*\n** CAPI3REF: Mutexes\n**\n** The SQLite core uses these routines for thread\n** synchronization. Though they are intended for internal\n** use by SQLite, code that links against SQLite is\n** permitted to use any of these routines.\n**\n** The SQLite source code contains multiple implementations\n** of these mutex routines.  An appropriate implementation\n** is selected automatically at compile-time.  The following\n** implementations are available in the SQLite core:\n**\n** <ul>\n** <li>   SQLITE_MUTEX_PTHREADS\n** <li>   SQLITE_MUTEX_W32\n** <li>   SQLITE_MUTEX_NOOP\n** </ul>\n**\n** The SQLITE_MUTEX_NOOP implementation is a set of routines\n** that does no real locking and is appropriate for use in\n** a single-threaded application.  The SQLITE_MUTEX_PTHREADS and\n** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix\n** and Windows.\n**\n** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor\n** macro defined (with \"-DSQLITE_MUTEX_APPDEF=1\"), then no mutex\n** implementation is included with the library. In this case the\n** application must supply a custom mutex implementation using the\n** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function\n** before calling sqlite3_initialize() or any other public sqlite3_\n** function that calls sqlite3_initialize().\n**\n** ^The sqlite3_mutex_alloc() routine allocates a new\n** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()\n** routine returns NULL if it is unable to allocate the requested\n** mutex.  The argument to sqlite3_mutex_alloc() must one of these\n** integer constants:\n**\n** <ul>\n** <li>  SQLITE_MUTEX_FAST\n** <li>  SQLITE_MUTEX_RECURSIVE\n** <li>  SQLITE_MUTEX_STATIC_MASTER\n** <li>  SQLITE_MUTEX_STATIC_MEM\n** <li>  SQLITE_MUTEX_STATIC_OPEN\n** <li>  SQLITE_MUTEX_STATIC_PRNG\n** <li>  SQLITE_MUTEX_STATIC_LRU\n** <li>  SQLITE_MUTEX_STATIC_PMEM\n** <li>  SQLITE_MUTEX_STATIC_APP1\n** <li>  SQLITE_MUTEX_STATIC_APP2\n** <li>  SQLITE_MUTEX_STATIC_APP3\n** <li>  SQLITE_MUTEX_STATIC_VFS1\n** <li>  SQLITE_MUTEX_STATIC_VFS2\n** <li>  SQLITE_MUTEX_STATIC_VFS3\n** </ul>\n**\n** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)\n** cause sqlite3_mutex_alloc() to create\n** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE\n** is used but not necessarily so when SQLITE_MUTEX_FAST is used.\n** The mutex implementation does not need to make a distinction\n** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does\n** not want to.  SQLite will only request a recursive mutex in\n** cases where it really needs one.  If a faster non-recursive mutex\n** implementation is available on the host platform, the mutex subsystem\n** might return such a mutex in response to SQLITE_MUTEX_FAST.\n**\n** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other\n** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return\n** a pointer to a static preexisting mutex.  ^Nine static mutexes are\n** used by the current version of SQLite.  Future versions of SQLite\n** may add additional static mutexes.  Static mutexes are for internal\n** use by SQLite only.  Applications that use SQLite mutexes should\n** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or\n** SQLITE_MUTEX_RECURSIVE.\n**\n** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST\n** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()\n** returns a different mutex on every call.  ^For the static\n** mutex types, the same mutex is returned on every call that has\n** the same type number.\n**\n** ^The sqlite3_mutex_free() routine deallocates a previously\n** allocated dynamic mutex.  Attempting to deallocate a static\n** mutex results in undefined behavior.\n**\n** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt\n** to enter a mutex.  ^If another thread is already within the mutex,\n** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return\n** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]\n** upon successful entry.  ^(Mutexes created using\n** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.\n** In such cases, the\n** mutex must be exited an equal number of times before another thread\n** can enter.)^  If the same thread tries to enter any mutex other\n** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.\n**\n** ^(Some systems (for example, Windows 95) do not support the operation\n** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()\n** will always return SQLITE_BUSY. The SQLite core only ever uses\n** sqlite3_mutex_try() as an optimization so this is acceptable \n** behavior.)^\n**\n** ^The sqlite3_mutex_leave() routine exits a mutex that was\n** previously entered by the same thread.   The behavior\n** is undefined if the mutex is not currently entered by the\n** calling thread or is not currently allocated.\n**\n** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or\n** sqlite3_mutex_leave() is a NULL pointer, then all three routines\n** behave as no-ops.\n**\n** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].\n*/\nSQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);\nSQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);\nSQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);\nSQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);\nSQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);\n\n/*\n** CAPI3REF: Mutex Methods Object\n**\n** An instance of this structure defines the low-level routines\n** used to allocate and use mutexes.\n**\n** Usually, the default mutex implementations provided by SQLite are\n** sufficient, however the application has the option of substituting a custom\n** implementation for specialized deployments or systems for which SQLite\n** does not provide a suitable implementation. In this case, the application\n** creates and populates an instance of this structure to pass\n** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.\n** Additionally, an instance of this structure can be used as an\n** output variable when querying the system for the current mutex\n** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.\n**\n** ^The xMutexInit method defined by this structure is invoked as\n** part of system initialization by the sqlite3_initialize() function.\n** ^The xMutexInit routine is called by SQLite exactly once for each\n** effective call to [sqlite3_initialize()].\n**\n** ^The xMutexEnd method defined by this structure is invoked as\n** part of system shutdown by the sqlite3_shutdown() function. The\n** implementation of this method is expected to release all outstanding\n** resources obtained by the mutex methods implementation, especially\n** those obtained by the xMutexInit method.  ^The xMutexEnd()\n** interface is invoked exactly once for each call to [sqlite3_shutdown()].\n**\n** ^(The remaining seven methods defined by this structure (xMutexAlloc,\n** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and\n** xMutexNotheld) implement the following interfaces (respectively):\n**\n** <ul>\n**   <li>  [sqlite3_mutex_alloc()] </li>\n**   <li>  [sqlite3_mutex_free()] </li>\n**   <li>  [sqlite3_mutex_enter()] </li>\n**   <li>  [sqlite3_mutex_try()] </li>\n**   <li>  [sqlite3_mutex_leave()] </li>\n**   <li>  [sqlite3_mutex_held()] </li>\n**   <li>  [sqlite3_mutex_notheld()] </li>\n** </ul>)^\n**\n** The only difference is that the public sqlite3_XXX functions enumerated\n** above silently ignore any invocations that pass a NULL pointer instead\n** of a valid mutex handle. The implementations of the methods defined\n** by this structure are not required to handle this case. The results\n** of passing a NULL pointer instead of a valid mutex handle are undefined\n** (i.e. it is acceptable to provide an implementation that segfaults if\n** it is passed a NULL pointer).\n**\n** The xMutexInit() method must be threadsafe.  It must be harmless to\n** invoke xMutexInit() multiple times within the same process and without\n** intervening calls to xMutexEnd().  Second and subsequent calls to\n** xMutexInit() must be no-ops.\n**\n** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]\n** and its associates).  Similarly, xMutexAlloc() must not use SQLite memory\n** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite\n** memory allocation for a fast or recursive mutex.\n**\n** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is\n** called, but only if the prior call to xMutexInit returned SQLITE_OK.\n** If xMutexInit fails in any way, it is expected to clean up after itself\n** prior to returning.\n*/\ntypedef struct sqlite3_mutex_methods sqlite3_mutex_methods;\nstruct sqlite3_mutex_methods {\n  int (*xMutexInit)(void);\n  int (*xMutexEnd)(void);\n  sqlite3_mutex *(*xMutexAlloc)(int);\n  void (*xMutexFree)(sqlite3_mutex *);\n  void (*xMutexEnter)(sqlite3_mutex *);\n  int (*xMutexTry)(sqlite3_mutex *);\n  void (*xMutexLeave)(sqlite3_mutex *);\n  int (*xMutexHeld)(sqlite3_mutex *);\n  int (*xMutexNotheld)(sqlite3_mutex *);\n};\n\n/*\n** CAPI3REF: Mutex Verification Routines\n**\n** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines\n** are intended for use inside assert() statements.  The SQLite core\n** never uses these routines except inside an assert() and applications\n** are advised to follow the lead of the core.  The SQLite core only\n** provides implementations for these routines when it is compiled\n** with the SQLITE_DEBUG flag.  External mutex implementations\n** are only required to provide these routines if SQLITE_DEBUG is\n** defined and if NDEBUG is not defined.\n**\n** These routines should return true if the mutex in their argument\n** is held or not held, respectively, by the calling thread.\n**\n** The implementation is not required to provide versions of these\n** routines that actually work. If the implementation does not provide working\n** versions of these routines, it should at least provide stubs that always\n** return true so that one does not get spurious assertion failures.\n**\n** If the argument to sqlite3_mutex_held() is a NULL pointer then\n** the routine should return 1.   This seems counter-intuitive since\n** clearly the mutex cannot be held if it does not exist.  But\n** the reason the mutex does not exist is because the build is not\n** using mutexes.  And we do not want the assert() containing the\n** call to sqlite3_mutex_held() to fail, so a non-zero return is\n** the appropriate thing to do.  The sqlite3_mutex_notheld()\n** interface should also return 1 when given a NULL pointer.\n*/\n#ifndef NDEBUG\nSQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);\nSQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);\n#endif\n\n/*\n** CAPI3REF: Mutex Types\n**\n** The [sqlite3_mutex_alloc()] interface takes a single argument\n** which is one of these integer constants.\n**\n** The set of static mutexes may change from one SQLite release to the\n** next.  Applications that override the built-in mutex logic must be\n** prepared to accommodate additional static mutexes.\n*/\n#define SQLITE_MUTEX_FAST             0\n#define SQLITE_MUTEX_RECURSIVE        1\n#define SQLITE_MUTEX_STATIC_MASTER    2\n#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */\n#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */\n#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */\n#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_randomness() */\n#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */\n#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */\n#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */\n#define SQLITE_MUTEX_STATIC_APP1      8  /* For use by application */\n#define SQLITE_MUTEX_STATIC_APP2      9  /* For use by application */\n#define SQLITE_MUTEX_STATIC_APP3     10  /* For use by application */\n#define SQLITE_MUTEX_STATIC_VFS1     11  /* For use by built-in VFS */\n#define SQLITE_MUTEX_STATIC_VFS2     12  /* For use by extension VFS */\n#define SQLITE_MUTEX_STATIC_VFS3     13  /* For use by application VFS */\n\n/*\n** CAPI3REF: Retrieve the mutex for a database connection\n** METHOD: sqlite3\n**\n** ^This interface returns a pointer the [sqlite3_mutex] object that \n** serializes access to the [database connection] given in the argument\n** when the [threading mode] is Serialized.\n** ^If the [threading mode] is Single-thread or Multi-thread then this\n** routine returns a NULL pointer.\n*/\nSQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);\n\n/*\n** CAPI3REF: Low-Level Control Of Database Files\n** METHOD: sqlite3\n** KEYWORDS: {file control}\n**\n** ^The [sqlite3_file_control()] interface makes a direct call to the\n** xFileControl method for the [sqlite3_io_methods] object associated\n** with a particular database identified by the second argument. ^The\n** name of the database is \"main\" for the main database or \"temp\" for the\n** TEMP database, or the name that appears after the AS keyword for\n** databases that are added using the [ATTACH] SQL command.\n** ^A NULL pointer can be used in place of \"main\" to refer to the\n** main database file.\n** ^The third and fourth parameters to this routine\n** are passed directly through to the second and third parameters of\n** the xFileControl method.  ^The return value of the xFileControl\n** method becomes the return value of this routine.\n**\n** A few opcodes for [sqlite3_file_control()] are handled directly\n** by the SQLite core and never invoke the \n** sqlite3_io_methods.xFileControl method.\n** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes\n** a pointer to the underlying [sqlite3_file] object to be written into\n** the space pointed to by the 4th parameter.  The\n** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns\n** the [sqlite3_file] object associated with the journal file instead of\n** the main database.  The [SQLITE_FCNTL_VFS_POINTER] opcode returns\n** a pointer to the underlying [sqlite3_vfs] object for the file.\n** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter\n** from the pager.\n**\n** ^If the second parameter (zDbName) does not match the name of any\n** open database file, then SQLITE_ERROR is returned.  ^This error\n** code is not remembered and will not be recalled by [sqlite3_errcode()]\n** or [sqlite3_errmsg()].  The underlying xFileControl method might\n** also return SQLITE_ERROR.  There is no way to distinguish between\n** an incorrect zDbName and an SQLITE_ERROR return from the underlying\n** xFileControl method.\n**\n** See also: [file control opcodes]\n*/\nSQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);\n\n/*\n** CAPI3REF: Testing Interface\n**\n** ^The sqlite3_test_control() interface is used to read out internal\n** state of SQLite and to inject faults into SQLite for testing\n** purposes.  ^The first parameter is an operation code that determines\n** the number, meaning, and operation of all subsequent parameters.\n**\n** This interface is not for use by applications.  It exists solely\n** for verifying the correct operation of the SQLite library.  Depending\n** on how the SQLite library is compiled, this interface might not exist.\n**\n** The details of the operation codes, their meanings, the parameters\n** they take, and what they do are all subject to change without notice.\n** Unlike most of the SQLite API, this function is not guaranteed to\n** operate consistently from one release to the next.\n*/\nSQLITE_API int sqlite3_test_control(int op, ...);\n\n/*\n** CAPI3REF: Testing Interface Operation Codes\n**\n** These constants are the valid operation code parameters used\n** as the first argument to [sqlite3_test_control()].\n**\n** These parameters and their meanings are subject to change\n** without notice.  These values are for testing purposes only.\n** Applications should not use any of these parameters or the\n** [sqlite3_test_control()] interface.\n*/\n#define SQLITE_TESTCTRL_FIRST                    5\n#define SQLITE_TESTCTRL_PRNG_SAVE                5\n#define SQLITE_TESTCTRL_PRNG_RESTORE             6\n#define SQLITE_TESTCTRL_PRNG_RESET               7  /* NOT USED */\n#define SQLITE_TESTCTRL_BITVEC_TEST              8\n#define SQLITE_TESTCTRL_FAULT_INSTALL            9\n#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10\n#define SQLITE_TESTCTRL_PENDING_BYTE            11\n#define SQLITE_TESTCTRL_ASSERT                  12\n#define SQLITE_TESTCTRL_ALWAYS                  13\n#define SQLITE_TESTCTRL_RESERVE                 14  /* NOT USED */\n#define SQLITE_TESTCTRL_OPTIMIZATIONS           15\n#define SQLITE_TESTCTRL_ISKEYWORD               16  /* NOT USED */\n#define SQLITE_TESTCTRL_SCRATCHMALLOC           17  /* NOT USED */\n#define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS      17\n#define SQLITE_TESTCTRL_LOCALTIME_FAULT         18\n#define SQLITE_TESTCTRL_EXPLAIN_STMT            19  /* NOT USED */\n#define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD    19\n#define SQLITE_TESTCTRL_NEVER_CORRUPT           20\n#define SQLITE_TESTCTRL_VDBE_COVERAGE           21\n#define SQLITE_TESTCTRL_BYTEORDER               22\n#define SQLITE_TESTCTRL_ISINIT                  23\n#define SQLITE_TESTCTRL_SORTER_MMAP             24\n#define SQLITE_TESTCTRL_IMPOSTER                25\n#define SQLITE_TESTCTRL_PARSER_COVERAGE         26\n#define SQLITE_TESTCTRL_RESULT_INTREAL          27\n#define SQLITE_TESTCTRL_PRNG_SEED               28\n#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS     29\n#define SQLITE_TESTCTRL_LAST                    29  /* Largest TESTCTRL */\n\n/*\n** CAPI3REF: SQL Keyword Checking\n**\n** These routines provide access to the set of SQL language keywords \n** recognized by SQLite.  Applications can uses these routines to determine\n** whether or not a specific identifier needs to be escaped (for example,\n** by enclosing in double-quotes) so as not to confuse the parser.\n**\n** The sqlite3_keyword_count() interface returns the number of distinct\n** keywords understood by SQLite.\n**\n** The sqlite3_keyword_name(N,Z,L) interface finds the N-th keyword and\n** makes *Z point to that keyword expressed as UTF8 and writes the number\n** of bytes in the keyword into *L.  The string that *Z points to is not\n** zero-terminated.  The sqlite3_keyword_name(N,Z,L) routine returns\n** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z\n** or L are NULL or invalid pointers then calls to\n** sqlite3_keyword_name(N,Z,L) result in undefined behavior.\n**\n** The sqlite3_keyword_check(Z,L) interface checks to see whether or not\n** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero\n** if it is and zero if not.\n**\n** The parser used by SQLite is forgiving.  It is often possible to use\n** a keyword as an identifier as long as such use does not result in a\n** parsing ambiguity.  For example, the statement\n** \"CREATE TABLE BEGIN(REPLACE,PRAGMA,END);\" is accepted by SQLite, and\n** creates a new table named \"BEGIN\" with three columns named\n** \"REPLACE\", \"PRAGMA\", and \"END\".  Nevertheless, best practice is to avoid\n** using keywords as identifiers.  Common techniques used to avoid keyword\n** name collisions include:\n** <ul>\n** <li> Put all identifier names inside double-quotes.  This is the official\n**      SQL way to escape identifier names.\n** <li> Put identifier names inside &#91;...&#93;.  This is not standard SQL,\n**      but it is what SQL Server does and so lots of programmers use this\n**      technique.\n** <li> Begin every identifier with the letter \"Z\" as no SQL keywords start\n**      with \"Z\".\n** <li> Include a digit somewhere in every identifier name.\n** </ul>\n**\n** Note that the number of keywords understood by SQLite can depend on\n** compile-time options.  For example, \"VACUUM\" is not a keyword if\n** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option.  Also,\n** new keywords may be added to future releases of SQLite.\n*/\nSQLITE_API int sqlite3_keyword_count(void);\nSQLITE_API int sqlite3_keyword_name(int,const char**,int*);\nSQLITE_API int sqlite3_keyword_check(const char*,int);\n\n/*\n** CAPI3REF: Dynamic String Object\n** KEYWORDS: {dynamic string}\n**\n** An instance of the sqlite3_str object contains a dynamically-sized\n** string under construction.\n**\n** The lifecycle of an sqlite3_str object is as follows:\n** <ol>\n** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].\n** <li> ^Text is appended to the sqlite3_str object using various\n** methods, such as [sqlite3_str_appendf()].\n** <li> ^The sqlite3_str object is destroyed and the string it created\n** is returned using the [sqlite3_str_finish()] interface.\n** </ol>\n*/\ntypedef struct sqlite3_str sqlite3_str;\n\n/*\n** CAPI3REF: Create A New Dynamic String Object\n** CONSTRUCTOR: sqlite3_str\n**\n** ^The [sqlite3_str_new(D)] interface allocates and initializes\n** a new [sqlite3_str] object.  To avoid memory leaks, the object returned by\n** [sqlite3_str_new()] must be freed by a subsequent call to \n** [sqlite3_str_finish(X)].\n**\n** ^The [sqlite3_str_new(D)] interface always returns a pointer to a\n** valid [sqlite3_str] object, though in the event of an out-of-memory\n** error the returned object might be a special singleton that will\n** silently reject new text, always return SQLITE_NOMEM from \n** [sqlite3_str_errcode()], always return 0 for \n** [sqlite3_str_length()], and always return NULL from\n** [sqlite3_str_finish(X)].  It is always safe to use the value\n** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter\n** to any of the other [sqlite3_str] methods.\n**\n** The D parameter to [sqlite3_str_new(D)] may be NULL.  If the\n** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum\n** length of the string contained in the [sqlite3_str] object will be\n** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead\n** of [SQLITE_MAX_LENGTH].\n*/\nSQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);\n\n/*\n** CAPI3REF: Finalize A Dynamic String\n** DESTRUCTOR: sqlite3_str\n**\n** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X\n** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]\n** that contains the constructed string.  The calling application should\n** pass the returned value to [sqlite3_free()] to avoid a memory leak.\n** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any\n** errors were encountered during construction of the string.  ^The\n** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the\n** string in [sqlite3_str] object X is zero bytes long.\n*/\nSQLITE_API char *sqlite3_str_finish(sqlite3_str*);\n\n/*\n** CAPI3REF: Add Content To A Dynamic String\n** METHOD: sqlite3_str\n**\n** These interfaces add content to an sqlite3_str object previously obtained\n** from [sqlite3_str_new()].\n**\n** ^The [sqlite3_str_appendf(X,F,...)] and \n** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]\n** functionality of SQLite to append formatted text onto the end of \n** [sqlite3_str] object X.\n**\n** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S\n** onto the end of the [sqlite3_str] object X.  N must be non-negative.\n** S must contain at least N non-zero bytes of content.  To append a\n** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]\n** method instead.\n**\n** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of\n** zero-terminated string S onto the end of [sqlite3_str] object X.\n**\n** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the\n** single-byte character C onto the end of [sqlite3_str] object X.\n** ^This method can be used, for example, to add whitespace indentation.\n**\n** ^The [sqlite3_str_reset(X)] method resets the string under construction\n** inside [sqlite3_str] object X back to zero bytes in length.  \n**\n** These methods do not return a result code.  ^If an error occurs, that fact\n** is recorded in the [sqlite3_str] object and can be recovered by a\n** subsequent call to [sqlite3_str_errcode(X)].\n*/\nSQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);\nSQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);\nSQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);\nSQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);\nSQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);\nSQLITE_API void sqlite3_str_reset(sqlite3_str*);\n\n/*\n** CAPI3REF: Status Of A Dynamic String\n** METHOD: sqlite3_str\n**\n** These interfaces return the current status of an [sqlite3_str] object.\n**\n** ^If any prior errors have occurred while constructing the dynamic string\n** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return\n** an appropriate error code.  ^The [sqlite3_str_errcode(X)] method returns\n** [SQLITE_NOMEM] following any out-of-memory error, or\n** [SQLITE_TOOBIG] if the size of the dynamic string exceeds\n** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.\n**\n** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,\n** of the dynamic string under construction in [sqlite3_str] object X.\n** ^The length returned by [sqlite3_str_length(X)] does not include the\n** zero-termination byte.\n**\n** ^The [sqlite3_str_value(X)] method returns a pointer to the current\n** content of the dynamic string under construction in X.  The value\n** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X\n** and might be freed or altered by any subsequent method on the same\n** [sqlite3_str] object.  Applications must not used the pointer returned\n** [sqlite3_str_value(X)] after any subsequent method call on the same\n** object.  ^Applications may change the content of the string returned\n** by [sqlite3_str_value(X)] as long as they do not write into any bytes\n** outside the range of 0 to [sqlite3_str_length(X)] and do not read or\n** write any byte after any subsequent sqlite3_str method call.\n*/\nSQLITE_API int sqlite3_str_errcode(sqlite3_str*);\nSQLITE_API int sqlite3_str_length(sqlite3_str*);\nSQLITE_API char *sqlite3_str_value(sqlite3_str*);\n\n/*\n** CAPI3REF: SQLite Runtime Status\n**\n** ^These interfaces are used to retrieve runtime status information\n** about the performance of SQLite, and optionally to reset various\n** highwater marks.  ^The first argument is an integer code for\n** the specific parameter to measure.  ^(Recognized integer codes\n** are of the form [status parameters | SQLITE_STATUS_...].)^\n** ^The current value of the parameter is returned into *pCurrent.\n** ^The highest recorded value is returned in *pHighwater.  ^If the\n** resetFlag is true, then the highest record value is reset after\n** *pHighwater is written.  ^(Some parameters do not record the highest\n** value.  For those parameters\n** nothing is written into *pHighwater and the resetFlag is ignored.)^\n** ^(Other parameters record only the highwater mark and not the current\n** value.  For these latter parameters nothing is written into *pCurrent.)^\n**\n** ^The sqlite3_status() and sqlite3_status64() routines return\n** SQLITE_OK on success and a non-zero [error code] on failure.\n**\n** If either the current value or the highwater mark is too large to\n** be represented by a 32-bit integer, then the values returned by\n** sqlite3_status() are undefined.\n**\n** See also: [sqlite3_db_status()]\n*/\nSQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);\nSQLITE_API int sqlite3_status64(\n  int op,\n  sqlite3_int64 *pCurrent,\n  sqlite3_int64 *pHighwater,\n  int resetFlag\n);\n\n\n/*\n** CAPI3REF: Status Parameters\n** KEYWORDS: {status parameters}\n**\n** These integer constants designate various run-time status parameters\n** that can be returned by [sqlite3_status()].\n**\n** <dl>\n** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>\n** <dd>This parameter is the current amount of memory checked out\n** using [sqlite3_malloc()], either directly or indirectly.  The\n** figure includes calls made to [sqlite3_malloc()] by the application\n** and internal memory usage by the SQLite library.  Auxiliary page-cache\n** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in\n** this parameter.  The amount returned is the sum of the allocation\n** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^\n**\n** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>\n** <dd>This parameter records the largest memory allocation request\n** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their\n** internal equivalents).  Only the value returned in the\n** *pHighwater parameter to [sqlite3_status()] is of interest.  \n** The value written into the *pCurrent parameter is undefined.</dd>)^\n**\n** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>\n** <dd>This parameter records the number of separate memory allocations\n** currently checked out.</dd>)^\n**\n** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>\n** <dd>This parameter returns the number of pages used out of the\n** [pagecache memory allocator] that was configured using \n** [SQLITE_CONFIG_PAGECACHE].  The\n** value returned is in pages, not in bytes.</dd>)^\n**\n** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] \n** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>\n** <dd>This parameter returns the number of bytes of page cache\n** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]\n** buffer and where forced to overflow to [sqlite3_malloc()].  The\n** returned value includes allocations that overflowed because they\n** where too large (they were larger than the \"sz\" parameter to\n** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because\n** no space was left in the page cache.</dd>)^\n**\n** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>\n** <dd>This parameter records the largest memory allocation request\n** handed to the [pagecache memory allocator].  Only the value returned in the\n** *pHighwater parameter to [sqlite3_status()] is of interest.  \n** The value written into the *pCurrent parameter is undefined.</dd>)^\n**\n** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>\n** <dd>No longer used.</dd>\n**\n** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>\n** <dd>No longer used.</dd>\n**\n** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>\n** <dd>No longer used.</dd>\n**\n** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>\n** <dd>The *pHighwater parameter records the deepest parser stack. \n** The *pCurrent value is undefined.  The *pHighwater value is only\n** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^\n** </dl>\n**\n** New status parameters may be added from time to time.\n*/\n#define SQLITE_STATUS_MEMORY_USED          0\n#define SQLITE_STATUS_PAGECACHE_USED       1\n#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2\n#define SQLITE_STATUS_SCRATCH_USED         3  /* NOT USED */\n#define SQLITE_STATUS_SCRATCH_OVERFLOW     4  /* NOT USED */\n#define SQLITE_STATUS_MALLOC_SIZE          5\n#define SQLITE_STATUS_PARSER_STACK         6\n#define SQLITE_STATUS_PAGECACHE_SIZE       7\n#define SQLITE_STATUS_SCRATCH_SIZE         8  /* NOT USED */\n#define SQLITE_STATUS_MALLOC_COUNT         9\n\n/*\n** CAPI3REF: Database Connection Status\n** METHOD: sqlite3\n**\n** ^This interface is used to retrieve runtime status information \n** about a single [database connection].  ^The first argument is the\n** database connection object to be interrogated.  ^The second argument\n** is an integer constant, taken from the set of\n** [SQLITE_DBSTATUS options], that\n** determines the parameter to interrogate.  The set of \n** [SQLITE_DBSTATUS options] is likely\n** to grow in future releases of SQLite.\n**\n** ^The current value of the requested parameter is written into *pCur\n** and the highest instantaneous value is written into *pHiwtr.  ^If\n** the resetFlg is true, then the highest instantaneous value is\n** reset back down to the current value.\n**\n** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a\n** non-zero [error code] on failure.\n**\n** See also: [sqlite3_status()] and [sqlite3_stmt_status()].\n*/\nSQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);\n\n/*\n** CAPI3REF: Status Parameters for database connections\n** KEYWORDS: {SQLITE_DBSTATUS options}\n**\n** These constants are the available integer \"verbs\" that can be passed as\n** the second argument to the [sqlite3_db_status()] interface.\n**\n** New verbs may be added in future releases of SQLite. Existing verbs\n** might be discontinued. Applications should check the return code from\n** [sqlite3_db_status()] to make sure that the call worked.\n** The [sqlite3_db_status()] interface will return a non-zero error code\n** if a discontinued or unsupported verb is invoked.\n**\n** <dl>\n** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>\n** <dd>This parameter returns the number of lookaside memory slots currently\n** checked out.</dd>)^\n**\n** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>\n** <dd>This parameter returns the number of malloc attempts that were \n** satisfied using lookaside memory. Only the high-water value is meaningful;\n** the current value is always zero.)^\n**\n** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]\n** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>\n** <dd>This parameter returns the number malloc attempts that might have\n** been satisfied using lookaside memory but failed due to the amount of\n** memory requested being larger than the lookaside slot size.\n** Only the high-water value is meaningful;\n** the current value is always zero.)^\n**\n** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]\n** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>\n** <dd>This parameter returns the number malloc attempts that might have\n** been satisfied using lookaside memory but failed due to all lookaside\n** memory already being in use.\n** Only the high-water value is meaningful;\n** the current value is always zero.)^\n**\n** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>\n** <dd>This parameter returns the approximate number of bytes of heap\n** memory used by all pager caches associated with the database connection.)^\n** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.\n**\n** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]] \n** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>\n** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a\n** pager cache is shared between two or more connections the bytes of heap\n** memory used by that pager cache is divided evenly between the attached\n** connections.)^  In other words, if none of the pager caches associated\n** with the database connection are shared, this request returns the same\n** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are\n** shared, the value returned by this call will be smaller than that returned\n** by DBSTATUS_CACHE_USED. ^The highwater mark associated with\n** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.\n**\n** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>\n** <dd>This parameter returns the approximate number of bytes of heap\n** memory used to store the schema for all databases associated\n** with the connection - main, temp, and any [ATTACH]-ed databases.)^ \n** ^The full amount of memory used by the schemas is reported, even if the\n** schema memory is shared with other database connections due to\n** [shared cache mode] being enabled.\n** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.\n**\n** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>\n** <dd>This parameter returns the approximate number of bytes of heap\n** and lookaside memory used by all prepared statements associated with\n** the database connection.)^\n** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.\n** </dd>\n**\n** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>\n** <dd>This parameter returns the number of pager cache hits that have\n** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT \n** is always 0.\n** </dd>\n**\n** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>\n** <dd>This parameter returns the number of pager cache misses that have\n** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS \n** is always 0.\n** </dd>\n**\n** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>\n** <dd>This parameter returns the number of dirty cache entries that have\n** been written to disk. Specifically, the number of pages written to the\n** wal file in wal mode databases, or the number of pages written to the\n** database file in rollback mode databases. Any pages written as part of\n** transaction rollback or database recovery operations are not included.\n** If an IO or other error occurs while writing a page to disk, the effect\n** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The\n** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.\n** </dd>\n**\n** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>\n** <dd>This parameter returns the number of dirty cache entries that have\n** been written to disk in the middle of a transaction due to the page\n** cache overflowing. Transactions are more efficient if they are written\n** to disk all at once. When pages spill mid-transaction, that introduces\n** additional overhead. This parameter can be used help identify\n** inefficiencies that can be resolved by increasing the cache size.\n** </dd>\n**\n** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>\n** <dd>This parameter returns zero for the current value if and only if\n** all foreign key constraints (deferred or immediate) have been\n** resolved.)^  ^The highwater mark is always 0.\n** </dd>\n** </dl>\n*/\n#define SQLITE_DBSTATUS_LOOKASIDE_USED       0\n#define SQLITE_DBSTATUS_CACHE_USED           1\n#define SQLITE_DBSTATUS_SCHEMA_USED          2\n#define SQLITE_DBSTATUS_STMT_USED            3\n#define SQLITE_DBSTATUS_LOOKASIDE_HIT        4\n#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5\n#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6\n#define SQLITE_DBSTATUS_CACHE_HIT            7\n#define SQLITE_DBSTATUS_CACHE_MISS           8\n#define SQLITE_DBSTATUS_CACHE_WRITE          9\n#define SQLITE_DBSTATUS_DEFERRED_FKS        10\n#define SQLITE_DBSTATUS_CACHE_USED_SHARED   11\n#define SQLITE_DBSTATUS_CACHE_SPILL         12\n#define SQLITE_DBSTATUS_MAX                 12   /* Largest defined DBSTATUS */\n\n\n/*\n** CAPI3REF: Prepared Statement Status\n** METHOD: sqlite3_stmt\n**\n** ^(Each prepared statement maintains various\n** [SQLITE_STMTSTATUS counters] that measure the number\n** of times it has performed specific operations.)^  These counters can\n** be used to monitor the performance characteristics of the prepared\n** statements.  For example, if the number of table steps greatly exceeds\n** the number of table searches or result rows, that would tend to indicate\n** that the prepared statement is using a full table scan rather than\n** an index.  \n**\n** ^(This interface is used to retrieve and reset counter values from\n** a [prepared statement].  The first argument is the prepared statement\n** object to be interrogated.  The second argument\n** is an integer code for a specific [SQLITE_STMTSTATUS counter]\n** to be interrogated.)^\n** ^The current value of the requested counter is returned.\n** ^If the resetFlg is true, then the counter is reset to zero after this\n** interface call returns.\n**\n** See also: [sqlite3_status()] and [sqlite3_db_status()].\n*/\nSQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);\n\n/*\n** CAPI3REF: Status Parameters for prepared statements\n** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}\n**\n** These preprocessor macros define integer codes that name counter\n** values associated with the [sqlite3_stmt_status()] interface.\n** The meanings of the various counters are as follows:\n**\n** <dl>\n** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>\n** <dd>^This is the number of times that SQLite has stepped forward in\n** a table as part of a full table scan.  Large numbers for this counter\n** may indicate opportunities for performance improvement through \n** careful use of indices.</dd>\n**\n** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>\n** <dd>^This is the number of sort operations that have occurred.\n** A non-zero value in this counter may indicate an opportunity to\n** improvement performance through careful use of indices.</dd>\n**\n** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>\n** <dd>^This is the number of rows inserted into transient indices that\n** were created automatically in order to help joins run faster.\n** A non-zero value in this counter may indicate an opportunity to\n** improvement performance by adding permanent indices that do not\n** need to be reinitialized each time the statement is run.</dd>\n**\n** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>\n** <dd>^This is the number of virtual machine operations executed\n** by the prepared statement if that number is less than or equal\n** to 2147483647.  The number of virtual machine operations can be \n** used as a proxy for the total work done by the prepared statement.\n** If the number of virtual machine operations exceeds 2147483647\n** then the value returned by this statement status code is undefined.\n**\n** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>\n** <dd>^This is the number of times that the prepare statement has been\n** automatically regenerated due to schema changes or changes to \n** [bound parameters] that might affect the query plan.\n**\n** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>\n** <dd>^This is the number of times that the prepared statement has\n** been run.  A single \"run\" for the purposes of this counter is one\n** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].\n** The counter is incremented on the first [sqlite3_step()] call of each\n** cycle.\n**\n** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>\n** <dd>^This is the approximate number of bytes of heap memory\n** used to store the prepared statement.  ^This value is not actually\n** a counter, and so the resetFlg parameter to sqlite3_stmt_status()\n** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.\n** </dd>\n** </dl>\n*/\n#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1\n#define SQLITE_STMTSTATUS_SORT              2\n#define SQLITE_STMTSTATUS_AUTOINDEX         3\n#define SQLITE_STMTSTATUS_VM_STEP           4\n#define SQLITE_STMTSTATUS_REPREPARE         5\n#define SQLITE_STMTSTATUS_RUN               6\n#define SQLITE_STMTSTATUS_MEMUSED           99\n\n/*\n** CAPI3REF: Custom Page Cache Object\n**\n** The sqlite3_pcache type is opaque.  It is implemented by\n** the pluggable module.  The SQLite core has no knowledge of\n** its size or internal structure and never deals with the\n** sqlite3_pcache object except by holding and passing pointers\n** to the object.\n**\n** See [sqlite3_pcache_methods2] for additional information.\n*/\ntypedef struct sqlite3_pcache sqlite3_pcache;\n\n/*\n** CAPI3REF: Custom Page Cache Object\n**\n** The sqlite3_pcache_page object represents a single page in the\n** page cache.  The page cache will allocate instances of this\n** object.  Various methods of the page cache use pointers to instances\n** of this object as parameters or as their return value.\n**\n** See [sqlite3_pcache_methods2] for additional information.\n*/\ntypedef struct sqlite3_pcache_page sqlite3_pcache_page;\nstruct sqlite3_pcache_page {\n  void *pBuf;        /* The content of the page */\n  void *pExtra;      /* Extra information associated with the page */\n};\n\n/*\n** CAPI3REF: Application Defined Page Cache.\n** KEYWORDS: {page cache}\n**\n** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can\n** register an alternative page cache implementation by passing in an \n** instance of the sqlite3_pcache_methods2 structure.)^\n** In many applications, most of the heap memory allocated by \n** SQLite is used for the page cache.\n** By implementing a \n** custom page cache using this API, an application can better control\n** the amount of memory consumed by SQLite, the way in which \n** that memory is allocated and released, and the policies used to \n** determine exactly which parts of a database file are cached and for \n** how long.\n**\n** The alternative page cache mechanism is an\n** extreme measure that is only needed by the most demanding applications.\n** The built-in page cache is recommended for most uses.\n**\n** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an\n** internal buffer by SQLite within the call to [sqlite3_config].  Hence\n** the application may discard the parameter after the call to\n** [sqlite3_config()] returns.)^\n**\n** [[the xInit() page cache method]]\n** ^(The xInit() method is called once for each effective \n** call to [sqlite3_initialize()])^\n** (usually only once during the lifetime of the process). ^(The xInit()\n** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^\n** The intent of the xInit() method is to set up global data structures \n** required by the custom page cache implementation. \n** ^(If the xInit() method is NULL, then the \n** built-in default page cache is used instead of the application defined\n** page cache.)^\n**\n** [[the xShutdown() page cache method]]\n** ^The xShutdown() method is called by [sqlite3_shutdown()].\n** It can be used to clean up \n** any outstanding resources before process shutdown, if required.\n** ^The xShutdown() method may be NULL.\n**\n** ^SQLite automatically serializes calls to the xInit method,\n** so the xInit method need not be threadsafe.  ^The\n** xShutdown method is only called from [sqlite3_shutdown()] so it does\n** not need to be threadsafe either.  All other methods must be threadsafe\n** in multithreaded applications.\n**\n** ^SQLite will never invoke xInit() more than once without an intervening\n** call to xShutdown().\n**\n** [[the xCreate() page cache methods]]\n** ^SQLite invokes the xCreate() method to construct a new cache instance.\n** SQLite will typically create one cache instance for each open database file,\n** though this is not guaranteed. ^The\n** first parameter, szPage, is the size in bytes of the pages that must\n** be allocated by the cache.  ^szPage will always a power of two.  ^The\n** second parameter szExtra is a number of bytes of extra storage \n** associated with each page cache entry.  ^The szExtra parameter will\n** a number less than 250.  SQLite will use the\n** extra szExtra bytes on each page to store metadata about the underlying\n** database page on disk.  The value passed into szExtra depends\n** on the SQLite version, the target platform, and how SQLite was compiled.\n** ^The third argument to xCreate(), bPurgeable, is true if the cache being\n** created will be used to cache database pages of a file stored on disk, or\n** false if it is used for an in-memory database. The cache implementation\n** does not have to do anything special based with the value of bPurgeable;\n** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will\n** never invoke xUnpin() except to deliberately delete a page.\n** ^In other words, calls to xUnpin() on a cache with bPurgeable set to\n** false will always have the \"discard\" flag set to true.  \n** ^Hence, a cache created with bPurgeable false will\n** never contain any unpinned pages.\n**\n** [[the xCachesize() page cache method]]\n** ^(The xCachesize() method may be called at any time by SQLite to set the\n** suggested maximum cache-size (number of pages stored by) the cache\n** instance passed as the first argument. This is the value configured using\n** the SQLite \"[PRAGMA cache_size]\" command.)^  As with the bPurgeable\n** parameter, the implementation is not required to do anything with this\n** value; it is advisory only.\n**\n** [[the xPagecount() page cache methods]]\n** The xPagecount() method must return the number of pages currently\n** stored in the cache, both pinned and unpinned.\n** \n** [[the xFetch() page cache methods]]\n** The xFetch() method locates a page in the cache and returns a pointer to \n** an sqlite3_pcache_page object associated with that page, or a NULL pointer.\n** The pBuf element of the returned sqlite3_pcache_page object will be a\n** pointer to a buffer of szPage bytes used to store the content of a \n** single database page.  The pExtra element of sqlite3_pcache_page will be\n** a pointer to the szExtra bytes of extra storage that SQLite has requested\n** for each entry in the page cache.\n**\n** The page to be fetched is determined by the key. ^The minimum key value\n** is 1.  After it has been retrieved using xFetch, the page is considered\n** to be \"pinned\".\n**\n** If the requested page is already in the page cache, then the page cache\n** implementation must return a pointer to the page buffer with its content\n** intact.  If the requested page is not already in the cache, then the\n** cache implementation should use the value of the createFlag\n** parameter to help it determined what action to take:\n**\n** <table border=1 width=85% align=center>\n** <tr><th> createFlag <th> Behavior when page is not already in cache\n** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.\n** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.\n**                 Otherwise return NULL.\n** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return\n**                 NULL if allocating a new page is effectively impossible.\n** </table>\n**\n** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite\n** will only use a createFlag of 2 after a prior call with a createFlag of 1\n** failed.)^  In between the xFetch() calls, SQLite may\n** attempt to unpin one or more cache pages by spilling the content of\n** pinned pages to disk and synching the operating system disk cache.\n**\n** [[the xUnpin() page cache method]]\n** ^xUnpin() is called by SQLite with a pointer to a currently pinned page\n** as its second argument.  If the third parameter, discard, is non-zero,\n** then the page must be evicted from the cache.\n** ^If the discard parameter is\n** zero, then the page may be discarded or retained at the discretion of\n** page cache implementation. ^The page cache implementation\n** may choose to evict unpinned pages at any time.\n**\n** The cache must not perform any reference counting. A single \n** call to xUnpin() unpins the page regardless of the number of prior calls \n** to xFetch().\n**\n** [[the xRekey() page cache methods]]\n** The xRekey() method is used to change the key value associated with the\n** page passed as the second argument. If the cache\n** previously contains an entry associated with newKey, it must be\n** discarded. ^Any prior cache entry associated with newKey is guaranteed not\n** to be pinned.\n**\n** When SQLite calls the xTruncate() method, the cache must discard all\n** existing cache entries with page numbers (keys) greater than or equal\n** to the value of the iLimit parameter passed to xTruncate(). If any\n** of these pages are pinned, they are implicitly unpinned, meaning that\n** they can be safely discarded.\n**\n** [[the xDestroy() page cache method]]\n** ^The xDestroy() method is used to delete a cache allocated by xCreate().\n** All resources associated with the specified cache should be freed. ^After\n** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]\n** handle invalid, and will not use it with any other sqlite3_pcache_methods2\n** functions.\n**\n** [[the xShrink() page cache method]]\n** ^SQLite invokes the xShrink() method when it wants the page cache to\n** free up as much of heap memory as possible.  The page cache implementation\n** is not obligated to free any memory, but well-behaved implementations should\n** do their best.\n*/\ntypedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;\nstruct sqlite3_pcache_methods2 {\n  int iVersion;\n  void *pArg;\n  int (*xInit)(void*);\n  void (*xShutdown)(void*);\n  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);\n  void (*xCachesize)(sqlite3_pcache*, int nCachesize);\n  int (*xPagecount)(sqlite3_pcache*);\n  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);\n  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);\n  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, \n      unsigned oldKey, unsigned newKey);\n  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);\n  void (*xDestroy)(sqlite3_pcache*);\n  void (*xShrink)(sqlite3_pcache*);\n};\n\n/*\n** This is the obsolete pcache_methods object that has now been replaced\n** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is\n** retained in the header file for backwards compatibility only.\n*/\ntypedef struct sqlite3_pcache_methods sqlite3_pcache_methods;\nstruct sqlite3_pcache_methods {\n  void *pArg;\n  int (*xInit)(void*);\n  void (*xShutdown)(void*);\n  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);\n  void (*xCachesize)(sqlite3_pcache*, int nCachesize);\n  int (*xPagecount)(sqlite3_pcache*);\n  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);\n  void (*xUnpin)(sqlite3_pcache*, void*, int discard);\n  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);\n  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);\n  void (*xDestroy)(sqlite3_pcache*);\n};\n\n\n/*\n** CAPI3REF: Online Backup Object\n**\n** The sqlite3_backup object records state information about an ongoing\n** online backup operation.  ^The sqlite3_backup object is created by\n** a call to [sqlite3_backup_init()] and is destroyed by a call to\n** [sqlite3_backup_finish()].\n**\n** See Also: [Using the SQLite Online Backup API]\n*/\ntypedef struct sqlite3_backup sqlite3_backup;\n\n/*\n** CAPI3REF: Online Backup API.\n**\n** The backup API copies the content of one database into another.\n** It is useful either for creating backups of databases or\n** for copying in-memory databases to or from persistent files. \n**\n** See Also: [Using the SQLite Online Backup API]\n**\n** ^SQLite holds a write transaction open on the destination database file\n** for the duration of the backup operation.\n** ^The source database is read-locked only while it is being read;\n** it is not locked continuously for the entire backup operation.\n** ^Thus, the backup may be performed on a live source database without\n** preventing other database connections from\n** reading or writing to the source database while the backup is underway.\n** \n** ^(To perform a backup operation: \n**   <ol>\n**     <li><b>sqlite3_backup_init()</b> is called once to initialize the\n**         backup, \n**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer \n**         the data between the two databases, and finally\n**     <li><b>sqlite3_backup_finish()</b> is called to release all resources \n**         associated with the backup operation. \n**   </ol>)^\n** There should be exactly one call to sqlite3_backup_finish() for each\n** successful call to sqlite3_backup_init().\n**\n** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>\n**\n** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the \n** [database connection] associated with the destination database \n** and the database name, respectively.\n** ^The database name is \"main\" for the main database, \"temp\" for the\n** temporary database, or the name specified after the AS keyword in\n** an [ATTACH] statement for an attached database.\n** ^The S and M arguments passed to \n** sqlite3_backup_init(D,N,S,M) identify the [database connection]\n** and database name of the source database, respectively.\n** ^The source and destination [database connections] (parameters S and D)\n** must be different or else sqlite3_backup_init(D,N,S,M) will fail with\n** an error.\n**\n** ^A call to sqlite3_backup_init() will fail, returning NULL, if \n** there is already a read or read-write transaction open on the \n** destination database.\n**\n** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is\n** returned and an error code and error message are stored in the\n** destination [database connection] D.\n** ^The error code and message for the failed call to sqlite3_backup_init()\n** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or\n** [sqlite3_errmsg16()] functions.\n** ^A successful call to sqlite3_backup_init() returns a pointer to an\n** [sqlite3_backup] object.\n** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and\n** sqlite3_backup_finish() functions to perform the specified backup \n** operation.\n**\n** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>\n**\n** ^Function sqlite3_backup_step(B,N) will copy up to N pages between \n** the source and destination databases specified by [sqlite3_backup] object B.\n** ^If N is negative, all remaining source pages are copied. \n** ^If sqlite3_backup_step(B,N) successfully copies N pages and there\n** are still more pages to be copied, then the function returns [SQLITE_OK].\n** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages\n** from source to destination, then it returns [SQLITE_DONE].\n** ^If an error occurs while running sqlite3_backup_step(B,N),\n** then an [error code] is returned. ^As well as [SQLITE_OK] and\n** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],\n** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an\n** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.\n**\n** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if\n** <ol>\n** <li> the destination database was opened read-only, or\n** <li> the destination database is using write-ahead-log journaling\n** and the destination and source page sizes differ, or\n** <li> the destination database is an in-memory database and the\n** destination and source page sizes differ.\n** </ol>)^\n**\n** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then\n** the [sqlite3_busy_handler | busy-handler function]\n** is invoked (if one is specified). ^If the \n** busy-handler returns non-zero before the lock is available, then \n** [SQLITE_BUSY] is returned to the caller. ^In this case the call to\n** sqlite3_backup_step() can be retried later. ^If the source\n** [database connection]\n** is being used to write to the source database when sqlite3_backup_step()\n** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this\n** case the call to sqlite3_backup_step() can be retried later on. ^(If\n** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or\n** [SQLITE_READONLY] is returned, then \n** there is no point in retrying the call to sqlite3_backup_step(). These \n** errors are considered fatal.)^  The application must accept \n** that the backup operation has failed and pass the backup operation handle \n** to the sqlite3_backup_finish() to release associated resources.\n**\n** ^The first call to sqlite3_backup_step() obtains an exclusive lock\n** on the destination file. ^The exclusive lock is not released until either \n** sqlite3_backup_finish() is called or the backup operation is complete \n** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to\n** sqlite3_backup_step() obtains a [shared lock] on the source database that\n** lasts for the duration of the sqlite3_backup_step() call.\n** ^Because the source database is not locked between calls to\n** sqlite3_backup_step(), the source database may be modified mid-way\n** through the backup process.  ^If the source database is modified by an\n** external process or via a database connection other than the one being\n** used by the backup operation, then the backup will be automatically\n** restarted by the next call to sqlite3_backup_step(). ^If the source \n** database is modified by the using the same database connection as is used\n** by the backup operation, then the backup database is automatically\n** updated at the same time.\n**\n** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>\n**\n** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the \n** application wishes to abandon the backup operation, the application\n** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().\n** ^The sqlite3_backup_finish() interfaces releases all\n** resources associated with the [sqlite3_backup] object. \n** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any\n** active write-transaction on the destination database is rolled back.\n** The [sqlite3_backup] object is invalid\n** and may not be used following a call to sqlite3_backup_finish().\n**\n** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no\n** sqlite3_backup_step() errors occurred, regardless or whether or not\n** sqlite3_backup_step() completed.\n** ^If an out-of-memory condition or IO error occurred during any prior\n** sqlite3_backup_step() call on the same [sqlite3_backup] object, then\n** sqlite3_backup_finish() returns the corresponding [error code].\n**\n** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()\n** is not a permanent error and does not affect the return value of\n** sqlite3_backup_finish().\n**\n** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]\n** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>\n**\n** ^The sqlite3_backup_remaining() routine returns the number of pages still\n** to be backed up at the conclusion of the most recent sqlite3_backup_step().\n** ^The sqlite3_backup_pagecount() routine returns the total number of pages\n** in the source database at the conclusion of the most recent\n** sqlite3_backup_step().\n** ^(The values returned by these functions are only updated by\n** sqlite3_backup_step(). If the source database is modified in a way that\n** changes the size of the source database or the number of pages remaining,\n** those changes are not reflected in the output of sqlite3_backup_pagecount()\n** and sqlite3_backup_remaining() until after the next\n** sqlite3_backup_step().)^\n**\n** <b>Concurrent Usage of Database Handles</b>\n**\n** ^The source [database connection] may be used by the application for other\n** purposes while a backup operation is underway or being initialized.\n** ^If SQLite is compiled and configured to support threadsafe database\n** connections, then the source database connection may be used concurrently\n** from within other threads.\n**\n** However, the application must guarantee that the destination \n** [database connection] is not passed to any other API (by any thread) after \n** sqlite3_backup_init() is called and before the corresponding call to\n** sqlite3_backup_finish().  SQLite does not currently check to see\n** if the application incorrectly accesses the destination [database connection]\n** and so no error code is reported, but the operations may malfunction\n** nevertheless.  Use of the destination database connection while a\n** backup is in progress might also also cause a mutex deadlock.\n**\n** If running in [shared cache mode], the application must\n** guarantee that the shared cache used by the destination database\n** is not accessed while the backup is running. In practice this means\n** that the application must guarantee that the disk file being \n** backed up to is not accessed by any connection within the process,\n** not just the specific connection that was passed to sqlite3_backup_init().\n**\n** The [sqlite3_backup] object itself is partially threadsafe. Multiple \n** threads may safely make multiple concurrent calls to sqlite3_backup_step().\n** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()\n** APIs are not strictly speaking threadsafe. If they are invoked at the\n** same time as another thread is invoking sqlite3_backup_step() it is\n** possible that they return invalid values.\n*/\nSQLITE_API sqlite3_backup *sqlite3_backup_init(\n  sqlite3 *pDest,                        /* Destination database handle */\n  const char *zDestName,                 /* Destination database name */\n  sqlite3 *pSource,                      /* Source database handle */\n  const char *zSourceName                /* Source database name */\n);\nSQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);\nSQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);\nSQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);\nSQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);\n\n/*\n** CAPI3REF: Unlock Notification\n** METHOD: sqlite3\n**\n** ^When running in shared-cache mode, a database operation may fail with\n** an [SQLITE_LOCKED] error if the required locks on the shared-cache or\n** individual tables within the shared-cache cannot be obtained. See\n** [SQLite Shared-Cache Mode] for a description of shared-cache locking. \n** ^This API may be used to register a callback that SQLite will invoke \n** when the connection currently holding the required lock relinquishes it.\n** ^This API is only available if the library was compiled with the\n** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.\n**\n** See Also: [Using the SQLite Unlock Notification Feature].\n**\n** ^Shared-cache locks are released when a database connection concludes\n** its current transaction, either by committing it or rolling it back. \n**\n** ^When a connection (known as the blocked connection) fails to obtain a\n** shared-cache lock and SQLITE_LOCKED is returned to the caller, the\n** identity of the database connection (the blocking connection) that\n** has locked the required resource is stored internally. ^After an \n** application receives an SQLITE_LOCKED error, it may call the\n** sqlite3_unlock_notify() method with the blocked connection handle as \n** the first argument to register for a callback that will be invoked\n** when the blocking connections current transaction is concluded. ^The\n** callback is invoked from within the [sqlite3_step] or [sqlite3_close]\n** call that concludes the blocking connection's transaction.\n**\n** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,\n** there is a chance that the blocking connection will have already\n** concluded its transaction by the time sqlite3_unlock_notify() is invoked.\n** If this happens, then the specified callback is invoked immediately,\n** from within the call to sqlite3_unlock_notify().)^\n**\n** ^If the blocked connection is attempting to obtain a write-lock on a\n** shared-cache table, and more than one other connection currently holds\n** a read-lock on the same table, then SQLite arbitrarily selects one of \n** the other connections to use as the blocking connection.\n**\n** ^(There may be at most one unlock-notify callback registered by a \n** blocked connection. If sqlite3_unlock_notify() is called when the\n** blocked connection already has a registered unlock-notify callback,\n** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is\n** called with a NULL pointer as its second argument, then any existing\n** unlock-notify callback is canceled. ^The blocked connections \n** unlock-notify callback may also be canceled by closing the blocked\n** connection using [sqlite3_close()].\n**\n** The unlock-notify callback is not reentrant. If an application invokes\n** any sqlite3_xxx API functions from within an unlock-notify callback, a\n** crash or deadlock may be the result.\n**\n** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always\n** returns SQLITE_OK.\n**\n** <b>Callback Invocation Details</b>\n**\n** When an unlock-notify callback is registered, the application provides a \n** single void* pointer that is passed to the callback when it is invoked.\n** However, the signature of the callback function allows SQLite to pass\n** it an array of void* context pointers. The first argument passed to\n** an unlock-notify callback is a pointer to an array of void* pointers,\n** and the second is the number of entries in the array.\n**\n** When a blocking connection's transaction is concluded, there may be\n** more than one blocked connection that has registered for an unlock-notify\n** callback. ^If two or more such blocked connections have specified the\n** same callback function, then instead of invoking the callback function\n** multiple times, it is invoked once with the set of void* context pointers\n** specified by the blocked connections bundled together into an array.\n** This gives the application an opportunity to prioritize any actions \n** related to the set of unblocked database connections.\n**\n** <b>Deadlock Detection</b>\n**\n** Assuming that after registering for an unlock-notify callback a \n** database waits for the callback to be issued before taking any further\n** action (a reasonable assumption), then using this API may cause the\n** application to deadlock. For example, if connection X is waiting for\n** connection Y's transaction to be concluded, and similarly connection\n** Y is waiting on connection X's transaction, then neither connection\n** will proceed and the system may remain deadlocked indefinitely.\n**\n** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock\n** detection. ^If a given call to sqlite3_unlock_notify() would put the\n** system in a deadlocked state, then SQLITE_LOCKED is returned and no\n** unlock-notify callback is registered. The system is said to be in\n** a deadlocked state if connection A has registered for an unlock-notify\n** callback on the conclusion of connection B's transaction, and connection\n** B has itself registered for an unlock-notify callback when connection\n** A's transaction is concluded. ^Indirect deadlock is also detected, so\n** the system is also considered to be deadlocked if connection B has\n** registered for an unlock-notify callback on the conclusion of connection\n** C's transaction, where connection C is waiting on connection A. ^Any\n** number of levels of indirection are allowed.\n**\n** <b>The \"DROP TABLE\" Exception</b>\n**\n** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost \n** always appropriate to call sqlite3_unlock_notify(). There is however,\n** one exception. When executing a \"DROP TABLE\" or \"DROP INDEX\" statement,\n** SQLite checks if there are any currently executing SELECT statements\n** that belong to the same connection. If there are, SQLITE_LOCKED is\n** returned. In this case there is no \"blocking connection\", so invoking\n** sqlite3_unlock_notify() results in the unlock-notify callback being\n** invoked immediately. If the application then re-attempts the \"DROP TABLE\"\n** or \"DROP INDEX\" query, an infinite loop might be the result.\n**\n** One way around this problem is to check the extended error code returned\n** by an sqlite3_step() call. ^(If there is a blocking connection, then the\n** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in\n** the special \"DROP TABLE/INDEX\" case, the extended error code is just \n** SQLITE_LOCKED.)^\n*/\nSQLITE_API int sqlite3_unlock_notify(\n  sqlite3 *pBlocked,                          /* Waiting connection */\n  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */\n  void *pNotifyArg                            /* Argument to pass to xNotify */\n);\n\n\n/*\n** CAPI3REF: String Comparison\n**\n** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications\n** and extensions to compare the contents of two buffers containing UTF-8\n** strings in a case-independent fashion, using the same definition of \"case\n** independence\" that SQLite uses internally when comparing identifiers.\n*/\nSQLITE_API int sqlite3_stricmp(const char *, const char *);\nSQLITE_API int sqlite3_strnicmp(const char *, const char *, int);\n\n/*\n** CAPI3REF: String Globbing\n*\n** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if\n** string X matches the [GLOB] pattern P.\n** ^The definition of [GLOB] pattern matching used in\n** [sqlite3_strglob(P,X)] is the same as for the \"X GLOB P\" operator in the\n** SQL dialect understood by SQLite.  ^The [sqlite3_strglob(P,X)] function\n** is case sensitive.\n**\n** Note that this routine returns zero on a match and non-zero if the strings\n** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].\n**\n** See also: [sqlite3_strlike()].\n*/\nSQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);\n\n/*\n** CAPI3REF: String LIKE Matching\n*\n** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if\n** string X matches the [LIKE] pattern P with escape character E.\n** ^The definition of [LIKE] pattern matching used in\n** [sqlite3_strlike(P,X,E)] is the same as for the \"X LIKE P ESCAPE E\"\n** operator in the SQL dialect understood by SQLite.  ^For \"X LIKE P\" without\n** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.\n** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case\n** insensitive - equivalent upper and lower case ASCII characters match\n** one another.\n**\n** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though\n** only ASCII characters are case folded.\n**\n** Note that this routine returns zero on a match and non-zero if the strings\n** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].\n**\n** See also: [sqlite3_strglob()].\n*/\nSQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);\n\n/*\n** CAPI3REF: Error Logging Interface\n**\n** ^The [sqlite3_log()] interface writes a message into the [error log]\n** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].\n** ^If logging is enabled, the zFormat string and subsequent arguments are\n** used with [sqlite3_snprintf()] to generate the final output string.\n**\n** The sqlite3_log() interface is intended for use by extensions such as\n** virtual tables, collating functions, and SQL functions.  While there is\n** nothing to prevent an application from calling sqlite3_log(), doing so\n** is considered bad form.\n**\n** The zFormat string must not be NULL.\n**\n** To avoid deadlocks and other threading problems, the sqlite3_log() routine\n** will not use dynamically allocated memory.  The log message is stored in\n** a fixed-length buffer on the stack.  If the log message is longer than\n** a few hundred characters, it will be truncated to the length of the\n** buffer.\n*/\nSQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);\n\n/*\n** CAPI3REF: Write-Ahead Log Commit Hook\n** METHOD: sqlite3\n**\n** ^The [sqlite3_wal_hook()] function is used to register a callback that\n** is invoked each time data is committed to a database in wal mode.\n**\n** ^(The callback is invoked by SQLite after the commit has taken place and \n** the associated write-lock on the database released)^, so the implementation \n** may read, write or [checkpoint] the database as required.\n**\n** ^The first parameter passed to the callback function when it is invoked\n** is a copy of the third parameter passed to sqlite3_wal_hook() when\n** registering the callback. ^The second is a copy of the database handle.\n** ^The third parameter is the name of the database that was written to -\n** either \"main\" or the name of an [ATTACH]-ed database. ^The fourth parameter\n** is the number of pages currently in the write-ahead log file,\n** including those that were just committed.\n**\n** The callback function should normally return [SQLITE_OK].  ^If an error\n** code is returned, that error will propagate back up through the\n** SQLite code base to cause the statement that provoked the callback\n** to report an error, though the commit will have still occurred. If the\n** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value\n** that does not correspond to any valid SQLite error code, the results\n** are undefined.\n**\n** A single database handle may have at most a single write-ahead log callback \n** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any\n** previously registered write-ahead log callback. ^Note that the\n** [sqlite3_wal_autocheckpoint()] interface and the\n** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will\n** overwrite any prior [sqlite3_wal_hook()] settings.\n*/\nSQLITE_API void *sqlite3_wal_hook(\n  sqlite3*, \n  int(*)(void *,sqlite3*,const char*,int),\n  void*\n);\n\n/*\n** CAPI3REF: Configure an auto-checkpoint\n** METHOD: sqlite3\n**\n** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around\n** [sqlite3_wal_hook()] that causes any database on [database connection] D\n** to automatically [checkpoint]\n** after committing a transaction if there are N or\n** more frames in the [write-ahead log] file.  ^Passing zero or \n** a negative value as the nFrame parameter disables automatic\n** checkpoints entirely.\n**\n** ^The callback registered by this function replaces any existing callback\n** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback\n** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism\n** configured by this function.\n**\n** ^The [wal_autocheckpoint pragma] can be used to invoke this interface\n** from SQL.\n**\n** ^Checkpoints initiated by this mechanism are\n** [sqlite3_wal_checkpoint_v2|PASSIVE].\n**\n** ^Every new [database connection] defaults to having the auto-checkpoint\n** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]\n** pages.  The use of this interface\n** is only necessary if the default setting is found to be suboptimal\n** for a particular application.\n*/\nSQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);\n\n/*\n** CAPI3REF: Checkpoint a database\n** METHOD: sqlite3\n**\n** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to\n** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^\n**\n** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the \n** [write-ahead log] for database X on [database connection] D to be\n** transferred into the database file and for the write-ahead log to\n** be reset.  See the [checkpointing] documentation for addition\n** information.\n**\n** This interface used to be the only way to cause a checkpoint to\n** occur.  But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]\n** interface was added.  This interface is retained for backwards\n** compatibility and as a convenience for applications that need to manually\n** start a callback but which do not need the full power (and corresponding\n** complication) of [sqlite3_wal_checkpoint_v2()].\n*/\nSQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);\n\n/*\n** CAPI3REF: Checkpoint a database\n** METHOD: sqlite3\n**\n** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint\n** operation on database X of [database connection] D in mode M.  Status\n** information is written back into integers pointed to by L and C.)^\n** ^(The M parameter must be a valid [checkpoint mode]:)^\n**\n** <dl>\n** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>\n**   ^Checkpoint as many frames as possible without waiting for any database \n**   readers or writers to finish, then sync the database file if all frames \n**   in the log were checkpointed. ^The [busy-handler callback]\n**   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.  \n**   ^On the other hand, passive mode might leave the checkpoint unfinished\n**   if there are concurrent readers or writers.\n**\n** <dt>SQLITE_CHECKPOINT_FULL<dd>\n**   ^This mode blocks (it invokes the\n**   [sqlite3_busy_handler|busy-handler callback]) until there is no\n**   database writer and all readers are reading from the most recent database\n**   snapshot. ^It then checkpoints all frames in the log file and syncs the\n**   database file. ^This mode blocks new database writers while it is pending,\n**   but new database readers are allowed to continue unimpeded.\n**\n** <dt>SQLITE_CHECKPOINT_RESTART<dd>\n**   ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition\n**   that after checkpointing the log file it blocks (calls the \n**   [busy-handler callback])\n**   until all readers are reading from the database file only. ^This ensures \n**   that the next writer will restart the log file from the beginning.\n**   ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new\n**   database writer attempts while it is pending, but does not impede readers.\n**\n** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>\n**   ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the\n**   addition that it also truncates the log file to zero bytes just prior\n**   to a successful return.\n** </dl>\n**\n** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in\n** the log file or to -1 if the checkpoint could not run because\n** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not\n** NULL,then *pnCkpt is set to the total number of checkpointed frames in the\n** log file (including any that were already checkpointed before the function\n** was called) or to -1 if the checkpoint could not run due to an error or\n** because the database is not in WAL mode. ^Note that upon successful\n** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been\n** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.\n**\n** ^All calls obtain an exclusive \"checkpoint\" lock on the database file. ^If\n** any other process is running a checkpoint operation at the same time, the \n** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a \n** busy-handler configured, it will not be invoked in this case.\n**\n** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the \n** exclusive \"writer\" lock on the database file. ^If the writer lock cannot be\n** obtained immediately, and a busy-handler is configured, it is invoked and\n** the writer lock retried until either the busy-handler returns 0 or the lock\n** is successfully obtained. ^The busy-handler is also invoked while waiting for\n** database readers as described above. ^If the busy-handler returns 0 before\n** the writer lock is obtained or while waiting for database readers, the\n** checkpoint operation proceeds from that point in the same way as \n** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible \n** without blocking any further. ^SQLITE_BUSY is returned in this case.\n**\n** ^If parameter zDb is NULL or points to a zero length string, then the\n** specified operation is attempted on all WAL databases [attached] to \n** [database connection] db.  In this case the\n** values written to output parameters *pnLog and *pnCkpt are undefined. ^If \n** an SQLITE_BUSY error is encountered when processing one or more of the \n** attached WAL databases, the operation is still attempted on any remaining \n** attached databases and SQLITE_BUSY is returned at the end. ^If any other \n** error occurs while processing an attached database, processing is abandoned \n** and the error code is returned to the caller immediately. ^If no error \n** (SQLITE_BUSY or otherwise) is encountered while processing the attached \n** databases, SQLITE_OK is returned.\n**\n** ^If database zDb is the name of an attached database that is not in WAL\n** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If\n** zDb is not NULL (or a zero length string) and is not the name of any\n** attached database, SQLITE_ERROR is returned to the caller.\n**\n** ^Unless it returns SQLITE_MISUSE,\n** the sqlite3_wal_checkpoint_v2() interface\n** sets the error information that is queried by\n** [sqlite3_errcode()] and [sqlite3_errmsg()].\n**\n** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface\n** from SQL.\n*/\nSQLITE_API int sqlite3_wal_checkpoint_v2(\n  sqlite3 *db,                    /* Database handle */\n  const char *zDb,                /* Name of attached database (or NULL) */\n  int eMode,                      /* SQLITE_CHECKPOINT_* value */\n  int *pnLog,                     /* OUT: Size of WAL log in frames */\n  int *pnCkpt                     /* OUT: Total number of frames checkpointed */\n);\n\n/*\n** CAPI3REF: Checkpoint Mode Values\n** KEYWORDS: {checkpoint mode}\n**\n** These constants define all valid values for the \"checkpoint mode\" passed\n** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.\n** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the\n** meaning of each of these checkpoint modes.\n*/\n#define SQLITE_CHECKPOINT_PASSIVE  0  /* Do as much as possible w/o blocking */\n#define SQLITE_CHECKPOINT_FULL     1  /* Wait for writers, then checkpoint */\n#define SQLITE_CHECKPOINT_RESTART  2  /* Like FULL but wait for for readers */\n#define SQLITE_CHECKPOINT_TRUNCATE 3  /* Like RESTART but also truncate WAL */\n\n/*\n** CAPI3REF: Virtual Table Interface Configuration\n**\n** This function may be called by either the [xConnect] or [xCreate] method\n** of a [virtual table] implementation to configure\n** various facets of the virtual table interface.\n**\n** If this interface is invoked outside the context of an xConnect or\n** xCreate virtual table method then the behavior is undefined.\n**\n** In the call sqlite3_vtab_config(D,C,...) the D parameter is the\n** [database connection] in which the virtual table is being created and\n** which is passed in as the first argument to the [xConnect] or [xCreate]\n** method that is invoking sqlite3_vtab_config().  The C parameter is one\n** of the [virtual table configuration options].  The presence and meaning\n** of parameters after C depend on which [virtual table configuration option]\n** is used.\n*/\nSQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);\n\n/*\n** CAPI3REF: Virtual Table Configuration Options\n** KEYWORDS: {virtual table configuration options} \n** KEYWORDS: {virtual table configuration option}\n**\n** These macros define the various options to the\n** [sqlite3_vtab_config()] interface that [virtual table] implementations\n** can use to customize and optimize their behavior.\n**\n** <dl>\n** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]]\n** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT</dt>\n** <dd>Calls of the form\n** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,\n** where X is an integer.  If X is zero, then the [virtual table] whose\n** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not\n** support constraints.  In this configuration (which is the default) if\n** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire\n** statement is rolled back as if [ON CONFLICT | OR ABORT] had been\n** specified as part of the users SQL statement, regardless of the actual\n** ON CONFLICT mode specified.\n**\n** If X is non-zero, then the virtual table implementation guarantees\n** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before\n** any modifications to internal or persistent data structures have been made.\n** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite \n** is able to roll back a statement or database transaction, and abandon\n** or continue processing the current SQL statement as appropriate. \n** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns\n** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode\n** had been ABORT.\n**\n** Virtual table implementations that are required to handle OR REPLACE\n** must do so within the [xUpdate] method. If a call to the \n** [sqlite3_vtab_on_conflict()] function indicates that the current ON \n** CONFLICT policy is REPLACE, the virtual table implementation should \n** silently replace the appropriate rows within the xUpdate callback and\n** return SQLITE_OK. Or, if this is not possible, it may return\n** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT \n** constraint handling.\n** </dd>\n**\n** [[SQLITE_VTAB_DIRECTONLY]]<dt>SQLITE_VTAB_DIRECTONLY</dt>\n** <dd>Calls of the form\n** [sqlite3_vtab_config](db,SQLITE_VTAB_DIRECTONLY) from within the\n** the [xConnect] or [xCreate] methods of a [virtual table] implmentation\n** prohibits that virtual table from being used from within triggers and\n** views.\n** </dd>\n**\n** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>\n** <dd>Calls of the form\n** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the\n** the [xConnect] or [xCreate] methods of a [virtual table] implmentation\n** identify that virtual table as being safe to use from within triggers\n** and views.  Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the\n** virtual table can do no serious harm even if it is controlled by a\n** malicious hacker.  Developers should avoid setting the SQLITE_VTAB_INNOCUOUS\n** flag unless absolutely necessary.\n** </dd>\n** </dl>\n*/\n#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1\n#define SQLITE_VTAB_INNOCUOUS          2\n#define SQLITE_VTAB_DIRECTONLY         3\n\n/*\n** CAPI3REF: Determine The Virtual Table Conflict Policy\n**\n** This function may only be called from within a call to the [xUpdate] method\n** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The\n** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],\n** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode\n** of the SQL statement that triggered the call to the [xUpdate] method of the\n** [virtual table].\n*/\nSQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);\n\n/*\n** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE\n**\n** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]\n** method of a [virtual table], then it returns true if and only if the\n** column is being fetched as part of an UPDATE operation during which the\n** column value will not change.  Applications might use this to substitute\n** a return value that is less expensive to compute and that the corresponding\n** [xUpdate] method understands as a \"no-change\" value.\n**\n** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that\n** the column is not changed by the UPDATE statement, then the xColumn\n** method can optionally return without setting a result, without calling\n** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].\n** In that case, [sqlite3_value_nochange(X)] will return true for the\n** same column in the [xUpdate] method.\n*/\nSQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);\n\n/*\n** CAPI3REF: Determine The Collation For a Virtual Table Constraint\n**\n** This function may only be called from within a call to the [xBestIndex]\n** method of a [virtual table]. \n**\n** The first argument must be the sqlite3_index_info object that is the\n** first parameter to the xBestIndex() method. The second argument must be\n** an index into the aConstraint[] array belonging to the sqlite3_index_info\n** structure passed to xBestIndex. This function returns a pointer to a buffer \n** containing the name of the collation sequence for the corresponding\n** constraint.\n*/\nSQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);\n\n/*\n** CAPI3REF: Conflict resolution modes\n** KEYWORDS: {conflict resolution mode}\n**\n** These constants are returned by [sqlite3_vtab_on_conflict()] to\n** inform a [virtual table] implementation what the [ON CONFLICT] mode\n** is for the SQL statement being evaluated.\n**\n** Note that the [SQLITE_IGNORE] constant is also used as a potential\n** return value from the [sqlite3_set_authorizer()] callback and that\n** [SQLITE_ABORT] is also a [result code].\n*/\n#define SQLITE_ROLLBACK 1\n/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */\n#define SQLITE_FAIL     3\n/* #define SQLITE_ABORT 4  // Also an error code */\n#define SQLITE_REPLACE  5\n\n/*\n** CAPI3REF: Prepared Statement Scan Status Opcodes\n** KEYWORDS: {scanstatus options}\n**\n** The following constants can be used for the T parameter to the\n** [sqlite3_stmt_scanstatus(S,X,T,V)] interface.  Each constant designates a\n** different metric for sqlite3_stmt_scanstatus() to return.\n**\n** When the value returned to V is a string, space to hold that string is\n** managed by the prepared statement S and will be automatically freed when\n** S is finalized.\n**\n** <dl>\n** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>\n** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be\n** set to the total number of times that the X-th loop has run.</dd>\n**\n** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>\n** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be set\n** to the total number of rows examined by all iterations of the X-th loop.</dd>\n**\n** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>\n** <dd>^The \"double\" variable pointed to by the V parameter will be set to the\n** query planner's estimate for the average number of rows output from each\n** iteration of the X-th loop.  If the query planner's estimates was accurate,\n** then this value will approximate the quotient NVISIT/NLOOP and the\n** product of this value for all prior loops with the same SELECTID will\n** be the NLOOP value for the current loop.\n**\n** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>\n** <dd>^The \"const char *\" variable pointed to by the V parameter will be set\n** to a zero-terminated UTF-8 string containing the name of the index or table\n** used for the X-th loop.\n**\n** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>\n** <dd>^The \"const char *\" variable pointed to by the V parameter will be set\n** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]\n** description for the X-th loop.\n**\n** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>\n** <dd>^The \"int\" variable pointed to by the V parameter will be set to the\n** \"select-id\" for the X-th loop.  The select-id identifies which query or\n** subquery the loop is part of.  The main query has a select-id of zero.\n** The select-id is the same value as is output in the first column\n** of an [EXPLAIN QUERY PLAN] query.\n** </dl>\n*/\n#define SQLITE_SCANSTAT_NLOOP    0\n#define SQLITE_SCANSTAT_NVISIT   1\n#define SQLITE_SCANSTAT_EST      2\n#define SQLITE_SCANSTAT_NAME     3\n#define SQLITE_SCANSTAT_EXPLAIN  4\n#define SQLITE_SCANSTAT_SELECTID 5\n\n/*\n** CAPI3REF: Prepared Statement Scan Status\n** METHOD: sqlite3_stmt\n**\n** This interface returns information about the predicted and measured\n** performance for pStmt.  Advanced applications can use this\n** interface to compare the predicted and the measured performance and\n** issue warnings and/or rerun [ANALYZE] if discrepancies are found.\n**\n** Since this interface is expected to be rarely used, it is only\n** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]\n** compile-time option.\n**\n** The \"iScanStatusOp\" parameter determines which status information to return.\n** The \"iScanStatusOp\" must be one of the [scanstatus options] or the behavior\n** of this interface is undefined.\n** ^The requested measurement is written into a variable pointed to by\n** the \"pOut\" parameter.\n** Parameter \"idx\" identifies the specific loop to retrieve statistics for.\n** Loops are numbered starting from zero. ^If idx is out of range - less than\n** zero or greater than or equal to the total number of loops used to implement\n** the statement - a non-zero value is returned and the variable that pOut\n** points to is unchanged.\n**\n** ^Statistics might not be available for all loops in all statements. ^In cases\n** where there exist loops with no available statistics, this function behaves\n** as if the loop did not exist - it returns non-zero and leave the variable\n** that pOut points to unchanged.\n**\n** See also: [sqlite3_stmt_scanstatus_reset()]\n*/\nSQLITE_API int sqlite3_stmt_scanstatus(\n  sqlite3_stmt *pStmt,      /* Prepared statement for which info desired */\n  int idx,                  /* Index of loop to report on */\n  int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */\n  void *pOut                /* Result written here */\n);     \n\n/*\n** CAPI3REF: Zero Scan-Status Counters\n** METHOD: sqlite3_stmt\n**\n** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.\n**\n** This API is only available if the library is built with pre-processor\n** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.\n*/\nSQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Flush caches to disk mid-transaction\n**\n** ^If a write-transaction is open on [database connection] D when the\n** [sqlite3_db_cacheflush(D)] interface invoked, any dirty\n** pages in the pager-cache that are not currently in use are written out \n** to disk. A dirty page may be in use if a database cursor created by an\n** active SQL statement is reading from it, or if it is page 1 of a database\n** file (page 1 is always \"in use\").  ^The [sqlite3_db_cacheflush(D)]\n** interface flushes caches for all schemas - \"main\", \"temp\", and\n** any [attached] databases.\n**\n** ^If this function needs to obtain extra database locks before dirty pages \n** can be flushed to disk, it does so. ^If those locks cannot be obtained \n** immediately and there is a busy-handler callback configured, it is invoked\n** in the usual manner. ^If the required lock still cannot be obtained, then\n** the database is skipped and an attempt made to flush any dirty pages\n** belonging to the next (if any) database. ^If any databases are skipped\n** because locks cannot be obtained, but no other error occurs, this\n** function returns SQLITE_BUSY.\n**\n** ^If any other error occurs while flushing dirty pages to disk (for\n** example an IO error or out-of-memory condition), then processing is\n** abandoned and an SQLite [error code] is returned to the caller immediately.\n**\n** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.\n**\n** ^This function does not set the database handle error code or message\n** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.\n*/\nSQLITE_API int sqlite3_db_cacheflush(sqlite3*);\n\n/*\n** CAPI3REF: The pre-update hook.\n**\n** ^These interfaces are only available if SQLite is compiled using the\n** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.\n**\n** ^The [sqlite3_preupdate_hook()] interface registers a callback function\n** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation\n** on a database table.\n** ^At most one preupdate hook may be registered at a time on a single\n** [database connection]; each call to [sqlite3_preupdate_hook()] overrides\n** the previous setting.\n** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]\n** with a NULL pointer as the second parameter.\n** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as\n** the first parameter to callbacks.\n**\n** ^The preupdate hook only fires for changes to real database tables; the\n** preupdate hook is not invoked for changes to [virtual tables] or to\n** system tables like sqlite_master or sqlite_stat1.\n**\n** ^The second parameter to the preupdate callback is a pointer to\n** the [database connection] that registered the preupdate hook.\n** ^The third parameter to the preupdate callback is one of the constants\n** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the\n** kind of update operation that is about to occur.\n** ^(The fourth parameter to the preupdate callback is the name of the\n** database within the database connection that is being modified.  This\n** will be \"main\" for the main database or \"temp\" for TEMP tables or \n** the name given after the AS keyword in the [ATTACH] statement for attached\n** databases.)^\n** ^The fifth parameter to the preupdate callback is the name of the\n** table that is being modified.\n**\n** For an UPDATE or DELETE operation on a [rowid table], the sixth\n** parameter passed to the preupdate callback is the initial [rowid] of the \n** row being modified or deleted. For an INSERT operation on a rowid table,\n** or any operation on a WITHOUT ROWID table, the value of the sixth \n** parameter is undefined. For an INSERT or UPDATE on a rowid table the\n** seventh parameter is the final rowid value of the row being inserted\n** or updated. The value of the seventh parameter passed to the callback\n** function is not defined for operations on WITHOUT ROWID tables, or for\n** INSERT operations on rowid tables.\n**\n** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],\n** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces\n** provide additional information about a preupdate event. These routines\n** may only be called from within a preupdate callback.  Invoking any of\n** these routines from outside of a preupdate callback or with a\n** [database connection] pointer that is different from the one supplied\n** to the preupdate callback results in undefined and probably undesirable\n** behavior.\n**\n** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns\n** in the row that is being inserted, updated, or deleted.\n**\n** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to\n** a [protected sqlite3_value] that contains the value of the Nth column of\n** the table row before it is updated.  The N parameter must be between 0\n** and one less than the number of columns or the behavior will be\n** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE\n** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the\n** behavior is undefined.  The [sqlite3_value] that P points to\n** will be destroyed when the preupdate callback returns.\n**\n** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to\n** a [protected sqlite3_value] that contains the value of the Nth column of\n** the table row after it is updated.  The N parameter must be between 0\n** and one less than the number of columns or the behavior will be\n** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE\n** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the\n** behavior is undefined.  The [sqlite3_value] that P points to\n** will be destroyed when the preupdate callback returns.\n**\n** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate\n** callback was invoked as a result of a direct insert, update, or delete\n** operation; or 1 for inserts, updates, or deletes invoked by top-level \n** triggers; or 2 for changes resulting from triggers called by top-level\n** triggers; and so forth.\n**\n** See also:  [sqlite3_update_hook()]\n*/\n#if defined(SQLITE_ENABLE_PREUPDATE_HOOK)\nSQLITE_API void *sqlite3_preupdate_hook(\n  sqlite3 *db,\n  void(*xPreUpdate)(\n    void *pCtx,                   /* Copy of third arg to preupdate_hook() */\n    sqlite3 *db,                  /* Database handle */\n    int op,                       /* SQLITE_UPDATE, DELETE or INSERT */\n    char const *zDb,              /* Database name */\n    char const *zName,            /* Table name */\n    sqlite3_int64 iKey1,          /* Rowid of row about to be deleted/updated */\n    sqlite3_int64 iKey2           /* New rowid value (for a rowid UPDATE) */\n  ),\n  void*\n);\nSQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);\nSQLITE_API int sqlite3_preupdate_count(sqlite3 *);\nSQLITE_API int sqlite3_preupdate_depth(sqlite3 *);\nSQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);\n#endif\n\n/*\n** CAPI3REF: Low-level system error code\n**\n** ^Attempt to return the underlying operating system error code or error\n** number that caused the most recent I/O error or failure to open a file.\n** The return value is OS-dependent.  For example, on unix systems, after\n** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be\n** called to get back the underlying \"errno\" that caused the problem, such\n** as ENOSPC, EAUTH, EISDIR, and so forth.  \n*/\nSQLITE_API int sqlite3_system_errno(sqlite3*);\n\n/*\n** CAPI3REF: Database Snapshot\n** KEYWORDS: {snapshot} {sqlite3_snapshot}\n**\n** An instance of the snapshot object records the state of a [WAL mode]\n** database for some specific point in history.\n**\n** In [WAL mode], multiple [database connections] that are open on the\n** same database file can each be reading a different historical version\n** of the database file.  When a [database connection] begins a read\n** transaction, that connection sees an unchanging copy of the database\n** as it existed for the point in time when the transaction first started.\n** Subsequent changes to the database from other connections are not seen\n** by the reader until a new read transaction is started.\n**\n** The sqlite3_snapshot object records state information about an historical\n** version of the database file so that it is possible to later open a new read\n** transaction that sees that historical version of the database rather than\n** the most recent version.\n*/\ntypedef struct sqlite3_snapshot {\n  unsigned char hidden[48];\n} sqlite3_snapshot;\n\n/*\n** CAPI3REF: Record A Database Snapshot\n** CONSTRUCTOR: sqlite3_snapshot\n**\n** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a\n** new [sqlite3_snapshot] object that records the current state of\n** schema S in database connection D.  ^On success, the\n** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly\n** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.\n** If there is not already a read-transaction open on schema S when\n** this function is called, one is opened automatically. \n**\n** The following must be true for this function to succeed. If any of\n** the following statements are false when sqlite3_snapshot_get() is\n** called, SQLITE_ERROR is returned. The final value of *P is undefined\n** in this case. \n**\n** <ul>\n**   <li> The database handle must not be in [autocommit mode].\n**\n**   <li> Schema S of [database connection] D must be a [WAL mode] database.\n**\n**   <li> There must not be a write transaction open on schema S of database\n**        connection D.\n**\n**   <li> One or more transactions must have been written to the current wal\n**        file since it was created on disk (by any connection). This means\n**        that a snapshot cannot be taken on a wal mode database with no wal \n**        file immediately after it is first opened. At least one transaction\n**        must be written to it first.\n** </ul>\n**\n** This function may also return SQLITE_NOMEM.  If it is called with the\n** database handle in autocommit mode but fails for some other reason, \n** whether or not a read transaction is opened on schema S is undefined.\n**\n** The [sqlite3_snapshot] object returned from a successful call to\n** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]\n** to avoid a memory leak.\n**\n** The [sqlite3_snapshot_get()] interface is only available when the\n** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.\n*/\nSQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(\n  sqlite3 *db,\n  const char *zSchema,\n  sqlite3_snapshot **ppSnapshot\n);\n\n/*\n** CAPI3REF: Start a read transaction on an historical snapshot\n** METHOD: sqlite3_snapshot\n**\n** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read \n** transaction or upgrades an existing one for schema S of \n** [database connection] D such that the read transaction refers to \n** historical [snapshot] P, rather than the most recent change to the \n** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK \n** on success or an appropriate [error code] if it fails.\n**\n** ^In order to succeed, the database connection must not be in \n** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there\n** is already a read transaction open on schema S, then the database handle\n** must have no active statements (SELECT statements that have been passed\n** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()). \n** SQLITE_ERROR is returned if either of these conditions is violated, or\n** if schema S does not exist, or if the snapshot object is invalid.\n**\n** ^A call to sqlite3_snapshot_open() will fail to open if the specified\n** snapshot has been overwritten by a [checkpoint]. In this case \n** SQLITE_ERROR_SNAPSHOT is returned.\n**\n** If there is already a read transaction open when this function is \n** invoked, then the same read transaction remains open (on the same\n** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT\n** is returned. If another error code - for example SQLITE_PROTOCOL or an\n** SQLITE_IOERR error code - is returned, then the final state of the\n** read transaction is undefined. If SQLITE_OK is returned, then the \n** read transaction is now open on database snapshot P.\n**\n** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the\n** database connection D does not know that the database file for\n** schema S is in [WAL mode].  A database connection might not know\n** that the database file is in [WAL mode] if there has been no prior\n** I/O on that database connection, or if the database entered [WAL mode] \n** after the most recent I/O on the database connection.)^\n** (Hint: Run \"[PRAGMA application_id]\" against a newly opened\n** database connection in order to make it ready to use snapshots.)\n**\n** The [sqlite3_snapshot_open()] interface is only available when the\n** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.\n*/\nSQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(\n  sqlite3 *db,\n  const char *zSchema,\n  sqlite3_snapshot *pSnapshot\n);\n\n/*\n** CAPI3REF: Destroy a snapshot\n** DESTRUCTOR: sqlite3_snapshot\n**\n** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.\n** The application must eventually free every [sqlite3_snapshot] object\n** using this routine to avoid a memory leak.\n**\n** The [sqlite3_snapshot_free()] interface is only available when the\n** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.\n*/\nSQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);\n\n/*\n** CAPI3REF: Compare the ages of two snapshot handles.\n** METHOD: sqlite3_snapshot\n**\n** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages\n** of two valid snapshot handles. \n**\n** If the two snapshot handles are not associated with the same database \n** file, the result of the comparison is undefined. \n**\n** Additionally, the result of the comparison is only valid if both of the\n** snapshot handles were obtained by calling sqlite3_snapshot_get() since the\n** last time the wal file was deleted. The wal file is deleted when the\n** database is changed back to rollback mode or when the number of database\n** clients drops to zero. If either snapshot handle was obtained before the \n** wal file was last deleted, the value returned by this function \n** is undefined.\n**\n** Otherwise, this API returns a negative value if P1 refers to an older\n** snapshot than P2, zero if the two handles refer to the same database\n** snapshot, and a positive value if P1 is a newer snapshot than P2.\n**\n** This interface is only available if SQLite is compiled with the\n** [SQLITE_ENABLE_SNAPSHOT] option.\n*/\nSQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(\n  sqlite3_snapshot *p1,\n  sqlite3_snapshot *p2\n);\n\n/*\n** CAPI3REF: Recover snapshots from a wal file\n** METHOD: sqlite3_snapshot\n**\n** If a [WAL file] remains on disk after all database connections close\n** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control]\n** or because the last process to have the database opened exited without\n** calling [sqlite3_close()]) and a new connection is subsequently opened\n** on that database and [WAL file], the [sqlite3_snapshot_open()] interface\n** will only be able to open the last transaction added to the WAL file\n** even though the WAL file contains other valid transactions.\n**\n** This function attempts to scan the WAL file associated with database zDb\n** of database handle db and make all valid snapshots available to\n** sqlite3_snapshot_open(). It is an error if there is already a read\n** transaction open on the database, or if the database is not a WAL mode\n** database.\n**\n** SQLITE_OK is returned if successful, or an SQLite error code otherwise.\n**\n** This interface is only available if SQLite is compiled with the\n** [SQLITE_ENABLE_SNAPSHOT] option.\n*/\nSQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);\n\n/*\n** CAPI3REF: Serialize a database\n**\n** The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory\n** that is a serialization of the S database on [database connection] D.\n** If P is not a NULL pointer, then the size of the database in bytes\n** is written into *P.\n**\n** For an ordinary on-disk database file, the serialization is just a\n** copy of the disk file.  For an in-memory database or a \"TEMP\" database,\n** the serialization is the same sequence of bytes which would be written\n** to disk if that database where backed up to disk.\n**\n** The usual case is that sqlite3_serialize() copies the serialization of\n** the database into memory obtained from [sqlite3_malloc64()] and returns\n** a pointer to that memory.  The caller is responsible for freeing the\n** returned value to avoid a memory leak.  However, if the F argument\n** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations\n** are made, and the sqlite3_serialize() function will return a pointer\n** to the contiguous memory representation of the database that SQLite\n** is currently using for that database, or NULL if the no such contiguous\n** memory representation of the database exists.  A contiguous memory\n** representation of the database will usually only exist if there has\n** been a prior call to [sqlite3_deserialize(D,S,...)] with the same\n** values of D and S.\n** The size of the database is written into *P even if the \n** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy\n** of the database exists.\n**\n** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the\n** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory\n** allocation error occurs.\n**\n** This interface is only available if SQLite is compiled with the\n** [SQLITE_ENABLE_DESERIALIZE] option.\n*/\nSQLITE_API unsigned char *sqlite3_serialize(\n  sqlite3 *db,           /* The database connection */\n  const char *zSchema,   /* Which DB to serialize. ex: \"main\", \"temp\", ... */\n  sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */\n  unsigned int mFlags    /* Zero or more SQLITE_SERIALIZE_* flags */\n);\n\n/*\n** CAPI3REF: Flags for sqlite3_serialize\n**\n** Zero or more of the following constants can be OR-ed together for\n** the F argument to [sqlite3_serialize(D,S,P,F)].\n**\n** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return\n** a pointer to contiguous in-memory database that it is currently using,\n** without making a copy of the database.  If SQLite is not currently using\n** a contiguous in-memory database, then this option causes\n** [sqlite3_serialize()] to return a NULL pointer.  SQLite will only be\n** using a contiguous in-memory database if it has been initialized by a\n** prior call to [sqlite3_deserialize()].\n*/\n#define SQLITE_SERIALIZE_NOCOPY 0x001   /* Do no memory allocations */\n\n/*\n** CAPI3REF: Deserialize a database\n**\n** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the \n** [database connection] D to disconnect from database S and then\n** reopen S as an in-memory database based on the serialization contained\n** in P.  The serialized database P is N bytes in size.  M is the size of\n** the buffer P, which might be larger than N.  If M is larger than N, and\n** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is\n** permitted to add content to the in-memory database as long as the total\n** size does not exceed M bytes.\n**\n** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will\n** invoke sqlite3_free() on the serialization buffer when the database\n** connection closes.  If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then\n** SQLite will try to increase the buffer size using sqlite3_realloc64()\n** if writes on the database cause it to grow larger than M bytes.\n**\n** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the\n** database is currently in a read transaction or is involved in a backup\n** operation.\n**\n** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the \n** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then\n** [sqlite3_free()] is invoked on argument P prior to returning.\n**\n** This interface is only available if SQLite is compiled with the\n** [SQLITE_ENABLE_DESERIALIZE] option.\n*/\nSQLITE_API int sqlite3_deserialize(\n  sqlite3 *db,            /* The database connection */\n  const char *zSchema,    /* Which DB to reopen with the deserialization */\n  unsigned char *pData,   /* The serialized database content */\n  sqlite3_int64 szDb,     /* Number bytes in the deserialization */\n  sqlite3_int64 szBuf,    /* Total size of buffer pData[] */\n  unsigned mFlags         /* Zero or more SQLITE_DESERIALIZE_* flags */\n);\n\n/*\n** CAPI3REF: Flags for sqlite3_deserialize()\n**\n** The following are allowed values for 6th argument (the F argument) to\n** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.\n**\n** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization\n** in the P argument is held in memory obtained from [sqlite3_malloc64()]\n** and that SQLite should take ownership of this memory and automatically\n** free it when it has finished using it.  Without this flag, the caller\n** is responsible for freeing any dynamically allocated memory.\n**\n** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to\n** grow the size of the database using calls to [sqlite3_realloc64()].  This\n** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.\n** Without this flag, the deserialized database cannot increase in size beyond\n** the number of bytes specified by the M parameter.\n**\n** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database\n** should be treated as read-only.\n*/\n#define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */\n#define SQLITE_DESERIALIZE_RESIZEABLE  2 /* Resize using sqlite3_realloc64() */\n#define SQLITE_DESERIALIZE_READONLY    4 /* Database is read-only */\n\n/*\n** Undo the hack that converts floating point types to integer for\n** builds on processors without floating point support.\n*/\n#ifdef SQLITE_OMIT_FLOATING_POINT\n# undef double\n#endif\n\n#if 0\n}  /* End of the 'extern \"C\"' block */\n#endif\n#endif /* SQLITE3_H */\n\n/******** Begin file sqlite3rtree.h *********/\n/*\n** 2010 August 30\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n*/\n\n#ifndef _SQLITE3RTREE_H_\n#define _SQLITE3RTREE_H_\n\n\n#if 0\nextern \"C\" {\n#endif\n\ntypedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;\ntypedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;\n\n/* The double-precision datatype used by RTree depends on the\n** SQLITE_RTREE_INT_ONLY compile-time option.\n*/\n#ifdef SQLITE_RTREE_INT_ONLY\n  typedef sqlite3_int64 sqlite3_rtree_dbl;\n#else\n  typedef double sqlite3_rtree_dbl;\n#endif\n\n/*\n** Register a geometry callback named zGeom that can be used as part of an\n** R-Tree geometry query as follows:\n**\n**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)\n*/\nSQLITE_API int sqlite3_rtree_geometry_callback(\n  sqlite3 *db,\n  const char *zGeom,\n  int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),\n  void *pContext\n);\n\n\n/*\n** A pointer to a structure of the following type is passed as the first\n** argument to callbacks registered using rtree_geometry_callback().\n*/\nstruct sqlite3_rtree_geometry {\n  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */\n  int nParam;                     /* Size of array aParam[] */\n  sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */\n  void *pUser;                    /* Callback implementation user data */\n  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */\n};\n\n/*\n** Register a 2nd-generation geometry callback named zScore that can be \n** used as part of an R-Tree geometry query as follows:\n**\n**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)\n*/\nSQLITE_API int sqlite3_rtree_query_callback(\n  sqlite3 *db,\n  const char *zQueryFunc,\n  int (*xQueryFunc)(sqlite3_rtree_query_info*),\n  void *pContext,\n  void (*xDestructor)(void*)\n);\n\n\n/*\n** A pointer to a structure of the following type is passed as the \n** argument to scored geometry callback registered using\n** sqlite3_rtree_query_callback().\n**\n** Note that the first 5 fields of this structure are identical to\n** sqlite3_rtree_geometry.  This structure is a subclass of\n** sqlite3_rtree_geometry.\n*/\nstruct sqlite3_rtree_query_info {\n  void *pContext;                   /* pContext from when function registered */\n  int nParam;                       /* Number of function parameters */\n  sqlite3_rtree_dbl *aParam;        /* value of function parameters */\n  void *pUser;                      /* callback can use this, if desired */\n  void (*xDelUser)(void*);          /* function to free pUser */\n  sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */\n  unsigned int *anQueue;            /* Number of pending entries in the queue */\n  int nCoord;                       /* Number of coordinates */\n  int iLevel;                       /* Level of current node or entry */\n  int mxLevel;                      /* The largest iLevel value in the tree */\n  sqlite3_int64 iRowid;             /* Rowid for current entry */\n  sqlite3_rtree_dbl rParentScore;   /* Score of parent node */\n  int eParentWithin;                /* Visibility of parent node */\n  int eWithin;                      /* OUT: Visibility */\n  sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */\n  /* The following fields are only available in 3.8.11 and later */\n  sqlite3_value **apSqlParam;       /* Original SQL values of parameters */\n};\n\n/*\n** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.\n*/\n#define NOT_WITHIN       0   /* Object completely outside of query region */\n#define PARTLY_WITHIN    1   /* Object partially overlaps query region */\n#define FULLY_WITHIN     2   /* Object fully contained within query region */\n\n\n#if 0\n}  /* end of the 'extern \"C\"' block */\n#endif\n\n#endif  /* ifndef _SQLITE3RTREE_H_ */\n\n/******** End of sqlite3rtree.h *********/\n/******** Begin file sqlite3session.h *********/\n\n#if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)\n#define __SQLITESESSION_H_ 1\n\n/*\n** Make sure we can call this stuff from C++.\n*/\n#if 0\nextern \"C\" {\n#endif\n\n\n/*\n** CAPI3REF: Session Object Handle\n**\n** An instance of this object is a [session] that can be used to\n** record changes to a database.\n*/\ntypedef struct sqlite3_session sqlite3_session;\n\n/*\n** CAPI3REF: Changeset Iterator Handle\n**\n** An instance of this object acts as a cursor for iterating\n** over the elements of a [changeset] or [patchset].\n*/\ntypedef struct sqlite3_changeset_iter sqlite3_changeset_iter;\n\n/*\n** CAPI3REF: Create A New Session Object\n** CONSTRUCTOR: sqlite3_session\n**\n** Create a new session object attached to database handle db. If successful,\n** a pointer to the new object is written to *ppSession and SQLITE_OK is\n** returned. If an error occurs, *ppSession is set to NULL and an SQLite\n** error code (e.g. SQLITE_NOMEM) is returned.\n**\n** It is possible to create multiple session objects attached to a single\n** database handle.\n**\n** Session objects created using this function should be deleted using the\n** [sqlite3session_delete()] function before the database handle that they\n** are attached to is itself closed. If the database handle is closed before\n** the session object is deleted, then the results of calling any session\n** module function, including [sqlite3session_delete()] on the session object\n** are undefined.\n**\n** Because the session module uses the [sqlite3_preupdate_hook()] API, it\n** is not possible for an application to register a pre-update hook on a\n** database handle that has one or more session objects attached. Nor is\n** it possible to create a session object attached to a database handle for\n** which a pre-update hook is already defined. The results of attempting \n** either of these things are undefined.\n**\n** The session object will be used to create changesets for tables in\n** database zDb, where zDb is either \"main\", or \"temp\", or the name of an\n** attached database. It is not an error if database zDb is not attached\n** to the database when the session object is created.\n*/\nSQLITE_API int sqlite3session_create(\n  sqlite3 *db,                    /* Database handle */\n  const char *zDb,                /* Name of db (e.g. \"main\") */\n  sqlite3_session **ppSession     /* OUT: New session object */\n);\n\n/*\n** CAPI3REF: Delete A Session Object\n** DESTRUCTOR: sqlite3_session\n**\n** Delete a session object previously allocated using \n** [sqlite3session_create()]. Once a session object has been deleted, the\n** results of attempting to use pSession with any other session module\n** function are undefined.\n**\n** Session objects must be deleted before the database handle to which they\n** are attached is closed. Refer to the documentation for \n** [sqlite3session_create()] for details.\n*/\nSQLITE_API void sqlite3session_delete(sqlite3_session *pSession);\n\n\n/*\n** CAPI3REF: Enable Or Disable A Session Object\n** METHOD: sqlite3_session\n**\n** Enable or disable the recording of changes by a session object. When\n** enabled, a session object records changes made to the database. When\n** disabled - it does not. A newly created session object is enabled.\n** Refer to the documentation for [sqlite3session_changeset()] for further\n** details regarding how enabling and disabling a session object affects\n** the eventual changesets.\n**\n** Passing zero to this function disables the session. Passing a value\n** greater than zero enables it. Passing a value less than zero is a \n** no-op, and may be used to query the current state of the session.\n**\n** The return value indicates the final state of the session object: 0 if \n** the session is disabled, or 1 if it is enabled.\n*/\nSQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);\n\n/*\n** CAPI3REF: Set Or Clear the Indirect Change Flag\n** METHOD: sqlite3_session\n**\n** Each change recorded by a session object is marked as either direct or\n** indirect. A change is marked as indirect if either:\n**\n** <ul>\n**   <li> The session object \"indirect\" flag is set when the change is\n**        made, or\n**   <li> The change is made by an SQL trigger or foreign key action \n**        instead of directly as a result of a users SQL statement.\n** </ul>\n**\n** If a single row is affected by more than one operation within a session,\n** then the change is considered indirect if all operations meet the criteria\n** for an indirect change above, or direct otherwise.\n**\n** This function is used to set, clear or query the session object indirect\n** flag.  If the second argument passed to this function is zero, then the\n** indirect flag is cleared. If it is greater than zero, the indirect flag\n** is set. Passing a value less than zero does not modify the current value\n** of the indirect flag, and may be used to query the current state of the \n** indirect flag for the specified session object.\n**\n** The return value indicates the final state of the indirect flag: 0 if \n** it is clear, or 1 if it is set.\n*/\nSQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);\n\n/*\n** CAPI3REF: Attach A Table To A Session Object\n** METHOD: sqlite3_session\n**\n** If argument zTab is not NULL, then it is the name of a table to attach\n** to the session object passed as the first argument. All subsequent changes \n** made to the table while the session object is enabled will be recorded. See \n** documentation for [sqlite3session_changeset()] for further details.\n**\n** Or, if argument zTab is NULL, then changes are recorded for all tables\n** in the database. If additional tables are added to the database (by \n** executing \"CREATE TABLE\" statements) after this call is made, changes for \n** the new tables are also recorded.\n**\n** Changes can only be recorded for tables that have a PRIMARY KEY explicitly\n** defined as part of their CREATE TABLE statement. It does not matter if the \n** PRIMARY KEY is an \"INTEGER PRIMARY KEY\" (rowid alias) or not. The PRIMARY\n** KEY may consist of a single column, or may be a composite key.\n** \n** It is not an error if the named table does not exist in the database. Nor\n** is it an error if the named table does not have a PRIMARY KEY. However,\n** no changes will be recorded in either of these scenarios.\n**\n** Changes are not recorded for individual rows that have NULL values stored\n** in one or more of their PRIMARY KEY columns.\n**\n** SQLITE_OK is returned if the call completes without error. Or, if an error \n** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.\n**\n** <h3>Special sqlite_stat1 Handling</h3>\n**\n** As of SQLite version 3.22.0, the \"sqlite_stat1\" table is an exception to \n** some of the rules above. In SQLite, the schema of sqlite_stat1 is:\n**  <pre>\n**  &nbsp;     CREATE TABLE sqlite_stat1(tbl,idx,stat)  \n**  </pre>\n**\n** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are \n** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes \n** are recorded for rows for which (idx IS NULL) is true. However, for such\n** rows a zero-length blob (SQL value X'') is stored in the changeset or\n** patchset instead of a NULL value. This allows such changesets to be\n** manipulated by legacy implementations of sqlite3changeset_invert(),\n** concat() and similar.\n**\n** The sqlite3changeset_apply() function automatically converts the \n** zero-length blob back to a NULL value when updating the sqlite_stat1\n** table. However, if the application calls sqlite3changeset_new(),\n** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset \n** iterator directly (including on a changeset iterator passed to a\n** conflict-handler callback) then the X'' value is returned. The application\n** must translate X'' to NULL itself if required.\n**\n** Legacy (older than 3.22.0) versions of the sessions module cannot capture\n** changes made to the sqlite_stat1 table. Legacy versions of the\n** sqlite3changeset_apply() function silently ignore any modifications to the\n** sqlite_stat1 table that are part of a changeset or patchset.\n*/\nSQLITE_API int sqlite3session_attach(\n  sqlite3_session *pSession,      /* Session object */\n  const char *zTab                /* Table name */\n);\n\n/*\n** CAPI3REF: Set a table filter on a Session Object.\n** METHOD: sqlite3_session\n**\n** The second argument (xFilter) is the \"filter callback\". For changes to rows \n** in tables that are not attached to the Session object, the filter is called\n** to determine whether changes to the table's rows should be tracked or not. \n** If xFilter returns 0, changes are not tracked. Note that once a table is \n** attached, xFilter will not be called again.\n*/\nSQLITE_API void sqlite3session_table_filter(\n  sqlite3_session *pSession,      /* Session object */\n  int(*xFilter)(\n    void *pCtx,                   /* Copy of third arg to _filter_table() */\n    const char *zTab              /* Table name */\n  ),\n  void *pCtx                      /* First argument passed to xFilter */\n);\n\n/*\n** CAPI3REF: Generate A Changeset From A Session Object\n** METHOD: sqlite3_session\n**\n** Obtain a changeset containing changes to the tables attached to the \n** session object passed as the first argument. If successful, \n** set *ppChangeset to point to a buffer containing the changeset \n** and *pnChangeset to the size of the changeset in bytes before returning\n** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to\n** zero and return an SQLite error code.\n**\n** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,\n** each representing a change to a single row of an attached table. An INSERT\n** change contains the values of each field of a new database row. A DELETE\n** contains the original values of each field of a deleted database row. An\n** UPDATE change contains the original values of each field of an updated\n** database row along with the updated values for each updated non-primary-key\n** column. It is not possible for an UPDATE change to represent a change that\n** modifies the values of primary key columns. If such a change is made, it\n** is represented in a changeset as a DELETE followed by an INSERT.\n**\n** Changes are not recorded for rows that have NULL values stored in one or \n** more of their PRIMARY KEY columns. If such a row is inserted or deleted,\n** no corresponding change is present in the changesets returned by this\n** function. If an existing row with one or more NULL values stored in\n** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,\n** only an INSERT is appears in the changeset. Similarly, if an existing row\n** with non-NULL PRIMARY KEY values is updated so that one or more of its\n** PRIMARY KEY columns are set to NULL, the resulting changeset contains a\n** DELETE change only.\n**\n** The contents of a changeset may be traversed using an iterator created\n** using the [sqlite3changeset_start()] API. A changeset may be applied to\n** a database with a compatible schema using the [sqlite3changeset_apply()]\n** API.\n**\n** Within a changeset generated by this function, all changes related to a\n** single table are grouped together. In other words, when iterating through\n** a changeset or when applying a changeset to a database, all changes related\n** to a single table are processed before moving on to the next table. Tables\n** are sorted in the same order in which they were attached (or auto-attached)\n** to the sqlite3_session object. The order in which the changes related to\n** a single table are stored is undefined.\n**\n** Following a successful call to this function, it is the responsibility of\n** the caller to eventually free the buffer that *ppChangeset points to using\n** [sqlite3_free()].\n**\n** <h3>Changeset Generation</h3>\n**\n** Once a table has been attached to a session object, the session object\n** records the primary key values of all new rows inserted into the table.\n** It also records the original primary key and other column values of any\n** deleted or updated rows. For each unique primary key value, data is only\n** recorded once - the first time a row with said primary key is inserted,\n** updated or deleted in the lifetime of the session.\n**\n** There is one exception to the previous paragraph: when a row is inserted,\n** updated or deleted, if one or more of its primary key columns contain a\n** NULL value, no record of the change is made.\n**\n** The session object therefore accumulates two types of records - those\n** that consist of primary key values only (created when the user inserts\n** a new record) and those that consist of the primary key values and the\n** original values of other table columns (created when the users deletes\n** or updates a record).\n**\n** When this function is called, the requested changeset is created using\n** both the accumulated records and the current contents of the database\n** file. Specifically:\n**\n** <ul>\n**   <li> For each record generated by an insert, the database is queried\n**        for a row with a matching primary key. If one is found, an INSERT\n**        change is added to the changeset. If no such row is found, no change \n**        is added to the changeset.\n**\n**   <li> For each record generated by an update or delete, the database is \n**        queried for a row with a matching primary key. If such a row is\n**        found and one or more of the non-primary key fields have been\n**        modified from their original values, an UPDATE change is added to \n**        the changeset. Or, if no such row is found in the table, a DELETE \n**        change is added to the changeset. If there is a row with a matching\n**        primary key in the database, but all fields contain their original\n**        values, no change is added to the changeset.\n** </ul>\n**\n** This means, amongst other things, that if a row is inserted and then later\n** deleted while a session object is active, neither the insert nor the delete\n** will be present in the changeset. Or if a row is deleted and then later a \n** row with the same primary key values inserted while a session object is\n** active, the resulting changeset will contain an UPDATE change instead of\n** a DELETE and an INSERT.\n**\n** When a session object is disabled (see the [sqlite3session_enable()] API),\n** it does not accumulate records when rows are inserted, updated or deleted.\n** This may appear to have some counter-intuitive effects if a single row\n** is written to more than once during a session. For example, if a row\n** is inserted while a session object is enabled, then later deleted while \n** the same session object is disabled, no INSERT record will appear in the\n** changeset, even though the delete took place while the session was disabled.\n** Or, if one field of a row is updated while a session is disabled, and \n** another field of the same row is updated while the session is enabled, the\n** resulting changeset will contain an UPDATE change that updates both fields.\n*/\nSQLITE_API int sqlite3session_changeset(\n  sqlite3_session *pSession,      /* Session object */\n  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */\n  void **ppChangeset              /* OUT: Buffer containing changeset */\n);\n\n/*\n** CAPI3REF: Load The Difference Between Tables Into A Session\n** METHOD: sqlite3_session\n**\n** If it is not already attached to the session object passed as the first\n** argument, this function attaches table zTbl in the same manner as the\n** [sqlite3session_attach()] function. If zTbl does not exist, or if it\n** does not have a primary key, this function is a no-op (but does not return\n** an error).\n**\n** Argument zFromDb must be the name of a database (\"main\", \"temp\" etc.)\n** attached to the same database handle as the session object that contains \n** a table compatible with the table attached to the session by this function.\n** A table is considered compatible if it:\n**\n** <ul>\n**   <li> Has the same name,\n**   <li> Has the same set of columns declared in the same order, and\n**   <li> Has the same PRIMARY KEY definition.\n** </ul>\n**\n** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables\n** are compatible but do not have any PRIMARY KEY columns, it is not an error\n** but no changes are added to the session object. As with other session\n** APIs, tables without PRIMARY KEYs are simply ignored.\n**\n** This function adds a set of changes to the session object that could be\n** used to update the table in database zFrom (call this the \"from-table\") \n** so that its content is the same as the table attached to the session \n** object (call this the \"to-table\"). Specifically:\n**\n** <ul>\n**   <li> For each row (primary key) that exists in the to-table but not in \n**     the from-table, an INSERT record is added to the session object.\n**\n**   <li> For each row (primary key) that exists in the to-table but not in \n**     the from-table, a DELETE record is added to the session object.\n**\n**   <li> For each row (primary key) that exists in both tables, but features \n**     different non-PK values in each, an UPDATE record is added to the\n**     session.  \n** </ul>\n**\n** To clarify, if this function is called and then a changeset constructed\n** using [sqlite3session_changeset()], then after applying that changeset to \n** database zFrom the contents of the two compatible tables would be \n** identical.\n**\n** It an error if database zFrom does not exist or does not contain the\n** required compatible table.\n**\n** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite\n** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg\n** may be set to point to a buffer containing an English language error \n** message. It is the responsibility of the caller to free this buffer using\n** sqlite3_free().\n*/\nSQLITE_API int sqlite3session_diff(\n  sqlite3_session *pSession,\n  const char *zFromDb,\n  const char *zTbl,\n  char **pzErrMsg\n);\n\n\n/*\n** CAPI3REF: Generate A Patchset From A Session Object\n** METHOD: sqlite3_session\n**\n** The differences between a patchset and a changeset are that:\n**\n** <ul>\n**   <li> DELETE records consist of the primary key fields only. The \n**        original values of other fields are omitted.\n**   <li> The original values of any modified fields are omitted from \n**        UPDATE records.\n** </ul>\n**\n** A patchset blob may be used with up to date versions of all \n** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(), \n** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,\n** attempting to use a patchset blob with old versions of the\n** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. \n**\n** Because the non-primary key \"old.*\" fields are omitted, no \n** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset\n** is passed to the sqlite3changeset_apply() API. Other conflict types work\n** in the same way as for changesets.\n**\n** Changes within a patchset are ordered in the same way as for changesets\n** generated by the sqlite3session_changeset() function (i.e. all changes for\n** a single table are grouped together, tables appear in the order in which\n** they were attached to the session object).\n*/\nSQLITE_API int sqlite3session_patchset(\n  sqlite3_session *pSession,      /* Session object */\n  int *pnPatchset,                /* OUT: Size of buffer at *ppPatchset */\n  void **ppPatchset               /* OUT: Buffer containing patchset */\n);\n\n/*\n** CAPI3REF: Test if a changeset has recorded any changes.\n**\n** Return non-zero if no changes to attached tables have been recorded by \n** the session object passed as the first argument. Otherwise, if one or \n** more changes have been recorded, return zero.\n**\n** Even if this function returns zero, it is possible that calling\n** [sqlite3session_changeset()] on the session handle may still return a\n** changeset that contains no changes. This can happen when a row in \n** an attached table is modified and then later on the original values \n** are restored. However, if this function returns non-zero, then it is\n** guaranteed that a call to sqlite3session_changeset() will return a \n** changeset containing zero changes.\n*/\nSQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);\n\n/*\n** CAPI3REF: Create An Iterator To Traverse A Changeset \n** CONSTRUCTOR: sqlite3_changeset_iter\n**\n** Create an iterator used to iterate through the contents of a changeset.\n** If successful, *pp is set to point to the iterator handle and SQLITE_OK\n** is returned. Otherwise, if an error occurs, *pp is set to zero and an\n** SQLite error code is returned.\n**\n** The following functions can be used to advance and query a changeset \n** iterator created by this function:\n**\n** <ul>\n**   <li> [sqlite3changeset_next()]\n**   <li> [sqlite3changeset_op()]\n**   <li> [sqlite3changeset_new()]\n**   <li> [sqlite3changeset_old()]\n** </ul>\n**\n** It is the responsibility of the caller to eventually destroy the iterator\n** by passing it to [sqlite3changeset_finalize()]. The buffer containing the\n** changeset (pChangeset) must remain valid until after the iterator is\n** destroyed.\n**\n** Assuming the changeset blob was created by one of the\n** [sqlite3session_changeset()], [sqlite3changeset_concat()] or\n** [sqlite3changeset_invert()] functions, all changes within the changeset \n** that apply to a single table are grouped together. This means that when \n** an application iterates through a changeset using an iterator created by \n** this function, all changes that relate to a single table are visited \n** consecutively. There is no chance that the iterator will visit a change \n** the applies to table X, then one for table Y, and then later on visit \n** another change for table X.\n**\n** The behavior of sqlite3changeset_start_v2() and its streaming equivalent\n** may be modified by passing a combination of\n** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter.\n**\n** Note that the sqlite3changeset_start_v2() API is still <b>experimental</b>\n** and therefore subject to change.\n*/\nSQLITE_API int sqlite3changeset_start(\n  sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */\n  int nChangeset,                 /* Size of changeset blob in bytes */\n  void *pChangeset                /* Pointer to blob containing changeset */\n);\nSQLITE_API int sqlite3changeset_start_v2(\n  sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */\n  int nChangeset,                 /* Size of changeset blob in bytes */\n  void *pChangeset,               /* Pointer to blob containing changeset */\n  int flags                       /* SESSION_CHANGESETSTART_* flags */\n);\n\n/*\n** CAPI3REF: Flags for sqlite3changeset_start_v2\n**\n** The following flags may passed via the 4th parameter to\n** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:\n**\n** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>\n**   Invert the changeset while iterating through it. This is equivalent to\n**   inverting a changeset using sqlite3changeset_invert() before applying it.\n**   It is an error to specify this flag with a patchset.\n*/\n#define SQLITE_CHANGESETSTART_INVERT        0x0002\n\n\n/*\n** CAPI3REF: Advance A Changeset Iterator\n** METHOD: sqlite3_changeset_iter\n**\n** This function may only be used with iterators created by the function\n** [sqlite3changeset_start()]. If it is called on an iterator passed to\n** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE\n** is returned and the call has no effect.\n**\n** Immediately after an iterator is created by sqlite3changeset_start(), it\n** does not point to any change in the changeset. Assuming the changeset\n** is not empty, the first call to this function advances the iterator to\n** point to the first change in the changeset. Each subsequent call advances\n** the iterator to point to the next change in the changeset (if any). If\n** no error occurs and the iterator points to a valid change after a call\n** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. \n** Otherwise, if all changes in the changeset have already been visited,\n** SQLITE_DONE is returned.\n**\n** If an error occurs, an SQLite error code is returned. Possible error \n** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or \n** SQLITE_NOMEM.\n*/\nSQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);\n\n/*\n** CAPI3REF: Obtain The Current Operation From A Changeset Iterator\n** METHOD: sqlite3_changeset_iter\n**\n** The pIter argument passed to this function may either be an iterator\n** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator\n** created by [sqlite3changeset_start()]. In the latter case, the most recent\n** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this\n** is not the case, this function returns [SQLITE_MISUSE].\n**\n** If argument pzTab is not NULL, then *pzTab is set to point to a\n** nul-terminated utf-8 encoded string containing the name of the table\n** affected by the current change. The buffer remains valid until either\n** sqlite3changeset_next() is called on the iterator or until the \n** conflict-handler function returns. If pnCol is not NULL, then *pnCol is \n** set to the number of columns in the table affected by the change. If\n** pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change\n** is an indirect change, or false (0) otherwise. See the documentation for\n** [sqlite3session_indirect()] for a description of direct and indirect\n** changes. Finally, if pOp is not NULL, then *pOp is set to one of \n** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the \n** type of change that the iterator currently points to.\n**\n** If no error occurs, SQLITE_OK is returned. If an error does occur, an\n** SQLite error code is returned. The values of the output variables may not\n** be trusted in this case.\n*/\nSQLITE_API int sqlite3changeset_op(\n  sqlite3_changeset_iter *pIter,  /* Iterator object */\n  const char **pzTab,             /* OUT: Pointer to table name */\n  int *pnCol,                     /* OUT: Number of columns in table */\n  int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */\n  int *pbIndirect                 /* OUT: True for an 'indirect' change */\n);\n\n/*\n** CAPI3REF: Obtain The Primary Key Definition Of A Table\n** METHOD: sqlite3_changeset_iter\n**\n** For each modified table, a changeset includes the following:\n**\n** <ul>\n**   <li> The number of columns in the table, and\n**   <li> Which of those columns make up the tables PRIMARY KEY.\n** </ul>\n**\n** This function is used to find which columns comprise the PRIMARY KEY of\n** the table modified by the change that iterator pIter currently points to.\n** If successful, *pabPK is set to point to an array of nCol entries, where\n** nCol is the number of columns in the table. Elements of *pabPK are set to\n** 0x01 if the corresponding column is part of the tables primary key, or\n** 0x00 if it is not.\n**\n** If argument pnCol is not NULL, then *pnCol is set to the number of columns\n** in the table.\n**\n** If this function is called when the iterator does not point to a valid\n** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,\n** SQLITE_OK is returned and the output variables populated as described\n** above.\n*/\nSQLITE_API int sqlite3changeset_pk(\n  sqlite3_changeset_iter *pIter,  /* Iterator object */\n  unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */\n  int *pnCol                      /* OUT: Number of entries in output array */\n);\n\n/*\n** CAPI3REF: Obtain old.* Values From A Changeset Iterator\n** METHOD: sqlite3_changeset_iter\n**\n** The pIter argument passed to this function may either be an iterator\n** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator\n** created by [sqlite3changeset_start()]. In the latter case, the most recent\n** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. \n** Furthermore, it may only be called if the type of change that the iterator\n** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,\n** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.\n**\n** Argument iVal must be greater than or equal to 0, and less than the number\n** of columns in the table affected by the current change. Otherwise,\n** [SQLITE_RANGE] is returned and *ppValue is set to NULL.\n**\n** If successful, this function sets *ppValue to point to a protected\n** sqlite3_value object containing the iVal'th value from the vector of \n** original row values stored as part of the UPDATE or DELETE change and\n** returns SQLITE_OK. The name of the function comes from the fact that this \n** is similar to the \"old.*\" columns available to update or delete triggers.\n**\n** If some other error occurs (e.g. an OOM condition), an SQLite error code\n** is returned and *ppValue is set to NULL.\n*/\nSQLITE_API int sqlite3changeset_old(\n  sqlite3_changeset_iter *pIter,  /* Changeset iterator */\n  int iVal,                       /* Column number */\n  sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */\n);\n\n/*\n** CAPI3REF: Obtain new.* Values From A Changeset Iterator\n** METHOD: sqlite3_changeset_iter\n**\n** The pIter argument passed to this function may either be an iterator\n** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator\n** created by [sqlite3changeset_start()]. In the latter case, the most recent\n** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. \n** Furthermore, it may only be called if the type of change that the iterator\n** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,\n** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.\n**\n** Argument iVal must be greater than or equal to 0, and less than the number\n** of columns in the table affected by the current change. Otherwise,\n** [SQLITE_RANGE] is returned and *ppValue is set to NULL.\n**\n** If successful, this function sets *ppValue to point to a protected\n** sqlite3_value object containing the iVal'th value from the vector of \n** new row values stored as part of the UPDATE or INSERT change and\n** returns SQLITE_OK. If the change is an UPDATE and does not include\n** a new value for the requested column, *ppValue is set to NULL and \n** SQLITE_OK returned. The name of the function comes from the fact that \n** this is similar to the \"new.*\" columns available to update or delete \n** triggers.\n**\n** If some other error occurs (e.g. an OOM condition), an SQLite error code\n** is returned and *ppValue is set to NULL.\n*/\nSQLITE_API int sqlite3changeset_new(\n  sqlite3_changeset_iter *pIter,  /* Changeset iterator */\n  int iVal,                       /* Column number */\n  sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */\n);\n\n/*\n** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator\n** METHOD: sqlite3_changeset_iter\n**\n** This function should only be used with iterator objects passed to a\n** conflict-handler callback by [sqlite3changeset_apply()] with either\n** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function\n** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue\n** is set to NULL.\n**\n** Argument iVal must be greater than or equal to 0, and less than the number\n** of columns in the table affected by the current change. Otherwise,\n** [SQLITE_RANGE] is returned and *ppValue is set to NULL.\n**\n** If successful, this function sets *ppValue to point to a protected\n** sqlite3_value object containing the iVal'th value from the \n** \"conflicting row\" associated with the current conflict-handler callback\n** and returns SQLITE_OK.\n**\n** If some other error occurs (e.g. an OOM condition), an SQLite error code\n** is returned and *ppValue is set to NULL.\n*/\nSQLITE_API int sqlite3changeset_conflict(\n  sqlite3_changeset_iter *pIter,  /* Changeset iterator */\n  int iVal,                       /* Column number */\n  sqlite3_value **ppValue         /* OUT: Value from conflicting row */\n);\n\n/*\n** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations\n** METHOD: sqlite3_changeset_iter\n**\n** This function may only be called with an iterator passed to an\n** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case\n** it sets the output variable to the total number of known foreign key\n** violations in the destination database and returns SQLITE_OK.\n**\n** In all other cases this function returns SQLITE_MISUSE.\n*/\nSQLITE_API int sqlite3changeset_fk_conflicts(\n  sqlite3_changeset_iter *pIter,  /* Changeset iterator */\n  int *pnOut                      /* OUT: Number of FK violations */\n);\n\n\n/*\n** CAPI3REF: Finalize A Changeset Iterator\n** METHOD: sqlite3_changeset_iter\n**\n** This function is used to finalize an iterator allocated with\n** [sqlite3changeset_start()].\n**\n** This function should only be called on iterators created using the\n** [sqlite3changeset_start()] function. If an application calls this\n** function with an iterator passed to a conflict-handler by\n** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the\n** call has no effect.\n**\n** If an error was encountered within a call to an sqlite3changeset_xxx()\n** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an \n** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding\n** to that error is returned by this function. Otherwise, SQLITE_OK is\n** returned. This is to allow the following pattern (pseudo-code):\n**\n** <pre>\n**   sqlite3changeset_start();\n**   while( SQLITE_ROW==sqlite3changeset_next() ){\n**     // Do something with change.\n**   }\n**   rc = sqlite3changeset_finalize();\n**   if( rc!=SQLITE_OK ){\n**     // An error has occurred \n**   }\n** </pre>\n*/\nSQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);\n\n/*\n** CAPI3REF: Invert A Changeset\n**\n** This function is used to \"invert\" a changeset object. Applying an inverted\n** changeset to a database reverses the effects of applying the uninverted\n** changeset. Specifically:\n**\n** <ul>\n**   <li> Each DELETE change is changed to an INSERT, and\n**   <li> Each INSERT change is changed to a DELETE, and\n**   <li> For each UPDATE change, the old.* and new.* values are exchanged.\n** </ul>\n**\n** This function does not change the order in which changes appear within\n** the changeset. It merely reverses the sense of each individual change.\n**\n** If successful, a pointer to a buffer containing the inverted changeset\n** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and\n** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are\n** zeroed and an SQLite error code returned.\n**\n** It is the responsibility of the caller to eventually call sqlite3_free()\n** on the *ppOut pointer to free the buffer allocation following a successful \n** call to this function.\n**\n** WARNING/TODO: This function currently assumes that the input is a valid\n** changeset. If it is not, the results are undefined.\n*/\nSQLITE_API int sqlite3changeset_invert(\n  int nIn, const void *pIn,       /* Input changeset */\n  int *pnOut, void **ppOut        /* OUT: Inverse of input */\n);\n\n/*\n** CAPI3REF: Concatenate Two Changeset Objects\n**\n** This function is used to concatenate two changesets, A and B, into a \n** single changeset. The result is a changeset equivalent to applying\n** changeset A followed by changeset B. \n**\n** This function combines the two input changesets using an \n** sqlite3_changegroup object. Calling it produces similar results as the\n** following code fragment:\n**\n** <pre>\n**   sqlite3_changegroup *pGrp;\n**   rc = sqlite3_changegroup_new(&pGrp);\n**   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);\n**   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);\n**   if( rc==SQLITE_OK ){\n**     rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);\n**   }else{\n**     *ppOut = 0;\n**     *pnOut = 0;\n**   }\n** </pre>\n**\n** Refer to the sqlite3_changegroup documentation below for details.\n*/\nSQLITE_API int sqlite3changeset_concat(\n  int nA,                         /* Number of bytes in buffer pA */\n  void *pA,                       /* Pointer to buffer containing changeset A */\n  int nB,                         /* Number of bytes in buffer pB */\n  void *pB,                       /* Pointer to buffer containing changeset B */\n  int *pnOut,                     /* OUT: Number of bytes in output changeset */\n  void **ppOut                    /* OUT: Buffer containing output changeset */\n);\n\n\n/*\n** CAPI3REF: Changegroup Handle\n**\n** A changegroup is an object used to combine two or more \n** [changesets] or [patchsets]\n*/\ntypedef struct sqlite3_changegroup sqlite3_changegroup;\n\n/*\n** CAPI3REF: Create A New Changegroup Object\n** CONSTRUCTOR: sqlite3_changegroup\n**\n** An sqlite3_changegroup object is used to combine two or more changesets\n** (or patchsets) into a single changeset (or patchset). A single changegroup\n** object may combine changesets or patchsets, but not both. The output is\n** always in the same format as the input.\n**\n** If successful, this function returns SQLITE_OK and populates (*pp) with\n** a pointer to a new sqlite3_changegroup object before returning. The caller\n** should eventually free the returned object using a call to \n** sqlite3changegroup_delete(). If an error occurs, an SQLite error code\n** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.\n**\n** The usual usage pattern for an sqlite3_changegroup object is as follows:\n**\n** <ul>\n**   <li> It is created using a call to sqlite3changegroup_new().\n**\n**   <li> Zero or more changesets (or patchsets) are added to the object\n**        by calling sqlite3changegroup_add().\n**\n**   <li> The result of combining all input changesets together is obtained \n**        by the application via a call to sqlite3changegroup_output().\n**\n**   <li> The object is deleted using a call to sqlite3changegroup_delete().\n** </ul>\n**\n** Any number of calls to add() and output() may be made between the calls to\n** new() and delete(), and in any order.\n**\n** As well as the regular sqlite3changegroup_add() and \n** sqlite3changegroup_output() functions, also available are the streaming\n** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().\n*/\nSQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);\n\n/*\n** CAPI3REF: Add A Changeset To A Changegroup\n** METHOD: sqlite3_changegroup\n**\n** Add all changes within the changeset (or patchset) in buffer pData (size\n** nData bytes) to the changegroup. \n**\n** If the buffer contains a patchset, then all prior calls to this function\n** on the same changegroup object must also have specified patchsets. Or, if\n** the buffer contains a changeset, so must have the earlier calls to this\n** function. Otherwise, SQLITE_ERROR is returned and no changes are added\n** to the changegroup.\n**\n** Rows within the changeset and changegroup are identified by the values in\n** their PRIMARY KEY columns. A change in the changeset is considered to\n** apply to the same row as a change already present in the changegroup if\n** the two rows have the same primary key.\n**\n** Changes to rows that do not already appear in the changegroup are\n** simply copied into it. Or, if both the new changeset and the changegroup\n** contain changes that apply to a single row, the final contents of the\n** changegroup depends on the type of each change, as follows:\n**\n** <table border=1 style=\"margin-left:8ex;margin-right:8ex\">\n**   <tr><th style=\"white-space:pre\">Existing Change  </th>\n**       <th style=\"white-space:pre\">New Change       </th>\n**       <th>Output Change\n**   <tr><td>INSERT <td>INSERT <td>\n**       The new change is ignored. This case does not occur if the new\n**       changeset was recorded immediately after the changesets already\n**       added to the changegroup.\n**   <tr><td>INSERT <td>UPDATE <td>\n**       The INSERT change remains in the changegroup. The values in the \n**       INSERT change are modified as if the row was inserted by the\n**       existing change and then updated according to the new change.\n**   <tr><td>INSERT <td>DELETE <td>\n**       The existing INSERT is removed from the changegroup. The DELETE is\n**       not added.\n**   <tr><td>UPDATE <td>INSERT <td>\n**       The new change is ignored. This case does not occur if the new\n**       changeset was recorded immediately after the changesets already\n**       added to the changegroup.\n**   <tr><td>UPDATE <td>UPDATE <td>\n**       The existing UPDATE remains within the changegroup. It is amended \n**       so that the accompanying values are as if the row was updated once \n**       by the existing change and then again by the new change.\n**   <tr><td>UPDATE <td>DELETE <td>\n**       The existing UPDATE is replaced by the new DELETE within the\n**       changegroup.\n**   <tr><td>DELETE <td>INSERT <td>\n**       If one or more of the column values in the row inserted by the\n**       new change differ from those in the row deleted by the existing \n**       change, the existing DELETE is replaced by an UPDATE within the\n**       changegroup. Otherwise, if the inserted row is exactly the same \n**       as the deleted row, the existing DELETE is simply discarded.\n**   <tr><td>DELETE <td>UPDATE <td>\n**       The new change is ignored. This case does not occur if the new\n**       changeset was recorded immediately after the changesets already\n**       added to the changegroup.\n**   <tr><td>DELETE <td>DELETE <td>\n**       The new change is ignored. This case does not occur if the new\n**       changeset was recorded immediately after the changesets already\n**       added to the changegroup.\n** </table>\n**\n** If the new changeset contains changes to a table that is already present\n** in the changegroup, then the number of columns and the position of the\n** primary key columns for the table must be consistent. If this is not the\n** case, this function fails with SQLITE_SCHEMA. If the input changeset\n** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is\n** returned. Or, if an out-of-memory condition occurs during processing, this\n** function returns SQLITE_NOMEM. In all cases, if an error occurs the state\n** of the final contents of the changegroup is undefined.\n**\n** If no error occurs, SQLITE_OK is returned.\n*/\nSQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);\n\n/*\n** CAPI3REF: Obtain A Composite Changeset From A Changegroup\n** METHOD: sqlite3_changegroup\n**\n** Obtain a buffer containing a changeset (or patchset) representing the\n** current contents of the changegroup. If the inputs to the changegroup\n** were themselves changesets, the output is a changeset. Or, if the\n** inputs were patchsets, the output is also a patchset.\n**\n** As with the output of the sqlite3session_changeset() and\n** sqlite3session_patchset() functions, all changes related to a single\n** table are grouped together in the output of this function. Tables appear\n** in the same order as for the very first changeset added to the changegroup.\n** If the second or subsequent changesets added to the changegroup contain\n** changes for tables that do not appear in the first changeset, they are\n** appended onto the end of the output changeset, again in the order in\n** which they are first encountered.\n**\n** If an error occurs, an SQLite error code is returned and the output\n** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK\n** is returned and the output variables are set to the size of and a \n** pointer to the output buffer, respectively. In this case it is the\n** responsibility of the caller to eventually free the buffer using a\n** call to sqlite3_free().\n*/\nSQLITE_API int sqlite3changegroup_output(\n  sqlite3_changegroup*,\n  int *pnData,                    /* OUT: Size of output buffer in bytes */\n  void **ppData                   /* OUT: Pointer to output buffer */\n);\n\n/*\n** CAPI3REF: Delete A Changegroup Object\n** DESTRUCTOR: sqlite3_changegroup\n*/\nSQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);\n\n/*\n** CAPI3REF: Apply A Changeset To A Database\n**\n** Apply a changeset or patchset to a database. These functions attempt to\n** update the \"main\" database attached to handle db with the changes found in\n** the changeset passed via the second and third arguments. \n**\n** The fourth argument (xFilter) passed to these functions is the \"filter\n** callback\". If it is not NULL, then for each table affected by at least one\n** change in the changeset, the filter callback is invoked with\n** the table name as the second argument, and a copy of the context pointer\n** passed as the sixth argument as the first. If the \"filter callback\"\n** returns zero, then no attempt is made to apply any changes to the table.\n** Otherwise, if the return value is non-zero or the xFilter argument to\n** is NULL, all changes related to the table are attempted.\n**\n** For each table that is not excluded by the filter callback, this function \n** tests that the target database contains a compatible table. A table is \n** considered compatible if all of the following are true:\n**\n** <ul>\n**   <li> The table has the same name as the name recorded in the \n**        changeset, and\n**   <li> The table has at least as many columns as recorded in the \n**        changeset, and\n**   <li> The table has primary key columns in the same position as \n**        recorded in the changeset.\n** </ul>\n**\n** If there is no compatible table, it is not an error, but none of the\n** changes associated with the table are applied. A warning message is issued\n** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most\n** one such warning is issued for each table in the changeset.\n**\n** For each change for which there is a compatible table, an attempt is made \n** to modify the table contents according to the UPDATE, INSERT or DELETE \n** change. If a change cannot be applied cleanly, the conflict handler \n** function passed as the fifth argument to sqlite3changeset_apply() may be \n** invoked. A description of exactly when the conflict handler is invoked for \n** each type of change is below.\n**\n** Unlike the xFilter argument, xConflict may not be passed NULL. The results\n** of passing anything other than a valid function pointer as the xConflict\n** argument are undefined.\n**\n** Each time the conflict handler function is invoked, it must return one\n** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or \n** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned\n** if the second argument passed to the conflict handler is either\n** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler\n** returns an illegal value, any changes already made are rolled back and\n** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different \n** actions are taken by sqlite3changeset_apply() depending on the value\n** returned by each invocation of the conflict-handler function. Refer to\n** the documentation for the three \n** [SQLITE_CHANGESET_OMIT|available return values] for details.\n**\n** <dl>\n** <dt>DELETE Changes<dd>\n**   For each DELETE change, the function checks if the target database \n**   contains a row with the same primary key value (or values) as the \n**   original row values stored in the changeset. If it does, and the values \n**   stored in all non-primary key columns also match the values stored in \n**   the changeset the row is deleted from the target database.\n**\n**   If a row with matching primary key values is found, but one or more of\n**   the non-primary key fields contains a value different from the original\n**   row value stored in the changeset, the conflict-handler function is\n**   invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the\n**   database table has more columns than are recorded in the changeset,\n**   only the values of those non-primary key fields are compared against\n**   the current database contents - any trailing database table columns\n**   are ignored.\n**\n**   If no row with matching primary key values is found in the database,\n**   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]\n**   passed as the second argument.\n**\n**   If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT\n**   (which can only happen if a foreign key constraint is violated), the\n**   conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]\n**   passed as the second argument. This includes the case where the DELETE\n**   operation is attempted because an earlier call to the conflict handler\n**   function returned [SQLITE_CHANGESET_REPLACE].\n**\n** <dt>INSERT Changes<dd>\n**   For each INSERT change, an attempt is made to insert the new row into\n**   the database. If the changeset row contains fewer fields than the\n**   database table, the trailing fields are populated with their default\n**   values.\n**\n**   If the attempt to insert the row fails because the database already \n**   contains a row with the same primary key values, the conflict handler\n**   function is invoked with the second argument set to \n**   [SQLITE_CHANGESET_CONFLICT].\n**\n**   If the attempt to insert the row fails because of some other constraint\n**   violation (e.g. NOT NULL or UNIQUE), the conflict handler function is \n**   invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].\n**   This includes the case where the INSERT operation is re-attempted because \n**   an earlier call to the conflict handler function returned \n**   [SQLITE_CHANGESET_REPLACE].\n**\n** <dt>UPDATE Changes<dd>\n**   For each UPDATE change, the function checks if the target database \n**   contains a row with the same primary key value (or values) as the \n**   original row values stored in the changeset. If it does, and the values \n**   stored in all modified non-primary key columns also match the values\n**   stored in the changeset the row is updated within the target database.\n**\n**   If a row with matching primary key values is found, but one or more of\n**   the modified non-primary key fields contains a value different from an\n**   original row value stored in the changeset, the conflict-handler function\n**   is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since\n**   UPDATE changes only contain values for non-primary key fields that are\n**   to be modified, only those fields need to match the original values to\n**   avoid the SQLITE_CHANGESET_DATA conflict-handler callback.\n**\n**   If no row with matching primary key values is found in the database,\n**   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]\n**   passed as the second argument.\n**\n**   If the UPDATE operation is attempted, but SQLite returns \n**   SQLITE_CONSTRAINT, the conflict-handler function is invoked with \n**   [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.\n**   This includes the case where the UPDATE operation is attempted after \n**   an earlier call to the conflict handler function returned\n**   [SQLITE_CHANGESET_REPLACE].  \n** </dl>\n**\n** It is safe to execute SQL statements, including those that write to the\n** table that the callback related to, from within the xConflict callback.\n** This can be used to further customize the application's conflict\n** resolution strategy.\n**\n** All changes made by these functions are enclosed in a savepoint transaction.\n** If any other error (aside from a constraint failure when attempting to\n** write to the target database) occurs, then the savepoint transaction is\n** rolled back, restoring the target database to its original state, and an \n** SQLite error code returned.\n**\n** If the output parameters (ppRebase) and (pnRebase) are non-NULL and\n** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()\n** may set (*ppRebase) to point to a \"rebase\" that may be used with the \n** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)\n** is set to the size of the buffer in bytes. It is the responsibility of the\n** caller to eventually free any such buffer using sqlite3_free(). The buffer\n** is only allocated and populated if one or more conflicts were encountered\n** while applying the patchset. See comments surrounding the sqlite3_rebaser\n** APIs for further details.\n**\n** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent\n** may be modified by passing a combination of\n** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter.\n**\n** Note that the sqlite3changeset_apply_v2() API is still <b>experimental</b>\n** and therefore subject to change.\n*/\nSQLITE_API int sqlite3changeset_apply(\n  sqlite3 *db,                    /* Apply change to \"main\" db of this handle */\n  int nChangeset,                 /* Size of changeset in bytes */\n  void *pChangeset,               /* Changeset blob */\n  int(*xFilter)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    const char *zTab              /* Table name */\n  ),\n  int(*xConflict)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */\n    sqlite3_changeset_iter *p     /* Handle describing change and conflict */\n  ),\n  void *pCtx                      /* First argument passed to xConflict */\n);\nSQLITE_API int sqlite3changeset_apply_v2(\n  sqlite3 *db,                    /* Apply change to \"main\" db of this handle */\n  int nChangeset,                 /* Size of changeset in bytes */\n  void *pChangeset,               /* Changeset blob */\n  int(*xFilter)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    const char *zTab              /* Table name */\n  ),\n  int(*xConflict)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */\n    sqlite3_changeset_iter *p     /* Handle describing change and conflict */\n  ),\n  void *pCtx,                     /* First argument passed to xConflict */\n  void **ppRebase, int *pnRebase, /* OUT: Rebase data */\n  int flags                       /* SESSION_CHANGESETAPPLY_* flags */\n);\n\n/*\n** CAPI3REF: Flags for sqlite3changeset_apply_v2\n**\n** The following flags may passed via the 9th parameter to\n** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:\n**\n** <dl>\n** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd>\n**   Usually, the sessions module encloses all operations performed by\n**   a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The\n**   SAVEPOINT is committed if the changeset or patchset is successfully\n**   applied, or rolled back if an error occurs. Specifying this flag\n**   causes the sessions module to omit this savepoint. In this case, if the\n**   caller has an open transaction or savepoint when apply_v2() is called, \n**   it may revert the partially applied changeset by rolling it back.\n**\n** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>\n**   Invert the changeset before applying it. This is equivalent to inverting\n**   a changeset using sqlite3changeset_invert() before applying it. It is\n**   an error to specify this flag with a patchset.\n*/\n#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT   0x0001\n#define SQLITE_CHANGESETAPPLY_INVERT        0x0002\n\n/* \n** CAPI3REF: Constants Passed To The Conflict Handler\n**\n** Values that may be passed as the second argument to a conflict-handler.\n**\n** <dl>\n** <dt>SQLITE_CHANGESET_DATA<dd>\n**   The conflict handler is invoked with CHANGESET_DATA as the second argument\n**   when processing a DELETE or UPDATE change if a row with the required\n**   PRIMARY KEY fields is present in the database, but one or more other \n**   (non primary-key) fields modified by the update do not contain the \n**   expected \"before\" values.\n** \n**   The conflicting row, in this case, is the database row with the matching\n**   primary key.\n** \n** <dt>SQLITE_CHANGESET_NOTFOUND<dd>\n**   The conflict handler is invoked with CHANGESET_NOTFOUND as the second\n**   argument when processing a DELETE or UPDATE change if a row with the\n**   required PRIMARY KEY fields is not present in the database.\n** \n**   There is no conflicting row in this case. The results of invoking the\n**   sqlite3changeset_conflict() API are undefined.\n** \n** <dt>SQLITE_CHANGESET_CONFLICT<dd>\n**   CHANGESET_CONFLICT is passed as the second argument to the conflict\n**   handler while processing an INSERT change if the operation would result \n**   in duplicate primary key values.\n** \n**   The conflicting row in this case is the database row with the matching\n**   primary key.\n**\n** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>\n**   If foreign key handling is enabled, and applying a changeset leaves the\n**   database in a state containing foreign key violations, the conflict \n**   handler is invoked with CHANGESET_FOREIGN_KEY as the second argument\n**   exactly once before the changeset is committed. If the conflict handler\n**   returns CHANGESET_OMIT, the changes, including those that caused the\n**   foreign key constraint violation, are committed. Or, if it returns\n**   CHANGESET_ABORT, the changeset is rolled back.\n**\n**   No current or conflicting row information is provided. The only function\n**   it is possible to call on the supplied sqlite3_changeset_iter handle\n**   is sqlite3changeset_fk_conflicts().\n** \n** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>\n**   If any other constraint violation occurs while applying a change (i.e. \n**   a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is \n**   invoked with CHANGESET_CONSTRAINT as the second argument.\n** \n**   There is no conflicting row in this case. The results of invoking the\n**   sqlite3changeset_conflict() API are undefined.\n**\n** </dl>\n*/\n#define SQLITE_CHANGESET_DATA        1\n#define SQLITE_CHANGESET_NOTFOUND    2\n#define SQLITE_CHANGESET_CONFLICT    3\n#define SQLITE_CHANGESET_CONSTRAINT  4\n#define SQLITE_CHANGESET_FOREIGN_KEY 5\n\n/* \n** CAPI3REF: Constants Returned By The Conflict Handler\n**\n** A conflict handler callback must return one of the following three values.\n**\n** <dl>\n** <dt>SQLITE_CHANGESET_OMIT<dd>\n**   If a conflict handler returns this value no special action is taken. The\n**   change that caused the conflict is not applied. The session module \n**   continues to the next change in the changeset.\n**\n** <dt>SQLITE_CHANGESET_REPLACE<dd>\n**   This value may only be returned if the second argument to the conflict\n**   handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this\n**   is not the case, any changes applied so far are rolled back and the \n**   call to sqlite3changeset_apply() returns SQLITE_MISUSE.\n**\n**   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict\n**   handler, then the conflicting row is either updated or deleted, depending\n**   on the type of change.\n**\n**   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict\n**   handler, then the conflicting row is removed from the database and a\n**   second attempt to apply the change is made. If this second attempt fails,\n**   the original row is restored to the database before continuing.\n**\n** <dt>SQLITE_CHANGESET_ABORT<dd>\n**   If this value is returned, any changes applied so far are rolled back \n**   and the call to sqlite3changeset_apply() returns SQLITE_ABORT.\n** </dl>\n*/\n#define SQLITE_CHANGESET_OMIT       0\n#define SQLITE_CHANGESET_REPLACE    1\n#define SQLITE_CHANGESET_ABORT      2\n\n/* \n** CAPI3REF: Rebasing changesets\n** EXPERIMENTAL\n**\n** Suppose there is a site hosting a database in state S0. And that\n** modifications are made that move that database to state S1 and a\n** changeset recorded (the \"local\" changeset). Then, a changeset based\n** on S0 is received from another site (the \"remote\" changeset) and \n** applied to the database. The database is then in state \n** (S1+\"remote\"), where the exact state depends on any conflict\n** resolution decisions (OMIT or REPLACE) made while applying \"remote\".\n** Rebasing a changeset is to update it to take those conflict \n** resolution decisions into account, so that the same conflicts\n** do not have to be resolved elsewhere in the network. \n**\n** For example, if both the local and remote changesets contain an\n** INSERT of the same key on \"CREATE TABLE t1(a PRIMARY KEY, b)\":\n**\n**   local:  INSERT INTO t1 VALUES(1, 'v1');\n**   remote: INSERT INTO t1 VALUES(1, 'v2');\n**\n** and the conflict resolution is REPLACE, then the INSERT change is\n** removed from the local changeset (it was overridden). Or, if the\n** conflict resolution was \"OMIT\", then the local changeset is modified\n** to instead contain:\n**\n**           UPDATE t1 SET b = 'v2' WHERE a=1;\n**\n** Changes within the local changeset are rebased as follows:\n**\n** <dl>\n** <dt>Local INSERT<dd>\n**   This may only conflict with a remote INSERT. If the conflict \n**   resolution was OMIT, then add an UPDATE change to the rebased\n**   changeset. Or, if the conflict resolution was REPLACE, add\n**   nothing to the rebased changeset.\n**\n** <dt>Local DELETE<dd>\n**   This may conflict with a remote UPDATE or DELETE. In both cases the\n**   only possible resolution is OMIT. If the remote operation was a\n**   DELETE, then add no change to the rebased changeset. If the remote\n**   operation was an UPDATE, then the old.* fields of change are updated\n**   to reflect the new.* values in the UPDATE.\n**\n** <dt>Local UPDATE<dd>\n**   This may conflict with a remote UPDATE or DELETE. If it conflicts\n**   with a DELETE, and the conflict resolution was OMIT, then the update\n**   is changed into an INSERT. Any undefined values in the new.* record\n**   from the update change are filled in using the old.* values from\n**   the conflicting DELETE. Or, if the conflict resolution was REPLACE,\n**   the UPDATE change is simply omitted from the rebased changeset.\n**\n**   If conflict is with a remote UPDATE and the resolution is OMIT, then\n**   the old.* values are rebased using the new.* values in the remote\n**   change. Or, if the resolution is REPLACE, then the change is copied\n**   into the rebased changeset with updates to columns also updated by\n**   the conflicting remote UPDATE removed. If this means no columns would \n**   be updated, the change is omitted.\n** </dl>\n**\n** A local change may be rebased against multiple remote changes \n** simultaneously. If a single key is modified by multiple remote \n** changesets, they are combined as follows before the local changeset\n** is rebased:\n**\n** <ul>\n**    <li> If there has been one or more REPLACE resolutions on a\n**         key, it is rebased according to a REPLACE.\n**\n**    <li> If there have been no REPLACE resolutions on a key, then\n**         the local changeset is rebased according to the most recent\n**         of the OMIT resolutions.\n** </ul>\n**\n** Note that conflict resolutions from multiple remote changesets are \n** combined on a per-field basis, not per-row. This means that in the \n** case of multiple remote UPDATE operations, some fields of a single \n** local change may be rebased for REPLACE while others are rebased for \n** OMIT.\n**\n** In order to rebase a local changeset, the remote changeset must first\n** be applied to the local database using sqlite3changeset_apply_v2() and\n** the buffer of rebase information captured. Then:\n**\n** <ol>\n**   <li> An sqlite3_rebaser object is created by calling \n**        sqlite3rebaser_create().\n**   <li> The new object is configured with the rebase buffer obtained from\n**        sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().\n**        If the local changeset is to be rebased against multiple remote\n**        changesets, then sqlite3rebaser_configure() should be called\n**        multiple times, in the same order that the multiple\n**        sqlite3changeset_apply_v2() calls were made.\n**   <li> Each local changeset is rebased by calling sqlite3rebaser_rebase().\n**   <li> The sqlite3_rebaser object is deleted by calling\n**        sqlite3rebaser_delete().\n** </ol>\n*/\ntypedef struct sqlite3_rebaser sqlite3_rebaser;\n\n/*\n** CAPI3REF: Create a changeset rebaser object.\n** EXPERIMENTAL\n**\n** Allocate a new changeset rebaser object. If successful, set (*ppNew) to\n** point to the new object and return SQLITE_OK. Otherwise, if an error\n** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew) \n** to NULL. \n*/\nSQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);\n\n/*\n** CAPI3REF: Configure a changeset rebaser object.\n** EXPERIMENTAL\n**\n** Configure the changeset rebaser object to rebase changesets according\n** to the conflict resolutions described by buffer pRebase (size nRebase\n** bytes), which must have been obtained from a previous call to\n** sqlite3changeset_apply_v2().\n*/\nSQLITE_API int sqlite3rebaser_configure(\n  sqlite3_rebaser*, \n  int nRebase, const void *pRebase\n); \n\n/*\n** CAPI3REF: Rebase a changeset\n** EXPERIMENTAL\n**\n** Argument pIn must point to a buffer containing a changeset nIn bytes\n** in size. This function allocates and populates a buffer with a copy\n** of the changeset rebased according to the configuration of the\n** rebaser object passed as the first argument. If successful, (*ppOut)\n** is set to point to the new buffer containing the rebased changeset and \n** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the\n** responsibility of the caller to eventually free the new buffer using\n** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)\n** are set to zero and an SQLite error code returned.\n*/\nSQLITE_API int sqlite3rebaser_rebase(\n  sqlite3_rebaser*,\n  int nIn, const void *pIn, \n  int *pnOut, void **ppOut \n);\n\n/*\n** CAPI3REF: Delete a changeset rebaser object.\n** EXPERIMENTAL\n**\n** Delete the changeset rebaser object and all associated resources. There\n** should be one call to this function for each successful invocation\n** of sqlite3rebaser_create().\n*/\nSQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p); \n\n/*\n** CAPI3REF: Streaming Versions of API functions.\n**\n** The six streaming API xxx_strm() functions serve similar purposes to the \n** corresponding non-streaming API functions:\n**\n** <table border=1 style=\"margin-left:8ex;margin-right:8ex\">\n**   <tr><th>Streaming function<th>Non-streaming equivalent</th>\n**   <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply] \n**   <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2] \n**   <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat] \n**   <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert] \n**   <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start] \n**   <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset] \n**   <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset] \n** </table>\n**\n** Non-streaming functions that accept changesets (or patchsets) as input\n** require that the entire changeset be stored in a single buffer in memory. \n** Similarly, those that return a changeset or patchset do so by returning \n** a pointer to a single large buffer allocated using sqlite3_malloc(). \n** Normally this is convenient. However, if an application running in a \n** low-memory environment is required to handle very large changesets, the\n** large contiguous memory allocations required can become onerous.\n**\n** In order to avoid this problem, instead of a single large buffer, input\n** is passed to a streaming API functions by way of a callback function that\n** the sessions module invokes to incrementally request input data as it is\n** required. In all cases, a pair of API function parameters such as\n**\n**  <pre>\n**  &nbsp;     int nChangeset,\n**  &nbsp;     void *pChangeset,\n**  </pre>\n**\n** Is replaced by:\n**\n**  <pre>\n**  &nbsp;     int (*xInput)(void *pIn, void *pData, int *pnData),\n**  &nbsp;     void *pIn,\n**  </pre>\n**\n** Each time the xInput callback is invoked by the sessions module, the first\n** argument passed is a copy of the supplied pIn context pointer. The second \n** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no \n** error occurs the xInput method should copy up to (*pnData) bytes of data \n** into the buffer and set (*pnData) to the actual number of bytes copied \n** before returning SQLITE_OK. If the input is completely exhausted, (*pnData) \n** should be set to zero to indicate this. Or, if an error occurs, an SQLite \n** error code should be returned. In all cases, if an xInput callback returns\n** an error, all processing is abandoned and the streaming API function\n** returns a copy of the error code to the caller.\n**\n** In the case of sqlite3changeset_start_strm(), the xInput callback may be\n** invoked by the sessions module at any point during the lifetime of the\n** iterator. If such an xInput callback returns an error, the iterator enters\n** an error state, whereby all subsequent calls to iterator functions \n** immediately fail with the same error code as returned by xInput.\n**\n** Similarly, streaming API functions that return changesets (or patchsets)\n** return them in chunks by way of a callback function instead of via a\n** pointer to a single large buffer. In this case, a pair of parameters such\n** as:\n**\n**  <pre>\n**  &nbsp;     int *pnChangeset,\n**  &nbsp;     void **ppChangeset,\n**  </pre>\n**\n** Is replaced by:\n**\n**  <pre>\n**  &nbsp;     int (*xOutput)(void *pOut, const void *pData, int nData),\n**  &nbsp;     void *pOut\n**  </pre>\n**\n** The xOutput callback is invoked zero or more times to return data to\n** the application. The first parameter passed to each call is a copy of the\n** pOut pointer supplied by the application. The second parameter, pData,\n** points to a buffer nData bytes in size containing the chunk of output\n** data being returned. If the xOutput callback successfully processes the\n** supplied data, it should return SQLITE_OK to indicate success. Otherwise,\n** it should return some other SQLite error code. In this case processing\n** is immediately abandoned and the streaming API function returns a copy\n** of the xOutput error code to the application.\n**\n** The sessions module never invokes an xOutput callback with the third \n** parameter set to a value less than or equal to zero. Other than this,\n** no guarantees are made as to the size of the chunks of data returned.\n*/\nSQLITE_API int sqlite3changeset_apply_strm(\n  sqlite3 *db,                    /* Apply change to \"main\" db of this handle */\n  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */\n  void *pIn,                                          /* First arg for xInput */\n  int(*xFilter)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    const char *zTab              /* Table name */\n  ),\n  int(*xConflict)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */\n    sqlite3_changeset_iter *p     /* Handle describing change and conflict */\n  ),\n  void *pCtx                      /* First argument passed to xConflict */\n);\nSQLITE_API int sqlite3changeset_apply_v2_strm(\n  sqlite3 *db,                    /* Apply change to \"main\" db of this handle */\n  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */\n  void *pIn,                                          /* First arg for xInput */\n  int(*xFilter)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    const char *zTab              /* Table name */\n  ),\n  int(*xConflict)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */\n    sqlite3_changeset_iter *p     /* Handle describing change and conflict */\n  ),\n  void *pCtx,                     /* First argument passed to xConflict */\n  void **ppRebase, int *pnRebase,\n  int flags\n);\nSQLITE_API int sqlite3changeset_concat_strm(\n  int (*xInputA)(void *pIn, void *pData, int *pnData),\n  void *pInA,\n  int (*xInputB)(void *pIn, void *pData, int *pnData),\n  void *pInB,\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut\n);\nSQLITE_API int sqlite3changeset_invert_strm(\n  int (*xInput)(void *pIn, void *pData, int *pnData),\n  void *pIn,\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut\n);\nSQLITE_API int sqlite3changeset_start_strm(\n  sqlite3_changeset_iter **pp,\n  int (*xInput)(void *pIn, void *pData, int *pnData),\n  void *pIn\n);\nSQLITE_API int sqlite3changeset_start_v2_strm(\n  sqlite3_changeset_iter **pp,\n  int (*xInput)(void *pIn, void *pData, int *pnData),\n  void *pIn,\n  int flags\n);\nSQLITE_API int sqlite3session_changeset_strm(\n  sqlite3_session *pSession,\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut\n);\nSQLITE_API int sqlite3session_patchset_strm(\n  sqlite3_session *pSession,\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut\n);\nSQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*, \n    int (*xInput)(void *pIn, void *pData, int *pnData),\n    void *pIn\n);\nSQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,\n    int (*xOutput)(void *pOut, const void *pData, int nData), \n    void *pOut\n);\nSQLITE_API int sqlite3rebaser_rebase_strm(\n  sqlite3_rebaser *pRebaser,\n  int (*xInput)(void *pIn, void *pData, int *pnData),\n  void *pIn,\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut\n);\n\n/*\n** CAPI3REF: Configure global parameters\n**\n** The sqlite3session_config() interface is used to make global configuration\n** changes to the sessions module in order to tune it to the specific needs \n** of the application.\n**\n** The sqlite3session_config() interface is not threadsafe. If it is invoked\n** while any other thread is inside any other sessions method then the\n** results are undefined. Furthermore, if it is invoked after any sessions\n** related objects have been created, the results are also undefined. \n**\n** The first argument to the sqlite3session_config() function must be one\n** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The \n** interpretation of the (void*) value passed as the second parameter and\n** the effect of calling this function depends on the value of the first\n** parameter.\n**\n** <dl>\n** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd>\n**    By default, the sessions module streaming interfaces attempt to input\n**    and output data in approximately 1 KiB chunks. This operand may be used\n**    to set and query the value of this configuration setting. The pointer\n**    passed as the second argument must point to a value of type (int).\n**    If this value is greater than 0, it is used as the new streaming data\n**    chunk size for both input and output. Before returning, the (int) value\n**    pointed to by pArg is set to the final value of the streaming interface\n**    chunk size.\n** </dl>\n**\n** This function returns SQLITE_OK if successful, or an SQLite error code\n** otherwise.\n*/\nSQLITE_API int sqlite3session_config(int op, void *pArg);\n\n/*\n** CAPI3REF: Values for sqlite3session_config().\n*/\n#define SQLITE_SESSION_CONFIG_STRMSIZE 1\n\n/*\n** Make sure we can call this stuff from C++.\n*/\n#if 0\n}\n#endif\n\n#endif  /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */\n\n/******** End of sqlite3session.h *********/\n/******** Begin file fts5.h *********/\n/*\n** 2014 May 31\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** Interfaces to extend FTS5. Using the interfaces defined in this file, \n** FTS5 may be extended with:\n**\n**     * custom tokenizers, and\n**     * custom auxiliary functions.\n*/\n\n\n#ifndef _FTS5_H\n#define _FTS5_H\n\n\n#if 0\nextern \"C\" {\n#endif\n\n/*************************************************************************\n** CUSTOM AUXILIARY FUNCTIONS\n**\n** Virtual table implementations may overload SQL functions by implementing\n** the sqlite3_module.xFindFunction() method.\n*/\n\ntypedef struct Fts5ExtensionApi Fts5ExtensionApi;\ntypedef struct Fts5Context Fts5Context;\ntypedef struct Fts5PhraseIter Fts5PhraseIter;\n\ntypedef void (*fts5_extension_function)(\n  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */\n  Fts5Context *pFts,              /* First arg to pass to pApi functions */\n  sqlite3_context *pCtx,          /* Context for returning result/error */\n  int nVal,                       /* Number of values in apVal[] array */\n  sqlite3_value **apVal           /* Array of trailing arguments */\n);\n\nstruct Fts5PhraseIter {\n  const unsigned char *a;\n  const unsigned char *b;\n};\n\n/*\n** EXTENSION API FUNCTIONS\n**\n** xUserData(pFts):\n**   Return a copy of the context pointer the extension function was \n**   registered with.\n**\n** xColumnTotalSize(pFts, iCol, pnToken):\n**   If parameter iCol is less than zero, set output variable *pnToken\n**   to the total number of tokens in the FTS5 table. Or, if iCol is\n**   non-negative but less than the number of columns in the table, return\n**   the total number of tokens in column iCol, considering all rows in \n**   the FTS5 table.\n**\n**   If parameter iCol is greater than or equal to the number of columns\n**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.\n**   an OOM condition or IO error), an appropriate SQLite error code is \n**   returned.\n**\n** xColumnCount(pFts):\n**   Return the number of columns in the table.\n**\n** xColumnSize(pFts, iCol, pnToken):\n**   If parameter iCol is less than zero, set output variable *pnToken\n**   to the total number of tokens in the current row. Or, if iCol is\n**   non-negative but less than the number of columns in the table, set\n**   *pnToken to the number of tokens in column iCol of the current row.\n**\n**   If parameter iCol is greater than or equal to the number of columns\n**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.\n**   an OOM condition or IO error), an appropriate SQLite error code is \n**   returned.\n**\n**   This function may be quite inefficient if used with an FTS5 table\n**   created with the \"columnsize=0\" option.\n**\n** xColumnText:\n**   This function attempts to retrieve the text of column iCol of the\n**   current document. If successful, (*pz) is set to point to a buffer\n**   containing the text in utf-8 encoding, (*pn) is set to the size in bytes\n**   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,\n**   if an error occurs, an SQLite error code is returned and the final values\n**   of (*pz) and (*pn) are undefined.\n**\n** xPhraseCount:\n**   Returns the number of phrases in the current query expression.\n**\n** xPhraseSize:\n**   Returns the number of tokens in phrase iPhrase of the query. Phrases\n**   are numbered starting from zero.\n**\n** xInstCount:\n**   Set *pnInst to the total number of occurrences of all phrases within\n**   the query within the current row. Return SQLITE_OK if successful, or\n**   an error code (i.e. SQLITE_NOMEM) if an error occurs.\n**\n**   This API can be quite slow if used with an FTS5 table created with the\n**   \"detail=none\" or \"detail=column\" option. If the FTS5 table is created \n**   with either \"detail=none\" or \"detail=column\" and \"content=\" option \n**   (i.e. if it is a contentless table), then this API always returns 0.\n**\n** xInst:\n**   Query for the details of phrase match iIdx within the current row.\n**   Phrase matches are numbered starting from zero, so the iIdx argument\n**   should be greater than or equal to zero and smaller than the value\n**   output by xInstCount().\n**\n**   Usually, output parameter *piPhrase is set to the phrase number, *piCol\n**   to the column in which it occurs and *piOff the token offset of the\n**   first token of the phrase. Returns SQLITE_OK if successful, or an error\n**   code (i.e. SQLITE_NOMEM) if an error occurs.\n**\n**   This API can be quite slow if used with an FTS5 table created with the\n**   \"detail=none\" or \"detail=column\" option. \n**\n** xRowid:\n**   Returns the rowid of the current row.\n**\n** xTokenize:\n**   Tokenize text using the tokenizer belonging to the FTS5 table.\n**\n** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):\n**   This API function is used to query the FTS table for phrase iPhrase\n**   of the current query. Specifically, a query equivalent to:\n**\n**       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid\n**\n**   with $p set to a phrase equivalent to the phrase iPhrase of the\n**   current query is executed. Any column filter that applies to\n**   phrase iPhrase of the current query is included in $p. For each \n**   row visited, the callback function passed as the fourth argument \n**   is invoked. The context and API objects passed to the callback \n**   function may be used to access the properties of each matched row.\n**   Invoking Api.xUserData() returns a copy of the pointer passed as \n**   the third argument to pUserData.\n**\n**   If the callback function returns any value other than SQLITE_OK, the\n**   query is abandoned and the xQueryPhrase function returns immediately.\n**   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.\n**   Otherwise, the error code is propagated upwards.\n**\n**   If the query runs to completion without incident, SQLITE_OK is returned.\n**   Or, if some error occurs before the query completes or is aborted by\n**   the callback, an SQLite error code is returned.\n**\n**\n** xSetAuxdata(pFts5, pAux, xDelete)\n**\n**   Save the pointer passed as the second argument as the extension function's \n**   \"auxiliary data\". The pointer may then be retrieved by the current or any\n**   future invocation of the same fts5 extension function made as part of\n**   the same MATCH query using the xGetAuxdata() API.\n**\n**   Each extension function is allocated a single auxiliary data slot for\n**   each FTS query (MATCH expression). If the extension function is invoked \n**   more than once for a single FTS query, then all invocations share a \n**   single auxiliary data context.\n**\n**   If there is already an auxiliary data pointer when this function is\n**   invoked, then it is replaced by the new pointer. If an xDelete callback\n**   was specified along with the original pointer, it is invoked at this\n**   point.\n**\n**   The xDelete callback, if one is specified, is also invoked on the\n**   auxiliary data pointer after the FTS5 query has finished.\n**\n**   If an error (e.g. an OOM condition) occurs within this function,\n**   the auxiliary data is set to NULL and an error code returned. If the\n**   xDelete parameter was not NULL, it is invoked on the auxiliary data\n**   pointer before returning.\n**\n**\n** xGetAuxdata(pFts5, bClear)\n**\n**   Returns the current auxiliary data pointer for the fts5 extension \n**   function. See the xSetAuxdata() method for details.\n**\n**   If the bClear argument is non-zero, then the auxiliary data is cleared\n**   (set to NULL) before this function returns. In this case the xDelete,\n**   if any, is not invoked.\n**\n**\n** xRowCount(pFts5, pnRow)\n**\n**   This function is used to retrieve the total number of rows in the table.\n**   In other words, the same value that would be returned by:\n**\n**        SELECT count(*) FROM ftstable;\n**\n** xPhraseFirst()\n**   This function is used, along with type Fts5PhraseIter and the xPhraseNext\n**   method, to iterate through all instances of a single query phrase within\n**   the current row. This is the same information as is accessible via the\n**   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient\n**   to use, this API may be faster under some circumstances. To iterate \n**   through instances of phrase iPhrase, use the following code:\n**\n**       Fts5PhraseIter iter;\n**       int iCol, iOff;\n**       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);\n**           iCol>=0;\n**           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)\n**       ){\n**         // An instance of phrase iPhrase at offset iOff of column iCol\n**       }\n**\n**   The Fts5PhraseIter structure is defined above. Applications should not\n**   modify this structure directly - it should only be used as shown above\n**   with the xPhraseFirst() and xPhraseNext() API methods (and by\n**   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).\n**\n**   This API can be quite slow if used with an FTS5 table created with the\n**   \"detail=none\" or \"detail=column\" option. If the FTS5 table is created \n**   with either \"detail=none\" or \"detail=column\" and \"content=\" option \n**   (i.e. if it is a contentless table), then this API always iterates\n**   through an empty set (all calls to xPhraseFirst() set iCol to -1).\n**\n** xPhraseNext()\n**   See xPhraseFirst above.\n**\n** xPhraseFirstColumn()\n**   This function and xPhraseNextColumn() are similar to the xPhraseFirst()\n**   and xPhraseNext() APIs described above. The difference is that instead\n**   of iterating through all instances of a phrase in the current row, these\n**   APIs are used to iterate through the set of columns in the current row\n**   that contain one or more instances of a specified phrase. For example:\n**\n**       Fts5PhraseIter iter;\n**       int iCol;\n**       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);\n**           iCol>=0;\n**           pApi->xPhraseNextColumn(pFts, &iter, &iCol)\n**       ){\n**         // Column iCol contains at least one instance of phrase iPhrase\n**       }\n**\n**   This API can be quite slow if used with an FTS5 table created with the\n**   \"detail=none\" option. If the FTS5 table is created with either \n**   \"detail=none\" \"content=\" option (i.e. if it is a contentless table), \n**   then this API always iterates through an empty set (all calls to \n**   xPhraseFirstColumn() set iCol to -1).\n**\n**   The information accessed using this API and its companion\n**   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext\n**   (or xInst/xInstCount). The chief advantage of this API is that it is\n**   significantly more efficient than those alternatives when used with\n**   \"detail=column\" tables.  \n**\n** xPhraseNextColumn()\n**   See xPhraseFirstColumn above.\n*/\nstruct Fts5ExtensionApi {\n  int iVersion;                   /* Currently always set to 3 */\n\n  void *(*xUserData)(Fts5Context*);\n\n  int (*xColumnCount)(Fts5Context*);\n  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);\n  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);\n\n  int (*xTokenize)(Fts5Context*, \n    const char *pText, int nText, /* Text to tokenize */\n    void *pCtx,                   /* Context passed to xToken() */\n    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */\n  );\n\n  int (*xPhraseCount)(Fts5Context*);\n  int (*xPhraseSize)(Fts5Context*, int iPhrase);\n\n  int (*xInstCount)(Fts5Context*, int *pnInst);\n  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);\n\n  sqlite3_int64 (*xRowid)(Fts5Context*);\n  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);\n  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);\n\n  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,\n    int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)\n  );\n  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));\n  void *(*xGetAuxdata)(Fts5Context*, int bClear);\n\n  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);\n  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);\n\n  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);\n  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);\n};\n\n/* \n** CUSTOM AUXILIARY FUNCTIONS\n*************************************************************************/\n\n/*************************************************************************\n** CUSTOM TOKENIZERS\n**\n** Applications may also register custom tokenizer types. A tokenizer \n** is registered by providing fts5 with a populated instance of the \n** following structure. All structure methods must be defined, setting\n** any member of the fts5_tokenizer struct to NULL leads to undefined\n** behaviour. The structure methods are expected to function as follows:\n**\n** xCreate:\n**   This function is used to allocate and initialize a tokenizer instance.\n**   A tokenizer instance is required to actually tokenize text.\n**\n**   The first argument passed to this function is a copy of the (void*)\n**   pointer provided by the application when the fts5_tokenizer object\n**   was registered with FTS5 (the third argument to xCreateTokenizer()). \n**   The second and third arguments are an array of nul-terminated strings\n**   containing the tokenizer arguments, if any, specified following the\n**   tokenizer name as part of the CREATE VIRTUAL TABLE statement used\n**   to create the FTS5 table.\n**\n**   The final argument is an output variable. If successful, (*ppOut) \n**   should be set to point to the new tokenizer handle and SQLITE_OK\n**   returned. If an error occurs, some value other than SQLITE_OK should\n**   be returned. In this case, fts5 assumes that the final value of *ppOut \n**   is undefined.\n**\n** xDelete:\n**   This function is invoked to delete a tokenizer handle previously\n**   allocated using xCreate(). Fts5 guarantees that this function will\n**   be invoked exactly once for each successful call to xCreate().\n**\n** xTokenize:\n**   This function is expected to tokenize the nText byte string indicated \n**   by argument pText. pText may or may not be nul-terminated. The first\n**   argument passed to this function is a pointer to an Fts5Tokenizer object\n**   returned by an earlier call to xCreate().\n**\n**   The second argument indicates the reason that FTS5 is requesting\n**   tokenization of the supplied text. This is always one of the following\n**   four values:\n**\n**   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into\n**            or removed from the FTS table. The tokenizer is being invoked to\n**            determine the set of tokens to add to (or delete from) the\n**            FTS index.\n**\n**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed \n**            against the FTS index. The tokenizer is being called to tokenize \n**            a bareword or quoted string specified as part of the query.\n**\n**       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as\n**            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is\n**            followed by a \"*\" character, indicating that the last token\n**            returned by the tokenizer will be treated as a token prefix.\n**\n**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to \n**            satisfy an fts5_api.xTokenize() request made by an auxiliary\n**            function. Or an fts5_api.xColumnSize() request made by the same\n**            on a columnsize=0 database.  \n**   </ul>\n**\n**   For each token in the input string, the supplied callback xToken() must\n**   be invoked. The first argument to it should be a copy of the pointer\n**   passed as the second argument to xTokenize(). The third and fourth\n**   arguments are a pointer to a buffer containing the token text, and the\n**   size of the token in bytes. The 4th and 5th arguments are the byte offsets\n**   of the first byte of and first byte immediately following the text from\n**   which the token is derived within the input.\n**\n**   The second argument passed to the xToken() callback (\"tflags\") should\n**   normally be set to 0. The exception is if the tokenizer supports \n**   synonyms. In this case see the discussion below for details.\n**\n**   FTS5 assumes the xToken() callback is invoked for each token in the \n**   order that they occur within the input text.\n**\n**   If an xToken() callback returns any value other than SQLITE_OK, then\n**   the tokenization should be abandoned and the xTokenize() method should\n**   immediately return a copy of the xToken() return value. Or, if the\n**   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,\n**   if an error occurs with the xTokenize() implementation itself, it\n**   may abandon the tokenization and return any error code other than\n**   SQLITE_OK or SQLITE_DONE.\n**\n** SYNONYM SUPPORT\n**\n**   Custom tokenizers may also support synonyms. Consider a case in which a\n**   user wishes to query for a phrase such as \"first place\". Using the \n**   built-in tokenizers, the FTS5 query 'first + place' will match instances\n**   of \"first place\" within the document set, but not alternative forms\n**   such as \"1st place\". In some applications, it would be better to match\n**   all instances of \"first place\" or \"1st place\" regardless of which form\n**   the user specified in the MATCH query text.\n**\n**   There are several ways to approach this in FTS5:\n**\n**   <ol><li> By mapping all synonyms to a single token. In this case, using\n**            the above example, this means that the tokenizer returns the\n**            same token for inputs \"first\" and \"1st\". Say that token is in\n**            fact \"first\", so that when the user inserts the document \"I won\n**            1st place\" entries are added to the index for tokens \"i\", \"won\",\n**            \"first\" and \"place\". If the user then queries for '1st + place',\n**            the tokenizer substitutes \"first\" for \"1st\" and the query works\n**            as expected.\n**\n**       <li> By querying the index for all synonyms of each query term\n**            separately. In this case, when tokenizing query text, the\n**            tokenizer may provide multiple synonyms for a single term \n**            within the document. FTS5 then queries the index for each \n**            synonym individually. For example, faced with the query:\n**\n**   <codeblock>\n**     ... MATCH 'first place'</codeblock>\n**\n**            the tokenizer offers both \"1st\" and \"first\" as synonyms for the\n**            first token in the MATCH query and FTS5 effectively runs a query \n**            similar to:\n**\n**   <codeblock>\n**     ... MATCH '(first OR 1st) place'</codeblock>\n**\n**            except that, for the purposes of auxiliary functions, the query\n**            still appears to contain just two phrases - \"(first OR 1st)\" \n**            being treated as a single phrase.\n**\n**       <li> By adding multiple synonyms for a single term to the FTS index.\n**            Using this method, when tokenizing document text, the tokenizer\n**            provides multiple synonyms for each token. So that when a \n**            document such as \"I won first place\" is tokenized, entries are\n**            added to the FTS index for \"i\", \"won\", \"first\", \"1st\" and\n**            \"place\".\n**\n**            This way, even if the tokenizer does not provide synonyms\n**            when tokenizing query text (it should not - to do so would be\n**            inefficient), it doesn't matter if the user queries for \n**            'first + place' or '1st + place', as there are entries in the\n**            FTS index corresponding to both forms of the first token.\n**   </ol>\n**\n**   Whether it is parsing document or query text, any call to xToken that\n**   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit\n**   is considered to supply a synonym for the previous token. For example,\n**   when parsing the document \"I won first place\", a tokenizer that supports\n**   synonyms would call xToken() 5 times, as follows:\n**\n**   <codeblock>\n**       xToken(pCtx, 0, \"i\",                      1,  0,  1);\n**       xToken(pCtx, 0, \"won\",                    3,  2,  5);\n**       xToken(pCtx, 0, \"first\",                  5,  6, 11);\n**       xToken(pCtx, FTS5_TOKEN_COLOCATED, \"1st\", 3,  6, 11);\n**       xToken(pCtx, 0, \"place\",                  5, 12, 17);\n**</codeblock>\n**\n**   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time\n**   xToken() is called. Multiple synonyms may be specified for a single token\n**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. \n**   There is no limit to the number of synonyms that may be provided for a\n**   single token.\n**\n**   In many cases, method (1) above is the best approach. It does not add \n**   extra data to the FTS index or require FTS5 to query for multiple terms,\n**   so it is efficient in terms of disk space and query speed. However, it\n**   does not support prefix queries very well. If, as suggested above, the\n**   token \"first\" is substituted for \"1st\" by the tokenizer, then the query:\n**\n**   <codeblock>\n**     ... MATCH '1s*'</codeblock>\n**\n**   will not match documents that contain the token \"1st\" (as the tokenizer\n**   will probably not map \"1s\" to any prefix of \"first\").\n**\n**   For full prefix support, method (3) may be preferred. In this case, \n**   because the index contains entries for both \"first\" and \"1st\", prefix\n**   queries such as 'fi*' or '1s*' will match correctly. However, because\n**   extra entries are added to the FTS index, this method uses more space\n**   within the database.\n**\n**   Method (2) offers a midpoint between (1) and (3). Using this method,\n**   a query such as '1s*' will match documents that contain the literal \n**   token \"1st\", but not \"first\" (assuming the tokenizer is not able to\n**   provide synonyms for prefixes). However, a non-prefix query like '1st'\n**   will match against \"1st\" and \"first\". This method does not require\n**   extra disk space, as no extra entries are added to the FTS index. \n**   On the other hand, it may require more CPU cycles to run MATCH queries,\n**   as separate queries of the FTS index are required for each synonym.\n**\n**   When using methods (2) or (3), it is important that the tokenizer only\n**   provide synonyms when tokenizing document text (method (2)) or query\n**   text (method (3)), not both. Doing so will not cause any errors, but is\n**   inefficient.\n*/\ntypedef struct Fts5Tokenizer Fts5Tokenizer;\ntypedef struct fts5_tokenizer fts5_tokenizer;\nstruct fts5_tokenizer {\n  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);\n  void (*xDelete)(Fts5Tokenizer*);\n  int (*xTokenize)(Fts5Tokenizer*, \n      void *pCtx,\n      int flags,            /* Mask of FTS5_TOKENIZE_* flags */\n      const char *pText, int nText, \n      int (*xToken)(\n        void *pCtx,         /* Copy of 2nd argument to xTokenize() */\n        int tflags,         /* Mask of FTS5_TOKEN_* flags */\n        const char *pToken, /* Pointer to buffer containing token */\n        int nToken,         /* Size of token in bytes */\n        int iStart,         /* Byte offset of token within input text */\n        int iEnd            /* Byte offset of end of token within input text */\n      )\n  );\n};\n\n/* Flags that may be passed as the third argument to xTokenize() */\n#define FTS5_TOKENIZE_QUERY     0x0001\n#define FTS5_TOKENIZE_PREFIX    0x0002\n#define FTS5_TOKENIZE_DOCUMENT  0x0004\n#define FTS5_TOKENIZE_AUX       0x0008\n\n/* Flags that may be passed by the tokenizer implementation back to FTS5\n** as the third argument to the supplied xToken callback. */\n#define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */\n\n/*\n** END OF CUSTOM TOKENIZERS\n*************************************************************************/\n\n/*************************************************************************\n** FTS5 EXTENSION REGISTRATION API\n*/\ntypedef struct fts5_api fts5_api;\nstruct fts5_api {\n  int iVersion;                   /* Currently always set to 2 */\n\n  /* Create a new tokenizer */\n  int (*xCreateTokenizer)(\n    fts5_api *pApi,\n    const char *zName,\n    void *pContext,\n    fts5_tokenizer *pTokenizer,\n    void (*xDestroy)(void*)\n  );\n\n  /* Find an existing tokenizer */\n  int (*xFindTokenizer)(\n    fts5_api *pApi,\n    const char *zName,\n    void **ppContext,\n    fts5_tokenizer *pTokenizer\n  );\n\n  /* Create a new auxiliary function */\n  int (*xCreateFunction)(\n    fts5_api *pApi,\n    const char *zName,\n    void *pContext,\n    fts5_extension_function xFunction,\n    void (*xDestroy)(void*)\n  );\n};\n\n/*\n** END OF REGISTRATION API\n*************************************************************************/\n\n#if 0\n}  /* end of the 'extern \"C\"' block */\n#endif\n\n#endif /* _FTS5_H */\n\n/******** End of fts5.h *********/\n\n/************** End of sqlite3.h *********************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n\n/*\n** Include the configuration header output by 'configure' if we're using the\n** autoconf-based build\n*/\n#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)\n/* #include \"config.h\" */\n#define SQLITECONFIG_H 1\n#endif\n\n/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/\n/************** Begin file sqliteLimit.h *************************************/\n/*\n** 2007 May 7\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** \n** This file defines various limits of what SQLite can process.\n*/\n\n/*\n** The maximum length of a TEXT or BLOB in bytes.   This also\n** limits the size of a row in a table or index.\n**\n** The hard limit is the ability of a 32-bit signed integer\n** to count the size: 2^31-1 or 2147483647.\n*/\n#ifndef SQLITE_MAX_LENGTH\n# define SQLITE_MAX_LENGTH 1000000000\n#endif\n\n/*\n** This is the maximum number of\n**\n**    * Columns in a table\n**    * Columns in an index\n**    * Columns in a view\n**    * Terms in the SET clause of an UPDATE statement\n**    * Terms in the result set of a SELECT statement\n**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.\n**    * Terms in the VALUES clause of an INSERT statement\n**\n** The hard upper limit here is 32676.  Most database people will\n** tell you that in a well-normalized database, you usually should\n** not have more than a dozen or so columns in any table.  And if\n** that is the case, there is no point in having more than a few\n** dozen values in any of the other situations described above.\n*/\n#ifndef SQLITE_MAX_COLUMN\n# define SQLITE_MAX_COLUMN 2000\n#endif\n\n/*\n** The maximum length of a single SQL statement in bytes.\n**\n** It used to be the case that setting this value to zero would\n** turn the limit off.  That is no longer true.  It is not possible\n** to turn this limit off.\n*/\n#ifndef SQLITE_MAX_SQL_LENGTH\n# define SQLITE_MAX_SQL_LENGTH 1000000000\n#endif\n\n/*\n** The maximum depth of an expression tree. This is limited to \n** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might \n** want to place more severe limits on the complexity of an \n** expression.\n**\n** A value of 0 used to mean that the limit was not enforced.\n** But that is no longer true.  The limit is now strictly enforced\n** at all times.\n*/\n#ifndef SQLITE_MAX_EXPR_DEPTH\n# define SQLITE_MAX_EXPR_DEPTH 1000\n#endif\n\n/*\n** The maximum number of terms in a compound SELECT statement.\n** The code generator for compound SELECT statements does one\n** level of recursion for each term.  A stack overflow can result\n** if the number of terms is too large.  In practice, most SQL\n** never has more than 3 or 4 terms.  Use a value of 0 to disable\n** any limit on the number of terms in a compount SELECT.\n*/\n#ifndef SQLITE_MAX_COMPOUND_SELECT\n# define SQLITE_MAX_COMPOUND_SELECT 500\n#endif\n\n/*\n** The maximum number of opcodes in a VDBE program.\n** Not currently enforced.\n*/\n#ifndef SQLITE_MAX_VDBE_OP\n# define SQLITE_MAX_VDBE_OP 250000000\n#endif\n\n/*\n** The maximum number of arguments to an SQL function.\n*/\n#ifndef SQLITE_MAX_FUNCTION_ARG\n# define SQLITE_MAX_FUNCTION_ARG 127\n#endif\n\n/*\n** The suggested maximum number of in-memory pages to use for\n** the main database table and for temporary tables.\n**\n** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,\n** which means the cache size is limited to 2048000 bytes of memory.\n** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be\n** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.\n*/\n#ifndef SQLITE_DEFAULT_CACHE_SIZE\n# define SQLITE_DEFAULT_CACHE_SIZE  -2000\n#endif\n\n/*\n** The default number of frames to accumulate in the log file before\n** checkpointing the database in WAL mode.\n*/\n#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT\n# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000\n#endif\n\n/*\n** The maximum number of attached databases.  This must be between 0\n** and 125.  The upper bound of 125 is because the attached databases are\n** counted using a signed 8-bit integer which has a maximum value of 127\n** and we have to allow 2 extra counts for the \"main\" and \"temp\" databases.\n*/\n#ifndef SQLITE_MAX_ATTACHED\n# define SQLITE_MAX_ATTACHED 10\n#endif\n\n\n/*\n** The maximum value of a ?nnn wildcard that the parser will accept.\n** If the value exceeds 32767 then extra space is required for the Expr\n** structure.  But otherwise, we believe that the number can be as large\n** as a signed 32-bit integer can hold.\n*/\n#ifndef SQLITE_MAX_VARIABLE_NUMBER\n# define SQLITE_MAX_VARIABLE_NUMBER 32766\n#endif\n\n/* Maximum page size.  The upper bound on this value is 65536.  This a limit\n** imposed by the use of 16-bit offsets within each page.\n**\n** Earlier versions of SQLite allowed the user to change this value at\n** compile time. This is no longer permitted, on the grounds that it creates\n** a library that is technically incompatible with an SQLite library \n** compiled with a different limit. If a process operating on a database \n** with a page-size of 65536 bytes crashes, then an instance of SQLite \n** compiled with the default page-size limit will not be able to rollback \n** the aborted transaction. This could lead to database corruption.\n*/\n#ifdef SQLITE_MAX_PAGE_SIZE\n# undef SQLITE_MAX_PAGE_SIZE\n#endif\n#define SQLITE_MAX_PAGE_SIZE 65536\n\n\n/*\n** The default size of a database page.\n*/\n#ifndef SQLITE_DEFAULT_PAGE_SIZE\n# define SQLITE_DEFAULT_PAGE_SIZE 4096\n#endif\n#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE\n# undef SQLITE_DEFAULT_PAGE_SIZE\n# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE\n#endif\n\n/*\n** Ordinarily, if no value is explicitly provided, SQLite creates databases\n** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain\n** device characteristics (sector-size and atomic write() support),\n** SQLite may choose a larger value. This constant is the maximum value\n** SQLite will choose on its own.\n*/\n#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE\n# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192\n#endif\n#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE\n# undef SQLITE_MAX_DEFAULT_PAGE_SIZE\n# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE\n#endif\n\n\n/*\n** Maximum number of pages in one database file.\n**\n** This is really just the default value for the max_page_count pragma.\n** This value can be lowered (or raised) at run-time using that the\n** max_page_count macro.\n*/\n#ifndef SQLITE_MAX_PAGE_COUNT\n# define SQLITE_MAX_PAGE_COUNT 1073741823\n#endif\n\n/*\n** Maximum length (in bytes) of the pattern in a LIKE or GLOB\n** operator.\n*/\n#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH\n# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000\n#endif\n\n/*\n** Maximum depth of recursion for triggers.\n**\n** A value of 1 means that a trigger program will not be able to itself\n** fire any triggers. A value of 0 means that no trigger programs at all \n** may be executed.\n*/\n#ifndef SQLITE_MAX_TRIGGER_DEPTH\n# define SQLITE_MAX_TRIGGER_DEPTH 1000\n#endif\n\n/************** End of sqliteLimit.h *****************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n\n/* Disable nuisance warnings on Borland compilers */\n#if defined(__BORLANDC__)\n#pragma warn -rch /* unreachable code */\n#pragma warn -ccc /* Condition is always true or false */\n#pragma warn -aus /* Assigned value is never used */\n#pragma warn -csu /* Comparing signed and unsigned */\n#pragma warn -spa /* Suspicious pointer arithmetic */\n#endif\n\n/*\n** WAL mode depends on atomic aligned 32-bit loads and stores in a few\n** places.  The following macros try to make this explicit.\n*/\n#ifndef __has_feature\n# define __has_feature(x) 0       /* compatibility with non-clang compilers */\n#endif\n#if GCC_VERSION>=4007000 || __has_feature(c_atomic)\n# define AtomicLoad(PTR)       __atomic_load_n((PTR),__ATOMIC_RELAXED)\n# define AtomicStore(PTR,VAL)  __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)\n#else\n# define AtomicLoad(PTR)       (*(PTR))\n# define AtomicStore(PTR,VAL)  (*(PTR) = (VAL))\n#endif\n\n/*\n** Include standard header files as necessary\n*/\n#ifdef HAVE_STDINT_H\n#include <stdint.h>\n#endif\n#ifdef HAVE_INTTYPES_H\n#include <inttypes.h>\n#endif\n\n/*\n** The following macros are used to cast pointers to integers and\n** integers to pointers.  The way you do this varies from one compiler\n** to the next, so we have developed the following set of #if statements\n** to generate appropriate macros for a wide range of compilers.\n**\n** The correct \"ANSI\" way to do this is to use the intptr_t type.\n** Unfortunately, that typedef is not available on all compilers, or\n** if it is available, it requires an #include of specific headers\n** that vary from one machine to the next.\n**\n** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on\n** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).\n** So we have to define the macros in different ways depending on the\n** compiler.\n*/\n#if defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */\n# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))\n# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))\n#elif defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */\n# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))\n# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))\n#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */\n# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])\n# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))\n#else                          /* Generates a warning - but it always works */\n# define SQLITE_INT_TO_PTR(X)  ((void*)(X))\n# define SQLITE_PTR_TO_INT(X)  ((int)(X))\n#endif\n\n/*\n** A macro to hint to the compiler that a function should not be\n** inlined.\n*/\n#if defined(__GNUC__)\n#  define SQLITE_NOINLINE  __attribute__((noinline))\n#elif defined(_MSC_VER) && _MSC_VER>=1310\n#  define SQLITE_NOINLINE  __declspec(noinline)\n#else\n#  define SQLITE_NOINLINE\n#endif\n\n/*\n** Make sure that the compiler intrinsics we desire are enabled when\n** compiling with an appropriate version of MSVC unless prevented by\n** the SQLITE_DISABLE_INTRINSIC define.\n*/\n#if !defined(SQLITE_DISABLE_INTRINSIC)\n#  if defined(_MSC_VER) && _MSC_VER>=1400\n#    if !defined(_WIN32_WCE)\n#      include <intrin.h>\n#      pragma intrinsic(_byteswap_ushort)\n#      pragma intrinsic(_byteswap_ulong)\n#      pragma intrinsic(_byteswap_uint64)\n#      pragma intrinsic(_ReadWriteBarrier)\n#    else\n#      include <cmnintrin.h>\n#    endif\n#  endif\n#endif\n\n/*\n** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.\n** 0 means mutexes are permanently disable and the library is never\n** threadsafe.  1 means the library is serialized which is the highest\n** level of threadsafety.  2 means the library is multithreaded - multiple\n** threads can use SQLite as long as no two threads try to use the same\n** database connection at the same time.\n**\n** Older versions of SQLite used an optional THREADSAFE macro.\n** We support that for legacy.\n**\n** To ensure that the correct value of \"THREADSAFE\" is reported when querying\n** for compile-time options at runtime (e.g. \"PRAGMA compile_options\"), this\n** logic is partially replicated in ctime.c. If it is updated here, it should\n** also be updated there.\n*/\n#if !defined(SQLITE_THREADSAFE)\n# if defined(THREADSAFE)\n#   define SQLITE_THREADSAFE THREADSAFE\n# else\n#   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */\n# endif\n#endif\n\n/*\n** Powersafe overwrite is on by default.  But can be turned off using\n** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.\n*/\n#ifndef SQLITE_POWERSAFE_OVERWRITE\n# define SQLITE_POWERSAFE_OVERWRITE 1\n#endif\n\n/*\n** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by\n** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in\n** which case memory allocation statistics are disabled by default.\n*/\n#if !defined(SQLITE_DEFAULT_MEMSTATUS)\n# define SQLITE_DEFAULT_MEMSTATUS 1\n#endif\n\n/*\n** Exactly one of the following macros must be defined in order to\n** specify which memory allocation subsystem to use.\n**\n**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()\n**     SQLITE_WIN32_MALLOC           // Use Win32 native heap API\n**     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails\n**     SQLITE_MEMDEBUG               // Debugging version of system malloc()\n**\n** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the\n** assert() macro is enabled, each call into the Win32 native heap subsystem\n** will cause HeapValidate to be called.  If heap validation should fail, an\n** assertion will be triggered.\n**\n** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as\n** the default.\n*/\n#if defined(SQLITE_SYSTEM_MALLOC) \\\n  + defined(SQLITE_WIN32_MALLOC) \\\n  + defined(SQLITE_ZERO_MALLOC) \\\n  + defined(SQLITE_MEMDEBUG)>1\n# error \"Two or more of the following compile-time configuration options\\\n are defined but at most one is allowed:\\\n SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\\\n SQLITE_ZERO_MALLOC\"\n#endif\n#if defined(SQLITE_SYSTEM_MALLOC) \\\n  + defined(SQLITE_WIN32_MALLOC) \\\n  + defined(SQLITE_ZERO_MALLOC) \\\n  + defined(SQLITE_MEMDEBUG)==0\n# define SQLITE_SYSTEM_MALLOC 1\n#endif\n\n/*\n** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the\n** sizes of memory allocations below this value where possible.\n*/\n#if !defined(SQLITE_MALLOC_SOFT_LIMIT)\n# define SQLITE_MALLOC_SOFT_LIMIT 1024\n#endif\n\n/*\n** We need to define _XOPEN_SOURCE as follows in order to enable\n** recursive mutexes on most Unix systems and fchmod() on OpenBSD.\n** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit\n** it.\n*/\n#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)\n#  define _XOPEN_SOURCE 600\n#endif\n\n/*\n** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that\n** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,\n** make it true by defining or undefining NDEBUG.\n**\n** Setting NDEBUG makes the code smaller and faster by disabling the\n** assert() statements in the code.  So we want the default action\n** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG\n** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out\n** feature.\n*/\n#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)\n# define NDEBUG 1\n#endif\n#if defined(NDEBUG) && defined(SQLITE_DEBUG)\n# undef NDEBUG\n#endif\n\n/*\n** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.\n*/\n#if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)\n# define SQLITE_ENABLE_EXPLAIN_COMMENTS 1\n#endif\n\n/*\n** The testcase() macro is used to aid in coverage testing.  When\n** doing coverage testing, the condition inside the argument to\n** testcase() must be evaluated both true and false in order to\n** get full branch coverage.  The testcase() macro is inserted\n** to help ensure adequate test coverage in places where simple\n** condition/decision coverage is inadequate.  For example, testcase()\n** can be used to make sure boundary values are tested.  For\n** bitmask tests, testcase() can be used to make sure each bit\n** is significant and used at least once.  On switch statements\n** where multiple cases go to the same block of code, testcase()\n** can insure that all cases are evaluated.\n**\n*/\n#ifdef SQLITE_COVERAGE_TEST\nSQLITE_PRIVATE   void sqlite3Coverage(int);\n# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }\n#else\n# define testcase(X)\n#endif\n\n/*\n** The TESTONLY macro is used to enclose variable declarations or\n** other bits of code that are needed to support the arguments\n** within testcase() and assert() macros.\n*/\n#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)\n# define TESTONLY(X)  X\n#else\n# define TESTONLY(X)\n#endif\n\n/*\n** Sometimes we need a small amount of code such as a variable initialization\n** to setup for a later assert() statement.  We do not want this code to\n** appear when assert() is disabled.  The following macro is therefore\n** used to contain that setup code.  The \"VVA\" acronym stands for\n** \"Verification, Validation, and Accreditation\".  In other words, the\n** code within VVA_ONLY() will only run during verification processes.\n*/\n#ifndef NDEBUG\n# define VVA_ONLY(X)  X\n#else\n# define VVA_ONLY(X)\n#endif\n\n/*\n** The ALWAYS and NEVER macros surround boolean expressions which\n** are intended to always be true or false, respectively.  Such\n** expressions could be omitted from the code completely.  But they\n** are included in a few cases in order to enhance the resilience\n** of SQLite to unexpected behavior - to make the code \"self-healing\"\n** or \"ductile\" rather than being \"brittle\" and crashing at the first\n** hint of unplanned behavior.\n**\n** In other words, ALWAYS and NEVER are added for defensive code.\n**\n** When doing coverage testing ALWAYS and NEVER are hard-coded to\n** be true and false so that the unreachable code they specify will\n** not be counted as untested code.\n*/\n#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)\n# define ALWAYS(X)      (1)\n# define NEVER(X)       (0)\n#elif !defined(NDEBUG)\n# define ALWAYS(X)      ((X)?1:(assert(0),0))\n# define NEVER(X)       ((X)?(assert(0),1):0)\n#else\n# define ALWAYS(X)      (X)\n# define NEVER(X)       (X)\n#endif\n\n/*\n** The harmless(X) macro indicates that expression X is usually false\n** but can be true without causing any problems, but we don't know of\n** any way to cause X to be true.\n**\n** In debugging and testing builds, this macro will abort if X is ever\n** true.  In this way, developers are alerted to a possible test case\n** that causes X to be true.  If a harmless macro ever fails, that is\n** an opportunity to change the macro into a testcase() and add a new\n** test case to the test suite.\n**\n** For normal production builds, harmless(X) is a no-op, since it does\n** not matter whether expression X is true or false.\n*/\n#ifdef SQLITE_DEBUG\n# define harmless(X)  assert(!(X));\n#else\n# define harmless(X)\n#endif\n\n/*\n** Some conditionals are optimizations only.  In other words, if the\n** conditionals are replaced with a constant 1 (true) or 0 (false) then\n** the correct answer is still obtained, though perhaps not as quickly.\n**\n** The following macros mark these optimizations conditionals.\n*/\n#if defined(SQLITE_MUTATION_TEST)\n# define OK_IF_ALWAYS_TRUE(X)  (1)\n# define OK_IF_ALWAYS_FALSE(X) (0)\n#else\n# define OK_IF_ALWAYS_TRUE(X)  (X)\n# define OK_IF_ALWAYS_FALSE(X) (X)\n#endif\n\n/*\n** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is\n** defined.  We need to defend against those failures when testing with\n** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches\n** during a normal build.  The following macro can be used to disable tests\n** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.\n*/\n#if defined(SQLITE_TEST_REALLOC_STRESS)\n# define ONLY_IF_REALLOC_STRESS(X)  (X)\n#elif !defined(NDEBUG)\n# define ONLY_IF_REALLOC_STRESS(X)  ((X)?(assert(0),1):0)\n#else\n# define ONLY_IF_REALLOC_STRESS(X)  (0)\n#endif\n\n/*\n** Declarations used for tracing the operating system interfaces.\n*/\n#if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \\\n    (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)\n  extern int sqlite3OSTrace;\n# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X\n# define SQLITE_HAVE_OS_TRACE\n#else\n# define OSTRACE(X)\n# undef  SQLITE_HAVE_OS_TRACE\n#endif\n\n/*\n** Is the sqlite3ErrName() function needed in the build?  Currently,\n** it is needed by \"mutex_w32.c\" (when debugging), \"os_win.c\" (when\n** OSTRACE is enabled), and by several \"test*.c\" files (which are\n** compiled using SQLITE_TEST).\n*/\n#if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \\\n    (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)\n# define SQLITE_NEED_ERR_NAME\n#else\n# undef  SQLITE_NEED_ERR_NAME\n#endif\n\n/*\n** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN\n*/\n#ifdef SQLITE_OMIT_EXPLAIN\n# undef SQLITE_ENABLE_EXPLAIN_COMMENTS\n#endif\n\n/*\n** Return true (non-zero) if the input is an integer that is too large\n** to fit in 32-bits.  This macro is used inside of various testcase()\n** macros to verify that we have tested SQLite for large-file support.\n*/\n#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)\n\n/*\n** The macro unlikely() is a hint that surrounds a boolean\n** expression that is usually false.  Macro likely() surrounds\n** a boolean expression that is usually true.  These hints could,\n** in theory, be used by the compiler to generate better code, but\n** currently they are just comments for human readers.\n*/\n#define likely(X)    (X)\n#define unlikely(X)  (X)\n\n/************** Include hash.h in the middle of sqliteInt.h ******************/\n/************** Begin file hash.h ********************************************/\n/*\n** 2001 September 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This is the header file for the generic hash-table implementation\n** used in SQLite.\n*/\n#ifndef SQLITE_HASH_H\n#define SQLITE_HASH_H\n\n/* Forward declarations of structures. */\ntypedef struct Hash Hash;\ntypedef struct HashElem HashElem;\n\n/* A complete hash table is an instance of the following structure.\n** The internals of this structure are intended to be opaque -- client\n** code should not attempt to access or modify the fields of this structure\n** directly.  Change this structure only by using the routines below.\n** However, some of the \"procedures\" and \"functions\" for modifying and\n** accessing this structure are really macros, so we can't really make\n** this structure opaque.\n**\n** All elements of the hash table are on a single doubly-linked list.\n** Hash.first points to the head of this list.\n**\n** There are Hash.htsize buckets.  Each bucket points to a spot in\n** the global doubly-linked list.  The contents of the bucket are the\n** element pointed to plus the next _ht.count-1 elements in the list.\n**\n** Hash.htsize and Hash.ht may be zero.  In that case lookup is done\n** by a linear search of the global list.  For small tables, the \n** Hash.ht table is never allocated because if there are few elements\n** in the table, it is faster to do a linear search than to manage\n** the hash table.\n*/\nstruct Hash {\n  unsigned int htsize;      /* Number of buckets in the hash table */\n  unsigned int count;       /* Number of entries in this table */\n  HashElem *first;          /* The first element of the array */\n  struct _ht {              /* the hash table */\n    unsigned int count;        /* Number of entries with this hash */\n    HashElem *chain;           /* Pointer to first entry with this hash */\n  } *ht;\n};\n\n/* Each element in the hash table is an instance of the following \n** structure.  All elements are stored on a single doubly-linked list.\n**\n** Again, this structure is intended to be opaque, but it can't really\n** be opaque because it is used by macros.\n*/\nstruct HashElem {\n  HashElem *next, *prev;       /* Next and previous elements in the table */\n  void *data;                  /* Data associated with this element */\n  const char *pKey;            /* Key associated with this element */\n};\n\n/*\n** Access routines.  To delete, insert a NULL pointer.\n*/\nSQLITE_PRIVATE void sqlite3HashInit(Hash*);\nSQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);\nSQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);\nSQLITE_PRIVATE void sqlite3HashClear(Hash*);\n\n/*\n** Macros for looping over all elements of a hash table.  The idiom is\n** like this:\n**\n**   Hash h;\n**   HashElem *p;\n**   ...\n**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){\n**     SomeStructure *pData = sqliteHashData(p);\n**     // do something with pData\n**   }\n*/\n#define sqliteHashFirst(H)  ((H)->first)\n#define sqliteHashNext(E)   ((E)->next)\n#define sqliteHashData(E)   ((E)->data)\n/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */\n/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */\n\n/*\n** Number of entries in a hash table\n*/\n/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */\n\n#endif /* SQLITE_HASH_H */\n\n/************** End of hash.h ************************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n/************** Include parse.h in the middle of sqliteInt.h *****************/\n/************** Begin file parse.h *******************************************/\n#define TK_SEMI                             1\n#define TK_EXPLAIN                          2\n#define TK_QUERY                            3\n#define TK_PLAN                             4\n#define TK_BEGIN                            5\n#define TK_TRANSACTION                      6\n#define TK_DEFERRED                         7\n#define TK_IMMEDIATE                        8\n#define TK_EXCLUSIVE                        9\n#define TK_COMMIT                          10\n#define TK_END                             11\n#define TK_ROLLBACK                        12\n#define TK_SAVEPOINT                       13\n#define TK_RELEASE                         14\n#define TK_TO                              15\n#define TK_TABLE                           16\n#define TK_CREATE                          17\n#define TK_IF                              18\n#define TK_NOT                             19\n#define TK_EXISTS                          20\n#define TK_TEMP                            21\n#define TK_LP                              22\n#define TK_RP                              23\n#define TK_AS                              24\n#define TK_WITHOUT                         25\n#define TK_COMMA                           26\n#define TK_ABORT                           27\n#define TK_ACTION                          28\n#define TK_AFTER                           29\n#define TK_ANALYZE                         30\n#define TK_ASC                             31\n#define TK_ATTACH                          32\n#define TK_BEFORE                          33\n#define TK_BY                              34\n#define TK_CASCADE                         35\n#define TK_CAST                            36\n#define TK_CONFLICT                        37\n#define TK_DATABASE                        38\n#define TK_DESC                            39\n#define TK_DETACH                          40\n#define TK_EACH                            41\n#define TK_FAIL                            42\n#define TK_OR                              43\n#define TK_AND                             44\n#define TK_IS                              45\n#define TK_MATCH                           46\n#define TK_LIKE_KW                         47\n#define TK_BETWEEN                         48\n#define TK_IN                              49\n#define TK_ISNULL                          50\n#define TK_NOTNULL                         51\n#define TK_NE                              52\n#define TK_EQ                              53\n#define TK_GT                              54\n#define TK_LE                              55\n#define TK_LT                              56\n#define TK_GE                              57\n#define TK_ESCAPE                          58\n#define TK_ID                              59\n#define TK_COLUMNKW                        60\n#define TK_DO                              61\n#define TK_FOR                             62\n#define TK_IGNORE                          63\n#define TK_INITIALLY                       64\n#define TK_INSTEAD                         65\n#define TK_NO                              66\n#define TK_KEY                             67\n#define TK_OF                              68\n#define TK_OFFSET                          69\n#define TK_PRAGMA                          70\n#define TK_RAISE                           71\n#define TK_RECURSIVE                       72\n#define TK_REPLACE                         73\n#define TK_RESTRICT                        74\n#define TK_ROW                             75\n#define TK_ROWS                            76\n#define TK_TRIGGER                         77\n#define TK_VACUUM                          78\n#define TK_VIEW                            79\n#define TK_VIRTUAL                         80\n#define TK_WITH                            81\n#define TK_NULLS                           82\n#define TK_FIRST                           83\n#define TK_LAST                            84\n#define TK_CURRENT                         85\n#define TK_FOLLOWING                       86\n#define TK_PARTITION                       87\n#define TK_PRECEDING                       88\n#define TK_RANGE                           89\n#define TK_UNBOUNDED                       90\n#define TK_EXCLUDE                         91\n#define TK_GROUPS                          92\n#define TK_OTHERS                          93\n#define TK_TIES                            94\n#define TK_GENERATED                       95\n#define TK_ALWAYS                          96\n#define TK_REINDEX                         97\n#define TK_RENAME                          98\n#define TK_CTIME_KW                        99\n#define TK_ANY                            100\n#define TK_BITAND                         101\n#define TK_BITOR                          102\n#define TK_LSHIFT                         103\n#define TK_RSHIFT                         104\n#define TK_PLUS                           105\n#define TK_MINUS                          106\n#define TK_STAR                           107\n#define TK_SLASH                          108\n#define TK_REM                            109\n#define TK_CONCAT                         110\n#define TK_COLLATE                        111\n#define TK_BITNOT                         112\n#define TK_ON                             113\n#define TK_INDEXED                        114\n#define TK_STRING                         115\n#define TK_JOIN_KW                        116\n#define TK_CONSTRAINT                     117\n#define TK_DEFAULT                        118\n#define TK_NULL                           119\n#define TK_PRIMARY                        120\n#define TK_UNIQUE                         121\n#define TK_CHECK                          122\n#define TK_REFERENCES                     123\n#define TK_AUTOINCR                       124\n#define TK_INSERT                         125\n#define TK_DELETE                         126\n#define TK_UPDATE                         127\n#define TK_SET                            128\n#define TK_DEFERRABLE                     129\n#define TK_FOREIGN                        130\n#define TK_DROP                           131\n#define TK_UNION                          132\n#define TK_ALL                            133\n#define TK_EXCEPT                         134\n#define TK_INTERSECT                      135\n#define TK_SELECT                         136\n#define TK_VALUES                         137\n#define TK_DISTINCT                       138\n#define TK_DOT                            139\n#define TK_FROM                           140\n#define TK_JOIN                           141\n#define TK_USING                          142\n#define TK_ORDER                          143\n#define TK_GROUP                          144\n#define TK_HAVING                         145\n#define TK_LIMIT                          146\n#define TK_WHERE                          147\n#define TK_INTO                           148\n#define TK_NOTHING                        149\n#define TK_FLOAT                          150\n#define TK_BLOB                           151\n#define TK_INTEGER                        152\n#define TK_VARIABLE                       153\n#define TK_CASE                           154\n#define TK_WHEN                           155\n#define TK_THEN                           156\n#define TK_ELSE                           157\n#define TK_INDEX                          158\n#define TK_ALTER                          159\n#define TK_ADD                            160\n#define TK_WINDOW                         161\n#define TK_OVER                           162\n#define TK_FILTER                         163\n#define TK_COLUMN                         164\n#define TK_AGG_FUNCTION                   165\n#define TK_AGG_COLUMN                     166\n#define TK_TRUEFALSE                      167\n#define TK_ISNOT                          168\n#define TK_FUNCTION                       169\n#define TK_UMINUS                         170\n#define TK_UPLUS                          171\n#define TK_TRUTH                          172\n#define TK_REGISTER                       173\n#define TK_VECTOR                         174\n#define TK_SELECT_COLUMN                  175\n#define TK_IF_NULL_ROW                    176\n#define TK_ASTERISK                       177\n#define TK_SPAN                           178\n#define TK_SPACE                          179\n#define TK_ILLEGAL                        180\n\n/************** End of parse.h ***********************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n#include <stddef.h>\n\n/*\n** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.\n** This allows better measurements of where memcpy() is used when running\n** cachegrind.  But this macro version of memcpy() is very slow so it\n** should not be used in production.  This is a performance measurement\n** hack only.\n*/\n#ifdef SQLITE_INLINE_MEMCPY\n# define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\\\n                        int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}\n#endif\n\n/*\n** If compiling for a processor that lacks floating point support,\n** substitute integer for floating-point\n*/\n#ifdef SQLITE_OMIT_FLOATING_POINT\n# define double sqlite_int64\n# define float sqlite_int64\n# define LONGDOUBLE_TYPE sqlite_int64\n# ifndef SQLITE_BIG_DBL\n#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)\n# endif\n# define SQLITE_OMIT_DATETIME_FUNCS 1\n# define SQLITE_OMIT_TRACE 1\n# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT\n# undef SQLITE_HAVE_ISNAN\n#endif\n#ifndef SQLITE_BIG_DBL\n# define SQLITE_BIG_DBL (1e99)\n#endif\n\n/*\n** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0\n** afterward. Having this macro allows us to cause the C compiler\n** to omit code used by TEMP tables without messy #ifndef statements.\n*/\n#ifdef SQLITE_OMIT_TEMPDB\n#define OMIT_TEMPDB 1\n#else\n#define OMIT_TEMPDB 0\n#endif\n\n/*\n** The \"file format\" number is an integer that is incremented whenever\n** the VDBE-level file format changes.  The following macros define the\n** the default file format for new databases and the maximum file format\n** that the library can read.\n*/\n#define SQLITE_MAX_FILE_FORMAT 4\n#ifndef SQLITE_DEFAULT_FILE_FORMAT\n# define SQLITE_DEFAULT_FILE_FORMAT 4\n#endif\n\n/*\n** Determine whether triggers are recursive by default.  This can be\n** changed at run-time using a pragma.\n*/\n#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS\n# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0\n#endif\n\n/*\n** Provide a default value for SQLITE_TEMP_STORE in case it is not specified\n** on the command-line\n*/\n#ifndef SQLITE_TEMP_STORE\n# define SQLITE_TEMP_STORE 1\n#endif\n\n/*\n** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if\n** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it\n** to zero.\n*/\n#if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0\n# undef SQLITE_MAX_WORKER_THREADS\n# define SQLITE_MAX_WORKER_THREADS 0\n#endif\n#ifndef SQLITE_MAX_WORKER_THREADS\n# define SQLITE_MAX_WORKER_THREADS 8\n#endif\n#ifndef SQLITE_DEFAULT_WORKER_THREADS\n# define SQLITE_DEFAULT_WORKER_THREADS 0\n#endif\n#if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS\n# undef SQLITE_MAX_WORKER_THREADS\n# define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS\n#endif\n\n/*\n** The default initial allocation for the pagecache when using separate\n** pagecaches for each database connection.  A positive number is the\n** number of pages.  A negative number N translations means that a buffer\n** of -1024*N bytes is allocated and used for as many pages as it will hold.\n**\n** The default value of \"20\" was choosen to minimize the run-time of the\n** speedtest1 test program with options: --shrink-memory --reprepare\n*/\n#ifndef SQLITE_DEFAULT_PCACHE_INITSZ\n# define SQLITE_DEFAULT_PCACHE_INITSZ 20\n#endif\n\n/*\n** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option.\n*/\n#ifndef SQLITE_DEFAULT_SORTERREF_SIZE\n# define SQLITE_DEFAULT_SORTERREF_SIZE 0x7fffffff\n#endif\n\n/*\n** The compile-time options SQLITE_MMAP_READWRITE and \n** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.\n** You must choose one or the other (or neither) but not both.\n*/\n#if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)\n#error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE\n#endif\n\n/*\n** GCC does not define the offsetof() macro so we'll have to do it\n** ourselves.\n*/\n#ifndef offsetof\n#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))\n#endif\n\n/*\n** Macros to compute minimum and maximum of two numbers.\n*/\n#ifndef MIN\n# define MIN(A,B) ((A)<(B)?(A):(B))\n#endif\n#ifndef MAX\n# define MAX(A,B) ((A)>(B)?(A):(B))\n#endif\n\n/*\n** Swap two objects of type TYPE.\n*/\n#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}\n\n/*\n** Check to see if this machine uses EBCDIC.  (Yes, believe it or\n** not, there are still machines out there that use EBCDIC.)\n*/\n#if 'A' == '\\301'\n# define SQLITE_EBCDIC 1\n#else\n# define SQLITE_ASCII 1\n#endif\n\n/*\n** Integers of known sizes.  These typedefs might change for architectures\n** where the sizes very.  Preprocessor macros are available so that the\n** types can be conveniently redefined at compile-type.  Like this:\n**\n**         cc '-DUINTPTR_TYPE=long long int' ...\n*/\n#ifndef UINT32_TYPE\n# ifdef HAVE_UINT32_T\n#  define UINT32_TYPE uint32_t\n# else\n#  define UINT32_TYPE unsigned int\n# endif\n#endif\n#ifndef UINT16_TYPE\n# ifdef HAVE_UINT16_T\n#  define UINT16_TYPE uint16_t\n# else\n#  define UINT16_TYPE unsigned short int\n# endif\n#endif\n#ifndef INT16_TYPE\n# ifdef HAVE_INT16_T\n#  define INT16_TYPE int16_t\n# else\n#  define INT16_TYPE short int\n# endif\n#endif\n#ifndef UINT8_TYPE\n# ifdef HAVE_UINT8_T\n#  define UINT8_TYPE uint8_t\n# else\n#  define UINT8_TYPE unsigned char\n# endif\n#endif\n#ifndef INT8_TYPE\n# ifdef HAVE_INT8_T\n#  define INT8_TYPE int8_t\n# else\n#  define INT8_TYPE signed char\n# endif\n#endif\n#ifndef LONGDOUBLE_TYPE\n# define LONGDOUBLE_TYPE long double\n#endif\ntypedef sqlite_int64 i64;          /* 8-byte signed integer */\ntypedef sqlite_uint64 u64;         /* 8-byte unsigned integer */\ntypedef UINT32_TYPE u32;           /* 4-byte unsigned integer */\ntypedef UINT16_TYPE u16;           /* 2-byte unsigned integer */\ntypedef INT16_TYPE i16;            /* 2-byte signed integer */\ntypedef UINT8_TYPE u8;             /* 1-byte unsigned integer */\ntypedef INT8_TYPE i8;              /* 1-byte signed integer */\n\n/*\n** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value\n** that can be stored in a u32 without loss of data.  The value\n** is 0x00000000ffffffff.  But because of quirks of some compilers, we\n** have to specify the value in the less intuitive manner shown:\n*/\n#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)\n\n/*\n** The datatype used to store estimates of the number of rows in a\n** table or index.  This is an unsigned integer type.  For 99.9% of\n** the world, a 32-bit integer is sufficient.  But a 64-bit integer\n** can be used at compile-time if desired.\n*/\n#ifdef SQLITE_64BIT_STATS\n typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */\n#else\n typedef u32 tRowcnt;    /* 32-bit is the default */\n#endif\n\n/*\n** Estimated quantities used for query planning are stored as 16-bit\n** logarithms.  For quantity X, the value stored is 10*log2(X).  This\n** gives a possible range of values of approximately 1.0e986 to 1e-986.\n** But the allowed values are \"grainy\".  Not every value is representable.\n** For example, quantities 16 and 17 are both represented by a LogEst\n** of 40.  However, since LogEst quantities are suppose to be estimates,\n** not exact values, this imprecision is not a problem.\n**\n** \"LogEst\" is short for \"Logarithmic Estimate\".\n**\n** Examples:\n**      1 -> 0              20 -> 43          10000 -> 132\n**      2 -> 10             25 -> 46          25000 -> 146\n**      3 -> 16            100 -> 66        1000000 -> 199\n**      4 -> 20           1000 -> 99        1048576 -> 200\n**     10 -> 33           1024 -> 100    4294967296 -> 320\n**\n** The LogEst can be negative to indicate fractional values.\n** Examples:\n**\n**    0.5 -> -10           0.1 -> -33        0.0625 -> -40\n*/\ntypedef INT16_TYPE LogEst;\n\n/*\n** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer\n*/\n#ifndef SQLITE_PTRSIZE\n# if defined(__SIZEOF_POINTER__)\n#   define SQLITE_PTRSIZE __SIZEOF_POINTER__\n# elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \\\n       defined(_M_ARM)   || defined(__arm__)    || defined(__x86)   ||    \\\n      (defined(__TOS_AIX__) && !defined(__64BIT__))\n#   define SQLITE_PTRSIZE 4\n# else\n#   define SQLITE_PTRSIZE 8\n# endif\n#endif\n\n/* The uptr type is an unsigned integer large enough to hold a pointer\n*/\n#if defined(HAVE_STDINT_H)\n  typedef uintptr_t uptr;\n#elif SQLITE_PTRSIZE==4\n  typedef u32 uptr;\n#else\n  typedef u64 uptr;\n#endif\n\n/*\n** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to\n** something between S (inclusive) and E (exclusive).\n**\n** In other words, S is a buffer and E is a pointer to the first byte after\n** the end of buffer S.  This macro returns true if P points to something\n** contained within the buffer S.\n*/\n#define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))\n\n\n/*\n** Macros to determine whether the machine is big or little endian,\n** and whether or not that determination is run-time or compile-time.\n**\n** For best performance, an attempt is made to guess at the byte-order\n** using C-preprocessor macros.  If that is unsuccessful, or if\n** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined\n** at run-time.\n*/\n#ifndef SQLITE_BYTEORDER\n# if defined(i386)      || defined(__i386__)      || defined(_M_IX86) ||    \\\n     defined(__x86_64)  || defined(__x86_64__)    || defined(_M_X64)  ||    \\\n     defined(_M_AMD64)  || defined(_M_ARM)        || defined(__x86)   ||    \\\n     defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)\n#   define SQLITE_BYTEORDER    1234\n# elif defined(sparc)     || defined(__ppc__) || \\\n       defined(__ARMEB__) || defined(__AARCH64EB__)\n#   define SQLITE_BYTEORDER    4321\n# else\n#   define SQLITE_BYTEORDER 0\n# endif\n#endif\n#if SQLITE_BYTEORDER==4321\n# define SQLITE_BIGENDIAN    1\n# define SQLITE_LITTLEENDIAN 0\n# define SQLITE_UTF16NATIVE  SQLITE_UTF16BE\n#elif SQLITE_BYTEORDER==1234\n# define SQLITE_BIGENDIAN    0\n# define SQLITE_LITTLEENDIAN 1\n# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE\n#else\n# ifdef SQLITE_AMALGAMATION\n  const int sqlite3one = 1;\n# else\n  extern const int sqlite3one;\n# endif\n# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)\n# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)\n# define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)\n#endif\n\n/*\n** Constants for the largest and smallest possible 64-bit signed integers.\n** These macros are designed to work correctly on both 32-bit and 64-bit\n** compilers.\n*/\n#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))\n#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)\n\n/*\n** Round up a number to the next larger multiple of 8.  This is used\n** to force 8-byte alignment on 64-bit architectures.\n*/\n#define ROUND8(x)     (((x)+7)&~7)\n\n/*\n** Round down to the nearest multiple of 8\n*/\n#define ROUNDDOWN8(x) ((x)&~7)\n\n/*\n** Assert that the pointer X is aligned to an 8-byte boundary.  This\n** macro is used only within assert() to verify that the code gets\n** all alignment restrictions correct.\n**\n** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the\n** underlying malloc() implementation might return us 4-byte aligned\n** pointers.  In that case, only verify 4-byte alignment.\n*/\n#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC\n# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)\n#else\n# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)\n#endif\n\n/*\n** Disable MMAP on platforms where it is known to not work\n*/\n#if defined(__OpenBSD__) || defined(__QNXNTO__)\n# undef SQLITE_MAX_MMAP_SIZE\n# define SQLITE_MAX_MMAP_SIZE 0\n#endif\n\n/*\n** Default maximum size of memory used by memory-mapped I/O in the VFS\n*/\n#ifdef __APPLE__\n# include <TargetConditionals.h>\n#endif\n#ifndef SQLITE_MAX_MMAP_SIZE\n# if defined(__linux__) \\\n  || defined(_WIN32) \\\n  || (defined(__APPLE__) && defined(__MACH__)) \\\n  || defined(__sun) \\\n  || defined(__FreeBSD__) \\\n  || defined(__DragonFly__)\n#   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */\n# else\n#   define SQLITE_MAX_MMAP_SIZE 0\n# endif\n#endif\n\n/*\n** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger\n** default MMAP_SIZE is specified at compile-time, make sure that it does\n** not exceed the maximum mmap size.\n*/\n#ifndef SQLITE_DEFAULT_MMAP_SIZE\n# define SQLITE_DEFAULT_MMAP_SIZE 0\n#endif\n#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE\n# undef SQLITE_DEFAULT_MMAP_SIZE\n# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE\n#endif\n\n/*\n** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not\n** the Select query generator tracing logic is turned on.\n*/\n#if defined(SQLITE_ENABLE_SELECTTRACE)\n# define SELECTTRACE_ENABLED 1\n#else\n# define SELECTTRACE_ENABLED 0\n#endif\n\n/*\n** An instance of the following structure is used to store the busy-handler\n** callback for a given sqlite handle.\n**\n** The sqlite.busyHandler member of the sqlite struct contains the busy\n** callback for the database handle. Each pager opened via the sqlite\n** handle is passed a pointer to sqlite.busyHandler. The busy-handler\n** callback is currently invoked only from within pager.c.\n*/\ntypedef struct BusyHandler BusyHandler;\nstruct BusyHandler {\n  int (*xBusyHandler)(void *,int);  /* The busy callback */\n  void *pBusyArg;                   /* First arg to busy callback */\n  int nBusy;                        /* Incremented with each busy call */\n};\n\n/*\n** Name of the master database table.  The master database table\n** is a special table that holds the names and attributes of all\n** user tables and indices.\n*/\n#define MASTER_NAME       \"sqlite_master\"\n#define TEMP_MASTER_NAME  \"sqlite_temp_master\"\n\n/*\n** The root-page of the master database table.\n*/\n#define MASTER_ROOT       1\n\n/*\n** The name of the schema table.\n*/\n#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)\n\n/*\n** A convenience macro that returns the number of elements in\n** an array.\n*/\n#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))\n\n/*\n** Determine if the argument is a power of two\n*/\n#define IsPowerOfTwo(X) (((X)&((X)-1))==0)\n\n/*\n** The following value as a destructor means to use sqlite3DbFree().\n** The sqlite3DbFree() routine requires two parameters instead of the\n** one parameter that destructors normally want.  So we have to introduce\n** this magic value that the code knows to handle differently.  Any\n** pointer will work here as long as it is distinct from SQLITE_STATIC\n** and SQLITE_TRANSIENT.\n*/\n#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)\n\n/*\n** When SQLITE_OMIT_WSD is defined, it means that the target platform does\n** not support Writable Static Data (WSD) such as global and static variables.\n** All variables must either be on the stack or dynamically allocated from\n** the heap.  When WSD is unsupported, the variable declarations scattered\n** throughout the SQLite code must become constants instead.  The SQLITE_WSD\n** macro is used for this purpose.  And instead of referencing the variable\n** directly, we use its constant as a key to lookup the run-time allocated\n** buffer that holds real variable.  The constant is also the initializer\n** for the run-time allocated buffer.\n**\n** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL\n** macros become no-ops and have zero performance impact.\n*/\n#ifdef SQLITE_OMIT_WSD\n  #define SQLITE_WSD const\n  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))\n  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)\nSQLITE_API int sqlite3_wsd_init(int N, int J);\nSQLITE_API void *sqlite3_wsd_find(void *K, int L);\n#else\n  #define SQLITE_WSD\n  #define GLOBAL(t,v) v\n  #define sqlite3GlobalConfig sqlite3Config\n#endif\n\n/*\n** The following macros are used to suppress compiler warnings and to\n** make it clear to human readers when a function parameter is deliberately\n** left unused within the body of a function. This usually happens when\n** a function is called via a function pointer. For example the\n** implementation of an SQL aggregate step callback may not use the\n** parameter indicating the number of arguments passed to the aggregate,\n** if it knows that this is enforced elsewhere.\n**\n** When a function parameter is not used at all within the body of a function,\n** it is generally named \"NotUsed\" or \"NotUsed2\" to make things even clearer.\n** However, these macros may also be used to suppress warnings related to\n** parameters that may or may not be used depending on compilation options.\n** For example those parameters only used in assert() statements. In these\n** cases the parameters are named as per the usual conventions.\n*/\n#define UNUSED_PARAMETER(x) (void)(x)\n#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)\n\n/*\n** Forward references to structures\n*/\ntypedef struct AggInfo AggInfo;\ntypedef struct AuthContext AuthContext;\ntypedef struct AutoincInfo AutoincInfo;\ntypedef struct Bitvec Bitvec;\ntypedef struct CollSeq CollSeq;\ntypedef struct Column Column;\ntypedef struct Db Db;\ntypedef struct Schema Schema;\ntypedef struct Expr Expr;\ntypedef struct ExprList ExprList;\ntypedef struct FKey FKey;\ntypedef struct FuncDestructor FuncDestructor;\ntypedef struct FuncDef FuncDef;\ntypedef struct FuncDefHash FuncDefHash;\ntypedef struct IdList IdList;\ntypedef struct Index Index;\ntypedef struct IndexSample IndexSample;\ntypedef struct KeyClass KeyClass;\ntypedef struct KeyInfo KeyInfo;\ntypedef struct Lookaside Lookaside;\ntypedef struct LookasideSlot LookasideSlot;\ntypedef struct Module Module;\ntypedef struct NameContext NameContext;\ntypedef struct Parse Parse;\ntypedef struct PreUpdate PreUpdate;\ntypedef struct PrintfArguments PrintfArguments;\ntypedef struct RenameToken RenameToken;\ntypedef struct RowSet RowSet;\ntypedef struct Savepoint Savepoint;\ntypedef struct Select Select;\ntypedef struct SQLiteThread SQLiteThread;\ntypedef struct SelectDest SelectDest;\ntypedef struct SrcList SrcList;\ntypedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */\ntypedef struct Table Table;\ntypedef struct TableLock TableLock;\ntypedef struct Token Token;\ntypedef struct TreeView TreeView;\ntypedef struct Trigger Trigger;\ntypedef struct TriggerPrg TriggerPrg;\ntypedef struct TriggerStep TriggerStep;\ntypedef struct UnpackedRecord UnpackedRecord;\ntypedef struct Upsert Upsert;\ntypedef struct VTable VTable;\ntypedef struct VtabCtx VtabCtx;\ntypedef struct Walker Walker;\ntypedef struct WhereInfo WhereInfo;\ntypedef struct Window Window;\ntypedef struct With With;\n\n\n/*\n** The bitmask datatype defined below is used for various optimizations.\n**\n** Changing this from a 64-bit to a 32-bit type limits the number of\n** tables in a join to 32 instead of 64.  But it also reduces the size\n** of the library by 738 bytes on ix86.\n*/\n#ifdef SQLITE_BITMASK_TYPE\n  typedef SQLITE_BITMASK_TYPE Bitmask;\n#else\n  typedef u64 Bitmask;\n#endif\n\n/*\n** The number of bits in a Bitmask.  \"BMS\" means \"BitMask Size\".\n*/\n#define BMS  ((int)(sizeof(Bitmask)*8))\n\n/*\n** A bit in a Bitmask\n*/\n#define MASKBIT(n)   (((Bitmask)1)<<(n))\n#define MASKBIT64(n) (((u64)1)<<(n))\n#define MASKBIT32(n) (((unsigned int)1)<<(n))\n#define ALLBITS      ((Bitmask)-1)\n\n/* A VList object records a mapping between parameters/variables/wildcards\n** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer\n** variable number associated with that parameter.  See the format description\n** on the sqlite3VListAdd() routine for more information.  A VList is really\n** just an array of integers.\n*/\ntypedef int VList;\n\n/*\n** Defer sourcing vdbe.h and btree.h until after the \"u8\" and\n** \"BusyHandler\" typedefs. vdbe.h also requires a few of the opaque\n** pointer types (i.e. FuncDef) defined above.\n*/\n/************** Include btree.h in the middle of sqliteInt.h *****************/\n/************** Begin file btree.h *******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This header file defines the interface that the sqlite B-Tree file\n** subsystem.  See comments in the source code for a detailed description\n** of what each interface routine does.\n*/\n#ifndef SQLITE_BTREE_H\n#define SQLITE_BTREE_H\n\n/* TODO: This definition is just included so other modules compile. It\n** needs to be revisited.\n*/\n#define SQLITE_N_BTREE_META 16\n\n/*\n** If defined as non-zero, auto-vacuum is enabled by default. Otherwise\n** it must be turned on for each database using \"PRAGMA auto_vacuum = 1\".\n*/\n#ifndef SQLITE_DEFAULT_AUTOVACUUM\n  #define SQLITE_DEFAULT_AUTOVACUUM 0\n#endif\n\n#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */\n#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */\n#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */\n\n/*\n** Forward declarations of structure\n*/\ntypedef struct Btree Btree;\ntypedef struct BtCursor BtCursor;\ntypedef struct BtShared BtShared;\ntypedef struct BtreePayload BtreePayload;\n\n\nSQLITE_PRIVATE int sqlite3BtreeOpen(\n  sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */\n  const char *zFilename,   /* Name of database file to open */\n  sqlite3 *db,             /* Associated database connection */\n  Btree **ppBtree,         /* Return open Btree* here */\n  int flags,               /* Flags */\n  int vfsFlags             /* Flags passed through to VFS open */\n);\n\n/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the\n** following values.\n**\n** NOTE:  These values must match the corresponding PAGER_ values in\n** pager.h.\n*/\n#define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */\n#define BTREE_MEMORY        2  /* This is an in-memory DB */\n#define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */\n#define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */\n\nSQLITE_PRIVATE int sqlite3BtreeClose(Btree*);\nSQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);\nSQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);\n#if SQLITE_MAX_MMAP_SIZE>0\nSQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);\n#endif\nSQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);\nSQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);\nSQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);\nSQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);\nSQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);\nSQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);\nSQLITE_PRIVATE int sqlite3BtreeGetRequestedReserve(Btree*);\nSQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);\nSQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);\nSQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);\nSQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int,int*);\nSQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);\nSQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);\nSQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);\nSQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);\nSQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);\nSQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);\nSQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);\nSQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);\nSQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);\nSQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));\nSQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);\n#ifndef SQLITE_OMIT_SHARED_CACHE\nSQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);\n#endif\nSQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);\n\nSQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);\nSQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);\nSQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);\n\nSQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);\n\n/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR\n** of the flags shown below.\n**\n** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.\n** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data\n** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With\n** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored\n** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL\n** indices.)\n*/\n#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */\n#define BTREE_BLOBKEY    2    /* Table has keys only - no data */\n\nSQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);\nSQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);\nSQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);\nSQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);\n\nSQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);\nSQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);\n\nSQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);\n\n/*\n** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta\n** should be one of the following values. The integer values are assigned \n** to constants so that the offset of the corresponding field in an\n** SQLite database header may be found using the following formula:\n**\n**   offset = 36 + (idx * 4)\n**\n** For example, the free-page-count field is located at byte offset 36 of\n** the database file header. The incr-vacuum-flag field is located at\n** byte offset 64 (== 36+4*7).\n**\n** The BTREE_DATA_VERSION value is not really a value stored in the header.\n** It is a read-only number computed by the pager.  But we merge it with\n** the header value access routines since its access pattern is the same.\n** Call it a \"virtual meta value\".\n*/\n#define BTREE_FREE_PAGE_COUNT     0\n#define BTREE_SCHEMA_VERSION      1\n#define BTREE_FILE_FORMAT         2\n#define BTREE_DEFAULT_CACHE_SIZE  3\n#define BTREE_LARGEST_ROOT_PAGE   4\n#define BTREE_TEXT_ENCODING       5\n#define BTREE_USER_VERSION        6\n#define BTREE_INCR_VACUUM         7\n#define BTREE_APPLICATION_ID      8\n#define BTREE_DATA_VERSION        15  /* A virtual meta-value */\n\n/*\n** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()\n** interface.\n**\n** BTREE_HINT_RANGE  (arguments: Expr*, Mem*)\n**\n**     The first argument is an Expr* (which is guaranteed to be constant for\n**     the lifetime of the cursor) that defines constraints on which rows\n**     might be fetched with this cursor.  The Expr* tree may contain\n**     TK_REGISTER nodes that refer to values stored in the array of registers\n**     passed as the second parameter.  In other words, if Expr.op==TK_REGISTER\n**     then the value of the node is the value in Mem[pExpr.iTable].  Any\n**     TK_COLUMN node in the expression tree refers to the Expr.iColumn-th\n**     column of the b-tree of the cursor.  The Expr tree will not contain\n**     any function calls nor subqueries nor references to b-trees other than\n**     the cursor being hinted.\n**\n**     The design of the _RANGE hint is aid b-tree implementations that try\n**     to prefetch content from remote machines - to provide those\n**     implementations with limits on what needs to be prefetched and thereby\n**     reduce network bandwidth.\n**\n** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by\n** standard SQLite.  The other hints are provided for extentions that use\n** the SQLite parser and code generator but substitute their own storage\n** engine.\n*/\n#define BTREE_HINT_RANGE 0       /* Range constraints on queries */\n\n/*\n** Values that may be OR'd together to form the argument to the\n** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():\n**\n** The BTREE_BULKLOAD flag is set on index cursors when the index is going\n** to be filled with content that is already in sorted order.\n**\n** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or\n** OP_SeekLE opcodes for a range search, but where the range of entries\n** selected will all have the same key.  In other words, the cursor will\n** be used only for equality key searches.\n**\n*/\n#define BTREE_BULKLOAD 0x00000001  /* Used to full index in sorted order */\n#define BTREE_SEEK_EQ  0x00000002  /* EQ seeks only - no range seeks */\n\n/* \n** Flags passed as the third argument to sqlite3BtreeCursor().\n**\n** For read-only cursors the wrFlag argument is always zero. For read-write\n** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just\n** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will\n** only be used by SQLite for the following:\n**\n**   * to seek to and then delete specific entries, and/or\n**\n**   * to read values that will be used to create keys that other\n**     BTREE_FORDELETE cursors will seek to and delete.\n**\n** The BTREE_FORDELETE flag is an optimization hint.  It is not used by\n** by this, the native b-tree engine of SQLite, but it is available to\n** alternative storage engines that might be substituted in place of this\n** b-tree system.  For alternative storage engines in which a delete of\n** the main table row automatically deletes corresponding index rows,\n** the FORDELETE flag hint allows those alternative storage engines to\n** skip a lot of work.  Namely:  FORDELETE cursors may treat all SEEK\n** and DELETE operations as no-ops, and any READ operation against a\n** FORDELETE cursor may return a null row: 0x01 0x00.\n*/\n#define BTREE_WRCSR     0x00000004     /* read-write cursor */\n#define BTREE_FORDELETE 0x00000008     /* Cursor is for seek/delete only */\n\nSQLITE_PRIVATE int sqlite3BtreeCursor(\n  Btree*,                              /* BTree containing table to open */\n  int iTable,                          /* Index of root page */\n  int wrFlag,                          /* 1 for writing.  0 for read-only */\n  struct KeyInfo*,                     /* First argument to compare function */\n  BtCursor *pCursor                    /* Space to write cursor structure */\n);\nSQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);\nSQLITE_PRIVATE int sqlite3BtreeCursorSize(void);\nSQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);\nSQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);\n#ifdef SQLITE_ENABLE_CURSOR_HINTS\nSQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);\n#endif\n\nSQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);\nSQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(\n  BtCursor*,\n  UnpackedRecord *pUnKey,\n  i64 intKey,\n  int bias,\n  int *pRes\n);\nSQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);\nSQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);\nSQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);\n\n/* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */\n#define BTREE_SAVEPOSITION 0x02  /* Leave cursor pointing at NEXT or PREV */\n#define BTREE_AUXDELETE    0x04  /* not the primary delete operation */\n#define BTREE_APPEND       0x08  /* Insert is likely an append */\n\n/* An instance of the BtreePayload object describes the content of a single\n** entry in either an index or table btree.\n**\n** Index btrees (used for indexes and also WITHOUT ROWID tables) contain\n** an arbitrary key and no data.  These btrees have pKey,nKey set to the\n** key and the pData,nData,nZero fields are uninitialized.  The aMem,nMem\n** fields give an array of Mem objects that are a decomposition of the key.\n** The nMem field might be zero, indicating that no decomposition is available.\n**\n** Table btrees (used for rowid tables) contain an integer rowid used as\n** the key and passed in the nKey field.  The pKey field is zero.  \n** pData,nData hold the content of the new entry.  nZero extra zero bytes\n** are appended to the end of the content when constructing the entry.\n** The aMem,nMem fields are uninitialized for table btrees.\n**\n** Field usage summary:\n**\n**               Table BTrees                   Index Btrees\n**\n**   pKey        always NULL                    encoded key\n**   nKey        the ROWID                      length of pKey\n**   pData       data                           not used\n**   aMem        not used                       decomposed key value\n**   nMem        not used                       entries in aMem\n**   nData       length of pData                not used\n**   nZero       extra zeros after pData        not used\n**\n** This object is used to pass information into sqlite3BtreeInsert().  The\n** same information used to be passed as five separate parameters.  But placing\n** the information into this object helps to keep the interface more \n** organized and understandable, and it also helps the resulting code to\n** run a little faster by using fewer registers for parameter passing.\n*/\nstruct BtreePayload {\n  const void *pKey;       /* Key content for indexes.  NULL for tables */\n  sqlite3_int64 nKey;     /* Size of pKey for indexes.  PRIMARY KEY for tabs */\n  const void *pData;      /* Data for tables. */\n  sqlite3_value *aMem;    /* First of nMem value in the unpacked pKey */\n  u16 nMem;               /* Number of aMem[] value.  Might be zero */\n  int nData;              /* Size of pData.  0 if none. */\n  int nZero;              /* Extra zero data appended after pData,nData */\n};\n\nSQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,\n                       int flags, int seekResult);\nSQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);\nSQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);\nSQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);\nSQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);\nSQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);\nSQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);\nSQLITE_PRIVATE void sqlite3BtreeCursorPin(BtCursor*);\nSQLITE_PRIVATE void sqlite3BtreeCursorUnpin(BtCursor*);\n#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC\nSQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor*);\n#endif\nSQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);\nSQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);\nSQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);\nSQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor*);\n\nSQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(sqlite3*,Btree*,int*aRoot,int nRoot,int,int*);\nSQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);\nSQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);\n\n#ifndef SQLITE_OMIT_INCRBLOB\nSQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);\nSQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);\nSQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);\n#endif\nSQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);\nSQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);\nSQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);\nSQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);\nSQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);\n\n#ifndef NDEBUG\nSQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);\n#endif\nSQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);\n\nSQLITE_PRIVATE int sqlite3BtreeCount(sqlite3*, BtCursor*, i64*);\n\n#ifdef SQLITE_TEST\nSQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);\nSQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);\n#endif\n\n#ifndef SQLITE_OMIT_WAL\nSQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);\n#endif\n\n/*\n** If we are not using shared cache, then there is no need to\n** use mutexes to access the BtShared structures.  So make the\n** Enter and Leave procedures no-ops.\n*/\n#ifndef SQLITE_OMIT_SHARED_CACHE\nSQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);\nSQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);\nSQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);\nSQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);\nSQLITE_PRIVATE   int sqlite3BtreeConnectionCount(Btree*);\n#else\n# define sqlite3BtreeEnter(X) \n# define sqlite3BtreeEnterAll(X)\n# define sqlite3BtreeSharable(X) 0\n# define sqlite3BtreeEnterCursor(X)\n# define sqlite3BtreeConnectionCount(X) 1\n#endif\n\n#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE\nSQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);\nSQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);\nSQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);\n#ifndef NDEBUG\n  /* These routines are used inside assert() statements only. */\nSQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);\nSQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);\nSQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);\n#endif\n#else\n\n# define sqlite3BtreeLeave(X)\n# define sqlite3BtreeLeaveCursor(X)\n# define sqlite3BtreeLeaveAll(X)\n\n# define sqlite3BtreeHoldsMutex(X) 1\n# define sqlite3BtreeHoldsAllMutexes(X) 1\n# define sqlite3SchemaMutexHeld(X,Y,Z) 1\n#endif\n\n\n#endif /* SQLITE_BTREE_H */\n\n/************** End of btree.h ***********************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n/************** Include vdbe.h in the middle of sqliteInt.h ******************/\n/************** Begin file vdbe.h ********************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** Header file for the Virtual DataBase Engine (VDBE)\n**\n** This header defines the interface to the virtual database engine\n** or VDBE.  The VDBE implements an abstract machine that runs a\n** simple program to access and modify the underlying database.\n*/\n#ifndef SQLITE_VDBE_H\n#define SQLITE_VDBE_H\n/* #include <stdio.h> */\n\n/*\n** A single VDBE is an opaque structure named \"Vdbe\".  Only routines\n** in the source file sqliteVdbe.c are allowed to see the insides\n** of this structure.\n*/\ntypedef struct Vdbe Vdbe;\n\n/*\n** The names of the following types declared in vdbeInt.h are required\n** for the VdbeOp definition.\n*/\ntypedef struct sqlite3_value Mem;\ntypedef struct SubProgram SubProgram;\n\n/*\n** A single instruction of the virtual machine has an opcode\n** and as many as three operands.  The instruction is recorded\n** as an instance of the following structure:\n*/\nstruct VdbeOp {\n  u8 opcode;          /* What operation to perform */\n  signed char p4type; /* One of the P4_xxx constants for p4 */\n  u16 p5;             /* Fifth parameter is an unsigned 16-bit integer */\n  int p1;             /* First operand */\n  int p2;             /* Second parameter (often the jump destination) */\n  int p3;             /* The third parameter */\n  union p4union {     /* fourth parameter */\n    int i;                 /* Integer value if p4type==P4_INT32 */\n    void *p;               /* Generic pointer */\n    char *z;               /* Pointer to data for string (char array) types */\n    i64 *pI64;             /* Used when p4type is P4_INT64 */\n    double *pReal;         /* Used when p4type is P4_REAL */\n    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */\n    sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */\n    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */\n    Mem *pMem;             /* Used when p4type is P4_MEM */\n    VTable *pVtab;         /* Used when p4type is P4_VTAB */\n    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */\n    int *ai;               /* Used when p4type is P4_INTARRAY */\n    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */\n    Table *pTab;           /* Used when p4type is P4_TABLE */\n#ifdef SQLITE_ENABLE_CURSOR_HINTS\n    Expr *pExpr;           /* Used when p4type is P4_EXPR */\n#endif\n    int (*xAdvance)(BtCursor *, int);\n  } p4;\n#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS\n  char *zComment;          /* Comment to improve readability */\n#endif\n#ifdef VDBE_PROFILE\n  u32 cnt;                 /* Number of times this instruction was executed */\n  u64 cycles;              /* Total time spent executing this instruction */\n#endif\n#ifdef SQLITE_VDBE_COVERAGE\n  u32 iSrcLine;            /* Source-code line that generated this opcode\n                           ** with flags in the upper 8 bits */\n#endif\n};\ntypedef struct VdbeOp VdbeOp;\n\n\n/*\n** A sub-routine used to implement a trigger program.\n*/\nstruct SubProgram {\n  VdbeOp *aOp;                  /* Array of opcodes for sub-program */\n  int nOp;                      /* Elements in aOp[] */\n  int nMem;                     /* Number of memory cells required */\n  int nCsr;                     /* Number of cursors required */\n  u8 *aOnce;                    /* Array of OP_Once flags */\n  void *token;                  /* id that may be used to recursive triggers */\n  SubProgram *pNext;            /* Next sub-program already visited */\n};\n\n/*\n** A smaller version of VdbeOp used for the VdbeAddOpList() function because\n** it takes up less space.\n*/\nstruct VdbeOpList {\n  u8 opcode;          /* What operation to perform */\n  signed char p1;     /* First operand */\n  signed char p2;     /* Second parameter (often the jump destination) */\n  signed char p3;     /* Third parameter */\n};\ntypedef struct VdbeOpList VdbeOpList;\n\n/*\n** Allowed values of VdbeOp.p4type\n*/\n#define P4_NOTUSED      0   /* The P4 parameter is not used */\n#define P4_TRANSIENT    0   /* P4 is a pointer to a transient string */\n#define P4_STATIC     (-1)  /* Pointer to a static string */\n#define P4_COLLSEQ    (-2)  /* P4 is a pointer to a CollSeq structure */\n#define P4_INT32      (-3)  /* P4 is a 32-bit signed integer */\n#define P4_SUBPROGRAM (-4)  /* P4 is a pointer to a SubProgram structure */\n#define P4_ADVANCE    (-5)  /* P4 is a pointer to BtreeNext() or BtreePrev() */\n#define P4_TABLE      (-6)  /* P4 is a pointer to a Table structure */\n/* Above do not own any resources.  Must free those below */\n#define P4_FREE_IF_LE (-7)\n#define P4_DYNAMIC    (-7)  /* Pointer to memory from sqliteMalloc() */\n#define P4_FUNCDEF    (-8)  /* P4 is a pointer to a FuncDef structure */\n#define P4_KEYINFO    (-9)  /* P4 is a pointer to a KeyInfo structure */\n#define P4_EXPR       (-10) /* P4 is a pointer to an Expr tree */\n#define P4_MEM        (-11) /* P4 is a pointer to a Mem*    structure */\n#define P4_VTAB       (-12) /* P4 is a pointer to an sqlite3_vtab structure */\n#define P4_REAL       (-13) /* P4 is a 64-bit floating point value */\n#define P4_INT64      (-14) /* P4 is a 64-bit signed integer */\n#define P4_INTARRAY   (-15) /* P4 is a vector of 32-bit integers */\n#define P4_FUNCCTX    (-16) /* P4 is a pointer to an sqlite3_context object */\n#define P4_DYNBLOB    (-17) /* Pointer to memory from sqliteMalloc() */\n\n/* Error message codes for OP_Halt */\n#define P5_ConstraintNotNull 1\n#define P5_ConstraintUnique  2\n#define P5_ConstraintCheck   3\n#define P5_ConstraintFK      4\n\n/*\n** The Vdbe.aColName array contains 5n Mem structures, where n is the \n** number of columns of data returned by the statement.\n*/\n#define COLNAME_NAME     0\n#define COLNAME_DECLTYPE 1\n#define COLNAME_DATABASE 2\n#define COLNAME_TABLE    3\n#define COLNAME_COLUMN   4\n#ifdef SQLITE_ENABLE_COLUMN_METADATA\n# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */\n#else\n# ifdef SQLITE_OMIT_DECLTYPE\n#   define COLNAME_N      1      /* Store only the name */\n# else\n#   define COLNAME_N      2      /* Store the name and decltype */\n# endif\n#endif\n\n/*\n** The following macro converts a label returned by sqlite3VdbeMakeLabel()\n** into an index into the Parse.aLabel[] array that contains the resolved\n** address of that label.\n*/\n#define ADDR(X)  (~(X))\n\n/*\n** The makefile scans the vdbe.c source file and creates the \"opcodes.h\"\n** header file that defines a number for each opcode used by the VDBE.\n*/\n/************** Include opcodes.h in the middle of vdbe.h ********************/\n/************** Begin file opcodes.h *****************************************/\n/* Automatically generated.  Do not edit */\n/* See the tool/mkopcodeh.tcl script for details */\n#define OP_Savepoint       0\n#define OP_AutoCommit      1\n#define OP_Transaction     2\n#define OP_SorterNext      3 /* jump                                       */\n#define OP_Prev            4 /* jump                                       */\n#define OP_Next            5 /* jump                                       */\n#define OP_Checkpoint      6\n#define OP_JournalMode     7\n#define OP_Vacuum          8\n#define OP_VFilter         9 /* jump, synopsis: iplan=r[P3] zplan='P4'     */\n#define OP_VUpdate        10 /* synopsis: data=r[P3@P2]                    */\n#define OP_Goto           11 /* jump                                       */\n#define OP_Gosub          12 /* jump                                       */\n#define OP_InitCoroutine  13 /* jump                                       */\n#define OP_Yield          14 /* jump                                       */\n#define OP_MustBeInt      15 /* jump                                       */\n#define OP_Jump           16 /* jump                                       */\n#define OP_Once           17 /* jump                                       */\n#define OP_If             18 /* jump                                       */\n#define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */\n#define OP_IfNot          20 /* jump                                       */\n#define OP_IfNullRow      21 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */\n#define OP_SeekLT         22 /* jump, synopsis: key=r[P3@P4]               */\n#define OP_SeekLE         23 /* jump, synopsis: key=r[P3@P4]               */\n#define OP_SeekGE         24 /* jump, synopsis: key=r[P3@P4]               */\n#define OP_SeekGT         25 /* jump, synopsis: key=r[P3@P4]               */\n#define OP_IfNotOpen      26 /* jump, synopsis: if( !csr[P1] ) goto P2     */\n#define OP_IfNoHope       27 /* jump, synopsis: key=r[P3@P4]               */\n#define OP_NoConflict     28 /* jump, synopsis: key=r[P3@P4]               */\n#define OP_NotFound       29 /* jump, synopsis: key=r[P3@P4]               */\n#define OP_Found          30 /* jump, synopsis: key=r[P3@P4]               */\n#define OP_SeekRowid      31 /* jump, synopsis: intkey=r[P3]               */\n#define OP_NotExists      32 /* jump, synopsis: intkey=r[P3]               */\n#define OP_Last           33 /* jump                                       */\n#define OP_IfSmaller      34 /* jump                                       */\n#define OP_SorterSort     35 /* jump                                       */\n#define OP_Sort           36 /* jump                                       */\n#define OP_Rewind         37 /* jump                                       */\n#define OP_IdxLE          38 /* jump, synopsis: key=r[P3@P4]               */\n#define OP_IdxGT          39 /* jump, synopsis: key=r[P3@P4]               */\n#define OP_IdxLT          40 /* jump, synopsis: key=r[P3@P4]               */\n#define OP_IdxGE          41 /* jump, synopsis: key=r[P3@P4]               */\n#define OP_RowSetRead     42 /* jump, synopsis: r[P3]=rowset(P1)           */\n#define OP_Or             43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */\n#define OP_And            44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */\n#define OP_RowSetTest     45 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */\n#define OP_Program        46 /* jump                                       */\n#define OP_FkIfZero       47 /* jump, synopsis: if fkctr[P1]==0 goto P2    */\n#define OP_IfPos          48 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */\n#define OP_IfNotZero      49 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */\n#define OP_IsNull         50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */\n#define OP_NotNull        51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */\n#define OP_Ne             52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */\n#define OP_Eq             53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */\n#define OP_Gt             54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */\n#define OP_Le             55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */\n#define OP_Lt             56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */\n#define OP_Ge             57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */\n#define OP_ElseNotEq      58 /* jump, same as TK_ESCAPE                    */\n#define OP_DecrJumpZero   59 /* jump, synopsis: if (--r[P1])==0 goto P2    */\n#define OP_IncrVacuum     60 /* jump                                       */\n#define OP_VNext          61 /* jump                                       */\n#define OP_Init           62 /* jump, synopsis: Start at P2                */\n#define OP_PureFunc       63 /* synopsis: r[P3]=func(r[P2@NP])             */\n#define OP_Function       64 /* synopsis: r[P3]=func(r[P2@NP])             */\n#define OP_Return         65\n#define OP_EndCoroutine   66\n#define OP_HaltIfNull     67 /* synopsis: if r[P3]=null halt               */\n#define OP_Halt           68\n#define OP_Integer        69 /* synopsis: r[P2]=P1                         */\n#define OP_Int64          70 /* synopsis: r[P2]=P4                         */\n#define OP_String         71 /* synopsis: r[P2]='P4' (len=P1)              */\n#define OP_Null           72 /* synopsis: r[P2..P3]=NULL                   */\n#define OP_SoftNull       73 /* synopsis: r[P1]=NULL                       */\n#define OP_Blob           74 /* synopsis: r[P2]=P4 (len=P1)                */\n#define OP_Variable       75 /* synopsis: r[P2]=parameter(P1,P4)           */\n#define OP_Move           76 /* synopsis: r[P2@P3]=r[P1@P3]                */\n#define OP_Copy           77 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */\n#define OP_SCopy          78 /* synopsis: r[P2]=r[P1]                      */\n#define OP_IntCopy        79 /* synopsis: r[P2]=r[P1]                      */\n#define OP_ResultRow      80 /* synopsis: output=r[P1@P2]                  */\n#define OP_CollSeq        81\n#define OP_AddImm         82 /* synopsis: r[P1]=r[P1]+P2                   */\n#define OP_RealAffinity   83\n#define OP_Cast           84 /* synopsis: affinity(r[P1])                  */\n#define OP_Permutation    85\n#define OP_Compare        86 /* synopsis: r[P1@P3] <-> r[P2@P3]            */\n#define OP_IsTrue         87 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */\n#define OP_Offset         88 /* synopsis: r[P3] = sqlite_offset(P1)        */\n#define OP_Column         89 /* synopsis: r[P3]=PX                         */\n#define OP_Affinity       90 /* synopsis: affinity(r[P1@P2])               */\n#define OP_MakeRecord     91 /* synopsis: r[P3]=mkrec(r[P1@P2])            */\n#define OP_Count          92 /* synopsis: r[P2]=count()                    */\n#define OP_ReadCookie     93\n#define OP_SetCookie      94\n#define OP_ReopenIdx      95 /* synopsis: root=P2 iDb=P3                   */\n#define OP_OpenRead       96 /* synopsis: root=P2 iDb=P3                   */\n#define OP_OpenWrite      97 /* synopsis: root=P2 iDb=P3                   */\n#define OP_OpenDup        98\n#define OP_OpenAutoindex  99 /* synopsis: nColumn=P2                       */\n#define OP_OpenEphemeral 100 /* synopsis: nColumn=P2                       */\n#define OP_BitAnd        101 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */\n#define OP_BitOr         102 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */\n#define OP_ShiftLeft     103 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */\n#define OP_ShiftRight    104 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */\n#define OP_Add           105 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */\n#define OP_Subtract      106 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */\n#define OP_Multiply      107 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */\n#define OP_Divide        108 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */\n#define OP_Remainder     109 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */\n#define OP_Concat        110 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */\n#define OP_SorterOpen    111\n#define OP_BitNot        112 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */\n#define OP_SequenceTest  113 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */\n#define OP_OpenPseudo    114 /* synopsis: P3 columns in r[P2]              */\n#define OP_String8       115 /* same as TK_STRING, synopsis: r[P2]='P4'    */\n#define OP_Close         116\n#define OP_ColumnsUsed   117\n#define OP_SeekHit       118 /* synopsis: seekHit=P2                       */\n#define OP_Sequence      119 /* synopsis: r[P2]=cursor[P1].ctr++           */\n#define OP_NewRowid      120 /* synopsis: r[P2]=rowid                      */\n#define OP_Insert        121 /* synopsis: intkey=r[P3] data=r[P2]          */\n#define OP_Delete        122\n#define OP_ResetCount    123\n#define OP_SorterCompare 124 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */\n#define OP_SorterData    125 /* synopsis: r[P2]=data                       */\n#define OP_RowData       126 /* synopsis: r[P2]=data                       */\n#define OP_Rowid         127 /* synopsis: r[P2]=rowid                      */\n#define OP_NullRow       128\n#define OP_SeekEnd       129\n#define OP_IdxInsert     130 /* synopsis: key=r[P2]                        */\n#define OP_SorterInsert  131 /* synopsis: key=r[P2]                        */\n#define OP_IdxDelete     132 /* synopsis: key=r[P2@P3]                     */\n#define OP_DeferredSeek  133 /* synopsis: Move P3 to P1.rowid if needed    */\n#define OP_IdxRowid      134 /* synopsis: r[P2]=rowid                      */\n#define OP_FinishSeek    135\n#define OP_Destroy       136\n#define OP_Clear         137\n#define OP_ResetSorter   138\n#define OP_CreateBtree   139 /* synopsis: r[P2]=root iDb=P1 flags=P3       */\n#define OP_SqlExec       140\n#define OP_ParseSchema   141\n#define OP_LoadAnalysis  142\n#define OP_DropTable     143\n#define OP_DropIndex     144\n#define OP_DropTrigger   145\n#define OP_IntegrityCk   146\n#define OP_RowSetAdd     147 /* synopsis: rowset(P1)=r[P2]                 */\n#define OP_Param         148\n#define OP_FkCounter     149 /* synopsis: fkctr[P1]+=P2                    */\n#define OP_Real          150 /* same as TK_FLOAT, synopsis: r[P2]=P4       */\n#define OP_MemMax        151 /* synopsis: r[P1]=max(r[P1],r[P2])           */\n#define OP_OffsetLimit   152 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */\n#define OP_AggInverse    153 /* synopsis: accum=r[P3] inverse(r[P2@P5])    */\n#define OP_AggStep       154 /* synopsis: accum=r[P3] step(r[P2@P5])       */\n#define OP_AggStep1      155 /* synopsis: accum=r[P3] step(r[P2@P5])       */\n#define OP_AggValue      156 /* synopsis: r[P3]=value N=P2                 */\n#define OP_AggFinal      157 /* synopsis: accum=r[P1] N=P2                 */\n#define OP_Expire        158\n#define OP_CursorLock    159\n#define OP_CursorUnlock  160\n#define OP_TableLock     161 /* synopsis: iDb=P1 root=P2 write=P3          */\n#define OP_VBegin        162\n#define OP_VCreate       163\n#define OP_VDestroy      164\n#define OP_VOpen         165\n#define OP_VColumn       166 /* synopsis: r[P3]=vcolumn(P2)                */\n#define OP_VRename       167\n#define OP_Pagecount     168\n#define OP_MaxPgcnt      169\n#define OP_Trace         170\n#define OP_CursorHint    171\n#define OP_ReleaseReg    172 /* synopsis: release r[P1@P2] mask P3         */\n#define OP_Noop          173\n#define OP_Explain       174\n#define OP_Abortable     175\n\n/* Properties such as \"out2\" or \"jump\" that are specified in\n** comments following the \"case\" for each opcode in the vdbe.c\n** are encoded into bitvectors as follows:\n*/\n#define OPFLG_JUMP        0x01  /* jump:  P2 holds jmp target */\n#define OPFLG_IN1         0x02  /* in1:   P1 is an input */\n#define OPFLG_IN2         0x04  /* in2:   P2 is an input */\n#define OPFLG_IN3         0x08  /* in3:   P3 is an input */\n#define OPFLG_OUT2        0x10  /* out2:  P2 is an output */\n#define OPFLG_OUT3        0x20  /* out3:  P3 is an output */\n#define OPFLG_INITIALIZER {\\\n/*   0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x10,\\\n/*   8 */ 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x03, 0x03,\\\n/*  16 */ 0x01, 0x01, 0x03, 0x12, 0x03, 0x01, 0x09, 0x09,\\\n/*  24 */ 0x09, 0x09, 0x01, 0x09, 0x09, 0x09, 0x09, 0x09,\\\n/*  32 */ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\\\n/*  40 */ 0x01, 0x01, 0x23, 0x26, 0x26, 0x0b, 0x01, 0x01,\\\n/*  48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\\\n/*  56 */ 0x0b, 0x0b, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00,\\\n/*  64 */ 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10, 0x10,\\\n/*  72 */ 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10,\\\n/*  80 */ 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x12,\\\n/*  88 */ 0x20, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\\\n/*  96 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x26, 0x26,\\\n/* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\\\n/* 112 */ 0x12, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10,\\\n/* 120 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\\\n/* 128 */ 0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x10, 0x00,\\\n/* 136 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\\\n/* 144 */ 0x00, 0x00, 0x00, 0x06, 0x10, 0x00, 0x10, 0x04,\\\n/* 152 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\\\n/* 160 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\\\n/* 168 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\\\n}\n\n/* The sqlite3P2Values() routine is able to run faster if it knows\n** the value of the largest JUMP opcode.  The smaller the maximum\n** JUMP opcode the better, so the mkopcodeh.tcl script that\n** generated this include file strives to group all JUMP opcodes\n** together near the beginning of the list.\n*/\n#define SQLITE_MX_JUMP_OPCODE  62  /* Maximum JUMP opcode */\n\n/************** End of opcodes.h *********************************************/\n/************** Continuing where we left off in vdbe.h ***********************/\n\n/*\n** Additional non-public SQLITE_PREPARE_* flags\n*/\n#define SQLITE_PREPARE_SAVESQL  0x80  /* Preserve SQL text */\n#define SQLITE_PREPARE_MASK     0x0f  /* Mask of public flags */\n\n/*\n** Prototypes for the VDBE interface.  See comments on the implementation\n** for a description of what each of these routines does.\n*/\nSQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);\nSQLITE_PRIVATE Parse *sqlite3VdbeParser(Vdbe*);\nSQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);\nSQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);\nSQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);\nSQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);\nSQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);\nSQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);\nSQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);\nSQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);\nSQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);\nSQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);\nSQLITE_PRIVATE int sqlite3VdbeAddFunctionCall(Parse*,int,int,int,int,const FuncDef*,int);\nSQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);\n#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)\nSQLITE_PRIVATE   void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);\nSQLITE_PRIVATE   void sqlite3VdbeVerifyNoResultRow(Vdbe *p);\n#else\n# define sqlite3VdbeVerifyNoMallocRequired(A,B)\n# define sqlite3VdbeVerifyNoResultRow(A)\n#endif\n#if defined(SQLITE_DEBUG)\nSQLITE_PRIVATE   void sqlite3VdbeVerifyAbortable(Vdbe *p, int);\n#else\n# define sqlite3VdbeVerifyAbortable(A,B)\n#endif\nSQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp,int iLineno);\n#ifndef SQLITE_OMIT_EXPLAIN\nSQLITE_PRIVATE   void sqlite3VdbeExplain(Parse*,u8,const char*,...);\nSQLITE_PRIVATE   void sqlite3VdbeExplainPop(Parse*);\nSQLITE_PRIVATE   int sqlite3VdbeExplainParent(Parse*);\n# define ExplainQueryPlan(P)        sqlite3VdbeExplain P\n# define ExplainQueryPlanPop(P)     sqlite3VdbeExplainPop(P)\n# define ExplainQueryPlanParent(P)  sqlite3VdbeExplainParent(P)\n#else\n# define ExplainQueryPlan(P)\n# define ExplainQueryPlanPop(P)\n# define ExplainQueryPlanParent(P) 0\n# define sqlite3ExplainBreakpoint(A,B) /*no-op*/\n#endif\n#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN)\nSQLITE_PRIVATE   void sqlite3ExplainBreakpoint(const char*,const char*);\n#else\n# define sqlite3ExplainBreakpoint(A,B) /*no-op*/\n#endif\nSQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);\nSQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, int addr, u8);\nSQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);\nSQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);\nSQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);\nSQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);\nSQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);\nSQLITE_PRIVATE void sqlite3VdbeJumpHereOrPopInst(Vdbe*, int addr);\nSQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);\nSQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE   void sqlite3VdbeReleaseRegisters(Parse*,int addr, int n, u32 mask, int);\n#else\n# define sqlite3VdbeReleaseRegisters(P,A,N,M,F)\n#endif\nSQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);\nSQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);\nSQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);\nSQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);\nSQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);\nSQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse*);\nSQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);\nSQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);\nSQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);\nSQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);\nSQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);\nSQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);\nSQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);\nSQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);\n#endif\nSQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);\nSQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);\nSQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);\nSQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);\nSQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));\nSQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);\nSQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);\nSQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);\nSQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);\n#ifdef SQLITE_ENABLE_NORMALIZE\nSQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3*,Vdbe*,const char*);\nSQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(Vdbe*,const char*);\n#endif\nSQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);\nSQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);\nSQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);\nSQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);\n#ifndef SQLITE_OMIT_TRACE\nSQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);\n#endif\nSQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);\nSQLITE_PRIVATE int sqlite3BlobCompare(const Mem*, const Mem*);\n\nSQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);\nSQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);\nSQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);\nSQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);\n\ntypedef int (*RecordCompare)(int,const void*,UnpackedRecord*);\nSQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);\n\nSQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);\nSQLITE_PRIVATE int sqlite3VdbeHasSubProgram(Vdbe*);\n\nSQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);\n#ifdef SQLITE_ENABLE_BYTECODE_VTAB\nSQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3*);\n#endif\n\n/* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on\n** each VDBE opcode.\n**\n** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op\n** comments in VDBE programs that show key decision points in the code\n** generator.\n*/\n#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS\nSQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);\n# define VdbeComment(X)  sqlite3VdbeComment X\nSQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);\n# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X\n# ifdef SQLITE_ENABLE_MODULE_COMMENTS\n#   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X\n# else\n#   define VdbeModuleComment(X)\n# endif\n#else\n# define VdbeComment(X)\n# define VdbeNoopComment(X)\n# define VdbeModuleComment(X)\n#endif\n\n/*\n** The VdbeCoverage macros are used to set a coverage testing point\n** for VDBE branch instructions.  The coverage testing points are line\n** numbers in the sqlite3.c source file.  VDBE branch coverage testing\n** only works with an amalagmation build.  That's ok since a VDBE branch\n** coverage build designed for testing the test suite only.  No application\n** should ever ship with VDBE branch coverage measuring turned on.\n**\n**    VdbeCoverage(v)                  // Mark the previously coded instruction\n**                                     // as a branch\n**\n**    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true\n**\n**    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken\n**\n**    VdbeCoverageNeverTaken(v)        // Previous branch is never taken\n**\n**    VdbeCoverageNeverNull(v)         // Previous three-way branch is only\n**                                     // taken on the first two ways.  The\n**                                     // NULL option is not possible\n**\n**    VdbeCoverageEqNe(v)              // Previous OP_Jump is only interested\n**                                     // in distingishing equal and not-equal.\n**\n** Every VDBE branch operation must be tagged with one of the macros above.\n** If not, then when \"make test\" is run with -DSQLITE_VDBE_COVERAGE and\n** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()\n** routine in vdbe.c, alerting the developer to the missed tag.\n**\n** During testing, the test application will invoke\n** sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE,...) to set a callback\n** routine that is invoked as each bytecode branch is taken.  The callback\n** contains the sqlite3.c source line number ov the VdbeCoverage macro and\n** flags to indicate whether or not the branch was taken.  The test application\n** is responsible for keeping track of this and reporting byte-code branches\n** that are never taken.\n**\n** See the VdbeBranchTaken() macro and vdbeTakeBranch() function in the\n** vdbe.c source file for additional information.\n*/\n#ifdef SQLITE_VDBE_COVERAGE\nSQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);\n# define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)\n# define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)\n# define VdbeCoverageAlwaysTaken(v) \\\n         sqlite3VdbeSetLineNumber(v,__LINE__|0x5000000);\n# define VdbeCoverageNeverTaken(v) \\\n         sqlite3VdbeSetLineNumber(v,__LINE__|0x6000000);\n# define VdbeCoverageNeverNull(v) \\\n         sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);\n# define VdbeCoverageNeverNullIf(v,x) \\\n         if(x)sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);\n# define VdbeCoverageEqNe(v) \\\n         sqlite3VdbeSetLineNumber(v,__LINE__|0x8000000);\n# define VDBE_OFFSET_LINENO(x) (__LINE__+x)\n#else\n# define VdbeCoverage(v)\n# define VdbeCoverageIf(v,x)\n# define VdbeCoverageAlwaysTaken(v)\n# define VdbeCoverageNeverTaken(v)\n# define VdbeCoverageNeverNull(v)\n# define VdbeCoverageNeverNullIf(v,x)\n# define VdbeCoverageEqNe(v)\n# define VDBE_OFFSET_LINENO(x) 0\n#endif\n\n#ifdef SQLITE_ENABLE_STMT_SCANSTATUS\nSQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);\n#else\n# define sqlite3VdbeScanStatus(a,b,c,d,e)\n#endif\n\n#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)\nSQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, VdbeOp*);\n#endif\n\n#endif /* SQLITE_VDBE_H */\n\n/************** End of vdbe.h ************************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n/************** Include pager.h in the middle of sqliteInt.h *****************/\n/************** Begin file pager.h *******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This header file defines the interface that the sqlite page cache\n** subsystem.  The page cache subsystem reads and writes a file a page\n** at a time and provides a journal for rollback.\n*/\n\n#ifndef SQLITE_PAGER_H\n#define SQLITE_PAGER_H\n\n/*\n** Default maximum size for persistent journal files. A negative \n** value means no limit. This value may be overridden using the \n** sqlite3PagerJournalSizeLimit() API. See also \"PRAGMA journal_size_limit\".\n*/\n#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT\n  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1\n#endif\n\n/*\n** The type used to represent a page number.  The first page in a file\n** is called page 1.  0 is used to represent \"not a page\".\n*/\ntypedef u32 Pgno;\n\n/*\n** Each open file is managed by a separate instance of the \"Pager\" structure.\n*/\ntypedef struct Pager Pager;\n\n/*\n** Handle type for pages.\n*/\ntypedef struct PgHdr DbPage;\n\n/*\n** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is\n** reserved for working around a windows/posix incompatibility). It is\n** used in the journal to signify that the remainder of the journal file \n** is devoted to storing a master journal name - there are no more pages to\n** roll back. See comments for function writeMasterJournal() in pager.c \n** for details.\n*/\n#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))\n\n/*\n** Allowed values for the flags parameter to sqlite3PagerOpen().\n**\n** NOTE: These values must match the corresponding BTREE_ values in btree.h.\n*/\n#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */\n#define PAGER_MEMORY        0x0002    /* In-memory database */\n\n/*\n** Valid values for the second argument to sqlite3PagerLockingMode().\n*/\n#define PAGER_LOCKINGMODE_QUERY      -1\n#define PAGER_LOCKINGMODE_NORMAL      0\n#define PAGER_LOCKINGMODE_EXCLUSIVE   1\n\n/*\n** Numeric constants that encode the journalmode.\n**\n** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)\n** are exposed in the API via the \"PRAGMA journal_mode\" command and\n** therefore cannot be changed without a compatibility break.\n*/\n#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */\n#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */\n#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */\n#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */\n#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */\n#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */\n#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */\n\n/*\n** Flags that make up the mask passed to sqlite3PagerGet().\n*/\n#define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */\n#define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */\n\n/*\n** Flags for sqlite3PagerSetFlags()\n**\n** Value constraints (enforced via assert()):\n**    PAGER_FULLFSYNC      == SQLITE_FullFSync\n**    PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync\n**    PAGER_CACHE_SPILL    == SQLITE_CacheSpill\n*/\n#define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */\n#define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */\n#define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */\n#define PAGER_SYNCHRONOUS_EXTRA     0x04  /* PRAGMA synchronous=EXTRA */\n#define PAGER_SYNCHRONOUS_MASK      0x07  /* Mask for four values above */\n#define PAGER_FULLFSYNC             0x08  /* PRAGMA fullfsync=ON */\n#define PAGER_CKPT_FULLFSYNC        0x10  /* PRAGMA checkpoint_fullfsync=ON */\n#define PAGER_CACHESPILL            0x20  /* PRAGMA cache_spill=ON */\n#define PAGER_FLAGS_MASK            0x38  /* All above except SYNCHRONOUS */\n\n/*\n** The remainder of this file contains the declarations of the functions\n** that make up the Pager sub-system API. See source code comments for \n** a detailed description of each routine.\n*/\n\n/* Open and close a Pager connection. */ \nSQLITE_PRIVATE int sqlite3PagerOpen(\n  sqlite3_vfs*,\n  Pager **ppPager,\n  const char*,\n  int,\n  int,\n  int,\n  void(*)(DbPage*)\n);\nSQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);\nSQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);\n\n/* Functions used to configure a Pager object. */\nSQLITE_PRIVATE void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *);\nSQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);\nSQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);\nSQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);\nSQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);\nSQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);\nSQLITE_PRIVATE void sqlite3PagerShrink(Pager*);\nSQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);\nSQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);\nSQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);\nSQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);\nSQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);\nSQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);\nSQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);\nSQLITE_PRIVATE int sqlite3PagerFlush(Pager*);\n\n/* Functions used to obtain and release page references. */ \nSQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);\nSQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);\nSQLITE_PRIVATE void sqlite3PagerRef(DbPage*);\nSQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);\nSQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);\nSQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);\n\n/* Operations on page references. */\nSQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);\nSQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);\nSQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);\nSQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);\nSQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); \nSQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); \n\n/* Functions used to manage pager transactions and savepoints. */\nSQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);\nSQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);\nSQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);\nSQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);\nSQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);\nSQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);\nSQLITE_PRIVATE int sqlite3PagerRollback(Pager*);\nSQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);\nSQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);\nSQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);\n\n#ifndef SQLITE_OMIT_WAL\nSQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);\nSQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);\nSQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);\nSQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);\nSQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);\n# ifdef SQLITE_ENABLE_SNAPSHOT\nSQLITE_PRIVATE   int sqlite3PagerSnapshotGet(Pager*, sqlite3_snapshot **ppSnapshot);\nSQLITE_PRIVATE   int sqlite3PagerSnapshotOpen(Pager*, sqlite3_snapshot *pSnapshot);\nSQLITE_PRIVATE   int sqlite3PagerSnapshotRecover(Pager *pPager);\nSQLITE_PRIVATE   int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot);\nSQLITE_PRIVATE   void sqlite3PagerSnapshotUnlock(Pager *pPager);\n# endif\n#endif\n\n#if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_ENABLE_SETLK_TIMEOUT)\nSQLITE_PRIVATE   int sqlite3PagerWalWriteLock(Pager*, int);\nSQLITE_PRIVATE   void sqlite3PagerWalDb(Pager*, sqlite3*);\n#else\n# define sqlite3PagerWalWriteLock(y,z) SQLITE_OK\n# define sqlite3PagerWalDb(x,y)\n#endif\n\n#ifdef SQLITE_DIRECT_OVERFLOW_READ\nSQLITE_PRIVATE   int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno);\n#endif\n\n#ifdef SQLITE_ENABLE_ZIPVFS\nSQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);\n#endif\n\n/* Functions used to query pager state and configuration. */\nSQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);\nSQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE   int sqlite3PagerRefcount(Pager*);\n#endif\nSQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);\nSQLITE_PRIVATE const char *sqlite3PagerFilename(const Pager*, int);\nSQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);\nSQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);\nSQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);\nSQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);\nSQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);\nSQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);\nSQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);\nSQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);\nSQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);\n\n/* Functions used to truncate the database file. */\nSQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);\n\nSQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);\n\n/* Functions to support testing and debugging. */\n#if !defined(NDEBUG) || defined(SQLITE_TEST)\nSQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);\nSQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);\n#endif\n#ifdef SQLITE_TEST\nSQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);\nSQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);\n  void disable_simulated_io_errors(void);\n  void enable_simulated_io_errors(void);\n#else\n# define disable_simulated_io_errors()\n# define enable_simulated_io_errors()\n#endif\n\n#endif /* SQLITE_PAGER_H */\n\n/************** End of pager.h ***********************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n/************** Include pcache.h in the middle of sqliteInt.h ****************/\n/************** Begin file pcache.h ******************************************/\n/*\n** 2008 August 05\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This header file defines the interface that the sqlite page cache\n** subsystem. \n*/\n\n#ifndef _PCACHE_H_\n\ntypedef struct PgHdr PgHdr;\ntypedef struct PCache PCache;\n\n/*\n** Every page in the cache is controlled by an instance of the following\n** structure.\n*/\nstruct PgHdr {\n  sqlite3_pcache_page *pPage;    /* Pcache object page handle */\n  void *pData;                   /* Page data */\n  void *pExtra;                  /* Extra content */\n  PCache *pCache;                /* PRIVATE: Cache that owns this page */\n  PgHdr *pDirty;                 /* Transient list of dirty sorted by pgno */\n  Pager *pPager;                 /* The pager this page is part of */\n  Pgno pgno;                     /* Page number for this page */\n#ifdef SQLITE_CHECK_PAGES\n  u32 pageHash;                  /* Hash of page content */\n#endif\n  u16 flags;                     /* PGHDR flags defined below */\n\n  /**********************************************************************\n  ** Elements above, except pCache, are public.  All that follow are \n  ** private to pcache.c and should not be accessed by other modules.\n  ** pCache is grouped with the public elements for efficiency.\n  */\n  i16 nRef;                      /* Number of users of this page */\n  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */\n  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */\n                          /* NB: pDirtyNext and pDirtyPrev are undefined if the\n                          ** PgHdr object is not dirty */\n};\n\n/* Bit values for PgHdr.flags */\n#define PGHDR_CLEAN           0x001  /* Page not on the PCache.pDirty list */\n#define PGHDR_DIRTY           0x002  /* Page is on the PCache.pDirty list */\n#define PGHDR_WRITEABLE       0x004  /* Journaled and ready to modify */\n#define PGHDR_NEED_SYNC       0x008  /* Fsync the rollback journal before\n                                     ** writing this page to the database */\n#define PGHDR_DONT_WRITE      0x010  /* Do not write content to disk */\n#define PGHDR_MMAP            0x020  /* This is an mmap page object */\n\n#define PGHDR_WAL_APPEND      0x040  /* Appended to wal file */\n\n/* Initialize and shutdown the page cache subsystem */\nSQLITE_PRIVATE int sqlite3PcacheInitialize(void);\nSQLITE_PRIVATE void sqlite3PcacheShutdown(void);\n\n/* Page cache buffer management:\n** These routines implement SQLITE_CONFIG_PAGECACHE.\n*/\nSQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);\n\n/* Create a new pager cache.\n** Under memory stress, invoke xStress to try to make pages clean.\n** Only clean and unpinned pages can be reclaimed.\n*/\nSQLITE_PRIVATE int sqlite3PcacheOpen(\n  int szPage,                    /* Size of every page */\n  int szExtra,                   /* Extra space associated with each page */\n  int bPurgeable,                /* True if pages are on backing store */\n  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */\n  void *pStress,                 /* Argument to xStress */\n  PCache *pToInit                /* Preallocated space for the PCache */\n);\n\n/* Modify the page-size after the cache has been created. */\nSQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);\n\n/* Return the size in bytes of a PCache object.  Used to preallocate\n** storage space.\n*/\nSQLITE_PRIVATE int sqlite3PcacheSize(void);\n\n/* One release per successful fetch.  Page is pinned until released.\n** Reference counted. \n*/\nSQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);\nSQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);\nSQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);\nSQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);\n\nSQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */\nSQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */\nSQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */\nSQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */\nSQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);\n\n/* Change a page number.  Used by incr-vacuum. */\nSQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);\n\n/* Remove all pages with pgno>x.  Reset the cache if x==0 */\nSQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);\n\n/* Get a list of all dirty pages in the cache, sorted by page number */\nSQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);\n\n/* Reset and close the cache object */\nSQLITE_PRIVATE void sqlite3PcacheClose(PCache*);\n\n/* Clear flags from pages of the page cache */\nSQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);\n\n/* Discard the contents of the cache */\nSQLITE_PRIVATE void sqlite3PcacheClear(PCache*);\n\n/* Return the total number of outstanding page references */\nSQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);\n\n/* Increment the reference count of an existing page */\nSQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);\n\nSQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);\n\n/* Return the total number of pages stored in the cache */\nSQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);\n\n#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)\n/* Iterate through all dirty pages currently stored in the cache. This\n** interface is only available if SQLITE_CHECK_PAGES is defined when the \n** library is built.\n*/\nSQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));\n#endif\n\n#if defined(SQLITE_DEBUG)\n/* Check invariants on a PgHdr object */\nSQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);\n#endif\n\n/* Set and get the suggested cache-size for the specified pager-cache.\n**\n** If no global maximum is configured, then the system attempts to limit\n** the total number of pages cached by purgeable pager-caches to the sum\n** of the suggested cache-sizes.\n*/\nSQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);\n#ifdef SQLITE_TEST\nSQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);\n#endif\n\n/* Set or get the suggested spill-size for the specified pager-cache.\n**\n** The spill-size is the minimum number of pages in cache before the cache\n** will attempt to spill dirty pages by calling xStress.\n*/\nSQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);\n\n/* Free up as much memory as possible from the page cache */\nSQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);\n\n#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT\n/* Try to return memory used by the pcache module to the main memory heap */\nSQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);\n#endif\n\n#ifdef SQLITE_TEST\nSQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);\n#endif\n\nSQLITE_PRIVATE void sqlite3PCacheSetDefault(void);\n\n/* Return the header size */\nSQLITE_PRIVATE int sqlite3HeaderSizePcache(void);\nSQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);\n\n/* Number of dirty pages as a percentage of the configured cache size */\nSQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);\n\n#ifdef SQLITE_DIRECT_OVERFLOW_READ\nSQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);\n#endif\n\n#endif /* _PCACHE_H_ */\n\n/************** End of pcache.h **********************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n/************** Include os.h in the middle of sqliteInt.h ********************/\n/************** Begin file os.h **********************************************/\n/*\n** 2001 September 16\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This header file (together with is companion C source-code file\n** \"os.c\") attempt to abstract the underlying operating system so that\n** the SQLite library will work on both POSIX and windows systems.\n**\n** This header file is #include-ed by sqliteInt.h and thus ends up\n** being included by every source file.\n*/\n#ifndef _SQLITE_OS_H_\n#define _SQLITE_OS_H_\n\n/*\n** Attempt to automatically detect the operating system and setup the\n** necessary pre-processor macros for it.\n*/\n/************** Include os_setup.h in the middle of os.h *********************/\n/************** Begin file os_setup.h ****************************************/\n/*\n** 2013 November 25\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains pre-processor directives related to operating system\n** detection and/or setup.\n*/\n#ifndef SQLITE_OS_SETUP_H\n#define SQLITE_OS_SETUP_H\n\n/*\n** Figure out if we are dealing with Unix, Windows, or some other operating\n** system.\n**\n** After the following block of preprocess macros, all of SQLITE_OS_UNIX,\n** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0.  One of\n** the three will be 1.  The other two will be 0.\n*/\n#if defined(SQLITE_OS_OTHER)\n#  if SQLITE_OS_OTHER==1\n#    undef SQLITE_OS_UNIX\n#    define SQLITE_OS_UNIX 0\n#    undef SQLITE_OS_WIN\n#    define SQLITE_OS_WIN 0\n#  else\n#    undef SQLITE_OS_OTHER\n#  endif\n#endif\n#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)\n#  define SQLITE_OS_OTHER 0\n#  ifndef SQLITE_OS_WIN\n#    if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \\\n        defined(__MINGW32__) || defined(__BORLANDC__)\n#      define SQLITE_OS_WIN 1\n#      define SQLITE_OS_UNIX 0\n#    else\n#      define SQLITE_OS_WIN 0\n#      define SQLITE_OS_UNIX 1\n#    endif\n#  else\n#    define SQLITE_OS_UNIX 0\n#  endif\n#else\n#  ifndef SQLITE_OS_WIN\n#    define SQLITE_OS_WIN 0\n#  endif\n#endif\n\n#endif /* SQLITE_OS_SETUP_H */\n\n/************** End of os_setup.h ********************************************/\n/************** Continuing where we left off in os.h *************************/\n\n/* If the SET_FULLSYNC macro is not defined above, then make it\n** a no-op\n*/\n#ifndef SET_FULLSYNC\n# define SET_FULLSYNC(x,y)\n#endif\n\n/*\n** The default size of a disk sector\n*/\n#ifndef SQLITE_DEFAULT_SECTOR_SIZE\n# define SQLITE_DEFAULT_SECTOR_SIZE 4096\n#endif\n\n/*\n** Temporary files are named starting with this prefix followed by 16 random\n** alphanumeric characters, and no file extension. They are stored in the\n** OS's standard temporary file directory, and are deleted prior to exit.\n** If sqlite is being embedded in another program, you may wish to change the\n** prefix to reflect your program's name, so that if your program exits\n** prematurely, old temporary files can be easily identified. This can be done\n** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.\n**\n** 2006-10-31:  The default prefix used to be \"sqlite_\".  But then\n** Mcafee started using SQLite in their anti-virus product and it\n** started putting files with the \"sqlite\" name in the c:/temp folder.\n** This annoyed many windows users.  Those users would then do a \n** Google search for \"sqlite\", find the telephone numbers of the\n** developers and call to wake them up at night and complain.\n** For this reason, the default name prefix is changed to be \"sqlite\" \n** spelled backwards.  So the temp files are still identified, but\n** anybody smart enough to figure out the code is also likely smart\n** enough to know that calling the developer will not help get rid\n** of the file.\n*/\n#ifndef SQLITE_TEMP_FILE_PREFIX\n# define SQLITE_TEMP_FILE_PREFIX \"etilqs_\"\n#endif\n\n/*\n** The following values may be passed as the second argument to\n** sqlite3OsLock(). The various locks exhibit the following semantics:\n**\n** SHARED:    Any number of processes may hold a SHARED lock simultaneously.\n** RESERVED:  A single process may hold a RESERVED lock on a file at\n**            any time. Other processes may hold and obtain new SHARED locks.\n** PENDING:   A single process may hold a PENDING lock on a file at\n**            any one time. Existing SHARED locks may persist, but no new\n**            SHARED locks may be obtained by other processes.\n** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.\n**\n** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a\n** process that requests an EXCLUSIVE lock may actually obtain a PENDING\n** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to\n** sqlite3OsLock().\n*/\n#define NO_LOCK         0\n#define SHARED_LOCK     1\n#define RESERVED_LOCK   2\n#define PENDING_LOCK    3\n#define EXCLUSIVE_LOCK  4\n\n/*\n** File Locking Notes:  (Mostly about windows but also some info for Unix)\n**\n** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because\n** those functions are not available.  So we use only LockFile() and\n** UnlockFile().\n**\n** LockFile() prevents not just writing but also reading by other processes.\n** A SHARED_LOCK is obtained by locking a single randomly-chosen \n** byte out of a specific range of bytes. The lock byte is obtained at \n** random so two separate readers can probably access the file at the \n** same time, unless they are unlucky and choose the same lock byte.\n** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.\n** There can only be one writer.  A RESERVED_LOCK is obtained by locking\n** a single byte of the file that is designated as the reserved lock byte.\n** A PENDING_LOCK is obtained by locking a designated byte different from\n** the RESERVED_LOCK byte.\n**\n** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,\n** which means we can use reader/writer locks.  When reader/writer locks\n** are used, the lock is placed on the same range of bytes that is used\n** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme\n** will support two or more Win95 readers or two or more WinNT readers.\n** But a single Win95 reader will lock out all WinNT readers and a single\n** WinNT reader will lock out all other Win95 readers.\n**\n** The following #defines specify the range of bytes used for locking.\n** SHARED_SIZE is the number of bytes available in the pool from which\n** a random byte is selected for a shared lock.  The pool of bytes for\n** shared locks begins at SHARED_FIRST. \n**\n** The same locking strategy and\n** byte ranges are used for Unix.  This leaves open the possibility of having\n** clients on win95, winNT, and unix all talking to the same shared file\n** and all locking correctly.  To do so would require that samba (or whatever\n** tool is being used for file sharing) implements locks correctly between\n** windows and unix.  I'm guessing that isn't likely to happen, but by\n** using the same locking range we are at least open to the possibility.\n**\n** Locking in windows is manditory.  For this reason, we cannot store\n** actual data in the bytes used for locking.  The pager never allocates\n** the pages involved in locking therefore.  SHARED_SIZE is selected so\n** that all locks will fit on a single page even at the minimum page size.\n** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE\n** is set high so that we don't have to allocate an unused page except\n** for very large databases.  But one should test the page skipping logic \n** by setting PENDING_BYTE low and running the entire regression suite.\n**\n** Changing the value of PENDING_BYTE results in a subtly incompatible\n** file format.  Depending on how it is changed, you might not notice\n** the incompatibility right away, even running a full regression test.\n** The default location of PENDING_BYTE is the first byte past the\n** 1GB boundary.\n**\n*/\n#ifdef SQLITE_OMIT_WSD\n# define PENDING_BYTE     (0x40000000)\n#else\n# define PENDING_BYTE      sqlite3PendingByte\n#endif\n#define RESERVED_BYTE     (PENDING_BYTE+1)\n#define SHARED_FIRST      (PENDING_BYTE+2)\n#define SHARED_SIZE       510\n\n/*\n** Wrapper around OS specific sqlite3_os_init() function.\n*/\nSQLITE_PRIVATE int sqlite3OsInit(void);\n\n/* \n** Functions for accessing sqlite3_file methods \n*/\nSQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);\nSQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);\nSQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);\nSQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);\nSQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);\nSQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);\nSQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);\nSQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);\nSQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);\nSQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);\nSQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);\n#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0\nSQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);\nSQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);\n#ifndef SQLITE_OMIT_WAL\nSQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);\nSQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);\nSQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);\nSQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);\n#endif /* SQLITE_OMIT_WAL */\nSQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);\nSQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);\n\n\n/* \n** Functions for accessing sqlite3_vfs methods \n*/\nSQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);\nSQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);\nSQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);\nSQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\nSQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);\nSQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);\nSQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);\nSQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);\n#endif /* SQLITE_OMIT_LOAD_EXTENSION */\nSQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);\nSQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);\nSQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);\nSQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);\n\n/*\n** Convenience functions for opening and closing files using \n** sqlite3_malloc() to obtain space for the file-handle structure.\n*/\nSQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);\nSQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);\n\n#endif /* _SQLITE_OS_H_ */\n\n/************** End of os.h **************************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n/************** Include mutex.h in the middle of sqliteInt.h *****************/\n/************** Begin file mutex.h *******************************************/\n/*\n** 2007 August 28\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains the common header for all mutex implementations.\n** The sqliteInt.h header #includes this file so that it is available\n** to all source files.  We break it out in an effort to keep the code\n** better organized.\n**\n** NOTE:  source files should *not* #include this header file directly.\n** Source files should #include the sqliteInt.h file and let that file\n** include this one indirectly.\n*/\n\n\n/*\n** Figure out what version of the code to use.  The choices are\n**\n**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The\n**                             mutexes implementation cannot be overridden\n**                             at start-time.\n**\n**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No\n**                             mutual exclusion is provided.  But this\n**                             implementation can be overridden at\n**                             start-time.\n**\n**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.\n**\n**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.\n*/\n#if !SQLITE_THREADSAFE\n# define SQLITE_MUTEX_OMIT\n#endif\n#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)\n#  if SQLITE_OS_UNIX\n#    define SQLITE_MUTEX_PTHREADS\n#  elif SQLITE_OS_WIN\n#    define SQLITE_MUTEX_W32\n#  else\n#    define SQLITE_MUTEX_NOOP\n#  endif\n#endif\n\n#ifdef SQLITE_MUTEX_OMIT\n/*\n** If this is a no-op implementation, implement everything as macros.\n*/\n#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)\n#define sqlite3_mutex_free(X)\n#define sqlite3_mutex_enter(X)    \n#define sqlite3_mutex_try(X)      SQLITE_OK\n#define sqlite3_mutex_leave(X)    \n#define sqlite3_mutex_held(X)     ((void)(X),1)\n#define sqlite3_mutex_notheld(X)  ((void)(X),1)\n#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)\n#define sqlite3MutexInit()        SQLITE_OK\n#define sqlite3MutexEnd()\n#define MUTEX_LOGIC(X)\n#else\n#define MUTEX_LOGIC(X)            X\nSQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);\n#endif /* defined(SQLITE_MUTEX_OMIT) */\n\n/************** End of mutex.h ***********************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n\n/* The SQLITE_EXTRA_DURABLE compile-time option used to set the default\n** synchronous setting to EXTRA.  It is no longer supported.\n*/\n#ifdef SQLITE_EXTRA_DURABLE\n# warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE\n# define SQLITE_DEFAULT_SYNCHRONOUS 3\n#endif\n\n/*\n** Default synchronous levels.\n**\n** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ\n** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.\n**\n**           PAGER_SYNCHRONOUS       DEFAULT_SYNCHRONOUS\n**   OFF           1                         0\n**   NORMAL        2                         1\n**   FULL          3                         2\n**   EXTRA         4                         3\n**\n** The \"PRAGMA synchronous\" statement also uses the zero-based numbers.\n** In other words, the zero-based numbers are used for all external interfaces\n** and the one-based values are used internally.\n*/\n#ifndef SQLITE_DEFAULT_SYNCHRONOUS\n# define SQLITE_DEFAULT_SYNCHRONOUS 2\n#endif\n#ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS\n# define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS\n#endif\n\n/*\n** Each database file to be accessed by the system is an instance\n** of the following structure.  There are normally two of these structures\n** in the sqlite.aDb[] array.  aDb[0] is the main database file and\n** aDb[1] is the database file used to hold temporary tables.  Additional\n** databases may be attached.\n*/\nstruct Db {\n  char *zDbSName;      /* Name of this database. (schema name, not filename) */\n  Btree *pBt;          /* The B*Tree structure for this database file */\n  u8 safety_level;     /* How aggressive at syncing data to disk */\n  u8 bSyncSet;         /* True if \"PRAGMA synchronous=N\" has been run */\n  Schema *pSchema;     /* Pointer to database schema (possibly shared) */\n};\n\n/*\n** An instance of the following structure stores a database schema.\n**\n** Most Schema objects are associated with a Btree.  The exception is\n** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.\n** In shared cache mode, a single Schema object can be shared by multiple\n** Btrees that refer to the same underlying BtShared object.\n**\n** Schema objects are automatically deallocated when the last Btree that\n** references them is destroyed.   The TEMP Schema is manually freed by\n** sqlite3_close().\n*\n** A thread must be holding a mutex on the corresponding Btree in order\n** to access Schema content.  This implies that the thread must also be\n** holding a mutex on the sqlite3 connection pointer that owns the Btree.\n** For a TEMP Schema, only the connection mutex is required.\n*/\nstruct Schema {\n  int schema_cookie;   /* Database schema version number for this file */\n  int iGeneration;     /* Generation counter.  Incremented with each change */\n  Hash tblHash;        /* All tables indexed by name */\n  Hash idxHash;        /* All (named) indices indexed by name */\n  Hash trigHash;       /* All triggers indexed by name */\n  Hash fkeyHash;       /* All foreign keys by referenced table name */\n  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */\n  u8 file_format;      /* Schema format version for this file */\n  u8 enc;              /* Text encoding used by this database */\n  u16 schemaFlags;     /* Flags associated with this schema */\n  int cache_size;      /* Number of pages to use in the cache */\n};\n\n/*\n** These macros can be used to test, set, or clear bits in the\n** Db.pSchema->flags field.\n*/\n#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))\n#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)\n#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)\n#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)\n\n/*\n** Allowed values for the DB.pSchema->flags field.\n**\n** The DB_SchemaLoaded flag is set after the database schema has been\n** read into internal hash tables.\n**\n** DB_UnresetViews means that one or more views have column names that\n** have been filled out.  If the schema changes, these column names might\n** changes and so the view will need to be reset.\n*/\n#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */\n#define DB_UnresetViews    0x0002  /* Some views have defined column names */\n#define DB_ResetWanted     0x0008  /* Reset the schema when nSchemaLock==0 */\n\n/*\n** The number of different kinds of things that can be limited\n** using the sqlite3_limit() interface.\n*/\n#define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)\n\n/*\n** Lookaside malloc is a set of fixed-size buffers that can be used\n** to satisfy small transient memory allocation requests for objects\n** associated with a particular database connection.  The use of\n** lookaside malloc provides a significant performance enhancement\n** (approx 10%) by avoiding numerous malloc/free requests while parsing\n** SQL statements.\n**\n** The Lookaside structure holds configuration information about the\n** lookaside malloc subsystem.  Each available memory allocation in\n** the lookaside subsystem is stored on a linked list of LookasideSlot\n** objects.\n**\n** Lookaside allocations are only allowed for objects that are associated\n** with a particular database connection.  Hence, schema information cannot\n** be stored in lookaside because in shared cache mode the schema information\n** is shared by multiple database connections.  Therefore, while parsing\n** schema information, the Lookaside.bEnabled flag is cleared so that\n** lookaside allocations are not used to construct the schema objects.\n**\n** New lookaside allocations are only allowed if bDisable==0.  When\n** bDisable is greater than zero, sz is set to zero which effectively\n** disables lookaside without adding a new test for the bDisable flag\n** in a performance-critical path.  sz should be set by to szTrue whenever\n** bDisable changes back to zero.\n**\n** Lookaside buffers are initially held on the pInit list.  As they are\n** used and freed, they are added back to the pFree list.  New allocations\n** come off of pFree first, then pInit as a fallback.  This dual-list\n** allows use to compute a high-water mark - the maximum number of allocations\n** outstanding at any point in the past - by subtracting the number of\n** allocations on the pInit list from the total number of allocations.\n**\n** Enhancement on 2019-12-12:  Two-size-lookaside\n** The default lookaside configuration is 100 slots of 1200 bytes each.\n** The larger slot sizes are important for performance, but they waste\n** a lot of space, as most lookaside allocations are less than 128 bytes.\n** The two-size-lookaside enhancement breaks up the lookaside allocation\n** into two pools:  One of 128-byte slots and the other of the default size\n** (1200-byte) slots.   Allocations are filled from the small-pool first,\n** failing over to the full-size pool if that does not work.  Thus more\n** lookaside slots are available while also using less memory.\n** This enhancement can be omitted by compiling with\n** SQLITE_OMIT_TWOSIZE_LOOKASIDE.\n*/\nstruct Lookaside {\n  u32 bDisable;           /* Only operate the lookaside when zero */\n  u16 sz;                 /* Size of each buffer in bytes */\n  u16 szTrue;             /* True value of sz, even if disabled */\n  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */\n  u32 nSlot;              /* Number of lookaside slots allocated */\n  u32 anStat[3];          /* 0: hits.  1: size misses.  2: full misses */\n  LookasideSlot *pInit;   /* List of buffers not previously used */\n  LookasideSlot *pFree;   /* List of available buffers */\n#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE\n  LookasideSlot *pSmallInit; /* List of small buffers not prediously used */\n  LookasideSlot *pSmallFree; /* List of available small buffers */\n  void *pMiddle;          /* First byte past end of full-size buffers and\n                          ** the first byte of LOOKASIDE_SMALL buffers */\n#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */\n  void *pStart;           /* First byte of available memory space */\n  void *pEnd;             /* First byte past end of available space */\n};\nstruct LookasideSlot {\n  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */\n};\n\n#define DisableLookaside  db->lookaside.bDisable++;db->lookaside.sz=0\n#define EnableLookaside   db->lookaside.bDisable--;\\\n   db->lookaside.sz=db->lookaside.bDisable?0:db->lookaside.szTrue\n\n/* Size of the smaller allocations in two-size lookside */\n#ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE\n#  define LOOKASIDE_SMALL           0\n#else\n#  define LOOKASIDE_SMALL         128\n#endif\n\n/*\n** A hash table for built-in function definitions.  (Application-defined\n** functions use a regular table table from hash.h.)\n**\n** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.\n** Collisions are on the FuncDef.u.pHash chain.  Use the SQLITE_FUNC_HASH()\n** macro to compute a hash on the function name.\n*/\n#define SQLITE_FUNC_HASH_SZ 23\nstruct FuncDefHash {\n  FuncDef *a[SQLITE_FUNC_HASH_SZ];       /* Hash table for functions */\n};\n#define SQLITE_FUNC_HASH(C,L) (((C)+(L))%SQLITE_FUNC_HASH_SZ)\n\n#ifdef SQLITE_USER_AUTHENTICATION\n/*\n** Information held in the \"sqlite3\" database connection object and used\n** to manage user authentication.\n*/\ntypedef struct sqlite3_userauth sqlite3_userauth;\nstruct sqlite3_userauth {\n  u8 authLevel;                 /* Current authentication level */\n  int nAuthPW;                  /* Size of the zAuthPW in bytes */\n  char *zAuthPW;                /* Password used to authenticate */\n  char *zAuthUser;              /* User name used to authenticate */\n};\n\n/* Allowed values for sqlite3_userauth.authLevel */\n#define UAUTH_Unknown     0     /* Authentication not yet checked */\n#define UAUTH_Fail        1     /* User authentication failed */\n#define UAUTH_User        2     /* Authenticated as a normal user */\n#define UAUTH_Admin       3     /* Authenticated as an administrator */\n\n/* Functions used only by user authorization logic */\nSQLITE_PRIVATE int sqlite3UserAuthTable(const char*);\nSQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);\nSQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);\nSQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);\n\n#endif /* SQLITE_USER_AUTHENTICATION */\n\n/*\n** typedef for the authorization callback function.\n*/\n#ifdef SQLITE_USER_AUTHENTICATION\n  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,\n                               const char*, const char*);\n#else\n  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,\n                               const char*);\n#endif\n\n#ifndef SQLITE_OMIT_DEPRECATED\n/* This is an extra SQLITE_TRACE macro that indicates \"legacy\" tracing\n** in the style of sqlite3_trace()\n*/\n#define SQLITE_TRACE_LEGACY          0x40     /* Use the legacy xTrace */\n#define SQLITE_TRACE_XPROFILE        0x80     /* Use the legacy xProfile */\n#else\n#define SQLITE_TRACE_LEGACY          0\n#define SQLITE_TRACE_XPROFILE        0\n#endif /* SQLITE_OMIT_DEPRECATED */\n#define SQLITE_TRACE_NONLEGACY_MASK  0x0f     /* Normal flags */\n\n\n/*\n** Each database connection is an instance of the following structure.\n*/\nstruct sqlite3 {\n  sqlite3_vfs *pVfs;            /* OS Interface */\n  struct Vdbe *pVdbe;           /* List of active virtual machines */\n  CollSeq *pDfltColl;           /* BINARY collseq for the database encoding */\n  sqlite3_mutex *mutex;         /* Connection mutex */\n  Db *aDb;                      /* All backends */\n  int nDb;                      /* Number of backends currently in use */\n  u32 mDbFlags;                 /* flags recording internal state */\n  u64 flags;                    /* flags settable by pragmas. See below */\n  i64 lastRowid;                /* ROWID of most recent insert (see above) */\n  i64 szMmap;                   /* Default mmap_size setting */\n  u32 nSchemaLock;              /* Do not reset the schema when non-zero */\n  unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */\n  int errCode;                  /* Most recent error code (SQLITE_*) */\n  int errMask;                  /* & result codes with this before returning */\n  int iSysErrno;                /* Errno value from last system error */\n  u16 dbOptFlags;               /* Flags to enable/disable optimizations */\n  u8 enc;                       /* Text encoding */\n  u8 autoCommit;                /* The auto-commit flag. */\n  u8 temp_store;                /* 1: file 2: memory 0: default */\n  u8 mallocFailed;              /* True if we have seen a malloc failure */\n  u8 bBenignMalloc;             /* Do not require OOMs if true */\n  u8 dfltLockMode;              /* Default locking-mode for attached dbs */\n  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */\n  u8 suppressErr;               /* Do not issue error messages if true */\n  u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */\n  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */\n  u8 mTrace;                    /* zero or more SQLITE_TRACE flags */\n  u8 noSharedCache;             /* True if no shared-cache backends */\n  u8 nSqlExec;                  /* Number of pending OP_SqlExec opcodes */\n  int nextPagesize;             /* Pagesize after VACUUM if >0 */\n  u32 magic;                    /* Magic number for detect library misuse */\n  int nChange;                  /* Value returned by sqlite3_changes() */\n  int nTotalChange;             /* Value returned by sqlite3_total_changes() */\n  int aLimit[SQLITE_N_LIMIT];   /* Limits */\n  int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */\n  struct sqlite3InitInfo {      /* Information used during initialization */\n    int newTnum;                /* Rootpage of table being initialized */\n    u8 iDb;                     /* Which db file is being initialized */\n    u8 busy;                    /* TRUE if currently initializing */\n    unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */\n    unsigned imposterTable : 1; /* Building an imposter table */\n    unsigned reopenMemdb : 1;   /* ATTACH is really a reopen using MemDB */\n    char **azInit;              /* \"type\", \"name\", and \"tbl_name\" columns */\n  } init;\n  int nVdbeActive;              /* Number of VDBEs currently running */\n  int nVdbeRead;                /* Number of active VDBEs that read or write */\n  int nVdbeWrite;               /* Number of active VDBEs that read and write */\n  int nVdbeExec;                /* Number of nested calls to VdbeExec() */\n  int nVDestroy;                /* Number of active OP_VDestroy operations */\n  int nExtension;               /* Number of loaded extensions */\n  void **aExtension;            /* Array of shared library handles */\n  int (*xTrace)(u32,void*,void*,void*);     /* Trace function */\n  void *pTraceArg;                          /* Argument to the trace function */\n#ifndef SQLITE_OMIT_DEPRECATED\n  void (*xProfile)(void*,const char*,u64);  /* Profiling function */\n  void *pProfileArg;                        /* Argument to profile function */\n#endif\n  void *pCommitArg;                 /* Argument to xCommitCallback() */\n  int (*xCommitCallback)(void*);    /* Invoked at every commit. */\n  void *pRollbackArg;               /* Argument to xRollbackCallback() */\n  void (*xRollbackCallback)(void*); /* Invoked at every commit. */\n  void *pUpdateArg;\n  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);\n  Parse *pParse;                /* Current parse */\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n  void *pPreUpdateArg;          /* First argument to xPreUpdateCallback */\n  void (*xPreUpdateCallback)(   /* Registered using sqlite3_preupdate_hook() */\n    void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64\n  );\n  PreUpdate *pPreUpdate;        /* Context for active pre-update callback */\n#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */\n#ifndef SQLITE_OMIT_WAL\n  int (*xWalCallback)(void *, sqlite3 *, const char *, int);\n  void *pWalArg;\n#endif\n  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);\n  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);\n  void *pCollNeededArg;\n  sqlite3_value *pErr;          /* Most recent error message */\n  union {\n    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */\n    double notUsed1;            /* Spacer */\n  } u1;\n  Lookaside lookaside;          /* Lookaside malloc configuration */\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  sqlite3_xauth xAuth;          /* Access authorization function */\n  void *pAuthArg;               /* 1st argument to the access auth function */\n#endif\n#ifndef SQLITE_OMIT_PROGRESS_CALLBACK\n  int (*xProgress)(void *);     /* The progress callback */\n  void *pProgressArg;           /* Argument to the progress callback */\n  unsigned nProgressOps;        /* Number of opcodes for progress callback */\n#endif\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  int nVTrans;                  /* Allocated size of aVTrans */\n  Hash aModule;                 /* populated by sqlite3_create_module() */\n  VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */\n  VTable **aVTrans;             /* Virtual tables with open transactions */\n  VTable *pDisconnect;          /* Disconnect these in next sqlite3_prepare() */\n#endif\n  Hash aFunc;                   /* Hash table of connection functions */\n  Hash aCollSeq;                /* All collating sequences */\n  BusyHandler busyHandler;      /* Busy callback */\n  Db aDbStatic[2];              /* Static space for the 2 default backends */\n  Savepoint *pSavepoint;        /* List of active savepoints */\n  int nAnalysisLimit;           /* Number of index rows to ANALYZE */\n  int busyTimeout;              /* Busy handler timeout, in msec */\n  int nSavepoint;               /* Number of non-transaction savepoints */\n  int nStatement;               /* Number of nested statement-transactions  */\n  i64 nDeferredCons;            /* Net deferred constraints this transaction. */\n  i64 nDeferredImmCons;         /* Net deferred immediate constraints */\n  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */\n#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY\n  /* The following variables are all protected by the STATIC_MASTER\n  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.\n  **\n  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to\n  ** unlock so that it can proceed.\n  **\n  ** When X.pBlockingConnection==Y, that means that something that X tried\n  ** tried to do recently failed with an SQLITE_LOCKED error due to locks\n  ** held by Y.\n  */\n  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */\n  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */\n  void *pUnlockArg;                     /* Argument to xUnlockNotify */\n  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */\n  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */\n#endif\n#ifdef SQLITE_USER_AUTHENTICATION\n  sqlite3_userauth auth;        /* User authentication information */\n#endif\n};\n\n/*\n** A macro to discover the encoding of a database.\n*/\n#define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)\n#define ENC(db)        ((db)->enc)\n\n/*\n** A u64 constant where the lower 32 bits are all zeros.  Only the\n** upper 32 bits are included in the argument.  Necessary because some\n** C-compilers still do not accept LL integer literals.\n*/\n#define HI(X)  ((u64)(X)<<32)\n\n/*\n** Possible values for the sqlite3.flags.\n**\n** Value constraints (enforced via assert()):\n**      SQLITE_FullFSync     == PAGER_FULLFSYNC\n**      SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC\n**      SQLITE_CacheSpill    == PAGER_CACHE_SPILL\n*/\n#define SQLITE_WriteSchema    0x00000001  /* OK to update SQLITE_MASTER */\n#define SQLITE_LegacyFileFmt  0x00000002  /* Create new databases in format 1 */\n#define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */\n#define SQLITE_FullFSync      0x00000008  /* Use full fsync on the backend */\n#define SQLITE_CkptFullFSync  0x00000010  /* Use full fsync for checkpoint */\n#define SQLITE_CacheSpill     0x00000020  /* OK to spill pager cache */\n#define SQLITE_ShortColNames  0x00000040  /* Show short columns names */\n#define SQLITE_TrustedSchema  0x00000080  /* Allow unsafe functions and\n                                          ** vtabs in the schema definition */\n#define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */\n                                          /*   result set is empty */\n#define SQLITE_IgnoreChecks   0x00000200  /* Do not enforce check constraints */\n#define SQLITE_ReadUncommit   0x00000400  /* READ UNCOMMITTED in shared-cache */\n#define SQLITE_NoCkptOnClose  0x00000800  /* No checkpoint on close()/DETACH */\n#define SQLITE_ReverseOrder   0x00001000  /* Reverse unordered SELECTs */\n#define SQLITE_RecTriggers    0x00002000  /* Enable recursive triggers */\n#define SQLITE_ForeignKeys    0x00004000  /* Enforce foreign key constraints  */\n#define SQLITE_AutoIndex      0x00008000  /* Enable automatic indexes */\n#define SQLITE_LoadExtension  0x00010000  /* Enable load_extension */\n#define SQLITE_LoadExtFunc    0x00020000  /* Enable load_extension() SQL func */\n#define SQLITE_EnableTrigger  0x00040000  /* True to enable triggers */\n#define SQLITE_DeferFKs       0x00080000  /* Defer all FK constraints */\n#define SQLITE_QueryOnly      0x00100000  /* Disable database changes */\n#define SQLITE_CellSizeCk     0x00200000  /* Check btree cell sizes on load */\n#define SQLITE_Fts3Tokenizer  0x00400000  /* Enable fts3_tokenizer(2) */\n#define SQLITE_EnableQPSG     0x00800000  /* Query Planner Stability Guarantee*/\n#define SQLITE_TriggerEQP     0x01000000  /* Show trigger EXPLAIN QUERY PLAN */\n#define SQLITE_ResetDatabase  0x02000000  /* Reset the database */\n#define SQLITE_LegacyAlter    0x04000000  /* Legacy ALTER TABLE behaviour */\n#define SQLITE_NoSchemaError  0x08000000  /* Do not report schema parse errors*/\n#define SQLITE_Defensive      0x10000000  /* Input SQL is likely hostile */\n#define SQLITE_DqsDDL         0x20000000  /* dbl-quoted strings allowed in DDL*/\n#define SQLITE_DqsDML         0x40000000  /* dbl-quoted strings allowed in DML*/\n#define SQLITE_EnableView     0x80000000  /* Enable the use of views */\n#define SQLITE_CountRows      HI(0x00001) /* Count rows changed by INSERT, */\n                                          /*   DELETE, or UPDATE and return */\n                                          /*   the count using a callback. */\n\n/* Flags used only if debugging */\n#ifdef SQLITE_DEBUG\n#define SQLITE_SqlTrace       HI(0x0100000) /* Debug print SQL as it executes */\n#define SQLITE_VdbeListing    HI(0x0200000) /* Debug listings of VDBE progs */\n#define SQLITE_VdbeTrace      HI(0x0400000) /* True to trace VDBE execution */\n#define SQLITE_VdbeAddopTrace HI(0x0800000) /* Trace sqlite3VdbeAddOp() calls */\n#define SQLITE_VdbeEQP        HI(0x1000000) /* Debug EXPLAIN QUERY PLAN */\n#define SQLITE_ParserTrace    HI(0x2000000) /* PRAGMA parser_trace=ON */\n#endif\n\n/*\n** Allowed values for sqlite3.mDbFlags\n*/\n#define DBFLAG_SchemaChange   0x0001  /* Uncommitted Hash table changes */\n#define DBFLAG_PreferBuiltin  0x0002  /* Preference to built-in funcs */\n#define DBFLAG_Vacuum         0x0004  /* Currently in a VACUUM */\n#define DBFLAG_VacuumInto     0x0008  /* Currently running VACUUM INTO */\n#define DBFLAG_SchemaKnownOk  0x0010  /* Schema is known to be valid */\n#define DBFLAG_InternalFunc   0x0020  /* Allow use of internal functions */\n#define DBFLAG_EncodingFixed  0x0040  /* No longer possible to change enc. */\n\n/*\n** Bits of the sqlite3.dbOptFlags field that are used by the\n** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to\n** selectively disable various optimizations.\n*/\n#define SQLITE_QueryFlattener 0x0001   /* Query flattening */\n#define SQLITE_WindowFunc     0x0002   /* Use xInverse for window functions */\n#define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */\n#define SQLITE_FactorOutConst 0x0008   /* Constant factoring */\n#define SQLITE_DistinctOpt    0x0010   /* DISTINCT using indexes */\n#define SQLITE_CoverIdxScan   0x0020   /* Covering index scans */\n#define SQLITE_OrderByIdxJoin 0x0040   /* ORDER BY of joins via index */\n#define SQLITE_Transitive     0x0080   /* Transitive constraints */\n#define SQLITE_OmitNoopJoin   0x0100   /* Omit unused tables in joins */\n#define SQLITE_CountOfView    0x0200   /* The count-of-view optimization */\n#define SQLITE_CursorHints    0x0400   /* Add OP_CursorHint opcodes */\n#define SQLITE_Stat4          0x0800   /* Use STAT4 data */\n   /* TH3 expects the Stat4   ^^^^^^ value to be 0x0800.  Don't change it */\n#define SQLITE_PushDown       0x1000   /* The push-down optimization */\n#define SQLITE_SimplifyJoin   0x2000   /* Convert LEFT JOIN to JOIN */\n#define SQLITE_SkipScan       0x4000   /* Skip-scans */\n#define SQLITE_PropagateConst 0x8000   /* The constant propagation opt */\n#define SQLITE_AllOpts        0xffff   /* All optimizations */\n\n/*\n** Macros for testing whether or not optimizations are enabled or disabled.\n*/\n#define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)\n#define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)\n\n/*\n** Return true if it OK to factor constant expressions into the initialization\n** code. The argument is a Parse object for the code generator.\n*/\n#define ConstFactorOk(P) ((P)->okConstFactor)\n\n/*\n** Possible values for the sqlite.magic field.\n** The numbers are obtained at random and have no special meaning, other\n** than being distinct from one another.\n*/\n#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */\n#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */\n#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */\n#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */\n#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */\n#define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */\n\n/*\n** Each SQL function is defined by an instance of the following\n** structure.  For global built-in functions (ex: substr(), max(), count())\n** a pointer to this structure is held in the sqlite3BuiltinFunctions object.\n** For per-connection application-defined functions, a pointer to this\n** structure is held in the db->aHash hash table.\n**\n** The u.pHash field is used by the global built-ins.  The u.pDestructor\n** field is used by per-connection app-def functions.\n*/\nstruct FuncDef {\n  i8 nArg;             /* Number of arguments.  -1 means unlimited */\n  u32 funcFlags;       /* Some combination of SQLITE_FUNC_* */\n  void *pUserData;     /* User data parameter */\n  FuncDef *pNext;      /* Next function with same name */\n  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */\n  void (*xFinalize)(sqlite3_context*);                  /* Agg finalizer */\n  void (*xValue)(sqlite3_context*);                     /* Current agg value */\n  void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */\n  const char *zName;   /* SQL name of the function. */\n  union {\n    FuncDef *pHash;      /* Next with a different name but the same hash */\n    FuncDestructor *pDestructor;   /* Reference counted destructor function */\n  } u;\n};\n\n/*\n** This structure encapsulates a user-function destructor callback (as\n** configured using create_function_v2()) and a reference counter. When\n** create_function_v2() is called to create a function with a destructor,\n** a single object of this type is allocated. FuncDestructor.nRef is set to\n** the number of FuncDef objects created (either 1 or 3, depending on whether\n** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor\n** member of each of the new FuncDef objects is set to point to the allocated\n** FuncDestructor.\n**\n** Thereafter, when one of the FuncDef objects is deleted, the reference\n** count on this object is decremented. When it reaches 0, the destructor\n** is invoked and the FuncDestructor structure freed.\n*/\nstruct FuncDestructor {\n  int nRef;\n  void (*xDestroy)(void *);\n  void *pUserData;\n};\n\n/*\n** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF\n** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  And\n** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC.  There\n** are assert() statements in the code to verify this.\n**\n** Value constraints (enforced via assert()):\n**     SQLITE_FUNC_MINMAX    ==  NC_MinMaxAgg      == SF_MinMaxAgg\n**     SQLITE_FUNC_LENGTH    ==  OPFLAG_LENGTHARG\n**     SQLITE_FUNC_TYPEOF    ==  OPFLAG_TYPEOFARG\n**     SQLITE_FUNC_CONSTANT  ==  SQLITE_DETERMINISTIC from the API\n**     SQLITE_FUNC_DIRECT    ==  SQLITE_DIRECTONLY from the API\n**     SQLITE_FUNC_UNSAFE    ==  SQLITE_INNOCUOUS\n**     SQLITE_FUNC_ENCMASK   depends on SQLITE_UTF* macros in the API\n*/\n#define SQLITE_FUNC_ENCMASK  0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */\n#define SQLITE_FUNC_LIKE     0x0004 /* Candidate for the LIKE optimization */\n#define SQLITE_FUNC_CASE     0x0008 /* Case-sensitive LIKE-type function */\n#define SQLITE_FUNC_EPHEM    0x0010 /* Ephemeral.  Delete with VDBE */\n#define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/\n#define SQLITE_FUNC_LENGTH   0x0040 /* Built-in length() function */\n#define SQLITE_FUNC_TYPEOF   0x0080 /* Built-in typeof() function */\n#define SQLITE_FUNC_COUNT    0x0100 /* Built-in count(*) aggregate */\n/*                           0x0200 -- available for reuse */\n#define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */\n#define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */\n#define SQLITE_FUNC_MINMAX   0x1000 /* True for min() and max() aggregates */\n#define SQLITE_FUNC_SLOCHNG  0x2000 /* \"Slow Change\". Value constant during a\n                                    ** single query - might change over time */\n#define SQLITE_FUNC_TEST     0x4000 /* Built-in testing functions */\n#define SQLITE_FUNC_OFFSET   0x8000 /* Built-in sqlite_offset() function */\n#define SQLITE_FUNC_WINDOW   0x00010000 /* Built-in window-only function */\n#define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */\n#define SQLITE_FUNC_DIRECT   0x00080000 /* Not for use in TRIGGERs or VIEWs */\n#define SQLITE_FUNC_SUBTYPE  0x00100000 /* Result likely to have sub-type */\n#define SQLITE_FUNC_UNSAFE   0x00200000 /* Function has side effects */\n#define SQLITE_FUNC_INLINE   0x00400000 /* Functions implemented in-line */\n\n/* Identifier numbers for each in-line function */\n#define INLINEFUNC_coalesce             0\n#define INLINEFUNC_implies_nonnull_row  1\n#define INLINEFUNC_expr_implies_expr    2\n#define INLINEFUNC_expr_compare         3      \n#define INLINEFUNC_affinity             4\n#define INLINEFUNC_iif                  5\n#define INLINEFUNC_unlikely            99  /* Default case */\n\n/*\n** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are\n** used to create the initializers for the FuncDef structures.\n**\n**   FUNCTION(zName, nArg, iArg, bNC, xFunc)\n**     Used to create a scalar function definition of a function zName\n**     implemented by C function xFunc that accepts nArg arguments. The\n**     value passed as iArg is cast to a (void*) and made available\n**     as the user-data (sqlite3_user_data()) for the function. If\n**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.\n**\n**   VFUNCTION(zName, nArg, iArg, bNC, xFunc)\n**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.\n**\n**   SFUNCTION(zName, nArg, iArg, bNC, xFunc)\n**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and\n**     adds the SQLITE_DIRECTONLY flag.\n**\n**   INLINE_FUNC(zName, nArg, iFuncId, mFlags)\n**     zName is the name of a function that is implemented by in-line\n**     byte code rather than by the usual callbacks. The iFuncId\n**     parameter determines the function id.  The mFlags parameter is\n**     optional SQLITE_FUNC_ flags for this function.\n**\n**   TEST_FUNC(zName, nArg, iFuncId, mFlags)\n**     zName is the name of a test-only function implemented by in-line\n**     byte code rather than by the usual callbacks. The iFuncId\n**     parameter determines the function id.  The mFlags parameter is\n**     optional SQLITE_FUNC_ flags for this function.\n**\n**   DFUNCTION(zName, nArg, iArg, bNC, xFunc)\n**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and\n**     adds the SQLITE_FUNC_SLOCHNG flag.  Used for date & time functions\n**     and functions like sqlite_version() that can change, but not during\n**     a single query.  The iArg is ignored.  The user-data is always set\n**     to a NULL pointer.  The bNC parameter is not used.\n**\n**   PURE_DATE(zName, nArg, iArg, bNC, xFunc)\n**     Used for \"pure\" date/time functions, this macro is like DFUNCTION\n**     except that it does set the SQLITE_FUNC_CONSTANT flags.  iArg is\n**     ignored and the user-data for these functions is set to an \n**     arbitrary non-NULL pointer.  The bNC parameter is not used.\n**\n**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)\n**     Used to create an aggregate function definition implemented by\n**     the C functions xStep and xFinal. The first four parameters\n**     are interpreted in the same way as the first 4 parameters to\n**     FUNCTION().\n**\n**   WFUNCTION(zName, nArg, iArg, xStep, xFinal, xValue, xInverse)\n**     Used to create an aggregate function definition implemented by\n**     the C functions xStep and xFinal. The first four parameters\n**     are interpreted in the same way as the first 4 parameters to\n**     FUNCTION().\n**\n**   LIKEFUNC(zName, nArg, pArg, flags)\n**     Used to create a scalar function definition of a function zName\n**     that accepts nArg arguments and is implemented by a call to C\n**     function likeFunc. Argument pArg is cast to a (void *) and made\n**     available as the function user-data (sqlite3_user_data()). The\n**     FuncDef.flags variable is set to the value passed as the flags\n**     parameter.\n*/\n#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \\\n  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \\\n   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }\n#define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \\\n  {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \\\n   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }\n#define SFUNCTION(zName, nArg, iArg, bNC, xFunc) \\\n  {nArg, SQLITE_UTF8|SQLITE_DIRECTONLY|SQLITE_FUNC_UNSAFE, \\\n   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }\n#define INLINE_FUNC(zName, nArg, iArg, mFlags) \\\n  {nArg, SQLITE_UTF8|SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \\\n   SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }\n#define TEST_FUNC(zName, nArg, iArg, mFlags) \\\n  {nArg, SQLITE_UTF8|SQLITE_FUNC_INTERNAL|SQLITE_FUNC_TEST| \\\n         SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \\\n   SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }\n#define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \\\n  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \\\n   0, 0, xFunc, 0, 0, 0, #zName, {0} }\n#define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \\\n  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \\\n   (void*)&sqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} }\n#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \\\n  {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\\\n   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }\n#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \\\n  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \\\n   pArg, 0, xFunc, 0, 0, 0, #zName, }\n#define LIKEFUNC(zName, nArg, arg, flags) \\\n  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \\\n   (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }\n#define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \\\n  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \\\n   SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}\n#define INTERNAL_FUNCTION(zName, nArg, xFunc) \\\n  {nArg, SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \\\n   0, 0, xFunc, 0, 0, 0, #zName, {0} }\n\n\n/*\n** All current savepoints are stored in a linked list starting at\n** sqlite3.pSavepoint. The first element in the list is the most recently\n** opened savepoint. Savepoints are added to the list by the vdbe\n** OP_Savepoint instruction.\n*/\nstruct Savepoint {\n  char *zName;                        /* Savepoint name (nul-terminated) */\n  i64 nDeferredCons;                  /* Number of deferred fk violations */\n  i64 nDeferredImmCons;               /* Number of deferred imm fk. */\n  Savepoint *pNext;                   /* Parent savepoint (if any) */\n};\n\n/*\n** The following are used as the second parameter to sqlite3Savepoint(),\n** and as the P1 argument to the OP_Savepoint instruction.\n*/\n#define SAVEPOINT_BEGIN      0\n#define SAVEPOINT_RELEASE    1\n#define SAVEPOINT_ROLLBACK   2\n\n\n/*\n** Each SQLite module (virtual table definition) is defined by an\n** instance of the following structure, stored in the sqlite3.aModule\n** hash table.\n*/\nstruct Module {\n  const sqlite3_module *pModule;       /* Callback pointers */\n  const char *zName;                   /* Name passed to create_module() */\n  int nRefModule;                      /* Number of pointers to this object */\n  void *pAux;                          /* pAux passed to create_module() */\n  void (*xDestroy)(void *);            /* Module destructor function */\n  Table *pEpoTab;                      /* Eponymous table for this module */\n};\n\n/*\n** Information about each column of an SQL table is held in an instance\n** of the Column structure, in the Table.aCol[] array.\n**\n** Definitions:\n**\n**   \"table column index\"     This is the index of the column in the\n**                            Table.aCol[] array, and also the index of\n**                            the column in the original CREATE TABLE stmt.\n**\n**   \"storage column index\"   This is the index of the column in the\n**                            record BLOB generated by the OP_MakeRecord\n**                            opcode.  The storage column index is less than\n**                            or equal to the table column index.  It is\n**                            equal if and only if there are no VIRTUAL\n**                            columns to the left.\n*/\nstruct Column {\n  char *zName;     /* Name of this column, \\000, then the type */\n  Expr *pDflt;     /* Default value or GENERATED ALWAYS AS value */\n  char *zColl;     /* Collating sequence.  If NULL, use the default */\n  u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */\n  char affinity;   /* One of the SQLITE_AFF_... values */\n  u8 szEst;        /* Estimated size of value in this column. sizeof(INT)==1 */\n  u8 hName;        /* Column name hash for faster lookup */\n  u16 colFlags;    /* Boolean properties.  See COLFLAG_ defines below */\n};\n\n/* Allowed values for Column.colFlags:\n*/\n#define COLFLAG_PRIMKEY   0x0001   /* Column is part of the primary key */\n#define COLFLAG_HIDDEN    0x0002   /* A hidden column in a virtual table */\n#define COLFLAG_HASTYPE   0x0004   /* Type name follows column name */\n#define COLFLAG_UNIQUE    0x0008   /* Column def contains \"UNIQUE\" or \"PK\" */\n#define COLFLAG_SORTERREF 0x0010   /* Use sorter-refs with this column */\n#define COLFLAG_VIRTUAL   0x0020   /* GENERATED ALWAYS AS ... VIRTUAL */\n#define COLFLAG_STORED    0x0040   /* GENERATED ALWAYS AS ... STORED */\n#define COLFLAG_NOTAVAIL  0x0080   /* STORED column not yet calculated */\n#define COLFLAG_BUSY      0x0100   /* Blocks recursion on GENERATED columns */\n#define COLFLAG_GENERATED 0x0060   /* Combo: _STORED, _VIRTUAL */\n#define COLFLAG_NOINSERT  0x0062   /* Combo: _HIDDEN, _STORED, _VIRTUAL */\n\n/*\n** A \"Collating Sequence\" is defined by an instance of the following\n** structure. Conceptually, a collating sequence consists of a name and\n** a comparison routine that defines the order of that sequence.\n**\n** If CollSeq.xCmp is NULL, it means that the\n** collating sequence is undefined.  Indices built on an undefined\n** collating sequence may not be read or written.\n*/\nstruct CollSeq {\n  char *zName;          /* Name of the collating sequence, UTF-8 encoded */\n  u8 enc;               /* Text encoding handled by xCmp() */\n  void *pUser;          /* First argument to xCmp() */\n  int (*xCmp)(void*,int, const void*, int, const void*);\n  void (*xDel)(void*);  /* Destructor for pUser */\n};\n\n/*\n** A sort order can be either ASC or DESC.\n*/\n#define SQLITE_SO_ASC       0  /* Sort in ascending order */\n#define SQLITE_SO_DESC      1  /* Sort in ascending order */\n#define SQLITE_SO_UNDEFINED -1 /* No sort order specified */\n\n/*\n** Column affinity types.\n**\n** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and\n** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve\n** the speed a little by numbering the values consecutively.\n**\n** But rather than start with 0 or 1, we begin with 'A'.  That way,\n** when multiple affinity types are concatenated into a string and\n** used as the P4 operand, they will be more readable.\n**\n** Note also that the numeric types are grouped together so that testing\n** for a numeric type is a single comparison.  And the BLOB type is first.\n*/\n#define SQLITE_AFF_NONE     0x40  /* '@' */\n#define SQLITE_AFF_BLOB     0x41  /* 'A' */\n#define SQLITE_AFF_TEXT     0x42  /* 'B' */\n#define SQLITE_AFF_NUMERIC  0x43  /* 'C' */\n#define SQLITE_AFF_INTEGER  0x44  /* 'D' */\n#define SQLITE_AFF_REAL     0x45  /* 'E' */\n\n#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)\n\n/*\n** The SQLITE_AFF_MASK values masks off the significant bits of an\n** affinity value.\n*/\n#define SQLITE_AFF_MASK     0x47\n\n/*\n** Additional bit values that can be ORed with an affinity without\n** changing the affinity.\n**\n** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.\n** It causes an assert() to fire if either operand to a comparison\n** operator is NULL.  It is added to certain comparison operators to\n** prove that the operands are always NOT NULL.\n*/\n#define SQLITE_KEEPNULL     0x08  /* Used by vector == or <> */\n#define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */\n#define SQLITE_STOREP2      0x20  /* Store result in reg[P2] rather than jump */\n#define SQLITE_NULLEQ       0x80  /* NULL=NULL */\n#define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */\n\n/*\n** An object of this type is created for each virtual table present in\n** the database schema.\n**\n** If the database schema is shared, then there is one instance of this\n** structure for each database connection (sqlite3*) that uses the shared\n** schema. This is because each database connection requires its own unique\n** instance of the sqlite3_vtab* handle used to access the virtual table\n** implementation. sqlite3_vtab* handles can not be shared between\n** database connections, even when the rest of the in-memory database\n** schema is shared, as the implementation often stores the database\n** connection handle passed to it via the xConnect() or xCreate() method\n** during initialization internally. This database connection handle may\n** then be used by the virtual table implementation to access real tables\n** within the database. So that they appear as part of the callers\n** transaction, these accesses need to be made via the same database\n** connection as that used to execute SQL operations on the virtual table.\n**\n** All VTable objects that correspond to a single table in a shared\n** database schema are initially stored in a linked-list pointed to by\n** the Table.pVTable member variable of the corresponding Table object.\n** When an sqlite3_prepare() operation is required to access the virtual\n** table, it searches the list for the VTable that corresponds to the\n** database connection doing the preparing so as to use the correct\n** sqlite3_vtab* handle in the compiled query.\n**\n** When an in-memory Table object is deleted (for example when the\n** schema is being reloaded for some reason), the VTable objects are not\n** deleted and the sqlite3_vtab* handles are not xDisconnect()ed\n** immediately. Instead, they are moved from the Table.pVTable list to\n** another linked list headed by the sqlite3.pDisconnect member of the\n** corresponding sqlite3 structure. They are then deleted/xDisconnected\n** next time a statement is prepared using said sqlite3*. This is done\n** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.\n** Refer to comments above function sqlite3VtabUnlockList() for an\n** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect\n** list without holding the corresponding sqlite3.mutex mutex.\n**\n** The memory for objects of this type is always allocated by\n** sqlite3DbMalloc(), using the connection handle stored in VTable.db as\n** the first argument.\n*/\nstruct VTable {\n  sqlite3 *db;              /* Database connection associated with this table */\n  Module *pMod;             /* Pointer to module implementation */\n  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */\n  int nRef;                 /* Number of pointers to this structure */\n  u8 bConstraint;           /* True if constraints are supported */\n  u8 eVtabRisk;             /* Riskiness of allowing hacker access */\n  int iSavepoint;           /* Depth of the SAVEPOINT stack */\n  VTable *pNext;            /* Next in linked list (see above) */\n};\n\n/* Allowed values for VTable.eVtabRisk\n*/\n#define SQLITE_VTABRISK_Low          0\n#define SQLITE_VTABRISK_Normal       1\n#define SQLITE_VTABRISK_High         2\n\n/*\n** The schema for each SQL table and view is represented in memory\n** by an instance of the following structure.\n*/\nstruct Table {\n  char *zName;         /* Name of the table or view */\n  Column *aCol;        /* Information about each column */\n  Index *pIndex;       /* List of SQL indexes on this table. */\n  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */\n  FKey *pFKey;         /* Linked list of all foreign keys in this table */\n  char *zColAff;       /* String defining the affinity of each column */\n  ExprList *pCheck;    /* All CHECK constraints */\n                       /*   ... also used as column name list in a VIEW */\n  int tnum;            /* Root BTree page for this table */\n  u32 nTabRef;         /* Number of pointers to this Table */\n  u32 tabFlags;        /* Mask of TF_* values */\n  i16 iPKey;           /* If not negative, use aCol[iPKey] as the rowid */\n  i16 nCol;            /* Number of columns in this table */\n  i16 nNVCol;          /* Number of columns that are not VIRTUAL */\n  LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */\n  LogEst szTabRow;     /* Estimated size of each table row in bytes */\n#ifdef SQLITE_ENABLE_COSTMULT\n  LogEst costMult;     /* Cost multiplier for using this table */\n#endif\n  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */\n#ifndef SQLITE_OMIT_ALTERTABLE\n  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */\n#endif\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  int nModuleArg;      /* Number of arguments to the module */\n  char **azModuleArg;  /* 0: module 1: schema 2: vtab name 3...: args */\n  VTable *pVTable;     /* List of VTable objects. */\n#endif\n  Trigger *pTrigger;   /* List of triggers stored in pSchema */\n  Schema *pSchema;     /* Schema that contains this table */\n  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */\n};\n\n/*\n** Allowed values for Table.tabFlags.\n**\n** TF_OOOHidden applies to tables or view that have hidden columns that are\n** followed by non-hidden columns.  Example:  \"CREATE VIRTUAL TABLE x USING\n** vtab1(a HIDDEN, b);\".  Since \"b\" is a non-hidden column but \"a\" is hidden,\n** the TF_OOOHidden attribute would apply in this case.  Such tables require\n** special handling during INSERT processing. The \"OOO\" means \"Out Of Order\".\n**\n** Constraints:\n**\n**         TF_HasVirtual == COLFLAG_Virtual\n**         TF_HasStored  == COLFLAG_Stored\n*/\n#define TF_Readonly        0x0001    /* Read-only system table */\n#define TF_Ephemeral       0x0002    /* An ephemeral table */\n#define TF_HasPrimaryKey   0x0004    /* Table has a primary key */\n#define TF_Autoincrement   0x0008    /* Integer primary key is autoincrement */\n#define TF_HasStat1        0x0010    /* nRowLogEst set from sqlite_stat1 */\n#define TF_HasVirtual      0x0020    /* Has one or more VIRTUAL columns */\n#define TF_HasStored       0x0040    /* Has one or more STORED columns */\n#define TF_HasGenerated    0x0060    /* Combo: HasVirtual + HasStored */\n#define TF_WithoutRowid    0x0080    /* No rowid.  PRIMARY KEY is the key */\n#define TF_StatsUsed       0x0100    /* Query planner decisions affected by\n                                     ** Index.aiRowLogEst[] values */\n#define TF_NoVisibleRowid  0x0200    /* No user-visible \"rowid\" column */\n#define TF_OOOHidden       0x0400    /* Out-of-Order hidden columns */\n#define TF_HasNotNull      0x0800    /* Contains NOT NULL constraints */\n#define TF_Shadow          0x1000    /* True for a shadow table */\n\n/*\n** Test to see whether or not a table is a virtual table.  This is\n** done as a macro so that it will be optimized out when virtual\n** table support is omitted from the build.\n*/\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n#  define IsVirtual(X)      ((X)->nModuleArg)\n#  define ExprIsVtab(X)  \\\n              ((X)->op==TK_COLUMN && (X)->y.pTab!=0 && (X)->y.pTab->nModuleArg)\n#else\n#  define IsVirtual(X)      0\n#  define ExprIsVtab(X)     0\n#endif\n\n/*\n** Macros to determine if a column is hidden.  IsOrdinaryHiddenColumn()\n** only works for non-virtual tables (ordinary tables and views) and is\n** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined.  The\n** IsHiddenColumn() macro is general purpose.\n*/\n#if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)\n#  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)\n#  define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)\n#elif !defined(SQLITE_OMIT_VIRTUALTABLE)\n#  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)\n#  define IsOrdinaryHiddenColumn(X) 0\n#else\n#  define IsHiddenColumn(X)         0\n#  define IsOrdinaryHiddenColumn(X) 0\n#endif\n\n\n/* Does the table have a rowid */\n#define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)\n#define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)\n\n/*\n** Each foreign key constraint is an instance of the following structure.\n**\n** A foreign key is associated with two tables.  The \"from\" table is\n** the table that contains the REFERENCES clause that creates the foreign\n** key.  The \"to\" table is the table that is named in the REFERENCES clause.\n** Consider this example:\n**\n**     CREATE TABLE ex1(\n**       a INTEGER PRIMARY KEY,\n**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)\n**     );\n**\n** For foreign key \"fk1\", the from-table is \"ex1\" and the to-table is \"ex2\".\n** Equivalent names:\n**\n**     from-table == child-table\n**       to-table == parent-table\n**\n** Each REFERENCES clause generates an instance of the following structure\n** which is attached to the from-table.  The to-table need not exist when\n** the from-table is created.  The existence of the to-table is not checked.\n**\n** The list of all parents for child Table X is held at X.pFKey.\n**\n** A list of all children for a table named Z (which might not even exist)\n** is held in Schema.fkeyHash with a hash key of Z.\n*/\nstruct FKey {\n  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */\n  FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */\n  char *zTo;        /* Name of table that the key points to (aka: Parent) */\n  FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */\n  FKey *pPrevTo;    /* Previous with the same zTo */\n  int nCol;         /* Number of columns in this key */\n  /* EV: R-30323-21917 */\n  u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */\n  u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */\n  Trigger *apTrigger[2];/* Triggers for aAction[] actions */\n  struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */\n    int iFrom;            /* Index of column in pFrom */\n    char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */\n  } aCol[1];            /* One entry for each of nCol columns */\n};\n\n/*\n** SQLite supports many different ways to resolve a constraint\n** error.  ROLLBACK processing means that a constraint violation\n** causes the operation in process to fail and for the current transaction\n** to be rolled back.  ABORT processing means the operation in process\n** fails and any prior changes from that one operation are backed out,\n** but the transaction is not rolled back.  FAIL processing means that\n** the operation in progress stops and returns an error code.  But prior\n** changes due to the same operation are not backed out and no rollback\n** occurs.  IGNORE means that the particular row that caused the constraint\n** error is not inserted or updated.  Processing continues and no error\n** is returned.  REPLACE means that preexisting database rows that caused\n** a UNIQUE constraint violation are removed so that the new insert or\n** update can proceed.  Processing continues and no error is reported.\n**\n** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.\n** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the\n** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign\n** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the\n** referenced table row is propagated into the row that holds the\n** foreign key.\n**\n** The following symbolic values are used to record which type\n** of action to take.\n*/\n#define OE_None     0   /* There is no constraint to check */\n#define OE_Rollback 1   /* Fail the operation and rollback the transaction */\n#define OE_Abort    2   /* Back out changes but do no rollback transaction */\n#define OE_Fail     3   /* Stop the operation but leave all prior changes */\n#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */\n#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */\n#define OE_Update   6   /* Process as a DO UPDATE in an upsert */\n#define OE_Restrict 7   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */\n#define OE_SetNull  8   /* Set the foreign key value to NULL */\n#define OE_SetDflt  9   /* Set the foreign key value to its default */\n#define OE_Cascade  10  /* Cascade the changes */\n#define OE_Default  11  /* Do whatever the default action is */\n\n\n/*\n** An instance of the following structure is passed as the first\n** argument to sqlite3VdbeKeyCompare and is used to control the\n** comparison of the two index keys.\n**\n** Note that aSortOrder[] and aColl[] have nField+1 slots.  There\n** are nField slots for the columns of an index then one extra slot\n** for the rowid at the end.\n*/\nstruct KeyInfo {\n  u32 nRef;           /* Number of references to this KeyInfo object */\n  u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */\n  u16 nKeyField;      /* Number of key columns in the index */\n  u16 nAllField;      /* Total columns, including key plus others */\n  sqlite3 *db;        /* The database connection */\n  u8 *aSortFlags;     /* Sort order for each column. */\n  CollSeq *aColl[1];  /* Collating sequence for each term of the key */\n};\n\n/*\n** Allowed bit values for entries in the KeyInfo.aSortFlags[] array.\n*/\n#define KEYINFO_ORDER_DESC    0x01    /* DESC sort order */\n#define KEYINFO_ORDER_BIGNULL 0x02    /* NULL is larger than any other value */\n\n/*\n** This object holds a record which has been parsed out into individual\n** fields, for the purposes of doing a comparison.\n**\n** A record is an object that contains one or more fields of data.\n** Records are used to store the content of a table row and to store\n** the key of an index.  A blob encoding of a record is created by\n** the OP_MakeRecord opcode of the VDBE and is disassembled by the\n** OP_Column opcode.\n**\n** An instance of this object serves as a \"key\" for doing a search on\n** an index b+tree. The goal of the search is to find the entry that\n** is closed to the key described by this object.  This object might hold\n** just a prefix of the key.  The number of fields is given by\n** pKeyInfo->nField.\n**\n** The r1 and r2 fields are the values to return if this key is less than\n** or greater than a key in the btree, respectively.  These are normally\n** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree\n** is in DESC order.\n**\n** The key comparison functions actually return default_rc when they find\n** an equals comparison.  default_rc can be -1, 0, or +1.  If there are\n** multiple entries in the b-tree with the same key (when only looking\n** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to\n** cause the search to find the last match, or +1 to cause the search to\n** find the first match.\n**\n** The key comparison functions will set eqSeen to true if they ever\n** get and equal results when comparing this structure to a b-tree record.\n** When default_rc!=0, the search might end up on the record immediately\n** before the first match or immediately after the last match.  The\n** eqSeen field will indicate whether or not an exact match exists in the\n** b-tree.\n*/\nstruct UnpackedRecord {\n  KeyInfo *pKeyInfo;  /* Collation and sort-order information */\n  Mem *aMem;          /* Values */\n  u16 nField;         /* Number of entries in apMem[] */\n  i8 default_rc;      /* Comparison result if keys are equal */\n  u8 errCode;         /* Error detected by xRecordCompare (CORRUPT or NOMEM) */\n  i8 r1;              /* Value to return if (lhs < rhs) */\n  i8 r2;              /* Value to return if (lhs > rhs) */\n  u8 eqSeen;          /* True if an equality comparison has been seen */\n};\n\n\n/*\n** Each SQL index is represented in memory by an\n** instance of the following structure.\n**\n** The columns of the table that are to be indexed are described\n** by the aiColumn[] field of this structure.  For example, suppose\n** we have the following table and index:\n**\n**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);\n**     CREATE INDEX Ex2 ON Ex1(c3,c1);\n**\n** In the Table structure describing Ex1, nCol==3 because there are\n** three columns in the table.  In the Index structure describing\n** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.\n** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the\n** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].\n** The second column to be indexed (c1) has an index of 0 in\n** Ex1.aCol[], hence Ex2.aiColumn[1]==0.\n**\n** The Index.onError field determines whether or not the indexed columns\n** must be unique and what to do if they are not.  When Index.onError=OE_None,\n** it means this is not a unique index.  Otherwise it is a unique index\n** and the value of Index.onError indicate the which conflict resolution\n** algorithm to employ whenever an attempt is made to insert a non-unique\n** element.\n**\n** While parsing a CREATE TABLE or CREATE INDEX statement in order to\n** generate VDBE code (as opposed to parsing one read from an sqlite_master\n** table as part of parsing an existing database schema), transient instances\n** of this structure may be created. In this case the Index.tnum variable is\n** used to store the address of a VDBE instruction, not a database page\n** number (it cannot - the database page is not allocated until the VDBE\n** program is executed). See convertToWithoutRowidTable() for details.\n*/\nstruct Index {\n  char *zName;             /* Name of this index */\n  i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */\n  LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */\n  Table *pTable;           /* The SQL table being indexed */\n  char *zColAff;           /* String defining the affinity of each column */\n  Index *pNext;            /* The next index associated with the same table */\n  Schema *pSchema;         /* Schema containing this index */\n  u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */\n  const char **azColl;     /* Array of collation sequence names for index */\n  Expr *pPartIdxWhere;     /* WHERE clause for partial indices */\n  ExprList *aColExpr;      /* Column expressions */\n  int tnum;                /* DB Page containing root of this index */\n  LogEst szIdxRow;         /* Estimated average row size in bytes */\n  u16 nKeyCol;             /* Number of columns forming the key */\n  u16 nColumn;             /* Number of columns stored in the index */\n  u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */\n  unsigned idxType:2;      /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */\n  unsigned bUnordered:1;   /* Use this index for == or IN queries only */\n  unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */\n  unsigned isResized:1;    /* True if resizeIndexObject() has been called */\n  unsigned isCovering:1;   /* True if this is a covering index */\n  unsigned noSkipScan:1;   /* Do not try to use skip-scan if true */\n  unsigned hasStat1:1;     /* aiRowLogEst values come from sqlite_stat1 */\n  unsigned bNoQuery:1;     /* Do not use this index to optimize queries */\n  unsigned bAscKeyBug:1;   /* True if the bba7b69f9849b5bf bug applies */\n  unsigned bHasVCol:1;     /* Index references one or more VIRTUAL columns */\n#ifdef SQLITE_ENABLE_STAT4\n  int nSample;             /* Number of elements in aSample[] */\n  int nSampleCol;          /* Size of IndexSample.anEq[] and so on */\n  tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */\n  IndexSample *aSample;    /* Samples of the left-most key */\n  tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */\n  tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */\n#endif\n  Bitmask colNotIdxed;     /* 0 for unindexed columns in pTab */\n};\n\n/*\n** Allowed values for Index.idxType\n*/\n#define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */\n#define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */\n#define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */\n#define SQLITE_IDXTYPE_IPK         3   /* INTEGER PRIMARY KEY index */\n\n/* Return true if index X is a PRIMARY KEY index */\n#define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)\n\n/* Return true if index X is a UNIQUE index */\n#define IsUniqueIndex(X)      ((X)->onError!=OE_None)\n\n/* The Index.aiColumn[] values are normally positive integer.  But\n** there are some negative values that have special meaning:\n*/\n#define XN_ROWID     (-1)     /* Indexed column is the rowid */\n#define XN_EXPR      (-2)     /* Indexed column is an expression */\n\n/*\n** Each sample stored in the sqlite_stat4 table is represented in memory\n** using a structure of this type.  See documentation at the top of the\n** analyze.c source file for additional information.\n*/\nstruct IndexSample {\n  void *p;          /* Pointer to sampled record */\n  int n;            /* Size of record in bytes */\n  tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */\n  tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */\n  tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */\n};\n\n/*\n** Possible values to use within the flags argument to sqlite3GetToken().\n*/\n#define SQLITE_TOKEN_QUOTED    0x1 /* Token is a quoted identifier. */\n#define SQLITE_TOKEN_KEYWORD   0x2 /* Token is a keyword. */\n\n/*\n** Each token coming out of the lexer is an instance of\n** this structure.  Tokens are also used as part of an expression.\n**\n** The memory that \"z\" points to is owned by other objects.  Take care\n** that the owner of the \"z\" string does not deallocate the string before\n** the Token goes out of scope!  Very often, the \"z\" points to some place\n** in the middle of the Parse.zSql text.  But it might also point to a\n** static string.\n*/\nstruct Token {\n  const char *z;     /* Text of the token.  Not NULL-terminated! */\n  unsigned int n;    /* Number of characters in this token */\n};\n\n/*\n** An instance of this structure contains information needed to generate\n** code for a SELECT that contains aggregate functions.\n**\n** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a\n** pointer to this structure.  The Expr.iAgg field is the index in\n** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate\n** code for that node.\n**\n** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the\n** original Select structure that describes the SELECT statement.  These\n** fields do not need to be freed when deallocating the AggInfo structure.\n*/\nstruct AggInfo {\n  u8 directMode;          /* Direct rendering mode means take data directly\n                          ** from source tables rather than from accumulators */\n  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather\n                          ** than the source table */\n  int sortingIdx;         /* Cursor number of the sorting index */\n  int sortingIdxPTab;     /* Cursor number of pseudo-table */\n  int nSortingColumn;     /* Number of columns in the sorting index */\n  int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */\n  ExprList *pGroupBy;     /* The group by clause */\n  struct AggInfo_col {    /* For each column used in source tables */\n    Table *pTab;             /* Source table */\n    Expr *pExpr;             /* The original expression */\n    int iTable;              /* Cursor number of the source table */\n    int iMem;                /* Memory location that acts as accumulator */\n    i16 iColumn;             /* Column number within the source table */\n    i16 iSorterColumn;       /* Column number in the sorting index */\n  } *aCol;\n  int nColumn;            /* Number of used entries in aCol[] */\n  int nAccumulator;       /* Number of columns that show through to the output.\n                          ** Additional columns are used only as parameters to\n                          ** aggregate functions */\n  struct AggInfo_func {   /* For each aggregate function */\n    Expr *pExpr;             /* Expression encoding the function */\n    FuncDef *pFunc;          /* The aggregate function implementation */\n    int iMem;                /* Memory location that acts as accumulator */\n    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */\n  } *aFunc;\n  int nFunc;              /* Number of entries in aFunc[] */\n#ifdef SQLITE_DEBUG\n  int iAggMagic;          /* Magic number when valid */\n#endif\n  AggInfo *pNext;         /* Next in list of them all */\n};\n\n/*\n** Value for AggInfo.iAggMagic when the structure is valid\n*/\n#define AggInfoMagic  0x2059e99e\n\n/*\n** The datatype ynVar is a signed integer, either 16-bit or 32-bit.\n** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater\n** than 32767 we have to make it 32-bit.  16-bit is preferred because\n** it uses less memory in the Expr object, which is a big memory user\n** in systems with lots of prepared statements.  And few applications\n** need more than about 10 or 20 variables.  But some extreme users want\n** to have prepared statements with over 32766 variables, and for them\n** the option is available (at compile-time).\n*/\n#if SQLITE_MAX_VARIABLE_NUMBER<32767\ntypedef i16 ynVar;\n#else\ntypedef int ynVar;\n#endif\n\n/*\n** Each node of an expression in the parse tree is an instance\n** of this structure.\n**\n** Expr.op is the opcode. The integer parser token codes are reused\n** as opcodes here. For example, the parser defines TK_GE to be an integer\n** code representing the \">=\" operator. This same integer code is reused\n** to represent the greater-than-or-equal-to operator in the expression\n** tree.\n**\n** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,\n** or TK_STRING), then Expr.token contains the text of the SQL literal. If\n** the expression is a variable (TK_VARIABLE), then Expr.token contains the\n** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),\n** then Expr.token contains the name of the function.\n**\n** Expr.pRight and Expr.pLeft are the left and right subexpressions of a\n** binary operator. Either or both may be NULL.\n**\n** Expr.x.pList is a list of arguments if the expression is an SQL function,\n** a CASE expression or an IN expression of the form \"<lhs> IN (<y>, <z>...)\".\n** Expr.x.pSelect is used if the expression is a sub-select or an expression of\n** the form \"<lhs> IN (SELECT ...)\". If the EP_xIsSelect bit is set in the\n** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is\n** valid.\n**\n** An expression of the form ID or ID.ID refers to a column in a table.\n** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is\n** the integer cursor number of a VDBE cursor pointing to that table and\n** Expr.iColumn is the column number for the specific column.  If the\n** expression is used as a result in an aggregate SELECT, then the\n** value is also stored in the Expr.iAgg column in the aggregate so that\n** it can be accessed after all aggregates are computed.\n**\n** If the expression is an unbound variable marker (a question mark\n** character '?' in the original SQL) then the Expr.iTable holds the index\n** number for that variable.\n**\n** If the expression is a subquery then Expr.iColumn holds an integer\n** register number containing the result of the subquery.  If the\n** subquery gives a constant result, then iTable is -1.  If the subquery\n** gives a different answer at different times during statement processing\n** then iTable is the address of a subroutine that computes the subquery.\n**\n** If the Expr is of type OP_Column, and the table it is selecting from\n** is a disk table or the \"old.*\" pseudo-table, then pTab points to the\n** corresponding table definition.\n**\n** ALLOCATION NOTES:\n**\n** Expr objects can use a lot of memory space in database schema.  To\n** help reduce memory requirements, sometimes an Expr object will be\n** truncated.  And to reduce the number of memory allocations, sometimes\n** two or more Expr objects will be stored in a single memory allocation,\n** together with Expr.zToken strings.\n**\n** If the EP_Reduced and EP_TokenOnly flags are set when\n** an Expr object is truncated.  When EP_Reduced is set, then all\n** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees\n** are contained within the same memory allocation.  Note, however, that\n** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately\n** allocated, regardless of whether or not EP_Reduced is set.\n*/\nstruct Expr {\n  u8 op;                 /* Operation performed by this node */\n  char affExpr;          /* affinity, or RAISE type */\n  u8 op2;                /* TK_REGISTER/TK_TRUTH: original value of Expr.op\n                         ** TK_COLUMN: the value of p5 for OP_Column\n                         ** TK_AGG_FUNCTION: nesting depth\n                         ** TK_FUNCTION: NC_SelfRef flag if needs OP_PureFunc */\n#ifdef SQLITE_DEBUG\n  u8 vvaFlags;           /* Verification flags. */\n#endif\n  u32 flags;             /* Various flags.  EP_* See below */\n  union {\n    char *zToken;          /* Token value. Zero terminated and dequoted */\n    int iValue;            /* Non-negative integer value if EP_IntValue */\n  } u;\n\n  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no\n  ** space is allocated for the fields below this point. An attempt to\n  ** access them will result in a segfault or malfunction.\n  *********************************************************************/\n\n  Expr *pLeft;           /* Left subnode */\n  Expr *pRight;          /* Right subnode */\n  union {\n    ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */\n    Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */\n  } x;\n\n  /* If the EP_Reduced flag is set in the Expr.flags mask, then no\n  ** space is allocated for the fields below this point. An attempt to\n  ** access them will result in a segfault or malfunction.\n  *********************************************************************/\n\n#if SQLITE_MAX_EXPR_DEPTH>0\n  int nHeight;           /* Height of the tree headed by this node */\n#endif\n  int iTable;            /* TK_COLUMN: cursor number of table holding column\n                         ** TK_REGISTER: register number\n                         ** TK_TRIGGER: 1 -> new, 0 -> old\n                         ** EP_Unlikely:  134217728 times likelihood\n                         ** TK_IN: ephemerial table holding RHS\n                         ** TK_SELECT_COLUMN: Number of columns on the LHS\n                         ** TK_SELECT: 1st register of result vector */\n  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.\n                         ** TK_VARIABLE: variable number (always >= 1).\n                         ** TK_SELECT_COLUMN: column of the result vector */\n  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */\n  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */\n  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */\n  union {\n    Table *pTab;           /* TK_COLUMN: Table containing column. Can be NULL\n                           ** for a column of an index on an expression */\n    Window *pWin;          /* EP_WinFunc: Window/Filter defn for a function */\n    struct {               /* TK_IN, TK_SELECT, and TK_EXISTS */\n      int iAddr;             /* Subroutine entry address */\n      int regReturn;         /* Register used to hold return address */\n    } sub;\n  } y;\n};\n\n/*\n** The following are the meanings of bits in the Expr.flags field.\n** Value restrictions:\n**\n**          EP_Agg == NC_HasAgg == SF_HasAgg\n**          EP_Win == NC_HasWin\n*/\n#define EP_FromJoin   0x000001 /* Originates in ON/USING clause of outer join */\n#define EP_Distinct   0x000002 /* Aggregate function with DISTINCT keyword */\n#define EP_HasFunc    0x000004 /* Contains one or more functions of any kind */\n#define EP_FixedCol   0x000008 /* TK_Column with a known fixed value */\n#define EP_Agg        0x000010 /* Contains one or more aggregate functions */\n#define EP_VarSelect  0x000020 /* pSelect is correlated, not constant */\n#define EP_DblQuoted  0x000040 /* token.z was originally in \"...\" */\n#define EP_InfixFunc  0x000080 /* True for an infix function: LIKE, GLOB, etc */\n#define EP_Collate    0x000100 /* Tree contains a TK_COLLATE operator */\n#define EP_Commuted   0x000200 /* Comparison operator has been commuted */\n#define EP_IntValue   0x000400 /* Integer value contained in u.iValue */\n#define EP_xIsSelect  0x000800 /* x.pSelect is valid (otherwise x.pList is) */\n#define EP_Skip       0x001000 /* Operator does not contribute to affinity */\n#define EP_Reduced    0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */\n#define EP_TokenOnly  0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */\n#define EP_Win        0x008000 /* Contains window functions */\n#define EP_MemToken   0x010000 /* Need to sqlite3DbFree() Expr.zToken */\n                  /*  0x020000 // available for reuse */\n#define EP_Unlikely   0x040000 /* unlikely() or likelihood() function */\n#define EP_ConstFunc  0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */\n#define EP_CanBeNull  0x100000 /* Can be null despite NOT NULL constraint */\n#define EP_Subquery   0x200000 /* Tree contains a TK_SELECT operator */\n#define EP_Alias      0x400000 /* Is an alias for a result set column */\n#define EP_Leaf       0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */\n#define EP_WinFunc   0x1000000 /* TK_FUNCTION with Expr.y.pWin set */\n#define EP_Subrtn    0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */\n#define EP_Quoted    0x4000000 /* TK_ID was originally quoted */\n#define EP_Static    0x8000000 /* Held in memory not obtained from malloc() */\n#define EP_IsTrue   0x10000000 /* Always has boolean value of TRUE */\n#define EP_IsFalse  0x20000000 /* Always has boolean value of FALSE */\n#define EP_FromDDL  0x40000000 /* Originates from sqlite_master */\n               /*   0x80000000 // Available */\n\n/*\n** The EP_Propagate mask is a set of properties that automatically propagate\n** upwards into parent nodes.\n*/\n#define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)\n\n/*\n** These macros can be used to test, set, or clear bits in the\n** Expr.flags field.\n*/\n#define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)\n#define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))\n#define ExprSetProperty(E,P)     (E)->flags|=(P)\n#define ExprClearProperty(E,P)   (E)->flags&=~(P)\n#define ExprAlwaysTrue(E)   (((E)->flags&(EP_FromJoin|EP_IsTrue))==EP_IsTrue)\n#define ExprAlwaysFalse(E)  (((E)->flags&(EP_FromJoin|EP_IsFalse))==EP_IsFalse)\n\n\n/* Flags for use with Expr.vvaFlags\n*/\n#define EP_NoReduce   0x01  /* Cannot EXPRDUP_REDUCE this Expr */\n#define EP_Immutable  0x02  /* Do not change this Expr node */\n\n/* The ExprSetVVAProperty() macro is used for Verification, Validation,\n** and Accreditation only.  It works like ExprSetProperty() during VVA\n** processes but is a no-op for delivery.\n*/\n#ifdef SQLITE_DEBUG\n# define ExprSetVVAProperty(E,P)   (E)->vvaFlags|=(P)\n# define ExprHasVVAProperty(E,P)   (((E)->vvaFlags&(P))!=0)\n# define ExprClearVVAProperties(E) (E)->vvaFlags = 0\n#else\n# define ExprSetVVAProperty(E,P)\n# define ExprHasVVAProperty(E,P)   0\n# define ExprClearVVAProperties(E)\n#endif\n\n/*\n** Macros to determine the number of bytes required by a normal Expr\n** struct, an Expr struct with the EP_Reduced flag set in Expr.flags\n** and an Expr struct with the EP_TokenOnly flag set.\n*/\n#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */\n#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */\n#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */\n\n/*\n** Flags passed to the sqlite3ExprDup() function. See the header comment\n** above sqlite3ExprDup() for details.\n*/\n#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */\n\n/*\n** True if the expression passed as an argument was a function with\n** an OVER() clause (a window function).\n*/\n#ifdef SQLITE_OMIT_WINDOWFUNC\n# define IsWindowFunc(p) 0\n#else\n# define IsWindowFunc(p) ( \\\n    ExprHasProperty((p), EP_WinFunc) && p->y.pWin->eFrmType!=TK_FILTER \\\n )\n#endif\n\n/*\n** A list of expressions.  Each expression may optionally have a\n** name.  An expr/name combination can be used in several ways, such\n** as the list of \"expr AS ID\" fields following a \"SELECT\" or in the\n** list of \"ID = expr\" items in an UPDATE.  A list of expressions can\n** also be used as the argument to a function, in which case the a.zName\n** field is not used.\n**\n** In order to try to keep memory usage down, the Expr.a.zEName field\n** is used for multiple purposes:\n**\n**     eEName          Usage\n**    ----------       -------------------------\n**    ENAME_NAME       (1) the AS of result set column\n**                     (2) COLUMN= of an UPDATE\n**\n**    ENAME_TAB        DB.TABLE.NAME used to resolve names\n**                     of subqueries\n**\n**    ENAME_SPAN       Text of the original result set\n**                     expression.\n*/\nstruct ExprList {\n  int nExpr;             /* Number of expressions on the list */\n  struct ExprList_item { /* For each expression in the list */\n    Expr *pExpr;            /* The parse tree for this expression */\n    char *zEName;           /* Token associated with this expression */\n    u8 sortFlags;           /* Mask of KEYINFO_ORDER_* flags */\n    unsigned eEName :2;     /* Meaning of zEName */\n    unsigned done :1;       /* A flag to indicate when processing is finished */\n    unsigned reusable :1;   /* Constant expression is reusable */\n    unsigned bSorterRef :1; /* Defer evaluation until after sorting */\n    unsigned bNulls: 1;     /* True if explicit \"NULLS FIRST/LAST\" */\n    union {\n      struct {\n        u16 iOrderByCol;      /* For ORDER BY, column number in result set */\n        u16 iAlias;           /* Index into Parse.aAlias[] for zName */\n      } x;\n      int iConstExprReg;      /* Register in which Expr value is cached */\n    } u;\n  } a[1];                  /* One slot for each expression in the list */\n};\n\n/*\n** Allowed values for Expr.a.eEName\n*/\n#define ENAME_NAME  0       /* The AS clause of a result set */\n#define ENAME_SPAN  1       /* Complete text of the result set expression */\n#define ENAME_TAB   2       /* \"DB.TABLE.NAME\" for the result set */\n\n/*\n** An instance of this structure can hold a simple list of identifiers,\n** such as the list \"a,b,c\" in the following statements:\n**\n**      INSERT INTO t(a,b,c) VALUES ...;\n**      CREATE INDEX idx ON t(a,b,c);\n**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;\n**\n** The IdList.a.idx field is used when the IdList represents the list of\n** column names after a table name in an INSERT statement.  In the statement\n**\n**     INSERT INTO t(a,b,c) ...\n**\n** If \"a\" is the k-th column of table \"t\", then IdList.a[0].idx==k.\n*/\nstruct IdList {\n  struct IdList_item {\n    char *zName;      /* Name of the identifier */\n    int idx;          /* Index in some Table.aCol[] of a column named zName */\n  } *a;\n  int nId;         /* Number of identifiers on the list */\n};\n\n/*\n** The following structure describes the FROM clause of a SELECT statement.\n** Each table or subquery in the FROM clause is a separate element of\n** the SrcList.a[] array.\n**\n** With the addition of multiple database support, the following structure\n** can also be used to describe a particular table such as the table that\n** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,\n** such a table must be a simple name: ID.  But in SQLite, the table can\n** now be identified by a database name, a dot, then the table name: ID.ID.\n**\n** The jointype starts out showing the join type between the current table\n** and the next table on the list.  The parser builds the list this way.\n** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each\n** jointype expresses the join between the table and the previous table.\n**\n** In the colUsed field, the high-order bit (bit 63) is set if the table\n** contains more than 63 columns and the 64-th or later column is used.\n*/\nstruct SrcList {\n  int nSrc;        /* Number of tables or subqueries in the FROM clause */\n  u32 nAlloc;      /* Number of entries allocated in a[] below */\n  struct SrcList_item {\n    Schema *pSchema;  /* Schema to which this item is fixed */\n    char *zDatabase;  /* Name of database holding this table */\n    char *zName;      /* Name of the table */\n    char *zAlias;     /* The \"B\" part of a \"A AS B\" phrase.  zName is the \"A\" */\n    Table *pTab;      /* An SQL table corresponding to zName */\n    Select *pSelect;  /* A SELECT statement used in place of a table name */\n    int addrFillSub;  /* Address of subroutine to manifest a subquery */\n    int regReturn;    /* Register holding return address of addrFillSub */\n    int regResult;    /* Registers holding results of a co-routine */\n    struct {\n      u8 jointype;      /* Type of join between this table and the previous */\n      unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */\n      unsigned isIndexedBy :1;   /* True if there is an INDEXED BY clause */\n      unsigned isTabFunc :1;     /* True if table-valued-function syntax */\n      unsigned isCorrelated :1;  /* True if sub-query is correlated */\n      unsigned viaCoroutine :1;  /* Implemented as a co-routine */\n      unsigned isRecursive :1;   /* True for recursive reference in WITH */\n      unsigned fromDDL :1;       /* Comes from sqlite_master */\n    } fg;\n    int iCursor;      /* The VDBE cursor number used to access this table */\n    Expr *pOn;        /* The ON clause of a join */\n    IdList *pUsing;   /* The USING clause of a join */\n    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */\n    union {\n      char *zIndexedBy;    /* Identifier from \"INDEXED BY <zIndex>\" clause */\n      ExprList *pFuncArg;  /* Arguments to table-valued-function */\n    } u1;\n    Index *pIBIndex;  /* Index structure corresponding to u1.zIndexedBy */\n  } a[1];             /* One entry for each identifier on the list */\n};\n\n/*\n** Permitted values of the SrcList.a.jointype field\n*/\n#define JT_INNER     0x0001    /* Any kind of inner or cross join */\n#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */\n#define JT_NATURAL   0x0004    /* True for a \"natural\" join */\n#define JT_LEFT      0x0008    /* Left outer join */\n#define JT_RIGHT     0x0010    /* Right outer join */\n#define JT_OUTER     0x0020    /* The \"OUTER\" keyword is present */\n#define JT_ERROR     0x0040    /* unknown or unsupported join type */\n\n\n/*\n** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()\n** and the WhereInfo.wctrlFlags member.\n**\n** Value constraints (enforced via assert()):\n**     WHERE_USE_LIMIT  == SF_FixedLimit\n*/\n#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */\n#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */\n#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */\n#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */\n#define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */\n#define WHERE_DUPLICATES_OK    0x0010 /* Ok to return a row more than once */\n#define WHERE_OR_SUBCLAUSE     0x0020 /* Processing a sub-WHERE as part of\n                                      ** the OR optimization  */\n#define WHERE_GROUPBY          0x0040 /* pOrderBy is really a GROUP BY */\n#define WHERE_DISTINCTBY       0x0080 /* pOrderby is really a DISTINCT clause */\n#define WHERE_WANT_DISTINCT    0x0100 /* All output needs to be distinct */\n#define WHERE_SORTBYGROUP      0x0200 /* Support sqlite3WhereIsSorted() */\n#define WHERE_SEEK_TABLE       0x0400 /* Do not defer seeks on main table */\n#define WHERE_ORDERBY_LIMIT    0x0800 /* ORDERBY+LIMIT on the inner loop */\n#define WHERE_SEEK_UNIQ_TABLE  0x1000 /* Do not defer seeks if unique */\n                        /*     0x2000    not currently used */\n#define WHERE_USE_LIMIT        0x4000 /* Use the LIMIT in cost estimates */\n                        /*     0x8000    not currently used */\n\n/* Allowed return values from sqlite3WhereIsDistinct()\n*/\n#define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */\n#define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */\n#define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */\n#define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */\n\n/*\n** A NameContext defines a context in which to resolve table and column\n** names.  The context consists of a list of tables (the pSrcList) field and\n** a list of named expression (pEList).  The named expression list may\n** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or\n** to the table being operated on by INSERT, UPDATE, or DELETE.  The\n** pEList corresponds to the result set of a SELECT and is NULL for\n** other statements.\n**\n** NameContexts can be nested.  When resolving names, the inner-most\n** context is searched first.  If no match is found, the next outer\n** context is checked.  If there is still no match, the next context\n** is checked.  This process continues until either a match is found\n** or all contexts are check.  When a match is found, the nRef member of\n** the context containing the match is incremented.\n**\n** Each subquery gets a new NameContext.  The pNext field points to the\n** NameContext in the parent query.  Thus the process of scanning the\n** NameContext list corresponds to searching through successively outer\n** subqueries looking for a match.\n*/\nstruct NameContext {\n  Parse *pParse;       /* The parser */\n  SrcList *pSrcList;   /* One or more tables used to resolve names */\n  union {\n    ExprList *pEList;    /* Optional list of result-set columns */\n    AggInfo *pAggInfo;   /* Information about aggregates at this level */\n    Upsert *pUpsert;     /* ON CONFLICT clause information from an upsert */\n  } uNC;\n  NameContext *pNext;  /* Next outer name context.  NULL for outermost */\n  int nRef;            /* Number of names resolved by this context */\n  int nErr;            /* Number of errors encountered while resolving names */\n  int ncFlags;         /* Zero or more NC_* flags defined below */\n  Select *pWinSelect;  /* SELECT statement for any window functions */\n};\n\n/*\n** Allowed values for the NameContext, ncFlags field.\n**\n** Value constraints (all checked via assert()):\n**    NC_HasAgg    == SF_HasAgg    == EP_Agg\n**    NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX\n**    NC_HasWin    == EP_Win\n**\n*/\n#define NC_AllowAgg  0x00001  /* Aggregate functions are allowed here */\n#define NC_PartIdx   0x00002  /* True if resolving a partial index WHERE */\n#define NC_IsCheck   0x00004  /* True if resolving a CHECK constraint */\n#define NC_GenCol    0x00008  /* True for a GENERATED ALWAYS AS clause */\n#define NC_HasAgg    0x00010  /* One or more aggregate functions seen */\n#define NC_IdxExpr   0x00020  /* True if resolving columns of CREATE INDEX */\n#define NC_SelfRef   0x0002e  /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */\n#define NC_VarSelect 0x00040  /* A correlated subquery has been seen */\n#define NC_UEList    0x00080  /* True if uNC.pEList is used */\n#define NC_UAggInfo  0x00100  /* True if uNC.pAggInfo is used */\n#define NC_UUpsert   0x00200  /* True if uNC.pUpsert is used */\n#define NC_MinMaxAgg 0x01000  /* min/max aggregates seen.  See note above */\n#define NC_Complex   0x02000  /* True if a function or subquery seen */\n#define NC_AllowWin  0x04000  /* Window functions are allowed here */\n#define NC_HasWin    0x08000  /* One or more window functions seen */\n#define NC_IsDDL     0x10000  /* Resolving names in a CREATE statement */\n#define NC_InAggFunc 0x20000  /* True if analyzing arguments to an agg func */\n#define NC_FromDDL   0x40000  /* SQL text comes from sqlite_master */\n\n/*\n** An instance of the following object describes a single ON CONFLICT\n** clause in an upsert.\n**\n** The pUpsertTarget field is only set if the ON CONFLICT clause includes\n** conflict-target clause.  (In \"ON CONFLICT(a,b)\" the \"(a,b)\" is the\n** conflict-target clause.)  The pUpsertTargetWhere is the optional\n** WHERE clause used to identify partial unique indexes.\n**\n** pUpsertSet is the list of column=expr terms of the UPDATE statement. \n** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING.  The\n** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the\n** WHERE clause is omitted.\n*/\nstruct Upsert {\n  ExprList *pUpsertTarget;  /* Optional description of conflicting index */\n  Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */\n  ExprList *pUpsertSet;     /* The SET clause from an ON CONFLICT UPDATE */\n  Expr *pUpsertWhere;       /* WHERE clause for the ON CONFLICT UPDATE */\n  /* The fields above comprise the parse tree for the upsert clause.\n  ** The fields below are used to transfer information from the INSERT\n  ** processing down into the UPDATE processing while generating code.\n  ** Upsert owns the memory allocated above, but not the memory below. */\n  Index *pUpsertIdx;        /* Constraint that pUpsertTarget identifies */\n  SrcList *pUpsertSrc;      /* Table to be updated */\n  int regData;              /* First register holding array of VALUES */\n  int iDataCur;             /* Index of the data cursor */\n  int iIdxCur;              /* Index of the first index cursor */\n};\n\n/*\n** An instance of the following structure contains all information\n** needed to generate code for a single SELECT statement.\n**\n** See the header comment on the computeLimitRegisters() routine for a\n** detailed description of the meaning of the iLimit and iOffset fields.\n**\n** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.\n** These addresses must be stored so that we can go back and fill in\n** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor\n** the number of columns in P2 can be computed at the same time\n** as the OP_OpenEphm instruction is coded because not\n** enough information about the compound query is known at that point.\n** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences\n** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating\n** sequences for the ORDER BY clause.\n*/\nstruct Select {\n  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */\n  LogEst nSelectRow;     /* Estimated number of result rows */\n  u32 selFlags;          /* Various SF_* values */\n  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */\n  u32 selId;             /* Unique identifier number for this SELECT */\n  int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */\n  ExprList *pEList;      /* The fields of the result */\n  SrcList *pSrc;         /* The FROM clause */\n  Expr *pWhere;          /* The WHERE clause */\n  ExprList *pGroupBy;    /* The GROUP BY clause */\n  Expr *pHaving;         /* The HAVING clause */\n  ExprList *pOrderBy;    /* The ORDER BY clause */\n  Select *pPrior;        /* Prior select in a compound select statement */\n  Select *pNext;         /* Next select to the left in a compound */\n  Expr *pLimit;          /* LIMIT expression. NULL means not used. */\n  With *pWith;           /* WITH clause attached to this select. Or NULL. */\n#ifndef SQLITE_OMIT_WINDOWFUNC\n  Window *pWin;          /* List of window functions */\n  Window *pWinDefn;      /* List of named window definitions */\n#endif\n};\n\n/*\n** Allowed values for Select.selFlags.  The \"SF\" prefix stands for\n** \"Select Flag\".\n**\n** Value constraints (all checked via assert())\n**     SF_HasAgg     == NC_HasAgg\n**     SF_MinMaxAgg  == NC_MinMaxAgg     == SQLITE_FUNC_MINMAX\n**     SF_FixedLimit == WHERE_USE_LIMIT\n*/\n#define SF_Distinct      0x0000001 /* Output should be DISTINCT */\n#define SF_All           0x0000002 /* Includes the ALL keyword */\n#define SF_Resolved      0x0000004 /* Identifiers have been resolved */\n#define SF_Aggregate     0x0000008 /* Contains agg functions or a GROUP BY */\n#define SF_HasAgg        0x0000010 /* Contains aggregate functions */\n#define SF_UsesEphemeral 0x0000020 /* Uses the OpenEphemeral opcode */\n#define SF_Expanded      0x0000040 /* sqlite3SelectExpand() called on this */\n#define SF_HasTypeInfo   0x0000080 /* FROM subqueries have Table metadata */\n#define SF_Compound      0x0000100 /* Part of a compound query */\n#define SF_Values        0x0000200 /* Synthesized from VALUES clause */\n#define SF_MultiValue    0x0000400 /* Single VALUES term with multiple rows */\n#define SF_NestedFrom    0x0000800 /* Part of a parenthesized FROM clause */\n#define SF_MinMaxAgg     0x0001000 /* Aggregate containing min() or max() */\n#define SF_Recursive     0x0002000 /* The recursive part of a recursive CTE */\n#define SF_FixedLimit    0x0004000 /* nSelectRow set by a constant LIMIT */\n#define SF_MaybeConvert  0x0008000 /* Need convertCompoundSelectToSubquery() */\n#define SF_Converted     0x0010000 /* By convertCompoundSelectToSubquery() */\n#define SF_IncludeHidden 0x0020000 /* Include hidden columns in output */\n#define SF_ComplexResult 0x0040000 /* Result contains subquery or function */\n#define SF_WhereBegin    0x0080000 /* Really a WhereBegin() call.  Debug Only */\n#define SF_WinRewrite    0x0100000 /* Window function rewrite accomplished */\n#define SF_View          0x0200000 /* SELECT statement is a view */\n#define SF_NoopOrderBy   0x0400000 /* ORDER BY is ignored for this query */\n\n/*\n** The results of a SELECT can be distributed in several ways, as defined\n** by one of the following macros.  The \"SRT\" prefix means \"SELECT Result\n** Type\".\n**\n**     SRT_Union       Store results as a key in a temporary index\n**                     identified by pDest->iSDParm.\n**\n**     SRT_Except      Remove results from the temporary index pDest->iSDParm.\n**\n**     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result\n**                     set is not empty.\n**\n**     SRT_Discard     Throw the results away.  This is used by SELECT\n**                     statements within triggers whose only purpose is\n**                     the side-effects of functions.\n**\n** All of the above are free to ignore their ORDER BY clause. Those that\n** follow must honor the ORDER BY clause.\n**\n**     SRT_Output      Generate a row of output (using the OP_ResultRow\n**                     opcode) for each row in the result set.\n**\n**     SRT_Mem         Only valid if the result is a single column.\n**                     Store the first column of the first result row\n**                     in register pDest->iSDParm then abandon the rest\n**                     of the query.  This destination implies \"LIMIT 1\".\n**\n**     SRT_Set         The result must be a single column.  Store each\n**                     row of result as the key in table pDest->iSDParm.\n**                     Apply the affinity pDest->affSdst before storing\n**                     results.  Used to implement \"IN (SELECT ...)\".\n**\n**     SRT_EphemTab    Create an temporary table pDest->iSDParm and store\n**                     the result there. The cursor is left open after\n**                     returning.  This is like SRT_Table except that\n**                     this destination uses OP_OpenEphemeral to create\n**                     the table first.\n**\n**     SRT_Coroutine   Generate a co-routine that returns a new row of\n**                     results each time it is invoked.  The entry point\n**                     of the co-routine is stored in register pDest->iSDParm\n**                     and the result row is stored in pDest->nDest registers\n**                     starting with pDest->iSdst.\n**\n**     SRT_Table       Store results in temporary table pDest->iSDParm.\n**     SRT_Fifo        This is like SRT_EphemTab except that the table\n**                     is assumed to already be open.  SRT_Fifo has\n**                     the additional property of being able to ignore\n**                     the ORDER BY clause.\n**\n**     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.\n**                     But also use temporary table pDest->iSDParm+1 as\n**                     a record of all prior results and ignore any duplicate\n**                     rows.  Name means:  \"Distinct Fifo\".\n**\n**     SRT_Queue       Store results in priority queue pDest->iSDParm (really\n**                     an index).  Append a sequence number so that all entries\n**                     are distinct.\n**\n**     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if\n**                     the same record has never been stored before.  The\n**                     index at pDest->iSDParm+1 hold all prior stores.\n*/\n#define SRT_Union        1  /* Store result as keys in an index */\n#define SRT_Except       2  /* Remove result from a UNION index */\n#define SRT_Exists       3  /* Store 1 if the result is not empty */\n#define SRT_Discard      4  /* Do not save the results anywhere */\n#define SRT_Fifo         5  /* Store result as data with an automatic rowid */\n#define SRT_DistFifo     6  /* Like SRT_Fifo, but unique results only */\n#define SRT_Queue        7  /* Store result in an queue */\n#define SRT_DistQueue    8  /* Like SRT_Queue, but unique results only */\n\n/* The ORDER BY clause is ignored for all of the above */\n#define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)\n\n#define SRT_Output       9  /* Output each row of result */\n#define SRT_Mem         10  /* Store result in a memory cell */\n#define SRT_Set         11  /* Store results as keys in an index */\n#define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */\n#define SRT_Coroutine   13  /* Generate a single row of result */\n#define SRT_Table       14  /* Store result as data with an automatic rowid */\n\n/*\n** An instance of this object describes where to put of the results of\n** a SELECT statement.\n*/\nstruct SelectDest {\n  u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */\n  int iSDParm;         /* A parameter used by the eDest disposal method */\n  int iSdst;           /* Base register where results are written */\n  int nSdst;           /* Number of registers allocated */\n  char *zAffSdst;      /* Affinity used when eDest==SRT_Set */\n  ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */\n};\n\n/*\n** During code generation of statements that do inserts into AUTOINCREMENT\n** tables, the following information is attached to the Table.u.autoInc.p\n** pointer of each autoincrement table to record some side information that\n** the code generator needs.  We have to keep per-table autoincrement\n** information in case inserts are done within triggers.  Triggers do not\n** normally coordinate their activities, but we do need to coordinate the\n** loading and saving of autoincrement information.\n*/\nstruct AutoincInfo {\n  AutoincInfo *pNext;   /* Next info block in a list of them all */\n  Table *pTab;          /* Table this info block refers to */\n  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */\n  int regCtr;           /* Memory register holding the rowid counter */\n};\n\n/*\n** At least one instance of the following structure is created for each\n** trigger that may be fired while parsing an INSERT, UPDATE or DELETE\n** statement. All such objects are stored in the linked list headed at\n** Parse.pTriggerPrg and deleted once statement compilation has been\n** completed.\n**\n** A Vdbe sub-program that implements the body and WHEN clause of trigger\n** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of\n** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.\n** The Parse.pTriggerPrg list never contains two entries with the same\n** values for both pTrigger and orconf.\n**\n** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns\n** accessed (or set to 0 for triggers fired as a result of INSERT\n** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to\n** a mask of new.* columns used by the program.\n*/\nstruct TriggerPrg {\n  Trigger *pTrigger;      /* Trigger this program was coded from */\n  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */\n  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */\n  int orconf;             /* Default ON CONFLICT policy */\n  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */\n};\n\n/*\n** The yDbMask datatype for the bitmask of all attached databases.\n*/\n#if SQLITE_MAX_ATTACHED>30\n  typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];\n# define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)\n# define DbMaskZero(M)      memset((M),0,sizeof(M))\n# define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))\n# define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)\n# define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)\n#else\n  typedef unsigned int yDbMask;\n# define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)\n# define DbMaskZero(M)      (M)=0\n# define DbMaskSet(M,I)     (M)|=(((yDbMask)1)<<(I))\n# define DbMaskAllZero(M)   (M)==0\n# define DbMaskNonZero(M)   (M)!=0\n#endif\n\n/*\n** An SQL parser context.  A copy of this structure is passed through\n** the parser and down into all the parser action routine in order to\n** carry around information that is global to the entire parse.\n**\n** The structure is divided into two parts.  When the parser and code\n** generate call themselves recursively, the first part of the structure\n** is constant but the second part is reset at the beginning and end of\n** each recursion.\n**\n** The nTableLock and aTableLock variables are only used if the shared-cache\n** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are\n** used to store the set of table-locks required by the statement being\n** compiled. Function sqlite3TableLock() is used to add entries to the\n** list.\n*/\nstruct Parse {\n  sqlite3 *db;         /* The main database structure */\n  char *zErrMsg;       /* An error message */\n  Vdbe *pVdbe;         /* An engine for executing database bytecode */\n  int rc;              /* Return code from execution */\n  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */\n  u8 checkSchema;      /* Causes schema cookie check after an error */\n  u8 nested;           /* Number of nested calls to the parser/code generator */\n  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */\n  u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */\n  u8 mayAbort;         /* True if statement may throw an ABORT exception */\n  u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */\n  u8 okConstFactor;    /* OK to factor out constants */\n  u8 disableLookaside; /* Number of times lookaside has been disabled */\n  u8 disableVtab;      /* Disable all virtual tables for this parse */\n  int nRangeReg;       /* Size of the temporary register block */\n  int iRangeReg;       /* First register in temporary register block */\n  int nErr;            /* Number of errors seen */\n  int nTab;            /* Number of previously allocated VDBE cursors */\n  int nMem;            /* Number of memory cells used so far */\n  int szOpAlloc;       /* Bytes of memory space allocated for Vdbe.aOp[] */\n  int iSelfTab;        /* Table associated with an index on expr, or negative\n                       ** of the base register during check-constraint eval */\n  int nLabel;          /* The *negative* of the number of labels used */\n  int nLabelAlloc;     /* Number of slots in aLabel */\n  int *aLabel;         /* Space to hold the labels */\n  ExprList *pConstExpr;/* Constant expressions */\n  Token constraintName;/* Name of the constraint currently being parsed */\n  yDbMask writeMask;   /* Start a write transaction on these databases */\n  yDbMask cookieMask;  /* Bitmask of schema verified databases */\n  int regRowid;        /* Register holding rowid of CREATE TABLE entry */\n  int regRoot;         /* Register holding root page number for new objects */\n  int nMaxArg;         /* Max args passed to user function by sub-program */\n  int nSelect;         /* Number of SELECT stmts. Counter for Select.selId */\n#ifndef SQLITE_OMIT_SHARED_CACHE\n  int nTableLock;        /* Number of locks in aTableLock */\n  TableLock *aTableLock; /* Required table locks for shared-cache mode */\n#endif\n  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */\n  Parse *pToplevel;    /* Parse structure for main program (or NULL) */\n  Table *pTriggerTab;  /* Table triggers are being coded for */\n  Parse *pParentParse; /* Parent parser if this parser is nested */\n  AggInfo *pAggList;   /* List of all AggInfo objects */\n  int addrCrTab;       /* Address of OP_CreateBtree opcode on CREATE TABLE */\n  u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */\n  u32 oldmask;         /* Mask of old.* columns referenced */\n  u32 newmask;         /* Mask of new.* columns referenced */\n  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */\n  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */\n  u8 disableTriggers;  /* True to disable triggers */\n\n  /**************************************************************************\n  ** Fields above must be initialized to zero.  The fields that follow,\n  ** down to the beginning of the recursive section, do not need to be\n  ** initialized as they will be set before being used.  The boundary is\n  ** determined by offsetof(Parse,aTempReg).\n  **************************************************************************/\n\n  int aTempReg[8];        /* Holding area for temporary registers */\n  Token sNameToken;       /* Token with unqualified schema object name */\n\n  /************************************************************************\n  ** Above is constant between recursions.  Below is reset before and after\n  ** each recursion.  The boundary between these two regions is determined\n  ** using offsetof(Parse,sLastToken) so the sLastToken field must be the\n  ** first field in the recursive region.\n  ************************************************************************/\n\n  Token sLastToken;       /* The last token parsed */\n  ynVar nVar;               /* Number of '?' variables seen in the SQL so far */\n  u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */\n  u8 explain;               /* True if the EXPLAIN flag is found on the query */\n#if !(defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE))\n  u8 eParseMode;            /* PARSE_MODE_XXX constant */\n#endif\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  int nVtabLock;            /* Number of virtual tables to lock */\n#endif\n  int nHeight;              /* Expression tree height of current sub-select */\n#ifndef SQLITE_OMIT_EXPLAIN\n  int addrExplain;          /* Address of current OP_Explain opcode */\n#endif\n  VList *pVList;            /* Mapping between variable names and numbers */\n  Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */\n  const char *zTail;        /* All SQL text past the last semicolon parsed */\n  Table *pNewTable;         /* A table being constructed by CREATE TABLE */\n  Index *pNewIndex;         /* An index being constructed by CREATE INDEX.\n                            ** Also used to hold redundant UNIQUE constraints\n                            ** during a RENAME COLUMN */\n  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */\n  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  Token sArg;               /* Complete text of a module argument */\n  Table **apVtabLock;       /* Pointer to virtual tables needing locking */\n#endif\n  Table *pZombieTab;        /* List of Table objects to delete after code gen */\n  TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */\n  With *pWith;              /* Current WITH clause, or NULL */\n  With *pWithToFree;        /* Free this WITH object at the end of the parse */\n#ifndef SQLITE_OMIT_ALTERTABLE\n  RenameToken *pRename;     /* Tokens subject to renaming by ALTER TABLE */\n#endif\n};\n\n#define PARSE_MODE_NORMAL        0\n#define PARSE_MODE_DECLARE_VTAB  1\n#define PARSE_MODE_RENAME        2\n#define PARSE_MODE_UNMAP         3\n\n/*\n** Sizes and pointers of various parts of the Parse object.\n*/\n#define PARSE_HDR_SZ offsetof(Parse,aTempReg) /* Recursive part w/o aColCache*/\n#define PARSE_RECURSE_SZ offsetof(Parse,sLastToken)    /* Recursive part */\n#define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */\n#define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ)  /* Pointer to tail */\n\n/*\n** Return true if currently inside an sqlite3_declare_vtab() call.\n*/\n#ifdef SQLITE_OMIT_VIRTUALTABLE\n  #define IN_DECLARE_VTAB 0\n#else\n  #define IN_DECLARE_VTAB (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB)\n#endif\n\n#if defined(SQLITE_OMIT_ALTERTABLE)\n  #define IN_RENAME_OBJECT 0\n#else\n  #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME)\n#endif\n\n#if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE)\n  #define IN_SPECIAL_PARSE 0\n#else\n  #define IN_SPECIAL_PARSE (pParse->eParseMode!=PARSE_MODE_NORMAL)\n#endif\n\n/*\n** An instance of the following structure can be declared on a stack and used\n** to save the Parse.zAuthContext value so that it can be restored later.\n*/\nstruct AuthContext {\n  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */\n  Parse *pParse;              /* The Parse structure */\n};\n\n/*\n** Bitfield flags for P5 value in various opcodes.\n**\n** Value constraints (enforced via assert()):\n**    OPFLAG_LENGTHARG    == SQLITE_FUNC_LENGTH\n**    OPFLAG_TYPEOFARG    == SQLITE_FUNC_TYPEOF\n**    OPFLAG_BULKCSR      == BTREE_BULKLOAD\n**    OPFLAG_SEEKEQ       == BTREE_SEEK_EQ\n**    OPFLAG_FORDELETE    == BTREE_FORDELETE\n**    OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION\n**    OPFLAG_AUXDELETE    == BTREE_AUXDELETE\n*/\n#define OPFLAG_NCHANGE       0x01    /* OP_Insert: Set to update db->nChange */\n                                     /* Also used in P2 (not P5) of OP_Delete */\n#define OPFLAG_NOCHNG        0x01    /* OP_VColumn nochange for UPDATE */\n#define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */\n#define OPFLAG_LASTROWID     0x20    /* Set to update db->lastRowid */\n#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */\n#define OPFLAG_APPEND        0x08    /* This is likely to be an append */\n#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */\n#define OPFLAG_ISNOOP        0x40    /* OP_Delete does pre-update-hook only */\n#define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */\n#define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */\n#define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */\n#define OPFLAG_SEEKEQ        0x02    /* OP_Open** cursor uses EQ seek only */\n#define OPFLAG_FORDELETE     0x08    /* OP_Open should use BTREE_FORDELETE */\n#define OPFLAG_P2ISREG       0x10    /* P2 to OP_Open** is a register number */\n#define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */\n#define OPFLAG_SAVEPOSITION  0x02    /* OP_Delete/Insert: save cursor pos */\n#define OPFLAG_AUXDELETE     0x04    /* OP_Delete: index in a DELETE op */\n#define OPFLAG_NOCHNG_MAGIC  0x6d    /* OP_MakeRecord: serialtype 10 is ok */\n\n/*\n * Each trigger present in the database schema is stored as an instance of\n * struct Trigger.\n *\n * Pointers to instances of struct Trigger are stored in two ways.\n * 1. In the \"trigHash\" hash table (part of the sqlite3* that represents the\n *    database). This allows Trigger structures to be retrieved by name.\n * 2. All triggers associated with a single table form a linked list, using the\n *    pNext member of struct Trigger. A pointer to the first element of the\n *    linked list is stored as the \"pTrigger\" member of the associated\n *    struct Table.\n *\n * The \"step_list\" member points to the first element of a linked list\n * containing the SQL statements specified as the trigger program.\n */\nstruct Trigger {\n  char *zName;            /* The name of the trigger                        */\n  char *table;            /* The table or view to which the trigger applies */\n  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */\n  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */\n  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */\n  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,\n                             the <column-list> is stored here */\n  Schema *pSchema;        /* Schema containing the trigger */\n  Schema *pTabSchema;     /* Schema containing the table */\n  TriggerStep *step_list; /* Link list of trigger program steps             */\n  Trigger *pNext;         /* Next trigger associated with the table */\n};\n\n/*\n** A trigger is either a BEFORE or an AFTER trigger.  The following constants\n** determine which.\n**\n** If there are multiple triggers, you might of some BEFORE and some AFTER.\n** In that cases, the constants below can be ORed together.\n*/\n#define TRIGGER_BEFORE  1\n#define TRIGGER_AFTER   2\n\n/*\n * An instance of struct TriggerStep is used to store a single SQL statement\n * that is a part of a trigger-program.\n *\n * Instances of struct TriggerStep are stored in a singly linked list (linked\n * using the \"pNext\" member) referenced by the \"step_list\" member of the\n * associated struct Trigger instance. The first element of the linked list is\n * the first step of the trigger-program.\n *\n * The \"op\" member indicates whether this is a \"DELETE\", \"INSERT\", \"UPDATE\" or\n * \"SELECT\" statement. The meanings of the other members is determined by the\n * value of \"op\" as follows:\n *\n * (op == TK_INSERT)\n * orconf    -> stores the ON CONFLICT algorithm\n * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then\n *              this stores a pointer to the SELECT statement. Otherwise NULL.\n * zTarget   -> Dequoted name of the table to insert into.\n * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then\n *              this stores values to be inserted. Otherwise NULL.\n * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...\n *              statement, then this stores the column-names to be\n *              inserted into.\n *\n * (op == TK_DELETE)\n * zTarget   -> Dequoted name of the table to delete from.\n * pWhere    -> The WHERE clause of the DELETE statement if one is specified.\n *              Otherwise NULL.\n *\n * (op == TK_UPDATE)\n * zTarget   -> Dequoted name of the table to update.\n * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.\n *              Otherwise NULL.\n * pExprList -> A list of the columns to update and the expressions to update\n *              them to. See sqlite3Update() documentation of \"pChanges\"\n *              argument.\n *\n */\nstruct TriggerStep {\n  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */\n  u8 orconf;           /* OE_Rollback etc. */\n  Trigger *pTrig;      /* The trigger that this step is a part of */\n  Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */\n  char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */\n  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */\n  ExprList *pExprList; /* SET clause for UPDATE */\n  IdList *pIdList;     /* Column names for INSERT */\n  Upsert *pUpsert;     /* Upsert clauses on an INSERT */\n  char *zSpan;         /* Original SQL text of this command */\n  TriggerStep *pNext;  /* Next in the link-list */\n  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */\n};\n\n/*\n** The following structure contains information used by the sqliteFix...\n** routines as they walk the parse tree to make database references\n** explicit.\n*/\ntypedef struct DbFixer DbFixer;\nstruct DbFixer {\n  Parse *pParse;      /* The parsing context.  Error messages written here */\n  Schema *pSchema;    /* Fix items to this schema */\n  u8 bTemp;           /* True for TEMP schema entries */\n  const char *zDb;    /* Make sure all objects are contained in this database */\n  const char *zType;  /* Type of the container - used for error messages */\n  const Token *pName; /* Name of the container - used for error messages */\n};\n\n/*\n** An objected used to accumulate the text of a string where we\n** do not necessarily know how big the string will be in the end.\n*/\nstruct sqlite3_str {\n  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */\n  char *zText;         /* The string collected so far */\n  u32  nAlloc;         /* Amount of space allocated in zText */\n  u32  mxAlloc;        /* Maximum allowed allocation.  0 for no malloc usage */\n  u32  nChar;          /* Length of the string so far */\n  u8   accError;       /* SQLITE_NOMEM or SQLITE_TOOBIG */\n  u8   printfFlags;    /* SQLITE_PRINTF flags below */\n};\n#define SQLITE_PRINTF_INTERNAL 0x01  /* Internal-use-only converters allowed */\n#define SQLITE_PRINTF_SQLFUNC  0x02  /* SQL function arguments to VXPrintf */\n#define SQLITE_PRINTF_MALLOCED 0x04  /* True if xText is allocated space */\n\n#define isMalloced(X)  (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)\n\n\n/*\n** A pointer to this structure is used to communicate information\n** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.\n*/\ntypedef struct {\n  sqlite3 *db;        /* The database being initialized */\n  char **pzErrMsg;    /* Error message stored here */\n  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */\n  int rc;             /* Result code stored here */\n  u32 mInitFlags;     /* Flags controlling error messages */\n  u32 nInitRow;       /* Number of rows processed */\n} InitData;\n\n/*\n** Allowed values for mInitFlags\n*/\n#define INITFLAG_AlterTable   0x0001  /* This is a reparse after ALTER TABLE */\n\n/*\n** Structure containing global configuration data for the SQLite library.\n**\n** This structure also contains some state information.\n*/\nstruct Sqlite3Config {\n  int bMemstat;                     /* True to enable memory status */\n  u8 bCoreMutex;                    /* True to enable core mutexing */\n  u8 bFullMutex;                    /* True to enable full mutexing */\n  u8 bOpenUri;                      /* True to interpret filenames as URIs */\n  u8 bUseCis;                       /* Use covering indices for full-scans */\n  u8 bSmallMalloc;                  /* Avoid large memory allocations if true */\n  u8 bExtraSchemaChecks;            /* Verify type,name,tbl_name in schema */\n  int mxStrlen;                     /* Maximum string length */\n  int neverCorrupt;                 /* Database is always well-formed */\n  int szLookaside;                  /* Default lookaside buffer size */\n  int nLookaside;                   /* Default lookaside buffer count */\n  int nStmtSpill;                   /* Stmt-journal spill-to-disk threshold */\n  sqlite3_mem_methods m;            /* Low-level memory allocation interface */\n  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */\n  sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */\n  void *pHeap;                      /* Heap storage space */\n  int nHeap;                        /* Size of pHeap[] */\n  int mnReq, mxReq;                 /* Min and max heap requests sizes */\n  sqlite3_int64 szMmap;             /* mmap() space per open file */\n  sqlite3_int64 mxMmap;             /* Maximum value for szMmap */\n  void *pPage;                      /* Page cache memory */\n  int szPage;                       /* Size of each page in pPage[] */\n  int nPage;                        /* Number of pages in pPage[] */\n  int mxParserStack;                /* maximum depth of the parser stack */\n  int sharedCacheEnabled;           /* true if shared-cache mode enabled */\n  u32 szPma;                        /* Maximum Sorter PMA size */\n  /* The above might be initialized to non-zero.  The following need to always\n  ** initially be zero, however. */\n  int isInit;                       /* True after initialization has finished */\n  int inProgress;                   /* True while initialization in progress */\n  int isMutexInit;                  /* True after mutexes are initialized */\n  int isMallocInit;                 /* True after malloc is initialized */\n  int isPCacheInit;                 /* True after malloc is initialized */\n  int nRefInitMutex;                /* Number of users of pInitMutex */\n  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */\n  void (*xLog)(void*,int,const char*); /* Function for logging */\n  void *pLogArg;                       /* First argument to xLog() */\n#ifdef SQLITE_ENABLE_SQLLOG\n  void(*xSqllog)(void*,sqlite3*,const char*, int);\n  void *pSqllogArg;\n#endif\n#ifdef SQLITE_VDBE_COVERAGE\n  /* The following callback (if not NULL) is invoked on every VDBE branch\n  ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.\n  */\n  void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx);  /* Callback */\n  void *pVdbeBranchArg;                                     /* 1st argument */\n#endif\n#ifdef SQLITE_ENABLE_DESERIALIZE\n  sqlite3_int64 mxMemdbSize;        /* Default max memdb size */\n#endif\n#ifndef SQLITE_UNTESTABLE\n  int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */\n#endif\n  int bLocaltimeFault;              /* True to fail localtime() calls */\n  int iOnceResetThreshold;          /* When to reset OP_Once counters */\n  u32 szSorterRef;                  /* Min size in bytes to use sorter-refs */\n  unsigned int iPrngSeed;           /* Alternative fixed seed for the PRNG */\n};\n\n/*\n** This macro is used inside of assert() statements to indicate that\n** the assert is only valid on a well-formed database.  Instead of:\n**\n**     assert( X );\n**\n** One writes:\n**\n**     assert( X || CORRUPT_DB );\n**\n** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate\n** that the database is definitely corrupt, only that it might be corrupt.\n** For most test cases, CORRUPT_DB is set to false using a special\n** sqlite3_test_control().  This enables assert() statements to prove\n** things that are always true for well-formed databases.\n*/\n#define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)\n\n/*\n** Context pointer passed down through the tree-walk.\n*/\nstruct Walker {\n  Parse *pParse;                            /* Parser context.  */\n  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */\n  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */\n  void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */\n  int walkerDepth;                          /* Number of subqueries */\n  u16 eCode;                                /* A small processing code */\n  union {                                   /* Extra data for callback */\n    NameContext *pNC;                         /* Naming context */\n    int n;                                    /* A counter */\n    int iCur;                                 /* A cursor number */\n    SrcList *pSrcList;                        /* FROM clause */\n    struct SrcCount *pSrcCount;               /* Counting column references */\n    struct CCurHint *pCCurHint;               /* Used by codeCursorHint() */\n    int *aiCol;                               /* array of column indexes */\n    struct IdxCover *pIdxCover;               /* Check for index coverage */\n    struct IdxExprTrans *pIdxTrans;           /* Convert idxed expr to column */\n    ExprList *pGroupBy;                       /* GROUP BY clause */\n    Select *pSelect;                          /* HAVING to WHERE clause ctx */\n    struct WindowRewrite *pRewrite;           /* Window rewrite context */\n    struct WhereConst *pConst;                /* WHERE clause constants */\n    struct RenameCtx *pRename;                /* RENAME COLUMN context */\n    struct Table *pTab;                       /* Table of generated column */\n    struct SrcList_item *pSrcItem;            /* A single FROM clause item */\n  } u;\n};\n\n/* Forward declarations */\nSQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);\nSQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);\nSQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);\nSQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);\nSQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);\nSQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);\nSQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);\nSQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);\nSQLITE_PRIVATE int sqlite3WalkerDepthIncrease(Walker*,Select*);\nSQLITE_PRIVATE void sqlite3WalkerDepthDecrease(Walker*,Select*);\n\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);\n#endif\n\n/*\n** Return code from the parse-tree walking primitives and their\n** callbacks.\n*/\n#define WRC_Continue    0   /* Continue down into children */\n#define WRC_Prune       1   /* Omit children but continue walking siblings */\n#define WRC_Abort       2   /* Abandon the tree walk */\n\n/*\n** An instance of this structure represents a set of one or more CTEs\n** (common table expressions) created by a single WITH clause.\n*/\nstruct With {\n  int nCte;                       /* Number of CTEs in the WITH clause */\n  With *pOuter;                   /* Containing WITH clause, or NULL */\n  struct Cte {                    /* For each CTE in the WITH clause.... */\n    char *zName;                    /* Name of this CTE */\n    ExprList *pCols;                /* List of explicit column names, or NULL */\n    Select *pSelect;                /* The definition of this CTE */\n    const char *zCteErr;            /* Error message for circular references */\n  } a[1];\n};\n\n#ifdef SQLITE_DEBUG\n/*\n** An instance of the TreeView object is used for printing the content of\n** data structures on sqlite3DebugPrintf() using a tree-like view.\n*/\nstruct TreeView {\n  int iLevel;             /* Which level of the tree we are on */\n  u8  bLine[100];         /* Draw vertical in column i if bLine[i] is true */\n};\n#endif /* SQLITE_DEBUG */\n\n/*\n** This object is used in various ways, most (but not all) related to window\n** functions.\n**\n**   (1) A single instance of this structure is attached to the\n**       the Expr.y.pWin field for each window function in an expression tree.\n**       This object holds the information contained in the OVER clause,\n**       plus additional fields used during code generation.\n**\n**   (2) All window functions in a single SELECT form a linked-list\n**       attached to Select.pWin.  The Window.pFunc and Window.pExpr\n**       fields point back to the expression that is the window function.\n**\n**   (3) The terms of the WINDOW clause of a SELECT are instances of this\n**       object on a linked list attached to Select.pWinDefn.\n**\n**   (4) For an aggregate function with a FILTER clause, an instance\n**       of this object is stored in Expr.y.pWin with eFrmType set to\n**       TK_FILTER. In this case the only field used is Window.pFilter.\n**\n** The uses (1) and (2) are really the same Window object that just happens\n** to be accessible in two different ways.  Use case (3) are separate objects.\n*/\nstruct Window {\n  char *zName;            /* Name of window (may be NULL) */\n  char *zBase;            /* Name of base window for chaining (may be NULL) */\n  ExprList *pPartition;   /* PARTITION BY clause */\n  ExprList *pOrderBy;     /* ORDER BY clause */\n  u8 eFrmType;            /* TK_RANGE, TK_GROUPS, TK_ROWS, or 0 */\n  u8 eStart;              /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */\n  u8 eEnd;                /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */\n  u8 bImplicitFrame;      /* True if frame was implicitly specified */\n  u8 eExclude;            /* TK_NO, TK_CURRENT, TK_TIES, TK_GROUP, or 0 */\n  Expr *pStart;           /* Expression for \"<expr> PRECEDING\" */\n  Expr *pEnd;             /* Expression for \"<expr> FOLLOWING\" */\n  Window **ppThis;        /* Pointer to this object in Select.pWin list */\n  Window *pNextWin;       /* Next window function belonging to this SELECT */\n  Expr *pFilter;          /* The FILTER expression */\n  FuncDef *pFunc;         /* The function */\n  int iEphCsr;            /* Partition buffer or Peer buffer */\n  int regAccum;           /* Accumulator */\n  int regResult;          /* Interim result */\n  int csrApp;             /* Function cursor (used by min/max) */\n  int regApp;             /* Function register (also used by min/max) */\n  int regPart;            /* Array of registers for PARTITION BY values */\n  Expr *pOwner;           /* Expression object this window is attached to */\n  int nBufferCol;         /* Number of columns in buffer table */\n  int iArgCol;            /* Offset of first argument for this function */\n  int regOne;             /* Register containing constant value 1 */\n  int regStartRowid;\n  int regEndRowid;\n  u8 bExprArgs;           /* Defer evaluation of window function arguments\n                          ** due to the SQLITE_SUBTYPE flag */\n};\n\n#ifndef SQLITE_OMIT_WINDOWFUNC\nSQLITE_PRIVATE void sqlite3WindowDelete(sqlite3*, Window*);\nSQLITE_PRIVATE void sqlite3WindowUnlinkFromSelect(Window*);\nSQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p);\nSQLITE_PRIVATE Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*, u8);\nSQLITE_PRIVATE void sqlite3WindowAttach(Parse*, Expr*, Window*);\nSQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin);\nSQLITE_PRIVATE int sqlite3WindowCompare(Parse*, Window*, Window*, int);\nSQLITE_PRIVATE void sqlite3WindowCodeInit(Parse*, Select*);\nSQLITE_PRIVATE void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);\nSQLITE_PRIVATE int sqlite3WindowRewrite(Parse*, Select*);\nSQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, struct SrcList_item*);\nSQLITE_PRIVATE void sqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*);\nSQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p);\nSQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p);\nSQLITE_PRIVATE void sqlite3WindowFunctions(void);\nSQLITE_PRIVATE void sqlite3WindowChain(Parse*, Window*, Window*);\nSQLITE_PRIVATE Window *sqlite3WindowAssemble(Parse*, Window*, ExprList*, ExprList*, Token*);\n#else\n# define sqlite3WindowDelete(a,b)\n# define sqlite3WindowFunctions()\n# define sqlite3WindowAttach(a,b,c)\n#endif\n\n/*\n** Assuming zIn points to the first byte of a UTF-8 character,\n** advance zIn to point to the first byte of the next UTF-8 character.\n*/\n#define SQLITE_SKIP_UTF8(zIn) {                        \\\n  if( (*(zIn++))>=0xc0 ){                              \\\n    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \\\n  }                                                    \\\n}\n\n/*\n** The SQLITE_*_BKPT macros are substitutes for the error codes with\n** the same name but without the _BKPT suffix.  These macros invoke\n** routines that report the line-number on which the error originated\n** using sqlite3_log().  The routines also provide a convenient place\n** to set a debugger breakpoint.\n*/\nSQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType);\nSQLITE_PRIVATE int sqlite3CorruptError(int);\nSQLITE_PRIVATE int sqlite3MisuseError(int);\nSQLITE_PRIVATE int sqlite3CantopenError(int);\n#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)\n#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)\n#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE   int sqlite3NomemError(int);\nSQLITE_PRIVATE   int sqlite3IoerrnomemError(int);\n# define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)\n# define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)\n#else\n# define SQLITE_NOMEM_BKPT SQLITE_NOMEM\n# define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM\n#endif\n#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)\nSQLITE_PRIVATE   int sqlite3CorruptPgnoError(int,Pgno);\n# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))\n#else\n# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)\n#endif\n\n/*\n** FTS3 and FTS4 both require virtual table support\n*/\n#if defined(SQLITE_OMIT_VIRTUALTABLE)\n# undef SQLITE_ENABLE_FTS3\n# undef SQLITE_ENABLE_FTS4\n#endif\n\n/*\n** FTS4 is really an extension for FTS3.  It is enabled using the\n** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call\n** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.\n*/\n#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)\n# define SQLITE_ENABLE_FTS3 1\n#endif\n\n/*\n** The ctype.h header is needed for non-ASCII systems.  It is also\n** needed by FTS3 when FTS3 is included in the amalgamation.\n*/\n#if !defined(SQLITE_ASCII) || \\\n    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))\n# include <ctype.h>\n#endif\n\n/*\n** The following macros mimic the standard library functions toupper(),\n** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The\n** sqlite versions only work for ASCII characters, regardless of locale.\n*/\n#ifdef SQLITE_ASCII\n# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))\n# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)\n# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)\n# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)\n# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)\n# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)\n# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])\n# define sqlite3Isquote(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x80)\n#else\n# define sqlite3Toupper(x)   toupper((unsigned char)(x))\n# define sqlite3Isspace(x)   isspace((unsigned char)(x))\n# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))\n# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))\n# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))\n# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))\n# define sqlite3Tolower(x)   tolower((unsigned char)(x))\n# define sqlite3Isquote(x)   ((x)=='\"'||(x)=='\\''||(x)=='['||(x)=='`')\n#endif\nSQLITE_PRIVATE int sqlite3IsIdChar(u8);\n\n/*\n** Internal function prototypes\n*/\nSQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);\nSQLITE_PRIVATE int sqlite3Strlen30(const char*);\n#define sqlite3Strlen30NN(C) (strlen(C)&0x3fffffff)\nSQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);\n#define sqlite3StrNICmp sqlite3_strnicmp\n\nSQLITE_PRIVATE int sqlite3MallocInit(void);\nSQLITE_PRIVATE void sqlite3MallocEnd(void);\nSQLITE_PRIVATE void *sqlite3Malloc(u64);\nSQLITE_PRIVATE void *sqlite3MallocZero(u64);\nSQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);\nSQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);\nSQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);\nSQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);\nSQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);\nSQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);\nSQLITE_PRIVATE void *sqlite3Realloc(void*, u64);\nSQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);\nSQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);\nSQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);\nSQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);\nSQLITE_PRIVATE int sqlite3MallocSize(void*);\nSQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);\nSQLITE_PRIVATE void *sqlite3PageMalloc(int);\nSQLITE_PRIVATE void sqlite3PageFree(void*);\nSQLITE_PRIVATE void sqlite3MemSetDefault(void);\n#ifndef SQLITE_UNTESTABLE\nSQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));\n#endif\nSQLITE_PRIVATE int sqlite3HeapNearlyFull(void);\n\n/*\n** On systems with ample stack space and that support alloca(), make\n** use of alloca() to obtain space for large automatic objects.  By default,\n** obtain space from malloc().\n**\n** The alloca() routine never returns NULL.  This will cause code paths\n** that deal with sqlite3StackAlloc() failures to be unreachable.\n*/\n#ifdef SQLITE_USE_ALLOCA\n# define sqlite3StackAllocRaw(D,N)   alloca(N)\n# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)\n# define sqlite3StackFree(D,P)\n#else\n# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)\n# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)\n# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)\n#endif\n\n/* Do not allow both MEMSYS5 and MEMSYS3 to be defined together.  If they\n** are, disable MEMSYS3\n*/\n#ifdef SQLITE_ENABLE_MEMSYS5\nSQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);\n#undef SQLITE_ENABLE_MEMSYS3\n#endif\n#ifdef SQLITE_ENABLE_MEMSYS3\nSQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);\n#endif\n\n\n#ifndef SQLITE_MUTEX_OMIT\nSQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);\nSQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);\nSQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);\nSQLITE_PRIVATE   int sqlite3MutexInit(void);\nSQLITE_PRIVATE   int sqlite3MutexEnd(void);\n#endif\n#if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)\nSQLITE_PRIVATE   void sqlite3MemoryBarrier(void);\n#else\n# define sqlite3MemoryBarrier()\n#endif\n\nSQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);\nSQLITE_PRIVATE void sqlite3StatusUp(int, int);\nSQLITE_PRIVATE void sqlite3StatusDown(int, int);\nSQLITE_PRIVATE void sqlite3StatusHighwater(int, int);\nSQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);\n\n/* Access to mutexes used by sqlite3_status() */\nSQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);\nSQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);\n\n#if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)\nSQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex*);\n#else\n# define sqlite3MutexWarnOnContention(x)\n#endif\n\n#ifndef SQLITE_OMIT_FLOATING_POINT\n# define EXP754 (((u64)0x7ff)<<52)\n# define MAN754 ((((u64)1)<<52)-1)\n# define IsNaN(X) (((X)&EXP754)==EXP754 && ((X)&MAN754)!=0)\nSQLITE_PRIVATE   int sqlite3IsNaN(double);\n#else\n# define IsNaN(X)         0\n# define sqlite3IsNaN(X)  0\n#endif\n\n/*\n** An instance of the following structure holds information about SQL\n** functions arguments that are the parameters to the printf() function.\n*/\nstruct PrintfArguments {\n  int nArg;                /* Total number of arguments */\n  int nUsed;               /* Number of arguments used so far */\n  sqlite3_value **apArg;   /* The argument values */\n};\n\nSQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);\nSQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);\n#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)\nSQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);\n#endif\n#if defined(SQLITE_TEST)\nSQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);\n#endif\n\n#if defined(SQLITE_DEBUG)\nSQLITE_PRIVATE   void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);\nSQLITE_PRIVATE   void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);\nSQLITE_PRIVATE   void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);\nSQLITE_PRIVATE   void sqlite3TreeViewSrcList(TreeView*, const SrcList*);\nSQLITE_PRIVATE   void sqlite3TreeViewSelect(TreeView*, const Select*, u8);\nSQLITE_PRIVATE   void sqlite3TreeViewWith(TreeView*, const With*, u8);\n#ifndef SQLITE_OMIT_WINDOWFUNC\nSQLITE_PRIVATE   void sqlite3TreeViewWindow(TreeView*, const Window*, u8);\nSQLITE_PRIVATE   void sqlite3TreeViewWinFunc(TreeView*, const Window*, u8);\n#endif\n#endif\n\n\nSQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);\nSQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);\nSQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3*,int);\nSQLITE_PRIVATE void sqlite3Dequote(char*);\nSQLITE_PRIVATE void sqlite3DequoteExpr(Expr*);\nSQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);\nSQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);\nSQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);\nSQLITE_PRIVATE void sqlite3FinishCoding(Parse*);\nSQLITE_PRIVATE int sqlite3GetTempReg(Parse*);\nSQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);\nSQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);\nSQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);\nSQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);\n#endif\nSQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);\nSQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);\nSQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);\nSQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);\nSQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);\nSQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse*,Expr*, Expr*);\nSQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr*);\nSQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*, int);\nSQLITE_PRIVATE void sqlite3ExprFunctionUsable(Parse*,Expr*,FuncDef*);\nSQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);\nSQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);\nSQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse*, Expr*);\nSQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);\nSQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);\nSQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int,int);\nSQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);\nSQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);\nSQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);\nSQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);\nSQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index*);\nSQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);\nSQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);\nSQLITE_PRIVATE int sqlite3InitOne(sqlite3*, int, char**, u32);\nSQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);\n#ifndef SQLITE_OMIT_VIRTUALTABLE\nSQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);\n#endif\nSQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);\nSQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);\nSQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);\nSQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);\nSQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);\nSQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);\nSQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*,char);\nSQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*,char);\nSQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);\nSQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);\nSQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index*, i16);\n#ifdef SQLITE_OMIT_GENERATED_COLUMNS\n# define sqlite3TableColumnToStorage(T,X) (X)  /* No-op pass-through */\n# define sqlite3StorageColumnToTable(T,X) (X)  /* No-op pass-through */\n#else\nSQLITE_PRIVATE   i16 sqlite3TableColumnToStorage(Table*, i16);\nSQLITE_PRIVATE   i16 sqlite3StorageColumnToTable(Table*, i16);\n#endif\nSQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);\n#if SQLITE_ENABLE_HIDDEN_COLUMNS\nSQLITE_PRIVATE   void sqlite3ColumnPropertiesFromName(Table*, Column*);\n#else\n# define sqlite3ColumnPropertiesFromName(T,C) /* no-op */\n#endif\nSQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);\nSQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);\nSQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);\nSQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);\nSQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);\nSQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);\nSQLITE_PRIVATE void sqlite3AddGenerated(Parse*,Expr*,Token*);\nSQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);\nSQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,\n                    sqlite3_vfs**,char**,char **);\n#define sqlite3CodecQueryParameters(A,B,C) 0\nSQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);\n\n#ifdef SQLITE_UNTESTABLE\n# define sqlite3FaultSim(X) SQLITE_OK\n#else\nSQLITE_PRIVATE   int sqlite3FaultSim(int);\n#endif\n\nSQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);\nSQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);\nSQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);\nSQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);\nSQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);\nSQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);\nSQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);\n#ifndef SQLITE_UNTESTABLE\nSQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);\n#endif\n\nSQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*);\nSQLITE_PRIVATE void sqlite3RowSetDelete(void*);\nSQLITE_PRIVATE void sqlite3RowSetClear(void*);\nSQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);\nSQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);\nSQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);\n\nSQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);\n\n#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)\nSQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);\n#else\n# define sqlite3ViewGetColumnNames(A,B) 0\n#endif\n\n#if SQLITE_MAX_ATTACHED>30\nSQLITE_PRIVATE   int sqlite3DbMaskAllZero(yDbMask);\n#endif\nSQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);\nSQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);\nSQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);\nSQLITE_PRIVATE void sqlite3FreeIndex(sqlite3*, Index*);\n#ifndef SQLITE_OMIT_AUTOINCREMENT\nSQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);\nSQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);\n#else\n# define sqlite3AutoincrementBegin(X)\n# define sqlite3AutoincrementEnd(X)\n#endif\nSQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*);\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\nSQLITE_PRIVATE   void sqlite3ComputeGeneratedColumns(Parse*, int, Table*);\n#endif\nSQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);\nSQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse*, IdList*, Token*);\nSQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);\nSQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(Parse*, SrcList*, int, int);\nSQLITE_PRIVATE SrcList *sqlite3SrcListAppend(Parse*, SrcList*, Token*, Token*);\nSQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,\n                                      Token*, Select*, Expr*, IdList*);\nSQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);\nSQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);\nSQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);\nSQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);\nSQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);\nSQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);\nSQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);\nSQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);\nSQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,\n                          Expr*, int, int, u8);\nSQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);\nSQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);\nSQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,\n                         Expr*,ExprList*,u32,Expr*);\nSQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);\nSQLITE_PRIVATE void sqlite3SelectReset(Parse*, Select*);\nSQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);\nSQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);\nSQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);\n#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)\nSQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);\n#endif\nSQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);\nSQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,\n                   Upsert*);\nSQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);\nSQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);\nSQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);\nSQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);\nSQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);\nSQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo*);\nSQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);\nSQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);\nSQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);\nSQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);\n#define ONEPASS_OFF      0        /* Use of ONEPASS not allowed */\n#define ONEPASS_SINGLE   1        /* ONEPASS valid for a single row update */\n#define ONEPASS_MULTI    2        /* ONEPASS is valid for multiple rows */\nSQLITE_PRIVATE int sqlite3WhereUsesDeferredSeek(WhereInfo*);\nSQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);\nSQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);\nSQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);\nSQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);\nSQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\nSQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(Parse*, Column*, int);\n#endif\nSQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);\nSQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);\nSQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(Parse*, Expr*, int);\nSQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);\nSQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);\nSQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);\n#define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */\n#define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */\n#define SQLITE_ECEL_REF      0x04  /* Use ExprList.u.x.iOrderByCol */\n#define SQLITE_ECEL_OMITREF  0x08  /* Omit if ExprList.u.x.iOrderByCol */\nSQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);\nSQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);\nSQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);\nSQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);\n#define LOCATE_VIEW    0x01\n#define LOCATE_NOERR   0x02\nSQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);\nSQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);\nSQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);\nSQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);\nSQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);\nSQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*,Expr*);\nSQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int, sqlite3_value*);\nSQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);\nSQLITE_PRIVATE int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);\nSQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);\nSQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);\nSQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);\nSQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr*,int);\nSQLITE_PRIVATE void sqlite3AggInfoPersistWalkerInit(Walker*,Parse*);\nSQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);\nSQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);\nSQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);\nSQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);\nSQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);\n#ifndef SQLITE_UNTESTABLE\nSQLITE_PRIVATE void sqlite3PrngSaveState(void);\nSQLITE_PRIVATE void sqlite3PrngRestoreState(void);\n#endif\nSQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);\nSQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);\nSQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);\nSQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);\nSQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);\nSQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);\nSQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);\nSQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);\nSQLITE_PRIVATE u32 sqlite3IsTrueOrFalse(const char*);\nSQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr*);\nSQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr*);\nSQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);\nSQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);\nSQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);\nSQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);\nSQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);\n#ifdef SQLITE_ENABLE_CURSOR_HINTS\nSQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);\n#endif\nSQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);\nSQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);\nSQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);\nSQLITE_PRIVATE int sqlite3IsRowid(const char*);\nSQLITE_PRIVATE void sqlite3GenerateRowDelete(\n    Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);\nSQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);\nSQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);\nSQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);\nSQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(Expr*,int*,int);\nSQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,\n                                     u8,u8,int,int*,int*,Upsert*);\n#ifdef SQLITE_ENABLE_NULL_TRIM\nSQLITE_PRIVATE   void sqlite3SetMakeRecordP5(Vdbe*,Table*);\n#else\n# define sqlite3SetMakeRecordP5(A,B)\n#endif\nSQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);\nSQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);\nSQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);\nSQLITE_PRIVATE void sqlite3MultiWrite(Parse*);\nSQLITE_PRIVATE void sqlite3MayAbort(Parse*);\nSQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);\nSQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);\nSQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);\nSQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);\nSQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);\nSQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);\nSQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);\nSQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);\nSQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(int,const char*);\nSQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);\nSQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);\nSQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);\nSQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);\nSQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);\nSQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);\nSQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);\nSQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);\n\n#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)\nSQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);\n#endif\n\n#ifndef SQLITE_OMIT_TRIGGER\nSQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,\n                           Expr*,int, int);\nSQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);\nSQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);\nSQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);\nSQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);\nSQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);\nSQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,\n                            int, int, int);\nSQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);\n  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);\nSQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);\nSQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,\n                                        const char*,const char*);\nSQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*,\n                                        Select*,u8,Upsert*,\n                                        const char*,const char*);\nSQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,ExprList*, Expr*, u8,\n                                        const char*,const char*);\nSQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*,\n                                        const char*,const char*);\nSQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);\nSQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);\nSQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);\n# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))\n# define sqlite3IsToplevel(p) ((p)->pToplevel==0)\n#else\n# define sqlite3TriggersExist(B,C,D,E,F) 0\n# define sqlite3DeleteTrigger(A,B)\n# define sqlite3DropTriggerPtr(A,B)\n# define sqlite3UnlinkAndDeleteTrigger(A,B,C)\n# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)\n# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)\n# define sqlite3TriggerList(X, Y) 0\n# define sqlite3ParseToplevel(p) p\n# define sqlite3IsToplevel(p) 1\n# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0\n#endif\n\nSQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);\nSQLITE_PRIVATE void sqlite3SetJoinExpr(Expr*,int);\nSQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);\nSQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);\n#ifndef SQLITE_OMIT_AUTHORIZATION\nSQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);\nSQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);\nSQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);\nSQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);\nSQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);\n#else\n# define sqlite3AuthRead(a,b,c,d)\n# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK\n# define sqlite3AuthContextPush(a,b,c)\n# define sqlite3AuthContextPop(a)  ((void)(a))\n#endif\nSQLITE_PRIVATE int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName);\nSQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);\nSQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);\nSQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);\nSQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);\nSQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);\nSQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);\nSQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);\nSQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);\nSQLITE_PRIVATE int sqlite3RealSameAsInt(double,sqlite3_int64);\nSQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);\nSQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);\nSQLITE_PRIVATE int sqlite3Atoi(const char*);\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);\n#endif\nSQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);\nSQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);\nSQLITE_PRIVATE LogEst sqlite3LogEst(u64);\nSQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);\n#ifndef SQLITE_OMIT_VIRTUALTABLE\nSQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);\n#endif\n#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \\\n    defined(SQLITE_ENABLE_STAT4) || \\\n    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)\nSQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);\n#endif\nSQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);\nSQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);\nSQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);\n\n/*\n** Routines to read and write variable-length integers.  These used to\n** be defined locally, but now we use the varint routines in the util.c\n** file.\n*/\nSQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);\nSQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);\nSQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);\nSQLITE_PRIVATE int sqlite3VarintLen(u64 v);\n\n/*\n** The common case is for a varint to be a single byte.  They following\n** macros handle the common case without a procedure call, but then call\n** the procedure for larger varints.\n*/\n#define getVarint32(A,B)  \\\n  (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))\n#define getVarint32NR(A,B) \\\n  B=(u32)*(A);if(B>=0x80)sqlite3GetVarint32((A),(u32*)&(B))\n#define putVarint32(A,B)  \\\n  (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\\\n  sqlite3PutVarint((A),(B)))\n#define getVarint    sqlite3GetVarint\n#define putVarint    sqlite3PutVarint\n\n\nSQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);\nSQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);\nSQLITE_PRIVATE char sqlite3CompareAffinity(const Expr *pExpr, char aff2);\nSQLITE_PRIVATE int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity);\nSQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);\nSQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr);\nSQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);\nSQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);\nSQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);\nSQLITE_PRIVATE void sqlite3Error(sqlite3*,int);\nSQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);\nSQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);\nSQLITE_PRIVATE u8 sqlite3HexToInt(int h);\nSQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);\n\n#if defined(SQLITE_NEED_ERR_NAME)\nSQLITE_PRIVATE const char *sqlite3ErrName(int);\n#endif\n\n#ifdef SQLITE_ENABLE_DESERIALIZE\nSQLITE_PRIVATE int sqlite3MemdbInit(void);\n#endif\n\nSQLITE_PRIVATE const char *sqlite3ErrStr(int);\nSQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);\nSQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);\nSQLITE_PRIVATE int sqlite3IsBinary(const CollSeq*);\nSQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);\nSQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8);\nSQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr);\nSQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr);\nSQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,const Expr*,const Expr*);\nSQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);\nSQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);\nSQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);\nSQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr*);\nSQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);\nSQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*);\nSQLITE_PRIVATE int sqlite3CheckObjectName(Parse*, const char*,const char*,const char*);\nSQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);\nSQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);\nSQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);\nSQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);\nSQLITE_PRIVATE int sqlite3AbsInt32(int);\n#ifdef SQLITE_ENABLE_8_3_NAMES\nSQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);\n#else\n# define sqlite3FileSuffix3(X,Y)\n#endif\nSQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);\n\nSQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);\nSQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);\nSQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,\n                        void(*)(void*));\nSQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);\nSQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);\n#ifndef SQLITE_UNTESTABLE\nSQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context*);\n#endif\nSQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);\n#endif\nSQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);\nSQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);\n#ifndef SQLITE_AMALGAMATION\nSQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];\nSQLITE_PRIVATE const char sqlite3StrBINARY[];\nSQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];\nSQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];\nSQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;\nSQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;\n#ifndef SQLITE_OMIT_WSD\nSQLITE_PRIVATE int sqlite3PendingByte;\n#endif\n#endif\n#ifdef VDBE_PROFILE\nSQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt;\n#endif\nSQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);\nSQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);\nSQLITE_PRIVATE void sqlite3AlterFunctions(void);\nSQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);\nSQLITE_PRIVATE void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*);\nSQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);\nSQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);\nSQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int);\nSQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int);\nSQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr*);\nSQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);\nSQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);\nSQLITE_PRIVATE int sqlite3MatchEName(\n  const struct ExprList_item*,\n  const char*,\n  const char*,\n  const char*\n);\nSQLITE_PRIVATE Bitmask sqlite3ExprColUsed(Expr*);\nSQLITE_PRIVATE u8 sqlite3StrIHash(const char*);\nSQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);\nSQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);\nSQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);\nSQLITE_PRIVATE int sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);\nSQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);\nSQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);\nSQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);\nSQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);\nSQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse*, void*, Token*);\nSQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse*, void *pTo, void *pFrom);\nSQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse*, Expr*);\nSQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse*, ExprList*);\nSQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);\nSQLITE_PRIVATE char sqlite3AffinityType(const char*, Column*);\nSQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);\nSQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);\nSQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);\nSQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);\nSQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);\nSQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);\nSQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);\nSQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);\nSQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);\nSQLITE_PRIVATE void sqlite3SchemaClear(void *);\nSQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);\nSQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);\nSQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);\nSQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);\nSQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);\nSQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);\nSQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int);\nSQLITE_PRIVATE int sqlite3HasExplicitNulls(Parse*, ExprList*);\n\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);\n#endif\nSQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,\n  void (*)(sqlite3_context*,int,sqlite3_value **),\n  void (*)(sqlite3_context*,int,sqlite3_value **), \n  void (*)(sqlite3_context*),\n  void (*)(sqlite3_context*),\n  void (*)(sqlite3_context*,int,sqlite3_value **), \n  FuncDestructor *pDestructor\n);\nSQLITE_PRIVATE void sqlite3NoopDestructor(void*);\nSQLITE_PRIVATE void sqlite3OomFault(sqlite3*);\nSQLITE_PRIVATE void sqlite3OomClear(sqlite3*);\nSQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);\nSQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);\n\nSQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);\nSQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);\nSQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);\nSQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);\n\nSQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);\nSQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);\n\n#ifndef SQLITE_OMIT_SUBQUERY\nSQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);\n#else\n# define sqlite3ExprCheckIN(x,y) SQLITE_OK\n#endif\n\n#ifdef SQLITE_ENABLE_STAT4\nSQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(\n    Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);\nSQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);\nSQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);\nSQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);\nSQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);\n#endif\n\n/*\n** The interface to the LEMON-generated parser\n*/\n#ifndef SQLITE_AMALGAMATION\nSQLITE_PRIVATE   void *sqlite3ParserAlloc(void*(*)(u64), Parse*);\nSQLITE_PRIVATE   void sqlite3ParserFree(void*, void(*)(void*));\n#endif\nSQLITE_PRIVATE void sqlite3Parser(void*, int, Token);\nSQLITE_PRIVATE int sqlite3ParserFallback(int);\n#ifdef YYTRACKMAXSTACKDEPTH\nSQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);\n#endif\n\nSQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\nSQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);\n#else\n# define sqlite3CloseExtensions(X)\n#endif\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\nSQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);\n#else\n  #define sqlite3TableLock(v,w,x,y,z)\n#endif\n\n#ifdef SQLITE_TEST\nSQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);\n#endif\n\n#ifdef SQLITE_OMIT_VIRTUALTABLE\n#  define sqlite3VtabClear(Y)\n#  define sqlite3VtabSync(X,Y) SQLITE_OK\n#  define sqlite3VtabRollback(X)\n#  define sqlite3VtabCommit(X)\n#  define sqlite3VtabInSync(db) 0\n#  define sqlite3VtabLock(X)\n#  define sqlite3VtabUnlock(X)\n#  define sqlite3VtabModuleUnref(D,X)\n#  define sqlite3VtabUnlockList(X)\n#  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK\n#  define sqlite3GetVTable(X,Y)  ((VTable*)0)\n#else\nSQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);\nSQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);\nSQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);\nSQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);\nSQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);\nSQLITE_PRIVATE    void sqlite3VtabLock(VTable *);\nSQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);\nSQLITE_PRIVATE    void sqlite3VtabModuleUnref(sqlite3*,Module*);\nSQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);\nSQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);\nSQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);\nSQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);\nSQLITE_PRIVATE    Module *sqlite3VtabCreateModule(\n     sqlite3*,\n     const char*,\n     const sqlite3_module*,\n     void*,\n     void(*)(void*)\n   );\n#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)\n#endif\nSQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db);\n#ifndef SQLITE_OMIT_VIRTUALTABLE\nSQLITE_PRIVATE   int sqlite3ShadowTableName(sqlite3 *db, const char *zName);\nSQLITE_PRIVATE   int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*);\n#else\n# define sqlite3ShadowTableName(A,B) 0\n# define sqlite3IsShadowTableOf(A,B,C) 0\n#endif\nSQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);\nSQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);\nSQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);\nSQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);\nSQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);\nSQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);\nSQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);\nSQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);\nSQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);\nSQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);\nSQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);\nSQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);\nSQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);\nSQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);\nSQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);\nSQLITE_PRIVATE void sqlite3ParserReset(Parse*);\n#ifdef SQLITE_ENABLE_NORMALIZE\nSQLITE_PRIVATE char *sqlite3Normalize(Vdbe*, const char*);\n#endif\nSQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);\nSQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);\nSQLITE_PRIVATE CollSeq *sqlite3ExprCompareCollSeq(Parse*,const Expr*);\nSQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, const Expr*, const Expr*);\nSQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);\nSQLITE_PRIVATE const char *sqlite3JournalModename(int);\n#ifndef SQLITE_OMIT_WAL\nSQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);\nSQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);\n#endif\n#ifndef SQLITE_OMIT_CTE\nSQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);\nSQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);\nSQLITE_PRIVATE   void sqlite3WithPush(Parse*, With*, u8);\n#else\n#define sqlite3WithPush(x,y,z)\n#define sqlite3WithDelete(x,y)\n#endif\n#ifndef SQLITE_OMIT_UPSERT\nSQLITE_PRIVATE   Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*);\nSQLITE_PRIVATE   void sqlite3UpsertDelete(sqlite3*,Upsert*);\nSQLITE_PRIVATE   Upsert *sqlite3UpsertDup(sqlite3*,Upsert*);\nSQLITE_PRIVATE   int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*);\nSQLITE_PRIVATE   void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int);\n#else\n#define sqlite3UpsertNew(v,w,x,y,z) ((Upsert*)0)\n#define sqlite3UpsertDelete(x,y)\n#define sqlite3UpsertDup(x,y)       ((Upsert*)0)\n#endif\n\n\n/* Declarations for functions in fkey.c. All of these are replaced by\n** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign\n** key functionality is available. If OMIT_TRIGGER is defined but\n** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In\n** this case foreign keys are parsed, but no other functionality is\n** provided (enforcement of FK constraints requires the triggers sub-system).\n*/\n#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)\nSQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);\nSQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);\nSQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);\nSQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);\nSQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);\nSQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);\n#else\n  #define sqlite3FkActions(a,b,c,d,e,f)\n  #define sqlite3FkCheck(a,b,c,d,e,f)\n  #define sqlite3FkDropTable(a,b,c)\n  #define sqlite3FkOldmask(a,b)         0\n  #define sqlite3FkRequired(a,b,c,d)    0\n  #define sqlite3FkReferences(a)        0\n#endif\n#ifndef SQLITE_OMIT_FOREIGN_KEY\nSQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);\nSQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);\n#else\n  #define sqlite3FkDelete(a,b)\n  #define sqlite3FkLocateIndex(a,b,c,d,e)\n#endif\n\n\n/*\n** Available fault injectors.  Should be numbered beginning with 0.\n*/\n#define SQLITE_FAULTINJECTOR_MALLOC     0\n#define SQLITE_FAULTINJECTOR_COUNT      1\n\n/*\n** The interface to the code in fault.c used for identifying \"benign\"\n** malloc failures. This is only present if SQLITE_UNTESTABLE\n** is not defined.\n*/\n#ifndef SQLITE_UNTESTABLE\nSQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);\nSQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);\n#else\n  #define sqlite3BeginBenignMalloc()\n  #define sqlite3EndBenignMalloc()\n#endif\n\n/*\n** Allowed return values from sqlite3FindInIndex()\n*/\n#define IN_INDEX_ROWID        1   /* Search the rowid of the table */\n#define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */\n#define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */\n#define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */\n#define IN_INDEX_NOOP         5   /* No table available. Use comparisons */\n/*\n** Allowed flags for the 3rd parameter to sqlite3FindInIndex().\n*/\n#define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */\n#define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */\n#define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */\nSQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*, int*);\n\nSQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);\nSQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);\n#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \\\n || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)\nSQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);\n#endif\n\nSQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);\nSQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);\n\nSQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);\n#if SQLITE_MAX_EXPR_DEPTH>0\nSQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);\nSQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);\n#else\n  #define sqlite3SelectExprHeight(x) 0\n  #define sqlite3ExprCheckHeight(x,y)\n#endif\n\nSQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);\nSQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);\n\n#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY\nSQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);\nSQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);\nSQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);\n#else\n  #define sqlite3ConnectionBlocked(x,y)\n  #define sqlite3ConnectionUnlocked(x)\n  #define sqlite3ConnectionClosed(x)\n#endif\n\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);\n#endif\n#if defined(YYCOVERAGE)\nSQLITE_PRIVATE   int sqlite3ParserCoverage(FILE*);\n#endif\n\n/*\n** If the SQLITE_ENABLE IOTRACE exists then the global variable\n** sqlite3IoTrace is a pointer to a printf-like routine used to\n** print I/O tracing messages.\n*/\n#ifdef SQLITE_ENABLE_IOTRACE\n# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }\nSQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);\nSQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);\n#else\n# define IOTRACE(A)\n# define sqlite3VdbeIOTraceSql(X)\n#endif\n\n/*\n** These routines are available for the mem2.c debugging memory allocator\n** only.  They are used to verify that different \"types\" of memory\n** allocations are properly tracked by the system.\n**\n** sqlite3MemdebugSetType() sets the \"type\" of an allocation to one of\n** the MEMTYPE_* macros defined below.  The type must be a bitmask with\n** a single bit set.\n**\n** sqlite3MemdebugHasType() returns true if any of the bits in its second\n** argument match the type set by the previous sqlite3MemdebugSetType().\n** sqlite3MemdebugHasType() is intended for use inside assert() statements.\n**\n** sqlite3MemdebugNoType() returns true if none of the bits in its second\n** argument match the type set by the previous sqlite3MemdebugSetType().\n**\n** Perhaps the most important point is the difference between MEMTYPE_HEAP\n** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means\n** it might have been allocated by lookaside, except the allocation was\n** too large or lookaside was already full.  It is important to verify\n** that allocations that might have been satisfied by lookaside are not\n** passed back to non-lookaside free() routines.  Asserts such as the\n** example above are placed on the non-lookaside free() routines to verify\n** this constraint.\n**\n** All of this is no-op for a production build.  It only comes into\n** play when the SQLITE_MEMDEBUG compile-time option is used.\n*/\n#ifdef SQLITE_MEMDEBUG\nSQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);\nSQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);\nSQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);\n#else\n# define sqlite3MemdebugSetType(X,Y)  /* no-op */\n# define sqlite3MemdebugHasType(X,Y)  1\n# define sqlite3MemdebugNoType(X,Y)   1\n#endif\n#define MEMTYPE_HEAP       0x01  /* General heap allocations */\n#define MEMTYPE_LOOKASIDE  0x02  /* Heap that might have been lookaside */\n#define MEMTYPE_PCACHE     0x04  /* Page cache allocations */\n\n/*\n** Threading interface\n*/\n#if SQLITE_MAX_WORKER_THREADS>0\nSQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);\nSQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);\n#endif\n\n#if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)\nSQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);\n#endif\n#if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)\nSQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);\n#endif\n\nSQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);\nSQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);\nSQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);\nSQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);\nSQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);\n\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\nSQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);\n#endif\n\n#endif /* SQLITEINT_H */\n\n/************** End of sqliteInt.h *******************************************/\n/************** Begin file global.c ******************************************/\n/*\n** 2008 June 13\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains definitions of global variables and constants.\n*/\n/* #include \"sqliteInt.h\" */\n\n/* An array to map all upper-case characters into their corresponding\n** lower-case character. \n**\n** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not\n** handle case conversions for the UTF character set since the tables\n** involved are nearly as big or bigger than SQLite itself.\n*/\nSQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {\n#ifdef SQLITE_ASCII\n      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,\n     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,\n     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,\n     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,\n    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,\n    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,\n    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,\n    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,\n    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,\n    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,\n    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,\n    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,\n    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,\n    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,\n    252,253,254,255\n#endif\n#ifdef SQLITE_EBCDIC\n      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */\n     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */\n     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */\n     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */\n     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */\n     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */\n     96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */\n    112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */\n    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */\n    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */\n    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */\n    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */\n    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */\n    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */\n    224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */\n    240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */\n#endif\n};\n\n/*\n** The following 256 byte lookup table is used to support SQLites built-in\n** equivalents to the following standard library functions:\n**\n**   isspace()                        0x01\n**   isalpha()                        0x02\n**   isdigit()                        0x04\n**   isalnum()                        0x06\n**   isxdigit()                       0x08\n**   toupper()                        0x20\n**   SQLite identifier character      0x40\n**   Quote character                  0x80\n**\n** Bit 0x20 is set if the mapped character requires translation to upper\n** case. i.e. if the character is a lower-case ASCII character.\n** If x is a lower-case ASCII character, then its upper-case equivalent\n** is (x - 0x20). Therefore toupper() can be implemented as:\n**\n**   (x & ~(map[x]&0x20))\n**\n** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]\n** array. tolower() is used more often than toupper() by SQLite.\n**\n** Bit 0x40 is set if the character is non-alphanumeric and can be used in an \n** SQLite identifier.  Identifiers are alphanumerics, \"_\", \"$\", and any\n** non-ASCII UTF character. Hence the test for whether or not a character is\n** part of an identifier is 0x46.\n*/\nSQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {\n  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */\n  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */\n  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */\n  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */\n  0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80,  /* 20..27     !\"#$%&' */\n  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */\n  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */\n  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */\n\n  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */\n  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */\n  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */\n  0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\\]^_ */\n  0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */\n  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */\n  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */\n  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */\n\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */\n\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */\n};\n\n/* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards\n** compatibility for legacy applications, the URI filename capability is\n** disabled by default.\n**\n** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled\n** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.\n**\n** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally\n** disabled. The default value may be changed by compiling with the\n** SQLITE_USE_URI symbol defined.\n*/\n#ifndef SQLITE_USE_URI\n# define SQLITE_USE_URI 0\n#endif\n\n/* EVIDENCE-OF: R-38720-18127 The default setting is determined by the\n** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is \"on\" if\n** that compile-time option is omitted.\n*/\n#if !defined(SQLITE_ALLOW_COVERING_INDEX_SCAN)\n# define SQLITE_ALLOW_COVERING_INDEX_SCAN 1\n#else\n# if !SQLITE_ALLOW_COVERING_INDEX_SCAN \n#   error \"Compile-time disabling of covering index scan using the\\\n -DSQLITE_ALLOW_COVERING_INDEX_SCAN=0 option is deprecated.\\\n Contact SQLite developers if this is a problem for you, and\\\n delete this #error macro to continue with your build.\"\n# endif\n#endif\n\n/* The minimum PMA size is set to this value multiplied by the database\n** page size in bytes.\n*/\n#ifndef SQLITE_SORTER_PMASZ\n# define SQLITE_SORTER_PMASZ 250\n#endif\n\n/* Statement journals spill to disk when their size exceeds the following\n** threshold (in bytes). 0 means that statement journals are created and\n** written to disk immediately (the default behavior for SQLite versions\n** before 3.12.0).  -1 means always keep the entire statement journal in\n** memory.  (The statement journal is also always held entirely in memory\n** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this\n** setting.)\n*/\n#ifndef SQLITE_STMTJRNL_SPILL \n# define SQLITE_STMTJRNL_SPILL (64*1024)\n#endif\n\n/*\n** The default lookaside-configuration, the format \"SZ,N\".  SZ is the\n** number of bytes in each lookaside slot (should be a multiple of 8)\n** and N is the number of slots.  The lookaside-configuration can be\n** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)\n** or at run-time for an individual database connection using\n** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);\n**\n** With the two-size-lookaside enhancement, less lookaside is required.\n** The default configuration of 1200,40 actually provides 30 1200-byte slots\n** and 93 128-byte slots, which is more lookaside than is available\n** using the older 1200,100 configuration without two-size-lookaside.\n*/\n#ifndef SQLITE_DEFAULT_LOOKASIDE\n# ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE\n#   define SQLITE_DEFAULT_LOOKASIDE 1200,100  /* 120KB of memory */\n# else\n#   define SQLITE_DEFAULT_LOOKASIDE 1200,40   /* 48KB of memory */\n# endif\n#endif\n\n\n/* The default maximum size of an in-memory database created using\n** sqlite3_deserialize()\n*/\n#ifndef SQLITE_MEMDB_DEFAULT_MAXSIZE\n# define SQLITE_MEMDB_DEFAULT_MAXSIZE 1073741824\n#endif\n\n/*\n** The following singleton contains the global configuration for\n** the SQLite library.\n*/\nSQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {\n   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */\n   1,                         /* bCoreMutex */\n   SQLITE_THREADSAFE==1,      /* bFullMutex */\n   SQLITE_USE_URI,            /* bOpenUri */\n   SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */\n   0,                         /* bSmallMalloc */\n   1,                         /* bExtraSchemaChecks */\n   0x7ffffffe,                /* mxStrlen */\n   0,                         /* neverCorrupt */\n   SQLITE_DEFAULT_LOOKASIDE,  /* szLookaside, nLookaside */\n   SQLITE_STMTJRNL_SPILL,     /* nStmtSpill */\n   {0,0,0,0,0,0,0,0},         /* m */\n   {0,0,0,0,0,0,0,0,0},       /* mutex */\n   {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */\n   (void*)0,                  /* pHeap */\n   0,                         /* nHeap */\n   0, 0,                      /* mnHeap, mxHeap */\n   SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */\n   SQLITE_MAX_MMAP_SIZE,      /* mxMmap */\n   (void*)0,                  /* pPage */\n   0,                         /* szPage */\n   SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */\n   0,                         /* mxParserStack */\n   0,                         /* sharedCacheEnabled */\n   SQLITE_SORTER_PMASZ,       /* szPma */\n   /* All the rest should always be initialized to zero */\n   0,                         /* isInit */\n   0,                         /* inProgress */\n   0,                         /* isMutexInit */\n   0,                         /* isMallocInit */\n   0,                         /* isPCacheInit */\n   0,                         /* nRefInitMutex */\n   0,                         /* pInitMutex */\n   0,                         /* xLog */\n   0,                         /* pLogArg */\n#ifdef SQLITE_ENABLE_SQLLOG\n   0,                         /* xSqllog */\n   0,                         /* pSqllogArg */\n#endif\n#ifdef SQLITE_VDBE_COVERAGE\n   0,                         /* xVdbeBranch */\n   0,                         /* pVbeBranchArg */\n#endif\n#ifdef SQLITE_ENABLE_DESERIALIZE\n   SQLITE_MEMDB_DEFAULT_MAXSIZE,   /* mxMemdbSize */\n#endif\n#ifndef SQLITE_UNTESTABLE\n   0,                         /* xTestCallback */\n#endif\n   0,                         /* bLocaltimeFault */\n   0x7ffffffe,                /* iOnceResetThreshold */\n   SQLITE_DEFAULT_SORTERREF_SIZE,   /* szSorterRef */\n   0,                         /* iPrngSeed */\n};\n\n/*\n** Hash table for global functions - functions common to all\n** database connections.  After initialization, this table is\n** read-only.\n*/\nSQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;\n\n#ifdef VDBE_PROFILE\n/*\n** The following performance counter can be used in place of\n** sqlite3Hwtime() for profiling.  This is a no-op on standard builds.\n*/\nSQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt = 0;\n#endif\n\n/*\n** The value of the \"pending\" byte must be 0x40000000 (1 byte past the\n** 1-gibabyte boundary) in a compatible database.  SQLite never uses\n** the database page that contains the pending byte.  It never attempts\n** to read or write that page.  The pending byte page is set aside\n** for use by the VFS layers as space for managing file locks.\n**\n** During testing, it is often desirable to move the pending byte to\n** a different position in the file.  This allows code that has to\n** deal with the pending byte to run on files that are much smaller\n** than 1 GiB.  The sqlite3_test_control() interface can be used to\n** move the pending byte.\n**\n** IMPORTANT:  Changing the pending byte to any value other than\n** 0x40000000 results in an incompatible database file format!\n** Changing the pending byte during operation will result in undefined\n** and incorrect behavior.\n*/\n#ifndef SQLITE_OMIT_WSD\nSQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;\n#endif\n\n/* #include \"opcodes.h\" */\n/*\n** Properties of opcodes.  The OPFLG_INITIALIZER macro is\n** created by mkopcodeh.awk during compilation.  Data is obtained\n** from the comments following the \"case OP_xxxx:\" statements in\n** the vdbe.c file.  \n*/\nSQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;\n\n/*\n** Name of the default collating sequence\n*/\nSQLITE_PRIVATE const char sqlite3StrBINARY[] = \"BINARY\";\n\n/************** End of global.c **********************************************/\n/************** Begin file status.c ******************************************/\n/*\n** 2008 June 18\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This module implements the sqlite3_status() interface and related\n** functionality.\n*/\n/* #include \"sqliteInt.h\" */\n/************** Include vdbeInt.h in the middle of status.c ******************/\n/************** Begin file vdbeInt.h *****************************************/\n/*\n** 2003 September 6\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This is the header file for information that is private to the\n** VDBE.  This information used to all be at the top of the single\n** source code file \"vdbe.c\".  When that file became too big (over\n** 6000 lines long) it was split up into several smaller files and\n** this header information was factored out.\n*/\n#ifndef SQLITE_VDBEINT_H\n#define SQLITE_VDBEINT_H\n\n/*\n** The maximum number of times that a statement will try to reparse\n** itself before giving up and returning SQLITE_SCHEMA.\n*/\n#ifndef SQLITE_MAX_SCHEMA_RETRY\n# define SQLITE_MAX_SCHEMA_RETRY 50\n#endif\n\n/*\n** VDBE_DISPLAY_P4 is true or false depending on whether or not the\n** \"explain\" P4 display logic is enabled.\n*/\n#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \\\n     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) \\\n     || defined(SQLITE_ENABLE_BYTECODE_VTAB)\n# define VDBE_DISPLAY_P4 1\n#else\n# define VDBE_DISPLAY_P4 0\n#endif\n\n/*\n** SQL is translated into a sequence of instructions to be\n** executed by a virtual machine.  Each instruction is an instance\n** of the following structure.\n*/\ntypedef struct VdbeOp Op;\n\n/*\n** Boolean values\n*/\ntypedef unsigned Bool;\n\n/* Opaque type used by code in vdbesort.c */\ntypedef struct VdbeSorter VdbeSorter;\n\n/* Elements of the linked list at Vdbe.pAuxData */\ntypedef struct AuxData AuxData;\n\n/* Types of VDBE cursors */\n#define CURTYPE_BTREE       0\n#define CURTYPE_SORTER      1\n#define CURTYPE_VTAB        2\n#define CURTYPE_PSEUDO      3\n\n/*\n** A VdbeCursor is an superclass (a wrapper) for various cursor objects:\n**\n**      * A b-tree cursor\n**          -  In the main database or in an ephemeral database\n**          -  On either an index or a table\n**      * A sorter\n**      * A virtual table\n**      * A one-row \"pseudotable\" stored in a single register\n*/\ntypedef struct VdbeCursor VdbeCursor;\nstruct VdbeCursor {\n  u8 eCurType;            /* One of the CURTYPE_* values above */\n  i8 iDb;                 /* Index of cursor database in db->aDb[] (or -1) */\n  u8 nullRow;             /* True if pointing to a row with no data */\n  u8 deferredMoveto;      /* A call to sqlite3BtreeMoveto() is needed */\n  u8 isTable;             /* True for rowid tables.  False for indexes */\n#ifdef SQLITE_DEBUG\n  u8 seekOp;              /* Most recent seek operation on this cursor */\n  u8 wrFlag;              /* The wrFlag argument to sqlite3BtreeCursor() */\n#endif\n  Bool isEphemeral:1;     /* True for an ephemeral table */\n  Bool useRandomRowid:1;  /* Generate new record numbers semi-randomly */\n  Bool isOrdered:1;       /* True if the table is not BTREE_UNORDERED */\n  Bool seekHit:1;         /* See the OP_SeekHit and OP_IfNoHope opcodes */\n  Btree *pBtx;            /* Separate file holding temporary table */\n  i64 seqCount;           /* Sequence counter */\n  int *aAltMap;           /* Mapping from table to index column numbers */\n\n  /* Cached OP_Column parse information is only valid if cacheStatus matches\n  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of\n  ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that\n  ** the cache is out of date. */\n  u32 cacheStatus;        /* Cache is valid if this matches Vdbe.cacheCtr */\n  int seekResult;         /* Result of previous sqlite3BtreeMoveto() or 0\n                          ** if there have been no prior seeks on the cursor. */\n  /* seekResult does not distinguish between \"no seeks have ever occurred\n  ** on this cursor\" and \"the most recent seek was an exact match\".\n  ** For CURTYPE_PSEUDO, seekResult is the register holding the record */\n\n  /* When a new VdbeCursor is allocated, only the fields above are zeroed.\n  ** The fields that follow are uninitialized, and must be individually\n  ** initialized prior to first use. */\n  VdbeCursor *pAltCursor; /* Associated index cursor from which to read */\n  union {\n    BtCursor *pCursor;          /* CURTYPE_BTREE or _PSEUDO.  Btree cursor */\n    sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB.              Vtab cursor */\n    VdbeSorter *pSorter;        /* CURTYPE_SORTER.            Sorter object */\n  } uc;\n  KeyInfo *pKeyInfo;      /* Info about index keys needed by index cursors */\n  u32 iHdrOffset;         /* Offset to next unparsed byte of the header */\n  Pgno pgnoRoot;          /* Root page of the open btree cursor */\n  i16 nField;             /* Number of fields in the header */\n  u16 nHdrParsed;         /* Number of header fields parsed so far */\n  i64 movetoTarget;       /* Argument to the deferred sqlite3BtreeMoveto() */\n  u32 *aOffset;           /* Pointer to aType[nField] */\n  const u8 *aRow;         /* Data for the current row, if all on one page */\n  u32 payloadSize;        /* Total number of bytes in the record */\n  u32 szRow;              /* Byte available in aRow */\n#ifdef SQLITE_ENABLE_COLUMN_USED_MASK\n  u64 maskUsed;           /* Mask of columns used by this cursor */\n#endif\n\n  /* 2*nField extra array elements allocated for aType[], beyond the one\n  ** static element declared in the structure.  nField total array slots for\n  ** aType[] and nField+1 array slots for aOffset[] */\n  u32 aType[1];           /* Type values record decode.  MUST BE LAST */\n};\n\n\n/*\n** A value for VdbeCursor.cacheStatus that means the cache is always invalid.\n*/\n#define CACHE_STALE 0\n\n/*\n** When a sub-program is executed (OP_Program), a structure of this type\n** is allocated to store the current value of the program counter, as\n** well as the current memory cell array and various other frame specific\n** values stored in the Vdbe struct. When the sub-program is finished, \n** these values are copied back to the Vdbe from the VdbeFrame structure,\n** restoring the state of the VM to as it was before the sub-program\n** began executing.\n**\n** The memory for a VdbeFrame object is allocated and managed by a memory\n** cell in the parent (calling) frame. When the memory cell is deleted or\n** overwritten, the VdbeFrame object is not freed immediately. Instead, it\n** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame\n** list is deleted when the VM is reset in VdbeHalt(). The reason for doing\n** this instead of deleting the VdbeFrame immediately is to avoid recursive\n** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the\n** child frame are released.\n**\n** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is\n** set to NULL if the currently executing frame is the main program.\n*/\ntypedef struct VdbeFrame VdbeFrame;\nstruct VdbeFrame {\n  Vdbe *v;                /* VM this frame belongs to */\n  VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */\n  Op *aOp;                /* Program instructions for parent frame */\n  i64 *anExec;            /* Event counters from parent frame */\n  Mem *aMem;              /* Array of memory cells for parent frame */\n  VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */\n  u8 *aOnce;              /* Bitmask used by OP_Once */\n  void *token;            /* Copy of SubProgram.token */\n  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */\n  AuxData *pAuxData;      /* Linked list of auxdata allocations */\n#if SQLITE_DEBUG\n  u32 iFrameMagic;        /* magic number for sanity checking */\n#endif\n  int nCursor;            /* Number of entries in apCsr */\n  int pc;                 /* Program Counter in parent (calling) frame */\n  int nOp;                /* Size of aOp array */\n  int nMem;               /* Number of entries in aMem */\n  int nChildMem;          /* Number of memory cells for child frame */\n  int nChildCsr;          /* Number of cursors for child frame */\n  int nChange;            /* Statement changes (Vdbe.nChange)     */\n  int nDbChange;          /* Value of db->nChange */\n};\n\n/* Magic number for sanity checking on VdbeFrame objects */\n#define SQLITE_FRAME_MAGIC 0x879fb71e\n\n/*\n** Return a pointer to the array of registers allocated for use\n** by a VdbeFrame.\n*/\n#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])\n\n/*\n** Internally, the vdbe manipulates nearly all SQL values as Mem\n** structures. Each Mem struct may cache multiple representations (string,\n** integer etc.) of the same value.\n*/\nstruct sqlite3_value {\n  union MemValue {\n    double r;           /* Real value used when MEM_Real is set in flags */\n    i64 i;              /* Integer value used when MEM_Int is set in flags */\n    int nZero;          /* Extra zero bytes when MEM_Zero and MEM_Blob set */\n    const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */\n    FuncDef *pDef;      /* Used only when flags==MEM_Agg */\n  } u;\n  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */\n  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */\n  u8  eSubtype;       /* Subtype for this value */\n  int n;              /* Number of characters in string value, excluding '\\0' */\n  char *z;            /* String or BLOB value */\n  /* ShallowCopy only needs to copy the information above */\n  char *zMalloc;      /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */\n  int szMalloc;       /* Size of the zMalloc allocation */\n  u32 uTemp;          /* Transient storage for serial_type in OP_MakeRecord */\n  sqlite3 *db;        /* The associated database connection */\n  void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */\n#ifdef SQLITE_DEBUG\n  Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */\n  u16 mScopyFlags;    /* flags value immediately after the shallow copy */\n#endif\n};\n\n/*\n** Size of struct Mem not including the Mem.zMalloc member or anything that\n** follows.\n*/\n#define MEMCELLSIZE offsetof(Mem,zMalloc)\n\n/* One or more of the following flags are set to indicate the validOK\n** representations of the value stored in the Mem struct.\n**\n** If the MEM_Null flag is set, then the value is an SQL NULL value.\n** For a pointer type created using sqlite3_bind_pointer() or\n** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.\n**\n** If the MEM_Str flag is set then Mem.z points at a string representation.\n** Usually this is encoded in the same unicode encoding as the main\n** database (see below for exceptions). If the MEM_Term flag is also\n** set, then the string is nul terminated. The MEM_Int and MEM_Real \n** flags may coexist with the MEM_Str flag.\n*/\n#define MEM_Null      0x0001   /* Value is NULL (or a pointer) */\n#define MEM_Str       0x0002   /* Value is a string */\n#define MEM_Int       0x0004   /* Value is an integer */\n#define MEM_Real      0x0008   /* Value is a real number */\n#define MEM_Blob      0x0010   /* Value is a BLOB */\n#define MEM_IntReal   0x0020   /* MEM_Int that stringifies like MEM_Real */\n#define MEM_AffMask   0x003f   /* Mask of affinity bits */\n#define MEM_FromBind  0x0040   /* Value originates from sqlite3_bind() */\n#define MEM_Undefined 0x0080   /* Value is undefined */\n#define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */\n#define MEM_TypeMask  0xc1bf   /* Mask of type bits */\n\n\n/* Whenever Mem contains a valid string or blob representation, one of\n** the following flags must be set to determine the memory management\n** policy for Mem.z.  The MEM_Term flag tells us whether or not the\n** string is \\000 or \\u0000 terminated\n*/\n#define MEM_Term      0x0200   /* String in Mem.z is zero terminated */\n#define MEM_Dyn       0x0400   /* Need to call Mem.xDel() on Mem.z */\n#define MEM_Static    0x0800   /* Mem.z points to a static string */\n#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */\n#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */\n#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */\n#define MEM_Subtype   0x8000   /* Mem.eSubtype is valid */\n#ifdef SQLITE_OMIT_INCRBLOB\n  #undef MEM_Zero\n  #define MEM_Zero 0x0000\n#endif\n\n/* Return TRUE if Mem X contains dynamically allocated content - anything\n** that needs to be deallocated to avoid a leak.\n*/\n#define VdbeMemDynamic(X)  \\\n  (((X)->flags&(MEM_Agg|MEM_Dyn))!=0)\n\n/*\n** Clear any existing type flags from a Mem and replace them with f\n*/\n#define MemSetTypeFlag(p, f) \\\n   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)\n\n/*\n** True if Mem X is a NULL-nochng type.\n*/\n#define MemNullNochng(X) \\\n  (((X)->flags&MEM_TypeMask)==(MEM_Null|MEM_Zero) \\\n    && (X)->n==0 && (X)->u.nZero==0)\n\n/*\n** Return true if a memory cell is not marked as invalid.  This macro\n** is for use inside assert() statements only.\n*/\n#ifdef SQLITE_DEBUG\n#define memIsValid(M)  ((M)->flags & MEM_Undefined)==0\n#endif\n\n/*\n** Each auxiliary data pointer stored by a user defined function \n** implementation calling sqlite3_set_auxdata() is stored in an instance\n** of this structure. All such structures associated with a single VM\n** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed\n** when the VM is halted (if not before).\n*/\nstruct AuxData {\n  int iAuxOp;                     /* Instruction number of OP_Function opcode */\n  int iAuxArg;                    /* Index of function argument. */\n  void *pAux;                     /* Aux data pointer */\n  void (*xDeleteAux)(void*);      /* Destructor for the aux data */\n  AuxData *pNextAux;              /* Next element in list */\n};\n\n/*\n** The \"context\" argument for an installable function.  A pointer to an\n** instance of this structure is the first argument to the routines used\n** implement the SQL functions.\n**\n** There is a typedef for this structure in sqlite.h.  So all routines,\n** even the public interface to SQLite, can use a pointer to this structure.\n** But this file is the only place where the internal details of this\n** structure are known.\n**\n** This structure is defined inside of vdbeInt.h because it uses substructures\n** (Mem) which are only defined there.\n*/\nstruct sqlite3_context {\n  Mem *pOut;              /* The return value is stored here */\n  FuncDef *pFunc;         /* Pointer to function information */\n  Mem *pMem;              /* Memory cell used to store aggregate context */\n  Vdbe *pVdbe;            /* The VM that owns this context */\n  int iOp;                /* Instruction number of OP_Function */\n  int isError;            /* Error code returned by the function. */\n  u8 skipFlag;            /* Skip accumulator loading if true */\n  u8 argc;                /* Number of arguments */\n  sqlite3_value *argv[1]; /* Argument set */\n};\n\n/* A bitfield type for use inside of structures.  Always follow with :N where\n** N is the number of bits.\n*/\ntypedef unsigned bft;  /* Bit Field Type */\n\n/* The ScanStatus object holds a single value for the\n** sqlite3_stmt_scanstatus() interface.\n*/\ntypedef struct ScanStatus ScanStatus;\nstruct ScanStatus {\n  int addrExplain;                /* OP_Explain for loop */\n  int addrLoop;                   /* Address of \"loops\" counter */\n  int addrVisit;                  /* Address of \"rows visited\" counter */\n  int iSelectID;                  /* The \"Select-ID\" for this loop */\n  LogEst nEst;                    /* Estimated output rows per loop */\n  char *zName;                    /* Name of table or index */\n};\n\n/* The DblquoteStr object holds the text of a double-quoted\n** string for a prepared statement.  A linked list of these objects\n** is constructed during statement parsing and is held on Vdbe.pDblStr.\n** When computing a normalized SQL statement for an SQL statement, that\n** list is consulted for each double-quoted identifier to see if the\n** identifier should really be a string literal.\n*/\ntypedef struct DblquoteStr DblquoteStr;\nstruct DblquoteStr {\n  DblquoteStr *pNextStr;   /* Next string literal in the list */\n  char z[8];               /* Dequoted value for the string */\n};\n\n/*\n** An instance of the virtual machine.  This structure contains the complete\n** state of the virtual machine.\n**\n** The \"sqlite3_stmt\" structure pointer that is returned by sqlite3_prepare()\n** is really a pointer to an instance of this structure.\n*/\nstruct Vdbe {\n  sqlite3 *db;            /* The database connection that owns this statement */\n  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */\n  Parse *pParse;          /* Parsing context used to create this Vdbe */\n  ynVar nVar;             /* Number of entries in aVar[] */\n  u32 magic;              /* Magic number for sanity checking */\n  int nMem;               /* Number of memory locations currently allocated */\n  int nCursor;            /* Number of slots in apCsr[] */\n  u32 cacheCtr;           /* VdbeCursor row cache generation counter */\n  int pc;                 /* The program counter */\n  int rc;                 /* Value to return */\n  int nChange;            /* Number of db changes made since last reset */\n  int iStatement;         /* Statement number (or 0 if has no opened stmt) */\n  i64 iCurrentTime;       /* Value of julianday('now') for this statement */\n  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */\n  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */\n  i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */\n  Mem *aMem;              /* The memory locations */\n  Mem **apArg;            /* Arguments to currently executing user function */\n  VdbeCursor **apCsr;     /* One element of this array for each open cursor */\n  Mem *aVar;              /* Values for the OP_Variable opcode. */\n\n  /* When allocating a new Vdbe object, all of the fields below should be\n  ** initialized to zero or NULL */\n\n  Op *aOp;                /* Space to hold the virtual machine's program */\n  int nOp;                /* Number of instructions in the program */\n  int nOpAlloc;           /* Slots allocated for aOp[] */\n  Mem *aColName;          /* Column names to return */\n  Mem *pResultSet;        /* Pointer to an array of results */\n  char *zErrMsg;          /* Error message written here */\n  VList *pVList;          /* Name of variables */\n#ifndef SQLITE_OMIT_TRACE\n  i64 startTime;          /* Time when query started - used for profiling */\n#endif\n#ifdef SQLITE_DEBUG\n  int rcApp;              /* errcode set by sqlite3_result_error_code() */\n  u32 nWrite;             /* Number of write operations that have occurred */\n#endif\n  u16 nResColumn;         /* Number of columns in one row of the result set */\n  u8 errorAction;         /* Recovery action to do in case of an error */\n  u8 minWriteFileFormat;  /* Minimum file format for writable database files */\n  u8 prepFlags;           /* SQLITE_PREPARE_* flags */\n  u8 doingRerun;          /* True if rerunning after an auto-reprepare */\n  bft expired:2;          /* 1: recompile VM immediately  2: when convenient */\n  bft explain:2;          /* True if EXPLAIN present on SQL command */\n  bft changeCntOn:1;      /* True to update the change-counter */\n  bft runOnlyOnce:1;      /* Automatically expire on reset */\n  bft usesStmtJournal:1;  /* True if uses a statement journal */\n  bft readOnly:1;         /* True for statements that do not write */\n  bft bIsReader:1;        /* True for statements that read */\n  yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */\n  yDbMask lockMask;       /* Subset of btreeMask that requires a lock */\n  u32 aCounter[7];        /* Counters used by sqlite3_stmt_status() */\n  char *zSql;             /* Text of the SQL statement that generated this */\n#ifdef SQLITE_ENABLE_NORMALIZE\n  char *zNormSql;         /* Normalization of the associated SQL statement */\n  DblquoteStr *pDblStr;   /* List of double-quoted string literals */\n#endif\n  void *pFree;            /* Free this when deleting the vdbe */\n  VdbeFrame *pFrame;      /* Parent frame */\n  VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */\n  int nFrame;             /* Number of frames in pFrame list */\n  u32 expmask;            /* Binding to these vars invalidates VM */\n  SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */\n  AuxData *pAuxData;      /* Linked list of auxdata allocations */\n#ifdef SQLITE_ENABLE_STMT_SCANSTATUS\n  i64 *anExec;            /* Number of times each op has been executed */\n  int nScan;              /* Entries in aScan[] */\n  ScanStatus *aScan;      /* Scan definitions for sqlite3_stmt_scanstatus() */\n#endif\n};\n\n/*\n** The following are allowed values for Vdbe.magic\n*/\n#define VDBE_MAGIC_INIT     0x16bceaa5    /* Building a VDBE program */\n#define VDBE_MAGIC_RUN      0x2df20da3    /* VDBE is ready to execute */\n#define VDBE_MAGIC_HALT     0x319c2973    /* VDBE has completed execution */\n#define VDBE_MAGIC_RESET    0x48fa9f76    /* Reset and ready to run again */\n#define VDBE_MAGIC_DEAD     0x5606c3c8    /* The VDBE has been deallocated */\n\n/*\n** Structure used to store the context required by the \n** sqlite3_preupdate_*() API functions.\n*/\nstruct PreUpdate {\n  Vdbe *v;\n  VdbeCursor *pCsr;               /* Cursor to read old values from */\n  int op;                         /* One of SQLITE_INSERT, UPDATE, DELETE */\n  u8 *aRecord;                    /* old.* database record */\n  KeyInfo keyinfo;\n  UnpackedRecord *pUnpacked;      /* Unpacked version of aRecord[] */\n  UnpackedRecord *pNewUnpacked;   /* Unpacked version of new.* record */\n  int iNewReg;                    /* Register for new.* values */\n  i64 iKey1;                      /* First key value passed to hook */\n  i64 iKey2;                      /* Second key value passed to hook */\n  Mem *aNew;                      /* Array of new.* values */\n  Table *pTab;                    /* Schema object being upated */          \n  Index *pPk;                     /* PK index if pTab is WITHOUT ROWID */\n};\n\n/*\n** Function prototypes\n*/\nSQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);\nSQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);\nvoid sqliteVdbePopStack(Vdbe*,int);\nSQLITE_PRIVATE int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor*);\nSQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);\nSQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);\nSQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);\nSQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);\nSQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);\nSQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);\nSQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);\n\nint sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);\nSQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);\nSQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);\nSQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);\n#if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB)\nSQLITE_PRIVATE int sqlite3VdbeNextOpcode(Vdbe*,Mem*,int,int*,int*,Op**);\nSQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3*,Op*);\n#endif\n#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)\nSQLITE_PRIVATE char *sqlite3VdbeDisplayComment(sqlite3*,const Op*,const char*);\n#endif\n#if !defined(SQLITE_OMIT_EXPLAIN)\nSQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);\n#endif\nSQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);\nSQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);\nSQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);\nSQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);\nSQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));\nSQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);\n#ifdef SQLITE_OMIT_FLOATING_POINT\n# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64\n#else\nSQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);\n#endif\nSQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));\nSQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);\nSQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);\nSQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem*);\n#endif\nSQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);\nSQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);\nSQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem*, int ifNull);\nSQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemCast(Mem*,u8,u8);\nSQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemFromBtreeZeroOffset(BtCursor*,u32,Mem*);\nSQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);\nSQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);\n#ifndef SQLITE_OMIT_WINDOWFUNC\nSQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem*, Mem*, FuncDef*);\n#endif\n#if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB)\nSQLITE_PRIVATE const char *sqlite3OpcodeName(int);\n#endif\nSQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);\nSQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);\nSQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame*);\n#endif\nSQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void*);      /* Destructor on Mem */\nSQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*); /* Actually deletes the Frame */\nSQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\nSQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);\n#endif\nSQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);\n\nSQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);\nSQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);\nSQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);\nSQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);\nSQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);\nSQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);\nSQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);\nSQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);\n\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE   void sqlite3VdbeIncrWriteCounter(Vdbe*, VdbeCursor*);\nSQLITE_PRIVATE   void sqlite3VdbeAssertAbortable(Vdbe*);\n#else\n# define sqlite3VdbeIncrWriteCounter(V,C)\n# define sqlite3VdbeAssertAbortable(V)\n#endif\n\n#if !defined(SQLITE_OMIT_SHARED_CACHE) \nSQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);\n#else\n# define sqlite3VdbeEnter(X)\n#endif\n\n#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0\nSQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);\n#else\n# define sqlite3VdbeLeave(X)\n#endif\n\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);\nSQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);\n#endif\n\n#ifndef SQLITE_OMIT_FOREIGN_KEY\nSQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);\n#else\n# define sqlite3VdbeCheckFk(p,i) 0\n#endif\n\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);\nSQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr);\n#endif\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_PRIVATE   int sqlite3VdbeMemTranslate(Mem*, u8);\nSQLITE_PRIVATE   int sqlite3VdbeMemHandleBom(Mem *pMem);\n#endif\n\n#ifndef SQLITE_OMIT_INCRBLOB\nSQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);\n  #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)\n#else\n  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK\n  #define ExpandBlob(P) SQLITE_OK\n#endif\n\n#endif /* !defined(SQLITE_VDBEINT_H) */\n\n/************** End of vdbeInt.h *********************************************/\n/************** Continuing where we left off in status.c *********************/\n\n/*\n** Variables in which to record status information.\n*/\n#if SQLITE_PTRSIZE>4\ntypedef sqlite3_int64 sqlite3StatValueType;\n#else\ntypedef u32 sqlite3StatValueType;\n#endif\ntypedef struct sqlite3StatType sqlite3StatType;\nstatic SQLITE_WSD struct sqlite3StatType {\n  sqlite3StatValueType nowValue[10];  /* Current value */\n  sqlite3StatValueType mxValue[10];   /* Maximum value */\n} sqlite3Stat = { {0,}, {0,} };\n\n/*\n** Elements of sqlite3Stat[] are protected by either the memory allocator\n** mutex, or by the pcache1 mutex.  The following array determines which.\n*/\nstatic const char statMutex[] = {\n  0,  /* SQLITE_STATUS_MEMORY_USED */\n  1,  /* SQLITE_STATUS_PAGECACHE_USED */\n  1,  /* SQLITE_STATUS_PAGECACHE_OVERFLOW */\n  0,  /* SQLITE_STATUS_SCRATCH_USED */\n  0,  /* SQLITE_STATUS_SCRATCH_OVERFLOW */\n  0,  /* SQLITE_STATUS_MALLOC_SIZE */\n  0,  /* SQLITE_STATUS_PARSER_STACK */\n  1,  /* SQLITE_STATUS_PAGECACHE_SIZE */\n  0,  /* SQLITE_STATUS_SCRATCH_SIZE */\n  0,  /* SQLITE_STATUS_MALLOC_COUNT */\n};\n\n\n/* The \"wsdStat\" macro will resolve to the status information\n** state vector.  If writable static data is unsupported on the target,\n** we have to locate the state vector at run-time.  In the more common\n** case where writable static data is supported, wsdStat can refer directly\n** to the \"sqlite3Stat\" state vector declared above.\n*/\n#ifdef SQLITE_OMIT_WSD\n# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)\n# define wsdStat x[0]\n#else\n# define wsdStatInit\n# define wsdStat sqlite3Stat\n#endif\n\n/*\n** Return the current value of a status parameter.  The caller must\n** be holding the appropriate mutex.\n*/\nSQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){\n  wsdStatInit;\n  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );\n  assert( op>=0 && op<ArraySize(statMutex) );\n  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()\n                                           : sqlite3MallocMutex()) );\n  return wsdStat.nowValue[op];\n}\n\n/*\n** Add N to the value of a status record.  The caller must hold the\n** appropriate mutex.  (Locking is checked by assert()).\n**\n** The StatusUp() routine can accept positive or negative values for N.\n** The value of N is added to the current status value and the high-water\n** mark is adjusted if necessary.\n**\n** The StatusDown() routine lowers the current value by N.  The highwater\n** mark is unchanged.  N must be non-negative for StatusDown().\n*/\nSQLITE_PRIVATE void sqlite3StatusUp(int op, int N){\n  wsdStatInit;\n  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );\n  assert( op>=0 && op<ArraySize(statMutex) );\n  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()\n                                           : sqlite3MallocMutex()) );\n  wsdStat.nowValue[op] += N;\n  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){\n    wsdStat.mxValue[op] = wsdStat.nowValue[op];\n  }\n}\nSQLITE_PRIVATE void sqlite3StatusDown(int op, int N){\n  wsdStatInit;\n  assert( N>=0 );\n  assert( op>=0 && op<ArraySize(statMutex) );\n  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()\n                                           : sqlite3MallocMutex()) );\n  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );\n  wsdStat.nowValue[op] -= N;\n}\n\n/*\n** Adjust the highwater mark if necessary.\n** The caller must hold the appropriate mutex.\n*/\nSQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){\n  sqlite3StatValueType newValue;\n  wsdStatInit;\n  assert( X>=0 );\n  newValue = (sqlite3StatValueType)X;\n  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );\n  assert( op>=0 && op<ArraySize(statMutex) );\n  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()\n                                           : sqlite3MallocMutex()) );\n  assert( op==SQLITE_STATUS_MALLOC_SIZE\n          || op==SQLITE_STATUS_PAGECACHE_SIZE\n          || op==SQLITE_STATUS_PARSER_STACK );\n  if( newValue>wsdStat.mxValue[op] ){\n    wsdStat.mxValue[op] = newValue;\n  }\n}\n\n/*\n** Query status information.\n*/\nSQLITE_API int sqlite3_status64(\n  int op,\n  sqlite3_int64 *pCurrent,\n  sqlite3_int64 *pHighwater,\n  int resetFlag\n){\n  sqlite3_mutex *pMutex;\n  wsdStatInit;\n  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;\n#endif\n  pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();\n  sqlite3_mutex_enter(pMutex);\n  *pCurrent = wsdStat.nowValue[op];\n  *pHighwater = wsdStat.mxValue[op];\n  if( resetFlag ){\n    wsdStat.mxValue[op] = wsdStat.nowValue[op];\n  }\n  sqlite3_mutex_leave(pMutex);\n  (void)pMutex;  /* Prevent warning when SQLITE_THREADSAFE=0 */\n  return SQLITE_OK;\n}\nSQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){\n  sqlite3_int64 iCur = 0, iHwtr = 0;\n  int rc;\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;\n#endif\n  rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);\n  if( rc==0 ){\n    *pCurrent = (int)iCur;\n    *pHighwater = (int)iHwtr;\n  }\n  return rc;\n}\n\n/*\n** Return the number of LookasideSlot elements on the linked list\n*/\nstatic u32 countLookasideSlots(LookasideSlot *p){\n  u32 cnt = 0;\n  while( p ){\n    p = p->pNext;\n    cnt++;\n  }\n  return cnt;\n}\n\n/*\n** Count the number of slots of lookaside memory that are outstanding\n*/\nSQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){\n  u32 nInit = countLookasideSlots(db->lookaside.pInit);\n  u32 nFree = countLookasideSlots(db->lookaside.pFree);\n#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE\n  nInit += countLookasideSlots(db->lookaside.pSmallInit);\n  nFree += countLookasideSlots(db->lookaside.pSmallFree);\n#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */\n  if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;\n  return db->lookaside.nSlot - (nInit+nFree);\n}\n\n/*\n** Query status information for a single database connection\n*/\nSQLITE_API int sqlite3_db_status(\n  sqlite3 *db,          /* The database connection whose status is desired */\n  int op,               /* Status verb */\n  int *pCurrent,        /* Write current value here */\n  int *pHighwater,      /* Write high-water mark here */\n  int resetFlag         /* Reset high-water mark if true */\n){\n  int rc = SQLITE_OK;   /* Return code */\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){\n    return SQLITE_MISUSE_BKPT;\n  }\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  switch( op ){\n    case SQLITE_DBSTATUS_LOOKASIDE_USED: {\n      *pCurrent = sqlite3LookasideUsed(db, pHighwater);\n      if( resetFlag ){\n        LookasideSlot *p = db->lookaside.pFree;\n        if( p ){\n          while( p->pNext ) p = p->pNext;\n          p->pNext = db->lookaside.pInit;\n          db->lookaside.pInit = db->lookaside.pFree;\n          db->lookaside.pFree = 0;\n        }\n#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE\n        p = db->lookaside.pSmallFree;\n        if( p ){\n          while( p->pNext ) p = p->pNext;\n          p->pNext = db->lookaside.pSmallInit;\n          db->lookaside.pSmallInit = db->lookaside.pSmallFree;\n          db->lookaside.pSmallFree = 0;\n        }\n#endif\n      }\n      break;\n    }\n\n    case SQLITE_DBSTATUS_LOOKASIDE_HIT:\n    case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:\n    case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {\n      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );\n      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );\n      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );\n      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );\n      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );\n      *pCurrent = 0;\n      *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];\n      if( resetFlag ){\n        db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;\n      }\n      break;\n    }\n\n    /* \n    ** Return an approximation for the amount of memory currently used\n    ** by all pagers associated with the given database connection.  The\n    ** highwater mark is meaningless and is returned as zero.\n    */\n    case SQLITE_DBSTATUS_CACHE_USED_SHARED:\n    case SQLITE_DBSTATUS_CACHE_USED: {\n      int totalUsed = 0;\n      int i;\n      sqlite3BtreeEnterAll(db);\n      for(i=0; i<db->nDb; i++){\n        Btree *pBt = db->aDb[i].pBt;\n        if( pBt ){\n          Pager *pPager = sqlite3BtreePager(pBt);\n          int nByte = sqlite3PagerMemUsed(pPager);\n          if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){\n            nByte = nByte / sqlite3BtreeConnectionCount(pBt);\n          }\n          totalUsed += nByte;\n        }\n      }\n      sqlite3BtreeLeaveAll(db);\n      *pCurrent = totalUsed;\n      *pHighwater = 0;\n      break;\n    }\n\n    /*\n    ** *pCurrent gets an accurate estimate of the amount of memory used\n    ** to store the schema for all databases (main, temp, and any ATTACHed\n    ** databases.  *pHighwater is set to zero.\n    */\n    case SQLITE_DBSTATUS_SCHEMA_USED: {\n      int i;                      /* Used to iterate through schemas */\n      int nByte = 0;              /* Used to accumulate return value */\n\n      sqlite3BtreeEnterAll(db);\n      db->pnBytesFreed = &nByte;\n      for(i=0; i<db->nDb; i++){\n        Schema *pSchema = db->aDb[i].pSchema;\n        if( ALWAYS(pSchema!=0) ){\n          HashElem *p;\n\n          nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (\n              pSchema->tblHash.count \n            + pSchema->trigHash.count\n            + pSchema->idxHash.count\n            + pSchema->fkeyHash.count\n          );\n          nByte += sqlite3_msize(pSchema->tblHash.ht);\n          nByte += sqlite3_msize(pSchema->trigHash.ht);\n          nByte += sqlite3_msize(pSchema->idxHash.ht);\n          nByte += sqlite3_msize(pSchema->fkeyHash.ht);\n\n          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){\n            sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));\n          }\n          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){\n            sqlite3DeleteTable(db, (Table *)sqliteHashData(p));\n          }\n        }\n      }\n      db->pnBytesFreed = 0;\n      sqlite3BtreeLeaveAll(db);\n\n      *pHighwater = 0;\n      *pCurrent = nByte;\n      break;\n    }\n\n    /*\n    ** *pCurrent gets an accurate estimate of the amount of memory used\n    ** to store all prepared statements.\n    ** *pHighwater is set to zero.\n    */\n    case SQLITE_DBSTATUS_STMT_USED: {\n      struct Vdbe *pVdbe;         /* Used to iterate through VMs */\n      int nByte = 0;              /* Used to accumulate return value */\n\n      db->pnBytesFreed = &nByte;\n      for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){\n        sqlite3VdbeClearObject(db, pVdbe);\n        sqlite3DbFree(db, pVdbe);\n      }\n      db->pnBytesFreed = 0;\n\n      *pHighwater = 0;  /* IMP: R-64479-57858 */\n      *pCurrent = nByte;\n\n      break;\n    }\n\n    /*\n    ** Set *pCurrent to the total cache hits or misses encountered by all\n    ** pagers the database handle is connected to. *pHighwater is always set \n    ** to zero.\n    */\n    case SQLITE_DBSTATUS_CACHE_SPILL:\n      op = SQLITE_DBSTATUS_CACHE_WRITE+1;\n      /* Fall through into the next case */\n    case SQLITE_DBSTATUS_CACHE_HIT:\n    case SQLITE_DBSTATUS_CACHE_MISS:\n    case SQLITE_DBSTATUS_CACHE_WRITE:{\n      int i;\n      int nRet = 0;\n      assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );\n      assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );\n\n      for(i=0; i<db->nDb; i++){\n        if( db->aDb[i].pBt ){\n          Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);\n          sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);\n        }\n      }\n      *pHighwater = 0; /* IMP: R-42420-56072 */\n                       /* IMP: R-54100-20147 */\n                       /* IMP: R-29431-39229 */\n      *pCurrent = nRet;\n      break;\n    }\n\n    /* Set *pCurrent to non-zero if there are unresolved deferred foreign\n    ** key constraints.  Set *pCurrent to zero if all foreign key constraints\n    ** have been satisfied.  The *pHighwater is always set to zero.\n    */\n    case SQLITE_DBSTATUS_DEFERRED_FKS: {\n      *pHighwater = 0;  /* IMP: R-11967-56545 */\n      *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;\n      break;\n    }\n\n    default: {\n      rc = SQLITE_ERROR;\n    }\n  }\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/************** End of status.c **********************************************/\n/************** Begin file date.c ********************************************/\n/*\n** 2003 October 31\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the C functions that implement date and time\n** functions for SQLite.  \n**\n** There is only one exported symbol in this file - the function\n** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.\n** All other code has file scope.\n**\n** SQLite processes all times and dates as julian day numbers.  The\n** dates and times are stored as the number of days since noon\n** in Greenwich on November 24, 4714 B.C. according to the Gregorian\n** calendar system. \n**\n** 1970-01-01 00:00:00 is JD 2440587.5\n** 2000-01-01 00:00:00 is JD 2451544.5\n**\n** This implementation requires years to be expressed as a 4-digit number\n** which means that only dates between 0000-01-01 and 9999-12-31 can\n** be represented, even though julian day numbers allow a much wider\n** range of dates.\n**\n** The Gregorian calendar system is used for all dates and times,\n** even those that predate the Gregorian calendar.  Historians usually\n** use the julian calendar for dates prior to 1582-10-15 and for some\n** dates afterwards, depending on locale.  Beware of this difference.\n**\n** The conversion algorithms are implemented based on descriptions\n** in the following text:\n**\n**      Jean Meeus\n**      Astronomical Algorithms, 2nd Edition, 1998\n**      ISBN 0-943396-61-1\n**      Willmann-Bell, Inc\n**      Richmond, Virginia (USA)\n*/\n/* #include \"sqliteInt.h\" */\n/* #include <stdlib.h> */\n/* #include <assert.h> */\n#include <time.h>\n\n#ifndef SQLITE_OMIT_DATETIME_FUNCS\n\n/*\n** The MSVC CRT on Windows CE may not have a localtime() function.\n** So declare a substitute.  The substitute function itself is\n** defined in \"os_win.c\".\n*/\n#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \\\n    (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)\nstruct tm *__cdecl localtime(const time_t *);\n#endif\n\n/*\n** A structure for holding a single date and time.\n*/\ntypedef struct DateTime DateTime;\nstruct DateTime {\n  sqlite3_int64 iJD;  /* The julian day number times 86400000 */\n  int Y, M, D;        /* Year, month, and day */\n  int h, m;           /* Hour and minutes */\n  int tz;             /* Timezone offset in minutes */\n  double s;           /* Seconds */\n  char validJD;       /* True (1) if iJD is valid */\n  char rawS;          /* Raw numeric value stored in s */\n  char validYMD;      /* True (1) if Y,M,D are valid */\n  char validHMS;      /* True (1) if h,m,s are valid */\n  char validTZ;       /* True (1) if tz is valid */\n  char tzSet;         /* Timezone was set explicitly */\n  char isError;       /* An overflow has occurred */\n};\n\n\n/*\n** Convert zDate into one or more integers according to the conversion\n** specifier zFormat.\n**\n** zFormat[] contains 4 characters for each integer converted, except for\n** the last integer which is specified by three characters.  The meaning\n** of a four-character format specifiers ABCD is:\n**\n**    A:   number of digits to convert.  Always \"2\" or \"4\".\n**    B:   minimum value.  Always \"0\" or \"1\".\n**    C:   maximum value, decoded as:\n**           a:  12\n**           b:  14\n**           c:  24\n**           d:  31\n**           e:  59\n**           f:  9999\n**    D:   the separator character, or \\000 to indicate this is the\n**         last number to convert.\n**\n** Example:  To translate an ISO-8601 date YYYY-MM-DD, the format would\n** be \"40f-21a-20c\".  The \"40f-\" indicates the 4-digit year followed by \"-\".\n** The \"21a-\" indicates the 2-digit month followed by \"-\".  The \"20c\" indicates\n** the 2-digit day which is the last integer in the set.\n**\n** The function returns the number of successful conversions.\n*/\nstatic int getDigits(const char *zDate, const char *zFormat, ...){\n  /* The aMx[] array translates the 3rd character of each format\n  ** spec into a max size:    a   b   c   d   e     f */\n  static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };\n  va_list ap;\n  int cnt = 0;\n  char nextC;\n  va_start(ap, zFormat);\n  do{\n    char N = zFormat[0] - '0';\n    char min = zFormat[1] - '0';\n    int val = 0;\n    u16 max;\n\n    assert( zFormat[2]>='a' && zFormat[2]<='f' );\n    max = aMx[zFormat[2] - 'a'];\n    nextC = zFormat[3];\n    val = 0;\n    while( N-- ){\n      if( !sqlite3Isdigit(*zDate) ){\n        goto end_getDigits;\n      }\n      val = val*10 + *zDate - '0';\n      zDate++;\n    }\n    if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){\n      goto end_getDigits;\n    }\n    *va_arg(ap,int*) = val;\n    zDate++;\n    cnt++;\n    zFormat += 4;\n  }while( nextC );\nend_getDigits:\n  va_end(ap);\n  return cnt;\n}\n\n/*\n** Parse a timezone extension on the end of a date-time.\n** The extension is of the form:\n**\n**        (+/-)HH:MM\n**\n** Or the \"zulu\" notation:\n**\n**        Z\n**\n** If the parse is successful, write the number of minutes\n** of change in p->tz and return 0.  If a parser error occurs,\n** return non-zero.\n**\n** A missing specifier is not considered an error.\n*/\nstatic int parseTimezone(const char *zDate, DateTime *p){\n  int sgn = 0;\n  int nHr, nMn;\n  int c;\n  while( sqlite3Isspace(*zDate) ){ zDate++; }\n  p->tz = 0;\n  c = *zDate;\n  if( c=='-' ){\n    sgn = -1;\n  }else if( c=='+' ){\n    sgn = +1;\n  }else if( c=='Z' || c=='z' ){\n    zDate++;\n    goto zulu_time;\n  }else{\n    return c!=0;\n  }\n  zDate++;\n  if( getDigits(zDate, \"20b:20e\", &nHr, &nMn)!=2 ){\n    return 1;\n  }\n  zDate += 5;\n  p->tz = sgn*(nMn + nHr*60);\nzulu_time:\n  while( sqlite3Isspace(*zDate) ){ zDate++; }\n  p->tzSet = 1;\n  return *zDate!=0;\n}\n\n/*\n** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.\n** The HH, MM, and SS must each be exactly 2 digits.  The\n** fractional seconds FFFF can be one or more digits.\n**\n** Return 1 if there is a parsing error and 0 on success.\n*/\nstatic int parseHhMmSs(const char *zDate, DateTime *p){\n  int h, m, s;\n  double ms = 0.0;\n  if( getDigits(zDate, \"20c:20e\", &h, &m)!=2 ){\n    return 1;\n  }\n  zDate += 5;\n  if( *zDate==':' ){\n    zDate++;\n    if( getDigits(zDate, \"20e\", &s)!=1 ){\n      return 1;\n    }\n    zDate += 2;\n    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){\n      double rScale = 1.0;\n      zDate++;\n      while( sqlite3Isdigit(*zDate) ){\n        ms = ms*10.0 + *zDate - '0';\n        rScale *= 10.0;\n        zDate++;\n      }\n      ms /= rScale;\n    }\n  }else{\n    s = 0;\n  }\n  p->validJD = 0;\n  p->rawS = 0;\n  p->validHMS = 1;\n  p->h = h;\n  p->m = m;\n  p->s = s + ms;\n  if( parseTimezone(zDate, p) ) return 1;\n  p->validTZ = (p->tz!=0)?1:0;\n  return 0;\n}\n\n/*\n** Put the DateTime object into its error state.\n*/\nstatic void datetimeError(DateTime *p){\n  memset(p, 0, sizeof(*p));\n  p->isError = 1;\n}\n\n/*\n** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume\n** that the YYYY-MM-DD is according to the Gregorian calendar.\n**\n** Reference:  Meeus page 61\n*/\nstatic void computeJD(DateTime *p){\n  int Y, M, D, A, B, X1, X2;\n\n  if( p->validJD ) return;\n  if( p->validYMD ){\n    Y = p->Y;\n    M = p->M;\n    D = p->D;\n  }else{\n    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */\n    M = 1;\n    D = 1;\n  }\n  if( Y<-4713 || Y>9999 || p->rawS ){\n    datetimeError(p);\n    return;\n  }\n  if( M<=2 ){\n    Y--;\n    M += 12;\n  }\n  A = Y/100;\n  B = 2 - A + (A/4);\n  X1 = 36525*(Y+4716)/100;\n  X2 = 306001*(M+1)/10000;\n  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);\n  p->validJD = 1;\n  if( p->validHMS ){\n    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);\n    if( p->validTZ ){\n      p->iJD -= p->tz*60000;\n      p->validYMD = 0;\n      p->validHMS = 0;\n      p->validTZ = 0;\n    }\n  }\n}\n\n/*\n** Parse dates of the form\n**\n**     YYYY-MM-DD HH:MM:SS.FFF\n**     YYYY-MM-DD HH:MM:SS\n**     YYYY-MM-DD HH:MM\n**     YYYY-MM-DD\n**\n** Write the result into the DateTime structure and return 0\n** on success and 1 if the input string is not a well-formed\n** date.\n*/\nstatic int parseYyyyMmDd(const char *zDate, DateTime *p){\n  int Y, M, D, neg;\n\n  if( zDate[0]=='-' ){\n    zDate++;\n    neg = 1;\n  }else{\n    neg = 0;\n  }\n  if( getDigits(zDate, \"40f-21a-21d\", &Y, &M, &D)!=3 ){\n    return 1;\n  }\n  zDate += 10;\n  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }\n  if( parseHhMmSs(zDate, p)==0 ){\n    /* We got the time */\n  }else if( *zDate==0 ){\n    p->validHMS = 0;\n  }else{\n    return 1;\n  }\n  p->validJD = 0;\n  p->validYMD = 1;\n  p->Y = neg ? -Y : Y;\n  p->M = M;\n  p->D = D;\n  if( p->validTZ ){\n    computeJD(p);\n  }\n  return 0;\n}\n\n/*\n** Set the time to the current time reported by the VFS.\n**\n** Return the number of errors.\n*/\nstatic int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){\n  p->iJD = sqlite3StmtCurrentTime(context);\n  if( p->iJD>0 ){\n    p->validJD = 1;\n    return 0;\n  }else{\n    return 1;\n  }\n}\n\n/*\n** Input \"r\" is a numeric quantity which might be a julian day number,\n** or the number of seconds since 1970.  If the value if r is within\n** range of a julian day number, install it as such and set validJD.\n** If the value is a valid unix timestamp, put it in p->s and set p->rawS.\n*/\nstatic void setRawDateNumber(DateTime *p, double r){\n  p->s = r;\n  p->rawS = 1;\n  if( r>=0.0 && r<5373484.5 ){\n    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);\n    p->validJD = 1;\n  }\n}\n\n/*\n** Attempt to parse the given string into a julian day number.  Return\n** the number of errors.\n**\n** The following are acceptable forms for the input string:\n**\n**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM\n**      DDDD.DD \n**      now\n**\n** In the first form, the +/-HH:MM is always optional.  The fractional\n** seconds extension (the \".FFF\") is optional.  The seconds portion\n** (\":SS.FFF\") is option.  The year and date can be omitted as long\n** as there is a time string.  The time string can be omitted as long\n** as there is a year and date.\n*/\nstatic int parseDateOrTime(\n  sqlite3_context *context, \n  const char *zDate, \n  DateTime *p\n){\n  double r;\n  if( parseYyyyMmDd(zDate,p)==0 ){\n    return 0;\n  }else if( parseHhMmSs(zDate, p)==0 ){\n    return 0;\n  }else if( sqlite3StrICmp(zDate,\"now\")==0 && sqlite3NotPureFunc(context) ){\n    return setDateTimeToCurrent(context, p);\n  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8)>0 ){\n    setRawDateNumber(p, r);\n    return 0;\n  }\n  return 1;\n}\n\n/* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.\n** Multiplying this by 86400000 gives 464269060799999 as the maximum value\n** for DateTime.iJD.\n**\n** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with \n** such a large integer literal, so we have to encode it.\n*/\n#define INT_464269060799999  ((((i64)0x1a640)<<32)|0x1072fdff)\n\n/*\n** Return TRUE if the given julian day number is within range.\n**\n** The input is the JulianDay times 86400000.\n*/\nstatic int validJulianDay(sqlite3_int64 iJD){\n  return iJD>=0 && iJD<=INT_464269060799999;\n}\n\n/*\n** Compute the Year, Month, and Day from the julian day number.\n*/\nstatic void computeYMD(DateTime *p){\n  int Z, A, B, C, D, E, X1;\n  if( p->validYMD ) return;\n  if( !p->validJD ){\n    p->Y = 2000;\n    p->M = 1;\n    p->D = 1;\n  }else if( !validJulianDay(p->iJD) ){\n    datetimeError(p);\n    return;\n  }else{\n    Z = (int)((p->iJD + 43200000)/86400000);\n    A = (int)((Z - 1867216.25)/36524.25);\n    A = Z + 1 + A - (A/4);\n    B = A + 1524;\n    C = (int)((B - 122.1)/365.25);\n    D = (36525*(C&32767))/100;\n    E = (int)((B-D)/30.6001);\n    X1 = (int)(30.6001*E);\n    p->D = B - D - X1;\n    p->M = E<14 ? E-1 : E-13;\n    p->Y = p->M>2 ? C - 4716 : C - 4715;\n  }\n  p->validYMD = 1;\n}\n\n/*\n** Compute the Hour, Minute, and Seconds from the julian day number.\n*/\nstatic void computeHMS(DateTime *p){\n  int s;\n  if( p->validHMS ) return;\n  computeJD(p);\n  s = (int)((p->iJD + 43200000) % 86400000);\n  p->s = s/1000.0;\n  s = (int)p->s;\n  p->s -= s;\n  p->h = s/3600;\n  s -= p->h*3600;\n  p->m = s/60;\n  p->s += s - p->m*60;\n  p->rawS = 0;\n  p->validHMS = 1;\n}\n\n/*\n** Compute both YMD and HMS\n*/\nstatic void computeYMD_HMS(DateTime *p){\n  computeYMD(p);\n  computeHMS(p);\n}\n\n/*\n** Clear the YMD and HMS and the TZ\n*/\nstatic void clearYMD_HMS_TZ(DateTime *p){\n  p->validYMD = 0;\n  p->validHMS = 0;\n  p->validTZ = 0;\n}\n\n#ifndef SQLITE_OMIT_LOCALTIME\n/*\n** On recent Windows platforms, the localtime_s() function is available\n** as part of the \"Secure CRT\". It is essentially equivalent to \n** localtime_r() available under most POSIX platforms, except that the \n** order of the parameters is reversed.\n**\n** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.\n**\n** If the user has not indicated to use localtime_r() or localtime_s()\n** already, check for an MSVC build environment that provides \n** localtime_s().\n*/\n#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \\\n    && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)\n#undef  HAVE_LOCALTIME_S\n#define HAVE_LOCALTIME_S 1\n#endif\n\n/*\n** The following routine implements the rough equivalent of localtime_r()\n** using whatever operating-system specific localtime facility that\n** is available.  This routine returns 0 on success and\n** non-zero on any kind of error.\n**\n** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this\n** routine will always fail.\n**\n** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C\n** library function localtime_r() is used to assist in the calculation of\n** local time.\n*/\nstatic int osLocaltime(time_t *t, struct tm *pTm){\n  int rc;\n#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S\n  struct tm *pX;\n#if SQLITE_THREADSAFE>0\n  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);\n#endif\n  sqlite3_mutex_enter(mutex);\n  pX = localtime(t);\n#ifndef SQLITE_UNTESTABLE\n  if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;\n#endif\n  if( pX ) *pTm = *pX;\n  sqlite3_mutex_leave(mutex);\n  rc = pX==0;\n#else\n#ifndef SQLITE_UNTESTABLE\n  if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;\n#endif\n#if HAVE_LOCALTIME_R\n  rc = localtime_r(t, pTm)==0;\n#else\n  rc = localtime_s(pTm, t);\n#endif /* HAVE_LOCALTIME_R */\n#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */\n  return rc;\n}\n#endif /* SQLITE_OMIT_LOCALTIME */\n\n\n#ifndef SQLITE_OMIT_LOCALTIME\n/*\n** Compute the difference (in milliseconds) between localtime and UTC\n** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,\n** return this value and set *pRc to SQLITE_OK. \n**\n** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value\n** is undefined in this case.\n*/\nstatic sqlite3_int64 localtimeOffset(\n  DateTime *p,                    /* Date at which to calculate offset */\n  sqlite3_context *pCtx,          /* Write error here if one occurs */\n  int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */\n){\n  DateTime x, y;\n  time_t t;\n  struct tm sLocal;\n\n  /* Initialize the contents of sLocal to avoid a compiler warning. */\n  memset(&sLocal, 0, sizeof(sLocal));\n\n  x = *p;\n  computeYMD_HMS(&x);\n  if( x.Y<1971 || x.Y>=2038 ){\n    /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only\n    ** works for years between 1970 and 2037. For dates outside this range,\n    ** SQLite attempts to map the year into an equivalent year within this\n    ** range, do the calculation, then map the year back.\n    */\n    x.Y = 2000;\n    x.M = 1;\n    x.D = 1;\n    x.h = 0;\n    x.m = 0;\n    x.s = 0.0;\n  } else {\n    int s = (int)(x.s + 0.5);\n    x.s = s;\n  }\n  x.tz = 0;\n  x.validJD = 0;\n  computeJD(&x);\n  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);\n  if( osLocaltime(&t, &sLocal) ){\n    sqlite3_result_error(pCtx, \"local time unavailable\", -1);\n    *pRc = SQLITE_ERROR;\n    return 0;\n  }\n  y.Y = sLocal.tm_year + 1900;\n  y.M = sLocal.tm_mon + 1;\n  y.D = sLocal.tm_mday;\n  y.h = sLocal.tm_hour;\n  y.m = sLocal.tm_min;\n  y.s = sLocal.tm_sec;\n  y.validYMD = 1;\n  y.validHMS = 1;\n  y.validJD = 0;\n  y.rawS = 0;\n  y.validTZ = 0;\n  y.isError = 0;\n  computeJD(&y);\n  *pRc = SQLITE_OK;\n  return y.iJD - x.iJD;\n}\n#endif /* SQLITE_OMIT_LOCALTIME */\n\n/*\n** The following table defines various date transformations of the form\n**\n**            'NNN days'\n**\n** Where NNN is an arbitrary floating-point number and \"days\" can be one\n** of several units of time.\n*/\nstatic const struct {\n  u8 eType;           /* Transformation type code */\n  u8 nName;           /* Length of th name */\n  char *zName;        /* Name of the transformation */\n  double rLimit;      /* Maximum NNN value for this transform */\n  double rXform;      /* Constant used for this transform */\n} aXformType[] = {\n  { 0, 6, \"second\", 464269060800.0, 1000.0         },\n  { 0, 6, \"minute\", 7737817680.0,   60000.0        },\n  { 0, 4, \"hour\",   128963628.0,    3600000.0      },\n  { 0, 3, \"day\",    5373485.0,      86400000.0     },\n  { 1, 5, \"month\",  176546.0,       2592000000.0   },\n  { 2, 4, \"year\",   14713.0,        31536000000.0  },\n};\n\n/*\n** Process a modifier to a date-time stamp.  The modifiers are\n** as follows:\n**\n**     NNN days\n**     NNN hours\n**     NNN minutes\n**     NNN.NNNN seconds\n**     NNN months\n**     NNN years\n**     start of month\n**     start of year\n**     start of week\n**     start of day\n**     weekday N\n**     unixepoch\n**     localtime\n**     utc\n**\n** Return 0 on success and 1 if there is any kind of error. If the error\n** is in a system call (i.e. localtime()), then an error message is written\n** to context pCtx. If the error is an unrecognized modifier, no error is\n** written to pCtx.\n*/\nstatic int parseModifier(\n  sqlite3_context *pCtx,      /* Function context */\n  const char *z,              /* The text of the modifier */\n  int n,                      /* Length of zMod in bytes */\n  DateTime *p                 /* The date/time value to be modified */\n){\n  int rc = 1;\n  double r;\n  switch(sqlite3UpperToLower[(u8)z[0]] ){\n#ifndef SQLITE_OMIT_LOCALTIME\n    case 'l': {\n      /*    localtime\n      **\n      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to\n      ** show local time.\n      */\n      if( sqlite3_stricmp(z, \"localtime\")==0 && sqlite3NotPureFunc(pCtx) ){\n        computeJD(p);\n        p->iJD += localtimeOffset(p, pCtx, &rc);\n        clearYMD_HMS_TZ(p);\n      }\n      break;\n    }\n#endif\n    case 'u': {\n      /*\n      **    unixepoch\n      **\n      ** Treat the current value of p->s as the number of\n      ** seconds since 1970.  Convert to a real julian day number.\n      */\n      if( sqlite3_stricmp(z, \"unixepoch\")==0 && p->rawS ){\n        r = p->s*1000.0 + 210866760000000.0;\n        if( r>=0.0 && r<464269060800000.0 ){\n          clearYMD_HMS_TZ(p);\n          p->iJD = (sqlite3_int64)(r + 0.5);\n          p->validJD = 1;\n          p->rawS = 0;\n          rc = 0;\n        }\n      }\n#ifndef SQLITE_OMIT_LOCALTIME\n      else if( sqlite3_stricmp(z, \"utc\")==0 && sqlite3NotPureFunc(pCtx) ){\n        if( p->tzSet==0 ){\n          sqlite3_int64 c1;\n          computeJD(p);\n          c1 = localtimeOffset(p, pCtx, &rc);\n          if( rc==SQLITE_OK ){\n            p->iJD -= c1;\n            clearYMD_HMS_TZ(p);\n            p->iJD += c1 - localtimeOffset(p, pCtx, &rc);\n          }\n          p->tzSet = 1;\n        }else{\n          rc = SQLITE_OK;\n        }\n      }\n#endif\n      break;\n    }\n    case 'w': {\n      /*\n      **    weekday N\n      **\n      ** Move the date to the same time on the next occurrence of\n      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the\n      ** date is already on the appropriate weekday, this is a no-op.\n      */\n      if( sqlite3_strnicmp(z, \"weekday \", 8)==0\n               && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)>0\n               && (n=(int)r)==r && n>=0 && r<7 ){\n        sqlite3_int64 Z;\n        computeYMD_HMS(p);\n        p->validTZ = 0;\n        p->validJD = 0;\n        computeJD(p);\n        Z = ((p->iJD + 129600000)/86400000) % 7;\n        if( Z>n ) Z -= 7;\n        p->iJD += (n - Z)*86400000;\n        clearYMD_HMS_TZ(p);\n        rc = 0;\n      }\n      break;\n    }\n    case 's': {\n      /*\n      **    start of TTTTT\n      **\n      ** Move the date backwards to the beginning of the current day,\n      ** or month or year.\n      */\n      if( sqlite3_strnicmp(z, \"start of \", 9)!=0 ) break;\n      if( !p->validJD && !p->validYMD && !p->validHMS ) break;\n      z += 9;\n      computeYMD(p);\n      p->validHMS = 1;\n      p->h = p->m = 0;\n      p->s = 0.0;\n      p->rawS = 0;\n      p->validTZ = 0;\n      p->validJD = 0;\n      if( sqlite3_stricmp(z,\"month\")==0 ){\n        p->D = 1;\n        rc = 0;\n      }else if( sqlite3_stricmp(z,\"year\")==0 ){\n        p->M = 1;\n        p->D = 1;\n        rc = 0;\n      }else if( sqlite3_stricmp(z,\"day\")==0 ){\n        rc = 0;\n      }\n      break;\n    }\n    case '+':\n    case '-':\n    case '0':\n    case '1':\n    case '2':\n    case '3':\n    case '4':\n    case '5':\n    case '6':\n    case '7':\n    case '8':\n    case '9': {\n      double rRounder;\n      int i;\n      for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}\n      if( sqlite3AtoF(z, &r, n, SQLITE_UTF8)<=0 ){\n        rc = 1;\n        break;\n      }\n      if( z[n]==':' ){\n        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the\n        ** specified number of hours, minutes, seconds, and fractional seconds\n        ** to the time.  The \".FFF\" may be omitted.  The \":SS.FFF\" may be\n        ** omitted.\n        */\n        const char *z2 = z;\n        DateTime tx;\n        sqlite3_int64 day;\n        if( !sqlite3Isdigit(*z2) ) z2++;\n        memset(&tx, 0, sizeof(tx));\n        if( parseHhMmSs(z2, &tx) ) break;\n        computeJD(&tx);\n        tx.iJD -= 43200000;\n        day = tx.iJD/86400000;\n        tx.iJD -= day*86400000;\n        if( z[0]=='-' ) tx.iJD = -tx.iJD;\n        computeJD(p);\n        clearYMD_HMS_TZ(p);\n        p->iJD += tx.iJD;\n        rc = 0;\n        break;\n      }\n\n      /* If control reaches this point, it means the transformation is\n      ** one of the forms like \"+NNN days\".  */\n      z += n;\n      while( sqlite3Isspace(*z) ) z++;\n      n = sqlite3Strlen30(z);\n      if( n>10 || n<3 ) break;\n      if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;\n      computeJD(p);\n      rc = 1;\n      rRounder = r<0 ? -0.5 : +0.5;\n      for(i=0; i<ArraySize(aXformType); i++){\n        if( aXformType[i].nName==n\n         && sqlite3_strnicmp(aXformType[i].zName, z, n)==0\n         && r>-aXformType[i].rLimit && r<aXformType[i].rLimit\n        ){\n          switch( aXformType[i].eType ){\n            case 1: { /* Special processing to add months */\n              int x;\n              computeYMD_HMS(p);\n              p->M += (int)r;\n              x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;\n              p->Y += x;\n              p->M -= x*12;\n              p->validJD = 0;\n              r -= (int)r;\n              break;\n            }\n            case 2: { /* Special processing to add years */\n              int y = (int)r;\n              computeYMD_HMS(p);\n              p->Y += y;\n              p->validJD = 0;\n              r -= (int)r;\n              break;\n            }\n          }\n          computeJD(p);\n          p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);\n          rc = 0;\n          break;\n        }\n      }\n      clearYMD_HMS_TZ(p);\n      break;\n    }\n    default: {\n      break;\n    }\n  }\n  return rc;\n}\n\n/*\n** Process time function arguments.  argv[0] is a date-time stamp.\n** argv[1] and following are modifiers.  Parse them all and write\n** the resulting time into the DateTime structure p.  Return 0\n** on success and 1 if there are any errors.\n**\n** If there are zero parameters (if even argv[0] is undefined)\n** then assume a default value of \"now\" for argv[0].\n*/\nstatic int isDate(\n  sqlite3_context *context, \n  int argc, \n  sqlite3_value **argv, \n  DateTime *p\n){\n  int i, n;\n  const unsigned char *z;\n  int eType;\n  memset(p, 0, sizeof(*p));\n  if( argc==0 ){\n    return setDateTimeToCurrent(context, p);\n  }\n  if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT\n                   || eType==SQLITE_INTEGER ){\n    setRawDateNumber(p, sqlite3_value_double(argv[0]));\n  }else{\n    z = sqlite3_value_text(argv[0]);\n    if( !z || parseDateOrTime(context, (char*)z, p) ){\n      return 1;\n    }\n  }\n  for(i=1; i<argc; i++){\n    z = sqlite3_value_text(argv[i]);\n    n = sqlite3_value_bytes(argv[i]);\n    if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;\n  }\n  computeJD(p);\n  if( p->isError || !validJulianDay(p->iJD) ) return 1;\n  return 0;\n}\n\n\n/*\n** The following routines implement the various date and time functions\n** of SQLite.\n*/\n\n/*\n**    julianday( TIMESTRING, MOD, MOD, ...)\n**\n** Return the julian day number of the date specified in the arguments\n*/\nstatic void juliandayFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  DateTime x;\n  if( isDate(context, argc, argv, &x)==0 ){\n    computeJD(&x);\n    sqlite3_result_double(context, x.iJD/86400000.0);\n  }\n}\n\n/*\n**    datetime( TIMESTRING, MOD, MOD, ...)\n**\n** Return YYYY-MM-DD HH:MM:SS\n*/\nstatic void datetimeFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  DateTime x;\n  if( isDate(context, argc, argv, &x)==0 ){\n    char zBuf[100];\n    computeYMD_HMS(&x);\n    sqlite3_snprintf(sizeof(zBuf), zBuf, \"%04d-%02d-%02d %02d:%02d:%02d\",\n                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));\n    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);\n  }\n}\n\n/*\n**    time( TIMESTRING, MOD, MOD, ...)\n**\n** Return HH:MM:SS\n*/\nstatic void timeFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  DateTime x;\n  if( isDate(context, argc, argv, &x)==0 ){\n    char zBuf[100];\n    computeHMS(&x);\n    sqlite3_snprintf(sizeof(zBuf), zBuf, \"%02d:%02d:%02d\", x.h, x.m, (int)x.s);\n    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);\n  }\n}\n\n/*\n**    date( TIMESTRING, MOD, MOD, ...)\n**\n** Return YYYY-MM-DD\n*/\nstatic void dateFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  DateTime x;\n  if( isDate(context, argc, argv, &x)==0 ){\n    char zBuf[100];\n    computeYMD(&x);\n    sqlite3_snprintf(sizeof(zBuf), zBuf, \"%04d-%02d-%02d\", x.Y, x.M, x.D);\n    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);\n  }\n}\n\n/*\n**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)\n**\n** Return a string described by FORMAT.  Conversions as follows:\n**\n**   %d  day of month\n**   %f  ** fractional seconds  SS.SSS\n**   %H  hour 00-24\n**   %j  day of year 000-366\n**   %J  ** julian day number\n**   %m  month 01-12\n**   %M  minute 00-59\n**   %s  seconds since 1970-01-01\n**   %S  seconds 00-59\n**   %w  day of week 0-6  sunday==0\n**   %W  week of year 00-53\n**   %Y  year 0000-9999\n**   %%  %\n*/\nstatic void strftimeFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  DateTime x;\n  u64 n;\n  size_t i,j;\n  char *z;\n  sqlite3 *db;\n  const char *zFmt;\n  char zBuf[100];\n  if( argc==0 ) return;\n  zFmt = (const char*)sqlite3_value_text(argv[0]);\n  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;\n  db = sqlite3_context_db_handle(context);\n  for(i=0, n=1; zFmt[i]; i++, n++){\n    if( zFmt[i]=='%' ){\n      switch( zFmt[i+1] ){\n        case 'd':\n        case 'H':\n        case 'm':\n        case 'M':\n        case 'S':\n        case 'W':\n          n++;\n          /* fall thru */\n        case 'w':\n        case '%':\n          break;\n        case 'f':\n          n += 8;\n          break;\n        case 'j':\n          n += 3;\n          break;\n        case 'Y':\n          n += 8;\n          break;\n        case 's':\n        case 'J':\n          n += 50;\n          break;\n        default:\n          return;  /* ERROR.  return a NULL */\n      }\n      i++;\n    }\n  }\n  testcase( n==sizeof(zBuf)-1 );\n  testcase( n==sizeof(zBuf) );\n  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );\n  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );\n  if( n<sizeof(zBuf) ){\n    z = zBuf;\n  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){\n    sqlite3_result_error_toobig(context);\n    return;\n  }else{\n    z = sqlite3DbMallocRawNN(db, (int)n);\n    if( z==0 ){\n      sqlite3_result_error_nomem(context);\n      return;\n    }\n  }\n  computeJD(&x);\n  computeYMD_HMS(&x);\n  for(i=j=0; zFmt[i]; i++){\n    if( zFmt[i]!='%' ){\n      z[j++] = zFmt[i];\n    }else{\n      i++;\n      switch( zFmt[i] ){\n        case 'd':  sqlite3_snprintf(3, &z[j],\"%02d\",x.D); j+=2; break;\n        case 'f': {\n          double s = x.s;\n          if( s>59.999 ) s = 59.999;\n          sqlite3_snprintf(7, &z[j],\"%06.3f\", s);\n          j += sqlite3Strlen30(&z[j]);\n          break;\n        }\n        case 'H':  sqlite3_snprintf(3, &z[j],\"%02d\",x.h); j+=2; break;\n        case 'W': /* Fall thru */\n        case 'j': {\n          int nDay;             /* Number of days since 1st day of year */\n          DateTime y = x;\n          y.validJD = 0;\n          y.M = 1;\n          y.D = 1;\n          computeJD(&y);\n          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);\n          if( zFmt[i]=='W' ){\n            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */\n            wd = (int)(((x.iJD+43200000)/86400000)%7);\n            sqlite3_snprintf(3, &z[j],\"%02d\",(nDay+7-wd)/7);\n            j += 2;\n          }else{\n            sqlite3_snprintf(4, &z[j],\"%03d\",nDay+1);\n            j += 3;\n          }\n          break;\n        }\n        case 'J': {\n          sqlite3_snprintf(20, &z[j],\"%.16g\",x.iJD/86400000.0);\n          j+=sqlite3Strlen30(&z[j]);\n          break;\n        }\n        case 'm':  sqlite3_snprintf(3, &z[j],\"%02d\",x.M); j+=2; break;\n        case 'M':  sqlite3_snprintf(3, &z[j],\"%02d\",x.m); j+=2; break;\n        case 's': {\n          sqlite3_snprintf(30,&z[j],\"%lld\",\n                           (i64)(x.iJD/1000 - 21086676*(i64)10000));\n          j += sqlite3Strlen30(&z[j]);\n          break;\n        }\n        case 'S':  sqlite3_snprintf(3,&z[j],\"%02d\",(int)x.s); j+=2; break;\n        case 'w': {\n          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';\n          break;\n        }\n        case 'Y': {\n          sqlite3_snprintf(5,&z[j],\"%04d\",x.Y); j+=sqlite3Strlen30(&z[j]);\n          break;\n        }\n        default:   z[j++] = '%'; break;\n      }\n    }\n  }\n  z[j] = 0;\n  sqlite3_result_text(context, z, -1,\n                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);\n}\n\n/*\n** current_time()\n**\n** This function returns the same value as time('now').\n*/\nstatic void ctimeFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **NotUsed2\n){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  timeFunc(context, 0, 0);\n}\n\n/*\n** current_date()\n**\n** This function returns the same value as date('now').\n*/\nstatic void cdateFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **NotUsed2\n){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  dateFunc(context, 0, 0);\n}\n\n/*\n** current_timestamp()\n**\n** This function returns the same value as datetime('now').\n*/\nstatic void ctimestampFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **NotUsed2\n){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  datetimeFunc(context, 0, 0);\n}\n#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */\n\n#ifdef SQLITE_OMIT_DATETIME_FUNCS\n/*\n** If the library is compiled to omit the full-scale date and time\n** handling (to get a smaller binary), the following minimal version\n** of the functions current_time(), current_date() and current_timestamp()\n** are included instead. This is to support column declarations that\n** include \"DEFAULT CURRENT_TIME\" etc.\n**\n** This function uses the C-library functions time(), gmtime()\n** and strftime(). The format string to pass to strftime() is supplied\n** as the user-data for the function.\n*/\nstatic void currentTimeFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  time_t t;\n  char *zFormat = (char *)sqlite3_user_data(context);\n  sqlite3_int64 iT;\n  struct tm *pTm;\n  struct tm sNow;\n  char zBuf[20];\n\n  UNUSED_PARAMETER(argc);\n  UNUSED_PARAMETER(argv);\n\n  iT = sqlite3StmtCurrentTime(context);\n  if( iT<=0 ) return;\n  t = iT/1000 - 10000*(sqlite3_int64)21086676;\n#if HAVE_GMTIME_R\n  pTm = gmtime_r(&t, &sNow);\n#else\n  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));\n  pTm = gmtime(&t);\n  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));\n  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));\n#endif\n  if( pTm ){\n    strftime(zBuf, 20, zFormat, &sNow);\n    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);\n  }\n}\n#endif\n\n/*\n** This function registered all of the above C functions as SQL\n** functions.  This should be the only routine in this file with\n** external linkage.\n*/\nSQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){\n  static FuncDef aDateTimeFuncs[] = {\n#ifndef SQLITE_OMIT_DATETIME_FUNCS\n    PURE_DATE(julianday,        -1, 0, 0, juliandayFunc ),\n    PURE_DATE(date,             -1, 0, 0, dateFunc      ),\n    PURE_DATE(time,             -1, 0, 0, timeFunc      ),\n    PURE_DATE(datetime,         -1, 0, 0, datetimeFunc  ),\n    PURE_DATE(strftime,         -1, 0, 0, strftimeFunc  ),\n    DFUNCTION(current_time,      0, 0, 0, ctimeFunc     ),\n    DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),\n    DFUNCTION(current_date,      0, 0, 0, cdateFunc     ),\n#else\n    STR_FUNCTION(current_time,      0, \"%H:%M:%S\",          0, currentTimeFunc),\n    STR_FUNCTION(current_date,      0, \"%Y-%m-%d\",          0, currentTimeFunc),\n    STR_FUNCTION(current_timestamp, 0, \"%Y-%m-%d %H:%M:%S\", 0, currentTimeFunc),\n#endif\n  };\n  sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));\n}\n\n/************** End of date.c ************************************************/\n/************** Begin file os.c **********************************************/\n/*\n** 2005 November 29\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains OS interface code that is common to all\n** architectures.\n*/\n/* #include \"sqliteInt.h\" */\n\n/*\n** If we compile with the SQLITE_TEST macro set, then the following block\n** of code will give us the ability to simulate a disk I/O error.  This\n** is used for testing the I/O recovery logic.\n*/\n#if defined(SQLITE_TEST)\nSQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */\nSQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */\nSQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */\nSQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */\nSQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */\nSQLITE_API int sqlite3_diskfull_pending = 0;\nSQLITE_API int sqlite3_diskfull = 0;\n#endif /* defined(SQLITE_TEST) */\n\n/*\n** When testing, also keep a count of the number of open files.\n*/\n#if defined(SQLITE_TEST)\nSQLITE_API int sqlite3_open_file_count = 0;\n#endif /* defined(SQLITE_TEST) */\n\n/*\n** The default SQLite sqlite3_vfs implementations do not allocate\n** memory (actually, os_unix.c allocates a small amount of memory\n** from within OsOpen()), but some third-party implementations may.\n** So we test the effects of a malloc() failing and the sqlite3OsXXX()\n** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.\n**\n** The following functions are instrumented for malloc() failure\n** testing:\n**\n**     sqlite3OsRead()\n**     sqlite3OsWrite()\n**     sqlite3OsSync()\n**     sqlite3OsFileSize()\n**     sqlite3OsLock()\n**     sqlite3OsCheckReservedLock()\n**     sqlite3OsFileControl()\n**     sqlite3OsShmMap()\n**     sqlite3OsOpen()\n**     sqlite3OsDelete()\n**     sqlite3OsAccess()\n**     sqlite3OsFullPathname()\n**\n*/\n#if defined(SQLITE_TEST)\nSQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;\n  #define DO_OS_MALLOC_TEST(x)                                       \\\n  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \\\n    void *pTstAlloc = sqlite3Malloc(10);                             \\\n    if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT;                  \\\n    sqlite3_free(pTstAlloc);                                         \\\n  }\n#else\n  #define DO_OS_MALLOC_TEST(x)\n#endif\n\n/*\n** The following routines are convenience wrappers around methods\n** of the sqlite3_file object.  This is mostly just syntactic sugar. All\n** of this would be completely automatic if SQLite were coded using\n** C++ instead of plain old C.\n*/\nSQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){\n  if( pId->pMethods ){\n    pId->pMethods->xClose(pId);\n    pId->pMethods = 0;\n  }\n}\nSQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){\n  DO_OS_MALLOC_TEST(id);\n  return id->pMethods->xRead(id, pBuf, amt, offset);\n}\nSQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){\n  DO_OS_MALLOC_TEST(id);\n  return id->pMethods->xWrite(id, pBuf, amt, offset);\n}\nSQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){\n  return id->pMethods->xTruncate(id, size);\n}\nSQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){\n  DO_OS_MALLOC_TEST(id);\n  return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;\n}\nSQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){\n  DO_OS_MALLOC_TEST(id);\n  return id->pMethods->xFileSize(id, pSize);\n}\nSQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){\n  DO_OS_MALLOC_TEST(id);\n  return id->pMethods->xLock(id, lockType);\n}\nSQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){\n  return id->pMethods->xUnlock(id, lockType);\n}\nSQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){\n  DO_OS_MALLOC_TEST(id);\n  return id->pMethods->xCheckReservedLock(id, pResOut);\n}\n\n/*\n** Use sqlite3OsFileControl() when we are doing something that might fail\n** and we need to know about the failures.  Use sqlite3OsFileControlHint()\n** when simply tossing information over the wall to the VFS and we do not\n** really care if the VFS receives and understands the information since it\n** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()\n** routine has no return value since the return value would be meaningless.\n*/\nSQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){\n  if( id->pMethods==0 ) return SQLITE_NOTFOUND;\n#ifdef SQLITE_TEST\n  if( op!=SQLITE_FCNTL_COMMIT_PHASETWO\n   && op!=SQLITE_FCNTL_LOCK_TIMEOUT\n  ){\n    /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite\n    ** is using a regular VFS, it is called after the corresponding\n    ** transaction has been committed. Injecting a fault at this point\n    ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM\n    ** but the transaction is committed anyway.\n    **\n    ** The core must call OsFileControl() though, not OsFileControlHint(),\n    ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably\n    ** means the commit really has failed and an error should be returned\n    ** to the user.  */\n    DO_OS_MALLOC_TEST(id);\n  }\n#endif\n  return id->pMethods->xFileControl(id, op, pArg);\n}\nSQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){\n  if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg);\n}\n\nSQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){\n  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;\n  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);\n}\nSQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){\n  return id->pMethods->xDeviceCharacteristics(id);\n}\n#ifndef SQLITE_OMIT_WAL\nSQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){\n  return id->pMethods->xShmLock(id, offset, n, flags);\n}\nSQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){\n  id->pMethods->xShmBarrier(id);\n}\nSQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){\n  return id->pMethods->xShmUnmap(id, deleteFlag);\n}\nSQLITE_PRIVATE int sqlite3OsShmMap(\n  sqlite3_file *id,               /* Database file handle */\n  int iPage,\n  int pgsz,\n  int bExtend,                    /* True to extend file if necessary */\n  void volatile **pp              /* OUT: Pointer to mapping */\n){\n  DO_OS_MALLOC_TEST(id);\n  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);\n}\n#endif /* SQLITE_OMIT_WAL */\n\n#if SQLITE_MAX_MMAP_SIZE>0\n/* The real implementation of xFetch and xUnfetch */\nSQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){\n  DO_OS_MALLOC_TEST(id);\n  return id->pMethods->xFetch(id, iOff, iAmt, pp);\n}\nSQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){\n  return id->pMethods->xUnfetch(id, iOff, p);\n}\n#else\n/* No-op stubs to use when memory-mapped I/O is disabled */\nSQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){\n  *pp = 0;\n  return SQLITE_OK;\n}\nSQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){\n  return SQLITE_OK;\n}\n#endif\n\n/*\n** The next group of routines are convenience wrappers around the\n** VFS methods.\n*/\nSQLITE_PRIVATE int sqlite3OsOpen(\n  sqlite3_vfs *pVfs,\n  const char *zPath,\n  sqlite3_file *pFile,\n  int flags,\n  int *pFlagsOut\n){\n  int rc;\n  DO_OS_MALLOC_TEST(0);\n  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed\n  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,\n  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before\n  ** reaching the VFS. */\n  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x1087f7f, pFlagsOut);\n  assert( rc==SQLITE_OK || pFile->pMethods==0 );\n  return rc;\n}\nSQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){\n  DO_OS_MALLOC_TEST(0);\n  assert( dirSync==0 || dirSync==1 );\n  return pVfs->xDelete(pVfs, zPath, dirSync);\n}\nSQLITE_PRIVATE int sqlite3OsAccess(\n  sqlite3_vfs *pVfs,\n  const char *zPath,\n  int flags,\n  int *pResOut\n){\n  DO_OS_MALLOC_TEST(0);\n  return pVfs->xAccess(pVfs, zPath, flags, pResOut);\n}\nSQLITE_PRIVATE int sqlite3OsFullPathname(\n  sqlite3_vfs *pVfs,\n  const char *zPath,\n  int nPathOut,\n  char *zPathOut\n){\n  DO_OS_MALLOC_TEST(0);\n  zPathOut[0] = 0;\n  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);\n}\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\nSQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){\n  return pVfs->xDlOpen(pVfs, zPath);\n}\nSQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){\n  pVfs->xDlError(pVfs, nByte, zBufOut);\n}\nSQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){\n  return pVfs->xDlSym(pVfs, pHdle, zSym);\n}\nSQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){\n  pVfs->xDlClose(pVfs, pHandle);\n}\n#endif /* SQLITE_OMIT_LOAD_EXTENSION */\nSQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){\n  if( sqlite3Config.iPrngSeed ){\n    memset(zBufOut, 0, nByte);\n    if( ALWAYS(nByte>(signed)sizeof(unsigned)) ) nByte = sizeof(unsigned int);\n    memcpy(zBufOut, &sqlite3Config.iPrngSeed, nByte);\n    return SQLITE_OK;\n  }else{\n    return pVfs->xRandomness(pVfs, nByte, zBufOut);\n  }\n  \n}\nSQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){\n  return pVfs->xSleep(pVfs, nMicro);\n}\nSQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){\n  return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;\n}\nSQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){\n  int rc;\n  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()\n  ** method to get the current date and time if that method is available\n  ** (if iVersion is 2 or greater and the function pointer is not NULL) and\n  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is\n  ** unavailable.\n  */\n  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){\n    rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);\n  }else{\n    double r;\n    rc = pVfs->xCurrentTime(pVfs, &r);\n    *pTimeOut = (sqlite3_int64)(r*86400000.0);\n  }\n  return rc;\n}\n\nSQLITE_PRIVATE int sqlite3OsOpenMalloc(\n  sqlite3_vfs *pVfs,\n  const char *zFile,\n  sqlite3_file **ppFile,\n  int flags,\n  int *pOutFlags\n){\n  int rc;\n  sqlite3_file *pFile;\n  pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);\n  if( pFile ){\n    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);\n    if( rc!=SQLITE_OK ){\n      sqlite3_free(pFile);\n    }else{\n      *ppFile = pFile;\n    }\n  }else{\n    rc = SQLITE_NOMEM_BKPT;\n  }\n  return rc;\n}\nSQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){\n  assert( pFile );\n  sqlite3OsClose(pFile);\n  sqlite3_free(pFile);\n}\n\n/*\n** This function is a wrapper around the OS specific implementation of\n** sqlite3_os_init(). The purpose of the wrapper is to provide the\n** ability to simulate a malloc failure, so that the handling of an\n** error in sqlite3_os_init() by the upper layers can be tested.\n*/\nSQLITE_PRIVATE int sqlite3OsInit(void){\n  void *p = sqlite3_malloc(10);\n  if( p==0 ) return SQLITE_NOMEM_BKPT;\n  sqlite3_free(p);\n  return sqlite3_os_init();\n}\n\n/*\n** The list of all registered VFS implementations.\n*/\nstatic sqlite3_vfs * SQLITE_WSD vfsList = 0;\n#define vfsList GLOBAL(sqlite3_vfs *, vfsList)\n\n/*\n** Locate a VFS by name.  If no name is given, simply return the\n** first VFS on the list.\n*/\nSQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){\n  sqlite3_vfs *pVfs = 0;\n#if SQLITE_THREADSAFE\n  sqlite3_mutex *mutex;\n#endif\n#ifndef SQLITE_OMIT_AUTOINIT\n  int rc = sqlite3_initialize();\n  if( rc ) return 0;\n#endif\n#if SQLITE_THREADSAFE\n  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);\n#endif\n  sqlite3_mutex_enter(mutex);\n  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){\n    if( zVfs==0 ) break;\n    if( strcmp(zVfs, pVfs->zName)==0 ) break;\n  }\n  sqlite3_mutex_leave(mutex);\n  return pVfs;\n}\n\n/*\n** Unlink a VFS from the linked list\n*/\nstatic void vfsUnlink(sqlite3_vfs *pVfs){\n  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );\n  if( pVfs==0 ){\n    /* No-op */\n  }else if( vfsList==pVfs ){\n    vfsList = pVfs->pNext;\n  }else if( vfsList ){\n    sqlite3_vfs *p = vfsList;\n    while( p->pNext && p->pNext!=pVfs ){\n      p = p->pNext;\n    }\n    if( p->pNext==pVfs ){\n      p->pNext = pVfs->pNext;\n    }\n  }\n}\n\n/*\n** Register a VFS with the system.  It is harmless to register the same\n** VFS multiple times.  The new VFS becomes the default if makeDflt is\n** true.\n*/\nSQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){\n  MUTEX_LOGIC(sqlite3_mutex *mutex;)\n#ifndef SQLITE_OMIT_AUTOINIT\n  int rc = sqlite3_initialize();\n  if( rc ) return rc;\n#endif\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( pVfs==0 ) return SQLITE_MISUSE_BKPT;\n#endif\n\n  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )\n  sqlite3_mutex_enter(mutex);\n  vfsUnlink(pVfs);\n  if( makeDflt || vfsList==0 ){\n    pVfs->pNext = vfsList;\n    vfsList = pVfs;\n  }else{\n    pVfs->pNext = vfsList->pNext;\n    vfsList->pNext = pVfs;\n  }\n  assert(vfsList);\n  sqlite3_mutex_leave(mutex);\n  return SQLITE_OK;\n}\n\n/*\n** Unregister a VFS so that it is no longer accessible.\n*/\nSQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){\n  MUTEX_LOGIC(sqlite3_mutex *mutex;)\n#ifndef SQLITE_OMIT_AUTOINIT\n  int rc = sqlite3_initialize();\n  if( rc ) return rc;\n#endif\n  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )\n  sqlite3_mutex_enter(mutex);\n  vfsUnlink(pVfs);\n  sqlite3_mutex_leave(mutex);\n  return SQLITE_OK;\n}\n\n/************** End of os.c **************************************************/\n/************** Begin file fault.c *******************************************/\n/*\n** 2008 Jan 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains code to support the concept of \"benign\" \n** malloc failures (when the xMalloc() or xRealloc() method of the\n** sqlite3_mem_methods structure fails to allocate a block of memory\n** and returns 0). \n**\n** Most malloc failures are non-benign. After they occur, SQLite\n** abandons the current operation and returns an error code (usually\n** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily\n** fatal. For example, if a malloc fails while resizing a hash table, this \n** is completely recoverable simply by not carrying out the resize. The \n** hash table will continue to function normally.  So a malloc failure \n** during a hash table resize is a benign fault.\n*/\n\n/* #include \"sqliteInt.h\" */\n\n#ifndef SQLITE_UNTESTABLE\n\n/*\n** Global variables.\n*/\ntypedef struct BenignMallocHooks BenignMallocHooks;\nstatic SQLITE_WSD struct BenignMallocHooks {\n  void (*xBenignBegin)(void);\n  void (*xBenignEnd)(void);\n} sqlite3Hooks = { 0, 0 };\n\n/* The \"wsdHooks\" macro will resolve to the appropriate BenignMallocHooks\n** structure.  If writable static data is unsupported on the target,\n** we have to locate the state vector at run-time.  In the more common\n** case where writable static data is supported, wsdHooks can refer directly\n** to the \"sqlite3Hooks\" state vector declared above.\n*/\n#ifdef SQLITE_OMIT_WSD\n# define wsdHooksInit \\\n  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)\n# define wsdHooks x[0]\n#else\n# define wsdHooksInit\n# define wsdHooks sqlite3Hooks\n#endif\n\n\n/*\n** Register hooks to call when sqlite3BeginBenignMalloc() and\n** sqlite3EndBenignMalloc() are called, respectively.\n*/\nSQLITE_PRIVATE void sqlite3BenignMallocHooks(\n  void (*xBenignBegin)(void),\n  void (*xBenignEnd)(void)\n){\n  wsdHooksInit;\n  wsdHooks.xBenignBegin = xBenignBegin;\n  wsdHooks.xBenignEnd = xBenignEnd;\n}\n\n/*\n** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that\n** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()\n** indicates that subsequent malloc failures are non-benign.\n*/\nSQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){\n  wsdHooksInit;\n  if( wsdHooks.xBenignBegin ){\n    wsdHooks.xBenignBegin();\n  }\n}\nSQLITE_PRIVATE void sqlite3EndBenignMalloc(void){\n  wsdHooksInit;\n  if( wsdHooks.xBenignEnd ){\n    wsdHooks.xBenignEnd();\n  }\n}\n\n#endif   /* #ifndef SQLITE_UNTESTABLE */\n\n/************** End of fault.c ***********************************************/\n/************** Begin file mem0.c ********************************************/\n/*\n** 2008 October 28\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains a no-op memory allocation drivers for use when\n** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented\n** here always fail.  SQLite will not operate with these drivers.  These\n** are merely placeholders.  Real drivers must be substituted using\n** sqlite3_config() before SQLite will operate.\n*/\n/* #include \"sqliteInt.h\" */\n\n/*\n** This version of the memory allocator is the default.  It is\n** used when no other memory allocator is specified using compile-time\n** macros.\n*/\n#ifdef SQLITE_ZERO_MALLOC\n\n/*\n** No-op versions of all memory allocation routines\n*/\nstatic void *sqlite3MemMalloc(int nByte){ return 0; }\nstatic void sqlite3MemFree(void *pPrior){ return; }\nstatic void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }\nstatic int sqlite3MemSize(void *pPrior){ return 0; }\nstatic int sqlite3MemRoundup(int n){ return n; }\nstatic int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }\nstatic void sqlite3MemShutdown(void *NotUsed){ return; }\n\n/*\n** This routine is the only routine in this file with external linkage.\n**\n** Populate the low-level memory allocation function pointers in\n** sqlite3GlobalConfig.m with pointers to the routines in this file.\n*/\nSQLITE_PRIVATE void sqlite3MemSetDefault(void){\n  static const sqlite3_mem_methods defaultMethods = {\n     sqlite3MemMalloc,\n     sqlite3MemFree,\n     sqlite3MemRealloc,\n     sqlite3MemSize,\n     sqlite3MemRoundup,\n     sqlite3MemInit,\n     sqlite3MemShutdown,\n     0\n  };\n  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);\n}\n\n#endif /* SQLITE_ZERO_MALLOC */\n\n/************** End of mem0.c ************************************************/\n/************** Begin file mem1.c ********************************************/\n/*\n** 2007 August 14\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains low-level memory allocation drivers for when\n** SQLite will use the standard C-library malloc/realloc/free interface\n** to obtain the memory it needs.\n**\n** This file contains implementations of the low-level memory allocation\n** routines specified in the sqlite3_mem_methods object.  The content of\n** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The\n** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the\n** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The\n** default configuration is to use memory allocation routines in this\n** file.\n**\n** C-preprocessor macro summary:\n**\n**    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if\n**                                the malloc_usable_size() interface exists\n**                                on the target platform.  Or, this symbol\n**                                can be set manually, if desired.\n**                                If an equivalent interface exists by\n**                                a different name, using a separate -D\n**                                option to rename it.\n**\n**    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone\n**                                memory allocator.  Set this symbol to enable\n**                                building on older macs.\n**\n**    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of\n**                                _msize() on windows systems.  This might\n**                                be necessary when compiling for Delphi,\n**                                for example.\n*/\n/* #include \"sqliteInt.h\" */\n\n/*\n** This version of the memory allocator is the default.  It is\n** used when no other memory allocator is specified using compile-time\n** macros.\n*/\n#ifdef SQLITE_SYSTEM_MALLOC\n#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)\n\n/*\n** Use the zone allocator available on apple products unless the\n** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.\n*/\n#include <sys/sysctl.h>\n#include <malloc/malloc.h>\n#ifdef SQLITE_MIGHT_BE_SINGLE_CORE\n#include <libkern/OSAtomic.h>\n#endif /* SQLITE_MIGHT_BE_SINGLE_CORE */\nstatic malloc_zone_t* _sqliteZone_;\n#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))\n#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));\n#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))\n#define SQLITE_MALLOCSIZE(x) \\\n        (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))\n\n#else /* if not __APPLE__ */\n\n/*\n** Use standard C library malloc and free on non-Apple systems.  \n** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.\n*/\n#define SQLITE_MALLOC(x)             malloc(x)\n#define SQLITE_FREE(x)               free(x)\n#define SQLITE_REALLOC(x,y)          realloc((x),(y))\n\n/*\n** The malloc.h header file is needed for malloc_usable_size() function\n** on some systems (e.g. Linux).\n*/\n#if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE\n#  define SQLITE_USE_MALLOC_H 1\n#  define SQLITE_USE_MALLOC_USABLE_SIZE 1\n/*\n** The MSVCRT has malloc_usable_size(), but it is called _msize().  The\n** use of _msize() is automatic, but can be disabled by compiling with\n** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires\n** the malloc.h header file.\n*/\n#elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)\n#  define SQLITE_USE_MALLOC_H\n#  define SQLITE_USE_MSIZE\n#endif\n\n/*\n** Include the malloc.h header file, if necessary.  Also set define macro\n** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()\n** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).\n** The memory size function can always be overridden manually by defining\n** the macro SQLITE_MALLOCSIZE to the desired function name.\n*/\n#if defined(SQLITE_USE_MALLOC_H)\n#  include <malloc.h>\n#  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)\n#    if !defined(SQLITE_MALLOCSIZE)\n#      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)\n#    endif\n#  elif defined(SQLITE_USE_MSIZE)\n#    if !defined(SQLITE_MALLOCSIZE)\n#      define SQLITE_MALLOCSIZE      _msize\n#    endif\n#  endif\n#endif /* defined(SQLITE_USE_MALLOC_H) */\n\n#endif /* __APPLE__ or not __APPLE__ */\n\n/*\n** Like malloc(), but remember the size of the allocation\n** so that we can find it later using sqlite3MemSize().\n**\n** For this low-level routine, we are guaranteed that nByte>0 because\n** cases of nByte<=0 will be intercepted and dealt with by higher level\n** routines.\n*/\nstatic void *sqlite3MemMalloc(int nByte){\n#ifdef SQLITE_MALLOCSIZE\n  void *p;\n  testcase( ROUND8(nByte)==nByte );\n  p = SQLITE_MALLOC( nByte );\n  if( p==0 ){\n    testcase( sqlite3GlobalConfig.xLog!=0 );\n    sqlite3_log(SQLITE_NOMEM, \"failed to allocate %u bytes of memory\", nByte);\n  }\n  return p;\n#else\n  sqlite3_int64 *p;\n  assert( nByte>0 );\n  testcase( ROUND8(nByte)!=nByte );\n  p = SQLITE_MALLOC( nByte+8 );\n  if( p ){\n    p[0] = nByte;\n    p++;\n  }else{\n    testcase( sqlite3GlobalConfig.xLog!=0 );\n    sqlite3_log(SQLITE_NOMEM, \"failed to allocate %u bytes of memory\", nByte);\n  }\n  return (void *)p;\n#endif\n}\n\n/*\n** Like free() but works for allocations obtained from sqlite3MemMalloc()\n** or sqlite3MemRealloc().\n**\n** For this low-level routine, we already know that pPrior!=0 since\n** cases where pPrior==0 will have been intecepted and dealt with\n** by higher-level routines.\n*/\nstatic void sqlite3MemFree(void *pPrior){\n#ifdef SQLITE_MALLOCSIZE\n  SQLITE_FREE(pPrior);\n#else\n  sqlite3_int64 *p = (sqlite3_int64*)pPrior;\n  assert( pPrior!=0 );\n  p--;\n  SQLITE_FREE(p);\n#endif\n}\n\n/*\n** Report the allocated size of a prior return from xMalloc()\n** or xRealloc().\n*/\nstatic int sqlite3MemSize(void *pPrior){\n#ifdef SQLITE_MALLOCSIZE\n  assert( pPrior!=0 );\n  return (int)SQLITE_MALLOCSIZE(pPrior);\n#else\n  sqlite3_int64 *p;\n  assert( pPrior!=0 );\n  p = (sqlite3_int64*)pPrior;\n  p--;\n  return (int)p[0];\n#endif\n}\n\n/*\n** Like realloc().  Resize an allocation previously obtained from\n** sqlite3MemMalloc().\n**\n** For this low-level interface, we know that pPrior!=0.  Cases where\n** pPrior==0 while have been intercepted by higher-level routine and\n** redirected to xMalloc.  Similarly, we know that nByte>0 because\n** cases where nByte<=0 will have been intercepted by higher-level\n** routines and redirected to xFree.\n*/\nstatic void *sqlite3MemRealloc(void *pPrior, int nByte){\n#ifdef SQLITE_MALLOCSIZE\n  void *p = SQLITE_REALLOC(pPrior, nByte);\n  if( p==0 ){\n    testcase( sqlite3GlobalConfig.xLog!=0 );\n    sqlite3_log(SQLITE_NOMEM,\n      \"failed memory resize %u to %u bytes\",\n      SQLITE_MALLOCSIZE(pPrior), nByte);\n  }\n  return p;\n#else\n  sqlite3_int64 *p = (sqlite3_int64*)pPrior;\n  assert( pPrior!=0 && nByte>0 );\n  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */\n  p--;\n  p = SQLITE_REALLOC(p, nByte+8 );\n  if( p ){\n    p[0] = nByte;\n    p++;\n  }else{\n    testcase( sqlite3GlobalConfig.xLog!=0 );\n    sqlite3_log(SQLITE_NOMEM,\n      \"failed memory resize %u to %u bytes\",\n      sqlite3MemSize(pPrior), nByte);\n  }\n  return (void*)p;\n#endif\n}\n\n/*\n** Round up a request size to the next valid allocation size.\n*/\nstatic int sqlite3MemRoundup(int n){\n  return ROUND8(n);\n}\n\n/*\n** Initialize this module.\n*/\nstatic int sqlite3MemInit(void *NotUsed){\n#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)\n  int cpuCount;\n  size_t len;\n  if( _sqliteZone_ ){\n    return SQLITE_OK;\n  }\n  len = sizeof(cpuCount);\n  /* One usually wants to use hw.acctivecpu for MT decisions, but not here */\n  sysctlbyname(\"hw.ncpu\", &cpuCount, &len, NULL, 0);\n  if( cpuCount>1 ){\n    /* defer MT decisions to system malloc */\n    _sqliteZone_ = malloc_default_zone();\n  }else{\n    /* only 1 core, use our own zone to contention over global locks, \n    ** e.g. we have our own dedicated locks */\n    _sqliteZone_ = malloc_create_zone(4096, 0);\n    malloc_set_zone_name(_sqliteZone_, \"Sqlite_Heap\");\n  }\n#endif /*  defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */\n  UNUSED_PARAMETER(NotUsed);\n  return SQLITE_OK;\n}\n\n/*\n** Deinitialize this module.\n*/\nstatic void sqlite3MemShutdown(void *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  return;\n}\n\n/*\n** This routine is the only routine in this file with external linkage.\n**\n** Populate the low-level memory allocation function pointers in\n** sqlite3GlobalConfig.m with pointers to the routines in this file.\n*/\nSQLITE_PRIVATE void sqlite3MemSetDefault(void){\n  static const sqlite3_mem_methods defaultMethods = {\n     sqlite3MemMalloc,\n     sqlite3MemFree,\n     sqlite3MemRealloc,\n     sqlite3MemSize,\n     sqlite3MemRoundup,\n     sqlite3MemInit,\n     sqlite3MemShutdown,\n     0\n  };\n  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);\n}\n\n#endif /* SQLITE_SYSTEM_MALLOC */\n\n/************** End of mem1.c ************************************************/\n/************** Begin file mem2.c ********************************************/\n/*\n** 2007 August 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains low-level memory allocation drivers for when\n** SQLite will use the standard C-library malloc/realloc/free interface\n** to obtain the memory it needs while adding lots of additional debugging\n** information to each allocation in order to help detect and fix memory\n** leaks and memory usage errors.\n**\n** This file contains implementations of the low-level memory allocation\n** routines specified in the sqlite3_mem_methods object.\n*/\n/* #include \"sqliteInt.h\" */\n\n/*\n** This version of the memory allocator is used only if the\n** SQLITE_MEMDEBUG macro is defined\n*/\n#ifdef SQLITE_MEMDEBUG\n\n/*\n** The backtrace functionality is only available with GLIBC\n*/\n#ifdef __GLIBC__\n  extern int backtrace(void**,int);\n  extern void backtrace_symbols_fd(void*const*,int,int);\n#else\n# define backtrace(A,B) 1\n# define backtrace_symbols_fd(A,B,C)\n#endif\n/* #include <stdio.h> */\n\n/*\n** Each memory allocation looks like this:\n**\n**  ------------------------------------------------------------------------\n**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |\n**  ------------------------------------------------------------------------\n**\n** The application code sees only a pointer to the allocation.  We have\n** to back up from the allocation pointer to find the MemBlockHdr.  The\n** MemBlockHdr tells us the size of the allocation and the number of\n** backtrace pointers.  There is also a guard word at the end of the\n** MemBlockHdr.\n*/\nstruct MemBlockHdr {\n  i64 iSize;                          /* Size of this allocation */\n  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */\n  char nBacktrace;                    /* Number of backtraces on this alloc */\n  char nBacktraceSlots;               /* Available backtrace slots */\n  u8 nTitle;                          /* Bytes of title; includes '\\0' */\n  u8 eType;                           /* Allocation type code */\n  int iForeGuard;                     /* Guard word for sanity */\n};\n\n/*\n** Guard words\n*/\n#define FOREGUARD 0x80F5E153\n#define REARGUARD 0xE4676B53\n\n/*\n** Number of malloc size increments to track.\n*/\n#define NCSIZE  1000\n\n/*\n** All of the static variables used by this module are collected\n** into a single structure named \"mem\".  This is to keep the\n** static variables organized and to reduce namespace pollution\n** when this module is combined with other in the amalgamation.\n*/\nstatic struct {\n  \n  /*\n  ** Mutex to control access to the memory allocation subsystem.\n  */\n  sqlite3_mutex *mutex;\n\n  /*\n  ** Head and tail of a linked list of all outstanding allocations\n  */\n  struct MemBlockHdr *pFirst;\n  struct MemBlockHdr *pLast;\n  \n  /*\n  ** The number of levels of backtrace to save in new allocations.\n  */\n  int nBacktrace;\n  void (*xBacktrace)(int, int, void **);\n\n  /*\n  ** Title text to insert in front of each block\n  */\n  int nTitle;        /* Bytes of zTitle to save.  Includes '\\0' and padding */\n  char zTitle[100];  /* The title text */\n\n  /* \n  ** sqlite3MallocDisallow() increments the following counter.\n  ** sqlite3MallocAllow() decrements it.\n  */\n  int disallow; /* Do not allow memory allocation */\n\n  /*\n  ** Gather statistics on the sizes of memory allocations.\n  ** nAlloc[i] is the number of allocation attempts of i*8\n  ** bytes.  i==NCSIZE is the number of allocation attempts for\n  ** sizes more than NCSIZE*8 bytes.\n  */\n  int nAlloc[NCSIZE];      /* Total number of allocations */\n  int nCurrent[NCSIZE];    /* Current number of allocations */\n  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */\n\n} mem;\n\n\n/*\n** Adjust memory usage statistics\n*/\nstatic void adjustStats(int iSize, int increment){\n  int i = ROUND8(iSize)/8;\n  if( i>NCSIZE-1 ){\n    i = NCSIZE - 1;\n  }\n  if( increment>0 ){\n    mem.nAlloc[i]++;\n    mem.nCurrent[i]++;\n    if( mem.nCurrent[i]>mem.mxCurrent[i] ){\n      mem.mxCurrent[i] = mem.nCurrent[i];\n    }\n  }else{\n    mem.nCurrent[i]--;\n    assert( mem.nCurrent[i]>=0 );\n  }\n}\n\n/*\n** Given an allocation, find the MemBlockHdr for that allocation.\n**\n** This routine checks the guards at either end of the allocation and\n** if they are incorrect it asserts.\n*/\nstatic struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){\n  struct MemBlockHdr *p;\n  int *pInt;\n  u8 *pU8;\n  int nReserve;\n\n  p = (struct MemBlockHdr*)pAllocation;\n  p--;\n  assert( p->iForeGuard==(int)FOREGUARD );\n  nReserve = ROUND8(p->iSize);\n  pInt = (int*)pAllocation;\n  pU8 = (u8*)pAllocation;\n  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );\n  /* This checks any of the \"extra\" bytes allocated due\n  ** to rounding up to an 8 byte boundary to ensure \n  ** they haven't been overwritten.\n  */\n  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );\n  return p;\n}\n\n/*\n** Return the number of bytes currently allocated at address p.\n*/\nstatic int sqlite3MemSize(void *p){\n  struct MemBlockHdr *pHdr;\n  if( !p ){\n    return 0;\n  }\n  pHdr = sqlite3MemsysGetHeader(p);\n  return (int)pHdr->iSize;\n}\n\n/*\n** Initialize the memory allocation subsystem.\n*/\nstatic int sqlite3MemInit(void *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  assert( (sizeof(struct MemBlockHdr)&7) == 0 );\n  if( !sqlite3GlobalConfig.bMemstat ){\n    /* If memory status is enabled, then the malloc.c wrapper will already\n    ** hold the STATIC_MEM mutex when the routines here are invoked. */\n    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Deinitialize the memory allocation subsystem.\n*/\nstatic void sqlite3MemShutdown(void *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  mem.mutex = 0;\n}\n\n/*\n** Round up a request size to the next valid allocation size.\n*/\nstatic int sqlite3MemRoundup(int n){\n  return ROUND8(n);\n}\n\n/*\n** Fill a buffer with pseudo-random bytes.  This is used to preset\n** the content of a new memory allocation to unpredictable values and\n** to clear the content of a freed allocation to unpredictable values.\n*/\nstatic void randomFill(char *pBuf, int nByte){\n  unsigned int x, y, r;\n  x = SQLITE_PTR_TO_INT(pBuf);\n  y = nByte | 1;\n  while( nByte >= 4 ){\n    x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);\n    y = y*1103515245 + 12345;\n    r = x ^ y;\n    *(int*)pBuf = r;\n    pBuf += 4;\n    nByte -= 4;\n  }\n  while( nByte-- > 0 ){\n    x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);\n    y = y*1103515245 + 12345;\n    r = x ^ y;\n    *(pBuf++) = r & 0xff;\n  }\n}\n\n/*\n** Allocate nByte bytes of memory.\n*/\nstatic void *sqlite3MemMalloc(int nByte){\n  struct MemBlockHdr *pHdr;\n  void **pBt;\n  char *z;\n  int *pInt;\n  void *p = 0;\n  int totalSize;\n  int nReserve;\n  sqlite3_mutex_enter(mem.mutex);\n  assert( mem.disallow==0 );\n  nReserve = ROUND8(nByte);\n  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +\n               mem.nBacktrace*sizeof(void*) + mem.nTitle;\n  p = malloc(totalSize);\n  if( p ){\n    z = p;\n    pBt = (void**)&z[mem.nTitle];\n    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];\n    pHdr->pNext = 0;\n    pHdr->pPrev = mem.pLast;\n    if( mem.pLast ){\n      mem.pLast->pNext = pHdr;\n    }else{\n      mem.pFirst = pHdr;\n    }\n    mem.pLast = pHdr;\n    pHdr->iForeGuard = FOREGUARD;\n    pHdr->eType = MEMTYPE_HEAP;\n    pHdr->nBacktraceSlots = mem.nBacktrace;\n    pHdr->nTitle = mem.nTitle;\n    if( mem.nBacktrace ){\n      void *aAddr[40];\n      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;\n      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));\n      assert(pBt[0]);\n      if( mem.xBacktrace ){\n        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);\n      }\n    }else{\n      pHdr->nBacktrace = 0;\n    }\n    if( mem.nTitle ){\n      memcpy(z, mem.zTitle, mem.nTitle);\n    }\n    pHdr->iSize = nByte;\n    adjustStats(nByte, +1);\n    pInt = (int*)&pHdr[1];\n    pInt[nReserve/sizeof(int)] = REARGUARD;\n    randomFill((char*)pInt, nByte);\n    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);\n    p = (void*)pInt;\n  }\n  sqlite3_mutex_leave(mem.mutex);\n  return p; \n}\n\n/*\n** Free memory.\n*/\nstatic void sqlite3MemFree(void *pPrior){\n  struct MemBlockHdr *pHdr;\n  void **pBt;\n  char *z;\n  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 \n       || mem.mutex!=0 );\n  pHdr = sqlite3MemsysGetHeader(pPrior);\n  pBt = (void**)pHdr;\n  pBt -= pHdr->nBacktraceSlots;\n  sqlite3_mutex_enter(mem.mutex);\n  if( pHdr->pPrev ){\n    assert( pHdr->pPrev->pNext==pHdr );\n    pHdr->pPrev->pNext = pHdr->pNext;\n  }else{\n    assert( mem.pFirst==pHdr );\n    mem.pFirst = pHdr->pNext;\n  }\n  if( pHdr->pNext ){\n    assert( pHdr->pNext->pPrev==pHdr );\n    pHdr->pNext->pPrev = pHdr->pPrev;\n  }else{\n    assert( mem.pLast==pHdr );\n    mem.pLast = pHdr->pPrev;\n  }\n  z = (char*)pBt;\n  z -= pHdr->nTitle;\n  adjustStats((int)pHdr->iSize, -1);\n  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +\n                (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);\n  free(z);\n  sqlite3_mutex_leave(mem.mutex);  \n}\n\n/*\n** Change the size of an existing memory allocation.\n**\n** For this debugging implementation, we *always* make a copy of the\n** allocation into a new place in memory.  In this way, if the \n** higher level code is using pointer to the old allocation, it is \n** much more likely to break and we are much more liking to find\n** the error.\n*/\nstatic void *sqlite3MemRealloc(void *pPrior, int nByte){\n  struct MemBlockHdr *pOldHdr;\n  void *pNew;\n  assert( mem.disallow==0 );\n  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */\n  pOldHdr = sqlite3MemsysGetHeader(pPrior);\n  pNew = sqlite3MemMalloc(nByte);\n  if( pNew ){\n    memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));\n    if( nByte>pOldHdr->iSize ){\n      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);\n    }\n    sqlite3MemFree(pPrior);\n  }\n  return pNew;\n}\n\n/*\n** Populate the low-level memory allocation function pointers in\n** sqlite3GlobalConfig.m with pointers to the routines in this file.\n*/\nSQLITE_PRIVATE void sqlite3MemSetDefault(void){\n  static const sqlite3_mem_methods defaultMethods = {\n     sqlite3MemMalloc,\n     sqlite3MemFree,\n     sqlite3MemRealloc,\n     sqlite3MemSize,\n     sqlite3MemRoundup,\n     sqlite3MemInit,\n     sqlite3MemShutdown,\n     0\n  };\n  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);\n}\n\n/*\n** Set the \"type\" of an allocation.\n*/\nSQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){\n  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){\n    struct MemBlockHdr *pHdr;\n    pHdr = sqlite3MemsysGetHeader(p);\n    assert( pHdr->iForeGuard==FOREGUARD );\n    pHdr->eType = eType;\n  }\n}\n\n/*\n** Return TRUE if the mask of type in eType matches the type of the\n** allocation p.  Also return true if p==NULL.\n**\n** This routine is designed for use within an assert() statement, to\n** verify the type of an allocation.  For example:\n**\n**     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );\n*/\nSQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){\n  int rc = 1;\n  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){\n    struct MemBlockHdr *pHdr;\n    pHdr = sqlite3MemsysGetHeader(p);\n    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */\n    if( (pHdr->eType&eType)==0 ){\n      rc = 0;\n    }\n  }\n  return rc;\n}\n\n/*\n** Return TRUE if the mask of type in eType matches no bits of the type of the\n** allocation p.  Also return true if p==NULL.\n**\n** This routine is designed for use within an assert() statement, to\n** verify the type of an allocation.  For example:\n**\n**     assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );\n*/\nSQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){\n  int rc = 1;\n  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){\n    struct MemBlockHdr *pHdr;\n    pHdr = sqlite3MemsysGetHeader(p);\n    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */\n    if( (pHdr->eType&eType)!=0 ){\n      rc = 0;\n    }\n  }\n  return rc;\n}\n\n/*\n** Set the number of backtrace levels kept for each allocation.\n** A value of zero turns off backtracing.  The number is always rounded\n** up to a multiple of 2.\n*/\nSQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){\n  if( depth<0 ){ depth = 0; }\n  if( depth>20 ){ depth = 20; }\n  depth = (depth+1)&0xfe;\n  mem.nBacktrace = depth;\n}\n\nSQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){\n  mem.xBacktrace = xBacktrace;\n}\n\n/*\n** Set the title string for subsequent allocations.\n*/\nSQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){\n  unsigned int n = sqlite3Strlen30(zTitle) + 1;\n  sqlite3_mutex_enter(mem.mutex);\n  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;\n  memcpy(mem.zTitle, zTitle, n);\n  mem.zTitle[n] = 0;\n  mem.nTitle = ROUND8(n);\n  sqlite3_mutex_leave(mem.mutex);\n}\n\nSQLITE_PRIVATE void sqlite3MemdebugSync(){\n  struct MemBlockHdr *pHdr;\n  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){\n    void **pBt = (void**)pHdr;\n    pBt -= pHdr->nBacktraceSlots;\n    mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);\n  }\n}\n\n/*\n** Open the file indicated and write a log of all unfreed memory \n** allocations into that log.\n*/\nSQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){\n  FILE *out;\n  struct MemBlockHdr *pHdr;\n  void **pBt;\n  int i;\n  out = fopen(zFilename, \"w\");\n  if( out==0 ){\n    fprintf(stderr, \"** Unable to output memory debug output log: %s **\\n\",\n                    zFilename);\n    return;\n  }\n  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){\n    char *z = (char*)pHdr;\n    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;\n    fprintf(out, \"**** %lld bytes at %p from %s ****\\n\", \n            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : \"???\");\n    if( pHdr->nBacktrace ){\n      fflush(out);\n      pBt = (void**)pHdr;\n      pBt -= pHdr->nBacktraceSlots;\n      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));\n      fprintf(out, \"\\n\");\n    }\n  }\n  fprintf(out, \"COUNTS:\\n\");\n  for(i=0; i<NCSIZE-1; i++){\n    if( mem.nAlloc[i] ){\n      fprintf(out, \"   %5d: %10d %10d %10d\\n\", \n            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);\n    }\n  }\n  if( mem.nAlloc[NCSIZE-1] ){\n    fprintf(out, \"   %5d: %10d %10d %10d\\n\",\n             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],\n             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);\n  }\n  fclose(out);\n}\n\n/*\n** Return the number of times sqlite3MemMalloc() has been called.\n*/\nSQLITE_PRIVATE int sqlite3MemdebugMallocCount(){\n  int i;\n  int nTotal = 0;\n  for(i=0; i<NCSIZE; i++){\n    nTotal += mem.nAlloc[i];\n  }\n  return nTotal;\n}\n\n\n#endif /* SQLITE_MEMDEBUG */\n\n/************** End of mem2.c ************************************************/\n/************** Begin file mem3.c ********************************************/\n/*\n** 2007 October 14\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the C functions that implement a memory\n** allocation subsystem for use by SQLite. \n**\n** This version of the memory allocation subsystem omits all\n** use of malloc(). The SQLite user supplies a block of memory\n** before calling sqlite3_initialize() from which allocations\n** are made and returned by the xMalloc() and xRealloc() \n** implementations. Once sqlite3_initialize() has been called,\n** the amount of memory available to SQLite is fixed and cannot\n** be changed.\n**\n** This version of the memory allocation subsystem is included\n** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.\n*/\n/* #include \"sqliteInt.h\" */\n\n/*\n** This version of the memory allocator is only built into the library\n** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not\n** mean that the library will use a memory-pool by default, just that\n** it is available. The mempool allocator is activated by calling\n** sqlite3_config().\n*/\n#ifdef SQLITE_ENABLE_MEMSYS3\n\n/*\n** Maximum size (in Mem3Blocks) of a \"small\" chunk.\n*/\n#define MX_SMALL 10\n\n\n/*\n** Number of freelist hash slots\n*/\n#define N_HASH  61\n\n/*\n** A memory allocation (also called a \"chunk\") consists of two or \n** more blocks where each block is 8 bytes.  The first 8 bytes are \n** a header that is not returned to the user.\n**\n** A chunk is two or more blocks that is either checked out or\n** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the\n** size of the allocation in blocks if the allocation is free.\n** The u.hdr.size4x&1 bit is true if the chunk is checked out and\n** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit\n** is true if the previous chunk is checked out and false if the\n** previous chunk is free.  The u.hdr.prevSize field is the size of\n** the previous chunk in blocks if the previous chunk is on the\n** freelist. If the previous chunk is checked out, then\n** u.hdr.prevSize can be part of the data for that chunk and should\n** not be read or written.\n**\n** We often identify a chunk by its index in mem3.aPool[].  When\n** this is done, the chunk index refers to the second block of\n** the chunk.  In this way, the first chunk has an index of 1.\n** A chunk index of 0 means \"no such chunk\" and is the equivalent\n** of a NULL pointer.\n**\n** The second block of free chunks is of the form u.list.  The\n** two fields form a double-linked list of chunks of related sizes.\n** Pointers to the head of the list are stored in mem3.aiSmall[] \n** for smaller chunks and mem3.aiHash[] for larger chunks.\n**\n** The second block of a chunk is user data if the chunk is checked \n** out.  If a chunk is checked out, the user data may extend into\n** the u.hdr.prevSize value of the following chunk.\n*/\ntypedef struct Mem3Block Mem3Block;\nstruct Mem3Block {\n  union {\n    struct {\n      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */\n      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */\n    } hdr;\n    struct {\n      u32 next;       /* Index in mem3.aPool[] of next free chunk */\n      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */\n    } list;\n  } u;\n};\n\n/*\n** All of the static variables used by this module are collected\n** into a single structure named \"mem3\".  This is to keep the\n** static variables organized and to reduce namespace pollution\n** when this module is combined with other in the amalgamation.\n*/\nstatic SQLITE_WSD struct Mem3Global {\n  /*\n  ** Memory available for allocation. nPool is the size of the array\n  ** (in Mem3Blocks) pointed to by aPool less 2.\n  */\n  u32 nPool;\n  Mem3Block *aPool;\n\n  /*\n  ** True if we are evaluating an out-of-memory callback.\n  */\n  int alarmBusy;\n  \n  /*\n  ** Mutex to control access to the memory allocation subsystem.\n  */\n  sqlite3_mutex *mutex;\n  \n  /*\n  ** The minimum amount of free space that we have seen.\n  */\n  u32 mnMaster;\n\n  /*\n  ** iMaster is the index of the master chunk.  Most new allocations\n  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)\n  ** of the current master.  iMaster is 0 if there is not master chunk.\n  ** The master chunk is not in either the aiHash[] or aiSmall[].\n  */\n  u32 iMaster;\n  u32 szMaster;\n\n  /*\n  ** Array of lists of free blocks according to the block size \n  ** for smaller chunks, or a hash on the block size for larger\n  ** chunks.\n  */\n  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */\n  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */\n} mem3 = { 97535575 };\n\n#define mem3 GLOBAL(struct Mem3Global, mem3)\n\n/*\n** Unlink the chunk at mem3.aPool[i] from list it is currently\n** on.  *pRoot is the list that i is a member of.\n*/\nstatic void memsys3UnlinkFromList(u32 i, u32 *pRoot){\n  u32 next = mem3.aPool[i].u.list.next;\n  u32 prev = mem3.aPool[i].u.list.prev;\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  if( prev==0 ){\n    *pRoot = next;\n  }else{\n    mem3.aPool[prev].u.list.next = next;\n  }\n  if( next ){\n    mem3.aPool[next].u.list.prev = prev;\n  }\n  mem3.aPool[i].u.list.next = 0;\n  mem3.aPool[i].u.list.prev = 0;\n}\n\n/*\n** Unlink the chunk at index i from \n** whatever list is currently a member of.\n*/\nstatic void memsys3Unlink(u32 i){\n  u32 size, hash;\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );\n  assert( i>=1 );\n  size = mem3.aPool[i-1].u.hdr.size4x/4;\n  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );\n  assert( size>=2 );\n  if( size <= MX_SMALL ){\n    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);\n  }else{\n    hash = size % N_HASH;\n    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);\n  }\n}\n\n/*\n** Link the chunk at mem3.aPool[i] so that is on the list rooted\n** at *pRoot.\n*/\nstatic void memsys3LinkIntoList(u32 i, u32 *pRoot){\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  mem3.aPool[i].u.list.next = *pRoot;\n  mem3.aPool[i].u.list.prev = 0;\n  if( *pRoot ){\n    mem3.aPool[*pRoot].u.list.prev = i;\n  }\n  *pRoot = i;\n}\n\n/*\n** Link the chunk at index i into either the appropriate\n** small chunk list, or into the large chunk hash table.\n*/\nstatic void memsys3Link(u32 i){\n  u32 size, hash;\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  assert( i>=1 );\n  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );\n  size = mem3.aPool[i-1].u.hdr.size4x/4;\n  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );\n  assert( size>=2 );\n  if( size <= MX_SMALL ){\n    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);\n  }else{\n    hash = size % N_HASH;\n    memsys3LinkIntoList(i, &mem3.aiHash[hash]);\n  }\n}\n\n/*\n** If the STATIC_MEM mutex is not already held, obtain it now. The mutex\n** will already be held (obtained by code in malloc.c) if\n** sqlite3GlobalConfig.bMemStat is true.\n*/\nstatic void memsys3Enter(void){\n  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){\n    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);\n  }\n  sqlite3_mutex_enter(mem3.mutex);\n}\nstatic void memsys3Leave(void){\n  sqlite3_mutex_leave(mem3.mutex);\n}\n\n/*\n** Called when we are unable to satisfy an allocation of nBytes.\n*/\nstatic void memsys3OutOfMemory(int nByte){\n  if( !mem3.alarmBusy ){\n    mem3.alarmBusy = 1;\n    assert( sqlite3_mutex_held(mem3.mutex) );\n    sqlite3_mutex_leave(mem3.mutex);\n    sqlite3_release_memory(nByte);\n    sqlite3_mutex_enter(mem3.mutex);\n    mem3.alarmBusy = 0;\n  }\n}\n\n\n/*\n** Chunk i is a free chunk that has been unlinked.  Adjust its \n** size parameters for check-out and return a pointer to the \n** user portion of the chunk.\n*/\nstatic void *memsys3Checkout(u32 i, u32 nBlock){\n  u32 x;\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  assert( i>=1 );\n  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );\n  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );\n  x = mem3.aPool[i-1].u.hdr.size4x;\n  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);\n  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;\n  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;\n  return &mem3.aPool[i];\n}\n\n/*\n** Carve a piece off of the end of the mem3.iMaster free chunk.\n** Return a pointer to the new allocation.  Or, if the master chunk\n** is not large enough, return 0.\n*/\nstatic void *memsys3FromMaster(u32 nBlock){\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  assert( mem3.szMaster>=nBlock );\n  if( nBlock>=mem3.szMaster-1 ){\n    /* Use the entire master */\n    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);\n    mem3.iMaster = 0;\n    mem3.szMaster = 0;\n    mem3.mnMaster = 0;\n    return p;\n  }else{\n    /* Split the master block.  Return the tail. */\n    u32 newi, x;\n    newi = mem3.iMaster + mem3.szMaster - nBlock;\n    assert( newi > mem3.iMaster+1 );\n    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;\n    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;\n    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;\n    mem3.szMaster -= nBlock;\n    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;\n    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;\n    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;\n    if( mem3.szMaster < mem3.mnMaster ){\n      mem3.mnMaster = mem3.szMaster;\n    }\n    return (void*)&mem3.aPool[newi];\n  }\n}\n\n/*\n** *pRoot is the head of a list of free chunks of the same size\n** or same size hash.  In other words, *pRoot is an entry in either\n** mem3.aiSmall[] or mem3.aiHash[].  \n**\n** This routine examines all entries on the given list and tries\n** to coalesce each entries with adjacent free chunks.  \n**\n** If it sees a chunk that is larger than mem3.iMaster, it replaces \n** the current mem3.iMaster with the new larger chunk.  In order for\n** this mem3.iMaster replacement to work, the master chunk must be\n** linked into the hash tables.  That is not the normal state of\n** affairs, of course.  The calling routine must link the master\n** chunk before invoking this routine, then must unlink the (possibly\n** changed) master chunk once this routine has finished.\n*/\nstatic void memsys3Merge(u32 *pRoot){\n  u32 iNext, prev, size, i, x;\n\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  for(i=*pRoot; i>0; i=iNext){\n    iNext = mem3.aPool[i].u.list.next;\n    size = mem3.aPool[i-1].u.hdr.size4x;\n    assert( (size&1)==0 );\n    if( (size&2)==0 ){\n      memsys3UnlinkFromList(i, pRoot);\n      assert( i > mem3.aPool[i-1].u.hdr.prevSize );\n      prev = i - mem3.aPool[i-1].u.hdr.prevSize;\n      if( prev==iNext ){\n        iNext = mem3.aPool[prev].u.list.next;\n      }\n      memsys3Unlink(prev);\n      size = i + size/4 - prev;\n      x = mem3.aPool[prev-1].u.hdr.size4x & 2;\n      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;\n      mem3.aPool[prev+size-1].u.hdr.prevSize = size;\n      memsys3Link(prev);\n      i = prev;\n    }else{\n      size /= 4;\n    }\n    if( size>mem3.szMaster ){\n      mem3.iMaster = i;\n      mem3.szMaster = size;\n    }\n  }\n}\n\n/*\n** Return a block of memory of at least nBytes in size.\n** Return NULL if unable.\n**\n** This function assumes that the necessary mutexes, if any, are\n** already held by the caller. Hence \"Unsafe\".\n*/\nstatic void *memsys3MallocUnsafe(int nByte){\n  u32 i;\n  u32 nBlock;\n  u32 toFree;\n\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  assert( sizeof(Mem3Block)==8 );\n  if( nByte<=12 ){\n    nBlock = 2;\n  }else{\n    nBlock = (nByte + 11)/8;\n  }\n  assert( nBlock>=2 );\n\n  /* STEP 1:\n  ** Look for an entry of the correct size in either the small\n  ** chunk table or in the large chunk hash table.  This is\n  ** successful most of the time (about 9 times out of 10).\n  */\n  if( nBlock <= MX_SMALL ){\n    i = mem3.aiSmall[nBlock-2];\n    if( i>0 ){\n      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);\n      return memsys3Checkout(i, nBlock);\n    }\n  }else{\n    int hash = nBlock % N_HASH;\n    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){\n      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){\n        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);\n        return memsys3Checkout(i, nBlock);\n      }\n    }\n  }\n\n  /* STEP 2:\n  ** Try to satisfy the allocation by carving a piece off of the end\n  ** of the master chunk.  This step usually works if step 1 fails.\n  */\n  if( mem3.szMaster>=nBlock ){\n    return memsys3FromMaster(nBlock);\n  }\n\n\n  /* STEP 3:  \n  ** Loop through the entire memory pool.  Coalesce adjacent free\n  ** chunks.  Recompute the master chunk as the largest free chunk.\n  ** Then try again to satisfy the allocation by carving a piece off\n  ** of the end of the master chunk.  This step happens very\n  ** rarely (we hope!)\n  */\n  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){\n    memsys3OutOfMemory(toFree);\n    if( mem3.iMaster ){\n      memsys3Link(mem3.iMaster);\n      mem3.iMaster = 0;\n      mem3.szMaster = 0;\n    }\n    for(i=0; i<N_HASH; i++){\n      memsys3Merge(&mem3.aiHash[i]);\n    }\n    for(i=0; i<MX_SMALL-1; i++){\n      memsys3Merge(&mem3.aiSmall[i]);\n    }\n    if( mem3.szMaster ){\n      memsys3Unlink(mem3.iMaster);\n      if( mem3.szMaster>=nBlock ){\n        return memsys3FromMaster(nBlock);\n      }\n    }\n  }\n\n  /* If none of the above worked, then we fail. */\n  return 0;\n}\n\n/*\n** Free an outstanding memory allocation.\n**\n** This function assumes that the necessary mutexes, if any, are\n** already held by the caller. Hence \"Unsafe\".\n*/\nstatic void memsys3FreeUnsafe(void *pOld){\n  Mem3Block *p = (Mem3Block*)pOld;\n  int i;\n  u32 size, x;\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );\n  i = p - mem3.aPool;\n  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );\n  size = mem3.aPool[i-1].u.hdr.size4x/4;\n  assert( i+size<=mem3.nPool+1 );\n  mem3.aPool[i-1].u.hdr.size4x &= ~1;\n  mem3.aPool[i+size-1].u.hdr.prevSize = size;\n  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;\n  memsys3Link(i);\n\n  /* Try to expand the master using the newly freed chunk */\n  if( mem3.iMaster ){\n    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){\n      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;\n      mem3.iMaster -= size;\n      mem3.szMaster += size;\n      memsys3Unlink(mem3.iMaster);\n      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;\n      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;\n      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;\n    }\n    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;\n    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){\n      memsys3Unlink(mem3.iMaster+mem3.szMaster);\n      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;\n      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;\n      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;\n    }\n  }\n}\n\n/*\n** Return the size of an outstanding allocation, in bytes.  The\n** size returned omits the 8-byte header overhead.  This only\n** works for chunks that are currently checked out.\n*/\nstatic int memsys3Size(void *p){\n  Mem3Block *pBlock;\n  assert( p!=0 );\n  pBlock = (Mem3Block*)p;\n  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );\n  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;\n}\n\n/*\n** Round up a request size to the next valid allocation size.\n*/\nstatic int memsys3Roundup(int n){\n  if( n<=12 ){\n    return 12;\n  }else{\n    return ((n+11)&~7) - 4;\n  }\n}\n\n/*\n** Allocate nBytes of memory.\n*/\nstatic void *memsys3Malloc(int nBytes){\n  sqlite3_int64 *p;\n  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */\n  memsys3Enter();\n  p = memsys3MallocUnsafe(nBytes);\n  memsys3Leave();\n  return (void*)p; \n}\n\n/*\n** Free memory.\n*/\nstatic void memsys3Free(void *pPrior){\n  assert( pPrior );\n  memsys3Enter();\n  memsys3FreeUnsafe(pPrior);\n  memsys3Leave();\n}\n\n/*\n** Change the size of an existing memory allocation\n*/\nstatic void *memsys3Realloc(void *pPrior, int nBytes){\n  int nOld;\n  void *p;\n  if( pPrior==0 ){\n    return sqlite3_malloc(nBytes);\n  }\n  if( nBytes<=0 ){\n    sqlite3_free(pPrior);\n    return 0;\n  }\n  nOld = memsys3Size(pPrior);\n  if( nBytes<=nOld && nBytes>=nOld-128 ){\n    return pPrior;\n  }\n  memsys3Enter();\n  p = memsys3MallocUnsafe(nBytes);\n  if( p ){\n    if( nOld<nBytes ){\n      memcpy(p, pPrior, nOld);\n    }else{\n      memcpy(p, pPrior, nBytes);\n    }\n    memsys3FreeUnsafe(pPrior);\n  }\n  memsys3Leave();\n  return p;\n}\n\n/*\n** Initialize this module.\n*/\nstatic int memsys3Init(void *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  if( !sqlite3GlobalConfig.pHeap ){\n    return SQLITE_ERROR;\n  }\n\n  /* Store a pointer to the memory block in global structure mem3. */\n  assert( sizeof(Mem3Block)==8 );\n  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;\n  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;\n\n  /* Initialize the master block. */\n  mem3.szMaster = mem3.nPool;\n  mem3.mnMaster = mem3.szMaster;\n  mem3.iMaster = 1;\n  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;\n  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;\n  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;\n\n  return SQLITE_OK;\n}\n\n/*\n** Deinitialize this module.\n*/\nstatic void memsys3Shutdown(void *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  mem3.mutex = 0;\n  return;\n}\n\n\n\n/*\n** Open the file indicated and write a log of all unfreed memory \n** allocations into that log.\n*/\nSQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){\n#ifdef SQLITE_DEBUG\n  FILE *out;\n  u32 i, j;\n  u32 size;\n  if( zFilename==0 || zFilename[0]==0 ){\n    out = stdout;\n  }else{\n    out = fopen(zFilename, \"w\");\n    if( out==0 ){\n      fprintf(stderr, \"** Unable to output memory debug output log: %s **\\n\",\n                      zFilename);\n      return;\n    }\n  }\n  memsys3Enter();\n  fprintf(out, \"CHUNKS:\\n\");\n  for(i=1; i<=mem3.nPool; i+=size/4){\n    size = mem3.aPool[i-1].u.hdr.size4x;\n    if( size/4<=1 ){\n      fprintf(out, \"%p size error\\n\", &mem3.aPool[i]);\n      assert( 0 );\n      break;\n    }\n    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){\n      fprintf(out, \"%p tail size does not match\\n\", &mem3.aPool[i]);\n      assert( 0 );\n      break;\n    }\n    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){\n      fprintf(out, \"%p tail checkout bit is incorrect\\n\", &mem3.aPool[i]);\n      assert( 0 );\n      break;\n    }\n    if( size&1 ){\n      fprintf(out, \"%p %6d bytes checked out\\n\", &mem3.aPool[i], (size/4)*8-8);\n    }else{\n      fprintf(out, \"%p %6d bytes free%s\\n\", &mem3.aPool[i], (size/4)*8-8,\n                  i==mem3.iMaster ? \" **master**\" : \"\");\n    }\n  }\n  for(i=0; i<MX_SMALL-1; i++){\n    if( mem3.aiSmall[i]==0 ) continue;\n    fprintf(out, \"small(%2d):\", i);\n    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){\n      fprintf(out, \" %p(%d)\", &mem3.aPool[j],\n              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);\n    }\n    fprintf(out, \"\\n\"); \n  }\n  for(i=0; i<N_HASH; i++){\n    if( mem3.aiHash[i]==0 ) continue;\n    fprintf(out, \"hash(%2d):\", i);\n    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){\n      fprintf(out, \" %p(%d)\", &mem3.aPool[j],\n              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);\n    }\n    fprintf(out, \"\\n\"); \n  }\n  fprintf(out, \"master=%d\\n\", mem3.iMaster);\n  fprintf(out, \"nowUsed=%d\\n\", mem3.nPool*8 - mem3.szMaster*8);\n  fprintf(out, \"mxUsed=%d\\n\", mem3.nPool*8 - mem3.mnMaster*8);\n  sqlite3_mutex_leave(mem3.mutex);\n  if( out==stdout ){\n    fflush(stdout);\n  }else{\n    fclose(out);\n  }\n#else\n  UNUSED_PARAMETER(zFilename);\n#endif\n}\n\n/*\n** This routine is the only routine in this file with external \n** linkage.\n**\n** Populate the low-level memory allocation function pointers in\n** sqlite3GlobalConfig.m with pointers to the routines in this file. The\n** arguments specify the block of memory to manage.\n**\n** This routine is only called by sqlite3_config(), and therefore\n** is not required to be threadsafe (it is not).\n*/\nSQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){\n  static const sqlite3_mem_methods mempoolMethods = {\n     memsys3Malloc,\n     memsys3Free,\n     memsys3Realloc,\n     memsys3Size,\n     memsys3Roundup,\n     memsys3Init,\n     memsys3Shutdown,\n     0\n  };\n  return &mempoolMethods;\n}\n\n#endif /* SQLITE_ENABLE_MEMSYS3 */\n\n/************** End of mem3.c ************************************************/\n/************** Begin file mem5.c ********************************************/\n/*\n** 2007 October 14\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the C functions that implement a memory\n** allocation subsystem for use by SQLite. \n**\n** This version of the memory allocation subsystem omits all\n** use of malloc(). The application gives SQLite a block of memory\n** before calling sqlite3_initialize() from which allocations\n** are made and returned by the xMalloc() and xRealloc() \n** implementations. Once sqlite3_initialize() has been called,\n** the amount of memory available to SQLite is fixed and cannot\n** be changed.\n**\n** This version of the memory allocation subsystem is included\n** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.\n**\n** This memory allocator uses the following algorithm:\n**\n**   1.  All memory allocation sizes are rounded up to a power of 2.\n**\n**   2.  If two adjacent free blocks are the halves of a larger block,\n**       then the two blocks are coalesced into the single larger block.\n**\n**   3.  New memory is allocated from the first available free block.\n**\n** This algorithm is described in: J. M. Robson. \"Bounds for Some Functions\n** Concerning Dynamic Storage Allocation\". Journal of the Association for\n** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.\n** \n** Let n be the size of the largest allocation divided by the minimum\n** allocation size (after rounding all sizes up to a power of 2.)  Let M\n** be the maximum amount of memory ever outstanding at one time.  Let\n** N be the total amount of memory available for allocation.  Robson\n** proved that this memory allocator will never breakdown due to \n** fragmentation as long as the following constraint holds:\n**\n**      N >=  M*(1 + log2(n)/2) - n + 1\n**\n** The sqlite3_status() logic tracks the maximum values of n and M so\n** that an application can, at any time, verify this constraint.\n*/\n/* #include \"sqliteInt.h\" */\n\n/*\n** This version of the memory allocator is used only when \n** SQLITE_ENABLE_MEMSYS5 is defined.\n*/\n#ifdef SQLITE_ENABLE_MEMSYS5\n\n/*\n** A minimum allocation is an instance of the following structure.\n** Larger allocations are an array of these structures where the\n** size of the array is a power of 2.\n**\n** The size of this object must be a power of two.  That fact is\n** verified in memsys5Init().\n*/\ntypedef struct Mem5Link Mem5Link;\nstruct Mem5Link {\n  int next;       /* Index of next free chunk */\n  int prev;       /* Index of previous free chunk */\n};\n\n/*\n** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since\n** mem5.szAtom is always at least 8 and 32-bit integers are used,\n** it is not actually possible to reach this limit.\n*/\n#define LOGMAX 30\n\n/*\n** Masks used for mem5.aCtrl[] elements.\n*/\n#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */\n#define CTRL_FREE     0x20    /* True if not checked out */\n\n/*\n** All of the static variables used by this module are collected\n** into a single structure named \"mem5\".  This is to keep the\n** static variables organized and to reduce namespace pollution\n** when this module is combined with other in the amalgamation.\n*/\nstatic SQLITE_WSD struct Mem5Global {\n  /*\n  ** Memory available for allocation\n  */\n  int szAtom;      /* Smallest possible allocation in bytes */\n  int nBlock;      /* Number of szAtom sized blocks in zPool */\n  u8 *zPool;       /* Memory available to be allocated */\n  \n  /*\n  ** Mutex to control access to the memory allocation subsystem.\n  */\n  sqlite3_mutex *mutex;\n\n#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)\n  /*\n  ** Performance statistics\n  */\n  u64 nAlloc;         /* Total number of calls to malloc */\n  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */\n  u64 totalExcess;    /* Total internal fragmentation */\n  u32 currentOut;     /* Current checkout, including internal fragmentation */\n  u32 currentCount;   /* Current number of distinct checkouts */\n  u32 maxOut;         /* Maximum instantaneous currentOut */\n  u32 maxCount;       /* Maximum instantaneous currentCount */\n  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */\n#endif\n  \n  /*\n  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of\n  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.\n  ** aiFreelist[2] holds free blocks of size szAtom*4.  And so forth.\n  */\n  int aiFreelist[LOGMAX+1];\n\n  /*\n  ** Space for tracking which blocks are checked out and the size\n  ** of each block.  One byte per block.\n  */\n  u8 *aCtrl;\n\n} mem5;\n\n/*\n** Access the static variable through a macro for SQLITE_OMIT_WSD.\n*/\n#define mem5 GLOBAL(struct Mem5Global, mem5)\n\n/*\n** Assuming mem5.zPool is divided up into an array of Mem5Link\n** structures, return a pointer to the idx-th such link.\n*/\n#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))\n\n/*\n** Unlink the chunk at mem5.aPool[i] from list it is currently\n** on.  It should be found on mem5.aiFreelist[iLogsize].\n*/\nstatic void memsys5Unlink(int i, int iLogsize){\n  int next, prev;\n  assert( i>=0 && i<mem5.nBlock );\n  assert( iLogsize>=0 && iLogsize<=LOGMAX );\n  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );\n\n  next = MEM5LINK(i)->next;\n  prev = MEM5LINK(i)->prev;\n  if( prev<0 ){\n    mem5.aiFreelist[iLogsize] = next;\n  }else{\n    MEM5LINK(prev)->next = next;\n  }\n  if( next>=0 ){\n    MEM5LINK(next)->prev = prev;\n  }\n}\n\n/*\n** Link the chunk at mem5.aPool[i] so that is on the iLogsize\n** free list.\n*/\nstatic void memsys5Link(int i, int iLogsize){\n  int x;\n  assert( sqlite3_mutex_held(mem5.mutex) );\n  assert( i>=0 && i<mem5.nBlock );\n  assert( iLogsize>=0 && iLogsize<=LOGMAX );\n  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );\n\n  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];\n  MEM5LINK(i)->prev = -1;\n  if( x>=0 ){\n    assert( x<mem5.nBlock );\n    MEM5LINK(x)->prev = i;\n  }\n  mem5.aiFreelist[iLogsize] = i;\n}\n\n/*\n** Obtain or release the mutex needed to access global data structures.\n*/\nstatic void memsys5Enter(void){\n  sqlite3_mutex_enter(mem5.mutex);\n}\nstatic void memsys5Leave(void){\n  sqlite3_mutex_leave(mem5.mutex);\n}\n\n/*\n** Return the size of an outstanding allocation, in bytes.\n** This only works for chunks that are currently checked out.\n*/\nstatic int memsys5Size(void *p){\n  int iSize, i;\n  assert( p!=0 );\n  i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);\n  assert( i>=0 && i<mem5.nBlock );\n  iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));\n  return iSize;\n}\n\n/*\n** Return a block of memory of at least nBytes in size.\n** Return NULL if unable.  Return NULL if nBytes==0.\n**\n** The caller guarantees that nByte is positive.\n**\n** The caller has obtained a mutex prior to invoking this\n** routine so there is never any chance that two or more\n** threads can be in this routine at the same time.\n*/\nstatic void *memsys5MallocUnsafe(int nByte){\n  int i;           /* Index of a mem5.aPool[] slot */\n  int iBin;        /* Index into mem5.aiFreelist[] */\n  int iFullSz;     /* Size of allocation rounded up to power of 2 */\n  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */\n\n  /* nByte must be a positive */\n  assert( nByte>0 );\n\n  /* No more than 1GiB per allocation */\n  if( nByte > 0x40000000 ) return 0;\n\n#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)\n  /* Keep track of the maximum allocation request.  Even unfulfilled\n  ** requests are counted */\n  if( (u32)nByte>mem5.maxRequest ){\n    mem5.maxRequest = nByte;\n  }\n#endif\n\n\n  /* Round nByte up to the next valid power of two */\n  for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}\n\n  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free\n  ** block.  If not, then split a block of the next larger power of\n  ** two in order to create a new free block of size iLogsize.\n  */\n  for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}\n  if( iBin>LOGMAX ){\n    testcase( sqlite3GlobalConfig.xLog!=0 );\n    sqlite3_log(SQLITE_NOMEM, \"failed to allocate %u bytes\", nByte);\n    return 0;\n  }\n  i = mem5.aiFreelist[iBin];\n  memsys5Unlink(i, iBin);\n  while( iBin>iLogsize ){\n    int newSize;\n\n    iBin--;\n    newSize = 1 << iBin;\n    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;\n    memsys5Link(i+newSize, iBin);\n  }\n  mem5.aCtrl[i] = iLogsize;\n\n#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)\n  /* Update allocator performance statistics. */\n  mem5.nAlloc++;\n  mem5.totalAlloc += iFullSz;\n  mem5.totalExcess += iFullSz - nByte;\n  mem5.currentCount++;\n  mem5.currentOut += iFullSz;\n  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;\n  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;\n#endif\n\n#ifdef SQLITE_DEBUG\n  /* Make sure the allocated memory does not assume that it is set to zero\n  ** or retains a value from a previous allocation */\n  memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);\n#endif\n\n  /* Return a pointer to the allocated memory. */\n  return (void*)&mem5.zPool[i*mem5.szAtom];\n}\n\n/*\n** Free an outstanding memory allocation.\n*/\nstatic void memsys5FreeUnsafe(void *pOld){\n  u32 size, iLogsize;\n  int iBlock;\n\n  /* Set iBlock to the index of the block pointed to by pOld in \n  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.\n  */\n  iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);\n\n  /* Check that the pointer pOld points to a valid, non-free block. */\n  assert( iBlock>=0 && iBlock<mem5.nBlock );\n  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );\n  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );\n\n  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;\n  size = 1<<iLogsize;\n  assert( iBlock+size-1<(u32)mem5.nBlock );\n\n  mem5.aCtrl[iBlock] |= CTRL_FREE;\n  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;\n\n#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)\n  assert( mem5.currentCount>0 );\n  assert( mem5.currentOut>=(size*mem5.szAtom) );\n  mem5.currentCount--;\n  mem5.currentOut -= size*mem5.szAtom;\n  assert( mem5.currentOut>0 || mem5.currentCount==0 );\n  assert( mem5.currentCount>0 || mem5.currentOut==0 );\n#endif\n\n  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;\n  while( ALWAYS(iLogsize<LOGMAX) ){\n    int iBuddy;\n    if( (iBlock>>iLogsize) & 1 ){\n      iBuddy = iBlock - size;\n      assert( iBuddy>=0 );\n    }else{\n      iBuddy = iBlock + size;\n      if( iBuddy>=mem5.nBlock ) break;\n    }\n    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;\n    memsys5Unlink(iBuddy, iLogsize);\n    iLogsize++;\n    if( iBuddy<iBlock ){\n      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;\n      mem5.aCtrl[iBlock] = 0;\n      iBlock = iBuddy;\n    }else{\n      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;\n      mem5.aCtrl[iBuddy] = 0;\n    }\n    size *= 2;\n  }\n\n#ifdef SQLITE_DEBUG\n  /* Overwrite freed memory with the 0x55 bit pattern to verify that it is\n  ** not used after being freed */\n  memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);\n#endif\n\n  memsys5Link(iBlock, iLogsize);\n}\n\n/*\n** Allocate nBytes of memory.\n*/\nstatic void *memsys5Malloc(int nBytes){\n  sqlite3_int64 *p = 0;\n  if( nBytes>0 ){\n    memsys5Enter();\n    p = memsys5MallocUnsafe(nBytes);\n    memsys5Leave();\n  }\n  return (void*)p; \n}\n\n/*\n** Free memory.\n**\n** The outer layer memory allocator prevents this routine from\n** being called with pPrior==0.\n*/\nstatic void memsys5Free(void *pPrior){\n  assert( pPrior!=0 );\n  memsys5Enter();\n  memsys5FreeUnsafe(pPrior);\n  memsys5Leave();  \n}\n\n/*\n** Change the size of an existing memory allocation.\n**\n** The outer layer memory allocator prevents this routine from\n** being called with pPrior==0.  \n**\n** nBytes is always a value obtained from a prior call to\n** memsys5Round().  Hence nBytes is always a non-negative power\n** of two.  If nBytes==0 that means that an oversize allocation\n** (an allocation larger than 0x40000000) was requested and this\n** routine should return 0 without freeing pPrior.\n*/\nstatic void *memsys5Realloc(void *pPrior, int nBytes){\n  int nOld;\n  void *p;\n  assert( pPrior!=0 );\n  assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */\n  assert( nBytes>=0 );\n  if( nBytes==0 ){\n    return 0;\n  }\n  nOld = memsys5Size(pPrior);\n  if( nBytes<=nOld ){\n    return pPrior;\n  }\n  p = memsys5Malloc(nBytes);\n  if( p ){\n    memcpy(p, pPrior, nOld);\n    memsys5Free(pPrior);\n  }\n  return p;\n}\n\n/*\n** Round up a request size to the next valid allocation size.  If\n** the allocation is too large to be handled by this allocation system,\n** return 0.\n**\n** All allocations must be a power of two and must be expressed by a\n** 32-bit signed integer.  Hence the largest allocation is 0x40000000\n** or 1073741824 bytes.\n*/\nstatic int memsys5Roundup(int n){\n  int iFullSz;\n  if( n > 0x40000000 ) return 0;\n  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);\n  return iFullSz;\n}\n\n/*\n** Return the ceiling of the logarithm base 2 of iValue.\n**\n** Examples:   memsys5Log(1) -> 0\n**             memsys5Log(2) -> 1\n**             memsys5Log(4) -> 2\n**             memsys5Log(5) -> 3\n**             memsys5Log(8) -> 3\n**             memsys5Log(9) -> 4\n*/\nstatic int memsys5Log(int iValue){\n  int iLog;\n  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);\n  return iLog;\n}\n\n/*\n** Initialize the memory allocator.\n**\n** This routine is not threadsafe.  The caller must be holding a mutex\n** to prevent multiple threads from entering at the same time.\n*/\nstatic int memsys5Init(void *NotUsed){\n  int ii;            /* Loop counter */\n  int nByte;         /* Number of bytes of memory available to this allocator */\n  u8 *zByte;         /* Memory usable by this allocator */\n  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */\n  int iOffset;       /* An offset into mem5.aCtrl[] */\n\n  UNUSED_PARAMETER(NotUsed);\n\n  /* For the purposes of this routine, disable the mutex */\n  mem5.mutex = 0;\n\n  /* The size of a Mem5Link object must be a power of two.  Verify that\n  ** this is case.\n  */\n  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );\n\n  nByte = sqlite3GlobalConfig.nHeap;\n  zByte = (u8*)sqlite3GlobalConfig.pHeap;\n  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */\n\n  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */\n  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);\n  mem5.szAtom = (1<<nMinLog);\n  while( (int)sizeof(Mem5Link)>mem5.szAtom ){\n    mem5.szAtom = mem5.szAtom << 1;\n  }\n\n  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));\n  mem5.zPool = zByte;\n  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];\n\n  for(ii=0; ii<=LOGMAX; ii++){\n    mem5.aiFreelist[ii] = -1;\n  }\n\n  iOffset = 0;\n  for(ii=LOGMAX; ii>=0; ii--){\n    int nAlloc = (1<<ii);\n    if( (iOffset+nAlloc)<=mem5.nBlock ){\n      mem5.aCtrl[iOffset] = ii | CTRL_FREE;\n      memsys5Link(iOffset, ii);\n      iOffset += nAlloc;\n    }\n    assert((iOffset+nAlloc)>mem5.nBlock);\n  }\n\n  /* If a mutex is required for normal operation, allocate one */\n  if( sqlite3GlobalConfig.bMemstat==0 ){\n    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Deinitialize this module.\n*/\nstatic void memsys5Shutdown(void *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  mem5.mutex = 0;\n  return;\n}\n\n#ifdef SQLITE_TEST\n/*\n** Open the file indicated and write a log of all unfreed memory \n** allocations into that log.\n*/\nSQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){\n  FILE *out;\n  int i, j, n;\n  int nMinLog;\n\n  if( zFilename==0 || zFilename[0]==0 ){\n    out = stdout;\n  }else{\n    out = fopen(zFilename, \"w\");\n    if( out==0 ){\n      fprintf(stderr, \"** Unable to output memory debug output log: %s **\\n\",\n                      zFilename);\n      return;\n    }\n  }\n  memsys5Enter();\n  nMinLog = memsys5Log(mem5.szAtom);\n  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){\n    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}\n    fprintf(out, \"freelist items of size %d: %d\\n\", mem5.szAtom << i, n);\n  }\n  fprintf(out, \"mem5.nAlloc       = %llu\\n\", mem5.nAlloc);\n  fprintf(out, \"mem5.totalAlloc   = %llu\\n\", mem5.totalAlloc);\n  fprintf(out, \"mem5.totalExcess  = %llu\\n\", mem5.totalExcess);\n  fprintf(out, \"mem5.currentOut   = %u\\n\", mem5.currentOut);\n  fprintf(out, \"mem5.currentCount = %u\\n\", mem5.currentCount);\n  fprintf(out, \"mem5.maxOut       = %u\\n\", mem5.maxOut);\n  fprintf(out, \"mem5.maxCount     = %u\\n\", mem5.maxCount);\n  fprintf(out, \"mem5.maxRequest   = %u\\n\", mem5.maxRequest);\n  memsys5Leave();\n  if( out==stdout ){\n    fflush(stdout);\n  }else{\n    fclose(out);\n  }\n}\n#endif\n\n/*\n** This routine is the only routine in this file with external \n** linkage. It returns a pointer to a static sqlite3_mem_methods\n** struct populated with the memsys5 methods.\n*/\nSQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){\n  static const sqlite3_mem_methods memsys5Methods = {\n     memsys5Malloc,\n     memsys5Free,\n     memsys5Realloc,\n     memsys5Size,\n     memsys5Roundup,\n     memsys5Init,\n     memsys5Shutdown,\n     0\n  };\n  return &memsys5Methods;\n}\n\n#endif /* SQLITE_ENABLE_MEMSYS5 */\n\n/************** End of mem5.c ************************************************/\n/************** Begin file mutex.c *******************************************/\n/*\n** 2007 August 14\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the C functions that implement mutexes.\n**\n** This file contains code that is common across all mutex implementations.\n*/\n/* #include \"sqliteInt.h\" */\n\n#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)\n/*\n** For debugging purposes, record when the mutex subsystem is initialized\n** and uninitialized so that we can assert() if there is an attempt to\n** allocate a mutex while the system is uninitialized.\n*/\nstatic SQLITE_WSD int mutexIsInit = 0;\n#endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */\n\n\n#ifndef SQLITE_MUTEX_OMIT\n\n#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS\n/*\n** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains\n** the implementation of a wrapper around the system default mutex\n** implementation (sqlite3DefaultMutex()). \n**\n** Most calls are passed directly through to the underlying default\n** mutex implementation. Except, if a mutex is configured by calling\n** sqlite3MutexWarnOnContention() on it, then if contention is ever\n** encountered within xMutexEnter() a warning is emitted via sqlite3_log().\n**\n** This type of mutex is used as the database handle mutex when testing\n** apps that usually use SQLITE_CONFIG_MULTITHREAD mode.\n*/\n\n/* \n** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS\n** is defined. Variable CheckMutex.mutex is a pointer to the real mutex\n** allocated by the system mutex implementation. Variable iType is usually set\n** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST\n** or one of the static mutex identifiers. Or, if this is a recursive mutex\n** that has been configured using sqlite3MutexWarnOnContention(), it is\n** set to SQLITE_MUTEX_WARNONCONTENTION.\n*/\ntypedef struct CheckMutex CheckMutex;\nstruct CheckMutex {\n  int iType;\n  sqlite3_mutex *mutex;\n};\n\n#define SQLITE_MUTEX_WARNONCONTENTION  (-1)\n\n/* \n** Pointer to real mutex methods object used by the CheckMutex\n** implementation. Set by checkMutexInit(). \n*/\nstatic SQLITE_WSD const sqlite3_mutex_methods *pGlobalMutexMethods;\n\n#ifdef SQLITE_DEBUG\nstatic int checkMutexHeld(sqlite3_mutex *p){\n  return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex);\n}\nstatic int checkMutexNotheld(sqlite3_mutex *p){\n  return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex);\n}\n#endif\n\n/*\n** Initialize and deinitialize the mutex subsystem.\n*/\nstatic int checkMutexInit(void){ \n  pGlobalMutexMethods = sqlite3DefaultMutex();\n  return SQLITE_OK; \n}\nstatic int checkMutexEnd(void){ \n  pGlobalMutexMethods = 0;\n  return SQLITE_OK; \n}\n\n/*\n** Allocate a mutex.\n*/\nstatic sqlite3_mutex *checkMutexAlloc(int iType){\n  static CheckMutex staticMutexes[] = {\n    {2, 0}, {3, 0}, {4, 0}, {5, 0},\n    {6, 0}, {7, 0}, {8, 0}, {9, 0},\n    {10, 0}, {11, 0}, {12, 0}, {13, 0}\n  };\n  CheckMutex *p = 0;\n\n  assert( SQLITE_MUTEX_RECURSIVE==1 && SQLITE_MUTEX_FAST==0 );\n  if( iType<2 ){\n    p = sqlite3MallocZero(sizeof(CheckMutex));\n    if( p==0 ) return 0;\n    p->iType = iType;\n  }else{\n#ifdef SQLITE_ENABLE_API_ARMOR\n    if( iType-2>=ArraySize(staticMutexes) ){\n      (void)SQLITE_MISUSE_BKPT;\n      return 0;\n    }\n#endif\n    p = &staticMutexes[iType-2];\n  }\n\n  if( p->mutex==0 ){\n    p->mutex = pGlobalMutexMethods->xMutexAlloc(iType);\n    if( p->mutex==0 ){\n      if( iType<2 ){\n        sqlite3_free(p);\n      }\n      p = 0;\n    }\n  }\n\n  return (sqlite3_mutex*)p;\n}\n\n/*\n** Free a mutex.\n*/\nstatic void checkMutexFree(sqlite3_mutex *p){\n  assert( SQLITE_MUTEX_RECURSIVE<2 );\n  assert( SQLITE_MUTEX_FAST<2 );\n  assert( SQLITE_MUTEX_WARNONCONTENTION<2 );\n\n#if SQLITE_ENABLE_API_ARMOR\n  if( ((CheckMutex*)p)->iType<2 )\n#endif\n  {\n    CheckMutex *pCheck = (CheckMutex*)p;\n    pGlobalMutexMethods->xMutexFree(pCheck->mutex);\n    sqlite3_free(pCheck);\n  }\n#ifdef SQLITE_ENABLE_API_ARMOR\n  else{\n    (void)SQLITE_MISUSE_BKPT;\n  }\n#endif\n}\n\n/*\n** Enter the mutex.\n*/\nstatic void checkMutexEnter(sqlite3_mutex *p){\n  CheckMutex *pCheck = (CheckMutex*)p;\n  if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){\n    if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){\n      return;\n    }\n    sqlite3_log(SQLITE_MISUSE, \n        \"illegal multi-threaded access to database connection\"\n    );\n  }\n  pGlobalMutexMethods->xMutexEnter(pCheck->mutex);\n}\n\n/*\n** Enter the mutex (do not block).\n*/\nstatic int checkMutexTry(sqlite3_mutex *p){\n  CheckMutex *pCheck = (CheckMutex*)p;\n  return pGlobalMutexMethods->xMutexTry(pCheck->mutex);\n}\n\n/*\n** Leave the mutex.\n*/\nstatic void checkMutexLeave(sqlite3_mutex *p){\n  CheckMutex *pCheck = (CheckMutex*)p;\n  pGlobalMutexMethods->xMutexLeave(pCheck->mutex);\n}\n\nsqlite3_mutex_methods const *multiThreadedCheckMutex(void){\n  static const sqlite3_mutex_methods sMutex = {\n    checkMutexInit,\n    checkMutexEnd,\n    checkMutexAlloc,\n    checkMutexFree,\n    checkMutexEnter,\n    checkMutexTry,\n    checkMutexLeave,\n#ifdef SQLITE_DEBUG\n    checkMutexHeld,\n    checkMutexNotheld\n#else\n    0,\n    0\n#endif\n  };\n  return &sMutex;\n}\n\n/*\n** Mark the SQLITE_MUTEX_RECURSIVE mutex passed as the only argument as\n** one on which there should be no contention.\n*/\nSQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex *p){\n  if( sqlite3GlobalConfig.mutex.xMutexAlloc==checkMutexAlloc ){\n    CheckMutex *pCheck = (CheckMutex*)p;\n    assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE );\n    pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION;\n  }\n}\n#endif   /* ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS */\n\n/*\n** Initialize the mutex system.\n*/\nSQLITE_PRIVATE int sqlite3MutexInit(void){ \n  int rc = SQLITE_OK;\n  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){\n    /* If the xMutexAlloc method has not been set, then the user did not\n    ** install a mutex implementation via sqlite3_config() prior to \n    ** sqlite3_initialize() being called. This block copies pointers to\n    ** the default implementation into the sqlite3GlobalConfig structure.\n    */\n    sqlite3_mutex_methods const *pFrom;\n    sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;\n\n    if( sqlite3GlobalConfig.bCoreMutex ){\n#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS\n      pFrom = multiThreadedCheckMutex();\n#else\n      pFrom = sqlite3DefaultMutex();\n#endif\n    }else{\n      pFrom = sqlite3NoopMutex();\n    }\n    pTo->xMutexInit = pFrom->xMutexInit;\n    pTo->xMutexEnd = pFrom->xMutexEnd;\n    pTo->xMutexFree = pFrom->xMutexFree;\n    pTo->xMutexEnter = pFrom->xMutexEnter;\n    pTo->xMutexTry = pFrom->xMutexTry;\n    pTo->xMutexLeave = pFrom->xMutexLeave;\n    pTo->xMutexHeld = pFrom->xMutexHeld;\n    pTo->xMutexNotheld = pFrom->xMutexNotheld;\n    sqlite3MemoryBarrier();\n    pTo->xMutexAlloc = pFrom->xMutexAlloc;\n  }\n  assert( sqlite3GlobalConfig.mutex.xMutexInit );\n  rc = sqlite3GlobalConfig.mutex.xMutexInit();\n\n#ifdef SQLITE_DEBUG\n  GLOBAL(int, mutexIsInit) = 1;\n#endif\n\n  sqlite3MemoryBarrier();\n  return rc;\n}\n\n/*\n** Shutdown the mutex system. This call frees resources allocated by\n** sqlite3MutexInit().\n*/\nSQLITE_PRIVATE int sqlite3MutexEnd(void){\n  int rc = SQLITE_OK;\n  if( sqlite3GlobalConfig.mutex.xMutexEnd ){\n    rc = sqlite3GlobalConfig.mutex.xMutexEnd();\n  }\n\n#ifdef SQLITE_DEBUG\n  GLOBAL(int, mutexIsInit) = 0;\n#endif\n\n  return rc;\n}\n\n/*\n** Retrieve a pointer to a static mutex or allocate a new dynamic one.\n*/\nSQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;\n  if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;\n#endif\n  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );\n  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);\n}\n\nSQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){\n  if( !sqlite3GlobalConfig.bCoreMutex ){\n    return 0;\n  }\n  assert( GLOBAL(int, mutexIsInit) );\n  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );\n  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);\n}\n\n/*\n** Free a dynamic mutex.\n*/\nSQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){\n  if( p ){\n    assert( sqlite3GlobalConfig.mutex.xMutexFree );\n    sqlite3GlobalConfig.mutex.xMutexFree(p);\n  }\n}\n\n/*\n** Obtain the mutex p. If some other thread already has the mutex, block\n** until it can be obtained.\n*/\nSQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){\n  if( p ){\n    assert( sqlite3GlobalConfig.mutex.xMutexEnter );\n    sqlite3GlobalConfig.mutex.xMutexEnter(p);\n  }\n}\n\n/*\n** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another\n** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.\n*/\nSQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){\n  int rc = SQLITE_OK;\n  if( p ){\n    assert( sqlite3GlobalConfig.mutex.xMutexTry );\n    return sqlite3GlobalConfig.mutex.xMutexTry(p);\n  }\n  return rc;\n}\n\n/*\n** The sqlite3_mutex_leave() routine exits a mutex that was previously\n** entered by the same thread.  The behavior is undefined if the mutex \n** is not currently entered. If a NULL pointer is passed as an argument\n** this function is a no-op.\n*/\nSQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){\n  if( p ){\n    assert( sqlite3GlobalConfig.mutex.xMutexLeave );\n    sqlite3GlobalConfig.mutex.xMutexLeave(p);\n  }\n}\n\n#ifndef NDEBUG\n/*\n** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are\n** intended for use inside assert() statements.\n*/\nSQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){\n  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );\n  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);\n}\nSQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){\n  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );\n  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);\n}\n#endif\n\n#endif /* !defined(SQLITE_MUTEX_OMIT) */\n\n/************** End of mutex.c ***********************************************/\n/************** Begin file mutex_noop.c **************************************/\n/*\n** 2008 October 07\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the C functions that implement mutexes.\n**\n** This implementation in this file does not provide any mutual\n** exclusion and is thus suitable for use only in applications\n** that use SQLite in a single thread.  The routines defined\n** here are place-holders.  Applications can substitute working\n** mutex routines at start-time using the\n**\n**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)\n**\n** interface.\n**\n** If compiled with SQLITE_DEBUG, then additional logic is inserted\n** that does error checking on mutexes to make sure they are being\n** called correctly.\n*/\n/* #include \"sqliteInt.h\" */\n\n#ifndef SQLITE_MUTEX_OMIT\n\n#ifndef SQLITE_DEBUG\n/*\n** Stub routines for all mutex methods.\n**\n** This routines provide no mutual exclusion or error checking.\n*/\nstatic int noopMutexInit(void){ return SQLITE_OK; }\nstatic int noopMutexEnd(void){ return SQLITE_OK; }\nstatic sqlite3_mutex *noopMutexAlloc(int id){ \n  UNUSED_PARAMETER(id);\n  return (sqlite3_mutex*)8; \n}\nstatic void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }\nstatic void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }\nstatic int noopMutexTry(sqlite3_mutex *p){\n  UNUSED_PARAMETER(p);\n  return SQLITE_OK;\n}\nstatic void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }\n\nSQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){\n  static const sqlite3_mutex_methods sMutex = {\n    noopMutexInit,\n    noopMutexEnd,\n    noopMutexAlloc,\n    noopMutexFree,\n    noopMutexEnter,\n    noopMutexTry,\n    noopMutexLeave,\n\n    0,\n    0,\n  };\n\n  return &sMutex;\n}\n#endif /* !SQLITE_DEBUG */\n\n#ifdef SQLITE_DEBUG\n/*\n** In this implementation, error checking is provided for testing\n** and debugging purposes.  The mutexes still do not provide any\n** mutual exclusion.\n*/\n\n/*\n** The mutex object\n*/\ntypedef struct sqlite3_debug_mutex {\n  int id;     /* The mutex type */\n  int cnt;    /* Number of entries without a matching leave */\n} sqlite3_debug_mutex;\n\n/*\n** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are\n** intended for use inside assert() statements.\n*/\nstatic int debugMutexHeld(sqlite3_mutex *pX){\n  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;\n  return p==0 || p->cnt>0;\n}\nstatic int debugMutexNotheld(sqlite3_mutex *pX){\n  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;\n  return p==0 || p->cnt==0;\n}\n\n/*\n** Initialize and deinitialize the mutex subsystem.\n*/\nstatic int debugMutexInit(void){ return SQLITE_OK; }\nstatic int debugMutexEnd(void){ return SQLITE_OK; }\n\n/*\n** The sqlite3_mutex_alloc() routine allocates a new\n** mutex and returns a pointer to it.  If it returns NULL\n** that means that a mutex could not be allocated. \n*/\nstatic sqlite3_mutex *debugMutexAlloc(int id){\n  static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];\n  sqlite3_debug_mutex *pNew = 0;\n  switch( id ){\n    case SQLITE_MUTEX_FAST:\n    case SQLITE_MUTEX_RECURSIVE: {\n      pNew = sqlite3Malloc(sizeof(*pNew));\n      if( pNew ){\n        pNew->id = id;\n        pNew->cnt = 0;\n      }\n      break;\n    }\n    default: {\n#ifdef SQLITE_ENABLE_API_ARMOR\n      if( id-2<0 || id-2>=ArraySize(aStatic) ){\n        (void)SQLITE_MISUSE_BKPT;\n        return 0;\n      }\n#endif\n      pNew = &aStatic[id-2];\n      pNew->id = id;\n      break;\n    }\n  }\n  return (sqlite3_mutex*)pNew;\n}\n\n/*\n** This routine deallocates a previously allocated mutex.\n*/\nstatic void debugMutexFree(sqlite3_mutex *pX){\n  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;\n  assert( p->cnt==0 );\n  if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){\n    sqlite3_free(p);\n  }else{\n#ifdef SQLITE_ENABLE_API_ARMOR\n    (void)SQLITE_MISUSE_BKPT;\n#endif\n  }\n}\n\n/*\n** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt\n** to enter a mutex.  If another thread is already within the mutex,\n** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return\n** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK\n** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can\n** be entered multiple times by the same thread.  In such cases the,\n** mutex must be exited an equal number of times before another thread\n** can enter.  If the same thread tries to enter any other kind of mutex\n** more than once, the behavior is undefined.\n*/\nstatic void debugMutexEnter(sqlite3_mutex *pX){\n  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;\n  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );\n  p->cnt++;\n}\nstatic int debugMutexTry(sqlite3_mutex *pX){\n  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;\n  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );\n  p->cnt++;\n  return SQLITE_OK;\n}\n\n/*\n** The sqlite3_mutex_leave() routine exits a mutex that was\n** previously entered by the same thread.  The behavior\n** is undefined if the mutex is not currently entered or\n** is not currently allocated.  SQLite will never do either.\n*/\nstatic void debugMutexLeave(sqlite3_mutex *pX){\n  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;\n  assert( debugMutexHeld(pX) );\n  p->cnt--;\n  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );\n}\n\nSQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){\n  static const sqlite3_mutex_methods sMutex = {\n    debugMutexInit,\n    debugMutexEnd,\n    debugMutexAlloc,\n    debugMutexFree,\n    debugMutexEnter,\n    debugMutexTry,\n    debugMutexLeave,\n\n    debugMutexHeld,\n    debugMutexNotheld\n  };\n\n  return &sMutex;\n}\n#endif /* SQLITE_DEBUG */\n\n/*\n** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation\n** is used regardless of the run-time threadsafety setting.\n*/\n#ifdef SQLITE_MUTEX_NOOP\nSQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){\n  return sqlite3NoopMutex();\n}\n#endif /* defined(SQLITE_MUTEX_NOOP) */\n#endif /* !defined(SQLITE_MUTEX_OMIT) */\n\n/************** End of mutex_noop.c ******************************************/\n/************** Begin file mutex_unix.c **************************************/\n/*\n** 2007 August 28\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the C functions that implement mutexes for pthreads\n*/\n/* #include \"sqliteInt.h\" */\n\n/*\n** The code in this file is only used if we are compiling threadsafe\n** under unix with pthreads.\n**\n** Note that this implementation requires a version of pthreads that\n** supports recursive mutexes.\n*/\n#ifdef SQLITE_MUTEX_PTHREADS\n\n#include <pthread.h>\n\n/*\n** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields\n** are necessary under two condidtions:  (1) Debug builds and (2) using\n** home-grown mutexes.  Encapsulate these conditions into a single #define.\n*/\n#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)\n# define SQLITE_MUTEX_NREF 1\n#else\n# define SQLITE_MUTEX_NREF 0\n#endif\n\n/*\n** Each recursive mutex is an instance of the following structure.\n*/\nstruct sqlite3_mutex {\n  pthread_mutex_t mutex;     /* Mutex controlling the lock */\n#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)\n  int id;                    /* Mutex type */\n#endif\n#if SQLITE_MUTEX_NREF\n  volatile int nRef;         /* Number of entrances */\n  volatile pthread_t owner;  /* Thread that is within this mutex */\n  int trace;                 /* True to trace changes */\n#endif\n};\n#if SQLITE_MUTEX_NREF\n# define SQLITE3_MUTEX_INITIALIZER(id) \\\n     {PTHREAD_MUTEX_INITIALIZER,id,0,(pthread_t)0,0}\n#elif defined(SQLITE_ENABLE_API_ARMOR)\n# define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER, id }\n#else\n#define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER }\n#endif\n\n/*\n** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are\n** intended for use only inside assert() statements.  On some platforms,\n** there might be race conditions that can cause these routines to\n** deliver incorrect results.  In particular, if pthread_equal() is\n** not an atomic operation, then these routines might delivery\n** incorrect results.  On most platforms, pthread_equal() is a \n** comparison of two integers and is therefore atomic.  But we are\n** told that HPUX is not such a platform.  If so, then these routines\n** will not always work correctly on HPUX.\n**\n** On those platforms where pthread_equal() is not atomic, SQLite\n** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to\n** make sure no assert() statements are evaluated and hence these\n** routines are never called.\n*/\n#if !defined(NDEBUG) || defined(SQLITE_DEBUG)\nstatic int pthreadMutexHeld(sqlite3_mutex *p){\n  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));\n}\nstatic int pthreadMutexNotheld(sqlite3_mutex *p){\n  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;\n}\n#endif\n\n/*\n** Try to provide a memory barrier operation, needed for initialization\n** and also for the implementation of xShmBarrier in the VFS in cases\n** where SQLite is compiled without mutexes.\n*/\nSQLITE_PRIVATE void sqlite3MemoryBarrier(void){\n#if defined(SQLITE_MEMORY_BARRIER)\n  SQLITE_MEMORY_BARRIER;\n#elif defined(__GNUC__) && GCC_VERSION>=4001000\n  __sync_synchronize();\n#endif\n}\n\n/*\n** Initialize and deinitialize the mutex subsystem.\n*/\nstatic int pthreadMutexInit(void){ return SQLITE_OK; }\nstatic int pthreadMutexEnd(void){ return SQLITE_OK; }\n\n/*\n** The sqlite3_mutex_alloc() routine allocates a new\n** mutex and returns a pointer to it.  If it returns NULL\n** that means that a mutex could not be allocated.  SQLite\n** will unwind its stack and return an error.  The argument\n** to sqlite3_mutex_alloc() is one of these integer constants:\n**\n** <ul>\n** <li>  SQLITE_MUTEX_FAST\n** <li>  SQLITE_MUTEX_RECURSIVE\n** <li>  SQLITE_MUTEX_STATIC_MASTER\n** <li>  SQLITE_MUTEX_STATIC_MEM\n** <li>  SQLITE_MUTEX_STATIC_OPEN\n** <li>  SQLITE_MUTEX_STATIC_PRNG\n** <li>  SQLITE_MUTEX_STATIC_LRU\n** <li>  SQLITE_MUTEX_STATIC_PMEM\n** <li>  SQLITE_MUTEX_STATIC_APP1\n** <li>  SQLITE_MUTEX_STATIC_APP2\n** <li>  SQLITE_MUTEX_STATIC_APP3\n** <li>  SQLITE_MUTEX_STATIC_VFS1\n** <li>  SQLITE_MUTEX_STATIC_VFS2\n** <li>  SQLITE_MUTEX_STATIC_VFS3\n** </ul>\n**\n** The first two constants cause sqlite3_mutex_alloc() to create\n** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE\n** is used but not necessarily so when SQLITE_MUTEX_FAST is used.\n** The mutex implementation does not need to make a distinction\n** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does\n** not want to.  But SQLite will only request a recursive mutex in\n** cases where it really needs one.  If a faster non-recursive mutex\n** implementation is available on the host platform, the mutex subsystem\n** might return such a mutex in response to SQLITE_MUTEX_FAST.\n**\n** The other allowed parameters to sqlite3_mutex_alloc() each return\n** a pointer to a static preexisting mutex.  Six static mutexes are\n** used by the current version of SQLite.  Future versions of SQLite\n** may add additional static mutexes.  Static mutexes are for internal\n** use by SQLite only.  Applications that use SQLite mutexes should\n** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or\n** SQLITE_MUTEX_RECURSIVE.\n**\n** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST\n** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()\n** returns a different mutex on every call.  But for the static \n** mutex types, the same mutex is returned on every call that has\n** the same type number.\n*/\nstatic sqlite3_mutex *pthreadMutexAlloc(int iType){\n  static sqlite3_mutex staticMutexes[] = {\n    SQLITE3_MUTEX_INITIALIZER(2),\n    SQLITE3_MUTEX_INITIALIZER(3),\n    SQLITE3_MUTEX_INITIALIZER(4),\n    SQLITE3_MUTEX_INITIALIZER(5),\n    SQLITE3_MUTEX_INITIALIZER(6),\n    SQLITE3_MUTEX_INITIALIZER(7),\n    SQLITE3_MUTEX_INITIALIZER(8),\n    SQLITE3_MUTEX_INITIALIZER(9),\n    SQLITE3_MUTEX_INITIALIZER(10),\n    SQLITE3_MUTEX_INITIALIZER(11),\n    SQLITE3_MUTEX_INITIALIZER(12),\n    SQLITE3_MUTEX_INITIALIZER(13)\n  };\n  sqlite3_mutex *p;\n  switch( iType ){\n    case SQLITE_MUTEX_RECURSIVE: {\n      p = sqlite3MallocZero( sizeof(*p) );\n      if( p ){\n#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX\n        /* If recursive mutexes are not available, we will have to\n        ** build our own.  See below. */\n        pthread_mutex_init(&p->mutex, 0);\n#else\n        /* Use a recursive mutex if it is available */\n        pthread_mutexattr_t recursiveAttr;\n        pthread_mutexattr_init(&recursiveAttr);\n        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);\n        pthread_mutex_init(&p->mutex, &recursiveAttr);\n        pthread_mutexattr_destroy(&recursiveAttr);\n#endif\n#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)\n        p->id = SQLITE_MUTEX_RECURSIVE;\n#endif\n      }\n      break;\n    }\n    case SQLITE_MUTEX_FAST: {\n      p = sqlite3MallocZero( sizeof(*p) );\n      if( p ){\n        pthread_mutex_init(&p->mutex, 0);\n#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)\n        p->id = SQLITE_MUTEX_FAST;\n#endif\n      }\n      break;\n    }\n    default: {\n#ifdef SQLITE_ENABLE_API_ARMOR\n      if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){\n        (void)SQLITE_MISUSE_BKPT;\n        return 0;\n      }\n#endif\n      p = &staticMutexes[iType-2];\n      break;\n    }\n  }\n#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)\n  assert( p==0 || p->id==iType );\n#endif\n  return p;\n}\n\n\n/*\n** This routine deallocates a previously\n** allocated mutex.  SQLite is careful to deallocate every\n** mutex that it allocates.\n*/\nstatic void pthreadMutexFree(sqlite3_mutex *p){\n  assert( p->nRef==0 );\n#if SQLITE_ENABLE_API_ARMOR\n  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )\n#endif\n  {\n    pthread_mutex_destroy(&p->mutex);\n    sqlite3_free(p);\n  }\n#ifdef SQLITE_ENABLE_API_ARMOR\n  else{\n    (void)SQLITE_MISUSE_BKPT;\n  }\n#endif\n}\n\n/*\n** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt\n** to enter a mutex.  If another thread is already within the mutex,\n** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return\n** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK\n** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can\n** be entered multiple times by the same thread.  In such cases the,\n** mutex must be exited an equal number of times before another thread\n** can enter.  If the same thread tries to enter any other kind of mutex\n** more than once, the behavior is undefined.\n*/\nstatic void pthreadMutexEnter(sqlite3_mutex *p){\n  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );\n\n#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX\n  /* If recursive mutexes are not available, then we have to grow\n  ** our own.  This implementation assumes that pthread_equal()\n  ** is atomic - that it cannot be deceived into thinking self\n  ** and p->owner are equal if p->owner changes between two values\n  ** that are not equal to self while the comparison is taking place.\n  ** This implementation also assumes a coherent cache - that \n  ** separate processes cannot read different values from the same\n  ** address at the same time.  If either of these two conditions\n  ** are not met, then the mutexes will fail and problems will result.\n  */\n  {\n    pthread_t self = pthread_self();\n    if( p->nRef>0 && pthread_equal(p->owner, self) ){\n      p->nRef++;\n    }else{\n      pthread_mutex_lock(&p->mutex);\n      assert( p->nRef==0 );\n      p->owner = self;\n      p->nRef = 1;\n    }\n  }\n#else\n  /* Use the built-in recursive mutexes if they are available.\n  */\n  pthread_mutex_lock(&p->mutex);\n#if SQLITE_MUTEX_NREF\n  assert( p->nRef>0 || p->owner==0 );\n  p->owner = pthread_self();\n  p->nRef++;\n#endif\n#endif\n\n#ifdef SQLITE_DEBUG\n  if( p->trace ){\n    printf(\"enter mutex %p (%d) with nRef=%d\\n\", p, p->trace, p->nRef);\n  }\n#endif\n}\nstatic int pthreadMutexTry(sqlite3_mutex *p){\n  int rc;\n  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );\n\n#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX\n  /* If recursive mutexes are not available, then we have to grow\n  ** our own.  This implementation assumes that pthread_equal()\n  ** is atomic - that it cannot be deceived into thinking self\n  ** and p->owner are equal if p->owner changes between two values\n  ** that are not equal to self while the comparison is taking place.\n  ** This implementation also assumes a coherent cache - that \n  ** separate processes cannot read different values from the same\n  ** address at the same time.  If either of these two conditions\n  ** are not met, then the mutexes will fail and problems will result.\n  */\n  {\n    pthread_t self = pthread_self();\n    if( p->nRef>0 && pthread_equal(p->owner, self) ){\n      p->nRef++;\n      rc = SQLITE_OK;\n    }else if( pthread_mutex_trylock(&p->mutex)==0 ){\n      assert( p->nRef==0 );\n      p->owner = self;\n      p->nRef = 1;\n      rc = SQLITE_OK;\n    }else{\n      rc = SQLITE_BUSY;\n    }\n  }\n#else\n  /* Use the built-in recursive mutexes if they are available.\n  */\n  if( pthread_mutex_trylock(&p->mutex)==0 ){\n#if SQLITE_MUTEX_NREF\n    p->owner = pthread_self();\n    p->nRef++;\n#endif\n    rc = SQLITE_OK;\n  }else{\n    rc = SQLITE_BUSY;\n  }\n#endif\n\n#ifdef SQLITE_DEBUG\n  if( rc==SQLITE_OK && p->trace ){\n    printf(\"enter mutex %p (%d) with nRef=%d\\n\", p, p->trace, p->nRef);\n  }\n#endif\n  return rc;\n}\n\n/*\n** The sqlite3_mutex_leave() routine exits a mutex that was\n** previously entered by the same thread.  The behavior\n** is undefined if the mutex is not currently entered or\n** is not currently allocated.  SQLite will never do either.\n*/\nstatic void pthreadMutexLeave(sqlite3_mutex *p){\n  assert( pthreadMutexHeld(p) );\n#if SQLITE_MUTEX_NREF\n  p->nRef--;\n  if( p->nRef==0 ) p->owner = 0;\n#endif\n  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );\n\n#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX\n  if( p->nRef==0 ){\n    pthread_mutex_unlock(&p->mutex);\n  }\n#else\n  pthread_mutex_unlock(&p->mutex);\n#endif\n\n#ifdef SQLITE_DEBUG\n  if( p->trace ){\n    printf(\"leave mutex %p (%d) with nRef=%d\\n\", p, p->trace, p->nRef);\n  }\n#endif\n}\n\nSQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){\n  static const sqlite3_mutex_methods sMutex = {\n    pthreadMutexInit,\n    pthreadMutexEnd,\n    pthreadMutexAlloc,\n    pthreadMutexFree,\n    pthreadMutexEnter,\n    pthreadMutexTry,\n    pthreadMutexLeave,\n#ifdef SQLITE_DEBUG\n    pthreadMutexHeld,\n    pthreadMutexNotheld\n#else\n    0,\n    0\n#endif\n  };\n\n  return &sMutex;\n}\n\n#endif /* SQLITE_MUTEX_PTHREADS */\n\n/************** End of mutex_unix.c ******************************************/\n/************** Begin file mutex_w32.c ***************************************/\n/*\n** 2007 August 14\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the C functions that implement mutexes for Win32.\n*/\n/* #include \"sqliteInt.h\" */\n\n#if SQLITE_OS_WIN\n/*\n** Include code that is common to all os_*.c files\n*/\n/************** Include os_common.h in the middle of mutex_w32.c *************/\n/************** Begin file os_common.h ***************************************/\n/*\n** 2004 May 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains macros and a little bit of code that is common to\n** all of the platform-specific files (os_*.c) and is #included into those\n** files.\n**\n** This file should be #included by the os_*.c files only.  It is not a\n** general purpose header file.\n*/\n#ifndef _OS_COMMON_H_\n#define _OS_COMMON_H_\n\n/*\n** At least two bugs have slipped in because we changed the MEMORY_DEBUG\n** macro to SQLITE_DEBUG and some older makefiles have not yet made the\n** switch.  The following code should catch this problem at compile-time.\n*/\n#ifdef MEMORY_DEBUG\n# error \"The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead.\"\n#endif\n\n/*\n** Macros for performance tracing.  Normally turned off.  Only works\n** on i486 hardware.\n*/\n#ifdef SQLITE_PERFORMANCE_TRACE\n\n/*\n** hwtime.h contains inline assembler code for implementing\n** high-performance timing routines.\n*/\n/************** Include hwtime.h in the middle of os_common.h ****************/\n/************** Begin file hwtime.h ******************************************/\n/*\n** 2008 May 27\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains inline asm code for retrieving \"high-performance\"\n** counters for x86 and x86_64 class CPUs.\n*/\n#ifndef SQLITE_HWTIME_H\n#define SQLITE_HWTIME_H\n\n/*\n** The following routine only works on pentium-class (or newer) processors.\n** It uses the RDTSC opcode to read the cycle count value out of the\n** processor and returns that value.  This can be used for high-res\n** profiling.\n*/\n#if !defined(__STRICT_ANSI__) && \\\n    (defined(__GNUC__) || defined(_MSC_VER)) && \\\n    (defined(i386) || defined(__i386__) || defined(_M_IX86))\n\n  #if defined(__GNUC__)\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n     unsigned int lo, hi;\n     __asm__ __volatile__ (\"rdtsc\" : \"=a\" (lo), \"=d\" (hi));\n     return (sqlite_uint64)hi << 32 | lo;\n  }\n\n  #elif defined(_MSC_VER)\n\n  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){\n     __asm {\n        rdtsc\n        ret       ; return value at EDX:EAX\n     }\n  }\n\n  #endif\n\n#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n      unsigned long val;\n      __asm__ __volatile__ (\"rdtsc\" : \"=A\" (val));\n      return val;\n  }\n \n#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n      unsigned long long retval;\n      unsigned long junk;\n      __asm__ __volatile__ (\"\\n\\\n          1:      mftbu   %1\\n\\\n                  mftb    %L0\\n\\\n                  mftbu   %0\\n\\\n                  cmpw    %0,%1\\n\\\n                  bne     1b\"\n                  : \"=r\" (retval), \"=r\" (junk));\n      return retval;\n  }\n\n#else\n\n  /*\n  ** asm() is needed for hardware timing support.  Without asm(),\n  ** disable the sqlite3Hwtime() routine.\n  **\n  ** sqlite3Hwtime() is only used for some obscure debugging\n  ** and analysis configurations, not in any deliverable, so this\n  ** should not be a great loss.\n  */\nSQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }\n\n#endif\n\n#endif /* !defined(SQLITE_HWTIME_H) */\n\n/************** End of hwtime.h **********************************************/\n/************** Continuing where we left off in os_common.h ******************/\n\nstatic sqlite_uint64 g_start;\nstatic sqlite_uint64 g_elapsed;\n#define TIMER_START       g_start=sqlite3Hwtime()\n#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start\n#define TIMER_ELAPSED     g_elapsed\n#else\n#define TIMER_START\n#define TIMER_END\n#define TIMER_ELAPSED     ((sqlite_uint64)0)\n#endif\n\n/*\n** If we compile with the SQLITE_TEST macro set, then the following block\n** of code will give us the ability to simulate a disk I/O error.  This\n** is used for testing the I/O recovery logic.\n*/\n#if defined(SQLITE_TEST)\nSQLITE_API extern int sqlite3_io_error_hit;\nSQLITE_API extern int sqlite3_io_error_hardhit;\nSQLITE_API extern int sqlite3_io_error_pending;\nSQLITE_API extern int sqlite3_io_error_persist;\nSQLITE_API extern int sqlite3_io_error_benign;\nSQLITE_API extern int sqlite3_diskfull_pending;\nSQLITE_API extern int sqlite3_diskfull;\n#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)\n#define SimulateIOError(CODE)  \\\n  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \\\n       || sqlite3_io_error_pending-- == 1 )  \\\n              { local_ioerr(); CODE; }\nstatic void local_ioerr(){\n  IOTRACE((\"IOERR\\n\"));\n  sqlite3_io_error_hit++;\n  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;\n}\n#define SimulateDiskfullError(CODE) \\\n   if( sqlite3_diskfull_pending ){ \\\n     if( sqlite3_diskfull_pending == 1 ){ \\\n       local_ioerr(); \\\n       sqlite3_diskfull = 1; \\\n       sqlite3_io_error_hit = 1; \\\n       CODE; \\\n     }else{ \\\n       sqlite3_diskfull_pending--; \\\n     } \\\n   }\n#else\n#define SimulateIOErrorBenign(X)\n#define SimulateIOError(A)\n#define SimulateDiskfullError(A)\n#endif /* defined(SQLITE_TEST) */\n\n/*\n** When testing, keep a count of the number of open files.\n*/\n#if defined(SQLITE_TEST)\nSQLITE_API extern int sqlite3_open_file_count;\n#define OpenCounter(X)  sqlite3_open_file_count+=(X)\n#else\n#define OpenCounter(X)\n#endif /* defined(SQLITE_TEST) */\n\n#endif /* !defined(_OS_COMMON_H_) */\n\n/************** End of os_common.h *******************************************/\n/************** Continuing where we left off in mutex_w32.c ******************/\n\n/*\n** Include the header file for the Windows VFS.\n*/\n/************** Include os_win.h in the middle of mutex_w32.c ****************/\n/************** Begin file os_win.h ******************************************/\n/*\n** 2013 November 25\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains code that is specific to Windows.\n*/\n#ifndef SQLITE_OS_WIN_H\n#define SQLITE_OS_WIN_H\n\n/*\n** Include the primary Windows SDK header file.\n*/\n#include \"windows.h\"\n\n#ifdef __CYGWIN__\n# include <sys/cygwin.h>\n# include <errno.h> /* amalgamator: dontcache */\n#endif\n\n/*\n** Determine if we are dealing with Windows NT.\n**\n** We ought to be able to determine if we are compiling for Windows 9x or\n** Windows NT using the _WIN32_WINNT macro as follows:\n**\n** #if defined(_WIN32_WINNT)\n** # define SQLITE_OS_WINNT 1\n** #else\n** # define SQLITE_OS_WINNT 0\n** #endif\n**\n** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as\n** it ought to, so the above test does not work.  We'll just assume that\n** everything is Windows NT unless the programmer explicitly says otherwise\n** by setting SQLITE_OS_WINNT to 0.\n*/\n#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)\n# define SQLITE_OS_WINNT 1\n#endif\n\n/*\n** Determine if we are dealing with Windows CE - which has a much reduced\n** API.\n*/\n#if defined(_WIN32_WCE)\n# define SQLITE_OS_WINCE 1\n#else\n# define SQLITE_OS_WINCE 0\n#endif\n\n/*\n** Determine if we are dealing with WinRT, which provides only a subset of\n** the full Win32 API.\n*/\n#if !defined(SQLITE_OS_WINRT)\n# define SQLITE_OS_WINRT 0\n#endif\n\n/*\n** For WinCE, some API function parameters do not appear to be declared as\n** volatile.\n*/\n#if SQLITE_OS_WINCE\n# define SQLITE_WIN32_VOLATILE\n#else\n# define SQLITE_WIN32_VOLATILE volatile\n#endif\n\n/*\n** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()\n** functions are not available (e.g. those not using MSVC, Cygwin, etc).\n*/\n#if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \\\n    SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)\n# define SQLITE_OS_WIN_THREADS 1\n#else\n# define SQLITE_OS_WIN_THREADS 0\n#endif\n\n#endif /* SQLITE_OS_WIN_H */\n\n/************** End of os_win.h **********************************************/\n/************** Continuing where we left off in mutex_w32.c ******************/\n#endif\n\n/*\n** The code in this file is only used if we are compiling multithreaded\n** on a Win32 system.\n*/\n#ifdef SQLITE_MUTEX_W32\n\n/*\n** Each recursive mutex is an instance of the following structure.\n*/\nstruct sqlite3_mutex {\n  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */\n  int id;                    /* Mutex type */\n#ifdef SQLITE_DEBUG\n  volatile int nRef;         /* Number of enterances */\n  volatile DWORD owner;      /* Thread holding this mutex */\n  volatile LONG trace;       /* True to trace changes */\n#endif\n};\n\n/*\n** These are the initializer values used when declaring a \"static\" mutex\n** on Win32.  It should be noted that all mutexes require initialization\n** on the Win32 platform.\n*/\n#define SQLITE_W32_MUTEX_INITIALIZER { 0 }\n\n#ifdef SQLITE_DEBUG\n#define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id, \\\n                                    0L, (DWORD)0, 0 }\n#else\n#define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id }\n#endif\n\n#ifdef SQLITE_DEBUG\n/*\n** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are\n** intended for use only inside assert() statements.\n*/\nstatic int winMutexHeld(sqlite3_mutex *p){\n  return p->nRef!=0 && p->owner==GetCurrentThreadId();\n}\n\nstatic int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){\n  return p->nRef==0 || p->owner!=tid;\n}\n\nstatic int winMutexNotheld(sqlite3_mutex *p){\n  DWORD tid = GetCurrentThreadId();\n  return winMutexNotheld2(p, tid);\n}\n#endif\n\n/*\n** Try to provide a memory barrier operation, needed for initialization\n** and also for the xShmBarrier method of the VFS in cases when SQLite is\n** compiled without mutexes (SQLITE_THREADSAFE=0).\n*/\nSQLITE_PRIVATE void sqlite3MemoryBarrier(void){\n#if defined(SQLITE_MEMORY_BARRIER)\n  SQLITE_MEMORY_BARRIER;\n#elif defined(__GNUC__)\n  __sync_synchronize();\n#elif MSVC_VERSION>=1300\n  _ReadWriteBarrier();\n#elif defined(MemoryBarrier)\n  MemoryBarrier();\n#endif\n}\n\n/*\n** Initialize and deinitialize the mutex subsystem.\n*/\nstatic sqlite3_mutex winMutex_staticMutexes[] = {\n  SQLITE3_MUTEX_INITIALIZER(2),\n  SQLITE3_MUTEX_INITIALIZER(3),\n  SQLITE3_MUTEX_INITIALIZER(4),\n  SQLITE3_MUTEX_INITIALIZER(5),\n  SQLITE3_MUTEX_INITIALIZER(6),\n  SQLITE3_MUTEX_INITIALIZER(7),\n  SQLITE3_MUTEX_INITIALIZER(8),\n  SQLITE3_MUTEX_INITIALIZER(9),\n  SQLITE3_MUTEX_INITIALIZER(10),\n  SQLITE3_MUTEX_INITIALIZER(11),\n  SQLITE3_MUTEX_INITIALIZER(12),\n  SQLITE3_MUTEX_INITIALIZER(13)\n};\n\nstatic int winMutex_isInit = 0;\nstatic int winMutex_isNt = -1; /* <0 means \"need to query\" */\n\n/* As the winMutexInit() and winMutexEnd() functions are called as part\n** of the sqlite3_initialize() and sqlite3_shutdown() processing, the\n** \"interlocked\" magic used here is probably not strictly necessary.\n*/\nstatic LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;\n\nSQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */\nSQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */\n\nstatic int winMutexInit(void){\n  /* The first to increment to 1 does actual initialization */\n  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){\n    int i;\n    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){\n#if SQLITE_OS_WINRT\n      InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);\n#else\n      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);\n#endif\n    }\n    winMutex_isInit = 1;\n  }else{\n    /* Another thread is (in the process of) initializing the static\n    ** mutexes */\n    while( !winMutex_isInit ){\n      sqlite3_win32_sleep(1);\n    }\n  }\n  return SQLITE_OK;\n}\n\nstatic int winMutexEnd(void){\n  /* The first to decrement to 0 does actual shutdown\n  ** (which should be the last to shutdown.) */\n  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){\n    if( winMutex_isInit==1 ){\n      int i;\n      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){\n        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);\n      }\n      winMutex_isInit = 0;\n    }\n  }\n  return SQLITE_OK;\n}\n\n/*\n** The sqlite3_mutex_alloc() routine allocates a new\n** mutex and returns a pointer to it.  If it returns NULL\n** that means that a mutex could not be allocated.  SQLite\n** will unwind its stack and return an error.  The argument\n** to sqlite3_mutex_alloc() is one of these integer constants:\n**\n** <ul>\n** <li>  SQLITE_MUTEX_FAST\n** <li>  SQLITE_MUTEX_RECURSIVE\n** <li>  SQLITE_MUTEX_STATIC_MASTER\n** <li>  SQLITE_MUTEX_STATIC_MEM\n** <li>  SQLITE_MUTEX_STATIC_OPEN\n** <li>  SQLITE_MUTEX_STATIC_PRNG\n** <li>  SQLITE_MUTEX_STATIC_LRU\n** <li>  SQLITE_MUTEX_STATIC_PMEM\n** <li>  SQLITE_MUTEX_STATIC_APP1\n** <li>  SQLITE_MUTEX_STATIC_APP2\n** <li>  SQLITE_MUTEX_STATIC_APP3\n** <li>  SQLITE_MUTEX_STATIC_VFS1\n** <li>  SQLITE_MUTEX_STATIC_VFS2\n** <li>  SQLITE_MUTEX_STATIC_VFS3\n** </ul>\n**\n** The first two constants cause sqlite3_mutex_alloc() to create\n** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE\n** is used but not necessarily so when SQLITE_MUTEX_FAST is used.\n** The mutex implementation does not need to make a distinction\n** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does\n** not want to.  But SQLite will only request a recursive mutex in\n** cases where it really needs one.  If a faster non-recursive mutex\n** implementation is available on the host platform, the mutex subsystem\n** might return such a mutex in response to SQLITE_MUTEX_FAST.\n**\n** The other allowed parameters to sqlite3_mutex_alloc() each return\n** a pointer to a static preexisting mutex.  Six static mutexes are\n** used by the current version of SQLite.  Future versions of SQLite\n** may add additional static mutexes.  Static mutexes are for internal\n** use by SQLite only.  Applications that use SQLite mutexes should\n** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or\n** SQLITE_MUTEX_RECURSIVE.\n**\n** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST\n** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()\n** returns a different mutex on every call.  But for the static\n** mutex types, the same mutex is returned on every call that has\n** the same type number.\n*/\nstatic sqlite3_mutex *winMutexAlloc(int iType){\n  sqlite3_mutex *p;\n\n  switch( iType ){\n    case SQLITE_MUTEX_FAST:\n    case SQLITE_MUTEX_RECURSIVE: {\n      p = sqlite3MallocZero( sizeof(*p) );\n      if( p ){\n        p->id = iType;\n#ifdef SQLITE_DEBUG\n#ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC\n        p->trace = 1;\n#endif\n#endif\n#if SQLITE_OS_WINRT\n        InitializeCriticalSectionEx(&p->mutex, 0, 0);\n#else\n        InitializeCriticalSection(&p->mutex);\n#endif\n      }\n      break;\n    }\n    default: {\n#ifdef SQLITE_ENABLE_API_ARMOR\n      if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){\n        (void)SQLITE_MISUSE_BKPT;\n        return 0;\n      }\n#endif\n      p = &winMutex_staticMutexes[iType-2];\n#ifdef SQLITE_DEBUG\n#ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC\n      InterlockedCompareExchange(&p->trace, 1, 0);\n#endif\n#endif\n      break;\n    }\n  }\n  assert( p==0 || p->id==iType );\n  return p;\n}\n\n\n/*\n** This routine deallocates a previously\n** allocated mutex.  SQLite is careful to deallocate every\n** mutex that it allocates.\n*/\nstatic void winMutexFree(sqlite3_mutex *p){\n  assert( p );\n  assert( p->nRef==0 && p->owner==0 );\n  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){\n    DeleteCriticalSection(&p->mutex);\n    sqlite3_free(p);\n  }else{\n#ifdef SQLITE_ENABLE_API_ARMOR\n    (void)SQLITE_MISUSE_BKPT;\n#endif\n  }\n}\n\n/*\n** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt\n** to enter a mutex.  If another thread is already within the mutex,\n** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return\n** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK\n** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can\n** be entered multiple times by the same thread.  In such cases the,\n** mutex must be exited an equal number of times before another thread\n** can enter.  If the same thread tries to enter any other kind of mutex\n** more than once, the behavior is undefined.\n*/\nstatic void winMutexEnter(sqlite3_mutex *p){\n#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)\n  DWORD tid = GetCurrentThreadId();\n#endif\n#ifdef SQLITE_DEBUG\n  assert( p );\n  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );\n#else\n  assert( p );\n#endif\n  assert( winMutex_isInit==1 );\n  EnterCriticalSection(&p->mutex);\n#ifdef SQLITE_DEBUG\n  assert( p->nRef>0 || p->owner==0 );\n  p->owner = tid;\n  p->nRef++;\n  if( p->trace ){\n    OSTRACE((\"ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\\n\",\n             tid, p->id, p, p->trace, p->nRef));\n  }\n#endif\n}\n\nstatic int winMutexTry(sqlite3_mutex *p){\n#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)\n  DWORD tid = GetCurrentThreadId();\n#endif\n  int rc = SQLITE_BUSY;\n  assert( p );\n  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );\n  /*\n  ** The sqlite3_mutex_try() routine is very rarely used, and when it\n  ** is used it is merely an optimization.  So it is OK for it to always\n  ** fail.\n  **\n  ** The TryEnterCriticalSection() interface is only available on WinNT.\n  ** And some windows compilers complain if you try to use it without\n  ** first doing some #defines that prevent SQLite from building on Win98.\n  ** For that reason, we will omit this optimization for now.  See\n  ** ticket #2685.\n  */\n#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400\n  assert( winMutex_isInit==1 );\n  assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );\n  if( winMutex_isNt<0 ){\n    winMutex_isNt = sqlite3_win32_is_nt();\n  }\n  assert( winMutex_isNt==0 || winMutex_isNt==1 );\n  if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){\n#ifdef SQLITE_DEBUG\n    p->owner = tid;\n    p->nRef++;\n#endif\n    rc = SQLITE_OK;\n  }\n#else\n  UNUSED_PARAMETER(p);\n#endif\n#ifdef SQLITE_DEBUG\n  if( p->trace ){\n    OSTRACE((\"TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\\n\",\n             tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));\n  }\n#endif\n  return rc;\n}\n\n/*\n** The sqlite3_mutex_leave() routine exits a mutex that was\n** previously entered by the same thread.  The behavior\n** is undefined if the mutex is not currently entered or\n** is not currently allocated.  SQLite will never do either.\n*/\nstatic void winMutexLeave(sqlite3_mutex *p){\n#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)\n  DWORD tid = GetCurrentThreadId();\n#endif\n  assert( p );\n#ifdef SQLITE_DEBUG\n  assert( p->nRef>0 );\n  assert( p->owner==tid );\n  p->nRef--;\n  if( p->nRef==0 ) p->owner = 0;\n  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );\n#endif\n  assert( winMutex_isInit==1 );\n  LeaveCriticalSection(&p->mutex);\n#ifdef SQLITE_DEBUG\n  if( p->trace ){\n    OSTRACE((\"LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\\n\",\n             tid, p->id, p, p->trace, p->nRef));\n  }\n#endif\n}\n\nSQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){\n  static const sqlite3_mutex_methods sMutex = {\n    winMutexInit,\n    winMutexEnd,\n    winMutexAlloc,\n    winMutexFree,\n    winMutexEnter,\n    winMutexTry,\n    winMutexLeave,\n#ifdef SQLITE_DEBUG\n    winMutexHeld,\n    winMutexNotheld\n#else\n    0,\n    0\n#endif\n  };\n  return &sMutex;\n}\n\n#endif /* SQLITE_MUTEX_W32 */\n\n/************** End of mutex_w32.c *******************************************/\n/************** Begin file malloc.c ******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** Memory allocation functions used throughout sqlite.\n*/\n/* #include \"sqliteInt.h\" */\n/* #include <stdarg.h> */\n\n/*\n** Attempt to release up to n bytes of non-essential memory currently\n** held by SQLite. An example of non-essential memory is memory used to\n** cache database pages that are not currently in use.\n*/\nSQLITE_API int sqlite3_release_memory(int n){\n#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT\n  return sqlite3PcacheReleaseMemory(n);\n#else\n  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine\n  ** is a no-op returning zero if SQLite is not compiled with\n  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */\n  UNUSED_PARAMETER(n);\n  return 0;\n#endif\n}\n\n/*\n** Default value of the hard heap limit.  0 means \"no limit\".\n*/\n#ifndef SQLITE_MAX_MEMORY\n# define SQLITE_MAX_MEMORY 0\n#endif\n\n/*\n** State information local to the memory allocation subsystem.\n*/\nstatic SQLITE_WSD struct Mem0Global {\n  sqlite3_mutex *mutex;         /* Mutex to serialize access */\n  sqlite3_int64 alarmThreshold; /* The soft heap limit */\n  sqlite3_int64 hardLimit;      /* The hard upper bound on memory */\n\n  /*\n  ** True if heap is nearly \"full\" where \"full\" is defined by the\n  ** sqlite3_soft_heap_limit() setting.\n  */\n  int nearlyFull;\n} mem0 = { 0, SQLITE_MAX_MEMORY, SQLITE_MAX_MEMORY, 0 };\n\n#define mem0 GLOBAL(struct Mem0Global, mem0)\n\n/*\n** Return the memory allocator mutex. sqlite3_status() needs it.\n*/\nSQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){\n  return mem0.mutex;\n}\n\n#ifndef SQLITE_OMIT_DEPRECATED\n/*\n** Deprecated external interface.  It used to set an alarm callback\n** that was invoked when memory usage grew too large.  Now it is a\n** no-op.\n*/\nSQLITE_API int sqlite3_memory_alarm(\n  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),\n  void *pArg,\n  sqlite3_int64 iThreshold\n){\n  (void)xCallback;\n  (void)pArg;\n  (void)iThreshold;\n  return SQLITE_OK;\n}\n#endif\n\n/*\n** Set the soft heap-size limit for the library.  An argument of\n** zero disables the limit.  A negative argument is a no-op used to\n** obtain the return value.\n**\n** The return value is the value of the heap limit just before this\n** interface was called.\n**\n** If the hard heap limit is enabled, then the soft heap limit cannot\n** be disabled nor raised above the hard heap limit.\n*/\nSQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){\n  sqlite3_int64 priorLimit;\n  sqlite3_int64 excess;\n  sqlite3_int64 nUsed;\n#ifndef SQLITE_OMIT_AUTOINIT\n  int rc = sqlite3_initialize();\n  if( rc ) return -1;\n#endif\n  sqlite3_mutex_enter(mem0.mutex);\n  priorLimit = mem0.alarmThreshold;\n  if( n<0 ){\n    sqlite3_mutex_leave(mem0.mutex);\n    return priorLimit;\n  }\n  if( mem0.hardLimit>0 && (n>mem0.hardLimit || n==0) ){\n    n = mem0.hardLimit;\n  }\n  mem0.alarmThreshold = n;\n  nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);\n  AtomicStore(&mem0.nearlyFull, n>0 && n<=nUsed);\n  sqlite3_mutex_leave(mem0.mutex);\n  excess = sqlite3_memory_used() - n;\n  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));\n  return priorLimit;\n}\nSQLITE_API void sqlite3_soft_heap_limit(int n){\n  if( n<0 ) n = 0;\n  sqlite3_soft_heap_limit64(n);\n}\n\n/*\n** Set the hard heap-size limit for the library. An argument of zero\n** disables the hard heap limit.  A negative argument is a no-op used\n** to obtain the return value without affecting the hard heap limit.\n**\n** The return value is the value of the hard heap limit just prior to\n** calling this interface.\n**\n** Setting the hard heap limit will also activate the soft heap limit\n** and constrain the soft heap limit to be no more than the hard heap\n** limit.\n*/\nSQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 n){\n  sqlite3_int64 priorLimit;\n#ifndef SQLITE_OMIT_AUTOINIT\n  int rc = sqlite3_initialize();\n  if( rc ) return -1;\n#endif\n  sqlite3_mutex_enter(mem0.mutex);\n  priorLimit = mem0.hardLimit;\n  if( n>=0 ){\n    mem0.hardLimit = n;\n    if( n<mem0.alarmThreshold || mem0.alarmThreshold==0 ){\n      mem0.alarmThreshold = n;\n    }\n  }\n  sqlite3_mutex_leave(mem0.mutex);\n  return priorLimit;\n}\n\n\n/*\n** Initialize the memory allocation subsystem.\n*/\nSQLITE_PRIVATE int sqlite3MallocInit(void){\n  int rc;\n  if( sqlite3GlobalConfig.m.xMalloc==0 ){\n    sqlite3MemSetDefault();\n  }\n  memset(&mem0, 0, sizeof(mem0));\n  mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);\n  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512\n      || sqlite3GlobalConfig.nPage<=0 ){\n    sqlite3GlobalConfig.pPage = 0;\n    sqlite3GlobalConfig.szPage = 0;\n  }\n  rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);\n  if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));\n  return rc;\n}\n\n/*\n** Return true if the heap is currently under memory pressure - in other\n** words if the amount of heap used is close to the limit set by\n** sqlite3_soft_heap_limit().\n*/\nSQLITE_PRIVATE int sqlite3HeapNearlyFull(void){\n  return AtomicLoad(&mem0.nearlyFull);\n}\n\n/*\n** Deinitialize the memory allocation subsystem.\n*/\nSQLITE_PRIVATE void sqlite3MallocEnd(void){\n  if( sqlite3GlobalConfig.m.xShutdown ){\n    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);\n  }\n  memset(&mem0, 0, sizeof(mem0));\n}\n\n/*\n** Return the amount of memory currently checked out.\n*/\nSQLITE_API sqlite3_int64 sqlite3_memory_used(void){\n  sqlite3_int64 res, mx;\n  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);\n  return res;\n}\n\n/*\n** Return the maximum amount of memory that has ever been\n** checked out since either the beginning of this process\n** or since the most recent reset.\n*/\nSQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){\n  sqlite3_int64 res, mx;\n  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);\n  return mx;\n}\n\n/*\n** Trigger the alarm \n*/\nstatic void sqlite3MallocAlarm(int nByte){\n  if( mem0.alarmThreshold<=0 ) return;\n  sqlite3_mutex_leave(mem0.mutex);\n  sqlite3_release_memory(nByte);\n  sqlite3_mutex_enter(mem0.mutex);\n}\n\n/*\n** Do a memory allocation with statistics and alarms.  Assume the\n** lock is already held.\n*/\nstatic void mallocWithAlarm(int n, void **pp){\n  void *p;\n  int nFull;\n  assert( sqlite3_mutex_held(mem0.mutex) );\n  assert( n>0 );\n\n  /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal\n  ** implementation of malloc_good_size(), which must be called in debug\n  ** mode and specifically when the DMD \"Dark Matter Detector\" is enabled\n  ** or else a crash results.  Hence, do not attempt to optimize out the\n  ** following xRoundup() call. */\n  nFull = sqlite3GlobalConfig.m.xRoundup(n);\n\n  sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);\n  if( mem0.alarmThreshold>0 ){\n    sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);\n    if( nUsed >= mem0.alarmThreshold - nFull ){\n      AtomicStore(&mem0.nearlyFull, 1);\n      sqlite3MallocAlarm(nFull);\n      if( mem0.hardLimit ){\n        nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);\n        if( nUsed >= mem0.hardLimit - nFull ){\n          *pp = 0;\n          return;\n        }\n      }\n    }else{\n      AtomicStore(&mem0.nearlyFull, 0);\n    }\n  }\n  p = sqlite3GlobalConfig.m.xMalloc(nFull);\n#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT\n  if( p==0 && mem0.alarmThreshold>0 ){\n    sqlite3MallocAlarm(nFull);\n    p = sqlite3GlobalConfig.m.xMalloc(nFull);\n  }\n#endif\n  if( p ){\n    nFull = sqlite3MallocSize(p);\n    sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);\n    sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);\n  }\n  *pp = p;\n}\n\n/*\n** Allocate memory.  This routine is like sqlite3_malloc() except that it\n** assumes the memory subsystem has already been initialized.\n*/\nSQLITE_PRIVATE void *sqlite3Malloc(u64 n){\n  void *p;\n  if( n==0 || n>=0x7fffff00 ){\n    /* A memory allocation of a number of bytes which is near the maximum\n    ** signed integer value might cause an integer overflow inside of the\n    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving\n    ** 255 bytes of overhead.  SQLite itself will never use anything near\n    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */\n    p = 0;\n  }else if( sqlite3GlobalConfig.bMemstat ){\n    sqlite3_mutex_enter(mem0.mutex);\n    mallocWithAlarm((int)n, &p);\n    sqlite3_mutex_leave(mem0.mutex);\n  }else{\n    p = sqlite3GlobalConfig.m.xMalloc((int)n);\n  }\n  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */\n  return p;\n}\n\n/*\n** This version of the memory allocation is for use by the application.\n** First make sure the memory subsystem is initialized, then do the\n** allocation.\n*/\nSQLITE_API void *sqlite3_malloc(int n){\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  return n<=0 ? 0 : sqlite3Malloc(n);\n}\nSQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  return sqlite3Malloc(n);\n}\n\n/*\n** TRUE if p is a lookaside memory allocation from db\n*/\n#ifndef SQLITE_OMIT_LOOKASIDE\nstatic int isLookaside(sqlite3 *db, void *p){\n  return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);\n}\n#else\n#define isLookaside(A,B) 0\n#endif\n\n/*\n** Return the size of a memory allocation previously obtained from\n** sqlite3Malloc() or sqlite3_malloc().\n*/\nSQLITE_PRIVATE int sqlite3MallocSize(void *p){\n  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );\n  return sqlite3GlobalConfig.m.xSize(p);\n}\nstatic int lookasideMallocSize(sqlite3 *db, void *p){\n#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE    \n  return p<db->lookaside.pMiddle ? db->lookaside.szTrue : LOOKASIDE_SMALL;\n#else\n  return db->lookaside.szTrue;\n#endif  \n}\nSQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){\n  assert( p!=0 );\n#ifdef SQLITE_DEBUG\n  if( db==0 || !isLookaside(db,p) ){\n    if( db==0 ){\n      assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );\n      assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );\n    }else{\n      assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );\n      assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );\n    }\n  }\n#endif\n  if( db ){\n    if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){\n#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE\n      if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){\n        assert( sqlite3_mutex_held(db->mutex) );\n        return LOOKASIDE_SMALL;\n      }\n#endif\n      if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){\n        assert( sqlite3_mutex_held(db->mutex) );\n        return db->lookaside.szTrue;\n      }\n    }\n  }\n  return sqlite3GlobalConfig.m.xSize(p);\n}\nSQLITE_API sqlite3_uint64 sqlite3_msize(void *p){\n  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );\n  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );\n  return p ? sqlite3GlobalConfig.m.xSize(p) : 0;\n}\n\n/*\n** Free memory previously obtained from sqlite3Malloc().\n*/\nSQLITE_API void sqlite3_free(void *p){\n  if( p==0 ) return;  /* IMP: R-49053-54554 */\n  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );\n  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );\n  if( sqlite3GlobalConfig.bMemstat ){\n    sqlite3_mutex_enter(mem0.mutex);\n    sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));\n    sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);\n    sqlite3GlobalConfig.m.xFree(p);\n    sqlite3_mutex_leave(mem0.mutex);\n  }else{\n    sqlite3GlobalConfig.m.xFree(p);\n  }\n}\n\n/*\n** Add the size of memory allocation \"p\" to the count in\n** *db->pnBytesFreed.\n*/\nstatic SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){\n  *db->pnBytesFreed += sqlite3DbMallocSize(db,p);\n}\n\n/*\n** Free memory that might be associated with a particular database\n** connection.  Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.\n** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.\n*/\nSQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){\n  assert( db==0 || sqlite3_mutex_held(db->mutex) );\n  assert( p!=0 );\n  if( db ){\n    if( db->pnBytesFreed ){\n      measureAllocationSize(db, p);\n      return;\n    }\n    if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){\n#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE\n      if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){\n        LookasideSlot *pBuf = (LookasideSlot*)p;\n#ifdef SQLITE_DEBUG\n        memset(p, 0xaa, LOOKASIDE_SMALL);  /* Trash freed content */\n#endif\n        pBuf->pNext = db->lookaside.pSmallFree;\n        db->lookaside.pSmallFree = pBuf;\n        return;\n      }\n#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */\n      if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){\n        LookasideSlot *pBuf = (LookasideSlot*)p;\n#ifdef SQLITE_DEBUG\n        memset(p, 0xaa, db->lookaside.szTrue);  /* Trash freed content */\n#endif\n        pBuf->pNext = db->lookaside.pFree;\n        db->lookaside.pFree = pBuf;\n        return;\n      }\n    }\n  }\n  assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );\n  assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );\n  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );\n  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);\n  sqlite3_free(p);\n}\nSQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){\n  assert( db==0 || sqlite3_mutex_held(db->mutex) );\n  if( p ) sqlite3DbFreeNN(db, p);\n}\n\n/*\n** Change the size of an existing memory allocation\n*/\nSQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){\n  int nOld, nNew, nDiff;\n  void *pNew;\n  assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );\n  assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );\n  if( pOld==0 ){\n    return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */\n  }\n  if( nBytes==0 ){\n    sqlite3_free(pOld); /* IMP: R-26507-47431 */\n    return 0;\n  }\n  if( nBytes>=0x7fffff00 ){\n    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */\n    return 0;\n  }\n  nOld = sqlite3MallocSize(pOld);\n  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second\n  ** argument to xRealloc is always a value returned by a prior call to\n  ** xRoundup. */\n  nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);\n  if( nOld==nNew ){\n    pNew = pOld;\n  }else if( sqlite3GlobalConfig.bMemstat ){\n    sqlite3_mutex_enter(mem0.mutex);\n    sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);\n    nDiff = nNew - nOld;\n    if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= \n          mem0.alarmThreshold-nDiff ){\n      sqlite3MallocAlarm(nDiff);\n    }\n    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);\n#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT\n    if( pNew==0 && mem0.alarmThreshold>0 ){\n      sqlite3MallocAlarm((int)nBytes);\n      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);\n    }\n#endif\n    if( pNew ){\n      nNew = sqlite3MallocSize(pNew);\n      sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);\n    }\n    sqlite3_mutex_leave(mem0.mutex);\n  }else{\n    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);\n  }\n  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */\n  return pNew;\n}\n\n/*\n** The public interface to sqlite3Realloc.  Make sure that the memory\n** subsystem is initialized prior to invoking sqliteRealloc.\n*/\nSQLITE_API void *sqlite3_realloc(void *pOld, int n){\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  if( n<0 ) n = 0;  /* IMP: R-26507-47431 */\n  return sqlite3Realloc(pOld, n);\n}\nSQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  return sqlite3Realloc(pOld, n);\n}\n\n\n/*\n** Allocate and zero memory.\n*/ \nSQLITE_PRIVATE void *sqlite3MallocZero(u64 n){\n  void *p = sqlite3Malloc(n);\n  if( p ){\n    memset(p, 0, (size_t)n);\n  }\n  return p;\n}\n\n/*\n** Allocate and zero memory.  If the allocation fails, make\n** the mallocFailed flag in the connection pointer.\n*/\nSQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){\n  void *p;\n  testcase( db==0 );\n  p = sqlite3DbMallocRaw(db, n);\n  if( p ) memset(p, 0, (size_t)n);\n  return p;\n}\n\n\n/* Finish the work of sqlite3DbMallocRawNN for the unusual and\n** slower case when the allocation cannot be fulfilled using lookaside.\n*/\nstatic SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){\n  void *p;\n  assert( db!=0 );\n  p = sqlite3Malloc(n);\n  if( !p ) sqlite3OomFault(db);\n  sqlite3MemdebugSetType(p, \n         (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);\n  return p;\n}\n\n/*\n** Allocate memory, either lookaside (if possible) or heap.  \n** If the allocation fails, set the mallocFailed flag in\n** the connection pointer.\n**\n** If db!=0 and db->mallocFailed is true (indicating a prior malloc\n** failure on the same database connection) then always return 0.\n** Hence for a particular database connection, once malloc starts\n** failing, it fails consistently until mallocFailed is reset.\n** This is an important assumption.  There are many places in the\n** code that do things like this:\n**\n**         int *a = (int*)sqlite3DbMallocRaw(db, 100);\n**         int *b = (int*)sqlite3DbMallocRaw(db, 200);\n**         if( b ) a[10] = 9;\n**\n** In other words, if a subsequent malloc (ex: \"b\") worked, it is assumed\n** that all prior mallocs (ex: \"a\") worked too.\n**\n** The sqlite3MallocRawNN() variant guarantees that the \"db\" parameter is\n** not a NULL pointer.\n*/\nSQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){\n  void *p;\n  if( db ) return sqlite3DbMallocRawNN(db, n);\n  p = sqlite3Malloc(n);\n  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);\n  return p;\n}\nSQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){\n#ifndef SQLITE_OMIT_LOOKASIDE\n  LookasideSlot *pBuf;\n  assert( db!=0 );\n  assert( sqlite3_mutex_held(db->mutex) );\n  assert( db->pnBytesFreed==0 );\n  if( n>db->lookaside.sz ){\n    if( !db->lookaside.bDisable ){\n      db->lookaside.anStat[1]++;      \n    }else if( db->mallocFailed ){\n      return 0;\n    }\n    return dbMallocRawFinish(db, n);\n  }\n#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE\n  if( n<=LOOKASIDE_SMALL ){\n    if( (pBuf = db->lookaside.pSmallFree)!=0 ){\n      db->lookaside.pSmallFree = pBuf->pNext;\n      db->lookaside.anStat[0]++;\n      return (void*)pBuf;\n    }else if( (pBuf = db->lookaside.pSmallInit)!=0 ){\n      db->lookaside.pSmallInit = pBuf->pNext;\n      db->lookaside.anStat[0]++;\n      return (void*)pBuf;\n    }\n  }\n#endif\n  if( (pBuf = db->lookaside.pFree)!=0 ){\n    db->lookaside.pFree = pBuf->pNext;\n    db->lookaside.anStat[0]++;\n    return (void*)pBuf;\n  }else if( (pBuf = db->lookaside.pInit)!=0 ){\n    db->lookaside.pInit = pBuf->pNext;\n    db->lookaside.anStat[0]++;\n    return (void*)pBuf;\n  }else{\n    db->lookaside.anStat[2]++;\n  }\n#else\n  assert( db!=0 );\n  assert( sqlite3_mutex_held(db->mutex) );\n  assert( db->pnBytesFreed==0 );\n  if( db->mallocFailed ){\n    return 0;\n  }\n#endif\n  return dbMallocRawFinish(db, n);\n}\n\n/* Forward declaration */\nstatic SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);\n\n/*\n** Resize the block of memory pointed to by p to n bytes. If the\n** resize fails, set the mallocFailed flag in the connection object.\n*/\nSQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){\n  assert( db!=0 );\n  if( p==0 ) return sqlite3DbMallocRawNN(db, n);\n  assert( sqlite3_mutex_held(db->mutex) );\n  if( ((uptr)p)<(uptr)db->lookaside.pEnd ){\n#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE\n    if( ((uptr)p)>=(uptr)db->lookaside.pMiddle ){\n      if( n<=LOOKASIDE_SMALL ) return p;\n    }else\n#endif\n    if( ((uptr)p)>=(uptr)db->lookaside.pStart ){\n      if( n<=db->lookaside.szTrue ) return p;\n    }\n  }\n  return dbReallocFinish(db, p, n);\n}\nstatic SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){\n  void *pNew = 0;\n  assert( db!=0 );\n  assert( p!=0 );\n  if( db->mallocFailed==0 ){\n    if( isLookaside(db, p) ){\n      pNew = sqlite3DbMallocRawNN(db, n);\n      if( pNew ){\n        memcpy(pNew, p, lookasideMallocSize(db, p));\n        sqlite3DbFree(db, p);\n      }\n    }else{\n      assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );\n      assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );\n      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);\n      pNew = sqlite3Realloc(p, n);\n      if( !pNew ){\n        sqlite3OomFault(db);\n      }\n      sqlite3MemdebugSetType(pNew,\n            (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));\n    }\n  }\n  return pNew;\n}\n\n/*\n** Attempt to reallocate p.  If the reallocation fails, then free p\n** and set the mallocFailed flag in the database connection.\n*/\nSQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){\n  void *pNew;\n  pNew = sqlite3DbRealloc(db, p, n);\n  if( !pNew ){\n    sqlite3DbFree(db, p);\n  }\n  return pNew;\n}\n\n/*\n** Make a copy of a string in memory obtained from sqliteMalloc(). These \n** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This\n** is because when memory debugging is turned on, these two functions are \n** called via macros that record the current file and line number in the\n** ThreadData structure.\n*/\nSQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){\n  char *zNew;\n  size_t n;\n  if( z==0 ){\n    return 0;\n  }\n  n = strlen(z) + 1;\n  zNew = sqlite3DbMallocRaw(db, n);\n  if( zNew ){\n    memcpy(zNew, z, n);\n  }\n  return zNew;\n}\nSQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){\n  char *zNew;\n  assert( db!=0 );\n  if( z==0 ){\n    return 0;\n  }\n  assert( (n&0x7fffffff)==n );\n  zNew = sqlite3DbMallocRawNN(db, n+1);\n  if( zNew ){\n    memcpy(zNew, z, (size_t)n);\n    zNew[n] = 0;\n  }\n  return zNew;\n}\n\n/*\n** The text between zStart and zEnd represents a phrase within a larger\n** SQL statement.  Make a copy of this phrase in space obtained form\n** sqlite3DbMalloc().  Omit leading and trailing whitespace.\n*/\nSQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){\n  int n;\n  while( sqlite3Isspace(zStart[0]) ) zStart++;\n  n = (int)(zEnd - zStart);\n  while( ALWAYS(n>0) && sqlite3Isspace(zStart[n-1]) ) n--;\n  return sqlite3DbStrNDup(db, zStart, n);\n}\n\n/*\n** Free any prior content in *pz and replace it with a copy of zNew.\n*/\nSQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){\n  sqlite3DbFree(db, *pz);\n  *pz = sqlite3DbStrDup(db, zNew);\n}\n\n/*\n** Call this routine to record the fact that an OOM (out-of-memory) error\n** has happened.  This routine will set db->mallocFailed, and also\n** temporarily disable the lookaside memory allocator and interrupt\n** any running VDBEs.\n*/\nSQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){\n  if( db->mallocFailed==0 && db->bBenignMalloc==0 ){\n    db->mallocFailed = 1;\n    if( db->nVdbeExec>0 ){\n      AtomicStore(&db->u1.isInterrupted, 1);\n    }\n    DisableLookaside;\n    if( db->pParse ){\n      db->pParse->rc = SQLITE_NOMEM_BKPT;\n    }\n  }\n}\n\n/*\n** This routine reactivates the memory allocator and clears the\n** db->mallocFailed flag as necessary.\n**\n** The memory allocator is not restarted if there are running\n** VDBEs.\n*/\nSQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){\n  if( db->mallocFailed && db->nVdbeExec==0 ){\n    db->mallocFailed = 0;\n    AtomicStore(&db->u1.isInterrupted, 0);\n    assert( db->lookaside.bDisable>0 );\n    EnableLookaside;\n  }\n}\n\n/*\n** Take actions at the end of an API call to indicate an OOM error\n*/\nstatic SQLITE_NOINLINE int apiOomError(sqlite3 *db){\n  sqlite3OomClear(db);\n  sqlite3Error(db, SQLITE_NOMEM);\n  return SQLITE_NOMEM_BKPT;\n}\n\n/*\n** This function must be called before exiting any API function (i.e. \n** returning control to the user) that has called sqlite3_malloc or\n** sqlite3_realloc.\n**\n** The returned value is normally a copy of the second argument to this\n** function. However, if a malloc() failure has occurred since the previous\n** invocation SQLITE_NOMEM is returned instead. \n**\n** If an OOM as occurred, then the connection error-code (the value\n** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.\n*/\nSQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){\n  /* If the db handle must hold the connection handle mutex here.\n  ** Otherwise the read (and possible write) of db->mallocFailed \n  ** is unsafe, as is the call to sqlite3Error().\n  */\n  assert( db!=0 );\n  assert( sqlite3_mutex_held(db->mutex) );\n  if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){\n    return apiOomError(db);\n  }\n  return rc & db->errMask;\n}\n\n/************** End of malloc.c **********************************************/\n/************** Begin file printf.c ******************************************/\n/*\n** The \"printf\" code that follows dates from the 1980's.  It is in\n** the public domain. \n**\n**************************************************************************\n**\n** This file contains code for a set of \"printf\"-like routines.  These\n** routines format strings much like the printf() from the standard C\n** library, though the implementation here has enhancements to support\n** SQLite.\n*/\n/* #include \"sqliteInt.h\" */\n\n/*\n** Conversion types fall into various categories as defined by the\n** following enumeration.\n*/\n#define etRADIX       0 /* non-decimal integer types.  %x %o */\n#define etFLOAT       1 /* Floating point.  %f */\n#define etEXP         2 /* Exponentional notation. %e and %E */\n#define etGENERIC     3 /* Floating or exponential, depending on exponent. %g */\n#define etSIZE        4 /* Return number of characters processed so far. %n */\n#define etSTRING      5 /* Strings. %s */\n#define etDYNSTRING   6 /* Dynamically allocated strings. %z */\n#define etPERCENT     7 /* Percent symbol. %% */\n#define etCHARX       8 /* Characters. %c */\n/* The rest are extensions, not normally found in printf() */\n#define etSQLESCAPE   9 /* Strings with '\\'' doubled.  %q */\n#define etSQLESCAPE2 10 /* Strings with '\\'' doubled and enclosed in '',\n                          NULL pointers replaced by SQL NULL.  %Q */\n#define etTOKEN      11 /* a pointer to a Token structure */\n#define etSRCLIST    12 /* a pointer to a SrcList */\n#define etPOINTER    13 /* The %p conversion */\n#define etSQLESCAPE3 14 /* %w -> Strings with '\\\"' doubled */\n#define etORDINAL    15 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */\n#define etDECIMAL    16 /* %d or %u, but not %x, %o */\n\n#define etINVALID    17 /* Any unrecognized conversion type */\n\n\n/*\n** An \"etByte\" is an 8-bit unsigned value.\n*/\ntypedef unsigned char etByte;\n\n/*\n** Each builtin conversion character (ex: the 'd' in \"%d\") is described\n** by an instance of the following structure\n*/\ntypedef struct et_info {   /* Information about each format field */\n  char fmttype;            /* The format field code letter */\n  etByte base;             /* The base for radix conversion */\n  etByte flags;            /* One or more of FLAG_ constants below */\n  etByte type;             /* Conversion paradigm */\n  etByte charset;          /* Offset into aDigits[] of the digits string */\n  etByte prefix;           /* Offset into aPrefix[] of the prefix string */\n} et_info;\n\n/*\n** Allowed values for et_info.flags\n*/\n#define FLAG_SIGNED    1     /* True if the value to convert is signed */\n#define FLAG_STRING    4     /* Allow infinite precision */\n\n\n/*\n** The following table is searched linearly, so it is good to put the\n** most frequently used conversion types first.\n*/\nstatic const char aDigits[] = \"0123456789ABCDEF0123456789abcdef\";\nstatic const char aPrefix[] = \"-x0\\000X0\";\nstatic const et_info fmtinfo[] = {\n  {  'd', 10, 1, etDECIMAL,    0,  0 },\n  {  's',  0, 4, etSTRING,     0,  0 },\n  {  'g',  0, 1, etGENERIC,    30, 0 },\n  {  'z',  0, 4, etDYNSTRING,  0,  0 },\n  {  'q',  0, 4, etSQLESCAPE,  0,  0 },\n  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },\n  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },\n  {  'c',  0, 0, etCHARX,      0,  0 },\n  {  'o',  8, 0, etRADIX,      0,  2 },\n  {  'u', 10, 0, etDECIMAL,    0,  0 },\n  {  'x', 16, 0, etRADIX,      16, 1 },\n  {  'X', 16, 0, etRADIX,      0,  4 },\n#ifndef SQLITE_OMIT_FLOATING_POINT\n  {  'f',  0, 1, etFLOAT,      0,  0 },\n  {  'e',  0, 1, etEXP,        30, 0 },\n  {  'E',  0, 1, etEXP,        14, 0 },\n  {  'G',  0, 1, etGENERIC,    14, 0 },\n#endif\n  {  'i', 10, 1, etDECIMAL,    0,  0 },\n  {  'n',  0, 0, etSIZE,       0,  0 },\n  {  '%',  0, 0, etPERCENT,    0,  0 },\n  {  'p', 16, 0, etPOINTER,    0,  1 },\n\n  /* All the rest are undocumented and are for internal use only */\n  {  'T',  0, 0, etTOKEN,      0,  0 },\n  {  'S',  0, 0, etSRCLIST,    0,  0 },\n  {  'r', 10, 1, etORDINAL,    0,  0 },\n};\n\n/* Floating point constants used for rounding */\nstatic const double arRound[] = {\n  5.0e-01, 5.0e-02, 5.0e-03, 5.0e-04, 5.0e-05,\n  5.0e-06, 5.0e-07, 5.0e-08, 5.0e-09, 5.0e-10,\n};\n\n/*\n** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point\n** conversions will work.\n*/\n#ifndef SQLITE_OMIT_FLOATING_POINT\n/*\n** \"*val\" is a double such that 0.1 <= *val < 10.0\n** Return the ascii code for the leading digit of *val, then\n** multiply \"*val\" by 10.0 to renormalize.\n**\n** Example:\n**     input:     *val = 3.14159\n**     output:    *val = 1.4159    function return = '3'\n**\n** The counter *cnt is incremented each time.  After counter exceeds\n** 16 (the number of significant digits in a 64-bit float) '0' is\n** always returned.\n*/\nstatic char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){\n  int digit;\n  LONGDOUBLE_TYPE d;\n  if( (*cnt)<=0 ) return '0';\n  (*cnt)--;\n  digit = (int)*val;\n  d = digit;\n  digit += '0';\n  *val = (*val - d)*10.0;\n  return (char)digit;\n}\n#endif /* SQLITE_OMIT_FLOATING_POINT */\n\n/*\n** Set the StrAccum object to an error mode.\n*/\nstatic void setStrAccumError(StrAccum *p, u8 eError){\n  assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );\n  p->accError = eError;\n  if( p->mxAlloc ) sqlite3_str_reset(p);\n  if( eError==SQLITE_TOOBIG ) sqlite3ErrorToParser(p->db, eError);\n}\n\n/*\n** Extra argument values from a PrintfArguments object\n*/\nstatic sqlite3_int64 getIntArg(PrintfArguments *p){\n  if( p->nArg<=p->nUsed ) return 0;\n  return sqlite3_value_int64(p->apArg[p->nUsed++]);\n}\nstatic double getDoubleArg(PrintfArguments *p){\n  if( p->nArg<=p->nUsed ) return 0.0;\n  return sqlite3_value_double(p->apArg[p->nUsed++]);\n}\nstatic char *getTextArg(PrintfArguments *p){\n  if( p->nArg<=p->nUsed ) return 0;\n  return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);\n}\n\n/*\n** Allocate memory for a temporary buffer needed for printf rendering.\n**\n** If the requested size of the temp buffer is larger than the size\n** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error.\n** Do the size check before the memory allocation to prevent rogue\n** SQL from requesting large allocations using the precision or width\n** field of the printf() function.\n*/\nstatic char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){\n  char *z;\n  if( pAccum->accError ) return 0;\n  if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){\n    setStrAccumError(pAccum, SQLITE_TOOBIG);\n    return 0;\n  }\n  z = sqlite3DbMallocRaw(pAccum->db, n);\n  if( z==0 ){\n    setStrAccumError(pAccum, SQLITE_NOMEM);\n  }\n  return z;\n}\n\n/*\n** On machines with a small stack size, you can redefine the\n** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.\n*/\n#ifndef SQLITE_PRINT_BUF_SIZE\n# define SQLITE_PRINT_BUF_SIZE 70\n#endif\n#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */\n\n/*\n** Hard limit on the precision of floating-point conversions.\n*/\n#ifndef SQLITE_PRINTF_PRECISION_LIMIT\n# define SQLITE_FP_PRECISION_LIMIT 100000000\n#endif\n\n/*\n** Render a string given by \"fmt\" into the StrAccum object.\n*/\nSQLITE_API void sqlite3_str_vappendf(\n  sqlite3_str *pAccum,       /* Accumulate results here */\n  const char *fmt,           /* Format string */\n  va_list ap                 /* arguments */\n){\n  int c;                     /* Next character in the format string */\n  char *bufpt;               /* Pointer to the conversion buffer */\n  int precision;             /* Precision of the current field */\n  int length;                /* Length of the field */\n  int idx;                   /* A general purpose loop counter */\n  int width;                 /* Width of the current field */\n  etByte flag_leftjustify;   /* True if \"-\" flag is present */\n  etByte flag_prefix;        /* '+' or ' ' or 0 for prefix */\n  etByte flag_alternateform; /* True if \"#\" flag is present */\n  etByte flag_altform2;      /* True if \"!\" flag is present */\n  etByte flag_zeropad;       /* True if field width constant starts with zero */\n  etByte flag_long;          /* 1 for the \"l\" flag, 2 for \"ll\", 0 by default */\n  etByte done;               /* Loop termination flag */\n  etByte cThousand;          /* Thousands separator for %d and %u */\n  etByte xtype = etINVALID;  /* Conversion paradigm */\n  u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */\n  char prefix;               /* Prefix character.  \"+\" or \"-\" or \" \" or '\\0'. */\n  sqlite_uint64 longvalue;   /* Value for integer types */\n  LONGDOUBLE_TYPE realvalue; /* Value for real types */\n  const et_info *infop;      /* Pointer to the appropriate info structure */\n  char *zOut;                /* Rendering buffer */\n  int nOut;                  /* Size of the rendering buffer */\n  char *zExtra = 0;          /* Malloced memory used by some conversion */\n#ifndef SQLITE_OMIT_FLOATING_POINT\n  int  exp, e2;              /* exponent of real numbers */\n  int nsd;                   /* Number of significant digits returned */\n  double rounder;            /* Used for rounding floating point values */\n  etByte flag_dp;            /* True if decimal point should be shown */\n  etByte flag_rtz;           /* True if trailing zeros should be removed */\n#endif\n  PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */\n  char buf[etBUFSIZE];       /* Conversion buffer */\n\n  /* pAccum never starts out with an empty buffer that was obtained from \n  ** malloc().  This precondition is required by the mprintf(\"%z...\")\n  ** optimization. */\n  assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );\n\n  bufpt = 0;\n  if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){\n    pArgList = va_arg(ap, PrintfArguments*);\n    bArgList = 1;\n  }else{\n    bArgList = 0;\n  }\n  for(; (c=(*fmt))!=0; ++fmt){\n    if( c!='%' ){\n      bufpt = (char *)fmt;\n#if HAVE_STRCHRNUL\n      fmt = strchrnul(fmt, '%');\n#else\n      do{ fmt++; }while( *fmt && *fmt != '%' );\n#endif\n      sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));\n      if( *fmt==0 ) break;\n    }\n    if( (c=(*++fmt))==0 ){\n      sqlite3_str_append(pAccum, \"%\", 1);\n      break;\n    }\n    /* Find out what flags are present */\n    flag_leftjustify = flag_prefix = cThousand =\n     flag_alternateform = flag_altform2 = flag_zeropad = 0;\n    done = 0;\n    width = 0;\n    flag_long = 0;\n    precision = -1;\n    do{\n      switch( c ){\n        case '-':   flag_leftjustify = 1;     break;\n        case '+':   flag_prefix = '+';        break;\n        case ' ':   flag_prefix = ' ';        break;\n        case '#':   flag_alternateform = 1;   break;\n        case '!':   flag_altform2 = 1;        break;\n        case '0':   flag_zeropad = 1;         break;\n        case ',':   cThousand = ',';          break;\n        default:    done = 1;                 break;\n        case 'l': {\n          flag_long = 1;\n          c = *++fmt;\n          if( c=='l' ){\n            c = *++fmt;\n            flag_long = 2;\n          }\n          done = 1;\n          break;\n        }\n        case '1': case '2': case '3': case '4': case '5':\n        case '6': case '7': case '8': case '9': {\n          unsigned wx = c - '0';\n          while( (c = *++fmt)>='0' && c<='9' ){\n            wx = wx*10 + c - '0';\n          }\n          testcase( wx>0x7fffffff );\n          width = wx & 0x7fffffff;\n#ifdef SQLITE_PRINTF_PRECISION_LIMIT\n          if( width>SQLITE_PRINTF_PRECISION_LIMIT ){\n            width = SQLITE_PRINTF_PRECISION_LIMIT;\n          }\n#endif\n          if( c!='.' && c!='l' ){\n            done = 1;\n          }else{\n            fmt--;\n          }\n          break;\n        }\n        case '*': {\n          if( bArgList ){\n            width = (int)getIntArg(pArgList);\n          }else{\n            width = va_arg(ap,int);\n          }\n          if( width<0 ){\n            flag_leftjustify = 1;\n            width = width >= -2147483647 ? -width : 0;\n          }\n#ifdef SQLITE_PRINTF_PRECISION_LIMIT\n          if( width>SQLITE_PRINTF_PRECISION_LIMIT ){\n            width = SQLITE_PRINTF_PRECISION_LIMIT;\n          }\n#endif\n          if( (c = fmt[1])!='.' && c!='l' ){\n            c = *++fmt;\n            done = 1;\n          }\n          break;\n        }\n        case '.': {\n          c = *++fmt;\n          if( c=='*' ){\n            if( bArgList ){\n              precision = (int)getIntArg(pArgList);\n            }else{\n              precision = va_arg(ap,int);\n            }\n            if( precision<0 ){\n              precision = precision >= -2147483647 ? -precision : -1;\n            }\n            c = *++fmt;\n          }else{\n            unsigned px = 0;\n            while( c>='0' && c<='9' ){\n              px = px*10 + c - '0';\n              c = *++fmt;\n            }\n            testcase( px>0x7fffffff );\n            precision = px & 0x7fffffff;\n          }\n#ifdef SQLITE_PRINTF_PRECISION_LIMIT\n          if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){\n            precision = SQLITE_PRINTF_PRECISION_LIMIT;\n          }\n#endif\n          if( c=='l' ){\n            --fmt;\n          }else{\n            done = 1;\n          }\n          break;\n        }\n      }\n    }while( !done && (c=(*++fmt))!=0 );\n\n    /* Fetch the info entry for the field */\n    infop = &fmtinfo[0];\n    xtype = etINVALID;\n    for(idx=0; idx<ArraySize(fmtinfo); idx++){\n      if( c==fmtinfo[idx].fmttype ){\n        infop = &fmtinfo[idx];\n        xtype = infop->type;\n        break;\n      }\n    }\n\n    /*\n    ** At this point, variables are initialized as follows:\n    **\n    **   flag_alternateform          TRUE if a '#' is present.\n    **   flag_altform2               TRUE if a '!' is present.\n    **   flag_prefix                 '+' or ' ' or zero\n    **   flag_leftjustify            TRUE if a '-' is present or if the\n    **                               field width was negative.\n    **   flag_zeropad                TRUE if the width began with 0.\n    **   flag_long                   1 for \"l\", 2 for \"ll\"\n    **   width                       The specified field width.  This is\n    **                               always non-negative.  Zero is the default.\n    **   precision                   The specified precision.  The default\n    **                               is -1.\n    **   xtype                       The class of the conversion.\n    **   infop                       Pointer to the appropriate info struct.\n    */\n    assert( width>=0 );\n    assert( precision>=(-1) );\n    switch( xtype ){\n      case etPOINTER:\n        flag_long = sizeof(char*)==sizeof(i64) ? 2 :\n                     sizeof(char*)==sizeof(long int) ? 1 : 0;\n        /* Fall through into the next case */\n      case etORDINAL:\n      case etRADIX:      \n        cThousand = 0;\n        /* Fall through into the next case */\n      case etDECIMAL:\n        if( infop->flags & FLAG_SIGNED ){\n          i64 v;\n          if( bArgList ){\n            v = getIntArg(pArgList);\n          }else if( flag_long ){\n            if( flag_long==2 ){\n              v = va_arg(ap,i64) ;\n            }else{\n              v = va_arg(ap,long int);\n            }\n          }else{\n            v = va_arg(ap,int);\n          }\n          if( v<0 ){\n            if( v==SMALLEST_INT64 ){\n              longvalue = ((u64)1)<<63;\n            }else{\n              longvalue = -v;\n            }\n            prefix = '-';\n          }else{\n            longvalue = v;\n            prefix = flag_prefix;\n          }\n        }else{\n          if( bArgList ){\n            longvalue = (u64)getIntArg(pArgList);\n          }else if( flag_long ){\n            if( flag_long==2 ){\n              longvalue = va_arg(ap,u64);\n            }else{\n              longvalue = va_arg(ap,unsigned long int);\n            }\n          }else{\n            longvalue = va_arg(ap,unsigned int);\n          }\n          prefix = 0;\n        }\n        if( longvalue==0 ) flag_alternateform = 0;\n        if( flag_zeropad && precision<width-(prefix!=0) ){\n          precision = width-(prefix!=0);\n        }\n        if( precision<etBUFSIZE-10-etBUFSIZE/3 ){\n          nOut = etBUFSIZE;\n          zOut = buf;\n        }else{\n          u64 n;\n          n = (u64)precision + 10;\n          if( cThousand ) n += precision/3;\n          zOut = zExtra = printfTempBuf(pAccum, n);\n          if( zOut==0 ) return;\n          nOut = (int)n;\n        }\n        bufpt = &zOut[nOut-1];\n        if( xtype==etORDINAL ){\n          static const char zOrd[] = \"thstndrd\";\n          int x = (int)(longvalue % 10);\n          if( x>=4 || (longvalue/10)%10==1 ){\n            x = 0;\n          }\n          *(--bufpt) = zOrd[x*2+1];\n          *(--bufpt) = zOrd[x*2];\n        }\n        {\n          const char *cset = &aDigits[infop->charset];\n          u8 base = infop->base;\n          do{                                           /* Convert to ascii */\n            *(--bufpt) = cset[longvalue%base];\n            longvalue = longvalue/base;\n          }while( longvalue>0 );\n        }\n        length = (int)(&zOut[nOut-1]-bufpt);\n        while( precision>length ){\n          *(--bufpt) = '0';                             /* Zero pad */\n          length++;\n        }\n        if( cThousand ){\n          int nn = (length - 1)/3;  /* Number of \",\" to insert */\n          int ix = (length - 1)%3 + 1;\n          bufpt -= nn;\n          for(idx=0; nn>0; idx++){\n            bufpt[idx] = bufpt[idx+nn];\n            ix--;\n            if( ix==0 ){\n              bufpt[++idx] = cThousand;\n              nn--;\n              ix = 3;\n            }\n          }\n        }\n        if( prefix ) *(--bufpt) = prefix;               /* Add sign */\n        if( flag_alternateform && infop->prefix ){      /* Add \"0\" or \"0x\" */\n          const char *pre;\n          char x;\n          pre = &aPrefix[infop->prefix];\n          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;\n        }\n        length = (int)(&zOut[nOut-1]-bufpt);\n        break;\n      case etFLOAT:\n      case etEXP:\n      case etGENERIC:\n        if( bArgList ){\n          realvalue = getDoubleArg(pArgList);\n        }else{\n          realvalue = va_arg(ap,double);\n        }\n#ifdef SQLITE_OMIT_FLOATING_POINT\n        length = 0;\n#else\n        if( precision<0 ) precision = 6;         /* Set default precision */\n#ifdef SQLITE_FP_PRECISION_LIMIT\n        if( precision>SQLITE_FP_PRECISION_LIMIT ){\n          precision = SQLITE_FP_PRECISION_LIMIT;\n        }\n#endif\n        if( realvalue<0.0 ){\n          realvalue = -realvalue;\n          prefix = '-';\n        }else{\n          prefix = flag_prefix;\n        }\n        if( xtype==etGENERIC && precision>0 ) precision--;\n        testcase( precision>0xfff );\n        idx = precision & 0xfff;\n        rounder = arRound[idx%10];\n        while( idx>=10 ){ rounder *= 1.0e-10; idx -= 10; }\n        if( xtype==etFLOAT ){\n          double rx = (double)realvalue;\n          sqlite3_uint64 u;\n          int ex;\n          memcpy(&u, &rx, sizeof(u));\n          ex = -1023 + (int)((u>>52)&0x7ff);\n          if( precision+(ex/3) < 15 ) rounder += realvalue*3e-16;\n          realvalue += rounder;\n        }\n        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */\n        exp = 0;\n        if( sqlite3IsNaN((double)realvalue) ){\n          bufpt = \"NaN\";\n          length = 3;\n          break;\n        }\n        if( realvalue>0.0 ){\n          LONGDOUBLE_TYPE scale = 1.0;\n          while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}\n          while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }\n          while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }\n          realvalue /= scale;\n          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }\n          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }\n          if( exp>350 ){\n            bufpt = buf;\n            buf[0] = prefix;\n            memcpy(buf+(prefix!=0),\"Inf\",4);\n            length = 3+(prefix!=0);\n            break;\n          }\n        }\n        bufpt = buf;\n        /*\n        ** If the field type is etGENERIC, then convert to either etEXP\n        ** or etFLOAT, as appropriate.\n        */\n        if( xtype!=etFLOAT ){\n          realvalue += rounder;\n          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }\n        }\n        if( xtype==etGENERIC ){\n          flag_rtz = !flag_alternateform;\n          if( exp<-4 || exp>precision ){\n            xtype = etEXP;\n          }else{\n            precision = precision - exp;\n            xtype = etFLOAT;\n          }\n        }else{\n          flag_rtz = flag_altform2;\n        }\n        if( xtype==etEXP ){\n          e2 = 0;\n        }else{\n          e2 = exp;\n        }\n        {\n          i64 szBufNeeded;           /* Size of a temporary buffer needed */\n          szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;\n          if( szBufNeeded > etBUFSIZE ){\n            bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded);\n            if( bufpt==0 ) return;\n          }\n        }\n        zOut = bufpt;\n        nsd = 16 + flag_altform2*10;\n        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;\n        /* The sign in front of the number */\n        if( prefix ){\n          *(bufpt++) = prefix;\n        }\n        /* Digits prior to the decimal point */\n        if( e2<0 ){\n          *(bufpt++) = '0';\n        }else{\n          for(; e2>=0; e2--){\n            *(bufpt++) = et_getdigit(&realvalue,&nsd);\n          }\n        }\n        /* The decimal point */\n        if( flag_dp ){\n          *(bufpt++) = '.';\n        }\n        /* \"0\" digits after the decimal point but before the first\n        ** significant digit of the number */\n        for(e2++; e2<0; precision--, e2++){\n          assert( precision>0 );\n          *(bufpt++) = '0';\n        }\n        /* Significant digits after the decimal point */\n        while( (precision--)>0 ){\n          *(bufpt++) = et_getdigit(&realvalue,&nsd);\n        }\n        /* Remove trailing zeros and the \".\" if no digits follow the \".\" */\n        if( flag_rtz && flag_dp ){\n          while( bufpt[-1]=='0' ) *(--bufpt) = 0;\n          assert( bufpt>zOut );\n          if( bufpt[-1]=='.' ){\n            if( flag_altform2 ){\n              *(bufpt++) = '0';\n            }else{\n              *(--bufpt) = 0;\n            }\n          }\n        }\n        /* Add the \"eNNN\" suffix */\n        if( xtype==etEXP ){\n          *(bufpt++) = aDigits[infop->charset];\n          if( exp<0 ){\n            *(bufpt++) = '-'; exp = -exp;\n          }else{\n            *(bufpt++) = '+';\n          }\n          if( exp>=100 ){\n            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */\n            exp %= 100;\n          }\n          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */\n          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */\n        }\n        *bufpt = 0;\n\n        /* The converted number is in buf[] and zero terminated. Output it.\n        ** Note that the number is in the usual order, not reversed as with\n        ** integer conversions. */\n        length = (int)(bufpt-zOut);\n        bufpt = zOut;\n\n        /* Special case:  Add leading zeros if the flag_zeropad flag is\n        ** set and we are not left justified */\n        if( flag_zeropad && !flag_leftjustify && length < width){\n          int i;\n          int nPad = width - length;\n          for(i=width; i>=nPad; i--){\n            bufpt[i] = bufpt[i-nPad];\n          }\n          i = prefix!=0;\n          while( nPad-- ) bufpt[i++] = '0';\n          length = width;\n        }\n#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */\n        break;\n      case etSIZE:\n        if( !bArgList ){\n          *(va_arg(ap,int*)) = pAccum->nChar;\n        }\n        length = width = 0;\n        break;\n      case etPERCENT:\n        buf[0] = '%';\n        bufpt = buf;\n        length = 1;\n        break;\n      case etCHARX:\n        if( bArgList ){\n          bufpt = getTextArg(pArgList);\n          length = 1;\n          if( bufpt ){\n            buf[0] = c = *(bufpt++);\n            if( (c&0xc0)==0xc0 ){\n              while( length<4 && (bufpt[0]&0xc0)==0x80 ){\n                buf[length++] = *(bufpt++);\n              }\n            }\n          }else{\n            buf[0] = 0;\n          }\n        }else{\n          unsigned int ch = va_arg(ap,unsigned int);\n          if( ch<0x00080 ){\n            buf[0] = ch & 0xff;\n            length = 1;\n          }else if( ch<0x00800 ){\n            buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);\n            buf[1] = 0x80 + (u8)(ch & 0x3f);\n            length = 2;\n          }else if( ch<0x10000 ){\n            buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);\n            buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);\n            buf[2] = 0x80 + (u8)(ch & 0x3f);\n            length = 3;\n          }else{\n            buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);\n            buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);\n            buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);\n            buf[3] = 0x80 + (u8)(ch & 0x3f);\n            length = 4;\n          }\n        }\n        if( precision>1 ){\n          width -= precision-1;\n          if( width>1 && !flag_leftjustify ){\n            sqlite3_str_appendchar(pAccum, width-1, ' ');\n            width = 0;\n          }\n          while( precision-- > 1 ){\n            sqlite3_str_append(pAccum, buf, length);\n          }\n        }\n        bufpt = buf;\n        flag_altform2 = 1;\n        goto adjust_width_for_utf8;\n      case etSTRING:\n      case etDYNSTRING:\n        if( bArgList ){\n          bufpt = getTextArg(pArgList);\n          xtype = etSTRING;\n        }else{\n          bufpt = va_arg(ap,char*);\n        }\n        if( bufpt==0 ){\n          bufpt = \"\";\n        }else if( xtype==etDYNSTRING ){\n          if( pAccum->nChar==0\n           && pAccum->mxAlloc\n           && width==0\n           && precision<0\n           && pAccum->accError==0\n          ){\n            /* Special optimization for sqlite3_mprintf(\"%z...\"):\n            ** Extend an existing memory allocation rather than creating\n            ** a new one. */\n            assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );\n            pAccum->zText = bufpt;\n            pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);\n            pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);\n            pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;\n            length = 0;\n            break;\n          }\n          zExtra = bufpt;\n        }\n        if( precision>=0 ){\n          if( flag_altform2 ){\n            /* Set length to the number of bytes needed in order to display\n            ** precision characters */\n            unsigned char *z = (unsigned char*)bufpt;\n            while( precision-- > 0 && z[0] ){\n              SQLITE_SKIP_UTF8(z);\n            }\n            length = (int)(z - (unsigned char*)bufpt);\n          }else{\n            for(length=0; length<precision && bufpt[length]; length++){}\n          }\n        }else{\n          length = 0x7fffffff & (int)strlen(bufpt);\n        }\n      adjust_width_for_utf8:\n        if( flag_altform2 && width>0 ){\n          /* Adjust width to account for extra bytes in UTF-8 characters */\n          int ii = length - 1;\n          while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;\n        }\n        break;\n      case etSQLESCAPE:           /* %q: Escape ' characters */\n      case etSQLESCAPE2:          /* %Q: Escape ' and enclose in '...' */\n      case etSQLESCAPE3: {        /* %w: Escape \" characters */\n        int i, j, k, n, isnull;\n        int needQuote;\n        char ch;\n        char q = ((xtype==etSQLESCAPE3)?'\"':'\\'');   /* Quote character */\n        char *escarg;\n\n        if( bArgList ){\n          escarg = getTextArg(pArgList);\n        }else{\n          escarg = va_arg(ap,char*);\n        }\n        isnull = escarg==0;\n        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? \"NULL\" : \"(NULL)\");\n        /* For %q, %Q, and %w, the precision is the number of bytes (or\n        ** characters if the ! flags is present) to use from the input.\n        ** Because of the extra quoting characters inserted, the number\n        ** of output characters may be larger than the precision.\n        */\n        k = precision;\n        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){\n          if( ch==q )  n++;\n          if( flag_altform2 && (ch&0xc0)==0xc0 ){\n            while( (escarg[i+1]&0xc0)==0x80 ){ i++; }\n          }\n        }\n        needQuote = !isnull && xtype==etSQLESCAPE2;\n        n += i + 3;\n        if( n>etBUFSIZE ){\n          bufpt = zExtra = printfTempBuf(pAccum, n);\n          if( bufpt==0 ) return;\n        }else{\n          bufpt = buf;\n        }\n        j = 0;\n        if( needQuote ) bufpt[j++] = q;\n        k = i;\n        for(i=0; i<k; i++){\n          bufpt[j++] = ch = escarg[i];\n          if( ch==q ) bufpt[j++] = ch;\n        }\n        if( needQuote ) bufpt[j++] = q;\n        bufpt[j] = 0;\n        length = j;\n        goto adjust_width_for_utf8;\n      }\n      case etTOKEN: {\n        Token *pToken;\n        if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;\n        pToken = va_arg(ap, Token*);\n        assert( bArgList==0 );\n        if( pToken && pToken->n ){\n          sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);\n        }\n        length = width = 0;\n        break;\n      }\n      case etSRCLIST: {\n        SrcList *pSrc;\n        int k;\n        struct SrcList_item *pItem;\n        if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;\n        pSrc = va_arg(ap, SrcList*);\n        k = va_arg(ap, int);\n        pItem = &pSrc->a[k];\n        assert( bArgList==0 );\n        assert( k>=0 && k<pSrc->nSrc );\n        if( pItem->zDatabase ){\n          sqlite3_str_appendall(pAccum, pItem->zDatabase);\n          sqlite3_str_append(pAccum, \".\", 1);\n        }\n        sqlite3_str_appendall(pAccum, pItem->zName);\n        length = width = 0;\n        break;\n      }\n      default: {\n        assert( xtype==etINVALID );\n        return;\n      }\n    }/* End switch over the format type */\n    /*\n    ** The text of the conversion is pointed to by \"bufpt\" and is\n    ** \"length\" characters long.  The field width is \"width\".  Do\n    ** the output.  Both length and width are in bytes, not characters,\n    ** at this point.  If the \"!\" flag was present on string conversions\n    ** indicating that width and precision should be expressed in characters,\n    ** then the values have been translated prior to reaching this point.\n    */\n    width -= length;\n    if( width>0 ){\n      if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');\n      sqlite3_str_append(pAccum, bufpt, length);\n      if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');\n    }else{\n      sqlite3_str_append(pAccum, bufpt, length);\n    }\n\n    if( zExtra ){\n      sqlite3DbFree(pAccum->db, zExtra);\n      zExtra = 0;\n    }\n  }/* End for loop over the format string */\n} /* End of function */\n\n/*\n** Enlarge the memory allocation on a StrAccum object so that it is\n** able to accept at least N more bytes of text.\n**\n** Return the number of bytes of text that StrAccum is able to accept\n** after the attempted enlargement.  The value returned might be zero.\n*/\nstatic int sqlite3StrAccumEnlarge(StrAccum *p, int N){\n  char *zNew;\n  assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */\n  if( p->accError ){\n    testcase(p->accError==SQLITE_TOOBIG);\n    testcase(p->accError==SQLITE_NOMEM);\n    return 0;\n  }\n  if( p->mxAlloc==0 ){\n    setStrAccumError(p, SQLITE_TOOBIG);\n    return p->nAlloc - p->nChar - 1;\n  }else{\n    char *zOld = isMalloced(p) ? p->zText : 0;\n    i64 szNew = p->nChar;\n    szNew += N + 1;\n    if( szNew+p->nChar<=p->mxAlloc ){\n      /* Force exponential buffer size growth as long as it does not overflow,\n      ** to avoid having to call this routine too often */\n      szNew += p->nChar;\n    }\n    if( szNew > p->mxAlloc ){\n      sqlite3_str_reset(p);\n      setStrAccumError(p, SQLITE_TOOBIG);\n      return 0;\n    }else{\n      p->nAlloc = (int)szNew;\n    }\n    if( p->db ){\n      zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);\n    }else{\n      zNew = sqlite3Realloc(zOld, p->nAlloc);\n    }\n    if( zNew ){\n      assert( p->zText!=0 || p->nChar==0 );\n      if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);\n      p->zText = zNew;\n      p->nAlloc = sqlite3DbMallocSize(p->db, zNew);\n      p->printfFlags |= SQLITE_PRINTF_MALLOCED;\n    }else{\n      sqlite3_str_reset(p);\n      setStrAccumError(p, SQLITE_NOMEM);\n      return 0;\n    }\n  }\n  return N;\n}\n\n/*\n** Append N copies of character c to the given string buffer.\n*/\nSQLITE_API void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){\n  testcase( p->nChar + (i64)N > 0x7fffffff );\n  if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){\n    return;\n  }\n  while( (N--)>0 ) p->zText[p->nChar++] = c;\n}\n\n/*\n** The StrAccum \"p\" is not large enough to accept N new bytes of z[].\n** So enlarge if first, then do the append.\n**\n** This is a helper routine to sqlite3_str_append() that does special-case\n** work (enlarging the buffer) using tail recursion, so that the\n** sqlite3_str_append() routine can use fast calling semantics.\n*/\nstatic void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){\n  N = sqlite3StrAccumEnlarge(p, N);\n  if( N>0 ){\n    memcpy(&p->zText[p->nChar], z, N);\n    p->nChar += N;\n  }\n}\n\n/*\n** Append N bytes of text from z to the StrAccum object.  Increase the\n** size of the memory allocation for StrAccum if necessary.\n*/\nSQLITE_API void sqlite3_str_append(sqlite3_str *p, const char *z, int N){\n  assert( z!=0 || N==0 );\n  assert( p->zText!=0 || p->nChar==0 || p->accError );\n  assert( N>=0 );\n  assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );\n  if( p->nChar+N >= p->nAlloc ){\n    enlargeAndAppend(p,z,N);\n  }else if( N ){\n    assert( p->zText );\n    p->nChar += N;\n    memcpy(&p->zText[p->nChar-N], z, N);\n  }\n}\n\n/*\n** Append the complete text of zero-terminated string z[] to the p string.\n*/\nSQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){\n  sqlite3_str_append(p, z, sqlite3Strlen30(z));\n}\n\n\n/*\n** Finish off a string by making sure it is zero-terminated.\n** Return a pointer to the resulting string.  Return a NULL\n** pointer if any kind of error was encountered.\n*/\nstatic SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){\n  char *zText;\n  assert( p->mxAlloc>0 && !isMalloced(p) );\n  zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );\n  if( zText ){\n    memcpy(zText, p->zText, p->nChar+1);\n    p->printfFlags |= SQLITE_PRINTF_MALLOCED;\n  }else{\n    setStrAccumError(p, SQLITE_NOMEM);\n  }\n  p->zText = zText;\n  return zText;\n}\nSQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){\n  if( p->zText ){\n    p->zText[p->nChar] = 0;\n    if( p->mxAlloc>0 && !isMalloced(p) ){\n      return strAccumFinishRealloc(p);\n    }\n  }\n  return p->zText;\n}\n\n/*\n** This singleton is an sqlite3_str object that is returned if\n** sqlite3_malloc() fails to provide space for a real one.  This\n** sqlite3_str object accepts no new text and always returns\n** an SQLITE_NOMEM error.\n*/\nstatic sqlite3_str sqlite3OomStr = {\n   0, 0, 0, 0, 0, SQLITE_NOMEM, 0\n};\n\n/* Finalize a string created using sqlite3_str_new().\n*/\nSQLITE_API char *sqlite3_str_finish(sqlite3_str *p){\n  char *z;\n  if( p!=0 && p!=&sqlite3OomStr ){\n    z = sqlite3StrAccumFinish(p);\n    sqlite3_free(p);\n  }else{\n    z = 0;\n  }\n  return z;\n}\n\n/* Return any error code associated with p */\nSQLITE_API int sqlite3_str_errcode(sqlite3_str *p){\n  return p ? p->accError : SQLITE_NOMEM;\n}\n\n/* Return the current length of p in bytes */\nSQLITE_API int sqlite3_str_length(sqlite3_str *p){\n  return p ? p->nChar : 0;\n}\n\n/* Return the current value for p */\nSQLITE_API char *sqlite3_str_value(sqlite3_str *p){\n  if( p==0 || p->nChar==0 ) return 0;\n  p->zText[p->nChar] = 0;\n  return p->zText;\n}\n\n/*\n** Reset an StrAccum string.  Reclaim all malloced memory.\n*/\nSQLITE_API void sqlite3_str_reset(StrAccum *p){\n  if( isMalloced(p) ){\n    sqlite3DbFree(p->db, p->zText);\n    p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;\n  }\n  p->nAlloc = 0;\n  p->nChar = 0;\n  p->zText = 0;\n}\n\n/*\n** Initialize a string accumulator.\n**\n** p:     The accumulator to be initialized.\n** db:    Pointer to a database connection.  May be NULL.  Lookaside\n**        memory is used if not NULL. db->mallocFailed is set appropriately\n**        when not NULL.\n** zBase: An initial buffer.  May be NULL in which case the initial buffer\n**        is malloced.\n** n:     Size of zBase in bytes.  If total space requirements never exceed\n**        n then no memory allocations ever occur.\n** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory\n**        allocations will ever occur.\n*/\nSQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){\n  p->zText = zBase;\n  p->db = db;\n  p->nAlloc = n;\n  p->mxAlloc = mx;\n  p->nChar = 0;\n  p->accError = 0;\n  p->printfFlags = 0;\n}\n\n/* Allocate and initialize a new dynamic string object */\nSQLITE_API sqlite3_str *sqlite3_str_new(sqlite3 *db){\n  sqlite3_str *p = sqlite3_malloc64(sizeof(*p));\n  if( p ){\n    sqlite3StrAccumInit(p, 0, 0, 0,\n            db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);\n  }else{\n    p = &sqlite3OomStr;\n  }\n  return p;\n}\n\n/*\n** Print into memory obtained from sqliteMalloc().  Use the internal\n** %-conversion extensions.\n*/\nSQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){\n  char *z;\n  char zBase[SQLITE_PRINT_BUF_SIZE];\n  StrAccum acc;\n  assert( db!=0 );\n  sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),\n                      db->aLimit[SQLITE_LIMIT_LENGTH]);\n  acc.printfFlags = SQLITE_PRINTF_INTERNAL;\n  sqlite3_str_vappendf(&acc, zFormat, ap);\n  z = sqlite3StrAccumFinish(&acc);\n  if( acc.accError==SQLITE_NOMEM ){\n    sqlite3OomFault(db);\n  }\n  return z;\n}\n\n/*\n** Print into memory obtained from sqliteMalloc().  Use the internal\n** %-conversion extensions.\n*/\nSQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){\n  va_list ap;\n  char *z;\n  va_start(ap, zFormat);\n  z = sqlite3VMPrintf(db, zFormat, ap);\n  va_end(ap);\n  return z;\n}\n\n/*\n** Print into memory obtained from sqlite3_malloc().  Omit the internal\n** %-conversion extensions.\n*/\nSQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){\n  char *z;\n  char zBase[SQLITE_PRINT_BUF_SIZE];\n  StrAccum acc;\n\n#ifdef SQLITE_ENABLE_API_ARMOR  \n  if( zFormat==0 ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);\n  sqlite3_str_vappendf(&acc, zFormat, ap);\n  z = sqlite3StrAccumFinish(&acc);\n  return z;\n}\n\n/*\n** Print into memory obtained from sqlite3_malloc()().  Omit the internal\n** %-conversion extensions.\n*/\nSQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){\n  va_list ap;\n  char *z;\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  va_start(ap, zFormat);\n  z = sqlite3_vmprintf(zFormat, ap);\n  va_end(ap);\n  return z;\n}\n\n/*\n** sqlite3_snprintf() works like snprintf() except that it ignores the\n** current locale settings.  This is important for SQLite because we\n** are not able to use a \",\" as the decimal point in place of \".\" as\n** specified by some locales.\n**\n** Oops:  The first two arguments of sqlite3_snprintf() are backwards\n** from the snprintf() standard.  Unfortunately, it is too late to change\n** this without breaking compatibility, so we just have to live with the\n** mistake.\n**\n** sqlite3_vsnprintf() is the varargs version.\n*/\nSQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){\n  StrAccum acc;\n  if( n<=0 ) return zBuf;\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( zBuf==0 || zFormat==0 ) {\n    (void)SQLITE_MISUSE_BKPT;\n    if( zBuf ) zBuf[0] = 0;\n    return zBuf;\n  }\n#endif\n  sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);\n  sqlite3_str_vappendf(&acc, zFormat, ap);\n  zBuf[acc.nChar] = 0;\n  return zBuf;\n}\nSQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){\n  char *z;\n  va_list ap;\n  va_start(ap,zFormat);\n  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);\n  va_end(ap);\n  return z;\n}\n\n/*\n** This is the routine that actually formats the sqlite3_log() message.\n** We house it in a separate routine from sqlite3_log() to avoid using\n** stack space on small-stack systems when logging is disabled.\n**\n** sqlite3_log() must render into a static buffer.  It cannot dynamically\n** allocate memory because it might be called while the memory allocator\n** mutex is held.\n**\n** sqlite3_str_vappendf() might ask for *temporary* memory allocations for\n** certain format characters (%q) or for very large precisions or widths.\n** Care must be taken that any sqlite3_log() calls that occur while the\n** memory mutex is held do not use these mechanisms.\n*/\nstatic void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){\n  StrAccum acc;                          /* String accumulator */\n  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */\n\n  sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);\n  sqlite3_str_vappendf(&acc, zFormat, ap);\n  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,\n                           sqlite3StrAccumFinish(&acc));\n}\n\n/*\n** Format and write a message to the log if logging is enabled.\n*/\nSQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){\n  va_list ap;                             /* Vararg list */\n  if( sqlite3GlobalConfig.xLog ){\n    va_start(ap, zFormat);\n    renderLogMsg(iErrCode, zFormat, ap);\n    va_end(ap);\n  }\n}\n\n#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)\n/*\n** A version of printf() that understands %lld.  Used for debugging.\n** The printf() built into some versions of windows does not understand %lld\n** and segfaults if you give it a long long int.\n*/\nSQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){\n  va_list ap;\n  StrAccum acc;\n  char zBuf[SQLITE_PRINT_BUF_SIZE*10];\n  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);\n  va_start(ap,zFormat);\n  sqlite3_str_vappendf(&acc, zFormat, ap);\n  va_end(ap);\n  sqlite3StrAccumFinish(&acc);\n#ifdef SQLITE_OS_TRACE_PROC\n  {\n    extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);\n    SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));\n  }\n#else\n  fprintf(stdout,\"%s\", zBuf);\n  fflush(stdout);\n#endif\n}\n#endif\n\n\n/*\n** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument\n** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.\n*/\nSQLITE_API void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){\n  va_list ap;\n  va_start(ap,zFormat);\n  sqlite3_str_vappendf(p, zFormat, ap);\n  va_end(ap);\n}\n\n/************** End of printf.c **********************************************/\n/************** Begin file treeview.c ****************************************/\n/*\n** 2015-06-08\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains C code to implement the TreeView debugging routines.\n** These routines print a parse tree to standard output for debugging and\n** analysis. \n**\n** The interfaces in this file is only available when compiling\n** with SQLITE_DEBUG.\n*/\n/* #include \"sqliteInt.h\" */\n#ifdef SQLITE_DEBUG\n\n/*\n** Add a new subitem to the tree.  The moreToFollow flag indicates that this\n** is not the last item in the tree.\n*/\nstatic TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){\n  if( p==0 ){\n    p = sqlite3_malloc64( sizeof(*p) );\n    if( p==0 ) return 0;\n    memset(p, 0, sizeof(*p));\n  }else{\n    p->iLevel++;\n  }\n  assert( moreToFollow==0 || moreToFollow==1 );\n  if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;\n  return p;\n}\n\n/*\n** Finished with one layer of the tree\n*/\nstatic void sqlite3TreeViewPop(TreeView *p){\n  if( p==0 ) return;\n  p->iLevel--;\n  if( p->iLevel<0 ) sqlite3_free(p);\n}\n\n/*\n** Generate a single line of output for the tree, with a prefix that contains\n** all the appropriate tree lines\n*/\nstatic void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){\n  va_list ap;\n  int i;\n  StrAccum acc;\n  char zBuf[500];\n  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);\n  if( p ){\n    for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){\n      sqlite3_str_append(&acc, p->bLine[i] ? \"|   \" : \"    \", 4);\n    }\n    sqlite3_str_append(&acc, p->bLine[i] ? \"|-- \" : \"'-- \", 4);\n  }\n  if( zFormat!=0 ){\n    va_start(ap, zFormat);\n    sqlite3_str_vappendf(&acc, zFormat, ap);\n    va_end(ap);\n    assert( acc.nChar>0 || acc.accError );\n    sqlite3_str_append(&acc, \"\\n\", 1);\n  }\n  sqlite3StrAccumFinish(&acc);\n  fprintf(stdout,\"%s\", zBuf);\n  fflush(stdout);\n}\n\n/*\n** Shorthand for starting a new tree item that consists of a single label\n*/\nstatic void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){\n  p = sqlite3TreeViewPush(p, moreFollows);\n  sqlite3TreeViewLine(p, \"%s\", zLabel);\n}\n\n/*\n** Generate a human-readable description of a WITH clause.\n*/\nSQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){\n  int i;\n  if( pWith==0 ) return;\n  if( pWith->nCte==0 ) return;\n  if( pWith->pOuter ){\n    sqlite3TreeViewLine(pView, \"WITH (0x%p, pOuter=0x%p)\",pWith,pWith->pOuter);\n  }else{\n    sqlite3TreeViewLine(pView, \"WITH (0x%p)\", pWith);\n  }\n  if( pWith->nCte>0 ){\n    pView = sqlite3TreeViewPush(pView, 1);\n    for(i=0; i<pWith->nCte; i++){\n      StrAccum x;\n      char zLine[1000];\n      const struct Cte *pCte = &pWith->a[i];\n      sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);\n      sqlite3_str_appendf(&x, \"%s\", pCte->zName);\n      if( pCte->pCols && pCte->pCols->nExpr>0 ){\n        char cSep = '(';\n        int j;\n        for(j=0; j<pCte->pCols->nExpr; j++){\n          sqlite3_str_appendf(&x, \"%c%s\", cSep, pCte->pCols->a[j].zEName);\n          cSep = ',';\n        }\n        sqlite3_str_appendf(&x, \")\");\n      }\n      sqlite3_str_appendf(&x, \" AS\");\n      sqlite3StrAccumFinish(&x);\n      sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);\n      sqlite3TreeViewSelect(pView, pCte->pSelect, 0);\n      sqlite3TreeViewPop(pView);\n    }\n    sqlite3TreeViewPop(pView);\n  }\n}\n\n/*\n** Generate a human-readable description of a SrcList object.\n*/\nSQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc){\n  int i;\n  for(i=0; i<pSrc->nSrc; i++){\n    const struct SrcList_item *pItem = &pSrc->a[i];\n    StrAccum x;\n    char zLine[100];\n    sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);\n    sqlite3_str_appendf(&x, \"{%d:*}\", pItem->iCursor);\n    if( pItem->zDatabase ){\n      sqlite3_str_appendf(&x, \" %s.%s\", pItem->zDatabase, pItem->zName);\n    }else if( pItem->zName ){\n      sqlite3_str_appendf(&x, \" %s\", pItem->zName);\n    }\n    if( pItem->pTab ){\n      sqlite3_str_appendf(&x, \" tab=%Q nCol=%d ptr=%p used=%llx\",\n           pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab, pItem->colUsed);\n    }\n    if( pItem->zAlias ){\n      sqlite3_str_appendf(&x, \" (AS %s)\", pItem->zAlias);\n    }\n    if( pItem->fg.jointype & JT_LEFT ){\n      sqlite3_str_appendf(&x, \" LEFT-JOIN\");\n    }\n    if( pItem->fg.fromDDL ){\n      sqlite3_str_appendf(&x, \" DDL\");\n    }\n    sqlite3StrAccumFinish(&x);\n    sqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1); \n    if( pItem->pSelect ){\n      sqlite3TreeViewSelect(pView, pItem->pSelect, 0);\n    }\n    if( pItem->fg.isTabFunc ){\n      sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, \"func-args:\");\n    }\n    sqlite3TreeViewPop(pView);\n  }\n}\n\n/*\n** Generate a human-readable description of a Select object.\n*/\nSQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){\n  int n = 0;\n  int cnt = 0;\n  if( p==0 ){\n    sqlite3TreeViewLine(pView, \"nil-SELECT\");\n    return;\n  } \n  pView = sqlite3TreeViewPush(pView, moreToFollow);\n  if( p->pWith ){\n    sqlite3TreeViewWith(pView, p->pWith, 1);\n    cnt = 1;\n    sqlite3TreeViewPush(pView, 1);\n  }\n  do{\n    if( p->selFlags & SF_WhereBegin ){\n      sqlite3TreeViewLine(pView, \"sqlite3WhereBegin()\");\n    }else{\n      sqlite3TreeViewLine(pView,\n        \"SELECT%s%s (%u/%p) selFlags=0x%x nSelectRow=%d\",\n        ((p->selFlags & SF_Distinct) ? \" DISTINCT\" : \"\"),\n        ((p->selFlags & SF_Aggregate) ? \" agg_flag\" : \"\"),\n        p->selId, p, p->selFlags,\n        (int)p->nSelectRow\n      );\n    }\n    if( cnt++ ) sqlite3TreeViewPop(pView);\n    if( p->pPrior ){\n      n = 1000;\n    }else{\n      n = 0;\n      if( p->pSrc && p->pSrc->nSrc ) n++;\n      if( p->pWhere ) n++;\n      if( p->pGroupBy ) n++;\n      if( p->pHaving ) n++;\n      if( p->pOrderBy ) n++;\n      if( p->pLimit ) n++;\n#ifndef SQLITE_OMIT_WINDOWFUNC\n      if( p->pWin ) n++;\n      if( p->pWinDefn ) n++;\n#endif\n    }\n    if( p->pEList ){\n      sqlite3TreeViewExprList(pView, p->pEList, n>0, \"result-set\");\n    }\n    n--;\n#ifndef SQLITE_OMIT_WINDOWFUNC\n    if( p->pWin ){\n      Window *pX;\n      pView = sqlite3TreeViewPush(pView, (n--)>0);\n      sqlite3TreeViewLine(pView, \"window-functions\");\n      for(pX=p->pWin; pX; pX=pX->pNextWin){\n        sqlite3TreeViewWinFunc(pView, pX, pX->pNextWin!=0);\n      }\n      sqlite3TreeViewPop(pView);\n    }\n#endif\n    if( p->pSrc && p->pSrc->nSrc ){\n      pView = sqlite3TreeViewPush(pView, (n--)>0);\n      sqlite3TreeViewLine(pView, \"FROM\");\n      sqlite3TreeViewSrcList(pView, p->pSrc);\n      sqlite3TreeViewPop(pView);\n    }\n    if( p->pWhere ){\n      sqlite3TreeViewItem(pView, \"WHERE\", (n--)>0);\n      sqlite3TreeViewExpr(pView, p->pWhere, 0);\n      sqlite3TreeViewPop(pView);\n    }\n    if( p->pGroupBy ){\n      sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, \"GROUPBY\");\n    }\n    if( p->pHaving ){\n      sqlite3TreeViewItem(pView, \"HAVING\", (n--)>0);\n      sqlite3TreeViewExpr(pView, p->pHaving, 0);\n      sqlite3TreeViewPop(pView);\n    }\n#ifndef SQLITE_OMIT_WINDOWFUNC\n    if( p->pWinDefn ){\n      Window *pX;\n      sqlite3TreeViewItem(pView, \"WINDOW\", (n--)>0);\n      for(pX=p->pWinDefn; pX; pX=pX->pNextWin){\n        sqlite3TreeViewWindow(pView, pX, pX->pNextWin!=0);\n      }\n      sqlite3TreeViewPop(pView);\n    }\n#endif\n    if( p->pOrderBy ){\n      sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, \"ORDERBY\");\n    }\n    if( p->pLimit ){\n      sqlite3TreeViewItem(pView, \"LIMIT\", (n--)>0);\n      sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0);\n      if( p->pLimit->pRight ){\n        sqlite3TreeViewItem(pView, \"OFFSET\", (n--)>0);\n        sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0);\n        sqlite3TreeViewPop(pView);\n      }\n      sqlite3TreeViewPop(pView);\n    }\n    if( p->pPrior ){\n      const char *zOp = \"UNION\";\n      switch( p->op ){\n        case TK_ALL:         zOp = \"UNION ALL\";  break;\n        case TK_INTERSECT:   zOp = \"INTERSECT\";  break;\n        case TK_EXCEPT:      zOp = \"EXCEPT\";     break;\n      }\n      sqlite3TreeViewItem(pView, zOp, 1);\n    }\n    p = p->pPrior;\n  }while( p!=0 );\n  sqlite3TreeViewPop(pView);\n}\n\n#ifndef SQLITE_OMIT_WINDOWFUNC\n/*\n** Generate a description of starting or stopping bounds\n*/\nSQLITE_PRIVATE void sqlite3TreeViewBound(\n  TreeView *pView,        /* View context */\n  u8 eBound,              /* UNBOUNDED, CURRENT, PRECEDING, FOLLOWING */\n  Expr *pExpr,            /* Value for PRECEDING or FOLLOWING */\n  u8 moreToFollow         /* True if more to follow */\n){\n  switch( eBound ){\n    case TK_UNBOUNDED: {\n      sqlite3TreeViewItem(pView, \"UNBOUNDED\", moreToFollow);\n      sqlite3TreeViewPop(pView);\n      break;\n    }\n    case TK_CURRENT: {\n      sqlite3TreeViewItem(pView, \"CURRENT\", moreToFollow);\n      sqlite3TreeViewPop(pView);\n      break;\n    }\n    case TK_PRECEDING: {\n      sqlite3TreeViewItem(pView, \"PRECEDING\", moreToFollow);\n      sqlite3TreeViewExpr(pView, pExpr, 0);\n      sqlite3TreeViewPop(pView);\n      break;\n    }\n    case TK_FOLLOWING: {\n      sqlite3TreeViewItem(pView, \"FOLLOWING\", moreToFollow);\n      sqlite3TreeViewExpr(pView, pExpr, 0);\n      sqlite3TreeViewPop(pView);\n      break;\n    }\n  }\n}\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n\n#ifndef SQLITE_OMIT_WINDOWFUNC\n/*\n** Generate a human-readable explanation for a Window object\n*/\nSQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView *pView, const Window *pWin, u8 more){\n  int nElement = 0;\n  if( pWin->pFilter ){\n    sqlite3TreeViewItem(pView, \"FILTER\", 1);\n    sqlite3TreeViewExpr(pView, pWin->pFilter, 0);\n    sqlite3TreeViewPop(pView);\n  }\n  pView = sqlite3TreeViewPush(pView, more);\n  if( pWin->zName ){\n    sqlite3TreeViewLine(pView, \"OVER %s (%p)\", pWin->zName, pWin);\n  }else{\n    sqlite3TreeViewLine(pView, \"OVER (%p)\", pWin);\n  }\n  if( pWin->zBase )    nElement++;\n  if( pWin->pOrderBy ) nElement++;\n  if( pWin->eFrmType ) nElement++;\n  if( pWin->eExclude ) nElement++;\n  if( pWin->zBase ){\n    sqlite3TreeViewPush(pView, (--nElement)>0);\n    sqlite3TreeViewLine(pView, \"window: %s\", pWin->zBase);\n    sqlite3TreeViewPop(pView);\n  }\n  if( pWin->pPartition ){\n    sqlite3TreeViewExprList(pView, pWin->pPartition, nElement>0,\"PARTITION-BY\");\n  }\n  if( pWin->pOrderBy ){\n    sqlite3TreeViewExprList(pView, pWin->pOrderBy, (--nElement)>0, \"ORDER-BY\");\n  }\n  if( pWin->eFrmType ){\n    char zBuf[30];\n    const char *zFrmType = \"ROWS\";\n    if( pWin->eFrmType==TK_RANGE ) zFrmType = \"RANGE\";\n    if( pWin->eFrmType==TK_GROUPS ) zFrmType = \"GROUPS\";\n    sqlite3_snprintf(sizeof(zBuf),zBuf,\"%s%s\",zFrmType,\n        pWin->bImplicitFrame ? \" (implied)\" : \"\");\n    sqlite3TreeViewItem(pView, zBuf, (--nElement)>0);\n    sqlite3TreeViewBound(pView, pWin->eStart, pWin->pStart, 1);\n    sqlite3TreeViewBound(pView, pWin->eEnd, pWin->pEnd, 0);\n    sqlite3TreeViewPop(pView);\n  }\n  if( pWin->eExclude ){\n    char zBuf[30];\n    const char *zExclude;\n    switch( pWin->eExclude ){\n      case TK_NO:      zExclude = \"NO OTHERS\";   break;\n      case TK_CURRENT: zExclude = \"CURRENT ROW\"; break;\n      case TK_GROUP:   zExclude = \"GROUP\";       break;\n      case TK_TIES:    zExclude = \"TIES\";        break;\n      default:\n        sqlite3_snprintf(sizeof(zBuf),zBuf,\"invalid(%d)\", pWin->eExclude);\n        zExclude = zBuf;\n        break;\n    }\n    sqlite3TreeViewPush(pView, 0);\n    sqlite3TreeViewLine(pView, \"EXCLUDE %s\", zExclude);\n    sqlite3TreeViewPop(pView);\n  }\n  sqlite3TreeViewPop(pView);\n}\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n\n#ifndef SQLITE_OMIT_WINDOWFUNC\n/*\n** Generate a human-readable explanation for a Window Function object\n*/\nSQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView *pView, const Window *pWin, u8 more){\n  pView = sqlite3TreeViewPush(pView, more);\n  sqlite3TreeViewLine(pView, \"WINFUNC %s(%d)\",\n                       pWin->pFunc->zName, pWin->pFunc->nArg);\n  sqlite3TreeViewWindow(pView, pWin, 0);\n  sqlite3TreeViewPop(pView);\n}\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n\n/*\n** Generate a human-readable explanation of an expression tree.\n*/\nSQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){\n  const char *zBinOp = 0;   /* Binary operator */\n  const char *zUniOp = 0;   /* Unary operator */\n  char zFlgs[200];\n  pView = sqlite3TreeViewPush(pView, moreToFollow);\n  if( pExpr==0 ){\n    sqlite3TreeViewLine(pView, \"nil\");\n    sqlite3TreeViewPop(pView);\n    return;\n  }\n  if( pExpr->flags || pExpr->affExpr || pExpr->vvaFlags ){\n    StrAccum x;\n    sqlite3StrAccumInit(&x, 0, zFlgs, sizeof(zFlgs), 0);\n    sqlite3_str_appendf(&x, \" fg.af=%x.%c\",\n      pExpr->flags, pExpr->affExpr ? pExpr->affExpr : 'n');\n    if( ExprHasProperty(pExpr, EP_FromJoin) ){\n      sqlite3_str_appendf(&x, \" iRJT=%d\", pExpr->iRightJoinTable);\n    }\n    if( ExprHasProperty(pExpr, EP_FromDDL) ){\n      sqlite3_str_appendf(&x, \" DDL\");\n    }\n    if( ExprHasVVAProperty(pExpr, EP_Immutable) ){\n      sqlite3_str_appendf(&x, \" IMMUTABLE\");\n    }\n    sqlite3StrAccumFinish(&x);\n  }else{\n    zFlgs[0] = 0;\n  }\n  switch( pExpr->op ){\n    case TK_AGG_COLUMN: {\n      sqlite3TreeViewLine(pView, \"AGG{%d:%d}%s\",\n            pExpr->iTable, pExpr->iColumn, zFlgs);\n      break;\n    }\n    case TK_COLUMN: {\n      if( pExpr->iTable<0 ){\n        /* This only happens when coding check constraints */\n        char zOp2[16];\n        if( pExpr->op2 ){\n          sqlite3_snprintf(sizeof(zOp2),zOp2,\" op2=0x%02x\",pExpr->op2);\n        }else{\n          zOp2[0] = 0;\n        }\n        sqlite3TreeViewLine(pView, \"COLUMN(%d)%s%s\",\n                                    pExpr->iColumn, zFlgs, zOp2);\n      }else{\n        sqlite3TreeViewLine(pView, \"{%d:%d} pTab=%p%s\",\n                        pExpr->iTable, pExpr->iColumn,\n                        pExpr->y.pTab, zFlgs);\n      }\n      if( ExprHasProperty(pExpr, EP_FixedCol) ){\n        sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);\n      }\n      break;\n    }\n    case TK_INTEGER: {\n      if( pExpr->flags & EP_IntValue ){\n        sqlite3TreeViewLine(pView, \"%d\", pExpr->u.iValue);\n      }else{\n        sqlite3TreeViewLine(pView, \"%s\", pExpr->u.zToken);\n      }\n      break;\n    }\n#ifndef SQLITE_OMIT_FLOATING_POINT\n    case TK_FLOAT: {\n      sqlite3TreeViewLine(pView,\"%s\", pExpr->u.zToken);\n      break;\n    }\n#endif\n    case TK_STRING: {\n      sqlite3TreeViewLine(pView,\"%Q\", pExpr->u.zToken);\n      break;\n    }\n    case TK_NULL: {\n      sqlite3TreeViewLine(pView,\"NULL\");\n      break;\n    }\n    case TK_TRUEFALSE: {\n      sqlite3TreeViewLine(pView,\n         sqlite3ExprTruthValue(pExpr) ? \"TRUE\" : \"FALSE\");\n      break;\n    }\n#ifndef SQLITE_OMIT_BLOB_LITERAL\n    case TK_BLOB: {\n      sqlite3TreeViewLine(pView,\"%s\", pExpr->u.zToken);\n      break;\n    }\n#endif\n    case TK_VARIABLE: {\n      sqlite3TreeViewLine(pView,\"VARIABLE(%s,%d)\",\n                          pExpr->u.zToken, pExpr->iColumn);\n      break;\n    }\n    case TK_REGISTER: {\n      sqlite3TreeViewLine(pView,\"REGISTER(%d)\", pExpr->iTable);\n      break;\n    }\n    case TK_ID: {\n      sqlite3TreeViewLine(pView,\"ID \\\"%w\\\"\", pExpr->u.zToken);\n      break;\n    }\n#ifndef SQLITE_OMIT_CAST\n    case TK_CAST: {\n      /* Expressions of the form:   CAST(pLeft AS token) */\n      sqlite3TreeViewLine(pView,\"CAST %Q\", pExpr->u.zToken);\n      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);\n      break;\n    }\n#endif /* SQLITE_OMIT_CAST */\n    case TK_LT:      zBinOp = \"LT\";     break;\n    case TK_LE:      zBinOp = \"LE\";     break;\n    case TK_GT:      zBinOp = \"GT\";     break;\n    case TK_GE:      zBinOp = \"GE\";     break;\n    case TK_NE:      zBinOp = \"NE\";     break;\n    case TK_EQ:      zBinOp = \"EQ\";     break;\n    case TK_IS:      zBinOp = \"IS\";     break;\n    case TK_ISNOT:   zBinOp = \"ISNOT\";  break;\n    case TK_AND:     zBinOp = \"AND\";    break;\n    case TK_OR:      zBinOp = \"OR\";     break;\n    case TK_PLUS:    zBinOp = \"ADD\";    break;\n    case TK_STAR:    zBinOp = \"MUL\";    break;\n    case TK_MINUS:   zBinOp = \"SUB\";    break;\n    case TK_REM:     zBinOp = \"REM\";    break;\n    case TK_BITAND:  zBinOp = \"BITAND\"; break;\n    case TK_BITOR:   zBinOp = \"BITOR\";  break;\n    case TK_SLASH:   zBinOp = \"DIV\";    break;\n    case TK_LSHIFT:  zBinOp = \"LSHIFT\"; break;\n    case TK_RSHIFT:  zBinOp = \"RSHIFT\"; break;\n    case TK_CONCAT:  zBinOp = \"CONCAT\"; break;\n    case TK_DOT:     zBinOp = \"DOT\";    break;\n    case TK_LIMIT:   zBinOp = \"LIMIT\";  break;\n\n    case TK_UMINUS:  zUniOp = \"UMINUS\"; break;\n    case TK_UPLUS:   zUniOp = \"UPLUS\";  break;\n    case TK_BITNOT:  zUniOp = \"BITNOT\"; break;\n    case TK_NOT:     zUniOp = \"NOT\";    break;\n    case TK_ISNULL:  zUniOp = \"ISNULL\"; break;\n    case TK_NOTNULL: zUniOp = \"NOTNULL\"; break;\n\n    case TK_TRUTH: {\n      int x;\n      const char *azOp[] = {\n         \"IS-FALSE\", \"IS-TRUE\", \"IS-NOT-FALSE\", \"IS-NOT-TRUE\"\n      };\n      assert( pExpr->op2==TK_IS || pExpr->op2==TK_ISNOT );\n      assert( pExpr->pRight );\n      assert( sqlite3ExprSkipCollate(pExpr->pRight)->op==TK_TRUEFALSE );\n      x = (pExpr->op2==TK_ISNOT)*2 + sqlite3ExprTruthValue(pExpr->pRight);\n      zUniOp = azOp[x];\n      break;\n    }\n\n    case TK_SPAN: {\n      sqlite3TreeViewLine(pView, \"SPAN %Q\", pExpr->u.zToken);\n      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);\n      break;\n    }\n\n    case TK_COLLATE: {\n      /* COLLATE operators without the EP_Collate flag are intended to\n      ** emulate collation associated with a table column.  These show\n      ** up in the treeview output as \"SOFT-COLLATE\".  Explicit COLLATE\n      ** operators that appear in the original SQL always have the\n      ** EP_Collate bit set and appear in treeview output as just \"COLLATE\" */\n      sqlite3TreeViewLine(pView, \"%sCOLLATE %Q%s\",\n        !ExprHasProperty(pExpr, EP_Collate) ? \"SOFT-\" : \"\",\n        pExpr->u.zToken, zFlgs);\n      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);\n      break;\n    }\n\n    case TK_AGG_FUNCTION:\n    case TK_FUNCTION: {\n      ExprList *pFarg;       /* List of function arguments */\n      Window *pWin;\n      if( ExprHasProperty(pExpr, EP_TokenOnly) ){\n        pFarg = 0;\n        pWin = 0;\n      }else{\n        pFarg = pExpr->x.pList;\n#ifndef SQLITE_OMIT_WINDOWFUNC\n        pWin = ExprHasProperty(pExpr, EP_WinFunc) ? pExpr->y.pWin : 0;\n#else\n        pWin = 0;\n#endif \n      }\n      if( pExpr->op==TK_AGG_FUNCTION ){\n        sqlite3TreeViewLine(pView, \"AGG_FUNCTION%d %Q%s iAgg=%d agg=%p\",\n                             pExpr->op2, pExpr->u.zToken, zFlgs,\n                             pExpr->iAgg, pExpr->pAggInfo);\n      }else if( pExpr->op2!=0 ){\n        const char *zOp2;\n        char zBuf[8];\n        sqlite3_snprintf(sizeof(zBuf),zBuf,\"0x%02x\",pExpr->op2);\n        zOp2 = zBuf;\n        if( pExpr->op2==NC_IsCheck ) zOp2 = \"NC_IsCheck\";\n        if( pExpr->op2==NC_IdxExpr ) zOp2 = \"NC_IdxExpr\";\n        if( pExpr->op2==NC_PartIdx ) zOp2 = \"NC_PartIdx\";\n        if( pExpr->op2==NC_GenCol ) zOp2 = \"NC_GenCol\";\n        sqlite3TreeViewLine(pView, \"FUNCTION %Q%s op2=%s\",\n                            pExpr->u.zToken, zFlgs, zOp2);\n      }else{\n        sqlite3TreeViewLine(pView, \"FUNCTION %Q%s\", pExpr->u.zToken, zFlgs);\n      }\n      if( pFarg ){\n        sqlite3TreeViewExprList(pView, pFarg, pWin!=0, 0);\n      }\n#ifndef SQLITE_OMIT_WINDOWFUNC\n      if( pWin ){\n        sqlite3TreeViewWindow(pView, pWin, 0);\n      }\n#endif\n      break;\n    }\n#ifndef SQLITE_OMIT_SUBQUERY\n    case TK_EXISTS: {\n      sqlite3TreeViewLine(pView, \"EXISTS-expr flags=0x%x\", pExpr->flags);\n      sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);\n      break;\n    }\n    case TK_SELECT: {\n      sqlite3TreeViewLine(pView, \"SELECT-expr flags=0x%x\", pExpr->flags);\n      sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);\n      break;\n    }\n    case TK_IN: {\n      sqlite3TreeViewLine(pView, \"IN flags=0x%x\", pExpr->flags);\n      sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);\n      if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n        sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);\n      }else{\n        sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);\n      }\n      break;\n    }\n#endif /* SQLITE_OMIT_SUBQUERY */\n\n    /*\n    **    x BETWEEN y AND z\n    **\n    ** This is equivalent to\n    **\n    **    x>=y AND x<=z\n    **\n    ** X is stored in pExpr->pLeft.\n    ** Y is stored in pExpr->pList->a[0].pExpr.\n    ** Z is stored in pExpr->pList->a[1].pExpr.\n    */\n    case TK_BETWEEN: {\n      Expr *pX = pExpr->pLeft;\n      Expr *pY = pExpr->x.pList->a[0].pExpr;\n      Expr *pZ = pExpr->x.pList->a[1].pExpr;\n      sqlite3TreeViewLine(pView, \"BETWEEN\");\n      sqlite3TreeViewExpr(pView, pX, 1);\n      sqlite3TreeViewExpr(pView, pY, 1);\n      sqlite3TreeViewExpr(pView, pZ, 0);\n      break;\n    }\n    case TK_TRIGGER: {\n      /* If the opcode is TK_TRIGGER, then the expression is a reference\n      ** to a column in the new.* or old.* pseudo-tables available to\n      ** trigger programs. In this case Expr.iTable is set to 1 for the\n      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn\n      ** is set to the column of the pseudo-table to read, or to -1 to\n      ** read the rowid field.\n      */\n      sqlite3TreeViewLine(pView, \"%s(%d)\", \n          pExpr->iTable ? \"NEW\" : \"OLD\", pExpr->iColumn);\n      break;\n    }\n    case TK_CASE: {\n      sqlite3TreeViewLine(pView, \"CASE\");\n      sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);\n      sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);\n      break;\n    }\n#ifndef SQLITE_OMIT_TRIGGER\n    case TK_RAISE: {\n      const char *zType = \"unk\";\n      switch( pExpr->affExpr ){\n        case OE_Rollback:   zType = \"rollback\";  break;\n        case OE_Abort:      zType = \"abort\";     break;\n        case OE_Fail:       zType = \"fail\";      break;\n        case OE_Ignore:     zType = \"ignore\";    break;\n      }\n      sqlite3TreeViewLine(pView, \"RAISE %s(%Q)\", zType, pExpr->u.zToken);\n      break;\n    }\n#endif\n    case TK_MATCH: {\n      sqlite3TreeViewLine(pView, \"MATCH {%d:%d}%s\",\n                          pExpr->iTable, pExpr->iColumn, zFlgs);\n      sqlite3TreeViewExpr(pView, pExpr->pRight, 0);\n      break;\n    }\n    case TK_VECTOR: {\n      char *z = sqlite3_mprintf(\"VECTOR%s\",zFlgs);\n      sqlite3TreeViewBareExprList(pView, pExpr->x.pList, z);\n      sqlite3_free(z);\n      break;\n    }\n    case TK_SELECT_COLUMN: {\n      sqlite3TreeViewLine(pView, \"SELECT-COLUMN %d\", pExpr->iColumn);\n      sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);\n      break;\n    }\n    case TK_IF_NULL_ROW: {\n      sqlite3TreeViewLine(pView, \"IF-NULL-ROW %d\", pExpr->iTable);\n      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);\n      break;\n    }\n    default: {\n      sqlite3TreeViewLine(pView, \"op=%d\", pExpr->op);\n      break;\n    }\n  }\n  if( zBinOp ){\n    sqlite3TreeViewLine(pView, \"%s%s\", zBinOp, zFlgs);\n    sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);\n    sqlite3TreeViewExpr(pView, pExpr->pRight, 0);\n  }else if( zUniOp ){\n    sqlite3TreeViewLine(pView, \"%s%s\", zUniOp, zFlgs);\n   sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);\n  }\n  sqlite3TreeViewPop(pView);\n}\n\n\n/*\n** Generate a human-readable explanation of an expression list.\n*/\nSQLITE_PRIVATE void sqlite3TreeViewBareExprList(\n  TreeView *pView,\n  const ExprList *pList,\n  const char *zLabel\n){\n  if( zLabel==0 || zLabel[0]==0 ) zLabel = \"LIST\";\n  if( pList==0 ){\n    sqlite3TreeViewLine(pView, \"%s (empty)\", zLabel);\n  }else{\n    int i;\n    sqlite3TreeViewLine(pView, \"%s\", zLabel);\n    for(i=0; i<pList->nExpr; i++){\n      int j = pList->a[i].u.x.iOrderByCol;\n      char *zName = pList->a[i].zEName;\n      int moreToFollow = i<pList->nExpr - 1;\n      if( pList->a[i].eEName!=ENAME_NAME ) zName = 0;\n      if( j || zName ){\n        sqlite3TreeViewPush(pView, moreToFollow);\n        moreToFollow = 0;\n        sqlite3TreeViewLine(pView, 0);\n        if( zName ){\n          fprintf(stdout, \"AS %s \", zName);\n        }\n        if( j ){\n          fprintf(stdout, \"iOrderByCol=%d\", j);\n        }\n        fprintf(stdout, \"\\n\");\n        fflush(stdout);\n      }\n      sqlite3TreeViewExpr(pView, pList->a[i].pExpr, moreToFollow);\n      if( j || zName ){\n        sqlite3TreeViewPop(pView);\n      }\n    }\n  }\n}\nSQLITE_PRIVATE void sqlite3TreeViewExprList(\n  TreeView *pView,\n  const ExprList *pList,\n  u8 moreToFollow,\n  const char *zLabel\n){\n  pView = sqlite3TreeViewPush(pView, moreToFollow);\n  sqlite3TreeViewBareExprList(pView, pList, zLabel);\n  sqlite3TreeViewPop(pView);\n}\n\n#endif /* SQLITE_DEBUG */\n\n/************** End of treeview.c ********************************************/\n/************** Begin file random.c ******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code to implement a pseudo-random number\n** generator (PRNG) for SQLite.\n**\n** Random numbers are used by some of the database backends in order\n** to generate random integer keys for tables or random filenames.\n*/\n/* #include \"sqliteInt.h\" */\n\n\n/* All threads share a single random number generator.\n** This structure is the current state of the generator.\n*/\nstatic SQLITE_WSD struct sqlite3PrngType {\n  unsigned char isInit;          /* True if initialized */\n  unsigned char i, j;            /* State variables */\n  unsigned char s[256];          /* State variables */\n} sqlite3Prng;\n\n/*\n** Return N random bytes.\n*/\nSQLITE_API void sqlite3_randomness(int N, void *pBuf){\n  unsigned char t;\n  unsigned char *zBuf = pBuf;\n\n  /* The \"wsdPrng\" macro will resolve to the pseudo-random number generator\n  ** state vector.  If writable static data is unsupported on the target,\n  ** we have to locate the state vector at run-time.  In the more common\n  ** case where writable static data is supported, wsdPrng can refer directly\n  ** to the \"sqlite3Prng\" state vector declared above.\n  */\n#ifdef SQLITE_OMIT_WSD\n  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);\n# define wsdPrng p[0]\n#else\n# define wsdPrng sqlite3Prng\n#endif\n\n#if SQLITE_THREADSAFE\n  sqlite3_mutex *mutex;\n#endif\n\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return;\n#endif\n\n#if SQLITE_THREADSAFE\n  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);\n#endif\n\n  sqlite3_mutex_enter(mutex);\n  if( N<=0 || pBuf==0 ){\n    wsdPrng.isInit = 0;\n    sqlite3_mutex_leave(mutex);\n    return;\n  }\n\n  /* Initialize the state of the random number generator once,\n  ** the first time this routine is called.  The seed value does\n  ** not need to contain a lot of randomness since we are not\n  ** trying to do secure encryption or anything like that...\n  **\n  ** Nothing in this file or anywhere else in SQLite does any kind of\n  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random\n  ** number generator) not as an encryption device.\n  */\n  if( !wsdPrng.isInit ){\n    int i;\n    char k[256];\n    wsdPrng.j = 0;\n    wsdPrng.i = 0;\n    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);\n    for(i=0; i<256; i++){\n      wsdPrng.s[i] = (u8)i;\n    }\n    for(i=0; i<256; i++){\n      wsdPrng.j += wsdPrng.s[i] + k[i];\n      t = wsdPrng.s[wsdPrng.j];\n      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];\n      wsdPrng.s[i] = t;\n    }\n    wsdPrng.isInit = 1;\n  }\n\n  assert( N>0 );\n  do{\n    wsdPrng.i++;\n    t = wsdPrng.s[wsdPrng.i];\n    wsdPrng.j += t;\n    wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];\n    wsdPrng.s[wsdPrng.j] = t;\n    t += wsdPrng.s[wsdPrng.i];\n    *(zBuf++) = wsdPrng.s[t];\n  }while( --N );\n  sqlite3_mutex_leave(mutex);\n}\n\n#ifndef SQLITE_UNTESTABLE\n/*\n** For testing purposes, we sometimes want to preserve the state of\n** PRNG and restore the PRNG to its saved state at a later time, or\n** to reset the PRNG to its initial state.  These routines accomplish\n** those tasks.\n**\n** The sqlite3_test_control() interface calls these routines to\n** control the PRNG.\n*/\nstatic SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;\nSQLITE_PRIVATE void sqlite3PrngSaveState(void){\n  memcpy(\n    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),\n    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),\n    sizeof(sqlite3Prng)\n  );\n}\nSQLITE_PRIVATE void sqlite3PrngRestoreState(void){\n  memcpy(\n    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),\n    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),\n    sizeof(sqlite3Prng)\n  );\n}\n#endif /* SQLITE_UNTESTABLE */\n\n/************** End of random.c **********************************************/\n/************** Begin file threads.c *****************************************/\n/*\n** 2012 July 21\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file presents a simple cross-platform threading interface for\n** use internally by SQLite.\n**\n** A \"thread\" can be created using sqlite3ThreadCreate().  This thread\n** runs independently of its creator until it is joined using\n** sqlite3ThreadJoin(), at which point it terminates.\n**\n** Threads do not have to be real.  It could be that the work of the\n** \"thread\" is done by the main thread at either the sqlite3ThreadCreate()\n** or sqlite3ThreadJoin() call.  This is, in fact, what happens in\n** single threaded systems.  Nothing in SQLite requires multiple threads.\n** This interface exists so that applications that want to take advantage\n** of multiple cores can do so, while also allowing applications to stay\n** single-threaded if desired.\n*/\n/* #include \"sqliteInt.h\" */\n#if SQLITE_OS_WIN\n/* #  include \"os_win.h\" */\n#endif\n\n#if SQLITE_MAX_WORKER_THREADS>0\n\n/********************************* Unix Pthreads ****************************/\n#if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0\n\n#define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */\n/* #include <pthread.h> */\n\n/* A running thread */\nstruct SQLiteThread {\n  pthread_t tid;                 /* Thread ID */\n  int done;                      /* Set to true when thread finishes */\n  void *pOut;                    /* Result returned by the thread */\n  void *(*xTask)(void*);         /* The thread routine */\n  void *pIn;                     /* Argument to the thread */\n};\n\n/* Create a new thread */\nSQLITE_PRIVATE int sqlite3ThreadCreate(\n  SQLiteThread **ppThread,  /* OUT: Write the thread object here */\n  void *(*xTask)(void*),    /* Routine to run in a separate thread */\n  void *pIn                 /* Argument passed into xTask() */\n){\n  SQLiteThread *p;\n  int rc;\n\n  assert( ppThread!=0 );\n  assert( xTask!=0 );\n  /* This routine is never used in single-threaded mode */\n  assert( sqlite3GlobalConfig.bCoreMutex!=0 );\n\n  *ppThread = 0;\n  p = sqlite3Malloc(sizeof(*p));\n  if( p==0 ) return SQLITE_NOMEM_BKPT;\n  memset(p, 0, sizeof(*p));\n  p->xTask = xTask;\n  p->pIn = pIn;\n  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a \n  ** function that returns SQLITE_ERROR when passed the argument 200, that\n  ** forces worker threads to run sequentially and deterministically \n  ** for testing purposes. */\n  if( sqlite3FaultSim(200) ){\n    rc = 1;\n  }else{    \n    rc = pthread_create(&p->tid, 0, xTask, pIn);\n  }\n  if( rc ){\n    p->done = 1;\n    p->pOut = xTask(pIn);\n  }\n  *ppThread = p;\n  return SQLITE_OK;\n}\n\n/* Get the results of the thread */\nSQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){\n  int rc;\n\n  assert( ppOut!=0 );\n  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;\n  if( p->done ){\n    *ppOut = p->pOut;\n    rc = SQLITE_OK;\n  }else{\n    rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;\n  }\n  sqlite3_free(p);\n  return rc;\n}\n\n#endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */\n/******************************** End Unix Pthreads *************************/\n\n\n/********************************* Win32 Threads ****************************/\n#if SQLITE_OS_WIN_THREADS\n\n#define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */\n#include <process.h>\n\n/* A running thread */\nstruct SQLiteThread {\n  void *tid;               /* The thread handle */\n  unsigned id;             /* The thread identifier */\n  void *(*xTask)(void*);   /* The routine to run as a thread */\n  void *pIn;               /* Argument to xTask */\n  void *pResult;           /* Result of xTask */\n};\n\n/* Thread procedure Win32 compatibility shim */\nstatic unsigned __stdcall sqlite3ThreadProc(\n  void *pArg  /* IN: Pointer to the SQLiteThread structure */\n){\n  SQLiteThread *p = (SQLiteThread *)pArg;\n\n  assert( p!=0 );\n#if 0\n  /*\n  ** This assert appears to trigger spuriously on certain\n  ** versions of Windows, possibly due to _beginthreadex()\n  ** and/or CreateThread() not fully setting their thread\n  ** ID parameter before starting the thread.\n  */\n  assert( p->id==GetCurrentThreadId() );\n#endif\n  assert( p->xTask!=0 );\n  p->pResult = p->xTask(p->pIn);\n\n  _endthreadex(0);\n  return 0; /* NOT REACHED */\n}\n\n/* Create a new thread */\nSQLITE_PRIVATE int sqlite3ThreadCreate(\n  SQLiteThread **ppThread,  /* OUT: Write the thread object here */\n  void *(*xTask)(void*),    /* Routine to run in a separate thread */\n  void *pIn                 /* Argument passed into xTask() */\n){\n  SQLiteThread *p;\n\n  assert( ppThread!=0 );\n  assert( xTask!=0 );\n  *ppThread = 0;\n  p = sqlite3Malloc(sizeof(*p));\n  if( p==0 ) return SQLITE_NOMEM_BKPT;\n  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a \n  ** function that returns SQLITE_ERROR when passed the argument 200, that\n  ** forces worker threads to run sequentially and deterministically \n  ** (via the sqlite3FaultSim() term of the conditional) for testing\n  ** purposes. */\n  if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){\n    memset(p, 0, sizeof(*p));\n  }else{\n    p->xTask = xTask;\n    p->pIn = pIn;\n    p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);\n    if( p->tid==0 ){\n      memset(p, 0, sizeof(*p));\n    }\n  }\n  if( p->xTask==0 ){\n    p->id = GetCurrentThreadId();\n    p->pResult = xTask(pIn);\n  }\n  *ppThread = p;\n  return SQLITE_OK;\n}\n\nSQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */\n\n/* Get the results of the thread */\nSQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){\n  DWORD rc;\n  BOOL bRc;\n\n  assert( ppOut!=0 );\n  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;\n  if( p->xTask==0 ){\n    /* assert( p->id==GetCurrentThreadId() ); */\n    rc = WAIT_OBJECT_0;\n    assert( p->tid==0 );\n  }else{\n    assert( p->id!=0 && p->id!=GetCurrentThreadId() );\n    rc = sqlite3Win32Wait((HANDLE)p->tid);\n    assert( rc!=WAIT_IO_COMPLETION );\n    bRc = CloseHandle((HANDLE)p->tid);\n    assert( bRc );\n  }\n  if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;\n  sqlite3_free(p);\n  return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;\n}\n\n#endif /* SQLITE_OS_WIN_THREADS */\n/******************************** End Win32 Threads *************************/\n\n\n/********************************* Single-Threaded **************************/\n#ifndef SQLITE_THREADS_IMPLEMENTED\n/*\n** This implementation does not actually create a new thread.  It does the\n** work of the thread in the main thread, when either the thread is created\n** or when it is joined\n*/\n\n/* A running thread */\nstruct SQLiteThread {\n  void *(*xTask)(void*);   /* The routine to run as a thread */\n  void *pIn;               /* Argument to xTask */\n  void *pResult;           /* Result of xTask */\n};\n\n/* Create a new thread */\nSQLITE_PRIVATE int sqlite3ThreadCreate(\n  SQLiteThread **ppThread,  /* OUT: Write the thread object here */\n  void *(*xTask)(void*),    /* Routine to run in a separate thread */\n  void *pIn                 /* Argument passed into xTask() */\n){\n  SQLiteThread *p;\n\n  assert( ppThread!=0 );\n  assert( xTask!=0 );\n  *ppThread = 0;\n  p = sqlite3Malloc(sizeof(*p));\n  if( p==0 ) return SQLITE_NOMEM_BKPT;\n  if( (SQLITE_PTR_TO_INT(p)/17)&1 ){\n    p->xTask = xTask;\n    p->pIn = pIn;\n  }else{\n    p->xTask = 0;\n    p->pResult = xTask(pIn);\n  }\n  *ppThread = p;\n  return SQLITE_OK;\n}\n\n/* Get the results of the thread */\nSQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){\n\n  assert( ppOut!=0 );\n  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;\n  if( p->xTask ){\n    *ppOut = p->xTask(p->pIn);\n  }else{\n    *ppOut = p->pResult;\n  }\n  sqlite3_free(p);\n\n#if defined(SQLITE_TEST)\n  {\n    void *pTstAlloc = sqlite3Malloc(10);\n    if (!pTstAlloc) return SQLITE_NOMEM_BKPT;\n    sqlite3_free(pTstAlloc);\n  }\n#endif\n\n  return SQLITE_OK;\n}\n\n#endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */\n/****************************** End Single-Threaded *************************/\n#endif /* SQLITE_MAX_WORKER_THREADS>0 */\n\n/************** End of threads.c *********************************************/\n/************** Begin file utf.c *********************************************/\n/*\n** 2004 April 13\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains routines used to translate between UTF-8, \n** UTF-16, UTF-16BE, and UTF-16LE.\n**\n** Notes on UTF-8:\n**\n**   Byte-0    Byte-1    Byte-2    Byte-3    Value\n**  0xxxxxxx                                 00000000 00000000 0xxxxxxx\n**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx\n**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx\n**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx\n**\n**\n** Notes on UTF-16:  (with wwww+1==uuuuu)\n**\n**      Word-0               Word-1          Value\n**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx\n**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx\n**\n**\n** BOM or Byte Order Mark:\n**     0xff 0xfe   little-endian utf-16 follows\n**     0xfe 0xff   big-endian utf-16 follows\n**\n*/\n/* #include \"sqliteInt.h\" */\n/* #include <assert.h> */\n/* #include \"vdbeInt.h\" */\n\n#if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0\n/*\n** The following constant value is used by the SQLITE_BIGENDIAN and\n** SQLITE_LITTLEENDIAN macros.\n*/\nSQLITE_PRIVATE const int sqlite3one = 1;\n#endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */\n\n/*\n** This lookup table is used to help decode the first byte of\n** a multi-byte UTF8 character.\n*/\nstatic const unsigned char sqlite3Utf8Trans1[] = {\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,\n  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,\n  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,\n};\n\n\n#define WRITE_UTF8(zOut, c) {                          \\\n  if( c<0x00080 ){                                     \\\n    *zOut++ = (u8)(c&0xFF);                            \\\n  }                                                    \\\n  else if( c<0x00800 ){                                \\\n    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \\\n    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \\\n  }                                                    \\\n  else if( c<0x10000 ){                                \\\n    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \\\n    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \\\n    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \\\n  }else{                                               \\\n    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \\\n    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \\\n    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \\\n    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \\\n  }                                                    \\\n}\n\n#define WRITE_UTF16LE(zOut, c) {                                    \\\n  if( c<=0xFFFF ){                                                  \\\n    *zOut++ = (u8)(c&0x00FF);                                       \\\n    *zOut++ = (u8)((c>>8)&0x00FF);                                  \\\n  }else{                                                            \\\n    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \\\n    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \\\n    *zOut++ = (u8)(c&0x00FF);                                       \\\n    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \\\n  }                                                                 \\\n}\n\n#define WRITE_UTF16BE(zOut, c) {                                    \\\n  if( c<=0xFFFF ){                                                  \\\n    *zOut++ = (u8)((c>>8)&0x00FF);                                  \\\n    *zOut++ = (u8)(c&0x00FF);                                       \\\n  }else{                                                            \\\n    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \\\n    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \\\n    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \\\n    *zOut++ = (u8)(c&0x00FF);                                       \\\n  }                                                                 \\\n}\n\n/*\n** Translate a single UTF-8 character.  Return the unicode value.\n**\n** During translation, assume that the byte that zTerm points\n** is a 0x00.\n**\n** Write a pointer to the next unread byte back into *pzNext.\n**\n** Notes On Invalid UTF-8:\n**\n**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to\n**     be encoded as a multi-byte character.  Any multi-byte character that\n**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.\n**\n**  *  This routine never allows a UTF16 surrogate value to be encoded.\n**     If a multi-byte character attempts to encode a value between\n**     0xd800 and 0xe000 then it is rendered as 0xfffd.\n**\n**  *  Bytes in the range of 0x80 through 0xbf which occur as the first\n**     byte of a character are interpreted as single-byte characters\n**     and rendered as themselves even though they are technically\n**     invalid characters.\n**\n**  *  This routine accepts over-length UTF8 encodings\n**     for unicode values 0x80 and greater.  It does not change over-length\n**     encodings to 0xfffd as some systems recommend.\n*/\n#define READ_UTF8(zIn, zTerm, c)                           \\\n  c = *(zIn++);                                            \\\n  if( c>=0xc0 ){                                           \\\n    c = sqlite3Utf8Trans1[c-0xc0];                         \\\n    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \\\n      c = (c<<6) + (0x3f & *(zIn++));                      \\\n    }                                                      \\\n    if( c<0x80                                             \\\n        || (c&0xFFFFF800)==0xD800                          \\\n        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \\\n  }\nSQLITE_PRIVATE u32 sqlite3Utf8Read(\n  const unsigned char **pz    /* Pointer to string from which to read char */\n){\n  unsigned int c;\n\n  /* Same as READ_UTF8() above but without the zTerm parameter.\n  ** For this routine, we assume the UTF8 string is always zero-terminated.\n  */\n  c = *((*pz)++);\n  if( c>=0xc0 ){\n    c = sqlite3Utf8Trans1[c-0xc0];\n    while( (*(*pz) & 0xc0)==0x80 ){\n      c = (c<<6) + (0x3f & *((*pz)++));\n    }\n    if( c<0x80\n        || (c&0xFFFFF800)==0xD800\n        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }\n  }\n  return c;\n}\n\n\n\n\n/*\n** If the TRANSLATE_TRACE macro is defined, the value of each Mem is\n** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().\n*/ \n/* #define TRANSLATE_TRACE 1 */\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** This routine transforms the internal text encoding used by pMem to\n** desiredEnc. It is an error if the string is already of the desired\n** encoding, or if *pMem does not contain a string value.\n*/\nSQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){\n  sqlite3_int64 len;          /* Maximum length of output string in bytes */\n  unsigned char *zOut;        /* Output buffer */\n  unsigned char *zIn;         /* Input iterator */\n  unsigned char *zTerm;       /* End of input */\n  unsigned char *z;           /* Output iterator */\n  unsigned int c;\n\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( pMem->flags&MEM_Str );\n  assert( pMem->enc!=desiredEnc );\n  assert( pMem->enc!=0 );\n  assert( pMem->n>=0 );\n\n#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)\n  {\n    StrAccum acc;\n    char zBuf[1000];\n    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);  \n    sqlite3VdbeMemPrettyPrint(pMem, &acc);\n    fprintf(stderr, \"INPUT:  %s\\n\", sqlite3StrAccumFinish(&acc));\n  }\n#endif\n\n  /* If the translation is between UTF-16 little and big endian, then \n  ** all that is required is to swap the byte order. This case is handled\n  ** differently from the others.\n  */\n  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){\n    u8 temp;\n    int rc;\n    rc = sqlite3VdbeMemMakeWriteable(pMem);\n    if( rc!=SQLITE_OK ){\n      assert( rc==SQLITE_NOMEM );\n      return SQLITE_NOMEM_BKPT;\n    }\n    zIn = (u8*)pMem->z;\n    zTerm = &zIn[pMem->n&~1];\n    while( zIn<zTerm ){\n      temp = *zIn;\n      *zIn = *(zIn+1);\n      zIn++;\n      *zIn++ = temp;\n    }\n    pMem->enc = desiredEnc;\n    goto translate_out;\n  }\n\n  /* Set len to the maximum number of bytes required in the output buffer. */\n  if( desiredEnc==SQLITE_UTF8 ){\n    /* When converting from UTF-16, the maximum growth results from\n    ** translating a 2-byte character to a 4-byte UTF-8 character.\n    ** A single byte is required for the output string\n    ** nul-terminator.\n    */\n    pMem->n &= ~1;\n    len = 2 * (sqlite3_int64)pMem->n + 1;\n  }else{\n    /* When converting from UTF-8 to UTF-16 the maximum growth is caused\n    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16\n    ** character. Two bytes are required in the output buffer for the\n    ** nul-terminator.\n    */\n    len = 2 * (sqlite3_int64)pMem->n + 2;\n  }\n\n  /* Set zIn to point at the start of the input buffer and zTerm to point 1\n  ** byte past the end.\n  **\n  ** Variable zOut is set to point at the output buffer, space obtained\n  ** from sqlite3_malloc().\n  */\n  zIn = (u8*)pMem->z;\n  zTerm = &zIn[pMem->n];\n  zOut = sqlite3DbMallocRaw(pMem->db, len);\n  if( !zOut ){\n    return SQLITE_NOMEM_BKPT;\n  }\n  z = zOut;\n\n  if( pMem->enc==SQLITE_UTF8 ){\n    if( desiredEnc==SQLITE_UTF16LE ){\n      /* UTF-8 -> UTF-16 Little-endian */\n      while( zIn<zTerm ){\n        READ_UTF8(zIn, zTerm, c);\n        WRITE_UTF16LE(z, c);\n      }\n    }else{\n      assert( desiredEnc==SQLITE_UTF16BE );\n      /* UTF-8 -> UTF-16 Big-endian */\n      while( zIn<zTerm ){\n        READ_UTF8(zIn, zTerm, c);\n        WRITE_UTF16BE(z, c);\n      }\n    }\n    pMem->n = (int)(z - zOut);\n    *z++ = 0;\n  }else{\n    assert( desiredEnc==SQLITE_UTF8 );\n    if( pMem->enc==SQLITE_UTF16LE ){\n      /* UTF-16 Little-endian -> UTF-8 */\n      while( zIn<zTerm ){\n        c = *(zIn++);\n        c += (*(zIn++))<<8;\n        if( c>=0xd800 && c<0xe000 ){\n#ifdef SQLITE_REPLACE_INVALID_UTF\n          if( c>=0xdc00 || zIn>=zTerm ){\n            c = 0xfffd;\n          }else{\n            int c2 = *(zIn++);\n            c2 += (*(zIn++))<<8;\n            if( c2<0xdc00 || c2>=0xe000 ){\n              zIn -= 2;\n              c = 0xfffd;\n            }else{\n              c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000;\n            }\n          }\n#else\n          if( zIn<zTerm ){\n            int c2 = (*zIn++);\n            c2 += ((*zIn++)<<8);\n            c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);\n          }\n#endif\n        }\n        WRITE_UTF8(z, c);\n      }\n    }else{\n      /* UTF-16 Big-endian -> UTF-8 */\n      while( zIn<zTerm ){\n        c = (*(zIn++))<<8;\n        c += *(zIn++);\n        if( c>=0xd800 && c<0xe000 ){\n#ifdef SQLITE_REPLACE_INVALID_UTF\n          if( c>=0xdc00 || zIn>=zTerm ){\n            c = 0xfffd;\n          }else{\n            int c2 = (*(zIn++))<<8;\n            c2 += *(zIn++);\n            if( c2<0xdc00 || c2>=0xe000 ){\n              zIn -= 2;\n              c = 0xfffd;\n            }else{\n              c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000;\n            }\n          }\n#else\n          if( zIn<zTerm ){\n            int c2 = ((*zIn++)<<8);\n            c2 += (*zIn++);\n            c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);\n          }\n#endif\n        }\n        WRITE_UTF8(z, c);\n      }\n    }\n    pMem->n = (int)(z - zOut);\n  }\n  *z = 0;\n  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );\n\n  c = pMem->flags;\n  sqlite3VdbeMemRelease(pMem);\n  pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));\n  pMem->enc = desiredEnc;\n  pMem->z = (char*)zOut;\n  pMem->zMalloc = pMem->z;\n  pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);\n\ntranslate_out:\n#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)\n  {\n    StrAccum acc;\n    char zBuf[1000];\n    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);  \n    sqlite3VdbeMemPrettyPrint(pMem, &acc);\n    fprintf(stderr, \"OUTPUT: %s\\n\", sqlite3StrAccumFinish(&acc));\n  }\n#endif\n  return SQLITE_OK;\n}\n#endif /* SQLITE_OMIT_UTF16 */\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** This routine checks for a byte-order mark at the beginning of the \n** UTF-16 string stored in *pMem. If one is present, it is removed and\n** the encoding of the Mem adjusted. This routine does not do any\n** byte-swapping, it just sets Mem.enc appropriately.\n**\n** The allocation (static, dynamic etc.) and encoding of the Mem may be\n** changed by this function.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){\n  int rc = SQLITE_OK;\n  u8 bom = 0;\n\n  assert( pMem->n>=0 );\n  if( pMem->n>1 ){\n    u8 b1 = *(u8 *)pMem->z;\n    u8 b2 = *(((u8 *)pMem->z) + 1);\n    if( b1==0xFE && b2==0xFF ){\n      bom = SQLITE_UTF16BE;\n    }\n    if( b1==0xFF && b2==0xFE ){\n      bom = SQLITE_UTF16LE;\n    }\n  }\n  \n  if( bom ){\n    rc = sqlite3VdbeMemMakeWriteable(pMem);\n    if( rc==SQLITE_OK ){\n      pMem->n -= 2;\n      memmove(pMem->z, &pMem->z[2], pMem->n);\n      pMem->z[pMem->n] = '\\0';\n      pMem->z[pMem->n+1] = '\\0';\n      pMem->flags |= MEM_Term;\n      pMem->enc = bom;\n    }\n  }\n  return rc;\n}\n#endif /* SQLITE_OMIT_UTF16 */\n\n/*\n** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,\n** return the number of unicode characters in pZ up to (but not including)\n** the first 0x00 byte. If nByte is not less than zero, return the\n** number of unicode characters in the first nByte of pZ (or up to \n** the first 0x00, whichever comes first).\n*/\nSQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){\n  int r = 0;\n  const u8 *z = (const u8*)zIn;\n  const u8 *zTerm;\n  if( nByte>=0 ){\n    zTerm = &z[nByte];\n  }else{\n    zTerm = (const u8*)(-1);\n  }\n  assert( z<=zTerm );\n  while( *z!=0 && z<zTerm ){\n    SQLITE_SKIP_UTF8(z);\n    r++;\n  }\n  return r;\n}\n\n/* This test function is not currently used by the automated test-suite. \n** Hence it is only available in debug builds.\n*/\n#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)\n/*\n** Translate UTF-8 to UTF-8.\n**\n** This has the effect of making sure that the string is well-formed\n** UTF-8.  Miscoded characters are removed.\n**\n** The translation is done in-place and aborted if the output\n** overruns the input.\n*/\nSQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){\n  unsigned char *zOut = zIn;\n  unsigned char *zStart = zIn;\n  u32 c;\n\n  while( zIn[0] && zOut<=zIn ){\n    c = sqlite3Utf8Read((const u8**)&zIn);\n    if( c!=0xfffd ){\n      WRITE_UTF8(zOut, c);\n    }\n  }\n  *zOut = 0;\n  return (int)(zOut - zStart);\n}\n#endif\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** Convert a UTF-16 string in the native encoding into a UTF-8 string.\n** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must\n** be freed by the calling function.\n**\n** NULL is returned if there is an allocation error.\n*/\nSQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){\n  Mem m;\n  memset(&m, 0, sizeof(m));\n  m.db = db;\n  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);\n  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);\n  if( db->mallocFailed ){\n    sqlite3VdbeMemRelease(&m);\n    m.z = 0;\n  }\n  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );\n  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );\n  assert( m.z || db->mallocFailed );\n  return m.z;\n}\n\n/*\n** zIn is a UTF-16 encoded unicode string at least nChar characters long.\n** Return the number of bytes in the first nChar unicode characters\n** in pZ.  nChar must be non-negative.\n*/\nSQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){\n  int c;\n  unsigned char const *z = zIn;\n  int n = 0;\n  \n  if( SQLITE_UTF16NATIVE==SQLITE_UTF16LE ) z++;\n  while( n<nChar ){\n    c = z[0];\n    z += 2;\n    if( c>=0xd8 && c<0xdc && z[0]>=0xdc && z[0]<0xe0 ) z += 2;\n    n++;\n  }\n  return (int)(z-(unsigned char const *)zIn) \n              - (SQLITE_UTF16NATIVE==SQLITE_UTF16LE);\n}\n\n#if defined(SQLITE_TEST)\n/*\n** This routine is called from the TCL test function \"translate_selftest\".\n** It checks that the primitives for serializing and deserializing\n** characters in each encoding are inverses of each other.\n*/\nSQLITE_PRIVATE void sqlite3UtfSelfTest(void){\n  unsigned int i, t;\n  unsigned char zBuf[20];\n  unsigned char *z;\n  int n;\n  unsigned int c;\n\n  for(i=0; i<0x00110000; i++){\n    z = zBuf;\n    WRITE_UTF8(z, i);\n    n = (int)(z-zBuf);\n    assert( n>0 && n<=4 );\n    z[0] = 0;\n    z = zBuf;\n    c = sqlite3Utf8Read((const u8**)&z);\n    t = i;\n    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;\n    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;\n    assert( c==t );\n    assert( (z-zBuf)==n );\n  }\n}\n#endif /* SQLITE_TEST */\n#endif /* SQLITE_OMIT_UTF16 */\n\n/************** End of utf.c *************************************************/\n/************** Begin file util.c ********************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** Utility functions used throughout sqlite.\n**\n** This file contains functions for allocating memory, comparing\n** strings, and stuff like that.\n**\n*/\n/* #include \"sqliteInt.h\" */\n/* #include <stdarg.h> */\n#ifndef SQLITE_OMIT_FLOATING_POINT\n#include <math.h>\n#endif\n\n/*\n** Routine needed to support the testcase() macro.\n*/\n#ifdef SQLITE_COVERAGE_TEST\nSQLITE_PRIVATE void sqlite3Coverage(int x){\n  static unsigned dummy = 0;\n  dummy += (unsigned)x;\n}\n#endif\n\n/*\n** Calls to sqlite3FaultSim() are used to simulate a failure during testing,\n** or to bypass normal error detection during testing in order to let \n** execute proceed futher downstream.\n**\n** In deployment, sqlite3FaultSim() *always* return SQLITE_OK (0).  The\n** sqlite3FaultSim() function only returns non-zero during testing.\n**\n** During testing, if the test harness has set a fault-sim callback using\n** a call to sqlite3_test_control(SQLITE_TESTCTRL_FAULT_INSTALL), then\n** each call to sqlite3FaultSim() is relayed to that application-supplied\n** callback and the integer return value form the application-supplied\n** callback is returned by sqlite3FaultSim().\n**\n** The integer argument to sqlite3FaultSim() is a code to identify which\n** sqlite3FaultSim() instance is being invoked. Each call to sqlite3FaultSim()\n** should have a unique code.  To prevent legacy testing applications from\n** breaking, the codes should not be changed or reused.\n*/\n#ifndef SQLITE_UNTESTABLE\nSQLITE_PRIVATE int sqlite3FaultSim(int iTest){\n  int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;\n  return xCallback ? xCallback(iTest) : SQLITE_OK;\n}\n#endif\n\n#ifndef SQLITE_OMIT_FLOATING_POINT\n/*\n** Return true if the floating point value is Not a Number (NaN).\n*/\nSQLITE_PRIVATE int sqlite3IsNaN(double x){\n  u64 y;\n  memcpy(&y,&x,sizeof(y));\n  return IsNaN(y);\n}\n#endif /* SQLITE_OMIT_FLOATING_POINT */\n\n/*\n** Compute a string length that is limited to what can be stored in\n** lower 30 bits of a 32-bit signed integer.\n**\n** The value returned will never be negative.  Nor will it ever be greater\n** than the actual length of the string.  For very long strings (greater\n** than 1GiB) the value returned might be less than the true string length.\n*/\nSQLITE_PRIVATE int sqlite3Strlen30(const char *z){\n  if( z==0 ) return 0;\n  return 0x3fffffff & (int)strlen(z);\n}\n\n/*\n** Return the declared type of a column.  Or return zDflt if the column \n** has no declared type.\n**\n** The column type is an extra string stored after the zero-terminator on\n** the column name if and only if the COLFLAG_HASTYPE flag is set.\n*/\nSQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){\n  if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;\n  return pCol->zName + strlen(pCol->zName) + 1;\n}\n\n/*\n** Helper function for sqlite3Error() - called rarely.  Broken out into\n** a separate routine to avoid unnecessary register saves on entry to\n** sqlite3Error().\n*/\nstatic SQLITE_NOINLINE void  sqlite3ErrorFinish(sqlite3 *db, int err_code){\n  if( db->pErr ) sqlite3ValueSetNull(db->pErr);\n  sqlite3SystemError(db, err_code);\n}\n\n/*\n** Set the current error code to err_code and clear any prior error message.\n** Also set iSysErrno (by calling sqlite3System) if the err_code indicates\n** that would be appropriate.\n*/\nSQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){\n  assert( db!=0 );\n  db->errCode = err_code;\n  if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);\n}\n\n/*\n** Load the sqlite3.iSysErrno field if that is an appropriate thing\n** to do based on the SQLite error code in rc.\n*/\nSQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){\n  if( rc==SQLITE_IOERR_NOMEM ) return;\n  rc &= 0xff;\n  if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){\n    db->iSysErrno = sqlite3OsGetLastError(db->pVfs);\n  }\n}\n\n/*\n** Set the most recent error code and error string for the sqlite\n** handle \"db\". The error code is set to \"err_code\".\n**\n** If it is not NULL, string zFormat specifies the format of the\n** error string in the style of the printf functions: The following\n** format characters are allowed:\n**\n**      %s      Insert a string\n**      %z      A string that should be freed after use\n**      %d      Insert an integer\n**      %T      Insert a token\n**      %S      Insert the first element of a SrcList\n**\n** zFormat and any string tokens that follow it are assumed to be\n** encoded in UTF-8.\n**\n** To clear the most recent error for sqlite handle \"db\", sqlite3Error\n** should be called with err_code set to SQLITE_OK and zFormat set\n** to NULL.\n*/\nSQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){\n  assert( db!=0 );\n  db->errCode = err_code;\n  sqlite3SystemError(db, err_code);\n  if( zFormat==0 ){\n    sqlite3Error(db, err_code);\n  }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){\n    char *z;\n    va_list ap;\n    va_start(ap, zFormat);\n    z = sqlite3VMPrintf(db, zFormat, ap);\n    va_end(ap);\n    sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);\n  }\n}\n\n/*\n** Add an error message to pParse->zErrMsg and increment pParse->nErr.\n** The following formatting characters are allowed:\n**\n**      %s      Insert a string\n**      %z      A string that should be freed after use\n**      %d      Insert an integer\n**      %T      Insert a token\n**      %S      Insert the first element of a SrcList\n**\n** This function should be used to report any error that occurs while\n** compiling an SQL statement (i.e. within sqlite3_prepare()). The\n** last thing the sqlite3_prepare() function does is copy the error\n** stored by this function into the database handle using sqlite3Error().\n** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used\n** during statement execution (sqlite3_step() etc.).\n*/\nSQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){\n  char *zMsg;\n  va_list ap;\n  sqlite3 *db = pParse->db;\n  va_start(ap, zFormat);\n  zMsg = sqlite3VMPrintf(db, zFormat, ap);\n  va_end(ap);\n  if( db->suppressErr ){\n    sqlite3DbFree(db, zMsg);\n  }else{\n    pParse->nErr++;\n    sqlite3DbFree(db, pParse->zErrMsg);\n    pParse->zErrMsg = zMsg;\n    pParse->rc = SQLITE_ERROR;\n    pParse->pWith = 0;\n  }\n}\n\n/*\n** If database connection db is currently parsing SQL, then transfer\n** error code errCode to that parser if the parser has not already\n** encountered some other kind of error.\n*/\nSQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3 *db, int errCode){\n  Parse *pParse;\n  if( db==0 || (pParse = db->pParse)==0 ) return errCode;\n  pParse->rc = errCode;\n  pParse->nErr++;\n  return errCode;\n}\n\n/*\n** Convert an SQL-style quoted string into a normal string by removing\n** the quote characters.  The conversion is done in-place.  If the\n** input does not begin with a quote character, then this routine\n** is a no-op.\n**\n** The input string must be zero-terminated.  A new zero-terminator\n** is added to the dequoted string.\n**\n** The return value is -1 if no dequoting occurs or the length of the\n** dequoted string, exclusive of the zero terminator, if dequoting does\n** occur.\n**\n** 2002-02-14: This routine is extended to remove MS-Access style\n** brackets from around identifiers.  For example:  \"[a-b-c]\" becomes\n** \"a-b-c\".\n*/\nSQLITE_PRIVATE void sqlite3Dequote(char *z){\n  char quote;\n  int i, j;\n  if( z==0 ) return;\n  quote = z[0];\n  if( !sqlite3Isquote(quote) ) return;\n  if( quote=='[' ) quote = ']';\n  for(i=1, j=0;; i++){\n    assert( z[i] );\n    if( z[i]==quote ){\n      if( z[i+1]==quote ){\n        z[j++] = quote;\n        i++;\n      }else{\n        break;\n      }\n    }else{\n      z[j++] = z[i];\n    }\n  }\n  z[j] = 0;\n}\nSQLITE_PRIVATE void sqlite3DequoteExpr(Expr *p){\n  assert( sqlite3Isquote(p->u.zToken[0]) );\n  p->flags |= p->u.zToken[0]=='\"' ? EP_Quoted|EP_DblQuoted : EP_Quoted;\n  sqlite3Dequote(p->u.zToken);\n}\n\n/*\n** Generate a Token object from a string\n*/\nSQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){\n  p->z = z;\n  p->n = sqlite3Strlen30(z);\n}\n\n/* Convenient short-hand */\n#define UpperToLower sqlite3UpperToLower\n\n/*\n** Some systems have stricmp().  Others have strcasecmp().  Because\n** there is no consistency, we will define our own.\n**\n** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and\n** sqlite3_strnicmp() APIs allow applications and extensions to compare\n** the contents of two buffers containing UTF-8 strings in a\n** case-independent fashion, using the same definition of \"case\n** independence\" that SQLite uses internally when comparing identifiers.\n*/\nSQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){\n  if( zLeft==0 ){\n    return zRight ? -1 : 0;\n  }else if( zRight==0 ){\n    return 1;\n  }\n  return sqlite3StrICmp(zLeft, zRight);\n}\nSQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){\n  unsigned char *a, *b;\n  int c, x;\n  a = (unsigned char *)zLeft;\n  b = (unsigned char *)zRight;\n  for(;;){\n    c = *a;\n    x = *b;\n    if( c==x ){\n      if( c==0 ) break;\n    }else{\n      c = (int)UpperToLower[c] - (int)UpperToLower[x];\n      if( c ) break;\n    }\n    a++;\n    b++;\n  }\n  return c;\n}\nSQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){\n  register unsigned char *a, *b;\n  if( zLeft==0 ){\n    return zRight ? -1 : 0;\n  }else if( zRight==0 ){\n    return 1;\n  }\n  a = (unsigned char *)zLeft;\n  b = (unsigned char *)zRight;\n  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }\n  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];\n}\n\n/*\n** Compute an 8-bit hash on a string that is insensitive to case differences\n*/\nSQLITE_PRIVATE u8 sqlite3StrIHash(const char *z){\n  u8 h = 0;\n  if( z==0 ) return 0;\n  while( z[0] ){\n    h += UpperToLower[(unsigned char)z[0]];\n    z++;\n  }\n  return h;\n}\n\n/*\n** Compute 10 to the E-th power.  Examples:  E==1 results in 10.\n** E==2 results in 100.  E==50 results in 1.0e50.\n**\n** This routine only works for values of E between 1 and 341.\n*/\nstatic LONGDOUBLE_TYPE sqlite3Pow10(int E){\n#if defined(_MSC_VER)\n  static const LONGDOUBLE_TYPE x[] = {\n    1.0e+001L,\n    1.0e+002L,\n    1.0e+004L,\n    1.0e+008L,\n    1.0e+016L,\n    1.0e+032L,\n    1.0e+064L,\n    1.0e+128L,\n    1.0e+256L\n  };\n  LONGDOUBLE_TYPE r = 1.0;\n  int i;\n  assert( E>=0 && E<=307 );\n  for(i=0; E!=0; i++, E >>=1){\n    if( E & 1 ) r *= x[i];\n  }\n  return r;\n#else\n  LONGDOUBLE_TYPE x = 10.0;\n  LONGDOUBLE_TYPE r = 1.0;\n  while(1){\n    if( E & 1 ) r *= x;\n    E >>= 1;\n    if( E==0 ) break;\n    x *= x;\n  }\n  return r; \n#endif\n}\n\n/*\n** The string z[] is an text representation of a real number.\n** Convert this string to a double and write it into *pResult.\n**\n** The string z[] is length bytes in length (bytes, not characters) and\n** uses the encoding enc.  The string is not necessarily zero-terminated.\n**\n** Return TRUE if the result is a valid real number (or integer) and FALSE\n** if the string is empty or contains extraneous text.  More specifically\n** return\n**      1          =>  The input string is a pure integer\n**      2 or more  =>  The input has a decimal point or eNNN clause\n**      0 or less  =>  The input string is not a valid number\n**     -1          =>  Not a valid number, but has a valid prefix which \n**                     includes a decimal point and/or an eNNN clause\n**\n** Valid numbers are in one of these formats:\n**\n**    [+-]digits[E[+-]digits]\n**    [+-]digits.[digits][E[+-]digits]\n**    [+-].digits[E[+-]digits]\n**\n** Leading and trailing whitespace is ignored for the purpose of determining\n** validity.\n**\n** If some prefix of the input string is a valid number, this routine\n** returns FALSE but it still converts the prefix and writes the result\n** into *pResult.\n*/\n#if defined(_MSC_VER)\n#pragma warning(disable : 4756)\n#endif\nSQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){\n#ifndef SQLITE_OMIT_FLOATING_POINT\n  int incr;\n  const char *zEnd;\n  /* sign * significand * (10 ^ (esign * exponent)) */\n  int sign = 1;    /* sign of significand */\n  i64 s = 0;       /* significand */\n  int d = 0;       /* adjust exponent for shifting decimal point */\n  int esign = 1;   /* sign of exponent */\n  int e = 0;       /* exponent */\n  int eValid = 1;  /* True exponent is either not used or is well-formed */\n  double result;\n  int nDigit = 0;  /* Number of digits processed */\n  int eType = 1;   /* 1: pure integer,  2+: fractional  -1 or less: bad UTF16 */\n\n  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );\n  *pResult = 0.0;   /* Default return value, in case of an error */\n  if( length==0 ) return 0;\n\n  if( enc==SQLITE_UTF8 ){\n    incr = 1;\n    zEnd = z + length;\n  }else{\n    int i;\n    incr = 2;\n    length &= ~1;\n    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );\n    testcase( enc==SQLITE_UTF16LE );\n    testcase( enc==SQLITE_UTF16BE );\n    for(i=3-enc; i<length && z[i]==0; i+=2){}\n    if( i<length ) eType = -100;\n    zEnd = &z[i^1];\n    z += (enc&1);\n  }\n\n  /* skip leading spaces */\n  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;\n  if( z>=zEnd ) return 0;\n\n  /* get sign of significand */\n  if( *z=='-' ){\n    sign = -1;\n    z+=incr;\n  }else if( *z=='+' ){\n    z+=incr;\n  }\n\n  /* copy max significant digits to significand */\n  while( z<zEnd && sqlite3Isdigit(*z) ){\n    s = s*10 + (*z - '0');\n    z+=incr; nDigit++;\n    if( s>=((LARGEST_INT64-9)/10) ){\n      /* skip non-significant significand digits\n      ** (increase exponent by d to shift decimal left) */\n      while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; d++; }\n    }\n  }\n  if( z>=zEnd ) goto do_atof_calc;\n\n  /* if decimal point is present */\n  if( *z=='.' ){\n    z+=incr;\n    eType++;\n    /* copy digits from after decimal to significand\n    ** (decrease exponent by d to shift decimal right) */\n    while( z<zEnd && sqlite3Isdigit(*z) ){\n      if( s<((LARGEST_INT64-9)/10) ){\n        s = s*10 + (*z - '0');\n        d--;\n        nDigit++;\n      }\n      z+=incr;\n    }\n  }\n  if( z>=zEnd ) goto do_atof_calc;\n\n  /* if exponent is present */\n  if( *z=='e' || *z=='E' ){\n    z+=incr;\n    eValid = 0;\n    eType++;\n\n    /* This branch is needed to avoid a (harmless) buffer overread.  The \n    ** special comment alerts the mutation tester that the correct answer\n    ** is obtained even if the branch is omitted */\n    if( z>=zEnd ) goto do_atof_calc;              /*PREVENTS-HARMLESS-OVERREAD*/\n\n    /* get sign of exponent */\n    if( *z=='-' ){\n      esign = -1;\n      z+=incr;\n    }else if( *z=='+' ){\n      z+=incr;\n    }\n    /* copy digits to exponent */\n    while( z<zEnd && sqlite3Isdigit(*z) ){\n      e = e<10000 ? (e*10 + (*z - '0')) : 10000;\n      z+=incr;\n      eValid = 1;\n    }\n  }\n\n  /* skip trailing spaces */\n  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;\n\ndo_atof_calc:\n  /* adjust exponent by d, and update sign */\n  e = (e*esign) + d;\n  if( e<0 ) {\n    esign = -1;\n    e *= -1;\n  } else {\n    esign = 1;\n  }\n\n  if( s==0 ) {\n    /* In the IEEE 754 standard, zero is signed. */\n    result = sign<0 ? -(double)0 : (double)0;\n  } else {\n    /* Attempt to reduce exponent.\n    **\n    ** Branches that are not required for the correct answer but which only\n    ** help to obtain the correct answer faster are marked with special\n    ** comments, as a hint to the mutation tester.\n    */\n    while( e>0 ){                                       /*OPTIMIZATION-IF-TRUE*/\n      if( esign>0 ){\n        if( s>=(LARGEST_INT64/10) ) break;             /*OPTIMIZATION-IF-FALSE*/\n        s *= 10;\n      }else{\n        if( s%10!=0 ) break;                           /*OPTIMIZATION-IF-FALSE*/\n        s /= 10;\n      }\n      e--;\n    }\n\n    /* adjust the sign of significand */\n    s = sign<0 ? -s : s;\n\n    if( e==0 ){                                         /*OPTIMIZATION-IF-TRUE*/\n      result = (double)s;\n    }else{\n      /* attempt to handle extremely small/large numbers better */\n      if( e>307 ){                                      /*OPTIMIZATION-IF-TRUE*/\n        if( e<342 ){                                    /*OPTIMIZATION-IF-TRUE*/\n          LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);\n          if( esign<0 ){\n            result = s / scale;\n            result /= 1.0e+308;\n          }else{\n            result = s * scale;\n            result *= 1.0e+308;\n          }\n        }else{ assert( e>=342 );\n          if( esign<0 ){\n            result = 0.0*s;\n          }else{\n#ifdef INFINITY\n            result = INFINITY*s;\n#else\n            result = 1e308*1e308*s;  /* Infinity */\n#endif\n          }\n        }\n      }else{\n        LONGDOUBLE_TYPE scale = sqlite3Pow10(e);\n        if( esign<0 ){\n          result = s / scale;\n        }else{\n          result = s * scale;\n        }\n      }\n    }\n  }\n\n  /* store the result */\n  *pResult = result;\n\n  /* return true if number and no extra non-whitespace chracters after */\n  if( z==zEnd && nDigit>0 && eValid && eType>0 ){\n    return eType;\n  }else if( eType>=2 && (eType==3 || eValid) && nDigit>0 ){\n    return -1;\n  }else{\n    return 0;\n  }\n#else\n  return !sqlite3Atoi64(z, pResult, length, enc);\n#endif /* SQLITE_OMIT_FLOATING_POINT */\n}\n#if defined(_MSC_VER)\n#pragma warning(default : 4756)\n#endif\n\n/*\n** Compare the 19-character string zNum against the text representation\n** value 2^63:  9223372036854775808.  Return negative, zero, or positive\n** if zNum is less than, equal to, or greater than the string.\n** Note that zNum must contain exactly 19 characters.\n**\n** Unlike memcmp() this routine is guaranteed to return the difference\n** in the values of the last digit if the only difference is in the\n** last digit.  So, for example,\n**\n**      compare2pow63(\"9223372036854775800\", 1)\n**\n** will return -8.\n*/\nstatic int compare2pow63(const char *zNum, int incr){\n  int c = 0;\n  int i;\n                    /* 012345678901234567 */\n  const char *pow63 = \"922337203685477580\";\n  for(i=0; c==0 && i<18; i++){\n    c = (zNum[i*incr]-pow63[i])*10;\n  }\n  if( c==0 ){\n    c = zNum[18*incr] - '8';\n    testcase( c==(-1) );\n    testcase( c==0 );\n    testcase( c==(+1) );\n  }\n  return c;\n}\n\n/*\n** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This\n** routine does *not* accept hexadecimal notation.\n**\n** Returns:\n**\n**    -1    Not even a prefix of the input text looks like an integer\n**     0    Successful transformation.  Fits in a 64-bit signed integer.\n**     1    Excess non-space text after the integer value\n**     2    Integer too large for a 64-bit signed integer or is malformed\n**     3    Special case of 9223372036854775808\n**\n** length is the number of bytes in the string (bytes, not characters).\n** The string is not necessarily zero-terminated.  The encoding is\n** given by enc.\n*/\nSQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){\n  int incr;\n  u64 u = 0;\n  int neg = 0; /* assume positive */\n  int i;\n  int c = 0;\n  int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */\n  int rc;          /* Baseline return code */\n  const char *zStart;\n  const char *zEnd = zNum + length;\n  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );\n  if( enc==SQLITE_UTF8 ){\n    incr = 1;\n  }else{\n    incr = 2;\n    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );\n    for(i=3-enc; i<length && zNum[i]==0; i+=2){}\n    nonNum = i<length;\n    zEnd = &zNum[i^1];\n    zNum += (enc&1);\n  }\n  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;\n  if( zNum<zEnd ){\n    if( *zNum=='-' ){\n      neg = 1;\n      zNum+=incr;\n    }else if( *zNum=='+' ){\n      zNum+=incr;\n    }\n  }\n  zStart = zNum;\n  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */\n  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){\n    u = u*10 + c - '0';\n  }\n  testcase( i==18*incr );\n  testcase( i==19*incr );\n  testcase( i==20*incr );\n  if( u>LARGEST_INT64 ){\n    /* This test and assignment is needed only to suppress UB warnings\n    ** from clang and -fsanitize=undefined.  This test and assignment make\n    ** the code a little larger and slower, and no harm comes from omitting\n    ** them, but we must appaise the undefined-behavior pharisees. */\n    *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;\n  }else if( neg ){\n    *pNum = -(i64)u;\n  }else{\n    *pNum = (i64)u;\n  }\n  rc = 0;\n  if( i==0 && zStart==zNum ){    /* No digits */\n    rc = -1;\n  }else if( nonNum ){            /* UTF16 with high-order bytes non-zero */\n    rc = 1;\n  }else if( &zNum[i]<zEnd ){     /* Extra bytes at the end */\n    int jj = i;\n    do{\n      if( !sqlite3Isspace(zNum[jj]) ){\n        rc = 1;          /* Extra non-space text after the integer */\n        break;\n      }\n      jj += incr;\n    }while( &zNum[jj]<zEnd );\n  }\n  if( i<19*incr ){\n    /* Less than 19 digits, so we know that it fits in 64 bits */\n    assert( u<=LARGEST_INT64 );\n    return rc;\n  }else{\n    /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */\n    c = i>19*incr ? 1 : compare2pow63(zNum, incr);\n    if( c<0 ){\n      /* zNum is less than 9223372036854775808 so it fits */\n      assert( u<=LARGEST_INT64 );\n      return rc;\n    }else{\n      *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;\n      if( c>0 ){\n        /* zNum is greater than 9223372036854775808 so it overflows */\n        return 2;\n      }else{\n        /* zNum is exactly 9223372036854775808.  Fits if negative.  The\n        ** special case 2 overflow if positive */\n        assert( u-1==LARGEST_INT64 );\n        return neg ? rc : 3;\n      }\n    }\n  }\n}\n\n/*\n** Transform a UTF-8 integer literal, in either decimal or hexadecimal,\n** into a 64-bit signed integer.  This routine accepts hexadecimal literals,\n** whereas sqlite3Atoi64() does not.\n**\n** Returns:\n**\n**     0    Successful transformation.  Fits in a 64-bit signed integer.\n**     1    Excess text after the integer value\n**     2    Integer too large for a 64-bit signed integer or is malformed\n**     3    Special case of 9223372036854775808\n*/\nSQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){\n#ifndef SQLITE_OMIT_HEX_INTEGER\n  if( z[0]=='0'\n   && (z[1]=='x' || z[1]=='X')\n  ){\n    u64 u = 0;\n    int i, k;\n    for(i=2; z[i]=='0'; i++){}\n    for(k=i; sqlite3Isxdigit(z[k]); k++){\n      u = u*16 + sqlite3HexToInt(z[k]);\n    }\n    memcpy(pOut, &u, 8);\n    return (z[k]==0 && k-i<=16) ? 0 : 2;\n  }else\n#endif /* SQLITE_OMIT_HEX_INTEGER */\n  {\n    return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);\n  }\n}\n\n/*\n** If zNum represents an integer that will fit in 32-bits, then set\n** *pValue to that integer and return true.  Otherwise return false.\n**\n** This routine accepts both decimal and hexadecimal notation for integers.\n**\n** Any non-numeric characters that following zNum are ignored.\n** This is different from sqlite3Atoi64() which requires the\n** input number to be zero-terminated.\n*/\nSQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){\n  sqlite_int64 v = 0;\n  int i, c;\n  int neg = 0;\n  if( zNum[0]=='-' ){\n    neg = 1;\n    zNum++;\n  }else if( zNum[0]=='+' ){\n    zNum++;\n  }\n#ifndef SQLITE_OMIT_HEX_INTEGER\n  else if( zNum[0]=='0'\n        && (zNum[1]=='x' || zNum[1]=='X')\n        && sqlite3Isxdigit(zNum[2])\n  ){\n    u32 u = 0;\n    zNum += 2;\n    while( zNum[0]=='0' ) zNum++;\n    for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){\n      u = u*16 + sqlite3HexToInt(zNum[i]);\n    }\n    if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){\n      memcpy(pValue, &u, 4);\n      return 1;\n    }else{\n      return 0;\n    }\n  }\n#endif\n  if( !sqlite3Isdigit(zNum[0]) ) return 0;\n  while( zNum[0]=='0' ) zNum++;\n  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){\n    v = v*10 + c;\n  }\n\n  /* The longest decimal representation of a 32 bit integer is 10 digits:\n  **\n  **             1234567890\n  **     2^31 -> 2147483648\n  */\n  testcase( i==10 );\n  if( i>10 ){\n    return 0;\n  }\n  testcase( v-neg==2147483647 );\n  if( v-neg>2147483647 ){\n    return 0;\n  }\n  if( neg ){\n    v = -v;\n  }\n  *pValue = (int)v;\n  return 1;\n}\n\n/*\n** Return a 32-bit integer value extracted from a string.  If the\n** string is not an integer, just return 0.\n*/\nSQLITE_PRIVATE int sqlite3Atoi(const char *z){\n  int x = 0;\n  if( z ) sqlite3GetInt32(z, &x);\n  return x;\n}\n\n/*\n** The variable-length integer encoding is as follows:\n**\n** KEY:\n**         A = 0xxxxxxx    7 bits of data and one flag bit\n**         B = 1xxxxxxx    7 bits of data and one flag bit\n**         C = xxxxxxxx    8 bits of data\n**\n**  7 bits - A\n** 14 bits - BA\n** 21 bits - BBA\n** 28 bits - BBBA\n** 35 bits - BBBBA\n** 42 bits - BBBBBA\n** 49 bits - BBBBBBA\n** 56 bits - BBBBBBBA\n** 64 bits - BBBBBBBBC\n*/\n\n/*\n** Write a 64-bit variable-length integer to memory starting at p[0].\n** The length of data write will be between 1 and 9 bytes.  The number\n** of bytes written is returned.\n**\n** A variable-length integer consists of the lower 7 bits of each byte\n** for all bytes that have the 8th bit set and one byte with the 8th\n** bit clear.  Except, if we get to the 9th byte, it stores the full\n** 8 bits and is the last byte.\n*/\nstatic int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){\n  int i, j, n;\n  u8 buf[10];\n  if( v & (((u64)0xff000000)<<32) ){\n    p[8] = (u8)v;\n    v >>= 8;\n    for(i=7; i>=0; i--){\n      p[i] = (u8)((v & 0x7f) | 0x80);\n      v >>= 7;\n    }\n    return 9;\n  }    \n  n = 0;\n  do{\n    buf[n++] = (u8)((v & 0x7f) | 0x80);\n    v >>= 7;\n  }while( v!=0 );\n  buf[0] &= 0x7f;\n  assert( n<=9 );\n  for(i=0, j=n-1; j>=0; j--, i++){\n    p[i] = buf[j];\n  }\n  return n;\n}\nSQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){\n  if( v<=0x7f ){\n    p[0] = v&0x7f;\n    return 1;\n  }\n  if( v<=0x3fff ){\n    p[0] = ((v>>7)&0x7f)|0x80;\n    p[1] = v&0x7f;\n    return 2;\n  }\n  return putVarint64(p,v);\n}\n\n/*\n** Bitmasks used by sqlite3GetVarint().  These precomputed constants\n** are defined here rather than simply putting the constant expressions\n** inline in order to work around bugs in the RVT compiler.\n**\n** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f\n**\n** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0\n*/\n#define SLOT_2_0     0x001fc07f\n#define SLOT_4_2_0   0xf01fc07f\n\n\n/*\n** Read a 64-bit variable-length integer from memory starting at p[0].\n** Return the number of bytes read.  The value is stored in *v.\n*/\nSQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){\n  u32 a,b,s;\n\n  if( ((signed char*)p)[0]>=0 ){\n    *v = *p;\n    return 1;\n  }\n  if( ((signed char*)p)[1]>=0 ){\n    *v = ((u32)(p[0]&0x7f)<<7) | p[1];\n    return 2;\n  }\n\n  /* Verify that constants are precomputed correctly */\n  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );\n  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );\n\n  a = ((u32)p[0])<<14;\n  b = p[1];\n  p += 2;\n  a |= *p;\n  /* a: p0<<14 | p2 (unmasked) */\n  if (!(a&0x80))\n  {\n    a &= SLOT_2_0;\n    b &= 0x7f;\n    b = b<<7;\n    a |= b;\n    *v = a;\n    return 3;\n  }\n\n  /* CSE1 from below */\n  a &= SLOT_2_0;\n  p++;\n  b = b<<14;\n  b |= *p;\n  /* b: p1<<14 | p3 (unmasked) */\n  if (!(b&0x80))\n  {\n    b &= SLOT_2_0;\n    /* moved CSE1 up */\n    /* a &= (0x7f<<14)|(0x7f); */\n    a = a<<7;\n    a |= b;\n    *v = a;\n    return 4;\n  }\n\n  /* a: p0<<14 | p2 (masked) */\n  /* b: p1<<14 | p3 (unmasked) */\n  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */\n  /* moved CSE1 up */\n  /* a &= (0x7f<<14)|(0x7f); */\n  b &= SLOT_2_0;\n  s = a;\n  /* s: p0<<14 | p2 (masked) */\n\n  p++;\n  a = a<<14;\n  a |= *p;\n  /* a: p0<<28 | p2<<14 | p4 (unmasked) */\n  if (!(a&0x80))\n  {\n    /* we can skip these cause they were (effectively) done above\n    ** while calculating s */\n    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */\n    /* b &= (0x7f<<14)|(0x7f); */\n    b = b<<7;\n    a |= b;\n    s = s>>18;\n    *v = ((u64)s)<<32 | a;\n    return 5;\n  }\n\n  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */\n  s = s<<7;\n  s |= b;\n  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */\n\n  p++;\n  b = b<<14;\n  b |= *p;\n  /* b: p1<<28 | p3<<14 | p5 (unmasked) */\n  if (!(b&0x80))\n  {\n    /* we can skip this cause it was (effectively) done above in calc'ing s */\n    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */\n    a &= SLOT_2_0;\n    a = a<<7;\n    a |= b;\n    s = s>>18;\n    *v = ((u64)s)<<32 | a;\n    return 6;\n  }\n\n  p++;\n  a = a<<14;\n  a |= *p;\n  /* a: p2<<28 | p4<<14 | p6 (unmasked) */\n  if (!(a&0x80))\n  {\n    a &= SLOT_4_2_0;\n    b &= SLOT_2_0;\n    b = b<<7;\n    a |= b;\n    s = s>>11;\n    *v = ((u64)s)<<32 | a;\n    return 7;\n  }\n\n  /* CSE2 from below */\n  a &= SLOT_2_0;\n  p++;\n  b = b<<14;\n  b |= *p;\n  /* b: p3<<28 | p5<<14 | p7 (unmasked) */\n  if (!(b&0x80))\n  {\n    b &= SLOT_4_2_0;\n    /* moved CSE2 up */\n    /* a &= (0x7f<<14)|(0x7f); */\n    a = a<<7;\n    a |= b;\n    s = s>>4;\n    *v = ((u64)s)<<32 | a;\n    return 8;\n  }\n\n  p++;\n  a = a<<15;\n  a |= *p;\n  /* a: p4<<29 | p6<<15 | p8 (unmasked) */\n\n  /* moved CSE2 up */\n  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */\n  b &= SLOT_2_0;\n  b = b<<8;\n  a |= b;\n\n  s = s<<4;\n  b = p[-4];\n  b &= 0x7f;\n  b = b>>3;\n  s |= b;\n\n  *v = ((u64)s)<<32 | a;\n\n  return 9;\n}\n\n/*\n** Read a 32-bit variable-length integer from memory starting at p[0].\n** Return the number of bytes read.  The value is stored in *v.\n**\n** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned\n** integer, then set *v to 0xffffffff.\n**\n** A MACRO version, getVarint32, is provided which inlines the \n** single-byte case.  All code should use the MACRO version as \n** this function assumes the single-byte case has already been handled.\n*/\nSQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){\n  u32 a,b;\n\n  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline\n  ** by the getVarin32() macro */\n  a = *p;\n  /* a: p0 (unmasked) */\n#ifndef getVarint32\n  if (!(a&0x80))\n  {\n    /* Values between 0 and 127 */\n    *v = a;\n    return 1;\n  }\n#endif\n\n  /* The 2-byte case */\n  p++;\n  b = *p;\n  /* b: p1 (unmasked) */\n  if (!(b&0x80))\n  {\n    /* Values between 128 and 16383 */\n    a &= 0x7f;\n    a = a<<7;\n    *v = a | b;\n    return 2;\n  }\n\n  /* The 3-byte case */\n  p++;\n  a = a<<14;\n  a |= *p;\n  /* a: p0<<14 | p2 (unmasked) */\n  if (!(a&0x80))\n  {\n    /* Values between 16384 and 2097151 */\n    a &= (0x7f<<14)|(0x7f);\n    b &= 0x7f;\n    b = b<<7;\n    *v = a | b;\n    return 3;\n  }\n\n  /* A 32-bit varint is used to store size information in btrees.\n  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.\n  ** A 3-byte varint is sufficient, for example, to record the size\n  ** of a 1048569-byte BLOB or string.\n  **\n  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very\n  ** rare larger cases can be handled by the slower 64-bit varint\n  ** routine.\n  */\n#if 1\n  {\n    u64 v64;\n    u8 n;\n\n    p -= 2;\n    n = sqlite3GetVarint(p, &v64);\n    assert( n>3 && n<=9 );\n    if( (v64 & SQLITE_MAX_U32)!=v64 ){\n      *v = 0xffffffff;\n    }else{\n      *v = (u32)v64;\n    }\n    return n;\n  }\n\n#else\n  /* For following code (kept for historical record only) shows an\n  ** unrolling for the 3- and 4-byte varint cases.  This code is\n  ** slightly faster, but it is also larger and much harder to test.\n  */\n  p++;\n  b = b<<14;\n  b |= *p;\n  /* b: p1<<14 | p3 (unmasked) */\n  if (!(b&0x80))\n  {\n    /* Values between 2097152 and 268435455 */\n    b &= (0x7f<<14)|(0x7f);\n    a &= (0x7f<<14)|(0x7f);\n    a = a<<7;\n    *v = a | b;\n    return 4;\n  }\n\n  p++;\n  a = a<<14;\n  a |= *p;\n  /* a: p0<<28 | p2<<14 | p4 (unmasked) */\n  if (!(a&0x80))\n  {\n    /* Values  between 268435456 and 34359738367 */\n    a &= SLOT_4_2_0;\n    b &= SLOT_4_2_0;\n    b = b<<7;\n    *v = a | b;\n    return 5;\n  }\n\n  /* We can only reach this point when reading a corrupt database\n  ** file.  In that case we are not in any hurry.  Use the (relatively\n  ** slow) general-purpose sqlite3GetVarint() routine to extract the\n  ** value. */\n  {\n    u64 v64;\n    u8 n;\n\n    p -= 4;\n    n = sqlite3GetVarint(p, &v64);\n    assert( n>5 && n<=9 );\n    *v = (u32)v64;\n    return n;\n  }\n#endif\n}\n\n/*\n** Return the number of bytes that will be needed to store the given\n** 64-bit integer.\n*/\nSQLITE_PRIVATE int sqlite3VarintLen(u64 v){\n  int i;\n  for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }\n  return i;\n}\n\n\n/*\n** Read or write a four-byte big-endian integer value.\n*/\nSQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){\n#if SQLITE_BYTEORDER==4321\n  u32 x;\n  memcpy(&x,p,4);\n  return x;\n#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000\n  u32 x;\n  memcpy(&x,p,4);\n  return __builtin_bswap32(x);\n#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300\n  u32 x;\n  memcpy(&x,p,4);\n  return _byteswap_ulong(x);\n#else\n  testcase( p[0]&0x80 );\n  return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];\n#endif\n}\nSQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){\n#if SQLITE_BYTEORDER==4321\n  memcpy(p,&v,4);\n#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000\n  u32 x = __builtin_bswap32(v);\n  memcpy(p,&x,4);\n#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300\n  u32 x = _byteswap_ulong(v);\n  memcpy(p,&x,4);\n#else\n  p[0] = (u8)(v>>24);\n  p[1] = (u8)(v>>16);\n  p[2] = (u8)(v>>8);\n  p[3] = (u8)v;\n#endif\n}\n\n\n\n/*\n** Translate a single byte of Hex into an integer.\n** This routine only works if h really is a valid hexadecimal\n** character:  0..9a..fA..F\n*/\nSQLITE_PRIVATE u8 sqlite3HexToInt(int h){\n  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );\n#ifdef SQLITE_ASCII\n  h += 9*(1&(h>>6));\n#endif\n#ifdef SQLITE_EBCDIC\n  h += 9*(1&~(h>>4));\n#endif\n  return (u8)(h & 0xf);\n}\n\n#if !defined(SQLITE_OMIT_BLOB_LITERAL)\n/*\n** Convert a BLOB literal of the form \"x'hhhhhh'\" into its binary\n** value.  Return a pointer to its binary value.  Space to hold the\n** binary value has been obtained from malloc and must be freed by\n** the calling routine.\n*/\nSQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){\n  char *zBlob;\n  int i;\n\n  zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);\n  n--;\n  if( zBlob ){\n    for(i=0; i<n; i+=2){\n      zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);\n    }\n    zBlob[i/2] = 0;\n  }\n  return zBlob;\n}\n#endif /* !SQLITE_OMIT_BLOB_LITERAL */\n\n/*\n** Log an error that is an API call on a connection pointer that should\n** not have been used.  The \"type\" of connection pointer is given as the\n** argument.  The zType is a word like \"NULL\" or \"closed\" or \"invalid\".\n*/\nstatic void logBadConnection(const char *zType){\n  sqlite3_log(SQLITE_MISUSE, \n     \"API call with %s database connection pointer\",\n     zType\n  );\n}\n\n/*\n** Check to make sure we have a valid db pointer.  This test is not\n** foolproof but it does provide some measure of protection against\n** misuse of the interface such as passing in db pointers that are\n** NULL or which have been previously closed.  If this routine returns\n** 1 it means that the db pointer is valid and 0 if it should not be\n** dereferenced for any reason.  The calling function should invoke\n** SQLITE_MISUSE immediately.\n**\n** sqlite3SafetyCheckOk() requires that the db pointer be valid for\n** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to\n** open properly and is not fit for general use but which can be\n** used as an argument to sqlite3_errmsg() or sqlite3_close().\n*/\nSQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){\n  u32 magic;\n  if( db==0 ){\n    logBadConnection(\"NULL\");\n    return 0;\n  }\n  magic = db->magic;\n  if( magic!=SQLITE_MAGIC_OPEN ){\n    if( sqlite3SafetyCheckSickOrOk(db) ){\n      testcase( sqlite3GlobalConfig.xLog!=0 );\n      logBadConnection(\"unopened\");\n    }\n    return 0;\n  }else{\n    return 1;\n  }\n}\nSQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){\n  u32 magic;\n  magic = db->magic;\n  if( magic!=SQLITE_MAGIC_SICK &&\n      magic!=SQLITE_MAGIC_OPEN &&\n      magic!=SQLITE_MAGIC_BUSY ){\n    testcase( sqlite3GlobalConfig.xLog!=0 );\n    logBadConnection(\"invalid\");\n    return 0;\n  }else{\n    return 1;\n  }\n}\n\n/*\n** Attempt to add, substract, or multiply the 64-bit signed value iB against\n** the other 64-bit signed integer at *pA and store the result in *pA.\n** Return 0 on success.  Or if the operation would have resulted in an\n** overflow, leave *pA unchanged and return 1.\n*/\nSQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){\n#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)\n  return __builtin_add_overflow(*pA, iB, pA);\n#else\n  i64 iA = *pA;\n  testcase( iA==0 ); testcase( iA==1 );\n  testcase( iB==-1 ); testcase( iB==0 );\n  if( iB>=0 ){\n    testcase( iA>0 && LARGEST_INT64 - iA == iB );\n    testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );\n    if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;\n  }else{\n    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );\n    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );\n    if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;\n  }\n  *pA += iB;\n  return 0; \n#endif\n}\nSQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){\n#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)\n  return __builtin_sub_overflow(*pA, iB, pA);\n#else\n  testcase( iB==SMALLEST_INT64+1 );\n  if( iB==SMALLEST_INT64 ){\n    testcase( (*pA)==(-1) ); testcase( (*pA)==0 );\n    if( (*pA)>=0 ) return 1;\n    *pA -= iB;\n    return 0;\n  }else{\n    return sqlite3AddInt64(pA, -iB);\n  }\n#endif\n}\nSQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){\n#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)\n  return __builtin_mul_overflow(*pA, iB, pA);\n#else\n  i64 iA = *pA;\n  if( iB>0 ){\n    if( iA>LARGEST_INT64/iB ) return 1;\n    if( iA<SMALLEST_INT64/iB ) return 1;\n  }else if( iB<0 ){\n    if( iA>0 ){\n      if( iB<SMALLEST_INT64/iA ) return 1;\n    }else if( iA<0 ){\n      if( iB==SMALLEST_INT64 ) return 1;\n      if( iA==SMALLEST_INT64 ) return 1;\n      if( -iA>LARGEST_INT64/-iB ) return 1;\n    }\n  }\n  *pA = iA*iB;\n  return 0;\n#endif\n}\n\n/*\n** Compute the absolute value of a 32-bit signed integer, of possible.  Or \n** if the integer has a value of -2147483648, return +2147483647\n*/\nSQLITE_PRIVATE int sqlite3AbsInt32(int x){\n  if( x>=0 ) return x;\n  if( x==(int)0x80000000 ) return 0x7fffffff;\n  return -x;\n}\n\n#ifdef SQLITE_ENABLE_8_3_NAMES\n/*\n** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database\n** filename in zBaseFilename is a URI with the \"8_3_names=1\" parameter and\n** if filename in z[] has a suffix (a.k.a. \"extension\") that is longer than\n** three characters, then shorten the suffix on z[] to be the last three\n** characters of the original suffix.\n**\n** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always\n** do the suffix shortening regardless of URI parameter.\n**\n** Examples:\n**\n**     test.db-journal    =>   test.nal\n**     test.db-wal        =>   test.wal\n**     test.db-shm        =>   test.shm\n**     test.db-mj7f3319fa =>   test.9fa\n*/\nSQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){\n#if SQLITE_ENABLE_8_3_NAMES<2\n  if( sqlite3_uri_boolean(zBaseFilename, \"8_3_names\", 0) )\n#endif\n  {\n    int i, sz;\n    sz = sqlite3Strlen30(z);\n    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}\n    if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);\n  }\n}\n#endif\n\n/* \n** Find (an approximate) sum of two LogEst values.  This computation is\n** not a simple \"+\" operator because LogEst is stored as a logarithmic\n** value.\n** \n*/\nSQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){\n  static const unsigned char x[] = {\n     10, 10,                         /* 0,1 */\n      9, 9,                          /* 2,3 */\n      8, 8,                          /* 4,5 */\n      7, 7, 7,                       /* 6,7,8 */\n      6, 6, 6,                       /* 9,10,11 */\n      5, 5, 5,                       /* 12-14 */\n      4, 4, 4, 4,                    /* 15-18 */\n      3, 3, 3, 3, 3, 3,              /* 19-24 */\n      2, 2, 2, 2, 2, 2, 2,           /* 25-31 */\n  };\n  if( a>=b ){\n    if( a>b+49 ) return a;\n    if( a>b+31 ) return a+1;\n    return a+x[a-b];\n  }else{\n    if( b>a+49 ) return b;\n    if( b>a+31 ) return b+1;\n    return b+x[b-a];\n  }\n}\n\n/*\n** Convert an integer into a LogEst.  In other words, compute an\n** approximation for 10*log2(x).\n*/\nSQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){\n  static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };\n  LogEst y = 40;\n  if( x<8 ){\n    if( x<2 ) return 0;\n    while( x<8 ){  y -= 10; x <<= 1; }\n  }else{\n#if GCC_VERSION>=5004000\n    int i = 60 - __builtin_clzll(x);\n    y += i*10;\n    x >>= i;\n#else\n    while( x>255 ){ y += 40; x >>= 4; }  /*OPTIMIZATION-IF-TRUE*/\n    while( x>15 ){  y += 10; x >>= 1; }\n#endif\n  }\n  return a[x&7] + y - 10;\n}\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/*\n** Convert a double into a LogEst\n** In other words, compute an approximation for 10*log2(x).\n*/\nSQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){\n  u64 a;\n  LogEst e;\n  assert( sizeof(x)==8 && sizeof(a)==8 );\n  if( x<=1 ) return 0;\n  if( x<=2000000000 ) return sqlite3LogEst((u64)x);\n  memcpy(&a, &x, 8);\n  e = (a>>52) - 1022;\n  return e*10;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \\\n    defined(SQLITE_ENABLE_STAT4) || \\\n    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)\n/*\n** Convert a LogEst into an integer.\n**\n** Note that this routine is only used when one or more of various\n** non-standard compile-time options is enabled.\n*/\nSQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){\n  u64 n;\n  n = x%10;\n  x /= 10;\n  if( n>=5 ) n -= 2;\n  else if( n>=1 ) n -= 1;\n#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \\\n    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)\n  if( x>60 ) return (u64)LARGEST_INT64;\n#else\n  /* If only SQLITE_ENABLE_STAT4 is on, then the largest input\n  ** possible to this routine is 310, resulting in a maximum x of 31 */\n  assert( x<=60 );\n#endif\n  return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);\n}\n#endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */\n\n/*\n** Add a new name/number pair to a VList.  This might require that the\n** VList object be reallocated, so return the new VList.  If an OOM\n** error occurs, the original VList returned and the\n** db->mallocFailed flag is set.\n**\n** A VList is really just an array of integers.  To destroy a VList,\n** simply pass it to sqlite3DbFree().\n**\n** The first integer is the number of integers allocated for the whole\n** VList.  The second integer is the number of integers actually used.\n** Each name/number pair is encoded by subsequent groups of 3 or more\n** integers.\n**\n** Each name/number pair starts with two integers which are the numeric\n** value for the pair and the size of the name/number pair, respectively.\n** The text name overlays one or more following integers.  The text name\n** is always zero-terminated.\n**\n** Conceptually:\n**\n**    struct VList {\n**      int nAlloc;   // Number of allocated slots \n**      int nUsed;    // Number of used slots \n**      struct VListEntry {\n**        int iValue;    // Value for this entry\n**        int nSlot;     // Slots used by this entry\n**        // ... variable name goes here\n**      } a[0];\n**    }\n**\n** During code generation, pointers to the variable names within the\n** VList are taken.  When that happens, nAlloc is set to zero as an \n** indication that the VList may never again be enlarged, since the\n** accompanying realloc() would invalidate the pointers.\n*/\nSQLITE_PRIVATE VList *sqlite3VListAdd(\n  sqlite3 *db,           /* The database connection used for malloc() */\n  VList *pIn,            /* The input VList.  Might be NULL */\n  const char *zName,     /* Name of symbol to add */\n  int nName,             /* Bytes of text in zName */\n  int iVal               /* Value to associate with zName */\n){\n  int nInt;              /* number of sizeof(int) objects needed for zName */\n  char *z;               /* Pointer to where zName will be stored */\n  int i;                 /* Index in pIn[] where zName is stored */\n\n  nInt = nName/4 + 3;\n  assert( pIn==0 || pIn[0]>=3 );  /* Verify ok to add new elements */\n  if( pIn==0 || pIn[1]+nInt > pIn[0] ){\n    /* Enlarge the allocation */\n    sqlite3_int64 nAlloc = (pIn ? 2*(sqlite3_int64)pIn[0] : 10) + nInt;\n    VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));\n    if( pOut==0 ) return pIn;\n    if( pIn==0 ) pOut[1] = 2;\n    pIn = pOut;\n    pIn[0] = nAlloc;\n  }\n  i = pIn[1];\n  pIn[i] = iVal;\n  pIn[i+1] = nInt;\n  z = (char*)&pIn[i+2];\n  pIn[1] = i+nInt;\n  assert( pIn[1]<=pIn[0] );\n  memcpy(z, zName, nName);\n  z[nName] = 0;\n  return pIn;\n}\n\n/*\n** Return a pointer to the name of a variable in the given VList that\n** has the value iVal.  Or return a NULL if there is no such variable in\n** the list\n*/\nSQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){\n  int i, mx;\n  if( pIn==0 ) return 0;\n  mx = pIn[1];\n  i = 2;\n  do{\n    if( pIn[i]==iVal ) return (char*)&pIn[i+2];\n    i += pIn[i+1];\n  }while( i<mx );\n  return 0;\n}\n\n/*\n** Return the number of the variable named zName, if it is in VList.\n** or return 0 if there is no such variable.\n*/\nSQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){\n  int i, mx;\n  if( pIn==0 ) return 0;\n  mx = pIn[1];\n  i = 2;\n  do{\n    const char *z = (const char*)&pIn[i+2];\n    if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];\n    i += pIn[i+1];\n  }while( i<mx );\n  return 0;\n}\n\n/************** End of util.c ************************************************/\n/************** Begin file hash.c ********************************************/\n/*\n** 2001 September 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This is the implementation of generic hash-tables\n** used in SQLite.\n*/\n/* #include \"sqliteInt.h\" */\n/* #include <assert.h> */\n\n/* Turn bulk memory into a hash table object by initializing the\n** fields of the Hash structure.\n**\n** \"pNew\" is a pointer to the hash table that is to be initialized.\n*/\nSQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){\n  assert( pNew!=0 );\n  pNew->first = 0;\n  pNew->count = 0;\n  pNew->htsize = 0;\n  pNew->ht = 0;\n}\n\n/* Remove all entries from a hash table.  Reclaim all memory.\n** Call this routine to delete a hash table or to reset a hash table\n** to the empty state.\n*/\nSQLITE_PRIVATE void sqlite3HashClear(Hash *pH){\n  HashElem *elem;         /* For looping over all elements of the table */\n\n  assert( pH!=0 );\n  elem = pH->first;\n  pH->first = 0;\n  sqlite3_free(pH->ht);\n  pH->ht = 0;\n  pH->htsize = 0;\n  while( elem ){\n    HashElem *next_elem = elem->next;\n    sqlite3_free(elem);\n    elem = next_elem;\n  }\n  pH->count = 0;\n}\n\n/*\n** The hashing function.\n*/\nstatic unsigned int strHash(const char *z){\n  unsigned int h = 0;\n  unsigned char c;\n  while( (c = (unsigned char)*z++)!=0 ){     /*OPTIMIZATION-IF-TRUE*/\n    /* Knuth multiplicative hashing.  (Sorting & Searching, p. 510).\n    ** 0x9e3779b1 is 2654435761 which is the closest prime number to\n    ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */\n    h += sqlite3UpperToLower[c];\n    h *= 0x9e3779b1;\n  }\n  return h;\n}\n\n\n/* Link pNew element into the hash table pH.  If pEntry!=0 then also\n** insert pNew into the pEntry hash bucket.\n*/\nstatic void insertElement(\n  Hash *pH,              /* The complete hash table */\n  struct _ht *pEntry,    /* The entry into which pNew is inserted */\n  HashElem *pNew         /* The element to be inserted */\n){\n  HashElem *pHead;       /* First element already in pEntry */\n  if( pEntry ){\n    pHead = pEntry->count ? pEntry->chain : 0;\n    pEntry->count++;\n    pEntry->chain = pNew;\n  }else{\n    pHead = 0;\n  }\n  if( pHead ){\n    pNew->next = pHead;\n    pNew->prev = pHead->prev;\n    if( pHead->prev ){ pHead->prev->next = pNew; }\n    else             { pH->first = pNew; }\n    pHead->prev = pNew;\n  }else{\n    pNew->next = pH->first;\n    if( pH->first ){ pH->first->prev = pNew; }\n    pNew->prev = 0;\n    pH->first = pNew;\n  }\n}\n\n\n/* Resize the hash table so that it cantains \"new_size\" buckets.\n**\n** The hash table might fail to resize if sqlite3_malloc() fails or\n** if the new size is the same as the prior size.\n** Return TRUE if the resize occurs and false if not.\n*/\nstatic int rehash(Hash *pH, unsigned int new_size){\n  struct _ht *new_ht;            /* The new hash table */\n  HashElem *elem, *next_elem;    /* For looping over existing elements */\n\n#if SQLITE_MALLOC_SOFT_LIMIT>0\n  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){\n    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);\n  }\n  if( new_size==pH->htsize ) return 0;\n#endif\n\n  /* The inability to allocates space for a larger hash table is\n  ** a performance hit but it is not a fatal error.  So mark the\n  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of \n  ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()\n  ** only zeroes the requested number of bytes whereas this module will\n  ** use the actual amount of space allocated for the hash table (which\n  ** may be larger than the requested amount).\n  */\n  sqlite3BeginBenignMalloc();\n  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );\n  sqlite3EndBenignMalloc();\n\n  if( new_ht==0 ) return 0;\n  sqlite3_free(pH->ht);\n  pH->ht = new_ht;\n  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);\n  memset(new_ht, 0, new_size*sizeof(struct _ht));\n  for(elem=pH->first, pH->first=0; elem; elem = next_elem){\n    unsigned int h = strHash(elem->pKey) % new_size;\n    next_elem = elem->next;\n    insertElement(pH, &new_ht[h], elem);\n  }\n  return 1;\n}\n\n/* This function (for internal use only) locates an element in an\n** hash table that matches the given key.  If no element is found,\n** a pointer to a static null element with HashElem.data==0 is returned.\n** If pH is not NULL, then the hash for this key is written to *pH.\n*/\nstatic HashElem *findElementWithHash(\n  const Hash *pH,     /* The pH to be searched */\n  const char *pKey,   /* The key we are searching for */\n  unsigned int *pHash /* Write the hash value here */\n){\n  HashElem *elem;                /* Used to loop thru the element list */\n  unsigned int count;            /* Number of elements left to test */\n  unsigned int h;                /* The computed hash */\n  static HashElem nullElement = { 0, 0, 0, 0 };\n\n  if( pH->ht ){   /*OPTIMIZATION-IF-TRUE*/\n    struct _ht *pEntry;\n    h = strHash(pKey) % pH->htsize;\n    pEntry = &pH->ht[h];\n    elem = pEntry->chain;\n    count = pEntry->count;\n  }else{\n    h = 0;\n    elem = pH->first;\n    count = pH->count;\n  }\n  if( pHash ) *pHash = h;\n  while( count-- ){\n    assert( elem!=0 );\n    if( sqlite3StrICmp(elem->pKey,pKey)==0 ){ \n      return elem;\n    }\n    elem = elem->next;\n  }\n  return &nullElement;\n}\n\n/* Remove a single entry from the hash table given a pointer to that\n** element and a hash on the element's key.\n*/\nstatic void removeElementGivenHash(\n  Hash *pH,         /* The pH containing \"elem\" */\n  HashElem* elem,   /* The element to be removed from the pH */\n  unsigned int h    /* Hash value for the element */\n){\n  struct _ht *pEntry;\n  if( elem->prev ){\n    elem->prev->next = elem->next; \n  }else{\n    pH->first = elem->next;\n  }\n  if( elem->next ){\n    elem->next->prev = elem->prev;\n  }\n  if( pH->ht ){\n    pEntry = &pH->ht[h];\n    if( pEntry->chain==elem ){\n      pEntry->chain = elem->next;\n    }\n    assert( pEntry->count>0 );\n    pEntry->count--;\n  }\n  sqlite3_free( elem );\n  pH->count--;\n  if( pH->count==0 ){\n    assert( pH->first==0 );\n    assert( pH->count==0 );\n    sqlite3HashClear(pH);\n  }\n}\n\n/* Attempt to locate an element of the hash table pH with a key\n** that matches pKey.  Return the data for this element if it is\n** found, or NULL if there is no match.\n*/\nSQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){\n  assert( pH!=0 );\n  assert( pKey!=0 );\n  return findElementWithHash(pH, pKey, 0)->data;\n}\n\n/* Insert an element into the hash table pH.  The key is pKey\n** and the data is \"data\".\n**\n** If no element exists with a matching key, then a new\n** element is created and NULL is returned.\n**\n** If another element already exists with the same key, then the\n** new data replaces the old data and the old data is returned.\n** The key is not copied in this instance.  If a malloc fails, then\n** the new data is returned and the hash table is unchanged.\n**\n** If the \"data\" parameter to this function is NULL, then the\n** element corresponding to \"key\" is removed from the hash table.\n*/\nSQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){\n  unsigned int h;       /* the hash of the key modulo hash table size */\n  HashElem *elem;       /* Used to loop thru the element list */\n  HashElem *new_elem;   /* New element added to the pH */\n\n  assert( pH!=0 );\n  assert( pKey!=0 );\n  elem = findElementWithHash(pH,pKey,&h);\n  if( elem->data ){\n    void *old_data = elem->data;\n    if( data==0 ){\n      removeElementGivenHash(pH,elem,h);\n    }else{\n      elem->data = data;\n      elem->pKey = pKey;\n    }\n    return old_data;\n  }\n  if( data==0 ) return 0;\n  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );\n  if( new_elem==0 ) return data;\n  new_elem->pKey = pKey;\n  new_elem->data = data;\n  pH->count++;\n  if( pH->count>=10 && pH->count > 2*pH->htsize ){\n    if( rehash(pH, pH->count*2) ){\n      assert( pH->htsize>0 );\n      h = strHash(pKey) % pH->htsize;\n    }\n  }\n  insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);\n  return 0;\n}\n\n/************** End of hash.c ************************************************/\n/************** Begin file opcodes.c *****************************************/\n/* Automatically generated.  Do not edit */\n/* See the tool/mkopcodec.tcl script for details. */\n#if !defined(SQLITE_OMIT_EXPLAIN) \\\n || defined(VDBE_PROFILE) \\\n || defined(SQLITE_DEBUG)\n#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)\n# define OpHelp(X) \"\\0\" X\n#else\n# define OpHelp(X)\n#endif\nSQLITE_PRIVATE const char *sqlite3OpcodeName(int i){\n static const char *const azName[] = {\n    /*   0 */ \"Savepoint\"        OpHelp(\"\"),\n    /*   1 */ \"AutoCommit\"       OpHelp(\"\"),\n    /*   2 */ \"Transaction\"      OpHelp(\"\"),\n    /*   3 */ \"SorterNext\"       OpHelp(\"\"),\n    /*   4 */ \"Prev\"             OpHelp(\"\"),\n    /*   5 */ \"Next\"             OpHelp(\"\"),\n    /*   6 */ \"Checkpoint\"       OpHelp(\"\"),\n    /*   7 */ \"JournalMode\"      OpHelp(\"\"),\n    /*   8 */ \"Vacuum\"           OpHelp(\"\"),\n    /*   9 */ \"VFilter\"          OpHelp(\"iplan=r[P3] zplan='P4'\"),\n    /*  10 */ \"VUpdate\"          OpHelp(\"data=r[P3@P2]\"),\n    /*  11 */ \"Goto\"             OpHelp(\"\"),\n    /*  12 */ \"Gosub\"            OpHelp(\"\"),\n    /*  13 */ \"InitCoroutine\"    OpHelp(\"\"),\n    /*  14 */ \"Yield\"            OpHelp(\"\"),\n    /*  15 */ \"MustBeInt\"        OpHelp(\"\"),\n    /*  16 */ \"Jump\"             OpHelp(\"\"),\n    /*  17 */ \"Once\"             OpHelp(\"\"),\n    /*  18 */ \"If\"               OpHelp(\"\"),\n    /*  19 */ \"Not\"              OpHelp(\"r[P2]= !r[P1]\"),\n    /*  20 */ \"IfNot\"            OpHelp(\"\"),\n    /*  21 */ \"IfNullRow\"        OpHelp(\"if P1.nullRow then r[P3]=NULL, goto P2\"),\n    /*  22 */ \"SeekLT\"           OpHelp(\"key=r[P3@P4]\"),\n    /*  23 */ \"SeekLE\"           OpHelp(\"key=r[P3@P4]\"),\n    /*  24 */ \"SeekGE\"           OpHelp(\"key=r[P3@P4]\"),\n    /*  25 */ \"SeekGT\"           OpHelp(\"key=r[P3@P4]\"),\n    /*  26 */ \"IfNotOpen\"        OpHelp(\"if( !csr[P1] ) goto P2\"),\n    /*  27 */ \"IfNoHope\"         OpHelp(\"key=r[P3@P4]\"),\n    /*  28 */ \"NoConflict\"       OpHelp(\"key=r[P3@P4]\"),\n    /*  29 */ \"NotFound\"         OpHelp(\"key=r[P3@P4]\"),\n    /*  30 */ \"Found\"            OpHelp(\"key=r[P3@P4]\"),\n    /*  31 */ \"SeekRowid\"        OpHelp(\"intkey=r[P3]\"),\n    /*  32 */ \"NotExists\"        OpHelp(\"intkey=r[P3]\"),\n    /*  33 */ \"Last\"             OpHelp(\"\"),\n    /*  34 */ \"IfSmaller\"        OpHelp(\"\"),\n    /*  35 */ \"SorterSort\"       OpHelp(\"\"),\n    /*  36 */ \"Sort\"             OpHelp(\"\"),\n    /*  37 */ \"Rewind\"           OpHelp(\"\"),\n    /*  38 */ \"IdxLE\"            OpHelp(\"key=r[P3@P4]\"),\n    /*  39 */ \"IdxGT\"            OpHelp(\"key=r[P3@P4]\"),\n    /*  40 */ \"IdxLT\"            OpHelp(\"key=r[P3@P4]\"),\n    /*  41 */ \"IdxGE\"            OpHelp(\"key=r[P3@P4]\"),\n    /*  42 */ \"RowSetRead\"       OpHelp(\"r[P3]=rowset(P1)\"),\n    /*  43 */ \"Or\"               OpHelp(\"r[P3]=(r[P1] || r[P2])\"),\n    /*  44 */ \"And\"              OpHelp(\"r[P3]=(r[P1] && r[P2])\"),\n    /*  45 */ \"RowSetTest\"       OpHelp(\"if r[P3] in rowset(P1) goto P2\"),\n    /*  46 */ \"Program\"          OpHelp(\"\"),\n    /*  47 */ \"FkIfZero\"         OpHelp(\"if fkctr[P1]==0 goto P2\"),\n    /*  48 */ \"IfPos\"            OpHelp(\"if r[P1]>0 then r[P1]-=P3, goto P2\"),\n    /*  49 */ \"IfNotZero\"        OpHelp(\"if r[P1]!=0 then r[P1]--, goto P2\"),\n    /*  50 */ \"IsNull\"           OpHelp(\"if r[P1]==NULL goto P2\"),\n    /*  51 */ \"NotNull\"          OpHelp(\"if r[P1]!=NULL goto P2\"),\n    /*  52 */ \"Ne\"               OpHelp(\"IF r[P3]!=r[P1]\"),\n    /*  53 */ \"Eq\"               OpHelp(\"IF r[P3]==r[P1]\"),\n    /*  54 */ \"Gt\"               OpHelp(\"IF r[P3]>r[P1]\"),\n    /*  55 */ \"Le\"               OpHelp(\"IF r[P3]<=r[P1]\"),\n    /*  56 */ \"Lt\"               OpHelp(\"IF r[P3]<r[P1]\"),\n    /*  57 */ \"Ge\"               OpHelp(\"IF r[P3]>=r[P1]\"),\n    /*  58 */ \"ElseNotEq\"        OpHelp(\"\"),\n    /*  59 */ \"DecrJumpZero\"     OpHelp(\"if (--r[P1])==0 goto P2\"),\n    /*  60 */ \"IncrVacuum\"       OpHelp(\"\"),\n    /*  61 */ \"VNext\"            OpHelp(\"\"),\n    /*  62 */ \"Init\"             OpHelp(\"Start at P2\"),\n    /*  63 */ \"PureFunc\"         OpHelp(\"r[P3]=func(r[P2@NP])\"),\n    /*  64 */ \"Function\"         OpHelp(\"r[P3]=func(r[P2@NP])\"),\n    /*  65 */ \"Return\"           OpHelp(\"\"),\n    /*  66 */ \"EndCoroutine\"     OpHelp(\"\"),\n    /*  67 */ \"HaltIfNull\"       OpHelp(\"if r[P3]=null halt\"),\n    /*  68 */ \"Halt\"             OpHelp(\"\"),\n    /*  69 */ \"Integer\"          OpHelp(\"r[P2]=P1\"),\n    /*  70 */ \"Int64\"            OpHelp(\"r[P2]=P4\"),\n    /*  71 */ \"String\"           OpHelp(\"r[P2]='P4' (len=P1)\"),\n    /*  72 */ \"Null\"             OpHelp(\"r[P2..P3]=NULL\"),\n    /*  73 */ \"SoftNull\"         OpHelp(\"r[P1]=NULL\"),\n    /*  74 */ \"Blob\"             OpHelp(\"r[P2]=P4 (len=P1)\"),\n    /*  75 */ \"Variable\"         OpHelp(\"r[P2]=parameter(P1,P4)\"),\n    /*  76 */ \"Move\"             OpHelp(\"r[P2@P3]=r[P1@P3]\"),\n    /*  77 */ \"Copy\"             OpHelp(\"r[P2@P3+1]=r[P1@P3+1]\"),\n    /*  78 */ \"SCopy\"            OpHelp(\"r[P2]=r[P1]\"),\n    /*  79 */ \"IntCopy\"          OpHelp(\"r[P2]=r[P1]\"),\n    /*  80 */ \"ResultRow\"        OpHelp(\"output=r[P1@P2]\"),\n    /*  81 */ \"CollSeq\"          OpHelp(\"\"),\n    /*  82 */ \"AddImm\"           OpHelp(\"r[P1]=r[P1]+P2\"),\n    /*  83 */ \"RealAffinity\"     OpHelp(\"\"),\n    /*  84 */ \"Cast\"             OpHelp(\"affinity(r[P1])\"),\n    /*  85 */ \"Permutation\"      OpHelp(\"\"),\n    /*  86 */ \"Compare\"          OpHelp(\"r[P1@P3] <-> r[P2@P3]\"),\n    /*  87 */ \"IsTrue\"           OpHelp(\"r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4\"),\n    /*  88 */ \"Offset\"           OpHelp(\"r[P3] = sqlite_offset(P1)\"),\n    /*  89 */ \"Column\"           OpHelp(\"r[P3]=PX\"),\n    /*  90 */ \"Affinity\"         OpHelp(\"affinity(r[P1@P2])\"),\n    /*  91 */ \"MakeRecord\"       OpHelp(\"r[P3]=mkrec(r[P1@P2])\"),\n    /*  92 */ \"Count\"            OpHelp(\"r[P2]=count()\"),\n    /*  93 */ \"ReadCookie\"       OpHelp(\"\"),\n    /*  94 */ \"SetCookie\"        OpHelp(\"\"),\n    /*  95 */ \"ReopenIdx\"        OpHelp(\"root=P2 iDb=P3\"),\n    /*  96 */ \"OpenRead\"         OpHelp(\"root=P2 iDb=P3\"),\n    /*  97 */ \"OpenWrite\"        OpHelp(\"root=P2 iDb=P3\"),\n    /*  98 */ \"OpenDup\"          OpHelp(\"\"),\n    /*  99 */ \"OpenAutoindex\"    OpHelp(\"nColumn=P2\"),\n    /* 100 */ \"OpenEphemeral\"    OpHelp(\"nColumn=P2\"),\n    /* 101 */ \"BitAnd\"           OpHelp(\"r[P3]=r[P1]&r[P2]\"),\n    /* 102 */ \"BitOr\"            OpHelp(\"r[P3]=r[P1]|r[P2]\"),\n    /* 103 */ \"ShiftLeft\"        OpHelp(\"r[P3]=r[P2]<<r[P1]\"),\n    /* 104 */ \"ShiftRight\"       OpHelp(\"r[P3]=r[P2]>>r[P1]\"),\n    /* 105 */ \"Add\"              OpHelp(\"r[P3]=r[P1]+r[P2]\"),\n    /* 106 */ \"Subtract\"         OpHelp(\"r[P3]=r[P2]-r[P1]\"),\n    /* 107 */ \"Multiply\"         OpHelp(\"r[P3]=r[P1]*r[P2]\"),\n    /* 108 */ \"Divide\"           OpHelp(\"r[P3]=r[P2]/r[P1]\"),\n    /* 109 */ \"Remainder\"        OpHelp(\"r[P3]=r[P2]%r[P1]\"),\n    /* 110 */ \"Concat\"           OpHelp(\"r[P3]=r[P2]+r[P1]\"),\n    /* 111 */ \"SorterOpen\"       OpHelp(\"\"),\n    /* 112 */ \"BitNot\"           OpHelp(\"r[P2]= ~r[P1]\"),\n    /* 113 */ \"SequenceTest\"     OpHelp(\"if( cursor[P1].ctr++ ) pc = P2\"),\n    /* 114 */ \"OpenPseudo\"       OpHelp(\"P3 columns in r[P2]\"),\n    /* 115 */ \"String8\"          OpHelp(\"r[P2]='P4'\"),\n    /* 116 */ \"Close\"            OpHelp(\"\"),\n    /* 117 */ \"ColumnsUsed\"      OpHelp(\"\"),\n    /* 118 */ \"SeekHit\"          OpHelp(\"seekHit=P2\"),\n    /* 119 */ \"Sequence\"         OpHelp(\"r[P2]=cursor[P1].ctr++\"),\n    /* 120 */ \"NewRowid\"         OpHelp(\"r[P2]=rowid\"),\n    /* 121 */ \"Insert\"           OpHelp(\"intkey=r[P3] data=r[P2]\"),\n    /* 122 */ \"Delete\"           OpHelp(\"\"),\n    /* 123 */ \"ResetCount\"       OpHelp(\"\"),\n    /* 124 */ \"SorterCompare\"    OpHelp(\"if key(P1)!=trim(r[P3],P4) goto P2\"),\n    /* 125 */ \"SorterData\"       OpHelp(\"r[P2]=data\"),\n    /* 126 */ \"RowData\"          OpHelp(\"r[P2]=data\"),\n    /* 127 */ \"Rowid\"            OpHelp(\"r[P2]=rowid\"),\n    /* 128 */ \"NullRow\"          OpHelp(\"\"),\n    /* 129 */ \"SeekEnd\"          OpHelp(\"\"),\n    /* 130 */ \"IdxInsert\"        OpHelp(\"key=r[P2]\"),\n    /* 131 */ \"SorterInsert\"     OpHelp(\"key=r[P2]\"),\n    /* 132 */ \"IdxDelete\"        OpHelp(\"key=r[P2@P3]\"),\n    /* 133 */ \"DeferredSeek\"     OpHelp(\"Move P3 to P1.rowid if needed\"),\n    /* 134 */ \"IdxRowid\"         OpHelp(\"r[P2]=rowid\"),\n    /* 135 */ \"FinishSeek\"       OpHelp(\"\"),\n    /* 136 */ \"Destroy\"          OpHelp(\"\"),\n    /* 137 */ \"Clear\"            OpHelp(\"\"),\n    /* 138 */ \"ResetSorter\"      OpHelp(\"\"),\n    /* 139 */ \"CreateBtree\"      OpHelp(\"r[P2]=root iDb=P1 flags=P3\"),\n    /* 140 */ \"SqlExec\"          OpHelp(\"\"),\n    /* 141 */ \"ParseSchema\"      OpHelp(\"\"),\n    /* 142 */ \"LoadAnalysis\"     OpHelp(\"\"),\n    /* 143 */ \"DropTable\"        OpHelp(\"\"),\n    /* 144 */ \"DropIndex\"        OpHelp(\"\"),\n    /* 145 */ \"DropTrigger\"      OpHelp(\"\"),\n    /* 146 */ \"IntegrityCk\"      OpHelp(\"\"),\n    /* 147 */ \"RowSetAdd\"        OpHelp(\"rowset(P1)=r[P2]\"),\n    /* 148 */ \"Param\"            OpHelp(\"\"),\n    /* 149 */ \"FkCounter\"        OpHelp(\"fkctr[P1]+=P2\"),\n    /* 150 */ \"Real\"             OpHelp(\"r[P2]=P4\"),\n    /* 151 */ \"MemMax\"           OpHelp(\"r[P1]=max(r[P1],r[P2])\"),\n    /* 152 */ \"OffsetLimit\"      OpHelp(\"if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)\"),\n    /* 153 */ \"AggInverse\"       OpHelp(\"accum=r[P3] inverse(r[P2@P5])\"),\n    /* 154 */ \"AggStep\"          OpHelp(\"accum=r[P3] step(r[P2@P5])\"),\n    /* 155 */ \"AggStep1\"         OpHelp(\"accum=r[P3] step(r[P2@P5])\"),\n    /* 156 */ \"AggValue\"         OpHelp(\"r[P3]=value N=P2\"),\n    /* 157 */ \"AggFinal\"         OpHelp(\"accum=r[P1] N=P2\"),\n    /* 158 */ \"Expire\"           OpHelp(\"\"),\n    /* 159 */ \"CursorLock\"       OpHelp(\"\"),\n    /* 160 */ \"CursorUnlock\"     OpHelp(\"\"),\n    /* 161 */ \"TableLock\"        OpHelp(\"iDb=P1 root=P2 write=P3\"),\n    /* 162 */ \"VBegin\"           OpHelp(\"\"),\n    /* 163 */ \"VCreate\"          OpHelp(\"\"),\n    /* 164 */ \"VDestroy\"         OpHelp(\"\"),\n    /* 165 */ \"VOpen\"            OpHelp(\"\"),\n    /* 166 */ \"VColumn\"          OpHelp(\"r[P3]=vcolumn(P2)\"),\n    /* 167 */ \"VRename\"          OpHelp(\"\"),\n    /* 168 */ \"Pagecount\"        OpHelp(\"\"),\n    /* 169 */ \"MaxPgcnt\"         OpHelp(\"\"),\n    /* 170 */ \"Trace\"            OpHelp(\"\"),\n    /* 171 */ \"CursorHint\"       OpHelp(\"\"),\n    /* 172 */ \"ReleaseReg\"       OpHelp(\"release r[P1@P2] mask P3\"),\n    /* 173 */ \"Noop\"             OpHelp(\"\"),\n    /* 174 */ \"Explain\"          OpHelp(\"\"),\n    /* 175 */ \"Abortable\"        OpHelp(\"\"),\n  };\n  return azName[i];\n}\n#endif\n\n/************** End of opcodes.c *********************************************/\n/************** Begin file os_unix.c *****************************************/\n/*\n** 2004 May 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains the VFS implementation for unix-like operating systems\n** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.\n**\n** There are actually several different VFS implementations in this file.\n** The differences are in the way that file locking is done.  The default\n** implementation uses Posix Advisory Locks.  Alternative implementations\n** use flock(), dot-files, various proprietary locking schemas, or simply\n** skip locking all together.\n**\n** This source file is organized into divisions where the logic for various\n** subfunctions is contained within the appropriate division.  PLEASE\n** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed\n** in the correct division and should be clearly labeled.\n**\n** The layout of divisions is as follows:\n**\n**   *  General-purpose declarations and utility functions.\n**   *  Unique file ID logic used by VxWorks.\n**   *  Various locking primitive implementations (all except proxy locking):\n**      + for Posix Advisory Locks\n**      + for no-op locks\n**      + for dot-file locks\n**      + for flock() locking\n**      + for named semaphore locks (VxWorks only)\n**      + for AFP filesystem locks (MacOSX only)\n**   *  sqlite3_file methods not associated with locking.\n**   *  Definitions of sqlite3_io_methods objects for all locking\n**      methods plus \"finder\" functions for each locking method.\n**   *  sqlite3_vfs method implementations.\n**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)\n**   *  Definitions of sqlite3_vfs objects for all locking methods\n**      plus implementations of sqlite3_os_init() and sqlite3_os_end().\n*/\n/* #include \"sqliteInt.h\" */\n#if SQLITE_OS_UNIX              /* This file is used on unix only */\n\n/*\n** There are various methods for file locking used for concurrency\n** control:\n**\n**   1. POSIX locking (the default),\n**   2. No locking,\n**   3. Dot-file locking,\n**   4. flock() locking,\n**   5. AFP locking (OSX only),\n**   6. Named POSIX semaphores (VXWorks only),\n**   7. proxy locking. (OSX only)\n**\n** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE\n** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic\n** selection of the appropriate locking style based on the filesystem\n** where the database is located.  \n*/\n#if !defined(SQLITE_ENABLE_LOCKING_STYLE)\n#  if defined(__APPLE__)\n#    define SQLITE_ENABLE_LOCKING_STYLE 1\n#  else\n#    define SQLITE_ENABLE_LOCKING_STYLE 0\n#  endif\n#endif\n\n/* Use pread() and pwrite() if they are available */\n#if defined(__APPLE__)\n# define HAVE_PREAD 1\n# define HAVE_PWRITE 1\n#endif\n#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)\n# undef USE_PREAD\n# define USE_PREAD64 1\n#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)\n# undef USE_PREAD64\n# define USE_PREAD 1\n#endif\n\n/*\n** standard include files.\n*/\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <sys/ioctl.h>\n#include <unistd.h>\n/* #include <time.h> */\n#include <sys/time.h>\n#include <errno.h>\n#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0\n# include <sys/mman.h>\n#endif\n\n#if SQLITE_ENABLE_LOCKING_STYLE\n/* # include <sys/ioctl.h> */\n# include <sys/file.h>\n# include <sys/param.h>\n#endif /* SQLITE_ENABLE_LOCKING_STYLE */\n\n/*\n** Try to determine if gethostuuid() is available based on standard\n** macros.  This might sometimes compute the wrong value for some\n** obscure platforms.  For those cases, simply compile with one of\n** the following:\n**\n**    -DHAVE_GETHOSTUUID=0\n**    -DHAVE_GETHOSTUUID=1\n**\n** None if this matters except when building on Apple products with\n** -DSQLITE_ENABLE_LOCKING_STYLE.\n*/\n#ifndef HAVE_GETHOSTUUID\n# define HAVE_GETHOSTUUID 0\n# if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \\\n                            (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))\n#    if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \\\n         && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))\n#      undef HAVE_GETHOSTUUID\n#      define HAVE_GETHOSTUUID 1\n#    else\n#      warning \"gethostuuid() is disabled.\"\n#    endif\n#  endif\n#endif\n\n\n#if OS_VXWORKS\n/* # include <sys/ioctl.h> */\n# include <semaphore.h>\n# include <limits.h>\n#endif /* OS_VXWORKS */\n\n#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE\n# include <sys/mount.h>\n#endif\n\n#ifdef HAVE_UTIME\n# include <utime.h>\n#endif\n\n/*\n** Allowed values of unixFile.fsFlags\n*/\n#define SQLITE_FSFLAGS_IS_MSDOS     0x1\n\n/*\n** If we are to be thread-safe, include the pthreads header.\n*/\n#if SQLITE_THREADSAFE\n/* # include <pthread.h> */\n#endif\n\n/*\n** Default permissions when creating a new file\n*/\n#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS\n# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644\n#endif\n\n/*\n** Default permissions when creating auto proxy dir\n*/\n#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS\n# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755\n#endif\n\n/*\n** Maximum supported path-length.\n*/\n#define MAX_PATHNAME 512\n\n/*\n** Maximum supported symbolic links\n*/\n#define SQLITE_MAX_SYMLINKS 100\n\n/* Always cast the getpid() return type for compatibility with\n** kernel modules in VxWorks. */\n#define osGetpid(X) (pid_t)getpid()\n\n/*\n** Only set the lastErrno if the error code is a real error and not \n** a normal expected return code of SQLITE_BUSY or SQLITE_OK\n*/\n#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))\n\n/* Forward references */\ntypedef struct unixShm unixShm;               /* Connection shared memory */\ntypedef struct unixShmNode unixShmNode;       /* Shared memory instance */\ntypedef struct unixInodeInfo unixInodeInfo;   /* An i-node */\ntypedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */\n\n/*\n** Sometimes, after a file handle is closed by SQLite, the file descriptor\n** cannot be closed immediately. In these cases, instances of the following\n** structure are used to store the file descriptor while waiting for an\n** opportunity to either close or reuse it.\n*/\nstruct UnixUnusedFd {\n  int fd;                   /* File descriptor to close */\n  int flags;                /* Flags this file descriptor was opened with */\n  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */\n};\n\n/*\n** The unixFile structure is subclass of sqlite3_file specific to the unix\n** VFS implementations.\n*/\ntypedef struct unixFile unixFile;\nstruct unixFile {\n  sqlite3_io_methods const *pMethod;  /* Always the first entry */\n  sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */\n  unixInodeInfo *pInode;              /* Info about locks on this inode */\n  int h;                              /* The file descriptor */\n  unsigned char eFileLock;            /* The type of lock held on this fd */\n  unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */\n  int lastErrno;                      /* The unix errno from last I/O error */\n  void *lockingContext;               /* Locking style specific state */\n  UnixUnusedFd *pPreallocatedUnused;  /* Pre-allocated UnixUnusedFd */\n  const char *zPath;                  /* Name of the file */\n  unixShm *pShm;                      /* Shared memory segment information */\n  int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */\n#if SQLITE_MAX_MMAP_SIZE>0\n  int nFetchOut;                      /* Number of outstanding xFetch refs */\n  sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */\n  sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */\n  sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */\n  void *pMapRegion;                   /* Memory mapped region */\n#endif\n  int sectorSize;                     /* Device sector size */\n  int deviceCharacteristics;          /* Precomputed device characteristics */\n#if SQLITE_ENABLE_LOCKING_STYLE\n  int openFlags;                      /* The flags specified at open() */\n#endif\n#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)\n  unsigned fsFlags;                   /* cached details from statfs() */\n#endif\n#ifdef SQLITE_ENABLE_SETLK_TIMEOUT\n  unsigned iBusyTimeout;              /* Wait this many millisec on locks */\n#endif\n#if OS_VXWORKS\n  struct vxworksFileId *pId;          /* Unique file ID */\n#endif\n#ifdef SQLITE_DEBUG\n  /* The next group of variables are used to track whether or not the\n  ** transaction counter in bytes 24-27 of database files are updated\n  ** whenever any part of the database changes.  An assertion fault will\n  ** occur if a file is updated without also updating the transaction\n  ** counter.  This test is made to avoid new problems similar to the\n  ** one described by ticket #3584. \n  */\n  unsigned char transCntrChng;   /* True if the transaction counter changed */\n  unsigned char dbUpdate;        /* True if any part of database file changed */\n  unsigned char inNormalWrite;   /* True if in a normal write operation */\n\n#endif\n\n#ifdef SQLITE_TEST\n  /* In test mode, increase the size of this structure a bit so that \n  ** it is larger than the struct CrashFile defined in test6.c.\n  */\n  char aPadding[32];\n#endif\n};\n\n/* This variable holds the process id (pid) from when the xRandomness()\n** method was called.  If xOpen() is called from a different process id,\n** indicating that a fork() has occurred, the PRNG will be reset.\n*/\nstatic pid_t randomnessPid = 0;\n\n/*\n** Allowed values for the unixFile.ctrlFlags bitmask:\n*/\n#define UNIXFILE_EXCL        0x01     /* Connections from one process only */\n#define UNIXFILE_RDONLY      0x02     /* Connection is read only */\n#define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */\n#ifndef SQLITE_DISABLE_DIRSYNC\n# define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */\n#else\n# define UNIXFILE_DIRSYNC    0x00\n#endif\n#define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */\n#define UNIXFILE_DELETE      0x20     /* Delete on close */\n#define UNIXFILE_URI         0x40     /* Filename might have query parameters */\n#define UNIXFILE_NOLOCK      0x80     /* Do no file locking */\n\n/*\n** Include code that is common to all os_*.c files\n*/\n/************** Include os_common.h in the middle of os_unix.c ***************/\n/************** Begin file os_common.h ***************************************/\n/*\n** 2004 May 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains macros and a little bit of code that is common to\n** all of the platform-specific files (os_*.c) and is #included into those\n** files.\n**\n** This file should be #included by the os_*.c files only.  It is not a\n** general purpose header file.\n*/\n#ifndef _OS_COMMON_H_\n#define _OS_COMMON_H_\n\n/*\n** At least two bugs have slipped in because we changed the MEMORY_DEBUG\n** macro to SQLITE_DEBUG and some older makefiles have not yet made the\n** switch.  The following code should catch this problem at compile-time.\n*/\n#ifdef MEMORY_DEBUG\n# error \"The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead.\"\n#endif\n\n/*\n** Macros for performance tracing.  Normally turned off.  Only works\n** on i486 hardware.\n*/\n#ifdef SQLITE_PERFORMANCE_TRACE\n\n/*\n** hwtime.h contains inline assembler code for implementing\n** high-performance timing routines.\n*/\n/************** Include hwtime.h in the middle of os_common.h ****************/\n/************** Begin file hwtime.h ******************************************/\n/*\n** 2008 May 27\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains inline asm code for retrieving \"high-performance\"\n** counters for x86 and x86_64 class CPUs.\n*/\n#ifndef SQLITE_HWTIME_H\n#define SQLITE_HWTIME_H\n\n/*\n** The following routine only works on pentium-class (or newer) processors.\n** It uses the RDTSC opcode to read the cycle count value out of the\n** processor and returns that value.  This can be used for high-res\n** profiling.\n*/\n#if !defined(__STRICT_ANSI__) && \\\n    (defined(__GNUC__) || defined(_MSC_VER)) && \\\n    (defined(i386) || defined(__i386__) || defined(_M_IX86))\n\n  #if defined(__GNUC__)\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n     unsigned int lo, hi;\n     __asm__ __volatile__ (\"rdtsc\" : \"=a\" (lo), \"=d\" (hi));\n     return (sqlite_uint64)hi << 32 | lo;\n  }\n\n  #elif defined(_MSC_VER)\n\n  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){\n     __asm {\n        rdtsc\n        ret       ; return value at EDX:EAX\n     }\n  }\n\n  #endif\n\n#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n      unsigned long val;\n      __asm__ __volatile__ (\"rdtsc\" : \"=A\" (val));\n      return val;\n  }\n \n#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n      unsigned long long retval;\n      unsigned long junk;\n      __asm__ __volatile__ (\"\\n\\\n          1:      mftbu   %1\\n\\\n                  mftb    %L0\\n\\\n                  mftbu   %0\\n\\\n                  cmpw    %0,%1\\n\\\n                  bne     1b\"\n                  : \"=r\" (retval), \"=r\" (junk));\n      return retval;\n  }\n\n#else\n\n  /*\n  ** asm() is needed for hardware timing support.  Without asm(),\n  ** disable the sqlite3Hwtime() routine.\n  **\n  ** sqlite3Hwtime() is only used for some obscure debugging\n  ** and analysis configurations, not in any deliverable, so this\n  ** should not be a great loss.\n  */\nSQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }\n\n#endif\n\n#endif /* !defined(SQLITE_HWTIME_H) */\n\n/************** End of hwtime.h **********************************************/\n/************** Continuing where we left off in os_common.h ******************/\n\nstatic sqlite_uint64 g_start;\nstatic sqlite_uint64 g_elapsed;\n#define TIMER_START       g_start=sqlite3Hwtime()\n#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start\n#define TIMER_ELAPSED     g_elapsed\n#else\n#define TIMER_START\n#define TIMER_END\n#define TIMER_ELAPSED     ((sqlite_uint64)0)\n#endif\n\n/*\n** If we compile with the SQLITE_TEST macro set, then the following block\n** of code will give us the ability to simulate a disk I/O error.  This\n** is used for testing the I/O recovery logic.\n*/\n#if defined(SQLITE_TEST)\nSQLITE_API extern int sqlite3_io_error_hit;\nSQLITE_API extern int sqlite3_io_error_hardhit;\nSQLITE_API extern int sqlite3_io_error_pending;\nSQLITE_API extern int sqlite3_io_error_persist;\nSQLITE_API extern int sqlite3_io_error_benign;\nSQLITE_API extern int sqlite3_diskfull_pending;\nSQLITE_API extern int sqlite3_diskfull;\n#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)\n#define SimulateIOError(CODE)  \\\n  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \\\n       || sqlite3_io_error_pending-- == 1 )  \\\n              { local_ioerr(); CODE; }\nstatic void local_ioerr(){\n  IOTRACE((\"IOERR\\n\"));\n  sqlite3_io_error_hit++;\n  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;\n}\n#define SimulateDiskfullError(CODE) \\\n   if( sqlite3_diskfull_pending ){ \\\n     if( sqlite3_diskfull_pending == 1 ){ \\\n       local_ioerr(); \\\n       sqlite3_diskfull = 1; \\\n       sqlite3_io_error_hit = 1; \\\n       CODE; \\\n     }else{ \\\n       sqlite3_diskfull_pending--; \\\n     } \\\n   }\n#else\n#define SimulateIOErrorBenign(X)\n#define SimulateIOError(A)\n#define SimulateDiskfullError(A)\n#endif /* defined(SQLITE_TEST) */\n\n/*\n** When testing, keep a count of the number of open files.\n*/\n#if defined(SQLITE_TEST)\nSQLITE_API extern int sqlite3_open_file_count;\n#define OpenCounter(X)  sqlite3_open_file_count+=(X)\n#else\n#define OpenCounter(X)\n#endif /* defined(SQLITE_TEST) */\n\n#endif /* !defined(_OS_COMMON_H_) */\n\n/************** End of os_common.h *******************************************/\n/************** Continuing where we left off in os_unix.c ********************/\n\n/*\n** Define various macros that are missing from some systems.\n*/\n#ifndef O_LARGEFILE\n# define O_LARGEFILE 0\n#endif\n#ifdef SQLITE_DISABLE_LFS\n# undef O_LARGEFILE\n# define O_LARGEFILE 0\n#endif\n#ifndef O_NOFOLLOW\n# define O_NOFOLLOW 0\n#endif\n#ifndef O_BINARY\n# define O_BINARY 0\n#endif\n\n/*\n** The threadid macro resolves to the thread-id or to 0.  Used for\n** testing and debugging only.\n*/\n#if SQLITE_THREADSAFE\n#define threadid pthread_self()\n#else\n#define threadid 0\n#endif\n\n/*\n** HAVE_MREMAP defaults to true on Linux and false everywhere else.\n*/\n#if !defined(HAVE_MREMAP)\n# if defined(__linux__) && defined(_GNU_SOURCE)\n#  define HAVE_MREMAP 1\n# else\n#  define HAVE_MREMAP 0\n# endif\n#endif\n\n/*\n** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()\n** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.\n*/\n#ifdef __ANDROID__\n# define lseek lseek64\n#endif\n\n#ifdef __linux__\n/*\n** Linux-specific IOCTL magic numbers used for controlling F2FS\n*/\n#define F2FS_IOCTL_MAGIC        0xf5\n#define F2FS_IOC_START_ATOMIC_WRITE     _IO(F2FS_IOCTL_MAGIC, 1)\n#define F2FS_IOC_COMMIT_ATOMIC_WRITE    _IO(F2FS_IOCTL_MAGIC, 2)\n#define F2FS_IOC_START_VOLATILE_WRITE   _IO(F2FS_IOCTL_MAGIC, 3)\n#define F2FS_IOC_ABORT_VOLATILE_WRITE   _IO(F2FS_IOCTL_MAGIC, 5)\n#define F2FS_IOC_GET_FEATURES           _IOR(F2FS_IOCTL_MAGIC, 12, u32)\n#define F2FS_FEATURE_ATOMIC_WRITE 0x0004\n#endif /* __linux__ */\n\n\n/*\n** Different Unix systems declare open() in different ways.  Same use\n** open(const char*,int,mode_t).  Others use open(const char*,int,...).\n** The difference is important when using a pointer to the function.\n**\n** The safest way to deal with the problem is to always use this wrapper\n** which always has the same well-defined interface.\n*/\nstatic int posixOpen(const char *zFile, int flags, int mode){\n  return open(zFile, flags, mode);\n}\n\n/* Forward reference */\nstatic int openDirectory(const char*, int*);\nstatic int unixGetpagesize(void);\n\n/*\n** Many system calls are accessed through pointer-to-functions so that\n** they may be overridden at runtime to facilitate fault injection during\n** testing and sandboxing.  The following array holds the names and pointers\n** to all overrideable system calls.\n*/\nstatic struct unix_syscall {\n  const char *zName;            /* Name of the system call */\n  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */\n  sqlite3_syscall_ptr pDefault; /* Default value */\n} aSyscall[] = {\n  { \"open\",         (sqlite3_syscall_ptr)posixOpen,  0  },\n#define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)\n\n  { \"close\",        (sqlite3_syscall_ptr)close,      0  },\n#define osClose     ((int(*)(int))aSyscall[1].pCurrent)\n\n  { \"access\",       (sqlite3_syscall_ptr)access,     0  },\n#define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)\n\n  { \"getcwd\",       (sqlite3_syscall_ptr)getcwd,     0  },\n#define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)\n\n  { \"stat\",         (sqlite3_syscall_ptr)stat,       0  },\n#define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)\n\n/*\n** The DJGPP compiler environment looks mostly like Unix, but it\n** lacks the fcntl() system call.  So redefine fcntl() to be something\n** that always succeeds.  This means that locking does not occur under\n** DJGPP.  But it is DOS - what did you expect?\n*/\n#ifdef __DJGPP__\n  { \"fstat\",        0,                 0  },\n#define osFstat(a,b,c)    0\n#else     \n  { \"fstat\",        (sqlite3_syscall_ptr)fstat,      0  },\n#define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)\n#endif\n\n  { \"ftruncate\",    (sqlite3_syscall_ptr)ftruncate,  0  },\n#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)\n\n  { \"fcntl\",        (sqlite3_syscall_ptr)fcntl,      0  },\n#define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)\n\n  { \"read\",         (sqlite3_syscall_ptr)read,       0  },\n#define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)\n\n#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE\n  { \"pread\",        (sqlite3_syscall_ptr)pread,      0  },\n#else\n  { \"pread\",        (sqlite3_syscall_ptr)0,          0  },\n#endif\n#define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)\n\n#if defined(USE_PREAD64)\n  { \"pread64\",      (sqlite3_syscall_ptr)pread64,    0  },\n#else\n  { \"pread64\",      (sqlite3_syscall_ptr)0,          0  },\n#endif\n#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)\n\n  { \"write\",        (sqlite3_syscall_ptr)write,      0  },\n#define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)\n\n#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE\n  { \"pwrite\",       (sqlite3_syscall_ptr)pwrite,     0  },\n#else\n  { \"pwrite\",       (sqlite3_syscall_ptr)0,          0  },\n#endif\n#define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\\\n                    aSyscall[12].pCurrent)\n\n#if defined(USE_PREAD64)\n  { \"pwrite64\",     (sqlite3_syscall_ptr)pwrite64,   0  },\n#else\n  { \"pwrite64\",     (sqlite3_syscall_ptr)0,          0  },\n#endif\n#define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off64_t))\\\n                    aSyscall[13].pCurrent)\n\n  { \"fchmod\",       (sqlite3_syscall_ptr)fchmod,          0  },\n#define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)\n\n#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE\n  { \"fallocate\",    (sqlite3_syscall_ptr)posix_fallocate,  0 },\n#else\n  { \"fallocate\",    (sqlite3_syscall_ptr)0,                0 },\n#endif\n#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)\n\n  { \"unlink\",       (sqlite3_syscall_ptr)unlink,           0 },\n#define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)\n\n  { \"openDirectory\",    (sqlite3_syscall_ptr)openDirectory,      0 },\n#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)\n\n  { \"mkdir\",        (sqlite3_syscall_ptr)mkdir,           0 },\n#define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)\n\n  { \"rmdir\",        (sqlite3_syscall_ptr)rmdir,           0 },\n#define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)\n\n#if defined(HAVE_FCHOWN)\n  { \"fchown\",       (sqlite3_syscall_ptr)fchown,          0 },\n#else\n  { \"fchown\",       (sqlite3_syscall_ptr)0,               0 },\n#endif\n#define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)\n\n#if defined(HAVE_FCHOWN)\n  { \"geteuid\",      (sqlite3_syscall_ptr)geteuid,         0 },\n#else\n  { \"geteuid\",      (sqlite3_syscall_ptr)0,               0 },\n#endif\n#define osGeteuid   ((uid_t(*)(void))aSyscall[21].pCurrent)\n\n#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0\n  { \"mmap\",         (sqlite3_syscall_ptr)mmap,            0 },\n#else\n  { \"mmap\",         (sqlite3_syscall_ptr)0,               0 },\n#endif\n#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)\n\n#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0\n  { \"munmap\",       (sqlite3_syscall_ptr)munmap,          0 },\n#else\n  { \"munmap\",       (sqlite3_syscall_ptr)0,               0 },\n#endif\n#define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)\n\n#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)\n  { \"mremap\",       (sqlite3_syscall_ptr)mremap,          0 },\n#else\n  { \"mremap\",       (sqlite3_syscall_ptr)0,               0 },\n#endif\n#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)\n\n#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0\n  { \"getpagesize\",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },\n#else\n  { \"getpagesize\",  (sqlite3_syscall_ptr)0,               0 },\n#endif\n#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)\n\n#if defined(HAVE_READLINK)\n  { \"readlink\",     (sqlite3_syscall_ptr)readlink,        0 },\n#else\n  { \"readlink\",     (sqlite3_syscall_ptr)0,               0 },\n#endif\n#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)\n\n#if defined(HAVE_LSTAT)\n  { \"lstat\",         (sqlite3_syscall_ptr)lstat,          0 },\n#else\n  { \"lstat\",         (sqlite3_syscall_ptr)0,              0 },\n#endif\n#define osLstat      ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)\n\n#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)\n# ifdef __ANDROID__\n  { \"ioctl\", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },\n#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)\n# else\n  { \"ioctl\",         (sqlite3_syscall_ptr)ioctl,          0 },\n#define osIoctl ((int(*)(int,unsigned long,...))aSyscall[28].pCurrent)\n# endif\n#else\n  { \"ioctl\",         (sqlite3_syscall_ptr)0,              0 },\n#endif\n\n}; /* End of the overrideable system calls */\n\n\n/*\n** On some systems, calls to fchown() will trigger a message in a security\n** log if they come from non-root processes.  So avoid calling fchown() if\n** we are not running as root.\n*/\nstatic int robustFchown(int fd, uid_t uid, gid_t gid){\n#if defined(HAVE_FCHOWN)\n  return osGeteuid() ? 0 : osFchown(fd,uid,gid);\n#else\n  return 0;\n#endif\n}\n\n/*\n** This is the xSetSystemCall() method of sqlite3_vfs for all of the\n** \"unix\" VFSes.  Return SQLITE_OK opon successfully updating the\n** system call pointer, or SQLITE_NOTFOUND if there is no configurable\n** system call named zName.\n*/\nstatic int unixSetSystemCall(\n  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */\n  const char *zName,            /* Name of system call to override */\n  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */\n){\n  unsigned int i;\n  int rc = SQLITE_NOTFOUND;\n\n  UNUSED_PARAMETER(pNotUsed);\n  if( zName==0 ){\n    /* If no zName is given, restore all system calls to their default\n    ** settings and return NULL\n    */\n    rc = SQLITE_OK;\n    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){\n      if( aSyscall[i].pDefault ){\n        aSyscall[i].pCurrent = aSyscall[i].pDefault;\n      }\n    }\n  }else{\n    /* If zName is specified, operate on only the one system call\n    ** specified.\n    */\n    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){\n      if( strcmp(zName, aSyscall[i].zName)==0 ){\n        if( aSyscall[i].pDefault==0 ){\n          aSyscall[i].pDefault = aSyscall[i].pCurrent;\n        }\n        rc = SQLITE_OK;\n        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;\n        aSyscall[i].pCurrent = pNewFunc;\n        break;\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** Return the value of a system call.  Return NULL if zName is not a\n** recognized system call name.  NULL is also returned if the system call\n** is currently undefined.\n*/\nstatic sqlite3_syscall_ptr unixGetSystemCall(\n  sqlite3_vfs *pNotUsed,\n  const char *zName\n){\n  unsigned int i;\n\n  UNUSED_PARAMETER(pNotUsed);\n  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){\n    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;\n  }\n  return 0;\n}\n\n/*\n** Return the name of the first system call after zName.  If zName==NULL\n** then return the name of the first system call.  Return NULL if zName\n** is the last system call or if zName is not the name of a valid\n** system call.\n*/\nstatic const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){\n  int i = -1;\n\n  UNUSED_PARAMETER(p);\n  if( zName ){\n    for(i=0; i<ArraySize(aSyscall)-1; i++){\n      if( strcmp(zName, aSyscall[i].zName)==0 ) break;\n    }\n  }\n  for(i++; i<ArraySize(aSyscall); i++){\n    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;\n  }\n  return 0;\n}\n\n/*\n** Do not accept any file descriptor less than this value, in order to avoid\n** opening database file using file descriptors that are commonly used for \n** standard input, output, and error.\n*/\n#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR\n# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3\n#endif\n\n/*\n** Invoke open().  Do so multiple times, until it either succeeds or\n** fails for some reason other than EINTR.\n**\n** If the file creation mode \"m\" is 0 then set it to the default for\n** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally\n** 0644) as modified by the system umask.  If m is not 0, then\n** make the file creation mode be exactly m ignoring the umask.\n**\n** The m parameter will be non-zero only when creating -wal, -journal,\n** and -shm files.  We want those files to have *exactly* the same\n** permissions as their original database, unadulterated by the umask.\n** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a\n** transaction crashes and leaves behind hot journals, then any\n** process that is able to write to the database will also be able to\n** recover the hot journals.\n*/\nstatic int robust_open(const char *z, int f, mode_t m){\n  int fd;\n  mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;\n  while(1){\n#if defined(O_CLOEXEC)\n    fd = osOpen(z,f|O_CLOEXEC,m2);\n#else\n    fd = osOpen(z,f,m2);\n#endif\n    if( fd<0 ){\n      if( errno==EINTR ) continue;\n      break;\n    }\n    if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;\n    osClose(fd);\n    sqlite3_log(SQLITE_WARNING, \n                \"attempt to open \\\"%s\\\" as file descriptor %d\", z, fd);\n    fd = -1;\n    if( osOpen(\"/dev/null\", O_RDONLY, m)<0 ) break;\n  }\n  if( fd>=0 ){\n    if( m!=0 ){\n      struct stat statbuf;\n      if( osFstat(fd, &statbuf)==0 \n       && statbuf.st_size==0\n       && (statbuf.st_mode&0777)!=m \n      ){\n        osFchmod(fd, m);\n      }\n    }\n#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)\n    osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);\n#endif\n  }\n  return fd;\n}\n\n/*\n** Helper functions to obtain and relinquish the global mutex. The\n** global mutex is used to protect the unixInodeInfo and\n** vxworksFileId objects used by this file, all of which may be \n** shared by multiple threads.\n**\n** Function unixMutexHeld() is used to assert() that the global mutex \n** is held when required. This function is only used as part of assert() \n** statements. e.g.\n**\n**   unixEnterMutex()\n**     assert( unixMutexHeld() );\n**   unixEnterLeave()\n**\n** To prevent deadlock, the global unixBigLock must must be acquired\n** before the unixInodeInfo.pLockMutex mutex, if both are held.  It is\n** OK to get the pLockMutex without holding unixBigLock first, but if\n** that happens, the unixBigLock mutex must not be acquired until after\n** pLockMutex is released.\n**\n**      OK:     enter(unixBigLock),  enter(pLockInfo)\n**      OK:     enter(unixBigLock)\n**      OK:     enter(pLockInfo)\n**   ERROR:     enter(pLockInfo), enter(unixBigLock)\n*/\nstatic sqlite3_mutex *unixBigLock = 0;\nstatic void unixEnterMutex(void){\n  assert( sqlite3_mutex_notheld(unixBigLock) );  /* Not a recursive mutex */\n  sqlite3_mutex_enter(unixBigLock);\n}\nstatic void unixLeaveMutex(void){\n  assert( sqlite3_mutex_held(unixBigLock) );\n  sqlite3_mutex_leave(unixBigLock);\n}\n#ifdef SQLITE_DEBUG\nstatic int unixMutexHeld(void) {\n  return sqlite3_mutex_held(unixBigLock);\n}\n#endif\n\n\n#ifdef SQLITE_HAVE_OS_TRACE\n/*\n** Helper function for printing out trace information from debugging\n** binaries. This returns the string representation of the supplied\n** integer lock-type.\n*/\nstatic const char *azFileLock(int eFileLock){\n  switch( eFileLock ){\n    case NO_LOCK: return \"NONE\";\n    case SHARED_LOCK: return \"SHARED\";\n    case RESERVED_LOCK: return \"RESERVED\";\n    case PENDING_LOCK: return \"PENDING\";\n    case EXCLUSIVE_LOCK: return \"EXCLUSIVE\";\n  }\n  return \"ERROR\";\n}\n#endif\n\n#ifdef SQLITE_LOCK_TRACE\n/*\n** Print out information about all locking operations.\n**\n** This routine is used for troubleshooting locks on multithreaded\n** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE\n** command-line option on the compiler.  This code is normally\n** turned off.\n*/\nstatic int lockTrace(int fd, int op, struct flock *p){\n  char *zOpName, *zType;\n  int s;\n  int savedErrno;\n  if( op==F_GETLK ){\n    zOpName = \"GETLK\";\n  }else if( op==F_SETLK ){\n    zOpName = \"SETLK\";\n  }else{\n    s = osFcntl(fd, op, p);\n    sqlite3DebugPrintf(\"fcntl unknown %d %d %d\\n\", fd, op, s);\n    return s;\n  }\n  if( p->l_type==F_RDLCK ){\n    zType = \"RDLCK\";\n  }else if( p->l_type==F_WRLCK ){\n    zType = \"WRLCK\";\n  }else if( p->l_type==F_UNLCK ){\n    zType = \"UNLCK\";\n  }else{\n    assert( 0 );\n  }\n  assert( p->l_whence==SEEK_SET );\n  s = osFcntl(fd, op, p);\n  savedErrno = errno;\n  sqlite3DebugPrintf(\"fcntl %d %d %s %s %d %d %d %d\\n\",\n     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,\n     (int)p->l_pid, s);\n  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){\n    struct flock l2;\n    l2 = *p;\n    osFcntl(fd, F_GETLK, &l2);\n    if( l2.l_type==F_RDLCK ){\n      zType = \"RDLCK\";\n    }else if( l2.l_type==F_WRLCK ){\n      zType = \"WRLCK\";\n    }else if( l2.l_type==F_UNLCK ){\n      zType = \"UNLCK\";\n    }else{\n      assert( 0 );\n    }\n    sqlite3DebugPrintf(\"fcntl-failure-reason: %s %d %d %d\\n\",\n       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);\n  }\n  errno = savedErrno;\n  return s;\n}\n#undef osFcntl\n#define osFcntl lockTrace\n#endif /* SQLITE_LOCK_TRACE */\n\n/*\n** Retry ftruncate() calls that fail due to EINTR\n**\n** All calls to ftruncate() within this file should be made through\n** this wrapper.  On the Android platform, bypassing the logic below\n** could lead to a corrupt database.\n*/\nstatic int robust_ftruncate(int h, sqlite3_int64 sz){\n  int rc;\n#ifdef __ANDROID__\n  /* On Android, ftruncate() always uses 32-bit offsets, even if \n  ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to\n  ** truncate a file to any size larger than 2GiB. Silently ignore any\n  ** such attempts.  */\n  if( sz>(sqlite3_int64)0x7FFFFFFF ){\n    rc = SQLITE_OK;\n  }else\n#endif\n  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );\n  return rc;\n}\n\n/*\n** This routine translates a standard POSIX errno code into something\n** useful to the clients of the sqlite3 functions.  Specifically, it is\n** intended to translate a variety of \"try again\" errors into SQLITE_BUSY\n** and a variety of \"please close the file descriptor NOW\" errors into \n** SQLITE_IOERR\n** \n** Errors during initialization of locks, or file system support for locks,\n** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.\n*/\nstatic int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {\n  assert( (sqliteIOErr == SQLITE_IOERR_LOCK) || \n          (sqliteIOErr == SQLITE_IOERR_UNLOCK) || \n          (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||\n          (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );\n  switch (posixError) {\n  case EACCES: \n  case EAGAIN:\n  case ETIMEDOUT:\n  case EBUSY:\n  case EINTR:\n  case ENOLCK:  \n    /* random NFS retry error, unless during file system support \n     * introspection, in which it actually means what it says */\n    return SQLITE_BUSY;\n    \n  case EPERM: \n    return SQLITE_PERM;\n    \n  default: \n    return sqliteIOErr;\n  }\n}\n\n\n/******************************************************************************\n****************** Begin Unique File ID Utility Used By VxWorks ***************\n**\n** On most versions of unix, we can get a unique ID for a file by concatenating\n** the device number and the inode number.  But this does not work on VxWorks.\n** On VxWorks, a unique file id must be based on the canonical filename.\n**\n** A pointer to an instance of the following structure can be used as a\n** unique file ID in VxWorks.  Each instance of this structure contains\n** a copy of the canonical filename.  There is also a reference count.  \n** The structure is reclaimed when the number of pointers to it drops to\n** zero.\n**\n** There are never very many files open at one time and lookups are not\n** a performance-critical path, so it is sufficient to put these\n** structures on a linked list.\n*/\nstruct vxworksFileId {\n  struct vxworksFileId *pNext;  /* Next in a list of them all */\n  int nRef;                     /* Number of references to this one */\n  int nName;                    /* Length of the zCanonicalName[] string */\n  char *zCanonicalName;         /* Canonical filename */\n};\n\n#if OS_VXWORKS\n/* \n** All unique filenames are held on a linked list headed by this\n** variable:\n*/\nstatic struct vxworksFileId *vxworksFileList = 0;\n\n/*\n** Simplify a filename into its canonical form\n** by making the following changes:\n**\n**  * removing any trailing and duplicate /\n**  * convert /./ into just /\n**  * convert /A/../ where A is any simple name into just /\n**\n** Changes are made in-place.  Return the new name length.\n**\n** The original filename is in z[0..n-1].  Return the number of\n** characters in the simplified name.\n*/\nstatic int vxworksSimplifyName(char *z, int n){\n  int i, j;\n  while( n>1 && z[n-1]=='/' ){ n--; }\n  for(i=j=0; i<n; i++){\n    if( z[i]=='/' ){\n      if( z[i+1]=='/' ) continue;\n      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){\n        i += 1;\n        continue;\n      }\n      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){\n        while( j>0 && z[j-1]!='/' ){ j--; }\n        if( j>0 ){ j--; }\n        i += 2;\n        continue;\n      }\n    }\n    z[j++] = z[i];\n  }\n  z[j] = 0;\n  return j;\n}\n\n/*\n** Find a unique file ID for the given absolute pathname.  Return\n** a pointer to the vxworksFileId object.  This pointer is the unique\n** file ID.\n**\n** The nRef field of the vxworksFileId object is incremented before\n** the object is returned.  A new vxworksFileId object is created\n** and added to the global list if necessary.\n**\n** If a memory allocation error occurs, return NULL.\n*/\nstatic struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){\n  struct vxworksFileId *pNew;         /* search key and new file ID */\n  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */\n  int n;                              /* Length of zAbsoluteName string */\n\n  assert( zAbsoluteName[0]=='/' );\n  n = (int)strlen(zAbsoluteName);\n  pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );\n  if( pNew==0 ) return 0;\n  pNew->zCanonicalName = (char*)&pNew[1];\n  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);\n  n = vxworksSimplifyName(pNew->zCanonicalName, n);\n\n  /* Search for an existing entry that matching the canonical name.\n  ** If found, increment the reference count and return a pointer to\n  ** the existing file ID.\n  */\n  unixEnterMutex();\n  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){\n    if( pCandidate->nName==n \n     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0\n    ){\n       sqlite3_free(pNew);\n       pCandidate->nRef++;\n       unixLeaveMutex();\n       return pCandidate;\n    }\n  }\n\n  /* No match was found.  We will make a new file ID */\n  pNew->nRef = 1;\n  pNew->nName = n;\n  pNew->pNext = vxworksFileList;\n  vxworksFileList = pNew;\n  unixLeaveMutex();\n  return pNew;\n}\n\n/*\n** Decrement the reference count on a vxworksFileId object.  Free\n** the object when the reference count reaches zero.\n*/\nstatic void vxworksReleaseFileId(struct vxworksFileId *pId){\n  unixEnterMutex();\n  assert( pId->nRef>0 );\n  pId->nRef--;\n  if( pId->nRef==0 ){\n    struct vxworksFileId **pp;\n    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}\n    assert( *pp==pId );\n    *pp = pId->pNext;\n    sqlite3_free(pId);\n  }\n  unixLeaveMutex();\n}\n#endif /* OS_VXWORKS */\n/*************** End of Unique File ID Utility Used By VxWorks ****************\n******************************************************************************/\n\n\n/******************************************************************************\n*************************** Posix Advisory Locking ****************************\n**\n** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)\n** section 6.5.2.2 lines 483 through 490 specify that when a process\n** sets or clears a lock, that operation overrides any prior locks set\n** by the same process.  It does not explicitly say so, but this implies\n** that it overrides locks set by the same process using a different\n** file descriptor.  Consider this test case:\n**\n**       int fd1 = open(\"./file1\", O_RDWR|O_CREAT, 0644);\n**       int fd2 = open(\"./file2\", O_RDWR|O_CREAT, 0644);\n**\n** Suppose ./file1 and ./file2 are really the same file (because\n** one is a hard or symbolic link to the other) then if you set\n** an exclusive lock on fd1, then try to get an exclusive lock\n** on fd2, it works.  I would have expected the second lock to\n** fail since there was already a lock on the file due to fd1.\n** But not so.  Since both locks came from the same process, the\n** second overrides the first, even though they were on different\n** file descriptors opened on different file names.\n**\n** This means that we cannot use POSIX locks to synchronize file access\n** among competing threads of the same process.  POSIX locks will work fine\n** to synchronize access for threads in separate processes, but not\n** threads within the same process.\n**\n** To work around the problem, SQLite has to manage file locks internally\n** on its own.  Whenever a new database is opened, we have to find the\n** specific inode of the database file (the inode is determined by the\n** st_dev and st_ino fields of the stat structure that fstat() fills in)\n** and check for locks already existing on that inode.  When locks are\n** created or removed, we have to look at our own internal record of the\n** locks to see if another thread has previously set a lock on that same\n** inode.\n**\n** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.\n** For VxWorks, we have to use the alternative unique ID system based on\n** canonical filename and implemented in the previous division.)\n**\n** The sqlite3_file structure for POSIX is no longer just an integer file\n** descriptor.  It is now a structure that holds the integer file\n** descriptor and a pointer to a structure that describes the internal\n** locks on the corresponding inode.  There is one locking structure\n** per inode, so if the same inode is opened twice, both unixFile structures\n** point to the same locking structure.  The locking structure keeps\n** a reference count (so we will know when to delete it) and a \"cnt\"\n** field that tells us its internal lock status.  cnt==0 means the\n** file is unlocked.  cnt==-1 means the file has an exclusive lock.\n** cnt>0 means there are cnt shared locks on the file.\n**\n** Any attempt to lock or unlock a file first checks the locking\n** structure.  The fcntl() system call is only invoked to set a \n** POSIX lock if the internal lock structure transitions between\n** a locked and an unlocked state.\n**\n** But wait:  there are yet more problems with POSIX advisory locks.\n**\n** If you close a file descriptor that points to a file that has locks,\n** all locks on that file that are owned by the current process are\n** released.  To work around this problem, each unixInodeInfo object\n** maintains a count of the number of pending locks on tha inode.\n** When an attempt is made to close an unixFile, if there are\n** other unixFile open on the same inode that are holding locks, the call\n** to close() the file descriptor is deferred until all of the locks clear.\n** The unixInodeInfo structure keeps a list of file descriptors that need to\n** be closed and that list is walked (and cleared) when the last lock\n** clears.\n**\n** Yet another problem:  LinuxThreads do not play well with posix locks.\n**\n** Many older versions of linux use the LinuxThreads library which is\n** not posix compliant.  Under LinuxThreads, a lock created by thread\n** A cannot be modified or overridden by a different thread B.\n** Only thread A can modify the lock.  Locking behavior is correct\n** if the appliation uses the newer Native Posix Thread Library (NPTL)\n** on linux - with NPTL a lock created by thread A can override locks\n** in thread B.  But there is no way to know at compile-time which\n** threading library is being used.  So there is no way to know at\n** compile-time whether or not thread A can override locks on thread B.\n** One has to do a run-time check to discover the behavior of the\n** current process.\n**\n** SQLite used to support LinuxThreads.  But support for LinuxThreads\n** was dropped beginning with version 3.7.0.  SQLite will still work with\n** LinuxThreads provided that (1) there is no more than one connection \n** per database file in the same process and (2) database connections\n** do not move across threads.\n*/\n\n/*\n** An instance of the following structure serves as the key used\n** to locate a particular unixInodeInfo object.\n*/\nstruct unixFileId {\n  dev_t dev;                  /* Device number */\n#if OS_VXWORKS\n  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */\n#else\n  /* We are told that some versions of Android contain a bug that\n  ** sizes ino_t at only 32-bits instead of 64-bits. (See\n  ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)\n  ** To work around this, always allocate 64-bits for the inode number.  \n  ** On small machines that only have 32-bit inodes, this wastes 4 bytes,\n  ** but that should not be a big deal. */\n  /* WAS:  ino_t ino;   */\n  u64 ino;                   /* Inode number */\n#endif\n};\n\n/*\n** An instance of the following structure is allocated for each open\n** inode.\n**\n** A single inode can have multiple file descriptors, so each unixFile\n** structure contains a pointer to an instance of this object and this\n** object keeps a count of the number of unixFile pointing to it.\n**\n** Mutex rules:\n**\n**  (1) Only the pLockMutex mutex must be held in order to read or write\n**      any of the locking fields:\n**          nShared, nLock, eFileLock, bProcessLock, pUnused\n**\n**  (2) When nRef>0, then the following fields are unchanging and can\n**      be read (but not written) without holding any mutex:\n**          fileId, pLockMutex\n**\n**  (3) With the exceptions above, all the fields may only be read\n**      or written while holding the global unixBigLock mutex.\n**\n** Deadlock prevention:  The global unixBigLock mutex may not\n** be acquired while holding the pLockMutex mutex.  If both unixBigLock\n** and pLockMutex are needed, then unixBigLock must be acquired first.\n*/\nstruct unixInodeInfo {\n  struct unixFileId fileId;       /* The lookup key */\n  sqlite3_mutex *pLockMutex;      /* Hold this mutex for... */\n  int nShared;                      /* Number of SHARED locks held */\n  int nLock;                        /* Number of outstanding file locks */\n  unsigned char eFileLock;          /* One of SHARED_LOCK, RESERVED_LOCK etc. */\n  unsigned char bProcessLock;       /* An exclusive process lock is held */\n  UnixUnusedFd *pUnused;            /* Unused file descriptors to close */\n  int nRef;                       /* Number of pointers to this structure */\n  unixShmNode *pShmNode;          /* Shared memory associated with this inode */\n  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */\n  unixInodeInfo *pPrev;           /*    .... doubly linked */\n#if SQLITE_ENABLE_LOCKING_STYLE\n  unsigned long long sharedByte;  /* for AFP simulated shared lock */\n#endif\n#if OS_VXWORKS\n  sem_t *pSem;                    /* Named POSIX semaphore */\n  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */\n#endif\n};\n\n/*\n** A lists of all unixInodeInfo objects.\n**\n** Must hold unixBigLock in order to read or write this variable.\n*/\nstatic unixInodeInfo *inodeList = 0;  /* All unixInodeInfo objects */\n\n#ifdef SQLITE_DEBUG\n/*\n** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.\n** This routine is used only within assert() to help verify correct mutex\n** usage.\n*/\nint unixFileMutexHeld(unixFile *pFile){\n  assert( pFile->pInode );\n  return sqlite3_mutex_held(pFile->pInode->pLockMutex);\n}\nint unixFileMutexNotheld(unixFile *pFile){\n  assert( pFile->pInode );\n  return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);\n}\n#endif\n\n/*\n**\n** This function - unixLogErrorAtLine(), is only ever called via the macro\n** unixLogError().\n**\n** It is invoked after an error occurs in an OS function and errno has been\n** set. It logs a message using sqlite3_log() containing the current value of\n** errno and, if possible, the human-readable equivalent from strerror() or\n** strerror_r().\n**\n** The first argument passed to the macro should be the error code that\n** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). \n** The two subsequent arguments should be the name of the OS function that\n** failed (e.g. \"unlink\", \"open\") and the associated file-system path,\n** if any.\n*/\n#define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)\nstatic int unixLogErrorAtLine(\n  int errcode,                    /* SQLite error code */\n  const char *zFunc,              /* Name of OS function that failed */\n  const char *zPath,              /* File path associated with error */\n  int iLine                       /* Source line number where error occurred */\n){\n  char *zErr;                     /* Message from strerror() or equivalent */\n  int iErrno = errno;             /* Saved syscall error number */\n\n  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use\n  ** the strerror() function to obtain the human-readable error message\n  ** equivalent to errno. Otherwise, use strerror_r().\n  */ \n#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)\n  char aErr[80];\n  memset(aErr, 0, sizeof(aErr));\n  zErr = aErr;\n\n  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,\n  ** assume that the system provides the GNU version of strerror_r() that\n  ** returns a pointer to a buffer containing the error message. That pointer \n  ** may point to aErr[], or it may point to some static storage somewhere. \n  ** Otherwise, assume that the system provides the POSIX version of \n  ** strerror_r(), which always writes an error message into aErr[].\n  **\n  ** If the code incorrectly assumes that it is the POSIX version that is\n  ** available, the error message will often be an empty string. Not a\n  ** huge problem. Incorrectly concluding that the GNU version is available \n  ** could lead to a segfault though.\n  */\n#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)\n  zErr = \n# endif\n  strerror_r(iErrno, aErr, sizeof(aErr)-1);\n\n#elif SQLITE_THREADSAFE\n  /* This is a threadsafe build, but strerror_r() is not available. */\n  zErr = \"\";\n#else\n  /* Non-threadsafe build, use strerror(). */\n  zErr = strerror(iErrno);\n#endif\n\n  if( zPath==0 ) zPath = \"\";\n  sqlite3_log(errcode,\n      \"os_unix.c:%d: (%d) %s(%s) - %s\",\n      iLine, iErrno, zFunc, zPath, zErr\n  );\n\n  return errcode;\n}\n\n/*\n** Close a file descriptor.\n**\n** We assume that close() almost always works, since it is only in a\n** very sick application or on a very sick platform that it might fail.\n** If it does fail, simply leak the file descriptor, but do log the\n** error.\n**\n** Note that it is not safe to retry close() after EINTR since the\n** file descriptor might have already been reused by another thread.\n** So we don't even try to recover from an EINTR.  Just log the error\n** and move on.\n*/\nstatic void robust_close(unixFile *pFile, int h, int lineno){\n  if( osClose(h) ){\n    unixLogErrorAtLine(SQLITE_IOERR_CLOSE, \"close\",\n                       pFile ? pFile->zPath : 0, lineno);\n  }\n}\n\n/*\n** Set the pFile->lastErrno.  Do this in a subroutine as that provides\n** a convenient place to set a breakpoint.\n*/\nstatic void storeLastErrno(unixFile *pFile, int error){\n  pFile->lastErrno = error;\n}\n\n/*\n** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.\n*/ \nstatic void closePendingFds(unixFile *pFile){\n  unixInodeInfo *pInode = pFile->pInode;\n  UnixUnusedFd *p;\n  UnixUnusedFd *pNext;\n  assert( unixFileMutexHeld(pFile) );\n  for(p=pInode->pUnused; p; p=pNext){\n    pNext = p->pNext;\n    robust_close(pFile, p->fd, __LINE__);\n    sqlite3_free(p);\n  }\n  pInode->pUnused = 0;\n}\n\n/*\n** Release a unixInodeInfo structure previously allocated by findInodeInfo().\n**\n** The global mutex must be held when this routine is called, but the mutex\n** on the inode being deleted must NOT be held.\n*/\nstatic void releaseInodeInfo(unixFile *pFile){\n  unixInodeInfo *pInode = pFile->pInode;\n  assert( unixMutexHeld() );\n  assert( unixFileMutexNotheld(pFile) );\n  if( ALWAYS(pInode) ){\n    pInode->nRef--;\n    if( pInode->nRef==0 ){\n      assert( pInode->pShmNode==0 );\n      sqlite3_mutex_enter(pInode->pLockMutex);\n      closePendingFds(pFile);\n      sqlite3_mutex_leave(pInode->pLockMutex);\n      if( pInode->pPrev ){\n        assert( pInode->pPrev->pNext==pInode );\n        pInode->pPrev->pNext = pInode->pNext;\n      }else{\n        assert( inodeList==pInode );\n        inodeList = pInode->pNext;\n      }\n      if( pInode->pNext ){\n        assert( pInode->pNext->pPrev==pInode );\n        pInode->pNext->pPrev = pInode->pPrev;\n      }\n      sqlite3_mutex_free(pInode->pLockMutex);\n      sqlite3_free(pInode);\n    }\n  }\n}\n\n/*\n** Given a file descriptor, locate the unixInodeInfo object that\n** describes that file descriptor.  Create a new one if necessary.  The\n** return value might be uninitialized if an error occurs.\n**\n** The global mutex must held when calling this routine.\n**\n** Return an appropriate error code.\n*/\nstatic int findInodeInfo(\n  unixFile *pFile,               /* Unix file with file desc used in the key */\n  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */\n){\n  int rc;                        /* System call return code */\n  int fd;                        /* The file descriptor for pFile */\n  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */\n  struct stat statbuf;           /* Low-level file information */\n  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */\n\n  assert( unixMutexHeld() );\n\n  /* Get low-level information about the file that we can used to\n  ** create a unique name for the file.\n  */\n  fd = pFile->h;\n  rc = osFstat(fd, &statbuf);\n  if( rc!=0 ){\n    storeLastErrno(pFile, errno);\n#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)\n    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;\n#endif\n    return SQLITE_IOERR;\n  }\n\n#ifdef __APPLE__\n  /* On OS X on an msdos filesystem, the inode number is reported\n  ** incorrectly for zero-size files.  See ticket #3260.  To work\n  ** around this problem (we consider it a bug in OS X, not SQLite)\n  ** we always increase the file size to 1 by writing a single byte\n  ** prior to accessing the inode number.  The one byte written is\n  ** an ASCII 'S' character which also happens to be the first byte\n  ** in the header of every SQLite database.  In this way, if there\n  ** is a race condition such that another thread has already populated\n  ** the first page of the database, no damage is done.\n  */\n  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){\n    do{ rc = osWrite(fd, \"S\", 1); }while( rc<0 && errno==EINTR );\n    if( rc!=1 ){\n      storeLastErrno(pFile, errno);\n      return SQLITE_IOERR;\n    }\n    rc = osFstat(fd, &statbuf);\n    if( rc!=0 ){\n      storeLastErrno(pFile, errno);\n      return SQLITE_IOERR;\n    }\n  }\n#endif\n\n  memset(&fileId, 0, sizeof(fileId));\n  fileId.dev = statbuf.st_dev;\n#if OS_VXWORKS\n  fileId.pId = pFile->pId;\n#else\n  fileId.ino = (u64)statbuf.st_ino;\n#endif\n  assert( unixMutexHeld() );\n  pInode = inodeList;\n  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){\n    pInode = pInode->pNext;\n  }\n  if( pInode==0 ){\n    pInode = sqlite3_malloc64( sizeof(*pInode) );\n    if( pInode==0 ){\n      return SQLITE_NOMEM_BKPT;\n    }\n    memset(pInode, 0, sizeof(*pInode));\n    memcpy(&pInode->fileId, &fileId, sizeof(fileId));\n    if( sqlite3GlobalConfig.bCoreMutex ){\n      pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);\n      if( pInode->pLockMutex==0 ){\n        sqlite3_free(pInode);\n        return SQLITE_NOMEM_BKPT;\n      }\n    }\n    pInode->nRef = 1;\n    assert( unixMutexHeld() );\n    pInode->pNext = inodeList;\n    pInode->pPrev = 0;\n    if( inodeList ) inodeList->pPrev = pInode;\n    inodeList = pInode;\n  }else{\n    pInode->nRef++;\n  }\n  *ppInode = pInode;\n  return SQLITE_OK;\n}\n\n/*\n** Return TRUE if pFile has been renamed or unlinked since it was first opened.\n*/\nstatic int fileHasMoved(unixFile *pFile){\n#if OS_VXWORKS\n  return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;\n#else\n  struct stat buf;\n  return pFile->pInode!=0 &&\n      (osStat(pFile->zPath, &buf)!=0 \n         || (u64)buf.st_ino!=pFile->pInode->fileId.ino);\n#endif\n}\n\n\n/*\n** Check a unixFile that is a database.  Verify the following:\n**\n** (1) There is exactly one hard link on the file\n** (2) The file is not a symbolic link\n** (3) The file has not been renamed or unlinked\n**\n** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.\n*/\nstatic void verifyDbFile(unixFile *pFile){\n  struct stat buf;\n  int rc;\n\n  /* These verifications occurs for the main database only */\n  if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;\n\n  rc = osFstat(pFile->h, &buf);\n  if( rc!=0 ){\n    sqlite3_log(SQLITE_WARNING, \"cannot fstat db file %s\", pFile->zPath);\n    return;\n  }\n  if( buf.st_nlink==0 ){\n    sqlite3_log(SQLITE_WARNING, \"file unlinked while open: %s\", pFile->zPath);\n    return;\n  }\n  if( buf.st_nlink>1 ){\n    sqlite3_log(SQLITE_WARNING, \"multiple links to file: %s\", pFile->zPath);\n    return;\n  }\n  if( fileHasMoved(pFile) ){\n    sqlite3_log(SQLITE_WARNING, \"file renamed while open: %s\", pFile->zPath);\n    return;\n  }\n}\n\n\n/*\n** This routine checks if there is a RESERVED lock held on the specified\n** file by this or any other process. If such a lock is held, set *pResOut\n** to a non-zero value otherwise *pResOut is set to zero.  The return value\n** is set to SQLITE_OK unless an I/O error occurs during lock checking.\n*/\nstatic int unixCheckReservedLock(sqlite3_file *id, int *pResOut){\n  int rc = SQLITE_OK;\n  int reserved = 0;\n  unixFile *pFile = (unixFile*)id;\n\n  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );\n\n  assert( pFile );\n  assert( pFile->eFileLock<=SHARED_LOCK );\n  sqlite3_mutex_enter(pFile->pInode->pLockMutex);\n\n  /* Check if a thread in this process holds such a lock */\n  if( pFile->pInode->eFileLock>SHARED_LOCK ){\n    reserved = 1;\n  }\n\n  /* Otherwise see if some other process holds it.\n  */\n#ifndef __DJGPP__\n  if( !reserved && !pFile->pInode->bProcessLock ){\n    struct flock lock;\n    lock.l_whence = SEEK_SET;\n    lock.l_start = RESERVED_BYTE;\n    lock.l_len = 1;\n    lock.l_type = F_WRLCK;\n    if( osFcntl(pFile->h, F_GETLK, &lock) ){\n      rc = SQLITE_IOERR_CHECKRESERVEDLOCK;\n      storeLastErrno(pFile, errno);\n    } else if( lock.l_type!=F_UNLCK ){\n      reserved = 1;\n    }\n  }\n#endif\n  \n  sqlite3_mutex_leave(pFile->pInode->pLockMutex);\n  OSTRACE((\"TEST WR-LOCK %d %d %d (unix)\\n\", pFile->h, rc, reserved));\n\n  *pResOut = reserved;\n  return rc;\n}\n\n/*\n** Set a posix-advisory-lock.\n**\n** There are two versions of this routine.  If compiled with\n** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter\n** which is a pointer to a unixFile.  If the unixFile->iBusyTimeout\n** value is set, then it is the number of milliseconds to wait before\n** failing the lock.  The iBusyTimeout value is always reset back to\n** zero on each call.\n**\n** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking\n** attempt to set the lock.\n*/\n#ifndef SQLITE_ENABLE_SETLK_TIMEOUT\n# define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)\n#else\nstatic int osSetPosixAdvisoryLock(\n  int h,                /* The file descriptor on which to take the lock */\n  struct flock *pLock,  /* The description of the lock */\n  unixFile *pFile       /* Structure holding timeout value */\n){\n  int tm = pFile->iBusyTimeout;\n  int rc = osFcntl(h,F_SETLK,pLock);\n  while( rc<0 && tm>0 ){\n    /* On systems that support some kind of blocking file lock with a timeout,\n    ** make appropriate changes here to invoke that blocking file lock.  On\n    ** generic posix, however, there is no such API.  So we simply try the\n    ** lock once every millisecond until either the timeout expires, or until\n    ** the lock is obtained. */\n    usleep(1000);\n    rc = osFcntl(h,F_SETLK,pLock);\n    tm--;\n  }\n  return rc;\n}\n#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */\n\n\n/*\n** Attempt to set a system-lock on the file pFile.  The lock is \n** described by pLock.\n**\n** If the pFile was opened read/write from unix-excl, then the only lock\n** ever obtained is an exclusive lock, and it is obtained exactly once\n** the first time any lock is attempted.  All subsequent system locking\n** operations become no-ops.  Locking operations still happen internally,\n** in order to coordinate access between separate database connections\n** within this process, but all of that is handled in memory and the\n** operating system does not participate.\n**\n** This function is a pass-through to fcntl(F_SETLK) if pFile is using\n** any VFS other than \"unix-excl\" or if pFile is opened on \"unix-excl\"\n** and is read-only.\n**\n** Zero is returned if the call completes successfully, or -1 if a call\n** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).\n*/\nstatic int unixFileLock(unixFile *pFile, struct flock *pLock){\n  int rc;\n  unixInodeInfo *pInode = pFile->pInode;\n  assert( pInode!=0 );\n  assert( sqlite3_mutex_held(pInode->pLockMutex) );\n  if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){\n    if( pInode->bProcessLock==0 ){\n      struct flock lock;\n      assert( pInode->nLock==0 );\n      lock.l_whence = SEEK_SET;\n      lock.l_start = SHARED_FIRST;\n      lock.l_len = SHARED_SIZE;\n      lock.l_type = F_WRLCK;\n      rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);\n      if( rc<0 ) return rc;\n      pInode->bProcessLock = 1;\n      pInode->nLock++;\n    }else{\n      rc = 0;\n    }\n  }else{\n    rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);\n  }\n  return rc;\n}\n\n/*\n** Lock the file with the lock specified by parameter eFileLock - one\n** of the following:\n**\n**     (1) SHARED_LOCK\n**     (2) RESERVED_LOCK\n**     (3) PENDING_LOCK\n**     (4) EXCLUSIVE_LOCK\n**\n** Sometimes when requesting one lock state, additional lock states\n** are inserted in between.  The locking might fail on one of the later\n** transitions leaving the lock state different from what it started but\n** still short of its goal.  The following chart shows the allowed\n** transitions and the inserted intermediate states:\n**\n**    UNLOCKED -> SHARED\n**    SHARED -> RESERVED\n**    SHARED -> (PENDING) -> EXCLUSIVE\n**    RESERVED -> (PENDING) -> EXCLUSIVE\n**    PENDING -> EXCLUSIVE\n**\n** This routine will only increase a lock.  Use the sqlite3OsUnlock()\n** routine to lower a locking level.\n*/\nstatic int unixLock(sqlite3_file *id, int eFileLock){\n  /* The following describes the implementation of the various locks and\n  ** lock transitions in terms of the POSIX advisory shared and exclusive\n  ** lock primitives (called read-locks and write-locks below, to avoid\n  ** confusion with SQLite lock names). The algorithms are complicated\n  ** slightly in order to be compatible with Windows95 systems simultaneously\n  ** accessing the same database file, in case that is ever required.\n  **\n  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved\n  ** byte', each single bytes at well known offsets, and the 'shared byte\n  ** range', a range of 510 bytes at a well known offset.\n  **\n  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending\n  ** byte'.  If this is successful, 'shared byte range' is read-locked\n  ** and the lock on the 'pending byte' released.  (Legacy note:  When\n  ** SQLite was first developed, Windows95 systems were still very common,\n  ** and Widnows95 lacks a shared-lock capability.  So on Windows95, a\n  ** single randomly selected by from the 'shared byte range' is locked.\n  ** Windows95 is now pretty much extinct, but this work-around for the\n  ** lack of shared-locks on Windows95 lives on, for backwards\n  ** compatibility.)\n  **\n  ** A process may only obtain a RESERVED lock after it has a SHARED lock.\n  ** A RESERVED lock is implemented by grabbing a write-lock on the\n  ** 'reserved byte'. \n  **\n  ** A process may only obtain a PENDING lock after it has obtained a\n  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock\n  ** on the 'pending byte'. This ensures that no new SHARED locks can be\n  ** obtained, but existing SHARED locks are allowed to persist. A process\n  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.\n  ** This property is used by the algorithm for rolling back a journal file\n  ** after a crash.\n  **\n  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is\n  ** implemented by obtaining a write-lock on the entire 'shared byte\n  ** range'. Since all other locks require a read-lock on one of the bytes\n  ** within this range, this ensures that no other locks are held on the\n  ** database. \n  */\n  int rc = SQLITE_OK;\n  unixFile *pFile = (unixFile*)id;\n  unixInodeInfo *pInode;\n  struct flock lock;\n  int tErrno = 0;\n\n  assert( pFile );\n  OSTRACE((\"LOCK    %d %s was %s(%s,%d) pid=%d (unix)\\n\", pFile->h,\n      azFileLock(eFileLock), azFileLock(pFile->eFileLock),\n      azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,\n      osGetpid(0)));\n\n  /* If there is already a lock of this type or more restrictive on the\n  ** unixFile, do nothing. Don't use the end_lock: exit path, as\n  ** unixEnterMutex() hasn't been called yet.\n  */\n  if( pFile->eFileLock>=eFileLock ){\n    OSTRACE((\"LOCK    %d %s ok (already held) (unix)\\n\", pFile->h,\n            azFileLock(eFileLock)));\n    return SQLITE_OK;\n  }\n\n  /* Make sure the locking sequence is correct.\n  **  (1) We never move from unlocked to anything higher than shared lock.\n  **  (2) SQLite never explicitly requests a pendig lock.\n  **  (3) A shared lock is always held when a reserve lock is requested.\n  */\n  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );\n  assert( eFileLock!=PENDING_LOCK );\n  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );\n\n  /* This mutex is needed because pFile->pInode is shared across threads\n  */\n  pInode = pFile->pInode;\n  sqlite3_mutex_enter(pInode->pLockMutex);\n\n  /* If some thread using this PID has a lock via a different unixFile*\n  ** handle that precludes the requested lock, return BUSY.\n  */\n  if( (pFile->eFileLock!=pInode->eFileLock && \n          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))\n  ){\n    rc = SQLITE_BUSY;\n    goto end_lock;\n  }\n\n  /* If a SHARED lock is requested, and some thread using this PID already\n  ** has a SHARED or RESERVED lock, then increment reference counts and\n  ** return SQLITE_OK.\n  */\n  if( eFileLock==SHARED_LOCK && \n      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){\n    assert( eFileLock==SHARED_LOCK );\n    assert( pFile->eFileLock==0 );\n    assert( pInode->nShared>0 );\n    pFile->eFileLock = SHARED_LOCK;\n    pInode->nShared++;\n    pInode->nLock++;\n    goto end_lock;\n  }\n\n\n  /* A PENDING lock is needed before acquiring a SHARED lock and before\n  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will\n  ** be released.\n  */\n  lock.l_len = 1L;\n  lock.l_whence = SEEK_SET;\n  if( eFileLock==SHARED_LOCK \n      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)\n  ){\n    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);\n    lock.l_start = PENDING_BYTE;\n    if( unixFileLock(pFile, &lock) ){\n      tErrno = errno;\n      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);\n      if( rc!=SQLITE_BUSY ){\n        storeLastErrno(pFile, tErrno);\n      }\n      goto end_lock;\n    }\n  }\n\n\n  /* If control gets to this point, then actually go ahead and make\n  ** operating system calls for the specified lock.\n  */\n  if( eFileLock==SHARED_LOCK ){\n    assert( pInode->nShared==0 );\n    assert( pInode->eFileLock==0 );\n    assert( rc==SQLITE_OK );\n\n    /* Now get the read-lock */\n    lock.l_start = SHARED_FIRST;\n    lock.l_len = SHARED_SIZE;\n    if( unixFileLock(pFile, &lock) ){\n      tErrno = errno;\n      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);\n    }\n\n    /* Drop the temporary PENDING lock */\n    lock.l_start = PENDING_BYTE;\n    lock.l_len = 1L;\n    lock.l_type = F_UNLCK;\n    if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){\n      /* This could happen with a network mount */\n      tErrno = errno;\n      rc = SQLITE_IOERR_UNLOCK; \n    }\n\n    if( rc ){\n      if( rc!=SQLITE_BUSY ){\n        storeLastErrno(pFile, tErrno);\n      }\n      goto end_lock;\n    }else{\n      pFile->eFileLock = SHARED_LOCK;\n      pInode->nLock++;\n      pInode->nShared = 1;\n    }\n  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){\n    /* We are trying for an exclusive lock but another thread in this\n    ** same process is still holding a shared lock. */\n    rc = SQLITE_BUSY;\n  }else{\n    /* The request was for a RESERVED or EXCLUSIVE lock.  It is\n    ** assumed that there is a SHARED or greater lock on the file\n    ** already.\n    */\n    assert( 0!=pFile->eFileLock );\n    lock.l_type = F_WRLCK;\n\n    assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );\n    if( eFileLock==RESERVED_LOCK ){\n      lock.l_start = RESERVED_BYTE;\n      lock.l_len = 1L;\n    }else{\n      lock.l_start = SHARED_FIRST;\n      lock.l_len = SHARED_SIZE;\n    }\n\n    if( unixFileLock(pFile, &lock) ){\n      tErrno = errno;\n      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);\n      if( rc!=SQLITE_BUSY ){\n        storeLastErrno(pFile, tErrno);\n      }\n    }\n  }\n  \n\n#ifdef SQLITE_DEBUG\n  /* Set up the transaction-counter change checking flags when\n  ** transitioning from a SHARED to a RESERVED lock.  The change\n  ** from SHARED to RESERVED marks the beginning of a normal\n  ** write operation (not a hot journal rollback).\n  */\n  if( rc==SQLITE_OK\n   && pFile->eFileLock<=SHARED_LOCK\n   && eFileLock==RESERVED_LOCK\n  ){\n    pFile->transCntrChng = 0;\n    pFile->dbUpdate = 0;\n    pFile->inNormalWrite = 1;\n  }\n#endif\n\n\n  if( rc==SQLITE_OK ){\n    pFile->eFileLock = eFileLock;\n    pInode->eFileLock = eFileLock;\n  }else if( eFileLock==EXCLUSIVE_LOCK ){\n    pFile->eFileLock = PENDING_LOCK;\n    pInode->eFileLock = PENDING_LOCK;\n  }\n\nend_lock:\n  sqlite3_mutex_leave(pInode->pLockMutex);\n  OSTRACE((\"LOCK    %d %s %s (unix)\\n\", pFile->h, azFileLock(eFileLock), \n      rc==SQLITE_OK ? \"ok\" : \"failed\"));\n  return rc;\n}\n\n/*\n** Add the file descriptor used by file handle pFile to the corresponding\n** pUnused list.\n*/\nstatic void setPendingFd(unixFile *pFile){\n  unixInodeInfo *pInode = pFile->pInode;\n  UnixUnusedFd *p = pFile->pPreallocatedUnused;\n  assert( unixFileMutexHeld(pFile) );\n  p->pNext = pInode->pUnused;\n  pInode->pUnused = p;\n  pFile->h = -1;\n  pFile->pPreallocatedUnused = 0;\n}\n\n/*\n** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock\n** must be either NO_LOCK or SHARED_LOCK.\n**\n** If the locking level of the file descriptor is already at or below\n** the requested locking level, this routine is a no-op.\n** \n** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED\n** the byte range is divided into 2 parts and the first part is unlocked then\n** set to a read lock, then the other part is simply unlocked.  This works \n** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to \n** remove the write lock on a region when a read lock is set.\n*/\nstatic int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){\n  unixFile *pFile = (unixFile*)id;\n  unixInodeInfo *pInode;\n  struct flock lock;\n  int rc = SQLITE_OK;\n\n  assert( pFile );\n  OSTRACE((\"UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\\n\", pFile->h, eFileLock,\n      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,\n      osGetpid(0)));\n\n  assert( eFileLock<=SHARED_LOCK );\n  if( pFile->eFileLock<=eFileLock ){\n    return SQLITE_OK;\n  }\n  pInode = pFile->pInode;\n  sqlite3_mutex_enter(pInode->pLockMutex);\n  assert( pInode->nShared!=0 );\n  if( pFile->eFileLock>SHARED_LOCK ){\n    assert( pInode->eFileLock==pFile->eFileLock );\n\n#ifdef SQLITE_DEBUG\n    /* When reducing a lock such that other processes can start\n    ** reading the database file again, make sure that the\n    ** transaction counter was updated if any part of the database\n    ** file changed.  If the transaction counter is not updated,\n    ** other connections to the same file might not realize that\n    ** the file has changed and hence might not know to flush their\n    ** cache.  The use of a stale cache can lead to database corruption.\n    */\n    pFile->inNormalWrite = 0;\n#endif\n\n    /* downgrading to a shared lock on NFS involves clearing the write lock\n    ** before establishing the readlock - to avoid a race condition we downgrade\n    ** the lock in 2 blocks, so that part of the range will be covered by a \n    ** write lock until the rest is covered by a read lock:\n    **  1:   [WWWWW]\n    **  2:   [....W]\n    **  3:   [RRRRW]\n    **  4:   [RRRR.]\n    */\n    if( eFileLock==SHARED_LOCK ){\n#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE\n      (void)handleNFSUnlock;\n      assert( handleNFSUnlock==0 );\n#endif\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\n      if( handleNFSUnlock ){\n        int tErrno;               /* Error code from system call errors */\n        off_t divSize = SHARED_SIZE - 1;\n        \n        lock.l_type = F_UNLCK;\n        lock.l_whence = SEEK_SET;\n        lock.l_start = SHARED_FIRST;\n        lock.l_len = divSize;\n        if( unixFileLock(pFile, &lock)==(-1) ){\n          tErrno = errno;\n          rc = SQLITE_IOERR_UNLOCK;\n          storeLastErrno(pFile, tErrno);\n          goto end_unlock;\n        }\n        lock.l_type = F_RDLCK;\n        lock.l_whence = SEEK_SET;\n        lock.l_start = SHARED_FIRST;\n        lock.l_len = divSize;\n        if( unixFileLock(pFile, &lock)==(-1) ){\n          tErrno = errno;\n          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);\n          if( IS_LOCK_ERROR(rc) ){\n            storeLastErrno(pFile, tErrno);\n          }\n          goto end_unlock;\n        }\n        lock.l_type = F_UNLCK;\n        lock.l_whence = SEEK_SET;\n        lock.l_start = SHARED_FIRST+divSize;\n        lock.l_len = SHARED_SIZE-divSize;\n        if( unixFileLock(pFile, &lock)==(-1) ){\n          tErrno = errno;\n          rc = SQLITE_IOERR_UNLOCK;\n          storeLastErrno(pFile, tErrno);\n          goto end_unlock;\n        }\n      }else\n#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */\n      {\n        lock.l_type = F_RDLCK;\n        lock.l_whence = SEEK_SET;\n        lock.l_start = SHARED_FIRST;\n        lock.l_len = SHARED_SIZE;\n        if( unixFileLock(pFile, &lock) ){\n          /* In theory, the call to unixFileLock() cannot fail because another\n          ** process is holding an incompatible lock. If it does, this \n          ** indicates that the other process is not following the locking\n          ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning\n          ** SQLITE_BUSY would confuse the upper layer (in practice it causes \n          ** an assert to fail). */ \n          rc = SQLITE_IOERR_RDLOCK;\n          storeLastErrno(pFile, errno);\n          goto end_unlock;\n        }\n      }\n    }\n    lock.l_type = F_UNLCK;\n    lock.l_whence = SEEK_SET;\n    lock.l_start = PENDING_BYTE;\n    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );\n    if( unixFileLock(pFile, &lock)==0 ){\n      pInode->eFileLock = SHARED_LOCK;\n    }else{\n      rc = SQLITE_IOERR_UNLOCK;\n      storeLastErrno(pFile, errno);\n      goto end_unlock;\n    }\n  }\n  if( eFileLock==NO_LOCK ){\n    /* Decrement the shared lock counter.  Release the lock using an\n    ** OS call only when all threads in this same process have released\n    ** the lock.\n    */\n    pInode->nShared--;\n    if( pInode->nShared==0 ){\n      lock.l_type = F_UNLCK;\n      lock.l_whence = SEEK_SET;\n      lock.l_start = lock.l_len = 0L;\n      if( unixFileLock(pFile, &lock)==0 ){\n        pInode->eFileLock = NO_LOCK;\n      }else{\n        rc = SQLITE_IOERR_UNLOCK;\n        storeLastErrno(pFile, errno);\n        pInode->eFileLock = NO_LOCK;\n        pFile->eFileLock = NO_LOCK;\n      }\n    }\n\n    /* Decrement the count of locks against this same file.  When the\n    ** count reaches zero, close any other file descriptors whose close\n    ** was deferred because of outstanding locks.\n    */\n    pInode->nLock--;\n    assert( pInode->nLock>=0 );\n    if( pInode->nLock==0 ) closePendingFds(pFile);\n  }\n\nend_unlock:\n  sqlite3_mutex_leave(pInode->pLockMutex);\n  if( rc==SQLITE_OK ){\n    pFile->eFileLock = eFileLock;\n  }\n  return rc;\n}\n\n/*\n** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock\n** must be either NO_LOCK or SHARED_LOCK.\n**\n** If the locking level of the file descriptor is already at or below\n** the requested locking level, this routine is a no-op.\n*/\nstatic int unixUnlock(sqlite3_file *id, int eFileLock){\n#if SQLITE_MAX_MMAP_SIZE>0\n  assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );\n#endif\n  return posixUnlock(id, eFileLock, 0);\n}\n\n#if SQLITE_MAX_MMAP_SIZE>0\nstatic int unixMapfile(unixFile *pFd, i64 nByte);\nstatic void unixUnmapfile(unixFile *pFd);\n#endif\n\n/*\n** This function performs the parts of the \"close file\" operation \n** common to all locking schemes. It closes the directory and file\n** handles, if they are valid, and sets all fields of the unixFile\n** structure to 0.\n**\n** It is *not* necessary to hold the mutex when this routine is called,\n** even on VxWorks.  A mutex will be acquired on VxWorks by the\n** vxworksReleaseFileId() routine.\n*/\nstatic int closeUnixFile(sqlite3_file *id){\n  unixFile *pFile = (unixFile*)id;\n#if SQLITE_MAX_MMAP_SIZE>0\n  unixUnmapfile(pFile);\n#endif\n  if( pFile->h>=0 ){\n    robust_close(pFile, pFile->h, __LINE__);\n    pFile->h = -1;\n  }\n#if OS_VXWORKS\n  if( pFile->pId ){\n    if( pFile->ctrlFlags & UNIXFILE_DELETE ){\n      osUnlink(pFile->pId->zCanonicalName);\n    }\n    vxworksReleaseFileId(pFile->pId);\n    pFile->pId = 0;\n  }\n#endif\n#ifdef SQLITE_UNLINK_AFTER_CLOSE\n  if( pFile->ctrlFlags & UNIXFILE_DELETE ){\n    osUnlink(pFile->zPath);\n    sqlite3_free(*(char**)&pFile->zPath);\n    pFile->zPath = 0;\n  }\n#endif\n  OSTRACE((\"CLOSE   %-3d\\n\", pFile->h));\n  OpenCounter(-1);\n  sqlite3_free(pFile->pPreallocatedUnused);\n  memset(pFile, 0, sizeof(unixFile));\n  return SQLITE_OK;\n}\n\n/*\n** Close a file.\n*/\nstatic int unixClose(sqlite3_file *id){\n  int rc = SQLITE_OK;\n  unixFile *pFile = (unixFile *)id;\n  unixInodeInfo *pInode = pFile->pInode;\n\n  assert( pInode!=0 );\n  verifyDbFile(pFile);\n  unixUnlock(id, NO_LOCK);\n  assert( unixFileMutexNotheld(pFile) );\n  unixEnterMutex();\n\n  /* unixFile.pInode is always valid here. Otherwise, a different close\n  ** routine (e.g. nolockClose()) would be called instead.\n  */\n  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );\n  sqlite3_mutex_enter(pInode->pLockMutex);\n  if( pInode->nLock ){\n    /* If there are outstanding locks, do not actually close the file just\n    ** yet because that would clear those locks.  Instead, add the file\n    ** descriptor to pInode->pUnused list.  It will be automatically closed \n    ** when the last lock is cleared.\n    */\n    setPendingFd(pFile);\n  }\n  sqlite3_mutex_leave(pInode->pLockMutex);\n  releaseInodeInfo(pFile);\n  rc = closeUnixFile(id);\n  unixLeaveMutex();\n  return rc;\n}\n\n/************** End of the posix advisory lock implementation *****************\n******************************************************************************/\n\n/******************************************************************************\n****************************** No-op Locking **********************************\n**\n** Of the various locking implementations available, this is by far the\n** simplest:  locking is ignored.  No attempt is made to lock the database\n** file for reading or writing.\n**\n** This locking mode is appropriate for use on read-only databases\n** (ex: databases that are burned into CD-ROM, for example.)  It can\n** also be used if the application employs some external mechanism to\n** prevent simultaneous access of the same database by two or more\n** database connections.  But there is a serious risk of database\n** corruption if this locking mode is used in situations where multiple\n** database connections are accessing the same database file at the same\n** time and one or more of those connections are writing.\n*/\n\nstatic int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){\n  UNUSED_PARAMETER(NotUsed);\n  *pResOut = 0;\n  return SQLITE_OK;\n}\nstatic int nolockLock(sqlite3_file *NotUsed, int NotUsed2){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  return SQLITE_OK;\n}\nstatic int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  return SQLITE_OK;\n}\n\n/*\n** Close the file.\n*/\nstatic int nolockClose(sqlite3_file *id) {\n  return closeUnixFile(id);\n}\n\n/******************* End of the no-op lock implementation *********************\n******************************************************************************/\n\n/******************************************************************************\n************************* Begin dot-file Locking ******************************\n**\n** The dotfile locking implementation uses the existence of separate lock\n** files (really a directory) to control access to the database.  This works\n** on just about every filesystem imaginable.  But there are serious downsides:\n**\n**    (1)  There is zero concurrency.  A single reader blocks all other\n**         connections from reading or writing the database.\n**\n**    (2)  An application crash or power loss can leave stale lock files\n**         sitting around that need to be cleared manually.\n**\n** Nevertheless, a dotlock is an appropriate locking mode for use if no\n** other locking strategy is available.\n**\n** Dotfile locking works by creating a subdirectory in the same directory as\n** the database and with the same name but with a \".lock\" extension added.\n** The existence of a lock directory implies an EXCLUSIVE lock.  All other\n** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.\n*/\n\n/*\n** The file suffix added to the data base filename in order to create the\n** lock directory.\n*/\n#define DOTLOCK_SUFFIX \".lock\"\n\n/*\n** This routine checks if there is a RESERVED lock held on the specified\n** file by this or any other process. If such a lock is held, set *pResOut\n** to a non-zero value otherwise *pResOut is set to zero.  The return value\n** is set to SQLITE_OK unless an I/O error occurs during lock checking.\n**\n** In dotfile locking, either a lock exists or it does not.  So in this\n** variation of CheckReservedLock(), *pResOut is set to true if any lock\n** is held on the file and false if the file is unlocked.\n*/\nstatic int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {\n  int rc = SQLITE_OK;\n  int reserved = 0;\n  unixFile *pFile = (unixFile*)id;\n\n  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );\n  \n  assert( pFile );\n  reserved = osAccess((const char*)pFile->lockingContext, 0)==0;\n  OSTRACE((\"TEST WR-LOCK %d %d %d (dotlock)\\n\", pFile->h, rc, reserved));\n  *pResOut = reserved;\n  return rc;\n}\n\n/*\n** Lock the file with the lock specified by parameter eFileLock - one\n** of the following:\n**\n**     (1) SHARED_LOCK\n**     (2) RESERVED_LOCK\n**     (3) PENDING_LOCK\n**     (4) EXCLUSIVE_LOCK\n**\n** Sometimes when requesting one lock state, additional lock states\n** are inserted in between.  The locking might fail on one of the later\n** transitions leaving the lock state different from what it started but\n** still short of its goal.  The following chart shows the allowed\n** transitions and the inserted intermediate states:\n**\n**    UNLOCKED -> SHARED\n**    SHARED -> RESERVED\n**    SHARED -> (PENDING) -> EXCLUSIVE\n**    RESERVED -> (PENDING) -> EXCLUSIVE\n**    PENDING -> EXCLUSIVE\n**\n** This routine will only increase a lock.  Use the sqlite3OsUnlock()\n** routine to lower a locking level.\n**\n** With dotfile locking, we really only support state (4): EXCLUSIVE.\n** But we track the other locking levels internally.\n*/\nstatic int dotlockLock(sqlite3_file *id, int eFileLock) {\n  unixFile *pFile = (unixFile*)id;\n  char *zLockFile = (char *)pFile->lockingContext;\n  int rc = SQLITE_OK;\n\n\n  /* If we have any lock, then the lock file already exists.  All we have\n  ** to do is adjust our internal record of the lock level.\n  */\n  if( pFile->eFileLock > NO_LOCK ){\n    pFile->eFileLock = eFileLock;\n    /* Always update the timestamp on the old file */\n#ifdef HAVE_UTIME\n    utime(zLockFile, NULL);\n#else\n    utimes(zLockFile, NULL);\n#endif\n    return SQLITE_OK;\n  }\n  \n  /* grab an exclusive lock */\n  rc = osMkdir(zLockFile, 0777);\n  if( rc<0 ){\n    /* failed to open/create the lock directory */\n    int tErrno = errno;\n    if( EEXIST == tErrno ){\n      rc = SQLITE_BUSY;\n    } else {\n      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);\n      if( rc!=SQLITE_BUSY ){\n        storeLastErrno(pFile, tErrno);\n      }\n    }\n    return rc;\n  } \n  \n  /* got it, set the type and return ok */\n  pFile->eFileLock = eFileLock;\n  return rc;\n}\n\n/*\n** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock\n** must be either NO_LOCK or SHARED_LOCK.\n**\n** If the locking level of the file descriptor is already at or below\n** the requested locking level, this routine is a no-op.\n**\n** When the locking level reaches NO_LOCK, delete the lock file.\n*/\nstatic int dotlockUnlock(sqlite3_file *id, int eFileLock) {\n  unixFile *pFile = (unixFile*)id;\n  char *zLockFile = (char *)pFile->lockingContext;\n  int rc;\n\n  assert( pFile );\n  OSTRACE((\"UNLOCK  %d %d was %d pid=%d (dotlock)\\n\", pFile->h, eFileLock,\n           pFile->eFileLock, osGetpid(0)));\n  assert( eFileLock<=SHARED_LOCK );\n  \n  /* no-op if possible */\n  if( pFile->eFileLock==eFileLock ){\n    return SQLITE_OK;\n  }\n\n  /* To downgrade to shared, simply update our internal notion of the\n  ** lock state.  No need to mess with the file on disk.\n  */\n  if( eFileLock==SHARED_LOCK ){\n    pFile->eFileLock = SHARED_LOCK;\n    return SQLITE_OK;\n  }\n  \n  /* To fully unlock the database, delete the lock file */\n  assert( eFileLock==NO_LOCK );\n  rc = osRmdir(zLockFile);\n  if( rc<0 ){\n    int tErrno = errno;\n    if( tErrno==ENOENT ){\n      rc = SQLITE_OK;\n    }else{\n      rc = SQLITE_IOERR_UNLOCK;\n      storeLastErrno(pFile, tErrno);\n    }\n    return rc; \n  }\n  pFile->eFileLock = NO_LOCK;\n  return SQLITE_OK;\n}\n\n/*\n** Close a file.  Make sure the lock has been released before closing.\n*/\nstatic int dotlockClose(sqlite3_file *id) {\n  unixFile *pFile = (unixFile*)id;\n  assert( id!=0 );\n  dotlockUnlock(id, NO_LOCK);\n  sqlite3_free(pFile->lockingContext);\n  return closeUnixFile(id);\n}\n/****************** End of the dot-file lock implementation *******************\n******************************************************************************/\n\n/******************************************************************************\n************************** Begin flock Locking ********************************\n**\n** Use the flock() system call to do file locking.\n**\n** flock() locking is like dot-file locking in that the various\n** fine-grain locking levels supported by SQLite are collapsed into\n** a single exclusive lock.  In other words, SHARED, RESERVED, and\n** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite\n** still works when you do this, but concurrency is reduced since\n** only a single process can be reading the database at a time.\n**\n** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off\n*/\n#if SQLITE_ENABLE_LOCKING_STYLE\n\n/*\n** Retry flock() calls that fail with EINTR\n*/\n#ifdef EINTR\nstatic int robust_flock(int fd, int op){\n  int rc;\n  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );\n  return rc;\n}\n#else\n# define robust_flock(a,b) flock(a,b)\n#endif\n     \n\n/*\n** This routine checks if there is a RESERVED lock held on the specified\n** file by this or any other process. If such a lock is held, set *pResOut\n** to a non-zero value otherwise *pResOut is set to zero.  The return value\n** is set to SQLITE_OK unless an I/O error occurs during lock checking.\n*/\nstatic int flockCheckReservedLock(sqlite3_file *id, int *pResOut){\n  int rc = SQLITE_OK;\n  int reserved = 0;\n  unixFile *pFile = (unixFile*)id;\n  \n  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );\n  \n  assert( pFile );\n  \n  /* Check if a thread in this process holds such a lock */\n  if( pFile->eFileLock>SHARED_LOCK ){\n    reserved = 1;\n  }\n  \n  /* Otherwise see if some other process holds it. */\n  if( !reserved ){\n    /* attempt to get the lock */\n    int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);\n    if( !lrc ){\n      /* got the lock, unlock it */\n      lrc = robust_flock(pFile->h, LOCK_UN);\n      if ( lrc ) {\n        int tErrno = errno;\n        /* unlock failed with an error */\n        lrc = SQLITE_IOERR_UNLOCK; \n        storeLastErrno(pFile, tErrno);\n        rc = lrc;\n      }\n    } else {\n      int tErrno = errno;\n      reserved = 1;\n      /* someone else might have it reserved */\n      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); \n      if( IS_LOCK_ERROR(lrc) ){\n        storeLastErrno(pFile, tErrno);\n        rc = lrc;\n      }\n    }\n  }\n  OSTRACE((\"TEST WR-LOCK %d %d %d (flock)\\n\", pFile->h, rc, reserved));\n\n#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS\n  if( (rc & 0xff) == SQLITE_IOERR ){\n    rc = SQLITE_OK;\n    reserved=1;\n  }\n#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */\n  *pResOut = reserved;\n  return rc;\n}\n\n/*\n** Lock the file with the lock specified by parameter eFileLock - one\n** of the following:\n**\n**     (1) SHARED_LOCK\n**     (2) RESERVED_LOCK\n**     (3) PENDING_LOCK\n**     (4) EXCLUSIVE_LOCK\n**\n** Sometimes when requesting one lock state, additional lock states\n** are inserted in between.  The locking might fail on one of the later\n** transitions leaving the lock state different from what it started but\n** still short of its goal.  The following chart shows the allowed\n** transitions and the inserted intermediate states:\n**\n**    UNLOCKED -> SHARED\n**    SHARED -> RESERVED\n**    SHARED -> (PENDING) -> EXCLUSIVE\n**    RESERVED -> (PENDING) -> EXCLUSIVE\n**    PENDING -> EXCLUSIVE\n**\n** flock() only really support EXCLUSIVE locks.  We track intermediate\n** lock states in the sqlite3_file structure, but all locks SHARED or\n** above are really EXCLUSIVE locks and exclude all other processes from\n** access the file.\n**\n** This routine will only increase a lock.  Use the sqlite3OsUnlock()\n** routine to lower a locking level.\n*/\nstatic int flockLock(sqlite3_file *id, int eFileLock) {\n  int rc = SQLITE_OK;\n  unixFile *pFile = (unixFile*)id;\n\n  assert( pFile );\n\n  /* if we already have a lock, it is exclusive.  \n  ** Just adjust level and punt on outta here. */\n  if (pFile->eFileLock > NO_LOCK) {\n    pFile->eFileLock = eFileLock;\n    return SQLITE_OK;\n  }\n  \n  /* grab an exclusive lock */\n  \n  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {\n    int tErrno = errno;\n    /* didn't get, must be busy */\n    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);\n    if( IS_LOCK_ERROR(rc) ){\n      storeLastErrno(pFile, tErrno);\n    }\n  } else {\n    /* got it, set the type and return ok */\n    pFile->eFileLock = eFileLock;\n  }\n  OSTRACE((\"LOCK    %d %s %s (flock)\\n\", pFile->h, azFileLock(eFileLock), \n           rc==SQLITE_OK ? \"ok\" : \"failed\"));\n#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS\n  if( (rc & 0xff) == SQLITE_IOERR ){\n    rc = SQLITE_BUSY;\n  }\n#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */\n  return rc;\n}\n\n\n/*\n** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock\n** must be either NO_LOCK or SHARED_LOCK.\n**\n** If the locking level of the file descriptor is already at or below\n** the requested locking level, this routine is a no-op.\n*/\nstatic int flockUnlock(sqlite3_file *id, int eFileLock) {\n  unixFile *pFile = (unixFile*)id;\n  \n  assert( pFile );\n  OSTRACE((\"UNLOCK  %d %d was %d pid=%d (flock)\\n\", pFile->h, eFileLock,\n           pFile->eFileLock, osGetpid(0)));\n  assert( eFileLock<=SHARED_LOCK );\n  \n  /* no-op if possible */\n  if( pFile->eFileLock==eFileLock ){\n    return SQLITE_OK;\n  }\n  \n  /* shared can just be set because we always have an exclusive */\n  if (eFileLock==SHARED_LOCK) {\n    pFile->eFileLock = eFileLock;\n    return SQLITE_OK;\n  }\n  \n  /* no, really, unlock. */\n  if( robust_flock(pFile->h, LOCK_UN) ){\n#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS\n    return SQLITE_OK;\n#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */\n    return SQLITE_IOERR_UNLOCK;\n  }else{\n    pFile->eFileLock = NO_LOCK;\n    return SQLITE_OK;\n  }\n}\n\n/*\n** Close a file.\n*/\nstatic int flockClose(sqlite3_file *id) {\n  assert( id!=0 );\n  flockUnlock(id, NO_LOCK);\n  return closeUnixFile(id);\n}\n\n#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */\n\n/******************* End of the flock lock implementation *********************\n******************************************************************************/\n\n/******************************************************************************\n************************ Begin Named Semaphore Locking ************************\n**\n** Named semaphore locking is only supported on VxWorks.\n**\n** Semaphore locking is like dot-lock and flock in that it really only\n** supports EXCLUSIVE locking.  Only a single process can read or write\n** the database file at a time.  This reduces potential concurrency, but\n** makes the lock implementation much easier.\n*/\n#if OS_VXWORKS\n\n/*\n** This routine checks if there is a RESERVED lock held on the specified\n** file by this or any other process. If such a lock is held, set *pResOut\n** to a non-zero value otherwise *pResOut is set to zero.  The return value\n** is set to SQLITE_OK unless an I/O error occurs during lock checking.\n*/\nstatic int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {\n  int rc = SQLITE_OK;\n  int reserved = 0;\n  unixFile *pFile = (unixFile*)id;\n\n  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );\n  \n  assert( pFile );\n\n  /* Check if a thread in this process holds such a lock */\n  if( pFile->eFileLock>SHARED_LOCK ){\n    reserved = 1;\n  }\n  \n  /* Otherwise see if some other process holds it. */\n  if( !reserved ){\n    sem_t *pSem = pFile->pInode->pSem;\n\n    if( sem_trywait(pSem)==-1 ){\n      int tErrno = errno;\n      if( EAGAIN != tErrno ){\n        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);\n        storeLastErrno(pFile, tErrno);\n      } else {\n        /* someone else has the lock when we are in NO_LOCK */\n        reserved = (pFile->eFileLock < SHARED_LOCK);\n      }\n    }else{\n      /* we could have it if we want it */\n      sem_post(pSem);\n    }\n  }\n  OSTRACE((\"TEST WR-LOCK %d %d %d (sem)\\n\", pFile->h, rc, reserved));\n\n  *pResOut = reserved;\n  return rc;\n}\n\n/*\n** Lock the file with the lock specified by parameter eFileLock - one\n** of the following:\n**\n**     (1) SHARED_LOCK\n**     (2) RESERVED_LOCK\n**     (3) PENDING_LOCK\n**     (4) EXCLUSIVE_LOCK\n**\n** Sometimes when requesting one lock state, additional lock states\n** are inserted in between.  The locking might fail on one of the later\n** transitions leaving the lock state different from what it started but\n** still short of its goal.  The following chart shows the allowed\n** transitions and the inserted intermediate states:\n**\n**    UNLOCKED -> SHARED\n**    SHARED -> RESERVED\n**    SHARED -> (PENDING) -> EXCLUSIVE\n**    RESERVED -> (PENDING) -> EXCLUSIVE\n**    PENDING -> EXCLUSIVE\n**\n** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate\n** lock states in the sqlite3_file structure, but all locks SHARED or\n** above are really EXCLUSIVE locks and exclude all other processes from\n** access the file.\n**\n** This routine will only increase a lock.  Use the sqlite3OsUnlock()\n** routine to lower a locking level.\n*/\nstatic int semXLock(sqlite3_file *id, int eFileLock) {\n  unixFile *pFile = (unixFile*)id;\n  sem_t *pSem = pFile->pInode->pSem;\n  int rc = SQLITE_OK;\n\n  /* if we already have a lock, it is exclusive.  \n  ** Just adjust level and punt on outta here. */\n  if (pFile->eFileLock > NO_LOCK) {\n    pFile->eFileLock = eFileLock;\n    rc = SQLITE_OK;\n    goto sem_end_lock;\n  }\n  \n  /* lock semaphore now but bail out when already locked. */\n  if( sem_trywait(pSem)==-1 ){\n    rc = SQLITE_BUSY;\n    goto sem_end_lock;\n  }\n\n  /* got it, set the type and return ok */\n  pFile->eFileLock = eFileLock;\n\n sem_end_lock:\n  return rc;\n}\n\n/*\n** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock\n** must be either NO_LOCK or SHARED_LOCK.\n**\n** If the locking level of the file descriptor is already at or below\n** the requested locking level, this routine is a no-op.\n*/\nstatic int semXUnlock(sqlite3_file *id, int eFileLock) {\n  unixFile *pFile = (unixFile*)id;\n  sem_t *pSem = pFile->pInode->pSem;\n\n  assert( pFile );\n  assert( pSem );\n  OSTRACE((\"UNLOCK  %d %d was %d pid=%d (sem)\\n\", pFile->h, eFileLock,\n           pFile->eFileLock, osGetpid(0)));\n  assert( eFileLock<=SHARED_LOCK );\n  \n  /* no-op if possible */\n  if( pFile->eFileLock==eFileLock ){\n    return SQLITE_OK;\n  }\n  \n  /* shared can just be set because we always have an exclusive */\n  if (eFileLock==SHARED_LOCK) {\n    pFile->eFileLock = eFileLock;\n    return SQLITE_OK;\n  }\n  \n  /* no, really unlock. */\n  if ( sem_post(pSem)==-1 ) {\n    int rc, tErrno = errno;\n    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);\n    if( IS_LOCK_ERROR(rc) ){\n      storeLastErrno(pFile, tErrno);\n    }\n    return rc; \n  }\n  pFile->eFileLock = NO_LOCK;\n  return SQLITE_OK;\n}\n\n/*\n ** Close a file.\n */\nstatic int semXClose(sqlite3_file *id) {\n  if( id ){\n    unixFile *pFile = (unixFile*)id;\n    semXUnlock(id, NO_LOCK);\n    assert( pFile );\n    assert( unixFileMutexNotheld(pFile) );\n    unixEnterMutex();\n    releaseInodeInfo(pFile);\n    unixLeaveMutex();\n    closeUnixFile(id);\n  }\n  return SQLITE_OK;\n}\n\n#endif /* OS_VXWORKS */\n/*\n** Named semaphore locking is only available on VxWorks.\n**\n*************** End of the named semaphore lock implementation ****************\n******************************************************************************/\n\n\n/******************************************************************************\n*************************** Begin AFP Locking *********************************\n**\n** AFP is the Apple Filing Protocol.  AFP is a network filesystem found\n** on Apple Macintosh computers - both OS9 and OSX.\n**\n** Third-party implementations of AFP are available.  But this code here\n** only works on OSX.\n*/\n\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\n/*\n** The afpLockingContext structure contains all afp lock specific state\n*/\ntypedef struct afpLockingContext afpLockingContext;\nstruct afpLockingContext {\n  int reserved;\n  const char *dbPath;             /* Name of the open file */\n};\n\nstruct ByteRangeLockPB2\n{\n  unsigned long long offset;        /* offset to first byte to lock */\n  unsigned long long length;        /* nbr of bytes to lock */\n  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */\n  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */\n  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */\n  int fd;                           /* file desc to assoc this lock with */\n};\n\n#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)\n\n/*\n** This is a utility for setting or clearing a bit-range lock on an\n** AFP filesystem.\n** \n** Return SQLITE_OK on success, SQLITE_BUSY on failure.\n*/\nstatic int afpSetLock(\n  const char *path,              /* Name of the file to be locked or unlocked */\n  unixFile *pFile,               /* Open file descriptor on path */\n  unsigned long long offset,     /* First byte to be locked */\n  unsigned long long length,     /* Number of bytes to lock */\n  int setLockFlag                /* True to set lock.  False to clear lock */\n){\n  struct ByteRangeLockPB2 pb;\n  int err;\n  \n  pb.unLockFlag = setLockFlag ? 0 : 1;\n  pb.startEndFlag = 0;\n  pb.offset = offset;\n  pb.length = length; \n  pb.fd = pFile->h;\n  \n  OSTRACE((\"AFPSETLOCK [%s] for %d%s in range %llx:%llx\\n\", \n    (setLockFlag?\"ON\":\"OFF\"), pFile->h, (pb.fd==-1?\"[testval-1]\":\"\"),\n    offset, length));\n  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);\n  if ( err==-1 ) {\n    int rc;\n    int tErrno = errno;\n    OSTRACE((\"AFPSETLOCK failed to fsctl() '%s' %d %s\\n\",\n             path, tErrno, strerror(tErrno)));\n#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS\n    rc = SQLITE_BUSY;\n#else\n    rc = sqliteErrorFromPosixError(tErrno,\n                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);\n#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */\n    if( IS_LOCK_ERROR(rc) ){\n      storeLastErrno(pFile, tErrno);\n    }\n    return rc;\n  } else {\n    return SQLITE_OK;\n  }\n}\n\n/*\n** This routine checks if there is a RESERVED lock held on the specified\n** file by this or any other process. If such a lock is held, set *pResOut\n** to a non-zero value otherwise *pResOut is set to zero.  The return value\n** is set to SQLITE_OK unless an I/O error occurs during lock checking.\n*/\nstatic int afpCheckReservedLock(sqlite3_file *id, int *pResOut){\n  int rc = SQLITE_OK;\n  int reserved = 0;\n  unixFile *pFile = (unixFile*)id;\n  afpLockingContext *context;\n  \n  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );\n  \n  assert( pFile );\n  context = (afpLockingContext *) pFile->lockingContext;\n  if( context->reserved ){\n    *pResOut = 1;\n    return SQLITE_OK;\n  }\n  sqlite3_mutex_enter(pFile->pInode->pLockMutex);\n  /* Check if a thread in this process holds such a lock */\n  if( pFile->pInode->eFileLock>SHARED_LOCK ){\n    reserved = 1;\n  }\n  \n  /* Otherwise see if some other process holds it.\n   */\n  if( !reserved ){\n    /* lock the RESERVED byte */\n    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  \n    if( SQLITE_OK==lrc ){\n      /* if we succeeded in taking the reserved lock, unlock it to restore\n      ** the original state */\n      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);\n    } else {\n      /* if we failed to get the lock then someone else must have it */\n      reserved = 1;\n    }\n    if( IS_LOCK_ERROR(lrc) ){\n      rc=lrc;\n    }\n  }\n  \n  sqlite3_mutex_leave(pFile->pInode->pLockMutex);\n  OSTRACE((\"TEST WR-LOCK %d %d %d (afp)\\n\", pFile->h, rc, reserved));\n  \n  *pResOut = reserved;\n  return rc;\n}\n\n/*\n** Lock the file with the lock specified by parameter eFileLock - one\n** of the following:\n**\n**     (1) SHARED_LOCK\n**     (2) RESERVED_LOCK\n**     (3) PENDING_LOCK\n**     (4) EXCLUSIVE_LOCK\n**\n** Sometimes when requesting one lock state, additional lock states\n** are inserted in between.  The locking might fail on one of the later\n** transitions leaving the lock state different from what it started but\n** still short of its goal.  The following chart shows the allowed\n** transitions and the inserted intermediate states:\n**\n**    UNLOCKED -> SHARED\n**    SHARED -> RESERVED\n**    SHARED -> (PENDING) -> EXCLUSIVE\n**    RESERVED -> (PENDING) -> EXCLUSIVE\n**    PENDING -> EXCLUSIVE\n**\n** This routine will only increase a lock.  Use the sqlite3OsUnlock()\n** routine to lower a locking level.\n*/\nstatic int afpLock(sqlite3_file *id, int eFileLock){\n  int rc = SQLITE_OK;\n  unixFile *pFile = (unixFile*)id;\n  unixInodeInfo *pInode = pFile->pInode;\n  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;\n  \n  assert( pFile );\n  OSTRACE((\"LOCK    %d %s was %s(%s,%d) pid=%d (afp)\\n\", pFile->h,\n           azFileLock(eFileLock), azFileLock(pFile->eFileLock),\n           azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));\n\n  /* If there is already a lock of this type or more restrictive on the\n  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as\n  ** unixEnterMutex() hasn't been called yet.\n  */\n  if( pFile->eFileLock>=eFileLock ){\n    OSTRACE((\"LOCK    %d %s ok (already held) (afp)\\n\", pFile->h,\n           azFileLock(eFileLock)));\n    return SQLITE_OK;\n  }\n\n  /* Make sure the locking sequence is correct\n  **  (1) We never move from unlocked to anything higher than shared lock.\n  **  (2) SQLite never explicitly requests a pendig lock.\n  **  (3) A shared lock is always held when a reserve lock is requested.\n  */\n  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );\n  assert( eFileLock!=PENDING_LOCK );\n  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );\n  \n  /* This mutex is needed because pFile->pInode is shared across threads\n  */\n  pInode = pFile->pInode;\n  sqlite3_mutex_enter(pInode->pLockMutex);\n\n  /* If some thread using this PID has a lock via a different unixFile*\n  ** handle that precludes the requested lock, return BUSY.\n  */\n  if( (pFile->eFileLock!=pInode->eFileLock && \n       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))\n     ){\n    rc = SQLITE_BUSY;\n    goto afp_end_lock;\n  }\n  \n  /* If a SHARED lock is requested, and some thread using this PID already\n  ** has a SHARED or RESERVED lock, then increment reference counts and\n  ** return SQLITE_OK.\n  */\n  if( eFileLock==SHARED_LOCK && \n     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){\n    assert( eFileLock==SHARED_LOCK );\n    assert( pFile->eFileLock==0 );\n    assert( pInode->nShared>0 );\n    pFile->eFileLock = SHARED_LOCK;\n    pInode->nShared++;\n    pInode->nLock++;\n    goto afp_end_lock;\n  }\n    \n  /* A PENDING lock is needed before acquiring a SHARED lock and before\n  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will\n  ** be released.\n  */\n  if( eFileLock==SHARED_LOCK \n      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)\n  ){\n    int failed;\n    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);\n    if (failed) {\n      rc = failed;\n      goto afp_end_lock;\n    }\n  }\n  \n  /* If control gets to this point, then actually go ahead and make\n  ** operating system calls for the specified lock.\n  */\n  if( eFileLock==SHARED_LOCK ){\n    int lrc1, lrc2, lrc1Errno = 0;\n    long lk, mask;\n    \n    assert( pInode->nShared==0 );\n    assert( pInode->eFileLock==0 );\n        \n    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;\n    /* Now get the read-lock SHARED_LOCK */\n    /* note that the quality of the randomness doesn't matter that much */\n    lk = random(); \n    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);\n    lrc1 = afpSetLock(context->dbPath, pFile, \n          SHARED_FIRST+pInode->sharedByte, 1, 1);\n    if( IS_LOCK_ERROR(lrc1) ){\n      lrc1Errno = pFile->lastErrno;\n    }\n    /* Drop the temporary PENDING lock */\n    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);\n    \n    if( IS_LOCK_ERROR(lrc1) ) {\n      storeLastErrno(pFile, lrc1Errno);\n      rc = lrc1;\n      goto afp_end_lock;\n    } else if( IS_LOCK_ERROR(lrc2) ){\n      rc = lrc2;\n      goto afp_end_lock;\n    } else if( lrc1 != SQLITE_OK ) {\n      rc = lrc1;\n    } else {\n      pFile->eFileLock = SHARED_LOCK;\n      pInode->nLock++;\n      pInode->nShared = 1;\n    }\n  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){\n    /* We are trying for an exclusive lock but another thread in this\n     ** same process is still holding a shared lock. */\n    rc = SQLITE_BUSY;\n  }else{\n    /* The request was for a RESERVED or EXCLUSIVE lock.  It is\n    ** assumed that there is a SHARED or greater lock on the file\n    ** already.\n    */\n    int failed = 0;\n    assert( 0!=pFile->eFileLock );\n    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {\n        /* Acquire a RESERVED lock */\n        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);\n      if( !failed ){\n        context->reserved = 1;\n      }\n    }\n    if (!failed && eFileLock == EXCLUSIVE_LOCK) {\n      /* Acquire an EXCLUSIVE lock */\n        \n      /* Remove the shared lock before trying the range.  we'll need to \n      ** reestablish the shared lock if we can't get the  afpUnlock\n      */\n      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +\n                         pInode->sharedByte, 1, 0)) ){\n        int failed2 = SQLITE_OK;\n        /* now attemmpt to get the exclusive lock range */\n        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, \n                               SHARED_SIZE, 1);\n        if( failed && (failed2 = afpSetLock(context->dbPath, pFile, \n                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){\n          /* Can't reestablish the shared lock.  Sqlite can't deal, this is\n          ** a critical I/O error\n          */\n          rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 : \n               SQLITE_IOERR_LOCK;\n          goto afp_end_lock;\n        } \n      }else{\n        rc = failed; \n      }\n    }\n    if( failed ){\n      rc = failed;\n    }\n  }\n  \n  if( rc==SQLITE_OK ){\n    pFile->eFileLock = eFileLock;\n    pInode->eFileLock = eFileLock;\n  }else if( eFileLock==EXCLUSIVE_LOCK ){\n    pFile->eFileLock = PENDING_LOCK;\n    pInode->eFileLock = PENDING_LOCK;\n  }\n  \nafp_end_lock:\n  sqlite3_mutex_leave(pInode->pLockMutex);\n  OSTRACE((\"LOCK    %d %s %s (afp)\\n\", pFile->h, azFileLock(eFileLock), \n         rc==SQLITE_OK ? \"ok\" : \"failed\"));\n  return rc;\n}\n\n/*\n** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock\n** must be either NO_LOCK or SHARED_LOCK.\n**\n** If the locking level of the file descriptor is already at or below\n** the requested locking level, this routine is a no-op.\n*/\nstatic int afpUnlock(sqlite3_file *id, int eFileLock) {\n  int rc = SQLITE_OK;\n  unixFile *pFile = (unixFile*)id;\n  unixInodeInfo *pInode;\n  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;\n  int skipShared = 0;\n#ifdef SQLITE_TEST\n  int h = pFile->h;\n#endif\n\n  assert( pFile );\n  OSTRACE((\"UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\\n\", pFile->h, eFileLock,\n           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,\n           osGetpid(0)));\n\n  assert( eFileLock<=SHARED_LOCK );\n  if( pFile->eFileLock<=eFileLock ){\n    return SQLITE_OK;\n  }\n  pInode = pFile->pInode;\n  sqlite3_mutex_enter(pInode->pLockMutex);\n  assert( pInode->nShared!=0 );\n  if( pFile->eFileLock>SHARED_LOCK ){\n    assert( pInode->eFileLock==pFile->eFileLock );\n    SimulateIOErrorBenign(1);\n    SimulateIOError( h=(-1) )\n    SimulateIOErrorBenign(0);\n    \n#ifdef SQLITE_DEBUG\n    /* When reducing a lock such that other processes can start\n    ** reading the database file again, make sure that the\n    ** transaction counter was updated if any part of the database\n    ** file changed.  If the transaction counter is not updated,\n    ** other connections to the same file might not realize that\n    ** the file has changed and hence might not know to flush their\n    ** cache.  The use of a stale cache can lead to database corruption.\n    */\n    assert( pFile->inNormalWrite==0\n           || pFile->dbUpdate==0\n           || pFile->transCntrChng==1 );\n    pFile->inNormalWrite = 0;\n#endif\n    \n    if( pFile->eFileLock==EXCLUSIVE_LOCK ){\n      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);\n      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){\n        /* only re-establish the shared lock if necessary */\n        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;\n        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);\n      } else {\n        skipShared = 1;\n      }\n    }\n    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){\n      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);\n    } \n    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){\n      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);\n      if( !rc ){ \n        context->reserved = 0; \n      }\n    }\n    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){\n      pInode->eFileLock = SHARED_LOCK;\n    }\n  }\n  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){\n\n    /* Decrement the shared lock counter.  Release the lock using an\n    ** OS call only when all threads in this same process have released\n    ** the lock.\n    */\n    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;\n    pInode->nShared--;\n    if( pInode->nShared==0 ){\n      SimulateIOErrorBenign(1);\n      SimulateIOError( h=(-1) )\n      SimulateIOErrorBenign(0);\n      if( !skipShared ){\n        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);\n      }\n      if( !rc ){\n        pInode->eFileLock = NO_LOCK;\n        pFile->eFileLock = NO_LOCK;\n      }\n    }\n    if( rc==SQLITE_OK ){\n      pInode->nLock--;\n      assert( pInode->nLock>=0 );\n      if( pInode->nLock==0 ) closePendingFds(pFile);\n    }\n  }\n  \n  sqlite3_mutex_leave(pInode->pLockMutex);\n  if( rc==SQLITE_OK ){\n    pFile->eFileLock = eFileLock;\n  }\n  return rc;\n}\n\n/*\n** Close a file & cleanup AFP specific locking context \n*/\nstatic int afpClose(sqlite3_file *id) {\n  int rc = SQLITE_OK;\n  unixFile *pFile = (unixFile*)id;\n  assert( id!=0 );\n  afpUnlock(id, NO_LOCK);\n  assert( unixFileMutexNotheld(pFile) );\n  unixEnterMutex();\n  if( pFile->pInode ){\n    unixInodeInfo *pInode = pFile->pInode;\n    sqlite3_mutex_enter(pInode->pLockMutex);\n    if( pInode->nLock ){\n      /* If there are outstanding locks, do not actually close the file just\n      ** yet because that would clear those locks.  Instead, add the file\n      ** descriptor to pInode->aPending.  It will be automatically closed when\n      ** the last lock is cleared.\n      */\n      setPendingFd(pFile);\n    }\n    sqlite3_mutex_leave(pInode->pLockMutex);\n  }\n  releaseInodeInfo(pFile);\n  sqlite3_free(pFile->lockingContext);\n  rc = closeUnixFile(id);\n  unixLeaveMutex();\n  return rc;\n}\n\n#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */\n/*\n** The code above is the AFP lock implementation.  The code is specific\n** to MacOSX and does not work on other unix platforms.  No alternative\n** is available.  If you don't compile for a mac, then the \"unix-afp\"\n** VFS is not available.\n**\n********************* End of the AFP lock implementation **********************\n******************************************************************************/\n\n/******************************************************************************\n*************************** Begin NFS Locking ********************************/\n\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\n/*\n ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock\n ** must be either NO_LOCK or SHARED_LOCK.\n **\n ** If the locking level of the file descriptor is already at or below\n ** the requested locking level, this routine is a no-op.\n */\nstatic int nfsUnlock(sqlite3_file *id, int eFileLock){\n  return posixUnlock(id, eFileLock, 1);\n}\n\n#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */\n/*\n** The code above is the NFS lock implementation.  The code is specific\n** to MacOSX and does not work on other unix platforms.  No alternative\n** is available.  \n**\n********************* End of the NFS lock implementation **********************\n******************************************************************************/\n\n/******************************************************************************\n**************** Non-locking sqlite3_file methods *****************************\n**\n** The next division contains implementations for all methods of the \n** sqlite3_file object other than the locking methods.  The locking\n** methods were defined in divisions above (one locking method per\n** division).  Those methods that are common to all locking modes\n** are gather together into this division.\n*/\n\n/*\n** Seek to the offset passed as the second argument, then read cnt \n** bytes into pBuf. Return the number of bytes actually read.\n**\n** NB:  If you define USE_PREAD or USE_PREAD64, then it might also\n** be necessary to define _XOPEN_SOURCE to be 500.  This varies from\n** one system to another.  Since SQLite does not define USE_PREAD\n** in any form by default, we will not attempt to define _XOPEN_SOURCE.\n** See tickets #2741 and #2681.\n**\n** To avoid stomping the errno value on a failed read the lastErrno value\n** is set before returning.\n*/\nstatic int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){\n  int got;\n  int prior = 0;\n#if (!defined(USE_PREAD) && !defined(USE_PREAD64))\n  i64 newOffset;\n#endif\n  TIMER_START;\n  assert( cnt==(cnt&0x1ffff) );\n  assert( id->h>2 );\n  do{\n#if defined(USE_PREAD)\n    got = osPread(id->h, pBuf, cnt, offset);\n    SimulateIOError( got = -1 );\n#elif defined(USE_PREAD64)\n    got = osPread64(id->h, pBuf, cnt, offset);\n    SimulateIOError( got = -1 );\n#else\n    newOffset = lseek(id->h, offset, SEEK_SET);\n    SimulateIOError( newOffset = -1 );\n    if( newOffset<0 ){\n      storeLastErrno((unixFile*)id, errno);\n      return -1;\n    }\n    got = osRead(id->h, pBuf, cnt);\n#endif\n    if( got==cnt ) break;\n    if( got<0 ){\n      if( errno==EINTR ){ got = 1; continue; }\n      prior = 0;\n      storeLastErrno((unixFile*)id,  errno);\n      break;\n    }else if( got>0 ){\n      cnt -= got;\n      offset += got;\n      prior += got;\n      pBuf = (void*)(got + (char*)pBuf);\n    }\n  }while( got>0 );\n  TIMER_END;\n  OSTRACE((\"READ    %-3d %5d %7lld %llu\\n\",\n            id->h, got+prior, offset-prior, TIMER_ELAPSED));\n  return got+prior;\n}\n\n/*\n** Read data from a file into a buffer.  Return SQLITE_OK if all\n** bytes were read successfully and SQLITE_IOERR if anything goes\n** wrong.\n*/\nstatic int unixRead(\n  sqlite3_file *id, \n  void *pBuf, \n  int amt,\n  sqlite3_int64 offset\n){\n  unixFile *pFile = (unixFile *)id;\n  int got;\n  assert( id );\n  assert( offset>=0 );\n  assert( amt>0 );\n\n  /* If this is a database file (not a journal, master-journal or temp\n  ** file), the bytes in the locking range should never be read or written. */\n#if 0\n  assert( pFile->pPreallocatedUnused==0\n       || offset>=PENDING_BYTE+512\n       || offset+amt<=PENDING_BYTE \n  );\n#endif\n\n#if SQLITE_MAX_MMAP_SIZE>0\n  /* Deal with as much of this read request as possible by transfering\n  ** data from the memory mapping using memcpy().  */\n  if( offset<pFile->mmapSize ){\n    if( offset+amt <= pFile->mmapSize ){\n      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);\n      return SQLITE_OK;\n    }else{\n      int nCopy = pFile->mmapSize - offset;\n      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);\n      pBuf = &((u8 *)pBuf)[nCopy];\n      amt -= nCopy;\n      offset += nCopy;\n    }\n  }\n#endif\n\n  got = seekAndRead(pFile, offset, pBuf, amt);\n  if( got==amt ){\n    return SQLITE_OK;\n  }else if( got<0 ){\n    /* lastErrno set by seekAndRead */\n    return SQLITE_IOERR_READ;\n  }else{\n    storeLastErrno(pFile, 0);   /* not a system error */\n    /* Unread parts of the buffer must be zero-filled */\n    memset(&((char*)pBuf)[got], 0, amt-got);\n    return SQLITE_IOERR_SHORT_READ;\n  }\n}\n\n/*\n** Attempt to seek the file-descriptor passed as the first argument to\n** absolute offset iOff, then attempt to write nBuf bytes of data from\n** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, \n** return the actual number of bytes written (which may be less than\n** nBuf).\n*/\nstatic int seekAndWriteFd(\n  int fd,                         /* File descriptor to write to */\n  i64 iOff,                       /* File offset to begin writing at */\n  const void *pBuf,               /* Copy data from this buffer to the file */\n  int nBuf,                       /* Size of buffer pBuf in bytes */\n  int *piErrno                    /* OUT: Error number if error occurs */\n){\n  int rc = 0;                     /* Value returned by system call */\n\n  assert( nBuf==(nBuf&0x1ffff) );\n  assert( fd>2 );\n  assert( piErrno!=0 );\n  nBuf &= 0x1ffff;\n  TIMER_START;\n\n#if defined(USE_PREAD)\n  do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );\n#elif defined(USE_PREAD64)\n  do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);\n#else\n  do{\n    i64 iSeek = lseek(fd, iOff, SEEK_SET);\n    SimulateIOError( iSeek = -1 );\n    if( iSeek<0 ){\n      rc = -1;\n      break;\n    }\n    rc = osWrite(fd, pBuf, nBuf);\n  }while( rc<0 && errno==EINTR );\n#endif\n\n  TIMER_END;\n  OSTRACE((\"WRITE   %-3d %5d %7lld %llu\\n\", fd, rc, iOff, TIMER_ELAPSED));\n\n  if( rc<0 ) *piErrno = errno;\n  return rc;\n}\n\n\n/*\n** Seek to the offset in id->offset then read cnt bytes into pBuf.\n** Return the number of bytes actually read.  Update the offset.\n**\n** To avoid stomping the errno value on a failed write the lastErrno value\n** is set before returning.\n*/\nstatic int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){\n  return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);\n}\n\n\n/*\n** Write data from a buffer into a file.  Return SQLITE_OK on success\n** or some other error code on failure.\n*/\nstatic int unixWrite(\n  sqlite3_file *id, \n  const void *pBuf, \n  int amt,\n  sqlite3_int64 offset \n){\n  unixFile *pFile = (unixFile*)id;\n  int wrote = 0;\n  assert( id );\n  assert( amt>0 );\n\n  /* If this is a database file (not a journal, master-journal or temp\n  ** file), the bytes in the locking range should never be read or written. */\n#if 0\n  assert( pFile->pPreallocatedUnused==0\n       || offset>=PENDING_BYTE+512\n       || offset+amt<=PENDING_BYTE \n  );\n#endif\n\n#ifdef SQLITE_DEBUG\n  /* If we are doing a normal write to a database file (as opposed to\n  ** doing a hot-journal rollback or a write to some file other than a\n  ** normal database file) then record the fact that the database\n  ** has changed.  If the transaction counter is modified, record that\n  ** fact too.\n  */\n  if( pFile->inNormalWrite ){\n    pFile->dbUpdate = 1;  /* The database has been modified */\n    if( offset<=24 && offset+amt>=27 ){\n      int rc;\n      char oldCntr[4];\n      SimulateIOErrorBenign(1);\n      rc = seekAndRead(pFile, 24, oldCntr, 4);\n      SimulateIOErrorBenign(0);\n      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){\n        pFile->transCntrChng = 1;  /* The transaction counter has changed */\n      }\n    }\n  }\n#endif\n\n#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0\n  /* Deal with as much of this write request as possible by transfering\n  ** data from the memory mapping using memcpy().  */\n  if( offset<pFile->mmapSize ){\n    if( offset+amt <= pFile->mmapSize ){\n      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);\n      return SQLITE_OK;\n    }else{\n      int nCopy = pFile->mmapSize - offset;\n      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);\n      pBuf = &((u8 *)pBuf)[nCopy];\n      amt -= nCopy;\n      offset += nCopy;\n    }\n  }\n#endif\n \n  while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){\n    amt -= wrote;\n    offset += wrote;\n    pBuf = &((char*)pBuf)[wrote];\n  }\n  SimulateIOError(( wrote=(-1), amt=1 ));\n  SimulateDiskfullError(( wrote=0, amt=1 ));\n\n  if( amt>wrote ){\n    if( wrote<0 && pFile->lastErrno!=ENOSPC ){\n      /* lastErrno set by seekAndWrite */\n      return SQLITE_IOERR_WRITE;\n    }else{\n      storeLastErrno(pFile, 0); /* not a system error */\n      return SQLITE_FULL;\n    }\n  }\n\n  return SQLITE_OK;\n}\n\n#ifdef SQLITE_TEST\n/*\n** Count the number of fullsyncs and normal syncs.  This is used to test\n** that syncs and fullsyncs are occurring at the right times.\n*/\nSQLITE_API int sqlite3_sync_count = 0;\nSQLITE_API int sqlite3_fullsync_count = 0;\n#endif\n\n/*\n** We do not trust systems to provide a working fdatasync().  Some do.\n** Others do no.  To be safe, we will stick with the (slightly slower)\n** fsync(). If you know that your system does support fdatasync() correctly,\n** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC\n*/\n#if !defined(fdatasync) && !HAVE_FDATASYNC\n# define fdatasync fsync\n#endif\n\n/*\n** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not\n** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently\n** only available on Mac OS X.  But that could change.\n*/\n#ifdef F_FULLFSYNC\n# define HAVE_FULLFSYNC 1\n#else\n# define HAVE_FULLFSYNC 0\n#endif\n\n\n/*\n** The fsync() system call does not work as advertised on many\n** unix systems.  The following procedure is an attempt to make\n** it work better.\n**\n** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful\n** for testing when we want to run through the test suite quickly.\n** You are strongly advised *not* to deploy with SQLITE_NO_SYNC\n** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash\n** or power failure will likely corrupt the database file.\n**\n** SQLite sets the dataOnly flag if the size of the file is unchanged.\n** The idea behind dataOnly is that it should only write the file content\n** to disk, not the inode.  We only set dataOnly if the file size is \n** unchanged since the file size is part of the inode.  However, \n** Ted Ts'o tells us that fdatasync() will also write the inode if the\n** file size has changed.  The only real difference between fdatasync()\n** and fsync(), Ted tells us, is that fdatasync() will not flush the\n** inode if the mtime or owner or other inode attributes have changed.\n** We only care about the file size, not the other file attributes, so\n** as far as SQLite is concerned, an fdatasync() is always adequate.\n** So, we always use fdatasync() if it is available, regardless of\n** the value of the dataOnly flag.\n*/\nstatic int full_fsync(int fd, int fullSync, int dataOnly){\n  int rc;\n\n  /* The following \"ifdef/elif/else/\" block has the same structure as\n  ** the one below. It is replicated here solely to avoid cluttering \n  ** up the real code with the UNUSED_PARAMETER() macros.\n  */\n#ifdef SQLITE_NO_SYNC\n  UNUSED_PARAMETER(fd);\n  UNUSED_PARAMETER(fullSync);\n  UNUSED_PARAMETER(dataOnly);\n#elif HAVE_FULLFSYNC\n  UNUSED_PARAMETER(dataOnly);\n#else\n  UNUSED_PARAMETER(fullSync);\n  UNUSED_PARAMETER(dataOnly);\n#endif\n\n  /* Record the number of times that we do a normal fsync() and \n  ** FULLSYNC.  This is used during testing to verify that this procedure\n  ** gets called with the correct arguments.\n  */\n#ifdef SQLITE_TEST\n  if( fullSync ) sqlite3_fullsync_count++;\n  sqlite3_sync_count++;\n#endif\n\n  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a\n  ** no-op.  But go ahead and call fstat() to validate the file\n  ** descriptor as we need a method to provoke a failure during\n  ** coverate testing.\n  */\n#ifdef SQLITE_NO_SYNC\n  {\n    struct stat buf;\n    rc = osFstat(fd, &buf);\n  }\n#elif HAVE_FULLFSYNC\n  if( fullSync ){\n    rc = osFcntl(fd, F_FULLFSYNC, 0);\n  }else{\n    rc = 1;\n  }\n  /* If the FULLFSYNC failed, fall back to attempting an fsync().\n  ** It shouldn't be possible for fullfsync to fail on the local \n  ** file system (on OSX), so failure indicates that FULLFSYNC\n  ** isn't supported for this file system. So, attempt an fsync \n  ** and (for now) ignore the overhead of a superfluous fcntl call.  \n  ** It'd be better to detect fullfsync support once and avoid \n  ** the fcntl call every time sync is called.\n  */\n  if( rc ) rc = fsync(fd);\n\n#elif defined(__APPLE__)\n  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly\n  ** so currently we default to the macro that redefines fdatasync to fsync\n  */\n  rc = fsync(fd);\n#else \n  rc = fdatasync(fd);\n#if OS_VXWORKS\n  if( rc==-1 && errno==ENOTSUP ){\n    rc = fsync(fd);\n  }\n#endif /* OS_VXWORKS */\n#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */\n\n  if( OS_VXWORKS && rc!= -1 ){\n    rc = 0;\n  }\n  return rc;\n}\n\n/*\n** Open a file descriptor to the directory containing file zFilename.\n** If successful, *pFd is set to the opened file descriptor and\n** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM\n** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined\n** value.\n**\n** The directory file descriptor is used for only one thing - to\n** fsync() a directory to make sure file creation and deletion events\n** are flushed to disk.  Such fsyncs are not needed on newer\n** journaling filesystems, but are required on older filesystems.\n**\n** This routine can be overridden using the xSetSysCall interface.\n** The ability to override this routine was added in support of the\n** chromium sandbox.  Opening a directory is a security risk (we are\n** told) so making it overrideable allows the chromium sandbox to\n** replace this routine with a harmless no-op.  To make this routine\n** a no-op, replace it with a stub that returns SQLITE_OK but leaves\n** *pFd set to a negative number.\n**\n** If SQLITE_OK is returned, the caller is responsible for closing\n** the file descriptor *pFd using close().\n*/\nstatic int openDirectory(const char *zFilename, int *pFd){\n  int ii;\n  int fd = -1;\n  char zDirname[MAX_PATHNAME+1];\n\n  sqlite3_snprintf(MAX_PATHNAME, zDirname, \"%s\", zFilename);\n  for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);\n  if( ii>0 ){\n    zDirname[ii] = '\\0';\n  }else{\n    if( zDirname[0]!='/' ) zDirname[0] = '.';\n    zDirname[1] = 0;\n  }\n  fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);\n  if( fd>=0 ){\n    OSTRACE((\"OPENDIR %-3d %s\\n\", fd, zDirname));\n  }\n  *pFd = fd;\n  if( fd>=0 ) return SQLITE_OK;\n  return unixLogError(SQLITE_CANTOPEN_BKPT, \"openDirectory\", zDirname);\n}\n\n/*\n** Make sure all writes to a particular file are committed to disk.\n**\n** If dataOnly==0 then both the file itself and its metadata (file\n** size, access time, etc) are synced.  If dataOnly!=0 then only the\n** file data is synced.\n**\n** Under Unix, also make sure that the directory entry for the file\n** has been created by fsync-ing the directory that contains the file.\n** If we do not do this and we encounter a power failure, the directory\n** entry for the journal might not exist after we reboot.  The next\n** SQLite to access the file will not know that the journal exists (because\n** the directory entry for the journal was never created) and the transaction\n** will not roll back - possibly leading to database corruption.\n*/\nstatic int unixSync(sqlite3_file *id, int flags){\n  int rc;\n  unixFile *pFile = (unixFile*)id;\n\n  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);\n  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;\n\n  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */\n  assert((flags&0x0F)==SQLITE_SYNC_NORMAL\n      || (flags&0x0F)==SQLITE_SYNC_FULL\n  );\n\n  /* Unix cannot, but some systems may return SQLITE_FULL from here. This\n  ** line is to test that doing so does not cause any problems.\n  */\n  SimulateDiskfullError( return SQLITE_FULL );\n\n  assert( pFile );\n  OSTRACE((\"SYNC    %-3d\\n\", pFile->h));\n  rc = full_fsync(pFile->h, isFullsync, isDataOnly);\n  SimulateIOError( rc=1 );\n  if( rc ){\n    storeLastErrno(pFile, errno);\n    return unixLogError(SQLITE_IOERR_FSYNC, \"full_fsync\", pFile->zPath);\n  }\n\n  /* Also fsync the directory containing the file if the DIRSYNC flag\n  ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)\n  ** are unable to fsync a directory, so ignore errors on the fsync.\n  */\n  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){\n    int dirfd;\n    OSTRACE((\"DIRSYNC %s (have_fullfsync=%d fullsync=%d)\\n\", pFile->zPath,\n            HAVE_FULLFSYNC, isFullsync));\n    rc = osOpenDirectory(pFile->zPath, &dirfd);\n    if( rc==SQLITE_OK ){\n      full_fsync(dirfd, 0, 0);\n      robust_close(pFile, dirfd, __LINE__);\n    }else{\n      assert( rc==SQLITE_CANTOPEN );\n      rc = SQLITE_OK;\n    }\n    pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;\n  }\n  return rc;\n}\n\n/*\n** Truncate an open file to a specified size\n*/\nstatic int unixTruncate(sqlite3_file *id, i64 nByte){\n  unixFile *pFile = (unixFile *)id;\n  int rc;\n  assert( pFile );\n  SimulateIOError( return SQLITE_IOERR_TRUNCATE );\n\n  /* If the user has configured a chunk-size for this file, truncate the\n  ** file so that it consists of an integer number of chunks (i.e. the\n  ** actual file size after the operation may be larger than the requested\n  ** size).\n  */\n  if( pFile->szChunk>0 ){\n    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;\n  }\n\n  rc = robust_ftruncate(pFile->h, nByte);\n  if( rc ){\n    storeLastErrno(pFile, errno);\n    return unixLogError(SQLITE_IOERR_TRUNCATE, \"ftruncate\", pFile->zPath);\n  }else{\n#ifdef SQLITE_DEBUG\n    /* If we are doing a normal write to a database file (as opposed to\n    ** doing a hot-journal rollback or a write to some file other than a\n    ** normal database file) and we truncate the file to zero length,\n    ** that effectively updates the change counter.  This might happen\n    ** when restoring a database using the backup API from a zero-length\n    ** source.\n    */\n    if( pFile->inNormalWrite && nByte==0 ){\n      pFile->transCntrChng = 1;\n    }\n#endif\n\n#if SQLITE_MAX_MMAP_SIZE>0\n    /* If the file was just truncated to a size smaller than the currently\n    ** mapped region, reduce the effective mapping size as well. SQLite will\n    ** use read() and write() to access data beyond this point from now on.  \n    */\n    if( nByte<pFile->mmapSize ){\n      pFile->mmapSize = nByte;\n    }\n#endif\n\n    return SQLITE_OK;\n  }\n}\n\n/*\n** Determine the current size of a file in bytes\n*/\nstatic int unixFileSize(sqlite3_file *id, i64 *pSize){\n  int rc;\n  struct stat buf;\n  assert( id );\n  rc = osFstat(((unixFile*)id)->h, &buf);\n  SimulateIOError( rc=1 );\n  if( rc!=0 ){\n    storeLastErrno((unixFile*)id, errno);\n    return SQLITE_IOERR_FSTAT;\n  }\n  *pSize = buf.st_size;\n\n  /* When opening a zero-size database, the findInodeInfo() procedure\n  ** writes a single byte into that file in order to work around a bug\n  ** in the OS-X msdos filesystem.  In order to avoid problems with upper\n  ** layers, we need to report this file size as zero even though it is\n  ** really 1.   Ticket #3260.\n  */\n  if( *pSize==1 ) *pSize = 0;\n\n\n  return SQLITE_OK;\n}\n\n#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)\n/*\n** Handler for proxy-locking file-control verbs.  Defined below in the\n** proxying locking division.\n*/\nstatic int proxyFileControl(sqlite3_file*,int,void*);\n#endif\n\n/* \n** This function is called to handle the SQLITE_FCNTL_SIZE_HINT \n** file-control operation.  Enlarge the database to nBytes in size\n** (rounded up to the next chunk-size).  If the database is already\n** nBytes or larger, this routine is a no-op.\n*/\nstatic int fcntlSizeHint(unixFile *pFile, i64 nByte){\n  if( pFile->szChunk>0 ){\n    i64 nSize;                    /* Required file size */\n    struct stat buf;              /* Used to hold return values of fstat() */\n   \n    if( osFstat(pFile->h, &buf) ){\n      return SQLITE_IOERR_FSTAT;\n    }\n\n    nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;\n    if( nSize>(i64)buf.st_size ){\n\n#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE\n      /* The code below is handling the return value of osFallocate() \n      ** correctly. posix_fallocate() is defined to \"returns zero on success, \n      ** or an error number on  failure\". See the manpage for details. */\n      int err;\n      do{\n        err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);\n      }while( err==EINTR );\n      if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;\n#else\n      /* If the OS does not have posix_fallocate(), fake it. Write a \n      ** single byte to the last byte in each block that falls entirely\n      ** within the extended region. Then, if required, a single byte\n      ** at offset (nSize-1), to set the size of the file correctly.\n      ** This is a similar technique to that used by glibc on systems\n      ** that do not have a real fallocate() call.\n      */\n      int nBlk = buf.st_blksize;  /* File-system block size */\n      int nWrite = 0;             /* Number of bytes written by seekAndWrite */\n      i64 iWrite;                 /* Next offset to write to */\n\n      iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;\n      assert( iWrite>=buf.st_size );\n      assert( ((iWrite+1)%nBlk)==0 );\n      for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){\n        if( iWrite>=nSize ) iWrite = nSize - 1;\n        nWrite = seekAndWrite(pFile, iWrite, \"\", 1);\n        if( nWrite!=1 ) return SQLITE_IOERR_WRITE;\n      }\n#endif\n    }\n  }\n\n#if SQLITE_MAX_MMAP_SIZE>0\n  if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){\n    int rc;\n    if( pFile->szChunk<=0 ){\n      if( robust_ftruncate(pFile->h, nByte) ){\n        storeLastErrno(pFile, errno);\n        return unixLogError(SQLITE_IOERR_TRUNCATE, \"ftruncate\", pFile->zPath);\n      }\n    }\n\n    rc = unixMapfile(pFile, nByte);\n    return rc;\n  }\n#endif\n\n  return SQLITE_OK;\n}\n\n/*\n** If *pArg is initially negative then this is a query.  Set *pArg to\n** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.\n**\n** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.\n*/\nstatic void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){\n  if( *pArg<0 ){\n    *pArg = (pFile->ctrlFlags & mask)!=0;\n  }else if( (*pArg)==0 ){\n    pFile->ctrlFlags &= ~mask;\n  }else{\n    pFile->ctrlFlags |= mask;\n  }\n}\n\n/* Forward declaration */\nstatic int unixGetTempname(int nBuf, char *zBuf);\n\n/*\n** Information and control of an open file handle.\n*/\nstatic int unixFileControl(sqlite3_file *id, int op, void *pArg){\n  unixFile *pFile = (unixFile*)id;\n  switch( op ){\n#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)\n    case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {\n      int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);\n      return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;\n    }\n    case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {\n      int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);\n      return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;\n    }\n    case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {\n      int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);\n      return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;\n    }\n#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */\n\n    case SQLITE_FCNTL_LOCKSTATE: {\n      *(int*)pArg = pFile->eFileLock;\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_LAST_ERRNO: {\n      *(int*)pArg = pFile->lastErrno;\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_CHUNK_SIZE: {\n      pFile->szChunk = *(int *)pArg;\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_SIZE_HINT: {\n      int rc;\n      SimulateIOErrorBenign(1);\n      rc = fcntlSizeHint(pFile, *(i64 *)pArg);\n      SimulateIOErrorBenign(0);\n      return rc;\n    }\n    case SQLITE_FCNTL_PERSIST_WAL: {\n      unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {\n      unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_VFSNAME: {\n      *(char**)pArg = sqlite3_mprintf(\"%s\", pFile->pVfs->zName);\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_TEMPFILENAME: {\n      char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );\n      if( zTFile ){\n        unixGetTempname(pFile->pVfs->mxPathname, zTFile);\n        *(char**)pArg = zTFile;\n      }\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_HAS_MOVED: {\n      *(int*)pArg = fileHasMoved(pFile);\n      return SQLITE_OK;\n    }\n#ifdef SQLITE_ENABLE_SETLK_TIMEOUT\n    case SQLITE_FCNTL_LOCK_TIMEOUT: {\n      int iOld = pFile->iBusyTimeout;\n      pFile->iBusyTimeout = *(int*)pArg;\n      *(int*)pArg = iOld;\n      return SQLITE_OK;\n    }\n#endif\n#if SQLITE_MAX_MMAP_SIZE>0\n    case SQLITE_FCNTL_MMAP_SIZE: {\n      i64 newLimit = *(i64*)pArg;\n      int rc = SQLITE_OK;\n      if( newLimit>sqlite3GlobalConfig.mxMmap ){\n        newLimit = sqlite3GlobalConfig.mxMmap;\n      }\n\n      /* The value of newLimit may be eventually cast to (size_t) and passed\n      ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a\n      ** 64-bit type. */\n      if( newLimit>0 && sizeof(size_t)<8 ){\n        newLimit = (newLimit & 0x7FFFFFFF);\n      }\n\n      *(i64*)pArg = pFile->mmapSizeMax;\n      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){\n        pFile->mmapSizeMax = newLimit;\n        if( pFile->mmapSize>0 ){\n          unixUnmapfile(pFile);\n          rc = unixMapfile(pFile, -1);\n        }\n      }\n      return rc;\n    }\n#endif\n#ifdef SQLITE_DEBUG\n    /* The pager calls this method to signal that it has done\n    ** a rollback and that the database is therefore unchanged and\n    ** it hence it is OK for the transaction change counter to be\n    ** unchanged.\n    */\n    case SQLITE_FCNTL_DB_UNCHANGED: {\n      ((unixFile*)id)->dbUpdate = 0;\n      return SQLITE_OK;\n    }\n#endif\n#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)\n    case SQLITE_FCNTL_SET_LOCKPROXYFILE:\n    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {\n      return proxyFileControl(id,op,pArg);\n    }\n#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */\n  }\n  return SQLITE_NOTFOUND;\n}\n\n/*\n** If pFd->sectorSize is non-zero when this function is called, it is a\n** no-op. Otherwise, the values of pFd->sectorSize and \n** pFd->deviceCharacteristics are set according to the file-system \n** characteristics. \n**\n** There are two versions of this function. One for QNX and one for all\n** other systems.\n*/\n#ifndef __QNXNTO__\nstatic void setDeviceCharacteristics(unixFile *pFd){\n  assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );\n  if( pFd->sectorSize==0 ){\n#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)\n    int res;\n    u32 f = 0;\n\n    /* Check for support for F2FS atomic batch writes. */\n    res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);\n    if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){\n      pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;\n    }\n#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */\n\n    /* Set the POWERSAFE_OVERWRITE flag if requested. */\n    if( pFd->ctrlFlags & UNIXFILE_PSOW ){\n      pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;\n    }\n\n    pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;\n  }\n}\n#else\n#include <sys/dcmd_blk.h>\n#include <sys/statvfs.h>\nstatic void setDeviceCharacteristics(unixFile *pFile){\n  if( pFile->sectorSize == 0 ){\n    struct statvfs fsInfo;\n       \n    /* Set defaults for non-supported filesystems */\n    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;\n    pFile->deviceCharacteristics = 0;\n    if( fstatvfs(pFile->h, &fsInfo) == -1 ) {\n      return;\n    }\n\n    if( !strcmp(fsInfo.f_basetype, \"tmp\") ) {\n      pFile->sectorSize = fsInfo.f_bsize;\n      pFile->deviceCharacteristics =\n        SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */\n        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until\n                                      ** the write succeeds */\n        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind\n                                      ** so it is ordered */\n        0;\n    }else if( strstr(fsInfo.f_basetype, \"etfs\") ){\n      pFile->sectorSize = fsInfo.f_bsize;\n      pFile->deviceCharacteristics =\n        /* etfs cluster size writes are atomic */\n        (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |\n        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until\n                                      ** the write succeeds */\n        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind\n                                      ** so it is ordered */\n        0;\n    }else if( !strcmp(fsInfo.f_basetype, \"qnx6\") ){\n      pFile->sectorSize = fsInfo.f_bsize;\n      pFile->deviceCharacteristics =\n        SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */\n        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until\n                                      ** the write succeeds */\n        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind\n                                      ** so it is ordered */\n        0;\n    }else if( !strcmp(fsInfo.f_basetype, \"qnx4\") ){\n      pFile->sectorSize = fsInfo.f_bsize;\n      pFile->deviceCharacteristics =\n        /* full bitset of atomics from max sector size and smaller */\n        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |\n        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind\n                                      ** so it is ordered */\n        0;\n    }else if( strstr(fsInfo.f_basetype, \"dos\") ){\n      pFile->sectorSize = fsInfo.f_bsize;\n      pFile->deviceCharacteristics =\n        /* full bitset of atomics from max sector size and smaller */\n        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |\n        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind\n                                      ** so it is ordered */\n        0;\n    }else{\n      pFile->deviceCharacteristics =\n        SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */\n        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until\n                                      ** the write succeeds */\n        0;\n    }\n  }\n  /* Last chance verification.  If the sector size isn't a multiple of 512\n  ** then it isn't valid.*/\n  if( pFile->sectorSize % 512 != 0 ){\n    pFile->deviceCharacteristics = 0;\n    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;\n  }\n}\n#endif\n\n/*\n** Return the sector size in bytes of the underlying block device for\n** the specified file. This is almost always 512 bytes, but may be\n** larger for some devices.\n**\n** SQLite code assumes this function cannot fail. It also assumes that\n** if two files are created in the same file-system directory (i.e.\n** a database and its journal file) that the sector size will be the\n** same for both.\n*/\nstatic int unixSectorSize(sqlite3_file *id){\n  unixFile *pFd = (unixFile*)id;\n  setDeviceCharacteristics(pFd);\n  return pFd->sectorSize;\n}\n\n/*\n** Return the device characteristics for the file.\n**\n** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.\n** However, that choice is controversial since technically the underlying\n** file system does not always provide powersafe overwrites.  (In other\n** words, after a power-loss event, parts of the file that were never\n** written might end up being altered.)  However, non-PSOW behavior is very,\n** very rare.  And asserting PSOW makes a large reduction in the amount\n** of required I/O for journaling, since a lot of padding is eliminated.\n**  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control\n** available to turn it off and URI query parameter available to turn it off.\n*/\nstatic int unixDeviceCharacteristics(sqlite3_file *id){\n  unixFile *pFd = (unixFile*)id;\n  setDeviceCharacteristics(pFd);\n  return pFd->deviceCharacteristics;\n}\n\n#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0\n\n/*\n** Return the system page size.\n**\n** This function should not be called directly by other code in this file. \n** Instead, it should be called via macro osGetpagesize().\n*/\nstatic int unixGetpagesize(void){\n#if OS_VXWORKS\n  return 1024;\n#elif defined(_BSD_SOURCE)\n  return getpagesize();\n#else\n  return (int)sysconf(_SC_PAGESIZE);\n#endif\n}\n\n#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */\n\n#ifndef SQLITE_OMIT_WAL\n\n/*\n** Object used to represent an shared memory buffer.  \n**\n** When multiple threads all reference the same wal-index, each thread\n** has its own unixShm object, but they all point to a single instance\n** of this unixShmNode object.  In other words, each wal-index is opened\n** only once per process.\n**\n** Each unixShmNode object is connected to a single unixInodeInfo object.\n** We could coalesce this object into unixInodeInfo, but that would mean\n** every open file that does not use shared memory (in other words, most\n** open files) would have to carry around this extra information.  So\n** the unixInodeInfo object contains a pointer to this unixShmNode object\n** and the unixShmNode object is created only when needed.\n**\n** unixMutexHeld() must be true when creating or destroying\n** this object or while reading or writing the following fields:\n**\n**      nRef\n**\n** The following fields are read-only after the object is created:\n** \n**      hShm\n**      zFilename\n**\n** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and\n** unixMutexHeld() is true when reading or writing any other field\n** in this structure.\n*/\nstruct unixShmNode {\n  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */\n  sqlite3_mutex *pShmMutex;  /* Mutex to access this object */\n  char *zFilename;           /* Name of the mmapped file */\n  int hShm;                  /* Open file descriptor */\n  int szRegion;              /* Size of shared-memory regions */\n  u16 nRegion;               /* Size of array apRegion */\n  u8 isReadonly;             /* True if read-only */\n  u8 isUnlocked;             /* True if no DMS lock held */\n  char **apRegion;           /* Array of mapped shared-memory regions */\n  int nRef;                  /* Number of unixShm objects pointing to this */\n  unixShm *pFirst;           /* All unixShm objects pointing to this */\n#ifdef SQLITE_DEBUG\n  u8 exclMask;               /* Mask of exclusive locks held */\n  u8 sharedMask;             /* Mask of shared locks held */\n  u8 nextShmId;              /* Next available unixShm.id value */\n#endif\n};\n\n/*\n** Structure used internally by this VFS to record the state of an\n** open shared memory connection.\n**\n** The following fields are initialized when this object is created and\n** are read-only thereafter:\n**\n**    unixShm.pShmNode\n**    unixShm.id\n**\n** All other fields are read/write.  The unixShm.pShmNode->pShmMutex must\n** be held while accessing any read/write fields.\n*/\nstruct unixShm {\n  unixShmNode *pShmNode;     /* The underlying unixShmNode object */\n  unixShm *pNext;            /* Next unixShm with the same unixShmNode */\n  u8 hasMutex;               /* True if holding the unixShmNode->pShmMutex */\n  u8 id;                     /* Id of this connection within its unixShmNode */\n  u16 sharedMask;            /* Mask of shared locks held */\n  u16 exclMask;              /* Mask of exclusive locks held */\n};\n\n/*\n** Constants used for locking\n*/\n#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */\n#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */\n\n/*\n** Apply posix advisory locks for all bytes from ofst through ofst+n-1.\n**\n** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking\n** otherwise.\n*/\nstatic int unixShmSystemLock(\n  unixFile *pFile,       /* Open connection to the WAL file */\n  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */\n  int ofst,              /* First byte of the locking range */\n  int n                  /* Number of bytes to lock */\n){\n  unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */\n  struct flock f;        /* The posix advisory locking structure */\n  int rc = SQLITE_OK;    /* Result code form fcntl() */\n\n  /* Access to the unixShmNode object is serialized by the caller */\n  pShmNode = pFile->pInode->pShmNode;\n  assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );\n  assert( pShmNode->nRef>0 || unixMutexHeld() );\n\n  /* Shared locks never span more than one byte */\n  assert( n==1 || lockType!=F_RDLCK );\n\n  /* Locks are within range */\n  assert( n>=1 && n<=SQLITE_SHM_NLOCK );\n\n  if( pShmNode->hShm>=0 ){\n    int res;\n    /* Initialize the locking parameters */\n    f.l_type = lockType;\n    f.l_whence = SEEK_SET;\n    f.l_start = ofst;\n    f.l_len = n;\n    res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);\n    if( res==-1 ){\n#ifdef SQLITE_ENABLE_SETLK_TIMEOUT\n      rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY);\n#else\n      rc = SQLITE_BUSY;\n#endif\n    }\n  }\n\n  /* Update the global lock state and do debug tracing */\n#ifdef SQLITE_DEBUG\n  { u16 mask;\n  OSTRACE((\"SHM-LOCK \"));\n  mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);\n  if( rc==SQLITE_OK ){\n    if( lockType==F_UNLCK ){\n      OSTRACE((\"unlock %d ok\", ofst));\n      pShmNode->exclMask &= ~mask;\n      pShmNode->sharedMask &= ~mask;\n    }else if( lockType==F_RDLCK ){\n      OSTRACE((\"read-lock %d ok\", ofst));\n      pShmNode->exclMask &= ~mask;\n      pShmNode->sharedMask |= mask;\n    }else{\n      assert( lockType==F_WRLCK );\n      OSTRACE((\"write-lock %d ok\", ofst));\n      pShmNode->exclMask |= mask;\n      pShmNode->sharedMask &= ~mask;\n    }\n  }else{\n    if( lockType==F_UNLCK ){\n      OSTRACE((\"unlock %d failed\", ofst));\n    }else if( lockType==F_RDLCK ){\n      OSTRACE((\"read-lock failed\"));\n    }else{\n      assert( lockType==F_WRLCK );\n      OSTRACE((\"write-lock %d failed\", ofst));\n    }\n  }\n  OSTRACE((\" - afterwards %03x,%03x\\n\",\n           pShmNode->sharedMask, pShmNode->exclMask));\n  }\n#endif\n\n  return rc;        \n}\n\n/*\n** Return the minimum number of 32KB shm regions that should be mapped at\n** a time, assuming that each mapping must be an integer multiple of the\n** current system page-size.\n**\n** Usually, this is 1. The exception seems to be systems that are configured\n** to use 64KB pages - in this case each mapping must cover at least two\n** shm regions.\n*/\nstatic int unixShmRegionPerMap(void){\n  int shmsz = 32*1024;            /* SHM region size */\n  int pgsz = osGetpagesize();   /* System page size */\n  assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */\n  if( pgsz<shmsz ) return 1;\n  return pgsz/shmsz;\n}\n\n/*\n** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.\n**\n** This is not a VFS shared-memory method; it is a utility function called\n** by VFS shared-memory methods.\n*/\nstatic void unixShmPurge(unixFile *pFd){\n  unixShmNode *p = pFd->pInode->pShmNode;\n  assert( unixMutexHeld() );\n  if( p && ALWAYS(p->nRef==0) ){\n    int nShmPerMap = unixShmRegionPerMap();\n    int i;\n    assert( p->pInode==pFd->pInode );\n    sqlite3_mutex_free(p->pShmMutex);\n    for(i=0; i<p->nRegion; i+=nShmPerMap){\n      if( p->hShm>=0 ){\n        osMunmap(p->apRegion[i], p->szRegion);\n      }else{\n        sqlite3_free(p->apRegion[i]);\n      }\n    }\n    sqlite3_free(p->apRegion);\n    if( p->hShm>=0 ){\n      robust_close(pFd, p->hShm, __LINE__);\n      p->hShm = -1;\n    }\n    p->pInode->pShmNode = 0;\n    sqlite3_free(p);\n  }\n}\n\n/*\n** The DMS lock has not yet been taken on shm file pShmNode. Attempt to\n** take it now. Return SQLITE_OK if successful, or an SQLite error\n** code otherwise.\n**\n** If the DMS cannot be locked because this is a readonly_shm=1 \n** connection and no other process already holds a lock, return\n** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.\n*/\nstatic int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){\n  struct flock lock;\n  int rc = SQLITE_OK;\n\n  /* Use F_GETLK to determine the locks other processes are holding\n  ** on the DMS byte. If it indicates that another process is holding\n  ** a SHARED lock, then this process may also take a SHARED lock\n  ** and proceed with opening the *-shm file. \n  **\n  ** Or, if no other process is holding any lock, then this process\n  ** is the first to open it. In this case take an EXCLUSIVE lock on the\n  ** DMS byte and truncate the *-shm file to zero bytes in size. Then\n  ** downgrade to a SHARED lock on the DMS byte.\n  **\n  ** If another process is holding an EXCLUSIVE lock on the DMS byte,\n  ** return SQLITE_BUSY to the caller (it will try again). An earlier\n  ** version of this code attempted the SHARED lock at this point. But\n  ** this introduced a subtle race condition: if the process holding\n  ** EXCLUSIVE failed just before truncating the *-shm file, then this\n  ** process might open and use the *-shm file without truncating it.\n  ** And if the *-shm file has been corrupted by a power failure or\n  ** system crash, the database itself may also become corrupt.  */\n  lock.l_whence = SEEK_SET;\n  lock.l_start = UNIX_SHM_DMS;\n  lock.l_len = 1;\n  lock.l_type = F_WRLCK;\n  if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {\n    rc = SQLITE_IOERR_LOCK;\n  }else if( lock.l_type==F_UNLCK ){\n    if( pShmNode->isReadonly ){\n      pShmNode->isUnlocked = 1;\n      rc = SQLITE_READONLY_CANTINIT;\n    }else{\n      rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);\n      /* The first connection to attach must truncate the -shm file.  We\n      ** truncate to 3 bytes (an arbitrary small number, less than the\n      ** -shm header size) rather than 0 as a system debugging aid, to\n      ** help detect if a -shm file truncation is legitimate or is the work\n      ** or a rogue process. */\n      if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){\n        rc = unixLogError(SQLITE_IOERR_SHMOPEN,\"ftruncate\",pShmNode->zFilename);\n      }\n    }\n  }else if( lock.l_type==F_WRLCK ){\n    rc = SQLITE_BUSY;\n  }\n\n  if( rc==SQLITE_OK ){\n    assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );\n    rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);\n  }\n  return rc;\n}\n\n/*\n** Open a shared-memory area associated with open database file pDbFd.  \n** This particular implementation uses mmapped files.\n**\n** The file used to implement shared-memory is in the same directory\n** as the open database file and has the same name as the open database\n** file with the \"-shm\" suffix added.  For example, if the database file\n** is \"/home/user1/config.db\" then the file that is created and mmapped\n** for shared memory will be called \"/home/user1/config.db-shm\".  \n**\n** Another approach to is to use files in /dev/shm or /dev/tmp or an\n** some other tmpfs mount. But if a file in a different directory\n** from the database file is used, then differing access permissions\n** or a chroot() might cause two different processes on the same\n** database to end up using different files for shared memory - \n** meaning that their memory would not really be shared - resulting\n** in database corruption.  Nevertheless, this tmpfs file usage\n** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY=\"/dev/shm\"\n** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time\n** option results in an incompatible build of SQLite;  builds of SQLite\n** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the\n** same database file at the same time, database corruption will likely\n** result. The SQLITE_SHM_DIRECTORY compile-time option is considered\n** \"unsupported\" and may go away in a future SQLite release.\n**\n** When opening a new shared-memory file, if no other instances of that\n** file are currently open, in this process or in other processes, then\n** the file must be truncated to zero length or have its header cleared.\n**\n** If the original database file (pDbFd) is using the \"unix-excl\" VFS\n** that means that an exclusive lock is held on the database file and\n** that no other processes are able to read or write the database.  In\n** that case, we do not really need shared memory.  No shared memory\n** file is created.  The shared memory will be simulated with heap memory.\n*/\nstatic int unixOpenSharedMemory(unixFile *pDbFd){\n  struct unixShm *p = 0;          /* The connection to be opened */\n  struct unixShmNode *pShmNode;   /* The underlying mmapped file */\n  int rc = SQLITE_OK;             /* Result code */\n  unixInodeInfo *pInode;          /* The inode of fd */\n  char *zShm;             /* Name of the file used for SHM */\n  int nShmFilename;               /* Size of the SHM filename in bytes */\n\n  /* Allocate space for the new unixShm object. */\n  p = sqlite3_malloc64( sizeof(*p) );\n  if( p==0 ) return SQLITE_NOMEM_BKPT;\n  memset(p, 0, sizeof(*p));\n  assert( pDbFd->pShm==0 );\n\n  /* Check to see if a unixShmNode object already exists. Reuse an existing\n  ** one if present. Create a new one if necessary.\n  */\n  assert( unixFileMutexNotheld(pDbFd) );\n  unixEnterMutex();\n  pInode = pDbFd->pInode;\n  pShmNode = pInode->pShmNode;\n  if( pShmNode==0 ){\n    struct stat sStat;                 /* fstat() info for database file */\n#ifndef SQLITE_SHM_DIRECTORY\n    const char *zBasePath = pDbFd->zPath;\n#endif\n\n    /* Call fstat() to figure out the permissions on the database file. If\n    ** a new *-shm file is created, an attempt will be made to create it\n    ** with the same permissions.\n    */\n    if( osFstat(pDbFd->h, &sStat) ){\n      rc = SQLITE_IOERR_FSTAT;\n      goto shm_open_err;\n    }\n\n#ifdef SQLITE_SHM_DIRECTORY\n    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;\n#else\n    nShmFilename = 6 + (int)strlen(zBasePath);\n#endif\n    pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );\n    if( pShmNode==0 ){\n      rc = SQLITE_NOMEM_BKPT;\n      goto shm_open_err;\n    }\n    memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);\n    zShm = pShmNode->zFilename = (char*)&pShmNode[1];\n#ifdef SQLITE_SHM_DIRECTORY\n    sqlite3_snprintf(nShmFilename, zShm, \n                     SQLITE_SHM_DIRECTORY \"/sqlite-shm-%x-%x\",\n                     (u32)sStat.st_ino, (u32)sStat.st_dev);\n#else\n    sqlite3_snprintf(nShmFilename, zShm, \"%s-shm\", zBasePath);\n    sqlite3FileSuffix3(pDbFd->zPath, zShm);\n#endif\n    pShmNode->hShm = -1;\n    pDbFd->pInode->pShmNode = pShmNode;\n    pShmNode->pInode = pDbFd->pInode;\n    if( sqlite3GlobalConfig.bCoreMutex ){\n      pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);\n      if( pShmNode->pShmMutex==0 ){\n        rc = SQLITE_NOMEM_BKPT;\n        goto shm_open_err;\n      }\n    }\n\n    if( pInode->bProcessLock==0 ){\n      if( 0==sqlite3_uri_boolean(pDbFd->zPath, \"readonly_shm\", 0) ){\n        pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW,\n                                     (sStat.st_mode&0777));\n      }\n      if( pShmNode->hShm<0 ){\n        pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW,\n                                     (sStat.st_mode&0777));\n        if( pShmNode->hShm<0 ){\n          rc = unixLogError(SQLITE_CANTOPEN_BKPT, \"open\", zShm);\n          goto shm_open_err;\n        }\n        pShmNode->isReadonly = 1;\n      }\n\n      /* If this process is running as root, make sure that the SHM file\n      ** is owned by the same user that owns the original database.  Otherwise,\n      ** the original owner will not be able to connect.\n      */\n      robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);\n\n      rc = unixLockSharedMemory(pDbFd, pShmNode);\n      if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;\n    }\n  }\n\n  /* Make the new connection a child of the unixShmNode */\n  p->pShmNode = pShmNode;\n#ifdef SQLITE_DEBUG\n  p->id = pShmNode->nextShmId++;\n#endif\n  pShmNode->nRef++;\n  pDbFd->pShm = p;\n  unixLeaveMutex();\n\n  /* The reference count on pShmNode has already been incremented under\n  ** the cover of the unixEnterMutex() mutex and the pointer from the\n  ** new (struct unixShm) object to the pShmNode has been set. All that is\n  ** left to do is to link the new object into the linked list starting\n  ** at pShmNode->pFirst. This must be done while holding the\n  ** pShmNode->pShmMutex.\n  */\n  sqlite3_mutex_enter(pShmNode->pShmMutex);\n  p->pNext = pShmNode->pFirst;\n  pShmNode->pFirst = p;\n  sqlite3_mutex_leave(pShmNode->pShmMutex);\n  return rc;\n\n  /* Jump here on any error */\nshm_open_err:\n  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */\n  sqlite3_free(p);\n  unixLeaveMutex();\n  return rc;\n}\n\n/*\n** This function is called to obtain a pointer to region iRegion of the \n** shared-memory associated with the database file fd. Shared-memory regions \n** are numbered starting from zero. Each shared-memory region is szRegion \n** bytes in size.\n**\n** If an error occurs, an error code is returned and *pp is set to NULL.\n**\n** Otherwise, if the bExtend parameter is 0 and the requested shared-memory\n** region has not been allocated (by any client, including one running in a\n** separate process), then *pp is set to NULL and SQLITE_OK returned. If \n** bExtend is non-zero and the requested shared-memory region has not yet \n** been allocated, it is allocated by this function.\n**\n** If the shared-memory region has already been allocated or is allocated by\n** this call as described above, then it is mapped into this processes \n** address space (if it is not already), *pp is set to point to the mapped \n** memory and SQLITE_OK returned.\n*/\nstatic int unixShmMap(\n  sqlite3_file *fd,               /* Handle open on database file */\n  int iRegion,                    /* Region to retrieve */\n  int szRegion,                   /* Size of regions */\n  int bExtend,                    /* True to extend file if necessary */\n  void volatile **pp              /* OUT: Mapped memory */\n){\n  unixFile *pDbFd = (unixFile*)fd;\n  unixShm *p;\n  unixShmNode *pShmNode;\n  int rc = SQLITE_OK;\n  int nShmPerMap = unixShmRegionPerMap();\n  int nReqRegion;\n\n  /* If the shared-memory file has not yet been opened, open it now. */\n  if( pDbFd->pShm==0 ){\n    rc = unixOpenSharedMemory(pDbFd);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n\n  p = pDbFd->pShm;\n  pShmNode = p->pShmNode;\n  sqlite3_mutex_enter(pShmNode->pShmMutex);\n  if( pShmNode->isUnlocked ){\n    rc = unixLockSharedMemory(pDbFd, pShmNode);\n    if( rc!=SQLITE_OK ) goto shmpage_out;\n    pShmNode->isUnlocked = 0;\n  }\n  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );\n  assert( pShmNode->pInode==pDbFd->pInode );\n  assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );\n  assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );\n\n  /* Minimum number of regions required to be mapped. */\n  nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;\n\n  if( pShmNode->nRegion<nReqRegion ){\n    char **apNew;                      /* New apRegion[] array */\n    int nByte = nReqRegion*szRegion;   /* Minimum required file size */\n    struct stat sStat;                 /* Used by fstat() */\n\n    pShmNode->szRegion = szRegion;\n\n    if( pShmNode->hShm>=0 ){\n      /* The requested region is not mapped into this processes address space.\n      ** Check to see if it has been allocated (i.e. if the wal-index file is\n      ** large enough to contain the requested region).\n      */\n      if( osFstat(pShmNode->hShm, &sStat) ){\n        rc = SQLITE_IOERR_SHMSIZE;\n        goto shmpage_out;\n      }\n  \n      if( sStat.st_size<nByte ){\n        /* The requested memory region does not exist. If bExtend is set to\n        ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.\n        */\n        if( !bExtend ){\n          goto shmpage_out;\n        }\n\n        /* Alternatively, if bExtend is true, extend the file. Do this by\n        ** writing a single byte to the end of each (OS) page being\n        ** allocated or extended. Technically, we need only write to the\n        ** last page in order to extend the file. But writing to all new\n        ** pages forces the OS to allocate them immediately, which reduces\n        ** the chances of SIGBUS while accessing the mapped region later on.\n        */\n        else{\n          static const int pgsz = 4096;\n          int iPg;\n\n          /* Write to the last byte of each newly allocated or extended page */\n          assert( (nByte % pgsz)==0 );\n          for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){\n            int x = 0;\n            if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,\"\",1,&x)!=1 ){\n              const char *zFile = pShmNode->zFilename;\n              rc = unixLogError(SQLITE_IOERR_SHMSIZE, \"write\", zFile);\n              goto shmpage_out;\n            }\n          }\n        }\n      }\n    }\n\n    /* Map the requested memory region into this processes address space. */\n    apNew = (char **)sqlite3_realloc(\n        pShmNode->apRegion, nReqRegion*sizeof(char *)\n    );\n    if( !apNew ){\n      rc = SQLITE_IOERR_NOMEM_BKPT;\n      goto shmpage_out;\n    }\n    pShmNode->apRegion = apNew;\n    while( pShmNode->nRegion<nReqRegion ){\n      int nMap = szRegion*nShmPerMap;\n      int i;\n      void *pMem;\n      if( pShmNode->hShm>=0 ){\n        pMem = osMmap(0, nMap,\n            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, \n            MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion\n        );\n        if( pMem==MAP_FAILED ){\n          rc = unixLogError(SQLITE_IOERR_SHMMAP, \"mmap\", pShmNode->zFilename);\n          goto shmpage_out;\n        }\n      }else{\n        pMem = sqlite3_malloc64(nMap);\n        if( pMem==0 ){\n          rc = SQLITE_NOMEM_BKPT;\n          goto shmpage_out;\n        }\n        memset(pMem, 0, nMap);\n      }\n\n      for(i=0; i<nShmPerMap; i++){\n        pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];\n      }\n      pShmNode->nRegion += nShmPerMap;\n    }\n  }\n\nshmpage_out:\n  if( pShmNode->nRegion>iRegion ){\n    *pp = pShmNode->apRegion[iRegion];\n  }else{\n    *pp = 0;\n  }\n  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;\n  sqlite3_mutex_leave(pShmNode->pShmMutex);\n  return rc;\n}\n\n/*\n** Change the lock state for a shared-memory segment.\n**\n** Note that the relationship between SHAREd and EXCLUSIVE locks is a little\n** different here than in posix.  In xShmLock(), one can go from unlocked\n** to shared and back or from unlocked to exclusive and back.  But one may\n** not go from shared to exclusive or from exclusive to shared.\n*/\nstatic int unixShmLock(\n  sqlite3_file *fd,          /* Database file holding the shared memory */\n  int ofst,                  /* First lock to acquire or release */\n  int n,                     /* Number of locks to acquire or release */\n  int flags                  /* What to do with the lock */\n){\n  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */\n  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */\n  unixShm *pX;                          /* For looping over all siblings */\n  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */\n  int rc = SQLITE_OK;                   /* Result code */\n  u16 mask;                             /* Mask of locks to take or release */\n\n  assert( pShmNode==pDbFd->pInode->pShmNode );\n  assert( pShmNode->pInode==pDbFd->pInode );\n  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );\n  assert( n>=1 );\n  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)\n       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)\n       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)\n       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );\n  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );\n  assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );\n  assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );\n\n  /* Check that, if this to be a blocking lock, no locks that occur later\n  ** in the following list than the lock being obtained are already held:\n  **\n  **   1. Checkpointer lock (ofst==1).\n  **   2. Write lock (ofst==0).\n  **   3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).\n  **\n  ** In other words, if this is a blocking lock, none of the locks that\n  ** occur later in the above list than the lock being obtained may be\n  ** held.  */\n#ifdef SQLITE_ENABLE_SETLK_TIMEOUT\n  assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (\n         (ofst!=2)                                   /* not RECOVER */\n      && (ofst!=1 || (p->exclMask|p->sharedMask)==0)\n      && (ofst!=0 || (p->exclMask|p->sharedMask)<3)\n      && (ofst<3  || (p->exclMask|p->sharedMask)<(1<<ofst))\n  ));\n#endif\n\n  mask = (1<<(ofst+n)) - (1<<ofst);\n  assert( n>1 || mask==(1<<ofst) );\n  sqlite3_mutex_enter(pShmNode->pShmMutex);\n  if( flags & SQLITE_SHM_UNLOCK ){\n    u16 allMask = 0; /* Mask of locks held by siblings */\n\n    /* See if any siblings hold this same lock */\n    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){\n      if( pX==p ) continue;\n      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );\n      allMask |= pX->sharedMask;\n    }\n\n    /* Unlock the system-level locks */\n    if( (mask & allMask)==0 ){\n      rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);\n    }else{\n      rc = SQLITE_OK;\n    }\n\n    /* Undo the local locks */\n    if( rc==SQLITE_OK ){\n      p->exclMask &= ~mask;\n      p->sharedMask &= ~mask;\n    } \n  }else if( flags & SQLITE_SHM_SHARED ){\n    u16 allShared = 0;  /* Union of locks held by connections other than \"p\" */\n\n    /* Find out which shared locks are already held by sibling connections.\n    ** If any sibling already holds an exclusive lock, go ahead and return\n    ** SQLITE_BUSY.\n    */\n    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){\n      if( (pX->exclMask & mask)!=0 ){\n        rc = SQLITE_BUSY;\n        break;\n      }\n      allShared |= pX->sharedMask;\n    }\n\n    /* Get shared locks at the system level, if necessary */\n    if( rc==SQLITE_OK ){\n      if( (allShared & mask)==0 ){\n        rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);\n      }else{\n        rc = SQLITE_OK;\n      }\n    }\n\n    /* Get the local shared locks */\n    if( rc==SQLITE_OK ){\n      p->sharedMask |= mask;\n    }\n  }else{\n    /* Make sure no sibling connections hold locks that will block this\n    ** lock.  If any do, return SQLITE_BUSY right away.\n    */\n    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){\n      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){\n        rc = SQLITE_BUSY;\n        break;\n      }\n    }\n  \n    /* Get the exclusive locks at the system level.  Then if successful\n    ** also mark the local connection as being locked.\n    */\n    if( rc==SQLITE_OK ){\n      rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);\n      if( rc==SQLITE_OK ){\n        assert( (p->sharedMask & mask)==0 );\n        p->exclMask |= mask;\n      }\n    }\n  }\n  sqlite3_mutex_leave(pShmNode->pShmMutex);\n  OSTRACE((\"SHM-LOCK shmid-%d, pid-%d got %03x,%03x\\n\",\n           p->id, osGetpid(0), p->sharedMask, p->exclMask));\n  return rc;\n}\n\n/*\n** Implement a memory barrier or memory fence on shared memory.  \n**\n** All loads and stores begun before the barrier must complete before\n** any load or store begun after the barrier.\n*/\nstatic void unixShmBarrier(\n  sqlite3_file *fd                /* Database file holding the shared memory */\n){\n  UNUSED_PARAMETER(fd);\n  sqlite3MemoryBarrier();         /* compiler-defined memory barrier */\n  assert( fd->pMethods->xLock==nolockLock \n       || unixFileMutexNotheld((unixFile*)fd) \n  );\n  unixEnterMutex();               /* Also mutex, for redundancy */\n  unixLeaveMutex();\n}\n\n/*\n** Close a connection to shared-memory.  Delete the underlying \n** storage if deleteFlag is true.\n**\n** If there is no shared memory associated with the connection then this\n** routine is a harmless no-op.\n*/\nstatic int unixShmUnmap(\n  sqlite3_file *fd,               /* The underlying database file */\n  int deleteFlag                  /* Delete shared-memory if true */\n){\n  unixShm *p;                     /* The connection to be closed */\n  unixShmNode *pShmNode;          /* The underlying shared-memory file */\n  unixShm **pp;                   /* For looping over sibling connections */\n  unixFile *pDbFd;                /* The underlying database file */\n\n  pDbFd = (unixFile*)fd;\n  p = pDbFd->pShm;\n  if( p==0 ) return SQLITE_OK;\n  pShmNode = p->pShmNode;\n\n  assert( pShmNode==pDbFd->pInode->pShmNode );\n  assert( pShmNode->pInode==pDbFd->pInode );\n\n  /* Remove connection p from the set of connections associated\n  ** with pShmNode */\n  sqlite3_mutex_enter(pShmNode->pShmMutex);\n  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}\n  *pp = p->pNext;\n\n  /* Free the connection p */\n  sqlite3_free(p);\n  pDbFd->pShm = 0;\n  sqlite3_mutex_leave(pShmNode->pShmMutex);\n\n  /* If pShmNode->nRef has reached 0, then close the underlying\n  ** shared-memory file, too */\n  assert( unixFileMutexNotheld(pDbFd) );\n  unixEnterMutex();\n  assert( pShmNode->nRef>0 );\n  pShmNode->nRef--;\n  if( pShmNode->nRef==0 ){\n    if( deleteFlag && pShmNode->hShm>=0 ){\n      osUnlink(pShmNode->zFilename);\n    }\n    unixShmPurge(pDbFd);\n  }\n  unixLeaveMutex();\n\n  return SQLITE_OK;\n}\n\n\n#else\n# define unixShmMap     0\n# define unixShmLock    0\n# define unixShmBarrier 0\n# define unixShmUnmap   0\n#endif /* #ifndef SQLITE_OMIT_WAL */\n\n#if SQLITE_MAX_MMAP_SIZE>0\n/*\n** If it is currently memory mapped, unmap file pFd.\n*/\nstatic void unixUnmapfile(unixFile *pFd){\n  assert( pFd->nFetchOut==0 );\n  if( pFd->pMapRegion ){\n    osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);\n    pFd->pMapRegion = 0;\n    pFd->mmapSize = 0;\n    pFd->mmapSizeActual = 0;\n  }\n}\n\n/*\n** Attempt to set the size of the memory mapping maintained by file \n** descriptor pFd to nNew bytes. Any existing mapping is discarded.\n**\n** If successful, this function sets the following variables:\n**\n**       unixFile.pMapRegion\n**       unixFile.mmapSize\n**       unixFile.mmapSizeActual\n**\n** If unsuccessful, an error message is logged via sqlite3_log() and\n** the three variables above are zeroed. In this case SQLite should\n** continue accessing the database using the xRead() and xWrite()\n** methods.\n*/\nstatic void unixRemapfile(\n  unixFile *pFd,                  /* File descriptor object */\n  i64 nNew                        /* Required mapping size */\n){\n  const char *zErr = \"mmap\";\n  int h = pFd->h;                      /* File descriptor open on db file */\n  u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */\n  i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */\n  u8 *pNew = 0;                        /* Location of new mapping */\n  int flags = PROT_READ;               /* Flags to pass to mmap() */\n\n  assert( pFd->nFetchOut==0 );\n  assert( nNew>pFd->mmapSize );\n  assert( nNew<=pFd->mmapSizeMax );\n  assert( nNew>0 );\n  assert( pFd->mmapSizeActual>=pFd->mmapSize );\n  assert( MAP_FAILED!=0 );\n\n#ifdef SQLITE_MMAP_READWRITE\n  if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;\n#endif\n\n  if( pOrig ){\n#if HAVE_MREMAP\n    i64 nReuse = pFd->mmapSize;\n#else\n    const int szSyspage = osGetpagesize();\n    i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));\n#endif\n    u8 *pReq = &pOrig[nReuse];\n\n    /* Unmap any pages of the existing mapping that cannot be reused. */\n    if( nReuse!=nOrig ){\n      osMunmap(pReq, nOrig-nReuse);\n    }\n\n#if HAVE_MREMAP\n    pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);\n    zErr = \"mremap\";\n#else\n    pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);\n    if( pNew!=MAP_FAILED ){\n      if( pNew!=pReq ){\n        osMunmap(pNew, nNew - nReuse);\n        pNew = 0;\n      }else{\n        pNew = pOrig;\n      }\n    }\n#endif\n\n    /* The attempt to extend the existing mapping failed. Free it. */\n    if( pNew==MAP_FAILED || pNew==0 ){\n      osMunmap(pOrig, nReuse);\n    }\n  }\n\n  /* If pNew is still NULL, try to create an entirely new mapping. */\n  if( pNew==0 ){\n    pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);\n  }\n\n  if( pNew==MAP_FAILED ){\n    pNew = 0;\n    nNew = 0;\n    unixLogError(SQLITE_OK, zErr, pFd->zPath);\n\n    /* If the mmap() above failed, assume that all subsequent mmap() calls\n    ** will probably fail too. Fall back to using xRead/xWrite exclusively\n    ** in this case.  */\n    pFd->mmapSizeMax = 0;\n  }\n  pFd->pMapRegion = (void *)pNew;\n  pFd->mmapSize = pFd->mmapSizeActual = nNew;\n}\n\n/*\n** Memory map or remap the file opened by file-descriptor pFd (if the file\n** is already mapped, the existing mapping is replaced by the new). Or, if \n** there already exists a mapping for this file, and there are still \n** outstanding xFetch() references to it, this function is a no-op.\n**\n** If parameter nByte is non-negative, then it is the requested size of \n** the mapping to create. Otherwise, if nByte is less than zero, then the \n** requested size is the size of the file on disk. The actual size of the\n** created mapping is either the requested size or the value configured \n** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.\n**\n** SQLITE_OK is returned if no error occurs (even if the mapping is not\n** recreated as a result of outstanding references) or an SQLite error\n** code otherwise.\n*/\nstatic int unixMapfile(unixFile *pFd, i64 nMap){\n  assert( nMap>=0 || pFd->nFetchOut==0 );\n  assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );\n  if( pFd->nFetchOut>0 ) return SQLITE_OK;\n\n  if( nMap<0 ){\n    struct stat statbuf;          /* Low-level file information */\n    if( osFstat(pFd->h, &statbuf) ){\n      return SQLITE_IOERR_FSTAT;\n    }\n    nMap = statbuf.st_size;\n  }\n  if( nMap>pFd->mmapSizeMax ){\n    nMap = pFd->mmapSizeMax;\n  }\n\n  assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );\n  if( nMap!=pFd->mmapSize ){\n    unixRemapfile(pFd, nMap);\n  }\n\n  return SQLITE_OK;\n}\n#endif /* SQLITE_MAX_MMAP_SIZE>0 */\n\n/*\n** If possible, return a pointer to a mapping of file fd starting at offset\n** iOff. The mapping must be valid for at least nAmt bytes.\n**\n** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.\n** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.\n** Finally, if an error does occur, return an SQLite error code. The final\n** value of *pp is undefined in this case.\n**\n** If this function does return a pointer, the caller must eventually \n** release the reference by calling unixUnfetch().\n*/\nstatic int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){\n#if SQLITE_MAX_MMAP_SIZE>0\n  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */\n#endif\n  *pp = 0;\n\n#if SQLITE_MAX_MMAP_SIZE>0\n  if( pFd->mmapSizeMax>0 ){\n    if( pFd->pMapRegion==0 ){\n      int rc = unixMapfile(pFd, -1);\n      if( rc!=SQLITE_OK ) return rc;\n    }\n    if( pFd->mmapSize >= iOff+nAmt ){\n      *pp = &((u8 *)pFd->pMapRegion)[iOff];\n      pFd->nFetchOut++;\n    }\n  }\n#endif\n  return SQLITE_OK;\n}\n\n/*\n** If the third argument is non-NULL, then this function releases a \n** reference obtained by an earlier call to unixFetch(). The second\n** argument passed to this function must be the same as the corresponding\n** argument that was passed to the unixFetch() invocation. \n**\n** Or, if the third argument is NULL, then this function is being called \n** to inform the VFS layer that, according to POSIX, any existing mapping \n** may now be invalid and should be unmapped.\n*/\nstatic int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){\n#if SQLITE_MAX_MMAP_SIZE>0\n  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */\n  UNUSED_PARAMETER(iOff);\n\n  /* If p==0 (unmap the entire file) then there must be no outstanding \n  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),\n  ** then there must be at least one outstanding.  */\n  assert( (p==0)==(pFd->nFetchOut==0) );\n\n  /* If p!=0, it must match the iOff value. */\n  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );\n\n  if( p ){\n    pFd->nFetchOut--;\n  }else{\n    unixUnmapfile(pFd);\n  }\n\n  assert( pFd->nFetchOut>=0 );\n#else\n  UNUSED_PARAMETER(fd);\n  UNUSED_PARAMETER(p);\n  UNUSED_PARAMETER(iOff);\n#endif\n  return SQLITE_OK;\n}\n\n/*\n** Here ends the implementation of all sqlite3_file methods.\n**\n********************** End sqlite3_file Methods *******************************\n******************************************************************************/\n\n/*\n** This division contains definitions of sqlite3_io_methods objects that\n** implement various file locking strategies.  It also contains definitions\n** of \"finder\" functions.  A finder-function is used to locate the appropriate\n** sqlite3_io_methods object for a particular database file.  The pAppData\n** field of the sqlite3_vfs VFS objects are initialized to be pointers to\n** the correct finder-function for that VFS.\n**\n** Most finder functions return a pointer to a fixed sqlite3_io_methods\n** object.  The only interesting finder-function is autolockIoFinder, which\n** looks at the filesystem type and tries to guess the best locking\n** strategy from that.\n**\n** For finder-function F, two objects are created:\n**\n**    (1) The real finder-function named \"FImpt()\".\n**\n**    (2) A constant pointer to this function named just \"F\".\n**\n**\n** A pointer to the F pointer is used as the pAppData value for VFS\n** objects.  We have to do this instead of letting pAppData point\n** directly at the finder-function since C90 rules prevent a void*\n** from be cast into a function pointer.\n**\n**\n** Each instance of this macro generates two objects:\n**\n**   *  A constant sqlite3_io_methods object call METHOD that has locking\n**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.\n**\n**   *  An I/O method finder function called FINDER that returns a pointer\n**      to the METHOD object in the previous bullet.\n*/\n#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP)     \\\nstatic const sqlite3_io_methods METHOD = {                                   \\\n   VERSION,                    /* iVersion */                                \\\n   CLOSE,                      /* xClose */                                  \\\n   unixRead,                   /* xRead */                                   \\\n   unixWrite,                  /* xWrite */                                  \\\n   unixTruncate,               /* xTruncate */                               \\\n   unixSync,                   /* xSync */                                   \\\n   unixFileSize,               /* xFileSize */                               \\\n   LOCK,                       /* xLock */                                   \\\n   UNLOCK,                     /* xUnlock */                                 \\\n   CKLOCK,                     /* xCheckReservedLock */                      \\\n   unixFileControl,            /* xFileControl */                            \\\n   unixSectorSize,             /* xSectorSize */                             \\\n   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \\\n   SHMMAP,                     /* xShmMap */                                 \\\n   unixShmLock,                /* xShmLock */                                \\\n   unixShmBarrier,             /* xShmBarrier */                             \\\n   unixShmUnmap,               /* xShmUnmap */                               \\\n   unixFetch,                  /* xFetch */                                  \\\n   unixUnfetch,                /* xUnfetch */                                \\\n};                                                                           \\\nstatic const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \\\n  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \\\n  return &METHOD;                                                            \\\n}                                                                            \\\nstatic const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \\\n    = FINDER##Impl;\n\n/*\n** Here are all of the sqlite3_io_methods objects for each of the\n** locking strategies.  Functions that return pointers to these methods\n** are also created.\n*/\nIOMETHODS(\n  posixIoFinder,            /* Finder function name */\n  posixIoMethods,           /* sqlite3_io_methods object name */\n  3,                        /* shared memory and mmap are enabled */\n  unixClose,                /* xClose method */\n  unixLock,                 /* xLock method */\n  unixUnlock,               /* xUnlock method */\n  unixCheckReservedLock,    /* xCheckReservedLock method */\n  unixShmMap                /* xShmMap method */\n)\nIOMETHODS(\n  nolockIoFinder,           /* Finder function name */\n  nolockIoMethods,          /* sqlite3_io_methods object name */\n  3,                        /* shared memory and mmap are enabled */\n  nolockClose,              /* xClose method */\n  nolockLock,               /* xLock method */\n  nolockUnlock,             /* xUnlock method */\n  nolockCheckReservedLock,  /* xCheckReservedLock method */\n  0                         /* xShmMap method */\n)\nIOMETHODS(\n  dotlockIoFinder,          /* Finder function name */\n  dotlockIoMethods,         /* sqlite3_io_methods object name */\n  1,                        /* shared memory is disabled */\n  dotlockClose,             /* xClose method */\n  dotlockLock,              /* xLock method */\n  dotlockUnlock,            /* xUnlock method */\n  dotlockCheckReservedLock, /* xCheckReservedLock method */\n  0                         /* xShmMap method */\n)\n\n#if SQLITE_ENABLE_LOCKING_STYLE\nIOMETHODS(\n  flockIoFinder,            /* Finder function name */\n  flockIoMethods,           /* sqlite3_io_methods object name */\n  1,                        /* shared memory is disabled */\n  flockClose,               /* xClose method */\n  flockLock,                /* xLock method */\n  flockUnlock,              /* xUnlock method */\n  flockCheckReservedLock,   /* xCheckReservedLock method */\n  0                         /* xShmMap method */\n)\n#endif\n\n#if OS_VXWORKS\nIOMETHODS(\n  semIoFinder,              /* Finder function name */\n  semIoMethods,             /* sqlite3_io_methods object name */\n  1,                        /* shared memory is disabled */\n  semXClose,                /* xClose method */\n  semXLock,                 /* xLock method */\n  semXUnlock,               /* xUnlock method */\n  semXCheckReservedLock,    /* xCheckReservedLock method */\n  0                         /* xShmMap method */\n)\n#endif\n\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\nIOMETHODS(\n  afpIoFinder,              /* Finder function name */\n  afpIoMethods,             /* sqlite3_io_methods object name */\n  1,                        /* shared memory is disabled */\n  afpClose,                 /* xClose method */\n  afpLock,                  /* xLock method */\n  afpUnlock,                /* xUnlock method */\n  afpCheckReservedLock,     /* xCheckReservedLock method */\n  0                         /* xShmMap method */\n)\n#endif\n\n/*\n** The proxy locking method is a \"super-method\" in the sense that it\n** opens secondary file descriptors for the conch and lock files and\n** it uses proxy, dot-file, AFP, and flock() locking methods on those\n** secondary files.  For this reason, the division that implements\n** proxy locking is located much further down in the file.  But we need\n** to go ahead and define the sqlite3_io_methods and finder function\n** for proxy locking here.  So we forward declare the I/O methods.\n*/\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\nstatic int proxyClose(sqlite3_file*);\nstatic int proxyLock(sqlite3_file*, int);\nstatic int proxyUnlock(sqlite3_file*, int);\nstatic int proxyCheckReservedLock(sqlite3_file*, int*);\nIOMETHODS(\n  proxyIoFinder,            /* Finder function name */\n  proxyIoMethods,           /* sqlite3_io_methods object name */\n  1,                        /* shared memory is disabled */\n  proxyClose,               /* xClose method */\n  proxyLock,                /* xLock method */\n  proxyUnlock,              /* xUnlock method */\n  proxyCheckReservedLock,   /* xCheckReservedLock method */\n  0                         /* xShmMap method */\n)\n#endif\n\n/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\nIOMETHODS(\n  nfsIoFinder,               /* Finder function name */\n  nfsIoMethods,              /* sqlite3_io_methods object name */\n  1,                         /* shared memory is disabled */\n  unixClose,                 /* xClose method */\n  unixLock,                  /* xLock method */\n  nfsUnlock,                 /* xUnlock method */\n  unixCheckReservedLock,     /* xCheckReservedLock method */\n  0                          /* xShmMap method */\n)\n#endif\n\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\n/* \n** This \"finder\" function attempts to determine the best locking strategy \n** for the database file \"filePath\".  It then returns the sqlite3_io_methods\n** object that implements that strategy.\n**\n** This is for MacOSX only.\n*/\nstatic const sqlite3_io_methods *autolockIoFinderImpl(\n  const char *filePath,    /* name of the database file */\n  unixFile *pNew           /* open file object for the database file */\n){\n  static const struct Mapping {\n    const char *zFilesystem;              /* Filesystem type name */\n    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */\n  } aMap[] = {\n    { \"hfs\",    &posixIoMethods },\n    { \"ufs\",    &posixIoMethods },\n    { \"afpfs\",  &afpIoMethods },\n    { \"smbfs\",  &afpIoMethods },\n    { \"webdav\", &nolockIoMethods },\n    { 0, 0 }\n  };\n  int i;\n  struct statfs fsInfo;\n  struct flock lockInfo;\n\n  if( !filePath ){\n    /* If filePath==NULL that means we are dealing with a transient file\n    ** that does not need to be locked. */\n    return &nolockIoMethods;\n  }\n  if( statfs(filePath, &fsInfo) != -1 ){\n    if( fsInfo.f_flags & MNT_RDONLY ){\n      return &nolockIoMethods;\n    }\n    for(i=0; aMap[i].zFilesystem; i++){\n      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){\n        return aMap[i].pMethods;\n      }\n    }\n  }\n\n  /* Default case. Handles, amongst others, \"nfs\".\n  ** Test byte-range lock using fcntl(). If the call succeeds, \n  ** assume that the file-system supports POSIX style locks. \n  */\n  lockInfo.l_len = 1;\n  lockInfo.l_start = 0;\n  lockInfo.l_whence = SEEK_SET;\n  lockInfo.l_type = F_RDLCK;\n  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {\n    if( strcmp(fsInfo.f_fstypename, \"nfs\")==0 ){\n      return &nfsIoMethods;\n    } else {\n      return &posixIoMethods;\n    }\n  }else{\n    return &dotlockIoMethods;\n  }\n}\nstatic const sqlite3_io_methods \n  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;\n\n#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */\n\n#if OS_VXWORKS\n/*\n** This \"finder\" function for VxWorks checks to see if posix advisory\n** locking works.  If it does, then that is what is used.  If it does not\n** work, then fallback to named semaphore locking.\n*/\nstatic const sqlite3_io_methods *vxworksIoFinderImpl(\n  const char *filePath,    /* name of the database file */\n  unixFile *pNew           /* the open file object */\n){\n  struct flock lockInfo;\n\n  if( !filePath ){\n    /* If filePath==NULL that means we are dealing with a transient file\n    ** that does not need to be locked. */\n    return &nolockIoMethods;\n  }\n\n  /* Test if fcntl() is supported and use POSIX style locks.\n  ** Otherwise fall back to the named semaphore method.\n  */\n  lockInfo.l_len = 1;\n  lockInfo.l_start = 0;\n  lockInfo.l_whence = SEEK_SET;\n  lockInfo.l_type = F_RDLCK;\n  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {\n    return &posixIoMethods;\n  }else{\n    return &semIoMethods;\n  }\n}\nstatic const sqlite3_io_methods \n  *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;\n\n#endif /* OS_VXWORKS */\n\n/*\n** An abstract type for a pointer to an IO method finder function:\n*/\ntypedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);\n\n\n/****************************************************************************\n**************************** sqlite3_vfs methods ****************************\n**\n** This division contains the implementation of methods on the\n** sqlite3_vfs object.\n*/\n\n/*\n** Initialize the contents of the unixFile structure pointed to by pId.\n*/\nstatic int fillInUnixFile(\n  sqlite3_vfs *pVfs,      /* Pointer to vfs object */\n  int h,                  /* Open file descriptor of file being opened */\n  sqlite3_file *pId,      /* Write to the unixFile structure here */\n  const char *zFilename,  /* Name of the file being opened */\n  int ctrlFlags           /* Zero or more UNIXFILE_* values */\n){\n  const sqlite3_io_methods *pLockingStyle;\n  unixFile *pNew = (unixFile *)pId;\n  int rc = SQLITE_OK;\n\n  assert( pNew->pInode==NULL );\n\n  /* No locking occurs in temporary files */\n  assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );\n\n  OSTRACE((\"OPEN    %-3d %s\\n\", h, zFilename));\n  pNew->h = h;\n  pNew->pVfs = pVfs;\n  pNew->zPath = zFilename;\n  pNew->ctrlFlags = (u8)ctrlFlags;\n#if SQLITE_MAX_MMAP_SIZE>0\n  pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;\n#endif\n  if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),\n                           \"psow\", SQLITE_POWERSAFE_OVERWRITE) ){\n    pNew->ctrlFlags |= UNIXFILE_PSOW;\n  }\n  if( strcmp(pVfs->zName,\"unix-excl\")==0 ){\n    pNew->ctrlFlags |= UNIXFILE_EXCL;\n  }\n\n#if OS_VXWORKS\n  pNew->pId = vxworksFindFileId(zFilename);\n  if( pNew->pId==0 ){\n    ctrlFlags |= UNIXFILE_NOLOCK;\n    rc = SQLITE_NOMEM_BKPT;\n  }\n#endif\n\n  if( ctrlFlags & UNIXFILE_NOLOCK ){\n    pLockingStyle = &nolockIoMethods;\n  }else{\n    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);\n#if SQLITE_ENABLE_LOCKING_STYLE\n    /* Cache zFilename in the locking context (AFP and dotlock override) for\n    ** proxyLock activation is possible (remote proxy is based on db name)\n    ** zFilename remains valid until file is closed, to support */\n    pNew->lockingContext = (void*)zFilename;\n#endif\n  }\n\n  if( pLockingStyle == &posixIoMethods\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\n    || pLockingStyle == &nfsIoMethods\n#endif\n  ){\n    unixEnterMutex();\n    rc = findInodeInfo(pNew, &pNew->pInode);\n    if( rc!=SQLITE_OK ){\n      /* If an error occurred in findInodeInfo(), close the file descriptor\n      ** immediately, before releasing the mutex. findInodeInfo() may fail\n      ** in two scenarios:\n      **\n      **   (a) A call to fstat() failed.\n      **   (b) A malloc failed.\n      **\n      ** Scenario (b) may only occur if the process is holding no other\n      ** file descriptors open on the same file. If there were other file\n      ** descriptors on this file, then no malloc would be required by\n      ** findInodeInfo(). If this is the case, it is quite safe to close\n      ** handle h - as it is guaranteed that no posix locks will be released\n      ** by doing so.\n      **\n      ** If scenario (a) caused the error then things are not so safe. The\n      ** implicit assumption here is that if fstat() fails, things are in\n      ** such bad shape that dropping a lock or two doesn't matter much.\n      */\n      robust_close(pNew, h, __LINE__);\n      h = -1;\n    }\n    unixLeaveMutex();\n  }\n\n#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)\n  else if( pLockingStyle == &afpIoMethods ){\n    /* AFP locking uses the file path so it needs to be included in\n    ** the afpLockingContext.\n    */\n    afpLockingContext *pCtx;\n    pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );\n    if( pCtx==0 ){\n      rc = SQLITE_NOMEM_BKPT;\n    }else{\n      /* NB: zFilename exists and remains valid until the file is closed\n      ** according to requirement F11141.  So we do not need to make a\n      ** copy of the filename. */\n      pCtx->dbPath = zFilename;\n      pCtx->reserved = 0;\n      srandomdev();\n      unixEnterMutex();\n      rc = findInodeInfo(pNew, &pNew->pInode);\n      if( rc!=SQLITE_OK ){\n        sqlite3_free(pNew->lockingContext);\n        robust_close(pNew, h, __LINE__);\n        h = -1;\n      }\n      unixLeaveMutex();        \n    }\n  }\n#endif\n\n  else if( pLockingStyle == &dotlockIoMethods ){\n    /* Dotfile locking uses the file path so it needs to be included in\n    ** the dotlockLockingContext \n    */\n    char *zLockFile;\n    int nFilename;\n    assert( zFilename!=0 );\n    nFilename = (int)strlen(zFilename) + 6;\n    zLockFile = (char *)sqlite3_malloc64(nFilename);\n    if( zLockFile==0 ){\n      rc = SQLITE_NOMEM_BKPT;\n    }else{\n      sqlite3_snprintf(nFilename, zLockFile, \"%s\" DOTLOCK_SUFFIX, zFilename);\n    }\n    pNew->lockingContext = zLockFile;\n  }\n\n#if OS_VXWORKS\n  else if( pLockingStyle == &semIoMethods ){\n    /* Named semaphore locking uses the file path so it needs to be\n    ** included in the semLockingContext\n    */\n    unixEnterMutex();\n    rc = findInodeInfo(pNew, &pNew->pInode);\n    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){\n      char *zSemName = pNew->pInode->aSemName;\n      int n;\n      sqlite3_snprintf(MAX_PATHNAME, zSemName, \"/%s.sem\",\n                       pNew->pId->zCanonicalName);\n      for( n=1; zSemName[n]; n++ )\n        if( zSemName[n]=='/' ) zSemName[n] = '_';\n      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);\n      if( pNew->pInode->pSem == SEM_FAILED ){\n        rc = SQLITE_NOMEM_BKPT;\n        pNew->pInode->aSemName[0] = '\\0';\n      }\n    }\n    unixLeaveMutex();\n  }\n#endif\n  \n  storeLastErrno(pNew, 0);\n#if OS_VXWORKS\n  if( rc!=SQLITE_OK ){\n    if( h>=0 ) robust_close(pNew, h, __LINE__);\n    h = -1;\n    osUnlink(zFilename);\n    pNew->ctrlFlags |= UNIXFILE_DELETE;\n  }\n#endif\n  if( rc!=SQLITE_OK ){\n    if( h>=0 ) robust_close(pNew, h, __LINE__);\n  }else{\n    pNew->pMethod = pLockingStyle;\n    OpenCounter(+1);\n    verifyDbFile(pNew);\n  }\n  return rc;\n}\n\n/*\n** Return the name of a directory in which to put temporary files.\n** If no suitable temporary file directory can be found, return NULL.\n*/\nstatic const char *unixTempFileDir(void){\n  static const char *azDirs[] = {\n     0,\n     0,\n     \"/var/tmp\",\n     \"/usr/tmp\",\n     \"/tmp\",\n     \".\"\n  };\n  unsigned int i = 0;\n  struct stat buf;\n  const char *zDir = sqlite3_temp_directory;\n\n  if( !azDirs[0] ) azDirs[0] = getenv(\"SQLITE_TMPDIR\");\n  if( !azDirs[1] ) azDirs[1] = getenv(\"TMPDIR\");\n  while(1){\n    if( zDir!=0\n     && osStat(zDir, &buf)==0\n     && S_ISDIR(buf.st_mode)\n     && osAccess(zDir, 03)==0\n    ){\n      return zDir;\n    }\n    if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;\n    zDir = azDirs[i++];\n  }\n  return 0;\n}\n\n/*\n** Create a temporary file name in zBuf.  zBuf must be allocated\n** by the calling process and must be big enough to hold at least\n** pVfs->mxPathname bytes.\n*/\nstatic int unixGetTempname(int nBuf, char *zBuf){\n  const char *zDir;\n  int iLimit = 0;\n\n  /* It's odd to simulate an io-error here, but really this is just\n  ** using the io-error infrastructure to test that SQLite handles this\n  ** function failing. \n  */\n  zBuf[0] = 0;\n  SimulateIOError( return SQLITE_IOERR );\n\n  zDir = unixTempFileDir();\n  if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;\n  do{\n    u64 r;\n    sqlite3_randomness(sizeof(r), &r);\n    assert( nBuf>2 );\n    zBuf[nBuf-2] = 0;\n    sqlite3_snprintf(nBuf, zBuf, \"%s/\"SQLITE_TEMP_FILE_PREFIX\"%llx%c\",\n                     zDir, r, 0);\n    if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;\n  }while( osAccess(zBuf,0)==0 );\n  return SQLITE_OK;\n}\n\n#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)\n/*\n** Routine to transform a unixFile into a proxy-locking unixFile.\n** Implementation in the proxy-lock division, but used by unixOpen()\n** if SQLITE_PREFER_PROXY_LOCKING is defined.\n*/\nstatic int proxyTransformUnixFile(unixFile*, const char*);\n#endif\n\n/*\n** Search for an unused file descriptor that was opened on the database \n** file (not a journal or master-journal file) identified by pathname\n** zPath with SQLITE_OPEN_XXX flags matching those passed as the second\n** argument to this function.\n**\n** Such a file descriptor may exist if a database connection was closed\n** but the associated file descriptor could not be closed because some\n** other file descriptor open on the same file is holding a file-lock.\n** Refer to comments in the unixClose() function and the lengthy comment\n** describing \"Posix Advisory Locking\" at the start of this file for \n** further details. Also, ticket #4018.\n**\n** If a suitable file descriptor is found, then it is returned. If no\n** such file descriptor is located, -1 is returned.\n*/\nstatic UnixUnusedFd *findReusableFd(const char *zPath, int flags){\n  UnixUnusedFd *pUnused = 0;\n\n  /* Do not search for an unused file descriptor on vxworks. Not because\n  ** vxworks would not benefit from the change (it might, we're not sure),\n  ** but because no way to test it is currently available. It is better \n  ** not to risk breaking vxworks support for the sake of such an obscure \n  ** feature.  */\n#if !OS_VXWORKS\n  struct stat sStat;                   /* Results of stat() call */\n\n  unixEnterMutex();\n\n  /* A stat() call may fail for various reasons. If this happens, it is\n  ** almost certain that an open() call on the same path will also fail.\n  ** For this reason, if an error occurs in the stat() call here, it is\n  ** ignored and -1 is returned. The caller will try to open a new file\n  ** descriptor on the same path, fail, and return an error to SQLite.\n  **\n  ** Even if a subsequent open() call does succeed, the consequences of\n  ** not searching for a reusable file descriptor are not dire.  */\n  if( inodeList!=0 && 0==osStat(zPath, &sStat) ){\n    unixInodeInfo *pInode;\n\n    pInode = inodeList;\n    while( pInode && (pInode->fileId.dev!=sStat.st_dev\n                     || pInode->fileId.ino!=(u64)sStat.st_ino) ){\n       pInode = pInode->pNext;\n    }\n    if( pInode ){\n      UnixUnusedFd **pp;\n      assert( sqlite3_mutex_notheld(pInode->pLockMutex) );\n      sqlite3_mutex_enter(pInode->pLockMutex);\n      flags &= (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);\n      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));\n      pUnused = *pp;\n      if( pUnused ){\n        *pp = pUnused->pNext;\n      }\n      sqlite3_mutex_leave(pInode->pLockMutex);\n    }\n  }\n  unixLeaveMutex();\n#endif    /* if !OS_VXWORKS */\n  return pUnused;\n}\n\n/*\n** Find the mode, uid and gid of file zFile. \n*/\nstatic int getFileMode(\n  const char *zFile,              /* File name */\n  mode_t *pMode,                  /* OUT: Permissions of zFile */\n  uid_t *pUid,                    /* OUT: uid of zFile. */\n  gid_t *pGid                     /* OUT: gid of zFile. */\n){\n  struct stat sStat;              /* Output of stat() on database file */\n  int rc = SQLITE_OK;\n  if( 0==osStat(zFile, &sStat) ){\n    *pMode = sStat.st_mode & 0777;\n    *pUid = sStat.st_uid;\n    *pGid = sStat.st_gid;\n  }else{\n    rc = SQLITE_IOERR_FSTAT;\n  }\n  return rc;\n}\n\n/*\n** This function is called by unixOpen() to determine the unix permissions\n** to create new files with. If no error occurs, then SQLITE_OK is returned\n** and a value suitable for passing as the third argument to open(2) is\n** written to *pMode. If an IO error occurs, an SQLite error code is \n** returned and the value of *pMode is not modified.\n**\n** In most cases, this routine sets *pMode to 0, which will become\n** an indication to robust_open() to create the file using\n** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.\n** But if the file being opened is a WAL or regular journal file, then \n** this function queries the file-system for the permissions on the \n** corresponding database file and sets *pMode to this value. Whenever \n** possible, WAL and journal files are created using the same permissions \n** as the associated database file.\n**\n** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the\n** original filename is unavailable.  But 8_3_NAMES is only used for\n** FAT filesystems and permissions do not matter there, so just use\n** the default permissions.  In 8_3_NAMES mode, leave *pMode set to zero.\n*/\nstatic int findCreateFileMode(\n  const char *zPath,              /* Path of file (possibly) being created */\n  int flags,                      /* Flags passed as 4th argument to xOpen() */\n  mode_t *pMode,                  /* OUT: Permissions to open file with */\n  uid_t *pUid,                    /* OUT: uid to set on the file */\n  gid_t *pGid                     /* OUT: gid to set on the file */\n){\n  int rc = SQLITE_OK;             /* Return Code */\n  *pMode = 0;\n  *pUid = 0;\n  *pGid = 0;\n  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){\n    char zDb[MAX_PATHNAME+1];     /* Database file path */\n    int nDb;                      /* Number of valid bytes in zDb */\n\n    /* zPath is a path to a WAL or journal file. The following block derives\n    ** the path to the associated database file from zPath. This block handles\n    ** the following naming conventions:\n    **\n    **   \"<path to db>-journal\"\n    **   \"<path to db>-wal\"\n    **   \"<path to db>-journalNN\"\n    **   \"<path to db>-walNN\"\n    **\n    ** where NN is a decimal number. The NN naming schemes are \n    ** used by the test_multiplex.c module.\n    */\n    nDb = sqlite3Strlen30(zPath) - 1; \n    while( zPath[nDb]!='-' ){\n      /* In normal operation, the journal file name will always contain\n      ** a '-' character.  However in 8+3 filename mode, or if a corrupt\n      ** rollback journal specifies a master journal with a goofy name, then\n      ** the '-' might be missing. */\n      if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;\n      nDb--;\n    }\n    memcpy(zDb, zPath, nDb);\n    zDb[nDb] = '\\0';\n\n    rc = getFileMode(zDb, pMode, pUid, pGid);\n  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){\n    *pMode = 0600;\n  }else if( flags & SQLITE_OPEN_URI ){\n    /* If this is a main database file and the file was opened using a URI\n    ** filename, check for the \"modeof\" parameter. If present, interpret\n    ** its value as a filename and try to copy the mode, uid and gid from\n    ** that file.  */\n    const char *z = sqlite3_uri_parameter(zPath, \"modeof\");\n    if( z ){\n      rc = getFileMode(z, pMode, pUid, pGid);\n    }\n  }\n  return rc;\n}\n\n/*\n** Open the file zPath.\n** \n** Previously, the SQLite OS layer used three functions in place of this\n** one:\n**\n**     sqlite3OsOpenReadWrite();\n**     sqlite3OsOpenReadOnly();\n**     sqlite3OsOpenExclusive();\n**\n** These calls correspond to the following combinations of flags:\n**\n**     ReadWrite() ->     (READWRITE | CREATE)\n**     ReadOnly()  ->     (READONLY) \n**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)\n**\n** The old OpenExclusive() accepted a boolean argument - \"delFlag\". If\n** true, the file was configured to be automatically deleted when the\n** file handle closed. To achieve the same effect using this new \n** interface, add the DELETEONCLOSE flag to those specified above for \n** OpenExclusive().\n*/\nstatic int unixOpen(\n  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */\n  const char *zPath,           /* Pathname of file to be opened */\n  sqlite3_file *pFile,         /* The file descriptor to be filled in */\n  int flags,                   /* Input flags to control the opening */\n  int *pOutFlags               /* Output flags returned to SQLite core */\n){\n  unixFile *p = (unixFile *)pFile;\n  int fd = -1;                   /* File descriptor returned by open() */\n  int openFlags = 0;             /* Flags to pass to open() */\n  int eType = flags&0x0FFF00;  /* Type of file to open */\n  int noLock;                    /* True to omit locking primitives */\n  int rc = SQLITE_OK;            /* Function Return Code */\n  int ctrlFlags = 0;             /* UNIXFILE_* flags */\n\n  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);\n  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);\n  int isCreate     = (flags & SQLITE_OPEN_CREATE);\n  int isReadonly   = (flags & SQLITE_OPEN_READONLY);\n  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);\n#if SQLITE_ENABLE_LOCKING_STYLE\n  int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);\n#endif\n#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE\n  struct statfs fsInfo;\n#endif\n\n  /* If creating a master or main-file journal, this function will open\n  ** a file-descriptor on the directory too. The first time unixSync()\n  ** is called the directory file descriptor will be fsync()ed and close()d.\n  */\n  int isNewJrnl = (isCreate && (\n        eType==SQLITE_OPEN_MASTER_JOURNAL \n     || eType==SQLITE_OPEN_MAIN_JOURNAL \n     || eType==SQLITE_OPEN_WAL\n  ));\n\n  /* If argument zPath is a NULL pointer, this function is required to open\n  ** a temporary file. Use this buffer to store the file name in.\n  */\n  char zTmpname[MAX_PATHNAME+2];\n  const char *zName = zPath;\n\n  /* Check the following statements are true: \n  **\n  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and \n  **   (b) if CREATE is set, then READWRITE must also be set, and\n  **   (c) if EXCLUSIVE is set, then CREATE must also be set.\n  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.\n  */\n  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));\n  assert(isCreate==0 || isReadWrite);\n  assert(isExclusive==0 || isCreate);\n  assert(isDelete==0 || isCreate);\n\n  /* The main DB, main journal, WAL file and master journal are never \n  ** automatically deleted. Nor are they ever temporary files.  */\n  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );\n  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );\n  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );\n  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );\n\n  /* Assert that the upper layer has set one of the \"file-type\" flags. */\n  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB \n       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL \n       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL \n       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL\n  );\n\n  /* Detect a pid change and reset the PRNG.  There is a race condition\n  ** here such that two or more threads all trying to open databases at\n  ** the same instant might all reset the PRNG.  But multiple resets\n  ** are harmless.\n  */\n  if( randomnessPid!=osGetpid(0) ){\n    randomnessPid = osGetpid(0);\n    sqlite3_randomness(0,0);\n  }\n  memset(p, 0, sizeof(unixFile));\n\n  if( eType==SQLITE_OPEN_MAIN_DB ){\n    UnixUnusedFd *pUnused;\n    pUnused = findReusableFd(zName, flags);\n    if( pUnused ){\n      fd = pUnused->fd;\n    }else{\n      pUnused = sqlite3_malloc64(sizeof(*pUnused));\n      if( !pUnused ){\n        return SQLITE_NOMEM_BKPT;\n      }\n    }\n    p->pPreallocatedUnused = pUnused;\n\n    /* Database filenames are double-zero terminated if they are not\n    ** URIs with parameters.  Hence, they can always be passed into\n    ** sqlite3_uri_parameter(). */\n    assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );\n\n  }else if( !zName ){\n    /* If zName is NULL, the upper layer is requesting a temp file. */\n    assert(isDelete && !isNewJrnl);\n    rc = unixGetTempname(pVfs->mxPathname, zTmpname);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    zName = zTmpname;\n\n    /* Generated temporary filenames are always double-zero terminated\n    ** for use by sqlite3_uri_parameter(). */\n    assert( zName[strlen(zName)+1]==0 );\n  }\n\n  /* Determine the value of the flags parameter passed to POSIX function\n  ** open(). These must be calculated even if open() is not called, as\n  ** they may be stored as part of the file handle and used by the \n  ** 'conch file' locking functions later on.  */\n  if( isReadonly )  openFlags |= O_RDONLY;\n  if( isReadWrite ) openFlags |= O_RDWR;\n  if( isCreate )    openFlags |= O_CREAT;\n  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);\n  openFlags |= (O_LARGEFILE|O_BINARY|O_NOFOLLOW);\n\n  if( fd<0 ){\n    mode_t openMode;              /* Permissions to create file with */\n    uid_t uid;                    /* Userid for the file */\n    gid_t gid;                    /* Groupid for the file */\n    rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);\n    if( rc!=SQLITE_OK ){\n      assert( !p->pPreallocatedUnused );\n      assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );\n      return rc;\n    }\n    fd = robust_open(zName, openFlags, openMode);\n    OSTRACE((\"OPENX   %-3d %s 0%o\\n\", fd, zName, openFlags));\n    assert( !isExclusive || (openFlags & O_CREAT)!=0 );\n    if( fd<0 ){\n      if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){\n        /* If unable to create a journal because the directory is not\n        ** writable, change the error code to indicate that. */\n        rc = SQLITE_READONLY_DIRECTORY;\n      }else if( errno!=EISDIR && isReadWrite ){\n        /* Failed to open the file for read/write access. Try read-only. */\n        flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);\n        openFlags &= ~(O_RDWR|O_CREAT);\n        flags |= SQLITE_OPEN_READONLY;\n        openFlags |= O_RDONLY;\n        isReadonly = 1;\n        fd = robust_open(zName, openFlags, openMode);\n      }\n    }\n    if( fd<0 ){\n      int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, \"open\", zName);\n      if( rc==SQLITE_OK ) rc = rc2;\n      goto open_finished;\n    }\n\n    /* The owner of the rollback journal or WAL file should always be the\n    ** same as the owner of the database file.  Try to ensure that this is\n    ** the case.  The chown() system call will be a no-op if the current\n    ** process lacks root privileges, be we should at least try.  Without\n    ** this step, if a root process opens a database file, it can leave\n    ** behinds a journal/WAL that is owned by root and hence make the\n    ** database inaccessible to unprivileged processes.\n    **\n    ** If openMode==0, then that means uid and gid are not set correctly\n    ** (probably because SQLite is configured to use 8+3 filename mode) and\n    ** in that case we do not want to attempt the chown().\n    */\n    if( openMode && (flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL))!=0 ){\n      robustFchown(fd, uid, gid);\n    }\n  }\n  assert( fd>=0 );\n  if( pOutFlags ){\n    *pOutFlags = flags;\n  }\n\n  if( p->pPreallocatedUnused ){\n    p->pPreallocatedUnused->fd = fd;\n    p->pPreallocatedUnused->flags = \n                          flags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);\n  }\n\n  if( isDelete ){\n#if OS_VXWORKS\n    zPath = zName;\n#elif defined(SQLITE_UNLINK_AFTER_CLOSE)\n    zPath = sqlite3_mprintf(\"%s\", zName);\n    if( zPath==0 ){\n      robust_close(p, fd, __LINE__);\n      return SQLITE_NOMEM_BKPT;\n    }\n#else\n    osUnlink(zName);\n#endif\n  }\n#if SQLITE_ENABLE_LOCKING_STYLE\n  else{\n    p->openFlags = openFlags;\n  }\n#endif\n  \n#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE\n  if( fstatfs(fd, &fsInfo) == -1 ){\n    storeLastErrno(p, errno);\n    robust_close(p, fd, __LINE__);\n    return SQLITE_IOERR_ACCESS;\n  }\n  if (0 == strncmp(\"msdos\", fsInfo.f_fstypename, 5)) {\n    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;\n  }\n  if (0 == strncmp(\"exfat\", fsInfo.f_fstypename, 5)) {\n    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;\n  }\n#endif\n\n  /* Set up appropriate ctrlFlags */\n  if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;\n  if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;\n  noLock = eType!=SQLITE_OPEN_MAIN_DB;\n  if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;\n  if( isNewJrnl )               ctrlFlags |= UNIXFILE_DIRSYNC;\n  if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;\n\n#if SQLITE_ENABLE_LOCKING_STYLE\n#if SQLITE_PREFER_PROXY_LOCKING\n  isAutoProxy = 1;\n#endif\n  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){\n    char *envforce = getenv(\"SQLITE_FORCE_PROXY_LOCKING\");\n    int useProxy = 0;\n\n    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means \n    ** never use proxy, NULL means use proxy for non-local files only.  */\n    if( envforce!=NULL ){\n      useProxy = atoi(envforce)>0;\n    }else{\n      useProxy = !(fsInfo.f_flags&MNT_LOCAL);\n    }\n    if( useProxy ){\n      rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);\n      if( rc==SQLITE_OK ){\n        rc = proxyTransformUnixFile((unixFile*)pFile, \":auto:\");\n        if( rc!=SQLITE_OK ){\n          /* Use unixClose to clean up the resources added in fillInUnixFile \n          ** and clear all the structure's references.  Specifically, \n          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op \n          */\n          unixClose(pFile);\n          return rc;\n        }\n      }\n      goto open_finished;\n    }\n  }\n#endif\n  \n  assert( zPath==0 || zPath[0]=='/' \n      || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL \n  );\n  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);\n\nopen_finished:\n  if( rc!=SQLITE_OK ){\n    sqlite3_free(p->pPreallocatedUnused);\n  }\n  return rc;\n}\n\n\n/*\n** Delete the file at zPath. If the dirSync argument is true, fsync()\n** the directory after deleting the file.\n*/\nstatic int unixDelete(\n  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */\n  const char *zPath,        /* Name of file to be deleted */\n  int dirSync               /* If true, fsync() directory after deleting file */\n){\n  int rc = SQLITE_OK;\n  UNUSED_PARAMETER(NotUsed);\n  SimulateIOError(return SQLITE_IOERR_DELETE);\n  if( osUnlink(zPath)==(-1) ){\n    if( errno==ENOENT\n#if OS_VXWORKS\n        || osAccess(zPath,0)!=0\n#endif\n    ){\n      rc = SQLITE_IOERR_DELETE_NOENT;\n    }else{\n      rc = unixLogError(SQLITE_IOERR_DELETE, \"unlink\", zPath);\n    }\n    return rc;\n  }\n#ifndef SQLITE_DISABLE_DIRSYNC\n  if( (dirSync & 1)!=0 ){\n    int fd;\n    rc = osOpenDirectory(zPath, &fd);\n    if( rc==SQLITE_OK ){\n      if( full_fsync(fd,0,0) ){\n        rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, \"fsync\", zPath);\n      }\n      robust_close(0, fd, __LINE__);\n    }else{\n      assert( rc==SQLITE_CANTOPEN );\n      rc = SQLITE_OK;\n    }\n  }\n#endif\n  return rc;\n}\n\n/*\n** Test the existence of or access permissions of file zPath. The\n** test performed depends on the value of flags:\n**\n**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists\n**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.\n**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.\n**\n** Otherwise return 0.\n*/\nstatic int unixAccess(\n  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */\n  const char *zPath,      /* Path of the file to examine */\n  int flags,              /* What do we want to learn about the zPath file? */\n  int *pResOut            /* Write result boolean here */\n){\n  UNUSED_PARAMETER(NotUsed);\n  SimulateIOError( return SQLITE_IOERR_ACCESS; );\n  assert( pResOut!=0 );\n\n  /* The spec says there are three possible values for flags.  But only\n  ** two of them are actually used */\n  assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );\n\n  if( flags==SQLITE_ACCESS_EXISTS ){\n    struct stat buf;\n    *pResOut = 0==osStat(zPath, &buf) &&\n                (!S_ISREG(buf.st_mode) || buf.st_size>0);\n  }else{\n    *pResOut = osAccess(zPath, W_OK|R_OK)==0;\n  }\n  return SQLITE_OK;\n}\n\n/*\n**\n*/\nstatic int mkFullPathname(\n  const char *zPath,              /* Input path */\n  char *zOut,                     /* Output buffer */\n  int nOut                        /* Allocated size of buffer zOut */\n){\n  int nPath = sqlite3Strlen30(zPath);\n  int iOff = 0;\n  if( zPath[0]!='/' ){\n    if( osGetcwd(zOut, nOut-2)==0 ){\n      return unixLogError(SQLITE_CANTOPEN_BKPT, \"getcwd\", zPath);\n    }\n    iOff = sqlite3Strlen30(zOut);\n    zOut[iOff++] = '/';\n  }\n  if( (iOff+nPath+1)>nOut ){\n    /* SQLite assumes that xFullPathname() nul-terminates the output buffer\n    ** even if it returns an error.  */\n    zOut[iOff] = '\\0';\n    return SQLITE_CANTOPEN_BKPT;\n  }\n  sqlite3_snprintf(nOut-iOff, &zOut[iOff], \"%s\", zPath);\n  return SQLITE_OK;\n}\n\n/*\n** Turn a relative pathname into a full pathname. The relative path\n** is stored as a nul-terminated string in the buffer pointed to by\n** zPath. \n**\n** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes \n** (in this case, MAX_PATHNAME bytes). The full-path is written to\n** this buffer before returning.\n*/\nstatic int unixFullPathname(\n  sqlite3_vfs *pVfs,            /* Pointer to vfs object */\n  const char *zPath,            /* Possibly relative input path */\n  int nOut,                     /* Size of output buffer in bytes */\n  char *zOut                    /* Output buffer */\n){\n#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)\n  return mkFullPathname(zPath, zOut, nOut);\n#else\n  int rc = SQLITE_OK;\n  int nByte;\n  int nLink = 0;                /* Number of symbolic links followed so far */\n  const char *zIn = zPath;      /* Input path for each iteration of loop */\n  char *zDel = 0;\n\n  assert( pVfs->mxPathname==MAX_PATHNAME );\n  UNUSED_PARAMETER(pVfs);\n\n  /* It's odd to simulate an io-error here, but really this is just\n  ** using the io-error infrastructure to test that SQLite handles this\n  ** function failing. This function could fail if, for example, the\n  ** current working directory has been unlinked.\n  */\n  SimulateIOError( return SQLITE_ERROR );\n\n  do {\n\n    /* Call stat() on path zIn. Set bLink to true if the path is a symbolic\n    ** link, or false otherwise.  */\n    int bLink = 0;\n    struct stat buf;\n    if( osLstat(zIn, &buf)!=0 ){\n      if( errno!=ENOENT ){\n        rc = unixLogError(SQLITE_CANTOPEN_BKPT, \"lstat\", zIn);\n      }\n    }else{\n      bLink = S_ISLNK(buf.st_mode);\n    }\n\n    if( bLink ){\n      nLink++;\n      if( zDel==0 ){\n        zDel = sqlite3_malloc(nOut);\n        if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;\n      }else if( nLink>=SQLITE_MAX_SYMLINKS ){\n        rc = SQLITE_CANTOPEN_BKPT;\n      }\n\n      if( rc==SQLITE_OK ){\n        nByte = osReadlink(zIn, zDel, nOut-1);\n        if( nByte<0 ){\n          rc = unixLogError(SQLITE_CANTOPEN_BKPT, \"readlink\", zIn);\n        }else{\n          if( zDel[0]!='/' ){\n            int n;\n            for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);\n            if( nByte+n+1>nOut ){\n              rc = SQLITE_CANTOPEN_BKPT;\n            }else{\n              memmove(&zDel[n], zDel, nByte+1);\n              memcpy(zDel, zIn, n);\n              nByte += n;\n            }\n          }\n          zDel[nByte] = '\\0';\n        }\n      }\n\n      zIn = zDel;\n    }\n\n    assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );\n    if( rc==SQLITE_OK && zIn!=zOut ){\n      rc = mkFullPathname(zIn, zOut, nOut);\n    }\n    if( bLink==0 ) break;\n    zIn = zOut;\n  }while( rc==SQLITE_OK );\n\n  sqlite3_free(zDel);\n  if( rc==SQLITE_OK && nLink ) rc = SQLITE_OK_SYMLINK;\n  return rc;\n#endif   /* HAVE_READLINK && HAVE_LSTAT */\n}\n\n\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\n/*\n** Interfaces for opening a shared library, finding entry points\n** within the shared library, and closing the shared library.\n*/\n#include <dlfcn.h>\nstatic void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){\n  UNUSED_PARAMETER(NotUsed);\n  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);\n}\n\n/*\n** SQLite calls this function immediately after a call to unixDlSym() or\n** unixDlOpen() fails (returns a null pointer). If a more detailed error\n** message is available, it is written to zBufOut. If no error message\n** is available, zBufOut is left unmodified and SQLite uses a default\n** error message.\n*/\nstatic void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){\n  const char *zErr;\n  UNUSED_PARAMETER(NotUsed);\n  unixEnterMutex();\n  zErr = dlerror();\n  if( zErr ){\n    sqlite3_snprintf(nBuf, zBufOut, \"%s\", zErr);\n  }\n  unixLeaveMutex();\n}\nstatic void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){\n  /* \n  ** GCC with -pedantic-errors says that C90 does not allow a void* to be\n  ** cast into a pointer to a function.  And yet the library dlsym() routine\n  ** returns a void* which is really a pointer to a function.  So how do we\n  ** use dlsym() with -pedantic-errors?\n  **\n  ** Variable x below is defined to be a pointer to a function taking\n  ** parameters void* and const char* and returning a pointer to a function.\n  ** We initialize x by assigning it a pointer to the dlsym() function.\n  ** (That assignment requires a cast.)  Then we call the function that\n  ** x points to.  \n  **\n  ** This work-around is unlikely to work correctly on any system where\n  ** you really cannot cast a function pointer into void*.  But then, on the\n  ** other hand, dlsym() will not work on such a system either, so we have\n  ** not really lost anything.\n  */\n  void (*(*x)(void*,const char*))(void);\n  UNUSED_PARAMETER(NotUsed);\n  x = (void(*(*)(void*,const char*))(void))dlsym;\n  return (*x)(p, zSym);\n}\nstatic void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){\n  UNUSED_PARAMETER(NotUsed);\n  dlclose(pHandle);\n}\n#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */\n  #define unixDlOpen  0\n  #define unixDlError 0\n  #define unixDlSym   0\n  #define unixDlClose 0\n#endif\n\n/*\n** Write nBuf bytes of random data to the supplied buffer zBuf.\n*/\nstatic int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){\n  UNUSED_PARAMETER(NotUsed);\n  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));\n\n  /* We have to initialize zBuf to prevent valgrind from reporting\n  ** errors.  The reports issued by valgrind are incorrect - we would\n  ** prefer that the randomness be increased by making use of the\n  ** uninitialized space in zBuf - but valgrind errors tend to worry\n  ** some users.  Rather than argue, it seems easier just to initialize\n  ** the whole array and silence valgrind, even if that means less randomness\n  ** in the random seed.\n  **\n  ** When testing, initializing zBuf[] to zero is all we do.  That means\n  ** that we always use the same random number sequence.  This makes the\n  ** tests repeatable.\n  */\n  memset(zBuf, 0, nBuf);\n  randomnessPid = osGetpid(0);  \n#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)\n  {\n    int fd, got;\n    fd = robust_open(\"/dev/urandom\", O_RDONLY, 0);\n    if( fd<0 ){\n      time_t t;\n      time(&t);\n      memcpy(zBuf, &t, sizeof(t));\n      memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));\n      assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );\n      nBuf = sizeof(t) + sizeof(randomnessPid);\n    }else{\n      do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );\n      robust_close(0, fd, __LINE__);\n    }\n  }\n#endif\n  return nBuf;\n}\n\n\n/*\n** Sleep for a little while.  Return the amount of time slept.\n** The argument is the number of microseconds we want to sleep.\n** The return value is the number of microseconds of sleep actually\n** requested from the underlying operating system, a number which\n** might be greater than or equal to the argument, but not less\n** than the argument.\n*/\nstatic int unixSleep(sqlite3_vfs *NotUsed, int microseconds){\n#if OS_VXWORKS\n  struct timespec sp;\n\n  sp.tv_sec = microseconds / 1000000;\n  sp.tv_nsec = (microseconds % 1000000) * 1000;\n  nanosleep(&sp, NULL);\n  UNUSED_PARAMETER(NotUsed);\n  return microseconds;\n#elif defined(HAVE_USLEEP) && HAVE_USLEEP\n  usleep(microseconds);\n  UNUSED_PARAMETER(NotUsed);\n  return microseconds;\n#else\n  int seconds = (microseconds+999999)/1000000;\n  sleep(seconds);\n  UNUSED_PARAMETER(NotUsed);\n  return seconds*1000000;\n#endif\n}\n\n/*\n** The following variable, if set to a non-zero value, is interpreted as\n** the number of seconds since 1970 and is used to set the result of\n** sqlite3OsCurrentTime() during testing.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */\n#endif\n\n/*\n** Find the current time (in Universal Coordinated Time).  Write into *piNow\n** the current time and date as a Julian Day number times 86_400_000.  In\n** other words, write into *piNow the number of milliseconds since the Julian\n** epoch of noon in Greenwich on November 24, 4714 B.C according to the\n** proleptic Gregorian calendar.\n**\n** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date \n** cannot be found.\n*/\nstatic int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){\n  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;\n  int rc = SQLITE_OK;\n#if defined(NO_GETTOD)\n  time_t t;\n  time(&t);\n  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;\n#elif OS_VXWORKS\n  struct timespec sNow;\n  clock_gettime(CLOCK_REALTIME, &sNow);\n  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;\n#else\n  struct timeval sNow;\n  (void)gettimeofday(&sNow, 0);  /* Cannot fail given valid arguments */\n  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;\n#endif\n\n#ifdef SQLITE_TEST\n  if( sqlite3_current_time ){\n    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;\n  }\n#endif\n  UNUSED_PARAMETER(NotUsed);\n  return rc;\n}\n\n#ifndef SQLITE_OMIT_DEPRECATED\n/*\n** Find the current time (in Universal Coordinated Time).  Write the\n** current time and date as a Julian Day number into *prNow and\n** return 0.  Return 1 if the time and date cannot be found.\n*/\nstatic int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){\n  sqlite3_int64 i = 0;\n  int rc;\n  UNUSED_PARAMETER(NotUsed);\n  rc = unixCurrentTimeInt64(0, &i);\n  *prNow = i/86400000.0;\n  return rc;\n}\n#else\n# define unixCurrentTime 0\n#endif\n\n/*\n** The xGetLastError() method is designed to return a better\n** low-level error message when operating-system problems come up\n** during SQLite operation.  Only the integer return code is currently\n** used.\n*/\nstatic int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){\n  UNUSED_PARAMETER(NotUsed);\n  UNUSED_PARAMETER(NotUsed2);\n  UNUSED_PARAMETER(NotUsed3);\n  return errno;\n}\n\n\n/*\n************************ End of sqlite3_vfs methods ***************************\n******************************************************************************/\n\n/******************************************************************************\n************************** Begin Proxy Locking ********************************\n**\n** Proxy locking is a \"uber-locking-method\" in this sense:  It uses the\n** other locking methods on secondary lock files.  Proxy locking is a\n** meta-layer over top of the primitive locking implemented above.  For\n** this reason, the division that implements of proxy locking is deferred\n** until late in the file (here) after all of the other I/O methods have\n** been defined - so that the primitive locking methods are available\n** as services to help with the implementation of proxy locking.\n**\n****\n**\n** The default locking schemes in SQLite use byte-range locks on the\n** database file to coordinate safe, concurrent access by multiple readers\n** and writers [http://sqlite.org/lockingv3.html].  The five file locking\n** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented\n** as POSIX read & write locks over fixed set of locations (via fsctl),\n** on AFP and SMB only exclusive byte-range locks are available via fsctl\n** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.\n** To simulate a F_RDLCK on the shared range, on AFP a randomly selected\n** address in the shared range is taken for a SHARED lock, the entire\n** shared range is taken for an EXCLUSIVE lock):\n**\n**      PENDING_BYTE        0x40000000\n**      RESERVED_BYTE       0x40000001\n**      SHARED_RANGE        0x40000002 -> 0x40000200\n**\n** This works well on the local file system, but shows a nearly 100x\n** slowdown in read performance on AFP because the AFP client disables\n** the read cache when byte-range locks are present.  Enabling the read\n** cache exposes a cache coherency problem that is present on all OS X\n** supported network file systems.  NFS and AFP both observe the\n** close-to-open semantics for ensuring cache coherency\n** [http://nfs.sourceforge.net/#faq_a8], which does not effectively\n** address the requirements for concurrent database access by multiple\n** readers and writers\n** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].\n**\n** To address the performance and cache coherency issues, proxy file locking\n** changes the way database access is controlled by limiting access to a\n** single host at a time and moving file locks off of the database file\n** and onto a proxy file on the local file system.  \n**\n**\n** Using proxy locks\n** -----------------\n**\n** C APIs\n**\n**  sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,\n**                       <proxy_path> | \":auto:\");\n**  sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,\n**                       &<proxy_path>);\n**\n**\n** SQL pragmas\n**\n**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:\n**  PRAGMA [database.]lock_proxy_file\n**\n** Specifying \":auto:\" means that if there is a conch file with a matching\n** host ID in it, the proxy path in the conch file will be used, otherwise\n** a proxy path based on the user's temp dir\n** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the\n** actual proxy file name is generated from the name and path of the\n** database file.  For example:\n**\n**       For database path \"/Users/me/foo.db\" \n**       The lock path will be \"<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:\")\n**\n** Once a lock proxy is configured for a database connection, it can not\n** be removed, however it may be switched to a different proxy path via\n** the above APIs (assuming the conch file is not being held by another\n** connection or process). \n**\n**\n** How proxy locking works\n** -----------------------\n**\n** Proxy file locking relies primarily on two new supporting files: \n**\n**   *  conch file to limit access to the database file to a single host\n**      at a time\n**\n**   *  proxy file to act as a proxy for the advisory locks normally\n**      taken on the database\n**\n** The conch file - to use a proxy file, sqlite must first \"hold the conch\"\n** by taking an sqlite-style shared lock on the conch file, reading the\n** contents and comparing the host's unique host ID (see below) and lock\n** proxy path against the values stored in the conch.  The conch file is\n** stored in the same directory as the database file and the file name\n** is patterned after the database file name as \".<databasename>-conch\".\n** If the conch file does not exist, or its contents do not match the\n** host ID and/or proxy path, then the lock is escalated to an exclusive\n** lock and the conch file contents is updated with the host ID and proxy\n** path and the lock is downgraded to a shared lock again.  If the conch\n** is held by another process (with a shared lock), the exclusive lock\n** will fail and SQLITE_BUSY is returned.\n**\n** The proxy file - a single-byte file used for all advisory file locks\n** normally taken on the database file.   This allows for safe sharing\n** of the database file for multiple readers and writers on the same\n** host (the conch ensures that they all use the same local lock file).\n**\n** Requesting the lock proxy does not immediately take the conch, it is\n** only taken when the first request to lock database file is made.  \n** This matches the semantics of the traditional locking behavior, where\n** opening a connection to a database file does not take a lock on it.\n** The shared lock and an open file descriptor are maintained until \n** the connection to the database is closed. \n**\n** The proxy file and the lock file are never deleted so they only need\n** to be created the first time they are used.\n**\n** Configuration options\n** ---------------------\n**\n**  SQLITE_PREFER_PROXY_LOCKING\n**\n**       Database files accessed on non-local file systems are\n**       automatically configured for proxy locking, lock files are\n**       named automatically using the same logic as\n**       PRAGMA lock_proxy_file=\":auto:\"\n**    \n**  SQLITE_PROXY_DEBUG\n**\n**       Enables the logging of error messages during host id file\n**       retrieval and creation\n**\n**  LOCKPROXYDIR\n**\n**       Overrides the default directory used for lock proxy files that\n**       are named automatically via the \":auto:\" setting\n**\n**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS\n**\n**       Permissions to use when creating a directory for storing the\n**       lock proxy files, only used when LOCKPROXYDIR is not set.\n**    \n**    \n** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,\n** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will\n** force proxy locking to be used for every database file opened, and 0\n** will force automatic proxy locking to be disabled for all database\n** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or\n** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).\n*/\n\n/*\n** Proxy locking is only available on MacOSX \n*/\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\n\n/*\n** The proxyLockingContext has the path and file structures for the remote \n** and local proxy files in it\n*/\ntypedef struct proxyLockingContext proxyLockingContext;\nstruct proxyLockingContext {\n  unixFile *conchFile;         /* Open conch file */\n  char *conchFilePath;         /* Name of the conch file */\n  unixFile *lockProxy;         /* Open proxy lock file */\n  char *lockProxyPath;         /* Name of the proxy lock file */\n  char *dbPath;                /* Name of the open file */\n  int conchHeld;               /* 1 if the conch is held, -1 if lockless */\n  int nFails;                  /* Number of conch taking failures */\n  void *oldLockingContext;     /* Original lockingcontext to restore on close */\n  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */\n};\n\n/* \n** The proxy lock file path for the database at dbPath is written into lPath, \n** which must point to valid, writable memory large enough for a maxLen length\n** file path. \n*/\nstatic int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){\n  int len;\n  int dbLen;\n  int i;\n\n#ifdef LOCKPROXYDIR\n  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);\n#else\n# ifdef _CS_DARWIN_USER_TEMP_DIR\n  {\n    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){\n      OSTRACE((\"GETLOCKPATH  failed %s errno=%d pid=%d\\n\",\n               lPath, errno, osGetpid(0)));\n      return SQLITE_IOERR_LOCK;\n    }\n    len = strlcat(lPath, \"sqliteplocks\", maxLen);    \n  }\n# else\n  len = strlcpy(lPath, \"/tmp/\", maxLen);\n# endif\n#endif\n\n  if( lPath[len-1]!='/' ){\n    len = strlcat(lPath, \"/\", maxLen);\n  }\n  \n  /* transform the db path to a unique cache name */\n  dbLen = (int)strlen(dbPath);\n  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){\n    char c = dbPath[i];\n    lPath[i+len] = (c=='/')?'_':c;\n  }\n  lPath[i+len]='\\0';\n  strlcat(lPath, \":auto:\", maxLen);\n  OSTRACE((\"GETLOCKPATH  proxy lock path=%s pid=%d\\n\", lPath, osGetpid(0)));\n  return SQLITE_OK;\n}\n\n/* \n ** Creates the lock file and any missing directories in lockPath\n */\nstatic int proxyCreateLockPath(const char *lockPath){\n  int i, len;\n  char buf[MAXPATHLEN];\n  int start = 0;\n  \n  assert(lockPath!=NULL);\n  /* try to create all the intermediate directories */\n  len = (int)strlen(lockPath);\n  buf[0] = lockPath[0];\n  for( i=1; i<len; i++ ){\n    if( lockPath[i] == '/' && (i - start > 0) ){\n      /* only mkdir if leaf dir != \".\" or \"/\" or \"..\" */\n      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') \n         || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){\n        buf[i]='\\0';\n        if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){\n          int err=errno;\n          if( err!=EEXIST ) {\n            OSTRACE((\"CREATELOCKPATH  FAILED creating %s, \"\n                     \"'%s' proxy lock path=%s pid=%d\\n\",\n                     buf, strerror(err), lockPath, osGetpid(0)));\n            return err;\n          }\n        }\n      }\n      start=i+1;\n    }\n    buf[i] = lockPath[i];\n  }\n  OSTRACE((\"CREATELOCKPATH  proxy lock path=%s pid=%d\\n\",lockPath,osGetpid(0)));\n  return 0;\n}\n\n/*\n** Create a new VFS file descriptor (stored in memory obtained from\n** sqlite3_malloc) and open the file named \"path\" in the file descriptor.\n**\n** The caller is responsible not only for closing the file descriptor\n** but also for freeing the memory associated with the file descriptor.\n*/\nstatic int proxyCreateUnixFile(\n    const char *path,        /* path for the new unixFile */\n    unixFile **ppFile,       /* unixFile created and returned by ref */\n    int islockfile           /* if non zero missing dirs will be created */\n) {\n  int fd = -1;\n  unixFile *pNew;\n  int rc = SQLITE_OK;\n  int openFlags = O_RDWR | O_CREAT | O_NOFOLLOW;\n  sqlite3_vfs dummyVfs;\n  int terrno = 0;\n  UnixUnusedFd *pUnused = NULL;\n\n  /* 1. first try to open/create the file\n  ** 2. if that fails, and this is a lock file (not-conch), try creating\n  ** the parent directories and then try again.\n  ** 3. if that fails, try to open the file read-only\n  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file\n  */\n  pUnused = findReusableFd(path, openFlags);\n  if( pUnused ){\n    fd = pUnused->fd;\n  }else{\n    pUnused = sqlite3_malloc64(sizeof(*pUnused));\n    if( !pUnused ){\n      return SQLITE_NOMEM_BKPT;\n    }\n  }\n  if( fd<0 ){\n    fd = robust_open(path, openFlags, 0);\n    terrno = errno;\n    if( fd<0 && errno==ENOENT && islockfile ){\n      if( proxyCreateLockPath(path) == SQLITE_OK ){\n        fd = robust_open(path, openFlags, 0);\n      }\n    }\n  }\n  if( fd<0 ){\n    openFlags = O_RDONLY | O_NOFOLLOW;\n    fd = robust_open(path, openFlags, 0);\n    terrno = errno;\n  }\n  if( fd<0 ){\n    if( islockfile ){\n      return SQLITE_BUSY;\n    }\n    switch (terrno) {\n      case EACCES:\n        return SQLITE_PERM;\n      case EIO: \n        return SQLITE_IOERR_LOCK; /* even though it is the conch */\n      default:\n        return SQLITE_CANTOPEN_BKPT;\n    }\n  }\n  \n  pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));\n  if( pNew==NULL ){\n    rc = SQLITE_NOMEM_BKPT;\n    goto end_create_proxy;\n  }\n  memset(pNew, 0, sizeof(unixFile));\n  pNew->openFlags = openFlags;\n  memset(&dummyVfs, 0, sizeof(dummyVfs));\n  dummyVfs.pAppData = (void*)&autolockIoFinder;\n  dummyVfs.zName = \"dummy\";\n  pUnused->fd = fd;\n  pUnused->flags = openFlags;\n  pNew->pPreallocatedUnused = pUnused;\n  \n  rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);\n  if( rc==SQLITE_OK ){\n    *ppFile = pNew;\n    return SQLITE_OK;\n  }\nend_create_proxy:    \n  robust_close(pNew, fd, __LINE__);\n  sqlite3_free(pNew);\n  sqlite3_free(pUnused);\n  return rc;\n}\n\n#ifdef SQLITE_TEST\n/* simulate multiple hosts by creating unique hostid file paths */\nSQLITE_API int sqlite3_hostid_num = 0;\n#endif\n\n#define PROXY_HOSTIDLEN    16  /* conch file host id length */\n\n#if HAVE_GETHOSTUUID\n/* Not always defined in the headers as it ought to be */\nextern int gethostuuid(uuid_t id, const struct timespec *wait);\n#endif\n\n/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN \n** bytes of writable memory.\n*/\nstatic int proxyGetHostID(unsigned char *pHostID, int *pError){\n  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));\n  memset(pHostID, 0, PROXY_HOSTIDLEN);\n#if HAVE_GETHOSTUUID\n  {\n    struct timespec timeout = {1, 0}; /* 1 sec timeout */\n    if( gethostuuid(pHostID, &timeout) ){\n      int err = errno;\n      if( pError ){\n        *pError = err;\n      }\n      return SQLITE_IOERR;\n    }\n  }\n#else\n  UNUSED_PARAMETER(pError);\n#endif\n#ifdef SQLITE_TEST\n  /* simulate multiple hosts by creating unique hostid file paths */\n  if( sqlite3_hostid_num != 0){\n    pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));\n  }\n#endif\n  \n  return SQLITE_OK;\n}\n\n/* The conch file contains the header, host id and lock file path\n */\n#define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */\n#define PROXY_HEADERLEN    1   /* conch file header length */\n#define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)\n#define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)\n\n/* \n** Takes an open conch file, copies the contents to a new path and then moves \n** it back.  The newly created file's file descriptor is assigned to the\n** conch file structure and finally the original conch file descriptor is \n** closed.  Returns zero if successful.\n*/\nstatic int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){\n  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; \n  unixFile *conchFile = pCtx->conchFile;\n  char tPath[MAXPATHLEN];\n  char buf[PROXY_MAXCONCHLEN];\n  char *cPath = pCtx->conchFilePath;\n  size_t readLen = 0;\n  size_t pathLen = 0;\n  char errmsg[64] = \"\";\n  int fd = -1;\n  int rc = -1;\n  UNUSED_PARAMETER(myHostID);\n\n  /* create a new path by replace the trailing '-conch' with '-break' */\n  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);\n  if( pathLen>MAXPATHLEN || pathLen<6 || \n     (strlcpy(&tPath[pathLen-5], \"break\", 6) != 5) ){\n    sqlite3_snprintf(sizeof(errmsg),errmsg,\"path error (len %d)\",(int)pathLen);\n    goto end_breaklock;\n  }\n  /* read the conch content */\n  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);\n  if( readLen<PROXY_PATHINDEX ){\n    sqlite3_snprintf(sizeof(errmsg),errmsg,\"read error (len %d)\",(int)readLen);\n    goto end_breaklock;\n  }\n  /* write it out to the temporary break file */\n  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW), 0);\n  if( fd<0 ){\n    sqlite3_snprintf(sizeof(errmsg), errmsg, \"create failed (%d)\", errno);\n    goto end_breaklock;\n  }\n  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){\n    sqlite3_snprintf(sizeof(errmsg), errmsg, \"write failed (%d)\", errno);\n    goto end_breaklock;\n  }\n  if( rename(tPath, cPath) ){\n    sqlite3_snprintf(sizeof(errmsg), errmsg, \"rename failed (%d)\", errno);\n    goto end_breaklock;\n  }\n  rc = 0;\n  fprintf(stderr, \"broke stale lock on %s\\n\", cPath);\n  robust_close(pFile, conchFile->h, __LINE__);\n  conchFile->h = fd;\n  conchFile->openFlags = O_RDWR | O_CREAT;\n\nend_breaklock:\n  if( rc ){\n    if( fd>=0 ){\n      osUnlink(tPath);\n      robust_close(pFile, fd, __LINE__);\n    }\n    fprintf(stderr, \"failed to break stale lock on %s, %s\\n\", cPath, errmsg);\n  }\n  return rc;\n}\n\n/* Take the requested lock on the conch file and break a stale lock if the \n** host id matches.\n*/\nstatic int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){\n  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; \n  unixFile *conchFile = pCtx->conchFile;\n  int rc = SQLITE_OK;\n  int nTries = 0;\n  struct timespec conchModTime;\n  \n  memset(&conchModTime, 0, sizeof(conchModTime));\n  do {\n    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);\n    nTries ++;\n    if( rc==SQLITE_BUSY ){\n      /* If the lock failed (busy):\n       * 1st try: get the mod time of the conch, wait 0.5s and try again. \n       * 2nd try: fail if the mod time changed or host id is different, wait \n       *           10 sec and try again\n       * 3rd try: break the lock unless the mod time has changed.\n       */\n      struct stat buf;\n      if( osFstat(conchFile->h, &buf) ){\n        storeLastErrno(pFile, errno);\n        return SQLITE_IOERR_LOCK;\n      }\n      \n      if( nTries==1 ){\n        conchModTime = buf.st_mtimespec;\n        usleep(500000); /* wait 0.5 sec and try the lock again*/\n        continue;  \n      }\n\n      assert( nTries>1 );\n      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || \n         conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){\n        return SQLITE_BUSY;\n      }\n      \n      if( nTries==2 ){  \n        char tBuf[PROXY_MAXCONCHLEN];\n        int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);\n        if( len<0 ){\n          storeLastErrno(pFile, errno);\n          return SQLITE_IOERR_LOCK;\n        }\n        if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){\n          /* don't break the lock if the host id doesn't match */\n          if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){\n            return SQLITE_BUSY;\n          }\n        }else{\n          /* don't break the lock on short read or a version mismatch */\n          return SQLITE_BUSY;\n        }\n        usleep(10000000); /* wait 10 sec and try the lock again */\n        continue; \n      }\n      \n      assert( nTries==3 );\n      if( 0==proxyBreakConchLock(pFile, myHostID) ){\n        rc = SQLITE_OK;\n        if( lockType==EXCLUSIVE_LOCK ){\n          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);\n        }\n        if( !rc ){\n          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);\n        }\n      }\n    }\n  } while( rc==SQLITE_BUSY && nTries<3 );\n  \n  return rc;\n}\n\n/* Takes the conch by taking a shared lock and read the contents conch, if \n** lockPath is non-NULL, the host ID and lock file path must match.  A NULL \n** lockPath means that the lockPath in the conch file will be used if the \n** host IDs match, or a new lock path will be generated automatically \n** and written to the conch file.\n*/\nstatic int proxyTakeConch(unixFile *pFile){\n  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; \n  \n  if( pCtx->conchHeld!=0 ){\n    return SQLITE_OK;\n  }else{\n    unixFile *conchFile = pCtx->conchFile;\n    uuid_t myHostID;\n    int pError = 0;\n    char readBuf[PROXY_MAXCONCHLEN];\n    char lockPath[MAXPATHLEN];\n    char *tempLockPath = NULL;\n    int rc = SQLITE_OK;\n    int createConch = 0;\n    int hostIdMatch = 0;\n    int readLen = 0;\n    int tryOldLockPath = 0;\n    int forceNewLockPath = 0;\n    \n    OSTRACE((\"TAKECONCH  %d for %s pid=%d\\n\", conchFile->h,\n             (pCtx->lockProxyPath ? pCtx->lockProxyPath : \":auto:\"),\n             osGetpid(0)));\n\n    rc = proxyGetHostID(myHostID, &pError);\n    if( (rc&0xff)==SQLITE_IOERR ){\n      storeLastErrno(pFile, pError);\n      goto end_takeconch;\n    }\n    rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);\n    if( rc!=SQLITE_OK ){\n      goto end_takeconch;\n    }\n    /* read the existing conch file */\n    readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);\n    if( readLen<0 ){\n      /* I/O error: lastErrno set by seekAndRead */\n      storeLastErrno(pFile, conchFile->lastErrno);\n      rc = SQLITE_IOERR_READ;\n      goto end_takeconch;\n    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || \n             readBuf[0]!=(char)PROXY_CONCHVERSION ){\n      /* a short read or version format mismatch means we need to create a new \n      ** conch file. \n      */\n      createConch = 1;\n    }\n    /* if the host id matches and the lock path already exists in the conch\n    ** we'll try to use the path there, if we can't open that path, we'll \n    ** retry with a new auto-generated path \n    */\n    do { /* in case we need to try again for an :auto: named lock file */\n\n      if( !createConch && !forceNewLockPath ){\n        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, \n                                  PROXY_HOSTIDLEN);\n        /* if the conch has data compare the contents */\n        if( !pCtx->lockProxyPath ){\n          /* for auto-named local lock file, just check the host ID and we'll\n           ** use the local lock file path that's already in there\n           */\n          if( hostIdMatch ){\n            size_t pathLen = (readLen - PROXY_PATHINDEX);\n            \n            if( pathLen>=MAXPATHLEN ){\n              pathLen=MAXPATHLEN-1;\n            }\n            memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);\n            lockPath[pathLen] = 0;\n            tempLockPath = lockPath;\n            tryOldLockPath = 1;\n            /* create a copy of the lock path if the conch is taken */\n            goto end_takeconch;\n          }\n        }else if( hostIdMatch\n               && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],\n                           readLen-PROXY_PATHINDEX)\n        ){\n          /* conch host and lock path match */\n          goto end_takeconch; \n        }\n      }\n      \n      /* if the conch isn't writable and doesn't match, we can't take it */\n      if( (conchFile->openFlags&O_RDWR) == 0 ){\n        rc = SQLITE_BUSY;\n        goto end_takeconch;\n      }\n      \n      /* either the conch didn't match or we need to create a new one */\n      if( !pCtx->lockProxyPath ){\n        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);\n        tempLockPath = lockPath;\n        /* create a copy of the lock path _only_ if the conch is taken */\n      }\n      \n      /* update conch with host and path (this will fail if other process\n      ** has a shared lock already), if the host id matches, use the big\n      ** stick.\n      */\n      futimes(conchFile->h, NULL);\n      if( hostIdMatch && !createConch ){\n        if( conchFile->pInode && conchFile->pInode->nShared>1 ){\n          /* We are trying for an exclusive lock but another thread in this\n           ** same process is still holding a shared lock. */\n          rc = SQLITE_BUSY;\n        } else {          \n          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);\n        }\n      }else{\n        rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);\n      }\n      if( rc==SQLITE_OK ){\n        char writeBuffer[PROXY_MAXCONCHLEN];\n        int writeSize = 0;\n        \n        writeBuffer[0] = (char)PROXY_CONCHVERSION;\n        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);\n        if( pCtx->lockProxyPath!=NULL ){\n          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,\n                  MAXPATHLEN);\n        }else{\n          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);\n        }\n        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);\n        robust_ftruncate(conchFile->h, writeSize);\n        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);\n        full_fsync(conchFile->h,0,0);\n        /* If we created a new conch file (not just updated the contents of a \n         ** valid conch file), try to match the permissions of the database \n         */\n        if( rc==SQLITE_OK && createConch ){\n          struct stat buf;\n          int err = osFstat(pFile->h, &buf);\n          if( err==0 ){\n            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |\n                                        S_IROTH|S_IWOTH);\n            /* try to match the database file R/W permissions, ignore failure */\n#ifndef SQLITE_PROXY_DEBUG\n            osFchmod(conchFile->h, cmode);\n#else\n            do{\n              rc = osFchmod(conchFile->h, cmode);\n            }while( rc==(-1) && errno==EINTR );\n            if( rc!=0 ){\n              int code = errno;\n              fprintf(stderr, \"fchmod %o FAILED with %d %s\\n\",\n                      cmode, code, strerror(code));\n            } else {\n              fprintf(stderr, \"fchmod %o SUCCEDED\\n\",cmode);\n            }\n          }else{\n            int code = errno;\n            fprintf(stderr, \"STAT FAILED[%d] with %d %s\\n\", \n                    err, code, strerror(code));\n#endif\n          }\n        }\n      }\n      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);\n      \n    end_takeconch:\n      OSTRACE((\"TRANSPROXY: CLOSE  %d\\n\", pFile->h));\n      if( rc==SQLITE_OK && pFile->openFlags ){\n        int fd;\n        if( pFile->h>=0 ){\n          robust_close(pFile, pFile->h, __LINE__);\n        }\n        pFile->h = -1;\n        fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);\n        OSTRACE((\"TRANSPROXY: OPEN  %d\\n\", fd));\n        if( fd>=0 ){\n          pFile->h = fd;\n        }else{\n          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called\n           during locking */\n        }\n      }\n      if( rc==SQLITE_OK && !pCtx->lockProxy ){\n        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;\n        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);\n        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){\n          /* we couldn't create the proxy lock file with the old lock file path\n           ** so try again via auto-naming \n           */\n          forceNewLockPath = 1;\n          tryOldLockPath = 0;\n          continue; /* go back to the do {} while start point, try again */\n        }\n      }\n      if( rc==SQLITE_OK ){\n        /* Need to make a copy of path if we extracted the value\n         ** from the conch file or the path was allocated on the stack\n         */\n        if( tempLockPath ){\n          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);\n          if( !pCtx->lockProxyPath ){\n            rc = SQLITE_NOMEM_BKPT;\n          }\n        }\n      }\n      if( rc==SQLITE_OK ){\n        pCtx->conchHeld = 1;\n        \n        if( pCtx->lockProxy->pMethod == &afpIoMethods ){\n          afpLockingContext *afpCtx;\n          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;\n          afpCtx->dbPath = pCtx->lockProxyPath;\n        }\n      } else {\n        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);\n      }\n      OSTRACE((\"TAKECONCH  %d %s\\n\", conchFile->h,\n               rc==SQLITE_OK?\"ok\":\"failed\"));\n      return rc;\n    } while (1); /* in case we need to retry the :auto: lock file - \n                 ** we should never get here except via the 'continue' call. */\n  }\n}\n\n/*\n** If pFile holds a lock on a conch file, then release that lock.\n*/\nstatic int proxyReleaseConch(unixFile *pFile){\n  int rc = SQLITE_OK;         /* Subroutine return code */\n  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */\n  unixFile *conchFile;        /* Name of the conch file */\n\n  pCtx = (proxyLockingContext *)pFile->lockingContext;\n  conchFile = pCtx->conchFile;\n  OSTRACE((\"RELEASECONCH  %d for %s pid=%d\\n\", conchFile->h,\n           (pCtx->lockProxyPath ? pCtx->lockProxyPath : \":auto:\"), \n           osGetpid(0)));\n  if( pCtx->conchHeld>0 ){\n    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);\n  }\n  pCtx->conchHeld = 0;\n  OSTRACE((\"RELEASECONCH  %d %s\\n\", conchFile->h,\n           (rc==SQLITE_OK ? \"ok\" : \"failed\")));\n  return rc;\n}\n\n/*\n** Given the name of a database file, compute the name of its conch file.\n** Store the conch filename in memory obtained from sqlite3_malloc64().\n** Make *pConchPath point to the new name.  Return SQLITE_OK on success\n** or SQLITE_NOMEM if unable to obtain memory.\n**\n** The caller is responsible for ensuring that the allocated memory\n** space is eventually freed.\n**\n** *pConchPath is set to NULL if a memory allocation error occurs.\n*/\nstatic int proxyCreateConchPathname(char *dbPath, char **pConchPath){\n  int i;                        /* Loop counter */\n  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */\n  char *conchPath;              /* buffer in which to construct conch name */\n\n  /* Allocate space for the conch filename and initialize the name to\n  ** the name of the original database file. */  \n  *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);\n  if( conchPath==0 ){\n    return SQLITE_NOMEM_BKPT;\n  }\n  memcpy(conchPath, dbPath, len+1);\n  \n  /* now insert a \".\" before the last / character */\n  for( i=(len-1); i>=0; i-- ){\n    if( conchPath[i]=='/' ){\n      i++;\n      break;\n    }\n  }\n  conchPath[i]='.';\n  while ( i<len ){\n    conchPath[i+1]=dbPath[i];\n    i++;\n  }\n\n  /* append the \"-conch\" suffix to the file */\n  memcpy(&conchPath[i+1], \"-conch\", 7);\n  assert( (int)strlen(conchPath) == len+7 );\n\n  return SQLITE_OK;\n}\n\n\n/* Takes a fully configured proxy locking-style unix file and switches\n** the local lock file path \n*/\nstatic int switchLockProxyPath(unixFile *pFile, const char *path) {\n  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;\n  char *oldPath = pCtx->lockProxyPath;\n  int rc = SQLITE_OK;\n\n  if( pFile->eFileLock!=NO_LOCK ){\n    return SQLITE_BUSY;\n  }  \n\n  /* nothing to do if the path is NULL, :auto: or matches the existing path */\n  if( !path || path[0]=='\\0' || !strcmp(path, \":auto:\") ||\n    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){\n    return SQLITE_OK;\n  }else{\n    unixFile *lockProxy = pCtx->lockProxy;\n    pCtx->lockProxy=NULL;\n    pCtx->conchHeld = 0;\n    if( lockProxy!=NULL ){\n      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);\n      if( rc ) return rc;\n      sqlite3_free(lockProxy);\n    }\n    sqlite3_free(oldPath);\n    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);\n  }\n  \n  return rc;\n}\n\n/*\n** pFile is a file that has been opened by a prior xOpen call.  dbPath\n** is a string buffer at least MAXPATHLEN+1 characters in size.\n**\n** This routine find the filename associated with pFile and writes it\n** int dbPath.\n*/\nstatic int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){\n#if defined(__APPLE__)\n  if( pFile->pMethod == &afpIoMethods ){\n    /* afp style keeps a reference to the db path in the filePath field \n    ** of the struct */\n    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );\n    strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,\n            MAXPATHLEN);\n  } else\n#endif\n  if( pFile->pMethod == &dotlockIoMethods ){\n    /* dot lock style uses the locking context to store the dot lock\n    ** file path */\n    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);\n    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);\n  }else{\n    /* all other styles use the locking context to store the db file path */\n    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );\n    strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Takes an already filled in unix file and alters it so all file locking \n** will be performed on the local proxy lock file.  The following fields\n** are preserved in the locking context so that they can be restored and \n** the unix structure properly cleaned up at close time:\n**  ->lockingContext\n**  ->pMethod\n*/\nstatic int proxyTransformUnixFile(unixFile *pFile, const char *path) {\n  proxyLockingContext *pCtx;\n  char dbPath[MAXPATHLEN+1];       /* Name of the database file */\n  char *lockPath=NULL;\n  int rc = SQLITE_OK;\n  \n  if( pFile->eFileLock!=NO_LOCK ){\n    return SQLITE_BUSY;\n  }\n  proxyGetDbPathForUnixFile(pFile, dbPath);\n  if( !path || path[0]=='\\0' || !strcmp(path, \":auto:\") ){\n    lockPath=NULL;\n  }else{\n    lockPath=(char *)path;\n  }\n  \n  OSTRACE((\"TRANSPROXY  %d for %s pid=%d\\n\", pFile->h,\n           (lockPath ? lockPath : \":auto:\"), osGetpid(0)));\n\n  pCtx = sqlite3_malloc64( sizeof(*pCtx) );\n  if( pCtx==0 ){\n    return SQLITE_NOMEM_BKPT;\n  }\n  memset(pCtx, 0, sizeof(*pCtx));\n\n  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);\n  if( rc==SQLITE_OK ){\n    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);\n    if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){\n      /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and\n      ** (c) the file system is read-only, then enable no-locking access.\n      ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts\n      ** that openFlags will have only one of O_RDONLY or O_RDWR.\n      */\n      struct statfs fsInfo;\n      struct stat conchInfo;\n      int goLockless = 0;\n\n      if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {\n        int err = errno;\n        if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){\n          goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;\n        }\n      }\n      if( goLockless ){\n        pCtx->conchHeld = -1; /* read only FS/ lockless */\n        rc = SQLITE_OK;\n      }\n    }\n  }  \n  if( rc==SQLITE_OK && lockPath ){\n    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);\n  }\n\n  if( rc==SQLITE_OK ){\n    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);\n    if( pCtx->dbPath==NULL ){\n      rc = SQLITE_NOMEM_BKPT;\n    }\n  }\n  if( rc==SQLITE_OK ){\n    /* all memory is allocated, proxys are created and assigned, \n    ** switch the locking context and pMethod then return.\n    */\n    pCtx->oldLockingContext = pFile->lockingContext;\n    pFile->lockingContext = pCtx;\n    pCtx->pOldMethod = pFile->pMethod;\n    pFile->pMethod = &proxyIoMethods;\n  }else{\n    if( pCtx->conchFile ){ \n      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);\n      sqlite3_free(pCtx->conchFile);\n    }\n    sqlite3DbFree(0, pCtx->lockProxyPath);\n    sqlite3_free(pCtx->conchFilePath); \n    sqlite3_free(pCtx);\n  }\n  OSTRACE((\"TRANSPROXY  %d %s\\n\", pFile->h,\n           (rc==SQLITE_OK ? \"ok\" : \"failed\")));\n  return rc;\n}\n\n\n/*\n** This routine handles sqlite3_file_control() calls that are specific\n** to proxy locking.\n*/\nstatic int proxyFileControl(sqlite3_file *id, int op, void *pArg){\n  switch( op ){\n    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {\n      unixFile *pFile = (unixFile*)id;\n      if( pFile->pMethod == &proxyIoMethods ){\n        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;\n        proxyTakeConch(pFile);\n        if( pCtx->lockProxyPath ){\n          *(const char **)pArg = pCtx->lockProxyPath;\n        }else{\n          *(const char **)pArg = \":auto: (not held)\";\n        }\n      } else {\n        *(const char **)pArg = NULL;\n      }\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_SET_LOCKPROXYFILE: {\n      unixFile *pFile = (unixFile*)id;\n      int rc = SQLITE_OK;\n      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);\n      if( pArg==NULL || (const char *)pArg==0 ){\n        if( isProxyStyle ){\n          /* turn off proxy locking - not supported.  If support is added for\n          ** switching proxy locking mode off then it will need to fail if\n          ** the journal mode is WAL mode. \n          */\n          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;\n        }else{\n          /* turn off proxy locking - already off - NOOP */\n          rc = SQLITE_OK;\n        }\n      }else{\n        const char *proxyPath = (const char *)pArg;\n        if( isProxyStyle ){\n          proxyLockingContext *pCtx = \n            (proxyLockingContext*)pFile->lockingContext;\n          if( !strcmp(pArg, \":auto:\") \n           || (pCtx->lockProxyPath &&\n               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))\n          ){\n            rc = SQLITE_OK;\n          }else{\n            rc = switchLockProxyPath(pFile, proxyPath);\n          }\n        }else{\n          /* turn on proxy file locking */\n          rc = proxyTransformUnixFile(pFile, proxyPath);\n        }\n      }\n      return rc;\n    }\n    default: {\n      assert( 0 );  /* The call assures that only valid opcodes are sent */\n    }\n  }\n  /*NOTREACHED*/ assert(0);\n  return SQLITE_ERROR;\n}\n\n/*\n** Within this division (the proxying locking implementation) the procedures\n** above this point are all utilities.  The lock-related methods of the\n** proxy-locking sqlite3_io_method object follow.\n*/\n\n\n/*\n** This routine checks if there is a RESERVED lock held on the specified\n** file by this or any other process. If such a lock is held, set *pResOut\n** to a non-zero value otherwise *pResOut is set to zero.  The return value\n** is set to SQLITE_OK unless an I/O error occurs during lock checking.\n*/\nstatic int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {\n  unixFile *pFile = (unixFile*)id;\n  int rc = proxyTakeConch(pFile);\n  if( rc==SQLITE_OK ){\n    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;\n    if( pCtx->conchHeld>0 ){\n      unixFile *proxy = pCtx->lockProxy;\n      return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);\n    }else{ /* conchHeld < 0 is lockless */\n      pResOut=0;\n    }\n  }\n  return rc;\n}\n\n/*\n** Lock the file with the lock specified by parameter eFileLock - one\n** of the following:\n**\n**     (1) SHARED_LOCK\n**     (2) RESERVED_LOCK\n**     (3) PENDING_LOCK\n**     (4) EXCLUSIVE_LOCK\n**\n** Sometimes when requesting one lock state, additional lock states\n** are inserted in between.  The locking might fail on one of the later\n** transitions leaving the lock state different from what it started but\n** still short of its goal.  The following chart shows the allowed\n** transitions and the inserted intermediate states:\n**\n**    UNLOCKED -> SHARED\n**    SHARED -> RESERVED\n**    SHARED -> (PENDING) -> EXCLUSIVE\n**    RESERVED -> (PENDING) -> EXCLUSIVE\n**    PENDING -> EXCLUSIVE\n**\n** This routine will only increase a lock.  Use the sqlite3OsUnlock()\n** routine to lower a locking level.\n*/\nstatic int proxyLock(sqlite3_file *id, int eFileLock) {\n  unixFile *pFile = (unixFile*)id;\n  int rc = proxyTakeConch(pFile);\n  if( rc==SQLITE_OK ){\n    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;\n    if( pCtx->conchHeld>0 ){\n      unixFile *proxy = pCtx->lockProxy;\n      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);\n      pFile->eFileLock = proxy->eFileLock;\n    }else{\n      /* conchHeld < 0 is lockless */\n    }\n  }\n  return rc;\n}\n\n\n/*\n** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock\n** must be either NO_LOCK or SHARED_LOCK.\n**\n** If the locking level of the file descriptor is already at or below\n** the requested locking level, this routine is a no-op.\n*/\nstatic int proxyUnlock(sqlite3_file *id, int eFileLock) {\n  unixFile *pFile = (unixFile*)id;\n  int rc = proxyTakeConch(pFile);\n  if( rc==SQLITE_OK ){\n    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;\n    if( pCtx->conchHeld>0 ){\n      unixFile *proxy = pCtx->lockProxy;\n      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);\n      pFile->eFileLock = proxy->eFileLock;\n    }else{\n      /* conchHeld < 0 is lockless */\n    }\n  }\n  return rc;\n}\n\n/*\n** Close a file that uses proxy locks.\n*/\nstatic int proxyClose(sqlite3_file *id) {\n  if( ALWAYS(id) ){\n    unixFile *pFile = (unixFile*)id;\n    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;\n    unixFile *lockProxy = pCtx->lockProxy;\n    unixFile *conchFile = pCtx->conchFile;\n    int rc = SQLITE_OK;\n    \n    if( lockProxy ){\n      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);\n      if( rc ) return rc;\n      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);\n      if( rc ) return rc;\n      sqlite3_free(lockProxy);\n      pCtx->lockProxy = 0;\n    }\n    if( conchFile ){\n      if( pCtx->conchHeld ){\n        rc = proxyReleaseConch(pFile);\n        if( rc ) return rc;\n      }\n      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);\n      if( rc ) return rc;\n      sqlite3_free(conchFile);\n    }\n    sqlite3DbFree(0, pCtx->lockProxyPath);\n    sqlite3_free(pCtx->conchFilePath);\n    sqlite3DbFree(0, pCtx->dbPath);\n    /* restore the original locking context and pMethod then close it */\n    pFile->lockingContext = pCtx->oldLockingContext;\n    pFile->pMethod = pCtx->pOldMethod;\n    sqlite3_free(pCtx);\n    return pFile->pMethod->xClose(id);\n  }\n  return SQLITE_OK;\n}\n\n\n\n#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */\n/*\n** The proxy locking style is intended for use with AFP filesystems.\n** And since AFP is only supported on MacOSX, the proxy locking is also\n** restricted to MacOSX.\n** \n**\n******************* End of the proxy lock implementation **********************\n******************************************************************************/\n\n/*\n** Initialize the operating system interface.\n**\n** This routine registers all VFS implementations for unix-like operating\n** systems.  This routine, and the sqlite3_os_end() routine that follows,\n** should be the only routines in this file that are visible from other\n** files.\n**\n** This routine is called once during SQLite initialization and by a\n** single thread.  The memory allocation and mutex subsystems have not\n** necessarily been initialized when this routine is called, and so they\n** should not be used.\n*/\nSQLITE_API int sqlite3_os_init(void){ \n  /* \n  ** The following macro defines an initializer for an sqlite3_vfs object.\n  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer\n  ** to the \"finder\" function.  (pAppData is a pointer to a pointer because\n  ** silly C90 rules prohibit a void* from being cast to a function pointer\n  ** and so we have to go through the intermediate pointer to avoid problems\n  ** when compiling with -pedantic-errors on GCC.)\n  **\n  ** The FINDER parameter to this macro is the name of the pointer to the\n  ** finder-function.  The finder-function returns a pointer to the\n  ** sqlite_io_methods object that implements the desired locking\n  ** behaviors.  See the division above that contains the IOMETHODS\n  ** macro for addition information on finder-functions.\n  **\n  ** Most finders simply return a pointer to a fixed sqlite3_io_methods\n  ** object.  But the \"autolockIoFinder\" available on MacOSX does a little\n  ** more than that; it looks at the filesystem type that hosts the \n  ** database file and tries to choose an locking method appropriate for\n  ** that filesystem time.\n  */\n  #define UNIXVFS(VFSNAME, FINDER) {                        \\\n    3,                    /* iVersion */                    \\\n    sizeof(unixFile),     /* szOsFile */                    \\\n    MAX_PATHNAME,         /* mxPathname */                  \\\n    0,                    /* pNext */                       \\\n    VFSNAME,              /* zName */                       \\\n    (void*)&FINDER,       /* pAppData */                    \\\n    unixOpen,             /* xOpen */                       \\\n    unixDelete,           /* xDelete */                     \\\n    unixAccess,           /* xAccess */                     \\\n    unixFullPathname,     /* xFullPathname */               \\\n    unixDlOpen,           /* xDlOpen */                     \\\n    unixDlError,          /* xDlError */                    \\\n    unixDlSym,            /* xDlSym */                      \\\n    unixDlClose,          /* xDlClose */                    \\\n    unixRandomness,       /* xRandomness */                 \\\n    unixSleep,            /* xSleep */                      \\\n    unixCurrentTime,      /* xCurrentTime */                \\\n    unixGetLastError,     /* xGetLastError */               \\\n    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \\\n    unixSetSystemCall,    /* xSetSystemCall */              \\\n    unixGetSystemCall,    /* xGetSystemCall */              \\\n    unixNextSystemCall,   /* xNextSystemCall */             \\\n  }\n\n  /*\n  ** All default VFSes for unix are contained in the following array.\n  **\n  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified\n  ** by the SQLite core when the VFS is registered.  So the following\n  ** array cannot be const.\n  */\n  static sqlite3_vfs aVfs[] = {\n#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)\n    UNIXVFS(\"unix\",          autolockIoFinder ),\n#elif OS_VXWORKS\n    UNIXVFS(\"unix\",          vxworksIoFinder ),\n#else\n    UNIXVFS(\"unix\",          posixIoFinder ),\n#endif\n    UNIXVFS(\"unix-none\",     nolockIoFinder ),\n    UNIXVFS(\"unix-dotfile\",  dotlockIoFinder ),\n    UNIXVFS(\"unix-excl\",     posixIoFinder ),\n#if OS_VXWORKS\n    UNIXVFS(\"unix-namedsem\", semIoFinder ),\n#endif\n#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS\n    UNIXVFS(\"unix-posix\",    posixIoFinder ),\n#endif\n#if SQLITE_ENABLE_LOCKING_STYLE\n    UNIXVFS(\"unix-flock\",    flockIoFinder ),\n#endif\n#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)\n    UNIXVFS(\"unix-afp\",      afpIoFinder ),\n    UNIXVFS(\"unix-nfs\",      nfsIoFinder ),\n    UNIXVFS(\"unix-proxy\",    proxyIoFinder ),\n#endif\n  };\n  unsigned int i;          /* Loop counter */\n\n  /* Double-check that the aSyscall[] array has been constructed\n  ** correctly.  See ticket [bb3a86e890c8e96ab] */\n  assert( ArraySize(aSyscall)==29 );\n\n  /* Register all VFSes defined in the aVfs[] array */\n  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){\n    sqlite3_vfs_register(&aVfs[i], i==0);\n  }\n  unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);\n  return SQLITE_OK; \n}\n\n/*\n** Shutdown the operating system interface.\n**\n** Some operating systems might need to do some cleanup in this routine,\n** to release dynamically allocated objects.  But not on unix.\n** This routine is a no-op for unix.\n*/\nSQLITE_API int sqlite3_os_end(void){ \n  unixBigLock = 0;\n  return SQLITE_OK; \n}\n \n#endif /* SQLITE_OS_UNIX */\n\n/************** End of os_unix.c *********************************************/\n/************** Begin file os_win.c ******************************************/\n/*\n** 2004 May 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains code that is specific to Windows.\n*/\n/* #include \"sqliteInt.h\" */\n#if SQLITE_OS_WIN               /* This file is used for Windows only */\n\n/*\n** Include code that is common to all os_*.c files\n*/\n/************** Include os_common.h in the middle of os_win.c ****************/\n/************** Begin file os_common.h ***************************************/\n/*\n** 2004 May 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains macros and a little bit of code that is common to\n** all of the platform-specific files (os_*.c) and is #included into those\n** files.\n**\n** This file should be #included by the os_*.c files only.  It is not a\n** general purpose header file.\n*/\n#ifndef _OS_COMMON_H_\n#define _OS_COMMON_H_\n\n/*\n** At least two bugs have slipped in because we changed the MEMORY_DEBUG\n** macro to SQLITE_DEBUG and some older makefiles have not yet made the\n** switch.  The following code should catch this problem at compile-time.\n*/\n#ifdef MEMORY_DEBUG\n# error \"The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead.\"\n#endif\n\n/*\n** Macros for performance tracing.  Normally turned off.  Only works\n** on i486 hardware.\n*/\n#ifdef SQLITE_PERFORMANCE_TRACE\n\n/*\n** hwtime.h contains inline assembler code for implementing\n** high-performance timing routines.\n*/\n/************** Include hwtime.h in the middle of os_common.h ****************/\n/************** Begin file hwtime.h ******************************************/\n/*\n** 2008 May 27\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains inline asm code for retrieving \"high-performance\"\n** counters for x86 and x86_64 class CPUs.\n*/\n#ifndef SQLITE_HWTIME_H\n#define SQLITE_HWTIME_H\n\n/*\n** The following routine only works on pentium-class (or newer) processors.\n** It uses the RDTSC opcode to read the cycle count value out of the\n** processor and returns that value.  This can be used for high-res\n** profiling.\n*/\n#if !defined(__STRICT_ANSI__) && \\\n    (defined(__GNUC__) || defined(_MSC_VER)) && \\\n    (defined(i386) || defined(__i386__) || defined(_M_IX86))\n\n  #if defined(__GNUC__)\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n     unsigned int lo, hi;\n     __asm__ __volatile__ (\"rdtsc\" : \"=a\" (lo), \"=d\" (hi));\n     return (sqlite_uint64)hi << 32 | lo;\n  }\n\n  #elif defined(_MSC_VER)\n\n  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){\n     __asm {\n        rdtsc\n        ret       ; return value at EDX:EAX\n     }\n  }\n\n  #endif\n\n#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n      unsigned long val;\n      __asm__ __volatile__ (\"rdtsc\" : \"=A\" (val));\n      return val;\n  }\n \n#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n      unsigned long long retval;\n      unsigned long junk;\n      __asm__ __volatile__ (\"\\n\\\n          1:      mftbu   %1\\n\\\n                  mftb    %L0\\n\\\n                  mftbu   %0\\n\\\n                  cmpw    %0,%1\\n\\\n                  bne     1b\"\n                  : \"=r\" (retval), \"=r\" (junk));\n      return retval;\n  }\n\n#else\n\n  /*\n  ** asm() is needed for hardware timing support.  Without asm(),\n  ** disable the sqlite3Hwtime() routine.\n  **\n  ** sqlite3Hwtime() is only used for some obscure debugging\n  ** and analysis configurations, not in any deliverable, so this\n  ** should not be a great loss.\n  */\nSQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }\n\n#endif\n\n#endif /* !defined(SQLITE_HWTIME_H) */\n\n/************** End of hwtime.h **********************************************/\n/************** Continuing where we left off in os_common.h ******************/\n\nstatic sqlite_uint64 g_start;\nstatic sqlite_uint64 g_elapsed;\n#define TIMER_START       g_start=sqlite3Hwtime()\n#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start\n#define TIMER_ELAPSED     g_elapsed\n#else\n#define TIMER_START\n#define TIMER_END\n#define TIMER_ELAPSED     ((sqlite_uint64)0)\n#endif\n\n/*\n** If we compile with the SQLITE_TEST macro set, then the following block\n** of code will give us the ability to simulate a disk I/O error.  This\n** is used for testing the I/O recovery logic.\n*/\n#if defined(SQLITE_TEST)\nSQLITE_API extern int sqlite3_io_error_hit;\nSQLITE_API extern int sqlite3_io_error_hardhit;\nSQLITE_API extern int sqlite3_io_error_pending;\nSQLITE_API extern int sqlite3_io_error_persist;\nSQLITE_API extern int sqlite3_io_error_benign;\nSQLITE_API extern int sqlite3_diskfull_pending;\nSQLITE_API extern int sqlite3_diskfull;\n#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)\n#define SimulateIOError(CODE)  \\\n  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \\\n       || sqlite3_io_error_pending-- == 1 )  \\\n              { local_ioerr(); CODE; }\nstatic void local_ioerr(){\n  IOTRACE((\"IOERR\\n\"));\n  sqlite3_io_error_hit++;\n  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;\n}\n#define SimulateDiskfullError(CODE) \\\n   if( sqlite3_diskfull_pending ){ \\\n     if( sqlite3_diskfull_pending == 1 ){ \\\n       local_ioerr(); \\\n       sqlite3_diskfull = 1; \\\n       sqlite3_io_error_hit = 1; \\\n       CODE; \\\n     }else{ \\\n       sqlite3_diskfull_pending--; \\\n     } \\\n   }\n#else\n#define SimulateIOErrorBenign(X)\n#define SimulateIOError(A)\n#define SimulateDiskfullError(A)\n#endif /* defined(SQLITE_TEST) */\n\n/*\n** When testing, keep a count of the number of open files.\n*/\n#if defined(SQLITE_TEST)\nSQLITE_API extern int sqlite3_open_file_count;\n#define OpenCounter(X)  sqlite3_open_file_count+=(X)\n#else\n#define OpenCounter(X)\n#endif /* defined(SQLITE_TEST) */\n\n#endif /* !defined(_OS_COMMON_H_) */\n\n/************** End of os_common.h *******************************************/\n/************** Continuing where we left off in os_win.c *********************/\n\n/*\n** Include the header file for the Windows VFS.\n*/\n/* #include \"os_win.h\" */\n\n/*\n** Compiling and using WAL mode requires several APIs that are only\n** available in Windows platforms based on the NT kernel.\n*/\n#if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)\n#  error \"WAL mode requires support from the Windows NT kernel, compile\\\n with SQLITE_OMIT_WAL.\"\n#endif\n\n#if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0\n#  error \"Memory mapped files require support from the Windows NT kernel,\\\n compile with SQLITE_MAX_MMAP_SIZE=0.\"\n#endif\n\n/*\n** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions\n** based on the sub-platform)?\n*/\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)\n#  define SQLITE_WIN32_HAS_ANSI\n#endif\n\n/*\n** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions\n** based on the sub-platform)?\n*/\n#if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \\\n    !defined(SQLITE_WIN32_NO_WIDE)\n#  define SQLITE_WIN32_HAS_WIDE\n#endif\n\n/*\n** Make sure at least one set of Win32 APIs is available.\n*/\n#if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)\n#  error \"At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\\\n must be defined.\"\n#endif\n\n/*\n** Define the required Windows SDK version constants if they are not\n** already available.\n*/\n#ifndef NTDDI_WIN8\n#  define NTDDI_WIN8                        0x06020000\n#endif\n\n#ifndef NTDDI_WINBLUE\n#  define NTDDI_WINBLUE                     0x06030000\n#endif\n\n#ifndef NTDDI_WINTHRESHOLD\n#  define NTDDI_WINTHRESHOLD                0x06040000\n#endif\n\n/*\n** Check to see if the GetVersionEx[AW] functions are deprecated on the\n** target system.  GetVersionEx was first deprecated in Win8.1.\n*/\n#ifndef SQLITE_WIN32_GETVERSIONEX\n#  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE\n#    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */\n#  else\n#    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */\n#  endif\n#endif\n\n/*\n** Check to see if the CreateFileMappingA function is supported on the\n** target system.  It is unavailable when using \"mincore.lib\" on Win10.\n** When compiling for Windows 10, always assume \"mincore.lib\" is in use.\n*/\n#ifndef SQLITE_WIN32_CREATEFILEMAPPINGA\n#  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD\n#    define SQLITE_WIN32_CREATEFILEMAPPINGA   0\n#  else\n#    define SQLITE_WIN32_CREATEFILEMAPPINGA   1\n#  endif\n#endif\n\n/*\n** This constant should already be defined (in the \"WinDef.h\" SDK file).\n*/\n#ifndef MAX_PATH\n#  define MAX_PATH                      (260)\n#endif\n\n/*\n** Maximum pathname length (in chars) for Win32.  This should normally be\n** MAX_PATH.\n*/\n#ifndef SQLITE_WIN32_MAX_PATH_CHARS\n#  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)\n#endif\n\n/*\n** This constant should already be defined (in the \"WinNT.h\" SDK file).\n*/\n#ifndef UNICODE_STRING_MAX_CHARS\n#  define UNICODE_STRING_MAX_CHARS      (32767)\n#endif\n\n/*\n** Maximum pathname length (in chars) for WinNT.  This should normally be\n** UNICODE_STRING_MAX_CHARS.\n*/\n#ifndef SQLITE_WINNT_MAX_PATH_CHARS\n#  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)\n#endif\n\n/*\n** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in\n** characters, so we allocate 4 bytes per character assuming worst-case of\n** 4-bytes-per-character for UTF8.\n*/\n#ifndef SQLITE_WIN32_MAX_PATH_BYTES\n#  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)\n#endif\n\n/*\n** Maximum pathname length (in bytes) for WinNT.  This should normally be\n** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).\n*/\n#ifndef SQLITE_WINNT_MAX_PATH_BYTES\n#  define SQLITE_WINNT_MAX_PATH_BYTES   \\\n                            (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)\n#endif\n\n/*\n** Maximum error message length (in chars) for WinRT.\n*/\n#ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS\n#  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)\n#endif\n\n/*\n** Returns non-zero if the character should be treated as a directory\n** separator.\n*/\n#ifndef winIsDirSep\n#  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\\\'))\n#endif\n\n/*\n** This macro is used when a local variable is set to a value that is\n** [sometimes] not used by the code (e.g. via conditional compilation).\n*/\n#ifndef UNUSED_VARIABLE_VALUE\n#  define UNUSED_VARIABLE_VALUE(x)      (void)(x)\n#endif\n\n/*\n** Returns the character that should be used as the directory separator.\n*/\n#ifndef winGetDirSep\n#  define winGetDirSep()                '\\\\'\n#endif\n\n/*\n** Do we need to manually define the Win32 file mapping APIs for use with WAL\n** mode or memory mapped files (e.g. these APIs are available in the Windows\n** CE SDK; however, they are not present in the header file)?\n*/\n#if SQLITE_WIN32_FILEMAPPING_API && \\\n        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)\n/*\n** Two of the file mapping APIs are different under WinRT.  Figure out which\n** set we need.\n*/\n#if SQLITE_OS_WINRT\nWINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \\\n        LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);\n\nWINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);\n#else\n#if defined(SQLITE_WIN32_HAS_ANSI)\nWINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \\\n        DWORD, DWORD, DWORD, LPCSTR);\n#endif /* defined(SQLITE_WIN32_HAS_ANSI) */\n\n#if defined(SQLITE_WIN32_HAS_WIDE)\nWINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \\\n        DWORD, DWORD, DWORD, LPCWSTR);\n#endif /* defined(SQLITE_WIN32_HAS_WIDE) */\n\nWINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);\n#endif /* SQLITE_OS_WINRT */\n\n/*\n** These file mapping APIs are common to both Win32 and WinRT.\n*/\n\nWINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);\nWINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);\n#endif /* SQLITE_WIN32_FILEMAPPING_API */\n\n/*\n** Some Microsoft compilers lack this definition.\n*/\n#ifndef INVALID_FILE_ATTRIBUTES\n# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)\n#endif\n\n#ifndef FILE_FLAG_MASK\n# define FILE_FLAG_MASK          (0xFF3C0000)\n#endif\n\n#ifndef FILE_ATTRIBUTE_MASK\n# define FILE_ATTRIBUTE_MASK     (0x0003FFF7)\n#endif\n\n#ifndef SQLITE_OMIT_WAL\n/* Forward references to structures used for WAL */\ntypedef struct winShm winShm;           /* A connection to shared-memory */\ntypedef struct winShmNode winShmNode;   /* A region of shared-memory */\n#endif\n\n/*\n** WinCE lacks native support for file locking so we have to fake it\n** with some code of our own.\n*/\n#if SQLITE_OS_WINCE\ntypedef struct winceLock {\n  int nReaders;       /* Number of reader locks obtained */\n  BOOL bPending;      /* Indicates a pending lock has been obtained */\n  BOOL bReserved;     /* Indicates a reserved lock has been obtained */\n  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */\n} winceLock;\n#endif\n\n/*\n** The winFile structure is a subclass of sqlite3_file* specific to the win32\n** portability layer.\n*/\ntypedef struct winFile winFile;\nstruct winFile {\n  const sqlite3_io_methods *pMethod; /*** Must be first ***/\n  sqlite3_vfs *pVfs;      /* The VFS used to open this file */\n  HANDLE h;               /* Handle for accessing the file */\n  u8 locktype;            /* Type of lock currently held on this file */\n  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */\n  u8 ctrlFlags;           /* Flags.  See WINFILE_* below */\n  DWORD lastErrno;        /* The Windows errno from the last I/O error */\n#ifndef SQLITE_OMIT_WAL\n  winShm *pShm;           /* Instance of shared memory on this file */\n#endif\n  const char *zPath;      /* Full pathname of this file */\n  int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */\n#if SQLITE_OS_WINCE\n  LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */\n  HANDLE hMutex;          /* Mutex used to control access to shared lock */\n  HANDLE hShared;         /* Shared memory segment used for locking */\n  winceLock local;        /* Locks obtained by this instance of winFile */\n  winceLock *shared;      /* Global shared lock memory for the file  */\n#endif\n#if SQLITE_MAX_MMAP_SIZE>0\n  int nFetchOut;                /* Number of outstanding xFetch references */\n  HANDLE hMap;                  /* Handle for accessing memory mapping */\n  void *pMapRegion;             /* Area memory mapped */\n  sqlite3_int64 mmapSize;       /* Size of mapped region */\n  sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */\n#endif\n};\n\n/*\n** The winVfsAppData structure is used for the pAppData member for all of the\n** Win32 VFS variants.\n*/\ntypedef struct winVfsAppData winVfsAppData;\nstruct winVfsAppData {\n  const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */\n  void *pAppData;                    /* The extra pAppData, if any. */\n  BOOL bNoLock;                      /* Non-zero if locking is disabled. */\n};\n\n/*\n** Allowed values for winFile.ctrlFlags\n*/\n#define WINFILE_RDONLY          0x02   /* Connection is read only */\n#define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */\n#define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */\n\n/*\n * The size of the buffer used by sqlite3_win32_write_debug().\n */\n#ifndef SQLITE_WIN32_DBG_BUF_SIZE\n#  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))\n#endif\n\n/*\n * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the\n * various Win32 API heap functions instead of our own.\n */\n#ifdef SQLITE_WIN32_MALLOC\n\n/*\n * If this is non-zero, an isolated heap will be created by the native Win32\n * allocator subsystem; otherwise, the default process heap will be used.  This\n * setting has no effect when compiling for WinRT.  By default, this is enabled\n * and an isolated heap will be created to store all allocated data.\n *\n ******************************************************************************\n * WARNING: It is important to note that when this setting is non-zero and the\n *          winMemShutdown function is called (e.g. by the sqlite3_shutdown\n *          function), all data that was allocated using the isolated heap will\n *          be freed immediately and any attempt to access any of that freed\n *          data will almost certainly result in an immediate access violation.\n ******************************************************************************\n */\n#ifndef SQLITE_WIN32_HEAP_CREATE\n#  define SQLITE_WIN32_HEAP_CREATE        (TRUE)\n#endif\n\n/*\n * This is the maximum possible initial size of the Win32-specific heap, in\n * bytes.\n */\n#ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE\n#  define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)\n#endif\n\n/*\n * This is the extra space for the initial size of the Win32-specific heap,\n * in bytes.  This value may be zero.\n */\n#ifndef SQLITE_WIN32_HEAP_INIT_EXTRA\n#  define SQLITE_WIN32_HEAP_INIT_EXTRA  (4194304)\n#endif\n\n/*\n * Calculate the maximum legal cache size, in pages, based on the maximum\n * possible initial heap size and the default page size, setting aside the\n * needed extra space.\n */\n#ifndef SQLITE_WIN32_MAX_CACHE_SIZE\n#  define SQLITE_WIN32_MAX_CACHE_SIZE   (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \\\n                                          (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \\\n                                         (SQLITE_DEFAULT_PAGE_SIZE))\n#endif\n\n/*\n * This is cache size used in the calculation of the initial size of the\n * Win32-specific heap.  It cannot be negative.\n */\n#ifndef SQLITE_WIN32_CACHE_SIZE\n#  if SQLITE_DEFAULT_CACHE_SIZE>=0\n#    define SQLITE_WIN32_CACHE_SIZE     (SQLITE_DEFAULT_CACHE_SIZE)\n#  else\n#    define SQLITE_WIN32_CACHE_SIZE     (-(SQLITE_DEFAULT_CACHE_SIZE))\n#  endif\n#endif\n\n/*\n * Make sure that the calculated cache size, in pages, cannot cause the\n * initial size of the Win32-specific heap to exceed the maximum amount\n * of memory that can be specified in the call to HeapCreate.\n */\n#if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE\n#  undef SQLITE_WIN32_CACHE_SIZE\n#  define SQLITE_WIN32_CACHE_SIZE       (2000)\n#endif\n\n/*\n * The initial size of the Win32-specific heap.  This value may be zero.\n */\n#ifndef SQLITE_WIN32_HEAP_INIT_SIZE\n#  define SQLITE_WIN32_HEAP_INIT_SIZE   ((SQLITE_WIN32_CACHE_SIZE) * \\\n                                         (SQLITE_DEFAULT_PAGE_SIZE) + \\\n                                         (SQLITE_WIN32_HEAP_INIT_EXTRA))\n#endif\n\n/*\n * The maximum size of the Win32-specific heap.  This value may be zero.\n */\n#ifndef SQLITE_WIN32_HEAP_MAX_SIZE\n#  define SQLITE_WIN32_HEAP_MAX_SIZE    (0)\n#endif\n\n/*\n * The extra flags to use in calls to the Win32 heap APIs.  This value may be\n * zero for the default behavior.\n */\n#ifndef SQLITE_WIN32_HEAP_FLAGS\n#  define SQLITE_WIN32_HEAP_FLAGS       (0)\n#endif\n\n\n/*\n** The winMemData structure stores information required by the Win32-specific\n** sqlite3_mem_methods implementation.\n*/\ntypedef struct winMemData winMemData;\nstruct winMemData {\n#ifndef NDEBUG\n  u32 magic1;   /* Magic number to detect structure corruption. */\n#endif\n  HANDLE hHeap; /* The handle to our heap. */\n  BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */\n#ifndef NDEBUG\n  u32 magic2;   /* Magic number to detect structure corruption. */\n#endif\n};\n\n#ifndef NDEBUG\n#define WINMEM_MAGIC1     0x42b2830b\n#define WINMEM_MAGIC2     0xbd4d7cf4\n#endif\n\nstatic struct winMemData win_mem_data = {\n#ifndef NDEBUG\n  WINMEM_MAGIC1,\n#endif\n  NULL, FALSE\n#ifndef NDEBUG\n  ,WINMEM_MAGIC2\n#endif\n};\n\n#ifndef NDEBUG\n#define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )\n#define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )\n#define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();\n#else\n#define winMemAssertMagic()\n#endif\n\n#define winMemGetDataPtr()  &win_mem_data\n#define winMemGetHeap()     win_mem_data.hHeap\n#define winMemGetOwned()    win_mem_data.bOwned\n\nstatic void *winMemMalloc(int nBytes);\nstatic void winMemFree(void *pPrior);\nstatic void *winMemRealloc(void *pPrior, int nBytes);\nstatic int winMemSize(void *p);\nstatic int winMemRoundup(int n);\nstatic int winMemInit(void *pAppData);\nstatic void winMemShutdown(void *pAppData);\n\nSQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);\n#endif /* SQLITE_WIN32_MALLOC */\n\n/*\n** The following variable is (normally) set once and never changes\n** thereafter.  It records whether the operating system is Win9x\n** or WinNT.\n**\n** 0:   Operating system unknown.\n** 1:   Operating system is Win9x.\n** 2:   Operating system is WinNT.\n**\n** In order to facilitate testing on a WinNT system, the test fixture\n** can manually set this value to 1 to emulate Win98 behavior.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;\n#else\nstatic LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;\n#endif\n\n#ifndef SYSCALL\n#  define SYSCALL sqlite3_syscall_ptr\n#endif\n\n/*\n** This function is not available on Windows CE or WinRT.\n */\n\n#if SQLITE_OS_WINCE || SQLITE_OS_WINRT\n#  define osAreFileApisANSI()       1\n#endif\n\n/*\n** Many system calls are accessed through pointer-to-functions so that\n** they may be overridden at runtime to facilitate fault injection during\n** testing and sandboxing.  The following array holds the names and pointers\n** to all overrideable system calls.\n*/\nstatic struct win_syscall {\n  const char *zName;            /* Name of the system call */\n  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */\n  sqlite3_syscall_ptr pDefault; /* Default value */\n} aSyscall[] = {\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT\n  { \"AreFileApisANSI\",         (SYSCALL)AreFileApisANSI,         0 },\n#else\n  { \"AreFileApisANSI\",         (SYSCALL)0,                       0 },\n#endif\n\n#ifndef osAreFileApisANSI\n#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)\n#endif\n\n#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"CharLowerW\",              (SYSCALL)CharLowerW,              0 },\n#else\n  { \"CharLowerW\",              (SYSCALL)0,                       0 },\n#endif\n\n#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)\n\n#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"CharUpperW\",              (SYSCALL)CharUpperW,              0 },\n#else\n  { \"CharUpperW\",              (SYSCALL)0,                       0 },\n#endif\n\n#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)\n\n  { \"CloseHandle\",             (SYSCALL)CloseHandle,             0 },\n\n#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_ANSI)\n  { \"CreateFileA\",             (SYSCALL)CreateFileA,             0 },\n#else\n  { \"CreateFileA\",             (SYSCALL)0,                       0 },\n#endif\n\n#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \\\n        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)\n\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"CreateFileW\",             (SYSCALL)CreateFileW,             0 },\n#else\n  { \"CreateFileW\",             (SYSCALL)0,                       0 },\n#endif\n\n#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \\\n        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)\n\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \\\n        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \\\n        SQLITE_WIN32_CREATEFILEMAPPINGA\n  { \"CreateFileMappingA\",      (SYSCALL)CreateFileMappingA,      0 },\n#else\n  { \"CreateFileMappingA\",      (SYSCALL)0,                       0 },\n#endif\n\n#define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \\\n        DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)\n\n#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \\\n        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))\n  { \"CreateFileMappingW\",      (SYSCALL)CreateFileMappingW,      0 },\n#else\n  { \"CreateFileMappingW\",      (SYSCALL)0,                       0 },\n#endif\n\n#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \\\n        DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)\n\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"CreateMutexW\",            (SYSCALL)CreateMutexW,            0 },\n#else\n  { \"CreateMutexW\",            (SYSCALL)0,                       0 },\n#endif\n\n#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \\\n        LPCWSTR))aSyscall[8].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_ANSI)\n  { \"DeleteFileA\",             (SYSCALL)DeleteFileA,             0 },\n#else\n  { \"DeleteFileA\",             (SYSCALL)0,                       0 },\n#endif\n\n#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_WIDE)\n  { \"DeleteFileW\",             (SYSCALL)DeleteFileW,             0 },\n#else\n  { \"DeleteFileW\",             (SYSCALL)0,                       0 },\n#endif\n\n#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)\n\n#if SQLITE_OS_WINCE\n  { \"FileTimeToLocalFileTime\", (SYSCALL)FileTimeToLocalFileTime, 0 },\n#else\n  { \"FileTimeToLocalFileTime\", (SYSCALL)0,                       0 },\n#endif\n\n#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \\\n        LPFILETIME))aSyscall[11].pCurrent)\n\n#if SQLITE_OS_WINCE\n  { \"FileTimeToSystemTime\",    (SYSCALL)FileTimeToSystemTime,    0 },\n#else\n  { \"FileTimeToSystemTime\",    (SYSCALL)0,                       0 },\n#endif\n\n#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \\\n        LPSYSTEMTIME))aSyscall[12].pCurrent)\n\n  { \"FlushFileBuffers\",        (SYSCALL)FlushFileBuffers,        0 },\n\n#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_ANSI)\n  { \"FormatMessageA\",          (SYSCALL)FormatMessageA,          0 },\n#else\n  { \"FormatMessageA\",          (SYSCALL)0,                       0 },\n#endif\n\n#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \\\n        DWORD,va_list*))aSyscall[14].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_WIDE)\n  { \"FormatMessageW\",          (SYSCALL)FormatMessageW,          0 },\n#else\n  { \"FormatMessageW\",          (SYSCALL)0,                       0 },\n#endif\n\n#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \\\n        DWORD,va_list*))aSyscall[15].pCurrent)\n\n#if !defined(SQLITE_OMIT_LOAD_EXTENSION)\n  { \"FreeLibrary\",             (SYSCALL)FreeLibrary,             0 },\n#else\n  { \"FreeLibrary\",             (SYSCALL)0,                       0 },\n#endif\n\n#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)\n\n  { \"GetCurrentProcessId\",     (SYSCALL)GetCurrentProcessId,     0 },\n\n#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)\n\n#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)\n  { \"GetDiskFreeSpaceA\",       (SYSCALL)GetDiskFreeSpaceA,       0 },\n#else\n  { \"GetDiskFreeSpaceA\",       (SYSCALL)0,                       0 },\n#endif\n\n#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \\\n        LPDWORD))aSyscall[18].pCurrent)\n\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"GetDiskFreeSpaceW\",       (SYSCALL)GetDiskFreeSpaceW,       0 },\n#else\n  { \"GetDiskFreeSpaceW\",       (SYSCALL)0,                       0 },\n#endif\n\n#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \\\n        LPDWORD))aSyscall[19].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_ANSI)\n  { \"GetFileAttributesA\",      (SYSCALL)GetFileAttributesA,      0 },\n#else\n  { \"GetFileAttributesA\",      (SYSCALL)0,                       0 },\n#endif\n\n#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)\n\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"GetFileAttributesW\",      (SYSCALL)GetFileAttributesW,      0 },\n#else\n  { \"GetFileAttributesW\",      (SYSCALL)0,                       0 },\n#endif\n\n#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_WIDE)\n  { \"GetFileAttributesExW\",    (SYSCALL)GetFileAttributesExW,    0 },\n#else\n  { \"GetFileAttributesExW\",    (SYSCALL)0,                       0 },\n#endif\n\n#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \\\n        LPVOID))aSyscall[22].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"GetFileSize\",             (SYSCALL)GetFileSize,             0 },\n#else\n  { \"GetFileSize\",             (SYSCALL)0,                       0 },\n#endif\n\n#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)\n\n#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)\n  { \"GetFullPathNameA\",        (SYSCALL)GetFullPathNameA,        0 },\n#else\n  { \"GetFullPathNameA\",        (SYSCALL)0,                       0 },\n#endif\n\n#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \\\n        LPSTR*))aSyscall[24].pCurrent)\n\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"GetFullPathNameW\",        (SYSCALL)GetFullPathNameW,        0 },\n#else\n  { \"GetFullPathNameW\",        (SYSCALL)0,                       0 },\n#endif\n\n#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \\\n        LPWSTR*))aSyscall[25].pCurrent)\n\n  { \"GetLastError\",            (SYSCALL)GetLastError,            0 },\n\n#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)\n\n#if !defined(SQLITE_OMIT_LOAD_EXTENSION)\n#if SQLITE_OS_WINCE\n  /* The GetProcAddressA() routine is only available on Windows CE. */\n  { \"GetProcAddressA\",         (SYSCALL)GetProcAddressA,         0 },\n#else\n  /* All other Windows platforms expect GetProcAddress() to take\n  ** an ANSI string regardless of the _UNICODE setting */\n  { \"GetProcAddressA\",         (SYSCALL)GetProcAddress,          0 },\n#endif\n#else\n  { \"GetProcAddressA\",         (SYSCALL)0,                       0 },\n#endif\n\n#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \\\n        LPCSTR))aSyscall[27].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"GetSystemInfo\",           (SYSCALL)GetSystemInfo,           0 },\n#else\n  { \"GetSystemInfo\",           (SYSCALL)0,                       0 },\n#endif\n\n#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)\n\n  { \"GetSystemTime\",           (SYSCALL)GetSystemTime,           0 },\n\n#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)\n\n#if !SQLITE_OS_WINCE\n  { \"GetSystemTimeAsFileTime\", (SYSCALL)GetSystemTimeAsFileTime, 0 },\n#else\n  { \"GetSystemTimeAsFileTime\", (SYSCALL)0,                       0 },\n#endif\n\n#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \\\n        LPFILETIME))aSyscall[30].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_ANSI)\n  { \"GetTempPathA\",            (SYSCALL)GetTempPathA,            0 },\n#else\n  { \"GetTempPathA\",            (SYSCALL)0,                       0 },\n#endif\n\n#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)\n\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"GetTempPathW\",            (SYSCALL)GetTempPathW,            0 },\n#else\n  { \"GetTempPathW\",            (SYSCALL)0,                       0 },\n#endif\n\n#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"GetTickCount\",            (SYSCALL)GetTickCount,            0 },\n#else\n  { \"GetTickCount\",            (SYSCALL)0,                       0 },\n#endif\n\n#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX\n  { \"GetVersionExA\",           (SYSCALL)GetVersionExA,           0 },\n#else\n  { \"GetVersionExA\",           (SYSCALL)0,                       0 },\n#endif\n\n#define osGetVersionExA ((BOOL(WINAPI*)( \\\n        LPOSVERSIONINFOA))aSyscall[34].pCurrent)\n\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \\\n        SQLITE_WIN32_GETVERSIONEX\n  { \"GetVersionExW\",           (SYSCALL)GetVersionExW,           0 },\n#else\n  { \"GetVersionExW\",           (SYSCALL)0,                       0 },\n#endif\n\n#define osGetVersionExW ((BOOL(WINAPI*)( \\\n        LPOSVERSIONINFOW))aSyscall[35].pCurrent)\n\n  { \"HeapAlloc\",               (SYSCALL)HeapAlloc,               0 },\n\n#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \\\n        SIZE_T))aSyscall[36].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"HeapCreate\",              (SYSCALL)HeapCreate,              0 },\n#else\n  { \"HeapCreate\",              (SYSCALL)0,                       0 },\n#endif\n\n#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \\\n        SIZE_T))aSyscall[37].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"HeapDestroy\",             (SYSCALL)HeapDestroy,             0 },\n#else\n  { \"HeapDestroy\",             (SYSCALL)0,                       0 },\n#endif\n\n#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)\n\n  { \"HeapFree\",                (SYSCALL)HeapFree,                0 },\n\n#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)\n\n  { \"HeapReAlloc\",             (SYSCALL)HeapReAlloc,             0 },\n\n#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \\\n        SIZE_T))aSyscall[40].pCurrent)\n\n  { \"HeapSize\",                (SYSCALL)HeapSize,                0 },\n\n#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \\\n        LPCVOID))aSyscall[41].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"HeapValidate\",            (SYSCALL)HeapValidate,            0 },\n#else\n  { \"HeapValidate\",            (SYSCALL)0,                       0 },\n#endif\n\n#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \\\n        LPCVOID))aSyscall[42].pCurrent)\n\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT\n  { \"HeapCompact\",             (SYSCALL)HeapCompact,             0 },\n#else\n  { \"HeapCompact\",             (SYSCALL)0,                       0 },\n#endif\n\n#define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)\n  { \"LoadLibraryA\",            (SYSCALL)LoadLibraryA,            0 },\n#else\n  { \"LoadLibraryA\",            (SYSCALL)0,                       0 },\n#endif\n\n#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)\n\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \\\n        !defined(SQLITE_OMIT_LOAD_EXTENSION)\n  { \"LoadLibraryW\",            (SYSCALL)LoadLibraryW,            0 },\n#else\n  { \"LoadLibraryW\",            (SYSCALL)0,                       0 },\n#endif\n\n#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"LocalFree\",               (SYSCALL)LocalFree,               0 },\n#else\n  { \"LocalFree\",               (SYSCALL)0,                       0 },\n#endif\n\n#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)\n\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT\n  { \"LockFile\",                (SYSCALL)LockFile,                0 },\n#else\n  { \"LockFile\",                (SYSCALL)0,                       0 },\n#endif\n\n#ifndef osLockFile\n#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \\\n        DWORD))aSyscall[47].pCurrent)\n#endif\n\n#if !SQLITE_OS_WINCE\n  { \"LockFileEx\",              (SYSCALL)LockFileEx,              0 },\n#else\n  { \"LockFileEx\",              (SYSCALL)0,                       0 },\n#endif\n\n#ifndef osLockFileEx\n#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \\\n        LPOVERLAPPED))aSyscall[48].pCurrent)\n#endif\n\n#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \\\n        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))\n  { \"MapViewOfFile\",           (SYSCALL)MapViewOfFile,           0 },\n#else\n  { \"MapViewOfFile\",           (SYSCALL)0,                       0 },\n#endif\n\n#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \\\n        SIZE_T))aSyscall[49].pCurrent)\n\n  { \"MultiByteToWideChar\",     (SYSCALL)MultiByteToWideChar,     0 },\n\n#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \\\n        int))aSyscall[50].pCurrent)\n\n  { \"QueryPerformanceCounter\", (SYSCALL)QueryPerformanceCounter, 0 },\n\n#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \\\n        LARGE_INTEGER*))aSyscall[51].pCurrent)\n\n  { \"ReadFile\",                (SYSCALL)ReadFile,                0 },\n\n#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \\\n        LPOVERLAPPED))aSyscall[52].pCurrent)\n\n  { \"SetEndOfFile\",            (SYSCALL)SetEndOfFile,            0 },\n\n#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"SetFilePointer\",          (SYSCALL)SetFilePointer,          0 },\n#else\n  { \"SetFilePointer\",          (SYSCALL)0,                       0 },\n#endif\n\n#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \\\n        DWORD))aSyscall[54].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"Sleep\",                   (SYSCALL)Sleep,                   0 },\n#else\n  { \"Sleep\",                   (SYSCALL)0,                       0 },\n#endif\n\n#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)\n\n  { \"SystemTimeToFileTime\",    (SYSCALL)SystemTimeToFileTime,    0 },\n\n#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \\\n        LPFILETIME))aSyscall[56].pCurrent)\n\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT\n  { \"UnlockFile\",              (SYSCALL)UnlockFile,              0 },\n#else\n  { \"UnlockFile\",              (SYSCALL)0,                       0 },\n#endif\n\n#ifndef osUnlockFile\n#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \\\n        DWORD))aSyscall[57].pCurrent)\n#endif\n\n#if !SQLITE_OS_WINCE\n  { \"UnlockFileEx\",            (SYSCALL)UnlockFileEx,            0 },\n#else\n  { \"UnlockFileEx\",            (SYSCALL)0,                       0 },\n#endif\n\n#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \\\n        LPOVERLAPPED))aSyscall[58].pCurrent)\n\n#if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0\n  { \"UnmapViewOfFile\",         (SYSCALL)UnmapViewOfFile,         0 },\n#else\n  { \"UnmapViewOfFile\",         (SYSCALL)0,                       0 },\n#endif\n\n#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)\n\n  { \"WideCharToMultiByte\",     (SYSCALL)WideCharToMultiByte,     0 },\n\n#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \\\n        LPCSTR,LPBOOL))aSyscall[60].pCurrent)\n\n  { \"WriteFile\",               (SYSCALL)WriteFile,               0 },\n\n#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \\\n        LPOVERLAPPED))aSyscall[61].pCurrent)\n\n#if SQLITE_OS_WINRT\n  { \"CreateEventExW\",          (SYSCALL)CreateEventExW,          0 },\n#else\n  { \"CreateEventExW\",          (SYSCALL)0,                       0 },\n#endif\n\n#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \\\n        DWORD,DWORD))aSyscall[62].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"WaitForSingleObject\",     (SYSCALL)WaitForSingleObject,     0 },\n#else\n  { \"WaitForSingleObject\",     (SYSCALL)0,                       0 },\n#endif\n\n#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \\\n        DWORD))aSyscall[63].pCurrent)\n\n#if !SQLITE_OS_WINCE\n  { \"WaitForSingleObjectEx\",   (SYSCALL)WaitForSingleObjectEx,   0 },\n#else\n  { \"WaitForSingleObjectEx\",   (SYSCALL)0,                       0 },\n#endif\n\n#define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \\\n        BOOL))aSyscall[64].pCurrent)\n\n#if SQLITE_OS_WINRT\n  { \"SetFilePointerEx\",        (SYSCALL)SetFilePointerEx,        0 },\n#else\n  { \"SetFilePointerEx\",        (SYSCALL)0,                       0 },\n#endif\n\n#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \\\n        PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)\n\n#if SQLITE_OS_WINRT\n  { \"GetFileInformationByHandleEx\", (SYSCALL)GetFileInformationByHandleEx, 0 },\n#else\n  { \"GetFileInformationByHandleEx\", (SYSCALL)0,                  0 },\n#endif\n\n#define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \\\n        FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)\n\n#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)\n  { \"MapViewOfFileFromApp\",    (SYSCALL)MapViewOfFileFromApp,    0 },\n#else\n  { \"MapViewOfFileFromApp\",    (SYSCALL)0,                       0 },\n#endif\n\n#define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \\\n        SIZE_T))aSyscall[67].pCurrent)\n\n#if SQLITE_OS_WINRT\n  { \"CreateFile2\",             (SYSCALL)CreateFile2,             0 },\n#else\n  { \"CreateFile2\",             (SYSCALL)0,                       0 },\n#endif\n\n#define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \\\n        LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)\n\n#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)\n  { \"LoadPackagedLibrary\",     (SYSCALL)LoadPackagedLibrary,     0 },\n#else\n  { \"LoadPackagedLibrary\",     (SYSCALL)0,                       0 },\n#endif\n\n#define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \\\n        DWORD))aSyscall[69].pCurrent)\n\n#if SQLITE_OS_WINRT\n  { \"GetTickCount64\",          (SYSCALL)GetTickCount64,          0 },\n#else\n  { \"GetTickCount64\",          (SYSCALL)0,                       0 },\n#endif\n\n#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)\n\n#if SQLITE_OS_WINRT\n  { \"GetNativeSystemInfo\",     (SYSCALL)GetNativeSystemInfo,     0 },\n#else\n  { \"GetNativeSystemInfo\",     (SYSCALL)0,                       0 },\n#endif\n\n#define osGetNativeSystemInfo ((VOID(WINAPI*)( \\\n        LPSYSTEM_INFO))aSyscall[71].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_ANSI)\n  { \"OutputDebugStringA\",      (SYSCALL)OutputDebugStringA,      0 },\n#else\n  { \"OutputDebugStringA\",      (SYSCALL)0,                       0 },\n#endif\n\n#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_WIDE)\n  { \"OutputDebugStringW\",      (SYSCALL)OutputDebugStringW,      0 },\n#else\n  { \"OutputDebugStringW\",      (SYSCALL)0,                       0 },\n#endif\n\n#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)\n\n  { \"GetProcessHeap\",          (SYSCALL)GetProcessHeap,          0 },\n\n#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)\n\n#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)\n  { \"CreateFileMappingFromApp\", (SYSCALL)CreateFileMappingFromApp, 0 },\n#else\n  { \"CreateFileMappingFromApp\", (SYSCALL)0,                      0 },\n#endif\n\n#define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \\\n        LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)\n\n/*\n** NOTE: On some sub-platforms, the InterlockedCompareExchange \"function\"\n**       is really just a macro that uses a compiler intrinsic (e.g. x64).\n**       So do not try to make this is into a redefinable interface.\n*/\n#if defined(InterlockedCompareExchange)\n  { \"InterlockedCompareExchange\", (SYSCALL)0,                    0 },\n\n#define osInterlockedCompareExchange InterlockedCompareExchange\n#else\n  { \"InterlockedCompareExchange\", (SYSCALL)InterlockedCompareExchange, 0 },\n\n#define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \\\n        SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)\n#endif /* defined(InterlockedCompareExchange) */\n\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID\n  { \"UuidCreate\",               (SYSCALL)UuidCreate,             0 },\n#else\n  { \"UuidCreate\",               (SYSCALL)0,                      0 },\n#endif\n\n#define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)\n\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID\n  { \"UuidCreateSequential\",     (SYSCALL)UuidCreateSequential,   0 },\n#else\n  { \"UuidCreateSequential\",     (SYSCALL)0,                      0 },\n#endif\n\n#define osUuidCreateSequential \\\n        ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)\n\n#if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0\n  { \"FlushViewOfFile\",          (SYSCALL)FlushViewOfFile,        0 },\n#else\n  { \"FlushViewOfFile\",          (SYSCALL)0,                      0 },\n#endif\n\n#define osFlushViewOfFile \\\n        ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)\n\n}; /* End of the overrideable system calls */\n\n/*\n** This is the xSetSystemCall() method of sqlite3_vfs for all of the\n** \"win32\" VFSes.  Return SQLITE_OK opon successfully updating the\n** system call pointer, or SQLITE_NOTFOUND if there is no configurable\n** system call named zName.\n*/\nstatic int winSetSystemCall(\n  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */\n  const char *zName,            /* Name of system call to override */\n  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */\n){\n  unsigned int i;\n  int rc = SQLITE_NOTFOUND;\n\n  UNUSED_PARAMETER(pNotUsed);\n  if( zName==0 ){\n    /* If no zName is given, restore all system calls to their default\n    ** settings and return NULL\n    */\n    rc = SQLITE_OK;\n    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){\n      if( aSyscall[i].pDefault ){\n        aSyscall[i].pCurrent = aSyscall[i].pDefault;\n      }\n    }\n  }else{\n    /* If zName is specified, operate on only the one system call\n    ** specified.\n    */\n    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){\n      if( strcmp(zName, aSyscall[i].zName)==0 ){\n        if( aSyscall[i].pDefault==0 ){\n          aSyscall[i].pDefault = aSyscall[i].pCurrent;\n        }\n        rc = SQLITE_OK;\n        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;\n        aSyscall[i].pCurrent = pNewFunc;\n        break;\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** Return the value of a system call.  Return NULL if zName is not a\n** recognized system call name.  NULL is also returned if the system call\n** is currently undefined.\n*/\nstatic sqlite3_syscall_ptr winGetSystemCall(\n  sqlite3_vfs *pNotUsed,\n  const char *zName\n){\n  unsigned int i;\n\n  UNUSED_PARAMETER(pNotUsed);\n  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){\n    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;\n  }\n  return 0;\n}\n\n/*\n** Return the name of the first system call after zName.  If zName==NULL\n** then return the name of the first system call.  Return NULL if zName\n** is the last system call or if zName is not the name of a valid\n** system call.\n*/\nstatic const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){\n  int i = -1;\n\n  UNUSED_PARAMETER(p);\n  if( zName ){\n    for(i=0; i<ArraySize(aSyscall)-1; i++){\n      if( strcmp(zName, aSyscall[i].zName)==0 ) break;\n    }\n  }\n  for(i++; i<ArraySize(aSyscall); i++){\n    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;\n  }\n  return 0;\n}\n\n#ifdef SQLITE_WIN32_MALLOC\n/*\n** If a Win32 native heap has been configured, this function will attempt to\n** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one\n** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The\n** \"pnLargest\" argument, if non-zero, will be used to return the size of the\n** largest committed free block in the heap, in bytes.\n*/\nSQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){\n  int rc = SQLITE_OK;\n  UINT nLargest = 0;\n  HANDLE hHeap;\n\n  winMemAssertMagic();\n  hHeap = winMemGetHeap();\n  assert( hHeap!=0 );\n  assert( hHeap!=INVALID_HANDLE_VALUE );\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)\n  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );\n#endif\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT\n  if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){\n    DWORD lastErrno = osGetLastError();\n    if( lastErrno==NO_ERROR ){\n      sqlite3_log(SQLITE_NOMEM, \"failed to HeapCompact (no space), heap=%p\",\n                  (void*)hHeap);\n      rc = SQLITE_NOMEM_BKPT;\n    }else{\n      sqlite3_log(SQLITE_ERROR, \"failed to HeapCompact (%lu), heap=%p\",\n                  osGetLastError(), (void*)hHeap);\n      rc = SQLITE_ERROR;\n    }\n  }\n#else\n  sqlite3_log(SQLITE_NOTFOUND, \"failed to HeapCompact, heap=%p\",\n              (void*)hHeap);\n  rc = SQLITE_NOTFOUND;\n#endif\n  if( pnLargest ) *pnLargest = nLargest;\n  return rc;\n}\n\n/*\n** If a Win32 native heap has been configured, this function will attempt to\n** destroy and recreate it.  If the Win32 native heap is not isolated and/or\n** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will\n** be returned and no changes will be made to the Win32 native heap.\n*/\nSQLITE_API int sqlite3_win32_reset_heap(){\n  int rc;\n  MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */\n  MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */\n  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )\n  MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )\n  sqlite3_mutex_enter(pMaster);\n  sqlite3_mutex_enter(pMem);\n  winMemAssertMagic();\n  if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){\n    /*\n    ** At this point, there should be no outstanding memory allocations on\n    ** the heap.  Also, since both the master and memsys locks are currently\n    ** being held by us, no other function (i.e. from another thread) should\n    ** be able to even access the heap.  Attempt to destroy and recreate our\n    ** isolated Win32 native heap now.\n    */\n    assert( winMemGetHeap()!=NULL );\n    assert( winMemGetOwned() );\n    assert( sqlite3_memory_used()==0 );\n    winMemShutdown(winMemGetDataPtr());\n    assert( winMemGetHeap()==NULL );\n    assert( !winMemGetOwned() );\n    assert( sqlite3_memory_used()==0 );\n    rc = winMemInit(winMemGetDataPtr());\n    assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );\n    assert( rc!=SQLITE_OK || winMemGetOwned() );\n    assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );\n  }else{\n    /*\n    ** The Win32 native heap cannot be modified because it may be in use.\n    */\n    rc = SQLITE_BUSY;\n  }\n  sqlite3_mutex_leave(pMem);\n  sqlite3_mutex_leave(pMaster);\n  return rc;\n}\n#endif /* SQLITE_WIN32_MALLOC */\n\n/*\n** This function outputs the specified (ANSI) string to the Win32 debugger\n** (if available).\n*/\n\nSQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){\n  char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];\n  int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */\n  if( nMin<-1 ) nMin = -1; /* all negative values become -1. */\n  assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !zBuf ){\n    (void)SQLITE_MISUSE_BKPT;\n    return;\n  }\n#endif\n#if defined(SQLITE_WIN32_HAS_ANSI)\n  if( nMin>0 ){\n    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);\n    memcpy(zDbgBuf, zBuf, nMin);\n    osOutputDebugStringA(zDbgBuf);\n  }else{\n    osOutputDebugStringA(zBuf);\n  }\n#elif defined(SQLITE_WIN32_HAS_WIDE)\n  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);\n  if ( osMultiByteToWideChar(\n          osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,\n          nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){\n    return;\n  }\n  osOutputDebugStringW((LPCWSTR)zDbgBuf);\n#else\n  if( nMin>0 ){\n    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);\n    memcpy(zDbgBuf, zBuf, nMin);\n    fprintf(stderr, \"%s\", zDbgBuf);\n  }else{\n    fprintf(stderr, \"%s\", zBuf);\n  }\n#endif\n}\n\n/*\n** The following routine suspends the current thread for at least ms\n** milliseconds.  This is equivalent to the Win32 Sleep() interface.\n*/\n#if SQLITE_OS_WINRT\nstatic HANDLE sleepObj = NULL;\n#endif\n\nSQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){\n#if SQLITE_OS_WINRT\n  if ( sleepObj==NULL ){\n    sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,\n                                SYNCHRONIZE);\n  }\n  assert( sleepObj!=NULL );\n  osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);\n#else\n  osSleep(milliseconds);\n#endif\n}\n\n#if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \\\n        SQLITE_THREADSAFE>0\nSQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){\n  DWORD rc;\n  while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,\n                                       TRUE))==WAIT_IO_COMPLETION ){}\n  return rc;\n}\n#endif\n\n/*\n** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,\n** or WinCE.  Return false (zero) for Win95, Win98, or WinME.\n**\n** Here is an interesting observation:  Win95, Win98, and WinME lack\n** the LockFileEx() API.  But we can still statically link against that\n** API as long as we don't call it when running Win95/98/ME.  A call to\n** this routine is used to determine if the host is Win95/98/ME or\n** WinNT/2K/XP so that we will know whether or not we can safely call\n** the LockFileEx() API.\n*/\n\n#if !SQLITE_WIN32_GETVERSIONEX\n# define osIsNT()  (1)\n#elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)\n# define osIsNT()  (1)\n#elif !defined(SQLITE_WIN32_HAS_WIDE)\n# define osIsNT()  (0)\n#else\n# define osIsNT()  ((sqlite3_os_type==2) || sqlite3_win32_is_nt())\n#endif\n\n/*\n** This function determines if the machine is running a version of Windows\n** based on the NT kernel.\n*/\nSQLITE_API int sqlite3_win32_is_nt(void){\n#if SQLITE_OS_WINRT\n  /*\n  ** NOTE: The WinRT sub-platform is always assumed to be based on the NT\n  **       kernel.\n  */\n  return 1;\n#elif SQLITE_WIN32_GETVERSIONEX\n  if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){\n#if defined(SQLITE_WIN32_HAS_ANSI)\n    OSVERSIONINFOA sInfo;\n    sInfo.dwOSVersionInfoSize = sizeof(sInfo);\n    osGetVersionExA(&sInfo);\n    osInterlockedCompareExchange(&sqlite3_os_type,\n        (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);\n#elif defined(SQLITE_WIN32_HAS_WIDE)\n    OSVERSIONINFOW sInfo;\n    sInfo.dwOSVersionInfoSize = sizeof(sInfo);\n    osGetVersionExW(&sInfo);\n    osInterlockedCompareExchange(&sqlite3_os_type,\n        (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);\n#endif\n  }\n  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;\n#elif SQLITE_TEST\n  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;\n#else\n  /*\n  ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are\n  **       deprecated are always assumed to be based on the NT kernel.\n  */\n  return 1;\n#endif\n}\n\n#ifdef SQLITE_WIN32_MALLOC\n/*\n** Allocate nBytes of memory.\n*/\nstatic void *winMemMalloc(int nBytes){\n  HANDLE hHeap;\n  void *p;\n\n  winMemAssertMagic();\n  hHeap = winMemGetHeap();\n  assert( hHeap!=0 );\n  assert( hHeap!=INVALID_HANDLE_VALUE );\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)\n  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );\n#endif\n  assert( nBytes>=0 );\n  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);\n  if( !p ){\n    sqlite3_log(SQLITE_NOMEM, \"failed to HeapAlloc %u bytes (%lu), heap=%p\",\n                nBytes, osGetLastError(), (void*)hHeap);\n  }\n  return p;\n}\n\n/*\n** Free memory.\n*/\nstatic void winMemFree(void *pPrior){\n  HANDLE hHeap;\n\n  winMemAssertMagic();\n  hHeap = winMemGetHeap();\n  assert( hHeap!=0 );\n  assert( hHeap!=INVALID_HANDLE_VALUE );\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)\n  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );\n#endif\n  if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */\n  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){\n    sqlite3_log(SQLITE_NOMEM, \"failed to HeapFree block %p (%lu), heap=%p\",\n                pPrior, osGetLastError(), (void*)hHeap);\n  }\n}\n\n/*\n** Change the size of an existing memory allocation\n*/\nstatic void *winMemRealloc(void *pPrior, int nBytes){\n  HANDLE hHeap;\n  void *p;\n\n  winMemAssertMagic();\n  hHeap = winMemGetHeap();\n  assert( hHeap!=0 );\n  assert( hHeap!=INVALID_HANDLE_VALUE );\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)\n  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );\n#endif\n  assert( nBytes>=0 );\n  if( !pPrior ){\n    p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);\n  }else{\n    p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);\n  }\n  if( !p ){\n    sqlite3_log(SQLITE_NOMEM, \"failed to %s %u bytes (%lu), heap=%p\",\n                pPrior ? \"HeapReAlloc\" : \"HeapAlloc\", nBytes, osGetLastError(),\n                (void*)hHeap);\n  }\n  return p;\n}\n\n/*\n** Return the size of an outstanding allocation, in bytes.\n*/\nstatic int winMemSize(void *p){\n  HANDLE hHeap;\n  SIZE_T n;\n\n  winMemAssertMagic();\n  hHeap = winMemGetHeap();\n  assert( hHeap!=0 );\n  assert( hHeap!=INVALID_HANDLE_VALUE );\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)\n  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );\n#endif\n  if( !p ) return 0;\n  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);\n  if( n==(SIZE_T)-1 ){\n    sqlite3_log(SQLITE_NOMEM, \"failed to HeapSize block %p (%lu), heap=%p\",\n                p, osGetLastError(), (void*)hHeap);\n    return 0;\n  }\n  return (int)n;\n}\n\n/*\n** Round up a request size to the next valid allocation size.\n*/\nstatic int winMemRoundup(int n){\n  return n;\n}\n\n/*\n** Initialize this module.\n*/\nstatic int winMemInit(void *pAppData){\n  winMemData *pWinMemData = (winMemData *)pAppData;\n\n  if( !pWinMemData ) return SQLITE_ERROR;\n  assert( pWinMemData->magic1==WINMEM_MAGIC1 );\n  assert( pWinMemData->magic2==WINMEM_MAGIC2 );\n\n#if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE\n  if( !pWinMemData->hHeap ){\n    DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;\n    DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;\n    if( dwMaximumSize==0 ){\n      dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;\n    }else if( dwInitialSize>dwMaximumSize ){\n      dwInitialSize = dwMaximumSize;\n    }\n    pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,\n                                      dwInitialSize, dwMaximumSize);\n    if( !pWinMemData->hHeap ){\n      sqlite3_log(SQLITE_NOMEM,\n          \"failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu\",\n          osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,\n          dwMaximumSize);\n      return SQLITE_NOMEM_BKPT;\n    }\n    pWinMemData->bOwned = TRUE;\n    assert( pWinMemData->bOwned );\n  }\n#else\n  pWinMemData->hHeap = osGetProcessHeap();\n  if( !pWinMemData->hHeap ){\n    sqlite3_log(SQLITE_NOMEM,\n        \"failed to GetProcessHeap (%lu)\", osGetLastError());\n    return SQLITE_NOMEM_BKPT;\n  }\n  pWinMemData->bOwned = FALSE;\n  assert( !pWinMemData->bOwned );\n#endif\n  assert( pWinMemData->hHeap!=0 );\n  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)\n  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );\n#endif\n  return SQLITE_OK;\n}\n\n/*\n** Deinitialize this module.\n*/\nstatic void winMemShutdown(void *pAppData){\n  winMemData *pWinMemData = (winMemData *)pAppData;\n\n  if( !pWinMemData ) return;\n  assert( pWinMemData->magic1==WINMEM_MAGIC1 );\n  assert( pWinMemData->magic2==WINMEM_MAGIC2 );\n\n  if( pWinMemData->hHeap ){\n    assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)\n    assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );\n#endif\n    if( pWinMemData->bOwned ){\n      if( !osHeapDestroy(pWinMemData->hHeap) ){\n        sqlite3_log(SQLITE_NOMEM, \"failed to HeapDestroy (%lu), heap=%p\",\n                    osGetLastError(), (void*)pWinMemData->hHeap);\n      }\n      pWinMemData->bOwned = FALSE;\n    }\n    pWinMemData->hHeap = NULL;\n  }\n}\n\n/*\n** Populate the low-level memory allocation function pointers in\n** sqlite3GlobalConfig.m with pointers to the routines in this file. The\n** arguments specify the block of memory to manage.\n**\n** This routine is only called by sqlite3_config(), and therefore\n** is not required to be threadsafe (it is not).\n*/\nSQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){\n  static const sqlite3_mem_methods winMemMethods = {\n    winMemMalloc,\n    winMemFree,\n    winMemRealloc,\n    winMemSize,\n    winMemRoundup,\n    winMemInit,\n    winMemShutdown,\n    &win_mem_data\n  };\n  return &winMemMethods;\n}\n\nSQLITE_PRIVATE void sqlite3MemSetDefault(void){\n  sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());\n}\n#endif /* SQLITE_WIN32_MALLOC */\n\n/*\n** Convert a UTF-8 string to Microsoft Unicode.\n**\n** Space to hold the returned string is obtained from sqlite3_malloc().\n*/\nstatic LPWSTR winUtf8ToUnicode(const char *zText){\n  int nChar;\n  LPWSTR zWideText;\n\n  nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);\n  if( nChar==0 ){\n    return 0;\n  }\n  zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );\n  if( zWideText==0 ){\n    return 0;\n  }\n  nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,\n                                nChar);\n  if( nChar==0 ){\n    sqlite3_free(zWideText);\n    zWideText = 0;\n  }\n  return zWideText;\n}\n\n/*\n** Convert a Microsoft Unicode string to UTF-8.\n**\n** Space to hold the returned string is obtained from sqlite3_malloc().\n*/\nstatic char *winUnicodeToUtf8(LPCWSTR zWideText){\n  int nByte;\n  char *zText;\n\n  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);\n  if( nByte == 0 ){\n    return 0;\n  }\n  zText = sqlite3MallocZero( nByte );\n  if( zText==0 ){\n    return 0;\n  }\n  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,\n                                0, 0);\n  if( nByte == 0 ){\n    sqlite3_free(zText);\n    zText = 0;\n  }\n  return zText;\n}\n\n/*\n** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM\n** code page.\n**\n** Space to hold the returned string is obtained from sqlite3_malloc().\n*/\nstatic LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){\n  int nByte;\n  LPWSTR zMbcsText;\n  int codepage = useAnsi ? CP_ACP : CP_OEMCP;\n\n  nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,\n                                0)*sizeof(WCHAR);\n  if( nByte==0 ){\n    return 0;\n  }\n  zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );\n  if( zMbcsText==0 ){\n    return 0;\n  }\n  nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,\n                                nByte);\n  if( nByte==0 ){\n    sqlite3_free(zMbcsText);\n    zMbcsText = 0;\n  }\n  return zMbcsText;\n}\n\n/*\n** Convert a Microsoft Unicode string to a multi-byte character string,\n** using the ANSI or OEM code page.\n**\n** Space to hold the returned string is obtained from sqlite3_malloc().\n*/\nstatic char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){\n  int nByte;\n  char *zText;\n  int codepage = useAnsi ? CP_ACP : CP_OEMCP;\n\n  nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);\n  if( nByte == 0 ){\n    return 0;\n  }\n  zText = sqlite3MallocZero( nByte );\n  if( zText==0 ){\n    return 0;\n  }\n  nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,\n                                nByte, 0, 0);\n  if( nByte == 0 ){\n    sqlite3_free(zText);\n    zText = 0;\n  }\n  return zText;\n}\n\n/*\n** Convert a multi-byte character string to UTF-8.\n**\n** Space to hold the returned string is obtained from sqlite3_malloc().\n*/\nstatic char *winMbcsToUtf8(const char *zText, int useAnsi){\n  char *zTextUtf8;\n  LPWSTR zTmpWide;\n\n  zTmpWide = winMbcsToUnicode(zText, useAnsi);\n  if( zTmpWide==0 ){\n    return 0;\n  }\n  zTextUtf8 = winUnicodeToUtf8(zTmpWide);\n  sqlite3_free(zTmpWide);\n  return zTextUtf8;\n}\n\n/*\n** Convert a UTF-8 string to a multi-byte character string.\n**\n** Space to hold the returned string is obtained from sqlite3_malloc().\n*/\nstatic char *winUtf8ToMbcs(const char *zText, int useAnsi){\n  char *zTextMbcs;\n  LPWSTR zTmpWide;\n\n  zTmpWide = winUtf8ToUnicode(zText);\n  if( zTmpWide==0 ){\n    return 0;\n  }\n  zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);\n  sqlite3_free(zTmpWide);\n  return zTextMbcs;\n}\n\n/*\n** This is a public wrapper for the winUtf8ToUnicode() function.\n*/\nSQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !zText ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  return winUtf8ToUnicode(zText);\n}\n\n/*\n** This is a public wrapper for the winUnicodeToUtf8() function.\n*/\nSQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !zWideText ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  return winUnicodeToUtf8(zWideText);\n}\n\n/*\n** This is a public wrapper for the winMbcsToUtf8() function.\n*/\nSQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !zText ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  return winMbcsToUtf8(zText, osAreFileApisANSI());\n}\n\n/*\n** This is a public wrapper for the winMbcsToUtf8() function.\n*/\nSQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !zText ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  return winMbcsToUtf8(zText, useAnsi);\n}\n\n/*\n** This is a public wrapper for the winUtf8ToMbcs() function.\n*/\nSQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !zText ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  return winUtf8ToMbcs(zText, osAreFileApisANSI());\n}\n\n/*\n** This is a public wrapper for the winUtf8ToMbcs() function.\n*/\nSQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !zText ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  return winUtf8ToMbcs(zText, useAnsi);\n}\n\n/*\n** This function is the same as sqlite3_win32_set_directory (below); however,\n** it accepts a UTF-8 string.\n*/\nSQLITE_API int sqlite3_win32_set_directory8(\n  unsigned long type, /* Identifier for directory being set or reset */\n  const char *zValue  /* New value for directory being set or reset */\n){\n  char **ppDirectory = 0;\n#ifndef SQLITE_OMIT_AUTOINIT\n  int rc = sqlite3_initialize();\n  if( rc ) return rc;\n#endif\n  if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){\n    ppDirectory = &sqlite3_data_directory;\n  }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){\n    ppDirectory = &sqlite3_temp_directory;\n  }\n  assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE\n          || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE\n  );\n  assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );\n  if( ppDirectory ){\n    char *zCopy = 0;\n    if( zValue && zValue[0] ){\n      zCopy = sqlite3_mprintf(\"%s\", zValue);\n      if ( zCopy==0 ){\n        return SQLITE_NOMEM_BKPT;\n      }\n    }\n    sqlite3_free(*ppDirectory);\n    *ppDirectory = zCopy;\n    return SQLITE_OK;\n  }\n  return SQLITE_ERROR;\n}\n\n/*\n** This function is the same as sqlite3_win32_set_directory (below); however,\n** it accepts a UTF-16 string.\n*/\nSQLITE_API int sqlite3_win32_set_directory16(\n  unsigned long type, /* Identifier for directory being set or reset */\n  const void *zValue  /* New value for directory being set or reset */\n){\n  int rc;\n  char *zUtf8 = 0;\n  if( zValue ){\n    zUtf8 = sqlite3_win32_unicode_to_utf8(zValue);\n    if( zUtf8==0 ) return SQLITE_NOMEM_BKPT;\n  }\n  rc = sqlite3_win32_set_directory8(type, zUtf8);\n  if( zUtf8 ) sqlite3_free(zUtf8);\n  return rc;\n}\n\n/*\n** This function sets the data directory or the temporary directory based on\n** the provided arguments.  The type argument must be 1 in order to set the\n** data directory or 2 in order to set the temporary directory.  The zValue\n** argument is the name of the directory to use.  The return value will be\n** SQLITE_OK if successful.\n*/\nSQLITE_API int sqlite3_win32_set_directory(\n  unsigned long type, /* Identifier for directory being set or reset */\n  void *zValue        /* New value for directory being set or reset */\n){\n  return sqlite3_win32_set_directory16(type, zValue);\n}\n\n/*\n** The return value of winGetLastErrorMsg\n** is zero if the error message fits in the buffer, or non-zero\n** otherwise (if the message was truncated).\n*/\nstatic int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){\n  /* FormatMessage returns 0 on failure.  Otherwise it\n  ** returns the number of TCHARs written to the output\n  ** buffer, excluding the terminating null char.\n  */\n  DWORD dwLen = 0;\n  char *zOut = 0;\n\n  if( osIsNT() ){\n#if SQLITE_OS_WINRT\n    WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];\n    dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |\n                             FORMAT_MESSAGE_IGNORE_INSERTS,\n                             NULL,\n                             lastErrno,\n                             0,\n                             zTempWide,\n                             SQLITE_WIN32_MAX_ERRMSG_CHARS,\n                             0);\n#else\n    LPWSTR zTempWide = NULL;\n    dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n                             FORMAT_MESSAGE_FROM_SYSTEM |\n                             FORMAT_MESSAGE_IGNORE_INSERTS,\n                             NULL,\n                             lastErrno,\n                             0,\n                             (LPWSTR) &zTempWide,\n                             0,\n                             0);\n#endif\n    if( dwLen > 0 ){\n      /* allocate a buffer and convert to UTF8 */\n      sqlite3BeginBenignMalloc();\n      zOut = winUnicodeToUtf8(zTempWide);\n      sqlite3EndBenignMalloc();\n#if !SQLITE_OS_WINRT\n      /* free the system buffer allocated by FormatMessage */\n      osLocalFree(zTempWide);\n#endif\n    }\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    char *zTemp = NULL;\n    dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n                             FORMAT_MESSAGE_FROM_SYSTEM |\n                             FORMAT_MESSAGE_IGNORE_INSERTS,\n                             NULL,\n                             lastErrno,\n                             0,\n                             (LPSTR) &zTemp,\n                             0,\n                             0);\n    if( dwLen > 0 ){\n      /* allocate a buffer and convert to UTF8 */\n      sqlite3BeginBenignMalloc();\n      zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());\n      sqlite3EndBenignMalloc();\n      /* free the system buffer allocated by FormatMessage */\n      osLocalFree(zTemp);\n    }\n  }\n#endif\n  if( 0 == dwLen ){\n    sqlite3_snprintf(nBuf, zBuf, \"OsError 0x%lx (%lu)\", lastErrno, lastErrno);\n  }else{\n    /* copy a maximum of nBuf chars to output buffer */\n    sqlite3_snprintf(nBuf, zBuf, \"%s\", zOut);\n    /* free the UTF8 buffer */\n    sqlite3_free(zOut);\n  }\n  return 0;\n}\n\n/*\n**\n** This function - winLogErrorAtLine() - is only ever called via the macro\n** winLogError().\n**\n** This routine is invoked after an error occurs in an OS function.\n** It logs a message using sqlite3_log() containing the current value of\n** error code and, if possible, the human-readable equivalent from\n** FormatMessage.\n**\n** The first argument passed to the macro should be the error code that\n** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).\n** The two subsequent arguments should be the name of the OS function that\n** failed and the associated file-system path, if any.\n*/\n#define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)\nstatic int winLogErrorAtLine(\n  int errcode,                    /* SQLite error code */\n  DWORD lastErrno,                /* Win32 last error */\n  const char *zFunc,              /* Name of OS function that failed */\n  const char *zPath,              /* File path associated with error */\n  int iLine                       /* Source line number where error occurred */\n){\n  char zMsg[500];                 /* Human readable error text */\n  int i;                          /* Loop counter */\n\n  zMsg[0] = 0;\n  winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);\n  assert( errcode!=SQLITE_OK );\n  if( zPath==0 ) zPath = \"\";\n  for(i=0; zMsg[i] && zMsg[i]!='\\r' && zMsg[i]!='\\n'; i++){}\n  zMsg[i] = 0;\n  sqlite3_log(errcode,\n      \"os_win.c:%d: (%lu) %s(%s) - %s\",\n      iLine, lastErrno, zFunc, zPath, zMsg\n  );\n\n  return errcode;\n}\n\n/*\n** The number of times that a ReadFile(), WriteFile(), and DeleteFile()\n** will be retried following a locking error - probably caused by\n** antivirus software.  Also the initial delay before the first retry.\n** The delay increases linearly with each retry.\n*/\n#ifndef SQLITE_WIN32_IOERR_RETRY\n# define SQLITE_WIN32_IOERR_RETRY 10\n#endif\n#ifndef SQLITE_WIN32_IOERR_RETRY_DELAY\n# define SQLITE_WIN32_IOERR_RETRY_DELAY 25\n#endif\nstatic int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;\nstatic int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;\n\n/*\n** The \"winIoerrCanRetry1\" macro is used to determine if a particular I/O\n** error code obtained via GetLastError() is eligible to be retried.  It\n** must accept the error code DWORD as its only argument and should return\n** non-zero if the error code is transient in nature and the operation\n** responsible for generating the original error might succeed upon being\n** retried.  The argument to this macro should be a variable.\n**\n** Additionally, a macro named \"winIoerrCanRetry2\" may be defined.  If it\n** is defined, it will be consulted only when the macro \"winIoerrCanRetry1\"\n** returns zero.  The \"winIoerrCanRetry2\" macro is completely optional and\n** may be used to include additional error codes in the set that should\n** result in the failing I/O operation being retried by the caller.  If\n** defined, the \"winIoerrCanRetry2\" macro must exhibit external semantics\n** identical to those of the \"winIoerrCanRetry1\" macro.\n*/\n#if !defined(winIoerrCanRetry1)\n#define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \\\n                              ((a)==ERROR_SHARING_VIOLATION)    || \\\n                              ((a)==ERROR_LOCK_VIOLATION)       || \\\n                              ((a)==ERROR_DEV_NOT_EXIST)        || \\\n                              ((a)==ERROR_NETNAME_DELETED)      || \\\n                              ((a)==ERROR_SEM_TIMEOUT)          || \\\n                              ((a)==ERROR_NETWORK_UNREACHABLE))\n#endif\n\n/*\n** If a ReadFile() or WriteFile() error occurs, invoke this routine\n** to see if it should be retried.  Return TRUE to retry.  Return FALSE\n** to give up with an error.\n*/\nstatic int winRetryIoerr(int *pnRetry, DWORD *pError){\n  DWORD e = osGetLastError();\n  if( *pnRetry>=winIoerrRetry ){\n    if( pError ){\n      *pError = e;\n    }\n    return 0;\n  }\n  if( winIoerrCanRetry1(e) ){\n    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));\n    ++*pnRetry;\n    return 1;\n  }\n#if defined(winIoerrCanRetry2)\n  else if( winIoerrCanRetry2(e) ){\n    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));\n    ++*pnRetry;\n    return 1;\n  }\n#endif\n  if( pError ){\n    *pError = e;\n  }\n  return 0;\n}\n\n/*\n** Log a I/O error retry episode.\n*/\nstatic void winLogIoerr(int nRetry, int lineno){\n  if( nRetry ){\n    sqlite3_log(SQLITE_NOTICE,\n      \"delayed %dms for lock/sharing conflict at line %d\",\n      winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno\n    );\n  }\n}\n\n/*\n** This #if does not rely on the SQLITE_OS_WINCE define because the\n** corresponding section in \"date.c\" cannot use it.\n*/\n#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \\\n    (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)\n/*\n** The MSVC CRT on Windows CE may not have a localtime() function.\n** So define a substitute.\n*/\n/* #  include <time.h> */\nstruct tm *__cdecl localtime(const time_t *t)\n{\n  static struct tm y;\n  FILETIME uTm, lTm;\n  SYSTEMTIME pTm;\n  sqlite3_int64 t64;\n  t64 = *t;\n  t64 = (t64 + 11644473600)*10000000;\n  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);\n  uTm.dwHighDateTime= (DWORD)(t64 >> 32);\n  osFileTimeToLocalFileTime(&uTm,&lTm);\n  osFileTimeToSystemTime(&lTm,&pTm);\n  y.tm_year = pTm.wYear - 1900;\n  y.tm_mon = pTm.wMonth - 1;\n  y.tm_wday = pTm.wDayOfWeek;\n  y.tm_mday = pTm.wDay;\n  y.tm_hour = pTm.wHour;\n  y.tm_min = pTm.wMinute;\n  y.tm_sec = pTm.wSecond;\n  return &y;\n}\n#endif\n\n#if SQLITE_OS_WINCE\n/*************************************************************************\n** This section contains code for WinCE only.\n*/\n#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]\n\n/*\n** Acquire a lock on the handle h\n*/\nstatic void winceMutexAcquire(HANDLE h){\n   DWORD dwErr;\n   do {\n     dwErr = osWaitForSingleObject(h, INFINITE);\n   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);\n}\n/*\n** Release a lock acquired by winceMutexAcquire()\n*/\n#define winceMutexRelease(h) ReleaseMutex(h)\n\n/*\n** Create the mutex and shared memory used for locking in the file\n** descriptor pFile\n*/\nstatic int winceCreateLock(const char *zFilename, winFile *pFile){\n  LPWSTR zTok;\n  LPWSTR zName;\n  DWORD lastErrno;\n  BOOL bLogged = FALSE;\n  BOOL bInit = TRUE;\n\n  zName = winUtf8ToUnicode(zFilename);\n  if( zName==0 ){\n    /* out of memory */\n    return SQLITE_IOERR_NOMEM_BKPT;\n  }\n\n  /* Initialize the local lockdata */\n  memset(&pFile->local, 0, sizeof(pFile->local));\n\n  /* Replace the backslashes from the filename and lowercase it\n  ** to derive a mutex name. */\n  zTok = osCharLowerW(zName);\n  for (;*zTok;zTok++){\n    if (*zTok == '\\\\') *zTok = '_';\n  }\n\n  /* Create/open the named mutex */\n  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);\n  if (!pFile->hMutex){\n    pFile->lastErrno = osGetLastError();\n    sqlite3_free(zName);\n    return winLogError(SQLITE_IOERR, pFile->lastErrno,\n                       \"winceCreateLock1\", zFilename);\n  }\n\n  /* Acquire the mutex before continuing */\n  winceMutexAcquire(pFile->hMutex);\n\n  /* Since the names of named mutexes, semaphores, file mappings etc are\n  ** case-sensitive, take advantage of that by uppercasing the mutex name\n  ** and using that as the shared filemapping name.\n  */\n  osCharUpperW(zName);\n  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,\n                                        PAGE_READWRITE, 0, sizeof(winceLock),\n                                        zName);\n\n  /* Set a flag that indicates we're the first to create the memory so it\n  ** must be zero-initialized */\n  lastErrno = osGetLastError();\n  if (lastErrno == ERROR_ALREADY_EXISTS){\n    bInit = FALSE;\n  }\n\n  sqlite3_free(zName);\n\n  /* If we succeeded in making the shared memory handle, map it. */\n  if( pFile->hShared ){\n    pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,\n             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));\n    /* If mapping failed, close the shared memory handle and erase it */\n    if( !pFile->shared ){\n      pFile->lastErrno = osGetLastError();\n      winLogError(SQLITE_IOERR, pFile->lastErrno,\n                  \"winceCreateLock2\", zFilename);\n      bLogged = TRUE;\n      osCloseHandle(pFile->hShared);\n      pFile->hShared = NULL;\n    }\n  }\n\n  /* If shared memory could not be created, then close the mutex and fail */\n  if( pFile->hShared==NULL ){\n    if( !bLogged ){\n      pFile->lastErrno = lastErrno;\n      winLogError(SQLITE_IOERR, pFile->lastErrno,\n                  \"winceCreateLock3\", zFilename);\n      bLogged = TRUE;\n    }\n    winceMutexRelease(pFile->hMutex);\n    osCloseHandle(pFile->hMutex);\n    pFile->hMutex = NULL;\n    return SQLITE_IOERR;\n  }\n\n  /* Initialize the shared memory if we're supposed to */\n  if( bInit ){\n    memset(pFile->shared, 0, sizeof(winceLock));\n  }\n\n  winceMutexRelease(pFile->hMutex);\n  return SQLITE_OK;\n}\n\n/*\n** Destroy the part of winFile that deals with wince locks\n*/\nstatic void winceDestroyLock(winFile *pFile){\n  if (pFile->hMutex){\n    /* Acquire the mutex */\n    winceMutexAcquire(pFile->hMutex);\n\n    /* The following blocks should probably assert in debug mode, but they\n       are to cleanup in case any locks remained open */\n    if (pFile->local.nReaders){\n      pFile->shared->nReaders --;\n    }\n    if (pFile->local.bReserved){\n      pFile->shared->bReserved = FALSE;\n    }\n    if (pFile->local.bPending){\n      pFile->shared->bPending = FALSE;\n    }\n    if (pFile->local.bExclusive){\n      pFile->shared->bExclusive = FALSE;\n    }\n\n    /* De-reference and close our copy of the shared memory handle */\n    osUnmapViewOfFile(pFile->shared);\n    osCloseHandle(pFile->hShared);\n\n    /* Done with the mutex */\n    winceMutexRelease(pFile->hMutex);\n    osCloseHandle(pFile->hMutex);\n    pFile->hMutex = NULL;\n  }\n}\n\n/*\n** An implementation of the LockFile() API of Windows for CE\n*/\nstatic BOOL winceLockFile(\n  LPHANDLE phFile,\n  DWORD dwFileOffsetLow,\n  DWORD dwFileOffsetHigh,\n  DWORD nNumberOfBytesToLockLow,\n  DWORD nNumberOfBytesToLockHigh\n){\n  winFile *pFile = HANDLE_TO_WINFILE(phFile);\n  BOOL bReturn = FALSE;\n\n  UNUSED_PARAMETER(dwFileOffsetHigh);\n  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);\n\n  if (!pFile->hMutex) return TRUE;\n  winceMutexAcquire(pFile->hMutex);\n\n  /* Wanting an exclusive lock? */\n  if (dwFileOffsetLow == (DWORD)SHARED_FIRST\n       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){\n    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){\n       pFile->shared->bExclusive = TRUE;\n       pFile->local.bExclusive = TRUE;\n       bReturn = TRUE;\n    }\n  }\n\n  /* Want a read-only lock? */\n  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&\n           nNumberOfBytesToLockLow == 1){\n    if (pFile->shared->bExclusive == 0){\n      pFile->local.nReaders ++;\n      if (pFile->local.nReaders == 1){\n        pFile->shared->nReaders ++;\n      }\n      bReturn = TRUE;\n    }\n  }\n\n  /* Want a pending lock? */\n  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE\n           && nNumberOfBytesToLockLow == 1){\n    /* If no pending lock has been acquired, then acquire it */\n    if (pFile->shared->bPending == 0) {\n      pFile->shared->bPending = TRUE;\n      pFile->local.bPending = TRUE;\n      bReturn = TRUE;\n    }\n  }\n\n  /* Want a reserved lock? */\n  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE\n           && nNumberOfBytesToLockLow == 1){\n    if (pFile->shared->bReserved == 0) {\n      pFile->shared->bReserved = TRUE;\n      pFile->local.bReserved = TRUE;\n      bReturn = TRUE;\n    }\n  }\n\n  winceMutexRelease(pFile->hMutex);\n  return bReturn;\n}\n\n/*\n** An implementation of the UnlockFile API of Windows for CE\n*/\nstatic BOOL winceUnlockFile(\n  LPHANDLE phFile,\n  DWORD dwFileOffsetLow,\n  DWORD dwFileOffsetHigh,\n  DWORD nNumberOfBytesToUnlockLow,\n  DWORD nNumberOfBytesToUnlockHigh\n){\n  winFile *pFile = HANDLE_TO_WINFILE(phFile);\n  BOOL bReturn = FALSE;\n\n  UNUSED_PARAMETER(dwFileOffsetHigh);\n  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);\n\n  if (!pFile->hMutex) return TRUE;\n  winceMutexAcquire(pFile->hMutex);\n\n  /* Releasing a reader lock or an exclusive lock */\n  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){\n    /* Did we have an exclusive lock? */\n    if (pFile->local.bExclusive){\n      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);\n      pFile->local.bExclusive = FALSE;\n      pFile->shared->bExclusive = FALSE;\n      bReturn = TRUE;\n    }\n\n    /* Did we just have a reader lock? */\n    else if (pFile->local.nReaders){\n      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE\n             || nNumberOfBytesToUnlockLow == 1);\n      pFile->local.nReaders --;\n      if (pFile->local.nReaders == 0)\n      {\n        pFile->shared->nReaders --;\n      }\n      bReturn = TRUE;\n    }\n  }\n\n  /* Releasing a pending lock */\n  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE\n           && nNumberOfBytesToUnlockLow == 1){\n    if (pFile->local.bPending){\n      pFile->local.bPending = FALSE;\n      pFile->shared->bPending = FALSE;\n      bReturn = TRUE;\n    }\n  }\n  /* Releasing a reserved lock */\n  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE\n           && nNumberOfBytesToUnlockLow == 1){\n    if (pFile->local.bReserved) {\n      pFile->local.bReserved = FALSE;\n      pFile->shared->bReserved = FALSE;\n      bReturn = TRUE;\n    }\n  }\n\n  winceMutexRelease(pFile->hMutex);\n  return bReturn;\n}\n/*\n** End of the special code for wince\n*****************************************************************************/\n#endif /* SQLITE_OS_WINCE */\n\n/*\n** Lock a file region.\n*/\nstatic BOOL winLockFile(\n  LPHANDLE phFile,\n  DWORD flags,\n  DWORD offsetLow,\n  DWORD offsetHigh,\n  DWORD numBytesLow,\n  DWORD numBytesHigh\n){\n#if SQLITE_OS_WINCE\n  /*\n  ** NOTE: Windows CE is handled differently here due its lack of the Win32\n  **       API LockFile.\n  */\n  return winceLockFile(phFile, offsetLow, offsetHigh,\n                       numBytesLow, numBytesHigh);\n#else\n  if( osIsNT() ){\n    OVERLAPPED ovlp;\n    memset(&ovlp, 0, sizeof(OVERLAPPED));\n    ovlp.Offset = offsetLow;\n    ovlp.OffsetHigh = offsetHigh;\n    return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);\n  }else{\n    return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,\n                      numBytesHigh);\n  }\n#endif\n}\n\n/*\n** Unlock a file region.\n */\nstatic BOOL winUnlockFile(\n  LPHANDLE phFile,\n  DWORD offsetLow,\n  DWORD offsetHigh,\n  DWORD numBytesLow,\n  DWORD numBytesHigh\n){\n#if SQLITE_OS_WINCE\n  /*\n  ** NOTE: Windows CE is handled differently here due its lack of the Win32\n  **       API UnlockFile.\n  */\n  return winceUnlockFile(phFile, offsetLow, offsetHigh,\n                         numBytesLow, numBytesHigh);\n#else\n  if( osIsNT() ){\n    OVERLAPPED ovlp;\n    memset(&ovlp, 0, sizeof(OVERLAPPED));\n    ovlp.Offset = offsetLow;\n    ovlp.OffsetHigh = offsetHigh;\n    return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);\n  }else{\n    return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,\n                        numBytesHigh);\n  }\n#endif\n}\n\n/*****************************************************************************\n** The next group of routines implement the I/O methods specified\n** by the sqlite3_io_methods object.\n******************************************************************************/\n\n/*\n** Some Microsoft compilers lack this definition.\n*/\n#ifndef INVALID_SET_FILE_POINTER\n# define INVALID_SET_FILE_POINTER ((DWORD)-1)\n#endif\n\n/*\n** Move the current position of the file handle passed as the first\n** argument to offset iOffset within the file. If successful, return 0.\n** Otherwise, set pFile->lastErrno and return non-zero.\n*/\nstatic int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){\n#if !SQLITE_OS_WINRT\n  LONG upperBits;                 /* Most sig. 32 bits of new offset */\n  LONG lowerBits;                 /* Least sig. 32 bits of new offset */\n  DWORD dwRet;                    /* Value returned by SetFilePointer() */\n  DWORD lastErrno;                /* Value returned by GetLastError() */\n\n  OSTRACE((\"SEEK file=%p, offset=%lld\\n\", pFile->h, iOffset));\n\n  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);\n  lowerBits = (LONG)(iOffset & 0xffffffff);\n\n  /* API oddity: If successful, SetFilePointer() returns a dword\n  ** containing the lower 32-bits of the new file-offset. Or, if it fails,\n  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,\n  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine\n  ** whether an error has actually occurred, it is also necessary to call\n  ** GetLastError().\n  */\n  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);\n\n  if( (dwRet==INVALID_SET_FILE_POINTER\n      && ((lastErrno = osGetLastError())!=NO_ERROR)) ){\n    pFile->lastErrno = lastErrno;\n    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,\n                \"winSeekFile\", pFile->zPath);\n    OSTRACE((\"SEEK file=%p, rc=SQLITE_IOERR_SEEK\\n\", pFile->h));\n    return 1;\n  }\n\n  OSTRACE((\"SEEK file=%p, rc=SQLITE_OK\\n\", pFile->h));\n  return 0;\n#else\n  /*\n  ** Same as above, except that this implementation works for WinRT.\n  */\n\n  LARGE_INTEGER x;                /* The new offset */\n  BOOL bRet;                      /* Value returned by SetFilePointerEx() */\n\n  x.QuadPart = iOffset;\n  bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);\n\n  if(!bRet){\n    pFile->lastErrno = osGetLastError();\n    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,\n                \"winSeekFile\", pFile->zPath);\n    OSTRACE((\"SEEK file=%p, rc=SQLITE_IOERR_SEEK\\n\", pFile->h));\n    return 1;\n  }\n\n  OSTRACE((\"SEEK file=%p, rc=SQLITE_OK\\n\", pFile->h));\n  return 0;\n#endif\n}\n\n#if SQLITE_MAX_MMAP_SIZE>0\n/* Forward references to VFS helper methods used for memory mapped files */\nstatic int winMapfile(winFile*, sqlite3_int64);\nstatic int winUnmapfile(winFile*);\n#endif\n\n/*\n** Close a file.\n**\n** It is reported that an attempt to close a handle might sometimes\n** fail.  This is a very unreasonable result, but Windows is notorious\n** for being unreasonable so I do not doubt that it might happen.  If\n** the close fails, we pause for 100 milliseconds and try again.  As\n** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before\n** giving up and returning an error.\n*/\n#define MX_CLOSE_ATTEMPT 3\nstatic int winClose(sqlite3_file *id){\n  int rc, cnt = 0;\n  winFile *pFile = (winFile*)id;\n\n  assert( id!=0 );\n#ifndef SQLITE_OMIT_WAL\n  assert( pFile->pShm==0 );\n#endif\n  assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );\n  OSTRACE((\"CLOSE pid=%lu, pFile=%p, file=%p\\n\",\n           osGetCurrentProcessId(), pFile, pFile->h));\n\n#if SQLITE_MAX_MMAP_SIZE>0\n  winUnmapfile(pFile);\n#endif\n\n  do{\n    rc = osCloseHandle(pFile->h);\n    /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */\n  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );\n#if SQLITE_OS_WINCE\n#define WINCE_DELETION_ATTEMPTS 3\n  {\n    winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;\n    if( pAppData==NULL || !pAppData->bNoLock ){\n      winceDestroyLock(pFile);\n    }\n  }\n  if( pFile->zDeleteOnClose ){\n    int cnt = 0;\n    while(\n           osDeleteFileW(pFile->zDeleteOnClose)==0\n        && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff\n        && cnt++ < WINCE_DELETION_ATTEMPTS\n    ){\n       sqlite3_win32_sleep(100);  /* Wait a little before trying again */\n    }\n    sqlite3_free(pFile->zDeleteOnClose);\n  }\n#endif\n  if( rc ){\n    pFile->h = NULL;\n  }\n  OpenCounter(-1);\n  OSTRACE((\"CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\\n\",\n           osGetCurrentProcessId(), pFile, pFile->h, rc ? \"ok\" : \"failed\"));\n  return rc ? SQLITE_OK\n            : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),\n                          \"winClose\", pFile->zPath);\n}\n\n/*\n** Read data from a file into a buffer.  Return SQLITE_OK if all\n** bytes were read successfully and SQLITE_IOERR if anything goes\n** wrong.\n*/\nstatic int winRead(\n  sqlite3_file *id,          /* File to read from */\n  void *pBuf,                /* Write content into this buffer */\n  int amt,                   /* Number of bytes to read */\n  sqlite3_int64 offset       /* Begin reading at this offset */\n){\n#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)\n  OVERLAPPED overlapped;          /* The offset for ReadFile. */\n#endif\n  winFile *pFile = (winFile*)id;  /* file handle */\n  DWORD nRead;                    /* Number of bytes actually read from file */\n  int nRetry = 0;                 /* Number of retrys */\n\n  assert( id!=0 );\n  assert( amt>0 );\n  assert( offset>=0 );\n  SimulateIOError(return SQLITE_IOERR_READ);\n  OSTRACE((\"READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, \"\n           \"offset=%lld, lock=%d\\n\", osGetCurrentProcessId(), pFile,\n           pFile->h, pBuf, amt, offset, pFile->locktype));\n\n#if SQLITE_MAX_MMAP_SIZE>0\n  /* Deal with as much of this read request as possible by transfering\n  ** data from the memory mapping using memcpy().  */\n  if( offset<pFile->mmapSize ){\n    if( offset+amt <= pFile->mmapSize ){\n      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);\n      OSTRACE((\"READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\\n\",\n               osGetCurrentProcessId(), pFile, pFile->h));\n      return SQLITE_OK;\n    }else{\n      int nCopy = (int)(pFile->mmapSize - offset);\n      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);\n      pBuf = &((u8 *)pBuf)[nCopy];\n      amt -= nCopy;\n      offset += nCopy;\n    }\n  }\n#endif\n\n#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)\n  if( winSeekFile(pFile, offset) ){\n    OSTRACE((\"READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\\n\",\n             osGetCurrentProcessId(), pFile, pFile->h));\n    return SQLITE_FULL;\n  }\n  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){\n#else\n  memset(&overlapped, 0, sizeof(OVERLAPPED));\n  overlapped.Offset = (LONG)(offset & 0xffffffff);\n  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);\n  while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&\n         osGetLastError()!=ERROR_HANDLE_EOF ){\n#endif\n    DWORD lastErrno;\n    if( winRetryIoerr(&nRetry, &lastErrno) ) continue;\n    pFile->lastErrno = lastErrno;\n    OSTRACE((\"READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\\n\",\n             osGetCurrentProcessId(), pFile, pFile->h));\n    return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,\n                       \"winRead\", pFile->zPath);\n  }\n  winLogIoerr(nRetry, __LINE__);\n  if( nRead<(DWORD)amt ){\n    /* Unread parts of the buffer must be zero-filled */\n    memset(&((char*)pBuf)[nRead], 0, amt-nRead);\n    OSTRACE((\"READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\\n\",\n             osGetCurrentProcessId(), pFile, pFile->h));\n    return SQLITE_IOERR_SHORT_READ;\n  }\n\n  OSTRACE((\"READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\\n\",\n           osGetCurrentProcessId(), pFile, pFile->h));\n  return SQLITE_OK;\n}\n\n/*\n** Write data from a buffer into a file.  Return SQLITE_OK on success\n** or some other error code on failure.\n*/\nstatic int winWrite(\n  sqlite3_file *id,               /* File to write into */\n  const void *pBuf,               /* The bytes to be written */\n  int amt,                        /* Number of bytes to write */\n  sqlite3_int64 offset            /* Offset into the file to begin writing at */\n){\n  int rc = 0;                     /* True if error has occurred, else false */\n  winFile *pFile = (winFile*)id;  /* File handle */\n  int nRetry = 0;                 /* Number of retries */\n\n  assert( amt>0 );\n  assert( pFile );\n  SimulateIOError(return SQLITE_IOERR_WRITE);\n  SimulateDiskfullError(return SQLITE_FULL);\n\n  OSTRACE((\"WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, \"\n           \"offset=%lld, lock=%d\\n\", osGetCurrentProcessId(), pFile,\n           pFile->h, pBuf, amt, offset, pFile->locktype));\n\n#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0\n  /* Deal with as much of this write request as possible by transfering\n  ** data from the memory mapping using memcpy().  */\n  if( offset<pFile->mmapSize ){\n    if( offset+amt <= pFile->mmapSize ){\n      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);\n      OSTRACE((\"WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\\n\",\n               osGetCurrentProcessId(), pFile, pFile->h));\n      return SQLITE_OK;\n    }else{\n      int nCopy = (int)(pFile->mmapSize - offset);\n      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);\n      pBuf = &((u8 *)pBuf)[nCopy];\n      amt -= nCopy;\n      offset += nCopy;\n    }\n  }\n#endif\n\n#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)\n  rc = winSeekFile(pFile, offset);\n  if( rc==0 ){\n#else\n  {\n#endif\n#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)\n    OVERLAPPED overlapped;        /* The offset for WriteFile. */\n#endif\n    u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */\n    int nRem = amt;               /* Number of bytes yet to be written */\n    DWORD nWrite;                 /* Bytes written by each WriteFile() call */\n    DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */\n\n#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)\n    memset(&overlapped, 0, sizeof(OVERLAPPED));\n    overlapped.Offset = (LONG)(offset & 0xffffffff);\n    overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);\n#endif\n\n    while( nRem>0 ){\n#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)\n      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){\n#else\n      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){\n#endif\n        if( winRetryIoerr(&nRetry, &lastErrno) ) continue;\n        break;\n      }\n      assert( nWrite==0 || nWrite<=(DWORD)nRem );\n      if( nWrite==0 || nWrite>(DWORD)nRem ){\n        lastErrno = osGetLastError();\n        break;\n      }\n#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)\n      offset += nWrite;\n      overlapped.Offset = (LONG)(offset & 0xffffffff);\n      overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);\n#endif\n      aRem += nWrite;\n      nRem -= nWrite;\n    }\n    if( nRem>0 ){\n      pFile->lastErrno = lastErrno;\n      rc = 1;\n    }\n  }\n\n  if( rc ){\n    if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )\n       || ( pFile->lastErrno==ERROR_DISK_FULL )){\n      OSTRACE((\"WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\\n\",\n               osGetCurrentProcessId(), pFile, pFile->h));\n      return winLogError(SQLITE_FULL, pFile->lastErrno,\n                         \"winWrite1\", pFile->zPath);\n    }\n    OSTRACE((\"WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\\n\",\n             osGetCurrentProcessId(), pFile, pFile->h));\n    return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,\n                       \"winWrite2\", pFile->zPath);\n  }else{\n    winLogIoerr(nRetry, __LINE__);\n  }\n  OSTRACE((\"WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\\n\",\n           osGetCurrentProcessId(), pFile, pFile->h));\n  return SQLITE_OK;\n}\n\n/*\n** Truncate an open file to a specified size\n*/\nstatic int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){\n  winFile *pFile = (winFile*)id;  /* File handle object */\n  int rc = SQLITE_OK;             /* Return code for this function */\n  DWORD lastErrno;\n#if SQLITE_MAX_MMAP_SIZE>0\n  sqlite3_int64 oldMmapSize;\n  if( pFile->nFetchOut>0 ){\n    /* File truncation is a no-op if there are outstanding memory mapped\n    ** pages.  This is because truncating the file means temporarily unmapping\n    ** the file, and that might delete memory out from under existing cursors.\n    **\n    ** This can result in incremental vacuum not truncating the file,\n    ** if there is an active read cursor when the incremental vacuum occurs.\n    ** No real harm comes of this - the database file is not corrupted,\n    ** though some folks might complain that the file is bigger than it\n    ** needs to be.\n    **\n    ** The only feasible work-around is to defer the truncation until after\n    ** all references to memory-mapped content are closed.  That is doable,\n    ** but involves adding a few branches in the common write code path which\n    ** could slow down normal operations slightly.  Hence, we have decided for\n    ** now to simply make trancations a no-op if there are pending reads.  We\n    ** can maybe revisit this decision in the future.\n    */\n    return SQLITE_OK;\n  }\n#endif\n\n  assert( pFile );\n  SimulateIOError(return SQLITE_IOERR_TRUNCATE);\n  OSTRACE((\"TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\\n\",\n           osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));\n\n  /* If the user has configured a chunk-size for this file, truncate the\n  ** file so that it consists of an integer number of chunks (i.e. the\n  ** actual file size after the operation may be larger than the requested\n  ** size).\n  */\n  if( pFile->szChunk>0 ){\n    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;\n  }\n\n#if SQLITE_MAX_MMAP_SIZE>0\n  if( pFile->pMapRegion ){\n    oldMmapSize = pFile->mmapSize;\n  }else{\n    oldMmapSize = 0;\n  }\n  winUnmapfile(pFile);\n#endif\n\n  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */\n  if( winSeekFile(pFile, nByte) ){\n    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,\n                     \"winTruncate1\", pFile->zPath);\n  }else if( 0==osSetEndOfFile(pFile->h) &&\n            ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){\n    pFile->lastErrno = lastErrno;\n    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,\n                     \"winTruncate2\", pFile->zPath);\n  }\n\n#if SQLITE_MAX_MMAP_SIZE>0\n  if( rc==SQLITE_OK && oldMmapSize>0 ){\n    if( oldMmapSize>nByte ){\n      winMapfile(pFile, -1);\n    }else{\n      winMapfile(pFile, oldMmapSize);\n    }\n  }\n#endif\n\n  OSTRACE((\"TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\\n\",\n           osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));\n  return rc;\n}\n\n#ifdef SQLITE_TEST\n/*\n** Count the number of fullsyncs and normal syncs.  This is used to test\n** that syncs and fullsyncs are occuring at the right times.\n*/\nSQLITE_API int sqlite3_sync_count = 0;\nSQLITE_API int sqlite3_fullsync_count = 0;\n#endif\n\n/*\n** Make sure all writes to a particular file are committed to disk.\n*/\nstatic int winSync(sqlite3_file *id, int flags){\n#ifndef SQLITE_NO_SYNC\n  /*\n  ** Used only when SQLITE_NO_SYNC is not defined.\n   */\n  BOOL rc;\n#endif\n#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \\\n    defined(SQLITE_HAVE_OS_TRACE)\n  /*\n  ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or\n  ** OSTRACE() macros.\n   */\n  winFile *pFile = (winFile*)id;\n#else\n  UNUSED_PARAMETER(id);\n#endif\n\n  assert( pFile );\n  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */\n  assert((flags&0x0F)==SQLITE_SYNC_NORMAL\n      || (flags&0x0F)==SQLITE_SYNC_FULL\n  );\n\n  /* Unix cannot, but some systems may return SQLITE_FULL from here. This\n  ** line is to test that doing so does not cause any problems.\n  */\n  SimulateDiskfullError( return SQLITE_FULL );\n\n  OSTRACE((\"SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\\n\",\n           osGetCurrentProcessId(), pFile, pFile->h, flags,\n           pFile->locktype));\n\n#ifndef SQLITE_TEST\n  UNUSED_PARAMETER(flags);\n#else\n  if( (flags&0x0F)==SQLITE_SYNC_FULL ){\n    sqlite3_fullsync_count++;\n  }\n  sqlite3_sync_count++;\n#endif\n\n  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a\n  ** no-op\n  */\n#ifdef SQLITE_NO_SYNC\n  OSTRACE((\"SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\\n\",\n           osGetCurrentProcessId(), pFile, pFile->h));\n  return SQLITE_OK;\n#else\n#if SQLITE_MAX_MMAP_SIZE>0\n  if( pFile->pMapRegion ){\n    if( osFlushViewOfFile(pFile->pMapRegion, 0) ){\n      OSTRACE((\"SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, \"\n               \"rc=SQLITE_OK\\n\", osGetCurrentProcessId(),\n               pFile, pFile->pMapRegion));\n    }else{\n      pFile->lastErrno = osGetLastError();\n      OSTRACE((\"SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, \"\n               \"rc=SQLITE_IOERR_MMAP\\n\", osGetCurrentProcessId(),\n               pFile, pFile->pMapRegion));\n      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,\n                         \"winSync1\", pFile->zPath);\n    }\n  }\n#endif\n  rc = osFlushFileBuffers(pFile->h);\n  SimulateIOError( rc=FALSE );\n  if( rc ){\n    OSTRACE((\"SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\\n\",\n             osGetCurrentProcessId(), pFile, pFile->h));\n    return SQLITE_OK;\n  }else{\n    pFile->lastErrno = osGetLastError();\n    OSTRACE((\"SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\\n\",\n             osGetCurrentProcessId(), pFile, pFile->h));\n    return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,\n                       \"winSync2\", pFile->zPath);\n  }\n#endif\n}\n\n/*\n** Determine the current size of a file in bytes\n*/\nstatic int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){\n  winFile *pFile = (winFile*)id;\n  int rc = SQLITE_OK;\n\n  assert( id!=0 );\n  assert( pSize!=0 );\n  SimulateIOError(return SQLITE_IOERR_FSTAT);\n  OSTRACE((\"SIZE file=%p, pSize=%p\\n\", pFile->h, pSize));\n\n#if SQLITE_OS_WINRT\n  {\n    FILE_STANDARD_INFO info;\n    if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,\n                                     &info, sizeof(info)) ){\n      *pSize = info.EndOfFile.QuadPart;\n    }else{\n      pFile->lastErrno = osGetLastError();\n      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,\n                       \"winFileSize\", pFile->zPath);\n    }\n  }\n#else\n  {\n    DWORD upperBits;\n    DWORD lowerBits;\n    DWORD lastErrno;\n\n    lowerBits = osGetFileSize(pFile->h, &upperBits);\n    *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;\n    if(   (lowerBits == INVALID_FILE_SIZE)\n       && ((lastErrno = osGetLastError())!=NO_ERROR) ){\n      pFile->lastErrno = lastErrno;\n      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,\n                       \"winFileSize\", pFile->zPath);\n    }\n  }\n#endif\n  OSTRACE((\"SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\\n\",\n           pFile->h, pSize, *pSize, sqlite3ErrName(rc)));\n  return rc;\n}\n\n/*\n** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.\n*/\n#ifndef LOCKFILE_FAIL_IMMEDIATELY\n# define LOCKFILE_FAIL_IMMEDIATELY 1\n#endif\n\n#ifndef LOCKFILE_EXCLUSIVE_LOCK\n# define LOCKFILE_EXCLUSIVE_LOCK 2\n#endif\n\n/*\n** Historically, SQLite has used both the LockFile and LockFileEx functions.\n** When the LockFile function was used, it was always expected to fail\n** immediately if the lock could not be obtained.  Also, it always expected to\n** obtain an exclusive lock.  These flags are used with the LockFileEx function\n** and reflect those expectations; therefore, they should not be changed.\n*/\n#ifndef SQLITE_LOCKFILE_FLAGS\n# define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \\\n                                  LOCKFILE_EXCLUSIVE_LOCK)\n#endif\n\n/*\n** Currently, SQLite never calls the LockFileEx function without wanting the\n** call to fail immediately if the lock cannot be obtained.\n*/\n#ifndef SQLITE_LOCKFILEEX_FLAGS\n# define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)\n#endif\n\n/*\n** Acquire a reader lock.\n** Different API routines are called depending on whether or not this\n** is Win9x or WinNT.\n*/\nstatic int winGetReadLock(winFile *pFile){\n  int res;\n  OSTRACE((\"READ-LOCK file=%p, lock=%d\\n\", pFile->h, pFile->locktype));\n  if( osIsNT() ){\n#if SQLITE_OS_WINCE\n    /*\n    ** NOTE: Windows CE is handled differently here due its lack of the Win32\n    **       API LockFileEx.\n    */\n    res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);\n#else\n    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,\n                      SHARED_SIZE, 0);\n#endif\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    int lk;\n    sqlite3_randomness(sizeof(lk), &lk);\n    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));\n    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,\n                      SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);\n  }\n#endif\n  if( res == 0 ){\n    pFile->lastErrno = osGetLastError();\n    /* No need to log a failure to lock */\n  }\n  OSTRACE((\"READ-LOCK file=%p, result=%d\\n\", pFile->h, res));\n  return res;\n}\n\n/*\n** Undo a readlock\n*/\nstatic int winUnlockReadLock(winFile *pFile){\n  int res;\n  DWORD lastErrno;\n  OSTRACE((\"READ-UNLOCK file=%p, lock=%d\\n\", pFile->h, pFile->locktype));\n  if( osIsNT() ){\n    res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);\n  }\n#endif\n  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){\n    pFile->lastErrno = lastErrno;\n    winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,\n                \"winUnlockReadLock\", pFile->zPath);\n  }\n  OSTRACE((\"READ-UNLOCK file=%p, result=%d\\n\", pFile->h, res));\n  return res;\n}\n\n/*\n** Lock the file with the lock specified by parameter locktype - one\n** of the following:\n**\n**     (1) SHARED_LOCK\n**     (2) RESERVED_LOCK\n**     (3) PENDING_LOCK\n**     (4) EXCLUSIVE_LOCK\n**\n** Sometimes when requesting one lock state, additional lock states\n** are inserted in between.  The locking might fail on one of the later\n** transitions leaving the lock state different from what it started but\n** still short of its goal.  The following chart shows the allowed\n** transitions and the inserted intermediate states:\n**\n**    UNLOCKED -> SHARED\n**    SHARED -> RESERVED\n**    SHARED -> (PENDING) -> EXCLUSIVE\n**    RESERVED -> (PENDING) -> EXCLUSIVE\n**    PENDING -> EXCLUSIVE\n**\n** This routine will only increase a lock.  The winUnlock() routine\n** erases all locks at once and returns us immediately to locking level 0.\n** It is not possible to lower the locking level one step at a time.  You\n** must go straight to locking level 0.\n*/\nstatic int winLock(sqlite3_file *id, int locktype){\n  int rc = SQLITE_OK;    /* Return code from subroutines */\n  int res = 1;           /* Result of a Windows lock call */\n  int newLocktype;       /* Set pFile->locktype to this value before exiting */\n  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */\n  winFile *pFile = (winFile*)id;\n  DWORD lastErrno = NO_ERROR;\n\n  assert( id!=0 );\n  OSTRACE((\"LOCK file=%p, oldLock=%d(%d), newLock=%d\\n\",\n           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));\n\n  /* If there is already a lock of this type or more restrictive on the\n  ** OsFile, do nothing. Don't use the end_lock: exit path, as\n  ** sqlite3OsEnterMutex() hasn't been called yet.\n  */\n  if( pFile->locktype>=locktype ){\n    OSTRACE((\"LOCK-HELD file=%p, rc=SQLITE_OK\\n\", pFile->h));\n    return SQLITE_OK;\n  }\n\n  /* Do not allow any kind of write-lock on a read-only database\n  */\n  if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){\n    return SQLITE_IOERR_LOCK;\n  }\n\n  /* Make sure the locking sequence is correct\n  */\n  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );\n  assert( locktype!=PENDING_LOCK );\n  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );\n\n  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or\n  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of\n  ** the PENDING_LOCK byte is temporary.\n  */\n  newLocktype = pFile->locktype;\n  if( pFile->locktype==NO_LOCK\n   || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)\n  ){\n    int cnt = 3;\n    while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,\n                                         PENDING_BYTE, 0, 1, 0))==0 ){\n      /* Try 3 times to get the pending lock.  This is needed to work\n      ** around problems caused by indexing and/or anti-virus software on\n      ** Windows systems.\n      ** If you are using this code as a model for alternative VFSes, do not\n      ** copy this retry logic.  It is a hack intended for Windows only.\n      */\n      lastErrno = osGetLastError();\n      OSTRACE((\"LOCK-PENDING-FAIL file=%p, count=%d, result=%d\\n\",\n               pFile->h, cnt, res));\n      if( lastErrno==ERROR_INVALID_HANDLE ){\n        pFile->lastErrno = lastErrno;\n        rc = SQLITE_IOERR_LOCK;\n        OSTRACE((\"LOCK-FAIL file=%p, count=%d, rc=%s\\n\",\n                 pFile->h, cnt, sqlite3ErrName(rc)));\n        return rc;\n      }\n      if( cnt ) sqlite3_win32_sleep(1);\n    }\n    gotPendingLock = res;\n    if( !res ){\n      lastErrno = osGetLastError();\n    }\n  }\n\n  /* Acquire a shared lock\n  */\n  if( locktype==SHARED_LOCK && res ){\n    assert( pFile->locktype==NO_LOCK );\n    res = winGetReadLock(pFile);\n    if( res ){\n      newLocktype = SHARED_LOCK;\n    }else{\n      lastErrno = osGetLastError();\n    }\n  }\n\n  /* Acquire a RESERVED lock\n  */\n  if( locktype==RESERVED_LOCK && res ){\n    assert( pFile->locktype==SHARED_LOCK );\n    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);\n    if( res ){\n      newLocktype = RESERVED_LOCK;\n    }else{\n      lastErrno = osGetLastError();\n    }\n  }\n\n  /* Acquire a PENDING lock\n  */\n  if( locktype==EXCLUSIVE_LOCK && res ){\n    newLocktype = PENDING_LOCK;\n    gotPendingLock = 0;\n  }\n\n  /* Acquire an EXCLUSIVE lock\n  */\n  if( locktype==EXCLUSIVE_LOCK && res ){\n    assert( pFile->locktype>=SHARED_LOCK );\n    res = winUnlockReadLock(pFile);\n    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,\n                      SHARED_SIZE, 0);\n    if( res ){\n      newLocktype = EXCLUSIVE_LOCK;\n    }else{\n      lastErrno = osGetLastError();\n      winGetReadLock(pFile);\n    }\n  }\n\n  /* If we are holding a PENDING lock that ought to be released, then\n  ** release it now.\n  */\n  if( gotPendingLock && locktype==SHARED_LOCK ){\n    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);\n  }\n\n  /* Update the state of the lock has held in the file descriptor then\n  ** return the appropriate result code.\n  */\n  if( res ){\n    rc = SQLITE_OK;\n  }else{\n    pFile->lastErrno = lastErrno;\n    rc = SQLITE_BUSY;\n    OSTRACE((\"LOCK-FAIL file=%p, wanted=%d, got=%d\\n\",\n             pFile->h, locktype, newLocktype));\n  }\n  pFile->locktype = (u8)newLocktype;\n  OSTRACE((\"LOCK file=%p, lock=%d, rc=%s\\n\",\n           pFile->h, pFile->locktype, sqlite3ErrName(rc)));\n  return rc;\n}\n\n/*\n** This routine checks if there is a RESERVED lock held on the specified\n** file by this or any other process. If such a lock is held, return\n** non-zero, otherwise zero.\n*/\nstatic int winCheckReservedLock(sqlite3_file *id, int *pResOut){\n  int res;\n  winFile *pFile = (winFile*)id;\n\n  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );\n  OSTRACE((\"TEST-WR-LOCK file=%p, pResOut=%p\\n\", pFile->h, pResOut));\n\n  assert( id!=0 );\n  if( pFile->locktype>=RESERVED_LOCK ){\n    res = 1;\n    OSTRACE((\"TEST-WR-LOCK file=%p, result=%d (local)\\n\", pFile->h, res));\n  }else{\n    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);\n    if( res ){\n      winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);\n    }\n    res = !res;\n    OSTRACE((\"TEST-WR-LOCK file=%p, result=%d (remote)\\n\", pFile->h, res));\n  }\n  *pResOut = res;\n  OSTRACE((\"TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\\n\",\n           pFile->h, pResOut, *pResOut));\n  return SQLITE_OK;\n}\n\n/*\n** Lower the locking level on file descriptor id to locktype.  locktype\n** must be either NO_LOCK or SHARED_LOCK.\n**\n** If the locking level of the file descriptor is already at or below\n** the requested locking level, this routine is a no-op.\n**\n** It is not possible for this routine to fail if the second argument\n** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine\n** might return SQLITE_IOERR;\n*/\nstatic int winUnlock(sqlite3_file *id, int locktype){\n  int type;\n  winFile *pFile = (winFile*)id;\n  int rc = SQLITE_OK;\n  assert( pFile!=0 );\n  assert( locktype<=SHARED_LOCK );\n  OSTRACE((\"UNLOCK file=%p, oldLock=%d(%d), newLock=%d\\n\",\n           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));\n  type = pFile->locktype;\n  if( type>=EXCLUSIVE_LOCK ){\n    winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);\n    if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){\n      /* This should never happen.  We should always be able to\n      ** reacquire the read lock */\n      rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),\n                       \"winUnlock\", pFile->zPath);\n    }\n  }\n  if( type>=RESERVED_LOCK ){\n    winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);\n  }\n  if( locktype==NO_LOCK && type>=SHARED_LOCK ){\n    winUnlockReadLock(pFile);\n  }\n  if( type>=PENDING_LOCK ){\n    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);\n  }\n  pFile->locktype = (u8)locktype;\n  OSTRACE((\"UNLOCK file=%p, lock=%d, rc=%s\\n\",\n           pFile->h, pFile->locktype, sqlite3ErrName(rc)));\n  return rc;\n}\n\n/******************************************************************************\n****************************** No-op Locking **********************************\n**\n** Of the various locking implementations available, this is by far the\n** simplest:  locking is ignored.  No attempt is made to lock the database\n** file for reading or writing.\n**\n** This locking mode is appropriate for use on read-only databases\n** (ex: databases that are burned into CD-ROM, for example.)  It can\n** also be used if the application employs some external mechanism to\n** prevent simultaneous access of the same database by two or more\n** database connections.  But there is a serious risk of database\n** corruption if this locking mode is used in situations where multiple\n** database connections are accessing the same database file at the same\n** time and one or more of those connections are writing.\n*/\n\nstatic int winNolockLock(sqlite3_file *id, int locktype){\n  UNUSED_PARAMETER(id);\n  UNUSED_PARAMETER(locktype);\n  return SQLITE_OK;\n}\n\nstatic int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){\n  UNUSED_PARAMETER(id);\n  UNUSED_PARAMETER(pResOut);\n  return SQLITE_OK;\n}\n\nstatic int winNolockUnlock(sqlite3_file *id, int locktype){\n  UNUSED_PARAMETER(id);\n  UNUSED_PARAMETER(locktype);\n  return SQLITE_OK;\n}\n\n/******************* End of the no-op lock implementation *********************\n******************************************************************************/\n\n/*\n** If *pArg is initially negative then this is a query.  Set *pArg to\n** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.\n**\n** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.\n*/\nstatic void winModeBit(winFile *pFile, unsigned char mask, int *pArg){\n  if( *pArg<0 ){\n    *pArg = (pFile->ctrlFlags & mask)!=0;\n  }else if( (*pArg)==0 ){\n    pFile->ctrlFlags &= ~mask;\n  }else{\n    pFile->ctrlFlags |= mask;\n  }\n}\n\n/* Forward references to VFS helper methods used for temporary files */\nstatic int winGetTempname(sqlite3_vfs *, char **);\nstatic int winIsDir(const void *);\nstatic BOOL winIsLongPathPrefix(const char *);\nstatic BOOL winIsDriveLetterAndColon(const char *);\n\n/*\n** Control and query of the open file handle.\n*/\nstatic int winFileControl(sqlite3_file *id, int op, void *pArg){\n  winFile *pFile = (winFile*)id;\n  OSTRACE((\"FCNTL file=%p, op=%d, pArg=%p\\n\", pFile->h, op, pArg));\n  switch( op ){\n    case SQLITE_FCNTL_LOCKSTATE: {\n      *(int*)pArg = pFile->locktype;\n      OSTRACE((\"FCNTL file=%p, rc=SQLITE_OK\\n\", pFile->h));\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_LAST_ERRNO: {\n      *(int*)pArg = (int)pFile->lastErrno;\n      OSTRACE((\"FCNTL file=%p, rc=SQLITE_OK\\n\", pFile->h));\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_CHUNK_SIZE: {\n      pFile->szChunk = *(int *)pArg;\n      OSTRACE((\"FCNTL file=%p, rc=SQLITE_OK\\n\", pFile->h));\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_SIZE_HINT: {\n      if( pFile->szChunk>0 ){\n        sqlite3_int64 oldSz;\n        int rc = winFileSize(id, &oldSz);\n        if( rc==SQLITE_OK ){\n          sqlite3_int64 newSz = *(sqlite3_int64*)pArg;\n          if( newSz>oldSz ){\n            SimulateIOErrorBenign(1);\n            rc = winTruncate(id, newSz);\n            SimulateIOErrorBenign(0);\n          }\n        }\n        OSTRACE((\"FCNTL file=%p, rc=%s\\n\", pFile->h, sqlite3ErrName(rc)));\n        return rc;\n      }\n      OSTRACE((\"FCNTL file=%p, rc=SQLITE_OK\\n\", pFile->h));\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_PERSIST_WAL: {\n      winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);\n      OSTRACE((\"FCNTL file=%p, rc=SQLITE_OK\\n\", pFile->h));\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {\n      winModeBit(pFile, WINFILE_PSOW, (int*)pArg);\n      OSTRACE((\"FCNTL file=%p, rc=SQLITE_OK\\n\", pFile->h));\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_VFSNAME: {\n      *(char**)pArg = sqlite3_mprintf(\"%s\", pFile->pVfs->zName);\n      OSTRACE((\"FCNTL file=%p, rc=SQLITE_OK\\n\", pFile->h));\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_WIN32_AV_RETRY: {\n      int *a = (int*)pArg;\n      if( a[0]>0 ){\n        winIoerrRetry = a[0];\n      }else{\n        a[0] = winIoerrRetry;\n      }\n      if( a[1]>0 ){\n        winIoerrRetryDelay = a[1];\n      }else{\n        a[1] = winIoerrRetryDelay;\n      }\n      OSTRACE((\"FCNTL file=%p, rc=SQLITE_OK\\n\", pFile->h));\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_WIN32_GET_HANDLE: {\n      LPHANDLE phFile = (LPHANDLE)pArg;\n      *phFile = pFile->h;\n      OSTRACE((\"FCNTL file=%p, rc=SQLITE_OK\\n\", pFile->h));\n      return SQLITE_OK;\n    }\n#ifdef SQLITE_TEST\n    case SQLITE_FCNTL_WIN32_SET_HANDLE: {\n      LPHANDLE phFile = (LPHANDLE)pArg;\n      HANDLE hOldFile = pFile->h;\n      pFile->h = *phFile;\n      *phFile = hOldFile;\n      OSTRACE((\"FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\\n\",\n               hOldFile, pFile->h));\n      return SQLITE_OK;\n    }\n#endif\n    case SQLITE_FCNTL_TEMPFILENAME: {\n      char *zTFile = 0;\n      int rc = winGetTempname(pFile->pVfs, &zTFile);\n      if( rc==SQLITE_OK ){\n        *(char**)pArg = zTFile;\n      }\n      OSTRACE((\"FCNTL file=%p, rc=%s\\n\", pFile->h, sqlite3ErrName(rc)));\n      return rc;\n    }\n#if SQLITE_MAX_MMAP_SIZE>0\n    case SQLITE_FCNTL_MMAP_SIZE: {\n      i64 newLimit = *(i64*)pArg;\n      int rc = SQLITE_OK;\n      if( newLimit>sqlite3GlobalConfig.mxMmap ){\n        newLimit = sqlite3GlobalConfig.mxMmap;\n      }\n\n      /* The value of newLimit may be eventually cast to (SIZE_T) and passed\n      ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at\n      ** least a 64-bit type. */\n      if( newLimit>0 && sizeof(SIZE_T)<8 ){\n        newLimit = (newLimit & 0x7FFFFFFF);\n      }\n\n      *(i64*)pArg = pFile->mmapSizeMax;\n      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){\n        pFile->mmapSizeMax = newLimit;\n        if( pFile->mmapSize>0 ){\n          winUnmapfile(pFile);\n          rc = winMapfile(pFile, -1);\n        }\n      }\n      OSTRACE((\"FCNTL file=%p, rc=%s\\n\", pFile->h, sqlite3ErrName(rc)));\n      return rc;\n    }\n#endif\n  }\n  OSTRACE((\"FCNTL file=%p, rc=SQLITE_NOTFOUND\\n\", pFile->h));\n  return SQLITE_NOTFOUND;\n}\n\n/*\n** Return the sector size in bytes of the underlying block device for\n** the specified file. This is almost always 512 bytes, but may be\n** larger for some devices.\n**\n** SQLite code assumes this function cannot fail. It also assumes that\n** if two files are created in the same file-system directory (i.e.\n** a database and its journal file) that the sector size will be the\n** same for both.\n*/\nstatic int winSectorSize(sqlite3_file *id){\n  (void)id;\n  return SQLITE_DEFAULT_SECTOR_SIZE;\n}\n\n/*\n** Return a vector of device characteristics.\n*/\nstatic int winDeviceCharacteristics(sqlite3_file *id){\n  winFile *p = (winFile*)id;\n  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |\n         ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);\n}\n\n/*\n** Windows will only let you create file view mappings\n** on allocation size granularity boundaries.\n** During sqlite3_os_init() we do a GetSystemInfo()\n** to get the granularity size.\n*/\nstatic SYSTEM_INFO winSysInfo;\n\n#ifndef SQLITE_OMIT_WAL\n\n/*\n** Helper functions to obtain and relinquish the global mutex. The\n** global mutex is used to protect the winLockInfo objects used by\n** this file, all of which may be shared by multiple threads.\n**\n** Function winShmMutexHeld() is used to assert() that the global mutex\n** is held when required. This function is only used as part of assert()\n** statements. e.g.\n**\n**   winShmEnterMutex()\n**     assert( winShmMutexHeld() );\n**   winShmLeaveMutex()\n*/\nstatic sqlite3_mutex *winBigLock = 0;\nstatic void winShmEnterMutex(void){\n  sqlite3_mutex_enter(winBigLock);\n}\nstatic void winShmLeaveMutex(void){\n  sqlite3_mutex_leave(winBigLock);\n}\n#ifndef NDEBUG\nstatic int winShmMutexHeld(void) {\n  return sqlite3_mutex_held(winBigLock);\n}\n#endif\n\n/*\n** Object used to represent a single file opened and mmapped to provide\n** shared memory.  When multiple threads all reference the same\n** log-summary, each thread has its own winFile object, but they all\n** point to a single instance of this object.  In other words, each\n** log-summary is opened only once per process.\n**\n** winShmMutexHeld() must be true when creating or destroying\n** this object or while reading or writing the following fields:\n**\n**      nRef\n**      pNext\n**\n** The following fields are read-only after the object is created:\n**\n**      fid\n**      zFilename\n**\n** Either winShmNode.mutex must be held or winShmNode.nRef==0 and\n** winShmMutexHeld() is true when reading or writing any other field\n** in this structure.\n**\n*/\nstruct winShmNode {\n  sqlite3_mutex *mutex;      /* Mutex to access this object */\n  char *zFilename;           /* Name of the file */\n  winFile hFile;             /* File handle from winOpen */\n\n  int szRegion;              /* Size of shared-memory regions */\n  int nRegion;               /* Size of array apRegion */\n  u8 isReadonly;             /* True if read-only */\n  u8 isUnlocked;             /* True if no DMS lock held */\n\n  struct ShmRegion {\n    HANDLE hMap;             /* File handle from CreateFileMapping */\n    void *pMap;\n  } *aRegion;\n  DWORD lastErrno;           /* The Windows errno from the last I/O error */\n\n  int nRef;                  /* Number of winShm objects pointing to this */\n  winShm *pFirst;            /* All winShm objects pointing to this */\n  winShmNode *pNext;         /* Next in list of all winShmNode objects */\n#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)\n  u8 nextShmId;              /* Next available winShm.id value */\n#endif\n};\n\n/*\n** A global array of all winShmNode objects.\n**\n** The winShmMutexHeld() must be true while reading or writing this list.\n*/\nstatic winShmNode *winShmNodeList = 0;\n\n/*\n** Structure used internally by this VFS to record the state of an\n** open shared memory connection.\n**\n** The following fields are initialized when this object is created and\n** are read-only thereafter:\n**\n**    winShm.pShmNode\n**    winShm.id\n**\n** All other fields are read/write.  The winShm.pShmNode->mutex must be held\n** while accessing any read/write fields.\n*/\nstruct winShm {\n  winShmNode *pShmNode;      /* The underlying winShmNode object */\n  winShm *pNext;             /* Next winShm with the same winShmNode */\n  u8 hasMutex;               /* True if holding the winShmNode mutex */\n  u16 sharedMask;            /* Mask of shared locks held */\n  u16 exclMask;              /* Mask of exclusive locks held */\n#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)\n  u8 id;                     /* Id of this connection with its winShmNode */\n#endif\n};\n\n/*\n** Constants used for locking\n*/\n#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */\n#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */\n\n/*\n** Apply advisory locks for all n bytes beginning at ofst.\n*/\n#define WINSHM_UNLCK  1\n#define WINSHM_RDLCK  2\n#define WINSHM_WRLCK  3\nstatic int winShmSystemLock(\n  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */\n  int lockType,         /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */\n  int ofst,             /* Offset to first byte to be locked/unlocked */\n  int nByte             /* Number of bytes to lock or unlock */\n){\n  int rc = 0;           /* Result code form Lock/UnlockFileEx() */\n\n  /* Access to the winShmNode object is serialized by the caller */\n  assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );\n\n  OSTRACE((\"SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\\n\",\n           pFile->hFile.h, lockType, ofst, nByte));\n\n  /* Release/Acquire the system-level lock */\n  if( lockType==WINSHM_UNLCK ){\n    rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);\n  }else{\n    /* Initialize the locking parameters */\n    DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;\n    if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;\n    rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);\n  }\n\n  if( rc!= 0 ){\n    rc = SQLITE_OK;\n  }else{\n    pFile->lastErrno =  osGetLastError();\n    rc = SQLITE_BUSY;\n  }\n\n  OSTRACE((\"SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\\n\",\n           pFile->hFile.h, (lockType == WINSHM_UNLCK) ? \"winUnlockFile\" :\n           \"winLockFile\", pFile->lastErrno, sqlite3ErrName(rc)));\n\n  return rc;\n}\n\n/* Forward references to VFS methods */\nstatic int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);\nstatic int winDelete(sqlite3_vfs *,const char*,int);\n\n/*\n** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.\n**\n** This is not a VFS shared-memory method; it is a utility function called\n** by VFS shared-memory methods.\n*/\nstatic void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){\n  winShmNode **pp;\n  winShmNode *p;\n  assert( winShmMutexHeld() );\n  OSTRACE((\"SHM-PURGE pid=%lu, deleteFlag=%d\\n\",\n           osGetCurrentProcessId(), deleteFlag));\n  pp = &winShmNodeList;\n  while( (p = *pp)!=0 ){\n    if( p->nRef==0 ){\n      int i;\n      if( p->mutex ){ sqlite3_mutex_free(p->mutex); }\n      for(i=0; i<p->nRegion; i++){\n        BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);\n        OSTRACE((\"SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\\n\",\n                 osGetCurrentProcessId(), i, bRc ? \"ok\" : \"failed\"));\n        UNUSED_VARIABLE_VALUE(bRc);\n        bRc = osCloseHandle(p->aRegion[i].hMap);\n        OSTRACE((\"SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\\n\",\n                 osGetCurrentProcessId(), i, bRc ? \"ok\" : \"failed\"));\n        UNUSED_VARIABLE_VALUE(bRc);\n      }\n      if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){\n        SimulateIOErrorBenign(1);\n        winClose((sqlite3_file *)&p->hFile);\n        SimulateIOErrorBenign(0);\n      }\n      if( deleteFlag ){\n        SimulateIOErrorBenign(1);\n        sqlite3BeginBenignMalloc();\n        winDelete(pVfs, p->zFilename, 0);\n        sqlite3EndBenignMalloc();\n        SimulateIOErrorBenign(0);\n      }\n      *pp = p->pNext;\n      sqlite3_free(p->aRegion);\n      sqlite3_free(p);\n    }else{\n      pp = &p->pNext;\n    }\n  }\n}\n\n/*\n** The DMS lock has not yet been taken on shm file pShmNode. Attempt to\n** take it now. Return SQLITE_OK if successful, or an SQLite error\n** code otherwise.\n**\n** If the DMS cannot be locked because this is a readonly_shm=1\n** connection and no other process already holds a lock, return\n** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.\n*/\nstatic int winLockSharedMemory(winShmNode *pShmNode){\n  int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);\n\n  if( rc==SQLITE_OK ){\n    if( pShmNode->isReadonly ){\n      pShmNode->isUnlocked = 1;\n      winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);\n      return SQLITE_READONLY_CANTINIT;\n    }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){\n      winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);\n      return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),\n                         \"winLockSharedMemory\", pShmNode->zFilename);\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);\n  }\n\n  return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);\n}\n\n/*\n** Open the shared-memory area associated with database file pDbFd.\n**\n** When opening a new shared-memory file, if no other instances of that\n** file are currently open, in this process or in other processes, then\n** the file must be truncated to zero length or have its header cleared.\n*/\nstatic int winOpenSharedMemory(winFile *pDbFd){\n  struct winShm *p;                  /* The connection to be opened */\n  winShmNode *pShmNode = 0;          /* The underlying mmapped file */\n  int rc = SQLITE_OK;                /* Result code */\n  winShmNode *pNew;                  /* Newly allocated winShmNode */\n  int nName;                         /* Size of zName in bytes */\n\n  assert( pDbFd->pShm==0 );    /* Not previously opened */\n\n  /* Allocate space for the new sqlite3_shm object.  Also speculatively\n  ** allocate space for a new winShmNode and filename.\n  */\n  p = sqlite3MallocZero( sizeof(*p) );\n  if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;\n  nName = sqlite3Strlen30(pDbFd->zPath);\n  pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );\n  if( pNew==0 ){\n    sqlite3_free(p);\n    return SQLITE_IOERR_NOMEM_BKPT;\n  }\n  pNew->zFilename = (char*)&pNew[1];\n  sqlite3_snprintf(nName+15, pNew->zFilename, \"%s-shm\", pDbFd->zPath);\n  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);\n\n  /* Look to see if there is an existing winShmNode that can be used.\n  ** If no matching winShmNode currently exists, create a new one.\n  */\n  winShmEnterMutex();\n  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){\n    /* TBD need to come up with better match here.  Perhaps\n    ** use FILE_ID_BOTH_DIR_INFO Structure.\n    */\n    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;\n  }\n  if( pShmNode ){\n    sqlite3_free(pNew);\n  }else{\n    int inFlags = SQLITE_OPEN_WAL;\n    int outFlags = 0;\n\n    pShmNode = pNew;\n    pNew = 0;\n    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;\n    pShmNode->pNext = winShmNodeList;\n    winShmNodeList = pShmNode;\n\n    if( sqlite3GlobalConfig.bCoreMutex ){\n      pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);\n      if( pShmNode->mutex==0 ){\n        rc = SQLITE_IOERR_NOMEM_BKPT;\n        goto shm_open_err;\n      }\n    }\n\n    if( 0==sqlite3_uri_boolean(pDbFd->zPath, \"readonly_shm\", 0) ){\n      inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;\n    }else{\n      inFlags |= SQLITE_OPEN_READONLY;\n    }\n    rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,\n                 (sqlite3_file*)&pShmNode->hFile,\n                 inFlags, &outFlags);\n    if( rc!=SQLITE_OK ){\n      rc = winLogError(rc, osGetLastError(), \"winOpenShm\",\n                       pShmNode->zFilename);\n      goto shm_open_err;\n    }\n    if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;\n\n    rc = winLockSharedMemory(pShmNode);\n    if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;\n  }\n\n  /* Make the new connection a child of the winShmNode */\n  p->pShmNode = pShmNode;\n#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)\n  p->id = pShmNode->nextShmId++;\n#endif\n  pShmNode->nRef++;\n  pDbFd->pShm = p;\n  winShmLeaveMutex();\n\n  /* The reference count on pShmNode has already been incremented under\n  ** the cover of the winShmEnterMutex() mutex and the pointer from the\n  ** new (struct winShm) object to the pShmNode has been set. All that is\n  ** left to do is to link the new object into the linked list starting\n  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex\n  ** mutex.\n  */\n  sqlite3_mutex_enter(pShmNode->mutex);\n  p->pNext = pShmNode->pFirst;\n  pShmNode->pFirst = p;\n  sqlite3_mutex_leave(pShmNode->mutex);\n  return rc;\n\n  /* Jump here on any error */\nshm_open_err:\n  winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);\n  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */\n  sqlite3_free(p);\n  sqlite3_free(pNew);\n  winShmLeaveMutex();\n  return rc;\n}\n\n/*\n** Close a connection to shared-memory.  Delete the underlying\n** storage if deleteFlag is true.\n*/\nstatic int winShmUnmap(\n  sqlite3_file *fd,          /* Database holding shared memory */\n  int deleteFlag             /* Delete after closing if true */\n){\n  winFile *pDbFd;       /* Database holding shared-memory */\n  winShm *p;            /* The connection to be closed */\n  winShmNode *pShmNode; /* The underlying shared-memory file */\n  winShm **pp;          /* For looping over sibling connections */\n\n  pDbFd = (winFile*)fd;\n  p = pDbFd->pShm;\n  if( p==0 ) return SQLITE_OK;\n  pShmNode = p->pShmNode;\n\n  /* Remove connection p from the set of connections associated\n  ** with pShmNode */\n  sqlite3_mutex_enter(pShmNode->mutex);\n  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}\n  *pp = p->pNext;\n\n  /* Free the connection p */\n  sqlite3_free(p);\n  pDbFd->pShm = 0;\n  sqlite3_mutex_leave(pShmNode->mutex);\n\n  /* If pShmNode->nRef has reached 0, then close the underlying\n  ** shared-memory file, too */\n  winShmEnterMutex();\n  assert( pShmNode->nRef>0 );\n  pShmNode->nRef--;\n  if( pShmNode->nRef==0 ){\n    winShmPurge(pDbFd->pVfs, deleteFlag);\n  }\n  winShmLeaveMutex();\n\n  return SQLITE_OK;\n}\n\n/*\n** Change the lock state for a shared-memory segment.\n*/\nstatic int winShmLock(\n  sqlite3_file *fd,          /* Database file holding the shared memory */\n  int ofst,                  /* First lock to acquire or release */\n  int n,                     /* Number of locks to acquire or release */\n  int flags                  /* What to do with the lock */\n){\n  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */\n  winShm *p = pDbFd->pShm;              /* The shared memory being locked */\n  winShm *pX;                           /* For looping over all siblings */\n  winShmNode *pShmNode = p->pShmNode;\n  int rc = SQLITE_OK;                   /* Result code */\n  u16 mask;                             /* Mask of locks to take or release */\n\n  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );\n  assert( n>=1 );\n  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)\n       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)\n       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)\n       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );\n  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );\n\n  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));\n  assert( n>1 || mask==(1<<ofst) );\n  sqlite3_mutex_enter(pShmNode->mutex);\n  if( flags & SQLITE_SHM_UNLOCK ){\n    u16 allMask = 0; /* Mask of locks held by siblings */\n\n    /* See if any siblings hold this same lock */\n    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){\n      if( pX==p ) continue;\n      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );\n      allMask |= pX->sharedMask;\n    }\n\n    /* Unlock the system-level locks */\n    if( (mask & allMask)==0 ){\n      rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);\n    }else{\n      rc = SQLITE_OK;\n    }\n\n    /* Undo the local locks */\n    if( rc==SQLITE_OK ){\n      p->exclMask &= ~mask;\n      p->sharedMask &= ~mask;\n    }\n  }else if( flags & SQLITE_SHM_SHARED ){\n    u16 allShared = 0;  /* Union of locks held by connections other than \"p\" */\n\n    /* Find out which shared locks are already held by sibling connections.\n    ** If any sibling already holds an exclusive lock, go ahead and return\n    ** SQLITE_BUSY.\n    */\n    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){\n      if( (pX->exclMask & mask)!=0 ){\n        rc = SQLITE_BUSY;\n        break;\n      }\n      allShared |= pX->sharedMask;\n    }\n\n    /* Get shared locks at the system level, if necessary */\n    if( rc==SQLITE_OK ){\n      if( (allShared & mask)==0 ){\n        rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);\n      }else{\n        rc = SQLITE_OK;\n      }\n    }\n\n    /* Get the local shared locks */\n    if( rc==SQLITE_OK ){\n      p->sharedMask |= mask;\n    }\n  }else{\n    /* Make sure no sibling connections hold locks that will block this\n    ** lock.  If any do, return SQLITE_BUSY right away.\n    */\n    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){\n      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){\n        rc = SQLITE_BUSY;\n        break;\n      }\n    }\n\n    /* Get the exclusive locks at the system level.  Then if successful\n    ** also mark the local connection as being locked.\n    */\n    if( rc==SQLITE_OK ){\n      rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);\n      if( rc==SQLITE_OK ){\n        assert( (p->sharedMask & mask)==0 );\n        p->exclMask |= mask;\n      }\n    }\n  }\n  sqlite3_mutex_leave(pShmNode->mutex);\n  OSTRACE((\"SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\\n\",\n           osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,\n           sqlite3ErrName(rc)));\n  return rc;\n}\n\n/*\n** Implement a memory barrier or memory fence on shared memory.\n**\n** All loads and stores begun before the barrier must complete before\n** any load or store begun after the barrier.\n*/\nstatic void winShmBarrier(\n  sqlite3_file *fd          /* Database holding the shared memory */\n){\n  UNUSED_PARAMETER(fd);\n  sqlite3MemoryBarrier();   /* compiler-defined memory barrier */\n  winShmEnterMutex();       /* Also mutex, for redundancy */\n  winShmLeaveMutex();\n}\n\n/*\n** This function is called to obtain a pointer to region iRegion of the\n** shared-memory associated with the database file fd. Shared-memory regions\n** are numbered starting from zero. Each shared-memory region is szRegion\n** bytes in size.\n**\n** If an error occurs, an error code is returned and *pp is set to NULL.\n**\n** Otherwise, if the isWrite parameter is 0 and the requested shared-memory\n** region has not been allocated (by any client, including one running in a\n** separate process), then *pp is set to NULL and SQLITE_OK returned. If\n** isWrite is non-zero and the requested shared-memory region has not yet\n** been allocated, it is allocated by this function.\n**\n** If the shared-memory region has already been allocated or is allocated by\n** this call as described above, then it is mapped into this processes\n** address space (if it is not already), *pp is set to point to the mapped\n** memory and SQLITE_OK returned.\n*/\nstatic int winShmMap(\n  sqlite3_file *fd,               /* Handle open on database file */\n  int iRegion,                    /* Region to retrieve */\n  int szRegion,                   /* Size of regions */\n  int isWrite,                    /* True to extend file if necessary */\n  void volatile **pp              /* OUT: Mapped memory */\n){\n  winFile *pDbFd = (winFile*)fd;\n  winShm *pShm = pDbFd->pShm;\n  winShmNode *pShmNode;\n  DWORD protect = PAGE_READWRITE;\n  DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ;\n  int rc = SQLITE_OK;\n\n  if( !pShm ){\n    rc = winOpenSharedMemory(pDbFd);\n    if( rc!=SQLITE_OK ) return rc;\n    pShm = pDbFd->pShm;\n    assert( pShm!=0 );\n  }\n  pShmNode = pShm->pShmNode;\n\n  sqlite3_mutex_enter(pShmNode->mutex);\n  if( pShmNode->isUnlocked ){\n    rc = winLockSharedMemory(pShmNode);\n    if( rc!=SQLITE_OK ) goto shmpage_out;\n    pShmNode->isUnlocked = 0;\n  }\n  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );\n\n  if( pShmNode->nRegion<=iRegion ){\n    struct ShmRegion *apNew;           /* New aRegion[] array */\n    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */\n    sqlite3_int64 sz;                  /* Current size of wal-index file */\n\n    pShmNode->szRegion = szRegion;\n\n    /* The requested region is not mapped into this processes address space.\n    ** Check to see if it has been allocated (i.e. if the wal-index file is\n    ** large enough to contain the requested region).\n    */\n    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);\n    if( rc!=SQLITE_OK ){\n      rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),\n                       \"winShmMap1\", pDbFd->zPath);\n      goto shmpage_out;\n    }\n\n    if( sz<nByte ){\n      /* The requested memory region does not exist. If isWrite is set to\n      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.\n      **\n      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate\n      ** the requested memory region.\n      */\n      if( !isWrite ) goto shmpage_out;\n      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);\n      if( rc!=SQLITE_OK ){\n        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),\n                         \"winShmMap2\", pDbFd->zPath);\n        goto shmpage_out;\n      }\n    }\n\n    /* Map the requested memory region into this processes address space. */\n    apNew = (struct ShmRegion *)sqlite3_realloc64(\n        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])\n    );\n    if( !apNew ){\n      rc = SQLITE_IOERR_NOMEM_BKPT;\n      goto shmpage_out;\n    }\n    pShmNode->aRegion = apNew;\n\n    if( pShmNode->isReadonly ){\n      protect = PAGE_READONLY;\n      flags = FILE_MAP_READ;\n    }\n\n    while( pShmNode->nRegion<=iRegion ){\n      HANDLE hMap = NULL;         /* file-mapping handle */\n      void *pMap = 0;             /* Mapped memory region */\n\n#if SQLITE_OS_WINRT\n      hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,\n          NULL, protect, nByte, NULL\n      );\n#elif defined(SQLITE_WIN32_HAS_WIDE)\n      hMap = osCreateFileMappingW(pShmNode->hFile.h,\n          NULL, protect, 0, nByte, NULL\n      );\n#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA\n      hMap = osCreateFileMappingA(pShmNode->hFile.h,\n          NULL, protect, 0, nByte, NULL\n      );\n#endif\n      OSTRACE((\"SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\\n\",\n               osGetCurrentProcessId(), pShmNode->nRegion, nByte,\n               hMap ? \"ok\" : \"failed\"));\n      if( hMap ){\n        int iOffset = pShmNode->nRegion*szRegion;\n        int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;\n#if SQLITE_OS_WINRT\n        pMap = osMapViewOfFileFromApp(hMap, flags,\n            iOffset - iOffsetShift, szRegion + iOffsetShift\n        );\n#else\n        pMap = osMapViewOfFile(hMap, flags,\n            0, iOffset - iOffsetShift, szRegion + iOffsetShift\n        );\n#endif\n        OSTRACE((\"SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\\n\",\n                 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,\n                 szRegion, pMap ? \"ok\" : \"failed\"));\n      }\n      if( !pMap ){\n        pShmNode->lastErrno = osGetLastError();\n        rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,\n                         \"winShmMap3\", pDbFd->zPath);\n        if( hMap ) osCloseHandle(hMap);\n        goto shmpage_out;\n      }\n\n      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;\n      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;\n      pShmNode->nRegion++;\n    }\n  }\n\nshmpage_out:\n  if( pShmNode->nRegion>iRegion ){\n    int iOffset = iRegion*szRegion;\n    int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;\n    char *p = (char *)pShmNode->aRegion[iRegion].pMap;\n    *pp = (void *)&p[iOffsetShift];\n  }else{\n    *pp = 0;\n  }\n  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;\n  sqlite3_mutex_leave(pShmNode->mutex);\n  return rc;\n}\n\n#else\n# define winShmMap     0\n# define winShmLock    0\n# define winShmBarrier 0\n# define winShmUnmap   0\n#endif /* #ifndef SQLITE_OMIT_WAL */\n\n/*\n** Cleans up the mapped region of the specified file, if any.\n*/\n#if SQLITE_MAX_MMAP_SIZE>0\nstatic int winUnmapfile(winFile *pFile){\n  assert( pFile!=0 );\n  OSTRACE((\"UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, \"\n           \"mmapSize=%lld, mmapSizeMax=%lld\\n\",\n           osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,\n           pFile->mmapSize, pFile->mmapSizeMax));\n  if( pFile->pMapRegion ){\n    if( !osUnmapViewOfFile(pFile->pMapRegion) ){\n      pFile->lastErrno = osGetLastError();\n      OSTRACE((\"UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, \"\n               \"rc=SQLITE_IOERR_MMAP\\n\", osGetCurrentProcessId(), pFile,\n               pFile->pMapRegion));\n      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,\n                         \"winUnmapfile1\", pFile->zPath);\n    }\n    pFile->pMapRegion = 0;\n    pFile->mmapSize = 0;\n  }\n  if( pFile->hMap!=NULL ){\n    if( !osCloseHandle(pFile->hMap) ){\n      pFile->lastErrno = osGetLastError();\n      OSTRACE((\"UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\\n\",\n               osGetCurrentProcessId(), pFile, pFile->hMap));\n      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,\n                         \"winUnmapfile2\", pFile->zPath);\n    }\n    pFile->hMap = NULL;\n  }\n  OSTRACE((\"UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\\n\",\n           osGetCurrentProcessId(), pFile));\n  return SQLITE_OK;\n}\n\n/*\n** Memory map or remap the file opened by file-descriptor pFd (if the file\n** is already mapped, the existing mapping is replaced by the new). Or, if\n** there already exists a mapping for this file, and there are still\n** outstanding xFetch() references to it, this function is a no-op.\n**\n** If parameter nByte is non-negative, then it is the requested size of\n** the mapping to create. Otherwise, if nByte is less than zero, then the\n** requested size is the size of the file on disk. The actual size of the\n** created mapping is either the requested size or the value configured\n** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.\n**\n** SQLITE_OK is returned if no error occurs (even if the mapping is not\n** recreated as a result of outstanding references) or an SQLite error\n** code otherwise.\n*/\nstatic int winMapfile(winFile *pFd, sqlite3_int64 nByte){\n  sqlite3_int64 nMap = nByte;\n  int rc;\n\n  assert( nMap>=0 || pFd->nFetchOut==0 );\n  OSTRACE((\"MAP-FILE pid=%lu, pFile=%p, size=%lld\\n\",\n           osGetCurrentProcessId(), pFd, nByte));\n\n  if( pFd->nFetchOut>0 ) return SQLITE_OK;\n\n  if( nMap<0 ){\n    rc = winFileSize((sqlite3_file*)pFd, &nMap);\n    if( rc ){\n      OSTRACE((\"MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\\n\",\n               osGetCurrentProcessId(), pFd));\n      return SQLITE_IOERR_FSTAT;\n    }\n  }\n  if( nMap>pFd->mmapSizeMax ){\n    nMap = pFd->mmapSizeMax;\n  }\n  nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);\n\n  if( nMap==0 && pFd->mmapSize>0 ){\n    winUnmapfile(pFd);\n  }\n  if( nMap!=pFd->mmapSize ){\n    void *pNew = 0;\n    DWORD protect = PAGE_READONLY;\n    DWORD flags = FILE_MAP_READ;\n\n    winUnmapfile(pFd);\n#ifdef SQLITE_MMAP_READWRITE\n    if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){\n      protect = PAGE_READWRITE;\n      flags |= FILE_MAP_WRITE;\n    }\n#endif\n#if SQLITE_OS_WINRT\n    pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);\n#elif defined(SQLITE_WIN32_HAS_WIDE)\n    pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,\n                                (DWORD)((nMap>>32) & 0xffffffff),\n                                (DWORD)(nMap & 0xffffffff), NULL);\n#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA\n    pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,\n                                (DWORD)((nMap>>32) & 0xffffffff),\n                                (DWORD)(nMap & 0xffffffff), NULL);\n#endif\n    if( pFd->hMap==NULL ){\n      pFd->lastErrno = osGetLastError();\n      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,\n                       \"winMapfile1\", pFd->zPath);\n      /* Log the error, but continue normal operation using xRead/xWrite */\n      OSTRACE((\"MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\\n\",\n               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));\n      return SQLITE_OK;\n    }\n    assert( (nMap % winSysInfo.dwPageSize)==0 );\n    assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );\n#if SQLITE_OS_WINRT\n    pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);\n#else\n    pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);\n#endif\n    if( pNew==NULL ){\n      osCloseHandle(pFd->hMap);\n      pFd->hMap = NULL;\n      pFd->lastErrno = osGetLastError();\n      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,\n                       \"winMapfile2\", pFd->zPath);\n      /* Log the error, but continue normal operation using xRead/xWrite */\n      OSTRACE((\"MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\\n\",\n               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));\n      return SQLITE_OK;\n    }\n    pFd->pMapRegion = pNew;\n    pFd->mmapSize = nMap;\n  }\n\n  OSTRACE((\"MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\\n\",\n           osGetCurrentProcessId(), pFd));\n  return SQLITE_OK;\n}\n#endif /* SQLITE_MAX_MMAP_SIZE>0 */\n\n/*\n** If possible, return a pointer to a mapping of file fd starting at offset\n** iOff. The mapping must be valid for at least nAmt bytes.\n**\n** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.\n** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.\n** Finally, if an error does occur, return an SQLite error code. The final\n** value of *pp is undefined in this case.\n**\n** If this function does return a pointer, the caller must eventually\n** release the reference by calling winUnfetch().\n*/\nstatic int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){\n#if SQLITE_MAX_MMAP_SIZE>0\n  winFile *pFd = (winFile*)fd;   /* The underlying database file */\n#endif\n  *pp = 0;\n\n  OSTRACE((\"FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\\n\",\n           osGetCurrentProcessId(), fd, iOff, nAmt, pp));\n\n#if SQLITE_MAX_MMAP_SIZE>0\n  if( pFd->mmapSizeMax>0 ){\n    if( pFd->pMapRegion==0 ){\n      int rc = winMapfile(pFd, -1);\n      if( rc!=SQLITE_OK ){\n        OSTRACE((\"FETCH pid=%lu, pFile=%p, rc=%s\\n\",\n                 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));\n        return rc;\n      }\n    }\n    if( pFd->mmapSize >= iOff+nAmt ){\n      assert( pFd->pMapRegion!=0 );\n      *pp = &((u8 *)pFd->pMapRegion)[iOff];\n      pFd->nFetchOut++;\n    }\n  }\n#endif\n\n  OSTRACE((\"FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\\n\",\n           osGetCurrentProcessId(), fd, pp, *pp));\n  return SQLITE_OK;\n}\n\n/*\n** If the third argument is non-NULL, then this function releases a\n** reference obtained by an earlier call to winFetch(). The second\n** argument passed to this function must be the same as the corresponding\n** argument that was passed to the winFetch() invocation.\n**\n** Or, if the third argument is NULL, then this function is being called\n** to inform the VFS layer that, according to POSIX, any existing mapping\n** may now be invalid and should be unmapped.\n*/\nstatic int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){\n#if SQLITE_MAX_MMAP_SIZE>0\n  winFile *pFd = (winFile*)fd;   /* The underlying database file */\n\n  /* If p==0 (unmap the entire file) then there must be no outstanding\n  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),\n  ** then there must be at least one outstanding.  */\n  assert( (p==0)==(pFd->nFetchOut==0) );\n\n  /* If p!=0, it must match the iOff value. */\n  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );\n\n  OSTRACE((\"UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\\n\",\n           osGetCurrentProcessId(), pFd, iOff, p));\n\n  if( p ){\n    pFd->nFetchOut--;\n  }else{\n    /* FIXME:  If Windows truly always prevents truncating or deleting a\n    ** file while a mapping is held, then the following winUnmapfile() call\n    ** is unnecessary can be omitted - potentially improving\n    ** performance.  */\n    winUnmapfile(pFd);\n  }\n\n  assert( pFd->nFetchOut>=0 );\n#endif\n\n  OSTRACE((\"UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\\n\",\n           osGetCurrentProcessId(), fd));\n  return SQLITE_OK;\n}\n\n/*\n** Here ends the implementation of all sqlite3_file methods.\n**\n********************** End sqlite3_file Methods *******************************\n******************************************************************************/\n\n/*\n** This vector defines all the methods that can operate on an\n** sqlite3_file for win32.\n*/\nstatic const sqlite3_io_methods winIoMethod = {\n  3,                              /* iVersion */\n  winClose,                       /* xClose */\n  winRead,                        /* xRead */\n  winWrite,                       /* xWrite */\n  winTruncate,                    /* xTruncate */\n  winSync,                        /* xSync */\n  winFileSize,                    /* xFileSize */\n  winLock,                        /* xLock */\n  winUnlock,                      /* xUnlock */\n  winCheckReservedLock,           /* xCheckReservedLock */\n  winFileControl,                 /* xFileControl */\n  winSectorSize,                  /* xSectorSize */\n  winDeviceCharacteristics,       /* xDeviceCharacteristics */\n  winShmMap,                      /* xShmMap */\n  winShmLock,                     /* xShmLock */\n  winShmBarrier,                  /* xShmBarrier */\n  winShmUnmap,                    /* xShmUnmap */\n  winFetch,                       /* xFetch */\n  winUnfetch                      /* xUnfetch */\n};\n\n/*\n** This vector defines all the methods that can operate on an\n** sqlite3_file for win32 without performing any locking.\n*/\nstatic const sqlite3_io_methods winIoNolockMethod = {\n  3,                              /* iVersion */\n  winClose,                       /* xClose */\n  winRead,                        /* xRead */\n  winWrite,                       /* xWrite */\n  winTruncate,                    /* xTruncate */\n  winSync,                        /* xSync */\n  winFileSize,                    /* xFileSize */\n  winNolockLock,                  /* xLock */\n  winNolockUnlock,                /* xUnlock */\n  winNolockCheckReservedLock,     /* xCheckReservedLock */\n  winFileControl,                 /* xFileControl */\n  winSectorSize,                  /* xSectorSize */\n  winDeviceCharacteristics,       /* xDeviceCharacteristics */\n  winShmMap,                      /* xShmMap */\n  winShmLock,                     /* xShmLock */\n  winShmBarrier,                  /* xShmBarrier */\n  winShmUnmap,                    /* xShmUnmap */\n  winFetch,                       /* xFetch */\n  winUnfetch                      /* xUnfetch */\n};\n\nstatic winVfsAppData winAppData = {\n  &winIoMethod,       /* pMethod */\n  0,                  /* pAppData */\n  0                   /* bNoLock */\n};\n\nstatic winVfsAppData winNolockAppData = {\n  &winIoNolockMethod, /* pMethod */\n  0,                  /* pAppData */\n  1                   /* bNoLock */\n};\n\n/****************************************************************************\n**************************** sqlite3_vfs methods ****************************\n**\n** This division contains the implementation of methods on the\n** sqlite3_vfs object.\n*/\n\n#if defined(__CYGWIN__)\n/*\n** Convert a filename from whatever the underlying operating system\n** supports for filenames into UTF-8.  Space to hold the result is\n** obtained from malloc and must be freed by the calling function.\n*/\nstatic char *winConvertToUtf8Filename(const void *zFilename){\n  char *zConverted = 0;\n  if( osIsNT() ){\n    zConverted = winUnicodeToUtf8(zFilename);\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());\n  }\n#endif\n  /* caller will handle out of memory */\n  return zConverted;\n}\n#endif\n\n/*\n** Convert a UTF-8 filename into whatever form the underlying\n** operating system wants filenames in.  Space to hold the result\n** is obtained from malloc and must be freed by the calling\n** function.\n*/\nstatic void *winConvertFromUtf8Filename(const char *zFilename){\n  void *zConverted = 0;\n  if( osIsNT() ){\n    zConverted = winUtf8ToUnicode(zFilename);\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());\n  }\n#endif\n  /* caller will handle out of memory */\n  return zConverted;\n}\n\n/*\n** This function returns non-zero if the specified UTF-8 string buffer\n** ends with a directory separator character or one was successfully\n** added to it.\n*/\nstatic int winMakeEndInDirSep(int nBuf, char *zBuf){\n  if( zBuf ){\n    int nLen = sqlite3Strlen30(zBuf);\n    if( nLen>0 ){\n      if( winIsDirSep(zBuf[nLen-1]) ){\n        return 1;\n      }else if( nLen+1<nBuf ){\n        zBuf[nLen] = winGetDirSep();\n        zBuf[nLen+1] = '\\0';\n        return 1;\n      }\n    }\n  }\n  return 0;\n}\n\n/*\n** Create a temporary file name and store the resulting pointer into pzBuf.\n** The pointer returned in pzBuf must be freed via sqlite3_free().\n*/\nstatic int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){\n  static char zChars[] =\n    \"abcdefghijklmnopqrstuvwxyz\"\n    \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    \"0123456789\";\n  size_t i, j;\n  int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);\n  int nMax, nBuf, nDir, nLen;\n  char *zBuf;\n\n  /* It's odd to simulate an io-error here, but really this is just\n  ** using the io-error infrastructure to test that SQLite handles this\n  ** function failing.\n  */\n  SimulateIOError( return SQLITE_IOERR );\n\n  /* Allocate a temporary buffer to store the fully qualified file\n  ** name for the temporary file.  If this fails, we cannot continue.\n  */\n  nMax = pVfs->mxPathname; nBuf = nMax + 2;\n  zBuf = sqlite3MallocZero( nBuf );\n  if( !zBuf ){\n    OSTRACE((\"TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\\n\"));\n    return SQLITE_IOERR_NOMEM_BKPT;\n  }\n\n  /* Figure out the effective temporary directory.  First, check if one\n  ** has been explicitly set by the application; otherwise, use the one\n  ** configured by the operating system.\n  */\n  nDir = nMax - (nPre + 15);\n  assert( nDir>0 );\n  if( sqlite3_temp_directory ){\n    int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);\n    if( nDirLen>0 ){\n      if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){\n        nDirLen++;\n      }\n      if( nDirLen>nDir ){\n        sqlite3_free(zBuf);\n        OSTRACE((\"TEMP-FILENAME rc=SQLITE_ERROR\\n\"));\n        return winLogError(SQLITE_ERROR, 0, \"winGetTempname1\", 0);\n      }\n      sqlite3_snprintf(nMax, zBuf, \"%s\", sqlite3_temp_directory);\n    }\n  }\n#if defined(__CYGWIN__)\n  else{\n    static const char *azDirs[] = {\n       0, /* getenv(\"SQLITE_TMPDIR\") */\n       0, /* getenv(\"TMPDIR\") */\n       0, /* getenv(\"TMP\") */\n       0, /* getenv(\"TEMP\") */\n       0, /* getenv(\"USERPROFILE\") */\n       \"/var/tmp\",\n       \"/usr/tmp\",\n       \"/tmp\",\n       \".\",\n       0        /* List terminator */\n    };\n    unsigned int i;\n    const char *zDir = 0;\n\n    if( !azDirs[0] ) azDirs[0] = getenv(\"SQLITE_TMPDIR\");\n    if( !azDirs[1] ) azDirs[1] = getenv(\"TMPDIR\");\n    if( !azDirs[2] ) azDirs[2] = getenv(\"TMP\");\n    if( !azDirs[3] ) azDirs[3] = getenv(\"TEMP\");\n    if( !azDirs[4] ) azDirs[4] = getenv(\"USERPROFILE\");\n    for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){\n      void *zConverted;\n      if( zDir==0 ) continue;\n      /* If the path starts with a drive letter followed by the colon\n      ** character, assume it is already a native Win32 path; otherwise,\n      ** it must be converted to a native Win32 path via the Cygwin API\n      ** prior to using it.\n      */\n      if( winIsDriveLetterAndColon(zDir) ){\n        zConverted = winConvertFromUtf8Filename(zDir);\n        if( !zConverted ){\n          sqlite3_free(zBuf);\n          OSTRACE((\"TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\\n\"));\n          return SQLITE_IOERR_NOMEM_BKPT;\n        }\n        if( winIsDir(zConverted) ){\n          sqlite3_snprintf(nMax, zBuf, \"%s\", zDir);\n          sqlite3_free(zConverted);\n          break;\n        }\n        sqlite3_free(zConverted);\n      }else{\n        zConverted = sqlite3MallocZero( nMax+1 );\n        if( !zConverted ){\n          sqlite3_free(zBuf);\n          OSTRACE((\"TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\\n\"));\n          return SQLITE_IOERR_NOMEM_BKPT;\n        }\n        if( cygwin_conv_path(\n                osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,\n                zConverted, nMax+1)<0 ){\n          sqlite3_free(zConverted);\n          sqlite3_free(zBuf);\n          OSTRACE((\"TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\\n\"));\n          return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,\n                             \"winGetTempname2\", zDir);\n        }\n        if( winIsDir(zConverted) ){\n          /* At this point, we know the candidate directory exists and should\n          ** be used.  However, we may need to convert the string containing\n          ** its name into UTF-8 (i.e. if it is UTF-16 right now).\n          */\n          char *zUtf8 = winConvertToUtf8Filename(zConverted);\n          if( !zUtf8 ){\n            sqlite3_free(zConverted);\n            sqlite3_free(zBuf);\n            OSTRACE((\"TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\\n\"));\n            return SQLITE_IOERR_NOMEM_BKPT;\n          }\n          sqlite3_snprintf(nMax, zBuf, \"%s\", zUtf8);\n          sqlite3_free(zUtf8);\n          sqlite3_free(zConverted);\n          break;\n        }\n        sqlite3_free(zConverted);\n      }\n    }\n  }\n#elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)\n  else if( osIsNT() ){\n    char *zMulti;\n    LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );\n    if( !zWidePath ){\n      sqlite3_free(zBuf);\n      OSTRACE((\"TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\\n\"));\n      return SQLITE_IOERR_NOMEM_BKPT;\n    }\n    if( osGetTempPathW(nMax, zWidePath)==0 ){\n      sqlite3_free(zWidePath);\n      sqlite3_free(zBuf);\n      OSTRACE((\"TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\\n\"));\n      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),\n                         \"winGetTempname2\", 0);\n    }\n    zMulti = winUnicodeToUtf8(zWidePath);\n    if( zMulti ){\n      sqlite3_snprintf(nMax, zBuf, \"%s\", zMulti);\n      sqlite3_free(zMulti);\n      sqlite3_free(zWidePath);\n    }else{\n      sqlite3_free(zWidePath);\n      sqlite3_free(zBuf);\n      OSTRACE((\"TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\\n\"));\n      return SQLITE_IOERR_NOMEM_BKPT;\n    }\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    char *zUtf8;\n    char *zMbcsPath = sqlite3MallocZero( nMax );\n    if( !zMbcsPath ){\n      sqlite3_free(zBuf);\n      OSTRACE((\"TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\\n\"));\n      return SQLITE_IOERR_NOMEM_BKPT;\n    }\n    if( osGetTempPathA(nMax, zMbcsPath)==0 ){\n      sqlite3_free(zBuf);\n      OSTRACE((\"TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\\n\"));\n      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),\n                         \"winGetTempname3\", 0);\n    }\n    zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());\n    if( zUtf8 ){\n      sqlite3_snprintf(nMax, zBuf, \"%s\", zUtf8);\n      sqlite3_free(zUtf8);\n    }else{\n      sqlite3_free(zBuf);\n      OSTRACE((\"TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\\n\"));\n      return SQLITE_IOERR_NOMEM_BKPT;\n    }\n  }\n#endif /* SQLITE_WIN32_HAS_ANSI */\n#endif /* !SQLITE_OS_WINRT */\n\n  /*\n  ** Check to make sure the temporary directory ends with an appropriate\n  ** separator.  If it does not and there is not enough space left to add\n  ** one, fail.\n  */\n  if( !winMakeEndInDirSep(nDir+1, zBuf) ){\n    sqlite3_free(zBuf);\n    OSTRACE((\"TEMP-FILENAME rc=SQLITE_ERROR\\n\"));\n    return winLogError(SQLITE_ERROR, 0, \"winGetTempname4\", 0);\n  }\n\n  /*\n  ** Check that the output buffer is large enough for the temporary file\n  ** name in the following format:\n  **\n  **   \"<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\\0\\0\"\n  **\n  ** If not, return SQLITE_ERROR.  The number 17 is used here in order to\n  ** account for the space used by the 15 character random suffix and the\n  ** two trailing NUL characters.  The final directory separator character\n  ** has already added if it was not already present.\n  */\n  nLen = sqlite3Strlen30(zBuf);\n  if( (nLen + nPre + 17) > nBuf ){\n    sqlite3_free(zBuf);\n    OSTRACE((\"TEMP-FILENAME rc=SQLITE_ERROR\\n\"));\n    return winLogError(SQLITE_ERROR, 0, \"winGetTempname5\", 0);\n  }\n\n  sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);\n\n  j = sqlite3Strlen30(zBuf);\n  sqlite3_randomness(15, &zBuf[j]);\n  for(i=0; i<15; i++, j++){\n    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];\n  }\n  zBuf[j] = 0;\n  zBuf[j+1] = 0;\n  *pzBuf = zBuf;\n\n  OSTRACE((\"TEMP-FILENAME name=%s, rc=SQLITE_OK\\n\", zBuf));\n  return SQLITE_OK;\n}\n\n/*\n** Return TRUE if the named file is really a directory.  Return false if\n** it is something other than a directory, or if there is any kind of memory\n** allocation failure.\n*/\nstatic int winIsDir(const void *zConverted){\n  DWORD attr;\n  int rc = 0;\n  DWORD lastErrno;\n\n  if( osIsNT() ){\n    int cnt = 0;\n    WIN32_FILE_ATTRIBUTE_DATA sAttrData;\n    memset(&sAttrData, 0, sizeof(sAttrData));\n    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,\n                             GetFileExInfoStandard,\n                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}\n    if( !rc ){\n      return 0; /* Invalid name? */\n    }\n    attr = sAttrData.dwFileAttributes;\n#if SQLITE_OS_WINCE==0\n  }else{\n    attr = osGetFileAttributesA((char*)zConverted);\n#endif\n  }\n  return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);\n}\n\n/* forward reference */\nstatic int winAccess(\n  sqlite3_vfs *pVfs,         /* Not used on win32 */\n  const char *zFilename,     /* Name of file to check */\n  int flags,                 /* Type of test to make on this file */\n  int *pResOut               /* OUT: Result */\n);\n\n/*\n** Open a file.\n*/\nstatic int winOpen(\n  sqlite3_vfs *pVfs,        /* Used to get maximum path length and AppData */\n  const char *zName,        /* Name of the file (UTF-8) */\n  sqlite3_file *id,         /* Write the SQLite file handle here */\n  int flags,                /* Open mode flags */\n  int *pOutFlags            /* Status return flags */\n){\n  HANDLE h;\n  DWORD lastErrno = 0;\n  DWORD dwDesiredAccess;\n  DWORD dwShareMode;\n  DWORD dwCreationDisposition;\n  DWORD dwFlagsAndAttributes = 0;\n#if SQLITE_OS_WINCE\n  int isTemp = 0;\n#endif\n  winVfsAppData *pAppData;\n  winFile *pFile = (winFile*)id;\n  void *zConverted;              /* Filename in OS encoding */\n  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */\n  int cnt = 0;\n\n  /* If argument zPath is a NULL pointer, this function is required to open\n  ** a temporary file. Use this buffer to store the file name in.\n  */\n  char *zTmpname = 0; /* For temporary filename, if necessary. */\n\n  int rc = SQLITE_OK;            /* Function Return Code */\n#if !defined(NDEBUG) || SQLITE_OS_WINCE\n  int eType = flags&0xFFFFFF00;  /* Type of file to open */\n#endif\n\n  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);\n  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);\n  int isCreate     = (flags & SQLITE_OPEN_CREATE);\n  int isReadonly   = (flags & SQLITE_OPEN_READONLY);\n  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);\n\n#ifndef NDEBUG\n  int isOpenJournal = (isCreate && (\n        eType==SQLITE_OPEN_MASTER_JOURNAL\n     || eType==SQLITE_OPEN_MAIN_JOURNAL\n     || eType==SQLITE_OPEN_WAL\n  ));\n#endif\n\n  OSTRACE((\"OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\\n\",\n           zUtf8Name, id, flags, pOutFlags));\n\n  /* Check the following statements are true:\n  **\n  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and\n  **   (b) if CREATE is set, then READWRITE must also be set, and\n  **   (c) if EXCLUSIVE is set, then CREATE must also be set.\n  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.\n  */\n  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));\n  assert(isCreate==0 || isReadWrite);\n  assert(isExclusive==0 || isCreate);\n  assert(isDelete==0 || isCreate);\n\n  /* The main DB, main journal, WAL file and master journal are never\n  ** automatically deleted. Nor are they ever temporary files.  */\n  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );\n  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );\n  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );\n  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );\n\n  /* Assert that the upper layer has set one of the \"file-type\" flags. */\n  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB\n       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL\n       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL\n       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL\n  );\n\n  assert( pFile!=0 );\n  memset(pFile, 0, sizeof(winFile));\n  pFile->h = INVALID_HANDLE_VALUE;\n\n#if SQLITE_OS_WINRT\n  if( !zUtf8Name && !sqlite3_temp_directory ){\n    sqlite3_log(SQLITE_ERROR,\n        \"sqlite3_temp_directory variable should be set for WinRT\");\n  }\n#endif\n\n  /* If the second argument to this function is NULL, generate a\n  ** temporary file name to use\n  */\n  if( !zUtf8Name ){\n    assert( isDelete && !isOpenJournal );\n    rc = winGetTempname(pVfs, &zTmpname);\n    if( rc!=SQLITE_OK ){\n      OSTRACE((\"OPEN name=%s, rc=%s\", zUtf8Name, sqlite3ErrName(rc)));\n      return rc;\n    }\n    zUtf8Name = zTmpname;\n  }\n\n  /* Database filenames are double-zero terminated if they are not\n  ** URIs with parameters.  Hence, they can always be passed into\n  ** sqlite3_uri_parameter().\n  */\n  assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||\n       zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );\n\n  /* Convert the filename to the system encoding. */\n  zConverted = winConvertFromUtf8Filename(zUtf8Name);\n  if( zConverted==0 ){\n    sqlite3_free(zTmpname);\n    OSTRACE((\"OPEN name=%s, rc=SQLITE_IOERR_NOMEM\", zUtf8Name));\n    return SQLITE_IOERR_NOMEM_BKPT;\n  }\n\n  if( winIsDir(zConverted) ){\n    sqlite3_free(zConverted);\n    sqlite3_free(zTmpname);\n    OSTRACE((\"OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR\", zUtf8Name));\n    return SQLITE_CANTOPEN_ISDIR;\n  }\n\n  if( isReadWrite ){\n    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;\n  }else{\n    dwDesiredAccess = GENERIC_READ;\n  }\n\n  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is\n  ** created. SQLite doesn't use it to indicate \"exclusive access\"\n  ** as it is usually understood.\n  */\n  if( isExclusive ){\n    /* Creates a new file, only if it does not already exist. */\n    /* If the file exists, it fails. */\n    dwCreationDisposition = CREATE_NEW;\n  }else if( isCreate ){\n    /* Open existing file, or create if it doesn't exist */\n    dwCreationDisposition = OPEN_ALWAYS;\n  }else{\n    /* Opens a file, only if it exists. */\n    dwCreationDisposition = OPEN_EXISTING;\n  }\n\n  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;\n\n  if( isDelete ){\n#if SQLITE_OS_WINCE\n    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;\n    isTemp = 1;\n#else\n    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY\n                               | FILE_ATTRIBUTE_HIDDEN\n                               | FILE_FLAG_DELETE_ON_CLOSE;\n#endif\n  }else{\n    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;\n  }\n  /* Reports from the internet are that performance is always\n  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */\n#if SQLITE_OS_WINCE\n  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;\n#endif\n\n  if( osIsNT() ){\n#if SQLITE_OS_WINRT\n    CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;\n    extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);\n    extendedParameters.dwFileAttributes =\n            dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;\n    extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;\n    extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;\n    extendedParameters.lpSecurityAttributes = NULL;\n    extendedParameters.hTemplateFile = NULL;\n    do{\n      h = osCreateFile2((LPCWSTR)zConverted,\n                        dwDesiredAccess,\n                        dwShareMode,\n                        dwCreationDisposition,\n                        &extendedParameters);\n      if( h!=INVALID_HANDLE_VALUE ) break;\n      if( isReadWrite ){\n        int rc2, isRO = 0;\n        sqlite3BeginBenignMalloc();\n        rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);\n        sqlite3EndBenignMalloc();\n        if( rc2==SQLITE_OK && isRO ) break;\n      }\n    }while( winRetryIoerr(&cnt, &lastErrno) );\n#else\n    do{\n      h = osCreateFileW((LPCWSTR)zConverted,\n                        dwDesiredAccess,\n                        dwShareMode, NULL,\n                        dwCreationDisposition,\n                        dwFlagsAndAttributes,\n                        NULL);\n      if( h!=INVALID_HANDLE_VALUE ) break;\n      if( isReadWrite ){\n        int rc2, isRO = 0;\n        sqlite3BeginBenignMalloc();\n        rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);\n        sqlite3EndBenignMalloc();\n        if( rc2==SQLITE_OK && isRO ) break;\n      }\n    }while( winRetryIoerr(&cnt, &lastErrno) );\n#endif\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    do{\n      h = osCreateFileA((LPCSTR)zConverted,\n                        dwDesiredAccess,\n                        dwShareMode, NULL,\n                        dwCreationDisposition,\n                        dwFlagsAndAttributes,\n                        NULL);\n      if( h!=INVALID_HANDLE_VALUE ) break;\n      if( isReadWrite ){\n        int rc2, isRO = 0;\n        sqlite3BeginBenignMalloc();\n        rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);\n        sqlite3EndBenignMalloc();\n        if( rc2==SQLITE_OK && isRO ) break;\n      }\n    }while( winRetryIoerr(&cnt, &lastErrno) );\n  }\n#endif\n  winLogIoerr(cnt, __LINE__);\n\n  OSTRACE((\"OPEN file=%p, name=%s, access=%lx, rc=%s\\n\", h, zUtf8Name,\n           dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? \"failed\" : \"ok\"));\n\n  if( h==INVALID_HANDLE_VALUE ){\n    sqlite3_free(zConverted);\n    sqlite3_free(zTmpname);\n    if( isReadWrite && !isExclusive ){\n      return winOpen(pVfs, zName, id,\n         ((flags|SQLITE_OPEN_READONLY) &\n                     ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),\n         pOutFlags);\n    }else{\n      pFile->lastErrno = lastErrno;\n      winLogError(SQLITE_CANTOPEN, pFile->lastErrno, \"winOpen\", zUtf8Name);\n      return SQLITE_CANTOPEN_BKPT;\n    }\n  }\n\n  if( pOutFlags ){\n    if( isReadWrite ){\n      *pOutFlags = SQLITE_OPEN_READWRITE;\n    }else{\n      *pOutFlags = SQLITE_OPEN_READONLY;\n    }\n  }\n\n  OSTRACE((\"OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, \"\n           \"rc=%s\\n\", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?\n           *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? \"failed\" : \"ok\"));\n\n  pAppData = (winVfsAppData*)pVfs->pAppData;\n\n#if SQLITE_OS_WINCE\n  {\n    if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB\n         && ((pAppData==NULL) || !pAppData->bNoLock)\n         && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK\n    ){\n      osCloseHandle(h);\n      sqlite3_free(zConverted);\n      sqlite3_free(zTmpname);\n      OSTRACE((\"OPEN-CE-LOCK name=%s, rc=%s\\n\", zName, sqlite3ErrName(rc)));\n      return rc;\n    }\n  }\n  if( isTemp ){\n    pFile->zDeleteOnClose = zConverted;\n  }else\n#endif\n  {\n    sqlite3_free(zConverted);\n  }\n\n  sqlite3_free(zTmpname);\n  pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;\n  pFile->pVfs = pVfs;\n  pFile->h = h;\n  if( isReadonly ){\n    pFile->ctrlFlags |= WINFILE_RDONLY;\n  }\n  if( (flags & SQLITE_OPEN_MAIN_DB)\n   && sqlite3_uri_boolean(zName, \"psow\", SQLITE_POWERSAFE_OVERWRITE) \n  ){\n    pFile->ctrlFlags |= WINFILE_PSOW;\n  }\n  pFile->lastErrno = NO_ERROR;\n  pFile->zPath = zName;\n#if SQLITE_MAX_MMAP_SIZE>0\n  pFile->hMap = NULL;\n  pFile->pMapRegion = 0;\n  pFile->mmapSize = 0;\n  pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;\n#endif\n\n  OpenCounter(+1);\n  return rc;\n}\n\n/*\n** Delete the named file.\n**\n** Note that Windows does not allow a file to be deleted if some other\n** process has it open.  Sometimes a virus scanner or indexing program\n** will open a journal file shortly after it is created in order to do\n** whatever it does.  While this other process is holding the\n** file open, we will be unable to delete it.  To work around this\n** problem, we delay 100 milliseconds and try to delete again.  Up\n** to MX_DELETION_ATTEMPTs deletion attempts are run before giving\n** up and returning an error.\n*/\nstatic int winDelete(\n  sqlite3_vfs *pVfs,          /* Not used on win32 */\n  const char *zFilename,      /* Name of file to delete */\n  int syncDir                 /* Not used on win32 */\n){\n  int cnt = 0;\n  int rc;\n  DWORD attr;\n  DWORD lastErrno = 0;\n  void *zConverted;\n  UNUSED_PARAMETER(pVfs);\n  UNUSED_PARAMETER(syncDir);\n\n  SimulateIOError(return SQLITE_IOERR_DELETE);\n  OSTRACE((\"DELETE name=%s, syncDir=%d\\n\", zFilename, syncDir));\n\n  zConverted = winConvertFromUtf8Filename(zFilename);\n  if( zConverted==0 ){\n    OSTRACE((\"DELETE name=%s, rc=SQLITE_IOERR_NOMEM\\n\", zFilename));\n    return SQLITE_IOERR_NOMEM_BKPT;\n  }\n  if( osIsNT() ){\n    do {\n#if SQLITE_OS_WINRT\n      WIN32_FILE_ATTRIBUTE_DATA sAttrData;\n      memset(&sAttrData, 0, sizeof(sAttrData));\n      if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,\n                                  &sAttrData) ){\n        attr = sAttrData.dwFileAttributes;\n      }else{\n        lastErrno = osGetLastError();\n        if( lastErrno==ERROR_FILE_NOT_FOUND\n         || lastErrno==ERROR_PATH_NOT_FOUND ){\n          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */\n        }else{\n          rc = SQLITE_ERROR;\n        }\n        break;\n      }\n#else\n      attr = osGetFileAttributesW(zConverted);\n#endif\n      if ( attr==INVALID_FILE_ATTRIBUTES ){\n        lastErrno = osGetLastError();\n        if( lastErrno==ERROR_FILE_NOT_FOUND\n         || lastErrno==ERROR_PATH_NOT_FOUND ){\n          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */\n        }else{\n          rc = SQLITE_ERROR;\n        }\n        break;\n      }\n      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){\n        rc = SQLITE_ERROR; /* Files only. */\n        break;\n      }\n      if ( osDeleteFileW(zConverted) ){\n        rc = SQLITE_OK; /* Deleted OK. */\n        break;\n      }\n      if ( !winRetryIoerr(&cnt, &lastErrno) ){\n        rc = SQLITE_ERROR; /* No more retries. */\n        break;\n      }\n    } while(1);\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    do {\n      attr = osGetFileAttributesA(zConverted);\n      if ( attr==INVALID_FILE_ATTRIBUTES ){\n        lastErrno = osGetLastError();\n        if( lastErrno==ERROR_FILE_NOT_FOUND\n         || lastErrno==ERROR_PATH_NOT_FOUND ){\n          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */\n        }else{\n          rc = SQLITE_ERROR;\n        }\n        break;\n      }\n      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){\n        rc = SQLITE_ERROR; /* Files only. */\n        break;\n      }\n      if ( osDeleteFileA(zConverted) ){\n        rc = SQLITE_OK; /* Deleted OK. */\n        break;\n      }\n      if ( !winRetryIoerr(&cnt, &lastErrno) ){\n        rc = SQLITE_ERROR; /* No more retries. */\n        break;\n      }\n    } while(1);\n  }\n#endif\n  if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){\n    rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, \"winDelete\", zFilename);\n  }else{\n    winLogIoerr(cnt, __LINE__);\n  }\n  sqlite3_free(zConverted);\n  OSTRACE((\"DELETE name=%s, rc=%s\\n\", zFilename, sqlite3ErrName(rc)));\n  return rc;\n}\n\n/*\n** Check the existence and status of a file.\n*/\nstatic int winAccess(\n  sqlite3_vfs *pVfs,         /* Not used on win32 */\n  const char *zFilename,     /* Name of file to check */\n  int flags,                 /* Type of test to make on this file */\n  int *pResOut               /* OUT: Result */\n){\n  DWORD attr;\n  int rc = 0;\n  DWORD lastErrno = 0;\n  void *zConverted;\n  UNUSED_PARAMETER(pVfs);\n\n  SimulateIOError( return SQLITE_IOERR_ACCESS; );\n  OSTRACE((\"ACCESS name=%s, flags=%x, pResOut=%p\\n\",\n           zFilename, flags, pResOut));\n\n  zConverted = winConvertFromUtf8Filename(zFilename);\n  if( zConverted==0 ){\n    OSTRACE((\"ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\\n\", zFilename));\n    return SQLITE_IOERR_NOMEM_BKPT;\n  }\n  if( osIsNT() ){\n    int cnt = 0;\n    WIN32_FILE_ATTRIBUTE_DATA sAttrData;\n    memset(&sAttrData, 0, sizeof(sAttrData));\n    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,\n                             GetFileExInfoStandard,\n                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}\n    if( rc ){\n      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file\n      ** as if it does not exist.\n      */\n      if(    flags==SQLITE_ACCESS_EXISTS\n          && sAttrData.nFileSizeHigh==0\n          && sAttrData.nFileSizeLow==0 ){\n        attr = INVALID_FILE_ATTRIBUTES;\n      }else{\n        attr = sAttrData.dwFileAttributes;\n      }\n    }else{\n      winLogIoerr(cnt, __LINE__);\n      if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){\n        sqlite3_free(zConverted);\n        return winLogError(SQLITE_IOERR_ACCESS, lastErrno, \"winAccess\",\n                           zFilename);\n      }else{\n        attr = INVALID_FILE_ATTRIBUTES;\n      }\n    }\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    attr = osGetFileAttributesA((char*)zConverted);\n  }\n#endif\n  sqlite3_free(zConverted);\n  switch( flags ){\n    case SQLITE_ACCESS_READ:\n    case SQLITE_ACCESS_EXISTS:\n      rc = attr!=INVALID_FILE_ATTRIBUTES;\n      break;\n    case SQLITE_ACCESS_READWRITE:\n      rc = attr!=INVALID_FILE_ATTRIBUTES &&\n             (attr & FILE_ATTRIBUTE_READONLY)==0;\n      break;\n    default:\n      assert(!\"Invalid flags argument\");\n  }\n  *pResOut = rc;\n  OSTRACE((\"ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\\n\",\n           zFilename, pResOut, *pResOut));\n  return SQLITE_OK;\n}\n\n/*\n** Returns non-zero if the specified path name starts with the \"long path\"\n** prefix.\n*/\nstatic BOOL winIsLongPathPrefix(\n  const char *zPathname\n){\n  return ( zPathname[0]=='\\\\' && zPathname[1]=='\\\\'\n        && zPathname[2]=='?'  && zPathname[3]=='\\\\' );\n}\n\n/*\n** Returns non-zero if the specified path name starts with a drive letter\n** followed by a colon character.\n*/\nstatic BOOL winIsDriveLetterAndColon(\n  const char *zPathname\n){\n  return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );\n}\n\n/*\n** Returns non-zero if the specified path name should be used verbatim.  If\n** non-zero is returned from this function, the calling function must simply\n** use the provided path name verbatim -OR- resolve it into a full path name\n** using the GetFullPathName Win32 API function (if available).\n*/\nstatic BOOL winIsVerbatimPathname(\n  const char *zPathname\n){\n  /*\n  ** If the path name starts with a forward slash or a backslash, it is either\n  ** a legal UNC name, a volume relative path, or an absolute path name in the\n  ** \"Unix\" format on Windows.  There is no easy way to differentiate between\n  ** the final two cases; therefore, we return the safer return value of TRUE\n  ** so that callers of this function will simply use it verbatim.\n  */\n  if ( winIsDirSep(zPathname[0]) ){\n    return TRUE;\n  }\n\n  /*\n  ** If the path name starts with a letter and a colon it is either a volume\n  ** relative path or an absolute path.  Callers of this function must not\n  ** attempt to treat it as a relative path name (i.e. they should simply use\n  ** it verbatim).\n  */\n  if ( winIsDriveLetterAndColon(zPathname) ){\n    return TRUE;\n  }\n\n  /*\n  ** If we get to this point, the path name should almost certainly be a purely\n  ** relative one (i.e. not a UNC name, not absolute, and not volume relative).\n  */\n  return FALSE;\n}\n\n/*\n** Turn a relative pathname into a full pathname.  Write the full\n** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname\n** bytes in size.\n*/\nstatic int winFullPathname(\n  sqlite3_vfs *pVfs,            /* Pointer to vfs object */\n  const char *zRelative,        /* Possibly relative input path */\n  int nFull,                    /* Size of output buffer in bytes */\n  char *zFull                   /* Output buffer */\n){\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)\n  DWORD nByte;\n  void *zConverted;\n  char *zOut;\n#endif\n\n  /* If this path name begins with \"/X:\" or \"\\\\?\\\", where \"X\" is any\n  ** alphabetic character, discard the initial \"/\" from the pathname.\n  */\n  if( zRelative[0]=='/' && (winIsDriveLetterAndColon(zRelative+1)\n       || winIsLongPathPrefix(zRelative+1)) ){\n    zRelative++;\n  }\n\n#if defined(__CYGWIN__)\n  SimulateIOError( return SQLITE_ERROR );\n  UNUSED_PARAMETER(nFull);\n  assert( nFull>=pVfs->mxPathname );\n  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){\n    /*\n    ** NOTE: We are dealing with a relative path name and the data\n    **       directory has been set.  Therefore, use it as the basis\n    **       for converting the relative path name to an absolute\n    **       one by prepending the data directory and a slash.\n    */\n    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );\n    if( !zOut ){\n      return SQLITE_IOERR_NOMEM_BKPT;\n    }\n    if( cygwin_conv_path(\n            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |\n            CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){\n      sqlite3_free(zOut);\n      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,\n                         \"winFullPathname1\", zRelative);\n    }else{\n      char *zUtf8 = winConvertToUtf8Filename(zOut);\n      if( !zUtf8 ){\n        sqlite3_free(zOut);\n        return SQLITE_IOERR_NOMEM_BKPT;\n      }\n      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, \"%s%c%s\",\n                       sqlite3_data_directory, winGetDirSep(), zUtf8);\n      sqlite3_free(zUtf8);\n      sqlite3_free(zOut);\n    }\n  }else{\n    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );\n    if( !zOut ){\n      return SQLITE_IOERR_NOMEM_BKPT;\n    }\n    if( cygwin_conv_path(\n            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),\n            zRelative, zOut, pVfs->mxPathname+1)<0 ){\n      sqlite3_free(zOut);\n      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,\n                         \"winFullPathname2\", zRelative);\n    }else{\n      char *zUtf8 = winConvertToUtf8Filename(zOut);\n      if( !zUtf8 ){\n        sqlite3_free(zOut);\n        return SQLITE_IOERR_NOMEM_BKPT;\n      }\n      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, \"%s\", zUtf8);\n      sqlite3_free(zUtf8);\n      sqlite3_free(zOut);\n    }\n  }\n  return SQLITE_OK;\n#endif\n\n#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)\n  SimulateIOError( return SQLITE_ERROR );\n  /* WinCE has no concept of a relative pathname, or so I am told. */\n  /* WinRT has no way to convert a relative path to an absolute one. */\n  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){\n    /*\n    ** NOTE: We are dealing with a relative path name and the data\n    **       directory has been set.  Therefore, use it as the basis\n    **       for converting the relative path name to an absolute\n    **       one by prepending the data directory and a backslash.\n    */\n    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, \"%s%c%s\",\n                     sqlite3_data_directory, winGetDirSep(), zRelative);\n  }else{\n    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, \"%s\", zRelative);\n  }\n  return SQLITE_OK;\n#endif\n\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)\n  /* It's odd to simulate an io-error here, but really this is just\n  ** using the io-error infrastructure to test that SQLite handles this\n  ** function failing. This function could fail if, for example, the\n  ** current working directory has been unlinked.\n  */\n  SimulateIOError( return SQLITE_ERROR );\n  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){\n    /*\n    ** NOTE: We are dealing with a relative path name and the data\n    **       directory has been set.  Therefore, use it as the basis\n    **       for converting the relative path name to an absolute\n    **       one by prepending the data directory and a backslash.\n    */\n    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, \"%s%c%s\",\n                     sqlite3_data_directory, winGetDirSep(), zRelative);\n    return SQLITE_OK;\n  }\n  zConverted = winConvertFromUtf8Filename(zRelative);\n  if( zConverted==0 ){\n    return SQLITE_IOERR_NOMEM_BKPT;\n  }\n  if( osIsNT() ){\n    LPWSTR zTemp;\n    nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);\n    if( nByte==0 ){\n      sqlite3_free(zConverted);\n      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),\n                         \"winFullPathname1\", zRelative);\n    }\n    nByte += 3;\n    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );\n    if( zTemp==0 ){\n      sqlite3_free(zConverted);\n      return SQLITE_IOERR_NOMEM_BKPT;\n    }\n    nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);\n    if( nByte==0 ){\n      sqlite3_free(zConverted);\n      sqlite3_free(zTemp);\n      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),\n                         \"winFullPathname2\", zRelative);\n    }\n    sqlite3_free(zConverted);\n    zOut = winUnicodeToUtf8(zTemp);\n    sqlite3_free(zTemp);\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    char *zTemp;\n    nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);\n    if( nByte==0 ){\n      sqlite3_free(zConverted);\n      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),\n                         \"winFullPathname3\", zRelative);\n    }\n    nByte += 3;\n    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );\n    if( zTemp==0 ){\n      sqlite3_free(zConverted);\n      return SQLITE_IOERR_NOMEM_BKPT;\n    }\n    nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);\n    if( nByte==0 ){\n      sqlite3_free(zConverted);\n      sqlite3_free(zTemp);\n      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),\n                         \"winFullPathname4\", zRelative);\n    }\n    sqlite3_free(zConverted);\n    zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());\n    sqlite3_free(zTemp);\n  }\n#endif\n  if( zOut ){\n    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, \"%s\", zOut);\n    sqlite3_free(zOut);\n    return SQLITE_OK;\n  }else{\n    return SQLITE_IOERR_NOMEM_BKPT;\n  }\n#endif\n}\n\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\n/*\n** Interfaces for opening a shared library, finding entry points\n** within the shared library, and closing the shared library.\n*/\nstatic void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){\n  HANDLE h;\n#if defined(__CYGWIN__)\n  int nFull = pVfs->mxPathname+1;\n  char *zFull = sqlite3MallocZero( nFull );\n  void *zConverted = 0;\n  if( zFull==0 ){\n    OSTRACE((\"DLOPEN name=%s, handle=%p\\n\", zFilename, (void*)0));\n    return 0;\n  }\n  if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){\n    sqlite3_free(zFull);\n    OSTRACE((\"DLOPEN name=%s, handle=%p\\n\", zFilename, (void*)0));\n    return 0;\n  }\n  zConverted = winConvertFromUtf8Filename(zFull);\n  sqlite3_free(zFull);\n#else\n  void *zConverted = winConvertFromUtf8Filename(zFilename);\n  UNUSED_PARAMETER(pVfs);\n#endif\n  if( zConverted==0 ){\n    OSTRACE((\"DLOPEN name=%s, handle=%p\\n\", zFilename, (void*)0));\n    return 0;\n  }\n  if( osIsNT() ){\n#if SQLITE_OS_WINRT\n    h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);\n#else\n    h = osLoadLibraryW((LPCWSTR)zConverted);\n#endif\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    h = osLoadLibraryA((char*)zConverted);\n  }\n#endif\n  OSTRACE((\"DLOPEN name=%s, handle=%p\\n\", zFilename, (void*)h));\n  sqlite3_free(zConverted);\n  return (void*)h;\n}\nstatic void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){\n  UNUSED_PARAMETER(pVfs);\n  winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);\n}\nstatic void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){\n  FARPROC proc;\n  UNUSED_PARAMETER(pVfs);\n  proc = osGetProcAddressA((HANDLE)pH, zSym);\n  OSTRACE((\"DLSYM handle=%p, symbol=%s, address=%p\\n\",\n           (void*)pH, zSym, (void*)proc));\n  return (void(*)(void))proc;\n}\nstatic void winDlClose(sqlite3_vfs *pVfs, void *pHandle){\n  UNUSED_PARAMETER(pVfs);\n  osFreeLibrary((HANDLE)pHandle);\n  OSTRACE((\"DLCLOSE handle=%p\\n\", (void*)pHandle));\n}\n#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */\n  #define winDlOpen  0\n  #define winDlError 0\n  #define winDlSym   0\n  #define winDlClose 0\n#endif\n\n/* State information for the randomness gatherer. */\ntypedef struct EntropyGatherer EntropyGatherer;\nstruct EntropyGatherer {\n  unsigned char *a;   /* Gather entropy into this buffer */\n  int na;             /* Size of a[] in bytes */\n  int i;              /* XOR next input into a[i] */\n  int nXor;           /* Number of XOR operations done */\n};\n\n#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)\n/* Mix sz bytes of entropy into p. */\nstatic void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){\n  int j, k;\n  for(j=0, k=p->i; j<sz; j++){\n    p->a[k++] ^= x[j];\n    if( k>=p->na ) k = 0;\n  }\n  p->i = k;\n  p->nXor += sz;\n}\n#endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */\n\n/*\n** Write up to nBuf bytes of randomness into zBuf.\n*/\nstatic int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){\n#if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)\n  UNUSED_PARAMETER(pVfs);\n  memset(zBuf, 0, nBuf);\n  return nBuf;\n#else\n  EntropyGatherer e;\n  UNUSED_PARAMETER(pVfs);\n  memset(zBuf, 0, nBuf);\n  e.a = (unsigned char*)zBuf;\n  e.na = nBuf;\n  e.nXor = 0;\n  e.i = 0;\n  {\n    SYSTEMTIME x;\n    osGetSystemTime(&x);\n    xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));\n  }\n  {\n    DWORD pid = osGetCurrentProcessId();\n    xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));\n  }\n#if SQLITE_OS_WINRT\n  {\n    ULONGLONG cnt = osGetTickCount64();\n    xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));\n  }\n#else\n  {\n    DWORD cnt = osGetTickCount();\n    xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));\n  }\n#endif /* SQLITE_OS_WINRT */\n  {\n    LARGE_INTEGER i;\n    osQueryPerformanceCounter(&i);\n    xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));\n  }\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID\n  {\n    UUID id;\n    memset(&id, 0, sizeof(UUID));\n    osUuidCreate(&id);\n    xorMemory(&e, (unsigned char*)&id, sizeof(UUID));\n    memset(&id, 0, sizeof(UUID));\n    osUuidCreateSequential(&id);\n    xorMemory(&e, (unsigned char*)&id, sizeof(UUID));\n  }\n#endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */\n  return e.nXor>nBuf ? nBuf : e.nXor;\n#endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */\n}\n\n\n/*\n** Sleep for a little while.  Return the amount of time slept.\n*/\nstatic int winSleep(sqlite3_vfs *pVfs, int microsec){\n  sqlite3_win32_sleep((microsec+999)/1000);\n  UNUSED_PARAMETER(pVfs);\n  return ((microsec+999)/1000)*1000;\n}\n\n/*\n** The following variable, if set to a non-zero value, is interpreted as\n** the number of seconds since 1970 and is used to set the result of\n** sqlite3OsCurrentTime() during testing.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */\n#endif\n\n/*\n** Find the current time (in Universal Coordinated Time).  Write into *piNow\n** the current time and date as a Julian Day number times 86_400_000.  In\n** other words, write into *piNow the number of milliseconds since the Julian\n** epoch of noon in Greenwich on November 24, 4714 B.C according to the\n** proleptic Gregorian calendar.\n**\n** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date\n** cannot be found.\n*/\nstatic int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){\n  /* FILETIME structure is a 64-bit value representing the number of\n     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).\n  */\n  FILETIME ft;\n  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;\n#ifdef SQLITE_TEST\n  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;\n#endif\n  /* 2^32 - to avoid use of LL and warnings in gcc */\n  static const sqlite3_int64 max32BitValue =\n      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +\n      (sqlite3_int64)294967296;\n\n#if SQLITE_OS_WINCE\n  SYSTEMTIME time;\n  osGetSystemTime(&time);\n  /* if SystemTimeToFileTime() fails, it returns zero. */\n  if (!osSystemTimeToFileTime(&time,&ft)){\n    return SQLITE_ERROR;\n  }\n#else\n  osGetSystemTimeAsFileTime( &ft );\n#endif\n\n  *piNow = winFiletimeEpoch +\n            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +\n               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;\n\n#ifdef SQLITE_TEST\n  if( sqlite3_current_time ){\n    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;\n  }\n#endif\n  UNUSED_PARAMETER(pVfs);\n  return SQLITE_OK;\n}\n\n/*\n** Find the current time (in Universal Coordinated Time).  Write the\n** current time and date as a Julian Day number into *prNow and\n** return 0.  Return 1 if the time and date cannot be found.\n*/\nstatic int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){\n  int rc;\n  sqlite3_int64 i;\n  rc = winCurrentTimeInt64(pVfs, &i);\n  if( !rc ){\n    *prNow = i/86400000.0;\n  }\n  return rc;\n}\n\n/*\n** The idea is that this function works like a combination of\n** GetLastError() and FormatMessage() on Windows (or errno and\n** strerror_r() on Unix). After an error is returned by an OS\n** function, SQLite calls this function with zBuf pointing to\n** a buffer of nBuf bytes. The OS layer should populate the\n** buffer with a nul-terminated UTF-8 encoded error message\n** describing the last IO error to have occurred within the calling\n** thread.\n**\n** If the error message is too large for the supplied buffer,\n** it should be truncated. The return value of xGetLastError\n** is zero if the error message fits in the buffer, or non-zero\n** otherwise (if the message was truncated). If non-zero is returned,\n** then it is not necessary to include the nul-terminator character\n** in the output buffer.\n**\n** Not supplying an error message will have no adverse effect\n** on SQLite. It is fine to have an implementation that never\n** returns an error message:\n**\n**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){\n**     assert(zBuf[0]=='\\0');\n**     return 0;\n**   }\n**\n** However if an error message is supplied, it will be incorporated\n** by sqlite into the error message available to the user using\n** sqlite3_errmsg(), possibly making IO errors easier to debug.\n*/\nstatic int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){\n  DWORD e = osGetLastError();\n  UNUSED_PARAMETER(pVfs);\n  if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);\n  return e;\n}\n\n/*\n** Initialize and deinitialize the operating system interface.\n*/\nSQLITE_API int sqlite3_os_init(void){\n  static sqlite3_vfs winVfs = {\n    3,                     /* iVersion */\n    sizeof(winFile),       /* szOsFile */\n    SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */\n    0,                     /* pNext */\n    \"win32\",               /* zName */\n    &winAppData,           /* pAppData */\n    winOpen,               /* xOpen */\n    winDelete,             /* xDelete */\n    winAccess,             /* xAccess */\n    winFullPathname,       /* xFullPathname */\n    winDlOpen,             /* xDlOpen */\n    winDlError,            /* xDlError */\n    winDlSym,              /* xDlSym */\n    winDlClose,            /* xDlClose */\n    winRandomness,         /* xRandomness */\n    winSleep,              /* xSleep */\n    winCurrentTime,        /* xCurrentTime */\n    winGetLastError,       /* xGetLastError */\n    winCurrentTimeInt64,   /* xCurrentTimeInt64 */\n    winSetSystemCall,      /* xSetSystemCall */\n    winGetSystemCall,      /* xGetSystemCall */\n    winNextSystemCall,     /* xNextSystemCall */\n  };\n#if defined(SQLITE_WIN32_HAS_WIDE)\n  static sqlite3_vfs winLongPathVfs = {\n    3,                     /* iVersion */\n    sizeof(winFile),       /* szOsFile */\n    SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */\n    0,                     /* pNext */\n    \"win32-longpath\",      /* zName */\n    &winAppData,           /* pAppData */\n    winOpen,               /* xOpen */\n    winDelete,             /* xDelete */\n    winAccess,             /* xAccess */\n    winFullPathname,       /* xFullPathname */\n    winDlOpen,             /* xDlOpen */\n    winDlError,            /* xDlError */\n    winDlSym,              /* xDlSym */\n    winDlClose,            /* xDlClose */\n    winRandomness,         /* xRandomness */\n    winSleep,              /* xSleep */\n    winCurrentTime,        /* xCurrentTime */\n    winGetLastError,       /* xGetLastError */\n    winCurrentTimeInt64,   /* xCurrentTimeInt64 */\n    winSetSystemCall,      /* xSetSystemCall */\n    winGetSystemCall,      /* xGetSystemCall */\n    winNextSystemCall,     /* xNextSystemCall */\n  };\n#endif\n  static sqlite3_vfs winNolockVfs = {\n    3,                     /* iVersion */\n    sizeof(winFile),       /* szOsFile */\n    SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */\n    0,                     /* pNext */\n    \"win32-none\",          /* zName */\n    &winNolockAppData,     /* pAppData */\n    winOpen,               /* xOpen */\n    winDelete,             /* xDelete */\n    winAccess,             /* xAccess */\n    winFullPathname,       /* xFullPathname */\n    winDlOpen,             /* xDlOpen */\n    winDlError,            /* xDlError */\n    winDlSym,              /* xDlSym */\n    winDlClose,            /* xDlClose */\n    winRandomness,         /* xRandomness */\n    winSleep,              /* xSleep */\n    winCurrentTime,        /* xCurrentTime */\n    winGetLastError,       /* xGetLastError */\n    winCurrentTimeInt64,   /* xCurrentTimeInt64 */\n    winSetSystemCall,      /* xSetSystemCall */\n    winGetSystemCall,      /* xGetSystemCall */\n    winNextSystemCall,     /* xNextSystemCall */\n  };\n#if defined(SQLITE_WIN32_HAS_WIDE)\n  static sqlite3_vfs winLongPathNolockVfs = {\n    3,                     /* iVersion */\n    sizeof(winFile),       /* szOsFile */\n    SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */\n    0,                     /* pNext */\n    \"win32-longpath-none\", /* zName */\n    &winNolockAppData,     /* pAppData */\n    winOpen,               /* xOpen */\n    winDelete,             /* xDelete */\n    winAccess,             /* xAccess */\n    winFullPathname,       /* xFullPathname */\n    winDlOpen,             /* xDlOpen */\n    winDlError,            /* xDlError */\n    winDlSym,              /* xDlSym */\n    winDlClose,            /* xDlClose */\n    winRandomness,         /* xRandomness */\n    winSleep,              /* xSleep */\n    winCurrentTime,        /* xCurrentTime */\n    winGetLastError,       /* xGetLastError */\n    winCurrentTimeInt64,   /* xCurrentTimeInt64 */\n    winSetSystemCall,      /* xSetSystemCall */\n    winGetSystemCall,      /* xGetSystemCall */\n    winNextSystemCall,     /* xNextSystemCall */\n  };\n#endif\n\n  /* Double-check that the aSyscall[] array has been constructed\n  ** correctly.  See ticket [bb3a86e890c8e96ab] */\n  assert( ArraySize(aSyscall)==80 );\n\n  /* get memory map allocation granularity */\n  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));\n#if SQLITE_OS_WINRT\n  osGetNativeSystemInfo(&winSysInfo);\n#else\n  osGetSystemInfo(&winSysInfo);\n#endif\n  assert( winSysInfo.dwAllocationGranularity>0 );\n  assert( winSysInfo.dwPageSize>0 );\n\n  sqlite3_vfs_register(&winVfs, 1);\n\n#if defined(SQLITE_WIN32_HAS_WIDE)\n  sqlite3_vfs_register(&winLongPathVfs, 0);\n#endif\n\n  sqlite3_vfs_register(&winNolockVfs, 0);\n\n#if defined(SQLITE_WIN32_HAS_WIDE)\n  sqlite3_vfs_register(&winLongPathNolockVfs, 0);\n#endif\n\n#ifndef SQLITE_OMIT_WAL\n  winBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);\n#endif\n\n  return SQLITE_OK;\n}\n\nSQLITE_API int sqlite3_os_end(void){\n#if SQLITE_OS_WINRT\n  if( sleepObj!=NULL ){\n    osCloseHandle(sleepObj);\n    sleepObj = NULL;\n  }\n#endif\n\n#ifndef SQLITE_OMIT_WAL\n  winBigLock = 0;\n#endif\n\n  return SQLITE_OK;\n}\n\n#endif /* SQLITE_OS_WIN */\n\n/************** End of os_win.c **********************************************/\n/************** Begin file memdb.c *******************************************/\n/*\n** 2016-09-07\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file implements an in-memory VFS. A database is held as a contiguous\n** block of memory.\n**\n** This file also implements interface sqlite3_serialize() and\n** sqlite3_deserialize().\n*/\n/* #include \"sqliteInt.h\" */\n#ifdef SQLITE_ENABLE_DESERIALIZE\n\n/*\n** Forward declaration of objects used by this utility\n*/\ntypedef struct sqlite3_vfs MemVfs;\ntypedef struct MemFile MemFile;\n\n/* Access to a lower-level VFS that (might) implement dynamic loading,\n** access to randomness, etc.\n*/\n#define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))\n\n/* An open file */\nstruct MemFile {\n  sqlite3_file base;              /* IO methods */\n  sqlite3_int64 sz;               /* Size of the file */\n  sqlite3_int64 szAlloc;          /* Space allocated to aData */\n  sqlite3_int64 szMax;            /* Maximum allowed size of the file */\n  unsigned char *aData;           /* content of the file */\n  int nMmap;                      /* Number of memory mapped pages */\n  unsigned mFlags;                /* Flags */\n  int eLock;                      /* Most recent lock against this file */\n};\n\n/*\n** Methods for MemFile\n*/\nstatic int memdbClose(sqlite3_file*);\nstatic int memdbRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);\nstatic int memdbWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);\nstatic int memdbTruncate(sqlite3_file*, sqlite3_int64 size);\nstatic int memdbSync(sqlite3_file*, int flags);\nstatic int memdbFileSize(sqlite3_file*, sqlite3_int64 *pSize);\nstatic int memdbLock(sqlite3_file*, int);\n/* static int memdbCheckReservedLock(sqlite3_file*, int *pResOut);// not used */\nstatic int memdbFileControl(sqlite3_file*, int op, void *pArg);\n/* static int memdbSectorSize(sqlite3_file*); // not used */\nstatic int memdbDeviceCharacteristics(sqlite3_file*);\nstatic int memdbFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);\nstatic int memdbUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);\n\n/*\n** Methods for MemVfs\n*/\nstatic int memdbOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);\n/* static int memdbDelete(sqlite3_vfs*, const char *zName, int syncDir); */\nstatic int memdbAccess(sqlite3_vfs*, const char *zName, int flags, int *);\nstatic int memdbFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);\nstatic void *memdbDlOpen(sqlite3_vfs*, const char *zFilename);\nstatic void memdbDlError(sqlite3_vfs*, int nByte, char *zErrMsg);\nstatic void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);\nstatic void memdbDlClose(sqlite3_vfs*, void*);\nstatic int memdbRandomness(sqlite3_vfs*, int nByte, char *zOut);\nstatic int memdbSleep(sqlite3_vfs*, int microseconds);\n/* static int memdbCurrentTime(sqlite3_vfs*, double*); */\nstatic int memdbGetLastError(sqlite3_vfs*, int, char *);\nstatic int memdbCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);\n\nstatic sqlite3_vfs memdb_vfs = {\n  2,                           /* iVersion */\n  0,                           /* szOsFile (set when registered) */\n  1024,                        /* mxPathname */\n  0,                           /* pNext */\n  \"memdb\",                     /* zName */\n  0,                           /* pAppData (set when registered) */ \n  memdbOpen,                   /* xOpen */\n  0, /* memdbDelete, */        /* xDelete */\n  memdbAccess,                 /* xAccess */\n  memdbFullPathname,           /* xFullPathname */\n  memdbDlOpen,                 /* xDlOpen */\n  memdbDlError,                /* xDlError */\n  memdbDlSym,                  /* xDlSym */\n  memdbDlClose,                /* xDlClose */\n  memdbRandomness,             /* xRandomness */\n  memdbSleep,                  /* xSleep */\n  0, /* memdbCurrentTime, */   /* xCurrentTime */\n  memdbGetLastError,           /* xGetLastError */\n  memdbCurrentTimeInt64        /* xCurrentTimeInt64 */\n};\n\nstatic const sqlite3_io_methods memdb_io_methods = {\n  3,                              /* iVersion */\n  memdbClose,                      /* xClose */\n  memdbRead,                       /* xRead */\n  memdbWrite,                      /* xWrite */\n  memdbTruncate,                   /* xTruncate */\n  memdbSync,                       /* xSync */\n  memdbFileSize,                   /* xFileSize */\n  memdbLock,                       /* xLock */\n  memdbLock,                       /* xUnlock - same as xLock in this case */ \n  0, /* memdbCheckReservedLock, */ /* xCheckReservedLock */\n  memdbFileControl,                /* xFileControl */\n  0, /* memdbSectorSize,*/         /* xSectorSize */\n  memdbDeviceCharacteristics,      /* xDeviceCharacteristics */\n  0,                               /* xShmMap */\n  0,                               /* xShmLock */\n  0,                               /* xShmBarrier */\n  0,                               /* xShmUnmap */\n  memdbFetch,                      /* xFetch */\n  memdbUnfetch                     /* xUnfetch */\n};\n\n\n\n/*\n** Close an memdb-file.\n**\n** The pData pointer is owned by the application, so there is nothing\n** to free.\n*/\nstatic int memdbClose(sqlite3_file *pFile){\n  MemFile *p = (MemFile *)pFile;\n  if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ) sqlite3_free(p->aData);\n  return SQLITE_OK;\n}\n\n/*\n** Read data from an memdb-file.\n*/\nstatic int memdbRead(\n  sqlite3_file *pFile, \n  void *zBuf, \n  int iAmt, \n  sqlite_int64 iOfst\n){\n  MemFile *p = (MemFile *)pFile;\n  if( iOfst+iAmt>p->sz ){\n    memset(zBuf, 0, iAmt);\n    if( iOfst<p->sz ) memcpy(zBuf, p->aData+iOfst, p->sz - iOfst);\n    return SQLITE_IOERR_SHORT_READ;\n  }\n  memcpy(zBuf, p->aData+iOfst, iAmt);\n  return SQLITE_OK;\n}\n\n/*\n** Try to enlarge the memory allocation to hold at least sz bytes\n*/\nstatic int memdbEnlarge(MemFile *p, sqlite3_int64 newSz){\n  unsigned char *pNew;\n  if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)==0 || p->nMmap>0 ){\n    return SQLITE_FULL;\n  }\n  if( newSz>p->szMax ){\n    return SQLITE_FULL;\n  }\n  newSz *= 2;\n  if( newSz>p->szMax ) newSz = p->szMax;\n  pNew = sqlite3Realloc(p->aData, newSz);\n  if( pNew==0 ) return SQLITE_NOMEM;\n  p->aData = pNew;\n  p->szAlloc = newSz;\n  return SQLITE_OK;\n}\n\n/*\n** Write data to an memdb-file.\n*/\nstatic int memdbWrite(\n  sqlite3_file *pFile,\n  const void *z,\n  int iAmt,\n  sqlite_int64 iOfst\n){\n  MemFile *p = (MemFile *)pFile;\n  if( NEVER(p->mFlags & SQLITE_DESERIALIZE_READONLY) ) return SQLITE_READONLY;\n  if( iOfst+iAmt>p->sz ){\n    int rc;\n    if( iOfst+iAmt>p->szAlloc\n     && (rc = memdbEnlarge(p, iOfst+iAmt))!=SQLITE_OK\n    ){\n      return rc;\n    }\n    if( iOfst>p->sz ) memset(p->aData+p->sz, 0, iOfst-p->sz);\n    p->sz = iOfst+iAmt;\n  }\n  memcpy(p->aData+iOfst, z, iAmt);\n  return SQLITE_OK;\n}\n\n/*\n** Truncate an memdb-file.\n**\n** In rollback mode (which is always the case for memdb, as it does not\n** support WAL mode) the truncate() method is only used to reduce\n** the size of a file, never to increase the size.\n*/\nstatic int memdbTruncate(sqlite3_file *pFile, sqlite_int64 size){\n  MemFile *p = (MemFile *)pFile;\n  if( NEVER(size>p->sz) ) return SQLITE_FULL;\n  p->sz = size; \n  return SQLITE_OK;\n}\n\n/*\n** Sync an memdb-file.\n*/\nstatic int memdbSync(sqlite3_file *pFile, int flags){\n  return SQLITE_OK;\n}\n\n/*\n** Return the current file-size of an memdb-file.\n*/\nstatic int memdbFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){\n  MemFile *p = (MemFile *)pFile;\n  *pSize = p->sz;\n  return SQLITE_OK;\n}\n\n/*\n** Lock an memdb-file.\n*/\nstatic int memdbLock(sqlite3_file *pFile, int eLock){\n  MemFile *p = (MemFile *)pFile;\n  if( eLock>SQLITE_LOCK_SHARED \n   && (p->mFlags & SQLITE_DESERIALIZE_READONLY)!=0\n  ){\n    return SQLITE_READONLY;\n  }\n  p->eLock = eLock;\n  return SQLITE_OK;\n}\n\n#if 0 /* Never used because memdbAccess() always returns false */\n/*\n** Check if another file-handle holds a RESERVED lock on an memdb-file.\n*/\nstatic int memdbCheckReservedLock(sqlite3_file *pFile, int *pResOut){\n  *pResOut = 0;\n  return SQLITE_OK;\n}\n#endif\n\n/*\n** File control method. For custom operations on an memdb-file.\n*/\nstatic int memdbFileControl(sqlite3_file *pFile, int op, void *pArg){\n  MemFile *p = (MemFile *)pFile;\n  int rc = SQLITE_NOTFOUND;\n  if( op==SQLITE_FCNTL_VFSNAME ){\n    *(char**)pArg = sqlite3_mprintf(\"memdb(%p,%lld)\", p->aData, p->sz);\n    rc = SQLITE_OK;\n  }\n  if( op==SQLITE_FCNTL_SIZE_LIMIT ){\n    sqlite3_int64 iLimit = *(sqlite3_int64*)pArg;\n    if( iLimit<p->sz ){\n      if( iLimit<0 ){\n        iLimit = p->szMax;\n      }else{\n        iLimit = p->sz;\n      }\n    }\n    p->szMax = iLimit;\n    *(sqlite3_int64*)pArg = iLimit;\n    rc = SQLITE_OK;\n  }\n  return rc;\n}\n\n#if 0  /* Not used because of SQLITE_IOCAP_POWERSAFE_OVERWRITE */\n/*\n** Return the sector-size in bytes for an memdb-file.\n*/\nstatic int memdbSectorSize(sqlite3_file *pFile){\n  return 1024;\n}\n#endif\n\n/*\n** Return the device characteristic flags supported by an memdb-file.\n*/\nstatic int memdbDeviceCharacteristics(sqlite3_file *pFile){\n  return SQLITE_IOCAP_ATOMIC | \n         SQLITE_IOCAP_POWERSAFE_OVERWRITE |\n         SQLITE_IOCAP_SAFE_APPEND |\n         SQLITE_IOCAP_SEQUENTIAL;\n}\n\n/* Fetch a page of a memory-mapped file */\nstatic int memdbFetch(\n  sqlite3_file *pFile,\n  sqlite3_int64 iOfst,\n  int iAmt,\n  void **pp\n){\n  MemFile *p = (MemFile *)pFile;\n  if( iOfst+iAmt>p->sz ){\n    *pp = 0;\n  }else{\n    p->nMmap++;\n    *pp = (void*)(p->aData + iOfst);\n  }\n  return SQLITE_OK;\n}\n\n/* Release a memory-mapped page */\nstatic int memdbUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){\n  MemFile *p = (MemFile *)pFile;\n  p->nMmap--;\n  return SQLITE_OK;\n}\n\n/*\n** Open an mem file handle.\n*/\nstatic int memdbOpen(\n  sqlite3_vfs *pVfs,\n  const char *zName,\n  sqlite3_file *pFile,\n  int flags,\n  int *pOutFlags\n){\n  MemFile *p = (MemFile*)pFile;\n  if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){\n    return ORIGVFS(pVfs)->xOpen(ORIGVFS(pVfs), zName, pFile, flags, pOutFlags);\n  }\n  memset(p, 0, sizeof(*p));\n  p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE;\n  assert( pOutFlags!=0 );  /* True because flags==SQLITE_OPEN_MAIN_DB */\n  *pOutFlags = flags | SQLITE_OPEN_MEMORY;\n  p->base.pMethods = &memdb_io_methods;\n  p->szMax = sqlite3GlobalConfig.mxMemdbSize;\n  return SQLITE_OK;\n}\n\n#if 0 /* Only used to delete rollback journals, master journals, and WAL\n      ** files, none of which exist in memdb.  So this routine is never used */\n/*\n** Delete the file located at zPath. If the dirSync argument is true,\n** ensure the file-system modifications are synced to disk before\n** returning.\n*/\nstatic int memdbDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){\n  return SQLITE_IOERR_DELETE;\n}\n#endif\n\n/*\n** Test for access permissions. Return true if the requested permission\n** is available, or false otherwise.\n**\n** With memdb, no files ever exist on disk.  So always return false.\n*/\nstatic int memdbAccess(\n  sqlite3_vfs *pVfs, \n  const char *zPath, \n  int flags, \n  int *pResOut\n){\n  *pResOut = 0;\n  return SQLITE_OK;\n}\n\n/*\n** Populate buffer zOut with the full canonical pathname corresponding\n** to the pathname in zPath. zOut is guaranteed to point to a buffer\n** of at least (INST_MAX_PATHNAME+1) bytes.\n*/\nstatic int memdbFullPathname(\n  sqlite3_vfs *pVfs, \n  const char *zPath, \n  int nOut, \n  char *zOut\n){\n  sqlite3_snprintf(nOut, zOut, \"%s\", zPath);\n  return SQLITE_OK;\n}\n\n/*\n** Open the dynamic library located at zPath and return a handle.\n*/\nstatic void *memdbDlOpen(sqlite3_vfs *pVfs, const char *zPath){\n  return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);\n}\n\n/*\n** Populate the buffer zErrMsg (size nByte bytes) with a human readable\n** utf-8 string describing the most recent error encountered associated \n** with dynamic libraries.\n*/\nstatic void memdbDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){\n  ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);\n}\n\n/*\n** Return a pointer to the symbol zSymbol in the dynamic library pHandle.\n*/\nstatic void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){\n  return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);\n}\n\n/*\n** Close the dynamic library handle pHandle.\n*/\nstatic void memdbDlClose(sqlite3_vfs *pVfs, void *pHandle){\n  ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);\n}\n\n/*\n** Populate the buffer pointed to by zBufOut with nByte bytes of \n** random data.\n*/\nstatic int memdbRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){\n  return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);\n}\n\n/*\n** Sleep for nMicro microseconds. Return the number of microseconds \n** actually slept.\n*/\nstatic int memdbSleep(sqlite3_vfs *pVfs, int nMicro){\n  return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);\n}\n\n#if 0  /* Never used.  Modern cores only call xCurrentTimeInt64() */\n/*\n** Return the current time as a Julian Day number in *pTimeOut.\n*/\nstatic int memdbCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){\n  return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);\n}\n#endif\n\nstatic int memdbGetLastError(sqlite3_vfs *pVfs, int a, char *b){\n  return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);\n}\nstatic int memdbCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){\n  return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);\n}\n\n/*\n** Translate a database connection pointer and schema name into a\n** MemFile pointer.\n*/\nstatic MemFile *memdbFromDbSchema(sqlite3 *db, const char *zSchema){\n  MemFile *p = 0;\n  int rc = sqlite3_file_control(db, zSchema, SQLITE_FCNTL_FILE_POINTER, &p);\n  if( rc ) return 0;\n  if( p->base.pMethods!=&memdb_io_methods ) return 0;\n  return p;\n}\n\n/*\n** Return the serialization of a database\n*/\nSQLITE_API unsigned char *sqlite3_serialize(\n  sqlite3 *db,              /* The database connection */\n  const char *zSchema,      /* Which database within the connection */\n  sqlite3_int64 *piSize,    /* Write size here, if not NULL */\n  unsigned int mFlags       /* Maybe SQLITE_SERIALIZE_NOCOPY */\n){\n  MemFile *p;\n  int iDb;\n  Btree *pBt;\n  sqlite3_int64 sz;\n  int szPage = 0;\n  sqlite3_stmt *pStmt = 0;\n  unsigned char *pOut;\n  char *zSql;\n  int rc;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n\n  if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;\n  p = memdbFromDbSchema(db, zSchema);\n  iDb = sqlite3FindDbName(db, zSchema);\n  if( piSize ) *piSize = -1;\n  if( iDb<0 ) return 0;\n  if( p ){\n    if( piSize ) *piSize = p->sz;\n    if( mFlags & SQLITE_SERIALIZE_NOCOPY ){\n      pOut = p->aData;\n    }else{\n      pOut = sqlite3_malloc64( p->sz );\n      if( pOut ) memcpy(pOut, p->aData, p->sz);\n    }\n    return pOut;\n  }\n  pBt = db->aDb[iDb].pBt;\n  if( pBt==0 ) return 0;\n  szPage = sqlite3BtreeGetPageSize(pBt);\n  zSql = sqlite3_mprintf(\"PRAGMA \\\"%w\\\".page_count\", zSchema);\n  rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM;\n  sqlite3_free(zSql);\n  if( rc ) return 0;\n  rc = sqlite3_step(pStmt);\n  if( rc!=SQLITE_ROW ){\n    pOut = 0;\n  }else{\n    sz = sqlite3_column_int64(pStmt, 0)*szPage;\n    if( piSize ) *piSize = sz;\n    if( mFlags & SQLITE_SERIALIZE_NOCOPY ){\n      pOut = 0;\n    }else{\n      pOut = sqlite3_malloc64( sz );\n      if( pOut ){\n        int nPage = sqlite3_column_int(pStmt, 0);\n        Pager *pPager = sqlite3BtreePager(pBt);\n        int pgno;\n        for(pgno=1; pgno<=nPage; pgno++){\n          DbPage *pPage = 0;\n          unsigned char *pTo = pOut + szPage*(sqlite3_int64)(pgno-1);\n          rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pPage, 0);\n          if( rc==SQLITE_OK ){\n            memcpy(pTo, sqlite3PagerGetData(pPage), szPage);\n          }else{\n            memset(pTo, 0, szPage);\n          }\n          sqlite3PagerUnref(pPage);       \n        }\n      }\n    }\n  }\n  sqlite3_finalize(pStmt);\n  return pOut;\n}\n\n/* Convert zSchema to a MemDB and initialize its content.\n*/\nSQLITE_API int sqlite3_deserialize(\n  sqlite3 *db,            /* The database connection */\n  const char *zSchema,    /* Which DB to reopen with the deserialization */\n  unsigned char *pData,   /* The serialized database content */\n  sqlite3_int64 szDb,     /* Number bytes in the deserialization */\n  sqlite3_int64 szBuf,    /* Total size of buffer pData[] */\n  unsigned mFlags         /* Zero or more SQLITE_DESERIALIZE_* flags */\n){\n  MemFile *p;\n  char *zSql;\n  sqlite3_stmt *pStmt = 0;\n  int rc;\n  int iDb;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  if( szDb<0 ) return SQLITE_MISUSE_BKPT;\n  if( szBuf<0 ) return SQLITE_MISUSE_BKPT;\n#endif\n\n  sqlite3_mutex_enter(db->mutex);\n  if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;\n  iDb = sqlite3FindDbName(db, zSchema);\n  if( iDb<0 ){\n    rc = SQLITE_ERROR;\n    goto end_deserialize;\n  }    \n  zSql = sqlite3_mprintf(\"ATTACH x AS %Q\", zSchema);\n  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);\n  sqlite3_free(zSql);\n  if( rc ) goto end_deserialize;\n  db->init.iDb = (u8)iDb;\n  db->init.reopenMemdb = 1;\n  rc = sqlite3_step(pStmt);\n  db->init.reopenMemdb = 0;\n  if( rc!=SQLITE_DONE ){\n    rc = SQLITE_ERROR;\n    goto end_deserialize;\n  }\n  p = memdbFromDbSchema(db, zSchema);\n  if( p==0 ){\n    rc = SQLITE_ERROR;\n  }else{\n    p->aData = pData;\n    p->sz = szDb;\n    p->szAlloc = szBuf;\n    p->szMax = szBuf;\n    if( p->szMax<sqlite3GlobalConfig.mxMemdbSize ){\n      p->szMax = sqlite3GlobalConfig.mxMemdbSize;\n    }\n    p->mFlags = mFlags;\n    rc = SQLITE_OK;\n  }\n\nend_deserialize:\n  sqlite3_finalize(pStmt);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/* \n** This routine is called when the extension is loaded.\n** Register the new VFS.\n*/\nSQLITE_PRIVATE int sqlite3MemdbInit(void){\n  sqlite3_vfs *pLower = sqlite3_vfs_find(0);\n  int sz = pLower->szOsFile;\n  memdb_vfs.pAppData = pLower;\n  /* The following conditional can only be true when compiled for\n  ** Windows x86 and SQLITE_MAX_MMAP_SIZE=0.  We always leave\n  ** it in, to be safe, but it is marked as NO_TEST since there\n  ** is no way to reach it under most builds. */\n  if( sz<sizeof(MemFile) ) sz = sizeof(MemFile); /*NO_TEST*/\n  memdb_vfs.szOsFile = sz;\n  return sqlite3_vfs_register(&memdb_vfs, 0);\n}\n#endif /* SQLITE_ENABLE_DESERIALIZE */\n\n/************** End of memdb.c ***********************************************/\n/************** Begin file bitvec.c ******************************************/\n/*\n** 2008 February 16\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file implements an object that represents a fixed-length\n** bitmap.  Bits are numbered starting with 1.\n**\n** A bitmap is used to record which pages of a database file have been\n** journalled during a transaction, or which pages have the \"dont-write\"\n** property.  Usually only a few pages are meet either condition.\n** So the bitmap is usually sparse and has low cardinality.\n** But sometimes (for example when during a DROP of a large table) most\n** or all of the pages in a database can get journalled.  In those cases, \n** the bitmap becomes dense with high cardinality.  The algorithm needs \n** to handle both cases well.\n**\n** The size of the bitmap is fixed when the object is created.\n**\n** All bits are clear when the bitmap is created.  Individual bits\n** may be set or cleared one at a time.\n**\n** Test operations are about 100 times more common that set operations.\n** Clear operations are exceedingly rare.  There are usually between\n** 5 and 500 set operations per Bitvec object, though the number of sets can\n** sometimes grow into tens of thousands or larger.  The size of the\n** Bitvec object is the number of pages in the database file at the\n** start of a transaction, and is thus usually less than a few thousand,\n** but can be as large as 2 billion for a really big database.\n*/\n/* #include \"sqliteInt.h\" */\n\n/* Size of the Bitvec structure in bytes. */\n#define BITVEC_SZ        512\n\n/* Round the union size down to the nearest pointer boundary, since that's how \n** it will be aligned within the Bitvec struct. */\n#define BITVEC_USIZE \\\n    (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))\n\n/* Type of the array \"element\" for the bitmap representation. \n** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. \n** Setting this to the \"natural word\" size of your CPU may improve\n** performance. */\n#define BITVEC_TELEM     u8\n/* Size, in bits, of the bitmap element. */\n#define BITVEC_SZELEM    8\n/* Number of elements in a bitmap array. */\n#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))\n/* Number of bits in the bitmap array. */\n#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)\n\n/* Number of u32 values in hash table. */\n#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))\n/* Maximum number of entries in hash table before \n** sub-dividing and re-hashing. */\n#define BITVEC_MXHASH    (BITVEC_NINT/2)\n/* Hashing function for the aHash representation.\n** Empirical testing showed that the *37 multiplier \n** (an arbitrary prime)in the hash function provided \n** no fewer collisions than the no-op *1. */\n#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)\n\n#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))\n\n\n/*\n** A bitmap is an instance of the following structure.\n**\n** This bitmap records the existence of zero or more bits\n** with values between 1 and iSize, inclusive.\n**\n** There are three possible representations of the bitmap.\n** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight\n** bitmap.  The least significant bit is bit 1.\n**\n** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is\n** a hash table that will hold up to BITVEC_MXHASH distinct values.\n**\n** Otherwise, the value i is redirected into one of BITVEC_NPTR\n** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap\n** handles up to iDivisor separate values of i.  apSub[0] holds\n** values between 1 and iDivisor.  apSub[1] holds values between\n** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between\n** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized\n** to hold deal with values between 1 and iDivisor.\n*/\nstruct Bitvec {\n  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */\n  u32 nSet;       /* Number of bits that are set - only valid for aHash\n                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,\n                  ** this would be 125. */\n  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */\n                  /* Should >=0 for apSub element. */\n                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */\n                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */\n  union {\n    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */\n    u32 aHash[BITVEC_NINT];      /* Hash table representation */\n    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */\n  } u;\n};\n\n/*\n** Create a new bitmap object able to handle bits between 0 and iSize,\n** inclusive.  Return a pointer to the new object.  Return NULL if \n** malloc fails.\n*/\nSQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){\n  Bitvec *p;\n  assert( sizeof(*p)==BITVEC_SZ );\n  p = sqlite3MallocZero( sizeof(*p) );\n  if( p ){\n    p->iSize = iSize;\n  }\n  return p;\n}\n\n/*\n** Check to see if the i-th bit is set.  Return true or false.\n** If p is NULL (if the bitmap has not been created) or if\n** i is out of range, then return false.\n*/\nSQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){\n  assert( p!=0 );\n  i--;\n  if( i>=p->iSize ) return 0;\n  while( p->iDivisor ){\n    u32 bin = i/p->iDivisor;\n    i = i%p->iDivisor;\n    p = p->u.apSub[bin];\n    if (!p) {\n      return 0;\n    }\n  }\n  if( p->iSize<=BITVEC_NBIT ){\n    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;\n  } else{\n    u32 h = BITVEC_HASH(i++);\n    while( p->u.aHash[h] ){\n      if( p->u.aHash[h]==i ) return 1;\n      h = (h+1) % BITVEC_NINT;\n    }\n    return 0;\n  }\n}\nSQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){\n  return p!=0 && sqlite3BitvecTestNotNull(p,i);\n}\n\n/*\n** Set the i-th bit.  Return 0 on success and an error code if\n** anything goes wrong.\n**\n** This routine might cause sub-bitmaps to be allocated.  Failing\n** to get the memory needed to hold the sub-bitmap is the only\n** that can go wrong with an insert, assuming p and i are valid.\n**\n** The calling function must ensure that p is a valid Bitvec object\n** and that the value for \"i\" is within range of the Bitvec object.\n** Otherwise the behavior is undefined.\n*/\nSQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){\n  u32 h;\n  if( p==0 ) return SQLITE_OK;\n  assert( i>0 );\n  assert( i<=p->iSize );\n  i--;\n  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {\n    u32 bin = i/p->iDivisor;\n    i = i%p->iDivisor;\n    if( p->u.apSub[bin]==0 ){\n      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );\n      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;\n    }\n    p = p->u.apSub[bin];\n  }\n  if( p->iSize<=BITVEC_NBIT ){\n    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));\n    return SQLITE_OK;\n  }\n  h = BITVEC_HASH(i++);\n  /* if there wasn't a hash collision, and this doesn't */\n  /* completely fill the hash, then just add it without */\n  /* worring about sub-dividing and re-hashing. */\n  if( !p->u.aHash[h] ){\n    if (p->nSet<(BITVEC_NINT-1)) {\n      goto bitvec_set_end;\n    } else {\n      goto bitvec_set_rehash;\n    }\n  }\n  /* there was a collision, check to see if it's already */\n  /* in hash, if not, try to find a spot for it */\n  do {\n    if( p->u.aHash[h]==i ) return SQLITE_OK;\n    h++;\n    if( h>=BITVEC_NINT ) h = 0;\n  } while( p->u.aHash[h] );\n  /* we didn't find it in the hash.  h points to the first */\n  /* available free spot. check to see if this is going to */\n  /* make our hash too \"full\".  */\nbitvec_set_rehash:\n  if( p->nSet>=BITVEC_MXHASH ){\n    unsigned int j;\n    int rc;\n    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));\n    if( aiValues==0 ){\n      return SQLITE_NOMEM_BKPT;\n    }else{\n      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));\n      memset(p->u.apSub, 0, sizeof(p->u.apSub));\n      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;\n      rc = sqlite3BitvecSet(p, i);\n      for(j=0; j<BITVEC_NINT; j++){\n        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);\n      }\n      sqlite3StackFree(0, aiValues);\n      return rc;\n    }\n  }\nbitvec_set_end:\n  p->nSet++;\n  p->u.aHash[h] = i;\n  return SQLITE_OK;\n}\n\n/*\n** Clear the i-th bit.\n**\n** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage\n** that BitvecClear can use to rebuilt its hash table.\n*/\nSQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){\n  if( p==0 ) return;\n  assert( i>0 );\n  i--;\n  while( p->iDivisor ){\n    u32 bin = i/p->iDivisor;\n    i = i%p->iDivisor;\n    p = p->u.apSub[bin];\n    if (!p) {\n      return;\n    }\n  }\n  if( p->iSize<=BITVEC_NBIT ){\n    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));\n  }else{\n    unsigned int j;\n    u32 *aiValues = pBuf;\n    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));\n    memset(p->u.aHash, 0, sizeof(p->u.aHash));\n    p->nSet = 0;\n    for(j=0; j<BITVEC_NINT; j++){\n      if( aiValues[j] && aiValues[j]!=(i+1) ){\n        u32 h = BITVEC_HASH(aiValues[j]-1);\n        p->nSet++;\n        while( p->u.aHash[h] ){\n          h++;\n          if( h>=BITVEC_NINT ) h = 0;\n        }\n        p->u.aHash[h] = aiValues[j];\n      }\n    }\n  }\n}\n\n/*\n** Destroy a bitmap object.  Reclaim all memory used.\n*/\nSQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){\n  if( p==0 ) return;\n  if( p->iDivisor ){\n    unsigned int i;\n    for(i=0; i<BITVEC_NPTR; i++){\n      sqlite3BitvecDestroy(p->u.apSub[i]);\n    }\n  }\n  sqlite3_free(p);\n}\n\n/*\n** Return the value of the iSize parameter specified when Bitvec *p\n** was created.\n*/\nSQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){\n  return p->iSize;\n}\n\n#ifndef SQLITE_UNTESTABLE\n/*\n** Let V[] be an array of unsigned characters sufficient to hold\n** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.\n** Then the following macros can be used to set, clear, or test\n** individual bits within V.\n*/\n#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))\n#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))\n#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0\n\n/*\n** This routine runs an extensive test of the Bitvec code.\n**\n** The input is an array of integers that acts as a program\n** to test the Bitvec.  The integers are opcodes followed\n** by 0, 1, or 3 operands, depending on the opcode.  Another\n** opcode follows immediately after the last operand.\n**\n** There are 6 opcodes numbered from 0 through 5.  0 is the\n** \"halt\" opcode and causes the test to end.\n**\n**    0          Halt and return the number of errors\n**    1 N S X    Set N bits beginning with S and incrementing by X\n**    2 N S X    Clear N bits beginning with S and incrementing by X\n**    3 N        Set N randomly chosen bits\n**    4 N        Clear N randomly chosen bits\n**    5 N S X    Set N bits from S increment X in array only, not in bitvec\n**\n** The opcodes 1 through 4 perform set and clear operations are performed\n** on both a Bitvec object and on a linear array of bits obtained from malloc.\n** Opcode 5 works on the linear array only, not on the Bitvec.\n** Opcode 5 is used to deliberately induce a fault in order to\n** confirm that error detection works.\n**\n** At the conclusion of the test the linear array is compared\n** against the Bitvec object.  If there are any differences,\n** an error is returned.  If they are the same, zero is returned.\n**\n** If a memory allocation error occurs, return -1.\n*/\nSQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){\n  Bitvec *pBitvec = 0;\n  unsigned char *pV = 0;\n  int rc = -1;\n  int i, nx, pc, op;\n  void *pTmpSpace;\n\n  /* Allocate the Bitvec to be tested and a linear array of\n  ** bits to act as the reference */\n  pBitvec = sqlite3BitvecCreate( sz );\n  pV = sqlite3MallocZero( (sz+7)/8 + 1 );\n  pTmpSpace = sqlite3_malloc64(BITVEC_SZ);\n  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;\n\n  /* NULL pBitvec tests */\n  sqlite3BitvecSet(0, 1);\n  sqlite3BitvecClear(0, 1, pTmpSpace);\n\n  /* Run the program */\n  pc = 0;\n  while( (op = aOp[pc])!=0 ){\n    switch( op ){\n      case 1:\n      case 2:\n      case 5: {\n        nx = 4;\n        i = aOp[pc+2] - 1;\n        aOp[pc+2] += aOp[pc+3];\n        break;\n      }\n      case 3:\n      case 4: \n      default: {\n        nx = 2;\n        sqlite3_randomness(sizeof(i), &i);\n        break;\n      }\n    }\n    if( (--aOp[pc+1]) > 0 ) nx = 0;\n    pc += nx;\n    i = (i & 0x7fffffff)%sz;\n    if( (op & 1)!=0 ){\n      SETBIT(pV, (i+1));\n      if( op!=5 ){\n        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;\n      }\n    }else{\n      CLEARBIT(pV, (i+1));\n      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);\n    }\n  }\n\n  /* Test to make sure the linear array exactly matches the\n  ** Bitvec object.  Start with the assumption that they do\n  ** match (rc==0).  Change rc to non-zero if a discrepancy\n  ** is found.\n  */\n  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)\n          + sqlite3BitvecTest(pBitvec, 0)\n          + (sqlite3BitvecSize(pBitvec) - sz);\n  for(i=1; i<=sz; i++){\n    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){\n      rc = i;\n      break;\n    }\n  }\n\n  /* Free allocated structure */\nbitvec_end:\n  sqlite3_free(pTmpSpace);\n  sqlite3_free(pV);\n  sqlite3BitvecDestroy(pBitvec);\n  return rc;\n}\n#endif /* SQLITE_UNTESTABLE */\n\n/************** End of bitvec.c **********************************************/\n/************** Begin file pcache.c ******************************************/\n/*\n** 2008 August 05\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file implements that page cache.\n*/\n/* #include \"sqliteInt.h\" */\n\n/*\n** A complete page cache is an instance of this structure.  Every\n** entry in the cache holds a single page of the database file.  The\n** btree layer only operates on the cached copy of the database pages.\n**\n** A page cache entry is \"clean\" if it exactly matches what is currently\n** on disk.  A page is \"dirty\" if it has been modified and needs to be\n** persisted to disk.\n**\n** pDirty, pDirtyTail, pSynced:\n**   All dirty pages are linked into the doubly linked list using\n**   PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order\n**   such that p was added to the list more recently than p->pDirtyNext.\n**   PCache.pDirty points to the first (newest) element in the list and\n**   pDirtyTail to the last (oldest).\n**\n**   The PCache.pSynced variable is used to optimize searching for a dirty\n**   page to eject from the cache mid-transaction. It is better to eject\n**   a page that does not require a journal sync than one that does. \n**   Therefore, pSynced is maintained so that it *almost* always points\n**   to either the oldest page in the pDirty/pDirtyTail list that has a\n**   clear PGHDR_NEED_SYNC flag or to a page that is older than this one\n**   (so that the right page to eject can be found by following pDirtyPrev\n**   pointers).\n*/\nstruct PCache {\n  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */\n  PgHdr *pSynced;                     /* Last synced page in dirty page list */\n  int nRefSum;                        /* Sum of ref counts over all pages */\n  int szCache;                        /* Configured cache size */\n  int szSpill;                        /* Size before spilling occurs */\n  int szPage;                         /* Size of every page in this cache */\n  int szExtra;                        /* Size of extra space for each page */\n  u8 bPurgeable;                      /* True if pages are on backing store */\n  u8 eCreate;                         /* eCreate value for for xFetch() */\n  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */\n  void *pStress;                      /* Argument to xStress */\n  sqlite3_pcache *pCache;             /* Pluggable cache module */\n};\n\n/********************************** Test and Debug Logic **********************/\n/*\n** Debug tracing macros.  Enable by by changing the \"0\" to \"1\" and\n** recompiling.\n**\n** When sqlite3PcacheTrace is 1, single line trace messages are issued.\n** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries\n** is displayed for many operations, resulting in a lot of output.\n*/\n#if defined(SQLITE_DEBUG) && 0\n  int sqlite3PcacheTrace = 2;       /* 0: off  1: simple  2: cache dumps */\n  int sqlite3PcacheMxDump = 9999;   /* Max cache entries for pcacheDump() */\n# define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}\n  void pcacheDump(PCache *pCache){\n    int N;\n    int i, j;\n    sqlite3_pcache_page *pLower;\n    PgHdr *pPg;\n    unsigned char *a;\n  \n    if( sqlite3PcacheTrace<2 ) return;\n    if( pCache->pCache==0 ) return;\n    N = sqlite3PcachePagecount(pCache);\n    if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;\n    for(i=1; i<=N; i++){\n       pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);\n       if( pLower==0 ) continue;\n       pPg = (PgHdr*)pLower->pExtra;\n       printf(\"%3d: nRef %2d flgs %02x data \", i, pPg->nRef, pPg->flags);\n       a = (unsigned char *)pLower->pBuf;\n       for(j=0; j<12; j++) printf(\"%02x\", a[j]);\n       printf(\"\\n\");\n       if( pPg->pPage==0 ){\n         sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);\n       }\n    }\n  }\n  #else\n# define pcacheTrace(X)\n# define pcacheDump(X)\n#endif\n\n/*\n** Check invariants on a PgHdr entry.  Return true if everything is OK.\n** Return false if any invariant is violated.\n**\n** This routine is for use inside of assert() statements only.  For\n** example:\n**\n**          assert( sqlite3PcachePageSanity(pPg) );\n*/\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){\n  PCache *pCache;\n  assert( pPg!=0 );\n  assert( pPg->pgno>0 || pPg->pPager==0 );    /* Page number is 1 or more */\n  pCache = pPg->pCache;\n  assert( pCache!=0 );      /* Every page has an associated PCache */\n  if( pPg->flags & PGHDR_CLEAN ){\n    assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */\n    assert( pCache->pDirty!=pPg );          /* CLEAN pages not on dirty list */\n    assert( pCache->pDirtyTail!=pPg );\n  }\n  /* WRITEABLE pages must also be DIRTY */\n  if( pPg->flags & PGHDR_WRITEABLE ){\n    assert( pPg->flags & PGHDR_DIRTY );     /* WRITEABLE implies DIRTY */\n  }\n  /* NEED_SYNC can be set independently of WRITEABLE.  This can happen,\n  ** for example, when using the sqlite3PagerDontWrite() optimization:\n  **    (1)  Page X is journalled, and gets WRITEABLE and NEED_SEEK.\n  **    (2)  Page X moved to freelist, WRITEABLE is cleared\n  **    (3)  Page X reused, WRITEABLE is set again\n  ** If NEED_SYNC had been cleared in step 2, then it would not be reset\n  ** in step 3, and page might be written into the database without first\n  ** syncing the rollback journal, which might cause corruption on a power\n  ** loss.\n  **\n  ** Another example is when the database page size is smaller than the\n  ** disk sector size.  When any page of a sector is journalled, all pages\n  ** in that sector are marked NEED_SYNC even if they are still CLEAN, just\n  ** in case they are later modified, since all pages in the same sector\n  ** must be journalled and synced before any of those pages can be safely\n  ** written.\n  */\n  return 1;\n}\n#endif /* SQLITE_DEBUG */\n\n\n/********************************** Linked List Management ********************/\n\n/* Allowed values for second argument to pcacheManageDirtyList() */\n#define PCACHE_DIRTYLIST_REMOVE   1    /* Remove pPage from dirty list */\n#define PCACHE_DIRTYLIST_ADD      2    /* Add pPage to the dirty list */\n#define PCACHE_DIRTYLIST_FRONT    3    /* Move pPage to the front of the list */\n\n/*\n** Manage pPage's participation on the dirty list.  Bits of the addRemove\n** argument determines what operation to do.  The 0x01 bit means first\n** remove pPage from the dirty list.  The 0x02 means add pPage back to\n** the dirty list.  Doing both moves pPage to the front of the dirty list.\n*/\nstatic void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){\n  PCache *p = pPage->pCache;\n\n  pcacheTrace((\"%p.DIRTYLIST.%s %d\\n\", p,\n                addRemove==1 ? \"REMOVE\" : addRemove==2 ? \"ADD\" : \"FRONT\",\n                pPage->pgno));\n  if( addRemove & PCACHE_DIRTYLIST_REMOVE ){\n    assert( pPage->pDirtyNext || pPage==p->pDirtyTail );\n    assert( pPage->pDirtyPrev || pPage==p->pDirty );\n  \n    /* Update the PCache1.pSynced variable if necessary. */\n    if( p->pSynced==pPage ){\n      p->pSynced = pPage->pDirtyPrev;\n    }\n  \n    if( pPage->pDirtyNext ){\n      pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;\n    }else{\n      assert( pPage==p->pDirtyTail );\n      p->pDirtyTail = pPage->pDirtyPrev;\n    }\n    if( pPage->pDirtyPrev ){\n      pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;\n    }else{\n      /* If there are now no dirty pages in the cache, set eCreate to 2. \n      ** This is an optimization that allows sqlite3PcacheFetch() to skip\n      ** searching for a dirty page to eject from the cache when it might\n      ** otherwise have to.  */\n      assert( pPage==p->pDirty );\n      p->pDirty = pPage->pDirtyNext;\n      assert( p->bPurgeable || p->eCreate==2 );\n      if( p->pDirty==0 ){         /*OPTIMIZATION-IF-TRUE*/\n        assert( p->bPurgeable==0 || p->eCreate==1 );\n        p->eCreate = 2;\n      }\n    }\n  }\n  if( addRemove & PCACHE_DIRTYLIST_ADD ){\n    pPage->pDirtyPrev = 0;\n    pPage->pDirtyNext = p->pDirty;\n    if( pPage->pDirtyNext ){\n      assert( pPage->pDirtyNext->pDirtyPrev==0 );\n      pPage->pDirtyNext->pDirtyPrev = pPage;\n    }else{\n      p->pDirtyTail = pPage;\n      if( p->bPurgeable ){\n        assert( p->eCreate==2 );\n        p->eCreate = 1;\n      }\n    }\n    p->pDirty = pPage;\n\n    /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set\n    ** pSynced to point to it. Checking the NEED_SYNC flag is an \n    ** optimization, as if pSynced points to a page with the NEED_SYNC\n    ** flag set sqlite3PcacheFetchStress() searches through all newer \n    ** entries of the dirty-list for a page with NEED_SYNC clear anyway.  */\n    if( !p->pSynced \n     && 0==(pPage->flags&PGHDR_NEED_SYNC)   /*OPTIMIZATION-IF-FALSE*/\n    ){\n      p->pSynced = pPage;\n    }\n  }\n  pcacheDump(p);\n}\n\n/*\n** Wrapper around the pluggable caches xUnpin method. If the cache is\n** being used for an in-memory database, this function is a no-op.\n*/\nstatic void pcacheUnpin(PgHdr *p){\n  if( p->pCache->bPurgeable ){\n    pcacheTrace((\"%p.UNPIN %d\\n\", p->pCache, p->pgno));\n    sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);\n    pcacheDump(p->pCache);\n  }\n}\n\n/*\n** Compute the number of pages of cache requested.   p->szCache is the\n** cache size requested by the \"PRAGMA cache_size\" statement.\n*/\nstatic int numberOfCachePages(PCache *p){\n  if( p->szCache>=0 ){\n    /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the\n    ** suggested cache size is set to N. */\n    return p->szCache;\n  }else{\n    /* IMPLEMANTATION-OF: R-59858-46238 If the argument N is negative, then the\n    ** number of cache pages is adjusted to be a number of pages that would\n    ** use approximately abs(N*1024) bytes of memory based on the current\n    ** page size. */\n    return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));\n  }\n}\n\n/*************************************************** General Interfaces ******\n**\n** Initialize and shutdown the page cache subsystem. Neither of these \n** functions are threadsafe.\n*/\nSQLITE_PRIVATE int sqlite3PcacheInitialize(void){\n  if( sqlite3GlobalConfig.pcache2.xInit==0 ){\n    /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the\n    ** built-in default page cache is used instead of the application defined\n    ** page cache. */\n    sqlite3PCacheSetDefault();\n    assert( sqlite3GlobalConfig.pcache2.xInit!=0 );\n  }\n  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);\n}\nSQLITE_PRIVATE void sqlite3PcacheShutdown(void){\n  if( sqlite3GlobalConfig.pcache2.xShutdown ){\n    /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */\n    sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);\n  }\n}\n\n/*\n** Return the size in bytes of a PCache object.\n*/\nSQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }\n\n/*\n** Create a new PCache object. Storage space to hold the object\n** has already been allocated and is passed in as the p pointer. \n** The caller discovers how much space needs to be allocated by \n** calling sqlite3PcacheSize().\n**\n** szExtra is some extra space allocated for each page.  The first\n** 8 bytes of the extra space will be zeroed as the page is allocated,\n** but remaining content will be uninitialized.  Though it is opaque\n** to this module, the extra space really ends up being the MemPage\n** structure in the pager.\n*/\nSQLITE_PRIVATE int sqlite3PcacheOpen(\n  int szPage,                  /* Size of every page */\n  int szExtra,                 /* Extra space associated with each page */\n  int bPurgeable,              /* True if pages are on backing store */\n  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */\n  void *pStress,               /* Argument to xStress */\n  PCache *p                    /* Preallocated space for the PCache */\n){\n  memset(p, 0, sizeof(PCache));\n  p->szPage = 1;\n  p->szExtra = szExtra;\n  assert( szExtra>=8 );  /* First 8 bytes will be zeroed */\n  p->bPurgeable = bPurgeable;\n  p->eCreate = 2;\n  p->xStress = xStress;\n  p->pStress = pStress;\n  p->szCache = 100;\n  p->szSpill = 1;\n  pcacheTrace((\"%p.OPEN szPage %d bPurgeable %d\\n\",p,szPage,bPurgeable));\n  return sqlite3PcacheSetPageSize(p, szPage);\n}\n\n/*\n** Change the page size for PCache object. The caller must ensure that there\n** are no outstanding page references when this function is called.\n*/\nSQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){\n  assert( pCache->nRefSum==0 && pCache->pDirty==0 );\n  if( pCache->szPage ){\n    sqlite3_pcache *pNew;\n    pNew = sqlite3GlobalConfig.pcache2.xCreate(\n                szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),\n                pCache->bPurgeable\n    );\n    if( pNew==0 ) return SQLITE_NOMEM_BKPT;\n    sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));\n    if( pCache->pCache ){\n      sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);\n    }\n    pCache->pCache = pNew;\n    pCache->szPage = szPage;\n    pcacheTrace((\"%p.PAGESIZE %d\\n\",pCache,szPage));\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Try to obtain a page from the cache.\n**\n** This routine returns a pointer to an sqlite3_pcache_page object if\n** such an object is already in cache, or if a new one is created.\n** This routine returns a NULL pointer if the object was not in cache\n** and could not be created.\n**\n** The createFlags should be 0 to check for existing pages and should\n** be 3 (not 1, but 3) to try to create a new page.\n**\n** If the createFlag is 0, then NULL is always returned if the page\n** is not already in the cache.  If createFlag is 1, then a new page\n** is created only if that can be done without spilling dirty pages\n** and without exceeding the cache size limit.\n**\n** The caller needs to invoke sqlite3PcacheFetchFinish() to properly\n** initialize the sqlite3_pcache_page object and convert it into a\n** PgHdr object.  The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()\n** routines are split this way for performance reasons. When separated\n** they can both (usually) operate without having to push values to\n** the stack on entry and pop them back off on exit, which saves a\n** lot of pushing and popping.\n*/\nSQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(\n  PCache *pCache,       /* Obtain the page from this cache */\n  Pgno pgno,            /* Page number to obtain */\n  int createFlag        /* If true, create page if it does not exist already */\n){\n  int eCreate;\n  sqlite3_pcache_page *pRes;\n\n  assert( pCache!=0 );\n  assert( pCache->pCache!=0 );\n  assert( createFlag==3 || createFlag==0 );\n  assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );\n\n  /* eCreate defines what to do if the page does not exist.\n  **    0     Do not allocate a new page.  (createFlag==0)\n  **    1     Allocate a new page if doing so is inexpensive.\n  **          (createFlag==1 AND bPurgeable AND pDirty)\n  **    2     Allocate a new page even it doing so is difficult.\n  **          (createFlag==1 AND !(bPurgeable AND pDirty)\n  */\n  eCreate = createFlag & pCache->eCreate;\n  assert( eCreate==0 || eCreate==1 || eCreate==2 );\n  assert( createFlag==0 || pCache->eCreate==eCreate );\n  assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );\n  pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);\n  pcacheTrace((\"%p.FETCH %d%s (result: %p)\\n\",pCache,pgno,\n               createFlag?\" create\":\"\",pRes));\n  return pRes;\n}\n\n/*\n** If the sqlite3PcacheFetch() routine is unable to allocate a new\n** page because no clean pages are available for reuse and the cache\n** size limit has been reached, then this routine can be invoked to \n** try harder to allocate a page.  This routine might invoke the stress\n** callback to spill dirty pages to the journal.  It will then try to\n** allocate the new page and will only fail to allocate a new page on\n** an OOM error.\n**\n** This routine should be invoked only after sqlite3PcacheFetch() fails.\n*/\nSQLITE_PRIVATE int sqlite3PcacheFetchStress(\n  PCache *pCache,                 /* Obtain the page from this cache */\n  Pgno pgno,                      /* Page number to obtain */\n  sqlite3_pcache_page **ppPage    /* Write result here */\n){\n  PgHdr *pPg;\n  if( pCache->eCreate==2 ) return 0;\n\n  if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){\n    /* Find a dirty page to write-out and recycle. First try to find a \n    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC\n    ** cleared), but if that is not possible settle for any other \n    ** unreferenced dirty page.\n    **\n    ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC\n    ** flag is currently referenced, then the following may leave pSynced\n    ** set incorrectly (pointing to other than the LRU page with NEED_SYNC\n    ** cleared). This is Ok, as pSynced is just an optimization.  */\n    for(pPg=pCache->pSynced; \n        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); \n        pPg=pPg->pDirtyPrev\n    );\n    pCache->pSynced = pPg;\n    if( !pPg ){\n      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);\n    }\n    if( pPg ){\n      int rc;\n#ifdef SQLITE_LOG_CACHE_SPILL\n      sqlite3_log(SQLITE_FULL, \n                  \"spill page %d making room for %d - cache used: %d/%d\",\n                  pPg->pgno, pgno,\n                  sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache),\n                numberOfCachePages(pCache));\n#endif\n      pcacheTrace((\"%p.SPILL %d\\n\",pCache,pPg->pgno));\n      rc = pCache->xStress(pCache->pStress, pPg);\n      pcacheDump(pCache);\n      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){\n        return rc;\n      }\n    }\n  }\n  *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);\n  return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;\n}\n\n/*\n** This is a helper routine for sqlite3PcacheFetchFinish()\n**\n** In the uncommon case where the page being fetched has not been\n** initialized, this routine is invoked to do the initialization.\n** This routine is broken out into a separate function since it\n** requires extra stack manipulation that can be avoided in the common\n** case.\n*/\nstatic SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(\n  PCache *pCache,             /* Obtain the page from this cache */\n  Pgno pgno,                  /* Page number obtained */\n  sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */\n){\n  PgHdr *pPgHdr;\n  assert( pPage!=0 );\n  pPgHdr = (PgHdr*)pPage->pExtra;\n  assert( pPgHdr->pPage==0 );\n  memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));\n  pPgHdr->pPage = pPage;\n  pPgHdr->pData = pPage->pBuf;\n  pPgHdr->pExtra = (void *)&pPgHdr[1];\n  memset(pPgHdr->pExtra, 0, 8);\n  pPgHdr->pCache = pCache;\n  pPgHdr->pgno = pgno;\n  pPgHdr->flags = PGHDR_CLEAN;\n  return sqlite3PcacheFetchFinish(pCache,pgno,pPage);\n}\n\n/*\n** This routine converts the sqlite3_pcache_page object returned by\n** sqlite3PcacheFetch() into an initialized PgHdr object.  This routine\n** must be called after sqlite3PcacheFetch() in order to get a usable\n** result.\n*/\nSQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(\n  PCache *pCache,             /* Obtain the page from this cache */\n  Pgno pgno,                  /* Page number obtained */\n  sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */\n){\n  PgHdr *pPgHdr;\n\n  assert( pPage!=0 );\n  pPgHdr = (PgHdr *)pPage->pExtra;\n\n  if( !pPgHdr->pPage ){\n    return pcacheFetchFinishWithInit(pCache, pgno, pPage);\n  }\n  pCache->nRefSum++;\n  pPgHdr->nRef++;\n  assert( sqlite3PcachePageSanity(pPgHdr) );\n  return pPgHdr;\n}\n\n/*\n** Decrement the reference count on a page. If the page is clean and the\n** reference count drops to 0, then it is made eligible for recycling.\n*/\nSQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){\n  assert( p->nRef>0 );\n  p->pCache->nRefSum--;\n  if( (--p->nRef)==0 ){\n    if( p->flags&PGHDR_CLEAN ){\n      pcacheUnpin(p);\n    }else{\n      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);\n    }\n  }\n}\n\n/*\n** Increase the reference count of a supplied page by 1.\n*/\nSQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){\n  assert(p->nRef>0);\n  assert( sqlite3PcachePageSanity(p) );\n  p->nRef++;\n  p->pCache->nRefSum++;\n}\n\n/*\n** Drop a page from the cache. There must be exactly one reference to the\n** page. This function deletes that reference, so after it returns the\n** page pointed to by p is invalid.\n*/\nSQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){\n  assert( p->nRef==1 );\n  assert( sqlite3PcachePageSanity(p) );\n  if( p->flags&PGHDR_DIRTY ){\n    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);\n  }\n  p->pCache->nRefSum--;\n  sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);\n}\n\n/*\n** Make sure the page is marked as dirty. If it isn't dirty already,\n** make it so.\n*/\nSQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){\n  assert( p->nRef>0 );\n  assert( sqlite3PcachePageSanity(p) );\n  if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){    /*OPTIMIZATION-IF-FALSE*/\n    p->flags &= ~PGHDR_DONT_WRITE;\n    if( p->flags & PGHDR_CLEAN ){\n      p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);\n      pcacheTrace((\"%p.DIRTY %d\\n\",p->pCache,p->pgno));\n      assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );\n      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);\n    }\n    assert( sqlite3PcachePageSanity(p) );\n  }\n}\n\n/*\n** Make sure the page is marked as clean. If it isn't clean already,\n** make it so.\n*/\nSQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){\n  assert( sqlite3PcachePageSanity(p) );\n  assert( (p->flags & PGHDR_DIRTY)!=0 );\n  assert( (p->flags & PGHDR_CLEAN)==0 );\n  pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);\n  p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);\n  p->flags |= PGHDR_CLEAN;\n  pcacheTrace((\"%p.CLEAN %d\\n\",p->pCache,p->pgno));\n  assert( sqlite3PcachePageSanity(p) );\n  if( p->nRef==0 ){\n    pcacheUnpin(p);\n  }\n}\n\n/*\n** Make every page in the cache clean.\n*/\nSQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){\n  PgHdr *p;\n  pcacheTrace((\"%p.CLEAN-ALL\\n\",pCache));\n  while( (p = pCache->pDirty)!=0 ){\n    sqlite3PcacheMakeClean(p);\n  }\n}\n\n/*\n** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.\n*/\nSQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){\n  PgHdr *p;\n  pcacheTrace((\"%p.CLEAR-WRITEABLE\\n\",pCache));\n  for(p=pCache->pDirty; p; p=p->pDirtyNext){\n    p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);\n  }\n  pCache->pSynced = pCache->pDirtyTail;\n}\n\n/*\n** Clear the PGHDR_NEED_SYNC flag from all dirty pages.\n*/\nSQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){\n  PgHdr *p;\n  for(p=pCache->pDirty; p; p=p->pDirtyNext){\n    p->flags &= ~PGHDR_NEED_SYNC;\n  }\n  pCache->pSynced = pCache->pDirtyTail;\n}\n\n/*\n** Change the page number of page p to newPgno. \n*/\nSQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){\n  PCache *pCache = p->pCache;\n  assert( p->nRef>0 );\n  assert( newPgno>0 );\n  assert( sqlite3PcachePageSanity(p) );\n  pcacheTrace((\"%p.MOVE %d -> %d\\n\",pCache,p->pgno,newPgno));\n  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);\n  p->pgno = newPgno;\n  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){\n    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);\n  }\n}\n\n/*\n** Drop every cache entry whose page number is greater than \"pgno\". The\n** caller must ensure that there are no outstanding references to any pages\n** other than page 1 with a page number greater than pgno.\n**\n** If there is a reference to page 1 and the pgno parameter passed to this\n** function is 0, then the data area associated with page 1 is zeroed, but\n** the page object is not dropped.\n*/\nSQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){\n  if( pCache->pCache ){\n    PgHdr *p;\n    PgHdr *pNext;\n    pcacheTrace((\"%p.TRUNCATE %d\\n\",pCache,pgno));\n    for(p=pCache->pDirty; p; p=pNext){\n      pNext = p->pDirtyNext;\n      /* This routine never gets call with a positive pgno except right\n      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,\n      ** it must be that pgno==0.\n      */\n      assert( p->pgno>0 );\n      if( p->pgno>pgno ){\n        assert( p->flags&PGHDR_DIRTY );\n        sqlite3PcacheMakeClean(p);\n      }\n    }\n    if( pgno==0 && pCache->nRefSum ){\n      sqlite3_pcache_page *pPage1;\n      pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);\n      if( ALWAYS(pPage1) ){  /* Page 1 is always available in cache, because\n                             ** pCache->nRefSum>0 */\n        memset(pPage1->pBuf, 0, pCache->szPage);\n        pgno = 1;\n      }\n    }\n    sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);\n  }\n}\n\n/*\n** Close a cache.\n*/\nSQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){\n  assert( pCache->pCache!=0 );\n  pcacheTrace((\"%p.CLOSE\\n\",pCache));\n  sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);\n}\n\n/* \n** Discard the contents of the cache.\n*/\nSQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){\n  sqlite3PcacheTruncate(pCache, 0);\n}\n\n/*\n** Merge two lists of pages connected by pDirty and in pgno order.\n** Do not bother fixing the pDirtyPrev pointers.\n*/\nstatic PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){\n  PgHdr result, *pTail;\n  pTail = &result;\n  assert( pA!=0 && pB!=0 );\n  for(;;){\n    if( pA->pgno<pB->pgno ){\n      pTail->pDirty = pA;\n      pTail = pA;\n      pA = pA->pDirty;\n      if( pA==0 ){\n        pTail->pDirty = pB;\n        break;\n      }\n    }else{\n      pTail->pDirty = pB;\n      pTail = pB;\n      pB = pB->pDirty;\n      if( pB==0 ){\n        pTail->pDirty = pA;\n        break;\n      }\n    }\n  }\n  return result.pDirty;\n}\n\n/*\n** Sort the list of pages in accending order by pgno.  Pages are\n** connected by pDirty pointers.  The pDirtyPrev pointers are\n** corrupted by this sort.\n**\n** Since there cannot be more than 2^31 distinct pages in a database,\n** there cannot be more than 31 buckets required by the merge sorter.\n** One extra bucket is added to catch overflow in case something\n** ever changes to make the previous sentence incorrect.\n*/\n#define N_SORT_BUCKET  32\nstatic PgHdr *pcacheSortDirtyList(PgHdr *pIn){\n  PgHdr *a[N_SORT_BUCKET], *p;\n  int i;\n  memset(a, 0, sizeof(a));\n  while( pIn ){\n    p = pIn;\n    pIn = p->pDirty;\n    p->pDirty = 0;\n    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){\n      if( a[i]==0 ){\n        a[i] = p;\n        break;\n      }else{\n        p = pcacheMergeDirtyList(a[i], p);\n        a[i] = 0;\n      }\n    }\n    if( NEVER(i==N_SORT_BUCKET-1) ){\n      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in\n      ** the input list.  But that is impossible.\n      */\n      a[i] = pcacheMergeDirtyList(a[i], p);\n    }\n  }\n  p = a[0];\n  for(i=1; i<N_SORT_BUCKET; i++){\n    if( a[i]==0 ) continue;\n    p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];\n  }\n  return p;\n}\n\n/*\n** Return a list of all dirty pages in the cache, sorted by page number.\n*/\nSQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){\n  PgHdr *p;\n  for(p=pCache->pDirty; p; p=p->pDirtyNext){\n    p->pDirty = p->pDirtyNext;\n  }\n  return pcacheSortDirtyList(pCache->pDirty);\n}\n\n/* \n** Return the total number of references to all pages held by the cache.\n**\n** This is not the total number of pages referenced, but the sum of the\n** reference count for all pages.\n*/\nSQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){\n  return pCache->nRefSum;\n}\n\n/*\n** Return the number of references to the page supplied as an argument.\n*/\nSQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){\n  return p->nRef;\n}\n\n/* \n** Return the total number of pages in the cache.\n*/\nSQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){\n  assert( pCache->pCache!=0 );\n  return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);\n}\n\n#ifdef SQLITE_TEST\n/*\n** Get the suggested cache-size value.\n*/\nSQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){\n  return numberOfCachePages(pCache);\n}\n#endif\n\n/*\n** Set the suggested cache-size value.\n*/\nSQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){\n  assert( pCache->pCache!=0 );\n  pCache->szCache = mxPage;\n  sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,\n                                         numberOfCachePages(pCache));\n}\n\n/*\n** Set the suggested cache-spill value.  Make no changes if if the\n** argument is zero.  Return the effective cache-spill size, which will\n** be the larger of the szSpill and szCache.\n*/\nSQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){\n  int res;\n  assert( p->pCache!=0 );\n  if( mxPage ){\n    if( mxPage<0 ){\n      mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));\n    }\n    p->szSpill = mxPage;\n  }\n  res = numberOfCachePages(p);\n  if( res<p->szSpill ) res = p->szSpill; \n  return res;\n}\n\n/*\n** Free up as much memory as possible from the page cache.\n*/\nSQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){\n  assert( pCache->pCache!=0 );\n  sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);\n}\n\n/*\n** Return the size of the header added by this middleware layer\n** in the page-cache hierarchy.\n*/\nSQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }\n\n/*\n** Return the number of dirty pages currently in the cache, as a percentage\n** of the configured cache size.\n*/\nSQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){\n  PgHdr *pDirty;\n  int nDirty = 0;\n  int nCache = numberOfCachePages(pCache);\n  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;\n  return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;\n}\n\n#ifdef SQLITE_DIRECT_OVERFLOW_READ\n/* \n** Return true if there are one or more dirty pages in the cache. Else false.\n*/\nSQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache){\n  return (pCache->pDirty!=0);\n}\n#endif\n\n#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)\n/*\n** For all dirty pages currently in the cache, invoke the specified\n** callback. This is only used if the SQLITE_CHECK_PAGES macro is\n** defined.\n*/\nSQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){\n  PgHdr *pDirty;\n  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){\n    xIter(pDirty);\n  }\n}\n#endif\n\n/************** End of pcache.c **********************************************/\n/************** Begin file pcache1.c *****************************************/\n/*\n** 2008 November 05\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file implements the default page cache implementation (the\n** sqlite3_pcache interface). It also contains part of the implementation\n** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.\n** If the default page cache implementation is overridden, then neither of\n** these two features are available.\n**\n** A Page cache line looks like this:\n**\n**  -------------------------------------------------------------\n**  |  database page content   |  PgHdr1  |  MemPage  |  PgHdr  |\n**  -------------------------------------------------------------\n**\n** The database page content is up front (so that buffer overreads tend to\n** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions).   MemPage\n** is the extension added by the btree.c module containing information such\n** as the database page number and how that database page is used.  PgHdr\n** is added by the pcache.c layer and contains information used to keep track\n** of which pages are \"dirty\".  PgHdr1 is an extension added by this\n** module (pcache1.c).  The PgHdr1 header is a subclass of sqlite3_pcache_page.\n** PgHdr1 contains information needed to look up a page by its page number.\n** The superclass sqlite3_pcache_page.pBuf points to the start of the\n** database page content and sqlite3_pcache_page.pExtra points to PgHdr.\n**\n** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at\n** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size).  The\n** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this\n** size can vary according to architecture, compile-time options, and\n** SQLite library version number.\n**\n** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained\n** using a separate memory allocation from the database page content.  This\n** seeks to overcome the \"clownshoe\" problem (also called \"internal\n** fragmentation\" in academic literature) of allocating a few bytes more\n** than a power of two with the memory allocator rounding up to the next\n** power of two, and leaving the rounded-up space unused.\n**\n** This module tracks pointers to PgHdr1 objects.  Only pcache.c communicates\n** with this module.  Information is passed back and forth as PgHdr1 pointers.\n**\n** The pcache.c and pager.c modules deal pointers to PgHdr objects.\n** The btree.c module deals with pointers to MemPage objects.\n**\n** SOURCE OF PAGE CACHE MEMORY:\n**\n** Memory for a page might come from any of three sources:\n**\n**    (1)  The general-purpose memory allocator - sqlite3Malloc()\n**    (2)  Global page-cache memory provided using sqlite3_config() with\n**         SQLITE_CONFIG_PAGECACHE.\n**    (3)  PCache-local bulk allocation.\n**\n** The third case is a chunk of heap memory (defaulting to 100 pages worth)\n** that is allocated when the page cache is created.  The size of the local\n** bulk allocation can be adjusted using \n**\n**     sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).\n**\n** If N is positive, then N pages worth of memory are allocated using a single\n** sqlite3Malloc() call and that memory is used for the first N pages allocated.\n** Or if N is negative, then -1024*N bytes of memory are allocated and used\n** for as many pages as can be accomodated.\n**\n** Only one of (2) or (3) can be used.  Once the memory available to (2) or\n** (3) is exhausted, subsequent allocations fail over to the general-purpose\n** memory allocator (1).\n**\n** Earlier versions of SQLite used only methods (1) and (2).  But experiments\n** show that method (3) with N==100 provides about a 5% performance boost for\n** common workloads.\n*/\n/* #include \"sqliteInt.h\" */\n\ntypedef struct PCache1 PCache1;\ntypedef struct PgHdr1 PgHdr1;\ntypedef struct PgFreeslot PgFreeslot;\ntypedef struct PGroup PGroup;\n\n/*\n** Each cache entry is represented by an instance of the following \n** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of\n** PgHdr1.pCache->szPage bytes is allocated directly before this structure \n** in memory.\n**\n** Note: Variables isBulkLocal and isAnchor were once type \"u8\". That works,\n** but causes a 2-byte gap in the structure for most architectures (since \n** pointers must be either 4 or 8-byte aligned). As this structure is located\n** in memory directly after the associated page data, if the database is\n** corrupt, code at the b-tree layer may overread the page buffer and \n** read part of this structure before the corruption is detected. This\n** can cause a valgrind error if the unitialized gap is accessed. Using u16\n** ensures there is no such gap, and therefore no bytes of unitialized memory\n** in the structure.\n*/\nstruct PgHdr1 {\n  sqlite3_pcache_page page;      /* Base class. Must be first. pBuf & pExtra */\n  unsigned int iKey;             /* Key value (page number) */\n  u16 isBulkLocal;               /* This page from bulk local storage */\n  u16 isAnchor;                  /* This is the PGroup.lru element */\n  PgHdr1 *pNext;                 /* Next in hash table chain */\n  PCache1 *pCache;               /* Cache that currently owns this page */\n  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */\n  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */\n                                 /* NB: pLruPrev is only valid if pLruNext!=0 */\n};\n\n/*\n** A page is pinned if it is not on the LRU list.  To be \"pinned\" means\n** that the page is in active use and must not be deallocated.\n*/\n#define PAGE_IS_PINNED(p)    ((p)->pLruNext==0)\n#define PAGE_IS_UNPINNED(p)  ((p)->pLruNext!=0)\n\n/* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set \n** of one or more PCaches that are able to recycle each other's unpinned\n** pages when they are under memory pressure.  A PGroup is an instance of\n** the following object.\n**\n** This page cache implementation works in one of two modes:\n**\n**   (1)  Every PCache is the sole member of its own PGroup.  There is\n**        one PGroup per PCache.\n**\n**   (2)  There is a single global PGroup that all PCaches are a member\n**        of.\n**\n** Mode 1 uses more memory (since PCache instances are not able to rob\n** unused pages from other PCaches) but it also operates without a mutex,\n** and is therefore often faster.  Mode 2 requires a mutex in order to be\n** threadsafe, but recycles pages more efficiently.\n**\n** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single\n** PGroup which is the pcache1.grp global variable and its mutex is\n** SQLITE_MUTEX_STATIC_LRU.\n*/\nstruct PGroup {\n  sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */\n  unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */\n  unsigned int nMinPage;         /* Sum of nMin for purgeable caches */\n  unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */\n  unsigned int nPurgeable;       /* Number of purgeable pages allocated */\n  PgHdr1 lru;                    /* The beginning and end of the LRU list */\n};\n\n/* Each page cache is an instance of the following object.  Every\n** open database file (including each in-memory database and each\n** temporary or transient database) has a single page cache which\n** is an instance of this object.\n**\n** Pointers to structures of this type are cast and returned as \n** opaque sqlite3_pcache* handles.\n*/\nstruct PCache1 {\n  /* Cache configuration parameters. Page size (szPage) and the purgeable\n  ** flag (bPurgeable) and the pnPurgeable pointer are all set when the\n  ** cache is created and are never changed thereafter. nMax may be \n  ** modified at any time by a call to the pcache1Cachesize() method.\n  ** The PGroup mutex must be held when accessing nMax.\n  */\n  PGroup *pGroup;                     /* PGroup this cache belongs to */\n  unsigned int *pnPurgeable;          /* Pointer to pGroup->nPurgeable */\n  int szPage;                         /* Size of database content section */\n  int szExtra;                        /* sizeof(MemPage)+sizeof(PgHdr) */\n  int szAlloc;                        /* Total size of one pcache line */\n  int bPurgeable;                     /* True if cache is purgeable */\n  unsigned int nMin;                  /* Minimum number of pages reserved */\n  unsigned int nMax;                  /* Configured \"cache_size\" value */\n  unsigned int n90pct;                /* nMax*9/10 */\n  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */\n  unsigned int nPurgeableDummy;       /* pnPurgeable points here when not used*/\n\n  /* Hash table of all pages. The following variables may only be accessed\n  ** when the accessor is holding the PGroup mutex.\n  */\n  unsigned int nRecyclable;           /* Number of pages in the LRU list */\n  unsigned int nPage;                 /* Total number of pages in apHash */\n  unsigned int nHash;                 /* Number of slots in apHash[] */\n  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */\n  PgHdr1 *pFree;                      /* List of unused pcache-local pages */\n  void *pBulk;                        /* Bulk memory used by pcache-local */\n};\n\n/*\n** Free slots in the allocator used to divide up the global page cache\n** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.\n*/\nstruct PgFreeslot {\n  PgFreeslot *pNext;  /* Next free slot */\n};\n\n/*\n** Global data used by this cache.\n*/\nstatic SQLITE_WSD struct PCacheGlobal {\n  PGroup grp;                    /* The global PGroup for mode (2) */\n\n  /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The\n  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all\n  ** fixed at sqlite3_initialize() time and do not require mutex protection.\n  ** The nFreeSlot and pFree values do require mutex protection.\n  */\n  int isInit;                    /* True if initialized */\n  int separateCache;             /* Use a new PGroup for each PCache */\n  int nInitPage;                 /* Initial bulk allocation size */   \n  int szSlot;                    /* Size of each free slot */\n  int nSlot;                     /* The number of pcache slots */\n  int nReserve;                  /* Try to keep nFreeSlot above this */\n  void *pStart, *pEnd;           /* Bounds of global page cache memory */\n  /* Above requires no mutex.  Use mutex below for variable that follow. */\n  sqlite3_mutex *mutex;          /* Mutex for accessing the following: */\n  PgFreeslot *pFree;             /* Free page blocks */\n  int nFreeSlot;                 /* Number of unused pcache slots */\n  /* The following value requires a mutex to change.  We skip the mutex on\n  ** reading because (1) most platforms read a 32-bit integer atomically and\n  ** (2) even if an incorrect value is read, no great harm is done since this\n  ** is really just an optimization. */\n  int bUnderPressure;            /* True if low on PAGECACHE memory */\n} pcache1_g;\n\n/*\n** All code in this file should access the global structure above via the\n** alias \"pcache1\". This ensures that the WSD emulation is used when\n** compiling for systems that do not support real WSD.\n*/\n#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))\n\n/*\n** Macros to enter and leave the PCache LRU mutex.\n*/\n#if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0\n# define pcache1EnterMutex(X)  assert((X)->mutex==0)\n# define pcache1LeaveMutex(X)  assert((X)->mutex==0)\n# define PCACHE1_MIGHT_USE_GROUP_MUTEX 0\n#else\n# define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)\n# define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)\n# define PCACHE1_MIGHT_USE_GROUP_MUTEX 1\n#endif\n\n/******************************************************************************/\n/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/\n\n\n/*\n** This function is called during initialization if a static buffer is \n** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE\n** verb to sqlite3_config(). Parameter pBuf points to an allocation large\n** enough to contain 'n' buffers of 'sz' bytes each.\n**\n** This routine is called from sqlite3_initialize() and so it is guaranteed\n** to be serialized already.  There is no need for further mutexing.\n*/\nSQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){\n  if( pcache1.isInit ){\n    PgFreeslot *p;\n    if( pBuf==0 ) sz = n = 0;\n    if( n==0 ) sz = 0;\n    sz = ROUNDDOWN8(sz);\n    pcache1.szSlot = sz;\n    pcache1.nSlot = pcache1.nFreeSlot = n;\n    pcache1.nReserve = n>90 ? 10 : (n/10 + 1);\n    pcache1.pStart = pBuf;\n    pcache1.pFree = 0;\n    pcache1.bUnderPressure = 0;\n    while( n-- ){\n      p = (PgFreeslot*)pBuf;\n      p->pNext = pcache1.pFree;\n      pcache1.pFree = p;\n      pBuf = (void*)&((char*)pBuf)[sz];\n    }\n    pcache1.pEnd = pBuf;\n  }\n}\n\n/*\n** Try to initialize the pCache->pFree and pCache->pBulk fields.  Return\n** true if pCache->pFree ends up containing one or more free pages.\n*/\nstatic int pcache1InitBulk(PCache1 *pCache){\n  i64 szBulk;\n  char *zBulk;\n  if( pcache1.nInitPage==0 ) return 0;\n  /* Do not bother with a bulk allocation if the cache size very small */\n  if( pCache->nMax<3 ) return 0;\n  sqlite3BeginBenignMalloc();\n  if( pcache1.nInitPage>0 ){\n    szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;\n  }else{\n    szBulk = -1024 * (i64)pcache1.nInitPage;\n  }\n  if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){\n    szBulk = pCache->szAlloc*(i64)pCache->nMax;\n  }\n  zBulk = pCache->pBulk = sqlite3Malloc( szBulk );\n  sqlite3EndBenignMalloc();\n  if( zBulk ){\n    int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;\n    do{\n      PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];\n      pX->page.pBuf = zBulk;\n      pX->page.pExtra = &pX[1];\n      pX->isBulkLocal = 1;\n      pX->isAnchor = 0;\n      pX->pNext = pCache->pFree;\n      pX->pLruPrev = 0;           /* Initializing this saves a valgrind error */\n      pCache->pFree = pX;\n      zBulk += pCache->szAlloc;\n    }while( --nBulk );\n  }\n  return pCache->pFree!=0;\n}\n\n/*\n** Malloc function used within this file to allocate space from the buffer\n** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no \n** such buffer exists or there is no space left in it, this function falls \n** back to sqlite3Malloc().\n**\n** Multiple threads can run this routine at the same time.  Global variables\n** in pcache1 need to be protected via mutex.\n*/\nstatic void *pcache1Alloc(int nByte){\n  void *p = 0;\n  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );\n  if( nByte<=pcache1.szSlot ){\n    sqlite3_mutex_enter(pcache1.mutex);\n    p = (PgHdr1 *)pcache1.pFree;\n    if( p ){\n      pcache1.pFree = pcache1.pFree->pNext;\n      pcache1.nFreeSlot--;\n      pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;\n      assert( pcache1.nFreeSlot>=0 );\n      sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);\n      sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);\n    }\n    sqlite3_mutex_leave(pcache1.mutex);\n  }\n  if( p==0 ){\n    /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get\n    ** it from sqlite3Malloc instead.\n    */\n    p = sqlite3Malloc(nByte);\n#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS\n    if( p ){\n      int sz = sqlite3MallocSize(p);\n      sqlite3_mutex_enter(pcache1.mutex);\n      sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);\n      sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);\n      sqlite3_mutex_leave(pcache1.mutex);\n    }\n#endif\n    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);\n  }\n  return p;\n}\n\n/*\n** Free an allocated buffer obtained from pcache1Alloc().\n*/\nstatic void pcache1Free(void *p){\n  if( p==0 ) return;\n  if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){\n    PgFreeslot *pSlot;\n    sqlite3_mutex_enter(pcache1.mutex);\n    sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);\n    pSlot = (PgFreeslot*)p;\n    pSlot->pNext = pcache1.pFree;\n    pcache1.pFree = pSlot;\n    pcache1.nFreeSlot++;\n    pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;\n    assert( pcache1.nFreeSlot<=pcache1.nSlot );\n    sqlite3_mutex_leave(pcache1.mutex);\n  }else{\n    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );\n    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);\n#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS\n    {\n      int nFreed = 0;\n      nFreed = sqlite3MallocSize(p);\n      sqlite3_mutex_enter(pcache1.mutex);\n      sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);\n      sqlite3_mutex_leave(pcache1.mutex);\n    }\n#endif\n    sqlite3_free(p);\n  }\n}\n\n#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT\n/*\n** Return the size of a pcache allocation\n*/\nstatic int pcache1MemSize(void *p){\n  if( p>=pcache1.pStart && p<pcache1.pEnd ){\n    return pcache1.szSlot;\n  }else{\n    int iSize;\n    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );\n    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);\n    iSize = sqlite3MallocSize(p);\n    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);\n    return iSize;\n  }\n}\n#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */\n\n/*\n** Allocate a new page object initially associated with cache pCache.\n*/\nstatic PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){\n  PgHdr1 *p = 0;\n  void *pPg;\n\n  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );\n  if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){\n    assert( pCache->pFree!=0 );\n    p = pCache->pFree;\n    pCache->pFree = p->pNext;\n    p->pNext = 0;\n  }else{\n#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT\n    /* The group mutex must be released before pcache1Alloc() is called. This\n    ** is because it might call sqlite3_release_memory(), which assumes that \n    ** this mutex is not held. */\n    assert( pcache1.separateCache==0 );\n    assert( pCache->pGroup==&pcache1.grp );\n    pcache1LeaveMutex(pCache->pGroup);\n#endif\n    if( benignMalloc ){ sqlite3BeginBenignMalloc(); }\n#ifdef SQLITE_PCACHE_SEPARATE_HEADER\n    pPg = pcache1Alloc(pCache->szPage);\n    p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);\n    if( !pPg || !p ){\n      pcache1Free(pPg);\n      sqlite3_free(p);\n      pPg = 0;\n    }\n#else\n    pPg = pcache1Alloc(pCache->szAlloc);\n#endif\n    if( benignMalloc ){ sqlite3EndBenignMalloc(); }\n#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT\n    pcache1EnterMutex(pCache->pGroup);\n#endif\n    if( pPg==0 ) return 0;\n#ifndef SQLITE_PCACHE_SEPARATE_HEADER\n    p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];\n#endif\n    p->page.pBuf = pPg;\n    p->page.pExtra = &p[1];\n    p->isBulkLocal = 0;\n    p->isAnchor = 0;\n  }\n  (*pCache->pnPurgeable)++;\n  return p;\n}\n\n/*\n** Free a page object allocated by pcache1AllocPage().\n*/\nstatic void pcache1FreePage(PgHdr1 *p){\n  PCache1 *pCache;\n  assert( p!=0 );\n  pCache = p->pCache;\n  assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );\n  if( p->isBulkLocal ){\n    p->pNext = pCache->pFree;\n    pCache->pFree = p;\n  }else{\n    pcache1Free(p->page.pBuf);\n#ifdef SQLITE_PCACHE_SEPARATE_HEADER\n    sqlite3_free(p);\n#endif\n  }\n  (*pCache->pnPurgeable)--;\n}\n\n/*\n** Malloc function used by SQLite to obtain space from the buffer configured\n** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer\n** exists, this function falls back to sqlite3Malloc().\n*/\nSQLITE_PRIVATE void *sqlite3PageMalloc(int sz){\n  assert( sz<=65536+8 ); /* These allocations are never very large */\n  return pcache1Alloc(sz);\n}\n\n/*\n** Free an allocated buffer obtained from sqlite3PageMalloc().\n*/\nSQLITE_PRIVATE void sqlite3PageFree(void *p){\n  pcache1Free(p);\n}\n\n\n/*\n** Return true if it desirable to avoid allocating a new page cache\n** entry.\n**\n** If memory was allocated specifically to the page cache using\n** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then\n** it is desirable to avoid allocating a new page cache entry because\n** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient\n** for all page cache needs and we should not need to spill the\n** allocation onto the heap.\n**\n** Or, the heap is used for all page cache memory but the heap is\n** under memory pressure, then again it is desirable to avoid\n** allocating a new page cache entry in order to avoid stressing\n** the heap even further.\n*/\nstatic int pcache1UnderMemoryPressure(PCache1 *pCache){\n  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){\n    return pcache1.bUnderPressure;\n  }else{\n    return sqlite3HeapNearlyFull();\n  }\n}\n\n/******************************************************************************/\n/******** General Implementation Functions ************************************/\n\n/*\n** This function is used to resize the hash table used by the cache passed\n** as the first argument.\n**\n** The PCache mutex must be held when this function is called.\n*/\nstatic void pcache1ResizeHash(PCache1 *p){\n  PgHdr1 **apNew;\n  unsigned int nNew;\n  unsigned int i;\n\n  assert( sqlite3_mutex_held(p->pGroup->mutex) );\n\n  nNew = p->nHash*2;\n  if( nNew<256 ){\n    nNew = 256;\n  }\n\n  pcache1LeaveMutex(p->pGroup);\n  if( p->nHash ){ sqlite3BeginBenignMalloc(); }\n  apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);\n  if( p->nHash ){ sqlite3EndBenignMalloc(); }\n  pcache1EnterMutex(p->pGroup);\n  if( apNew ){\n    for(i=0; i<p->nHash; i++){\n      PgHdr1 *pPage;\n      PgHdr1 *pNext = p->apHash[i];\n      while( (pPage = pNext)!=0 ){\n        unsigned int h = pPage->iKey % nNew;\n        pNext = pPage->pNext;\n        pPage->pNext = apNew[h];\n        apNew[h] = pPage;\n      }\n    }\n    sqlite3_free(p->apHash);\n    p->apHash = apNew;\n    p->nHash = nNew;\n  }\n}\n\n/*\n** This function is used internally to remove the page pPage from the \n** PGroup LRU list, if is part of it. If pPage is not part of the PGroup\n** LRU list, then this function is a no-op.\n**\n** The PGroup mutex must be held when this function is called.\n*/\nstatic PgHdr1 *pcache1PinPage(PgHdr1 *pPage){\n  assert( pPage!=0 );\n  assert( PAGE_IS_UNPINNED(pPage) );\n  assert( pPage->pLruNext );\n  assert( pPage->pLruPrev );\n  assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );\n  pPage->pLruPrev->pLruNext = pPage->pLruNext;\n  pPage->pLruNext->pLruPrev = pPage->pLruPrev;\n  pPage->pLruNext = 0;\n  /* pPage->pLruPrev = 0;\n  ** No need to clear pLruPrev as it is never accessed if pLruNext is 0 */\n  assert( pPage->isAnchor==0 );\n  assert( pPage->pCache->pGroup->lru.isAnchor==1 );\n  pPage->pCache->nRecyclable--;\n  return pPage;\n}\n\n\n/*\n** Remove the page supplied as an argument from the hash table \n** (PCache1.apHash structure) that it is currently stored in.\n** Also free the page if freePage is true.\n**\n** The PGroup mutex must be held when this function is called.\n*/\nstatic void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){\n  unsigned int h;\n  PCache1 *pCache = pPage->pCache;\n  PgHdr1 **pp;\n\n  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );\n  h = pPage->iKey % pCache->nHash;\n  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);\n  *pp = (*pp)->pNext;\n\n  pCache->nPage--;\n  if( freeFlag ) pcache1FreePage(pPage);\n}\n\n/*\n** If there are currently more than nMaxPage pages allocated, try\n** to recycle pages to reduce the number allocated to nMaxPage.\n*/\nstatic void pcache1EnforceMaxPage(PCache1 *pCache){\n  PGroup *pGroup = pCache->pGroup;\n  PgHdr1 *p;\n  assert( sqlite3_mutex_held(pGroup->mutex) );\n  while( pGroup->nPurgeable>pGroup->nMaxPage\n      && (p=pGroup->lru.pLruPrev)->isAnchor==0\n  ){\n    assert( p->pCache->pGroup==pGroup );\n    assert( PAGE_IS_UNPINNED(p) );\n    pcache1PinPage(p);\n    pcache1RemoveFromHash(p, 1);\n  }\n  if( pCache->nPage==0 && pCache->pBulk ){\n    sqlite3_free(pCache->pBulk);\n    pCache->pBulk = pCache->pFree = 0;\n  }\n}\n\n/*\n** Discard all pages from cache pCache with a page number (key value) \n** greater than or equal to iLimit. Any pinned pages that meet this \n** criteria are unpinned before they are discarded.\n**\n** The PCache mutex must be held when this function is called.\n*/\nstatic void pcache1TruncateUnsafe(\n  PCache1 *pCache,             /* The cache to truncate */\n  unsigned int iLimit          /* Drop pages with this pgno or larger */\n){\n  TESTONLY( int nPage = 0; )  /* To assert pCache->nPage is correct */\n  unsigned int h, iStop;\n  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );\n  assert( pCache->iMaxKey >= iLimit );\n  assert( pCache->nHash > 0 );\n  if( pCache->iMaxKey - iLimit < pCache->nHash ){\n    /* If we are just shaving the last few pages off the end of the\n    ** cache, then there is no point in scanning the entire hash table.\n    ** Only scan those hash slots that might contain pages that need to\n    ** be removed. */\n    h = iLimit % pCache->nHash;\n    iStop = pCache->iMaxKey % pCache->nHash;\n    TESTONLY( nPage = -10; )  /* Disable the pCache->nPage validity check */\n  }else{\n    /* This is the general case where many pages are being removed.\n    ** It is necessary to scan the entire hash table */\n    h = pCache->nHash/2;\n    iStop = h - 1;\n  }\n  for(;;){\n    PgHdr1 **pp;\n    PgHdr1 *pPage;\n    assert( h<pCache->nHash );\n    pp = &pCache->apHash[h]; \n    while( (pPage = *pp)!=0 ){\n      if( pPage->iKey>=iLimit ){\n        pCache->nPage--;\n        *pp = pPage->pNext;\n        if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);\n        pcache1FreePage(pPage);\n      }else{\n        pp = &pPage->pNext;\n        TESTONLY( if( nPage>=0 ) nPage++; )\n      }\n    }\n    if( h==iStop ) break;\n    h = (h+1) % pCache->nHash;\n  }\n  assert( nPage<0 || pCache->nPage==(unsigned)nPage );\n}\n\n/******************************************************************************/\n/******** sqlite3_pcache Methods **********************************************/\n\n/*\n** Implementation of the sqlite3_pcache.xInit method.\n*/\nstatic int pcache1Init(void *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  assert( pcache1.isInit==0 );\n  memset(&pcache1, 0, sizeof(pcache1));\n\n\n  /*\n  ** The pcache1.separateCache variable is true if each PCache has its own\n  ** private PGroup (mode-1).  pcache1.separateCache is false if the single\n  ** PGroup in pcache1.grp is used for all page caches (mode-2).\n  **\n  **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT\n  **\n  **   *  Use a unified cache in single-threaded applications that have\n  **      configured a start-time buffer for use as page-cache memory using\n  **      sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL \n  **      pBuf argument.\n  **\n  **   *  Otherwise use separate caches (mode-1)\n  */\n#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)\n  pcache1.separateCache = 0;\n#elif SQLITE_THREADSAFE\n  pcache1.separateCache = sqlite3GlobalConfig.pPage==0\n                          || sqlite3GlobalConfig.bCoreMutex>0;\n#else\n  pcache1.separateCache = sqlite3GlobalConfig.pPage==0;\n#endif\n\n#if SQLITE_THREADSAFE\n  if( sqlite3GlobalConfig.bCoreMutex ){\n    pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);\n    pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);\n  }\n#endif\n  if( pcache1.separateCache\n   && sqlite3GlobalConfig.nPage!=0\n   && sqlite3GlobalConfig.pPage==0\n  ){\n    pcache1.nInitPage = sqlite3GlobalConfig.nPage;\n  }else{\n    pcache1.nInitPage = 0;\n  }\n  pcache1.grp.mxPinned = 10;\n  pcache1.isInit = 1;\n  return SQLITE_OK;\n}\n\n/*\n** Implementation of the sqlite3_pcache.xShutdown method.\n** Note that the static mutex allocated in xInit does \n** not need to be freed.\n*/\nstatic void pcache1Shutdown(void *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  assert( pcache1.isInit!=0 );\n  memset(&pcache1, 0, sizeof(pcache1));\n}\n\n/* forward declaration */\nstatic void pcache1Destroy(sqlite3_pcache *p);\n\n/*\n** Implementation of the sqlite3_pcache.xCreate method.\n**\n** Allocate a new cache.\n*/\nstatic sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){\n  PCache1 *pCache;      /* The newly created page cache */\n  PGroup *pGroup;       /* The group the new page cache will belong to */\n  int sz;               /* Bytes of memory required to allocate the new cache */\n\n  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );\n  assert( szExtra < 300 );\n\n  sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;\n  pCache = (PCache1 *)sqlite3MallocZero(sz);\n  if( pCache ){\n    if( pcache1.separateCache ){\n      pGroup = (PGroup*)&pCache[1];\n      pGroup->mxPinned = 10;\n    }else{\n      pGroup = &pcache1.grp;\n    }\n    pcache1EnterMutex(pGroup);\n    if( pGroup->lru.isAnchor==0 ){\n      pGroup->lru.isAnchor = 1;\n      pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;\n    }\n    pCache->pGroup = pGroup;\n    pCache->szPage = szPage;\n    pCache->szExtra = szExtra;\n    pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));\n    pCache->bPurgeable = (bPurgeable ? 1 : 0);\n    pcache1ResizeHash(pCache);\n    if( bPurgeable ){\n      pCache->nMin = 10;\n      pGroup->nMinPage += pCache->nMin;\n      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;\n      pCache->pnPurgeable = &pGroup->nPurgeable;\n    }else{\n      pCache->pnPurgeable = &pCache->nPurgeableDummy;\n    }\n    pcache1LeaveMutex(pGroup);\n    if( pCache->nHash==0 ){\n      pcache1Destroy((sqlite3_pcache*)pCache);\n      pCache = 0;\n    }\n  }\n  return (sqlite3_pcache *)pCache;\n}\n\n/*\n** Implementation of the sqlite3_pcache.xCachesize method. \n**\n** Configure the cache_size limit for a cache.\n*/\nstatic void pcache1Cachesize(sqlite3_pcache *p, int nMax){\n  PCache1 *pCache = (PCache1 *)p;\n  if( pCache->bPurgeable ){\n    PGroup *pGroup = pCache->pGroup;\n    pcache1EnterMutex(pGroup);\n    pGroup->nMaxPage += (nMax - pCache->nMax);\n    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;\n    pCache->nMax = nMax;\n    pCache->n90pct = pCache->nMax*9/10;\n    pcache1EnforceMaxPage(pCache);\n    pcache1LeaveMutex(pGroup);\n  }\n}\n\n/*\n** Implementation of the sqlite3_pcache.xShrink method. \n**\n** Free up as much memory as possible.\n*/\nstatic void pcache1Shrink(sqlite3_pcache *p){\n  PCache1 *pCache = (PCache1*)p;\n  if( pCache->bPurgeable ){\n    PGroup *pGroup = pCache->pGroup;\n    int savedMaxPage;\n    pcache1EnterMutex(pGroup);\n    savedMaxPage = pGroup->nMaxPage;\n    pGroup->nMaxPage = 0;\n    pcache1EnforceMaxPage(pCache);\n    pGroup->nMaxPage = savedMaxPage;\n    pcache1LeaveMutex(pGroup);\n  }\n}\n\n/*\n** Implementation of the sqlite3_pcache.xPagecount method. \n*/\nstatic int pcache1Pagecount(sqlite3_pcache *p){\n  int n;\n  PCache1 *pCache = (PCache1*)p;\n  pcache1EnterMutex(pCache->pGroup);\n  n = pCache->nPage;\n  pcache1LeaveMutex(pCache->pGroup);\n  return n;\n}\n\n\n/*\n** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described\n** in the header of the pcache1Fetch() procedure.\n**\n** This steps are broken out into a separate procedure because they are\n** usually not needed, and by avoiding the stack initialization required\n** for these steps, the main pcache1Fetch() procedure can run faster.\n*/\nstatic SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(\n  PCache1 *pCache, \n  unsigned int iKey, \n  int createFlag\n){\n  unsigned int nPinned;\n  PGroup *pGroup = pCache->pGroup;\n  PgHdr1 *pPage = 0;\n\n  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */\n  assert( pCache->nPage >= pCache->nRecyclable );\n  nPinned = pCache->nPage - pCache->nRecyclable;\n  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );\n  assert( pCache->n90pct == pCache->nMax*9/10 );\n  if( createFlag==1 && (\n        nPinned>=pGroup->mxPinned\n     || nPinned>=pCache->n90pct\n     || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)\n  )){\n    return 0;\n  }\n\n  if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);\n  assert( pCache->nHash>0 && pCache->apHash );\n\n  /* Step 4. Try to recycle a page. */\n  if( pCache->bPurgeable\n   && !pGroup->lru.pLruPrev->isAnchor\n   && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))\n  ){\n    PCache1 *pOther;\n    pPage = pGroup->lru.pLruPrev;\n    assert( PAGE_IS_UNPINNED(pPage) );\n    pcache1RemoveFromHash(pPage, 0);\n    pcache1PinPage(pPage);\n    pOther = pPage->pCache;\n    if( pOther->szAlloc != pCache->szAlloc ){\n      pcache1FreePage(pPage);\n      pPage = 0;\n    }else{\n      pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);\n    }\n  }\n\n  /* Step 5. If a usable page buffer has still not been found, \n  ** attempt to allocate a new one. \n  */\n  if( !pPage ){\n    pPage = pcache1AllocPage(pCache, createFlag==1);\n  }\n\n  if( pPage ){\n    unsigned int h = iKey % pCache->nHash;\n    pCache->nPage++;\n    pPage->iKey = iKey;\n    pPage->pNext = pCache->apHash[h];\n    pPage->pCache = pCache;\n    pPage->pLruNext = 0;\n    /* pPage->pLruPrev = 0;\n    ** No need to clear pLruPrev since it is not accessed when pLruNext==0 */\n    *(void **)pPage->page.pExtra = 0;\n    pCache->apHash[h] = pPage;\n    if( iKey>pCache->iMaxKey ){\n      pCache->iMaxKey = iKey;\n    }\n  }\n  return pPage;\n}\n\n/*\n** Implementation of the sqlite3_pcache.xFetch method. \n**\n** Fetch a page by key value.\n**\n** Whether or not a new page may be allocated by this function depends on\n** the value of the createFlag argument.  0 means do not allocate a new\n** page.  1 means allocate a new page if space is easily available.  2 \n** means to try really hard to allocate a new page.\n**\n** For a non-purgeable cache (a cache used as the storage for an in-memory\n** database) there is really no difference between createFlag 1 and 2.  So\n** the calling function (pcache.c) will never have a createFlag of 1 on\n** a non-purgeable cache.\n**\n** There are three different approaches to obtaining space for a page,\n** depending on the value of parameter createFlag (which may be 0, 1 or 2).\n**\n**   1. Regardless of the value of createFlag, the cache is searched for a \n**      copy of the requested page. If one is found, it is returned.\n**\n**   2. If createFlag==0 and the page is not already in the cache, NULL is\n**      returned.\n**\n**   3. If createFlag is 1, and the page is not already in the cache, then\n**      return NULL (do not allocate a new page) if any of the following\n**      conditions are true:\n**\n**       (a) the number of pages pinned by the cache is greater than\n**           PCache1.nMax, or\n**\n**       (b) the number of pages pinned by the cache is greater than\n**           the sum of nMax for all purgeable caches, less the sum of \n**           nMin for all other purgeable caches, or\n**\n**   4. If none of the first three conditions apply and the cache is marked\n**      as purgeable, and if one of the following is true:\n**\n**       (a) The number of pages allocated for the cache is already \n**           PCache1.nMax, or\n**\n**       (b) The number of pages allocated for all purgeable caches is\n**           already equal to or greater than the sum of nMax for all\n**           purgeable caches,\n**\n**       (c) The system is under memory pressure and wants to avoid\n**           unnecessary pages cache entry allocations\n**\n**      then attempt to recycle a page from the LRU list. If it is the right\n**      size, return the recycled buffer. Otherwise, free the buffer and\n**      proceed to step 5. \n**\n**   5. Otherwise, allocate and return a new page buffer.\n**\n** There are two versions of this routine.  pcache1FetchWithMutex() is\n** the general case.  pcache1FetchNoMutex() is a faster implementation for\n** the common case where pGroup->mutex is NULL.  The pcache1Fetch() wrapper\n** invokes the appropriate routine.\n*/\nstatic PgHdr1 *pcache1FetchNoMutex(\n  sqlite3_pcache *p, \n  unsigned int iKey, \n  int createFlag\n){\n  PCache1 *pCache = (PCache1 *)p;\n  PgHdr1 *pPage = 0;\n\n  /* Step 1: Search the hash table for an existing entry. */\n  pPage = pCache->apHash[iKey % pCache->nHash];\n  while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }\n\n  /* Step 2: If the page was found in the hash table, then return it.\n  ** If the page was not in the hash table and createFlag is 0, abort.\n  ** Otherwise (page not in hash and createFlag!=0) continue with\n  ** subsequent steps to try to create the page. */\n  if( pPage ){\n    if( PAGE_IS_UNPINNED(pPage) ){\n      return pcache1PinPage(pPage);\n    }else{\n      return pPage;\n    }\n  }else if( createFlag ){\n    /* Steps 3, 4, and 5 implemented by this subroutine */\n    return pcache1FetchStage2(pCache, iKey, createFlag);\n  }else{\n    return 0;\n  }\n}\n#if PCACHE1_MIGHT_USE_GROUP_MUTEX\nstatic PgHdr1 *pcache1FetchWithMutex(\n  sqlite3_pcache *p, \n  unsigned int iKey, \n  int createFlag\n){\n  PCache1 *pCache = (PCache1 *)p;\n  PgHdr1 *pPage;\n\n  pcache1EnterMutex(pCache->pGroup);\n  pPage = pcache1FetchNoMutex(p, iKey, createFlag);\n  assert( pPage==0 || pCache->iMaxKey>=iKey );\n  pcache1LeaveMutex(pCache->pGroup);\n  return pPage;\n}\n#endif\nstatic sqlite3_pcache_page *pcache1Fetch(\n  sqlite3_pcache *p, \n  unsigned int iKey, \n  int createFlag\n){\n#if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)\n  PCache1 *pCache = (PCache1 *)p;\n#endif\n\n  assert( offsetof(PgHdr1,page)==0 );\n  assert( pCache->bPurgeable || createFlag!=1 );\n  assert( pCache->bPurgeable || pCache->nMin==0 );\n  assert( pCache->bPurgeable==0 || pCache->nMin==10 );\n  assert( pCache->nMin==0 || pCache->bPurgeable );\n  assert( pCache->nHash>0 );\n#if PCACHE1_MIGHT_USE_GROUP_MUTEX\n  if( pCache->pGroup->mutex ){\n    return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);\n  }else\n#endif\n  {\n    return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);\n  }\n}\n\n\n/*\n** Implementation of the sqlite3_pcache.xUnpin method.\n**\n** Mark a page as unpinned (eligible for asynchronous recycling).\n*/\nstatic void pcache1Unpin(\n  sqlite3_pcache *p, \n  sqlite3_pcache_page *pPg, \n  int reuseUnlikely\n){\n  PCache1 *pCache = (PCache1 *)p;\n  PgHdr1 *pPage = (PgHdr1 *)pPg;\n  PGroup *pGroup = pCache->pGroup;\n \n  assert( pPage->pCache==pCache );\n  pcache1EnterMutex(pGroup);\n\n  /* It is an error to call this function if the page is already \n  ** part of the PGroup LRU list.\n  */\n  assert( pPage->pLruNext==0 );\n  assert( PAGE_IS_PINNED(pPage) );\n\n  if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){\n    pcache1RemoveFromHash(pPage, 1);\n  }else{\n    /* Add the page to the PGroup LRU list. */\n    PgHdr1 **ppFirst = &pGroup->lru.pLruNext;\n    pPage->pLruPrev = &pGroup->lru;\n    (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;\n    *ppFirst = pPage;\n    pCache->nRecyclable++;\n  }\n\n  pcache1LeaveMutex(pCache->pGroup);\n}\n\n/*\n** Implementation of the sqlite3_pcache.xRekey method. \n*/\nstatic void pcache1Rekey(\n  sqlite3_pcache *p,\n  sqlite3_pcache_page *pPg,\n  unsigned int iOld,\n  unsigned int iNew\n){\n  PCache1 *pCache = (PCache1 *)p;\n  PgHdr1 *pPage = (PgHdr1 *)pPg;\n  PgHdr1 **pp;\n  unsigned int h; \n  assert( pPage->iKey==iOld );\n  assert( pPage->pCache==pCache );\n\n  pcache1EnterMutex(pCache->pGroup);\n\n  h = iOld%pCache->nHash;\n  pp = &pCache->apHash[h];\n  while( (*pp)!=pPage ){\n    pp = &(*pp)->pNext;\n  }\n  *pp = pPage->pNext;\n\n  h = iNew%pCache->nHash;\n  pPage->iKey = iNew;\n  pPage->pNext = pCache->apHash[h];\n  pCache->apHash[h] = pPage;\n  if( iNew>pCache->iMaxKey ){\n    pCache->iMaxKey = iNew;\n  }\n\n  pcache1LeaveMutex(pCache->pGroup);\n}\n\n/*\n** Implementation of the sqlite3_pcache.xTruncate method. \n**\n** Discard all unpinned pages in the cache with a page number equal to\n** or greater than parameter iLimit. Any pinned pages with a page number\n** equal to or greater than iLimit are implicitly unpinned.\n*/\nstatic void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){\n  PCache1 *pCache = (PCache1 *)p;\n  pcache1EnterMutex(pCache->pGroup);\n  if( iLimit<=pCache->iMaxKey ){\n    pcache1TruncateUnsafe(pCache, iLimit);\n    pCache->iMaxKey = iLimit-1;\n  }\n  pcache1LeaveMutex(pCache->pGroup);\n}\n\n/*\n** Implementation of the sqlite3_pcache.xDestroy method. \n**\n** Destroy a cache allocated using pcache1Create().\n*/\nstatic void pcache1Destroy(sqlite3_pcache *p){\n  PCache1 *pCache = (PCache1 *)p;\n  PGroup *pGroup = pCache->pGroup;\n  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );\n  pcache1EnterMutex(pGroup);\n  if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);\n  assert( pGroup->nMaxPage >= pCache->nMax );\n  pGroup->nMaxPage -= pCache->nMax;\n  assert( pGroup->nMinPage >= pCache->nMin );\n  pGroup->nMinPage -= pCache->nMin;\n  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;\n  pcache1EnforceMaxPage(pCache);\n  pcache1LeaveMutex(pGroup);\n  sqlite3_free(pCache->pBulk);\n  sqlite3_free(pCache->apHash);\n  sqlite3_free(pCache);\n}\n\n/*\n** This function is called during initialization (sqlite3_initialize()) to\n** install the default pluggable cache module, assuming the user has not\n** already provided an alternative.\n*/\nSQLITE_PRIVATE void sqlite3PCacheSetDefault(void){\n  static const sqlite3_pcache_methods2 defaultMethods = {\n    1,                       /* iVersion */\n    0,                       /* pArg */\n    pcache1Init,             /* xInit */\n    pcache1Shutdown,         /* xShutdown */\n    pcache1Create,           /* xCreate */\n    pcache1Cachesize,        /* xCachesize */\n    pcache1Pagecount,        /* xPagecount */\n    pcache1Fetch,            /* xFetch */\n    pcache1Unpin,            /* xUnpin */\n    pcache1Rekey,            /* xRekey */\n    pcache1Truncate,         /* xTruncate */\n    pcache1Destroy,          /* xDestroy */\n    pcache1Shrink            /* xShrink */\n  };\n  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);\n}\n\n/*\n** Return the size of the header on each page of this PCACHE implementation.\n*/\nSQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }\n\n/*\n** Return the global mutex used by this PCACHE implementation.  The\n** sqlite3_status() routine needs access to this mutex.\n*/\nSQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){\n  return pcache1.mutex;\n}\n\n#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT\n/*\n** This function is called to free superfluous dynamically allocated memory\n** held by the pager system. Memory in use by any SQLite pager allocated\n** by the current thread may be sqlite3_free()ed.\n**\n** nReq is the number of bytes of memory required. Once this much has\n** been released, the function returns. The return value is the total number \n** of bytes of memory released.\n*/\nSQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){\n  int nFree = 0;\n  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );\n  assert( sqlite3_mutex_notheld(pcache1.mutex) );\n  if( sqlite3GlobalConfig.pPage==0 ){\n    PgHdr1 *p;\n    pcache1EnterMutex(&pcache1.grp);\n    while( (nReq<0 || nFree<nReq)\n       &&  (p=pcache1.grp.lru.pLruPrev)!=0\n       &&  p->isAnchor==0\n    ){\n      nFree += pcache1MemSize(p->page.pBuf);\n#ifdef SQLITE_PCACHE_SEPARATE_HEADER\n      nFree += sqlite3MemSize(p);\n#endif\n      assert( PAGE_IS_UNPINNED(p) );\n      pcache1PinPage(p);\n      pcache1RemoveFromHash(p, 1);\n    }\n    pcache1LeaveMutex(&pcache1.grp);\n  }\n  return nFree;\n}\n#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */\n\n#ifdef SQLITE_TEST\n/*\n** This function is used by test procedures to inspect the internal state\n** of the global cache.\n*/\nSQLITE_PRIVATE void sqlite3PcacheStats(\n  int *pnCurrent,      /* OUT: Total number of pages cached */\n  int *pnMax,          /* OUT: Global maximum cache size */\n  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */\n  int *pnRecyclable    /* OUT: Total number of pages available for recycling */\n){\n  PgHdr1 *p;\n  int nRecyclable = 0;\n  for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){\n    assert( PAGE_IS_UNPINNED(p) );\n    nRecyclable++;\n  }\n  *pnCurrent = pcache1.grp.nPurgeable;\n  *pnMax = (int)pcache1.grp.nMaxPage;\n  *pnMin = (int)pcache1.grp.nMinPage;\n  *pnRecyclable = nRecyclable;\n}\n#endif\n\n/************** End of pcache1.c *********************************************/\n/************** Begin file rowset.c ******************************************/\n/*\n** 2008 December 3\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This module implements an object we call a \"RowSet\".\n**\n** The RowSet object is a collection of rowids.  Rowids\n** are inserted into the RowSet in an arbitrary order.  Inserts\n** can be intermixed with tests to see if a given rowid has been\n** previously inserted into the RowSet.\n**\n** After all inserts are finished, it is possible to extract the\n** elements of the RowSet in sorted order.  Once this extraction\n** process has started, no new elements may be inserted.\n**\n** Hence, the primitive operations for a RowSet are:\n**\n**    CREATE\n**    INSERT\n**    TEST\n**    SMALLEST\n**    DESTROY\n**\n** The CREATE and DESTROY primitives are the constructor and destructor,\n** obviously.  The INSERT primitive adds a new element to the RowSet.\n** TEST checks to see if an element is already in the RowSet.  SMALLEST\n** extracts the least value from the RowSet.\n**\n** The INSERT primitive might allocate additional memory.  Memory is\n** allocated in chunks so most INSERTs do no allocation.  There is an \n** upper bound on the size of allocated memory.  No memory is freed\n** until DESTROY.\n**\n** The TEST primitive includes a \"batch\" number.  The TEST primitive\n** will only see elements that were inserted before the last change\n** in the batch number.  In other words, if an INSERT occurs between\n** two TESTs where the TESTs have the same batch nubmer, then the\n** value added by the INSERT will not be visible to the second TEST.\n** The initial batch number is zero, so if the very first TEST contains\n** a non-zero batch number, it will see all prior INSERTs.\n**\n** No INSERTs may occurs after a SMALLEST.  An assertion will fail if\n** that is attempted.\n**\n** The cost of an INSERT is roughly constant.  (Sometimes new memory\n** has to be allocated on an INSERT.)  The cost of a TEST with a new\n** batch number is O(NlogN) where N is the number of elements in the RowSet.\n** The cost of a TEST using the same batch number is O(logN).  The cost\n** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST\n** primitives are constant time.  The cost of DESTROY is O(N).\n**\n** TEST and SMALLEST may not be used by the same RowSet.  This used to\n** be possible, but the feature was not used, so it was removed in order\n** to simplify the code.\n*/\n/* #include \"sqliteInt.h\" */\n\n\n/*\n** Target size for allocation chunks.\n*/\n#define ROWSET_ALLOCATION_SIZE 1024\n\n/*\n** The number of rowset entries per allocation chunk.\n*/\n#define ROWSET_ENTRY_PER_CHUNK  \\\n                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))\n\n/*\n** Each entry in a RowSet is an instance of the following object.\n**\n** This same object is reused to store a linked list of trees of RowSetEntry\n** objects.  In that alternative use, pRight points to the next entry\n** in the list, pLeft points to the tree, and v is unused.  The\n** RowSet.pForest value points to the head of this forest list.\n*/\nstruct RowSetEntry {            \n  i64 v;                        /* ROWID value for this entry */\n  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */\n  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */\n};\n\n/*\n** RowSetEntry objects are allocated in large chunks (instances of the\n** following structure) to reduce memory allocation overhead.  The\n** chunks are kept on a linked list so that they can be deallocated\n** when the RowSet is destroyed.\n*/\nstruct RowSetChunk {\n  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */\n  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */\n};\n\n/*\n** A RowSet in an instance of the following structure.\n**\n** A typedef of this structure if found in sqliteInt.h.\n*/\nstruct RowSet {\n  struct RowSetChunk *pChunk;    /* List of all chunk allocations */\n  sqlite3 *db;                   /* The database connection */\n  struct RowSetEntry *pEntry;    /* List of entries using pRight */\n  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */\n  struct RowSetEntry *pFresh;    /* Source of new entry objects */\n  struct RowSetEntry *pForest;   /* List of binary trees of entries */\n  u16 nFresh;                    /* Number of objects on pFresh */\n  u16 rsFlags;                   /* Various flags */\n  int iBatch;                    /* Current insert batch */\n};\n\n/*\n** Allowed values for RowSet.rsFlags\n*/\n#define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */\n#define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */\n\n/*\n** Allocate a RowSet object.  Return NULL if a memory allocation\n** error occurs.\n*/\nSQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db){\n  RowSet *p = sqlite3DbMallocRawNN(db, sizeof(*p));\n  if( p ){\n    int N = sqlite3DbMallocSize(db, p);\n    p->pChunk = 0;\n    p->db = db;\n    p->pEntry = 0;\n    p->pLast = 0;\n    p->pForest = 0;\n    p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);\n    p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));\n    p->rsFlags = ROWSET_SORTED;\n    p->iBatch = 0;\n  }\n  return p;\n}\n\n/*\n** Deallocate all chunks from a RowSet.  This frees all memory that\n** the RowSet has allocated over its lifetime.  This routine is\n** the destructor for the RowSet.\n*/\nSQLITE_PRIVATE void sqlite3RowSetClear(void *pArg){\n  RowSet *p = (RowSet*)pArg;\n  struct RowSetChunk *pChunk, *pNextChunk;\n  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){\n    pNextChunk = pChunk->pNextChunk;\n    sqlite3DbFree(p->db, pChunk);\n  }\n  p->pChunk = 0;\n  p->nFresh = 0;\n  p->pEntry = 0;\n  p->pLast = 0;\n  p->pForest = 0;\n  p->rsFlags = ROWSET_SORTED;\n}\n\n/*\n** Deallocate all chunks from a RowSet.  This frees all memory that\n** the RowSet has allocated over its lifetime.  This routine is\n** the destructor for the RowSet.\n*/\nSQLITE_PRIVATE void sqlite3RowSetDelete(void *pArg){\n  sqlite3RowSetClear(pArg);\n  sqlite3DbFree(((RowSet*)pArg)->db, pArg);\n}\n\n/*\n** Allocate a new RowSetEntry object that is associated with the\n** given RowSet.  Return a pointer to the new and completely uninitialized\n** object.\n**\n** In an OOM situation, the RowSet.db->mallocFailed flag is set and this\n** routine returns NULL.\n*/\nstatic struct RowSetEntry *rowSetEntryAlloc(RowSet *p){\n  assert( p!=0 );\n  if( p->nFresh==0 ){  /*OPTIMIZATION-IF-FALSE*/\n    /* We could allocate a fresh RowSetEntry each time one is needed, but it\n    ** is more efficient to pull a preallocated entry from the pool */\n    struct RowSetChunk *pNew;\n    pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));\n    if( pNew==0 ){\n      return 0;\n    }\n    pNew->pNextChunk = p->pChunk;\n    p->pChunk = pNew;\n    p->pFresh = pNew->aEntry;\n    p->nFresh = ROWSET_ENTRY_PER_CHUNK;\n  }\n  p->nFresh--;\n  return p->pFresh++;\n}\n\n/*\n** Insert a new value into a RowSet.\n**\n** The mallocFailed flag of the database connection is set if a\n** memory allocation fails.\n*/\nSQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){\n  struct RowSetEntry *pEntry;  /* The new entry */\n  struct RowSetEntry *pLast;   /* The last prior entry */\n\n  /* This routine is never called after sqlite3RowSetNext() */\n  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );\n\n  pEntry = rowSetEntryAlloc(p);\n  if( pEntry==0 ) return;\n  pEntry->v = rowid;\n  pEntry->pRight = 0;\n  pLast = p->pLast;\n  if( pLast ){\n    if( rowid<=pLast->v ){  /*OPTIMIZATION-IF-FALSE*/\n      /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags\n      ** where possible */\n      p->rsFlags &= ~ROWSET_SORTED;\n    }\n    pLast->pRight = pEntry;\n  }else{\n    p->pEntry = pEntry;\n  }\n  p->pLast = pEntry;\n}\n\n/*\n** Merge two lists of RowSetEntry objects.  Remove duplicates.\n**\n** The input lists are connected via pRight pointers and are \n** assumed to each already be in sorted order.\n*/\nstatic struct RowSetEntry *rowSetEntryMerge(\n  struct RowSetEntry *pA,    /* First sorted list to be merged */\n  struct RowSetEntry *pB     /* Second sorted list to be merged */\n){\n  struct RowSetEntry head;\n  struct RowSetEntry *pTail;\n\n  pTail = &head;\n  assert( pA!=0 && pB!=0 );\n  for(;;){\n    assert( pA->pRight==0 || pA->v<=pA->pRight->v );\n    assert( pB->pRight==0 || pB->v<=pB->pRight->v );\n    if( pA->v<=pB->v ){\n      if( pA->v<pB->v ) pTail = pTail->pRight = pA;\n      pA = pA->pRight;\n      if( pA==0 ){\n        pTail->pRight = pB;\n        break;\n      }\n    }else{\n      pTail = pTail->pRight = pB;\n      pB = pB->pRight;\n      if( pB==0 ){\n        pTail->pRight = pA;\n        break;\n      }\n    }\n  }\n  return head.pRight;\n}\n\n/*\n** Sort all elements on the list of RowSetEntry objects into order of\n** increasing v.\n*/ \nstatic struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){\n  unsigned int i;\n  struct RowSetEntry *pNext, *aBucket[40];\n\n  memset(aBucket, 0, sizeof(aBucket));\n  while( pIn ){\n    pNext = pIn->pRight;\n    pIn->pRight = 0;\n    for(i=0; aBucket[i]; i++){\n      pIn = rowSetEntryMerge(aBucket[i], pIn);\n      aBucket[i] = 0;\n    }\n    aBucket[i] = pIn;\n    pIn = pNext;\n  }\n  pIn = aBucket[0];\n  for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){\n    if( aBucket[i]==0 ) continue;\n    pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];\n  }\n  return pIn;\n}\n\n\n/*\n** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.\n** Convert this tree into a linked list connected by the pRight pointers\n** and return pointers to the first and last elements of the new list.\n*/\nstatic void rowSetTreeToList(\n  struct RowSetEntry *pIn,         /* Root of the input tree */\n  struct RowSetEntry **ppFirst,    /* Write head of the output list here */\n  struct RowSetEntry **ppLast      /* Write tail of the output list here */\n){\n  assert( pIn!=0 );\n  if( pIn->pLeft ){\n    struct RowSetEntry *p;\n    rowSetTreeToList(pIn->pLeft, ppFirst, &p);\n    p->pRight = pIn;\n  }else{\n    *ppFirst = pIn;\n  }\n  if( pIn->pRight ){\n    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);\n  }else{\n    *ppLast = pIn;\n  }\n  assert( (*ppLast)->pRight==0 );\n}\n\n\n/*\n** Convert a sorted list of elements (connected by pRight) into a binary\n** tree with depth of iDepth.  A depth of 1 means the tree contains a single\n** node taken from the head of *ppList.  A depth of 2 means a tree with\n** three nodes.  And so forth.\n**\n** Use as many entries from the input list as required and update the\n** *ppList to point to the unused elements of the list.  If the input\n** list contains too few elements, then construct an incomplete tree\n** and leave *ppList set to NULL.\n**\n** Return a pointer to the root of the constructed binary tree.\n*/\nstatic struct RowSetEntry *rowSetNDeepTree(\n  struct RowSetEntry **ppList,\n  int iDepth\n){\n  struct RowSetEntry *p;         /* Root of the new tree */\n  struct RowSetEntry *pLeft;     /* Left subtree */\n  if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/\n    /* Prevent unnecessary deep recursion when we run out of entries */\n    return 0; \n  }\n  if( iDepth>1 ){   /*OPTIMIZATION-IF-TRUE*/\n    /* This branch causes a *balanced* tree to be generated.  A valid tree\n    ** is still generated without this branch, but the tree is wildly\n    ** unbalanced and inefficient. */\n    pLeft = rowSetNDeepTree(ppList, iDepth-1);\n    p = *ppList;\n    if( p==0 ){     /*OPTIMIZATION-IF-FALSE*/\n      /* It is safe to always return here, but the resulting tree\n      ** would be unbalanced */\n      return pLeft;\n    }\n    p->pLeft = pLeft;\n    *ppList = p->pRight;\n    p->pRight = rowSetNDeepTree(ppList, iDepth-1);\n  }else{\n    p = *ppList;\n    *ppList = p->pRight;\n    p->pLeft = p->pRight = 0;\n  }\n  return p;\n}\n\n/*\n** Convert a sorted list of elements into a binary tree. Make the tree\n** as deep as it needs to be in order to contain the entire list.\n*/\nstatic struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){\n  int iDepth;           /* Depth of the tree so far */\n  struct RowSetEntry *p;       /* Current tree root */\n  struct RowSetEntry *pLeft;   /* Left subtree */\n\n  assert( pList!=0 );\n  p = pList;\n  pList = p->pRight;\n  p->pLeft = p->pRight = 0;\n  for(iDepth=1; pList; iDepth++){\n    pLeft = p;\n    p = pList;\n    pList = p->pRight;\n    p->pLeft = pLeft;\n    p->pRight = rowSetNDeepTree(&pList, iDepth);\n  }\n  return p;\n}\n\n/*\n** Extract the smallest element from the RowSet.\n** Write the element into *pRowid.  Return 1 on success.  Return\n** 0 if the RowSet is already empty.\n**\n** After this routine has been called, the sqlite3RowSetInsert()\n** routine may not be called again.\n**\n** This routine may not be called after sqlite3RowSetTest() has\n** been used.  Older versions of RowSet allowed that, but as the\n** capability was not used by the code generator, it was removed\n** for code economy.\n*/\nSQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){\n  assert( p!=0 );\n  assert( p->pForest==0 );  /* Cannot be used with sqlite3RowSetText() */\n\n  /* Merge the forest into a single sorted list on first call */\n  if( (p->rsFlags & ROWSET_NEXT)==0 ){  /*OPTIMIZATION-IF-FALSE*/\n    if( (p->rsFlags & ROWSET_SORTED)==0 ){  /*OPTIMIZATION-IF-FALSE*/\n      p->pEntry = rowSetEntrySort(p->pEntry);\n    }\n    p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;\n  }\n\n  /* Return the next entry on the list */\n  if( p->pEntry ){\n    *pRowid = p->pEntry->v;\n    p->pEntry = p->pEntry->pRight;\n    if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/\n      /* Free memory immediately, rather than waiting on sqlite3_finalize() */\n      sqlite3RowSetClear(p);\n    }\n    return 1;\n  }else{\n    return 0;\n  }\n}\n\n/*\n** Check to see if element iRowid was inserted into the rowset as\n** part of any insert batch prior to iBatch.  Return 1 or 0.\n**\n** If this is the first test of a new batch and if there exist entries\n** on pRowSet->pEntry, then sort those entries into the forest at\n** pRowSet->pForest so that they can be tested.\n*/\nSQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){\n  struct RowSetEntry *p, *pTree;\n\n  /* This routine is never called after sqlite3RowSetNext() */\n  assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );\n\n  /* Sort entries into the forest on the first test of a new batch.\n  ** To save unnecessary work, only do this when the batch number changes.\n  */\n  if( iBatch!=pRowSet->iBatch ){  /*OPTIMIZATION-IF-FALSE*/\n    p = pRowSet->pEntry;\n    if( p ){\n      struct RowSetEntry **ppPrevTree = &pRowSet->pForest;\n      if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/\n        /* Only sort the current set of entries if they need it */\n        p = rowSetEntrySort(p);\n      }\n      for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){\n        ppPrevTree = &pTree->pRight;\n        if( pTree->pLeft==0 ){\n          pTree->pLeft = rowSetListToTree(p);\n          break;\n        }else{\n          struct RowSetEntry *pAux, *pTail;\n          rowSetTreeToList(pTree->pLeft, &pAux, &pTail);\n          pTree->pLeft = 0;\n          p = rowSetEntryMerge(pAux, p);\n        }\n      }\n      if( pTree==0 ){\n        *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);\n        if( pTree ){\n          pTree->v = 0;\n          pTree->pRight = 0;\n          pTree->pLeft = rowSetListToTree(p);\n        }\n      }\n      pRowSet->pEntry = 0;\n      pRowSet->pLast = 0;\n      pRowSet->rsFlags |= ROWSET_SORTED;\n    }\n    pRowSet->iBatch = iBatch;\n  }\n\n  /* Test to see if the iRowid value appears anywhere in the forest.\n  ** Return 1 if it does and 0 if not.\n  */\n  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){\n    p = pTree->pLeft;\n    while( p ){\n      if( p->v<iRowid ){\n        p = p->pRight;\n      }else if( p->v>iRowid ){\n        p = p->pLeft;\n      }else{\n        return 1;\n      }\n    }\n  }\n  return 0;\n}\n\n/************** End of rowset.c **********************************************/\n/************** Begin file pager.c *******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This is the implementation of the page cache subsystem or \"pager\".\n** \n** The pager is used to access a database disk file.  It implements\n** atomic commit and rollback through the use of a journal file that\n** is separate from the database file.  The pager also implements file\n** locking to prevent two processes from writing the same database\n** file simultaneously, or one process from reading the database while\n** another is writing.\n*/\n#ifndef SQLITE_OMIT_DISKIO\n/* #include \"sqliteInt.h\" */\n/************** Include wal.h in the middle of pager.c ***********************/\n/************** Begin file wal.h *********************************************/\n/*\n** 2010 February 1\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This header file defines the interface to the write-ahead logging \n** system. Refer to the comments below and the header comment attached to \n** the implementation of each function in log.c for further details.\n*/\n\n#ifndef SQLITE_WAL_H\n#define SQLITE_WAL_H\n\n/* #include \"sqliteInt.h\" */\n\n/* Macros for extracting appropriate sync flags for either transaction\n** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)):\n*/\n#define WAL_SYNC_FLAGS(X)   ((X)&0x03)\n#define CKPT_SYNC_FLAGS(X)  (((X)>>2)&0x03)\n\n#ifdef SQLITE_OMIT_WAL\n# define sqlite3WalOpen(x,y,z)                   0\n# define sqlite3WalLimit(x,y)\n# define sqlite3WalClose(v,w,x,y,z)              0\n# define sqlite3WalBeginReadTransaction(y,z)     0\n# define sqlite3WalEndReadTransaction(z)\n# define sqlite3WalDbsize(y)                     0\n# define sqlite3WalBeginWriteTransaction(y)      0\n# define sqlite3WalEndWriteTransaction(x)        0\n# define sqlite3WalUndo(x,y,z)                   0\n# define sqlite3WalSavepoint(y,z)\n# define sqlite3WalSavepointUndo(y,z)            0\n# define sqlite3WalFrames(u,v,w,x,y,z)           0\n# define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0\n# define sqlite3WalCallback(z)                   0\n# define sqlite3WalExclusiveMode(y,z)            0\n# define sqlite3WalHeapMemory(z)                 0\n# define sqlite3WalFramesize(z)                  0\n# define sqlite3WalFindFrame(x,y,z)              0\n# define sqlite3WalFile(x)                       0\n#else\n\n#define WAL_SAVEPOINT_NDATA 4\n\n/* Connection to a write-ahead log (WAL) file. \n** There is one object of this type for each pager. \n*/\ntypedef struct Wal Wal;\n\n/* Open and close a connection to a write-ahead log. */\nSQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);\nSQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);\n\n/* Set the limiting size of a WAL file. */\nSQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);\n\n/* Used by readers to open (lock) and close (unlock) a snapshot.  A \n** snapshot is like a read-transaction.  It is the state of the database\n** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and\n** preserves the current state even if the other threads or processes\n** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the\n** transaction and releases the lock.\n*/\nSQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);\nSQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);\n\n/* Read a page from the write-ahead log, if it is present. */\nSQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);\nSQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);\n\n/* If the WAL is not empty, return the size of the database. */\nSQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);\n\n/* Obtain or release the WRITER lock. */\nSQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);\nSQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);\n\n/* Undo any frames written (but not committed) to the log */\nSQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);\n\n/* Return an integer that records the current (uncommitted) write\n** position in the WAL */\nSQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);\n\n/* Move the write position of the WAL back to iFrame.  Called in\n** response to a ROLLBACK TO command. */\nSQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);\n\n/* Write a frame or frames to the log. */\nSQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);\n\n/* Copy pages from the log to the database file */ \nSQLITE_PRIVATE int sqlite3WalCheckpoint(\n  Wal *pWal,                      /* Write-ahead log connection */\n  sqlite3 *db,                    /* Check this handle's interrupt flag */\n  int eMode,                      /* One of PASSIVE, FULL and RESTART */\n  int (*xBusy)(void*),            /* Function to call when busy */\n  void *pBusyArg,                 /* Context argument for xBusyHandler */\n  int sync_flags,                 /* Flags to sync db file with (or 0) */\n  int nBuf,                       /* Size of buffer nBuf */\n  u8 *zBuf,                       /* Temporary buffer to use */\n  int *pnLog,                     /* OUT: Number of frames in WAL */\n  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */\n);\n\n/* Return the value to pass to a sqlite3_wal_hook callback, the\n** number of frames in the WAL at the point of the last commit since\n** sqlite3WalCallback() was called.  If no commits have occurred since\n** the last call, then return 0.\n*/\nSQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);\n\n/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)\n** by the pager layer on the database file.\n*/\nSQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);\n\n/* Return true if the argument is non-NULL and the WAL module is using\n** heap-memory for the wal-index. Otherwise, if the argument is NULL or the\n** WAL module is using shared-memory, return false. \n*/\nSQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);\n\n#ifdef SQLITE_ENABLE_SNAPSHOT\nSQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);\nSQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);\nSQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);\nSQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot);\nSQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal);\n#endif\n\n#ifdef SQLITE_ENABLE_ZIPVFS\n/* If the WAL file is not empty, return the number of bytes of content\n** stored in each frame (i.e. the db page-size when the WAL was created).\n*/\nSQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);\n#endif\n\n/* Return the sqlite3_file object for the WAL file */\nSQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);\n\n#ifdef SQLITE_ENABLE_SETLK_TIMEOUT\nSQLITE_PRIVATE int sqlite3WalWriteLock(Wal *pWal, int bLock);\nSQLITE_PRIVATE void sqlite3WalDb(Wal *pWal, sqlite3 *db);\n#endif\n\n#endif /* ifndef SQLITE_OMIT_WAL */\n#endif /* SQLITE_WAL_H */\n\n/************** End of wal.h *************************************************/\n/************** Continuing where we left off in pager.c **********************/\n\n\n/******************* NOTES ON THE DESIGN OF THE PAGER ************************\n**\n** This comment block describes invariants that hold when using a rollback\n** journal.  These invariants do not apply for journal_mode=WAL,\n** journal_mode=MEMORY, or journal_mode=OFF.\n**\n** Within this comment block, a page is deemed to have been synced\n** automatically as soon as it is written when PRAGMA synchronous=OFF.\n** Otherwise, the page is not synced until the xSync method of the VFS\n** is called successfully on the file containing the page.\n**\n** Definition:  A page of the database file is said to be \"overwriteable\" if\n** one or more of the following are true about the page:\n** \n**     (a)  The original content of the page as it was at the beginning of\n**          the transaction has been written into the rollback journal and\n**          synced.\n** \n**     (b)  The page was a freelist leaf page at the start of the transaction.\n** \n**     (c)  The page number is greater than the largest page that existed in\n**          the database file at the start of the transaction.\n** \n** (1) A page of the database file is never overwritten unless one of the\n**     following are true:\n** \n**     (a) The page and all other pages on the same sector are overwriteable.\n** \n**     (b) The atomic page write optimization is enabled, and the entire\n**         transaction other than the update of the transaction sequence\n**         number consists of a single page change.\n** \n** (2) The content of a page written into the rollback journal exactly matches\n**     both the content in the database when the rollback journal was written\n**     and the content in the database at the beginning of the current\n**     transaction.\n** \n** (3) Writes to the database file are an integer multiple of the page size\n**     in length and are aligned on a page boundary.\n** \n** (4) Reads from the database file are either aligned on a page boundary and\n**     an integer multiple of the page size in length or are taken from the\n**     first 100 bytes of the database file.\n** \n** (5) All writes to the database file are synced prior to the rollback journal\n**     being deleted, truncated, or zeroed.\n** \n** (6) If a master journal file is used, then all writes to the database file\n**     are synced prior to the master journal being deleted.\n** \n** Definition: Two databases (or the same database at two points it time)\n** are said to be \"logically equivalent\" if they give the same answer to\n** all queries.  Note in particular the content of freelist leaf\n** pages can be changed arbitrarily without affecting the logical equivalence\n** of the database.\n** \n** (7) At any time, if any subset, including the empty set and the total set,\n**     of the unsynced changes to a rollback journal are removed and the \n**     journal is rolled back, the resulting database file will be logically\n**     equivalent to the database file at the beginning of the transaction.\n** \n** (8) When a transaction is rolled back, the xTruncate method of the VFS\n**     is called to restore the database file to the same size it was at\n**     the beginning of the transaction.  (In some VFSes, the xTruncate\n**     method is a no-op, but that does not change the fact the SQLite will\n**     invoke it.)\n** \n** (9) Whenever the database file is modified, at least one bit in the range\n**     of bytes from 24 through 39 inclusive will be changed prior to releasing\n**     the EXCLUSIVE lock, thus signaling other connections on the same\n**     database to flush their caches.\n**\n** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less\n**      than one billion transactions.\n**\n** (11) A database file is well-formed at the beginning and at the conclusion\n**      of every transaction.\n**\n** (12) An EXCLUSIVE lock is held on the database file when writing to\n**      the database file.\n**\n** (13) A SHARED lock is held on the database file while reading any\n**      content out of the database file.\n**\n******************************************************************************/\n\n/*\n** Macros for troubleshooting.  Normally turned off\n*/\n#if 0\nint sqlite3PagerTrace=1;  /* True to enable tracing */\n#define sqlite3DebugPrintf printf\n#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }\n#else\n#define PAGERTRACE(X)\n#endif\n\n/*\n** The following two macros are used within the PAGERTRACE() macros above\n** to print out file-descriptors. \n**\n** PAGERID() takes a pointer to a Pager struct as its argument. The\n** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file\n** struct as its argument.\n*/\n#define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))\n#define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd))\n\n/*\n** The Pager.eState variable stores the current 'state' of a pager. A\n** pager may be in any one of the seven states shown in the following\n** state diagram.\n**\n**                            OPEN <------+------+\n**                              |         |      |\n**                              V         |      |\n**               +---------> READER-------+      |\n**               |              |                |\n**               |              V                |\n**               |<-------WRITER_LOCKED------> ERROR\n**               |              |                ^  \n**               |              V                |\n**               |<------WRITER_CACHEMOD-------->|\n**               |              |                |\n**               |              V                |\n**               |<-------WRITER_DBMOD---------->|\n**               |              |                |\n**               |              V                |\n**               +<------WRITER_FINISHED-------->+\n**\n**\n** List of state transitions and the C [function] that performs each:\n** \n**   OPEN              -> READER              [sqlite3PagerSharedLock]\n**   READER            -> OPEN                [pager_unlock]\n**\n**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]\n**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]\n**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]\n**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]\n**   WRITER_***        -> READER              [pager_end_transaction]\n**\n**   WRITER_***        -> ERROR               [pager_error]\n**   ERROR             -> OPEN                [pager_unlock]\n** \n**\n**  OPEN:\n**\n**    The pager starts up in this state. Nothing is guaranteed in this\n**    state - the file may or may not be locked and the database size is\n**    unknown. The database may not be read or written.\n**\n**    * No read or write transaction is active.\n**    * Any lock, or no lock at all, may be held on the database file.\n**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.\n**\n**  READER:\n**\n**    In this state all the requirements for reading the database in \n**    rollback (non-WAL) mode are met. Unless the pager is (or recently\n**    was) in exclusive-locking mode, a user-level read transaction is \n**    open. The database size is known in this state.\n**\n**    A connection running with locking_mode=normal enters this state when\n**    it opens a read-transaction on the database and returns to state\n**    OPEN after the read-transaction is completed. However a connection\n**    running in locking_mode=exclusive (including temp databases) remains in\n**    this state even after the read-transaction is closed. The only way\n**    a locking_mode=exclusive connection can transition from READER to OPEN\n**    is via the ERROR state (see below).\n** \n**    * A read transaction may be active (but a write-transaction cannot).\n**    * A SHARED or greater lock is held on the database file.\n**    * The dbSize variable may be trusted (even if a user-level read \n**      transaction is not active). The dbOrigSize and dbFileSize variables\n**      may not be trusted at this point.\n**    * If the database is a WAL database, then the WAL connection is open.\n**    * Even if a read-transaction is not open, it is guaranteed that \n**      there is no hot-journal in the file-system.\n**\n**  WRITER_LOCKED:\n**\n**    The pager moves to this state from READER when a write-transaction\n**    is first opened on the database. In WRITER_LOCKED state, all locks \n**    required to start a write-transaction are held, but no actual \n**    modifications to the cache or database have taken place.\n**\n**    In rollback mode, a RESERVED or (if the transaction was opened with \n**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when\n**    moving to this state, but the journal file is not written to or opened \n**    to in this state. If the transaction is committed or rolled back while \n**    in WRITER_LOCKED state, all that is required is to unlock the database \n**    file.\n**\n**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.\n**    If the connection is running with locking_mode=exclusive, an attempt\n**    is made to obtain an EXCLUSIVE lock on the database file.\n**\n**    * A write transaction is active.\n**    * If the connection is open in rollback-mode, a RESERVED or greater \n**      lock is held on the database file.\n**    * If the connection is open in WAL-mode, a WAL write transaction\n**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully\n**      called).\n**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.\n**    * The contents of the pager cache have not been modified.\n**    * The journal file may or may not be open.\n**    * Nothing (not even the first header) has been written to the journal.\n**\n**  WRITER_CACHEMOD:\n**\n**    A pager moves from WRITER_LOCKED state to this state when a page is\n**    first modified by the upper layer. In rollback mode the journal file\n**    is opened (if it is not already open) and a header written to the\n**    start of it. The database file on disk has not been modified.\n**\n**    * A write transaction is active.\n**    * A RESERVED or greater lock is held on the database file.\n**    * The journal file is open and the first header has been written \n**      to it, but the header has not been synced to disk.\n**    * The contents of the page cache have been modified.\n**\n**  WRITER_DBMOD:\n**\n**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state\n**    when it modifies the contents of the database file. WAL connections\n**    never enter this state (since they do not modify the database file,\n**    just the log file).\n**\n**    * A write transaction is active.\n**    * An EXCLUSIVE or greater lock is held on the database file.\n**    * The journal file is open and the first header has been written \n**      and synced to disk.\n**    * The contents of the page cache have been modified (and possibly\n**      written to disk).\n**\n**  WRITER_FINISHED:\n**\n**    It is not possible for a WAL connection to enter this state.\n**\n**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD\n**    state after the entire transaction has been successfully written into the\n**    database file. In this state the transaction may be committed simply\n**    by finalizing the journal file. Once in WRITER_FINISHED state, it is \n**    not possible to modify the database further. At this point, the upper \n**    layer must either commit or rollback the transaction.\n**\n**    * A write transaction is active.\n**    * An EXCLUSIVE or greater lock is held on the database file.\n**    * All writing and syncing of journal and database data has finished.\n**      If no error occurred, all that remains is to finalize the journal to\n**      commit the transaction. If an error did occur, the caller will need\n**      to rollback the transaction. \n**\n**  ERROR:\n**\n**    The ERROR state is entered when an IO or disk-full error (including\n**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it \n**    difficult to be sure that the in-memory pager state (cache contents, \n**    db size etc.) are consistent with the contents of the file-system.\n**\n**    Temporary pager files may enter the ERROR state, but in-memory pagers\n**    cannot.\n**\n**    For example, if an IO error occurs while performing a rollback, \n**    the contents of the page-cache may be left in an inconsistent state.\n**    At this point it would be dangerous to change back to READER state\n**    (as usually happens after a rollback). Any subsequent readers might\n**    report database corruption (due to the inconsistent cache), and if\n**    they upgrade to writers, they may inadvertently corrupt the database\n**    file. To avoid this hazard, the pager switches into the ERROR state\n**    instead of READER following such an error.\n**\n**    Once it has entered the ERROR state, any attempt to use the pager\n**    to read or write data returns an error. Eventually, once all \n**    outstanding transactions have been abandoned, the pager is able to\n**    transition back to OPEN state, discarding the contents of the \n**    page-cache and any other in-memory state at the same time. Everything\n**    is reloaded from disk (and, if necessary, hot-journal rollback peformed)\n**    when a read-transaction is next opened on the pager (transitioning\n**    the pager into READER state). At that point the system has recovered \n**    from the error.\n**\n**    Specifically, the pager jumps into the ERROR state if:\n**\n**      1. An error occurs while attempting a rollback. This happens in\n**         function sqlite3PagerRollback().\n**\n**      2. An error occurs while attempting to finalize a journal file\n**         following a commit in function sqlite3PagerCommitPhaseTwo().\n**\n**      3. An error occurs while attempting to write to the journal or\n**         database file in function pagerStress() in order to free up\n**         memory.\n**\n**    In other cases, the error is returned to the b-tree layer. The b-tree\n**    layer then attempts a rollback operation. If the error condition \n**    persists, the pager enters the ERROR state via condition (1) above.\n**\n**    Condition (3) is necessary because it can be triggered by a read-only\n**    statement executed within a transaction. In this case, if the error\n**    code were simply returned to the user, the b-tree layer would not\n**    automatically attempt a rollback, as it assumes that an error in a\n**    read-only statement cannot leave the pager in an internally inconsistent \n**    state.\n**\n**    * The Pager.errCode variable is set to something other than SQLITE_OK.\n**    * There are one or more outstanding references to pages (after the\n**      last reference is dropped the pager should move back to OPEN state).\n**    * The pager is not an in-memory pager.\n**    \n**\n** Notes:\n**\n**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the\n**     connection is open in WAL mode. A WAL connection is always in one\n**     of the first four states.\n**\n**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN\n**     state. There are two exceptions: immediately after exclusive-mode has\n**     been turned on (and before any read or write transactions are \n**     executed), and when the pager is leaving the \"error state\".\n**\n**   * See also: assert_pager_state().\n*/\n#define PAGER_OPEN                  0\n#define PAGER_READER                1\n#define PAGER_WRITER_LOCKED         2\n#define PAGER_WRITER_CACHEMOD       3\n#define PAGER_WRITER_DBMOD          4\n#define PAGER_WRITER_FINISHED       5\n#define PAGER_ERROR                 6\n\n/*\n** The Pager.eLock variable is almost always set to one of the \n** following locking-states, according to the lock currently held on\n** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.\n** This variable is kept up to date as locks are taken and released by\n** the pagerLockDb() and pagerUnlockDb() wrappers.\n**\n** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY\n** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not\n** the operation was successful. In these circumstances pagerLockDb() and\n** pagerUnlockDb() take a conservative approach - eLock is always updated\n** when unlocking the file, and only updated when locking the file if the\n** VFS call is successful. This way, the Pager.eLock variable may be set\n** to a less exclusive (lower) value than the lock that is actually held\n** at the system level, but it is never set to a more exclusive value.\n**\n** This is usually safe. If an xUnlock fails or appears to fail, there may \n** be a few redundant xLock() calls or a lock may be held for longer than\n** required, but nothing really goes wrong.\n**\n** The exception is when the database file is unlocked as the pager moves\n** from ERROR to OPEN state. At this point there may be a hot-journal file \n** in the file-system that needs to be rolled back (as part of an OPEN->SHARED\n** transition, by the same pager or any other). If the call to xUnlock()\n** fails at this point and the pager is left holding an EXCLUSIVE lock, this\n** can confuse the call to xCheckReservedLock() call made later as part\n** of hot-journal detection.\n**\n** xCheckReservedLock() is defined as returning true \"if there is a RESERVED \n** lock held by this process or any others\". So xCheckReservedLock may \n** return true because the caller itself is holding an EXCLUSIVE lock (but\n** doesn't know it because of a previous error in xUnlock). If this happens\n** a hot-journal may be mistaken for a journal being created by an active\n** transaction in another process, causing SQLite to read from the database\n** without rolling it back.\n**\n** To work around this, if a call to xUnlock() fails when unlocking the\n** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It\n** is only changed back to a real locking state after a successful call\n** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition\n** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK \n** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE\n** lock on the database file before attempting to roll it back. See function\n** PagerSharedLock() for more detail.\n**\n** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in \n** PAGER_OPEN state.\n*/\n#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)\n\n/*\n** The maximum allowed sector size. 64KiB. If the xSectorsize() method \n** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.\n** This could conceivably cause corruption following a power failure on\n** such a system. This is currently an undocumented limit.\n*/\n#define MAX_SECTOR_SIZE 0x10000\n\n\n/*\n** An instance of the following structure is allocated for each active\n** savepoint and statement transaction in the system. All such structures\n** are stored in the Pager.aSavepoint[] array, which is allocated and\n** resized using sqlite3Realloc().\n**\n** When a savepoint is created, the PagerSavepoint.iHdrOffset field is\n** set to 0. If a journal-header is written into the main journal while\n** the savepoint is active, then iHdrOffset is set to the byte offset \n** immediately following the last journal record written into the main\n** journal before the journal-header. This is required during savepoint\n** rollback (see pagerPlaybackSavepoint()).\n*/\ntypedef struct PagerSavepoint PagerSavepoint;\nstruct PagerSavepoint {\n  i64 iOffset;                 /* Starting offset in main journal */\n  i64 iHdrOffset;              /* See above */\n  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */\n  Pgno nOrig;                  /* Original number of pages in file */\n  Pgno iSubRec;                /* Index of first record in sub-journal */\n#ifndef SQLITE_OMIT_WAL\n  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */\n#endif\n};\n\n/*\n** Bits of the Pager.doNotSpill flag.  See further description below.\n*/\n#define SPILLFLAG_OFF         0x01 /* Never spill cache.  Set via pragma */\n#define SPILLFLAG_ROLLBACK    0x02 /* Current rolling back, so do not spill */\n#define SPILLFLAG_NOSYNC      0x04 /* Spill is ok, but do not sync */\n\n/*\n** An open page cache is an instance of struct Pager. A description of\n** some of the more important member variables follows:\n**\n** eState\n**\n**   The current 'state' of the pager object. See the comment and state\n**   diagram above for a description of the pager state.\n**\n** eLock\n**\n**   For a real on-disk database, the current lock held on the database file -\n**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.\n**\n**   For a temporary or in-memory database (neither of which require any\n**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such\n**   databases always have Pager.exclusiveMode==1, this tricks the pager\n**   logic into thinking that it already has all the locks it will ever\n**   need (and no reason to release them).\n**\n**   In some (obscure) circumstances, this variable may also be set to\n**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for\n**   details.\n**\n** changeCountDone\n**\n**   This boolean variable is used to make sure that the change-counter \n**   (the 4-byte header field at byte offset 24 of the database file) is \n**   not updated more often than necessary. \n**\n**   It is set to true when the change-counter field is updated, which \n**   can only happen if an exclusive lock is held on the database file.\n**   It is cleared (set to false) whenever an exclusive lock is \n**   relinquished on the database file. Each time a transaction is committed,\n**   The changeCountDone flag is inspected. If it is true, the work of\n**   updating the change-counter is omitted for the current transaction.\n**\n**   This mechanism means that when running in exclusive mode, a connection \n**   need only update the change-counter once, for the first transaction\n**   committed.\n**\n** setMaster\n**\n**   When PagerCommitPhaseOne() is called to commit a transaction, it may\n**   (or may not) specify a master-journal name to be written into the \n**   journal file before it is synced to disk.\n**\n**   Whether or not a journal file contains a master-journal pointer affects \n**   the way in which the journal file is finalized after the transaction is \n**   committed or rolled back when running in \"journal_mode=PERSIST\" mode.\n**   If a journal file does not contain a master-journal pointer, it is\n**   finalized by overwriting the first journal header with zeroes. If\n**   it does contain a master-journal pointer the journal file is finalized \n**   by truncating it to zero bytes, just as if the connection were \n**   running in \"journal_mode=truncate\" mode.\n**\n**   Journal files that contain master journal pointers cannot be finalized\n**   simply by overwriting the first journal-header with zeroes, as the\n**   master journal pointer could interfere with hot-journal rollback of any\n**   subsequently interrupted transaction that reuses the journal file.\n**\n**   The flag is cleared as soon as the journal file is finalized (either\n**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the\n**   journal file from being successfully finalized, the setMaster flag\n**   is cleared anyway (and the pager will move to ERROR state).\n**\n** doNotSpill\n**\n**   This variables control the behavior of cache-spills  (calls made by\n**   the pcache module to the pagerStress() routine to write cached data\n**   to the file-system in order to free up memory).\n**\n**   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,\n**   writing to the database from pagerStress() is disabled altogether.\n**   The SPILLFLAG_ROLLBACK case is done in a very obscure case that\n**   comes up during savepoint rollback that requires the pcache module\n**   to allocate a new page to prevent the journal file from being written\n**   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF\n**   case is a user preference.\n** \n**   If the SPILLFLAG_NOSYNC bit is set, writing to the database from\n**   pagerStress() is permitted, but syncing the journal file is not.\n**   This flag is set by sqlite3PagerWrite() when the file-system sector-size\n**   is larger than the database page-size in order to prevent a journal sync\n**   from happening in between the journalling of two pages on the same sector. \n**\n** subjInMemory\n**\n**   This is a boolean variable. If true, then any required sub-journal\n**   is opened as an in-memory journal file. If false, then in-memory\n**   sub-journals are only used for in-memory pager files.\n**\n**   This variable is updated by the upper layer each time a new \n**   write-transaction is opened.\n**\n** dbSize, dbOrigSize, dbFileSize\n**\n**   Variable dbSize is set to the number of pages in the database file.\n**   It is valid in PAGER_READER and higher states (all states except for\n**   OPEN and ERROR). \n**\n**   dbSize is set based on the size of the database file, which may be \n**   larger than the size of the database (the value stored at offset\n**   28 of the database header by the btree). If the size of the file\n**   is not an integer multiple of the page-size, the value stored in\n**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).\n**   Except, any file that is greater than 0 bytes in size is considered\n**   to have at least one page. (i.e. a 1KB file with 2K page-size leads\n**   to dbSize==1).\n**\n**   During a write-transaction, if pages with page-numbers greater than\n**   dbSize are modified in the cache, dbSize is updated accordingly.\n**   Similarly, if the database is truncated using PagerTruncateImage(), \n**   dbSize is updated.\n**\n**   Variables dbOrigSize and dbFileSize are valid in states \n**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize\n**   variable at the start of the transaction. It is used during rollback,\n**   and to determine whether or not pages need to be journalled before\n**   being modified.\n**\n**   Throughout a write-transaction, dbFileSize contains the size of\n**   the file on disk in pages. It is set to a copy of dbSize when the\n**   write-transaction is first opened, and updated when VFS calls are made\n**   to write or truncate the database file on disk. \n**\n**   The only reason the dbFileSize variable is required is to suppress \n**   unnecessary calls to xTruncate() after committing a transaction. If, \n**   when a transaction is committed, the dbFileSize variable indicates \n**   that the database file is larger than the database image (Pager.dbSize), \n**   pager_truncate() is called. The pager_truncate() call uses xFilesize()\n**   to measure the database file on disk, and then truncates it if required.\n**   dbFileSize is not used when rolling back a transaction. In this case\n**   pager_truncate() is called unconditionally (which means there may be\n**   a call to xFilesize() that is not strictly required). In either case,\n**   pager_truncate() may cause the file to become smaller or larger.\n**\n** dbHintSize\n**\n**   The dbHintSize variable is used to limit the number of calls made to\n**   the VFS xFileControl(FCNTL_SIZE_HINT) method. \n**\n**   dbHintSize is set to a copy of the dbSize variable when a\n**   write-transaction is opened (at the same time as dbFileSize and\n**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,\n**   dbHintSize is increased to the number of pages that correspond to the\n**   size-hint passed to the method call. See pager_write_pagelist() for \n**   details.\n**\n** errCode\n**\n**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It\n**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode \n**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX \n**   sub-codes.\n**\n** syncFlags, walSyncFlags\n**\n**   syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03).\n**   syncFlags is used for rollback mode.  walSyncFlags is used for WAL mode\n**   and contains the flags used to sync the checkpoint operations in the\n**   lower two bits, and sync flags used for transaction commits in the WAL\n**   file in bits 0x04 and 0x08.  In other words, to get the correct sync flags\n**   for checkpoint operations, use (walSyncFlags&0x03) and to get the correct\n**   sync flags for transaction commit, use ((walSyncFlags>>2)&0x03).  Note\n**   that with synchronous=NORMAL in WAL mode, transaction commit is not synced\n**   meaning that the 0x04 and 0x08 bits are both zero.\n*/\nstruct Pager {\n  sqlite3_vfs *pVfs;          /* OS functions to use for IO */\n  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */\n  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */\n  u8 useJournal;              /* Use a rollback journal on this file */\n  u8 noSync;                  /* Do not sync the journal if true */\n  u8 fullSync;                /* Do extra syncs of the journal for robustness */\n  u8 extraSync;               /* sync directory after journal delete */\n  u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */\n  u8 walSyncFlags;            /* See description above */\n  u8 tempFile;                /* zFilename is a temporary or immutable file */\n  u8 noLock;                  /* Do not lock (except in WAL mode) */\n  u8 readOnly;                /* True for a read-only database */\n  u8 memDb;                   /* True to inhibit all file I/O */\n\n  /**************************************************************************\n  ** The following block contains those class members that change during\n  ** routine operation.  Class members not in this block are either fixed\n  ** when the pager is first created or else only change when there is a\n  ** significant mode change (such as changing the page_size, locking_mode,\n  ** or the journal_mode).  From another view, these class members describe\n  ** the \"state\" of the pager, while other class members describe the\n  ** \"configuration\" of the pager.\n  */\n  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */\n  u8 eLock;                   /* Current lock held on database file */\n  u8 changeCountDone;         /* Set after incrementing the change-counter */\n  u8 setMaster;               /* True if a m-j name has been written to jrnl */\n  u8 doNotSpill;              /* Do not spill the cache when non-zero */\n  u8 subjInMemory;            /* True to use in-memory sub-journals */\n  u8 bUseFetch;               /* True to use xFetch() */\n  u8 hasHeldSharedLock;       /* True if a shared lock has ever been held */\n  Pgno dbSize;                /* Number of pages in the database */\n  Pgno dbOrigSize;            /* dbSize before the current transaction */\n  Pgno dbFileSize;            /* Number of pages in the database file */\n  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */\n  int errCode;                /* One of several kinds of errors */\n  int nRec;                   /* Pages journalled since last j-header written */\n  u32 cksumInit;              /* Quasi-random value added to every checksum */\n  u32 nSubRec;                /* Number of records written to sub-journal */\n  Bitvec *pInJournal;         /* One bit for each page in the database file */\n  sqlite3_file *fd;           /* File descriptor for database */\n  sqlite3_file *jfd;          /* File descriptor for main journal */\n  sqlite3_file *sjfd;         /* File descriptor for sub-journal */\n  i64 journalOff;             /* Current write offset in the journal file */\n  i64 journalHdr;             /* Byte offset to previous journal header */\n  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */\n  PagerSavepoint *aSavepoint; /* Array of active savepoints */\n  int nSavepoint;             /* Number of elements in aSavepoint[] */\n  u32 iDataVersion;           /* Changes whenever database content changes */\n  char dbFileVers[16];        /* Changes whenever database file changes */\n\n  int nMmapOut;               /* Number of mmap pages currently outstanding */\n  sqlite3_int64 szMmap;       /* Desired maximum mmap size */\n  PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */\n  /*\n  ** End of the routinely-changing class members\n  ***************************************************************************/\n\n  u16 nExtra;                 /* Add this many bytes to each in-memory page */\n  i16 nReserve;               /* Number of unused bytes at end of each page */\n  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */\n  u32 sectorSize;             /* Assumed sector size during rollback */\n  int pageSize;               /* Number of bytes in a page */\n  Pgno mxPgno;                /* Maximum allowed size of the database */\n  i64 journalSizeLimit;       /* Size limit for persistent journal files */\n  char *zFilename;            /* Name of the database file */\n  char *zJournal;             /* Name of the journal file */\n  int (*xBusyHandler)(void*); /* Function to call when busy */\n  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */\n  int aStat[4];               /* Total cache hits, misses, writes, spills */\n#ifdef SQLITE_TEST\n  int nRead;                  /* Database pages read */\n#endif\n  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */\n  int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */\n  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */\n  PCache *pPCache;            /* Pointer to page cache object */\n#ifndef SQLITE_OMIT_WAL\n  Wal *pWal;                  /* Write-ahead log used by \"journal_mode=wal\" */\n  char *zWal;                 /* File name for write-ahead log */\n#endif\n};\n\n/*\n** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains\n** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS \n** or CACHE_WRITE to sqlite3_db_status().\n*/\n#define PAGER_STAT_HIT   0\n#define PAGER_STAT_MISS  1\n#define PAGER_STAT_WRITE 2\n#define PAGER_STAT_SPILL 3\n\n/*\n** The following global variables hold counters used for\n** testing purposes only.  These variables do not exist in\n** a non-testing build.  These variables are not thread-safe.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */\nSQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */\nSQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */\n# define PAGER_INCR(v)  v++\n#else\n# define PAGER_INCR(v)\n#endif\n\n\n\n/*\n** Journal files begin with the following magic string.  The data\n** was obtained from /dev/random.  It is used only as a sanity check.\n**\n** Since version 2.8.0, the journal format contains additional sanity\n** checking information.  If the power fails while the journal is being\n** written, semi-random garbage data might appear in the journal\n** file after power is restored.  If an attempt is then made\n** to roll the journal back, the database could be corrupted.  The additional\n** sanity checking data is an attempt to discover the garbage in the\n** journal and ignore it.\n**\n** The sanity checking information for the new journal format consists\n** of a 32-bit checksum on each page of data.  The checksum covers both\n** the page number and the pPager->pageSize bytes of data for the page.\n** This cksum is initialized to a 32-bit random value that appears in the\n** journal file right after the header.  The random initializer is important,\n** because garbage data that appears at the end of a journal is likely\n** data that was once in other files that have now been deleted.  If the\n** garbage data came from an obsolete journal file, the checksums might\n** be correct.  But by initializing the checksum to random value which\n** is different for every journal, we minimize that risk.\n*/\nstatic const unsigned char aJournalMagic[] = {\n  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,\n};\n\n/*\n** The size of the of each page record in the journal is given by\n** the following macro.\n*/\n#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)\n\n/*\n** The journal header size for this pager. This is usually the same \n** size as a single disk sector. See also setSectorSize().\n*/\n#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)\n\n/*\n** The macro MEMDB is true if we are dealing with an in-memory database.\n** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,\n** the value of MEMDB will be a constant and the compiler will optimize\n** out code that would never execute.\n*/\n#ifdef SQLITE_OMIT_MEMORYDB\n# define MEMDB 0\n#else\n# define MEMDB pPager->memDb\n#endif\n\n/*\n** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch\n** interfaces to access the database using memory-mapped I/O.\n*/\n#if SQLITE_MAX_MMAP_SIZE>0\n# define USEFETCH(x) ((x)->bUseFetch)\n#else\n# define USEFETCH(x) 0\n#endif\n\n/*\n** The maximum legal page number is (2^31 - 1).\n*/\n#define PAGER_MAX_PGNO 2147483647\n\n/*\n** The argument to this macro is a file descriptor (type sqlite3_file*).\n** Return 0 if it is not open, or non-zero (but not 1) if it is.\n**\n** This is so that expressions can be written as:\n**\n**   if( isOpen(pPager->jfd) ){ ...\n**\n** instead of\n**\n**   if( pPager->jfd->pMethods ){ ...\n*/\n#define isOpen(pFd) ((pFd)->pMethods!=0)\n\n#ifdef SQLITE_DIRECT_OVERFLOW_READ\n/*\n** Return true if page pgno can be read directly from the database file\n** by the b-tree layer. This is the case if:\n**\n**   * the database file is open,\n**   * there are no dirty pages in the cache, and\n**   * the desired page is not currently in the wal file.\n*/\nSQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){\n  if( pPager->fd->pMethods==0 ) return 0;\n  if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0;\n#ifndef SQLITE_OMIT_WAL\n  if( pPager->pWal ){\n    u32 iRead = 0;\n    int rc;\n    rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);\n    return (rc==SQLITE_OK && iRead==0);\n  }\n#endif\n  return 1;\n}\n#endif\n\n#ifndef SQLITE_OMIT_WAL\n# define pagerUseWal(x) ((x)->pWal!=0)\n#else\n# define pagerUseWal(x) 0\n# define pagerRollbackWal(x) 0\n# define pagerWalFrames(v,w,x,y) 0\n# define pagerOpenWalIfPresent(z) SQLITE_OK\n# define pagerBeginReadTransaction(z) SQLITE_OK\n#endif\n\n#ifndef NDEBUG \n/*\n** Usage:\n**\n**   assert( assert_pager_state(pPager) );\n**\n** This function runs many asserts to try to find inconsistencies in\n** the internal state of the Pager object.\n*/\nstatic int assert_pager_state(Pager *p){\n  Pager *pPager = p;\n\n  /* State must be valid. */\n  assert( p->eState==PAGER_OPEN\n       || p->eState==PAGER_READER\n       || p->eState==PAGER_WRITER_LOCKED\n       || p->eState==PAGER_WRITER_CACHEMOD\n       || p->eState==PAGER_WRITER_DBMOD\n       || p->eState==PAGER_WRITER_FINISHED\n       || p->eState==PAGER_ERROR\n  );\n\n  /* Regardless of the current state, a temp-file connection always behaves\n  ** as if it has an exclusive lock on the database file. It never updates\n  ** the change-counter field, so the changeCountDone flag is always set.\n  */\n  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );\n  assert( p->tempFile==0 || pPager->changeCountDone );\n\n  /* If the useJournal flag is clear, the journal-mode must be \"OFF\". \n  ** And if the journal-mode is \"OFF\", the journal file must not be open.\n  */\n  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );\n  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );\n\n  /* Check that MEMDB implies noSync. And an in-memory journal. Since \n  ** this means an in-memory pager performs no IO at all, it cannot encounter \n  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing \n  ** a journal file. (although the in-memory journal implementation may \n  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It \n  ** is therefore not possible for an in-memory pager to enter the ERROR \n  ** state.\n  */\n  if( MEMDB ){\n    assert( !isOpen(p->fd) );\n    assert( p->noSync );\n    assert( p->journalMode==PAGER_JOURNALMODE_OFF \n         || p->journalMode==PAGER_JOURNALMODE_MEMORY \n    );\n    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );\n    assert( pagerUseWal(p)==0 );\n  }\n\n  /* If changeCountDone is set, a RESERVED lock or greater must be held\n  ** on the file.\n  */\n  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );\n  assert( p->eLock!=PENDING_LOCK );\n\n  switch( p->eState ){\n    case PAGER_OPEN:\n      assert( !MEMDB );\n      assert( pPager->errCode==SQLITE_OK );\n      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );\n      break;\n\n    case PAGER_READER:\n      assert( pPager->errCode==SQLITE_OK );\n      assert( p->eLock!=UNKNOWN_LOCK );\n      assert( p->eLock>=SHARED_LOCK );\n      break;\n\n    case PAGER_WRITER_LOCKED:\n      assert( p->eLock!=UNKNOWN_LOCK );\n      assert( pPager->errCode==SQLITE_OK );\n      if( !pagerUseWal(pPager) ){\n        assert( p->eLock>=RESERVED_LOCK );\n      }\n      assert( pPager->dbSize==pPager->dbOrigSize );\n      assert( pPager->dbOrigSize==pPager->dbFileSize );\n      assert( pPager->dbOrigSize==pPager->dbHintSize );\n      assert( pPager->setMaster==0 );\n      break;\n\n    case PAGER_WRITER_CACHEMOD:\n      assert( p->eLock!=UNKNOWN_LOCK );\n      assert( pPager->errCode==SQLITE_OK );\n      if( !pagerUseWal(pPager) ){\n        /* It is possible that if journal_mode=wal here that neither the\n        ** journal file nor the WAL file are open. This happens during\n        ** a rollback transaction that switches from journal_mode=off\n        ** to journal_mode=wal.\n        */\n        assert( p->eLock>=RESERVED_LOCK );\n        assert( isOpen(p->jfd) \n             || p->journalMode==PAGER_JOURNALMODE_OFF \n             || p->journalMode==PAGER_JOURNALMODE_WAL \n        );\n      }\n      assert( pPager->dbOrigSize==pPager->dbFileSize );\n      assert( pPager->dbOrigSize==pPager->dbHintSize );\n      break;\n\n    case PAGER_WRITER_DBMOD:\n      assert( p->eLock==EXCLUSIVE_LOCK );\n      assert( pPager->errCode==SQLITE_OK );\n      assert( !pagerUseWal(pPager) );\n      assert( p->eLock>=EXCLUSIVE_LOCK );\n      assert( isOpen(p->jfd) \n           || p->journalMode==PAGER_JOURNALMODE_OFF \n           || p->journalMode==PAGER_JOURNALMODE_WAL \n           || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)\n      );\n      assert( pPager->dbOrigSize<=pPager->dbHintSize );\n      break;\n\n    case PAGER_WRITER_FINISHED:\n      assert( p->eLock==EXCLUSIVE_LOCK );\n      assert( pPager->errCode==SQLITE_OK );\n      assert( !pagerUseWal(pPager) );\n      assert( isOpen(p->jfd) \n           || p->journalMode==PAGER_JOURNALMODE_OFF \n           || p->journalMode==PAGER_JOURNALMODE_WAL \n           || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)\n      );\n      break;\n\n    case PAGER_ERROR:\n      /* There must be at least one outstanding reference to the pager if\n      ** in ERROR state. Otherwise the pager should have already dropped\n      ** back to OPEN state.\n      */\n      assert( pPager->errCode!=SQLITE_OK );\n      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );\n      break;\n  }\n\n  return 1;\n}\n#endif /* ifndef NDEBUG */\n\n#ifdef SQLITE_DEBUG \n/*\n** Return a pointer to a human readable string in a static buffer\n** containing the state of the Pager object passed as an argument. This\n** is intended to be used within debuggers. For example, as an alternative\n** to \"print *pPager\" in gdb:\n**\n** (gdb) printf \"%s\", print_pager_state(pPager)\n**\n** This routine has external linkage in order to suppress compiler warnings\n** about an unused function.  It is enclosed within SQLITE_DEBUG and so does\n** not appear in normal builds.\n*/\nchar *print_pager_state(Pager *p){\n  static char zRet[1024];\n\n  sqlite3_snprintf(1024, zRet,\n      \"Filename:      %s\\n\"\n      \"State:         %s errCode=%d\\n\"\n      \"Lock:          %s\\n\"\n      \"Locking mode:  locking_mode=%s\\n\"\n      \"Journal mode:  journal_mode=%s\\n\"\n      \"Backing store: tempFile=%d memDb=%d useJournal=%d\\n\"\n      \"Journal:       journalOff=%lld journalHdr=%lld\\n\"\n      \"Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\\n\"\n      , p->zFilename\n      , p->eState==PAGER_OPEN            ? \"OPEN\" :\n        p->eState==PAGER_READER          ? \"READER\" :\n        p->eState==PAGER_WRITER_LOCKED   ? \"WRITER_LOCKED\" :\n        p->eState==PAGER_WRITER_CACHEMOD ? \"WRITER_CACHEMOD\" :\n        p->eState==PAGER_WRITER_DBMOD    ? \"WRITER_DBMOD\" :\n        p->eState==PAGER_WRITER_FINISHED ? \"WRITER_FINISHED\" :\n        p->eState==PAGER_ERROR           ? \"ERROR\" : \"?error?\"\n      , (int)p->errCode\n      , p->eLock==NO_LOCK         ? \"NO_LOCK\" :\n        p->eLock==RESERVED_LOCK   ? \"RESERVED\" :\n        p->eLock==EXCLUSIVE_LOCK  ? \"EXCLUSIVE\" :\n        p->eLock==SHARED_LOCK     ? \"SHARED\" :\n        p->eLock==UNKNOWN_LOCK    ? \"UNKNOWN\" : \"?error?\"\n      , p->exclusiveMode ? \"exclusive\" : \"normal\"\n      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? \"memory\" :\n        p->journalMode==PAGER_JOURNALMODE_OFF      ? \"off\" :\n        p->journalMode==PAGER_JOURNALMODE_DELETE   ? \"delete\" :\n        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? \"persist\" :\n        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? \"truncate\" :\n        p->journalMode==PAGER_JOURNALMODE_WAL      ? \"wal\" : \"?error?\"\n      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal\n      , p->journalOff, p->journalHdr\n      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize\n  );\n\n  return zRet;\n}\n#endif\n\n/* Forward references to the various page getters */\nstatic int getPageNormal(Pager*,Pgno,DbPage**,int);\nstatic int getPageError(Pager*,Pgno,DbPage**,int);\n#if SQLITE_MAX_MMAP_SIZE>0\nstatic int getPageMMap(Pager*,Pgno,DbPage**,int);\n#endif\n\n/*\n** Set the Pager.xGet method for the appropriate routine used to fetch\n** content from the pager.\n*/\nstatic void setGetterMethod(Pager *pPager){\n  if( pPager->errCode ){\n    pPager->xGet = getPageError;\n#if SQLITE_MAX_MMAP_SIZE>0\n  }else if( USEFETCH(pPager) ){\n    pPager->xGet = getPageMMap;\n#endif /* SQLITE_MAX_MMAP_SIZE>0 */\n  }else{\n    pPager->xGet = getPageNormal;\n  }\n}\n\n/*\n** Return true if it is necessary to write page *pPg into the sub-journal.\n** A page needs to be written into the sub-journal if there exists one\n** or more open savepoints for which:\n**\n**   * The page-number is less than or equal to PagerSavepoint.nOrig, and\n**   * The bit corresponding to the page-number is not set in\n**     PagerSavepoint.pInSavepoint.\n*/\nstatic int subjRequiresPage(PgHdr *pPg){\n  Pager *pPager = pPg->pPager;\n  PagerSavepoint *p;\n  Pgno pgno = pPg->pgno;\n  int i;\n  for(i=0; i<pPager->nSavepoint; i++){\n    p = &pPager->aSavepoint[i];\n    if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){\n      return 1;\n    }\n  }\n  return 0;\n}\n\n#ifdef SQLITE_DEBUG\n/*\n** Return true if the page is already in the journal file.\n*/\nstatic int pageInJournal(Pager *pPager, PgHdr *pPg){\n  return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);\n}\n#endif\n\n/*\n** Read a 32-bit integer from the given file descriptor.  Store the integer\n** that is read in *pRes.  Return SQLITE_OK if everything worked, or an\n** error code is something goes wrong.\n**\n** All values are stored on disk as big-endian.\n*/\nstatic int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){\n  unsigned char ac[4];\n  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);\n  if( rc==SQLITE_OK ){\n    *pRes = sqlite3Get4byte(ac);\n  }\n  return rc;\n}\n\n/*\n** Write a 32-bit integer into a string buffer in big-endian byte order.\n*/\n#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)\n\n\n/*\n** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK\n** on success or an error code is something goes wrong.\n*/\nstatic int write32bits(sqlite3_file *fd, i64 offset, u32 val){\n  char ac[4];\n  put32bits(ac, val);\n  return sqlite3OsWrite(fd, ac, 4, offset);\n}\n\n/*\n** Unlock the database file to level eLock, which must be either NO_LOCK\n** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()\n** succeeds, set the Pager.eLock variable to match the (attempted) new lock.\n**\n** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is\n** called, do not modify it. See the comment above the #define of \n** UNKNOWN_LOCK for an explanation of this.\n*/\nstatic int pagerUnlockDb(Pager *pPager, int eLock){\n  int rc = SQLITE_OK;\n\n  assert( !pPager->exclusiveMode || pPager->eLock==eLock );\n  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );\n  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );\n  if( isOpen(pPager->fd) ){\n    assert( pPager->eLock>=eLock );\n    rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);\n    if( pPager->eLock!=UNKNOWN_LOCK ){\n      pPager->eLock = (u8)eLock;\n    }\n    IOTRACE((\"UNLOCK %p %d\\n\", pPager, eLock))\n  }\n  pPager->changeCountDone = pPager->tempFile; /* ticket fb3b3024ea238d5c */\n  return rc;\n}\n\n/*\n** Lock the database file to level eLock, which must be either SHARED_LOCK,\n** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the\n** Pager.eLock variable to the new locking state. \n**\n** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is \n** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. \n** See the comment above the #define of UNKNOWN_LOCK for an explanation \n** of this.\n*/\nstatic int pagerLockDb(Pager *pPager, int eLock){\n  int rc = SQLITE_OK;\n\n  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );\n  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){\n    rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);\n    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){\n      pPager->eLock = (u8)eLock;\n      IOTRACE((\"LOCK %p %d\\n\", pPager, eLock))\n    }\n  }\n  return rc;\n}\n\n/*\n** This function determines whether or not the atomic-write or\n** atomic-batch-write optimizations can be used with this pager. The\n** atomic-write optimization can be used if:\n**\n**  (a) the value returned by OsDeviceCharacteristics() indicates that\n**      a database page may be written atomically, and\n**  (b) the value returned by OsSectorSize() is less than or equal\n**      to the page size.\n**\n** If it can be used, then the value returned is the size of the journal \n** file when it contains rollback data for exactly one page.\n**\n** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()\n** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is\n** returned in this case.\n**\n** If neither optimization can be used, 0 is returned.\n*/\nstatic int jrnlBufferSize(Pager *pPager){\n  assert( !MEMDB );\n\n#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \\\n || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)\n  int dc;                           /* Device characteristics */\n\n  assert( isOpen(pPager->fd) );\n  dc = sqlite3OsDeviceCharacteristics(pPager->fd);\n#else\n  UNUSED_PARAMETER(pPager);\n#endif\n\n#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE\n  if( pPager->dbSize>0 && (dc&SQLITE_IOCAP_BATCH_ATOMIC) ){\n    return -1;\n  }\n#endif\n\n#ifdef SQLITE_ENABLE_ATOMIC_WRITE\n  {\n    int nSector = pPager->sectorSize;\n    int szPage = pPager->pageSize;\n\n    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));\n    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));\n    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){\n      return 0;\n    }\n  }\n\n  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);\n#endif\n\n  return 0;\n}\n\n/*\n** If SQLITE_CHECK_PAGES is defined then we do some sanity checking\n** on the cache using a hash function.  This is used for testing\n** and debugging only.\n*/\n#ifdef SQLITE_CHECK_PAGES\n/*\n** Return a 32-bit hash of the page data for pPage.\n*/\nstatic u32 pager_datahash(int nByte, unsigned char *pData){\n  u32 hash = 0;\n  int i;\n  for(i=0; i<nByte; i++){\n    hash = (hash*1039) + pData[i];\n  }\n  return hash;\n}\nstatic u32 pager_pagehash(PgHdr *pPage){\n  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);\n}\nstatic void pager_set_pagehash(PgHdr *pPage){\n  pPage->pageHash = pager_pagehash(pPage);\n}\n\n/*\n** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES\n** is defined, and NDEBUG is not defined, an assert() statement checks\n** that the page is either dirty or still matches the calculated page-hash.\n*/\n#define CHECK_PAGE(x) checkPage(x)\nstatic void checkPage(PgHdr *pPg){\n  Pager *pPager = pPg->pPager;\n  assert( pPager->eState!=PAGER_ERROR );\n  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );\n}\n\n#else\n#define pager_datahash(X,Y)  0\n#define pager_pagehash(X)  0\n#define pager_set_pagehash(X)\n#define CHECK_PAGE(x)\n#endif  /* SQLITE_CHECK_PAGES */\n\n/*\n** When this is called the journal file for pager pPager must be open.\n** This function attempts to read a master journal file name from the \n** end of the file and, if successful, copies it into memory supplied \n** by the caller. See comments above writeMasterJournal() for the format\n** used to store a master journal file name at the end of a journal file.\n**\n** zMaster must point to a buffer of at least nMaster bytes allocated by\n** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is\n** enough space to write the master journal name). If the master journal\n** name in the journal is longer than nMaster bytes (including a\n** nul-terminator), then this is handled as if no master journal name\n** were present in the journal.\n**\n** If a master journal file name is present at the end of the journal\n** file, then it is copied into the buffer pointed to by zMaster. A\n** nul-terminator byte is appended to the buffer following the master\n** journal file name.\n**\n** If it is determined that no master journal file name is present \n** zMaster[0] is set to 0 and SQLITE_OK returned.\n**\n** If an error occurs while reading from the journal file, an SQLite\n** error code is returned.\n*/\nstatic int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){\n  int rc;                    /* Return code */\n  u32 len;                   /* Length in bytes of master journal name */\n  i64 szJ;                   /* Total size in bytes of journal file pJrnl */\n  u32 cksum;                 /* MJ checksum value read from journal */\n  u32 u;                     /* Unsigned loop counter */\n  unsigned char aMagic[8];   /* A buffer to hold the magic header */\n  zMaster[0] = '\\0';\n\n  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))\n   || szJ<16\n   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))\n   || len>=nMaster \n   || len>szJ-16\n   || len==0 \n   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))\n   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))\n   || memcmp(aMagic, aJournalMagic, 8)\n   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))\n  ){\n    return rc;\n  }\n\n  /* See if the checksum matches the master journal name */\n  for(u=0; u<len; u++){\n    cksum -= zMaster[u];\n  }\n  if( cksum ){\n    /* If the checksum doesn't add up, then one or more of the disk sectors\n    ** containing the master journal filename is corrupted. This means\n    ** definitely roll back, so just return SQLITE_OK and report a (nul)\n    ** master-journal filename.\n    */\n    len = 0;\n  }\n  zMaster[len] = '\\0';\n  zMaster[len+1] = '\\0';\n   \n  return SQLITE_OK;\n}\n\n/*\n** Return the offset of the sector boundary at or immediately \n** following the value in pPager->journalOff, assuming a sector \n** size of pPager->sectorSize bytes.\n**\n** i.e for a sector size of 512:\n**\n**   Pager.journalOff          Return value\n**   ---------------------------------------\n**   0                         0\n**   512                       512\n**   100                       512\n**   2000                      2048\n** \n*/\nstatic i64 journalHdrOffset(Pager *pPager){\n  i64 offset = 0;\n  i64 c = pPager->journalOff;\n  if( c ){\n    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);\n  }\n  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );\n  assert( offset>=c );\n  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );\n  return offset;\n}\n\n/*\n** The journal file must be open when this function is called.\n**\n** This function is a no-op if the journal file has not been written to\n** within the current transaction (i.e. if Pager.journalOff==0).\n**\n** If doTruncate is non-zero or the Pager.journalSizeLimit variable is\n** set to 0, then truncate the journal file to zero bytes in size. Otherwise,\n** zero the 28-byte header at the start of the journal file. In either case, \n** if the pager is not in no-sync mode, sync the journal file immediately \n** after writing or truncating it.\n**\n** If Pager.journalSizeLimit is set to a positive, non-zero value, and\n** following the truncation or zeroing described above the size of the \n** journal file in bytes is larger than this value, then truncate the\n** journal file to Pager.journalSizeLimit bytes. The journal file does\n** not need to be synced following this operation.\n**\n** If an IO error occurs, abandon processing and return the IO error code.\n** Otherwise, return SQLITE_OK.\n*/\nstatic int zeroJournalHdr(Pager *pPager, int doTruncate){\n  int rc = SQLITE_OK;                               /* Return code */\n  assert( isOpen(pPager->jfd) );\n  assert( !sqlite3JournalIsInMemory(pPager->jfd) );\n  if( pPager->journalOff ){\n    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */\n\n    IOTRACE((\"JZEROHDR %p\\n\", pPager))\n    if( doTruncate || iLimit==0 ){\n      rc = sqlite3OsTruncate(pPager->jfd, 0);\n    }else{\n      static const char zeroHdr[28] = {0};\n      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);\n    }\n    if( rc==SQLITE_OK && !pPager->noSync ){\n      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);\n    }\n\n    /* At this point the transaction is committed but the write lock \n    ** is still held on the file. If there is a size limit configured for \n    ** the persistent journal and the journal file currently consumes more\n    ** space than that limit allows for, truncate it now. There is no need\n    ** to sync the file following this operation.\n    */\n    if( rc==SQLITE_OK && iLimit>0 ){\n      i64 sz;\n      rc = sqlite3OsFileSize(pPager->jfd, &sz);\n      if( rc==SQLITE_OK && sz>iLimit ){\n        rc = sqlite3OsTruncate(pPager->jfd, iLimit);\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** The journal file must be open when this routine is called. A journal\n** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the\n** current location.\n**\n** The format for the journal header is as follows:\n** - 8 bytes: Magic identifying journal format.\n** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.\n** - 4 bytes: Random number used for page hash.\n** - 4 bytes: Initial database page count.\n** - 4 bytes: Sector size used by the process that wrote this journal.\n** - 4 bytes: Database page size.\n** \n** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.\n*/\nstatic int writeJournalHdr(Pager *pPager){\n  int rc = SQLITE_OK;                 /* Return code */\n  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */\n  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */\n  u32 nWrite;                         /* Bytes of header sector written */\n  int ii;                             /* Loop counter */\n\n  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */\n\n  if( nHeader>JOURNAL_HDR_SZ(pPager) ){\n    nHeader = JOURNAL_HDR_SZ(pPager);\n  }\n\n  /* If there are active savepoints and any of them were created \n  ** since the most recent journal header was written, update the \n  ** PagerSavepoint.iHdrOffset fields now.\n  */\n  for(ii=0; ii<pPager->nSavepoint; ii++){\n    if( pPager->aSavepoint[ii].iHdrOffset==0 ){\n      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;\n    }\n  }\n\n  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);\n\n  /* \n  ** Write the nRec Field - the number of page records that follow this\n  ** journal header. Normally, zero is written to this value at this time.\n  ** After the records are added to the journal (and the journal synced, \n  ** if in full-sync mode), the zero is overwritten with the true number\n  ** of records (see syncJournal()).\n  **\n  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When\n  ** reading the journal this value tells SQLite to assume that the\n  ** rest of the journal file contains valid page records. This assumption\n  ** is dangerous, as if a failure occurred whilst writing to the journal\n  ** file it may contain some garbage data. There are two scenarios\n  ** where this risk can be ignored:\n  **\n  **   * When the pager is in no-sync mode. Corruption can follow a\n  **     power failure in this case anyway.\n  **\n  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees\n  **     that garbage data is never appended to the journal file.\n  */\n  assert( isOpen(pPager->fd) || pPager->noSync );\n  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)\n   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) \n  ){\n    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));\n    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);\n  }else{\n    memset(zHeader, 0, sizeof(aJournalMagic)+4);\n  }\n\n  /* The random check-hash initializer */ \n  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);\n  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);\n  /* The initial database size */\n  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);\n  /* The assumed sector size for this process */\n  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);\n\n  /* The page size */\n  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);\n\n  /* Initializing the tail of the buffer is not necessary.  Everything\n  ** works find if the following memset() is omitted.  But initializing\n  ** the memory prevents valgrind from complaining, so we are willing to\n  ** take the performance hit.\n  */\n  memset(&zHeader[sizeof(aJournalMagic)+20], 0,\n         nHeader-(sizeof(aJournalMagic)+20));\n\n  /* In theory, it is only necessary to write the 28 bytes that the \n  ** journal header consumes to the journal file here. Then increment the \n  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next \n  ** record is written to the following sector (leaving a gap in the file\n  ** that will be implicitly filled in by the OS).\n  **\n  ** However it has been discovered that on some systems this pattern can \n  ** be significantly slower than contiguously writing data to the file,\n  ** even if that means explicitly writing data to the block of \n  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what\n  ** is done. \n  **\n  ** The loop is required here in case the sector-size is larger than the \n  ** database page size. Since the zHeader buffer is only Pager.pageSize\n  ** bytes in size, more than one call to sqlite3OsWrite() may be required\n  ** to populate the entire journal header sector.\n  */ \n  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){\n    IOTRACE((\"JHDR %p %lld %d\\n\", pPager, pPager->journalHdr, nHeader))\n    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);\n    assert( pPager->journalHdr <= pPager->journalOff );\n    pPager->journalOff += nHeader;\n  }\n\n  return rc;\n}\n\n/*\n** The journal file must be open when this is called. A journal header file\n** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal\n** file. The current location in the journal file is given by\n** pPager->journalOff. See comments above function writeJournalHdr() for\n** a description of the journal header format.\n**\n** If the header is read successfully, *pNRec is set to the number of\n** page records following this header and *pDbSize is set to the size of the\n** database before the transaction began, in pages. Also, pPager->cksumInit\n** is set to the value read from the journal header. SQLITE_OK is returned\n** in this case.\n**\n** If the journal header file appears to be corrupted, SQLITE_DONE is\n** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes\n** cannot be read from the journal file an error code is returned.\n*/\nstatic int readJournalHdr(\n  Pager *pPager,               /* Pager object */\n  int isHot,\n  i64 journalSize,             /* Size of the open journal file in bytes */\n  u32 *pNRec,                  /* OUT: Value read from the nRec field */\n  u32 *pDbSize                 /* OUT: Value of original database size field */\n){\n  int rc;                      /* Return code */\n  unsigned char aMagic[8];     /* A buffer to hold the magic header */\n  i64 iHdrOff;                 /* Offset of journal header being read */\n\n  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */\n\n  /* Advance Pager.journalOff to the start of the next sector. If the\n  ** journal file is too small for there to be a header stored at this\n  ** point, return SQLITE_DONE.\n  */\n  pPager->journalOff = journalHdrOffset(pPager);\n  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){\n    return SQLITE_DONE;\n  }\n  iHdrOff = pPager->journalOff;\n\n  /* Read in the first 8 bytes of the journal header. If they do not match\n  ** the  magic string found at the start of each journal header, return\n  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,\n  ** proceed.\n  */\n  if( isHot || iHdrOff!=pPager->journalHdr ){\n    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);\n    if( rc ){\n      return rc;\n    }\n    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){\n      return SQLITE_DONE;\n    }\n  }\n\n  /* Read the first three 32-bit fields of the journal header: The nRec\n  ** field, the checksum-initializer and the database size at the start\n  ** of the transaction. Return an error code if anything goes wrong.\n  */\n  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))\n   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))\n   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))\n  ){\n    return rc;\n  }\n\n  if( pPager->journalOff==0 ){\n    u32 iPageSize;               /* Page-size field of journal header */\n    u32 iSectorSize;             /* Sector-size field of journal header */\n\n    /* Read the page-size and sector-size journal header fields. */\n    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))\n     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))\n    ){\n      return rc;\n    }\n\n    /* Versions of SQLite prior to 3.5.8 set the page-size field of the\n    ** journal header to zero. In this case, assume that the Pager.pageSize\n    ** variable is already set to the correct page size.\n    */\n    if( iPageSize==0 ){\n      iPageSize = pPager->pageSize;\n    }\n\n    /* Check that the values read from the page-size and sector-size fields\n    ** are within range. To be 'in range', both values need to be a power\n    ** of two greater than or equal to 512 or 32, and not greater than their \n    ** respective compile time maximum limits.\n    */\n    if( iPageSize<512                  || iSectorSize<32\n     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE\n     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 \n    ){\n      /* If the either the page-size or sector-size in the journal-header is \n      ** invalid, then the process that wrote the journal-header must have \n      ** crashed before the header was synced. In this case stop reading \n      ** the journal file here.\n      */\n      return SQLITE_DONE;\n    }\n\n    /* Update the page-size to match the value read from the journal. \n    ** Use a testcase() macro to make sure that malloc failure within \n    ** PagerSetPagesize() is tested.\n    */\n    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);\n    testcase( rc!=SQLITE_OK );\n\n    /* Update the assumed sector-size to match the value used by \n    ** the process that created this journal. If this journal was\n    ** created by a process other than this one, then this routine\n    ** is being called from within pager_playback(). The local value\n    ** of Pager.sectorSize is restored at the end of that routine.\n    */\n    pPager->sectorSize = iSectorSize;\n  }\n\n  pPager->journalOff += JOURNAL_HDR_SZ(pPager);\n  return rc;\n}\n\n\n/*\n** Write the supplied master journal name into the journal file for pager\n** pPager at the current location. The master journal name must be the last\n** thing written to a journal file. If the pager is in full-sync mode, the\n** journal file descriptor is advanced to the next sector boundary before\n** anything is written. The format is:\n**\n**   + 4 bytes: PAGER_MJ_PGNO.\n**   + N bytes: Master journal filename in utf-8.\n**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).\n**   + 4 bytes: Master journal name checksum.\n**   + 8 bytes: aJournalMagic[].\n**\n** The master journal page checksum is the sum of the bytes in the master\n** journal name, where each byte is interpreted as a signed 8-bit integer.\n**\n** If zMaster is a NULL pointer (occurs for a single database transaction), \n** this call is a no-op.\n*/\nstatic int writeMasterJournal(Pager *pPager, const char *zMaster){\n  int rc;                          /* Return code */\n  int nMaster;                     /* Length of string zMaster */\n  i64 iHdrOff;                     /* Offset of header in journal file */\n  i64 jrnlSize;                    /* Size of journal file on disk */\n  u32 cksum = 0;                   /* Checksum of string zMaster */\n\n  assert( pPager->setMaster==0 );\n  assert( !pagerUseWal(pPager) );\n\n  if( !zMaster \n   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY \n   || !isOpen(pPager->jfd)\n  ){\n    return SQLITE_OK;\n  }\n  pPager->setMaster = 1;\n  assert( pPager->journalHdr <= pPager->journalOff );\n\n  /* Calculate the length in bytes and the checksum of zMaster */\n  for(nMaster=0; zMaster[nMaster]; nMaster++){\n    cksum += zMaster[nMaster];\n  }\n\n  /* If in full-sync mode, advance to the next disk sector before writing\n  ** the master journal name. This is in case the previous page written to\n  ** the journal has already been synced.\n  */\n  if( pPager->fullSync ){\n    pPager->journalOff = journalHdrOffset(pPager);\n  }\n  iHdrOff = pPager->journalOff;\n\n  /* Write the master journal data to the end of the journal file. If\n  ** an error occurs, return the error code to the caller.\n  */\n  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))\n   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))\n   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))\n   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))\n   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,\n                                 iHdrOff+4+nMaster+8)))\n  ){\n    return rc;\n  }\n  pPager->journalOff += (nMaster+20);\n\n  /* If the pager is in peristent-journal mode, then the physical \n  ** journal-file may extend past the end of the master-journal name\n  ** and 8 bytes of magic data just written to the file. This is \n  ** dangerous because the code to rollback a hot-journal file\n  ** will not be able to find the master-journal name to determine \n  ** whether or not the journal is hot. \n  **\n  ** Easiest thing to do in this scenario is to truncate the journal \n  ** file to the required size.\n  */ \n  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))\n   && jrnlSize>pPager->journalOff\n  ){\n    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);\n  }\n  return rc;\n}\n\n/*\n** Discard the entire contents of the in-memory page-cache.\n*/\nstatic void pager_reset(Pager *pPager){\n  pPager->iDataVersion++;\n  sqlite3BackupRestart(pPager->pBackup);\n  sqlite3PcacheClear(pPager->pPCache);\n}\n\n/*\n** Return the pPager->iDataVersion value\n*/\nSQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){\n  return pPager->iDataVersion;\n}\n\n/*\n** Free all structures in the Pager.aSavepoint[] array and set both\n** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal\n** if it is open and the pager is not in exclusive mode.\n*/\nstatic void releaseAllSavepoints(Pager *pPager){\n  int ii;               /* Iterator for looping through Pager.aSavepoint */\n  for(ii=0; ii<pPager->nSavepoint; ii++){\n    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);\n  }\n  if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){\n    sqlite3OsClose(pPager->sjfd);\n  }\n  sqlite3_free(pPager->aSavepoint);\n  pPager->aSavepoint = 0;\n  pPager->nSavepoint = 0;\n  pPager->nSubRec = 0;\n}\n\n/*\n** Set the bit number pgno in the PagerSavepoint.pInSavepoint \n** bitvecs of all open savepoints. Return SQLITE_OK if successful\n** or SQLITE_NOMEM if a malloc failure occurs.\n*/\nstatic int addToSavepointBitvecs(Pager *pPager, Pgno pgno){\n  int ii;                   /* Loop counter */\n  int rc = SQLITE_OK;       /* Result code */\n\n  for(ii=0; ii<pPager->nSavepoint; ii++){\n    PagerSavepoint *p = &pPager->aSavepoint[ii];\n    if( pgno<=p->nOrig ){\n      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);\n      testcase( rc==SQLITE_NOMEM );\n      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );\n    }\n  }\n  return rc;\n}\n\n/*\n** This function is a no-op if the pager is in exclusive mode and not\n** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN\n** state.\n**\n** If the pager is not in exclusive-access mode, the database file is\n** completely unlocked. If the file is unlocked and the file-system does\n** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is\n** closed (if it is open).\n**\n** If the pager is in ERROR state when this function is called, the \n** contents of the pager cache are discarded before switching back to \n** the OPEN state. Regardless of whether the pager is in exclusive-mode\n** or not, any journal file left in the file-system will be treated\n** as a hot-journal and rolled back the next time a read-transaction\n** is opened (by this or by any other connection).\n*/\nstatic void pager_unlock(Pager *pPager){\n\n  assert( pPager->eState==PAGER_READER \n       || pPager->eState==PAGER_OPEN \n       || pPager->eState==PAGER_ERROR \n  );\n\n  sqlite3BitvecDestroy(pPager->pInJournal);\n  pPager->pInJournal = 0;\n  releaseAllSavepoints(pPager);\n\n  if( pagerUseWal(pPager) ){\n    assert( !isOpen(pPager->jfd) );\n    sqlite3WalEndReadTransaction(pPager->pWal);\n    pPager->eState = PAGER_OPEN;\n  }else if( !pPager->exclusiveMode ){\n    int rc;                       /* Error code returned by pagerUnlockDb() */\n    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;\n\n    /* If the operating system support deletion of open files, then\n    ** close the journal file when dropping the database lock.  Otherwise\n    ** another connection with journal_mode=delete might delete the file\n    ** out from under us.\n    */\n    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );\n    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );\n    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );\n    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );\n    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );\n    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );\n    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)\n     || 1!=(pPager->journalMode & 5)\n    ){\n      sqlite3OsClose(pPager->jfd);\n    }\n\n    /* If the pager is in the ERROR state and the call to unlock the database\n    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment\n    ** above the #define for UNKNOWN_LOCK for an explanation of why this\n    ** is necessary.\n    */\n    rc = pagerUnlockDb(pPager, NO_LOCK);\n    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){\n      pPager->eLock = UNKNOWN_LOCK;\n    }\n\n    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here\n    ** without clearing the error code. This is intentional - the error\n    ** code is cleared and the cache reset in the block below.\n    */\n    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );\n    pPager->eState = PAGER_OPEN;\n  }\n\n  /* If Pager.errCode is set, the contents of the pager cache cannot be\n  ** trusted. Now that there are no outstanding references to the pager,\n  ** it can safely move back to PAGER_OPEN state. This happens in both\n  ** normal and exclusive-locking mode.\n  */\n  assert( pPager->errCode==SQLITE_OK || !MEMDB );\n  if( pPager->errCode ){\n    if( pPager->tempFile==0 ){\n      pager_reset(pPager);\n      pPager->changeCountDone = 0;\n      pPager->eState = PAGER_OPEN;\n    }else{\n      pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);\n    }\n    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);\n    pPager->errCode = SQLITE_OK;\n    setGetterMethod(pPager);\n  }\n\n  pPager->journalOff = 0;\n  pPager->journalHdr = 0;\n  pPager->setMaster = 0;\n}\n\n/*\n** This function is called whenever an IOERR or FULL error that requires\n** the pager to transition into the ERROR state may ahve occurred.\n** The first argument is a pointer to the pager structure, the second \n** the error-code about to be returned by a pager API function. The \n** value returned is a copy of the second argument to this function. \n**\n** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the\n** IOERR sub-codes, the pager enters the ERROR state and the error code\n** is stored in Pager.errCode. While the pager remains in the ERROR state,\n** all major API calls on the Pager will immediately return Pager.errCode.\n**\n** The ERROR state indicates that the contents of the pager-cache \n** cannot be trusted. This state can be cleared by completely discarding \n** the contents of the pager-cache. If a transaction was active when\n** the persistent error occurred, then the rollback journal may need\n** to be replayed to restore the contents of the database file (as if\n** it were a hot-journal).\n*/\nstatic int pager_error(Pager *pPager, int rc){\n  int rc2 = rc & 0xff;\n  assert( rc==SQLITE_OK || !MEMDB );\n  assert(\n       pPager->errCode==SQLITE_FULL ||\n       pPager->errCode==SQLITE_OK ||\n       (pPager->errCode & 0xff)==SQLITE_IOERR\n  );\n  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){\n    pPager->errCode = rc;\n    pPager->eState = PAGER_ERROR;\n    setGetterMethod(pPager);\n  }\n  return rc;\n}\n\nstatic int pager_truncate(Pager *pPager, Pgno nPage);\n\n/*\n** The write transaction open on pPager is being committed (bCommit==1)\n** or rolled back (bCommit==0).\n**\n** Return TRUE if and only if all dirty pages should be flushed to disk.\n**\n** Rules:\n**\n**   *  For non-TEMP databases, always sync to disk.  This is necessary\n**      for transactions to be durable.\n**\n**   *  Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing\n**      file has been created already (via a spill on pagerStress()) and\n**      when the number of dirty pages in memory exceeds 25% of the total\n**      cache size.\n*/\nstatic int pagerFlushOnCommit(Pager *pPager, int bCommit){\n  if( pPager->tempFile==0 ) return 1;\n  if( !bCommit ) return 0;\n  if( !isOpen(pPager->fd) ) return 0;\n  return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);\n}\n\n/*\n** This routine ends a transaction. A transaction is usually ended by \n** either a COMMIT or a ROLLBACK operation. This routine may be called \n** after rollback of a hot-journal, or if an error occurs while opening\n** the journal file or writing the very first journal-header of a\n** database transaction.\n** \n** This routine is never called in PAGER_ERROR state. If it is called\n** in PAGER_NONE or PAGER_SHARED state and the lock held is less\n** exclusive than a RESERVED lock, it is a no-op.\n**\n** Otherwise, any active savepoints are released.\n**\n** If the journal file is open, then it is \"finalized\". Once a journal \n** file has been finalized it is not possible to use it to roll back a \n** transaction. Nor will it be considered to be a hot-journal by this\n** or any other database connection. Exactly how a journal is finalized\n** depends on whether or not the pager is running in exclusive mode and\n** the current journal-mode (Pager.journalMode value), as follows:\n**\n**   journalMode==MEMORY\n**     Journal file descriptor is simply closed. This destroys an \n**     in-memory journal.\n**\n**   journalMode==TRUNCATE\n**     Journal file is truncated to zero bytes in size.\n**\n**   journalMode==PERSIST\n**     The first 28 bytes of the journal file are zeroed. This invalidates\n**     the first journal header in the file, and hence the entire journal\n**     file. An invalid journal file cannot be rolled back.\n**\n**   journalMode==DELETE\n**     The journal file is closed and deleted using sqlite3OsDelete().\n**\n**     If the pager is running in exclusive mode, this method of finalizing\n**     the journal file is never used. Instead, if the journalMode is\n**     DELETE and the pager is in exclusive mode, the method described under\n**     journalMode==PERSIST is used instead.\n**\n** After the journal is finalized, the pager moves to PAGER_READER state.\n** If running in non-exclusive rollback mode, the lock on the file is \n** downgraded to a SHARED_LOCK.\n**\n** SQLITE_OK is returned if no error occurs. If an error occurs during\n** any of the IO operations to finalize the journal file or unlock the\n** database then the IO error code is returned to the user. If the \n** operation to finalize the journal file fails, then the code still\n** tries to unlock the database file if not in exclusive mode. If the\n** unlock operation fails as well, then the first error code related\n** to the first error encountered (the journal finalization one) is\n** returned.\n*/\nstatic int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){\n  int rc = SQLITE_OK;      /* Error code from journal finalization operation */\n  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */\n\n  /* Do nothing if the pager does not have an open write transaction\n  ** or at least a RESERVED lock. This function may be called when there\n  ** is no write-transaction active but a RESERVED or greater lock is\n  ** held under two circumstances:\n  **\n  **   1. After a successful hot-journal rollback, it is called with\n  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.\n  **\n  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE \n  **      lock switches back to locking_mode=normal and then executes a\n  **      read-transaction, this function is called with eState==PAGER_READER \n  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.\n  */\n  assert( assert_pager_state(pPager) );\n  assert( pPager->eState!=PAGER_ERROR );\n  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){\n    return SQLITE_OK;\n  }\n\n  releaseAllSavepoints(pPager);\n  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 \n      || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)\n  );\n  if( isOpen(pPager->jfd) ){\n    assert( !pagerUseWal(pPager) );\n\n    /* Finalize the journal file. */\n    if( sqlite3JournalIsInMemory(pPager->jfd) ){\n      /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */\n      sqlite3OsClose(pPager->jfd);\n    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){\n      if( pPager->journalOff==0 ){\n        rc = SQLITE_OK;\n      }else{\n        rc = sqlite3OsTruncate(pPager->jfd, 0);\n        if( rc==SQLITE_OK && pPager->fullSync ){\n          /* Make sure the new file size is written into the inode right away.\n          ** Otherwise the journal might resurrect following a power loss and\n          ** cause the last transaction to roll back.  See\n          ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773\n          */\n          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);\n        }\n      }\n      pPager->journalOff = 0;\n    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST\n      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)\n    ){\n      rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);\n      pPager->journalOff = 0;\n    }else{\n      /* This branch may be executed with Pager.journalMode==MEMORY if\n      ** a hot-journal was just rolled back. In this case the journal\n      ** file should be closed and deleted. If this connection writes to\n      ** the database file, it will do so using an in-memory journal.\n      */\n      int bDelete = !pPager->tempFile;\n      assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );\n      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE \n           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY \n           || pPager->journalMode==PAGER_JOURNALMODE_WAL \n      );\n      sqlite3OsClose(pPager->jfd);\n      if( bDelete ){\n        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);\n      }\n    }\n  }\n\n#ifdef SQLITE_CHECK_PAGES\n  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);\n  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){\n    PgHdr *p = sqlite3PagerLookup(pPager, 1);\n    if( p ){\n      p->pageHash = 0;\n      sqlite3PagerUnrefNotNull(p);\n    }\n  }\n#endif\n\n  sqlite3BitvecDestroy(pPager->pInJournal);\n  pPager->pInJournal = 0;\n  pPager->nRec = 0;\n  if( rc==SQLITE_OK ){\n    if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){\n      sqlite3PcacheCleanAll(pPager->pPCache);\n    }else{\n      sqlite3PcacheClearWritable(pPager->pPCache);\n    }\n    sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);\n  }\n\n  if( pagerUseWal(pPager) ){\n    /* Drop the WAL write-lock, if any. Also, if the connection was in \n    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE \n    ** lock held on the database file.\n    */\n    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);\n    assert( rc2==SQLITE_OK );\n  }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){\n    /* This branch is taken when committing a transaction in rollback-journal\n    ** mode if the database file on disk is larger than the database image.\n    ** At this point the journal has been finalized and the transaction \n    ** successfully committed, but the EXCLUSIVE lock is still held on the\n    ** file. So it is safe to truncate the database file to its minimum\n    ** required size.  */\n    assert( pPager->eLock==EXCLUSIVE_LOCK );\n    rc = pager_truncate(pPager, pPager->dbSize);\n  }\n\n  if( rc==SQLITE_OK && bCommit ){\n    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);\n    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;\n  }\n\n  if( !pPager->exclusiveMode \n   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))\n  ){\n    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);\n  }\n  pPager->eState = PAGER_READER;\n  pPager->setMaster = 0;\n\n  return (rc==SQLITE_OK?rc2:rc);\n}\n\n/*\n** Execute a rollback if a transaction is active and unlock the \n** database file. \n**\n** If the pager has already entered the ERROR state, do not attempt \n** the rollback at this time. Instead, pager_unlock() is called. The\n** call to pager_unlock() will discard all in-memory pages, unlock\n** the database file and move the pager back to OPEN state. If this \n** means that there is a hot-journal left in the file-system, the next \n** connection to obtain a shared lock on the pager (which may be this one) \n** will roll it back.\n**\n** If the pager has not already entered the ERROR state, but an IO or\n** malloc error occurs during a rollback, then this will itself cause \n** the pager to enter the ERROR state. Which will be cleared by the\n** call to pager_unlock(), as described above.\n*/\nstatic void pagerUnlockAndRollback(Pager *pPager){\n  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){\n    assert( assert_pager_state(pPager) );\n    if( pPager->eState>=PAGER_WRITER_LOCKED ){\n      sqlite3BeginBenignMalloc();\n      sqlite3PagerRollback(pPager);\n      sqlite3EndBenignMalloc();\n    }else if( !pPager->exclusiveMode ){\n      assert( pPager->eState==PAGER_READER );\n      pager_end_transaction(pPager, 0, 0);\n    }\n  }\n  pager_unlock(pPager);\n}\n\n/*\n** Parameter aData must point to a buffer of pPager->pageSize bytes\n** of data. Compute and return a checksum based ont the contents of the \n** page of data and the current value of pPager->cksumInit.\n**\n** This is not a real checksum. It is really just the sum of the \n** random initial value (pPager->cksumInit) and every 200th byte\n** of the page data, starting with byte offset (pPager->pageSize%200).\n** Each byte is interpreted as an 8-bit unsigned integer.\n**\n** Changing the formula used to compute this checksum results in an\n** incompatible journal file format.\n**\n** If journal corruption occurs due to a power failure, the most likely \n** scenario is that one end or the other of the record will be changed. \n** It is much less likely that the two ends of the journal record will be\n** correct and the middle be corrupt.  Thus, this \"checksum\" scheme,\n** though fast and simple, catches the mostly likely kind of corruption.\n*/\nstatic u32 pager_cksum(Pager *pPager, const u8 *aData){\n  u32 cksum = pPager->cksumInit;         /* Checksum value to return */\n  int i = pPager->pageSize-200;          /* Loop counter */\n  while( i>0 ){\n    cksum += aData[i];\n    i -= 200;\n  }\n  return cksum;\n}\n\n/*\n** Read a single page from either the journal file (if isMainJrnl==1) or\n** from the sub-journal (if isMainJrnl==0) and playback that page.\n** The page begins at offset *pOffset into the file. The *pOffset\n** value is increased to the start of the next page in the journal.\n**\n** The main rollback journal uses checksums - the statement journal does \n** not.\n**\n** If the page number of the page record read from the (sub-)journal file\n** is greater than the current value of Pager.dbSize, then playback is\n** skipped and SQLITE_OK is returned.\n**\n** If pDone is not NULL, then it is a record of pages that have already\n** been played back.  If the page at *pOffset has already been played back\n** (if the corresponding pDone bit is set) then skip the playback.\n** Make sure the pDone bit corresponding to the *pOffset page is set\n** prior to returning.\n**\n** If the page record is successfully read from the (sub-)journal file\n** and played back, then SQLITE_OK is returned. If an IO error occurs\n** while reading the record from the (sub-)journal file or while writing\n** to the database file, then the IO error code is returned. If data\n** is successfully read from the (sub-)journal file but appears to be\n** corrupted, SQLITE_DONE is returned. Data is considered corrupted in\n** two circumstances:\n** \n**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or\n**   * If the record is being rolled back from the main journal file\n**     and the checksum field does not match the record content.\n**\n** Neither of these two scenarios are possible during a savepoint rollback.\n**\n** If this is a savepoint rollback, then memory may have to be dynamically\n** allocated by this function. If this is the case and an allocation fails,\n** SQLITE_NOMEM is returned.\n*/\nstatic int pager_playback_one_page(\n  Pager *pPager,                /* The pager being played back */\n  i64 *pOffset,                 /* Offset of record to playback */\n  Bitvec *pDone,                /* Bitvec of pages already played back */\n  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */\n  int isSavepnt                 /* True for a savepoint rollback */\n){\n  int rc;\n  PgHdr *pPg;                   /* An existing page in the cache */\n  Pgno pgno;                    /* The page number of a page in journal */\n  u32 cksum;                    /* Checksum used for sanity checking */\n  char *aData;                  /* Temporary storage for the page */\n  sqlite3_file *jfd;            /* The file descriptor for the journal file */\n  int isSynced;                 /* True if journal page is synced */\n\n  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */\n  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */\n  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */\n  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */\n\n  aData = pPager->pTmpSpace;\n  assert( aData );         /* Temp storage must have already been allocated */\n  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );\n\n  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction \n  ** or savepoint rollback done at the request of the caller) or this is\n  ** a hot-journal rollback. If it is a hot-journal rollback, the pager\n  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback\n  ** only reads from the main journal, not the sub-journal.\n  */\n  assert( pPager->eState>=PAGER_WRITER_CACHEMOD\n       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)\n  );\n  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );\n\n  /* Read the page number and page data from the journal or sub-journal\n  ** file. Return an error code to the caller if an IO error occurs.\n  */\n  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;\n  rc = read32bits(jfd, *pOffset, &pgno);\n  if( rc!=SQLITE_OK ) return rc;\n  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);\n  if( rc!=SQLITE_OK ) return rc;\n  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;\n\n  /* Sanity checking on the page.  This is more important that I originally\n  ** thought.  If a power failure occurs while the journal is being written,\n  ** it could cause invalid data to be written into the journal.  We need to\n  ** detect this invalid data (with high probability) and ignore it.\n  */\n  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){\n    assert( !isSavepnt );\n    return SQLITE_DONE;\n  }\n  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){\n    return SQLITE_OK;\n  }\n  if( isMainJrnl ){\n    rc = read32bits(jfd, (*pOffset)-4, &cksum);\n    if( rc ) return rc;\n    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){\n      return SQLITE_DONE;\n    }\n  }\n\n  /* If this page has already been played back before during the current\n  ** rollback, then don't bother to play it back again.\n  */\n  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){\n    return rc;\n  }\n\n  /* When playing back page 1, restore the nReserve setting\n  */\n  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){\n    pPager->nReserve = ((u8*)aData)[20];\n  }\n\n  /* If the pager is in CACHEMOD state, then there must be a copy of this\n  ** page in the pager cache. In this case just update the pager cache,\n  ** not the database file. The page is left marked dirty in this case.\n  **\n  ** An exception to the above rule: If the database is in no-sync mode\n  ** and a page is moved during an incremental vacuum then the page may\n  ** not be in the pager cache. Later: if a malloc() or IO error occurs\n  ** during a Movepage() call, then the page may not be in the cache\n  ** either. So the condition described in the above paragraph is not\n  ** assert()able.\n  **\n  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the\n  ** pager cache if it exists and the main file. The page is then marked \n  ** not dirty. Since this code is only executed in PAGER_OPEN state for\n  ** a hot-journal rollback, it is guaranteed that the page-cache is empty\n  ** if the pager is in OPEN state.\n  **\n  ** Ticket #1171:  The statement journal might contain page content that is\n  ** different from the page content at the start of the transaction.\n  ** This occurs when a page is changed prior to the start of a statement\n  ** then changed again within the statement.  When rolling back such a\n  ** statement we must not write to the original database unless we know\n  ** for certain that original page contents are synced into the main rollback\n  ** journal.  Otherwise, a power loss might leave modified data in the\n  ** database file without an entry in the rollback journal that can\n  ** restore the database to its original form.  Two conditions must be\n  ** met before writing to the database files. (1) the database must be\n  ** locked.  (2) we know that the original page content is fully synced\n  ** in the main journal either because the page is not in cache or else\n  ** the page is marked as needSync==0.\n  **\n  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it\n  ** is possible to fail a statement on a database that does not yet exist.\n  ** Do not attempt to write if database file has never been opened.\n  */\n  if( pagerUseWal(pPager) ){\n    pPg = 0;\n  }else{\n    pPg = sqlite3PagerLookup(pPager, pgno);\n  }\n  assert( pPg || !MEMDB );\n  assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );\n  PAGERTRACE((\"PLAYBACK %d page %d hash(%08x) %s\\n\",\n           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),\n           (isMainJrnl?\"main-journal\":\"sub-journal\")\n  ));\n  if( isMainJrnl ){\n    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);\n  }else{\n    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));\n  }\n  if( isOpen(pPager->fd)\n   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)\n   && isSynced\n  ){\n    i64 ofst = (pgno-1)*(i64)pPager->pageSize;\n    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );\n    assert( !pagerUseWal(pPager) );\n\n    /* Write the data read from the journal back into the database file.\n    ** This is usually safe even for an encrypted database - as the data\n    ** was encrypted before it was written to the journal file. The exception\n    ** is if the data was just read from an in-memory sub-journal. In that\n    ** case it must be encrypted here before it is copied into the database\n    ** file.  */\n    rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);\n\n    if( pgno>pPager->dbFileSize ){\n      pPager->dbFileSize = pgno;\n    }\n    if( pPager->pBackup ){\n      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);\n    }\n  }else if( !isMainJrnl && pPg==0 ){\n    /* If this is a rollback of a savepoint and data was not written to\n    ** the database and the page is not in-memory, there is a potential\n    ** problem. When the page is next fetched by the b-tree layer, it \n    ** will be read from the database file, which may or may not be \n    ** current. \n    **\n    ** There are a couple of different ways this can happen. All are quite\n    ** obscure. When running in synchronous mode, this can only happen \n    ** if the page is on the free-list at the start of the transaction, then\n    ** populated, then moved using sqlite3PagerMovepage().\n    **\n    ** The solution is to add an in-memory page to the cache containing\n    ** the data just read from the sub-journal. Mark the page as dirty \n    ** and if the pager requires a journal-sync, then mark the page as \n    ** requiring a journal-sync before it is written.\n    */\n    assert( isSavepnt );\n    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );\n    pPager->doNotSpill |= SPILLFLAG_ROLLBACK;\n    rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);\n    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );\n    pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;\n    if( rc!=SQLITE_OK ) return rc;\n    sqlite3PcacheMakeDirty(pPg);\n  }\n  if( pPg ){\n    /* No page should ever be explicitly rolled back that is in use, except\n    ** for page 1 which is held in use in order to keep the lock on the\n    ** database active. However such a page may be rolled back as a result\n    ** of an internal error resulting in an automatic call to\n    ** sqlite3PagerRollback().\n    */\n    void *pData;\n    pData = pPg->pData;\n    memcpy(pData, (u8*)aData, pPager->pageSize);\n    pPager->xReiniter(pPg);\n    /* It used to be that sqlite3PcacheMakeClean(pPg) was called here.  But\n    ** that call was dangerous and had no detectable benefit since the cache\n    ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so\n    ** has been removed. */\n    pager_set_pagehash(pPg);\n\n    /* If this was page 1, then restore the value of Pager.dbFileVers.\n    ** Do this before any decoding. */\n    if( pgno==1 ){\n      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));\n    }\n    sqlite3PcacheRelease(pPg);\n  }\n  return rc;\n}\n\n/*\n** Parameter zMaster is the name of a master journal file. A single journal\n** file that referred to the master journal file has just been rolled back.\n** This routine checks if it is possible to delete the master journal file,\n** and does so if it is.\n**\n** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not \n** available for use within this function.\n**\n** When a master journal file is created, it is populated with the names \n** of all of its child journals, one after another, formatted as utf-8 \n** encoded text. The end of each child journal file is marked with a \n** nul-terminator byte (0x00). i.e. the entire contents of a master journal\n** file for a transaction involving two databases might be:\n**\n**   \"/home/bill/a.db-journal\\x00/home/bill/b.db-journal\\x00\"\n**\n** A master journal file may only be deleted once all of its child \n** journals have been rolled back.\n**\n** This function reads the contents of the master-journal file into \n** memory and loops through each of the child journal names. For\n** each child journal, it checks if:\n**\n**   * if the child journal exists, and if so\n**   * if the child journal contains a reference to master journal \n**     file zMaster\n**\n** If a child journal can be found that matches both of the criteria\n** above, this function returns without doing anything. Otherwise, if\n** no such child journal can be found, file zMaster is deleted from\n** the file-system using sqlite3OsDelete().\n**\n** If an IO error within this function, an error code is returned. This\n** function allocates memory by calling sqlite3Malloc(). If an allocation\n** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors \n** occur, SQLITE_OK is returned.\n**\n** TODO: This function allocates a single block of memory to load\n** the entire contents of the master journal file. This could be\n** a couple of kilobytes or so - potentially larger than the page \n** size.\n*/\nstatic int pager_delmaster(Pager *pPager, const char *zMaster){\n  sqlite3_vfs *pVfs = pPager->pVfs;\n  int rc;                   /* Return code */\n  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */\n  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */\n  char *zMasterJournal = 0; /* Contents of master journal file */\n  i64 nMasterJournal;       /* Size of master journal file */\n  char *zJournal;           /* Pointer to one journal within MJ file */\n  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */\n  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */\n\n  /* Allocate space for both the pJournal and pMaster file descriptors.\n  ** If successful, open the master journal file for reading.\n  */\n  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);\n  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);\n  if( !pMaster ){\n    rc = SQLITE_NOMEM_BKPT;\n  }else{\n    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);\n    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);\n  }\n  if( rc!=SQLITE_OK ) goto delmaster_out;\n\n  /* Load the entire master journal file into space obtained from\n  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain\n  ** sufficient space (in zMasterPtr) to hold the names of master\n  ** journal files extracted from regular rollback-journals.\n  */\n  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);\n  if( rc!=SQLITE_OK ) goto delmaster_out;\n  nMasterPtr = pVfs->mxPathname+1;\n  zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 2);\n  if( !zMasterJournal ){\n    rc = SQLITE_NOMEM_BKPT;\n    goto delmaster_out;\n  }\n  zMasterPtr = &zMasterJournal[nMasterJournal+2];\n  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);\n  if( rc!=SQLITE_OK ) goto delmaster_out;\n  zMasterJournal[nMasterJournal] = 0;\n  zMasterJournal[nMasterJournal+1] = 0;\n\n  zJournal = zMasterJournal;\n  while( (zJournal-zMasterJournal)<nMasterJournal ){\n    int exists;\n    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);\n    if( rc!=SQLITE_OK ){\n      goto delmaster_out;\n    }\n    if( exists ){\n      /* One of the journals pointed to by the master journal exists.\n      ** Open it and check if it points at the master journal. If\n      ** so, return without deleting the master journal file.\n      ** NB:  zJournal is really a MAIN_JOURNAL.  But call it a \n      ** MASTER_JOURNAL here so that the VFS will not send the zJournal\n      ** name into sqlite3_database_file_object().\n      */\n      int c;\n      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);\n      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);\n      if( rc!=SQLITE_OK ){\n        goto delmaster_out;\n      }\n\n      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);\n      sqlite3OsClose(pJournal);\n      if( rc!=SQLITE_OK ){\n        goto delmaster_out;\n      }\n\n      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;\n      if( c ){\n        /* We have a match. Do not delete the master journal file. */\n        goto delmaster_out;\n      }\n    }\n    zJournal += (sqlite3Strlen30(zJournal)+1);\n  }\n \n  sqlite3OsClose(pMaster);\n  rc = sqlite3OsDelete(pVfs, zMaster, 0);\n\ndelmaster_out:\n  sqlite3_free(zMasterJournal);\n  if( pMaster ){\n    sqlite3OsClose(pMaster);\n    assert( !isOpen(pJournal) );\n    sqlite3_free(pMaster);\n  }\n  return rc;\n}\n\n\n/*\n** This function is used to change the actual size of the database \n** file in the file-system. This only happens when committing a transaction,\n** or rolling back a transaction (including rolling back a hot-journal).\n**\n** If the main database file is not open, or the pager is not in either\n** DBMOD or OPEN state, this function is a no-op. Otherwise, the size \n** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). \n** If the file on disk is currently larger than nPage pages, then use the VFS\n** xTruncate() method to truncate it.\n**\n** Or, it might be the case that the file on disk is smaller than \n** nPage pages. Some operating system implementations can get confused if \n** you try to truncate a file to some size that is larger than it \n** currently is, so detect this case and write a single zero byte to \n** the end of the new file instead.\n**\n** If successful, return SQLITE_OK. If an IO error occurs while modifying\n** the database file, return the error code to the caller.\n*/\nstatic int pager_truncate(Pager *pPager, Pgno nPage){\n  int rc = SQLITE_OK;\n  assert( pPager->eState!=PAGER_ERROR );\n  assert( pPager->eState!=PAGER_READER );\n  \n  if( isOpen(pPager->fd) \n   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) \n  ){\n    i64 currentSize, newSize;\n    int szPage = pPager->pageSize;\n    assert( pPager->eLock==EXCLUSIVE_LOCK );\n    /* TODO: Is it safe to use Pager.dbFileSize here? */\n    rc = sqlite3OsFileSize(pPager->fd, &currentSize);\n    newSize = szPage*(i64)nPage;\n    if( rc==SQLITE_OK && currentSize!=newSize ){\n      if( currentSize>newSize ){\n        rc = sqlite3OsTruncate(pPager->fd, newSize);\n      }else if( (currentSize+szPage)<=newSize ){\n        char *pTmp = pPager->pTmpSpace;\n        memset(pTmp, 0, szPage);\n        testcase( (newSize-szPage) == currentSize );\n        testcase( (newSize-szPage) >  currentSize );\n        rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);\n      }\n      if( rc==SQLITE_OK ){\n        pPager->dbFileSize = nPage;\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** Return a sanitized version of the sector-size of OS file pFile. The\n** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.\n*/\nSQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){\n  int iRet = sqlite3OsSectorSize(pFile);\n  if( iRet<32 ){\n    iRet = 512;\n  }else if( iRet>MAX_SECTOR_SIZE ){\n    assert( MAX_SECTOR_SIZE>=512 );\n    iRet = MAX_SECTOR_SIZE;\n  }\n  return iRet;\n}\n\n/*\n** Set the value of the Pager.sectorSize variable for the given\n** pager based on the value returned by the xSectorSize method\n** of the open database file. The sector size will be used \n** to determine the size and alignment of journal header and \n** master journal pointers within created journal files.\n**\n** For temporary files the effective sector size is always 512 bytes.\n**\n** Otherwise, for non-temporary files, the effective sector size is\n** the value returned by the xSectorSize() method rounded up to 32 if\n** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it\n** is greater than MAX_SECTOR_SIZE.\n**\n** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set\n** the effective sector size to its minimum value (512).  The purpose of\n** pPager->sectorSize is to define the \"blast radius\" of bytes that\n** might change if a crash occurs while writing to a single byte in\n** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero\n** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector\n** size.  For backwards compatibility of the rollback journal file format,\n** we cannot reduce the effective sector size below 512.\n*/\nstatic void setSectorSize(Pager *pPager){\n  assert( isOpen(pPager->fd) || pPager->tempFile );\n\n  if( pPager->tempFile\n   || (sqlite3OsDeviceCharacteristics(pPager->fd) & \n              SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0\n  ){\n    /* Sector size doesn't matter for temporary files. Also, the file\n    ** may not have been opened yet, in which case the OsSectorSize()\n    ** call will segfault. */\n    pPager->sectorSize = 512;\n  }else{\n    pPager->sectorSize = sqlite3SectorSize(pPager->fd);\n  }\n}\n\n/*\n** Playback the journal and thus restore the database file to\n** the state it was in before we started making changes.  \n**\n** The journal file format is as follows: \n**\n**  (1)  8 byte prefix.  A copy of aJournalMagic[].\n**  (2)  4 byte big-endian integer which is the number of valid page records\n**       in the journal.  If this value is 0xffffffff, then compute the\n**       number of page records from the journal size.\n**  (3)  4 byte big-endian integer which is the initial value for the \n**       sanity checksum.\n**  (4)  4 byte integer which is the number of pages to truncate the\n**       database to during a rollback.\n**  (5)  4 byte big-endian integer which is the sector size.  The header\n**       is this many bytes in size.\n**  (6)  4 byte big-endian integer which is the page size.\n**  (7)  zero padding out to the next sector size.\n**  (8)  Zero or more pages instances, each as follows:\n**        +  4 byte page number.\n**        +  pPager->pageSize bytes of data.\n**        +  4 byte checksum\n**\n** When we speak of the journal header, we mean the first 7 items above.\n** Each entry in the journal is an instance of the 8th item.\n**\n** Call the value from the second bullet \"nRec\".  nRec is the number of\n** valid page entries in the journal.  In most cases, you can compute the\n** value of nRec from the size of the journal file.  But if a power\n** failure occurred while the journal was being written, it could be the\n** case that the size of the journal file had already been increased but\n** the extra entries had not yet made it safely to disk.  In such a case,\n** the value of nRec computed from the file size would be too large.  For\n** that reason, we always use the nRec value in the header.\n**\n** If the nRec value is 0xffffffff it means that nRec should be computed\n** from the file size.  This value is used when the user selects the\n** no-sync option for the journal.  A power failure could lead to corruption\n** in this case.  But for things like temporary table (which will be\n** deleted when the power is restored) we don't care.  \n**\n** If the file opened as the journal file is not a well-formed\n** journal file then all pages up to the first corrupted page are rolled\n** back (or no pages if the journal header is corrupted). The journal file\n** is then deleted and SQLITE_OK returned, just as if no corruption had\n** been encountered.\n**\n** If an I/O or malloc() error occurs, the journal-file is not deleted\n** and an error code is returned.\n**\n** The isHot parameter indicates that we are trying to rollback a journal\n** that might be a hot journal.  Or, it could be that the journal is \n** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.\n** If the journal really is hot, reset the pager cache prior rolling\n** back any content.  If the journal is merely persistent, no reset is\n** needed.\n*/\nstatic int pager_playback(Pager *pPager, int isHot){\n  sqlite3_vfs *pVfs = pPager->pVfs;\n  i64 szJ;                 /* Size of the journal file in bytes */\n  u32 nRec;                /* Number of Records in the journal */\n  u32 u;                   /* Unsigned loop counter */\n  Pgno mxPg = 0;           /* Size of the original file in pages */\n  int rc;                  /* Result code of a subroutine */\n  int res = 1;             /* Value returned by sqlite3OsAccess() */\n  char *zMaster = 0;       /* Name of master journal file if any */\n  int needPagerReset;      /* True to reset page prior to first page rollback */\n  int nPlayback = 0;       /* Total number of pages restored from journal */\n  u32 savedPageSize = pPager->pageSize;\n\n  /* Figure out how many records are in the journal.  Abort early if\n  ** the journal is empty.\n  */\n  assert( isOpen(pPager->jfd) );\n  rc = sqlite3OsFileSize(pPager->jfd, &szJ);\n  if( rc!=SQLITE_OK ){\n    goto end_playback;\n  }\n\n  /* Read the master journal name from the journal, if it is present.\n  ** If a master journal file name is specified, but the file is not\n  ** present on disk, then the journal is not hot and does not need to be\n  ** played back.\n  **\n  ** TODO: Technically the following is an error because it assumes that\n  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that\n  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,\n  ** mxPathname is 512, which is the same as the minimum allowable value\n  ** for pageSize.\n  */\n  zMaster = pPager->pTmpSpace;\n  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);\n  if( rc==SQLITE_OK && zMaster[0] ){\n    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);\n  }\n  zMaster = 0;\n  if( rc!=SQLITE_OK || !res ){\n    goto end_playback;\n  }\n  pPager->journalOff = 0;\n  needPagerReset = isHot;\n\n  /* This loop terminates either when a readJournalHdr() or \n  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error \n  ** occurs. \n  */\n  while( 1 ){\n    /* Read the next journal header from the journal file.  If there are\n    ** not enough bytes left in the journal file for a complete header, or\n    ** it is corrupted, then a process must have failed while writing it.\n    ** This indicates nothing more needs to be rolled back.\n    */\n    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);\n    if( rc!=SQLITE_OK ){ \n      if( rc==SQLITE_DONE ){\n        rc = SQLITE_OK;\n      }\n      goto end_playback;\n    }\n\n    /* If nRec is 0xffffffff, then this journal was created by a process\n    ** working in no-sync mode. This means that the rest of the journal\n    ** file consists of pages, there are no more journal headers. Compute\n    ** the value of nRec based on this assumption.\n    */\n    if( nRec==0xffffffff ){\n      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );\n      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));\n    }\n\n    /* If nRec is 0 and this rollback is of a transaction created by this\n    ** process and if this is the final header in the journal, then it means\n    ** that this part of the journal was being filled but has not yet been\n    ** synced to disk.  Compute the number of pages based on the remaining\n    ** size of the file.\n    **\n    ** The third term of the test was added to fix ticket #2565.\n    ** When rolling back a hot journal, nRec==0 always means that the next\n    ** chunk of the journal contains zero pages to be rolled back.  But\n    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in\n    ** the journal, it means that the journal might contain additional\n    ** pages that need to be rolled back and that the number of pages \n    ** should be computed based on the journal file size.\n    */\n    if( nRec==0 && !isHot &&\n        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){\n      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));\n    }\n\n    /* If this is the first header read from the journal, truncate the\n    ** database file back to its original size.\n    */\n    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){\n      rc = pager_truncate(pPager, mxPg);\n      if( rc!=SQLITE_OK ){\n        goto end_playback;\n      }\n      pPager->dbSize = mxPg;\n    }\n\n    /* Copy original pages out of the journal and back into the \n    ** database file and/or page cache.\n    */\n    for(u=0; u<nRec; u++){\n      if( needPagerReset ){\n        pager_reset(pPager);\n        needPagerReset = 0;\n      }\n      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);\n      if( rc==SQLITE_OK ){\n        nPlayback++;\n      }else{\n        if( rc==SQLITE_DONE ){\n          pPager->journalOff = szJ;\n          break;\n        }else if( rc==SQLITE_IOERR_SHORT_READ ){\n          /* If the journal has been truncated, simply stop reading and\n          ** processing the journal. This might happen if the journal was\n          ** not completely written and synced prior to a crash.  In that\n          ** case, the database should have never been written in the\n          ** first place so it is OK to simply abandon the rollback. */\n          rc = SQLITE_OK;\n          goto end_playback;\n        }else{\n          /* If we are unable to rollback, quit and return the error\n          ** code.  This will cause the pager to enter the error state\n          ** so that no further harm will be done.  Perhaps the next\n          ** process to come along will be able to rollback the database.\n          */\n          goto end_playback;\n        }\n      }\n    }\n  }\n  /*NOTREACHED*/\n  assert( 0 );\n\nend_playback:\n  if( rc==SQLITE_OK ){\n    rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);\n  }\n  /* Following a rollback, the database file should be back in its original\n  ** state prior to the start of the transaction, so invoke the\n  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the\n  ** assertion that the transaction counter was modified.\n  */\n#ifdef SQLITE_DEBUG\n  sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);\n#endif\n\n  /* If this playback is happening automatically as a result of an IO or \n  ** malloc error that occurred after the change-counter was updated but \n  ** before the transaction was committed, then the change-counter \n  ** modification may just have been reverted. If this happens in exclusive \n  ** mode, then subsequent transactions performed by the connection will not\n  ** update the change-counter at all. This may lead to cache inconsistency\n  ** problems for other processes at some point in the future. So, just\n  ** in case this has happened, clear the changeCountDone flag now.\n  */\n  pPager->changeCountDone = pPager->tempFile;\n\n  if( rc==SQLITE_OK ){\n    zMaster = pPager->pTmpSpace;\n    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);\n    testcase( rc!=SQLITE_OK );\n  }\n  if( rc==SQLITE_OK\n   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)\n  ){\n    rc = sqlite3PagerSync(pPager, 0);\n  }\n  if( rc==SQLITE_OK ){\n    rc = pager_end_transaction(pPager, zMaster[0]!='\\0', 0);\n    testcase( rc!=SQLITE_OK );\n  }\n  if( rc==SQLITE_OK && zMaster[0] && res ){\n    /* If there was a master journal and this routine will return success,\n    ** see if it is possible to delete the master journal.\n    */\n    rc = pager_delmaster(pPager, zMaster);\n    testcase( rc!=SQLITE_OK );\n  }\n  if( isHot && nPlayback ){\n    sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, \"recovered %d pages from %s\",\n                nPlayback, pPager->zJournal);\n  }\n\n  /* The Pager.sectorSize variable may have been updated while rolling\n  ** back a journal created by a process with a different sector size\n  ** value. Reset it to the correct value for this process.\n  */\n  setSectorSize(pPager);\n  return rc;\n}\n\n\n/*\n** Read the content for page pPg out of the database file (or out of\n** the WAL if that is where the most recent copy if found) into \n** pPg->pData. A shared lock or greater must be held on the database\n** file before this function is called.\n**\n** If page 1 is read, then the value of Pager.dbFileVers[] is set to\n** the value read from the database file.\n**\n** If an IO error occurs, then the IO error is returned to the caller.\n** Otherwise, SQLITE_OK is returned.\n*/\nstatic int readDbPage(PgHdr *pPg){\n  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */\n  int rc = SQLITE_OK;          /* Return code */\n\n#ifndef SQLITE_OMIT_WAL\n  u32 iFrame = 0;              /* Frame of WAL containing pgno */\n\n  assert( pPager->eState>=PAGER_READER && !MEMDB );\n  assert( isOpen(pPager->fd) );\n\n  if( pagerUseWal(pPager) ){\n    rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);\n    if( rc ) return rc;\n  }\n  if( iFrame ){\n    rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);\n  }else\n#endif\n  {\n    i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;\n    rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);\n    if( rc==SQLITE_IOERR_SHORT_READ ){\n      rc = SQLITE_OK;\n    }\n  }\n\n  if( pPg->pgno==1 ){\n    if( rc ){\n      /* If the read is unsuccessful, set the dbFileVers[] to something\n      ** that will never be a valid file version.  dbFileVers[] is a copy\n      ** of bytes 24..39 of the database.  Bytes 28..31 should always be\n      ** zero or the size of the database in page. Bytes 32..35 and 35..39\n      ** should be page numbers which are never 0xffffffff.  So filling\n      ** pPager->dbFileVers[] with all 0xff bytes should suffice.\n      **\n      ** For an encrypted database, the situation is more complex:  bytes\n      ** 24..39 of the database are white noise.  But the probability of\n      ** white noise equaling 16 bytes of 0xff is vanishingly small so\n      ** we should still be ok.\n      */\n      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));\n    }else{\n      u8 *dbFileVers = &((u8*)pPg->pData)[24];\n      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));\n    }\n  }\n  PAGER_INCR(sqlite3_pager_readdb_count);\n  PAGER_INCR(pPager->nRead);\n  IOTRACE((\"PGIN %p %d\\n\", pPager, pPg->pgno));\n  PAGERTRACE((\"FETCH %d page %d hash(%08x)\\n\",\n               PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));\n\n  return rc;\n}\n\n/*\n** Update the value of the change-counter at offsets 24 and 92 in\n** the header and the sqlite version number at offset 96.\n**\n** This is an unconditional update.  See also the pager_incr_changecounter()\n** routine which only updates the change-counter if the update is actually\n** needed, as determined by the pPager->changeCountDone state variable.\n*/\nstatic void pager_write_changecounter(PgHdr *pPg){\n  u32 change_counter;\n\n  /* Increment the value just read and write it back to byte 24. */\n  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;\n  put32bits(((char*)pPg->pData)+24, change_counter);\n\n  /* Also store the SQLite version number in bytes 96..99 and in\n  ** bytes 92..95 store the change counter for which the version number\n  ** is valid. */\n  put32bits(((char*)pPg->pData)+92, change_counter);\n  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);\n}\n\n#ifndef SQLITE_OMIT_WAL\n/*\n** This function is invoked once for each page that has already been \n** written into the log file when a WAL transaction is rolled back.\n** Parameter iPg is the page number of said page. The pCtx argument \n** is actually a pointer to the Pager structure.\n**\n** If page iPg is present in the cache, and has no outstanding references,\n** it is discarded. Otherwise, if there are one or more outstanding\n** references, the page content is reloaded from the database. If the\n** attempt to reload content from the database is required and fails, \n** return an SQLite error code. Otherwise, SQLITE_OK.\n*/\nstatic int pagerUndoCallback(void *pCtx, Pgno iPg){\n  int rc = SQLITE_OK;\n  Pager *pPager = (Pager *)pCtx;\n  PgHdr *pPg;\n\n  assert( pagerUseWal(pPager) );\n  pPg = sqlite3PagerLookup(pPager, iPg);\n  if( pPg ){\n    if( sqlite3PcachePageRefcount(pPg)==1 ){\n      sqlite3PcacheDrop(pPg);\n    }else{\n      rc = readDbPage(pPg);\n      if( rc==SQLITE_OK ){\n        pPager->xReiniter(pPg);\n      }\n      sqlite3PagerUnrefNotNull(pPg);\n    }\n  }\n\n  /* Normally, if a transaction is rolled back, any backup processes are\n  ** updated as data is copied out of the rollback journal and into the\n  ** database. This is not generally possible with a WAL database, as\n  ** rollback involves simply truncating the log file. Therefore, if one\n  ** or more frames have already been written to the log (and therefore \n  ** also copied into the backup databases) as part of this transaction,\n  ** the backups must be restarted.\n  */\n  sqlite3BackupRestart(pPager->pBackup);\n\n  return rc;\n}\n\n/*\n** This function is called to rollback a transaction on a WAL database.\n*/\nstatic int pagerRollbackWal(Pager *pPager){\n  int rc;                         /* Return Code */\n  PgHdr *pList;                   /* List of dirty pages to revert */\n\n  /* For all pages in the cache that are currently dirty or have already\n  ** been written (but not committed) to the log file, do one of the \n  ** following:\n  **\n  **   + Discard the cached page (if refcount==0), or\n  **   + Reload page content from the database (if refcount>0).\n  */\n  pPager->dbSize = pPager->dbOrigSize;\n  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);\n  pList = sqlite3PcacheDirtyList(pPager->pPCache);\n  while( pList && rc==SQLITE_OK ){\n    PgHdr *pNext = pList->pDirty;\n    rc = pagerUndoCallback((void *)pPager, pList->pgno);\n    pList = pNext;\n  }\n\n  return rc;\n}\n\n/*\n** This function is a wrapper around sqlite3WalFrames(). As well as logging\n** the contents of the list of pages headed by pList (connected by pDirty),\n** this function notifies any active backup processes that the pages have\n** changed. \n**\n** The list of pages passed into this routine is always sorted by page number.\n** Hence, if page 1 appears anywhere on the list, it will be the first page.\n*/ \nstatic int pagerWalFrames(\n  Pager *pPager,                  /* Pager object */\n  PgHdr *pList,                   /* List of frames to log */\n  Pgno nTruncate,                 /* Database size after this commit */\n  int isCommit                    /* True if this is a commit */\n){\n  int rc;                         /* Return code */\n  int nList;                      /* Number of pages in pList */\n  PgHdr *p;                       /* For looping over pages */\n\n  assert( pPager->pWal );\n  assert( pList );\n#ifdef SQLITE_DEBUG\n  /* Verify that the page list is in accending order */\n  for(p=pList; p && p->pDirty; p=p->pDirty){\n    assert( p->pgno < p->pDirty->pgno );\n  }\n#endif\n\n  assert( pList->pDirty==0 || isCommit );\n  if( isCommit ){\n    /* If a WAL transaction is being committed, there is no point in writing\n    ** any pages with page numbers greater than nTruncate into the WAL file.\n    ** They will never be read by any client. So remove them from the pDirty\n    ** list here. */\n    PgHdr **ppNext = &pList;\n    nList = 0;\n    for(p=pList; (*ppNext = p)!=0; p=p->pDirty){\n      if( p->pgno<=nTruncate ){\n        ppNext = &p->pDirty;\n        nList++;\n      }\n    }\n    assert( pList );\n  }else{\n    nList = 1;\n  }\n  pPager->aStat[PAGER_STAT_WRITE] += nList;\n\n  if( pList->pgno==1 ) pager_write_changecounter(pList);\n  rc = sqlite3WalFrames(pPager->pWal, \n      pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags\n  );\n  if( rc==SQLITE_OK && pPager->pBackup ){\n    for(p=pList; p; p=p->pDirty){\n      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);\n    }\n  }\n\n#ifdef SQLITE_CHECK_PAGES\n  pList = sqlite3PcacheDirtyList(pPager->pPCache);\n  for(p=pList; p; p=p->pDirty){\n    pager_set_pagehash(p);\n  }\n#endif\n\n  return rc;\n}\n\n/*\n** Begin a read transaction on the WAL.\n**\n** This routine used to be called \"pagerOpenSnapshot()\" because it essentially\n** makes a snapshot of the database at the current point in time and preserves\n** that snapshot for use by the reader in spite of concurrently changes by\n** other writers or checkpointers.\n*/\nstatic int pagerBeginReadTransaction(Pager *pPager){\n  int rc;                         /* Return code */\n  int changed = 0;                /* True if cache must be reset */\n\n  assert( pagerUseWal(pPager) );\n  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );\n\n  /* sqlite3WalEndReadTransaction() was not called for the previous\n  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we\n  ** are in locking_mode=NORMAL and EndRead() was previously called,\n  ** the duplicate call is harmless.\n  */\n  sqlite3WalEndReadTransaction(pPager->pWal);\n\n  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);\n  if( rc!=SQLITE_OK || changed ){\n    pager_reset(pPager);\n    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);\n  }\n\n  return rc;\n}\n#endif\n\n/*\n** This function is called as part of the transition from PAGER_OPEN\n** to PAGER_READER state to determine the size of the database file\n** in pages (assuming the page size currently stored in Pager.pageSize).\n**\n** If no error occurs, SQLITE_OK is returned and the size of the database\n** in pages is stored in *pnPage. Otherwise, an error code (perhaps\n** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.\n*/\nstatic int pagerPagecount(Pager *pPager, Pgno *pnPage){\n  Pgno nPage;                     /* Value to return via *pnPage */\n\n  /* Query the WAL sub-system for the database size. The WalDbsize()\n  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or\n  ** if the database size is not available. The database size is not\n  ** available from the WAL sub-system if the log file is empty or\n  ** contains no valid committed transactions.\n  */\n  assert( pPager->eState==PAGER_OPEN );\n  assert( pPager->eLock>=SHARED_LOCK );\n  assert( isOpen(pPager->fd) );\n  assert( pPager->tempFile==0 );\n  nPage = sqlite3WalDbsize(pPager->pWal);\n\n  /* If the number of pages in the database is not available from the\n  ** WAL sub-system, determine the page count based on the size of\n  ** the database file.  If the size of the database file is not an\n  ** integer multiple of the page-size, round up the result.\n  */\n  if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){\n    i64 n = 0;                    /* Size of db file in bytes */\n    int rc = sqlite3OsFileSize(pPager->fd, &n);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);\n  }\n\n  /* If the current number of pages in the file is greater than the\n  ** configured maximum pager number, increase the allowed limit so\n  ** that the file can be read.\n  */\n  if( nPage>pPager->mxPgno ){\n    pPager->mxPgno = (Pgno)nPage;\n  }\n\n  *pnPage = nPage;\n  return SQLITE_OK;\n}\n\n#ifndef SQLITE_OMIT_WAL\n/*\n** Check if the *-wal file that corresponds to the database opened by pPager\n** exists if the database is not empy, or verify that the *-wal file does\n** not exist (by deleting it) if the database file is empty.\n**\n** If the database is not empty and the *-wal file exists, open the pager\n** in WAL mode.  If the database is empty or if no *-wal file exists and\n** if no error occurs, make sure Pager.journalMode is not set to\n** PAGER_JOURNALMODE_WAL.\n**\n** Return SQLITE_OK or an error code.\n**\n** The caller must hold a SHARED lock on the database file to call this\n** function. Because an EXCLUSIVE lock on the db file is required to delete \n** a WAL on a none-empty database, this ensures there is no race condition \n** between the xAccess() below and an xDelete() being executed by some \n** other connection.\n*/\nstatic int pagerOpenWalIfPresent(Pager *pPager){\n  int rc = SQLITE_OK;\n  assert( pPager->eState==PAGER_OPEN );\n  assert( pPager->eLock>=SHARED_LOCK );\n\n  if( !pPager->tempFile ){\n    int isWal;                    /* True if WAL file exists */\n    rc = sqlite3OsAccess(\n        pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal\n    );\n    if( rc==SQLITE_OK ){\n      if( isWal ){\n        Pgno nPage;                   /* Size of the database file */\n\n        rc = pagerPagecount(pPager, &nPage);\n        if( rc ) return rc;\n        if( nPage==0 ){\n          rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);\n        }else{\n          testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );\n          rc = sqlite3PagerOpenWal(pPager, 0);\n        }\n      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){\n        pPager->journalMode = PAGER_JOURNALMODE_DELETE;\n      }\n    }\n  }\n  return rc;\n}\n#endif\n\n/*\n** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback\n** the entire master journal file. The case pSavepoint==NULL occurs when \n** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction \n** savepoint.\n**\n** When pSavepoint is not NULL (meaning a non-transaction savepoint is \n** being rolled back), then the rollback consists of up to three stages,\n** performed in the order specified:\n**\n**   * Pages are played back from the main journal starting at byte\n**     offset PagerSavepoint.iOffset and continuing to \n**     PagerSavepoint.iHdrOffset, or to the end of the main journal\n**     file if PagerSavepoint.iHdrOffset is zero.\n**\n**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played\n**     back starting from the journal header immediately following \n**     PagerSavepoint.iHdrOffset to the end of the main journal file.\n**\n**   * Pages are then played back from the sub-journal file, starting\n**     with the PagerSavepoint.iSubRec and continuing to the end of\n**     the journal file.\n**\n** Throughout the rollback process, each time a page is rolled back, the\n** corresponding bit is set in a bitvec structure (variable pDone in the\n** implementation below). This is used to ensure that a page is only\n** rolled back the first time it is encountered in either journal.\n**\n** If pSavepoint is NULL, then pages are only played back from the main\n** journal file. There is no need for a bitvec in this case.\n**\n** In either case, before playback commences the Pager.dbSize variable\n** is reset to the value that it held at the start of the savepoint \n** (or transaction). No page with a page-number greater than this value\n** is played back. If one is encountered it is simply skipped.\n*/\nstatic int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){\n  i64 szJ;                 /* Effective size of the main journal */\n  i64 iHdrOff;             /* End of first segment of main-journal records */\n  int rc = SQLITE_OK;      /* Return code */\n  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */\n\n  assert( pPager->eState!=PAGER_ERROR );\n  assert( pPager->eState>=PAGER_WRITER_LOCKED );\n\n  /* Allocate a bitvec to use to store the set of pages rolled back */\n  if( pSavepoint ){\n    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);\n    if( !pDone ){\n      return SQLITE_NOMEM_BKPT;\n    }\n  }\n\n  /* Set the database size back to the value it was before the savepoint \n  ** being reverted was opened.\n  */\n  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;\n  pPager->changeCountDone = pPager->tempFile;\n\n  if( !pSavepoint && pagerUseWal(pPager) ){\n    return pagerRollbackWal(pPager);\n  }\n\n  /* Use pPager->journalOff as the effective size of the main rollback\n  ** journal.  The actual file might be larger than this in\n  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything\n  ** past pPager->journalOff is off-limits to us.\n  */\n  szJ = pPager->journalOff;\n  assert( pagerUseWal(pPager)==0 || szJ==0 );\n\n  /* Begin by rolling back records from the main journal starting at\n  ** PagerSavepoint.iOffset and continuing to the next journal header.\n  ** There might be records in the main journal that have a page number\n  ** greater than the current database size (pPager->dbSize) but those\n  ** will be skipped automatically.  Pages are added to pDone as they\n  ** are played back.\n  */\n  if( pSavepoint && !pagerUseWal(pPager) ){\n    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;\n    pPager->journalOff = pSavepoint->iOffset;\n    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){\n      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);\n    }\n    assert( rc!=SQLITE_DONE );\n  }else{\n    pPager->journalOff = 0;\n  }\n\n  /* Continue rolling back records out of the main journal starting at\n  ** the first journal header seen and continuing until the effective end\n  ** of the main journal file.  Continue to skip out-of-range pages and\n  ** continue adding pages rolled back to pDone.\n  */\n  while( rc==SQLITE_OK && pPager->journalOff<szJ ){\n    u32 ii;            /* Loop counter */\n    u32 nJRec = 0;     /* Number of Journal Records */\n    u32 dummy;\n    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);\n    assert( rc!=SQLITE_DONE );\n\n    /*\n    ** The \"pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff\"\n    ** test is related to ticket #2565.  See the discussion in the\n    ** pager_playback() function for additional information.\n    */\n    if( nJRec==0 \n     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff\n    ){\n      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));\n    }\n    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){\n      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);\n    }\n    assert( rc!=SQLITE_DONE );\n  }\n  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );\n\n  /* Finally,  rollback pages from the sub-journal.  Page that were\n  ** previously rolled back out of the main journal (and are hence in pDone)\n  ** will be skipped.  Out-of-range pages are also skipped.\n  */\n  if( pSavepoint ){\n    u32 ii;            /* Loop counter */\n    i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);\n\n    if( pagerUseWal(pPager) ){\n      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);\n    }\n    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){\n      assert( offset==(i64)ii*(4+pPager->pageSize) );\n      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);\n    }\n    assert( rc!=SQLITE_DONE );\n  }\n\n  sqlite3BitvecDestroy(pDone);\n  if( rc==SQLITE_OK ){\n    pPager->journalOff = szJ;\n  }\n\n  return rc;\n}\n\n/*\n** Change the maximum number of in-memory pages that are allowed\n** before attempting to recycle clean and unused pages.\n*/\nSQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){\n  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);\n}\n\n/*\n** Change the maximum number of in-memory pages that are allowed\n** before attempting to spill pages to journal.\n*/\nSQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){\n  return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);\n}\n\n/*\n** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.\n*/\nstatic void pagerFixMaplimit(Pager *pPager){\n#if SQLITE_MAX_MMAP_SIZE>0\n  sqlite3_file *fd = pPager->fd;\n  if( isOpen(fd) && fd->pMethods->iVersion>=3 ){\n    sqlite3_int64 sz;\n    sz = pPager->szMmap;\n    pPager->bUseFetch = (sz>0);\n    setGetterMethod(pPager);\n    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);\n  }\n#endif\n}\n\n/*\n** Change the maximum size of any memory mapping made of the database file.\n*/\nSQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){\n  pPager->szMmap = szMmap;\n  pagerFixMaplimit(pPager);\n}\n\n/*\n** Free as much memory as possible from the pager.\n*/\nSQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){\n  sqlite3PcacheShrink(pPager->pPCache);\n}\n\n/*\n** Adjust settings of the pager to those specified in the pgFlags parameter.\n**\n** The \"level\" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness\n** of the database to damage due to OS crashes or power failures by\n** changing the number of syncs()s when writing the journals.\n** There are four levels:\n**\n**    OFF       sqlite3OsSync() is never called.  This is the default\n**              for temporary and transient files.\n**\n**    NORMAL    The journal is synced once before writes begin on the\n**              database.  This is normally adequate protection, but\n**              it is theoretically possible, though very unlikely,\n**              that an inopertune power failure could leave the journal\n**              in a state which would cause damage to the database\n**              when it is rolled back.\n**\n**    FULL      The journal is synced twice before writes begin on the\n**              database (with some additional information - the nRec field\n**              of the journal header - being written in between the two\n**              syncs).  If we assume that writing a\n**              single disk sector is atomic, then this mode provides\n**              assurance that the journal will not be corrupted to the\n**              point of causing damage to the database during rollback.\n**\n**    EXTRA     This is like FULL except that is also syncs the directory\n**              that contains the rollback journal after the rollback\n**              journal is unlinked.\n**\n** The above is for a rollback-journal mode.  For WAL mode, OFF continues\n** to mean that no syncs ever occur.  NORMAL means that the WAL is synced\n** prior to the start of checkpoint and that the database file is synced\n** at the conclusion of the checkpoint if the entire content of the WAL\n** was written back into the database.  But no sync operations occur for\n** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL\n** file is synced following each commit operation, in addition to the\n** syncs associated with NORMAL.  There is no difference between FULL\n** and EXTRA for WAL mode.\n**\n** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The\n** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync\n** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an\n** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL\n** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the\n** synchronous=FULL versus synchronous=NORMAL setting determines when\n** the xSync primitive is called and is relevant to all platforms.\n**\n** Numeric values associated with these states are OFF==1, NORMAL=2,\n** and FULL=3.\n*/\n#ifndef SQLITE_OMIT_PAGER_PRAGMAS\nSQLITE_PRIVATE void sqlite3PagerSetFlags(\n  Pager *pPager,        /* The pager to set safety level for */\n  unsigned pgFlags      /* Various flags */\n){\n  unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;\n  if( pPager->tempFile ){\n    pPager->noSync = 1;\n    pPager->fullSync = 0;\n    pPager->extraSync = 0;\n  }else{\n    pPager->noSync =  level==PAGER_SYNCHRONOUS_OFF ?1:0;\n    pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;\n    pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;\n  }\n  if( pPager->noSync ){\n    pPager->syncFlags = 0;\n  }else if( pgFlags & PAGER_FULLFSYNC ){\n    pPager->syncFlags = SQLITE_SYNC_FULL;\n  }else{\n    pPager->syncFlags = SQLITE_SYNC_NORMAL;\n  }\n  pPager->walSyncFlags = (pPager->syncFlags<<2);\n  if( pPager->fullSync ){\n    pPager->walSyncFlags |= pPager->syncFlags;\n  }\n  if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){\n    pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);\n  }\n  if( pgFlags & PAGER_CACHESPILL ){\n    pPager->doNotSpill &= ~SPILLFLAG_OFF;\n  }else{\n    pPager->doNotSpill |= SPILLFLAG_OFF;\n  }\n}\n#endif\n\n/*\n** The following global variable is incremented whenever the library\n** attempts to open a temporary file.  This information is used for\n** testing and analysis only.  \n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_opentemp_count = 0;\n#endif\n\n/*\n** Open a temporary file.\n**\n** Write the file descriptor into *pFile. Return SQLITE_OK on success \n** or some other error code if we fail. The OS will automatically \n** delete the temporary file when it is closed.\n**\n** The flags passed to the VFS layer xOpen() call are those specified\n** by parameter vfsFlags ORed with the following:\n**\n**     SQLITE_OPEN_READWRITE\n**     SQLITE_OPEN_CREATE\n**     SQLITE_OPEN_EXCLUSIVE\n**     SQLITE_OPEN_DELETEONCLOSE\n*/\nstatic int pagerOpentemp(\n  Pager *pPager,        /* The pager object */\n  sqlite3_file *pFile,  /* Write the file descriptor here */\n  int vfsFlags          /* Flags passed through to the VFS */\n){\n  int rc;               /* Return code */\n\n#ifdef SQLITE_TEST\n  sqlite3_opentemp_count++;  /* Used for testing and analysis only */\n#endif\n\n  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |\n            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;\n  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);\n  assert( rc!=SQLITE_OK || isOpen(pFile) );\n  return rc;\n}\n\n/*\n** Set the busy handler function.\n**\n** The pager invokes the busy-handler if sqlite3OsLock() returns \n** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,\n** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE \n** lock. It does *not* invoke the busy handler when upgrading from\n** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE\n** (which occurs during hot-journal rollback). Summary:\n**\n**   Transition                        | Invokes xBusyHandler\n**   --------------------------------------------------------\n**   NO_LOCK       -> SHARED_LOCK      | Yes\n**   SHARED_LOCK   -> RESERVED_LOCK    | No\n**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No\n**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes\n**\n** If the busy-handler callback returns non-zero, the lock is \n** retried. If it returns zero, then the SQLITE_BUSY error is\n** returned to the caller of the pager API function.\n*/\nSQLITE_PRIVATE void sqlite3PagerSetBusyHandler(\n  Pager *pPager,                       /* Pager object */\n  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */\n  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */\n){\n  void **ap;\n  pPager->xBusyHandler = xBusyHandler;\n  pPager->pBusyHandlerArg = pBusyHandlerArg;\n  ap = (void **)&pPager->xBusyHandler;\n  assert( ((int(*)(void *))(ap[0]))==xBusyHandler );\n  assert( ap[1]==pBusyHandlerArg );\n  sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);\n}\n\n/*\n** Change the page size used by the Pager object. The new page size \n** is passed in *pPageSize.\n**\n** If the pager is in the error state when this function is called, it\n** is a no-op. The value returned is the error state error code (i.e. \n** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).\n**\n** Otherwise, if all of the following are true:\n**\n**   * the new page size (value of *pPageSize) is valid (a power \n**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and\n**\n**   * there are no outstanding page references, and\n**\n**   * the database is either not an in-memory database or it is\n**     an in-memory database that currently consists of zero pages.\n**\n** then the pager object page size is set to *pPageSize.\n**\n** If the page size is changed, then this function uses sqlite3PagerMalloc() \n** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt \n** fails, SQLITE_NOMEM is returned and the page size remains unchanged. \n** In all other cases, SQLITE_OK is returned.\n**\n** If the page size is not changed, either because one of the enumerated\n** conditions above is not true, the pager was in error state when this\n** function was called, or because the memory allocation attempt failed, \n** then *pPageSize is set to the old, retained page size before returning.\n*/\nSQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){\n  int rc = SQLITE_OK;\n\n  /* It is not possible to do a full assert_pager_state() here, as this\n  ** function may be called from within PagerOpen(), before the state\n  ** of the Pager object is internally consistent.\n  **\n  ** At one point this function returned an error if the pager was in \n  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that\n  ** there is at least one outstanding page reference, this function\n  ** is a no-op for that case anyhow.\n  */\n\n  u32 pageSize = *pPageSize;\n  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );\n  if( (pPager->memDb==0 || pPager->dbSize==0)\n   && sqlite3PcacheRefCount(pPager->pPCache)==0 \n   && pageSize && pageSize!=(u32)pPager->pageSize \n  ){\n    char *pNew = NULL;             /* New temp space */\n    i64 nByte = 0;\n\n    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){\n      rc = sqlite3OsFileSize(pPager->fd, &nByte);\n    }\n    if( rc==SQLITE_OK ){\n      /* 8 bytes of zeroed overrun space is sufficient so that the b-tree\n      * cell header parser will never run off the end of the allocation */\n      pNew = (char *)sqlite3PageMalloc(pageSize+8);\n      if( !pNew ){\n        rc = SQLITE_NOMEM_BKPT;\n      }else{\n        memset(pNew+pageSize, 0, 8);\n      }\n    }\n\n    if( rc==SQLITE_OK ){\n      pager_reset(pPager);\n      rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);\n    }\n    if( rc==SQLITE_OK ){\n      sqlite3PageFree(pPager->pTmpSpace);\n      pPager->pTmpSpace = pNew;\n      pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);\n      pPager->pageSize = pageSize;\n    }else{\n      sqlite3PageFree(pNew);\n    }\n  }\n\n  *pPageSize = pPager->pageSize;\n  if( rc==SQLITE_OK ){\n    if( nReserve<0 ) nReserve = pPager->nReserve;\n    assert( nReserve>=0 && nReserve<1000 );\n    pPager->nReserve = (i16)nReserve;\n    pagerFixMaplimit(pPager);\n  }\n  return rc;\n}\n\n/*\n** Return a pointer to the \"temporary page\" buffer held internally\n** by the pager.  This is a buffer that is big enough to hold the\n** entire content of a database page.  This buffer is used internally\n** during rollback and will be overwritten whenever a rollback\n** occurs.  But other modules are free to use it too, as long as\n** no rollbacks are happening.\n*/\nSQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){\n  return pPager->pTmpSpace;\n}\n\n/*\n** Attempt to set the maximum database page count if mxPage is positive. \n** Make no changes if mxPage is zero or negative.  And never reduce the\n** maximum page count below the current size of the database.\n**\n** Regardless of mxPage, return the current maximum page count.\n*/\nSQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){\n  if( mxPage>0 ){\n    pPager->mxPgno = mxPage;\n  }\n  assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */\n  /* assert( pPager->mxPgno>=pPager->dbSize ); */\n  /* OP_MaxPgcnt ensures that the parameter passed to this function is not\n  ** less than the total number of valid pages in the database. But this\n  ** may be less than Pager.dbSize, and so the assert() above is not valid */\n  return pPager->mxPgno;\n}\n\n/*\n** The following set of routines are used to disable the simulated\n** I/O error mechanism.  These routines are used to avoid simulated\n** errors in places where we do not care about errors.\n**\n** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops\n** and generate no code.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API extern int sqlite3_io_error_pending;\nSQLITE_API extern int sqlite3_io_error_hit;\nstatic int saved_cnt;\nvoid disable_simulated_io_errors(void){\n  saved_cnt = sqlite3_io_error_pending;\n  sqlite3_io_error_pending = -1;\n}\nvoid enable_simulated_io_errors(void){\n  sqlite3_io_error_pending = saved_cnt;\n}\n#else\n# define disable_simulated_io_errors()\n# define enable_simulated_io_errors()\n#endif\n\n/*\n** Read the first N bytes from the beginning of the file into memory\n** that pDest points to. \n**\n** If the pager was opened on a transient file (zFilename==\"\"), or\n** opened on a file less than N bytes in size, the output buffer is\n** zeroed and SQLITE_OK returned. The rationale for this is that this \n** function is used to read database headers, and a new transient or\n** zero sized database has a header than consists entirely of zeroes.\n**\n** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,\n** the error code is returned to the caller and the contents of the\n** output buffer undefined.\n*/\nSQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){\n  int rc = SQLITE_OK;\n  memset(pDest, 0, N);\n  assert( isOpen(pPager->fd) || pPager->tempFile );\n\n  /* This routine is only called by btree immediately after creating\n  ** the Pager object.  There has not been an opportunity to transition\n  ** to WAL mode yet.\n  */\n  assert( !pagerUseWal(pPager) );\n\n  if( isOpen(pPager->fd) ){\n    IOTRACE((\"DBHDR %p 0 %d\\n\", pPager, N))\n    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);\n    if( rc==SQLITE_IOERR_SHORT_READ ){\n      rc = SQLITE_OK;\n    }\n  }\n  return rc;\n}\n\n/*\n** This function may only be called when a read-transaction is open on\n** the pager. It returns the total number of pages in the database.\n**\n** However, if the file is between 1 and <page-size> bytes in size, then \n** this is considered a 1 page file.\n*/\nSQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){\n  assert( pPager->eState>=PAGER_READER );\n  assert( pPager->eState!=PAGER_WRITER_FINISHED );\n  *pnPage = (int)pPager->dbSize;\n}\n\n\n/*\n** Try to obtain a lock of type locktype on the database file. If\n** a similar or greater lock is already held, this function is a no-op\n** (returning SQLITE_OK immediately).\n**\n** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke \n** the busy callback if the lock is currently not available. Repeat \n** until the busy callback returns false or until the attempt to \n** obtain the lock succeeds.\n**\n** Return SQLITE_OK on success and an error code if we cannot obtain\n** the lock. If the lock is obtained successfully, set the Pager.state \n** variable to locktype before returning.\n*/\nstatic int pager_wait_on_lock(Pager *pPager, int locktype){\n  int rc;                              /* Return code */\n\n  /* Check that this is either a no-op (because the requested lock is \n  ** already held), or one of the transitions that the busy-handler\n  ** may be invoked during, according to the comment above\n  ** sqlite3PagerSetBusyhandler().\n  */\n  assert( (pPager->eLock>=locktype)\n       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)\n       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)\n  );\n\n  do {\n    rc = pagerLockDb(pPager, locktype);\n  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );\n  return rc;\n}\n\n/*\n** Function assertTruncateConstraint(pPager) checks that one of the \n** following is true for all dirty pages currently in the page-cache:\n**\n**   a) The page number is less than or equal to the size of the \n**      current database image, in pages, OR\n**\n**   b) if the page content were written at this time, it would not\n**      be necessary to write the current content out to the sub-journal\n**      (as determined by function subjRequiresPage()).\n**\n** If the condition asserted by this function were not true, and the\n** dirty page were to be discarded from the cache via the pagerStress()\n** routine, pagerStress() would not write the current page content to\n** the database file. If a savepoint transaction were rolled back after\n** this happened, the correct behavior would be to restore the current\n** content of the page. However, since this content is not present in either\n** the database file or the portion of the rollback journal and \n** sub-journal rolled back the content could not be restored and the\n** database image would become corrupt. It is therefore fortunate that \n** this circumstance cannot arise.\n*/\n#if defined(SQLITE_DEBUG)\nstatic void assertTruncateConstraintCb(PgHdr *pPg){\n  assert( pPg->flags&PGHDR_DIRTY );\n  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );\n}\nstatic void assertTruncateConstraint(Pager *pPager){\n  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);\n}\n#else\n# define assertTruncateConstraint(pPager)\n#endif\n\n/*\n** Truncate the in-memory database file image to nPage pages. This \n** function does not actually modify the database file on disk. It \n** just sets the internal state of the pager object so that the \n** truncation will be done when the current transaction is committed.\n**\n** This function is only called right before committing a transaction.\n** Once this function has been called, the transaction must either be\n** rolled back or committed. It is not safe to call this function and\n** then continue writing to the database.\n*/\nSQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){\n  assert( pPager->dbSize>=nPage );\n  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );\n  pPager->dbSize = nPage;\n\n  /* At one point the code here called assertTruncateConstraint() to\n  ** ensure that all pages being truncated away by this operation are,\n  ** if one or more savepoints are open, present in the savepoint \n  ** journal so that they can be restored if the savepoint is rolled\n  ** back. This is no longer necessary as this function is now only\n  ** called right before committing a transaction. So although the \n  ** Pager object may still have open savepoints (Pager.nSavepoint!=0), \n  ** they cannot be rolled back. So the assertTruncateConstraint() call\n  ** is no longer correct. */\n}\n\n\n/*\n** This function is called before attempting a hot-journal rollback. It\n** syncs the journal file to disk, then sets pPager->journalHdr to the\n** size of the journal file so that the pager_playback() routine knows\n** that the entire journal file has been synced.\n**\n** Syncing a hot-journal to disk before attempting to roll it back ensures \n** that if a power-failure occurs during the rollback, the process that\n** attempts rollback following system recovery sees the same journal\n** content as this process.\n**\n** If everything goes as planned, SQLITE_OK is returned. Otherwise, \n** an SQLite error code.\n*/\nstatic int pagerSyncHotJournal(Pager *pPager){\n  int rc = SQLITE_OK;\n  if( !pPager->noSync ){\n    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);\n  }\n  return rc;\n}\n\n#if SQLITE_MAX_MMAP_SIZE>0\n/*\n** Obtain a reference to a memory mapped page object for page number pgno. \n** The new object will use the pointer pData, obtained from xFetch().\n** If successful, set *ppPage to point to the new page reference\n** and return SQLITE_OK. Otherwise, return an SQLite error code and set\n** *ppPage to zero.\n**\n** Page references obtained by calling this function should be released\n** by calling pagerReleaseMapPage().\n*/\nstatic int pagerAcquireMapPage(\n  Pager *pPager,                  /* Pager object */\n  Pgno pgno,                      /* Page number */\n  void *pData,                    /* xFetch()'d data for this page */\n  PgHdr **ppPage                  /* OUT: Acquired page object */\n){\n  PgHdr *p;                       /* Memory mapped page to return */\n  \n  if( pPager->pMmapFreelist ){\n    *ppPage = p = pPager->pMmapFreelist;\n    pPager->pMmapFreelist = p->pDirty;\n    p->pDirty = 0;\n    assert( pPager->nExtra>=8 );\n    memset(p->pExtra, 0, 8);\n  }else{\n    *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);\n    if( p==0 ){\n      sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);\n      return SQLITE_NOMEM_BKPT;\n    }\n    p->pExtra = (void *)&p[1];\n    p->flags = PGHDR_MMAP;\n    p->nRef = 1;\n    p->pPager = pPager;\n  }\n\n  assert( p->pExtra==(void *)&p[1] );\n  assert( p->pPage==0 );\n  assert( p->flags==PGHDR_MMAP );\n  assert( p->pPager==pPager );\n  assert( p->nRef==1 );\n\n  p->pgno = pgno;\n  p->pData = pData;\n  pPager->nMmapOut++;\n\n  return SQLITE_OK;\n}\n#endif\n\n/*\n** Release a reference to page pPg. pPg must have been returned by an \n** earlier call to pagerAcquireMapPage().\n*/\nstatic void pagerReleaseMapPage(PgHdr *pPg){\n  Pager *pPager = pPg->pPager;\n  pPager->nMmapOut--;\n  pPg->pDirty = pPager->pMmapFreelist;\n  pPager->pMmapFreelist = pPg;\n\n  assert( pPager->fd->pMethods->iVersion>=3 );\n  sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);\n}\n\n/*\n** Free all PgHdr objects stored in the Pager.pMmapFreelist list.\n*/\nstatic void pagerFreeMapHdrs(Pager *pPager){\n  PgHdr *p;\n  PgHdr *pNext;\n  for(p=pPager->pMmapFreelist; p; p=pNext){\n    pNext = p->pDirty;\n    sqlite3_free(p);\n  }\n}\n\n/* Verify that the database file has not be deleted or renamed out from\n** under the pager.  Return SQLITE_OK if the database is still where it ought\n** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error\n** code from sqlite3OsAccess()) if the database has gone missing.\n*/\nstatic int databaseIsUnmoved(Pager *pPager){\n  int bHasMoved = 0;\n  int rc;\n\n  if( pPager->tempFile ) return SQLITE_OK;\n  if( pPager->dbSize==0 ) return SQLITE_OK;\n  assert( pPager->zFilename && pPager->zFilename[0] );\n  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);\n  if( rc==SQLITE_NOTFOUND ){\n    /* If the HAS_MOVED file-control is unimplemented, assume that the file\n    ** has not been moved.  That is the historical behavior of SQLite: prior to\n    ** version 3.8.3, it never checked */\n    rc = SQLITE_OK;\n  }else if( rc==SQLITE_OK && bHasMoved ){\n    rc = SQLITE_READONLY_DBMOVED;\n  }\n  return rc;\n}\n\n\n/*\n** Shutdown the page cache.  Free all memory and close all files.\n**\n** If a transaction was in progress when this routine is called, that\n** transaction is rolled back.  All outstanding pages are invalidated\n** and their memory is freed.  Any attempt to use a page associated\n** with this page cache after this function returns will likely\n** result in a coredump.\n**\n** This function always succeeds. If a transaction is active an attempt\n** is made to roll it back. If an error occurs during the rollback \n** a hot journal may be left in the filesystem but no error is returned\n** to the caller.\n*/\nSQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){\n  u8 *pTmp = (u8*)pPager->pTmpSpace;\n  assert( db || pagerUseWal(pPager)==0 );\n  assert( assert_pager_state(pPager) );\n  disable_simulated_io_errors();\n  sqlite3BeginBenignMalloc();\n  pagerFreeMapHdrs(pPager);\n  /* pPager->errCode = 0; */\n  pPager->exclusiveMode = 0;\n#ifndef SQLITE_OMIT_WAL\n  {\n    u8 *a = 0;\n    assert( db || pPager->pWal==0 );\n    if( db && 0==(db->flags & SQLITE_NoCkptOnClose) \n     && SQLITE_OK==databaseIsUnmoved(pPager)\n    ){\n      a = pTmp;\n    }\n    sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a);\n    pPager->pWal = 0;\n  }\n#endif\n  pager_reset(pPager);\n  if( MEMDB ){\n    pager_unlock(pPager);\n  }else{\n    /* If it is open, sync the journal file before calling UnlockAndRollback.\n    ** If this is not done, then an unsynced portion of the open journal \n    ** file may be played back into the database. If a power failure occurs \n    ** while this is happening, the database could become corrupt.\n    **\n    ** If an error occurs while trying to sync the journal, shift the pager\n    ** into the ERROR state. This causes UnlockAndRollback to unlock the\n    ** database and close the journal file without attempting to roll it\n    ** back or finalize it. The next database user will have to do hot-journal\n    ** rollback before accessing the database file.\n    */\n    if( isOpen(pPager->jfd) ){\n      pager_error(pPager, pagerSyncHotJournal(pPager));\n    }\n    pagerUnlockAndRollback(pPager);\n  }\n  sqlite3EndBenignMalloc();\n  enable_simulated_io_errors();\n  PAGERTRACE((\"CLOSE %d\\n\", PAGERID(pPager)));\n  IOTRACE((\"CLOSE %p\\n\", pPager))\n  sqlite3OsClose(pPager->jfd);\n  sqlite3OsClose(pPager->fd);\n  sqlite3PageFree(pTmp);\n  sqlite3PcacheClose(pPager->pPCache);\n  assert( !pPager->aSavepoint && !pPager->pInJournal );\n  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );\n\n  sqlite3_free(pPager);\n  return SQLITE_OK;\n}\n\n#if !defined(NDEBUG) || defined(SQLITE_TEST)\n/*\n** Return the page number for page pPg.\n*/\nSQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){\n  return pPg->pgno;\n}\n#endif\n\n/*\n** Increment the reference count for page pPg.\n*/\nSQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){\n  sqlite3PcacheRef(pPg);\n}\n\n/*\n** Sync the journal. In other words, make sure all the pages that have\n** been written to the journal have actually reached the surface of the\n** disk and can be restored in the event of a hot-journal rollback.\n**\n** If the Pager.noSync flag is set, then this function is a no-op.\n** Otherwise, the actions required depend on the journal-mode and the \n** device characteristics of the file-system, as follows:\n**\n**   * If the journal file is an in-memory journal file, no action need\n**     be taken.\n**\n**   * Otherwise, if the device does not support the SAFE_APPEND property,\n**     then the nRec field of the most recently written journal header\n**     is updated to contain the number of journal records that have\n**     been written following it. If the pager is operating in full-sync\n**     mode, then the journal file is synced before this field is updated.\n**\n**   * If the device does not support the SEQUENTIAL property, then \n**     journal file is synced.\n**\n** Or, in pseudo-code:\n**\n**   if( NOT <in-memory journal> ){\n**     if( NOT SAFE_APPEND ){\n**       if( <full-sync mode> ) xSync(<journal file>);\n**       <update nRec field>\n**     } \n**     if( NOT SEQUENTIAL ) xSync(<journal file>);\n**   }\n**\n** If successful, this routine clears the PGHDR_NEED_SYNC flag of every \n** page currently held in memory before returning SQLITE_OK. If an IO\n** error is encountered, then the IO error code is returned to the caller.\n*/\nstatic int syncJournal(Pager *pPager, int newHdr){\n  int rc;                         /* Return code */\n\n  assert( pPager->eState==PAGER_WRITER_CACHEMOD\n       || pPager->eState==PAGER_WRITER_DBMOD\n  );\n  assert( assert_pager_state(pPager) );\n  assert( !pagerUseWal(pPager) );\n\n  rc = sqlite3PagerExclusiveLock(pPager);\n  if( rc!=SQLITE_OK ) return rc;\n\n  if( !pPager->noSync ){\n    assert( !pPager->tempFile );\n    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){\n      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);\n      assert( isOpen(pPager->jfd) );\n\n      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){\n        /* This block deals with an obscure problem. If the last connection\n        ** that wrote to this database was operating in persistent-journal\n        ** mode, then the journal file may at this point actually be larger\n        ** than Pager.journalOff bytes. If the next thing in the journal\n        ** file happens to be a journal-header (written as part of the\n        ** previous connection's transaction), and a crash or power-failure \n        ** occurs after nRec is updated but before this connection writes \n        ** anything else to the journal file (or commits/rolls back its \n        ** transaction), then SQLite may become confused when doing the \n        ** hot-journal rollback following recovery. It may roll back all\n        ** of this connections data, then proceed to rolling back the old,\n        ** out-of-date data that follows it. Database corruption.\n        **\n        ** To work around this, if the journal file does appear to contain\n        ** a valid header following Pager.journalOff, then write a 0x00\n        ** byte to the start of it to prevent it from being recognized.\n        **\n        ** Variable iNextHdrOffset is set to the offset at which this\n        ** problematic header will occur, if it exists. aMagic is used \n        ** as a temporary buffer to inspect the first couple of bytes of\n        ** the potential journal header.\n        */\n        i64 iNextHdrOffset;\n        u8 aMagic[8];\n        u8 zHeader[sizeof(aJournalMagic)+4];\n\n        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));\n        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);\n\n        iNextHdrOffset = journalHdrOffset(pPager);\n        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);\n        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){\n          static const u8 zerobyte = 0;\n          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);\n        }\n        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){\n          return rc;\n        }\n\n        /* Write the nRec value into the journal file header. If in\n        ** full-synchronous mode, sync the journal first. This ensures that\n        ** all data has really hit the disk before nRec is updated to mark\n        ** it as a candidate for rollback.\n        **\n        ** This is not required if the persistent media supports the\n        ** SAFE_APPEND property. Because in this case it is not possible \n        ** for garbage data to be appended to the file, the nRec field\n        ** is populated with 0xFFFFFFFF when the journal header is written\n        ** and never needs to be updated.\n        */\n        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){\n          PAGERTRACE((\"SYNC journal of %d\\n\", PAGERID(pPager)));\n          IOTRACE((\"JSYNC %p\\n\", pPager))\n          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);\n          if( rc!=SQLITE_OK ) return rc;\n        }\n        IOTRACE((\"JHDR %p %lld\\n\", pPager, pPager->journalHdr));\n        rc = sqlite3OsWrite(\n            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr\n        );\n        if( rc!=SQLITE_OK ) return rc;\n      }\n      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){\n        PAGERTRACE((\"SYNC journal of %d\\n\", PAGERID(pPager)));\n        IOTRACE((\"JSYNC %p\\n\", pPager))\n        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| \n          (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)\n        );\n        if( rc!=SQLITE_OK ) return rc;\n      }\n\n      pPager->journalHdr = pPager->journalOff;\n      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){\n        pPager->nRec = 0;\n        rc = writeJournalHdr(pPager);\n        if( rc!=SQLITE_OK ) return rc;\n      }\n    }else{\n      pPager->journalHdr = pPager->journalOff;\n    }\n  }\n\n  /* Unless the pager is in noSync mode, the journal file was just \n  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on \n  ** all pages.\n  */\n  sqlite3PcacheClearSyncFlags(pPager->pPCache);\n  pPager->eState = PAGER_WRITER_DBMOD;\n  assert( assert_pager_state(pPager) );\n  return SQLITE_OK;\n}\n\n/*\n** The argument is the first in a linked list of dirty pages connected\n** by the PgHdr.pDirty pointer. This function writes each one of the\n** in-memory pages in the list to the database file. The argument may\n** be NULL, representing an empty list. In this case this function is\n** a no-op.\n**\n** The pager must hold at least a RESERVED lock when this function\n** is called. Before writing anything to the database file, this lock\n** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,\n** SQLITE_BUSY is returned and no data is written to the database file.\n** \n** If the pager is a temp-file pager and the actual file-system file\n** is not yet open, it is created and opened before any data is \n** written out.\n**\n** Once the lock has been upgraded and, if necessary, the file opened,\n** the pages are written out to the database file in list order. Writing\n** a page is skipped if it meets either of the following criteria:\n**\n**   * The page number is greater than Pager.dbSize, or\n**   * The PGHDR_DONT_WRITE flag is set on the page.\n**\n** If writing out a page causes the database file to grow, Pager.dbFileSize\n** is updated accordingly. If page 1 is written out, then the value cached\n** in Pager.dbFileVers[] is updated to match the new value stored in\n** the database file.\n**\n** If everything is successful, SQLITE_OK is returned. If an IO error \n** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot\n** be obtained, SQLITE_BUSY is returned.\n*/\nstatic int pager_write_pagelist(Pager *pPager, PgHdr *pList){\n  int rc = SQLITE_OK;                  /* Return code */\n\n  /* This function is only called for rollback pagers in WRITER_DBMOD state. */\n  assert( !pagerUseWal(pPager) );\n  assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );\n  assert( pPager->eLock==EXCLUSIVE_LOCK );\n  assert( isOpen(pPager->fd) || pList->pDirty==0 );\n\n  /* If the file is a temp-file has not yet been opened, open it now. It\n  ** is not possible for rc to be other than SQLITE_OK if this branch\n  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.\n  */\n  if( !isOpen(pPager->fd) ){\n    assert( pPager->tempFile && rc==SQLITE_OK );\n    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);\n  }\n\n  /* Before the first write, give the VFS a hint of what the final\n  ** file size will be.\n  */\n  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );\n  if( rc==SQLITE_OK \n   && pPager->dbHintSize<pPager->dbSize\n   && (pList->pDirty || pList->pgno>pPager->dbHintSize)\n  ){\n    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;\n    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);\n    pPager->dbHintSize = pPager->dbSize;\n  }\n\n  while( rc==SQLITE_OK && pList ){\n    Pgno pgno = pList->pgno;\n\n    /* If there are dirty pages in the page cache with page numbers greater\n    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to\n    ** make the file smaller (presumably by auto-vacuum code). Do not write\n    ** any such pages to the file.\n    **\n    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag\n    ** set (set by sqlite3PagerDontWrite()).\n    */\n    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){\n      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */\n      char *pData;                                   /* Data to write */    \n\n      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );\n      if( pList->pgno==1 ) pager_write_changecounter(pList);\n\n      pData = pList->pData;\n\n      /* Write out the page data. */\n      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);\n\n      /* If page 1 was just written, update Pager.dbFileVers to match\n      ** the value now stored in the database file. If writing this \n      ** page caused the database file to grow, update dbFileSize. \n      */\n      if( pgno==1 ){\n        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));\n      }\n      if( pgno>pPager->dbFileSize ){\n        pPager->dbFileSize = pgno;\n      }\n      pPager->aStat[PAGER_STAT_WRITE]++;\n\n      /* Update any backup objects copying the contents of this pager. */\n      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);\n\n      PAGERTRACE((\"STORE %d page %d hash(%08x)\\n\",\n                   PAGERID(pPager), pgno, pager_pagehash(pList)));\n      IOTRACE((\"PGOUT %p %d\\n\", pPager, pgno));\n      PAGER_INCR(sqlite3_pager_writedb_count);\n    }else{\n      PAGERTRACE((\"NOSTORE %d page %d\\n\", PAGERID(pPager), pgno));\n    }\n    pager_set_pagehash(pList);\n    pList = pList->pDirty;\n  }\n\n  return rc;\n}\n\n/*\n** Ensure that the sub-journal file is open. If it is already open, this \n** function is a no-op.\n**\n** SQLITE_OK is returned if everything goes according to plan. An \n** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() \n** fails.\n*/\nstatic int openSubJournal(Pager *pPager){\n  int rc = SQLITE_OK;\n  if( !isOpen(pPager->sjfd) ){\n    const int flags =  SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE \n      | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE \n      | SQLITE_OPEN_DELETEONCLOSE;\n    int nStmtSpill = sqlite3Config.nStmtSpill;\n    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){\n      nStmtSpill = -1;\n    }\n    rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);\n  }\n  return rc;\n}\n\n/*\n** Append a record of the current state of page pPg to the sub-journal. \n**\n** If successful, set the bit corresponding to pPg->pgno in the bitvecs\n** for all open savepoints before returning.\n**\n** This function returns SQLITE_OK if everything is successful, an IO\n** error code if the attempt to write to the sub-journal fails, or \n** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint\n** bitvec.\n*/\nstatic int subjournalPage(PgHdr *pPg){\n  int rc = SQLITE_OK;\n  Pager *pPager = pPg->pPager;\n  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){\n\n    /* Open the sub-journal, if it has not already been opened */\n    assert( pPager->useJournal );\n    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );\n    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );\n    assert( pagerUseWal(pPager) \n         || pageInJournal(pPager, pPg) \n         || pPg->pgno>pPager->dbOrigSize \n    );\n    rc = openSubJournal(pPager);\n\n    /* If the sub-journal was opened successfully (or was already open),\n    ** write the journal record into the file.  */\n    if( rc==SQLITE_OK ){\n      void *pData = pPg->pData;\n      i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);\n      char *pData2;\n      pData2 = pData;\n      PAGERTRACE((\"STMT-JOURNAL %d page %d\\n\", PAGERID(pPager), pPg->pgno));\n      rc = write32bits(pPager->sjfd, offset, pPg->pgno);\n      if( rc==SQLITE_OK ){\n        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);\n      }\n    }\n  }\n  if( rc==SQLITE_OK ){\n    pPager->nSubRec++;\n    assert( pPager->nSavepoint>0 );\n    rc = addToSavepointBitvecs(pPager, pPg->pgno);\n  }\n  return rc;\n}\nstatic int subjournalPageIfRequired(PgHdr *pPg){\n  if( subjRequiresPage(pPg) ){\n    return subjournalPage(pPg);\n  }else{\n    return SQLITE_OK;\n  }\n}\n\n/*\n** This function is called by the pcache layer when it has reached some\n** soft memory limit. The first argument is a pointer to a Pager object\n** (cast as a void*). The pager is always 'purgeable' (not an in-memory\n** database). The second argument is a reference to a page that is \n** currently dirty but has no outstanding references. The page\n** is always associated with the Pager object passed as the first \n** argument.\n**\n** The job of this function is to make pPg clean by writing its contents\n** out to the database file, if possible. This may involve syncing the\n** journal file. \n**\n** If successful, sqlite3PcacheMakeClean() is called on the page and\n** SQLITE_OK returned. If an IO error occurs while trying to make the\n** page clean, the IO error code is returned. If the page cannot be\n** made clean for some other reason, but no error occurs, then SQLITE_OK\n** is returned by sqlite3PcacheMakeClean() is not called.\n*/\nstatic int pagerStress(void *p, PgHdr *pPg){\n  Pager *pPager = (Pager *)p;\n  int rc = SQLITE_OK;\n\n  assert( pPg->pPager==pPager );\n  assert( pPg->flags&PGHDR_DIRTY );\n\n  /* The doNotSpill NOSYNC bit is set during times when doing a sync of\n  ** journal (and adding a new header) is not allowed.  This occurs\n  ** during calls to sqlite3PagerWrite() while trying to journal multiple\n  ** pages belonging to the same sector.\n  **\n  ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling\n  ** regardless of whether or not a sync is required.  This is set during\n  ** a rollback or by user request, respectively.\n  **\n  ** Spilling is also prohibited when in an error state since that could\n  ** lead to database corruption.   In the current implementation it \n  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3\n  ** while in the error state, hence it is impossible for this routine to\n  ** be called in the error state.  Nevertheless, we include a NEVER()\n  ** test for the error state as a safeguard against future changes.\n  */\n  if( NEVER(pPager->errCode) ) return SQLITE_OK;\n  testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );\n  testcase( pPager->doNotSpill & SPILLFLAG_OFF );\n  testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );\n  if( pPager->doNotSpill\n   && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0\n      || (pPg->flags & PGHDR_NEED_SYNC)!=0)\n  ){\n    return SQLITE_OK;\n  }\n\n  pPager->aStat[PAGER_STAT_SPILL]++;\n  pPg->pDirty = 0;\n  if( pagerUseWal(pPager) ){\n    /* Write a single frame for this page to the log. */\n    rc = subjournalPageIfRequired(pPg); \n    if( rc==SQLITE_OK ){\n      rc = pagerWalFrames(pPager, pPg, 0, 0);\n    }\n  }else{\n    \n#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE\n    if( pPager->tempFile==0 ){\n      rc = sqlite3JournalCreate(pPager->jfd);\n      if( rc!=SQLITE_OK ) return pager_error(pPager, rc);\n    }\n#endif\n  \n    /* Sync the journal file if required. */\n    if( pPg->flags&PGHDR_NEED_SYNC \n     || pPager->eState==PAGER_WRITER_CACHEMOD\n    ){\n      rc = syncJournal(pPager, 1);\n    }\n  \n    /* Write the contents of the page out to the database file. */\n    if( rc==SQLITE_OK ){\n      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );\n      rc = pager_write_pagelist(pPager, pPg);\n    }\n  }\n\n  /* Mark the page as clean. */\n  if( rc==SQLITE_OK ){\n    PAGERTRACE((\"STRESS %d page %d\\n\", PAGERID(pPager), pPg->pgno));\n    sqlite3PcacheMakeClean(pPg);\n  }\n\n  return pager_error(pPager, rc); \n}\n\n/*\n** Flush all unreferenced dirty pages to disk.\n*/\nSQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){\n  int rc = pPager->errCode;\n  if( !MEMDB ){\n    PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);\n    assert( assert_pager_state(pPager) );\n    while( rc==SQLITE_OK && pList ){\n      PgHdr *pNext = pList->pDirty;\n      if( pList->nRef==0 ){\n        rc = pagerStress((void*)pPager, pList);\n      }\n      pList = pNext;\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Allocate and initialize a new Pager object and put a pointer to it\n** in *ppPager. The pager should eventually be freed by passing it\n** to sqlite3PagerClose().\n**\n** The zFilename argument is the path to the database file to open.\n** If zFilename is NULL then a randomly-named temporary file is created\n** and used as the file to be cached. Temporary files are be deleted\n** automatically when they are closed. If zFilename is \":memory:\" then \n** all information is held in cache. It is never written to disk. \n** This can be used to implement an in-memory database.\n**\n** The nExtra parameter specifies the number of bytes of space allocated\n** along with each page reference. This space is available to the user\n** via the sqlite3PagerGetExtra() API.  When a new page is allocated, the\n** first 8 bytes of this space are zeroed but the remainder is uninitialized.\n** (The extra space is used by btree as the MemPage object.)\n**\n** The flags argument is used to specify properties that affect the\n** operation of the pager. It should be passed some bitwise combination\n** of the PAGER_* flags.\n**\n** The vfsFlags parameter is a bitmask to pass to the flags parameter\n** of the xOpen() method of the supplied VFS when opening files. \n**\n** If the pager object is allocated and the specified file opened \n** successfully, SQLITE_OK is returned and *ppPager set to point to\n** the new pager object. If an error occurs, *ppPager is set to NULL\n** and error code returned. This function may return SQLITE_NOMEM\n** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or \n** various SQLITE_IO_XXX errors.\n*/\nSQLITE_PRIVATE int sqlite3PagerOpen(\n  sqlite3_vfs *pVfs,       /* The virtual file system to use */\n  Pager **ppPager,         /* OUT: Return the Pager structure here */\n  const char *zFilename,   /* Name of the database file to open */\n  int nExtra,              /* Extra bytes append to each in-memory page */\n  int flags,               /* flags controlling this file */\n  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */\n  void (*xReinit)(DbPage*) /* Function to reinitialize pages */\n){\n  u8 *pPtr;\n  Pager *pPager = 0;       /* Pager object to allocate and return */\n  int rc = SQLITE_OK;      /* Return code */\n  int tempFile = 0;        /* True for temp files (incl. in-memory files) */\n  int memDb = 0;           /* True if this is an in-memory file */\n#ifdef SQLITE_ENABLE_DESERIALIZE\n  int memJM = 0;           /* Memory journal mode */\n#else\n# define memJM 0\n#endif\n  int readOnly = 0;        /* True if this is a read-only file */\n  int journalFileSize;     /* Bytes to allocate for each journal fd */\n  char *zPathname = 0;     /* Full path to database file */\n  int nPathname = 0;       /* Number of bytes in zPathname */\n  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */\n  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */\n  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */\n  const char *zUri = 0;    /* URI args to copy */\n  int nUriByte = 1;        /* Number of bytes of URI args at *zUri */\n  int nUri = 0;            /* Number of URI parameters */\n\n  /* Figure out how much space is required for each journal file-handle\n  ** (there are two of them, the main journal and the sub-journal).  */\n  journalFileSize = ROUND8(sqlite3JournalSize(pVfs));\n\n  /* Set the output variable to NULL in case an error occurs. */\n  *ppPager = 0;\n\n#ifndef SQLITE_OMIT_MEMORYDB\n  if( flags & PAGER_MEMORY ){\n    memDb = 1;\n    if( zFilename && zFilename[0] ){\n      zPathname = sqlite3DbStrDup(0, zFilename);\n      if( zPathname==0  ) return SQLITE_NOMEM_BKPT;\n      nPathname = sqlite3Strlen30(zPathname);\n      zFilename = 0;\n    }\n  }\n#endif\n\n  /* Compute and store the full pathname in an allocated buffer pointed\n  ** to by zPathname, length nPathname. Or, if this is a temporary file,\n  ** leave both nPathname and zPathname set to 0.\n  */\n  if( zFilename && zFilename[0] ){\n    const char *z;\n    nPathname = pVfs->mxPathname+1;\n    zPathname = sqlite3DbMallocRaw(0, nPathname*2);\n    if( zPathname==0 ){\n      return SQLITE_NOMEM_BKPT;\n    }\n    zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */\n    rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);\n    if( rc!=SQLITE_OK ){\n      if( rc==SQLITE_OK_SYMLINK ){\n        if( vfsFlags & SQLITE_OPEN_NOFOLLOW ){\n          rc = SQLITE_CANTOPEN_SYMLINK;\n        }else{\n          rc = SQLITE_OK;\n        }\n      }\n    }\n    nPathname = sqlite3Strlen30(zPathname);\n    z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];\n    while( *z ){\n      z += strlen(z)+1;\n      z += strlen(z)+1;\n      nUri++;\n    }\n    nUriByte = (int)(&z[1] - zUri);\n    assert( nUriByte>=1 );\n    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){\n      /* This branch is taken when the journal path required by\n      ** the database being opened will be more than pVfs->mxPathname\n      ** bytes in length. This means the database cannot be opened,\n      ** as it will not be possible to open the journal file or even\n      ** check for a hot-journal before reading.\n      */\n      rc = SQLITE_CANTOPEN_BKPT;\n    }\n    if( rc!=SQLITE_OK ){\n      sqlite3DbFree(0, zPathname);\n      return rc;\n    }\n  }\n\n  /* Allocate memory for the Pager structure, PCache object, the\n  ** three file descriptors, the database file name and the journal \n  ** file name. The layout in memory is as follows:\n  **\n  **     Pager object                    (sizeof(Pager) bytes)\n  **     PCache object                   (sqlite3PcacheSize() bytes)\n  **     Database file handle            (pVfs->szOsFile bytes)\n  **     Sub-journal file handle         (journalFileSize bytes)\n  **     Main journal file handle        (journalFileSize bytes)\n  **     Ptr back to the Pager           (sizeof(Pager*) bytes)\n  **     \\0\\0\\0\\0 database prefix        (4 bytes)\n  **     Database file name              (nPathname+1 bytes)\n  **     URI query parameters            (nUriByte bytes)\n  **     Journal filename                (nPathname+8+1 bytes)\n  **     WAL filename                    (nPathname+4+1 bytes)\n  **     \\0\\0\\0 terminator               (3 bytes)\n  **\n  ** Some 3rd-party software, over which we have no control, depends on\n  ** the specific order of the filenames and the \\0 separators between them\n  ** so that it can (for example) find the database filename given the WAL\n  ** filename without using the sqlite3_filename_database() API.  This is a\n  ** misuse of SQLite and a bug in the 3rd-party software, but the 3rd-party\n  ** software is in widespread use, so we try to avoid changing the filename\n  ** order and formatting if possible.  In particular, the details of the\n  ** filename format expected by 3rd-party software should be as follows:\n  **\n  **   - Main Database Path\n  **   - \\0\n  **   - Multiple URI components consisting of:\n  **     - Key\n  **     - \\0\n  **     - Value\n  **     - \\0\n  **   - \\0\n  **   - Journal Path\n  **   - \\0\n  **   - WAL Path (zWALName)\n  **   - \\0\n  **\n  ** The sqlite3_create_filename() interface and the databaseFilename() utility\n  ** that is used by sqlite3_filename_database() and kin also depend on the\n  ** specific formatting and order of the various filenames, so if the format\n  ** changes here, be sure to change it there as well.\n  */\n  pPtr = (u8 *)sqlite3MallocZero(\n    ROUND8(sizeof(*pPager)) +            /* Pager structure */\n    ROUND8(pcacheSize) +                 /* PCache object */\n    ROUND8(pVfs->szOsFile) +             /* The main db file */\n    journalFileSize * 2 +                /* The two journal files */\n    sizeof(pPager) +                     /* Space to hold a pointer */\n    4 +                                  /* Database prefix */\n    nPathname + 1 +                      /* database filename */\n    nUriByte +                           /* query parameters */\n    nPathname + 8 + 1 +                  /* Journal filename */\n#ifndef SQLITE_OMIT_WAL\n    nPathname + 4 + 1 +                  /* WAL filename */\n#endif\n    3                                    /* Terminator */\n  );\n  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );\n  if( !pPtr ){\n    sqlite3DbFree(0, zPathname);\n    return SQLITE_NOMEM_BKPT;\n  }\n  pPager = (Pager*)pPtr;                  pPtr += ROUND8(sizeof(*pPager));\n  pPager->pPCache = (PCache*)pPtr;        pPtr += ROUND8(pcacheSize);\n  pPager->fd = (sqlite3_file*)pPtr;       pPtr += ROUND8(pVfs->szOsFile);\n  pPager->sjfd = (sqlite3_file*)pPtr;     pPtr += journalFileSize;\n  pPager->jfd =  (sqlite3_file*)pPtr;     pPtr += journalFileSize;\n  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );\n  memcpy(pPtr, &pPager, sizeof(pPager));  pPtr += sizeof(pPager);\n\n  /* Fill in the Pager.zFilename and pPager.zQueryParam fields */\n                                          pPtr += 4;  /* Skip zero prefix */\n  pPager->zFilename = (char*)pPtr;\n  if( nPathname>0 ){\n    memcpy(pPtr, zPathname, nPathname);   pPtr += nPathname + 1;\n    if( zUri ){\n      memcpy(pPtr, zUri, nUriByte);       pPtr += nUriByte;\n    }else{\n                                          pPtr++;\n    }\n  }\n\n\n  /* Fill in Pager.zJournal */\n  if( nPathname>0 ){\n    pPager->zJournal = (char*)pPtr;\n    memcpy(pPtr, zPathname, nPathname);   pPtr += nPathname;\n    memcpy(pPtr, \"-journal\",8);           pPtr += 8 + 1;\n#ifdef SQLITE_ENABLE_8_3_NAMES\n    sqlite3FileSuffix3(zFilename,pPager->zJournal);\n    pPtr = (u8*)(pPager->zJournal + sqlite3Strlen30(pPager->zJournal)+1);\n#endif\n  }else{\n    pPager->zJournal = 0;\n  }\n\n#ifndef SQLITE_OMIT_WAL\n  /* Fill in Pager.zWal */\n  if( nPathname>0 ){\n    pPager->zWal = (char*)pPtr;\n    memcpy(pPtr, zPathname, nPathname);   pPtr += nPathname;\n    memcpy(pPtr, \"-wal\", 4);              pPtr += 4 + 1;\n#ifdef SQLITE_ENABLE_8_3_NAMES\n    sqlite3FileSuffix3(zFilename, pPager->zWal);\n    pPtr = (u8*)(pPager->zWal + sqlite3Strlen30(pPager->zWal)+1);\n#endif\n  }else{\n    pPager->zWal = 0;\n  }\n#endif\n\n  if( nPathname ) sqlite3DbFree(0, zPathname);\n  pPager->pVfs = pVfs;\n  pPager->vfsFlags = vfsFlags;\n\n  /* Open the pager file.\n  */\n  if( zFilename && zFilename[0] ){\n    int fout = 0;                    /* VFS flags returned by xOpen() */\n    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);\n    assert( !memDb );\n#ifdef SQLITE_ENABLE_DESERIALIZE\n    memJM = (fout&SQLITE_OPEN_MEMORY)!=0;\n#endif\n    readOnly = (fout&SQLITE_OPEN_READONLY)!=0;\n\n    /* If the file was successfully opened for read/write access,\n    ** choose a default page size in case we have to create the\n    ** database file. The default page size is the maximum of:\n    **\n    **    + SQLITE_DEFAULT_PAGE_SIZE,\n    **    + The value returned by sqlite3OsSectorSize()\n    **    + The largest page size that can be written atomically.\n    */\n    if( rc==SQLITE_OK ){\n      int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);\n      if( !readOnly ){\n        setSectorSize(pPager);\n        assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);\n        if( szPageDflt<pPager->sectorSize ){\n          if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){\n            szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;\n          }else{\n            szPageDflt = (u32)pPager->sectorSize;\n          }\n        }\n#ifdef SQLITE_ENABLE_ATOMIC_WRITE\n        {\n          int ii;\n          assert(SQLITE_IOCAP_ATOMIC512==(512>>8));\n          assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));\n          assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);\n          for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){\n            if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){\n              szPageDflt = ii;\n            }\n          }\n        }\n#endif\n      }\n      pPager->noLock = sqlite3_uri_boolean(pPager->zFilename, \"nolock\", 0);\n      if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0\n       || sqlite3_uri_boolean(pPager->zFilename, \"immutable\", 0) ){\n          vfsFlags |= SQLITE_OPEN_READONLY;\n          goto act_like_temp_file;\n      }\n    }\n  }else{\n    /* If a temporary file is requested, it is not opened immediately.\n    ** In this case we accept the default page size and delay actually\n    ** opening the file until the first call to OsWrite().\n    **\n    ** This branch is also run for an in-memory database. An in-memory\n    ** database is the same as a temp-file that is never written out to\n    ** disk and uses an in-memory rollback journal.\n    **\n    ** This branch also runs for files marked as immutable.\n    */ \nact_like_temp_file:\n    tempFile = 1;\n    pPager->eState = PAGER_READER;     /* Pretend we already have a lock */\n    pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE mode */\n    pPager->noLock = 1;                /* Do no locking */\n    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);\n  }\n\n  /* The following call to PagerSetPagesize() serves to set the value of \n  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.\n  */\n  if( rc==SQLITE_OK ){\n    assert( pPager->memDb==0 );\n    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);\n    testcase( rc!=SQLITE_OK );\n  }\n\n  /* Initialize the PCache object. */\n  if( rc==SQLITE_OK ){\n    nExtra = ROUND8(nExtra);\n    assert( nExtra>=8 && nExtra<1000 );\n    rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,\n                       !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);\n  }\n\n  /* If an error occurred above, free the  Pager structure and close the file.\n  */\n  if( rc!=SQLITE_OK ){\n    sqlite3OsClose(pPager->fd);\n    sqlite3PageFree(pPager->pTmpSpace);\n    sqlite3_free(pPager);\n    return rc;\n  }\n\n  PAGERTRACE((\"OPEN %d %s\\n\", FILEHANDLEID(pPager->fd), pPager->zFilename));\n  IOTRACE((\"OPEN %p %s\\n\", pPager, pPager->zFilename))\n\n  pPager->useJournal = (u8)useJournal;\n  /* pPager->stmtOpen = 0; */\n  /* pPager->stmtInUse = 0; */\n  /* pPager->nRef = 0; */\n  /* pPager->stmtSize = 0; */\n  /* pPager->stmtJSize = 0; */\n  /* pPager->nPage = 0; */\n  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;\n  /* pPager->state = PAGER_UNLOCK; */\n  /* pPager->errMask = 0; */\n  pPager->tempFile = (u8)tempFile;\n  assert( tempFile==PAGER_LOCKINGMODE_NORMAL \n          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );\n  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );\n  pPager->exclusiveMode = (u8)tempFile; \n  pPager->changeCountDone = pPager->tempFile;\n  pPager->memDb = (u8)memDb;\n  pPager->readOnly = (u8)readOnly;\n  assert( useJournal || pPager->tempFile );\n  pPager->noSync = pPager->tempFile;\n  if( pPager->noSync ){\n    assert( pPager->fullSync==0 );\n    assert( pPager->extraSync==0 );\n    assert( pPager->syncFlags==0 );\n    assert( pPager->walSyncFlags==0 );\n  }else{\n    pPager->fullSync = 1;\n    pPager->extraSync = 0;\n    pPager->syncFlags = SQLITE_SYNC_NORMAL;\n    pPager->walSyncFlags = SQLITE_SYNC_NORMAL | (SQLITE_SYNC_NORMAL<<2);\n  }\n  /* pPager->pFirst = 0; */\n  /* pPager->pFirstSynced = 0; */\n  /* pPager->pLast = 0; */\n  pPager->nExtra = (u16)nExtra;\n  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;\n  assert( isOpen(pPager->fd) || tempFile );\n  setSectorSize(pPager);\n  if( !useJournal ){\n    pPager->journalMode = PAGER_JOURNALMODE_OFF;\n  }else if( memDb || memJM ){\n    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;\n  }\n  /* pPager->xBusyHandler = 0; */\n  /* pPager->pBusyHandlerArg = 0; */\n  pPager->xReiniter = xReinit;\n  setGetterMethod(pPager);\n  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */\n  /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */\n\n  *ppPager = pPager;\n  return SQLITE_OK;\n}\n\n/*\n** Return the sqlite3_file for the main database given the name\n** of the corresonding WAL or Journal name as passed into\n** xOpen.\n*/\nSQLITE_API sqlite3_file *sqlite3_database_file_object(const char *zName){\n  Pager *pPager;\n  while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){\n    zName--;\n  }\n  pPager = *(Pager**)(zName - 4 - sizeof(Pager*));\n  return pPager->fd;\n}\n\n\n/*\n** This function is called after transitioning from PAGER_UNLOCK to\n** PAGER_SHARED state. It tests if there is a hot journal present in\n** the file-system for the given pager. A hot journal is one that \n** needs to be played back. According to this function, a hot-journal\n** file exists if the following criteria are met:\n**\n**   * The journal file exists in the file system, and\n**   * No process holds a RESERVED or greater lock on the database file, and\n**   * The database file itself is greater than 0 bytes in size, and\n**   * The first byte of the journal file exists and is not 0x00.\n**\n** If the current size of the database file is 0 but a journal file\n** exists, that is probably an old journal left over from a prior\n** database with the same name. In this case the journal file is\n** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK\n** is returned.\n**\n** This routine does not check if there is a master journal filename\n** at the end of the file. If there is, and that master journal file\n** does not exist, then the journal file is not really hot. In this\n** case this routine will return a false-positive. The pager_playback()\n** routine will discover that the journal file is not really hot and \n** will not roll it back. \n**\n** If a hot-journal file is found to exist, *pExists is set to 1 and \n** SQLITE_OK returned. If no hot-journal file is present, *pExists is\n** set to 0 and SQLITE_OK returned. If an IO error occurs while trying\n** to determine whether or not a hot-journal file exists, the IO error\n** code is returned and the value of *pExists is undefined.\n*/\nstatic int hasHotJournal(Pager *pPager, int *pExists){\n  sqlite3_vfs * const pVfs = pPager->pVfs;\n  int rc = SQLITE_OK;           /* Return code */\n  int exists = 1;               /* True if a journal file is present */\n  int jrnlOpen = !!isOpen(pPager->jfd);\n\n  assert( pPager->useJournal );\n  assert( isOpen(pPager->fd) );\n  assert( pPager->eState==PAGER_OPEN );\n\n  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &\n    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN\n  ));\n\n  *pExists = 0;\n  if( !jrnlOpen ){\n    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);\n  }\n  if( rc==SQLITE_OK && exists ){\n    int locked = 0;             /* True if some process holds a RESERVED lock */\n\n    /* Race condition here:  Another process might have been holding the\n    ** the RESERVED lock and have a journal open at the sqlite3OsAccess() \n    ** call above, but then delete the journal and drop the lock before\n    ** we get to the following sqlite3OsCheckReservedLock() call.  If that\n    ** is the case, this routine might think there is a hot journal when\n    ** in fact there is none.  This results in a false-positive which will\n    ** be dealt with by the playback routine.  Ticket #3883.\n    */\n    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);\n    if( rc==SQLITE_OK && !locked ){\n      Pgno nPage;                 /* Number of pages in database file */\n\n      assert( pPager->tempFile==0 );\n      rc = pagerPagecount(pPager, &nPage);\n      if( rc==SQLITE_OK ){\n        /* If the database is zero pages in size, that means that either (1) the\n        ** journal is a remnant from a prior database with the same name where\n        ** the database file but not the journal was deleted, or (2) the initial\n        ** transaction that populates a new database is being rolled back.\n        ** In either case, the journal file can be deleted.  However, take care\n        ** not to delete the journal file if it is already open due to\n        ** journal_mode=PERSIST.\n        */\n        if( nPage==0 && !jrnlOpen ){\n          sqlite3BeginBenignMalloc();\n          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){\n            sqlite3OsDelete(pVfs, pPager->zJournal, 0);\n            if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);\n          }\n          sqlite3EndBenignMalloc();\n        }else{\n          /* The journal file exists and no other connection has a reserved\n          ** or greater lock on the database file. Now check that there is\n          ** at least one non-zero bytes at the start of the journal file.\n          ** If there is, then we consider this journal to be hot. If not, \n          ** it can be ignored.\n          */\n          if( !jrnlOpen ){\n            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;\n            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);\n          }\n          if( rc==SQLITE_OK ){\n            u8 first = 0;\n            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);\n            if( rc==SQLITE_IOERR_SHORT_READ ){\n              rc = SQLITE_OK;\n            }\n            if( !jrnlOpen ){\n              sqlite3OsClose(pPager->jfd);\n            }\n            *pExists = (first!=0);\n          }else if( rc==SQLITE_CANTOPEN ){\n            /* If we cannot open the rollback journal file in order to see if\n            ** it has a zero header, that might be due to an I/O error, or\n            ** it might be due to the race condition described above and in\n            ** ticket #3883.  Either way, assume that the journal is hot.\n            ** This might be a false positive.  But if it is, then the\n            ** automatic journal playback and recovery mechanism will deal\n            ** with it under an EXCLUSIVE lock where we do not need to\n            ** worry so much with race conditions.\n            */\n            *pExists = 1;\n            rc = SQLITE_OK;\n          }\n        }\n      }\n    }\n  }\n\n  return rc;\n}\n\n/*\n** This function is called to obtain a shared lock on the database file.\n** It is illegal to call sqlite3PagerGet() until after this function\n** has been successfully called. If a shared-lock is already held when\n** this function is called, it is a no-op.\n**\n** The following operations are also performed by this function.\n**\n**   1) If the pager is currently in PAGER_OPEN state (no lock held\n**      on the database file), then an attempt is made to obtain a\n**      SHARED lock on the database file. Immediately after obtaining\n**      the SHARED lock, the file-system is checked for a hot-journal,\n**      which is played back if present. Following any hot-journal \n**      rollback, the contents of the cache are validated by checking\n**      the 'change-counter' field of the database file header and\n**      discarded if they are found to be invalid.\n**\n**   2) If the pager is running in exclusive-mode, and there are currently\n**      no outstanding references to any pages, and is in the error state,\n**      then an attempt is made to clear the error state by discarding\n**      the contents of the page cache and rolling back any open journal\n**      file.\n**\n** If everything is successful, SQLITE_OK is returned. If an IO error \n** occurs while locking the database, checking for a hot-journal file or \n** rolling back a journal file, the IO error code is returned.\n*/\nSQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){\n  int rc = SQLITE_OK;                /* Return code */\n\n  /* This routine is only called from b-tree and only when there are no\n  ** outstanding pages. This implies that the pager state should either\n  ** be OPEN or READER. READER is only possible if the pager is or was in \n  ** exclusive access mode.  */\n  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );\n  assert( assert_pager_state(pPager) );\n  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );\n  assert( pPager->errCode==SQLITE_OK );\n\n  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){\n    int bHotJournal = 1;          /* True if there exists a hot journal-file */\n\n    assert( !MEMDB );\n    assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );\n\n    rc = pager_wait_on_lock(pPager, SHARED_LOCK);\n    if( rc!=SQLITE_OK ){\n      assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );\n      goto failed;\n    }\n\n    /* If a journal file exists, and there is no RESERVED lock on the\n    ** database file, then it either needs to be played back or deleted.\n    */\n    if( pPager->eLock<=SHARED_LOCK ){\n      rc = hasHotJournal(pPager, &bHotJournal);\n    }\n    if( rc!=SQLITE_OK ){\n      goto failed;\n    }\n    if( bHotJournal ){\n      if( pPager->readOnly ){\n        rc = SQLITE_READONLY_ROLLBACK;\n        goto failed;\n      }\n\n      /* Get an EXCLUSIVE lock on the database file. At this point it is\n      ** important that a RESERVED lock is not obtained on the way to the\n      ** EXCLUSIVE lock. If it were, another process might open the\n      ** database file, detect the RESERVED lock, and conclude that the\n      ** database is safe to read while this process is still rolling the \n      ** hot-journal back.\n      ** \n      ** Because the intermediate RESERVED lock is not requested, any\n      ** other process attempting to access the database file will get to \n      ** this point in the code and fail to obtain its own EXCLUSIVE lock \n      ** on the database file.\n      **\n      ** Unless the pager is in locking_mode=exclusive mode, the lock is\n      ** downgraded to SHARED_LOCK before this function returns.\n      */\n      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);\n      if( rc!=SQLITE_OK ){\n        goto failed;\n      }\n \n      /* If it is not already open and the file exists on disk, open the \n      ** journal for read/write access. Write access is required because \n      ** in exclusive-access mode the file descriptor will be kept open \n      ** and possibly used for a transaction later on. Also, write-access \n      ** is usually required to finalize the journal in journal_mode=persist \n      ** mode (and also for journal_mode=truncate on some systems).\n      **\n      ** If the journal does not exist, it usually means that some \n      ** other connection managed to get in and roll it back before \n      ** this connection obtained the exclusive lock above. Or, it \n      ** may mean that the pager was in the error-state when this\n      ** function was called and the journal file does not exist.\n      */\n      if( !isOpen(pPager->jfd) ){\n        sqlite3_vfs * const pVfs = pPager->pVfs;\n        int bExists;              /* True if journal file exists */\n        rc = sqlite3OsAccess(\n            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);\n        if( rc==SQLITE_OK && bExists ){\n          int fout = 0;\n          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;\n          assert( !pPager->tempFile );\n          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);\n          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );\n          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){\n            rc = SQLITE_CANTOPEN_BKPT;\n            sqlite3OsClose(pPager->jfd);\n          }\n        }\n      }\n \n      /* Playback and delete the journal.  Drop the database write\n      ** lock and reacquire the read lock. Purge the cache before\n      ** playing back the hot-journal so that we don't end up with\n      ** an inconsistent cache.  Sync the hot journal before playing\n      ** it back since the process that crashed and left the hot journal\n      ** probably did not sync it and we are required to always sync\n      ** the journal before playing it back.\n      */\n      if( isOpen(pPager->jfd) ){\n        assert( rc==SQLITE_OK );\n        rc = pagerSyncHotJournal(pPager);\n        if( rc==SQLITE_OK ){\n          rc = pager_playback(pPager, !pPager->tempFile);\n          pPager->eState = PAGER_OPEN;\n        }\n      }else if( !pPager->exclusiveMode ){\n        pagerUnlockDb(pPager, SHARED_LOCK);\n      }\n\n      if( rc!=SQLITE_OK ){\n        /* This branch is taken if an error occurs while trying to open\n        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The\n        ** pager_unlock() routine will be called before returning to unlock\n        ** the file. If the unlock attempt fails, then Pager.eLock must be\n        ** set to UNKNOWN_LOCK (see the comment above the #define for \n        ** UNKNOWN_LOCK above for an explanation). \n        **\n        ** In order to get pager_unlock() to do this, set Pager.eState to\n        ** PAGER_ERROR now. This is not actually counted as a transition\n        ** to ERROR state in the state diagram at the top of this file,\n        ** since we know that the same call to pager_unlock() will very\n        ** shortly transition the pager object to the OPEN state. Calling\n        ** assert_pager_state() would fail now, as it should not be possible\n        ** to be in ERROR state when there are zero outstanding page \n        ** references.\n        */\n        pager_error(pPager, rc);\n        goto failed;\n      }\n\n      assert( pPager->eState==PAGER_OPEN );\n      assert( (pPager->eLock==SHARED_LOCK)\n           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)\n      );\n    }\n\n    if( !pPager->tempFile && pPager->hasHeldSharedLock ){\n      /* The shared-lock has just been acquired then check to\n      ** see if the database has been modified.  If the database has changed,\n      ** flush the cache.  The hasHeldSharedLock flag prevents this from\n      ** occurring on the very first access to a file, in order to save a\n      ** single unnecessary sqlite3OsRead() call at the start-up.\n      **\n      ** Database changes are detected by looking at 15 bytes beginning\n      ** at offset 24 into the file.  The first 4 of these 16 bytes are\n      ** a 32-bit counter that is incremented with each change.  The\n      ** other bytes change randomly with each file change when\n      ** a codec is in use.\n      ** \n      ** There is a vanishingly small chance that a change will not be \n      ** detected.  The chance of an undetected change is so small that\n      ** it can be neglected.\n      */\n      char dbFileVers[sizeof(pPager->dbFileVers)];\n\n      IOTRACE((\"CKVERS %p %d\\n\", pPager, sizeof(dbFileVers)));\n      rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);\n      if( rc!=SQLITE_OK ){\n        if( rc!=SQLITE_IOERR_SHORT_READ ){\n          goto failed;\n        }\n        memset(dbFileVers, 0, sizeof(dbFileVers));\n      }\n\n      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){\n        pager_reset(pPager);\n\n        /* Unmap the database file. It is possible that external processes\n        ** may have truncated the database file and then extended it back\n        ** to its original size while this process was not holding a lock.\n        ** In this case there may exist a Pager.pMap mapping that appears\n        ** to be the right size but is not actually valid. Avoid this\n        ** possibility by unmapping the db here. */\n        if( USEFETCH(pPager) ){\n          sqlite3OsUnfetch(pPager->fd, 0, 0);\n        }\n      }\n    }\n\n    /* If there is a WAL file in the file-system, open this database in WAL\n    ** mode. Otherwise, the following function call is a no-op.\n    */\n    rc = pagerOpenWalIfPresent(pPager);\n#ifndef SQLITE_OMIT_WAL\n    assert( pPager->pWal==0 || rc==SQLITE_OK );\n#endif\n  }\n\n  if( pagerUseWal(pPager) ){\n    assert( rc==SQLITE_OK );\n    rc = pagerBeginReadTransaction(pPager);\n  }\n\n  if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){\n    rc = pagerPagecount(pPager, &pPager->dbSize);\n  }\n\n failed:\n  if( rc!=SQLITE_OK ){\n    assert( !MEMDB );\n    pager_unlock(pPager);\n    assert( pPager->eState==PAGER_OPEN );\n  }else{\n    pPager->eState = PAGER_READER;\n    pPager->hasHeldSharedLock = 1;\n  }\n  return rc;\n}\n\n/*\n** If the reference count has reached zero, rollback any active\n** transaction and unlock the pager.\n**\n** Except, in locking_mode=EXCLUSIVE when there is nothing to in\n** the rollback journal, the unlock is not performed and there is\n** nothing to rollback, so this routine is a no-op.\n*/ \nstatic void pagerUnlockIfUnused(Pager *pPager){\n  if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){\n    assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */\n    pagerUnlockAndRollback(pPager);\n  }\n}\n\n/*\n** The page getter methods each try to acquire a reference to a\n** page with page number pgno. If the requested reference is \n** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.\n**\n** There are different implementations of the getter method depending\n** on the current state of the pager.\n**\n**     getPageNormal()         --  The normal getter\n**     getPageError()          --  Used if the pager is in an error state\n**     getPageMmap()           --  Used if memory-mapped I/O is enabled\n**\n** If the requested page is already in the cache, it is returned. \n** Otherwise, a new page object is allocated and populated with data\n** read from the database file. In some cases, the pcache module may\n** choose not to allocate a new page object and may reuse an existing\n** object with no outstanding references.\n**\n** The extra data appended to a page is always initialized to zeros the \n** first time a page is loaded into memory. If the page requested is \n** already in the cache when this function is called, then the extra\n** data is left as it was when the page object was last used.\n**\n** If the database image is smaller than the requested page or if \n** the flags parameter contains the PAGER_GET_NOCONTENT bit and the \n** requested page is not already stored in the cache, then no \n** actual disk read occurs. In this case the memory image of the \n** page is initialized to all zeros. \n**\n** If PAGER_GET_NOCONTENT is true, it means that we do not care about\n** the contents of the page. This occurs in two scenarios:\n**\n**   a) When reading a free-list leaf page from the database, and\n**\n**   b) When a savepoint is being rolled back and we need to load\n**      a new page into the cache to be filled with the data read\n**      from the savepoint journal.\n**\n** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead\n** of being read from the database. Additionally, the bits corresponding\n** to pgno in Pager.pInJournal (bitvec of pages already written to the\n** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open\n** savepoints are set. This means if the page is made writable at any\n** point in the future, using a call to sqlite3PagerWrite(), its contents\n** will not be journaled. This saves IO.\n**\n** The acquisition might fail for several reasons.  In all cases,\n** an appropriate error code is returned and *ppPage is set to NULL.\n**\n** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt\n** to find a page in the in-memory cache first.  If the page is not already\n** in memory, this routine goes to disk to read it in whereas Lookup()\n** just returns 0.  This routine acquires a read-lock the first time it\n** has to go to disk, and could also playback an old journal if necessary.\n** Since Lookup() never goes to disk, it never has to deal with locks\n** or journal files.\n*/\nstatic int getPageNormal(\n  Pager *pPager,      /* The pager open on the database file */\n  Pgno pgno,          /* Page number to fetch */\n  DbPage **ppPage,    /* Write a pointer to the page here */\n  int flags           /* PAGER_GET_XXX flags */\n){\n  int rc = SQLITE_OK;\n  PgHdr *pPg;\n  u8 noContent;                   /* True if PAGER_GET_NOCONTENT is set */\n  sqlite3_pcache_page *pBase;\n\n  assert( pPager->errCode==SQLITE_OK );\n  assert( pPager->eState>=PAGER_READER );\n  assert( assert_pager_state(pPager) );\n  assert( pPager->hasHeldSharedLock==1 );\n\n  if( pgno==0 ) return SQLITE_CORRUPT_BKPT;\n  pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);\n  if( pBase==0 ){\n    pPg = 0;\n    rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);\n    if( rc!=SQLITE_OK ) goto pager_acquire_err;\n    if( pBase==0 ){\n      rc = SQLITE_NOMEM_BKPT;\n      goto pager_acquire_err;\n    }\n  }\n  pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);\n  assert( pPg==(*ppPage) );\n  assert( pPg->pgno==pgno );\n  assert( pPg->pPager==pPager || pPg->pPager==0 );\n\n  noContent = (flags & PAGER_GET_NOCONTENT)!=0;\n  if( pPg->pPager && !noContent ){\n    /* In this case the pcache already contains an initialized copy of\n    ** the page. Return without further ado.  */\n    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );\n    pPager->aStat[PAGER_STAT_HIT]++;\n    return SQLITE_OK;\n\n  }else{\n    /* The pager cache has created a new page. Its content needs to \n    ** be initialized. But first some error checks:\n    **\n    ** (1) The maximum page number is 2^31\n    ** (2) Never try to fetch the locking page\n    */\n    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){\n      rc = SQLITE_CORRUPT_BKPT;\n      goto pager_acquire_err;\n    }\n\n    pPg->pPager = pPager;\n\n    assert( !isOpen(pPager->fd) || !MEMDB );\n    if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){\n      if( pgno>pPager->mxPgno ){\n        rc = SQLITE_FULL;\n        goto pager_acquire_err;\n      }\n      if( noContent ){\n        /* Failure to set the bits in the InJournal bit-vectors is benign.\n        ** It merely means that we might do some extra work to journal a \n        ** page that does not need to be journaled.  Nevertheless, be sure \n        ** to test the case where a malloc error occurs while trying to set \n        ** a bit in a bit vector.\n        */\n        sqlite3BeginBenignMalloc();\n        if( pgno<=pPager->dbOrigSize ){\n          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);\n          testcase( rc==SQLITE_NOMEM );\n        }\n        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);\n        testcase( rc==SQLITE_NOMEM );\n        sqlite3EndBenignMalloc();\n      }\n      memset(pPg->pData, 0, pPager->pageSize);\n      IOTRACE((\"ZERO %p %d\\n\", pPager, pgno));\n    }else{\n      assert( pPg->pPager==pPager );\n      pPager->aStat[PAGER_STAT_MISS]++;\n      rc = readDbPage(pPg);\n      if( rc!=SQLITE_OK ){\n        goto pager_acquire_err;\n      }\n    }\n    pager_set_pagehash(pPg);\n  }\n  return SQLITE_OK;\n\npager_acquire_err:\n  assert( rc!=SQLITE_OK );\n  if( pPg ){\n    sqlite3PcacheDrop(pPg);\n  }\n  pagerUnlockIfUnused(pPager);\n  *ppPage = 0;\n  return rc;\n}\n\n#if SQLITE_MAX_MMAP_SIZE>0\n/* The page getter for when memory-mapped I/O is enabled */\nstatic int getPageMMap(\n  Pager *pPager,      /* The pager open on the database file */\n  Pgno pgno,          /* Page number to fetch */\n  DbPage **ppPage,    /* Write a pointer to the page here */\n  int flags           /* PAGER_GET_XXX flags */\n){\n  int rc = SQLITE_OK;\n  PgHdr *pPg = 0;\n  u32 iFrame = 0;                 /* Frame to read from WAL file */\n\n  /* It is acceptable to use a read-only (mmap) page for any page except\n  ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY\n  ** flag was specified by the caller. And so long as the db is not a \n  ** temporary or in-memory database.  */\n  const int bMmapOk = (pgno>1\n   && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))\n  );\n\n  assert( USEFETCH(pPager) );\n\n  /* Optimization note:  Adding the \"pgno<=1\" term before \"pgno==0\" here\n  ** allows the compiler optimizer to reuse the results of the \"pgno>1\"\n  ** test in the previous statement, and avoid testing pgno==0 in the\n  ** common case where pgno is large. */\n  if( pgno<=1 && pgno==0 ){\n    return SQLITE_CORRUPT_BKPT;\n  }\n  assert( pPager->eState>=PAGER_READER );\n  assert( assert_pager_state(pPager) );\n  assert( pPager->hasHeldSharedLock==1 );\n  assert( pPager->errCode==SQLITE_OK );\n\n  if( bMmapOk && pagerUseWal(pPager) ){\n    rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);\n    if( rc!=SQLITE_OK ){\n      *ppPage = 0;\n      return rc;\n    }\n  }\n  if( bMmapOk && iFrame==0 ){\n    void *pData = 0;\n    rc = sqlite3OsFetch(pPager->fd, \n        (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData\n    );\n    if( rc==SQLITE_OK && pData ){\n      if( pPager->eState>PAGER_READER || pPager->tempFile ){\n        pPg = sqlite3PagerLookup(pPager, pgno);\n      }\n      if( pPg==0 ){\n        rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);\n      }else{\n        sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);\n      }\n      if( pPg ){\n        assert( rc==SQLITE_OK );\n        *ppPage = pPg;\n        return SQLITE_OK;\n      }\n    }\n    if( rc!=SQLITE_OK ){\n      *ppPage = 0;\n      return rc;\n    }\n  }\n  return getPageNormal(pPager, pgno, ppPage, flags);\n}\n#endif /* SQLITE_MAX_MMAP_SIZE>0 */\n\n/* The page getter method for when the pager is an error state */\nstatic int getPageError(\n  Pager *pPager,      /* The pager open on the database file */\n  Pgno pgno,          /* Page number to fetch */\n  DbPage **ppPage,    /* Write a pointer to the page here */\n  int flags           /* PAGER_GET_XXX flags */\n){\n  UNUSED_PARAMETER(pgno);\n  UNUSED_PARAMETER(flags);\n  assert( pPager->errCode!=SQLITE_OK );\n  *ppPage = 0;\n  return pPager->errCode;\n}\n\n\n/* Dispatch all page fetch requests to the appropriate getter method.\n*/\nSQLITE_PRIVATE int sqlite3PagerGet(\n  Pager *pPager,      /* The pager open on the database file */\n  Pgno pgno,          /* Page number to fetch */\n  DbPage **ppPage,    /* Write a pointer to the page here */\n  int flags           /* PAGER_GET_XXX flags */\n){\n  return pPager->xGet(pPager, pgno, ppPage, flags);\n}\n\n/*\n** Acquire a page if it is already in the in-memory cache.  Do\n** not read the page from disk.  Return a pointer to the page,\n** or 0 if the page is not in cache. \n**\n** See also sqlite3PagerGet().  The difference between this routine\n** and sqlite3PagerGet() is that _get() will go to the disk and read\n** in the page if the page is not already in cache.  This routine\n** returns NULL if the page is not in cache or if a disk I/O error \n** has ever happened.\n*/\nSQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){\n  sqlite3_pcache_page *pPage;\n  assert( pPager!=0 );\n  assert( pgno!=0 );\n  assert( pPager->pPCache!=0 );\n  pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);\n  assert( pPage==0 || pPager->hasHeldSharedLock );\n  if( pPage==0 ) return 0;\n  return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);\n}\n\n/*\n** Release a page reference.\n**\n** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be\n** used if we know that the page being released is not the last page.\n** The btree layer always holds page1 open until the end, so these first\n** to routines can be used to release any page other than BtShared.pPage1.\n**\n** Use sqlite3PagerUnrefPageOne() to release page1.  This latter routine\n** checks the total number of outstanding pages and if the number of\n** pages reaches zero it drops the database lock.\n*/\nSQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){\n  TESTONLY( Pager *pPager = pPg->pPager; )\n  assert( pPg!=0 );\n  if( pPg->flags & PGHDR_MMAP ){\n    assert( pPg->pgno!=1 );  /* Page1 is never memory mapped */\n    pagerReleaseMapPage(pPg);\n  }else{\n    sqlite3PcacheRelease(pPg);\n  }\n  /* Do not use this routine to release the last reference to page1 */\n  assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );\n}\nSQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){\n  if( pPg ) sqlite3PagerUnrefNotNull(pPg);\n}\nSQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){\n  Pager *pPager;\n  assert( pPg!=0 );\n  assert( pPg->pgno==1 );\n  assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */\n  pPager = pPg->pPager;\n  sqlite3PcacheRelease(pPg);\n  pagerUnlockIfUnused(pPager);\n}\n\n/*\n** This function is called at the start of every write transaction.\n** There must already be a RESERVED or EXCLUSIVE lock on the database \n** file when this routine is called.\n**\n** Open the journal file for pager pPager and write a journal header\n** to the start of it. If there are active savepoints, open the sub-journal\n** as well. This function is only used when the journal file is being \n** opened to write a rollback log for a transaction. It is not used \n** when opening a hot journal file to roll it back.\n**\n** If the journal file is already open (as it may be in exclusive mode),\n** then this function just writes a journal header to the start of the\n** already open file. \n**\n** Whether or not the journal file is opened by this function, the\n** Pager.pInJournal bitvec structure is allocated.\n**\n** Return SQLITE_OK if everything is successful. Otherwise, return \n** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or \n** an IO error code if opening or writing the journal file fails.\n*/\nstatic int pager_open_journal(Pager *pPager){\n  int rc = SQLITE_OK;                        /* Return code */\n  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */\n\n  assert( pPager->eState==PAGER_WRITER_LOCKED );\n  assert( assert_pager_state(pPager) );\n  assert( pPager->pInJournal==0 );\n  \n  /* If already in the error state, this function is a no-op.  But on\n  ** the other hand, this routine is never called if we are already in\n  ** an error state. */\n  if( NEVER(pPager->errCode) ) return pPager->errCode;\n\n  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){\n    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);\n    if( pPager->pInJournal==0 ){\n      return SQLITE_NOMEM_BKPT;\n    }\n  \n    /* Open the journal file if it is not already open. */\n    if( !isOpen(pPager->jfd) ){\n      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){\n        sqlite3MemJournalOpen(pPager->jfd);\n      }else{\n        int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;\n        int nSpill;\n\n        if( pPager->tempFile ){\n          flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);\n          nSpill = sqlite3Config.nStmtSpill;\n        }else{\n          flags |= SQLITE_OPEN_MAIN_JOURNAL;\n          nSpill = jrnlBufferSize(pPager);\n        }\n          \n        /* Verify that the database still has the same name as it did when\n        ** it was originally opened. */\n        rc = databaseIsUnmoved(pPager);\n        if( rc==SQLITE_OK ){\n          rc = sqlite3JournalOpen (\n              pVfs, pPager->zJournal, pPager->jfd, flags, nSpill\n          );\n        }\n      }\n      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );\n    }\n  \n  \n    /* Write the first journal header to the journal file and open \n    ** the sub-journal if necessary.\n    */\n    if( rc==SQLITE_OK ){\n      /* TODO: Check if all of these are really required. */\n      pPager->nRec = 0;\n      pPager->journalOff = 0;\n      pPager->setMaster = 0;\n      pPager->journalHdr = 0;\n      rc = writeJournalHdr(pPager);\n    }\n  }\n\n  if( rc!=SQLITE_OK ){\n    sqlite3BitvecDestroy(pPager->pInJournal);\n    pPager->pInJournal = 0;\n  }else{\n    assert( pPager->eState==PAGER_WRITER_LOCKED );\n    pPager->eState = PAGER_WRITER_CACHEMOD;\n  }\n\n  return rc;\n}\n\n/*\n** Begin a write-transaction on the specified pager object. If a \n** write-transaction has already been opened, this function is a no-op.\n**\n** If the exFlag argument is false, then acquire at least a RESERVED\n** lock on the database file. If exFlag is true, then acquire at least\n** an EXCLUSIVE lock. If such a lock is already held, no locking \n** functions need be called.\n**\n** If the subjInMemory argument is non-zero, then any sub-journal opened\n** within this transaction will be opened as an in-memory file. This\n** has no effect if the sub-journal is already opened (as it may be when\n** running in exclusive mode) or if the transaction does not require a\n** sub-journal. If the subjInMemory argument is zero, then any required\n** sub-journal is implemented in-memory if pPager is an in-memory database, \n** or using a temporary file otherwise.\n*/\nSQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){\n  int rc = SQLITE_OK;\n\n  if( pPager->errCode ) return pPager->errCode;\n  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );\n  pPager->subjInMemory = (u8)subjInMemory;\n\n  if( ALWAYS(pPager->eState==PAGER_READER) ){\n    assert( pPager->pInJournal==0 );\n\n    if( pagerUseWal(pPager) ){\n      /* If the pager is configured to use locking_mode=exclusive, and an\n      ** exclusive lock on the database is not already held, obtain it now.\n      */\n      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){\n        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);\n        if( rc!=SQLITE_OK ){\n          return rc;\n        }\n        (void)sqlite3WalExclusiveMode(pPager->pWal, 1);\n      }\n\n      /* Grab the write lock on the log file. If successful, upgrade to\n      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.\n      ** The busy-handler is not invoked if another connection already\n      ** holds the write-lock. If possible, the upper layer will call it.\n      */\n      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);\n    }else{\n      /* Obtain a RESERVED lock on the database file. If the exFlag parameter\n      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The\n      ** busy-handler callback can be used when upgrading to the EXCLUSIVE\n      ** lock, but not when obtaining the RESERVED lock.\n      */\n      rc = pagerLockDb(pPager, RESERVED_LOCK);\n      if( rc==SQLITE_OK && exFlag ){\n        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);\n      }\n    }\n\n    if( rc==SQLITE_OK ){\n      /* Change to WRITER_LOCKED state.\n      **\n      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD\n      ** when it has an open transaction, but never to DBMOD or FINISHED.\n      ** This is because in those states the code to roll back savepoint \n      ** transactions may copy data from the sub-journal into the database \n      ** file as well as into the page cache. Which would be incorrect in \n      ** WAL mode.\n      */\n      pPager->eState = PAGER_WRITER_LOCKED;\n      pPager->dbHintSize = pPager->dbSize;\n      pPager->dbFileSize = pPager->dbSize;\n      pPager->dbOrigSize = pPager->dbSize;\n      pPager->journalOff = 0;\n    }\n\n    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );\n    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );\n    assert( assert_pager_state(pPager) );\n  }\n\n  PAGERTRACE((\"TRANSACTION %d\\n\", PAGERID(pPager)));\n  return rc;\n}\n\n/*\n** Write page pPg onto the end of the rollback journal.\n*/\nstatic SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){\n  Pager *pPager = pPg->pPager;\n  int rc;\n  u32 cksum;\n  char *pData2;\n  i64 iOff = pPager->journalOff;\n\n  /* We should never write to the journal file the page that\n  ** contains the database locks.  The following assert verifies\n  ** that we do not. */\n  assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );\n\n  assert( pPager->journalHdr<=pPager->journalOff );\n  pData2 = pPg->pData;\n  cksum = pager_cksum(pPager, (u8*)pData2);\n\n  /* Even if an IO or diskfull error occurs while journalling the\n  ** page in the block above, set the need-sync flag for the page.\n  ** Otherwise, when the transaction is rolled back, the logic in\n  ** playback_one_page() will think that the page needs to be restored\n  ** in the database file. And if an IO error occurs while doing so,\n  ** then corruption may follow.\n  */\n  pPg->flags |= PGHDR_NEED_SYNC;\n\n  rc = write32bits(pPager->jfd, iOff, pPg->pgno);\n  if( rc!=SQLITE_OK ) return rc;\n  rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);\n  if( rc!=SQLITE_OK ) return rc;\n  rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);\n  if( rc!=SQLITE_OK ) return rc;\n\n  IOTRACE((\"JOUT %p %d %lld %d\\n\", pPager, pPg->pgno, \n           pPager->journalOff, pPager->pageSize));\n  PAGER_INCR(sqlite3_pager_writej_count);\n  PAGERTRACE((\"JOURNAL %d page %d needSync=%d hash(%08x)\\n\",\n       PAGERID(pPager), pPg->pgno, \n       ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));\n\n  pPager->journalOff += 8 + pPager->pageSize;\n  pPager->nRec++;\n  assert( pPager->pInJournal!=0 );\n  rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);\n  testcase( rc==SQLITE_NOMEM );\n  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );\n  rc |= addToSavepointBitvecs(pPager, pPg->pgno);\n  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );\n  return rc;\n}\n\n/*\n** Mark a single data page as writeable. The page is written into the \n** main journal or sub-journal as required. If the page is written into\n** one of the journals, the corresponding bit is set in the \n** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs\n** of any open savepoints as appropriate.\n*/\nstatic int pager_write(PgHdr *pPg){\n  Pager *pPager = pPg->pPager;\n  int rc = SQLITE_OK;\n\n  /* This routine is not called unless a write-transaction has already \n  ** been started. The journal file may or may not be open at this point.\n  ** It is never called in the ERROR state.\n  */\n  assert( pPager->eState==PAGER_WRITER_LOCKED\n       || pPager->eState==PAGER_WRITER_CACHEMOD\n       || pPager->eState==PAGER_WRITER_DBMOD\n  );\n  assert( assert_pager_state(pPager) );\n  assert( pPager->errCode==0 );\n  assert( pPager->readOnly==0 );\n  CHECK_PAGE(pPg);\n\n  /* The journal file needs to be opened. Higher level routines have already\n  ** obtained the necessary locks to begin the write-transaction, but the\n  ** rollback journal might not yet be open. Open it now if this is the case.\n  **\n  ** This is done before calling sqlite3PcacheMakeDirty() on the page. \n  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then\n  ** an error might occur and the pager would end up in WRITER_LOCKED state\n  ** with pages marked as dirty in the cache.\n  */\n  if( pPager->eState==PAGER_WRITER_LOCKED ){\n    rc = pager_open_journal(pPager);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );\n  assert( assert_pager_state(pPager) );\n\n  /* Mark the page that is about to be modified as dirty. */\n  sqlite3PcacheMakeDirty(pPg);\n\n  /* If a rollback journal is in use, them make sure the page that is about\n  ** to change is in the rollback journal, or if the page is a new page off\n  ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.\n  */\n  assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );\n  if( pPager->pInJournal!=0\n   && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0\n  ){\n    assert( pagerUseWal(pPager)==0 );\n    if( pPg->pgno<=pPager->dbOrigSize ){\n      rc = pagerAddPageToRollbackJournal(pPg);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n    }else{\n      if( pPager->eState!=PAGER_WRITER_DBMOD ){\n        pPg->flags |= PGHDR_NEED_SYNC;\n      }\n      PAGERTRACE((\"APPEND %d page %d needSync=%d\\n\",\n              PAGERID(pPager), pPg->pgno,\n             ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));\n    }\n  }\n\n  /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list\n  ** and before writing the page into the rollback journal.  Wait until now,\n  ** after the page has been successfully journalled, before setting the\n  ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.\n  */\n  pPg->flags |= PGHDR_WRITEABLE;\n  \n  /* If the statement journal is open and the page is not in it,\n  ** then write the page into the statement journal.\n  */\n  if( pPager->nSavepoint>0 ){\n    rc = subjournalPageIfRequired(pPg);\n  }\n\n  /* Update the database size and return. */\n  if( pPager->dbSize<pPg->pgno ){\n    pPager->dbSize = pPg->pgno;\n  }\n  return rc;\n}\n\n/*\n** This is a variant of sqlite3PagerWrite() that runs when the sector size\n** is larger than the page size.  SQLite makes the (reasonable) assumption that\n** all bytes of a sector are written together by hardware.  Hence, all bytes of\n** a sector need to be journalled in case of a power loss in the middle of\n** a write.\n**\n** Usually, the sector size is less than or equal to the page size, in which\n** case pages can be individually written.  This routine only runs in the\n** exceptional case where the page size is smaller than the sector size.\n*/\nstatic SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){\n  int rc = SQLITE_OK;          /* Return code */\n  Pgno nPageCount;             /* Total number of pages in database file */\n  Pgno pg1;                    /* First page of the sector pPg is located on. */\n  int nPage = 0;               /* Number of pages starting at pg1 to journal */\n  int ii;                      /* Loop counter */\n  int needSync = 0;            /* True if any page has PGHDR_NEED_SYNC */\n  Pager *pPager = pPg->pPager; /* The pager that owns pPg */\n  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);\n\n  /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow\n  ** a journal header to be written between the pages journaled by\n  ** this function.\n  */\n  assert( !MEMDB );\n  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );\n  pPager->doNotSpill |= SPILLFLAG_NOSYNC;\n\n  /* This trick assumes that both the page-size and sector-size are\n  ** an integer power of 2. It sets variable pg1 to the identifier\n  ** of the first page of the sector pPg is located on.\n  */\n  pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;\n\n  nPageCount = pPager->dbSize;\n  if( pPg->pgno>nPageCount ){\n    nPage = (pPg->pgno - pg1)+1;\n  }else if( (pg1+nPagePerSector-1)>nPageCount ){\n    nPage = nPageCount+1-pg1;\n  }else{\n    nPage = nPagePerSector;\n  }\n  assert(nPage>0);\n  assert(pg1<=pPg->pgno);\n  assert((pg1+nPage)>pPg->pgno);\n\n  for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){\n    Pgno pg = pg1+ii;\n    PgHdr *pPage;\n    if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){\n      if( pg!=PAGER_MJ_PGNO(pPager) ){\n        rc = sqlite3PagerGet(pPager, pg, &pPage, 0);\n        if( rc==SQLITE_OK ){\n          rc = pager_write(pPage);\n          if( pPage->flags&PGHDR_NEED_SYNC ){\n            needSync = 1;\n          }\n          sqlite3PagerUnrefNotNull(pPage);\n        }\n      }\n    }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){\n      if( pPage->flags&PGHDR_NEED_SYNC ){\n        needSync = 1;\n      }\n      sqlite3PagerUnrefNotNull(pPage);\n    }\n  }\n\n  /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages \n  ** starting at pg1, then it needs to be set for all of them. Because\n  ** writing to any of these nPage pages may damage the others, the\n  ** journal file must contain sync()ed copies of all of them\n  ** before any of them can be written out to the database file.\n  */\n  if( rc==SQLITE_OK && needSync ){\n    assert( !MEMDB );\n    for(ii=0; ii<nPage; ii++){\n      PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);\n      if( pPage ){\n        pPage->flags |= PGHDR_NEED_SYNC;\n        sqlite3PagerUnrefNotNull(pPage);\n      }\n    }\n  }\n\n  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );\n  pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;\n  return rc;\n}\n\n/*\n** Mark a data page as writeable. This routine must be called before \n** making changes to a page. The caller must check the return value \n** of this function and be careful not to change any page data unless \n** this routine returns SQLITE_OK.\n**\n** The difference between this function and pager_write() is that this\n** function also deals with the special case where 2 or more pages\n** fit on a single disk sector. In this case all co-resident pages\n** must have been written to the journal file before returning.\n**\n** If an error occurs, SQLITE_NOMEM or an IO error code is returned\n** as appropriate. Otherwise, SQLITE_OK.\n*/\nSQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){\n  Pager *pPager = pPg->pPager;\n  assert( (pPg->flags & PGHDR_MMAP)==0 );\n  assert( pPager->eState>=PAGER_WRITER_LOCKED );\n  assert( assert_pager_state(pPager) );\n  if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){\n    if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);\n    return SQLITE_OK;\n  }else if( pPager->errCode ){\n    return pPager->errCode;\n  }else if( pPager->sectorSize > (u32)pPager->pageSize ){\n    assert( pPager->tempFile==0 );\n    return pagerWriteLargeSector(pPg);\n  }else{\n    return pager_write(pPg);\n  }\n}\n\n/*\n** Return TRUE if the page given in the argument was previously passed\n** to sqlite3PagerWrite().  In other words, return TRUE if it is ok\n** to change the content of the page.\n*/\n#ifndef NDEBUG\nSQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){\n  return pPg->flags & PGHDR_WRITEABLE;\n}\n#endif\n\n/*\n** A call to this routine tells the pager that it is not necessary to\n** write the information on page pPg back to the disk, even though\n** that page might be marked as dirty.  This happens, for example, when\n** the page has been added as a leaf of the freelist and so its\n** content no longer matters.\n**\n** The overlying software layer calls this routine when all of the data\n** on the given page is unused. The pager marks the page as clean so\n** that it does not get written to disk.\n**\n** Tests show that this optimization can quadruple the speed of large \n** DELETE operations.\n**\n** This optimization cannot be used with a temp-file, as the page may\n** have been dirty at the start of the transaction. In that case, if\n** memory pressure forces page pPg out of the cache, the data does need \n** to be written out to disk so that it may be read back in if the \n** current transaction is rolled back.\n*/\nSQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){\n  Pager *pPager = pPg->pPager;\n  if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){\n    PAGERTRACE((\"DONT_WRITE page %d of %d\\n\", pPg->pgno, PAGERID(pPager)));\n    IOTRACE((\"CLEAN %p %d\\n\", pPager, pPg->pgno))\n    pPg->flags |= PGHDR_DONT_WRITE;\n    pPg->flags &= ~PGHDR_WRITEABLE;\n    testcase( pPg->flags & PGHDR_NEED_SYNC );\n    pager_set_pagehash(pPg);\n  }\n}\n\n/*\n** This routine is called to increment the value of the database file \n** change-counter, stored as a 4-byte big-endian integer starting at \n** byte offset 24 of the pager file.  The secondary change counter at\n** 92 is also updated, as is the SQLite version number at offset 96.\n**\n** But this only happens if the pPager->changeCountDone flag is false.\n** To avoid excess churning of page 1, the update only happens once.\n** See also the pager_write_changecounter() routine that does an \n** unconditional update of the change counters.\n**\n** If the isDirectMode flag is zero, then this is done by calling \n** sqlite3PagerWrite() on page 1, then modifying the contents of the\n** page data. In this case the file will be updated when the current\n** transaction is committed.\n**\n** The isDirectMode flag may only be non-zero if the library was compiled\n** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,\n** if isDirect is non-zero, then the database file is updated directly\n** by writing an updated version of page 1 using a call to the \n** sqlite3OsWrite() function.\n*/\nstatic int pager_incr_changecounter(Pager *pPager, int isDirectMode){\n  int rc = SQLITE_OK;\n\n  assert( pPager->eState==PAGER_WRITER_CACHEMOD\n       || pPager->eState==PAGER_WRITER_DBMOD\n  );\n  assert( assert_pager_state(pPager) );\n\n  /* Declare and initialize constant integer 'isDirect'. If the\n  ** atomic-write optimization is enabled in this build, then isDirect\n  ** is initialized to the value passed as the isDirectMode parameter\n  ** to this function. Otherwise, it is always set to zero.\n  **\n  ** The idea is that if the atomic-write optimization is not\n  ** enabled at compile time, the compiler can omit the tests of\n  ** 'isDirect' below, as well as the block enclosed in the\n  ** \"if( isDirect )\" condition.\n  */\n#ifndef SQLITE_ENABLE_ATOMIC_WRITE\n# define DIRECT_MODE 0\n  assert( isDirectMode==0 );\n  UNUSED_PARAMETER(isDirectMode);\n#else\n# define DIRECT_MODE isDirectMode\n#endif\n\n  if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){\n    PgHdr *pPgHdr;                /* Reference to page 1 */\n\n    assert( !pPager->tempFile && isOpen(pPager->fd) );\n\n    /* Open page 1 of the file for writing. */\n    rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);\n    assert( pPgHdr==0 || rc==SQLITE_OK );\n\n    /* If page one was fetched successfully, and this function is not\n    ** operating in direct-mode, make page 1 writable.  When not in \n    ** direct mode, page 1 is always held in cache and hence the PagerGet()\n    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.\n    */\n    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){\n      rc = sqlite3PagerWrite(pPgHdr);\n    }\n\n    if( rc==SQLITE_OK ){\n      /* Actually do the update of the change counter */\n      pager_write_changecounter(pPgHdr);\n\n      /* If running in direct mode, write the contents of page 1 to the file. */\n      if( DIRECT_MODE ){\n        const void *zBuf;\n        assert( pPager->dbFileSize>0 );\n        zBuf = pPgHdr->pData;\n        if( rc==SQLITE_OK ){\n          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);\n          pPager->aStat[PAGER_STAT_WRITE]++;\n        }\n        if( rc==SQLITE_OK ){\n          /* Update the pager's copy of the change-counter. Otherwise, the\n          ** next time a read transaction is opened the cache will be\n          ** flushed (as the change-counter values will not match).  */\n          const void *pCopy = (const void *)&((const char *)zBuf)[24];\n          memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));\n          pPager->changeCountDone = 1;\n        }\n      }else{\n        pPager->changeCountDone = 1;\n      }\n    }\n\n    /* Release the page reference. */\n    sqlite3PagerUnref(pPgHdr);\n  }\n  return rc;\n}\n\n/*\n** Sync the database file to disk. This is a no-op for in-memory databases\n** or pages with the Pager.noSync flag set.\n**\n** If successful, or if called on a pager for which it is a no-op, this\n** function returns SQLITE_OK. Otherwise, an IO error code is returned.\n*/\nSQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){\n  int rc = SQLITE_OK;\n  void *pArg = (void*)zMaster;\n  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);\n  if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;\n  if( rc==SQLITE_OK && !pPager->noSync ){\n    assert( !MEMDB );\n    rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);\n  }\n  return rc;\n}\n\n/*\n** This function may only be called while a write-transaction is active in\n** rollback. If the connection is in WAL mode, this call is a no-op. \n** Otherwise, if the connection does not already have an EXCLUSIVE lock on \n** the database file, an attempt is made to obtain one.\n**\n** If the EXCLUSIVE lock is already held or the attempt to obtain it is\n** successful, or the connection is in WAL mode, SQLITE_OK is returned.\n** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is \n** returned.\n*/\nSQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){\n  int rc = pPager->errCode;\n  assert( assert_pager_state(pPager) );\n  if( rc==SQLITE_OK ){\n    assert( pPager->eState==PAGER_WRITER_CACHEMOD \n         || pPager->eState==PAGER_WRITER_DBMOD \n         || pPager->eState==PAGER_WRITER_LOCKED \n    );\n    assert( assert_pager_state(pPager) );\n    if( 0==pagerUseWal(pPager) ){\n      rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);\n    }\n  }\n  return rc;\n}\n\n/*\n** Sync the database file for the pager pPager. zMaster points to the name\n** of a master journal file that should be written into the individual\n** journal file. zMaster may be NULL, which is interpreted as no master\n** journal (a single database transaction).\n**\n** This routine ensures that:\n**\n**   * The database file change-counter is updated,\n**   * the journal is synced (unless the atomic-write optimization is used),\n**   * all dirty pages are written to the database file, \n**   * the database file is truncated (if required), and\n**   * the database file synced. \n**\n** The only thing that remains to commit the transaction is to finalize \n** (delete, truncate or zero the first part of) the journal file (or \n** delete the master journal file if specified).\n**\n** Note that if zMaster==NULL, this does not overwrite a previous value\n** passed to an sqlite3PagerCommitPhaseOne() call.\n**\n** If the final parameter - noSync - is true, then the database file itself\n** is not synced. The caller must call sqlite3PagerSync() directly to\n** sync the database file before calling CommitPhaseTwo() to delete the\n** journal file in this case.\n*/\nSQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(\n  Pager *pPager,                  /* Pager object */\n  const char *zMaster,            /* If not NULL, the master journal name */\n  int noSync                      /* True to omit the xSync on the db file */\n){\n  int rc = SQLITE_OK;             /* Return code */\n\n  assert( pPager->eState==PAGER_WRITER_LOCKED\n       || pPager->eState==PAGER_WRITER_CACHEMOD\n       || pPager->eState==PAGER_WRITER_DBMOD\n       || pPager->eState==PAGER_ERROR\n  );\n  assert( assert_pager_state(pPager) );\n\n  /* If a prior error occurred, report that error again. */\n  if( NEVER(pPager->errCode) ) return pPager->errCode;\n\n  /* Provide the ability to easily simulate an I/O error during testing */\n  if( sqlite3FaultSim(400) ) return SQLITE_IOERR;\n\n  PAGERTRACE((\"DATABASE SYNC: File=%s zMaster=%s nSize=%d\\n\", \n      pPager->zFilename, zMaster, pPager->dbSize));\n\n  /* If no database changes have been made, return early. */\n  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;\n\n  assert( MEMDB==0 || pPager->tempFile );\n  assert( isOpen(pPager->fd) || pPager->tempFile );\n  if( 0==pagerFlushOnCommit(pPager, 1) ){\n    /* If this is an in-memory db, or no pages have been written to, or this\n    ** function has already been called, it is mostly a no-op.  However, any\n    ** backup in progress needs to be restarted.  */\n    sqlite3BackupRestart(pPager->pBackup);\n  }else{\n    PgHdr *pList;\n    if( pagerUseWal(pPager) ){\n      PgHdr *pPageOne = 0;\n      pList = sqlite3PcacheDirtyList(pPager->pPCache);\n      if( pList==0 ){\n        /* Must have at least one page for the WAL commit flag.\n        ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */\n        rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);\n        pList = pPageOne;\n        pList->pDirty = 0;\n      }\n      assert( rc==SQLITE_OK );\n      if( ALWAYS(pList) ){\n        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);\n      }\n      sqlite3PagerUnref(pPageOne);\n      if( rc==SQLITE_OK ){\n        sqlite3PcacheCleanAll(pPager->pPCache);\n      }\n    }else{\n      /* The bBatch boolean is true if the batch-atomic-write commit method\n      ** should be used.  No rollback journal is created if batch-atomic-write\n      ** is enabled.\n      */\n#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE\n      sqlite3_file *fd = pPager->fd;\n      int bBatch = zMaster==0    /* An SQLITE_IOCAP_BATCH_ATOMIC commit */\n        && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC)\n        && !pPager->noSync\n        && sqlite3JournalIsInMemory(pPager->jfd);\n#else\n#     define bBatch 0\n#endif\n\n#ifdef SQLITE_ENABLE_ATOMIC_WRITE\n      /* The following block updates the change-counter. Exactly how it\n      ** does this depends on whether or not the atomic-update optimization\n      ** was enabled at compile time, and if this transaction meets the \n      ** runtime criteria to use the operation: \n      **\n      **    * The file-system supports the atomic-write property for\n      **      blocks of size page-size, and \n      **    * This commit is not part of a multi-file transaction, and\n      **    * Exactly one page has been modified and store in the journal file.\n      **\n      ** If the optimization was not enabled at compile time, then the\n      ** pager_incr_changecounter() function is called to update the change\n      ** counter in 'indirect-mode'. If the optimization is compiled in but\n      ** is not applicable to this transaction, call sqlite3JournalCreate()\n      ** to make sure the journal file has actually been created, then call\n      ** pager_incr_changecounter() to update the change-counter in indirect\n      ** mode. \n      **\n      ** Otherwise, if the optimization is both enabled and applicable,\n      ** then call pager_incr_changecounter() to update the change-counter\n      ** in 'direct' mode. In this case the journal file will never be\n      ** created for this transaction.\n      */\n      if( bBatch==0 ){\n        PgHdr *pPg;\n        assert( isOpen(pPager->jfd) \n            || pPager->journalMode==PAGER_JOURNALMODE_OFF \n            || pPager->journalMode==PAGER_JOURNALMODE_WAL \n            );\n        if( !zMaster && isOpen(pPager->jfd) \n         && pPager->journalOff==jrnlBufferSize(pPager) \n         && pPager->dbSize>=pPager->dbOrigSize\n         && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)\n        ){\n          /* Update the db file change counter via the direct-write method. The \n          ** following call will modify the in-memory representation of page 1 \n          ** to include the updated change counter and then write page 1 \n          ** directly to the database file. Because of the atomic-write \n          ** property of the host file-system, this is safe.\n          */\n          rc = pager_incr_changecounter(pPager, 1);\n        }else{\n          rc = sqlite3JournalCreate(pPager->jfd);\n          if( rc==SQLITE_OK ){\n            rc = pager_incr_changecounter(pPager, 0);\n          }\n        }\n      }\n#else  /* SQLITE_ENABLE_ATOMIC_WRITE */\n#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE\n      if( zMaster ){\n        rc = sqlite3JournalCreate(pPager->jfd);\n        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;\n        assert( bBatch==0 );\n      }\n#endif\n      rc = pager_incr_changecounter(pPager, 0);\n#endif /* !SQLITE_ENABLE_ATOMIC_WRITE */\n      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;\n  \n      /* Write the master journal name into the journal file. If a master \n      ** journal file name has already been written to the journal file, \n      ** or if zMaster is NULL (no master journal), then this call is a no-op.\n      */\n      rc = writeMasterJournal(pPager, zMaster);\n      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;\n  \n      /* Sync the journal file and write all dirty pages to the database.\n      ** If the atomic-update optimization is being used, this sync will not \n      ** create the journal file or perform any real IO.\n      **\n      ** Because the change-counter page was just modified, unless the\n      ** atomic-update optimization is used it is almost certain that the\n      ** journal requires a sync here. However, in locking_mode=exclusive\n      ** on a system under memory pressure it is just possible that this is \n      ** not the case. In this case it is likely enough that the redundant\n      ** xSync() call will be changed to a no-op by the OS anyhow. \n      */\n      rc = syncJournal(pPager, 0);\n      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;\n\n      pList = sqlite3PcacheDirtyList(pPager->pPCache);\n#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE\n      if( bBatch ){\n        rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0);\n        if( rc==SQLITE_OK ){\n          rc = pager_write_pagelist(pPager, pList);\n          if( rc==SQLITE_OK ){\n            rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0);\n          }\n          if( rc!=SQLITE_OK ){\n            sqlite3OsFileControlHint(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0);\n          }\n        }\n\n        if( (rc&0xFF)==SQLITE_IOERR && rc!=SQLITE_IOERR_NOMEM ){\n          rc = sqlite3JournalCreate(pPager->jfd);\n          if( rc!=SQLITE_OK ){\n            sqlite3OsClose(pPager->jfd);\n            goto commit_phase_one_exit;\n          }\n          bBatch = 0;\n        }else{\n          sqlite3OsClose(pPager->jfd);\n        }\n      }\n#endif /* SQLITE_ENABLE_BATCH_ATOMIC_WRITE */\n\n      if( bBatch==0 ){\n        rc = pager_write_pagelist(pPager, pList);\n      }\n      if( rc!=SQLITE_OK ){\n        assert( rc!=SQLITE_IOERR_BLOCKED );\n        goto commit_phase_one_exit;\n      }\n      sqlite3PcacheCleanAll(pPager->pPCache);\n\n      /* If the file on disk is smaller than the database image, use \n      ** pager_truncate to grow the file here. This can happen if the database\n      ** image was extended as part of the current transaction and then the\n      ** last page in the db image moved to the free-list. In this case the\n      ** last page is never written out to disk, leaving the database file\n      ** undersized. Fix this now if it is the case.  */\n      if( pPager->dbSize>pPager->dbFileSize ){\n        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));\n        assert( pPager->eState==PAGER_WRITER_DBMOD );\n        rc = pager_truncate(pPager, nNew);\n        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;\n      }\n  \n      /* Finally, sync the database file. */\n      if( !noSync ){\n        rc = sqlite3PagerSync(pPager, zMaster);\n      }\n      IOTRACE((\"DBSYNC %p\\n\", pPager))\n    }\n  }\n\ncommit_phase_one_exit:\n  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){\n    pPager->eState = PAGER_WRITER_FINISHED;\n  }\n  return rc;\n}\n\n\n/*\n** When this function is called, the database file has been completely\n** updated to reflect the changes made by the current transaction and\n** synced to disk. The journal file still exists in the file-system \n** though, and if a failure occurs at this point it will eventually\n** be used as a hot-journal and the current transaction rolled back.\n**\n** This function finalizes the journal file, either by deleting, \n** truncating or partially zeroing it, so that it cannot be used \n** for hot-journal rollback. Once this is done the transaction is\n** irrevocably committed.\n**\n** If an error occurs, an IO error code is returned and the pager\n** moves into the error state. Otherwise, SQLITE_OK is returned.\n*/\nSQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){\n  int rc = SQLITE_OK;                  /* Return code */\n\n  /* This routine should not be called if a prior error has occurred.\n  ** But if (due to a coding error elsewhere in the system) it does get\n  ** called, just return the same error code without doing anything. */\n  if( NEVER(pPager->errCode) ) return pPager->errCode;\n  pPager->iDataVersion++;\n\n  assert( pPager->eState==PAGER_WRITER_LOCKED\n       || pPager->eState==PAGER_WRITER_FINISHED\n       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)\n  );\n  assert( assert_pager_state(pPager) );\n\n  /* An optimization. If the database was not actually modified during\n  ** this transaction, the pager is running in exclusive-mode and is\n  ** using persistent journals, then this function is a no-op.\n  **\n  ** The start of the journal file currently contains a single journal \n  ** header with the nRec field set to 0. If such a journal is used as\n  ** a hot-journal during hot-journal rollback, 0 changes will be made\n  ** to the database file. So there is no need to zero the journal \n  ** header. Since the pager is in exclusive mode, there is no need\n  ** to drop any locks either.\n  */\n  if( pPager->eState==PAGER_WRITER_LOCKED \n   && pPager->exclusiveMode \n   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST\n  ){\n    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );\n    pPager->eState = PAGER_READER;\n    return SQLITE_OK;\n  }\n\n  PAGERTRACE((\"COMMIT %d\\n\", PAGERID(pPager)));\n  rc = pager_end_transaction(pPager, pPager->setMaster, 1);\n  return pager_error(pPager, rc);\n}\n\n/*\n** If a write transaction is open, then all changes made within the \n** transaction are reverted and the current write-transaction is closed.\n** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR\n** state if an error occurs.\n**\n** If the pager is already in PAGER_ERROR state when this function is called,\n** it returns Pager.errCode immediately. No work is performed in this case.\n**\n** Otherwise, in rollback mode, this function performs two functions:\n**\n**   1) It rolls back the journal file, restoring all database file and \n**      in-memory cache pages to the state they were in when the transaction\n**      was opened, and\n**\n**   2) It finalizes the journal file, so that it is not used for hot\n**      rollback at any point in the future.\n**\n** Finalization of the journal file (task 2) is only performed if the \n** rollback is successful.\n**\n** In WAL mode, all cache-entries containing data modified within the\n** current transaction are either expelled from the cache or reverted to\n** their pre-transaction state by re-reading data from the database or\n** WAL files. The WAL transaction is then closed.\n*/\nSQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){\n  int rc = SQLITE_OK;                  /* Return code */\n  PAGERTRACE((\"ROLLBACK %d\\n\", PAGERID(pPager)));\n\n  /* PagerRollback() is a no-op if called in READER or OPEN state. If\n  ** the pager is already in the ERROR state, the rollback is not \n  ** attempted here. Instead, the error code is returned to the caller.\n  */\n  assert( assert_pager_state(pPager) );\n  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;\n  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;\n\n  if( pagerUseWal(pPager) ){\n    int rc2;\n    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);\n    rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){\n    int eState = pPager->eState;\n    rc = pager_end_transaction(pPager, 0, 0);\n    if( !MEMDB && eState>PAGER_WRITER_LOCKED ){\n      /* This can happen using journal_mode=off. Move the pager to the error \n      ** state to indicate that the contents of the cache may not be trusted.\n      ** Any active readers will get SQLITE_ABORT.\n      */\n      pPager->errCode = SQLITE_ABORT;\n      pPager->eState = PAGER_ERROR;\n      setGetterMethod(pPager);\n      return rc;\n    }\n  }else{\n    rc = pager_playback(pPager, 0);\n  }\n\n  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );\n  assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT\n          || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR \n          || rc==SQLITE_CANTOPEN\n  );\n\n  /* If an error occurs during a ROLLBACK, we can no longer trust the pager\n  ** cache. So call pager_error() on the way out to make any error persistent.\n  */\n  return pager_error(pPager, rc);\n}\n\n/*\n** Return TRUE if the database file is opened read-only.  Return FALSE\n** if the database is (in theory) writable.\n*/\nSQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){\n  return pPager->readOnly;\n}\n\n#ifdef SQLITE_DEBUG\n/*\n** Return the sum of the reference counts for all pages held by pPager.\n*/\nSQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){\n  return sqlite3PcacheRefCount(pPager->pPCache);\n}\n#endif\n\n/*\n** Return the approximate number of bytes of memory currently\n** used by the pager and its associated cache.\n*/\nSQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){\n  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)\n                                     + 5*sizeof(void*);\n  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)\n           + sqlite3MallocSize(pPager)\n           + pPager->pageSize;\n}\n\n/*\n** Return the number of references to the specified page.\n*/\nSQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){\n  return sqlite3PcachePageRefcount(pPage);\n}\n\n#ifdef SQLITE_TEST\n/*\n** This routine is used for testing and analysis only.\n*/\nSQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){\n  static int a[11];\n  a[0] = sqlite3PcacheRefCount(pPager->pPCache);\n  a[1] = sqlite3PcachePagecount(pPager->pPCache);\n  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);\n  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;\n  a[4] = pPager->eState;\n  a[5] = pPager->errCode;\n  a[6] = pPager->aStat[PAGER_STAT_HIT];\n  a[7] = pPager->aStat[PAGER_STAT_MISS];\n  a[8] = 0;  /* Used to be pPager->nOvfl */\n  a[9] = pPager->nRead;\n  a[10] = pPager->aStat[PAGER_STAT_WRITE];\n  return a;\n}\n#endif\n\n/*\n** Parameter eStat must be one of SQLITE_DBSTATUS_CACHE_HIT, _MISS, _WRITE,\n** or _WRITE+1.  The SQLITE_DBSTATUS_CACHE_WRITE+1 case is a translation\n** of SQLITE_DBSTATUS_CACHE_SPILL.  The _SPILL case is not contiguous because\n** it was added later.\n**\n** Before returning, *pnVal is incremented by the\n** current cache hit or miss count, according to the value of eStat. If the \n** reset parameter is non-zero, the cache hit or miss count is zeroed before \n** returning.\n*/\nSQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){\n\n  assert( eStat==SQLITE_DBSTATUS_CACHE_HIT\n       || eStat==SQLITE_DBSTATUS_CACHE_MISS\n       || eStat==SQLITE_DBSTATUS_CACHE_WRITE\n       || eStat==SQLITE_DBSTATUS_CACHE_WRITE+1\n  );\n\n  assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );\n  assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );\n  assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1\n           && PAGER_STAT_WRITE==2 && PAGER_STAT_SPILL==3 );\n\n  eStat -= SQLITE_DBSTATUS_CACHE_HIT;\n  *pnVal += pPager->aStat[eStat];\n  if( reset ){\n    pPager->aStat[eStat] = 0;\n  }\n}\n\n/*\n** Return true if this is an in-memory or temp-file backed pager.\n*/\nSQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){\n  return pPager->tempFile;\n}\n\n/*\n** Check that there are at least nSavepoint savepoints open. If there are\n** currently less than nSavepoints open, then open one or more savepoints\n** to make up the difference. If the number of savepoints is already\n** equal to nSavepoint, then this function is a no-op.\n**\n** If a memory allocation fails, SQLITE_NOMEM is returned. If an error \n** occurs while opening the sub-journal file, then an IO error code is\n** returned. Otherwise, SQLITE_OK.\n*/\nstatic SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){\n  int rc = SQLITE_OK;                       /* Return code */\n  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */\n  int ii;                                   /* Iterator variable */\n  PagerSavepoint *aNew;                     /* New Pager.aSavepoint array */\n\n  assert( pPager->eState>=PAGER_WRITER_LOCKED );\n  assert( assert_pager_state(pPager) );\n  assert( nSavepoint>nCurrent && pPager->useJournal );\n\n  /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM\n  ** if the allocation fails. Otherwise, zero the new portion in case a \n  ** malloc failure occurs while populating it in the for(...) loop below.\n  */\n  aNew = (PagerSavepoint *)sqlite3Realloc(\n      pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint\n  );\n  if( !aNew ){\n    return SQLITE_NOMEM_BKPT;\n  }\n  memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));\n  pPager->aSavepoint = aNew;\n\n  /* Populate the PagerSavepoint structures just allocated. */\n  for(ii=nCurrent; ii<nSavepoint; ii++){\n    aNew[ii].nOrig = pPager->dbSize;\n    if( isOpen(pPager->jfd) && pPager->journalOff>0 ){\n      aNew[ii].iOffset = pPager->journalOff;\n    }else{\n      aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);\n    }\n    aNew[ii].iSubRec = pPager->nSubRec;\n    aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);\n    if( !aNew[ii].pInSavepoint ){\n      return SQLITE_NOMEM_BKPT;\n    }\n    if( pagerUseWal(pPager) ){\n      sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);\n    }\n    pPager->nSavepoint = ii+1;\n  }\n  assert( pPager->nSavepoint==nSavepoint );\n  assertTruncateConstraint(pPager);\n  return rc;\n}\nSQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){\n  assert( pPager->eState>=PAGER_WRITER_LOCKED );\n  assert( assert_pager_state(pPager) );\n\n  if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){\n    return pagerOpenSavepoint(pPager, nSavepoint);\n  }else{\n    return SQLITE_OK;\n  }\n}\n\n\n/*\n** This function is called to rollback or release (commit) a savepoint.\n** The savepoint to release or rollback need not be the most recently \n** created savepoint.\n**\n** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.\n** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with\n** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes\n** that have occurred since the specified savepoint was created.\n**\n** The savepoint to rollback or release is identified by parameter \n** iSavepoint. A value of 0 means to operate on the outermost savepoint\n** (the first created). A value of (Pager.nSavepoint-1) means operate\n** on the most recently created savepoint. If iSavepoint is greater than\n** (Pager.nSavepoint-1), then this function is a no-op.\n**\n** If a negative value is passed to this function, then the current\n** transaction is rolled back. This is different to calling \n** sqlite3PagerRollback() because this function does not terminate\n** the transaction or unlock the database, it just restores the \n** contents of the database to its original state. \n**\n** In any case, all savepoints with an index greater than iSavepoint \n** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),\n** then savepoint iSavepoint is also destroyed.\n**\n** This function may return SQLITE_NOMEM if a memory allocation fails,\n** or an IO error code if an IO error occurs while rolling back a \n** savepoint. If no errors occur, SQLITE_OK is returned.\n*/ \nSQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){\n  int rc = pPager->errCode;\n  \n#ifdef SQLITE_ENABLE_ZIPVFS\n  if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;\n#endif\n\n  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );\n  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );\n\n  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){\n    int ii;            /* Iterator variable */\n    int nNew;          /* Number of remaining savepoints after this op. */\n\n    /* Figure out how many savepoints will still be active after this\n    ** operation. Store this value in nNew. Then free resources associated \n    ** with any savepoints that are destroyed by this operation.\n    */\n    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);\n    for(ii=nNew; ii<pPager->nSavepoint; ii++){\n      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);\n    }\n    pPager->nSavepoint = nNew;\n\n    /* If this is a release of the outermost savepoint, truncate \n    ** the sub-journal to zero bytes in size. */\n    if( op==SAVEPOINT_RELEASE ){\n      if( nNew==0 && isOpen(pPager->sjfd) ){\n        /* Only truncate if it is an in-memory sub-journal. */\n        if( sqlite3JournalIsInMemory(pPager->sjfd) ){\n          rc = sqlite3OsTruncate(pPager->sjfd, 0);\n          assert( rc==SQLITE_OK );\n        }\n        pPager->nSubRec = 0;\n      }\n    }\n    /* Else this is a rollback operation, playback the specified savepoint.\n    ** If this is a temp-file, it is possible that the journal file has\n    ** not yet been opened. In this case there have been no changes to\n    ** the database file, so the playback operation can be skipped.\n    */\n    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){\n      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];\n      rc = pagerPlaybackSavepoint(pPager, pSavepoint);\n      assert(rc!=SQLITE_DONE);\n    }\n    \n#ifdef SQLITE_ENABLE_ZIPVFS\n    /* If the cache has been modified but the savepoint cannot be rolled \n    ** back journal_mode=off, put the pager in the error state. This way,\n    ** if the VFS used by this pager includes ZipVFS, the entire transaction\n    ** can be rolled back at the ZipVFS level.  */\n    else if( \n        pPager->journalMode==PAGER_JOURNALMODE_OFF \n     && pPager->eState>=PAGER_WRITER_CACHEMOD\n    ){\n      pPager->errCode = SQLITE_ABORT;\n      pPager->eState = PAGER_ERROR;\n      setGetterMethod(pPager);\n    }\n#endif\n  }\n\n  return rc;\n}\n\n/*\n** Return the full pathname of the database file.\n**\n** Except, if the pager is in-memory only, then return an empty string if\n** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when\n** used to report the filename to the user, for compatibility with legacy\n** behavior.  But when the Btree needs to know the filename for matching to\n** shared cache, it uses nullIfMemDb==0 so that in-memory databases can\n** participate in shared-cache.\n**\n** The return value to this routine is always safe to use with\n** sqlite3_uri_parameter() and sqlite3_filename_database() and friends.\n*/\nSQLITE_PRIVATE const char *sqlite3PagerFilename(const Pager *pPager, int nullIfMemDb){\n  static const char zFake[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };\n  return (nullIfMemDb && pPager->memDb) ? &zFake[4] : pPager->zFilename;\n}\n\n/*\n** Return the VFS structure for the pager.\n*/\nSQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){\n  return pPager->pVfs;\n}\n\n/*\n** Return the file handle for the database file associated\n** with the pager.  This might return NULL if the file has\n** not yet been opened.\n*/\nSQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){\n  return pPager->fd;\n}\n\n/*\n** Return the file handle for the journal file (if it exists).\n** This will be either the rollback journal or the WAL file.\n*/\nSQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){\n#if SQLITE_OMIT_WAL\n  return pPager->jfd;\n#else\n  return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;\n#endif\n}\n\n/*\n** Return the full pathname of the journal file.\n*/\nSQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){\n  return pPager->zJournal;\n}\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n/*\n** Move the page pPg to location pgno in the file.\n**\n** There must be no references to the page previously located at\n** pgno (which we call pPgOld) though that page is allowed to be\n** in cache.  If the page previously located at pgno is not already\n** in the rollback journal, it is not put there by by this routine.\n**\n** References to the page pPg remain valid. Updating any\n** meta-data associated with pPg (i.e. data stored in the nExtra bytes\n** allocated along with the page) is the responsibility of the caller.\n**\n** A transaction must be active when this routine is called. It used to be\n** required that a statement transaction was not active, but this restriction\n** has been removed (CREATE INDEX needs to move a page when a statement\n** transaction is active).\n**\n** If the fourth argument, isCommit, is non-zero, then this page is being\n** moved as part of a database reorganization just before the transaction \n** is being committed. In this case, it is guaranteed that the database page \n** pPg refers to will not be written to again within this transaction.\n**\n** This function may return SQLITE_NOMEM or an IO error code if an error\n** occurs. Otherwise, it returns SQLITE_OK.\n*/\nSQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){\n  PgHdr *pPgOld;               /* The page being overwritten. */\n  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */\n  int rc;                      /* Return code */\n  Pgno origPgno;               /* The original page number */\n\n  assert( pPg->nRef>0 );\n  assert( pPager->eState==PAGER_WRITER_CACHEMOD\n       || pPager->eState==PAGER_WRITER_DBMOD\n  );\n  assert( assert_pager_state(pPager) );\n\n  /* In order to be able to rollback, an in-memory database must journal\n  ** the page we are moving from.\n  */\n  assert( pPager->tempFile || !MEMDB );\n  if( pPager->tempFile ){\n    rc = sqlite3PagerWrite(pPg);\n    if( rc ) return rc;\n  }\n\n  /* If the page being moved is dirty and has not been saved by the latest\n  ** savepoint, then save the current contents of the page into the \n  ** sub-journal now. This is required to handle the following scenario:\n  **\n  **   BEGIN;\n  **     <journal page X, then modify it in memory>\n  **     SAVEPOINT one;\n  **       <Move page X to location Y>\n  **     ROLLBACK TO one;\n  **\n  ** If page X were not written to the sub-journal here, it would not\n  ** be possible to restore its contents when the \"ROLLBACK TO one\"\n  ** statement were is processed.\n  **\n  ** subjournalPage() may need to allocate space to store pPg->pgno into\n  ** one or more savepoint bitvecs. This is the reason this function\n  ** may return SQLITE_NOMEM.\n  */\n  if( (pPg->flags & PGHDR_DIRTY)!=0\n   && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))\n  ){\n    return rc;\n  }\n\n  PAGERTRACE((\"MOVE %d page %d (needSync=%d) moves to %d\\n\", \n      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));\n  IOTRACE((\"MOVE %p %d %d\\n\", pPager, pPg->pgno, pgno))\n\n  /* If the journal needs to be sync()ed before page pPg->pgno can\n  ** be written to, store pPg->pgno in local variable needSyncPgno.\n  **\n  ** If the isCommit flag is set, there is no need to remember that\n  ** the journal needs to be sync()ed before database page pPg->pgno \n  ** can be written to. The caller has already promised not to write to it.\n  */\n  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){\n    needSyncPgno = pPg->pgno;\n    assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||\n            pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );\n    assert( pPg->flags&PGHDR_DIRTY );\n  }\n\n  /* If the cache contains a page with page-number pgno, remove it\n  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for \n  ** page pgno before the 'move' operation, it needs to be retained \n  ** for the page moved there.\n  */\n  pPg->flags &= ~PGHDR_NEED_SYNC;\n  pPgOld = sqlite3PagerLookup(pPager, pgno);\n  assert( !pPgOld || pPgOld->nRef==1 || CORRUPT_DB );\n  if( pPgOld ){\n    if( pPgOld->nRef>1 ){\n      sqlite3PagerUnrefNotNull(pPgOld);\n      return SQLITE_CORRUPT_BKPT;\n    }\n    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);\n    if( pPager->tempFile ){\n      /* Do not discard pages from an in-memory database since we might\n      ** need to rollback later.  Just move the page out of the way. */\n      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);\n    }else{\n      sqlite3PcacheDrop(pPgOld);\n    }\n  }\n\n  origPgno = pPg->pgno;\n  sqlite3PcacheMove(pPg, pgno);\n  sqlite3PcacheMakeDirty(pPg);\n\n  /* For an in-memory database, make sure the original page continues\n  ** to exist, in case the transaction needs to roll back.  Use pPgOld\n  ** as the original page since it has already been allocated.\n  */\n  if( pPager->tempFile && pPgOld ){\n    sqlite3PcacheMove(pPgOld, origPgno);\n    sqlite3PagerUnrefNotNull(pPgOld);\n  }\n\n  if( needSyncPgno ){\n    /* If needSyncPgno is non-zero, then the journal file needs to be \n    ** sync()ed before any data is written to database file page needSyncPgno.\n    ** Currently, no such page exists in the page-cache and the \n    ** \"is journaled\" bitvec flag has been set. This needs to be remedied by\n    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC\n    ** flag.\n    **\n    ** If the attempt to load the page into the page-cache fails, (due\n    ** to a malloc() or IO failure), clear the bit in the pInJournal[]\n    ** array. Otherwise, if the page is loaded and written again in\n    ** this transaction, it may be written to the database file before\n    ** it is synced into the journal file. This way, it may end up in\n    ** the journal file twice, but that is not a problem.\n    */\n    PgHdr *pPgHdr;\n    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);\n    if( rc!=SQLITE_OK ){\n      if( needSyncPgno<=pPager->dbOrigSize ){\n        assert( pPager->pTmpSpace!=0 );\n        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);\n      }\n      return rc;\n    }\n    pPgHdr->flags |= PGHDR_NEED_SYNC;\n    sqlite3PcacheMakeDirty(pPgHdr);\n    sqlite3PagerUnrefNotNull(pPgHdr);\n  }\n\n  return SQLITE_OK;\n}\n#endif\n\n/*\n** The page handle passed as the first argument refers to a dirty page \n** with a page number other than iNew. This function changes the page's \n** page number to iNew and sets the value of the PgHdr.flags field to \n** the value passed as the third parameter.\n*/\nSQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){\n  assert( pPg->pgno!=iNew );\n  pPg->flags = flags;\n  sqlite3PcacheMove(pPg, iNew);\n}\n\n/*\n** Return a pointer to the data for the specified page.\n*/\nSQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){\n  assert( pPg->nRef>0 || pPg->pPager->memDb );\n  return pPg->pData;\n}\n\n/*\n** Return a pointer to the Pager.nExtra bytes of \"extra\" space \n** allocated along with the specified page.\n*/\nSQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){\n  return pPg->pExtra;\n}\n\n/*\n** Get/set the locking-mode for this pager. Parameter eMode must be one\n** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or \n** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then\n** the locking-mode is set to the value specified.\n**\n** The returned value is either PAGER_LOCKINGMODE_NORMAL or\n** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)\n** locking-mode.\n*/\nSQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){\n  assert( eMode==PAGER_LOCKINGMODE_QUERY\n            || eMode==PAGER_LOCKINGMODE_NORMAL\n            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );\n  assert( PAGER_LOCKINGMODE_QUERY<0 );\n  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );\n  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );\n  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){\n    pPager->exclusiveMode = (u8)eMode;\n  }\n  return (int)pPager->exclusiveMode;\n}\n\n/*\n** Set the journal-mode for this pager. Parameter eMode must be one of:\n**\n**    PAGER_JOURNALMODE_DELETE\n**    PAGER_JOURNALMODE_TRUNCATE\n**    PAGER_JOURNALMODE_PERSIST\n**    PAGER_JOURNALMODE_OFF\n**    PAGER_JOURNALMODE_MEMORY\n**    PAGER_JOURNALMODE_WAL\n**\n** The journalmode is set to the value specified if the change is allowed.\n** The change may be disallowed for the following reasons:\n**\n**   *  An in-memory database can only have its journal_mode set to _OFF\n**      or _MEMORY.\n**\n**   *  Temporary databases cannot have _WAL journalmode.\n**\n** The returned indicate the current (possibly updated) journal-mode.\n*/\nSQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){\n  u8 eOld = pPager->journalMode;    /* Prior journalmode */\n\n  /* The eMode parameter is always valid */\n  assert(      eMode==PAGER_JOURNALMODE_DELETE\n            || eMode==PAGER_JOURNALMODE_TRUNCATE\n            || eMode==PAGER_JOURNALMODE_PERSIST\n            || eMode==PAGER_JOURNALMODE_OFF \n            || eMode==PAGER_JOURNALMODE_WAL \n            || eMode==PAGER_JOURNALMODE_MEMORY );\n\n  /* This routine is only called from the OP_JournalMode opcode, and\n  ** the logic there will never allow a temporary file to be changed\n  ** to WAL mode.\n  */\n  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );\n\n  /* Do allow the journalmode of an in-memory database to be set to\n  ** anything other than MEMORY or OFF\n  */\n  if( MEMDB ){\n    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );\n    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){\n      eMode = eOld;\n    }\n  }\n\n  if( eMode!=eOld ){\n\n    /* Change the journal mode. */\n    assert( pPager->eState!=PAGER_ERROR );\n    pPager->journalMode = (u8)eMode;\n\n    /* When transistioning from TRUNCATE or PERSIST to any other journal\n    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,\n    ** delete the journal file.\n    */\n    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );\n    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );\n    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );\n    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );\n    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );\n    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );\n\n    assert( isOpen(pPager->fd) || pPager->exclusiveMode );\n    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){\n\n      /* In this case we would like to delete the journal file. If it is\n      ** not possible, then that is not a problem. Deleting the journal file\n      ** here is an optimization only.\n      **\n      ** Before deleting the journal file, obtain a RESERVED lock on the\n      ** database file. This ensures that the journal file is not deleted\n      ** while it is in use by some other client.\n      */\n      sqlite3OsClose(pPager->jfd);\n      if( pPager->eLock>=RESERVED_LOCK ){\n        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);\n      }else{\n        int rc = SQLITE_OK;\n        int state = pPager->eState;\n        assert( state==PAGER_OPEN || state==PAGER_READER );\n        if( state==PAGER_OPEN ){\n          rc = sqlite3PagerSharedLock(pPager);\n        }\n        if( pPager->eState==PAGER_READER ){\n          assert( rc==SQLITE_OK );\n          rc = pagerLockDb(pPager, RESERVED_LOCK);\n        }\n        if( rc==SQLITE_OK ){\n          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);\n        }\n        if( rc==SQLITE_OK && state==PAGER_READER ){\n          pagerUnlockDb(pPager, SHARED_LOCK);\n        }else if( state==PAGER_OPEN ){\n          pager_unlock(pPager);\n        }\n        assert( state==pPager->eState );\n      }\n    }else if( eMode==PAGER_JOURNALMODE_OFF ){\n      sqlite3OsClose(pPager->jfd);\n    }\n  }\n\n  /* Return the new journal mode */\n  return (int)pPager->journalMode;\n}\n\n/*\n** Return the current journal mode.\n*/\nSQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){\n  return (int)pPager->journalMode;\n}\n\n/*\n** Return TRUE if the pager is in a state where it is OK to change the\n** journalmode.  Journalmode changes can only happen when the database\n** is unmodified.\n*/\nSQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){\n  assert( assert_pager_state(pPager) );\n  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;\n  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;\n  return 1;\n}\n\n/*\n** Get/set the size-limit used for persistent journal files.\n**\n** Setting the size limit to -1 means no limit is enforced.\n** An attempt to set a limit smaller than -1 is a no-op.\n*/\nSQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){\n  if( iLimit>=-1 ){\n    pPager->journalSizeLimit = iLimit;\n    sqlite3WalLimit(pPager->pWal, iLimit);\n  }\n  return pPager->journalSizeLimit;\n}\n\n/*\n** Return a pointer to the pPager->pBackup variable. The backup module\n** in backup.c maintains the content of this variable. This module\n** uses it opaquely as an argument to sqlite3BackupRestart() and\n** sqlite3BackupUpdate() only.\n*/\nSQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){\n  return &pPager->pBackup;\n}\n\n#ifndef SQLITE_OMIT_VACUUM\n/*\n** Unless this is an in-memory or temporary database, clear the pager cache.\n*/\nSQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){\n  assert( MEMDB==0 || pPager->tempFile );\n  if( pPager->tempFile==0 ) pager_reset(pPager);\n}\n#endif\n\n\n#ifndef SQLITE_OMIT_WAL\n/*\n** This function is called when the user invokes \"PRAGMA wal_checkpoint\",\n** \"PRAGMA wal_blocking_checkpoint\" or calls the sqlite3_wal_checkpoint()\n** or wal_blocking_checkpoint() API functions.\n**\n** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.\n*/\nSQLITE_PRIVATE int sqlite3PagerCheckpoint(\n  Pager *pPager,                  /* Checkpoint on this pager */\n  sqlite3 *db,                    /* Db handle used to check for interrupts */\n  int eMode,                      /* Type of checkpoint */\n  int *pnLog,                     /* OUT: Final number of frames in log */\n  int *pnCkpt                     /* OUT: Final number of checkpointed frames */\n){\n  int rc = SQLITE_OK;\n  if( pPager->pWal ){\n    rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,\n        (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),\n        pPager->pBusyHandlerArg,\n        pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,\n        pnLog, pnCkpt\n    );\n  }\n  return rc;\n}\n\nSQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){\n  return sqlite3WalCallback(pPager->pWal);\n}\n\n/*\n** Return true if the underlying VFS for the given pager supports the\n** primitives necessary for write-ahead logging.\n*/\nSQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){\n  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;\n  if( pPager->noLock ) return 0;\n  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);\n}\n\n/*\n** Attempt to take an exclusive lock on the database file. If a PENDING lock\n** is obtained instead, immediately release it.\n*/\nstatic int pagerExclusiveLock(Pager *pPager){\n  int rc;                         /* Return code */\n\n  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );\n  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);\n  if( rc!=SQLITE_OK ){\n    /* If the attempt to grab the exclusive lock failed, release the \n    ** pending lock that may have been obtained instead.  */\n    pagerUnlockDb(pPager, SHARED_LOCK);\n  }\n\n  return rc;\n}\n\n/*\n** Call sqlite3WalOpen() to open the WAL handle. If the pager is in \n** exclusive-locking mode when this function is called, take an EXCLUSIVE\n** lock on the database file and use heap-memory to store the wal-index\n** in. Otherwise, use the normal shared-memory.\n*/\nstatic int pagerOpenWal(Pager *pPager){\n  int rc = SQLITE_OK;\n\n  assert( pPager->pWal==0 && pPager->tempFile==0 );\n  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );\n\n  /* If the pager is already in exclusive-mode, the WAL module will use \n  ** heap-memory for the wal-index instead of the VFS shared-memory \n  ** implementation. Take the exclusive lock now, before opening the WAL\n  ** file, to make sure this is safe.\n  */\n  if( pPager->exclusiveMode ){\n    rc = pagerExclusiveLock(pPager);\n  }\n\n  /* Open the connection to the log file. If this operation fails, \n  ** (e.g. due to malloc() failure), return an error code.\n  */\n  if( rc==SQLITE_OK ){\n    rc = sqlite3WalOpen(pPager->pVfs,\n        pPager->fd, pPager->zWal, pPager->exclusiveMode,\n        pPager->journalSizeLimit, &pPager->pWal\n    );\n  }\n  pagerFixMaplimit(pPager);\n\n  return rc;\n}\n\n\n/*\n** The caller must be holding a SHARED lock on the database file to call\n** this function.\n**\n** If the pager passed as the first argument is open on a real database\n** file (not a temp file or an in-memory database), and the WAL file\n** is not already open, make an attempt to open it now. If successful,\n** return SQLITE_OK. If an error occurs or the VFS used by the pager does \n** not support the xShmXXX() methods, return an error code. *pbOpen is\n** not modified in either case.\n**\n** If the pager is open on a temp-file (or in-memory database), or if\n** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK\n** without doing anything.\n*/\nSQLITE_PRIVATE int sqlite3PagerOpenWal(\n  Pager *pPager,                  /* Pager object */\n  int *pbOpen                     /* OUT: Set to true if call is a no-op */\n){\n  int rc = SQLITE_OK;             /* Return code */\n\n  assert( assert_pager_state(pPager) );\n  assert( pPager->eState==PAGER_OPEN   || pbOpen );\n  assert( pPager->eState==PAGER_READER || !pbOpen );\n  assert( pbOpen==0 || *pbOpen==0 );\n  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );\n\n  if( !pPager->tempFile && !pPager->pWal ){\n    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;\n\n    /* Close any rollback journal previously open */\n    sqlite3OsClose(pPager->jfd);\n\n    rc = pagerOpenWal(pPager);\n    if( rc==SQLITE_OK ){\n      pPager->journalMode = PAGER_JOURNALMODE_WAL;\n      pPager->eState = PAGER_OPEN;\n    }\n  }else{\n    *pbOpen = 1;\n  }\n\n  return rc;\n}\n\n/*\n** This function is called to close the connection to the log file prior\n** to switching from WAL to rollback mode.\n**\n** Before closing the log file, this function attempts to take an \n** EXCLUSIVE lock on the database file. If this cannot be obtained, an\n** error (SQLITE_BUSY) is returned and the log connection is not closed.\n** If successful, the EXCLUSIVE lock is not released before returning.\n*/\nSQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){\n  int rc = SQLITE_OK;\n\n  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );\n\n  /* If the log file is not already open, but does exist in the file-system,\n  ** it may need to be checkpointed before the connection can switch to\n  ** rollback mode. Open it now so this can happen.\n  */\n  if( !pPager->pWal ){\n    int logexists = 0;\n    rc = pagerLockDb(pPager, SHARED_LOCK);\n    if( rc==SQLITE_OK ){\n      rc = sqlite3OsAccess(\n          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists\n      );\n    }\n    if( rc==SQLITE_OK && logexists ){\n      rc = pagerOpenWal(pPager);\n    }\n  }\n    \n  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on\n  ** the database file, the log and log-summary files will be deleted.\n  */\n  if( rc==SQLITE_OK && pPager->pWal ){\n    rc = pagerExclusiveLock(pPager);\n    if( rc==SQLITE_OK ){\n      rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,\n                           pPager->pageSize, (u8*)pPager->pTmpSpace);\n      pPager->pWal = 0;\n      pagerFixMaplimit(pPager);\n      if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);\n    }\n  }\n  return rc;\n}\n\n#ifdef SQLITE_ENABLE_SETLK_TIMEOUT\n/*\n** If pager pPager is a wal-mode database not in exclusive locking mode,\n** invoke the sqlite3WalWriteLock() function on the associated Wal object \n** with the same db and bLock parameters as were passed to this function.\n** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.\n*/\nSQLITE_PRIVATE int sqlite3PagerWalWriteLock(Pager *pPager, int bLock){\n  int rc = SQLITE_OK;\n  if( pagerUseWal(pPager) && pPager->exclusiveMode==0 ){\n    rc = sqlite3WalWriteLock(pPager->pWal, bLock);\n  }\n  return rc;\n}\n\n/*\n** Set the database handle used by the wal layer to determine if \n** blocking locks are required.\n*/\nSQLITE_PRIVATE void sqlite3PagerWalDb(Pager *pPager, sqlite3 *db){\n  if( pagerUseWal(pPager) ){\n    sqlite3WalDb(pPager->pWal, db);\n  }\n}\n#endif\n\n#ifdef SQLITE_ENABLE_SNAPSHOT\n/*\n** If this is a WAL database, obtain a snapshot handle for the snapshot\n** currently open. Otherwise, return an error.\n*/\nSQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){\n  int rc = SQLITE_ERROR;\n  if( pPager->pWal ){\n    rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);\n  }\n  return rc;\n}\n\n/*\n** If this is a WAL database, store a pointer to pSnapshot. Next time a\n** read transaction is opened, attempt to read from the snapshot it \n** identifies. If this is not a WAL database, return an error.\n*/\nSQLITE_PRIVATE int sqlite3PagerSnapshotOpen(\n  Pager *pPager, \n  sqlite3_snapshot *pSnapshot\n){\n  int rc = SQLITE_OK;\n  if( pPager->pWal ){\n    sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);\n  }else{\n    rc = SQLITE_ERROR;\n  }\n  return rc;\n}\n\n/*\n** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this \n** is not a WAL database, return an error.\n*/\nSQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){\n  int rc;\n  if( pPager->pWal ){\n    rc = sqlite3WalSnapshotRecover(pPager->pWal);\n  }else{\n    rc = SQLITE_ERROR;\n  }\n  return rc;\n}\n\n/*\n** The caller currently has a read transaction open on the database.\n** If this is not a WAL database, SQLITE_ERROR is returned. Otherwise,\n** this function takes a SHARED lock on the CHECKPOINTER slot and then\n** checks if the snapshot passed as the second argument is still \n** available. If so, SQLITE_OK is returned.\n**\n** If the snapshot is not available, SQLITE_ERROR is returned. Or, if\n** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error\n** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER\n** lock is released before returning.\n*/\nSQLITE_PRIVATE int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot){\n  int rc;\n  if( pPager->pWal ){\n    rc = sqlite3WalSnapshotCheck(pPager->pWal, pSnapshot);\n  }else{\n    rc = SQLITE_ERROR;\n  }\n  return rc;\n}\n\n/*\n** Release a lock obtained by an earlier successful call to\n** sqlite3PagerSnapshotCheck().\n*/\nSQLITE_PRIVATE void sqlite3PagerSnapshotUnlock(Pager *pPager){\n  assert( pPager->pWal );\n  sqlite3WalSnapshotUnlock(pPager->pWal);\n}\n\n#endif /* SQLITE_ENABLE_SNAPSHOT */\n#endif /* !SQLITE_OMIT_WAL */\n\n#ifdef SQLITE_ENABLE_ZIPVFS\n/*\n** A read-lock must be held on the pager when this function is called. If\n** the pager is in WAL mode and the WAL file currently contains one or more\n** frames, return the size in bytes of the page images stored within the\n** WAL frames. Otherwise, if this is not a WAL database or the WAL file\n** is empty, return 0.\n*/\nSQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){\n  assert( pPager->eState>=PAGER_READER );\n  return sqlite3WalFramesize(pPager->pWal);\n}\n#endif\n\n#endif /* SQLITE_OMIT_DISKIO */\n\n/************** End of pager.c ***********************************************/\n/************** Begin file wal.c *********************************************/\n/*\n** 2010 February 1\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains the implementation of a write-ahead log (WAL) used in \n** \"journal_mode=WAL\" mode.\n**\n** WRITE-AHEAD LOG (WAL) FILE FORMAT\n**\n** A WAL file consists of a header followed by zero or more \"frames\".\n** Each frame records the revised content of a single page from the\n** database file.  All changes to the database are recorded by writing\n** frames into the WAL.  Transactions commit when a frame is written that\n** contains a commit marker.  A single WAL can and usually does record \n** multiple transactions.  Periodically, the content of the WAL is\n** transferred back into the database file in an operation called a\n** \"checkpoint\".\n**\n** A single WAL file can be used multiple times.  In other words, the\n** WAL can fill up with frames and then be checkpointed and then new\n** frames can overwrite the old ones.  A WAL always grows from beginning\n** toward the end.  Checksums and counters attached to each frame are\n** used to determine which frames within the WAL are valid and which\n** are leftovers from prior checkpoints.\n**\n** The WAL header is 32 bytes in size and consists of the following eight\n** big-endian 32-bit unsigned integer values:\n**\n**     0: Magic number.  0x377f0682 or 0x377f0683\n**     4: File format version.  Currently 3007000\n**     8: Database page size.  Example: 1024\n**    12: Checkpoint sequence number\n**    16: Salt-1, random integer incremented with each checkpoint\n**    20: Salt-2, a different random integer changing with each ckpt\n**    24: Checksum-1 (first part of checksum for first 24 bytes of header).\n**    28: Checksum-2 (second part of checksum for first 24 bytes of header).\n**\n** Immediately following the wal-header are zero or more frames. Each\n** frame consists of a 24-byte frame-header followed by a <page-size> bytes\n** of page data. The frame-header is six big-endian 32-bit unsigned \n** integer values, as follows:\n**\n**     0: Page number.\n**     4: For commit records, the size of the database image in pages \n**        after the commit. For all other records, zero.\n**     8: Salt-1 (copied from the header)\n**    12: Salt-2 (copied from the header)\n**    16: Checksum-1.\n**    20: Checksum-2.\n**\n** A frame is considered valid if and only if the following conditions are\n** true:\n**\n**    (1) The salt-1 and salt-2 values in the frame-header match\n**        salt values in the wal-header\n**\n**    (2) The checksum values in the final 8 bytes of the frame-header\n**        exactly match the checksum computed consecutively on the\n**        WAL header and the first 8 bytes and the content of all frames\n**        up to and including the current frame.\n**\n** The checksum is computed using 32-bit big-endian integers if the\n** magic number in the first 4 bytes of the WAL is 0x377f0683 and it\n** is computed using little-endian if the magic number is 0x377f0682.\n** The checksum values are always stored in the frame header in a\n** big-endian format regardless of which byte order is used to compute\n** the checksum.  The checksum is computed by interpreting the input as\n** an even number of unsigned 32-bit integers: x[0] through x[N].  The\n** algorithm used for the checksum is as follows:\n** \n**   for i from 0 to n-1 step 2:\n**     s0 += x[i] + s1;\n**     s1 += x[i+1] + s0;\n**   endfor\n**\n** Note that s0 and s1 are both weighted checksums using fibonacci weights\n** in reverse order (the largest fibonacci weight occurs on the first element\n** of the sequence being summed.)  The s1 value spans all 32-bit \n** terms of the sequence whereas s0 omits the final term.\n**\n** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the\n** WAL is transferred into the database, then the database is VFS.xSync-ed.\n** The VFS.xSync operations serve as write barriers - all writes launched\n** before the xSync must complete before any write that launches after the\n** xSync begins.\n**\n** After each checkpoint, the salt-1 value is incremented and the salt-2\n** value is randomized.  This prevents old and new frames in the WAL from\n** being considered valid at the same time and being checkpointing together\n** following a crash.\n**\n** READER ALGORITHM\n**\n** To read a page from the database (call it page number P), a reader\n** first checks the WAL to see if it contains page P.  If so, then the\n** last valid instance of page P that is a followed by a commit frame\n** or is a commit frame itself becomes the value read.  If the WAL\n** contains no copies of page P that are valid and which are a commit\n** frame or are followed by a commit frame, then page P is read from\n** the database file.\n**\n** To start a read transaction, the reader records the index of the last\n** valid frame in the WAL.  The reader uses this recorded \"mxFrame\" value\n** for all subsequent read operations.  New transactions can be appended\n** to the WAL, but as long as the reader uses its original mxFrame value\n** and ignores the newly appended content, it will see a consistent snapshot\n** of the database from a single point in time.  This technique allows\n** multiple concurrent readers to view different versions of the database\n** content simultaneously.\n**\n** The reader algorithm in the previous paragraphs works correctly, but \n** because frames for page P can appear anywhere within the WAL, the\n** reader has to scan the entire WAL looking for page P frames.  If the\n** WAL is large (multiple megabytes is typical) that scan can be slow,\n** and read performance suffers.  To overcome this problem, a separate\n** data structure called the wal-index is maintained to expedite the\n** search for frames of a particular page.\n** \n** WAL-INDEX FORMAT\n**\n** Conceptually, the wal-index is shared memory, though VFS implementations\n** might choose to implement the wal-index using a mmapped file.  Because\n** the wal-index is shared memory, SQLite does not support journal_mode=WAL \n** on a network filesystem.  All users of the database must be able to\n** share memory.\n**\n** In the default unix and windows implementation, the wal-index is a mmapped\n** file whose name is the database name with a \"-shm\" suffix added.  For that\n** reason, the wal-index is sometimes called the \"shm\" file.\n**\n** The wal-index is transient.  After a crash, the wal-index can (and should\n** be) reconstructed from the original WAL file.  In fact, the VFS is required\n** to either truncate or zero the header of the wal-index when the last\n** connection to it closes.  Because the wal-index is transient, it can\n** use an architecture-specific format; it does not have to be cross-platform.\n** Hence, unlike the database and WAL file formats which store all values\n** as big endian, the wal-index can store multi-byte values in the native\n** byte order of the host computer.\n**\n** The purpose of the wal-index is to answer this question quickly:  Given\n** a page number P and a maximum frame index M, return the index of the \n** last frame in the wal before frame M for page P in the WAL, or return\n** NULL if there are no frames for page P in the WAL prior to M.\n**\n** The wal-index consists of a header region, followed by an one or\n** more index blocks.  \n**\n** The wal-index header contains the total number of frames within the WAL\n** in the mxFrame field.\n**\n** Each index block except for the first contains information on \n** HASHTABLE_NPAGE frames. The first index block contains information on\n** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and \n** HASHTABLE_NPAGE are selected so that together the wal-index header and\n** first index block are the same size as all other index blocks in the\n** wal-index.\n**\n** Each index block contains two sections, a page-mapping that contains the\n** database page number associated with each wal frame, and a hash-table \n** that allows readers to query an index block for a specific page number.\n** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE\n** for the first index block) 32-bit page numbers. The first entry in the \n** first index-block contains the database page number corresponding to the\n** first frame in the WAL file. The first entry in the second index block\n** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in\n** the log, and so on.\n**\n** The last index block in a wal-index usually contains less than the full\n** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,\n** depending on the contents of the WAL file. This does not change the\n** allocated size of the page-mapping array - the page-mapping array merely\n** contains unused entries.\n**\n** Even without using the hash table, the last frame for page P\n** can be found by scanning the page-mapping sections of each index block\n** starting with the last index block and moving toward the first, and\n** within each index block, starting at the end and moving toward the\n** beginning.  The first entry that equals P corresponds to the frame\n** holding the content for that page.\n**\n** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.\n** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the\n** hash table for each page number in the mapping section, so the hash \n** table is never more than half full.  The expected number of collisions \n** prior to finding a match is 1.  Each entry of the hash table is an\n** 1-based index of an entry in the mapping section of the same\n** index block.   Let K be the 1-based index of the largest entry in\n** the mapping section.  (For index blocks other than the last, K will\n** always be exactly HASHTABLE_NPAGE (4096) and for the last index block\n** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table\n** contain a value of 0.\n**\n** To look for page P in the hash table, first compute a hash iKey on\n** P as follows:\n**\n**      iKey = (P * 383) % HASHTABLE_NSLOT\n**\n** Then start scanning entries of the hash table, starting with iKey\n** (wrapping around to the beginning when the end of the hash table is\n** reached) until an unused hash slot is found. Let the first unused slot\n** be at index iUnused.  (iUnused might be less than iKey if there was\n** wrap-around.) Because the hash table is never more than half full,\n** the search is guaranteed to eventually hit an unused entry.  Let \n** iMax be the value between iKey and iUnused, closest to iUnused,\n** where aHash[iMax]==P.  If there is no iMax entry (if there exists\n** no hash slot such that aHash[i]==p) then page P is not in the\n** current index block.  Otherwise the iMax-th mapping entry of the\n** current index block corresponds to the last entry that references \n** page P.\n**\n** A hash search begins with the last index block and moves toward the\n** first index block, looking for entries corresponding to page P.  On\n** average, only two or three slots in each index block need to be\n** examined in order to either find the last entry for page P, or to\n** establish that no such entry exists in the block.  Each index block\n** holds over 4000 entries.  So two or three index blocks are sufficient\n** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10\n** comparisons (on average) suffice to either locate a frame in the\n** WAL or to establish that the frame does not exist in the WAL.  This\n** is much faster than scanning the entire 10MB WAL.\n**\n** Note that entries are added in order of increasing K.  Hence, one\n** reader might be using some value K0 and a second reader that started\n** at a later time (after additional transactions were added to the WAL\n** and to the wal-index) might be using a different value K1, where K1>K0.\n** Both readers can use the same hash table and mapping section to get\n** the correct result.  There may be entries in the hash table with\n** K>K0 but to the first reader, those entries will appear to be unused\n** slots in the hash table and so the first reader will get an answer as\n** if no values greater than K0 had ever been inserted into the hash table\n** in the first place - which is what reader one wants.  Meanwhile, the\n** second reader using K1 will see additional values that were inserted\n** later, which is exactly what reader two wants.  \n**\n** When a rollback occurs, the value of K is decreased. Hash table entries\n** that correspond to frames greater than the new K value are removed\n** from the hash table at this point.\n*/\n#ifndef SQLITE_OMIT_WAL\n\n/* #include \"wal.h\" */\n\n/*\n** Trace output macros\n*/\n#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)\nSQLITE_PRIVATE int sqlite3WalTrace = 0;\n# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X\n#else\n# define WALTRACE(X)\n#endif\n\n/*\n** The maximum (and only) versions of the wal and wal-index formats\n** that may be interpreted by this version of SQLite.\n**\n** If a client begins recovering a WAL file and finds that (a) the checksum\n** values in the wal-header are correct and (b) the version field is not\n** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.\n**\n** Similarly, if a client successfully reads a wal-index header (i.e. the \n** checksum test is successful) and finds that the version field is not\n** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite\n** returns SQLITE_CANTOPEN.\n*/\n#define WAL_MAX_VERSION      3007000\n#define WALINDEX_MAX_VERSION 3007000\n\n/*\n** Index numbers for various locking bytes.   WAL_NREADER is the number\n** of available reader locks and should be at least 3.  The default\n** is SQLITE_SHM_NLOCK==8 and  WAL_NREADER==5.\n**\n** Technically, the various VFSes are free to implement these locks however\n** they see fit.  However, compatibility is encouraged so that VFSes can\n** interoperate.  The standard implemention used on both unix and windows\n** is for the index number to indicate a byte offset into the\n** WalCkptInfo.aLock[] array in the wal-index header.  In other words, all\n** locks are on the shm file.  The WALINDEX_LOCK_OFFSET constant (which\n** should be 120) is the location in the shm file for the first locking\n** byte.\n*/\n#define WAL_WRITE_LOCK         0\n#define WAL_ALL_BUT_WRITE      1\n#define WAL_CKPT_LOCK          1\n#define WAL_RECOVER_LOCK       2\n#define WAL_READ_LOCK(I)       (3+(I))\n#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)\n\n\n/* Object declarations */\ntypedef struct WalIndexHdr WalIndexHdr;\ntypedef struct WalIterator WalIterator;\ntypedef struct WalCkptInfo WalCkptInfo;\n\n\n/*\n** The following object holds a copy of the wal-index header content.\n**\n** The actual header in the wal-index consists of two copies of this\n** object followed by one instance of the WalCkptInfo object.\n** For all versions of SQLite through 3.10.0 and probably beyond,\n** the locking bytes (WalCkptInfo.aLock) start at offset 120 and\n** the total header size is 136 bytes.\n**\n** The szPage value can be any power of 2 between 512 and 32768, inclusive.\n** Or it can be 1 to represent a 65536-byte page.  The latter case was\n** added in 3.7.1 when support for 64K pages was added.  \n*/\nstruct WalIndexHdr {\n  u32 iVersion;                   /* Wal-index version */\n  u32 unused;                     /* Unused (padding) field */\n  u32 iChange;                    /* Counter incremented each transaction */\n  u8 isInit;                      /* 1 when initialized */\n  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */\n  u16 szPage;                     /* Database page size in bytes. 1==64K */\n  u32 mxFrame;                    /* Index of last valid frame in the WAL */\n  u32 nPage;                      /* Size of database in pages */\n  u32 aFrameCksum[2];             /* Checksum of last frame in log */\n  u32 aSalt[2];                   /* Two salt values copied from WAL header */\n  u32 aCksum[2];                  /* Checksum over all prior fields */\n};\n\n/*\n** A copy of the following object occurs in the wal-index immediately\n** following the second copy of the WalIndexHdr.  This object stores\n** information used by checkpoint.\n**\n** nBackfill is the number of frames in the WAL that have been written\n** back into the database. (We call the act of moving content from WAL to\n** database \"backfilling\".)  The nBackfill number is never greater than\n** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads\n** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).\n** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from\n** mxFrame back to zero when the WAL is reset.\n**\n** nBackfillAttempted is the largest value of nBackfill that a checkpoint\n** has attempted to achieve.  Normally nBackfill==nBackfillAtempted, however\n** the nBackfillAttempted is set before any backfilling is done and the\n** nBackfill is only set after all backfilling completes.  So if a checkpoint\n** crashes, nBackfillAttempted might be larger than nBackfill.  The\n** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.\n**\n** The aLock[] field is a set of bytes used for locking.  These bytes should\n** never be read or written.\n**\n** There is one entry in aReadMark[] for each reader lock.  If a reader\n** holds read-lock K, then the value in aReadMark[K] is no greater than\n** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)\n** for any aReadMark[] means that entry is unused.  aReadMark[0] is \n** a special case; its value is never used and it exists as a place-holder\n** to avoid having to offset aReadMark[] indexs by one.  Readers holding\n** WAL_READ_LOCK(0) always ignore the entire WAL and read all content\n** directly from the database.\n**\n** The value of aReadMark[K] may only be changed by a thread that\n** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of\n** aReadMark[K] cannot changed while there is a reader is using that mark\n** since the reader will be holding a shared lock on WAL_READ_LOCK(K).\n**\n** The checkpointer may only transfer frames from WAL to database where\n** the frame numbers are less than or equal to every aReadMark[] that is\n** in use (that is, every aReadMark[j] for which there is a corresponding\n** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the\n** largest value and will increase an unused aReadMark[] to mxFrame if there\n** is not already an aReadMark[] equal to mxFrame.  The exception to the\n** previous sentence is when nBackfill equals mxFrame (meaning that everything\n** in the WAL has been backfilled into the database) then new readers\n** will choose aReadMark[0] which has value 0 and hence such reader will\n** get all their all content directly from the database file and ignore \n** the WAL.\n**\n** Writers normally append new frames to the end of the WAL.  However,\n** if nBackfill equals mxFrame (meaning that all WAL content has been\n** written back into the database) and if no readers are using the WAL\n** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then\n** the writer will first \"reset\" the WAL back to the beginning and start\n** writing new content beginning at frame 1.\n**\n** We assume that 32-bit loads are atomic and so no locks are needed in\n** order to read from any aReadMark[] entries.\n*/\nstruct WalCkptInfo {\n  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */\n  u32 aReadMark[WAL_NREADER];     /* Reader marks */\n  u8 aLock[SQLITE_SHM_NLOCK];     /* Reserved space for locks */\n  u32 nBackfillAttempted;         /* WAL frames perhaps written, or maybe not */\n  u32 notUsed0;                   /* Available for future enhancements */\n};\n#define READMARK_NOT_USED  0xffffffff\n\n\n/* A block of WALINDEX_LOCK_RESERVED bytes beginning at\n** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems\n** only support mandatory file-locks, we do not read or write data\n** from the region of the file on which locks are applied.\n*/\n#define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))\n#define WALINDEX_HDR_SIZE    (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))\n\n/* Size of header before each frame in wal */\n#define WAL_FRAME_HDRSIZE 24\n\n/* Size of write ahead log header, including checksum. */\n#define WAL_HDRSIZE 32\n\n/* WAL magic value. Either this value, or the same value with the least\n** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit\n** big-endian format in the first 4 bytes of a WAL file.\n**\n** If the LSB is set, then the checksums for each frame within the WAL\n** file are calculated by treating all data as an array of 32-bit \n** big-endian words. Otherwise, they are calculated by interpreting \n** all data as 32-bit little-endian words.\n*/\n#define WAL_MAGIC 0x377f0682\n\n/*\n** Return the offset of frame iFrame in the write-ahead log file, \n** assuming a database page size of szPage bytes. The offset returned\n** is to the start of the write-ahead log frame-header.\n*/\n#define walFrameOffset(iFrame, szPage) (                               \\\n  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \\\n)\n\n/*\n** An open write-ahead log file is represented by an instance of the\n** following object.\n*/\nstruct Wal {\n  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */\n  sqlite3_file *pDbFd;       /* File handle for the database file */\n  sqlite3_file *pWalFd;      /* File handle for WAL file */\n  u32 iCallback;             /* Value to pass to log callback (or 0) */\n  i64 mxWalSize;             /* Truncate WAL to this size upon reset */\n  int nWiData;               /* Size of array apWiData */\n  int szFirstBlock;          /* Size of first block written to WAL file */\n  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */\n  u32 szPage;                /* Database page size */\n  i16 readLock;              /* Which read lock is being held.  -1 for none */\n  u8 syncFlags;              /* Flags to use to sync header writes */\n  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */\n  u8 writeLock;              /* True if in a write transaction */\n  u8 ckptLock;               /* True if holding a checkpoint lock */\n  u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */\n  u8 truncateOnCommit;       /* True to truncate WAL file on commit */\n  u8 syncHeader;             /* Fsync the WAL header if true */\n  u8 padToSectorBoundary;    /* Pad transactions out to the next sector */\n  u8 bShmUnreliable;         /* SHM content is read-only and unreliable */\n  WalIndexHdr hdr;           /* Wal-index header for current transaction */\n  u32 minFrame;              /* Ignore wal frames before this one */\n  u32 iReCksum;              /* On commit, recalculate checksums from here */\n  const char *zWalName;      /* Name of WAL file */\n  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */\n#ifdef SQLITE_DEBUG\n  u8 lockError;              /* True if a locking error has occurred */\n#endif\n#ifdef SQLITE_ENABLE_SNAPSHOT\n  WalIndexHdr *pSnapshot;    /* Start transaction here if not NULL */\n#endif\n#ifdef SQLITE_ENABLE_SETLK_TIMEOUT\n  sqlite3 *db;\n#endif\n};\n\n/*\n** Candidate values for Wal.exclusiveMode.\n*/\n#define WAL_NORMAL_MODE     0\n#define WAL_EXCLUSIVE_MODE  1     \n#define WAL_HEAPMEMORY_MODE 2\n\n/*\n** Possible values for WAL.readOnly\n*/\n#define WAL_RDWR        0    /* Normal read/write connection */\n#define WAL_RDONLY      1    /* The WAL file is readonly */\n#define WAL_SHM_RDONLY  2    /* The SHM file is readonly */\n\n/*\n** Each page of the wal-index mapping contains a hash-table made up of\n** an array of HASHTABLE_NSLOT elements of the following type.\n*/\ntypedef u16 ht_slot;\n\n/*\n** This structure is used to implement an iterator that loops through\n** all frames in the WAL in database page order. Where two or more frames\n** correspond to the same database page, the iterator visits only the \n** frame most recently written to the WAL (in other words, the frame with\n** the largest index).\n**\n** The internals of this structure are only accessed by:\n**\n**   walIteratorInit() - Create a new iterator,\n**   walIteratorNext() - Step an iterator,\n**   walIteratorFree() - Free an iterator.\n**\n** This functionality is used by the checkpoint code (see walCheckpoint()).\n*/\nstruct WalIterator {\n  int iPrior;                     /* Last result returned from the iterator */\n  int nSegment;                   /* Number of entries in aSegment[] */\n  struct WalSegment {\n    int iNext;                    /* Next slot in aIndex[] not yet returned */\n    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */\n    u32 *aPgno;                   /* Array of page numbers. */\n    int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */\n    int iZero;                    /* Frame number associated with aPgno[0] */\n  } aSegment[1];                  /* One for every 32KB page in the wal-index */\n};\n\n/*\n** Define the parameters of the hash tables in the wal-index file. There\n** is a hash-table following every HASHTABLE_NPAGE page numbers in the\n** wal-index.\n**\n** Changing any of these constants will alter the wal-index format and\n** create incompatibilities.\n*/\n#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */\n#define HASHTABLE_HASH_1     383                  /* Should be prime */\n#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */\n\n/* \n** The block of page numbers associated with the first hash-table in a\n** wal-index is smaller than usual. This is so that there is a complete\n** hash-table on each aligned 32KB page of the wal-index.\n*/\n#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))\n\n/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */\n#define WALINDEX_PGSZ   (                                         \\\n    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \\\n)\n\n/*\n** Obtain a pointer to the iPage'th page of the wal-index. The wal-index\n** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are\n** numbered from zero.\n**\n** If the wal-index is currently smaller the iPage pages then the size\n** of the wal-index might be increased, but only if it is safe to do\n** so.  It is safe to enlarge the wal-index if pWal->writeLock is true\n** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.\n**\n** If this call is successful, *ppPage is set to point to the wal-index\n** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,\n** then an SQLite error code is returned and *ppPage is set to 0.\n*/\nstatic SQLITE_NOINLINE int walIndexPageRealloc(\n  Wal *pWal,               /* The WAL context */\n  int iPage,               /* The page we seek */\n  volatile u32 **ppPage    /* Write the page pointer here */\n){\n  int rc = SQLITE_OK;\n\n  /* Enlarge the pWal->apWiData[] array if required */\n  if( pWal->nWiData<=iPage ){\n    sqlite3_int64 nByte = sizeof(u32*)*(iPage+1);\n    volatile u32 **apNew;\n    apNew = (volatile u32 **)sqlite3Realloc((void *)pWal->apWiData, nByte);\n    if( !apNew ){\n      *ppPage = 0;\n      return SQLITE_NOMEM_BKPT;\n    }\n    memset((void*)&apNew[pWal->nWiData], 0,\n           sizeof(u32*)*(iPage+1-pWal->nWiData));\n    pWal->apWiData = apNew;\n    pWal->nWiData = iPage+1;\n  }\n\n  /* Request a pointer to the required page from the VFS */\n  assert( pWal->apWiData[iPage]==0 );\n  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){\n    pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);\n    if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;\n  }else{\n    rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, \n        pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]\n    );\n    assert( pWal->apWiData[iPage]!=0 || rc!=SQLITE_OK || pWal->writeLock==0 );\n    testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );\n    if( (rc&0xff)==SQLITE_READONLY ){\n      pWal->readOnly |= WAL_SHM_RDONLY;\n      if( rc==SQLITE_READONLY ){\n        rc = SQLITE_OK;\n      }\n    }\n  }\n\n  *ppPage = pWal->apWiData[iPage];\n  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );\n  return rc;\n}\nstatic int walIndexPage(\n  Wal *pWal,               /* The WAL context */\n  int iPage,               /* The page we seek */\n  volatile u32 **ppPage    /* Write the page pointer here */\n){\n  if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){\n    return walIndexPageRealloc(pWal, iPage, ppPage);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Return a pointer to the WalCkptInfo structure in the wal-index.\n*/\nstatic volatile WalCkptInfo *walCkptInfo(Wal *pWal){\n  assert( pWal->nWiData>0 && pWal->apWiData[0] );\n  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);\n}\n\n/*\n** Return a pointer to the WalIndexHdr structure in the wal-index.\n*/\nstatic volatile WalIndexHdr *walIndexHdr(Wal *pWal){\n  assert( pWal->nWiData>0 && pWal->apWiData[0] );\n  return (volatile WalIndexHdr*)pWal->apWiData[0];\n}\n\n/*\n** The argument to this macro must be of type u32. On a little-endian\n** architecture, it returns the u32 value that results from interpreting\n** the 4 bytes as a big-endian value. On a big-endian architecture, it\n** returns the value that would be produced by interpreting the 4 bytes\n** of the input value as a little-endian integer.\n*/\n#define BYTESWAP32(x) ( \\\n    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \\\n  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \\\n)\n\n/*\n** Generate or extend an 8 byte checksum based on the data in \n** array aByte[] and the initial values of aIn[0] and aIn[1] (or\n** initial values of 0 and 0 if aIn==NULL).\n**\n** The checksum is written back into aOut[] before returning.\n**\n** nByte must be a positive multiple of 8.\n*/\nstatic void walChecksumBytes(\n  int nativeCksum, /* True for native byte-order, false for non-native */\n  u8 *a,           /* Content to be checksummed */\n  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */\n  const u32 *aIn,  /* Initial checksum value input */\n  u32 *aOut        /* OUT: Final checksum value output */\n){\n  u32 s1, s2;\n  u32 *aData = (u32 *)a;\n  u32 *aEnd = (u32 *)&a[nByte];\n\n  if( aIn ){\n    s1 = aIn[0];\n    s2 = aIn[1];\n  }else{\n    s1 = s2 = 0;\n  }\n\n  assert( nByte>=8 );\n  assert( (nByte&0x00000007)==0 );\n  assert( nByte<=65536 );\n\n  if( nativeCksum ){\n    do {\n      s1 += *aData++ + s2;\n      s2 += *aData++ + s1;\n    }while( aData<aEnd );\n  }else{\n    do {\n      s1 += BYTESWAP32(aData[0]) + s2;\n      s2 += BYTESWAP32(aData[1]) + s1;\n      aData += 2;\n    }while( aData<aEnd );\n  }\n\n  aOut[0] = s1;\n  aOut[1] = s2;\n}\n\n/*\n** If there is the possibility of concurrent access to the SHM file\n** from multiple threads and/or processes, then do a memory barrier.\n*/\nstatic void walShmBarrier(Wal *pWal){\n  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){\n    sqlite3OsShmBarrier(pWal->pDbFd);\n  }\n}\n\n/*\n** Add the SQLITE_NO_TSAN as part of the return-type of a function\n** definition as a hint that the function contains constructs that\n** might give false-positive TSAN warnings.\n**\n** See tag-20200519-1.\n*/\n#if defined(__clang__) && !defined(SQLITE_NO_TSAN)\n# define SQLITE_NO_TSAN __attribute__((no_sanitize_thread))\n#else\n# define SQLITE_NO_TSAN\n#endif\n\n/*\n** Write the header information in pWal->hdr into the wal-index.\n**\n** The checksum on pWal->hdr is updated before it is written.\n*/\nstatic SQLITE_NO_TSAN void walIndexWriteHdr(Wal *pWal){\n  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);\n  const int nCksum = offsetof(WalIndexHdr, aCksum);\n\n  assert( pWal->writeLock );\n  pWal->hdr.isInit = 1;\n  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;\n  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);\n  /* Possible TSAN false-positive.  See tag-20200519-1 */\n  memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));\n  walShmBarrier(pWal);\n  memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));\n}\n\n/*\n** This function encodes a single frame header and writes it to a buffer\n** supplied by the caller. A frame-header is made up of a series of \n** 4-byte big-endian integers, as follows:\n**\n**     0: Page number.\n**     4: For commit records, the size of the database image in pages \n**        after the commit. For all other records, zero.\n**     8: Salt-1 (copied from the wal-header)\n**    12: Salt-2 (copied from the wal-header)\n**    16: Checksum-1.\n**    20: Checksum-2.\n*/\nstatic void walEncodeFrame(\n  Wal *pWal,                      /* The write-ahead log */\n  u32 iPage,                      /* Database page number for frame */\n  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */\n  u8 *aData,                      /* Pointer to page data */\n  u8 *aFrame                      /* OUT: Write encoded frame here */\n){\n  int nativeCksum;                /* True for native byte-order checksums */\n  u32 *aCksum = pWal->hdr.aFrameCksum;\n  assert( WAL_FRAME_HDRSIZE==24 );\n  sqlite3Put4byte(&aFrame[0], iPage);\n  sqlite3Put4byte(&aFrame[4], nTruncate);\n  if( pWal->iReCksum==0 ){\n    memcpy(&aFrame[8], pWal->hdr.aSalt, 8);\n\n    nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);\n    walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);\n    walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);\n\n    sqlite3Put4byte(&aFrame[16], aCksum[0]);\n    sqlite3Put4byte(&aFrame[20], aCksum[1]);\n  }else{\n    memset(&aFrame[8], 0, 16);\n  }\n}\n\n/*\n** Check to see if the frame with header in aFrame[] and content\n** in aData[] is valid.  If it is a valid frame, fill *piPage and\n** *pnTruncate and return true.  Return if the frame is not valid.\n*/\nstatic int walDecodeFrame(\n  Wal *pWal,                      /* The write-ahead log */\n  u32 *piPage,                    /* OUT: Database page number for frame */\n  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */\n  u8 *aData,                      /* Pointer to page data (for checksum) */\n  u8 *aFrame                      /* Frame data */\n){\n  int nativeCksum;                /* True for native byte-order checksums */\n  u32 *aCksum = pWal->hdr.aFrameCksum;\n  u32 pgno;                       /* Page number of the frame */\n  assert( WAL_FRAME_HDRSIZE==24 );\n\n  /* A frame is only valid if the salt values in the frame-header\n  ** match the salt values in the wal-header. \n  */\n  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){\n    return 0;\n  }\n\n  /* A frame is only valid if the page number is creater than zero.\n  */\n  pgno = sqlite3Get4byte(&aFrame[0]);\n  if( pgno==0 ){\n    return 0;\n  }\n\n  /* A frame is only valid if a checksum of the WAL header,\n  ** all prior frams, the first 16 bytes of this frame-header, \n  ** and the frame-data matches the checksum in the last 8 \n  ** bytes of this frame-header.\n  */\n  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);\n  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);\n  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);\n  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) \n   || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) \n  ){\n    /* Checksum failed. */\n    return 0;\n  }\n\n  /* If we reach this point, the frame is valid.  Return the page number\n  ** and the new database size.\n  */\n  *piPage = pgno;\n  *pnTruncate = sqlite3Get4byte(&aFrame[4]);\n  return 1;\n}\n\n\n#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)\n/*\n** Names of locks.  This routine is used to provide debugging output and is not\n** a part of an ordinary build.\n*/\nstatic const char *walLockName(int lockIdx){\n  if( lockIdx==WAL_WRITE_LOCK ){\n    return \"WRITE-LOCK\";\n  }else if( lockIdx==WAL_CKPT_LOCK ){\n    return \"CKPT-LOCK\";\n  }else if( lockIdx==WAL_RECOVER_LOCK ){\n    return \"RECOVER-LOCK\";\n  }else{\n    static char zName[15];\n    sqlite3_snprintf(sizeof(zName), zName, \"READ-LOCK[%d]\",\n                     lockIdx-WAL_READ_LOCK(0));\n    return zName;\n  }\n}\n#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */\n    \n\n/*\n** Set or release locks on the WAL.  Locks are either shared or exclusive.\n** A lock cannot be moved directly between shared and exclusive - it must go\n** through the unlocked state first.\n**\n** In locking_mode=EXCLUSIVE, all of these routines become no-ops.\n*/\nstatic int walLockShared(Wal *pWal, int lockIdx){\n  int rc;\n  if( pWal->exclusiveMode ) return SQLITE_OK;\n  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,\n                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);\n  WALTRACE((\"WAL%p: acquire SHARED-%s %s\\n\", pWal,\n            walLockName(lockIdx), rc ? \"failed\" : \"ok\"));\n  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )\n  return rc;\n}\nstatic void walUnlockShared(Wal *pWal, int lockIdx){\n  if( pWal->exclusiveMode ) return;\n  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,\n                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);\n  WALTRACE((\"WAL%p: release SHARED-%s\\n\", pWal, walLockName(lockIdx)));\n}\nstatic int walLockExclusive(Wal *pWal, int lockIdx, int n){\n  int rc;\n  if( pWal->exclusiveMode ) return SQLITE_OK;\n  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,\n                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);\n  WALTRACE((\"WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\\n\", pWal,\n            walLockName(lockIdx), n, rc ? \"failed\" : \"ok\"));\n  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )\n  return rc;\n}\nstatic void walUnlockExclusive(Wal *pWal, int lockIdx, int n){\n  if( pWal->exclusiveMode ) return;\n  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,\n                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);\n  WALTRACE((\"WAL%p: release EXCLUSIVE-%s cnt=%d\\n\", pWal,\n             walLockName(lockIdx), n));\n}\n\n/*\n** Compute a hash on a page number.  The resulting hash value must land\n** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances\n** the hash to the next value in the event of a collision.\n*/\nstatic int walHash(u32 iPage){\n  assert( iPage>0 );\n  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );\n  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);\n}\nstatic int walNextHash(int iPriorHash){\n  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);\n}\n\n/*\n** An instance of the WalHashLoc object is used to describe the location\n** of a page hash table in the wal-index.  This becomes the return value\n** from walHashGet().\n*/\ntypedef struct WalHashLoc WalHashLoc;\nstruct WalHashLoc {\n  volatile ht_slot *aHash;  /* Start of the wal-index hash table */\n  volatile u32 *aPgno;      /* aPgno[1] is the page of first frame indexed */\n  u32 iZero;                /* One less than the frame number of first indexed*/\n};\n\n/* \n** Return pointers to the hash table and page number array stored on\n** page iHash of the wal-index. The wal-index is broken into 32KB pages\n** numbered starting from 0.\n**\n** Set output variable pLoc->aHash to point to the start of the hash table\n** in the wal-index file. Set pLoc->iZero to one less than the frame \n** number of the first frame indexed by this hash table. If a\n** slot in the hash table is set to N, it refers to frame number \n** (pLoc->iZero+N) in the log.\n**\n** Finally, set pLoc->aPgno so that pLoc->aPgno[1] is the page number of the\n** first frame indexed by the hash table, frame (pLoc->iZero+1).\n*/\nstatic int walHashGet(\n  Wal *pWal,                      /* WAL handle */\n  int iHash,                      /* Find the iHash'th table */\n  WalHashLoc *pLoc                /* OUT: Hash table location */\n){\n  int rc;                         /* Return code */\n\n  rc = walIndexPage(pWal, iHash, &pLoc->aPgno);\n  assert( rc==SQLITE_OK || iHash>0 );\n\n  if( rc==SQLITE_OK ){\n    pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE];\n    if( iHash==0 ){\n      pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];\n      pLoc->iZero = 0;\n    }else{\n      pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;\n    }\n    pLoc->aPgno = &pLoc->aPgno[-1];\n  }\n  return rc;\n}\n\n/*\n** Return the number of the wal-index page that contains the hash-table\n** and page-number array that contain entries corresponding to WAL frame\n** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages \n** are numbered starting from 0.\n*/\nstatic int walFramePage(u32 iFrame){\n  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;\n  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)\n       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)\n       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))\n       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)\n       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))\n  );\n  return iHash;\n}\n\n/*\n** Return the page number associated with frame iFrame in this WAL.\n*/\nstatic u32 walFramePgno(Wal *pWal, u32 iFrame){\n  int iHash = walFramePage(iFrame);\n  if( iHash==0 ){\n    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];\n  }\n  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];\n}\n\n/*\n** Remove entries from the hash table that point to WAL slots greater\n** than pWal->hdr.mxFrame.\n**\n** This function is called whenever pWal->hdr.mxFrame is decreased due\n** to a rollback or savepoint.\n**\n** At most only the hash table containing pWal->hdr.mxFrame needs to be\n** updated.  Any later hash tables will be automatically cleared when\n** pWal->hdr.mxFrame advances to the point where those hash tables are\n** actually needed.\n*/\nstatic void walCleanupHash(Wal *pWal){\n  WalHashLoc sLoc;                /* Hash table location */\n  int iLimit = 0;                 /* Zero values greater than this */\n  int nByte;                      /* Number of bytes to zero in aPgno[] */\n  int i;                          /* Used to iterate through aHash[] */\n  int rc;                         /* Return code form walHashGet() */\n\n  assert( pWal->writeLock );\n  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );\n  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );\n  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );\n\n  if( pWal->hdr.mxFrame==0 ) return;\n\n  /* Obtain pointers to the hash-table and page-number array containing \n  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed\n  ** that the page said hash-table and array reside on is already mapped.(1)\n  */\n  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );\n  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );\n  rc = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);\n  if( NEVER(rc) ) return; /* Defense-in-depth, in case (1) above is wrong */\n\n  /* Zero all hash-table entries that correspond to frame numbers greater\n  ** than pWal->hdr.mxFrame.\n  */\n  iLimit = pWal->hdr.mxFrame - sLoc.iZero;\n  assert( iLimit>0 );\n  for(i=0; i<HASHTABLE_NSLOT; i++){\n    if( sLoc.aHash[i]>iLimit ){\n      sLoc.aHash[i] = 0;\n    }\n  }\n  \n  /* Zero the entries in the aPgno array that correspond to frames with\n  ** frame numbers greater than pWal->hdr.mxFrame. \n  */\n  nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit+1]);\n  memset((void *)&sLoc.aPgno[iLimit+1], 0, nByte);\n\n#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT\n  /* Verify that the every entry in the mapping region is still reachable\n  ** via the hash table even after the cleanup.\n  */\n  if( iLimit ){\n    int j;           /* Loop counter */\n    int iKey;        /* Hash key */\n    for(j=1; j<=iLimit; j++){\n      for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){\n        if( sLoc.aHash[iKey]==j ) break;\n      }\n      assert( sLoc.aHash[iKey]==j );\n    }\n  }\n#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */\n}\n\n\n/*\n** Set an entry in the wal-index that will map database page number\n** pPage into WAL frame iFrame.\n*/\nstatic int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){\n  int rc;                         /* Return code */\n  WalHashLoc sLoc;                /* Wal-index hash table location */\n\n  rc = walHashGet(pWal, walFramePage(iFrame), &sLoc);\n\n  /* Assuming the wal-index file was successfully mapped, populate the\n  ** page number array and hash table entry.\n  */\n  if( rc==SQLITE_OK ){\n    int iKey;                     /* Hash table key */\n    int idx;                      /* Value to write to hash-table slot */\n    int nCollide;                 /* Number of hash collisions */\n\n    idx = iFrame - sLoc.iZero;\n    assert( idx <= HASHTABLE_NSLOT/2 + 1 );\n    \n    /* If this is the first entry to be added to this hash-table, zero the\n    ** entire hash table and aPgno[] array before proceeding. \n    */\n    if( idx==1 ){\n      int nByte = (int)((u8 *)&sLoc.aHash[HASHTABLE_NSLOT]\n                               - (u8 *)&sLoc.aPgno[1]);\n      memset((void*)&sLoc.aPgno[1], 0, nByte);\n    }\n\n    /* If the entry in aPgno[] is already set, then the previous writer\n    ** must have exited unexpectedly in the middle of a transaction (after\n    ** writing one or more dirty pages to the WAL to free up memory). \n    ** Remove the remnants of that writers uncommitted transaction from \n    ** the hash-table before writing any new entries.\n    */\n    if( sLoc.aPgno[idx] ){\n      walCleanupHash(pWal);\n      assert( !sLoc.aPgno[idx] );\n    }\n\n    /* Write the aPgno[] array entry and the hash-table slot. */\n    nCollide = idx;\n    for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){\n      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;\n    }\n    sLoc.aPgno[idx] = iPage;\n    sLoc.aHash[iKey] = (ht_slot)idx;\n\n#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT\n    /* Verify that the number of entries in the hash table exactly equals\n    ** the number of entries in the mapping region.\n    */\n    {\n      int i;           /* Loop counter */\n      int nEntry = 0;  /* Number of entries in the hash table */\n      for(i=0; i<HASHTABLE_NSLOT; i++){ if( sLoc.aHash[i] ) nEntry++; }\n      assert( nEntry==idx );\n    }\n\n    /* Verify that the every entry in the mapping region is reachable\n    ** via the hash table.  This turns out to be a really, really expensive\n    ** thing to check, so only do this occasionally - not on every\n    ** iteration.\n    */\n    if( (idx&0x3ff)==0 ){\n      int i;           /* Loop counter */\n      for(i=1; i<=idx; i++){\n        for(iKey=walHash(sLoc.aPgno[i]);\n            sLoc.aHash[iKey];\n            iKey=walNextHash(iKey)){\n          if( sLoc.aHash[iKey]==i ) break;\n        }\n        assert( sLoc.aHash[iKey]==i );\n      }\n    }\n#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */\n  }\n\n\n  return rc;\n}\n\n\n/*\n** Recover the wal-index by reading the write-ahead log file. \n**\n** This routine first tries to establish an exclusive lock on the\n** wal-index to prevent other threads/processes from doing anything\n** with the WAL or wal-index while recovery is running.  The\n** WAL_RECOVER_LOCK is also held so that other threads will know\n** that this thread is running recovery.  If unable to establish\n** the necessary locks, this routine returns SQLITE_BUSY.\n*/\nstatic int walIndexRecover(Wal *pWal){\n  int rc;                         /* Return Code */\n  i64 nSize;                      /* Size of log file */\n  u32 aFrameCksum[2] = {0, 0};\n  int iLock;                      /* Lock offset to lock for checkpoint */\n\n  /* Obtain an exclusive lock on all byte in the locking range not already\n  ** locked by the caller. The caller is guaranteed to have locked the\n  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.\n  ** If successful, the same bytes that are locked here are unlocked before\n  ** this function returns.\n  */\n  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );\n  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );\n  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );\n  assert( pWal->writeLock );\n  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;\n  rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);\n  if( rc==SQLITE_OK ){\n    rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);\n    if( rc!=SQLITE_OK ){\n      walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);\n    }\n  }\n  if( rc ){\n    return rc;\n  }\n\n  WALTRACE((\"WAL%p: recovery begin...\\n\", pWal));\n\n  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));\n\n  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);\n  if( rc!=SQLITE_OK ){\n    goto recovery_error;\n  }\n\n  if( nSize>WAL_HDRSIZE ){\n    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */\n    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */\n    int szFrame;                  /* Number of bytes in buffer aFrame[] */\n    u8 *aData;                    /* Pointer to data part of aFrame buffer */\n    int iFrame;                   /* Index of last frame read */\n    i64 iOffset;                  /* Next offset to read from log file */\n    int szPage;                   /* Page size according to the log */\n    u32 magic;                    /* Magic value read from WAL header */\n    u32 version;                  /* Magic value read from WAL header */\n    int isValid;                  /* True if this frame is valid */\n\n    /* Read in the WAL header. */\n    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);\n    if( rc!=SQLITE_OK ){\n      goto recovery_error;\n    }\n\n    /* If the database page size is not a power of two, or is greater than\n    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid \n    ** data. Similarly, if the 'magic' value is invalid, ignore the whole\n    ** WAL file.\n    */\n    magic = sqlite3Get4byte(&aBuf[0]);\n    szPage = sqlite3Get4byte(&aBuf[8]);\n    if( (magic&0xFFFFFFFE)!=WAL_MAGIC \n     || szPage&(szPage-1) \n     || szPage>SQLITE_MAX_PAGE_SIZE \n     || szPage<512 \n    ){\n      goto finished;\n    }\n    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);\n    pWal->szPage = szPage;\n    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);\n    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);\n\n    /* Verify that the WAL header checksum is correct */\n    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, \n        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum\n    );\n    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])\n     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])\n    ){\n      goto finished;\n    }\n\n    /* Verify that the version number on the WAL format is one that\n    ** are able to understand */\n    version = sqlite3Get4byte(&aBuf[4]);\n    if( version!=WAL_MAX_VERSION ){\n      rc = SQLITE_CANTOPEN_BKPT;\n      goto finished;\n    }\n\n    /* Malloc a buffer to read frames into. */\n    szFrame = szPage + WAL_FRAME_HDRSIZE;\n    aFrame = (u8 *)sqlite3_malloc64(szFrame);\n    if( !aFrame ){\n      rc = SQLITE_NOMEM_BKPT;\n      goto recovery_error;\n    }\n    aData = &aFrame[WAL_FRAME_HDRSIZE];\n\n    /* Read all frames from the log file. */\n    iFrame = 0;\n    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){\n      u32 pgno;                   /* Database page number for frame */\n      u32 nTruncate;              /* dbsize field from frame header */\n\n      /* Read and decode the next log frame. */\n      iFrame++;\n      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);\n      if( rc!=SQLITE_OK ) break;\n      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);\n      if( !isValid ) break;\n      rc = walIndexAppend(pWal, iFrame, pgno);\n      if( rc!=SQLITE_OK ) break;\n\n      /* If nTruncate is non-zero, this is a commit record. */\n      if( nTruncate ){\n        pWal->hdr.mxFrame = iFrame;\n        pWal->hdr.nPage = nTruncate;\n        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));\n        testcase( szPage<=32768 );\n        testcase( szPage>=65536 );\n        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];\n        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];\n      }\n    }\n\n    sqlite3_free(aFrame);\n  }\n\nfinished:\n  if( rc==SQLITE_OK ){\n    volatile WalCkptInfo *pInfo;\n    int i;\n    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];\n    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];\n    walIndexWriteHdr(pWal);\n\n    /* Reset the checkpoint-header. This is safe because this thread is \n    ** currently holding locks that exclude all other readers, writers and\n    ** checkpointers.\n    */\n    pInfo = walCkptInfo(pWal);\n    pInfo->nBackfill = 0;\n    pInfo->nBackfillAttempted = pWal->hdr.mxFrame;\n    pInfo->aReadMark[0] = 0;\n    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;\n    if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;\n\n    /* If more than one frame was recovered from the log file, report an\n    ** event via sqlite3_log(). This is to help with identifying performance\n    ** problems caused by applications routinely shutting down without\n    ** checkpointing the log file.\n    */\n    if( pWal->hdr.nPage ){\n      sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,\n          \"recovered %d frames from WAL file %s\",\n          pWal->hdr.mxFrame, pWal->zWalName\n      );\n    }\n  }\n\nrecovery_error:\n  WALTRACE((\"WAL%p: recovery %s\\n\", pWal, rc ? \"failed\" : \"ok\"));\n  walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);\n  walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);\n  return rc;\n}\n\n/*\n** Close an open wal-index.\n*/\nstatic void walIndexClose(Wal *pWal, int isDelete){\n  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){\n    int i;\n    for(i=0; i<pWal->nWiData; i++){\n      sqlite3_free((void *)pWal->apWiData[i]);\n      pWal->apWiData[i] = 0;\n    }\n  }\n  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){\n    sqlite3OsShmUnmap(pWal->pDbFd, isDelete);\n  }\n}\n\n/* \n** Open a connection to the WAL file zWalName. The database file must \n** already be opened on connection pDbFd. The buffer that zWalName points\n** to must remain valid for the lifetime of the returned Wal* handle.\n**\n** A SHARED lock should be held on the database file when this function\n** is called. The purpose of this SHARED lock is to prevent any other\n** client from unlinking the WAL or wal-index file. If another process\n** were to do this just after this client opened one of these files, the\n** system would be badly broken.\n**\n** If the log file is successfully opened, SQLITE_OK is returned and \n** *ppWal is set to point to a new WAL handle. If an error occurs,\n** an SQLite error code is returned and *ppWal is left unmodified.\n*/\nSQLITE_PRIVATE int sqlite3WalOpen(\n  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */\n  sqlite3_file *pDbFd,            /* The open database file */\n  const char *zWalName,           /* Name of the WAL file */\n  int bNoShm,                     /* True to run in heap-memory mode */\n  i64 mxWalSize,                  /* Truncate WAL to this size on reset */\n  Wal **ppWal                     /* OUT: Allocated Wal handle */\n){\n  int rc;                         /* Return Code */\n  Wal *pRet;                      /* Object to allocate and return */\n  int flags;                      /* Flags passed to OsOpen() */\n\n  assert( zWalName && zWalName[0] );\n  assert( pDbFd );\n\n  /* In the amalgamation, the os_unix.c and os_win.c source files come before\n  ** this source file.  Verify that the #defines of the locking byte offsets\n  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.\n  ** For that matter, if the lock offset ever changes from its initial design\n  ** value of 120, we need to know that so there is an assert() to check it.\n  */\n  assert( 120==WALINDEX_LOCK_OFFSET );\n  assert( 136==WALINDEX_HDR_SIZE );\n#ifdef WIN_SHM_BASE\n  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );\n#endif\n#ifdef UNIX_SHM_BASE\n  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );\n#endif\n\n\n  /* Allocate an instance of struct Wal to return. */\n  *ppWal = 0;\n  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);\n  if( !pRet ){\n    return SQLITE_NOMEM_BKPT;\n  }\n\n  pRet->pVfs = pVfs;\n  pRet->pWalFd = (sqlite3_file *)&pRet[1];\n  pRet->pDbFd = pDbFd;\n  pRet->readLock = -1;\n  pRet->mxWalSize = mxWalSize;\n  pRet->zWalName = zWalName;\n  pRet->syncHeader = 1;\n  pRet->padToSectorBoundary = 1;\n  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);\n\n  /* Open file handle on the write-ahead log file. */\n  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);\n  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);\n  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){\n    pRet->readOnly = WAL_RDONLY;\n  }\n\n  if( rc!=SQLITE_OK ){\n    walIndexClose(pRet, 0);\n    sqlite3OsClose(pRet->pWalFd);\n    sqlite3_free(pRet);\n  }else{\n    int iDC = sqlite3OsDeviceCharacteristics(pDbFd);\n    if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }\n    if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){\n      pRet->padToSectorBoundary = 0;\n    }\n    *ppWal = pRet;\n    WALTRACE((\"WAL%d: opened\\n\", pRet));\n  }\n  return rc;\n}\n\n/*\n** Change the size to which the WAL file is trucated on each reset.\n*/\nSQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){\n  if( pWal ) pWal->mxWalSize = iLimit;\n}\n\n/*\n** Find the smallest page number out of all pages held in the WAL that\n** has not been returned by any prior invocation of this method on the\n** same WalIterator object.   Write into *piFrame the frame index where\n** that page was last written into the WAL.  Write into *piPage the page\n** number.\n**\n** Return 0 on success.  If there are no pages in the WAL with a page\n** number larger than *piPage, then return 1.\n*/\nstatic int walIteratorNext(\n  WalIterator *p,               /* Iterator */\n  u32 *piPage,                  /* OUT: The page number of the next page */\n  u32 *piFrame                  /* OUT: Wal frame index of next page */\n){\n  u32 iMin;                     /* Result pgno must be greater than iMin */\n  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */\n  int i;                        /* For looping through segments */\n\n  iMin = p->iPrior;\n  assert( iMin<0xffffffff );\n  for(i=p->nSegment-1; i>=0; i--){\n    struct WalSegment *pSegment = &p->aSegment[i];\n    while( pSegment->iNext<pSegment->nEntry ){\n      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];\n      if( iPg>iMin ){\n        if( iPg<iRet ){\n          iRet = iPg;\n          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];\n        }\n        break;\n      }\n      pSegment->iNext++;\n    }\n  }\n\n  *piPage = p->iPrior = iRet;\n  return (iRet==0xFFFFFFFF);\n}\n\n/*\n** This function merges two sorted lists into a single sorted list.\n**\n** aLeft[] and aRight[] are arrays of indices.  The sort key is\n** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following\n** is guaranteed for all J<K:\n**\n**        aContent[aLeft[J]] < aContent[aLeft[K]]\n**        aContent[aRight[J]] < aContent[aRight[K]]\n**\n** This routine overwrites aRight[] with a new (probably longer) sequence\n** of indices such that the aRight[] contains every index that appears in\n** either aLeft[] or the old aRight[] and such that the second condition\n** above is still met.\n**\n** The aContent[aLeft[X]] values will be unique for all X.  And the\n** aContent[aRight[X]] values will be unique too.  But there might be\n** one or more combinations of X and Y such that\n**\n**      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]\n**\n** When that happens, omit the aLeft[X] and use the aRight[Y] index.\n*/\nstatic void walMerge(\n  const u32 *aContent,            /* Pages in wal - keys for the sort */\n  ht_slot *aLeft,                 /* IN: Left hand input list */\n  int nLeft,                      /* IN: Elements in array *paLeft */\n  ht_slot **paRight,              /* IN/OUT: Right hand input list */\n  int *pnRight,                   /* IN/OUT: Elements in *paRight */\n  ht_slot *aTmp                   /* Temporary buffer */\n){\n  int iLeft = 0;                  /* Current index in aLeft */\n  int iRight = 0;                 /* Current index in aRight */\n  int iOut = 0;                   /* Current index in output buffer */\n  int nRight = *pnRight;\n  ht_slot *aRight = *paRight;\n\n  assert( nLeft>0 && nRight>0 );\n  while( iRight<nRight || iLeft<nLeft ){\n    ht_slot logpage;\n    Pgno dbpage;\n\n    if( (iLeft<nLeft) \n     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])\n    ){\n      logpage = aLeft[iLeft++];\n    }else{\n      logpage = aRight[iRight++];\n    }\n    dbpage = aContent[logpage];\n\n    aTmp[iOut++] = logpage;\n    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;\n\n    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );\n    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );\n  }\n\n  *paRight = aLeft;\n  *pnRight = iOut;\n  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);\n}\n\n/*\n** Sort the elements in list aList using aContent[] as the sort key.\n** Remove elements with duplicate keys, preferring to keep the\n** larger aList[] values.\n**\n** The aList[] entries are indices into aContent[].  The values in\n** aList[] are to be sorted so that for all J<K:\n**\n**      aContent[aList[J]] < aContent[aList[K]]\n**\n** For any X and Y such that\n**\n**      aContent[aList[X]] == aContent[aList[Y]]\n**\n** Keep the larger of the two values aList[X] and aList[Y] and discard\n** the smaller.\n*/\nstatic void walMergesort(\n  const u32 *aContent,            /* Pages in wal */\n  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */\n  ht_slot *aList,                 /* IN/OUT: List to sort */\n  int *pnList                     /* IN/OUT: Number of elements in aList[] */\n){\n  struct Sublist {\n    int nList;                    /* Number of elements in aList */\n    ht_slot *aList;               /* Pointer to sub-list content */\n  };\n\n  const int nList = *pnList;      /* Size of input list */\n  int nMerge = 0;                 /* Number of elements in list aMerge */\n  ht_slot *aMerge = 0;            /* List to be merged */\n  int iList;                      /* Index into input list */\n  u32 iSub = 0;                   /* Index into aSub array */\n  struct Sublist aSub[13];        /* Array of sub-lists */\n\n  memset(aSub, 0, sizeof(aSub));\n  assert( nList<=HASHTABLE_NPAGE && nList>0 );\n  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );\n\n  for(iList=0; iList<nList; iList++){\n    nMerge = 1;\n    aMerge = &aList[iList];\n    for(iSub=0; iList & (1<<iSub); iSub++){\n      struct Sublist *p;\n      assert( iSub<ArraySize(aSub) );\n      p = &aSub[iSub];\n      assert( p->aList && p->nList<=(1<<iSub) );\n      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );\n      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);\n    }\n    aSub[iSub].aList = aMerge;\n    aSub[iSub].nList = nMerge;\n  }\n\n  for(iSub++; iSub<ArraySize(aSub); iSub++){\n    if( nList & (1<<iSub) ){\n      struct Sublist *p;\n      assert( iSub<ArraySize(aSub) );\n      p = &aSub[iSub];\n      assert( p->nList<=(1<<iSub) );\n      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );\n      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);\n    }\n  }\n  assert( aMerge==aList );\n  *pnList = nMerge;\n\n#ifdef SQLITE_DEBUG\n  {\n    int i;\n    for(i=1; i<*pnList; i++){\n      assert( aContent[aList[i]] > aContent[aList[i-1]] );\n    }\n  }\n#endif\n}\n\n/* \n** Free an iterator allocated by walIteratorInit().\n*/\nstatic void walIteratorFree(WalIterator *p){\n  sqlite3_free(p);\n}\n\n/*\n** Construct a WalInterator object that can be used to loop over all \n** pages in the WAL following frame nBackfill in ascending order. Frames\n** nBackfill or earlier may be included - excluding them is an optimization\n** only. The caller must hold the checkpoint lock.\n**\n** On success, make *pp point to the newly allocated WalInterator object\n** return SQLITE_OK. Otherwise, return an error code. If this routine\n** returns an error, the value of *pp is undefined.\n**\n** The calling routine should invoke walIteratorFree() to destroy the\n** WalIterator object when it has finished with it.\n*/\nstatic int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){\n  WalIterator *p;                 /* Return value */\n  int nSegment;                   /* Number of segments to merge */\n  u32 iLast;                      /* Last frame in log */\n  sqlite3_int64 nByte;            /* Number of bytes to allocate */\n  int i;                          /* Iterator variable */\n  ht_slot *aTmp;                  /* Temp space used by merge-sort */\n  int rc = SQLITE_OK;             /* Return Code */\n\n  /* This routine only runs while holding the checkpoint lock. And\n  ** it only runs if there is actually content in the log (mxFrame>0).\n  */\n  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );\n  iLast = pWal->hdr.mxFrame;\n\n  /* Allocate space for the WalIterator object. */\n  nSegment = walFramePage(iLast) + 1;\n  nByte = sizeof(WalIterator) \n        + (nSegment-1)*sizeof(struct WalSegment)\n        + iLast*sizeof(ht_slot);\n  p = (WalIterator *)sqlite3_malloc64(nByte);\n  if( !p ){\n    return SQLITE_NOMEM_BKPT;\n  }\n  memset(p, 0, nByte);\n  p->nSegment = nSegment;\n\n  /* Allocate temporary space used by the merge-sort routine. This block\n  ** of memory will be freed before this function returns.\n  */\n  aTmp = (ht_slot *)sqlite3_malloc64(\n      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)\n  );\n  if( !aTmp ){\n    rc = SQLITE_NOMEM_BKPT;\n  }\n\n  for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){\n    WalHashLoc sLoc;\n\n    rc = walHashGet(pWal, i, &sLoc);\n    if( rc==SQLITE_OK ){\n      int j;                      /* Counter variable */\n      int nEntry;                 /* Number of entries in this segment */\n      ht_slot *aIndex;            /* Sorted index for this segment */\n\n      sLoc.aPgno++;\n      if( (i+1)==nSegment ){\n        nEntry = (int)(iLast - sLoc.iZero);\n      }else{\n        nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno);\n      }\n      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero];\n      sLoc.iZero++;\n  \n      for(j=0; j<nEntry; j++){\n        aIndex[j] = (ht_slot)j;\n      }\n      walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry);\n      p->aSegment[i].iZero = sLoc.iZero;\n      p->aSegment[i].nEntry = nEntry;\n      p->aSegment[i].aIndex = aIndex;\n      p->aSegment[i].aPgno = (u32 *)sLoc.aPgno;\n    }\n  }\n  sqlite3_free(aTmp);\n\n  if( rc!=SQLITE_OK ){\n    walIteratorFree(p);\n    p = 0;\n  }\n  *pp = p;\n  return rc;\n}\n\n#ifdef SQLITE_ENABLE_SETLK_TIMEOUT\n/*\n** Attempt to enable blocking locks. Blocking locks are enabled only if (a)\n** they are supported by the VFS, and (b) the database handle is configured \n** with a busy-timeout. Return 1 if blocking locks are successfully enabled, \n** or 0 otherwise.\n*/\nstatic int walEnableBlocking(Wal *pWal){\n  int res = 0;\n  if( pWal->db ){\n    int tmout = pWal->db->busyTimeout;\n    if( tmout ){\n      int rc;\n      rc = sqlite3OsFileControl(\n          pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout\n      );\n      res = (rc==SQLITE_OK);\n    }\n  }\n  return res;\n}\n\n/*\n** Disable blocking locks.\n*/\nstatic void walDisableBlocking(Wal *pWal){\n  int tmout = 0;\n  sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout);\n}\n\n/*\n** If parameter bLock is true, attempt to enable blocking locks, take\n** the WRITER lock, and then disable blocking locks. If blocking locks\n** cannot be enabled, no attempt to obtain the WRITER lock is made. Return \n** an SQLite error code if an error occurs, or SQLITE_OK otherwise. It is not\n** an error if blocking locks can not be enabled.\n**\n** If the bLock parameter is false and the WRITER lock is held, release it.\n*/\nSQLITE_PRIVATE int sqlite3WalWriteLock(Wal *pWal, int bLock){\n  int rc = SQLITE_OK;\n  assert( pWal->readLock<0 || bLock==0 );\n  if( bLock ){\n    assert( pWal->db );\n    if( walEnableBlocking(pWal) ){\n      rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);\n      if( rc==SQLITE_OK ){\n        pWal->writeLock = 1;\n      }\n      walDisableBlocking(pWal);\n    }\n  }else if( pWal->writeLock ){\n    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);\n    pWal->writeLock = 0;\n  }\n  return rc;\n}\n\n/*\n** Set the database handle used to determine if blocking locks are required.\n*/\nSQLITE_PRIVATE void sqlite3WalDb(Wal *pWal, sqlite3 *db){\n  pWal->db = db;\n}\n\n/*\n** Take an exclusive WRITE lock. Blocking if so configured.\n*/\nstatic int walLockWriter(Wal *pWal){\n  int rc;\n  walEnableBlocking(pWal);\n  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);\n  walDisableBlocking(pWal);\n  return rc;\n}\n#else\n# define walEnableBlocking(x) 0\n# define walDisableBlocking(x)\n# define walLockWriter(pWal) walLockExclusive((pWal), WAL_WRITE_LOCK, 1)\n# define sqlite3WalDb(pWal, db)\n#endif   /* ifdef SQLITE_ENABLE_SETLK_TIMEOUT */\n\n\n/*\n** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and\n** n. If the attempt fails and parameter xBusy is not NULL, then it is a\n** busy-handler function. Invoke it and retry the lock until either the\n** lock is successfully obtained or the busy-handler returns 0.\n*/\nstatic int walBusyLock(\n  Wal *pWal,                      /* WAL connection */\n  int (*xBusy)(void*),            /* Function to call when busy */\n  void *pBusyArg,                 /* Context argument for xBusyHandler */\n  int lockIdx,                    /* Offset of first byte to lock */\n  int n                           /* Number of bytes to lock */\n){\n  int rc;\n  do {\n    rc = walLockExclusive(pWal, lockIdx, n);\n  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );\n#ifdef SQLITE_ENABLE_SETLK_TIMEOUT\n  if( rc==SQLITE_BUSY_TIMEOUT ){\n    walDisableBlocking(pWal);\n    rc = SQLITE_BUSY;\n  }\n#endif\n  return rc;\n}\n\n/*\n** The cache of the wal-index header must be valid to call this function.\n** Return the page-size in bytes used by the database.\n*/\nstatic int walPagesize(Wal *pWal){\n  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);\n}\n\n/*\n** The following is guaranteed when this function is called:\n**\n**   a) the WRITER lock is held,\n**   b) the entire log file has been checkpointed, and\n**   c) any existing readers are reading exclusively from the database\n**      file - there are no readers that may attempt to read a frame from\n**      the log file.\n**\n** This function updates the shared-memory structures so that the next\n** client to write to the database (which may be this one) does so by\n** writing frames into the start of the log file.\n**\n** The value of parameter salt1 is used as the aSalt[1] value in the \n** new wal-index header. It should be passed a pseudo-random value (i.e. \n** one obtained from sqlite3_randomness()).\n*/\nstatic void walRestartHdr(Wal *pWal, u32 salt1){\n  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);\n  int i;                          /* Loop counter */\n  u32 *aSalt = pWal->hdr.aSalt;   /* Big-endian salt values */\n  pWal->nCkpt++;\n  pWal->hdr.mxFrame = 0;\n  sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));\n  memcpy(&pWal->hdr.aSalt[1], &salt1, 4);\n  walIndexWriteHdr(pWal);\n  AtomicStore(&pInfo->nBackfill, 0);\n  pInfo->nBackfillAttempted = 0;\n  pInfo->aReadMark[1] = 0;\n  for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;\n  assert( pInfo->aReadMark[0]==0 );\n}\n\n/*\n** Copy as much content as we can from the WAL back into the database file\n** in response to an sqlite3_wal_checkpoint() request or the equivalent.\n**\n** The amount of information copies from WAL to database might be limited\n** by active readers.  This routine will never overwrite a database page\n** that a concurrent reader might be using.\n**\n** All I/O barrier operations (a.k.a fsyncs) occur in this routine when\n** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if \n** checkpoints are always run by a background thread or background \n** process, foreground threads will never block on a lengthy fsync call.\n**\n** Fsync is called on the WAL before writing content out of the WAL and\n** into the database.  This ensures that if the new content is persistent\n** in the WAL and can be recovered following a power-loss or hard reset.\n**\n** Fsync is also called on the database file if (and only if) the entire\n** WAL content is copied into the database file.  This second fsync makes\n** it safe to delete the WAL since the new content will persist in the\n** database file.\n**\n** This routine uses and updates the nBackfill field of the wal-index header.\n** This is the only routine that will increase the value of nBackfill.  \n** (A WAL reset or recovery will revert nBackfill to zero, but not increase\n** its value.)\n**\n** The caller must be holding sufficient locks to ensure that no other\n** checkpoint is running (in any other thread or process) at the same\n** time.\n*/\nstatic int walCheckpoint(\n  Wal *pWal,                      /* Wal connection */\n  sqlite3 *db,                    /* Check for interrupts on this handle */\n  int eMode,                      /* One of PASSIVE, FULL or RESTART */\n  int (*xBusy)(void*),            /* Function to call when busy */\n  void *pBusyArg,                 /* Context argument for xBusyHandler */\n  int sync_flags,                 /* Flags for OsSync() (or 0) */\n  u8 *zBuf                        /* Temporary buffer to use */\n){\n  int rc = SQLITE_OK;             /* Return code */\n  int szPage;                     /* Database page-size */\n  WalIterator *pIter = 0;         /* Wal iterator context */\n  u32 iDbpage = 0;                /* Next database page to write */\n  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */\n  u32 mxSafeFrame;                /* Max frame that can be backfilled */\n  u32 mxPage;                     /* Max database page to write */\n  int i;                          /* Loop counter */\n  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */\n\n  szPage = walPagesize(pWal);\n  testcase( szPage<=32768 );\n  testcase( szPage>=65536 );\n  pInfo = walCkptInfo(pWal);\n  if( pInfo->nBackfill<pWal->hdr.mxFrame ){\n\n    /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked\n    ** in the SQLITE_CHECKPOINT_PASSIVE mode. */\n    assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );\n\n    /* Compute in mxSafeFrame the index of the last frame of the WAL that is\n    ** safe to write into the database.  Frames beyond mxSafeFrame might\n    ** overwrite database pages that are in use by active readers and thus\n    ** cannot be backfilled from the WAL.\n    */\n    mxSafeFrame = pWal->hdr.mxFrame;\n    mxPage = pWal->hdr.nPage;\n    for(i=1; i<WAL_NREADER; i++){\n      u32 y = AtomicLoad(pInfo->aReadMark+i);\n      if( mxSafeFrame>y ){\n        assert( y<=pWal->hdr.mxFrame );\n        rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);\n        if( rc==SQLITE_OK ){\n          u32 iMark = (i==1 ? mxSafeFrame : READMARK_NOT_USED);\n          AtomicStore(pInfo->aReadMark+i, iMark);\n          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);\n        }else if( rc==SQLITE_BUSY ){\n          mxSafeFrame = y;\n          xBusy = 0;\n        }else{\n          goto walcheckpoint_out;\n        }\n      }\n    }\n\n    /* Allocate the iterator */\n    if( pInfo->nBackfill<mxSafeFrame ){\n      rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter);\n      assert( rc==SQLITE_OK || pIter==0 );\n    }\n\n    if( pIter\n     && (rc = walBusyLock(pWal,xBusy,pBusyArg,WAL_READ_LOCK(0),1))==SQLITE_OK\n    ){\n      u32 nBackfill = pInfo->nBackfill;\n\n      pInfo->nBackfillAttempted = mxSafeFrame;\n\n      /* Sync the WAL to disk */\n      rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));\n\n      /* If the database may grow as a result of this checkpoint, hint\n      ** about the eventual size of the db file to the VFS layer.\n      */\n      if( rc==SQLITE_OK ){\n        i64 nReq = ((i64)mxPage * szPage);\n        i64 nSize;                    /* Current size of database file */\n        sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_START, 0);\n        rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);\n        if( rc==SQLITE_OK && nSize<nReq ){\n          sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);\n        }\n      }\n\n\n      /* Iterate through the contents of the WAL, copying data to the db file */\n      while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){\n        i64 iOffset;\n        assert( walFramePgno(pWal, iFrame)==iDbpage );\n        if( AtomicLoad(&db->u1.isInterrupted) ){\n          rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;\n          break;\n        }\n        if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){\n          continue;\n        }\n        iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;\n        /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */\n        rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);\n        if( rc!=SQLITE_OK ) break;\n        iOffset = (iDbpage-1)*(i64)szPage;\n        testcase( IS_BIG_INT(iOffset) );\n        rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);\n        if( rc!=SQLITE_OK ) break;\n      }\n      sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE, 0);\n\n      /* If work was actually accomplished... */\n      if( rc==SQLITE_OK ){\n        if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){\n          i64 szDb = pWal->hdr.nPage*(i64)szPage;\n          testcase( IS_BIG_INT(szDb) );\n          rc = sqlite3OsTruncate(pWal->pDbFd, szDb);\n          if( rc==SQLITE_OK ){\n            rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));\n          }\n        }\n        if( rc==SQLITE_OK ){\n          AtomicStore(&pInfo->nBackfill, mxSafeFrame);\n        }\n      }\n\n      /* Release the reader lock held while backfilling */\n      walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);\n    }\n\n    if( rc==SQLITE_BUSY ){\n      /* Reset the return code so as not to report a checkpoint failure\n      ** just because there are active readers.  */\n      rc = SQLITE_OK;\n    }\n  }\n\n  /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the\n  ** entire wal file has been copied into the database file, then block \n  ** until all readers have finished using the wal file. This ensures that \n  ** the next process to write to the database restarts the wal file.\n  */\n  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){\n    assert( pWal->writeLock );\n    if( pInfo->nBackfill<pWal->hdr.mxFrame ){\n      rc = SQLITE_BUSY;\n    }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){\n      u32 salt1;\n      sqlite3_randomness(4, &salt1);\n      assert( pInfo->nBackfill==pWal->hdr.mxFrame );\n      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);\n      if( rc==SQLITE_OK ){\n        if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){\n          /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as\n          ** SQLITE_CHECKPOINT_RESTART with the addition that it also\n          ** truncates the log file to zero bytes just prior to a\n          ** successful return.\n          **\n          ** In theory, it might be safe to do this without updating the\n          ** wal-index header in shared memory, as all subsequent reader or\n          ** writer clients should see that the entire log file has been\n          ** checkpointed and behave accordingly. This seems unsafe though,\n          ** as it would leave the system in a state where the contents of\n          ** the wal-index header do not match the contents of the \n          ** file-system. To avoid this, update the wal-index header to\n          ** indicate that the log file contains zero valid frames.  */\n          walRestartHdr(pWal, salt1);\n          rc = sqlite3OsTruncate(pWal->pWalFd, 0);\n        }\n        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);\n      }\n    }\n  }\n\n walcheckpoint_out:\n  walIteratorFree(pIter);\n  return rc;\n}\n\n/*\n** If the WAL file is currently larger than nMax bytes in size, truncate\n** it to exactly nMax bytes. If an error occurs while doing so, ignore it.\n*/\nstatic void walLimitSize(Wal *pWal, i64 nMax){\n  i64 sz;\n  int rx;\n  sqlite3BeginBenignMalloc();\n  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);\n  if( rx==SQLITE_OK && (sz > nMax ) ){\n    rx = sqlite3OsTruncate(pWal->pWalFd, nMax);\n  }\n  sqlite3EndBenignMalloc();\n  if( rx ){\n    sqlite3_log(rx, \"cannot limit WAL size: %s\", pWal->zWalName);\n  }\n}\n\n/*\n** Close a connection to a log file.\n*/\nSQLITE_PRIVATE int sqlite3WalClose(\n  Wal *pWal,                      /* Wal to close */\n  sqlite3 *db,                    /* For interrupt flag */\n  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */\n  int nBuf,\n  u8 *zBuf                        /* Buffer of at least nBuf bytes */\n){\n  int rc = SQLITE_OK;\n  if( pWal ){\n    int isDelete = 0;             /* True to unlink wal and wal-index files */\n\n    /* If an EXCLUSIVE lock can be obtained on the database file (using the\n    ** ordinary, rollback-mode locking methods, this guarantees that the\n    ** connection associated with this log file is the only connection to\n    ** the database. In this case checkpoint the database and unlink both\n    ** the wal and wal-index files.\n    **\n    ** The EXCLUSIVE lock is not released before returning.\n    */\n    if( zBuf!=0\n     && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))\n    ){\n      if( pWal->exclusiveMode==WAL_NORMAL_MODE ){\n        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;\n      }\n      rc = sqlite3WalCheckpoint(pWal, db, \n          SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0\n      );\n      if( rc==SQLITE_OK ){\n        int bPersist = -1;\n        sqlite3OsFileControlHint(\n            pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist\n        );\n        if( bPersist!=1 ){\n          /* Try to delete the WAL file if the checkpoint completed and\n          ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal\n          ** mode (!bPersist) */\n          isDelete = 1;\n        }else if( pWal->mxWalSize>=0 ){\n          /* Try to truncate the WAL file to zero bytes if the checkpoint\n          ** completed and fsynced (rc==SQLITE_OK) and we are in persistent\n          ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a\n          ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate\n          ** to zero bytes as truncating to the journal_size_limit might\n          ** leave a corrupt WAL file on disk. */\n          walLimitSize(pWal, 0);\n        }\n      }\n    }\n\n    walIndexClose(pWal, isDelete);\n    sqlite3OsClose(pWal->pWalFd);\n    if( isDelete ){\n      sqlite3BeginBenignMalloc();\n      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);\n      sqlite3EndBenignMalloc();\n    }\n    WALTRACE((\"WAL%p: closed\\n\", pWal));\n    sqlite3_free((void *)pWal->apWiData);\n    sqlite3_free(pWal);\n  }\n  return rc;\n}\n\n/*\n** Try to read the wal-index header.  Return 0 on success and 1 if\n** there is a problem.\n**\n** The wal-index is in shared memory.  Another thread or process might\n** be writing the header at the same time this procedure is trying to\n** read it, which might result in inconsistency.  A dirty read is detected\n** by verifying that both copies of the header are the same and also by\n** a checksum on the header.\n**\n** If and only if the read is consistent and the header is different from\n** pWal->hdr, then pWal->hdr is updated to the content of the new header\n** and *pChanged is set to 1.\n**\n** If the checksum cannot be verified return non-zero. If the header\n** is read successfully and the checksum verified, return zero.\n*/\nstatic SQLITE_NO_TSAN int walIndexTryHdr(Wal *pWal, int *pChanged){\n  u32 aCksum[2];                  /* Checksum on the header content */\n  WalIndexHdr h1, h2;             /* Two copies of the header content */\n  WalIndexHdr volatile *aHdr;     /* Header in shared memory */\n\n  /* The first page of the wal-index must be mapped at this point. */\n  assert( pWal->nWiData>0 && pWal->apWiData[0] );\n\n  /* Read the header. This might happen concurrently with a write to the\n  ** same area of shared memory on a different CPU in a SMP,\n  ** meaning it is possible that an inconsistent snapshot is read\n  ** from the file. If this happens, return non-zero.\n  **\n  ** tag-20200519-1:\n  ** There are two copies of the header at the beginning of the wal-index.\n  ** When reading, read [0] first then [1].  Writes are in the reverse order.\n  ** Memory barriers are used to prevent the compiler or the hardware from\n  ** reordering the reads and writes.  TSAN and similar tools can sometimes\n  ** give false-positive warnings about these accesses because the tools do not\n  ** account for the double-read and the memory barrier. The use of mutexes\n  ** here would be problematic as the memory being accessed is potentially\n  ** shared among multiple processes and not all mutex implementions work\n  ** reliably in that environment.\n  */\n  aHdr = walIndexHdr(pWal);\n  memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); /* Possible TSAN false-positive */\n  walShmBarrier(pWal);\n  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));\n\n  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){\n    return 1;   /* Dirty read */\n  }  \n  if( h1.isInit==0 ){\n    return 1;   /* Malformed header - probably all zeros */\n  }\n  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);\n  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){\n    return 1;   /* Checksum does not match */\n  }\n\n  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){\n    *pChanged = 1;\n    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));\n    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);\n    testcase( pWal->szPage<=32768 );\n    testcase( pWal->szPage>=65536 );\n  }\n\n  /* The header was successfully read. Return zero. */\n  return 0;\n}\n\n/*\n** This is the value that walTryBeginRead returns when it needs to\n** be retried.\n*/\n#define WAL_RETRY  (-1)\n\n/*\n** Read the wal-index header from the wal-index and into pWal->hdr.\n** If the wal-header appears to be corrupt, try to reconstruct the\n** wal-index from the WAL before returning.\n**\n** Set *pChanged to 1 if the wal-index header value in pWal->hdr is\n** changed by this operation.  If pWal->hdr is unchanged, set *pChanged\n** to 0.\n**\n** If the wal-index header is successfully read, return SQLITE_OK. \n** Otherwise an SQLite error code.\n*/\nstatic int walIndexReadHdr(Wal *pWal, int *pChanged){\n  int rc;                         /* Return code */\n  int badHdr;                     /* True if a header read failed */\n  volatile u32 *page0;            /* Chunk of wal-index containing header */\n\n  /* Ensure that page 0 of the wal-index (the page that contains the \n  ** wal-index header) is mapped. Return early if an error occurs here.\n  */\n  assert( pChanged );\n  rc = walIndexPage(pWal, 0, &page0);\n  if( rc!=SQLITE_OK ){\n    assert( rc!=SQLITE_READONLY ); /* READONLY changed to OK in walIndexPage */\n    if( rc==SQLITE_READONLY_CANTINIT ){\n      /* The SQLITE_READONLY_CANTINIT return means that the shared-memory\n      ** was openable but is not writable, and this thread is unable to\n      ** confirm that another write-capable connection has the shared-memory\n      ** open, and hence the content of the shared-memory is unreliable,\n      ** since the shared-memory might be inconsistent with the WAL file\n      ** and there is no writer on hand to fix it. */\n      assert( page0==0 );\n      assert( pWal->writeLock==0 );\n      assert( pWal->readOnly & WAL_SHM_RDONLY );\n      pWal->bShmUnreliable = 1;\n      pWal->exclusiveMode = WAL_HEAPMEMORY_MODE;\n      *pChanged = 1;\n    }else{\n      return rc; /* Any other non-OK return is just an error */\n    }\n  }else{\n    /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock\n    ** is zero, which prevents the SHM from growing */\n    testcase( page0!=0 );\n  }\n  assert( page0!=0 || pWal->writeLock==0 );\n\n  /* If the first page of the wal-index has been mapped, try to read the\n  ** wal-index header immediately, without holding any lock. This usually\n  ** works, but may fail if the wal-index header is corrupt or currently \n  ** being modified by another thread or process.\n  */\n  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);\n\n  /* If the first attempt failed, it might have been due to a race\n  ** with a writer.  So get a WRITE lock and try again.\n  */\n  if( badHdr ){\n    if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){\n      if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){\n        walUnlockShared(pWal, WAL_WRITE_LOCK);\n        rc = SQLITE_READONLY_RECOVERY;\n      }\n    }else{\n      int bWriteLock = pWal->writeLock;\n      if( bWriteLock || SQLITE_OK==(rc = walLockWriter(pWal)) ){\n        pWal->writeLock = 1;\n        if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){\n          badHdr = walIndexTryHdr(pWal, pChanged);\n          if( badHdr ){\n            /* If the wal-index header is still malformed even while holding\n            ** a WRITE lock, it can only mean that the header is corrupted and\n            ** needs to be reconstructed.  So run recovery to do exactly that.\n            */\n            rc = walIndexRecover(pWal);\n            *pChanged = 1;\n          }\n        }\n        if( bWriteLock==0 ){\n          pWal->writeLock = 0;\n          walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);\n        }\n      }\n    }\n  }\n\n  /* If the header is read successfully, check the version number to make\n  ** sure the wal-index was not constructed with some future format that\n  ** this version of SQLite cannot understand.\n  */\n  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){\n    rc = SQLITE_CANTOPEN_BKPT;\n  }\n  if( pWal->bShmUnreliable ){\n    if( rc!=SQLITE_OK ){\n      walIndexClose(pWal, 0);\n      pWal->bShmUnreliable = 0;\n      assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );\n      /* walIndexRecover() might have returned SHORT_READ if a concurrent\n      ** writer truncated the WAL out from under it.  If that happens, it\n      ** indicates that a writer has fixed the SHM file for us, so retry */\n      if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY;\n    }\n    pWal->exclusiveMode = WAL_NORMAL_MODE;\n  }\n\n  return rc;\n}\n\n/*\n** Open a transaction in a connection where the shared-memory is read-only\n** and where we cannot verify that there is a separate write-capable connection\n** on hand to keep the shared-memory up-to-date with the WAL file.\n**\n** This can happen, for example, when the shared-memory is implemented by\n** memory-mapping a *-shm file, where a prior writer has shut down and\n** left the *-shm file on disk, and now the present connection is trying\n** to use that database but lacks write permission on the *-shm file.\n** Other scenarios are also possible, depending on the VFS implementation.\n**\n** Precondition:\n**\n**    The *-wal file has been read and an appropriate wal-index has been\n**    constructed in pWal->apWiData[] using heap memory instead of shared\n**    memory. \n**\n** If this function returns SQLITE_OK, then the read transaction has\n** been successfully opened. In this case output variable (*pChanged) \n** is set to true before returning if the caller should discard the\n** contents of the page cache before proceeding. Or, if it returns \n** WAL_RETRY, then the heap memory wal-index has been discarded and \n** the caller should retry opening the read transaction from the \n** beginning (including attempting to map the *-shm file). \n**\n** If an error occurs, an SQLite error code is returned.\n*/\nstatic int walBeginShmUnreliable(Wal *pWal, int *pChanged){\n  i64 szWal;                      /* Size of wal file on disk in bytes */\n  i64 iOffset;                    /* Current offset when reading wal file */\n  u8 aBuf[WAL_HDRSIZE];           /* Buffer to load WAL header into */\n  u8 *aFrame = 0;                 /* Malloc'd buffer to load entire frame */\n  int szFrame;                    /* Number of bytes in buffer aFrame[] */\n  u8 *aData;                      /* Pointer to data part of aFrame buffer */\n  volatile void *pDummy;          /* Dummy argument for xShmMap */\n  int rc;                         /* Return code */\n  u32 aSaveCksum[2];              /* Saved copy of pWal->hdr.aFrameCksum */\n\n  assert( pWal->bShmUnreliable );\n  assert( pWal->readOnly & WAL_SHM_RDONLY );\n  assert( pWal->nWiData>0 && pWal->apWiData[0] );\n\n  /* Take WAL_READ_LOCK(0). This has the effect of preventing any\n  ** writers from running a checkpoint, but does not stop them\n  ** from running recovery.  */\n  rc = walLockShared(pWal, WAL_READ_LOCK(0));\n  if( rc!=SQLITE_OK ){\n    if( rc==SQLITE_BUSY ) rc = WAL_RETRY;\n    goto begin_unreliable_shm_out;\n  }\n  pWal->readLock = 0;\n\n  /* Check to see if a separate writer has attached to the shared-memory area,\n  ** thus making the shared-memory \"reliable\" again.  Do this by invoking\n  ** the xShmMap() routine of the VFS and looking to see if the return\n  ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT.\n  **\n  ** If the shared-memory is now \"reliable\" return WAL_RETRY, which will\n  ** cause the heap-memory WAL-index to be discarded and the actual\n  ** shared memory to be used in its place.\n  **\n  ** This step is important because, even though this connection is holding\n  ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might\n  ** have already checkpointed the WAL file and, while the current\n  ** is active, wrap the WAL and start overwriting frames that this\n  ** process wants to use.\n  **\n  ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has\n  ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY\n  ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,\n  ** even if some external agent does a \"chmod\" to make the shared-memory\n  ** writable by us, until sqlite3OsShmUnmap() has been called.\n  ** This is a requirement on the VFS implementation.\n   */\n  rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);\n  assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */\n  if( rc!=SQLITE_READONLY_CANTINIT ){\n    rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc);\n    goto begin_unreliable_shm_out;\n  }\n\n  /* We reach this point only if the real shared-memory is still unreliable.\n  ** Assume the in-memory WAL-index substitute is correct and load it\n  ** into pWal->hdr.\n  */\n  memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));\n\n  /* Make sure some writer hasn't come in and changed the WAL file out\n  ** from under us, then disconnected, while we were not looking.\n  */\n  rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);\n  if( rc!=SQLITE_OK ){\n    goto begin_unreliable_shm_out;\n  }\n  if( szWal<WAL_HDRSIZE ){\n    /* If the wal file is too small to contain a wal-header and the\n    ** wal-index header has mxFrame==0, then it must be safe to proceed\n    ** reading the database file only. However, the page cache cannot\n    ** be trusted, as a read/write connection may have connected, written\n    ** the db, run a checkpoint, truncated the wal file and disconnected\n    ** since this client's last read transaction.  */\n    *pChanged = 1;\n    rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);\n    goto begin_unreliable_shm_out;\n  }\n\n  /* Check the salt keys at the start of the wal file still match. */\n  rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);\n  if( rc!=SQLITE_OK ){\n    goto begin_unreliable_shm_out;\n  }\n  if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){\n    /* Some writer has wrapped the WAL file while we were not looking.\n    ** Return WAL_RETRY which will cause the in-memory WAL-index to be\n    ** rebuilt. */\n    rc = WAL_RETRY;\n    goto begin_unreliable_shm_out;\n  }\n\n  /* Allocate a buffer to read frames into */\n  szFrame = pWal->hdr.szPage + WAL_FRAME_HDRSIZE;\n  aFrame = (u8 *)sqlite3_malloc64(szFrame);\n  if( aFrame==0 ){\n    rc = SQLITE_NOMEM_BKPT;\n    goto begin_unreliable_shm_out;\n  }\n  aData = &aFrame[WAL_FRAME_HDRSIZE];\n\n  /* Check to see if a complete transaction has been appended to the\n  ** wal file since the heap-memory wal-index was created. If so, the\n  ** heap-memory wal-index is discarded and WAL_RETRY returned to\n  ** the caller.  */\n  aSaveCksum[0] = pWal->hdr.aFrameCksum[0];\n  aSaveCksum[1] = pWal->hdr.aFrameCksum[1];\n  for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->hdr.szPage); \n      iOffset+szFrame<=szWal; \n      iOffset+=szFrame\n  ){\n    u32 pgno;                   /* Database page number for frame */\n    u32 nTruncate;              /* dbsize field from frame header */\n\n    /* Read and decode the next log frame. */\n    rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);\n    if( rc!=SQLITE_OK ) break;\n    if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break;\n\n    /* If nTruncate is non-zero, then a complete transaction has been\n    ** appended to this wal file. Set rc to WAL_RETRY and break out of\n    ** the loop.  */\n    if( nTruncate ){\n      rc = WAL_RETRY;\n      break;\n    }\n  }\n  pWal->hdr.aFrameCksum[0] = aSaveCksum[0];\n  pWal->hdr.aFrameCksum[1] = aSaveCksum[1];\n\n begin_unreliable_shm_out:\n  sqlite3_free(aFrame);\n  if( rc!=SQLITE_OK ){\n    int i;\n    for(i=0; i<pWal->nWiData; i++){\n      sqlite3_free((void*)pWal->apWiData[i]);\n      pWal->apWiData[i] = 0;\n    }\n    pWal->bShmUnreliable = 0;\n    sqlite3WalEndReadTransaction(pWal);\n    *pChanged = 1;\n  }\n  return rc;\n}\n\n/*\n** Attempt to start a read transaction.  This might fail due to a race or\n** other transient condition.  When that happens, it returns WAL_RETRY to\n** indicate to the caller that it is safe to retry immediately.\n**\n** On success return SQLITE_OK.  On a permanent failure (such an\n** I/O error or an SQLITE_BUSY because another process is running\n** recovery) return a positive error code.\n**\n** The useWal parameter is true to force the use of the WAL and disable\n** the case where the WAL is bypassed because it has been completely\n** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() \n** to make a copy of the wal-index header into pWal->hdr.  If the \n** wal-index header has changed, *pChanged is set to 1 (as an indication \n** to the caller that the local page cache is obsolete and needs to be \n** flushed.)  When useWal==1, the wal-index header is assumed to already\n** be loaded and the pChanged parameter is unused.\n**\n** The caller must set the cnt parameter to the number of prior calls to\n** this routine during the current read attempt that returned WAL_RETRY.\n** This routine will start taking more aggressive measures to clear the\n** race conditions after multiple WAL_RETRY returns, and after an excessive\n** number of errors will ultimately return SQLITE_PROTOCOL.  The\n** SQLITE_PROTOCOL return indicates that some other process has gone rogue\n** and is not honoring the locking protocol.  There is a vanishingly small\n** chance that SQLITE_PROTOCOL could be returned because of a run of really\n** bad luck when there is lots of contention for the wal-index, but that\n** possibility is so small that it can be safely neglected, we believe.\n**\n** On success, this routine obtains a read lock on \n** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is\n** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)\n** that means the Wal does not hold any read lock.  The reader must not\n** access any database page that is modified by a WAL frame up to and\n** including frame number aReadMark[pWal->readLock].  The reader will\n** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0\n** Or if pWal->readLock==0, then the reader will ignore the WAL\n** completely and get all content directly from the database file.\n** If the useWal parameter is 1 then the WAL will never be ignored and\n** this routine will always set pWal->readLock>0 on success.\n** When the read transaction is completed, the caller must release the\n** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.\n**\n** This routine uses the nBackfill and aReadMark[] fields of the header\n** to select a particular WAL_READ_LOCK() that strives to let the\n** checkpoint process do as much work as possible.  This routine might\n** update values of the aReadMark[] array in the header, but if it does\n** so it takes care to hold an exclusive lock on the corresponding\n** WAL_READ_LOCK() while changing values.\n*/\nstatic int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){\n  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */\n  u32 mxReadMark;                 /* Largest aReadMark[] value */\n  int mxI;                        /* Index of largest aReadMark[] value */\n  int i;                          /* Loop counter */\n  int rc = SQLITE_OK;             /* Return code  */\n  u32 mxFrame;                    /* Wal frame to lock to */\n\n  assert( pWal->readLock<0 );     /* Not currently locked */\n\n  /* useWal may only be set for read/write connections */\n  assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );\n\n  /* Take steps to avoid spinning forever if there is a protocol error.\n  **\n  ** Circumstances that cause a RETRY should only last for the briefest\n  ** instances of time.  No I/O or other system calls are done while the\n  ** locks are held, so the locks should not be held for very long. But \n  ** if we are unlucky, another process that is holding a lock might get\n  ** paged out or take a page-fault that is time-consuming to resolve, \n  ** during the few nanoseconds that it is holding the lock.  In that case,\n  ** it might take longer than normal for the lock to free.\n  **\n  ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few\n  ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this\n  ** is more of a scheduler yield than an actual delay.  But on the 10th\n  ** an subsequent retries, the delays start becoming longer and longer, \n  ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.\n  ** The total delay time before giving up is less than 10 seconds.\n  */\n  if( cnt>5 ){\n    int nDelay = 1;                      /* Pause time in microseconds */\n    if( cnt>100 ){\n      VVA_ONLY( pWal->lockError = 1; )\n      return SQLITE_PROTOCOL;\n    }\n    if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;\n    sqlite3OsSleep(pWal->pVfs, nDelay);\n  }\n\n  if( !useWal ){\n    assert( rc==SQLITE_OK );\n    if( pWal->bShmUnreliable==0 ){\n      rc = walIndexReadHdr(pWal, pChanged);\n    }\n    if( rc==SQLITE_BUSY ){\n      /* If there is not a recovery running in another thread or process\n      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to\n      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here\n      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY\n      ** would be technically correct.  But the race is benign since with\n      ** WAL_RETRY this routine will be called again and will probably be\n      ** right on the second iteration.\n      */\n      if( pWal->apWiData[0]==0 ){\n        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.\n        ** We assume this is a transient condition, so return WAL_RETRY. The\n        ** xShmMap() implementation used by the default unix and win32 VFS \n        ** modules may return SQLITE_BUSY due to a race condition in the \n        ** code that determines whether or not the shared-memory region \n        ** must be zeroed before the requested page is returned.\n        */\n        rc = WAL_RETRY;\n      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){\n        walUnlockShared(pWal, WAL_RECOVER_LOCK);\n        rc = WAL_RETRY;\n      }else if( rc==SQLITE_BUSY ){\n        rc = SQLITE_BUSY_RECOVERY;\n      }\n    }\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    else if( pWal->bShmUnreliable ){\n      return walBeginShmUnreliable(pWal, pChanged);\n    }\n  }\n\n  assert( pWal->nWiData>0 );\n  assert( pWal->apWiData[0]!=0 );\n  pInfo = walCkptInfo(pWal);\n  if( !useWal && AtomicLoad(&pInfo->nBackfill)==pWal->hdr.mxFrame\n#ifdef SQLITE_ENABLE_SNAPSHOT\n   && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)\n#endif\n  ){\n    /* The WAL has been completely backfilled (or it is empty).\n    ** and can be safely ignored.\n    */\n    rc = walLockShared(pWal, WAL_READ_LOCK(0));\n    walShmBarrier(pWal);\n    if( rc==SQLITE_OK ){\n      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){\n        /* It is not safe to allow the reader to continue here if frames\n        ** may have been appended to the log before READ_LOCK(0) was obtained.\n        ** When holding READ_LOCK(0), the reader ignores the entire log file,\n        ** which implies that the database file contains a trustworthy\n        ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from\n        ** happening, this is usually correct.\n        **\n        ** However, if frames have been appended to the log (or if the log \n        ** is wrapped and written for that matter) before the READ_LOCK(0)\n        ** is obtained, that is not necessarily true. A checkpointer may\n        ** have started to backfill the appended frames but crashed before\n        ** it finished. Leaving a corrupt image in the database file.\n        */\n        walUnlockShared(pWal, WAL_READ_LOCK(0));\n        return WAL_RETRY;\n      }\n      pWal->readLock = 0;\n      return SQLITE_OK;\n    }else if( rc!=SQLITE_BUSY ){\n      return rc;\n    }\n  }\n\n  /* If we get this far, it means that the reader will want to use\n  ** the WAL to get at content from recent commits.  The job now is\n  ** to select one of the aReadMark[] entries that is closest to\n  ** but not exceeding pWal->hdr.mxFrame and lock that entry.\n  */\n  mxReadMark = 0;\n  mxI = 0;\n  mxFrame = pWal->hdr.mxFrame;\n#ifdef SQLITE_ENABLE_SNAPSHOT\n  if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){\n    mxFrame = pWal->pSnapshot->mxFrame;\n  }\n#endif\n  for(i=1; i<WAL_NREADER; i++){\n    u32 thisMark = AtomicLoad(pInfo->aReadMark+i);\n    if( mxReadMark<=thisMark && thisMark<=mxFrame ){\n      assert( thisMark!=READMARK_NOT_USED );\n      mxReadMark = thisMark;\n      mxI = i;\n    }\n  }\n  if( (pWal->readOnly & WAL_SHM_RDONLY)==0\n   && (mxReadMark<mxFrame || mxI==0)\n  ){\n    for(i=1; i<WAL_NREADER; i++){\n      rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);\n      if( rc==SQLITE_OK ){\n        AtomicStore(pInfo->aReadMark+i,mxFrame);\n        mxReadMark = mxFrame;\n        mxI = i;\n        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);\n        break;\n      }else if( rc!=SQLITE_BUSY ){\n        return rc;\n      }\n    }\n  }\n  if( mxI==0 ){\n    assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );\n    return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;\n  }\n\n  rc = walLockShared(pWal, WAL_READ_LOCK(mxI));\n  if( rc ){\n    return rc==SQLITE_BUSY ? WAL_RETRY : rc;\n  }\n  /* Now that the read-lock has been obtained, check that neither the\n  ** value in the aReadMark[] array or the contents of the wal-index\n  ** header have changed.\n  **\n  ** It is necessary to check that the wal-index header did not change\n  ** between the time it was read and when the shared-lock was obtained\n  ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility\n  ** that the log file may have been wrapped by a writer, or that frames\n  ** that occur later in the log than pWal->hdr.mxFrame may have been\n  ** copied into the database by a checkpointer. If either of these things\n  ** happened, then reading the database with the current value of\n  ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry\n  ** instead.\n  **\n  ** Before checking that the live wal-index header has not changed\n  ** since it was read, set Wal.minFrame to the first frame in the wal\n  ** file that has not yet been checkpointed. This client will not need\n  ** to read any frames earlier than minFrame from the wal file - they\n  ** can be safely read directly from the database file.\n  **\n  ** Because a ShmBarrier() call is made between taking the copy of \n  ** nBackfill and checking that the wal-header in shared-memory still\n  ** matches the one cached in pWal->hdr, it is guaranteed that the \n  ** checkpointer that set nBackfill was not working with a wal-index\n  ** header newer than that cached in pWal->hdr. If it were, that could\n  ** cause a problem. The checkpointer could omit to checkpoint\n  ** a version of page X that lies before pWal->minFrame (call that version\n  ** A) on the basis that there is a newer version (version B) of the same\n  ** page later in the wal file. But if version B happens to like past\n  ** frame pWal->hdr.mxFrame - then the client would incorrectly assume\n  ** that it can read version A from the database file. However, since\n  ** we can guarantee that the checkpointer that set nBackfill could not\n  ** see any pages past pWal->hdr.mxFrame, this problem does not come up.\n  */\n  pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1;\n  walShmBarrier(pWal);\n  if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark\n   || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))\n  ){\n    walUnlockShared(pWal, WAL_READ_LOCK(mxI));\n    return WAL_RETRY;\n  }else{\n    assert( mxReadMark<=pWal->hdr.mxFrame );\n    pWal->readLock = (i16)mxI;\n  }\n  return rc;\n}\n\n#ifdef SQLITE_ENABLE_SNAPSHOT\n/*\n** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted \n** variable so that older snapshots can be accessed. To do this, loop\n** through all wal frames from nBackfillAttempted to (nBackfill+1), \n** comparing their content to the corresponding page with the database\n** file, if any. Set nBackfillAttempted to the frame number of the\n** first frame for which the wal file content matches the db file.\n**\n** This is only really safe if the file-system is such that any page \n** writes made by earlier checkpointers were atomic operations, which \n** is not always true. It is also possible that nBackfillAttempted\n** may be left set to a value larger than expected, if a wal frame\n** contains content that duplicate of an earlier version of the same\n** page.\n**\n** SQLITE_OK is returned if successful, or an SQLite error code if an\n** error occurs. It is not an error if nBackfillAttempted cannot be\n** decreased at all.\n*/\nSQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){\n  int rc;\n\n  assert( pWal->readLock>=0 );\n  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);\n  if( rc==SQLITE_OK ){\n    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);\n    int szPage = (int)pWal->szPage;\n    i64 szDb;                   /* Size of db file in bytes */\n\n    rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);\n    if( rc==SQLITE_OK ){\n      void *pBuf1 = sqlite3_malloc(szPage);\n      void *pBuf2 = sqlite3_malloc(szPage);\n      if( pBuf1==0 || pBuf2==0 ){\n        rc = SQLITE_NOMEM;\n      }else{\n        u32 i = pInfo->nBackfillAttempted;\n        for(i=pInfo->nBackfillAttempted; i>AtomicLoad(&pInfo->nBackfill); i--){\n          WalHashLoc sLoc;          /* Hash table location */\n          u32 pgno;                 /* Page number in db file */\n          i64 iDbOff;               /* Offset of db file entry */\n          i64 iWalOff;              /* Offset of wal file entry */\n\n          rc = walHashGet(pWal, walFramePage(i), &sLoc);\n          if( rc!=SQLITE_OK ) break;\n          pgno = sLoc.aPgno[i-sLoc.iZero];\n          iDbOff = (i64)(pgno-1) * szPage;\n\n          if( iDbOff+szPage<=szDb ){\n            iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;\n            rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);\n\n            if( rc==SQLITE_OK ){\n              rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);\n            }\n\n            if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){\n              break;\n            }\n          }\n\n          pInfo->nBackfillAttempted = i-1;\n        }\n      }\n\n      sqlite3_free(pBuf1);\n      sqlite3_free(pBuf2);\n    }\n    walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);\n  }\n\n  return rc;\n}\n#endif /* SQLITE_ENABLE_SNAPSHOT */\n\n/*\n** Begin a read transaction on the database.\n**\n** This routine used to be called sqlite3OpenSnapshot() and with good reason:\n** it takes a snapshot of the state of the WAL and wal-index for the current\n** instant in time.  The current thread will continue to use this snapshot.\n** Other threads might append new content to the WAL and wal-index but\n** that extra content is ignored by the current thread.\n**\n** If the database contents have changes since the previous read\n** transaction, then *pChanged is set to 1 before returning.  The\n** Pager layer will use this to know that its cache is stale and\n** needs to be flushed.\n*/\nSQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){\n  int rc;                         /* Return code */\n  int cnt = 0;                    /* Number of TryBeginRead attempts */\n#ifdef SQLITE_ENABLE_SNAPSHOT\n  int bChanged = 0;\n  WalIndexHdr *pSnapshot = pWal->pSnapshot;\n#endif\n\n  assert( pWal->ckptLock==0 );\n\n#ifdef SQLITE_ENABLE_SNAPSHOT\n  if( pSnapshot ){\n    if( memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){\n      bChanged = 1;\n    }\n\n    /* It is possible that there is a checkpointer thread running \n    ** concurrent with this code. If this is the case, it may be that the\n    ** checkpointer has already determined that it will checkpoint \n    ** snapshot X, where X is later in the wal file than pSnapshot, but \n    ** has not yet set the pInfo->nBackfillAttempted variable to indicate \n    ** its intent. To avoid the race condition this leads to, ensure that\n    ** there is no checkpointer process by taking a shared CKPT lock \n    ** before checking pInfo->nBackfillAttempted.  */\n    (void)walEnableBlocking(pWal);\n    rc = walLockShared(pWal, WAL_CKPT_LOCK);\n    walDisableBlocking(pWal);\n\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    pWal->ckptLock = 1;\n  }\n#endif\n\n  do{\n    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);\n  }while( rc==WAL_RETRY );\n  testcase( (rc&0xff)==SQLITE_BUSY );\n  testcase( (rc&0xff)==SQLITE_IOERR );\n  testcase( rc==SQLITE_PROTOCOL );\n  testcase( rc==SQLITE_OK );\n\n#ifdef SQLITE_ENABLE_SNAPSHOT\n  if( rc==SQLITE_OK ){\n    if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){\n      /* At this point the client has a lock on an aReadMark[] slot holding\n      ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr\n      ** is populated with the wal-index header corresponding to the head\n      ** of the wal file. Verify that pSnapshot is still valid before\n      ** continuing.  Reasons why pSnapshot might no longer be valid:\n      **\n      **    (1)  The WAL file has been reset since the snapshot was taken.\n      **         In this case, the salt will have changed.\n      **\n      **    (2)  A checkpoint as been attempted that wrote frames past\n      **         pSnapshot->mxFrame into the database file.  Note that the\n      **         checkpoint need not have completed for this to cause problems.\n      */\n      volatile WalCkptInfo *pInfo = walCkptInfo(pWal);\n\n      assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );\n      assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );\n\n      /* Check that the wal file has not been wrapped. Assuming that it has\n      ** not, also check that no checkpointer has attempted to checkpoint any\n      ** frames beyond pSnapshot->mxFrame. If either of these conditions are\n      ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr\n      ** with *pSnapshot and set *pChanged as appropriate for opening the\n      ** snapshot.  */\n      if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))\n       && pSnapshot->mxFrame>=pInfo->nBackfillAttempted\n      ){\n        assert( pWal->readLock>0 );\n        memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));\n        *pChanged = bChanged;\n      }else{\n        rc = SQLITE_ERROR_SNAPSHOT;\n      }\n\n      /* A client using a non-current snapshot may not ignore any frames\n      ** from the start of the wal file. This is because, for a system\n      ** where (minFrame < iSnapshot < maxFrame), a checkpointer may\n      ** have omitted to checkpoint a frame earlier than minFrame in \n      ** the file because there exists a frame after iSnapshot that\n      ** is the same database page.  */\n      pWal->minFrame = 1;\n\n      if( rc!=SQLITE_OK ){\n        sqlite3WalEndReadTransaction(pWal);\n      }\n    }\n  }\n\n  /* Release the shared CKPT lock obtained above. */\n  if( pWal->ckptLock ){\n    assert( pSnapshot );\n    walUnlockShared(pWal, WAL_CKPT_LOCK);\n    pWal->ckptLock = 0;\n  }\n#endif\n  return rc;\n}\n\n/*\n** Finish with a read transaction.  All this does is release the\n** read-lock.\n*/\nSQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){\n  sqlite3WalEndWriteTransaction(pWal);\n  if( pWal->readLock>=0 ){\n    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));\n    pWal->readLock = -1;\n  }\n}\n\n/*\n** Search the wal file for page pgno. If found, set *piRead to the frame that\n** contains the page. Otherwise, if pgno is not in the wal file, set *piRead\n** to zero.\n**\n** Return SQLITE_OK if successful, or an error code if an error occurs. If an\n** error does occur, the final value of *piRead is undefined.\n*/\nSQLITE_PRIVATE int sqlite3WalFindFrame(\n  Wal *pWal,                      /* WAL handle */\n  Pgno pgno,                      /* Database page number to read data for */\n  u32 *piRead                     /* OUT: Frame number (or zero) */\n){\n  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */\n  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */\n  int iHash;                      /* Used to loop through N hash tables */\n  int iMinHash;\n\n  /* This routine is only be called from within a read transaction. */\n  assert( pWal->readLock>=0 || pWal->lockError );\n\n  /* If the \"last page\" field of the wal-index header snapshot is 0, then\n  ** no data will be read from the wal under any circumstances. Return early\n  ** in this case as an optimization.  Likewise, if pWal->readLock==0, \n  ** then the WAL is ignored by the reader so return early, as if the \n  ** WAL were empty.\n  */\n  if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){\n    *piRead = 0;\n    return SQLITE_OK;\n  }\n\n  /* Search the hash table or tables for an entry matching page number\n  ** pgno. Each iteration of the following for() loop searches one\n  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).\n  **\n  ** This code might run concurrently to the code in walIndexAppend()\n  ** that adds entries to the wal-index (and possibly to this hash \n  ** table). This means the value just read from the hash \n  ** slot (aHash[iKey]) may have been added before or after the \n  ** current read transaction was opened. Values added after the\n  ** read transaction was opened may have been written incorrectly -\n  ** i.e. these slots may contain garbage data. However, we assume\n  ** that any slots written before the current read transaction was\n  ** opened remain unmodified.\n  **\n  ** For the reasons above, the if(...) condition featured in the inner\n  ** loop of the following block is more stringent that would be required \n  ** if we had exclusive access to the hash-table:\n  **\n  **   (aPgno[iFrame]==pgno): \n  **     This condition filters out normal hash-table collisions.\n  **\n  **   (iFrame<=iLast): \n  **     This condition filters out entries that were added to the hash\n  **     table after the current read-transaction had started.\n  */\n  iMinHash = walFramePage(pWal->minFrame);\n  for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){\n    WalHashLoc sLoc;              /* Hash table location */\n    int iKey;                     /* Hash slot index */\n    int nCollide;                 /* Number of hash collisions remaining */\n    int rc;                       /* Error code */\n    u32 iH;\n\n    rc = walHashGet(pWal, iHash, &sLoc);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    nCollide = HASHTABLE_NSLOT;\n    iKey = walHash(pgno);\n    while( (iH = AtomicLoad(&sLoc.aHash[iKey]))!=0 ){\n      u32 iFrame = iH + sLoc.iZero;\n      if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH]==pgno ){\n        assert( iFrame>iRead || CORRUPT_DB );\n        iRead = iFrame;\n      }\n      if( (nCollide--)==0 ){\n        return SQLITE_CORRUPT_BKPT;\n      }\n      iKey = walNextHash(iKey);\n    }\n    if( iRead ) break;\n  }\n\n#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT\n  /* If expensive assert() statements are available, do a linear search\n  ** of the wal-index file content. Make sure the results agree with the\n  ** result obtained using the hash indexes above.  */\n  {\n    u32 iRead2 = 0;\n    u32 iTest;\n    assert( pWal->bShmUnreliable || pWal->minFrame>0 );\n    for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){\n      if( walFramePgno(pWal, iTest)==pgno ){\n        iRead2 = iTest;\n        break;\n      }\n    }\n    assert( iRead==iRead2 );\n  }\n#endif\n\n  *piRead = iRead;\n  return SQLITE_OK;\n}\n\n/*\n** Read the contents of frame iRead from the wal file into buffer pOut\n** (which is nOut bytes in size). Return SQLITE_OK if successful, or an\n** error code otherwise.\n*/\nSQLITE_PRIVATE int sqlite3WalReadFrame(\n  Wal *pWal,                      /* WAL handle */\n  u32 iRead,                      /* Frame to read */\n  int nOut,                       /* Size of buffer pOut in bytes */\n  u8 *pOut                        /* Buffer to write page data to */\n){\n  int sz;\n  i64 iOffset;\n  sz = pWal->hdr.szPage;\n  sz = (sz&0xfe00) + ((sz&0x0001)<<16);\n  testcase( sz<=32768 );\n  testcase( sz>=65536 );\n  iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;\n  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */\n  return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);\n}\n\n/* \n** Return the size of the database in pages (or zero, if unknown).\n*/\nSQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){\n  if( pWal && ALWAYS(pWal->readLock>=0) ){\n    return pWal->hdr.nPage;\n  }\n  return 0;\n}\n\n\n/* \n** This function starts a write transaction on the WAL.\n**\n** A read transaction must have already been started by a prior call\n** to sqlite3WalBeginReadTransaction().\n**\n** If another thread or process has written into the database since\n** the read transaction was started, then it is not possible for this\n** thread to write as doing so would cause a fork.  So this routine\n** returns SQLITE_BUSY in that case and no write transaction is started.\n**\n** There can only be a single writer active at a time.\n*/\nSQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){\n  int rc;\n\n#ifdef SQLITE_ENABLE_SETLK_TIMEOUT\n  /* If the write-lock is already held, then it was obtained before the\n  ** read-transaction was even opened, making this call a no-op.\n  ** Return early. */\n  if( pWal->writeLock ){\n    assert( !memcmp(&pWal->hdr,(void *)walIndexHdr(pWal),sizeof(WalIndexHdr)) );\n    return SQLITE_OK;\n  }\n#endif\n\n  /* Cannot start a write transaction without first holding a read\n  ** transaction. */\n  assert( pWal->readLock>=0 );\n  assert( pWal->writeLock==0 && pWal->iReCksum==0 );\n\n  if( pWal->readOnly ){\n    return SQLITE_READONLY;\n  }\n\n  /* Only one writer allowed at a time.  Get the write lock.  Return\n  ** SQLITE_BUSY if unable.\n  */\n  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);\n  if( rc ){\n    return rc;\n  }\n  pWal->writeLock = 1;\n\n  /* If another connection has written to the database file since the\n  ** time the read transaction on this connection was started, then\n  ** the write is disallowed.\n  */\n  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){\n    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);\n    pWal->writeLock = 0;\n    rc = SQLITE_BUSY_SNAPSHOT;\n  }\n\n  return rc;\n}\n\n/*\n** End a write transaction.  The commit has already been done.  This\n** routine merely releases the lock.\n*/\nSQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){\n  if( pWal->writeLock ){\n    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);\n    pWal->writeLock = 0;\n    pWal->iReCksum = 0;\n    pWal->truncateOnCommit = 0;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** If any data has been written (but not committed) to the log file, this\n** function moves the write-pointer back to the start of the transaction.\n**\n** Additionally, the callback function is invoked for each frame written\n** to the WAL since the start of the transaction. If the callback returns\n** other than SQLITE_OK, it is not invoked again and the error code is\n** returned to the caller.\n**\n** Otherwise, if the callback function does not return an error, this\n** function returns SQLITE_OK.\n*/\nSQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){\n  int rc = SQLITE_OK;\n  if( ALWAYS(pWal->writeLock) ){\n    Pgno iMax = pWal->hdr.mxFrame;\n    Pgno iFrame;\n  \n    /* Restore the clients cache of the wal-index header to the state it\n    ** was in before the client began writing to the database. \n    */\n    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));\n\n    for(iFrame=pWal->hdr.mxFrame+1; \n        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; \n        iFrame++\n    ){\n      /* This call cannot fail. Unless the page for which the page number\n      ** is passed as the second argument is (a) in the cache and \n      ** (b) has an outstanding reference, then xUndo is either a no-op\n      ** (if (a) is false) or simply expels the page from the cache (if (b)\n      ** is false).\n      **\n      ** If the upper layer is doing a rollback, it is guaranteed that there\n      ** are no outstanding references to any page other than page 1. And\n      ** page 1 is never written to the log until the transaction is\n      ** committed. As a result, the call to xUndo may not fail.\n      */\n      assert( walFramePgno(pWal, iFrame)!=1 );\n      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));\n    }\n    if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);\n  }\n  return rc;\n}\n\n/* \n** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 \n** values. This function populates the array with values required to \n** \"rollback\" the write position of the WAL handle back to the current \n** point in the event of a savepoint rollback (via WalSavepointUndo()).\n*/\nSQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){\n  assert( pWal->writeLock );\n  aWalData[0] = pWal->hdr.mxFrame;\n  aWalData[1] = pWal->hdr.aFrameCksum[0];\n  aWalData[2] = pWal->hdr.aFrameCksum[1];\n  aWalData[3] = pWal->nCkpt;\n}\n\n/* \n** Move the write position of the WAL back to the point identified by\n** the values in the aWalData[] array. aWalData must point to an array\n** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated\n** by a call to WalSavepoint().\n*/\nSQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){\n  int rc = SQLITE_OK;\n\n  assert( pWal->writeLock );\n  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );\n\n  if( aWalData[3]!=pWal->nCkpt ){\n    /* This savepoint was opened immediately after the write-transaction\n    ** was started. Right after that, the writer decided to wrap around\n    ** to the start of the log. Update the savepoint values to match.\n    */\n    aWalData[0] = 0;\n    aWalData[3] = pWal->nCkpt;\n  }\n\n  if( aWalData[0]<pWal->hdr.mxFrame ){\n    pWal->hdr.mxFrame = aWalData[0];\n    pWal->hdr.aFrameCksum[0] = aWalData[1];\n    pWal->hdr.aFrameCksum[1] = aWalData[2];\n    walCleanupHash(pWal);\n  }\n\n  return rc;\n}\n\n/*\n** This function is called just before writing a set of frames to the log\n** file (see sqlite3WalFrames()). It checks to see if, instead of appending\n** to the current log file, it is possible to overwrite the start of the\n** existing log file with the new frames (i.e. \"reset\" the log). If so,\n** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left\n** unchanged.\n**\n** SQLITE_OK is returned if no error is encountered (regardless of whether\n** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned\n** if an error occurs.\n*/\nstatic int walRestartLog(Wal *pWal){\n  int rc = SQLITE_OK;\n  int cnt;\n\n  if( pWal->readLock==0 ){\n    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);\n    assert( pInfo->nBackfill==pWal->hdr.mxFrame );\n    if( pInfo->nBackfill>0 ){\n      u32 salt1;\n      sqlite3_randomness(4, &salt1);\n      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);\n      if( rc==SQLITE_OK ){\n        /* If all readers are using WAL_READ_LOCK(0) (in other words if no\n        ** readers are currently using the WAL), then the transactions\n        ** frames will overwrite the start of the existing log. Update the\n        ** wal-index header to reflect this.\n        **\n        ** In theory it would be Ok to update the cache of the header only\n        ** at this point. But updating the actual wal-index header is also\n        ** safe and means there is no special case for sqlite3WalUndo()\n        ** to handle if this transaction is rolled back.  */\n        walRestartHdr(pWal, salt1);\n        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);\n      }else if( rc!=SQLITE_BUSY ){\n        return rc;\n      }\n    }\n    walUnlockShared(pWal, WAL_READ_LOCK(0));\n    pWal->readLock = -1;\n    cnt = 0;\n    do{\n      int notUsed;\n      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);\n    }while( rc==WAL_RETRY );\n    assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */\n    testcase( (rc&0xff)==SQLITE_IOERR );\n    testcase( rc==SQLITE_PROTOCOL );\n    testcase( rc==SQLITE_OK );\n  }\n  return rc;\n}\n\n/*\n** Information about the current state of the WAL file and where\n** the next fsync should occur - passed from sqlite3WalFrames() into\n** walWriteToLog().\n*/\ntypedef struct WalWriter {\n  Wal *pWal;                   /* The complete WAL information */\n  sqlite3_file *pFd;           /* The WAL file to which we write */\n  sqlite3_int64 iSyncPoint;    /* Fsync at this offset */\n  int syncFlags;               /* Flags for the fsync */\n  int szPage;                  /* Size of one page */\n} WalWriter;\n\n/*\n** Write iAmt bytes of content into the WAL file beginning at iOffset.\n** Do a sync when crossing the p->iSyncPoint boundary.\n**\n** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,\n** first write the part before iSyncPoint, then sync, then write the\n** rest.\n*/\nstatic int walWriteToLog(\n  WalWriter *p,              /* WAL to write to */\n  void *pContent,            /* Content to be written */\n  int iAmt,                  /* Number of bytes to write */\n  sqlite3_int64 iOffset      /* Start writing at this offset */\n){\n  int rc;\n  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){\n    int iFirstAmt = (int)(p->iSyncPoint - iOffset);\n    rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);\n    if( rc ) return rc;\n    iOffset += iFirstAmt;\n    iAmt -= iFirstAmt;\n    pContent = (void*)(iFirstAmt + (char*)pContent);\n    assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );\n    rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));\n    if( iAmt==0 || rc ) return rc;\n  }\n  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);\n  return rc;\n}\n\n/*\n** Write out a single frame of the WAL\n*/\nstatic int walWriteOneFrame(\n  WalWriter *p,               /* Where to write the frame */\n  PgHdr *pPage,               /* The page of the frame to be written */\n  int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */\n  sqlite3_int64 iOffset       /* Byte offset at which to write */\n){\n  int rc;                         /* Result code from subfunctions */\n  void *pData;                    /* Data actually written */\n  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */\n  pData = pPage->pData;\n  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);\n  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);\n  if( rc ) return rc;\n  /* Write the page data */\n  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));\n  return rc;\n}\n\n/*\n** This function is called as part of committing a transaction within which\n** one or more frames have been overwritten. It updates the checksums for\n** all frames written to the wal file by the current transaction starting\n** with the earliest to have been overwritten.\n**\n** SQLITE_OK is returned if successful, or an SQLite error code otherwise.\n*/\nstatic int walRewriteChecksums(Wal *pWal, u32 iLast){\n  const int szPage = pWal->szPage;/* Database page size */\n  int rc = SQLITE_OK;             /* Return code */\n  u8 *aBuf;                       /* Buffer to load data from wal file into */\n  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-headers in */\n  u32 iRead;                      /* Next frame to read from wal file */\n  i64 iCksumOff;\n\n  aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);\n  if( aBuf==0 ) return SQLITE_NOMEM_BKPT;\n\n  /* Find the checksum values to use as input for the recalculating the\n  ** first checksum. If the first frame is frame 1 (implying that the current\n  ** transaction restarted the wal file), these values must be read from the\n  ** wal-file header. Otherwise, read them from the frame header of the\n  ** previous frame.  */\n  assert( pWal->iReCksum>0 );\n  if( pWal->iReCksum==1 ){\n    iCksumOff = 24;\n  }else{\n    iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;\n  }\n  rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);\n  pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);\n  pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);\n\n  iRead = pWal->iReCksum;\n  pWal->iReCksum = 0;\n  for(; rc==SQLITE_OK && iRead<=iLast; iRead++){\n    i64 iOff = walFrameOffset(iRead, szPage);\n    rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);\n    if( rc==SQLITE_OK ){\n      u32 iPgno, nDbSize;\n      iPgno = sqlite3Get4byte(aBuf);\n      nDbSize = sqlite3Get4byte(&aBuf[4]);\n\n      walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);\n      rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);\n    }\n  }\n\n  sqlite3_free(aBuf);\n  return rc;\n}\n\n/* \n** Write a set of frames to the log. The caller must hold the write-lock\n** on the log file (obtained using sqlite3WalBeginWriteTransaction()).\n*/\nSQLITE_PRIVATE int sqlite3WalFrames(\n  Wal *pWal,                      /* Wal handle to write to */\n  int szPage,                     /* Database page-size in bytes */\n  PgHdr *pList,                   /* List of dirty pages to write */\n  Pgno nTruncate,                 /* Database size after this commit */\n  int isCommit,                   /* True if this is a commit */\n  int sync_flags                  /* Flags to pass to OsSync() (or 0) */\n){\n  int rc;                         /* Used to catch return codes */\n  u32 iFrame;                     /* Next frame address */\n  PgHdr *p;                       /* Iterator to run through pList with. */\n  PgHdr *pLast = 0;               /* Last frame in list */\n  int nExtra = 0;                 /* Number of extra copies of last page */\n  int szFrame;                    /* The size of a single frame */\n  i64 iOffset;                    /* Next byte to write in WAL file */\n  WalWriter w;                    /* The writer */\n  u32 iFirst = 0;                 /* First frame that may be overwritten */\n  WalIndexHdr *pLive;             /* Pointer to shared header */\n\n  assert( pList );\n  assert( pWal->writeLock );\n\n  /* If this frame set completes a transaction, then nTruncate>0.  If\n  ** nTruncate==0 then this frame set does not complete the transaction. */\n  assert( (isCommit!=0)==(nTruncate!=0) );\n\n#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)\n  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}\n    WALTRACE((\"WAL%p: frame write begin. %d frames. mxFrame=%d. %s\\n\",\n              pWal, cnt, pWal->hdr.mxFrame, isCommit ? \"Commit\" : \"Spill\"));\n  }\n#endif\n\n  pLive = (WalIndexHdr*)walIndexHdr(pWal);\n  if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){\n    iFirst = pLive->mxFrame+1;\n  }\n\n  /* See if it is possible to write these frames into the start of the\n  ** log file, instead of appending to it at pWal->hdr.mxFrame.\n  */\n  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){\n    return rc;\n  }\n\n  /* If this is the first frame written into the log, write the WAL\n  ** header to the start of the WAL file. See comments at the top of\n  ** this source file for a description of the WAL header format.\n  */\n  iFrame = pWal->hdr.mxFrame;\n  if( iFrame==0 ){\n    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */\n    u32 aCksum[2];                /* Checksum for wal-header */\n\n    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));\n    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);\n    sqlite3Put4byte(&aWalHdr[8], szPage);\n    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);\n    if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);\n    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);\n    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);\n    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);\n    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);\n    \n    pWal->szPage = szPage;\n    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;\n    pWal->hdr.aFrameCksum[0] = aCksum[0];\n    pWal->hdr.aFrameCksum[1] = aCksum[1];\n    pWal->truncateOnCommit = 1;\n\n    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);\n    WALTRACE((\"WAL%p: wal-header write %s\\n\", pWal, rc ? \"failed\" : \"ok\"));\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n\n    /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless\n    ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise\n    ** an out-of-order write following a WAL restart could result in\n    ** database corruption.  See the ticket:\n    **\n    **     https://sqlite.org/src/info/ff5be73dee\n    */\n    if( pWal->syncHeader ){\n      rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));\n      if( rc ) return rc;\n    }\n  }\n  assert( (int)pWal->szPage==szPage );\n\n  /* Setup information needed to write frames into the WAL */\n  w.pWal = pWal;\n  w.pFd = pWal->pWalFd;\n  w.iSyncPoint = 0;\n  w.syncFlags = sync_flags;\n  w.szPage = szPage;\n  iOffset = walFrameOffset(iFrame+1, szPage);\n  szFrame = szPage + WAL_FRAME_HDRSIZE;\n\n  /* Write all frames into the log file exactly once */\n  for(p=pList; p; p=p->pDirty){\n    int nDbSize;   /* 0 normally.  Positive == commit flag */\n\n    /* Check if this page has already been written into the wal file by\n    ** the current transaction. If so, overwrite the existing frame and\n    ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that \n    ** checksums must be recomputed when the transaction is committed.  */\n    if( iFirst && (p->pDirty || isCommit==0) ){\n      u32 iWrite = 0;\n      VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);\n      assert( rc==SQLITE_OK || iWrite==0 );\n      if( iWrite>=iFirst ){\n        i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;\n        void *pData;\n        if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){\n          pWal->iReCksum = iWrite;\n        }\n        pData = p->pData;\n        rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);\n        if( rc ) return rc;\n        p->flags &= ~PGHDR_WAL_APPEND;\n        continue;\n      }\n    }\n\n    iFrame++;\n    assert( iOffset==walFrameOffset(iFrame, szPage) );\n    nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;\n    rc = walWriteOneFrame(&w, p, nDbSize, iOffset);\n    if( rc ) return rc;\n    pLast = p;\n    iOffset += szFrame;\n    p->flags |= PGHDR_WAL_APPEND;\n  }\n\n  /* Recalculate checksums within the wal file if required. */\n  if( isCommit && pWal->iReCksum ){\n    rc = walRewriteChecksums(pWal, iFrame);\n    if( rc ) return rc;\n  }\n\n  /* If this is the end of a transaction, then we might need to pad\n  ** the transaction and/or sync the WAL file.\n  **\n  ** Padding and syncing only occur if this set of frames complete a\n  ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL\n  ** or synchronous==OFF, then no padding or syncing are needed.\n  **\n  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not\n  ** needed and only the sync is done.  If padding is needed, then the\n  ** final frame is repeated (with its commit mark) until the next sector\n  ** boundary is crossed.  Only the part of the WAL prior to the last\n  ** sector boundary is synced; the part of the last frame that extends\n  ** past the sector boundary is written after the sync.\n  */\n  if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){\n    int bSync = 1;\n    if( pWal->padToSectorBoundary ){\n      int sectorSize = sqlite3SectorSize(pWal->pWalFd);\n      w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;\n      bSync = (w.iSyncPoint==iOffset);\n      testcase( bSync );\n      while( iOffset<w.iSyncPoint ){\n        rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);\n        if( rc ) return rc;\n        iOffset += szFrame;\n        nExtra++;\n        assert( pLast!=0 );\n      }\n    }\n    if( bSync ){\n      assert( rc==SQLITE_OK );\n      rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));\n    }\n  }\n\n  /* If this frame set completes the first transaction in the WAL and\n  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the\n  ** journal size limit, if possible.\n  */\n  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){\n    i64 sz = pWal->mxWalSize;\n    if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){\n      sz = walFrameOffset(iFrame+nExtra+1, szPage);\n    }\n    walLimitSize(pWal, sz);\n    pWal->truncateOnCommit = 0;\n  }\n\n  /* Append data to the wal-index. It is not necessary to lock the \n  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index\n  ** guarantees that there are no other writers, and no data that may\n  ** be in use by existing readers is being overwritten.\n  */\n  iFrame = pWal->hdr.mxFrame;\n  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){\n    if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;\n    iFrame++;\n    rc = walIndexAppend(pWal, iFrame, p->pgno);\n  }\n  assert( pLast!=0 || nExtra==0 );\n  while( rc==SQLITE_OK && nExtra>0 ){\n    iFrame++;\n    nExtra--;\n    rc = walIndexAppend(pWal, iFrame, pLast->pgno);\n  }\n\n  if( rc==SQLITE_OK ){\n    /* Update the private copy of the header. */\n    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));\n    testcase( szPage<=32768 );\n    testcase( szPage>=65536 );\n    pWal->hdr.mxFrame = iFrame;\n    if( isCommit ){\n      pWal->hdr.iChange++;\n      pWal->hdr.nPage = nTruncate;\n    }\n    /* If this is a commit, update the wal-index header too. */\n    if( isCommit ){\n      walIndexWriteHdr(pWal);\n      pWal->iCallback = iFrame;\n    }\n  }\n\n  WALTRACE((\"WAL%p: frame write %s\\n\", pWal, rc ? \"failed\" : \"ok\"));\n  return rc;\n}\n\n/* \n** This routine is called to implement sqlite3_wal_checkpoint() and\n** related interfaces.\n**\n** Obtain a CHECKPOINT lock and then backfill as much information as\n** we can from WAL into the database.\n**\n** If parameter xBusy is not NULL, it is a pointer to a busy-handler\n** callback. In this case this function runs a blocking checkpoint.\n*/\nSQLITE_PRIVATE int sqlite3WalCheckpoint(\n  Wal *pWal,                      /* Wal connection */\n  sqlite3 *db,                    /* Check this handle's interrupt flag */\n  int eMode,                      /* PASSIVE, FULL, RESTART, or TRUNCATE */\n  int (*xBusy)(void*),            /* Function to call when busy */\n  void *pBusyArg,                 /* Context argument for xBusyHandler */\n  int sync_flags,                 /* Flags to sync db file with (or 0) */\n  int nBuf,                       /* Size of temporary buffer */\n  u8 *zBuf,                       /* Temporary buffer to use */\n  int *pnLog,                     /* OUT: Number of frames in WAL */\n  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */\n){\n  int rc;                         /* Return code */\n  int isChanged = 0;              /* True if a new wal-index header is loaded */\n  int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */\n  int (*xBusy2)(void*) = xBusy;   /* Busy handler for eMode2 */\n\n  assert( pWal->ckptLock==0 );\n  assert( pWal->writeLock==0 );\n\n  /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked\n  ** in the SQLITE_CHECKPOINT_PASSIVE mode. */\n  assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );\n\n  if( pWal->readOnly ) return SQLITE_READONLY;\n  WALTRACE((\"WAL%p: checkpoint begins\\n\", pWal));\n\n  /* Enable blocking locks, if possible. If blocking locks are successfully\n  ** enabled, set xBusy2=0 so that the busy-handler is never invoked. */\n  sqlite3WalDb(pWal, db);\n  (void)walEnableBlocking(pWal);\n\n  /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive \n  ** \"checkpoint\" lock on the database file.\n  ** EVIDENCE-OF: R-10421-19736 If any other process is running a\n  ** checkpoint operation at the same time, the lock cannot be obtained and\n  ** SQLITE_BUSY is returned.\n  ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,\n  ** it will not be invoked in this case.\n  */\n  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);\n  testcase( rc==SQLITE_BUSY );\n  testcase( rc!=SQLITE_OK && xBusy2!=0 );\n  if( rc==SQLITE_OK ){\n    pWal->ckptLock = 1;\n\n    /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and\n    ** TRUNCATE modes also obtain the exclusive \"writer\" lock on the database\n    ** file.\n    **\n    ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained\n    ** immediately, and a busy-handler is configured, it is invoked and the\n    ** writer lock retried until either the busy-handler returns 0 or the\n    ** lock is successfully obtained.\n    */\n    if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){\n      rc = walBusyLock(pWal, xBusy2, pBusyArg, WAL_WRITE_LOCK, 1);\n      if( rc==SQLITE_OK ){\n        pWal->writeLock = 1;\n      }else if( rc==SQLITE_BUSY ){\n        eMode2 = SQLITE_CHECKPOINT_PASSIVE;\n        xBusy2 = 0;\n        rc = SQLITE_OK;\n      }\n    }\n  }\n\n\n  /* Read the wal-index header. */\n  if( rc==SQLITE_OK ){\n    walDisableBlocking(pWal);\n    rc = walIndexReadHdr(pWal, &isChanged);\n    (void)walEnableBlocking(pWal);\n    if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){\n      sqlite3OsUnfetch(pWal->pDbFd, 0, 0);\n    }\n  }\n\n  /* Copy data from the log to the database file. */\n  if( rc==SQLITE_OK ){\n\n    if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){\n      rc = SQLITE_CORRUPT_BKPT;\n    }else{\n      rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);\n    }\n\n    /* If no error occurred, set the output variables. */\n    if( rc==SQLITE_OK || rc==SQLITE_BUSY ){\n      if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;\n      if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);\n    }\n  }\n\n  if( isChanged ){\n    /* If a new wal-index header was loaded before the checkpoint was \n    ** performed, then the pager-cache associated with pWal is now\n    ** out of date. So zero the cached wal-index header to ensure that\n    ** next time the pager opens a snapshot on this database it knows that\n    ** the cache needs to be reset.\n    */\n    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));\n  }\n\n  walDisableBlocking(pWal);\n  sqlite3WalDb(pWal, 0);\n\n  /* Release the locks. */\n  sqlite3WalEndWriteTransaction(pWal);\n  if( pWal->ckptLock ){\n    walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);\n    pWal->ckptLock = 0;\n  }\n  WALTRACE((\"WAL%p: checkpoint %s\\n\", pWal, rc ? \"failed\" : \"ok\"));\n#ifdef SQLITE_ENABLE_SETLK_TIMEOUT\n  if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;\n#endif\n  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);\n}\n\n/* Return the value to pass to a sqlite3_wal_hook callback, the\n** number of frames in the WAL at the point of the last commit since\n** sqlite3WalCallback() was called.  If no commits have occurred since\n** the last call, then return 0.\n*/\nSQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){\n  u32 ret = 0;\n  if( pWal ){\n    ret = pWal->iCallback;\n    pWal->iCallback = 0;\n  }\n  return (int)ret;\n}\n\n/*\n** This function is called to change the WAL subsystem into or out\n** of locking_mode=EXCLUSIVE.\n**\n** If op is zero, then attempt to change from locking_mode=EXCLUSIVE\n** into locking_mode=NORMAL.  This means that we must acquire a lock\n** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL\n** or if the acquisition of the lock fails, then return 0.  If the\n** transition out of exclusive-mode is successful, return 1.  This\n** operation must occur while the pager is still holding the exclusive\n** lock on the main database file.\n**\n** If op is one, then change from locking_mode=NORMAL into \n** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must\n** be released.  Return 1 if the transition is made and 0 if the\n** WAL is already in exclusive-locking mode - meaning that this\n** routine is a no-op.  The pager must already hold the exclusive lock\n** on the main database file before invoking this operation.\n**\n** If op is negative, then do a dry-run of the op==1 case but do\n** not actually change anything. The pager uses this to see if it\n** should acquire the database exclusive lock prior to invoking\n** the op==1 case.\n*/\nSQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){\n  int rc;\n  assert( pWal->writeLock==0 );\n  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );\n\n  /* pWal->readLock is usually set, but might be -1 if there was a \n  ** prior error while attempting to acquire are read-lock. This cannot \n  ** happen if the connection is actually in exclusive mode (as no xShmLock\n  ** locks are taken in this case). Nor should the pager attempt to\n  ** upgrade to exclusive-mode following such an error.\n  */\n  assert( pWal->readLock>=0 || pWal->lockError );\n  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );\n\n  if( op==0 ){\n    if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){\n      pWal->exclusiveMode = WAL_NORMAL_MODE;\n      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){\n        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;\n      }\n      rc = pWal->exclusiveMode==WAL_NORMAL_MODE;\n    }else{\n      /* Already in locking_mode=NORMAL */\n      rc = 0;\n    }\n  }else if( op>0 ){\n    assert( pWal->exclusiveMode==WAL_NORMAL_MODE );\n    assert( pWal->readLock>=0 );\n    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));\n    pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;\n    rc = 1;\n  }else{\n    rc = pWal->exclusiveMode==WAL_NORMAL_MODE;\n  }\n  return rc;\n}\n\n/* \n** Return true if the argument is non-NULL and the WAL module is using\n** heap-memory for the wal-index. Otherwise, if the argument is NULL or the\n** WAL module is using shared-memory, return false. \n*/\nSQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){\n  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );\n}\n\n#ifdef SQLITE_ENABLE_SNAPSHOT\n/* Create a snapshot object.  The content of a snapshot is opaque to\n** every other subsystem, so the WAL module can put whatever it needs\n** in the object.\n*/\nSQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){\n  int rc = SQLITE_OK;\n  WalIndexHdr *pRet;\n  static const u32 aZero[4] = { 0, 0, 0, 0 };\n\n  assert( pWal->readLock>=0 && pWal->writeLock==0 );\n\n  if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){\n    *ppSnapshot = 0;\n    return SQLITE_ERROR;\n  }\n  pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));\n  if( pRet==0 ){\n    rc = SQLITE_NOMEM_BKPT;\n  }else{\n    memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));\n    *ppSnapshot = (sqlite3_snapshot*)pRet;\n  }\n\n  return rc;\n}\n\n/* Try to open on pSnapshot when the next read-transaction starts\n*/\nSQLITE_PRIVATE void sqlite3WalSnapshotOpen(\n  Wal *pWal, \n  sqlite3_snapshot *pSnapshot\n){\n  pWal->pSnapshot = (WalIndexHdr*)pSnapshot;\n}\n\n/* \n** Return a +ve value if snapshot p1 is newer than p2. A -ve value if\n** p1 is older than p2 and zero if p1 and p2 are the same snapshot.\n*/\nSQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){\n  WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;\n  WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;\n\n  /* aSalt[0] is a copy of the value stored in the wal file header. It\n  ** is incremented each time the wal file is restarted.  */\n  if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;\n  if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;\n  if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;\n  if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;\n  return 0;\n}\n\n/*\n** The caller currently has a read transaction open on the database.\n** This function takes a SHARED lock on the CHECKPOINTER slot and then\n** checks if the snapshot passed as the second argument is still \n** available. If so, SQLITE_OK is returned.\n**\n** If the snapshot is not available, SQLITE_ERROR is returned. Or, if\n** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error\n** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER\n** lock is released before returning.\n*/\nSQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot){\n  int rc;\n  rc = walLockShared(pWal, WAL_CKPT_LOCK);\n  if( rc==SQLITE_OK ){\n    WalIndexHdr *pNew = (WalIndexHdr*)pSnapshot;\n    if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))\n     || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted\n    ){\n      rc = SQLITE_ERROR_SNAPSHOT;\n      walUnlockShared(pWal, WAL_CKPT_LOCK);\n    }\n  }\n  return rc;\n}\n\n/*\n** Release a lock obtained by an earlier successful call to\n** sqlite3WalSnapshotCheck().\n*/\nSQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal){\n  assert( pWal );\n  walUnlockShared(pWal, WAL_CKPT_LOCK);\n}\n\n\n#endif /* SQLITE_ENABLE_SNAPSHOT */\n\n#ifdef SQLITE_ENABLE_ZIPVFS\n/*\n** If the argument is not NULL, it points to a Wal object that holds a\n** read-lock. This function returns the database page-size if it is known,\n** or zero if it is not (or if pWal is NULL).\n*/\nSQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){\n  assert( pWal==0 || pWal->readLock>=0 );\n  return (pWal ? pWal->szPage : 0);\n}\n#endif\n\n/* Return the sqlite3_file object for the WAL file\n*/\nSQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){\n  return pWal->pWalFd;\n}\n\n#endif /* #ifndef SQLITE_OMIT_WAL */\n\n/************** End of wal.c *************************************************/\n/************** Begin file btmutex.c *****************************************/\n/*\n** 2007 August 27\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains code used to implement mutexes on Btree objects.\n** This code really belongs in btree.c.  But btree.c is getting too\n** big and we want to break it down some.  This packaged seemed like\n** a good breakout.\n*/\n/************** Include btreeInt.h in the middle of btmutex.c ****************/\n/************** Begin file btreeInt.h ****************************************/\n/*\n** 2004 April 6\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file implements an external (disk-based) database using BTrees.\n** For a detailed discussion of BTrees, refer to\n**\n**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:\n**     \"Sorting And Searching\", pages 473-480. Addison-Wesley\n**     Publishing Company, Reading, Massachusetts.\n**\n** The basic idea is that each page of the file contains N database\n** entries and N+1 pointers to subpages.\n**\n**   ----------------------------------------------------------------\n**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |\n**   ----------------------------------------------------------------\n**\n** All of the keys on the page that Ptr(0) points to have values less\n** than Key(0).  All of the keys on page Ptr(1) and its subpages have\n** values greater than Key(0) and less than Key(1).  All of the keys\n** on Ptr(N) and its subpages have values greater than Key(N-1).  And\n** so forth.\n**\n** Finding a particular key requires reading O(log(M)) pages from the \n** disk where M is the number of entries in the tree.\n**\n** In this implementation, a single file can hold one or more separate \n** BTrees.  Each BTree is identified by the index of its root page.  The\n** key and data for any entry are combined to form the \"payload\".  A\n** fixed amount of payload can be carried directly on the database\n** page.  If the payload is larger than the preset amount then surplus\n** bytes are stored on overflow pages.  The payload for an entry\n** and the preceding pointer are combined to form a \"Cell\".  Each \n** page has a small header which contains the Ptr(N) pointer and other\n** information such as the size of key and data.\n**\n** FORMAT DETAILS\n**\n** The file is divided into pages.  The first page is called page 1,\n** the second is page 2, and so forth.  A page number of zero indicates\n** \"no such page\".  The page size can be any power of 2 between 512 and 65536.\n** Each page can be either a btree page, a freelist page, an overflow\n** page, or a pointer-map page.\n**\n** The first page is always a btree page.  The first 100 bytes of the first\n** page contain a special header (the \"file header\") that describes the file.\n** The format of the file header is as follows:\n**\n**   OFFSET   SIZE    DESCRIPTION\n**      0      16     Header string: \"SQLite format 3\\000\"\n**     16       2     Page size in bytes.  (1 means 65536)\n**     18       1     File format write version\n**     19       1     File format read version\n**     20       1     Bytes of unused space at the end of each page\n**     21       1     Max embedded payload fraction (must be 64)\n**     22       1     Min embedded payload fraction (must be 32)\n**     23       1     Min leaf payload fraction (must be 32)\n**     24       4     File change counter\n**     28       4     Reserved for future use\n**     32       4     First freelist page\n**     36       4     Number of freelist pages in the file\n**     40      60     15 4-byte meta values passed to higher layers\n**\n**     40       4     Schema cookie\n**     44       4     File format of schema layer\n**     48       4     Size of page cache\n**     52       4     Largest root-page (auto/incr_vacuum)\n**     56       4     1=UTF-8 2=UTF16le 3=UTF16be\n**     60       4     User version\n**     64       4     Incremental vacuum mode\n**     68       4     Application-ID\n**     72      20     unused\n**     92       4     The version-valid-for number\n**     96       4     SQLITE_VERSION_NUMBER\n**\n** All of the integer values are big-endian (most significant byte first).\n**\n** The file change counter is incremented when the database is changed\n** This counter allows other processes to know when the file has changed\n** and thus when they need to flush their cache.\n**\n** The max embedded payload fraction is the amount of the total usable\n** space in a page that can be consumed by a single cell for standard\n** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default\n** is to limit the maximum cell size so that at least 4 cells will fit\n** on one page.  Thus the default max embedded payload fraction is 64.\n**\n** If the payload for a cell is larger than the max payload, then extra\n** payload is spilled to overflow pages.  Once an overflow page is allocated,\n** as many bytes as possible are moved into the overflow pages without letting\n** the cell size drop below the min embedded payload fraction.\n**\n** The min leaf payload fraction is like the min embedded payload fraction\n** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum\n** payload fraction for a LEAFDATA tree is always 100% (or 255) and it\n** not specified in the header.\n**\n** Each btree pages is divided into three sections:  The header, the\n** cell pointer array, and the cell content area.  Page 1 also has a 100-byte\n** file header that occurs before the page header.\n**\n**      |----------------|\n**      | file header    |   100 bytes.  Page 1 only.\n**      |----------------|\n**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes\n**      |----------------|\n**      | cell pointer   |   |  2 bytes per cell.  Sorted order.\n**      | array          |   |  Grows downward\n**      |                |   v\n**      |----------------|\n**      | unallocated    |\n**      | space          |\n**      |----------------|   ^  Grows upwards\n**      | cell content   |   |  Arbitrary order interspersed with freeblocks.\n**      | area           |   |  and free space fragments.\n**      |----------------|\n**\n** The page headers looks like this:\n**\n**   OFFSET   SIZE     DESCRIPTION\n**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf\n**      1       2      byte offset to the first freeblock\n**      3       2      number of cells on this page\n**      5       2      first byte of the cell content area\n**      7       1      number of fragmented free bytes\n**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.\n**\n** The flags define the format of this btree page.  The leaf flag means that\n** this page has no children.  The zerodata flag means that this page carries\n** only keys and no data.  The intkey flag means that the key is an integer\n** which is stored in the key size entry of the cell header rather than in\n** the payload area.\n**\n** The cell pointer array begins on the first byte after the page header.\n** The cell pointer array contains zero or more 2-byte numbers which are\n** offsets from the beginning of the page to the cell content in the cell\n** content area.  The cell pointers occur in sorted order.  The system strives\n** to keep free space after the last cell pointer so that new cells can\n** be easily added without having to defragment the page.\n**\n** Cell content is stored at the very end of the page and grows toward the\n** beginning of the page.\n**\n** Unused space within the cell content area is collected into a linked list of\n** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset\n** to the first freeblock is given in the header.  Freeblocks occur in\n** increasing order.  Because a freeblock must be at least 4 bytes in size,\n** any group of 3 or fewer unused bytes in the cell content area cannot\n** exist on the freeblock chain.  A group of 3 or fewer free bytes is called\n** a fragment.  The total number of bytes in all fragments is recorded.\n** in the page header at offset 7.\n**\n**    SIZE    DESCRIPTION\n**      2     Byte offset of the next freeblock\n**      2     Bytes in this freeblock\n**\n** Cells are of variable length.  Cells are stored in the cell content area at\n** the end of the page.  Pointers to the cells are in the cell pointer array\n** that immediately follows the page header.  Cells is not necessarily\n** contiguous or in order, but cell pointers are contiguous and in order.\n**\n** Cell content makes use of variable length integers.  A variable\n** length integer is 1 to 9 bytes where the lower 7 bits of each \n** byte are used.  The integer consists of all bytes that have bit 8 set and\n** the first byte with bit 8 clear.  The most significant byte of the integer\n** appears first.  A variable-length integer may not be more than 9 bytes long.\n** As a special case, all 8 bytes of the 9th byte are used as data.  This\n** allows a 64-bit integer to be encoded in 9 bytes.\n**\n**    0x00                      becomes  0x00000000\n**    0x7f                      becomes  0x0000007f\n**    0x81 0x00                 becomes  0x00000080\n**    0x82 0x00                 becomes  0x00000100\n**    0x80 0x7f                 becomes  0x0000007f\n**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678\n**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081\n**\n** Variable length integers are used for rowids and to hold the number of\n** bytes of key and data in a btree cell.\n**\n** The content of a cell looks like this:\n**\n**    SIZE    DESCRIPTION\n**      4     Page number of the left child. Omitted if leaf flag is set.\n**     var    Number of bytes of data. Omitted if the zerodata flag is set.\n**     var    Number of bytes of key. Or the key itself if intkey flag is set.\n**      *     Payload\n**      4     First page of the overflow chain.  Omitted if no overflow\n**\n** Overflow pages form a linked list.  Each page except the last is completely\n** filled with data (pagesize - 4 bytes).  The last page can have as little\n** as 1 byte of data.\n**\n**    SIZE    DESCRIPTION\n**      4     Page number of next overflow page\n**      *     Data\n**\n** Freelist pages come in two subtypes: trunk pages and leaf pages.  The\n** file header points to the first in a linked list of trunk page.  Each trunk\n** page points to multiple leaf pages.  The content of a leaf page is\n** unspecified.  A trunk page looks like this:\n**\n**    SIZE    DESCRIPTION\n**      4     Page number of next trunk page\n**      4     Number of leaf pointers on this page\n**      *     zero or more pages numbers of leaves\n*/\n/* #include \"sqliteInt.h\" */\n\n\n/* The following value is the maximum cell size assuming a maximum page\n** size give above.\n*/\n#define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))\n\n/* The maximum number of cells on a single page of the database.  This\n** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself\n** plus 2 bytes for the index to the cell in the page header).  Such\n** small cells will be rare, but they are possible.\n*/\n#define MX_CELL(pBt) ((pBt->pageSize-8)/6)\n\n/* Forward declarations */\ntypedef struct MemPage MemPage;\ntypedef struct BtLock BtLock;\ntypedef struct CellInfo CellInfo;\n\n/*\n** This is a magic string that appears at the beginning of every\n** SQLite database in order to identify the file as a real database.\n**\n** You can change this value at compile-time by specifying a\n** -DSQLITE_FILE_HEADER=\"...\" on the compiler command-line.  The\n** header must be exactly 16 bytes including the zero-terminator so\n** the string itself should be 15 characters long.  If you change\n** the header, then your custom library will not be able to read \n** databases generated by the standard tools and the standard tools\n** will not be able to read databases created by your custom library.\n*/\n#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */\n#  define SQLITE_FILE_HEADER \"SQLite format 3\"\n#endif\n\n/*\n** Page type flags.  An ORed combination of these flags appear as the\n** first byte of on-disk image of every BTree page.\n*/\n#define PTF_INTKEY    0x01\n#define PTF_ZERODATA  0x02\n#define PTF_LEAFDATA  0x04\n#define PTF_LEAF      0x08\n\n/*\n** An instance of this object stores information about each a single database\n** page that has been loaded into memory.  The information in this object\n** is derived from the raw on-disk page content.\n**\n** As each database page is loaded into memory, the pager allocats an\n** instance of this object and zeros the first 8 bytes.  (This is the\n** \"extra\" information associated with each page of the pager.)\n**\n** Access to all fields of this structure is controlled by the mutex\n** stored in MemPage.pBt->mutex.\n*/\nstruct MemPage {\n  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */\n  u8 bBusy;            /* Prevent endless loops on corrupt database files */\n  u8 intKey;           /* True if table b-trees.  False for index b-trees */\n  u8 intKeyLeaf;       /* True if the leaf of an intKey table */\n  Pgno pgno;           /* Page number for this page */\n  /* Only the first 8 bytes (above) are zeroed by pager.c when a new page\n  ** is allocated. All fields that follow must be initialized before use */\n  u8 leaf;             /* True if a leaf page */\n  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */\n  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */\n  u8 max1bytePayload;  /* min(maxLocal,127) */\n  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */\n  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */\n  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */\n  u16 cellOffset;      /* Index in aData of first cell pointer */\n  int nFree;           /* Number of free bytes on the page. -1 for unknown */\n  u16 nCell;           /* Number of cells on this page, local and ovfl */\n  u16 maskPage;        /* Mask for page offset */\n  u16 aiOvfl[4];       /* Insert the i-th overflow cell before the aiOvfl-th\n                       ** non-overflow cell */\n  u8 *apOvfl[4];       /* Pointers to the body of overflow cells */\n  BtShared *pBt;       /* Pointer to BtShared that this page is part of */\n  u8 *aData;           /* Pointer to disk image of the page data */\n  u8 *aDataEnd;        /* One byte past the end of usable data */\n  u8 *aCellIdx;        /* The cell index area */\n  u8 *aDataOfst;       /* Same as aData for leaves.  aData+4 for interior */\n  DbPage *pDbPage;     /* Pager page handle */\n  u16 (*xCellSize)(MemPage*,u8*);             /* cellSizePtr method */\n  void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */\n};\n\n/*\n** A linked list of the following structures is stored at BtShared.pLock.\n** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor \n** is opened on the table with root page BtShared.iTable. Locks are removed\n** from this list when a transaction is committed or rolled back, or when\n** a btree handle is closed.\n*/\nstruct BtLock {\n  Btree *pBtree;        /* Btree handle holding this lock */\n  Pgno iTable;          /* Root page of table */\n  u8 eLock;             /* READ_LOCK or WRITE_LOCK */\n  BtLock *pNext;        /* Next in BtShared.pLock list */\n};\n\n/* Candidate values for BtLock.eLock */\n#define READ_LOCK     1\n#define WRITE_LOCK    2\n\n/* A Btree handle\n**\n** A database connection contains a pointer to an instance of\n** this object for every database file that it has open.  This structure\n** is opaque to the database connection.  The database connection cannot\n** see the internals of this structure and only deals with pointers to\n** this structure.\n**\n** For some database files, the same underlying database cache might be \n** shared between multiple connections.  In that case, each connection\n** has it own instance of this object.  But each instance of this object\n** points to the same BtShared object.  The database cache and the\n** schema associated with the database file are all contained within\n** the BtShared object.\n**\n** All fields in this structure are accessed under sqlite3.mutex.\n** The pBt pointer itself may not be changed while there exists cursors \n** in the referenced BtShared that point back to this Btree since those\n** cursors have to go through this Btree to find their BtShared and\n** they often do so without holding sqlite3.mutex.\n*/\nstruct Btree {\n  sqlite3 *db;       /* The database connection holding this btree */\n  BtShared *pBt;     /* Sharable content of this btree */\n  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */\n  u8 sharable;       /* True if we can share pBt with another db */\n  u8 locked;         /* True if db currently has pBt locked */\n  u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */\n  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */\n  int nBackup;       /* Number of backup operations reading this btree */\n  u32 iDataVersion;  /* Combines with pBt->pPager->iDataVersion */\n  Btree *pNext;      /* List of other sharable Btrees from the same db */\n  Btree *pPrev;      /* Back pointer of the same list */\n#ifndef SQLITE_OMIT_SHARED_CACHE\n  BtLock lock;       /* Object used to lock page 1 */\n#endif\n};\n\n/*\n** Btree.inTrans may take one of the following values.\n**\n** If the shared-data extension is enabled, there may be multiple users\n** of the Btree structure. At most one of these may open a write transaction,\n** but any number may have active read transactions.\n*/\n#define TRANS_NONE  0\n#define TRANS_READ  1\n#define TRANS_WRITE 2\n\n/*\n** An instance of this object represents a single database file.\n** \n** A single database file can be in use at the same time by two\n** or more database connections.  When two or more connections are\n** sharing the same database file, each connection has it own\n** private Btree object for the file and each of those Btrees points\n** to this one BtShared object.  BtShared.nRef is the number of\n** connections currently sharing this database file.\n**\n** Fields in this structure are accessed under the BtShared.mutex\n** mutex, except for nRef and pNext which are accessed under the\n** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field\n** may not be modified once it is initially set as long as nRef>0.\n** The pSchema field may be set once under BtShared.mutex and\n** thereafter is unchanged as long as nRef>0.\n**\n** isPending:\n**\n**   If a BtShared client fails to obtain a write-lock on a database\n**   table (because there exists one or more read-locks on the table),\n**   the shared-cache enters 'pending-lock' state and isPending is\n**   set to true.\n**\n**   The shared-cache leaves the 'pending lock' state when either of\n**   the following occur:\n**\n**     1) The current writer (BtShared.pWriter) concludes its transaction, OR\n**     2) The number of locks held by other connections drops to zero.\n**\n**   while in the 'pending-lock' state, no connection may start a new\n**   transaction.\n**\n**   This feature is included to help prevent writer-starvation.\n*/\nstruct BtShared {\n  Pager *pPager;        /* The page cache */\n  sqlite3 *db;          /* Database connection currently using this Btree */\n  BtCursor *pCursor;    /* A list of all open cursors */\n  MemPage *pPage1;      /* First page of the database */\n  u8 openFlags;         /* Flags to sqlite3BtreeOpen() */\n#ifndef SQLITE_OMIT_AUTOVACUUM\n  u8 autoVacuum;        /* True if auto-vacuum is enabled */\n  u8 incrVacuum;        /* True if incr-vacuum is enabled */\n  u8 bDoTruncate;       /* True to truncate db on commit */\n#endif\n  u8 inTransaction;     /* Transaction state */\n  u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */\n  u8 nReserveWanted;    /* Desired number of extra bytes per page */\n  u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */\n  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */\n  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */\n  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */\n  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */\n  u32 pageSize;         /* Total number of bytes on a page */\n  u32 usableSize;       /* Number of usable bytes on each page */\n  int nTransaction;     /* Number of open transactions (read + write) */\n  u32 nPage;            /* Number of pages in the database */\n  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */\n  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */\n  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */\n  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */\n#ifndef SQLITE_OMIT_SHARED_CACHE\n  int nRef;             /* Number of references to this structure */\n  BtShared *pNext;      /* Next on a list of sharable BtShared structs */\n  BtLock *pLock;        /* List of locks held on this shared-btree struct */\n  Btree *pWriter;       /* Btree with currently open write transaction */\n#endif\n  u8 *pTmpSpace;        /* Temp space sufficient to hold a single cell */\n};\n\n/*\n** Allowed values for BtShared.btsFlags\n*/\n#define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */\n#define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */\n#define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */\n#define BTS_OVERWRITE        0x0008   /* Overwrite deleted content with zeros */\n#define BTS_FAST_SECURE      0x000c   /* Combination of the previous two */\n#define BTS_INITIALLY_EMPTY  0x0010   /* Database was empty at trans start */\n#define BTS_NO_WAL           0x0020   /* Do not open write-ahead-log files */\n#define BTS_EXCLUSIVE        0x0040   /* pWriter has an exclusive lock */\n#define BTS_PENDING          0x0080   /* Waiting for read-locks to clear */\n\n/*\n** An instance of the following structure is used to hold information\n** about a cell.  The parseCellPtr() function fills in this structure\n** based on information extract from the raw disk page.\n*/\nstruct CellInfo {\n  i64 nKey;      /* The key for INTKEY tables, or nPayload otherwise */\n  u8 *pPayload;  /* Pointer to the start of payload */\n  u32 nPayload;  /* Bytes of payload */\n  u16 nLocal;    /* Amount of payload held locally, not on overflow */\n  u16 nSize;     /* Size of the cell content on the main b-tree page */\n};\n\n/*\n** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than\n** this will be declared corrupt. This value is calculated based on a\n** maximum database size of 2^31 pages a minimum fanout of 2 for a\n** root-node and 3 for all other internal nodes.\n**\n** If a tree that appears to be taller than this is encountered, it is\n** assumed that the database is corrupt.\n*/\n#define BTCURSOR_MAX_DEPTH 20\n\n/*\n** A cursor is a pointer to a particular entry within a particular\n** b-tree within a database file.\n**\n** The entry is identified by its MemPage and the index in\n** MemPage.aCell[] of the entry.\n**\n** A single database file can be shared by two more database connections,\n** but cursors cannot be shared.  Each cursor is associated with a\n** particular database connection identified BtCursor.pBtree.db.\n**\n** Fields in this structure are accessed under the BtShared.mutex\n** found at self->pBt->mutex. \n**\n** skipNext meaning:\n** The meaning of skipNext depends on the value of eState:\n**\n**   eState            Meaning of skipNext\n**   VALID             skipNext is meaningless and is ignored\n**   INVALID           skipNext is meaningless and is ignored\n**   SKIPNEXT          sqlite3BtreeNext() is a no-op if skipNext>0 and\n**                     sqlite3BtreePrevious() is no-op if skipNext<0.\n**   REQUIRESEEK       restoreCursorPosition() restores the cursor to\n**                     eState=SKIPNEXT if skipNext!=0\n**   FAULT             skipNext holds the cursor fault error code.\n*/\nstruct BtCursor {\n  u8 eState;                /* One of the CURSOR_XXX constants (see below) */\n  u8 curFlags;              /* zero or more BTCF_* flags defined below */\n  u8 curPagerFlags;         /* Flags to send to sqlite3PagerGet() */\n  u8 hints;                 /* As configured by CursorSetHints() */\n  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive.\n                   ** Error code if eState==CURSOR_FAULT */\n  Btree *pBtree;            /* The Btree to which this cursor belongs */\n  Pgno *aOverflow;          /* Cache of overflow page locations */\n  void *pKey;               /* Saved key that was cursor last known position */\n  /* All fields above are zeroed when the cursor is allocated.  See\n  ** sqlite3BtreeCursorZero().  Fields that follow must be manually\n  ** initialized. */\n#define BTCURSOR_FIRST_UNINIT pBt   /* Name of first uninitialized field */\n  BtShared *pBt;            /* The BtShared this cursor points to */\n  BtCursor *pNext;          /* Forms a linked list of all cursors */\n  CellInfo info;            /* A parse of the cell we are pointing at */\n  i64 nKey;                 /* Size of pKey, or last integer key */\n  Pgno pgnoRoot;            /* The root page of this tree */\n  i8 iPage;                 /* Index of current page in apPage */\n  u8 curIntKey;             /* Value of apPage[0]->intKey */\n  u16 ix;                   /* Current index for apPage[iPage] */\n  u16 aiIdx[BTCURSOR_MAX_DEPTH-1];     /* Current index in apPage[i] */\n  struct KeyInfo *pKeyInfo;            /* Arg passed to comparison function */\n  MemPage *pPage;                        /* Current page */\n  MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */\n};\n\n/*\n** Legal values for BtCursor.curFlags\n*/\n#define BTCF_WriteFlag    0x01   /* True if a write cursor */\n#define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */\n#define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */\n#define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */\n#define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */\n#define BTCF_Multiple     0x20   /* Maybe another cursor on the same btree */\n#define BTCF_Pinned       0x40   /* Cursor is busy and cannot be moved */\n\n/*\n** Potential values for BtCursor.eState.\n**\n** CURSOR_INVALID:\n**   Cursor does not point to a valid entry. This can happen (for example) \n**   because the table is empty or because BtreeCursorFirst() has not been\n**   called.\n**\n** CURSOR_VALID:\n**   Cursor points to a valid entry. getPayload() etc. may be called.\n**\n** CURSOR_SKIPNEXT:\n**   Cursor is valid except that the Cursor.skipNext field is non-zero\n**   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()\n**   operation should be a no-op.\n**\n** CURSOR_REQUIRESEEK:\n**   The table that this cursor was opened on still exists, but has been \n**   modified since the cursor was last used. The cursor position is saved\n**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in \n**   this state, restoreCursorPosition() can be called to attempt to\n**   seek the cursor to the saved position.\n**\n** CURSOR_FAULT:\n**   An unrecoverable error (an I/O error or a malloc failure) has occurred\n**   on a different connection that shares the BtShared cache with this\n**   cursor.  The error has left the cache in an inconsistent state.\n**   Do nothing else with this cursor.  Any attempt to use the cursor\n**   should return the error code stored in BtCursor.skipNext\n*/\n#define CURSOR_VALID             0\n#define CURSOR_INVALID           1\n#define CURSOR_SKIPNEXT          2\n#define CURSOR_REQUIRESEEK       3\n#define CURSOR_FAULT             4\n\n/* \n** The database page the PENDING_BYTE occupies. This page is never used.\n*/\n# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)\n\n/*\n** These macros define the location of the pointer-map entry for a \n** database page. The first argument to each is the number of usable\n** bytes on each page of the database (often 1024). The second is the\n** page number to look up in the pointer map.\n**\n** PTRMAP_PAGENO returns the database page number of the pointer-map\n** page that stores the required pointer. PTRMAP_PTROFFSET returns\n** the offset of the requested map entry.\n**\n** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,\n** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be\n** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements\n** this test.\n*/\n#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)\n#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))\n#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))\n\n/*\n** The pointer map is a lookup table that identifies the parent page for\n** each child page in the database file.  The parent page is the page that\n** contains a pointer to the child.  Every page in the database contains\n** 0 or 1 parent pages.  (In this context 'database page' refers\n** to any page that is not part of the pointer map itself.)  Each pointer map\n** entry consists of a single byte 'type' and a 4 byte parent page number.\n** The PTRMAP_XXX identifiers below are the valid types.\n**\n** The purpose of the pointer map is to facility moving pages from one\n** position in the file to another as part of autovacuum.  When a page\n** is moved, the pointer in its parent must be updated to point to the\n** new location.  The pointer map is used to locate the parent page quickly.\n**\n** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not\n**                  used in this case.\n**\n** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number \n**                  is not used in this case.\n**\n** PTRMAP_OVERFLOW1: The database page is the first page in a list of \n**                   overflow pages. The page number identifies the page that\n**                   contains the cell with a pointer to this overflow page.\n**\n** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of\n**                   overflow pages. The page-number identifies the previous\n**                   page in the overflow page list.\n**\n** PTRMAP_BTREE: The database page is a non-root btree page. The page number\n**               identifies the parent page in the btree.\n*/\n#define PTRMAP_ROOTPAGE 1\n#define PTRMAP_FREEPAGE 2\n#define PTRMAP_OVERFLOW1 3\n#define PTRMAP_OVERFLOW2 4\n#define PTRMAP_BTREE 5\n\n/* A bunch of assert() statements to check the transaction state variables\n** of handle p (type Btree*) are internally consistent.\n*/\n#define btreeIntegrity(p) \\\n  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \\\n  assert( p->pBt->inTransaction>=p->inTrans ); \n\n\n/*\n** The ISAUTOVACUUM macro is used within balance_nonroot() to determine\n** if the database supports auto-vacuum or not. Because it is used\n** within an expression that is an argument to another macro \n** (sqliteMallocRaw), it is not possible to use conditional compilation.\n** So, this macro is defined instead.\n*/\n#ifndef SQLITE_OMIT_AUTOVACUUM\n#define ISAUTOVACUUM (pBt->autoVacuum)\n#else\n#define ISAUTOVACUUM 0\n#endif\n\n\n/*\n** This structure is passed around through all the sanity checking routines\n** in order to keep track of some global state information.\n**\n** The aRef[] array is allocated so that there is 1 bit for each page in\n** the database. As the integrity-check proceeds, for each page used in\n** the database the corresponding bit is set. This allows integrity-check to \n** detect pages that are used twice and orphaned pages (both of which \n** indicate corruption).\n*/\ntypedef struct IntegrityCk IntegrityCk;\nstruct IntegrityCk {\n  BtShared *pBt;    /* The tree being checked out */\n  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */\n  u8 *aPgRef;       /* 1 bit per page in the db (see above) */\n  Pgno nPage;       /* Number of pages in the database */\n  int mxErr;        /* Stop accumulating errors when this reaches zero */\n  int nErr;         /* Number of messages written to zErrMsg so far */\n  int mallocFailed; /* A memory allocation error has occurred */\n  const char *zPfx; /* Error message prefix */\n  int v1, v2;       /* Values for up to two %d fields in zPfx */\n  StrAccum errMsg;  /* Accumulate the error message text here */\n  u32 *heap;        /* Min-heap used for analyzing cell coverage */\n  sqlite3 *db;      /* Database connection running the check */\n};\n\n/*\n** Routines to read or write a two- and four-byte big-endian integer values.\n*/\n#define get2byte(x)   ((x)[0]<<8 | (x)[1])\n#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))\n#define get4byte sqlite3Get4byte\n#define put4byte sqlite3Put4byte\n\n/*\n** get2byteAligned(), unlike get2byte(), requires that its argument point to a\n** two-byte aligned address.  get2bytea() is only used for accessing the\n** cell addresses in a btree header.\n*/\n#if SQLITE_BYTEORDER==4321\n# define get2byteAligned(x)  (*(u16*)(x))\n#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000\n# define get2byteAligned(x)  __builtin_bswap16(*(u16*)(x))\n#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300\n# define get2byteAligned(x)  _byteswap_ushort(*(u16*)(x))\n#else\n# define get2byteAligned(x)  ((x)[0]<<8 | (x)[1])\n#endif\n\n/************** End of btreeInt.h ********************************************/\n/************** Continuing where we left off in btmutex.c ********************/\n#ifndef SQLITE_OMIT_SHARED_CACHE\n#if SQLITE_THREADSAFE\n\n/*\n** Obtain the BtShared mutex associated with B-Tree handle p. Also,\n** set BtShared.db to the database handle associated with p and the\n** p->locked boolean to true.\n*/\nstatic void lockBtreeMutex(Btree *p){\n  assert( p->locked==0 );\n  assert( sqlite3_mutex_notheld(p->pBt->mutex) );\n  assert( sqlite3_mutex_held(p->db->mutex) );\n\n  sqlite3_mutex_enter(p->pBt->mutex);\n  p->pBt->db = p->db;\n  p->locked = 1;\n}\n\n/*\n** Release the BtShared mutex associated with B-Tree handle p and\n** clear the p->locked boolean.\n*/\nstatic void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){\n  BtShared *pBt = p->pBt;\n  assert( p->locked==1 );\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  assert( p->db==pBt->db );\n\n  sqlite3_mutex_leave(pBt->mutex);\n  p->locked = 0;\n}\n\n/* Forward reference */\nstatic void SQLITE_NOINLINE btreeLockCarefully(Btree *p);\n\n/*\n** Enter a mutex on the given BTree object.\n**\n** If the object is not sharable, then no mutex is ever required\n** and this routine is a no-op.  The underlying mutex is non-recursive.\n** But we keep a reference count in Btree.wantToLock so the behavior\n** of this interface is recursive.\n**\n** To avoid deadlocks, multiple Btrees are locked in the same order\n** by all database connections.  The p->pNext is a list of other\n** Btrees belonging to the same database connection as the p Btree\n** which need to be locked after p.  If we cannot get a lock on\n** p, then first unlock all of the others on p->pNext, then wait\n** for the lock to become available on p, then relock all of the\n** subsequent Btrees that desire a lock.\n*/\nSQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){\n  /* Some basic sanity checking on the Btree.  The list of Btrees\n  ** connected by pNext and pPrev should be in sorted order by\n  ** Btree.pBt value. All elements of the list should belong to\n  ** the same connection. Only shared Btrees are on the list. */\n  assert( p->pNext==0 || p->pNext->pBt>p->pBt );\n  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );\n  assert( p->pNext==0 || p->pNext->db==p->db );\n  assert( p->pPrev==0 || p->pPrev->db==p->db );\n  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );\n\n  /* Check for locking consistency */\n  assert( !p->locked || p->wantToLock>0 );\n  assert( p->sharable || p->wantToLock==0 );\n\n  /* We should already hold a lock on the database connection */\n  assert( sqlite3_mutex_held(p->db->mutex) );\n\n  /* Unless the database is sharable and unlocked, then BtShared.db\n  ** should already be set correctly. */\n  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );\n\n  if( !p->sharable ) return;\n  p->wantToLock++;\n  if( p->locked ) return;\n  btreeLockCarefully(p);\n}\n\n/* This is a helper function for sqlite3BtreeLock(). By moving\n** complex, but seldom used logic, out of sqlite3BtreeLock() and\n** into this routine, we avoid unnecessary stack pointer changes\n** and thus help the sqlite3BtreeLock() routine to run much faster\n** in the common case.\n*/\nstatic void SQLITE_NOINLINE btreeLockCarefully(Btree *p){\n  Btree *pLater;\n\n  /* In most cases, we should be able to acquire the lock we\n  ** want without having to go through the ascending lock\n  ** procedure that follows.  Just be sure not to block.\n  */\n  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){\n    p->pBt->db = p->db;\n    p->locked = 1;\n    return;\n  }\n\n  /* To avoid deadlock, first release all locks with a larger\n  ** BtShared address.  Then acquire our lock.  Then reacquire\n  ** the other BtShared locks that we used to hold in ascending\n  ** order.\n  */\n  for(pLater=p->pNext; pLater; pLater=pLater->pNext){\n    assert( pLater->sharable );\n    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );\n    assert( !pLater->locked || pLater->wantToLock>0 );\n    if( pLater->locked ){\n      unlockBtreeMutex(pLater);\n    }\n  }\n  lockBtreeMutex(p);\n  for(pLater=p->pNext; pLater; pLater=pLater->pNext){\n    if( pLater->wantToLock ){\n      lockBtreeMutex(pLater);\n    }\n  }\n}\n\n\n/*\n** Exit the recursive mutex on a Btree.\n*/\nSQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  if( p->sharable ){\n    assert( p->wantToLock>0 );\n    p->wantToLock--;\n    if( p->wantToLock==0 ){\n      unlockBtreeMutex(p);\n    }\n  }\n}\n\n#ifndef NDEBUG\n/*\n** Return true if the BtShared mutex is held on the btree, or if the\n** B-Tree is not marked as sharable.\n**\n** This routine is used only from within assert() statements.\n*/\nSQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){\n  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );\n  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );\n  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );\n  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );\n\n  return (p->sharable==0 || p->locked);\n}\n#endif\n\n\n/*\n** Enter the mutex on every Btree associated with a database\n** connection.  This is needed (for example) prior to parsing\n** a statement since we will be comparing table and column names\n** against all schemas and we do not want those schemas being\n** reset out from under us.\n**\n** There is a corresponding leave-all procedures.\n**\n** Enter the mutexes in accending order by BtShared pointer address\n** to avoid the possibility of deadlock when two threads with\n** two or more btrees in common both try to lock all their btrees\n** at the same instant.\n*/\nstatic void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){\n  int i;\n  int skipOk = 1;\n  Btree *p;\n  assert( sqlite3_mutex_held(db->mutex) );\n  for(i=0; i<db->nDb; i++){\n    p = db->aDb[i].pBt;\n    if( p && p->sharable ){\n      sqlite3BtreeEnter(p);\n      skipOk = 0;\n    }\n  }\n  db->noSharedCache = skipOk;\n}\nSQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){\n  if( db->noSharedCache==0 ) btreeEnterAll(db);\n}\nstatic void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){\n  int i;\n  Btree *p;\n  assert( sqlite3_mutex_held(db->mutex) );\n  for(i=0; i<db->nDb; i++){\n    p = db->aDb[i].pBt;\n    if( p ) sqlite3BtreeLeave(p);\n  }\n}\nSQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){\n  if( db->noSharedCache==0 ) btreeLeaveAll(db);\n}\n\n#ifndef NDEBUG\n/*\n** Return true if the current thread holds the database connection\n** mutex and all required BtShared mutexes.\n**\n** This routine is used inside assert() statements only.\n*/\nSQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){\n  int i;\n  if( !sqlite3_mutex_held(db->mutex) ){\n    return 0;\n  }\n  for(i=0; i<db->nDb; i++){\n    Btree *p;\n    p = db->aDb[i].pBt;\n    if( p && p->sharable &&\n         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){\n      return 0;\n    }\n  }\n  return 1;\n}\n#endif /* NDEBUG */\n\n#ifndef NDEBUG\n/*\n** Return true if the correct mutexes are held for accessing the\n** db->aDb[iDb].pSchema structure.  The mutexes required for schema\n** access are:\n**\n**   (1) The mutex on db\n**   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.\n**\n** If pSchema is not NULL, then iDb is computed from pSchema and\n** db using sqlite3SchemaToIndex().\n*/\nSQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){\n  Btree *p;\n  assert( db!=0 );\n  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);\n  assert( iDb>=0 && iDb<db->nDb );\n  if( !sqlite3_mutex_held(db->mutex) ) return 0;\n  if( iDb==1 ) return 1;\n  p = db->aDb[iDb].pBt;\n  assert( p!=0 );\n  return p->sharable==0 || p->locked==1;\n}\n#endif /* NDEBUG */\n\n#else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */\n/*\n** The following are special cases for mutex enter routines for use\n** in single threaded applications that use shared cache.  Except for\n** these two routines, all mutex operations are no-ops in that case and\n** are null #defines in btree.h.\n**\n** If shared cache is disabled, then all btree mutex routines, including\n** the ones below, are no-ops and are null #defines in btree.h.\n*/\n\nSQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){\n  p->pBt->db = p->db;\n}\nSQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){\n  int i;\n  for(i=0; i<db->nDb; i++){\n    Btree *p = db->aDb[i].pBt;\n    if( p ){\n      p->pBt->db = p->db;\n    }\n  }\n}\n#endif /* if SQLITE_THREADSAFE */\n\n#ifndef SQLITE_OMIT_INCRBLOB\n/*\n** Enter a mutex on a Btree given a cursor owned by that Btree. \n**\n** These entry points are used by incremental I/O only. Enter() is required \n** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not \n** the build is threadsafe. Leave() is only required by threadsafe builds.\n*/\nSQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){\n  sqlite3BtreeEnter(pCur->pBtree);\n}\n# if SQLITE_THREADSAFE\nSQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){\n  sqlite3BtreeLeave(pCur->pBtree);\n}\n# endif\n#endif /* ifndef SQLITE_OMIT_INCRBLOB */\n\n#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */\n\n/************** End of btmutex.c *********************************************/\n/************** Begin file btree.c *******************************************/\n/*\n** 2004 April 6\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file implements an external (disk-based) database using BTrees.\n** See the header comment on \"btreeInt.h\" for additional information.\n** Including a description of file format and an overview of operation.\n*/\n/* #include \"btreeInt.h\" */\n\n/*\n** The header string that appears at the beginning of every\n** SQLite database.\n*/\nstatic const char zMagicHeader[] = SQLITE_FILE_HEADER;\n\n/*\n** Set this global variable to 1 to enable tracing using the TRACE\n** macro.\n*/\n#if 0\nint sqlite3BtreeTrace=1;  /* True to enable tracing */\n# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}\n#else\n# define TRACE(X)\n#endif\n\n/*\n** Extract a 2-byte big-endian integer from an array of unsigned bytes.\n** But if the value is zero, make it 65536.\n**\n** This routine is used to extract the \"offset to cell content area\" value\n** from the header of a btree page.  If the page size is 65536 and the page\n** is empty, the offset should be 65536, but the 2-byte value stores zero.\n** This routine makes the necessary adjustment to 65536.\n*/\n#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)\n\n/*\n** Values passed as the 5th argument to allocateBtreePage()\n*/\n#define BTALLOC_ANY   0           /* Allocate any page */\n#define BTALLOC_EXACT 1           /* Allocate exact page if possible */\n#define BTALLOC_LE    2           /* Allocate any page <= the parameter */\n\n/*\n** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not \n** defined, or 0 if it is. For example:\n**\n**   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);\n*/\n#ifndef SQLITE_OMIT_AUTOVACUUM\n#define IfNotOmitAV(expr) (expr)\n#else\n#define IfNotOmitAV(expr) 0\n#endif\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n/*\n** A list of BtShared objects that are eligible for participation\n** in shared cache.  This variable has file scope during normal builds,\n** but the test harness needs to access it so we make it global for \n** test builds.\n**\n** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.\n*/\n#ifdef SQLITE_TEST\nSQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;\n#else\nstatic BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;\n#endif\n#endif /* SQLITE_OMIT_SHARED_CACHE */\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n/*\n** Enable or disable the shared pager and schema features.\n**\n** This routine has no effect on existing database connections.\n** The shared cache setting effects only future calls to\n** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().\n*/\nSQLITE_API int sqlite3_enable_shared_cache(int enable){\n  sqlite3GlobalConfig.sharedCacheEnabled = enable;\n  return SQLITE_OK;\n}\n#endif\n\n\n\n#ifdef SQLITE_OMIT_SHARED_CACHE\n  /*\n  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),\n  ** and clearAllSharedCacheTableLocks()\n  ** manipulate entries in the BtShared.pLock linked list used to store\n  ** shared-cache table level locks. If the library is compiled with the\n  ** shared-cache feature disabled, then there is only ever one user\n  ** of each BtShared structure and so this locking is not necessary. \n  ** So define the lock related functions as no-ops.\n  */\n  #define querySharedCacheTableLock(a,b,c) SQLITE_OK\n  #define setSharedCacheTableLock(a,b,c) SQLITE_OK\n  #define clearAllSharedCacheTableLocks(a)\n  #define downgradeAllSharedCacheTableLocks(a)\n  #define hasSharedCacheTableLock(a,b,c,d) 1\n  #define hasReadConflicts(a, b) 0\n#endif\n\n/*\n** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single\n** (MemPage*) as an argument. The (MemPage*) must not be NULL.\n**\n** If SQLITE_DEBUG is not defined, then this macro is equivalent to\n** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message\n** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented\n** with the page number and filename associated with the (MemPage*).\n*/\n#ifdef SQLITE_DEBUG\nint corruptPageError(int lineno, MemPage *p){\n  char *zMsg;\n  sqlite3BeginBenignMalloc();\n  zMsg = sqlite3_mprintf(\"database corruption page %d of %s\",\n      (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)\n  );\n  sqlite3EndBenignMalloc();\n  if( zMsg ){\n    sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);\n  }\n  sqlite3_free(zMsg);\n  return SQLITE_CORRUPT_BKPT;\n}\n# define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)\n#else\n# define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)\n#endif\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n\n#ifdef SQLITE_DEBUG\n/*\n**** This function is only used as part of an assert() statement. ***\n**\n** Check to see if pBtree holds the required locks to read or write to the \n** table with root page iRoot.   Return 1 if it does and 0 if not.\n**\n** For example, when writing to a table with root-page iRoot via \n** Btree connection pBtree:\n**\n**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );\n**\n** When writing to an index that resides in a sharable database, the \n** caller should have first obtained a lock specifying the root page of\n** the corresponding table. This makes things a bit more complicated,\n** as this module treats each table as a separate structure. To determine\n** the table corresponding to the index being written, this\n** function has to search through the database schema.\n**\n** Instead of a lock on the table/index rooted at page iRoot, the caller may\n** hold a write-lock on the schema table (root page 1). This is also\n** acceptable.\n*/\nstatic int hasSharedCacheTableLock(\n  Btree *pBtree,         /* Handle that must hold lock */\n  Pgno iRoot,            /* Root page of b-tree */\n  int isIndex,           /* True if iRoot is the root of an index b-tree */\n  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */\n){\n  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;\n  Pgno iTab = 0;\n  BtLock *pLock;\n\n  /* If this database is not shareable, or if the client is reading\n  ** and has the read-uncommitted flag set, then no lock is required. \n  ** Return true immediately.\n  */\n  if( (pBtree->sharable==0)\n   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))\n  ){\n    return 1;\n  }\n\n  /* If the client is reading  or writing an index and the schema is\n  ** not loaded, then it is too difficult to actually check to see if\n  ** the correct locks are held.  So do not bother - just return true.\n  ** This case does not come up very often anyhow.\n  */\n  if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){\n    return 1;\n  }\n\n  /* Figure out the root-page that the lock should be held on. For table\n  ** b-trees, this is just the root page of the b-tree being read or\n  ** written. For index b-trees, it is the root page of the associated\n  ** table.  */\n  if( isIndex ){\n    HashElem *p;\n    int bSeen = 0;\n    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){\n      Index *pIdx = (Index *)sqliteHashData(p);\n      if( pIdx->tnum==(int)iRoot ){\n        if( bSeen ){\n          /* Two or more indexes share the same root page.  There must\n          ** be imposter tables.  So just return true.  The assert is not\n          ** useful in that case. */\n          return 1;\n        }\n        iTab = pIdx->pTable->tnum;\n        bSeen = 1;\n      }\n    }\n  }else{\n    iTab = iRoot;\n  }\n\n  /* Search for the required lock. Either a write-lock on root-page iTab, a \n  ** write-lock on the schema table, or (if the client is reading) a\n  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */\n  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){\n    if( pLock->pBtree==pBtree \n     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))\n     && pLock->eLock>=eLockType \n    ){\n      return 1;\n    }\n  }\n\n  /* Failed to find the required lock. */\n  return 0;\n}\n#endif /* SQLITE_DEBUG */\n\n#ifdef SQLITE_DEBUG\n/*\n**** This function may be used as part of assert() statements only. ****\n**\n** Return true if it would be illegal for pBtree to write into the\n** table or index rooted at iRoot because other shared connections are\n** simultaneously reading that same table or index.\n**\n** It is illegal for pBtree to write if some other Btree object that\n** shares the same BtShared object is currently reading or writing\n** the iRoot table.  Except, if the other Btree object has the\n** read-uncommitted flag set, then it is OK for the other object to\n** have a read cursor.\n**\n** For example, before writing to any part of the table or index\n** rooted at page iRoot, one should call:\n**\n**    assert( !hasReadConflicts(pBtree, iRoot) );\n*/\nstatic int hasReadConflicts(Btree *pBtree, Pgno iRoot){\n  BtCursor *p;\n  for(p=pBtree->pBt->pCursor; p; p=p->pNext){\n    if( p->pgnoRoot==iRoot \n     && p->pBtree!=pBtree\n     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)\n    ){\n      return 1;\n    }\n  }\n  return 0;\n}\n#endif    /* #ifdef SQLITE_DEBUG */\n\n/*\n** Query to see if Btree handle p may obtain a lock of type eLock \n** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return\n** SQLITE_OK if the lock may be obtained (by calling\n** setSharedCacheTableLock()), or SQLITE_LOCKED if not.\n*/\nstatic int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){\n  BtShared *pBt = p->pBt;\n  BtLock *pIter;\n\n  assert( sqlite3BtreeHoldsMutex(p) );\n  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );\n  assert( p->db!=0 );\n  assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );\n  \n  /* If requesting a write-lock, then the Btree must have an open write\n  ** transaction on this file. And, obviously, for this to be so there \n  ** must be an open write transaction on the file itself.\n  */\n  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );\n  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );\n  \n  /* This routine is a no-op if the shared-cache is not enabled */\n  if( !p->sharable ){\n    return SQLITE_OK;\n  }\n\n  /* If some other connection is holding an exclusive lock, the\n  ** requested lock may not be obtained.\n  */\n  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){\n    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);\n    return SQLITE_LOCKED_SHAREDCACHE;\n  }\n\n  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){\n    /* The condition (pIter->eLock!=eLock) in the following if(...) \n    ** statement is a simplification of:\n    **\n    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)\n    **\n    ** since we know that if eLock==WRITE_LOCK, then no other connection\n    ** may hold a WRITE_LOCK on any table in this file (since there can\n    ** only be a single writer).\n    */\n    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );\n    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);\n    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){\n      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);\n      if( eLock==WRITE_LOCK ){\n        assert( p==pBt->pWriter );\n        pBt->btsFlags |= BTS_PENDING;\n      }\n      return SQLITE_LOCKED_SHAREDCACHE;\n    }\n  }\n  return SQLITE_OK;\n}\n#endif /* !SQLITE_OMIT_SHARED_CACHE */\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n/*\n** Add a lock on the table with root-page iTable to the shared-btree used\n** by Btree handle p. Parameter eLock must be either READ_LOCK or \n** WRITE_LOCK.\n**\n** This function assumes the following:\n**\n**   (a) The specified Btree object p is connected to a sharable\n**       database (one with the BtShared.sharable flag set), and\n**\n**   (b) No other Btree objects hold a lock that conflicts\n**       with the requested lock (i.e. querySharedCacheTableLock() has\n**       already been called and returned SQLITE_OK).\n**\n** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM \n** is returned if a malloc attempt fails.\n*/\nstatic int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){\n  BtShared *pBt = p->pBt;\n  BtLock *pLock = 0;\n  BtLock *pIter;\n\n  assert( sqlite3BtreeHoldsMutex(p) );\n  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );\n  assert( p->db!=0 );\n\n  /* A connection with the read-uncommitted flag set will never try to\n  ** obtain a read-lock using this function. The only read-lock obtained\n  ** by a connection in read-uncommitted mode is on the sqlite_master \n  ** table, and that lock is obtained in BtreeBeginTrans().  */\n  assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );\n\n  /* This function should only be called on a sharable b-tree after it \n  ** has been determined that no other b-tree holds a conflicting lock.  */\n  assert( p->sharable );\n  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );\n\n  /* First search the list for an existing lock on this table. */\n  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){\n    if( pIter->iTable==iTable && pIter->pBtree==p ){\n      pLock = pIter;\n      break;\n    }\n  }\n\n  /* If the above search did not find a BtLock struct associating Btree p\n  ** with table iTable, allocate one and link it into the list.\n  */\n  if( !pLock ){\n    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));\n    if( !pLock ){\n      return SQLITE_NOMEM_BKPT;\n    }\n    pLock->iTable = iTable;\n    pLock->pBtree = p;\n    pLock->pNext = pBt->pLock;\n    pBt->pLock = pLock;\n  }\n\n  /* Set the BtLock.eLock variable to the maximum of the current lock\n  ** and the requested lock. This means if a write-lock was already held\n  ** and a read-lock requested, we don't incorrectly downgrade the lock.\n  */\n  assert( WRITE_LOCK>READ_LOCK );\n  if( eLock>pLock->eLock ){\n    pLock->eLock = eLock;\n  }\n\n  return SQLITE_OK;\n}\n#endif /* !SQLITE_OMIT_SHARED_CACHE */\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n/*\n** Release all the table locks (locks obtained via calls to\n** the setSharedCacheTableLock() procedure) held by Btree object p.\n**\n** This function assumes that Btree p has an open read or write \n** transaction. If it does not, then the BTS_PENDING flag\n** may be incorrectly cleared.\n*/\nstatic void clearAllSharedCacheTableLocks(Btree *p){\n  BtShared *pBt = p->pBt;\n  BtLock **ppIter = &pBt->pLock;\n\n  assert( sqlite3BtreeHoldsMutex(p) );\n  assert( p->sharable || 0==*ppIter );\n  assert( p->inTrans>0 );\n\n  while( *ppIter ){\n    BtLock *pLock = *ppIter;\n    assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );\n    assert( pLock->pBtree->inTrans>=pLock->eLock );\n    if( pLock->pBtree==p ){\n      *ppIter = pLock->pNext;\n      assert( pLock->iTable!=1 || pLock==&p->lock );\n      if( pLock->iTable!=1 ){\n        sqlite3_free(pLock);\n      }\n    }else{\n      ppIter = &pLock->pNext;\n    }\n  }\n\n  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );\n  if( pBt->pWriter==p ){\n    pBt->pWriter = 0;\n    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);\n  }else if( pBt->nTransaction==2 ){\n    /* This function is called when Btree p is concluding its \n    ** transaction. If there currently exists a writer, and p is not\n    ** that writer, then the number of locks held by connections other\n    ** than the writer must be about to drop to zero. In this case\n    ** set the BTS_PENDING flag to 0.\n    **\n    ** If there is not currently a writer, then BTS_PENDING must\n    ** be zero already. So this next line is harmless in that case.\n    */\n    pBt->btsFlags &= ~BTS_PENDING;\n  }\n}\n\n/*\n** This function changes all write-locks held by Btree p into read-locks.\n*/\nstatic void downgradeAllSharedCacheTableLocks(Btree *p){\n  BtShared *pBt = p->pBt;\n  if( pBt->pWriter==p ){\n    BtLock *pLock;\n    pBt->pWriter = 0;\n    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);\n    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){\n      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );\n      pLock->eLock = READ_LOCK;\n    }\n  }\n}\n\n#endif /* SQLITE_OMIT_SHARED_CACHE */\n\nstatic void releasePage(MemPage *pPage);         /* Forward reference */\nstatic void releasePageOne(MemPage *pPage);      /* Forward reference */\nstatic void releasePageNotNull(MemPage *pPage);  /* Forward reference */\n\n/*\n***** This routine is used inside of assert() only ****\n**\n** Verify that the cursor holds the mutex on its BtShared\n*/\n#ifdef SQLITE_DEBUG\nstatic int cursorHoldsMutex(BtCursor *p){\n  return sqlite3_mutex_held(p->pBt->mutex);\n}\n\n/* Verify that the cursor and the BtShared agree about what is the current\n** database connetion. This is important in shared-cache mode. If the database \n** connection pointers get out-of-sync, it is possible for routines like\n** btreeInitPage() to reference an stale connection pointer that references a\n** a connection that has already closed.  This routine is used inside assert()\n** statements only and for the purpose of double-checking that the btree code\n** does keep the database connection pointers up-to-date.\n*/\nstatic int cursorOwnsBtShared(BtCursor *p){\n  assert( cursorHoldsMutex(p) );\n  return (p->pBtree->db==p->pBt->db);\n}\n#endif\n\n/*\n** Invalidate the overflow cache of the cursor passed as the first argument.\n** on the shared btree structure pBt.\n*/\n#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)\n\n/*\n** Invalidate the overflow page-list cache for all cursors opened\n** on the shared btree structure pBt.\n*/\nstatic void invalidateAllOverflowCache(BtShared *pBt){\n  BtCursor *p;\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  for(p=pBt->pCursor; p; p=p->pNext){\n    invalidateOverflowCache(p);\n  }\n}\n\n#ifndef SQLITE_OMIT_INCRBLOB\n/*\n** This function is called before modifying the contents of a table\n** to invalidate any incrblob cursors that are open on the\n** row or one of the rows being modified.\n**\n** If argument isClearTable is true, then the entire contents of the\n** table is about to be deleted. In this case invalidate all incrblob\n** cursors open on any row within the table with root-page pgnoRoot.\n**\n** Otherwise, if argument isClearTable is false, then the row with\n** rowid iRow is being replaced or deleted. In this case invalidate\n** only those incrblob cursors open on that specific row.\n*/\nstatic void invalidateIncrblobCursors(\n  Btree *pBtree,          /* The database file to check */\n  Pgno pgnoRoot,          /* The table that might be changing */\n  i64 iRow,               /* The rowid that might be changing */\n  int isClearTable        /* True if all rows are being deleted */\n){\n  BtCursor *p;\n  if( pBtree->hasIncrblobCur==0 ) return;\n  assert( sqlite3BtreeHoldsMutex(pBtree) );\n  pBtree->hasIncrblobCur = 0;\n  for(p=pBtree->pBt->pCursor; p; p=p->pNext){\n    if( (p->curFlags & BTCF_Incrblob)!=0 ){\n      pBtree->hasIncrblobCur = 1;\n      if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){\n        p->eState = CURSOR_INVALID;\n      }\n    }\n  }\n}\n\n#else\n  /* Stub function when INCRBLOB is omitted */\n  #define invalidateIncrblobCursors(w,x,y,z)\n#endif /* SQLITE_OMIT_INCRBLOB */\n\n/*\n** Set bit pgno of the BtShared.pHasContent bitvec. This is called \n** when a page that previously contained data becomes a free-list leaf \n** page.\n**\n** The BtShared.pHasContent bitvec exists to work around an obscure\n** bug caused by the interaction of two useful IO optimizations surrounding\n** free-list leaf pages:\n**\n**   1) When all data is deleted from a page and the page becomes\n**      a free-list leaf page, the page is not written to the database\n**      (as free-list leaf pages contain no meaningful data). Sometimes\n**      such a page is not even journalled (as it will not be modified,\n**      why bother journalling it?).\n**\n**   2) When a free-list leaf page is reused, its content is not read\n**      from the database or written to the journal file (why should it\n**      be, if it is not at all meaningful?).\n**\n** By themselves, these optimizations work fine and provide a handy\n** performance boost to bulk delete or insert operations. However, if\n** a page is moved to the free-list and then reused within the same\n** transaction, a problem comes up. If the page is not journalled when\n** it is moved to the free-list and it is also not journalled when it\n** is extracted from the free-list and reused, then the original data\n** may be lost. In the event of a rollback, it may not be possible\n** to restore the database to its original configuration.\n**\n** The solution is the BtShared.pHasContent bitvec. Whenever a page is \n** moved to become a free-list leaf page, the corresponding bit is\n** set in the bitvec. Whenever a leaf page is extracted from the free-list,\n** optimization 2 above is omitted if the corresponding bit is already\n** set in BtShared.pHasContent. The contents of the bitvec are cleared\n** at the end of every transaction.\n*/\nstatic int btreeSetHasContent(BtShared *pBt, Pgno pgno){\n  int rc = SQLITE_OK;\n  if( !pBt->pHasContent ){\n    assert( pgno<=pBt->nPage );\n    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);\n    if( !pBt->pHasContent ){\n      rc = SQLITE_NOMEM_BKPT;\n    }\n  }\n  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){\n    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);\n  }\n  return rc;\n}\n\n/*\n** Query the BtShared.pHasContent vector.\n**\n** This function is called when a free-list leaf page is removed from the\n** free-list for reuse. It returns false if it is safe to retrieve the\n** page from the pager layer with the 'no-content' flag set. True otherwise.\n*/\nstatic int btreeGetHasContent(BtShared *pBt, Pgno pgno){\n  Bitvec *p = pBt->pHasContent;\n  return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno));\n}\n\n/*\n** Clear (destroy) the BtShared.pHasContent bitvec. This should be\n** invoked at the conclusion of each write-transaction.\n*/\nstatic void btreeClearHasContent(BtShared *pBt){\n  sqlite3BitvecDestroy(pBt->pHasContent);\n  pBt->pHasContent = 0;\n}\n\n/*\n** Release all of the apPage[] pages for a cursor.\n*/\nstatic void btreeReleaseAllCursorPages(BtCursor *pCur){\n  int i;\n  if( pCur->iPage>=0 ){\n    for(i=0; i<pCur->iPage; i++){\n      releasePageNotNull(pCur->apPage[i]);\n    }\n    releasePageNotNull(pCur->pPage);\n    pCur->iPage = -1;\n  }\n}\n\n/*\n** The cursor passed as the only argument must point to a valid entry\n** when this function is called (i.e. have eState==CURSOR_VALID). This\n** function saves the current cursor key in variables pCur->nKey and\n** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error \n** code otherwise.\n**\n** If the cursor is open on an intkey table, then the integer key\n** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to\n** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is \n** set to point to a malloced buffer pCur->nKey bytes in size containing \n** the key.\n*/\nstatic int saveCursorKey(BtCursor *pCur){\n  int rc = SQLITE_OK;\n  assert( CURSOR_VALID==pCur->eState );\n  assert( 0==pCur->pKey );\n  assert( cursorHoldsMutex(pCur) );\n\n  if( pCur->curIntKey ){\n    /* Only the rowid is required for a table btree */\n    pCur->nKey = sqlite3BtreeIntegerKey(pCur);\n  }else{\n    /* For an index btree, save the complete key content. It is possible\n    ** that the current key is corrupt. In that case, it is possible that\n    ** the sqlite3VdbeRecordUnpack() function may overread the buffer by\n    ** up to the size of 1 varint plus 1 8-byte value when the cursor \n    ** position is restored. Hence the 17 bytes of padding allocated \n    ** below. */\n    void *pKey;\n    pCur->nKey = sqlite3BtreePayloadSize(pCur);\n    pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );\n    if( pKey ){\n      rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);\n      if( rc==SQLITE_OK ){\n        memset(((u8*)pKey)+pCur->nKey, 0, 9+8);\n        pCur->pKey = pKey;\n      }else{\n        sqlite3_free(pKey);\n      }\n    }else{\n      rc = SQLITE_NOMEM_BKPT;\n    }\n  }\n  assert( !pCur->curIntKey || !pCur->pKey );\n  return rc;\n}\n\n/*\n** Save the current cursor position in the variables BtCursor.nKey \n** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.\n**\n** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)\n** prior to calling this routine.  \n*/\nstatic int saveCursorPosition(BtCursor *pCur){\n  int rc;\n\n  assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );\n  assert( 0==pCur->pKey );\n  assert( cursorHoldsMutex(pCur) );\n\n  if( pCur->curFlags & BTCF_Pinned ){\n    return SQLITE_CONSTRAINT_PINNED;\n  }\n  if( pCur->eState==CURSOR_SKIPNEXT ){\n    pCur->eState = CURSOR_VALID;\n  }else{\n    pCur->skipNext = 0;\n  }\n\n  rc = saveCursorKey(pCur);\n  if( rc==SQLITE_OK ){\n    btreeReleaseAllCursorPages(pCur);\n    pCur->eState = CURSOR_REQUIRESEEK;\n  }\n\n  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);\n  return rc;\n}\n\n/* Forward reference */\nstatic int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);\n\n/*\n** Save the positions of all cursors (except pExcept) that are open on\n** the table with root-page iRoot.  \"Saving the cursor position\" means that\n** the location in the btree is remembered in such a way that it can be\n** moved back to the same spot after the btree has been modified.  This\n** routine is called just before cursor pExcept is used to modify the\n** table, for example in BtreeDelete() or BtreeInsert().\n**\n** If there are two or more cursors on the same btree, then all such \n** cursors should have their BTCF_Multiple flag set.  The btreeCursor()\n** routine enforces that rule.  This routine only needs to be called in\n** the uncommon case when pExpect has the BTCF_Multiple flag set.\n**\n** If pExpect!=NULL and if no other cursors are found on the same root-page,\n** then the BTCF_Multiple flag on pExpect is cleared, to avoid another\n** pointless call to this routine.\n**\n** Implementation note:  This routine merely checks to see if any cursors\n** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)\n** event that cursors are in need to being saved.\n*/\nstatic int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){\n  BtCursor *p;\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( pExcept==0 || pExcept->pBt==pBt );\n  for(p=pBt->pCursor; p; p=p->pNext){\n    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;\n  }\n  if( p ) return saveCursorsOnList(p, iRoot, pExcept);\n  if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;\n  return SQLITE_OK;\n}\n\n/* This helper routine to saveAllCursors does the actual work of saving\n** the cursors if and when a cursor is found that actually requires saving.\n** The common case is that no cursors need to be saved, so this routine is\n** broken out from its caller to avoid unnecessary stack pointer movement.\n*/\nstatic int SQLITE_NOINLINE saveCursorsOnList(\n  BtCursor *p,         /* The first cursor that needs saving */\n  Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */\n  BtCursor *pExcept    /* Do not save this cursor */\n){\n  do{\n    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){\n      if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){\n        int rc = saveCursorPosition(p);\n        if( SQLITE_OK!=rc ){\n          return rc;\n        }\n      }else{\n        testcase( p->iPage>=0 );\n        btreeReleaseAllCursorPages(p);\n      }\n    }\n    p = p->pNext;\n  }while( p );\n  return SQLITE_OK;\n}\n\n/*\n** Clear the current cursor position.\n*/\nSQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){\n  assert( cursorHoldsMutex(pCur) );\n  sqlite3_free(pCur->pKey);\n  pCur->pKey = 0;\n  pCur->eState = CURSOR_INVALID;\n}\n\n/*\n** In this version of BtreeMoveto, pKey is a packed index record\n** such as is generated by the OP_MakeRecord opcode.  Unpack the\n** record and then call BtreeMovetoUnpacked() to do the work.\n*/\nstatic int btreeMoveto(\n  BtCursor *pCur,     /* Cursor open on the btree to be searched */\n  const void *pKey,   /* Packed key if the btree is an index */\n  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */\n  int bias,           /* Bias search to the high end */\n  int *pRes           /* Write search results here */\n){\n  int rc;                    /* Status code */\n  UnpackedRecord *pIdxKey;   /* Unpacked index key */\n\n  if( pKey ){\n    KeyInfo *pKeyInfo = pCur->pKeyInfo;\n    assert( nKey==(i64)(int)nKey );\n    pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);\n    if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;\n    sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);\n    if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){\n      rc = SQLITE_CORRUPT_BKPT;\n      goto moveto_done;\n    }\n  }else{\n    pIdxKey = 0;\n  }\n  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);\nmoveto_done:\n  if( pIdxKey ){\n    sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);\n  }\n  return rc;\n}\n\n/*\n** Restore the cursor to the position it was in (or as close to as possible)\n** when saveCursorPosition() was called. Note that this call deletes the \n** saved position info stored by saveCursorPosition(), so there can be\n** at most one effective restoreCursorPosition() call after each \n** saveCursorPosition().\n*/\nstatic int btreeRestoreCursorPosition(BtCursor *pCur){\n  int rc;\n  int skipNext = 0;\n  assert( cursorOwnsBtShared(pCur) );\n  assert( pCur->eState>=CURSOR_REQUIRESEEK );\n  if( pCur->eState==CURSOR_FAULT ){\n    return pCur->skipNext;\n  }\n  pCur->eState = CURSOR_INVALID;\n  if( sqlite3FaultSim(410) ){\n    rc = SQLITE_IOERR;\n  }else{\n    rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);\n  }\n  if( rc==SQLITE_OK ){\n    sqlite3_free(pCur->pKey);\n    pCur->pKey = 0;\n    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );\n    if( skipNext ) pCur->skipNext = skipNext;\n    if( pCur->skipNext && pCur->eState==CURSOR_VALID ){\n      pCur->eState = CURSOR_SKIPNEXT;\n    }\n  }\n  return rc;\n}\n\n#define restoreCursorPosition(p) \\\n  (p->eState>=CURSOR_REQUIRESEEK ? \\\n         btreeRestoreCursorPosition(p) : \\\n         SQLITE_OK)\n\n/*\n** Determine whether or not a cursor has moved from the position where\n** it was last placed, or has been invalidated for any other reason.\n** Cursors can move when the row they are pointing at is deleted out\n** from under them, for example.  Cursor might also move if a btree\n** is rebalanced.\n**\n** Calling this routine with a NULL cursor pointer returns false.\n**\n** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor\n** back to where it ought to be if this routine returns true.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){\n  assert( EIGHT_BYTE_ALIGNMENT(pCur)\n       || pCur==sqlite3BtreeFakeValidCursor() );\n  assert( offsetof(BtCursor, eState)==0 );\n  assert( sizeof(pCur->eState)==1 );\n  return CURSOR_VALID != *(u8*)pCur;\n}\n\n/*\n** Return a pointer to a fake BtCursor object that will always answer\n** false to the sqlite3BtreeCursorHasMoved() routine above.  The fake\n** cursor returned must not be used with any other Btree interface.\n*/\nSQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void){\n  static u8 fakeCursor = CURSOR_VALID;\n  assert( offsetof(BtCursor, eState)==0 );\n  return (BtCursor*)&fakeCursor;\n}\n\n/*\n** This routine restores a cursor back to its original position after it\n** has been moved by some outside activity (such as a btree rebalance or\n** a row having been deleted out from under the cursor).  \n**\n** On success, the *pDifferentRow parameter is false if the cursor is left\n** pointing at exactly the same row.  *pDifferntRow is the row the cursor\n** was pointing to has been deleted, forcing the cursor to point to some\n** nearby row.\n**\n** This routine should only be called for a cursor that just returned\n** TRUE from sqlite3BtreeCursorHasMoved().\n*/\nSQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){\n  int rc;\n\n  assert( pCur!=0 );\n  assert( pCur->eState!=CURSOR_VALID );\n  rc = restoreCursorPosition(pCur);\n  if( rc ){\n    *pDifferentRow = 1;\n    return rc;\n  }\n  if( pCur->eState!=CURSOR_VALID ){\n    *pDifferentRow = 1;\n  }else{\n    *pDifferentRow = 0;\n  }\n  return SQLITE_OK;\n}\n\n#ifdef SQLITE_ENABLE_CURSOR_HINTS\n/*\n** Provide hints to the cursor.  The particular hint given (and the type\n** and number of the varargs parameters) is determined by the eHintType\n** parameter.  See the definitions of the BTREE_HINT_* macros for details.\n*/\nSQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){\n  /* Used only by system that substitute their own storage engine */\n}\n#endif\n\n/*\n** Provide flag hints to the cursor.\n*/\nSQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){\n  assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );\n  pCur->hints = x;\n}\n\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n/*\n** Given a page number of a regular database page, return the page\n** number for the pointer-map page that contains the entry for the\n** input page number.\n**\n** Return 0 (not a valid page) for pgno==1 since there is\n** no pointer map associated with page 1.  The integrity_check logic\n** requires that ptrmapPageno(*,1)!=1.\n*/\nstatic Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){\n  int nPagesPerMapPage;\n  Pgno iPtrMap, ret;\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  if( pgno<2 ) return 0;\n  nPagesPerMapPage = (pBt->usableSize/5)+1;\n  iPtrMap = (pgno-2)/nPagesPerMapPage;\n  ret = (iPtrMap*nPagesPerMapPage) + 2; \n  if( ret==PENDING_BYTE_PAGE(pBt) ){\n    ret++;\n  }\n  return ret;\n}\n\n/*\n** Write an entry into the pointer map.\n**\n** This routine updates the pointer map entry for page number 'key'\n** so that it maps to type 'eType' and parent page number 'pgno'.\n**\n** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is\n** a no-op.  If an error occurs, the appropriate error code is written\n** into *pRC.\n*/\nstatic void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){\n  DbPage *pDbPage;  /* The pointer map page */\n  u8 *pPtrmap;      /* The pointer map data */\n  Pgno iPtrmap;     /* The pointer map page number */\n  int offset;       /* Offset in pointer map page */\n  int rc;           /* Return code from subfunctions */\n\n  if( *pRC ) return;\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  /* The master-journal page number must never be used as a pointer map page */\n  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );\n\n  assert( pBt->autoVacuum );\n  if( key==0 ){\n    *pRC = SQLITE_CORRUPT_BKPT;\n    return;\n  }\n  iPtrmap = PTRMAP_PAGENO(pBt, key);\n  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);\n  if( rc!=SQLITE_OK ){\n    *pRC = rc;\n    return;\n  }\n  if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){\n    /* The first byte of the extra data is the MemPage.isInit byte.\n    ** If that byte is set, it means this page is also being used\n    ** as a btree page. */\n    *pRC = SQLITE_CORRUPT_BKPT;\n    goto ptrmap_exit;\n  }\n  offset = PTRMAP_PTROFFSET(iPtrmap, key);\n  if( offset<0 ){\n    *pRC = SQLITE_CORRUPT_BKPT;\n    goto ptrmap_exit;\n  }\n  assert( offset <= (int)pBt->usableSize-5 );\n  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);\n\n  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){\n    TRACE((\"PTRMAP_UPDATE: %d->(%d,%d)\\n\", key, eType, parent));\n    *pRC= rc = sqlite3PagerWrite(pDbPage);\n    if( rc==SQLITE_OK ){\n      pPtrmap[offset] = eType;\n      put4byte(&pPtrmap[offset+1], parent);\n    }\n  }\n\nptrmap_exit:\n  sqlite3PagerUnref(pDbPage);\n}\n\n/*\n** Read an entry from the pointer map.\n**\n** This routine retrieves the pointer map entry for page 'key', writing\n** the type and parent page number to *pEType and *pPgno respectively.\n** An error code is returned if something goes wrong, otherwise SQLITE_OK.\n*/\nstatic int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){\n  DbPage *pDbPage;   /* The pointer map page */\n  int iPtrmap;       /* Pointer map page index */\n  u8 *pPtrmap;       /* Pointer map page data */\n  int offset;        /* Offset of entry in pointer map */\n  int rc;\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n\n  iPtrmap = PTRMAP_PAGENO(pBt, key);\n  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);\n  if( rc!=0 ){\n    return rc;\n  }\n  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);\n\n  offset = PTRMAP_PTROFFSET(iPtrmap, key);\n  if( offset<0 ){\n    sqlite3PagerUnref(pDbPage);\n    return SQLITE_CORRUPT_BKPT;\n  }\n  assert( offset <= (int)pBt->usableSize-5 );\n  assert( pEType!=0 );\n  *pEType = pPtrmap[offset];\n  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);\n\n  sqlite3PagerUnref(pDbPage);\n  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);\n  return SQLITE_OK;\n}\n\n#else /* if defined SQLITE_OMIT_AUTOVACUUM */\n  #define ptrmapPut(w,x,y,z,rc)\n  #define ptrmapGet(w,x,y,z) SQLITE_OK\n  #define ptrmapPutOvflPtr(x, y, z, rc)\n#endif\n\n/*\n** Given a btree page and a cell index (0 means the first cell on\n** the page, 1 means the second cell, and so forth) return a pointer\n** to the cell content.\n**\n** findCellPastPtr() does the same except it skips past the initial\n** 4-byte child pointer found on interior pages, if there is one.\n**\n** This routine works only for pages that do not contain overflow cells.\n*/\n#define findCell(P,I) \\\n  ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))\n#define findCellPastPtr(P,I) \\\n  ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))\n\n\n/*\n** This is common tail processing for btreeParseCellPtr() and\n** btreeParseCellPtrIndex() for the case when the cell does not fit entirely\n** on a single B-tree page.  Make necessary adjustments to the CellInfo\n** structure.\n*/\nstatic SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(\n  MemPage *pPage,         /* Page containing the cell */\n  u8 *pCell,              /* Pointer to the cell text. */\n  CellInfo *pInfo         /* Fill in this structure */\n){\n  /* If the payload will not fit completely on the local page, we have\n  ** to decide how much to store locally and how much to spill onto\n  ** overflow pages.  The strategy is to minimize the amount of unused\n  ** space on overflow pages while keeping the amount of local storage\n  ** in between minLocal and maxLocal.\n  **\n  ** Warning:  changing the way overflow payload is distributed in any\n  ** way will result in an incompatible file format.\n  */\n  int minLocal;  /* Minimum amount of payload held locally */\n  int maxLocal;  /* Maximum amount of payload held locally */\n  int surplus;   /* Overflow payload available for local storage */\n\n  minLocal = pPage->minLocal;\n  maxLocal = pPage->maxLocal;\n  surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);\n  testcase( surplus==maxLocal );\n  testcase( surplus==maxLocal+1 );\n  if( surplus <= maxLocal ){\n    pInfo->nLocal = (u16)surplus;\n  }else{\n    pInfo->nLocal = (u16)minLocal;\n  }\n  pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;\n}\n\n/*\n** The following routines are implementations of the MemPage.xParseCell()\n** method.\n**\n** Parse a cell content block and fill in the CellInfo structure.\n**\n** btreeParseCellPtr()        =>   table btree leaf nodes\n** btreeParseCellNoPayload()  =>   table btree internal nodes\n** btreeParseCellPtrIndex()   =>   index btree nodes\n**\n** There is also a wrapper function btreeParseCell() that works for\n** all MemPage types and that references the cell by index rather than\n** by pointer.\n*/\nstatic void btreeParseCellPtrNoPayload(\n  MemPage *pPage,         /* Page containing the cell */\n  u8 *pCell,              /* Pointer to the cell text. */\n  CellInfo *pInfo         /* Fill in this structure */\n){\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( pPage->leaf==0 );\n  assert( pPage->childPtrSize==4 );\n#ifndef SQLITE_DEBUG\n  UNUSED_PARAMETER(pPage);\n#endif\n  pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);\n  pInfo->nPayload = 0;\n  pInfo->nLocal = 0;\n  pInfo->pPayload = 0;\n  return;\n}\nstatic void btreeParseCellPtr(\n  MemPage *pPage,         /* Page containing the cell */\n  u8 *pCell,              /* Pointer to the cell text. */\n  CellInfo *pInfo         /* Fill in this structure */\n){\n  u8 *pIter;              /* For scanning through pCell */\n  u32 nPayload;           /* Number of bytes of cell payload */\n  u64 iKey;               /* Extracted Key value */\n\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( pPage->leaf==0 || pPage->leaf==1 );\n  assert( pPage->intKeyLeaf );\n  assert( pPage->childPtrSize==0 );\n  pIter = pCell;\n\n  /* The next block of code is equivalent to:\n  **\n  **     pIter += getVarint32(pIter, nPayload);\n  **\n  ** The code is inlined to avoid a function call.\n  */\n  nPayload = *pIter;\n  if( nPayload>=0x80 ){\n    u8 *pEnd = &pIter[8];\n    nPayload &= 0x7f;\n    do{\n      nPayload = (nPayload<<7) | (*++pIter & 0x7f);\n    }while( (*pIter)>=0x80 && pIter<pEnd );\n  }\n  pIter++;\n\n  /* The next block of code is equivalent to:\n  **\n  **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);\n  **\n  ** The code is inlined to avoid a function call.\n  */\n  iKey = *pIter;\n  if( iKey>=0x80 ){\n    u8 *pEnd = &pIter[7];\n    iKey &= 0x7f;\n    while(1){\n      iKey = (iKey<<7) | (*++pIter & 0x7f);\n      if( (*pIter)<0x80 ) break;\n      if( pIter>=pEnd ){\n        iKey = (iKey<<8) | *++pIter;\n        break;\n      }\n    }\n  }\n  pIter++;\n\n  pInfo->nKey = *(i64*)&iKey;\n  pInfo->nPayload = nPayload;\n  pInfo->pPayload = pIter;\n  testcase( nPayload==pPage->maxLocal );\n  testcase( nPayload==pPage->maxLocal+1 );\n  if( nPayload<=pPage->maxLocal ){\n    /* This is the (easy) common case where the entire payload fits\n    ** on the local page.  No overflow is required.\n    */\n    pInfo->nSize = nPayload + (u16)(pIter - pCell);\n    if( pInfo->nSize<4 ) pInfo->nSize = 4;\n    pInfo->nLocal = (u16)nPayload;\n  }else{\n    btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);\n  }\n}\nstatic void btreeParseCellPtrIndex(\n  MemPage *pPage,         /* Page containing the cell */\n  u8 *pCell,              /* Pointer to the cell text. */\n  CellInfo *pInfo         /* Fill in this structure */\n){\n  u8 *pIter;              /* For scanning through pCell */\n  u32 nPayload;           /* Number of bytes of cell payload */\n\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( pPage->leaf==0 || pPage->leaf==1 );\n  assert( pPage->intKeyLeaf==0 );\n  pIter = pCell + pPage->childPtrSize;\n  nPayload = *pIter;\n  if( nPayload>=0x80 ){\n    u8 *pEnd = &pIter[8];\n    nPayload &= 0x7f;\n    do{\n      nPayload = (nPayload<<7) | (*++pIter & 0x7f);\n    }while( *(pIter)>=0x80 && pIter<pEnd );\n  }\n  pIter++;\n  pInfo->nKey = nPayload;\n  pInfo->nPayload = nPayload;\n  pInfo->pPayload = pIter;\n  testcase( nPayload==pPage->maxLocal );\n  testcase( nPayload==pPage->maxLocal+1 );\n  if( nPayload<=pPage->maxLocal ){\n    /* This is the (easy) common case where the entire payload fits\n    ** on the local page.  No overflow is required.\n    */\n    pInfo->nSize = nPayload + (u16)(pIter - pCell);\n    if( pInfo->nSize<4 ) pInfo->nSize = 4;\n    pInfo->nLocal = (u16)nPayload;\n  }else{\n    btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);\n  }\n}\nstatic void btreeParseCell(\n  MemPage *pPage,         /* Page containing the cell */\n  int iCell,              /* The cell index.  First cell is 0 */\n  CellInfo *pInfo         /* Fill in this structure */\n){\n  pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);\n}\n\n/*\n** The following routines are implementations of the MemPage.xCellSize\n** method.\n**\n** Compute the total number of bytes that a Cell needs in the cell\n** data area of the btree-page.  The return number includes the cell\n** data header and the local payload, but not any overflow page or\n** the space used by the cell pointer.\n**\n** cellSizePtrNoPayload()    =>   table internal nodes\n** cellSizePtr()             =>   all index nodes & table leaf nodes\n*/\nstatic u16 cellSizePtr(MemPage *pPage, u8 *pCell){\n  u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */\n  u8 *pEnd;                                /* End mark for a varint */\n  u32 nSize;                               /* Size value to return */\n\n#ifdef SQLITE_DEBUG\n  /* The value returned by this function should always be the same as\n  ** the (CellInfo.nSize) value found by doing a full parse of the\n  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of\n  ** this function verifies that this invariant is not violated. */\n  CellInfo debuginfo;\n  pPage->xParseCell(pPage, pCell, &debuginfo);\n#endif\n\n  nSize = *pIter;\n  if( nSize>=0x80 ){\n    pEnd = &pIter[8];\n    nSize &= 0x7f;\n    do{\n      nSize = (nSize<<7) | (*++pIter & 0x7f);\n    }while( *(pIter)>=0x80 && pIter<pEnd );\n  }\n  pIter++;\n  if( pPage->intKey ){\n    /* pIter now points at the 64-bit integer key value, a variable length \n    ** integer. The following block moves pIter to point at the first byte\n    ** past the end of the key value. */\n    pEnd = &pIter[9];\n    while( (*pIter++)&0x80 && pIter<pEnd );\n  }\n  testcase( nSize==pPage->maxLocal );\n  testcase( nSize==pPage->maxLocal+1 );\n  if( nSize<=pPage->maxLocal ){\n    nSize += (u32)(pIter - pCell);\n    if( nSize<4 ) nSize = 4;\n  }else{\n    int minLocal = pPage->minLocal;\n    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);\n    testcase( nSize==pPage->maxLocal );\n    testcase( nSize==pPage->maxLocal+1 );\n    if( nSize>pPage->maxLocal ){\n      nSize = minLocal;\n    }\n    nSize += 4 + (u16)(pIter - pCell);\n  }\n  assert( nSize==debuginfo.nSize || CORRUPT_DB );\n  return (u16)nSize;\n}\nstatic u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){\n  u8 *pIter = pCell + 4; /* For looping over bytes of pCell */\n  u8 *pEnd;              /* End mark for a varint */\n\n#ifdef SQLITE_DEBUG\n  /* The value returned by this function should always be the same as\n  ** the (CellInfo.nSize) value found by doing a full parse of the\n  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of\n  ** this function verifies that this invariant is not violated. */\n  CellInfo debuginfo;\n  pPage->xParseCell(pPage, pCell, &debuginfo);\n#else\n  UNUSED_PARAMETER(pPage);\n#endif\n\n  assert( pPage->childPtrSize==4 );\n  pEnd = pIter + 9;\n  while( (*pIter++)&0x80 && pIter<pEnd );\n  assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );\n  return (u16)(pIter - pCell);\n}\n\n\n#ifdef SQLITE_DEBUG\n/* This variation on cellSizePtr() is used inside of assert() statements\n** only. */\nstatic u16 cellSize(MemPage *pPage, int iCell){\n  return pPage->xCellSize(pPage, findCell(pPage, iCell));\n}\n#endif\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n/*\n** The cell pCell is currently part of page pSrc but will ultimately be part\n** of pPage.  (pSrc and pPager are often the same.)  If pCell contains a\n** pointer to an overflow page, insert an entry into the pointer-map for\n** the overflow page that will be valid after pCell has been moved to pPage.\n*/\nstatic void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){\n  CellInfo info;\n  if( *pRC ) return;\n  assert( pCell!=0 );\n  pPage->xParseCell(pPage, pCell, &info);\n  if( info.nLocal<info.nPayload ){\n    Pgno ovfl;\n    if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){\n      testcase( pSrc!=pPage );\n      *pRC = SQLITE_CORRUPT_BKPT;\n      return;\n    }\n    ovfl = get4byte(&pCell[info.nSize-4]);\n    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);\n  }\n}\n#endif\n\n\n/*\n** Defragment the page given. This routine reorganizes cells within the\n** page so that there are no free-blocks on the free-block list.\n**\n** Parameter nMaxFrag is the maximum amount of fragmented space that may be\n** present in the page after this routine returns.\n**\n** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a\n** b-tree page so that there are no freeblocks or fragment bytes, all\n** unused bytes are contained in the unallocated space region, and all\n** cells are packed tightly at the end of the page.\n*/\nstatic int defragmentPage(MemPage *pPage, int nMaxFrag){\n  int i;                     /* Loop counter */\n  int pc;                    /* Address of the i-th cell */\n  int hdr;                   /* Offset to the page header */\n  int size;                  /* Size of a cell */\n  int usableSize;            /* Number of usable bytes on a page */\n  int cellOffset;            /* Offset to the cell pointer array */\n  int cbrk;                  /* Offset to the cell content area */\n  int nCell;                 /* Number of cells on the page */\n  unsigned char *data;       /* The page data */\n  unsigned char *temp;       /* Temp area for cell content */\n  unsigned char *src;        /* Source of content */\n  int iCellFirst;            /* First allowable cell index */\n  int iCellLast;             /* Last possible cell index */\n\n  assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n  assert( pPage->pBt!=0 );\n  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );\n  assert( pPage->nOverflow==0 );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  temp = 0;\n  src = data = pPage->aData;\n  hdr = pPage->hdrOffset;\n  cellOffset = pPage->cellOffset;\n  nCell = pPage->nCell;\n  assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );\n  iCellFirst = cellOffset + 2*nCell;\n  usableSize = pPage->pBt->usableSize;\n\n  /* This block handles pages with two or fewer free blocks and nMaxFrag\n  ** or fewer fragmented bytes. In this case it is faster to move the\n  ** two (or one) blocks of cells using memmove() and add the required\n  ** offsets to each pointer in the cell-pointer array than it is to \n  ** reconstruct the entire page.  */\n  if( (int)data[hdr+7]<=nMaxFrag ){\n    int iFree = get2byte(&data[hdr+1]);\n    if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);\n    if( iFree ){\n      int iFree2 = get2byte(&data[iFree]);\n      if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);\n      if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){\n        u8 *pEnd = &data[cellOffset + nCell*2];\n        u8 *pAddr;\n        int sz2 = 0;\n        int sz = get2byte(&data[iFree+2]);\n        int top = get2byte(&data[hdr+5]);\n        if( top>=iFree ){\n          return SQLITE_CORRUPT_PAGE(pPage);\n        }\n        if( iFree2 ){\n          if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);\n          sz2 = get2byte(&data[iFree2+2]);\n          if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);\n          memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));\n          sz += sz2;\n        }else if( NEVER(iFree+sz>usableSize) ){\n          return SQLITE_CORRUPT_PAGE(pPage);\n        }\n\n        cbrk = top+sz;\n        assert( cbrk+(iFree-top) <= usableSize );\n        memmove(&data[cbrk], &data[top], iFree-top);\n        for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){\n          pc = get2byte(pAddr);\n          if( pc<iFree ){ put2byte(pAddr, pc+sz); }\n          else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }\n        }\n        goto defragment_out;\n      }\n    }\n  }\n\n  cbrk = usableSize;\n  iCellLast = usableSize - 4;\n  for(i=0; i<nCell; i++){\n    u8 *pAddr;     /* The i-th cell pointer */\n    pAddr = &data[cellOffset + i*2];\n    pc = get2byte(pAddr);\n    testcase( pc==iCellFirst );\n    testcase( pc==iCellLast );\n    /* These conditions have already been verified in btreeInitPage()\n    ** if PRAGMA cell_size_check=ON.\n    */\n    if( pc<iCellFirst || pc>iCellLast ){\n      return SQLITE_CORRUPT_PAGE(pPage);\n    }\n    assert( pc>=iCellFirst && pc<=iCellLast );\n    size = pPage->xCellSize(pPage, &src[pc]);\n    cbrk -= size;\n    if( cbrk<iCellFirst || pc+size>usableSize ){\n      return SQLITE_CORRUPT_PAGE(pPage);\n    }\n    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );\n    testcase( cbrk+size==usableSize );\n    testcase( pc+size==usableSize );\n    put2byte(pAddr, cbrk);\n    if( temp==0 ){\n      int x;\n      if( cbrk==pc ) continue;\n      temp = sqlite3PagerTempSpace(pPage->pBt->pPager);\n      x = get2byte(&data[hdr+5]);\n      memcpy(&temp[x], &data[x], (cbrk+size) - x);\n      src = temp;\n    }\n    memcpy(&data[cbrk], &src[pc], size);\n  }\n  data[hdr+7] = 0;\n\n defragment_out:\n  assert( pPage->nFree>=0 );\n  if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){\n    return SQLITE_CORRUPT_PAGE(pPage);\n  }\n  assert( cbrk>=iCellFirst );\n  put2byte(&data[hdr+5], cbrk);\n  data[hdr+1] = 0;\n  data[hdr+2] = 0;\n  memset(&data[iCellFirst], 0, cbrk-iCellFirst);\n  assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n  return SQLITE_OK;\n}\n\n/*\n** Search the free-list on page pPg for space to store a cell nByte bytes in\n** size. If one can be found, return a pointer to the space and remove it\n** from the free-list.\n**\n** If no suitable space can be found on the free-list, return NULL.\n**\n** This function may detect corruption within pPg.  If corruption is\n** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.\n**\n** Slots on the free list that are between 1 and 3 bytes larger than nByte\n** will be ignored if adding the extra space to the fragmentation count\n** causes the fragmentation count to exceed 60.\n*/\nstatic u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){\n  const int hdr = pPg->hdrOffset;            /* Offset to page header */\n  u8 * const aData = pPg->aData;             /* Page data */\n  int iAddr = hdr + 1;                       /* Address of ptr to pc */\n  int pc = get2byte(&aData[iAddr]);          /* Address of a free slot */\n  int x;                                     /* Excess size of the slot */\n  int maxPC = pPg->pBt->usableSize - nByte;  /* Max address for a usable slot */\n  int size;                                  /* Size of the free slot */\n\n  assert( pc>0 );\n  while( pc<=maxPC ){\n    /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each\n    ** freeblock form a big-endian integer which is the size of the freeblock\n    ** in bytes, including the 4-byte header. */\n    size = get2byte(&aData[pc+2]);\n    if( (x = size - nByte)>=0 ){\n      testcase( x==4 );\n      testcase( x==3 );\n      if( x<4 ){\n        /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total\n        ** number of bytes in fragments may not exceed 60. */\n        if( aData[hdr+7]>57 ) return 0;\n\n        /* Remove the slot from the free-list. Update the number of\n        ** fragmented bytes within the page. */\n        memcpy(&aData[iAddr], &aData[pc], 2);\n        aData[hdr+7] += (u8)x;\n      }else if( x+pc > maxPC ){\n        /* This slot extends off the end of the usable part of the page */\n        *pRc = SQLITE_CORRUPT_PAGE(pPg);\n        return 0;\n      }else{\n        /* The slot remains on the free-list. Reduce its size to account\n        ** for the portion used by the new allocation. */\n        put2byte(&aData[pc+2], x);\n      }\n      return &aData[pc + x];\n    }\n    iAddr = pc;\n    pc = get2byte(&aData[pc]);\n    if( pc<=iAddr+size ){\n      if( pc ){\n        /* The next slot in the chain is not past the end of the current slot */\n        *pRc = SQLITE_CORRUPT_PAGE(pPg);\n      }\n      return 0;\n    }\n  }\n  if( pc>maxPC+nByte-4 ){\n    /* The free slot chain extends off the end of the page */\n    *pRc = SQLITE_CORRUPT_PAGE(pPg);\n  }\n  return 0;\n}\n\n/*\n** Allocate nByte bytes of space from within the B-Tree page passed\n** as the first argument. Write into *pIdx the index into pPage->aData[]\n** of the first byte of allocated space. Return either SQLITE_OK or\n** an error code (usually SQLITE_CORRUPT).\n**\n** The caller guarantees that there is sufficient space to make the\n** allocation.  This routine might need to defragment in order to bring\n** all the space together, however.  This routine will avoid using\n** the first two bytes past the cell pointer area since presumably this\n** allocation is being made in order to insert a new cell, so we will\n** also end up needing a new cell pointer.\n*/\nstatic int allocateSpace(MemPage *pPage, int nByte, int *pIdx){\n  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */\n  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */\n  int top;                             /* First byte of cell content area */\n  int rc = SQLITE_OK;                  /* Integer return code */\n  int gap;        /* First byte of gap between cell pointers and cell content */\n  \n  assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n  assert( pPage->pBt );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( nByte>=0 );  /* Minimum cell size is 4 */\n  assert( pPage->nFree>=nByte );\n  assert( pPage->nOverflow==0 );\n  assert( nByte < (int)(pPage->pBt->usableSize-8) );\n\n  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );\n  gap = pPage->cellOffset + 2*pPage->nCell;\n  assert( gap<=65536 );\n  /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size\n  ** and the reserved space is zero (the usual value for reserved space)\n  ** then the cell content offset of an empty page wants to be 65536.\n  ** However, that integer is too large to be stored in a 2-byte unsigned\n  ** integer, so a value of 0 is used in its place. */\n  top = get2byte(&data[hdr+5]);\n  assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */\n  if( gap>top ){\n    if( top==0 && pPage->pBt->usableSize==65536 ){\n      top = 65536;\n    }else{\n      return SQLITE_CORRUPT_PAGE(pPage);\n    }\n  }\n\n  /* If there is enough space between gap and top for one more cell pointer,\n  ** and if the freelist is not empty, then search the\n  ** freelist looking for a slot big enough to satisfy the request.\n  */\n  testcase( gap+2==top );\n  testcase( gap+1==top );\n  testcase( gap==top );\n  if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){\n    u8 *pSpace = pageFindSlot(pPage, nByte, &rc);\n    if( pSpace ){\n      int g2;\n      assert( pSpace+nByte<=data+pPage->pBt->usableSize );\n      *pIdx = g2 = (int)(pSpace-data);\n      if( NEVER(g2<=gap) ){\n        return SQLITE_CORRUPT_PAGE(pPage);\n      }else{\n        return SQLITE_OK;\n      }\n    }else if( rc ){\n      return rc;\n    }\n  }\n\n  /* The request could not be fulfilled using a freelist slot.  Check\n  ** to see if defragmentation is necessary.\n  */\n  testcase( gap+2+nByte==top );\n  if( gap+2+nByte>top ){\n    assert( pPage->nCell>0 || CORRUPT_DB );\n    assert( pPage->nFree>=0 );\n    rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));\n    if( rc ) return rc;\n    top = get2byteNotZero(&data[hdr+5]);\n    assert( gap+2+nByte<=top );\n  }\n\n\n  /* Allocate memory from the gap in between the cell pointer array\n  ** and the cell content area.  The btreeComputeFreeSpace() call has already\n  ** validated the freelist.  Given that the freelist is valid, there\n  ** is no way that the allocation can extend off the end of the page.\n  ** The assert() below verifies the previous sentence.\n  */\n  top -= nByte;\n  put2byte(&data[hdr+5], top);\n  assert( top+nByte <= (int)pPage->pBt->usableSize );\n  *pIdx = top;\n  return SQLITE_OK;\n}\n\n/*\n** Return a section of the pPage->aData to the freelist.\n** The first byte of the new free block is pPage->aData[iStart]\n** and the size of the block is iSize bytes.\n**\n** Adjacent freeblocks are coalesced.\n**\n** Even though the freeblock list was checked by btreeComputeFreeSpace(),\n** that routine will not detect overlap between cells or freeblocks.  Nor\n** does it detect cells or freeblocks that encrouch into the reserved bytes\n** at the end of the page.  So do additional corruption checks inside this\n** routine and return SQLITE_CORRUPT if any problems are found.\n*/\nstatic int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){\n  u16 iPtr;                             /* Address of ptr to next freeblock */\n  u16 iFreeBlk;                         /* Address of the next freeblock */\n  u8 hdr;                               /* Page header size.  0 or 100 */\n  u8 nFrag = 0;                         /* Reduction in fragmentation */\n  u16 iOrigSize = iSize;                /* Original value of iSize */\n  u16 x;                                /* Offset to cell content area */\n  u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */\n  unsigned char *data = pPage->aData;   /* Page content */\n\n  assert( pPage->pBt!=0 );\n  assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n  assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );\n  assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( iSize>=4 );   /* Minimum cell size is 4 */\n  assert( iStart<=pPage->pBt->usableSize-4 );\n\n  /* The list of freeblocks must be in ascending order.  Find the \n  ** spot on the list where iStart should be inserted.\n  */\n  hdr = pPage->hdrOffset;\n  iPtr = hdr + 1;\n  if( data[iPtr+1]==0 && data[iPtr]==0 ){\n    iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */\n  }else{\n    while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){\n      if( iFreeBlk<iPtr+4 ){\n        if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */\n        return SQLITE_CORRUPT_PAGE(pPage);\n      }\n      iPtr = iFreeBlk;\n    }\n    if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */\n      return SQLITE_CORRUPT_PAGE(pPage);\n    }\n    assert( iFreeBlk>iPtr || iFreeBlk==0 );\n  \n    /* At this point:\n    **    iFreeBlk:   First freeblock after iStart, or zero if none\n    **    iPtr:       The address of a pointer to iFreeBlk\n    **\n    ** Check to see if iFreeBlk should be coalesced onto the end of iStart.\n    */\n    if( iFreeBlk && iEnd+3>=iFreeBlk ){\n      nFrag = iFreeBlk - iEnd;\n      if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);\n      iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);\n      if( iEnd > pPage->pBt->usableSize ){\n        return SQLITE_CORRUPT_PAGE(pPage);\n      }\n      iSize = iEnd - iStart;\n      iFreeBlk = get2byte(&data[iFreeBlk]);\n    }\n  \n    /* If iPtr is another freeblock (that is, if iPtr is not the freelist\n    ** pointer in the page header) then check to see if iStart should be\n    ** coalesced onto the end of iPtr.\n    */\n    if( iPtr>hdr+1 ){\n      int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);\n      if( iPtrEnd+3>=iStart ){\n        if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);\n        nFrag += iStart - iPtrEnd;\n        iSize = iEnd - iPtr;\n        iStart = iPtr;\n      }\n    }\n    if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);\n    data[hdr+7] -= nFrag;\n  }\n  x = get2byte(&data[hdr+5]);\n  if( iStart<=x ){\n    /* The new freeblock is at the beginning of the cell content area,\n    ** so just extend the cell content area rather than create another\n    ** freelist entry */\n    if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);\n    if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);\n    put2byte(&data[hdr+1], iFreeBlk);\n    put2byte(&data[hdr+5], iEnd);\n  }else{\n    /* Insert the new freeblock into the freelist */\n    put2byte(&data[iPtr], iStart);\n  }\n  if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){\n    /* Overwrite deleted information with zeros when the secure_delete\n    ** option is enabled */\n    memset(&data[iStart], 0, iSize);\n  }\n  put2byte(&data[iStart], iFreeBlk);\n  put2byte(&data[iStart+2], iSize);\n  pPage->nFree += iOrigSize;\n  return SQLITE_OK;\n}\n\n/*\n** Decode the flags byte (the first byte of the header) for a page\n** and initialize fields of the MemPage structure accordingly.\n**\n** Only the following combinations are supported.  Anything different\n** indicates a corrupt database files:\n**\n**         PTF_ZERODATA\n**         PTF_ZERODATA | PTF_LEAF\n**         PTF_LEAFDATA | PTF_INTKEY\n**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF\n*/\nstatic int decodeFlags(MemPage *pPage, int flagByte){\n  BtShared *pBt;     /* A copy of pPage->pBt */\n\n  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );\n  flagByte &= ~PTF_LEAF;\n  pPage->childPtrSize = 4-4*pPage->leaf;\n  pPage->xCellSize = cellSizePtr;\n  pBt = pPage->pBt;\n  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){\n    /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an\n    ** interior table b-tree page. */\n    assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );\n    /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a\n    ** leaf table b-tree page. */\n    assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );\n    pPage->intKey = 1;\n    if( pPage->leaf ){\n      pPage->intKeyLeaf = 1;\n      pPage->xParseCell = btreeParseCellPtr;\n    }else{\n      pPage->intKeyLeaf = 0;\n      pPage->xCellSize = cellSizePtrNoPayload;\n      pPage->xParseCell = btreeParseCellPtrNoPayload;\n    }\n    pPage->maxLocal = pBt->maxLeaf;\n    pPage->minLocal = pBt->minLeaf;\n  }else if( flagByte==PTF_ZERODATA ){\n    /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an\n    ** interior index b-tree page. */\n    assert( (PTF_ZERODATA)==2 );\n    /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a\n    ** leaf index b-tree page. */\n    assert( (PTF_ZERODATA|PTF_LEAF)==10 );\n    pPage->intKey = 0;\n    pPage->intKeyLeaf = 0;\n    pPage->xParseCell = btreeParseCellPtrIndex;\n    pPage->maxLocal = pBt->maxLocal;\n    pPage->minLocal = pBt->minLocal;\n  }else{\n    /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is\n    ** an error. */\n    return SQLITE_CORRUPT_PAGE(pPage);\n  }\n  pPage->max1bytePayload = pBt->max1bytePayload;\n  return SQLITE_OK;\n}\n\n/*\n** Compute the amount of freespace on the page.  In other words, fill\n** in the pPage->nFree field.\n*/\nstatic int btreeComputeFreeSpace(MemPage *pPage){\n  int pc;            /* Address of a freeblock within pPage->aData[] */\n  u8 hdr;            /* Offset to beginning of page header */\n  u8 *data;          /* Equal to pPage->aData */\n  int usableSize;    /* Amount of usable space on each page */\n  int nFree;         /* Number of unused bytes on the page */\n  int top;           /* First byte of the cell content area */\n  int iCellFirst;    /* First allowable cell or freeblock offset */\n  int iCellLast;     /* Last possible cell or freeblock offset */\n\n  assert( pPage->pBt!=0 );\n  assert( pPage->pBt->db!=0 );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );\n  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );\n  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );\n  assert( pPage->isInit==1 );\n  assert( pPage->nFree<0 );\n\n  usableSize = pPage->pBt->usableSize;\n  hdr = pPage->hdrOffset;\n  data = pPage->aData;\n  /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates\n  ** the start of the cell content area. A zero value for this integer is\n  ** interpreted as 65536. */\n  top = get2byteNotZero(&data[hdr+5]);\n  iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;\n  iCellLast = usableSize - 4;\n\n  /* Compute the total free space on the page\n  ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the\n  ** start of the first freeblock on the page, or is zero if there are no\n  ** freeblocks. */\n  pc = get2byte(&data[hdr+1]);\n  nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */\n  if( pc>0 ){\n    u32 next, size;\n    if( pc<top ){\n      /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will\n      ** always be at least one cell before the first freeblock.\n      */\n      return SQLITE_CORRUPT_PAGE(pPage); \n    }\n    while( 1 ){\n      if( pc>iCellLast ){\n        /* Freeblock off the end of the page */\n        return SQLITE_CORRUPT_PAGE(pPage);\n      }\n      next = get2byte(&data[pc]);\n      size = get2byte(&data[pc+2]);\n      nFree = nFree + size;\n      if( next<=pc+size+3 ) break;\n      pc = next;\n    }\n    if( next>0 ){\n      /* Freeblock not in ascending order */\n      return SQLITE_CORRUPT_PAGE(pPage);\n    }\n    if( pc+size>(unsigned int)usableSize ){\n      /* Last freeblock extends past page end */\n      return SQLITE_CORRUPT_PAGE(pPage);\n    }\n  }\n\n  /* At this point, nFree contains the sum of the offset to the start\n  ** of the cell-content area plus the number of free bytes within\n  ** the cell-content area. If this is greater than the usable-size\n  ** of the page, then the page must be corrupted. This check also\n  ** serves to verify that the offset to the start of the cell-content\n  ** area, according to the page header, lies within the page.\n  */\n  if( nFree>usableSize || nFree<iCellFirst ){\n    return SQLITE_CORRUPT_PAGE(pPage);\n  }\n  pPage->nFree = (u16)(nFree - iCellFirst);\n  return SQLITE_OK;\n}\n\n/*\n** Do additional sanity check after btreeInitPage() if\n** PRAGMA cell_size_check=ON \n*/\nstatic SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){\n  int iCellFirst;    /* First allowable cell or freeblock offset */\n  int iCellLast;     /* Last possible cell or freeblock offset */\n  int i;             /* Index into the cell pointer array */\n  int sz;            /* Size of a cell */\n  int pc;            /* Address of a freeblock within pPage->aData[] */\n  u8 *data;          /* Equal to pPage->aData */\n  int usableSize;    /* Maximum usable space on the page */\n  int cellOffset;    /* Start of cell content area */\n\n  iCellFirst = pPage->cellOffset + 2*pPage->nCell;\n  usableSize = pPage->pBt->usableSize;\n  iCellLast = usableSize - 4;\n  data = pPage->aData;\n  cellOffset = pPage->cellOffset;\n  if( !pPage->leaf ) iCellLast--;\n  for(i=0; i<pPage->nCell; i++){\n    pc = get2byteAligned(&data[cellOffset+i*2]);\n    testcase( pc==iCellFirst );\n    testcase( pc==iCellLast );\n    if( pc<iCellFirst || pc>iCellLast ){\n      return SQLITE_CORRUPT_PAGE(pPage);\n    }\n    sz = pPage->xCellSize(pPage, &data[pc]);\n    testcase( pc+sz==usableSize );\n    if( pc+sz>usableSize ){\n      return SQLITE_CORRUPT_PAGE(pPage);\n    }\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Initialize the auxiliary information for a disk block.\n**\n** Return SQLITE_OK on success.  If we see that the page does\n** not contain a well-formed database page, then return \n** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not\n** guarantee that the page is well-formed.  It only shows that\n** we failed to detect any corruption.\n*/\nstatic int btreeInitPage(MemPage *pPage){\n  u8 *data;          /* Equal to pPage->aData */\n  BtShared *pBt;        /* The main btree structure */\n\n  assert( pPage->pBt!=0 );\n  assert( pPage->pBt->db!=0 );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );\n  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );\n  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );\n  assert( pPage->isInit==0 );\n\n  pBt = pPage->pBt;\n  data = pPage->aData + pPage->hdrOffset;\n  /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating\n  ** the b-tree page type. */\n  if( decodeFlags(pPage, data[0]) ){\n    return SQLITE_CORRUPT_PAGE(pPage);\n  }\n  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );\n  pPage->maskPage = (u16)(pBt->pageSize - 1);\n  pPage->nOverflow = 0;\n  pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;\n  pPage->aCellIdx = data + pPage->childPtrSize + 8;\n  pPage->aDataEnd = pPage->aData + pBt->usableSize;\n  pPage->aDataOfst = pPage->aData + pPage->childPtrSize;\n  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the\n  ** number of cells on the page. */\n  pPage->nCell = get2byte(&data[3]);\n  if( pPage->nCell>MX_CELL(pBt) ){\n    /* To many cells for a single page.  The page must be corrupt */\n    return SQLITE_CORRUPT_PAGE(pPage);\n  }\n  testcase( pPage->nCell==MX_CELL(pBt) );\n  /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only\n  ** possible for a root page of a table that contains no rows) then the\n  ** offset to the cell content area will equal the page size minus the\n  ** bytes of reserved space. */\n  assert( pPage->nCell>0\n       || get2byteNotZero(&data[5])==(int)pBt->usableSize\n       || CORRUPT_DB );\n  pPage->nFree = -1;  /* Indicate that this value is yet uncomputed */\n  pPage->isInit = 1;\n  if( pBt->db->flags & SQLITE_CellSizeCk ){\n    return btreeCellSizeCheck(pPage);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Set up a raw page so that it looks like a database page holding\n** no entries.\n*/\nstatic void zeroPage(MemPage *pPage, int flags){\n  unsigned char *data = pPage->aData;\n  BtShared *pBt = pPage->pBt;\n  u8 hdr = pPage->hdrOffset;\n  u16 first;\n\n  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );\n  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );\n  assert( sqlite3PagerGetData(pPage->pDbPage) == data );\n  assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  if( pBt->btsFlags & BTS_FAST_SECURE ){\n    memset(&data[hdr], 0, pBt->usableSize - hdr);\n  }\n  data[hdr] = (char)flags;\n  first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);\n  memset(&data[hdr+1], 0, 4);\n  data[hdr+7] = 0;\n  put2byte(&data[hdr+5], pBt->usableSize);\n  pPage->nFree = (u16)(pBt->usableSize - first);\n  decodeFlags(pPage, flags);\n  pPage->cellOffset = first;\n  pPage->aDataEnd = &data[pBt->usableSize];\n  pPage->aCellIdx = &data[first];\n  pPage->aDataOfst = &data[pPage->childPtrSize];\n  pPage->nOverflow = 0;\n  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );\n  pPage->maskPage = (u16)(pBt->pageSize - 1);\n  pPage->nCell = 0;\n  pPage->isInit = 1;\n}\n\n\n/*\n** Convert a DbPage obtained from the pager into a MemPage used by\n** the btree layer.\n*/\nstatic MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){\n  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);\n  if( pgno!=pPage->pgno ){\n    pPage->aData = sqlite3PagerGetData(pDbPage);\n    pPage->pDbPage = pDbPage;\n    pPage->pBt = pBt;\n    pPage->pgno = pgno;\n    pPage->hdrOffset = pgno==1 ? 100 : 0;\n  }\n  assert( pPage->aData==sqlite3PagerGetData(pDbPage) );\n  return pPage; \n}\n\n/*\n** Get a page from the pager.  Initialize the MemPage.pBt and\n** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().\n**\n** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care\n** about the content of the page at this time.  So do not go to the disk\n** to fetch the content.  Just fill in the content with zeros for now.\n** If in the future we call sqlite3PagerWrite() on this page, that\n** means we have started to be concerned about content and the disk\n** read should occur at that point.\n*/\nstatic int btreeGetPage(\n  BtShared *pBt,       /* The btree */\n  Pgno pgno,           /* Number of the page to fetch */\n  MemPage **ppPage,    /* Return the page in this parameter */\n  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */\n){\n  int rc;\n  DbPage *pDbPage;\n\n  assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);\n  if( rc ) return rc;\n  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);\n  return SQLITE_OK;\n}\n\n/*\n** Retrieve a page from the pager cache. If the requested page is not\n** already in the pager cache return NULL. Initialize the MemPage.pBt and\n** MemPage.aData elements if needed.\n*/\nstatic MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){\n  DbPage *pDbPage;\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);\n  if( pDbPage ){\n    return btreePageFromDbPage(pDbPage, pgno, pBt);\n  }\n  return 0;\n}\n\n/*\n** Return the size of the database file in pages. If there is any kind of\n** error, return ((unsigned int)-1).\n*/\nstatic Pgno btreePagecount(BtShared *pBt){\n  assert( (pBt->nPage & 0x80000000)==0 || CORRUPT_DB );\n  return pBt->nPage;\n}\nSQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){\n  assert( sqlite3BtreeHoldsMutex(p) );\n  return btreePagecount(p->pBt) & 0x7fffffff;\n}\n\n/*\n** Get a page from the pager and initialize it.\n**\n** If pCur!=0 then the page is being fetched as part of a moveToChild()\n** call.  Do additional sanity checking on the page in this case.\n** And if the fetch fails, this routine must decrement pCur->iPage.\n**\n** The page is fetched as read-write unless pCur is not NULL and is\n** a read-only cursor.\n**\n** If an error occurs, then *ppPage is undefined. It\n** may remain unchanged, or it may be set to an invalid value.\n*/\nstatic int getAndInitPage(\n  BtShared *pBt,                  /* The database file */\n  Pgno pgno,                      /* Number of the page to get */\n  MemPage **ppPage,               /* Write the page pointer here */\n  BtCursor *pCur,                 /* Cursor to receive the page, or NULL */\n  int bReadOnly                   /* True for a read-only page */\n){\n  int rc;\n  DbPage *pDbPage;\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( pCur==0 || ppPage==&pCur->pPage );\n  assert( pCur==0 || bReadOnly==pCur->curPagerFlags );\n  assert( pCur==0 || pCur->iPage>0 );\n\n  if( pgno>btreePagecount(pBt) ){\n    rc = SQLITE_CORRUPT_BKPT;\n    goto getAndInitPage_error1;\n  }\n  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);\n  if( rc ){\n    goto getAndInitPage_error1;\n  }\n  *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);\n  if( (*ppPage)->isInit==0 ){\n    btreePageFromDbPage(pDbPage, pgno, pBt);\n    rc = btreeInitPage(*ppPage);\n    if( rc!=SQLITE_OK ){\n      goto getAndInitPage_error2;\n    }\n  }\n  assert( (*ppPage)->pgno==pgno );\n  assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );\n\n  /* If obtaining a child page for a cursor, we must verify that the page is\n  ** compatible with the root page. */\n  if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){\n    rc = SQLITE_CORRUPT_PGNO(pgno);\n    goto getAndInitPage_error2;\n  }\n  return SQLITE_OK;\n\ngetAndInitPage_error2:\n  releasePage(*ppPage);\ngetAndInitPage_error1:\n  if( pCur ){\n    pCur->iPage--;\n    pCur->pPage = pCur->apPage[pCur->iPage];\n  }\n  testcase( pgno==0 );\n  assert( pgno!=0 || rc==SQLITE_CORRUPT );\n  return rc;\n}\n\n/*\n** Release a MemPage.  This should be called once for each prior\n** call to btreeGetPage.\n**\n** Page1 is a special case and must be released using releasePageOne().\n*/\nstatic void releasePageNotNull(MemPage *pPage){\n  assert( pPage->aData );\n  assert( pPage->pBt );\n  assert( pPage->pDbPage!=0 );\n  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );\n  assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  sqlite3PagerUnrefNotNull(pPage->pDbPage);\n}\nstatic void releasePage(MemPage *pPage){\n  if( pPage ) releasePageNotNull(pPage);\n}\nstatic void releasePageOne(MemPage *pPage){\n  assert( pPage!=0 );\n  assert( pPage->aData );\n  assert( pPage->pBt );\n  assert( pPage->pDbPage!=0 );\n  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );\n  assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  sqlite3PagerUnrefPageOne(pPage->pDbPage);\n}\n\n/*\n** Get an unused page.\n**\n** This works just like btreeGetPage() with the addition:\n**\n**   *  If the page is already in use for some other purpose, immediately\n**      release it and return an SQLITE_CURRUPT error.\n**   *  Make sure the isInit flag is clear\n*/\nstatic int btreeGetUnusedPage(\n  BtShared *pBt,       /* The btree */\n  Pgno pgno,           /* Number of the page to fetch */\n  MemPage **ppPage,    /* Return the page in this parameter */\n  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */\n){\n  int rc = btreeGetPage(pBt, pgno, ppPage, flags);\n  if( rc==SQLITE_OK ){\n    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){\n      releasePage(*ppPage);\n      *ppPage = 0;\n      return SQLITE_CORRUPT_BKPT;\n    }\n    (*ppPage)->isInit = 0;\n  }else{\n    *ppPage = 0;\n  }\n  return rc;\n}\n\n\n/*\n** During a rollback, when the pager reloads information into the cache\n** so that the cache is restored to its original state at the start of\n** the transaction, for each page restored this routine is called.\n**\n** This routine needs to reset the extra data section at the end of the\n** page to agree with the restored data.\n*/\nstatic void pageReinit(DbPage *pData){\n  MemPage *pPage;\n  pPage = (MemPage *)sqlite3PagerGetExtra(pData);\n  assert( sqlite3PagerPageRefcount(pData)>0 );\n  if( pPage->isInit ){\n    assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n    pPage->isInit = 0;\n    if( sqlite3PagerPageRefcount(pData)>1 ){\n      /* pPage might not be a btree page;  it might be an overflow page\n      ** or ptrmap page or a free page.  In those cases, the following\n      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.\n      ** But no harm is done by this.  And it is very important that\n      ** btreeInitPage() be called on every btree page so we make\n      ** the call for every page that comes in for re-initing. */\n      btreeInitPage(pPage);\n    }\n  }\n}\n\n/*\n** Invoke the busy handler for a btree.\n*/\nstatic int btreeInvokeBusyHandler(void *pArg){\n  BtShared *pBt = (BtShared*)pArg;\n  assert( pBt->db );\n  assert( sqlite3_mutex_held(pBt->db->mutex) );\n  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);\n}\n\n/*\n** Open a database file.\n** \n** zFilename is the name of the database file.  If zFilename is NULL\n** then an ephemeral database is created.  The ephemeral database might\n** be exclusively in memory, or it might use a disk-based memory cache.\n** Either way, the ephemeral database will be automatically deleted \n** when sqlite3BtreeClose() is called.\n**\n** If zFilename is \":memory:\" then an in-memory database is created\n** that is automatically destroyed when it is closed.\n**\n** The \"flags\" parameter is a bitmask that might contain bits like\n** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.\n**\n** If the database is already opened in the same database connection\n** and we are in shared cache mode, then the open will fail with an\n** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared\n** objects in the same database connection since doing so will lead\n** to problems with locking.\n*/\nSQLITE_PRIVATE int sqlite3BtreeOpen(\n  sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */\n  const char *zFilename,  /* Name of the file containing the BTree database */\n  sqlite3 *db,            /* Associated database handle */\n  Btree **ppBtree,        /* Pointer to new Btree object written here */\n  int flags,              /* Options */\n  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */\n){\n  BtShared *pBt = 0;             /* Shared part of btree structure */\n  Btree *p;                      /* Handle to return */\n  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */\n  int rc = SQLITE_OK;            /* Result code from this function */\n  u8 nReserve;                   /* Byte of unused space on each page */\n  unsigned char zDbHeader[100];  /* Database header content */\n\n  /* True if opening an ephemeral, temporary database */\n  const int isTempDb = zFilename==0 || zFilename[0]==0;\n\n  /* Set the variable isMemdb to true for an in-memory database, or \n  ** false for a file-based database.\n  */\n#ifdef SQLITE_OMIT_MEMORYDB\n  const int isMemdb = 0;\n#else\n  const int isMemdb = (zFilename && strcmp(zFilename, \":memory:\")==0)\n                       || (isTempDb && sqlite3TempInMemory(db))\n                       || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;\n#endif\n\n  assert( db!=0 );\n  assert( pVfs!=0 );\n  assert( sqlite3_mutex_held(db->mutex) );\n  assert( (flags&0xff)==flags );   /* flags fit in 8 bits */\n\n  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */\n  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );\n\n  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */\n  assert( (flags & BTREE_SINGLE)==0 || isTempDb );\n\n  if( isMemdb ){\n    flags |= BTREE_MEMORY;\n  }\n  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){\n    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;\n  }\n  p = sqlite3MallocZero(sizeof(Btree));\n  if( !p ){\n    return SQLITE_NOMEM_BKPT;\n  }\n  p->inTrans = TRANS_NONE;\n  p->db = db;\n#ifndef SQLITE_OMIT_SHARED_CACHE\n  p->lock.pBtree = p;\n  p->lock.iTable = 1;\n#endif\n\n#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)\n  /*\n  ** If this Btree is a candidate for shared cache, try to find an\n  ** existing BtShared object that we can share with\n  */\n  if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){\n    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){\n      int nFilename = sqlite3Strlen30(zFilename)+1;\n      int nFullPathname = pVfs->mxPathname+1;\n      char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));\n      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )\n\n      p->sharable = 1;\n      if( !zFullPathname ){\n        sqlite3_free(p);\n        return SQLITE_NOMEM_BKPT;\n      }\n      if( isMemdb ){\n        memcpy(zFullPathname, zFilename, nFilename);\n      }else{\n        rc = sqlite3OsFullPathname(pVfs, zFilename,\n                                   nFullPathname, zFullPathname);\n        if( rc ){\n          if( rc==SQLITE_OK_SYMLINK ){\n            rc = SQLITE_OK;\n          }else{\n            sqlite3_free(zFullPathname);\n            sqlite3_free(p);\n            return rc;\n          }\n        }\n      }\n#if SQLITE_THREADSAFE\n      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);\n      sqlite3_mutex_enter(mutexOpen);\n      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);\n      sqlite3_mutex_enter(mutexShared);\n#endif\n      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){\n        assert( pBt->nRef>0 );\n        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))\n                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){\n          int iDb;\n          for(iDb=db->nDb-1; iDb>=0; iDb--){\n            Btree *pExisting = db->aDb[iDb].pBt;\n            if( pExisting && pExisting->pBt==pBt ){\n              sqlite3_mutex_leave(mutexShared);\n              sqlite3_mutex_leave(mutexOpen);\n              sqlite3_free(zFullPathname);\n              sqlite3_free(p);\n              return SQLITE_CONSTRAINT;\n            }\n          }\n          p->pBt = pBt;\n          pBt->nRef++;\n          break;\n        }\n      }\n      sqlite3_mutex_leave(mutexShared);\n      sqlite3_free(zFullPathname);\n    }\n#ifdef SQLITE_DEBUG\n    else{\n      /* In debug mode, we mark all persistent databases as sharable\n      ** even when they are not.  This exercises the locking code and\n      ** gives more opportunity for asserts(sqlite3_mutex_held())\n      ** statements to find locking problems.\n      */\n      p->sharable = 1;\n    }\n#endif\n  }\n#endif\n  if( pBt==0 ){\n    /*\n    ** The following asserts make sure that structures used by the btree are\n    ** the right size.  This is to guard against size changes that result\n    ** when compiling on a different architecture.\n    */\n    assert( sizeof(i64)==8 );\n    assert( sizeof(u64)==8 );\n    assert( sizeof(u32)==4 );\n    assert( sizeof(u16)==2 );\n    assert( sizeof(Pgno)==4 );\n  \n    pBt = sqlite3MallocZero( sizeof(*pBt) );\n    if( pBt==0 ){\n      rc = SQLITE_NOMEM_BKPT;\n      goto btree_open_out;\n    }\n    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,\n                          sizeof(MemPage), flags, vfsFlags, pageReinit);\n    if( rc==SQLITE_OK ){\n      sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);\n      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);\n    }\n    if( rc!=SQLITE_OK ){\n      goto btree_open_out;\n    }\n    pBt->openFlags = (u8)flags;\n    pBt->db = db;\n    sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);\n    p->pBt = pBt;\n  \n    pBt->pCursor = 0;\n    pBt->pPage1 = 0;\n    if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;\n#if defined(SQLITE_SECURE_DELETE)\n    pBt->btsFlags |= BTS_SECURE_DELETE;\n#elif defined(SQLITE_FAST_SECURE_DELETE)\n    pBt->btsFlags |= BTS_OVERWRITE;\n#endif\n    /* EVIDENCE-OF: R-51873-39618 The page size for a database file is\n    ** determined by the 2-byte integer located at an offset of 16 bytes from\n    ** the beginning of the database file. */\n    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);\n    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE\n         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){\n      pBt->pageSize = 0;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n      /* If the magic name \":memory:\" will create an in-memory database, then\n      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if\n      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if\n      ** SQLITE_OMIT_MEMORYDB has been defined, then \":memory:\" is just a\n      ** regular file-name. In this case the auto-vacuum applies as per normal.\n      */\n      if( zFilename && !isMemdb ){\n        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);\n        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);\n      }\n#endif\n      nReserve = 0;\n    }else{\n      /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is\n      ** determined by the one-byte unsigned integer found at an offset of 20\n      ** into the database file header. */\n      nReserve = zDbHeader[20];\n      pBt->btsFlags |= BTS_PAGESIZE_FIXED;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);\n      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);\n#endif\n    }\n    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);\n    if( rc ) goto btree_open_out;\n    pBt->usableSize = pBt->pageSize - nReserve;\n    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */\n   \n#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)\n    /* Add the new BtShared object to the linked list sharable BtShareds.\n    */\n    pBt->nRef = 1;\n    if( p->sharable ){\n      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )\n      MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)\n      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){\n        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);\n        if( pBt->mutex==0 ){\n          rc = SQLITE_NOMEM_BKPT;\n          goto btree_open_out;\n        }\n      }\n      sqlite3_mutex_enter(mutexShared);\n      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);\n      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;\n      sqlite3_mutex_leave(mutexShared);\n    }\n#endif\n  }\n\n#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)\n  /* If the new Btree uses a sharable pBtShared, then link the new\n  ** Btree into the list of all sharable Btrees for the same connection.\n  ** The list is kept in ascending order by pBt address.\n  */\n  if( p->sharable ){\n    int i;\n    Btree *pSib;\n    for(i=0; i<db->nDb; i++){\n      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){\n        while( pSib->pPrev ){ pSib = pSib->pPrev; }\n        if( (uptr)p->pBt<(uptr)pSib->pBt ){\n          p->pNext = pSib;\n          p->pPrev = 0;\n          pSib->pPrev = p;\n        }else{\n          while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){\n            pSib = pSib->pNext;\n          }\n          p->pNext = pSib->pNext;\n          p->pPrev = pSib;\n          if( p->pNext ){\n            p->pNext->pPrev = p;\n          }\n          pSib->pNext = p;\n        }\n        break;\n      }\n    }\n  }\n#endif\n  *ppBtree = p;\n\nbtree_open_out:\n  if( rc!=SQLITE_OK ){\n    if( pBt && pBt->pPager ){\n      sqlite3PagerClose(pBt->pPager, 0);\n    }\n    sqlite3_free(pBt);\n    sqlite3_free(p);\n    *ppBtree = 0;\n  }else{\n    sqlite3_file *pFile;\n\n    /* If the B-Tree was successfully opened, set the pager-cache size to the\n    ** default value. Except, when opening on an existing shared pager-cache,\n    ** do not change the pager-cache size.\n    */\n    if( sqlite3BtreeSchema(p, 0, 0)==0 ){\n      sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);\n    }\n\n    pFile = sqlite3PagerFile(pBt->pPager);\n    if( pFile->pMethods ){\n      sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);\n    }\n  }\n  if( mutexOpen ){\n    assert( sqlite3_mutex_held(mutexOpen) );\n    sqlite3_mutex_leave(mutexOpen);\n  }\n  assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );\n  return rc;\n}\n\n/*\n** Decrement the BtShared.nRef counter.  When it reaches zero,\n** remove the BtShared structure from the sharing list.  Return\n** true if the BtShared.nRef counter reaches zero and return\n** false if it is still positive.\n*/\nstatic int removeFromSharingList(BtShared *pBt){\n#ifndef SQLITE_OMIT_SHARED_CACHE\n  MUTEX_LOGIC( sqlite3_mutex *pMaster; )\n  BtShared *pList;\n  int removed = 0;\n\n  assert( sqlite3_mutex_notheld(pBt->mutex) );\n  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )\n  sqlite3_mutex_enter(pMaster);\n  pBt->nRef--;\n  if( pBt->nRef<=0 ){\n    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){\n      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;\n    }else{\n      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);\n      while( ALWAYS(pList) && pList->pNext!=pBt ){\n        pList=pList->pNext;\n      }\n      if( ALWAYS(pList) ){\n        pList->pNext = pBt->pNext;\n      }\n    }\n    if( SQLITE_THREADSAFE ){\n      sqlite3_mutex_free(pBt->mutex);\n    }\n    removed = 1;\n  }\n  sqlite3_mutex_leave(pMaster);\n  return removed;\n#else\n  return 1;\n#endif\n}\n\n/*\n** Make sure pBt->pTmpSpace points to an allocation of \n** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child\n** pointer.\n*/\nstatic void allocateTempSpace(BtShared *pBt){\n  if( !pBt->pTmpSpace ){\n    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );\n\n    /* One of the uses of pBt->pTmpSpace is to format cells before\n    ** inserting them into a leaf page (function fillInCell()). If\n    ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes\n    ** by the various routines that manipulate binary cells. Which\n    ** can mean that fillInCell() only initializes the first 2 or 3\n    ** bytes of pTmpSpace, but that the first 4 bytes are copied from\n    ** it into a database page. This is not actually a problem, but it\n    ** does cause a valgrind error when the 1 or 2 bytes of unitialized \n    ** data is passed to system call write(). So to avoid this error,\n    ** zero the first 4 bytes of temp space here.\n    **\n    ** Also:  Provide four bytes of initialized space before the\n    ** beginning of pTmpSpace as an area available to prepend the\n    ** left-child pointer to the beginning of a cell.\n    */\n    if( pBt->pTmpSpace ){\n      memset(pBt->pTmpSpace, 0, 8);\n      pBt->pTmpSpace += 4;\n    }\n  }\n}\n\n/*\n** Free the pBt->pTmpSpace allocation\n*/\nstatic void freeTempSpace(BtShared *pBt){\n  if( pBt->pTmpSpace ){\n    pBt->pTmpSpace -= 4;\n    sqlite3PageFree(pBt->pTmpSpace);\n    pBt->pTmpSpace = 0;\n  }\n}\n\n/*\n** Close an open database and invalidate all cursors.\n*/\nSQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){\n  BtShared *pBt = p->pBt;\n  BtCursor *pCur;\n\n  /* Close all cursors opened via this handle.  */\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  sqlite3BtreeEnter(p);\n  pCur = pBt->pCursor;\n  while( pCur ){\n    BtCursor *pTmp = pCur;\n    pCur = pCur->pNext;\n    if( pTmp->pBtree==p ){\n      sqlite3BtreeCloseCursor(pTmp);\n    }\n  }\n\n  /* Rollback any active transaction and free the handle structure.\n  ** The call to sqlite3BtreeRollback() drops any table-locks held by\n  ** this handle.\n  */\n  sqlite3BtreeRollback(p, SQLITE_OK, 0);\n  sqlite3BtreeLeave(p);\n\n  /* If there are still other outstanding references to the shared-btree\n  ** structure, return now. The remainder of this procedure cleans \n  ** up the shared-btree.\n  */\n  assert( p->wantToLock==0 && p->locked==0 );\n  if( !p->sharable || removeFromSharingList(pBt) ){\n    /* The pBt is no longer on the sharing list, so we can access\n    ** it without having to hold the mutex.\n    **\n    ** Clean out and delete the BtShared object.\n    */\n    assert( !pBt->pCursor );\n    sqlite3PagerClose(pBt->pPager, p->db);\n    if( pBt->xFreeSchema && pBt->pSchema ){\n      pBt->xFreeSchema(pBt->pSchema);\n    }\n    sqlite3DbFree(0, pBt->pSchema);\n    freeTempSpace(pBt);\n    sqlite3_free(pBt);\n  }\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n  assert( p->wantToLock==0 );\n  assert( p->locked==0 );\n  if( p->pPrev ) p->pPrev->pNext = p->pNext;\n  if( p->pNext ) p->pNext->pPrev = p->pPrev;\n#endif\n\n  sqlite3_free(p);\n  return SQLITE_OK;\n}\n\n/*\n** Change the \"soft\" limit on the number of pages in the cache.\n** Unused and unmodified pages will be recycled when the number of\n** pages in the cache exceeds this soft limit.  But the size of the\n** cache is allowed to grow larger than this limit if it contains\n** dirty pages or pages still in active use.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){\n  BtShared *pBt = p->pBt;\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  sqlite3BtreeEnter(p);\n  sqlite3PagerSetCachesize(pBt->pPager, mxPage);\n  sqlite3BtreeLeave(p);\n  return SQLITE_OK;\n}\n\n/*\n** Change the \"spill\" limit on the number of pages in the cache.\n** If the number of pages exceeds this limit during a write transaction,\n** the pager might attempt to \"spill\" pages to the journal early in\n** order to free up memory.\n**\n** The value returned is the current spill size.  If zero is passed\n** as an argument, no changes are made to the spill size setting, so\n** using mxPage of 0 is a way to query the current spill size.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){\n  BtShared *pBt = p->pBt;\n  int res;\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  sqlite3BtreeEnter(p);\n  res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);\n  sqlite3BtreeLeave(p);\n  return res;\n}\n\n#if SQLITE_MAX_MMAP_SIZE>0\n/*\n** Change the limit on the amount of the database file that may be\n** memory mapped.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){\n  BtShared *pBt = p->pBt;\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  sqlite3BtreeEnter(p);\n  sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);\n  sqlite3BtreeLeave(p);\n  return SQLITE_OK;\n}\n#endif /* SQLITE_MAX_MMAP_SIZE>0 */\n\n/*\n** Change the way data is synced to disk in order to increase or decrease\n** how well the database resists damage due to OS crashes and power\n** failures.  Level 1 is the same as asynchronous (no syncs() occur and\n** there is a high probability of damage)  Level 2 is the default.  There\n** is a very low but non-zero probability of damage.  Level 3 reduces the\n** probability of damage to near zero but with a write performance reduction.\n*/\n#ifndef SQLITE_OMIT_PAGER_PRAGMAS\nSQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(\n  Btree *p,              /* The btree to set the safety level on */\n  unsigned pgFlags       /* Various PAGER_* flags */\n){\n  BtShared *pBt = p->pBt;\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  sqlite3BtreeEnter(p);\n  sqlite3PagerSetFlags(pBt->pPager, pgFlags);\n  sqlite3BtreeLeave(p);\n  return SQLITE_OK;\n}\n#endif\n\n/*\n** Change the default pages size and the number of reserved bytes per page.\n** Or, if the page size has already been fixed, return SQLITE_READONLY \n** without changing anything.\n**\n** The page size must be a power of 2 between 512 and 65536.  If the page\n** size supplied does not meet this constraint then the page size is not\n** changed.\n**\n** Page sizes are constrained to be a power of two so that the region\n** of the database file used for locking (beginning at PENDING_BYTE,\n** the first byte past the 1GB boundary, 0x40000000) needs to occur\n** at the beginning of a page.\n**\n** If parameter nReserve is less than zero, then the number of reserved\n** bytes per page is left unchanged.\n**\n** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size\n** and autovacuum mode can no longer be changed.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){\n  int rc = SQLITE_OK;\n  int x;\n  BtShared *pBt = p->pBt;\n  assert( nReserve>=0 && nReserve<=255 );\n  sqlite3BtreeEnter(p);\n  pBt->nReserveWanted = nReserve;\n  x = pBt->pageSize - pBt->usableSize;\n  if( nReserve<x ) nReserve = x;\n  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){\n    sqlite3BtreeLeave(p);\n    return SQLITE_READONLY;\n  }\n  assert( nReserve>=0 && nReserve<=255 );\n  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&\n        ((pageSize-1)&pageSize)==0 ){\n    assert( (pageSize & 7)==0 );\n    assert( !pBt->pCursor );\n    pBt->pageSize = (u32)pageSize;\n    freeTempSpace(pBt);\n  }\n  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);\n  pBt->usableSize = pBt->pageSize - (u16)nReserve;\n  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** Return the currently defined page size\n*/\nSQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){\n  return p->pBt->pageSize;\n}\n\n/*\n** This function is similar to sqlite3BtreeGetReserve(), except that it\n** may only be called if it is guaranteed that the b-tree mutex is already\n** held.\n**\n** This is useful in one special case in the backup API code where it is\n** known that the shared b-tree mutex is held, but the mutex on the \n** database handle that owns *p is not. In this case if sqlite3BtreeEnter()\n** were to be called, it might collide with some other operation on the\n** database handle that owns *p, causing undefined behavior.\n*/\nSQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){\n  int n;\n  assert( sqlite3_mutex_held(p->pBt->mutex) );\n  n = p->pBt->pageSize - p->pBt->usableSize;\n  return n;\n}\n\n/*\n** Return the number of bytes of space at the end of every page that\n** are intentually left unused.  This is the \"reserved\" space that is\n** sometimes used by extensions.\n**\n** The value returned is the larger of the current reserve size and\n** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.\n** The amount of reserve can only grow - never shrink.\n*/\nSQLITE_PRIVATE int sqlite3BtreeGetRequestedReserve(Btree *p){\n  int n1, n2;\n  sqlite3BtreeEnter(p);\n  n1 = (int)p->pBt->nReserveWanted;\n  n2 = sqlite3BtreeGetReserveNoMutex(p);\n  sqlite3BtreeLeave(p);\n  return n1>n2 ? n1 : n2;\n}\n\n\n/*\n** Set the maximum page count for a database if mxPage is positive.\n** No changes are made if mxPage is 0 or negative.\n** Regardless of the value of mxPage, return the maximum page count.\n*/\nSQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){\n  int n;\n  sqlite3BtreeEnter(p);\n  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);\n  sqlite3BtreeLeave(p);\n  return n;\n}\n\n/*\n** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:\n**\n**    newFlag==0       Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared\n**    newFlag==1       BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared\n**    newFlag==2       BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set\n**    newFlag==(-1)    No changes\n**\n** This routine acts as a query if newFlag is less than zero\n**\n** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but\n** freelist leaf pages are not written back to the database.  Thus in-page\n** deleted content is cleared, but freelist deleted content is not.\n**\n** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition\n** that freelist leaf pages are written back into the database, increasing\n** the amount of disk I/O.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){\n  int b;\n  if( p==0 ) return 0;\n  sqlite3BtreeEnter(p);\n  assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );\n  assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );\n  if( newFlag>=0 ){\n    p->pBt->btsFlags &= ~BTS_FAST_SECURE;\n    p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;\n  }\n  b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;\n  sqlite3BtreeLeave(p);\n  return b;\n}\n\n/*\n** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'\n** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it\n** is disabled. The default value for the auto-vacuum property is \n** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){\n#ifdef SQLITE_OMIT_AUTOVACUUM\n  return SQLITE_READONLY;\n#else\n  BtShared *pBt = p->pBt;\n  int rc = SQLITE_OK;\n  u8 av = (u8)autoVacuum;\n\n  sqlite3BtreeEnter(p);\n  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){\n    rc = SQLITE_READONLY;\n  }else{\n    pBt->autoVacuum = av ?1:0;\n    pBt->incrVacuum = av==2 ?1:0;\n  }\n  sqlite3BtreeLeave(p);\n  return rc;\n#endif\n}\n\n/*\n** Return the value of the 'auto-vacuum' property. If auto-vacuum is \n** enabled 1 is returned. Otherwise 0.\n*/\nSQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){\n#ifdef SQLITE_OMIT_AUTOVACUUM\n  return BTREE_AUTOVACUUM_NONE;\n#else\n  int rc;\n  sqlite3BtreeEnter(p);\n  rc = (\n    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:\n    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:\n    BTREE_AUTOVACUUM_INCR\n  );\n  sqlite3BtreeLeave(p);\n  return rc;\n#endif\n}\n\n/*\n** If the user has not set the safety-level for this database connection\n** using \"PRAGMA synchronous\", and if the safety-level is not already\n** set to the value passed to this function as the second parameter,\n** set it so.\n*/\n#if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \\\n    && !defined(SQLITE_OMIT_WAL)\nstatic void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){\n  sqlite3 *db;\n  Db *pDb;\n  if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){\n    while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }\n    if( pDb->bSyncSet==0 \n     && pDb->safety_level!=safety_level \n     && pDb!=&db->aDb[1] \n    ){\n      pDb->safety_level = safety_level;\n      sqlite3PagerSetFlags(pBt->pPager,\n          pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));\n    }\n  }\n}\n#else\n# define setDefaultSyncFlag(pBt,safety_level)\n#endif\n\n/* Forward declaration */\nstatic int newDatabase(BtShared*);\n\n\n/*\n** Get a reference to pPage1 of the database file.  This will\n** also acquire a readlock on that file.\n**\n** SQLITE_OK is returned on success.  If the file is not a\n** well-formed database file, then SQLITE_CORRUPT is returned.\n** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM\n** is returned if we run out of memory. \n*/\nstatic int lockBtree(BtShared *pBt){\n  int rc;              /* Result code from subfunctions */\n  MemPage *pPage1;     /* Page 1 of the database file */\n  u32 nPage;           /* Number of pages in the database */\n  u32 nPageFile = 0;   /* Number of pages in the database file */\n  u32 nPageHeader;     /* Number of pages in the database according to hdr */\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( pBt->pPage1==0 );\n  rc = sqlite3PagerSharedLock(pBt->pPager);\n  if( rc!=SQLITE_OK ) return rc;\n  rc = btreeGetPage(pBt, 1, &pPage1, 0);\n  if( rc!=SQLITE_OK ) return rc;\n\n  /* Do some checking to help insure the file we opened really is\n  ** a valid database file. \n  */\n  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);\n  sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);\n  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){\n    nPage = nPageFile;\n  }\n  if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){\n    nPage = 0;\n  }\n  if( nPage>0 ){\n    u32 pageSize;\n    u32 usableSize;\n    u8 *page1 = pPage1->aData;\n    rc = SQLITE_NOTADB;\n    /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins\n    ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d\n    ** 61 74 20 33 00. */\n    if( memcmp(page1, zMagicHeader, 16)!=0 ){\n      goto page1_init_failed;\n    }\n\n#ifdef SQLITE_OMIT_WAL\n    if( page1[18]>1 ){\n      pBt->btsFlags |= BTS_READ_ONLY;\n    }\n    if( page1[19]>1 ){\n      goto page1_init_failed;\n    }\n#else\n    if( page1[18]>2 ){\n      pBt->btsFlags |= BTS_READ_ONLY;\n    }\n    if( page1[19]>2 ){\n      goto page1_init_failed;\n    }\n\n    /* If the write version is set to 2, this database should be accessed\n    ** in WAL mode. If the log is not already open, open it now. Then \n    ** return SQLITE_OK and return without populating BtShared.pPage1.\n    ** The caller detects this and calls this function again. This is\n    ** required as the version of page 1 currently in the page1 buffer\n    ** may not be the latest version - there may be a newer one in the log\n    ** file.\n    */\n    if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){\n      int isOpen = 0;\n      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);\n      if( rc!=SQLITE_OK ){\n        goto page1_init_failed;\n      }else{\n        setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);\n        if( isOpen==0 ){\n          releasePageOne(pPage1);\n          return SQLITE_OK;\n        }\n      }\n      rc = SQLITE_NOTADB;\n    }else{\n      setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);\n    }\n#endif\n\n    /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload\n    ** fractions and the leaf payload fraction values must be 64, 32, and 32.\n    **\n    ** The original design allowed these amounts to vary, but as of\n    ** version 3.6.0, we require them to be fixed.\n    */\n    if( memcmp(&page1[21], \"\\100\\040\\040\",3)!=0 ){\n      goto page1_init_failed;\n    }\n    /* EVIDENCE-OF: R-51873-39618 The page size for a database file is\n    ** determined by the 2-byte integer located at an offset of 16 bytes from\n    ** the beginning of the database file. */\n    pageSize = (page1[16]<<8) | (page1[17]<<16);\n    /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two\n    ** between 512 and 65536 inclusive. */\n    if( ((pageSize-1)&pageSize)!=0\n     || pageSize>SQLITE_MAX_PAGE_SIZE \n     || pageSize<=256 \n    ){\n      goto page1_init_failed;\n    }\n    pBt->btsFlags |= BTS_PAGESIZE_FIXED;\n    assert( (pageSize & 7)==0 );\n    /* EVIDENCE-OF: R-59310-51205 The \"reserved space\" size in the 1-byte\n    ** integer at offset 20 is the number of bytes of space at the end of\n    ** each page to reserve for extensions. \n    **\n    ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is\n    ** determined by the one-byte unsigned integer found at an offset of 20\n    ** into the database file header. */\n    usableSize = pageSize - page1[20];\n    if( (u32)pageSize!=pBt->pageSize ){\n      /* After reading the first page of the database assuming a page size\n      ** of BtShared.pageSize, we have discovered that the page-size is\n      ** actually pageSize. Unlock the database, leave pBt->pPage1 at\n      ** zero and return SQLITE_OK. The caller will call this function\n      ** again with the correct page-size.\n      */\n      releasePageOne(pPage1);\n      pBt->usableSize = usableSize;\n      pBt->pageSize = pageSize;\n      freeTempSpace(pBt);\n      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,\n                                   pageSize-usableSize);\n      return rc;\n    }\n    if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){\n      rc = SQLITE_CORRUPT_BKPT;\n      goto page1_init_failed;\n    }\n    /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to\n    ** be less than 480. In other words, if the page size is 512, then the\n    ** reserved space size cannot exceed 32. */\n    if( usableSize<480 ){\n      goto page1_init_failed;\n    }\n    pBt->pageSize = pageSize;\n    pBt->usableSize = usableSize;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);\n    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);\n#endif\n  }\n\n  /* maxLocal is the maximum amount of payload to store locally for\n  ** a cell.  Make sure it is small enough so that at least minFanout\n  ** cells can will fit on one page.  We assume a 10-byte page header.\n  ** Besides the payload, the cell must store:\n  **     2-byte pointer to the cell\n  **     4-byte child pointer\n  **     9-byte nKey value\n  **     4-byte nData value\n  **     4-byte overflow page pointer\n  ** So a cell consists of a 2-byte pointer, a header which is as much as\n  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow\n  ** page pointer.\n  */\n  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);\n  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);\n  pBt->maxLeaf = (u16)(pBt->usableSize - 35);\n  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);\n  if( pBt->maxLocal>127 ){\n    pBt->max1bytePayload = 127;\n  }else{\n    pBt->max1bytePayload = (u8)pBt->maxLocal;\n  }\n  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );\n  pBt->pPage1 = pPage1;\n  pBt->nPage = nPage;\n  return SQLITE_OK;\n\npage1_init_failed:\n  releasePageOne(pPage1);\n  pBt->pPage1 = 0;\n  return rc;\n}\n\n#ifndef NDEBUG\n/*\n** Return the number of cursors open on pBt. This is for use\n** in assert() expressions, so it is only compiled if NDEBUG is not\n** defined.\n**\n** Only write cursors are counted if wrOnly is true.  If wrOnly is\n** false then all cursors are counted.\n**\n** For the purposes of this routine, a cursor is any cursor that\n** is capable of reading or writing to the database.  Cursors that\n** have been tripped into the CURSOR_FAULT state are not counted.\n*/\nstatic int countValidCursors(BtShared *pBt, int wrOnly){\n  BtCursor *pCur;\n  int r = 0;\n  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){\n    if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)\n     && pCur->eState!=CURSOR_FAULT ) r++; \n  }\n  return r;\n}\n#endif\n\n/*\n** If there are no outstanding cursors and we are not in the middle\n** of a transaction but there is a read lock on the database, then\n** this routine unrefs the first page of the database file which \n** has the effect of releasing the read lock.\n**\n** If there is a transaction in progress, this routine is a no-op.\n*/\nstatic void unlockBtreeIfUnused(BtShared *pBt){\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );\n  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){\n    MemPage *pPage1 = pBt->pPage1;\n    assert( pPage1->aData );\n    assert( sqlite3PagerRefcount(pBt->pPager)==1 );\n    pBt->pPage1 = 0;\n    releasePageOne(pPage1);\n  }\n}\n\n/*\n** If pBt points to an empty file then convert that empty file\n** into a new empty database by initializing the first page of\n** the database.\n*/\nstatic int newDatabase(BtShared *pBt){\n  MemPage *pP1;\n  unsigned char *data;\n  int rc;\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  if( pBt->nPage>0 ){\n    return SQLITE_OK;\n  }\n  pP1 = pBt->pPage1;\n  assert( pP1!=0 );\n  data = pP1->aData;\n  rc = sqlite3PagerWrite(pP1->pDbPage);\n  if( rc ) return rc;\n  memcpy(data, zMagicHeader, sizeof(zMagicHeader));\n  assert( sizeof(zMagicHeader)==16 );\n  data[16] = (u8)((pBt->pageSize>>8)&0xff);\n  data[17] = (u8)((pBt->pageSize>>16)&0xff);\n  data[18] = 1;\n  data[19] = 1;\n  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);\n  data[20] = (u8)(pBt->pageSize - pBt->usableSize);\n  data[21] = 64;\n  data[22] = 32;\n  data[23] = 32;\n  memset(&data[24], 0, 100-24);\n  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );\n  pBt->btsFlags |= BTS_PAGESIZE_FIXED;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );\n  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );\n  put4byte(&data[36 + 4*4], pBt->autoVacuum);\n  put4byte(&data[36 + 7*4], pBt->incrVacuum);\n#endif\n  pBt->nPage = 1;\n  data[31] = 1;\n  return SQLITE_OK;\n}\n\n/*\n** Initialize the first page of the database file (creating a database\n** consisting of a single page and no schema objects). Return SQLITE_OK\n** if successful, or an SQLite error code otherwise.\n*/\nSQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){\n  int rc;\n  sqlite3BtreeEnter(p);\n  p->pBt->nPage = 0;\n  rc = newDatabase(p->pBt);\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** Attempt to start a new transaction. A write-transaction\n** is started if the second argument is nonzero, otherwise a read-\n** transaction.  If the second argument is 2 or more and exclusive\n** transaction is started, meaning that no other process is allowed\n** to access the database.  A preexisting transaction may not be\n** upgraded to exclusive by calling this routine a second time - the\n** exclusivity flag only works for a new transaction.\n**\n** A write-transaction must be started before attempting any \n** changes to the database.  None of the following routines \n** will work unless a transaction is started first:\n**\n**      sqlite3BtreeCreateTable()\n**      sqlite3BtreeCreateIndex()\n**      sqlite3BtreeClearTable()\n**      sqlite3BtreeDropTable()\n**      sqlite3BtreeInsert()\n**      sqlite3BtreeDelete()\n**      sqlite3BtreeUpdateMeta()\n**\n** If an initial attempt to acquire the lock fails because of lock contention\n** and the database was previously unlocked, then invoke the busy handler\n** if there is one.  But if there was previously a read-lock, do not\n** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is \n** returned when there is already a read-lock in order to avoid a deadlock.\n**\n** Suppose there are two processes A and B.  A has a read lock and B has\n** a reserved lock.  B tries to promote to exclusive but is blocked because\n** of A's read lock.  A tries to promote to reserved but is blocked by B.\n** One or the other of the two processes must give way or there can be\n** no progress.  By returning SQLITE_BUSY and not invoking the busy callback\n** when A already has a read lock, we encourage A to give up and let B\n** proceed.\n*/\nSQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){\n  BtShared *pBt = p->pBt;\n  Pager *pPager = pBt->pPager;\n  int rc = SQLITE_OK;\n\n  sqlite3BtreeEnter(p);\n  btreeIntegrity(p);\n\n  /* If the btree is already in a write-transaction, or it\n  ** is already in a read-transaction and a read-transaction\n  ** is requested, this is a no-op.\n  */\n  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){\n    goto trans_begun;\n  }\n  assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );\n\n  if( (p->db->flags & SQLITE_ResetDatabase) \n   && sqlite3PagerIsreadonly(pPager)==0 \n  ){\n    pBt->btsFlags &= ~BTS_READ_ONLY;\n  }\n\n  /* Write transactions are not possible on a read-only database */\n  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){\n    rc = SQLITE_READONLY;\n    goto trans_begun;\n  }\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n  {\n    sqlite3 *pBlock = 0;\n    /* If another database handle has already opened a write transaction \n    ** on this shared-btree structure and a second write transaction is\n    ** requested, return SQLITE_LOCKED.\n    */\n    if( (wrflag && pBt->inTransaction==TRANS_WRITE)\n     || (pBt->btsFlags & BTS_PENDING)!=0\n    ){\n      pBlock = pBt->pWriter->db;\n    }else if( wrflag>1 ){\n      BtLock *pIter;\n      for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){\n        if( pIter->pBtree!=p ){\n          pBlock = pIter->pBtree->db;\n          break;\n        }\n      }\n    }\n    if( pBlock ){\n      sqlite3ConnectionBlocked(p->db, pBlock);\n      rc = SQLITE_LOCKED_SHAREDCACHE;\n      goto trans_begun;\n    }\n  }\n#endif\n\n  /* Any read-only or read-write transaction implies a read-lock on \n  ** page 1. So if some other shared-cache client already has a write-lock \n  ** on page 1, the transaction cannot be opened. */\n  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);\n  if( SQLITE_OK!=rc ) goto trans_begun;\n\n  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;\n  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;\n  do {\n    sqlite3PagerWalDb(pPager, p->db);\n\n#ifdef SQLITE_ENABLE_SETLK_TIMEOUT\n    /* If transitioning from no transaction directly to a write transaction,\n    ** block for the WRITER lock first if possible. */\n    if( pBt->pPage1==0 && wrflag ){\n      assert( pBt->inTransaction==TRANS_NONE );\n      rc = sqlite3PagerWalWriteLock(pPager, 1);\n      if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;\n    }\n#endif\n\n    /* Call lockBtree() until either pBt->pPage1 is populated or\n    ** lockBtree() returns something other than SQLITE_OK. lockBtree()\n    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after\n    ** reading page 1 it discovers that the page-size of the database \n    ** file is not pBt->pageSize. In this case lockBtree() will update\n    ** pBt->pageSize to the page-size of the file on disk.\n    */\n    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );\n\n    if( rc==SQLITE_OK && wrflag ){\n      if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){\n        rc = SQLITE_READONLY;\n      }else{\n        rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));\n        if( rc==SQLITE_OK ){\n          rc = newDatabase(pBt);\n        }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){\n          /* if there was no transaction opened when this function was\n          ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error\n          ** code to SQLITE_BUSY. */\n          rc = SQLITE_BUSY;\n        }\n      }\n    }\n  \n    if( rc!=SQLITE_OK ){\n      (void)sqlite3PagerWalWriteLock(pPager, 0);\n      unlockBtreeIfUnused(pBt);\n    }\n  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&\n          btreeInvokeBusyHandler(pBt) );\n  sqlite3PagerWalDb(pPager, 0);\n#ifdef SQLITE_ENABLE_SETLK_TIMEOUT\n  if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;\n#endif\n\n  if( rc==SQLITE_OK ){\n    if( p->inTrans==TRANS_NONE ){\n      pBt->nTransaction++;\n#ifndef SQLITE_OMIT_SHARED_CACHE\n      if( p->sharable ){\n        assert( p->lock.pBtree==p && p->lock.iTable==1 );\n        p->lock.eLock = READ_LOCK;\n        p->lock.pNext = pBt->pLock;\n        pBt->pLock = &p->lock;\n      }\n#endif\n    }\n    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);\n    if( p->inTrans>pBt->inTransaction ){\n      pBt->inTransaction = p->inTrans;\n    }\n    if( wrflag ){\n      MemPage *pPage1 = pBt->pPage1;\n#ifndef SQLITE_OMIT_SHARED_CACHE\n      assert( !pBt->pWriter );\n      pBt->pWriter = p;\n      pBt->btsFlags &= ~BTS_EXCLUSIVE;\n      if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;\n#endif\n\n      /* If the db-size header field is incorrect (as it may be if an old\n      ** client has been writing the database file), update it now. Doing\n      ** this sooner rather than later means the database size can safely \n      ** re-read the database size from page 1 if a savepoint or transaction\n      ** rollback occurs within the transaction.\n      */\n      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){\n        rc = sqlite3PagerWrite(pPage1->pDbPage);\n        if( rc==SQLITE_OK ){\n          put4byte(&pPage1->aData[28], pBt->nPage);\n        }\n      }\n    }\n  }\n\ntrans_begun:\n  if( rc==SQLITE_OK ){\n    if( pSchemaVersion ){\n      *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);\n    }\n    if( wrflag ){\n      /* This call makes sure that the pager has the correct number of\n      ** open savepoints. If the second parameter is greater than 0 and\n      ** the sub-journal is not already open, then it will be opened here.\n      */\n      rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);\n    }\n  }\n\n  btreeIntegrity(p);\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n\n/*\n** Set the pointer-map entries for all children of page pPage. Also, if\n** pPage contains cells that point to overflow pages, set the pointer\n** map entries for the overflow pages as well.\n*/\nstatic int setChildPtrmaps(MemPage *pPage){\n  int i;                             /* Counter variable */\n  int nCell;                         /* Number of cells in page pPage */\n  int rc;                            /* Return code */\n  BtShared *pBt = pPage->pBt;\n  Pgno pgno = pPage->pgno;\n\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);\n  if( rc!=SQLITE_OK ) return rc;\n  nCell = pPage->nCell;\n\n  for(i=0; i<nCell; i++){\n    u8 *pCell = findCell(pPage, i);\n\n    ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);\n\n    if( !pPage->leaf ){\n      Pgno childPgno = get4byte(pCell);\n      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);\n    }\n  }\n\n  if( !pPage->leaf ){\n    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);\n    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);\n  }\n\n  return rc;\n}\n\n/*\n** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so\n** that it points to iTo. Parameter eType describes the type of pointer to\n** be modified, as  follows:\n**\n** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child \n**                   page of pPage.\n**\n** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow\n**                   page pointed to by one of the cells on pPage.\n**\n** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next\n**                   overflow page in the list.\n*/\nstatic int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n  if( eType==PTRMAP_OVERFLOW2 ){\n    /* The pointer is always the first 4 bytes of the page in this case.  */\n    if( get4byte(pPage->aData)!=iFrom ){\n      return SQLITE_CORRUPT_PAGE(pPage);\n    }\n    put4byte(pPage->aData, iTo);\n  }else{\n    int i;\n    int nCell;\n    int rc;\n\n    rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);\n    if( rc ) return rc;\n    nCell = pPage->nCell;\n\n    for(i=0; i<nCell; i++){\n      u8 *pCell = findCell(pPage, i);\n      if( eType==PTRMAP_OVERFLOW1 ){\n        CellInfo info;\n        pPage->xParseCell(pPage, pCell, &info);\n        if( info.nLocal<info.nPayload ){\n          if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){\n            return SQLITE_CORRUPT_PAGE(pPage);\n          }\n          if( iFrom==get4byte(pCell+info.nSize-4) ){\n            put4byte(pCell+info.nSize-4, iTo);\n            break;\n          }\n        }\n      }else{\n        if( get4byte(pCell)==iFrom ){\n          put4byte(pCell, iTo);\n          break;\n        }\n      }\n    }\n  \n    if( i==nCell ){\n      if( eType!=PTRMAP_BTREE || \n          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){\n        return SQLITE_CORRUPT_PAGE(pPage);\n      }\n      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);\n    }\n  }\n  return SQLITE_OK;\n}\n\n\n/*\n** Move the open database page pDbPage to location iFreePage in the \n** database. The pDbPage reference remains valid.\n**\n** The isCommit flag indicates that there is no need to remember that\n** the journal needs to be sync()ed before database page pDbPage->pgno \n** can be written to. The caller has already promised not to write to that\n** page.\n*/\nstatic int relocatePage(\n  BtShared *pBt,           /* Btree */\n  MemPage *pDbPage,        /* Open page to move */\n  u8 eType,                /* Pointer map 'type' entry for pDbPage */\n  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */\n  Pgno iFreePage,          /* The location to move pDbPage to */\n  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */\n){\n  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */\n  Pgno iDbPage = pDbPage->pgno;\n  Pager *pPager = pBt->pPager;\n  int rc;\n\n  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || \n      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( pDbPage->pBt==pBt );\n  if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;\n\n  /* Move page iDbPage from its current location to page number iFreePage */\n  TRACE((\"AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\\n\", \n      iDbPage, iFreePage, iPtrPage, eType));\n  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n  pDbPage->pgno = iFreePage;\n\n  /* If pDbPage was a btree-page, then it may have child pages and/or cells\n  ** that point to overflow pages. The pointer map entries for all these\n  ** pages need to be changed.\n  **\n  ** If pDbPage is an overflow page, then the first 4 bytes may store a\n  ** pointer to a subsequent overflow page. If this is the case, then\n  ** the pointer map needs to be updated for the subsequent overflow page.\n  */\n  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){\n    rc = setChildPtrmaps(pDbPage);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n  }else{\n    Pgno nextOvfl = get4byte(pDbPage->aData);\n    if( nextOvfl!=0 ){\n      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n    }\n  }\n\n  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so\n  ** that it points at iFreePage. Also fix the pointer map entry for\n  ** iPtrPage.\n  */\n  if( eType!=PTRMAP_ROOTPAGE ){\n    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    rc = sqlite3PagerWrite(pPtrPage->pDbPage);\n    if( rc!=SQLITE_OK ){\n      releasePage(pPtrPage);\n      return rc;\n    }\n    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);\n    releasePage(pPtrPage);\n    if( rc==SQLITE_OK ){\n      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);\n    }\n  }\n  return rc;\n}\n\n/* Forward declaration required by incrVacuumStep(). */\nstatic int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);\n\n/*\n** Perform a single step of an incremental-vacuum. If successful, return\n** SQLITE_OK. If there is no work to do (and therefore no point in \n** calling this function again), return SQLITE_DONE. Or, if an error \n** occurs, return some other error code.\n**\n** More specifically, this function attempts to re-organize the database so \n** that the last page of the file currently in use is no longer in use.\n**\n** Parameter nFin is the number of pages that this database would contain\n** were this function called until it returns SQLITE_DONE.\n**\n** If the bCommit parameter is non-zero, this function assumes that the \n** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE \n** or an error. bCommit is passed true for an auto-vacuum-on-commit \n** operation, or false for an incremental vacuum.\n*/\nstatic int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){\n  Pgno nFreeList;           /* Number of pages still on the free-list */\n  int rc;\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( iLastPg>nFin );\n\n  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){\n    u8 eType;\n    Pgno iPtrPage;\n\n    nFreeList = get4byte(&pBt->pPage1->aData[36]);\n    if( nFreeList==0 ){\n      return SQLITE_DONE;\n    }\n\n    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    if( eType==PTRMAP_ROOTPAGE ){\n      return SQLITE_CORRUPT_BKPT;\n    }\n\n    if( eType==PTRMAP_FREEPAGE ){\n      if( bCommit==0 ){\n        /* Remove the page from the files free-list. This is not required\n        ** if bCommit is non-zero. In that case, the free-list will be\n        ** truncated to zero after this function returns, so it doesn't \n        ** matter if it still contains some garbage entries.\n        */\n        Pgno iFreePg;\n        MemPage *pFreePg;\n        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);\n        if( rc!=SQLITE_OK ){\n          return rc;\n        }\n        assert( iFreePg==iLastPg );\n        releasePage(pFreePg);\n      }\n    } else {\n      Pgno iFreePg;             /* Index of free page to move pLastPg to */\n      MemPage *pLastPg;\n      u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */\n      Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */\n\n      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n\n      /* If bCommit is zero, this loop runs exactly once and page pLastPg\n      ** is swapped with the first free page pulled off the free list.\n      **\n      ** On the other hand, if bCommit is greater than zero, then keep\n      ** looping until a free-page located within the first nFin pages\n      ** of the file is found.\n      */\n      if( bCommit==0 ){\n        eMode = BTALLOC_LE;\n        iNear = nFin;\n      }\n      do {\n        MemPage *pFreePg;\n        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);\n        if( rc!=SQLITE_OK ){\n          releasePage(pLastPg);\n          return rc;\n        }\n        releasePage(pFreePg);\n      }while( bCommit && iFreePg>nFin );\n      assert( iFreePg<iLastPg );\n      \n      rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);\n      releasePage(pLastPg);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n    }\n  }\n\n  if( bCommit==0 ){\n    do {\n      iLastPg--;\n    }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );\n    pBt->bDoTruncate = 1;\n    pBt->nPage = iLastPg;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** The database opened by the first argument is an auto-vacuum database\n** nOrig pages in size containing nFree free pages. Return the expected \n** size of the database in pages following an auto-vacuum operation.\n*/\nstatic Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){\n  int nEntry;                     /* Number of entries on one ptrmap page */\n  Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */\n  Pgno nFin;                      /* Return value */\n\n  nEntry = pBt->usableSize/5;\n  nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;\n  nFin = nOrig - nFree - nPtrmap;\n  if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){\n    nFin--;\n  }\n  while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){\n    nFin--;\n  }\n\n  return nFin;\n}\n\n/*\n** A write-transaction must be opened before calling this function.\n** It performs a single unit of work towards an incremental vacuum.\n**\n** If the incremental vacuum is finished after this function has run,\n** SQLITE_DONE is returned. If it is not finished, but no error occurred,\n** SQLITE_OK is returned. Otherwise an SQLite error code. \n*/\nSQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){\n  int rc;\n  BtShared *pBt = p->pBt;\n\n  sqlite3BtreeEnter(p);\n  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );\n  if( !pBt->autoVacuum ){\n    rc = SQLITE_DONE;\n  }else{\n    Pgno nOrig = btreePagecount(pBt);\n    Pgno nFree = get4byte(&pBt->pPage1->aData[36]);\n    Pgno nFin = finalDbSize(pBt, nOrig, nFree);\n\n    if( nOrig<nFin ){\n      rc = SQLITE_CORRUPT_BKPT;\n    }else if( nFree>0 ){\n      rc = saveAllCursors(pBt, 0, 0);\n      if( rc==SQLITE_OK ){\n        invalidateAllOverflowCache(pBt);\n        rc = incrVacuumStep(pBt, nFin, nOrig, 0);\n      }\n      if( rc==SQLITE_OK ){\n        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);\n        put4byte(&pBt->pPage1->aData[28], pBt->nPage);\n      }\n    }else{\n      rc = SQLITE_DONE;\n    }\n  }\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** This routine is called prior to sqlite3PagerCommit when a transaction\n** is committed for an auto-vacuum database.\n**\n** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages\n** the database file should be truncated to during the commit process. \n** i.e. the database has been reorganized so that only the first *pnTrunc\n** pages are in use.\n*/\nstatic int autoVacuumCommit(BtShared *pBt){\n  int rc = SQLITE_OK;\n  Pager *pPager = pBt->pPager;\n  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  invalidateAllOverflowCache(pBt);\n  assert(pBt->autoVacuum);\n  if( !pBt->incrVacuum ){\n    Pgno nFin;         /* Number of pages in database after autovacuuming */\n    Pgno nFree;        /* Number of pages on the freelist initially */\n    Pgno iFree;        /* The next page to be freed */\n    Pgno nOrig;        /* Database size before freeing */\n\n    nOrig = btreePagecount(pBt);\n    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){\n      /* It is not possible to create a database for which the final page\n      ** is either a pointer-map page or the pending-byte page. If one\n      ** is encountered, this indicates corruption.\n      */\n      return SQLITE_CORRUPT_BKPT;\n    }\n\n    nFree = get4byte(&pBt->pPage1->aData[36]);\n    nFin = finalDbSize(pBt, nOrig, nFree);\n    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;\n    if( nFin<nOrig ){\n      rc = saveAllCursors(pBt, 0, 0);\n    }\n    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){\n      rc = incrVacuumStep(pBt, nFin, iFree, 1);\n    }\n    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){\n      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);\n      put4byte(&pBt->pPage1->aData[32], 0);\n      put4byte(&pBt->pPage1->aData[36], 0);\n      put4byte(&pBt->pPage1->aData[28], nFin);\n      pBt->bDoTruncate = 1;\n      pBt->nPage = nFin;\n    }\n    if( rc!=SQLITE_OK ){\n      sqlite3PagerRollback(pPager);\n    }\n  }\n\n  assert( nRef>=sqlite3PagerRefcount(pPager) );\n  return rc;\n}\n\n#else /* ifndef SQLITE_OMIT_AUTOVACUUM */\n# define setChildPtrmaps(x) SQLITE_OK\n#endif\n\n/*\n** This routine does the first phase of a two-phase commit.  This routine\n** causes a rollback journal to be created (if it does not already exist)\n** and populated with enough information so that if a power loss occurs\n** the database can be restored to its original state by playing back\n** the journal.  Then the contents of the journal are flushed out to\n** the disk.  After the journal is safely on oxide, the changes to the\n** database are written into the database file and flushed to oxide.\n** At the end of this call, the rollback journal still exists on the\n** disk and we are still holding all locks, so the transaction has not\n** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the\n** commit process.\n**\n** This call is a no-op if no write-transaction is currently active on pBt.\n**\n** Otherwise, sync the database file for the btree pBt. zMaster points to\n** the name of a master journal file that should be written into the\n** individual journal file, or is NULL, indicating no master journal file \n** (single database transaction).\n**\n** When this is called, the master journal should already have been\n** created, populated with this journal pointer and synced to disk.\n**\n** Once this is routine has returned, the only thing required to commit\n** the write-transaction for this database file is to delete the journal.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){\n  int rc = SQLITE_OK;\n  if( p->inTrans==TRANS_WRITE ){\n    BtShared *pBt = p->pBt;\n    sqlite3BtreeEnter(p);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( pBt->autoVacuum ){\n      rc = autoVacuumCommit(pBt);\n      if( rc!=SQLITE_OK ){\n        sqlite3BtreeLeave(p);\n        return rc;\n      }\n    }\n    if( pBt->bDoTruncate ){\n      sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);\n    }\n#endif\n    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);\n    sqlite3BtreeLeave(p);\n  }\n  return rc;\n}\n\n/*\n** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()\n** at the conclusion of a transaction.\n*/\nstatic void btreeEndTransaction(Btree *p){\n  BtShared *pBt = p->pBt;\n  sqlite3 *db = p->db;\n  assert( sqlite3BtreeHoldsMutex(p) );\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n  pBt->bDoTruncate = 0;\n#endif\n  if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){\n    /* If there are other active statements that belong to this database\n    ** handle, downgrade to a read-only transaction. The other statements\n    ** may still be reading from the database.  */\n    downgradeAllSharedCacheTableLocks(p);\n    p->inTrans = TRANS_READ;\n  }else{\n    /* If the handle had any kind of transaction open, decrement the \n    ** transaction count of the shared btree. If the transaction count \n    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()\n    ** call below will unlock the pager.  */\n    if( p->inTrans!=TRANS_NONE ){\n      clearAllSharedCacheTableLocks(p);\n      pBt->nTransaction--;\n      if( 0==pBt->nTransaction ){\n        pBt->inTransaction = TRANS_NONE;\n      }\n    }\n\n    /* Set the current transaction state to TRANS_NONE and unlock the \n    ** pager if this call closed the only read or write transaction.  */\n    p->inTrans = TRANS_NONE;\n    unlockBtreeIfUnused(pBt);\n  }\n\n  btreeIntegrity(p);\n}\n\n/*\n** Commit the transaction currently in progress.\n**\n** This routine implements the second phase of a 2-phase commit.  The\n** sqlite3BtreeCommitPhaseOne() routine does the first phase and should\n** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()\n** routine did all the work of writing information out to disk and flushing the\n** contents so that they are written onto the disk platter.  All this\n** routine has to do is delete or truncate or zero the header in the\n** the rollback journal (which causes the transaction to commit) and\n** drop locks.\n**\n** Normally, if an error occurs while the pager layer is attempting to \n** finalize the underlying journal file, this function returns an error and\n** the upper layer will attempt a rollback. However, if the second argument\n** is non-zero then this b-tree transaction is part of a multi-file \n** transaction. In this case, the transaction has already been committed \n** (by deleting a master journal file) and the caller will ignore this \n** functions return code. So, even if an error occurs in the pager layer,\n** reset the b-tree objects internal state to indicate that the write\n** transaction has been closed. This is quite safe, as the pager will have\n** transitioned to the error state.\n**\n** This will release the write lock on the database file.  If there\n** are no active cursors, it also releases the read lock.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){\n\n  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;\n  sqlite3BtreeEnter(p);\n  btreeIntegrity(p);\n\n  /* If the handle has a write-transaction open, commit the shared-btrees \n  ** transaction and set the shared state to TRANS_READ.\n  */\n  if( p->inTrans==TRANS_WRITE ){\n    int rc;\n    BtShared *pBt = p->pBt;\n    assert( pBt->inTransaction==TRANS_WRITE );\n    assert( pBt->nTransaction>0 );\n    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);\n    if( rc!=SQLITE_OK && bCleanup==0 ){\n      sqlite3BtreeLeave(p);\n      return rc;\n    }\n    p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */\n    pBt->inTransaction = TRANS_READ;\n    btreeClearHasContent(pBt);\n  }\n\n  btreeEndTransaction(p);\n  sqlite3BtreeLeave(p);\n  return SQLITE_OK;\n}\n\n/*\n** Do both phases of a commit.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){\n  int rc;\n  sqlite3BtreeEnter(p);\n  rc = sqlite3BtreeCommitPhaseOne(p, 0);\n  if( rc==SQLITE_OK ){\n    rc = sqlite3BtreeCommitPhaseTwo(p, 0);\n  }\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** This routine sets the state to CURSOR_FAULT and the error\n** code to errCode for every cursor on any BtShared that pBtree\n** references.  Or if the writeOnly flag is set to 1, then only\n** trip write cursors and leave read cursors unchanged.\n**\n** Every cursor is a candidate to be tripped, including cursors\n** that belong to other database connections that happen to be\n** sharing the cache with pBtree.\n**\n** This routine gets called when a rollback occurs. If the writeOnly\n** flag is true, then only write-cursors need be tripped - read-only\n** cursors save their current positions so that they may continue \n** following the rollback. Or, if writeOnly is false, all cursors are \n** tripped. In general, writeOnly is false if the transaction being\n** rolled back modified the database schema. In this case b-tree root\n** pages may be moved or deleted from the database altogether, making\n** it unsafe for read cursors to continue.\n**\n** If the writeOnly flag is true and an error is encountered while \n** saving the current position of a read-only cursor, all cursors, \n** including all read-cursors are tripped.\n**\n** SQLITE_OK is returned if successful, or if an error occurs while\n** saving a cursor position, an SQLite error code.\n*/\nSQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){\n  BtCursor *p;\n  int rc = SQLITE_OK;\n\n  assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );\n  if( pBtree ){\n    sqlite3BtreeEnter(pBtree);\n    for(p=pBtree->pBt->pCursor; p; p=p->pNext){\n      if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){\n        if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){\n          rc = saveCursorPosition(p);\n          if( rc!=SQLITE_OK ){\n            (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);\n            break;\n          }\n        }\n      }else{\n        sqlite3BtreeClearCursor(p);\n        p->eState = CURSOR_FAULT;\n        p->skipNext = errCode;\n      }\n      btreeReleaseAllCursorPages(p);\n    }\n    sqlite3BtreeLeave(pBtree);\n  }\n  return rc;\n}\n\n/*\n** Set the pBt->nPage field correctly, according to the current\n** state of the database.  Assume pBt->pPage1 is valid.\n*/\nstatic void btreeSetNPage(BtShared *pBt, MemPage *pPage1){\n  int nPage = get4byte(&pPage1->aData[28]);\n  testcase( nPage==0 );\n  if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);\n  testcase( pBt->nPage!=nPage );\n  pBt->nPage = nPage;\n}\n\n/*\n** Rollback the transaction in progress.\n**\n** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).\n** Only write cursors are tripped if writeOnly is true but all cursors are\n** tripped if writeOnly is false.  Any attempt to use\n** a tripped cursor will result in an error.\n**\n** This will release the write lock on the database file.  If there\n** are no active cursors, it also releases the read lock.\n*/\nSQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){\n  int rc;\n  BtShared *pBt = p->pBt;\n  MemPage *pPage1;\n\n  assert( writeOnly==1 || writeOnly==0 );\n  assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );\n  sqlite3BtreeEnter(p);\n  if( tripCode==SQLITE_OK ){\n    rc = tripCode = saveAllCursors(pBt, 0, 0);\n    if( rc ) writeOnly = 0;\n  }else{\n    rc = SQLITE_OK;\n  }\n  if( tripCode ){\n    int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);\n    assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );\n    if( rc2!=SQLITE_OK ) rc = rc2;\n  }\n  btreeIntegrity(p);\n\n  if( p->inTrans==TRANS_WRITE ){\n    int rc2;\n\n    assert( TRANS_WRITE==pBt->inTransaction );\n    rc2 = sqlite3PagerRollback(pBt->pPager);\n    if( rc2!=SQLITE_OK ){\n      rc = rc2;\n    }\n\n    /* The rollback may have destroyed the pPage1->aData value.  So\n    ** call btreeGetPage() on page 1 again to make\n    ** sure pPage1->aData is set correctly. */\n    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){\n      btreeSetNPage(pBt, pPage1);\n      releasePageOne(pPage1);\n    }\n    assert( countValidCursors(pBt, 1)==0 );\n    pBt->inTransaction = TRANS_READ;\n    btreeClearHasContent(pBt);\n  }\n\n  btreeEndTransaction(p);\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** Start a statement subtransaction. The subtransaction can be rolled\n** back independently of the main transaction. You must start a transaction \n** before starting a subtransaction. The subtransaction is ended automatically \n** if the main transaction commits or rolls back.\n**\n** Statement subtransactions are used around individual SQL statements\n** that are contained within a BEGIN...COMMIT block.  If a constraint\n** error occurs within the statement, the effect of that one statement\n** can be rolled back without having to rollback the entire transaction.\n**\n** A statement sub-transaction is implemented as an anonymous savepoint. The\n** value passed as the second parameter is the total number of savepoints,\n** including the new anonymous savepoint, open on the B-Tree. i.e. if there\n** are no active savepoints and no other statement-transactions open,\n** iStatement is 1. This anonymous savepoint can be released or rolled back\n** using the sqlite3BtreeSavepoint() function.\n*/\nSQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){\n  int rc;\n  BtShared *pBt = p->pBt;\n  sqlite3BtreeEnter(p);\n  assert( p->inTrans==TRANS_WRITE );\n  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );\n  assert( iStatement>0 );\n  assert( iStatement>p->db->nSavepoint );\n  assert( pBt->inTransaction==TRANS_WRITE );\n  /* At the pager level, a statement transaction is a savepoint with\n  ** an index greater than all savepoints created explicitly using\n  ** SQL statements. It is illegal to open, release or rollback any\n  ** such savepoints while the statement transaction savepoint is active.\n  */\n  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** The second argument to this function, op, is always SAVEPOINT_ROLLBACK\n** or SAVEPOINT_RELEASE. This function either releases or rolls back the\n** savepoint identified by parameter iSavepoint, depending on the value \n** of op.\n**\n** Normally, iSavepoint is greater than or equal to zero. However, if op is\n** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the \n** contents of the entire transaction are rolled back. This is different\n** from a normal transaction rollback, as no locks are released and the\n** transaction remains open.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){\n  int rc = SQLITE_OK;\n  if( p && p->inTrans==TRANS_WRITE ){\n    BtShared *pBt = p->pBt;\n    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );\n    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );\n    sqlite3BtreeEnter(p);\n    if( op==SAVEPOINT_ROLLBACK ){\n      rc = saveAllCursors(pBt, 0, 0);\n    }\n    if( rc==SQLITE_OK ){\n      rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);\n    }\n    if( rc==SQLITE_OK ){\n      if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){\n        pBt->nPage = 0;\n      }\n      rc = newDatabase(pBt);\n      btreeSetNPage(pBt, pBt->pPage1);\n\n      /* pBt->nPage might be zero if the database was corrupt when \n      ** the transaction was started. Otherwise, it must be at least 1.  */\n      assert( CORRUPT_DB || pBt->nPage>0 );\n    }\n    sqlite3BtreeLeave(p);\n  }\n  return rc;\n}\n\n/*\n** Create a new cursor for the BTree whose root is on the page\n** iTable. If a read-only cursor is requested, it is assumed that\n** the caller already has at least a read-only transaction open\n** on the database already. If a write-cursor is requested, then\n** the caller is assumed to have an open write transaction.\n**\n** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only\n** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor\n** can be used for reading or for writing if other conditions for writing\n** are also met.  These are the conditions that must be met in order\n** for writing to be allowed:\n**\n** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR\n**\n** 2:  Other database connections that share the same pager cache\n**     but which are not in the READ_UNCOMMITTED state may not have\n**     cursors open with wrFlag==0 on the same table.  Otherwise\n**     the changes made by this write cursor would be visible to\n**     the read cursors in the other database connection.\n**\n** 3:  The database must be writable (not on read-only media)\n**\n** 4:  There must be an active transaction.\n**\n** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR\n** is set.  If FORDELETE is set, that is a hint to the implementation that\n** this cursor will only be used to seek to and delete entries of an index\n** as part of a larger DELETE statement.  The FORDELETE hint is not used by\n** this implementation.  But in a hypothetical alternative storage engine \n** in which index entries are automatically deleted when corresponding table\n** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE\n** operations on this cursor can be no-ops and all READ operations can \n** return a null row (2-bytes: 0x01 0x00).\n**\n** No checking is done to make sure that page iTable really is the\n** root page of a b-tree.  If it is not, then the cursor acquired\n** will not work correctly.\n**\n** It is assumed that the sqlite3BtreeCursorZero() has been called\n** on pCur to initialize the memory space prior to invoking this routine.\n*/\nstatic int btreeCursor(\n  Btree *p,                              /* The btree */\n  int iTable,                            /* Root page of table to open */\n  int wrFlag,                            /* 1 to write. 0 read-only */\n  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */\n  BtCursor *pCur                         /* Space for new cursor */\n){\n  BtShared *pBt = p->pBt;                /* Shared b-tree handle */\n  BtCursor *pX;                          /* Looping over other all cursors */\n\n  assert( sqlite3BtreeHoldsMutex(p) );\n  assert( wrFlag==0 \n       || wrFlag==BTREE_WRCSR \n       || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE) \n  );\n\n  /* The following assert statements verify that if this is a sharable \n  ** b-tree database, the connection is holding the required table locks, \n  ** and that no other connection has any open cursor that conflicts with \n  ** this lock.  The iTable<1 term disables the check for corrupt schemas. */\n  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))\n          || iTable<1 );\n  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );\n\n  /* Assert that the caller has opened the required transaction. */\n  assert( p->inTrans>TRANS_NONE );\n  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );\n  assert( pBt->pPage1 && pBt->pPage1->aData );\n  assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );\n\n  if( wrFlag ){\n    allocateTempSpace(pBt);\n    if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;\n  }\n  if( iTable<=1 ){\n    if( iTable<1 ){\n      return SQLITE_CORRUPT_BKPT;\n    }else if( btreePagecount(pBt)==0 ){\n      assert( wrFlag==0 );\n      iTable = 0;\n    }\n  }\n\n  /* Now that no other errors can occur, finish filling in the BtCursor\n  ** variables and link the cursor into the BtShared list.  */\n  pCur->pgnoRoot = (Pgno)iTable;\n  pCur->iPage = -1;\n  pCur->pKeyInfo = pKeyInfo;\n  pCur->pBtree = p;\n  pCur->pBt = pBt;\n  pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;\n  pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;\n  /* If there are two or more cursors on the same btree, then all such\n  ** cursors *must* have the BTCF_Multiple flag set. */\n  for(pX=pBt->pCursor; pX; pX=pX->pNext){\n    if( pX->pgnoRoot==(Pgno)iTable ){\n      pX->curFlags |= BTCF_Multiple;\n      pCur->curFlags |= BTCF_Multiple;\n    }\n  }\n  pCur->pNext = pBt->pCursor;\n  pBt->pCursor = pCur;\n  pCur->eState = CURSOR_INVALID;\n  return SQLITE_OK;\n}\nstatic int btreeCursorWithLock(\n  Btree *p,                              /* The btree */\n  int iTable,                            /* Root page of table to open */\n  int wrFlag,                            /* 1 to write. 0 read-only */\n  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */\n  BtCursor *pCur                         /* Space for new cursor */\n){\n  int rc;\n  sqlite3BtreeEnter(p);\n  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);\n  sqlite3BtreeLeave(p);\n  return rc;\n}\nSQLITE_PRIVATE int sqlite3BtreeCursor(\n  Btree *p,                                   /* The btree */\n  int iTable,                                 /* Root page of table to open */\n  int wrFlag,                                 /* 1 to write. 0 read-only */\n  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */\n  BtCursor *pCur                              /* Write new cursor here */\n){\n  if( p->sharable ){\n    return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);\n  }else{\n    return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);\n  }\n}\n\n/*\n** Return the size of a BtCursor object in bytes.\n**\n** This interfaces is needed so that users of cursors can preallocate\n** sufficient storage to hold a cursor.  The BtCursor object is opaque\n** to users so they cannot do the sizeof() themselves - they must call\n** this routine.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCursorSize(void){\n  return ROUND8(sizeof(BtCursor));\n}\n\n/*\n** Initialize memory that will be converted into a BtCursor object.\n**\n** The simple approach here would be to memset() the entire object\n** to zero.  But it turns out that the apPage[] and aiIdx[] arrays\n** do not need to be zeroed and they are large, so we can save a lot\n** of run-time by skipping the initialization of those elements.\n*/\nSQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){\n  memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));\n}\n\n/*\n** Close a cursor.  The read lock on the database file is released\n** when the last cursor is closed.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){\n  Btree *pBtree = pCur->pBtree;\n  if( pBtree ){\n    BtShared *pBt = pCur->pBt;\n    sqlite3BtreeEnter(pBtree);\n    assert( pBt->pCursor!=0 );\n    if( pBt->pCursor==pCur ){\n      pBt->pCursor = pCur->pNext;\n    }else{\n      BtCursor *pPrev = pBt->pCursor;\n      do{\n        if( pPrev->pNext==pCur ){\n          pPrev->pNext = pCur->pNext;\n          break;\n        }\n        pPrev = pPrev->pNext;\n      }while( ALWAYS(pPrev) );\n    }\n    btreeReleaseAllCursorPages(pCur);\n    unlockBtreeIfUnused(pBt);\n    sqlite3_free(pCur->aOverflow);\n    sqlite3_free(pCur->pKey);\n    sqlite3BtreeLeave(pBtree);\n    pCur->pBtree = 0;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Make sure the BtCursor* given in the argument has a valid\n** BtCursor.info structure.  If it is not already valid, call\n** btreeParseCell() to fill it in.\n**\n** BtCursor.info is a cache of the information in the current cell.\n** Using this cache reduces the number of calls to btreeParseCell().\n*/\n#ifndef NDEBUG\n  static int cellInfoEqual(CellInfo *a, CellInfo *b){\n    if( a->nKey!=b->nKey ) return 0;\n    if( a->pPayload!=b->pPayload ) return 0;\n    if( a->nPayload!=b->nPayload ) return 0;\n    if( a->nLocal!=b->nLocal ) return 0;\n    if( a->nSize!=b->nSize ) return 0;\n    return 1;\n  }\n  static void assertCellInfo(BtCursor *pCur){\n    CellInfo info;\n    memset(&info, 0, sizeof(info));\n    btreeParseCell(pCur->pPage, pCur->ix, &info);\n    assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );\n  }\n#else\n  #define assertCellInfo(x)\n#endif\nstatic SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){\n  if( pCur->info.nSize==0 ){\n    pCur->curFlags |= BTCF_ValidNKey;\n    btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);\n  }else{\n    assertCellInfo(pCur);\n  }\n}\n\n#ifndef NDEBUG  /* The next routine used only within assert() statements */\n/*\n** Return true if the given BtCursor is valid.  A valid cursor is one\n** that is currently pointing to a row in a (non-empty) table.\n** This is a verification routine is used only within assert() statements.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){\n  return pCur && pCur->eState==CURSOR_VALID;\n}\n#endif /* NDEBUG */\nSQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){\n  assert( pCur!=0 );\n  return pCur->eState==CURSOR_VALID;\n}\n\n/*\n** Return the value of the integer key or \"rowid\" for a table btree.\n** This routine is only valid for a cursor that is pointing into a\n** ordinary table btree.  If the cursor points to an index btree or\n** is invalid, the result of this routine is undefined.\n*/\nSQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){\n  assert( cursorHoldsMutex(pCur) );\n  assert( pCur->eState==CURSOR_VALID );\n  assert( pCur->curIntKey );\n  getCellInfo(pCur);\n  return pCur->info.nKey;\n}\n\n/*\n** Pin or unpin a cursor.\n*/\nSQLITE_PRIVATE void sqlite3BtreeCursorPin(BtCursor *pCur){\n  assert( (pCur->curFlags & BTCF_Pinned)==0 );\n  pCur->curFlags |= BTCF_Pinned;\n}\nSQLITE_PRIVATE void sqlite3BtreeCursorUnpin(BtCursor *pCur){\n  assert( (pCur->curFlags & BTCF_Pinned)!=0 );\n  pCur->curFlags &= ~BTCF_Pinned;\n}\n\n#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC\n/*\n** Return the offset into the database file for the start of the\n** payload to which the cursor is pointing.\n*/\nSQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor *pCur){\n  assert( cursorHoldsMutex(pCur) );\n  assert( pCur->eState==CURSOR_VALID );\n  getCellInfo(pCur);\n  return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +\n         (i64)(pCur->info.pPayload - pCur->pPage->aData);\n}\n#endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */\n\n/*\n** Return the number of bytes of payload for the entry that pCur is\n** currently pointing to.  For table btrees, this will be the amount\n** of data.  For index btrees, this will be the size of the key.\n**\n** The caller must guarantee that the cursor is pointing to a non-NULL\n** valid entry.  In other words, the calling procedure must guarantee\n** that the cursor has Cursor.eState==CURSOR_VALID.\n*/\nSQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){\n  assert( cursorHoldsMutex(pCur) );\n  assert( pCur->eState==CURSOR_VALID );\n  getCellInfo(pCur);\n  return pCur->info.nPayload;\n}\n\n/*\n** Return an upper bound on the size of any record for the table\n** that the cursor is pointing into.\n**\n** This is an optimization.  Everything will still work if this\n** routine always returns 2147483647 (which is the largest record\n** that SQLite can handle) or more.  But returning a smaller value might\n** prevent large memory allocations when trying to interpret a\n** corrupt datrabase.\n**\n** The current implementation merely returns the size of the underlying\n** database file.\n*/\nSQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){\n  assert( cursorHoldsMutex(pCur) );\n  assert( pCur->eState==CURSOR_VALID );\n  return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;\n}\n\n/*\n** Given the page number of an overflow page in the database (parameter\n** ovfl), this function finds the page number of the next page in the \n** linked list of overflow pages. If possible, it uses the auto-vacuum\n** pointer-map data instead of reading the content of page ovfl to do so. \n**\n** If an error occurs an SQLite error code is returned. Otherwise:\n**\n** The page number of the next overflow page in the linked list is \n** written to *pPgnoNext. If page ovfl is the last page in its linked \n** list, *pPgnoNext is set to zero. \n**\n** If ppPage is not NULL, and a reference to the MemPage object corresponding\n** to page number pOvfl was obtained, then *ppPage is set to point to that\n** reference. It is the responsibility of the caller to call releasePage()\n** on *ppPage to free the reference. In no reference was obtained (because\n** the pointer-map was used to obtain the value for *pPgnoNext), then\n** *ppPage is set to zero.\n*/\nstatic int getOverflowPage(\n  BtShared *pBt,               /* The database file */\n  Pgno ovfl,                   /* Current overflow page number */\n  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */\n  Pgno *pPgnoNext              /* OUT: Next overflow page number */\n){\n  Pgno next = 0;\n  MemPage *pPage = 0;\n  int rc = SQLITE_OK;\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert(pPgnoNext);\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n  /* Try to find the next page in the overflow list using the\n  ** autovacuum pointer-map pages. Guess that the next page in \n  ** the overflow list is page number (ovfl+1). If that guess turns \n  ** out to be wrong, fall back to loading the data of page \n  ** number ovfl to determine the next page number.\n  */\n  if( pBt->autoVacuum ){\n    Pgno pgno;\n    Pgno iGuess = ovfl+1;\n    u8 eType;\n\n    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){\n      iGuess++;\n    }\n\n    if( iGuess<=btreePagecount(pBt) ){\n      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);\n      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){\n        next = iGuess;\n        rc = SQLITE_DONE;\n      }\n    }\n  }\n#endif\n\n  assert( next==0 || rc==SQLITE_DONE );\n  if( rc==SQLITE_OK ){\n    rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);\n    assert( rc==SQLITE_OK || pPage==0 );\n    if( rc==SQLITE_OK ){\n      next = get4byte(pPage->aData);\n    }\n  }\n\n  *pPgnoNext = next;\n  if( ppPage ){\n    *ppPage = pPage;\n  }else{\n    releasePage(pPage);\n  }\n  return (rc==SQLITE_DONE ? SQLITE_OK : rc);\n}\n\n/*\n** Copy data from a buffer to a page, or from a page to a buffer.\n**\n** pPayload is a pointer to data stored on database page pDbPage.\n** If argument eOp is false, then nByte bytes of data are copied\n** from pPayload to the buffer pointed at by pBuf. If eOp is true,\n** then sqlite3PagerWrite() is called on pDbPage and nByte bytes\n** of data are copied from the buffer pBuf to pPayload.\n**\n** SQLITE_OK is returned on success, otherwise an error code.\n*/\nstatic int copyPayload(\n  void *pPayload,           /* Pointer to page data */\n  void *pBuf,               /* Pointer to buffer */\n  int nByte,                /* Number of bytes to copy */\n  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */\n  DbPage *pDbPage           /* Page containing pPayload */\n){\n  if( eOp ){\n    /* Copy data from buffer to page (a write operation) */\n    int rc = sqlite3PagerWrite(pDbPage);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    memcpy(pPayload, pBuf, nByte);\n  }else{\n    /* Copy data from page to buffer (a read operation) */\n    memcpy(pBuf, pPayload, nByte);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** This function is used to read or overwrite payload information\n** for the entry that the pCur cursor is pointing to. The eOp\n** argument is interpreted as follows:\n**\n**   0: The operation is a read. Populate the overflow cache.\n**   1: The operation is a write. Populate the overflow cache.\n**\n** A total of \"amt\" bytes are read or written beginning at \"offset\".\n** Data is read to or from the buffer pBuf.\n**\n** The content being read or written might appear on the main page\n** or be scattered out on multiple overflow pages.\n**\n** If the current cursor entry uses one or more overflow pages\n** this function may allocate space for and lazily populate\n** the overflow page-list cache array (BtCursor.aOverflow). \n** Subsequent calls use this cache to make seeking to the supplied offset \n** more efficient.\n**\n** Once an overflow page-list cache has been allocated, it must be\n** invalidated if some other cursor writes to the same table, or if\n** the cursor is moved to a different row. Additionally, in auto-vacuum\n** mode, the following events may invalidate an overflow page-list cache.\n**\n**   * An incremental vacuum,\n**   * A commit in auto_vacuum=\"full\" mode,\n**   * Creating a table (may require moving an overflow page).\n*/\nstatic int accessPayload(\n  BtCursor *pCur,      /* Cursor pointing to entry to read from */\n  u32 offset,          /* Begin reading this far into payload */\n  u32 amt,             /* Read this many bytes */\n  unsigned char *pBuf, /* Write the bytes into this buffer */ \n  int eOp              /* zero to read. non-zero to write. */\n){\n  unsigned char *aPayload;\n  int rc = SQLITE_OK;\n  int iIdx = 0;\n  MemPage *pPage = pCur->pPage;               /* Btree page of current entry */\n  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */\n#ifdef SQLITE_DIRECT_OVERFLOW_READ\n  unsigned char * const pBufStart = pBuf;     /* Start of original out buffer */\n#endif\n\n  assert( pPage );\n  assert( eOp==0 || eOp==1 );\n  assert( pCur->eState==CURSOR_VALID );\n  assert( pCur->ix<pPage->nCell );\n  assert( cursorHoldsMutex(pCur) );\n\n  getCellInfo(pCur);\n  aPayload = pCur->info.pPayload;\n  assert( offset+amt <= pCur->info.nPayload );\n\n  assert( aPayload > pPage->aData );\n  if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){\n    /* Trying to read or write past the end of the data is an error.  The\n    ** conditional above is really:\n    **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]\n    ** but is recast into its current form to avoid integer overflow problems\n    */\n    return SQLITE_CORRUPT_PAGE(pPage);\n  }\n\n  /* Check if data must be read/written to/from the btree page itself. */\n  if( offset<pCur->info.nLocal ){\n    int a = amt;\n    if( a+offset>pCur->info.nLocal ){\n      a = pCur->info.nLocal - offset;\n    }\n    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);\n    offset = 0;\n    pBuf += a;\n    amt -= a;\n  }else{\n    offset -= pCur->info.nLocal;\n  }\n\n\n  if( rc==SQLITE_OK && amt>0 ){\n    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */\n    Pgno nextPage;\n\n    nextPage = get4byte(&aPayload[pCur->info.nLocal]);\n\n    /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.\n    **\n    ** The aOverflow[] array is sized at one entry for each overflow page\n    ** in the overflow chain. The page number of the first overflow page is\n    ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array\n    ** means \"not yet known\" (the cache is lazily populated).\n    */\n    if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){\n      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;\n      if( pCur->aOverflow==0\n       || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)\n      ){\n        Pgno *aNew = (Pgno*)sqlite3Realloc(\n            pCur->aOverflow, nOvfl*2*sizeof(Pgno)\n        );\n        if( aNew==0 ){\n          return SQLITE_NOMEM_BKPT;\n        }else{\n          pCur->aOverflow = aNew;\n        }\n      }\n      memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));\n      pCur->curFlags |= BTCF_ValidOvfl;\n    }else{\n      /* If the overflow page-list cache has been allocated and the\n      ** entry for the first required overflow page is valid, skip\n      ** directly to it.\n      */\n      if( pCur->aOverflow[offset/ovflSize] ){\n        iIdx = (offset/ovflSize);\n        nextPage = pCur->aOverflow[iIdx];\n        offset = (offset%ovflSize);\n      }\n    }\n\n    assert( rc==SQLITE_OK && amt>0 );\n    while( nextPage ){\n      /* If required, populate the overflow page-list cache. */\n      assert( pCur->aOverflow[iIdx]==0\n              || pCur->aOverflow[iIdx]==nextPage\n              || CORRUPT_DB );\n      pCur->aOverflow[iIdx] = nextPage;\n\n      if( offset>=ovflSize ){\n        /* The only reason to read this page is to obtain the page\n        ** number for the next page in the overflow chain. The page\n        ** data is not required. So first try to lookup the overflow\n        ** page-list cache, if any, then fall back to the getOverflowPage()\n        ** function.\n        */\n        assert( pCur->curFlags & BTCF_ValidOvfl );\n        assert( pCur->pBtree->db==pBt->db );\n        if( pCur->aOverflow[iIdx+1] ){\n          nextPage = pCur->aOverflow[iIdx+1];\n        }else{\n          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);\n        }\n        offset -= ovflSize;\n      }else{\n        /* Need to read this page properly. It contains some of the\n        ** range of data that is being read (eOp==0) or written (eOp!=0).\n        */\n        int a = amt;\n        if( a + offset > ovflSize ){\n          a = ovflSize - offset;\n        }\n\n#ifdef SQLITE_DIRECT_OVERFLOW_READ\n        /* If all the following are true:\n        **\n        **   1) this is a read operation, and \n        **   2) data is required from the start of this overflow page, and\n        **   3) there are no dirty pages in the page-cache\n        **   4) the database is file-backed, and\n        **   5) the page is not in the WAL file\n        **   6) at least 4 bytes have already been read into the output buffer \n        **\n        ** then data can be read directly from the database file into the\n        ** output buffer, bypassing the page-cache altogether. This speeds\n        ** up loading large records that span many overflow pages.\n        */\n        if( eOp==0                                             /* (1) */\n         && offset==0                                          /* (2) */\n         && sqlite3PagerDirectReadOk(pBt->pPager, nextPage)    /* (3,4,5) */\n         && &pBuf[-4]>=pBufStart                               /* (6) */\n        ){\n          sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);\n          u8 aSave[4];\n          u8 *aWrite = &pBuf[-4];\n          assert( aWrite>=pBufStart );                         /* due to (6) */\n          memcpy(aSave, aWrite, 4);\n          rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));\n          if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT;\n          nextPage = get4byte(aWrite);\n          memcpy(aWrite, aSave, 4);\n        }else\n#endif\n\n        {\n          DbPage *pDbPage;\n          rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,\n              (eOp==0 ? PAGER_GET_READONLY : 0)\n          );\n          if( rc==SQLITE_OK ){\n            aPayload = sqlite3PagerGetData(pDbPage);\n            nextPage = get4byte(aPayload);\n            rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);\n            sqlite3PagerUnref(pDbPage);\n            offset = 0;\n          }\n        }\n        amt -= a;\n        if( amt==0 ) return rc;\n        pBuf += a;\n      }\n      if( rc ) break;\n      iIdx++;\n    }\n  }\n\n  if( rc==SQLITE_OK && amt>0 ){\n    /* Overflow chain ends prematurely */\n    return SQLITE_CORRUPT_PAGE(pPage);\n  }\n  return rc;\n}\n\n/*\n** Read part of the payload for the row at which that cursor pCur is currently\n** pointing.  \"amt\" bytes will be transferred into pBuf[].  The transfer\n** begins at \"offset\".\n**\n** pCur can be pointing to either a table or an index b-tree.\n** If pointing to a table btree, then the content section is read.  If\n** pCur is pointing to an index b-tree then the key section is read.\n**\n** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing\n** to a valid row in the table.  For sqlite3BtreePayloadChecked(), the\n** cursor might be invalid or might need to be restored before being read.\n**\n** Return SQLITE_OK on success or an error code if anything goes\n** wrong.  An error is returned if \"offset+amt\" is larger than\n** the available payload.\n*/\nSQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){\n  assert( cursorHoldsMutex(pCur) );\n  assert( pCur->eState==CURSOR_VALID );\n  assert( pCur->iPage>=0 && pCur->pPage );\n  assert( pCur->ix<pCur->pPage->nCell );\n  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);\n}\n\n/*\n** This variant of sqlite3BtreePayload() works even if the cursor has not\n** in the CURSOR_VALID state.  It is only used by the sqlite3_blob_read()\n** interface.\n*/\n#ifndef SQLITE_OMIT_INCRBLOB\nstatic SQLITE_NOINLINE int accessPayloadChecked(\n  BtCursor *pCur,\n  u32 offset,\n  u32 amt,\n  void *pBuf\n){\n  int rc;\n  if ( pCur->eState==CURSOR_INVALID ){\n    return SQLITE_ABORT;\n  }\n  assert( cursorOwnsBtShared(pCur) );\n  rc = btreeRestoreCursorPosition(pCur);\n  return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);\n}\nSQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){\n  if( pCur->eState==CURSOR_VALID ){\n    assert( cursorOwnsBtShared(pCur) );\n    return accessPayload(pCur, offset, amt, pBuf, 0);\n  }else{\n    return accessPayloadChecked(pCur, offset, amt, pBuf);\n  }\n}\n#endif /* SQLITE_OMIT_INCRBLOB */\n\n/*\n** Return a pointer to payload information from the entry that the \n** pCur cursor is pointing to.  The pointer is to the beginning of\n** the key if index btrees (pPage->intKey==0) and is the data for\n** table btrees (pPage->intKey==1). The number of bytes of available\n** key/data is written into *pAmt.  If *pAmt==0, then the value\n** returned will not be a valid pointer.\n**\n** This routine is an optimization.  It is common for the entire key\n** and data to fit on the local page and for there to be no overflow\n** pages.  When that is so, this routine can be used to access the\n** key and data without making a copy.  If the key and/or data spills\n** onto overflow pages, then accessPayload() must be used to reassemble\n** the key/data and copy it into a preallocated buffer.\n**\n** The pointer returned by this routine looks directly into the cached\n** page of the database.  The data might change or move the next time\n** any btree routine is called.\n*/\nstatic const void *fetchPayload(\n  BtCursor *pCur,      /* Cursor pointing to entry to read from */\n  u32 *pAmt            /* Write the number of available bytes here */\n){\n  int amt;\n  assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);\n  assert( pCur->eState==CURSOR_VALID );\n  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );\n  assert( cursorOwnsBtShared(pCur) );\n  assert( pCur->ix<pCur->pPage->nCell );\n  assert( pCur->info.nSize>0 );\n  assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );\n  assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);\n  amt = pCur->info.nLocal;\n  if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){\n    /* There is too little space on the page for the expected amount\n    ** of local content. Database must be corrupt. */\n    assert( CORRUPT_DB );\n    amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));\n  }\n  *pAmt = (u32)amt;\n  return (void*)pCur->info.pPayload;\n}\n\n\n/*\n** For the entry that cursor pCur is point to, return as\n** many bytes of the key or data as are available on the local\n** b-tree page.  Write the number of available bytes into *pAmt.\n**\n** The pointer returned is ephemeral.  The key/data may move\n** or be destroyed on the next call to any Btree routine,\n** including calls from other threads against the same cache.\n** Hence, a mutex on the BtShared should be held prior to calling\n** this routine.\n**\n** These routines is used to get quick access to key and data\n** in the common case where no overflow pages are used.\n*/\nSQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){\n  return fetchPayload(pCur, pAmt);\n}\n\n\n/*\n** Move the cursor down to a new child page.  The newPgno argument is the\n** page number of the child page to move to.\n**\n** This function returns SQLITE_CORRUPT if the page-header flags field of\n** the new child page does not match the flags field of the parent (i.e.\n** if an intkey page appears to be the parent of a non-intkey page, or\n** vice-versa).\n*/\nstatic int moveToChild(BtCursor *pCur, u32 newPgno){\n  BtShared *pBt = pCur->pBt;\n\n  assert( cursorOwnsBtShared(pCur) );\n  assert( pCur->eState==CURSOR_VALID );\n  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );\n  assert( pCur->iPage>=0 );\n  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){\n    return SQLITE_CORRUPT_BKPT;\n  }\n  pCur->info.nSize = 0;\n  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);\n  pCur->aiIdx[pCur->iPage] = pCur->ix;\n  pCur->apPage[pCur->iPage] = pCur->pPage;\n  pCur->ix = 0;\n  pCur->iPage++;\n  return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);\n}\n\n#ifdef SQLITE_DEBUG\n/*\n** Page pParent is an internal (non-leaf) tree page. This function \n** asserts that page number iChild is the left-child if the iIdx'th\n** cell in page pParent. Or, if iIdx is equal to the total number of\n** cells in pParent, that page number iChild is the right-child of\n** the page.\n*/\nstatic void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){\n  if( CORRUPT_DB ) return;  /* The conditions tested below might not be true\n                            ** in a corrupt database */\n  assert( iIdx<=pParent->nCell );\n  if( iIdx==pParent->nCell ){\n    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );\n  }else{\n    assert( get4byte(findCell(pParent, iIdx))==iChild );\n  }\n}\n#else\n#  define assertParentIndex(x,y,z) \n#endif\n\n/*\n** Move the cursor up to the parent page.\n**\n** pCur->idx is set to the cell index that contains the pointer\n** to the page we are coming from.  If we are coming from the\n** right-most child page then pCur->idx is set to one more than\n** the largest cell index.\n*/\nstatic void moveToParent(BtCursor *pCur){\n  MemPage *pLeaf;\n  assert( cursorOwnsBtShared(pCur) );\n  assert( pCur->eState==CURSOR_VALID );\n  assert( pCur->iPage>0 );\n  assert( pCur->pPage );\n  assertParentIndex(\n    pCur->apPage[pCur->iPage-1], \n    pCur->aiIdx[pCur->iPage-1], \n    pCur->pPage->pgno\n  );\n  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );\n  pCur->info.nSize = 0;\n  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);\n  pCur->ix = pCur->aiIdx[pCur->iPage-1];\n  pLeaf = pCur->pPage;\n  pCur->pPage = pCur->apPage[--pCur->iPage];\n  releasePageNotNull(pLeaf);\n}\n\n/*\n** Move the cursor to point to the root page of its b-tree structure.\n**\n** If the table has a virtual root page, then the cursor is moved to point\n** to the virtual root page instead of the actual root page. A table has a\n** virtual root page when the actual root page contains no cells and a \n** single child page. This can only happen with the table rooted at page 1.\n**\n** If the b-tree structure is empty, the cursor state is set to \n** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,\n** the cursor is set to point to the first cell located on the root\n** (or virtual root) page and the cursor state is set to CURSOR_VALID.\n**\n** If this function returns successfully, it may be assumed that the\n** page-header flags indicate that the [virtual] root-page is the expected \n** kind of b-tree page (i.e. if when opening the cursor the caller did not\n** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,\n** indicating a table b-tree, or if the caller did specify a KeyInfo \n** structure the flags byte is set to 0x02 or 0x0A, indicating an index\n** b-tree).\n*/\nstatic int moveToRoot(BtCursor *pCur){\n  MemPage *pRoot;\n  int rc = SQLITE_OK;\n\n  assert( cursorOwnsBtShared(pCur) );\n  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );\n  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );\n  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );\n  assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );\n  assert( pCur->pgnoRoot>0 || pCur->iPage<0 );\n\n  if( pCur->iPage>=0 ){\n    if( pCur->iPage ){\n      releasePageNotNull(pCur->pPage);\n      while( --pCur->iPage ){\n        releasePageNotNull(pCur->apPage[pCur->iPage]);\n      }\n      pCur->pPage = pCur->apPage[0];\n      goto skip_init;\n    }\n  }else if( pCur->pgnoRoot==0 ){\n    pCur->eState = CURSOR_INVALID;\n    return SQLITE_EMPTY;\n  }else{\n    assert( pCur->iPage==(-1) );\n    if( pCur->eState>=CURSOR_REQUIRESEEK ){\n      if( pCur->eState==CURSOR_FAULT ){\n        assert( pCur->skipNext!=SQLITE_OK );\n        return pCur->skipNext;\n      }\n      sqlite3BtreeClearCursor(pCur);\n    }\n    rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,\n                        0, pCur->curPagerFlags);\n    if( rc!=SQLITE_OK ){\n      pCur->eState = CURSOR_INVALID;\n      return rc;\n    }\n    pCur->iPage = 0;\n    pCur->curIntKey = pCur->pPage->intKey;\n  }\n  pRoot = pCur->pPage;\n  assert( pRoot->pgno==pCur->pgnoRoot );\n\n  /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor\n  ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is\n  ** NULL, the caller expects a table b-tree. If this is not the case,\n  ** return an SQLITE_CORRUPT error. \n  **\n  ** Earlier versions of SQLite assumed that this test could not fail\n  ** if the root page was already loaded when this function was called (i.e.\n  ** if pCur->iPage>=0). But this is not so if the database is corrupted \n  ** in such a way that page pRoot is linked into a second b-tree table \n  ** (or the freelist).  */\n  assert( pRoot->intKey==1 || pRoot->intKey==0 );\n  if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){\n    return SQLITE_CORRUPT_PAGE(pCur->pPage);\n  }\n\nskip_init:  \n  pCur->ix = 0;\n  pCur->info.nSize = 0;\n  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);\n\n  pRoot = pCur->pPage;\n  if( pRoot->nCell>0 ){\n    pCur->eState = CURSOR_VALID;\n  }else if( !pRoot->leaf ){\n    Pgno subpage;\n    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;\n    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);\n    pCur->eState = CURSOR_VALID;\n    rc = moveToChild(pCur, subpage);\n  }else{\n    pCur->eState = CURSOR_INVALID;\n    rc = SQLITE_EMPTY;\n  }\n  return rc;\n}\n\n/*\n** Move the cursor down to the left-most leaf entry beneath the\n** entry to which it is currently pointing.\n**\n** The left-most leaf is the one with the smallest key - the first\n** in ascending order.\n*/\nstatic int moveToLeftmost(BtCursor *pCur){\n  Pgno pgno;\n  int rc = SQLITE_OK;\n  MemPage *pPage;\n\n  assert( cursorOwnsBtShared(pCur) );\n  assert( pCur->eState==CURSOR_VALID );\n  while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){\n    assert( pCur->ix<pPage->nCell );\n    pgno = get4byte(findCell(pPage, pCur->ix));\n    rc = moveToChild(pCur, pgno);\n  }\n  return rc;\n}\n\n/*\n** Move the cursor down to the right-most leaf entry beneath the\n** page to which it is currently pointing.  Notice the difference\n** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()\n** finds the left-most entry beneath the *entry* whereas moveToRightmost()\n** finds the right-most entry beneath the *page*.\n**\n** The right-most entry is the one with the largest key - the last\n** key in ascending order.\n*/\nstatic int moveToRightmost(BtCursor *pCur){\n  Pgno pgno;\n  int rc = SQLITE_OK;\n  MemPage *pPage = 0;\n\n  assert( cursorOwnsBtShared(pCur) );\n  assert( pCur->eState==CURSOR_VALID );\n  while( !(pPage = pCur->pPage)->leaf ){\n    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);\n    pCur->ix = pPage->nCell;\n    rc = moveToChild(pCur, pgno);\n    if( rc ) return rc;\n  }\n  pCur->ix = pPage->nCell-1;\n  assert( pCur->info.nSize==0 );\n  assert( (pCur->curFlags & BTCF_ValidNKey)==0 );\n  return SQLITE_OK;\n}\n\n/* Move the cursor to the first entry in the table.  Return SQLITE_OK\n** on success.  Set *pRes to 0 if the cursor actually points to something\n** or set *pRes to 1 if the table is empty.\n*/\nSQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){\n  int rc;\n\n  assert( cursorOwnsBtShared(pCur) );\n  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );\n  rc = moveToRoot(pCur);\n  if( rc==SQLITE_OK ){\n    assert( pCur->pPage->nCell>0 );\n    *pRes = 0;\n    rc = moveToLeftmost(pCur);\n  }else if( rc==SQLITE_EMPTY ){\n    assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );\n    *pRes = 1;\n    rc = SQLITE_OK;\n  }\n  return rc;\n}\n\n/* Move the cursor to the last entry in the table.  Return SQLITE_OK\n** on success.  Set *pRes to 0 if the cursor actually points to something\n** or set *pRes to 1 if the table is empty.\n*/\nSQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){\n  int rc;\n \n  assert( cursorOwnsBtShared(pCur) );\n  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );\n\n  /* If the cursor already points to the last entry, this is a no-op. */\n  if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){\n#ifdef SQLITE_DEBUG\n    /* This block serves to assert() that the cursor really does point \n    ** to the last entry in the b-tree. */\n    int ii;\n    for(ii=0; ii<pCur->iPage; ii++){\n      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );\n    }\n    assert( pCur->ix==pCur->pPage->nCell-1 );\n    assert( pCur->pPage->leaf );\n#endif\n    *pRes = 0;\n    return SQLITE_OK;\n  }\n\n  rc = moveToRoot(pCur);\n  if( rc==SQLITE_OK ){\n    assert( pCur->eState==CURSOR_VALID );\n    *pRes = 0;\n    rc = moveToRightmost(pCur);\n    if( rc==SQLITE_OK ){\n      pCur->curFlags |= BTCF_AtLast;\n    }else{\n      pCur->curFlags &= ~BTCF_AtLast;\n    }\n  }else if( rc==SQLITE_EMPTY ){\n    assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );\n    *pRes = 1;\n    rc = SQLITE_OK;\n  }\n  return rc;\n}\n\n/* Move the cursor so that it points to an entry near the key \n** specified by pIdxKey or intKey.   Return a success code.\n**\n** For INTKEY tables, the intKey parameter is used.  pIdxKey \n** must be NULL.  For index tables, pIdxKey is used and intKey\n** is ignored.\n**\n** If an exact match is not found, then the cursor is always\n** left pointing at a leaf page which would hold the entry if it\n** were present.  The cursor might point to an entry that comes\n** before or after the key.\n**\n** An integer is written into *pRes which is the result of\n** comparing the key with the entry to which the cursor is \n** pointing.  The meaning of the integer written into\n** *pRes is as follows:\n**\n**     *pRes<0      The cursor is left pointing at an entry that\n**                  is smaller than intKey/pIdxKey or if the table is empty\n**                  and the cursor is therefore left point to nothing.\n**\n**     *pRes==0     The cursor is left pointing at an entry that\n**                  exactly matches intKey/pIdxKey.\n**\n**     *pRes>0      The cursor is left pointing at an entry that\n**                  is larger than intKey/pIdxKey.\n**\n** For index tables, the pIdxKey->eqSeen field is set to 1 if there\n** exists an entry in the table that exactly matches pIdxKey.  \n*/\nSQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(\n  BtCursor *pCur,          /* The cursor to be moved */\n  UnpackedRecord *pIdxKey, /* Unpacked index key */\n  i64 intKey,              /* The table key */\n  int biasRight,           /* If true, bias the search to the high end */\n  int *pRes                /* Write search results here */\n){\n  int rc;\n  RecordCompare xRecordCompare;\n\n  assert( cursorOwnsBtShared(pCur) );\n  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );\n  assert( pRes );\n  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );\n  assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );\n\n  /* If the cursor is already positioned at the point we are trying\n  ** to move to, then just return without doing any work */\n  if( pIdxKey==0\n   && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0\n  ){\n    if( pCur->info.nKey==intKey ){\n      *pRes = 0;\n      return SQLITE_OK;\n    }\n    if( pCur->info.nKey<intKey ){\n      if( (pCur->curFlags & BTCF_AtLast)!=0 ){\n        *pRes = -1;\n        return SQLITE_OK;\n      }\n      /* If the requested key is one more than the previous key, then\n      ** try to get there using sqlite3BtreeNext() rather than a full\n      ** binary search.  This is an optimization only.  The correct answer\n      ** is still obtained without this case, only a little more slowely */\n      if( pCur->info.nKey+1==intKey ){\n        *pRes = 0;\n        rc = sqlite3BtreeNext(pCur, 0);\n        if( rc==SQLITE_OK ){\n          getCellInfo(pCur);\n          if( pCur->info.nKey==intKey ){\n            return SQLITE_OK;\n          }\n        }else if( rc==SQLITE_DONE ){\n          rc = SQLITE_OK;\n        }else{\n          return rc;\n        }\n      }\n    }\n  }\n\n  if( pIdxKey ){\n    xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);\n    pIdxKey->errCode = 0;\n    assert( pIdxKey->default_rc==1 \n         || pIdxKey->default_rc==0 \n         || pIdxKey->default_rc==-1\n    );\n  }else{\n    xRecordCompare = 0; /* All keys are integers */\n  }\n\n  rc = moveToRoot(pCur);\n  if( rc ){\n    if( rc==SQLITE_EMPTY ){\n      assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );\n      *pRes = -1;\n      return SQLITE_OK;\n    }\n    return rc;\n  }\n  assert( pCur->pPage );\n  assert( pCur->pPage->isInit );\n  assert( pCur->eState==CURSOR_VALID );\n  assert( pCur->pPage->nCell > 0 );\n  assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );\n  assert( pCur->curIntKey || pIdxKey );\n  for(;;){\n    int lwr, upr, idx, c;\n    Pgno chldPg;\n    MemPage *pPage = pCur->pPage;\n    u8 *pCell;                          /* Pointer to current cell in pPage */\n\n    /* pPage->nCell must be greater than zero. If this is the root-page\n    ** the cursor would have been INVALID above and this for(;;) loop\n    ** not run. If this is not the root-page, then the moveToChild() routine\n    ** would have already detected db corruption. Similarly, pPage must\n    ** be the right kind (index or table) of b-tree page. Otherwise\n    ** a moveToChild() or moveToRoot() call would have detected corruption.  */\n    assert( pPage->nCell>0 );\n    assert( pPage->intKey==(pIdxKey==0) );\n    lwr = 0;\n    upr = pPage->nCell-1;\n    assert( biasRight==0 || biasRight==1 );\n    idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */\n    pCur->ix = (u16)idx;\n    if( xRecordCompare==0 ){\n      for(;;){\n        i64 nCellKey;\n        pCell = findCellPastPtr(pPage, idx);\n        if( pPage->intKeyLeaf ){\n          while( 0x80 <= *(pCell++) ){\n            if( pCell>=pPage->aDataEnd ){\n              return SQLITE_CORRUPT_PAGE(pPage);\n            }\n          }\n        }\n        getVarint(pCell, (u64*)&nCellKey);\n        if( nCellKey<intKey ){\n          lwr = idx+1;\n          if( lwr>upr ){ c = -1; break; }\n        }else if( nCellKey>intKey ){\n          upr = idx-1;\n          if( lwr>upr ){ c = +1; break; }\n        }else{\n          assert( nCellKey==intKey );\n          pCur->ix = (u16)idx;\n          if( !pPage->leaf ){\n            lwr = idx;\n            goto moveto_next_layer;\n          }else{\n            pCur->curFlags |= BTCF_ValidNKey;\n            pCur->info.nKey = nCellKey;\n            pCur->info.nSize = 0;\n            *pRes = 0;\n            return SQLITE_OK;\n          }\n        }\n        assert( lwr+upr>=0 );\n        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */\n      }\n    }else{\n      for(;;){\n        int nCell;  /* Size of the pCell cell in bytes */\n        pCell = findCellPastPtr(pPage, idx);\n\n        /* The maximum supported page-size is 65536 bytes. This means that\n        ** the maximum number of record bytes stored on an index B-Tree\n        ** page is less than 16384 bytes and may be stored as a 2-byte\n        ** varint. This information is used to attempt to avoid parsing \n        ** the entire cell by checking for the cases where the record is \n        ** stored entirely within the b-tree page by inspecting the first \n        ** 2 bytes of the cell.\n        */\n        nCell = pCell[0];\n        if( nCell<=pPage->max1bytePayload ){\n          /* This branch runs if the record-size field of the cell is a\n          ** single byte varint and the record fits entirely on the main\n          ** b-tree page.  */\n          testcase( pCell+nCell+1==pPage->aDataEnd );\n          c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);\n        }else if( !(pCell[1] & 0x80) \n          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal\n        ){\n          /* The record-size field is a 2 byte varint and the record \n          ** fits entirely on the main b-tree page.  */\n          testcase( pCell+nCell+2==pPage->aDataEnd );\n          c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);\n        }else{\n          /* The record flows over onto one or more overflow pages. In\n          ** this case the whole cell needs to be parsed, a buffer allocated\n          ** and accessPayload() used to retrieve the record into the\n          ** buffer before VdbeRecordCompare() can be called. \n          **\n          ** If the record is corrupt, the xRecordCompare routine may read\n          ** up to two varints past the end of the buffer. An extra 18 \n          ** bytes of padding is allocated at the end of the buffer in\n          ** case this happens.  */\n          void *pCellKey;\n          u8 * const pCellBody = pCell - pPage->childPtrSize;\n          const int nOverrun = 18;  /* Size of the overrun padding */\n          pPage->xParseCell(pPage, pCellBody, &pCur->info);\n          nCell = (int)pCur->info.nKey;\n          testcase( nCell<0 );   /* True if key size is 2^32 or more */\n          testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */\n          testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */\n          testcase( nCell==2 );  /* Minimum legal index key size */\n          if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){\n            rc = SQLITE_CORRUPT_PAGE(pPage);\n            goto moveto_finish;\n          }\n          pCellKey = sqlite3Malloc( nCell+nOverrun );\n          if( pCellKey==0 ){\n            rc = SQLITE_NOMEM_BKPT;\n            goto moveto_finish;\n          }\n          pCur->ix = (u16)idx;\n          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);\n          memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */\n          pCur->curFlags &= ~BTCF_ValidOvfl;\n          if( rc ){\n            sqlite3_free(pCellKey);\n            goto moveto_finish;\n          }\n          c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);\n          sqlite3_free(pCellKey);\n        }\n        assert( \n            (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)\n         && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)\n        );\n        if( c<0 ){\n          lwr = idx+1;\n        }else if( c>0 ){\n          upr = idx-1;\n        }else{\n          assert( c==0 );\n          *pRes = 0;\n          rc = SQLITE_OK;\n          pCur->ix = (u16)idx;\n          if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;\n          goto moveto_finish;\n        }\n        if( lwr>upr ) break;\n        assert( lwr+upr>=0 );\n        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */\n      }\n    }\n    assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );\n    assert( pPage->isInit );\n    if( pPage->leaf ){\n      assert( pCur->ix<pCur->pPage->nCell );\n      pCur->ix = (u16)idx;\n      *pRes = c;\n      rc = SQLITE_OK;\n      goto moveto_finish;\n    }\nmoveto_next_layer:\n    if( lwr>=pPage->nCell ){\n      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);\n    }else{\n      chldPg = get4byte(findCell(pPage, lwr));\n    }\n    pCur->ix = (u16)lwr;\n    rc = moveToChild(pCur, chldPg);\n    if( rc ) break;\n  }\nmoveto_finish:\n  pCur->info.nSize = 0;\n  assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );\n  return rc;\n}\n\n\n/*\n** Return TRUE if the cursor is not pointing at an entry of the table.\n**\n** TRUE will be returned after a call to sqlite3BtreeNext() moves\n** past the last entry in the table or sqlite3BtreePrev() moves past\n** the first entry.  TRUE is also returned if the table is empty.\n*/\nSQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){\n  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries\n  ** have been deleted? This API will need to change to return an error code\n  ** as well as the boolean result value.\n  */\n  return (CURSOR_VALID!=pCur->eState);\n}\n\n/*\n** Return an estimate for the number of rows in the table that pCur is\n** pointing to.  Return a negative number if no estimate is currently \n** available.\n*/\nSQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){\n  i64 n;\n  u8 i;\n\n  assert( cursorOwnsBtShared(pCur) );\n  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );\n\n  /* Currently this interface is only called by the OP_IfSmaller\n  ** opcode, and it that case the cursor will always be valid and\n  ** will always point to a leaf node. */\n  if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;\n  if( NEVER(pCur->pPage->leaf==0) ) return -1;\n\n  n = pCur->pPage->nCell;\n  for(i=0; i<pCur->iPage; i++){\n    n *= pCur->apPage[i]->nCell;\n  }\n  return n;\n}\n\n/*\n** Advance the cursor to the next entry in the database. \n** Return value:\n**\n**    SQLITE_OK        success\n**    SQLITE_DONE      cursor is already pointing at the last element\n**    otherwise        some kind of error occurred\n**\n** The main entry point is sqlite3BtreeNext().  That routine is optimized\n** for the common case of merely incrementing the cell counter BtCursor.aiIdx\n** to the next cell on the current page.  The (slower) btreeNext() helper\n** routine is called when it is necessary to move to a different page or\n** to restore the cursor.\n**\n** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the\n** cursor corresponds to an SQL index and this routine could have been\n** skipped if the SQL index had been a unique index.  The F argument\n** is a hint to the implement.  SQLite btree implementation does not use\n** this hint, but COMDB2 does.\n*/\nstatic SQLITE_NOINLINE int btreeNext(BtCursor *pCur){\n  int rc;\n  int idx;\n  MemPage *pPage;\n\n  assert( cursorOwnsBtShared(pCur) );\n  if( pCur->eState!=CURSOR_VALID ){\n    assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );\n    rc = restoreCursorPosition(pCur);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    if( CURSOR_INVALID==pCur->eState ){\n      return SQLITE_DONE;\n    }\n    if( pCur->eState==CURSOR_SKIPNEXT ){\n      pCur->eState = CURSOR_VALID;\n      if( pCur->skipNext>0 ) return SQLITE_OK;\n    }\n  }\n\n  pPage = pCur->pPage;\n  idx = ++pCur->ix;\n  if( !pPage->isInit ){\n    /* The only known way for this to happen is for there to be a\n    ** recursive SQL function that does a DELETE operation as part of a\n    ** SELECT which deletes content out from under an active cursor\n    ** in a corrupt database file where the table being DELETE-ed from\n    ** has pages in common with the table being queried.  See TH3\n    ** module cov1/btree78.test testcase 220 (2018-06-08) for an\n    ** example. */\n    return SQLITE_CORRUPT_BKPT;\n  }\n\n  /* If the database file is corrupt, it is possible for the value of idx \n  ** to be invalid here. This can only occur if a second cursor modifies\n  ** the page while cursor pCur is holding a reference to it. Which can\n  ** only happen if the database is corrupt in such a way as to link the\n  ** page into more than one b-tree structure.\n  **\n  ** Update 2019-12-23: appears to long longer be possible after the\n  ** addition of anotherValidCursor() condition on balance_deeper().  */\n  harmless( idx>pPage->nCell );\n\n  if( idx>=pPage->nCell ){\n    if( !pPage->leaf ){\n      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));\n      if( rc ) return rc;\n      return moveToLeftmost(pCur);\n    }\n    do{\n      if( pCur->iPage==0 ){\n        pCur->eState = CURSOR_INVALID;\n        return SQLITE_DONE;\n      }\n      moveToParent(pCur);\n      pPage = pCur->pPage;\n    }while( pCur->ix>=pPage->nCell );\n    if( pPage->intKey ){\n      return sqlite3BtreeNext(pCur, 0);\n    }else{\n      return SQLITE_OK;\n    }\n  }\n  if( pPage->leaf ){\n    return SQLITE_OK;\n  }else{\n    return moveToLeftmost(pCur);\n  }\n}\nSQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int flags){\n  MemPage *pPage;\n  UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */\n  assert( cursorOwnsBtShared(pCur) );\n  assert( flags==0 || flags==1 );\n  pCur->info.nSize = 0;\n  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);\n  if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);\n  pPage = pCur->pPage;\n  if( (++pCur->ix)>=pPage->nCell ){\n    pCur->ix--;\n    return btreeNext(pCur);\n  }\n  if( pPage->leaf ){\n    return SQLITE_OK;\n  }else{\n    return moveToLeftmost(pCur);\n  }\n}\n\n/*\n** Step the cursor to the back to the previous entry in the database.\n** Return values:\n**\n**     SQLITE_OK     success\n**     SQLITE_DONE   the cursor is already on the first element of the table\n**     otherwise     some kind of error occurred\n**\n** The main entry point is sqlite3BtreePrevious().  That routine is optimized\n** for the common case of merely decrementing the cell counter BtCursor.aiIdx\n** to the previous cell on the current page.  The (slower) btreePrevious()\n** helper routine is called when it is necessary to move to a different page\n** or to restore the cursor.\n**\n** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then\n** the cursor corresponds to an SQL index and this routine could have been\n** skipped if the SQL index had been a unique index.  The F argument is a\n** hint to the implement.  The native SQLite btree implementation does not\n** use this hint, but COMDB2 does.\n*/\nstatic SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){\n  int rc;\n  MemPage *pPage;\n\n  assert( cursorOwnsBtShared(pCur) );\n  assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );\n  assert( pCur->info.nSize==0 );\n  if( pCur->eState!=CURSOR_VALID ){\n    rc = restoreCursorPosition(pCur);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    if( CURSOR_INVALID==pCur->eState ){\n      return SQLITE_DONE;\n    }\n    if( CURSOR_SKIPNEXT==pCur->eState ){\n      pCur->eState = CURSOR_VALID;\n      if( pCur->skipNext<0 ) return SQLITE_OK;\n    }\n  }\n\n  pPage = pCur->pPage;\n  assert( pPage->isInit );\n  if( !pPage->leaf ){\n    int idx = pCur->ix;\n    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));\n    if( rc ) return rc;\n    rc = moveToRightmost(pCur);\n  }else{\n    while( pCur->ix==0 ){\n      if( pCur->iPage==0 ){\n        pCur->eState = CURSOR_INVALID;\n        return SQLITE_DONE;\n      }\n      moveToParent(pCur);\n    }\n    assert( pCur->info.nSize==0 );\n    assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );\n\n    pCur->ix--;\n    pPage = pCur->pPage;\n    if( pPage->intKey && !pPage->leaf ){\n      rc = sqlite3BtreePrevious(pCur, 0);\n    }else{\n      rc = SQLITE_OK;\n    }\n  }\n  return rc;\n}\nSQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){\n  assert( cursorOwnsBtShared(pCur) );\n  assert( flags==0 || flags==1 );\n  UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */\n  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);\n  pCur->info.nSize = 0;\n  if( pCur->eState!=CURSOR_VALID\n   || pCur->ix==0\n   || pCur->pPage->leaf==0\n  ){\n    return btreePrevious(pCur);\n  }\n  pCur->ix--;\n  return SQLITE_OK;\n}\n\n/*\n** Allocate a new page from the database file.\n**\n** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()\n** has already been called on the new page.)  The new page has also\n** been referenced and the calling routine is responsible for calling\n** sqlite3PagerUnref() on the new page when it is done.\n**\n** SQLITE_OK is returned on success.  Any other return value indicates\n** an error.  *ppPage is set to NULL in the event of an error.\n**\n** If the \"nearby\" parameter is not 0, then an effort is made to \n** locate a page close to the page number \"nearby\".  This can be used in an\n** attempt to keep related pages close to each other in the database file,\n** which in turn can make database access faster.\n**\n** If the eMode parameter is BTALLOC_EXACT and the nearby page exists\n** anywhere on the free-list, then it is guaranteed to be returned.  If\n** eMode is BTALLOC_LT then the page returned will be less than or equal\n** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there\n** are no restrictions on which page is returned.\n*/\nstatic int allocateBtreePage(\n  BtShared *pBt,         /* The btree */\n  MemPage **ppPage,      /* Store pointer to the allocated page here */\n  Pgno *pPgno,           /* Store the page number here */\n  Pgno nearby,           /* Search for a page near this one */\n  u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */\n){\n  MemPage *pPage1;\n  int rc;\n  u32 n;     /* Number of pages on the freelist */\n  u32 k;     /* Number of leaves on the trunk of the freelist */\n  MemPage *pTrunk = 0;\n  MemPage *pPrevTrunk = 0;\n  Pgno mxPage;     /* Total size of the database file */\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );\n  pPage1 = pBt->pPage1;\n  mxPage = btreePagecount(pBt);\n  /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36\n  ** stores stores the total number of pages on the freelist. */\n  n = get4byte(&pPage1->aData[36]);\n  testcase( n==mxPage-1 );\n  if( n>=mxPage ){\n    return SQLITE_CORRUPT_BKPT;\n  }\n  if( n>0 ){\n    /* There are pages on the freelist.  Reuse one of those pages. */\n    Pgno iTrunk;\n    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */\n    u32 nSearch = 0;   /* Count of the number of search attempts */\n    \n    /* If eMode==BTALLOC_EXACT and a query of the pointer-map\n    ** shows that the page 'nearby' is somewhere on the free-list, then\n    ** the entire-list will be searched for that page.\n    */\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( eMode==BTALLOC_EXACT ){\n      if( nearby<=mxPage ){\n        u8 eType;\n        assert( nearby>0 );\n        assert( pBt->autoVacuum );\n        rc = ptrmapGet(pBt, nearby, &eType, 0);\n        if( rc ) return rc;\n        if( eType==PTRMAP_FREEPAGE ){\n          searchList = 1;\n        }\n      }\n    }else if( eMode==BTALLOC_LE ){\n      searchList = 1;\n    }\n#endif\n\n    /* Decrement the free-list count by 1. Set iTrunk to the index of the\n    ** first free-list trunk page. iPrevTrunk is initially 1.\n    */\n    rc = sqlite3PagerWrite(pPage1->pDbPage);\n    if( rc ) return rc;\n    put4byte(&pPage1->aData[36], n-1);\n\n    /* The code within this loop is run only once if the 'searchList' variable\n    ** is not true. Otherwise, it runs once for each trunk-page on the\n    ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)\n    ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)\n    */\n    do {\n      pPrevTrunk = pTrunk;\n      if( pPrevTrunk ){\n        /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page\n        ** is the page number of the next freelist trunk page in the list or\n        ** zero if this is the last freelist trunk page. */\n        iTrunk = get4byte(&pPrevTrunk->aData[0]);\n      }else{\n        /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32\n        ** stores the page number of the first page of the freelist, or zero if\n        ** the freelist is empty. */\n        iTrunk = get4byte(&pPage1->aData[32]);\n      }\n      testcase( iTrunk==mxPage );\n      if( iTrunk>mxPage || nSearch++ > n ){\n        rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);\n      }else{\n        rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);\n      }\n      if( rc ){\n        pTrunk = 0;\n        goto end_allocate_page;\n      }\n      assert( pTrunk!=0 );\n      assert( pTrunk->aData!=0 );\n      /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page\n      ** is the number of leaf page pointers to follow. */\n      k = get4byte(&pTrunk->aData[4]);\n      if( k==0 && !searchList ){\n        /* The trunk has no leaves and the list is not being searched. \n        ** So extract the trunk page itself and use it as the newly \n        ** allocated page */\n        assert( pPrevTrunk==0 );\n        rc = sqlite3PagerWrite(pTrunk->pDbPage);\n        if( rc ){\n          goto end_allocate_page;\n        }\n        *pPgno = iTrunk;\n        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);\n        *ppPage = pTrunk;\n        pTrunk = 0;\n        TRACE((\"ALLOCATE: %d trunk - %d free pages left\\n\", *pPgno, n-1));\n      }else if( k>(u32)(pBt->usableSize/4 - 2) ){\n        /* Value of k is out of range.  Database corruption */\n        rc = SQLITE_CORRUPT_PGNO(iTrunk);\n        goto end_allocate_page;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n      }else if( searchList \n            && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE)) \n      ){\n        /* The list is being searched and this trunk page is the page\n        ** to allocate, regardless of whether it has leaves.\n        */\n        *pPgno = iTrunk;\n        *ppPage = pTrunk;\n        searchList = 0;\n        rc = sqlite3PagerWrite(pTrunk->pDbPage);\n        if( rc ){\n          goto end_allocate_page;\n        }\n        if( k==0 ){\n          if( !pPrevTrunk ){\n            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);\n          }else{\n            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);\n            if( rc!=SQLITE_OK ){\n              goto end_allocate_page;\n            }\n            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);\n          }\n        }else{\n          /* The trunk page is required by the caller but it contains \n          ** pointers to free-list leaves. The first leaf becomes a trunk\n          ** page in this case.\n          */\n          MemPage *pNewTrunk;\n          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);\n          if( iNewTrunk>mxPage ){ \n            rc = SQLITE_CORRUPT_PGNO(iTrunk);\n            goto end_allocate_page;\n          }\n          testcase( iNewTrunk==mxPage );\n          rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);\n          if( rc!=SQLITE_OK ){\n            goto end_allocate_page;\n          }\n          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);\n          if( rc!=SQLITE_OK ){\n            releasePage(pNewTrunk);\n            goto end_allocate_page;\n          }\n          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);\n          put4byte(&pNewTrunk->aData[4], k-1);\n          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);\n          releasePage(pNewTrunk);\n          if( !pPrevTrunk ){\n            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );\n            put4byte(&pPage1->aData[32], iNewTrunk);\n          }else{\n            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);\n            if( rc ){\n              goto end_allocate_page;\n            }\n            put4byte(&pPrevTrunk->aData[0], iNewTrunk);\n          }\n        }\n        pTrunk = 0;\n        TRACE((\"ALLOCATE: %d trunk - %d free pages left\\n\", *pPgno, n-1));\n#endif\n      }else if( k>0 ){\n        /* Extract a leaf from the trunk */\n        u32 closest;\n        Pgno iPage;\n        unsigned char *aData = pTrunk->aData;\n        if( nearby>0 ){\n          u32 i;\n          closest = 0;\n          if( eMode==BTALLOC_LE ){\n            for(i=0; i<k; i++){\n              iPage = get4byte(&aData[8+i*4]);\n              if( iPage<=nearby ){\n                closest = i;\n                break;\n              }\n            }\n          }else{\n            int dist;\n            dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);\n            for(i=1; i<k; i++){\n              int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);\n              if( d2<dist ){\n                closest = i;\n                dist = d2;\n              }\n            }\n          }\n        }else{\n          closest = 0;\n        }\n\n        iPage = get4byte(&aData[8+closest*4]);\n        testcase( iPage==mxPage );\n        if( iPage>mxPage ){\n          rc = SQLITE_CORRUPT_PGNO(iTrunk);\n          goto end_allocate_page;\n        }\n        testcase( iPage==mxPage );\n        if( !searchList \n         || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE)) \n        ){\n          int noContent;\n          *pPgno = iPage;\n          TRACE((\"ALLOCATE: %d was leaf %d of %d on trunk %d\"\n                 \": %d more free pages\\n\",\n                 *pPgno, closest+1, k, pTrunk->pgno, n-1));\n          rc = sqlite3PagerWrite(pTrunk->pDbPage);\n          if( rc ) goto end_allocate_page;\n          if( closest<k-1 ){\n            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);\n          }\n          put4byte(&aData[4], k-1);\n          noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;\n          rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);\n          if( rc==SQLITE_OK ){\n            rc = sqlite3PagerWrite((*ppPage)->pDbPage);\n            if( rc!=SQLITE_OK ){\n              releasePage(*ppPage);\n              *ppPage = 0;\n            }\n          }\n          searchList = 0;\n        }\n      }\n      releasePage(pPrevTrunk);\n      pPrevTrunk = 0;\n    }while( searchList );\n  }else{\n    /* There are no pages on the freelist, so append a new page to the\n    ** database image.\n    **\n    ** Normally, new pages allocated by this block can be requested from the\n    ** pager layer with the 'no-content' flag set. This prevents the pager\n    ** from trying to read the pages content from disk. However, if the\n    ** current transaction has already run one or more incremental-vacuum\n    ** steps, then the page we are about to allocate may contain content\n    ** that is required in the event of a rollback. In this case, do\n    ** not set the no-content flag. This causes the pager to load and journal\n    ** the current page content before overwriting it.\n    **\n    ** Note that the pager will not actually attempt to load or journal \n    ** content for any page that really does lie past the end of the database\n    ** file on disk. So the effects of disabling the no-content optimization\n    ** here are confined to those pages that lie between the end of the\n    ** database image and the end of the database file.\n    */\n    int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;\n\n    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);\n    if( rc ) return rc;\n    pBt->nPage++;\n    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){\n      /* If *pPgno refers to a pointer-map page, allocate two new pages\n      ** at the end of the file instead of one. The first allocated page\n      ** becomes a new pointer-map page, the second is used by the caller.\n      */\n      MemPage *pPg = 0;\n      TRACE((\"ALLOCATE: %d from end of file (pointer-map page)\\n\", pBt->nPage));\n      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );\n      rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);\n      if( rc==SQLITE_OK ){\n        rc = sqlite3PagerWrite(pPg->pDbPage);\n        releasePage(pPg);\n      }\n      if( rc ) return rc;\n      pBt->nPage++;\n      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }\n    }\n#endif\n    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);\n    *pPgno = pBt->nPage;\n\n    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );\n    rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);\n    if( rc ) return rc;\n    rc = sqlite3PagerWrite((*ppPage)->pDbPage);\n    if( rc!=SQLITE_OK ){\n      releasePage(*ppPage);\n      *ppPage = 0;\n    }\n    TRACE((\"ALLOCATE: %d from end of file\\n\", *pPgno));\n  }\n\n  assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );\n\nend_allocate_page:\n  releasePage(pTrunk);\n  releasePage(pPrevTrunk);\n  assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );\n  assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );\n  return rc;\n}\n\n/*\n** This function is used to add page iPage to the database file free-list. \n** It is assumed that the page is not already a part of the free-list.\n**\n** The value passed as the second argument to this function is optional.\n** If the caller happens to have a pointer to the MemPage object \n** corresponding to page iPage handy, it may pass it as the second value. \n** Otherwise, it may pass NULL.\n**\n** If a pointer to a MemPage object is passed as the second argument,\n** its reference count is not altered by this function.\n*/\nstatic int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){\n  MemPage *pTrunk = 0;                /* Free-list trunk page */\n  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ \n  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */\n  MemPage *pPage;                     /* Page being freed. May be NULL. */\n  int rc;                             /* Return Code */\n  u32 nFree;                          /* Initial number of pages on free-list */\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( CORRUPT_DB || iPage>1 );\n  assert( !pMemPage || pMemPage->pgno==iPage );\n\n  if( iPage<2 || iPage>pBt->nPage ){\n    return SQLITE_CORRUPT_BKPT;\n  }\n  if( pMemPage ){\n    pPage = pMemPage;\n    sqlite3PagerRef(pPage->pDbPage);\n  }else{\n    pPage = btreePageLookup(pBt, iPage);\n  }\n\n  /* Increment the free page count on pPage1 */\n  rc = sqlite3PagerWrite(pPage1->pDbPage);\n  if( rc ) goto freepage_out;\n  nFree = get4byte(&pPage1->aData[36]);\n  put4byte(&pPage1->aData[36], nFree+1);\n\n  if( pBt->btsFlags & BTS_SECURE_DELETE ){\n    /* If the secure_delete option is enabled, then\n    ** always fully overwrite deleted information with zeros.\n    */\n    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )\n     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)\n    ){\n      goto freepage_out;\n    }\n    memset(pPage->aData, 0, pPage->pBt->pageSize);\n  }\n\n  /* If the database supports auto-vacuum, write an entry in the pointer-map\n  ** to indicate that the page is free.\n  */\n  if( ISAUTOVACUUM ){\n    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);\n    if( rc ) goto freepage_out;\n  }\n\n  /* Now manipulate the actual database free-list structure. There are two\n  ** possibilities. If the free-list is currently empty, or if the first\n  ** trunk page in the free-list is full, then this page will become a\n  ** new free-list trunk page. Otherwise, it will become a leaf of the\n  ** first trunk page in the current free-list. This block tests if it\n  ** is possible to add the page as a new free-list leaf.\n  */\n  if( nFree!=0 ){\n    u32 nLeaf;                /* Initial number of leaf cells on trunk page */\n\n    iTrunk = get4byte(&pPage1->aData[32]);\n    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);\n    if( rc!=SQLITE_OK ){\n      goto freepage_out;\n    }\n\n    nLeaf = get4byte(&pTrunk->aData[4]);\n    assert( pBt->usableSize>32 );\n    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){\n      rc = SQLITE_CORRUPT_BKPT;\n      goto freepage_out;\n    }\n    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){\n      /* In this case there is room on the trunk page to insert the page\n      ** being freed as a new leaf.\n      **\n      ** Note that the trunk page is not really full until it contains\n      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have\n      ** coded.  But due to a coding error in versions of SQLite prior to\n      ** 3.6.0, databases with freelist trunk pages holding more than\n      ** usableSize/4 - 8 entries will be reported as corrupt.  In order\n      ** to maintain backwards compatibility with older versions of SQLite,\n      ** we will continue to restrict the number of entries to usableSize/4 - 8\n      ** for now.  At some point in the future (once everyone has upgraded\n      ** to 3.6.0 or later) we should consider fixing the conditional above\n      ** to read \"usableSize/4-2\" instead of \"usableSize/4-8\".\n      **\n      ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still\n      ** avoid using the last six entries in the freelist trunk page array in\n      ** order that database files created by newer versions of SQLite can be\n      ** read by older versions of SQLite.\n      */\n      rc = sqlite3PagerWrite(pTrunk->pDbPage);\n      if( rc==SQLITE_OK ){\n        put4byte(&pTrunk->aData[4], nLeaf+1);\n        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);\n        if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){\n          sqlite3PagerDontWrite(pPage->pDbPage);\n        }\n        rc = btreeSetHasContent(pBt, iPage);\n      }\n      TRACE((\"FREE-PAGE: %d leaf on trunk page %d\\n\",pPage->pgno,pTrunk->pgno));\n      goto freepage_out;\n    }\n  }\n\n  /* If control flows to this point, then it was not possible to add the\n  ** the page being freed as a leaf page of the first trunk in the free-list.\n  ** Possibly because the free-list is empty, or possibly because the \n  ** first trunk in the free-list is full. Either way, the page being freed\n  ** will become the new first trunk page in the free-list.\n  */\n  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){\n    goto freepage_out;\n  }\n  rc = sqlite3PagerWrite(pPage->pDbPage);\n  if( rc!=SQLITE_OK ){\n    goto freepage_out;\n  }\n  put4byte(pPage->aData, iTrunk);\n  put4byte(&pPage->aData[4], 0);\n  put4byte(&pPage1->aData[32], iPage);\n  TRACE((\"FREE-PAGE: %d new trunk page replacing %d\\n\", pPage->pgno, iTrunk));\n\nfreepage_out:\n  if( pPage ){\n    pPage->isInit = 0;\n  }\n  releasePage(pPage);\n  releasePage(pTrunk);\n  return rc;\n}\nstatic void freePage(MemPage *pPage, int *pRC){\n  if( (*pRC)==SQLITE_OK ){\n    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);\n  }\n}\n\n/*\n** Free any overflow pages associated with the given Cell.  Store\n** size information about the cell in pInfo.\n*/\nstatic int clearCell(\n  MemPage *pPage,          /* The page that contains the Cell */\n  unsigned char *pCell,    /* First byte of the Cell */\n  CellInfo *pInfo          /* Size information about the cell */\n){\n  BtShared *pBt;\n  Pgno ovflPgno;\n  int rc;\n  int nOvfl;\n  u32 ovflPageSize;\n\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  pPage->xParseCell(pPage, pCell, pInfo);\n  if( pInfo->nLocal==pInfo->nPayload ){\n    return SQLITE_OK;  /* No overflow pages. Return without doing anything */\n  }\n  testcase( pCell + pInfo->nSize == pPage->aDataEnd );\n  testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );\n  if( pCell + pInfo->nSize > pPage->aDataEnd ){\n    /* Cell extends past end of page */\n    return SQLITE_CORRUPT_PAGE(pPage);\n  }\n  ovflPgno = get4byte(pCell + pInfo->nSize - 4);\n  pBt = pPage->pBt;\n  assert( pBt->usableSize > 4 );\n  ovflPageSize = pBt->usableSize - 4;\n  nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;\n  assert( nOvfl>0 || \n    (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)\n  );\n  while( nOvfl-- ){\n    Pgno iNext = 0;\n    MemPage *pOvfl = 0;\n    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){\n      /* 0 is not a legal page number and page 1 cannot be an \n      ** overflow page. Therefore if ovflPgno<2 or past the end of the \n      ** file the database must be corrupt. */\n      return SQLITE_CORRUPT_BKPT;\n    }\n    if( nOvfl ){\n      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);\n      if( rc ) return rc;\n    }\n\n    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )\n     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1\n    ){\n      /* There is no reason any cursor should have an outstanding reference \n      ** to an overflow page belonging to a cell that is being deleted/updated.\n      ** So if there exists more than one reference to this page, then it \n      ** must not really be an overflow page and the database must be corrupt. \n      ** It is helpful to detect this before calling freePage2(), as \n      ** freePage2() may zero the page contents if secure-delete mode is\n      ** enabled. If this 'overflow' page happens to be a page that the\n      ** caller is iterating through or using in some other way, this\n      ** can be problematic.\n      */\n      rc = SQLITE_CORRUPT_BKPT;\n    }else{\n      rc = freePage2(pBt, pOvfl, ovflPgno);\n    }\n\n    if( pOvfl ){\n      sqlite3PagerUnref(pOvfl->pDbPage);\n    }\n    if( rc ) return rc;\n    ovflPgno = iNext;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Create the byte sequence used to represent a cell on page pPage\n** and write that byte sequence into pCell[].  Overflow pages are\n** allocated and filled in as necessary.  The calling procedure\n** is responsible for making sure sufficient space has been allocated\n** for pCell[].\n**\n** Note that pCell does not necessary need to point to the pPage->aData\n** area.  pCell might point to some temporary storage.  The cell will\n** be constructed in this temporary area then copied into pPage->aData\n** later.\n*/\nstatic int fillInCell(\n  MemPage *pPage,                /* The page that contains the cell */\n  unsigned char *pCell,          /* Complete text of the cell */\n  const BtreePayload *pX,        /* Payload with which to construct the cell */\n  int *pnSize                    /* Write cell size here */\n){\n  int nPayload;\n  const u8 *pSrc;\n  int nSrc, n, rc, mn;\n  int spaceLeft;\n  MemPage *pToRelease;\n  unsigned char *pPrior;\n  unsigned char *pPayload;\n  BtShared *pBt;\n  Pgno pgnoOvfl;\n  int nHeader;\n\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n\n  /* pPage is not necessarily writeable since pCell might be auxiliary\n  ** buffer space that is separate from the pPage buffer area */\n  assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]\n            || sqlite3PagerIswriteable(pPage->pDbPage) );\n\n  /* Fill in the header. */\n  nHeader = pPage->childPtrSize;\n  if( pPage->intKey ){\n    nPayload = pX->nData + pX->nZero;\n    pSrc = pX->pData;\n    nSrc = pX->nData;\n    assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */\n    nHeader += putVarint32(&pCell[nHeader], nPayload);\n    nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);\n  }else{\n    assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );\n    nSrc = nPayload = (int)pX->nKey;\n    pSrc = pX->pKey;\n    nHeader += putVarint32(&pCell[nHeader], nPayload);\n  }\n  \n  /* Fill in the payload */\n  pPayload = &pCell[nHeader];\n  if( nPayload<=pPage->maxLocal ){\n    /* This is the common case where everything fits on the btree page\n    ** and no overflow pages are required. */\n    n = nHeader + nPayload;\n    testcase( n==3 );\n    testcase( n==4 );\n    if( n<4 ) n = 4;\n    *pnSize = n;\n    assert( nSrc<=nPayload );\n    testcase( nSrc<nPayload );\n    memcpy(pPayload, pSrc, nSrc);\n    memset(pPayload+nSrc, 0, nPayload-nSrc);\n    return SQLITE_OK;\n  }\n\n  /* If we reach this point, it means that some of the content will need\n  ** to spill onto overflow pages.\n  */\n  mn = pPage->minLocal;\n  n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);\n  testcase( n==pPage->maxLocal );\n  testcase( n==pPage->maxLocal+1 );\n  if( n > pPage->maxLocal ) n = mn;\n  spaceLeft = n;\n  *pnSize = n + nHeader + 4;\n  pPrior = &pCell[nHeader+n];\n  pToRelease = 0;\n  pgnoOvfl = 0;\n  pBt = pPage->pBt;\n\n  /* At this point variables should be set as follows:\n  **\n  **   nPayload           Total payload size in bytes\n  **   pPayload           Begin writing payload here\n  **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,\n  **                      that means content must spill into overflow pages.\n  **   *pnSize            Size of the local cell (not counting overflow pages)\n  **   pPrior             Where to write the pgno of the first overflow page\n  **\n  ** Use a call to btreeParseCellPtr() to verify that the values above\n  ** were computed correctly.\n  */\n#ifdef SQLITE_DEBUG\n  {\n    CellInfo info;\n    pPage->xParseCell(pPage, pCell, &info);\n    assert( nHeader==(int)(info.pPayload - pCell) );\n    assert( info.nKey==pX->nKey );\n    assert( *pnSize == info.nSize );\n    assert( spaceLeft == info.nLocal );\n  }\n#endif\n\n  /* Write the payload into the local Cell and any extra into overflow pages */\n  while( 1 ){\n    n = nPayload;\n    if( n>spaceLeft ) n = spaceLeft;\n\n    /* If pToRelease is not zero than pPayload points into the data area\n    ** of pToRelease.  Make sure pToRelease is still writeable. */\n    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );\n\n    /* If pPayload is part of the data area of pPage, then make sure pPage\n    ** is still writeable */\n    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]\n            || sqlite3PagerIswriteable(pPage->pDbPage) );\n\n    if( nSrc>=n ){\n      memcpy(pPayload, pSrc, n);\n    }else if( nSrc>0 ){\n      n = nSrc;\n      memcpy(pPayload, pSrc, n);\n    }else{\n      memset(pPayload, 0, n);\n    }\n    nPayload -= n;\n    if( nPayload<=0 ) break;\n    pPayload += n;\n    pSrc += n;\n    nSrc -= n;\n    spaceLeft -= n;\n    if( spaceLeft==0 ){\n      MemPage *pOvfl = 0;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */\n      if( pBt->autoVacuum ){\n        do{\n          pgnoOvfl++;\n        } while( \n          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) \n        );\n      }\n#endif\n      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n      /* If the database supports auto-vacuum, and the second or subsequent\n      ** overflow page is being allocated, add an entry to the pointer-map\n      ** for that page now. \n      **\n      ** If this is the first overflow page, then write a partial entry \n      ** to the pointer-map. If we write nothing to this pointer-map slot,\n      ** then the optimistic overflow chain processing in clearCell()\n      ** may misinterpret the uninitialized values and delete the\n      ** wrong pages from the database.\n      */\n      if( pBt->autoVacuum && rc==SQLITE_OK ){\n        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);\n        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);\n        if( rc ){\n          releasePage(pOvfl);\n        }\n      }\n#endif\n      if( rc ){\n        releasePage(pToRelease);\n        return rc;\n      }\n\n      /* If pToRelease is not zero than pPrior points into the data area\n      ** of pToRelease.  Make sure pToRelease is still writeable. */\n      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );\n\n      /* If pPrior is part of the data area of pPage, then make sure pPage\n      ** is still writeable */\n      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]\n            || sqlite3PagerIswriteable(pPage->pDbPage) );\n\n      put4byte(pPrior, pgnoOvfl);\n      releasePage(pToRelease);\n      pToRelease = pOvfl;\n      pPrior = pOvfl->aData;\n      put4byte(pPrior, 0);\n      pPayload = &pOvfl->aData[4];\n      spaceLeft = pBt->usableSize - 4;\n    }\n  }\n  releasePage(pToRelease);\n  return SQLITE_OK;\n}\n\n/*\n** Remove the i-th cell from pPage.  This routine effects pPage only.\n** The cell content is not freed or deallocated.  It is assumed that\n** the cell content has been copied someplace else.  This routine just\n** removes the reference to the cell from pPage.\n**\n** \"sz\" must be the number of bytes in the cell.\n*/\nstatic void dropCell(MemPage *pPage, int idx, int sz, int *pRC){\n  u32 pc;         /* Offset to cell content of cell being deleted */\n  u8 *data;       /* pPage->aData */\n  u8 *ptr;        /* Used to move bytes around within data[] */\n  int rc;         /* The return code */\n  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */\n\n  if( *pRC ) return;\n  assert( idx>=0 && idx<pPage->nCell );\n  assert( CORRUPT_DB || sz==cellSize(pPage, idx) );\n  assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( pPage->nFree>=0 );\n  data = pPage->aData;\n  ptr = &pPage->aCellIdx[2*idx];\n  pc = get2byte(ptr);\n  hdr = pPage->hdrOffset;\n  testcase( pc==get2byte(&data[hdr+5]) );\n  testcase( pc+sz==pPage->pBt->usableSize );\n  if( pc+sz > pPage->pBt->usableSize ){\n    *pRC = SQLITE_CORRUPT_BKPT;\n    return;\n  }\n  rc = freeSpace(pPage, pc, sz);\n  if( rc ){\n    *pRC = rc;\n    return;\n  }\n  pPage->nCell--;\n  if( pPage->nCell==0 ){\n    memset(&data[hdr+1], 0, 4);\n    data[hdr+7] = 0;\n    put2byte(&data[hdr+5], pPage->pBt->usableSize);\n    pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset\n                       - pPage->childPtrSize - 8;\n  }else{\n    memmove(ptr, ptr+2, 2*(pPage->nCell - idx));\n    put2byte(&data[hdr+3], pPage->nCell);\n    pPage->nFree += 2;\n  }\n}\n\n/*\n** Insert a new cell on pPage at cell index \"i\".  pCell points to the\n** content of the cell.\n**\n** If the cell content will fit on the page, then put it there.  If it\n** will not fit, then make a copy of the cell content into pTemp if\n** pTemp is not null.  Regardless of pTemp, allocate a new entry\n** in pPage->apOvfl[] and make it point to the cell content (either\n** in pTemp or the original pCell) and also record its index. \n** Allocating a new entry in pPage->aCell[] implies that \n** pPage->nOverflow is incremented.\n**\n** *pRC must be SQLITE_OK when this routine is called.\n*/\nstatic void insertCell(\n  MemPage *pPage,   /* Page into which we are copying */\n  int i,            /* New cell becomes the i-th cell of the page */\n  u8 *pCell,        /* Content of the new cell */\n  int sz,           /* Bytes of content in pCell */\n  u8 *pTemp,        /* Temp storage space for pCell, if needed */\n  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */\n  int *pRC          /* Read and write return code from here */\n){\n  int idx = 0;      /* Where to write new cell content in data[] */\n  int j;            /* Loop counter */\n  u8 *data;         /* The content of the whole page */\n  u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */\n\n  assert( *pRC==SQLITE_OK );\n  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );\n  assert( MX_CELL(pPage->pBt)<=10921 );\n  assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );\n  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );\n  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );\n  assert( pPage->nFree>=0 );\n  if( pPage->nOverflow || sz+2>pPage->nFree ){\n    if( pTemp ){\n      memcpy(pTemp, pCell, sz);\n      pCell = pTemp;\n    }\n    if( iChild ){\n      put4byte(pCell, iChild);\n    }\n    j = pPage->nOverflow++;\n    /* Comparison against ArraySize-1 since we hold back one extra slot\n    ** as a contingency.  In other words, never need more than 3 overflow\n    ** slots but 4 are allocated, just to be safe. */\n    assert( j < ArraySize(pPage->apOvfl)-1 );\n    pPage->apOvfl[j] = pCell;\n    pPage->aiOvfl[j] = (u16)i;\n\n    /* When multiple overflows occur, they are always sequential and in\n    ** sorted order.  This invariants arise because multiple overflows can\n    ** only occur when inserting divider cells into the parent page during\n    ** balancing, and the dividers are adjacent and sorted.\n    */\n    assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */\n    assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */\n  }else{\n    int rc = sqlite3PagerWrite(pPage->pDbPage);\n    if( rc!=SQLITE_OK ){\n      *pRC = rc;\n      return;\n    }\n    assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n    data = pPage->aData;\n    assert( &data[pPage->cellOffset]==pPage->aCellIdx );\n    rc = allocateSpace(pPage, sz, &idx);\n    if( rc ){ *pRC = rc; return; }\n    /* The allocateSpace() routine guarantees the following properties\n    ** if it returns successfully */\n    assert( idx >= 0 );\n    assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );\n    assert( idx+sz <= (int)pPage->pBt->usableSize );\n    pPage->nFree -= (u16)(2 + sz);\n    if( iChild ){\n      /* In a corrupt database where an entry in the cell index section of\n      ** a btree page has a value of 3 or less, the pCell value might point\n      ** as many as 4 bytes in front of the start of the aData buffer for\n      ** the source page.  Make sure this does not cause problems by not\n      ** reading the first 4 bytes */\n      memcpy(&data[idx+4], pCell+4, sz-4);\n      put4byte(&data[idx], iChild);\n    }else{\n      memcpy(&data[idx], pCell, sz);\n    }\n    pIns = pPage->aCellIdx + i*2;\n    memmove(pIns+2, pIns, 2*(pPage->nCell - i));\n    put2byte(pIns, idx);\n    pPage->nCell++;\n    /* increment the cell count */\n    if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;\n    assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( pPage->pBt->autoVacuum ){\n      /* The cell may contain a pointer to an overflow page. If so, write\n      ** the entry for the overflow page into the pointer map.\n      */\n      ptrmapPutOvflPtr(pPage, pPage, pCell, pRC);\n    }\n#endif\n  }\n}\n\n/*\n** The following parameters determine how many adjacent pages get involved\n** in a balancing operation.  NN is the number of neighbors on either side\n** of the page that participate in the balancing operation.  NB is the\n** total number of pages that participate, including the target page and\n** NN neighbors on either side.\n**\n** The minimum value of NN is 1 (of course).  Increasing NN above 1\n** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance\n** in exchange for a larger degradation in INSERT and UPDATE performance.\n** The value of NN appears to give the best results overall.\n**\n** (Later:) The description above makes it seem as if these values are\n** tunable - as if you could change them and recompile and it would all work.\n** But that is unlikely.  NB has been 3 since the inception of SQLite and\n** we have never tested any other value.\n*/\n#define NN 1             /* Number of neighbors on either side of pPage */\n#define NB 3             /* (NN*2+1): Total pages involved in the balance */\n\n/*\n** A CellArray object contains a cache of pointers and sizes for a\n** consecutive sequence of cells that might be held on multiple pages.\n**\n** The cells in this array are the divider cell or cells from the pParent\n** page plus up to three child pages.  There are a total of nCell cells.\n**\n** pRef is a pointer to one of the pages that contributes cells.  This is\n** used to access information such as MemPage.intKey and MemPage.pBt->pageSize\n** which should be common to all pages that contribute cells to this array.\n**\n** apCell[] and szCell[] hold, respectively, pointers to the start of each\n** cell and the size of each cell.  Some of the apCell[] pointers might refer\n** to overflow cells.  In other words, some apCel[] pointers might not point\n** to content area of the pages.\n**\n** A szCell[] of zero means the size of that cell has not yet been computed.\n**\n** The cells come from as many as four different pages:\n**\n**             -----------\n**             | Parent  |\n**             -----------\n**            /     |     \\\n**           /      |      \\\n**  ---------   ---------   ---------\n**  |Child-1|   |Child-2|   |Child-3|\n**  ---------   ---------   ---------\n**\n** The order of cells is in the array is for an index btree is:\n**\n**       1.  All cells from Child-1 in order\n**       2.  The first divider cell from Parent\n**       3.  All cells from Child-2 in order\n**       4.  The second divider cell from Parent\n**       5.  All cells from Child-3 in order\n**\n** For a table-btree (with rowids) the items 2 and 4 are empty because\n** content exists only in leaves and there are no divider cells.\n**\n** For an index btree, the apEnd[] array holds pointer to the end of page\n** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,\n** respectively. The ixNx[] array holds the number of cells contained in\n** each of these 5 stages, and all stages to the left.  Hence:\n**\n**    ixNx[0] = Number of cells in Child-1.\n**    ixNx[1] = Number of cells in Child-1 plus 1 for first divider.\n**    ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.\n**    ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells\n**    ixNx[4] = Total number of cells.\n**\n** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]\n** are used and they point to the leaf pages only, and the ixNx value are:\n**\n**    ixNx[0] = Number of cells in Child-1.\n**    ixNx[1] = Number of cells in Child-1 and Child-2.\n**    ixNx[2] = Total number of cells.\n**\n** Sometimes when deleting, a child page can have zero cells.  In those\n** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]\n** entries, shift down.  The end result is that each ixNx[] entry should\n** be larger than the previous\n*/\ntypedef struct CellArray CellArray;\nstruct CellArray {\n  int nCell;              /* Number of cells in apCell[] */\n  MemPage *pRef;          /* Reference page */\n  u8 **apCell;            /* All cells begin balanced */\n  u16 *szCell;            /* Local size of all cells in apCell[] */\n  u8 *apEnd[NB*2];        /* MemPage.aDataEnd values */\n  int ixNx[NB*2];         /* Index of at which we move to the next apEnd[] */\n};\n\n/*\n** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been\n** computed.\n*/\nstatic void populateCellCache(CellArray *p, int idx, int N){\n  assert( idx>=0 && idx+N<=p->nCell );\n  while( N>0 ){\n    assert( p->apCell[idx]!=0 );\n    if( p->szCell[idx]==0 ){\n      p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);\n    }else{\n      assert( CORRUPT_DB ||\n              p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );\n    }\n    idx++;\n    N--;\n  }\n}\n\n/*\n** Return the size of the Nth element of the cell array\n*/\nstatic SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){\n  assert( N>=0 && N<p->nCell );\n  assert( p->szCell[N]==0 );\n  p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);\n  return p->szCell[N];\n}\nstatic u16 cachedCellSize(CellArray *p, int N){\n  assert( N>=0 && N<p->nCell );\n  if( p->szCell[N] ) return p->szCell[N];\n  return computeCellSize(p, N);\n}\n\n/*\n** Array apCell[] contains pointers to nCell b-tree page cells. The \n** szCell[] array contains the size in bytes of each cell. This function\n** replaces the current contents of page pPg with the contents of the cell\n** array.\n**\n** Some of the cells in apCell[] may currently be stored in pPg. This\n** function works around problems caused by this by making a copy of any \n** such cells before overwriting the page data.\n**\n** The MemPage.nFree field is invalidated by this function. It is the \n** responsibility of the caller to set it correctly.\n*/\nstatic int rebuildPage(\n  CellArray *pCArray,             /* Content to be added to page pPg */\n  int iFirst,                     /* First cell in pCArray to use */\n  int nCell,                      /* Final number of cells on page */\n  MemPage *pPg                    /* The page to be reconstructed */\n){\n  const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */\n  u8 * const aData = pPg->aData;           /* Pointer to data for pPg */\n  const int usableSize = pPg->pBt->usableSize;\n  u8 * const pEnd = &aData[usableSize];\n  int i = iFirst;                 /* Which cell to copy from pCArray*/\n  u32 j;                          /* Start of cell content area */\n  int iEnd = i+nCell;             /* Loop terminator */\n  u8 *pCellptr = pPg->aCellIdx;\n  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);\n  u8 *pData;\n  int k;                          /* Current slot in pCArray->apEnd[] */\n  u8 *pSrcEnd;                    /* Current pCArray->apEnd[k] value */\n\n  assert( i<iEnd );\n  j = get2byte(&aData[hdr+5]);\n  if( NEVER(j>(u32)usableSize) ){ j = 0; }\n  memcpy(&pTmp[j], &aData[j], usableSize - j);\n\n  for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}\n  pSrcEnd = pCArray->apEnd[k];\n\n  pData = pEnd;\n  while( 1/*exit by break*/ ){\n    u8 *pCell = pCArray->apCell[i];\n    u16 sz = pCArray->szCell[i];\n    assert( sz>0 );\n    if( SQLITE_WITHIN(pCell,aData,pEnd) ){\n      if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;\n      pCell = &pTmp[pCell - aData];\n    }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd\n           && (uptr)(pCell)<(uptr)pSrcEnd\n    ){\n      return SQLITE_CORRUPT_BKPT;\n    }\n\n    pData -= sz;\n    put2byte(pCellptr, (pData - aData));\n    pCellptr += 2;\n    if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;\n    memcpy(pData, pCell, sz);\n    assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );\n    testcase( sz!=pPg->xCellSize(pPg,pCell) )\n    i++;\n    if( i>=iEnd ) break;\n    if( pCArray->ixNx[k]<=i ){\n      k++;\n      pSrcEnd = pCArray->apEnd[k];\n    }\n  }\n\n  /* The pPg->nFree field is now set incorrectly. The caller will fix it. */\n  pPg->nCell = nCell;\n  pPg->nOverflow = 0;\n\n  put2byte(&aData[hdr+1], 0);\n  put2byte(&aData[hdr+3], pPg->nCell);\n  put2byte(&aData[hdr+5], pData - aData);\n  aData[hdr+7] = 0x00;\n  return SQLITE_OK;\n}\n\n/*\n** The pCArray objects contains pointers to b-tree cells and the cell sizes.\n** This function attempts to add the cells stored in the array to page pPg.\n** If it cannot (because the page needs to be defragmented before the cells\n** will fit), non-zero is returned. Otherwise, if the cells are added\n** successfully, zero is returned.\n**\n** Argument pCellptr points to the first entry in the cell-pointer array\n** (part of page pPg) to populate. After cell apCell[0] is written to the\n** page body, a 16-bit offset is written to pCellptr. And so on, for each\n** cell in the array. It is the responsibility of the caller to ensure\n** that it is safe to overwrite this part of the cell-pointer array.\n**\n** When this function is called, *ppData points to the start of the \n** content area on page pPg. If the size of the content area is extended,\n** *ppData is updated to point to the new start of the content area\n** before returning.\n**\n** Finally, argument pBegin points to the byte immediately following the\n** end of the space required by this page for the cell-pointer area (for\n** all cells - not just those inserted by the current call). If the content\n** area must be extended to before this point in order to accomodate all\n** cells in apCell[], then the cells do not fit and non-zero is returned.\n*/\nstatic int pageInsertArray(\n  MemPage *pPg,                   /* Page to add cells to */\n  u8 *pBegin,                     /* End of cell-pointer array */\n  u8 **ppData,                    /* IN/OUT: Page content-area pointer */\n  u8 *pCellptr,                   /* Pointer to cell-pointer area */\n  int iFirst,                     /* Index of first cell to add */\n  int nCell,                      /* Number of cells to add to pPg */\n  CellArray *pCArray              /* Array of cells */\n){\n  int i = iFirst;                 /* Loop counter - cell index to insert */\n  u8 *aData = pPg->aData;         /* Complete page */\n  u8 *pData = *ppData;            /* Content area.  A subset of aData[] */\n  int iEnd = iFirst + nCell;      /* End of loop. One past last cell to ins */\n  int k;                          /* Current slot in pCArray->apEnd[] */\n  u8 *pEnd;                       /* Maximum extent of cell data */\n  assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */\n  if( iEnd<=iFirst ) return 0;\n  for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}\n  pEnd = pCArray->apEnd[k];\n  while( 1 /*Exit by break*/ ){\n    int sz, rc;\n    u8 *pSlot;\n    assert( pCArray->szCell[i]!=0 );\n    sz = pCArray->szCell[i];\n    if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){\n      if( (pData - pBegin)<sz ) return 1;\n      pData -= sz;\n      pSlot = pData;\n    }\n    /* pSlot and pCArray->apCell[i] will never overlap on a well-formed\n    ** database.  But they might for a corrupt database.  Hence use memmove()\n    ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */\n    assert( (pSlot+sz)<=pCArray->apCell[i]\n         || pSlot>=(pCArray->apCell[i]+sz)\n         || CORRUPT_DB );\n    if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd\n     && (uptr)(pCArray->apCell[i])<(uptr)pEnd\n    ){\n      assert( CORRUPT_DB );\n      (void)SQLITE_CORRUPT_BKPT;\n      return 1;\n    }\n    memmove(pSlot, pCArray->apCell[i], sz);\n    put2byte(pCellptr, (pSlot - aData));\n    pCellptr += 2;\n    i++;\n    if( i>=iEnd ) break;\n    if( pCArray->ixNx[k]<=i ){\n      k++;\n      pEnd = pCArray->apEnd[k];\n    }\n  }\n  *ppData = pData;\n  return 0;\n}\n\n/*\n** The pCArray object contains pointers to b-tree cells and their sizes.\n**\n** This function adds the space associated with each cell in the array\n** that is currently stored within the body of pPg to the pPg free-list.\n** The cell-pointers and other fields of the page are not updated.\n**\n** This function returns the total number of cells added to the free-list.\n*/\nstatic int pageFreeArray(\n  MemPage *pPg,                   /* Page to edit */\n  int iFirst,                     /* First cell to delete */\n  int nCell,                      /* Cells to delete */\n  CellArray *pCArray              /* Array of cells */\n){\n  u8 * const aData = pPg->aData;\n  u8 * const pEnd = &aData[pPg->pBt->usableSize];\n  u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];\n  int nRet = 0;\n  int i;\n  int iEnd = iFirst + nCell;\n  u8 *pFree = 0;\n  int szFree = 0;\n\n  for(i=iFirst; i<iEnd; i++){\n    u8 *pCell = pCArray->apCell[i];\n    if( SQLITE_WITHIN(pCell, pStart, pEnd) ){\n      int sz;\n      /* No need to use cachedCellSize() here.  The sizes of all cells that\n      ** are to be freed have already been computing while deciding which\n      ** cells need freeing */\n      sz = pCArray->szCell[i];  assert( sz>0 );\n      if( pFree!=(pCell + sz) ){\n        if( pFree ){\n          assert( pFree>aData && (pFree - aData)<65536 );\n          freeSpace(pPg, (u16)(pFree - aData), szFree);\n        }\n        pFree = pCell;\n        szFree = sz;\n        if( pFree+sz>pEnd ) return 0;\n      }else{\n        pFree = pCell;\n        szFree += sz;\n      }\n      nRet++;\n    }\n  }\n  if( pFree ){\n    assert( pFree>aData && (pFree - aData)<65536 );\n    freeSpace(pPg, (u16)(pFree - aData), szFree);\n  }\n  return nRet;\n}\n\n/*\n** pCArray contains pointers to and sizes of all cells in the page being\n** balanced.  The current page, pPg, has pPg->nCell cells starting with\n** pCArray->apCell[iOld].  After balancing, this page should hold nNew cells\n** starting at apCell[iNew].\n**\n** This routine makes the necessary adjustments to pPg so that it contains\n** the correct cells after being balanced.\n**\n** The pPg->nFree field is invalid when this function returns. It is the\n** responsibility of the caller to set it correctly.\n*/\nstatic int editPage(\n  MemPage *pPg,                   /* Edit this page */\n  int iOld,                       /* Index of first cell currently on page */\n  int iNew,                       /* Index of new first cell on page */\n  int nNew,                       /* Final number of cells on page */\n  CellArray *pCArray              /* Array of cells and sizes */\n){\n  u8 * const aData = pPg->aData;\n  const int hdr = pPg->hdrOffset;\n  u8 *pBegin = &pPg->aCellIdx[nNew * 2];\n  int nCell = pPg->nCell;       /* Cells stored on pPg */\n  u8 *pData;\n  u8 *pCellptr;\n  int i;\n  int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;\n  int iNewEnd = iNew + nNew;\n\n#ifdef SQLITE_DEBUG\n  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);\n  memcpy(pTmp, aData, pPg->pBt->usableSize);\n#endif\n\n  /* Remove cells from the start and end of the page */\n  assert( nCell>=0 );\n  if( iOld<iNew ){\n    int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);\n    if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;\n    memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);\n    nCell -= nShift;\n  }\n  if( iNewEnd < iOldEnd ){\n    int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);\n    assert( nCell>=nTail );\n    nCell -= nTail;\n  }\n\n  pData = &aData[get2byteNotZero(&aData[hdr+5])];\n  if( pData<pBegin ) goto editpage_fail;\n\n  /* Add cells to the start of the page */\n  if( iNew<iOld ){\n    int nAdd = MIN(nNew,iOld-iNew);\n    assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );\n    assert( nAdd>=0 );\n    pCellptr = pPg->aCellIdx;\n    memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);\n    if( pageInsertArray(\n          pPg, pBegin, &pData, pCellptr,\n          iNew, nAdd, pCArray\n    ) ) goto editpage_fail;\n    nCell += nAdd;\n  }\n\n  /* Add any overflow cells */\n  for(i=0; i<pPg->nOverflow; i++){\n    int iCell = (iOld + pPg->aiOvfl[i]) - iNew;\n    if( iCell>=0 && iCell<nNew ){\n      pCellptr = &pPg->aCellIdx[iCell * 2];\n      if( nCell>iCell ){\n        memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);\n      }\n      nCell++;\n      cachedCellSize(pCArray, iCell+iNew);\n      if( pageInsertArray(\n            pPg, pBegin, &pData, pCellptr,\n            iCell+iNew, 1, pCArray\n      ) ) goto editpage_fail;\n    }\n  }\n\n  /* Append cells to the end of the page */\n  assert( nCell>=0 );\n  pCellptr = &pPg->aCellIdx[nCell*2];\n  if( pageInsertArray(\n        pPg, pBegin, &pData, pCellptr,\n        iNew+nCell, nNew-nCell, pCArray\n  ) ) goto editpage_fail;\n\n  pPg->nCell = nNew;\n  pPg->nOverflow = 0;\n\n  put2byte(&aData[hdr+3], pPg->nCell);\n  put2byte(&aData[hdr+5], pData - aData);\n\n#ifdef SQLITE_DEBUG\n  for(i=0; i<nNew && !CORRUPT_DB; i++){\n    u8 *pCell = pCArray->apCell[i+iNew];\n    int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);\n    if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){\n      pCell = &pTmp[pCell - aData];\n    }\n    assert( 0==memcmp(pCell, &aData[iOff],\n            pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );\n  }\n#endif\n\n  return SQLITE_OK;\n editpage_fail:\n  /* Unable to edit this page. Rebuild it from scratch instead. */\n  populateCellCache(pCArray, iNew, nNew);\n  return rebuildPage(pCArray, iNew, nNew, pPg);\n}\n\n\n#ifndef SQLITE_OMIT_QUICKBALANCE\n/*\n** This version of balance() handles the common special case where\n** a new entry is being inserted on the extreme right-end of the\n** tree, in other words, when the new entry will become the largest\n** entry in the tree.\n**\n** Instead of trying to balance the 3 right-most leaf pages, just add\n** a new page to the right-hand side and put the one new entry in\n** that page.  This leaves the right side of the tree somewhat\n** unbalanced.  But odds are that we will be inserting new entries\n** at the end soon afterwards so the nearly empty page will quickly\n** fill up.  On average.\n**\n** pPage is the leaf page which is the right-most page in the tree.\n** pParent is its parent.  pPage must have a single overflow entry\n** which is also the right-most entry on the page.\n**\n** The pSpace buffer is used to store a temporary copy of the divider\n** cell that will be inserted into pParent. Such a cell consists of a 4\n** byte page number followed by a variable length integer. In other\n** words, at most 13 bytes. Hence the pSpace buffer must be at\n** least 13 bytes in size.\n*/\nstatic int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){\n  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */\n  MemPage *pNew;                       /* Newly allocated page */\n  int rc;                              /* Return Code */\n  Pgno pgnoNew;                        /* Page number of pNew */\n\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( sqlite3PagerIswriteable(pParent->pDbPage) );\n  assert( pPage->nOverflow==1 );\n  \n  if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;  /* dbfuzz001.test */\n  assert( pPage->nFree>=0 );\n  assert( pParent->nFree>=0 );\n\n  /* Allocate a new page. This page will become the right-sibling of \n  ** pPage. Make the parent page writable, so that the new divider cell\n  ** may be inserted. If both these operations are successful, proceed.\n  */\n  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);\n\n  if( rc==SQLITE_OK ){\n\n    u8 *pOut = &pSpace[4];\n    u8 *pCell = pPage->apOvfl[0];\n    u16 szCell = pPage->xCellSize(pPage, pCell);\n    u8 *pStop;\n    CellArray b;\n\n    assert( sqlite3PagerIswriteable(pNew->pDbPage) );\n    assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );\n    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);\n    b.nCell = 1;\n    b.pRef = pPage;\n    b.apCell = &pCell;\n    b.szCell = &szCell;\n    b.apEnd[0] = pPage->aDataEnd;\n    b.ixNx[0] = 2;\n    rc = rebuildPage(&b, 0, 1, pNew);\n    if( NEVER(rc) ){\n      releasePage(pNew);\n      return rc;\n    }\n    pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;\n\n    /* If this is an auto-vacuum database, update the pointer map\n    ** with entries for the new page, and any pointer from the \n    ** cell on the page to an overflow page. If either of these\n    ** operations fails, the return code is set, but the contents\n    ** of the parent page are still manipulated by thh code below.\n    ** That is Ok, at this point the parent page is guaranteed to\n    ** be marked as dirty. Returning an error code will cause a\n    ** rollback, undoing any changes made to the parent page.\n    */\n    if( ISAUTOVACUUM ){\n      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);\n      if( szCell>pNew->minLocal ){\n        ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);\n      }\n    }\n  \n    /* Create a divider cell to insert into pParent. The divider cell\n    ** consists of a 4-byte page number (the page number of pPage) and\n    ** a variable length key value (which must be the same value as the\n    ** largest key on pPage).\n    **\n    ** To find the largest key value on pPage, first find the right-most \n    ** cell on pPage. The first two fields of this cell are the \n    ** record-length (a variable length integer at most 32-bits in size)\n    ** and the key value (a variable length integer, may have any value).\n    ** The first of the while(...) loops below skips over the record-length\n    ** field. The second while(...) loop copies the key value from the\n    ** cell on pPage into the pSpace buffer.\n    */\n    pCell = findCell(pPage, pPage->nCell-1);\n    pStop = &pCell[9];\n    while( (*(pCell++)&0x80) && pCell<pStop );\n    pStop = &pCell[9];\n    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );\n\n    /* Insert the new divider cell into pParent. */\n    if( rc==SQLITE_OK ){\n      insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),\n                   0, pPage->pgno, &rc);\n    }\n\n    /* Set the right-child pointer of pParent to point to the new page. */\n    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);\n  \n    /* Release the reference to the new page. */\n    releasePage(pNew);\n  }\n\n  return rc;\n}\n#endif /* SQLITE_OMIT_QUICKBALANCE */\n\n#if 0\n/*\n** This function does not contribute anything to the operation of SQLite.\n** it is sometimes activated temporarily while debugging code responsible \n** for setting pointer-map entries.\n*/\nstatic int ptrmapCheckPages(MemPage **apPage, int nPage){\n  int i, j;\n  for(i=0; i<nPage; i++){\n    Pgno n;\n    u8 e;\n    MemPage *pPage = apPage[i];\n    BtShared *pBt = pPage->pBt;\n    assert( pPage->isInit );\n\n    for(j=0; j<pPage->nCell; j++){\n      CellInfo info;\n      u8 *z;\n     \n      z = findCell(pPage, j);\n      pPage->xParseCell(pPage, z, &info);\n      if( info.nLocal<info.nPayload ){\n        Pgno ovfl = get4byte(&z[info.nSize-4]);\n        ptrmapGet(pBt, ovfl, &e, &n);\n        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );\n      }\n      if( !pPage->leaf ){\n        Pgno child = get4byte(z);\n        ptrmapGet(pBt, child, &e, &n);\n        assert( n==pPage->pgno && e==PTRMAP_BTREE );\n      }\n    }\n    if( !pPage->leaf ){\n      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);\n      ptrmapGet(pBt, child, &e, &n);\n      assert( n==pPage->pgno && e==PTRMAP_BTREE );\n    }\n  }\n  return 1;\n}\n#endif\n\n/*\n** This function is used to copy the contents of the b-tree node stored \n** on page pFrom to page pTo. If page pFrom was not a leaf page, then\n** the pointer-map entries for each child page are updated so that the\n** parent page stored in the pointer map is page pTo. If pFrom contained\n** any cells with overflow page pointers, then the corresponding pointer\n** map entries are also updated so that the parent page is page pTo.\n**\n** If pFrom is currently carrying any overflow cells (entries in the\n** MemPage.apOvfl[] array), they are not copied to pTo. \n**\n** Before returning, page pTo is reinitialized using btreeInitPage().\n**\n** The performance of this function is not critical. It is only used by \n** the balance_shallower() and balance_deeper() procedures, neither of\n** which are called often under normal circumstances.\n*/\nstatic void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){\n  if( (*pRC)==SQLITE_OK ){\n    BtShared * const pBt = pFrom->pBt;\n    u8 * const aFrom = pFrom->aData;\n    u8 * const aTo = pTo->aData;\n    int const iFromHdr = pFrom->hdrOffset;\n    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);\n    int rc;\n    int iData;\n  \n  \n    assert( pFrom->isInit );\n    assert( pFrom->nFree>=iToHdr );\n    assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );\n  \n    /* Copy the b-tree node content from page pFrom to page pTo. */\n    iData = get2byte(&aFrom[iFromHdr+5]);\n    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);\n    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);\n  \n    /* Reinitialize page pTo so that the contents of the MemPage structure\n    ** match the new data. The initialization of pTo can actually fail under\n    ** fairly obscure circumstances, even though it is a copy of initialized \n    ** page pFrom.\n    */\n    pTo->isInit = 0;\n    rc = btreeInitPage(pTo);\n    if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);\n    if( rc!=SQLITE_OK ){\n      *pRC = rc;\n      return;\n    }\n  \n    /* If this is an auto-vacuum database, update the pointer-map entries\n    ** for any b-tree or overflow pages that pTo now contains the pointers to.\n    */\n    if( ISAUTOVACUUM ){\n      *pRC = setChildPtrmaps(pTo);\n    }\n  }\n}\n\n/*\n** This routine redistributes cells on the iParentIdx'th child of pParent\n** (hereafter \"the page\") and up to 2 siblings so that all pages have about the\n** same amount of free space. Usually a single sibling on either side of the\n** page are used in the balancing, though both siblings might come from one\n** side if the page is the first or last child of its parent. If the page \n** has fewer than 2 siblings (something which can only happen if the page\n** is a root page or a child of a root page) then all available siblings\n** participate in the balancing.\n**\n** The number of siblings of the page might be increased or decreased by \n** one or two in an effort to keep pages nearly full but not over full. \n**\n** Note that when this routine is called, some of the cells on the page\n** might not actually be stored in MemPage.aData[]. This can happen\n** if the page is overfull. This routine ensures that all cells allocated\n** to the page and its siblings fit into MemPage.aData[] before returning.\n**\n** In the course of balancing the page and its siblings, cells may be\n** inserted into or removed from the parent page (pParent). Doing so\n** may cause the parent page to become overfull or underfull. If this\n** happens, it is the responsibility of the caller to invoke the correct\n** balancing routine to fix this problem (see the balance() routine). \n**\n** If this routine fails for any reason, it might leave the database\n** in a corrupted state. So if this routine fails, the database should\n** be rolled back.\n**\n** The third argument to this function, aOvflSpace, is a pointer to a\n** buffer big enough to hold one page. If while inserting cells into the parent\n** page (pParent) the parent page becomes overfull, this buffer is\n** used to store the parent's overflow cells. Because this function inserts\n** a maximum of four divider cells into the parent page, and the maximum\n** size of a cell stored within an internal node is always less than 1/4\n** of the page-size, the aOvflSpace[] buffer is guaranteed to be large\n** enough for all overflow cells.\n**\n** If aOvflSpace is set to a null pointer, this function returns \n** SQLITE_NOMEM.\n*/\nstatic int balance_nonroot(\n  MemPage *pParent,               /* Parent page of siblings being balanced */\n  int iParentIdx,                 /* Index of \"the page\" in pParent */\n  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */\n  int isRoot,                     /* True if pParent is a root-page */\n  int bBulk                       /* True if this call is part of a bulk load */\n){\n  BtShared *pBt;               /* The whole database */\n  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */\n  int nNew = 0;                /* Number of pages in apNew[] */\n  int nOld;                    /* Number of pages in apOld[] */\n  int i, j, k;                 /* Loop counters */\n  int nxDiv;                   /* Next divider slot in pParent->aCell[] */\n  int rc = SQLITE_OK;          /* The return code */\n  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */\n  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */\n  int usableSpace;             /* Bytes in pPage beyond the header */\n  int pageFlags;               /* Value of pPage->aData[0] */\n  int iSpace1 = 0;             /* First unused byte of aSpace1[] */\n  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */\n  int szScratch;               /* Size of scratch memory requested */\n  MemPage *apOld[NB];          /* pPage and up to two siblings */\n  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */\n  u8 *pRight;                  /* Location in parent of right-sibling pointer */\n  u8 *apDiv[NB-1];             /* Divider cells in pParent */\n  int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */\n  int cntOld[NB+2];            /* Old index in b.apCell[] */\n  int szNew[NB+2];             /* Combined size of cells placed on i-th page */\n  u8 *aSpace1;                 /* Space for copies of dividers cells */\n  Pgno pgno;                   /* Temp var to store a page number in */\n  u8 abDone[NB+2];             /* True after i'th new page is populated */\n  Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */\n  Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */\n  u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */\n  CellArray b;                  /* Parsed information on cells being balanced */\n\n  memset(abDone, 0, sizeof(abDone));\n  b.nCell = 0;\n  b.apCell = 0;\n  pBt = pParent->pBt;\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( sqlite3PagerIswriteable(pParent->pDbPage) );\n\n  /* At this point pParent may have at most one overflow cell. And if\n  ** this overflow cell is present, it must be the cell with \n  ** index iParentIdx. This scenario comes about when this function\n  ** is called (indirectly) from sqlite3BtreeDelete().\n  */\n  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );\n  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );\n\n  if( !aOvflSpace ){\n    return SQLITE_NOMEM_BKPT;\n  }\n  assert( pParent->nFree>=0 );\n\n  /* Find the sibling pages to balance. Also locate the cells in pParent \n  ** that divide the siblings. An attempt is made to find NN siblings on \n  ** either side of pPage. More siblings are taken from one side, however, \n  ** if there are fewer than NN siblings on the other side. If pParent\n  ** has NB or fewer children then all children of pParent are taken.  \n  **\n  ** This loop also drops the divider cells from the parent page. This\n  ** way, the remainder of the function does not have to deal with any\n  ** overflow cells in the parent page, since if any existed they will\n  ** have already been removed.\n  */\n  i = pParent->nOverflow + pParent->nCell;\n  if( i<2 ){\n    nxDiv = 0;\n  }else{\n    assert( bBulk==0 || bBulk==1 );\n    if( iParentIdx==0 ){                 \n      nxDiv = 0;\n    }else if( iParentIdx==i ){\n      nxDiv = i-2+bBulk;\n    }else{\n      nxDiv = iParentIdx-1;\n    }\n    i = 2-bBulk;\n  }\n  nOld = i+1;\n  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){\n    pRight = &pParent->aData[pParent->hdrOffset+8];\n  }else{\n    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);\n  }\n  pgno = get4byte(pRight);\n  while( 1 ){\n    rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);\n    if( rc ){\n      memset(apOld, 0, (i+1)*sizeof(MemPage*));\n      goto balance_cleanup;\n    }\n    if( apOld[i]->nFree<0 ){\n      rc = btreeComputeFreeSpace(apOld[i]);\n      if( rc ){\n        memset(apOld, 0, (i)*sizeof(MemPage*));\n        goto balance_cleanup;\n      }\n    }\n    if( (i--)==0 ) break;\n\n    if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){\n      apDiv[i] = pParent->apOvfl[0];\n      pgno = get4byte(apDiv[i]);\n      szNew[i] = pParent->xCellSize(pParent, apDiv[i]);\n      pParent->nOverflow = 0;\n    }else{\n      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);\n      pgno = get4byte(apDiv[i]);\n      szNew[i] = pParent->xCellSize(pParent, apDiv[i]);\n\n      /* Drop the cell from the parent page. apDiv[i] still points to\n      ** the cell within the parent, even though it has been dropped.\n      ** This is safe because dropping a cell only overwrites the first\n      ** four bytes of it, and this function does not need the first\n      ** four bytes of the divider cell. So the pointer is safe to use\n      ** later on.  \n      **\n      ** But not if we are in secure-delete mode. In secure-delete mode,\n      ** the dropCell() routine will overwrite the entire cell with zeroes.\n      ** In this case, temporarily copy the cell into the aOvflSpace[]\n      ** buffer. It will be copied out again as soon as the aSpace[] buffer\n      ** is allocated.  */\n      if( pBt->btsFlags & BTS_FAST_SECURE ){\n        int iOff;\n\n        iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);\n        if( (iOff+szNew[i])>(int)pBt->usableSize ){\n          rc = SQLITE_CORRUPT_BKPT;\n          memset(apOld, 0, (i+1)*sizeof(MemPage*));\n          goto balance_cleanup;\n        }else{\n          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);\n          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];\n        }\n      }\n      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);\n    }\n  }\n\n  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte\n  ** alignment */\n  nMaxCells = nOld*(MX_CELL(pBt) + ArraySize(pParent->apOvfl));\n  nMaxCells = (nMaxCells + 3)&~3;\n\n  /*\n  ** Allocate space for memory structures\n  */\n  szScratch =\n       nMaxCells*sizeof(u8*)                       /* b.apCell */\n     + nMaxCells*sizeof(u16)                       /* b.szCell */\n     + pBt->pageSize;                              /* aSpace1 */\n\n  assert( szScratch<=7*(int)pBt->pageSize );\n  b.apCell = sqlite3StackAllocRaw(0, szScratch );\n  if( b.apCell==0 ){\n    rc = SQLITE_NOMEM_BKPT;\n    goto balance_cleanup;\n  }\n  b.szCell = (u16*)&b.apCell[nMaxCells];\n  aSpace1 = (u8*)&b.szCell[nMaxCells];\n  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );\n\n  /*\n  ** Load pointers to all cells on sibling pages and the divider cells\n  ** into the local b.apCell[] array.  Make copies of the divider cells\n  ** into space obtained from aSpace1[]. The divider cells have already\n  ** been removed from pParent.\n  **\n  ** If the siblings are on leaf pages, then the child pointers of the\n  ** divider cells are stripped from the cells before they are copied\n  ** into aSpace1[].  In this way, all cells in b.apCell[] are without\n  ** child pointers.  If siblings are not leaves, then all cell in\n  ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]\n  ** are alike.\n  **\n  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.\n  **       leafData:  1 if pPage holds key+data and pParent holds only keys.\n  */\n  b.pRef = apOld[0];\n  leafCorrection = b.pRef->leaf*4;\n  leafData = b.pRef->intKeyLeaf;\n  for(i=0; i<nOld; i++){\n    MemPage *pOld = apOld[i];\n    int limit = pOld->nCell;\n    u8 *aData = pOld->aData;\n    u16 maskPage = pOld->maskPage;\n    u8 *piCell = aData + pOld->cellOffset;\n    u8 *piEnd;\n    VVA_ONLY( int nCellAtStart = b.nCell; )\n\n    /* Verify that all sibling pages are of the same \"type\" (table-leaf,\n    ** table-interior, index-leaf, or index-interior).\n    */\n    if( pOld->aData[0]!=apOld[0]->aData[0] ){\n      rc = SQLITE_CORRUPT_BKPT;\n      goto balance_cleanup;\n    }\n\n    /* Load b.apCell[] with pointers to all cells in pOld.  If pOld\n    ** contains overflow cells, include them in the b.apCell[] array\n    ** in the correct spot.\n    **\n    ** Note that when there are multiple overflow cells, it is always the\n    ** case that they are sequential and adjacent.  This invariant arises\n    ** because multiple overflows can only occurs when inserting divider\n    ** cells into a parent on a prior balance, and divider cells are always\n    ** adjacent and are inserted in order.  There is an assert() tagged\n    ** with \"NOTE 1\" in the overflow cell insertion loop to prove this\n    ** invariant.\n    **\n    ** This must be done in advance.  Once the balance starts, the cell\n    ** offset section of the btree page will be overwritten and we will no\n    ** long be able to find the cells if a pointer to each cell is not saved\n    ** first.\n    */\n    memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));\n    if( pOld->nOverflow>0 ){\n      if( NEVER(limit<pOld->aiOvfl[0]) ){\n        rc = SQLITE_CORRUPT_BKPT;\n        goto balance_cleanup;\n      }\n      limit = pOld->aiOvfl[0];\n      for(j=0; j<limit; j++){\n        b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));\n        piCell += 2;\n        b.nCell++;\n      }\n      for(k=0; k<pOld->nOverflow; k++){\n        assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */\n        b.apCell[b.nCell] = pOld->apOvfl[k];\n        b.nCell++;\n      }\n    }\n    piEnd = aData + pOld->cellOffset + 2*pOld->nCell;\n    while( piCell<piEnd ){\n      assert( b.nCell<nMaxCells );\n      b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));\n      piCell += 2;\n      b.nCell++;\n    }\n    assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );\n\n    cntOld[i] = b.nCell;\n    if( i<nOld-1 && !leafData){\n      u16 sz = (u16)szNew[i];\n      u8 *pTemp;\n      assert( b.nCell<nMaxCells );\n      b.szCell[b.nCell] = sz;\n      pTemp = &aSpace1[iSpace1];\n      iSpace1 += sz;\n      assert( sz<=pBt->maxLocal+23 );\n      assert( iSpace1 <= (int)pBt->pageSize );\n      memcpy(pTemp, apDiv[i], sz);\n      b.apCell[b.nCell] = pTemp+leafCorrection;\n      assert( leafCorrection==0 || leafCorrection==4 );\n      b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;\n      if( !pOld->leaf ){\n        assert( leafCorrection==0 );\n        assert( pOld->hdrOffset==0 );\n        /* The right pointer of the child page pOld becomes the left\n        ** pointer of the divider cell */\n        memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);\n      }else{\n        assert( leafCorrection==4 );\n        while( b.szCell[b.nCell]<4 ){\n          /* Do not allow any cells smaller than 4 bytes. If a smaller cell\n          ** does exist, pad it with 0x00 bytes. */\n          assert( b.szCell[b.nCell]==3 || CORRUPT_DB );\n          assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );\n          aSpace1[iSpace1++] = 0x00;\n          b.szCell[b.nCell]++;\n        }\n      }\n      b.nCell++;\n    }\n  }\n\n  /*\n  ** Figure out the number of pages needed to hold all b.nCell cells.\n  ** Store this number in \"k\".  Also compute szNew[] which is the total\n  ** size of all cells on the i-th page and cntNew[] which is the index\n  ** in b.apCell[] of the cell that divides page i from page i+1.  \n  ** cntNew[k] should equal b.nCell.\n  **\n  ** Values computed by this block:\n  **\n  **           k: The total number of sibling pages\n  **    szNew[i]: Spaced used on the i-th sibling page.\n  **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to\n  **              the right of the i-th sibling page.\n  ** usableSpace: Number of bytes of space available on each sibling.\n  ** \n  */\n  usableSpace = pBt->usableSize - 12 + leafCorrection;\n  for(i=k=0; i<nOld; i++, k++){\n    MemPage *p = apOld[i];\n    b.apEnd[k] = p->aDataEnd;\n    b.ixNx[k] = cntOld[i];\n    if( k && b.ixNx[k]==b.ixNx[k-1] ){\n      k--;  /* Omit b.ixNx[] entry for child pages with no cells */\n    }\n    if( !leafData ){\n      k++;\n      b.apEnd[k] = pParent->aDataEnd;\n      b.ixNx[k] = cntOld[i]+1;\n    }\n    assert( p->nFree>=0 );\n    szNew[i] = usableSpace - p->nFree;\n    for(j=0; j<p->nOverflow; j++){\n      szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);\n    }\n    cntNew[i] = cntOld[i];\n  }\n  k = nOld;\n  for(i=0; i<k; i++){\n    int sz;\n    while( szNew[i]>usableSpace ){\n      if( i+1>=k ){\n        k = i+2;\n        if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }\n        szNew[k-1] = 0;\n        cntNew[k-1] = b.nCell;\n      }\n      sz = 2 + cachedCellSize(&b, cntNew[i]-1);\n      szNew[i] -= sz;\n      if( !leafData ){\n        if( cntNew[i]<b.nCell ){\n          sz = 2 + cachedCellSize(&b, cntNew[i]);\n        }else{\n          sz = 0;\n        }\n      }\n      szNew[i+1] += sz;\n      cntNew[i]--;\n    }\n    while( cntNew[i]<b.nCell ){\n      sz = 2 + cachedCellSize(&b, cntNew[i]);\n      if( szNew[i]+sz>usableSpace ) break;\n      szNew[i] += sz;\n      cntNew[i]++;\n      if( !leafData ){\n        if( cntNew[i]<b.nCell ){\n          sz = 2 + cachedCellSize(&b, cntNew[i]);\n        }else{\n          sz = 0;\n        }\n      }\n      szNew[i+1] -= sz;\n    }\n    if( cntNew[i]>=b.nCell ){\n      k = i+1;\n    }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){\n      rc = SQLITE_CORRUPT_BKPT;\n      goto balance_cleanup;\n    }\n  }\n\n  /*\n  ** The packing computed by the previous block is biased toward the siblings\n  ** on the left side (siblings with smaller keys). The left siblings are\n  ** always nearly full, while the right-most sibling might be nearly empty.\n  ** The next block of code attempts to adjust the packing of siblings to\n  ** get a better balance.\n  **\n  ** This adjustment is more than an optimization.  The packing above might\n  ** be so out of balance as to be illegal.  For example, the right-most\n  ** sibling might be completely empty.  This adjustment is not optional.\n  */\n  for(i=k-1; i>0; i--){\n    int szRight = szNew[i];  /* Size of sibling on the right */\n    int szLeft = szNew[i-1]; /* Size of sibling on the left */\n    int r;              /* Index of right-most cell in left sibling */\n    int d;              /* Index of first cell to the left of right sibling */\n\n    r = cntNew[i-1] - 1;\n    d = r + 1 - leafData;\n    (void)cachedCellSize(&b, d);\n    do{\n      assert( d<nMaxCells );\n      assert( r<nMaxCells );\n      (void)cachedCellSize(&b, r);\n      if( szRight!=0\n       && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){\n        break;\n      }\n      szRight += b.szCell[d] + 2;\n      szLeft -= b.szCell[r] + 2;\n      cntNew[i-1] = r;\n      r--;\n      d--;\n    }while( r>=0 );\n    szNew[i] = szRight;\n    szNew[i-1] = szLeft;\n    if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){\n      rc = SQLITE_CORRUPT_BKPT;\n      goto balance_cleanup;\n    }\n  }\n\n  /* Sanity check:  For a non-corrupt database file one of the follwing\n  ** must be true:\n  **    (1) We found one or more cells (cntNew[0])>0), or\n  **    (2) pPage is a virtual root page.  A virtual root page is when\n  **        the real root page is page 1 and we are the only child of\n  **        that page.\n  */\n  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);\n  TRACE((\"BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\\n\",\n    apOld[0]->pgno, apOld[0]->nCell,\n    nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,\n    nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0\n  ));\n\n  /*\n  ** Allocate k new pages.  Reuse old pages where possible.\n  */\n  pageFlags = apOld[0]->aData[0];\n  for(i=0; i<k; i++){\n    MemPage *pNew;\n    if( i<nOld ){\n      pNew = apNew[i] = apOld[i];\n      apOld[i] = 0;\n      rc = sqlite3PagerWrite(pNew->pDbPage);\n      nNew++;\n      if( rc ) goto balance_cleanup;\n    }else{\n      assert( i>0 );\n      rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);\n      if( rc ) goto balance_cleanup;\n      zeroPage(pNew, pageFlags);\n      apNew[i] = pNew;\n      nNew++;\n      cntOld[i] = b.nCell;\n\n      /* Set the pointer-map entry for the new sibling page. */\n      if( ISAUTOVACUUM ){\n        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);\n        if( rc!=SQLITE_OK ){\n          goto balance_cleanup;\n        }\n      }\n    }\n  }\n\n  /*\n  ** Reassign page numbers so that the new pages are in ascending order. \n  ** This helps to keep entries in the disk file in order so that a scan\n  ** of the table is closer to a linear scan through the file. That in turn \n  ** helps the operating system to deliver pages from the disk more rapidly.\n  **\n  ** An O(n^2) insertion sort algorithm is used, but since n is never more \n  ** than (NB+2) (a small constant), that should not be a problem.\n  **\n  ** When NB==3, this one optimization makes the database about 25% faster \n  ** for large insertions and deletions.\n  */\n  for(i=0; i<nNew; i++){\n    aPgOrder[i] = aPgno[i] = apNew[i]->pgno;\n    aPgFlags[i] = apNew[i]->pDbPage->flags;\n    for(j=0; j<i; j++){\n      if( aPgno[j]==aPgno[i] ){\n        /* This branch is taken if the set of sibling pages somehow contains\n        ** duplicate entries. This can happen if the database is corrupt. \n        ** It would be simpler to detect this as part of the loop below, but\n        ** we do the detection here in order to avoid populating the pager\n        ** cache with two separate objects associated with the same\n        ** page number.  */\n        assert( CORRUPT_DB );\n        rc = SQLITE_CORRUPT_BKPT;\n        goto balance_cleanup;\n      }\n    }\n  }\n  for(i=0; i<nNew; i++){\n    int iBest = 0;                /* aPgno[] index of page number to use */\n    for(j=1; j<nNew; j++){\n      if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;\n    }\n    pgno = aPgOrder[iBest];\n    aPgOrder[iBest] = 0xffffffff;\n    if( iBest!=i ){\n      if( iBest>i ){\n        sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);\n      }\n      sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);\n      apNew[i]->pgno = pgno;\n    }\n  }\n\n  TRACE((\"BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) \"\n         \"%d(%d nc=%d) %d(%d nc=%d)\\n\",\n    apNew[0]->pgno, szNew[0], cntNew[0],\n    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,\n    nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,\n    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,\n    nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,\n    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,\n    nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,\n    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,\n    nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0\n  ));\n\n  assert( sqlite3PagerIswriteable(pParent->pDbPage) );\n  assert( nNew>=1 && nNew<=ArraySize(apNew) );\n  assert( apNew[nNew-1]!=0 );\n  put4byte(pRight, apNew[nNew-1]->pgno);\n\n  /* If the sibling pages are not leaves, ensure that the right-child pointer\n  ** of the right-most new sibling page is set to the value that was \n  ** originally in the same field of the right-most old sibling page. */\n  if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){\n    MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];\n    memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);\n  }\n\n  /* Make any required updates to pointer map entries associated with \n  ** cells stored on sibling pages following the balance operation. Pointer\n  ** map entries associated with divider cells are set by the insertCell()\n  ** routine. The associated pointer map entries are:\n  **\n  **   a) if the cell contains a reference to an overflow chain, the\n  **      entry associated with the first page in the overflow chain, and\n  **\n  **   b) if the sibling pages are not leaves, the child page associated\n  **      with the cell.\n  **\n  ** If the sibling pages are not leaves, then the pointer map entry \n  ** associated with the right-child of each sibling may also need to be \n  ** updated. This happens below, after the sibling pages have been \n  ** populated, not here.\n  */\n  if( ISAUTOVACUUM ){\n    MemPage *pOld;\n    MemPage *pNew = pOld = apNew[0];\n    int cntOldNext = pNew->nCell + pNew->nOverflow;\n    int iNew = 0;\n    int iOld = 0;\n\n    for(i=0; i<b.nCell; i++){\n      u8 *pCell = b.apCell[i];\n      while( i==cntOldNext ){\n        iOld++;\n        assert( iOld<nNew || iOld<nOld );\n        assert( iOld>=0 && iOld<NB );\n        pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];\n        cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;\n      }\n      if( i==cntNew[iNew] ){\n        pNew = apNew[++iNew];\n        if( !leafData ) continue;\n      }\n\n      /* Cell pCell is destined for new sibling page pNew. Originally, it\n      ** was either part of sibling page iOld (possibly an overflow cell), \n      ** or else the divider cell to the left of sibling page iOld. So,\n      ** if sibling page iOld had the same page number as pNew, and if\n      ** pCell really was a part of sibling page iOld (not a divider or\n      ** overflow cell), we can skip updating the pointer map entries.  */\n      if( iOld>=nNew\n       || pNew->pgno!=aPgno[iOld]\n       || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)\n      ){\n        if( !leafCorrection ){\n          ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);\n        }\n        if( cachedCellSize(&b,i)>pNew->minLocal ){\n          ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);\n        }\n        if( rc ) goto balance_cleanup;\n      }\n    }\n  }\n\n  /* Insert new divider cells into pParent. */\n  for(i=0; i<nNew-1; i++){\n    u8 *pCell;\n    u8 *pTemp;\n    int sz;\n    MemPage *pNew = apNew[i];\n    j = cntNew[i];\n\n    assert( j<nMaxCells );\n    assert( b.apCell[j]!=0 );\n    pCell = b.apCell[j];\n    sz = b.szCell[j] + leafCorrection;\n    pTemp = &aOvflSpace[iOvflSpace];\n    if( !pNew->leaf ){\n      memcpy(&pNew->aData[8], pCell, 4);\n    }else if( leafData ){\n      /* If the tree is a leaf-data tree, and the siblings are leaves, \n      ** then there is no divider cell in b.apCell[]. Instead, the divider \n      ** cell consists of the integer key for the right-most cell of \n      ** the sibling-page assembled above only.\n      */\n      CellInfo info;\n      j--;\n      pNew->xParseCell(pNew, b.apCell[j], &info);\n      pCell = pTemp;\n      sz = 4 + putVarint(&pCell[4], info.nKey);\n      pTemp = 0;\n    }else{\n      pCell -= 4;\n      /* Obscure case for non-leaf-data trees: If the cell at pCell was\n      ** previously stored on a leaf node, and its reported size was 4\n      ** bytes, then it may actually be smaller than this \n      ** (see btreeParseCellPtr(), 4 bytes is the minimum size of\n      ** any cell). But it is important to pass the correct size to \n      ** insertCell(), so reparse the cell now.\n      **\n      ** This can only happen for b-trees used to evaluate \"IN (SELECT ...)\"\n      ** and WITHOUT ROWID tables with exactly one column which is the\n      ** primary key.\n      */\n      if( b.szCell[j]==4 ){\n        assert(leafCorrection==4);\n        sz = pParent->xCellSize(pParent, pCell);\n      }\n    }\n    iOvflSpace += sz;\n    assert( sz<=pBt->maxLocal+23 );\n    assert( iOvflSpace <= (int)pBt->pageSize );\n    insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);\n    if( rc!=SQLITE_OK ) goto balance_cleanup;\n    assert( sqlite3PagerIswriteable(pParent->pDbPage) );\n  }\n\n  /* Now update the actual sibling pages. The order in which they are updated\n  ** is important, as this code needs to avoid disrupting any page from which\n  ** cells may still to be read. In practice, this means:\n  **\n  **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])\n  **      then it is not safe to update page apNew[iPg] until after\n  **      the left-hand sibling apNew[iPg-1] has been updated.\n  **\n  **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])\n  **      then it is not safe to update page apNew[iPg] until after\n  **      the right-hand sibling apNew[iPg+1] has been updated.\n  **\n  ** If neither of the above apply, the page is safe to update.\n  **\n  ** The iPg value in the following loop starts at nNew-1 goes down\n  ** to 0, then back up to nNew-1 again, thus making two passes over\n  ** the pages.  On the initial downward pass, only condition (1) above\n  ** needs to be tested because (2) will always be true from the previous\n  ** step.  On the upward pass, both conditions are always true, so the\n  ** upwards pass simply processes pages that were missed on the downward\n  ** pass.\n  */\n  for(i=1-nNew; i<nNew; i++){\n    int iPg = i<0 ? -i : i;\n    assert( iPg>=0 && iPg<nNew );\n    if( abDone[iPg] ) continue;         /* Skip pages already processed */\n    if( i>=0                            /* On the upwards pass, or... */\n     || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */\n    ){\n      int iNew;\n      int iOld;\n      int nNewCell;\n\n      /* Verify condition (1):  If cells are moving left, update iPg\n      ** only after iPg-1 has already been updated. */\n      assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );\n\n      /* Verify condition (2):  If cells are moving right, update iPg\n      ** only after iPg+1 has already been updated. */\n      assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );\n\n      if( iPg==0 ){\n        iNew = iOld = 0;\n        nNewCell = cntNew[0];\n      }else{\n        iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;\n        iNew = cntNew[iPg-1] + !leafData;\n        nNewCell = cntNew[iPg] - iNew;\n      }\n\n      rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);\n      if( rc ) goto balance_cleanup;\n      abDone[iPg]++;\n      apNew[iPg]->nFree = usableSpace-szNew[iPg];\n      assert( apNew[iPg]->nOverflow==0 );\n      assert( apNew[iPg]->nCell==nNewCell );\n    }\n  }\n\n  /* All pages have been processed exactly once */\n  assert( memcmp(abDone, \"\\01\\01\\01\\01\\01\", nNew)==0 );\n\n  assert( nOld>0 );\n  assert( nNew>0 );\n\n  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){\n    /* The root page of the b-tree now contains no cells. The only sibling\n    ** page is the right-child of the parent. Copy the contents of the\n    ** child page into the parent, decreasing the overall height of the\n    ** b-tree structure by one. This is described as the \"balance-shallower\"\n    ** sub-algorithm in some documentation.\n    **\n    ** If this is an auto-vacuum database, the call to copyNodeContent() \n    ** sets all pointer-map entries corresponding to database image pages \n    ** for which the pointer is stored within the content being copied.\n    **\n    ** It is critical that the child page be defragmented before being\n    ** copied into the parent, because if the parent is page 1 then it will\n    ** by smaller than the child due to the database header, and so all the\n    ** free space needs to be up front.\n    */\n    assert( nNew==1 || CORRUPT_DB );\n    rc = defragmentPage(apNew[0], -1);\n    testcase( rc!=SQLITE_OK );\n    assert( apNew[0]->nFree == \n        (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset\n          - apNew[0]->nCell*2)\n      || rc!=SQLITE_OK\n    );\n    copyNodeContent(apNew[0], pParent, &rc);\n    freePage(apNew[0], &rc);\n  }else if( ISAUTOVACUUM && !leafCorrection ){\n    /* Fix the pointer map entries associated with the right-child of each\n    ** sibling page. All other pointer map entries have already been taken\n    ** care of.  */\n    for(i=0; i<nNew; i++){\n      u32 key = get4byte(&apNew[i]->aData[8]);\n      ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);\n    }\n  }\n\n  assert( pParent->isInit );\n  TRACE((\"BALANCE: finished: old=%d new=%d cells=%d\\n\",\n          nOld, nNew, b.nCell));\n\n  /* Free any old pages that were not reused as new pages.\n  */\n  for(i=nNew; i<nOld; i++){\n    freePage(apOld[i], &rc);\n  }\n\n#if 0\n  if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){\n    /* The ptrmapCheckPages() contains assert() statements that verify that\n    ** all pointer map pages are set correctly. This is helpful while \n    ** debugging. This is usually disabled because a corrupt database may\n    ** cause an assert() statement to fail.  */\n    ptrmapCheckPages(apNew, nNew);\n    ptrmapCheckPages(&pParent, 1);\n  }\n#endif\n\n  /*\n  ** Cleanup before returning.\n  */\nbalance_cleanup:\n  sqlite3StackFree(0, b.apCell);\n  for(i=0; i<nOld; i++){\n    releasePage(apOld[i]);\n  }\n  for(i=0; i<nNew; i++){\n    releasePage(apNew[i]);\n  }\n\n  return rc;\n}\n\n\n/*\n** This function is called when the root page of a b-tree structure is\n** overfull (has one or more overflow pages).\n**\n** A new child page is allocated and the contents of the current root\n** page, including overflow cells, are copied into the child. The root\n** page is then overwritten to make it an empty page with the right-child \n** pointer pointing to the new page.\n**\n** Before returning, all pointer-map entries corresponding to pages \n** that the new child-page now contains pointers to are updated. The\n** entry corresponding to the new right-child pointer of the root\n** page is also updated.\n**\n** If successful, *ppChild is set to contain a reference to the child \n** page and SQLITE_OK is returned. In this case the caller is required\n** to call releasePage() on *ppChild exactly once. If an error occurs,\n** an error code is returned and *ppChild is set to 0.\n*/\nstatic int balance_deeper(MemPage *pRoot, MemPage **ppChild){\n  int rc;                        /* Return value from subprocedures */\n  MemPage *pChild = 0;           /* Pointer to a new child page */\n  Pgno pgnoChild = 0;            /* Page number of the new child page */\n  BtShared *pBt = pRoot->pBt;    /* The BTree */\n\n  assert( pRoot->nOverflow>0 );\n  assert( sqlite3_mutex_held(pBt->mutex) );\n\n  /* Make pRoot, the root page of the b-tree, writable. Allocate a new \n  ** page that will become the new right-child of pPage. Copy the contents\n  ** of the node stored on pRoot into the new child page.\n  */\n  rc = sqlite3PagerWrite(pRoot->pDbPage);\n  if( rc==SQLITE_OK ){\n    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);\n    copyNodeContent(pRoot, pChild, &rc);\n    if( ISAUTOVACUUM ){\n      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);\n    }\n  }\n  if( rc ){\n    *ppChild = 0;\n    releasePage(pChild);\n    return rc;\n  }\n  assert( sqlite3PagerIswriteable(pChild->pDbPage) );\n  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );\n  assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );\n\n  TRACE((\"BALANCE: copy root %d into %d\\n\", pRoot->pgno, pChild->pgno));\n\n  /* Copy the overflow cells from pRoot to pChild */\n  memcpy(pChild->aiOvfl, pRoot->aiOvfl,\n         pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));\n  memcpy(pChild->apOvfl, pRoot->apOvfl,\n         pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));\n  pChild->nOverflow = pRoot->nOverflow;\n\n  /* Zero the contents of pRoot. Then install pChild as the right-child. */\n  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);\n  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);\n\n  *ppChild = pChild;\n  return SQLITE_OK;\n}\n\n/*\n** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid\n** on the same B-tree as pCur.\n**\n** This can if a database is corrupt with two or more SQL tables\n** pointing to the same b-tree.  If an insert occurs on one SQL table\n** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL\n** table linked to the same b-tree.  If the secondary insert causes a\n** rebalance, that can change content out from under the cursor on the\n** first SQL table, violating invariants on the first insert.\n*/\nstatic int anotherValidCursor(BtCursor *pCur){\n  BtCursor *pOther;\n  for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){\n    if( pOther!=pCur\n     && pOther->eState==CURSOR_VALID\n     && pOther->pPage==pCur->pPage\n    ){\n      return SQLITE_CORRUPT_BKPT;\n    }\n  }\n  return SQLITE_OK;\n}\n\n/*\n** The page that pCur currently points to has just been modified in\n** some way. This function figures out if this modification means the\n** tree needs to be balanced, and if so calls the appropriate balancing \n** routine. Balancing routines are:\n**\n**   balance_quick()\n**   balance_deeper()\n**   balance_nonroot()\n*/\nstatic int balance(BtCursor *pCur){\n  int rc = SQLITE_OK;\n  const int nMin = pCur->pBt->usableSize * 2 / 3;\n  u8 aBalanceQuickSpace[13];\n  u8 *pFree = 0;\n\n  VVA_ONLY( int balance_quick_called = 0 );\n  VVA_ONLY( int balance_deeper_called = 0 );\n\n  do {\n    int iPage;\n    MemPage *pPage = pCur->pPage;\n\n    if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;\n    if( pPage->nOverflow==0 && pPage->nFree<=nMin ){\n      break;\n    }else if( (iPage = pCur->iPage)==0 ){\n      if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){\n        /* The root page of the b-tree is overfull. In this case call the\n        ** balance_deeper() function to create a new child for the root-page\n        ** and copy the current contents of the root-page to it. The\n        ** next iteration of the do-loop will balance the child page.\n        */ \n        assert( balance_deeper_called==0 );\n        VVA_ONLY( balance_deeper_called++ );\n        rc = balance_deeper(pPage, &pCur->apPage[1]);\n        if( rc==SQLITE_OK ){\n          pCur->iPage = 1;\n          pCur->ix = 0;\n          pCur->aiIdx[0] = 0;\n          pCur->apPage[0] = pPage;\n          pCur->pPage = pCur->apPage[1];\n          assert( pCur->pPage->nOverflow );\n        }\n      }else{\n        break;\n      }\n    }else{\n      MemPage * const pParent = pCur->apPage[iPage-1];\n      int const iIdx = pCur->aiIdx[iPage-1];\n\n      rc = sqlite3PagerWrite(pParent->pDbPage);\n      if( rc==SQLITE_OK && pParent->nFree<0 ){\n        rc = btreeComputeFreeSpace(pParent);\n      }\n      if( rc==SQLITE_OK ){\n#ifndef SQLITE_OMIT_QUICKBALANCE\n        if( pPage->intKeyLeaf\n         && pPage->nOverflow==1\n         && pPage->aiOvfl[0]==pPage->nCell\n         && pParent->pgno!=1\n         && pParent->nCell==iIdx\n        ){\n          /* Call balance_quick() to create a new sibling of pPage on which\n          ** to store the overflow cell. balance_quick() inserts a new cell\n          ** into pParent, which may cause pParent overflow. If this\n          ** happens, the next iteration of the do-loop will balance pParent \n          ** use either balance_nonroot() or balance_deeper(). Until this\n          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]\n          ** buffer. \n          **\n          ** The purpose of the following assert() is to check that only a\n          ** single call to balance_quick() is made for each call to this\n          ** function. If this were not verified, a subtle bug involving reuse\n          ** of the aBalanceQuickSpace[] might sneak in.\n          */\n          assert( balance_quick_called==0 ); \n          VVA_ONLY( balance_quick_called++ );\n          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);\n        }else\n#endif\n        {\n          /* In this case, call balance_nonroot() to redistribute cells\n          ** between pPage and up to 2 of its sibling pages. This involves\n          ** modifying the contents of pParent, which may cause pParent to\n          ** become overfull or underfull. The next iteration of the do-loop\n          ** will balance the parent page to correct this.\n          ** \n          ** If the parent page becomes overfull, the overflow cell or cells\n          ** are stored in the pSpace buffer allocated immediately below. \n          ** A subsequent iteration of the do-loop will deal with this by\n          ** calling balance_nonroot() (balance_deeper() may be called first,\n          ** but it doesn't deal with overflow cells - just moves them to a\n          ** different page). Once this subsequent call to balance_nonroot() \n          ** has completed, it is safe to release the pSpace buffer used by\n          ** the previous call, as the overflow cell data will have been \n          ** copied either into the body of a database page or into the new\n          ** pSpace buffer passed to the latter call to balance_nonroot().\n          */\n          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);\n          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,\n                               pCur->hints&BTREE_BULKLOAD);\n          if( pFree ){\n            /* If pFree is not NULL, it points to the pSpace buffer used \n            ** by a previous call to balance_nonroot(). Its contents are\n            ** now stored either on real database pages or within the \n            ** new pSpace buffer, so it may be safely freed here. */\n            sqlite3PageFree(pFree);\n          }\n\n          /* The pSpace buffer will be freed after the next call to\n          ** balance_nonroot(), or just before this function returns, whichever\n          ** comes first. */\n          pFree = pSpace;\n        }\n      }\n\n      pPage->nOverflow = 0;\n\n      /* The next iteration of the do-loop balances the parent page. */\n      releasePage(pPage);\n      pCur->iPage--;\n      assert( pCur->iPage>=0 );\n      pCur->pPage = pCur->apPage[pCur->iPage];\n    }\n  }while( rc==SQLITE_OK );\n\n  if( pFree ){\n    sqlite3PageFree(pFree);\n  }\n  return rc;\n}\n\n/* Overwrite content from pX into pDest.  Only do the write if the\n** content is different from what is already there.\n*/\nstatic int btreeOverwriteContent(\n  MemPage *pPage,           /* MemPage on which writing will occur */\n  u8 *pDest,                /* Pointer to the place to start writing */\n  const BtreePayload *pX,   /* Source of data to write */\n  int iOffset,              /* Offset of first byte to write */\n  int iAmt                  /* Number of bytes to be written */\n){\n  int nData = pX->nData - iOffset;\n  if( nData<=0 ){\n    /* Overwritting with zeros */\n    int i;\n    for(i=0; i<iAmt && pDest[i]==0; i++){}\n    if( i<iAmt ){\n      int rc = sqlite3PagerWrite(pPage->pDbPage);\n      if( rc ) return rc;\n      memset(pDest + i, 0, iAmt - i);\n    }\n  }else{\n    if( nData<iAmt ){\n      /* Mixed read data and zeros at the end.  Make a recursive call\n      ** to write the zeros then fall through to write the real data */\n      int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,\n                                 iAmt-nData);\n      if( rc ) return rc;\n      iAmt = nData;\n    }\n    if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){\n      int rc = sqlite3PagerWrite(pPage->pDbPage);\n      if( rc ) return rc;\n      /* In a corrupt database, it is possible for the source and destination\n      ** buffers to overlap.  This is harmless since the database is already\n      ** corrupt but it does cause valgrind and ASAN warnings.  So use\n      ** memmove(). */\n      memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);\n    }\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Overwrite the cell that cursor pCur is pointing to with fresh content\n** contained in pX.\n*/\nstatic int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){\n  int iOffset;                        /* Next byte of pX->pData to write */\n  int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */\n  int rc;                             /* Return code */\n  MemPage *pPage = pCur->pPage;       /* Page being written */\n  BtShared *pBt;                      /* Btree */\n  Pgno ovflPgno;                      /* Next overflow page to write */\n  u32 ovflPageSize;                   /* Size to write on overflow page */\n\n  if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd\n   || pCur->info.pPayload < pPage->aData + pPage->cellOffset\n  ){\n    return SQLITE_CORRUPT_BKPT;\n  }\n  /* Overwrite the local portion first */\n  rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,\n                             0, pCur->info.nLocal);\n  if( rc ) return rc;\n  if( pCur->info.nLocal==nTotal ) return SQLITE_OK;\n\n  /* Now overwrite the overflow pages */\n  iOffset = pCur->info.nLocal;\n  assert( nTotal>=0 );\n  assert( iOffset>=0 );\n  ovflPgno = get4byte(pCur->info.pPayload + iOffset);\n  pBt = pPage->pBt;\n  ovflPageSize = pBt->usableSize - 4;\n  do{\n    rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);\n    if( rc ) return rc;\n    if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){\n      rc = SQLITE_CORRUPT_BKPT;\n    }else{\n      if( iOffset+ovflPageSize<(u32)nTotal ){\n        ovflPgno = get4byte(pPage->aData);\n      }else{\n        ovflPageSize = nTotal - iOffset;\n      }\n      rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,\n                                 iOffset, ovflPageSize);\n    }\n    sqlite3PagerUnref(pPage->pDbPage);\n    if( rc ) return rc;\n    iOffset += ovflPageSize;\n  }while( iOffset<nTotal );\n  return SQLITE_OK;    \n}\n\n\n/*\n** Insert a new record into the BTree.  The content of the new record\n** is described by the pX object.  The pCur cursor is used only to\n** define what table the record should be inserted into, and is left\n** pointing at a random location.\n**\n** For a table btree (used for rowid tables), only the pX.nKey value of\n** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the\n** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields\n** hold the content of the row.\n**\n** For an index btree (used for indexes and WITHOUT ROWID tables), the\n** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The \n** pX.pData,nData,nZero fields must be zero.\n**\n** If the seekResult parameter is non-zero, then a successful call to\n** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already\n** been performed.  In other words, if seekResult!=0 then the cursor\n** is currently pointing to a cell that will be adjacent to the cell\n** to be inserted.  If seekResult<0 then pCur points to a cell that is\n** smaller then (pKey,nKey).  If seekResult>0 then pCur points to a cell\n** that is larger than (pKey,nKey).\n**\n** If seekResult==0, that means pCur is pointing at some unknown location.\n** In that case, this routine must seek the cursor to the correct insertion\n** point for (pKey,nKey) before doing the insertion.  For index btrees,\n** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked\n** key values and pX->aMem can be used instead of pX->pKey to avoid having\n** to decode the key.\n*/\nSQLITE_PRIVATE int sqlite3BtreeInsert(\n  BtCursor *pCur,                /* Insert data into the table of this cursor */\n  const BtreePayload *pX,        /* Content of the row to be inserted */\n  int flags,                     /* True if this is likely an append */\n  int seekResult                 /* Result of prior MovetoUnpacked() call */\n){\n  int rc;\n  int loc = seekResult;          /* -1: before desired location  +1: after */\n  int szNew = 0;\n  int idx;\n  MemPage *pPage;\n  Btree *p = pCur->pBtree;\n  BtShared *pBt = p->pBt;\n  unsigned char *oldCell;\n  unsigned char *newCell = 0;\n\n  assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );\n\n  if( pCur->eState==CURSOR_FAULT ){\n    assert( pCur->skipNext!=SQLITE_OK );\n    return pCur->skipNext;\n  }\n\n  assert( cursorOwnsBtShared(pCur) );\n  assert( (pCur->curFlags & BTCF_WriteFlag)!=0\n              && pBt->inTransaction==TRANS_WRITE\n              && (pBt->btsFlags & BTS_READ_ONLY)==0 );\n  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );\n\n  /* Assert that the caller has been consistent. If this cursor was opened\n  ** expecting an index b-tree, then the caller should be inserting blob\n  ** keys with no associated data. If the cursor was opened expecting an\n  ** intkey table, the caller should be inserting integer keys with a\n  ** blob of associated data.  */\n  assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );\n\n  /* Save the positions of any other cursors open on this table.\n  **\n  ** In some cases, the call to btreeMoveto() below is a no-op. For\n  ** example, when inserting data into a table with auto-generated integer\n  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the \n  ** integer key to use. It then calls this function to actually insert the \n  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes\n  ** that the cursor is already where it needs to be and returns without\n  ** doing any work. To avoid thwarting these optimizations, it is important\n  ** not to clear the cursor here.\n  */\n  if( pCur->curFlags & BTCF_Multiple ){\n    rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);\n    if( rc ) return rc;\n  }\n\n  if( pCur->pKeyInfo==0 ){\n    assert( pX->pKey==0 );\n    /* If this is an insert into a table b-tree, invalidate any incrblob \n    ** cursors open on the row being replaced */\n    invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);\n\n    /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing \n    ** to a row with the same key as the new entry being inserted.\n    */\n#ifdef SQLITE_DEBUG\n    if( flags & BTREE_SAVEPOSITION ){\n      assert( pCur->curFlags & BTCF_ValidNKey );\n      assert( pX->nKey==pCur->info.nKey );\n      assert( loc==0 );\n    }\n#endif\n\n    /* On the other hand, BTREE_SAVEPOSITION==0 does not imply\n    ** that the cursor is not pointing to a row to be overwritten.\n    ** So do a complete check.\n    */\n    if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){\n      /* The cursor is pointing to the entry that is to be\n      ** overwritten */\n      assert( pX->nData>=0 && pX->nZero>=0 );\n      if( pCur->info.nSize!=0\n       && pCur->info.nPayload==(u32)pX->nData+pX->nZero\n      ){\n        /* New entry is the same size as the old.  Do an overwrite */\n        return btreeOverwriteCell(pCur, pX);\n      }\n      assert( loc==0 );\n    }else if( loc==0 ){\n      /* The cursor is *not* pointing to the cell to be overwritten, nor\n      ** to an adjacent cell.  Move the cursor so that it is pointing either\n      ** to the cell to be overwritten or an adjacent cell.\n      */\n      rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);\n      if( rc ) return rc;\n    }\n  }else{\n    /* This is an index or a WITHOUT ROWID table */\n\n    /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing \n    ** to a row with the same key as the new entry being inserted.\n    */\n    assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );\n\n    /* If the cursor is not already pointing either to the cell to be\n    ** overwritten, or if a new cell is being inserted, if the cursor is\n    ** not pointing to an immediately adjacent cell, then move the cursor\n    ** so that it does.\n    */\n    if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){\n      if( pX->nMem ){\n        UnpackedRecord r;\n        r.pKeyInfo = pCur->pKeyInfo;\n        r.aMem = pX->aMem;\n        r.nField = pX->nMem;\n        r.default_rc = 0;\n        r.errCode = 0;\n        r.r1 = 0;\n        r.r2 = 0;\n        r.eqSeen = 0;\n        rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);\n      }else{\n        rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);\n      }\n      if( rc ) return rc;\n    }\n\n    /* If the cursor is currently pointing to an entry to be overwritten\n    ** and the new content is the same as as the old, then use the\n    ** overwrite optimization.\n    */\n    if( loc==0 ){\n      getCellInfo(pCur);\n      if( pCur->info.nKey==pX->nKey ){\n        BtreePayload x2;\n        x2.pData = pX->pKey;\n        x2.nData = pX->nKey;\n        x2.nZero = 0;\n        return btreeOverwriteCell(pCur, &x2);\n      }\n    }\n\n  }\n  assert( pCur->eState==CURSOR_VALID \n       || (pCur->eState==CURSOR_INVALID && loc)\n       || CORRUPT_DB );\n\n  pPage = pCur->pPage;\n  assert( pPage->intKey || pX->nKey>=0 );\n  assert( pPage->leaf || !pPage->intKey );\n  if( pPage->nFree<0 ){\n    rc = btreeComputeFreeSpace(pPage);\n    if( rc ) return rc;\n  }\n\n  TRACE((\"INSERT: table=%d nkey=%lld ndata=%d page=%d %s\\n\",\n          pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,\n          loc==0 ? \"overwrite\" : \"new entry\"));\n  assert( pPage->isInit );\n  newCell = pBt->pTmpSpace;\n  assert( newCell!=0 );\n  rc = fillInCell(pPage, newCell, pX, &szNew);\n  if( rc ) goto end_insert;\n  assert( szNew==pPage->xCellSize(pPage, newCell) );\n  assert( szNew <= MX_CELL_SIZE(pBt) );\n  idx = pCur->ix;\n  if( loc==0 ){\n    CellInfo info;\n    assert( idx<pPage->nCell );\n    rc = sqlite3PagerWrite(pPage->pDbPage);\n    if( rc ){\n      goto end_insert;\n    }\n    oldCell = findCell(pPage, idx);\n    if( !pPage->leaf ){\n      memcpy(newCell, oldCell, 4);\n    }\n    rc = clearCell(pPage, oldCell, &info);\n    testcase( pCur->curFlags & BTCF_ValidOvfl );\n    invalidateOverflowCache(pCur);\n    if( info.nSize==szNew && info.nLocal==info.nPayload \n     && (!ISAUTOVACUUM || szNew<pPage->minLocal)\n    ){\n      /* Overwrite the old cell with the new if they are the same size.\n      ** We could also try to do this if the old cell is smaller, then add\n      ** the leftover space to the free list.  But experiments show that\n      ** doing that is no faster then skipping this optimization and just\n      ** calling dropCell() and insertCell(). \n      **\n      ** This optimization cannot be used on an autovacuum database if the\n      ** new entry uses overflow pages, as the insertCell() call below is\n      ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry.  */\n      assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */\n      if( oldCell < pPage->aData+pPage->hdrOffset+10 ){\n        return SQLITE_CORRUPT_BKPT;\n      }\n      if( oldCell+szNew > pPage->aDataEnd ){\n        return SQLITE_CORRUPT_BKPT;\n      }\n      memcpy(oldCell, newCell, szNew);\n      return SQLITE_OK;\n    }\n    dropCell(pPage, idx, info.nSize, &rc);\n    if( rc ) goto end_insert;\n  }else if( loc<0 && pPage->nCell>0 ){\n    assert( pPage->leaf );\n    idx = ++pCur->ix;\n    pCur->curFlags &= ~BTCF_ValidNKey;\n  }else{\n    assert( pPage->leaf );\n  }\n  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);\n  assert( pPage->nOverflow==0 || rc==SQLITE_OK );\n  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );\n\n  /* If no error has occurred and pPage has an overflow cell, call balance() \n  ** to redistribute the cells within the tree. Since balance() may move\n  ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey\n  ** variables.\n  **\n  ** Previous versions of SQLite called moveToRoot() to move the cursor\n  ** back to the root page as balance() used to invalidate the contents\n  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,\n  ** set the cursor state to \"invalid\". This makes common insert operations\n  ** slightly faster.\n  **\n  ** There is a subtle but important optimization here too. When inserting\n  ** multiple records into an intkey b-tree using a single cursor (as can\n  ** happen while processing an \"INSERT INTO ... SELECT\" statement), it\n  ** is advantageous to leave the cursor pointing to the last entry in\n  ** the b-tree if possible. If the cursor is left pointing to the last\n  ** entry in the table, and the next row inserted has an integer key\n  ** larger than the largest existing key, it is possible to insert the\n  ** row without seeking the cursor. This can be a big performance boost.\n  */\n  pCur->info.nSize = 0;\n  if( pPage->nOverflow ){\n    assert( rc==SQLITE_OK );\n    pCur->curFlags &= ~(BTCF_ValidNKey);\n    rc = balance(pCur);\n\n    /* Must make sure nOverflow is reset to zero even if the balance()\n    ** fails. Internal data structure corruption will result otherwise. \n    ** Also, set the cursor state to invalid. This stops saveCursorPosition()\n    ** from trying to save the current position of the cursor.  */\n    pCur->pPage->nOverflow = 0;\n    pCur->eState = CURSOR_INVALID;\n    if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){\n      btreeReleaseAllCursorPages(pCur);\n      if( pCur->pKeyInfo ){\n        assert( pCur->pKey==0 );\n        pCur->pKey = sqlite3Malloc( pX->nKey );\n        if( pCur->pKey==0 ){\n          rc = SQLITE_NOMEM;\n        }else{\n          memcpy(pCur->pKey, pX->pKey, pX->nKey);\n        }\n      }\n      pCur->eState = CURSOR_REQUIRESEEK;\n      pCur->nKey = pX->nKey;\n    }\n  }\n  assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );\n\nend_insert:\n  return rc;\n}\n\n/*\n** Delete the entry that the cursor is pointing to. \n**\n** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then\n** the cursor is left pointing at an arbitrary location after the delete.\n** But if that bit is set, then the cursor is left in a state such that\n** the next call to BtreeNext() or BtreePrev() moves it to the same row\n** as it would have been on if the call to BtreeDelete() had been omitted.\n**\n** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes\n** associated with a single table entry and its indexes.  Only one of those\n** deletes is considered the \"primary\" delete.  The primary delete occurs\n** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete\n** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.\n** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,\n** but which might be used by alternative storage engines.\n*/\nSQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){\n  Btree *p = pCur->pBtree;\n  BtShared *pBt = p->pBt;              \n  int rc;                              /* Return code */\n  MemPage *pPage;                      /* Page to delete cell from */\n  unsigned char *pCell;                /* Pointer to cell to delete */\n  int iCellIdx;                        /* Index of cell to delete */\n  int iCellDepth;                      /* Depth of node containing pCell */ \n  CellInfo info;                       /* Size of the cell being deleted */\n  int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */\n  u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */\n\n  assert( cursorOwnsBtShared(pCur) );\n  assert( pBt->inTransaction==TRANS_WRITE );\n  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );\n  assert( pCur->curFlags & BTCF_WriteFlag );\n  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );\n  assert( !hasReadConflicts(p, pCur->pgnoRoot) );\n  assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );\n  if( pCur->eState==CURSOR_REQUIRESEEK ){\n    rc = btreeRestoreCursorPosition(pCur);\n    if( rc ) return rc;\n  }\n  assert( pCur->eState==CURSOR_VALID );\n\n  iCellDepth = pCur->iPage;\n  iCellIdx = pCur->ix;\n  pPage = pCur->pPage;\n  pCell = findCell(pPage, iCellIdx);\n  if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ) return SQLITE_CORRUPT;\n\n  /* If the bPreserve flag is set to true, then the cursor position must\n  ** be preserved following this delete operation. If the current delete\n  ** will cause a b-tree rebalance, then this is done by saving the cursor\n  ** key and leaving the cursor in CURSOR_REQUIRESEEK state before \n  ** returning. \n  **\n  ** Or, if the current delete will not cause a rebalance, then the cursor\n  ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately\n  ** before or after the deleted entry. In this case set bSkipnext to true.  */\n  if( bPreserve ){\n    if( !pPage->leaf \n     || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)\n     || pPage->nCell==1  /* See dbfuzz001.test for a test case */\n    ){\n      /* A b-tree rebalance will be required after deleting this entry.\n      ** Save the cursor key.  */\n      rc = saveCursorKey(pCur);\n      if( rc ) return rc;\n    }else{\n      bSkipnext = 1;\n    }\n  }\n\n  /* If the page containing the entry to delete is not a leaf page, move\n  ** the cursor to the largest entry in the tree that is smaller than\n  ** the entry being deleted. This cell will replace the cell being deleted\n  ** from the internal node. The 'previous' entry is used for this instead\n  ** of the 'next' entry, as the previous entry is always a part of the\n  ** sub-tree headed by the child page of the cell being deleted. This makes\n  ** balancing the tree following the delete operation easier.  */\n  if( !pPage->leaf ){\n    rc = sqlite3BtreePrevious(pCur, 0);\n    assert( rc!=SQLITE_DONE );\n    if( rc ) return rc;\n  }\n\n  /* Save the positions of any other cursors open on this table before\n  ** making any modifications.  */\n  if( pCur->curFlags & BTCF_Multiple ){\n    rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);\n    if( rc ) return rc;\n  }\n\n  /* If this is a delete operation to remove a row from a table b-tree,\n  ** invalidate any incrblob cursors open on the row being deleted.  */\n  if( pCur->pKeyInfo==0 ){\n    invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);\n  }\n\n  /* Make the page containing the entry to be deleted writable. Then free any\n  ** overflow pages associated with the entry and finally remove the cell\n  ** itself from within the page.  */\n  rc = sqlite3PagerWrite(pPage->pDbPage);\n  if( rc ) return rc;\n  rc = clearCell(pPage, pCell, &info);\n  dropCell(pPage, iCellIdx, info.nSize, &rc);\n  if( rc ) return rc;\n\n  /* If the cell deleted was not located on a leaf page, then the cursor\n  ** is currently pointing to the largest entry in the sub-tree headed\n  ** by the child-page of the cell that was just deleted from an internal\n  ** node. The cell from the leaf node needs to be moved to the internal\n  ** node to replace the deleted cell.  */\n  if( !pPage->leaf ){\n    MemPage *pLeaf = pCur->pPage;\n    int nCell;\n    Pgno n;\n    unsigned char *pTmp;\n\n    if( pLeaf->nFree<0 ){\n      rc = btreeComputeFreeSpace(pLeaf);\n      if( rc ) return rc;\n    }\n    if( iCellDepth<pCur->iPage-1 ){\n      n = pCur->apPage[iCellDepth+1]->pgno;\n    }else{\n      n = pCur->pPage->pgno;\n    }\n    pCell = findCell(pLeaf, pLeaf->nCell-1);\n    if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;\n    nCell = pLeaf->xCellSize(pLeaf, pCell);\n    assert( MX_CELL_SIZE(pBt) >= nCell );\n    pTmp = pBt->pTmpSpace;\n    assert( pTmp!=0 );\n    rc = sqlite3PagerWrite(pLeaf->pDbPage);\n    if( rc==SQLITE_OK ){\n      insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);\n    }\n    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);\n    if( rc ) return rc;\n  }\n\n  /* Balance the tree. If the entry deleted was located on a leaf page,\n  ** then the cursor still points to that page. In this case the first\n  ** call to balance() repairs the tree, and the if(...) condition is\n  ** never true.\n  **\n  ** Otherwise, if the entry deleted was on an internal node page, then\n  ** pCur is pointing to the leaf page from which a cell was removed to\n  ** replace the cell deleted from the internal node. This is slightly\n  ** tricky as the leaf node may be underfull, and the internal node may\n  ** be either under or overfull. In this case run the balancing algorithm\n  ** on the leaf node first. If the balance proceeds far enough up the\n  ** tree that we can be sure that any problem in the internal node has\n  ** been corrected, so be it. Otherwise, after balancing the leaf node,\n  ** walk the cursor up the tree to the internal node and balance it as \n  ** well.  */\n  rc = balance(pCur);\n  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){\n    releasePageNotNull(pCur->pPage);\n    pCur->iPage--;\n    while( pCur->iPage>iCellDepth ){\n      releasePage(pCur->apPage[pCur->iPage--]);\n    }\n    pCur->pPage = pCur->apPage[pCur->iPage];\n    rc = balance(pCur);\n  }\n\n  if( rc==SQLITE_OK ){\n    if( bSkipnext ){\n      assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );\n      assert( pPage==pCur->pPage || CORRUPT_DB );\n      assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );\n      pCur->eState = CURSOR_SKIPNEXT;\n      if( iCellIdx>=pPage->nCell ){\n        pCur->skipNext = -1;\n        pCur->ix = pPage->nCell-1;\n      }else{\n        pCur->skipNext = 1;\n      }\n    }else{\n      rc = moveToRoot(pCur);\n      if( bPreserve ){\n        btreeReleaseAllCursorPages(pCur);\n        pCur->eState = CURSOR_REQUIRESEEK;\n      }\n      if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;\n    }\n  }\n  return rc;\n}\n\n/*\n** Create a new BTree table.  Write into *piTable the page\n** number for the root page of the new table.\n**\n** The type of type is determined by the flags parameter.  Only the\n** following values of flags are currently in use.  Other values for\n** flags might not work:\n**\n**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys\n**     BTREE_ZERODATA                  Used for SQL indices\n*/\nstatic int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){\n  BtShared *pBt = p->pBt;\n  MemPage *pRoot;\n  Pgno pgnoRoot;\n  int rc;\n  int ptfFlags;          /* Page-type flage for the root page of new table */\n\n  assert( sqlite3BtreeHoldsMutex(p) );\n  assert( pBt->inTransaction==TRANS_WRITE );\n  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );\n\n#ifdef SQLITE_OMIT_AUTOVACUUM\n  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);\n  if( rc ){\n    return rc;\n  }\n#else\n  if( pBt->autoVacuum ){\n    Pgno pgnoMove;      /* Move a page here to make room for the root-page */\n    MemPage *pPageMove; /* The page to move to. */\n\n    /* Creating a new table may probably require moving an existing database\n    ** to make room for the new tables root page. In case this page turns\n    ** out to be an overflow page, delete all overflow page-map caches\n    ** held by open cursors.\n    */\n    invalidateAllOverflowCache(pBt);\n\n    /* Read the value of meta[3] from the database to determine where the\n    ** root page of the new table should go. meta[3] is the largest root-page\n    ** created so far, so the new root-page is (meta[3]+1).\n    */\n    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);\n    pgnoRoot++;\n\n    /* The new root-page may not be allocated on a pointer-map page, or the\n    ** PENDING_BYTE page.\n    */\n    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||\n        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){\n      pgnoRoot++;\n    }\n    assert( pgnoRoot>=3 || CORRUPT_DB );\n    testcase( pgnoRoot<3 );\n\n    /* Allocate a page. The page that currently resides at pgnoRoot will\n    ** be moved to the allocated page (unless the allocated page happens\n    ** to reside at pgnoRoot).\n    */\n    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n\n    if( pgnoMove!=pgnoRoot ){\n      /* pgnoRoot is the page that will be used for the root-page of\n      ** the new table (assuming an error did not occur). But we were\n      ** allocated pgnoMove. If required (i.e. if it was not allocated\n      ** by extending the file), the current page at position pgnoMove\n      ** is already journaled.\n      */\n      u8 eType = 0;\n      Pgno iPtrPage = 0;\n\n      /* Save the positions of any open cursors. This is required in\n      ** case they are holding a reference to an xFetch reference\n      ** corresponding to page pgnoRoot.  */\n      rc = saveAllCursors(pBt, 0, 0);\n      releasePage(pPageMove);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n\n      /* Move the page currently at pgnoRoot to pgnoMove. */\n      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);\n      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){\n        rc = SQLITE_CORRUPT_BKPT;\n      }\n      if( rc!=SQLITE_OK ){\n        releasePage(pRoot);\n        return rc;\n      }\n      assert( eType!=PTRMAP_ROOTPAGE );\n      assert( eType!=PTRMAP_FREEPAGE );\n      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);\n      releasePage(pRoot);\n\n      /* Obtain the page at pgnoRoot */\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n      rc = sqlite3PagerWrite(pRoot->pDbPage);\n      if( rc!=SQLITE_OK ){\n        releasePage(pRoot);\n        return rc;\n      }\n    }else{\n      pRoot = pPageMove;\n    } \n\n    /* Update the pointer-map and meta-data with the new root-page number. */\n    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);\n    if( rc ){\n      releasePage(pRoot);\n      return rc;\n    }\n\n    /* When the new root page was allocated, page 1 was made writable in\n    ** order either to increase the database filesize, or to decrement the\n    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.\n    */\n    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );\n    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);\n    if( NEVER(rc) ){\n      releasePage(pRoot);\n      return rc;\n    }\n\n  }else{\n    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);\n    if( rc ) return rc;\n  }\n#endif\n  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );\n  if( createTabFlags & BTREE_INTKEY ){\n    ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;\n  }else{\n    ptfFlags = PTF_ZERODATA | PTF_LEAF;\n  }\n  zeroPage(pRoot, ptfFlags);\n  sqlite3PagerUnref(pRoot->pDbPage);\n  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );\n  *piTable = (int)pgnoRoot;\n  return SQLITE_OK;\n}\nSQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){\n  int rc;\n  sqlite3BtreeEnter(p);\n  rc = btreeCreateTable(p, piTable, flags);\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** Erase the given database page and all its children.  Return\n** the page to the freelist.\n*/\nstatic int clearDatabasePage(\n  BtShared *pBt,           /* The BTree that contains the table */\n  Pgno pgno,               /* Page number to clear */\n  int freePageFlag,        /* Deallocate page if true */\n  int *pnChange            /* Add number of Cells freed to this counter */\n){\n  MemPage *pPage;\n  int rc;\n  unsigned char *pCell;\n  int i;\n  int hdr;\n  CellInfo info;\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  if( pgno>btreePagecount(pBt) ){\n    return SQLITE_CORRUPT_BKPT;\n  }\n  rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);\n  if( rc ) return rc;\n  if( pPage->bBusy ){\n    rc = SQLITE_CORRUPT_BKPT;\n    goto cleardatabasepage_out;\n  }\n  pPage->bBusy = 1;\n  hdr = pPage->hdrOffset;\n  for(i=0; i<pPage->nCell; i++){\n    pCell = findCell(pPage, i);\n    if( !pPage->leaf ){\n      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);\n      if( rc ) goto cleardatabasepage_out;\n    }\n    rc = clearCell(pPage, pCell, &info);\n    if( rc ) goto cleardatabasepage_out;\n  }\n  if( !pPage->leaf ){\n    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);\n    if( rc ) goto cleardatabasepage_out;\n  }else if( pnChange ){\n    assert( pPage->intKey || CORRUPT_DB );\n    testcase( !pPage->intKey );\n    *pnChange += pPage->nCell;\n  }\n  if( freePageFlag ){\n    freePage(pPage, &rc);\n  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){\n    zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);\n  }\n\ncleardatabasepage_out:\n  pPage->bBusy = 0;\n  releasePage(pPage);\n  return rc;\n}\n\n/*\n** Delete all information from a single table in the database.  iTable is\n** the page number of the root of the table.  After this routine returns,\n** the root page is empty, but still exists.\n**\n** This routine will fail with SQLITE_LOCKED if there are any open\n** read cursors on the table.  Open write cursors are moved to the\n** root of the table.\n**\n** If pnChange is not NULL, then table iTable must be an intkey table. The\n** integer value pointed to by pnChange is incremented by the number of\n** entries in the table.\n*/\nSQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){\n  int rc;\n  BtShared *pBt = p->pBt;\n  sqlite3BtreeEnter(p);\n  assert( p->inTrans==TRANS_WRITE );\n\n  rc = saveAllCursors(pBt, (Pgno)iTable, 0);\n\n  if( SQLITE_OK==rc ){\n    /* Invalidate all incrblob cursors open on table iTable (assuming iTable\n    ** is the root of a table b-tree - if it is not, the following call is\n    ** a no-op).  */\n    invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);\n    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);\n  }\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** Delete all information from the single table that pCur is open on.\n**\n** This routine only work for pCur on an ephemeral table.\n*/\nSQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){\n  return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);\n}\n\n/*\n** Erase all information in a table and add the root of the table to\n** the freelist.  Except, the root of the principle table (the one on\n** page 1) is never added to the freelist.\n**\n** This routine will fail with SQLITE_LOCKED if there are any open\n** cursors on the table.\n**\n** If AUTOVACUUM is enabled and the page at iTable is not the last\n** root page in the database file, then the last root page \n** in the database file is moved into the slot formerly occupied by\n** iTable and that last slot formerly occupied by the last root page\n** is added to the freelist instead of iTable.  In this say, all\n** root pages are kept at the beginning of the database file, which\n** is necessary for AUTOVACUUM to work right.  *piMoved is set to the \n** page number that used to be the last root page in the file before\n** the move.  If no page gets moved, *piMoved is set to 0.\n** The last root page is recorded in meta[3] and the value of\n** meta[3] is updated by this procedure.\n*/\nstatic int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){\n  int rc;\n  MemPage *pPage = 0;\n  BtShared *pBt = p->pBt;\n\n  assert( sqlite3BtreeHoldsMutex(p) );\n  assert( p->inTrans==TRANS_WRITE );\n  assert( iTable>=2 );\n  if( iTable>btreePagecount(pBt) ){\n    return SQLITE_CORRUPT_BKPT;\n  }\n\n  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);\n  if( rc ) return rc;\n  rc = sqlite3BtreeClearTable(p, iTable, 0);\n  if( rc ){\n    releasePage(pPage);\n    return rc;\n  }\n\n  *piMoved = 0;\n\n#ifdef SQLITE_OMIT_AUTOVACUUM\n  freePage(pPage, &rc);\n  releasePage(pPage);\n#else\n  if( pBt->autoVacuum ){\n    Pgno maxRootPgno;\n    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);\n\n    if( iTable==maxRootPgno ){\n      /* If the table being dropped is the table with the largest root-page\n      ** number in the database, put the root page on the free list. \n      */\n      freePage(pPage, &rc);\n      releasePage(pPage);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n    }else{\n      /* The table being dropped does not have the largest root-page\n      ** number in the database. So move the page that does into the \n      ** gap left by the deleted root-page.\n      */\n      MemPage *pMove;\n      releasePage(pPage);\n      rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n      rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);\n      releasePage(pMove);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n      pMove = 0;\n      rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);\n      freePage(pMove, &rc);\n      releasePage(pMove);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n      *piMoved = maxRootPgno;\n    }\n\n    /* Set the new 'max-root-page' value in the database header. This\n    ** is the old value less one, less one more if that happens to\n    ** be a root-page number, less one again if that is the\n    ** PENDING_BYTE_PAGE.\n    */\n    maxRootPgno--;\n    while( maxRootPgno==PENDING_BYTE_PAGE(pBt)\n           || PTRMAP_ISPAGE(pBt, maxRootPgno) ){\n      maxRootPgno--;\n    }\n    assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );\n\n    rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);\n  }else{\n    freePage(pPage, &rc);\n    releasePage(pPage);\n  }\n#endif\n  return rc;  \n}\nSQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){\n  int rc;\n  sqlite3BtreeEnter(p);\n  rc = btreeDropTable(p, iTable, piMoved);\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n\n/*\n** This function may only be called if the b-tree connection already\n** has a read or write transaction open on the database.\n**\n** Read the meta-information out of a database file.  Meta[0]\n** is the number of free pages currently in the database.  Meta[1]\n** through meta[15] are available for use by higher layers.  Meta[0]\n** is read-only, the others are read/write.\n** \n** The schema layer numbers meta values differently.  At the schema\n** layer (and the SetCookie and ReadCookie opcodes) the number of\n** free pages is not visible.  So Cookie[0] is the same as Meta[1].\n**\n** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead\n** of reading the value out of the header, it instead loads the \"DataVersion\"\n** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the\n** database file.  It is a number computed by the pager.  But its access\n** pattern is the same as header meta values, and so it is convenient to\n** read it from this routine.\n*/\nSQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){\n  BtShared *pBt = p->pBt;\n\n  sqlite3BtreeEnter(p);\n  assert( p->inTrans>TRANS_NONE );\n  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );\n  assert( pBt->pPage1 );\n  assert( idx>=0 && idx<=15 );\n\n  if( idx==BTREE_DATA_VERSION ){\n    *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;\n  }else{\n    *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);\n  }\n\n  /* If auto-vacuum is disabled in this build and this is an auto-vacuum\n  ** database, mark the database as read-only.  */\n#ifdef SQLITE_OMIT_AUTOVACUUM\n  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){\n    pBt->btsFlags |= BTS_READ_ONLY;\n  }\n#endif\n\n  sqlite3BtreeLeave(p);\n}\n\n/*\n** Write meta-information back into the database.  Meta[0] is\n** read-only and may not be written.\n*/\nSQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){\n  BtShared *pBt = p->pBt;\n  unsigned char *pP1;\n  int rc;\n  assert( idx>=1 && idx<=15 );\n  sqlite3BtreeEnter(p);\n  assert( p->inTrans==TRANS_WRITE );\n  assert( pBt->pPage1!=0 );\n  pP1 = pBt->pPage1->aData;\n  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);\n  if( rc==SQLITE_OK ){\n    put4byte(&pP1[36 + idx*4], iMeta);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( idx==BTREE_INCR_VACUUM ){\n      assert( pBt->autoVacuum || iMeta==0 );\n      assert( iMeta==0 || iMeta==1 );\n      pBt->incrVacuum = (u8)iMeta;\n    }\n#endif\n  }\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** The first argument, pCur, is a cursor opened on some b-tree. Count the\n** number of entries in the b-tree and write the result to *pnEntry.\n**\n** SQLITE_OK is returned if the operation is successfully executed. \n** Otherwise, if an error is encountered (i.e. an IO error or database\n** corruption) an SQLite error code is returned.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){\n  i64 nEntry = 0;                      /* Value to return in *pnEntry */\n  int rc;                              /* Return code */\n\n  rc = moveToRoot(pCur);\n  if( rc==SQLITE_EMPTY ){\n    *pnEntry = 0;\n    return SQLITE_OK;\n  }\n\n  /* Unless an error occurs, the following loop runs one iteration for each\n  ** page in the B-Tree structure (not including overflow pages). \n  */\n  while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){\n    int iIdx;                          /* Index of child node in parent */\n    MemPage *pPage;                    /* Current page of the b-tree */\n\n    /* If this is a leaf page or the tree is not an int-key tree, then \n    ** this page contains countable entries. Increment the entry counter\n    ** accordingly.\n    */\n    pPage = pCur->pPage;\n    if( pPage->leaf || !pPage->intKey ){\n      nEntry += pPage->nCell;\n    }\n\n    /* pPage is a leaf node. This loop navigates the cursor so that it \n    ** points to the first interior cell that it points to the parent of\n    ** the next page in the tree that has not yet been visited. The\n    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell\n    ** of the page, or to the number of cells in the page if the next page\n    ** to visit is the right-child of its parent.\n    **\n    ** If all pages in the tree have been visited, return SQLITE_OK to the\n    ** caller.\n    */\n    if( pPage->leaf ){\n      do {\n        if( pCur->iPage==0 ){\n          /* All pages of the b-tree have been visited. Return successfully. */\n          *pnEntry = nEntry;\n          return moveToRoot(pCur);\n        }\n        moveToParent(pCur);\n      }while ( pCur->ix>=pCur->pPage->nCell );\n\n      pCur->ix++;\n      pPage = pCur->pPage;\n    }\n\n    /* Descend to the child node of the cell that the cursor currently \n    ** points at. This is the right-child if (iIdx==pPage->nCell).\n    */\n    iIdx = pCur->ix;\n    if( iIdx==pPage->nCell ){\n      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));\n    }else{\n      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));\n    }\n  }\n\n  /* An error has occurred. Return an error code. */\n  return rc;\n}\n\n/*\n** Return the pager associated with a BTree.  This routine is used for\n** testing and debugging only.\n*/\nSQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){\n  return p->pBt->pPager;\n}\n\n#ifndef SQLITE_OMIT_INTEGRITY_CHECK\n/*\n** Append a message to the error message string.\n*/\nstatic void checkAppendMsg(\n  IntegrityCk *pCheck,\n  const char *zFormat,\n  ...\n){\n  va_list ap;\n  if( !pCheck->mxErr ) return;\n  pCheck->mxErr--;\n  pCheck->nErr++;\n  va_start(ap, zFormat);\n  if( pCheck->errMsg.nChar ){\n    sqlite3_str_append(&pCheck->errMsg, \"\\n\", 1);\n  }\n  if( pCheck->zPfx ){\n    sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);\n  }\n  sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);\n  va_end(ap);\n  if( pCheck->errMsg.accError==SQLITE_NOMEM ){\n    pCheck->mallocFailed = 1;\n  }\n}\n#endif /* SQLITE_OMIT_INTEGRITY_CHECK */\n\n#ifndef SQLITE_OMIT_INTEGRITY_CHECK\n\n/*\n** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that\n** corresponds to page iPg is already set.\n*/\nstatic int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){\n  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );\n  return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));\n}\n\n/*\n** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.\n*/\nstatic void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){\n  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );\n  pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));\n}\n\n\n/*\n** Add 1 to the reference count for page iPage.  If this is the second\n** reference to the page, add an error message to pCheck->zErrMsg.\n** Return 1 if there are 2 or more references to the page and 0 if\n** if this is the first reference to the page.\n**\n** Also check that the page number is in bounds.\n*/\nstatic int checkRef(IntegrityCk *pCheck, Pgno iPage){\n  if( iPage>pCheck->nPage || iPage==0 ){\n    checkAppendMsg(pCheck, \"invalid page number %d\", iPage);\n    return 1;\n  }\n  if( getPageReferenced(pCheck, iPage) ){\n    checkAppendMsg(pCheck, \"2nd reference to page %d\", iPage);\n    return 1;\n  }\n  if( AtomicLoad(&pCheck->db->u1.isInterrupted) ) return 1;\n  setPageReferenced(pCheck, iPage);\n  return 0;\n}\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n/*\n** Check that the entry in the pointer-map for page iChild maps to \n** page iParent, pointer type ptrType. If not, append an error message\n** to pCheck.\n*/\nstatic void checkPtrmap(\n  IntegrityCk *pCheck,   /* Integrity check context */\n  Pgno iChild,           /* Child page number */\n  u8 eType,              /* Expected pointer map type */\n  Pgno iParent           /* Expected pointer map parent page number */\n){\n  int rc;\n  u8 ePtrmapType;\n  Pgno iPtrmapParent;\n\n  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);\n  if( rc!=SQLITE_OK ){\n    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;\n    checkAppendMsg(pCheck, \"Failed to read ptrmap key=%d\", iChild);\n    return;\n  }\n\n  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){\n    checkAppendMsg(pCheck,\n      \"Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)\", \n      iChild, eType, iParent, ePtrmapType, iPtrmapParent);\n  }\n}\n#endif\n\n/*\n** Check the integrity of the freelist or of an overflow page list.\n** Verify that the number of pages on the list is N.\n*/\nstatic void checkList(\n  IntegrityCk *pCheck,  /* Integrity checking context */\n  int isFreeList,       /* True for a freelist.  False for overflow page list */\n  int iPage,            /* Page number for first page in the list */\n  u32 N                 /* Expected number of pages in the list */\n){\n  int i;\n  u32 expected = N;\n  int nErrAtStart = pCheck->nErr;\n  while( iPage!=0 && pCheck->mxErr ){\n    DbPage *pOvflPage;\n    unsigned char *pOvflData;\n    if( checkRef(pCheck, iPage) ) break;\n    N--;\n    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){\n      checkAppendMsg(pCheck, \"failed to get page %d\", iPage);\n      break;\n    }\n    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);\n    if( isFreeList ){\n      u32 n = (u32)get4byte(&pOvflData[4]);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n      if( pCheck->pBt->autoVacuum ){\n        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);\n      }\n#endif\n      if( n>pCheck->pBt->usableSize/4-2 ){\n        checkAppendMsg(pCheck,\n           \"freelist leaf count too big on page %d\", iPage);\n        N--;\n      }else{\n        for(i=0; i<(int)n; i++){\n          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n          if( pCheck->pBt->autoVacuum ){\n            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);\n          }\n#endif\n          checkRef(pCheck, iFreePage);\n        }\n        N -= n;\n      }\n    }\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    else{\n      /* If this database supports auto-vacuum and iPage is not the last\n      ** page in this overflow list, check that the pointer-map entry for\n      ** the following page matches iPage.\n      */\n      if( pCheck->pBt->autoVacuum && N>0 ){\n        i = get4byte(pOvflData);\n        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);\n      }\n    }\n#endif\n    iPage = get4byte(pOvflData);\n    sqlite3PagerUnref(pOvflPage);\n  }\n  if( N && nErrAtStart==pCheck->nErr ){\n    checkAppendMsg(pCheck,\n      \"%s is %d but should be %d\",\n      isFreeList ? \"size\" : \"overflow list length\",\n      expected-N, expected);\n  }\n}\n#endif /* SQLITE_OMIT_INTEGRITY_CHECK */\n\n/*\n** An implementation of a min-heap.\n**\n** aHeap[0] is the number of elements on the heap.  aHeap[1] is the\n** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]\n** and aHeap[N*2+1].\n**\n** The heap property is this:  Every node is less than or equal to both\n** of its daughter nodes.  A consequence of the heap property is that the\n** root node aHeap[1] is always the minimum value currently in the heap.\n**\n** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto\n** the heap, preserving the heap property.  The btreeHeapPull() routine\n** removes the root element from the heap (the minimum value in the heap)\n** and then moves other nodes around as necessary to preserve the heap\n** property.\n**\n** This heap is used for cell overlap and coverage testing.  Each u32\n** entry represents the span of a cell or freeblock on a btree page.  \n** The upper 16 bits are the index of the first byte of a range and the\n** lower 16 bits are the index of the last byte of that range.\n*/\nstatic void btreeHeapInsert(u32 *aHeap, u32 x){\n  u32 j, i = ++aHeap[0];\n  aHeap[i] = x;\n  while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){\n    x = aHeap[j];\n    aHeap[j] = aHeap[i];\n    aHeap[i] = x;\n    i = j;\n  }\n}\nstatic int btreeHeapPull(u32 *aHeap, u32 *pOut){\n  u32 j, i, x;\n  if( (x = aHeap[0])==0 ) return 0;\n  *pOut = aHeap[1];\n  aHeap[1] = aHeap[x];\n  aHeap[x] = 0xffffffff;\n  aHeap[0]--;\n  i = 1;\n  while( (j = i*2)<=aHeap[0] ){\n    if( aHeap[j]>aHeap[j+1] ) j++;\n    if( aHeap[i]<aHeap[j] ) break;\n    x = aHeap[i];\n    aHeap[i] = aHeap[j];\n    aHeap[j] = x;\n    i = j;\n  }\n  return 1;  \n}\n\n#ifndef SQLITE_OMIT_INTEGRITY_CHECK\n/*\n** Do various sanity checks on a single page of a tree.  Return\n** the tree depth.  Root pages return 0.  Parents of root pages\n** return 1, and so forth.\n** \n** These checks are done:\n**\n**      1.  Make sure that cells and freeblocks do not overlap\n**          but combine to completely cover the page.\n**      2.  Make sure integer cell keys are in order.\n**      3.  Check the integrity of overflow pages.\n**      4.  Recursively call checkTreePage on all children.\n**      5.  Verify that the depth of all children is the same.\n*/\nstatic int checkTreePage(\n  IntegrityCk *pCheck,  /* Context for the sanity check */\n  int iPage,            /* Page number of the page to check */\n  i64 *piMinKey,        /* Write minimum integer primary key here */\n  i64 maxKey            /* Error if integer primary key greater than this */\n){\n  MemPage *pPage = 0;      /* The page being analyzed */\n  int i;                   /* Loop counter */\n  int rc;                  /* Result code from subroutine call */\n  int depth = -1, d2;      /* Depth of a subtree */\n  int pgno;                /* Page number */\n  int nFrag;               /* Number of fragmented bytes on the page */\n  int hdr;                 /* Offset to the page header */\n  int cellStart;           /* Offset to the start of the cell pointer array */\n  int nCell;               /* Number of cells */\n  int doCoverageCheck = 1; /* True if cell coverage checking should be done */\n  int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey\n                           ** False if IPK must be strictly less than maxKey */\n  u8 *data;                /* Page content */\n  u8 *pCell;               /* Cell content */\n  u8 *pCellIdx;            /* Next element of the cell pointer array */\n  BtShared *pBt;           /* The BtShared object that owns pPage */\n  u32 pc;                  /* Address of a cell */\n  u32 usableSize;          /* Usable size of the page */\n  u32 contentOffset;       /* Offset to the start of the cell content area */\n  u32 *heap = 0;           /* Min-heap used for checking cell coverage */\n  u32 x, prev = 0;         /* Next and previous entry on the min-heap */\n  const char *saved_zPfx = pCheck->zPfx;\n  int saved_v1 = pCheck->v1;\n  int saved_v2 = pCheck->v2;\n  u8 savedIsInit = 0;\n\n  /* Check that the page exists\n  */\n  pBt = pCheck->pBt;\n  usableSize = pBt->usableSize;\n  if( iPage==0 ) return 0;\n  if( checkRef(pCheck, iPage) ) return 0;\n  pCheck->zPfx = \"Page %d: \";\n  pCheck->v1 = iPage;\n  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){\n    checkAppendMsg(pCheck,\n       \"unable to get the page. error code=%d\", rc);\n    goto end_of_check;\n  }\n\n  /* Clear MemPage.isInit to make sure the corruption detection code in\n  ** btreeInitPage() is executed.  */\n  savedIsInit = pPage->isInit;\n  pPage->isInit = 0;\n  if( (rc = btreeInitPage(pPage))!=0 ){\n    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */\n    checkAppendMsg(pCheck,\n                   \"btreeInitPage() returns error code %d\", rc);\n    goto end_of_check;\n  }\n  if( (rc = btreeComputeFreeSpace(pPage))!=0 ){\n    assert( rc==SQLITE_CORRUPT );\n    checkAppendMsg(pCheck, \"free space corruption\", rc);\n    goto end_of_check;\n  }\n  data = pPage->aData;\n  hdr = pPage->hdrOffset;\n\n  /* Set up for cell analysis */\n  pCheck->zPfx = \"On tree page %d cell %d: \";\n  contentOffset = get2byteNotZero(&data[hdr+5]);\n  assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */\n\n  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the\n  ** number of cells on the page. */\n  nCell = get2byte(&data[hdr+3]);\n  assert( pPage->nCell==nCell );\n\n  /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page\n  ** immediately follows the b-tree page header. */\n  cellStart = hdr + 12 - 4*pPage->leaf;\n  assert( pPage->aCellIdx==&data[cellStart] );\n  pCellIdx = &data[cellStart + 2*(nCell-1)];\n\n  if( !pPage->leaf ){\n    /* Analyze the right-child page of internal pages */\n    pgno = get4byte(&data[hdr+8]);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( pBt->autoVacuum ){\n      pCheck->zPfx = \"On page %d at right child: \";\n      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);\n    }\n#endif\n    depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);\n    keyCanBeEqual = 0;\n  }else{\n    /* For leaf pages, the coverage check will occur in the same loop\n    ** as the other cell checks, so initialize the heap.  */\n    heap = pCheck->heap;\n    heap[0] = 0;\n  }\n\n  /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte\n  ** integer offsets to the cell contents. */\n  for(i=nCell-1; i>=0 && pCheck->mxErr; i--){\n    CellInfo info;\n\n    /* Check cell size */\n    pCheck->v2 = i;\n    assert( pCellIdx==&data[cellStart + i*2] );\n    pc = get2byteAligned(pCellIdx);\n    pCellIdx -= 2;\n    if( pc<contentOffset || pc>usableSize-4 ){\n      checkAppendMsg(pCheck, \"Offset %d out of range %d..%d\",\n                             pc, contentOffset, usableSize-4);\n      doCoverageCheck = 0;\n      continue;\n    }\n    pCell = &data[pc];\n    pPage->xParseCell(pPage, pCell, &info);\n    if( pc+info.nSize>usableSize ){\n      checkAppendMsg(pCheck, \"Extends off end of page\");\n      doCoverageCheck = 0;\n      continue;\n    }\n\n    /* Check for integer primary key out of range */\n    if( pPage->intKey ){\n      if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){\n        checkAppendMsg(pCheck, \"Rowid %lld out of order\", info.nKey);\n      }\n      maxKey = info.nKey;\n      keyCanBeEqual = 0;     /* Only the first key on the page may ==maxKey */\n    }\n\n    /* Check the content overflow list */\n    if( info.nPayload>info.nLocal ){\n      u32 nPage;       /* Number of pages on the overflow chain */\n      Pgno pgnoOvfl;   /* First page of the overflow chain */\n      assert( pc + info.nSize - 4 <= usableSize );\n      nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);\n      pgnoOvfl = get4byte(&pCell[info.nSize - 4]);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n      if( pBt->autoVacuum ){\n        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);\n      }\n#endif\n      checkList(pCheck, 0, pgnoOvfl, nPage);\n    }\n\n    if( !pPage->leaf ){\n      /* Check sanity of left child page for internal pages */\n      pgno = get4byte(pCell);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n      if( pBt->autoVacuum ){\n        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);\n      }\n#endif\n      d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);\n      keyCanBeEqual = 0;\n      if( d2!=depth ){\n        checkAppendMsg(pCheck, \"Child page depth differs\");\n        depth = d2;\n      }\n    }else{\n      /* Populate the coverage-checking heap for leaf pages */\n      btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));\n    }\n  }\n  *piMinKey = maxKey;\n\n  /* Check for complete coverage of the page\n  */\n  pCheck->zPfx = 0;\n  if( doCoverageCheck && pCheck->mxErr>0 ){\n    /* For leaf pages, the min-heap has already been initialized and the\n    ** cells have already been inserted.  But for internal pages, that has\n    ** not yet been done, so do it now */\n    if( !pPage->leaf ){\n      heap = pCheck->heap;\n      heap[0] = 0;\n      for(i=nCell-1; i>=0; i--){\n        u32 size;\n        pc = get2byteAligned(&data[cellStart+i*2]);\n        size = pPage->xCellSize(pPage, &data[pc]);\n        btreeHeapInsert(heap, (pc<<16)|(pc+size-1));\n      }\n    }\n    /* Add the freeblocks to the min-heap\n    **\n    ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header\n    ** is the offset of the first freeblock, or zero if there are no\n    ** freeblocks on the page. \n    */\n    i = get2byte(&data[hdr+1]);\n    while( i>0 ){\n      int size, j;\n      assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */\n      size = get2byte(&data[i+2]);\n      assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */\n      btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));\n      /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a\n      ** big-endian integer which is the offset in the b-tree page of the next\n      ** freeblock in the chain, or zero if the freeblock is the last on the\n      ** chain. */\n      j = get2byte(&data[i]);\n      /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of\n      ** increasing offset. */\n      assert( j==0 || j>i+size );     /* Enforced by btreeComputeFreeSpace() */\n      assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */\n      i = j;\n    }\n    /* Analyze the min-heap looking for overlap between cells and/or \n    ** freeblocks, and counting the number of untracked bytes in nFrag.\n    ** \n    ** Each min-heap entry is of the form:    (start_address<<16)|end_address.\n    ** There is an implied first entry the covers the page header, the cell\n    ** pointer index, and the gap between the cell pointer index and the start\n    ** of cell content.  \n    **\n    ** The loop below pulls entries from the min-heap in order and compares\n    ** the start_address against the previous end_address.  If there is an\n    ** overlap, that means bytes are used multiple times.  If there is a gap,\n    ** that gap is added to the fragmentation count.\n    */\n    nFrag = 0;\n    prev = contentOffset - 1;   /* Implied first min-heap entry */\n    while( btreeHeapPull(heap,&x) ){\n      if( (prev&0xffff)>=(x>>16) ){\n        checkAppendMsg(pCheck,\n          \"Multiple uses for byte %u of page %d\", x>>16, iPage);\n        break;\n      }else{\n        nFrag += (x>>16) - (prev&0xffff) - 1;\n        prev = x;\n      }\n    }\n    nFrag += usableSize - (prev&0xffff) - 1;\n    /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments\n    ** is stored in the fifth field of the b-tree page header.\n    ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the\n    ** number of fragmented free bytes within the cell content area.\n    */\n    if( heap[0]==0 && nFrag!=data[hdr+7] ){\n      checkAppendMsg(pCheck,\n          \"Fragmentation of %d bytes reported as %d on page %d\",\n          nFrag, data[hdr+7], iPage);\n    }\n  }\n\nend_of_check:\n  if( !doCoverageCheck ) pPage->isInit = savedIsInit;\n  releasePage(pPage);\n  pCheck->zPfx = saved_zPfx;\n  pCheck->v1 = saved_v1;\n  pCheck->v2 = saved_v2;\n  return depth+1;\n}\n#endif /* SQLITE_OMIT_INTEGRITY_CHECK */\n\n#ifndef SQLITE_OMIT_INTEGRITY_CHECK\n/*\n** This routine does a complete check of the given BTree file.  aRoot[] is\n** an array of pages numbers were each page number is the root page of\n** a table.  nRoot is the number of entries in aRoot.\n**\n** A read-only or read-write transaction must be opened before calling\n** this function.\n**\n** Write the number of error seen in *pnErr.  Except for some memory\n** allocation errors,  an error message held in memory obtained from\n** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is\n** returned.  If a memory allocation error occurs, NULL is returned.\n*/\nSQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(\n  sqlite3 *db,  /* Database connection that is running the check */\n  Btree *p,     /* The btree to be checked */\n  int *aRoot,   /* An array of root pages numbers for individual trees */\n  int nRoot,    /* Number of entries in aRoot[] */\n  int mxErr,    /* Stop reporting errors after this many */\n  int *pnErr    /* Write number of errors seen to this variable */\n){\n  Pgno i;\n  IntegrityCk sCheck;\n  BtShared *pBt = p->pBt;\n  u64 savedDbFlags = pBt->db->flags;\n  char zErr[100];\n  VVA_ONLY( int nRef );\n\n  sqlite3BtreeEnter(p);\n  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );\n  VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );\n  assert( nRef>=0 );\n  sCheck.db = db;\n  sCheck.pBt = pBt;\n  sCheck.pPager = pBt->pPager;\n  sCheck.nPage = btreePagecount(sCheck.pBt);\n  sCheck.mxErr = mxErr;\n  sCheck.nErr = 0;\n  sCheck.mallocFailed = 0;\n  sCheck.zPfx = 0;\n  sCheck.v1 = 0;\n  sCheck.v2 = 0;\n  sCheck.aPgRef = 0;\n  sCheck.heap = 0;\n  sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);\n  sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;\n  if( sCheck.nPage==0 ){\n    goto integrity_ck_cleanup;\n  }\n\n  sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);\n  if( !sCheck.aPgRef ){\n    sCheck.mallocFailed = 1;\n    goto integrity_ck_cleanup;\n  }\n  sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );\n  if( sCheck.heap==0 ){\n    sCheck.mallocFailed = 1;\n    goto integrity_ck_cleanup;\n  }\n\n  i = PENDING_BYTE_PAGE(pBt);\n  if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);\n\n  /* Check the integrity of the freelist\n  */\n  sCheck.zPfx = \"Main freelist: \";\n  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),\n            get4byte(&pBt->pPage1->aData[36]));\n  sCheck.zPfx = 0;\n\n  /* Check all the tables.\n  */\n#ifndef SQLITE_OMIT_AUTOVACUUM\n  if( pBt->autoVacuum ){\n    int mx = 0;\n    int mxInHdr;\n    for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];\n    mxInHdr = get4byte(&pBt->pPage1->aData[52]);\n    if( mx!=mxInHdr ){\n      checkAppendMsg(&sCheck,\n        \"max rootpage (%d) disagrees with header (%d)\",\n        mx, mxInHdr\n      );\n    }\n  }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){\n    checkAppendMsg(&sCheck,\n      \"incremental_vacuum enabled with a max rootpage of zero\"\n    );\n  }\n#endif\n  testcase( pBt->db->flags & SQLITE_CellSizeCk );\n  pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;\n  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){\n    i64 notUsed;\n    if( aRoot[i]==0 ) continue;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( pBt->autoVacuum && aRoot[i]>1 ){\n      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);\n    }\n#endif\n    checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);\n  }\n  pBt->db->flags = savedDbFlags;\n\n  /* Make sure every page in the file is referenced\n  */\n  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){\n#ifdef SQLITE_OMIT_AUTOVACUUM\n    if( getPageReferenced(&sCheck, i)==0 ){\n      checkAppendMsg(&sCheck, \"Page %d is never used\", i);\n    }\n#else\n    /* If the database supports auto-vacuum, make sure no tables contain\n    ** references to pointer-map pages.\n    */\n    if( getPageReferenced(&sCheck, i)==0 && \n       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){\n      checkAppendMsg(&sCheck, \"Page %d is never used\", i);\n    }\n    if( getPageReferenced(&sCheck, i)!=0 && \n       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){\n      checkAppendMsg(&sCheck, \"Pointer map page %d is referenced\", i);\n    }\n#endif\n  }\n\n  /* Clean  up and report errors.\n  */\nintegrity_ck_cleanup:\n  sqlite3PageFree(sCheck.heap);\n  sqlite3_free(sCheck.aPgRef);\n  if( sCheck.mallocFailed ){\n    sqlite3_str_reset(&sCheck.errMsg);\n    sCheck.nErr++;\n  }\n  *pnErr = sCheck.nErr;\n  if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);\n  /* Make sure this analysis did not leave any unref() pages. */\n  assert( nRef==sqlite3PagerRefcount(pBt->pPager) );\n  sqlite3BtreeLeave(p);\n  return sqlite3StrAccumFinish(&sCheck.errMsg);\n}\n#endif /* SQLITE_OMIT_INTEGRITY_CHECK */\n\n/*\n** Return the full pathname of the underlying database file.  Return\n** an empty string if the database is in-memory or a TEMP database.\n**\n** The pager filename is invariant as long as the pager is\n** open so it is safe to access without the BtShared mutex.\n*/\nSQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){\n  assert( p->pBt->pPager!=0 );\n  return sqlite3PagerFilename(p->pBt->pPager, 1);\n}\n\n/*\n** Return the pathname of the journal file for this database. The return\n** value of this routine is the same regardless of whether the journal file\n** has been created or not.\n**\n** The pager journal filename is invariant as long as the pager is\n** open so it is safe to access without the BtShared mutex.\n*/\nSQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){\n  assert( p->pBt->pPager!=0 );\n  return sqlite3PagerJournalname(p->pBt->pPager);\n}\n\n/*\n** Return non-zero if a transaction is active.\n*/\nSQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){\n  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );\n  return (p && (p->inTrans==TRANS_WRITE));\n}\n\n#ifndef SQLITE_OMIT_WAL\n/*\n** Run a checkpoint on the Btree passed as the first argument.\n**\n** Return SQLITE_LOCKED if this or any other connection has an open \n** transaction on the shared-cache the argument Btree is connected to.\n**\n** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){\n  int rc = SQLITE_OK;\n  if( p ){\n    BtShared *pBt = p->pBt;\n    sqlite3BtreeEnter(p);\n    if( pBt->inTransaction!=TRANS_NONE ){\n      rc = SQLITE_LOCKED;\n    }else{\n      rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);\n    }\n    sqlite3BtreeLeave(p);\n  }\n  return rc;\n}\n#endif\n\n/*\n** Return non-zero if a read (or write) transaction is active.\n*/\nSQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){\n  assert( p );\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  return p->inTrans!=TRANS_NONE;\n}\n\nSQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){\n  assert( p );\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  return p->nBackup!=0;\n}\n\n/*\n** This function returns a pointer to a blob of memory associated with\n** a single shared-btree. The memory is used by client code for its own\n** purposes (for example, to store a high-level schema associated with \n** the shared-btree). The btree layer manages reference counting issues.\n**\n** The first time this is called on a shared-btree, nBytes bytes of memory\n** are allocated, zeroed, and returned to the caller. For each subsequent \n** call the nBytes parameter is ignored and a pointer to the same blob\n** of memory returned. \n**\n** If the nBytes parameter is 0 and the blob of memory has not yet been\n** allocated, a null pointer is returned. If the blob has already been\n** allocated, it is returned as normal.\n**\n** Just before the shared-btree is closed, the function passed as the \n** xFree argument when the memory allocation was made is invoked on the \n** blob of allocated memory. The xFree function should not call sqlite3_free()\n** on the memory, the btree layer does that.\n*/\nSQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){\n  BtShared *pBt = p->pBt;\n  sqlite3BtreeEnter(p);\n  if( !pBt->pSchema && nBytes ){\n    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);\n    pBt->xFreeSchema = xFree;\n  }\n  sqlite3BtreeLeave(p);\n  return pBt->pSchema;\n}\n\n/*\n** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared \n** btree as the argument handle holds an exclusive lock on the \n** sqlite_master table. Otherwise SQLITE_OK.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){\n  int rc;\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  sqlite3BtreeEnter(p);\n  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);\n  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n/*\n** Obtain a lock on the table whose root page is iTab.  The\n** lock is a write lock if isWritelock is true or a read lock\n** if it is false.\n*/\nSQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){\n  int rc = SQLITE_OK;\n  assert( p->inTrans!=TRANS_NONE );\n  if( p->sharable ){\n    u8 lockType = READ_LOCK + isWriteLock;\n    assert( READ_LOCK+1==WRITE_LOCK );\n    assert( isWriteLock==0 || isWriteLock==1 );\n\n    sqlite3BtreeEnter(p);\n    rc = querySharedCacheTableLock(p, iTab, lockType);\n    if( rc==SQLITE_OK ){\n      rc = setSharedCacheTableLock(p, iTab, lockType);\n    }\n    sqlite3BtreeLeave(p);\n  }\n  return rc;\n}\n#endif\n\n#ifndef SQLITE_OMIT_INCRBLOB\n/*\n** Argument pCsr must be a cursor opened for writing on an \n** INTKEY table currently pointing at a valid table entry. \n** This function modifies the data stored as part of that entry.\n**\n** Only the data content may only be modified, it is not possible to \n** change the length of the data stored. If this function is called with\n** parameters that attempt to write past the end of the existing data,\n** no modifications are made and SQLITE_CORRUPT is returned.\n*/\nSQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){\n  int rc;\n  assert( cursorOwnsBtShared(pCsr) );\n  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );\n  assert( pCsr->curFlags & BTCF_Incrblob );\n\n  rc = restoreCursorPosition(pCsr);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n  assert( pCsr->eState!=CURSOR_REQUIRESEEK );\n  if( pCsr->eState!=CURSOR_VALID ){\n    return SQLITE_ABORT;\n  }\n\n  /* Save the positions of all other cursors open on this table. This is\n  ** required in case any of them are holding references to an xFetch\n  ** version of the b-tree page modified by the accessPayload call below.\n  **\n  ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()\n  ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence\n  ** saveAllCursors can only return SQLITE_OK.\n  */\n  VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);\n  assert( rc==SQLITE_OK );\n\n  /* Check some assumptions: \n  **   (a) the cursor is open for writing,\n  **   (b) there is a read/write transaction open,\n  **   (c) the connection holds a write-lock on the table (if required),\n  **   (d) there are no conflicting read-locks, and\n  **   (e) the cursor points at a valid row of an intKey table.\n  */\n  if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){\n    return SQLITE_READONLY;\n  }\n  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0\n              && pCsr->pBt->inTransaction==TRANS_WRITE );\n  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );\n  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );\n  assert( pCsr->pPage->intKey );\n\n  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);\n}\n\n/* \n** Mark this cursor as an incremental blob cursor.\n*/\nSQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){\n  pCur->curFlags |= BTCF_Incrblob;\n  pCur->pBtree->hasIncrblobCur = 1;\n}\n#endif\n\n/*\n** Set both the \"read version\" (single byte at byte offset 18) and \n** \"write version\" (single byte at byte offset 19) fields in the database\n** header to iVersion.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){\n  BtShared *pBt = pBtree->pBt;\n  int rc;                         /* Return code */\n \n  assert( iVersion==1 || iVersion==2 );\n\n  /* If setting the version fields to 1, do not automatically open the\n  ** WAL connection, even if the version fields are currently set to 2.\n  */\n  pBt->btsFlags &= ~BTS_NO_WAL;\n  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;\n\n  rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);\n  if( rc==SQLITE_OK ){\n    u8 *aData = pBt->pPage1->aData;\n    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){\n      rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);\n      if( rc==SQLITE_OK ){\n        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);\n        if( rc==SQLITE_OK ){\n          aData[18] = (u8)iVersion;\n          aData[19] = (u8)iVersion;\n        }\n      }\n    }\n  }\n\n  pBt->btsFlags &= ~BTS_NO_WAL;\n  return rc;\n}\n\n/*\n** Return true if the cursor has a hint specified.  This routine is\n** only used from within assert() statements\n*/\nSQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){\n  return (pCsr->hints & mask)!=0;\n}\n\n/*\n** Return true if the given Btree is read-only.\n*/\nSQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){\n  return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;\n}\n\n/*\n** Return the size of the header added to each page by this module.\n*/\nSQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }\n\n#if !defined(SQLITE_OMIT_SHARED_CACHE)\n/*\n** Return true if the Btree passed as the only argument is sharable.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){\n  return p->sharable;\n}\n\n/*\n** Return the number of connections to the BtShared object accessed by\n** the Btree handle passed as the only argument. For private caches \n** this is always 1. For shared caches it may be 1 or greater.\n*/\nSQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){\n  testcase( p->sharable );\n  return p->pBt->nRef;\n}\n#endif\n\n/************** End of btree.c ***********************************************/\n/************** Begin file backup.c ******************************************/\n/*\n** 2009 January 28\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the implementation of the sqlite3_backup_XXX() \n** API functions and the related features.\n*/\n/* #include \"sqliteInt.h\" */\n/* #include \"btreeInt.h\" */\n\n/*\n** Structure allocated for each backup operation.\n*/\nstruct sqlite3_backup {\n  sqlite3* pDestDb;        /* Destination database handle */\n  Btree *pDest;            /* Destination b-tree file */\n  u32 iDestSchema;         /* Original schema cookie in destination */\n  int bDestLocked;         /* True once a write-transaction is open on pDest */\n\n  Pgno iNext;              /* Page number of the next source page to copy */\n  sqlite3* pSrcDb;         /* Source database handle */\n  Btree *pSrc;             /* Source b-tree file */\n\n  int rc;                  /* Backup process error code */\n\n  /* These two variables are set by every call to backup_step(). They are\n  ** read by calls to backup_remaining() and backup_pagecount().\n  */\n  Pgno nRemaining;         /* Number of pages left to copy */\n  Pgno nPagecount;         /* Total number of pages to copy */\n\n  int isAttached;          /* True once backup has been registered with pager */\n  sqlite3_backup *pNext;   /* Next backup associated with source pager */\n};\n\n/*\n** THREAD SAFETY NOTES:\n**\n**   Once it has been created using backup_init(), a single sqlite3_backup\n**   structure may be accessed via two groups of thread-safe entry points:\n**\n**     * Via the sqlite3_backup_XXX() API function backup_step() and \n**       backup_finish(). Both these functions obtain the source database\n**       handle mutex and the mutex associated with the source BtShared \n**       structure, in that order.\n**\n**     * Via the BackupUpdate() and BackupRestart() functions, which are\n**       invoked by the pager layer to report various state changes in\n**       the page cache associated with the source database. The mutex\n**       associated with the source database BtShared structure will always \n**       be held when either of these functions are invoked.\n**\n**   The other sqlite3_backup_XXX() API functions, backup_remaining() and\n**   backup_pagecount() are not thread-safe functions. If they are called\n**   while some other thread is calling backup_step() or backup_finish(),\n**   the values returned may be invalid. There is no way for a call to\n**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()\n**   or backup_pagecount().\n**\n**   Depending on the SQLite configuration, the database handles and/or\n**   the Btree objects may have their own mutexes that require locking.\n**   Non-sharable Btrees (in-memory databases for example), do not have\n**   associated mutexes.\n*/\n\n/*\n** Return a pointer corresponding to database zDb (i.e. \"main\", \"temp\")\n** in connection handle pDb. If such a database cannot be found, return\n** a NULL pointer and write an error message to pErrorDb.\n**\n** If the \"temp\" database is requested, it may need to be opened by this \n** function. If an error occurs while doing so, return 0 and write an \n** error message to pErrorDb.\n*/\nstatic Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){\n  int i = sqlite3FindDbName(pDb, zDb);\n\n  if( i==1 ){\n    Parse sParse;\n    int rc = 0;\n    memset(&sParse, 0, sizeof(sParse));\n    sParse.db = pDb;\n    if( sqlite3OpenTempDatabase(&sParse) ){\n      sqlite3ErrorWithMsg(pErrorDb, sParse.rc, \"%s\", sParse.zErrMsg);\n      rc = SQLITE_ERROR;\n    }\n    sqlite3DbFree(pErrorDb, sParse.zErrMsg);\n    sqlite3ParserReset(&sParse);\n    if( rc ){\n      return 0;\n    }\n  }\n\n  if( i<0 ){\n    sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, \"unknown database %s\", zDb);\n    return 0;\n  }\n\n  return pDb->aDb[i].pBt;\n}\n\n/*\n** Attempt to set the page size of the destination to match the page size\n** of the source.\n*/\nstatic int setDestPgsz(sqlite3_backup *p){\n  int rc;\n  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),0,0);\n  return rc;\n}\n\n/*\n** Check that there is no open read-transaction on the b-tree passed as the\n** second argument. If there is not, return SQLITE_OK. Otherwise, if there\n** is an open read-transaction, return SQLITE_ERROR and leave an error \n** message in database handle db.\n*/\nstatic int checkReadTransaction(sqlite3 *db, Btree *p){\n  if( sqlite3BtreeIsInReadTrans(p) ){\n    sqlite3ErrorWithMsg(db, SQLITE_ERROR, \"destination database is in use\");\n    return SQLITE_ERROR;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Create an sqlite3_backup process to copy the contents of zSrcDb from\n** connection handle pSrcDb to zDestDb in pDestDb. If successful, return\n** a pointer to the new sqlite3_backup object.\n**\n** If an error occurs, NULL is returned and an error code and error message\n** stored in database handle pDestDb.\n*/\nSQLITE_API sqlite3_backup *sqlite3_backup_init(\n  sqlite3* pDestDb,                     /* Database to write to */\n  const char *zDestDb,                  /* Name of database within pDestDb */\n  sqlite3* pSrcDb,                      /* Database connection to read from */\n  const char *zSrcDb                    /* Name of database within pSrcDb */\n){\n  sqlite3_backup *p;                    /* Value to return */\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n\n  /* Lock the source database handle. The destination database\n  ** handle is not locked in this routine, but it is locked in\n  ** sqlite3_backup_step(). The user is required to ensure that no\n  ** other thread accesses the destination handle for the duration\n  ** of the backup operation.  Any attempt to use the destination\n  ** database connection while a backup is in progress may cause\n  ** a malfunction or a deadlock.\n  */\n  sqlite3_mutex_enter(pSrcDb->mutex);\n  sqlite3_mutex_enter(pDestDb->mutex);\n\n  if( pSrcDb==pDestDb ){\n    sqlite3ErrorWithMsg(\n        pDestDb, SQLITE_ERROR, \"source and destination must be distinct\"\n    );\n    p = 0;\n  }else {\n    /* Allocate space for a new sqlite3_backup object...\n    ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a\n    ** call to sqlite3_backup_init() and is destroyed by a call to\n    ** sqlite3_backup_finish(). */\n    p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));\n    if( !p ){\n      sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);\n    }\n  }\n\n  /* If the allocation succeeded, populate the new object. */\n  if( p ){\n    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);\n    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);\n    p->pDestDb = pDestDb;\n    p->pSrcDb = pSrcDb;\n    p->iNext = 1;\n    p->isAttached = 0;\n\n    if( 0==p->pSrc || 0==p->pDest \n     || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK \n     ){\n      /* One (or both) of the named databases did not exist or an OOM\n      ** error was hit. Or there is a transaction open on the destination\n      ** database. The error has already been written into the pDestDb \n      ** handle. All that is left to do here is free the sqlite3_backup \n      ** structure.  */\n      sqlite3_free(p);\n      p = 0;\n    }\n  }\n  if( p ){\n    p->pSrc->nBackup++;\n  }\n\n  sqlite3_mutex_leave(pDestDb->mutex);\n  sqlite3_mutex_leave(pSrcDb->mutex);\n  return p;\n}\n\n/*\n** Argument rc is an SQLite error code. Return true if this error is \n** considered fatal if encountered during a backup operation. All errors\n** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.\n*/\nstatic int isFatalError(int rc){\n  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));\n}\n\n/*\n** Parameter zSrcData points to a buffer containing the data for \n** page iSrcPg from the source database. Copy this data into the \n** destination database.\n*/\nstatic int backupOnePage(\n  sqlite3_backup *p,              /* Backup handle */\n  Pgno iSrcPg,                    /* Source database page to backup */\n  const u8 *zSrcData,             /* Source database page data */\n  int bUpdate                     /* True for an update, false otherwise */\n){\n  Pager * const pDestPager = sqlite3BtreePager(p->pDest);\n  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);\n  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);\n  const int nCopy = MIN(nSrcPgsz, nDestPgsz);\n  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;\n  int rc = SQLITE_OK;\n  i64 iOff;\n\n  assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );\n  assert( p->bDestLocked );\n  assert( !isFatalError(p->rc) );\n  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );\n  assert( zSrcData );\n\n  /* Catch the case where the destination is an in-memory database and the\n  ** page sizes of the source and destination differ. \n  */\n  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){\n    rc = SQLITE_READONLY;\n  }\n\n  /* This loop runs once for each destination page spanned by the source \n  ** page. For each iteration, variable iOff is set to the byte offset\n  ** of the destination page.\n  */\n  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){\n    DbPage *pDestPg = 0;\n    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;\n    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;\n    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))\n     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))\n    ){\n      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];\n      u8 *zDestData = sqlite3PagerGetData(pDestPg);\n      u8 *zOut = &zDestData[iOff%nDestPgsz];\n\n      /* Copy the data from the source page into the destination page.\n      ** Then clear the Btree layer MemPage.isInit flag. Both this module\n      ** and the pager code use this trick (clearing the first byte\n      ** of the page 'extra' space to invalidate the Btree layers\n      ** cached parse of the page). MemPage.isInit is marked \n      ** \"MUST BE FIRST\" for this purpose.\n      */\n      memcpy(zOut, zIn, nCopy);\n      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;\n      if( iOff==0 && bUpdate==0 ){\n        sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));\n      }\n    }\n    sqlite3PagerUnref(pDestPg);\n  }\n\n  return rc;\n}\n\n/*\n** If pFile is currently larger than iSize bytes, then truncate it to\n** exactly iSize bytes. If pFile is not larger than iSize bytes, then\n** this function is a no-op.\n**\n** Return SQLITE_OK if everything is successful, or an SQLite error \n** code if an error occurs.\n*/\nstatic int backupTruncateFile(sqlite3_file *pFile, i64 iSize){\n  i64 iCurrent;\n  int rc = sqlite3OsFileSize(pFile, &iCurrent);\n  if( rc==SQLITE_OK && iCurrent>iSize ){\n    rc = sqlite3OsTruncate(pFile, iSize);\n  }\n  return rc;\n}\n\n/*\n** Register this backup object with the associated source pager for\n** callbacks when pages are changed or the cache invalidated.\n*/\nstatic void attachBackupObject(sqlite3_backup *p){\n  sqlite3_backup **pp;\n  assert( sqlite3BtreeHoldsMutex(p->pSrc) );\n  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));\n  p->pNext = *pp;\n  *pp = p;\n  p->isAttached = 1;\n}\n\n/*\n** Copy nPage pages from the source b-tree to the destination.\n*/\nSQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){\n  int rc;\n  int destMode;       /* Destination journal mode */\n  int pgszSrc = 0;    /* Source page size */\n  int pgszDest = 0;   /* Destination page size */\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( p==0 ) return SQLITE_MISUSE_BKPT;\n#endif\n  sqlite3_mutex_enter(p->pSrcDb->mutex);\n  sqlite3BtreeEnter(p->pSrc);\n  if( p->pDestDb ){\n    sqlite3_mutex_enter(p->pDestDb->mutex);\n  }\n\n  rc = p->rc;\n  if( !isFatalError(rc) ){\n    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */\n    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */\n    int ii;                            /* Iterator variable */\n    int nSrcPage = -1;                 /* Size of source db in pages */\n    int bCloseTrans = 0;               /* True if src db requires unlocking */\n\n    /* If the source pager is currently in a write-transaction, return\n    ** SQLITE_BUSY immediately.\n    */\n    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){\n      rc = SQLITE_BUSY;\n    }else{\n      rc = SQLITE_OK;\n    }\n\n    /* If there is no open read-transaction on the source database, open\n    ** one now. If a transaction is opened here, then it will be closed\n    ** before this function exits.\n    */\n    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){\n      rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0);\n      bCloseTrans = 1;\n    }\n\n    /* If the destination database has not yet been locked (i.e. if this\n    ** is the first call to backup_step() for the current backup operation),\n    ** try to set its page size to the same as the source database. This\n    ** is especially important on ZipVFS systems, as in that case it is\n    ** not possible to create a database file that uses one page size by\n    ** writing to it with another.  */\n    if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){\n      rc = SQLITE_NOMEM;\n    }\n\n    /* Lock the destination database, if it is not locked already. */\n    if( SQLITE_OK==rc && p->bDestLocked==0\n     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2,\n                                                (int*)&p->iDestSchema)) \n    ){\n      p->bDestLocked = 1;\n    }\n\n    /* Do not allow backup if the destination database is in WAL mode\n    ** and the page sizes are different between source and destination */\n    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);\n    pgszDest = sqlite3BtreeGetPageSize(p->pDest);\n    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));\n    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){\n      rc = SQLITE_READONLY;\n    }\n  \n    /* Now that there is a read-lock on the source database, query the\n    ** source pager for the number of pages in the database.\n    */\n    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);\n    assert( nSrcPage>=0 );\n    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){\n      const Pgno iSrcPg = p->iNext;                 /* Source page number */\n      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){\n        DbPage *pSrcPg;                             /* Source page object */\n        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);\n        if( rc==SQLITE_OK ){\n          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);\n          sqlite3PagerUnref(pSrcPg);\n        }\n      }\n      p->iNext++;\n    }\n    if( rc==SQLITE_OK ){\n      p->nPagecount = nSrcPage;\n      p->nRemaining = nSrcPage+1-p->iNext;\n      if( p->iNext>(Pgno)nSrcPage ){\n        rc = SQLITE_DONE;\n      }else if( !p->isAttached ){\n        attachBackupObject(p);\n      }\n    }\n  \n    /* Update the schema version field in the destination database. This\n    ** is to make sure that the schema-version really does change in\n    ** the case where the source and destination databases have the\n    ** same schema version.\n    */\n    if( rc==SQLITE_DONE ){\n      if( nSrcPage==0 ){\n        rc = sqlite3BtreeNewDb(p->pDest);\n        nSrcPage = 1;\n      }\n      if( rc==SQLITE_OK || rc==SQLITE_DONE ){\n        rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);\n      }\n      if( rc==SQLITE_OK ){\n        if( p->pDestDb ){\n          sqlite3ResetAllSchemasOfConnection(p->pDestDb);\n        }\n        if( destMode==PAGER_JOURNALMODE_WAL ){\n          rc = sqlite3BtreeSetVersion(p->pDest, 2);\n        }\n      }\n      if( rc==SQLITE_OK ){\n        int nDestTruncate;\n        /* Set nDestTruncate to the final number of pages in the destination\n        ** database. The complication here is that the destination page\n        ** size may be different to the source page size. \n        **\n        ** If the source page size is smaller than the destination page size, \n        ** round up. In this case the call to sqlite3OsTruncate() below will\n        ** fix the size of the file. However it is important to call\n        ** sqlite3PagerTruncateImage() here so that any pages in the \n        ** destination file that lie beyond the nDestTruncate page mark are\n        ** journalled by PagerCommitPhaseOne() before they are destroyed\n        ** by the file truncation.\n        */\n        assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );\n        assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );\n        if( pgszSrc<pgszDest ){\n          int ratio = pgszDest/pgszSrc;\n          nDestTruncate = (nSrcPage+ratio-1)/ratio;\n          if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){\n            nDestTruncate--;\n          }\n        }else{\n          nDestTruncate = nSrcPage * (pgszSrc/pgszDest);\n        }\n        assert( nDestTruncate>0 );\n\n        if( pgszSrc<pgszDest ){\n          /* If the source page-size is smaller than the destination page-size,\n          ** two extra things may need to happen:\n          **\n          **   * The destination may need to be truncated, and\n          **\n          **   * Data stored on the pages immediately following the \n          **     pending-byte page in the source database may need to be\n          **     copied into the destination database.\n          */\n          const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;\n          sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);\n          Pgno iPg;\n          int nDstPage;\n          i64 iOff;\n          i64 iEnd;\n\n          assert( pFile );\n          assert( nDestTruncate==0 \n              || (i64)nDestTruncate*(i64)pgszDest >= iSize || (\n                nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)\n             && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest\n          ));\n\n          /* This block ensures that all data required to recreate the original\n          ** database has been stored in the journal for pDestPager and the\n          ** journal synced to disk. So at this point we may safely modify\n          ** the database file in any way, knowing that if a power failure\n          ** occurs, the original database will be reconstructed from the \n          ** journal file.  */\n          sqlite3PagerPagecount(pDestPager, &nDstPage);\n          for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){\n            if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){\n              DbPage *pPg;\n              rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);\n              if( rc==SQLITE_OK ){\n                rc = sqlite3PagerWrite(pPg);\n                sqlite3PagerUnref(pPg);\n              }\n            }\n          }\n          if( rc==SQLITE_OK ){\n            rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);\n          }\n\n          /* Write the extra pages and truncate the database file as required */\n          iEnd = MIN(PENDING_BYTE + pgszDest, iSize);\n          for(\n            iOff=PENDING_BYTE+pgszSrc; \n            rc==SQLITE_OK && iOff<iEnd; \n            iOff+=pgszSrc\n          ){\n            PgHdr *pSrcPg = 0;\n            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);\n            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);\n            if( rc==SQLITE_OK ){\n              u8 *zData = sqlite3PagerGetData(pSrcPg);\n              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);\n            }\n            sqlite3PagerUnref(pSrcPg);\n          }\n          if( rc==SQLITE_OK ){\n            rc = backupTruncateFile(pFile, iSize);\n          }\n\n          /* Sync the database file to disk. */\n          if( rc==SQLITE_OK ){\n            rc = sqlite3PagerSync(pDestPager, 0);\n          }\n        }else{\n          sqlite3PagerTruncateImage(pDestPager, nDestTruncate);\n          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);\n        }\n    \n        /* Finish committing the transaction to the destination database. */\n        if( SQLITE_OK==rc\n         && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))\n        ){\n          rc = SQLITE_DONE;\n        }\n      }\n    }\n  \n    /* If bCloseTrans is true, then this function opened a read transaction\n    ** on the source database. Close the read transaction here. There is\n    ** no need to check the return values of the btree methods here, as\n    ** \"committing\" a read-only transaction cannot fail.\n    */\n    if( bCloseTrans ){\n      TESTONLY( int rc2 );\n      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);\n      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);\n      assert( rc2==SQLITE_OK );\n    }\n  \n    if( rc==SQLITE_IOERR_NOMEM ){\n      rc = SQLITE_NOMEM_BKPT;\n    }\n    p->rc = rc;\n  }\n  if( p->pDestDb ){\n    sqlite3_mutex_leave(p->pDestDb->mutex);\n  }\n  sqlite3BtreeLeave(p->pSrc);\n  sqlite3_mutex_leave(p->pSrcDb->mutex);\n  return rc;\n}\n\n/*\n** Release all resources associated with an sqlite3_backup* handle.\n*/\nSQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){\n  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */\n  sqlite3 *pSrcDb;                     /* Source database connection */\n  int rc;                              /* Value to return */\n\n  /* Enter the mutexes */\n  if( p==0 ) return SQLITE_OK;\n  pSrcDb = p->pSrcDb;\n  sqlite3_mutex_enter(pSrcDb->mutex);\n  sqlite3BtreeEnter(p->pSrc);\n  if( p->pDestDb ){\n    sqlite3_mutex_enter(p->pDestDb->mutex);\n  }\n\n  /* Detach this backup from the source pager. */\n  if( p->pDestDb ){\n    p->pSrc->nBackup--;\n  }\n  if( p->isAttached ){\n    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));\n    assert( pp!=0 );\n    while( *pp!=p ){\n      pp = &(*pp)->pNext;\n      assert( pp!=0 );\n    }\n    *pp = p->pNext;\n  }\n\n  /* If a transaction is still open on the Btree, roll it back. */\n  sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);\n\n  /* Set the error code of the destination database handle. */\n  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;\n  if( p->pDestDb ){\n    sqlite3Error(p->pDestDb, rc);\n\n    /* Exit the mutexes and free the backup context structure. */\n    sqlite3LeaveMutexAndCloseZombie(p->pDestDb);\n  }\n  sqlite3BtreeLeave(p->pSrc);\n  if( p->pDestDb ){\n    /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a\n    ** call to sqlite3_backup_init() and is destroyed by a call to\n    ** sqlite3_backup_finish(). */\n    sqlite3_free(p);\n  }\n  sqlite3LeaveMutexAndCloseZombie(pSrcDb);\n  return rc;\n}\n\n/*\n** Return the number of pages still to be backed up as of the most recent\n** call to sqlite3_backup_step().\n*/\nSQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( p==0 ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  return p->nRemaining;\n}\n\n/*\n** Return the total number of pages in the source database as of the most \n** recent call to sqlite3_backup_step().\n*/\nSQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( p==0 ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  return p->nPagecount;\n}\n\n/*\n** This function is called after the contents of page iPage of the\n** source database have been modified. If page iPage has already been \n** copied into the destination database, then the data written to the\n** destination is now invalidated. The destination copy of iPage needs\n** to be updated with the new data before the backup operation is\n** complete.\n**\n** It is assumed that the mutex associated with the BtShared object\n** corresponding to the source database is held when this function is\n** called.\n*/\nstatic SQLITE_NOINLINE void backupUpdate(\n  sqlite3_backup *p,\n  Pgno iPage,\n  const u8 *aData\n){\n  assert( p!=0 );\n  do{\n    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );\n    if( !isFatalError(p->rc) && iPage<p->iNext ){\n      /* The backup process p has already copied page iPage. But now it\n      ** has been modified by a transaction on the source pager. Copy\n      ** the new data into the backup.\n      */\n      int rc;\n      assert( p->pDestDb );\n      sqlite3_mutex_enter(p->pDestDb->mutex);\n      rc = backupOnePage(p, iPage, aData, 1);\n      sqlite3_mutex_leave(p->pDestDb->mutex);\n      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );\n      if( rc!=SQLITE_OK ){\n        p->rc = rc;\n      }\n    }\n  }while( (p = p->pNext)!=0 );\n}\nSQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){\n  if( pBackup ) backupUpdate(pBackup, iPage, aData);\n}\n\n/*\n** Restart the backup process. This is called when the pager layer\n** detects that the database has been modified by an external database\n** connection. In this case there is no way of knowing which of the\n** pages that have been copied into the destination database are still \n** valid and which are not, so the entire process needs to be restarted.\n**\n** It is assumed that the mutex associated with the BtShared object\n** corresponding to the source database is held when this function is\n** called.\n*/\nSQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){\n  sqlite3_backup *p;                   /* Iterator variable */\n  for(p=pBackup; p; p=p->pNext){\n    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );\n    p->iNext = 1;\n  }\n}\n\n#ifndef SQLITE_OMIT_VACUUM\n/*\n** Copy the complete content of pBtFrom into pBtTo.  A transaction\n** must be active for both files.\n**\n** The size of file pTo may be reduced by this operation. If anything \n** goes wrong, the transaction on pTo is rolled back. If successful, the \n** transaction is committed before returning.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){\n  int rc;\n  sqlite3_file *pFd;              /* File descriptor for database pTo */\n  sqlite3_backup b;\n  sqlite3BtreeEnter(pTo);\n  sqlite3BtreeEnter(pFrom);\n\n  assert( sqlite3BtreeIsInTrans(pTo) );\n  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));\n  if( pFd->pMethods ){\n    i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);\n    rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);\n    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;\n    if( rc ) goto copy_finished;\n  }\n\n  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set\n  ** to 0. This is used by the implementations of sqlite3_backup_step()\n  ** and sqlite3_backup_finish() to detect that they are being called\n  ** from this function, not directly by the user.\n  */\n  memset(&b, 0, sizeof(b));\n  b.pSrcDb = pFrom->db;\n  b.pSrc = pFrom;\n  b.pDest = pTo;\n  b.iNext = 1;\n\n  /* 0x7FFFFFFF is the hard limit for the number of pages in a database\n  ** file. By passing this as the number of pages to copy to\n  ** sqlite3_backup_step(), we can guarantee that the copy finishes \n  ** within a single call (unless an error occurs). The assert() statement\n  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE \n  ** or an error code.  */\n  sqlite3_backup_step(&b, 0x7FFFFFFF);\n  assert( b.rc!=SQLITE_OK );\n\n  rc = sqlite3_backup_finish(&b);\n  if( rc==SQLITE_OK ){\n    pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;\n  }else{\n    sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));\n  }\n\n  assert( sqlite3BtreeIsInTrans(pTo)==0 );\ncopy_finished:\n  sqlite3BtreeLeave(pFrom);\n  sqlite3BtreeLeave(pTo);\n  return rc;\n}\n#endif /* SQLITE_OMIT_VACUUM */\n\n/************** End of backup.c **********************************************/\n/************** Begin file vdbemem.c *****************************************/\n/*\n** 2004 May 26\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains code use to manipulate \"Mem\" structure.  A \"Mem\"\n** stores a single value in the VDBE.  Mem is an opaque structure visible\n** only within the VDBE.  Interface routines refer to a Mem using the\n** name sqlite_value\n*/\n/* #include \"sqliteInt.h\" */\n/* #include \"vdbeInt.h\" */\n\n/* True if X is a power of two.  0 is considered a power of two here.\n** In other words, return true if X has at most one bit set.\n*/\n#define ISPOWEROF2(X)  (((X)&((X)-1))==0)\n\n#ifdef SQLITE_DEBUG\n/*\n** Check invariants on a Mem object.\n**\n** This routine is intended for use inside of assert() statements, like\n** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );\n*/\nSQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){\n  /* If MEM_Dyn is set then Mem.xDel!=0.  \n  ** Mem.xDel might not be initialized if MEM_Dyn is clear.\n  */\n  assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );\n\n  /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we\n  ** ensure that if Mem.szMalloc>0 then it is safe to do\n  ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.\n  ** That saves a few cycles in inner loops. */\n  assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );\n\n  /* Cannot have more than one of MEM_Int, MEM_Real, or MEM_IntReal */\n  assert( ISPOWEROF2(p->flags & (MEM_Int|MEM_Real|MEM_IntReal)) );\n\n  if( p->flags & MEM_Null ){\n    /* Cannot be both MEM_Null and some other type */\n    assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob|MEM_Agg))==0 );\n\n    /* If MEM_Null is set, then either the value is a pure NULL (the usual\n    ** case) or it is a pointer set using sqlite3_bind_pointer() or\n    ** sqlite3_result_pointer().  If a pointer, then MEM_Term must also be\n    ** set.\n    */\n    if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){\n      /* This is a pointer type.  There may be a flag to indicate what to\n      ** do with the pointer. */\n      assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +\n              ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +\n              ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );\n\n      /* No other bits set */\n      assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype|MEM_FromBind\n                           |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );\n    }else{\n      /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,\n      ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */\n    }\n  }else{\n    /* The MEM_Cleared bit is only allowed on NULLs */\n    assert( (p->flags & MEM_Cleared)==0 );\n  }\n\n  /* The szMalloc field holds the correct memory allocation size */\n  assert( p->szMalloc==0\n       || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );\n\n  /* If p holds a string or blob, the Mem.z must point to exactly\n  ** one of the following:\n  **\n  **   (1) Memory in Mem.zMalloc and managed by the Mem object\n  **   (2) Memory to be freed using Mem.xDel\n  **   (3) An ephemeral string or blob\n  **   (4) A static string or blob\n  */\n  if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){\n    assert( \n      ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +\n      ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +\n      ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +\n      ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1\n    );\n  }\n  return 1;\n}\n#endif\n\n/*\n** Render a Mem object which is one of MEM_Int, MEM_Real, or MEM_IntReal\n** into a buffer.\n*/\nstatic void vdbeMemRenderNum(int sz, char *zBuf, Mem *p){\n  StrAccum acc;\n  assert( p->flags & (MEM_Int|MEM_Real|MEM_IntReal) );\n  sqlite3StrAccumInit(&acc, 0, zBuf, sz, 0);\n  if( p->flags & MEM_Int ){\n    sqlite3_str_appendf(&acc, \"%lld\", p->u.i);\n  }else if( p->flags & MEM_IntReal ){\n    sqlite3_str_appendf(&acc, \"%!.15g\", (double)p->u.i);\n  }else{\n    sqlite3_str_appendf(&acc, \"%!.15g\", p->u.r);\n  }\n  assert( acc.zText==zBuf && acc.mxAlloc<=0 );\n  zBuf[acc.nChar] = 0; /* Fast version of sqlite3StrAccumFinish(&acc) */\n}\n\n#ifdef SQLITE_DEBUG\n/*\n** Validity checks on pMem.  pMem holds a string.\n**\n** (1) Check that string value of pMem agrees with its integer or real value.\n** (2) Check that the string is correctly zero terminated\n**\n** A single int or real value always converts to the same strings.  But\n** many different strings can be converted into the same int or real.\n** If a table contains a numeric value and an index is based on the\n** corresponding string value, then it is important that the string be\n** derived from the numeric value, not the other way around, to ensure\n** that the index and table are consistent.  See ticket\n** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for\n** an example.\n**\n** This routine looks at pMem to verify that if it has both a numeric\n** representation and a string representation then the string rep has\n** been derived from the numeric and not the other way around.  It returns\n** true if everything is ok and false if there is a problem.\n**\n** This routine is for use inside of assert() statements only.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemValidStrRep(Mem *p){\n  char zBuf[100];\n  char *z;\n  int i, j, incr;\n  if( (p->flags & MEM_Str)==0 ) return 1;\n  if( p->flags & MEM_Term ){\n    /* Insure that the string is properly zero-terminated.  Pay particular\n    ** attention to the case where p->n is odd */\n    if( p->szMalloc>0 && p->z==p->zMalloc ){\n      assert( p->enc==SQLITE_UTF8 || p->szMalloc >= ((p->n+1)&~1)+2 );\n      assert( p->enc!=SQLITE_UTF8 || p->szMalloc >= p->n+1 );\n    }\n    assert( p->z[p->n]==0 );\n    assert( p->enc==SQLITE_UTF8 || p->z[(p->n+1)&~1]==0 );\n    assert( p->enc==SQLITE_UTF8 || p->z[((p->n+1)&~1)+1]==0 );\n  }\n  if( (p->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ) return 1;\n  vdbeMemRenderNum(sizeof(zBuf), zBuf, p);\n  z = p->z;\n  i = j = 0;\n  incr = 1;\n  if( p->enc!=SQLITE_UTF8 ){\n    incr = 2;\n    if( p->enc==SQLITE_UTF16BE ) z++;\n  }\n  while( zBuf[j] ){\n    if( zBuf[j++]!=z[i] ) return 0;\n    i += incr;\n  }\n  return 1;\n}\n#endif /* SQLITE_DEBUG */\n\n/*\n** If pMem is an object with a valid string representation, this routine\n** ensures the internal encoding for the string representation is\n** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.\n**\n** If pMem is not a string object, or the encoding of the string\n** representation is already stored using the requested encoding, then this\n** routine is a no-op.\n**\n** SQLITE_OK is returned if the conversion is successful (or not required).\n** SQLITE_NOMEM may be returned if a malloc() fails during conversion\n** between formats.\n*/\nSQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){\n#ifndef SQLITE_OMIT_UTF16\n  int rc;\n#endif\n  assert( !sqlite3VdbeMemIsRowSet(pMem) );\n  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE\n           || desiredEnc==SQLITE_UTF16BE );\n  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){\n    return SQLITE_OK;\n  }\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n#ifdef SQLITE_OMIT_UTF16\n  return SQLITE_ERROR;\n#else\n\n  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,\n  ** then the encoding of the value may not have changed.\n  */\n  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);\n  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);\n  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);\n  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);\n  return rc;\n#endif\n}\n\n/*\n** Make sure pMem->z points to a writable allocation of at least n bytes.\n**\n** If the bPreserve argument is true, then copy of the content of\n** pMem->z into the new allocation.  pMem must be either a string or\n** blob if bPreserve is true.  If bPreserve is false, any prior content\n** in pMem->z is discarded.\n*/\nSQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){\n  assert( sqlite3VdbeCheckMemInvariants(pMem) );\n  assert( !sqlite3VdbeMemIsRowSet(pMem) );\n  testcase( pMem->db==0 );\n\n  /* If the bPreserve flag is set to true, then the memory cell must already\n  ** contain a valid string or blob value.  */\n  assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );\n  testcase( bPreserve && pMem->z==0 );\n\n  assert( pMem->szMalloc==0\n       || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );\n  if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){\n    if( pMem->db ){\n      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);\n    }else{\n      pMem->zMalloc = sqlite3Realloc(pMem->z, n);\n      if( pMem->zMalloc==0 ) sqlite3_free(pMem->z);\n      pMem->z = pMem->zMalloc;\n    }\n    bPreserve = 0;\n  }else{\n    if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);\n    pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);\n  }\n  if( pMem->zMalloc==0 ){\n    sqlite3VdbeMemSetNull(pMem);\n    pMem->z = 0;\n    pMem->szMalloc = 0;\n    return SQLITE_NOMEM_BKPT;\n  }else{\n    pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);\n  }\n\n  if( bPreserve && pMem->z ){\n    assert( pMem->z!=pMem->zMalloc );\n    memcpy(pMem->zMalloc, pMem->z, pMem->n);\n  }\n  if( (pMem->flags&MEM_Dyn)!=0 ){\n    assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );\n    pMem->xDel((void *)(pMem->z));\n  }\n\n  pMem->z = pMem->zMalloc;\n  pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);\n  return SQLITE_OK;\n}\n\n/*\n** Change the pMem->zMalloc allocation to be at least szNew bytes.\n** If pMem->zMalloc already meets or exceeds the requested size, this\n** routine is a no-op.\n**\n** Any prior string or blob content in the pMem object may be discarded.\n** The pMem->xDel destructor is called, if it exists.  Though MEM_Str\n** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, MEM_IntReal,\n** and MEM_Null values are preserved.\n**\n** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)\n** if unable to complete the resizing.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){\n  assert( CORRUPT_DB || szNew>0 );\n  assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );\n  if( pMem->szMalloc<szNew ){\n    return sqlite3VdbeMemGrow(pMem, szNew, 0);\n  }\n  assert( (pMem->flags & MEM_Dyn)==0 );\n  pMem->z = pMem->zMalloc;\n  pMem->flags &= (MEM_Null|MEM_Int|MEM_Real|MEM_IntReal);\n  return SQLITE_OK;\n}\n\n/*\n** It is already known that pMem contains an unterminated string.\n** Add the zero terminator.\n**\n** Three bytes of zero are added.  In this way, there is guaranteed\n** to be a double-zero byte at an even byte boundary in order to\n** terminate a UTF16 string, even if the initial size of the buffer\n** is an odd number of bytes.\n*/\nstatic SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){\n  if( sqlite3VdbeMemGrow(pMem, pMem->n+3, 1) ){\n    return SQLITE_NOMEM_BKPT;\n  }\n  pMem->z[pMem->n] = 0;\n  pMem->z[pMem->n+1] = 0;\n  pMem->z[pMem->n+2] = 0;\n  pMem->flags |= MEM_Term;\n  return SQLITE_OK;\n}\n\n/*\n** Change pMem so that its MEM_Str or MEM_Blob value is stored in\n** MEM.zMalloc, where it can be safely written.\n**\n** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( !sqlite3VdbeMemIsRowSet(pMem) );\n  if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){\n    if( ExpandBlob(pMem) ) return SQLITE_NOMEM;\n    if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){\n      int rc = vdbeMemAddTerminator(pMem);\n      if( rc ) return rc;\n    }\n  }\n  pMem->flags &= ~MEM_Ephem;\n#ifdef SQLITE_DEBUG\n  pMem->pScopyFrom = 0;\n#endif\n\n  return SQLITE_OK;\n}\n\n/*\n** If the given Mem* has a zero-filled tail, turn it into an ordinary\n** blob stored in dynamically allocated space.\n*/\n#ifndef SQLITE_OMIT_INCRBLOB\nSQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){\n  int nByte;\n  assert( pMem->flags & MEM_Zero );\n  assert( (pMem->flags&MEM_Blob)!=0 || MemNullNochng(pMem) );\n  testcase( sqlite3_value_nochange(pMem) );\n  assert( !sqlite3VdbeMemIsRowSet(pMem) );\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n\n  /* Set nByte to the number of bytes required to store the expanded blob. */\n  nByte = pMem->n + pMem->u.nZero;\n  if( nByte<=0 ){\n    if( (pMem->flags & MEM_Blob)==0 ) return SQLITE_OK;\n    nByte = 1;\n  }\n  if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){\n    return SQLITE_NOMEM_BKPT;\n  }\n\n  memset(&pMem->z[pMem->n], 0, pMem->u.nZero);\n  pMem->n += pMem->u.nZero;\n  pMem->flags &= ~(MEM_Zero|MEM_Term);\n  return SQLITE_OK;\n}\n#endif\n\n/*\n** Make sure the given Mem is \\u0000 terminated.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );\n  testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );\n  if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){\n    return SQLITE_OK;   /* Nothing to do */\n  }else{\n    return vdbeMemAddTerminator(pMem);\n  }\n}\n\n/*\n** Add MEM_Str to the set of representations for the given Mem.  This\n** routine is only called if pMem is a number of some kind, not a NULL\n** or a BLOB.\n**\n** Existing representations MEM_Int, MEM_Real, or MEM_IntReal are invalidated\n** if bForce is true but are retained if bForce is false.\n**\n** A MEM_Null value will never be passed to this function. This function is\n** used for converting values to text for returning to the user (i.e. via\n** sqlite3_value_text()), or for ensuring that values to be used as btree\n** keys are strings. In the former case a NULL pointer is returned the\n** user and the latter is an internal programming error.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){\n  const int nByte = 32;\n\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( !(pMem->flags&MEM_Zero) );\n  assert( !(pMem->flags&(MEM_Str|MEM_Blob)) );\n  assert( pMem->flags&(MEM_Int|MEM_Real|MEM_IntReal) );\n  assert( !sqlite3VdbeMemIsRowSet(pMem) );\n  assert( EIGHT_BYTE_ALIGNMENT(pMem) );\n\n\n  if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){\n    pMem->enc = 0;\n    return SQLITE_NOMEM_BKPT;\n  }\n\n  vdbeMemRenderNum(nByte, pMem->z, pMem);\n  assert( pMem->z!=0 );\n  pMem->n = sqlite3Strlen30NN(pMem->z);\n  pMem->enc = SQLITE_UTF8;\n  pMem->flags |= MEM_Str|MEM_Term;\n  if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);\n  sqlite3VdbeChangeEncoding(pMem, enc);\n  return SQLITE_OK;\n}\n\n/*\n** Memory cell pMem contains the context of an aggregate function.\n** This routine calls the finalize method for that function.  The\n** result of the aggregate is stored back into pMem.\n**\n** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK\n** otherwise.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){\n  sqlite3_context ctx;\n  Mem t;\n  assert( pFunc!=0 );\n  assert( pFunc->xFinalize!=0 );\n  assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  memset(&ctx, 0, sizeof(ctx));\n  memset(&t, 0, sizeof(t));\n  t.flags = MEM_Null;\n  t.db = pMem->db;\n  ctx.pOut = &t;\n  ctx.pMem = pMem;\n  ctx.pFunc = pFunc;\n  pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */\n  assert( (pMem->flags & MEM_Dyn)==0 );\n  if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);\n  memcpy(pMem, &t, sizeof(t));\n  return ctx.isError;\n}\n\n/*\n** Memory cell pAccum contains the context of an aggregate function.\n** This routine calls the xValue method for that function and stores\n** the results in memory cell pMem.\n**\n** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK \n** otherwise.\n*/\n#ifndef SQLITE_OMIT_WINDOWFUNC\nSQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem *pAccum, Mem *pOut, FuncDef *pFunc){\n  sqlite3_context ctx;\n  assert( pFunc!=0 );\n  assert( pFunc->xValue!=0 );\n  assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef );\n  assert( pAccum->db==0 || sqlite3_mutex_held(pAccum->db->mutex) );\n  memset(&ctx, 0, sizeof(ctx));\n  sqlite3VdbeMemSetNull(pOut);\n  ctx.pOut = pOut;\n  ctx.pMem = pAccum;\n  ctx.pFunc = pFunc;\n  pFunc->xValue(&ctx);\n  return ctx.isError;\n}\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n\n/*\n** If the memory cell contains a value that must be freed by\n** invoking the external callback in Mem.xDel, then this routine\n** will free that value.  It also sets Mem.flags to MEM_Null.\n**\n** This is a helper routine for sqlite3VdbeMemSetNull() and\n** for sqlite3VdbeMemRelease().  Use those other routines as the\n** entry point for releasing Mem resources.\n*/\nstatic SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){\n  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );\n  assert( VdbeMemDynamic(p) );\n  if( p->flags&MEM_Agg ){\n    sqlite3VdbeMemFinalize(p, p->u.pDef);\n    assert( (p->flags & MEM_Agg)==0 );\n    testcase( p->flags & MEM_Dyn );\n  }\n  if( p->flags&MEM_Dyn ){\n    assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );\n    p->xDel((void *)p->z);\n  }\n  p->flags = MEM_Null;\n}\n\n/*\n** Release memory held by the Mem p, both external memory cleared\n** by p->xDel and memory in p->zMalloc.\n**\n** This is a helper routine invoked by sqlite3VdbeMemRelease() in\n** the unusual case where there really is memory in p that needs\n** to be freed.\n*/\nstatic SQLITE_NOINLINE void vdbeMemClear(Mem *p){\n  if( VdbeMemDynamic(p) ){\n    vdbeMemClearExternAndSetNull(p);\n  }\n  if( p->szMalloc ){\n    sqlite3DbFreeNN(p->db, p->zMalloc);\n    p->szMalloc = 0;\n  }\n  p->z = 0;\n}\n\n/*\n** Release any memory resources held by the Mem.  Both the memory that is\n** free by Mem.xDel and the Mem.zMalloc allocation are freed.\n**\n** Use this routine prior to clean up prior to abandoning a Mem, or to\n** reset a Mem back to its minimum memory utilization.\n**\n** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space\n** prior to inserting new content into the Mem.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){\n  assert( sqlite3VdbeCheckMemInvariants(p) );\n  if( VdbeMemDynamic(p) || p->szMalloc ){\n    vdbeMemClear(p);\n  }\n}\n\n/*\n** Convert a 64-bit IEEE double into a 64-bit signed integer.\n** If the double is out of range of a 64-bit signed integer then\n** return the closest available 64-bit signed integer.\n*/\nstatic SQLITE_NOINLINE i64 doubleToInt64(double r){\n#ifdef SQLITE_OMIT_FLOATING_POINT\n  /* When floating-point is omitted, double and int64 are the same thing */\n  return r;\n#else\n  /*\n  ** Many compilers we encounter do not define constants for the\n  ** minimum and maximum 64-bit integers, or they define them\n  ** inconsistently.  And many do not understand the \"LL\" notation.\n  ** So we define our own static constants here using nothing\n  ** larger than a 32-bit integer constant.\n  */\n  static const i64 maxInt = LARGEST_INT64;\n  static const i64 minInt = SMALLEST_INT64;\n\n  if( r<=(double)minInt ){\n    return minInt;\n  }else if( r>=(double)maxInt ){\n    return maxInt;\n  }else{\n    return (i64)r;\n  }\n#endif\n}\n\n/*\n** Return some kind of integer value which is the best we can do\n** at representing the value that *pMem describes as an integer.\n** If pMem is an integer, then the value is exact.  If pMem is\n** a floating-point then the value returned is the integer part.\n** If pMem is a string or blob, then we make an attempt to convert\n** it into an integer and return that.  If pMem represents an\n** an SQL-NULL value, return 0.\n**\n** If pMem represents a string value, its encoding might be changed.\n*/\nstatic SQLITE_NOINLINE i64 memIntValue(Mem *pMem){\n  i64 value = 0;\n  sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);\n  return value;\n}\nSQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){\n  int flags;\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( EIGHT_BYTE_ALIGNMENT(pMem) );\n  flags = pMem->flags;\n  if( flags & (MEM_Int|MEM_IntReal) ){\n    testcase( flags & MEM_IntReal );\n    return pMem->u.i;\n  }else if( flags & MEM_Real ){\n    return doubleToInt64(pMem->u.r);\n  }else if( (flags & (MEM_Str|MEM_Blob))!=0 && pMem->z!=0 ){\n    return memIntValue(pMem);\n  }else{\n    return 0;\n  }\n}\n\n/*\n** Return the best representation of pMem that we can get into a\n** double.  If pMem is already a double or an integer, return its\n** value.  If it is a string or blob, try to convert it to a double.\n** If it is a NULL, return 0.0.\n*/\nstatic SQLITE_NOINLINE double memRealValue(Mem *pMem){\n  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */\n  double val = (double)0;\n  sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);\n  return val;\n}\nSQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( EIGHT_BYTE_ALIGNMENT(pMem) );\n  if( pMem->flags & MEM_Real ){\n    return pMem->u.r;\n  }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){\n    testcase( pMem->flags & MEM_IntReal );\n    return (double)pMem->u.i;\n  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){\n    return memRealValue(pMem);\n  }else{\n    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */\n    return (double)0;\n  }\n}\n\n/*\n** Return 1 if pMem represents true, and return 0 if pMem represents false.\n** Return the value ifNull if pMem is NULL.  \n*/\nSQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){\n  testcase( pMem->flags & MEM_IntReal );\n  if( pMem->flags & (MEM_Int|MEM_IntReal) ) return pMem->u.i!=0;\n  if( pMem->flags & MEM_Null ) return ifNull;\n  return sqlite3VdbeRealValue(pMem)!=0.0;\n}\n\n/*\n** The MEM structure is already a MEM_Real.  Try to also make it a\n** MEM_Int if we can.\n*/\nSQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){\n  i64 ix;\n  assert( pMem->flags & MEM_Real );\n  assert( !sqlite3VdbeMemIsRowSet(pMem) );\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( EIGHT_BYTE_ALIGNMENT(pMem) );\n\n  ix = doubleToInt64(pMem->u.r);\n\n  /* Only mark the value as an integer if\n  **\n  **    (1) the round-trip conversion real->int->real is a no-op, and\n  **    (2) The integer is neither the largest nor the smallest\n  **        possible integer (ticket #3922)\n  **\n  ** The second and third terms in the following conditional enforces\n  ** the second condition under the assumption that addition overflow causes\n  ** values to wrap around.\n  */\n  if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){\n    pMem->u.i = ix;\n    MemSetTypeFlag(pMem, MEM_Int);\n  }\n}\n\n/*\n** Convert pMem to type integer.  Invalidate any prior representations.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( !sqlite3VdbeMemIsRowSet(pMem) );\n  assert( EIGHT_BYTE_ALIGNMENT(pMem) );\n\n  pMem->u.i = sqlite3VdbeIntValue(pMem);\n  MemSetTypeFlag(pMem, MEM_Int);\n  return SQLITE_OK;\n}\n\n/*\n** Convert pMem so that it is of type MEM_Real.\n** Invalidate any prior representations.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( EIGHT_BYTE_ALIGNMENT(pMem) );\n\n  pMem->u.r = sqlite3VdbeRealValue(pMem);\n  MemSetTypeFlag(pMem, MEM_Real);\n  return SQLITE_OK;\n}\n\n/* Compare a floating point value to an integer.  Return true if the two\n** values are the same within the precision of the floating point value.\n**\n** This function assumes that i was obtained by assignment from r1.\n**\n** For some versions of GCC on 32-bit machines, if you do the more obvious\n** comparison of \"r1==(double)i\" you sometimes get an answer of false even\n** though the r1 and (double)i values are bit-for-bit the same.\n*/\nSQLITE_PRIVATE int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){\n  double r2 = (double)i;\n  return r1==0.0\n      || (memcmp(&r1, &r2, sizeof(r1))==0\n          && i >= -2251799813685248LL && i < 2251799813685248LL);\n}\n\n/*\n** Convert pMem so that it has type MEM_Real or MEM_Int.\n** Invalidate any prior representations.\n**\n** Every effort is made to force the conversion, even if the input\n** is a string that does not look completely like a number.  Convert\n** as much of the string as we can and ignore the rest.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){\n  testcase( pMem->flags & MEM_Int );\n  testcase( pMem->flags & MEM_Real );\n  testcase( pMem->flags & MEM_IntReal );\n  testcase( pMem->flags & MEM_Null );\n  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))==0 ){\n    int rc;\n    sqlite3_int64 ix;\n    assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );\n    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n    rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);\n    if( ((rc==0 || rc==1) && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1)\n     || sqlite3RealSameAsInt(pMem->u.r, (ix = (i64)pMem->u.r))\n    ){\n      pMem->u.i = ix;\n      MemSetTypeFlag(pMem, MEM_Int);\n    }else{\n      MemSetTypeFlag(pMem, MEM_Real);\n    }\n  }\n  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))!=0 );\n  pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);\n  return SQLITE_OK;\n}\n\n/*\n** Cast the datatype of the value in pMem according to the affinity\n** \"aff\".  Casting is different from applying affinity in that a cast\n** is forced.  In other words, the value is converted into the desired\n** affinity even if that results in loss of data.  This routine is\n** used (for example) to implement the SQL \"cast()\" operator.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){\n  if( pMem->flags & MEM_Null ) return SQLITE_OK;\n  switch( aff ){\n    case SQLITE_AFF_BLOB: {   /* Really a cast to BLOB */\n      if( (pMem->flags & MEM_Blob)==0 ){\n        sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);\n        assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );\n        if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);\n      }else{\n        pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);\n      }\n      break;\n    }\n    case SQLITE_AFF_NUMERIC: {\n      sqlite3VdbeMemNumerify(pMem);\n      break;\n    }\n    case SQLITE_AFF_INTEGER: {\n      sqlite3VdbeMemIntegerify(pMem);\n      break;\n    }\n    case SQLITE_AFF_REAL: {\n      sqlite3VdbeMemRealify(pMem);\n      break;\n    }\n    default: {\n      assert( aff==SQLITE_AFF_TEXT );\n      assert( MEM_Str==(MEM_Blob>>3) );\n      pMem->flags |= (pMem->flags&MEM_Blob)>>3;\n      sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);\n      assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );\n      pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal|MEM_Blob|MEM_Zero);\n      return sqlite3VdbeChangeEncoding(pMem, encoding);\n    }\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Initialize bulk memory to be a consistent Mem object.\n**\n** The minimum amount of initialization feasible is performed.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){\n  assert( (flags & ~MEM_TypeMask)==0 );\n  pMem->flags = flags;\n  pMem->db = db;\n  pMem->szMalloc = 0;\n}\n\n\n/*\n** Delete any previous value and set the value stored in *pMem to NULL.\n**\n** This routine calls the Mem.xDel destructor to dispose of values that\n** require the destructor.  But it preserves the Mem.zMalloc memory allocation.\n** To free all resources, use sqlite3VdbeMemRelease(), which both calls this\n** routine to invoke the destructor and deallocates Mem.zMalloc.\n**\n** Use this routine to reset the Mem prior to insert a new value.\n**\n** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){\n  if( VdbeMemDynamic(pMem) ){\n    vdbeMemClearExternAndSetNull(pMem);\n  }else{\n    pMem->flags = MEM_Null;\n  }\n}\nSQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){\n  sqlite3VdbeMemSetNull((Mem*)p); \n}\n\n/*\n** Delete any previous value and set the value to be a BLOB of length\n** n containing all zeros.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){\n  sqlite3VdbeMemRelease(pMem);\n  pMem->flags = MEM_Blob|MEM_Zero;\n  pMem->n = 0;\n  if( n<0 ) n = 0;\n  pMem->u.nZero = n;\n  pMem->enc = SQLITE_UTF8;\n  pMem->z = 0;\n}\n\n/*\n** The pMem is known to contain content that needs to be destroyed prior\n** to a value change.  So invoke the destructor, then set the value to\n** a 64-bit integer.\n*/\nstatic SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){\n  sqlite3VdbeMemSetNull(pMem);\n  pMem->u.i = val;\n  pMem->flags = MEM_Int;\n}\n\n/*\n** Delete any previous value and set the value stored in *pMem to val,\n** manifest type INTEGER.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){\n  if( VdbeMemDynamic(pMem) ){\n    vdbeReleaseAndSetInt64(pMem, val);\n  }else{\n    pMem->u.i = val;\n    pMem->flags = MEM_Int;\n  }\n}\n\n/* A no-op destructor */\nSQLITE_PRIVATE void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }\n\n/*\n** Set the value stored in *pMem should already be a NULL.\n** Also store a pointer to go with it.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemSetPointer(\n  Mem *pMem,\n  void *pPtr,\n  const char *zPType,\n  void (*xDestructor)(void*)\n){\n  assert( pMem->flags==MEM_Null );\n  pMem->u.zPType = zPType ? zPType : \"\";\n  pMem->z = pPtr;\n  pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;\n  pMem->eSubtype = 'p';\n  pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;\n}\n\n#ifndef SQLITE_OMIT_FLOATING_POINT\n/*\n** Delete any previous value and set the value stored in *pMem to val,\n** manifest type REAL.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){\n  sqlite3VdbeMemSetNull(pMem);\n  if( !sqlite3IsNaN(val) ){\n    pMem->u.r = val;\n    pMem->flags = MEM_Real;\n  }\n}\n#endif\n\n#ifdef SQLITE_DEBUG\n/*\n** Return true if the Mem holds a RowSet object.  This routine is intended\n** for use inside of assert() statements.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem *pMem){\n  return (pMem->flags&(MEM_Blob|MEM_Dyn))==(MEM_Blob|MEM_Dyn)\n         && pMem->xDel==sqlite3RowSetDelete;\n}\n#endif\n\n/*\n** Delete any previous value and set the value of pMem to be an\n** empty boolean index.\n**\n** Return SQLITE_OK on success and SQLITE_NOMEM if a memory allocation\n** error occurs.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem *pMem){\n  sqlite3 *db = pMem->db;\n  RowSet *p;\n  assert( db!=0 );\n  assert( !sqlite3VdbeMemIsRowSet(pMem) );\n  sqlite3VdbeMemRelease(pMem);\n  p = sqlite3RowSetInit(db);\n  if( p==0 ) return SQLITE_NOMEM;\n  pMem->z = (char*)p;\n  pMem->flags = MEM_Blob|MEM_Dyn;\n  pMem->xDel = sqlite3RowSetDelete;\n  return SQLITE_OK;\n}\n\n/*\n** Return true if the Mem object contains a TEXT or BLOB that is\n** too large - whose size exceeds SQLITE_MAX_LENGTH.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){\n  assert( p->db!=0 );\n  if( p->flags & (MEM_Str|MEM_Blob) ){\n    int n = p->n;\n    if( p->flags & MEM_Zero ){\n      n += p->u.nZero;\n    }\n    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];\n  }\n  return 0; \n}\n\n#ifdef SQLITE_DEBUG\n/*\n** This routine prepares a memory cell for modification by breaking\n** its link to a shallow copy and by marking any current shallow\n** copies of this cell as invalid.\n**\n** This is used for testing and debugging only - to help ensure that shallow\n** copies (created by OP_SCopy) are not misused.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){\n  int i;\n  Mem *pX;\n  for(i=1, pX=pVdbe->aMem+1; i<pVdbe->nMem; i++, pX++){\n    if( pX->pScopyFrom==pMem ){\n      u16 mFlags;\n      if( pVdbe->db->flags & SQLITE_VdbeTrace ){\n        sqlite3DebugPrintf(\"Invalidate R[%d] due to change in R[%d]\\n\",\n          (int)(pX - pVdbe->aMem), (int)(pMem - pVdbe->aMem));\n      }\n      /* If pX is marked as a shallow copy of pMem, then try to verify that\n      ** no significant changes have been made to pX since the OP_SCopy.\n      ** A significant change would indicated a missed call to this\n      ** function for pX.  Minor changes, such as adding or removing a\n      ** dual type, are allowed, as long as the underlying value is the\n      ** same. */\n      mFlags = pMem->flags & pX->flags & pX->mScopyFlags;\n      assert( (mFlags&(MEM_Int|MEM_IntReal))==0 || pMem->u.i==pX->u.i );\n      \n      /* pMem is the register that is changing.  But also mark pX as\n      ** undefined so that we can quickly detect the shallow-copy error */\n      pX->flags = MEM_Undefined;\n      pX->pScopyFrom = 0;\n    }\n  }\n  pMem->pScopyFrom = 0;\n}\n#endif /* SQLITE_DEBUG */\n\n/*\n** Make an shallow copy of pFrom into pTo.  Prior contents of\n** pTo are freed.  The pFrom->z field is not duplicated.  If\n** pFrom->z is used, then pTo->z points to the same thing as pFrom->z\n** and flags gets srcType (either MEM_Ephem or MEM_Static).\n*/\nstatic SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){\n  vdbeMemClearExternAndSetNull(pTo);\n  assert( !VdbeMemDynamic(pTo) );\n  sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);\n}\nSQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){\n  assert( !sqlite3VdbeMemIsRowSet(pFrom) );\n  assert( pTo->db==pFrom->db );\n  if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }\n  memcpy(pTo, pFrom, MEMCELLSIZE);\n  if( (pFrom->flags&MEM_Static)==0 ){\n    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);\n    assert( srcType==MEM_Ephem || srcType==MEM_Static );\n    pTo->flags |= srcType;\n  }\n}\n\n/*\n** Make a full copy of pFrom into pTo.  Prior contents of pTo are\n** freed before the copy is made.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){\n  int rc = SQLITE_OK;\n\n  assert( !sqlite3VdbeMemIsRowSet(pFrom) );\n  if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);\n  memcpy(pTo, pFrom, MEMCELLSIZE);\n  pTo->flags &= ~MEM_Dyn;\n  if( pTo->flags&(MEM_Str|MEM_Blob) ){\n    if( 0==(pFrom->flags&MEM_Static) ){\n      pTo->flags |= MEM_Ephem;\n      rc = sqlite3VdbeMemMakeWriteable(pTo);\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Transfer the contents of pFrom to pTo. Any existing value in pTo is\n** freed. If pFrom contains ephemeral data, a copy is made.\n**\n** pFrom contains an SQL NULL when this routine returns.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){\n  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );\n  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );\n  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );\n\n  sqlite3VdbeMemRelease(pTo);\n  memcpy(pTo, pFrom, sizeof(Mem));\n  pFrom->flags = MEM_Null;\n  pFrom->szMalloc = 0;\n}\n\n/*\n** Change the value of a Mem to be a string or a BLOB.\n**\n** The memory management strategy depends on the value of the xDel\n** parameter. If the value passed is SQLITE_TRANSIENT, then the \n** string is copied into a (possibly existing) buffer managed by the \n** Mem structure. Otherwise, any existing buffer is freed and the\n** pointer copied.\n**\n** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH\n** size limit) then no memory allocation occurs.  If the string can be\n** stored without allocating memory, then it is.  If a memory allocation\n** is required to store the string, then value of pMem is unchanged.  In\n** either case, SQLITE_TOOBIG is returned.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemSetStr(\n  Mem *pMem,          /* Memory cell to set to string value */\n  const char *z,      /* String pointer */\n  int n,              /* Bytes in string, or negative */\n  u8 enc,             /* Encoding of z.  0 for BLOBs */\n  void (*xDel)(void*) /* Destructor function */\n){\n  int nByte = n;      /* New value for pMem->n */\n  int iLimit;         /* Maximum allowed string or blob size */\n  u16 flags = 0;      /* New value for pMem->flags */\n\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( !sqlite3VdbeMemIsRowSet(pMem) );\n\n  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */\n  if( !z ){\n    sqlite3VdbeMemSetNull(pMem);\n    return SQLITE_OK;\n  }\n\n  if( pMem->db ){\n    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];\n  }else{\n    iLimit = SQLITE_MAX_LENGTH;\n  }\n  flags = (enc==0?MEM_Blob:MEM_Str);\n  if( nByte<0 ){\n    assert( enc!=0 );\n    if( enc==SQLITE_UTF8 ){\n      nByte = 0x7fffffff & (int)strlen(z);\n    }else{\n      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}\n    }\n    flags |= MEM_Term;\n  }\n\n  /* The following block sets the new values of Mem.z and Mem.xDel. It\n  ** also sets a flag in local variable \"flags\" to indicate the memory\n  ** management (one of MEM_Dyn or MEM_Static).\n  */\n  if( xDel==SQLITE_TRANSIENT ){\n    u32 nAlloc = nByte;\n    if( flags&MEM_Term ){\n      nAlloc += (enc==SQLITE_UTF8?1:2);\n    }\n    if( nByte>iLimit ){\n      return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG);\n    }\n    testcase( nAlloc==0 );\n    testcase( nAlloc==31 );\n    testcase( nAlloc==32 );\n    if( sqlite3VdbeMemClearAndResize(pMem, (int)MAX(nAlloc,32)) ){\n      return SQLITE_NOMEM_BKPT;\n    }\n    memcpy(pMem->z, z, nAlloc);\n  }else{\n    sqlite3VdbeMemRelease(pMem);\n    pMem->z = (char *)z;\n    if( xDel==SQLITE_DYNAMIC ){\n      pMem->zMalloc = pMem->z;\n      pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);\n    }else{\n      pMem->xDel = xDel;\n      flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);\n    }\n  }\n\n  pMem->n = nByte;\n  pMem->flags = flags;\n  if( enc ){\n    pMem->enc = enc;\n#ifdef SQLITE_ENABLE_SESSION\n  }else if( pMem->db==0 ){\n    pMem->enc = SQLITE_UTF8;\n#endif\n  }else{\n    assert( pMem->db!=0 );\n    pMem->enc = ENC(pMem->db);\n  }\n\n#ifndef SQLITE_OMIT_UTF16\n  if( enc>SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){\n    return SQLITE_NOMEM_BKPT;\n  }\n#endif\n\n  if( nByte>iLimit ){\n    return SQLITE_TOOBIG;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Move data out of a btree key or data field and into a Mem structure.\n** The data is payload from the entry that pCur is currently pointing\n** to.  offset and amt determine what portion of the data or key to retrieve.\n** The result is written into the pMem element.\n**\n** The pMem object must have been initialized.  This routine will use\n** pMem->zMalloc to hold the content from the btree, if possible.  New\n** pMem->zMalloc space will be allocated if necessary.  The calling routine\n** is responsible for making sure that the pMem object is eventually\n** destroyed.\n**\n** If this routine fails for any reason (malloc returns NULL or unable\n** to read from the disk) then the pMem is left in an inconsistent state.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemFromBtree(\n  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */\n  u32 offset,       /* Offset from the start of data to return bytes from. */\n  u32 amt,          /* Number of bytes to return. */\n  Mem *pMem         /* OUT: Return data in this Mem structure. */\n){\n  int rc;\n  pMem->flags = MEM_Null;\n  if( sqlite3BtreeMaxRecordSize(pCur)<offset+amt ){\n    return SQLITE_CORRUPT_BKPT;\n  }\n  if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){\n    rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);\n    if( rc==SQLITE_OK ){\n      pMem->z[amt] = 0;   /* Overrun area used when reading malformed records */\n      pMem->flags = MEM_Blob;\n      pMem->n = (int)amt;\n    }else{\n      sqlite3VdbeMemRelease(pMem);\n    }\n  }\n  return rc;\n}\nSQLITE_PRIVATE int sqlite3VdbeMemFromBtreeZeroOffset(\n  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */\n  u32 amt,          /* Number of bytes to return. */\n  Mem *pMem         /* OUT: Return data in this Mem structure. */\n){\n  u32 available = 0;  /* Number of bytes available on the local btree page */\n  int rc = SQLITE_OK; /* Return code */\n\n  assert( sqlite3BtreeCursorIsValid(pCur) );\n  assert( !VdbeMemDynamic(pMem) );\n\n  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() \n  ** that both the BtShared and database handle mutexes are held. */\n  assert( !sqlite3VdbeMemIsRowSet(pMem) );\n  pMem->z = (char *)sqlite3BtreePayloadFetch(pCur, &available);\n  assert( pMem->z!=0 );\n\n  if( amt<=available ){\n    pMem->flags = MEM_Blob|MEM_Ephem;\n    pMem->n = (int)amt;\n  }else{\n    rc = sqlite3VdbeMemFromBtree(pCur, 0, amt, pMem);\n  }\n\n  return rc;\n}\n\n/*\n** The pVal argument is known to be a value other than NULL.\n** Convert it into a string with encoding enc and return a pointer\n** to a zero-terminated version of that string.\n*/\nstatic SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){\n  assert( pVal!=0 );\n  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );\n  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );\n  assert( !sqlite3VdbeMemIsRowSet(pVal) );\n  assert( (pVal->flags & (MEM_Null))==0 );\n  if( pVal->flags & (MEM_Blob|MEM_Str) ){\n    if( ExpandBlob(pVal) ) return 0;\n    pVal->flags |= MEM_Str;\n    if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){\n      sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);\n    }\n    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){\n      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );\n      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){\n        return 0;\n      }\n    }\n    sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */\n  }else{\n    sqlite3VdbeMemStringify(pVal, enc, 0);\n    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );\n  }\n  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0\n              || pVal->db->mallocFailed );\n  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){\n    assert( sqlite3VdbeMemValidStrRep(pVal) );\n    return pVal->z;\n  }else{\n    return 0;\n  }\n}\n\n/* This function is only available internally, it is not part of the\n** external API. It works in a similar way to sqlite3_value_text(),\n** except the data returned is in the encoding specified by the second\n** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or\n** SQLITE_UTF8.\n**\n** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.\n** If that is the case, then the result must be aligned on an even byte\n** boundary.\n*/\nSQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){\n  if( !pVal ) return 0;\n  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );\n  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );\n  assert( !sqlite3VdbeMemIsRowSet(pVal) );\n  if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){\n    assert( sqlite3VdbeMemValidStrRep(pVal) );\n    return pVal->z;\n  }\n  if( pVal->flags&MEM_Null ){\n    return 0;\n  }\n  return valueToText(pVal, enc);\n}\n\n/*\n** Create a new sqlite3_value object.\n*/\nSQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){\n  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));\n  if( p ){\n    p->flags = MEM_Null;\n    p->db = db;\n  }\n  return p;\n}\n\n/*\n** Context object passed by sqlite3Stat4ProbeSetValue() through to \n** valueNew(). See comments above valueNew() for details.\n*/\nstruct ValueNewStat4Ctx {\n  Parse *pParse;\n  Index *pIdx;\n  UnpackedRecord **ppRec;\n  int iVal;\n};\n\n/*\n** Allocate and return a pointer to a new sqlite3_value object. If\n** the second argument to this function is NULL, the object is allocated\n** by calling sqlite3ValueNew().\n**\n** Otherwise, if the second argument is non-zero, then this function is \n** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not\n** already been allocated, allocate the UnpackedRecord structure that \n** that function will return to its caller here. Then return a pointer to\n** an sqlite3_value within the UnpackedRecord.a[] array.\n*/\nstatic sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){\n#ifdef SQLITE_ENABLE_STAT4\n  if( p ){\n    UnpackedRecord *pRec = p->ppRec[0];\n\n    if( pRec==0 ){\n      Index *pIdx = p->pIdx;      /* Index being probed */\n      int nByte;                  /* Bytes of space to allocate */\n      int i;                      /* Counter variable */\n      int nCol = pIdx->nColumn;   /* Number of index columns including rowid */\n  \n      nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));\n      pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);\n      if( pRec ){\n        pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);\n        if( pRec->pKeyInfo ){\n          assert( pRec->pKeyInfo->nAllField==nCol );\n          assert( pRec->pKeyInfo->enc==ENC(db) );\n          pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));\n          for(i=0; i<nCol; i++){\n            pRec->aMem[i].flags = MEM_Null;\n            pRec->aMem[i].db = db;\n          }\n        }else{\n          sqlite3DbFreeNN(db, pRec);\n          pRec = 0;\n        }\n      }\n      if( pRec==0 ) return 0;\n      p->ppRec[0] = pRec;\n    }\n  \n    pRec->nField = p->iVal+1;\n    return &pRec->aMem[p->iVal];\n  }\n#else\n  UNUSED_PARAMETER(p);\n#endif /* defined(SQLITE_ENABLE_STAT4) */\n  return sqlite3ValueNew(db);\n}\n\n/*\n** The expression object indicated by the second argument is guaranteed\n** to be a scalar SQL function. If\n**\n**   * all function arguments are SQL literals,\n**   * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and\n**   * the SQLITE_FUNC_NEEDCOLL function flag is not set,\n**\n** then this routine attempts to invoke the SQL function. Assuming no\n** error occurs, output parameter (*ppVal) is set to point to a value \n** object containing the result before returning SQLITE_OK.\n**\n** Affinity aff is applied to the result of the function before returning.\n** If the result is a text value, the sqlite3_value object uses encoding \n** enc.\n**\n** If the conditions above are not met, this function returns SQLITE_OK\n** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to\n** NULL and an SQLite error code returned.\n*/\n#ifdef SQLITE_ENABLE_STAT4\nstatic int valueFromFunction(\n  sqlite3 *db,                    /* The database connection */\n  Expr *p,                        /* The expression to evaluate */\n  u8 enc,                         /* Encoding to use */\n  u8 aff,                         /* Affinity to use */\n  sqlite3_value **ppVal,          /* Write the new value here */\n  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */\n){\n  sqlite3_context ctx;            /* Context object for function invocation */\n  sqlite3_value **apVal = 0;      /* Function arguments */\n  int nVal = 0;                   /* Size of apVal[] array */\n  FuncDef *pFunc = 0;             /* Function definition */\n  sqlite3_value *pVal = 0;        /* New value */\n  int rc = SQLITE_OK;             /* Return code */\n  ExprList *pList = 0;            /* Function arguments */\n  int i;                          /* Iterator variable */\n\n  assert( pCtx!=0 );\n  assert( (p->flags & EP_TokenOnly)==0 );\n  pList = p->x.pList;\n  if( pList ) nVal = pList->nExpr;\n  pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);\n  assert( pFunc );\n  if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0 \n   || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)\n  ){\n    return SQLITE_OK;\n  }\n\n  if( pList ){\n    apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);\n    if( apVal==0 ){\n      rc = SQLITE_NOMEM_BKPT;\n      goto value_from_function_out;\n    }\n    for(i=0; i<nVal; i++){\n      rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);\n      if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;\n    }\n  }\n\n  pVal = valueNew(db, pCtx);\n  if( pVal==0 ){\n    rc = SQLITE_NOMEM_BKPT;\n    goto value_from_function_out;\n  }\n\n  assert( pCtx->pParse->rc==SQLITE_OK );\n  memset(&ctx, 0, sizeof(ctx));\n  ctx.pOut = pVal;\n  ctx.pFunc = pFunc;\n  pFunc->xSFunc(&ctx, nVal, apVal);\n  if( ctx.isError ){\n    rc = ctx.isError;\n    sqlite3ErrorMsg(pCtx->pParse, \"%s\", sqlite3_value_text(pVal));\n  }else{\n    sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);\n    assert( rc==SQLITE_OK );\n    rc = sqlite3VdbeChangeEncoding(pVal, enc);\n    if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){\n      rc = SQLITE_TOOBIG;\n      pCtx->pParse->nErr++;\n    }\n  }\n  pCtx->pParse->rc = rc;\n\n value_from_function_out:\n  if( rc!=SQLITE_OK ){\n    pVal = 0;\n  }\n  if( apVal ){\n    for(i=0; i<nVal; i++){\n      sqlite3ValueFree(apVal[i]);\n    }\n    sqlite3DbFreeNN(db, apVal);\n  }\n\n  *ppVal = pVal;\n  return rc;\n}\n#else\n# define valueFromFunction(a,b,c,d,e,f) SQLITE_OK\n#endif /* defined(SQLITE_ENABLE_STAT4) */\n\n/*\n** Extract a value from the supplied expression in the manner described\n** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object\n** using valueNew().\n**\n** If pCtx is NULL and an error occurs after the sqlite3_value object\n** has been allocated, it is freed before returning. Or, if pCtx is not\n** NULL, it is assumed that the caller will free any allocated object\n** in all cases.\n*/\nstatic int valueFromExpr(\n  sqlite3 *db,                    /* The database connection */\n  Expr *pExpr,                    /* The expression to evaluate */\n  u8 enc,                         /* Encoding to use */\n  u8 affinity,                    /* Affinity to use */\n  sqlite3_value **ppVal,          /* Write the new value here */\n  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */\n){\n  int op;\n  char *zVal = 0;\n  sqlite3_value *pVal = 0;\n  int negInt = 1;\n  const char *zNeg = \"\";\n  int rc = SQLITE_OK;\n\n  assert( pExpr!=0 );\n  while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;\n#if defined(SQLITE_ENABLE_STAT4)\n  if( op==TK_REGISTER ) op = pExpr->op2;\n#else\n  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;\n#endif\n\n  /* Compressed expressions only appear when parsing the DEFAULT clause\n  ** on a table column definition, and hence only when pCtx==0.  This\n  ** check ensures that an EP_TokenOnly expression is never passed down\n  ** into valueFromFunction(). */\n  assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );\n\n  if( op==TK_CAST ){\n    u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);\n    rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);\n    testcase( rc!=SQLITE_OK );\n    if( *ppVal ){\n      sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);\n      sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);\n    }\n    return rc;\n  }\n\n  /* Handle negative integers in a single step.  This is needed in the\n  ** case when the value is -9223372036854775808.\n  */\n  if( op==TK_UMINUS\n   && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){\n    pExpr = pExpr->pLeft;\n    op = pExpr->op;\n    negInt = -1;\n    zNeg = \"-\";\n  }\n\n  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){\n    pVal = valueNew(db, pCtx);\n    if( pVal==0 ) goto no_mem;\n    if( ExprHasProperty(pExpr, EP_IntValue) ){\n      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);\n    }else{\n      zVal = sqlite3MPrintf(db, \"%s%s\", zNeg, pExpr->u.zToken);\n      if( zVal==0 ) goto no_mem;\n      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);\n    }\n    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){\n      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);\n    }else{\n      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);\n    }\n    assert( (pVal->flags & MEM_IntReal)==0 );\n    if( pVal->flags & (MEM_Int|MEM_IntReal|MEM_Real) ){\n      testcase( pVal->flags & MEM_Int );\n      testcase( pVal->flags & MEM_Real );\n      pVal->flags &= ~MEM_Str;\n    }\n    if( enc!=SQLITE_UTF8 ){\n      rc = sqlite3VdbeChangeEncoding(pVal, enc);\n    }\n  }else if( op==TK_UMINUS ) {\n    /* This branch happens for multiple negative signs.  Ex: -(-5) */\n    if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx) \n     && pVal!=0\n    ){\n      sqlite3VdbeMemNumerify(pVal);\n      if( pVal->flags & MEM_Real ){\n        pVal->u.r = -pVal->u.r;\n      }else if( pVal->u.i==SMALLEST_INT64 ){\n#ifndef SQLITE_OMIT_FLOATING_POINT\n        pVal->u.r = -(double)SMALLEST_INT64;\n#else\n        pVal->u.r = LARGEST_INT64;\n#endif\n        MemSetTypeFlag(pVal, MEM_Real);\n      }else{\n        pVal->u.i = -pVal->u.i;\n      }\n      sqlite3ValueApplyAffinity(pVal, affinity, enc);\n    }\n  }else if( op==TK_NULL ){\n    pVal = valueNew(db, pCtx);\n    if( pVal==0 ) goto no_mem;\n    sqlite3VdbeMemSetNull(pVal);\n  }\n#ifndef SQLITE_OMIT_BLOB_LITERAL\n  else if( op==TK_BLOB ){\n    int nVal;\n    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );\n    assert( pExpr->u.zToken[1]=='\\'' );\n    pVal = valueNew(db, pCtx);\n    if( !pVal ) goto no_mem;\n    zVal = &pExpr->u.zToken[2];\n    nVal = sqlite3Strlen30(zVal)-1;\n    assert( zVal[nVal]=='\\'' );\n    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,\n                         0, SQLITE_DYNAMIC);\n  }\n#endif\n#ifdef SQLITE_ENABLE_STAT4\n  else if( op==TK_FUNCTION && pCtx!=0 ){\n    rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);\n  }\n#endif\n  else if( op==TK_TRUEFALSE ){\n    pVal = valueNew(db, pCtx);\n    if( pVal ){\n      pVal->flags = MEM_Int;\n      pVal->u.i = pExpr->u.zToken[4]==0;\n    }\n  }\n\n  *ppVal = pVal;\n  return rc;\n\nno_mem:\n#ifdef SQLITE_ENABLE_STAT4\n  if( pCtx==0 || pCtx->pParse->nErr==0 )\n#endif\n    sqlite3OomFault(db);\n  sqlite3DbFree(db, zVal);\n  assert( *ppVal==0 );\n#ifdef SQLITE_ENABLE_STAT4\n  if( pCtx==0 ) sqlite3ValueFree(pVal);\n#else\n  assert( pCtx==0 ); sqlite3ValueFree(pVal);\n#endif\n  return SQLITE_NOMEM_BKPT;\n}\n\n/*\n** Create a new sqlite3_value object, containing the value of pExpr.\n**\n** This only works for very simple expressions that consist of one constant\n** token (i.e. \"5\", \"5.1\", \"'a string'\"). If the expression can\n** be converted directly into a value, then the value is allocated and\n** a pointer written to *ppVal. The caller is responsible for deallocating\n** the value by passing it to sqlite3ValueFree() later on. If the expression\n** cannot be converted to a value, then *ppVal is set to NULL.\n*/\nSQLITE_PRIVATE int sqlite3ValueFromExpr(\n  sqlite3 *db,              /* The database connection */\n  Expr *pExpr,              /* The expression to evaluate */\n  u8 enc,                   /* Encoding to use */\n  u8 affinity,              /* Affinity to use */\n  sqlite3_value **ppVal     /* Write the new value here */\n){\n  return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;\n}\n\n#ifdef SQLITE_ENABLE_STAT4\n/*\n** Attempt to extract a value from pExpr and use it to construct *ppVal.\n**\n** If pAlloc is not NULL, then an UnpackedRecord object is created for\n** pAlloc if one does not exist and the new value is added to the\n** UnpackedRecord object.\n**\n** A value is extracted in the following cases:\n**\n**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,\n**\n**  * The expression is a bound variable, and this is a reprepare, or\n**\n**  * The expression is a literal value.\n**\n** On success, *ppVal is made to point to the extracted value.  The caller\n** is responsible for ensuring that the value is eventually freed.\n*/\nstatic int stat4ValueFromExpr(\n  Parse *pParse,                  /* Parse context */\n  Expr *pExpr,                    /* The expression to extract a value from */\n  u8 affinity,                    /* Affinity to use */\n  struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */\n  sqlite3_value **ppVal           /* OUT: New value object (or NULL) */\n){\n  int rc = SQLITE_OK;\n  sqlite3_value *pVal = 0;\n  sqlite3 *db = pParse->db;\n\n  /* Skip over any TK_COLLATE nodes */\n  pExpr = sqlite3ExprSkipCollate(pExpr);\n\n  assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );\n  if( !pExpr ){\n    pVal = valueNew(db, pAlloc);\n    if( pVal ){\n      sqlite3VdbeMemSetNull((Mem*)pVal);\n    }\n  }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){\n    Vdbe *v;\n    int iBindVar = pExpr->iColumn;\n    sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);\n    if( (v = pParse->pReprepare)!=0 ){\n      pVal = valueNew(db, pAlloc);\n      if( pVal ){\n        rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);\n        sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));\n        pVal->db = pParse->db;\n      }\n    }\n  }else{\n    rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);\n  }\n\n  assert( pVal==0 || pVal->db==db );\n  *ppVal = pVal;\n  return rc;\n}\n\n/*\n** This function is used to allocate and populate UnpackedRecord \n** structures intended to be compared against sample index keys stored \n** in the sqlite_stat4 table.\n**\n** A single call to this function populates zero or more fields of the\n** record starting with field iVal (fields are numbered from left to\n** right starting with 0). A single field is populated if:\n**\n**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,\n**\n**  * The expression is a bound variable, and this is a reprepare, or\n**\n**  * The sqlite3ValueFromExpr() function is able to extract a value \n**    from the expression (i.e. the expression is a literal value).\n**\n** Or, if pExpr is a TK_VECTOR, one field is populated for each of the\n** vector components that match either of the two latter criteria listed\n** above.\n**\n** Before any value is appended to the record, the affinity of the \n** corresponding column within index pIdx is applied to it. Before\n** this function returns, output parameter *pnExtract is set to the\n** number of values appended to the record.\n**\n** When this function is called, *ppRec must either point to an object\n** allocated by an earlier call to this function, or must be NULL. If it\n** is NULL and a value can be successfully extracted, a new UnpackedRecord\n** is allocated (and *ppRec set to point to it) before returning.\n**\n** Unless an error is encountered, SQLITE_OK is returned. It is not an\n** error if a value cannot be extracted from pExpr. If an error does\n** occur, an SQLite error code is returned.\n*/\nSQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(\n  Parse *pParse,                  /* Parse context */\n  Index *pIdx,                    /* Index being probed */\n  UnpackedRecord **ppRec,         /* IN/OUT: Probe record */\n  Expr *pExpr,                    /* The expression to extract a value from */\n  int nElem,                      /* Maximum number of values to append */\n  int iVal,                       /* Array element to populate */\n  int *pnExtract                  /* OUT: Values appended to the record */\n){\n  int rc = SQLITE_OK;\n  int nExtract = 0;\n\n  if( pExpr==0 || pExpr->op!=TK_SELECT ){\n    int i;\n    struct ValueNewStat4Ctx alloc;\n\n    alloc.pParse = pParse;\n    alloc.pIdx = pIdx;\n    alloc.ppRec = ppRec;\n\n    for(i=0; i<nElem; i++){\n      sqlite3_value *pVal = 0;\n      Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);\n      u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);\n      alloc.iVal = iVal+i;\n      rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);\n      if( !pVal ) break;\n      nExtract++;\n    }\n  }\n\n  *pnExtract = nExtract;\n  return rc;\n}\n\n/*\n** Attempt to extract a value from expression pExpr using the methods\n** as described for sqlite3Stat4ProbeSetValue() above. \n**\n** If successful, set *ppVal to point to a new value object and return \n** SQLITE_OK. If no value can be extracted, but no other error occurs\n** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error\n** does occur, return an SQLite error code. The final value of *ppVal\n** is undefined in this case.\n*/\nSQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(\n  Parse *pParse,                  /* Parse context */\n  Expr *pExpr,                    /* The expression to extract a value from */\n  u8 affinity,                    /* Affinity to use */\n  sqlite3_value **ppVal           /* OUT: New value object (or NULL) */\n){\n  return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);\n}\n\n/*\n** Extract the iCol-th column from the nRec-byte record in pRec.  Write\n** the column value into *ppVal.  If *ppVal is initially NULL then a new\n** sqlite3_value object is allocated.\n**\n** If *ppVal is initially NULL then the caller is responsible for \n** ensuring that the value written into *ppVal is eventually freed.\n*/\nSQLITE_PRIVATE int sqlite3Stat4Column(\n  sqlite3 *db,                    /* Database handle */\n  const void *pRec,               /* Pointer to buffer containing record */\n  int nRec,                       /* Size of buffer pRec in bytes */\n  int iCol,                       /* Column to extract */\n  sqlite3_value **ppVal           /* OUT: Extracted value */\n){\n  u32 t = 0;                      /* a column type code */\n  int nHdr;                       /* Size of the header in the record */\n  int iHdr;                       /* Next unread header byte */\n  int iField;                     /* Next unread data byte */\n  int szField = 0;                /* Size of the current data field */\n  int i;                          /* Column index */\n  u8 *a = (u8*)pRec;              /* Typecast byte array */\n  Mem *pMem = *ppVal;             /* Write result into this Mem object */\n\n  assert( iCol>0 );\n  iHdr = getVarint32(a, nHdr);\n  if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;\n  iField = nHdr;\n  for(i=0; i<=iCol; i++){\n    iHdr += getVarint32(&a[iHdr], t);\n    testcase( iHdr==nHdr );\n    testcase( iHdr==nHdr+1 );\n    if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;\n    szField = sqlite3VdbeSerialTypeLen(t);\n    iField += szField;\n  }\n  testcase( iField==nRec );\n  testcase( iField==nRec+1 );\n  if( iField>nRec ) return SQLITE_CORRUPT_BKPT;\n  if( pMem==0 ){\n    pMem = *ppVal = sqlite3ValueNew(db);\n    if( pMem==0 ) return SQLITE_NOMEM_BKPT;\n  }\n  sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);\n  pMem->enc = ENC(db);\n  return SQLITE_OK;\n}\n\n/*\n** Unless it is NULL, the argument must be an UnpackedRecord object returned\n** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes\n** the object.\n*/\nSQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){\n  if( pRec ){\n    int i;\n    int nCol = pRec->pKeyInfo->nAllField;\n    Mem *aMem = pRec->aMem;\n    sqlite3 *db = aMem[0].db;\n    for(i=0; i<nCol; i++){\n      sqlite3VdbeMemRelease(&aMem[i]);\n    }\n    sqlite3KeyInfoUnref(pRec->pKeyInfo);\n    sqlite3DbFreeNN(db, pRec);\n  }\n}\n#endif /* ifdef SQLITE_ENABLE_STAT4 */\n\n/*\n** Change the string value of an sqlite3_value object\n*/\nSQLITE_PRIVATE void sqlite3ValueSetStr(\n  sqlite3_value *v,     /* Value to be set */\n  int n,                /* Length of string z */\n  const void *z,        /* Text of the new string */\n  u8 enc,               /* Encoding to use */\n  void (*xDel)(void*)   /* Destructor for the string */\n){\n  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);\n}\n\n/*\n** Free an sqlite3_value object\n*/\nSQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){\n  if( !v ) return;\n  sqlite3VdbeMemRelease((Mem *)v);\n  sqlite3DbFreeNN(((Mem*)v)->db, v);\n}\n\n/*\n** The sqlite3ValueBytes() routine returns the number of bytes in the\n** sqlite3_value object assuming that it uses the encoding \"enc\".\n** The valueBytes() routine is a helper function.\n*/\nstatic SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){\n  return valueToText(pVal, enc)!=0 ? pVal->n : 0;\n}\nSQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){\n  Mem *p = (Mem*)pVal;\n  assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );\n  if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){\n    return p->n;\n  }\n  if( (p->flags & MEM_Blob)!=0 ){\n    if( p->flags & MEM_Zero ){\n      return p->n + p->u.nZero;\n    }else{\n      return p->n;\n    }\n  }\n  if( p->flags & MEM_Null ) return 0;\n  return valueBytes(pVal, enc);\n}\n\n/************** End of vdbemem.c *********************************************/\n/************** Begin file vdbeaux.c *****************************************/\n/*\n** 2003 September 6\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code used for creating, destroying, and populating\n** a VDBE (or an \"sqlite3_stmt\" as it is known to the outside world.) \n*/\n/* #include \"sqliteInt.h\" */\n/* #include \"vdbeInt.h\" */\n\n/* Forward references */\nstatic void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef);\nstatic void vdbeFreeOpArray(sqlite3 *, Op *, int);\n\n/*\n** Create a new virtual database engine.\n*/\nSQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){\n  sqlite3 *db = pParse->db;\n  Vdbe *p;\n  p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );\n  if( p==0 ) return 0;\n  memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));\n  p->db = db;\n  if( db->pVdbe ){\n    db->pVdbe->pPrev = p;\n  }\n  p->pNext = db->pVdbe;\n  p->pPrev = 0;\n  db->pVdbe = p;\n  p->magic = VDBE_MAGIC_INIT;\n  p->pParse = pParse;\n  pParse->pVdbe = p;\n  assert( pParse->aLabel==0 );\n  assert( pParse->nLabel==0 );\n  assert( p->nOpAlloc==0 );\n  assert( pParse->szOpAlloc==0 );\n  sqlite3VdbeAddOp2(p, OP_Init, 0, 1);\n  return p;\n}\n\n/*\n** Return the Parse object that owns a Vdbe object.\n*/\nSQLITE_PRIVATE Parse *sqlite3VdbeParser(Vdbe *p){\n  return p->pParse;\n}\n\n/*\n** Change the error string stored in Vdbe.zErrMsg\n*/\nSQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){\n  va_list ap;\n  sqlite3DbFree(p->db, p->zErrMsg);\n  va_start(ap, zFormat);\n  p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);\n  va_end(ap);\n}\n\n/*\n** Remember the SQL string for a prepared statement.\n*/\nSQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){\n  if( p==0 ) return;\n  p->prepFlags = prepFlags;\n  if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){\n    p->expmask = 0;\n  }\n  assert( p->zSql==0 );\n  p->zSql = sqlite3DbStrNDup(p->db, z, n);\n}\n\n#ifdef SQLITE_ENABLE_NORMALIZE\n/*\n** Add a new element to the Vdbe->pDblStr list.\n*/\nSQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3 *db, Vdbe *p, const char *z){\n  if( p ){\n    int n = sqlite3Strlen30(z);\n    DblquoteStr *pStr = sqlite3DbMallocRawNN(db,\n                            sizeof(*pStr)+n+1-sizeof(pStr->z));\n    if( pStr ){\n      pStr->pNextStr = p->pDblStr;\n      p->pDblStr = pStr;\n      memcpy(pStr->z, z, n+1);\n    }\n  }\n}\n#endif\n\n#ifdef SQLITE_ENABLE_NORMALIZE\n/*\n** zId of length nId is a double-quoted identifier.  Check to see if\n** that identifier is really used as a string literal.\n*/\nSQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(\n  Vdbe *pVdbe,            /* The prepared statement */\n  const char *zId         /* The double-quoted identifier, already dequoted */\n){\n  DblquoteStr *pStr;\n  assert( zId!=0 );\n  if( pVdbe->pDblStr==0 ) return 0;\n  for(pStr=pVdbe->pDblStr; pStr; pStr=pStr->pNextStr){\n    if( strcmp(zId, pStr->z)==0 ) return 1;\n  }\n  return 0;\n}\n#endif\n\n/*\n** Swap all content between two VDBE structures.\n*/\nSQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){\n  Vdbe tmp, *pTmp;\n  char *zTmp;\n  assert( pA->db==pB->db );\n  tmp = *pA;\n  *pA = *pB;\n  *pB = tmp;\n  pTmp = pA->pNext;\n  pA->pNext = pB->pNext;\n  pB->pNext = pTmp;\n  pTmp = pA->pPrev;\n  pA->pPrev = pB->pPrev;\n  pB->pPrev = pTmp;\n  zTmp = pA->zSql;\n  pA->zSql = pB->zSql;\n  pB->zSql = zTmp;\n#ifdef SQLITE_ENABLE_NORMALIZE\n  zTmp = pA->zNormSql;\n  pA->zNormSql = pB->zNormSql;\n  pB->zNormSql = zTmp;\n#endif\n  pB->expmask = pA->expmask;\n  pB->prepFlags = pA->prepFlags;\n  memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));\n  pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;\n}\n\n/*\n** Resize the Vdbe.aOp array so that it is at least nOp elements larger \n** than its current size. nOp is guaranteed to be less than or equal\n** to 1024/sizeof(Op).\n**\n** If an out-of-memory error occurs while resizing the array, return\n** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain \n** unchanged (this is so that any opcodes already allocated can be \n** correctly deallocated along with the rest of the Vdbe).\n*/\nstatic int growOpArray(Vdbe *v, int nOp){\n  VdbeOp *pNew;\n  Parse *p = v->pParse;\n\n  /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force\n  ** more frequent reallocs and hence provide more opportunities for \n  ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used\n  ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array\n  ** by the minimum* amount required until the size reaches 512.  Normal\n  ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current\n  ** size of the op array or add 1KB of space, whichever is smaller. */\n#ifdef SQLITE_TEST_REALLOC_STRESS\n  sqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(sqlite3_int64)v->nOpAlloc\n                        : (sqlite3_int64)v->nOpAlloc+nOp);\n#else\n  sqlite3_int64 nNew = (v->nOpAlloc ? 2*(sqlite3_int64)v->nOpAlloc\n                        : (sqlite3_int64)(1024/sizeof(Op)));\n  UNUSED_PARAMETER(nOp);\n#endif\n\n  /* Ensure that the size of a VDBE does not grow too large */\n  if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){\n    sqlite3OomFault(p->db);\n    return SQLITE_NOMEM;\n  }\n\n  assert( nOp<=(1024/sizeof(Op)) );\n  assert( nNew>=(v->nOpAlloc+nOp) );\n  pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));\n  if( pNew ){\n    p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);\n    v->nOpAlloc = p->szOpAlloc/sizeof(Op);\n    v->aOp = pNew;\n  }\n  return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);\n}\n\n#ifdef SQLITE_DEBUG\n/* This routine is just a convenient place to set a breakpoint that will\n** fire after each opcode is inserted and displayed using\n** \"PRAGMA vdbe_addoptrace=on\".  Parameters \"pc\" (program counter) and\n** pOp are available to make the breakpoint conditional.\n**\n** Other useful labels for breakpoints include:\n**   test_trace_breakpoint(pc,pOp)\n**   sqlite3CorruptError(lineno)\n**   sqlite3MisuseError(lineno)\n**   sqlite3CantopenError(lineno)\n*/\nstatic void test_addop_breakpoint(int pc, Op *pOp){\n  static int n = 0;\n  n++;\n}\n#endif\n\n/*\n** Add a new instruction to the list of instructions current in the\n** VDBE.  Return the address of the new instruction.\n**\n** Parameters:\n**\n**    p               Pointer to the VDBE\n**\n**    op              The opcode for this instruction\n**\n**    p1, p2, p3      Operands\n**\n** Use the sqlite3VdbeResolveLabel() function to fix an address and\n** the sqlite3VdbeChangeP4() function to change the value of the P4\n** operand.\n*/\nstatic SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){\n  assert( p->nOpAlloc<=p->nOp );\n  if( growOpArray(p, 1) ) return 1;\n  assert( p->nOpAlloc>p->nOp );\n  return sqlite3VdbeAddOp3(p, op, p1, p2, p3);\n}\nSQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){\n  int i;\n  VdbeOp *pOp;\n\n  i = p->nOp;\n  assert( p->magic==VDBE_MAGIC_INIT );\n  assert( op>=0 && op<0xff );\n  if( p->nOpAlloc<=i ){\n    return growOp3(p, op, p1, p2, p3);\n  }\n  p->nOp++;\n  pOp = &p->aOp[i];\n  pOp->opcode = (u8)op;\n  pOp->p5 = 0;\n  pOp->p1 = p1;\n  pOp->p2 = p2;\n  pOp->p3 = p3;\n  pOp->p4.p = 0;\n  pOp->p4type = P4_NOTUSED;\n#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS\n  pOp->zComment = 0;\n#endif\n#ifdef SQLITE_DEBUG\n  if( p->db->flags & SQLITE_VdbeAddopTrace ){\n    sqlite3VdbePrintOp(0, i, &p->aOp[i]);\n    test_addop_breakpoint(i, &p->aOp[i]);\n  }\n#endif\n#ifdef VDBE_PROFILE\n  pOp->cycles = 0;\n  pOp->cnt = 0;\n#endif\n#ifdef SQLITE_VDBE_COVERAGE\n  pOp->iSrcLine = 0;\n#endif\n  return i;\n}\nSQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){\n  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);\n}\nSQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){\n  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);\n}\nSQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){\n  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);\n}\n\n/* Generate code for an unconditional jump to instruction iDest\n*/\nSQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){\n  return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);\n}\n\n/* Generate code to cause the string zStr to be loaded into\n** register iDest\n*/\nSQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){\n  return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);\n}\n\n/*\n** Generate code that initializes multiple registers to string or integer\n** constants.  The registers begin with iDest and increase consecutively.\n** One register is initialized for each characgter in zTypes[].  For each\n** \"s\" character in zTypes[], the register is a string if the argument is\n** not NULL, or OP_Null if the value is a null pointer.  For each \"i\" character\n** in zTypes[], the register is initialized to an integer.\n**\n** If the input string does not end with \"X\" then an OP_ResultRow instruction\n** is generated for the values inserted.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){\n  va_list ap;\n  int i;\n  char c;\n  va_start(ap, zTypes);\n  for(i=0; (c = zTypes[i])!=0; i++){\n    if( c=='s' ){\n      const char *z = va_arg(ap, const char*);\n      sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);\n    }else if( c=='i' ){\n      sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);\n    }else{\n      goto skip_op_resultrow;\n    }\n  }\n  sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);\nskip_op_resultrow:\n  va_end(ap);\n}\n\n/*\n** Add an opcode that includes the p4 value as a pointer.\n*/\nSQLITE_PRIVATE int sqlite3VdbeAddOp4(\n  Vdbe *p,            /* Add the opcode to this VM */\n  int op,             /* The new opcode */\n  int p1,             /* The P1 operand */\n  int p2,             /* The P2 operand */\n  int p3,             /* The P3 operand */\n  const char *zP4,    /* The P4 operand */\n  int p4type          /* P4 operand type */\n){\n  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);\n  sqlite3VdbeChangeP4(p, addr, zP4, p4type);\n  return addr;\n}\n\n/*\n** Add an OP_Function or OP_PureFunc opcode.\n**\n** The eCallCtx argument is information (typically taken from Expr.op2)\n** that describes the calling context of the function.  0 means a general\n** function call.  NC_IsCheck means called by a check constraint,\n** NC_IdxExpr means called as part of an index expression.  NC_PartIdx\n** means in the WHERE clause of a partial index.  NC_GenCol means called\n** while computing a generated column value.  0 is the usual case.\n*/\nSQLITE_PRIVATE int sqlite3VdbeAddFunctionCall(\n  Parse *pParse,        /* Parsing context */\n  int p1,               /* Constant argument mask */\n  int p2,               /* First argument register */\n  int p3,               /* Register into which results are written */\n  int nArg,             /* Number of argument */\n  const FuncDef *pFunc, /* The function to be invoked */\n  int eCallCtx          /* Calling context */\n){\n  Vdbe *v = pParse->pVdbe;\n  int nByte;\n  int addr;\n  sqlite3_context *pCtx;\n  assert( v );\n  nByte = sizeof(*pCtx) + (nArg-1)*sizeof(sqlite3_value*);\n  pCtx = sqlite3DbMallocRawNN(pParse->db, nByte);\n  if( pCtx==0 ){\n    assert( pParse->db->mallocFailed );\n    freeEphemeralFunction(pParse->db, (FuncDef*)pFunc);\n    return 0;\n  }\n  pCtx->pOut = 0;\n  pCtx->pFunc = (FuncDef*)pFunc;\n  pCtx->pVdbe = 0;\n  pCtx->isError = 0;\n  pCtx->argc = nArg;\n  pCtx->iOp = sqlite3VdbeCurrentAddr(v);\n  addr = sqlite3VdbeAddOp4(v, eCallCtx ? OP_PureFunc : OP_Function,\n                           p1, p2, p3, (char*)pCtx, P4_FUNCCTX);\n  sqlite3VdbeChangeP5(v, eCallCtx & NC_SelfRef);\n  return addr;\n}\n\n/*\n** Add an opcode that includes the p4 value with a P4_INT64 or\n** P4_REAL type.\n*/\nSQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(\n  Vdbe *p,            /* Add the opcode to this VM */\n  int op,             /* The new opcode */\n  int p1,             /* The P1 operand */\n  int p2,             /* The P2 operand */\n  int p3,             /* The P3 operand */\n  const u8 *zP4,      /* The P4 operand */\n  int p4type          /* P4 operand type */\n){\n  char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);\n  if( p4copy ) memcpy(p4copy, zP4, 8);\n  return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);\n}\n\n#ifndef SQLITE_OMIT_EXPLAIN\n/*\n** Return the address of the current EXPLAIN QUERY PLAN baseline.\n** 0 means \"none\".\n*/\nSQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse *pParse){\n  VdbeOp *pOp;\n  if( pParse->addrExplain==0 ) return 0;\n  pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);\n  return pOp->p2;\n}\n\n/*\n** Set a debugger breakpoint on the following routine in order to\n** monitor the EXPLAIN QUERY PLAN code generation.\n*/\n#if defined(SQLITE_DEBUG)\nSQLITE_PRIVATE void sqlite3ExplainBreakpoint(const char *z1, const char *z2){\n  (void)z1;\n  (void)z2;\n}\n#endif\n\n/*\n** Add a new OP_Explain opcode.\n**\n** If the bPush flag is true, then make this opcode the parent for\n** subsequent Explains until sqlite3VdbeExplainPop() is called.\n*/\nSQLITE_PRIVATE void sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){\n#ifndef SQLITE_DEBUG\n  /* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined.\n  ** But omit them (for performance) during production builds */\n  if( pParse->explain==2 )\n#endif\n  {\n    char *zMsg;\n    Vdbe *v;\n    va_list ap;\n    int iThis;\n    va_start(ap, zFmt);\n    zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);\n    va_end(ap);\n    v = pParse->pVdbe;\n    iThis = v->nOp;\n    sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,\n                      zMsg, P4_DYNAMIC);\n    sqlite3ExplainBreakpoint(bPush?\"PUSH\":\"\", sqlite3VdbeGetOp(v,-1)->p4.z);\n    if( bPush){\n      pParse->addrExplain = iThis;\n    }\n  }\n}\n\n/*\n** Pop the EXPLAIN QUERY PLAN stack one level.\n*/\nSQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse *pParse){\n  sqlite3ExplainBreakpoint(\"POP\", 0);\n  pParse->addrExplain = sqlite3VdbeExplainParent(pParse);\n}\n#endif /* SQLITE_OMIT_EXPLAIN */\n\n/*\n** Add an OP_ParseSchema opcode.  This routine is broken out from\n** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees\n** as having been used.\n**\n** The zWhere string must have been obtained from sqlite3_malloc().\n** This routine will take ownership of the allocated memory.\n*/\nSQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){\n  int j;\n  sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);\n  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);\n}\n\n/*\n** Add an opcode that includes the p4 value as an integer.\n*/\nSQLITE_PRIVATE int sqlite3VdbeAddOp4Int(\n  Vdbe *p,            /* Add the opcode to this VM */\n  int op,             /* The new opcode */\n  int p1,             /* The P1 operand */\n  int p2,             /* The P2 operand */\n  int p3,             /* The P3 operand */\n  int p4              /* The P4 operand as an integer */\n){\n  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);\n  if( p->db->mallocFailed==0 ){\n    VdbeOp *pOp = &p->aOp[addr];\n    pOp->p4type = P4_INT32;\n    pOp->p4.i = p4;\n  }\n  return addr;\n}\n\n/* Insert the end of a co-routine\n*/\nSQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){\n  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);\n\n  /* Clear the temporary register cache, thereby ensuring that each\n  ** co-routine has its own independent set of registers, because co-routines\n  ** might expect their registers to be preserved across an OP_Yield, and\n  ** that could cause problems if two or more co-routines are using the same\n  ** temporary register.\n  */\n  v->pParse->nTempReg = 0;\n  v->pParse->nRangeReg = 0;\n}\n\n/*\n** Create a new symbolic label for an instruction that has yet to be\n** coded.  The symbolic label is really just a negative number.  The\n** label can be used as the P2 value of an operation.  Later, when\n** the label is resolved to a specific address, the VDBE will scan\n** through its operation list and change all values of P2 which match\n** the label into the resolved address.\n**\n** The VDBE knows that a P2 value is a label because labels are\n** always negative and P2 values are suppose to be non-negative.\n** Hence, a negative P2 value is a label that has yet to be resolved.\n** (Later:) This is only true for opcodes that have the OPFLG_JUMP\n** property.\n**\n** Variable usage notes:\n**\n**     Parse.aLabel[x]     Stores the address that the x-th label resolves\n**                         into.  For testing (SQLITE_DEBUG), unresolved\n**                         labels stores -1, but that is not required.\n**     Parse.nLabelAlloc   Number of slots allocated to Parse.aLabel[]\n**     Parse.nLabel        The *negative* of the number of labels that have\n**                         been issued.  The negative is stored because\n**                         that gives a performance improvement over storing\n**                         the equivalent positive value.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse *pParse){\n  return --pParse->nLabel;\n}\n\n/*\n** Resolve label \"x\" to be the address of the next instruction to\n** be inserted.  The parameter \"x\" must have been obtained from\n** a prior call to sqlite3VdbeMakeLabel().\n*/\nstatic SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){\n  int nNewSize = 10 - p->nLabel;\n  p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,\n                     nNewSize*sizeof(p->aLabel[0]));\n  if( p->aLabel==0 ){\n    p->nLabelAlloc = 0;\n  }else{\n#ifdef SQLITE_DEBUG\n    int i;\n    for(i=p->nLabelAlloc; i<nNewSize; i++) p->aLabel[i] = -1;\n#endif\n    p->nLabelAlloc = nNewSize;\n    p->aLabel[j] = v->nOp;\n  }\n}\nSQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){\n  Parse *p = v->pParse;\n  int j = ADDR(x);\n  assert( v->magic==VDBE_MAGIC_INIT );\n  assert( j<-p->nLabel );\n  assert( j>=0 );\n#ifdef SQLITE_DEBUG\n  if( p->db->flags & SQLITE_VdbeAddopTrace ){\n    printf(\"RESOLVE LABEL %d to %d\\n\", x, v->nOp);\n  }\n#endif\n  if( p->nLabelAlloc + p->nLabel < 0 ){\n    resizeResolveLabel(p,v,j);\n  }else{\n    assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */\n    p->aLabel[j] = v->nOp;\n  }\n}\n\n/*\n** Mark the VDBE as one that can only be run one time.\n*/\nSQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){\n  p->runOnlyOnce = 1;\n}\n\n/*\n** Mark the VDBE as one that can only be run multiple times.\n*/\nSQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){\n  p->runOnlyOnce = 0;\n}\n\n#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */\n\n/*\n** The following type and function are used to iterate through all opcodes\n** in a Vdbe main program and each of the sub-programs (triggers) it may \n** invoke directly or indirectly. It should be used as follows:\n**\n**   Op *pOp;\n**   VdbeOpIter sIter;\n**\n**   memset(&sIter, 0, sizeof(sIter));\n**   sIter.v = v;                            // v is of type Vdbe* \n**   while( (pOp = opIterNext(&sIter)) ){\n**     // Do something with pOp\n**   }\n**   sqlite3DbFree(v->db, sIter.apSub);\n** \n*/\ntypedef struct VdbeOpIter VdbeOpIter;\nstruct VdbeOpIter {\n  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */\n  SubProgram **apSub;        /* Array of subprograms */\n  int nSub;                  /* Number of entries in apSub */\n  int iAddr;                 /* Address of next instruction to return */\n  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */\n};\nstatic Op *opIterNext(VdbeOpIter *p){\n  Vdbe *v = p->v;\n  Op *pRet = 0;\n  Op *aOp;\n  int nOp;\n\n  if( p->iSub<=p->nSub ){\n\n    if( p->iSub==0 ){\n      aOp = v->aOp;\n      nOp = v->nOp;\n    }else{\n      aOp = p->apSub[p->iSub-1]->aOp;\n      nOp = p->apSub[p->iSub-1]->nOp;\n    }\n    assert( p->iAddr<nOp );\n\n    pRet = &aOp[p->iAddr];\n    p->iAddr++;\n    if( p->iAddr==nOp ){\n      p->iSub++;\n      p->iAddr = 0;\n    }\n  \n    if( pRet->p4type==P4_SUBPROGRAM ){\n      int nByte = (p->nSub+1)*sizeof(SubProgram*);\n      int j;\n      for(j=0; j<p->nSub; j++){\n        if( p->apSub[j]==pRet->p4.pProgram ) break;\n      }\n      if( j==p->nSub ){\n        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);\n        if( !p->apSub ){\n          pRet = 0;\n        }else{\n          p->apSub[p->nSub++] = pRet->p4.pProgram;\n        }\n      }\n    }\n  }\n\n  return pRet;\n}\n\n/*\n** Check if the program stored in the VM associated with pParse may\n** throw an ABORT exception (causing the statement, but not entire transaction\n** to be rolled back). This condition is true if the main program or any\n** sub-programs contains any of the following:\n**\n**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.\n**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.\n**   *  OP_Destroy\n**   *  OP_VUpdate\n**   *  OP_VCreate\n**   *  OP_VRename\n**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)\n**   *  OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine \n**      (for CREATE TABLE AS SELECT ...)\n**\n** Then check that the value of Parse.mayAbort is true if an\n** ABORT may be thrown, or false otherwise. Return true if it does\n** match, or false otherwise. This function is intended to be used as\n** part of an assert statement in the compiler. Similar to:\n**\n**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );\n*/\nSQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){\n  int hasAbort = 0;\n  int hasFkCounter = 0;\n  int hasCreateTable = 0;\n  int hasCreateIndex = 0;\n  int hasInitCoroutine = 0;\n  Op *pOp;\n  VdbeOpIter sIter;\n  memset(&sIter, 0, sizeof(sIter));\n  sIter.v = v;\n\n  while( (pOp = opIterNext(&sIter))!=0 ){\n    int opcode = pOp->opcode;\n    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename \n     || opcode==OP_VDestroy\n     || opcode==OP_VCreate\n     || (opcode==OP_ParseSchema && pOp->p4.z==0)\n     || ((opcode==OP_Halt || opcode==OP_HaltIfNull) \n      && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))\n    ){\n      hasAbort = 1;\n      break;\n    }\n    if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;\n    if( mayAbort ){\n      /* hasCreateIndex may also be set for some DELETE statements that use\n      ** OP_Clear. So this routine may end up returning true in the case \n      ** where a \"DELETE FROM tbl\" has a statement-journal but does not\n      ** require one. This is not so bad - it is an inefficiency, not a bug. */\n      if( opcode==OP_CreateBtree && pOp->p3==BTREE_BLOBKEY ) hasCreateIndex = 1;\n      if( opcode==OP_Clear ) hasCreateIndex = 1;\n    }\n    if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n    if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){\n      hasFkCounter = 1;\n    }\n#endif\n  }\n  sqlite3DbFree(v->db, sIter.apSub);\n\n  /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.\n  ** If malloc failed, then the while() loop above may not have iterated\n  ** through all opcodes and hasAbort may be set incorrectly. Return\n  ** true for this case to prevent the assert() in the callers frame\n  ** from failing.  */\n  return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter\n        || (hasCreateTable && hasInitCoroutine) || hasCreateIndex\n  );\n}\n#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */\n\n#ifdef SQLITE_DEBUG\n/*\n** Increment the nWrite counter in the VDBE if the cursor is not an\n** ephemeral cursor, or if the cursor argument is NULL.\n*/\nSQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){\n  if( pC==0\n   || (pC->eCurType!=CURTYPE_SORTER\n       && pC->eCurType!=CURTYPE_PSEUDO\n       && !pC->isEphemeral)\n  ){\n    p->nWrite++;\n  }\n}\n#endif\n\n#ifdef SQLITE_DEBUG\n/*\n** Assert if an Abort at this point in time might result in a corrupt\n** database.\n*/\nSQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe *p){\n  assert( p->nWrite==0 || p->usesStmtJournal );\n}\n#endif\n\n/*\n** This routine is called after all opcodes have been inserted.  It loops\n** through all the opcodes and fixes up some details.\n**\n** (1) For each jump instruction with a negative P2 value (a label)\n**     resolve the P2 value to an actual address.\n**\n** (2) Compute the maximum number of arguments used by any SQL function\n**     and store that value in *pMaxFuncArgs.\n**\n** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately\n**     indicate what the prepared statement actually does.\n**\n** (4) Initialize the p4.xAdvance pointer on opcodes that use it.\n**\n** (5) Reclaim the memory allocated for storing labels.\n**\n** This routine will only function correctly if the mkopcodeh.tcl generator\n** script numbers the opcodes correctly.  Changes to this routine must be\n** coordinated with changes to mkopcodeh.tcl.\n*/\nstatic void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){\n  int nMaxArgs = *pMaxFuncArgs;\n  Op *pOp;\n  Parse *pParse = p->pParse;\n  int *aLabel = pParse->aLabel;\n  p->readOnly = 1;\n  p->bIsReader = 0;\n  pOp = &p->aOp[p->nOp-1];\n  while(1){\n\n    /* Only JUMP opcodes and the short list of special opcodes in the switch\n    ** below need to be considered.  The mkopcodeh.tcl generator script groups\n    ** all these opcodes together near the front of the opcode list.  Skip\n    ** any opcode that does not need processing by virtual of the fact that\n    ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.\n    */\n    if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){\n      /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing\n      ** cases from this switch! */\n      switch( pOp->opcode ){\n        case OP_Transaction: {\n          if( pOp->p2!=0 ) p->readOnly = 0;\n          /* fall thru */\n        }\n        case OP_AutoCommit:\n        case OP_Savepoint: {\n          p->bIsReader = 1;\n          break;\n        }\n#ifndef SQLITE_OMIT_WAL\n        case OP_Checkpoint:\n#endif\n        case OP_Vacuum:\n        case OP_JournalMode: {\n          p->readOnly = 0;\n          p->bIsReader = 1;\n          break;\n        }\n        case OP_Next:\n        case OP_SorterNext: {\n          pOp->p4.xAdvance = sqlite3BtreeNext;\n          pOp->p4type = P4_ADVANCE;\n          /* The code generator never codes any of these opcodes as a jump\n          ** to a label.  They are always coded as a jump backwards to a \n          ** known address */\n          assert( pOp->p2>=0 );\n          break;\n        }\n        case OP_Prev: {\n          pOp->p4.xAdvance = sqlite3BtreePrevious;\n          pOp->p4type = P4_ADVANCE;\n          /* The code generator never codes any of these opcodes as a jump\n          ** to a label.  They are always coded as a jump backwards to a \n          ** known address */\n          assert( pOp->p2>=0 );\n          break;\n        }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n        case OP_VUpdate: {\n          if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;\n          break;\n        }\n        case OP_VFilter: {\n          int n;\n          assert( (pOp - p->aOp) >= 3 );\n          assert( pOp[-1].opcode==OP_Integer );\n          n = pOp[-1].p1;\n          if( n>nMaxArgs ) nMaxArgs = n;\n          /* Fall through into the default case */\n        }\n#endif\n        default: {\n          if( pOp->p2<0 ){\n            /* The mkopcodeh.tcl script has so arranged things that the only\n            ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to\n            ** have non-negative values for P2. */\n            assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );\n            assert( ADDR(pOp->p2)<-pParse->nLabel );\n            pOp->p2 = aLabel[ADDR(pOp->p2)];\n          }\n          break;\n        }\n      }\n      /* The mkopcodeh.tcl script has so arranged things that the only\n      ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to\n      ** have non-negative values for P2. */\n      assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);\n    }\n    if( pOp==p->aOp ) break;\n    pOp--;\n  }\n  sqlite3DbFree(p->db, pParse->aLabel);\n  pParse->aLabel = 0;\n  pParse->nLabel = 0;\n  *pMaxFuncArgs = nMaxArgs;\n  assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );\n}\n\n/*\n** Return the address of the next instruction to be inserted.\n*/\nSQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){\n  assert( p->magic==VDBE_MAGIC_INIT );\n  return p->nOp;\n}\n\n/*\n** Verify that at least N opcode slots are available in p without\n** having to malloc for more space (except when compiled using\n** SQLITE_TEST_REALLOC_STRESS).  This interface is used during testing\n** to verify that certain calls to sqlite3VdbeAddOpList() can never\n** fail due to a OOM fault and hence that the return value from\n** sqlite3VdbeAddOpList() will always be non-NULL.\n*/\n#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)\nSQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){\n  assert( p->nOp + N <= p->nOpAlloc );\n}\n#endif\n\n/*\n** Verify that the VM passed as the only argument does not contain\n** an OP_ResultRow opcode. Fail an assert() if it does. This is used\n** by code in pragma.c to ensure that the implementation of certain\n** pragmas comports with the flags specified in the mkpragmatab.tcl\n** script.\n*/\n#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)\nSQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){\n  int i;\n  for(i=0; i<p->nOp; i++){\n    assert( p->aOp[i].opcode!=OP_ResultRow );\n  }\n}\n#endif\n\n/*\n** Generate code (a single OP_Abortable opcode) that will\n** verify that the VDBE program can safely call Abort in the current\n** context.\n*/\n#if defined(SQLITE_DEBUG)\nSQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){\n  if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);\n}\n#endif\n\n/*\n** This function returns a pointer to the array of opcodes associated with\n** the Vdbe passed as the first argument. It is the callers responsibility\n** to arrange for the returned array to be eventually freed using the \n** vdbeFreeOpArray() function.\n**\n** Before returning, *pnOp is set to the number of entries in the returned\n** array. Also, *pnMaxArg is set to the larger of its current value and \n** the number of entries in the Vdbe.apArg[] array required to execute the \n** returned program.\n*/\nSQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){\n  VdbeOp *aOp = p->aOp;\n  assert( aOp && !p->db->mallocFailed );\n\n  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */\n  assert( DbMaskAllZero(p->btreeMask) );\n\n  resolveP2Values(p, pnMaxArg);\n  *pnOp = p->nOp;\n  p->aOp = 0;\n  return aOp;\n}\n\n/*\n** Add a whole list of operations to the operation stack.  Return a\n** pointer to the first operation inserted.\n**\n** Non-zero P2 arguments to jump instructions are automatically adjusted\n** so that the jump target is relative to the first operation inserted.\n*/\nSQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(\n  Vdbe *p,                     /* Add opcodes to the prepared statement */\n  int nOp,                     /* Number of opcodes to add */\n  VdbeOpList const *aOp,       /* The opcodes to be added */\n  int iLineno                  /* Source-file line number of first opcode */\n){\n  int i;\n  VdbeOp *pOut, *pFirst;\n  assert( nOp>0 );\n  assert( p->magic==VDBE_MAGIC_INIT );\n  if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){\n    return 0;\n  }\n  pFirst = pOut = &p->aOp[p->nOp];\n  for(i=0; i<nOp; i++, aOp++, pOut++){\n    pOut->opcode = aOp->opcode;\n    pOut->p1 = aOp->p1;\n    pOut->p2 = aOp->p2;\n    assert( aOp->p2>=0 );\n    if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){\n      pOut->p2 += p->nOp;\n    }\n    pOut->p3 = aOp->p3;\n    pOut->p4type = P4_NOTUSED;\n    pOut->p4.p = 0;\n    pOut->p5 = 0;\n#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS\n    pOut->zComment = 0;\n#endif\n#ifdef SQLITE_VDBE_COVERAGE\n    pOut->iSrcLine = iLineno+i;\n#else\n    (void)iLineno;\n#endif\n#ifdef SQLITE_DEBUG\n    if( p->db->flags & SQLITE_VdbeAddopTrace ){\n      sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);\n    }\n#endif\n  }\n  p->nOp += nOp;\n  return pFirst;\n}\n\n#if defined(SQLITE_ENABLE_STMT_SCANSTATUS)\n/*\n** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().\n*/\nSQLITE_PRIVATE void sqlite3VdbeScanStatus(\n  Vdbe *p,                        /* VM to add scanstatus() to */\n  int addrExplain,                /* Address of OP_Explain (or 0) */\n  int addrLoop,                   /* Address of loop counter */ \n  int addrVisit,                  /* Address of rows visited counter */\n  LogEst nEst,                    /* Estimated number of output rows */\n  const char *zName               /* Name of table or index being scanned */\n){\n  sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus);\n  ScanStatus *aNew;\n  aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);\n  if( aNew ){\n    ScanStatus *pNew = &aNew[p->nScan++];\n    pNew->addrExplain = addrExplain;\n    pNew->addrLoop = addrLoop;\n    pNew->addrVisit = addrVisit;\n    pNew->nEst = nEst;\n    pNew->zName = sqlite3DbStrDup(p->db, zName);\n    p->aScan = aNew;\n  }\n}\n#endif\n\n\n/*\n** Change the value of the opcode, or P1, P2, P3, or P5 operands\n** for a specific instruction.\n*/\nSQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, int addr, u8 iNewOpcode){\n  sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;\n}\nSQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){\n  sqlite3VdbeGetOp(p,addr)->p1 = val;\n}\nSQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){\n  sqlite3VdbeGetOp(p,addr)->p2 = val;\n}\nSQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){\n  sqlite3VdbeGetOp(p,addr)->p3 = val;\n}\nSQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){\n  assert( p->nOp>0 || p->db->mallocFailed );\n  if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;\n}\n\n/*\n** Change the P2 operand of instruction addr so that it points to\n** the address of the next instruction to be coded.\n*/\nSQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){\n  sqlite3VdbeChangeP2(p, addr, p->nOp);\n}\n\n/*\n** Change the P2 operand of the jump instruction at addr so that\n** the jump lands on the next opcode.  Or if the jump instruction was\n** the previous opcode (and is thus a no-op) then simply back up\n** the next instruction counter by one slot so that the jump is\n** overwritten by the next inserted opcode.\n**\n** This routine is an optimization of sqlite3VdbeJumpHere() that\n** strives to omit useless byte-code like this:\n**\n**        7   Once 0 8 0\n**        8   ...\n*/\nSQLITE_PRIVATE void sqlite3VdbeJumpHereOrPopInst(Vdbe *p, int addr){\n  if( addr==p->nOp-1 ){\n    assert( p->aOp[addr].opcode==OP_Once\n         || p->aOp[addr].opcode==OP_If\n         || p->aOp[addr].opcode==OP_FkIfZero );\n    assert( p->aOp[addr].p4type==0 );\n#ifdef SQLITE_VDBE_COVERAGE\n    sqlite3VdbeGetOp(p,-1)->iSrcLine = 0;  /* Erase VdbeCoverage() macros */\n#endif\n    p->nOp--;\n  }else{\n    sqlite3VdbeChangeP2(p, addr, p->nOp);\n  }\n}\n\n\n/*\n** If the input FuncDef structure is ephemeral, then free it.  If\n** the FuncDef is not ephermal, then do nothing.\n*/\nstatic void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){\n  if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){\n    sqlite3DbFreeNN(db, pDef);\n  }\n}\n\n/*\n** Delete a P4 value if necessary.\n*/\nstatic SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){\n  if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);\n  sqlite3DbFreeNN(db, p);\n}\nstatic SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){\n  freeEphemeralFunction(db, p->pFunc);\n  sqlite3DbFreeNN(db, p);\n}\nstatic void freeP4(sqlite3 *db, int p4type, void *p4){\n  assert( db );\n  switch( p4type ){\n    case P4_FUNCCTX: {\n      freeP4FuncCtx(db, (sqlite3_context*)p4);\n      break;\n    }\n    case P4_REAL:\n    case P4_INT64:\n    case P4_DYNAMIC:\n    case P4_DYNBLOB:\n    case P4_INTARRAY: {\n      sqlite3DbFree(db, p4);\n      break;\n    }\n    case P4_KEYINFO: {\n      if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);\n      break;\n    }\n#ifdef SQLITE_ENABLE_CURSOR_HINTS\n    case P4_EXPR: {\n      sqlite3ExprDelete(db, (Expr*)p4);\n      break;\n    }\n#endif\n    case P4_FUNCDEF: {\n      freeEphemeralFunction(db, (FuncDef*)p4);\n      break;\n    }\n    case P4_MEM: {\n      if( db->pnBytesFreed==0 ){\n        sqlite3ValueFree((sqlite3_value*)p4);\n      }else{\n        freeP4Mem(db, (Mem*)p4);\n      }\n      break;\n    }\n    case P4_VTAB : {\n      if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);\n      break;\n    }\n  }\n}\n\n/*\n** Free the space allocated for aOp and any p4 values allocated for the\n** opcodes contained within. If aOp is not NULL it is assumed to contain \n** nOp entries. \n*/\nstatic void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){\n  if( aOp ){\n    Op *pOp;\n    for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){\n      if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);\n#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS\n      sqlite3DbFree(db, pOp->zComment);\n#endif     \n    }\n    sqlite3DbFreeNN(db, aOp);\n  }\n}\n\n/*\n** Link the SubProgram object passed as the second argument into the linked\n** list at Vdbe.pSubProgram. This list is used to delete all sub-program\n** objects when the VM is no longer required.\n*/\nSQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){\n  p->pNext = pVdbe->pProgram;\n  pVdbe->pProgram = p;\n}\n\n/*\n** Return true if the given Vdbe has any SubPrograms.\n*/\nSQLITE_PRIVATE int sqlite3VdbeHasSubProgram(Vdbe *pVdbe){\n  return pVdbe->pProgram!=0;\n}\n\n/*\n** Change the opcode at addr into OP_Noop\n*/\nSQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){\n  VdbeOp *pOp;\n  if( p->db->mallocFailed ) return 0;\n  assert( addr>=0 && addr<p->nOp );\n  pOp = &p->aOp[addr];\n  freeP4(p->db, pOp->p4type, pOp->p4.p);\n  pOp->p4type = P4_NOTUSED;\n  pOp->p4.z = 0;\n  pOp->opcode = OP_Noop;\n  return 1;\n}\n\n/*\n** If the last opcode is \"op\" and it is not a jump destination,\n** then remove it.  Return true if and only if an opcode was removed.\n*/\nSQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){\n  if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){\n    return sqlite3VdbeChangeToNoop(p, p->nOp-1);\n  }else{\n    return 0;\n  }\n}\n\n#ifdef SQLITE_DEBUG\n/*\n** Generate an OP_ReleaseReg opcode to indicate that a range of\n** registers, except any identified by mask, are no longer in use.\n*/\nSQLITE_PRIVATE void sqlite3VdbeReleaseRegisters(\n  Parse *pParse,       /* Parsing context */\n  int iFirst,          /* Index of first register to be released */\n  int N,               /* Number of registers to release */\n  u32 mask,            /* Mask of registers to NOT release */\n  int bUndefine        /* If true, mark registers as undefined */\n){\n  if( N==0 ) return;\n  assert( pParse->pVdbe );\n  assert( iFirst>=1 );\n  assert( iFirst+N-1<=pParse->nMem );\n  if( N<=31 && mask!=0 ){\n    while( N>0 && (mask&1)!=0 ){\n      mask >>= 1;\n      iFirst++;\n      N--;\n    }\n    while( N>0 && N<=32 && (mask & MASKBIT32(N-1))!=0 ){\n      mask &= ~MASKBIT32(N-1);\n      N--;\n    }\n  }\n  if( N>0 ){\n    sqlite3VdbeAddOp3(pParse->pVdbe, OP_ReleaseReg, iFirst, N, *(int*)&mask);\n    if( bUndefine ) sqlite3VdbeChangeP5(pParse->pVdbe, 1);\n  }\n}\n#endif /* SQLITE_DEBUG */\n\n\n/*\n** Change the value of the P4 operand for a specific instruction.\n** This routine is useful when a large program is loaded from a\n** static array using sqlite3VdbeAddOpList but we want to make a\n** few minor changes to the program.\n**\n** If n>=0 then the P4 operand is dynamic, meaning that a copy of\n** the string is made into memory obtained from sqlite3_malloc().\n** A value of n==0 means copy bytes of zP4 up to and including the\n** first null byte.  If n>0 then copy n+1 bytes of zP4.\n** \n** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points\n** to a string or structure that is guaranteed to exist for the lifetime of\n** the Vdbe. In these cases we can just copy the pointer.\n**\n** If addr<0 then change P4 on the most recently inserted instruction.\n*/\nstatic void SQLITE_NOINLINE vdbeChangeP4Full(\n  Vdbe *p,\n  Op *pOp,\n  const char *zP4,\n  int n\n){\n  if( pOp->p4type ){\n    freeP4(p->db, pOp->p4type, pOp->p4.p);\n    pOp->p4type = 0;\n    pOp->p4.p = 0;\n  }\n  if( n<0 ){\n    sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);\n  }else{\n    if( n==0 ) n = sqlite3Strlen30(zP4);\n    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);\n    pOp->p4type = P4_DYNAMIC;\n  }\n}\nSQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){\n  Op *pOp;\n  sqlite3 *db;\n  assert( p!=0 );\n  db = p->db;\n  assert( p->magic==VDBE_MAGIC_INIT );\n  assert( p->aOp!=0 || db->mallocFailed );\n  if( db->mallocFailed ){\n    if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);\n    return;\n  }\n  assert( p->nOp>0 );\n  assert( addr<p->nOp );\n  if( addr<0 ){\n    addr = p->nOp - 1;\n  }\n  pOp = &p->aOp[addr];\n  if( n>=0 || pOp->p4type ){\n    vdbeChangeP4Full(p, pOp, zP4, n);\n    return;\n  }\n  if( n==P4_INT32 ){\n    /* Note: this cast is safe, because the origin data point was an int\n    ** that was cast to a (const char *). */\n    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);\n    pOp->p4type = P4_INT32;\n  }else if( zP4!=0 ){\n    assert( n<0 );\n    pOp->p4.p = (void*)zP4;\n    pOp->p4type = (signed char)n;\n    if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);\n  }\n}\n\n/*\n** Change the P4 operand of the most recently coded instruction \n** to the value defined by the arguments.  This is a high-speed\n** version of sqlite3VdbeChangeP4().\n**\n** The P4 operand must not have been previously defined.  And the new\n** P4 must not be P4_INT32.  Use sqlite3VdbeChangeP4() in either of\n** those cases.\n*/\nSQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){\n  VdbeOp *pOp;\n  assert( n!=P4_INT32 && n!=P4_VTAB );\n  assert( n<=0 );\n  if( p->db->mallocFailed ){\n    freeP4(p->db, n, pP4);\n  }else{\n    assert( pP4!=0 );\n    assert( p->nOp>0 );\n    pOp = &p->aOp[p->nOp-1];\n    assert( pOp->p4type==P4_NOTUSED );\n    pOp->p4type = n;\n    pOp->p4.p = pP4;\n  }\n}\n\n/*\n** Set the P4 on the most recently added opcode to the KeyInfo for the\n** index given.\n*/\nSQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){\n  Vdbe *v = pParse->pVdbe;\n  KeyInfo *pKeyInfo;\n  assert( v!=0 );\n  assert( pIdx!=0 );\n  pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);\n  if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);\n}\n\n#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS\n/*\n** Change the comment on the most recently coded instruction.  Or\n** insert a No-op and add the comment to that new instruction.  This\n** makes the code easier to read during debugging.  None of this happens\n** in a production build.\n*/\nstatic void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){\n  assert( p->nOp>0 || p->aOp==0 );\n  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed\n          || p->pParse->nErr>0 );\n  if( p->nOp ){\n    assert( p->aOp );\n    sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);\n    p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);\n  }\n}\nSQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){\n  va_list ap;\n  if( p ){\n    va_start(ap, zFormat);\n    vdbeVComment(p, zFormat, ap);\n    va_end(ap);\n  }\n}\nSQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){\n  va_list ap;\n  if( p ){\n    sqlite3VdbeAddOp0(p, OP_Noop);\n    va_start(ap, zFormat);\n    vdbeVComment(p, zFormat, ap);\n    va_end(ap);\n  }\n}\n#endif  /* NDEBUG */\n\n#ifdef SQLITE_VDBE_COVERAGE\n/*\n** Set the value if the iSrcLine field for the previously coded instruction.\n*/\nSQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){\n  sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;\n}\n#endif /* SQLITE_VDBE_COVERAGE */\n\n/*\n** Return the opcode for a given address.  If the address is -1, then\n** return the most recently inserted opcode.\n**\n** If a memory allocation error has occurred prior to the calling of this\n** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode\n** is readable but not writable, though it is cast to a writable value.\n** The return of a dummy opcode allows the call to continue functioning\n** after an OOM fault without having to check to see if the return from \n** this routine is a valid pointer.  But because the dummy.opcode is 0,\n** dummy will never be written to.  This is verified by code inspection and\n** by running with Valgrind.\n*/\nSQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){\n  /* C89 specifies that the constant \"dummy\" will be initialized to all\n  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */\n  static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */\n  assert( p->magic==VDBE_MAGIC_INIT );\n  if( addr<0 ){\n    addr = p->nOp - 1;\n  }\n  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );\n  if( p->db->mallocFailed ){\n    return (VdbeOp*)&dummy;\n  }else{\n    return &p->aOp[addr];\n  }\n}\n\n#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)\n/*\n** Return an integer value for one of the parameters to the opcode pOp\n** determined by character c.\n*/\nstatic int translateP(char c, const Op *pOp){\n  if( c=='1' ) return pOp->p1;\n  if( c=='2' ) return pOp->p2;\n  if( c=='3' ) return pOp->p3;\n  if( c=='4' ) return pOp->p4.i;\n  return pOp->p5;\n}\n\n/*\n** Compute a string for the \"comment\" field of a VDBE opcode listing.\n**\n** The Synopsis: field in comments in the vdbe.c source file gets converted\n** to an extra string that is appended to the sqlite3OpcodeName().  In the\n** absence of other comments, this synopsis becomes the comment on the opcode.\n** Some translation occurs:\n**\n**       \"PX\"      ->  \"r[X]\"\n**       \"PX@PY\"   ->  \"r[X..X+Y-1]\"  or \"r[x]\" if y is 0 or 1\n**       \"PX@PY+1\" ->  \"r[X..X+Y]\"    or \"r[x]\" if y is 0\n**       \"PY..PY\"  ->  \"r[X..Y]\"      or \"r[x]\" if y<=x\n*/\nSQLITE_PRIVATE char *sqlite3VdbeDisplayComment(\n  sqlite3 *db,       /* Optional - Oom error reporting only */\n  const Op *pOp,     /* The opcode to be commented */\n  const char *zP4    /* Previously obtained value for P4 */\n){\n  const char *zOpName;\n  const char *zSynopsis;\n  int nOpName;\n  int ii;\n  char zAlt[50];\n  StrAccum x;\n\n  sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);\n  zOpName = sqlite3OpcodeName(pOp->opcode);\n  nOpName = sqlite3Strlen30(zOpName);\n  if( zOpName[nOpName+1] ){\n    int seenCom = 0;\n    char c;\n    zSynopsis = zOpName += nOpName + 1;\n    if( strncmp(zSynopsis,\"IF \",3)==0 ){\n      if( pOp->p5 & SQLITE_STOREP2 ){\n        sqlite3_snprintf(sizeof(zAlt), zAlt, \"r[P2] = (%s)\", zSynopsis+3);\n      }else{\n        sqlite3_snprintf(sizeof(zAlt), zAlt, \"if %s goto P2\", zSynopsis+3);\n      }\n      zSynopsis = zAlt;\n    }\n    for(ii=0; (c = zSynopsis[ii])!=0; ii++){\n      if( c=='P' ){\n        c = zSynopsis[++ii];\n        if( c=='4' ){\n          sqlite3_str_appendall(&x, zP4);\n        }else if( c=='X' ){\n          sqlite3_str_appendall(&x, pOp->zComment);\n          seenCom = 1;\n        }else{\n          int v1 = translateP(c, pOp);\n          int v2;\n          if( strncmp(zSynopsis+ii+1, \"@P\", 2)==0 ){\n            ii += 3;\n            v2 = translateP(zSynopsis[ii], pOp);\n            if( strncmp(zSynopsis+ii+1,\"+1\",2)==0 ){\n              ii += 2;\n              v2++;\n            }\n            if( v2<2 ){\n              sqlite3_str_appendf(&x, \"%d\", v1);\n            }else{\n              sqlite3_str_appendf(&x, \"%d..%d\", v1, v1+v2-1);\n            }\n          }else if( strncmp(zSynopsis+ii+1, \"@NP\", 3)==0 ){\n            sqlite3_context *pCtx = pOp->p4.pCtx;\n            if( pOp->p4type!=P4_FUNCCTX || pCtx->argc==1 ){\n              sqlite3_str_appendf(&x, \"%d\", v1);\n            }else if( pCtx->argc>1 ){\n              sqlite3_str_appendf(&x, \"%d..%d\", v1, v1+pCtx->argc-1);\n            }else{\n              assert( x.nChar>2 );\n              x.nChar -= 2;\n              ii++;\n            }\n            ii += 3;\n          }else{\n            sqlite3_str_appendf(&x, \"%d\", v1);\n            if( strncmp(zSynopsis+ii+1, \"..P3\", 4)==0 && pOp->p3==0 ){\n              ii += 4;\n            }\n          }\n        }\n      }else{\n        sqlite3_str_appendchar(&x, 1, c);\n      }\n    }\n    if( !seenCom && pOp->zComment ){\n      sqlite3_str_appendf(&x, \"; %s\", pOp->zComment);\n    }\n  }else if( pOp->zComment ){\n    sqlite3_str_appendall(&x, pOp->zComment);\n  }\n  if( (x.accError & SQLITE_NOMEM)!=0 && db!=0 ){\n    sqlite3OomFault(db);\n  }\n  return sqlite3StrAccumFinish(&x);\n}\n#endif /* SQLITE_ENABLE_EXPLAIN_COMMENTS */\n\n#if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)\n/*\n** Translate the P4.pExpr value for an OP_CursorHint opcode into text\n** that can be displayed in the P4 column of EXPLAIN output.\n*/\nstatic void displayP4Expr(StrAccum *p, Expr *pExpr){\n  const char *zOp = 0;\n  switch( pExpr->op ){\n    case TK_STRING:\n      sqlite3_str_appendf(p, \"%Q\", pExpr->u.zToken);\n      break;\n    case TK_INTEGER:\n      sqlite3_str_appendf(p, \"%d\", pExpr->u.iValue);\n      break;\n    case TK_NULL:\n      sqlite3_str_appendf(p, \"NULL\");\n      break;\n    case TK_REGISTER: {\n      sqlite3_str_appendf(p, \"r[%d]\", pExpr->iTable);\n      break;\n    }\n    case TK_COLUMN: {\n      if( pExpr->iColumn<0 ){\n        sqlite3_str_appendf(p, \"rowid\");\n      }else{\n        sqlite3_str_appendf(p, \"c%d\", (int)pExpr->iColumn);\n      }\n      break;\n    }\n    case TK_LT:      zOp = \"LT\";      break;\n    case TK_LE:      zOp = \"LE\";      break;\n    case TK_GT:      zOp = \"GT\";      break;\n    case TK_GE:      zOp = \"GE\";      break;\n    case TK_NE:      zOp = \"NE\";      break;\n    case TK_EQ:      zOp = \"EQ\";      break;\n    case TK_IS:      zOp = \"IS\";      break;\n    case TK_ISNOT:   zOp = \"ISNOT\";   break;\n    case TK_AND:     zOp = \"AND\";     break;\n    case TK_OR:      zOp = \"OR\";      break;\n    case TK_PLUS:    zOp = \"ADD\";     break;\n    case TK_STAR:    zOp = \"MUL\";     break;\n    case TK_MINUS:   zOp = \"SUB\";     break;\n    case TK_REM:     zOp = \"REM\";     break;\n    case TK_BITAND:  zOp = \"BITAND\";  break;\n    case TK_BITOR:   zOp = \"BITOR\";   break;\n    case TK_SLASH:   zOp = \"DIV\";     break;\n    case TK_LSHIFT:  zOp = \"LSHIFT\";  break;\n    case TK_RSHIFT:  zOp = \"RSHIFT\";  break;\n    case TK_CONCAT:  zOp = \"CONCAT\";  break;\n    case TK_UMINUS:  zOp = \"MINUS\";   break;\n    case TK_UPLUS:   zOp = \"PLUS\";    break;\n    case TK_BITNOT:  zOp = \"BITNOT\";  break;\n    case TK_NOT:     zOp = \"NOT\";     break;\n    case TK_ISNULL:  zOp = \"ISNULL\";  break;\n    case TK_NOTNULL: zOp = \"NOTNULL\"; break;\n\n    default:\n      sqlite3_str_appendf(p, \"%s\", \"expr\");\n      break;\n  }\n\n  if( zOp ){\n    sqlite3_str_appendf(p, \"%s(\", zOp);\n    displayP4Expr(p, pExpr->pLeft);\n    if( pExpr->pRight ){\n      sqlite3_str_append(p, \",\", 1);\n      displayP4Expr(p, pExpr->pRight);\n    }\n    sqlite3_str_append(p, \")\", 1);\n  }\n}\n#endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */\n\n\n#if VDBE_DISPLAY_P4\n/*\n** Compute a string that describes the P4 parameter for an opcode.\n** Use zTemp for any required temporary buffer space.\n*/\nSQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3 *db, Op *pOp){\n  char *zP4 = 0;\n  StrAccum x;\n\n  sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);\n  switch( pOp->p4type ){\n    case P4_KEYINFO: {\n      int j;\n      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;\n      assert( pKeyInfo->aSortFlags!=0 );\n      sqlite3_str_appendf(&x, \"k(%d\", pKeyInfo->nKeyField);\n      for(j=0; j<pKeyInfo->nKeyField; j++){\n        CollSeq *pColl = pKeyInfo->aColl[j];\n        const char *zColl = pColl ? pColl->zName : \"\";\n        if( strcmp(zColl, \"BINARY\")==0 ) zColl = \"B\";\n        sqlite3_str_appendf(&x, \",%s%s%s\", \n               (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_DESC) ? \"-\" : \"\", \n               (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_BIGNULL)? \"N.\" : \"\", \n               zColl);\n      }\n      sqlite3_str_append(&x, \")\", 1);\n      break;\n    }\n#ifdef SQLITE_ENABLE_CURSOR_HINTS\n    case P4_EXPR: {\n      displayP4Expr(&x, pOp->p4.pExpr);\n      break;\n    }\n#endif\n    case P4_COLLSEQ: {\n      static const char *const encnames[] = {\"?\", \"8\", \"16LE\", \"16BE\"};\n      CollSeq *pColl = pOp->p4.pColl;\n      assert( pColl->enc>=0 && pColl->enc<4 );\n      sqlite3_str_appendf(&x, \"%.18s-%s\", pColl->zName,\n                          encnames[pColl->enc]);\n      break;\n    }\n    case P4_FUNCDEF: {\n      FuncDef *pDef = pOp->p4.pFunc;\n      sqlite3_str_appendf(&x, \"%s(%d)\", pDef->zName, pDef->nArg);\n      break;\n    }\n    case P4_FUNCCTX: {\n      FuncDef *pDef = pOp->p4.pCtx->pFunc;\n      sqlite3_str_appendf(&x, \"%s(%d)\", pDef->zName, pDef->nArg);\n      break;\n    }\n    case P4_INT64: {\n      sqlite3_str_appendf(&x, \"%lld\", *pOp->p4.pI64);\n      break;\n    }\n    case P4_INT32: {\n      sqlite3_str_appendf(&x, \"%d\", pOp->p4.i);\n      break;\n    }\n    case P4_REAL: {\n      sqlite3_str_appendf(&x, \"%.16g\", *pOp->p4.pReal);\n      break;\n    }\n    case P4_MEM: {\n      Mem *pMem = pOp->p4.pMem;\n      if( pMem->flags & MEM_Str ){\n        zP4 = pMem->z;\n      }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){\n        sqlite3_str_appendf(&x, \"%lld\", pMem->u.i);\n      }else if( pMem->flags & MEM_Real ){\n        sqlite3_str_appendf(&x, \"%.16g\", pMem->u.r);\n      }else if( pMem->flags & MEM_Null ){\n        zP4 = \"NULL\";\n      }else{\n        assert( pMem->flags & MEM_Blob );\n        zP4 = \"(blob)\";\n      }\n      break;\n    }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    case P4_VTAB: {\n      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;\n      sqlite3_str_appendf(&x, \"vtab:%p\", pVtab);\n      break;\n    }\n#endif\n    case P4_INTARRAY: {\n      int i;\n      int *ai = pOp->p4.ai;\n      int n = ai[0];   /* The first element of an INTARRAY is always the\n                       ** count of the number of elements to follow */\n      for(i=1; i<=n; i++){\n        sqlite3_str_appendf(&x, \"%c%d\", (i==1 ? '[' : ','), ai[i]);\n      }\n      sqlite3_str_append(&x, \"]\", 1);\n      break;\n    }\n    case P4_SUBPROGRAM: {\n      zP4 = \"program\";\n      break;\n    }\n    case P4_DYNBLOB:\n    case P4_ADVANCE: {\n      break;\n    }\n    case P4_TABLE: {\n      zP4 = pOp->p4.pTab->zName;\n      break;\n    }\n    default: {\n      zP4 = pOp->p4.z;\n    }\n  }\n  if( zP4 ) sqlite3_str_appendall(&x, zP4);\n  if( (x.accError & SQLITE_NOMEM)!=0 ){\n    sqlite3OomFault(db);\n  }\n  return sqlite3StrAccumFinish(&x);\n}\n#endif /* VDBE_DISPLAY_P4 */\n\n/*\n** Declare to the Vdbe that the BTree object at db->aDb[i] is used.\n**\n** The prepared statements need to know in advance the complete set of\n** attached databases that will be use.  A mask of these databases\n** is maintained in p->btreeMask.  The p->lockMask value is the subset of\n** p->btreeMask of databases that will require a lock.\n*/\nSQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){\n  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );\n  assert( i<(int)sizeof(p->btreeMask)*8 );\n  DbMaskSet(p->btreeMask, i);\n  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){\n    DbMaskSet(p->lockMask, i);\n  }\n}\n\n#if !defined(SQLITE_OMIT_SHARED_CACHE)\n/*\n** If SQLite is compiled to support shared-cache mode and to be threadsafe,\n** this routine obtains the mutex associated with each BtShared structure\n** that may be accessed by the VM passed as an argument. In doing so it also\n** sets the BtShared.db member of each of the BtShared structures, ensuring\n** that the correct busy-handler callback is invoked if required.\n**\n** If SQLite is not threadsafe but does support shared-cache mode, then\n** sqlite3BtreeEnter() is invoked to set the BtShared.db variables\n** of all of BtShared structures accessible via the database handle \n** associated with the VM.\n**\n** If SQLite is not threadsafe and does not support shared-cache mode, this\n** function is a no-op.\n**\n** The p->btreeMask field is a bitmask of all btrees that the prepared \n** statement p will ever use.  Let N be the number of bits in p->btreeMask\n** corresponding to btrees that use shared cache.  Then the runtime of\n** this routine is N*N.  But as N is rarely more than 1, this should not\n** be a problem.\n*/\nSQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){\n  int i;\n  sqlite3 *db;\n  Db *aDb;\n  int nDb;\n  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */\n  db = p->db;\n  aDb = db->aDb;\n  nDb = db->nDb;\n  for(i=0; i<nDb; i++){\n    if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){\n      sqlite3BtreeEnter(aDb[i].pBt);\n    }\n  }\n}\n#endif\n\n#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0\n/*\n** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().\n*/\nstatic SQLITE_NOINLINE void vdbeLeave(Vdbe *p){\n  int i;\n  sqlite3 *db;\n  Db *aDb;\n  int nDb;\n  db = p->db;\n  aDb = db->aDb;\n  nDb = db->nDb;\n  for(i=0; i<nDb; i++){\n    if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){\n      sqlite3BtreeLeave(aDb[i].pBt);\n    }\n  }\n}\nSQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){\n  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */\n  vdbeLeave(p);\n}\n#endif\n\n#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)\n/*\n** Print a single opcode.  This routine is used for debugging only.\n*/\nSQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){\n  char *zP4;\n  char *zCom;\n  sqlite3 dummyDb;\n  static const char *zFormat1 = \"%4d %-13s %4d %4d %4d %-13s %.2X %s\\n\";\n  if( pOut==0 ) pOut = stdout;\n  sqlite3BeginBenignMalloc();\n  dummyDb.mallocFailed = 1;\n  zP4 = sqlite3VdbeDisplayP4(&dummyDb, pOp);\n#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS\n  zCom = sqlite3VdbeDisplayComment(0, pOp, zP4);\n#else\n  zCom = 0;\n#endif\n  /* NB:  The sqlite3OpcodeName() function is implemented by code created\n  ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the\n  ** information from the vdbe.c source text */\n  fprintf(pOut, zFormat1, pc, \n      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, \n      zP4 ? zP4 : \"\", pOp->p5,\n      zCom ? zCom : \"\"\n  );\n  fflush(pOut);\n  sqlite3_free(zP4);\n  sqlite3_free(zCom);\n  sqlite3EndBenignMalloc();\n}\n#endif\n\n/*\n** Initialize an array of N Mem element.\n*/\nstatic void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){\n  while( (N--)>0 ){\n    p->db = db;\n    p->flags = flags;\n    p->szMalloc = 0;\n#ifdef SQLITE_DEBUG\n    p->pScopyFrom = 0;\n#endif\n    p++;\n  }\n}\n\n/*\n** Release an array of N Mem elements\n*/\nstatic void releaseMemArray(Mem *p, int N){\n  if( p && N ){\n    Mem *pEnd = &p[N];\n    sqlite3 *db = p->db;\n    if( db->pnBytesFreed ){\n      do{\n        if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);\n      }while( (++p)<pEnd );\n      return;\n    }\n    do{\n      assert( (&p[1])==pEnd || p[0].db==p[1].db );\n      assert( sqlite3VdbeCheckMemInvariants(p) );\n\n      /* This block is really an inlined version of sqlite3VdbeMemRelease()\n      ** that takes advantage of the fact that the memory cell value is \n      ** being set to NULL after releasing any dynamic resources.\n      **\n      ** The justification for duplicating code is that according to \n      ** callgrind, this causes a certain test case to hit the CPU 4.7 \n      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if \n      ** sqlite3MemRelease() were called from here. With -O2, this jumps\n      ** to 6.6 percent. The test case is inserting 1000 rows into a table \n      ** with no indexes using a single prepared INSERT statement, bind() \n      ** and reset(). Inserts are grouped into a transaction.\n      */\n      testcase( p->flags & MEM_Agg );\n      testcase( p->flags & MEM_Dyn );\n      testcase( p->xDel==sqlite3VdbeFrameMemDel );\n      if( p->flags&(MEM_Agg|MEM_Dyn) ){\n        sqlite3VdbeMemRelease(p);\n      }else if( p->szMalloc ){\n        sqlite3DbFreeNN(db, p->zMalloc);\n        p->szMalloc = 0;\n      }\n\n      p->flags = MEM_Undefined;\n    }while( (++p)<pEnd );\n  }\n}\n\n#ifdef SQLITE_DEBUG\n/*\n** Verify that pFrame is a valid VdbeFrame pointer.  Return true if it is\n** and false if something is wrong.\n**\n** This routine is intended for use inside of assert() statements only.\n*/\nSQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame *pFrame){\n  if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0;\n  return 1;\n}\n#endif\n\n\n/*\n** This is a destructor on a Mem object (which is really an sqlite3_value)\n** that deletes the Frame object that is attached to it as a blob.\n**\n** This routine does not delete the Frame right away.  It merely adds the\n** frame to a list of frames to be deleted when the Vdbe halts.\n*/\nSQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void *pArg){\n  VdbeFrame *pFrame = (VdbeFrame*)pArg;\n  assert( sqlite3VdbeFrameIsValid(pFrame) );\n  pFrame->pParent = pFrame->v->pDelFrame;\n  pFrame->v->pDelFrame = pFrame;\n}\n\n#if defined(SQLITE_ENABLE_BYTECODE_VTAB) || !defined(SQLITE_OMIT_EXPLAIN)\n/*\n** Locate the next opcode to be displayed in EXPLAIN or EXPLAIN\n** QUERY PLAN output.\n**\n** Return SQLITE_ROW on success.  Return SQLITE_DONE if there are no\n** more opcodes to be displayed.\n*/\nSQLITE_PRIVATE int sqlite3VdbeNextOpcode(\n  Vdbe *p,         /* The statement being explained */\n  Mem *pSub,       /* Storage for keeping track of subprogram nesting */\n  int eMode,       /* 0: normal.  1: EQP.  2:  TablesUsed */\n  int *piPc,       /* IN/OUT: Current rowid.  Overwritten with next rowid */\n  int *piAddr,     /* OUT: Write index into (*paOp)[] here */\n  Op **paOp        /* OUT: Write the opcode array here */\n){\n  int nRow;                            /* Stop when row count reaches this */\n  int nSub = 0;                        /* Number of sub-vdbes seen so far */\n  SubProgram **apSub = 0;              /* Array of sub-vdbes */\n  int i;                               /* Next instruction address */\n  int rc = SQLITE_OK;                  /* Result code */\n  Op *aOp = 0;                         /* Opcode array */\n  int iPc;                             /* Rowid.  Copy of value in *piPc */\n\n  /* When the number of output rows reaches nRow, that means the\n  ** listing has finished and sqlite3_step() should return SQLITE_DONE.\n  ** nRow is the sum of the number of rows in the main program, plus\n  ** the sum of the number of rows in all trigger subprograms encountered\n  ** so far.  The nRow value will increase as new trigger subprograms are\n  ** encountered, but p->pc will eventually catch up to nRow.\n  */\n  nRow = p->nOp;\n  if( pSub!=0 ){\n    if( pSub->flags&MEM_Blob ){\n      /* pSub is initiallly NULL.  It is initialized to a BLOB by\n      ** the P4_SUBPROGRAM processing logic below */\n      nSub = pSub->n/sizeof(Vdbe*);\n      apSub = (SubProgram **)pSub->z;\n    }\n    for(i=0; i<nSub; i++){\n      nRow += apSub[i]->nOp;\n    }\n  }\n  iPc = *piPc;\n  while(1){  /* Loop exits via break */\n    i = iPc++;\n    if( i>=nRow ){\n      p->rc = SQLITE_OK;\n      rc = SQLITE_DONE;\n      break;\n    }\n    if( i<p->nOp ){\n      /* The rowid is small enough that we are still in the\n      ** main program. */\n      aOp = p->aOp;\n    }else{\n      /* We are currently listing subprograms.  Figure out which one and\n      ** pick up the appropriate opcode. */\n      int j;\n      i -= p->nOp;\n      assert( apSub!=0 );\n      assert( nSub>0 );\n      for(j=0; i>=apSub[j]->nOp; j++){\n        i -= apSub[j]->nOp;\n        assert( i<apSub[j]->nOp || j+1<nSub );\n      }\n      aOp = apSub[j]->aOp;\n    }\n\n    /* When an OP_Program opcode is encounter (the only opcode that has\n    ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms\n    ** kept in p->aMem[9].z to hold the new program - assuming this subprogram\n    ** has not already been seen.\n    */\n    if( pSub!=0 && aOp[i].p4type==P4_SUBPROGRAM ){\n      int nByte = (nSub+1)*sizeof(SubProgram*);\n      int j;\n      for(j=0; j<nSub; j++){\n        if( apSub[j]==aOp[i].p4.pProgram ) break;\n      }\n      if( j==nSub ){\n        p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);\n        if( p->rc!=SQLITE_OK ){\n          rc = SQLITE_ERROR;\n          break;\n        }\n        apSub = (SubProgram **)pSub->z;\n        apSub[nSub++] = aOp[i].p4.pProgram;\n        MemSetTypeFlag(pSub, MEM_Blob);\n        pSub->n = nSub*sizeof(SubProgram*);\n        nRow += aOp[i].p4.pProgram->nOp;\n      }\n    }\n    if( eMode==0 ) break;\n#ifdef SQLITE_ENABLE_BYTECODE_VTAB\n    if( eMode==2 ){\n      Op *pOp = aOp + i;\n      if( pOp->opcode==OP_OpenRead ) break;\n      if( pOp->opcode==OP_OpenWrite && (pOp->p5 & OPFLAG_P2ISREG)==0 ) break;\n      if( pOp->opcode==OP_ReopenIdx ) break;      \n    }else\n#endif\n    {\n      assert( eMode==1 );\n      if( aOp[i].opcode==OP_Explain ) break;\n      if( aOp[i].opcode==OP_Init && iPc>1 ) break;\n    }\n  }\n  *piPc = iPc;\n  *piAddr = i;\n  *paOp = aOp;\n  return rc;\n}\n#endif /* SQLITE_ENABLE_BYTECODE_VTAB || !SQLITE_OMIT_EXPLAIN */\n\n\n/*\n** Delete a VdbeFrame object and its contents. VdbeFrame objects are\n** allocated by the OP_Program opcode in sqlite3VdbeExec().\n*/\nSQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){\n  int i;\n  Mem *aMem = VdbeFrameMem(p);\n  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];\n  assert( sqlite3VdbeFrameIsValid(p) );\n  for(i=0; i<p->nChildCsr; i++){\n    sqlite3VdbeFreeCursor(p->v, apCsr[i]);\n  }\n  releaseMemArray(aMem, p->nChildMem);\n  sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);\n  sqlite3DbFree(p->v->db, p);\n}\n\n#ifndef SQLITE_OMIT_EXPLAIN\n/*\n** Give a listing of the program in the virtual machine.\n**\n** The interface is the same as sqlite3VdbeExec().  But instead of\n** running the code, it invokes the callback once for each instruction.\n** This feature is used to implement \"EXPLAIN\".\n**\n** When p->explain==1, each instruction is listed.  When\n** p->explain==2, only OP_Explain instructions are listed and these\n** are shown in a different format.  p->explain==2 is used to implement\n** EXPLAIN QUERY PLAN.\n** 2018-04-24:  In p->explain==2 mode, the OP_Init opcodes of triggers\n** are also shown, so that the boundaries between the main program and\n** each trigger are clear.\n**\n** When p->explain==1, first the main program is listed, then each of\n** the trigger subprograms are listed one by one.\n*/\nSQLITE_PRIVATE int sqlite3VdbeList(\n  Vdbe *p                   /* The VDBE */\n){\n  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */\n  sqlite3 *db = p->db;                 /* The database connection */\n  int i;                               /* Loop counter */\n  int rc = SQLITE_OK;                  /* Return code */\n  Mem *pMem = &p->aMem[1];             /* First Mem of result set */\n  int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);\n  Op *aOp;                             /* Array of opcodes */\n  Op *pOp;                             /* Current opcode */\n\n  assert( p->explain );\n  assert( p->magic==VDBE_MAGIC_RUN );\n  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );\n\n  /* Even though this opcode does not use dynamic strings for\n  ** the result, result columns may become dynamic if the user calls\n  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.\n  */\n  releaseMemArray(pMem, 8);\n  p->pResultSet = 0;\n\n  if( p->rc==SQLITE_NOMEM ){\n    /* This happens if a malloc() inside a call to sqlite3_column_text() or\n    ** sqlite3_column_text16() failed.  */\n    sqlite3OomFault(db);\n    return SQLITE_ERROR;\n  }\n\n  if( bListSubprogs ){\n    /* The first 8 memory cells are used for the result set.  So we will\n    ** commandeer the 9th cell to use as storage for an array of pointers\n    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9\n    ** cells.  */\n    assert( p->nMem>9 );\n    pSub = &p->aMem[9];\n  }else{\n    pSub = 0;\n  }\n\n  /* Figure out which opcode is next to display */\n  rc = sqlite3VdbeNextOpcode(p, pSub, p->explain==2, &p->pc, &i, &aOp);\n\n  if( rc==SQLITE_OK ){\n    pOp = aOp + i;\n    if( AtomicLoad(&db->u1.isInterrupted) ){\n      p->rc = SQLITE_INTERRUPT;\n      rc = SQLITE_ERROR;\n      sqlite3VdbeError(p, sqlite3ErrStr(p->rc));\n    }else{\n      char *zP4 = sqlite3VdbeDisplayP4(db, pOp);\n      if( p->explain==2 ){\n        sqlite3VdbeMemSetInt64(pMem, pOp->p1);\n        sqlite3VdbeMemSetInt64(pMem+1, pOp->p2);\n        sqlite3VdbeMemSetInt64(pMem+2, pOp->p3);\n        sqlite3VdbeMemSetStr(pMem+3, zP4, -1, SQLITE_UTF8, sqlite3_free);     \n        p->nResColumn = 4;\n      }else{\n        sqlite3VdbeMemSetInt64(pMem+0, i);\n        sqlite3VdbeMemSetStr(pMem+1, (char*)sqlite3OpcodeName(pOp->opcode),\n                             -1, SQLITE_UTF8, SQLITE_STATIC);\n        sqlite3VdbeMemSetInt64(pMem+2, pOp->p1);\n        sqlite3VdbeMemSetInt64(pMem+3, pOp->p2);\n        sqlite3VdbeMemSetInt64(pMem+4, pOp->p3);\n        /* pMem+5 for p4 is done last */\n        sqlite3VdbeMemSetInt64(pMem+6, pOp->p5);\n#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS\n        {\n          char *zCom = sqlite3VdbeDisplayComment(db, pOp, zP4);\n          sqlite3VdbeMemSetStr(pMem+7, zCom, -1, SQLITE_UTF8, sqlite3_free);\n        }\n#else\n        sqlite3VdbeMemSetNull(pMem+7);\n#endif\n        sqlite3VdbeMemSetStr(pMem+5, zP4, -1, SQLITE_UTF8, sqlite3_free);\n        p->nResColumn = 8;\n      }\n      p->pResultSet = pMem;\n      if( db->mallocFailed ){\n        p->rc = SQLITE_NOMEM;\n        rc = SQLITE_ERROR;\n      }else{\n        p->rc = SQLITE_OK;\n        rc = SQLITE_ROW;\n      }\n    }\n  }\n  return rc;\n}\n#endif /* SQLITE_OMIT_EXPLAIN */\n\n#ifdef SQLITE_DEBUG\n/*\n** Print the SQL that was used to generate a VDBE program.\n*/\nSQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){\n  const char *z = 0;\n  if( p->zSql ){\n    z = p->zSql;\n  }else if( p->nOp>=1 ){\n    const VdbeOp *pOp = &p->aOp[0];\n    if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){\n      z = pOp->p4.z;\n      while( sqlite3Isspace(*z) ) z++;\n    }\n  }\n  if( z ) printf(\"SQL: [%s]\\n\", z);\n}\n#endif\n\n#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)\n/*\n** Print an IOTRACE message showing SQL content.\n*/\nSQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){\n  int nOp = p->nOp;\n  VdbeOp *pOp;\n  if( sqlite3IoTrace==0 ) return;\n  if( nOp<1 ) return;\n  pOp = &p->aOp[0];\n  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){\n    int i, j;\n    char z[1000];\n    sqlite3_snprintf(sizeof(z), z, \"%s\", pOp->p4.z);\n    for(i=0; sqlite3Isspace(z[i]); i++){}\n    for(j=0; z[i]; i++){\n      if( sqlite3Isspace(z[i]) ){\n        if( z[i-1]!=' ' ){\n          z[j++] = ' ';\n        }\n      }else{\n        z[j++] = z[i];\n      }\n    }\n    z[j] = 0;\n    sqlite3IoTrace(\"SQL %s\\n\", z);\n  }\n}\n#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */\n\n/* An instance of this object describes bulk memory available for use\n** by subcomponents of a prepared statement.  Space is allocated out\n** of a ReusableSpace object by the allocSpace() routine below.\n*/\nstruct ReusableSpace {\n  u8 *pSpace;            /* Available memory */\n  sqlite3_int64 nFree;   /* Bytes of available memory */\n  sqlite3_int64 nNeeded; /* Total bytes that could not be allocated */\n};\n\n/* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf\n** from the ReusableSpace object.  Return a pointer to the allocated\n** memory on success.  If insufficient memory is available in the\n** ReusableSpace object, increase the ReusableSpace.nNeeded\n** value by the amount needed and return NULL.\n**\n** If pBuf is not initially NULL, that means that the memory has already\n** been allocated by a prior call to this routine, so just return a copy\n** of pBuf and leave ReusableSpace unchanged.\n**\n** This allocator is employed to repurpose unused slots at the end of the\n** opcode array of prepared state for other memory needs of the prepared\n** statement.\n*/\nstatic void *allocSpace(\n  struct ReusableSpace *p,  /* Bulk memory available for allocation */\n  void *pBuf,               /* Pointer to a prior allocation */\n  sqlite3_int64 nByte       /* Bytes of memory needed */\n){\n  assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );\n  if( pBuf==0 ){\n    nByte = ROUND8(nByte);\n    if( nByte <= p->nFree ){\n      p->nFree -= nByte;\n      pBuf = &p->pSpace[p->nFree];\n    }else{\n      p->nNeeded += nByte;\n    }\n  }\n  assert( EIGHT_BYTE_ALIGNMENT(pBuf) );\n  return pBuf;\n}\n\n/*\n** Rewind the VDBE back to the beginning in preparation for\n** running it.\n*/\nSQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){\n#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)\n  int i;\n#endif\n  assert( p!=0 );\n  assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );\n\n  /* There should be at least one opcode.\n  */\n  assert( p->nOp>0 );\n\n  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */\n  p->magic = VDBE_MAGIC_RUN;\n\n#ifdef SQLITE_DEBUG\n  for(i=0; i<p->nMem; i++){\n    assert( p->aMem[i].db==p->db );\n  }\n#endif\n  p->pc = -1;\n  p->rc = SQLITE_OK;\n  p->errorAction = OE_Abort;\n  p->nChange = 0;\n  p->cacheCtr = 1;\n  p->minWriteFileFormat = 255;\n  p->iStatement = 0;\n  p->nFkConstraint = 0;\n#ifdef VDBE_PROFILE\n  for(i=0; i<p->nOp; i++){\n    p->aOp[i].cnt = 0;\n    p->aOp[i].cycles = 0;\n  }\n#endif\n}\n\n/*\n** Prepare a virtual machine for execution for the first time after\n** creating the virtual machine.  This involves things such\n** as allocating registers and initializing the program counter.\n** After the VDBE has be prepped, it can be executed by one or more\n** calls to sqlite3VdbeExec().  \n**\n** This function may be called exactly once on each virtual machine.\n** After this routine is called the VM has been \"packaged\" and is ready\n** to run.  After this routine is called, further calls to \n** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects\n** the Vdbe from the Parse object that helped generate it so that the\n** the Vdbe becomes an independent entity and the Parse object can be\n** destroyed.\n**\n** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back\n** to its initial state after it has been run.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMakeReady(\n  Vdbe *p,                       /* The VDBE */\n  Parse *pParse                  /* Parsing context */\n){\n  sqlite3 *db;                   /* The database connection */\n  int nVar;                      /* Number of parameters */\n  int nMem;                      /* Number of VM memory registers */\n  int nCursor;                   /* Number of cursors required */\n  int nArg;                      /* Number of arguments in subprograms */\n  int n;                         /* Loop counter */\n  struct ReusableSpace x;        /* Reusable bulk memory */\n\n  assert( p!=0 );\n  assert( p->nOp>0 );\n  assert( pParse!=0 );\n  assert( p->magic==VDBE_MAGIC_INIT );\n  assert( pParse==p->pParse );\n  db = p->db;\n  assert( db->mallocFailed==0 );\n  nVar = pParse->nVar;\n  nMem = pParse->nMem;\n  nCursor = pParse->nTab;\n  nArg = pParse->nMaxArg;\n  \n  /* Each cursor uses a memory cell.  The first cursor (cursor 0) can\n  ** use aMem[0] which is not otherwise used by the VDBE program.  Allocate\n  ** space at the end of aMem[] for cursors 1 and greater.\n  ** See also: allocateCursor().\n  */\n  nMem += nCursor;\n  if( nCursor==0 && nMem>0 ) nMem++;  /* Space for aMem[0] even if not used */\n\n  /* Figure out how much reusable memory is available at the end of the\n  ** opcode array.  This extra memory will be reallocated for other elements\n  ** of the prepared statement.\n  */\n  n = ROUND8(sizeof(Op)*p->nOp);              /* Bytes of opcode memory used */\n  x.pSpace = &((u8*)p->aOp)[n];               /* Unused opcode memory */\n  assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );\n  x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n);  /* Bytes of unused memory */\n  assert( x.nFree>=0 );\n  assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );\n\n  resolveP2Values(p, &nArg);\n  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);\n  if( pParse->explain ){\n    static const char * const azColName[] = {\n       \"addr\", \"opcode\", \"p1\", \"p2\", \"p3\", \"p4\", \"p5\", \"comment\",\n       \"id\", \"parent\", \"notused\", \"detail\"\n    };\n    int iFirst, mx, i;\n    if( nMem<10 ) nMem = 10;\n    p->explain = pParse->explain;\n    if( pParse->explain==2 ){\n      sqlite3VdbeSetNumCols(p, 4);\n      iFirst = 8;\n      mx = 12;\n    }else{\n      sqlite3VdbeSetNumCols(p, 8);\n      iFirst = 0;\n      mx = 8;\n    }\n    for(i=iFirst; i<mx; i++){\n      sqlite3VdbeSetColName(p, i-iFirst, COLNAME_NAME,\n                            azColName[i], SQLITE_STATIC);\n    }\n  }\n  p->expired = 0;\n\n  /* Memory for registers, parameters, cursor, etc, is allocated in one or two\n  ** passes.  On the first pass, we try to reuse unused memory at the \n  ** end of the opcode array.  If we are unable to satisfy all memory\n  ** requirements by reusing the opcode array tail, then the second\n  ** pass will fill in the remainder using a fresh memory allocation.  \n  **\n  ** This two-pass approach that reuses as much memory as possible from\n  ** the leftover memory at the end of the opcode array.  This can significantly\n  ** reduce the amount of memory held by a prepared statement.\n  */\n  x.nNeeded = 0;\n  p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem));\n  p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem));\n  p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*));\n  p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*));\n#ifdef SQLITE_ENABLE_STMT_SCANSTATUS\n  p->anExec = allocSpace(&x, 0, p->nOp*sizeof(i64));\n#endif\n  if( x.nNeeded ){\n    x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);\n    x.nFree = x.nNeeded;\n    if( !db->mallocFailed ){\n      p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));\n      p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));\n      p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));\n      p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));\n#ifdef SQLITE_ENABLE_STMT_SCANSTATUS\n      p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));\n#endif\n    }\n  }\n\n  p->pVList = pParse->pVList;\n  pParse->pVList =  0;\n  if( db->mallocFailed ){\n    p->nVar = 0;\n    p->nCursor = 0;\n    p->nMem = 0;\n  }else{\n    p->nCursor = nCursor;\n    p->nVar = (ynVar)nVar;\n    initMemArray(p->aVar, nVar, db, MEM_Null);\n    p->nMem = nMem;\n    initMemArray(p->aMem, nMem, db, MEM_Undefined);\n    memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));\n#ifdef SQLITE_ENABLE_STMT_SCANSTATUS\n    memset(p->anExec, 0, p->nOp*sizeof(i64));\n#endif\n  }\n  sqlite3VdbeRewind(p);\n}\n\n/*\n** Close a VDBE cursor and release all the resources that cursor \n** happens to hold.\n*/\nSQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){\n  if( pCx==0 ){\n    return;\n  }\n  assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );\n  switch( pCx->eCurType ){\n    case CURTYPE_SORTER: {\n      sqlite3VdbeSorterClose(p->db, pCx);\n      break;\n    }\n    case CURTYPE_BTREE: {\n      if( pCx->isEphemeral ){\n        if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);\n        /* The pCx->pCursor will be close automatically, if it exists, by\n        ** the call above. */\n      }else{\n        assert( pCx->uc.pCursor!=0 );\n        sqlite3BtreeCloseCursor(pCx->uc.pCursor);\n      }\n      break;\n    }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    case CURTYPE_VTAB: {\n      sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;\n      const sqlite3_module *pModule = pVCur->pVtab->pModule;\n      assert( pVCur->pVtab->nRef>0 );\n      pVCur->pVtab->nRef--;\n      pModule->xClose(pVCur);\n      break;\n    }\n#endif\n  }\n}\n\n/*\n** Close all cursors in the current frame.\n*/\nstatic void closeCursorsInFrame(Vdbe *p){\n  if( p->apCsr ){\n    int i;\n    for(i=0; i<p->nCursor; i++){\n      VdbeCursor *pC = p->apCsr[i];\n      if( pC ){\n        sqlite3VdbeFreeCursor(p, pC);\n        p->apCsr[i] = 0;\n      }\n    }\n  }\n}\n\n/*\n** Copy the values stored in the VdbeFrame structure to its Vdbe. This\n** is used, for example, when a trigger sub-program is halted to restore\n** control to the main program.\n*/\nSQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){\n  Vdbe *v = pFrame->v;\n  closeCursorsInFrame(v);\n#ifdef SQLITE_ENABLE_STMT_SCANSTATUS\n  v->anExec = pFrame->anExec;\n#endif\n  v->aOp = pFrame->aOp;\n  v->nOp = pFrame->nOp;\n  v->aMem = pFrame->aMem;\n  v->nMem = pFrame->nMem;\n  v->apCsr = pFrame->apCsr;\n  v->nCursor = pFrame->nCursor;\n  v->db->lastRowid = pFrame->lastRowid;\n  v->nChange = pFrame->nChange;\n  v->db->nChange = pFrame->nDbChange;\n  sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);\n  v->pAuxData = pFrame->pAuxData;\n  pFrame->pAuxData = 0;\n  return pFrame->pc;\n}\n\n/*\n** Close all cursors.\n**\n** Also release any dynamic memory held by the VM in the Vdbe.aMem memory \n** cell array. This is necessary as the memory cell array may contain\n** pointers to VdbeFrame objects, which may in turn contain pointers to\n** open cursors.\n*/\nstatic void closeAllCursors(Vdbe *p){\n  if( p->pFrame ){\n    VdbeFrame *pFrame;\n    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);\n    sqlite3VdbeFrameRestore(pFrame);\n    p->pFrame = 0;\n    p->nFrame = 0;\n  }\n  assert( p->nFrame==0 );\n  closeCursorsInFrame(p);\n  if( p->aMem ){\n    releaseMemArray(p->aMem, p->nMem);\n  }\n  while( p->pDelFrame ){\n    VdbeFrame *pDel = p->pDelFrame;\n    p->pDelFrame = pDel->pParent;\n    sqlite3VdbeFrameDelete(pDel);\n  }\n\n  /* Delete any auxdata allocations made by the VM */\n  if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);\n  assert( p->pAuxData==0 );\n}\n\n/*\n** Set the number of result columns that will be returned by this SQL\n** statement. This is now set at compile time, rather than during\n** execution of the vdbe program so that sqlite3_column_count() can\n** be called on an SQL statement before sqlite3_step().\n*/\nSQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){\n  int n;\n  sqlite3 *db = p->db;\n\n  if( p->nResColumn ){\n    releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);\n    sqlite3DbFree(db, p->aColName);\n  }\n  n = nResColumn*COLNAME_N;\n  p->nResColumn = (u16)nResColumn;\n  p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );\n  if( p->aColName==0 ) return;\n  initMemArray(p->aColName, n, db, MEM_Null);\n}\n\n/*\n** Set the name of the idx'th column to be returned by the SQL statement.\n** zName must be a pointer to a nul terminated string.\n**\n** This call must be made after a call to sqlite3VdbeSetNumCols().\n**\n** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC\n** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed\n** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.\n*/\nSQLITE_PRIVATE int sqlite3VdbeSetColName(\n  Vdbe *p,                         /* Vdbe being configured */\n  int idx,                         /* Index of column zName applies to */\n  int var,                         /* One of the COLNAME_* constants */\n  const char *zName,               /* Pointer to buffer containing name */\n  void (*xDel)(void*)              /* Memory management strategy for zName */\n){\n  int rc;\n  Mem *pColName;\n  assert( idx<p->nResColumn );\n  assert( var<COLNAME_N );\n  if( p->db->mallocFailed ){\n    assert( !zName || xDel!=SQLITE_DYNAMIC );\n    return SQLITE_NOMEM_BKPT;\n  }\n  assert( p->aColName!=0 );\n  pColName = &(p->aColName[idx+var*p->nResColumn]);\n  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);\n  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );\n  return rc;\n}\n\n/*\n** A read or write transaction may or may not be active on database handle\n** db. If a transaction is active, commit it. If there is a\n** write-transaction spanning more than one database file, this routine\n** takes care of the master journal trickery.\n*/\nstatic int vdbeCommit(sqlite3 *db, Vdbe *p){\n  int i;\n  int nTrans = 0;  /* Number of databases with an active write-transaction\n                   ** that are candidates for a two-phase commit using a\n                   ** master-journal */\n  int rc = SQLITE_OK;\n  int needXcommit = 0;\n\n#ifdef SQLITE_OMIT_VIRTUALTABLE\n  /* With this option, sqlite3VtabSync() is defined to be simply \n  ** SQLITE_OK so p is not used. \n  */\n  UNUSED_PARAMETER(p);\n#endif\n\n  /* Before doing anything else, call the xSync() callback for any\n  ** virtual module tables written in this transaction. This has to\n  ** be done before determining whether a master journal file is \n  ** required, as an xSync() callback may add an attached database\n  ** to the transaction.\n  */\n  rc = sqlite3VtabSync(db, p);\n\n  /* This loop determines (a) if the commit hook should be invoked and\n  ** (b) how many database files have open write transactions, not \n  ** including the temp database. (b) is important because if more than \n  ** one database file has an open write transaction, a master journal\n  ** file is required for an atomic commit.\n  */ \n  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ \n    Btree *pBt = db->aDb[i].pBt;\n    if( sqlite3BtreeIsInTrans(pBt) ){\n      /* Whether or not a database might need a master journal depends upon\n      ** its journal mode (among other things).  This matrix determines which\n      ** journal modes use a master journal and which do not */\n      static const u8 aMJNeeded[] = {\n        /* DELETE   */  1,\n        /* PERSIST   */ 1,\n        /* OFF       */ 0,\n        /* TRUNCATE  */ 1,\n        /* MEMORY    */ 0,\n        /* WAL       */ 0\n      };\n      Pager *pPager;   /* Pager associated with pBt */\n      needXcommit = 1;\n      sqlite3BtreeEnter(pBt);\n      pPager = sqlite3BtreePager(pBt);\n      if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF\n       && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]\n       && sqlite3PagerIsMemdb(pPager)==0\n      ){ \n        assert( i!=1 );\n        nTrans++;\n      }\n      rc = sqlite3PagerExclusiveLock(pPager);\n      sqlite3BtreeLeave(pBt);\n    }\n  }\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  /* If there are any write-transactions at all, invoke the commit hook */\n  if( needXcommit && db->xCommitCallback ){\n    rc = db->xCommitCallback(db->pCommitArg);\n    if( rc ){\n      return SQLITE_CONSTRAINT_COMMITHOOK;\n    }\n  }\n\n  /* The simple case - no more than one database file (not counting the\n  ** TEMP database) has a transaction active.   There is no need for the\n  ** master-journal.\n  **\n  ** If the return value of sqlite3BtreeGetFilename() is a zero length\n  ** string, it means the main database is :memory: or a temp file.  In \n  ** that case we do not support atomic multi-file commits, so use the \n  ** simple case then too.\n  */\n  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))\n   || nTrans<=1\n  ){\n    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){\n      Btree *pBt = db->aDb[i].pBt;\n      if( pBt ){\n        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);\n      }\n    }\n\n    /* Do the commit only if all databases successfully complete phase 1. \n    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an\n    ** IO error while deleting or truncating a journal file. It is unlikely,\n    ** but could happen. In this case abandon processing and return the error.\n    */\n    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){\n      Btree *pBt = db->aDb[i].pBt;\n      if( pBt ){\n        rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);\n      }\n    }\n    if( rc==SQLITE_OK ){\n      sqlite3VtabCommit(db);\n    }\n  }\n\n  /* The complex case - There is a multi-file write-transaction active.\n  ** This requires a master journal file to ensure the transaction is\n  ** committed atomically.\n  */\n#ifndef SQLITE_OMIT_DISKIO\n  else{\n    sqlite3_vfs *pVfs = db->pVfs;\n    char *zMaster = 0;   /* File-name for the master journal */\n    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);\n    sqlite3_file *pMaster = 0;\n    i64 offset = 0;\n    int res;\n    int retryCount = 0;\n    int nMainFile;\n\n    /* Select a master journal file name */\n    nMainFile = sqlite3Strlen30(zMainFile);\n    zMaster = sqlite3MPrintf(db, \"%.4c%s%.16c\", 0,zMainFile,0);\n    if( zMaster==0 ) return SQLITE_NOMEM_BKPT;\n    zMaster += 4;\n    do {\n      u32 iRandom;\n      if( retryCount ){\n        if( retryCount>100 ){\n          sqlite3_log(SQLITE_FULL, \"MJ delete: %s\", zMaster);\n          sqlite3OsDelete(pVfs, zMaster, 0);\n          break;\n        }else if( retryCount==1 ){\n          sqlite3_log(SQLITE_FULL, \"MJ collide: %s\", zMaster);\n        }\n      }\n      retryCount++;\n      sqlite3_randomness(sizeof(iRandom), &iRandom);\n      sqlite3_snprintf(13, &zMaster[nMainFile], \"-mj%06X9%02X\",\n                               (iRandom>>8)&0xffffff, iRandom&0xff);\n      /* The antipenultimate character of the master journal name must\n      ** be \"9\" to avoid name collisions when using 8+3 filenames. */\n      assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );\n      sqlite3FileSuffix3(zMainFile, zMaster);\n      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);\n    }while( rc==SQLITE_OK && res );\n    if( rc==SQLITE_OK ){\n      /* Open the master journal. */\n      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, \n          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|\n          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0\n      );\n    }\n    if( rc!=SQLITE_OK ){\n      sqlite3DbFree(db, zMaster-4);\n      return rc;\n    }\n \n    /* Write the name of each database file in the transaction into the new\n    ** master journal file. If an error occurs at this point close\n    ** and delete the master journal file. All the individual journal files\n    ** still have 'null' as the master journal pointer, so they will roll\n    ** back independently if a failure occurs.\n    */\n    for(i=0; i<db->nDb; i++){\n      Btree *pBt = db->aDb[i].pBt;\n      if( sqlite3BtreeIsInTrans(pBt) ){\n        char const *zFile = sqlite3BtreeGetJournalname(pBt);\n        if( zFile==0 ){\n          continue;  /* Ignore TEMP and :memory: databases */\n        }\n        assert( zFile[0]!=0 );\n        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);\n        offset += sqlite3Strlen30(zFile)+1;\n        if( rc!=SQLITE_OK ){\n          sqlite3OsCloseFree(pMaster);\n          sqlite3OsDelete(pVfs, zMaster, 0);\n          sqlite3DbFree(db, zMaster-4);\n          return rc;\n        }\n      }\n    }\n\n    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device\n    ** flag is set this is not required.\n    */\n    if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)\n     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))\n    ){\n      sqlite3OsCloseFree(pMaster);\n      sqlite3OsDelete(pVfs, zMaster, 0);\n      sqlite3DbFree(db, zMaster-4);\n      return rc;\n    }\n\n    /* Sync all the db files involved in the transaction. The same call\n    ** sets the master journal pointer in each individual journal. If\n    ** an error occurs here, do not delete the master journal file.\n    **\n    ** If the error occurs during the first call to\n    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the\n    ** master journal file will be orphaned. But we cannot delete it,\n    ** in case the master journal file name was written into the journal\n    ** file before the failure occurred.\n    */\n    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ \n      Btree *pBt = db->aDb[i].pBt;\n      if( pBt ){\n        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);\n      }\n    }\n    sqlite3OsCloseFree(pMaster);\n    assert( rc!=SQLITE_BUSY );\n    if( rc!=SQLITE_OK ){\n      sqlite3DbFree(db, zMaster-4);\n      return rc;\n    }\n\n    /* Delete the master journal file. This commits the transaction. After\n    ** doing this the directory is synced again before any individual\n    ** transaction files are deleted.\n    */\n    rc = sqlite3OsDelete(pVfs, zMaster, 1);\n    sqlite3DbFree(db, zMaster-4);\n    zMaster = 0;\n    if( rc ){\n      return rc;\n    }\n\n    /* All files and directories have already been synced, so the following\n    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and\n    ** deleting or truncating journals. If something goes wrong while\n    ** this is happening we don't really care. The integrity of the\n    ** transaction is already guaranteed, but some stray 'cold' journals\n    ** may be lying around. Returning an error code won't help matters.\n    */\n    disable_simulated_io_errors();\n    sqlite3BeginBenignMalloc();\n    for(i=0; i<db->nDb; i++){ \n      Btree *pBt = db->aDb[i].pBt;\n      if( pBt ){\n        sqlite3BtreeCommitPhaseTwo(pBt, 1);\n      }\n    }\n    sqlite3EndBenignMalloc();\n    enable_simulated_io_errors();\n\n    sqlite3VtabCommit(db);\n  }\n#endif\n\n  return rc;\n}\n\n/* \n** This routine checks that the sqlite3.nVdbeActive count variable\n** matches the number of vdbe's in the list sqlite3.pVdbe that are\n** currently active. An assertion fails if the two counts do not match.\n** This is an internal self-check only - it is not an essential processing\n** step.\n**\n** This is a no-op if NDEBUG is defined.\n*/\n#ifndef NDEBUG\nstatic void checkActiveVdbeCnt(sqlite3 *db){\n  Vdbe *p;\n  int cnt = 0;\n  int nWrite = 0;\n  int nRead = 0;\n  p = db->pVdbe;\n  while( p ){\n    if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){\n      cnt++;\n      if( p->readOnly==0 ) nWrite++;\n      if( p->bIsReader ) nRead++;\n    }\n    p = p->pNext;\n  }\n  assert( cnt==db->nVdbeActive );\n  assert( nWrite==db->nVdbeWrite );\n  assert( nRead==db->nVdbeRead );\n}\n#else\n#define checkActiveVdbeCnt(x)\n#endif\n\n/*\n** If the Vdbe passed as the first argument opened a statement-transaction,\n** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or\n** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement\n** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the \n** statement transaction is committed.\n**\n** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. \n** Otherwise SQLITE_OK.\n*/\nstatic SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){\n  sqlite3 *const db = p->db;\n  int rc = SQLITE_OK;\n  int i;\n  const int iSavepoint = p->iStatement-1;\n\n  assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);\n  assert( db->nStatement>0 );\n  assert( p->iStatement==(db->nStatement+db->nSavepoint) );\n\n  for(i=0; i<db->nDb; i++){ \n    int rc2 = SQLITE_OK;\n    Btree *pBt = db->aDb[i].pBt;\n    if( pBt ){\n      if( eOp==SAVEPOINT_ROLLBACK ){\n        rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);\n      }\n      if( rc2==SQLITE_OK ){\n        rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);\n      }\n      if( rc==SQLITE_OK ){\n        rc = rc2;\n      }\n    }\n  }\n  db->nStatement--;\n  p->iStatement = 0;\n\n  if( rc==SQLITE_OK ){\n    if( eOp==SAVEPOINT_ROLLBACK ){\n      rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);\n    }\n    if( rc==SQLITE_OK ){\n      rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);\n    }\n  }\n\n  /* If the statement transaction is being rolled back, also restore the \n  ** database handles deferred constraint counter to the value it had when \n  ** the statement transaction was opened.  */\n  if( eOp==SAVEPOINT_ROLLBACK ){\n    db->nDeferredCons = p->nStmtDefCons;\n    db->nDeferredImmCons = p->nStmtDefImmCons;\n  }\n  return rc;\n}\nSQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){\n  if( p->db->nStatement && p->iStatement ){\n    return vdbeCloseStatement(p, eOp);\n  }\n  return SQLITE_OK;\n}\n\n\n/*\n** This function is called when a transaction opened by the database \n** handle associated with the VM passed as an argument is about to be \n** committed. If there are outstanding deferred foreign key constraint\n** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.\n**\n** If there are outstanding FK violations and this function returns \n** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY\n** and write an error message to it. Then return SQLITE_ERROR.\n*/\n#ifndef SQLITE_OMIT_FOREIGN_KEY\nSQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){\n  sqlite3 *db = p->db;\n  if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0) \n   || (!deferred && p->nFkConstraint>0) \n  ){\n    p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;\n    p->errorAction = OE_Abort;\n    sqlite3VdbeError(p, \"FOREIGN KEY constraint failed\");\n    return SQLITE_ERROR;\n  }\n  return SQLITE_OK;\n}\n#endif\n\n/*\n** This routine is called the when a VDBE tries to halt.  If the VDBE\n** has made changes and is in autocommit mode, then commit those\n** changes.  If a rollback is needed, then do the rollback.\n**\n** This routine is the only way to move the state of a VM from\n** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to\n** call this on a VM that is in the SQLITE_MAGIC_HALT state.\n**\n** Return an error code.  If the commit could not complete because of\n** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it\n** means the close did not happen and needs to be repeated.\n*/\nSQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){\n  int rc;                         /* Used to store transient return codes */\n  sqlite3 *db = p->db;\n\n  /* This function contains the logic that determines if a statement or\n  ** transaction will be committed or rolled back as a result of the\n  ** execution of this virtual machine. \n  **\n  ** If any of the following errors occur:\n  **\n  **     SQLITE_NOMEM\n  **     SQLITE_IOERR\n  **     SQLITE_FULL\n  **     SQLITE_INTERRUPT\n  **\n  ** Then the internal cache might have been left in an inconsistent\n  ** state.  We need to rollback the statement transaction, if there is\n  ** one, or the complete transaction if there is no statement transaction.\n  */\n\n  if( p->magic!=VDBE_MAGIC_RUN ){\n    return SQLITE_OK;\n  }\n  if( db->mallocFailed ){\n    p->rc = SQLITE_NOMEM_BKPT;\n  }\n  closeAllCursors(p);\n  checkActiveVdbeCnt(db);\n\n  /* No commit or rollback needed if the program never started or if the\n  ** SQL statement does not read or write a database file.  */\n  if( p->pc>=0 && p->bIsReader ){\n    int mrc;   /* Primary error code from p->rc */\n    int eStatementOp = 0;\n    int isSpecialError;            /* Set to true if a 'special' error */\n\n    /* Lock all btrees used by the statement */\n    sqlite3VdbeEnter(p);\n\n    /* Check for one of the special errors */\n    mrc = p->rc & 0xff;\n    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR\n                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;\n    if( isSpecialError ){\n      /* If the query was read-only and the error code is SQLITE_INTERRUPT, \n      ** no rollback is necessary. Otherwise, at least a savepoint \n      ** transaction must be rolled back to restore the database to a \n      ** consistent state.\n      **\n      ** Even if the statement is read-only, it is important to perform\n      ** a statement or transaction rollback operation. If the error \n      ** occurred while writing to the journal, sub-journal or database\n      ** file as part of an effort to free up cache space (see function\n      ** pagerStress() in pager.c), the rollback is required to restore \n      ** the pager to a consistent state.\n      */\n      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){\n        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){\n          eStatementOp = SAVEPOINT_ROLLBACK;\n        }else{\n          /* We are forced to roll back the active transaction. Before doing\n          ** so, abort any other statements this handle currently has active.\n          */\n          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);\n          sqlite3CloseSavepoints(db);\n          db->autoCommit = 1;\n          p->nChange = 0;\n        }\n      }\n    }\n\n    /* Check for immediate foreign key violations. */\n    if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){\n      sqlite3VdbeCheckFk(p, 0);\n    }\n  \n    /* If the auto-commit flag is set and this is the only active writer \n    ** VM, then we do either a commit or rollback of the current transaction. \n    **\n    ** Note: This block also runs if one of the special errors handled \n    ** above has occurred. \n    */\n    if( !sqlite3VtabInSync(db) \n     && db->autoCommit \n     && db->nVdbeWrite==(p->readOnly==0) \n    ){\n      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){\n        rc = sqlite3VdbeCheckFk(p, 1);\n        if( rc!=SQLITE_OK ){\n          if( NEVER(p->readOnly) ){\n            sqlite3VdbeLeave(p);\n            return SQLITE_ERROR;\n          }\n          rc = SQLITE_CONSTRAINT_FOREIGNKEY;\n        }else{ \n          /* The auto-commit flag is true, the vdbe program was successful \n          ** or hit an 'OR FAIL' constraint and there are no deferred foreign\n          ** key constraints to hold up the transaction. This means a commit \n          ** is required. */\n          rc = vdbeCommit(db, p);\n        }\n        if( rc==SQLITE_BUSY && p->readOnly ){\n          sqlite3VdbeLeave(p);\n          return SQLITE_BUSY;\n        }else if( rc!=SQLITE_OK ){\n          p->rc = rc;\n          sqlite3RollbackAll(db, SQLITE_OK);\n          p->nChange = 0;\n        }else{\n          db->nDeferredCons = 0;\n          db->nDeferredImmCons = 0;\n          db->flags &= ~(u64)SQLITE_DeferFKs;\n          sqlite3CommitInternalChanges(db);\n        }\n      }else{\n        sqlite3RollbackAll(db, SQLITE_OK);\n        p->nChange = 0;\n      }\n      db->nStatement = 0;\n    }else if( eStatementOp==0 ){\n      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){\n        eStatementOp = SAVEPOINT_RELEASE;\n      }else if( p->errorAction==OE_Abort ){\n        eStatementOp = SAVEPOINT_ROLLBACK;\n      }else{\n        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);\n        sqlite3CloseSavepoints(db);\n        db->autoCommit = 1;\n        p->nChange = 0;\n      }\n    }\n  \n    /* If eStatementOp is non-zero, then a statement transaction needs to\n    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to\n    ** do so. If this operation returns an error, and the current statement\n    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the\n    ** current statement error code.\n    */\n    if( eStatementOp ){\n      rc = sqlite3VdbeCloseStatement(p, eStatementOp);\n      if( rc ){\n        if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){\n          p->rc = rc;\n          sqlite3DbFree(db, p->zErrMsg);\n          p->zErrMsg = 0;\n        }\n        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);\n        sqlite3CloseSavepoints(db);\n        db->autoCommit = 1;\n        p->nChange = 0;\n      }\n    }\n  \n    /* If this was an INSERT, UPDATE or DELETE and no statement transaction\n    ** has been rolled back, update the database connection change-counter. \n    */\n    if( p->changeCntOn ){\n      if( eStatementOp!=SAVEPOINT_ROLLBACK ){\n        sqlite3VdbeSetChanges(db, p->nChange);\n      }else{\n        sqlite3VdbeSetChanges(db, 0);\n      }\n      p->nChange = 0;\n    }\n\n    /* Release the locks */\n    sqlite3VdbeLeave(p);\n  }\n\n  /* We have successfully halted and closed the VM.  Record this fact. */\n  if( p->pc>=0 ){\n    db->nVdbeActive--;\n    if( !p->readOnly ) db->nVdbeWrite--;\n    if( p->bIsReader ) db->nVdbeRead--;\n    assert( db->nVdbeActive>=db->nVdbeRead );\n    assert( db->nVdbeRead>=db->nVdbeWrite );\n    assert( db->nVdbeWrite>=0 );\n  }\n  p->magic = VDBE_MAGIC_HALT;\n  checkActiveVdbeCnt(db);\n  if( db->mallocFailed ){\n    p->rc = SQLITE_NOMEM_BKPT;\n  }\n\n  /* If the auto-commit flag is set to true, then any locks that were held\n  ** by connection db have now been released. Call sqlite3ConnectionUnlocked() \n  ** to invoke any required unlock-notify callbacks.\n  */\n  if( db->autoCommit ){\n    sqlite3ConnectionUnlocked(db);\n  }\n\n  assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );\n  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);\n}\n\n\n/*\n** Each VDBE holds the result of the most recent sqlite3_step() call\n** in p->rc.  This routine sets that result back to SQLITE_OK.\n*/\nSQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){\n  p->rc = SQLITE_OK;\n}\n\n/*\n** Copy the error code and error message belonging to the VDBE passed\n** as the first argument to its database handle (so that they will be \n** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).\n**\n** This function does not clear the VDBE error code or message, just\n** copies them to the database handle.\n*/\nSQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){\n  sqlite3 *db = p->db;\n  int rc = p->rc;\n  if( p->zErrMsg ){\n    db->bBenignMalloc++;\n    sqlite3BeginBenignMalloc();\n    if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);\n    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);\n    sqlite3EndBenignMalloc();\n    db->bBenignMalloc--;\n  }else if( db->pErr ){\n    sqlite3ValueSetNull(db->pErr);\n  }\n  db->errCode = rc;\n  return rc;\n}\n\n#ifdef SQLITE_ENABLE_SQLLOG\n/*\n** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run, \n** invoke it.\n*/\nstatic void vdbeInvokeSqllog(Vdbe *v){\n  if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){\n    char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);\n    assert( v->db->init.busy==0 );\n    if( zExpanded ){\n      sqlite3GlobalConfig.xSqllog(\n          sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1\n      );\n      sqlite3DbFree(v->db, zExpanded);\n    }\n  }\n}\n#else\n# define vdbeInvokeSqllog(x)\n#endif\n\n/*\n** Clean up a VDBE after execution but do not delete the VDBE just yet.\n** Write any error messages into *pzErrMsg.  Return the result code.\n**\n** After this routine is run, the VDBE should be ready to be executed\n** again.\n**\n** To look at it another way, this routine resets the state of the\n** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to\n** VDBE_MAGIC_INIT.\n*/\nSQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){\n#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)\n  int i;\n#endif\n\n  sqlite3 *db;\n  db = p->db;\n\n  /* If the VM did not run to completion or if it encountered an\n  ** error, then it might not have been halted properly.  So halt\n  ** it now.\n  */\n  sqlite3VdbeHalt(p);\n\n  /* If the VDBE has been run even partially, then transfer the error code\n  ** and error message from the VDBE into the main database structure.  But\n  ** if the VDBE has just been set to run but has not actually executed any\n  ** instructions yet, leave the main database error information unchanged.\n  */\n  if( p->pc>=0 ){\n    vdbeInvokeSqllog(p);\n    sqlite3VdbeTransferError(p);\n    if( p->runOnlyOnce ) p->expired = 1;\n  }else if( p->rc && p->expired ){\n    /* The expired flag was set on the VDBE before the first call\n    ** to sqlite3_step(). For consistency (since sqlite3_step() was\n    ** called), set the database error in this case as well.\n    */\n    sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? \"%s\" : 0, p->zErrMsg);\n  }\n\n  /* Reset register contents and reclaim error message memory.\n  */\n#ifdef SQLITE_DEBUG\n  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and \n  ** Vdbe.aMem[] arrays have already been cleaned up.  */\n  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );\n  if( p->aMem ){\n    for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );\n  }\n#endif\n  sqlite3DbFree(db, p->zErrMsg);\n  p->zErrMsg = 0;\n  p->pResultSet = 0;\n#ifdef SQLITE_DEBUG\n  p->nWrite = 0;\n#endif\n\n  /* Save profiling information from this VDBE run.\n  */\n#ifdef VDBE_PROFILE\n  {\n    FILE *out = fopen(\"vdbe_profile.out\", \"a\");\n    if( out ){\n      fprintf(out, \"---- \");\n      for(i=0; i<p->nOp; i++){\n        fprintf(out, \"%02x\", p->aOp[i].opcode);\n      }\n      fprintf(out, \"\\n\");\n      if( p->zSql ){\n        char c, pc = 0;\n        fprintf(out, \"-- \");\n        for(i=0; (c = p->zSql[i])!=0; i++){\n          if( pc=='\\n' ) fprintf(out, \"-- \");\n          putc(c, out);\n          pc = c;\n        }\n        if( pc!='\\n' ) fprintf(out, \"\\n\");\n      }\n      for(i=0; i<p->nOp; i++){\n        char zHdr[100];\n        sqlite3_snprintf(sizeof(zHdr), zHdr, \"%6u %12llu %8llu \",\n           p->aOp[i].cnt,\n           p->aOp[i].cycles,\n           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0\n        );\n        fprintf(out, \"%s\", zHdr);\n        sqlite3VdbePrintOp(out, i, &p->aOp[i]);\n      }\n      fclose(out);\n    }\n  }\n#endif\n  p->magic = VDBE_MAGIC_RESET;\n  return p->rc & db->errMask;\n}\n \n/*\n** Clean up and delete a VDBE after execution.  Return an integer which is\n** the result code.  Write any error message text into *pzErrMsg.\n*/\nSQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){\n  int rc = SQLITE_OK;\n  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){\n    rc = sqlite3VdbeReset(p);\n    assert( (rc & p->db->errMask)==rc );\n  }\n  sqlite3VdbeDelete(p);\n  return rc;\n}\n\n/*\n** If parameter iOp is less than zero, then invoke the destructor for\n** all auxiliary data pointers currently cached by the VM passed as\n** the first argument.\n**\n** Or, if iOp is greater than or equal to zero, then the destructor is\n** only invoked for those auxiliary data pointers created by the user \n** function invoked by the OP_Function opcode at instruction iOp of \n** VM pVdbe, and only then if:\n**\n**    * the associated function parameter is the 32nd or later (counting\n**      from left to right), or\n**\n**    * the corresponding bit in argument mask is clear (where the first\n**      function parameter corresponds to bit 0 etc.).\n*/\nSQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){\n  while( *pp ){\n    AuxData *pAux = *pp;\n    if( (iOp<0)\n     || (pAux->iAuxOp==iOp\n          && pAux->iAuxArg>=0\n          && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))\n    ){\n      testcase( pAux->iAuxArg==31 );\n      if( pAux->xDeleteAux ){\n        pAux->xDeleteAux(pAux->pAux);\n      }\n      *pp = pAux->pNextAux;\n      sqlite3DbFree(db, pAux);\n    }else{\n      pp= &pAux->pNextAux;\n    }\n  }\n}\n\n/*\n** Free all memory associated with the Vdbe passed as the second argument,\n** except for object itself, which is preserved.\n**\n** The difference between this function and sqlite3VdbeDelete() is that\n** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with\n** the database connection and frees the object itself.\n*/\nSQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){\n  SubProgram *pSub, *pNext;\n  assert( p->db==0 || p->db==db );\n  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);\n  for(pSub=p->pProgram; pSub; pSub=pNext){\n    pNext = pSub->pNext;\n    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);\n    sqlite3DbFree(db, pSub);\n  }\n  if( p->magic!=VDBE_MAGIC_INIT ){\n    releaseMemArray(p->aVar, p->nVar);\n    sqlite3DbFree(db, p->pVList);\n    sqlite3DbFree(db, p->pFree);\n  }\n  vdbeFreeOpArray(db, p->aOp, p->nOp);\n  sqlite3DbFree(db, p->aColName);\n  sqlite3DbFree(db, p->zSql);\n#ifdef SQLITE_ENABLE_NORMALIZE\n  sqlite3DbFree(db, p->zNormSql);\n  {\n    DblquoteStr *pThis, *pNext;\n    for(pThis=p->pDblStr; pThis; pThis=pNext){\n      pNext = pThis->pNextStr;\n      sqlite3DbFree(db, pThis);\n    }\n  }\n#endif\n#ifdef SQLITE_ENABLE_STMT_SCANSTATUS\n  {\n    int i;\n    for(i=0; i<p->nScan; i++){\n      sqlite3DbFree(db, p->aScan[i].zName);\n    }\n    sqlite3DbFree(db, p->aScan);\n  }\n#endif\n}\n\n/*\n** Delete an entire VDBE.\n*/\nSQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){\n  sqlite3 *db;\n\n  assert( p!=0 );\n  db = p->db;\n  assert( sqlite3_mutex_held(db->mutex) );\n  sqlite3VdbeClearObject(db, p);\n  if( p->pPrev ){\n    p->pPrev->pNext = p->pNext;\n  }else{\n    assert( db->pVdbe==p );\n    db->pVdbe = p->pNext;\n  }\n  if( p->pNext ){\n    p->pNext->pPrev = p->pPrev;\n  }\n  p->magic = VDBE_MAGIC_DEAD;\n  p->db = 0;\n  sqlite3DbFreeNN(db, p);\n}\n\n/*\n** The cursor \"p\" has a pending seek operation that has not yet been\n** carried out.  Seek the cursor now.  If an error occurs, return\n** the appropriate error code.\n*/\nSQLITE_PRIVATE int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor *p){\n  int res, rc;\n#ifdef SQLITE_TEST\n  extern int sqlite3_search_count;\n#endif\n  assert( p->deferredMoveto );\n  assert( p->isTable );\n  assert( p->eCurType==CURTYPE_BTREE );\n  rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);\n  if( rc ) return rc;\n  if( res!=0 ) return SQLITE_CORRUPT_BKPT;\n#ifdef SQLITE_TEST\n  sqlite3_search_count++;\n#endif\n  p->deferredMoveto = 0;\n  p->cacheStatus = CACHE_STALE;\n  return SQLITE_OK;\n}\n\n/*\n** Something has moved cursor \"p\" out of place.  Maybe the row it was\n** pointed to was deleted out from under it.  Or maybe the btree was\n** rebalanced.  Whatever the cause, try to restore \"p\" to the place it\n** is supposed to be pointing.  If the row was deleted out from under the\n** cursor, set the cursor to point to a NULL row.\n*/\nstatic int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){\n  int isDifferentRow, rc;\n  assert( p->eCurType==CURTYPE_BTREE );\n  assert( p->uc.pCursor!=0 );\n  assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );\n  rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);\n  p->cacheStatus = CACHE_STALE;\n  if( isDifferentRow ) p->nullRow = 1;\n  return rc;\n}\n\n/*\n** Check to ensure that the cursor is valid.  Restore the cursor\n** if need be.  Return any I/O error from the restore operation.\n*/\nSQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){\n  assert( p->eCurType==CURTYPE_BTREE );\n  if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){\n    return handleMovedCursor(p);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Make sure the cursor p is ready to read or write the row to which it\n** was last positioned.  Return an error code if an OOM fault or I/O error\n** prevents us from positioning the cursor to its correct position.\n**\n** If a MoveTo operation is pending on the given cursor, then do that\n** MoveTo now.  If no move is pending, check to see if the row has been\n** deleted out from under the cursor and if it has, mark the row as\n** a NULL row.\n**\n** If the cursor is already pointing to the correct row and that row has\n** not been deleted out from under the cursor, then this routine is a no-op.\n*/\nSQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){\n  VdbeCursor *p = *pp;\n  assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );\n  if( p->deferredMoveto ){\n    int iMap;\n    if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 && !p->nullRow ){\n      *pp = p->pAltCursor;\n      *piCol = iMap - 1;\n      return SQLITE_OK;\n    }\n    return sqlite3VdbeFinishMoveto(p);\n  }\n  if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){\n    return handleMovedCursor(p);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** The following functions:\n**\n** sqlite3VdbeSerialType()\n** sqlite3VdbeSerialTypeLen()\n** sqlite3VdbeSerialLen()\n** sqlite3VdbeSerialPut()\n** sqlite3VdbeSerialGet()\n**\n** encapsulate the code that serializes values for storage in SQLite\n** data and index records. Each serialized value consists of a\n** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned\n** integer, stored as a varint.\n**\n** In an SQLite index record, the serial type is stored directly before\n** the blob of data that it corresponds to. In a table record, all serial\n** types are stored at the start of the record, and the blobs of data at\n** the end. Hence these functions allow the caller to handle the\n** serial-type and data blob separately.\n**\n** The following table describes the various storage classes for data:\n**\n**   serial type        bytes of data      type\n**   --------------     ---------------    ---------------\n**      0                     0            NULL\n**      1                     1            signed integer\n**      2                     2            signed integer\n**      3                     3            signed integer\n**      4                     4            signed integer\n**      5                     6            signed integer\n**      6                     8            signed integer\n**      7                     8            IEEE float\n**      8                     0            Integer constant 0\n**      9                     0            Integer constant 1\n**     10,11                               reserved for expansion\n**    N>=12 and even       (N-12)/2        BLOB\n**    N>=13 and odd        (N-13)/2        text\n**\n** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions\n** of SQLite will not understand those serial types.\n*/\n\n#if 0 /* Inlined into the OP_MakeRecord opcode */\n/*\n** Return the serial-type for the value stored in pMem.\n**\n** This routine might convert a large MEM_IntReal value into MEM_Real.\n**\n** 2019-07-11:  The primary user of this subroutine was the OP_MakeRecord\n** opcode in the byte-code engine.  But by moving this routine in-line, we\n** can omit some redundant tests and make that opcode a lot faster.  So\n** this routine is now only used by the STAT3 logic and STAT3 support has\n** ended.  The code is kept here for historical reference only.\n*/\nSQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){\n  int flags = pMem->flags;\n  u32 n;\n\n  assert( pLen!=0 );\n  if( flags&MEM_Null ){\n    *pLen = 0;\n    return 0;\n  }\n  if( flags&(MEM_Int|MEM_IntReal) ){\n    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */\n#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)\n    i64 i = pMem->u.i;\n    u64 u;\n    testcase( flags & MEM_Int );\n    testcase( flags & MEM_IntReal );\n    if( i<0 ){\n      u = ~i;\n    }else{\n      u = i;\n    }\n    if( u<=127 ){\n      if( (i&1)==i && file_format>=4 ){\n        *pLen = 0;\n        return 8+(u32)u;\n      }else{\n        *pLen = 1;\n        return 1;\n      }\n    }\n    if( u<=32767 ){ *pLen = 2; return 2; }\n    if( u<=8388607 ){ *pLen = 3; return 3; }\n    if( u<=2147483647 ){ *pLen = 4; return 4; }\n    if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }\n    *pLen = 8;\n    if( flags&MEM_IntReal ){\n      /* If the value is IntReal and is going to take up 8 bytes to store\n      ** as an integer, then we might as well make it an 8-byte floating\n      ** point value */\n      pMem->u.r = (double)pMem->u.i;\n      pMem->flags &= ~MEM_IntReal;\n      pMem->flags |= MEM_Real;\n      return 7;\n    }\n    return 6;\n  }\n  if( flags&MEM_Real ){\n    *pLen = 8;\n    return 7;\n  }\n  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );\n  assert( pMem->n>=0 );\n  n = (u32)pMem->n;\n  if( flags & MEM_Zero ){\n    n += pMem->u.nZero;\n  }\n  *pLen = n;\n  return ((n*2) + 12 + ((flags&MEM_Str)!=0));\n}\n#endif /* inlined into OP_MakeRecord */\n\n/*\n** The sizes for serial types less than 128\n*/\nstatic const u8 sqlite3SmallTypeSizes[] = {\n        /*  0   1   2   3   4   5   6   7   8   9 */   \n/*   0 */   0,  1,  2,  3,  4,  6,  8,  8,  0,  0,\n/*  10 */   0,  0,  0,  0,  1,  1,  2,  2,  3,  3,\n/*  20 */   4,  4,  5,  5,  6,  6,  7,  7,  8,  8,\n/*  30 */   9,  9, 10, 10, 11, 11, 12, 12, 13, 13,\n/*  40 */  14, 14, 15, 15, 16, 16, 17, 17, 18, 18,\n/*  50 */  19, 19, 20, 20, 21, 21, 22, 22, 23, 23,\n/*  60 */  24, 24, 25, 25, 26, 26, 27, 27, 28, 28,\n/*  70 */  29, 29, 30, 30, 31, 31, 32, 32, 33, 33,\n/*  80 */  34, 34, 35, 35, 36, 36, 37, 37, 38, 38,\n/*  90 */  39, 39, 40, 40, 41, 41, 42, 42, 43, 43,\n/* 100 */  44, 44, 45, 45, 46, 46, 47, 47, 48, 48,\n/* 110 */  49, 49, 50, 50, 51, 51, 52, 52, 53, 53,\n/* 120 */  54, 54, 55, 55, 56, 56, 57, 57\n};\n\n/*\n** Return the length of the data corresponding to the supplied serial-type.\n*/\nSQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){\n  if( serial_type>=128 ){\n    return (serial_type-12)/2;\n  }else{\n    assert( serial_type<12 \n            || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );\n    return sqlite3SmallTypeSizes[serial_type];\n  }\n}\nSQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){\n  assert( serial_type<128 );\n  return sqlite3SmallTypeSizes[serial_type];  \n}\n\n/*\n** If we are on an architecture with mixed-endian floating \n** points (ex: ARM7) then swap the lower 4 bytes with the \n** upper 4 bytes.  Return the result.\n**\n** For most architectures, this is a no-op.\n**\n** (later):  It is reported to me that the mixed-endian problem\n** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems\n** that early versions of GCC stored the two words of a 64-bit\n** float in the wrong order.  And that error has been propagated\n** ever since.  The blame is not necessarily with GCC, though.\n** GCC might have just copying the problem from a prior compiler.\n** I am also told that newer versions of GCC that follow a different\n** ABI get the byte order right.\n**\n** Developers using SQLite on an ARM7 should compile and run their\n** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG\n** enabled, some asserts below will ensure that the byte order of\n** floating point values is correct.\n**\n** (2007-08-30)  Frank van Vugt has studied this problem closely\n** and has send his findings to the SQLite developers.  Frank\n** writes that some Linux kernels offer floating point hardware\n** emulation that uses only 32-bit mantissas instead of a full \n** 48-bits as required by the IEEE standard.  (This is the\n** CONFIG_FPE_FASTFPE option.)  On such systems, floating point\n** byte swapping becomes very complicated.  To avoid problems,\n** the necessary byte swapping is carried out using a 64-bit integer\n** rather than a 64-bit float.  Frank assures us that the code here\n** works for him.  We, the developers, have no way to independently\n** verify this, but Frank seems to know what he is talking about\n** so we trust him.\n*/\n#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT\nstatic u64 floatSwap(u64 in){\n  union {\n    u64 r;\n    u32 i[2];\n  } u;\n  u32 t;\n\n  u.r = in;\n  t = u.i[0];\n  u.i[0] = u.i[1];\n  u.i[1] = t;\n  return u.r;\n}\n# define swapMixedEndianFloat(X)  X = floatSwap(X)\n#else\n# define swapMixedEndianFloat(X)\n#endif\n\n/*\n** Write the serialized data blob for the value stored in pMem into \n** buf. It is assumed that the caller has allocated sufficient space.\n** Return the number of bytes written.\n**\n** nBuf is the amount of space left in buf[].  The caller is responsible\n** for allocating enough space to buf[] to hold the entire field, exclusive\n** of the pMem->u.nZero bytes for a MEM_Zero value.\n**\n** Return the number of bytes actually written into buf[].  The number\n** of bytes in the zero-filled tail is included in the return value only\n** if those bytes were zeroed in buf[].\n*/ \nSQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){\n  u32 len;\n\n  /* Integer and Real */\n  if( serial_type<=7 && serial_type>0 ){\n    u64 v;\n    u32 i;\n    if( serial_type==7 ){\n      assert( sizeof(v)==sizeof(pMem->u.r) );\n      memcpy(&v, &pMem->u.r, sizeof(v));\n      swapMixedEndianFloat(v);\n    }else{\n      v = pMem->u.i;\n    }\n    len = i = sqlite3SmallTypeSizes[serial_type];\n    assert( i>0 );\n    do{\n      buf[--i] = (u8)(v&0xFF);\n      v >>= 8;\n    }while( i );\n    return len;\n  }\n\n  /* String or blob */\n  if( serial_type>=12 ){\n    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)\n             == (int)sqlite3VdbeSerialTypeLen(serial_type) );\n    len = pMem->n;\n    if( len>0 ) memcpy(buf, pMem->z, len);\n    return len;\n  }\n\n  /* NULL or constants 0 or 1 */\n  return 0;\n}\n\n/* Input \"x\" is a sequence of unsigned characters that represent a\n** big-endian integer.  Return the equivalent native integer\n*/\n#define ONE_BYTE_INT(x)    ((i8)(x)[0])\n#define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])\n#define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])\n#define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])\n#define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])\n\n/*\n** Deserialize the data blob pointed to by buf as serial type serial_type\n** and store the result in pMem.  Return the number of bytes read.\n**\n** This function is implemented as two separate routines for performance.\n** The few cases that require local variables are broken out into a separate\n** routine so that in most cases the overhead of moving the stack pointer\n** is avoided.\n*/ \nstatic u32 serialGet(\n  const unsigned char *buf,     /* Buffer to deserialize from */\n  u32 serial_type,              /* Serial type to deserialize */\n  Mem *pMem                     /* Memory cell to write value into */\n){\n  u64 x = FOUR_BYTE_UINT(buf);\n  u32 y = FOUR_BYTE_UINT(buf+4);\n  x = (x<<32) + y;\n  if( serial_type==6 ){\n    /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit\n    ** twos-complement integer. */\n    pMem->u.i = *(i64*)&x;\n    pMem->flags = MEM_Int;\n    testcase( pMem->u.i<0 );\n  }else{\n    /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit\n    ** floating point number. */\n#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)\n    /* Verify that integers and floating point values use the same\n    ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is\n    ** defined that 64-bit floating point values really are mixed\n    ** endian.\n    */\n    static const u64 t1 = ((u64)0x3ff00000)<<32;\n    static const double r1 = 1.0;\n    u64 t2 = t1;\n    swapMixedEndianFloat(t2);\n    assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );\n#endif\n    assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );\n    swapMixedEndianFloat(x);\n    memcpy(&pMem->u.r, &x, sizeof(x));\n    pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real;\n  }\n  return 8;\n}\nSQLITE_PRIVATE u32 sqlite3VdbeSerialGet(\n  const unsigned char *buf,     /* Buffer to deserialize from */\n  u32 serial_type,              /* Serial type to deserialize */\n  Mem *pMem                     /* Memory cell to write value into */\n){\n  switch( serial_type ){\n    case 10: { /* Internal use only: NULL with virtual table\n               ** UPDATE no-change flag set */\n      pMem->flags = MEM_Null|MEM_Zero;\n      pMem->n = 0;\n      pMem->u.nZero = 0;\n      break;\n    }\n    case 11:   /* Reserved for future use */\n    case 0: {  /* Null */\n      /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */\n      pMem->flags = MEM_Null;\n      break;\n    }\n    case 1: {\n      /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement\n      ** integer. */\n      pMem->u.i = ONE_BYTE_INT(buf);\n      pMem->flags = MEM_Int;\n      testcase( pMem->u.i<0 );\n      return 1;\n    }\n    case 2: { /* 2-byte signed integer */\n      /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit\n      ** twos-complement integer. */\n      pMem->u.i = TWO_BYTE_INT(buf);\n      pMem->flags = MEM_Int;\n      testcase( pMem->u.i<0 );\n      return 2;\n    }\n    case 3: { /* 3-byte signed integer */\n      /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit\n      ** twos-complement integer. */\n      pMem->u.i = THREE_BYTE_INT(buf);\n      pMem->flags = MEM_Int;\n      testcase( pMem->u.i<0 );\n      return 3;\n    }\n    case 4: { /* 4-byte signed integer */\n      /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit\n      ** twos-complement integer. */\n      pMem->u.i = FOUR_BYTE_INT(buf);\n#ifdef __HP_cc \n      /* Work around a sign-extension bug in the HP compiler for HP/UX */\n      if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;\n#endif\n      pMem->flags = MEM_Int;\n      testcase( pMem->u.i<0 );\n      return 4;\n    }\n    case 5: { /* 6-byte signed integer */\n      /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit\n      ** twos-complement integer. */\n      pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);\n      pMem->flags = MEM_Int;\n      testcase( pMem->u.i<0 );\n      return 6;\n    }\n    case 6:   /* 8-byte signed integer */\n    case 7: { /* IEEE floating point */\n      /* These use local variables, so do them in a separate routine\n      ** to avoid having to move the frame pointer in the common case */\n      return serialGet(buf,serial_type,pMem);\n    }\n    case 8:    /* Integer 0 */\n    case 9: {  /* Integer 1 */\n      /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */\n      /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */\n      pMem->u.i = serial_type-8;\n      pMem->flags = MEM_Int;\n      return 0;\n    }\n    default: {\n      /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in\n      ** length.\n      ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and\n      ** (N-13)/2 bytes in length. */\n      static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };\n      pMem->z = (char *)buf;\n      pMem->n = (serial_type-12)/2;\n      pMem->flags = aFlag[serial_type&1];\n      return pMem->n;\n    }\n  }\n  return 0;\n}\n/*\n** This routine is used to allocate sufficient space for an UnpackedRecord\n** structure large enough to be used with sqlite3VdbeRecordUnpack() if\n** the first argument is a pointer to KeyInfo structure pKeyInfo.\n**\n** The space is either allocated using sqlite3DbMallocRaw() or from within\n** the unaligned buffer passed via the second and third arguments (presumably\n** stack space). If the former, then *ppFree is set to a pointer that should\n** be eventually freed by the caller using sqlite3DbFree(). Or, if the \n** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL\n** before returning.\n**\n** If an OOM error occurs, NULL is returned.\n*/\nSQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(\n  KeyInfo *pKeyInfo               /* Description of the record */\n){\n  UnpackedRecord *p;              /* Unpacked record to return */\n  int nByte;                      /* Number of bytes required for *p */\n  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);\n  p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);\n  if( !p ) return 0;\n  p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];\n  assert( pKeyInfo->aSortFlags!=0 );\n  p->pKeyInfo = pKeyInfo;\n  p->nField = pKeyInfo->nKeyField + 1;\n  return p;\n}\n\n/*\n** Given the nKey-byte encoding of a record in pKey[], populate the \n** UnpackedRecord structure indicated by the fourth argument with the\n** contents of the decoded record.\n*/ \nSQLITE_PRIVATE void sqlite3VdbeRecordUnpack(\n  KeyInfo *pKeyInfo,     /* Information about the record format */\n  int nKey,              /* Size of the binary record */\n  const void *pKey,      /* The binary record */\n  UnpackedRecord *p      /* Populate this structure before returning. */\n){\n  const unsigned char *aKey = (const unsigned char *)pKey;\n  u32 d; \n  u32 idx;                        /* Offset in aKey[] to read from */\n  u16 u;                          /* Unsigned loop counter */\n  u32 szHdr;\n  Mem *pMem = p->aMem;\n\n  p->default_rc = 0;\n  assert( EIGHT_BYTE_ALIGNMENT(pMem) );\n  idx = getVarint32(aKey, szHdr);\n  d = szHdr;\n  u = 0;\n  while( idx<szHdr && d<=(u32)nKey ){\n    u32 serial_type;\n\n    idx += getVarint32(&aKey[idx], serial_type);\n    pMem->enc = pKeyInfo->enc;\n    pMem->db = pKeyInfo->db;\n    /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */\n    pMem->szMalloc = 0;\n    pMem->z = 0;\n    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);\n    pMem++;\n    if( (++u)>=p->nField ) break;\n  }\n  if( d>(u32)nKey && u ){\n    assert( CORRUPT_DB );\n    /* In a corrupt record entry, the last pMem might have been set up using \n    ** uninitialized memory. Overwrite its value with NULL, to prevent\n    ** warnings from MSAN. */\n    sqlite3VdbeMemSetNull(pMem-1);\n  }\n  assert( u<=pKeyInfo->nKeyField + 1 );\n  p->nField = u;\n}\n\n#ifdef SQLITE_DEBUG\n/*\n** This function compares two index or table record keys in the same way\n** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),\n** this function deserializes and compares values using the\n** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used\n** in assert() statements to ensure that the optimized code in\n** sqlite3VdbeRecordCompare() returns results with these two primitives.\n**\n** Return true if the result of comparison is equivalent to desiredResult.\n** Return false if there is a disagreement.\n*/\nstatic int vdbeRecordCompareDebug(\n  int nKey1, const void *pKey1, /* Left key */\n  const UnpackedRecord *pPKey2, /* Right key */\n  int desiredResult             /* Correct answer */\n){\n  u32 d1;            /* Offset into aKey[] of next data element */\n  u32 idx1;          /* Offset into aKey[] of next header element */\n  u32 szHdr1;        /* Number of bytes in header */\n  int i = 0;\n  int rc = 0;\n  const unsigned char *aKey1 = (const unsigned char *)pKey1;\n  KeyInfo *pKeyInfo;\n  Mem mem1;\n\n  pKeyInfo = pPKey2->pKeyInfo;\n  if( pKeyInfo->db==0 ) return 1;\n  mem1.enc = pKeyInfo->enc;\n  mem1.db = pKeyInfo->db;\n  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */\n  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */\n\n  /* Compilers may complain that mem1.u.i is potentially uninitialized.\n  ** We could initialize it, as shown here, to silence those complaints.\n  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing \n  ** the unnecessary initialization has a measurable negative performance\n  ** impact, since this routine is a very high runner.  And so, we choose\n  ** to ignore the compiler warnings and leave this variable uninitialized.\n  */\n  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */\n  \n  idx1 = getVarint32(aKey1, szHdr1);\n  if( szHdr1>98307 ) return SQLITE_CORRUPT;\n  d1 = szHdr1;\n  assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );\n  assert( pKeyInfo->aSortFlags!=0 );\n  assert( pKeyInfo->nKeyField>0 );\n  assert( idx1<=szHdr1 || CORRUPT_DB );\n  do{\n    u32 serial_type1;\n\n    /* Read the serial types for the next element in each key. */\n    idx1 += getVarint32( aKey1+idx1, serial_type1 );\n\n    /* Verify that there is enough key space remaining to avoid\n    ** a buffer overread.  The \"d1+serial_type1+2\" subexpression will\n    ** always be greater than or equal to the amount of required key space.\n    ** Use that approximation to avoid the more expensive call to\n    ** sqlite3VdbeSerialTypeLen() in the common case.\n    */\n    if( d1+(u64)serial_type1+2>(u64)nKey1\n     && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1 \n    ){\n      break;\n    }\n\n    /* Extract the values to be compared.\n    */\n    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);\n\n    /* Do the comparison\n    */\n    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],\n                           pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0);\n    if( rc!=0 ){\n      assert( mem1.szMalloc==0 );  /* See comment below */\n      if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)\n       && ((mem1.flags & MEM_Null) || (pPKey2->aMem[i].flags & MEM_Null)) \n      ){\n        rc = -rc;\n      }\n      if( pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC ){\n        rc = -rc;  /* Invert the result for DESC sort order. */\n      }\n      goto debugCompareEnd;\n    }\n    i++;\n  }while( idx1<szHdr1 && i<pPKey2->nField );\n\n  /* No memory allocation is ever used on mem1.  Prove this using\n  ** the following assert().  If the assert() fails, it indicates a\n  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).\n  */\n  assert( mem1.szMalloc==0 );\n\n  /* rc==0 here means that one of the keys ran out of fields and\n  ** all the fields up to that point were equal. Return the default_rc\n  ** value.  */\n  rc = pPKey2->default_rc;\n\ndebugCompareEnd:\n  if( desiredResult==0 && rc==0 ) return 1;\n  if( desiredResult<0 && rc<0 ) return 1;\n  if( desiredResult>0 && rc>0 ) return 1;\n  if( CORRUPT_DB ) return 1;\n  if( pKeyInfo->db->mallocFailed ) return 1;\n  return 0;\n}\n#endif\n\n#ifdef SQLITE_DEBUG\n/*\n** Count the number of fields (a.k.a. columns) in the record given by\n** pKey,nKey.  The verify that this count is less than or equal to the\n** limit given by pKeyInfo->nAllField.\n**\n** If this constraint is not satisfied, it means that the high-speed\n** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will\n** not work correctly.  If this assert() ever fires, it probably means\n** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed\n** incorrectly.\n*/\nstatic void vdbeAssertFieldCountWithinLimits(\n  int nKey, const void *pKey,   /* The record to verify */ \n  const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */\n){\n  int nField = 0;\n  u32 szHdr;\n  u32 idx;\n  u32 notUsed;\n  const unsigned char *aKey = (const unsigned char*)pKey;\n\n  if( CORRUPT_DB ) return;\n  idx = getVarint32(aKey, szHdr);\n  assert( nKey>=0 );\n  assert( szHdr<=(u32)nKey );\n  while( idx<szHdr ){\n    idx += getVarint32(aKey+idx, notUsed);\n    nField++;\n  }\n  assert( nField <= pKeyInfo->nAllField );\n}\n#else\n# define vdbeAssertFieldCountWithinLimits(A,B,C)\n#endif\n\n/*\n** Both *pMem1 and *pMem2 contain string values. Compare the two values\n** using the collation sequence pColl. As usual, return a negative , zero\n** or positive value if *pMem1 is less than, equal to or greater than \n** *pMem2, respectively. Similar in spirit to \"rc = (*pMem1) - (*pMem2);\".\n*/\nstatic int vdbeCompareMemString(\n  const Mem *pMem1,\n  const Mem *pMem2,\n  const CollSeq *pColl,\n  u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */\n){\n  if( pMem1->enc==pColl->enc ){\n    /* The strings are already in the correct encoding.  Call the\n     ** comparison function directly */\n    return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);\n  }else{\n    int rc;\n    const void *v1, *v2;\n    Mem c1;\n    Mem c2;\n    sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);\n    sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);\n    sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);\n    sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);\n    v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);\n    v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);\n    if( (v1==0 || v2==0) ){\n      if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;\n      rc = 0;\n    }else{\n      rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);\n    }\n    sqlite3VdbeMemRelease(&c1);\n    sqlite3VdbeMemRelease(&c2);\n    return rc;\n  }\n}\n\n/*\n** The input pBlob is guaranteed to be a Blob that is not marked\n** with MEM_Zero.  Return true if it could be a zero-blob.\n*/\nstatic int isAllZero(const char *z, int n){\n  int i;\n  for(i=0; i<n; i++){\n    if( z[i] ) return 0;\n  }\n  return 1;\n}\n\n/*\n** Compare two blobs.  Return negative, zero, or positive if the first\n** is less than, equal to, or greater than the second, respectively.\n** If one blob is a prefix of the other, then the shorter is the lessor.\n*/\nSQLITE_PRIVATE SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){\n  int c;\n  int n1 = pB1->n;\n  int n2 = pB2->n;\n\n  /* It is possible to have a Blob value that has some non-zero content\n  ** followed by zero content.  But that only comes up for Blobs formed\n  ** by the OP_MakeRecord opcode, and such Blobs never get passed into\n  ** sqlite3MemCompare(). */\n  assert( (pB1->flags & MEM_Zero)==0 || n1==0 );\n  assert( (pB2->flags & MEM_Zero)==0 || n2==0 );\n\n  if( (pB1->flags|pB2->flags) & MEM_Zero ){\n    if( pB1->flags & pB2->flags & MEM_Zero ){\n      return pB1->u.nZero - pB2->u.nZero;\n    }else if( pB1->flags & MEM_Zero ){\n      if( !isAllZero(pB2->z, pB2->n) ) return -1;\n      return pB1->u.nZero - n2;\n    }else{\n      if( !isAllZero(pB1->z, pB1->n) ) return +1;\n      return n1 - pB2->u.nZero;\n    }\n  }\n  c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);\n  if( c ) return c;\n  return n1 - n2;\n}\n\n/*\n** Do a comparison between a 64-bit signed integer and a 64-bit floating-point\n** number.  Return negative, zero, or positive if the first (i64) is less than,\n** equal to, or greater than the second (double).\n*/\nstatic int sqlite3IntFloatCompare(i64 i, double r){\n  if( sizeof(LONGDOUBLE_TYPE)>8 ){\n    LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;\n    if( x<r ) return -1;\n    if( x>r ) return +1;\n    return 0;\n  }else{\n    i64 y;\n    double s;\n    if( r<-9223372036854775808.0 ) return +1;\n    if( r>=9223372036854775808.0 ) return -1;\n    y = (i64)r;\n    if( i<y ) return -1;\n    if( i>y ) return +1;\n    s = (double)i;\n    if( s<r ) return -1;\n    if( s>r ) return +1;\n    return 0;\n  }\n}\n\n/*\n** Compare the values contained by the two memory cells, returning\n** negative, zero or positive if pMem1 is less than, equal to, or greater\n** than pMem2. Sorting order is NULL's first, followed by numbers (integers\n** and reals) sorted numerically, followed by text ordered by the collating\n** sequence pColl and finally blob's ordered by memcmp().\n**\n** Two NULL values are considered equal by this function.\n*/\nSQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){\n  int f1, f2;\n  int combined_flags;\n\n  f1 = pMem1->flags;\n  f2 = pMem2->flags;\n  combined_flags = f1|f2;\n  assert( !sqlite3VdbeMemIsRowSet(pMem1) && !sqlite3VdbeMemIsRowSet(pMem2) );\n \n  /* If one value is NULL, it is less than the other. If both values\n  ** are NULL, return 0.\n  */\n  if( combined_flags&MEM_Null ){\n    return (f2&MEM_Null) - (f1&MEM_Null);\n  }\n\n  /* At least one of the two values is a number\n  */\n  if( combined_flags&(MEM_Int|MEM_Real|MEM_IntReal) ){\n    testcase( combined_flags & MEM_Int );\n    testcase( combined_flags & MEM_Real );\n    testcase( combined_flags & MEM_IntReal );\n    if( (f1 & f2 & (MEM_Int|MEM_IntReal))!=0 ){\n      testcase( f1 & f2 & MEM_Int );\n      testcase( f1 & f2 & MEM_IntReal );\n      if( pMem1->u.i < pMem2->u.i ) return -1;\n      if( pMem1->u.i > pMem2->u.i ) return +1;\n      return 0;\n    }\n    if( (f1 & f2 & MEM_Real)!=0 ){\n      if( pMem1->u.r < pMem2->u.r ) return -1;\n      if( pMem1->u.r > pMem2->u.r ) return +1;\n      return 0;\n    }\n    if( (f1&(MEM_Int|MEM_IntReal))!=0 ){\n      testcase( f1 & MEM_Int );\n      testcase( f1 & MEM_IntReal );\n      if( (f2&MEM_Real)!=0 ){\n        return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);\n      }else if( (f2&(MEM_Int|MEM_IntReal))!=0 ){\n        if( pMem1->u.i < pMem2->u.i ) return -1;\n        if( pMem1->u.i > pMem2->u.i ) return +1;\n        return 0;\n      }else{\n        return -1;\n      }\n    }\n    if( (f1&MEM_Real)!=0 ){\n      if( (f2&(MEM_Int|MEM_IntReal))!=0 ){\n        testcase( f2 & MEM_Int );\n        testcase( f2 & MEM_IntReal );\n        return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);\n      }else{\n        return -1;\n      }\n    }\n    return +1;\n  }\n\n  /* If one value is a string and the other is a blob, the string is less.\n  ** If both are strings, compare using the collating functions.\n  */\n  if( combined_flags&MEM_Str ){\n    if( (f1 & MEM_Str)==0 ){\n      return 1;\n    }\n    if( (f2 & MEM_Str)==0 ){\n      return -1;\n    }\n\n    assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );\n    assert( pMem1->enc==SQLITE_UTF8 || \n            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );\n\n    /* The collation sequence must be defined at this point, even if\n    ** the user deletes the collation sequence after the vdbe program is\n    ** compiled (this was not always the case).\n    */\n    assert( !pColl || pColl->xCmp );\n\n    if( pColl ){\n      return vdbeCompareMemString(pMem1, pMem2, pColl, 0);\n    }\n    /* If a NULL pointer was passed as the collate function, fall through\n    ** to the blob case and use memcmp().  */\n  }\n \n  /* Both values must be blobs.  Compare using memcmp().  */\n  return sqlite3BlobCompare(pMem1, pMem2);\n}\n\n\n/*\n** The first argument passed to this function is a serial-type that\n** corresponds to an integer - all values between 1 and 9 inclusive \n** except 7. The second points to a buffer containing an integer value\n** serialized according to serial_type. This function deserializes\n** and returns the value.\n*/\nstatic i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){\n  u32 y;\n  assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );\n  switch( serial_type ){\n    case 0:\n    case 1:\n      testcase( aKey[0]&0x80 );\n      return ONE_BYTE_INT(aKey);\n    case 2:\n      testcase( aKey[0]&0x80 );\n      return TWO_BYTE_INT(aKey);\n    case 3:\n      testcase( aKey[0]&0x80 );\n      return THREE_BYTE_INT(aKey);\n    case 4: {\n      testcase( aKey[0]&0x80 );\n      y = FOUR_BYTE_UINT(aKey);\n      return (i64)*(int*)&y;\n    }\n    case 5: {\n      testcase( aKey[0]&0x80 );\n      return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);\n    }\n    case 6: {\n      u64 x = FOUR_BYTE_UINT(aKey);\n      testcase( aKey[0]&0x80 );\n      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);\n      return (i64)*(i64*)&x;\n    }\n  }\n\n  return (serial_type - 8);\n}\n\n/*\n** This function compares the two table rows or index records\n** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero\n** or positive integer if key1 is less than, equal to or \n** greater than key2.  The {nKey1, pKey1} key must be a blob\n** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2\n** key must be a parsed key such as obtained from\n** sqlite3VdbeParseRecord.\n**\n** If argument bSkip is non-zero, it is assumed that the caller has already\n** determined that the first fields of the keys are equal.\n**\n** Key1 and Key2 do not have to contain the same number of fields. If all \n** fields that appear in both keys are equal, then pPKey2->default_rc is \n** returned.\n**\n** If database corruption is discovered, set pPKey2->errCode to \n** SQLITE_CORRUPT and return 0. If an OOM error is encountered, \n** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the\n** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).\n*/\nSQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(\n  int nKey1, const void *pKey1,   /* Left key */\n  UnpackedRecord *pPKey2,         /* Right key */\n  int bSkip                       /* If true, skip the first field */\n){\n  u32 d1;                         /* Offset into aKey[] of next data element */\n  int i;                          /* Index of next field to compare */\n  u32 szHdr1;                     /* Size of record header in bytes */\n  u32 idx1;                       /* Offset of first type in header */\n  int rc = 0;                     /* Return value */\n  Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */\n  KeyInfo *pKeyInfo;\n  const unsigned char *aKey1 = (const unsigned char *)pKey1;\n  Mem mem1;\n\n  /* If bSkip is true, then the caller has already determined that the first\n  ** two elements in the keys are equal. Fix the various stack variables so\n  ** that this routine begins comparing at the second field. */\n  if( bSkip ){\n    u32 s1;\n    idx1 = 1 + getVarint32(&aKey1[1], s1);\n    szHdr1 = aKey1[0];\n    d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);\n    i = 1;\n    pRhs++;\n  }else{\n    idx1 = getVarint32(aKey1, szHdr1);\n    d1 = szHdr1;\n    i = 0;\n  }\n  if( d1>(unsigned)nKey1 ){ \n    pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;\n    return 0;  /* Corruption */\n  }\n\n  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */\n  assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField \n       || CORRUPT_DB );\n  assert( pPKey2->pKeyInfo->aSortFlags!=0 );\n  assert( pPKey2->pKeyInfo->nKeyField>0 );\n  assert( idx1<=szHdr1 || CORRUPT_DB );\n  do{\n    u32 serial_type;\n\n    /* RHS is an integer */\n    if( pRhs->flags & (MEM_Int|MEM_IntReal) ){\n      testcase( pRhs->flags & MEM_Int );\n      testcase( pRhs->flags & MEM_IntReal );\n      serial_type = aKey1[idx1];\n      testcase( serial_type==12 );\n      if( serial_type>=10 ){\n        rc = +1;\n      }else if( serial_type==0 ){\n        rc = -1;\n      }else if( serial_type==7 ){\n        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);\n        rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);\n      }else{\n        i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);\n        i64 rhs = pRhs->u.i;\n        if( lhs<rhs ){\n          rc = -1;\n        }else if( lhs>rhs ){\n          rc = +1;\n        }\n      }\n    }\n\n    /* RHS is real */\n    else if( pRhs->flags & MEM_Real ){\n      serial_type = aKey1[idx1];\n      if( serial_type>=10 ){\n        /* Serial types 12 or greater are strings and blobs (greater than\n        ** numbers). Types 10 and 11 are currently \"reserved for future \n        ** use\", so it doesn't really matter what the results of comparing\n        ** them to numberic values are.  */\n        rc = +1;\n      }else if( serial_type==0 ){\n        rc = -1;\n      }else{\n        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);\n        if( serial_type==7 ){\n          if( mem1.u.r<pRhs->u.r ){\n            rc = -1;\n          }else if( mem1.u.r>pRhs->u.r ){\n            rc = +1;\n          }\n        }else{\n          rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);\n        }\n      }\n    }\n\n    /* RHS is a string */\n    else if( pRhs->flags & MEM_Str ){\n      getVarint32NR(&aKey1[idx1], serial_type);\n      testcase( serial_type==12 );\n      if( serial_type<12 ){\n        rc = -1;\n      }else if( !(serial_type & 0x01) ){\n        rc = +1;\n      }else{\n        mem1.n = (serial_type - 12) / 2;\n        testcase( (d1+mem1.n)==(unsigned)nKey1 );\n        testcase( (d1+mem1.n+1)==(unsigned)nKey1 );\n        if( (d1+mem1.n) > (unsigned)nKey1\n         || (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i\n        ){\n          pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;\n          return 0;                /* Corruption */\n        }else if( pKeyInfo->aColl[i] ){\n          mem1.enc = pKeyInfo->enc;\n          mem1.db = pKeyInfo->db;\n          mem1.flags = MEM_Str;\n          mem1.z = (char*)&aKey1[d1];\n          rc = vdbeCompareMemString(\n              &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode\n          );\n        }else{\n          int nCmp = MIN(mem1.n, pRhs->n);\n          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);\n          if( rc==0 ) rc = mem1.n - pRhs->n; \n        }\n      }\n    }\n\n    /* RHS is a blob */\n    else if( pRhs->flags & MEM_Blob ){\n      assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );\n      getVarint32NR(&aKey1[idx1], serial_type);\n      testcase( serial_type==12 );\n      if( serial_type<12 || (serial_type & 0x01) ){\n        rc = -1;\n      }else{\n        int nStr = (serial_type - 12) / 2;\n        testcase( (d1+nStr)==(unsigned)nKey1 );\n        testcase( (d1+nStr+1)==(unsigned)nKey1 );\n        if( (d1+nStr) > (unsigned)nKey1 ){\n          pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;\n          return 0;                /* Corruption */\n        }else if( pRhs->flags & MEM_Zero ){\n          if( !isAllZero((const char*)&aKey1[d1],nStr) ){\n            rc = 1;\n          }else{\n            rc = nStr - pRhs->u.nZero;\n          }\n        }else{\n          int nCmp = MIN(nStr, pRhs->n);\n          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);\n          if( rc==0 ) rc = nStr - pRhs->n;\n        }\n      }\n    }\n\n    /* RHS is null */\n    else{\n      serial_type = aKey1[idx1];\n      rc = (serial_type!=0);\n    }\n\n    if( rc!=0 ){\n      int sortFlags = pPKey2->pKeyInfo->aSortFlags[i];\n      if( sortFlags ){\n        if( (sortFlags & KEYINFO_ORDER_BIGNULL)==0\n         || ((sortFlags & KEYINFO_ORDER_DESC)\n           !=(serial_type==0 || (pRhs->flags&MEM_Null)))\n        ){\n          rc = -rc;\n        }\n      }\n      assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );\n      assert( mem1.szMalloc==0 );  /* See comment below */\n      return rc;\n    }\n\n    i++;\n    if( i==pPKey2->nField ) break;\n    pRhs++;\n    d1 += sqlite3VdbeSerialTypeLen(serial_type);\n    idx1 += sqlite3VarintLen(serial_type);\n  }while( idx1<(unsigned)szHdr1 && d1<=(unsigned)nKey1 );\n\n  /* No memory allocation is ever used on mem1.  Prove this using\n  ** the following assert().  If the assert() fails, it indicates a\n  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */\n  assert( mem1.szMalloc==0 );\n\n  /* rc==0 here means that one or both of the keys ran out of fields and\n  ** all the fields up to that point were equal. Return the default_rc\n  ** value.  */\n  assert( CORRUPT_DB \n       || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc) \n       || pPKey2->pKeyInfo->db->mallocFailed\n  );\n  pPKey2->eqSeen = 1;\n  return pPKey2->default_rc;\n}\nSQLITE_PRIVATE int sqlite3VdbeRecordCompare(\n  int nKey1, const void *pKey1,   /* Left key */\n  UnpackedRecord *pPKey2          /* Right key */\n){\n  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);\n}\n\n\n/*\n** This function is an optimized version of sqlite3VdbeRecordCompare() \n** that (a) the first field of pPKey2 is an integer, and (b) the \n** size-of-header varint at the start of (pKey1/nKey1) fits in a single\n** byte (i.e. is less than 128).\n**\n** To avoid concerns about buffer overreads, this routine is only used\n** on schemas where the maximum valid header size is 63 bytes or less.\n*/\nstatic int vdbeRecordCompareInt(\n  int nKey1, const void *pKey1, /* Left key */\n  UnpackedRecord *pPKey2        /* Right key */\n){\n  const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];\n  int serial_type = ((const u8*)pKey1)[1];\n  int res;\n  u32 y;\n  u64 x;\n  i64 v;\n  i64 lhs;\n\n  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);\n  assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );\n  switch( serial_type ){\n    case 1: { /* 1-byte signed integer */\n      lhs = ONE_BYTE_INT(aKey);\n      testcase( lhs<0 );\n      break;\n    }\n    case 2: { /* 2-byte signed integer */\n      lhs = TWO_BYTE_INT(aKey);\n      testcase( lhs<0 );\n      break;\n    }\n    case 3: { /* 3-byte signed integer */\n      lhs = THREE_BYTE_INT(aKey);\n      testcase( lhs<0 );\n      break;\n    }\n    case 4: { /* 4-byte signed integer */\n      y = FOUR_BYTE_UINT(aKey);\n      lhs = (i64)*(int*)&y;\n      testcase( lhs<0 );\n      break;\n    }\n    case 5: { /* 6-byte signed integer */\n      lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);\n      testcase( lhs<0 );\n      break;\n    }\n    case 6: { /* 8-byte signed integer */\n      x = FOUR_BYTE_UINT(aKey);\n      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);\n      lhs = *(i64*)&x;\n      testcase( lhs<0 );\n      break;\n    }\n    case 8: \n      lhs = 0;\n      break;\n    case 9:\n      lhs = 1;\n      break;\n\n    /* This case could be removed without changing the results of running\n    ** this code. Including it causes gcc to generate a faster switch \n    ** statement (since the range of switch targets now starts at zero and\n    ** is contiguous) but does not cause any duplicate code to be generated\n    ** (as gcc is clever enough to combine the two like cases). Other \n    ** compilers might be similar.  */ \n    case 0: case 7:\n      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);\n\n    default:\n      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);\n  }\n\n  v = pPKey2->aMem[0].u.i;\n  if( v>lhs ){\n    res = pPKey2->r1;\n  }else if( v<lhs ){\n    res = pPKey2->r2;\n  }else if( pPKey2->nField>1 ){\n    /* The first fields of the two keys are equal. Compare the trailing \n    ** fields.  */\n    res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);\n  }else{\n    /* The first fields of the two keys are equal and there are no trailing\n    ** fields. Return pPKey2->default_rc in this case. */\n    res = pPKey2->default_rc;\n    pPKey2->eqSeen = 1;\n  }\n\n  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );\n  return res;\n}\n\n/*\n** This function is an optimized version of sqlite3VdbeRecordCompare() \n** that (a) the first field of pPKey2 is a string, that (b) the first field\n** uses the collation sequence BINARY and (c) that the size-of-header varint \n** at the start of (pKey1/nKey1) fits in a single byte.\n*/\nstatic int vdbeRecordCompareString(\n  int nKey1, const void *pKey1, /* Left key */\n  UnpackedRecord *pPKey2        /* Right key */\n){\n  const u8 *aKey1 = (const u8*)pKey1;\n  int serial_type;\n  int res;\n\n  assert( pPKey2->aMem[0].flags & MEM_Str );\n  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);\n  serial_type = (u8)(aKey1[1]);\n  if( serial_type >= 0x80 ){\n    sqlite3GetVarint32(&aKey1[1], (u32*)&serial_type);\n  }\n  if( serial_type<12 ){\n    res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */\n  }else if( !(serial_type & 0x01) ){ \n    res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */\n  }else{\n    int nCmp;\n    int nStr;\n    int szHdr = aKey1[0];\n\n    nStr = (serial_type-12) / 2;\n    if( (szHdr + nStr) > nKey1 ){\n      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;\n      return 0;    /* Corruption */\n    }\n    nCmp = MIN( pPKey2->aMem[0].n, nStr );\n    res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);\n\n    if( res>0 ){\n      res = pPKey2->r2;\n    }else if( res<0 ){\n      res = pPKey2->r1;\n    }else{\n      res = nStr - pPKey2->aMem[0].n;\n      if( res==0 ){\n        if( pPKey2->nField>1 ){\n          res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);\n        }else{\n          res = pPKey2->default_rc;\n          pPKey2->eqSeen = 1;\n        }\n      }else if( res>0 ){\n        res = pPKey2->r2;\n      }else{\n        res = pPKey2->r1;\n      }\n    }\n  }\n\n  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)\n       || CORRUPT_DB\n       || pPKey2->pKeyInfo->db->mallocFailed\n  );\n  return res;\n}\n\n/*\n** Return a pointer to an sqlite3VdbeRecordCompare() compatible function\n** suitable for comparing serialized records to the unpacked record passed\n** as the only argument.\n*/\nSQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){\n  /* varintRecordCompareInt() and varintRecordCompareString() both assume\n  ** that the size-of-header varint that occurs at the start of each record\n  ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()\n  ** also assumes that it is safe to overread a buffer by at least the \n  ** maximum possible legal header size plus 8 bytes. Because there is\n  ** guaranteed to be at least 74 (but not 136) bytes of padding following each\n  ** buffer passed to varintRecordCompareInt() this makes it convenient to\n  ** limit the size of the header to 64 bytes in cases where the first field\n  ** is an integer.\n  **\n  ** The easiest way to enforce this limit is to consider only records with\n  ** 13 fields or less. If the first field is an integer, the maximum legal\n  ** header size is (12*5 + 1 + 1) bytes.  */\n  if( p->pKeyInfo->nAllField<=13 ){\n    int flags = p->aMem[0].flags;\n    if( p->pKeyInfo->aSortFlags[0] ){\n      if( p->pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL ){\n        return sqlite3VdbeRecordCompare;\n      }\n      p->r1 = 1;\n      p->r2 = -1;\n    }else{\n      p->r1 = -1;\n      p->r2 = 1;\n    }\n    if( (flags & MEM_Int) ){\n      return vdbeRecordCompareInt;\n    }\n    testcase( flags & MEM_Real );\n    testcase( flags & MEM_Null );\n    testcase( flags & MEM_Blob );\n    if( (flags & (MEM_Real|MEM_IntReal|MEM_Null|MEM_Blob))==0\n     && p->pKeyInfo->aColl[0]==0\n    ){\n      assert( flags & MEM_Str );\n      return vdbeRecordCompareString;\n    }\n  }\n\n  return sqlite3VdbeRecordCompare;\n}\n\n/*\n** pCur points at an index entry created using the OP_MakeRecord opcode.\n** Read the rowid (the last field in the record) and store it in *rowid.\n** Return SQLITE_OK if everything works, or an error code otherwise.\n**\n** pCur might be pointing to text obtained from a corrupt database file.\n** So the content cannot be trusted.  Do appropriate checks on the content.\n*/\nSQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){\n  i64 nCellKey = 0;\n  int rc;\n  u32 szHdr;        /* Size of the header */\n  u32 typeRowid;    /* Serial type of the rowid */\n  u32 lenRowid;     /* Size of the rowid */\n  Mem m, v;\n\n  /* Get the size of the index entry.  Only indices entries of less\n  ** than 2GiB are support - anything large must be database corruption.\n  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so\n  ** this code can safely assume that nCellKey is 32-bits  \n  */\n  assert( sqlite3BtreeCursorIsValid(pCur) );\n  nCellKey = sqlite3BtreePayloadSize(pCur);\n  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );\n\n  /* Read in the complete content of the index entry */\n  sqlite3VdbeMemInit(&m, db, 0);\n  rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);\n  if( rc ){\n    return rc;\n  }\n\n  /* The index entry must begin with a header size */\n  getVarint32NR((u8*)m.z, szHdr);\n  testcase( szHdr==3 );\n  testcase( szHdr==m.n );\n  testcase( szHdr>0x7fffffff );\n  assert( m.n>=0 );\n  if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){\n    goto idx_rowid_corruption;\n  }\n\n  /* The last field of the index should be an integer - the ROWID.\n  ** Verify that the last entry really is an integer. */\n  getVarint32NR((u8*)&m.z[szHdr-1], typeRowid);\n  testcase( typeRowid==1 );\n  testcase( typeRowid==2 );\n  testcase( typeRowid==3 );\n  testcase( typeRowid==4 );\n  testcase( typeRowid==5 );\n  testcase( typeRowid==6 );\n  testcase( typeRowid==8 );\n  testcase( typeRowid==9 );\n  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){\n    goto idx_rowid_corruption;\n  }\n  lenRowid = sqlite3SmallTypeSizes[typeRowid];\n  testcase( (u32)m.n==szHdr+lenRowid );\n  if( unlikely((u32)m.n<szHdr+lenRowid) ){\n    goto idx_rowid_corruption;\n  }\n\n  /* Fetch the integer off the end of the index record */\n  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);\n  *rowid = v.u.i;\n  sqlite3VdbeMemRelease(&m);\n  return SQLITE_OK;\n\n  /* Jump here if database corruption is detected after m has been\n  ** allocated.  Free the m object and return SQLITE_CORRUPT. */\nidx_rowid_corruption:\n  testcase( m.szMalloc!=0 );\n  sqlite3VdbeMemRelease(&m);\n  return SQLITE_CORRUPT_BKPT;\n}\n\n/*\n** Compare the key of the index entry that cursor pC is pointing to against\n** the key string in pUnpacked.  Write into *pRes a number\n** that is negative, zero, or positive if pC is less than, equal to,\n** or greater than pUnpacked.  Return SQLITE_OK on success.\n**\n** pUnpacked is either created without a rowid or is truncated so that it\n** omits the rowid at the end.  The rowid at the end of the index entry\n** is ignored as well.  Hence, this routine only compares the prefixes \n** of the keys prior to the final rowid, not the entire key.\n*/\nSQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(\n  sqlite3 *db,                     /* Database connection */\n  VdbeCursor *pC,                  /* The cursor to compare against */\n  UnpackedRecord *pUnpacked,       /* Unpacked version of key */\n  int *res                         /* Write the comparison result here */\n){\n  i64 nCellKey = 0;\n  int rc;\n  BtCursor *pCur;\n  Mem m;\n\n  assert( pC->eCurType==CURTYPE_BTREE );\n  pCur = pC->uc.pCursor;\n  assert( sqlite3BtreeCursorIsValid(pCur) );\n  nCellKey = sqlite3BtreePayloadSize(pCur);\n  /* nCellKey will always be between 0 and 0xffffffff because of the way\n  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */\n  if( nCellKey<=0 || nCellKey>0x7fffffff ){\n    *res = 0;\n    return SQLITE_CORRUPT_BKPT;\n  }\n  sqlite3VdbeMemInit(&m, db, 0);\n  rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);\n  if( rc ){\n    return rc;\n  }\n  *res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, pUnpacked, 0);\n  sqlite3VdbeMemRelease(&m);\n  return SQLITE_OK;\n}\n\n/*\n** This routine sets the value to be returned by subsequent calls to\n** sqlite3_changes() on the database handle 'db'. \n*/\nSQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){\n  assert( sqlite3_mutex_held(db->mutex) );\n  db->nChange = nChange;\n  db->nTotalChange += nChange;\n}\n\n/*\n** Set a flag in the vdbe to update the change counter when it is finalised\n** or reset.\n*/\nSQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){\n  v->changeCntOn = 1;\n}\n\n/*\n** Mark every prepared statement associated with a database connection\n** as expired.\n**\n** An expired statement means that recompilation of the statement is\n** recommend.  Statements expire when things happen that make their\n** programs obsolete.  Removing user-defined functions or collating\n** sequences, or changing an authorization function are the types of\n** things that make prepared statements obsolete.\n**\n** If iCode is 1, then expiration is advisory.  The statement should\n** be reprepared before being restarted, but if it is already running\n** it is allowed to run to completion.\n**\n** Internally, this function just sets the Vdbe.expired flag on all\n** prepared statements.  The flag is set to 1 for an immediate expiration\n** and set to 2 for an advisory expiration.\n*/\nSQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db, int iCode){\n  Vdbe *p;\n  for(p = db->pVdbe; p; p=p->pNext){\n    p->expired = iCode+1;\n  }\n}\n\n/*\n** Return the database associated with the Vdbe.\n*/\nSQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){\n  return v->db;\n}\n\n/*\n** Return the SQLITE_PREPARE flags for a Vdbe.\n*/\nSQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){\n  return v->prepFlags;\n}\n\n/*\n** Return a pointer to an sqlite3_value structure containing the value bound\n** parameter iVar of VM v. Except, if the value is an SQL NULL, return \n** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*\n** constants) to the value before returning it.\n**\n** The returned value must be freed by the caller using sqlite3ValueFree().\n*/\nSQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){\n  assert( iVar>0 );\n  if( v ){\n    Mem *pMem = &v->aVar[iVar-1];\n    assert( (v->db->flags & SQLITE_EnableQPSG)==0 );\n    if( 0==(pMem->flags & MEM_Null) ){\n      sqlite3_value *pRet = sqlite3ValueNew(v->db);\n      if( pRet ){\n        sqlite3VdbeMemCopy((Mem *)pRet, pMem);\n        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);\n      }\n      return pRet;\n    }\n  }\n  return 0;\n}\n\n/*\n** Configure SQL variable iVar so that binding a new value to it signals\n** to sqlite3_reoptimize() that re-preparing the statement may result\n** in a better query plan.\n*/\nSQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){\n  assert( iVar>0 );\n  assert( (v->db->flags & SQLITE_EnableQPSG)==0 );\n  if( iVar>=32 ){\n    v->expmask |= 0x80000000;\n  }else{\n    v->expmask |= ((u32)1 << (iVar-1));\n  }\n}\n\n/*\n** Cause a function to throw an error if it was call from OP_PureFunc\n** rather than OP_Function.\n**\n** OP_PureFunc means that the function must be deterministic, and should\n** throw an error if it is given inputs that would make it non-deterministic.\n** This routine is invoked by date/time functions that use non-deterministic\n** features such as 'now'.\n*/\nSQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){\n  const VdbeOp *pOp;\n#ifdef SQLITE_ENABLE_STAT4\n  if( pCtx->pVdbe==0 ) return 1;\n#endif\n  pOp = pCtx->pVdbe->aOp + pCtx->iOp;\n  if( pOp->opcode==OP_PureFunc ){\n    const char *zContext;\n    char *zMsg;\n    if( pOp->p5 & NC_IsCheck ){\n      zContext = \"a CHECK constraint\";\n    }else if( pOp->p5 & NC_GenCol ){\n      zContext = \"a generated column\";\n    }else{\n      zContext = \"an index\";\n    }\n    zMsg = sqlite3_mprintf(\"non-deterministic use of %s() in %s\",\n                           pCtx->pFunc->zName, zContext);\n    sqlite3_result_error(pCtx, zMsg, -1);\n    sqlite3_free(zMsg);\n    return 0;\n  }\n  return 1;\n}\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/*\n** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored\n** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored\n** in memory obtained from sqlite3DbMalloc).\n*/\nSQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){\n  if( pVtab->zErrMsg ){\n    sqlite3 *db = p->db;\n    sqlite3DbFree(db, p->zErrMsg);\n    p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);\n    sqlite3_free(pVtab->zErrMsg);\n    pVtab->zErrMsg = 0;\n  }\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n\n/*\n** If the second argument is not NULL, release any allocations associated \n** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord\n** structure itself, using sqlite3DbFree().\n**\n** This function is used to free UnpackedRecord structures allocated by\n** the vdbeUnpackRecord() function found in vdbeapi.c.\n*/\nstatic void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){\n  if( p ){\n    int i;\n    for(i=0; i<nField; i++){\n      Mem *pMem = &p->aMem[i];\n      if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);\n    }\n    sqlite3DbFreeNN(db, p);\n  }\n}\n#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */\n\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n/*\n** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,\n** then cursor passed as the second argument should point to the row about\n** to be update or deleted. If the application calls sqlite3_preupdate_old(),\n** the required value will be read from the row the cursor points to.\n*/\nSQLITE_PRIVATE void sqlite3VdbePreUpdateHook(\n  Vdbe *v,                        /* Vdbe pre-update hook is invoked by */\n  VdbeCursor *pCsr,               /* Cursor to grab old.* values from */\n  int op,                         /* SQLITE_INSERT, UPDATE or DELETE */\n  const char *zDb,                /* Database name */\n  Table *pTab,                    /* Modified table */\n  i64 iKey1,                      /* Initial key value */\n  int iReg                        /* Register for new.* record */\n){\n  sqlite3 *db = v->db;\n  i64 iKey2;\n  PreUpdate preupdate;\n  const char *zTbl = pTab->zName;\n  static const u8 fakeSortOrder = 0;\n\n  assert( db->pPreUpdate==0 );\n  memset(&preupdate, 0, sizeof(PreUpdate));\n  if( HasRowid(pTab)==0 ){\n    iKey1 = iKey2 = 0;\n    preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);\n  }else{\n    if( op==SQLITE_UPDATE ){\n      iKey2 = v->aMem[iReg].u.i;\n    }else{\n      iKey2 = iKey1;\n    }\n  }\n\n  assert( pCsr->nField==pTab->nCol \n       || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)\n  );\n\n  preupdate.v = v;\n  preupdate.pCsr = pCsr;\n  preupdate.op = op;\n  preupdate.iNewReg = iReg;\n  preupdate.keyinfo.db = db;\n  preupdate.keyinfo.enc = ENC(db);\n  preupdate.keyinfo.nKeyField = pTab->nCol;\n  preupdate.keyinfo.aSortFlags = (u8*)&fakeSortOrder;\n  preupdate.iKey1 = iKey1;\n  preupdate.iKey2 = iKey2;\n  preupdate.pTab = pTab;\n\n  db->pPreUpdate = &preupdate;\n  db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);\n  db->pPreUpdate = 0;\n  sqlite3DbFree(db, preupdate.aRecord);\n  vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);\n  vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);\n  if( preupdate.aNew ){\n    int i;\n    for(i=0; i<pCsr->nField; i++){\n      sqlite3VdbeMemRelease(&preupdate.aNew[i]);\n    }\n    sqlite3DbFreeNN(db, preupdate.aNew);\n  }\n}\n#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */\n\n/************** End of vdbeaux.c *********************************************/\n/************** Begin file vdbeapi.c *****************************************/\n/*\n** 2004 May 26\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains code use to implement APIs that are part of the\n** VDBE.\n*/\n/* #include \"sqliteInt.h\" */\n/* #include \"vdbeInt.h\" */\n\n#ifndef SQLITE_OMIT_DEPRECATED\n/*\n** Return TRUE (non-zero) of the statement supplied as an argument needs\n** to be recompiled.  A statement needs to be recompiled whenever the\n** execution environment changes in a way that would alter the program\n** that sqlite3_prepare() generates.  For example, if new functions or\n** collating sequences are registered or if an authorizer function is\n** added or changed.\n*/\nSQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){\n  Vdbe *p = (Vdbe*)pStmt;\n  return p==0 || p->expired;\n}\n#endif\n\n/*\n** Check on a Vdbe to make sure it has not been finalized.  Log\n** an error and return true if it has been finalized (or is otherwise\n** invalid).  Return false if it is ok.\n*/\nstatic int vdbeSafety(Vdbe *p){\n  if( p->db==0 ){\n    sqlite3_log(SQLITE_MISUSE, \"API called with finalized prepared statement\");\n    return 1;\n  }else{\n    return 0;\n  }\n}\nstatic int vdbeSafetyNotNull(Vdbe *p){\n  if( p==0 ){\n    sqlite3_log(SQLITE_MISUSE, \"API called with NULL prepared statement\");\n    return 1;\n  }else{\n    return vdbeSafety(p);\n  }\n}\n\n#ifndef SQLITE_OMIT_TRACE\n/*\n** Invoke the profile callback.  This routine is only called if we already\n** know that the profile callback is defined and needs to be invoked.\n*/\nstatic SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){\n  sqlite3_int64 iNow;\n  sqlite3_int64 iElapse;\n  assert( p->startTime>0 );\n  assert( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0 );\n  assert( db->init.busy==0 );\n  assert( p->zSql!=0 );\n  sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);\n  iElapse = (iNow - p->startTime)*1000000;\n#ifndef SQLITE_OMIT_DEPRECATED\n  if( db->xProfile ){\n    db->xProfile(db->pProfileArg, p->zSql, iElapse);\n  }\n#endif\n  if( db->mTrace & SQLITE_TRACE_PROFILE ){\n    db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);\n  }\n  p->startTime = 0;\n}\n/*\n** The checkProfileCallback(DB,P) macro checks to see if a profile callback\n** is needed, and it invokes the callback if it is needed.\n*/\n# define checkProfileCallback(DB,P) \\\n   if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }\n#else\n# define checkProfileCallback(DB,P)  /*no-op*/\n#endif\n\n/*\n** The following routine destroys a virtual machine that is created by\n** the sqlite3_compile() routine. The integer returned is an SQLITE_\n** success/failure code that describes the result of executing the virtual\n** machine.\n**\n** This routine sets the error code and string returned by\n** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().\n*/\nSQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){\n  int rc;\n  if( pStmt==0 ){\n    /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL\n    ** pointer is a harmless no-op. */\n    rc = SQLITE_OK;\n  }else{\n    Vdbe *v = (Vdbe*)pStmt;\n    sqlite3 *db = v->db;\n    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;\n    sqlite3_mutex_enter(db->mutex);\n    checkProfileCallback(db, v);\n    rc = sqlite3VdbeFinalize(v);\n    rc = sqlite3ApiExit(db, rc);\n    sqlite3LeaveMutexAndCloseZombie(db);\n  }\n  return rc;\n}\n\n/*\n** Terminate the current execution of an SQL statement and reset it\n** back to its starting state so that it can be reused. A success code from\n** the prior execution is returned.\n**\n** This routine sets the error code and string returned by\n** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().\n*/\nSQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){\n  int rc;\n  if( pStmt==0 ){\n    rc = SQLITE_OK;\n  }else{\n    Vdbe *v = (Vdbe*)pStmt;\n    sqlite3 *db = v->db;\n    sqlite3_mutex_enter(db->mutex);\n    checkProfileCallback(db, v);\n    rc = sqlite3VdbeReset(v);\n    sqlite3VdbeRewind(v);\n    assert( (rc & (db->errMask))==rc );\n    rc = sqlite3ApiExit(db, rc);\n    sqlite3_mutex_leave(db->mutex);\n  }\n  return rc;\n}\n\n/*\n** Set all the parameters in the compiled SQL statement to NULL.\n*/\nSQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){\n  int i;\n  int rc = SQLITE_OK;\n  Vdbe *p = (Vdbe*)pStmt;\n#if SQLITE_THREADSAFE\n  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;\n#endif\n  sqlite3_mutex_enter(mutex);\n  for(i=0; i<p->nVar; i++){\n    sqlite3VdbeMemRelease(&p->aVar[i]);\n    p->aVar[i].flags = MEM_Null;\n  }\n  assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );\n  if( p->expmask ){\n    p->expired = 1;\n  }\n  sqlite3_mutex_leave(mutex);\n  return rc;\n}\n\n\n/**************************** sqlite3_value_  *******************************\n** The following routines extract information from a Mem or sqlite3_value\n** structure.\n*/\nSQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){\n  Mem *p = (Mem*)pVal;\n  if( p->flags & (MEM_Blob|MEM_Str) ){\n    if( ExpandBlob(p)!=SQLITE_OK ){\n      assert( p->flags==MEM_Null && p->z==0 );\n      return 0;\n    }\n    p->flags |= MEM_Blob;\n    return p->n ? p->z : 0;\n  }else{\n    return sqlite3_value_text(pVal);\n  }\n}\nSQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){\n  return sqlite3ValueBytes(pVal, SQLITE_UTF8);\n}\nSQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){\n  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);\n}\nSQLITE_API double sqlite3_value_double(sqlite3_value *pVal){\n  return sqlite3VdbeRealValue((Mem*)pVal);\n}\nSQLITE_API int sqlite3_value_int(sqlite3_value *pVal){\n  return (int)sqlite3VdbeIntValue((Mem*)pVal);\n}\nSQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){\n  return sqlite3VdbeIntValue((Mem*)pVal);\n}\nSQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){\n  Mem *pMem = (Mem*)pVal;\n  return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);\n}\nSQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){\n  Mem *p = (Mem*)pVal;\n  if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==\n                 (MEM_Null|MEM_Term|MEM_Subtype)\n   && zPType!=0\n   && p->eSubtype=='p'\n   && strcmp(p->u.zPType, zPType)==0\n  ){\n    return (void*)p->z;\n  }else{\n    return 0;\n  }\n}\nSQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){\n  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){\n  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);\n}\nSQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){\n  return sqlite3ValueText(pVal, SQLITE_UTF16BE);\n}\nSQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){\n  return sqlite3ValueText(pVal, SQLITE_UTF16LE);\n}\n#endif /* SQLITE_OMIT_UTF16 */\n/* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five\n** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating\n** point number string BLOB NULL\n*/\nSQLITE_API int sqlite3_value_type(sqlite3_value* pVal){\n  static const u8 aType[] = {\n     SQLITE_BLOB,     /* 0x00 (not possible) */\n     SQLITE_NULL,     /* 0x01 NULL */\n     SQLITE_TEXT,     /* 0x02 TEXT */\n     SQLITE_NULL,     /* 0x03 (not possible) */\n     SQLITE_INTEGER,  /* 0x04 INTEGER */\n     SQLITE_NULL,     /* 0x05 (not possible) */\n     SQLITE_INTEGER,  /* 0x06 INTEGER + TEXT */\n     SQLITE_NULL,     /* 0x07 (not possible) */\n     SQLITE_FLOAT,    /* 0x08 FLOAT */\n     SQLITE_NULL,     /* 0x09 (not possible) */\n     SQLITE_FLOAT,    /* 0x0a FLOAT + TEXT */\n     SQLITE_NULL,     /* 0x0b (not possible) */\n     SQLITE_INTEGER,  /* 0x0c (not possible) */\n     SQLITE_NULL,     /* 0x0d (not possible) */\n     SQLITE_INTEGER,  /* 0x0e (not possible) */\n     SQLITE_NULL,     /* 0x0f (not possible) */\n     SQLITE_BLOB,     /* 0x10 BLOB */\n     SQLITE_NULL,     /* 0x11 (not possible) */\n     SQLITE_TEXT,     /* 0x12 (not possible) */\n     SQLITE_NULL,     /* 0x13 (not possible) */\n     SQLITE_INTEGER,  /* 0x14 INTEGER + BLOB */\n     SQLITE_NULL,     /* 0x15 (not possible) */\n     SQLITE_INTEGER,  /* 0x16 (not possible) */\n     SQLITE_NULL,     /* 0x17 (not possible) */\n     SQLITE_FLOAT,    /* 0x18 FLOAT + BLOB */\n     SQLITE_NULL,     /* 0x19 (not possible) */\n     SQLITE_FLOAT,    /* 0x1a (not possible) */\n     SQLITE_NULL,     /* 0x1b (not possible) */\n     SQLITE_INTEGER,  /* 0x1c (not possible) */\n     SQLITE_NULL,     /* 0x1d (not possible) */\n     SQLITE_INTEGER,  /* 0x1e (not possible) */\n     SQLITE_NULL,     /* 0x1f (not possible) */\n     SQLITE_FLOAT,    /* 0x20 INTREAL */\n     SQLITE_NULL,     /* 0x21 (not possible) */\n     SQLITE_TEXT,     /* 0x22 INTREAL + TEXT */\n     SQLITE_NULL,     /* 0x23 (not possible) */\n     SQLITE_FLOAT,    /* 0x24 (not possible) */\n     SQLITE_NULL,     /* 0x25 (not possible) */\n     SQLITE_FLOAT,    /* 0x26 (not possible) */\n     SQLITE_NULL,     /* 0x27 (not possible) */\n     SQLITE_FLOAT,    /* 0x28 (not possible) */\n     SQLITE_NULL,     /* 0x29 (not possible) */\n     SQLITE_FLOAT,    /* 0x2a (not possible) */\n     SQLITE_NULL,     /* 0x2b (not possible) */\n     SQLITE_FLOAT,    /* 0x2c (not possible) */\n     SQLITE_NULL,     /* 0x2d (not possible) */\n     SQLITE_FLOAT,    /* 0x2e (not possible) */\n     SQLITE_NULL,     /* 0x2f (not possible) */\n     SQLITE_BLOB,     /* 0x30 (not possible) */\n     SQLITE_NULL,     /* 0x31 (not possible) */\n     SQLITE_TEXT,     /* 0x32 (not possible) */\n     SQLITE_NULL,     /* 0x33 (not possible) */\n     SQLITE_FLOAT,    /* 0x34 (not possible) */\n     SQLITE_NULL,     /* 0x35 (not possible) */\n     SQLITE_FLOAT,    /* 0x36 (not possible) */\n     SQLITE_NULL,     /* 0x37 (not possible) */\n     SQLITE_FLOAT,    /* 0x38 (not possible) */\n     SQLITE_NULL,     /* 0x39 (not possible) */\n     SQLITE_FLOAT,    /* 0x3a (not possible) */\n     SQLITE_NULL,     /* 0x3b (not possible) */\n     SQLITE_FLOAT,    /* 0x3c (not possible) */\n     SQLITE_NULL,     /* 0x3d (not possible) */\n     SQLITE_FLOAT,    /* 0x3e (not possible) */\n     SQLITE_NULL,     /* 0x3f (not possible) */\n  };\n#ifdef SQLITE_DEBUG\n  {\n    int eType = SQLITE_BLOB;\n    if( pVal->flags & MEM_Null ){\n      eType = SQLITE_NULL;\n    }else if( pVal->flags & (MEM_Real|MEM_IntReal) ){\n      eType = SQLITE_FLOAT;\n    }else if( pVal->flags & MEM_Int ){\n      eType = SQLITE_INTEGER;\n    }else if( pVal->flags & MEM_Str ){\n      eType = SQLITE_TEXT;\n    }\n    assert( eType == aType[pVal->flags&MEM_AffMask] );\n  }\n#endif\n  return aType[pVal->flags&MEM_AffMask];\n}\n\n/* Return true if a parameter to xUpdate represents an unchanged column */\nSQLITE_API int sqlite3_value_nochange(sqlite3_value *pVal){\n  return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);\n}\n\n/* Return true if a parameter value originated from an sqlite3_bind() */\nSQLITE_API int sqlite3_value_frombind(sqlite3_value *pVal){\n  return (pVal->flags&MEM_FromBind)!=0;\n}\n\n/* Make a copy of an sqlite3_value object\n*/\nSQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){\n  sqlite3_value *pNew;\n  if( pOrig==0 ) return 0;\n  pNew = sqlite3_malloc( sizeof(*pNew) );\n  if( pNew==0 ) return 0;\n  memset(pNew, 0, sizeof(*pNew));\n  memcpy(pNew, pOrig, MEMCELLSIZE);\n  pNew->flags &= ~MEM_Dyn;\n  pNew->db = 0;\n  if( pNew->flags&(MEM_Str|MEM_Blob) ){\n    pNew->flags &= ~(MEM_Static|MEM_Dyn);\n    pNew->flags |= MEM_Ephem;\n    if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){\n      sqlite3ValueFree(pNew);\n      pNew = 0;\n    }\n  }\n  return pNew;\n}\n\n/* Destroy an sqlite3_value object previously obtained from\n** sqlite3_value_dup().\n*/\nSQLITE_API void sqlite3_value_free(sqlite3_value *pOld){\n  sqlite3ValueFree(pOld);\n}\n  \n\n/**************************** sqlite3_result_  *******************************\n** The following routines are used by user-defined functions to specify\n** the function result.\n**\n** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the\n** result as a string or blob but if the string or blob is too large, it\n** then sets the error code to SQLITE_TOOBIG\n**\n** The invokeValueDestructor(P,X) routine invokes destructor function X()\n** on value P is not going to be used and need to be destroyed.\n*/\nstatic void setResultStrOrError(\n  sqlite3_context *pCtx,  /* Function context */\n  const char *z,          /* String pointer */\n  int n,                  /* Bytes in string, or negative */\n  u8 enc,                 /* Encoding of z.  0 for BLOBs */\n  void (*xDel)(void*)     /* Destructor function */\n){\n  if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){\n    sqlite3_result_error_toobig(pCtx);\n  }\n}\nstatic int invokeValueDestructor(\n  const void *p,             /* Value to destroy */\n  void (*xDel)(void*),       /* The destructor */\n  sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */\n){\n  assert( xDel!=SQLITE_DYNAMIC );\n  if( xDel==0 ){\n    /* noop */\n  }else if( xDel==SQLITE_TRANSIENT ){\n    /* noop */\n  }else{\n    xDel((void*)p);\n  }\n  if( pCtx ) sqlite3_result_error_toobig(pCtx);\n  return SQLITE_TOOBIG;\n}\nSQLITE_API void sqlite3_result_blob(\n  sqlite3_context *pCtx, \n  const void *z, \n  int n, \n  void (*xDel)(void *)\n){\n  assert( n>=0 );\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  setResultStrOrError(pCtx, z, n, 0, xDel);\n}\nSQLITE_API void sqlite3_result_blob64(\n  sqlite3_context *pCtx, \n  const void *z, \n  sqlite3_uint64 n,\n  void (*xDel)(void *)\n){\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  assert( xDel!=SQLITE_DYNAMIC );\n  if( n>0x7fffffff ){\n    (void)invokeValueDestructor(z, xDel, pCtx);\n  }else{\n    setResultStrOrError(pCtx, z, (int)n, 0, xDel);\n  }\n}\nSQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);\n}\nSQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  pCtx->isError = SQLITE_ERROR;\n  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  pCtx->isError = SQLITE_ERROR;\n  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);\n}\n#endif\nSQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);\n}\nSQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);\n}\nSQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  sqlite3VdbeMemSetNull(pCtx->pOut);\n}\nSQLITE_API void sqlite3_result_pointer(\n  sqlite3_context *pCtx,\n  void *pPtr,\n  const char *zPType,\n  void (*xDestructor)(void*)\n){\n  Mem *pOut = pCtx->pOut;\n  assert( sqlite3_mutex_held(pOut->db->mutex) );\n  sqlite3VdbeMemRelease(pOut);\n  pOut->flags = MEM_Null;\n  sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);\n}\nSQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){\n  Mem *pOut = pCtx->pOut;\n  assert( sqlite3_mutex_held(pOut->db->mutex) );\n  pOut->eSubtype = eSubtype & 0xff;\n  pOut->flags |= MEM_Subtype;\n}\nSQLITE_API void sqlite3_result_text(\n  sqlite3_context *pCtx, \n  const char *z, \n  int n,\n  void (*xDel)(void *)\n){\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);\n}\nSQLITE_API void sqlite3_result_text64(\n  sqlite3_context *pCtx, \n  const char *z, \n  sqlite3_uint64 n,\n  void (*xDel)(void *),\n  unsigned char enc\n){\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  assert( xDel!=SQLITE_DYNAMIC );\n  if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;\n  if( n>0x7fffffff ){\n    (void)invokeValueDestructor(z, xDel, pCtx);\n  }else{\n    setResultStrOrError(pCtx, z, (int)n, enc, xDel);\n  }\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API void sqlite3_result_text16(\n  sqlite3_context *pCtx, \n  const void *z, \n  int n, \n  void (*xDel)(void *)\n){\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);\n}\nSQLITE_API void sqlite3_result_text16be(\n  sqlite3_context *pCtx, \n  const void *z, \n  int n, \n  void (*xDel)(void *)\n){\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);\n}\nSQLITE_API void sqlite3_result_text16le(\n  sqlite3_context *pCtx, \n  const void *z, \n  int n, \n  void (*xDel)(void *)\n){\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);\n}\n#endif /* SQLITE_OMIT_UTF16 */\nSQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  sqlite3VdbeMemCopy(pCtx->pOut, pValue);\n}\nSQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);\n}\nSQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){\n  Mem *pOut = pCtx->pOut;\n  assert( sqlite3_mutex_held(pOut->db->mutex) );\n  if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){\n    return SQLITE_TOOBIG;\n  }\n  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);\n  return SQLITE_OK;\n}\nSQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){\n  pCtx->isError = errCode ? errCode : -1;\n#ifdef SQLITE_DEBUG\n  if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;\n#endif\n  if( pCtx->pOut->flags & MEM_Null ){\n    sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1, \n                         SQLITE_UTF8, SQLITE_STATIC);\n  }\n}\n\n/* Force an SQLITE_TOOBIG error. */\nSQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  pCtx->isError = SQLITE_TOOBIG;\n  sqlite3VdbeMemSetStr(pCtx->pOut, \"string or blob too big\", -1, \n                       SQLITE_UTF8, SQLITE_STATIC);\n}\n\n/* An SQLITE_NOMEM error. */\nSQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  sqlite3VdbeMemSetNull(pCtx->pOut);\n  pCtx->isError = SQLITE_NOMEM_BKPT;\n  sqlite3OomFault(pCtx->pOut->db);\n}\n\n#ifndef SQLITE_UNTESTABLE\n/* Force the INT64 value currently stored as the result to be\n** a MEM_IntReal value.  See the SQLITE_TESTCTRL_RESULT_INTREAL\n** test-control.\n*/\nSQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context *pCtx){ \n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n  if( pCtx->pOut->flags & MEM_Int ){\n    pCtx->pOut->flags &= ~MEM_Int;\n    pCtx->pOut->flags |= MEM_IntReal;\n  }\n}\n#endif\n\n\n/*\n** This function is called after a transaction has been committed. It \n** invokes callbacks registered with sqlite3_wal_hook() as required.\n*/\nstatic int doWalCallbacks(sqlite3 *db){\n  int rc = SQLITE_OK;\n#ifndef SQLITE_OMIT_WAL\n  int i;\n  for(i=0; i<db->nDb; i++){\n    Btree *pBt = db->aDb[i].pBt;\n    if( pBt ){\n      int nEntry;\n      sqlite3BtreeEnter(pBt);\n      nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));\n      sqlite3BtreeLeave(pBt);\n      if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){\n        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);\n      }\n    }\n  }\n#endif\n  return rc;\n}\n\n\n/*\n** Execute the statement pStmt, either until a row of data is ready, the\n** statement is completely executed or an error occurs.\n**\n** This routine implements the bulk of the logic behind the sqlite_step()\n** API.  The only thing omitted is the automatic recompile if a \n** schema change has occurred.  That detail is handled by the\n** outer sqlite3_step() wrapper procedure.\n*/\nstatic int sqlite3Step(Vdbe *p){\n  sqlite3 *db;\n  int rc;\n\n  assert(p);\n  if( p->magic!=VDBE_MAGIC_RUN ){\n    /* We used to require that sqlite3_reset() be called before retrying\n    ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning\n    ** with version 3.7.0, we changed this so that sqlite3_reset() would\n    ** be called automatically instead of throwing the SQLITE_MISUSE error.\n    ** This \"automatic-reset\" change is not technically an incompatibility, \n    ** since any application that receives an SQLITE_MISUSE is broken by\n    ** definition.\n    **\n    ** Nevertheless, some published applications that were originally written\n    ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE \n    ** returns, and those were broken by the automatic-reset change.  As a\n    ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the\n    ** legacy behavior of returning SQLITE_MISUSE for cases where the \n    ** previous sqlite3_step() returned something other than a SQLITE_LOCKED\n    ** or SQLITE_BUSY error.\n    */\n#ifdef SQLITE_OMIT_AUTORESET\n    if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){\n      sqlite3_reset((sqlite3_stmt*)p);\n    }else{\n      return SQLITE_MISUSE_BKPT;\n    }\n#else\n    sqlite3_reset((sqlite3_stmt*)p);\n#endif\n  }\n\n  /* Check that malloc() has not failed. If it has, return early. */\n  db = p->db;\n  if( db->mallocFailed ){\n    p->rc = SQLITE_NOMEM;\n    return SQLITE_NOMEM_BKPT;\n  }\n\n  if( p->pc<0 && p->expired ){\n    p->rc = SQLITE_SCHEMA;\n    rc = SQLITE_ERROR;\n    goto end_of_step;\n  }\n  if( p->pc<0 ){\n    /* If there are no other statements currently running, then\n    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt\n    ** from interrupting a statement that has not yet started.\n    */\n    if( db->nVdbeActive==0 ){\n      AtomicStore(&db->u1.isInterrupted, 0);\n    }\n\n    assert( db->nVdbeWrite>0 || db->autoCommit==0 \n        || (db->nDeferredCons==0 && db->nDeferredImmCons==0)\n    );\n\n#ifndef SQLITE_OMIT_TRACE\n    if( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0\n        && !db->init.busy && p->zSql ){\n      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);\n    }else{\n      assert( p->startTime==0 );\n    }\n#endif\n\n    db->nVdbeActive++;\n    if( p->readOnly==0 ) db->nVdbeWrite++;\n    if( p->bIsReader ) db->nVdbeRead++;\n    p->pc = 0;\n  }\n#ifdef SQLITE_DEBUG\n  p->rcApp = SQLITE_OK;\n#endif\n#ifndef SQLITE_OMIT_EXPLAIN\n  if( p->explain ){\n    rc = sqlite3VdbeList(p);\n  }else\n#endif /* SQLITE_OMIT_EXPLAIN */\n  {\n    db->nVdbeExec++;\n    rc = sqlite3VdbeExec(p);\n    db->nVdbeExec--;\n  }\n\n  if( rc!=SQLITE_ROW ){\n#ifndef SQLITE_OMIT_TRACE\n    /* If the statement completed successfully, invoke the profile callback */\n    checkProfileCallback(db, p);\n#endif\n\n    if( rc==SQLITE_DONE && db->autoCommit ){\n      assert( p->rc==SQLITE_OK );\n      p->rc = doWalCallbacks(db);\n      if( p->rc!=SQLITE_OK ){\n        rc = SQLITE_ERROR;\n      }\n    }\n  }\n\n  db->errCode = rc;\n  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){\n    p->rc = SQLITE_NOMEM_BKPT;\n  }\nend_of_step:\n  /* At this point local variable rc holds the value that should be \n  ** returned if this statement was compiled using the legacy \n  ** sqlite3_prepare() interface. According to the docs, this can only\n  ** be one of the values in the first assert() below. Variable p->rc \n  ** contains the value that would be returned if sqlite3_finalize() \n  ** were called on statement p.\n  */\n  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR \n       || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE\n  );\n  assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );\n  if( rc!=SQLITE_ROW \n   && rc!=SQLITE_DONE\n   && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0\n  ){\n    /* If this statement was prepared using saved SQL and an \n    ** error has occurred, then return the error code in p->rc to the\n    ** caller. Set the error code in the database handle to the same value.\n    */ \n    rc = sqlite3VdbeTransferError(p);\n  }\n  return (rc&db->errMask);\n}\n\n/*\n** This is the top-level implementation of sqlite3_step().  Call\n** sqlite3Step() to do most of the work.  If a schema error occurs,\n** call sqlite3Reprepare() and try again.\n*/\nSQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){\n  int rc = SQLITE_OK;      /* Result from sqlite3Step() */\n  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */\n  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */\n  sqlite3 *db;             /* The database connection */\n\n  if( vdbeSafetyNotNull(v) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  db = v->db;\n  sqlite3_mutex_enter(db->mutex);\n  v->doingRerun = 0;\n  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA\n         && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){\n    int savedPc = v->pc;\n    rc = sqlite3Reprepare(v);\n    if( rc!=SQLITE_OK ){\n      /* This case occurs after failing to recompile an sql statement. \n      ** The error message from the SQL compiler has already been loaded \n      ** into the database handle. This block copies the error message \n      ** from the database handle into the statement and sets the statement\n      ** program counter to 0 to ensure that when the statement is \n      ** finalized or reset the parser error message is available via\n      ** sqlite3_errmsg() and sqlite3_errcode().\n      */\n      const char *zErr = (const char *)sqlite3_value_text(db->pErr); \n      sqlite3DbFree(db, v->zErrMsg);\n      if( !db->mallocFailed ){\n        v->zErrMsg = sqlite3DbStrDup(db, zErr);\n        v->rc = rc = sqlite3ApiExit(db, rc);\n      } else {\n        v->zErrMsg = 0;\n        v->rc = rc = SQLITE_NOMEM_BKPT;\n      }\n      break;\n    }\n    sqlite3_reset(pStmt);\n    if( savedPc>=0 ) v->doingRerun = 1;\n    assert( v->expired==0 );\n  }\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n\n/*\n** Extract the user data from a sqlite3_context structure and return a\n** pointer to it.\n*/\nSQLITE_API void *sqlite3_user_data(sqlite3_context *p){\n  assert( p && p->pFunc );\n  return p->pFunc->pUserData;\n}\n\n/*\n** Extract the user data from a sqlite3_context structure and return a\n** pointer to it.\n**\n** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface\n** returns a copy of the pointer to the database connection (the 1st\n** parameter) of the sqlite3_create_function() and\n** sqlite3_create_function16() routines that originally registered the\n** application defined function.\n*/\nSQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){\n  assert( p && p->pOut );\n  return p->pOut->db;\n}\n\n/*\n** If this routine is invoked from within an xColumn method of a virtual\n** table, then it returns true if and only if the the call is during an\n** UPDATE operation and the value of the column will not be modified\n** by the UPDATE.\n**\n** If this routine is called from any context other than within the\n** xColumn method of a virtual table, then the return value is meaningless\n** and arbitrary.\n**\n** Virtual table implements might use this routine to optimize their\n** performance by substituting a NULL result, or some other light-weight\n** value, as a signal to the xUpdate routine that the column is unchanged.\n*/\nSQLITE_API int sqlite3_vtab_nochange(sqlite3_context *p){\n  assert( p );\n  return sqlite3_value_nochange(p->pOut);\n}\n\n/*\n** Return the current time for a statement.  If the current time\n** is requested more than once within the same run of a single prepared\n** statement, the exact same time is returned for each invocation regardless\n** of the amount of time that elapses between invocations.  In other words,\n** the time returned is always the time of the first call.\n*/\nSQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){\n  int rc;\n#ifndef SQLITE_ENABLE_STAT4\n  sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;\n  assert( p->pVdbe!=0 );\n#else\n  sqlite3_int64 iTime = 0;\n  sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;\n#endif\n  if( *piTime==0 ){\n    rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);\n    if( rc ) *piTime = 0;\n  }\n  return *piTime;\n}\n\n/*\n** Create a new aggregate context for p and return a pointer to\n** its pMem->z element.\n*/\nstatic SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){\n  Mem *pMem = p->pMem;\n  assert( (pMem->flags & MEM_Agg)==0 );\n  if( nByte<=0 ){\n    sqlite3VdbeMemSetNull(pMem);\n    pMem->z = 0;\n  }else{\n    sqlite3VdbeMemClearAndResize(pMem, nByte);\n    pMem->flags = MEM_Agg;\n    pMem->u.pDef = p->pFunc;\n    if( pMem->z ){\n      memset(pMem->z, 0, nByte);\n    }\n  }\n  return (void*)pMem->z;\n}\n\n/*\n** Allocate or return the aggregate context for a user function.  A new\n** context is allocated on the first call.  Subsequent calls return the\n** same context that was returned on prior calls.\n*/\nSQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){\n  assert( p && p->pFunc && p->pFunc->xFinalize );\n  assert( sqlite3_mutex_held(p->pOut->db->mutex) );\n  testcase( nByte<0 );\n  if( (p->pMem->flags & MEM_Agg)==0 ){\n    return createAggContext(p, nByte);\n  }else{\n    return (void*)p->pMem->z;\n  }\n}\n\n/*\n** Return the auxiliary data pointer, if any, for the iArg'th argument to\n** the user-function defined by pCtx.\n**\n** The left-most argument is 0.\n**\n** Undocumented behavior:  If iArg is negative then access a cache of\n** auxiliary data pointers that is available to all functions within a\n** single prepared statement.  The iArg values must match.\n*/\nSQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){\n  AuxData *pAuxData;\n\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n#if SQLITE_ENABLE_STAT4\n  if( pCtx->pVdbe==0 ) return 0;\n#else\n  assert( pCtx->pVdbe!=0 );\n#endif\n  for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){\n    if(  pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){\n      return pAuxData->pAux;\n    }\n  }\n  return 0;\n}\n\n/*\n** Set the auxiliary data pointer and delete function, for the iArg'th\n** argument to the user-function defined by pCtx. Any previous value is\n** deleted by calling the delete function specified when it was set.\n**\n** The left-most argument is 0.\n**\n** Undocumented behavior:  If iArg is negative then make the data available\n** to all functions within the current prepared statement using iArg as an\n** access code.\n*/\nSQLITE_API void sqlite3_set_auxdata(\n  sqlite3_context *pCtx, \n  int iArg, \n  void *pAux, \n  void (*xDelete)(void*)\n){\n  AuxData *pAuxData;\n  Vdbe *pVdbe = pCtx->pVdbe;\n\n  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );\n#ifdef SQLITE_ENABLE_STAT4\n  if( pVdbe==0 ) goto failed;\n#else\n  assert( pVdbe!=0 );\n#endif\n\n  for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){\n    if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){\n      break;\n    }\n  }\n  if( pAuxData==0 ){\n    pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));\n    if( !pAuxData ) goto failed;\n    pAuxData->iAuxOp = pCtx->iOp;\n    pAuxData->iAuxArg = iArg;\n    pAuxData->pNextAux = pVdbe->pAuxData;\n    pVdbe->pAuxData = pAuxData;\n    if( pCtx->isError==0 ) pCtx->isError = -1;\n  }else if( pAuxData->xDeleteAux ){\n    pAuxData->xDeleteAux(pAuxData->pAux);\n  }\n\n  pAuxData->pAux = pAux;\n  pAuxData->xDeleteAux = xDelete;\n  return;\n\nfailed:\n  if( xDelete ){\n    xDelete(pAux);\n  }\n}\n\n#ifndef SQLITE_OMIT_DEPRECATED\n/*\n** Return the number of times the Step function of an aggregate has been \n** called.\n**\n** This function is deprecated.  Do not use it for new code.  It is\n** provide only to avoid breaking legacy code.  New aggregate function\n** implementations should keep their own counts within their aggregate\n** context.\n*/\nSQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){\n  assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );\n  return p->pMem->n;\n}\n#endif\n\n/*\n** Return the number of columns in the result set for the statement pStmt.\n*/\nSQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){\n  Vdbe *pVm = (Vdbe *)pStmt;\n  return pVm ? pVm->nResColumn : 0;\n}\n\n/*\n** Return the number of values available from the current row of the\n** currently executing statement pStmt.\n*/\nSQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){\n  Vdbe *pVm = (Vdbe *)pStmt;\n  if( pVm==0 || pVm->pResultSet==0 ) return 0;\n  return pVm->nResColumn;\n}\n\n/*\n** Return a pointer to static memory containing an SQL NULL value.\n*/\nstatic const Mem *columnNullValue(void){\n  /* Even though the Mem structure contains an element\n  ** of type i64, on certain architectures (x86) with certain compiler\n  ** switches (-Os), gcc may align this Mem object on a 4-byte boundary\n  ** instead of an 8-byte one. This all works fine, except that when\n  ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s\n  ** that a Mem structure is located on an 8-byte boundary. To prevent\n  ** these assert()s from failing, when building with SQLITE_DEBUG defined\n  ** using gcc, we force nullMem to be 8-byte aligned using the magical\n  ** __attribute__((aligned(8))) macro.  */\n  static const Mem nullMem \n#if defined(SQLITE_DEBUG) && defined(__GNUC__)\n    __attribute__((aligned(8))) \n#endif\n    = {\n        /* .u          = */ {0},\n        /* .flags      = */ (u16)MEM_Null,\n        /* .enc        = */ (u8)0,\n        /* .eSubtype   = */ (u8)0,\n        /* .n          = */ (int)0,\n        /* .z          = */ (char*)0,\n        /* .zMalloc    = */ (char*)0,\n        /* .szMalloc   = */ (int)0,\n        /* .uTemp      = */ (u32)0,\n        /* .db         = */ (sqlite3*)0,\n        /* .xDel       = */ (void(*)(void*))0,\n#ifdef SQLITE_DEBUG\n        /* .pScopyFrom = */ (Mem*)0,\n        /* .mScopyFlags= */ 0,\n#endif\n      };\n  return &nullMem;\n}\n\n/*\n** Check to see if column iCol of the given statement is valid.  If\n** it is, return a pointer to the Mem for the value of that column.\n** If iCol is not valid, return a pointer to a Mem which has a value\n** of NULL.\n*/\nstatic Mem *columnMem(sqlite3_stmt *pStmt, int i){\n  Vdbe *pVm;\n  Mem *pOut;\n\n  pVm = (Vdbe *)pStmt;\n  if( pVm==0 ) return (Mem*)columnNullValue();\n  assert( pVm->db );\n  sqlite3_mutex_enter(pVm->db->mutex);\n  if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){\n    pOut = &pVm->pResultSet[i];\n  }else{\n    sqlite3Error(pVm->db, SQLITE_RANGE);\n    pOut = (Mem*)columnNullValue();\n  }\n  return pOut;\n}\n\n/*\n** This function is called after invoking an sqlite3_value_XXX function on a \n** column value (i.e. a value returned by evaluating an SQL expression in the\n** select list of a SELECT statement) that may cause a malloc() failure. If \n** malloc() has failed, the threads mallocFailed flag is cleared and the result\n** code of statement pStmt set to SQLITE_NOMEM.\n**\n** Specifically, this is called from within:\n**\n**     sqlite3_column_int()\n**     sqlite3_column_int64()\n**     sqlite3_column_text()\n**     sqlite3_column_text16()\n**     sqlite3_column_real()\n**     sqlite3_column_bytes()\n**     sqlite3_column_bytes16()\n**     sqiite3_column_blob()\n*/\nstatic void columnMallocFailure(sqlite3_stmt *pStmt)\n{\n  /* If malloc() failed during an encoding conversion within an\n  ** sqlite3_column_XXX API, then set the return code of the statement to\n  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR\n  ** and _finalize() will return NOMEM.\n  */\n  Vdbe *p = (Vdbe *)pStmt;\n  if( p ){\n    assert( p->db!=0 );\n    assert( sqlite3_mutex_held(p->db->mutex) );\n    p->rc = sqlite3ApiExit(p->db, p->rc);\n    sqlite3_mutex_leave(p->db->mutex);\n  }\n}\n\n/**************************** sqlite3_column_  *******************************\n** The following routines are used to access elements of the current row\n** in the result set.\n*/\nSQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){\n  const void *val;\n  val = sqlite3_value_blob( columnMem(pStmt,i) );\n  /* Even though there is no encoding conversion, value_blob() might\n  ** need to call malloc() to expand the result of a zeroblob() \n  ** expression. \n  */\n  columnMallocFailure(pStmt);\n  return val;\n}\nSQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){\n  int val = sqlite3_value_bytes( columnMem(pStmt,i) );\n  columnMallocFailure(pStmt);\n  return val;\n}\nSQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){\n  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );\n  columnMallocFailure(pStmt);\n  return val;\n}\nSQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){\n  double val = sqlite3_value_double( columnMem(pStmt,i) );\n  columnMallocFailure(pStmt);\n  return val;\n}\nSQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){\n  int val = sqlite3_value_int( columnMem(pStmt,i) );\n  columnMallocFailure(pStmt);\n  return val;\n}\nSQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){\n  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );\n  columnMallocFailure(pStmt);\n  return val;\n}\nSQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){\n  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );\n  columnMallocFailure(pStmt);\n  return val;\n}\nSQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){\n  Mem *pOut = columnMem(pStmt, i);\n  if( pOut->flags&MEM_Static ){\n    pOut->flags &= ~MEM_Static;\n    pOut->flags |= MEM_Ephem;\n  }\n  columnMallocFailure(pStmt);\n  return (sqlite3_value *)pOut;\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){\n  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );\n  columnMallocFailure(pStmt);\n  return val;\n}\n#endif /* SQLITE_OMIT_UTF16 */\nSQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){\n  int iType = sqlite3_value_type( columnMem(pStmt,i) );\n  columnMallocFailure(pStmt);\n  return iType;\n}\n\n/*\n** Convert the N-th element of pStmt->pColName[] into a string using\n** xFunc() then return that string.  If N is out of range, return 0.\n**\n** There are up to 5 names for each column.  useType determines which\n** name is returned.  Here are the names:\n**\n**    0      The column name as it should be displayed for output\n**    1      The datatype name for the column\n**    2      The name of the database that the column derives from\n**    3      The name of the table that the column derives from\n**    4      The name of the table column that the result column derives from\n**\n** If the result is not a simple column reference (if it is an expression\n** or a constant) then useTypes 2, 3, and 4 return NULL.\n*/\nstatic const void *columnName(\n  sqlite3_stmt *pStmt,     /* The statement */\n  int N,                   /* Which column to get the name for */\n  int useUtf16,            /* True to return the name as UTF16 */\n  int useType              /* What type of name */\n){\n  const void *ret;\n  Vdbe *p;\n  int n;\n  sqlite3 *db;\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( pStmt==0 ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  ret = 0;\n  p = (Vdbe *)pStmt;\n  db = p->db;\n  assert( db!=0 );\n  n = sqlite3_column_count(pStmt);\n  if( N<n && N>=0 ){\n    N += useType*n;\n    sqlite3_mutex_enter(db->mutex);\n    assert( db->mallocFailed==0 );\n#ifndef SQLITE_OMIT_UTF16\n    if( useUtf16 ){\n      ret = sqlite3_value_text16((sqlite3_value*)&p->aColName[N]);\n    }else\n#endif\n    {\n      ret = sqlite3_value_text((sqlite3_value*)&p->aColName[N]);\n    }\n    /* A malloc may have failed inside of the _text() call. If this\n    ** is the case, clear the mallocFailed flag and return NULL.\n    */\n    if( db->mallocFailed ){\n      sqlite3OomClear(db);\n      ret = 0;\n    }\n    sqlite3_mutex_leave(db->mutex);\n  }\n  return ret;\n}\n\n/*\n** Return the name of the Nth column of the result set returned by SQL\n** statement pStmt.\n*/\nSQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){\n  return columnName(pStmt, N, 0, COLNAME_NAME);\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){\n  return columnName(pStmt, N, 1, COLNAME_NAME);\n}\n#endif\n\n/*\n** Constraint:  If you have ENABLE_COLUMN_METADATA then you must\n** not define OMIT_DECLTYPE.\n*/\n#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)\n# error \"Must not define both SQLITE_OMIT_DECLTYPE \\\n         and SQLITE_ENABLE_COLUMN_METADATA\"\n#endif\n\n#ifndef SQLITE_OMIT_DECLTYPE\n/*\n** Return the column declaration type (if applicable) of the 'i'th column\n** of the result set of SQL statement pStmt.\n*/\nSQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){\n  return columnName(pStmt, N, 0, COLNAME_DECLTYPE);\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){\n  return columnName(pStmt, N, 1, COLNAME_DECLTYPE);\n}\n#endif /* SQLITE_OMIT_UTF16 */\n#endif /* SQLITE_OMIT_DECLTYPE */\n\n#ifdef SQLITE_ENABLE_COLUMN_METADATA\n/*\n** Return the name of the database from which a result column derives.\n** NULL is returned if the result column is an expression or constant or\n** anything else which is not an unambiguous reference to a database column.\n*/\nSQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){\n  return columnName(pStmt, N, 0, COLNAME_DATABASE);\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){\n  return columnName(pStmt, N, 1, COLNAME_DATABASE);\n}\n#endif /* SQLITE_OMIT_UTF16 */\n\n/*\n** Return the name of the table from which a result column derives.\n** NULL is returned if the result column is an expression or constant or\n** anything else which is not an unambiguous reference to a database column.\n*/\nSQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){\n  return columnName(pStmt, N, 0, COLNAME_TABLE);\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){\n  return columnName(pStmt, N, 1, COLNAME_TABLE);\n}\n#endif /* SQLITE_OMIT_UTF16 */\n\n/*\n** Return the name of the table column from which a result column derives.\n** NULL is returned if the result column is an expression or constant or\n** anything else which is not an unambiguous reference to a database column.\n*/\nSQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){\n  return columnName(pStmt, N, 0, COLNAME_COLUMN);\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){\n  return columnName(pStmt, N, 1, COLNAME_COLUMN);\n}\n#endif /* SQLITE_OMIT_UTF16 */\n#endif /* SQLITE_ENABLE_COLUMN_METADATA */\n\n\n/******************************* sqlite3_bind_  ***************************\n** \n** Routines used to attach values to wildcards in a compiled SQL statement.\n*/\n/*\n** Unbind the value bound to variable i in virtual machine p. This is the \n** the same as binding a NULL value to the column. If the \"i\" parameter is\n** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.\n**\n** A successful evaluation of this routine acquires the mutex on p.\n** the mutex is released if any kind of error occurs.\n**\n** The error code stored in database p->db is overwritten with the return\n** value in any case.\n*/\nstatic int vdbeUnbind(Vdbe *p, int i){\n  Mem *pVar;\n  if( vdbeSafetyNotNull(p) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  sqlite3_mutex_enter(p->db->mutex);\n  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){\n    sqlite3Error(p->db, SQLITE_MISUSE);\n    sqlite3_mutex_leave(p->db->mutex);\n    sqlite3_log(SQLITE_MISUSE, \n        \"bind on a busy prepared statement: [%s]\", p->zSql);\n    return SQLITE_MISUSE_BKPT;\n  }\n  if( i<1 || i>p->nVar ){\n    sqlite3Error(p->db, SQLITE_RANGE);\n    sqlite3_mutex_leave(p->db->mutex);\n    return SQLITE_RANGE;\n  }\n  i--;\n  pVar = &p->aVar[i];\n  sqlite3VdbeMemRelease(pVar);\n  pVar->flags = MEM_Null;\n  p->db->errCode = SQLITE_OK;\n\n  /* If the bit corresponding to this variable in Vdbe.expmask is set, then \n  ** binding a new value to this variable invalidates the current query plan.\n  **\n  ** IMPLEMENTATION-OF: R-57496-20354 If the specific value bound to a host\n  ** parameter in the WHERE clause might influence the choice of query plan\n  ** for a statement, then the statement will be automatically recompiled,\n  ** as if there had been a schema change, on the first sqlite3_step() call\n  ** following any change to the bindings of that parameter.\n  */\n  assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );\n  if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){\n    p->expired = 1;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Bind a text or BLOB value.\n*/\nstatic int bindText(\n  sqlite3_stmt *pStmt,   /* The statement to bind against */\n  int i,                 /* Index of the parameter to bind */\n  const void *zData,     /* Pointer to the data to be bound */\n  int nData,             /* Number of bytes of data to be bound */\n  void (*xDel)(void*),   /* Destructor for the data */\n  u8 encoding            /* Encoding for the data */\n){\n  Vdbe *p = (Vdbe *)pStmt;\n  Mem *pVar;\n  int rc;\n\n  rc = vdbeUnbind(p, i);\n  if( rc==SQLITE_OK ){\n    if( zData!=0 ){\n      pVar = &p->aVar[i-1];\n      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);\n      if( rc==SQLITE_OK && encoding!=0 ){\n        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));\n      }\n      if( rc ){\n        sqlite3Error(p->db, rc);\n        rc = sqlite3ApiExit(p->db, rc);\n      }\n    }\n    sqlite3_mutex_leave(p->db->mutex);\n  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){\n    xDel((void*)zData);\n  }\n  return rc;\n}\n\n\n/*\n** Bind a blob value to an SQL statement variable.\n*/\nSQLITE_API int sqlite3_bind_blob(\n  sqlite3_stmt *pStmt, \n  int i, \n  const void *zData, \n  int nData, \n  void (*xDel)(void*)\n){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( nData<0 ) return SQLITE_MISUSE_BKPT;\n#endif\n  return bindText(pStmt, i, zData, nData, xDel, 0);\n}\nSQLITE_API int sqlite3_bind_blob64(\n  sqlite3_stmt *pStmt, \n  int i, \n  const void *zData, \n  sqlite3_uint64 nData, \n  void (*xDel)(void*)\n){\n  assert( xDel!=SQLITE_DYNAMIC );\n  if( nData>0x7fffffff ){\n    return invokeValueDestructor(zData, xDel, 0);\n  }else{\n    return bindText(pStmt, i, zData, (int)nData, xDel, 0);\n  }\n}\nSQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){\n  int rc;\n  Vdbe *p = (Vdbe *)pStmt;\n  rc = vdbeUnbind(p, i);\n  if( rc==SQLITE_OK ){\n    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);\n    sqlite3_mutex_leave(p->db->mutex);\n  }\n  return rc;\n}\nSQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){\n  return sqlite3_bind_int64(p, i, (i64)iValue);\n}\nSQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){\n  int rc;\n  Vdbe *p = (Vdbe *)pStmt;\n  rc = vdbeUnbind(p, i);\n  if( rc==SQLITE_OK ){\n    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);\n    sqlite3_mutex_leave(p->db->mutex);\n  }\n  return rc;\n}\nSQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){\n  int rc;\n  Vdbe *p = (Vdbe*)pStmt;\n  rc = vdbeUnbind(p, i);\n  if( rc==SQLITE_OK ){\n    sqlite3_mutex_leave(p->db->mutex);\n  }\n  return rc;\n}\nSQLITE_API int sqlite3_bind_pointer(\n  sqlite3_stmt *pStmt,\n  int i,\n  void *pPtr,\n  const char *zPTtype,\n  void (*xDestructor)(void*)\n){\n  int rc;\n  Vdbe *p = (Vdbe*)pStmt;\n  rc = vdbeUnbind(p, i);\n  if( rc==SQLITE_OK ){\n    sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);\n    sqlite3_mutex_leave(p->db->mutex);\n  }else if( xDestructor ){\n    xDestructor(pPtr);\n  }\n  return rc;\n}\nSQLITE_API int sqlite3_bind_text( \n  sqlite3_stmt *pStmt, \n  int i, \n  const char *zData, \n  int nData, \n  void (*xDel)(void*)\n){\n  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);\n}\nSQLITE_API int sqlite3_bind_text64( \n  sqlite3_stmt *pStmt, \n  int i, \n  const char *zData, \n  sqlite3_uint64 nData, \n  void (*xDel)(void*),\n  unsigned char enc\n){\n  assert( xDel!=SQLITE_DYNAMIC );\n  if( nData>0x7fffffff ){\n    return invokeValueDestructor(zData, xDel, 0);\n  }else{\n    if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;\n    return bindText(pStmt, i, zData, (int)nData, xDel, enc);\n  }\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API int sqlite3_bind_text16(\n  sqlite3_stmt *pStmt, \n  int i, \n  const void *zData, \n  int nData, \n  void (*xDel)(void*)\n){\n  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);\n}\n#endif /* SQLITE_OMIT_UTF16 */\nSQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){\n  int rc;\n  switch( sqlite3_value_type((sqlite3_value*)pValue) ){\n    case SQLITE_INTEGER: {\n      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);\n      break;\n    }\n    case SQLITE_FLOAT: {\n      rc = sqlite3_bind_double(pStmt, i, pValue->u.r);\n      break;\n    }\n    case SQLITE_BLOB: {\n      if( pValue->flags & MEM_Zero ){\n        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);\n      }else{\n        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);\n      }\n      break;\n    }\n    case SQLITE_TEXT: {\n      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,\n                              pValue->enc);\n      break;\n    }\n    default: {\n      rc = sqlite3_bind_null(pStmt, i);\n      break;\n    }\n  }\n  return rc;\n}\nSQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){\n  int rc;\n  Vdbe *p = (Vdbe *)pStmt;\n  rc = vdbeUnbind(p, i);\n  if( rc==SQLITE_OK ){\n    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);\n    sqlite3_mutex_leave(p->db->mutex);\n  }\n  return rc;\n}\nSQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){\n  int rc;\n  Vdbe *p = (Vdbe *)pStmt;\n  sqlite3_mutex_enter(p->db->mutex);\n  if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){\n    rc = SQLITE_TOOBIG;\n  }else{\n    assert( (n & 0x7FFFFFFF)==n );\n    rc = sqlite3_bind_zeroblob(pStmt, i, n);\n  }\n  rc = sqlite3ApiExit(p->db, rc);\n  sqlite3_mutex_leave(p->db->mutex);\n  return rc;\n}\n\n/*\n** Return the number of wildcards that can be potentially bound to.\n** This routine is added to support DBD::SQLite.  \n*/\nSQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){\n  Vdbe *p = (Vdbe*)pStmt;\n  return p ? p->nVar : 0;\n}\n\n/*\n** Return the name of a wildcard parameter.  Return NULL if the index\n** is out of range or if the wildcard is unnamed.\n**\n** The result is always UTF-8.\n*/\nSQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){\n  Vdbe *p = (Vdbe*)pStmt;\n  if( p==0 ) return 0;\n  return sqlite3VListNumToName(p->pVList, i);\n}\n\n/*\n** Given a wildcard parameter name, return the index of the variable\n** with that name.  If there is no variable with the given name,\n** return 0.\n*/\nSQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){\n  if( p==0 || zName==0 ) return 0;\n  return sqlite3VListNameToNum(p->pVList, zName, nName);\n}\nSQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){\n  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));\n}\n\n/*\n** Transfer all bindings from the first statement over to the second.\n*/\nSQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){\n  Vdbe *pFrom = (Vdbe*)pFromStmt;\n  Vdbe *pTo = (Vdbe*)pToStmt;\n  int i;\n  assert( pTo->db==pFrom->db );\n  assert( pTo->nVar==pFrom->nVar );\n  sqlite3_mutex_enter(pTo->db->mutex);\n  for(i=0; i<pFrom->nVar; i++){\n    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);\n  }\n  sqlite3_mutex_leave(pTo->db->mutex);\n  return SQLITE_OK;\n}\n\n#ifndef SQLITE_OMIT_DEPRECATED\n/*\n** Deprecated external interface.  Internal/core SQLite code\n** should call sqlite3TransferBindings.\n**\n** It is misuse to call this routine with statements from different\n** database connections.  But as this is a deprecated interface, we\n** will not bother to check for that condition.\n**\n** If the two statements contain a different number of bindings, then\n** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise\n** SQLITE_OK is returned.\n*/\nSQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){\n  Vdbe *pFrom = (Vdbe*)pFromStmt;\n  Vdbe *pTo = (Vdbe*)pToStmt;\n  if( pFrom->nVar!=pTo->nVar ){\n    return SQLITE_ERROR;\n  }\n  assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );\n  if( pTo->expmask ){\n    pTo->expired = 1;\n  }\n  assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );\n  if( pFrom->expmask ){\n    pFrom->expired = 1;\n  }\n  return sqlite3TransferBindings(pFromStmt, pToStmt);\n}\n#endif\n\n/*\n** Return the sqlite3* database handle to which the prepared statement given\n** in the argument belongs.  This is the same database handle that was\n** the first argument to the sqlite3_prepare() that was used to create\n** the statement in the first place.\n*/\nSQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){\n  return pStmt ? ((Vdbe*)pStmt)->db : 0;\n}\n\n/*\n** Return true if the prepared statement is guaranteed to not modify the\n** database.\n*/\nSQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){\n  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;\n}\n\n/*\n** Return 1 if the statement is an EXPLAIN and return 2 if the\n** statement is an EXPLAIN QUERY PLAN\n*/\nSQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt){\n  return pStmt ? ((Vdbe*)pStmt)->explain : 0;\n}\n\n/*\n** Return true if the prepared statement is in need of being reset.\n*/\nSQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){\n  Vdbe *v = (Vdbe*)pStmt;\n  return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;\n}\n\n/*\n** Return a pointer to the next prepared statement after pStmt associated\n** with database connection pDb.  If pStmt is NULL, return the first\n** prepared statement for the database connection.  Return NULL if there\n** are no more.\n*/\nSQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){\n  sqlite3_stmt *pNext;\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(pDb) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  sqlite3_mutex_enter(pDb->mutex);\n  if( pStmt==0 ){\n    pNext = (sqlite3_stmt*)pDb->pVdbe;\n  }else{\n    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;\n  }\n  sqlite3_mutex_leave(pDb->mutex);\n  return pNext;\n}\n\n/*\n** Return the value of a status counter for a prepared statement\n*/\nSQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){\n  Vdbe *pVdbe = (Vdbe*)pStmt;\n  u32 v;\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !pStmt \n   || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))\n  ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  if( op==SQLITE_STMTSTATUS_MEMUSED ){\n    sqlite3 *db = pVdbe->db;\n    sqlite3_mutex_enter(db->mutex);\n    v = 0;\n    db->pnBytesFreed = (int*)&v;\n    sqlite3VdbeClearObject(db, pVdbe);\n    sqlite3DbFree(db, pVdbe);\n    db->pnBytesFreed = 0;\n    sqlite3_mutex_leave(db->mutex);\n  }else{\n    v = pVdbe->aCounter[op];\n    if( resetFlag ) pVdbe->aCounter[op] = 0;\n  }\n  return (int)v;\n}\n\n/*\n** Return the SQL associated with a prepared statement\n*/\nSQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){\n  Vdbe *p = (Vdbe *)pStmt;\n  return p ? p->zSql : 0;\n}\n\n/*\n** Return the SQL associated with a prepared statement with\n** bound parameters expanded.  Space to hold the returned string is\n** obtained from sqlite3_malloc().  The caller is responsible for\n** freeing the returned string by passing it to sqlite3_free().\n**\n** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of\n** expanded bound parameters.\n*/\nSQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){\n#ifdef SQLITE_OMIT_TRACE\n  return 0;\n#else\n  char *z = 0;\n  const char *zSql = sqlite3_sql(pStmt);\n  if( zSql ){\n    Vdbe *p = (Vdbe *)pStmt;\n    sqlite3_mutex_enter(p->db->mutex);\n    z = sqlite3VdbeExpandSql(p, zSql);\n    sqlite3_mutex_leave(p->db->mutex);\n  }\n  return z;\n#endif\n}\n\n#ifdef SQLITE_ENABLE_NORMALIZE\n/*\n** Return the normalized SQL associated with a prepared statement.\n*/\nSQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt){\n  Vdbe *p = (Vdbe *)pStmt;\n  if( p==0 ) return 0;\n  if( p->zNormSql==0 && ALWAYS(p->zSql!=0) ){\n    sqlite3_mutex_enter(p->db->mutex);\n    p->zNormSql = sqlite3Normalize(p, p->zSql);\n    sqlite3_mutex_leave(p->db->mutex);\n  }\n  return p->zNormSql;\n}\n#endif /* SQLITE_ENABLE_NORMALIZE */\n\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n/*\n** Allocate and populate an UnpackedRecord structure based on the serialized\n** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure\n** if successful, or a NULL pointer if an OOM error is encountered.\n*/\nstatic UnpackedRecord *vdbeUnpackRecord(\n  KeyInfo *pKeyInfo, \n  int nKey, \n  const void *pKey\n){\n  UnpackedRecord *pRet;           /* Return value */\n\n  pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);\n  if( pRet ){\n    memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));\n    sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);\n  }\n  return pRet;\n}\n\n/*\n** This function is called from within a pre-update callback to retrieve\n** a field of the row currently being updated or deleted.\n*/\nSQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){\n  PreUpdate *p = db->pPreUpdate;\n  Mem *pMem;\n  int rc = SQLITE_OK;\n\n  /* Test that this call is being made from within an SQLITE_DELETE or\n  ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */\n  if( !p || p->op==SQLITE_INSERT ){\n    rc = SQLITE_MISUSE_BKPT;\n    goto preupdate_old_out;\n  }\n  if( p->pPk ){\n    iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);\n  }\n  if( iIdx>=p->pCsr->nField || iIdx<0 ){\n    rc = SQLITE_RANGE;\n    goto preupdate_old_out;\n  }\n\n  /* If the old.* record has not yet been loaded into memory, do so now. */\n  if( p->pUnpacked==0 ){\n    u32 nRec;\n    u8 *aRec;\n\n    nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);\n    aRec = sqlite3DbMallocRaw(db, nRec);\n    if( !aRec ) goto preupdate_old_out;\n    rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);\n    if( rc==SQLITE_OK ){\n      p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);\n      if( !p->pUnpacked ) rc = SQLITE_NOMEM;\n    }\n    if( rc!=SQLITE_OK ){\n      sqlite3DbFree(db, aRec);\n      goto preupdate_old_out;\n    }\n    p->aRecord = aRec;\n  }\n\n  pMem = *ppValue = &p->pUnpacked->aMem[iIdx];\n  if( iIdx==p->pTab->iPKey ){\n    sqlite3VdbeMemSetInt64(pMem, p->iKey1);\n  }else if( iIdx>=p->pUnpacked->nField ){\n    *ppValue = (sqlite3_value *)columnNullValue();\n  }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){\n    if( pMem->flags & (MEM_Int|MEM_IntReal) ){\n      testcase( pMem->flags & MEM_Int );\n      testcase( pMem->flags & MEM_IntReal );\n      sqlite3VdbeMemRealify(pMem);\n    }\n  }\n\n preupdate_old_out:\n  sqlite3Error(db, rc);\n  return sqlite3ApiExit(db, rc);\n}\n#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */\n\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n/*\n** This function is called from within a pre-update callback to retrieve\n** the number of columns in the row being updated, deleted or inserted.\n*/\nSQLITE_API int sqlite3_preupdate_count(sqlite3 *db){\n  PreUpdate *p = db->pPreUpdate;\n  return (p ? p->keyinfo.nKeyField : 0);\n}\n#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */\n\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n/*\n** This function is designed to be called from within a pre-update callback\n** only. It returns zero if the change that caused the callback was made\n** immediately by a user SQL statement. Or, if the change was made by a\n** trigger program, it returns the number of trigger programs currently\n** on the stack (1 for a top-level trigger, 2 for a trigger fired by a \n** top-level trigger etc.).\n**\n** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL\n** or SET DEFAULT action is considered a trigger.\n*/\nSQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){\n  PreUpdate *p = db->pPreUpdate;\n  return (p ? p->v->nFrame : 0);\n}\n#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */\n\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n/*\n** This function is called from within a pre-update callback to retrieve\n** a field of the row currently being updated or inserted.\n*/\nSQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){\n  PreUpdate *p = db->pPreUpdate;\n  int rc = SQLITE_OK;\n  Mem *pMem;\n\n  if( !p || p->op==SQLITE_DELETE ){\n    rc = SQLITE_MISUSE_BKPT;\n    goto preupdate_new_out;\n  }\n  if( p->pPk && p->op!=SQLITE_UPDATE ){\n    iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);\n  }\n  if( iIdx>=p->pCsr->nField || iIdx<0 ){\n    rc = SQLITE_RANGE;\n    goto preupdate_new_out;\n  }\n\n  if( p->op==SQLITE_INSERT ){\n    /* For an INSERT, memory cell p->iNewReg contains the serialized record\n    ** that is being inserted. Deserialize it. */\n    UnpackedRecord *pUnpack = p->pNewUnpacked;\n    if( !pUnpack ){\n      Mem *pData = &p->v->aMem[p->iNewReg];\n      rc = ExpandBlob(pData);\n      if( rc!=SQLITE_OK ) goto preupdate_new_out;\n      pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);\n      if( !pUnpack ){\n        rc = SQLITE_NOMEM;\n        goto preupdate_new_out;\n      }\n      p->pNewUnpacked = pUnpack;\n    }\n    pMem = &pUnpack->aMem[iIdx];\n    if( iIdx==p->pTab->iPKey ){\n      sqlite3VdbeMemSetInt64(pMem, p->iKey2);\n    }else if( iIdx>=pUnpack->nField ){\n      pMem = (sqlite3_value *)columnNullValue();\n    }\n  }else{\n    /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required\n    ** value. Make a copy of the cell contents and return a pointer to it.\n    ** It is not safe to return a pointer to the memory cell itself as the\n    ** caller may modify the value text encoding.\n    */\n    assert( p->op==SQLITE_UPDATE );\n    if( !p->aNew ){\n      p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);\n      if( !p->aNew ){\n        rc = SQLITE_NOMEM;\n        goto preupdate_new_out;\n      }\n    }\n    assert( iIdx>=0 && iIdx<p->pCsr->nField );\n    pMem = &p->aNew[iIdx];\n    if( pMem->flags==0 ){\n      if( iIdx==p->pTab->iPKey ){\n        sqlite3VdbeMemSetInt64(pMem, p->iKey2);\n      }else{\n        rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);\n        if( rc!=SQLITE_OK ) goto preupdate_new_out;\n      }\n    }\n  }\n  *ppValue = pMem;\n\n preupdate_new_out:\n  sqlite3Error(db, rc);\n  return sqlite3ApiExit(db, rc);\n}\n#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */\n\n#ifdef SQLITE_ENABLE_STMT_SCANSTATUS\n/*\n** Return status data for a single loop within query pStmt.\n*/\nSQLITE_API int sqlite3_stmt_scanstatus(\n  sqlite3_stmt *pStmt,            /* Prepared statement being queried */\n  int idx,                        /* Index of loop to report on */\n  int iScanStatusOp,              /* Which metric to return */\n  void *pOut                      /* OUT: Write the answer here */\n){\n  Vdbe *p = (Vdbe*)pStmt;\n  ScanStatus *pScan;\n  if( idx<0 || idx>=p->nScan ) return 1;\n  pScan = &p->aScan[idx];\n  switch( iScanStatusOp ){\n    case SQLITE_SCANSTAT_NLOOP: {\n      *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];\n      break;\n    }\n    case SQLITE_SCANSTAT_NVISIT: {\n      *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];\n      break;\n    }\n    case SQLITE_SCANSTAT_EST: {\n      double r = 1.0;\n      LogEst x = pScan->nEst;\n      while( x<100 ){\n        x += 10;\n        r *= 0.5;\n      }\n      *(double*)pOut = r*sqlite3LogEstToInt(x);\n      break;\n    }\n    case SQLITE_SCANSTAT_NAME: {\n      *(const char**)pOut = pScan->zName;\n      break;\n    }\n    case SQLITE_SCANSTAT_EXPLAIN: {\n      if( pScan->addrExplain ){\n        *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;\n      }else{\n        *(const char**)pOut = 0;\n      }\n      break;\n    }\n    case SQLITE_SCANSTAT_SELECTID: {\n      if( pScan->addrExplain ){\n        *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;\n      }else{\n        *(int*)pOut = -1;\n      }\n      break;\n    }\n    default: {\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/*\n** Zero all counters associated with the sqlite3_stmt_scanstatus() data.\n*/\nSQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){\n  Vdbe *p = (Vdbe*)pStmt;\n  memset(p->anExec, 0, p->nOp * sizeof(i64));\n}\n#endif /* SQLITE_ENABLE_STMT_SCANSTATUS */\n\n/************** End of vdbeapi.c *********************************************/\n/************** Begin file vdbetrace.c ***************************************/\n/*\n** 2009 November 25\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains code used to insert the values of host parameters\n** (aka \"wildcards\") into the SQL text output by sqlite3_trace().\n**\n** The Vdbe parse-tree explainer is also found here.\n*/\n/* #include \"sqliteInt.h\" */\n/* #include \"vdbeInt.h\" */\n\n#ifndef SQLITE_OMIT_TRACE\n\n/*\n** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of\n** bytes in this text up to but excluding the first character in\n** a host parameter.  If the text contains no host parameters, return\n** the total number of bytes in the text.\n*/\nstatic int findNextHostParameter(const char *zSql, int *pnToken){\n  int tokenType;\n  int nTotal = 0;\n  int n;\n\n  *pnToken = 0;\n  while( zSql[0] ){\n    n = sqlite3GetToken((u8*)zSql, &tokenType);\n    assert( n>0 && tokenType!=TK_ILLEGAL );\n    if( tokenType==TK_VARIABLE ){\n      *pnToken = n;\n      break;\n    }\n    nTotal += n;\n    zSql += n;\n  }\n  return nTotal;\n}\n\n/*\n** This function returns a pointer to a nul-terminated string in memory\n** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the\n** string contains a copy of zRawSql but with host parameters expanded to \n** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1, \n** then the returned string holds a copy of zRawSql with \"-- \" prepended\n** to each line of text.\n**\n** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then\n** then long strings and blobs are truncated to that many bytes.  This\n** can be used to prevent unreasonably large trace strings when dealing\n** with large (multi-megabyte) strings and blobs.\n**\n** The calling function is responsible for making sure the memory returned\n** is eventually freed.\n**\n** ALGORITHM:  Scan the input string looking for host parameters in any of\n** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within\n** string literals, quoted identifier names, and comments.  For text forms,\n** the host parameter index is found by scanning the prepared\n** statement for the corresponding OP_Variable opcode.  Once the host\n** parameter index is known, locate the value in p->aVar[].  Then render\n** the value as a literal in place of the host parameter name.\n*/\nSQLITE_PRIVATE char *sqlite3VdbeExpandSql(\n  Vdbe *p,                 /* The prepared statement being evaluated */\n  const char *zRawSql      /* Raw text of the SQL statement */\n){\n  sqlite3 *db;             /* The database connection */\n  int idx = 0;             /* Index of a host parameter */\n  int nextIndex = 1;       /* Index of next ? host parameter */\n  int n;                   /* Length of a token prefix */\n  int nToken;              /* Length of the parameter token */\n  int i;                   /* Loop counter */\n  Mem *pVar;               /* Value of a host parameter */\n  StrAccum out;            /* Accumulate the output here */\n#ifndef SQLITE_OMIT_UTF16\n  Mem utf8;                /* Used to convert UTF16 into UTF8 for display */\n#endif\n  char zBase[100];         /* Initial working space */\n\n  db = p->db;\n  sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase), \n                      db->aLimit[SQLITE_LIMIT_LENGTH]);\n  if( db->nVdbeExec>1 ){\n    while( *zRawSql ){\n      const char *zStart = zRawSql;\n      while( *(zRawSql++)!='\\n' && *zRawSql );\n      sqlite3_str_append(&out, \"-- \", 3);\n      assert( (zRawSql - zStart) > 0 );\n      sqlite3_str_append(&out, zStart, (int)(zRawSql-zStart));\n    }\n  }else if( p->nVar==0 ){\n    sqlite3_str_append(&out, zRawSql, sqlite3Strlen30(zRawSql));\n  }else{\n    while( zRawSql[0] ){\n      n = findNextHostParameter(zRawSql, &nToken);\n      assert( n>0 );\n      sqlite3_str_append(&out, zRawSql, n);\n      zRawSql += n;\n      assert( zRawSql[0] || nToken==0 );\n      if( nToken==0 ) break;\n      if( zRawSql[0]=='?' ){\n        if( nToken>1 ){\n          assert( sqlite3Isdigit(zRawSql[1]) );\n          sqlite3GetInt32(&zRawSql[1], &idx);\n        }else{\n          idx = nextIndex;\n        }\n      }else{\n        assert( zRawSql[0]==':' || zRawSql[0]=='$' ||\n                zRawSql[0]=='@' || zRawSql[0]=='#' );\n        testcase( zRawSql[0]==':' );\n        testcase( zRawSql[0]=='$' );\n        testcase( zRawSql[0]=='@' );\n        testcase( zRawSql[0]=='#' );\n        idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);\n        assert( idx>0 );\n      }\n      zRawSql += nToken;\n      nextIndex = idx + 1;\n      assert( idx>0 && idx<=p->nVar );\n      pVar = &p->aVar[idx-1];\n      if( pVar->flags & MEM_Null ){\n        sqlite3_str_append(&out, \"NULL\", 4);\n      }else if( pVar->flags & (MEM_Int|MEM_IntReal) ){\n        sqlite3_str_appendf(&out, \"%lld\", pVar->u.i);\n      }else if( pVar->flags & MEM_Real ){\n        sqlite3_str_appendf(&out, \"%!.15g\", pVar->u.r);\n      }else if( pVar->flags & MEM_Str ){\n        int nOut;  /* Number of bytes of the string text to include in output */\n#ifndef SQLITE_OMIT_UTF16\n        u8 enc = ENC(db);\n        if( enc!=SQLITE_UTF8 ){\n          memset(&utf8, 0, sizeof(utf8));\n          utf8.db = db;\n          sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);\n          if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){\n            out.accError = SQLITE_NOMEM;\n            out.nAlloc = 0;\n          }\n          pVar = &utf8;\n        }\n#endif\n        nOut = pVar->n;\n#ifdef SQLITE_TRACE_SIZE_LIMIT\n        if( nOut>SQLITE_TRACE_SIZE_LIMIT ){\n          nOut = SQLITE_TRACE_SIZE_LIMIT;\n          while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }\n        }\n#endif    \n        sqlite3_str_appendf(&out, \"'%.*q'\", nOut, pVar->z);\n#ifdef SQLITE_TRACE_SIZE_LIMIT\n        if( nOut<pVar->n ){\n          sqlite3_str_appendf(&out, \"/*+%d bytes*/\", pVar->n-nOut);\n        }\n#endif\n#ifndef SQLITE_OMIT_UTF16\n        if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);\n#endif\n      }else if( pVar->flags & MEM_Zero ){\n        sqlite3_str_appendf(&out, \"zeroblob(%d)\", pVar->u.nZero);\n      }else{\n        int nOut;  /* Number of bytes of the blob to include in output */\n        assert( pVar->flags & MEM_Blob );\n        sqlite3_str_append(&out, \"x'\", 2);\n        nOut = pVar->n;\n#ifdef SQLITE_TRACE_SIZE_LIMIT\n        if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;\n#endif\n        for(i=0; i<nOut; i++){\n          sqlite3_str_appendf(&out, \"%02x\", pVar->z[i]&0xff);\n        }\n        sqlite3_str_append(&out, \"'\", 1);\n#ifdef SQLITE_TRACE_SIZE_LIMIT\n        if( nOut<pVar->n ){\n          sqlite3_str_appendf(&out, \"/*+%d bytes*/\", pVar->n-nOut);\n        }\n#endif\n      }\n    }\n  }\n  if( out.accError ) sqlite3_str_reset(&out);\n  return sqlite3StrAccumFinish(&out);\n}\n\n#endif /* #ifndef SQLITE_OMIT_TRACE */\n\n/************** End of vdbetrace.c *******************************************/\n/************** Begin file vdbe.c ********************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** The code in this file implements the function that runs the\n** bytecode of a prepared statement.\n**\n** Various scripts scan this source file in order to generate HTML\n** documentation, headers files, or other derived files.  The formatting\n** of the code in this file is, therefore, important.  See other comments\n** in this file for details.  If in doubt, do not deviate from existing\n** commenting and indentation practices when changing or adding code.\n*/\n/* #include \"sqliteInt.h\" */\n/* #include \"vdbeInt.h\" */\n\n/*\n** Invoke this macro on memory cells just prior to changing the\n** value of the cell.  This macro verifies that shallow copies are\n** not misused.  A shallow copy of a string or blob just copies a\n** pointer to the string or blob, not the content.  If the original\n** is changed while the copy is still in use, the string or blob might\n** be changed out from under the copy.  This macro verifies that nothing\n** like that ever happens.\n*/\n#ifdef SQLITE_DEBUG\n# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)\n#else\n# define memAboutToChange(P,M)\n#endif\n\n/*\n** The following global variable is incremented every time a cursor\n** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test\n** procedures use this information to make sure that indices are\n** working correctly.  This variable has no function other than to\n** help verify the correct operation of the library.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_search_count = 0;\n#endif\n\n/*\n** When this global variable is positive, it gets decremented once before\n** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted\n** field of the sqlite3 structure is set in order to simulate an interrupt.\n**\n** This facility is used for testing purposes only.  It does not function\n** in an ordinary build.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_interrupt_count = 0;\n#endif\n\n/*\n** The next global variable is incremented each type the OP_Sort opcode\n** is executed.  The test procedures use this information to make sure that\n** sorting is occurring or not occurring at appropriate times.   This variable\n** has no function other than to help verify the correct operation of the\n** library.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_sort_count = 0;\n#endif\n\n/*\n** The next global variable records the size of the largest MEM_Blob\n** or MEM_Str that has been used by a VDBE opcode.  The test procedures\n** use this information to make sure that the zero-blob functionality\n** is working correctly.   This variable has no function other than to\n** help verify the correct operation of the library.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_max_blobsize = 0;\nstatic void updateMaxBlobsize(Mem *p){\n  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){\n    sqlite3_max_blobsize = p->n;\n  }\n}\n#endif\n\n/*\n** This macro evaluates to true if either the update hook or the preupdate\n** hook are enabled for database connect DB.\n*/\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n# define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)\n#else\n# define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)\n#endif\n\n/*\n** The next global variable is incremented each time the OP_Found opcode\n** is executed. This is used to test whether or not the foreign key\n** operation implemented using OP_FkIsZero is working. This variable\n** has no function other than to help verify the correct operation of the\n** library.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_found_count = 0;\n#endif\n\n/*\n** Test a register to see if it exceeds the current maximum blob size.\n** If it does, record the new maximum blob size.\n*/\n#if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)\n# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)\n#else\n# define UPDATE_MAX_BLOBSIZE(P)\n#endif\n\n#ifdef SQLITE_DEBUG\n/* This routine provides a convenient place to set a breakpoint during\n** tracing with PRAGMA vdbe_trace=on.  The breakpoint fires right after\n** each opcode is printed.  Variables \"pc\" (program counter) and pOp are\n** available to add conditionals to the breakpoint.  GDB example:\n**\n**         break test_trace_breakpoint if pc=22\n**\n** Other useful labels for breakpoints include:\n**   test_addop_breakpoint(pc,pOp)\n**   sqlite3CorruptError(lineno)\n**   sqlite3MisuseError(lineno)\n**   sqlite3CantopenError(lineno)\n*/\nstatic void test_trace_breakpoint(int pc, Op *pOp, Vdbe *v){\n  static int n = 0;\n  n++;\n}\n#endif\n\n/*\n** Invoke the VDBE coverage callback, if that callback is defined.  This\n** feature is used for test suite validation only and does not appear an\n** production builds.\n**\n** M is the type of branch.  I is the direction taken for this instance of\n** the branch.\n**\n**   M: 2 - two-way branch (I=0: fall-thru   1: jump                )\n**      3 - two-way + NULL (I=0: fall-thru   1: jump      2: NULL   )\n**      4 - OP_Jump        (I=0: jump p1     1: jump p2   2: jump p3)\n**\n** In other words, if M is 2, then I is either 0 (for fall-through) or\n** 1 (for when the branch is taken).  If M is 3, the I is 0 for an\n** ordinary fall-through, I is 1 if the branch was taken, and I is 2 \n** if the result of comparison is NULL.  For M=3, I=2 the jump may or\n** may not be taken, depending on the SQLITE_JUMPIFNULL flags in p5.\n** When M is 4, that means that an OP_Jump is being run.  I is 0, 1, or 2\n** depending on if the operands are less than, equal, or greater than.\n**\n** iSrcLine is the source code line (from the __LINE__ macro) that\n** generated the VDBE instruction combined with flag bits.  The source\n** code line number is in the lower 24 bits of iSrcLine and the upper\n** 8 bytes are flags.  The lower three bits of the flags indicate\n** values for I that should never occur.  For example, if the branch is\n** always taken, the flags should be 0x05 since the fall-through and\n** alternate branch are never taken.  If a branch is never taken then\n** flags should be 0x06 since only the fall-through approach is allowed.\n**\n** Bit 0x08 of the flags indicates an OP_Jump opcode that is only\n** interested in equal or not-equal.  In other words, I==0 and I==2\n** should be treated as equivalent\n**\n** Since only a line number is retained, not the filename, this macro\n** only works for amalgamation builds.  But that is ok, since these macros\n** should be no-ops except for special builds used to measure test coverage.\n*/\n#if !defined(SQLITE_VDBE_COVERAGE)\n# define VdbeBranchTaken(I,M)\n#else\n# define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)\n  static void vdbeTakeBranch(u32 iSrcLine, u8 I, u8 M){\n    u8 mNever;\n    assert( I<=2 );  /* 0: fall through,  1: taken,  2: alternate taken */\n    assert( M<=4 );  /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */\n    assert( I<M );   /* I can only be 2 if M is 3 or 4 */\n    /* Transform I from a integer [0,1,2] into a bitmask of [1,2,4] */\n    I = 1<<I;\n    /* The upper 8 bits of iSrcLine are flags.  The lower three bits of\n    ** the flags indicate directions that the branch can never go.  If\n    ** a branch really does go in one of those directions, assert right\n    ** away. */\n    mNever = iSrcLine >> 24;\n    assert( (I & mNever)==0 );\n    if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/\n    /* Invoke the branch coverage callback with three arguments:\n    **    iSrcLine - the line number of the VdbeCoverage() macro, with\n    **               flags removed.\n    **    I        - Mask of bits 0x07 indicating which cases are are\n    **               fulfilled by this instance of the jump.  0x01 means\n    **               fall-thru, 0x02 means taken, 0x04 means NULL.  Any\n    **               impossible cases (ex: if the comparison is never NULL)\n    **               are filled in automatically so that the coverage\n    **               measurement logic does not flag those impossible cases\n    **               as missed coverage.\n    **    M        - Type of jump.  Same as M argument above\n    */\n    I |= mNever;\n    if( M==2 ) I |= 0x04;\n    if( M==4 ){\n      I |= 0x08;\n      if( (mNever&0x08)!=0 && (I&0x05)!=0) I |= 0x05; /*NO_TEST*/\n    }\n    sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,\n                                    iSrcLine&0xffffff, I, M);\n  }\n#endif\n\n/*\n** An ephemeral string value (signified by the MEM_Ephem flag) contains\n** a pointer to a dynamically allocated string where some other entity\n** is responsible for deallocating that string.  Because the register\n** does not control the string, it might be deleted without the register\n** knowing it.\n**\n** This routine converts an ephemeral string into a dynamically allocated\n** string that the register itself controls.  In other words, it\n** converts an MEM_Ephem string into a string with P.z==P.zMalloc.\n*/\n#define Deephemeralize(P) \\\n   if( ((P)->flags&MEM_Ephem)!=0 \\\n       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}\n\n/* Return true if the cursor was opened using the OP_OpenSorter opcode. */\n#define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)\n\n/*\n** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL\n** if we run out of memory.\n*/\nstatic VdbeCursor *allocateCursor(\n  Vdbe *p,              /* The virtual machine */\n  int iCur,             /* Index of the new VdbeCursor */\n  int nField,           /* Number of fields in the table or index */\n  int iDb,              /* Database the cursor belongs to, or -1 */\n  u8 eCurType           /* Type of the new cursor */\n){\n  /* Find the memory cell that will be used to store the blob of memory\n  ** required for this VdbeCursor structure. It is convenient to use a \n  ** vdbe memory cell to manage the memory allocation required for a\n  ** VdbeCursor structure for the following reasons:\n  **\n  **   * Sometimes cursor numbers are used for a couple of different\n  **     purposes in a vdbe program. The different uses might require\n  **     different sized allocations. Memory cells provide growable\n  **     allocations.\n  **\n  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can\n  **     be freed lazily via the sqlite3_release_memory() API. This\n  **     minimizes the number of malloc calls made by the system.\n  **\n  ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from\n  ** the top of the register space.  Cursor 1 is at Mem[p->nMem-1].\n  ** Cursor 2 is at Mem[p->nMem-2]. And so forth.\n  */\n  Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;\n\n  int nByte;\n  VdbeCursor *pCx = 0;\n  nByte = \n      ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField + \n      (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);\n\n  assert( iCur>=0 && iCur<p->nCursor );\n  if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/\n    /* Before calling sqlite3VdbeFreeCursor(), ensure the isEphemeral flag\n    ** is clear. Otherwise, if this is an ephemeral cursor created by \n    ** OP_OpenDup, the cursor will not be closed and will still be part\n    ** of a BtShared.pCursor list.  */\n    if( p->apCsr[iCur]->pBtx==0 ) p->apCsr[iCur]->isEphemeral = 0;\n    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);\n    p->apCsr[iCur] = 0;\n  }\n  if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){\n    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;\n    memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));\n    pCx->eCurType = eCurType;\n    pCx->iDb = iDb;\n    pCx->nField = nField;\n    pCx->aOffset = &pCx->aType[nField];\n    if( eCurType==CURTYPE_BTREE ){\n      pCx->uc.pCursor = (BtCursor*)\n          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];\n      sqlite3BtreeCursorZero(pCx->uc.pCursor);\n    }\n  }\n  return pCx;\n}\n\n/*\n** The string in pRec is known to look like an integer and to have a\n** floating point value of rValue.  Return true and set *piValue to the\n** integer value if the string is in range to be an integer.  Otherwise,\n** return false.\n*/\nstatic int alsoAnInt(Mem *pRec, double rValue, i64 *piValue){\n  i64 iValue = (double)rValue;\n  if( sqlite3RealSameAsInt(rValue,iValue) ){\n    *piValue = iValue;\n    return 1;\n  }\n  return 0==sqlite3Atoi64(pRec->z, piValue, pRec->n, pRec->enc);\n}\n\n/*\n** Try to convert a value into a numeric representation if we can\n** do so without loss of information.  In other words, if the string\n** looks like a number, convert it into a number.  If it does not\n** look like a number, leave it alone.\n**\n** If the bTryForInt flag is true, then extra effort is made to give\n** an integer representation.  Strings that look like floating point\n** values but which have no fractional component (example: '48.00')\n** will have a MEM_Int representation when bTryForInt is true.\n**\n** If bTryForInt is false, then if the input string contains a decimal\n** point or exponential notation, the result is only MEM_Real, even\n** if there is an exact integer representation of the quantity.\n*/\nstatic void applyNumericAffinity(Mem *pRec, int bTryForInt){\n  double rValue;\n  u8 enc = pRec->enc;\n  int rc;\n  assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real|MEM_IntReal))==MEM_Str );\n  rc = sqlite3AtoF(pRec->z, &rValue, pRec->n, enc);\n  if( rc<=0 ) return;\n  if( rc==1 && alsoAnInt(pRec, rValue, &pRec->u.i) ){\n    pRec->flags |= MEM_Int;\n  }else{\n    pRec->u.r = rValue;\n    pRec->flags |= MEM_Real;\n    if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);\n  }\n  /* TEXT->NUMERIC is many->one.  Hence, it is important to invalidate the\n  ** string representation after computing a numeric equivalent, because the\n  ** string representation might not be the canonical representation for the\n  ** numeric value.  Ticket [343634942dd54ab57b7024] 2018-01-31. */\n  pRec->flags &= ~MEM_Str;\n}\n\n/*\n** Processing is determine by the affinity parameter:\n**\n** SQLITE_AFF_INTEGER:\n** SQLITE_AFF_REAL:\n** SQLITE_AFF_NUMERIC:\n**    Try to convert pRec to an integer representation or a \n**    floating-point representation if an integer representation\n**    is not possible.  Note that the integer representation is\n**    always preferred, even if the affinity is REAL, because\n**    an integer representation is more space efficient on disk.\n**\n** SQLITE_AFF_TEXT:\n**    Convert pRec to a text representation.\n**\n** SQLITE_AFF_BLOB:\n** SQLITE_AFF_NONE:\n**    No-op.  pRec is unchanged.\n*/\nstatic void applyAffinity(\n  Mem *pRec,          /* The value to apply affinity to */\n  char affinity,      /* The affinity to be applied */\n  u8 enc              /* Use this text encoding */\n){\n  if( affinity>=SQLITE_AFF_NUMERIC ){\n    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL\n             || affinity==SQLITE_AFF_NUMERIC );\n    if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/\n      if( (pRec->flags & MEM_Real)==0 ){\n        if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);\n      }else{\n        sqlite3VdbeIntegerAffinity(pRec);\n      }\n    }\n  }else if( affinity==SQLITE_AFF_TEXT ){\n    /* Only attempt the conversion to TEXT if there is an integer or real\n    ** representation (blob and NULL do not get converted) but no string\n    ** representation.  It would be harmless to repeat the conversion if \n    ** there is already a string rep, but it is pointless to waste those\n    ** CPU cycles. */\n    if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/\n      if( (pRec->flags&(MEM_Real|MEM_Int|MEM_IntReal)) ){\n        testcase( pRec->flags & MEM_Int );\n        testcase( pRec->flags & MEM_Real );\n        testcase( pRec->flags & MEM_IntReal );\n        sqlite3VdbeMemStringify(pRec, enc, 1);\n      }\n    }\n    pRec->flags &= ~(MEM_Real|MEM_Int|MEM_IntReal);\n  }\n}\n\n/*\n** Try to convert the type of a function argument or a result column\n** into a numeric representation.  Use either INTEGER or REAL whichever\n** is appropriate.  But only do the conversion if it is possible without\n** loss of information and return the revised type of the argument.\n*/\nSQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){\n  int eType = sqlite3_value_type(pVal);\n  if( eType==SQLITE_TEXT ){\n    Mem *pMem = (Mem*)pVal;\n    applyNumericAffinity(pMem, 0);\n    eType = sqlite3_value_type(pVal);\n  }\n  return eType;\n}\n\n/*\n** Exported version of applyAffinity(). This one works on sqlite3_value*, \n** not the internal Mem* type.\n*/\nSQLITE_PRIVATE void sqlite3ValueApplyAffinity(\n  sqlite3_value *pVal, \n  u8 affinity, \n  u8 enc\n){\n  applyAffinity((Mem *)pVal, affinity, enc);\n}\n\n/*\n** pMem currently only holds a string type (or maybe a BLOB that we can\n** interpret as a string if we want to).  Compute its corresponding\n** numeric type, if has one.  Set the pMem->u.r and pMem->u.i fields\n** accordingly.\n*/\nstatic u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){\n  int rc;\n  sqlite3_int64 ix;\n  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 );\n  assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );\n  ExpandBlob(pMem);\n  rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);\n  if( rc<=0 ){\n    if( rc==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1 ){\n      pMem->u.i = ix;\n      return MEM_Int;\n    }else{\n      return MEM_Real;\n    }\n  }else if( rc==1 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)==0 ){\n    pMem->u.i = ix;\n    return MEM_Int;\n  }\n  return MEM_Real;\n}\n\n/*\n** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or\n** none.  \n**\n** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.\n** But it does set pMem->u.r and pMem->u.i appropriately.\n*/\nstatic u16 numericType(Mem *pMem){\n  if( pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal) ){\n    testcase( pMem->flags & MEM_Int );\n    testcase( pMem->flags & MEM_Real );\n    testcase( pMem->flags & MEM_IntReal );\n    return pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal);\n  }\n  if( pMem->flags & (MEM_Str|MEM_Blob) ){\n    testcase( pMem->flags & MEM_Str );\n    testcase( pMem->flags & MEM_Blob );\n    return computeNumericType(pMem);\n  }\n  return 0;\n}\n\n#ifdef SQLITE_DEBUG\n/*\n** Write a nice string representation of the contents of cell pMem\n** into buffer zBuf, length nBuf.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr){\n  int f = pMem->flags;\n  static const char *const encnames[] = {\"(X)\", \"(8)\", \"(16LE)\", \"(16BE)\"};\n  if( f&MEM_Blob ){\n    int i;\n    char c;\n    if( f & MEM_Dyn ){\n      c = 'z';\n      assert( (f & (MEM_Static|MEM_Ephem))==0 );\n    }else if( f & MEM_Static ){\n      c = 't';\n      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );\n    }else if( f & MEM_Ephem ){\n      c = 'e';\n      assert( (f & (MEM_Static|MEM_Dyn))==0 );\n    }else{\n      c = 's';\n    }\n    sqlite3_str_appendf(pStr, \"%cx[\", c);\n    for(i=0; i<25 && i<pMem->n; i++){\n      sqlite3_str_appendf(pStr, \"%02X\", ((int)pMem->z[i] & 0xFF));\n    }\n    sqlite3_str_appendf(pStr, \"|\");\n    for(i=0; i<25 && i<pMem->n; i++){\n      char z = pMem->z[i];\n      sqlite3_str_appendchar(pStr, 1, (z<32||z>126)?'.':z);\n    }\n    sqlite3_str_appendf(pStr,\"]\");\n    if( f & MEM_Zero ){\n      sqlite3_str_appendf(pStr, \"+%dz\",pMem->u.nZero);\n    }\n  }else if( f & MEM_Str ){\n    int j;\n    u8 c;\n    if( f & MEM_Dyn ){\n      c = 'z';\n      assert( (f & (MEM_Static|MEM_Ephem))==0 );\n    }else if( f & MEM_Static ){\n      c = 't';\n      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );\n    }else if( f & MEM_Ephem ){\n      c = 'e';\n      assert( (f & (MEM_Static|MEM_Dyn))==0 );\n    }else{\n      c = 's';\n    }\n    sqlite3_str_appendf(pStr, \" %c%d[\", c, pMem->n);\n    for(j=0; j<25 && j<pMem->n; j++){\n      c = pMem->z[j];\n      sqlite3_str_appendchar(pStr, 1, (c>=0x20&&c<=0x7f) ? c : '.');\n    }\n    sqlite3_str_appendf(pStr, \"]%s\", encnames[pMem->enc]);\n  }\n}\n#endif\n\n#ifdef SQLITE_DEBUG\n/*\n** Print the value of a register for tracing purposes:\n*/\nstatic void memTracePrint(Mem *p){\n  if( p->flags & MEM_Undefined ){\n    printf(\" undefined\");\n  }else if( p->flags & MEM_Null ){\n    printf(p->flags & MEM_Zero ? \" NULL-nochng\" : \" NULL\");\n  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){\n    printf(\" si:%lld\", p->u.i);\n  }else if( (p->flags & (MEM_IntReal))!=0 ){\n    printf(\" ir:%lld\", p->u.i);\n  }else if( p->flags & MEM_Int ){\n    printf(\" i:%lld\", p->u.i);\n#ifndef SQLITE_OMIT_FLOATING_POINT\n  }else if( p->flags & MEM_Real ){\n    printf(\" r:%.17g\", p->u.r);\n#endif\n  }else if( sqlite3VdbeMemIsRowSet(p) ){\n    printf(\" (rowset)\");\n  }else{\n    StrAccum acc;\n    char zBuf[1000];\n    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);\n    sqlite3VdbeMemPrettyPrint(p, &acc);\n    printf(\" %s\", sqlite3StrAccumFinish(&acc));\n  }\n  if( p->flags & MEM_Subtype ) printf(\" subtype=0x%02x\", p->eSubtype);\n}\nstatic void registerTrace(int iReg, Mem *p){\n  printf(\"R[%d] = \", iReg);\n  memTracePrint(p);\n  if( p->pScopyFrom ){\n    printf(\" <== R[%d]\", (int)(p->pScopyFrom - &p[-iReg]));\n  }\n  printf(\"\\n\");\n  sqlite3VdbeCheckMemInvariants(p);\n}\n#endif\n\n#ifdef SQLITE_DEBUG\n/*\n** Show the values of all registers in the virtual machine.  Used for\n** interactive debugging.\n*/\nSQLITE_PRIVATE void sqlite3VdbeRegisterDump(Vdbe *v){\n  int i;\n  for(i=1; i<v->nMem; i++) registerTrace(i, v->aMem+i);\n}\n#endif /* SQLITE_DEBUG */\n\n\n#ifdef SQLITE_DEBUG\n#  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)\n#else\n#  define REGISTER_TRACE(R,M)\n#endif\n\n\n#ifdef VDBE_PROFILE\n\n/* \n** hwtime.h contains inline assembler code for implementing \n** high-performance timing routines.\n*/\n/************** Include hwtime.h in the middle of vdbe.c *********************/\n/************** Begin file hwtime.h ******************************************/\n/*\n** 2008 May 27\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains inline asm code for retrieving \"high-performance\"\n** counters for x86 and x86_64 class CPUs.\n*/\n#ifndef SQLITE_HWTIME_H\n#define SQLITE_HWTIME_H\n\n/*\n** The following routine only works on pentium-class (or newer) processors.\n** It uses the RDTSC opcode to read the cycle count value out of the\n** processor and returns that value.  This can be used for high-res\n** profiling.\n*/\n#if !defined(__STRICT_ANSI__) && \\\n    (defined(__GNUC__) || defined(_MSC_VER)) && \\\n    (defined(i386) || defined(__i386__) || defined(_M_IX86))\n\n  #if defined(__GNUC__)\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n     unsigned int lo, hi;\n     __asm__ __volatile__ (\"rdtsc\" : \"=a\" (lo), \"=d\" (hi));\n     return (sqlite_uint64)hi << 32 | lo;\n  }\n\n  #elif defined(_MSC_VER)\n\n  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){\n     __asm {\n        rdtsc\n        ret       ; return value at EDX:EAX\n     }\n  }\n\n  #endif\n\n#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n      unsigned long val;\n      __asm__ __volatile__ (\"rdtsc\" : \"=A\" (val));\n      return val;\n  }\n \n#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n      unsigned long long retval;\n      unsigned long junk;\n      __asm__ __volatile__ (\"\\n\\\n          1:      mftbu   %1\\n\\\n                  mftb    %L0\\n\\\n                  mftbu   %0\\n\\\n                  cmpw    %0,%1\\n\\\n                  bne     1b\"\n                  : \"=r\" (retval), \"=r\" (junk));\n      return retval;\n  }\n\n#else\n\n  /*\n  ** asm() is needed for hardware timing support.  Without asm(),\n  ** disable the sqlite3Hwtime() routine.\n  **\n  ** sqlite3Hwtime() is only used for some obscure debugging\n  ** and analysis configurations, not in any deliverable, so this\n  ** should not be a great loss.\n  */\nSQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }\n\n#endif\n\n#endif /* !defined(SQLITE_HWTIME_H) */\n\n/************** End of hwtime.h **********************************************/\n/************** Continuing where we left off in vdbe.c ***********************/\n\n#endif\n\n#ifndef NDEBUG\n/*\n** This function is only called from within an assert() expression. It\n** checks that the sqlite3.nTransaction variable is correctly set to\n** the number of non-transaction savepoints currently in the \n** linked list starting at sqlite3.pSavepoint.\n** \n** Usage:\n**\n**     assert( checkSavepointCount(db) );\n*/\nstatic int checkSavepointCount(sqlite3 *db){\n  int n = 0;\n  Savepoint *p;\n  for(p=db->pSavepoint; p; p=p->pNext) n++;\n  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );\n  return 1;\n}\n#endif\n\n/*\n** Return the register of pOp->p2 after first preparing it to be\n** overwritten with an integer value.\n*/\nstatic SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){\n  sqlite3VdbeMemSetNull(pOut);\n  pOut->flags = MEM_Int;\n  return pOut;\n}\nstatic Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){\n  Mem *pOut;\n  assert( pOp->p2>0 );\n  assert( pOp->p2<=(p->nMem+1 - p->nCursor) );\n  pOut = &p->aMem[pOp->p2];\n  memAboutToChange(p, pOut);\n  if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/\n    return out2PrereleaseWithClear(pOut);\n  }else{\n    pOut->flags = MEM_Int;\n    return pOut;\n  }\n}\n\n\n/*\n** Execute as much of a VDBE program as we can.\n** This is the core of sqlite3_step().  \n*/\nSQLITE_PRIVATE int sqlite3VdbeExec(\n  Vdbe *p                    /* The VDBE */\n){\n  Op *aOp = p->aOp;          /* Copy of p->aOp */\n  Op *pOp = aOp;             /* Current operation */\n#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)\n  Op *pOrigOp;               /* Value of pOp at the top of the loop */\n#endif\n#ifdef SQLITE_DEBUG\n  int nExtraDelete = 0;      /* Verifies FORDELETE and AUXDELETE flags */\n#endif\n  int rc = SQLITE_OK;        /* Value to return */\n  sqlite3 *db = p->db;       /* The database */\n  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */\n  u8 encoding = ENC(db);     /* The database encoding */\n  int iCompare = 0;          /* Result of last comparison */\n  unsigned nVmStep = 0;      /* Number of virtual machine steps */\n#ifndef SQLITE_OMIT_PROGRESS_CALLBACK\n  unsigned nProgressLimit;   /* Invoke xProgress() when nVmStep reaches this */\n#endif\n  Mem *aMem = p->aMem;       /* Copy of p->aMem */\n  Mem *pIn1 = 0;             /* 1st input operand */\n  Mem *pIn2 = 0;             /* 2nd input operand */\n  Mem *pIn3 = 0;             /* 3rd input operand */\n  Mem *pOut = 0;             /* Output operand */\n#ifdef VDBE_PROFILE\n  u64 start;                 /* CPU clock count at start of opcode */\n#endif\n  /*** INSERT STACK UNION HERE ***/\n\n  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */\n  sqlite3VdbeEnter(p);\n#ifndef SQLITE_OMIT_PROGRESS_CALLBACK\n  if( db->xProgress ){\n    u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];\n    assert( 0 < db->nProgressOps );\n    nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);\n  }else{\n    nProgressLimit = 0xffffffff;\n  }\n#endif\n  if( p->rc==SQLITE_NOMEM ){\n    /* This happens if a malloc() inside a call to sqlite3_column_text() or\n    ** sqlite3_column_text16() failed.  */\n    goto no_mem;\n  }\n  assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );\n  testcase( p->rc!=SQLITE_OK );\n  p->rc = SQLITE_OK;\n  assert( p->bIsReader || p->readOnly!=0 );\n  p->iCurrentTime = 0;\n  assert( p->explain==0 );\n  p->pResultSet = 0;\n  db->busyHandler.nBusy = 0;\n  if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;\n  sqlite3VdbeIOTraceSql(p);\n#ifdef SQLITE_DEBUG\n  sqlite3BeginBenignMalloc();\n  if( p->pc==0\n   && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0\n  ){\n    int i;\n    int once = 1;\n    sqlite3VdbePrintSql(p);\n    if( p->db->flags & SQLITE_VdbeListing ){\n      printf(\"VDBE Program Listing:\\n\");\n      for(i=0; i<p->nOp; i++){\n        sqlite3VdbePrintOp(stdout, i, &aOp[i]);\n      }\n    }\n    if( p->db->flags & SQLITE_VdbeEQP ){\n      for(i=0; i<p->nOp; i++){\n        if( aOp[i].opcode==OP_Explain ){\n          if( once ) printf(\"VDBE Query Plan:\\n\");\n          printf(\"%s\\n\", aOp[i].p4.z);\n          once = 0;\n        }\n      }\n    }\n    if( p->db->flags & SQLITE_VdbeTrace )  printf(\"VDBE Trace:\\n\");\n  }\n  sqlite3EndBenignMalloc();\n#endif\n  for(pOp=&aOp[p->pc]; 1; pOp++){\n    /* Errors are detected by individual opcodes, with an immediate\n    ** jumps to abort_due_to_error. */\n    assert( rc==SQLITE_OK );\n\n    assert( pOp>=aOp && pOp<&aOp[p->nOp]);\n#ifdef VDBE_PROFILE\n    start = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();\n#endif\n    nVmStep++;\n#ifdef SQLITE_ENABLE_STMT_SCANSTATUS\n    if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;\n#endif\n\n    /* Only allow tracing if SQLITE_DEBUG is defined.\n    */\n#ifdef SQLITE_DEBUG\n    if( db->flags & SQLITE_VdbeTrace ){\n      sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);\n      test_trace_breakpoint((int)(pOp - aOp),pOp,p);\n    }\n#endif\n      \n\n    /* Check to see if we need to simulate an interrupt.  This only happens\n    ** if we have a special test build.\n    */\n#ifdef SQLITE_TEST\n    if( sqlite3_interrupt_count>0 ){\n      sqlite3_interrupt_count--;\n      if( sqlite3_interrupt_count==0 ){\n        sqlite3_interrupt(db);\n      }\n    }\n#endif\n\n    /* Sanity checking on other operands */\n#ifdef SQLITE_DEBUG\n    {\n      u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];\n      if( (opProperty & OPFLG_IN1)!=0 ){\n        assert( pOp->p1>0 );\n        assert( pOp->p1<=(p->nMem+1 - p->nCursor) );\n        assert( memIsValid(&aMem[pOp->p1]) );\n        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );\n        REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);\n      }\n      if( (opProperty & OPFLG_IN2)!=0 ){\n        assert( pOp->p2>0 );\n        assert( pOp->p2<=(p->nMem+1 - p->nCursor) );\n        assert( memIsValid(&aMem[pOp->p2]) );\n        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );\n        REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);\n      }\n      if( (opProperty & OPFLG_IN3)!=0 ){\n        assert( pOp->p3>0 );\n        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );\n        assert( memIsValid(&aMem[pOp->p3]) );\n        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );\n        REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);\n      }\n      if( (opProperty & OPFLG_OUT2)!=0 ){\n        assert( pOp->p2>0 );\n        assert( pOp->p2<=(p->nMem+1 - p->nCursor) );\n        memAboutToChange(p, &aMem[pOp->p2]);\n      }\n      if( (opProperty & OPFLG_OUT3)!=0 ){\n        assert( pOp->p3>0 );\n        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );\n        memAboutToChange(p, &aMem[pOp->p3]);\n      }\n    }\n#endif\n#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)\n    pOrigOp = pOp;\n#endif\n  \n    switch( pOp->opcode ){\n\n/*****************************************************************************\n** What follows is a massive switch statement where each case implements a\n** separate instruction in the virtual machine.  If we follow the usual\n** indentation conventions, each case should be indented by 6 spaces.  But\n** that is a lot of wasted space on the left margin.  So the code within\n** the switch statement will break with convention and be flush-left. Another\n** big comment (similar to this one) will mark the point in the code where\n** we transition back to normal indentation.\n**\n** The formatting of each case is important.  The makefile for SQLite\n** generates two C files \"opcodes.h\" and \"opcodes.c\" by scanning this\n** file looking for lines that begin with \"case OP_\".  The opcodes.h files\n** will be filled with #defines that give unique integer values to each\n** opcode and the opcodes.c file is filled with an array of strings where\n** each string is the symbolic name for the corresponding opcode.  If the\n** case statement is followed by a comment of the form \"/# same as ... #/\"\n** that comment is used to determine the particular value of the opcode.\n**\n** Other keywords in the comment that follows each case are used to\n** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].\n** Keywords include: in1, in2, in3, out2, out3.  See\n** the mkopcodeh.awk script for additional information.\n**\n** Documentation about VDBE opcodes is generated by scanning this file\n** for lines of that contain \"Opcode:\".  That line and all subsequent\n** comment lines are used in the generation of the opcode.html documentation\n** file.\n**\n** SUMMARY:\n**\n**     Formatting is important to scripts that scan this file.\n**     Do not deviate from the formatting style currently in use.\n**\n*****************************************************************************/\n\n/* Opcode:  Goto * P2 * * *\n**\n** An unconditional jump to address P2.\n** The next instruction executed will be \n** the one at index P2 from the beginning of\n** the program.\n**\n** The P1 parameter is not actually used by this opcode.  However, it\n** is sometimes set to 1 instead of 0 as a hint to the command-line shell\n** that this Goto is the bottom of a loop and that the lines from P2 down\n** to the current line should be indented for EXPLAIN output.\n*/\ncase OP_Goto: {             /* jump */\n\n#ifdef SQLITE_DEBUG\n  /* In debuggging mode, when the p5 flags is set on an OP_Goto, that\n  ** means we should really jump back to the preceeding OP_ReleaseReg\n  ** instruction. */\n  if( pOp->p5 ){\n    assert( pOp->p2 < (int)(pOp - aOp) );\n    assert( pOp->p2 > 1 );\n    pOp = &aOp[pOp->p2 - 2];\n    assert( pOp[1].opcode==OP_ReleaseReg );\n    goto check_for_interrupt;\n  }\n#endif\n\njump_to_p2_and_check_for_interrupt:\n  pOp = &aOp[pOp->p2 - 1];\n\n  /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,\n  ** OP_VNext, or OP_SorterNext) all jump here upon\n  ** completion.  Check to see if sqlite3_interrupt() has been called\n  ** or if the progress callback needs to be invoked. \n  **\n  ** This code uses unstructured \"goto\" statements and does not look clean.\n  ** But that is not due to sloppy coding habits. The code is written this\n  ** way for performance, to avoid having to run the interrupt and progress\n  ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%\n  ** faster according to \"valgrind --tool=cachegrind\" */\ncheck_for_interrupt:\n  if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;\n#ifndef SQLITE_OMIT_PROGRESS_CALLBACK\n  /* Call the progress callback if it is configured and the required number\n  ** of VDBE ops have been executed (either since this invocation of\n  ** sqlite3VdbeExec() or since last time the progress callback was called).\n  ** If the progress callback returns non-zero, exit the virtual machine with\n  ** a return code SQLITE_ABORT.\n  */\n  while( nVmStep>=nProgressLimit && db->xProgress!=0 ){\n    assert( db->nProgressOps!=0 );\n    nProgressLimit += db->nProgressOps;\n    if( db->xProgress(db->pProgressArg) ){\n      nProgressLimit = 0xffffffff;\n      rc = SQLITE_INTERRUPT;\n      goto abort_due_to_error;\n    }\n  }\n#endif\n  \n  break;\n}\n\n/* Opcode:  Gosub P1 P2 * * *\n**\n** Write the current address onto register P1\n** and then jump to address P2.\n*/\ncase OP_Gosub: {            /* jump */\n  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );\n  pIn1 = &aMem[pOp->p1];\n  assert( VdbeMemDynamic(pIn1)==0 );\n  memAboutToChange(p, pIn1);\n  pIn1->flags = MEM_Int;\n  pIn1->u.i = (int)(pOp-aOp);\n  REGISTER_TRACE(pOp->p1, pIn1);\n\n  /* Most jump operations do a goto to this spot in order to update\n  ** the pOp pointer. */\njump_to_p2:\n  pOp = &aOp[pOp->p2 - 1];\n  break;\n}\n\n/* Opcode:  Return P1 * * * *\n**\n** Jump to the next instruction after the address in register P1.  After\n** the jump, register P1 becomes undefined.\n*/\ncase OP_Return: {           /* in1 */\n  pIn1 = &aMem[pOp->p1];\n  assert( pIn1->flags==MEM_Int );\n  pOp = &aOp[pIn1->u.i];\n  pIn1->flags = MEM_Undefined;\n  break;\n}\n\n/* Opcode: InitCoroutine P1 P2 P3 * *\n**\n** Set up register P1 so that it will Yield to the coroutine\n** located at address P3.\n**\n** If P2!=0 then the coroutine implementation immediately follows\n** this opcode.  So jump over the coroutine implementation to\n** address P2.\n**\n** See also: EndCoroutine\n*/\ncase OP_InitCoroutine: {     /* jump */\n  assert( pOp->p1>0 &&  pOp->p1<=(p->nMem+1 - p->nCursor) );\n  assert( pOp->p2>=0 && pOp->p2<p->nOp );\n  assert( pOp->p3>=0 && pOp->p3<p->nOp );\n  pOut = &aMem[pOp->p1];\n  assert( !VdbeMemDynamic(pOut) );\n  pOut->u.i = pOp->p3 - 1;\n  pOut->flags = MEM_Int;\n  if( pOp->p2 ) goto jump_to_p2;\n  break;\n}\n\n/* Opcode:  EndCoroutine P1 * * * *\n**\n** The instruction at the address in register P1 is a Yield.\n** Jump to the P2 parameter of that Yield.\n** After the jump, register P1 becomes undefined.\n**\n** See also: InitCoroutine\n*/\ncase OP_EndCoroutine: {           /* in1 */\n  VdbeOp *pCaller;\n  pIn1 = &aMem[pOp->p1];\n  assert( pIn1->flags==MEM_Int );\n  assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );\n  pCaller = &aOp[pIn1->u.i];\n  assert( pCaller->opcode==OP_Yield );\n  assert( pCaller->p2>=0 && pCaller->p2<p->nOp );\n  pOp = &aOp[pCaller->p2 - 1];\n  pIn1->flags = MEM_Undefined;\n  break;\n}\n\n/* Opcode:  Yield P1 P2 * * *\n**\n** Swap the program counter with the value in register P1.  This\n** has the effect of yielding to a coroutine.\n**\n** If the coroutine that is launched by this instruction ends with\n** Yield or Return then continue to the next instruction.  But if\n** the coroutine launched by this instruction ends with\n** EndCoroutine, then jump to P2 rather than continuing with the\n** next instruction.\n**\n** See also: InitCoroutine\n*/\ncase OP_Yield: {            /* in1, jump */\n  int pcDest;\n  pIn1 = &aMem[pOp->p1];\n  assert( VdbeMemDynamic(pIn1)==0 );\n  pIn1->flags = MEM_Int;\n  pcDest = (int)pIn1->u.i;\n  pIn1->u.i = (int)(pOp - aOp);\n  REGISTER_TRACE(pOp->p1, pIn1);\n  pOp = &aOp[pcDest];\n  break;\n}\n\n/* Opcode:  HaltIfNull  P1 P2 P3 P4 P5\n** Synopsis: if r[P3]=null halt\n**\n** Check the value in register P3.  If it is NULL then Halt using\n** parameter P1, P2, and P4 as if this were a Halt instruction.  If the\n** value in register P3 is not NULL, then this routine is a no-op.\n** The P5 parameter should be 1.\n*/\ncase OP_HaltIfNull: {      /* in3 */\n  pIn3 = &aMem[pOp->p3];\n#ifdef SQLITE_DEBUG\n  if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }\n#endif\n  if( (pIn3->flags & MEM_Null)==0 ) break;\n  /* Fall through into OP_Halt */\n}\n\n/* Opcode:  Halt P1 P2 * P4 P5\n**\n** Exit immediately.  All open cursors, etc are closed\n** automatically.\n**\n** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),\n** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).\n** For errors, it can be some other value.  If P1!=0 then P2 will determine\n** whether or not to rollback the current transaction.  Do not rollback\n** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,\n** then back out all changes that have occurred during this execution of the\n** VDBE, but do not rollback the transaction. \n**\n** If P4 is not null then it is an error message string.\n**\n** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.\n**\n**    0:  (no change)\n**    1:  NOT NULL contraint failed: P4\n**    2:  UNIQUE constraint failed: P4\n**    3:  CHECK constraint failed: P4\n**    4:  FOREIGN KEY constraint failed: P4\n**\n** If P5 is not zero and P4 is NULL, then everything after the \":\" is\n** omitted.\n**\n** There is an implied \"Halt 0 0 0\" instruction inserted at the very end of\n** every program.  So a jump past the last instruction of the program\n** is the same as executing Halt.\n*/\ncase OP_Halt: {\n  VdbeFrame *pFrame;\n  int pcx;\n\n  pcx = (int)(pOp - aOp);\n#ifdef SQLITE_DEBUG\n  if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }\n#endif\n  if( pOp->p1==SQLITE_OK && p->pFrame ){\n    /* Halt the sub-program. Return control to the parent frame. */\n    pFrame = p->pFrame;\n    p->pFrame = pFrame->pParent;\n    p->nFrame--;\n    sqlite3VdbeSetChanges(db, p->nChange);\n    pcx = sqlite3VdbeFrameRestore(pFrame);\n    if( pOp->p2==OE_Ignore ){\n      /* Instruction pcx is the OP_Program that invoked the sub-program \n      ** currently being halted. If the p2 instruction of this OP_Halt\n      ** instruction is set to OE_Ignore, then the sub-program is throwing\n      ** an IGNORE exception. In this case jump to the address specified\n      ** as the p2 of the calling OP_Program.  */\n      pcx = p->aOp[pcx].p2-1;\n    }\n    aOp = p->aOp;\n    aMem = p->aMem;\n    pOp = &aOp[pcx];\n    break;\n  }\n  p->rc = pOp->p1;\n  p->errorAction = (u8)pOp->p2;\n  p->pc = pcx;\n  assert( pOp->p5<=4 );\n  if( p->rc ){\n    if( pOp->p5 ){\n      static const char * const azType[] = { \"NOT NULL\", \"UNIQUE\", \"CHECK\",\n                                             \"FOREIGN KEY\" };\n      testcase( pOp->p5==1 );\n      testcase( pOp->p5==2 );\n      testcase( pOp->p5==3 );\n      testcase( pOp->p5==4 );\n      sqlite3VdbeError(p, \"%s constraint failed\", azType[pOp->p5-1]);\n      if( pOp->p4.z ){\n        p->zErrMsg = sqlite3MPrintf(db, \"%z: %s\", p->zErrMsg, pOp->p4.z);\n      }\n    }else{\n      sqlite3VdbeError(p, \"%s\", pOp->p4.z);\n    }\n    sqlite3_log(pOp->p1, \"abort at %d in [%s]: %s\", pcx, p->zSql, p->zErrMsg);\n  }\n  rc = sqlite3VdbeHalt(p);\n  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );\n  if( rc==SQLITE_BUSY ){\n    p->rc = SQLITE_BUSY;\n  }else{\n    assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );\n    assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );\n    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;\n  }\n  goto vdbe_return;\n}\n\n/* Opcode: Integer P1 P2 * * *\n** Synopsis: r[P2]=P1\n**\n** The 32-bit integer value P1 is written into register P2.\n*/\ncase OP_Integer: {         /* out2 */\n  pOut = out2Prerelease(p, pOp);\n  pOut->u.i = pOp->p1;\n  break;\n}\n\n/* Opcode: Int64 * P2 * P4 *\n** Synopsis: r[P2]=P4\n**\n** P4 is a pointer to a 64-bit integer value.\n** Write that value into register P2.\n*/\ncase OP_Int64: {           /* out2 */\n  pOut = out2Prerelease(p, pOp);\n  assert( pOp->p4.pI64!=0 );\n  pOut->u.i = *pOp->p4.pI64;\n  break;\n}\n\n#ifndef SQLITE_OMIT_FLOATING_POINT\n/* Opcode: Real * P2 * P4 *\n** Synopsis: r[P2]=P4\n**\n** P4 is a pointer to a 64-bit floating point value.\n** Write that value into register P2.\n*/\ncase OP_Real: {            /* same as TK_FLOAT, out2 */\n  pOut = out2Prerelease(p, pOp);\n  pOut->flags = MEM_Real;\n  assert( !sqlite3IsNaN(*pOp->p4.pReal) );\n  pOut->u.r = *pOp->p4.pReal;\n  break;\n}\n#endif\n\n/* Opcode: String8 * P2 * P4 *\n** Synopsis: r[P2]='P4'\n**\n** P4 points to a nul terminated UTF-8 string. This opcode is transformed \n** into a String opcode before it is executed for the first time.  During\n** this transformation, the length of string P4 is computed and stored\n** as the P1 parameter.\n*/\ncase OP_String8: {         /* same as TK_STRING, out2 */\n  assert( pOp->p4.z!=0 );\n  pOut = out2Prerelease(p, pOp);\n  pOp->p1 = sqlite3Strlen30(pOp->p4.z);\n\n#ifndef SQLITE_OMIT_UTF16\n  if( encoding!=SQLITE_UTF8 ){\n    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);\n    assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );\n    if( rc ) goto too_big;\n    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;\n    assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );\n    assert( VdbeMemDynamic(pOut)==0 );\n    pOut->szMalloc = 0;\n    pOut->flags |= MEM_Static;\n    if( pOp->p4type==P4_DYNAMIC ){\n      sqlite3DbFree(db, pOp->p4.z);\n    }\n    pOp->p4type = P4_DYNAMIC;\n    pOp->p4.z = pOut->z;\n    pOp->p1 = pOut->n;\n  }\n#endif\n  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){\n    goto too_big;\n  }\n  pOp->opcode = OP_String;\n  assert( rc==SQLITE_OK );\n  /* Fall through to the next case, OP_String */\n}\n  \n/* Opcode: String P1 P2 P3 P4 P5\n** Synopsis: r[P2]='P4' (len=P1)\n**\n** The string value P4 of length P1 (bytes) is stored in register P2.\n**\n** If P3 is not zero and the content of register P3 is equal to P5, then\n** the datatype of the register P2 is converted to BLOB.  The content is\n** the same sequence of bytes, it is merely interpreted as a BLOB instead\n** of a string, as if it had been CAST.  In other words:\n**\n** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)\n*/\ncase OP_String: {          /* out2 */\n  assert( pOp->p4.z!=0 );\n  pOut = out2Prerelease(p, pOp);\n  pOut->flags = MEM_Str|MEM_Static|MEM_Term;\n  pOut->z = pOp->p4.z;\n  pOut->n = pOp->p1;\n  pOut->enc = encoding;\n  UPDATE_MAX_BLOBSIZE(pOut);\n#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS\n  if( pOp->p3>0 ){\n    assert( pOp->p3<=(p->nMem+1 - p->nCursor) );\n    pIn3 = &aMem[pOp->p3];\n    assert( pIn3->flags & MEM_Int );\n    if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;\n  }\n#endif\n  break;\n}\n\n/* Opcode: Null P1 P2 P3 * *\n** Synopsis: r[P2..P3]=NULL\n**\n** Write a NULL into registers P2.  If P3 greater than P2, then also write\n** NULL into register P3 and every register in between P2 and P3.  If P3\n** is less than P2 (typically P3 is zero) then only register P2 is\n** set to NULL.\n**\n** If the P1 value is non-zero, then also set the MEM_Cleared flag so that\n** NULL values will not compare equal even if SQLITE_NULLEQ is set on\n** OP_Ne or OP_Eq.\n*/\ncase OP_Null: {           /* out2 */\n  int cnt;\n  u16 nullFlag;\n  pOut = out2Prerelease(p, pOp);\n  cnt = pOp->p3-pOp->p2;\n  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );\n  pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;\n  pOut->n = 0;\n#ifdef SQLITE_DEBUG\n  pOut->uTemp = 0;\n#endif\n  while( cnt>0 ){\n    pOut++;\n    memAboutToChange(p, pOut);\n    sqlite3VdbeMemSetNull(pOut);\n    pOut->flags = nullFlag;\n    pOut->n = 0;\n    cnt--;\n  }\n  break;\n}\n\n/* Opcode: SoftNull P1 * * * *\n** Synopsis: r[P1]=NULL\n**\n** Set register P1 to have the value NULL as seen by the OP_MakeRecord\n** instruction, but do not free any string or blob memory associated with\n** the register, so that if the value was a string or blob that was\n** previously copied using OP_SCopy, the copies will continue to be valid.\n*/\ncase OP_SoftNull: {\n  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );\n  pOut = &aMem[pOp->p1];\n  pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;\n  break;\n}\n\n/* Opcode: Blob P1 P2 * P4 *\n** Synopsis: r[P2]=P4 (len=P1)\n**\n** P4 points to a blob of data P1 bytes long.  Store this\n** blob in register P2.\n*/\ncase OP_Blob: {                /* out2 */\n  assert( pOp->p1 <= SQLITE_MAX_LENGTH );\n  pOut = out2Prerelease(p, pOp);\n  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);\n  pOut->enc = encoding;\n  UPDATE_MAX_BLOBSIZE(pOut);\n  break;\n}\n\n/* Opcode: Variable P1 P2 * P4 *\n** Synopsis: r[P2]=parameter(P1,P4)\n**\n** Transfer the values of bound parameter P1 into register P2\n**\n** If the parameter is named, then its name appears in P4.\n** The P4 value is used by sqlite3_bind_parameter_name().\n*/\ncase OP_Variable: {            /* out2 */\n  Mem *pVar;       /* Value being transferred */\n\n  assert( pOp->p1>0 && pOp->p1<=p->nVar );\n  assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );\n  pVar = &p->aVar[pOp->p1 - 1];\n  if( sqlite3VdbeMemTooBig(pVar) ){\n    goto too_big;\n  }\n  pOut = &aMem[pOp->p2];\n  if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);\n  memcpy(pOut, pVar, MEMCELLSIZE);\n  pOut->flags &= ~(MEM_Dyn|MEM_Ephem);\n  pOut->flags |= MEM_Static|MEM_FromBind;\n  UPDATE_MAX_BLOBSIZE(pOut);\n  break;\n}\n\n/* Opcode: Move P1 P2 P3 * *\n** Synopsis: r[P2@P3]=r[P1@P3]\n**\n** Move the P3 values in register P1..P1+P3-1 over into\n** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are\n** left holding a NULL.  It is an error for register ranges\n** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error\n** for P3 to be less than 1.\n*/\ncase OP_Move: {\n  int n;           /* Number of registers left to copy */\n  int p1;          /* Register to copy from */\n  int p2;          /* Register to copy to */\n\n  n = pOp->p3;\n  p1 = pOp->p1;\n  p2 = pOp->p2;\n  assert( n>0 && p1>0 && p2>0 );\n  assert( p1+n<=p2 || p2+n<=p1 );\n\n  pIn1 = &aMem[p1];\n  pOut = &aMem[p2];\n  do{\n    assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );\n    assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );\n    assert( memIsValid(pIn1) );\n    memAboutToChange(p, pOut);\n    sqlite3VdbeMemMove(pOut, pIn1);\n#ifdef SQLITE_DEBUG\n    pIn1->pScopyFrom = 0;\n    { int i;\n      for(i=1; i<p->nMem; i++){\n        if( aMem[i].pScopyFrom==pIn1 ){\n          aMem[i].pScopyFrom = pOut;\n        }\n      }\n    }\n#endif\n    Deephemeralize(pOut);\n    REGISTER_TRACE(p2++, pOut);\n    pIn1++;\n    pOut++;\n  }while( --n );\n  break;\n}\n\n/* Opcode: Copy P1 P2 P3 * *\n** Synopsis: r[P2@P3+1]=r[P1@P3+1]\n**\n** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.\n**\n** This instruction makes a deep copy of the value.  A duplicate\n** is made of any string or blob constant.  See also OP_SCopy.\n*/\ncase OP_Copy: {\n  int n;\n\n  n = pOp->p3;\n  pIn1 = &aMem[pOp->p1];\n  pOut = &aMem[pOp->p2];\n  assert( pOut!=pIn1 );\n  while( 1 ){\n    memAboutToChange(p, pOut);\n    sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);\n    Deephemeralize(pOut);\n#ifdef SQLITE_DEBUG\n    pOut->pScopyFrom = 0;\n#endif\n    REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);\n    if( (n--)==0 ) break;\n    pOut++;\n    pIn1++;\n  }\n  break;\n}\n\n/* Opcode: SCopy P1 P2 * * *\n** Synopsis: r[P2]=r[P1]\n**\n** Make a shallow copy of register P1 into register P2.\n**\n** This instruction makes a shallow copy of the value.  If the value\n** is a string or blob, then the copy is only a pointer to the\n** original and hence if the original changes so will the copy.\n** Worse, if the original is deallocated, the copy becomes invalid.\n** Thus the program must guarantee that the original will not change\n** during the lifetime of the copy.  Use OP_Copy to make a complete\n** copy.\n*/\ncase OP_SCopy: {            /* out2 */\n  pIn1 = &aMem[pOp->p1];\n  pOut = &aMem[pOp->p2];\n  assert( pOut!=pIn1 );\n  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);\n#ifdef SQLITE_DEBUG\n  pOut->pScopyFrom = pIn1;\n  pOut->mScopyFlags = pIn1->flags;\n#endif\n  break;\n}\n\n/* Opcode: IntCopy P1 P2 * * *\n** Synopsis: r[P2]=r[P1]\n**\n** Transfer the integer value held in register P1 into register P2.\n**\n** This is an optimized version of SCopy that works only for integer\n** values.\n*/\ncase OP_IntCopy: {            /* out2 */\n  pIn1 = &aMem[pOp->p1];\n  assert( (pIn1->flags & MEM_Int)!=0 );\n  pOut = &aMem[pOp->p2];\n  sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);\n  break;\n}\n\n/* Opcode: ResultRow P1 P2 * * *\n** Synopsis: output=r[P1@P2]\n**\n** The registers P1 through P1+P2-1 contain a single row of\n** results. This opcode causes the sqlite3_step() call to terminate\n** with an SQLITE_ROW return code and it sets up the sqlite3_stmt\n** structure to provide access to the r(P1)..r(P1+P2-1) values as\n** the result row.\n*/\ncase OP_ResultRow: {\n  Mem *pMem;\n  int i;\n  assert( p->nResColumn==pOp->p2 );\n  assert( pOp->p1>0 );\n  assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );\n\n  /* If this statement has violated immediate foreign key constraints, do\n  ** not return the number of rows modified. And do not RELEASE the statement\n  ** transaction. It needs to be rolled back.  */\n  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){\n    assert( db->flags&SQLITE_CountRows );\n    assert( p->usesStmtJournal );\n    goto abort_due_to_error;\n  }\n\n  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then \n  ** DML statements invoke this opcode to return the number of rows \n  ** modified to the user. This is the only way that a VM that\n  ** opens a statement transaction may invoke this opcode.\n  **\n  ** In case this is such a statement, close any statement transaction\n  ** opened by this VM before returning control to the user. This is to\n  ** ensure that statement-transactions are always nested, not overlapping.\n  ** If the open statement-transaction is not closed here, then the user\n  ** may step another VM that opens its own statement transaction. This\n  ** may lead to overlapping statement transactions.\n  **\n  ** The statement transaction is never a top-level transaction.  Hence\n  ** the RELEASE call below can never fail.\n  */\n  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );\n  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);\n  assert( rc==SQLITE_OK );\n\n  /* Invalidate all ephemeral cursor row caches */\n  p->cacheCtr = (p->cacheCtr + 2)|1;\n\n  /* Make sure the results of the current row are \\000 terminated\n  ** and have an assigned type.  The results are de-ephemeralized as\n  ** a side effect.\n  */\n  pMem = p->pResultSet = &aMem[pOp->p1];\n  for(i=0; i<pOp->p2; i++){\n    assert( memIsValid(&pMem[i]) );\n    Deephemeralize(&pMem[i]);\n    assert( (pMem[i].flags & MEM_Ephem)==0\n            || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );\n    sqlite3VdbeMemNulTerminate(&pMem[i]);\n    REGISTER_TRACE(pOp->p1+i, &pMem[i]);\n#ifdef SQLITE_DEBUG\n    /* The registers in the result will not be used again when the\n    ** prepared statement restarts.  This is because sqlite3_column()\n    ** APIs might have caused type conversions of made other changes to\n    ** the register values.  Therefore, we can go ahead and break any\n    ** OP_SCopy dependencies. */\n    pMem[i].pScopyFrom = 0;\n#endif\n  }\n  if( db->mallocFailed ) goto no_mem;\n\n  if( db->mTrace & SQLITE_TRACE_ROW ){\n    db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);\n  }\n\n\n  /* Return SQLITE_ROW\n  */\n  p->pc = (int)(pOp - aOp) + 1;\n  rc = SQLITE_ROW;\n  goto vdbe_return;\n}\n\n/* Opcode: Concat P1 P2 P3 * *\n** Synopsis: r[P3]=r[P2]+r[P1]\n**\n** Add the text in register P1 onto the end of the text in\n** register P2 and store the result in register P3.\n** If either the P1 or P2 text are NULL then store NULL in P3.\n**\n**   P3 = P2 || P1\n**\n** It is illegal for P1 and P3 to be the same register. Sometimes,\n** if P3 is the same register as P2, the implementation is able\n** to avoid a memcpy().\n*/\ncase OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */\n  i64 nByte;          /* Total size of the output string or blob */\n  u16 flags1;         /* Initial flags for P1 */\n  u16 flags2;         /* Initial flags for P2 */\n\n  pIn1 = &aMem[pOp->p1];\n  pIn2 = &aMem[pOp->p2];\n  pOut = &aMem[pOp->p3];\n  testcase( pOut==pIn2 );\n  assert( pIn1!=pOut );\n  flags1 = pIn1->flags;\n  testcase( flags1 & MEM_Null );\n  testcase( pIn2->flags & MEM_Null );\n  if( (flags1 | pIn2->flags) & MEM_Null ){\n    sqlite3VdbeMemSetNull(pOut);\n    break;\n  }\n  if( (flags1 & (MEM_Str|MEM_Blob))==0 ){\n    if( sqlite3VdbeMemStringify(pIn1,encoding,0) ) goto no_mem;\n    flags1 = pIn1->flags & ~MEM_Str;\n  }else if( (flags1 & MEM_Zero)!=0 ){\n    if( sqlite3VdbeMemExpandBlob(pIn1) ) goto no_mem;\n    flags1 = pIn1->flags & ~MEM_Str;\n  }\n  flags2 = pIn2->flags;\n  if( (flags2 & (MEM_Str|MEM_Blob))==0 ){\n    if( sqlite3VdbeMemStringify(pIn2,encoding,0) ) goto no_mem;\n    flags2 = pIn2->flags & ~MEM_Str;\n  }else if( (flags2 & MEM_Zero)!=0 ){\n    if( sqlite3VdbeMemExpandBlob(pIn2) ) goto no_mem;\n    flags2 = pIn2->flags & ~MEM_Str;\n  }\n  nByte = pIn1->n + pIn2->n;\n  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){\n    goto too_big;\n  }\n  if( sqlite3VdbeMemGrow(pOut, (int)nByte+3, pOut==pIn2) ){\n    goto no_mem;\n  }\n  MemSetTypeFlag(pOut, MEM_Str);\n  if( pOut!=pIn2 ){\n    memcpy(pOut->z, pIn2->z, pIn2->n);\n    assert( (pIn2->flags & MEM_Dyn) == (flags2 & MEM_Dyn) );\n    pIn2->flags = flags2;\n  }\n  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);\n  assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );\n  pIn1->flags = flags1;\n  pOut->z[nByte]=0;\n  pOut->z[nByte+1] = 0;\n  pOut->z[nByte+2] = 0;\n  pOut->flags |= MEM_Term;\n  pOut->n = (int)nByte;\n  pOut->enc = encoding;\n  UPDATE_MAX_BLOBSIZE(pOut);\n  break;\n}\n\n/* Opcode: Add P1 P2 P3 * *\n** Synopsis: r[P3]=r[P1]+r[P2]\n**\n** Add the value in register P1 to the value in register P2\n** and store the result in register P3.\n** If either input is NULL, the result is NULL.\n*/\n/* Opcode: Multiply P1 P2 P3 * *\n** Synopsis: r[P3]=r[P1]*r[P2]\n**\n**\n** Multiply the value in register P1 by the value in register P2\n** and store the result in register P3.\n** If either input is NULL, the result is NULL.\n*/\n/* Opcode: Subtract P1 P2 P3 * *\n** Synopsis: r[P3]=r[P2]-r[P1]\n**\n** Subtract the value in register P1 from the value in register P2\n** and store the result in register P3.\n** If either input is NULL, the result is NULL.\n*/\n/* Opcode: Divide P1 P2 P3 * *\n** Synopsis: r[P3]=r[P2]/r[P1]\n**\n** Divide the value in register P1 by the value in register P2\n** and store the result in register P3 (P3=P2/P1). If the value in \n** register P1 is zero, then the result is NULL. If either input is \n** NULL, the result is NULL.\n*/\n/* Opcode: Remainder P1 P2 P3 * *\n** Synopsis: r[P3]=r[P2]%r[P1]\n**\n** Compute the remainder after integer register P2 is divided by \n** register P1 and store the result in register P3. \n** If the value in register P1 is zero the result is NULL.\n** If either operand is NULL, the result is NULL.\n*/\ncase OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */\ncase OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */\ncase OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */\ncase OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */\ncase OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */\n  u16 flags;      /* Combined MEM_* flags from both inputs */\n  u16 type1;      /* Numeric type of left operand */\n  u16 type2;      /* Numeric type of right operand */\n  i64 iA;         /* Integer value of left operand */\n  i64 iB;         /* Integer value of right operand */\n  double rA;      /* Real value of left operand */\n  double rB;      /* Real value of right operand */\n\n  pIn1 = &aMem[pOp->p1];\n  type1 = numericType(pIn1);\n  pIn2 = &aMem[pOp->p2];\n  type2 = numericType(pIn2);\n  pOut = &aMem[pOp->p3];\n  flags = pIn1->flags | pIn2->flags;\n  if( (type1 & type2 & MEM_Int)!=0 ){\n    iA = pIn1->u.i;\n    iB = pIn2->u.i;\n    switch( pOp->opcode ){\n      case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;\n      case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;\n      case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;\n      case OP_Divide: {\n        if( iA==0 ) goto arithmetic_result_is_null;\n        if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;\n        iB /= iA;\n        break;\n      }\n      default: {\n        if( iA==0 ) goto arithmetic_result_is_null;\n        if( iA==-1 ) iA = 1;\n        iB %= iA;\n        break;\n      }\n    }\n    pOut->u.i = iB;\n    MemSetTypeFlag(pOut, MEM_Int);\n  }else if( (flags & MEM_Null)!=0 ){\n    goto arithmetic_result_is_null;\n  }else{\nfp_math:\n    rA = sqlite3VdbeRealValue(pIn1);\n    rB = sqlite3VdbeRealValue(pIn2);\n    switch( pOp->opcode ){\n      case OP_Add:         rB += rA;       break;\n      case OP_Subtract:    rB -= rA;       break;\n      case OP_Multiply:    rB *= rA;       break;\n      case OP_Divide: {\n        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */\n        if( rA==(double)0 ) goto arithmetic_result_is_null;\n        rB /= rA;\n        break;\n      }\n      default: {\n        iA = sqlite3VdbeIntValue(pIn1);\n        iB = sqlite3VdbeIntValue(pIn2);\n        if( iA==0 ) goto arithmetic_result_is_null;\n        if( iA==-1 ) iA = 1;\n        rB = (double)(iB % iA);\n        break;\n      }\n    }\n#ifdef SQLITE_OMIT_FLOATING_POINT\n    pOut->u.i = rB;\n    MemSetTypeFlag(pOut, MEM_Int);\n#else\n    if( sqlite3IsNaN(rB) ){\n      goto arithmetic_result_is_null;\n    }\n    pOut->u.r = rB;\n    MemSetTypeFlag(pOut, MEM_Real);\n#endif\n  }\n  break;\n\narithmetic_result_is_null:\n  sqlite3VdbeMemSetNull(pOut);\n  break;\n}\n\n/* Opcode: CollSeq P1 * * P4\n**\n** P4 is a pointer to a CollSeq object. If the next call to a user function\n** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will\n** be returned. This is used by the built-in min(), max() and nullif()\n** functions.\n**\n** If P1 is not zero, then it is a register that a subsequent min() or\n** max() aggregate will set to 1 if the current row is not the minimum or\n** maximum.  The P1 register is initialized to 0 by this instruction.\n**\n** The interface used by the implementation of the aforementioned functions\n** to retrieve the collation sequence set by this opcode is not available\n** publicly.  Only built-in functions have access to this feature.\n*/\ncase OP_CollSeq: {\n  assert( pOp->p4type==P4_COLLSEQ );\n  if( pOp->p1 ){\n    sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);\n  }\n  break;\n}\n\n/* Opcode: BitAnd P1 P2 P3 * *\n** Synopsis: r[P3]=r[P1]&r[P2]\n**\n** Take the bit-wise AND of the values in register P1 and P2 and\n** store the result in register P3.\n** If either input is NULL, the result is NULL.\n*/\n/* Opcode: BitOr P1 P2 P3 * *\n** Synopsis: r[P3]=r[P1]|r[P2]\n**\n** Take the bit-wise OR of the values in register P1 and P2 and\n** store the result in register P3.\n** If either input is NULL, the result is NULL.\n*/\n/* Opcode: ShiftLeft P1 P2 P3 * *\n** Synopsis: r[P3]=r[P2]<<r[P1]\n**\n** Shift the integer value in register P2 to the left by the\n** number of bits specified by the integer in register P1.\n** Store the result in register P3.\n** If either input is NULL, the result is NULL.\n*/\n/* Opcode: ShiftRight P1 P2 P3 * *\n** Synopsis: r[P3]=r[P2]>>r[P1]\n**\n** Shift the integer value in register P2 to the right by the\n** number of bits specified by the integer in register P1.\n** Store the result in register P3.\n** If either input is NULL, the result is NULL.\n*/\ncase OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */\ncase OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */\ncase OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */\ncase OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */\n  i64 iA;\n  u64 uA;\n  i64 iB;\n  u8 op;\n\n  pIn1 = &aMem[pOp->p1];\n  pIn2 = &aMem[pOp->p2];\n  pOut = &aMem[pOp->p3];\n  if( (pIn1->flags | pIn2->flags) & MEM_Null ){\n    sqlite3VdbeMemSetNull(pOut);\n    break;\n  }\n  iA = sqlite3VdbeIntValue(pIn2);\n  iB = sqlite3VdbeIntValue(pIn1);\n  op = pOp->opcode;\n  if( op==OP_BitAnd ){\n    iA &= iB;\n  }else if( op==OP_BitOr ){\n    iA |= iB;\n  }else if( iB!=0 ){\n    assert( op==OP_ShiftRight || op==OP_ShiftLeft );\n\n    /* If shifting by a negative amount, shift in the other direction */\n    if( iB<0 ){\n      assert( OP_ShiftRight==OP_ShiftLeft+1 );\n      op = 2*OP_ShiftLeft + 1 - op;\n      iB = iB>(-64) ? -iB : 64;\n    }\n\n    if( iB>=64 ){\n      iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;\n    }else{\n      memcpy(&uA, &iA, sizeof(uA));\n      if( op==OP_ShiftLeft ){\n        uA <<= iB;\n      }else{\n        uA >>= iB;\n        /* Sign-extend on a right shift of a negative number */\n        if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);\n      }\n      memcpy(&iA, &uA, sizeof(iA));\n    }\n  }\n  pOut->u.i = iA;\n  MemSetTypeFlag(pOut, MEM_Int);\n  break;\n}\n\n/* Opcode: AddImm  P1 P2 * * *\n** Synopsis: r[P1]=r[P1]+P2\n** \n** Add the constant P2 to the value in register P1.\n** The result is always an integer.\n**\n** To force any register to be an integer, just add 0.\n*/\ncase OP_AddImm: {            /* in1 */\n  pIn1 = &aMem[pOp->p1];\n  memAboutToChange(p, pIn1);\n  sqlite3VdbeMemIntegerify(pIn1);\n  pIn1->u.i += pOp->p2;\n  break;\n}\n\n/* Opcode: MustBeInt P1 P2 * * *\n** \n** Force the value in register P1 to be an integer.  If the value\n** in P1 is not an integer and cannot be converted into an integer\n** without data loss, then jump immediately to P2, or if P2==0\n** raise an SQLITE_MISMATCH exception.\n*/\ncase OP_MustBeInt: {            /* jump, in1 */\n  pIn1 = &aMem[pOp->p1];\n  if( (pIn1->flags & MEM_Int)==0 ){\n    applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);\n    if( (pIn1->flags & MEM_Int)==0 ){\n      VdbeBranchTaken(1, 2);\n      if( pOp->p2==0 ){\n        rc = SQLITE_MISMATCH;\n        goto abort_due_to_error;\n      }else{\n        goto jump_to_p2;\n      }\n    }\n  }\n  VdbeBranchTaken(0, 2);\n  MemSetTypeFlag(pIn1, MEM_Int);\n  break;\n}\n\n#ifndef SQLITE_OMIT_FLOATING_POINT\n/* Opcode: RealAffinity P1 * * * *\n**\n** If register P1 holds an integer convert it to a real value.\n**\n** This opcode is used when extracting information from a column that\n** has REAL affinity.  Such column values may still be stored as\n** integers, for space efficiency, but after extraction we want them\n** to have only a real value.\n*/\ncase OP_RealAffinity: {                  /* in1 */\n  pIn1 = &aMem[pOp->p1];\n  if( pIn1->flags & (MEM_Int|MEM_IntReal) ){\n    testcase( pIn1->flags & MEM_Int );\n    testcase( pIn1->flags & MEM_IntReal );\n    sqlite3VdbeMemRealify(pIn1);\n    REGISTER_TRACE(pOp->p1, pIn1);\n  }\n  break;\n}\n#endif\n\n#ifndef SQLITE_OMIT_CAST\n/* Opcode: Cast P1 P2 * * *\n** Synopsis: affinity(r[P1])\n**\n** Force the value in register P1 to be the type defined by P2.\n** \n** <ul>\n** <li> P2=='A' &rarr; BLOB\n** <li> P2=='B' &rarr; TEXT\n** <li> P2=='C' &rarr; NUMERIC\n** <li> P2=='D' &rarr; INTEGER\n** <li> P2=='E' &rarr; REAL\n** </ul>\n**\n** A NULL value is not changed by this routine.  It remains NULL.\n*/\ncase OP_Cast: {                  /* in1 */\n  assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );\n  testcase( pOp->p2==SQLITE_AFF_TEXT );\n  testcase( pOp->p2==SQLITE_AFF_BLOB );\n  testcase( pOp->p2==SQLITE_AFF_NUMERIC );\n  testcase( pOp->p2==SQLITE_AFF_INTEGER );\n  testcase( pOp->p2==SQLITE_AFF_REAL );\n  pIn1 = &aMem[pOp->p1];\n  memAboutToChange(p, pIn1);\n  rc = ExpandBlob(pIn1);\n  if( rc ) goto abort_due_to_error;\n  rc = sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);\n  if( rc ) goto abort_due_to_error;\n  UPDATE_MAX_BLOBSIZE(pIn1);\n  REGISTER_TRACE(pOp->p1, pIn1);\n  break;\n}\n#endif /* SQLITE_OMIT_CAST */\n\n/* Opcode: Eq P1 P2 P3 P4 P5\n** Synopsis: IF r[P3]==r[P1]\n**\n** Compare the values in register P1 and P3.  If reg(P3)==reg(P1) then\n** jump to address P2.  Or if the SQLITE_STOREP2 flag is set in P5, then\n** store the result of comparison in register P2.\n**\n** The SQLITE_AFF_MASK portion of P5 must be an affinity character -\n** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made \n** to coerce both inputs according to this affinity before the\n** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric\n** affinity is used. Note that the affinity conversions are stored\n** back into the input registers P1 and P3.  So this opcode can cause\n** persistent changes to registers P1 and P3.\n**\n** Once any conversions have taken place, and neither value is NULL, \n** the values are compared. If both values are blobs then memcmp() is\n** used to determine the results of the comparison.  If both values\n** are text, then the appropriate collating function specified in\n** P4 is used to do the comparison.  If P4 is not specified then\n** memcmp() is used to compare text string.  If both values are\n** numeric, then a numeric comparison is used. If the two values\n** are of different types, then numbers are considered less than\n** strings and strings are considered less than blobs.\n**\n** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either\n** true or false and is never NULL.  If both operands are NULL then the result\n** of comparison is true.  If either operand is NULL then the result is false.\n** If neither operand is NULL the result is the same as it would be if\n** the SQLITE_NULLEQ flag were omitted from P5.\n**\n** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the\n** content of r[P2] is only changed if the new value is NULL or 0 (false).\n** In other words, a prior r[P2] value will not be overwritten by 1 (true).\n*/\n/* Opcode: Ne P1 P2 P3 P4 P5\n** Synopsis: IF r[P3]!=r[P1]\n**\n** This works just like the Eq opcode except that the jump is taken if\n** the operands in registers P1 and P3 are not equal.  See the Eq opcode for\n** additional information.\n**\n** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the\n** content of r[P2] is only changed if the new value is NULL or 1 (true).\n** In other words, a prior r[P2] value will not be overwritten by 0 (false).\n*/\n/* Opcode: Lt P1 P2 P3 P4 P5\n** Synopsis: IF r[P3]<r[P1]\n**\n** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then\n** jump to address P2.  Or if the SQLITE_STOREP2 flag is set in P5 store\n** the result of comparison (0 or 1 or NULL) into register P2.\n**\n** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or\n** reg(P3) is NULL then the take the jump.  If the SQLITE_JUMPIFNULL \n** bit is clear then fall through if either operand is NULL.\n**\n** The SQLITE_AFF_MASK portion of P5 must be an affinity character -\n** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made \n** to coerce both inputs according to this affinity before the\n** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric\n** affinity is used. Note that the affinity conversions are stored\n** back into the input registers P1 and P3.  So this opcode can cause\n** persistent changes to registers P1 and P3.\n**\n** Once any conversions have taken place, and neither value is NULL, \n** the values are compared. If both values are blobs then memcmp() is\n** used to determine the results of the comparison.  If both values\n** are text, then the appropriate collating function specified in\n** P4 is  used to do the comparison.  If P4 is not specified then\n** memcmp() is used to compare text string.  If both values are\n** numeric, then a numeric comparison is used. If the two values\n** are of different types, then numbers are considered less than\n** strings and strings are considered less than blobs.\n*/\n/* Opcode: Le P1 P2 P3 P4 P5\n** Synopsis: IF r[P3]<=r[P1]\n**\n** This works just like the Lt opcode except that the jump is taken if\n** the content of register P3 is less than or equal to the content of\n** register P1.  See the Lt opcode for additional information.\n*/\n/* Opcode: Gt P1 P2 P3 P4 P5\n** Synopsis: IF r[P3]>r[P1]\n**\n** This works just like the Lt opcode except that the jump is taken if\n** the content of register P3 is greater than the content of\n** register P1.  See the Lt opcode for additional information.\n*/\n/* Opcode: Ge P1 P2 P3 P4 P5\n** Synopsis: IF r[P3]>=r[P1]\n**\n** This works just like the Lt opcode except that the jump is taken if\n** the content of register P3 is greater than or equal to the content of\n** register P1.  See the Lt opcode for additional information.\n*/\ncase OP_Eq:               /* same as TK_EQ, jump, in1, in3 */\ncase OP_Ne:               /* same as TK_NE, jump, in1, in3 */\ncase OP_Lt:               /* same as TK_LT, jump, in1, in3 */\ncase OP_Le:               /* same as TK_LE, jump, in1, in3 */\ncase OP_Gt:               /* same as TK_GT, jump, in1, in3 */\ncase OP_Ge: {             /* same as TK_GE, jump, in1, in3 */\n  int res, res2;      /* Result of the comparison of pIn1 against pIn3 */\n  char affinity;      /* Affinity to use for comparison */\n  u16 flags1;         /* Copy of initial value of pIn1->flags */\n  u16 flags3;         /* Copy of initial value of pIn3->flags */\n\n  pIn1 = &aMem[pOp->p1];\n  pIn3 = &aMem[pOp->p3];\n  flags1 = pIn1->flags;\n  flags3 = pIn3->flags;\n  if( (flags1 | flags3)&MEM_Null ){\n    /* One or both operands are NULL */\n    if( pOp->p5 & SQLITE_NULLEQ ){\n      /* If SQLITE_NULLEQ is set (which will only happen if the operator is\n      ** OP_Eq or OP_Ne) then take the jump or not depending on whether\n      ** or not both operands are null.\n      */\n      assert( (flags1 & MEM_Cleared)==0 );\n      assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB );\n      testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 );\n      if( (flags1&flags3&MEM_Null)!=0\n       && (flags3&MEM_Cleared)==0\n      ){\n        res = 0;  /* Operands are equal */\n      }else{\n        res = ((flags3 & MEM_Null) ? -1 : +1);  /* Operands are not equal */\n      }\n    }else{\n      /* SQLITE_NULLEQ is clear and at least one operand is NULL,\n      ** then the result is always NULL.\n      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.\n      */\n      if( pOp->p5 & SQLITE_STOREP2 ){\n        pOut = &aMem[pOp->p2];\n        iCompare = 1;    /* Operands are not equal */\n        memAboutToChange(p, pOut);\n        MemSetTypeFlag(pOut, MEM_Null);\n        REGISTER_TRACE(pOp->p2, pOut);\n      }else{\n        VdbeBranchTaken(2,3);\n        if( pOp->p5 & SQLITE_JUMPIFNULL ){\n          goto jump_to_p2;\n        }\n      }\n      break;\n    }\n  }else{\n    /* Neither operand is NULL.  Do a comparison. */\n    affinity = pOp->p5 & SQLITE_AFF_MASK;\n    if( affinity>=SQLITE_AFF_NUMERIC ){\n      if( (flags1 | flags3)&MEM_Str ){\n        if( (flags1 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){\n          applyNumericAffinity(pIn1,0);\n          testcase( flags3==pIn3->flags );\n          flags3 = pIn3->flags;\n        }\n        if( (flags3 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){\n          applyNumericAffinity(pIn3,0);\n        }\n      }\n      /* Handle the common case of integer comparison here, as an\n      ** optimization, to avoid a call to sqlite3MemCompare() */\n      if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){\n        if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }\n        if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }\n        res = 0;\n        goto compare_op;\n      }\n    }else if( affinity==SQLITE_AFF_TEXT ){\n      if( (flags1 & MEM_Str)==0 && (flags1&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){\n        testcase( pIn1->flags & MEM_Int );\n        testcase( pIn1->flags & MEM_Real );\n        testcase( pIn1->flags & MEM_IntReal );\n        sqlite3VdbeMemStringify(pIn1, encoding, 1);\n        testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );\n        flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);\n        if( NEVER(pIn1==pIn3) ) flags3 = flags1 | MEM_Str;\n      }\n      if( (flags3 & MEM_Str)==0 && (flags3&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){\n        testcase( pIn3->flags & MEM_Int );\n        testcase( pIn3->flags & MEM_Real );\n        testcase( pIn3->flags & MEM_IntReal );\n        sqlite3VdbeMemStringify(pIn3, encoding, 1);\n        testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );\n        flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);\n      }\n    }\n    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );\n    res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);\n  }\ncompare_op:\n  /* At this point, res is negative, zero, or positive if reg[P1] is\n  ** less than, equal to, or greater than reg[P3], respectively.  Compute\n  ** the answer to this operator in res2, depending on what the comparison\n  ** operator actually is.  The next block of code depends on the fact\n  ** that the 6 comparison operators are consecutive integers in this\n  ** order:  NE, EQ, GT, LE, LT, GE */\n  assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );\n  assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );\n  if( res<0 ){                        /* ne, eq, gt, le, lt, ge */\n    static const unsigned char aLTb[] = { 1,  0,  0,  1,  1,  0 };\n    res2 = aLTb[pOp->opcode - OP_Ne];\n  }else if( res==0 ){\n    static const unsigned char aEQb[] = { 0,  1,  0,  1,  0,  1 };\n    res2 = aEQb[pOp->opcode - OP_Ne];\n  }else{\n    static const unsigned char aGTb[] = { 1,  0,  1,  0,  0,  1 };\n    res2 = aGTb[pOp->opcode - OP_Ne];\n  }\n\n  /* Undo any changes made by applyAffinity() to the input registers. */\n  assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );\n  pIn3->flags = flags3;\n  assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );\n  pIn1->flags = flags1;\n\n  if( pOp->p5 & SQLITE_STOREP2 ){\n    pOut = &aMem[pOp->p2];\n    iCompare = res;\n    if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){\n      /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1\n      ** and prevents OP_Ne from overwriting NULL with 0.  This flag\n      ** is only used in contexts where either:\n      **   (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)\n      **   (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)\n      ** Therefore it is not necessary to check the content of r[P2] for\n      ** NULL. */\n      assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );\n      assert( res2==0 || res2==1 );\n      testcase( res2==0 && pOp->opcode==OP_Eq );\n      testcase( res2==1 && pOp->opcode==OP_Eq );\n      testcase( res2==0 && pOp->opcode==OP_Ne );\n      testcase( res2==1 && pOp->opcode==OP_Ne );\n      if( (pOp->opcode==OP_Eq)==res2 ) break;\n    }\n    memAboutToChange(p, pOut);\n    MemSetTypeFlag(pOut, MEM_Int);\n    pOut->u.i = res2;\n    REGISTER_TRACE(pOp->p2, pOut);\n  }else{\n    VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);\n    if( res2 ){\n      goto jump_to_p2;\n    }\n  }\n  break;\n}\n\n/* Opcode: ElseNotEq * P2 * * *\n**\n** This opcode must follow an OP_Lt or OP_Gt comparison operator.  There\n** can be zero or more OP_ReleaseReg opcodes intervening, but no other\n** opcodes are allowed to occur between this instruction and the previous\n** OP_Lt or OP_Gt.  Furthermore, the prior OP_Lt or OP_Gt must have the\n** SQLITE_STOREP2 bit set in the P5 field.\n**\n** If result of an OP_Eq comparison on the same two operands as the\n** prior OP_Lt or OP_Gt would have been NULL or false (0), then then\n** jump to P2.  If the result of an OP_Eq comparison on the two previous\n** operands would have been true (1), then fall through.\n*/\ncase OP_ElseNotEq: {       /* same as TK_ESCAPE, jump */\n\n#ifdef SQLITE_DEBUG\n  /* Verify the preconditions of this opcode - that it follows an OP_Lt or\n  ** OP_Gt with the SQLITE_STOREP2 flag set, with zero or more intervening\n  ** OP_ReleaseReg opcodes */\n  int iAddr;\n  for(iAddr = (int)(pOp - aOp) - 1; ALWAYS(iAddr>=0); iAddr--){\n    if( aOp[iAddr].opcode==OP_ReleaseReg ) continue;\n    assert( aOp[iAddr].opcode==OP_Lt || aOp[iAddr].opcode==OP_Gt );\n    assert( aOp[iAddr].p5 & SQLITE_STOREP2 );\n    break;\n  }\n#endif /* SQLITE_DEBUG */\n  VdbeBranchTaken(iCompare!=0, 2);\n  if( iCompare!=0 ) goto jump_to_p2;\n  break;\n}\n\n\n/* Opcode: Permutation * * * P4 *\n**\n** Set the permutation used by the OP_Compare operator in the next\n** instruction.  The permutation is stored in the P4 operand.\n**\n** The permutation is only valid until the next OP_Compare that has\n** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should \n** occur immediately prior to the OP_Compare.\n**\n** The first integer in the P4 integer array is the length of the array\n** and does not become part of the permutation.\n*/\ncase OP_Permutation: {\n  assert( pOp->p4type==P4_INTARRAY );\n  assert( pOp->p4.ai );\n  assert( pOp[1].opcode==OP_Compare );\n  assert( pOp[1].p5 & OPFLAG_PERMUTE );\n  break;\n}\n\n/* Opcode: Compare P1 P2 P3 P4 P5\n** Synopsis: r[P1@P3] <-> r[P2@P3]\n**\n** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this\n** vector \"A\") and in reg(P2)..reg(P2+P3-1) (\"B\").  Save the result of\n** the comparison for use by the next OP_Jump instruct.\n**\n** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is\n** determined by the most recent OP_Permutation operator.  If the\n** OPFLAG_PERMUTE bit is clear, then register are compared in sequential\n** order.\n**\n** P4 is a KeyInfo structure that defines collating sequences and sort\n** orders for the comparison.  The permutation applies to registers\n** only.  The KeyInfo elements are used sequentially.\n**\n** The comparison is a sort comparison, so NULLs compare equal,\n** NULLs are less than numbers, numbers are less than strings,\n** and strings are less than blobs.\n*/\ncase OP_Compare: {\n  int n;\n  int i;\n  int p1;\n  int p2;\n  const KeyInfo *pKeyInfo;\n  int idx;\n  CollSeq *pColl;    /* Collating sequence to use on this term */\n  int bRev;          /* True for DESCENDING sort order */\n  int *aPermute;     /* The permutation */\n\n  if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){\n    aPermute = 0;\n  }else{\n    assert( pOp>aOp );\n    assert( pOp[-1].opcode==OP_Permutation );\n    assert( pOp[-1].p4type==P4_INTARRAY );\n    aPermute = pOp[-1].p4.ai + 1;\n    assert( aPermute!=0 );\n  }\n  n = pOp->p3;\n  pKeyInfo = pOp->p4.pKeyInfo;\n  assert( n>0 );\n  assert( pKeyInfo!=0 );\n  p1 = pOp->p1;\n  p2 = pOp->p2;\n#ifdef SQLITE_DEBUG\n  if( aPermute ){\n    int k, mx = 0;\n    for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];\n    assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );\n    assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );\n  }else{\n    assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );\n    assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );\n  }\n#endif /* SQLITE_DEBUG */\n  for(i=0; i<n; i++){\n    idx = aPermute ? aPermute[i] : i;\n    assert( memIsValid(&aMem[p1+idx]) );\n    assert( memIsValid(&aMem[p2+idx]) );\n    REGISTER_TRACE(p1+idx, &aMem[p1+idx]);\n    REGISTER_TRACE(p2+idx, &aMem[p2+idx]);\n    assert( i<pKeyInfo->nKeyField );\n    pColl = pKeyInfo->aColl[i];\n    bRev = (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC);\n    iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);\n    if( iCompare ){\n      if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) \n       && ((aMem[p1+idx].flags & MEM_Null) || (aMem[p2+idx].flags & MEM_Null))\n      ){\n        iCompare = -iCompare;\n      }\n      if( bRev ) iCompare = -iCompare;\n      break;\n    }\n  }\n  break;\n}\n\n/* Opcode: Jump P1 P2 P3 * *\n**\n** Jump to the instruction at address P1, P2, or P3 depending on whether\n** in the most recent OP_Compare instruction the P1 vector was less than\n** equal to, or greater than the P2 vector, respectively.\n*/\ncase OP_Jump: {             /* jump */\n  if( iCompare<0 ){\n    VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1];\n  }else if( iCompare==0 ){\n    VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1];\n  }else{\n    VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1];\n  }\n  break;\n}\n\n/* Opcode: And P1 P2 P3 * *\n** Synopsis: r[P3]=(r[P1] && r[P2])\n**\n** Take the logical AND of the values in registers P1 and P2 and\n** write the result into register P3.\n**\n** If either P1 or P2 is 0 (false) then the result is 0 even if\n** the other input is NULL.  A NULL and true or two NULLs give\n** a NULL output.\n*/\n/* Opcode: Or P1 P2 P3 * *\n** Synopsis: r[P3]=(r[P1] || r[P2])\n**\n** Take the logical OR of the values in register P1 and P2 and\n** store the answer in register P3.\n**\n** If either P1 or P2 is nonzero (true) then the result is 1 (true)\n** even if the other input is NULL.  A NULL and false or two NULLs\n** give a NULL output.\n*/\ncase OP_And:              /* same as TK_AND, in1, in2, out3 */\ncase OP_Or: {             /* same as TK_OR, in1, in2, out3 */\n  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */\n  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */\n\n  v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);\n  v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);\n  if( pOp->opcode==OP_And ){\n    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };\n    v1 = and_logic[v1*3+v2];\n  }else{\n    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };\n    v1 = or_logic[v1*3+v2];\n  }\n  pOut = &aMem[pOp->p3];\n  if( v1==2 ){\n    MemSetTypeFlag(pOut, MEM_Null);\n  }else{\n    pOut->u.i = v1;\n    MemSetTypeFlag(pOut, MEM_Int);\n  }\n  break;\n}\n\n/* Opcode: IsTrue P1 P2 P3 P4 *\n** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4\n**\n** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and\n** IS NOT FALSE operators.\n**\n** Interpret the value in register P1 as a boolean value.  Store that\n** boolean (a 0 or 1) in register P2.  Or if the value in register P1 is \n** NULL, then the P3 is stored in register P2.  Invert the answer if P4\n** is 1.\n**\n** The logic is summarized like this:\n**\n** <ul> \n** <li> If P3==0 and P4==0  then  r[P2] := r[P1] IS TRUE\n** <li> If P3==1 and P4==1  then  r[P2] := r[P1] IS FALSE\n** <li> If P3==0 and P4==1  then  r[P2] := r[P1] IS NOT TRUE\n** <li> If P3==1 and P4==0  then  r[P2] := r[P1] IS NOT FALSE\n** </ul>\n*/\ncase OP_IsTrue: {               /* in1, out2 */\n  assert( pOp->p4type==P4_INT32 );\n  assert( pOp->p4.i==0 || pOp->p4.i==1 );\n  assert( pOp->p3==0 || pOp->p3==1 );\n  sqlite3VdbeMemSetInt64(&aMem[pOp->p2],\n      sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);\n  break;\n}\n\n/* Opcode: Not P1 P2 * * *\n** Synopsis: r[P2]= !r[P1]\n**\n** Interpret the value in register P1 as a boolean value.  Store the\n** boolean complement in register P2.  If the value in register P1 is \n** NULL, then a NULL is stored in P2.\n*/\ncase OP_Not: {                /* same as TK_NOT, in1, out2 */\n  pIn1 = &aMem[pOp->p1];\n  pOut = &aMem[pOp->p2];\n  if( (pIn1->flags & MEM_Null)==0 ){\n    sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));\n  }else{\n    sqlite3VdbeMemSetNull(pOut);\n  }\n  break;\n}\n\n/* Opcode: BitNot P1 P2 * * *\n** Synopsis: r[P2]= ~r[P1]\n**\n** Interpret the content of register P1 as an integer.  Store the\n** ones-complement of the P1 value into register P2.  If P1 holds\n** a NULL then store a NULL in P2.\n*/\ncase OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */\n  pIn1 = &aMem[pOp->p1];\n  pOut = &aMem[pOp->p2];\n  sqlite3VdbeMemSetNull(pOut);\n  if( (pIn1->flags & MEM_Null)==0 ){\n    pOut->flags = MEM_Int;\n    pOut->u.i = ~sqlite3VdbeIntValue(pIn1);\n  }\n  break;\n}\n\n/* Opcode: Once P1 P2 * * *\n**\n** Fall through to the next instruction the first time this opcode is\n** encountered on each invocation of the byte-code program.  Jump to P2\n** on the second and all subsequent encounters during the same invocation.\n**\n** Top-level programs determine first invocation by comparing the P1\n** operand against the P1 operand on the OP_Init opcode at the beginning\n** of the program.  If the P1 values differ, then fall through and make\n** the P1 of this opcode equal to the P1 of OP_Init.  If P1 values are\n** the same then take the jump.\n**\n** For subprograms, there is a bitmask in the VdbeFrame that determines\n** whether or not the jump should be taken.  The bitmask is necessary\n** because the self-altering code trick does not work for recursive\n** triggers.\n*/\ncase OP_Once: {             /* jump */\n  u32 iAddr;                /* Address of this instruction */\n  assert( p->aOp[0].opcode==OP_Init );\n  if( p->pFrame ){\n    iAddr = (int)(pOp - p->aOp);\n    if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){\n      VdbeBranchTaken(1, 2);\n      goto jump_to_p2;\n    }\n    p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);\n  }else{\n    if( p->aOp[0].p1==pOp->p1 ){\n      VdbeBranchTaken(1, 2);\n      goto jump_to_p2;\n    }\n  }\n  VdbeBranchTaken(0, 2);\n  pOp->p1 = p->aOp[0].p1;\n  break;\n}\n\n/* Opcode: If P1 P2 P3 * *\n**\n** Jump to P2 if the value in register P1 is true.  The value\n** is considered true if it is numeric and non-zero.  If the value\n** in P1 is NULL then take the jump if and only if P3 is non-zero.\n*/\ncase OP_If:  {               /* jump, in1 */\n  int c;\n  c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);\n  VdbeBranchTaken(c!=0, 2);\n  if( c ) goto jump_to_p2;\n  break;\n}\n\n/* Opcode: IfNot P1 P2 P3 * *\n**\n** Jump to P2 if the value in register P1 is False.  The value\n** is considered false if it has a numeric value of zero.  If the value\n** in P1 is NULL then take the jump if and only if P3 is non-zero.\n*/\ncase OP_IfNot: {            /* jump, in1 */\n  int c;\n  c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);\n  VdbeBranchTaken(c!=0, 2);\n  if( c ) goto jump_to_p2;\n  break;\n}\n\n/* Opcode: IsNull P1 P2 * * *\n** Synopsis: if r[P1]==NULL goto P2\n**\n** Jump to P2 if the value in register P1 is NULL.\n*/\ncase OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */\n  pIn1 = &aMem[pOp->p1];\n  VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);\n  if( (pIn1->flags & MEM_Null)!=0 ){\n    goto jump_to_p2;\n  }\n  break;\n}\n\n/* Opcode: NotNull P1 P2 * * *\n** Synopsis: if r[P1]!=NULL goto P2\n**\n** Jump to P2 if the value in register P1 is not NULL.  \n*/\ncase OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */\n  pIn1 = &aMem[pOp->p1];\n  VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);\n  if( (pIn1->flags & MEM_Null)==0 ){\n    goto jump_to_p2;\n  }\n  break;\n}\n\n/* Opcode: IfNullRow P1 P2 P3 * *\n** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2\n**\n** Check the cursor P1 to see if it is currently pointing at a NULL row.\n** If it is, then set register P3 to NULL and jump immediately to P2.\n** If P1 is not on a NULL row, then fall through without making any\n** changes.\n*/\ncase OP_IfNullRow: {         /* jump */\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  assert( p->apCsr[pOp->p1]!=0 );\n  if( p->apCsr[pOp->p1]->nullRow ){\n    sqlite3VdbeMemSetNull(aMem + pOp->p3);\n    goto jump_to_p2;\n  }\n  break;\n}\n\n#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC\n/* Opcode: Offset P1 P2 P3 * *\n** Synopsis: r[P3] = sqlite_offset(P1)\n**\n** Store in register r[P3] the byte offset into the database file that is the\n** start of the payload for the record at which that cursor P1 is currently\n** pointing.\n**\n** P2 is the column number for the argument to the sqlite_offset() function.\n** This opcode does not use P2 itself, but the P2 value is used by the\n** code generator.  The P1, P2, and P3 operands to this opcode are the\n** same as for OP_Column.\n**\n** This opcode is only available if SQLite is compiled with the\n** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.\n*/\ncase OP_Offset: {          /* out3 */\n  VdbeCursor *pC;    /* The VDBE cursor */\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  pOut = &p->aMem[pOp->p3];\n  if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){\n    sqlite3VdbeMemSetNull(pOut);\n  }else{\n    sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));\n  }\n  break;\n}\n#endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */\n\n/* Opcode: Column P1 P2 P3 P4 P5\n** Synopsis: r[P3]=PX\n**\n** Interpret the data that cursor P1 points to as a structure built using\n** the MakeRecord instruction.  (See the MakeRecord opcode for additional\n** information about the format of the data.)  Extract the P2-th column\n** from this record.  If there are less that (P2+1) \n** values in the record, extract a NULL.\n**\n** The value extracted is stored in register P3.\n**\n** If the record contains fewer than P2 fields, then extract a NULL.  Or,\n** if the P4 argument is a P4_MEM use the value of the P4 argument as\n** the result.\n**\n** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then\n** the result is guaranteed to only be used as the argument of a length()\n** or typeof() function, respectively.  The loading of large blobs can be\n** skipped for length() and all content loading can be skipped for typeof().\n*/\ncase OP_Column: {\n  int p2;            /* column number to retrieve */\n  VdbeCursor *pC;    /* The VDBE cursor */\n  BtCursor *pCrsr;   /* The BTree cursor */\n  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */\n  int len;           /* The length of the serialized data for the column */\n  int i;             /* Loop counter */\n  Mem *pDest;        /* Where to write the extracted value */\n  Mem sMem;          /* For storing the record being decoded */\n  const u8 *zData;   /* Part of the record being decoded */\n  const u8 *zHdr;    /* Next unparsed byte of the header */\n  const u8 *zEndHdr; /* Pointer to first byte after the header */\n  u64 offset64;      /* 64-bit offset */\n  u32 t;             /* A type code from the record header */\n  Mem *pReg;         /* PseudoTable input register */\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  p2 = pOp->p2;\n\n  /* If the cursor cache is stale (meaning it is not currently point at\n  ** the correct row) then bring it up-to-date by doing the necessary \n  ** B-Tree seek. */\n  rc = sqlite3VdbeCursorMoveto(&pC, &p2);\n  if( rc ) goto abort_due_to_error;\n\n  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );\n  pDest = &aMem[pOp->p3];\n  memAboutToChange(p, pDest);\n  assert( pC!=0 );\n  assert( p2<pC->nField );\n  aOffset = pC->aOffset;\n  assert( pC->eCurType!=CURTYPE_VTAB );\n  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );\n  assert( pC->eCurType!=CURTYPE_SORTER );\n\n  if( pC->cacheStatus!=p->cacheCtr ){                /*OPTIMIZATION-IF-FALSE*/\n    if( pC->nullRow ){\n      if( pC->eCurType==CURTYPE_PSEUDO ){\n        /* For the special case of as pseudo-cursor, the seekResult field\n        ** identifies the register that holds the record */\n        assert( pC->seekResult>0 );\n        pReg = &aMem[pC->seekResult];\n        assert( pReg->flags & MEM_Blob );\n        assert( memIsValid(pReg) );\n        pC->payloadSize = pC->szRow = pReg->n;\n        pC->aRow = (u8*)pReg->z;\n      }else{\n        sqlite3VdbeMemSetNull(pDest);\n        goto op_column_out;\n      }\n    }else{\n      pCrsr = pC->uc.pCursor;\n      assert( pC->eCurType==CURTYPE_BTREE );\n      assert( pCrsr );\n      assert( sqlite3BtreeCursorIsValid(pCrsr) );\n      pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);\n      pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);\n      assert( pC->szRow<=pC->payloadSize );\n      assert( pC->szRow<=65536 );  /* Maximum page size is 64KiB */\n      if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){\n        goto too_big;\n      }\n    }\n    pC->cacheStatus = p->cacheCtr;\n    pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);\n    pC->nHdrParsed = 0;\n\n\n    if( pC->szRow<aOffset[0] ){      /*OPTIMIZATION-IF-FALSE*/\n      /* pC->aRow does not have to hold the entire row, but it does at least\n      ** need to cover the header of the record.  If pC->aRow does not contain\n      ** the complete header, then set it to zero, forcing the header to be\n      ** dynamically allocated. */\n      pC->aRow = 0;\n      pC->szRow = 0;\n\n      /* Make sure a corrupt database has not given us an oversize header.\n      ** Do this now to avoid an oversize memory allocation.\n      **\n      ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte\n      ** types use so much data space that there can only be 4096 and 32 of\n      ** them, respectively.  So the maximum header length results from a\n      ** 3-byte type for each of the maximum of 32768 columns plus three\n      ** extra bytes for the header length itself.  32768*3 + 3 = 98307.\n      */\n      if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){\n        goto op_column_corrupt;\n      }\n    }else{\n      /* This is an optimization.  By skipping over the first few tests\n      ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a\n      ** measurable performance gain.\n      **\n      ** This branch is taken even if aOffset[0]==0.  Such a record is never\n      ** generated by SQLite, and could be considered corruption, but we\n      ** accept it for historical reasons.  When aOffset[0]==0, the code this\n      ** branch jumps to reads past the end of the record, but never more\n      ** than a few bytes.  Even if the record occurs at the end of the page\n      ** content area, the \"page header\" comes after the page content and so\n      ** this overread is harmless.  Similar overreads can occur for a corrupt\n      ** database file.\n      */\n      zData = pC->aRow;\n      assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */\n      testcase( aOffset[0]==0 );\n      goto op_column_read_header;\n    }\n  }\n\n  /* Make sure at least the first p2+1 entries of the header have been\n  ** parsed and valid information is in aOffset[] and pC->aType[].\n  */\n  if( pC->nHdrParsed<=p2 ){\n    /* If there is more header available for parsing in the record, try\n    ** to extract additional fields up through the p2+1-th field \n    */\n    if( pC->iHdrOffset<aOffset[0] ){\n      /* Make sure zData points to enough of the record to cover the header. */\n      if( pC->aRow==0 ){\n        memset(&sMem, 0, sizeof(sMem));\n        rc = sqlite3VdbeMemFromBtreeZeroOffset(pC->uc.pCursor,aOffset[0],&sMem);\n        if( rc!=SQLITE_OK ) goto abort_due_to_error;\n        zData = (u8*)sMem.z;\n      }else{\n        zData = pC->aRow;\n      }\n  \n      /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */\n    op_column_read_header:\n      i = pC->nHdrParsed;\n      offset64 = aOffset[i];\n      zHdr = zData + pC->iHdrOffset;\n      zEndHdr = zData + aOffset[0];\n      testcase( zHdr>=zEndHdr );\n      do{\n        if( (pC->aType[i] = t = zHdr[0])<0x80 ){\n          zHdr++;\n          offset64 += sqlite3VdbeOneByteSerialTypeLen(t);\n        }else{\n          zHdr += sqlite3GetVarint32(zHdr, &t);\n          pC->aType[i] = t;\n          offset64 += sqlite3VdbeSerialTypeLen(t);\n        }\n        aOffset[++i] = (u32)(offset64 & 0xffffffff);\n      }while( i<=p2 && zHdr<zEndHdr );\n\n      /* The record is corrupt if any of the following are true:\n      ** (1) the bytes of the header extend past the declared header size\n      ** (2) the entire header was used but not all data was used\n      ** (3) the end of the data extends beyond the end of the record.\n      */\n      if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))\n       || (offset64 > pC->payloadSize)\n      ){\n        if( aOffset[0]==0 ){\n          i = 0;\n          zHdr = zEndHdr;\n        }else{\n          if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);\n          goto op_column_corrupt;\n        }\n      }\n\n      pC->nHdrParsed = i;\n      pC->iHdrOffset = (u32)(zHdr - zData);\n      if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);\n    }else{\n      t = 0;\n    }\n\n    /* If after trying to extract new entries from the header, nHdrParsed is\n    ** still not up to p2, that means that the record has fewer than p2\n    ** columns.  So the result will be either the default value or a NULL.\n    */\n    if( pC->nHdrParsed<=p2 ){\n      if( pOp->p4type==P4_MEM ){\n        sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);\n      }else{\n        sqlite3VdbeMemSetNull(pDest);\n      }\n      goto op_column_out;\n    }\n  }else{\n    t = pC->aType[p2];\n  }\n\n  /* Extract the content for the p2+1-th column.  Control can only\n  ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are\n  ** all valid.\n  */\n  assert( p2<pC->nHdrParsed );\n  assert( rc==SQLITE_OK );\n  assert( sqlite3VdbeCheckMemInvariants(pDest) );\n  if( VdbeMemDynamic(pDest) ){\n    sqlite3VdbeMemSetNull(pDest);\n  }\n  assert( t==pC->aType[p2] );\n  if( pC->szRow>=aOffset[p2+1] ){\n    /* This is the common case where the desired content fits on the original\n    ** page - where the content is not on an overflow page */\n    zData = pC->aRow + aOffset[p2];\n    if( t<12 ){\n      sqlite3VdbeSerialGet(zData, t, pDest);\n    }else{\n      /* If the column value is a string, we need a persistent value, not\n      ** a MEM_Ephem value.  This branch is a fast short-cut that is equivalent\n      ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().\n      */\n      static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };\n      pDest->n = len = (t-12)/2;\n      pDest->enc = encoding;\n      if( pDest->szMalloc < len+2 ){\n        pDest->flags = MEM_Null;\n        if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;\n      }else{\n        pDest->z = pDest->zMalloc;\n      }\n      memcpy(pDest->z, zData, len);\n      pDest->z[len] = 0;\n      pDest->z[len+1] = 0;\n      pDest->flags = aFlag[t&1];\n    }\n  }else{\n    pDest->enc = encoding;\n    /* This branch happens only when content is on overflow pages */\n    if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0\n          && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))\n     || (len = sqlite3VdbeSerialTypeLen(t))==0\n    ){\n      /* Content is irrelevant for\n      **    1. the typeof() function,\n      **    2. the length(X) function if X is a blob, and\n      **    3. if the content length is zero.\n      ** So we might as well use bogus content rather than reading\n      ** content from disk. \n      **\n      ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the\n      ** buffer passed to it, debugging function VdbeMemPrettyPrint() may\n      ** read more.  Use the global constant sqlite3CtypeMap[] as the array,\n      ** as that array is 256 bytes long (plenty for VdbeMemPrettyPrint())\n      ** and it begins with a bunch of zeros.\n      */\n      sqlite3VdbeSerialGet((u8*)sqlite3CtypeMap, t, pDest);\n    }else{\n      rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);\n      if( rc!=SQLITE_OK ) goto abort_due_to_error;\n      sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);\n      pDest->flags &= ~MEM_Ephem;\n    }\n  }\n\nop_column_out:\n  UPDATE_MAX_BLOBSIZE(pDest);\n  REGISTER_TRACE(pOp->p3, pDest);\n  break;\n\nop_column_corrupt:\n  if( aOp[0].p3>0 ){\n    pOp = &aOp[aOp[0].p3-1];\n    break;\n  }else{\n    rc = SQLITE_CORRUPT_BKPT;\n    goto abort_due_to_error;\n  }\n}\n\n/* Opcode: Affinity P1 P2 * P4 *\n** Synopsis: affinity(r[P1@P2])\n**\n** Apply affinities to a range of P2 registers starting with P1.\n**\n** P4 is a string that is P2 characters long. The N-th character of the\n** string indicates the column affinity that should be used for the N-th\n** memory cell in the range.\n*/\ncase OP_Affinity: {\n  const char *zAffinity;   /* The affinity to be applied */\n\n  zAffinity = pOp->p4.z;\n  assert( zAffinity!=0 );\n  assert( pOp->p2>0 );\n  assert( zAffinity[pOp->p2]==0 );\n  pIn1 = &aMem[pOp->p1];\n  while( 1 /*exit-by-break*/ ){\n    assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );\n    assert( zAffinity[0]==SQLITE_AFF_NONE || memIsValid(pIn1) );\n    applyAffinity(pIn1, zAffinity[0], encoding);\n    if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){\n      /* When applying REAL affinity, if the result is still an MEM_Int\n      ** that will fit in 6 bytes, then change the type to MEM_IntReal\n      ** so that we keep the high-resolution integer value but know that\n      ** the type really wants to be REAL. */\n      testcase( pIn1->u.i==140737488355328LL );\n      testcase( pIn1->u.i==140737488355327LL );\n      testcase( pIn1->u.i==-140737488355328LL );\n      testcase( pIn1->u.i==-140737488355329LL );\n      if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){\n        pIn1->flags |= MEM_IntReal;\n        pIn1->flags &= ~MEM_Int;\n      }else{\n        pIn1->u.r = (double)pIn1->u.i;\n        pIn1->flags |= MEM_Real;\n        pIn1->flags &= ~MEM_Int;\n      }\n    }\n    REGISTER_TRACE((int)(pIn1-aMem), pIn1);\n    zAffinity++;\n    if( zAffinity[0]==0 ) break;\n    pIn1++;\n  }\n  break;\n}\n\n/* Opcode: MakeRecord P1 P2 P3 P4 *\n** Synopsis: r[P3]=mkrec(r[P1@P2])\n**\n** Convert P2 registers beginning with P1 into the [record format]\n** use as a data record in a database table or as a key\n** in an index.  The OP_Column opcode can decode the record later.\n**\n** P4 may be a string that is P2 characters long.  The N-th character of the\n** string indicates the column affinity that should be used for the N-th\n** field of the index key.\n**\n** The mapping from character to affinity is given by the SQLITE_AFF_\n** macros defined in sqliteInt.h.\n**\n** If P4 is NULL then all index fields have the affinity BLOB.\n*/\ncase OP_MakeRecord: {\n  Mem *pRec;             /* The new record */\n  u64 nData;             /* Number of bytes of data space */\n  int nHdr;              /* Number of bytes of header space */\n  i64 nByte;             /* Data space required for this record */\n  i64 nZero;             /* Number of zero bytes at the end of the record */\n  int nVarint;           /* Number of bytes in a varint */\n  u32 serial_type;       /* Type field */\n  Mem *pData0;           /* First field to be combined into the record */\n  Mem *pLast;            /* Last field of the record */\n  int nField;            /* Number of fields in the record */\n  char *zAffinity;       /* The affinity string for the record */\n  int file_format;       /* File format to use for encoding */\n  u32 len;               /* Length of a field */\n  u8 *zHdr;              /* Where to write next byte of the header */\n  u8 *zPayload;          /* Where to write next byte of the payload */\n\n  /* Assuming the record contains N fields, the record format looks\n  ** like this:\n  **\n  ** ------------------------------------------------------------------------\n  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | \n  ** ------------------------------------------------------------------------\n  **\n  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1\n  ** and so forth.\n  **\n  ** Each type field is a varint representing the serial type of the \n  ** corresponding data element (see sqlite3VdbeSerialType()). The\n  ** hdr-size field is also a varint which is the offset from the beginning\n  ** of the record to data0.\n  */\n  nData = 0;         /* Number of bytes of data space */\n  nHdr = 0;          /* Number of bytes of header space */\n  nZero = 0;         /* Number of zero bytes at the end of the record */\n  nField = pOp->p1;\n  zAffinity = pOp->p4.z;\n  assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );\n  pData0 = &aMem[nField];\n  nField = pOp->p2;\n  pLast = &pData0[nField-1];\n  file_format = p->minWriteFileFormat;\n\n  /* Identify the output register */\n  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );\n  pOut = &aMem[pOp->p3];\n  memAboutToChange(p, pOut);\n\n  /* Apply the requested affinity to all inputs\n  */\n  assert( pData0<=pLast );\n  if( zAffinity ){\n    pRec = pData0;\n    do{\n      applyAffinity(pRec, zAffinity[0], encoding);\n      if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){\n        pRec->flags |= MEM_IntReal;\n        pRec->flags &= ~(MEM_Int);\n      }\n      REGISTER_TRACE((int)(pRec-aMem), pRec);\n      zAffinity++;\n      pRec++;\n      assert( zAffinity[0]==0 || pRec<=pLast );\n    }while( zAffinity[0] );\n  }\n\n#ifdef SQLITE_ENABLE_NULL_TRIM\n  /* NULLs can be safely trimmed from the end of the record, as long as\n  ** as the schema format is 2 or more and none of the omitted columns\n  ** have a non-NULL default value.  Also, the record must be left with\n  ** at least one field.  If P5>0 then it will be one more than the\n  ** index of the right-most column with a non-NULL default value */\n  if( pOp->p5 ){\n    while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){\n      pLast--;\n      nField--;\n    }\n  }\n#endif\n\n  /* Loop through the elements that will make up the record to figure\n  ** out how much space is required for the new record.  After this loop,\n  ** the Mem.uTemp field of each term should hold the serial-type that will\n  ** be used for that term in the generated record:\n  **\n  **   Mem.uTemp value    type\n  **   ---------------    ---------------\n  **      0               NULL\n  **      1               1-byte signed integer\n  **      2               2-byte signed integer\n  **      3               3-byte signed integer\n  **      4               4-byte signed integer\n  **      5               6-byte signed integer\n  **      6               8-byte signed integer\n  **      7               IEEE float\n  **      8               Integer constant 0\n  **      9               Integer constant 1\n  **     10,11            reserved for expansion\n  **    N>=12 and even    BLOB\n  **    N>=13 and odd     text\n  **\n  ** The following additional values are computed:\n  **     nHdr        Number of bytes needed for the record header\n  **     nData       Number of bytes of data space needed for the record\n  **     nZero       Zero bytes at the end of the record\n  */\n  pRec = pLast;\n  do{\n    assert( memIsValid(pRec) );\n    if( pRec->flags & MEM_Null ){\n      if( pRec->flags & MEM_Zero ){\n        /* Values with MEM_Null and MEM_Zero are created by xColumn virtual\n        ** table methods that never invoke sqlite3_result_xxxxx() while\n        ** computing an unchanging column value in an UPDATE statement.\n        ** Give such values a special internal-use-only serial-type of 10\n        ** so that they can be passed through to xUpdate and have\n        ** a true sqlite3_value_nochange(). */\n        assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );\n        pRec->uTemp = 10;\n      }else{\n        pRec->uTemp = 0;\n      }\n      nHdr++;\n    }else if( pRec->flags & (MEM_Int|MEM_IntReal) ){\n      /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */\n      i64 i = pRec->u.i;\n      u64 uu;\n      testcase( pRec->flags & MEM_Int );\n      testcase( pRec->flags & MEM_IntReal );\n      if( i<0 ){\n        uu = ~i;\n      }else{\n        uu = i;\n      }\n      nHdr++;\n      testcase( uu==127 );               testcase( uu==128 );\n      testcase( uu==32767 );             testcase( uu==32768 );\n      testcase( uu==8388607 );           testcase( uu==8388608 );\n      testcase( uu==2147483647 );        testcase( uu==2147483648 );\n      testcase( uu==140737488355327LL ); testcase( uu==140737488355328LL );\n      if( uu<=127 ){\n        if( (i&1)==i && file_format>=4 ){\n          pRec->uTemp = 8+(u32)uu;\n        }else{\n          nData++;\n          pRec->uTemp = 1;\n        }\n      }else if( uu<=32767 ){\n        nData += 2;\n        pRec->uTemp = 2;\n      }else if( uu<=8388607 ){\n        nData += 3;\n        pRec->uTemp = 3;\n      }else if( uu<=2147483647 ){\n        nData += 4;\n        pRec->uTemp = 4;\n      }else if( uu<=140737488355327LL ){\n        nData += 6;\n        pRec->uTemp = 5;\n      }else{\n        nData += 8;\n        if( pRec->flags & MEM_IntReal ){\n          /* If the value is IntReal and is going to take up 8 bytes to store\n          ** as an integer, then we might as well make it an 8-byte floating\n          ** point value */\n          pRec->u.r = (double)pRec->u.i;\n          pRec->flags &= ~MEM_IntReal;\n          pRec->flags |= MEM_Real;\n          pRec->uTemp = 7;\n        }else{\n          pRec->uTemp = 6;\n        }\n      }\n    }else if( pRec->flags & MEM_Real ){\n      nHdr++;\n      nData += 8;\n      pRec->uTemp = 7;\n    }else{\n      assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) );\n      assert( pRec->n>=0 );\n      len = (u32)pRec->n;\n      serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);\n      if( pRec->flags & MEM_Zero ){\n        serial_type += pRec->u.nZero*2;\n        if( nData ){\n          if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;\n          len += pRec->u.nZero;\n        }else{\n          nZero += pRec->u.nZero;\n        }\n      }\n      nData += len;\n      nHdr += sqlite3VarintLen(serial_type);\n      pRec->uTemp = serial_type;\n    }\n    if( pRec==pData0 ) break;\n    pRec--;\n  }while(1);\n\n  /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint\n  ** which determines the total number of bytes in the header. The varint\n  ** value is the size of the header in bytes including the size varint\n  ** itself. */\n  testcase( nHdr==126 );\n  testcase( nHdr==127 );\n  if( nHdr<=126 ){\n    /* The common case */\n    nHdr += 1;\n  }else{\n    /* Rare case of a really large header */\n    nVarint = sqlite3VarintLen(nHdr);\n    nHdr += nVarint;\n    if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;\n  }\n  nByte = nHdr+nData;\n\n  /* Make sure the output register has a buffer large enough to store \n  ** the new record. The output register (pOp->p3) is not allowed to\n  ** be one of the input registers (because the following call to\n  ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).\n  */\n  if( nByte+nZero<=pOut->szMalloc ){\n    /* The output register is already large enough to hold the record.\n    ** No error checks or buffer enlargement is required */\n    pOut->z = pOut->zMalloc;\n  }else{\n    /* Need to make sure that the output is not too big and then enlarge\n    ** the output register to hold the full result */\n    if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){\n      goto too_big;\n    }\n    if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){\n      goto no_mem;\n    }\n  }\n  pOut->n = (int)nByte;\n  pOut->flags = MEM_Blob;\n  if( nZero ){\n    pOut->u.nZero = nZero;\n    pOut->flags |= MEM_Zero;\n  }\n  UPDATE_MAX_BLOBSIZE(pOut);\n  zHdr = (u8 *)pOut->z;\n  zPayload = zHdr + nHdr;\n\n  /* Write the record */\n  zHdr += putVarint32(zHdr, nHdr);\n  assert( pData0<=pLast );\n  pRec = pData0;\n  do{\n    serial_type = pRec->uTemp;\n    /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more\n    ** additional varints, one per column. */\n    zHdr += putVarint32(zHdr, serial_type);            /* serial type */\n    /* EVIDENCE-OF: R-64536-51728 The values for each column in the record\n    ** immediately follow the header. */\n    zPayload += sqlite3VdbeSerialPut(zPayload, pRec, serial_type); /* content */\n  }while( (++pRec)<=pLast );\n  assert( nHdr==(int)(zHdr - (u8*)pOut->z) );\n  assert( nByte==(int)(zPayload - (u8*)pOut->z) );\n\n  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );\n  REGISTER_TRACE(pOp->p3, pOut);\n  break;\n}\n\n/* Opcode: Count P1 P2 p3 * *\n** Synopsis: r[P2]=count()\n**\n** Store the number of entries (an integer value) in the table or index \n** opened by cursor P1 in register P2.\n**\n** If P3==0, then an exact count is obtained, which involves visiting\n** every btree page of the table.  But if P3 is non-zero, an estimate\n** is returned based on the current cursor position.  \n*/\ncase OP_Count: {         /* out2 */\n  i64 nEntry;\n  BtCursor *pCrsr;\n\n  assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );\n  pCrsr = p->apCsr[pOp->p1]->uc.pCursor;\n  assert( pCrsr );\n  if( pOp->p3 ){\n    nEntry = sqlite3BtreeRowCountEst(pCrsr);\n  }else{\n    nEntry = 0;  /* Not needed.  Only used to silence a warning. */\n    rc = sqlite3BtreeCount(db, pCrsr, &nEntry);\n    if( rc ) goto abort_due_to_error;\n  }\n  pOut = out2Prerelease(p, pOp);\n  pOut->u.i = nEntry;\n  goto check_for_interrupt;\n}\n\n/* Opcode: Savepoint P1 * * P4 *\n**\n** Open, release or rollback the savepoint named by parameter P4, depending\n** on the value of P1. To open a new savepoint set P1==0 (SAVEPOINT_BEGIN).\n** To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE).\n** To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK).\n*/\ncase OP_Savepoint: {\n  int p1;                         /* Value of P1 operand */\n  char *zName;                    /* Name of savepoint */\n  int nName;\n  Savepoint *pNew;\n  Savepoint *pSavepoint;\n  Savepoint *pTmp;\n  int iSavepoint;\n  int ii;\n\n  p1 = pOp->p1;\n  zName = pOp->p4.z;\n\n  /* Assert that the p1 parameter is valid. Also that if there is no open\n  ** transaction, then there cannot be any savepoints. \n  */\n  assert( db->pSavepoint==0 || db->autoCommit==0 );\n  assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );\n  assert( db->pSavepoint || db->isTransactionSavepoint==0 );\n  assert( checkSavepointCount(db) );\n  assert( p->bIsReader );\n\n  if( p1==SAVEPOINT_BEGIN ){\n    if( db->nVdbeWrite>0 ){\n      /* A new savepoint cannot be created if there are active write \n      ** statements (i.e. open read/write incremental blob handles).\n      */\n      sqlite3VdbeError(p, \"cannot open savepoint - SQL statements in progress\");\n      rc = SQLITE_BUSY;\n    }else{\n      nName = sqlite3Strlen30(zName);\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n      /* This call is Ok even if this savepoint is actually a transaction\n      ** savepoint (and therefore should not prompt xSavepoint()) callbacks.\n      ** If this is a transaction savepoint being opened, it is guaranteed\n      ** that the db->aVTrans[] array is empty.  */\n      assert( db->autoCommit==0 || db->nVTrans==0 );\n      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,\n                                db->nStatement+db->nSavepoint);\n      if( rc!=SQLITE_OK ) goto abort_due_to_error;\n#endif\n\n      /* Create a new savepoint structure. */\n      pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);\n      if( pNew ){\n        pNew->zName = (char *)&pNew[1];\n        memcpy(pNew->zName, zName, nName+1);\n    \n        /* If there is no open transaction, then mark this as a special\n        ** \"transaction savepoint\". */\n        if( db->autoCommit ){\n          db->autoCommit = 0;\n          db->isTransactionSavepoint = 1;\n        }else{\n          db->nSavepoint++;\n        }\n\n        /* Link the new savepoint into the database handle's list. */\n        pNew->pNext = db->pSavepoint;\n        db->pSavepoint = pNew;\n        pNew->nDeferredCons = db->nDeferredCons;\n        pNew->nDeferredImmCons = db->nDeferredImmCons;\n      }\n    }\n  }else{\n    assert( p1==SAVEPOINT_RELEASE || p1==SAVEPOINT_ROLLBACK );\n    iSavepoint = 0;\n\n    /* Find the named savepoint. If there is no such savepoint, then an\n    ** an error is returned to the user.  */\n    for(\n      pSavepoint = db->pSavepoint; \n      pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);\n      pSavepoint = pSavepoint->pNext\n    ){\n      iSavepoint++;\n    }\n    if( !pSavepoint ){\n      sqlite3VdbeError(p, \"no such savepoint: %s\", zName);\n      rc = SQLITE_ERROR;\n    }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){\n      /* It is not possible to release (commit) a savepoint if there are \n      ** active write statements.\n      */\n      sqlite3VdbeError(p, \"cannot release savepoint - \"\n                          \"SQL statements in progress\");\n      rc = SQLITE_BUSY;\n    }else{\n\n      /* Determine whether or not this is a transaction savepoint. If so,\n      ** and this is a RELEASE command, then the current transaction \n      ** is committed. \n      */\n      int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;\n      if( isTransaction && p1==SAVEPOINT_RELEASE ){\n        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){\n          goto vdbe_return;\n        }\n        db->autoCommit = 1;\n        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){\n          p->pc = (int)(pOp - aOp);\n          db->autoCommit = 0;\n          p->rc = rc = SQLITE_BUSY;\n          goto vdbe_return;\n        }\n        rc = p->rc;\n        if( rc ){\n          db->autoCommit = 0;\n        }else{\n          db->isTransactionSavepoint = 0;\n        }\n      }else{\n        int isSchemaChange;\n        iSavepoint = db->nSavepoint - iSavepoint - 1;\n        if( p1==SAVEPOINT_ROLLBACK ){\n          isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;\n          for(ii=0; ii<db->nDb; ii++){\n            rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,\n                                       SQLITE_ABORT_ROLLBACK,\n                                       isSchemaChange==0);\n            if( rc!=SQLITE_OK ) goto abort_due_to_error;\n          }\n        }else{\n          assert( p1==SAVEPOINT_RELEASE );\n          isSchemaChange = 0;\n        }\n        for(ii=0; ii<db->nDb; ii++){\n          rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);\n          if( rc!=SQLITE_OK ){\n            goto abort_due_to_error;\n          }\n        }\n        if( isSchemaChange ){\n          sqlite3ExpirePreparedStatements(db, 0);\n          sqlite3ResetAllSchemasOfConnection(db);\n          db->mDbFlags |= DBFLAG_SchemaChange;\n        }\n      }\n      if( rc ) goto abort_due_to_error;\n  \n      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all \n      ** savepoints nested inside of the savepoint being operated on. */\n      while( db->pSavepoint!=pSavepoint ){\n        pTmp = db->pSavepoint;\n        db->pSavepoint = pTmp->pNext;\n        sqlite3DbFree(db, pTmp);\n        db->nSavepoint--;\n      }\n\n      /* If it is a RELEASE, then destroy the savepoint being operated on \n      ** too. If it is a ROLLBACK TO, then set the number of deferred \n      ** constraint violations present in the database to the value stored\n      ** when the savepoint was created.  */\n      if( p1==SAVEPOINT_RELEASE ){\n        assert( pSavepoint==db->pSavepoint );\n        db->pSavepoint = pSavepoint->pNext;\n        sqlite3DbFree(db, pSavepoint);\n        if( !isTransaction ){\n          db->nSavepoint--;\n        }\n      }else{\n        assert( p1==SAVEPOINT_ROLLBACK );\n        db->nDeferredCons = pSavepoint->nDeferredCons;\n        db->nDeferredImmCons = pSavepoint->nDeferredImmCons;\n      }\n\n      if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){\n        rc = sqlite3VtabSavepoint(db, p1, iSavepoint);\n        if( rc!=SQLITE_OK ) goto abort_due_to_error;\n      }\n    }\n  }\n  if( rc ) goto abort_due_to_error;\n\n  break;\n}\n\n/* Opcode: AutoCommit P1 P2 * * *\n**\n** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll\n** back any currently active btree transactions. If there are any active\n** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if\n** there are active writing VMs or active VMs that use shared cache.\n**\n** This instruction causes the VM to halt.\n*/\ncase OP_AutoCommit: {\n  int desiredAutoCommit;\n  int iRollback;\n\n  desiredAutoCommit = pOp->p1;\n  iRollback = pOp->p2;\n  assert( desiredAutoCommit==1 || desiredAutoCommit==0 );\n  assert( desiredAutoCommit==1 || iRollback==0 );\n  assert( db->nVdbeActive>0 );  /* At least this one VM is active */\n  assert( p->bIsReader );\n\n  if( desiredAutoCommit!=db->autoCommit ){\n    if( iRollback ){\n      assert( desiredAutoCommit==1 );\n      sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);\n      db->autoCommit = 1;\n    }else if( desiredAutoCommit && db->nVdbeWrite>0 ){\n      /* If this instruction implements a COMMIT and other VMs are writing\n      ** return an error indicating that the other VMs must complete first. \n      */\n      sqlite3VdbeError(p, \"cannot commit transaction - \"\n                          \"SQL statements in progress\");\n      rc = SQLITE_BUSY;\n      goto abort_due_to_error;\n    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){\n      goto vdbe_return;\n    }else{\n      db->autoCommit = (u8)desiredAutoCommit;\n    }\n    if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){\n      p->pc = (int)(pOp - aOp);\n      db->autoCommit = (u8)(1-desiredAutoCommit);\n      p->rc = rc = SQLITE_BUSY;\n      goto vdbe_return;\n    }\n    sqlite3CloseSavepoints(db);\n    if( p->rc==SQLITE_OK ){\n      rc = SQLITE_DONE;\n    }else{\n      rc = SQLITE_ERROR;\n    }\n    goto vdbe_return;\n  }else{\n    sqlite3VdbeError(p,\n        (!desiredAutoCommit)?\"cannot start a transaction within a transaction\":(\n        (iRollback)?\"cannot rollback - no transaction is active\":\n                   \"cannot commit - no transaction is active\"));\n         \n    rc = SQLITE_ERROR;\n    goto abort_due_to_error;\n  }\n  /*NOTREACHED*/ assert(0);\n}\n\n/* Opcode: Transaction P1 P2 P3 P4 P5\n**\n** Begin a transaction on database P1 if a transaction is not already\n** active.\n** If P2 is non-zero, then a write-transaction is started, or if a \n** read-transaction is already active, it is upgraded to a write-transaction.\n** If P2 is zero, then a read-transaction is started.\n**\n** P1 is the index of the database file on which the transaction is\n** started.  Index 0 is the main database file and index 1 is the\n** file used for temporary tables.  Indices of 2 or more are used for\n** attached databases.\n**\n** If a write-transaction is started and the Vdbe.usesStmtJournal flag is\n** true (this flag is set if the Vdbe may modify more than one row and may\n** throw an ABORT exception), a statement transaction may also be opened.\n** More specifically, a statement transaction is opened iff the database\n** connection is currently not in autocommit mode, or if there are other\n** active statements. A statement transaction allows the changes made by this\n** VDBE to be rolled back after an error without having to roll back the\n** entire transaction. If no error is encountered, the statement transaction\n** will automatically commit when the VDBE halts.\n**\n** If P5!=0 then this opcode also checks the schema cookie against P3\n** and the schema generation counter against P4.\n** The cookie changes its value whenever the database schema changes.\n** This operation is used to detect when that the cookie has changed\n** and that the current process needs to reread the schema.  If the schema\n** cookie in P3 differs from the schema cookie in the database header or\n** if the schema generation counter in P4 differs from the current\n** generation counter, then an SQLITE_SCHEMA error is raised and execution\n** halts.  The sqlite3_step() wrapper function might then reprepare the\n** statement and rerun it from the beginning.\n*/\ncase OP_Transaction: {\n  Btree *pBt;\n  int iMeta = 0;\n\n  assert( p->bIsReader );\n  assert( p->readOnly==0 || pOp->p2==0 );\n  assert( pOp->p1>=0 && pOp->p1<db->nDb );\n  assert( DbMaskTest(p->btreeMask, pOp->p1) );\n  if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){\n    rc = SQLITE_READONLY;\n    goto abort_due_to_error;\n  }\n  pBt = db->aDb[pOp->p1].pBt;\n\n  if( pBt ){\n    rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);\n    testcase( rc==SQLITE_BUSY_SNAPSHOT );\n    testcase( rc==SQLITE_BUSY_RECOVERY );\n    if( rc!=SQLITE_OK ){\n      if( (rc&0xff)==SQLITE_BUSY ){\n        p->pc = (int)(pOp - aOp);\n        p->rc = rc;\n        goto vdbe_return;\n      }\n      goto abort_due_to_error;\n    }\n\n    if( p->usesStmtJournal\n     && pOp->p2\n     && (db->autoCommit==0 || db->nVdbeRead>1) \n    ){\n      assert( sqlite3BtreeIsInTrans(pBt) );\n      if( p->iStatement==0 ){\n        assert( db->nStatement>=0 && db->nSavepoint>=0 );\n        db->nStatement++; \n        p->iStatement = db->nSavepoint + db->nStatement;\n      }\n\n      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);\n      if( rc==SQLITE_OK ){\n        rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);\n      }\n\n      /* Store the current value of the database handles deferred constraint\n      ** counter. If the statement transaction needs to be rolled back,\n      ** the value of this counter needs to be restored too.  */\n      p->nStmtDefCons = db->nDeferredCons;\n      p->nStmtDefImmCons = db->nDeferredImmCons;\n    }\n  }\n  assert( pOp->p5==0 || pOp->p4type==P4_INT32 );\n  if( pOp->p5\n   && (iMeta!=pOp->p3\n      || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i)\n  ){\n    /*\n    ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema\n    ** version is checked to ensure that the schema has not changed since the\n    ** SQL statement was prepared.\n    */\n    sqlite3DbFree(db, p->zErrMsg);\n    p->zErrMsg = sqlite3DbStrDup(db, \"database schema has changed\");\n    /* If the schema-cookie from the database file matches the cookie \n    ** stored with the in-memory representation of the schema, do\n    ** not reload the schema from the database file.\n    **\n    ** If virtual-tables are in use, this is not just an optimization.\n    ** Often, v-tables store their data in other SQLite tables, which\n    ** are queried from within xNext() and other v-table methods using\n    ** prepared queries. If such a query is out-of-date, we do not want to\n    ** discard the database schema, as the user code implementing the\n    ** v-table would have to be ready for the sqlite3_vtab structure itself\n    ** to be invalidated whenever sqlite3_step() is called from within \n    ** a v-table method.\n    */\n    if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){\n      sqlite3ResetOneSchema(db, pOp->p1);\n    }\n    p->expired = 1;\n    rc = SQLITE_SCHEMA;\n  }\n  if( rc ) goto abort_due_to_error;\n  break;\n}\n\n/* Opcode: ReadCookie P1 P2 P3 * *\n**\n** Read cookie number P3 from database P1 and write it into register P2.\n** P3==1 is the schema version.  P3==2 is the database format.\n** P3==3 is the recommended pager cache size, and so forth.  P1==0 is\n** the main database file and P1==1 is the database file used to store\n** temporary tables.\n**\n** There must be a read-lock on the database (either a transaction\n** must be started or there must be an open cursor) before\n** executing this instruction.\n*/\ncase OP_ReadCookie: {               /* out2 */\n  int iMeta;\n  int iDb;\n  int iCookie;\n\n  assert( p->bIsReader );\n  iDb = pOp->p1;\n  iCookie = pOp->p3;\n  assert( pOp->p3<SQLITE_N_BTREE_META );\n  assert( iDb>=0 && iDb<db->nDb );\n  assert( db->aDb[iDb].pBt!=0 );\n  assert( DbMaskTest(p->btreeMask, iDb) );\n\n  sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);\n  pOut = out2Prerelease(p, pOp);\n  pOut->u.i = iMeta;\n  break;\n}\n\n/* Opcode: SetCookie P1 P2 P3 * *\n**\n** Write the integer value P3 into cookie number P2 of database P1.\n** P2==1 is the schema version.  P2==2 is the database format.\n** P2==3 is the recommended pager cache \n** size, and so forth.  P1==0 is the main database file and P1==1 is the \n** database file used to store temporary tables.\n**\n** A transaction must be started before executing this opcode.\n*/\ncase OP_SetCookie: {\n  Db *pDb;\n\n  sqlite3VdbeIncrWriteCounter(p, 0);\n  assert( pOp->p2<SQLITE_N_BTREE_META );\n  assert( pOp->p1>=0 && pOp->p1<db->nDb );\n  assert( DbMaskTest(p->btreeMask, pOp->p1) );\n  assert( p->readOnly==0 );\n  pDb = &db->aDb[pOp->p1];\n  assert( pDb->pBt!=0 );\n  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );\n  /* See note about index shifting on OP_ReadCookie */\n  rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);\n  if( pOp->p2==BTREE_SCHEMA_VERSION ){\n    /* When the schema cookie changes, record the new cookie internally */\n    pDb->pSchema->schema_cookie = pOp->p3;\n    db->mDbFlags |= DBFLAG_SchemaChange;\n  }else if( pOp->p2==BTREE_FILE_FORMAT ){\n    /* Record changes in the file format */\n    pDb->pSchema->file_format = pOp->p3;\n  }\n  if( pOp->p1==1 ){\n    /* Invalidate all prepared statements whenever the TEMP database\n    ** schema is changed.  Ticket #1644 */\n    sqlite3ExpirePreparedStatements(db, 0);\n    p->expired = 0;\n  }\n  if( rc ) goto abort_due_to_error;\n  break;\n}\n\n/* Opcode: OpenRead P1 P2 P3 P4 P5\n** Synopsis: root=P2 iDb=P3\n**\n** Open a read-only cursor for the database table whose root page is\n** P2 in a database file.  The database file is determined by P3. \n** P3==0 means the main database, P3==1 means the database used for \n** temporary tables, and P3>1 means used the corresponding attached\n** database.  Give the new cursor an identifier of P1.  The P1\n** values need not be contiguous but all P1 values should be small integers.\n** It is an error for P1 to be negative.\n**\n** Allowed P5 bits:\n** <ul>\n** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for\n**       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT\n**       of OP_SeekLE/OP_IdxLT)\n** </ul>\n**\n** The P4 value may be either an integer (P4_INT32) or a pointer to\n** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo \n** object, then table being opened must be an [index b-tree] where the\n** KeyInfo object defines the content and collating \n** sequence of that index b-tree. Otherwise, if P4 is an integer \n** value, then the table being opened must be a [table b-tree] with a\n** number of columns no less than the value of P4.\n**\n** See also: OpenWrite, ReopenIdx\n*/\n/* Opcode: ReopenIdx P1 P2 P3 P4 P5\n** Synopsis: root=P2 iDb=P3\n**\n** The ReopenIdx opcode works like OP_OpenRead except that it first\n** checks to see if the cursor on P1 is already open on the same\n** b-tree and if it is this opcode becomes a no-op.  In other words,\n** if the cursor is already open, do not reopen it.\n**\n** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ\n** and with P4 being a P4_KEYINFO object.  Furthermore, the P3 value must\n** be the same as every other ReopenIdx or OpenRead for the same cursor\n** number.\n**\n** Allowed P5 bits:\n** <ul>\n** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for\n**       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT\n**       of OP_SeekLE/OP_IdxLT)\n** </ul>\n**\n** See also: OP_OpenRead, OP_OpenWrite\n*/\n/* Opcode: OpenWrite P1 P2 P3 P4 P5\n** Synopsis: root=P2 iDb=P3\n**\n** Open a read/write cursor named P1 on the table or index whose root\n** page is P2 (or whose root page is held in register P2 if the\n** OPFLAG_P2ISREG bit is set in P5 - see below).\n**\n** The P4 value may be either an integer (P4_INT32) or a pointer to\n** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo \n** object, then table being opened must be an [index b-tree] where the\n** KeyInfo object defines the content and collating \n** sequence of that index b-tree. Otherwise, if P4 is an integer \n** value, then the table being opened must be a [table b-tree] with a\n** number of columns no less than the value of P4.\n**\n** Allowed P5 bits:\n** <ul>\n** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for\n**       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT\n**       of OP_SeekLE/OP_IdxLT)\n** <li>  <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek\n**       and subsequently delete entries in an index btree.  This is a\n**       hint to the storage engine that the storage engine is allowed to\n**       ignore.  The hint is not used by the official SQLite b*tree storage\n**       engine, but is used by COMDB2.\n** <li>  <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2\n**       as the root page, not the value of P2 itself.\n** </ul>\n**\n** This instruction works like OpenRead except that it opens the cursor\n** in read/write mode.\n**\n** See also: OP_OpenRead, OP_ReopenIdx\n*/\ncase OP_ReopenIdx: {\n  int nField;\n  KeyInfo *pKeyInfo;\n  int p2;\n  int iDb;\n  int wrFlag;\n  Btree *pX;\n  VdbeCursor *pCur;\n  Db *pDb;\n\n  assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );\n  assert( pOp->p4type==P4_KEYINFO );\n  pCur = p->apCsr[pOp->p1];\n  if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){\n    assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */\n    goto open_cursor_set_hints;\n  }\n  /* If the cursor is not currently open or is open on a different\n  ** index, then fall through into OP_OpenRead to force a reopen */\ncase OP_OpenRead:\ncase OP_OpenWrite:\n\n  assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );\n  assert( p->bIsReader );\n  assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx\n          || p->readOnly==0 );\n\n  if( p->expired==1 ){\n    rc = SQLITE_ABORT_ROLLBACK;\n    goto abort_due_to_error;\n  }\n\n  nField = 0;\n  pKeyInfo = 0;\n  p2 = pOp->p2;\n  iDb = pOp->p3;\n  assert( iDb>=0 && iDb<db->nDb );\n  assert( DbMaskTest(p->btreeMask, iDb) );\n  pDb = &db->aDb[iDb];\n  pX = pDb->pBt;\n  assert( pX!=0 );\n  if( pOp->opcode==OP_OpenWrite ){\n    assert( OPFLAG_FORDELETE==BTREE_FORDELETE );\n    wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);\n    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n    if( pDb->pSchema->file_format < p->minWriteFileFormat ){\n      p->minWriteFileFormat = pDb->pSchema->file_format;\n    }\n  }else{\n    wrFlag = 0;\n  }\n  if( pOp->p5 & OPFLAG_P2ISREG ){\n    assert( p2>0 );\n    assert( p2<=(p->nMem+1 - p->nCursor) );\n    assert( pOp->opcode==OP_OpenWrite );\n    pIn2 = &aMem[p2];\n    assert( memIsValid(pIn2) );\n    assert( (pIn2->flags & MEM_Int)!=0 );\n    sqlite3VdbeMemIntegerify(pIn2);\n    p2 = (int)pIn2->u.i;\n    /* The p2 value always comes from a prior OP_CreateBtree opcode and\n    ** that opcode will always set the p2 value to 2 or more or else fail.\n    ** If there were a failure, the prepared statement would have halted\n    ** before reaching this instruction. */\n    assert( p2>=2 );\n  }\n  if( pOp->p4type==P4_KEYINFO ){\n    pKeyInfo = pOp->p4.pKeyInfo;\n    assert( pKeyInfo->enc==ENC(db) );\n    assert( pKeyInfo->db==db );\n    nField = pKeyInfo->nAllField;\n  }else if( pOp->p4type==P4_INT32 ){\n    nField = pOp->p4.i;\n  }\n  assert( pOp->p1>=0 );\n  assert( nField>=0 );\n  testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */\n  pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);\n  if( pCur==0 ) goto no_mem;\n  pCur->nullRow = 1;\n  pCur->isOrdered = 1;\n  pCur->pgnoRoot = p2;\n#ifdef SQLITE_DEBUG\n  pCur->wrFlag = wrFlag;\n#endif\n  rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);\n  pCur->pKeyInfo = pKeyInfo;\n  /* Set the VdbeCursor.isTable variable. Previous versions of\n  ** SQLite used to check if the root-page flags were sane at this point\n  ** and report database corruption if they were not, but this check has\n  ** since moved into the btree layer.  */  \n  pCur->isTable = pOp->p4type!=P4_KEYINFO;\n\nopen_cursor_set_hints:\n  assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );\n  assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );\n  testcase( pOp->p5 & OPFLAG_BULKCSR );\n  testcase( pOp->p2 & OPFLAG_SEEKEQ );\n  sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,\n                               (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));\n  if( rc ) goto abort_due_to_error;\n  break;\n}\n\n/* Opcode: OpenDup P1 P2 * * *\n**\n** Open a new cursor P1 that points to the same ephemeral table as\n** cursor P2.  The P2 cursor must have been opened by a prior OP_OpenEphemeral\n** opcode.  Only ephemeral cursors may be duplicated.\n**\n** Duplicate ephemeral cursors are used for self-joins of materialized views.\n*/\ncase OP_OpenDup: {\n  VdbeCursor *pOrig;    /* The original cursor to be duplicated */\n  VdbeCursor *pCx;      /* The new cursor */\n\n  pOrig = p->apCsr[pOp->p2];\n  assert( pOrig );\n  assert( pOrig->pBtx!=0 );  /* Only ephemeral cursors can be duplicated */\n\n  pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);\n  if( pCx==0 ) goto no_mem;\n  pCx->nullRow = 1;\n  pCx->isEphemeral = 1;\n  pCx->pKeyInfo = pOrig->pKeyInfo;\n  pCx->isTable = pOrig->isTable;\n  pCx->pgnoRoot = pOrig->pgnoRoot;\n  pCx->isOrdered = pOrig->isOrdered;\n  rc = sqlite3BtreeCursor(pOrig->pBtx, pCx->pgnoRoot, BTREE_WRCSR,\n                          pCx->pKeyInfo, pCx->uc.pCursor);\n  /* The sqlite3BtreeCursor() routine can only fail for the first cursor\n  ** opened for a database.  Since there is already an open cursor when this\n  ** opcode is run, the sqlite3BtreeCursor() cannot fail */\n  assert( rc==SQLITE_OK );\n  break;\n}\n\n\n/* Opcode: OpenEphemeral P1 P2 * P4 P5\n** Synopsis: nColumn=P2\n**\n** Open a new cursor P1 to a transient table.\n** The cursor is always opened read/write even if \n** the main database is read-only.  The ephemeral\n** table is deleted automatically when the cursor is closed.\n**\n** If the cursor P1 is already opened on an ephemeral table, the table\n** is cleared (all content is erased).\n**\n** P2 is the number of columns in the ephemeral table.\n** The cursor points to a BTree table if P4==0 and to a BTree index\n** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure\n** that defines the format of keys in the index.\n**\n** The P5 parameter can be a mask of the BTREE_* flags defined\n** in btree.h.  These flags control aspects of the operation of\n** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are\n** added automatically.\n*/\n/* Opcode: OpenAutoindex P1 P2 * P4 *\n** Synopsis: nColumn=P2\n**\n** This opcode works the same as OP_OpenEphemeral.  It has a\n** different name to distinguish its use.  Tables created using\n** by this opcode will be used for automatically created transient\n** indices in joins.\n*/\ncase OP_OpenAutoindex: \ncase OP_OpenEphemeral: {\n  VdbeCursor *pCx;\n  KeyInfo *pKeyInfo;\n\n  static const int vfsFlags = \n      SQLITE_OPEN_READWRITE |\n      SQLITE_OPEN_CREATE |\n      SQLITE_OPEN_EXCLUSIVE |\n      SQLITE_OPEN_DELETEONCLOSE |\n      SQLITE_OPEN_TRANSIENT_DB;\n  assert( pOp->p1>=0 );\n  assert( pOp->p2>=0 );\n  pCx = p->apCsr[pOp->p1];\n  if( pCx && pCx->pBtx ){\n    /* If the ephermeral table is already open, erase all existing content\n    ** so that the table is empty again, rather than creating a new table. */\n    assert( pCx->isEphemeral );\n    pCx->seqCount = 0;\n    pCx->cacheStatus = CACHE_STALE;\n    rc = sqlite3BtreeClearTable(pCx->pBtx, pCx->pgnoRoot, 0);\n  }else{\n    pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);\n    if( pCx==0 ) goto no_mem;\n    pCx->isEphemeral = 1;\n    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx, \n                          BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,\n                          vfsFlags);\n    if( rc==SQLITE_OK ){\n      rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0);\n    }\n    if( rc==SQLITE_OK ){\n      /* If a transient index is required, create it by calling\n      ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before\n      ** opening it. If a transient table is required, just use the\n      ** automatically created table with root-page 1 (an BLOB_INTKEY table).\n      */\n      if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){\n        assert( pOp->p4type==P4_KEYINFO );\n        rc = sqlite3BtreeCreateTable(pCx->pBtx, (int*)&pCx->pgnoRoot,\n                                     BTREE_BLOBKEY | pOp->p5); \n        if( rc==SQLITE_OK ){\n          assert( pCx->pgnoRoot==MASTER_ROOT+1 );\n          assert( pKeyInfo->db==db );\n          assert( pKeyInfo->enc==ENC(db) );\n          rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR,\n                                  pKeyInfo, pCx->uc.pCursor);\n        }\n        pCx->isTable = 0;\n      }else{\n        pCx->pgnoRoot = MASTER_ROOT;\n        rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,\n                                0, pCx->uc.pCursor);\n        pCx->isTable = 1;\n      }\n    }\n    pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);\n  }\n  if( rc ) goto abort_due_to_error;\n  pCx->nullRow = 1;\n  break;\n}\n\n/* Opcode: SorterOpen P1 P2 P3 P4 *\n**\n** This opcode works like OP_OpenEphemeral except that it opens\n** a transient index that is specifically designed to sort large\n** tables using an external merge-sort algorithm.\n**\n** If argument P3 is non-zero, then it indicates that the sorter may\n** assume that a stable sort considering the first P3 fields of each\n** key is sufficient to produce the required results.\n*/\ncase OP_SorterOpen: {\n  VdbeCursor *pCx;\n\n  assert( pOp->p1>=0 );\n  assert( pOp->p2>=0 );\n  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);\n  if( pCx==0 ) goto no_mem;\n  pCx->pKeyInfo = pOp->p4.pKeyInfo;\n  assert( pCx->pKeyInfo->db==db );\n  assert( pCx->pKeyInfo->enc==ENC(db) );\n  rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);\n  if( rc ) goto abort_due_to_error;\n  break;\n}\n\n/* Opcode: SequenceTest P1 P2 * * *\n** Synopsis: if( cursor[P1].ctr++ ) pc = P2\n**\n** P1 is a sorter cursor. If the sequence counter is currently zero, jump\n** to P2. Regardless of whether or not the jump is taken, increment the\n** the sequence value.\n*/\ncase OP_SequenceTest: {\n  VdbeCursor *pC;\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( isSorter(pC) );\n  if( (pC->seqCount++)==0 ){\n    goto jump_to_p2;\n  }\n  break;\n}\n\n/* Opcode: OpenPseudo P1 P2 P3 * *\n** Synopsis: P3 columns in r[P2]\n**\n** Open a new cursor that points to a fake table that contains a single\n** row of data.  The content of that one row is the content of memory\n** register P2.  In other words, cursor P1 becomes an alias for the \n** MEM_Blob content contained in register P2.\n**\n** A pseudo-table created by this opcode is used to hold a single\n** row output from the sorter so that the row can be decomposed into\n** individual columns using the OP_Column opcode.  The OP_Column opcode\n** is the only cursor opcode that works with a pseudo-table.\n**\n** P3 is the number of fields in the records that will be stored by\n** the pseudo-table.\n*/\ncase OP_OpenPseudo: {\n  VdbeCursor *pCx;\n\n  assert( pOp->p1>=0 );\n  assert( pOp->p3>=0 );\n  pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);\n  if( pCx==0 ) goto no_mem;\n  pCx->nullRow = 1;\n  pCx->seekResult = pOp->p2;\n  pCx->isTable = 1;\n  /* Give this pseudo-cursor a fake BtCursor pointer so that pCx\n  ** can be safely passed to sqlite3VdbeCursorMoveto().  This avoids a test\n  ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()\n  ** which is a performance optimization */\n  pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();\n  assert( pOp->p5==0 );\n  break;\n}\n\n/* Opcode: Close P1 * * * *\n**\n** Close a cursor previously opened as P1.  If P1 is not\n** currently open, this instruction is a no-op.\n*/\ncase OP_Close: {\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);\n  p->apCsr[pOp->p1] = 0;\n  break;\n}\n\n#ifdef SQLITE_ENABLE_COLUMN_USED_MASK\n/* Opcode: ColumnsUsed P1 * * P4 *\n**\n** This opcode (which only exists if SQLite was compiled with\n** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the\n** table or index for cursor P1 are used.  P4 is a 64-bit integer\n** (P4_INT64) in which the first 63 bits are one for each of the\n** first 63 columns of the table or index that are actually used\n** by the cursor.  The high-order bit is set if any column after\n** the 64th is used.\n*/\ncase OP_ColumnsUsed: {\n  VdbeCursor *pC;\n  pC = p->apCsr[pOp->p1];\n  assert( pC->eCurType==CURTYPE_BTREE );\n  pC->maskUsed = *(u64*)pOp->p4.pI64;\n  break;\n}\n#endif\n\n/* Opcode: SeekGE P1 P2 P3 P4 *\n** Synopsis: key=r[P3@P4]\n**\n** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), \n** use the value in register P3 as the key.  If cursor P1 refers \n** to an SQL index, then P3 is the first in an array of P4 registers \n** that are used as an unpacked index key. \n**\n** Reposition cursor P1 so that  it points to the smallest entry that \n** is greater than or equal to the key value. If there are no records \n** greater than or equal to the key and P2 is not zero, then jump to P2.\n**\n** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this\n** opcode will either land on a record that exactly matches the key, or\n** else it will cause a jump to P2.  When the cursor is OPFLAG_SEEKEQ,\n** this opcode must be followed by an IdxLE opcode with the same arguments.\n** The IdxGT opcode will be skipped if this opcode succeeds, but the\n** IdxGT opcode will be used on subsequent loop iterations.  The \n** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this\n** is an equality search.\n**\n** This opcode leaves the cursor configured to move in forward order,\n** from the beginning toward the end.  In other words, the cursor is\n** configured to use Next, not Prev.\n**\n** See also: Found, NotFound, SeekLt, SeekGt, SeekLe\n*/\n/* Opcode: SeekGT P1 P2 P3 P4 *\n** Synopsis: key=r[P3@P4]\n**\n** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), \n** use the value in register P3 as a key. If cursor P1 refers \n** to an SQL index, then P3 is the first in an array of P4 registers \n** that are used as an unpacked index key. \n**\n** Reposition cursor P1 so that it points to the smallest entry that \n** is greater than the key value. If there are no records greater than \n** the key and P2 is not zero, then jump to P2.\n**\n** This opcode leaves the cursor configured to move in forward order,\n** from the beginning toward the end.  In other words, the cursor is\n** configured to use Next, not Prev.\n**\n** See also: Found, NotFound, SeekLt, SeekGe, SeekLe\n*/\n/* Opcode: SeekLT P1 P2 P3 P4 * \n** Synopsis: key=r[P3@P4]\n**\n** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), \n** use the value in register P3 as a key. If cursor P1 refers \n** to an SQL index, then P3 is the first in an array of P4 registers \n** that are used as an unpacked index key. \n**\n** Reposition cursor P1 so that  it points to the largest entry that \n** is less than the key value. If there are no records less than \n** the key and P2 is not zero, then jump to P2.\n**\n** This opcode leaves the cursor configured to move in reverse order,\n** from the end toward the beginning.  In other words, the cursor is\n** configured to use Prev, not Next.\n**\n** See also: Found, NotFound, SeekGt, SeekGe, SeekLe\n*/\n/* Opcode: SeekLE P1 P2 P3 P4 *\n** Synopsis: key=r[P3@P4]\n**\n** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), \n** use the value in register P3 as a key. If cursor P1 refers \n** to an SQL index, then P3 is the first in an array of P4 registers \n** that are used as an unpacked index key. \n**\n** Reposition cursor P1 so that it points to the largest entry that \n** is less than or equal to the key value. If there are no records \n** less than or equal to the key and P2 is not zero, then jump to P2.\n**\n** This opcode leaves the cursor configured to move in reverse order,\n** from the end toward the beginning.  In other words, the cursor is\n** configured to use Prev, not Next.\n**\n** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this\n** opcode will either land on a record that exactly matches the key, or\n** else it will cause a jump to P2.  When the cursor is OPFLAG_SEEKEQ,\n** this opcode must be followed by an IdxLE opcode with the same arguments.\n** The IdxGE opcode will be skipped if this opcode succeeds, but the\n** IdxGE opcode will be used on subsequent loop iterations.  The \n** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this\n** is an equality search.\n**\n** See also: Found, NotFound, SeekGt, SeekGe, SeekLt\n*/\ncase OP_SeekLT:         /* jump, in3, group */\ncase OP_SeekLE:         /* jump, in3, group */\ncase OP_SeekGE:         /* jump, in3, group */\ncase OP_SeekGT: {       /* jump, in3, group */\n  int res;           /* Comparison result */\n  int oc;            /* Opcode */\n  VdbeCursor *pC;    /* The cursor to seek */\n  UnpackedRecord r;  /* The key to seek for */\n  int nField;        /* Number of columns or fields in the key */\n  i64 iKey;          /* The rowid we are to seek to */\n  int eqOnly;        /* Only interested in == results */\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  assert( pOp->p2!=0 );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  assert( pC->eCurType==CURTYPE_BTREE );\n  assert( OP_SeekLE == OP_SeekLT+1 );\n  assert( OP_SeekGE == OP_SeekLT+2 );\n  assert( OP_SeekGT == OP_SeekLT+3 );\n  assert( pC->isOrdered );\n  assert( pC->uc.pCursor!=0 );\n  oc = pOp->opcode;\n  eqOnly = 0;\n  pC->nullRow = 0;\n#ifdef SQLITE_DEBUG\n  pC->seekOp = pOp->opcode;\n#endif\n\n  pC->deferredMoveto = 0;\n  pC->cacheStatus = CACHE_STALE;\n  if( pC->isTable ){\n    u16 flags3, newType;\n    /* The OPFLAG_SEEKEQ/BTREE_SEEK_EQ flag is only set on index cursors */\n    assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0\n              || CORRUPT_DB );\n\n    /* The input value in P3 might be of any type: integer, real, string,\n    ** blob, or NULL.  But it needs to be an integer before we can do\n    ** the seek, so convert it. */\n    pIn3 = &aMem[pOp->p3];\n    flags3 = pIn3->flags;\n    if( (flags3 & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){\n      applyNumericAffinity(pIn3, 0);\n    }\n    iKey = sqlite3VdbeIntValue(pIn3); /* Get the integer key value */\n    newType = pIn3->flags; /* Record the type after applying numeric affinity */\n    pIn3->flags = flags3;  /* But convert the type back to its original */\n\n    /* If the P3 value could not be converted into an integer without\n    ** loss of information, then special processing is required... */\n    if( (newType & (MEM_Int|MEM_IntReal))==0 ){\n      if( (newType & MEM_Real)==0 ){\n        if( (newType & MEM_Null) || oc>=OP_SeekGE ){\n          VdbeBranchTaken(1,2);\n          goto jump_to_p2;\n        }else{\n          rc = sqlite3BtreeLast(pC->uc.pCursor, &res);\n          if( rc!=SQLITE_OK ) goto abort_due_to_error;\n          goto seek_not_found;\n        }\n      }else\n\n      /* If the approximation iKey is larger than the actual real search\n      ** term, substitute >= for > and < for <=. e.g. if the search term\n      ** is 4.9 and the integer approximation 5:\n      **\n      **        (x >  4.9)    ->     (x >= 5)\n      **        (x <= 4.9)    ->     (x <  5)\n      */\n      if( pIn3->u.r<(double)iKey ){\n        assert( OP_SeekGE==(OP_SeekGT-1) );\n        assert( OP_SeekLT==(OP_SeekLE-1) );\n        assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );\n        if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;\n      }\n\n      /* If the approximation iKey is smaller than the actual real search\n      ** term, substitute <= for < and > for >=.  */\n      else if( pIn3->u.r>(double)iKey ){\n        assert( OP_SeekLE==(OP_SeekLT+1) );\n        assert( OP_SeekGT==(OP_SeekGE+1) );\n        assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );\n        if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;\n      }\n    }\n    rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);\n    pC->movetoTarget = iKey;  /* Used by OP_Delete */\n    if( rc!=SQLITE_OK ){\n      goto abort_due_to_error;\n    }\n  }else{\n    /* For a cursor with the OPFLAG_SEEKEQ/BTREE_SEEK_EQ hint, only the\n    ** OP_SeekGE and OP_SeekLE opcodes are allowed, and these must be\n    ** immediately followed by an OP_IdxGT or OP_IdxLT opcode, respectively,\n    ** with the same key.\n    */\n    if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){\n      eqOnly = 1;\n      assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );\n      assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );\n      assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT );\n      assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT );\n      assert( pOp[1].p1==pOp[0].p1 );\n      assert( pOp[1].p2==pOp[0].p2 );\n      assert( pOp[1].p3==pOp[0].p3 );\n      assert( pOp[1].p4.i==pOp[0].p4.i );\n    }\n\n    nField = pOp->p4.i;\n    assert( pOp->p4type==P4_INT32 );\n    assert( nField>0 );\n    r.pKeyInfo = pC->pKeyInfo;\n    r.nField = (u16)nField;\n\n    /* The next line of code computes as follows, only faster:\n    **   if( oc==OP_SeekGT || oc==OP_SeekLE ){\n    **     r.default_rc = -1;\n    **   }else{\n    **     r.default_rc = +1;\n    **   }\n    */\n    r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);\n    assert( oc!=OP_SeekGT || r.default_rc==-1 );\n    assert( oc!=OP_SeekLE || r.default_rc==-1 );\n    assert( oc!=OP_SeekGE || r.default_rc==+1 );\n    assert( oc!=OP_SeekLT || r.default_rc==+1 );\n\n    r.aMem = &aMem[pOp->p3];\n#ifdef SQLITE_DEBUG\n    { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }\n#endif\n    r.eqSeen = 0;\n    rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);\n    if( rc!=SQLITE_OK ){\n      goto abort_due_to_error;\n    }\n    if( eqOnly && r.eqSeen==0 ){\n      assert( res!=0 );\n      goto seek_not_found;\n    }\n  }\n#ifdef SQLITE_TEST\n  sqlite3_search_count++;\n#endif\n  if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );\n    if( res<0 || (res==0 && oc==OP_SeekGT) ){\n      res = 0;\n      rc = sqlite3BtreeNext(pC->uc.pCursor, 0);\n      if( rc!=SQLITE_OK ){\n        if( rc==SQLITE_DONE ){\n          rc = SQLITE_OK;\n          res = 1;\n        }else{\n          goto abort_due_to_error;\n        }\n      }\n    }else{\n      res = 0;\n    }\n  }else{\n    assert( oc==OP_SeekLT || oc==OP_SeekLE );\n    if( res>0 || (res==0 && oc==OP_SeekLT) ){\n      res = 0;\n      rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);\n      if( rc!=SQLITE_OK ){\n        if( rc==SQLITE_DONE ){\n          rc = SQLITE_OK;\n          res = 1;\n        }else{\n          goto abort_due_to_error;\n        }\n      }\n    }else{\n      /* res might be negative because the table is empty.  Check to\n      ** see if this is the case.\n      */\n      res = sqlite3BtreeEof(pC->uc.pCursor);\n    }\n  }\nseek_not_found:\n  assert( pOp->p2>0 );\n  VdbeBranchTaken(res!=0,2);\n  if( res ){\n    goto jump_to_p2;\n  }else if( eqOnly ){\n    assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );\n    pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */\n  }\n  break;\n}\n\n/* Opcode: SeekHit P1 P2 * * *\n** Synopsis: seekHit=P2\n**\n** Set the seekHit flag on cursor P1 to the value in P2.\n* The seekHit flag is used by the IfNoHope opcode.\n**\n** P1 must be a valid b-tree cursor.  P2 must be a boolean value,\n** either 0 or 1.\n*/\ncase OP_SeekHit: {\n  VdbeCursor *pC;\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  assert( pOp->p2==0 || pOp->p2==1 );\n  pC->seekHit = pOp->p2 & 1;\n  break;\n}\n\n/* Opcode: IfNotOpen P1 P2 * * *\n** Synopsis: if( !csr[P1] ) goto P2\n**\n** If cursor P1 is not open, jump to instruction P2. Otherwise, fall through.\n*/\ncase OP_IfNotOpen: {        /* jump */\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  VdbeBranchTaken(p->apCsr[pOp->p1]==0, 2);\n  if( !p->apCsr[pOp->p1] ){\n    goto jump_to_p2_and_check_for_interrupt;\n  }\n  break;\n}\n\n/* Opcode: Found P1 P2 P3 P4 *\n** Synopsis: key=r[P3@P4]\n**\n** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If\n** P4>0 then register P3 is the first of P4 registers that form an unpacked\n** record.\n**\n** Cursor P1 is on an index btree.  If the record identified by P3 and P4\n** is a prefix of any entry in P1 then a jump is made to P2 and\n** P1 is left pointing at the matching entry.\n**\n** This operation leaves the cursor in a state where it can be\n** advanced in the forward direction.  The Next instruction will work,\n** but not the Prev instruction.\n**\n** See also: NotFound, NoConflict, NotExists. SeekGe\n*/\n/* Opcode: NotFound P1 P2 P3 P4 *\n** Synopsis: key=r[P3@P4]\n**\n** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If\n** P4>0 then register P3 is the first of P4 registers that form an unpacked\n** record.\n** \n** Cursor P1 is on an index btree.  If the record identified by P3 and P4\n** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 \n** does contain an entry whose prefix matches the P3/P4 record then control\n** falls through to the next instruction and P1 is left pointing at the\n** matching entry.\n**\n** This operation leaves the cursor in a state where it cannot be\n** advanced in either direction.  In other words, the Next and Prev\n** opcodes do not work after this operation.\n**\n** See also: Found, NotExists, NoConflict, IfNoHope\n*/\n/* Opcode: IfNoHope P1 P2 P3 P4 *\n** Synopsis: key=r[P3@P4]\n**\n** Register P3 is the first of P4 registers that form an unpacked\n** record.\n**\n** Cursor P1 is on an index btree.  If the seekHit flag is set on P1, then\n** this opcode is a no-op.  But if the seekHit flag of P1 is clear, then\n** check to see if there is any entry in P1 that matches the\n** prefix identified by P3 and P4.  If no entry matches the prefix,\n** jump to P2.  Otherwise fall through.\n**\n** This opcode behaves like OP_NotFound if the seekHit\n** flag is clear and it behaves like OP_Noop if the seekHit flag is set.\n**\n** This opcode is used in IN clause processing for a multi-column key.\n** If an IN clause is attached to an element of the key other than the\n** left-most element, and if there are no matches on the most recent\n** seek over the whole key, then it might be that one of the key element\n** to the left is prohibiting a match, and hence there is \"no hope\" of\n** any match regardless of how many IN clause elements are checked.\n** In such a case, we abandon the IN clause search early, using this\n** opcode.  The opcode name comes from the fact that the\n** jump is taken if there is \"no hope\" of achieving a match.\n**\n** See also: NotFound, SeekHit\n*/\n/* Opcode: NoConflict P1 P2 P3 P4 *\n** Synopsis: key=r[P3@P4]\n**\n** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If\n** P4>0 then register P3 is the first of P4 registers that form an unpacked\n** record.\n** \n** Cursor P1 is on an index btree.  If the record identified by P3 and P4\n** contains any NULL value, jump immediately to P2.  If all terms of the\n** record are not-NULL then a check is done to determine if any row in the\n** P1 index btree has a matching key prefix.  If there are no matches, jump\n** immediately to P2.  If there is a match, fall through and leave the P1\n** cursor pointing to the matching row.\n**\n** This opcode is similar to OP_NotFound with the exceptions that the\n** branch is always taken if any part of the search key input is NULL.\n**\n** This operation leaves the cursor in a state where it cannot be\n** advanced in either direction.  In other words, the Next and Prev\n** opcodes do not work after this operation.\n**\n** See also: NotFound, Found, NotExists\n*/\ncase OP_IfNoHope: {     /* jump, in3 */\n  VdbeCursor *pC;\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  if( pC->seekHit ) break;\n  /* Fall through into OP_NotFound */\n}\ncase OP_NoConflict:     /* jump, in3 */\ncase OP_NotFound:       /* jump, in3 */\ncase OP_Found: {        /* jump, in3 */\n  int alreadyExists;\n  int takeJump;\n  int ii;\n  VdbeCursor *pC;\n  int res;\n  UnpackedRecord *pFree;\n  UnpackedRecord *pIdxKey;\n  UnpackedRecord r;\n\n#ifdef SQLITE_TEST\n  if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;\n#endif\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  assert( pOp->p4type==P4_INT32 );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n#ifdef SQLITE_DEBUG\n  pC->seekOp = pOp->opcode;\n#endif\n  pIn3 = &aMem[pOp->p3];\n  assert( pC->eCurType==CURTYPE_BTREE );\n  assert( pC->uc.pCursor!=0 );\n  assert( pC->isTable==0 );\n  if( pOp->p4.i>0 ){\n    r.pKeyInfo = pC->pKeyInfo;\n    r.nField = (u16)pOp->p4.i;\n    r.aMem = pIn3;\n#ifdef SQLITE_DEBUG\n    for(ii=0; ii<r.nField; ii++){\n      assert( memIsValid(&r.aMem[ii]) );\n      assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );\n      if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);\n    }\n#endif\n    pIdxKey = &r;\n    pFree = 0;\n  }else{\n    assert( pIn3->flags & MEM_Blob );\n    rc = ExpandBlob(pIn3);\n    assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );\n    if( rc ) goto no_mem;\n    pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);\n    if( pIdxKey==0 ) goto no_mem;\n    sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);\n  }\n  pIdxKey->default_rc = 0;\n  takeJump = 0;\n  if( pOp->opcode==OP_NoConflict ){\n    /* For the OP_NoConflict opcode, take the jump if any of the\n    ** input fields are NULL, since any key with a NULL will not\n    ** conflict */\n    for(ii=0; ii<pIdxKey->nField; ii++){\n      if( pIdxKey->aMem[ii].flags & MEM_Null ){\n        takeJump = 1;\n        break;\n      }\n    }\n  }\n  rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);\n  if( pFree ) sqlite3DbFreeNN(db, pFree);\n  if( rc!=SQLITE_OK ){\n    goto abort_due_to_error;\n  }\n  pC->seekResult = res;\n  alreadyExists = (res==0);\n  pC->nullRow = 1-alreadyExists;\n  pC->deferredMoveto = 0;\n  pC->cacheStatus = CACHE_STALE;\n  if( pOp->opcode==OP_Found ){\n    VdbeBranchTaken(alreadyExists!=0,2);\n    if( alreadyExists ) goto jump_to_p2;\n  }else{\n    VdbeBranchTaken(takeJump||alreadyExists==0,2);\n    if( takeJump || !alreadyExists ) goto jump_to_p2;\n  }\n  break;\n}\n\n/* Opcode: SeekRowid P1 P2 P3 * *\n** Synopsis: intkey=r[P3]\n**\n** P1 is the index of a cursor open on an SQL table btree (with integer\n** keys).  If register P3 does not contain an integer or if P1 does not\n** contain a record with rowid P3 then jump immediately to P2.  \n** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain\n** a record with rowid P3 then \n** leave the cursor pointing at that record and fall through to the next\n** instruction.\n**\n** The OP_NotExists opcode performs the same operation, but with OP_NotExists\n** the P3 register must be guaranteed to contain an integer value.  With this\n** opcode, register P3 might not contain an integer.\n**\n** The OP_NotFound opcode performs the same operation on index btrees\n** (with arbitrary multi-value keys).\n**\n** This opcode leaves the cursor in a state where it cannot be advanced\n** in either direction.  In other words, the Next and Prev opcodes will\n** not work following this opcode.\n**\n** See also: Found, NotFound, NoConflict, SeekRowid\n*/\n/* Opcode: NotExists P1 P2 P3 * *\n** Synopsis: intkey=r[P3]\n**\n** P1 is the index of a cursor open on an SQL table btree (with integer\n** keys).  P3 is an integer rowid.  If P1 does not contain a record with\n** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an\n** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then \n** leave the cursor pointing at that record and fall through to the next\n** instruction.\n**\n** The OP_SeekRowid opcode performs the same operation but also allows the\n** P3 register to contain a non-integer value, in which case the jump is\n** always taken.  This opcode requires that P3 always contain an integer.\n**\n** The OP_NotFound opcode performs the same operation on index btrees\n** (with arbitrary multi-value keys).\n**\n** This opcode leaves the cursor in a state where it cannot be advanced\n** in either direction.  In other words, the Next and Prev opcodes will\n** not work following this opcode.\n**\n** See also: Found, NotFound, NoConflict, SeekRowid\n*/\ncase OP_SeekRowid: {        /* jump, in3 */\n  VdbeCursor *pC;\n  BtCursor *pCrsr;\n  int res;\n  u64 iKey;\n\n  pIn3 = &aMem[pOp->p3];\n  testcase( pIn3->flags & MEM_Int );\n  testcase( pIn3->flags & MEM_IntReal );\n  testcase( pIn3->flags & MEM_Real );\n  testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str );\n  if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){\n    /* If pIn3->u.i does not contain an integer, compute iKey as the\n    ** integer value of pIn3.  Jump to P2 if pIn3 cannot be converted\n    ** into an integer without loss of information.  Take care to avoid\n    ** changing the datatype of pIn3, however, as it is used by other\n    ** parts of the prepared statement. */\n    Mem x = pIn3[0];\n    applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding);\n    if( (x.flags & MEM_Int)==0 ) goto jump_to_p2;\n    iKey = x.u.i;\n    goto notExistsWithKey;\n  }\n  /* Fall through into OP_NotExists */\ncase OP_NotExists:          /* jump, in3 */\n  pIn3 = &aMem[pOp->p3];\n  assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  iKey = pIn3->u.i;\nnotExistsWithKey:\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n#ifdef SQLITE_DEBUG\n  if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;\n#endif\n  assert( pC->isTable );\n  assert( pC->eCurType==CURTYPE_BTREE );\n  pCrsr = pC->uc.pCursor;\n  assert( pCrsr!=0 );\n  res = 0;\n  rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);\n  assert( rc==SQLITE_OK || res==0 );\n  pC->movetoTarget = iKey;  /* Used by OP_Delete */\n  pC->nullRow = 0;\n  pC->cacheStatus = CACHE_STALE;\n  pC->deferredMoveto = 0;\n  VdbeBranchTaken(res!=0,2);\n  pC->seekResult = res;\n  if( res!=0 ){\n    assert( rc==SQLITE_OK );\n    if( pOp->p2==0 ){\n      rc = SQLITE_CORRUPT_BKPT;\n    }else{\n      goto jump_to_p2;\n    }\n  }\n  if( rc ) goto abort_due_to_error;\n  break;\n}\n\n/* Opcode: Sequence P1 P2 * * *\n** Synopsis: r[P2]=cursor[P1].ctr++\n**\n** Find the next available sequence number for cursor P1.\n** Write the sequence number into register P2.\n** The sequence number on the cursor is incremented after this\n** instruction.  \n*/\ncase OP_Sequence: {           /* out2 */\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  assert( p->apCsr[pOp->p1]!=0 );\n  assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );\n  pOut = out2Prerelease(p, pOp);\n  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;\n  break;\n}\n\n\n/* Opcode: NewRowid P1 P2 P3 * *\n** Synopsis: r[P2]=rowid\n**\n** Get a new integer record number (a.k.a \"rowid\") used as the key to a table.\n** The record number is not previously used as a key in the database\n** table that cursor P1 points to.  The new record number is written\n** written to register P2.\n**\n** If P3>0 then P3 is a register in the root frame of this VDBE that holds \n** the largest previously generated record number. No new record numbers are\n** allowed to be less than this value. When this value reaches its maximum, \n** an SQLITE_FULL error is generated. The P3 register is updated with the '\n** generated record number. This P3 mechanism is used to help implement the\n** AUTOINCREMENT feature.\n*/\ncase OP_NewRowid: {           /* out2 */\n  i64 v;                 /* The new rowid */\n  VdbeCursor *pC;        /* Cursor of table to get the new rowid */\n  int res;               /* Result of an sqlite3BtreeLast() */\n  int cnt;               /* Counter to limit the number of searches */\n  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */\n  VdbeFrame *pFrame;     /* Root frame of VDBE */\n\n  v = 0;\n  res = 0;\n  pOut = out2Prerelease(p, pOp);\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  assert( pC->isTable );\n  assert( pC->eCurType==CURTYPE_BTREE );\n  assert( pC->uc.pCursor!=0 );\n  {\n    /* The next rowid or record number (different terms for the same\n    ** thing) is obtained in a two-step algorithm.\n    **\n    ** First we attempt to find the largest existing rowid and add one\n    ** to that.  But if the largest existing rowid is already the maximum\n    ** positive integer, we have to fall through to the second\n    ** probabilistic algorithm\n    **\n    ** The second algorithm is to select a rowid at random and see if\n    ** it already exists in the table.  If it does not exist, we have\n    ** succeeded.  If the random rowid does exist, we select a new one\n    ** and try again, up to 100 times.\n    */\n    assert( pC->isTable );\n\n#ifdef SQLITE_32BIT_ROWID\n#   define MAX_ROWID 0x7fffffff\n#else\n    /* Some compilers complain about constants of the form 0x7fffffffffffffff.\n    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems\n    ** to provide the constant while making all compilers happy.\n    */\n#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )\n#endif\n\n    if( !pC->useRandomRowid ){\n      rc = sqlite3BtreeLast(pC->uc.pCursor, &res);\n      if( rc!=SQLITE_OK ){\n        goto abort_due_to_error;\n      }\n      if( res ){\n        v = 1;   /* IMP: R-61914-48074 */\n      }else{\n        assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );\n        v = sqlite3BtreeIntegerKey(pC->uc.pCursor);\n        if( v>=MAX_ROWID ){\n          pC->useRandomRowid = 1;\n        }else{\n          v++;   /* IMP: R-29538-34987 */\n        }\n      }\n    }\n\n#ifndef SQLITE_OMIT_AUTOINCREMENT\n    if( pOp->p3 ){\n      /* Assert that P3 is a valid memory cell. */\n      assert( pOp->p3>0 );\n      if( p->pFrame ){\n        for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);\n        /* Assert that P3 is a valid memory cell. */\n        assert( pOp->p3<=pFrame->nMem );\n        pMem = &pFrame->aMem[pOp->p3];\n      }else{\n        /* Assert that P3 is a valid memory cell. */\n        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );\n        pMem = &aMem[pOp->p3];\n        memAboutToChange(p, pMem);\n      }\n      assert( memIsValid(pMem) );\n\n      REGISTER_TRACE(pOp->p3, pMem);\n      sqlite3VdbeMemIntegerify(pMem);\n      assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */\n      if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){\n        rc = SQLITE_FULL;   /* IMP: R-17817-00630 */\n        goto abort_due_to_error;\n      }\n      if( v<pMem->u.i+1 ){\n        v = pMem->u.i + 1;\n      }\n      pMem->u.i = v;\n    }\n#endif\n    if( pC->useRandomRowid ){\n      /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the\n      ** largest possible integer (9223372036854775807) then the database\n      ** engine starts picking positive candidate ROWIDs at random until\n      ** it finds one that is not previously used. */\n      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is\n                             ** an AUTOINCREMENT table. */\n      cnt = 0;\n      do{\n        sqlite3_randomness(sizeof(v), &v);\n        v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */\n      }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,\n                                                 0, &res))==SQLITE_OK)\n            && (res==0)\n            && (++cnt<100));\n      if( rc ) goto abort_due_to_error;\n      if( res==0 ){\n        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */\n        goto abort_due_to_error;\n      }\n      assert( v>0 );  /* EV: R-40812-03570 */\n    }\n    pC->deferredMoveto = 0;\n    pC->cacheStatus = CACHE_STALE;\n  }\n  pOut->u.i = v;\n  break;\n}\n\n/* Opcode: Insert P1 P2 P3 P4 P5\n** Synopsis: intkey=r[P3] data=r[P2]\n**\n** Write an entry into the table of cursor P1.  A new entry is\n** created if it doesn't already exist or the data for an existing\n** entry is overwritten.  The data is the value MEM_Blob stored in register\n** number P2. The key is stored in register P3. The key must\n** be a MEM_Int.\n**\n** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is\n** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,\n** then rowid is stored for subsequent return by the\n** sqlite3_last_insert_rowid() function (otherwise it is unmodified).\n**\n** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might\n** run faster by avoiding an unnecessary seek on cursor P1.  However,\n** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior\n** seeks on the cursor or if the most recent seek used a key equal to P3.\n**\n** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an\n** UPDATE operation.  Otherwise (if the flag is clear) then this opcode\n** is part of an INSERT operation.  The difference is only important to\n** the update hook.\n**\n** Parameter P4 may point to a Table structure, or may be NULL. If it is \n** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked \n** following a successful insert.\n**\n** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically\n** allocated, then ownership of P2 is transferred to the pseudo-cursor\n** and register P2 becomes ephemeral.  If the cursor is changed, the\n** value of register P2 will then change.  Make sure this does not\n** cause any problems.)\n**\n** This instruction only works on tables.  The equivalent instruction\n** for indices is OP_IdxInsert.\n*/\ncase OP_Insert: {\n  Mem *pData;       /* MEM cell holding data for the record to be inserted */\n  Mem *pKey;        /* MEM cell holding key  for the record */\n  VdbeCursor *pC;   /* Cursor to table into which insert is written */\n  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */\n  const char *zDb;  /* database name - used by the update hook */\n  Table *pTab;      /* Table structure - used by update and pre-update hooks */\n  BtreePayload x;   /* Payload to be inserted */\n\n  pData = &aMem[pOp->p2];\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  assert( memIsValid(pData) );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  assert( pC->eCurType==CURTYPE_BTREE );\n  assert( pC->deferredMoveto==0 );\n  assert( pC->uc.pCursor!=0 );\n  assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );\n  assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );\n  REGISTER_TRACE(pOp->p2, pData);\n  sqlite3VdbeIncrWriteCounter(p, pC);\n\n  pKey = &aMem[pOp->p3];\n  assert( pKey->flags & MEM_Int );\n  assert( memIsValid(pKey) );\n  REGISTER_TRACE(pOp->p3, pKey);\n  x.nKey = pKey->u.i;\n\n  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){\n    assert( pC->iDb>=0 );\n    zDb = db->aDb[pC->iDb].zDbSName;\n    pTab = pOp->p4.pTab;\n    assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );\n  }else{\n    pTab = 0;\n    zDb = 0;  /* Not needed.  Silence a compiler warning. */\n  }\n\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n  /* Invoke the pre-update hook, if any */\n  if( pTab ){\n    if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){\n      sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);\n    }\n    if( db->xUpdateCallback==0 || pTab->aCol==0 ){\n      /* Prevent post-update hook from running in cases when it should not */\n      pTab = 0;\n    }\n  }\n  if( pOp->p5 & OPFLAG_ISNOOP ) break;\n#endif\n\n  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;\n  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;\n  assert( pData->flags & (MEM_Blob|MEM_Str) );\n  x.pData = pData->z;\n  x.nData = pData->n;\n  seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);\n  if( pData->flags & MEM_Zero ){\n    x.nZero = pData->u.nZero;\n  }else{\n    x.nZero = 0;\n  }\n  x.pKey = 0;\n  rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,\n      (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult\n  );\n  pC->deferredMoveto = 0;\n  pC->cacheStatus = CACHE_STALE;\n\n  /* Invoke the update-hook if required. */\n  if( rc ) goto abort_due_to_error;\n  if( pTab ){\n    assert( db->xUpdateCallback!=0 );\n    assert( pTab->aCol!=0 );\n    db->xUpdateCallback(db->pUpdateArg,\n           (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,\n           zDb, pTab->zName, x.nKey);\n  }\n  break;\n}\n\n/* Opcode: Delete P1 P2 P3 P4 P5\n**\n** Delete the record at which the P1 cursor is currently pointing.\n**\n** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then\n** the cursor will be left pointing at  either the next or the previous\n** record in the table. If it is left pointing at the next record, then\n** the next Next instruction will be a no-op. As a result, in this case\n** it is ok to delete a record from within a Next loop. If \n** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be\n** left in an undefined state.\n**\n** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this\n** delete one of several associated with deleting a table row and all its\n** associated index entries.  Exactly one of those deletes is the \"primary\"\n** delete.  The others are all on OPFLAG_FORDELETE cursors or else are\n** marked with the AUXDELETE flag.\n**\n** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row\n** change count is incremented (otherwise not).\n**\n** P1 must not be pseudo-table.  It has to be a real table with\n** multiple rows.\n**\n** If P4 is not NULL then it points to a Table object. In this case either \n** the update or pre-update hook, or both, may be invoked. The P1 cursor must\n** have been positioned using OP_NotFound prior to invoking this opcode in \n** this case. Specifically, if one is configured, the pre-update hook is \n** invoked if P4 is not NULL. The update-hook is invoked if one is configured, \n** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.\n**\n** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address\n** of the memory cell that contains the value that the rowid of the row will\n** be set to by the update.\n*/\ncase OP_Delete: {\n  VdbeCursor *pC;\n  const char *zDb;\n  Table *pTab;\n  int opflags;\n\n  opflags = pOp->p2;\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  assert( pC->eCurType==CURTYPE_BTREE );\n  assert( pC->uc.pCursor!=0 );\n  assert( pC->deferredMoveto==0 );\n  sqlite3VdbeIncrWriteCounter(p, pC);\n\n#ifdef SQLITE_DEBUG\n  if( pOp->p4type==P4_TABLE\n   && HasRowid(pOp->p4.pTab)\n   && pOp->p5==0\n   && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)\n  ){\n    /* If p5 is zero, the seek operation that positioned the cursor prior to\n    ** OP_Delete will have also set the pC->movetoTarget field to the rowid of\n    ** the row that is being deleted */\n    i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);\n    assert( CORRUPT_DB || pC->movetoTarget==iKey );\n  }\n#endif\n\n  /* If the update-hook or pre-update-hook will be invoked, set zDb to\n  ** the name of the db to pass as to it. Also set local pTab to a copy\n  ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was\n  ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set \n  ** VdbeCursor.movetoTarget to the current rowid.  */\n  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){\n    assert( pC->iDb>=0 );\n    assert( pOp->p4.pTab!=0 );\n    zDb = db->aDb[pC->iDb].zDbSName;\n    pTab = pOp->p4.pTab;\n    if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){\n      pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);\n    }\n  }else{\n    zDb = 0;   /* Not needed.  Silence a compiler warning. */\n    pTab = 0;  /* Not needed.  Silence a compiler warning. */\n  }\n\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n  /* Invoke the pre-update-hook if required. */\n  if( db->xPreUpdateCallback && pOp->p4.pTab ){\n    assert( !(opflags & OPFLAG_ISUPDATE) \n         || HasRowid(pTab)==0 \n         || (aMem[pOp->p3].flags & MEM_Int) \n    );\n    sqlite3VdbePreUpdateHook(p, pC,\n        (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE, \n        zDb, pTab, pC->movetoTarget,\n        pOp->p3\n    );\n  }\n  if( opflags & OPFLAG_ISNOOP ) break;\n#endif\n \n  /* Only flags that can be set are SAVEPOISTION and AUXDELETE */ \n  assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );\n  assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );\n  assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );\n\n#ifdef SQLITE_DEBUG\n  if( p->pFrame==0 ){\n    if( pC->isEphemeral==0\n        && (pOp->p5 & OPFLAG_AUXDELETE)==0\n        && (pC->wrFlag & OPFLAG_FORDELETE)==0\n      ){\n      nExtraDelete++;\n    }\n    if( pOp->p2 & OPFLAG_NCHANGE ){\n      nExtraDelete--;\n    }\n  }\n#endif\n\n  rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);\n  pC->cacheStatus = CACHE_STALE;\n  pC->seekResult = 0;\n  if( rc ) goto abort_due_to_error;\n\n  /* Invoke the update-hook if required. */\n  if( opflags & OPFLAG_NCHANGE ){\n    p->nChange++;\n    if( db->xUpdateCallback && HasRowid(pTab) ){\n      db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,\n          pC->movetoTarget);\n      assert( pC->iDb>=0 );\n    }\n  }\n\n  break;\n}\n/* Opcode: ResetCount * * * * *\n**\n** The value of the change counter is copied to the database handle\n** change counter (returned by subsequent calls to sqlite3_changes()).\n** Then the VMs internal change counter resets to 0.\n** This is used by trigger programs.\n*/\ncase OP_ResetCount: {\n  sqlite3VdbeSetChanges(db, p->nChange);\n  p->nChange = 0;\n  break;\n}\n\n/* Opcode: SorterCompare P1 P2 P3 P4\n** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2\n**\n** P1 is a sorter cursor. This instruction compares a prefix of the\n** record blob in register P3 against a prefix of the entry that \n** the sorter cursor currently points to.  Only the first P4 fields\n** of r[P3] and the sorter record are compared.\n**\n** If either P3 or the sorter contains a NULL in one of their significant\n** fields (not counting the P4 fields at the end which are ignored) then\n** the comparison is assumed to be equal.\n**\n** Fall through to next instruction if the two records compare equal to\n** each other.  Jump to P2 if they are different.\n*/\ncase OP_SorterCompare: {\n  VdbeCursor *pC;\n  int res;\n  int nKeyCol;\n\n  pC = p->apCsr[pOp->p1];\n  assert( isSorter(pC) );\n  assert( pOp->p4type==P4_INT32 );\n  pIn3 = &aMem[pOp->p3];\n  nKeyCol = pOp->p4.i;\n  res = 0;\n  rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);\n  VdbeBranchTaken(res!=0,2);\n  if( rc ) goto abort_due_to_error;\n  if( res ) goto jump_to_p2;\n  break;\n};\n\n/* Opcode: SorterData P1 P2 P3 * *\n** Synopsis: r[P2]=data\n**\n** Write into register P2 the current sorter data for sorter cursor P1.\n** Then clear the column header cache on cursor P3.\n**\n** This opcode is normally use to move a record out of the sorter and into\n** a register that is the source for a pseudo-table cursor created using\n** OpenPseudo.  That pseudo-table cursor is the one that is identified by\n** parameter P3.  Clearing the P3 column cache as part of this opcode saves\n** us from having to issue a separate NullRow instruction to clear that cache.\n*/\ncase OP_SorterData: {\n  VdbeCursor *pC;\n\n  pOut = &aMem[pOp->p2];\n  pC = p->apCsr[pOp->p1];\n  assert( isSorter(pC) );\n  rc = sqlite3VdbeSorterRowkey(pC, pOut);\n  assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  if( rc ) goto abort_due_to_error;\n  p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;\n  break;\n}\n\n/* Opcode: RowData P1 P2 P3 * *\n** Synopsis: r[P2]=data\n**\n** Write into register P2 the complete row content for the row at \n** which cursor P1 is currently pointing.\n** There is no interpretation of the data.  \n** It is just copied onto the P2 register exactly as \n** it is found in the database file.\n**\n** If cursor P1 is an index, then the content is the key of the row.\n** If cursor P2 is a table, then the content extracted is the data.\n**\n** If the P1 cursor must be pointing to a valid row (not a NULL row)\n** of a real table, not a pseudo-table.\n**\n** If P3!=0 then this opcode is allowed to make an ephemeral pointer\n** into the database page.  That means that the content of the output\n** register will be invalidated as soon as the cursor moves - including\n** moves caused by other cursors that \"save\" the current cursors\n** position in order that they can write to the same table.  If P3==0\n** then a copy of the data is made into memory.  P3!=0 is faster, but\n** P3==0 is safer.\n**\n** If P3!=0 then the content of the P2 register is unsuitable for use\n** in OP_Result and any OP_Result will invalidate the P2 register content.\n** The P2 register content is invalidated by opcodes like OP_Function or\n** by any use of another cursor pointing to the same table.\n*/\ncase OP_RowData: {\n  VdbeCursor *pC;\n  BtCursor *pCrsr;\n  u32 n;\n\n  pOut = out2Prerelease(p, pOp);\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  assert( pC->eCurType==CURTYPE_BTREE );\n  assert( isSorter(pC)==0 );\n  assert( pC->nullRow==0 );\n  assert( pC->uc.pCursor!=0 );\n  pCrsr = pC->uc.pCursor;\n\n  /* The OP_RowData opcodes always follow OP_NotExists or\n  ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions\n  ** that might invalidate the cursor.\n  ** If this where not the case, on of the following assert()s\n  ** would fail.  Should this ever change (because of changes in the code\n  ** generator) then the fix would be to insert a call to\n  ** sqlite3VdbeCursorMoveto().\n  */\n  assert( pC->deferredMoveto==0 );\n  assert( sqlite3BtreeCursorIsValid(pCrsr) );\n#if 0  /* Not required due to the previous to assert() statements */\n  rc = sqlite3VdbeCursorMoveto(pC);\n  if( rc!=SQLITE_OK ) goto abort_due_to_error;\n#endif\n\n  n = sqlite3BtreePayloadSize(pCrsr);\n  if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){\n    goto too_big;\n  }\n  testcase( n==0 );\n  rc = sqlite3VdbeMemFromBtreeZeroOffset(pCrsr, n, pOut);\n  if( rc ) goto abort_due_to_error;\n  if( !pOp->p3 ) Deephemeralize(pOut);\n  UPDATE_MAX_BLOBSIZE(pOut);\n  REGISTER_TRACE(pOp->p2, pOut);\n  break;\n}\n\n/* Opcode: Rowid P1 P2 * * *\n** Synopsis: r[P2]=rowid\n**\n** Store in register P2 an integer which is the key of the table entry that\n** P1 is currently point to.\n**\n** P1 can be either an ordinary table or a virtual table.  There used to\n** be a separate OP_VRowid opcode for use with virtual tables, but this\n** one opcode now works for both table types.\n*/\ncase OP_Rowid: {                 /* out2 */\n  VdbeCursor *pC;\n  i64 v;\n  sqlite3_vtab *pVtab;\n  const sqlite3_module *pModule;\n\n  pOut = out2Prerelease(p, pOp);\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );\n  if( pC->nullRow ){\n    pOut->flags = MEM_Null;\n    break;\n  }else if( pC->deferredMoveto ){\n    v = pC->movetoTarget;\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  }else if( pC->eCurType==CURTYPE_VTAB ){\n    assert( pC->uc.pVCur!=0 );\n    pVtab = pC->uc.pVCur->pVtab;\n    pModule = pVtab->pModule;\n    assert( pModule->xRowid );\n    rc = pModule->xRowid(pC->uc.pVCur, &v);\n    sqlite3VtabImportErrmsg(p, pVtab);\n    if( rc ) goto abort_due_to_error;\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n  }else{\n    assert( pC->eCurType==CURTYPE_BTREE );\n    assert( pC->uc.pCursor!=0 );\n    rc = sqlite3VdbeCursorRestore(pC);\n    if( rc ) goto abort_due_to_error;\n    if( pC->nullRow ){\n      pOut->flags = MEM_Null;\n      break;\n    }\n    v = sqlite3BtreeIntegerKey(pC->uc.pCursor);\n  }\n  pOut->u.i = v;\n  break;\n}\n\n/* Opcode: NullRow P1 * * * *\n**\n** Move the cursor P1 to a null row.  Any OP_Column operations\n** that occur while the cursor is on the null row will always\n** write a NULL.\n*/\ncase OP_NullRow: {\n  VdbeCursor *pC;\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  pC->nullRow = 1;\n  pC->cacheStatus = CACHE_STALE;\n  if( pC->eCurType==CURTYPE_BTREE ){\n    assert( pC->uc.pCursor!=0 );\n    sqlite3BtreeClearCursor(pC->uc.pCursor);\n  }\n#ifdef SQLITE_DEBUG\n  if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;\n#endif\n  break;\n}\n\n/* Opcode: SeekEnd P1 * * * *\n**\n** Position cursor P1 at the end of the btree for the purpose of\n** appending a new entry onto the btree.\n**\n** It is assumed that the cursor is used only for appending and so\n** if the cursor is valid, then the cursor must already be pointing\n** at the end of the btree and so no changes are made to\n** the cursor.\n*/\n/* Opcode: Last P1 P2 * * *\n**\n** The next use of the Rowid or Column or Prev instruction for P1 \n** will refer to the last entry in the database table or index.\n** If the table or index is empty and P2>0, then jump immediately to P2.\n** If P2 is 0 or if the table or index is not empty, fall through\n** to the following instruction.\n**\n** This opcode leaves the cursor configured to move in reverse order,\n** from the end toward the beginning.  In other words, the cursor is\n** configured to use Prev, not Next.\n*/\ncase OP_SeekEnd:\ncase OP_Last: {        /* jump */\n  VdbeCursor *pC;\n  BtCursor *pCrsr;\n  int res;\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  assert( pC->eCurType==CURTYPE_BTREE );\n  pCrsr = pC->uc.pCursor;\n  res = 0;\n  assert( pCrsr!=0 );\n#ifdef SQLITE_DEBUG\n  pC->seekOp = pOp->opcode;\n#endif\n  if( pOp->opcode==OP_SeekEnd ){\n    assert( pOp->p2==0 );\n    pC->seekResult = -1;\n    if( sqlite3BtreeCursorIsValidNN(pCrsr) ){\n      break;\n    }\n  }\n  rc = sqlite3BtreeLast(pCrsr, &res);\n  pC->nullRow = (u8)res;\n  pC->deferredMoveto = 0;\n  pC->cacheStatus = CACHE_STALE;\n  if( rc ) goto abort_due_to_error;\n  if( pOp->p2>0 ){\n    VdbeBranchTaken(res!=0,2);\n    if( res ) goto jump_to_p2;\n  }\n  break;\n}\n\n/* Opcode: IfSmaller P1 P2 P3 * *\n**\n** Estimate the number of rows in the table P1.  Jump to P2 if that\n** estimate is less than approximately 2**(0.1*P3).\n*/\ncase OP_IfSmaller: {        /* jump */\n  VdbeCursor *pC;\n  BtCursor *pCrsr;\n  int res;\n  i64 sz;\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  pCrsr = pC->uc.pCursor;\n  assert( pCrsr );\n  rc = sqlite3BtreeFirst(pCrsr, &res);\n  if( rc ) goto abort_due_to_error;\n  if( res==0 ){\n    sz = sqlite3BtreeRowCountEst(pCrsr);\n    if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;\n  }\n  VdbeBranchTaken(res!=0,2);\n  if( res ) goto jump_to_p2;\n  break;\n}\n\n\n/* Opcode: SorterSort P1 P2 * * *\n**\n** After all records have been inserted into the Sorter object\n** identified by P1, invoke this opcode to actually do the sorting.\n** Jump to P2 if there are no records to be sorted.\n**\n** This opcode is an alias for OP_Sort and OP_Rewind that is used\n** for Sorter objects.\n*/\n/* Opcode: Sort P1 P2 * * *\n**\n** This opcode does exactly the same thing as OP_Rewind except that\n** it increments an undocumented global variable used for testing.\n**\n** Sorting is accomplished by writing records into a sorting index,\n** then rewinding that index and playing it back from beginning to\n** end.  We use the OP_Sort opcode instead of OP_Rewind to do the\n** rewinding so that the global variable will be incremented and\n** regression tests can determine whether or not the optimizer is\n** correctly optimizing out sorts.\n*/\ncase OP_SorterSort:    /* jump */\ncase OP_Sort: {        /* jump */\n#ifdef SQLITE_TEST\n  sqlite3_sort_count++;\n  sqlite3_search_count--;\n#endif\n  p->aCounter[SQLITE_STMTSTATUS_SORT]++;\n  /* Fall through into OP_Rewind */\n}\n/* Opcode: Rewind P1 P2 * * *\n**\n** The next use of the Rowid or Column or Next instruction for P1 \n** will refer to the first entry in the database table or index.\n** If the table or index is empty, jump immediately to P2.\n** If the table or index is not empty, fall through to the following \n** instruction.\n**\n** This opcode leaves the cursor configured to move in forward order,\n** from the beginning toward the end.  In other words, the cursor is\n** configured to use Next, not Prev.\n*/\ncase OP_Rewind: {        /* jump */\n  VdbeCursor *pC;\n  BtCursor *pCrsr;\n  int res;\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  assert( pOp->p5==0 );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );\n  res = 1;\n#ifdef SQLITE_DEBUG\n  pC->seekOp = OP_Rewind;\n#endif\n  if( isSorter(pC) ){\n    rc = sqlite3VdbeSorterRewind(pC, &res);\n  }else{\n    assert( pC->eCurType==CURTYPE_BTREE );\n    pCrsr = pC->uc.pCursor;\n    assert( pCrsr );\n    rc = sqlite3BtreeFirst(pCrsr, &res);\n    pC->deferredMoveto = 0;\n    pC->cacheStatus = CACHE_STALE;\n  }\n  if( rc ) goto abort_due_to_error;\n  pC->nullRow = (u8)res;\n  assert( pOp->p2>0 && pOp->p2<p->nOp );\n  VdbeBranchTaken(res!=0,2);\n  if( res ) goto jump_to_p2;\n  break;\n}\n\n/* Opcode: Next P1 P2 P3 P4 P5\n**\n** Advance cursor P1 so that it points to the next key/data pair in its\n** table or index.  If there are no more key/value pairs then fall through\n** to the following instruction.  But if the cursor advance was successful,\n** jump immediately to P2.\n**\n** The Next opcode is only valid following an SeekGT, SeekGE, or\n** OP_Rewind opcode used to position the cursor.  Next is not allowed\n** to follow SeekLT, SeekLE, or OP_Last.\n**\n** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have\n** been opened prior to this opcode or the program will segfault.\n**\n** The P3 value is a hint to the btree implementation. If P3==1, that\n** means P1 is an SQL index and that this instruction could have been\n** omitted if that index had been unique.  P3 is usually 0.  P3 is\n** always either 0 or 1.\n**\n** P4 is always of type P4_ADVANCE. The function pointer points to\n** sqlite3BtreeNext().\n**\n** If P5 is positive and the jump is taken, then event counter\n** number P5-1 in the prepared statement is incremented.\n**\n** See also: Prev\n*/\n/* Opcode: Prev P1 P2 P3 P4 P5\n**\n** Back up cursor P1 so that it points to the previous key/data pair in its\n** table or index.  If there is no previous key/value pairs then fall through\n** to the following instruction.  But if the cursor backup was successful,\n** jump immediately to P2.\n**\n**\n** The Prev opcode is only valid following an SeekLT, SeekLE, or\n** OP_Last opcode used to position the cursor.  Prev is not allowed\n** to follow SeekGT, SeekGE, or OP_Rewind.\n**\n** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is\n** not open then the behavior is undefined.\n**\n** The P3 value is a hint to the btree implementation. If P3==1, that\n** means P1 is an SQL index and that this instruction could have been\n** omitted if that index had been unique.  P3 is usually 0.  P3 is\n** always either 0 or 1.\n**\n** P4 is always of type P4_ADVANCE. The function pointer points to\n** sqlite3BtreePrevious().\n**\n** If P5 is positive and the jump is taken, then event counter\n** number P5-1 in the prepared statement is incremented.\n*/\n/* Opcode: SorterNext P1 P2 * * P5\n**\n** This opcode works just like OP_Next except that P1 must be a\n** sorter object for which the OP_SorterSort opcode has been\n** invoked.  This opcode advances the cursor to the next sorted\n** record, or jumps to P2 if there are no more sorted records.\n*/\ncase OP_SorterNext: {  /* jump */\n  VdbeCursor *pC;\n\n  pC = p->apCsr[pOp->p1];\n  assert( isSorter(pC) );\n  rc = sqlite3VdbeSorterNext(db, pC);\n  goto next_tail;\ncase OP_Prev:          /* jump */\ncase OP_Next:          /* jump */\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  assert( pOp->p5<ArraySize(p->aCounter) );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  assert( pC->deferredMoveto==0 );\n  assert( pC->eCurType==CURTYPE_BTREE );\n  assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );\n  assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );\n\n  /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found.\n  ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */\n  assert( pOp->opcode!=OP_Next\n       || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE\n       || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found\n       || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid\n       || pC->seekOp==OP_IfNoHope);\n  assert( pOp->opcode!=OP_Prev\n       || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE\n       || pC->seekOp==OP_Last   || pC->seekOp==OP_IfNoHope\n       || pC->seekOp==OP_NullRow);\n\n  rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);\nnext_tail:\n  pC->cacheStatus = CACHE_STALE;\n  VdbeBranchTaken(rc==SQLITE_OK,2);\n  if( rc==SQLITE_OK ){\n    pC->nullRow = 0;\n    p->aCounter[pOp->p5]++;\n#ifdef SQLITE_TEST\n    sqlite3_search_count++;\n#endif\n    goto jump_to_p2_and_check_for_interrupt;\n  }\n  if( rc!=SQLITE_DONE ) goto abort_due_to_error;\n  rc = SQLITE_OK;\n  pC->nullRow = 1;\n  goto check_for_interrupt;\n}\n\n/* Opcode: IdxInsert P1 P2 P3 P4 P5\n** Synopsis: key=r[P2]\n**\n** Register P2 holds an SQL index key made using the\n** MakeRecord instructions.  This opcode writes that key\n** into the index P1.  Data for the entry is nil.\n**\n** If P4 is not zero, then it is the number of values in the unpacked\n** key of reg(P2).  In that case, P3 is the index of the first register\n** for the unpacked key.  The availability of the unpacked key can sometimes\n** be an optimization.\n**\n** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer\n** that this insert is likely to be an append.\n**\n** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is\n** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,\n** then the change counter is unchanged.\n**\n** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might\n** run faster by avoiding an unnecessary seek on cursor P1.  However,\n** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior\n** seeks on the cursor or if the most recent seek used a key equivalent\n** to P2. \n**\n** This instruction only works for indices.  The equivalent instruction\n** for tables is OP_Insert.\n*/\ncase OP_IdxInsert: {        /* in2 */\n  VdbeCursor *pC;\n  BtreePayload x;\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  sqlite3VdbeIncrWriteCounter(p, pC);\n  assert( pC!=0 );\n  assert( !isSorter(pC) );\n  pIn2 = &aMem[pOp->p2];\n  assert( pIn2->flags & MEM_Blob );\n  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;\n  assert( pC->eCurType==CURTYPE_BTREE );\n  assert( pC->isTable==0 );\n  rc = ExpandBlob(pIn2);\n  if( rc ) goto abort_due_to_error;\n  x.nKey = pIn2->n;\n  x.pKey = pIn2->z;\n  x.aMem = aMem + pOp->p3;\n  x.nMem = (u16)pOp->p4.i;\n  rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,\n       (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), \n      ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)\n      );\n  assert( pC->deferredMoveto==0 );\n  pC->cacheStatus = CACHE_STALE;\n  if( rc) goto abort_due_to_error;\n  break;\n}\n\n/* Opcode: SorterInsert P1 P2 * * *\n** Synopsis: key=r[P2]\n**\n** Register P2 holds an SQL index key made using the\n** MakeRecord instructions.  This opcode writes that key\n** into the sorter P1.  Data for the entry is nil.\n*/\ncase OP_SorterInsert: {     /* in2 */\n  VdbeCursor *pC;\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  sqlite3VdbeIncrWriteCounter(p, pC);\n  assert( pC!=0 );\n  assert( isSorter(pC) );\n  pIn2 = &aMem[pOp->p2];\n  assert( pIn2->flags & MEM_Blob );\n  assert( pC->isTable==0 );\n  rc = ExpandBlob(pIn2);\n  if( rc ) goto abort_due_to_error;\n  rc = sqlite3VdbeSorterWrite(pC, pIn2);\n  if( rc) goto abort_due_to_error;\n  break;\n}\n\n/* Opcode: IdxDelete P1 P2 P3 * P5\n** Synopsis: key=r[P2@P3]\n**\n** The content of P3 registers starting at register P2 form\n** an unpacked index key. This opcode removes that entry from the \n** index opened by cursor P1.\n**\n** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error\n** if no matching index entry is found.  This happens when running\n** an UPDATE or DELETE statement and the index entry to be updated\n** or deleted is not found.  For some uses of IdxDelete\n** (example:  the EXCEPT operator) it does not matter that no matching\n** entry is found.  For those cases, P5 is zero.\n*/\ncase OP_IdxDelete: {\n  VdbeCursor *pC;\n  BtCursor *pCrsr;\n  int res;\n  UnpackedRecord r;\n\n  assert( pOp->p3>0 );\n  assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  assert( pC->eCurType==CURTYPE_BTREE );\n  sqlite3VdbeIncrWriteCounter(p, pC);\n  pCrsr = pC->uc.pCursor;\n  assert( pCrsr!=0 );\n  r.pKeyInfo = pC->pKeyInfo;\n  r.nField = (u16)pOp->p3;\n  r.default_rc = 0;\n  r.aMem = &aMem[pOp->p2];\n  rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);\n  if( rc ) goto abort_due_to_error;\n  if( res==0 ){\n    rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);\n    if( rc ) goto abort_due_to_error;\n  }else if( pOp->p5 ){\n    rc = SQLITE_CORRUPT_INDEX;\n    goto abort_due_to_error;\n  }\n  assert( pC->deferredMoveto==0 );\n  pC->cacheStatus = CACHE_STALE;\n  pC->seekResult = 0;\n  break;\n}\n\n/* Opcode: DeferredSeek P1 * P3 P4 *\n** Synopsis: Move P3 to P1.rowid if needed\n**\n** P1 is an open index cursor and P3 is a cursor on the corresponding\n** table.  This opcode does a deferred seek of the P3 table cursor\n** to the row that corresponds to the current row of P1.\n**\n** This is a deferred seek.  Nothing actually happens until\n** the cursor is used to read a record.  That way, if no reads\n** occur, no unnecessary I/O happens.\n**\n** P4 may be an array of integers (type P4_INTARRAY) containing\n** one entry for each column in the P3 table.  If array entry a(i)\n** is non-zero, then reading column a(i)-1 from cursor P3 is \n** equivalent to performing the deferred seek and then reading column i \n** from P1.  This information is stored in P3 and used to redirect\n** reads against P3 over to P1, thus possibly avoiding the need to\n** seek and read cursor P3.\n*/\n/* Opcode: IdxRowid P1 P2 * * *\n** Synopsis: r[P2]=rowid\n**\n** Write into register P2 an integer which is the last entry in the record at\n** the end of the index key pointed to by cursor P1.  This integer should be\n** the rowid of the table entry to which this index entry points.\n**\n** See also: Rowid, MakeRecord.\n*/\ncase OP_DeferredSeek:\ncase OP_IdxRowid: {           /* out2 */\n  VdbeCursor *pC;             /* The P1 index cursor */\n  VdbeCursor *pTabCur;        /* The P2 table cursor (OP_DeferredSeek only) */\n  i64 rowid;                  /* Rowid that P1 current points to */\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  assert( pC->eCurType==CURTYPE_BTREE );\n  assert( pC->uc.pCursor!=0 );\n  assert( pC->isTable==0 );\n  assert( pC->deferredMoveto==0 );\n  assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );\n\n  /* The IdxRowid and Seek opcodes are combined because of the commonality\n  ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */\n  rc = sqlite3VdbeCursorRestore(pC);\n\n  /* sqlite3VbeCursorRestore() can only fail if the record has been deleted\n  ** out from under the cursor.  That will never happens for an IdxRowid\n  ** or Seek opcode */\n  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;\n\n  if( !pC->nullRow ){\n    rowid = 0;  /* Not needed.  Only used to silence a warning. */\n    rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);\n    if( rc!=SQLITE_OK ){\n      goto abort_due_to_error;\n    }\n    if( pOp->opcode==OP_DeferredSeek ){\n      assert( pOp->p3>=0 && pOp->p3<p->nCursor );\n      pTabCur = p->apCsr[pOp->p3];\n      assert( pTabCur!=0 );\n      assert( pTabCur->eCurType==CURTYPE_BTREE );\n      assert( pTabCur->uc.pCursor!=0 );\n      assert( pTabCur->isTable );\n      pTabCur->nullRow = 0;\n      pTabCur->movetoTarget = rowid;\n      pTabCur->deferredMoveto = 1;\n      assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );\n      pTabCur->aAltMap = pOp->p4.ai;\n      pTabCur->pAltCursor = pC;\n    }else{\n      pOut = out2Prerelease(p, pOp);\n      pOut->u.i = rowid;\n    }\n  }else{\n    assert( pOp->opcode==OP_IdxRowid );\n    sqlite3VdbeMemSetNull(&aMem[pOp->p2]);\n  }\n  break;\n}\n\n/* Opcode: FinishSeek P1 * * * *\n** \n** If cursor P1 was previously moved via OP_DeferredSeek, complete that\n** seek operation now, without further delay.  If the cursor seek has\n** already occurred, this instruction is a no-op.\n*/\ncase OP_FinishSeek: {\n  VdbeCursor *pC;             /* The P1 index cursor */\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  if( pC->deferredMoveto ){\n    rc = sqlite3VdbeFinishMoveto(pC);\n    if( rc ) goto abort_due_to_error;\n  }\n  break;\n}\n\n/* Opcode: IdxGE P1 P2 P3 P4 P5\n** Synopsis: key=r[P3@P4]\n**\n** The P4 register values beginning with P3 form an unpacked index \n** key that omits the PRIMARY KEY.  Compare this key value against the index \n** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID \n** fields at the end.\n**\n** If the P1 index entry is greater than or equal to the key value\n** then jump to P2.  Otherwise fall through to the next instruction.\n*/\n/* Opcode: IdxGT P1 P2 P3 P4 P5\n** Synopsis: key=r[P3@P4]\n**\n** The P4 register values beginning with P3 form an unpacked index \n** key that omits the PRIMARY KEY.  Compare this key value against the index \n** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID \n** fields at the end.\n**\n** If the P1 index entry is greater than the key value\n** then jump to P2.  Otherwise fall through to the next instruction.\n*/\n/* Opcode: IdxLT P1 P2 P3 P4 P5\n** Synopsis: key=r[P3@P4]\n**\n** The P4 register values beginning with P3 form an unpacked index \n** key that omits the PRIMARY KEY or ROWID.  Compare this key value against\n** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or\n** ROWID on the P1 index.\n**\n** If the P1 index entry is less than the key value then jump to P2.\n** Otherwise fall through to the next instruction.\n*/\n/* Opcode: IdxLE P1 P2 P3 P4 P5\n** Synopsis: key=r[P3@P4]\n**\n** The P4 register values beginning with P3 form an unpacked index \n** key that omits the PRIMARY KEY or ROWID.  Compare this key value against\n** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or\n** ROWID on the P1 index.\n**\n** If the P1 index entry is less than or equal to the key value then jump\n** to P2. Otherwise fall through to the next instruction.\n*/\ncase OP_IdxLE:          /* jump */\ncase OP_IdxGT:          /* jump */\ncase OP_IdxLT:          /* jump */\ncase OP_IdxGE:  {       /* jump */\n  VdbeCursor *pC;\n  int res;\n  UnpackedRecord r;\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  assert( pC->isOrdered );\n  assert( pC->eCurType==CURTYPE_BTREE );\n  assert( pC->uc.pCursor!=0);\n  assert( pC->deferredMoveto==0 );\n  assert( pOp->p5==0 || pOp->p5==1 );\n  assert( pOp->p4type==P4_INT32 );\n  r.pKeyInfo = pC->pKeyInfo;\n  r.nField = (u16)pOp->p4.i;\n  if( pOp->opcode<OP_IdxLT ){\n    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );\n    r.default_rc = -1;\n  }else{\n    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );\n    r.default_rc = 0;\n  }\n  r.aMem = &aMem[pOp->p3];\n#ifdef SQLITE_DEBUG\n  {\n    int i;\n    for(i=0; i<r.nField; i++){\n      assert( memIsValid(&r.aMem[i]) );\n      REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);\n    }\n  }\n#endif\n  res = 0;  /* Not needed.  Only used to silence a warning. */\n  rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);\n  assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );\n  if( (pOp->opcode&1)==(OP_IdxLT&1) ){\n    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );\n    res = -res;\n  }else{\n    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );\n    res++;\n  }\n  VdbeBranchTaken(res>0,2);\n  if( rc ) goto abort_due_to_error;\n  if( res>0 ) goto jump_to_p2;\n  break;\n}\n\n/* Opcode: Destroy P1 P2 P3 * *\n**\n** Delete an entire database table or index whose root page in the database\n** file is given by P1.\n**\n** The table being destroyed is in the main database file if P3==0.  If\n** P3==1 then the table to be clear is in the auxiliary database file\n** that is used to store tables create using CREATE TEMPORARY TABLE.\n**\n** If AUTOVACUUM is enabled then it is possible that another root page\n** might be moved into the newly deleted root page in order to keep all\n** root pages contiguous at the beginning of the database.  The former\n** value of the root page that moved - its value before the move occurred -\n** is stored in register P2. If no page movement was required (because the\n** table being dropped was already the last one in the database) then a \n** zero is stored in register P2.  If AUTOVACUUM is disabled then a zero \n** is stored in register P2.\n**\n** This opcode throws an error if there are any active reader VMs when\n** it is invoked. This is done to avoid the difficulty associated with \n** updating existing cursors when a root page is moved in an AUTOVACUUM \n** database. This error is thrown even if the database is not an AUTOVACUUM \n** db in order to avoid introducing an incompatibility between autovacuum \n** and non-autovacuum modes.\n**\n** See also: Clear\n*/\ncase OP_Destroy: {     /* out2 */\n  int iMoved;\n  int iDb;\n\n  sqlite3VdbeIncrWriteCounter(p, 0);\n  assert( p->readOnly==0 );\n  assert( pOp->p1>1 );\n  pOut = out2Prerelease(p, pOp);\n  pOut->flags = MEM_Null;\n  if( db->nVdbeRead > db->nVDestroy+1 ){\n    rc = SQLITE_LOCKED;\n    p->errorAction = OE_Abort;\n    goto abort_due_to_error;\n  }else{\n    iDb = pOp->p3;\n    assert( DbMaskTest(p->btreeMask, iDb) );\n    iMoved = 0;  /* Not needed.  Only to silence a warning. */\n    rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);\n    pOut->flags = MEM_Int;\n    pOut->u.i = iMoved;\n    if( rc ) goto abort_due_to_error;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( iMoved!=0 ){\n      sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);\n      /* All OP_Destroy operations occur on the same btree */\n      assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );\n      resetSchemaOnFault = iDb+1;\n    }\n#endif\n  }\n  break;\n}\n\n/* Opcode: Clear P1 P2 P3\n**\n** Delete all contents of the database table or index whose root page\n** in the database file is given by P1.  But, unlike Destroy, do not\n** remove the table or index from the database file.\n**\n** The table being clear is in the main database file if P2==0.  If\n** P2==1 then the table to be clear is in the auxiliary database file\n** that is used to store tables create using CREATE TEMPORARY TABLE.\n**\n** If the P3 value is non-zero, then the table referred to must be an\n** intkey table (an SQL table, not an index). In this case the row change \n** count is incremented by the number of rows in the table being cleared. \n** If P3 is greater than zero, then the value stored in register P3 is\n** also incremented by the number of rows in the table being cleared.\n**\n** See also: Destroy\n*/\ncase OP_Clear: {\n  int nChange;\n \n  sqlite3VdbeIncrWriteCounter(p, 0);\n  nChange = 0;\n  assert( p->readOnly==0 );\n  assert( DbMaskTest(p->btreeMask, pOp->p2) );\n  rc = sqlite3BtreeClearTable(\n      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)\n  );\n  if( pOp->p3 ){\n    p->nChange += nChange;\n    if( pOp->p3>0 ){\n      assert( memIsValid(&aMem[pOp->p3]) );\n      memAboutToChange(p, &aMem[pOp->p3]);\n      aMem[pOp->p3].u.i += nChange;\n    }\n  }\n  if( rc ) goto abort_due_to_error;\n  break;\n}\n\n/* Opcode: ResetSorter P1 * * * *\n**\n** Delete all contents from the ephemeral table or sorter\n** that is open on cursor P1.\n**\n** This opcode only works for cursors used for sorting and\n** opened with OP_OpenEphemeral or OP_SorterOpen.\n*/\ncase OP_ResetSorter: {\n  VdbeCursor *pC;\n \n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  if( isSorter(pC) ){\n    sqlite3VdbeSorterReset(db, pC->uc.pSorter);\n  }else{\n    assert( pC->eCurType==CURTYPE_BTREE );\n    assert( pC->isEphemeral );\n    rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);\n    if( rc ) goto abort_due_to_error;\n  }\n  break;\n}\n\n/* Opcode: CreateBtree P1 P2 P3 * *\n** Synopsis: r[P2]=root iDb=P1 flags=P3\n**\n** Allocate a new b-tree in the main database file if P1==0 or in the\n** TEMP database file if P1==1 or in an attached database if\n** P1>1.  The P3 argument must be 1 (BTREE_INTKEY) for a rowid table\n** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.\n** The root page number of the new b-tree is stored in register P2.\n*/\ncase OP_CreateBtree: {          /* out2 */\n  int pgno;\n  Db *pDb;\n\n  sqlite3VdbeIncrWriteCounter(p, 0);\n  pOut = out2Prerelease(p, pOp);\n  pgno = 0;\n  assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );\n  assert( pOp->p1>=0 && pOp->p1<db->nDb );\n  assert( DbMaskTest(p->btreeMask, pOp->p1) );\n  assert( p->readOnly==0 );\n  pDb = &db->aDb[pOp->p1];\n  assert( pDb->pBt!=0 );\n  rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);\n  if( rc ) goto abort_due_to_error;\n  pOut->u.i = pgno;\n  break;\n}\n\n/* Opcode: SqlExec * * * P4 *\n**\n** Run the SQL statement or statements specified in the P4 string.\n*/\ncase OP_SqlExec: {\n  sqlite3VdbeIncrWriteCounter(p, 0);\n  db->nSqlExec++;\n  rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);\n  db->nSqlExec--;\n  if( rc ) goto abort_due_to_error;\n  break;\n}\n\n/* Opcode: ParseSchema P1 * * P4 *\n**\n** Read and parse all entries from the SQLITE_MASTER table of database P1\n** that match the WHERE clause P4.  If P4 is a NULL pointer, then the\n** entire schema for P1 is reparsed.\n**\n** This opcode invokes the parser to create a new virtual machine,\n** then runs the new virtual machine.  It is thus a re-entrant opcode.\n*/\ncase OP_ParseSchema: {\n  int iDb;\n  const char *zMaster;\n  char *zSql;\n  InitData initData;\n\n  /* Any prepared statement that invokes this opcode will hold mutexes\n  ** on every btree.  This is a prerequisite for invoking \n  ** sqlite3InitCallback().\n  */\n#ifdef SQLITE_DEBUG\n  for(iDb=0; iDb<db->nDb; iDb++){\n    assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );\n  }\n#endif\n\n  iDb = pOp->p1;\n  assert( iDb>=0 && iDb<db->nDb );\n  assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );\n\n#ifndef SQLITE_OMIT_ALTERTABLE\n  if( pOp->p4.z==0 ){\n    sqlite3SchemaClear(db->aDb[iDb].pSchema);\n    db->mDbFlags &= ~DBFLAG_SchemaKnownOk;\n    rc = sqlite3InitOne(db, iDb, &p->zErrMsg, INITFLAG_AlterTable);\n    db->mDbFlags |= DBFLAG_SchemaChange;\n    p->expired = 0;\n  }else\n#endif\n  {\n    zMaster = MASTER_NAME;\n    initData.db = db;\n    initData.iDb = iDb;\n    initData.pzErrMsg = &p->zErrMsg;\n    initData.mInitFlags = 0;\n    zSql = sqlite3MPrintf(db,\n       \"SELECT*FROM\\\"%w\\\".%s WHERE %s ORDER BY rowid\",\n       db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);\n    if( zSql==0 ){\n      rc = SQLITE_NOMEM_BKPT;\n    }else{\n      assert( db->init.busy==0 );\n      db->init.busy = 1;\n      initData.rc = SQLITE_OK;\n      initData.nInitRow = 0;\n      assert( !db->mallocFailed );\n      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);\n      if( rc==SQLITE_OK ) rc = initData.rc;\n      if( rc==SQLITE_OK && initData.nInitRow==0 ){\n        /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse\n        ** at least one SQL statement. Any less than that indicates that\n        ** the sqlite_master table is corrupt. */\n        rc = SQLITE_CORRUPT_BKPT;\n      }\n      sqlite3DbFreeNN(db, zSql);\n      db->init.busy = 0;\n    }\n  }\n  if( rc ){\n    sqlite3ResetAllSchemasOfConnection(db);\n    if( rc==SQLITE_NOMEM ){\n      goto no_mem;\n    }\n    goto abort_due_to_error;\n  }\n  break;  \n}\n\n#if !defined(SQLITE_OMIT_ANALYZE)\n/* Opcode: LoadAnalysis P1 * * * *\n**\n** Read the sqlite_stat1 table for database P1 and load the content\n** of that table into the internal index hash table.  This will cause\n** the analysis to be used when preparing all subsequent queries.\n*/\ncase OP_LoadAnalysis: {\n  assert( pOp->p1>=0 && pOp->p1<db->nDb );\n  rc = sqlite3AnalysisLoad(db, pOp->p1);\n  if( rc ) goto abort_due_to_error;\n  break;  \n}\n#endif /* !defined(SQLITE_OMIT_ANALYZE) */\n\n/* Opcode: DropTable P1 * * P4 *\n**\n** Remove the internal (in-memory) data structures that describe\n** the table named P4 in database P1.  This is called after a table\n** is dropped from disk (using the Destroy opcode) in order to keep \n** the internal representation of the\n** schema consistent with what is on disk.\n*/\ncase OP_DropTable: {\n  sqlite3VdbeIncrWriteCounter(p, 0);\n  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);\n  break;\n}\n\n/* Opcode: DropIndex P1 * * P4 *\n**\n** Remove the internal (in-memory) data structures that describe\n** the index named P4 in database P1.  This is called after an index\n** is dropped from disk (using the Destroy opcode)\n** in order to keep the internal representation of the\n** schema consistent with what is on disk.\n*/\ncase OP_DropIndex: {\n  sqlite3VdbeIncrWriteCounter(p, 0);\n  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);\n  break;\n}\n\n/* Opcode: DropTrigger P1 * * P4 *\n**\n** Remove the internal (in-memory) data structures that describe\n** the trigger named P4 in database P1.  This is called after a trigger\n** is dropped from disk (using the Destroy opcode) in order to keep \n** the internal representation of the\n** schema consistent with what is on disk.\n*/\ncase OP_DropTrigger: {\n  sqlite3VdbeIncrWriteCounter(p, 0);\n  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);\n  break;\n}\n\n\n#ifndef SQLITE_OMIT_INTEGRITY_CHECK\n/* Opcode: IntegrityCk P1 P2 P3 P4 P5\n**\n** Do an analysis of the currently open database.  Store in\n** register P1 the text of an error message describing any problems.\n** If no problems are found, store a NULL in register P1.\n**\n** The register P3 contains one less than the maximum number of allowed errors.\n** At most reg(P3) errors will be reported.\n** In other words, the analysis stops as soon as reg(P1) errors are \n** seen.  Reg(P1) is updated with the number of errors remaining.\n**\n** The root page numbers of all tables in the database are integers\n** stored in P4_INTARRAY argument.\n**\n** If P5 is not zero, the check is done on the auxiliary database\n** file, not the main database file.\n**\n** This opcode is used to implement the integrity_check pragma.\n*/\ncase OP_IntegrityCk: {\n  int nRoot;      /* Number of tables to check.  (Number of root pages.) */\n  int *aRoot;     /* Array of rootpage numbers for tables to be checked */\n  int nErr;       /* Number of errors reported */\n  char *z;        /* Text of the error report */\n  Mem *pnErr;     /* Register keeping track of errors remaining */\n\n  assert( p->bIsReader );\n  nRoot = pOp->p2;\n  aRoot = pOp->p4.ai;\n  assert( nRoot>0 );\n  assert( aRoot[0]==nRoot );\n  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );\n  pnErr = &aMem[pOp->p3];\n  assert( (pnErr->flags & MEM_Int)!=0 );\n  assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );\n  pIn1 = &aMem[pOp->p1];\n  assert( pOp->p5<db->nDb );\n  assert( DbMaskTest(p->btreeMask, pOp->p5) );\n  z = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,\n                                 (int)pnErr->u.i+1, &nErr);\n  sqlite3VdbeMemSetNull(pIn1);\n  if( nErr==0 ){\n    assert( z==0 );\n  }else if( z==0 ){\n    goto no_mem;\n  }else{\n    pnErr->u.i -= nErr-1;\n    sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);\n  }\n  UPDATE_MAX_BLOBSIZE(pIn1);\n  sqlite3VdbeChangeEncoding(pIn1, encoding);\n  goto check_for_interrupt;\n}\n#endif /* SQLITE_OMIT_INTEGRITY_CHECK */\n\n/* Opcode: RowSetAdd P1 P2 * * *\n** Synopsis: rowset(P1)=r[P2]\n**\n** Insert the integer value held by register P2 into a RowSet object\n** held in register P1.\n**\n** An assertion fails if P2 is not an integer.\n*/\ncase OP_RowSetAdd: {       /* in1, in2 */\n  pIn1 = &aMem[pOp->p1];\n  pIn2 = &aMem[pOp->p2];\n  assert( (pIn2->flags & MEM_Int)!=0 );\n  if( (pIn1->flags & MEM_Blob)==0 ){\n    if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;\n  }\n  assert( sqlite3VdbeMemIsRowSet(pIn1) );\n  sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);\n  break;\n}\n\n/* Opcode: RowSetRead P1 P2 P3 * *\n** Synopsis: r[P3]=rowset(P1)\n**\n** Extract the smallest value from the RowSet object in P1\n** and put that value into register P3.\n** Or, if RowSet object P1 is initially empty, leave P3\n** unchanged and jump to instruction P2.\n*/\ncase OP_RowSetRead: {       /* jump, in1, out3 */\n  i64 val;\n\n  pIn1 = &aMem[pOp->p1];\n  assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );\n  if( (pIn1->flags & MEM_Blob)==0 \n   || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0\n  ){\n    /* The boolean index is empty */\n    sqlite3VdbeMemSetNull(pIn1);\n    VdbeBranchTaken(1,2);\n    goto jump_to_p2_and_check_for_interrupt;\n  }else{\n    /* A value was pulled from the index */\n    VdbeBranchTaken(0,2);\n    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);\n  }\n  goto check_for_interrupt;\n}\n\n/* Opcode: RowSetTest P1 P2 P3 P4\n** Synopsis: if r[P3] in rowset(P1) goto P2\n**\n** Register P3 is assumed to hold a 64-bit integer value. If register P1\n** contains a RowSet object and that RowSet object contains\n** the value held in P3, jump to register P2. Otherwise, insert the\n** integer in P3 into the RowSet and continue on to the\n** next opcode.\n**\n** The RowSet object is optimized for the case where sets of integers\n** are inserted in distinct phases, which each set contains no duplicates.\n** Each set is identified by a unique P4 value. The first set\n** must have P4==0, the final set must have P4==-1, and for all other sets\n** must have P4>0.\n**\n** This allows optimizations: (a) when P4==0 there is no need to test\n** the RowSet object for P3, as it is guaranteed not to contain it,\n** (b) when P4==-1 there is no need to insert the value, as it will\n** never be tested for, and (c) when a value that is part of set X is\n** inserted, there is no need to search to see if the same value was\n** previously inserted as part of set X (only if it was previously\n** inserted as part of some other set).\n*/\ncase OP_RowSetTest: {                     /* jump, in1, in3 */\n  int iSet;\n  int exists;\n\n  pIn1 = &aMem[pOp->p1];\n  pIn3 = &aMem[pOp->p3];\n  iSet = pOp->p4.i;\n  assert( pIn3->flags&MEM_Int );\n\n  /* If there is anything other than a rowset object in memory cell P1,\n  ** delete it now and initialize P1 with an empty rowset\n  */\n  if( (pIn1->flags & MEM_Blob)==0 ){\n    if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;\n  }\n  assert( sqlite3VdbeMemIsRowSet(pIn1) );\n  assert( pOp->p4type==P4_INT32 );\n  assert( iSet==-1 || iSet>=0 );\n  if( iSet ){\n    exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);\n    VdbeBranchTaken(exists!=0,2);\n    if( exists ) goto jump_to_p2;\n  }\n  if( iSet>=0 ){\n    sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);\n  }\n  break;\n}\n\n\n#ifndef SQLITE_OMIT_TRIGGER\n\n/* Opcode: Program P1 P2 P3 P4 P5\n**\n** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). \n**\n** P1 contains the address of the memory cell that contains the first memory \n** cell in an array of values used as arguments to the sub-program. P2 \n** contains the address to jump to if the sub-program throws an IGNORE \n** exception using the RAISE() function. Register P3 contains the address \n** of a memory cell in this (the parent) VM that is used to allocate the \n** memory required by the sub-vdbe at runtime.\n**\n** P4 is a pointer to the VM containing the trigger program.\n**\n** If P5 is non-zero, then recursive program invocation is enabled.\n*/\ncase OP_Program: {        /* jump */\n  int nMem;               /* Number of memory registers for sub-program */\n  int nByte;              /* Bytes of runtime space required for sub-program */\n  Mem *pRt;               /* Register to allocate runtime space */\n  Mem *pMem;              /* Used to iterate through memory cells */\n  Mem *pEnd;              /* Last memory cell in new array */\n  VdbeFrame *pFrame;      /* New vdbe frame to execute in */\n  SubProgram *pProgram;   /* Sub-program to execute */\n  void *t;                /* Token identifying trigger */\n\n  pProgram = pOp->p4.pProgram;\n  pRt = &aMem[pOp->p3];\n  assert( pProgram->nOp>0 );\n  \n  /* If the p5 flag is clear, then recursive invocation of triggers is \n  ** disabled for backwards compatibility (p5 is set if this sub-program\n  ** is really a trigger, not a foreign key action, and the flag set\n  ** and cleared by the \"PRAGMA recursive_triggers\" command is clear).\n  ** \n  ** It is recursive invocation of triggers, at the SQL level, that is \n  ** disabled. In some cases a single trigger may generate more than one \n  ** SubProgram (if the trigger may be executed with more than one different \n  ** ON CONFLICT algorithm). SubProgram structures associated with a\n  ** single trigger all have the same value for the SubProgram.token \n  ** variable.  */\n  if( pOp->p5 ){\n    t = pProgram->token;\n    for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);\n    if( pFrame ) break;\n  }\n\n  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){\n    rc = SQLITE_ERROR;\n    sqlite3VdbeError(p, \"too many levels of trigger recursion\");\n    goto abort_due_to_error;\n  }\n\n  /* Register pRt is used to store the memory required to save the state\n  ** of the current program, and the memory required at runtime to execute\n  ** the trigger program. If this trigger has been fired before, then pRt \n  ** is already allocated. Otherwise, it must be initialized.  */\n  if( (pRt->flags&MEM_Blob)==0 ){\n    /* SubProgram.nMem is set to the number of memory cells used by the \n    ** program stored in SubProgram.aOp. As well as these, one memory\n    ** cell is required for each cursor used by the program. Set local\n    ** variable nMem (and later, VdbeFrame.nChildMem) to this value.\n    */\n    nMem = pProgram->nMem + pProgram->nCsr;\n    assert( nMem>0 );\n    if( pProgram->nCsr==0 ) nMem++;\n    nByte = ROUND8(sizeof(VdbeFrame))\n              + nMem * sizeof(Mem)\n              + pProgram->nCsr * sizeof(VdbeCursor*)\n              + (pProgram->nOp + 7)/8;\n    pFrame = sqlite3DbMallocZero(db, nByte);\n    if( !pFrame ){\n      goto no_mem;\n    }\n    sqlite3VdbeMemRelease(pRt);\n    pRt->flags = MEM_Blob|MEM_Dyn;\n    pRt->z = (char*)pFrame;\n    pRt->n = nByte;\n    pRt->xDel = sqlite3VdbeFrameMemDel;\n\n    pFrame->v = p;\n    pFrame->nChildMem = nMem;\n    pFrame->nChildCsr = pProgram->nCsr;\n    pFrame->pc = (int)(pOp - aOp);\n    pFrame->aMem = p->aMem;\n    pFrame->nMem = p->nMem;\n    pFrame->apCsr = p->apCsr;\n    pFrame->nCursor = p->nCursor;\n    pFrame->aOp = p->aOp;\n    pFrame->nOp = p->nOp;\n    pFrame->token = pProgram->token;\n#ifdef SQLITE_ENABLE_STMT_SCANSTATUS\n    pFrame->anExec = p->anExec;\n#endif\n#ifdef SQLITE_DEBUG\n    pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;\n#endif\n\n    pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];\n    for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){\n      pMem->flags = MEM_Undefined;\n      pMem->db = db;\n    }\n  }else{\n    pFrame = (VdbeFrame*)pRt->z;\n    assert( pRt->xDel==sqlite3VdbeFrameMemDel );\n    assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem \n        || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );\n    assert( pProgram->nCsr==pFrame->nChildCsr );\n    assert( (int)(pOp - aOp)==pFrame->pc );\n  }\n\n  p->nFrame++;\n  pFrame->pParent = p->pFrame;\n  pFrame->lastRowid = db->lastRowid;\n  pFrame->nChange = p->nChange;\n  pFrame->nDbChange = p->db->nChange;\n  assert( pFrame->pAuxData==0 );\n  pFrame->pAuxData = p->pAuxData;\n  p->pAuxData = 0;\n  p->nChange = 0;\n  p->pFrame = pFrame;\n  p->aMem = aMem = VdbeFrameMem(pFrame);\n  p->nMem = pFrame->nChildMem;\n  p->nCursor = (u16)pFrame->nChildCsr;\n  p->apCsr = (VdbeCursor **)&aMem[p->nMem];\n  pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];\n  memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);\n  p->aOp = aOp = pProgram->aOp;\n  p->nOp = pProgram->nOp;\n#ifdef SQLITE_ENABLE_STMT_SCANSTATUS\n  p->anExec = 0;\n#endif\n#ifdef SQLITE_DEBUG\n  /* Verify that second and subsequent executions of the same trigger do not\n  ** try to reuse register values from the first use. */\n  {\n    int i;\n    for(i=0; i<p->nMem; i++){\n      aMem[i].pScopyFrom = 0;  /* Prevent false-positive AboutToChange() errs */\n      MemSetTypeFlag(&aMem[i], MEM_Undefined); /* Fault if this reg is reused */\n    }\n  }\n#endif\n  pOp = &aOp[-1];\n  goto check_for_interrupt;\n}\n\n/* Opcode: Param P1 P2 * * *\n**\n** This opcode is only ever present in sub-programs called via the \n** OP_Program instruction. Copy a value currently stored in a memory \n** cell of the calling (parent) frame to cell P2 in the current frames \n** address space. This is used by trigger programs to access the new.* \n** and old.* values.\n**\n** The address of the cell in the parent frame is determined by adding\n** the value of the P1 argument to the value of the P1 argument to the\n** calling OP_Program instruction.\n*/\ncase OP_Param: {           /* out2 */\n  VdbeFrame *pFrame;\n  Mem *pIn;\n  pOut = out2Prerelease(p, pOp);\n  pFrame = p->pFrame;\n  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];   \n  sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);\n  break;\n}\n\n#endif /* #ifndef SQLITE_OMIT_TRIGGER */\n\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n/* Opcode: FkCounter P1 P2 * * *\n** Synopsis: fkctr[P1]+=P2\n**\n** Increment a \"constraint counter\" by P2 (P2 may be negative or positive).\n** If P1 is non-zero, the database constraint counter is incremented \n** (deferred foreign key constraints). Otherwise, if P1 is zero, the \n** statement counter is incremented (immediate foreign key constraints).\n*/\ncase OP_FkCounter: {\n  if( db->flags & SQLITE_DeferFKs ){\n    db->nDeferredImmCons += pOp->p2;\n  }else if( pOp->p1 ){\n    db->nDeferredCons += pOp->p2;\n  }else{\n    p->nFkConstraint += pOp->p2;\n  }\n  break;\n}\n\n/* Opcode: FkIfZero P1 P2 * * *\n** Synopsis: if fkctr[P1]==0 goto P2\n**\n** This opcode tests if a foreign key constraint-counter is currently zero.\n** If so, jump to instruction P2. Otherwise, fall through to the next \n** instruction.\n**\n** If P1 is non-zero, then the jump is taken if the database constraint-counter\n** is zero (the one that counts deferred constraint violations). If P1 is\n** zero, the jump is taken if the statement constraint-counter is zero\n** (immediate foreign key constraint violations).\n*/\ncase OP_FkIfZero: {         /* jump */\n  if( pOp->p1 ){\n    VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);\n    if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;\n  }else{\n    VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);\n    if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;\n  }\n  break;\n}\n#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */\n\n#ifndef SQLITE_OMIT_AUTOINCREMENT\n/* Opcode: MemMax P1 P2 * * *\n** Synopsis: r[P1]=max(r[P1],r[P2])\n**\n** P1 is a register in the root frame of this VM (the root frame is\n** different from the current frame if this instruction is being executed\n** within a sub-program). Set the value of register P1 to the maximum of \n** its current value and the value in register P2.\n**\n** This instruction throws an error if the memory cell is not initially\n** an integer.\n*/\ncase OP_MemMax: {        /* in2 */\n  VdbeFrame *pFrame;\n  if( p->pFrame ){\n    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);\n    pIn1 = &pFrame->aMem[pOp->p1];\n  }else{\n    pIn1 = &aMem[pOp->p1];\n  }\n  assert( memIsValid(pIn1) );\n  sqlite3VdbeMemIntegerify(pIn1);\n  pIn2 = &aMem[pOp->p2];\n  sqlite3VdbeMemIntegerify(pIn2);\n  if( pIn1->u.i<pIn2->u.i){\n    pIn1->u.i = pIn2->u.i;\n  }\n  break;\n}\n#endif /* SQLITE_OMIT_AUTOINCREMENT */\n\n/* Opcode: IfPos P1 P2 P3 * *\n** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2\n**\n** Register P1 must contain an integer.\n** If the value of register P1 is 1 or greater, subtract P3 from the\n** value in P1 and jump to P2.\n**\n** If the initial value of register P1 is less than 1, then the\n** value is unchanged and control passes through to the next instruction.\n*/\ncase OP_IfPos: {        /* jump, in1 */\n  pIn1 = &aMem[pOp->p1];\n  assert( pIn1->flags&MEM_Int );\n  VdbeBranchTaken( pIn1->u.i>0, 2);\n  if( pIn1->u.i>0 ){\n    pIn1->u.i -= pOp->p3;\n    goto jump_to_p2;\n  }\n  break;\n}\n\n/* Opcode: OffsetLimit P1 P2 P3 * *\n** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)\n**\n** This opcode performs a commonly used computation associated with\n** LIMIT and OFFSET process.  r[P1] holds the limit counter.  r[P3]\n** holds the offset counter.  The opcode computes the combined value\n** of the LIMIT and OFFSET and stores that value in r[P2].  The r[P2]\n** value computed is the total number of rows that will need to be\n** visited in order to complete the query.\n**\n** If r[P3] is zero or negative, that means there is no OFFSET\n** and r[P2] is set to be the value of the LIMIT, r[P1].\n**\n** if r[P1] is zero or negative, that means there is no LIMIT\n** and r[P2] is set to -1. \n**\n** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].\n*/\ncase OP_OffsetLimit: {    /* in1, out2, in3 */\n  i64 x;\n  pIn1 = &aMem[pOp->p1];\n  pIn3 = &aMem[pOp->p3];\n  pOut = out2Prerelease(p, pOp);\n  assert( pIn1->flags & MEM_Int );\n  assert( pIn3->flags & MEM_Int );\n  x = pIn1->u.i;\n  if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){\n    /* If the LIMIT is less than or equal to zero, loop forever.  This\n    ** is documented.  But also, if the LIMIT+OFFSET exceeds 2^63 then\n    ** also loop forever.  This is undocumented.  In fact, one could argue\n    ** that the loop should terminate.  But assuming 1 billion iterations\n    ** per second (far exceeding the capabilities of any current hardware)\n    ** it would take nearly 300 years to actually reach the limit.  So\n    ** looping forever is a reasonable approximation. */\n    pOut->u.i = -1;\n  }else{\n    pOut->u.i = x;\n  }\n  break;\n}\n\n/* Opcode: IfNotZero P1 P2 * * *\n** Synopsis: if r[P1]!=0 then r[P1]--, goto P2\n**\n** Register P1 must contain an integer.  If the content of register P1 is\n** initially greater than zero, then decrement the value in register P1.\n** If it is non-zero (negative or positive) and then also jump to P2.  \n** If register P1 is initially zero, leave it unchanged and fall through.\n*/\ncase OP_IfNotZero: {        /* jump, in1 */\n  pIn1 = &aMem[pOp->p1];\n  assert( pIn1->flags&MEM_Int );\n  VdbeBranchTaken(pIn1->u.i<0, 2);\n  if( pIn1->u.i ){\n     if( pIn1->u.i>0 ) pIn1->u.i--;\n     goto jump_to_p2;\n  }\n  break;\n}\n\n/* Opcode: DecrJumpZero P1 P2 * * *\n** Synopsis: if (--r[P1])==0 goto P2\n**\n** Register P1 must hold an integer.  Decrement the value in P1\n** and jump to P2 if the new value is exactly zero.\n*/\ncase OP_DecrJumpZero: {      /* jump, in1 */\n  pIn1 = &aMem[pOp->p1];\n  assert( pIn1->flags&MEM_Int );\n  if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;\n  VdbeBranchTaken(pIn1->u.i==0, 2);\n  if( pIn1->u.i==0 ) goto jump_to_p2;\n  break;\n}\n\n\n/* Opcode: AggStep * P2 P3 P4 P5\n** Synopsis: accum=r[P3] step(r[P2@P5])\n**\n** Execute the xStep function for an aggregate.\n** The function has P5 arguments.  P4 is a pointer to the \n** FuncDef structure that specifies the function.  Register P3 is the\n** accumulator.\n**\n** The P5 arguments are taken from register P2 and its\n** successors.\n*/\n/* Opcode: AggInverse * P2 P3 P4 P5\n** Synopsis: accum=r[P3] inverse(r[P2@P5])\n**\n** Execute the xInverse function for an aggregate.\n** The function has P5 arguments.  P4 is a pointer to the \n** FuncDef structure that specifies the function.  Register P3 is the\n** accumulator.\n**\n** The P5 arguments are taken from register P2 and its\n** successors.\n*/\n/* Opcode: AggStep1 P1 P2 P3 P4 P5\n** Synopsis: accum=r[P3] step(r[P2@P5])\n**\n** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an\n** aggregate.  The function has P5 arguments.  P4 is a pointer to the \n** FuncDef structure that specifies the function.  Register P3 is the\n** accumulator.\n**\n** The P5 arguments are taken from register P2 and its\n** successors.\n**\n** This opcode is initially coded as OP_AggStep0.  On first evaluation,\n** the FuncDef stored in P4 is converted into an sqlite3_context and\n** the opcode is changed.  In this way, the initialization of the\n** sqlite3_context only happens once, instead of on each call to the\n** step function.\n*/\ncase OP_AggInverse:\ncase OP_AggStep: {\n  int n;\n  sqlite3_context *pCtx;\n\n  assert( pOp->p4type==P4_FUNCDEF );\n  n = pOp->p5;\n  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );\n  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );\n  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );\n  pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +\n               (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));\n  if( pCtx==0 ) goto no_mem;\n  pCtx->pMem = 0;\n  pCtx->pOut = (Mem*)&(pCtx->argv[n]);\n  sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);\n  pCtx->pFunc = pOp->p4.pFunc;\n  pCtx->iOp = (int)(pOp - aOp);\n  pCtx->pVdbe = p;\n  pCtx->skipFlag = 0;\n  pCtx->isError = 0;\n  pCtx->argc = n;\n  pOp->p4type = P4_FUNCCTX;\n  pOp->p4.pCtx = pCtx;\n\n  /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */\n  assert( pOp->p1==(pOp->opcode==OP_AggInverse) );\n\n  pOp->opcode = OP_AggStep1;\n  /* Fall through into OP_AggStep */\n}\ncase OP_AggStep1: {\n  int i;\n  sqlite3_context *pCtx;\n  Mem *pMem;\n\n  assert( pOp->p4type==P4_FUNCCTX );\n  pCtx = pOp->p4.pCtx;\n  pMem = &aMem[pOp->p3];\n\n#ifdef SQLITE_DEBUG\n  if( pOp->p1 ){\n    /* This is an OP_AggInverse call.  Verify that xStep has always\n    ** been called at least once prior to any xInverse call. */\n    assert( pMem->uTemp==0x1122e0e3 );\n  }else{\n    /* This is an OP_AggStep call.  Mark it as such. */\n    pMem->uTemp = 0x1122e0e3;\n  }\n#endif\n\n  /* If this function is inside of a trigger, the register array in aMem[]\n  ** might change from one evaluation to the next.  The next block of code\n  ** checks to see if the register array has changed, and if so it\n  ** reinitializes the relavant parts of the sqlite3_context object */\n  if( pCtx->pMem != pMem ){\n    pCtx->pMem = pMem;\n    for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];\n  }\n\n#ifdef SQLITE_DEBUG\n  for(i=0; i<pCtx->argc; i++){\n    assert( memIsValid(pCtx->argv[i]) );\n    REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);\n  }\n#endif\n\n  pMem->n++;\n  assert( pCtx->pOut->flags==MEM_Null );\n  assert( pCtx->isError==0 );\n  assert( pCtx->skipFlag==0 );\n#ifndef SQLITE_OMIT_WINDOWFUNC\n  if( pOp->p1 ){\n    (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);\n  }else\n#endif\n  (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */\n\n  if( pCtx->isError ){\n    if( pCtx->isError>0 ){\n      sqlite3VdbeError(p, \"%s\", sqlite3_value_text(pCtx->pOut));\n      rc = pCtx->isError;\n    }\n    if( pCtx->skipFlag ){\n      assert( pOp[-1].opcode==OP_CollSeq );\n      i = pOp[-1].p1;\n      if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);\n      pCtx->skipFlag = 0;\n    }\n    sqlite3VdbeMemRelease(pCtx->pOut);\n    pCtx->pOut->flags = MEM_Null;\n    pCtx->isError = 0;\n    if( rc ) goto abort_due_to_error;\n  }\n  assert( pCtx->pOut->flags==MEM_Null );\n  assert( pCtx->skipFlag==0 );\n  break;\n}\n\n/* Opcode: AggFinal P1 P2 * P4 *\n** Synopsis: accum=r[P1] N=P2\n**\n** P1 is the memory location that is the accumulator for an aggregate\n** or window function.  Execute the finalizer function \n** for an aggregate and store the result in P1.\n**\n** P2 is the number of arguments that the step function takes and\n** P4 is a pointer to the FuncDef for this function.  The P2\n** argument is not used by this opcode.  It is only there to disambiguate\n** functions that can take varying numbers of arguments.  The\n** P4 argument is only needed for the case where\n** the step function was not previously called.\n*/\n/* Opcode: AggValue * P2 P3 P4 *\n** Synopsis: r[P3]=value N=P2\n**\n** Invoke the xValue() function and store the result in register P3.\n**\n** P2 is the number of arguments that the step function takes and\n** P4 is a pointer to the FuncDef for this function.  The P2\n** argument is not used by this opcode.  It is only there to disambiguate\n** functions that can take varying numbers of arguments.  The\n** P4 argument is only needed for the case where\n** the step function was not previously called.\n*/\ncase OP_AggValue:\ncase OP_AggFinal: {\n  Mem *pMem;\n  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );\n  assert( pOp->p3==0 || pOp->opcode==OP_AggValue );\n  pMem = &aMem[pOp->p1];\n  assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );\n#ifndef SQLITE_OMIT_WINDOWFUNC\n  if( pOp->p3 ){\n    memAboutToChange(p, &aMem[pOp->p3]);\n    rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);\n    pMem = &aMem[pOp->p3];\n  }else\n#endif\n  {\n    rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);\n  }\n  \n  if( rc ){\n    sqlite3VdbeError(p, \"%s\", sqlite3_value_text(pMem));\n    goto abort_due_to_error;\n  }\n  sqlite3VdbeChangeEncoding(pMem, encoding);\n  UPDATE_MAX_BLOBSIZE(pMem);\n  if( sqlite3VdbeMemTooBig(pMem) ){\n    goto too_big;\n  }\n  break;\n}\n\n#ifndef SQLITE_OMIT_WAL\n/* Opcode: Checkpoint P1 P2 P3 * *\n**\n** Checkpoint database P1. This is a no-op if P1 is not currently in\n** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,\n** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns\n** SQLITE_BUSY or not, respectively.  Write the number of pages in the\n** WAL after the checkpoint into mem[P3+1] and the number of pages\n** in the WAL that have been checkpointed after the checkpoint\n** completes into mem[P3+2].  However on an error, mem[P3+1] and\n** mem[P3+2] are initialized to -1.\n*/\ncase OP_Checkpoint: {\n  int i;                          /* Loop counter */\n  int aRes[3];                    /* Results */\n  Mem *pMem;                      /* Write results here */\n\n  assert( p->readOnly==0 );\n  aRes[0] = 0;\n  aRes[1] = aRes[2] = -1;\n  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE\n       || pOp->p2==SQLITE_CHECKPOINT_FULL\n       || pOp->p2==SQLITE_CHECKPOINT_RESTART\n       || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE\n  );\n  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);\n  if( rc ){\n    if( rc!=SQLITE_BUSY ) goto abort_due_to_error;\n    rc = SQLITE_OK;\n    aRes[0] = 1;\n  }\n  for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){\n    sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);\n  }    \n  break;\n};  \n#endif\n\n#ifndef SQLITE_OMIT_PRAGMA\n/* Opcode: JournalMode P1 P2 P3 * *\n**\n** Change the journal mode of database P1 to P3. P3 must be one of the\n** PAGER_JOURNALMODE_XXX values. If changing between the various rollback\n** modes (delete, truncate, persist, off and memory), this is a simple\n** operation. No IO is required.\n**\n** If changing into or out of WAL mode the procedure is more complicated.\n**\n** Write a string containing the final journal-mode to register P2.\n*/\ncase OP_JournalMode: {    /* out2 */\n  Btree *pBt;                     /* Btree to change journal mode of */\n  Pager *pPager;                  /* Pager associated with pBt */\n  int eNew;                       /* New journal mode */\n  int eOld;                       /* The old journal mode */\n#ifndef SQLITE_OMIT_WAL\n  const char *zFilename;          /* Name of database file for pPager */\n#endif\n\n  pOut = out2Prerelease(p, pOp);\n  eNew = pOp->p3;\n  assert( eNew==PAGER_JOURNALMODE_DELETE \n       || eNew==PAGER_JOURNALMODE_TRUNCATE \n       || eNew==PAGER_JOURNALMODE_PERSIST \n       || eNew==PAGER_JOURNALMODE_OFF\n       || eNew==PAGER_JOURNALMODE_MEMORY\n       || eNew==PAGER_JOURNALMODE_WAL\n       || eNew==PAGER_JOURNALMODE_QUERY\n  );\n  assert( pOp->p1>=0 && pOp->p1<db->nDb );\n  assert( p->readOnly==0 );\n\n  pBt = db->aDb[pOp->p1].pBt;\n  pPager = sqlite3BtreePager(pBt);\n  eOld = sqlite3PagerGetJournalMode(pPager);\n  if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;\n  if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;\n\n#ifndef SQLITE_OMIT_WAL\n  zFilename = sqlite3PagerFilename(pPager, 1);\n\n  /* Do not allow a transition to journal_mode=WAL for a database\n  ** in temporary storage or if the VFS does not support shared memory \n  */\n  if( eNew==PAGER_JOURNALMODE_WAL\n   && (sqlite3Strlen30(zFilename)==0           /* Temp file */\n       || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */\n  ){\n    eNew = eOld;\n  }\n\n  if( (eNew!=eOld)\n   && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)\n  ){\n    if( !db->autoCommit || db->nVdbeRead>1 ){\n      rc = SQLITE_ERROR;\n      sqlite3VdbeError(p,\n          \"cannot change %s wal mode from within a transaction\",\n          (eNew==PAGER_JOURNALMODE_WAL ? \"into\" : \"out of\")\n      );\n      goto abort_due_to_error;\n    }else{\n \n      if( eOld==PAGER_JOURNALMODE_WAL ){\n        /* If leaving WAL mode, close the log file. If successful, the call\n        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log \n        ** file. An EXCLUSIVE lock may still be held on the database file \n        ** after a successful return. \n        */\n        rc = sqlite3PagerCloseWal(pPager, db);\n        if( rc==SQLITE_OK ){\n          sqlite3PagerSetJournalMode(pPager, eNew);\n        }\n      }else if( eOld==PAGER_JOURNALMODE_MEMORY ){\n        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF\n        ** as an intermediate */\n        sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);\n      }\n  \n      /* Open a transaction on the database file. Regardless of the journal\n      ** mode, this transaction always uses a rollback journal.\n      */\n      assert( sqlite3BtreeIsInTrans(pBt)==0 );\n      if( rc==SQLITE_OK ){\n        rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));\n      }\n    }\n  }\n#endif /* ifndef SQLITE_OMIT_WAL */\n\n  if( rc ) eNew = eOld;\n  eNew = sqlite3PagerSetJournalMode(pPager, eNew);\n\n  pOut->flags = MEM_Str|MEM_Static|MEM_Term;\n  pOut->z = (char *)sqlite3JournalModename(eNew);\n  pOut->n = sqlite3Strlen30(pOut->z);\n  pOut->enc = SQLITE_UTF8;\n  sqlite3VdbeChangeEncoding(pOut, encoding);\n  if( rc ) goto abort_due_to_error;\n  break;\n};\n#endif /* SQLITE_OMIT_PRAGMA */\n\n#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)\n/* Opcode: Vacuum P1 P2 * * *\n**\n** Vacuum the entire database P1.  P1 is 0 for \"main\", and 2 or more\n** for an attached database.  The \"temp\" database may not be vacuumed.\n**\n** If P2 is not zero, then it is a register holding a string which is\n** the file into which the result of vacuum should be written.  When\n** P2 is zero, the vacuum overwrites the original database.\n*/\ncase OP_Vacuum: {\n  assert( p->readOnly==0 );\n  rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,\n                        pOp->p2 ? &aMem[pOp->p2] : 0);\n  if( rc ) goto abort_due_to_error;\n  break;\n}\n#endif\n\n#if !defined(SQLITE_OMIT_AUTOVACUUM)\n/* Opcode: IncrVacuum P1 P2 * * *\n**\n** Perform a single step of the incremental vacuum procedure on\n** the P1 database. If the vacuum has finished, jump to instruction\n** P2. Otherwise, fall through to the next instruction.\n*/\ncase OP_IncrVacuum: {        /* jump */\n  Btree *pBt;\n\n  assert( pOp->p1>=0 && pOp->p1<db->nDb );\n  assert( DbMaskTest(p->btreeMask, pOp->p1) );\n  assert( p->readOnly==0 );\n  pBt = db->aDb[pOp->p1].pBt;\n  rc = sqlite3BtreeIncrVacuum(pBt);\n  VdbeBranchTaken(rc==SQLITE_DONE,2);\n  if( rc ){\n    if( rc!=SQLITE_DONE ) goto abort_due_to_error;\n    rc = SQLITE_OK;\n    goto jump_to_p2;\n  }\n  break;\n}\n#endif\n\n/* Opcode: Expire P1 P2 * * *\n**\n** Cause precompiled statements to expire.  When an expired statement\n** is executed using sqlite3_step() it will either automatically\n** reprepare itself (if it was originally created using sqlite3_prepare_v2())\n** or it will fail with SQLITE_SCHEMA.\n** \n** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,\n** then only the currently executing statement is expired.\n**\n** If P2 is 0, then SQL statements are expired immediately.  If P2 is 1,\n** then running SQL statements are allowed to continue to run to completion.\n** The P2==1 case occurs when a CREATE INDEX or similar schema change happens\n** that might help the statement run faster but which does not affect the\n** correctness of operation.\n*/\ncase OP_Expire: {\n  assert( pOp->p2==0 || pOp->p2==1 );\n  if( !pOp->p1 ){\n    sqlite3ExpirePreparedStatements(db, pOp->p2);\n  }else{\n    p->expired = pOp->p2+1;\n  }\n  break;\n}\n\n/* Opcode: CursorLock P1 * * * *\n**\n** Lock the btree to which cursor P1 is pointing so that the btree cannot be\n** written by an other cursor.\n*/\ncase OP_CursorLock: {\n  VdbeCursor *pC;\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  assert( pC->eCurType==CURTYPE_BTREE );\n  sqlite3BtreeCursorPin(pC->uc.pCursor);\n  break;\n}\n\n/* Opcode: CursorUnlock P1 * * * *\n**\n** Unlock the btree to which cursor P1 is pointing so that it can be\n** written by other cursors.\n*/\ncase OP_CursorUnlock: {\n  VdbeCursor *pC;\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  pC = p->apCsr[pOp->p1];\n  assert( pC!=0 );\n  assert( pC->eCurType==CURTYPE_BTREE );\n  sqlite3BtreeCursorUnpin(pC->uc.pCursor);\n  break;\n}\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n/* Opcode: TableLock P1 P2 P3 P4 *\n** Synopsis: iDb=P1 root=P2 write=P3\n**\n** Obtain a lock on a particular table. This instruction is only used when\n** the shared-cache feature is enabled. \n**\n** P1 is the index of the database in sqlite3.aDb[] of the database\n** on which the lock is acquired.  A readlock is obtained if P3==0 or\n** a write lock if P3==1.\n**\n** P2 contains the root-page of the table to lock.\n**\n** P4 contains a pointer to the name of the table being locked. This is only\n** used to generate an error message if the lock cannot be obtained.\n*/\ncase OP_TableLock: {\n  u8 isWriteLock = (u8)pOp->p3;\n  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){\n    int p1 = pOp->p1; \n    assert( p1>=0 && p1<db->nDb );\n    assert( DbMaskTest(p->btreeMask, p1) );\n    assert( isWriteLock==0 || isWriteLock==1 );\n    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);\n    if( rc ){\n      if( (rc&0xFF)==SQLITE_LOCKED ){\n        const char *z = pOp->p4.z;\n        sqlite3VdbeError(p, \"database table is locked: %s\", z);\n      }\n      goto abort_due_to_error;\n    }\n  }\n  break;\n}\n#endif /* SQLITE_OMIT_SHARED_CACHE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VBegin * * * P4 *\n**\n** P4 may be a pointer to an sqlite3_vtab structure. If so, call the \n** xBegin method for that table.\n**\n** Also, whether or not P4 is set, check that this is not being called from\n** within a callback to a virtual table xSync() method. If it is, the error\n** code will be set to SQLITE_LOCKED.\n*/\ncase OP_VBegin: {\n  VTable *pVTab;\n  pVTab = pOp->p4.pVtab;\n  rc = sqlite3VtabBegin(db, pVTab);\n  if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);\n  if( rc ) goto abort_due_to_error;\n  break;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VCreate P1 P2 * * *\n**\n** P2 is a register that holds the name of a virtual table in database \n** P1. Call the xCreate method for that table.\n*/\ncase OP_VCreate: {\n  Mem sMem;          /* For storing the record being decoded */\n  const char *zTab;  /* Name of the virtual table */\n\n  memset(&sMem, 0, sizeof(sMem));\n  sMem.db = db;\n  /* Because P2 is always a static string, it is impossible for the\n  ** sqlite3VdbeMemCopy() to fail */\n  assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );\n  assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );\n  rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);\n  assert( rc==SQLITE_OK );\n  zTab = (const char*)sqlite3_value_text(&sMem);\n  assert( zTab || db->mallocFailed );\n  if( zTab ){\n    rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);\n  }\n  sqlite3VdbeMemRelease(&sMem);\n  if( rc ) goto abort_due_to_error;\n  break;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VDestroy P1 * * P4 *\n**\n** P4 is the name of a virtual table in database P1.  Call the xDestroy method\n** of that table.\n*/\ncase OP_VDestroy: {\n  db->nVDestroy++;\n  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);\n  db->nVDestroy--;\n  assert( p->errorAction==OE_Abort && p->usesStmtJournal );\n  if( rc ) goto abort_due_to_error;\n  break;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VOpen P1 * * P4 *\n**\n** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.\n** P1 is a cursor number.  This opcode opens a cursor to the virtual\n** table and stores that cursor in P1.\n*/\ncase OP_VOpen: {\n  VdbeCursor *pCur;\n  sqlite3_vtab_cursor *pVCur;\n  sqlite3_vtab *pVtab;\n  const sqlite3_module *pModule;\n\n  assert( p->bIsReader );\n  pCur = 0;\n  pVCur = 0;\n  pVtab = pOp->p4.pVtab->pVtab;\n  if( pVtab==0 || NEVER(pVtab->pModule==0) ){\n    rc = SQLITE_LOCKED;\n    goto abort_due_to_error;\n  }\n  pModule = pVtab->pModule;\n  rc = pModule->xOpen(pVtab, &pVCur);\n  sqlite3VtabImportErrmsg(p, pVtab);\n  if( rc ) goto abort_due_to_error;\n\n  /* Initialize sqlite3_vtab_cursor base class */\n  pVCur->pVtab = pVtab;\n\n  /* Initialize vdbe cursor object */\n  pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);\n  if( pCur ){\n    pCur->uc.pVCur = pVCur;\n    pVtab->nRef++;\n  }else{\n    assert( db->mallocFailed );\n    pModule->xClose(pVCur);\n    goto no_mem;\n  }\n  break;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VFilter P1 P2 P3 P4 *\n** Synopsis: iplan=r[P3] zplan='P4'\n**\n** P1 is a cursor opened using VOpen.  P2 is an address to jump to if\n** the filtered result set is empty.\n**\n** P4 is either NULL or a string that was generated by the xBestIndex\n** method of the module.  The interpretation of the P4 string is left\n** to the module implementation.\n**\n** This opcode invokes the xFilter method on the virtual table specified\n** by P1.  The integer query plan parameter to xFilter is stored in register\n** P3. Register P3+1 stores the argc parameter to be passed to the\n** xFilter method. Registers P3+2..P3+1+argc are the argc\n** additional parameters which are passed to\n** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.\n**\n** A jump is made to P2 if the result set after filtering would be empty.\n*/\ncase OP_VFilter: {   /* jump */\n  int nArg;\n  int iQuery;\n  const sqlite3_module *pModule;\n  Mem *pQuery;\n  Mem *pArgc;\n  sqlite3_vtab_cursor *pVCur;\n  sqlite3_vtab *pVtab;\n  VdbeCursor *pCur;\n  int res;\n  int i;\n  Mem **apArg;\n\n  pQuery = &aMem[pOp->p3];\n  pArgc = &pQuery[1];\n  pCur = p->apCsr[pOp->p1];\n  assert( memIsValid(pQuery) );\n  REGISTER_TRACE(pOp->p3, pQuery);\n  assert( pCur->eCurType==CURTYPE_VTAB );\n  pVCur = pCur->uc.pVCur;\n  pVtab = pVCur->pVtab;\n  pModule = pVtab->pModule;\n\n  /* Grab the index number and argc parameters */\n  assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );\n  nArg = (int)pArgc->u.i;\n  iQuery = (int)pQuery->u.i;\n\n  /* Invoke the xFilter method */\n  res = 0;\n  apArg = p->apArg;\n  for(i = 0; i<nArg; i++){\n    apArg[i] = &pArgc[i+1];\n  }\n  rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);\n  sqlite3VtabImportErrmsg(p, pVtab);\n  if( rc ) goto abort_due_to_error;\n  res = pModule->xEof(pVCur);\n  pCur->nullRow = 0;\n  VdbeBranchTaken(res!=0,2);\n  if( res ) goto jump_to_p2;\n  break;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VColumn P1 P2 P3 * P5\n** Synopsis: r[P3]=vcolumn(P2)\n**\n** Store in register P3 the value of the P2-th column of\n** the current row of the virtual-table of cursor P1.\n**\n** If the VColumn opcode is being used to fetch the value of\n** an unchanging column during an UPDATE operation, then the P5\n** value is OPFLAG_NOCHNG.  This will cause the sqlite3_vtab_nochange()\n** function to return true inside the xColumn method of the virtual\n** table implementation.  The P5 column might also contain other\n** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are\n** unused by OP_VColumn.\n*/\ncase OP_VColumn: {\n  sqlite3_vtab *pVtab;\n  const sqlite3_module *pModule;\n  Mem *pDest;\n  sqlite3_context sContext;\n\n  VdbeCursor *pCur = p->apCsr[pOp->p1];\n  assert( pCur->eCurType==CURTYPE_VTAB );\n  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );\n  pDest = &aMem[pOp->p3];\n  memAboutToChange(p, pDest);\n  if( pCur->nullRow ){\n    sqlite3VdbeMemSetNull(pDest);\n    break;\n  }\n  pVtab = pCur->uc.pVCur->pVtab;\n  pModule = pVtab->pModule;\n  assert( pModule->xColumn );\n  memset(&sContext, 0, sizeof(sContext));\n  sContext.pOut = pDest;\n  assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 );\n  if( pOp->p5 & OPFLAG_NOCHNG ){\n    sqlite3VdbeMemSetNull(pDest);\n    pDest->flags = MEM_Null|MEM_Zero;\n    pDest->u.nZero = 0;\n  }else{\n    MemSetTypeFlag(pDest, MEM_Null);\n  }\n  rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);\n  sqlite3VtabImportErrmsg(p, pVtab);\n  if( sContext.isError>0 ){\n    sqlite3VdbeError(p, \"%s\", sqlite3_value_text(pDest));\n    rc = sContext.isError;\n  }\n  sqlite3VdbeChangeEncoding(pDest, encoding);\n  REGISTER_TRACE(pOp->p3, pDest);\n  UPDATE_MAX_BLOBSIZE(pDest);\n\n  if( sqlite3VdbeMemTooBig(pDest) ){\n    goto too_big;\n  }\n  if( rc ) goto abort_due_to_error;\n  break;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VNext P1 P2 * * *\n**\n** Advance virtual table P1 to the next row in its result set and\n** jump to instruction P2.  Or, if the virtual table has reached\n** the end of its result set, then fall through to the next instruction.\n*/\ncase OP_VNext: {   /* jump */\n  sqlite3_vtab *pVtab;\n  const sqlite3_module *pModule;\n  int res;\n  VdbeCursor *pCur;\n\n  res = 0;\n  pCur = p->apCsr[pOp->p1];\n  assert( pCur->eCurType==CURTYPE_VTAB );\n  if( pCur->nullRow ){\n    break;\n  }\n  pVtab = pCur->uc.pVCur->pVtab;\n  pModule = pVtab->pModule;\n  assert( pModule->xNext );\n\n  /* Invoke the xNext() method of the module. There is no way for the\n  ** underlying implementation to return an error if one occurs during\n  ** xNext(). Instead, if an error occurs, true is returned (indicating that \n  ** data is available) and the error code returned when xColumn or\n  ** some other method is next invoked on the save virtual table cursor.\n  */\n  rc = pModule->xNext(pCur->uc.pVCur);\n  sqlite3VtabImportErrmsg(p, pVtab);\n  if( rc ) goto abort_due_to_error;\n  res = pModule->xEof(pCur->uc.pVCur);\n  VdbeBranchTaken(!res,2);\n  if( !res ){\n    /* If there is data, jump to P2 */\n    goto jump_to_p2_and_check_for_interrupt;\n  }\n  goto check_for_interrupt;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VRename P1 * * P4 *\n**\n** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.\n** This opcode invokes the corresponding xRename method. The value\n** in register P1 is passed as the zName argument to the xRename method.\n*/\ncase OP_VRename: {\n  sqlite3_vtab *pVtab;\n  Mem *pName;\n  int isLegacy;\n  \n  isLegacy = (db->flags & SQLITE_LegacyAlter);\n  db->flags |= SQLITE_LegacyAlter;\n  pVtab = pOp->p4.pVtab->pVtab;\n  pName = &aMem[pOp->p1];\n  assert( pVtab->pModule->xRename );\n  assert( memIsValid(pName) );\n  assert( p->readOnly==0 );\n  REGISTER_TRACE(pOp->p1, pName);\n  assert( pName->flags & MEM_Str );\n  testcase( pName->enc==SQLITE_UTF8 );\n  testcase( pName->enc==SQLITE_UTF16BE );\n  testcase( pName->enc==SQLITE_UTF16LE );\n  rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);\n  if( rc ) goto abort_due_to_error;\n  rc = pVtab->pModule->xRename(pVtab, pName->z);\n  if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;\n  sqlite3VtabImportErrmsg(p, pVtab);\n  p->expired = 0;\n  if( rc ) goto abort_due_to_error;\n  break;\n}\n#endif\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VUpdate P1 P2 P3 P4 P5\n** Synopsis: data=r[P3@P2]\n**\n** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.\n** This opcode invokes the corresponding xUpdate method. P2 values\n** are contiguous memory cells starting at P3 to pass to the xUpdate \n** invocation. The value in register (P3+P2-1) corresponds to the \n** p2th element of the argv array passed to xUpdate.\n**\n** The xUpdate method will do a DELETE or an INSERT or both.\n** The argv[0] element (which corresponds to memory cell P3)\n** is the rowid of a row to delete.  If argv[0] is NULL then no \n** deletion occurs.  The argv[1] element is the rowid of the new \n** row.  This can be NULL to have the virtual table select the new \n** rowid for itself.  The subsequent elements in the array are \n** the values of columns in the new row.\n**\n** If P2==1 then no insert is performed.  argv[0] is the rowid of\n** a row to delete.\n**\n** P1 is a boolean flag. If it is set to true and the xUpdate call\n** is successful, then the value returned by sqlite3_last_insert_rowid() \n** is set to the value of the rowid for the row just inserted.\n**\n** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to\n** apply in the case of a constraint failure on an insert or update.\n*/\ncase OP_VUpdate: {\n  sqlite3_vtab *pVtab;\n  const sqlite3_module *pModule;\n  int nArg;\n  int i;\n  sqlite_int64 rowid;\n  Mem **apArg;\n  Mem *pX;\n\n  assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback \n       || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace\n  );\n  assert( p->readOnly==0 );\n  if( db->mallocFailed ) goto no_mem;\n  sqlite3VdbeIncrWriteCounter(p, 0);\n  pVtab = pOp->p4.pVtab->pVtab;\n  if( pVtab==0 || NEVER(pVtab->pModule==0) ){\n    rc = SQLITE_LOCKED;\n    goto abort_due_to_error;\n  }\n  pModule = pVtab->pModule;\n  nArg = pOp->p2;\n  assert( pOp->p4type==P4_VTAB );\n  if( ALWAYS(pModule->xUpdate) ){\n    u8 vtabOnConflict = db->vtabOnConflict;\n    apArg = p->apArg;\n    pX = &aMem[pOp->p3];\n    for(i=0; i<nArg; i++){\n      assert( memIsValid(pX) );\n      memAboutToChange(p, pX);\n      apArg[i] = pX;\n      pX++;\n    }\n    db->vtabOnConflict = pOp->p5;\n    rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);\n    db->vtabOnConflict = vtabOnConflict;\n    sqlite3VtabImportErrmsg(p, pVtab);\n    if( rc==SQLITE_OK && pOp->p1 ){\n      assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );\n      db->lastRowid = rowid;\n    }\n    if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){\n      if( pOp->p5==OE_Ignore ){\n        rc = SQLITE_OK;\n      }else{\n        p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);\n      }\n    }else{\n      p->nChange++;\n    }\n    if( rc ) goto abort_due_to_error;\n  }\n  break;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef  SQLITE_OMIT_PAGER_PRAGMAS\n/* Opcode: Pagecount P1 P2 * * *\n**\n** Write the current number of pages in database P1 to memory cell P2.\n*/\ncase OP_Pagecount: {            /* out2 */\n  pOut = out2Prerelease(p, pOp);\n  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);\n  break;\n}\n#endif\n\n\n#ifndef  SQLITE_OMIT_PAGER_PRAGMAS\n/* Opcode: MaxPgcnt P1 P2 P3 * *\n**\n** Try to set the maximum page count for database P1 to the value in P3.\n** Do not let the maximum page count fall below the current page count and\n** do not change the maximum page count value if P3==0.\n**\n** Store the maximum page count after the change in register P2.\n*/\ncase OP_MaxPgcnt: {            /* out2 */\n  unsigned int newMax;\n  Btree *pBt;\n\n  pOut = out2Prerelease(p, pOp);\n  pBt = db->aDb[pOp->p1].pBt;\n  newMax = 0;\n  if( pOp->p3 ){\n    newMax = sqlite3BtreeLastPage(pBt);\n    if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;\n  }\n  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);\n  break;\n}\n#endif\n\n/* Opcode: Function P1 P2 P3 P4 *\n** Synopsis: r[P3]=func(r[P2@NP])\n**\n** Invoke a user function (P4 is a pointer to an sqlite3_context object that\n** contains a pointer to the function to be run) with arguments taken\n** from register P2 and successors.  The number of arguments is in\n** the sqlite3_context object that P4 points to.\n** The result of the function is stored\n** in register P3.  Register P3 must not be one of the function inputs.\n**\n** P1 is a 32-bit bitmask indicating whether or not each argument to the \n** function was determined to be constant at compile time. If the first\n** argument was constant then bit 0 of P1 is set. This is used to determine\n** whether meta data associated with a user function argument using the\n** sqlite3_set_auxdata() API may be safely retained until the next\n** invocation of this opcode.\n**\n** See also: AggStep, AggFinal, PureFunc\n*/\n/* Opcode: PureFunc P1 P2 P3 P4 *\n** Synopsis: r[P3]=func(r[P2@NP])\n**\n** Invoke a user function (P4 is a pointer to an sqlite3_context object that\n** contains a pointer to the function to be run) with arguments taken\n** from register P2 and successors.  The number of arguments is in\n** the sqlite3_context object that P4 points to.\n** The result of the function is stored\n** in register P3.  Register P3 must not be one of the function inputs.\n**\n** P1 is a 32-bit bitmask indicating whether or not each argument to the \n** function was determined to be constant at compile time. If the first\n** argument was constant then bit 0 of P1 is set. This is used to determine\n** whether meta data associated with a user function argument using the\n** sqlite3_set_auxdata() API may be safely retained until the next\n** invocation of this opcode.\n**\n** This opcode works exactly like OP_Function.  The only difference is in\n** its name.  This opcode is used in places where the function must be\n** purely non-deterministic.  Some built-in date/time functions can be\n** either determinitic of non-deterministic, depending on their arguments.\n** When those function are used in a non-deterministic way, they will check\n** to see if they were called using OP_PureFunc instead of OP_Function, and\n** if they were, they throw an error.\n**\n** See also: AggStep, AggFinal, Function\n*/\ncase OP_PureFunc:              /* group */\ncase OP_Function: {            /* group */\n  int i;\n  sqlite3_context *pCtx;\n\n  assert( pOp->p4type==P4_FUNCCTX );\n  pCtx = pOp->p4.pCtx;\n\n  /* If this function is inside of a trigger, the register array in aMem[]\n  ** might change from one evaluation to the next.  The next block of code\n  ** checks to see if the register array has changed, and if so it\n  ** reinitializes the relavant parts of the sqlite3_context object */\n  pOut = &aMem[pOp->p3];\n  if( pCtx->pOut != pOut ){\n    pCtx->pVdbe = p;\n    pCtx->pOut = pOut;\n    for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];\n  }\n  assert( pCtx->pVdbe==p );\n\n  memAboutToChange(p, pOut);\n#ifdef SQLITE_DEBUG\n  for(i=0; i<pCtx->argc; i++){\n    assert( memIsValid(pCtx->argv[i]) );\n    REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);\n  }\n#endif\n  MemSetTypeFlag(pOut, MEM_Null);\n  assert( pCtx->isError==0 );\n  (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */\n\n  /* If the function returned an error, throw an exception */\n  if( pCtx->isError ){\n    if( pCtx->isError>0 ){\n      sqlite3VdbeError(p, \"%s\", sqlite3_value_text(pOut));\n      rc = pCtx->isError;\n    }\n    sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);\n    pCtx->isError = 0;\n    if( rc ) goto abort_due_to_error;\n  }\n\n  /* Copy the result of the function into register P3 */\n  if( pOut->flags & (MEM_Str|MEM_Blob) ){\n    sqlite3VdbeChangeEncoding(pOut, encoding);\n    if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;\n  }\n\n  REGISTER_TRACE(pOp->p3, pOut);\n  UPDATE_MAX_BLOBSIZE(pOut);\n  break;\n}\n\n/* Opcode: Trace P1 P2 * P4 *\n**\n** Write P4 on the statement trace output if statement tracing is\n** enabled.\n**\n** Operand P1 must be 0x7fffffff and P2 must positive.\n*/\n/* Opcode: Init P1 P2 P3 P4 *\n** Synopsis: Start at P2\n**\n** Programs contain a single instance of this opcode as the very first\n** opcode.\n**\n** If tracing is enabled (by the sqlite3_trace()) interface, then\n** the UTF-8 string contained in P4 is emitted on the trace callback.\n** Or if P4 is blank, use the string returned by sqlite3_sql().\n**\n** If P2 is not zero, jump to instruction P2.\n**\n** Increment the value of P1 so that OP_Once opcodes will jump the\n** first time they are evaluated for this run.\n**\n** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT\n** error is encountered.\n*/\ncase OP_Trace:\ncase OP_Init: {          /* jump */\n  int i;\n#ifndef SQLITE_OMIT_TRACE\n  char *zTrace;\n#endif\n\n  /* If the P4 argument is not NULL, then it must be an SQL comment string.\n  ** The \"--\" string is broken up to prevent false-positives with srcck1.c.\n  **\n  ** This assert() provides evidence for:\n  ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that\n  ** would have been returned by the legacy sqlite3_trace() interface by\n  ** using the X argument when X begins with \"--\" and invoking\n  ** sqlite3_expanded_sql(P) otherwise.\n  */\n  assert( pOp->p4.z==0 || strncmp(pOp->p4.z, \"-\" \"- \", 3)==0 );\n\n  /* OP_Init is always instruction 0 */\n  assert( pOp==p->aOp || pOp->opcode==OP_Trace );\n\n#ifndef SQLITE_OMIT_TRACE\n  if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0\n   && !p->doingRerun\n   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0\n  ){\n#ifndef SQLITE_OMIT_DEPRECATED\n    if( db->mTrace & SQLITE_TRACE_LEGACY ){\n      void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;\n      char *z = sqlite3VdbeExpandSql(p, zTrace);\n      x(db->pTraceArg, z);\n      sqlite3_free(z);\n    }else\n#endif\n    if( db->nVdbeExec>1 ){\n      char *z = sqlite3MPrintf(db, \"-- %s\", zTrace);\n      (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);\n      sqlite3DbFree(db, z);\n    }else{\n      (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);\n    }\n  }\n#ifdef SQLITE_USE_FCNTL_TRACE\n  zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);\n  if( zTrace ){\n    int j;\n    for(j=0; j<db->nDb; j++){\n      if( DbMaskTest(p->btreeMask, j)==0 ) continue;\n      sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);\n    }\n  }\n#endif /* SQLITE_USE_FCNTL_TRACE */\n#ifdef SQLITE_DEBUG\n  if( (db->flags & SQLITE_SqlTrace)!=0\n   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0\n  ){\n    sqlite3DebugPrintf(\"SQL-trace: %s\\n\", zTrace);\n  }\n#endif /* SQLITE_DEBUG */\n#endif /* SQLITE_OMIT_TRACE */\n  assert( pOp->p2>0 );\n  if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){\n    if( pOp->opcode==OP_Trace ) break;\n    for(i=1; i<p->nOp; i++){\n      if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;\n    }\n    pOp->p1 = 0;\n  }\n  pOp->p1++;\n  p->aCounter[SQLITE_STMTSTATUS_RUN]++;\n  goto jump_to_p2;\n}\n\n#ifdef SQLITE_ENABLE_CURSOR_HINTS\n/* Opcode: CursorHint P1 * * P4 *\n**\n** Provide a hint to cursor P1 that it only needs to return rows that\n** satisfy the Expr in P4.  TK_REGISTER terms in the P4 expression refer\n** to values currently held in registers.  TK_COLUMN terms in the P4\n** expression refer to columns in the b-tree to which cursor P1 is pointing.\n*/\ncase OP_CursorHint: {\n  VdbeCursor *pC;\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  assert( pOp->p4type==P4_EXPR );\n  pC = p->apCsr[pOp->p1];\n  if( pC ){\n    assert( pC->eCurType==CURTYPE_BTREE );\n    sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,\n                           pOp->p4.pExpr, aMem);\n  }\n  break;\n}\n#endif /* SQLITE_ENABLE_CURSOR_HINTS */\n\n#ifdef SQLITE_DEBUG\n/* Opcode:  Abortable   * * * * *\n**\n** Verify that an Abort can happen.  Assert if an Abort at this point\n** might cause database corruption.  This opcode only appears in debugging\n** builds.\n**\n** An Abort is safe if either there have been no writes, or if there is\n** an active statement journal.\n*/\ncase OP_Abortable: {\n  sqlite3VdbeAssertAbortable(p);\n  break;\n}\n#endif\n\n#ifdef SQLITE_DEBUG\n/* Opcode:  ReleaseReg   P1 P2 P3 * P5\n** Synopsis: release r[P1@P2] mask P3\n**\n** Release registers from service.  Any content that was in the\n** the registers is unreliable after this opcode completes.\n**\n** The registers released will be the P2 registers starting at P1,\n** except if bit ii of P3 set, then do not release register P1+ii.\n** In other words, P3 is a mask of registers to preserve.\n**\n** Releasing a register clears the Mem.pScopyFrom pointer.  That means\n** that if the content of the released register was set using OP_SCopy,\n** a change to the value of the source register for the OP_SCopy will no longer\n** generate an assertion fault in sqlite3VdbeMemAboutToChange().\n**\n** If P5 is set, then all released registers have their type set\n** to MEM_Undefined so that any subsequent attempt to read the released\n** register (before it is reinitialized) will generate an assertion fault.\n**\n** P5 ought to be set on every call to this opcode.\n** However, there are places in the code generator will release registers\n** before their are used, under the (valid) assumption that the registers\n** will not be reallocated for some other purpose before they are used and\n** hence are safe to release.\n**\n** This opcode is only available in testing and debugging builds.  It is\n** not generated for release builds.  The purpose of this opcode is to help\n** validate the generated bytecode.  This opcode does not actually contribute\n** to computing an answer.\n*/\ncase OP_ReleaseReg: {\n  Mem *pMem;\n  int i;\n  u32 constMask;\n  assert( pOp->p1>0 );\n  assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );\n  pMem = &aMem[pOp->p1];\n  constMask = pOp->p3;\n  for(i=0; i<pOp->p2; i++, pMem++){\n    if( i>=32 || (constMask & MASKBIT32(i))==0 ){\n      pMem->pScopyFrom = 0;\n      if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined);\n    }\n  }\n  break;\n}\n#endif\n\n/* Opcode: Noop * * * * *\n**\n** Do nothing.  This instruction is often useful as a jump\n** destination.\n*/\n/*\n** The magic Explain opcode are only inserted when explain==2 (which\n** is to say when the EXPLAIN QUERY PLAN syntax is used.)\n** This opcode records information from the optimizer.  It is the\n** the same as a no-op.  This opcodesnever appears in a real VM program.\n*/\ndefault: {          /* This is really OP_Noop, OP_Explain */\n  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );\n\n  break;\n}\n\n/*****************************************************************************\n** The cases of the switch statement above this line should all be indented\n** by 6 spaces.  But the left-most 6 spaces have been removed to improve the\n** readability.  From this point on down, the normal indentation rules are\n** restored.\n*****************************************************************************/\n    }\n\n#ifdef VDBE_PROFILE\n    {\n      u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();\n      if( endTime>start ) pOrigOp->cycles += endTime - start;\n      pOrigOp->cnt++;\n    }\n#endif\n\n    /* The following code adds nothing to the actual functionality\n    ** of the program.  It is only here for testing and debugging.\n    ** On the other hand, it does burn CPU cycles every time through\n    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.\n    */\n#ifndef NDEBUG\n    assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );\n\n#ifdef SQLITE_DEBUG\n    if( db->flags & SQLITE_VdbeTrace ){\n      u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];\n      if( rc!=0 ) printf(\"rc=%d\\n\",rc);\n      if( opProperty & (OPFLG_OUT2) ){\n        registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);\n      }\n      if( opProperty & OPFLG_OUT3 ){\n        registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);\n      }\n      if( opProperty==0xff ){\n        /* Never happens.  This code exists to avoid a harmless linkage\n        ** warning aboud sqlite3VdbeRegisterDump() being defined but not\n        ** used. */\n        sqlite3VdbeRegisterDump(p);\n      }\n    }\n#endif  /* SQLITE_DEBUG */\n#endif  /* NDEBUG */\n  }  /* The end of the for(;;) loop the loops through opcodes */\n\n  /* If we reach this point, it means that execution is finished with\n  ** an error of some kind.\n  */\nabort_due_to_error:\n  if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;\n  assert( rc );\n  if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){\n    sqlite3VdbeError(p, \"%s\", sqlite3ErrStr(rc));\n  }\n  p->rc = rc;\n  sqlite3SystemError(db, rc);\n  testcase( sqlite3GlobalConfig.xLog!=0 );\n  sqlite3_log(rc, \"statement aborts at %d: [%s] %s\", \n                   (int)(pOp - aOp), p->zSql, p->zErrMsg);\n  sqlite3VdbeHalt(p);\n  if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);\n  rc = SQLITE_ERROR;\n  if( resetSchemaOnFault>0 ){\n    sqlite3ResetOneSchema(db, resetSchemaOnFault-1);\n  }\n\n  /* This is the only way out of this procedure.  We have to\n  ** release the mutexes on btrees that were acquired at the\n  ** top. */\nvdbe_return:\n#ifndef SQLITE_OMIT_PROGRESS_CALLBACK\n  while( nVmStep>=nProgressLimit && db->xProgress!=0 ){\n    nProgressLimit += db->nProgressOps;\n    if( db->xProgress(db->pProgressArg) ){\n      nProgressLimit = 0xffffffff;\n      rc = SQLITE_INTERRUPT;\n      goto abort_due_to_error;\n    }\n  }\n#endif\n  p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;\n  sqlite3VdbeLeave(p);\n  assert( rc!=SQLITE_OK || nExtraDelete==0 \n       || sqlite3_strlike(\"DELETE%\",p->zSql,0)!=0 \n  );\n  return rc;\n\n  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH\n  ** is encountered.\n  */\ntoo_big:\n  sqlite3VdbeError(p, \"string or blob too big\");\n  rc = SQLITE_TOOBIG;\n  goto abort_due_to_error;\n\n  /* Jump to here if a malloc() fails.\n  */\nno_mem:\n  sqlite3OomFault(db);\n  sqlite3VdbeError(p, \"out of memory\");\n  rc = SQLITE_NOMEM_BKPT;\n  goto abort_due_to_error;\n\n  /* Jump to here if the sqlite3_interrupt() API sets the interrupt\n  ** flag.\n  */\nabort_due_to_interrupt:\n  assert( AtomicLoad(&db->u1.isInterrupted) );\n  rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;\n  p->rc = rc;\n  sqlite3VdbeError(p, \"%s\", sqlite3ErrStr(rc));\n  goto abort_due_to_error;\n}\n\n\n/************** End of vdbe.c ************************************************/\n/************** Begin file vdbeblob.c ****************************************/\n/*\n** 2007 May 1\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains code used to implement incremental BLOB I/O.\n*/\n\n/* #include \"sqliteInt.h\" */\n/* #include \"vdbeInt.h\" */\n\n#ifndef SQLITE_OMIT_INCRBLOB\n\n/*\n** Valid sqlite3_blob* handles point to Incrblob structures.\n*/\ntypedef struct Incrblob Incrblob;\nstruct Incrblob {\n  int nByte;              /* Size of open blob, in bytes */\n  int iOffset;            /* Byte offset of blob in cursor data */\n  u16 iCol;               /* Table column this handle is open on */\n  BtCursor *pCsr;         /* Cursor pointing at blob row */\n  sqlite3_stmt *pStmt;    /* Statement holding cursor open */\n  sqlite3 *db;            /* The associated database */\n  char *zDb;              /* Database name */\n  Table *pTab;            /* Table object */\n};\n\n\n/*\n** This function is used by both blob_open() and blob_reopen(). It seeks\n** the b-tree cursor associated with blob handle p to point to row iRow.\n** If successful, SQLITE_OK is returned and subsequent calls to\n** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.\n**\n** If an error occurs, or if the specified row does not exist or does not\n** contain a value of type TEXT or BLOB in the column nominated when the\n** blob handle was opened, then an error code is returned and *pzErr may\n** be set to point to a buffer containing an error message. It is the\n** responsibility of the caller to free the error message buffer using\n** sqlite3DbFree().\n**\n** If an error does occur, then the b-tree cursor is closed. All subsequent\n** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will \n** immediately return SQLITE_ABORT.\n*/\nstatic int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){\n  int rc;                         /* Error code */\n  char *zErr = 0;                 /* Error message */\n  Vdbe *v = (Vdbe *)p->pStmt;\n\n  /* Set the value of register r[1] in the SQL statement to integer iRow. \n  ** This is done directly as a performance optimization\n  */\n  v->aMem[1].flags = MEM_Int;\n  v->aMem[1].u.i = iRow;\n\n  /* If the statement has been run before (and is paused at the OP_ResultRow)\n  ** then back it up to the point where it does the OP_NotExists.  This could\n  ** have been down with an extra OP_Goto, but simply setting the program\n  ** counter is faster. */\n  if( v->pc>4 ){\n    v->pc = 4;\n    assert( v->aOp[v->pc].opcode==OP_NotExists );\n    rc = sqlite3VdbeExec(v);\n  }else{\n    rc = sqlite3_step(p->pStmt);\n  }\n  if( rc==SQLITE_ROW ){\n    VdbeCursor *pC = v->apCsr[0];\n    u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;\n    testcase( pC->nHdrParsed==p->iCol );\n    testcase( pC->nHdrParsed==p->iCol+1 );\n    if( type<12 ){\n      zErr = sqlite3MPrintf(p->db, \"cannot open value of type %s\",\n          type==0?\"null\": type==7?\"real\": \"integer\"\n      );\n      rc = SQLITE_ERROR;\n      sqlite3_finalize(p->pStmt);\n      p->pStmt = 0;\n    }else{\n      p->iOffset = pC->aType[p->iCol + pC->nField];\n      p->nByte = sqlite3VdbeSerialTypeLen(type);\n      p->pCsr =  pC->uc.pCursor;\n      sqlite3BtreeIncrblobCursor(p->pCsr);\n    }\n  }\n\n  if( rc==SQLITE_ROW ){\n    rc = SQLITE_OK;\n  }else if( p->pStmt ){\n    rc = sqlite3_finalize(p->pStmt);\n    p->pStmt = 0;\n    if( rc==SQLITE_OK ){\n      zErr = sqlite3MPrintf(p->db, \"no such rowid: %lld\", iRow);\n      rc = SQLITE_ERROR;\n    }else{\n      zErr = sqlite3MPrintf(p->db, \"%s\", sqlite3_errmsg(p->db));\n    }\n  }\n\n  assert( rc!=SQLITE_OK || zErr==0 );\n  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );\n\n  *pzErr = zErr;\n  return rc;\n}\n\n/*\n** Open a blob handle.\n*/\nSQLITE_API int sqlite3_blob_open(\n  sqlite3* db,            /* The database connection */\n  const char *zDb,        /* The attached database containing the blob */\n  const char *zTable,     /* The table containing the blob */\n  const char *zColumn,    /* The column containing the blob */\n  sqlite_int64 iRow,      /* The row containing the glob */\n  int wrFlag,             /* True -> read/write access, false -> read-only */\n  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */\n){\n  int nAttempt = 0;\n  int iCol;               /* Index of zColumn in row-record */\n  int rc = SQLITE_OK;\n  char *zErr = 0;\n  Table *pTab;\n  Incrblob *pBlob = 0;\n  Parse sParse;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( ppBlob==0 ){\n    return SQLITE_MISUSE_BKPT;\n  }\n#endif\n  *ppBlob = 0;\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) || zTable==0 ){\n    return SQLITE_MISUSE_BKPT;\n  }\n#endif\n  wrFlag = !!wrFlag;                /* wrFlag = (wrFlag ? 1 : 0); */\n\n  sqlite3_mutex_enter(db->mutex);\n\n  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));\n  do {\n    memset(&sParse, 0, sizeof(Parse));\n    if( !pBlob ) goto blob_open_out;\n    sParse.db = db;\n    sqlite3DbFree(db, zErr);\n    zErr = 0;\n\n    sqlite3BtreeEnterAll(db);\n    pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);\n    if( pTab && IsVirtual(pTab) ){\n      pTab = 0;\n      sqlite3ErrorMsg(&sParse, \"cannot open virtual table: %s\", zTable);\n    }\n    if( pTab && !HasRowid(pTab) ){\n      pTab = 0;\n      sqlite3ErrorMsg(&sParse, \"cannot open table without rowid: %s\", zTable);\n    }\n#ifndef SQLITE_OMIT_VIEW\n    if( pTab && pTab->pSelect ){\n      pTab = 0;\n      sqlite3ErrorMsg(&sParse, \"cannot open view: %s\", zTable);\n    }\n#endif\n    if( !pTab ){\n      if( sParse.zErrMsg ){\n        sqlite3DbFree(db, zErr);\n        zErr = sParse.zErrMsg;\n        sParse.zErrMsg = 0;\n      }\n      rc = SQLITE_ERROR;\n      sqlite3BtreeLeaveAll(db);\n      goto blob_open_out;\n    }\n    pBlob->pTab = pTab;\n    pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;\n\n    /* Now search pTab for the exact column. */\n    for(iCol=0; iCol<pTab->nCol; iCol++) {\n      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){\n        break;\n      }\n    }\n    if( iCol==pTab->nCol ){\n      sqlite3DbFree(db, zErr);\n      zErr = sqlite3MPrintf(db, \"no such column: \\\"%s\\\"\", zColumn);\n      rc = SQLITE_ERROR;\n      sqlite3BtreeLeaveAll(db);\n      goto blob_open_out;\n    }\n\n    /* If the value is being opened for writing, check that the\n    ** column is not indexed, and that it is not part of a foreign key. \n    */\n    if( wrFlag ){\n      const char *zFault = 0;\n      Index *pIdx;\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n      if( db->flags&SQLITE_ForeignKeys ){\n        /* Check that the column is not part of an FK child key definition. It\n        ** is not necessary to check if it is part of a parent key, as parent\n        ** key columns must be indexed. The check below will pick up this \n        ** case.  */\n        FKey *pFKey;\n        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){\n          int j;\n          for(j=0; j<pFKey->nCol; j++){\n            if( pFKey->aCol[j].iFrom==iCol ){\n              zFault = \"foreign key\";\n            }\n          }\n        }\n      }\n#endif\n      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n        int j;\n        for(j=0; j<pIdx->nKeyCol; j++){\n          /* FIXME: Be smarter about indexes that use expressions */\n          if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){\n            zFault = \"indexed\";\n          }\n        }\n      }\n      if( zFault ){\n        sqlite3DbFree(db, zErr);\n        zErr = sqlite3MPrintf(db, \"cannot open %s column for writing\", zFault);\n        rc = SQLITE_ERROR;\n        sqlite3BtreeLeaveAll(db);\n        goto blob_open_out;\n      }\n    }\n\n    pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);\n    assert( pBlob->pStmt || db->mallocFailed );\n    if( pBlob->pStmt ){\n      \n      /* This VDBE program seeks a btree cursor to the identified \n      ** db/table/row entry. The reason for using a vdbe program instead\n      ** of writing code to use the b-tree layer directly is that the\n      ** vdbe program will take advantage of the various transaction,\n      ** locking and error handling infrastructure built into the vdbe.\n      **\n      ** After seeking the cursor, the vdbe executes an OP_ResultRow.\n      ** Code external to the Vdbe then \"borrows\" the b-tree cursor and\n      ** uses it to implement the blob_read(), blob_write() and \n      ** blob_bytes() functions.\n      **\n      ** The sqlite3_blob_close() function finalizes the vdbe program,\n      ** which closes the b-tree cursor and (possibly) commits the \n      ** transaction.\n      */\n      static const int iLn = VDBE_OFFSET_LINENO(2);\n      static const VdbeOpList openBlob[] = {\n        {OP_TableLock,      0, 0, 0},  /* 0: Acquire a read or write lock */\n        {OP_OpenRead,       0, 0, 0},  /* 1: Open a cursor */\n        /* blobSeekToRow() will initialize r[1] to the desired rowid */\n        {OP_NotExists,      0, 5, 1},  /* 2: Seek the cursor to rowid=r[1] */\n        {OP_Column,         0, 0, 1},  /* 3  */\n        {OP_ResultRow,      1, 0, 0},  /* 4  */\n        {OP_Halt,           0, 0, 0},  /* 5  */\n      };\n      Vdbe *v = (Vdbe *)pBlob->pStmt;\n      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n      VdbeOp *aOp;\n\n      sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag, \n                           pTab->pSchema->schema_cookie,\n                           pTab->pSchema->iGeneration);\n      sqlite3VdbeChangeP5(v, 1);\n      assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );\n      aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);\n\n      /* Make sure a mutex is held on the table to be accessed */\n      sqlite3VdbeUsesBtree(v, iDb); \n\n      if( db->mallocFailed==0 ){\n        assert( aOp!=0 );\n        /* Configure the OP_TableLock instruction */\n#ifdef SQLITE_OMIT_SHARED_CACHE\n        aOp[0].opcode = OP_Noop;\n#else\n        aOp[0].p1 = iDb;\n        aOp[0].p2 = pTab->tnum;\n        aOp[0].p3 = wrFlag;\n        sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);\n      }\n      if( db->mallocFailed==0 ){\n#endif\n\n        /* Remove either the OP_OpenWrite or OpenRead. Set the P2 \n        ** parameter of the other to pTab->tnum.  */\n        if( wrFlag ) aOp[1].opcode = OP_OpenWrite;\n        aOp[1].p2 = pTab->tnum;\n        aOp[1].p3 = iDb;   \n\n        /* Configure the number of columns. Configure the cursor to\n        ** think that the table has one more column than it really\n        ** does. An OP_Column to retrieve this imaginary column will\n        ** always return an SQL NULL. This is useful because it means\n        ** we can invoke OP_Column to fill in the vdbe cursors type \n        ** and offset cache without causing any IO.\n        */\n        aOp[1].p4type = P4_INT32;\n        aOp[1].p4.i = pTab->nCol+1;\n        aOp[3].p2 = pTab->nCol;\n\n        sParse.nVar = 0;\n        sParse.nMem = 1;\n        sParse.nTab = 1;\n        sqlite3VdbeMakeReady(v, &sParse);\n      }\n    }\n   \n    pBlob->iCol = iCol;\n    pBlob->db = db;\n    sqlite3BtreeLeaveAll(db);\n    if( db->mallocFailed ){\n      goto blob_open_out;\n    }\n    rc = blobSeekToRow(pBlob, iRow, &zErr);\n  } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );\n\nblob_open_out:\n  if( rc==SQLITE_OK && db->mallocFailed==0 ){\n    *ppBlob = (sqlite3_blob *)pBlob;\n  }else{\n    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);\n    sqlite3DbFree(db, pBlob);\n  }\n  sqlite3ErrorWithMsg(db, rc, (zErr ? \"%s\" : 0), zErr);\n  sqlite3DbFree(db, zErr);\n  sqlite3ParserReset(&sParse);\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** Close a blob handle that was previously created using\n** sqlite3_blob_open().\n*/\nSQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){\n  Incrblob *p = (Incrblob *)pBlob;\n  int rc;\n  sqlite3 *db;\n\n  if( p ){\n    sqlite3_stmt *pStmt = p->pStmt;\n    db = p->db;\n    sqlite3_mutex_enter(db->mutex);\n    sqlite3DbFree(db, p);\n    sqlite3_mutex_leave(db->mutex);\n    rc = sqlite3_finalize(pStmt);\n  }else{\n    rc = SQLITE_OK;\n  }\n  return rc;\n}\n\n/*\n** Perform a read or write operation on a blob\n*/\nstatic int blobReadWrite(\n  sqlite3_blob *pBlob, \n  void *z, \n  int n, \n  int iOffset, \n  int (*xCall)(BtCursor*, u32, u32, void*)\n){\n  int rc;\n  Incrblob *p = (Incrblob *)pBlob;\n  Vdbe *v;\n  sqlite3 *db;\n\n  if( p==0 ) return SQLITE_MISUSE_BKPT;\n  db = p->db;\n  sqlite3_mutex_enter(db->mutex);\n  v = (Vdbe*)p->pStmt;\n\n  if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){\n    /* Request is out of range. Return a transient error. */\n    rc = SQLITE_ERROR;\n  }else if( v==0 ){\n    /* If there is no statement handle, then the blob-handle has\n    ** already been invalidated. Return SQLITE_ABORT in this case.\n    */\n    rc = SQLITE_ABORT;\n  }else{\n    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is\n    ** returned, clean-up the statement handle.\n    */\n    assert( db == v->db );\n    sqlite3BtreeEnterCursor(p->pCsr);\n\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n    if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){\n      /* If a pre-update hook is registered and this is a write cursor, \n      ** invoke it here. \n      ** \n      ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this\n      ** operation should really be an SQLITE_UPDATE. This is probably\n      ** incorrect, but is convenient because at this point the new.* values \n      ** are not easily obtainable. And for the sessions module, an \n      ** SQLITE_UPDATE where the PK columns do not change is handled in the \n      ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually\n      ** slightly more efficient). Since you cannot write to a PK column\n      ** using the incremental-blob API, this works. For the sessions module\n      ** anyhow.\n      */\n      sqlite3_int64 iKey;\n      iKey = sqlite3BtreeIntegerKey(p->pCsr);\n      sqlite3VdbePreUpdateHook(\n          v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1\n      );\n    }\n#endif\n\n    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);\n    sqlite3BtreeLeaveCursor(p->pCsr);\n    if( rc==SQLITE_ABORT ){\n      sqlite3VdbeFinalize(v);\n      p->pStmt = 0;\n    }else{\n      v->rc = rc;\n    }\n  }\n  sqlite3Error(db, rc);\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** Read data from a blob handle.\n*/\nSQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){\n  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);\n}\n\n/*\n** Write data to a blob handle.\n*/\nSQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){\n  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);\n}\n\n/*\n** Query a blob handle for the size of the data.\n**\n** The Incrblob.nByte field is fixed for the lifetime of the Incrblob\n** so no mutex is required for access.\n*/\nSQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){\n  Incrblob *p = (Incrblob *)pBlob;\n  return (p && p->pStmt) ? p->nByte : 0;\n}\n\n/*\n** Move an existing blob handle to point to a different row of the same\n** database table.\n**\n** If an error occurs, or if the specified row does not exist or does not\n** contain a blob or text value, then an error code is returned and the\n** database handle error code and message set. If this happens, then all \n** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) \n** immediately return SQLITE_ABORT.\n*/\nSQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){\n  int rc;\n  Incrblob *p = (Incrblob *)pBlob;\n  sqlite3 *db;\n\n  if( p==0 ) return SQLITE_MISUSE_BKPT;\n  db = p->db;\n  sqlite3_mutex_enter(db->mutex);\n\n  if( p->pStmt==0 ){\n    /* If there is no statement handle, then the blob-handle has\n    ** already been invalidated. Return SQLITE_ABORT in this case.\n    */\n    rc = SQLITE_ABORT;\n  }else{\n    char *zErr;\n    rc = blobSeekToRow(p, iRow, &zErr);\n    if( rc!=SQLITE_OK ){\n      sqlite3ErrorWithMsg(db, rc, (zErr ? \"%s\" : 0), zErr);\n      sqlite3DbFree(db, zErr);\n    }\n    assert( rc!=SQLITE_SCHEMA );\n  }\n\n  rc = sqlite3ApiExit(db, rc);\n  assert( rc==SQLITE_OK || p->pStmt==0 );\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n#endif /* #ifndef SQLITE_OMIT_INCRBLOB */\n\n/************** End of vdbeblob.c ********************************************/\n/************** Begin file vdbesort.c ****************************************/\n/*\n** 2011-07-09\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code for the VdbeSorter object, used in concert with\n** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements\n** or by SELECT statements with ORDER BY clauses that cannot be satisfied\n** using indexes and without LIMIT clauses.\n**\n** The VdbeSorter object implements a multi-threaded external merge sort\n** algorithm that is efficient even if the number of elements being sorted\n** exceeds the available memory.\n**\n** Here is the (internal, non-API) interface between this module and the\n** rest of the SQLite system:\n**\n**    sqlite3VdbeSorterInit()       Create a new VdbeSorter object.\n**\n**    sqlite3VdbeSorterWrite()      Add a single new row to the VdbeSorter\n**                                  object.  The row is a binary blob in the\n**                                  OP_MakeRecord format that contains both\n**                                  the ORDER BY key columns and result columns\n**                                  in the case of a SELECT w/ ORDER BY, or\n**                                  the complete record for an index entry\n**                                  in the case of a CREATE INDEX.\n**\n**    sqlite3VdbeSorterRewind()     Sort all content previously added.\n**                                  Position the read cursor on the\n**                                  first sorted element.\n**\n**    sqlite3VdbeSorterNext()       Advance the read cursor to the next sorted\n**                                  element.\n**\n**    sqlite3VdbeSorterRowkey()     Return the complete binary blob for the\n**                                  row currently under the read cursor.\n**\n**    sqlite3VdbeSorterCompare()    Compare the binary blob for the row\n**                                  currently under the read cursor against\n**                                  another binary blob X and report if\n**                                  X is strictly less than the read cursor.\n**                                  Used to enforce uniqueness in a\n**                                  CREATE UNIQUE INDEX statement.\n**\n**    sqlite3VdbeSorterClose()      Close the VdbeSorter object and reclaim\n**                                  all resources.\n**\n**    sqlite3VdbeSorterReset()      Refurbish the VdbeSorter for reuse.  This\n**                                  is like Close() followed by Init() only\n**                                  much faster.\n**\n** The interfaces above must be called in a particular order.  Write() can \n** only occur in between Init()/Reset() and Rewind().  Next(), Rowkey(), and\n** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.\n**\n**   Init()\n**   for each record: Write()\n**   Rewind()\n**     Rowkey()/Compare()\n**   Next() \n**   Close()\n**\n** Algorithm:\n**\n** Records passed to the sorter via calls to Write() are initially held \n** unsorted in main memory. Assuming the amount of memory used never exceeds\n** a threshold, when Rewind() is called the set of records is sorted using\n** an in-memory merge sort. In this case, no temporary files are required\n** and subsequent calls to Rowkey(), Next() and Compare() read records \n** directly from main memory.\n**\n** If the amount of space used to store records in main memory exceeds the\n** threshold, then the set of records currently in memory are sorted and\n** written to a temporary file in \"Packed Memory Array\" (PMA) format.\n** A PMA created at this point is known as a \"level-0 PMA\". Higher levels\n** of PMAs may be created by merging existing PMAs together - for example\n** merging two or more level-0 PMAs together creates a level-1 PMA.\n**\n** The threshold for the amount of main memory to use before flushing \n** records to a PMA is roughly the same as the limit configured for the\n** page-cache of the main database. Specifically, the threshold is set to \n** the value returned by \"PRAGMA main.page_size\" multipled by \n** that returned by \"PRAGMA main.cache_size\", in bytes.\n**\n** If the sorter is running in single-threaded mode, then all PMAs generated\n** are appended to a single temporary file. Or, if the sorter is running in\n** multi-threaded mode then up to (N+1) temporary files may be opened, where\n** N is the configured number of worker threads. In this case, instead of\n** sorting the records and writing the PMA to a temporary file itself, the\n** calling thread usually launches a worker thread to do so. Except, if\n** there are already N worker threads running, the main thread does the work\n** itself.\n**\n** The sorter is running in multi-threaded mode if (a) the library was built\n** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater\n** than zero, and (b) worker threads have been enabled at runtime by calling\n** \"PRAGMA threads=N\" with some value of N greater than 0.\n**\n** When Rewind() is called, any data remaining in memory is flushed to a \n** final PMA. So at this point the data is stored in some number of sorted\n** PMAs within temporary files on disk.\n**\n** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the\n** sorter is running in single-threaded mode, then these PMAs are merged\n** incrementally as keys are retreived from the sorter by the VDBE.  The\n** MergeEngine object, described in further detail below, performs this\n** merge.\n**\n** Or, if running in multi-threaded mode, then a background thread is\n** launched to merge the existing PMAs. Once the background thread has\n** merged T bytes of data into a single sorted PMA, the main thread \n** begins reading keys from that PMA while the background thread proceeds\n** with merging the next T bytes of data. And so on.\n**\n** Parameter T is set to half the value of the memory threshold used \n** by Write() above to determine when to create a new PMA.\n**\n** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when \n** Rewind() is called, then a hierarchy of incremental-merges is used. \n** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on \n** disk are merged together. Then T bytes of data from the second set, and\n** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT\n** PMAs at a time. This done is to improve locality.\n**\n** If running in multi-threaded mode and there are more than\n** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more\n** than one background thread may be created. Specifically, there may be\n** one background thread for each temporary file on disk, and one background\n** thread to merge the output of each of the others to a single PMA for\n** the main thread to read from.\n*/\n/* #include \"sqliteInt.h\" */\n/* #include \"vdbeInt.h\" */\n\n/* \n** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various\n** messages to stderr that may be helpful in understanding the performance\n** characteristics of the sorter in multi-threaded mode.\n*/\n#if 0\n# define SQLITE_DEBUG_SORTER_THREADS 1\n#endif\n\n/*\n** Hard-coded maximum amount of data to accumulate in memory before flushing\n** to a level 0 PMA. The purpose of this limit is to prevent various integer\n** overflows. 512MiB.\n*/\n#define SQLITE_MAX_PMASZ    (1<<29)\n\n/*\n** Private objects used by the sorter\n*/\ntypedef struct MergeEngine MergeEngine;     /* Merge PMAs together */\ntypedef struct PmaReader PmaReader;         /* Incrementally read one PMA */\ntypedef struct PmaWriter PmaWriter;         /* Incrementally write one PMA */\ntypedef struct SorterRecord SorterRecord;   /* A record being sorted */\ntypedef struct SortSubtask SortSubtask;     /* A sub-task in the sort process */\ntypedef struct SorterFile SorterFile;       /* Temporary file object wrapper */\ntypedef struct SorterList SorterList;       /* In-memory list of records */\ntypedef struct IncrMerger IncrMerger;       /* Read & merge multiple PMAs */\n\n/*\n** A container for a temp file handle and the current amount of data \n** stored in the file.\n*/\nstruct SorterFile {\n  sqlite3_file *pFd;              /* File handle */\n  i64 iEof;                       /* Bytes of data stored in pFd */\n};\n\n/*\n** An in-memory list of objects to be sorted.\n**\n** If aMemory==0 then each object is allocated separately and the objects\n** are connected using SorterRecord.u.pNext.  If aMemory!=0 then all objects\n** are stored in the aMemory[] bulk memory, one right after the other, and\n** are connected using SorterRecord.u.iNext.\n*/\nstruct SorterList {\n  SorterRecord *pList;            /* Linked list of records */\n  u8 *aMemory;                    /* If non-NULL, bulk memory to hold pList */\n  int szPMA;                      /* Size of pList as PMA in bytes */\n};\n\n/*\n** The MergeEngine object is used to combine two or more smaller PMAs into\n** one big PMA using a merge operation.  Separate PMAs all need to be\n** combined into one big PMA in order to be able to step through the sorted\n** records in order.\n**\n** The aReadr[] array contains a PmaReader object for each of the PMAs being\n** merged.  An aReadr[] object either points to a valid key or else is at EOF.\n** (\"EOF\" means \"End Of File\".  When aReadr[] is at EOF there is no more data.)\n** For the purposes of the paragraphs below, we assume that the array is\n** actually N elements in size, where N is the smallest power of 2 greater\n** to or equal to the number of PMAs being merged. The extra aReadr[] elements\n** are treated as if they are empty (always at EOF).\n**\n** The aTree[] array is also N elements in size. The value of N is stored in\n** the MergeEngine.nTree variable.\n**\n** The final (N/2) elements of aTree[] contain the results of comparing\n** pairs of PMA keys together. Element i contains the result of \n** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the\n** aTree element is set to the index of it. \n**\n** For the purposes of this comparison, EOF is considered greater than any\n** other key value. If the keys are equal (only possible with two EOF\n** values), it doesn't matter which index is stored.\n**\n** The (N/4) elements of aTree[] that precede the final (N/2) described \n** above contains the index of the smallest of each block of 4 PmaReaders\n** And so on. So that aTree[1] contains the index of the PmaReader that \n** currently points to the smallest key value. aTree[0] is unused.\n**\n** Example:\n**\n**     aReadr[0] -> Banana\n**     aReadr[1] -> Feijoa\n**     aReadr[2] -> Elderberry\n**     aReadr[3] -> Currant\n**     aReadr[4] -> Grapefruit\n**     aReadr[5] -> Apple\n**     aReadr[6] -> Durian\n**     aReadr[7] -> EOF\n**\n**     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }\n**\n** The current element is \"Apple\" (the value of the key indicated by \n** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will\n** be advanced to the next key in its segment. Say the next key is\n** \"Eggplant\":\n**\n**     aReadr[5] -> Eggplant\n**\n** The contents of aTree[] are updated first by comparing the new PmaReader\n** 5 key to the current key of PmaReader 4 (still \"Grapefruit\"). The PmaReader\n** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.\n** The value of PmaReader 6 - \"Durian\" - is now smaller than that of PmaReader\n** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),\n** so the value written into element 1 of the array is 0. As follows:\n**\n**     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }\n**\n** In other words, each time we advance to the next sorter element, log2(N)\n** key comparison operations are required, where N is the number of segments\n** being merged (rounded up to the next power of 2).\n*/\nstruct MergeEngine {\n  int nTree;                 /* Used size of aTree/aReadr (power of 2) */\n  SortSubtask *pTask;        /* Used by this thread only */\n  int *aTree;                /* Current state of incremental merge */\n  PmaReader *aReadr;         /* Array of PmaReaders to merge data from */\n};\n\n/*\n** This object represents a single thread of control in a sort operation.\n** Exactly VdbeSorter.nTask instances of this object are allocated\n** as part of each VdbeSorter object. Instances are never allocated any\n** other way. VdbeSorter.nTask is set to the number of worker threads allowed\n** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread).  Thus for\n** single-threaded operation, there is exactly one instance of this object\n** and for multi-threaded operation there are two or more instances.\n**\n** Essentially, this structure contains all those fields of the VdbeSorter\n** structure for which each thread requires a separate instance. For example,\n** each thread requries its own UnpackedRecord object to unpack records in\n** as part of comparison operations.\n**\n** Before a background thread is launched, variable bDone is set to 0. Then, \n** right before it exits, the thread itself sets bDone to 1. This is used for \n** two purposes:\n**\n**   1. When flushing the contents of memory to a level-0 PMA on disk, to\n**      attempt to select a SortSubtask for which there is not already an\n**      active background thread (since doing so causes the main thread\n**      to block until it finishes).\n**\n**   2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call\n**      to sqlite3ThreadJoin() is likely to block. Cases that are likely to\n**      block provoke debugging output.\n**\n** In both cases, the effects of the main thread seeing (bDone==0) even\n** after the thread has finished are not dire. So we don't worry about\n** memory barriers and such here.\n*/\ntypedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);\nstruct SortSubtask {\n  SQLiteThread *pThread;          /* Background thread, if any */\n  int bDone;                      /* Set if thread is finished but not joined */\n  VdbeSorter *pSorter;            /* Sorter that owns this sub-task */\n  UnpackedRecord *pUnpacked;      /* Space to unpack a record */\n  SorterList list;                /* List for thread to write to a PMA */\n  int nPMA;                       /* Number of PMAs currently in file */\n  SorterCompare xCompare;         /* Compare function to use */\n  SorterFile file;                /* Temp file for level-0 PMAs */\n  SorterFile file2;               /* Space for other PMAs */\n};\n\n\n/*\n** Main sorter structure. A single instance of this is allocated for each \n** sorter cursor created by the VDBE.\n**\n** mxKeysize:\n**   As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),\n**   this variable is updated so as to be set to the size on disk of the\n**   largest record in the sorter.\n*/\nstruct VdbeSorter {\n  int mnPmaSize;                  /* Minimum PMA size, in bytes */\n  int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */\n  int mxKeysize;                  /* Largest serialized key seen so far */\n  int pgsz;                       /* Main database page size */\n  PmaReader *pReader;             /* Readr data from here after Rewind() */\n  MergeEngine *pMerger;           /* Or here, if bUseThreads==0 */\n  sqlite3 *db;                    /* Database connection */\n  KeyInfo *pKeyInfo;              /* How to compare records */\n  UnpackedRecord *pUnpacked;      /* Used by VdbeSorterCompare() */\n  SorterList list;                /* List of in-memory records */\n  int iMemory;                    /* Offset of free space in list.aMemory */\n  int nMemory;                    /* Size of list.aMemory allocation in bytes */\n  u8 bUsePMA;                     /* True if one or more PMAs created */\n  u8 bUseThreads;                 /* True to use background threads */\n  u8 iPrev;                       /* Previous thread used to flush PMA */\n  u8 nTask;                       /* Size of aTask[] array */\n  u8 typeMask;\n  SortSubtask aTask[1];           /* One or more subtasks */\n};\n\n#define SORTER_TYPE_INTEGER 0x01\n#define SORTER_TYPE_TEXT    0x02\n\n/*\n** An instance of the following object is used to read records out of a\n** PMA, in sorted order.  The next key to be read is cached in nKey/aKey.\n** aKey might point into aMap or into aBuffer.  If neither of those locations\n** contain a contiguous representation of the key, then aAlloc is allocated\n** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.\n**\n** pFd==0 at EOF.\n*/\nstruct PmaReader {\n  i64 iReadOff;               /* Current read offset */\n  i64 iEof;                   /* 1 byte past EOF for this PmaReader */\n  int nAlloc;                 /* Bytes of space at aAlloc */\n  int nKey;                   /* Number of bytes in key */\n  sqlite3_file *pFd;          /* File handle we are reading from */\n  u8 *aAlloc;                 /* Space for aKey if aBuffer and pMap wont work */\n  u8 *aKey;                   /* Pointer to current key */\n  u8 *aBuffer;                /* Current read buffer */\n  int nBuffer;                /* Size of read buffer in bytes */\n  u8 *aMap;                   /* Pointer to mapping of entire file */\n  IncrMerger *pIncr;          /* Incremental merger */\n};\n\n/*\n** Normally, a PmaReader object iterates through an existing PMA stored \n** within a temp file. However, if the PmaReader.pIncr variable points to\n** an object of the following type, it may be used to iterate/merge through\n** multiple PMAs simultaneously.\n**\n** There are two types of IncrMerger object - single (bUseThread==0) and \n** multi-threaded (bUseThread==1). \n**\n** A multi-threaded IncrMerger object uses two temporary files - aFile[0] \n** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in \n** size. When the IncrMerger is initialized, it reads enough data from \n** pMerger to populate aFile[0]. It then sets variables within the \n** corresponding PmaReader object to read from that file and kicks off \n** a background thread to populate aFile[1] with the next mxSz bytes of \n** sorted record data from pMerger. \n**\n** When the PmaReader reaches the end of aFile[0], it blocks until the\n** background thread has finished populating aFile[1]. It then exchanges\n** the contents of the aFile[0] and aFile[1] variables within this structure,\n** sets the PmaReader fields to read from the new aFile[0] and kicks off\n** another background thread to populate the new aFile[1]. And so on, until\n** the contents of pMerger are exhausted.\n**\n** A single-threaded IncrMerger does not open any temporary files of its\n** own. Instead, it has exclusive access to mxSz bytes of space beginning\n** at offset iStartOff of file pTask->file2. And instead of using a \n** background thread to prepare data for the PmaReader, with a single\n** threaded IncrMerger the allocate part of pTask->file2 is \"refilled\" with\n** keys from pMerger by the calling thread whenever the PmaReader runs out\n** of data.\n*/\nstruct IncrMerger {\n  SortSubtask *pTask;             /* Task that owns this merger */\n  MergeEngine *pMerger;           /* Merge engine thread reads data from */\n  i64 iStartOff;                  /* Offset to start writing file at */\n  int mxSz;                       /* Maximum bytes of data to store */\n  int bEof;                       /* Set to true when merge is finished */\n  int bUseThread;                 /* True to use a bg thread for this object */\n  SorterFile aFile[2];            /* aFile[0] for reading, [1] for writing */\n};\n\n/*\n** An instance of this object is used for writing a PMA.\n**\n** The PMA is written one record at a time.  Each record is of an arbitrary\n** size.  But I/O is more efficient if it occurs in page-sized blocks where\n** each block is aligned on a page boundary.  This object caches writes to\n** the PMA so that aligned, page-size blocks are written.\n*/\nstruct PmaWriter {\n  int eFWErr;                     /* Non-zero if in an error state */\n  u8 *aBuffer;                    /* Pointer to write buffer */\n  int nBuffer;                    /* Size of write buffer in bytes */\n  int iBufStart;                  /* First byte of buffer to write */\n  int iBufEnd;                    /* Last byte of buffer to write */\n  i64 iWriteOff;                  /* Offset of start of buffer in file */\n  sqlite3_file *pFd;              /* File handle to write to */\n};\n\n/*\n** This object is the header on a single record while that record is being\n** held in memory and prior to being written out as part of a PMA.\n**\n** How the linked list is connected depends on how memory is being managed\n** by this module. If using a separate allocation for each in-memory record\n** (VdbeSorter.list.aMemory==0), then the list is always connected using the\n** SorterRecord.u.pNext pointers.\n**\n** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),\n** then while records are being accumulated the list is linked using the\n** SorterRecord.u.iNext offset. This is because the aMemory[] array may\n** be sqlite3Realloc()ed while records are being accumulated. Once the VM\n** has finished passing records to the sorter, or when the in-memory buffer\n** is full, the list is sorted. As part of the sorting process, it is\n** converted to use the SorterRecord.u.pNext pointers. See function\n** vdbeSorterSort() for details.\n*/\nstruct SorterRecord {\n  int nVal;                       /* Size of the record in bytes */\n  union {\n    SorterRecord *pNext;          /* Pointer to next record in list */\n    int iNext;                    /* Offset within aMemory of next record */\n  } u;\n  /* The data for the record immediately follows this header */\n};\n\n/* Return a pointer to the buffer containing the record data for SorterRecord\n** object p. Should be used as if:\n**\n**   void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }\n*/\n#define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))\n\n\n/* Maximum number of PMAs that a single MergeEngine can merge */\n#define SORTER_MAX_MERGE_COUNT 16\n\nstatic int vdbeIncrSwap(IncrMerger*);\nstatic void vdbeIncrFree(IncrMerger *);\n\n/*\n** Free all memory belonging to the PmaReader object passed as the\n** argument. All structure fields are set to zero before returning.\n*/\nstatic void vdbePmaReaderClear(PmaReader *pReadr){\n  sqlite3_free(pReadr->aAlloc);\n  sqlite3_free(pReadr->aBuffer);\n  if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);\n  vdbeIncrFree(pReadr->pIncr);\n  memset(pReadr, 0, sizeof(PmaReader));\n}\n\n/*\n** Read the next nByte bytes of data from the PMA p.\n** If successful, set *ppOut to point to a buffer containing the data\n** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite\n** error code.\n**\n** The buffer returned in *ppOut is only valid until the\n** next call to this function.\n*/\nstatic int vdbePmaReadBlob(\n  PmaReader *p,                   /* PmaReader from which to take the blob */\n  int nByte,                      /* Bytes of data to read */\n  u8 **ppOut                      /* OUT: Pointer to buffer containing data */\n){\n  int iBuf;                       /* Offset within buffer to read from */\n  int nAvail;                     /* Bytes of data available in buffer */\n\n  if( p->aMap ){\n    *ppOut = &p->aMap[p->iReadOff];\n    p->iReadOff += nByte;\n    return SQLITE_OK;\n  }\n\n  assert( p->aBuffer );\n\n  /* If there is no more data to be read from the buffer, read the next \n  ** p->nBuffer bytes of data from the file into it. Or, if there are less\n  ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */\n  iBuf = p->iReadOff % p->nBuffer;\n  if( iBuf==0 ){\n    int nRead;                    /* Bytes to read from disk */\n    int rc;                       /* sqlite3OsRead() return code */\n\n    /* Determine how many bytes of data to read. */\n    if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){\n      nRead = p->nBuffer;\n    }else{\n      nRead = (int)(p->iEof - p->iReadOff);\n    }\n    assert( nRead>0 );\n\n    /* Readr data from the file. Return early if an error occurs. */\n    rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);\n    assert( rc!=SQLITE_IOERR_SHORT_READ );\n    if( rc!=SQLITE_OK ) return rc;\n  }\n  nAvail = p->nBuffer - iBuf; \n\n  if( nByte<=nAvail ){\n    /* The requested data is available in the in-memory buffer. In this\n    ** case there is no need to make a copy of the data, just return a \n    ** pointer into the buffer to the caller.  */\n    *ppOut = &p->aBuffer[iBuf];\n    p->iReadOff += nByte;\n  }else{\n    /* The requested data is not all available in the in-memory buffer.\n    ** In this case, allocate space at p->aAlloc[] to copy the requested\n    ** range into. Then return a copy of pointer p->aAlloc to the caller.  */\n    int nRem;                     /* Bytes remaining to copy */\n\n    /* Extend the p->aAlloc[] allocation if required. */\n    if( p->nAlloc<nByte ){\n      u8 *aNew;\n      sqlite3_int64 nNew = MAX(128, 2*(sqlite3_int64)p->nAlloc);\n      while( nByte>nNew ) nNew = nNew*2;\n      aNew = sqlite3Realloc(p->aAlloc, nNew);\n      if( !aNew ) return SQLITE_NOMEM_BKPT;\n      p->nAlloc = nNew;\n      p->aAlloc = aNew;\n    }\n\n    /* Copy as much data as is available in the buffer into the start of\n    ** p->aAlloc[].  */\n    memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);\n    p->iReadOff += nAvail;\n    nRem = nByte - nAvail;\n\n    /* The following loop copies up to p->nBuffer bytes per iteration into\n    ** the p->aAlloc[] buffer.  */\n    while( nRem>0 ){\n      int rc;                     /* vdbePmaReadBlob() return code */\n      int nCopy;                  /* Number of bytes to copy */\n      u8 *aNext;                  /* Pointer to buffer to copy data from */\n\n      nCopy = nRem;\n      if( nRem>p->nBuffer ) nCopy = p->nBuffer;\n      rc = vdbePmaReadBlob(p, nCopy, &aNext);\n      if( rc!=SQLITE_OK ) return rc;\n      assert( aNext!=p->aAlloc );\n      memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);\n      nRem -= nCopy;\n    }\n\n    *ppOut = p->aAlloc;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Read a varint from the stream of data accessed by p. Set *pnOut to\n** the value read.\n*/\nstatic int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){\n  int iBuf;\n\n  if( p->aMap ){\n    p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);\n  }else{\n    iBuf = p->iReadOff % p->nBuffer;\n    if( iBuf && (p->nBuffer-iBuf)>=9 ){\n      p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);\n    }else{\n      u8 aVarint[16], *a;\n      int i = 0, rc;\n      do{\n        rc = vdbePmaReadBlob(p, 1, &a);\n        if( rc ) return rc;\n        aVarint[(i++)&0xf] = a[0];\n      }while( (a[0]&0x80)!=0 );\n      sqlite3GetVarint(aVarint, pnOut);\n    }\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Attempt to memory map file pFile. If successful, set *pp to point to the\n** new mapping and return SQLITE_OK. If the mapping is not attempted \n** (because the file is too large or the VFS layer is configured not to use\n** mmap), return SQLITE_OK and set *pp to NULL.\n**\n** Or, if an error occurs, return an SQLite error code. The final value of\n** *pp is undefined in this case.\n*/\nstatic int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){\n  int rc = SQLITE_OK;\n  if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){\n    sqlite3_file *pFd = pFile->pFd;\n    if( pFd->pMethods->iVersion>=3 ){\n      rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);\n      testcase( rc!=SQLITE_OK );\n    }\n  }\n  return rc;\n}\n\n/*\n** Attach PmaReader pReadr to file pFile (if it is not already attached to\n** that file) and seek it to offset iOff within the file.  Return SQLITE_OK \n** if successful, or an SQLite error code if an error occurs.\n*/\nstatic int vdbePmaReaderSeek(\n  SortSubtask *pTask,             /* Task context */\n  PmaReader *pReadr,              /* Reader whose cursor is to be moved */\n  SorterFile *pFile,              /* Sorter file to read from */\n  i64 iOff                        /* Offset in pFile */\n){\n  int rc = SQLITE_OK;\n\n  assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );\n\n  if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;\n  if( pReadr->aMap ){\n    sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);\n    pReadr->aMap = 0;\n  }\n  pReadr->iReadOff = iOff;\n  pReadr->iEof = pFile->iEof;\n  pReadr->pFd = pFile->pFd;\n\n  rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);\n  if( rc==SQLITE_OK && pReadr->aMap==0 ){\n    int pgsz = pTask->pSorter->pgsz;\n    int iBuf = pReadr->iReadOff % pgsz;\n    if( pReadr->aBuffer==0 ){\n      pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);\n      if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;\n      pReadr->nBuffer = pgsz;\n    }\n    if( rc==SQLITE_OK && iBuf ){\n      int nRead = pgsz - iBuf;\n      if( (pReadr->iReadOff + nRead) > pReadr->iEof ){\n        nRead = (int)(pReadr->iEof - pReadr->iReadOff);\n      }\n      rc = sqlite3OsRead(\n          pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff\n      );\n      testcase( rc!=SQLITE_OK );\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if\n** no error occurs, or an SQLite error code if one does.\n*/\nstatic int vdbePmaReaderNext(PmaReader *pReadr){\n  int rc = SQLITE_OK;             /* Return Code */\n  u64 nRec = 0;                   /* Size of record in bytes */\n\n\n  if( pReadr->iReadOff>=pReadr->iEof ){\n    IncrMerger *pIncr = pReadr->pIncr;\n    int bEof = 1;\n    if( pIncr ){\n      rc = vdbeIncrSwap(pIncr);\n      if( rc==SQLITE_OK && pIncr->bEof==0 ){\n        rc = vdbePmaReaderSeek(\n            pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff\n        );\n        bEof = 0;\n      }\n    }\n\n    if( bEof ){\n      /* This is an EOF condition */\n      vdbePmaReaderClear(pReadr);\n      testcase( rc!=SQLITE_OK );\n      return rc;\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = vdbePmaReadVarint(pReadr, &nRec);\n  }\n  if( rc==SQLITE_OK ){\n    pReadr->nKey = (int)nRec;\n    rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);\n    testcase( rc!=SQLITE_OK );\n  }\n\n  return rc;\n}\n\n/*\n** Initialize PmaReader pReadr to scan through the PMA stored in file pFile\n** starting at offset iStart and ending at offset iEof-1. This function \n** leaves the PmaReader pointing to the first key in the PMA (or EOF if the \n** PMA is empty).\n**\n** If the pnByte parameter is NULL, then it is assumed that the file \n** contains a single PMA, and that that PMA omits the initial length varint.\n*/\nstatic int vdbePmaReaderInit(\n  SortSubtask *pTask,             /* Task context */\n  SorterFile *pFile,              /* Sorter file to read from */\n  i64 iStart,                     /* Start offset in pFile */\n  PmaReader *pReadr,              /* PmaReader to populate */\n  i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */\n){\n  int rc;\n\n  assert( pFile->iEof>iStart );\n  assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );\n  assert( pReadr->aBuffer==0 );\n  assert( pReadr->aMap==0 );\n\n  rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);\n  if( rc==SQLITE_OK ){\n    u64 nByte = 0;                 /* Size of PMA in bytes */\n    rc = vdbePmaReadVarint(pReadr, &nByte);\n    pReadr->iEof = pReadr->iReadOff + nByte;\n    *pnByte += nByte;\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = vdbePmaReaderNext(pReadr);\n  }\n  return rc;\n}\n\n/*\n** A version of vdbeSorterCompare() that assumes that it has already been\n** determined that the first field of key1 is equal to the first field of \n** key2.\n*/\nstatic int vdbeSorterCompareTail(\n  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */\n  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */\n  const void *pKey1, int nKey1,   /* Left side of comparison */\n  const void *pKey2, int nKey2    /* Right side of comparison */\n){\n  UnpackedRecord *r2 = pTask->pUnpacked;\n  if( *pbKey2Cached==0 ){\n    sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);\n    *pbKey2Cached = 1;\n  }\n  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);\n}\n\n/*\n** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, \n** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences\n** used by the comparison. Return the result of the comparison.\n**\n** If IN/OUT parameter *pbKey2Cached is true when this function is called,\n** it is assumed that (pTask->pUnpacked) contains the unpacked version\n** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked\n** version of key2 and *pbKey2Cached set to true before returning.\n**\n** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set\n** to SQLITE_NOMEM.\n*/\nstatic int vdbeSorterCompare(\n  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */\n  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */\n  const void *pKey1, int nKey1,   /* Left side of comparison */\n  const void *pKey2, int nKey2    /* Right side of comparison */\n){\n  UnpackedRecord *r2 = pTask->pUnpacked;\n  if( !*pbKey2Cached ){\n    sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);\n    *pbKey2Cached = 1;\n  }\n  return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);\n}\n\n/*\n** A specially optimized version of vdbeSorterCompare() that assumes that\n** the first field of each key is a TEXT value and that the collation\n** sequence to compare them with is BINARY.\n*/\nstatic int vdbeSorterCompareText(\n  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */\n  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */\n  const void *pKey1, int nKey1,   /* Left side of comparison */\n  const void *pKey2, int nKey2    /* Right side of comparison */\n){\n  const u8 * const p1 = (const u8 * const)pKey1;\n  const u8 * const p2 = (const u8 * const)pKey2;\n  const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */\n  const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */\n\n  int n1;\n  int n2;\n  int res;\n\n  getVarint32NR(&p1[1], n1);\n  getVarint32NR(&p2[1], n2);\n  res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);\n  if( res==0 ){\n    res = n1 - n2;\n  }\n\n  if( res==0 ){\n    if( pTask->pSorter->pKeyInfo->nKeyField>1 ){\n      res = vdbeSorterCompareTail(\n          pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2\n      );\n    }\n  }else{\n    assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) );\n    if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){\n      res = res * -1;\n    }\n  }\n\n  return res;\n}\n\n/*\n** A specially optimized version of vdbeSorterCompare() that assumes that\n** the first field of each key is an INTEGER value.\n*/\nstatic int vdbeSorterCompareInt(\n  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */\n  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */\n  const void *pKey1, int nKey1,   /* Left side of comparison */\n  const void *pKey2, int nKey2    /* Right side of comparison */\n){\n  const u8 * const p1 = (const u8 * const)pKey1;\n  const u8 * const p2 = (const u8 * const)pKey2;\n  const int s1 = p1[1];                 /* Left hand serial type */\n  const int s2 = p2[1];                 /* Right hand serial type */\n  const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */\n  const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */\n  int res;                              /* Return value */\n\n  assert( (s1>0 && s1<7) || s1==8 || s1==9 );\n  assert( (s2>0 && s2<7) || s2==8 || s2==9 );\n\n  if( s1==s2 ){\n    /* The two values have the same sign. Compare using memcmp(). */\n    static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };\n    const u8 n = aLen[s1];\n    int i;\n    res = 0;\n    for(i=0; i<n; i++){\n      if( (res = v1[i] - v2[i])!=0 ){\n        if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){\n          res = v1[0] & 0x80 ? -1 : +1;\n        }\n        break;\n      }\n    }\n  }else if( s1>7 && s2>7 ){\n    res = s1 - s2;\n  }else{\n    if( s2>7 ){\n      res = +1;\n    }else if( s1>7 ){\n      res = -1;\n    }else{\n      res = s1 - s2;\n    }\n    assert( res!=0 );\n\n    if( res>0 ){\n      if( *v1 & 0x80 ) res = -1;\n    }else{\n      if( *v2 & 0x80 ) res = +1;\n    }\n  }\n\n  if( res==0 ){\n    if( pTask->pSorter->pKeyInfo->nKeyField>1 ){\n      res = vdbeSorterCompareTail(\n          pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2\n      );\n    }\n  }else if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){\n    assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) );\n    res = res * -1;\n  }\n\n  return res;\n}\n\n/*\n** Initialize the temporary index cursor just opened as a sorter cursor.\n**\n** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)\n** to determine the number of fields that should be compared from the\n** records being sorted. However, if the value passed as argument nField\n** is non-zero and the sorter is able to guarantee a stable sort, nField\n** is used instead. This is used when sorting records for a CREATE INDEX\n** statement. In this case, keys are always delivered to the sorter in\n** order of the primary key, which happens to be make up the final part \n** of the records being sorted. So if the sort is stable, there is never\n** any reason to compare PK fields and they can be ignored for a small\n** performance boost.\n**\n** The sorter can guarantee a stable sort when running in single-threaded\n** mode, but not in multi-threaded mode.\n**\n** SQLITE_OK is returned if successful, or an SQLite error code otherwise.\n*/\nSQLITE_PRIVATE int sqlite3VdbeSorterInit(\n  sqlite3 *db,                    /* Database connection (for malloc()) */\n  int nField,                     /* Number of key fields in each record */\n  VdbeCursor *pCsr                /* Cursor that holds the new sorter */\n){\n  int pgsz;                       /* Page size of main database */\n  int i;                          /* Used to iterate through aTask[] */\n  VdbeSorter *pSorter;            /* The new sorter */\n  KeyInfo *pKeyInfo;              /* Copy of pCsr->pKeyInfo with db==0 */\n  int szKeyInfo;                  /* Size of pCsr->pKeyInfo in bytes */\n  int sz;                         /* Size of pSorter in bytes */\n  int rc = SQLITE_OK;\n#if SQLITE_MAX_WORKER_THREADS==0\n# define nWorker 0\n#else\n  int nWorker;\n#endif\n\n  /* Initialize the upper limit on the number of worker threads */\n#if SQLITE_MAX_WORKER_THREADS>0\n  if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){\n    nWorker = 0;\n  }else{\n    nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];\n  }\n#endif\n\n  /* Do not allow the total number of threads (main thread + all workers)\n  ** to exceed the maximum merge count */\n#if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT\n  if( nWorker>=SORTER_MAX_MERGE_COUNT ){\n    nWorker = SORTER_MAX_MERGE_COUNT-1;\n  }\n#endif\n\n  assert( pCsr->pKeyInfo && pCsr->pBtx==0 );\n  assert( pCsr->eCurType==CURTYPE_SORTER );\n  szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);\n  sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);\n\n  pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);\n  pCsr->uc.pSorter = pSorter;\n  if( pSorter==0 ){\n    rc = SQLITE_NOMEM_BKPT;\n  }else{\n    pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);\n    memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);\n    pKeyInfo->db = 0;\n    if( nField && nWorker==0 ){\n      pKeyInfo->nKeyField = nField;\n    }\n    pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);\n    pSorter->nTask = nWorker + 1;\n    pSorter->iPrev = (u8)(nWorker - 1);\n    pSorter->bUseThreads = (pSorter->nTask>1);\n    pSorter->db = db;\n    for(i=0; i<pSorter->nTask; i++){\n      SortSubtask *pTask = &pSorter->aTask[i];\n      pTask->pSorter = pSorter;\n    }\n\n    if( !sqlite3TempInMemory(db) ){\n      i64 mxCache;                /* Cache size in bytes*/\n      u32 szPma = sqlite3GlobalConfig.szPma;\n      pSorter->mnPmaSize = szPma * pgsz;\n\n      mxCache = db->aDb[0].pSchema->cache_size;\n      if( mxCache<0 ){\n        /* A negative cache-size value C indicates that the cache is abs(C)\n        ** KiB in size.  */\n        mxCache = mxCache * -1024;\n      }else{\n        mxCache = mxCache * pgsz;\n      }\n      mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);\n      pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);\n\n      /* Avoid large memory allocations if the application has requested\n      ** SQLITE_CONFIG_SMALL_MALLOC. */\n      if( sqlite3GlobalConfig.bSmallMalloc==0 ){\n        assert( pSorter->iMemory==0 );\n        pSorter->nMemory = pgsz;\n        pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);\n        if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;\n      }\n    }\n\n    if( pKeyInfo->nAllField<13 \n     && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)\n     && (pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL)==0\n    ){\n      pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;\n    }\n  }\n\n  return rc;\n}\n#undef nWorker   /* Defined at the top of this function */\n\n/*\n** Free the list of sorted records starting at pRecord.\n*/\nstatic void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){\n  SorterRecord *p;\n  SorterRecord *pNext;\n  for(p=pRecord; p; p=pNext){\n    pNext = p->u.pNext;\n    sqlite3DbFree(db, p);\n  }\n}\n\n/*\n** Free all resources owned by the object indicated by argument pTask. All \n** fields of *pTask are zeroed before returning.\n*/\nstatic void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){\n  sqlite3DbFree(db, pTask->pUnpacked);\n#if SQLITE_MAX_WORKER_THREADS>0\n  /* pTask->list.aMemory can only be non-zero if it was handed memory\n  ** from the main thread.  That only occurs SQLITE_MAX_WORKER_THREADS>0 */\n  if( pTask->list.aMemory ){\n    sqlite3_free(pTask->list.aMemory);\n  }else\n#endif\n  {\n    assert( pTask->list.aMemory==0 );\n    vdbeSorterRecordFree(0, pTask->list.pList);\n  }\n  if( pTask->file.pFd ){\n    sqlite3OsCloseFree(pTask->file.pFd);\n  }\n  if( pTask->file2.pFd ){\n    sqlite3OsCloseFree(pTask->file2.pFd);\n  }\n  memset(pTask, 0, sizeof(SortSubtask));\n}\n\n#ifdef SQLITE_DEBUG_SORTER_THREADS\nstatic void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){\n  i64 t;\n  int iTask = (pTask - pTask->pSorter->aTask);\n  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);\n  fprintf(stderr, \"%lld:%d %s\\n\", t, iTask, zEvent);\n}\nstatic void vdbeSorterRewindDebug(const char *zEvent){\n  i64 t;\n  sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);\n  fprintf(stderr, \"%lld:X %s\\n\", t, zEvent);\n}\nstatic void vdbeSorterPopulateDebug(\n  SortSubtask *pTask,\n  const char *zEvent\n){\n  i64 t;\n  int iTask = (pTask - pTask->pSorter->aTask);\n  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);\n  fprintf(stderr, \"%lld:bg%d %s\\n\", t, iTask, zEvent);\n}\nstatic void vdbeSorterBlockDebug(\n  SortSubtask *pTask,\n  int bBlocked,\n  const char *zEvent\n){\n  if( bBlocked ){\n    i64 t;\n    sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);\n    fprintf(stderr, \"%lld:main %s\\n\", t, zEvent);\n  }\n}\n#else\n# define vdbeSorterWorkDebug(x,y)\n# define vdbeSorterRewindDebug(y)\n# define vdbeSorterPopulateDebug(x,y)\n# define vdbeSorterBlockDebug(x,y,z)\n#endif\n\n#if SQLITE_MAX_WORKER_THREADS>0\n/*\n** Join thread pTask->thread.\n*/\nstatic int vdbeSorterJoinThread(SortSubtask *pTask){\n  int rc = SQLITE_OK;\n  if( pTask->pThread ){\n#ifdef SQLITE_DEBUG_SORTER_THREADS\n    int bDone = pTask->bDone;\n#endif\n    void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);\n    vdbeSorterBlockDebug(pTask, !bDone, \"enter\");\n    (void)sqlite3ThreadJoin(pTask->pThread, &pRet);\n    vdbeSorterBlockDebug(pTask, !bDone, \"exit\");\n    rc = SQLITE_PTR_TO_INT(pRet);\n    assert( pTask->bDone==1 );\n    pTask->bDone = 0;\n    pTask->pThread = 0;\n  }\n  return rc;\n}\n\n/*\n** Launch a background thread to run xTask(pIn).\n*/\nstatic int vdbeSorterCreateThread(\n  SortSubtask *pTask,             /* Thread will use this task object */\n  void *(*xTask)(void*),          /* Routine to run in a separate thread */\n  void *pIn                       /* Argument passed into xTask() */\n){\n  assert( pTask->pThread==0 && pTask->bDone==0 );\n  return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);\n}\n\n/*\n** Join all outstanding threads launched by SorterWrite() to create \n** level-0 PMAs.\n*/\nstatic int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){\n  int rc = rcin;\n  int i;\n\n  /* This function is always called by the main user thread.\n  **\n  ** If this function is being called after SorterRewind() has been called, \n  ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread\n  ** is currently attempt to join one of the other threads. To avoid a race\n  ** condition where this thread also attempts to join the same object, join \n  ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */\n  for(i=pSorter->nTask-1; i>=0; i--){\n    SortSubtask *pTask = &pSorter->aTask[i];\n    int rc2 = vdbeSorterJoinThread(pTask);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n  return rc;\n}\n#else\n# define vdbeSorterJoinAll(x,rcin) (rcin)\n# define vdbeSorterJoinThread(pTask) SQLITE_OK\n#endif\n\n/*\n** Allocate a new MergeEngine object capable of handling up to\n** nReader PmaReader inputs.\n**\n** nReader is automatically rounded up to the next power of two.\n** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.\n*/\nstatic MergeEngine *vdbeMergeEngineNew(int nReader){\n  int N = 2;                      /* Smallest power of two >= nReader */\n  int nByte;                      /* Total bytes of space to allocate */\n  MergeEngine *pNew;              /* Pointer to allocated object to return */\n\n  assert( nReader<=SORTER_MAX_MERGE_COUNT );\n\n  while( N<nReader ) N += N;\n  nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));\n\n  pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);\n  if( pNew ){\n    pNew->nTree = N;\n    pNew->pTask = 0;\n    pNew->aReadr = (PmaReader*)&pNew[1];\n    pNew->aTree = (int*)&pNew->aReadr[N];\n  }\n  return pNew;\n}\n\n/*\n** Free the MergeEngine object passed as the only argument.\n*/\nstatic void vdbeMergeEngineFree(MergeEngine *pMerger){\n  int i;\n  if( pMerger ){\n    for(i=0; i<pMerger->nTree; i++){\n      vdbePmaReaderClear(&pMerger->aReadr[i]);\n    }\n  }\n  sqlite3_free(pMerger);\n}\n\n/*\n** Free all resources associated with the IncrMerger object indicated by\n** the first argument.\n*/\nstatic void vdbeIncrFree(IncrMerger *pIncr){\n  if( pIncr ){\n#if SQLITE_MAX_WORKER_THREADS>0\n    if( pIncr->bUseThread ){\n      vdbeSorterJoinThread(pIncr->pTask);\n      if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);\n      if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);\n    }\n#endif\n    vdbeMergeEngineFree(pIncr->pMerger);\n    sqlite3_free(pIncr);\n  }\n}\n\n/*\n** Reset a sorting cursor back to its original empty state.\n*/\nSQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){\n  int i;\n  (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);\n  assert( pSorter->bUseThreads || pSorter->pReader==0 );\n#if SQLITE_MAX_WORKER_THREADS>0\n  if( pSorter->pReader ){\n    vdbePmaReaderClear(pSorter->pReader);\n    sqlite3DbFree(db, pSorter->pReader);\n    pSorter->pReader = 0;\n  }\n#endif\n  vdbeMergeEngineFree(pSorter->pMerger);\n  pSorter->pMerger = 0;\n  for(i=0; i<pSorter->nTask; i++){\n    SortSubtask *pTask = &pSorter->aTask[i];\n    vdbeSortSubtaskCleanup(db, pTask);\n    pTask->pSorter = pSorter;\n  }\n  if( pSorter->list.aMemory==0 ){\n    vdbeSorterRecordFree(0, pSorter->list.pList);\n  }\n  pSorter->list.pList = 0;\n  pSorter->list.szPMA = 0;\n  pSorter->bUsePMA = 0;\n  pSorter->iMemory = 0;\n  pSorter->mxKeysize = 0;\n  sqlite3DbFree(db, pSorter->pUnpacked);\n  pSorter->pUnpacked = 0;\n}\n\n/*\n** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.\n*/\nSQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){\n  VdbeSorter *pSorter;\n  assert( pCsr->eCurType==CURTYPE_SORTER );\n  pSorter = pCsr->uc.pSorter;\n  if( pSorter ){\n    sqlite3VdbeSorterReset(db, pSorter);\n    sqlite3_free(pSorter->list.aMemory);\n    sqlite3DbFree(db, pSorter);\n    pCsr->uc.pSorter = 0;\n  }\n}\n\n#if SQLITE_MAX_MMAP_SIZE>0\n/*\n** The first argument is a file-handle open on a temporary file. The file\n** is guaranteed to be nByte bytes or smaller in size. This function\n** attempts to extend the file to nByte bytes in size and to ensure that\n** the VFS has memory mapped it.\n**\n** Whether or not the file does end up memory mapped of course depends on\n** the specific VFS implementation.\n*/\nstatic void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){\n  if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){\n    void *p = 0;\n    int chunksize = 4*1024;\n    sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);\n    sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);\n    sqlite3OsFetch(pFd, 0, (int)nByte, &p);\n    sqlite3OsUnfetch(pFd, 0, p);\n  }\n}\n#else\n# define vdbeSorterExtendFile(x,y,z)\n#endif\n\n/*\n** Allocate space for a file-handle and open a temporary file. If successful,\n** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.\n** Otherwise, set *ppFd to 0 and return an SQLite error code.\n*/\nstatic int vdbeSorterOpenTempFile(\n  sqlite3 *db,                    /* Database handle doing sort */\n  i64 nExtend,                    /* Attempt to extend file to this size */\n  sqlite3_file **ppFd\n){\n  int rc;\n  if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;\n  rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,\n      SQLITE_OPEN_TEMP_JOURNAL |\n      SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |\n      SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &rc\n  );\n  if( rc==SQLITE_OK ){\n    i64 max = SQLITE_MAX_MMAP_SIZE;\n    sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);\n    if( nExtend>0 ){\n      vdbeSorterExtendFile(db, *ppFd, nExtend);\n    }\n  }\n  return rc;\n}\n\n/*\n** If it has not already been allocated, allocate the UnpackedRecord \n** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or \n** if no allocation was required), or SQLITE_NOMEM otherwise.\n*/\nstatic int vdbeSortAllocUnpacked(SortSubtask *pTask){\n  if( pTask->pUnpacked==0 ){\n    pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);\n    if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;\n    pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;\n    pTask->pUnpacked->errCode = 0;\n  }\n  return SQLITE_OK;\n}\n\n\n/*\n** Merge the two sorted lists p1 and p2 into a single list.\n*/\nstatic SorterRecord *vdbeSorterMerge(\n  SortSubtask *pTask,             /* Calling thread context */\n  SorterRecord *p1,               /* First list to merge */\n  SorterRecord *p2                /* Second list to merge */\n){\n  SorterRecord *pFinal = 0;\n  SorterRecord **pp = &pFinal;\n  int bCached = 0;\n\n  assert( p1!=0 && p2!=0 );\n  for(;;){\n    int res;\n    res = pTask->xCompare(\n        pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal\n    );\n\n    if( res<=0 ){\n      *pp = p1;\n      pp = &p1->u.pNext;\n      p1 = p1->u.pNext;\n      if( p1==0 ){\n        *pp = p2;\n        break;\n      }\n    }else{\n      *pp = p2;\n      pp = &p2->u.pNext;\n      p2 = p2->u.pNext;\n      bCached = 0;\n      if( p2==0 ){\n        *pp = p1;\n        break;\n      }\n    }\n  }\n  return pFinal;\n}\n\n/*\n** Return the SorterCompare function to compare values collected by the\n** sorter object passed as the only argument.\n*/\nstatic SorterCompare vdbeSorterGetCompare(VdbeSorter *p){\n  if( p->typeMask==SORTER_TYPE_INTEGER ){\n    return vdbeSorterCompareInt;\n  }else if( p->typeMask==SORTER_TYPE_TEXT ){\n    return vdbeSorterCompareText; \n  }\n  return vdbeSorterCompare;\n}\n\n/*\n** Sort the linked list of records headed at pTask->pList. Return \n** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if \n** an error occurs.\n*/\nstatic int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){\n  int i;\n  SorterRecord *p;\n  int rc;\n  SorterRecord *aSlot[64];\n\n  rc = vdbeSortAllocUnpacked(pTask);\n  if( rc!=SQLITE_OK ) return rc;\n\n  p = pList->pList;\n  pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);\n  memset(aSlot, 0, sizeof(aSlot));\n\n  while( p ){\n    SorterRecord *pNext;\n    if( pList->aMemory ){\n      if( (u8*)p==pList->aMemory ){\n        pNext = 0;\n      }else{\n        assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );\n        pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];\n      }\n    }else{\n      pNext = p->u.pNext;\n    }\n\n    p->u.pNext = 0;\n    for(i=0; aSlot[i]; i++){\n      p = vdbeSorterMerge(pTask, p, aSlot[i]);\n      aSlot[i] = 0;\n    }\n    aSlot[i] = p;\n    p = pNext;\n  }\n\n  p = 0;\n  for(i=0; i<ArraySize(aSlot); i++){\n    if( aSlot[i]==0 ) continue;\n    p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];\n  }\n  pList->pList = p;\n\n  assert( pTask->pUnpacked->errCode==SQLITE_OK \n       || pTask->pUnpacked->errCode==SQLITE_NOMEM \n  );\n  return pTask->pUnpacked->errCode;\n}\n\n/*\n** Initialize a PMA-writer object.\n*/\nstatic void vdbePmaWriterInit(\n  sqlite3_file *pFd,              /* File handle to write to */\n  PmaWriter *p,                   /* Object to populate */\n  int nBuf,                       /* Buffer size */\n  i64 iStart                      /* Offset of pFd to begin writing at */\n){\n  memset(p, 0, sizeof(PmaWriter));\n  p->aBuffer = (u8*)sqlite3Malloc(nBuf);\n  if( !p->aBuffer ){\n    p->eFWErr = SQLITE_NOMEM_BKPT;\n  }else{\n    p->iBufEnd = p->iBufStart = (iStart % nBuf);\n    p->iWriteOff = iStart - p->iBufStart;\n    p->nBuffer = nBuf;\n    p->pFd = pFd;\n  }\n}\n\n/*\n** Write nData bytes of data to the PMA. Return SQLITE_OK\n** if successful, or an SQLite error code if an error occurs.\n*/\nstatic void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){\n  int nRem = nData;\n  while( nRem>0 && p->eFWErr==0 ){\n    int nCopy = nRem;\n    if( nCopy>(p->nBuffer - p->iBufEnd) ){\n      nCopy = p->nBuffer - p->iBufEnd;\n    }\n\n    memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);\n    p->iBufEnd += nCopy;\n    if( p->iBufEnd==p->nBuffer ){\n      p->eFWErr = sqlite3OsWrite(p->pFd, \n          &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, \n          p->iWriteOff + p->iBufStart\n      );\n      p->iBufStart = p->iBufEnd = 0;\n      p->iWriteOff += p->nBuffer;\n    }\n    assert( p->iBufEnd<p->nBuffer );\n\n    nRem -= nCopy;\n  }\n}\n\n/*\n** Flush any buffered data to disk and clean up the PMA-writer object.\n** The results of using the PMA-writer after this call are undefined.\n** Return SQLITE_OK if flushing the buffered data succeeds or is not \n** required. Otherwise, return an SQLite error code.\n**\n** Before returning, set *piEof to the offset immediately following the\n** last byte written to the file.\n*/\nstatic int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){\n  int rc;\n  if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){\n    p->eFWErr = sqlite3OsWrite(p->pFd, \n        &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, \n        p->iWriteOff + p->iBufStart\n    );\n  }\n  *piEof = (p->iWriteOff + p->iBufEnd);\n  sqlite3_free(p->aBuffer);\n  rc = p->eFWErr;\n  memset(p, 0, sizeof(PmaWriter));\n  return rc;\n}\n\n/*\n** Write value iVal encoded as a varint to the PMA. Return \n** SQLITE_OK if successful, or an SQLite error code if an error occurs.\n*/\nstatic void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){\n  int nByte; \n  u8 aByte[10];\n  nByte = sqlite3PutVarint(aByte, iVal);\n  vdbePmaWriteBlob(p, aByte, nByte);\n}\n\n/*\n** Write the current contents of in-memory linked-list pList to a level-0\n** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if \n** successful, or an SQLite error code otherwise.\n**\n** The format of a PMA is:\n**\n**     * A varint. This varint contains the total number of bytes of content\n**       in the PMA (not including the varint itself).\n**\n**     * One or more records packed end-to-end in order of ascending keys. \n**       Each record consists of a varint followed by a blob of data (the \n**       key). The varint is the number of bytes in the blob of data.\n*/\nstatic int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){\n  sqlite3 *db = pTask->pSorter->db;\n  int rc = SQLITE_OK;             /* Return code */\n  PmaWriter writer;               /* Object used to write to the file */\n\n#ifdef SQLITE_DEBUG\n  /* Set iSz to the expected size of file pTask->file after writing the PMA. \n  ** This is used by an assert() statement at the end of this function.  */\n  i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;\n#endif\n\n  vdbeSorterWorkDebug(pTask, \"enter\");\n  memset(&writer, 0, sizeof(PmaWriter));\n  assert( pList->szPMA>0 );\n\n  /* If the first temporary PMA file has not been opened, open it now. */\n  if( pTask->file.pFd==0 ){\n    rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);\n    assert( rc!=SQLITE_OK || pTask->file.pFd );\n    assert( pTask->file.iEof==0 );\n    assert( pTask->nPMA==0 );\n  }\n\n  /* Try to get the file to memory map */\n  if( rc==SQLITE_OK ){\n    vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);\n  }\n\n  /* Sort the list */\n  if( rc==SQLITE_OK ){\n    rc = vdbeSorterSort(pTask, pList);\n  }\n\n  if( rc==SQLITE_OK ){\n    SorterRecord *p;\n    SorterRecord *pNext = 0;\n\n    vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,\n                      pTask->file.iEof);\n    pTask->nPMA++;\n    vdbePmaWriteVarint(&writer, pList->szPMA);\n    for(p=pList->pList; p; p=pNext){\n      pNext = p->u.pNext;\n      vdbePmaWriteVarint(&writer, p->nVal);\n      vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);\n      if( pList->aMemory==0 ) sqlite3_free(p);\n    }\n    pList->pList = p;\n    rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);\n  }\n\n  vdbeSorterWorkDebug(pTask, \"exit\");\n  assert( rc!=SQLITE_OK || pList->pList==0 );\n  assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );\n  return rc;\n}\n\n/*\n** Advance the MergeEngine to its next entry.\n** Set *pbEof to true there is no next entry because\n** the MergeEngine has reached the end of all its inputs.\n**\n** Return SQLITE_OK if successful or an error code if an error occurs.\n*/\nstatic int vdbeMergeEngineStep(\n  MergeEngine *pMerger,      /* The merge engine to advance to the next row */\n  int *pbEof                 /* Set TRUE at EOF.  Set false for more content */\n){\n  int rc;\n  int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */\n  SortSubtask *pTask = pMerger->pTask;\n\n  /* Advance the current PmaReader */\n  rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);\n\n  /* Update contents of aTree[] */\n  if( rc==SQLITE_OK ){\n    int i;                      /* Index of aTree[] to recalculate */\n    PmaReader *pReadr1;         /* First PmaReader to compare */\n    PmaReader *pReadr2;         /* Second PmaReader to compare */\n    int bCached = 0;\n\n    /* Find the first two PmaReaders to compare. The one that was just\n    ** advanced (iPrev) and the one next to it in the array.  */\n    pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];\n    pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];\n\n    for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){\n      /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */\n      int iRes;\n      if( pReadr1->pFd==0 ){\n        iRes = +1;\n      }else if( pReadr2->pFd==0 ){\n        iRes = -1;\n      }else{\n        iRes = pTask->xCompare(pTask, &bCached,\n            pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey\n        );\n      }\n\n      /* If pReadr1 contained the smaller value, set aTree[i] to its index.\n      ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this\n      ** case there is no cache of pReadr2 in pTask->pUnpacked, so set\n      ** pKey2 to point to the record belonging to pReadr2.\n      **\n      ** Alternatively, if pReadr2 contains the smaller of the two values,\n      ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()\n      ** was actually called above, then pTask->pUnpacked now contains\n      ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent\n      ** vdbeSorterCompare() from decoding pReadr2 again.\n      **\n      ** If the two values were equal, then the value from the oldest\n      ** PMA should be considered smaller. The VdbeSorter.aReadr[] array\n      ** is sorted from oldest to newest, so pReadr1 contains older values\n      ** than pReadr2 iff (pReadr1<pReadr2).  */\n      if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){\n        pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);\n        pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];\n        bCached = 0;\n      }else{\n        if( pReadr1->pFd ) bCached = 0;\n        pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);\n        pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];\n      }\n    }\n    *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);\n  }\n\n  return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);\n}\n\n#if SQLITE_MAX_WORKER_THREADS>0\n/*\n** The main routine for background threads that write level-0 PMAs.\n*/\nstatic void *vdbeSorterFlushThread(void *pCtx){\n  SortSubtask *pTask = (SortSubtask*)pCtx;\n  int rc;                         /* Return code */\n  assert( pTask->bDone==0 );\n  rc = vdbeSorterListToPMA(pTask, &pTask->list);\n  pTask->bDone = 1;\n  return SQLITE_INT_TO_PTR(rc);\n}\n#endif /* SQLITE_MAX_WORKER_THREADS>0 */\n\n/*\n** Flush the current contents of VdbeSorter.list to a new PMA, possibly\n** using a background thread.\n*/\nstatic int vdbeSorterFlushPMA(VdbeSorter *pSorter){\n#if SQLITE_MAX_WORKER_THREADS==0\n  pSorter->bUsePMA = 1;\n  return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);\n#else\n  int rc = SQLITE_OK;\n  int i;\n  SortSubtask *pTask = 0;    /* Thread context used to create new PMA */\n  int nWorker = (pSorter->nTask-1);\n\n  /* Set the flag to indicate that at least one PMA has been written. \n  ** Or will be, anyhow.  */\n  pSorter->bUsePMA = 1;\n\n  /* Select a sub-task to sort and flush the current list of in-memory\n  ** records to disk. If the sorter is running in multi-threaded mode,\n  ** round-robin between the first (pSorter->nTask-1) tasks. Except, if\n  ** the background thread from a sub-tasks previous turn is still running,\n  ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,\n  ** fall back to using the final sub-task. The first (pSorter->nTask-1)\n  ** sub-tasks are prefered as they use background threads - the final \n  ** sub-task uses the main thread. */\n  for(i=0; i<nWorker; i++){\n    int iTest = (pSorter->iPrev + i + 1) % nWorker;\n    pTask = &pSorter->aTask[iTest];\n    if( pTask->bDone ){\n      rc = vdbeSorterJoinThread(pTask);\n    }\n    if( rc!=SQLITE_OK || pTask->pThread==0 ) break;\n  }\n\n  if( rc==SQLITE_OK ){\n    if( i==nWorker ){\n      /* Use the foreground thread for this operation */\n      rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);\n    }else{\n      /* Launch a background thread for this operation */\n      u8 *aMem;\n      void *pCtx;\n\n      assert( pTask!=0 );\n      assert( pTask->pThread==0 && pTask->bDone==0 );\n      assert( pTask->list.pList==0 );\n      assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );\n\n      aMem = pTask->list.aMemory;\n      pCtx = (void*)pTask;\n      pSorter->iPrev = (u8)(pTask - pSorter->aTask);\n      pTask->list = pSorter->list;\n      pSorter->list.pList = 0;\n      pSorter->list.szPMA = 0;\n      if( aMem ){\n        pSorter->list.aMemory = aMem;\n        pSorter->nMemory = sqlite3MallocSize(aMem);\n      }else if( pSorter->list.aMemory ){\n        pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);\n        if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;\n      }\n\n      rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);\n    }\n  }\n\n  return rc;\n#endif /* SQLITE_MAX_WORKER_THREADS!=0 */\n}\n\n/*\n** Add a record to the sorter.\n*/\nSQLITE_PRIVATE int sqlite3VdbeSorterWrite(\n  const VdbeCursor *pCsr,         /* Sorter cursor */\n  Mem *pVal                       /* Memory cell containing record */\n){\n  VdbeSorter *pSorter;\n  int rc = SQLITE_OK;             /* Return Code */\n  SorterRecord *pNew;             /* New list element */\n  int bFlush;                     /* True to flush contents of memory to PMA */\n  int nReq;                       /* Bytes of memory required */\n  int nPMA;                       /* Bytes of PMA space required */\n  int t;                          /* serial type of first record field */\n\n  assert( pCsr->eCurType==CURTYPE_SORTER );\n  pSorter = pCsr->uc.pSorter;\n  getVarint32NR((const u8*)&pVal->z[1], t);\n  if( t>0 && t<10 && t!=7 ){\n    pSorter->typeMask &= SORTER_TYPE_INTEGER;\n  }else if( t>10 && (t & 0x01) ){\n    pSorter->typeMask &= SORTER_TYPE_TEXT;\n  }else{\n    pSorter->typeMask = 0;\n  }\n\n  assert( pSorter );\n\n  /* Figure out whether or not the current contents of memory should be\n  ** flushed to a PMA before continuing. If so, do so.\n  **\n  ** If using the single large allocation mode (pSorter->aMemory!=0), then\n  ** flush the contents of memory to a new PMA if (a) at least one value is\n  ** already in memory and (b) the new value will not fit in memory.\n  ** \n  ** Or, if using separate allocations for each record, flush the contents\n  ** of memory to a PMA if either of the following are true:\n  **\n  **   * The total memory allocated for the in-memory list is greater \n  **     than (page-size * cache-size), or\n  **\n  **   * The total memory allocated for the in-memory list is greater \n  **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.\n  */\n  nReq = pVal->n + sizeof(SorterRecord);\n  nPMA = pVal->n + sqlite3VarintLen(pVal->n);\n  if( pSorter->mxPmaSize ){\n    if( pSorter->list.aMemory ){\n      bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;\n    }else{\n      bFlush = (\n          (pSorter->list.szPMA > pSorter->mxPmaSize)\n       || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())\n      );\n    }\n    if( bFlush ){\n      rc = vdbeSorterFlushPMA(pSorter);\n      pSorter->list.szPMA = 0;\n      pSorter->iMemory = 0;\n      assert( rc!=SQLITE_OK || pSorter->list.pList==0 );\n    }\n  }\n\n  pSorter->list.szPMA += nPMA;\n  if( nPMA>pSorter->mxKeysize ){\n    pSorter->mxKeysize = nPMA;\n  }\n\n  if( pSorter->list.aMemory ){\n    int nMin = pSorter->iMemory + nReq;\n\n    if( nMin>pSorter->nMemory ){\n      u8 *aNew;\n      sqlite3_int64 nNew = 2 * (sqlite3_int64)pSorter->nMemory;\n      int iListOff = -1;\n      if( pSorter->list.pList ){\n        iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;\n      }\n      while( nNew < nMin ) nNew = nNew*2;\n      if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;\n      if( nNew < nMin ) nNew = nMin;\n      aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);\n      if( !aNew ) return SQLITE_NOMEM_BKPT;\n      if( iListOff>=0 ){\n        pSorter->list.pList = (SorterRecord*)&aNew[iListOff];\n      }\n      pSorter->list.aMemory = aNew;\n      pSorter->nMemory = nNew;\n    }\n\n    pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];\n    pSorter->iMemory += ROUND8(nReq);\n    if( pSorter->list.pList ){\n      pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);\n    }\n  }else{\n    pNew = (SorterRecord *)sqlite3Malloc(nReq);\n    if( pNew==0 ){\n      return SQLITE_NOMEM_BKPT;\n    }\n    pNew->u.pNext = pSorter->list.pList;\n  }\n\n  memcpy(SRVAL(pNew), pVal->z, pVal->n);\n  pNew->nVal = pVal->n;\n  pSorter->list.pList = pNew;\n\n  return rc;\n}\n\n/*\n** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format\n** of the data stored in aFile[1] is the same as that used by regular PMAs,\n** except that the number-of-bytes varint is omitted from the start.\n*/\nstatic int vdbeIncrPopulate(IncrMerger *pIncr){\n  int rc = SQLITE_OK;\n  int rc2;\n  i64 iStart = pIncr->iStartOff;\n  SorterFile *pOut = &pIncr->aFile[1];\n  SortSubtask *pTask = pIncr->pTask;\n  MergeEngine *pMerger = pIncr->pMerger;\n  PmaWriter writer;\n  assert( pIncr->bEof==0 );\n\n  vdbeSorterPopulateDebug(pTask, \"enter\");\n\n  vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);\n  while( rc==SQLITE_OK ){\n    int dummy;\n    PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];\n    int nKey = pReader->nKey;\n    i64 iEof = writer.iWriteOff + writer.iBufEnd;\n\n    /* Check if the output file is full or if the input has been exhausted.\n    ** In either case exit the loop. */\n    if( pReader->pFd==0 ) break;\n    if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;\n\n    /* Write the next key to the output. */\n    vdbePmaWriteVarint(&writer, nKey);\n    vdbePmaWriteBlob(&writer, pReader->aKey, nKey);\n    assert( pIncr->pMerger->pTask==pTask );\n    rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);\n  }\n\n  rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);\n  if( rc==SQLITE_OK ) rc = rc2;\n  vdbeSorterPopulateDebug(pTask, \"exit\");\n  return rc;\n}\n\n#if SQLITE_MAX_WORKER_THREADS>0\n/*\n** The main routine for background threads that populate aFile[1] of\n** multi-threaded IncrMerger objects.\n*/\nstatic void *vdbeIncrPopulateThread(void *pCtx){\n  IncrMerger *pIncr = (IncrMerger*)pCtx;\n  void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );\n  pIncr->pTask->bDone = 1;\n  return pRet;\n}\n\n/*\n** Launch a background thread to populate aFile[1] of pIncr.\n*/\nstatic int vdbeIncrBgPopulate(IncrMerger *pIncr){\n  void *p = (void*)pIncr;\n  assert( pIncr->bUseThread );\n  return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);\n}\n#endif\n\n/*\n** This function is called when the PmaReader corresponding to pIncr has\n** finished reading the contents of aFile[0]. Its purpose is to \"refill\"\n** aFile[0] such that the PmaReader should start rereading it from the\n** beginning.\n**\n** For single-threaded objects, this is accomplished by literally reading \n** keys from pIncr->pMerger and repopulating aFile[0]. \n**\n** For multi-threaded objects, all that is required is to wait until the \n** background thread is finished (if it is not already) and then swap \n** aFile[0] and aFile[1] in place. If the contents of pMerger have not\n** been exhausted, this function also launches a new background thread\n** to populate the new aFile[1].\n**\n** SQLITE_OK is returned on success, or an SQLite error code otherwise.\n*/\nstatic int vdbeIncrSwap(IncrMerger *pIncr){\n  int rc = SQLITE_OK;\n\n#if SQLITE_MAX_WORKER_THREADS>0\n  if( pIncr->bUseThread ){\n    rc = vdbeSorterJoinThread(pIncr->pTask);\n\n    if( rc==SQLITE_OK ){\n      SorterFile f0 = pIncr->aFile[0];\n      pIncr->aFile[0] = pIncr->aFile[1];\n      pIncr->aFile[1] = f0;\n    }\n\n    if( rc==SQLITE_OK ){\n      if( pIncr->aFile[0].iEof==pIncr->iStartOff ){\n        pIncr->bEof = 1;\n      }else{\n        rc = vdbeIncrBgPopulate(pIncr);\n      }\n    }\n  }else\n#endif\n  {\n    rc = vdbeIncrPopulate(pIncr);\n    pIncr->aFile[0] = pIncr->aFile[1];\n    if( pIncr->aFile[0].iEof==pIncr->iStartOff ){\n      pIncr->bEof = 1;\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Allocate and return a new IncrMerger object to read data from pMerger.\n**\n** If an OOM condition is encountered, return NULL. In this case free the\n** pMerger argument before returning.\n*/\nstatic int vdbeIncrMergerNew(\n  SortSubtask *pTask,     /* The thread that will be using the new IncrMerger */\n  MergeEngine *pMerger,   /* The MergeEngine that the IncrMerger will control */\n  IncrMerger **ppOut      /* Write the new IncrMerger here */\n){\n  int rc = SQLITE_OK;\n  IncrMerger *pIncr = *ppOut = (IncrMerger*)\n       (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));\n  if( pIncr ){\n    pIncr->pMerger = pMerger;\n    pIncr->pTask = pTask;\n    pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);\n    pTask->file2.iEof += pIncr->mxSz;\n  }else{\n    vdbeMergeEngineFree(pMerger);\n    rc = SQLITE_NOMEM_BKPT;\n  }\n  return rc;\n}\n\n#if SQLITE_MAX_WORKER_THREADS>0\n/*\n** Set the \"use-threads\" flag on object pIncr.\n*/\nstatic void vdbeIncrMergerSetThreads(IncrMerger *pIncr){\n  pIncr->bUseThread = 1;\n  pIncr->pTask->file2.iEof -= pIncr->mxSz;\n}\n#endif /* SQLITE_MAX_WORKER_THREADS>0 */\n\n\n\n/*\n** Recompute pMerger->aTree[iOut] by comparing the next keys on the\n** two PmaReaders that feed that entry.  Neither of the PmaReaders\n** are advanced.  This routine merely does the comparison.\n*/\nstatic void vdbeMergeEngineCompare(\n  MergeEngine *pMerger,  /* Merge engine containing PmaReaders to compare */\n  int iOut               /* Store the result in pMerger->aTree[iOut] */\n){\n  int i1;\n  int i2;\n  int iRes;\n  PmaReader *p1;\n  PmaReader *p2;\n\n  assert( iOut<pMerger->nTree && iOut>0 );\n\n  if( iOut>=(pMerger->nTree/2) ){\n    i1 = (iOut - pMerger->nTree/2) * 2;\n    i2 = i1 + 1;\n  }else{\n    i1 = pMerger->aTree[iOut*2];\n    i2 = pMerger->aTree[iOut*2+1];\n  }\n\n  p1 = &pMerger->aReadr[i1];\n  p2 = &pMerger->aReadr[i2];\n\n  if( p1->pFd==0 ){\n    iRes = i2;\n  }else if( p2->pFd==0 ){\n    iRes = i1;\n  }else{\n    SortSubtask *pTask = pMerger->pTask;\n    int bCached = 0;\n    int res;\n    assert( pTask->pUnpacked!=0 );  /* from vdbeSortSubtaskMain() */\n    res = pTask->xCompare(\n        pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey\n    );\n    if( res<=0 ){\n      iRes = i1;\n    }else{\n      iRes = i2;\n    }\n  }\n\n  pMerger->aTree[iOut] = iRes;\n}\n\n/*\n** Allowed values for the eMode parameter to vdbeMergeEngineInit()\n** and vdbePmaReaderIncrMergeInit().\n**\n** Only INCRINIT_NORMAL is valid in single-threaded builds (when\n** SQLITE_MAX_WORKER_THREADS==0).  The other values are only used\n** when there exists one or more separate worker threads.\n*/\n#define INCRINIT_NORMAL 0\n#define INCRINIT_TASK   1\n#define INCRINIT_ROOT   2\n\n/* \n** Forward reference required as the vdbeIncrMergeInit() and\n** vdbePmaReaderIncrInit() routines are called mutually recursively when\n** building a merge tree.\n*/\nstatic int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);\n\n/*\n** Initialize the MergeEngine object passed as the second argument. Once this\n** function returns, the first key of merged data may be read from the \n** MergeEngine object in the usual fashion.\n**\n** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge\n** objects attached to the PmaReader objects that the merger reads from have\n** already been populated, but that they have not yet populated aFile[0] and\n** set the PmaReader objects up to read from it. In this case all that is\n** required is to call vdbePmaReaderNext() on each PmaReader to point it at\n** its first key.\n**\n** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use \n** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data \n** to pMerger.\n**\n** SQLITE_OK is returned if successful, or an SQLite error code otherwise.\n*/\nstatic int vdbeMergeEngineInit(\n  SortSubtask *pTask,             /* Thread that will run pMerger */\n  MergeEngine *pMerger,           /* MergeEngine to initialize */\n  int eMode                       /* One of the INCRINIT_XXX constants */\n){\n  int rc = SQLITE_OK;             /* Return code */\n  int i;                          /* For looping over PmaReader objects */\n  int nTree;                      /* Number of subtrees to merge */\n\n  /* Failure to allocate the merge would have been detected prior to\n  ** invoking this routine */\n  assert( pMerger!=0 );\n\n  /* eMode is always INCRINIT_NORMAL in single-threaded mode */\n  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );\n\n  /* Verify that the MergeEngine is assigned to a single thread */\n  assert( pMerger->pTask==0 );\n  pMerger->pTask = pTask;\n\n  nTree = pMerger->nTree;\n  for(i=0; i<nTree; i++){\n    if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){\n      /* PmaReaders should be normally initialized in order, as if they are\n      ** reading from the same temp file this makes for more linear file IO.\n      ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is\n      ** in use it will block the vdbePmaReaderNext() call while it uses\n      ** the main thread to fill its buffer. So calling PmaReaderNext()\n      ** on this PmaReader before any of the multi-threaded PmaReaders takes\n      ** better advantage of multi-processor hardware. */\n      rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);\n    }else{\n      rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);\n    }\n    if( rc!=SQLITE_OK ) return rc;\n  }\n\n  for(i=pMerger->nTree-1; i>0; i--){\n    vdbeMergeEngineCompare(pMerger, i);\n  }\n  return pTask->pUnpacked->errCode;\n}\n\n/*\n** The PmaReader passed as the first argument is guaranteed to be an\n** incremental-reader (pReadr->pIncr!=0). This function serves to open\n** and/or initialize the temp file related fields of the IncrMerge\n** object at (pReadr->pIncr).\n**\n** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders\n** in the sub-tree headed by pReadr are also initialized. Data is then \n** loaded into the buffers belonging to pReadr and it is set to point to \n** the first key in its range.\n**\n** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed\n** to be a multi-threaded PmaReader and this function is being called in a\n** background thread. In this case all PmaReaders in the sub-tree are \n** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to\n** pReadr is populated. However, pReadr itself is not set up to point\n** to its first key. A call to vdbePmaReaderNext() is still required to do\n** that. \n**\n** The reason this function does not call vdbePmaReaderNext() immediately \n** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has\n** to block on thread (pTask->thread) before accessing aFile[1]. But, since\n** this entire function is being run by thread (pTask->thread), that will\n** lead to the current background thread attempting to join itself.\n**\n** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed\n** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all\n** child-trees have already been initialized using IncrInit(INCRINIT_TASK).\n** In this case vdbePmaReaderNext() is called on all child PmaReaders and\n** the current PmaReader set to point to the first key in its range.\n**\n** SQLITE_OK is returned if successful, or an SQLite error code otherwise.\n*/\nstatic int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){\n  int rc = SQLITE_OK;\n  IncrMerger *pIncr = pReadr->pIncr;\n  SortSubtask *pTask = pIncr->pTask;\n  sqlite3 *db = pTask->pSorter->db;\n\n  /* eMode is always INCRINIT_NORMAL in single-threaded mode */\n  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );\n\n  rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);\n\n  /* Set up the required files for pIncr. A multi-theaded IncrMerge object\n  ** requires two temp files to itself, whereas a single-threaded object\n  ** only requires a region of pTask->file2. */\n  if( rc==SQLITE_OK ){\n    int mxSz = pIncr->mxSz;\n#if SQLITE_MAX_WORKER_THREADS>0\n    if( pIncr->bUseThread ){\n      rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);\n      if( rc==SQLITE_OK ){\n        rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);\n      }\n    }else\n#endif\n    /*if( !pIncr->bUseThread )*/{\n      if( pTask->file2.pFd==0 ){\n        assert( pTask->file2.iEof>0 );\n        rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);\n        pTask->file2.iEof = 0;\n      }\n      if( rc==SQLITE_OK ){\n        pIncr->aFile[1].pFd = pTask->file2.pFd;\n        pIncr->iStartOff = pTask->file2.iEof;\n        pTask->file2.iEof += mxSz;\n      }\n    }\n  }\n\n#if SQLITE_MAX_WORKER_THREADS>0\n  if( rc==SQLITE_OK && pIncr->bUseThread ){\n    /* Use the current thread to populate aFile[1], even though this\n    ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,\n    ** then this function is already running in background thread \n    ** pIncr->pTask->thread. \n    **\n    ** If this is the INCRINIT_ROOT object, then it is running in the \n    ** main VDBE thread. But that is Ok, as that thread cannot return\n    ** control to the VDBE or proceed with anything useful until the \n    ** first results are ready from this merger object anyway.\n    */\n    assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );\n    rc = vdbeIncrPopulate(pIncr);\n  }\n#endif\n\n  if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){\n    rc = vdbePmaReaderNext(pReadr);\n  }\n\n  return rc;\n}\n\n#if SQLITE_MAX_WORKER_THREADS>0\n/*\n** The main routine for vdbePmaReaderIncrMergeInit() operations run in \n** background threads.\n*/\nstatic void *vdbePmaReaderBgIncrInit(void *pCtx){\n  PmaReader *pReader = (PmaReader*)pCtx;\n  void *pRet = SQLITE_INT_TO_PTR(\n                  vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)\n               );\n  pReader->pIncr->pTask->bDone = 1;\n  return pRet;\n}\n#endif\n\n/*\n** If the PmaReader passed as the first argument is not an incremental-reader\n** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes\n** the vdbePmaReaderIncrMergeInit() function with the parameters passed to\n** this routine to initialize the incremental merge.\n** \n** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1), \n** then a background thread is launched to call vdbePmaReaderIncrMergeInit().\n** Or, if the IncrMerger is single threaded, the same function is called\n** using the current thread.\n*/\nstatic int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){\n  IncrMerger *pIncr = pReadr->pIncr;   /* Incremental merger */\n  int rc = SQLITE_OK;                  /* Return code */\n  if( pIncr ){\n#if SQLITE_MAX_WORKER_THREADS>0\n    assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );\n    if( pIncr->bUseThread ){\n      void *pCtx = (void*)pReadr;\n      rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);\n    }else\n#endif\n    {\n      rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);\n    }\n  }\n  return rc;\n}\n\n/*\n** Allocate a new MergeEngine object to merge the contents of nPMA level-0\n** PMAs from pTask->file. If no error occurs, set *ppOut to point to\n** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut\n** to NULL and return an SQLite error code.\n**\n** When this function is called, *piOffset is set to the offset of the\n** first PMA to read from pTask->file. Assuming no error occurs, it is \n** set to the offset immediately following the last byte of the last\n** PMA before returning. If an error does occur, then the final value of\n** *piOffset is undefined.\n*/\nstatic int vdbeMergeEngineLevel0(\n  SortSubtask *pTask,             /* Sorter task to read from */\n  int nPMA,                       /* Number of PMAs to read */\n  i64 *piOffset,                  /* IN/OUT: Readr offset in pTask->file */\n  MergeEngine **ppOut             /* OUT: New merge-engine */\n){\n  MergeEngine *pNew;              /* Merge engine to return */\n  i64 iOff = *piOffset;\n  int i;\n  int rc = SQLITE_OK;\n\n  *ppOut = pNew = vdbeMergeEngineNew(nPMA);\n  if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;\n\n  for(i=0; i<nPMA && rc==SQLITE_OK; i++){\n    i64 nDummy = 0;\n    PmaReader *pReadr = &pNew->aReadr[i];\n    rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);\n    iOff = pReadr->iEof;\n  }\n\n  if( rc!=SQLITE_OK ){\n    vdbeMergeEngineFree(pNew);\n    *ppOut = 0;\n  }\n  *piOffset = iOff;\n  return rc;\n}\n\n/*\n** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of\n** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.\n**\n** i.e.\n**\n**   nPMA<=16    -> TreeDepth() == 0\n**   nPMA<=256   -> TreeDepth() == 1\n**   nPMA<=65536 -> TreeDepth() == 2\n*/\nstatic int vdbeSorterTreeDepth(int nPMA){\n  int nDepth = 0;\n  i64 nDiv = SORTER_MAX_MERGE_COUNT;\n  while( nDiv < (i64)nPMA ){\n    nDiv = nDiv * SORTER_MAX_MERGE_COUNT;\n    nDepth++;\n  }\n  return nDepth;\n}\n\n/*\n** pRoot is the root of an incremental merge-tree with depth nDepth (according\n** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the\n** tree, counting from zero. This function adds pLeaf to the tree.\n**\n** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error\n** code is returned and pLeaf is freed.\n*/\nstatic int vdbeSorterAddToTree(\n  SortSubtask *pTask,             /* Task context */\n  int nDepth,                     /* Depth of tree according to TreeDepth() */\n  int iSeq,                       /* Sequence number of leaf within tree */\n  MergeEngine *pRoot,             /* Root of tree */\n  MergeEngine *pLeaf              /* Leaf to add to tree */\n){\n  int rc = SQLITE_OK;\n  int nDiv = 1;\n  int i;\n  MergeEngine *p = pRoot;\n  IncrMerger *pIncr;\n\n  rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);\n\n  for(i=1; i<nDepth; i++){\n    nDiv = nDiv * SORTER_MAX_MERGE_COUNT;\n  }\n\n  for(i=1; i<nDepth && rc==SQLITE_OK; i++){\n    int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;\n    PmaReader *pReadr = &p->aReadr[iIter];\n\n    if( pReadr->pIncr==0 ){\n      MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);\n      if( pNew==0 ){\n        rc = SQLITE_NOMEM_BKPT;\n      }else{\n        rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);\n      }\n    }\n    if( rc==SQLITE_OK ){\n      p = pReadr->pIncr->pMerger;\n      nDiv = nDiv / SORTER_MAX_MERGE_COUNT;\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;\n  }else{\n    vdbeIncrFree(pIncr);\n  }\n  return rc;\n}\n\n/*\n** This function is called as part of a SorterRewind() operation on a sorter\n** that has already written two or more level-0 PMAs to one or more temp\n** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that \n** can be used to incrementally merge all PMAs on disk.\n**\n** If successful, SQLITE_OK is returned and *ppOut set to point to the\n** MergeEngine object at the root of the tree before returning. Or, if an\n** error occurs, an SQLite error code is returned and the final value \n** of *ppOut is undefined.\n*/\nstatic int vdbeSorterMergeTreeBuild(\n  VdbeSorter *pSorter,       /* The VDBE cursor that implements the sort */\n  MergeEngine **ppOut        /* Write the MergeEngine here */\n){\n  MergeEngine *pMain = 0;\n  int rc = SQLITE_OK;\n  int iTask;\n\n#if SQLITE_MAX_WORKER_THREADS>0\n  /* If the sorter uses more than one task, then create the top-level \n  ** MergeEngine here. This MergeEngine will read data from exactly \n  ** one PmaReader per sub-task.  */\n  assert( pSorter->bUseThreads || pSorter->nTask==1 );\n  if( pSorter->nTask>1 ){\n    pMain = vdbeMergeEngineNew(pSorter->nTask);\n    if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;\n  }\n#endif\n\n  for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){\n    SortSubtask *pTask = &pSorter->aTask[iTask];\n    assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );\n    if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){\n      MergeEngine *pRoot = 0;     /* Root node of tree for this task */\n      int nDepth = vdbeSorterTreeDepth(pTask->nPMA);\n      i64 iReadOff = 0;\n\n      if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){\n        rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);\n      }else{\n        int i;\n        int iSeq = 0;\n        pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);\n        if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;\n        for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){\n          MergeEngine *pMerger = 0; /* New level-0 PMA merger */\n          int nReader;              /* Number of level-0 PMAs to merge */\n\n          nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);\n          rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);\n          if( rc==SQLITE_OK ){\n            rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);\n          }\n        }\n      }\n\n      if( rc==SQLITE_OK ){\n#if SQLITE_MAX_WORKER_THREADS>0\n        if( pMain!=0 ){\n          rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);\n        }else\n#endif\n        {\n          assert( pMain==0 );\n          pMain = pRoot;\n        }\n      }else{\n        vdbeMergeEngineFree(pRoot);\n      }\n    }\n  }\n\n  if( rc!=SQLITE_OK ){\n    vdbeMergeEngineFree(pMain);\n    pMain = 0;\n  }\n  *ppOut = pMain;\n  return rc;\n}\n\n/*\n** This function is called as part of an sqlite3VdbeSorterRewind() operation\n** on a sorter that has written two or more PMAs to temporary files. It sets\n** up either VdbeSorter.pMerger (for single threaded sorters) or pReader\n** (for multi-threaded sorters) so that it can be used to iterate through\n** all records stored in the sorter.\n**\n** SQLITE_OK is returned if successful, or an SQLite error code otherwise.\n*/\nstatic int vdbeSorterSetupMerge(VdbeSorter *pSorter){\n  int rc;                         /* Return code */\n  SortSubtask *pTask0 = &pSorter->aTask[0];\n  MergeEngine *pMain = 0;\n#if SQLITE_MAX_WORKER_THREADS\n  sqlite3 *db = pTask0->pSorter->db;\n  int i;\n  SorterCompare xCompare = vdbeSorterGetCompare(pSorter);\n  for(i=0; i<pSorter->nTask; i++){\n    pSorter->aTask[i].xCompare = xCompare;\n  }\n#endif\n\n  rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);\n  if( rc==SQLITE_OK ){\n#if SQLITE_MAX_WORKER_THREADS\n    assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );\n    if( pSorter->bUseThreads ){\n      int iTask;\n      PmaReader *pReadr = 0;\n      SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];\n      rc = vdbeSortAllocUnpacked(pLast);\n      if( rc==SQLITE_OK ){\n        pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));\n        pSorter->pReader = pReadr;\n        if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;\n      }\n      if( rc==SQLITE_OK ){\n        rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);\n        if( rc==SQLITE_OK ){\n          vdbeIncrMergerSetThreads(pReadr->pIncr);\n          for(iTask=0; iTask<(pSorter->nTask-1); iTask++){\n            IncrMerger *pIncr;\n            if( (pIncr = pMain->aReadr[iTask].pIncr) ){\n              vdbeIncrMergerSetThreads(pIncr);\n              assert( pIncr->pTask!=pLast );\n            }\n          }\n          for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){\n            /* Check that:\n            **   \n            **   a) The incremental merge object is configured to use the\n            **      right task, and\n            **   b) If it is using task (nTask-1), it is configured to run\n            **      in single-threaded mode. This is important, as the\n            **      root merge (INCRINIT_ROOT) will be using the same task\n            **      object.\n            */\n            PmaReader *p = &pMain->aReadr[iTask];\n            assert( p->pIncr==0 || (\n                (p->pIncr->pTask==&pSorter->aTask[iTask])             /* a */\n             && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0)  /* b */\n            ));\n            rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);\n          }\n        }\n        pMain = 0;\n      }\n      if( rc==SQLITE_OK ){\n        rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);\n      }\n    }else\n#endif\n    {\n      rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);\n      pSorter->pMerger = pMain;\n      pMain = 0;\n    }\n  }\n\n  if( rc!=SQLITE_OK ){\n    vdbeMergeEngineFree(pMain);\n  }\n  return rc;\n}\n\n\n/*\n** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,\n** this function is called to prepare for iterating through the records\n** in sorted order.\n*/\nSQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){\n  VdbeSorter *pSorter;\n  int rc = SQLITE_OK;             /* Return code */\n\n  assert( pCsr->eCurType==CURTYPE_SORTER );\n  pSorter = pCsr->uc.pSorter;\n  assert( pSorter );\n\n  /* If no data has been written to disk, then do not do so now. Instead,\n  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly\n  ** from the in-memory list.  */\n  if( pSorter->bUsePMA==0 ){\n    if( pSorter->list.pList ){\n      *pbEof = 0;\n      rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);\n    }else{\n      *pbEof = 1;\n    }\n    return rc;\n  }\n\n  /* Write the current in-memory list to a PMA. When the VdbeSorterWrite() \n  ** function flushes the contents of memory to disk, it immediately always\n  ** creates a new list consisting of a single key immediately afterwards.\n  ** So the list is never empty at this point.  */\n  assert( pSorter->list.pList );\n  rc = vdbeSorterFlushPMA(pSorter);\n\n  /* Join all threads */\n  rc = vdbeSorterJoinAll(pSorter, rc);\n\n  vdbeSorterRewindDebug(\"rewind\");\n\n  /* Assuming no errors have occurred, set up a merger structure to \n  ** incrementally read and merge all remaining PMAs.  */\n  assert( pSorter->pReader==0 );\n  if( rc==SQLITE_OK ){\n    rc = vdbeSorterSetupMerge(pSorter);\n    *pbEof = 0;\n  }\n\n  vdbeSorterRewindDebug(\"rewinddone\");\n  return rc;\n}\n\n/*\n** Advance to the next element in the sorter.  Return value:\n**\n**    SQLITE_OK     success\n**    SQLITE_DONE   end of data\n**    otherwise     some kind of error.\n*/\nSQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){\n  VdbeSorter *pSorter;\n  int rc;                         /* Return code */\n\n  assert( pCsr->eCurType==CURTYPE_SORTER );\n  pSorter = pCsr->uc.pSorter;\n  assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );\n  if( pSorter->bUsePMA ){\n    assert( pSorter->pReader==0 || pSorter->pMerger==0 );\n    assert( pSorter->bUseThreads==0 || pSorter->pReader );\n    assert( pSorter->bUseThreads==1 || pSorter->pMerger );\n#if SQLITE_MAX_WORKER_THREADS>0\n    if( pSorter->bUseThreads ){\n      rc = vdbePmaReaderNext(pSorter->pReader);\n      if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;\n    }else\n#endif\n    /*if( !pSorter->bUseThreads )*/ {\n      int res = 0;\n      assert( pSorter->pMerger!=0 );\n      assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );\n      rc = vdbeMergeEngineStep(pSorter->pMerger, &res);\n      if( rc==SQLITE_OK && res ) rc = SQLITE_DONE;\n    }\n  }else{\n    SorterRecord *pFree = pSorter->list.pList;\n    pSorter->list.pList = pFree->u.pNext;\n    pFree->u.pNext = 0;\n    if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);\n    rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;\n  }\n  return rc;\n}\n\n/*\n** Return a pointer to a buffer owned by the sorter that contains the \n** current key.\n*/\nstatic void *vdbeSorterRowkey(\n  const VdbeSorter *pSorter,      /* Sorter object */\n  int *pnKey                      /* OUT: Size of current key in bytes */\n){\n  void *pKey;\n  if( pSorter->bUsePMA ){\n    PmaReader *pReader;\n#if SQLITE_MAX_WORKER_THREADS>0\n    if( pSorter->bUseThreads ){\n      pReader = pSorter->pReader;\n    }else\n#endif\n    /*if( !pSorter->bUseThreads )*/{\n      pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];\n    }\n    *pnKey = pReader->nKey;\n    pKey = pReader->aKey;\n  }else{\n    *pnKey = pSorter->list.pList->nVal;\n    pKey = SRVAL(pSorter->list.pList);\n  }\n  return pKey;\n}\n\n/*\n** Copy the current sorter key into the memory cell pOut.\n*/\nSQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){\n  VdbeSorter *pSorter;\n  void *pKey; int nKey;           /* Sorter key to copy into pOut */\n\n  assert( pCsr->eCurType==CURTYPE_SORTER );\n  pSorter = pCsr->uc.pSorter;\n  pKey = vdbeSorterRowkey(pSorter, &nKey);\n  if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){\n    return SQLITE_NOMEM_BKPT;\n  }\n  pOut->n = nKey;\n  MemSetTypeFlag(pOut, MEM_Blob);\n  memcpy(pOut->z, pKey, nKey);\n\n  return SQLITE_OK;\n}\n\n/*\n** Compare the key in memory cell pVal with the key that the sorter cursor\n** passed as the first argument currently points to. For the purposes of\n** the comparison, ignore the rowid field at the end of each record.\n**\n** If the sorter cursor key contains any NULL values, consider it to be\n** less than pVal. Even if pVal also contains NULL values.\n**\n** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).\n** Otherwise, set *pRes to a negative, zero or positive value if the\n** key in pVal is smaller than, equal to or larger than the current sorter\n** key.\n**\n** This routine forms the core of the OP_SorterCompare opcode, which in\n** turn is used to verify uniqueness when constructing a UNIQUE INDEX.\n*/\nSQLITE_PRIVATE int sqlite3VdbeSorterCompare(\n  const VdbeCursor *pCsr,         /* Sorter cursor */\n  Mem *pVal,                      /* Value to compare to current sorter key */\n  int nKeyCol,                    /* Compare this many columns */\n  int *pRes                       /* OUT: Result of comparison */\n){\n  VdbeSorter *pSorter;\n  UnpackedRecord *r2;\n  KeyInfo *pKeyInfo;\n  int i;\n  void *pKey; int nKey;           /* Sorter key to compare pVal with */\n\n  assert( pCsr->eCurType==CURTYPE_SORTER );\n  pSorter = pCsr->uc.pSorter;\n  r2 = pSorter->pUnpacked;\n  pKeyInfo = pCsr->pKeyInfo;\n  if( r2==0 ){\n    r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);\n    if( r2==0 ) return SQLITE_NOMEM_BKPT;\n    r2->nField = nKeyCol;\n  }\n  assert( r2->nField==nKeyCol );\n\n  pKey = vdbeSorterRowkey(pSorter, &nKey);\n  sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);\n  for(i=0; i<nKeyCol; i++){\n    if( r2->aMem[i].flags & MEM_Null ){\n      *pRes = -1;\n      return SQLITE_OK;\n    }\n  }\n\n  *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);\n  return SQLITE_OK;\n}\n\n/************** End of vdbesort.c ********************************************/\n/************** Begin file vdbevtab.c ****************************************/\n/*\n** 2020-03-23\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file implements virtual-tables for examining the bytecode content\n** of a prepared statement.\n*/\n/* #include \"sqliteInt.h\" */\n#if defined(SQLITE_ENABLE_BYTECODE_VTAB) && !defined(SQLITE_OMIT_VIRTUALTABLE)\n/* #include \"vdbeInt.h\" */\n\n/* An instance of the bytecode() table-valued function.\n*/\ntypedef struct bytecodevtab bytecodevtab;\nstruct bytecodevtab {\n  sqlite3_vtab base;     /* Base class - must be first */\n  sqlite3 *db;           /* Database connection */\n  int bTablesUsed;       /* 2 for tables_used().  0 for bytecode(). */\n};\n\n/* A cursor for scanning through the bytecode\n*/\ntypedef struct bytecodevtab_cursor bytecodevtab_cursor;\nstruct bytecodevtab_cursor {\n  sqlite3_vtab_cursor base;  /* Base class - must be first */\n  sqlite3_stmt *pStmt;       /* The statement whose bytecode is displayed */\n  int iRowid;                /* The rowid of the output table */\n  int iAddr;                 /* Address */\n  int needFinalize;          /* Cursors owns pStmt and must finalize it */\n  int showSubprograms;       /* Provide a listing of subprograms */\n  Op *aOp;                   /* Operand array */\n  char *zP4;                 /* Rendered P4 value */\n  const char *zType;         /* tables_used.type */\n  const char *zSchema;       /* tables_used.schema */\n  const char *zName;         /* tables_used.name */\n  Mem sub;                   /* Subprograms */\n};\n\n/*\n** Create a new bytecode() table-valued function.\n*/\nstatic int bytecodevtabConnect(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  bytecodevtab *pNew;\n  int rc;\n  int isTabUsed = pAux!=0;\n  const char *azSchema[2] = {\n    /* bytecode() schema */\n    \"CREATE TABLE x(\"\n      \"addr INT,\"\n      \"opcode TEXT,\"\n      \"p1 INT,\"\n      \"p2 INT,\"\n      \"p3 INT,\"\n      \"p4 TEXT,\"\n      \"p5 INT,\"\n      \"comment TEXT,\"\n      \"subprog TEXT,\" \n      \"stmt HIDDEN\"\n    \");\",\n\n    /* Tables_used() schema */\n    \"CREATE TABLE x(\"\n      \"type TEXT,\"\n      \"schema TEXT,\"\n      \"name TEXT,\"\n      \"wr INT,\"\n      \"subprog TEXT,\" \n      \"stmt HIDDEN\"\n   \");\"\n  };\n\n  rc = sqlite3_declare_vtab(db, azSchema[isTabUsed]);\n  if( rc==SQLITE_OK ){\n    pNew = sqlite3_malloc( sizeof(*pNew) );\n    *ppVtab = (sqlite3_vtab*)pNew;\n    if( pNew==0 ) return SQLITE_NOMEM;\n    memset(pNew, 0, sizeof(*pNew));\n    pNew->db = db;\n    pNew->bTablesUsed = isTabUsed*2;\n  }\n  return rc;\n}\n\n/*\n** This method is the destructor for bytecodevtab objects.\n*/\nstatic int bytecodevtabDisconnect(sqlite3_vtab *pVtab){\n  bytecodevtab *p = (bytecodevtab*)pVtab;\n  sqlite3_free(p);\n  return SQLITE_OK;\n}\n\n/*\n** Constructor for a new bytecodevtab_cursor object.\n*/\nstatic int bytecodevtabOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){\n  bytecodevtab *pVTab = (bytecodevtab*)p;\n  bytecodevtab_cursor *pCur;\n  pCur = sqlite3_malloc( sizeof(*pCur) );\n  if( pCur==0 ) return SQLITE_NOMEM;\n  memset(pCur, 0, sizeof(*pCur));\n  sqlite3VdbeMemInit(&pCur->sub, pVTab->db, 1);\n  *ppCursor = &pCur->base;\n  return SQLITE_OK;\n}\n\n/*\n** Clear all internal content from a bytecodevtab cursor.\n*/\nstatic void bytecodevtabCursorClear(bytecodevtab_cursor *pCur){\n  sqlite3_free(pCur->zP4);\n  pCur->zP4 = 0;\n  sqlite3VdbeMemRelease(&pCur->sub);\n  sqlite3VdbeMemSetNull(&pCur->sub);\n  if( pCur->needFinalize ){\n    sqlite3_finalize(pCur->pStmt);\n  }\n  pCur->pStmt = 0;\n  pCur->needFinalize = 0;\n  pCur->zType = 0;\n  pCur->zSchema = 0;\n  pCur->zName = 0;\n}\n\n/*\n** Destructor for a bytecodevtab_cursor.\n*/\nstatic int bytecodevtabClose(sqlite3_vtab_cursor *cur){\n  bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;\n  bytecodevtabCursorClear(pCur);\n  sqlite3_free(pCur);\n  return SQLITE_OK;\n}\n\n\n/*\n** Advance a bytecodevtab_cursor to its next row of output.\n*/\nstatic int bytecodevtabNext(sqlite3_vtab_cursor *cur){\n  bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;\n  bytecodevtab *pTab = (bytecodevtab*)cur->pVtab;\n  int rc;\n  if( pCur->zP4 ){\n    sqlite3_free(pCur->zP4);\n    pCur->zP4 = 0;\n  }\n  if( pCur->zName ){\n    pCur->zName = 0;\n    pCur->zType = 0;\n    pCur->zSchema = 0;\n  }\n  rc = sqlite3VdbeNextOpcode(\n           (Vdbe*)pCur->pStmt, \n           pCur->showSubprograms ? &pCur->sub : 0,\n           pTab->bTablesUsed,\n           &pCur->iRowid,\n           &pCur->iAddr,\n           &pCur->aOp);\n  if( rc!=SQLITE_OK ){\n    sqlite3VdbeMemSetNull(&pCur->sub);\n    pCur->aOp = 0;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Return TRUE if the cursor has been moved off of the last\n** row of output.\n*/\nstatic int bytecodevtabEof(sqlite3_vtab_cursor *cur){\n  bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;\n  return pCur->aOp==0;\n}\n\n/*\n** Return values of columns for the row at which the bytecodevtab_cursor\n** is currently pointing.\n*/\nstatic int bytecodevtabColumn(\n  sqlite3_vtab_cursor *cur,   /* The cursor */\n  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */\n  int i                       /* Which column to return */\n){\n  bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;\n  bytecodevtab *pVTab = (bytecodevtab*)cur->pVtab;\n  Op *pOp = pCur->aOp + pCur->iAddr;\n  if( pVTab->bTablesUsed ){\n    if( i==4 ){\n      i = 8;\n    }else{\n      if( i<=2 && pCur->zType==0 ){\n        Schema *pSchema;\n        HashElem *k;\n        int iDb = pOp->p3;\n        int iRoot = pOp->p2;\n        sqlite3 *db = pVTab->db;\n        pSchema = db->aDb[iDb].pSchema;\n        pCur->zSchema = db->aDb[iDb].zDbSName;\n        for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){\n          Table *pTab = (Table*)sqliteHashData(k);\n          if( !IsVirtual(pTab) && pTab->tnum==iRoot ){\n            pCur->zName = pTab->zName;\n            pCur->zType = \"table\";\n            break;\n          }\n        }\n        if( pCur->zName==0 ){\n          for(k=sqliteHashFirst(&pSchema->idxHash); k; k=sqliteHashNext(k)){\n            Index *pIdx = (Index*)sqliteHashData(k);\n            if( pIdx->tnum==iRoot ){\n              pCur->zName = pIdx->zName;\n              pCur->zType = \"index\";\n            }\n          }\n        }\n      }\n      i += 10;\n    }\n  }\n  switch( i ){\n    case 0:   /* addr */\n      sqlite3_result_int(ctx, pCur->iAddr);\n      break;\n    case 1:   /* opcode */\n      sqlite3_result_text(ctx, (char*)sqlite3OpcodeName(pOp->opcode),\n                          -1, SQLITE_STATIC);\n      break;\n    case 2:   /* p1 */\n      sqlite3_result_int(ctx, pOp->p1);\n      break;\n    case 3:   /* p2 */\n      sqlite3_result_int(ctx, pOp->p2);\n      break;\n    case 4:   /* p3 */\n      sqlite3_result_int(ctx, pOp->p3);\n      break;\n    case 5:   /* p4 */\n    case 7:   /* comment */\n      if( pCur->zP4==0 ){\n        pCur->zP4 = sqlite3VdbeDisplayP4(pVTab->db, pOp);\n      }\n      if( i==5 ){\n        sqlite3_result_text(ctx, pCur->zP4, -1, SQLITE_STATIC);\n      }else{\n#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS\n        char *zCom = sqlite3VdbeDisplayComment(pVTab->db, pOp, pCur->zP4);\n        sqlite3_result_text(ctx, zCom, -1, sqlite3_free);\n#endif\n      }\n      break;\n    case 6:     /* p5 */\n      sqlite3_result_int(ctx, pOp->p5);\n      break;\n    case 8: {   /* subprog */\n      Op *aOp = pCur->aOp;\n      assert( aOp[0].opcode==OP_Init );\n      assert( aOp[0].p4.z==0 || strncmp(aOp[0].p4.z,\"-\" \"- \",3)==0 );\n      if( pCur->iRowid==pCur->iAddr+1 ){\n        break;  /* Result is NULL for the main program */\n      }else if( aOp[0].p4.z!=0 ){\n         sqlite3_result_text(ctx, aOp[0].p4.z+3, -1, SQLITE_STATIC);\n      }else{\n         sqlite3_result_text(ctx, \"(FK)\", 4, SQLITE_STATIC);\n      }\n      break;\n    }\n    case 10:  /* tables_used.type */\n      sqlite3_result_text(ctx, pCur->zType, -1, SQLITE_STATIC);\n      break;\n    case 11:  /* tables_used.schema */\n      sqlite3_result_text(ctx, pCur->zSchema, -1, SQLITE_STATIC);\n      break;\n    case 12:  /* tables_used.name */\n      sqlite3_result_text(ctx, pCur->zName, -1, SQLITE_STATIC);\n      break;\n    case 13:  /* tables_used.wr */\n      sqlite3_result_int(ctx, pOp->opcode==OP_OpenWrite);\n      break;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Return the rowid for the current row.  In this implementation, the\n** rowid is the same as the output value.\n*/\nstatic int bytecodevtabRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){\n  bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;\n  *pRowid = pCur->iRowid;\n  return SQLITE_OK;\n}\n\n/*\n** Initialize a cursor.\n**\n**    idxNum==0     means show all subprograms\n**    idxNum==1     means show only the main bytecode and omit subprograms.\n*/\nstatic int bytecodevtabFilter(\n  sqlite3_vtab_cursor *pVtabCursor, \n  int idxNum, const char *idxStr,\n  int argc, sqlite3_value **argv\n){\n  bytecodevtab_cursor *pCur = (bytecodevtab_cursor *)pVtabCursor;\n  bytecodevtab *pVTab = (bytecodevtab *)pVtabCursor->pVtab;\n  int rc = SQLITE_OK;\n\n  bytecodevtabCursorClear(pCur);\n  pCur->iRowid = 0;\n  pCur->iAddr = 0;\n  pCur->showSubprograms = idxNum==0;\n  assert( argc==1 );\n  if( sqlite3_value_type(argv[0])==SQLITE_TEXT ){\n    const char *zSql = (const char*)sqlite3_value_text(argv[0]);\n    if( zSql==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      rc = sqlite3_prepare_v2(pVTab->db, zSql, -1, &pCur->pStmt, 0);\n      pCur->needFinalize = 1;\n    }\n  }else{\n    pCur->pStmt = (sqlite3_stmt*)sqlite3_value_pointer(argv[0],\"stmt-pointer\");\n  }\n  if( pCur->pStmt==0 ){\n    pVTab->base.zErrMsg = sqlite3_mprintf(\n       \"argument to %s() is not a valid SQL statement\",\n       pVTab->bTablesUsed ? \"tables_used\" : \"bytecode\"\n    );\n    rc = SQLITE_ERROR;\n  }else{\n    bytecodevtabNext(pVtabCursor);\n  }\n  return rc;\n}\n\n/*\n** We must have a single stmt=? constraint that will be passed through\n** into the xFilter method.  If there is no valid stmt=? constraint,\n** then return an SQLITE_CONSTRAINT error.\n*/\nstatic int bytecodevtabBestIndex(\n  sqlite3_vtab *tab,\n  sqlite3_index_info *pIdxInfo\n){\n  int i;\n  int rc = SQLITE_CONSTRAINT;\n  struct sqlite3_index_constraint *p;\n  bytecodevtab *pVTab = (bytecodevtab*)tab;\n  int iBaseCol = pVTab->bTablesUsed ? 4 : 8;\n  pIdxInfo->estimatedCost = (double)100;\n  pIdxInfo->estimatedRows = 100;\n  pIdxInfo->idxNum = 0;\n  for(i=0, p=pIdxInfo->aConstraint; i<pIdxInfo->nConstraint; i++, p++){\n    if( p->usable==0 ) continue;\n    if( p->op==SQLITE_INDEX_CONSTRAINT_EQ && p->iColumn==iBaseCol+1 ){\n      rc = SQLITE_OK;\n      pIdxInfo->aConstraintUsage[i].omit = 1;\n      pIdxInfo->aConstraintUsage[i].argvIndex = 1;\n    }\n    if( p->op==SQLITE_INDEX_CONSTRAINT_ISNULL && p->iColumn==iBaseCol ){\n      pIdxInfo->aConstraintUsage[i].omit = 1;\n      pIdxInfo->idxNum = 1;\n    }\n  }\n  return rc;\n}\n\n/*\n** This following structure defines all the methods for the \n** virtual table.\n*/\nstatic sqlite3_module bytecodevtabModule = {\n  /* iVersion    */ 0,\n  /* xCreate     */ 0,\n  /* xConnect    */ bytecodevtabConnect,\n  /* xBestIndex  */ bytecodevtabBestIndex,\n  /* xDisconnect */ bytecodevtabDisconnect,\n  /* xDestroy    */ 0,\n  /* xOpen       */ bytecodevtabOpen,\n  /* xClose      */ bytecodevtabClose,\n  /* xFilter     */ bytecodevtabFilter,\n  /* xNext       */ bytecodevtabNext,\n  /* xEof        */ bytecodevtabEof,\n  /* xColumn     */ bytecodevtabColumn,\n  /* xRowid      */ bytecodevtabRowid,\n  /* xUpdate     */ 0,\n  /* xBegin      */ 0,\n  /* xSync       */ 0,\n  /* xCommit     */ 0,\n  /* xRollback   */ 0,\n  /* xFindMethod */ 0,\n  /* xRename     */ 0,\n  /* xSavepoint  */ 0,\n  /* xRelease    */ 0,\n  /* xRollbackTo */ 0,\n  /* xShadowName */ 0\n};\n\n\nSQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3 *db){\n  int rc;\n  rc = sqlite3_create_module(db, \"bytecode\", &bytecodevtabModule, 0);\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_module(db, \"tables_used\", &bytecodevtabModule, &db);\n  }\n  return rc;\n}\n#elif defined(SQLITE_ENABLE_BYTECODE_VTAB)\nSQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3 *db){ return SQLITE_OK; }\n#endif /* SQLITE_ENABLE_BYTECODE_VTAB */\n\n/************** End of vdbevtab.c ********************************************/\n/************** Begin file memjournal.c **************************************/\n/*\n** 2008 October 7\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains code use to implement an in-memory rollback journal.\n** The in-memory rollback journal is used to journal transactions for\n** \":memory:\" databases and when the journal_mode=MEMORY pragma is used.\n**\n** Update:  The in-memory journal is also used to temporarily cache\n** smaller journals that are not critical for power-loss recovery.\n** For example, statement journals that are not too big will be held\n** entirely in memory, thus reducing the number of file I/O calls, and\n** more importantly, reducing temporary file creation events.  If these\n** journals become too large for memory, they are spilled to disk.  But\n** in the common case, they are usually small and no file I/O needs to\n** occur.\n*/\n/* #include \"sqliteInt.h\" */\n\n/* Forward references to internal structures */\ntypedef struct MemJournal MemJournal;\ntypedef struct FilePoint FilePoint;\ntypedef struct FileChunk FileChunk;\n\n/*\n** The rollback journal is composed of a linked list of these structures.\n**\n** The zChunk array is always at least 8 bytes in size - usually much more.\n** Its actual size is stored in the MemJournal.nChunkSize variable.\n*/\nstruct FileChunk {\n  FileChunk *pNext;               /* Next chunk in the journal */\n  u8 zChunk[8];                   /* Content of this chunk */\n};\n\n/*\n** By default, allocate this many bytes of memory for each FileChunk object.\n*/\n#define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024\n\n/*\n** For chunk size nChunkSize, return the number of bytes that should\n** be allocated for each FileChunk structure.\n*/\n#define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))\n\n/*\n** An instance of this object serves as a cursor into the rollback journal.\n** The cursor can be either for reading or writing.\n*/\nstruct FilePoint {\n  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */\n  FileChunk *pChunk;              /* Specific chunk into which cursor points */\n};\n\n/*\n** This structure is a subclass of sqlite3_file. Each open memory-journal\n** is an instance of this class.\n*/\nstruct MemJournal {\n  const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */\n  int nChunkSize;                 /* In-memory chunk-size */\n\n  int nSpill;                     /* Bytes of data before flushing */\n  int nSize;                      /* Bytes of data currently in memory */\n  FileChunk *pFirst;              /* Head of in-memory chunk-list */\n  FilePoint endpoint;             /* Pointer to the end of the file */\n  FilePoint readpoint;            /* Pointer to the end of the last xRead() */\n\n  int flags;                      /* xOpen flags */\n  sqlite3_vfs *pVfs;              /* The \"real\" underlying VFS */\n  const char *zJournal;           /* Name of the journal file */\n};\n\n/*\n** Read data from the in-memory journal file.  This is the implementation\n** of the sqlite3_vfs.xRead method.\n*/\nstatic int memjrnlRead(\n  sqlite3_file *pJfd,    /* The journal file from which to read */\n  void *zBuf,            /* Put the results here */\n  int iAmt,              /* Number of bytes to read */\n  sqlite_int64 iOfst     /* Begin reading at this offset */\n){\n  MemJournal *p = (MemJournal *)pJfd;\n  u8 *zOut = zBuf;\n  int nRead = iAmt;\n  int iChunkOffset;\n  FileChunk *pChunk;\n\n  if( (iAmt+iOfst)>p->endpoint.iOffset ){\n    return SQLITE_IOERR_SHORT_READ;\n  }\n  assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );\n  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){\n    sqlite3_int64 iOff = 0;\n    for(pChunk=p->pFirst; \n        ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;\n        pChunk=pChunk->pNext\n    ){\n      iOff += p->nChunkSize;\n    }\n  }else{\n    pChunk = p->readpoint.pChunk;\n    assert( pChunk!=0 );\n  }\n\n  iChunkOffset = (int)(iOfst%p->nChunkSize);\n  do {\n    int iSpace = p->nChunkSize - iChunkOffset;\n    int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));\n    memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);\n    zOut += nCopy;\n    nRead -= iSpace;\n    iChunkOffset = 0;\n  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );\n  p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;\n  p->readpoint.pChunk = pChunk;\n\n  return SQLITE_OK;\n}\n\n/*\n** Free the list of FileChunk structures headed at MemJournal.pFirst.\n*/\nstatic void memjrnlFreeChunks(MemJournal *p){\n  FileChunk *pIter;\n  FileChunk *pNext;\n  for(pIter=p->pFirst; pIter; pIter=pNext){\n    pNext = pIter->pNext;\n    sqlite3_free(pIter);\n  } \n  p->pFirst = 0;\n}\n\n/*\n** Flush the contents of memory to a real file on disk.\n*/\nstatic int memjrnlCreateFile(MemJournal *p){\n  int rc;\n  sqlite3_file *pReal = (sqlite3_file*)p;\n  MemJournal copy = *p;\n\n  memset(p, 0, sizeof(MemJournal));\n  rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);\n  if( rc==SQLITE_OK ){\n    int nChunk = copy.nChunkSize;\n    i64 iOff = 0;\n    FileChunk *pIter;\n    for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){\n      if( iOff + nChunk > copy.endpoint.iOffset ){\n        nChunk = copy.endpoint.iOffset - iOff;\n      }\n      rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);\n      if( rc ) break;\n      iOff += nChunk;\n    }\n    if( rc==SQLITE_OK ){\n      /* No error has occurred. Free the in-memory buffers. */\n      memjrnlFreeChunks(&copy);\n    }\n  }\n  if( rc!=SQLITE_OK ){\n    /* If an error occurred while creating or writing to the file, restore\n    ** the original before returning. This way, SQLite uses the in-memory\n    ** journal data to roll back changes made to the internal page-cache\n    ** before this function was called.  */\n    sqlite3OsClose(pReal);\n    *p = copy;\n  }\n  return rc;\n}\n\n\n/*\n** Write data to the file.\n*/\nstatic int memjrnlWrite(\n  sqlite3_file *pJfd,    /* The journal file into which to write */\n  const void *zBuf,      /* Take data to be written from here */\n  int iAmt,              /* Number of bytes to write */\n  sqlite_int64 iOfst     /* Begin writing at this offset into the file */\n){\n  MemJournal *p = (MemJournal *)pJfd;\n  int nWrite = iAmt;\n  u8 *zWrite = (u8 *)zBuf;\n\n  /* If the file should be created now, create it and write the new data\n  ** into the file on disk. */\n  if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){\n    int rc = memjrnlCreateFile(p);\n    if( rc==SQLITE_OK ){\n      rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);\n    }\n    return rc;\n  }\n\n  /* If the contents of this write should be stored in memory */\n  else{\n    /* An in-memory journal file should only ever be appended to. Random\n    ** access writes are not required. The only exception to this is when\n    ** the in-memory journal is being used by a connection using the\n    ** atomic-write optimization. In this case the first 28 bytes of the\n    ** journal file may be written as part of committing the transaction. */ \n    assert( iOfst==p->endpoint.iOffset || iOfst==0 );\n#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \\\n || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)\n    if( iOfst==0 && p->pFirst ){\n      assert( p->nChunkSize>iAmt );\n      memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);\n    }else\n#else\n    assert( iOfst>0 || p->pFirst==0 );\n#endif\n    {\n      while( nWrite>0 ){\n        FileChunk *pChunk = p->endpoint.pChunk;\n        int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);\n        int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);\n\n        if( iChunkOffset==0 ){\n          /* New chunk is required to extend the file. */\n          FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));\n          if( !pNew ){\n            return SQLITE_IOERR_NOMEM_BKPT;\n          }\n          pNew->pNext = 0;\n          if( pChunk ){\n            assert( p->pFirst );\n            pChunk->pNext = pNew;\n          }else{\n            assert( !p->pFirst );\n            p->pFirst = pNew;\n          }\n          p->endpoint.pChunk = pNew;\n        }\n\n        memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);\n        zWrite += iSpace;\n        nWrite -= iSpace;\n        p->endpoint.iOffset += iSpace;\n      }\n      p->nSize = iAmt + iOfst;\n    }\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Truncate the file.\n**\n** If the journal file is already on disk, truncate it there. Or, if it\n** is still in main memory but is being truncated to zero bytes in size,\n** ignore \n*/\nstatic int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){\n  MemJournal *p = (MemJournal *)pJfd;\n  if( ALWAYS(size==0) ){\n    memjrnlFreeChunks(p);\n    p->nSize = 0;\n    p->endpoint.pChunk = 0;\n    p->endpoint.iOffset = 0;\n    p->readpoint.pChunk = 0;\n    p->readpoint.iOffset = 0;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Close the file.\n*/\nstatic int memjrnlClose(sqlite3_file *pJfd){\n  MemJournal *p = (MemJournal *)pJfd;\n  memjrnlFreeChunks(p);\n  return SQLITE_OK;\n}\n\n/*\n** Sync the file.\n**\n** If the real file has been created, call its xSync method. Otherwise, \n** syncing an in-memory journal is a no-op. \n*/\nstatic int memjrnlSync(sqlite3_file *pJfd, int flags){\n  UNUSED_PARAMETER2(pJfd, flags);\n  return SQLITE_OK;\n}\n\n/*\n** Query the size of the file in bytes.\n*/\nstatic int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){\n  MemJournal *p = (MemJournal *)pJfd;\n  *pSize = (sqlite_int64) p->endpoint.iOffset;\n  return SQLITE_OK;\n}\n\n/*\n** Table of methods for MemJournal sqlite3_file object.\n*/\nstatic const struct sqlite3_io_methods MemJournalMethods = {\n  1,                /* iVersion */\n  memjrnlClose,     /* xClose */\n  memjrnlRead,      /* xRead */\n  memjrnlWrite,     /* xWrite */\n  memjrnlTruncate,  /* xTruncate */\n  memjrnlSync,      /* xSync */\n  memjrnlFileSize,  /* xFileSize */\n  0,                /* xLock */\n  0,                /* xUnlock */\n  0,                /* xCheckReservedLock */\n  0,                /* xFileControl */\n  0,                /* xSectorSize */\n  0,                /* xDeviceCharacteristics */\n  0,                /* xShmMap */\n  0,                /* xShmLock */\n  0,                /* xShmBarrier */\n  0,                /* xShmUnmap */\n  0,                /* xFetch */\n  0                 /* xUnfetch */\n};\n\n/* \n** Open a journal file. \n**\n** The behaviour of the journal file depends on the value of parameter \n** nSpill. If nSpill is 0, then the journal file is always create and \n** accessed using the underlying VFS. If nSpill is less than zero, then\n** all content is always stored in main-memory. Finally, if nSpill is a\n** positive value, then the journal file is initially created in-memory\n** but may be flushed to disk later on. In this case the journal file is\n** flushed to disk either when it grows larger than nSpill bytes in size,\n** or when sqlite3JournalCreate() is called.\n*/\nSQLITE_PRIVATE int sqlite3JournalOpen(\n  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */\n  const char *zName,         /* Name of the journal file */\n  sqlite3_file *pJfd,        /* Preallocated, blank file handle */\n  int flags,                 /* Opening flags */\n  int nSpill                 /* Bytes buffered before opening the file */\n){\n  MemJournal *p = (MemJournal*)pJfd;\n\n  /* Zero the file-handle object. If nSpill was passed zero, initialize\n  ** it using the sqlite3OsOpen() function of the underlying VFS. In this\n  ** case none of the code in this module is executed as a result of calls\n  ** made on the journal file-handle.  */\n  memset(p, 0, sizeof(MemJournal));\n  if( nSpill==0 ){\n    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);\n  }\n\n  if( nSpill>0 ){\n    p->nChunkSize = nSpill;\n  }else{\n    p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);\n    assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );\n  }\n\n  p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;\n  p->nSpill = nSpill;\n  p->flags = flags;\n  p->zJournal = zName;\n  p->pVfs = pVfs;\n  return SQLITE_OK;\n}\n\n/*\n** Open an in-memory journal file.\n*/\nSQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){\n  sqlite3JournalOpen(0, 0, pJfd, 0, -1);\n}\n\n#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \\\n || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)\n/*\n** If the argument p points to a MemJournal structure that is not an \n** in-memory-only journal file (i.e. is one that was opened with a +ve\n** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying \n** file has not yet been created, create it now.\n*/\nSQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *pJfd){\n  int rc = SQLITE_OK;\n  MemJournal *p = (MemJournal*)pJfd;\n  if( p->pMethod==&MemJournalMethods && (\n#ifdef SQLITE_ENABLE_ATOMIC_WRITE\n     p->nSpill>0\n#else\n     /* While this appears to not be possible without ATOMIC_WRITE, the\n     ** paths are complex, so it seems prudent to leave the test in as\n     ** a NEVER(), in case our analysis is subtly flawed. */\n     NEVER(p->nSpill>0)\n#endif\n#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE\n     || (p->flags & SQLITE_OPEN_MAIN_JOURNAL)\n#endif\n  )){\n    rc = memjrnlCreateFile(p);\n  }\n  return rc;\n}\n#endif\n\n/*\n** The file-handle passed as the only argument is open on a journal file.\n** Return true if this \"journal file\" is currently stored in heap memory,\n** or false otherwise.\n*/\nSQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){\n  return p->pMethods==&MemJournalMethods;\n}\n\n/* \n** Return the number of bytes required to store a JournalFile that uses vfs\n** pVfs to create the underlying on-disk files.\n*/\nSQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){\n  return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));\n}\n\n/************** End of memjournal.c ******************************************/\n/************** Begin file walker.c ******************************************/\n/*\n** 2008 August 16\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains routines used for walking the parser tree for\n** an SQL statement.\n*/\n/* #include \"sqliteInt.h\" */\n/* #include <stdlib.h> */\n/* #include <string.h> */\n\n\n#if !defined(SQLITE_OMIT_WINDOWFUNC)\n/*\n** Walk all expressions linked into the list of Window objects passed\n** as the second argument.\n*/\nstatic int walkWindowList(Walker *pWalker, Window *pList){\n  Window *pWin;\n  for(pWin=pList; pWin; pWin=pWin->pNextWin){\n    int rc;\n    rc = sqlite3WalkExprList(pWalker, pWin->pOrderBy);\n    if( rc ) return WRC_Abort;\n    rc = sqlite3WalkExprList(pWalker, pWin->pPartition);\n    if( rc ) return WRC_Abort;\n    rc = sqlite3WalkExpr(pWalker, pWin->pFilter);\n    if( rc ) return WRC_Abort;\n\n    /* The next two are purely for calls to sqlite3RenameExprUnmap()\n    ** within sqlite3WindowOffsetExpr().  Because of constraints imposed\n    ** by sqlite3WindowOffsetExpr(), they can never fail.  The results do\n    ** not matter anyhow. */\n    rc = sqlite3WalkExpr(pWalker, pWin->pStart);\n    if( NEVER(rc) ) return WRC_Abort;\n    rc = sqlite3WalkExpr(pWalker, pWin->pEnd);\n    if( NEVER(rc) ) return WRC_Abort;\n  }\n  return WRC_Continue;\n}\n#endif\n\n/*\n** Walk an expression tree.  Invoke the callback once for each node\n** of the expression, while descending.  (In other words, the callback\n** is invoked before visiting children.)\n**\n** The return value from the callback should be one of the WRC_*\n** constants to specify how to proceed with the walk.\n**\n**    WRC_Continue      Continue descending down the tree.\n**\n**    WRC_Prune         Do not descend into child nodes, but allow\n**                      the walk to continue with sibling nodes.\n**\n**    WRC_Abort         Do no more callbacks.  Unwind the stack and\n**                      return from the top-level walk call.\n**\n** The return value from this routine is WRC_Abort to abandon the tree walk\n** and WRC_Continue to continue.\n*/\nstatic SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){\n  int rc;\n  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );\n  testcase( ExprHasProperty(pExpr, EP_Reduced) );\n  while(1){\n    rc = pWalker->xExprCallback(pWalker, pExpr);\n    if( rc ) return rc & WRC_Abort;\n    if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){\n      assert( pExpr->x.pList==0 || pExpr->pRight==0 );\n      if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;\n      if( pExpr->pRight ){\n        assert( !ExprHasProperty(pExpr, EP_WinFunc) );\n        pExpr = pExpr->pRight;\n        continue;\n      }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n        assert( !ExprHasProperty(pExpr, EP_WinFunc) );\n        if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;\n      }else{\n        if( pExpr->x.pList ){\n          if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;\n        }\n#ifndef SQLITE_OMIT_WINDOWFUNC\n        if( ExprHasProperty(pExpr, EP_WinFunc) ){\n          if( walkWindowList(pWalker, pExpr->y.pWin) ) return WRC_Abort;\n        }\n#endif\n      }\n    }\n    break;\n  }\n  return WRC_Continue;\n}\nSQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){\n  return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;\n}\n\n/*\n** Call sqlite3WalkExpr() for every expression in list p or until\n** an abort request is seen.\n*/\nSQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){\n  int i;\n  struct ExprList_item *pItem;\n  if( p ){\n    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){\n      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;\n    }\n  }\n  return WRC_Continue;\n}\n\n/*\n** Walk all expressions associated with SELECT statement p.  Do\n** not invoke the SELECT callback on p, but do (of course) invoke\n** any expr callbacks and SELECT callbacks that come from subqueries.\n** Return WRC_Abort or WRC_Continue.\n*/\nSQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){\n  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;\n  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;\n  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;\n  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;\n  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;\n  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;\n#if !defined(SQLITE_OMIT_WINDOWFUNC) && !defined(SQLITE_OMIT_ALTERTABLE)\n  {\n    Parse *pParse = pWalker->pParse;\n    if( pParse && IN_RENAME_OBJECT ){\n      /* The following may return WRC_Abort if there are unresolvable\n      ** symbols (e.g. a table that does not exist) in a window definition. */\n      int rc = walkWindowList(pWalker, p->pWinDefn);\n      return rc;\n    }\n  }\n#endif\n  return WRC_Continue;\n}\n\n/*\n** Walk the parse trees associated with all subqueries in the\n** FROM clause of SELECT statement p.  Do not invoke the select\n** callback on p, but do invoke it on each FROM clause subquery\n** and on any subqueries further down in the tree.  Return \n** WRC_Abort or WRC_Continue;\n*/\nSQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){\n  SrcList *pSrc;\n  int i;\n  struct SrcList_item *pItem;\n\n  pSrc = p->pSrc;\n  if( pSrc ){\n    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){\n      if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){\n        return WRC_Abort;\n      }\n      if( pItem->fg.isTabFunc\n       && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)\n      ){\n        return WRC_Abort;\n      }\n    }\n  }\n  return WRC_Continue;\n} \n\n/*\n** Call sqlite3WalkExpr() for every expression in Select statement p.\n** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and\n** on the compound select chain, p->pPrior. \n**\n** If it is not NULL, the xSelectCallback() callback is invoked before\n** the walk of the expressions and FROM clause. The xSelectCallback2()\n** method is invoked following the walk of the expressions and FROM clause,\n** but only if both xSelectCallback and xSelectCallback2 are both non-NULL\n** and if the expressions and FROM clause both return WRC_Continue;\n**\n** Return WRC_Continue under normal conditions.  Return WRC_Abort if\n** there is an abort request.\n**\n** If the Walker does not have an xSelectCallback() then this routine\n** is a no-op returning WRC_Continue.\n*/\nSQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){\n  int rc;\n  if( p==0 ) return WRC_Continue;\n  if( pWalker->xSelectCallback==0 ) return WRC_Continue;\n  do{\n    rc = pWalker->xSelectCallback(pWalker, p);\n    if( rc ) return rc & WRC_Abort;\n    if( sqlite3WalkSelectExpr(pWalker, p)\n     || sqlite3WalkSelectFrom(pWalker, p)\n    ){\n      return WRC_Abort;\n    }\n    if( pWalker->xSelectCallback2 ){\n      pWalker->xSelectCallback2(pWalker, p);\n    }\n    p = p->pPrior;\n  }while( p!=0 );\n  return WRC_Continue;\n}\n\n/* Increase the walkerDepth when entering a subquery, and\n** descrease when leaving the subquery.\n*/\nSQLITE_PRIVATE int sqlite3WalkerDepthIncrease(Walker *pWalker, Select *pSelect){\n  UNUSED_PARAMETER(pSelect);\n  pWalker->walkerDepth++;\n  return WRC_Continue;\n}\nSQLITE_PRIVATE void sqlite3WalkerDepthDecrease(Walker *pWalker, Select *pSelect){\n  UNUSED_PARAMETER(pSelect);\n  pWalker->walkerDepth--;\n}\n\n\n/*\n** No-op routine for the parse-tree walker.\n**\n** When this routine is the Walker.xExprCallback then expression trees\n** are walked without any actions being taken at each node.  Presumably,\n** when this routine is used for Walker.xExprCallback then \n** Walker.xSelectCallback is set to do something useful for every \n** subquery in the parser tree.\n*/\nSQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  return WRC_Continue;\n}\n\n/*\n** No-op routine for the parse-tree walker for SELECT statements.\n** subquery in the parser tree.\n*/\nSQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  return WRC_Continue;\n}\n\n/************** End of walker.c **********************************************/\n/************** Begin file resolve.c *****************************************/\n/*\n** 2008 August 18\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains routines used for walking the parser tree and\n** resolve all identifiers by associating them with a particular\n** table and column.\n*/\n/* #include \"sqliteInt.h\" */\n\n/*\n** Walk the expression tree pExpr and increase the aggregate function\n** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.\n** This needs to occur when copying a TK_AGG_FUNCTION node from an\n** outer query into an inner subquery.\n**\n** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)\n** is a helper function - a callback for the tree walker.\n**\n** See also the sqlite3WindowExtraAggFuncDepth() routine in window.c\n*/\nstatic int incrAggDepth(Walker *pWalker, Expr *pExpr){\n  if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;\n  return WRC_Continue;\n}\nstatic void incrAggFunctionDepth(Expr *pExpr, int N){\n  if( N>0 ){\n    Walker w;\n    memset(&w, 0, sizeof(w));\n    w.xExprCallback = incrAggDepth;\n    w.u.n = N;\n    sqlite3WalkExpr(&w, pExpr);\n  }\n}\n\n/*\n** Turn the pExpr expression into an alias for the iCol-th column of the\n** result set in pEList.\n**\n** If the reference is followed by a COLLATE operator, then make sure\n** the COLLATE operator is preserved.  For example:\n**\n**     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;\n**\n** Should be transformed into:\n**\n**     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;\n**\n** The nSubquery parameter specifies how many levels of subquery the\n** alias is removed from the original expression.  The usual value is\n** zero but it might be more if the alias is contained within a subquery\n** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION\n** structures must be increased by the nSubquery amount.\n*/\nstatic void resolveAlias(\n  Parse *pParse,         /* Parsing context */\n  ExprList *pEList,      /* A result set */\n  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */\n  Expr *pExpr,           /* Transform this into an alias to the result set */\n  const char *zType,     /* \"GROUP\" or \"ORDER\" or \"\" */\n  int nSubquery          /* Number of subqueries that the label is moving */\n){\n  Expr *pOrig;           /* The iCol-th column of the result set */\n  Expr *pDup;            /* Copy of pOrig */\n  sqlite3 *db;           /* The database connection */\n\n  assert( iCol>=0 && iCol<pEList->nExpr );\n  pOrig = pEList->a[iCol].pExpr;\n  assert( pOrig!=0 );\n  db = pParse->db;\n  pDup = sqlite3ExprDup(db, pOrig, 0);\n  if( pDup!=0 ){\n    if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);\n    if( pExpr->op==TK_COLLATE ){\n      pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);\n    }\n\n    /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This \n    ** prevents ExprDelete() from deleting the Expr structure itself,\n    ** allowing it to be repopulated by the memcpy() on the following line.\n    ** The pExpr->u.zToken might point into memory that will be freed by the\n    ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to\n    ** make a copy of the token before doing the sqlite3DbFree().\n    */\n    ExprSetProperty(pExpr, EP_Static);\n    sqlite3ExprDelete(db, pExpr);\n    memcpy(pExpr, pDup, sizeof(*pExpr));\n    if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){\n      assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );\n      pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);\n      pExpr->flags |= EP_MemToken;\n    }\n    if( ExprHasProperty(pExpr, EP_WinFunc) ){\n      if( pExpr->y.pWin!=0 ){\n        pExpr->y.pWin->pOwner = pExpr;\n      }else{\n        assert( db->mallocFailed );\n      }\n    }\n    sqlite3DbFree(db, pDup);\n  }\n  ExprSetProperty(pExpr, EP_Alias);\n}\n\n\n/*\n** Return TRUE if the name zCol occurs anywhere in the USING clause.\n**\n** Return FALSE if the USING clause is NULL or if it does not contain\n** zCol.\n*/\nstatic int nameInUsingClause(IdList *pUsing, const char *zCol){\n  if( pUsing ){\n    int k;\n    for(k=0; k<pUsing->nId; k++){\n      if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;\n    }\n  }\n  return 0;\n}\n\n/*\n** Subqueries stores the original database, table and column names for their\n** result sets in ExprList.a[].zSpan, in the form \"DATABASE.TABLE.COLUMN\".\n** Check to see if the zSpan given to this routine matches the zDb, zTab,\n** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will\n** match anything.\n*/\nSQLITE_PRIVATE int sqlite3MatchEName(\n  const struct ExprList_item *pItem,\n  const char *zCol,\n  const char *zTab,\n  const char *zDb\n){\n  int n;\n  const char *zSpan;\n  if( pItem->eEName!=ENAME_TAB ) return 0;\n  zSpan = pItem->zEName;\n  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}\n  if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){\n    return 0;\n  }\n  zSpan += n+1;\n  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}\n  if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){\n    return 0;\n  }\n  zSpan += n+1;\n  if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){\n    return 0;\n  }\n  return 1;\n}\n\n/*\n** Return TRUE if the double-quoted string  mis-feature should be supported.\n*/\nstatic int areDoubleQuotedStringsEnabled(sqlite3 *db, NameContext *pTopNC){\n  if( db->init.busy ) return 1;  /* Always support for legacy schemas */\n  if( pTopNC->ncFlags & NC_IsDDL ){\n    /* Currently parsing a DDL statement */\n    if( sqlite3WritableSchema(db) && (db->flags & SQLITE_DqsDML)!=0 ){\n      return 1;\n    }\n    return (db->flags & SQLITE_DqsDDL)!=0;\n  }else{\n    /* Currently parsing a DML statement */\n    return (db->flags & SQLITE_DqsDML)!=0;\n  }\n}\n\n/*\n** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN.\n** return the appropriate colUsed mask.\n*/\nSQLITE_PRIVATE Bitmask sqlite3ExprColUsed(Expr *pExpr){\n  int n;\n  Table *pExTab;\n\n  n = pExpr->iColumn;\n  pExTab = pExpr->y.pTab;\n  assert( pExTab!=0 );\n  if( (pExTab->tabFlags & TF_HasGenerated)!=0\n   && (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0 \n  ){\n    testcase( pExTab->nCol==BMS-1 );\n    testcase( pExTab->nCol==BMS );\n    return pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1;\n  }else{\n    testcase( n==BMS-1 );\n    testcase( n==BMS );\n    if( n>=BMS ) n = BMS-1;\n    return ((Bitmask)1)<<n;\n  }\n}\n\n/*\n** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up\n** that name in the set of source tables in pSrcList and make the pExpr \n** expression node refer back to that source column.  The following changes\n** are made to pExpr:\n**\n**    pExpr->iDb           Set the index in db->aDb[] of the database X\n**                         (even if X is implied).\n**    pExpr->iTable        Set to the cursor number for the table obtained\n**                         from pSrcList.\n**    pExpr->y.pTab        Points to the Table structure of X.Y (even if\n**                         X and/or Y are implied.)\n**    pExpr->iColumn       Set to the column number within the table.\n**    pExpr->op            Set to TK_COLUMN.\n**    pExpr->pLeft         Any expression this points to is deleted\n**    pExpr->pRight        Any expression this points to is deleted.\n**\n** The zDb variable is the name of the database (the \"X\").  This value may be\n** NULL meaning that name is of the form Y.Z or Z.  Any available database\n** can be used.  The zTable variable is the name of the table (the \"Y\").  This\n** value can be NULL if zDb is also NULL.  If zTable is NULL it\n** means that the form of the name is Z and that columns from any table\n** can be used.\n**\n** If the name cannot be resolved unambiguously, leave an error message\n** in pParse and return WRC_Abort.  Return WRC_Prune on success.\n*/\nstatic int lookupName(\n  Parse *pParse,       /* The parsing context */\n  const char *zDb,     /* Name of the database containing table, or NULL */\n  const char *zTab,    /* Name of table containing column, or NULL */\n  const char *zCol,    /* Name of the column. */\n  NameContext *pNC,    /* The name context used to resolve the name */\n  Expr *pExpr          /* Make this EXPR node point to the selected column */\n){\n  int i, j;                         /* Loop counters */\n  int cnt = 0;                      /* Number of matching column names */\n  int cntTab = 0;                   /* Number of matching table names */\n  int nSubquery = 0;                /* How many levels of subquery */\n  sqlite3 *db = pParse->db;         /* The database connection */\n  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */\n  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */\n  NameContext *pTopNC = pNC;        /* First namecontext in the list */\n  Schema *pSchema = 0;              /* Schema of the expression */\n  int eNewExprOp = TK_COLUMN;       /* New value for pExpr->op on success */\n  Table *pTab = 0;                  /* Table hold the row */\n  Column *pCol;                     /* A column of pTab */\n\n  assert( pNC );     /* the name context cannot be NULL. */\n  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */\n  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );\n\n  /* Initialize the node to no-match */\n  pExpr->iTable = -1;\n  ExprSetVVAProperty(pExpr, EP_NoReduce);\n\n  /* Translate the schema name in zDb into a pointer to the corresponding\n  ** schema.  If not found, pSchema will remain NULL and nothing will match\n  ** resulting in an appropriate error message toward the end of this routine\n  */\n  if( zDb ){\n    testcase( pNC->ncFlags & NC_PartIdx );\n    testcase( pNC->ncFlags & NC_IsCheck );\n    if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){\n      /* Silently ignore database qualifiers inside CHECK constraints and\n      ** partial indices.  Do not raise errors because that might break\n      ** legacy and because it does not hurt anything to just ignore the\n      ** database name. */\n      zDb = 0;\n    }else{\n      for(i=0; i<db->nDb; i++){\n        assert( db->aDb[i].zDbSName );\n        if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){\n          pSchema = db->aDb[i].pSchema;\n          break;\n        }\n      }\n      if( i==db->nDb && sqlite3StrICmp(\"main\", zDb)==0 ){\n        /* This branch is taken when the main database has been renamed\n        ** using SQLITE_DBCONFIG_MAINDBNAME. */\n        pSchema = db->aDb[0].pSchema;\n        zDb = db->aDb[0].zDbSName;\n      }\n    }\n  }\n\n  /* Start at the inner-most context and move outward until a match is found */\n  assert( pNC && cnt==0 );\n  do{\n    ExprList *pEList;\n    SrcList *pSrcList = pNC->pSrcList;\n\n    if( pSrcList ){\n      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){\n        u8 hCol;\n        pTab = pItem->pTab;\n        assert( pTab!=0 && pTab->zName!=0 );\n        assert( pTab->nCol>0 );\n        if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){\n          int hit = 0;\n          pEList = pItem->pSelect->pEList;\n          for(j=0; j<pEList->nExpr; j++){\n            if( sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb) ){\n              cnt++;\n              cntTab = 2;\n              pMatch = pItem;\n              pExpr->iColumn = j;\n              hit = 1;\n            }\n          }\n          if( hit || zTab==0 ) continue;\n        }\n        if( zDb && pTab->pSchema!=pSchema ){\n          continue;\n        }\n        if( zTab ){\n          const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;\n          assert( zTabName!=0 );\n          if( sqlite3StrICmp(zTabName, zTab)!=0 ){\n            continue;\n          }\n          if( IN_RENAME_OBJECT && pItem->zAlias ){\n            sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);\n          }\n        }\n        if( 0==(cntTab++) ){\n          pMatch = pItem;\n        }\n        hCol = sqlite3StrIHash(zCol);\n        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){\n          if( pCol->hName==hCol && sqlite3StrICmp(pCol->zName, zCol)==0 ){\n            /* If there has been exactly one prior match and this match\n            ** is for the right-hand table of a NATURAL JOIN or is in a \n            ** USING clause, then skip this match.\n            */\n            if( cnt==1 ){\n              if( pItem->fg.jointype & JT_NATURAL ) continue;\n              if( nameInUsingClause(pItem->pUsing, zCol) ) continue;\n            }\n            cnt++;\n            pMatch = pItem;\n            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */\n            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;\n            break;\n          }\n        }\n      }\n      if( pMatch ){\n        pExpr->iTable = pMatch->iCursor;\n        pExpr->y.pTab = pMatch->pTab;\n        /* RIGHT JOIN not (yet) supported */\n        assert( (pMatch->fg.jointype & JT_RIGHT)==0 );\n        if( (pMatch->fg.jointype & JT_LEFT)!=0 ){\n          ExprSetProperty(pExpr, EP_CanBeNull);\n        }\n        pSchema = pExpr->y.pTab->pSchema;\n      }\n    } /* if( pSrcList ) */\n\n#if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)\n    /* If we have not already resolved the name, then maybe \n    ** it is a new.* or old.* trigger argument reference.  Or\n    ** maybe it is an excluded.* from an upsert.\n    */\n    if( zDb==0 && zTab!=0 && cntTab==0 ){\n      pTab = 0;\n#ifndef SQLITE_OMIT_TRIGGER\n      if( pParse->pTriggerTab!=0 ){\n        int op = pParse->eTriggerOp;\n        assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );\n        if( op!=TK_DELETE && sqlite3StrICmp(\"new\",zTab) == 0 ){\n          pExpr->iTable = 1;\n          pTab = pParse->pTriggerTab;\n        }else if( op!=TK_INSERT && sqlite3StrICmp(\"old\",zTab)==0 ){\n          pExpr->iTable = 0;\n          pTab = pParse->pTriggerTab;\n        }\n      }\n#endif /* SQLITE_OMIT_TRIGGER */\n#ifndef SQLITE_OMIT_UPSERT\n      if( (pNC->ncFlags & NC_UUpsert)!=0 ){\n        Upsert *pUpsert = pNC->uNC.pUpsert;\n        if( pUpsert && sqlite3StrICmp(\"excluded\",zTab)==0 ){\n          pTab = pUpsert->pUpsertSrc->a[0].pTab;\n          pExpr->iTable = 2;\n        }\n      }\n#endif /* SQLITE_OMIT_UPSERT */\n\n      if( pTab ){ \n        int iCol;\n        u8 hCol = sqlite3StrIHash(zCol);\n        pSchema = pTab->pSchema;\n        cntTab++;\n        for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){\n          if( pCol->hName==hCol && sqlite3StrICmp(pCol->zName, zCol)==0 ){\n            if( iCol==pTab->iPKey ){\n              iCol = -1;\n            }\n            break;\n          }\n        }\n        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){\n          /* IMP: R-51414-32910 */\n          iCol = -1;\n        }\n        if( iCol<pTab->nCol ){\n          cnt++;\n#ifndef SQLITE_OMIT_UPSERT\n          if( pExpr->iTable==2 ){\n            testcase( iCol==(-1) );\n            if( IN_RENAME_OBJECT ){\n              pExpr->iColumn = iCol;\n              pExpr->y.pTab = pTab;\n              eNewExprOp = TK_COLUMN;\n            }else{\n              pExpr->iTable = pNC->uNC.pUpsert->regData + iCol;\n              eNewExprOp = TK_REGISTER;\n              ExprSetProperty(pExpr, EP_Alias);\n            }\n          }else\n#endif /* SQLITE_OMIT_UPSERT */\n          {\n#ifndef SQLITE_OMIT_TRIGGER\n            if( iCol<0 ){\n              pExpr->affExpr = SQLITE_AFF_INTEGER;\n            }else if( pExpr->iTable==0 ){\n              testcase( iCol==31 );\n              testcase( iCol==32 );\n              pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));\n            }else{\n              testcase( iCol==31 );\n              testcase( iCol==32 );\n              pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));\n            }\n            pExpr->y.pTab = pTab;\n            pExpr->iColumn = (i16)iCol;\n            eNewExprOp = TK_TRIGGER;\n#endif /* SQLITE_OMIT_TRIGGER */\n          }\n        }\n      }\n    }\n#endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */\n\n    /*\n    ** Perhaps the name is a reference to the ROWID\n    */\n    if( cnt==0\n     && cntTab==1\n     && pMatch\n     && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0\n     && sqlite3IsRowid(zCol)\n     && VisibleRowid(pMatch->pTab)\n    ){\n      cnt = 1;\n      pExpr->iColumn = -1;\n      pExpr->affExpr = SQLITE_AFF_INTEGER;\n    }\n\n    /*\n    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z\n    ** might refer to an result-set alias.  This happens, for example, when\n    ** we are resolving names in the WHERE clause of the following command:\n    **\n    **     SELECT a+b AS x FROM table WHERE x<10;\n    **\n    ** In cases like this, replace pExpr with a copy of the expression that\n    ** forms the result set entry (\"a+b\" in the example) and return immediately.\n    ** Note that the expression in the result set should have already been\n    ** resolved by the time the WHERE clause is resolved.\n    **\n    ** The ability to use an output result-set column in the WHERE, GROUP BY,\n    ** or HAVING clauses, or as part of a larger expression in the ORDER BY\n    ** clause is not standard SQL.  This is a (goofy) SQLite extension, that\n    ** is supported for backwards compatibility only. Hence, we issue a warning\n    ** on sqlite3_log() whenever the capability is used.\n    */\n    if( (pNC->ncFlags & NC_UEList)!=0\n     && cnt==0\n     && zTab==0\n    ){\n      pEList = pNC->uNC.pEList;\n      assert( pEList!=0 );\n      for(j=0; j<pEList->nExpr; j++){\n        char *zAs = pEList->a[j].zEName;\n        if( pEList->a[j].eEName==ENAME_NAME\n         && sqlite3_stricmp(zAs, zCol)==0\n        ){\n          Expr *pOrig;\n          assert( pExpr->pLeft==0 && pExpr->pRight==0 );\n          assert( pExpr->x.pList==0 );\n          assert( pExpr->x.pSelect==0 );\n          pOrig = pEList->a[j].pExpr;\n          if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){\n            sqlite3ErrorMsg(pParse, \"misuse of aliased aggregate %s\", zAs);\n            return WRC_Abort;\n          }\n          if( ExprHasProperty(pOrig, EP_Win)\n           && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC )\n          ){\n            sqlite3ErrorMsg(pParse, \"misuse of aliased window function %s\",zAs);\n            return WRC_Abort;\n          }\n          if( sqlite3ExprVectorSize(pOrig)!=1 ){\n            sqlite3ErrorMsg(pParse, \"row value misused\");\n            return WRC_Abort;\n          }\n          resolveAlias(pParse, pEList, j, pExpr, \"\", nSubquery);\n          cnt = 1;\n          pMatch = 0;\n          assert( zTab==0 && zDb==0 );\n          if( IN_RENAME_OBJECT ){\n            sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);\n          }\n          goto lookupname_end;\n        }\n      } \n    }\n\n    /* Advance to the next name context.  The loop will exit when either\n    ** we have a match (cnt>0) or when we run out of name contexts.\n    */\n    if( cnt ) break;\n    pNC = pNC->pNext;\n    nSubquery++;\n  }while( pNC );\n\n\n  /*\n  ** If X and Y are NULL (in other words if only the column name Z is\n  ** supplied) and the value of Z is enclosed in double-quotes, then\n  ** Z is a string literal if it doesn't match any column names.  In that\n  ** case, we need to return right away and not make any changes to\n  ** pExpr.\n  **\n  ** Because no reference was made to outer contexts, the pNC->nRef\n  ** fields are not changed in any context.\n  */\n  if( cnt==0 && zTab==0 ){\n    assert( pExpr->op==TK_ID );\n    if( ExprHasProperty(pExpr,EP_DblQuoted)\n     && areDoubleQuotedStringsEnabled(db, pTopNC)\n    ){\n      /* If a double-quoted identifier does not match any known column name,\n      ** then treat it as a string.\n      **\n      ** This hack was added in the early days of SQLite in a misguided attempt\n      ** to be compatible with MySQL 3.x, which used double-quotes for strings.\n      ** I now sorely regret putting in this hack. The effect of this hack is\n      ** that misspelled identifier names are silently converted into strings\n      ** rather than causing an error, to the frustration of countless\n      ** programmers. To all those frustrated programmers, my apologies.\n      **\n      ** Someday, I hope to get rid of this hack. Unfortunately there is\n      ** a huge amount of legacy SQL that uses it. So for now, we just\n      ** issue a warning.\n      */\n      sqlite3_log(SQLITE_WARNING,\n        \"double-quoted string literal: \\\"%w\\\"\", zCol);\n#ifdef SQLITE_ENABLE_NORMALIZE\n      sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);\n#endif\n      pExpr->op = TK_STRING;\n      pExpr->y.pTab = 0;\n      return WRC_Prune;\n    }\n    if( sqlite3ExprIdToTrueFalse(pExpr) ){\n      return WRC_Prune;\n    }\n  }\n\n  /*\n  ** cnt==0 means there was not match.  cnt>1 means there were two or\n  ** more matches.  Either way, we have an error.\n  */\n  if( cnt!=1 ){\n    const char *zErr;\n    zErr = cnt==0 ? \"no such column\" : \"ambiguous column name\";\n    if( zDb ){\n      sqlite3ErrorMsg(pParse, \"%s: %s.%s.%s\", zErr, zDb, zTab, zCol);\n    }else if( zTab ){\n      sqlite3ErrorMsg(pParse, \"%s: %s.%s\", zErr, zTab, zCol);\n    }else{\n      sqlite3ErrorMsg(pParse, \"%s: %s\", zErr, zCol);\n    }\n    pParse->checkSchema = 1;\n    pTopNC->nErr++;\n  }\n\n  /* If a column from a table in pSrcList is referenced, then record\n  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes\n  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  Bit 63 is\n  ** set if the 63rd or any subsequent column is used.\n  **\n  ** The colUsed mask is an optimization used to help determine if an\n  ** index is a covering index.  The correct answer is still obtained\n  ** if the mask contains extra set bits.  However, it is important to\n  ** avoid setting bits beyond the maximum column number of the table.\n  ** (See ticket [b92e5e8ec2cdbaa1]).\n  **\n  ** If a generated column is referenced, set bits for every column\n  ** of the table.\n  */\n  if( pExpr->iColumn>=0 && pMatch!=0 ){\n    pMatch->colUsed |= sqlite3ExprColUsed(pExpr);\n  }\n\n  /* Clean up and return\n  */\n  sqlite3ExprDelete(db, pExpr->pLeft);\n  pExpr->pLeft = 0;\n  sqlite3ExprDelete(db, pExpr->pRight);\n  pExpr->pRight = 0;\n  pExpr->op = eNewExprOp;\n  ExprSetProperty(pExpr, EP_Leaf);\nlookupname_end:\n  if( cnt==1 ){\n    assert( pNC!=0 );\n    if( !ExprHasProperty(pExpr, EP_Alias) ){\n      sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);\n    }\n    /* Increment the nRef value on all name contexts from TopNC up to\n    ** the point where the name matched. */\n    for(;;){\n      assert( pTopNC!=0 );\n      pTopNC->nRef++;\n      if( pTopNC==pNC ) break;\n      pTopNC = pTopNC->pNext;\n    }\n    return WRC_Prune;\n  } else {\n    return WRC_Abort;\n  }\n}\n\n/*\n** Allocate and return a pointer to an expression to load the column iCol\n** from datasource iSrc in SrcList pSrc.\n*/\nSQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){\n  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);\n  if( p ){\n    struct SrcList_item *pItem = &pSrc->a[iSrc];\n    Table *pTab = p->y.pTab = pItem->pTab;\n    p->iTable = pItem->iCursor;\n    if( p->y.pTab->iPKey==iCol ){\n      p->iColumn = -1;\n    }else{\n      p->iColumn = (ynVar)iCol;\n      if( (pTab->tabFlags & TF_HasGenerated)!=0\n       && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0\n      ){\n        testcase( pTab->nCol==63 );\n        testcase( pTab->nCol==64 );\n        pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1;\n      }else{\n        testcase( iCol==BMS );\n        testcase( iCol==BMS-1 );\n        pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);\n      }\n    }\n  }\n  return p;\n}\n\n/*\n** Report an error that an expression is not valid for some set of\n** pNC->ncFlags values determined by validMask.\n**\n** static void notValid(\n**   Parse *pParse,       // Leave error message here\n**   NameContext *pNC,    // The name context \n**   const char *zMsg,    // Type of error\n**   int validMask,       // Set of contexts for which prohibited\n**   Expr *pExpr          // Invalidate this expression on error\n** ){...}\n**\n** As an optimization, since the conditional is almost always false\n** (because errors are rare), the conditional is moved outside of the\n** function call using a macro.\n*/\nstatic void notValidImpl(\n   Parse *pParse,       /* Leave error message here */\n   NameContext *pNC,    /* The name context */\n   const char *zMsg,    /* Type of error */\n   Expr *pExpr          /* Invalidate this expression on error */\n){\n  const char *zIn = \"partial index WHERE clauses\";\n  if( pNC->ncFlags & NC_IdxExpr )      zIn = \"index expressions\";\n#ifndef SQLITE_OMIT_CHECK\n  else if( pNC->ncFlags & NC_IsCheck ) zIn = \"CHECK constraints\";\n#endif\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n  else if( pNC->ncFlags & NC_GenCol ) zIn = \"generated columns\";\n#endif\n  sqlite3ErrorMsg(pParse, \"%s prohibited in %s\", zMsg, zIn);\n  if( pExpr ) pExpr->op = TK_NULL;\n}\n#define sqlite3ResolveNotValid(P,N,M,X,E) \\\n  assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \\\n  if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E);\n\n/*\n** Expression p should encode a floating point value between 1.0 and 0.0.\n** Return 1024 times this value.  Or return -1 if p is not a floating point\n** value between 1.0 and 0.0.\n*/\nstatic int exprProbability(Expr *p){\n  double r = -1.0;\n  if( p->op!=TK_FLOAT ) return -1;\n  sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);\n  assert( r>=0.0 );\n  if( r>1.0 ) return -1;\n  return (int)(r*134217728.0);\n}\n\n/*\n** This routine is callback for sqlite3WalkExpr().\n**\n** Resolve symbolic names into TK_COLUMN operators for the current\n** node in the expression tree.  Return 0 to continue the search down\n** the tree or 2 to abort the tree walk.\n**\n** This routine also does error checking and name resolution for\n** function names.  The operator for aggregate functions is changed\n** to TK_AGG_FUNCTION.\n*/\nstatic int resolveExprStep(Walker *pWalker, Expr *pExpr){\n  NameContext *pNC;\n  Parse *pParse;\n\n  pNC = pWalker->u.pNC;\n  assert( pNC!=0 );\n  pParse = pNC->pParse;\n  assert( pParse==pWalker->pParse );\n\n#ifndef NDEBUG\n  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){\n    SrcList *pSrcList = pNC->pSrcList;\n    int i;\n    for(i=0; i<pNC->pSrcList->nSrc; i++){\n      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);\n    }\n  }\n#endif\n  switch( pExpr->op ){\n\n#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)\n    /* The special operator TK_ROW means use the rowid for the first\n    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY\n    ** clause processing on UPDATE and DELETE statements.\n    */\n    case TK_ROW: {\n      SrcList *pSrcList = pNC->pSrcList;\n      struct SrcList_item *pItem;\n      assert( pSrcList && pSrcList->nSrc==1 );\n      pItem = pSrcList->a;\n      assert( HasRowid(pItem->pTab) && pItem->pTab->pSelect==0 );\n      pExpr->op = TK_COLUMN;\n      pExpr->y.pTab = pItem->pTab;\n      pExpr->iTable = pItem->iCursor;\n      pExpr->iColumn = -1;\n      pExpr->affExpr = SQLITE_AFF_INTEGER;\n      break;\n    }\n#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)\n          && !defined(SQLITE_OMIT_SUBQUERY) */\n\n    /* A column name:                    ID\n    ** Or table name and column name:    ID.ID\n    ** Or a database, table and column:  ID.ID.ID\n    **\n    ** The TK_ID and TK_OUT cases are combined so that there will only\n    ** be one call to lookupName().  Then the compiler will in-line \n    ** lookupName() for a size reduction and performance increase.\n    */\n    case TK_ID:\n    case TK_DOT: {\n      const char *zColumn;\n      const char *zTable;\n      const char *zDb;\n      Expr *pRight;\n\n      if( pExpr->op==TK_ID ){\n        zDb = 0;\n        zTable = 0;\n        zColumn = pExpr->u.zToken;\n      }else{\n        Expr *pLeft = pExpr->pLeft;\n        testcase( pNC->ncFlags & NC_IdxExpr );\n        testcase( pNC->ncFlags & NC_GenCol );\n        sqlite3ResolveNotValid(pParse, pNC, \"the \\\".\\\" operator\",\n                               NC_IdxExpr|NC_GenCol, 0);\n        pRight = pExpr->pRight;\n        if( pRight->op==TK_ID ){\n          zDb = 0;\n        }else{\n          assert( pRight->op==TK_DOT );\n          zDb = pLeft->u.zToken;\n          pLeft = pRight->pLeft;\n          pRight = pRight->pRight;\n        }\n        zTable = pLeft->u.zToken;\n        zColumn = pRight->u.zToken;\n        if( IN_RENAME_OBJECT ){\n          sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);\n          sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);\n        }\n      }\n      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);\n    }\n\n    /* Resolve function names\n    */\n    case TK_FUNCTION: {\n      ExprList *pList = pExpr->x.pList;    /* The argument list */\n      int n = pList ? pList->nExpr : 0;    /* Number of arguments */\n      int no_such_func = 0;       /* True if no such function exists */\n      int wrong_num_args = 0;     /* True if wrong number of arguments */\n      int is_agg = 0;             /* True if is an aggregate function */\n      int nId;                    /* Number of characters in function name */\n      const char *zId;            /* The function name. */\n      FuncDef *pDef;              /* Information about the function */\n      u8 enc = ENC(pParse->db);   /* The database encoding */\n      int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin));\n#ifndef SQLITE_OMIT_WINDOWFUNC\n      Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0);\n#endif\n      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );\n      zId = pExpr->u.zToken;\n      nId = sqlite3Strlen30(zId);\n      pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);\n      if( pDef==0 ){\n        pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);\n        if( pDef==0 ){\n          no_such_func = 1;\n        }else{\n          wrong_num_args = 1;\n        }\n      }else{\n        is_agg = pDef->xFinalize!=0;\n        if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){\n          ExprSetProperty(pExpr, EP_Unlikely);\n          if( n==2 ){\n            pExpr->iTable = exprProbability(pList->a[1].pExpr);\n            if( pExpr->iTable<0 ){\n              sqlite3ErrorMsg(pParse,\n                \"second argument to likelihood() must be a \"\n                \"constant between 0.0 and 1.0\");\n              pNC->nErr++;\n            }\n          }else{\n            /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is\n            ** equivalent to likelihood(X, 0.0625).\n            ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is\n            ** short-hand for likelihood(X,0.0625).\n            ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand\n            ** for likelihood(X,0.9375).\n            ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent\n            ** to likelihood(X,0.9375). */\n            /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */\n            pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;\n          }             \n        }\n#ifndef SQLITE_OMIT_AUTHORIZATION\n        {\n          int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);\n          if( auth!=SQLITE_OK ){\n            if( auth==SQLITE_DENY ){\n              sqlite3ErrorMsg(pParse, \"not authorized to use function: %s\",\n                                      pDef->zName);\n              pNC->nErr++;\n            }\n            pExpr->op = TK_NULL;\n            return WRC_Prune;\n          }\n        }\n#endif\n        if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){\n          /* For the purposes of the EP_ConstFunc flag, date and time\n          ** functions and other functions that change slowly are considered\n          ** constant because they are constant for the duration of one query.\n          ** This allows them to be factored out of inner loops. */\n          ExprSetProperty(pExpr,EP_ConstFunc);\n        }\n        if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){\n          /* Clearly non-deterministic functions like random(), but also\n          ** date/time functions that use 'now', and other functions like\n          ** sqlite_version() that might change over time cannot be used\n          ** in an index or generated column.  Curiously, they can be used\n          ** in a CHECK constraint.  SQLServer, MySQL, and PostgreSQL all\n          ** all this. */\n          sqlite3ResolveNotValid(pParse, pNC, \"non-deterministic functions\",\n                                 NC_IdxExpr|NC_PartIdx|NC_GenCol, 0);\n        }else{\n          assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */\n          pExpr->op2 = pNC->ncFlags & NC_SelfRef;\n          if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL);\n        }\n        if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0\n         && pParse->nested==0\n         && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0\n        ){\n          /* Internal-use-only functions are disallowed unless the\n          ** SQL is being compiled using sqlite3NestedParse() or\n          ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be\n          ** used to activate internal functionsn for testing purposes */\n          no_such_func = 1;\n          pDef = 0;\n        }else\n        if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0\n         && !IN_RENAME_OBJECT\n        ){\n          sqlite3ExprFunctionUsable(pParse, pExpr, pDef);\n        }\n      }\n\n      if( 0==IN_RENAME_OBJECT ){\n#ifndef SQLITE_OMIT_WINDOWFUNC\n        assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)\n          || (pDef->xValue==0 && pDef->xInverse==0)\n          || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)\n        );\n        if( pDef && pDef->xValue==0 && pWin ){\n          sqlite3ErrorMsg(pParse, \n              \"%.*s() may not be used as a window function\", nId, zId\n          );\n          pNC->nErr++;\n        }else if( \n              (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)\n           || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin)\n           || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0)\n        ){\n          const char *zType;\n          if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){\n            zType = \"window\";\n          }else{\n            zType = \"aggregate\";\n          }\n          sqlite3ErrorMsg(pParse, \"misuse of %s function %.*s()\",zType,nId,zId);\n          pNC->nErr++;\n          is_agg = 0;\n        }\n#else\n        if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){\n          sqlite3ErrorMsg(pParse,\"misuse of aggregate function %.*s()\",nId,zId);\n          pNC->nErr++;\n          is_agg = 0;\n        }\n#endif\n        else if( no_such_func && pParse->db->init.busy==0\n#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION\n                  && pParse->explain==0\n#endif\n        ){\n          sqlite3ErrorMsg(pParse, \"no such function: %.*s\", nId, zId);\n          pNC->nErr++;\n        }else if( wrong_num_args ){\n          sqlite3ErrorMsg(pParse,\"wrong number of arguments to function %.*s()\",\n               nId, zId);\n          pNC->nErr++;\n        }\n#ifndef SQLITE_OMIT_WINDOWFUNC\n        else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){\n          sqlite3ErrorMsg(pParse, \n              \"FILTER may not be used with non-aggregate %.*s()\", \n              nId, zId\n          );\n          pNC->nErr++;\n        }\n#endif\n        if( is_agg ){\n          /* Window functions may not be arguments of aggregate functions.\n          ** Or arguments of other window functions. But aggregate functions\n          ** may be arguments for window functions.  */\n#ifndef SQLITE_OMIT_WINDOWFUNC\n          pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0));\n#else\n          pNC->ncFlags &= ~NC_AllowAgg;\n#endif\n        }\n      }\n#ifndef SQLITE_OMIT_WINDOWFUNC\n      else if( ExprHasProperty(pExpr, EP_WinFunc) ){\n        is_agg = 1;\n      }\n#endif\n      sqlite3WalkExprList(pWalker, pList);\n      if( is_agg ){\n#ifndef SQLITE_OMIT_WINDOWFUNC\n        if( pWin ){\n          Select *pSel = pNC->pWinSelect;\n          assert( pWin==pExpr->y.pWin );\n          if( IN_RENAME_OBJECT==0 ){\n            sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef);\n          }\n          sqlite3WalkExprList(pWalker, pWin->pPartition);\n          sqlite3WalkExprList(pWalker, pWin->pOrderBy);\n          sqlite3WalkExpr(pWalker, pWin->pFilter);\n          sqlite3WindowLink(pSel, pWin);\n          pNC->ncFlags |= NC_HasWin;\n        }else\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n        {\n          NameContext *pNC2 = pNC;\n          pExpr->op = TK_AGG_FUNCTION;\n          pExpr->op2 = 0;\n#ifndef SQLITE_OMIT_WINDOWFUNC\n          if( ExprHasProperty(pExpr, EP_WinFunc) ){\n            sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);\n          }\n#endif\n          while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){\n            pExpr->op2++;\n            pNC2 = pNC2->pNext;\n          }\n          assert( pDef!=0 || IN_RENAME_OBJECT );\n          if( pNC2 && pDef ){\n            assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );\n            testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );\n            pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);\n\n          }\n        }\n        pNC->ncFlags |= savedAllowFlags;\n      }\n      /* FIX ME:  Compute pExpr->affinity based on the expected return\n      ** type of the function \n      */\n      return WRC_Prune;\n    }\n#ifndef SQLITE_OMIT_SUBQUERY\n    case TK_SELECT:\n    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );\n#endif\n    case TK_IN: {\n      testcase( pExpr->op==TK_IN );\n      if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n        int nRef = pNC->nRef;\n        testcase( pNC->ncFlags & NC_IsCheck );\n        testcase( pNC->ncFlags & NC_PartIdx );\n        testcase( pNC->ncFlags & NC_IdxExpr );\n        testcase( pNC->ncFlags & NC_GenCol );\n        sqlite3ResolveNotValid(pParse, pNC, \"subqueries\",\n                 NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr);\n        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);\n        assert( pNC->nRef>=nRef );\n        if( nRef!=pNC->nRef ){\n          ExprSetProperty(pExpr, EP_VarSelect);\n          pNC->ncFlags |= NC_VarSelect;\n        }\n      }\n      break;\n    }\n    case TK_VARIABLE: {\n      testcase( pNC->ncFlags & NC_IsCheck );\n      testcase( pNC->ncFlags & NC_PartIdx );\n      testcase( pNC->ncFlags & NC_IdxExpr );\n      testcase( pNC->ncFlags & NC_GenCol );\n      sqlite3ResolveNotValid(pParse, pNC, \"parameters\",\n               NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr);\n      break;\n    }\n    case TK_IS:\n    case TK_ISNOT: {\n      Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);\n      assert( !ExprHasProperty(pExpr, EP_Reduced) );\n      /* Handle special cases of \"x IS TRUE\", \"x IS FALSE\", \"x IS NOT TRUE\",\n      ** and \"x IS NOT FALSE\". */\n      if( pRight && pRight->op==TK_ID ){\n        int rc = resolveExprStep(pWalker, pRight);\n        if( rc==WRC_Abort ) return WRC_Abort;\n        if( pRight->op==TK_TRUEFALSE ){\n          pExpr->op2 = pExpr->op;\n          pExpr->op = TK_TRUTH;\n          return WRC_Continue;\n        }\n      }\n      /* Fall thru */\n    }\n    case TK_BETWEEN:\n    case TK_EQ:\n    case TK_NE:\n    case TK_LT:\n    case TK_LE:\n    case TK_GT:\n    case TK_GE: {\n      int nLeft, nRight;\n      if( pParse->db->mallocFailed ) break;\n      assert( pExpr->pLeft!=0 );\n      nLeft = sqlite3ExprVectorSize(pExpr->pLeft);\n      if( pExpr->op==TK_BETWEEN ){\n        nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);\n        if( nRight==nLeft ){\n          nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);\n        }\n      }else{\n        assert( pExpr->pRight!=0 );\n        nRight = sqlite3ExprVectorSize(pExpr->pRight);\n      }\n      if( nLeft!=nRight ){\n        testcase( pExpr->op==TK_EQ );\n        testcase( pExpr->op==TK_NE );\n        testcase( pExpr->op==TK_LT );\n        testcase( pExpr->op==TK_LE );\n        testcase( pExpr->op==TK_GT );\n        testcase( pExpr->op==TK_GE );\n        testcase( pExpr->op==TK_IS );\n        testcase( pExpr->op==TK_ISNOT );\n        testcase( pExpr->op==TK_BETWEEN );\n        sqlite3ErrorMsg(pParse, \"row value misused\");\n      }\n      break; \n    }\n  }\n  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;\n}\n\n/*\n** pEList is a list of expressions which are really the result set of the\n** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.\n** This routine checks to see if pE is a simple identifier which corresponds\n** to the AS-name of one of the terms of the expression list.  If it is,\n** this routine return an integer between 1 and N where N is the number of\n** elements in pEList, corresponding to the matching entry.  If there is\n** no match, or if pE is not a simple identifier, then this routine\n** return 0.\n**\n** pEList has been resolved.  pE has not.\n*/\nstatic int resolveAsName(\n  Parse *pParse,     /* Parsing context for error messages */\n  ExprList *pEList,  /* List of expressions to scan */\n  Expr *pE           /* Expression we are trying to match */\n){\n  int i;             /* Loop counter */\n\n  UNUSED_PARAMETER(pParse);\n\n  if( pE->op==TK_ID ){\n    char *zCol = pE->u.zToken;\n    for(i=0; i<pEList->nExpr; i++){\n      if( pEList->a[i].eEName==ENAME_NAME\n       && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0\n      ){\n        return i+1;\n      }\n    }\n  }\n  return 0;\n}\n\n/*\n** pE is a pointer to an expression which is a single term in the\n** ORDER BY of a compound SELECT.  The expression has not been\n** name resolved.\n**\n** At the point this routine is called, we already know that the\n** ORDER BY term is not an integer index into the result set.  That\n** case is handled by the calling routine.\n**\n** Attempt to match pE against result set columns in the left-most\n** SELECT statement.  Return the index i of the matching column,\n** as an indication to the caller that it should sort by the i-th column.\n** The left-most column is 1.  In other words, the value returned is the\n** same integer value that would be used in the SQL statement to indicate\n** the column.\n**\n** If there is no match, return 0.  Return -1 if an error occurs.\n*/\nstatic int resolveOrderByTermToExprList(\n  Parse *pParse,     /* Parsing context for error messages */\n  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */\n  Expr *pE           /* The specific ORDER BY term */\n){\n  int i;             /* Loop counter */\n  ExprList *pEList;  /* The columns of the result set */\n  NameContext nc;    /* Name context for resolving pE */\n  sqlite3 *db;       /* Database connection */\n  int rc;            /* Return code from subprocedures */\n  u8 savedSuppErr;   /* Saved value of db->suppressErr */\n\n  assert( sqlite3ExprIsInteger(pE, &i)==0 );\n  pEList = pSelect->pEList;\n\n  /* Resolve all names in the ORDER BY term expression\n  */\n  memset(&nc, 0, sizeof(nc));\n  nc.pParse = pParse;\n  nc.pSrcList = pSelect->pSrc;\n  nc.uNC.pEList = pEList;\n  nc.ncFlags = NC_AllowAgg|NC_UEList;\n  nc.nErr = 0;\n  db = pParse->db;\n  savedSuppErr = db->suppressErr;\n  if( IN_RENAME_OBJECT==0 ) db->suppressErr = 1;\n  rc = sqlite3ResolveExprNames(&nc, pE);\n  db->suppressErr = savedSuppErr;\n  if( rc ) return 0;\n\n  /* Try to match the ORDER BY expression against an expression\n  ** in the result set.  Return an 1-based index of the matching\n  ** result-set entry.\n  */\n  for(i=0; i<pEList->nExpr; i++){\n    if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){\n      return i+1;\n    }\n  }\n\n  /* If no match, return 0. */\n  return 0;\n}\n\n/*\n** Generate an ORDER BY or GROUP BY term out-of-range error.\n*/\nstatic void resolveOutOfRangeError(\n  Parse *pParse,         /* The error context into which to write the error */\n  const char *zType,     /* \"ORDER\" or \"GROUP\" */\n  int i,                 /* The index (1-based) of the term out of range */\n  int mx                 /* Largest permissible value of i */\n){\n  sqlite3ErrorMsg(pParse, \n    \"%r %s BY term out of range - should be \"\n    \"between 1 and %d\", i, zType, mx);\n}\n\n/*\n** Analyze the ORDER BY clause in a compound SELECT statement.   Modify\n** each term of the ORDER BY clause is a constant integer between 1\n** and N where N is the number of columns in the compound SELECT.\n**\n** ORDER BY terms that are already an integer between 1 and N are\n** unmodified.  ORDER BY terms that are integers outside the range of\n** 1 through N generate an error.  ORDER BY terms that are expressions\n** are matched against result set expressions of compound SELECT\n** beginning with the left-most SELECT and working toward the right.\n** At the first match, the ORDER BY expression is transformed into\n** the integer column number.\n**\n** Return the number of errors seen.\n*/\nstatic int resolveCompoundOrderBy(\n  Parse *pParse,        /* Parsing context.  Leave error messages here */\n  Select *pSelect       /* The SELECT statement containing the ORDER BY */\n){\n  int i;\n  ExprList *pOrderBy;\n  ExprList *pEList;\n  sqlite3 *db;\n  int moreToDo = 1;\n\n  pOrderBy = pSelect->pOrderBy;\n  if( pOrderBy==0 ) return 0;\n  db = pParse->db;\n  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){\n    sqlite3ErrorMsg(pParse, \"too many terms in ORDER BY clause\");\n    return 1;\n  }\n  for(i=0; i<pOrderBy->nExpr; i++){\n    pOrderBy->a[i].done = 0;\n  }\n  pSelect->pNext = 0;\n  while( pSelect->pPrior ){\n    pSelect->pPrior->pNext = pSelect;\n    pSelect = pSelect->pPrior;\n  }\n  while( pSelect && moreToDo ){\n    struct ExprList_item *pItem;\n    moreToDo = 0;\n    pEList = pSelect->pEList;\n    assert( pEList!=0 );\n    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){\n      int iCol = -1;\n      Expr *pE, *pDup;\n      if( pItem->done ) continue;\n      pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);\n      if( sqlite3ExprIsInteger(pE, &iCol) ){\n        if( iCol<=0 || iCol>pEList->nExpr ){\n          resolveOutOfRangeError(pParse, \"ORDER\", i+1, pEList->nExpr);\n          return 1;\n        }\n      }else{\n        iCol = resolveAsName(pParse, pEList, pE);\n        if( iCol==0 ){\n          /* Now test if expression pE matches one of the values returned\n          ** by pSelect. In the usual case this is done by duplicating the \n          ** expression, resolving any symbols in it, and then comparing\n          ** it against each expression returned by the SELECT statement.\n          ** Once the comparisons are finished, the duplicate expression\n          ** is deleted.\n          **\n          ** Or, if this is running as part of an ALTER TABLE operation,\n          ** resolve the symbols in the actual expression, not a duplicate.\n          ** And, if one of the comparisons is successful, leave the expression\n          ** as is instead of transforming it to an integer as in the usual\n          ** case. This allows the code in alter.c to modify column\n          ** refererences within the ORDER BY expression as required.  */\n          if( IN_RENAME_OBJECT ){\n            pDup = pE;\n          }else{\n            pDup = sqlite3ExprDup(db, pE, 0);\n          }\n          if( !db->mallocFailed ){\n            assert(pDup);\n            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);\n          }\n          if( !IN_RENAME_OBJECT ){\n            sqlite3ExprDelete(db, pDup);\n          }\n        }\n      }\n      if( iCol>0 ){\n        /* Convert the ORDER BY term into an integer column number iCol,\n        ** taking care to preserve the COLLATE clause if it exists */\n        if( !IN_RENAME_OBJECT ){\n          Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);\n          if( pNew==0 ) return 1;\n          pNew->flags |= EP_IntValue;\n          pNew->u.iValue = iCol;\n          if( pItem->pExpr==pE ){\n            pItem->pExpr = pNew;\n          }else{\n            Expr *pParent = pItem->pExpr;\n            assert( pParent->op==TK_COLLATE );\n            while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;\n            assert( pParent->pLeft==pE );\n            pParent->pLeft = pNew;\n          }\n          sqlite3ExprDelete(db, pE);\n          pItem->u.x.iOrderByCol = (u16)iCol;\n        }\n        pItem->done = 1;\n      }else{\n        moreToDo = 1;\n      }\n    }\n    pSelect = pSelect->pNext;\n  }\n  for(i=0; i<pOrderBy->nExpr; i++){\n    if( pOrderBy->a[i].done==0 ){\n      sqlite3ErrorMsg(pParse, \"%r ORDER BY term does not match any \"\n            \"column in the result set\", i+1);\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/*\n** Check every term in the ORDER BY or GROUP BY clause pOrderBy of\n** the SELECT statement pSelect.  If any term is reference to a\n** result set expression (as determined by the ExprList.a.u.x.iOrderByCol\n** field) then convert that term into a copy of the corresponding result set\n** column.\n**\n** If any errors are detected, add an error message to pParse and\n** return non-zero.  Return zero if no errors are seen.\n*/\nSQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(\n  Parse *pParse,        /* Parsing context.  Leave error messages here */\n  Select *pSelect,      /* The SELECT statement containing the clause */\n  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */\n  const char *zType     /* \"ORDER\" or \"GROUP\" */\n){\n  int i;\n  sqlite3 *db = pParse->db;\n  ExprList *pEList;\n  struct ExprList_item *pItem;\n\n  if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0;\n  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){\n    sqlite3ErrorMsg(pParse, \"too many terms in %s BY clause\", zType);\n    return 1;\n  }\n  pEList = pSelect->pEList;\n  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */\n  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){\n    if( pItem->u.x.iOrderByCol ){\n      if( pItem->u.x.iOrderByCol>pEList->nExpr ){\n        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);\n        return 1;\n      }\n      resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,\n                   zType,0);\n    }\n  }\n  return 0;\n}\n\n#ifndef SQLITE_OMIT_WINDOWFUNC\n/*\n** Walker callback for windowRemoveExprFromSelect().\n*/\nstatic int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){\n  UNUSED_PARAMETER(pWalker);\n  if( ExprHasProperty(pExpr, EP_WinFunc) ){\n    Window *pWin = pExpr->y.pWin;\n    sqlite3WindowUnlinkFromSelect(pWin);\n  }\n  return WRC_Continue;\n}\n\n/*\n** Remove any Window objects owned by the expression pExpr from the\n** Select.pWin list of Select object pSelect.\n*/\nstatic void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){\n  if( pSelect->pWin ){\n    Walker sWalker;\n    memset(&sWalker, 0, sizeof(Walker));\n    sWalker.xExprCallback = resolveRemoveWindowsCb;\n    sWalker.u.pSelect = pSelect;\n    sqlite3WalkExpr(&sWalker, pExpr);\n  }\n}\n#else\n# define windowRemoveExprFromSelect(a, b)\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n\n/*\n** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.\n** The Name context of the SELECT statement is pNC.  zType is either\n** \"ORDER\" or \"GROUP\" depending on which type of clause pOrderBy is.\n**\n** This routine resolves each term of the clause into an expression.\n** If the order-by term is an integer I between 1 and N (where N is the\n** number of columns in the result set of the SELECT) then the expression\n** in the resolution is a copy of the I-th result-set expression.  If\n** the order-by term is an identifier that corresponds to the AS-name of\n** a result-set expression, then the term resolves to a copy of the\n** result-set expression.  Otherwise, the expression is resolved in\n** the usual way - using sqlite3ResolveExprNames().\n**\n** This routine returns the number of errors.  If errors occur, then\n** an appropriate error message might be left in pParse.  (OOM errors\n** excepted.)\n*/\nstatic int resolveOrderGroupBy(\n  NameContext *pNC,     /* The name context of the SELECT statement */\n  Select *pSelect,      /* The SELECT statement holding pOrderBy */\n  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */\n  const char *zType     /* Either \"ORDER\" or \"GROUP\", as appropriate */\n){\n  int i, j;                      /* Loop counters */\n  int iCol;                      /* Column number */\n  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */\n  Parse *pParse;                 /* Parsing context */\n  int nResult;                   /* Number of terms in the result set */\n\n  if( pOrderBy==0 ) return 0;\n  nResult = pSelect->pEList->nExpr;\n  pParse = pNC->pParse;\n  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){\n    Expr *pE = pItem->pExpr;\n    Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);\n    if( zType[0]!='G' ){\n      iCol = resolveAsName(pParse, pSelect->pEList, pE2);\n      if( iCol>0 ){\n        /* If an AS-name match is found, mark this ORDER BY column as being\n        ** a copy of the iCol-th result-set column.  The subsequent call to\n        ** sqlite3ResolveOrderGroupBy() will convert the expression to a\n        ** copy of the iCol-th result-set expression. */\n        pItem->u.x.iOrderByCol = (u16)iCol;\n        continue;\n      }\n    }\n    if( sqlite3ExprIsInteger(pE2, &iCol) ){\n      /* The ORDER BY term is an integer constant.  Again, set the column\n      ** number so that sqlite3ResolveOrderGroupBy() will convert the\n      ** order-by term to a copy of the result-set expression */\n      if( iCol<1 || iCol>0xffff ){\n        resolveOutOfRangeError(pParse, zType, i+1, nResult);\n        return 1;\n      }\n      pItem->u.x.iOrderByCol = (u16)iCol;\n      continue;\n    }\n\n    /* Otherwise, treat the ORDER BY term as an ordinary expression */\n    pItem->u.x.iOrderByCol = 0;\n    if( sqlite3ResolveExprNames(pNC, pE) ){\n      return 1;\n    }\n    for(j=0; j<pSelect->pEList->nExpr; j++){\n      if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){\n        /* Since this expresion is being changed into a reference\n        ** to an identical expression in the result set, remove all Window\n        ** objects belonging to the expression from the Select.pWin list. */\n        windowRemoveExprFromSelect(pSelect, pE);\n        pItem->u.x.iOrderByCol = j+1;\n      }\n    }\n  }\n  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);\n}\n\n/*\n** Resolve names in the SELECT statement p and all of its descendants.\n*/\nstatic int resolveSelectStep(Walker *pWalker, Select *p){\n  NameContext *pOuterNC;  /* Context that contains this SELECT */\n  NameContext sNC;        /* Name context of this SELECT */\n  int isCompound;         /* True if p is a compound select */\n  int nCompound;          /* Number of compound terms processed so far */\n  Parse *pParse;          /* Parsing context */\n  int i;                  /* Loop counter */\n  ExprList *pGroupBy;     /* The GROUP BY clause */\n  Select *pLeftmost;      /* Left-most of SELECT of a compound */\n  sqlite3 *db;            /* Database connection */\n  \n\n  assert( p!=0 );\n  if( p->selFlags & SF_Resolved ){\n    return WRC_Prune;\n  }\n  pOuterNC = pWalker->u.pNC;\n  pParse = pWalker->pParse;\n  db = pParse->db;\n\n  /* Normally sqlite3SelectExpand() will be called first and will have\n  ** already expanded this SELECT.  However, if this is a subquery within\n  ** an expression, sqlite3ResolveExprNames() will be called without a\n  ** prior call to sqlite3SelectExpand().  When that happens, let\n  ** sqlite3SelectPrep() do all of the processing for this SELECT.\n  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and\n  ** this routine in the correct order.\n  */\n  if( (p->selFlags & SF_Expanded)==0 ){\n    sqlite3SelectPrep(pParse, p, pOuterNC);\n    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;\n  }\n\n  isCompound = p->pPrior!=0;\n  nCompound = 0;\n  pLeftmost = p;\n  while( p ){\n    assert( (p->selFlags & SF_Expanded)!=0 );\n    assert( (p->selFlags & SF_Resolved)==0 );\n    p->selFlags |= SF_Resolved;\n\n    /* Resolve the expressions in the LIMIT and OFFSET clauses. These\n    ** are not allowed to refer to any names, so pass an empty NameContext.\n    */\n    memset(&sNC, 0, sizeof(sNC));\n    sNC.pParse = pParse;\n    sNC.pWinSelect = p;\n    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){\n      return WRC_Abort;\n    }\n\n    /* If the SF_Converted flags is set, then this Select object was\n    ** was created by the convertCompoundSelectToSubquery() function.\n    ** In this case the ORDER BY clause (p->pOrderBy) should be resolved\n    ** as if it were part of the sub-query, not the parent. This block\n    ** moves the pOrderBy down to the sub-query. It will be moved back\n    ** after the names have been resolved.  */\n    if( p->selFlags & SF_Converted ){\n      Select *pSub = p->pSrc->a[0].pSelect;\n      assert( p->pSrc->nSrc==1 && p->pOrderBy );\n      assert( pSub->pPrior && pSub->pOrderBy==0 );\n      pSub->pOrderBy = p->pOrderBy;\n      p->pOrderBy = 0;\n    }\n  \n    /* Recursively resolve names in all subqueries\n    */\n    for(i=0; i<p->pSrc->nSrc; i++){\n      struct SrcList_item *pItem = &p->pSrc->a[i];\n      if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){\n        NameContext *pNC;         /* Used to iterate name contexts */\n        int nRef = 0;             /* Refcount for pOuterNC and outer contexts */\n        const char *zSavedContext = pParse->zAuthContext;\n\n        /* Count the total number of references to pOuterNC and all of its\n        ** parent contexts. After resolving references to expressions in\n        ** pItem->pSelect, check if this value has changed. If so, then\n        ** SELECT statement pItem->pSelect must be correlated. Set the\n        ** pItem->fg.isCorrelated flag if this is the case. */\n        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;\n\n        if( pItem->zName ) pParse->zAuthContext = pItem->zName;\n        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);\n        pParse->zAuthContext = zSavedContext;\n        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;\n\n        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;\n        assert( pItem->fg.isCorrelated==0 && nRef<=0 );\n        pItem->fg.isCorrelated = (nRef!=0);\n      }\n    }\n  \n    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to\n    ** resolve the result-set expression list.\n    */\n    sNC.ncFlags = NC_AllowAgg|NC_AllowWin;\n    sNC.pSrcList = p->pSrc;\n    sNC.pNext = pOuterNC;\n  \n    /* Resolve names in the result set. */\n    if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;\n    sNC.ncFlags &= ~NC_AllowWin;\n  \n    /* If there are no aggregate functions in the result-set, and no GROUP BY \n    ** expression, do not allow aggregates in any of the other expressions.\n    */\n    assert( (p->selFlags & SF_Aggregate)==0 );\n    pGroupBy = p->pGroupBy;\n    if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){\n      assert( NC_MinMaxAgg==SF_MinMaxAgg );\n      p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);\n    }else{\n      sNC.ncFlags &= ~NC_AllowAgg;\n    }\n  \n    /* If a HAVING clause is present, then there must be a GROUP BY clause.\n    */\n    if( p->pHaving && !pGroupBy ){\n      sqlite3ErrorMsg(pParse, \"a GROUP BY clause is required before HAVING\");\n      return WRC_Abort;\n    }\n  \n    /* Add the output column list to the name-context before parsing the\n    ** other expressions in the SELECT statement. This is so that\n    ** expressions in the WHERE clause (etc.) can refer to expressions by\n    ** aliases in the result set.\n    **\n    ** Minor point: If this is the case, then the expression will be\n    ** re-evaluated for each reference to it.\n    */\n    assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert))==0 );\n    sNC.uNC.pEList = p->pEList;\n    sNC.ncFlags |= NC_UEList;\n    if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;\n    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;\n\n    /* Resolve names in table-valued-function arguments */\n    for(i=0; i<p->pSrc->nSrc; i++){\n      struct SrcList_item *pItem = &p->pSrc->a[i];\n      if( pItem->fg.isTabFunc\n       && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg) \n      ){\n        return WRC_Abort;\n      }\n    }\n\n    /* The ORDER BY and GROUP BY clauses may not refer to terms in\n    ** outer queries \n    */\n    sNC.pNext = 0;\n    sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;\n\n    /* If this is a converted compound query, move the ORDER BY clause from \n    ** the sub-query back to the parent query. At this point each term\n    ** within the ORDER BY clause has been transformed to an integer value.\n    ** These integers will be replaced by copies of the corresponding result\n    ** set expressions by the call to resolveOrderGroupBy() below.  */\n    if( p->selFlags & SF_Converted ){\n      Select *pSub = p->pSrc->a[0].pSelect;\n      p->pOrderBy = pSub->pOrderBy;\n      pSub->pOrderBy = 0;\n    }\n\n    /* Process the ORDER BY clause for singleton SELECT statements.\n    ** The ORDER BY clause for compounds SELECT statements is handled\n    ** below, after all of the result-sets for all of the elements of\n    ** the compound have been resolved.\n    **\n    ** If there is an ORDER BY clause on a term of a compound-select other\n    ** than the right-most term, then that is a syntax error.  But the error\n    ** is not detected until much later, and so we need to go ahead and\n    ** resolve those symbols on the incorrect ORDER BY for consistency.\n    */\n    if( isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */\n     && resolveOrderGroupBy(&sNC, p, p->pOrderBy, \"ORDER\")\n    ){\n      return WRC_Abort;\n    }\n    if( db->mallocFailed ){\n      return WRC_Abort;\n    }\n    sNC.ncFlags &= ~NC_AllowWin;\n  \n    /* Resolve the GROUP BY clause.  At the same time, make sure \n    ** the GROUP BY clause does not contain aggregate functions.\n    */\n    if( pGroupBy ){\n      struct ExprList_item *pItem;\n    \n      if( resolveOrderGroupBy(&sNC, p, pGroupBy, \"GROUP\") || db->mallocFailed ){\n        return WRC_Abort;\n      }\n      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){\n        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){\n          sqlite3ErrorMsg(pParse, \"aggregate functions are not allowed in \"\n              \"the GROUP BY clause\");\n          return WRC_Abort;\n        }\n      }\n    }\n\n#ifndef SQLITE_OMIT_WINDOWFUNC\n    if( IN_RENAME_OBJECT ){\n      Window *pWin;\n      for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){\n        if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)\n         || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)\n        ){\n          return WRC_Abort;\n        }\n      }\n    }\n#endif\n\n    /* If this is part of a compound SELECT, check that it has the right\n    ** number of expressions in the select list. */\n    if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){\n      sqlite3SelectWrongNumTermsError(pParse, p->pNext);\n      return WRC_Abort;\n    }\n\n    /* Advance to the next term of the compound\n    */\n    p = p->pPrior;\n    nCompound++;\n  }\n\n  /* Resolve the ORDER BY on a compound SELECT after all terms of\n  ** the compound have been resolved.\n  */\n  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){\n    return WRC_Abort;\n  }\n\n  return WRC_Prune;\n}\n\n/*\n** This routine walks an expression tree and resolves references to\n** table columns and result-set columns.  At the same time, do error\n** checking on function usage and set a flag if any aggregate functions\n** are seen.\n**\n** To resolve table columns references we look for nodes (or subtrees) of the \n** form X.Y.Z or Y.Z or just Z where\n**\n**      X:   The name of a database.  Ex:  \"main\" or \"temp\" or\n**           the symbolic name assigned to an ATTACH-ed database.\n**\n**      Y:   The name of a table in a FROM clause.  Or in a trigger\n**           one of the special names \"old\" or \"new\".\n**\n**      Z:   The name of a column in table Y.\n**\n** The node at the root of the subtree is modified as follows:\n**\n**    Expr.op        Changed to TK_COLUMN\n**    Expr.pTab      Points to the Table object for X.Y\n**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.\n**    Expr.iTable    The VDBE cursor number for X.Y\n**\n**\n** To resolve result-set references, look for expression nodes of the\n** form Z (with no X and Y prefix) where the Z matches the right-hand\n** size of an AS clause in the result-set of a SELECT.  The Z expression\n** is replaced by a copy of the left-hand side of the result-set expression.\n** Table-name and function resolution occurs on the substituted expression\n** tree.  For example, in:\n**\n**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;\n**\n** The \"x\" term of the order by is replaced by \"a+b\" to render:\n**\n**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;\n**\n** Function calls are checked to make sure that the function is \n** defined and that the correct number of arguments are specified.\n** If the function is an aggregate function, then the NC_HasAgg flag is\n** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.\n** If an expression contains aggregate functions then the EP_Agg\n** property on the expression is set.\n**\n** An error message is left in pParse if anything is amiss.  The number\n** if errors is returned.\n*/\nSQLITE_PRIVATE int sqlite3ResolveExprNames( \n  NameContext *pNC,       /* Namespace to resolve expressions in. */\n  Expr *pExpr             /* The expression to be analyzed. */\n){\n  int savedHasAgg;\n  Walker w;\n\n  if( pExpr==0 ) return SQLITE_OK;\n  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);\n  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);\n  w.pParse = pNC->pParse;\n  w.xExprCallback = resolveExprStep;\n  w.xSelectCallback = resolveSelectStep;\n  w.xSelectCallback2 = 0;\n  w.u.pNC = pNC;\n#if SQLITE_MAX_EXPR_DEPTH>0\n  w.pParse->nHeight += pExpr->nHeight;\n  if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){\n    return SQLITE_ERROR;\n  }\n#endif\n  sqlite3WalkExpr(&w, pExpr);\n#if SQLITE_MAX_EXPR_DEPTH>0\n  w.pParse->nHeight -= pExpr->nHeight;\n#endif\n  assert( EP_Agg==NC_HasAgg );\n  assert( EP_Win==NC_HasWin );\n  testcase( pNC->ncFlags & NC_HasAgg );\n  testcase( pNC->ncFlags & NC_HasWin );\n  ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );\n  pNC->ncFlags |= savedHasAgg;\n  return pNC->nErr>0 || w.pParse->nErr>0;\n}\n\n/*\n** Resolve all names for all expression in an expression list.  This is\n** just like sqlite3ResolveExprNames() except that it works for an expression\n** list rather than a single expression.\n*/\nSQLITE_PRIVATE int sqlite3ResolveExprListNames( \n  NameContext *pNC,       /* Namespace to resolve expressions in. */\n  ExprList *pList         /* The expression list to be analyzed. */\n){\n  int i;\n  int savedHasAgg = 0;\n  Walker w;\n  if( pList==0 ) return WRC_Continue;\n  w.pParse = pNC->pParse;\n  w.xExprCallback = resolveExprStep;\n  w.xSelectCallback = resolveSelectStep;\n  w.xSelectCallback2 = 0;\n  w.u.pNC = pNC;\n  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);\n  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);\n  for(i=0; i<pList->nExpr; i++){\n    Expr *pExpr = pList->a[i].pExpr;\n    if( pExpr==0 ) continue;\n#if SQLITE_MAX_EXPR_DEPTH>0\n    w.pParse->nHeight += pExpr->nHeight;\n    if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){\n      return WRC_Abort;\n    }\n#endif\n    sqlite3WalkExpr(&w, pExpr);\n#if SQLITE_MAX_EXPR_DEPTH>0\n    w.pParse->nHeight -= pExpr->nHeight;\n#endif\n    assert( EP_Agg==NC_HasAgg );\n    assert( EP_Win==NC_HasWin );\n    testcase( pNC->ncFlags & NC_HasAgg );\n    testcase( pNC->ncFlags & NC_HasWin );\n    if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin) ){\n      ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );\n      savedHasAgg |= pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);\n      pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);\n    }\n    if( pNC->nErr>0 || w.pParse->nErr>0 ) return WRC_Abort;\n  }\n  pNC->ncFlags |= savedHasAgg;\n  return WRC_Continue;\n}\n\n/*\n** Resolve all names in all expressions of a SELECT and in all\n** decendents of the SELECT, including compounds off of p->pPrior,\n** subqueries in expressions, and subqueries used as FROM clause\n** terms.\n**\n** See sqlite3ResolveExprNames() for a description of the kinds of\n** transformations that occur.\n**\n** All SELECT statements should have been expanded using\n** sqlite3SelectExpand() prior to invoking this routine.\n*/\nSQLITE_PRIVATE void sqlite3ResolveSelectNames(\n  Parse *pParse,         /* The parser context */\n  Select *p,             /* The SELECT statement being coded. */\n  NameContext *pOuterNC  /* Name context for parent SELECT statement */\n){\n  Walker w;\n\n  assert( p!=0 );\n  w.xExprCallback = resolveExprStep;\n  w.xSelectCallback = resolveSelectStep;\n  w.xSelectCallback2 = 0;\n  w.pParse = pParse;\n  w.u.pNC = pOuterNC;\n  sqlite3WalkSelect(&w, p);\n}\n\n/*\n** Resolve names in expressions that can only reference a single table\n** or which cannot reference any tables at all.  Examples:\n**\n**                                                    \"type\" flag\n**                                                    ------------\n**    (1)   CHECK constraints                         NC_IsCheck\n**    (2)   WHERE clauses on partial indices          NC_PartIdx\n**    (3)   Expressions in indexes on expressions     NC_IdxExpr\n**    (4)   Expression arguments to VACUUM INTO.      0\n**    (5)   GENERATED ALWAYS as expressions           NC_GenCol\n**\n** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN\n** nodes of the expression is set to -1 and the Expr.iColumn value is\n** set to the column number.  In case (4), TK_COLUMN nodes cause an error.\n**\n** Any errors cause an error message to be set in pParse.\n*/\nSQLITE_PRIVATE int sqlite3ResolveSelfReference(\n  Parse *pParse,   /* Parsing context */\n  Table *pTab,     /* The table being referenced, or NULL */\n  int type,        /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */\n  Expr *pExpr,     /* Expression to resolve.  May be NULL. */\n  ExprList *pList  /* Expression list to resolve.  May be NULL. */\n){\n  SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */\n  NameContext sNC;                /* Name context for pParse->pNewTable */\n  int rc;\n\n  assert( type==0 || pTab!=0 );\n  assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr\n          || type==NC_GenCol || pTab==0 );\n  memset(&sNC, 0, sizeof(sNC));\n  memset(&sSrc, 0, sizeof(sSrc));\n  if( pTab ){\n    sSrc.nSrc = 1;\n    sSrc.a[0].zName = pTab->zName;\n    sSrc.a[0].pTab = pTab;\n    sSrc.a[0].iCursor = -1;\n    if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){\n      /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP\n      ** schema elements */\n      type |= NC_FromDDL;\n    }\n  }\n  sNC.pParse = pParse;\n  sNC.pSrcList = &sSrc;\n  sNC.ncFlags = type | NC_IsDDL;\n  if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;\n  if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);\n  return rc;\n}\n\n/************** End of resolve.c *********************************************/\n/************** Begin file expr.c ********************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains routines used for analyzing expressions and\n** for generating VDBE code that evaluates expressions in SQLite.\n*/\n/* #include \"sqliteInt.h\" */\n\n/* Forward declarations */\nstatic void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);\nstatic int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);\n\n/*\n** Return the affinity character for a single column of a table.\n*/\nSQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){\n  assert( iCol<pTab->nCol );\n  return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;\n}\n\n/*\n** Return the 'affinity' of the expression pExpr if any.\n**\n** If pExpr is a column, a reference to a column via an 'AS' alias,\n** or a sub-select with a column as the return value, then the \n** affinity of that column is returned. Otherwise, 0x00 is returned,\n** indicating no affinity for the expression.\n**\n** i.e. the WHERE clause expressions in the following statements all\n** have an affinity:\n**\n** CREATE TABLE t1(a);\n** SELECT * FROM t1 WHERE a;\n** SELECT a AS b FROM t1 WHERE b;\n** SELECT * FROM t1 WHERE (select a from t1);\n*/\nSQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr){\n  int op;\n  while( ExprHasProperty(pExpr, EP_Skip) ){\n    assert( pExpr->op==TK_COLLATE || pExpr->op==TK_IF_NULL_ROW );\n    pExpr = pExpr->pLeft;\n    assert( pExpr!=0 );\n  }\n  op = pExpr->op;\n  if( op==TK_SELECT ){\n    assert( pExpr->flags&EP_xIsSelect );\n    if( ALWAYS(pExpr->x.pSelect)\n     && pExpr->x.pSelect->pEList\n     && ALWAYS(pExpr->x.pSelect->pEList->a[0].pExpr)\n    ){\n      return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);\n    }\n  }\n  if( op==TK_REGISTER ) op = pExpr->op2;\n#ifndef SQLITE_OMIT_CAST\n  if( op==TK_CAST ){\n    assert( !ExprHasProperty(pExpr, EP_IntValue) );\n    return sqlite3AffinityType(pExpr->u.zToken, 0);\n  }\n#endif\n  if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){\n    return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);\n  }\n  if( op==TK_SELECT_COLUMN ){\n    assert( pExpr->pLeft->flags&EP_xIsSelect );\n    return sqlite3ExprAffinity(\n        pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr\n    );\n  }\n  if( op==TK_VECTOR ){\n    return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);\n  }\n  return pExpr->affExpr;\n}\n\n/*\n** Set the collating sequence for expression pExpr to be the collating\n** sequence named by pToken.   Return a pointer to a new Expr node that\n** implements the COLLATE operator.\n**\n** If a memory allocation error occurs, that fact is recorded in pParse->db\n** and the pExpr parameter is returned unchanged.\n*/\nSQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(\n  Parse *pParse,           /* Parsing context */\n  Expr *pExpr,             /* Add the \"COLLATE\" clause to this expression */\n  const Token *pCollName,  /* Name of collating sequence */\n  int dequote              /* True to dequote pCollName */\n){\n  if( pCollName->n>0 ){\n    Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);\n    if( pNew ){\n      pNew->pLeft = pExpr;\n      pNew->flags |= EP_Collate|EP_Skip;\n      pExpr = pNew;\n    }\n  }\n  return pExpr;\n}\nSQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){\n  Token s;\n  assert( zC!=0 );\n  sqlite3TokenInit(&s, (char*)zC);\n  return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);\n}\n\n/*\n** Skip over any TK_COLLATE operators.\n*/\nSQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){\n  while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){\n    assert( pExpr->op==TK_COLLATE || pExpr->op==TK_IF_NULL_ROW );\n    pExpr = pExpr->pLeft;\n  }   \n  return pExpr;\n}\n\n/*\n** Skip over any TK_COLLATE operators and/or any unlikely()\n** or likelihood() or likely() functions at the root of an\n** expression.\n*/\nSQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){\n  while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){\n    if( ExprHasProperty(pExpr, EP_Unlikely) ){\n      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );\n      assert( pExpr->x.pList->nExpr>0 );\n      assert( pExpr->op==TK_FUNCTION );\n      pExpr = pExpr->x.pList->a[0].pExpr;\n    }else{\n      assert( pExpr->op==TK_COLLATE || pExpr->op==TK_IF_NULL_ROW );\n      pExpr = pExpr->pLeft;\n    }\n  }   \n  return pExpr;\n}\n\n/*\n** Return the collation sequence for the expression pExpr. If\n** there is no defined collating sequence, return NULL.\n**\n** See also: sqlite3ExprNNCollSeq()\n**\n** The sqlite3ExprNNCollSeq() works the same exact that it returns the\n** default collation if pExpr has no defined collation.\n**\n** The collating sequence might be determined by a COLLATE operator\n** or by the presence of a column with a defined collating sequence.\n** COLLATE operators take first precedence.  Left operands take\n** precedence over right operands.\n*/\nSQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){\n  sqlite3 *db = pParse->db;\n  CollSeq *pColl = 0;\n  const Expr *p = pExpr;\n  while( p ){\n    int op = p->op;\n    if( op==TK_REGISTER ) op = p->op2;\n    if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER)\n     && p->y.pTab!=0\n    ){\n      /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally\n      ** a TK_COLUMN but was previously evaluated and cached in a register */\n      int j = p->iColumn;\n      if( j>=0 ){\n        const char *zColl = p->y.pTab->aCol[j].zColl;\n        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);\n      }\n      break;\n    }\n    if( op==TK_CAST || op==TK_UPLUS ){\n      p = p->pLeft;\n      continue;\n    }\n    if( op==TK_VECTOR ){\n      p = p->x.pList->a[0].pExpr;\n      continue;\n    }\n    if( op==TK_COLLATE ){\n      pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);\n      break;\n    }\n    if( p->flags & EP_Collate ){\n      if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){\n        p = p->pLeft;\n      }else{\n        Expr *pNext  = p->pRight;\n        /* The Expr.x union is never used at the same time as Expr.pRight */\n        assert( p->x.pList==0 || p->pRight==0 );\n        if( p->x.pList!=0 \n         && !db->mallocFailed\n         && ALWAYS(!ExprHasProperty(p, EP_xIsSelect))\n        ){\n          int i;\n          for(i=0; i<p->x.pList->nExpr; i++){\n            if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){\n              pNext = p->x.pList->a[i].pExpr;\n              break;\n            }\n          }\n        }\n        p = pNext;\n      }\n    }else{\n      break;\n    }\n  }\n  if( sqlite3CheckCollSeq(pParse, pColl) ){ \n    pColl = 0;\n  }\n  return pColl;\n}\n\n/*\n** Return the collation sequence for the expression pExpr. If\n** there is no defined collating sequence, return a pointer to the\n** defautl collation sequence.\n**\n** See also: sqlite3ExprCollSeq()\n**\n** The sqlite3ExprCollSeq() routine works the same except that it\n** returns NULL if there is no defined collation.\n*/\nSQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){\n  CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);\n  if( p==0 ) p = pParse->db->pDfltColl;\n  assert( p!=0 );\n  return p;\n}\n\n/*\n** Return TRUE if the two expressions have equivalent collating sequences.\n*/\nSQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){\n  CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);\n  CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);\n  return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;\n}\n\n/*\n** pExpr is an operand of a comparison operator.  aff2 is the\n** type affinity of the other operand.  This routine returns the\n** type affinity that should be used for the comparison operator.\n*/\nSQLITE_PRIVATE char sqlite3CompareAffinity(const Expr *pExpr, char aff2){\n  char aff1 = sqlite3ExprAffinity(pExpr);\n  if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){\n    /* Both sides of the comparison are columns. If one has numeric\n    ** affinity, use that. Otherwise use no affinity.\n    */\n    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){\n      return SQLITE_AFF_NUMERIC;\n    }else{\n      return SQLITE_AFF_BLOB;\n    }\n  }else{\n    /* One side is a column, the other is not. Use the columns affinity. */\n    assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );\n    return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;\n  }\n}\n\n/*\n** pExpr is a comparison operator.  Return the type affinity that should\n** be applied to both operands prior to doing the comparison.\n*/\nstatic char comparisonAffinity(const Expr *pExpr){\n  char aff;\n  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||\n          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||\n          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );\n  assert( pExpr->pLeft );\n  aff = sqlite3ExprAffinity(pExpr->pLeft);\n  if( pExpr->pRight ){\n    aff = sqlite3CompareAffinity(pExpr->pRight, aff);\n  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);\n  }else if( aff==0 ){\n    aff = SQLITE_AFF_BLOB;\n  }\n  return aff;\n}\n\n/*\n** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.\n** idx_affinity is the affinity of an indexed column. Return true\n** if the index with affinity idx_affinity may be used to implement\n** the comparison in pExpr.\n*/\nSQLITE_PRIVATE int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){\n  char aff = comparisonAffinity(pExpr);\n  if( aff<SQLITE_AFF_TEXT ){\n    return 1;\n  }\n  if( aff==SQLITE_AFF_TEXT ){\n    return idx_affinity==SQLITE_AFF_TEXT;\n  }\n  return sqlite3IsNumericAffinity(idx_affinity);\n}\n\n/*\n** Return the P5 value that should be used for a binary comparison\n** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.\n*/\nstatic u8 binaryCompareP5(\n  const Expr *pExpr1,   /* Left operand */\n  const Expr *pExpr2,   /* Right operand */\n  int jumpIfNull        /* Extra flags added to P5 */\n){\n  u8 aff = (char)sqlite3ExprAffinity(pExpr2);\n  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;\n  return aff;\n}\n\n/*\n** Return a pointer to the collation sequence that should be used by\n** a binary comparison operator comparing pLeft and pRight.\n**\n** If the left hand expression has a collating sequence type, then it is\n** used. Otherwise the collation sequence for the right hand expression\n** is used, or the default (BINARY) if neither expression has a collating\n** type.\n**\n** Argument pRight (but not pLeft) may be a null pointer. In this case,\n** it is not considered.\n*/\nSQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(\n  Parse *pParse, \n  const Expr *pLeft, \n  const Expr *pRight\n){\n  CollSeq *pColl;\n  assert( pLeft );\n  if( pLeft->flags & EP_Collate ){\n    pColl = sqlite3ExprCollSeq(pParse, pLeft);\n  }else if( pRight && (pRight->flags & EP_Collate)!=0 ){\n    pColl = sqlite3ExprCollSeq(pParse, pRight);\n  }else{\n    pColl = sqlite3ExprCollSeq(pParse, pLeft);\n    if( !pColl ){\n      pColl = sqlite3ExprCollSeq(pParse, pRight);\n    }\n  }\n  return pColl;\n}\n\n/* Expresssion p is a comparison operator.  Return a collation sequence\n** appropriate for the comparison operator.\n**\n** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().\n** However, if the OP_Commuted flag is set, then the order of the operands\n** is reversed in the sqlite3BinaryCompareCollSeq() call so that the\n** correct collating sequence is found.\n*/\nSQLITE_PRIVATE CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){\n  if( ExprHasProperty(p, EP_Commuted) ){\n    return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);\n  }else{\n    return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);\n  }\n}\n\n/*\n** Generate code for a comparison operator.\n*/\nstatic int codeCompare(\n  Parse *pParse,    /* The parsing (and code generating) context */\n  Expr *pLeft,      /* The left operand */\n  Expr *pRight,     /* The right operand */\n  int opcode,       /* The comparison opcode */\n  int in1, int in2, /* Register holding operands */\n  int dest,         /* Jump here if true.  */\n  int jumpIfNull,   /* If true, jump if either operand is NULL */\n  int isCommuted    /* The comparison has been commuted */\n){\n  int p5;\n  int addr;\n  CollSeq *p4;\n\n  if( pParse->nErr ) return 0;\n  if( isCommuted ){\n    p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);\n  }else{\n    p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);\n  }\n  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);\n  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,\n                           (void*)p4, P4_COLLSEQ);\n  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);\n  return addr;\n}\n\n/*\n** Return true if expression pExpr is a vector, or false otherwise.\n**\n** A vector is defined as any expression that results in two or more\n** columns of result.  Every TK_VECTOR node is an vector because the\n** parser will not generate a TK_VECTOR with fewer than two entries.\n** But a TK_SELECT might be either a vector or a scalar. It is only\n** considered a vector if it has two or more result columns.\n*/\nSQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){\n  return sqlite3ExprVectorSize(pExpr)>1;\n}\n\n/*\n** If the expression passed as the only argument is of type TK_VECTOR \n** return the number of expressions in the vector. Or, if the expression\n** is a sub-select, return the number of columns in the sub-select. For\n** any other type of expression, return 1.\n*/\nSQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){\n  u8 op = pExpr->op;\n  if( op==TK_REGISTER ) op = pExpr->op2;\n  if( op==TK_VECTOR ){\n    return pExpr->x.pList->nExpr;\n  }else if( op==TK_SELECT ){\n    return pExpr->x.pSelect->pEList->nExpr;\n  }else{\n    return 1;\n  }\n}\n\n/*\n** Return a pointer to a subexpression of pVector that is the i-th\n** column of the vector (numbered starting with 0).  The caller must\n** ensure that i is within range.\n**\n** If pVector is really a scalar (and \"scalar\" here includes subqueries\n** that return a single column!) then return pVector unmodified.\n**\n** pVector retains ownership of the returned subexpression.\n**\n** If the vector is a (SELECT ...) then the expression returned is\n** just the expression for the i-th term of the result set, and may\n** not be ready for evaluation because the table cursor has not yet\n** been positioned.\n*/\nSQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){\n  assert( i<sqlite3ExprVectorSize(pVector) );\n  if( sqlite3ExprIsVector(pVector) ){\n    assert( pVector->op2==0 || pVector->op==TK_REGISTER );\n    if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){\n      return pVector->x.pSelect->pEList->a[i].pExpr;\n    }else{\n      return pVector->x.pList->a[i].pExpr;\n    }\n  }\n  return pVector;\n}\n\n/*\n** Compute and return a new Expr object which when passed to\n** sqlite3ExprCode() will generate all necessary code to compute\n** the iField-th column of the vector expression pVector.\n**\n** It is ok for pVector to be a scalar (as long as iField==0).  \n** In that case, this routine works like sqlite3ExprDup().\n**\n** The caller owns the returned Expr object and is responsible for\n** ensuring that the returned value eventually gets freed.\n**\n** The caller retains ownership of pVector.  If pVector is a TK_SELECT,\n** then the returned object will reference pVector and so pVector must remain\n** valid for the life of the returned object.  If pVector is a TK_VECTOR\n** or a scalar expression, then it can be deleted as soon as this routine\n** returns.\n**\n** A trick to cause a TK_SELECT pVector to be deleted together with\n** the returned Expr object is to attach the pVector to the pRight field\n** of the returned TK_SELECT_COLUMN Expr object.\n*/\nSQLITE_PRIVATE Expr *sqlite3ExprForVectorField(\n  Parse *pParse,       /* Parsing context */\n  Expr *pVector,       /* The vector.  List of expressions or a sub-SELECT */\n  int iField           /* Which column of the vector to return */\n){\n  Expr *pRet;\n  if( pVector->op==TK_SELECT ){\n    assert( pVector->flags & EP_xIsSelect );\n    /* The TK_SELECT_COLUMN Expr node:\n    **\n    ** pLeft:           pVector containing TK_SELECT.  Not deleted.\n    ** pRight:          not used.  But recursively deleted.\n    ** iColumn:         Index of a column in pVector\n    ** iTable:          0 or the number of columns on the LHS of an assignment\n    ** pLeft->iTable:   First in an array of register holding result, or 0\n    **                  if the result is not yet computed.\n    **\n    ** sqlite3ExprDelete() specifically skips the recursive delete of\n    ** pLeft on TK_SELECT_COLUMN nodes.  But pRight is followed, so pVector\n    ** can be attached to pRight to cause this node to take ownership of\n    ** pVector.  Typically there will be multiple TK_SELECT_COLUMN nodes\n    ** with the same pLeft pointer to the pVector, but only one of them\n    ** will own the pVector.\n    */\n    pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);\n    if( pRet ){\n      pRet->iColumn = iField;\n      pRet->pLeft = pVector;\n    }\n    assert( pRet==0 || pRet->iTable==0 );\n  }else{\n    if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;\n    pRet = sqlite3ExprDup(pParse->db, pVector, 0);\n    sqlite3RenameTokenRemap(pParse, pRet, pVector);\n  }\n  return pRet;\n}\n\n/*\n** If expression pExpr is of type TK_SELECT, generate code to evaluate\n** it. Return the register in which the result is stored (or, if the \n** sub-select returns more than one column, the first in an array\n** of registers in which the result is stored).\n**\n** If pExpr is not a TK_SELECT expression, return 0.\n*/\nstatic int exprCodeSubselect(Parse *pParse, Expr *pExpr){\n  int reg = 0;\n#ifndef SQLITE_OMIT_SUBQUERY\n  if( pExpr->op==TK_SELECT ){\n    reg = sqlite3CodeSubselect(pParse, pExpr);\n  }\n#endif\n  return reg;\n}\n\n/*\n** Argument pVector points to a vector expression - either a TK_VECTOR\n** or TK_SELECT that returns more than one column. This function returns\n** the register number of a register that contains the value of\n** element iField of the vector.\n**\n** If pVector is a TK_SELECT expression, then code for it must have \n** already been generated using the exprCodeSubselect() routine. In this\n** case parameter regSelect should be the first in an array of registers\n** containing the results of the sub-select. \n**\n** If pVector is of type TK_VECTOR, then code for the requested field\n** is generated. In this case (*pRegFree) may be set to the number of\n** a temporary register to be freed by the caller before returning.\n**\n** Before returning, output parameter (*ppExpr) is set to point to the\n** Expr object corresponding to element iElem of the vector.\n*/\nstatic int exprVectorRegister(\n  Parse *pParse,                  /* Parse context */\n  Expr *pVector,                  /* Vector to extract element from */\n  int iField,                     /* Field to extract from pVector */\n  int regSelect,                  /* First in array of registers */\n  Expr **ppExpr,                  /* OUT: Expression element */\n  int *pRegFree                   /* OUT: Temp register to free */\n){\n  u8 op = pVector->op;\n  assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );\n  if( op==TK_REGISTER ){\n    *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);\n    return pVector->iTable+iField;\n  }\n  if( op==TK_SELECT ){\n    *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;\n     return regSelect+iField;\n  }\n  *ppExpr = pVector->x.pList->a[iField].pExpr;\n  return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);\n}\n\n/*\n** Expression pExpr is a comparison between two vector values. Compute\n** the result of the comparison (1, 0, or NULL) and write that\n** result into register dest.\n**\n** The caller must satisfy the following preconditions:\n**\n**    if pExpr->op==TK_IS:      op==TK_EQ and p5==SQLITE_NULLEQ\n**    if pExpr->op==TK_ISNOT:   op==TK_NE and p5==SQLITE_NULLEQ\n**    otherwise:                op==pExpr->op and p5==0\n*/\nstatic void codeVectorCompare(\n  Parse *pParse,        /* Code generator context */\n  Expr *pExpr,          /* The comparison operation */\n  int dest,             /* Write results into this register */\n  u8 op,                /* Comparison operator */\n  u8 p5                 /* SQLITE_NULLEQ or zero */\n){\n  Vdbe *v = pParse->pVdbe;\n  Expr *pLeft = pExpr->pLeft;\n  Expr *pRight = pExpr->pRight;\n  int nLeft = sqlite3ExprVectorSize(pLeft);\n  int i;\n  int regLeft = 0;\n  int regRight = 0;\n  u8 opx = op;\n  int addrDone = sqlite3VdbeMakeLabel(pParse);\n  int isCommuted = ExprHasProperty(pExpr,EP_Commuted);\n\n  assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );\n  if( pParse->nErr ) return;\n  if( nLeft!=sqlite3ExprVectorSize(pRight) ){\n    sqlite3ErrorMsg(pParse, \"row value misused\");\n    return;\n  }\n  assert( pExpr->op==TK_EQ || pExpr->op==TK_NE \n       || pExpr->op==TK_IS || pExpr->op==TK_ISNOT \n       || pExpr->op==TK_LT || pExpr->op==TK_GT \n       || pExpr->op==TK_LE || pExpr->op==TK_GE \n  );\n  assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)\n            || (pExpr->op==TK_ISNOT && op==TK_NE) );\n  assert( p5==0 || pExpr->op!=op );\n  assert( p5==SQLITE_NULLEQ || pExpr->op==op );\n\n  p5 |= SQLITE_STOREP2;\n  if( opx==TK_LE ) opx = TK_LT;\n  if( opx==TK_GE ) opx = TK_GT;\n\n  regLeft = exprCodeSubselect(pParse, pLeft);\n  regRight = exprCodeSubselect(pParse, pRight);\n\n  for(i=0; 1 /*Loop exits by \"break\"*/; i++){\n    int regFree1 = 0, regFree2 = 0;\n    Expr *pL, *pR; \n    int r1, r2;\n    assert( i>=0 && i<nLeft );\n    r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);\n    r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);\n    codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5, isCommuted);\n    testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);\n    testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);\n    testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);\n    testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);\n    testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);\n    testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);\n    sqlite3ReleaseTempReg(pParse, regFree1);\n    sqlite3ReleaseTempReg(pParse, regFree2);\n    if( i==nLeft-1 ){\n      break;\n    }\n    if( opx==TK_EQ ){\n      sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);\n      p5 |= SQLITE_KEEPNULL;\n    }else if( opx==TK_NE ){\n      sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);\n      p5 |= SQLITE_KEEPNULL;\n    }else{\n      assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );\n      sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);\n      VdbeCoverageIf(v, op==TK_LT);\n      VdbeCoverageIf(v, op==TK_GT);\n      VdbeCoverageIf(v, op==TK_LE);\n      VdbeCoverageIf(v, op==TK_GE);\n      if( i==nLeft-2 ) opx = op;\n    }\n  }\n  sqlite3VdbeResolveLabel(v, addrDone);\n}\n\n#if SQLITE_MAX_EXPR_DEPTH>0\n/*\n** Check that argument nHeight is less than or equal to the maximum\n** expression depth allowed. If it is not, leave an error message in\n** pParse.\n*/\nSQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){\n  int rc = SQLITE_OK;\n  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];\n  if( nHeight>mxHeight ){\n    sqlite3ErrorMsg(pParse, \n       \"Expression tree is too large (maximum depth %d)\", mxHeight\n    );\n    rc = SQLITE_ERROR;\n  }\n  return rc;\n}\n\n/* The following three functions, heightOfExpr(), heightOfExprList()\n** and heightOfSelect(), are used to determine the maximum height\n** of any expression tree referenced by the structure passed as the\n** first argument.\n**\n** If this maximum height is greater than the current value pointed\n** to by pnHeight, the second parameter, then set *pnHeight to that\n** value.\n*/\nstatic void heightOfExpr(Expr *p, int *pnHeight){\n  if( p ){\n    if( p->nHeight>*pnHeight ){\n      *pnHeight = p->nHeight;\n    }\n  }\n}\nstatic void heightOfExprList(ExprList *p, int *pnHeight){\n  if( p ){\n    int i;\n    for(i=0; i<p->nExpr; i++){\n      heightOfExpr(p->a[i].pExpr, pnHeight);\n    }\n  }\n}\nstatic void heightOfSelect(Select *pSelect, int *pnHeight){\n  Select *p;\n  for(p=pSelect; p; p=p->pPrior){\n    heightOfExpr(p->pWhere, pnHeight);\n    heightOfExpr(p->pHaving, pnHeight);\n    heightOfExpr(p->pLimit, pnHeight);\n    heightOfExprList(p->pEList, pnHeight);\n    heightOfExprList(p->pGroupBy, pnHeight);\n    heightOfExprList(p->pOrderBy, pnHeight);\n  }\n}\n\n/*\n** Set the Expr.nHeight variable in the structure passed as an \n** argument. An expression with no children, Expr.pList or \n** Expr.pSelect member has a height of 1. Any other expression\n** has a height equal to the maximum height of any other \n** referenced Expr plus one.\n**\n** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,\n** if appropriate.\n*/\nstatic void exprSetHeight(Expr *p){\n  int nHeight = 0;\n  heightOfExpr(p->pLeft, &nHeight);\n  heightOfExpr(p->pRight, &nHeight);\n  if( ExprHasProperty(p, EP_xIsSelect) ){\n    heightOfSelect(p->x.pSelect, &nHeight);\n  }else if( p->x.pList ){\n    heightOfExprList(p->x.pList, &nHeight);\n    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);\n  }\n  p->nHeight = nHeight + 1;\n}\n\n/*\n** Set the Expr.nHeight variable using the exprSetHeight() function. If\n** the height is greater than the maximum allowed expression depth,\n** leave an error in pParse.\n**\n** Also propagate all EP_Propagate flags from the Expr.x.pList into\n** Expr.flags. \n*/\nSQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){\n  if( pParse->nErr ) return;\n  exprSetHeight(p);\n  sqlite3ExprCheckHeight(pParse, p->nHeight);\n}\n\n/*\n** Return the maximum height of any expression tree referenced\n** by the select statement passed as an argument.\n*/\nSQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){\n  int nHeight = 0;\n  heightOfSelect(p, &nHeight);\n  return nHeight;\n}\n#else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */\n/*\n** Propagate all EP_Propagate flags from the Expr.x.pList into\n** Expr.flags. \n*/\nSQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){\n  if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){\n    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);\n  }\n}\n#define exprSetHeight(y)\n#endif /* SQLITE_MAX_EXPR_DEPTH>0 */\n\n/*\n** This routine is the core allocator for Expr nodes.\n**\n** Construct a new expression node and return a pointer to it.  Memory\n** for this node and for the pToken argument is a single allocation\n** obtained from sqlite3DbMalloc().  The calling function\n** is responsible for making sure the node eventually gets freed.\n**\n** If dequote is true, then the token (if it exists) is dequoted.\n** If dequote is false, no dequoting is performed.  The deQuote\n** parameter is ignored if pToken is NULL or if the token does not\n** appear to be quoted.  If the quotes were of the form \"...\" (double-quotes)\n** then the EP_DblQuoted flag is set on the expression node.\n**\n** Special case:  If op==TK_INTEGER and pToken points to a string that\n** can be translated into a 32-bit integer, then the token is not\n** stored in u.zToken.  Instead, the integer values is written\n** into u.iValue and the EP_IntValue flag is set.  No extra storage\n** is allocated to hold the integer text and the dequote flag is ignored.\n*/\nSQLITE_PRIVATE Expr *sqlite3ExprAlloc(\n  sqlite3 *db,            /* Handle for sqlite3DbMallocRawNN() */\n  int op,                 /* Expression opcode */\n  const Token *pToken,    /* Token argument.  Might be NULL */\n  int dequote             /* True to dequote */\n){\n  Expr *pNew;\n  int nExtra = 0;\n  int iValue = 0;\n\n  assert( db!=0 );\n  if( pToken ){\n    if( op!=TK_INTEGER || pToken->z==0\n          || sqlite3GetInt32(pToken->z, &iValue)==0 ){\n      nExtra = pToken->n+1;\n      assert( iValue>=0 );\n    }\n  }\n  pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);\n  if( pNew ){\n    memset(pNew, 0, sizeof(Expr));\n    pNew->op = (u8)op;\n    pNew->iAgg = -1;\n    if( pToken ){\n      if( nExtra==0 ){\n        pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);\n        pNew->u.iValue = iValue;\n      }else{\n        pNew->u.zToken = (char*)&pNew[1];\n        assert( pToken->z!=0 || pToken->n==0 );\n        if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);\n        pNew->u.zToken[pToken->n] = 0;\n        if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){\n          sqlite3DequoteExpr(pNew);\n        }\n      }\n    }\n#if SQLITE_MAX_EXPR_DEPTH>0\n    pNew->nHeight = 1;\n#endif  \n  }\n  return pNew;\n}\n\n/*\n** Allocate a new expression node from a zero-terminated token that has\n** already been dequoted.\n*/\nSQLITE_PRIVATE Expr *sqlite3Expr(\n  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */\n  int op,                 /* Expression opcode */\n  const char *zToken      /* Token argument.  Might be NULL */\n){\n  Token x;\n  x.z = zToken;\n  x.n = sqlite3Strlen30(zToken);\n  return sqlite3ExprAlloc(db, op, &x, 0);\n}\n\n/*\n** Attach subtrees pLeft and pRight to the Expr node pRoot.\n**\n** If pRoot==NULL that means that a memory allocation error has occurred.\n** In that case, delete the subtrees pLeft and pRight.\n*/\nSQLITE_PRIVATE void sqlite3ExprAttachSubtrees(\n  sqlite3 *db,\n  Expr *pRoot,\n  Expr *pLeft,\n  Expr *pRight\n){\n  if( pRoot==0 ){\n    assert( db->mallocFailed );\n    sqlite3ExprDelete(db, pLeft);\n    sqlite3ExprDelete(db, pRight);\n  }else{\n    if( pRight ){\n      pRoot->pRight = pRight;\n      pRoot->flags |= EP_Propagate & pRight->flags;\n    }\n    if( pLeft ){\n      pRoot->pLeft = pLeft;\n      pRoot->flags |= EP_Propagate & pLeft->flags;\n    }\n    exprSetHeight(pRoot);\n  }\n}\n\n/*\n** Allocate an Expr node which joins as many as two subtrees.\n**\n** One or both of the subtrees can be NULL.  Return a pointer to the new\n** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,\n** free the subtrees and return NULL.\n*/\nSQLITE_PRIVATE Expr *sqlite3PExpr(\n  Parse *pParse,          /* Parsing context */\n  int op,                 /* Expression opcode */\n  Expr *pLeft,            /* Left operand */\n  Expr *pRight            /* Right operand */\n){\n  Expr *p;\n  p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));\n  if( p ){\n    memset(p, 0, sizeof(Expr));\n    p->op = op & 0xff;\n    p->iAgg = -1;\n    sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);\n    sqlite3ExprCheckHeight(pParse, p->nHeight);\n  }else{\n    sqlite3ExprDelete(pParse->db, pLeft);\n    sqlite3ExprDelete(pParse->db, pRight);\n  }\n  return p;\n}\n\n/*\n** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due\n** do a memory allocation failure) then delete the pSelect object.\n*/\nSQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){\n  if( pExpr ){\n    pExpr->x.pSelect = pSelect;\n    ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);\n    sqlite3ExprSetHeightAndFlags(pParse, pExpr);\n  }else{\n    assert( pParse->db->mallocFailed );\n    sqlite3SelectDelete(pParse->db, pSelect);\n  }\n}\n\n\n/*\n** Join two expressions using an AND operator.  If either expression is\n** NULL, then just return the other expression.\n**\n** If one side or the other of the AND is known to be false, then instead\n** of returning an AND expression, just return a constant expression with\n** a value of false.\n*/\nSQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){\n  sqlite3 *db = pParse->db;\n  if( pLeft==0  ){\n    return pRight;\n  }else if( pRight==0 ){\n    return pLeft;\n  }else if( (ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight)) \n         && !IN_RENAME_OBJECT\n  ){\n    sqlite3ExprDelete(db, pLeft);\n    sqlite3ExprDelete(db, pRight);\n    return sqlite3Expr(db, TK_INTEGER, \"0\");\n  }else{\n    return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);\n  }\n}\n\n/*\n** Construct a new expression node for a function with multiple\n** arguments.\n*/\nSQLITE_PRIVATE Expr *sqlite3ExprFunction(\n  Parse *pParse,        /* Parsing context */\n  ExprList *pList,      /* Argument list */\n  Token *pToken,        /* Name of the function */\n  int eDistinct         /* SF_Distinct or SF_ALL or 0 */\n){\n  Expr *pNew;\n  sqlite3 *db = pParse->db;\n  assert( pToken );\n  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);\n  if( pNew==0 ){\n    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */\n    return 0;\n  }\n  if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){\n    sqlite3ErrorMsg(pParse, \"too many arguments on function %T\", pToken);\n  }\n  pNew->x.pList = pList;\n  ExprSetProperty(pNew, EP_HasFunc);\n  assert( !ExprHasProperty(pNew, EP_xIsSelect) );\n  sqlite3ExprSetHeightAndFlags(pParse, pNew);\n  if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);\n  return pNew;\n}\n\n/*\n** Check to see if a function is usable according to current access\n** rules:\n**\n**    SQLITE_FUNC_DIRECT    -     Only usable from top-level SQL\n**\n**    SQLITE_FUNC_UNSAFE    -     Usable if TRUSTED_SCHEMA or from\n**                                top-level SQL\n**\n** If the function is not usable, create an error.\n*/\nSQLITE_PRIVATE void sqlite3ExprFunctionUsable(\n  Parse *pParse,         /* Parsing and code generating context */\n  Expr *pExpr,           /* The function invocation */\n  FuncDef *pDef          /* The function being invoked */\n){\n  assert( !IN_RENAME_OBJECT );\n  assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );\n  if( ExprHasProperty(pExpr, EP_FromDDL) ){\n    if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0\n     || (pParse->db->flags & SQLITE_TrustedSchema)==0\n    ){\n      /* Functions prohibited in triggers and views if:\n      **     (1) tagged with SQLITE_DIRECTONLY\n      **     (2) not tagged with SQLITE_INNOCUOUS (which means it\n      **         is tagged with SQLITE_FUNC_UNSAFE) and \n      **         SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning\n      **         that the schema is possibly tainted).\n      */\n      sqlite3ErrorMsg(pParse, \"unsafe use of %s()\", pDef->zName);\n    }\n  }\n}\n\n/*\n** Assign a variable number to an expression that encodes a wildcard\n** in the original SQL statement.  \n**\n** Wildcards consisting of a single \"?\" are assigned the next sequential\n** variable number.\n**\n** Wildcards of the form \"?nnn\" are assigned the number \"nnn\".  We make\n** sure \"nnn\" is not too big to avoid a denial of service attack when\n** the SQL statement comes from an external source.\n**\n** Wildcards of the form \":aaa\", \"@aaa\", or \"$aaa\" are assigned the same number\n** as the previous instance of the same wildcard.  Or if this is the first\n** instance of the wildcard, the next sequential variable number is\n** assigned.\n*/\nSQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){\n  sqlite3 *db = pParse->db;\n  const char *z;\n  ynVar x;\n\n  if( pExpr==0 ) return;\n  assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );\n  z = pExpr->u.zToken;\n  assert( z!=0 );\n  assert( z[0]!=0 );\n  assert( n==(u32)sqlite3Strlen30(z) );\n  if( z[1]==0 ){\n    /* Wildcard of the form \"?\".  Assign the next variable number */\n    assert( z[0]=='?' );\n    x = (ynVar)(++pParse->nVar);\n  }else{\n    int doAdd = 0;\n    if( z[0]=='?' ){\n      /* Wildcard of the form \"?nnn\".  Convert \"nnn\" to an integer and\n      ** use it as the variable number */\n      i64 i;\n      int bOk;\n      if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/\n        i = z[1]-'0';  /* The common case of ?N for a single digit N */\n        bOk = 1;\n      }else{\n        bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);\n      }\n      testcase( i==0 );\n      testcase( i==1 );\n      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );\n      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );\n      if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){\n        sqlite3ErrorMsg(pParse, \"variable number must be between ?1 and ?%d\",\n            db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);\n        return;\n      }\n      x = (ynVar)i;\n      if( x>pParse->nVar ){\n        pParse->nVar = (int)x;\n        doAdd = 1;\n      }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){\n        doAdd = 1;\n      }\n    }else{\n      /* Wildcards like \":aaa\", \"$aaa\" or \"@aaa\".  Reuse the same variable\n      ** number as the prior appearance of the same name, or if the name\n      ** has never appeared before, reuse the same variable number\n      */\n      x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);\n      if( x==0 ){\n        x = (ynVar)(++pParse->nVar);\n        doAdd = 1;\n      }\n    }\n    if( doAdd ){\n      pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);\n    }\n  }\n  pExpr->iColumn = x;\n  if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){\n    sqlite3ErrorMsg(pParse, \"too many SQL variables\");\n  }\n}\n\n/*\n** Recursively delete an expression tree.\n*/\nstatic SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){\n  assert( p!=0 );\n  /* Sanity check: Assert that the IntValue is non-negative if it exists */\n  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );\n\n  assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );\n  assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)\n          || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );\n#ifdef SQLITE_DEBUG\n  if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){\n    assert( p->pLeft==0 );\n    assert( p->pRight==0 );\n    assert( p->x.pSelect==0 );\n  }\n#endif\n  if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){\n    /* The Expr.x union is never used at the same time as Expr.pRight */\n    assert( p->x.pList==0 || p->pRight==0 );\n    if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);\n    if( p->pRight ){\n      assert( !ExprHasProperty(p, EP_WinFunc) );\n      sqlite3ExprDeleteNN(db, p->pRight);\n    }else if( ExprHasProperty(p, EP_xIsSelect) ){\n      assert( !ExprHasProperty(p, EP_WinFunc) );\n      sqlite3SelectDelete(db, p->x.pSelect);\n    }else{\n      sqlite3ExprListDelete(db, p->x.pList);\n#ifndef SQLITE_OMIT_WINDOWFUNC\n      if( ExprHasProperty(p, EP_WinFunc) ){\n        sqlite3WindowDelete(db, p->y.pWin);\n      }\n#endif\n    }\n  }\n  if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);\n  if( !ExprHasProperty(p, EP_Static) ){\n    sqlite3DbFreeNN(db, p);\n  }\n}\nSQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){\n  if( p ) sqlite3ExprDeleteNN(db, p);\n}\n\n/* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the\n** expression.\n*/\nSQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){\n  if( p ){\n    if( IN_RENAME_OBJECT ){\n      sqlite3RenameExprUnmap(pParse, p);\n    }\n    sqlite3ExprDeleteNN(pParse->db, p);\n  }\n}\n\n/*\n** Return the number of bytes allocated for the expression structure \n** passed as the first argument. This is always one of EXPR_FULLSIZE,\n** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.\n*/\nstatic int exprStructSize(Expr *p){\n  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;\n  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;\n  return EXPR_FULLSIZE;\n}\n\n/*\n** The dupedExpr*Size() routines each return the number of bytes required\n** to store a copy of an expression or expression tree.  They differ in\n** how much of the tree is measured.\n**\n**     dupedExprStructSize()     Size of only the Expr structure \n**     dupedExprNodeSize()       Size of Expr + space for token\n**     dupedExprSize()           Expr + token + subtree components\n**\n***************************************************************************\n**\n** The dupedExprStructSize() function returns two values OR-ed together:  \n** (1) the space required for a copy of the Expr structure only and \n** (2) the EP_xxx flags that indicate what the structure size should be.\n** The return values is always one of:\n**\n**      EXPR_FULLSIZE\n**      EXPR_REDUCEDSIZE   | EP_Reduced\n**      EXPR_TOKENONLYSIZE | EP_TokenOnly\n**\n** The size of the structure can be found by masking the return value\n** of this routine with 0xfff.  The flags can be found by masking the\n** return value with EP_Reduced|EP_TokenOnly.\n**\n** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size\n** (unreduced) Expr objects as they or originally constructed by the parser.\n** During expression analysis, extra information is computed and moved into\n** later parts of the Expr object and that extra information might get chopped\n** off if the expression is reduced.  Note also that it does not work to\n** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal\n** to reduce a pristine expression tree from the parser.  The implementation\n** of dupedExprStructSize() contain multiple assert() statements that attempt\n** to enforce this constraint.\n*/\nstatic int dupedExprStructSize(Expr *p, int flags){\n  int nSize;\n  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */\n  assert( EXPR_FULLSIZE<=0xfff );\n  assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );\n  if( 0==flags || p->op==TK_SELECT_COLUMN \n#ifndef SQLITE_OMIT_WINDOWFUNC\n   || ExprHasProperty(p, EP_WinFunc)\n#endif\n  ){\n    nSize = EXPR_FULLSIZE;\n  }else{\n    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );\n    assert( !ExprHasProperty(p, EP_FromJoin) ); \n    assert( !ExprHasProperty(p, EP_MemToken) );\n    assert( !ExprHasVVAProperty(p, EP_NoReduce) );\n    if( p->pLeft || p->x.pList ){\n      nSize = EXPR_REDUCEDSIZE | EP_Reduced;\n    }else{\n      assert( p->pRight==0 );\n      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;\n    }\n  }\n  return nSize;\n}\n\n/*\n** This function returns the space in bytes required to store the copy \n** of the Expr structure and a copy of the Expr.u.zToken string (if that\n** string is defined.)\n*/\nstatic int dupedExprNodeSize(Expr *p, int flags){\n  int nByte = dupedExprStructSize(p, flags) & 0xfff;\n  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){\n    nByte += sqlite3Strlen30NN(p->u.zToken)+1;\n  }\n  return ROUND8(nByte);\n}\n\n/*\n** Return the number of bytes required to create a duplicate of the \n** expression passed as the first argument. The second argument is a\n** mask containing EXPRDUP_XXX flags.\n**\n** The value returned includes space to create a copy of the Expr struct\n** itself and the buffer referred to by Expr.u.zToken, if any.\n**\n** If the EXPRDUP_REDUCE flag is set, then the return value includes \n** space to duplicate all Expr nodes in the tree formed by Expr.pLeft \n** and Expr.pRight variables (but not for any structures pointed to or \n** descended from the Expr.x.pList or Expr.x.pSelect variables).\n*/\nstatic int dupedExprSize(Expr *p, int flags){\n  int nByte = 0;\n  if( p ){\n    nByte = dupedExprNodeSize(p, flags);\n    if( flags&EXPRDUP_REDUCE ){\n      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);\n    }\n  }\n  return nByte;\n}\n\n/*\n** This function is similar to sqlite3ExprDup(), except that if pzBuffer \n** is not NULL then *pzBuffer is assumed to point to a buffer large enough \n** to store the copy of expression p, the copies of p->u.zToken\n** (if applicable), and the copies of the p->pLeft and p->pRight expressions,\n** if any. Before returning, *pzBuffer is set to the first byte past the\n** portion of the buffer copied into by this function.\n*/\nstatic Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){\n  Expr *pNew;           /* Value to return */\n  u8 *zAlloc;           /* Memory space from which to build Expr object */\n  u32 staticFlag;       /* EP_Static if space not obtained from malloc */\n\n  assert( db!=0 );\n  assert( p );\n  assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );\n  assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );\n\n  /* Figure out where to write the new Expr structure. */\n  if( pzBuffer ){\n    zAlloc = *pzBuffer;\n    staticFlag = EP_Static;\n  }else{\n    zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));\n    staticFlag = 0;\n  }\n  pNew = (Expr *)zAlloc;\n\n  if( pNew ){\n    /* Set nNewSize to the size allocated for the structure pointed to\n    ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or\n    ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed\n    ** by the copy of the p->u.zToken string (if any).\n    */\n    const unsigned nStructSize = dupedExprStructSize(p, dupFlags);\n    const int nNewSize = nStructSize & 0xfff;\n    int nToken;\n    if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){\n      nToken = sqlite3Strlen30(p->u.zToken) + 1;\n    }else{\n      nToken = 0;\n    }\n    if( dupFlags ){\n      assert( ExprHasProperty(p, EP_Reduced)==0 );\n      memcpy(zAlloc, p, nNewSize);\n    }else{\n      u32 nSize = (u32)exprStructSize(p);\n      memcpy(zAlloc, p, nSize);\n      if( nSize<EXPR_FULLSIZE ){ \n        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);\n      }\n    }\n\n    /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */\n    pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);\n    pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);\n    pNew->flags |= staticFlag;\n    ExprClearVVAProperties(pNew);\n    if( dupFlags ){\n      ExprSetVVAProperty(pNew, EP_Immutable);\n    }\n\n    /* Copy the p->u.zToken string, if any. */\n    if( nToken ){\n      char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];\n      memcpy(zToken, p->u.zToken, nToken);\n    }\n\n    if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){\n      /* Fill in the pNew->x.pSelect or pNew->x.pList member. */\n      if( ExprHasProperty(p, EP_xIsSelect) ){\n        pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);\n      }else{\n        pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);\n      }\n    }\n\n    /* Fill in pNew->pLeft and pNew->pRight. */\n    if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){\n      zAlloc += dupedExprNodeSize(p, dupFlags);\n      if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){\n        pNew->pLeft = p->pLeft ?\n                      exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;\n        pNew->pRight = p->pRight ?\n                       exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;\n      }\n#ifndef SQLITE_OMIT_WINDOWFUNC\n      if( ExprHasProperty(p, EP_WinFunc) ){\n        pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);\n        assert( ExprHasProperty(pNew, EP_WinFunc) );\n      }\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n      if( pzBuffer ){\n        *pzBuffer = zAlloc;\n      }\n    }else{\n      if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){\n        if( pNew->op==TK_SELECT_COLUMN ){\n          pNew->pLeft = p->pLeft;\n          assert( p->iColumn==0 || p->pRight==0 );\n          assert( p->pRight==0  || p->pRight==p->pLeft );\n        }else{\n          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);\n        }\n        pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);\n      }\n    }\n  }\n  return pNew;\n}\n\n/*\n** Create and return a deep copy of the object passed as the second \n** argument. If an OOM condition is encountered, NULL is returned\n** and the db->mallocFailed flag set.\n*/\n#ifndef SQLITE_OMIT_CTE\nstatic With *withDup(sqlite3 *db, With *p){\n  With *pRet = 0;\n  if( p ){\n    sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);\n    pRet = sqlite3DbMallocZero(db, nByte);\n    if( pRet ){\n      int i;\n      pRet->nCte = p->nCte;\n      for(i=0; i<p->nCte; i++){\n        pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);\n        pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);\n        pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);\n      }\n    }\n  }\n  return pRet;\n}\n#else\n# define withDup(x,y) 0\n#endif\n\n#ifndef SQLITE_OMIT_WINDOWFUNC\n/*\n** The gatherSelectWindows() procedure and its helper routine\n** gatherSelectWindowsCallback() are used to scan all the expressions\n** an a newly duplicated SELECT statement and gather all of the Window\n** objects found there, assembling them onto the linked list at Select->pWin.\n*/\nstatic int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){\n  if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){\n    Select *pSelect = pWalker->u.pSelect;\n    Window *pWin = pExpr->y.pWin;\n    assert( pWin );\n    assert( IsWindowFunc(pExpr) );\n    assert( pWin->ppThis==0 );\n    sqlite3WindowLink(pSelect, pWin);\n  }\n  return WRC_Continue;\n}\nstatic int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){\n  return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;\n}\nstatic void gatherSelectWindows(Select *p){\n  Walker w;\n  w.xExprCallback = gatherSelectWindowsCallback;\n  w.xSelectCallback = gatherSelectWindowsSelectCallback;\n  w.xSelectCallback2 = 0;\n  w.pParse = 0;\n  w.u.pSelect = p;\n  sqlite3WalkSelect(&w, p);\n}\n#endif\n\n\n/*\n** The following group of routines make deep copies of expressions,\n** expression lists, ID lists, and select statements.  The copies can\n** be deleted (by being passed to their respective ...Delete() routines)\n** without effecting the originals.\n**\n** The expression list, ID, and source lists return by sqlite3ExprListDup(),\n** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded \n** by subsequent calls to sqlite*ListAppend() routines.\n**\n** Any tables that the SrcList might point to are not duplicated.\n**\n** The flags parameter contains a combination of the EXPRDUP_XXX flags.\n** If the EXPRDUP_REDUCE flag is set, then the structure returned is a\n** truncated version of the usual Expr structure that will be stored as\n** part of the in-memory representation of the database schema.\n*/\nSQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){\n  assert( flags==0 || flags==EXPRDUP_REDUCE );\n  return p ? exprDup(db, p, flags, 0) : 0;\n}\nSQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){\n  ExprList *pNew;\n  struct ExprList_item *pItem, *pOldItem;\n  int i;\n  Expr *pPriorSelectCol = 0;\n  assert( db!=0 );\n  if( p==0 ) return 0;\n  pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));\n  if( pNew==0 ) return 0;\n  pNew->nExpr = p->nExpr;\n  pItem = pNew->a;\n  pOldItem = p->a;\n  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){\n    Expr *pOldExpr = pOldItem->pExpr;\n    Expr *pNewExpr;\n    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);\n    if( pOldExpr \n     && pOldExpr->op==TK_SELECT_COLUMN\n     && (pNewExpr = pItem->pExpr)!=0 \n    ){\n      assert( pNewExpr->iColumn==0 || i>0 );\n      if( pNewExpr->iColumn==0 ){\n        assert( pOldExpr->pLeft==pOldExpr->pRight );\n        pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;\n      }else{\n        assert( i>0 );\n        assert( pItem[-1].pExpr!=0 );\n        assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );\n        assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );\n        pNewExpr->pLeft = pPriorSelectCol;\n      }\n    }\n    pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);\n    pItem->sortFlags = pOldItem->sortFlags;\n    pItem->eEName = pOldItem->eEName;\n    pItem->done = 0;\n    pItem->bNulls = pOldItem->bNulls;\n    pItem->bSorterRef = pOldItem->bSorterRef;\n    pItem->u = pOldItem->u;\n  }\n  return pNew;\n}\n\n/*\n** If cursors, triggers, views and subqueries are all omitted from\n** the build, then none of the following routines, except for \n** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes\n** called with a NULL argument.\n*/\n#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \\\n || !defined(SQLITE_OMIT_SUBQUERY)\nSQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){\n  SrcList *pNew;\n  int i;\n  int nByte;\n  assert( db!=0 );\n  if( p==0 ) return 0;\n  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);\n  pNew = sqlite3DbMallocRawNN(db, nByte );\n  if( pNew==0 ) return 0;\n  pNew->nSrc = pNew->nAlloc = p->nSrc;\n  for(i=0; i<p->nSrc; i++){\n    struct SrcList_item *pNewItem = &pNew->a[i];\n    struct SrcList_item *pOldItem = &p->a[i];\n    Table *pTab;\n    pNewItem->pSchema = pOldItem->pSchema;\n    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);\n    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);\n    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);\n    pNewItem->fg = pOldItem->fg;\n    pNewItem->iCursor = pOldItem->iCursor;\n    pNewItem->addrFillSub = pOldItem->addrFillSub;\n    pNewItem->regReturn = pOldItem->regReturn;\n    if( pNewItem->fg.isIndexedBy ){\n      pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);\n    }\n    pNewItem->pIBIndex = pOldItem->pIBIndex;\n    if( pNewItem->fg.isTabFunc ){\n      pNewItem->u1.pFuncArg = \n          sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);\n    }\n    pTab = pNewItem->pTab = pOldItem->pTab;\n    if( pTab ){\n      pTab->nTabRef++;\n    }\n    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);\n    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);\n    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);\n    pNewItem->colUsed = pOldItem->colUsed;\n  }\n  return pNew;\n}\nSQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){\n  IdList *pNew;\n  int i;\n  assert( db!=0 );\n  if( p==0 ) return 0;\n  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );\n  if( pNew==0 ) return 0;\n  pNew->nId = p->nId;\n  pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );\n  if( pNew->a==0 ){\n    sqlite3DbFreeNN(db, pNew);\n    return 0;\n  }\n  /* Note that because the size of the allocation for p->a[] is not\n  ** necessarily a power of two, sqlite3IdListAppend() may not be called\n  ** on the duplicate created by this function. */\n  for(i=0; i<p->nId; i++){\n    struct IdList_item *pNewItem = &pNew->a[i];\n    struct IdList_item *pOldItem = &p->a[i];\n    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);\n    pNewItem->idx = pOldItem->idx;\n  }\n  return pNew;\n}\nSQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){\n  Select *pRet = 0;\n  Select *pNext = 0;\n  Select **pp = &pRet;\n  Select *p;\n\n  assert( db!=0 );\n  for(p=pDup; p; p=p->pPrior){\n    Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );\n    if( pNew==0 ) break;\n    pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);\n    pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);\n    pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);\n    pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);\n    pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);\n    pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);\n    pNew->op = p->op;\n    pNew->pNext = pNext;\n    pNew->pPrior = 0;\n    pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);\n    pNew->iLimit = 0;\n    pNew->iOffset = 0;\n    pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;\n    pNew->addrOpenEphm[0] = -1;\n    pNew->addrOpenEphm[1] = -1;\n    pNew->nSelectRow = p->nSelectRow;\n    pNew->pWith = withDup(db, p->pWith);\n#ifndef SQLITE_OMIT_WINDOWFUNC\n    pNew->pWin = 0;\n    pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);\n    if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);\n#endif\n    pNew->selId = p->selId;\n    *pp = pNew;\n    pp = &pNew->pPrior;\n    pNext = pNew;\n  }\n\n  return pRet;\n}\n#else\nSQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){\n  assert( p==0 );\n  return 0;\n}\n#endif\n\n\n/*\n** Add a new element to the end of an expression list.  If pList is\n** initially NULL, then create a new expression list.\n**\n** The pList argument must be either NULL or a pointer to an ExprList\n** obtained from a prior call to sqlite3ExprListAppend().  This routine\n** may not be used with an ExprList obtained from sqlite3ExprListDup().\n** Reason:  This routine assumes that the number of slots in pList->a[]\n** is a power of two.  That is true for sqlite3ExprListAppend() returns\n** but is not necessarily true from the return value of sqlite3ExprListDup().\n**\n** If a memory allocation error occurs, the entire list is freed and\n** NULL is returned.  If non-NULL is returned, then it is guaranteed\n** that the new entry was successfully appended.\n*/\nSQLITE_PRIVATE ExprList *sqlite3ExprListAppend(\n  Parse *pParse,          /* Parsing context */\n  ExprList *pList,        /* List to which to append. Might be NULL */\n  Expr *pExpr             /* Expression to be appended. Might be NULL */\n){\n  struct ExprList_item *pItem;\n  sqlite3 *db = pParse->db;\n  assert( db!=0 );\n  if( pList==0 ){\n    pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );\n    if( pList==0 ){\n      goto no_mem;\n    }\n    pList->nExpr = 0;\n  }else if( (pList->nExpr & (pList->nExpr-1))==0 ){\n    ExprList *pNew;\n    pNew = sqlite3DbRealloc(db, pList, \n         sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0]));\n    if( pNew==0 ){\n      goto no_mem;\n    }\n    pList = pNew;\n  }\n  pItem = &pList->a[pList->nExpr++];\n  assert( offsetof(struct ExprList_item,zEName)==sizeof(pItem->pExpr) );\n  assert( offsetof(struct ExprList_item,pExpr)==0 );\n  memset(&pItem->zEName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zEName));\n  pItem->pExpr = pExpr;\n  return pList;\n\nno_mem:     \n  /* Avoid leaking memory if malloc has failed. */\n  sqlite3ExprDelete(db, pExpr);\n  sqlite3ExprListDelete(db, pList);\n  return 0;\n}\n\n/*\n** pColumns and pExpr form a vector assignment which is part of the SET\n** clause of an UPDATE statement.  Like this:\n**\n**        (a,b,c) = (expr1,expr2,expr3)\n** Or:    (a,b,c) = (SELECT x,y,z FROM ....)\n**\n** For each term of the vector assignment, append new entries to the\n** expression list pList.  In the case of a subquery on the RHS, append\n** TK_SELECT_COLUMN expressions.\n*/\nSQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(\n  Parse *pParse,         /* Parsing context */\n  ExprList *pList,       /* List to which to append. Might be NULL */\n  IdList *pColumns,      /* List of names of LHS of the assignment */\n  Expr *pExpr            /* Vector expression to be appended. Might be NULL */\n){\n  sqlite3 *db = pParse->db;\n  int n;\n  int i;\n  int iFirst = pList ? pList->nExpr : 0;\n  /* pColumns can only be NULL due to an OOM but an OOM will cause an\n  ** exit prior to this routine being invoked */\n  if( NEVER(pColumns==0) ) goto vector_append_error;\n  if( pExpr==0 ) goto vector_append_error;\n\n  /* If the RHS is a vector, then we can immediately check to see that \n  ** the size of the RHS and LHS match.  But if the RHS is a SELECT, \n  ** wildcards (\"*\") in the result set of the SELECT must be expanded before\n  ** we can do the size check, so defer the size check until code generation.\n  */\n  if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){\n    sqlite3ErrorMsg(pParse, \"%d columns assigned %d values\",\n                    pColumns->nId, n);\n    goto vector_append_error;\n  }\n\n  for(i=0; i<pColumns->nId; i++){\n    Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);\n    assert( pSubExpr!=0 || db->mallocFailed );\n    assert( pSubExpr==0 || pSubExpr->iTable==0 );\n    if( pSubExpr==0 ) continue;\n    pSubExpr->iTable = pColumns->nId;\n    pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);\n    if( pList ){\n      assert( pList->nExpr==iFirst+i+1 );\n      pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName;\n      pColumns->a[i].zName = 0;\n    }\n  }\n\n  if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){\n    Expr *pFirst = pList->a[iFirst].pExpr;\n    assert( pFirst!=0 );\n    assert( pFirst->op==TK_SELECT_COLUMN );\n     \n    /* Store the SELECT statement in pRight so it will be deleted when\n    ** sqlite3ExprListDelete() is called */\n    pFirst->pRight = pExpr;\n    pExpr = 0;\n\n    /* Remember the size of the LHS in iTable so that we can check that\n    ** the RHS and LHS sizes match during code generation. */\n    pFirst->iTable = pColumns->nId;\n  }\n\nvector_append_error:\n  sqlite3ExprUnmapAndDelete(pParse, pExpr);\n  sqlite3IdListDelete(db, pColumns);\n  return pList;\n}\n\n/*\n** Set the sort order for the last element on the given ExprList.\n*/\nSQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){\n  struct ExprList_item *pItem;\n  if( p==0 ) return;\n  assert( p->nExpr>0 );\n\n  assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );\n  assert( iSortOrder==SQLITE_SO_UNDEFINED \n       || iSortOrder==SQLITE_SO_ASC \n       || iSortOrder==SQLITE_SO_DESC \n  );\n  assert( eNulls==SQLITE_SO_UNDEFINED \n       || eNulls==SQLITE_SO_ASC \n       || eNulls==SQLITE_SO_DESC \n  );\n\n  pItem = &p->a[p->nExpr-1];\n  assert( pItem->bNulls==0 );\n  if( iSortOrder==SQLITE_SO_UNDEFINED ){\n    iSortOrder = SQLITE_SO_ASC;\n  }\n  pItem->sortFlags = (u8)iSortOrder;\n\n  if( eNulls!=SQLITE_SO_UNDEFINED ){\n    pItem->bNulls = 1;\n    if( iSortOrder!=eNulls ){\n      pItem->sortFlags |= KEYINFO_ORDER_BIGNULL;\n    }\n  }\n}\n\n/*\n** Set the ExprList.a[].zEName element of the most recently added item\n** on the expression list.\n**\n** pList might be NULL following an OOM error.  But pName should never be\n** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag\n** is set.\n*/\nSQLITE_PRIVATE void sqlite3ExprListSetName(\n  Parse *pParse,          /* Parsing context */\n  ExprList *pList,        /* List to which to add the span. */\n  Token *pName,           /* Name to be added */\n  int dequote             /* True to cause the name to be dequoted */\n){\n  assert( pList!=0 || pParse->db->mallocFailed!=0 );\n  assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 );\n  if( pList ){\n    struct ExprList_item *pItem;\n    assert( pList->nExpr>0 );\n    pItem = &pList->a[pList->nExpr-1];\n    assert( pItem->zEName==0 );\n    assert( pItem->eEName==ENAME_NAME );\n    pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);\n    if( dequote ){\n      /* If dequote==0, then pName->z does not point to part of a DDL\n      ** statement handled by the parser. And so no token need be added\n      ** to the token-map.  */\n      sqlite3Dequote(pItem->zEName);\n      if( IN_RENAME_OBJECT ){\n        sqlite3RenameTokenMap(pParse, (void*)pItem->zEName, pName);\n      }\n    }\n  }\n}\n\n/*\n** Set the ExprList.a[].zSpan element of the most recently added item\n** on the expression list.\n**\n** pList might be NULL following an OOM error.  But pSpan should never be\n** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag\n** is set.\n*/\nSQLITE_PRIVATE void sqlite3ExprListSetSpan(\n  Parse *pParse,          /* Parsing context */\n  ExprList *pList,        /* List to which to add the span. */\n  const char *zStart,     /* Start of the span */\n  const char *zEnd        /* End of the span */\n){\n  sqlite3 *db = pParse->db;\n  assert( pList!=0 || db->mallocFailed!=0 );\n  if( pList ){\n    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];\n    assert( pList->nExpr>0 );\n    if( pItem->zEName==0 ){\n      pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd);\n      pItem->eEName = ENAME_SPAN;\n    }\n  }\n}\n\n/*\n** If the expression list pEList contains more than iLimit elements,\n** leave an error message in pParse.\n*/\nSQLITE_PRIVATE void sqlite3ExprListCheckLength(\n  Parse *pParse,\n  ExprList *pEList,\n  const char *zObject\n){\n  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];\n  testcase( pEList && pEList->nExpr==mx );\n  testcase( pEList && pEList->nExpr==mx+1 );\n  if( pEList && pEList->nExpr>mx ){\n    sqlite3ErrorMsg(pParse, \"too many columns in %s\", zObject);\n  }\n}\n\n/*\n** Delete an entire expression list.\n*/\nstatic SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){\n  int i = pList->nExpr;\n  struct ExprList_item *pItem =  pList->a;\n  assert( pList->nExpr>0 );\n  do{\n    sqlite3ExprDelete(db, pItem->pExpr);\n    sqlite3DbFree(db, pItem->zEName);\n    pItem++;\n  }while( --i>0 );\n  sqlite3DbFreeNN(db, pList);\n}\nSQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){\n  if( pList ) exprListDeleteNN(db, pList);\n}\n\n/*\n** Return the bitwise-OR of all Expr.flags fields in the given\n** ExprList.\n*/\nSQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){\n  int i;\n  u32 m = 0;\n  assert( pList!=0 );\n  for(i=0; i<pList->nExpr; i++){\n     Expr *pExpr = pList->a[i].pExpr;\n     assert( pExpr!=0 );\n     m |= pExpr->flags;\n  }\n  return m;\n}\n\n/*\n** This is a SELECT-node callback for the expression walker that\n** always \"fails\".  By \"fail\" in this case, we mean set\n** pWalker->eCode to zero and abort.\n**\n** This callback is used by multiple expression walkers.\n*/\nSQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  pWalker->eCode = 0;\n  return WRC_Abort;\n}\n\n/*\n** Check the input string to see if it is \"true\" or \"false\" (in any case).\n**\n**       If the string is....           Return\n**         \"true\"                         EP_IsTrue\n**         \"false\"                        EP_IsFalse\n**         anything else                  0\n*/\nSQLITE_PRIVATE u32 sqlite3IsTrueOrFalse(const char *zIn){\n  if( sqlite3StrICmp(zIn, \"true\")==0  ) return EP_IsTrue;\n  if( sqlite3StrICmp(zIn, \"false\")==0 ) return EP_IsFalse;\n  return 0;\n}\n\n\n/*\n** If the input expression is an ID with the name \"true\" or \"false\"\n** then convert it into an TK_TRUEFALSE term.  Return non-zero if\n** the conversion happened, and zero if the expression is unaltered.\n*/\nSQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr *pExpr){\n  u32 v;\n  assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );\n  if( !ExprHasProperty(pExpr, EP_Quoted)\n   && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0\n  ){\n    pExpr->op = TK_TRUEFALSE;\n    ExprSetProperty(pExpr, v);\n    return 1;\n  }\n  return 0;\n}\n\n/*\n** The argument must be a TK_TRUEFALSE Expr node.  Return 1 if it is TRUE\n** and 0 if it is FALSE.\n*/\nSQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr *pExpr){\n  pExpr = sqlite3ExprSkipCollate((Expr*)pExpr);\n  assert( pExpr->op==TK_TRUEFALSE );\n  assert( sqlite3StrICmp(pExpr->u.zToken,\"true\")==0\n       || sqlite3StrICmp(pExpr->u.zToken,\"false\")==0 );\n  return pExpr->u.zToken[4]==0;\n}\n\n/*\n** If pExpr is an AND or OR expression, try to simplify it by eliminating\n** terms that are always true or false.  Return the simplified expression.\n** Or return the original expression if no simplification is possible.\n**\n** Examples:\n**\n**     (x<10) AND true                =>   (x<10)\n**     (x<10) AND false               =>   false\n**     (x<10) AND (y=22 OR false)     =>   (x<10) AND (y=22)\n**     (x<10) AND (y=22 OR true)      =>   (x<10)\n**     (y=22) OR true                 =>   true\n*/\nSQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){\n  assert( pExpr!=0 );\n  if( pExpr->op==TK_AND || pExpr->op==TK_OR ){\n    Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);\n    Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);\n    if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){\n      pExpr = pExpr->op==TK_AND ? pRight : pLeft;\n    }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){\n      pExpr = pExpr->op==TK_AND ? pLeft : pRight;\n    }\n  }\n  return pExpr;\n}\n\n\n/*\n** These routines are Walker callbacks used to check expressions to\n** see if they are \"constant\" for some definition of constant.  The\n** Walker.eCode value determines the type of \"constant\" we are looking\n** for.\n**\n** These callback routines are used to implement the following:\n**\n**     sqlite3ExprIsConstant()                  pWalker->eCode==1\n**     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2\n**     sqlite3ExprIsTableConstant()             pWalker->eCode==3\n**     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5\n**\n** In all cases, the callbacks set Walker.eCode=0 and abort if the expression\n** is found to not be a constant.\n**\n** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT\n** expressions in a CREATE TABLE statement.  The Walker.eCode value is 5\n** when parsing an existing schema out of the sqlite_master table and 4\n** when processing a new CREATE TABLE statement.  A bound parameter raises\n** an error for new statements, but is silently converted\n** to NULL for existing schemas.  This allows sqlite_master tables that \n** contain a bound parameter because they were generated by older versions\n** of SQLite to be parsed by newer versions of SQLite without raising a\n** malformed schema error.\n*/\nstatic int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){\n\n  /* If pWalker->eCode is 2 then any term of the expression that comes from\n  ** the ON or USING clauses of a left join disqualifies the expression\n  ** from being considered constant. */\n  if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){\n    pWalker->eCode = 0;\n    return WRC_Abort;\n  }\n\n  switch( pExpr->op ){\n    /* Consider functions to be constant if all their arguments are constant\n    ** and either pWalker->eCode==4 or 5 or the function has the\n    ** SQLITE_FUNC_CONST flag. */\n    case TK_FUNCTION:\n      if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))\n       && !ExprHasProperty(pExpr, EP_WinFunc)\n      ){\n        if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL);\n        return WRC_Continue;\n      }else{\n        pWalker->eCode = 0;\n        return WRC_Abort;\n      }\n    case TK_ID:\n      /* Convert \"true\" or \"false\" in a DEFAULT clause into the\n      ** appropriate TK_TRUEFALSE operator */\n      if( sqlite3ExprIdToTrueFalse(pExpr) ){\n        return WRC_Prune;\n      }\n      /* Fall thru */\n    case TK_COLUMN:\n    case TK_AGG_FUNCTION:\n    case TK_AGG_COLUMN:\n      testcase( pExpr->op==TK_ID );\n      testcase( pExpr->op==TK_COLUMN );\n      testcase( pExpr->op==TK_AGG_FUNCTION );\n      testcase( pExpr->op==TK_AGG_COLUMN );\n      if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){\n        return WRC_Continue;\n      }\n      if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){\n        return WRC_Continue;\n      }\n      /* Fall through */\n    case TK_IF_NULL_ROW:\n    case TK_REGISTER:\n    case TK_DOT:\n      testcase( pExpr->op==TK_REGISTER );\n      testcase( pExpr->op==TK_IF_NULL_ROW );\n      testcase( pExpr->op==TK_DOT );\n      pWalker->eCode = 0;\n      return WRC_Abort;\n    case TK_VARIABLE:\n      if( pWalker->eCode==5 ){\n        /* Silently convert bound parameters that appear inside of CREATE\n        ** statements into a NULL when parsing the CREATE statement text out\n        ** of the sqlite_master table */\n        pExpr->op = TK_NULL;\n      }else if( pWalker->eCode==4 ){\n        /* A bound parameter in a CREATE statement that originates from\n        ** sqlite3_prepare() causes an error */\n        pWalker->eCode = 0;\n        return WRC_Abort;\n      }\n      /* Fall through */\n    default:\n      testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */\n      testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */\n      return WRC_Continue;\n  }\n}\nstatic int exprIsConst(Expr *p, int initFlag, int iCur){\n  Walker w;\n  w.eCode = initFlag;\n  w.xExprCallback = exprNodeIsConstant;\n  w.xSelectCallback = sqlite3SelectWalkFail;\n#ifdef SQLITE_DEBUG\n  w.xSelectCallback2 = sqlite3SelectWalkAssert2;\n#endif\n  w.u.iCur = iCur;\n  sqlite3WalkExpr(&w, p);\n  return w.eCode;\n}\n\n/*\n** Walk an expression tree.  Return non-zero if the expression is constant\n** and 0 if it involves variables or function calls.\n**\n** For the purposes of this function, a double-quoted string (ex: \"abc\")\n** is considered a variable but a single-quoted string (ex: 'abc') is\n** a constant.\n*/\nSQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){\n  return exprIsConst(p, 1, 0);\n}\n\n/*\n** Walk an expression tree.  Return non-zero if\n**\n**   (1) the expression is constant, and\n**   (2) the expression does originate in the ON or USING clause\n**       of a LEFT JOIN, and\n**   (3) the expression does not contain any EP_FixedCol TK_COLUMN\n**       operands created by the constant propagation optimization.\n**\n** When this routine returns true, it indicates that the expression\n** can be added to the pParse->pConstExpr list and evaluated once when\n** the prepared statement starts up.  See sqlite3ExprCodeRunJustOnce().\n*/\nSQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){\n  return exprIsConst(p, 2, 0);\n}\n\n/*\n** Walk an expression tree.  Return non-zero if the expression is constant\n** for any single row of the table with cursor iCur.  In other words, the\n** expression must not refer to any non-deterministic function nor any\n** table other than iCur.\n*/\nSQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){\n  return exprIsConst(p, 3, iCur);\n}\n\n\n/*\n** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().\n*/\nstatic int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){\n  ExprList *pGroupBy = pWalker->u.pGroupBy;\n  int i;\n\n  /* Check if pExpr is identical to any GROUP BY term. If so, consider\n  ** it constant.  */\n  for(i=0; i<pGroupBy->nExpr; i++){\n    Expr *p = pGroupBy->a[i].pExpr;\n    if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){\n      CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);\n      if( sqlite3IsBinary(pColl) ){\n        return WRC_Prune;\n      }\n    }\n  }\n\n  /* Check if pExpr is a sub-select. If so, consider it variable. */\n  if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n    pWalker->eCode = 0;\n    return WRC_Abort;\n  }\n\n  return exprNodeIsConstant(pWalker, pExpr);\n}\n\n/*\n** Walk the expression tree passed as the first argument. Return non-zero\n** if the expression consists entirely of constants or copies of terms \n** in pGroupBy that sort with the BINARY collation sequence.\n**\n** This routine is used to determine if a term of the HAVING clause can\n** be promoted into the WHERE clause.  In order for such a promotion to work,\n** the value of the HAVING clause term must be the same for all members of\n** a \"group\".  The requirement that the GROUP BY term must be BINARY\n** assumes that no other collating sequence will have a finer-grained\n** grouping than binary.  In other words (A=B COLLATE binary) implies\n** A=B in every other collating sequence.  The requirement that the\n** GROUP BY be BINARY is stricter than necessary.  It would also work\n** to promote HAVING clauses that use the same alternative collating\n** sequence as the GROUP BY term, but that is much harder to check,\n** alternative collating sequences are uncommon, and this is only an\n** optimization, so we take the easy way out and simply require the\n** GROUP BY to use the BINARY collating sequence.\n*/\nSQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){\n  Walker w;\n  w.eCode = 1;\n  w.xExprCallback = exprNodeIsConstantOrGroupBy;\n  w.xSelectCallback = 0;\n  w.u.pGroupBy = pGroupBy;\n  w.pParse = pParse;\n  sqlite3WalkExpr(&w, p);\n  return w.eCode;\n}\n\n/*\n** Walk an expression tree for the DEFAULT field of a column definition\n** in a CREATE TABLE statement.  Return non-zero if the expression is \n** acceptable for use as a DEFAULT.  That is to say, return non-zero if\n** the expression is constant or a function call with constant arguments.\n** Return and 0 if there are any variables.\n**\n** isInit is true when parsing from sqlite_master.  isInit is false when\n** processing a new CREATE TABLE statement.  When isInit is true, parameters\n** (such as ? or $abc) in the expression are converted into NULL.  When\n** isInit is false, parameters raise an error.  Parameters should not be\n** allowed in a CREATE TABLE statement, but some legacy versions of SQLite\n** allowed it, so we need to support it when reading sqlite_master for\n** backwards compatibility.\n**\n** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.\n**\n** For the purposes of this function, a double-quoted string (ex: \"abc\")\n** is considered a variable but a single-quoted string (ex: 'abc') is\n** a constant.\n*/\nSQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){\n  assert( isInit==0 || isInit==1 );\n  return exprIsConst(p, 4+isInit, 0);\n}\n\n#ifdef SQLITE_ENABLE_CURSOR_HINTS\n/*\n** Walk an expression tree.  Return 1 if the expression contains a\n** subquery of some kind.  Return 0 if there are no subqueries.\n*/\nSQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){\n  Walker w;\n  w.eCode = 1;\n  w.xExprCallback = sqlite3ExprWalkNoop;\n  w.xSelectCallback = sqlite3SelectWalkFail;\n#ifdef SQLITE_DEBUG\n  w.xSelectCallback2 = sqlite3SelectWalkAssert2;\n#endif\n  sqlite3WalkExpr(&w, p);\n  return w.eCode==0;\n}\n#endif\n\n/*\n** If the expression p codes a constant integer that is small enough\n** to fit in a 32-bit integer, return 1 and put the value of the integer\n** in *pValue.  If the expression is not an integer or if it is too big\n** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.\n*/\nSQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){\n  int rc = 0;\n  if( NEVER(p==0) ) return 0;  /* Used to only happen following on OOM */\n\n  /* If an expression is an integer literal that fits in a signed 32-bit\n  ** integer, then the EP_IntValue flag will have already been set */\n  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0\n           || sqlite3GetInt32(p->u.zToken, &rc)==0 );\n\n  if( p->flags & EP_IntValue ){\n    *pValue = p->u.iValue;\n    return 1;\n  }\n  switch( p->op ){\n    case TK_UPLUS: {\n      rc = sqlite3ExprIsInteger(p->pLeft, pValue);\n      break;\n    }\n    case TK_UMINUS: {\n      int v;\n      if( sqlite3ExprIsInteger(p->pLeft, &v) ){\n        assert( v!=(-2147483647-1) );\n        *pValue = -v;\n        rc = 1;\n      }\n      break;\n    }\n    default: break;\n  }\n  return rc;\n}\n\n/*\n** Return FALSE if there is no chance that the expression can be NULL.\n**\n** If the expression might be NULL or if the expression is too complex\n** to tell return TRUE.  \n**\n** This routine is used as an optimization, to skip OP_IsNull opcodes\n** when we know that a value cannot be NULL.  Hence, a false positive\n** (returning TRUE when in fact the expression can never be NULL) might\n** be a small performance hit but is otherwise harmless.  On the other\n** hand, a false negative (returning FALSE when the result could be NULL)\n** will likely result in an incorrect answer.  So when in doubt, return\n** TRUE.\n*/\nSQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){\n  u8 op;\n  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){\n    p = p->pLeft;\n  }\n  op = p->op;\n  if( op==TK_REGISTER ) op = p->op2;\n  switch( op ){\n    case TK_INTEGER:\n    case TK_STRING:\n    case TK_FLOAT:\n    case TK_BLOB:\n      return 0;\n    case TK_COLUMN:\n      return ExprHasProperty(p, EP_CanBeNull) ||\n             p->y.pTab==0 ||  /* Reference to column of index on expression */\n             (p->iColumn>=0\n              && ALWAYS(p->y.pTab->aCol!=0) /* Defense against OOM problems */\n              && p->y.pTab->aCol[p->iColumn].notNull==0);\n    default:\n      return 1;\n  }\n}\n\n/*\n** Return TRUE if the given expression is a constant which would be\n** unchanged by OP_Affinity with the affinity given in the second\n** argument.\n**\n** This routine is used to determine if the OP_Affinity operation\n** can be omitted.  When in doubt return FALSE.  A false negative\n** is harmless.  A false positive, however, can result in the wrong\n** answer.\n*/\nSQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){\n  u8 op;\n  int unaryMinus = 0;\n  if( aff==SQLITE_AFF_BLOB ) return 1;\n  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){\n    if( p->op==TK_UMINUS ) unaryMinus = 1;\n    p = p->pLeft;\n  }\n  op = p->op;\n  if( op==TK_REGISTER ) op = p->op2;\n  switch( op ){\n    case TK_INTEGER: {\n      return aff>=SQLITE_AFF_NUMERIC;\n    }\n    case TK_FLOAT: {\n      return aff>=SQLITE_AFF_NUMERIC;\n    }\n    case TK_STRING: {\n      return !unaryMinus && aff==SQLITE_AFF_TEXT;\n    }\n    case TK_BLOB: {\n      return !unaryMinus;\n    }\n    case TK_COLUMN: {\n      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */\n      return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;\n    }\n    default: {\n      return 0;\n    }\n  }\n}\n\n/*\n** Return TRUE if the given string is a row-id column name.\n*/\nSQLITE_PRIVATE int sqlite3IsRowid(const char *z){\n  if( sqlite3StrICmp(z, \"_ROWID_\")==0 ) return 1;\n  if( sqlite3StrICmp(z, \"ROWID\")==0 ) return 1;\n  if( sqlite3StrICmp(z, \"OID\")==0 ) return 1;\n  return 0;\n}\n\n/*\n** pX is the RHS of an IN operator.  If pX is a SELECT statement \n** that can be simplified to a direct table access, then return\n** a pointer to the SELECT statement.  If pX is not a SELECT statement,\n** or if the SELECT statement needs to be manifested into a transient\n** table, then return NULL.\n*/\n#ifndef SQLITE_OMIT_SUBQUERY\nstatic Select *isCandidateForInOpt(Expr *pX){\n  Select *p;\n  SrcList *pSrc;\n  ExprList *pEList;\n  Table *pTab;\n  int i;\n  if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */\n  if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */\n  p = pX->x.pSelect;\n  if( p->pPrior ) return 0;              /* Not a compound SELECT */\n  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){\n    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );\n    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );\n    return 0; /* No DISTINCT keyword and no aggregate functions */\n  }\n  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */\n  if( p->pLimit ) return 0;              /* Has no LIMIT clause */\n  if( p->pWhere ) return 0;              /* Has no WHERE clause */\n  pSrc = p->pSrc;\n  assert( pSrc!=0 );\n  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */\n  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */\n  pTab = pSrc->a[0].pTab;\n  assert( pTab!=0 );\n  assert( pTab->pSelect==0 );            /* FROM clause is not a view */\n  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */\n  pEList = p->pEList;\n  assert( pEList!=0 );\n  /* All SELECT results must be columns. */\n  for(i=0; i<pEList->nExpr; i++){\n    Expr *pRes = pEList->a[i].pExpr;\n    if( pRes->op!=TK_COLUMN ) return 0;\n    assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */\n  }\n  return p;\n}\n#endif /* SQLITE_OMIT_SUBQUERY */\n\n#ifndef SQLITE_OMIT_SUBQUERY\n/*\n** Generate code that checks the left-most column of index table iCur to see if\n** it contains any NULL entries.  Cause the register at regHasNull to be set\n** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull\n** to be set to NULL if iCur contains one or more NULL values.\n*/\nstatic void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){\n  int addr1;\n  sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);\n  addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);\n  sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);\n  sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);\n  VdbeComment((v, \"first_entry_in(%d)\", iCur));\n  sqlite3VdbeJumpHere(v, addr1);\n}\n#endif\n\n\n#ifndef SQLITE_OMIT_SUBQUERY\n/*\n** The argument is an IN operator with a list (not a subquery) on the \n** right-hand side.  Return TRUE if that list is constant.\n*/\nstatic int sqlite3InRhsIsConstant(Expr *pIn){\n  Expr *pLHS;\n  int res;\n  assert( !ExprHasProperty(pIn, EP_xIsSelect) );\n  pLHS = pIn->pLeft;\n  pIn->pLeft = 0;\n  res = sqlite3ExprIsConstant(pIn);\n  pIn->pLeft = pLHS;\n  return res;\n}\n#endif\n\n/*\n** This function is used by the implementation of the IN (...) operator.\n** The pX parameter is the expression on the RHS of the IN operator, which\n** might be either a list of expressions or a subquery.\n**\n** The job of this routine is to find or create a b-tree object that can\n** be used either to test for membership in the RHS set or to iterate through\n** all members of the RHS set, skipping duplicates.\n**\n** A cursor is opened on the b-tree object that is the RHS of the IN operator\n** and pX->iTable is set to the index of that cursor.\n**\n** The returned value of this function indicates the b-tree type, as follows:\n**\n**   IN_INDEX_ROWID      - The cursor was opened on a database table.\n**   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.\n**   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.\n**   IN_INDEX_EPH        - The cursor was opened on a specially created and\n**                         populated epheremal table.\n**   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be\n**                         implemented as a sequence of comparisons.\n**\n** An existing b-tree might be used if the RHS expression pX is a simple\n** subquery such as:\n**\n**     SELECT <column1>, <column2>... FROM <table>\n**\n** If the RHS of the IN operator is a list or a more complex subquery, then\n** an ephemeral table might need to be generated from the RHS and then\n** pX->iTable made to point to the ephemeral table instead of an\n** existing table.\n**\n** The inFlags parameter must contain, at a minimum, one of the bits\n** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both.  If inFlags contains\n** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast\n** membership test.  When the IN_INDEX_LOOP bit is set, the IN index will\n** be used to loop over all values of the RHS of the IN operator.\n**\n** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate\n** through the set members) then the b-tree must not contain duplicates.\n** An epheremal table will be created unless the selected columns are guaranteed\n** to be unique - either because it is an INTEGER PRIMARY KEY or due to\n** a UNIQUE constraint or index.\n**\n** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used \n** for fast set membership tests) then an epheremal table must \n** be used unless <columns> is a single INTEGER PRIMARY KEY column or an \n** index can be found with the specified <columns> as its left-most.\n**\n** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and\n** if the RHS of the IN operator is a list (not a subquery) then this\n** routine might decide that creating an ephemeral b-tree for membership\n** testing is too expensive and return IN_INDEX_NOOP.  In that case, the\n** calling routine should implement the IN operator using a sequence\n** of Eq or Ne comparison operations.\n**\n** When the b-tree is being used for membership tests, the calling function\n** might need to know whether or not the RHS side of the IN operator\n** contains a NULL.  If prRhsHasNull is not a NULL pointer and \n** if there is any chance that the (...) might contain a NULL value at\n** runtime, then a register is allocated and the register number written\n** to *prRhsHasNull. If there is no chance that the (...) contains a\n** NULL value, then *prRhsHasNull is left unchanged.\n**\n** If a register is allocated and its location stored in *prRhsHasNull, then\n** the value in that register will be NULL if the b-tree contains one or more\n** NULL values, and it will be some non-NULL value if the b-tree contains no\n** NULL values.\n**\n** If the aiMap parameter is not NULL, it must point to an array containing\n** one element for each column returned by the SELECT statement on the RHS\n** of the IN(...) operator. The i'th entry of the array is populated with the\n** offset of the index column that matches the i'th column returned by the\n** SELECT. For example, if the expression and selected index are:\n**\n**   (?,?,?) IN (SELECT a, b, c FROM t1)\n**   CREATE INDEX i1 ON t1(b, c, a);\n**\n** then aiMap[] is populated with {2, 0, 1}.\n*/\n#ifndef SQLITE_OMIT_SUBQUERY\nSQLITE_PRIVATE int sqlite3FindInIndex(\n  Parse *pParse,             /* Parsing context */\n  Expr *pX,                  /* The IN expression */\n  u32 inFlags,               /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */\n  int *prRhsHasNull,         /* Register holding NULL status.  See notes */\n  int *aiMap,                /* Mapping from Index fields to RHS fields */\n  int *piTab                 /* OUT: index to use */\n){\n  Select *p;                            /* SELECT to the right of IN operator */\n  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */\n  int iTab = pParse->nTab++;            /* Cursor of the RHS table */\n  int mustBeUnique;                     /* True if RHS must be unique */\n  Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */\n\n  assert( pX->op==TK_IN );\n  mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;\n\n  /* If the RHS of this IN(...) operator is a SELECT, and if it matters \n  ** whether or not the SELECT result contains NULL values, check whether\n  ** or not NULL is actually possible (it may not be, for example, due \n  ** to NOT NULL constraints in the schema). If no NULL values are possible,\n  ** set prRhsHasNull to 0 before continuing.  */\n  if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){\n    int i;\n    ExprList *pEList = pX->x.pSelect->pEList;\n    for(i=0; i<pEList->nExpr; i++){\n      if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;\n    }\n    if( i==pEList->nExpr ){\n      prRhsHasNull = 0;\n    }\n  }\n\n  /* Check to see if an existing table or index can be used to\n  ** satisfy the query.  This is preferable to generating a new \n  ** ephemeral table.  */\n  if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){\n    sqlite3 *db = pParse->db;              /* Database connection */\n    Table *pTab;                           /* Table <table>. */\n    i16 iDb;                               /* Database idx for pTab */\n    ExprList *pEList = p->pEList;\n    int nExpr = pEList->nExpr;\n\n    assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */\n    assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */\n    assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */\n    pTab = p->pSrc->a[0].pTab;\n\n    /* Code an OP_Transaction and OP_TableLock for <table>. */\n    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n    sqlite3CodeVerifySchema(pParse, iDb);\n    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);\n\n    assert(v);  /* sqlite3GetVdbe() has always been previously called */\n    if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){\n      /* The \"x IN (SELECT rowid FROM table)\" case */\n      int iAddr = sqlite3VdbeAddOp0(v, OP_Once);\n      VdbeCoverage(v);\n\n      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);\n      eType = IN_INDEX_ROWID;\n      ExplainQueryPlan((pParse, 0,\n            \"USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR\",pTab->zName));\n      sqlite3VdbeJumpHere(v, iAddr);\n    }else{\n      Index *pIdx;                         /* Iterator variable */\n      int affinity_ok = 1;\n      int i;\n\n      /* Check that the affinity that will be used to perform each \n      ** comparison is the same as the affinity of each column in table\n      ** on the RHS of the IN operator.  If it not, it is not possible to\n      ** use any index of the RHS table.  */\n      for(i=0; i<nExpr && affinity_ok; i++){\n        Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);\n        int iCol = pEList->a[i].pExpr->iColumn;\n        char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */\n        char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);\n        testcase( cmpaff==SQLITE_AFF_BLOB );\n        testcase( cmpaff==SQLITE_AFF_TEXT );\n        switch( cmpaff ){\n          case SQLITE_AFF_BLOB:\n            break;\n          case SQLITE_AFF_TEXT:\n            /* sqlite3CompareAffinity() only returns TEXT if one side or the\n            ** other has no affinity and the other side is TEXT.  Hence,\n            ** the only way for cmpaff to be TEXT is for idxaff to be TEXT\n            ** and for the term on the LHS of the IN to have no affinity. */\n            assert( idxaff==SQLITE_AFF_TEXT );\n            break;\n          default:\n            affinity_ok = sqlite3IsNumericAffinity(idxaff);\n        }\n      }\n\n      if( affinity_ok ){\n        /* Search for an existing index that will work for this IN operator */\n        for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){\n          Bitmask colUsed;      /* Columns of the index used */\n          Bitmask mCol;         /* Mask for the current column */\n          if( pIdx->nColumn<nExpr ) continue;\n          if( pIdx->pPartIdxWhere!=0 ) continue;\n          /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute\n          ** BITMASK(nExpr) without overflowing */\n          testcase( pIdx->nColumn==BMS-2 );\n          testcase( pIdx->nColumn==BMS-1 );\n          if( pIdx->nColumn>=BMS-1 ) continue;\n          if( mustBeUnique ){\n            if( pIdx->nKeyCol>nExpr\n             ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))\n            ){\n              continue;  /* This index is not unique over the IN RHS columns */\n            }\n          }\n  \n          colUsed = 0;   /* Columns of index used so far */\n          for(i=0; i<nExpr; i++){\n            Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);\n            Expr *pRhs = pEList->a[i].pExpr;\n            CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);\n            int j;\n  \n            assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );\n            for(j=0; j<nExpr; j++){\n              if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;\n              assert( pIdx->azColl[j] );\n              if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){\n                continue;\n              }\n              break;\n            }\n            if( j==nExpr ) break;\n            mCol = MASKBIT(j);\n            if( mCol & colUsed ) break; /* Each column used only once */\n            colUsed |= mCol;\n            if( aiMap ) aiMap[i] = j;\n          }\n  \n          assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );\n          if( colUsed==(MASKBIT(nExpr)-1) ){\n            /* If we reach this point, that means the index pIdx is usable */\n            int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);\n            ExplainQueryPlan((pParse, 0,\n                              \"USING INDEX %s FOR IN-OPERATOR\",pIdx->zName));\n            sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);\n            sqlite3VdbeSetP4KeyInfo(pParse, pIdx);\n            VdbeComment((v, \"%s\", pIdx->zName));\n            assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );\n            eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];\n  \n            if( prRhsHasNull ){\n#ifdef SQLITE_ENABLE_COLUMN_USED_MASK\n              i64 mask = (1<<nExpr)-1;\n              sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, \n                  iTab, 0, 0, (u8*)&mask, P4_INT64);\n#endif\n              *prRhsHasNull = ++pParse->nMem;\n              if( nExpr==1 ){\n                sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);\n              }\n            }\n            sqlite3VdbeJumpHere(v, iAddr);\n          }\n        } /* End loop over indexes */\n      } /* End if( affinity_ok ) */\n    } /* End if not an rowid index */\n  } /* End attempt to optimize using an index */\n\n  /* If no preexisting index is available for the IN clause\n  ** and IN_INDEX_NOOP is an allowed reply\n  ** and the RHS of the IN operator is a list, not a subquery\n  ** and the RHS is not constant or has two or fewer terms,\n  ** then it is not worth creating an ephemeral table to evaluate\n  ** the IN operator so return IN_INDEX_NOOP.\n  */\n  if( eType==0\n   && (inFlags & IN_INDEX_NOOP_OK)\n   && !ExprHasProperty(pX, EP_xIsSelect)\n   && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)\n  ){\n    eType = IN_INDEX_NOOP;\n  }\n\n  if( eType==0 ){\n    /* Could not find an existing table or index to use as the RHS b-tree.\n    ** We will have to generate an ephemeral table to do the job.\n    */\n    u32 savedNQueryLoop = pParse->nQueryLoop;\n    int rMayHaveNull = 0;\n    eType = IN_INDEX_EPH;\n    if( inFlags & IN_INDEX_LOOP ){\n      pParse->nQueryLoop = 0;\n    }else if( prRhsHasNull ){\n      *prRhsHasNull = rMayHaveNull = ++pParse->nMem;\n    }\n    assert( pX->op==TK_IN );\n    sqlite3CodeRhsOfIN(pParse, pX, iTab);\n    if( rMayHaveNull ){\n      sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);\n    }\n    pParse->nQueryLoop = savedNQueryLoop;\n  }\n\n  if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){\n    int i, n;\n    n = sqlite3ExprVectorSize(pX->pLeft);\n    for(i=0; i<n; i++) aiMap[i] = i;\n  }\n  *piTab = iTab;\n  return eType;\n}\n#endif\n\n#ifndef SQLITE_OMIT_SUBQUERY\n/*\n** Argument pExpr is an (?, ?...) IN(...) expression. This \n** function allocates and returns a nul-terminated string containing \n** the affinities to be used for each column of the comparison.\n**\n** It is the responsibility of the caller to ensure that the returned\n** string is eventually freed using sqlite3DbFree().\n*/\nstatic char *exprINAffinity(Parse *pParse, Expr *pExpr){\n  Expr *pLeft = pExpr->pLeft;\n  int nVal = sqlite3ExprVectorSize(pLeft);\n  Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;\n  char *zRet;\n\n  assert( pExpr->op==TK_IN );\n  zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);\n  if( zRet ){\n    int i;\n    for(i=0; i<nVal; i++){\n      Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);\n      char a = sqlite3ExprAffinity(pA);\n      if( pSelect ){\n        zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);\n      }else{\n        zRet[i] = a;\n      }\n    }\n    zRet[nVal] = '\\0';\n  }\n  return zRet;\n}\n#endif\n\n#ifndef SQLITE_OMIT_SUBQUERY\n/*\n** Load the Parse object passed as the first argument with an error \n** message of the form:\n**\n**   \"sub-select returns N columns - expected M\"\n*/   \nSQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){\n  if( pParse->nErr==0 ){\n    const char *zFmt = \"sub-select returns %d columns - expected %d\";\n    sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);\n  }\n}\n#endif\n\n/*\n** Expression pExpr is a vector that has been used in a context where\n** it is not permitted. If pExpr is a sub-select vector, this routine \n** loads the Parse object with a message of the form:\n**\n**   \"sub-select returns N columns - expected 1\"\n**\n** Or, if it is a regular scalar vector:\n**\n**   \"row value misused\"\n*/   \nSQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){\n#ifndef SQLITE_OMIT_SUBQUERY\n  if( pExpr->flags & EP_xIsSelect ){\n    sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);\n  }else\n#endif\n  {\n    sqlite3ErrorMsg(pParse, \"row value misused\");\n  }\n}\n\n#ifndef SQLITE_OMIT_SUBQUERY\n/*\n** Generate code that will construct an ephemeral table containing all terms\n** in the RHS of an IN operator.  The IN operator can be in either of two\n** forms:\n**\n**     x IN (4,5,11)              -- IN operator with list on right-hand side\n**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right\n**\n** The pExpr parameter is the IN operator.  The cursor number for the\n** constructed ephermeral table is returned.  The first time the ephemeral\n** table is computed, the cursor number is also stored in pExpr->iTable,\n** however the cursor number returned might not be the same, as it might\n** have been duplicated using OP_OpenDup.\n**\n** If the LHS expression (\"x\" in the examples) is a column value, or\n** the SELECT statement returns a column value, then the affinity of that\n** column is used to build the index keys. If both 'x' and the\n** SELECT... statement are columns, then numeric affinity is used\n** if either column has NUMERIC or INTEGER affinity. If neither\n** 'x' nor the SELECT... statement are columns, then numeric affinity\n** is used.\n*/\nSQLITE_PRIVATE void sqlite3CodeRhsOfIN(\n  Parse *pParse,          /* Parsing context */\n  Expr *pExpr,            /* The IN operator */\n  int iTab                /* Use this cursor number */\n){\n  int addrOnce = 0;           /* Address of the OP_Once instruction at top */\n  int addr;                   /* Address of OP_OpenEphemeral instruction */\n  Expr *pLeft;                /* the LHS of the IN operator */\n  KeyInfo *pKeyInfo = 0;      /* Key information */\n  int nVal;                   /* Size of vector pLeft */\n  Vdbe *v;                    /* The prepared statement under construction */\n\n  v = pParse->pVdbe;\n  assert( v!=0 );\n\n  /* The evaluation of the IN must be repeated every time it\n  ** is encountered if any of the following is true:\n  **\n  **    *  The right-hand side is a correlated subquery\n  **    *  The right-hand side is an expression list containing variables\n  **    *  We are inside a trigger\n  **\n  ** If all of the above are false, then we can compute the RHS just once\n  ** and reuse it many names.\n  */\n  if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){\n    /* Reuse of the RHS is allowed */\n    /* If this routine has already been coded, but the previous code\n    ** might not have been invoked yet, so invoke it now as a subroutine. \n    */\n    if( ExprHasProperty(pExpr, EP_Subrtn) ){\n      addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);\n      if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n        ExplainQueryPlan((pParse, 0, \"REUSE LIST SUBQUERY %d\",\n              pExpr->x.pSelect->selId));\n      }\n      sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,\n                        pExpr->y.sub.iAddr);\n      sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);\n      sqlite3VdbeJumpHere(v, addrOnce);\n      return;\n    }\n\n    /* Begin coding the subroutine */\n    ExprSetProperty(pExpr, EP_Subrtn);\n    assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );\n    pExpr->y.sub.regReturn = ++pParse->nMem;\n    pExpr->y.sub.iAddr =\n      sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;\n    VdbeComment((v, \"return address\"));\n\n    addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);\n  }\n\n  /* Check to see if this is a vector IN operator */\n  pLeft = pExpr->pLeft;\n  nVal = sqlite3ExprVectorSize(pLeft);\n\n  /* Construct the ephemeral table that will contain the content of\n  ** RHS of the IN operator.\n  */\n  pExpr->iTable = iTab;\n  addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);\n#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS\n  if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n    VdbeComment((v, \"Result of SELECT %u\", pExpr->x.pSelect->selId));\n  }else{\n    VdbeComment((v, \"RHS of IN operator\"));\n  }\n#endif\n  pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);\n\n  if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n    /* Case 1:     expr IN (SELECT ...)\n    **\n    ** Generate code to write the results of the select into the temporary\n    ** table allocated and opened above.\n    */\n    Select *pSelect = pExpr->x.pSelect;\n    ExprList *pEList = pSelect->pEList;\n\n    ExplainQueryPlan((pParse, 1, \"%sLIST SUBQUERY %d\",\n        addrOnce?\"\":\"CORRELATED \", pSelect->selId\n    ));\n    /* If the LHS and RHS of the IN operator do not match, that\n    ** error will have been caught long before we reach this point. */\n    if( ALWAYS(pEList->nExpr==nVal) ){\n      SelectDest dest;\n      int i;\n      sqlite3SelectDestInit(&dest, SRT_Set, iTab);\n      dest.zAffSdst = exprINAffinity(pParse, pExpr);\n      pSelect->iLimit = 0;\n      testcase( pSelect->selFlags & SF_Distinct );\n      testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */\n      if( sqlite3Select(pParse, pSelect, &dest) ){\n        sqlite3DbFree(pParse->db, dest.zAffSdst);\n        sqlite3KeyInfoUnref(pKeyInfo);\n        return;\n      }\n      sqlite3DbFree(pParse->db, dest.zAffSdst);\n      assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */\n      assert( pEList!=0 );\n      assert( pEList->nExpr>0 );\n      assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );\n      for(i=0; i<nVal; i++){\n        Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);\n        pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(\n            pParse, p, pEList->a[i].pExpr\n        );\n      }\n    }\n  }else if( ALWAYS(pExpr->x.pList!=0) ){\n    /* Case 2:     expr IN (exprlist)\n    **\n    ** For each expression, build an index key from the evaluation and\n    ** store it in the temporary table. If <expr> is a column, then use\n    ** that columns affinity when building index keys. If <expr> is not\n    ** a column, use numeric affinity.\n    */\n    char affinity;            /* Affinity of the LHS of the IN */\n    int i;\n    ExprList *pList = pExpr->x.pList;\n    struct ExprList_item *pItem;\n    int r1, r2;\n    affinity = sqlite3ExprAffinity(pLeft);\n    if( affinity<=SQLITE_AFF_NONE ){\n      affinity = SQLITE_AFF_BLOB;\n    }else if( affinity==SQLITE_AFF_REAL ){\n      affinity = SQLITE_AFF_NUMERIC;\n    }\n    if( pKeyInfo ){\n      assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );\n      pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);\n    }\n\n    /* Loop through each expression in <exprlist>. */\n    r1 = sqlite3GetTempReg(pParse);\n    r2 = sqlite3GetTempReg(pParse);\n    for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){\n      Expr *pE2 = pItem->pExpr;\n\n      /* If the expression is not constant then we will need to\n      ** disable the test that was generated above that makes sure\n      ** this code only executes once.  Because for a non-constant\n      ** expression we need to rerun this code each time.\n      */\n      if( addrOnce && !sqlite3ExprIsConstant(pE2) ){\n        sqlite3VdbeChangeToNoop(v, addrOnce);\n        ExprClearProperty(pExpr, EP_Subrtn);\n        addrOnce = 0;\n      }\n\n      /* Evaluate the expression and insert it into the temp table */\n      sqlite3ExprCode(pParse, pE2, r1);\n      sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);\n      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1);\n    }\n    sqlite3ReleaseTempReg(pParse, r1);\n    sqlite3ReleaseTempReg(pParse, r2);\n  }\n  if( pKeyInfo ){\n    sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);\n  }\n  if( addrOnce ){\n    sqlite3VdbeJumpHere(v, addrOnce);\n    /* Subroutine return */\n    sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);\n    sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);\n    sqlite3ClearTempRegCache(pParse);\n  }\n}\n#endif /* SQLITE_OMIT_SUBQUERY */\n\n/*\n** Generate code for scalar subqueries used as a subquery expression\n** or EXISTS operator:\n**\n**     (SELECT a FROM b)          -- subquery\n**     EXISTS (SELECT a FROM b)   -- EXISTS subquery\n**\n** The pExpr parameter is the SELECT or EXISTS operator to be coded.\n**\n** Return the register that holds the result.  For a multi-column SELECT, \n** the result is stored in a contiguous array of registers and the\n** return value is the register of the left-most result column.\n** Return 0 if an error occurs.\n*/\n#ifndef SQLITE_OMIT_SUBQUERY\nSQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){\n  int addrOnce = 0;           /* Address of OP_Once at top of subroutine */\n  int rReg = 0;               /* Register storing resulting */\n  Select *pSel;               /* SELECT statement to encode */\n  SelectDest dest;            /* How to deal with SELECT result */\n  int nReg;                   /* Registers to allocate */\n  Expr *pLimit;               /* New limit expression */\n\n  Vdbe *v = pParse->pVdbe;\n  assert( v!=0 );\n  testcase( pExpr->op==TK_EXISTS );\n  testcase( pExpr->op==TK_SELECT );\n  assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );\n  assert( ExprHasProperty(pExpr, EP_xIsSelect) );\n  pSel = pExpr->x.pSelect;\n\n  /* The evaluation of the EXISTS/SELECT must be repeated every time it\n  ** is encountered if any of the following is true:\n  **\n  **    *  The right-hand side is a correlated subquery\n  **    *  The right-hand side is an expression list containing variables\n  **    *  We are inside a trigger\n  **\n  ** If all of the above are false, then we can run this code just once\n  ** save the results, and reuse the same result on subsequent invocations.\n  */\n  if( !ExprHasProperty(pExpr, EP_VarSelect) ){\n    /* If this routine has already been coded, then invoke it as a\n    ** subroutine. */\n    if( ExprHasProperty(pExpr, EP_Subrtn) ){\n      ExplainQueryPlan((pParse, 0, \"REUSE SUBQUERY %d\", pSel->selId));\n      sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,\n                        pExpr->y.sub.iAddr);\n      return pExpr->iTable;\n    }\n\n    /* Begin coding the subroutine */\n    ExprSetProperty(pExpr, EP_Subrtn);\n    pExpr->y.sub.regReturn = ++pParse->nMem;\n    pExpr->y.sub.iAddr =\n      sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;\n    VdbeComment((v, \"return address\"));\n\n    addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);\n  }\n  \n  /* For a SELECT, generate code to put the values for all columns of\n  ** the first row into an array of registers and return the index of\n  ** the first register.\n  **\n  ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)\n  ** into a register and return that register number.\n  **\n  ** In both cases, the query is augmented with \"LIMIT 1\".  Any \n  ** preexisting limit is discarded in place of the new LIMIT 1.\n  */\n  ExplainQueryPlan((pParse, 1, \"%sSCALAR SUBQUERY %d\",\n        addrOnce?\"\":\"CORRELATED \", pSel->selId));\n  nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;\n  sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);\n  pParse->nMem += nReg;\n  if( pExpr->op==TK_SELECT ){\n    dest.eDest = SRT_Mem;\n    dest.iSdst = dest.iSDParm;\n    dest.nSdst = nReg;\n    sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);\n    VdbeComment((v, \"Init subquery result\"));\n  }else{\n    dest.eDest = SRT_Exists;\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);\n    VdbeComment((v, \"Init EXISTS result\"));\n  }\n  if( pSel->pLimit ){\n    /* The subquery already has a limit.  If the pre-existing limit is X\n    ** then make the new limit X<>0 so that the new limit is either 1 or 0 */\n    sqlite3 *db = pParse->db;\n    pLimit = sqlite3Expr(db, TK_INTEGER, \"0\");\n    if( pLimit ){\n      pLimit->affExpr = SQLITE_AFF_NUMERIC;\n      pLimit = sqlite3PExpr(pParse, TK_NE,\n                            sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);\n    }\n    sqlite3ExprDelete(db, pSel->pLimit->pLeft);\n    pSel->pLimit->pLeft = pLimit;\n  }else{\n    /* If there is no pre-existing limit add a limit of 1 */\n    pLimit = sqlite3Expr(pParse->db, TK_INTEGER, \"1\");\n    pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);\n  }\n  pSel->iLimit = 0;\n  if( sqlite3Select(pParse, pSel, &dest) ){\n    return 0;\n  }\n  pExpr->iTable = rReg = dest.iSDParm;\n  ExprSetVVAProperty(pExpr, EP_NoReduce);\n  if( addrOnce ){\n    sqlite3VdbeJumpHere(v, addrOnce);\n\n    /* Subroutine return */\n    sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);\n    sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);\n    sqlite3ClearTempRegCache(pParse);\n  }\n\n  return rReg;\n}\n#endif /* SQLITE_OMIT_SUBQUERY */\n\n#ifndef SQLITE_OMIT_SUBQUERY\n/*\n** Expr pIn is an IN(...) expression. This function checks that the \n** sub-select on the RHS of the IN() operator has the same number of \n** columns as the vector on the LHS. Or, if the RHS of the IN() is not \n** a sub-query, that the LHS is a vector of size 1.\n*/\nSQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){\n  int nVector = sqlite3ExprVectorSize(pIn->pLeft);\n  if( (pIn->flags & EP_xIsSelect) ){\n    if( nVector!=pIn->x.pSelect->pEList->nExpr ){\n      sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);\n      return 1;\n    }\n  }else if( nVector!=1 ){\n    sqlite3VectorErrorMsg(pParse, pIn->pLeft);\n    return 1;\n  }\n  return 0;\n}\n#endif\n\n#ifndef SQLITE_OMIT_SUBQUERY\n/*\n** Generate code for an IN expression.\n**\n**      x IN (SELECT ...)\n**      x IN (value, value, ...)\n**\n** The left-hand side (LHS) is a scalar or vector expression.  The \n** right-hand side (RHS) is an array of zero or more scalar values, or a\n** subquery.  If the RHS is a subquery, the number of result columns must\n** match the number of columns in the vector on the LHS.  If the RHS is\n** a list of values, the LHS must be a scalar. \n**\n** The IN operator is true if the LHS value is contained within the RHS.\n** The result is false if the LHS is definitely not in the RHS.  The \n** result is NULL if the presence of the LHS in the RHS cannot be \n** determined due to NULLs.\n**\n** This routine generates code that jumps to destIfFalse if the LHS is not \n** contained within the RHS.  If due to NULLs we cannot determine if the LHS\n** is contained in the RHS then jump to destIfNull.  If the LHS is contained\n** within the RHS then fall through.\n**\n** See the separate in-operator.md documentation file in the canonical\n** SQLite source tree for additional information.\n*/\nstatic void sqlite3ExprCodeIN(\n  Parse *pParse,        /* Parsing and code generating context */\n  Expr *pExpr,          /* The IN expression */\n  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */\n  int destIfNull        /* Jump here if the results are unknown due to NULLs */\n){\n  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */\n  int eType;            /* Type of the RHS */\n  int rLhs;             /* Register(s) holding the LHS values */\n  int rLhsOrig;         /* LHS values prior to reordering by aiMap[] */\n  Vdbe *v;              /* Statement under construction */\n  int *aiMap = 0;       /* Map from vector field to index column */\n  char *zAff = 0;       /* Affinity string for comparisons */\n  int nVector;          /* Size of vectors for this IN operator */\n  int iDummy;           /* Dummy parameter to exprCodeVector() */\n  Expr *pLeft;          /* The LHS of the IN operator */\n  int i;                /* loop counter */\n  int destStep2;        /* Where to jump when NULLs seen in step 2 */\n  int destStep6 = 0;    /* Start of code for Step 6 */\n  int addrTruthOp;      /* Address of opcode that determines the IN is true */\n  int destNotNull;      /* Jump here if a comparison is not true in step 6 */\n  int addrTop;          /* Top of the step-6 loop */ \n  int iTab = 0;         /* Index to use */\n  u8 okConstFactor = pParse->okConstFactor;\n\n  assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );\n  pLeft = pExpr->pLeft;\n  if( sqlite3ExprCheckIN(pParse, pExpr) ) return;\n  zAff = exprINAffinity(pParse, pExpr);\n  nVector = sqlite3ExprVectorSize(pExpr->pLeft);\n  aiMap = (int*)sqlite3DbMallocZero(\n      pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1\n  );\n  if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;\n\n  /* Attempt to compute the RHS. After this step, if anything other than\n  ** IN_INDEX_NOOP is returned, the table opened with cursor iTab\n  ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,\n  ** the RHS has not yet been coded.  */\n  v = pParse->pVdbe;\n  assert( v!=0 );       /* OOM detected prior to this routine */\n  VdbeNoopComment((v, \"begin IN expr\"));\n  eType = sqlite3FindInIndex(pParse, pExpr,\n                             IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,\n                             destIfFalse==destIfNull ? 0 : &rRhsHasNull,\n                             aiMap, &iTab);\n\n  assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH\n       || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC \n  );\n#ifdef SQLITE_DEBUG\n  /* Confirm that aiMap[] contains nVector integer values between 0 and\n  ** nVector-1. */\n  for(i=0; i<nVector; i++){\n    int j, cnt;\n    for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;\n    assert( cnt==1 );\n  }\n#endif\n\n  /* Code the LHS, the <expr> from \"<expr> IN (...)\". If the LHS is a \n  ** vector, then it is stored in an array of nVector registers starting \n  ** at r1.\n  **\n  ** sqlite3FindInIndex() might have reordered the fields of the LHS vector\n  ** so that the fields are in the same order as an existing index.   The\n  ** aiMap[] array contains a mapping from the original LHS field order to\n  ** the field order that matches the RHS index.\n  **\n  ** Avoid factoring the LHS of the IN(...) expression out of the loop,\n  ** even if it is constant, as OP_Affinity may be used on the register\n  ** by code generated below.  */\n  assert( pParse->okConstFactor==okConstFactor );\n  pParse->okConstFactor = 0;\n  rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);\n  pParse->okConstFactor = okConstFactor;\n  for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */\n  if( i==nVector ){\n    /* LHS fields are not reordered */\n    rLhs = rLhsOrig;\n  }else{\n    /* Need to reorder the LHS fields according to aiMap */\n    rLhs = sqlite3GetTempRange(pParse, nVector);\n    for(i=0; i<nVector; i++){\n      sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);\n    }\n  }\n\n  /* If sqlite3FindInIndex() did not find or create an index that is\n  ** suitable for evaluating the IN operator, then evaluate using a\n  ** sequence of comparisons.\n  **\n  ** This is step (1) in the in-operator.md optimized algorithm.\n  */\n  if( eType==IN_INDEX_NOOP ){\n    ExprList *pList = pExpr->x.pList;\n    CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);\n    int labelOk = sqlite3VdbeMakeLabel(pParse);\n    int r2, regToFree;\n    int regCkNull = 0;\n    int ii;\n    assert( !ExprHasProperty(pExpr, EP_xIsSelect) );\n    if( destIfNull!=destIfFalse ){\n      regCkNull = sqlite3GetTempReg(pParse);\n      sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);\n    }\n    for(ii=0; ii<pList->nExpr; ii++){\n      r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);\n      if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){\n        sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);\n      }\n      sqlite3ReleaseTempReg(pParse, regToFree);\n      if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){\n        int op = rLhs!=r2 ? OP_Eq : OP_NotNull;\n        sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2,\n                          (void*)pColl, P4_COLLSEQ);\n        VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq);\n        VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq);\n        VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull);\n        VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull);\n        sqlite3VdbeChangeP5(v, zAff[0]);\n      }else{\n        int op = rLhs!=r2 ? OP_Ne : OP_IsNull;\n        assert( destIfNull==destIfFalse );\n        sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2,\n                          (void*)pColl, P4_COLLSEQ);\n        VdbeCoverageIf(v, op==OP_Ne);\n        VdbeCoverageIf(v, op==OP_IsNull);\n        sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);\n      }\n    }\n    if( regCkNull ){\n      sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);\n      sqlite3VdbeGoto(v, destIfFalse);\n    }\n    sqlite3VdbeResolveLabel(v, labelOk);\n    sqlite3ReleaseTempReg(pParse, regCkNull);\n    goto sqlite3ExprCodeIN_finished;\n  }\n\n  /* Step 2: Check to see if the LHS contains any NULL columns.  If the\n  ** LHS does contain NULLs then the result must be either FALSE or NULL.\n  ** We will then skip the binary search of the RHS.\n  */\n  if( destIfNull==destIfFalse ){\n    destStep2 = destIfFalse;\n  }else{\n    destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);\n  }\n  if( pParse->nErr ) goto sqlite3ExprCodeIN_finished;\n  for(i=0; i<nVector; i++){\n    Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);\n    if( sqlite3ExprCanBeNull(p) ){\n      sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);\n      VdbeCoverage(v);\n    }\n  }\n\n  /* Step 3.  The LHS is now known to be non-NULL.  Do the binary search\n  ** of the RHS using the LHS as a probe.  If found, the result is\n  ** true.\n  */\n  if( eType==IN_INDEX_ROWID ){\n    /* In this case, the RHS is the ROWID of table b-tree and so we also\n    ** know that the RHS is non-NULL.  Hence, we combine steps 3 and 4\n    ** into a single opcode. */\n    sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);\n    VdbeCoverage(v);\n    addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto);  /* Return True */\n  }else{\n    sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);\n    if( destIfFalse==destIfNull ){\n      /* Combine Step 3 and Step 5 into a single opcode */\n      sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,\n                           rLhs, nVector); VdbeCoverage(v);\n      goto sqlite3ExprCodeIN_finished;\n    }\n    /* Ordinary Step 3, for the case where FALSE and NULL are distinct */\n    addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,\n                                      rLhs, nVector); VdbeCoverage(v);\n  }\n\n  /* Step 4.  If the RHS is known to be non-NULL and we did not find\n  ** an match on the search above, then the result must be FALSE.\n  */\n  if( rRhsHasNull && nVector==1 ){\n    sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);\n    VdbeCoverage(v);\n  }\n\n  /* Step 5.  If we do not care about the difference between NULL and\n  ** FALSE, then just return false. \n  */\n  if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);\n\n  /* Step 6: Loop through rows of the RHS.  Compare each row to the LHS.\n  ** If any comparison is NULL, then the result is NULL.  If all\n  ** comparisons are FALSE then the final result is FALSE.\n  **\n  ** For a scalar LHS, it is sufficient to check just the first row\n  ** of the RHS.\n  */\n  if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);\n  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);\n  VdbeCoverage(v);\n  if( nVector>1 ){\n    destNotNull = sqlite3VdbeMakeLabel(pParse);\n  }else{\n    /* For nVector==1, combine steps 6 and 7 by immediately returning\n    ** FALSE if the first comparison is not NULL */\n    destNotNull = destIfFalse;\n  }\n  for(i=0; i<nVector; i++){\n    Expr *p;\n    CollSeq *pColl;\n    int r3 = sqlite3GetTempReg(pParse);\n    p = sqlite3VectorFieldSubexpr(pLeft, i);\n    pColl = sqlite3ExprCollSeq(pParse, p);\n    sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);\n    sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,\n                      (void*)pColl, P4_COLLSEQ);\n    VdbeCoverage(v);\n    sqlite3ReleaseTempReg(pParse, r3);\n  }\n  sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);\n  if( nVector>1 ){\n    sqlite3VdbeResolveLabel(v, destNotNull);\n    sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);\n    VdbeCoverage(v);\n\n    /* Step 7:  If we reach this point, we know that the result must\n    ** be false. */\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);\n  }\n\n  /* Jumps here in order to return true. */\n  sqlite3VdbeJumpHere(v, addrTruthOp);\n\nsqlite3ExprCodeIN_finished:\n  if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);\n  VdbeComment((v, \"end IN expr\"));\nsqlite3ExprCodeIN_oom_error:\n  sqlite3DbFree(pParse->db, aiMap);\n  sqlite3DbFree(pParse->db, zAff);\n}\n#endif /* SQLITE_OMIT_SUBQUERY */\n\n#ifndef SQLITE_OMIT_FLOATING_POINT\n/*\n** Generate an instruction that will put the floating point\n** value described by z[0..n-1] into register iMem.\n**\n** The z[] string will probably not be zero-terminated.  But the \n** z[n] character is guaranteed to be something that does not look\n** like the continuation of the number.\n*/\nstatic void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){\n  if( ALWAYS(z!=0) ){\n    double value;\n    sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);\n    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */\n    if( negateFlag ) value = -value;\n    sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);\n  }\n}\n#endif\n\n\n/*\n** Generate an instruction that will put the integer describe by\n** text z[0..n-1] into register iMem.\n**\n** Expr.u.zToken is always UTF8 and zero-terminated.\n*/\nstatic void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){\n  Vdbe *v = pParse->pVdbe;\n  if( pExpr->flags & EP_IntValue ){\n    int i = pExpr->u.iValue;\n    assert( i>=0 );\n    if( negFlag ) i = -i;\n    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);\n  }else{\n    int c;\n    i64 value;\n    const char *z = pExpr->u.zToken;\n    assert( z!=0 );\n    c = sqlite3DecOrHexToI64(z, &value);\n    if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){\n#ifdef SQLITE_OMIT_FLOATING_POINT\n      sqlite3ErrorMsg(pParse, \"oversized integer: %s%s\", negFlag ? \"-\" : \"\", z);\n#else\n#ifndef SQLITE_OMIT_HEX_INTEGER\n      if( sqlite3_strnicmp(z,\"0x\",2)==0 ){\n        sqlite3ErrorMsg(pParse, \"hex literal too big: %s%s\", negFlag?\"-\":\"\",z);\n      }else\n#endif\n      {\n        codeReal(v, z, negFlag, iMem);\n      }\n#endif\n    }else{\n      if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }\n      sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);\n    }\n  }\n}\n\n\n/* Generate code that will load into register regOut a value that is\n** appropriate for the iIdxCol-th column of index pIdx.\n*/\nSQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(\n  Parse *pParse,  /* The parsing context */\n  Index *pIdx,    /* The index whose column is to be loaded */\n  int iTabCur,    /* Cursor pointing to a table row */\n  int iIdxCol,    /* The column of the index to be loaded */\n  int regOut      /* Store the index column value in this register */\n){\n  i16 iTabCol = pIdx->aiColumn[iIdxCol];\n  if( iTabCol==XN_EXPR ){\n    assert( pIdx->aColExpr );\n    assert( pIdx->aColExpr->nExpr>iIdxCol );\n    pParse->iSelfTab = iTabCur + 1;\n    sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);\n    pParse->iSelfTab = 0;\n  }else{\n    sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,\n                                    iTabCol, regOut);\n  }\n}\n\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n/*\n** Generate code that will compute the value of generated column pCol\n** and store the result in register regOut\n*/\nSQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(\n  Parse *pParse,\n  Column *pCol,\n  int regOut\n){\n  int iAddr;\n  Vdbe *v = pParse->pVdbe;\n  assert( v!=0 );\n  assert( pParse->iSelfTab!=0 );\n  if( pParse->iSelfTab>0 ){\n    iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);\n  }else{\n    iAddr = 0;\n  }\n  sqlite3ExprCodeCopy(pParse, pCol->pDflt, regOut);\n  if( pCol->affinity>=SQLITE_AFF_TEXT ){\n    sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);\n  }\n  if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);\n}\n#endif /* SQLITE_OMIT_GENERATED_COLUMNS */\n\n/*\n** Generate code to extract the value of the iCol-th column of a table.\n*/\nSQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(\n  Vdbe *v,        /* Parsing context */\n  Table *pTab,    /* The table containing the value */\n  int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */\n  int iCol,       /* Index of the column to extract */\n  int regOut      /* Extract the value into this register */\n){\n  Column *pCol;\n  assert( v!=0 );\n  if( pTab==0 ){\n    sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);\n    return;\n  }\n  if( iCol<0 || iCol==pTab->iPKey ){\n    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);\n  }else{\n    int op;\n    int x;\n    if( IsVirtual(pTab) ){\n      op = OP_VColumn;\n      x = iCol;\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n    }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){\n      Parse *pParse = sqlite3VdbeParser(v);\n      if( pCol->colFlags & COLFLAG_BUSY ){\n        sqlite3ErrorMsg(pParse, \"generated column loop on \\\"%s\\\"\", pCol->zName);\n      }else{\n        int savedSelfTab = pParse->iSelfTab;\n        pCol->colFlags |= COLFLAG_BUSY;\n        pParse->iSelfTab = iTabCur+1;\n        sqlite3ExprCodeGeneratedColumn(pParse, pCol, regOut);\n        pParse->iSelfTab = savedSelfTab;\n        pCol->colFlags &= ~COLFLAG_BUSY;\n      }\n      return;\n#endif\n    }else if( !HasRowid(pTab) ){\n      testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );\n      x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);\n      op = OP_Column;\n    }else{\n      x = sqlite3TableColumnToStorage(pTab,iCol);\n      testcase( x!=iCol );\n      op = OP_Column;\n    }\n    sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);\n    sqlite3ColumnDefault(v, pTab, iCol, regOut);\n  }\n}\n\n/*\n** Generate code that will extract the iColumn-th column from\n** table pTab and store the column value in register iReg. \n**\n** There must be an open cursor to pTab in iTable when this routine\n** is called.  If iColumn<0 then code is generated that extracts the rowid.\n*/\nSQLITE_PRIVATE int sqlite3ExprCodeGetColumn(\n  Parse *pParse,   /* Parsing and code generating context */\n  Table *pTab,     /* Description of the table we are reading from */\n  int iColumn,     /* Index of the table column */\n  int iTable,      /* The cursor pointing to the table */\n  int iReg,        /* Store results here */\n  u8 p5            /* P5 value for OP_Column + FLAGS */\n){\n  assert( pParse->pVdbe!=0 );\n  sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);\n  if( p5 ){\n    VdbeOp *pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1);\n    if( pOp->opcode==OP_Column ) pOp->p5 = p5;\n  }\n  return iReg;\n}\n\n/*\n** Generate code to move content from registers iFrom...iFrom+nReg-1\n** over to iTo..iTo+nReg-1.\n*/\nSQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){\n  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);\n}\n\n/*\n** Convert a scalar expression node to a TK_REGISTER referencing\n** register iReg.  The caller must ensure that iReg already contains\n** the correct value for the expression.\n*/\nstatic void exprToRegister(Expr *pExpr, int iReg){\n  Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);\n  p->op2 = p->op;\n  p->op = TK_REGISTER;\n  p->iTable = iReg;\n  ExprClearProperty(p, EP_Skip);\n}\n\n/*\n** Evaluate an expression (either a vector or a scalar expression) and store\n** the result in continguous temporary registers.  Return the index of\n** the first register used to store the result.\n**\n** If the returned result register is a temporary scalar, then also write\n** that register number into *piFreeable.  If the returned result register\n** is not a temporary or if the expression is a vector set *piFreeable\n** to 0.\n*/\nstatic int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){\n  int iResult;\n  int nResult = sqlite3ExprVectorSize(p);\n  if( nResult==1 ){\n    iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);\n  }else{\n    *piFreeable = 0;\n    if( p->op==TK_SELECT ){\n#if SQLITE_OMIT_SUBQUERY\n      iResult = 0;\n#else\n      iResult = sqlite3CodeSubselect(pParse, p);\n#endif\n    }else{\n      int i;\n      iResult = pParse->nMem+1;\n      pParse->nMem += nResult;\n      for(i=0; i<nResult; i++){\n        sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);\n      }\n    }\n  }\n  return iResult;\n}\n\n/*\n** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)\n** so that a subsequent copy will not be merged into this one.\n*/\nstatic void setDoNotMergeFlagOnCopy(Vdbe *v){\n  if( sqlite3VdbeGetOp(v, -1)->opcode==OP_Copy ){\n    sqlite3VdbeChangeP5(v, 1);  /* Tag trailing OP_Copy as not mergable */\n  }\n}\n\n/*\n** Generate code to implement special SQL functions that are implemented\n** in-line rather than by using the usual callbacks.\n*/\nstatic int exprCodeInlineFunction(\n  Parse *pParse,        /* Parsing context */\n  ExprList *pFarg,      /* List of function arguments */\n  int iFuncId,          /* Function ID.  One of the INTFUNC_... values */\n  int target            /* Store function result in this register */\n){\n  int nFarg;\n  Vdbe *v = pParse->pVdbe;\n  assert( v!=0 );\n  assert( pFarg!=0 );\n  nFarg = pFarg->nExpr;\n  assert( nFarg>0 );  /* All in-line functions have at least one argument */\n  switch( iFuncId ){\n    case INLINEFUNC_coalesce: {\n      /* Attempt a direct implementation of the built-in COALESCE() and\n      ** IFNULL() functions.  This avoids unnecessary evaluation of\n      ** arguments past the first non-NULL argument.\n      */\n      int endCoalesce = sqlite3VdbeMakeLabel(pParse);\n      int i;\n      assert( nFarg>=2 );\n      sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);\n      for(i=1; i<nFarg; i++){\n        sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);\n        VdbeCoverage(v);\n        sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);\n      }\n      setDoNotMergeFlagOnCopy(v);\n      sqlite3VdbeResolveLabel(v, endCoalesce);\n      break;\n    }\n    case INLINEFUNC_iif: {\n      Expr caseExpr;\n      memset(&caseExpr, 0, sizeof(caseExpr));\n      caseExpr.op = TK_CASE;\n      caseExpr.x.pList = pFarg;\n      return sqlite3ExprCodeTarget(pParse, &caseExpr, target);\n    }\n\n    default: {   \n      /* The UNLIKELY() function is a no-op.  The result is the value\n      ** of the first argument.\n      */\n      assert( nFarg==1 || nFarg==2 );\n      target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);\n      break;\n    }\n\n  /***********************************************************************\n  ** Test-only SQL functions that are only usable if enabled\n  ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS\n  */\n    case INLINEFUNC_expr_compare: {\n      /* Compare two expressions using sqlite3ExprCompare() */\n      assert( nFarg==2 );\n      sqlite3VdbeAddOp2(v, OP_Integer, \n         sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),\n         target);\n      break;\n    }\n\n    case INLINEFUNC_expr_implies_expr: {\n      /* Compare two expressions using sqlite3ExprImpliesExpr() */\n      assert( nFarg==2 );\n      sqlite3VdbeAddOp2(v, OP_Integer, \n         sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),\n         target);\n      break;\n    }\n\n    case INLINEFUNC_implies_nonnull_row: {\n      /* REsult of sqlite3ExprImpliesNonNullRow() */\n      Expr *pA1;\n      assert( nFarg==2 );\n      pA1 = pFarg->a[1].pExpr;\n      if( pA1->op==TK_COLUMN ){\n        sqlite3VdbeAddOp2(v, OP_Integer, \n           sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable),\n           target);\n      }else{\n        sqlite3VdbeAddOp2(v, OP_Null, 0, target);\n      }\n      break;\n    }\n\n#ifdef SQLITE_DEBUG\n    case INLINEFUNC_affinity: {\n      /* The AFFINITY() function evaluates to a string that describes\n      ** the type affinity of the argument.  This is used for testing of\n      ** the SQLite type logic.\n      */\n      const char *azAff[] = { \"blob\", \"text\", \"numeric\", \"integer\", \"real\" };\n      char aff;\n      assert( nFarg==1 );\n      aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);\n      sqlite3VdbeLoadString(v, target, \n              (aff<=SQLITE_AFF_NONE) ? \"none\" : azAff[aff-SQLITE_AFF_BLOB]);\n      break;\n    }\n#endif\n  }\n  return target;\n}\n\n\n/*\n** Generate code into the current Vdbe to evaluate the given\n** expression.  Attempt to store the results in register \"target\".\n** Return the register where results are stored.\n**\n** With this routine, there is no guarantee that results will\n** be stored in target.  The result might be stored in some other\n** register if it is convenient to do so.  The calling function\n** must check the return code and move the results to the desired\n** register.\n*/\nSQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){\n  Vdbe *v = pParse->pVdbe;  /* The VM under construction */\n  int op;                   /* The opcode being coded */\n  int inReg = target;       /* Results stored in register inReg */\n  int regFree1 = 0;         /* If non-zero free this temporary register */\n  int regFree2 = 0;         /* If non-zero free this temporary register */\n  int r1, r2;               /* Various register numbers */\n  Expr tempX;               /* Temporary expression node */\n  int p5 = 0;\n\n  assert( target>0 && target<=pParse->nMem );\n  if( v==0 ){\n    assert( pParse->db->mallocFailed );\n    return 0;\n  }\n\nexpr_code_doover:\n  if( pExpr==0 ){\n    op = TK_NULL;\n  }else{\n    assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );\n    op = pExpr->op;\n  }\n  switch( op ){\n    case TK_AGG_COLUMN: {\n      AggInfo *pAggInfo = pExpr->pAggInfo;\n      struct AggInfo_col *pCol;\n      assert( pAggInfo!=0 );\n      assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );\n      pCol = &pAggInfo->aCol[pExpr->iAgg];\n      if( !pAggInfo->directMode ){\n        assert( pCol->iMem>0 );\n        return pCol->iMem;\n      }else if( pAggInfo->useSortingIdx ){\n        Table *pTab = pCol->pTab;\n        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,\n                              pCol->iSorterColumn, target);\n        if( pCol->iColumn<0 ){\n          VdbeComment((v,\"%s.rowid\",pTab->zName));\n        }else{\n          VdbeComment((v,\"%s.%s\",pTab->zName,pTab->aCol[pCol->iColumn].zName));\n          if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){\n            sqlite3VdbeAddOp1(v, OP_RealAffinity, target);\n          }\n        }\n        return target;\n      }\n      /* Otherwise, fall thru into the TK_COLUMN case */\n    }\n    case TK_COLUMN: {\n      int iTab = pExpr->iTable;\n      int iReg;\n      if( ExprHasProperty(pExpr, EP_FixedCol) ){\n        /* This COLUMN expression is really a constant due to WHERE clause\n        ** constraints, and that constant is coded by the pExpr->pLeft\n        ** expresssion.  However, make sure the constant has the correct\n        ** datatype by applying the Affinity of the table column to the\n        ** constant.\n        */\n        int aff;\n        iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);\n        if( pExpr->y.pTab ){\n          aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);\n        }else{\n          aff = pExpr->affExpr;\n        }\n        if( aff>SQLITE_AFF_BLOB ){\n          static const char zAff[] = \"B\\000C\\000D\\000E\";\n          assert( SQLITE_AFF_BLOB=='A' );\n          assert( SQLITE_AFF_TEXT=='B' );\n          sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,\n                            &zAff[(aff-'B')*2], P4_STATIC);\n        }\n        return iReg;\n      }\n      if( iTab<0 ){\n        if( pParse->iSelfTab<0 ){\n          /* Other columns in the same row for CHECK constraints or\n          ** generated columns or for inserting into partial index.\n          ** The row is unpacked into registers beginning at\n          ** 0-(pParse->iSelfTab).  The rowid (if any) is in a register\n          ** immediately prior to the first column.\n          */\n          Column *pCol;\n          Table *pTab = pExpr->y.pTab;\n          int iSrc;\n          int iCol = pExpr->iColumn;\n          assert( pTab!=0 );\n          assert( iCol>=XN_ROWID );\n          assert( iCol<pTab->nCol );\n          if( iCol<0 ){\n            return -1-pParse->iSelfTab;\n          }\n          pCol = pTab->aCol + iCol;\n          testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );\n          iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n          if( pCol->colFlags & COLFLAG_GENERATED ){\n            if( pCol->colFlags & COLFLAG_BUSY ){\n              sqlite3ErrorMsg(pParse, \"generated column loop on \\\"%s\\\"\",\n                              pCol->zName);\n              return 0;\n            }\n            pCol->colFlags |= COLFLAG_BUSY;\n            if( pCol->colFlags & COLFLAG_NOTAVAIL ){\n              sqlite3ExprCodeGeneratedColumn(pParse, pCol, iSrc);\n            }\n            pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);\n            return iSrc;\n          }else\n#endif /* SQLITE_OMIT_GENERATED_COLUMNS */\n          if( pCol->affinity==SQLITE_AFF_REAL ){\n            sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);\n            sqlite3VdbeAddOp1(v, OP_RealAffinity, target);\n            return target;\n          }else{\n            return iSrc;\n          }\n        }else{\n          /* Coding an expression that is part of an index where column names\n          ** in the index refer to the table to which the index belongs */\n          iTab = pParse->iSelfTab - 1;\n        }\n      }\n      iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,\n                               pExpr->iColumn, iTab, target,\n                               pExpr->op2);\n      if( pExpr->y.pTab==0 && pExpr->affExpr==SQLITE_AFF_REAL ){\n        sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);\n      }\n      return iReg;\n    }\n    case TK_INTEGER: {\n      codeInteger(pParse, pExpr, 0, target);\n      return target;\n    }\n    case TK_TRUEFALSE: {\n      sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);\n      return target;\n    }\n#ifndef SQLITE_OMIT_FLOATING_POINT\n    case TK_FLOAT: {\n      assert( !ExprHasProperty(pExpr, EP_IntValue) );\n      codeReal(v, pExpr->u.zToken, 0, target);\n      return target;\n    }\n#endif\n    case TK_STRING: {\n      assert( !ExprHasProperty(pExpr, EP_IntValue) );\n      sqlite3VdbeLoadString(v, target, pExpr->u.zToken);\n      return target;\n    }\n    default: {\n      /* Make NULL the default case so that if a bug causes an illegal\n      ** Expr node to be passed into this function, it will be handled\n      ** sanely and not crash.  But keep the assert() to bring the problem\n      ** to the attention of the developers. */\n      assert( op==TK_NULL );\n      sqlite3VdbeAddOp2(v, OP_Null, 0, target);\n      return target;\n    }\n#ifndef SQLITE_OMIT_BLOB_LITERAL\n    case TK_BLOB: {\n      int n;\n      const char *z;\n      char *zBlob;\n      assert( !ExprHasProperty(pExpr, EP_IntValue) );\n      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );\n      assert( pExpr->u.zToken[1]=='\\'' );\n      z = &pExpr->u.zToken[2];\n      n = sqlite3Strlen30(z) - 1;\n      assert( z[n]=='\\'' );\n      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);\n      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);\n      return target;\n    }\n#endif\n    case TK_VARIABLE: {\n      assert( !ExprHasProperty(pExpr, EP_IntValue) );\n      assert( pExpr->u.zToken!=0 );\n      assert( pExpr->u.zToken[0]!=0 );\n      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);\n      if( pExpr->u.zToken[1]!=0 ){\n        const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);\n        assert( pExpr->u.zToken[0]=='?' || (z && !strcmp(pExpr->u.zToken, z)) );\n        pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */\n        sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);\n      }\n      return target;\n    }\n    case TK_REGISTER: {\n      return pExpr->iTable;\n    }\n#ifndef SQLITE_OMIT_CAST\n    case TK_CAST: {\n      /* Expressions of the form:   CAST(pLeft AS token) */\n      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);\n      if( inReg!=target ){\n        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);\n        inReg = target;\n      }\n      sqlite3VdbeAddOp2(v, OP_Cast, target,\n                        sqlite3AffinityType(pExpr->u.zToken, 0));\n      return inReg;\n    }\n#endif /* SQLITE_OMIT_CAST */\n    case TK_IS:\n    case TK_ISNOT:\n      op = (op==TK_IS) ? TK_EQ : TK_NE;\n      p5 = SQLITE_NULLEQ;\n      /* fall-through */\n    case TK_LT:\n    case TK_LE:\n    case TK_GT:\n    case TK_GE:\n    case TK_NE:\n    case TK_EQ: {\n      Expr *pLeft = pExpr->pLeft;\n      if( sqlite3ExprIsVector(pLeft) ){\n        codeVectorCompare(pParse, pExpr, target, op, p5);\n      }else{\n        r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);\n        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);\n        codeCompare(pParse, pLeft, pExpr->pRight, op,\n            r1, r2, inReg, SQLITE_STOREP2 | p5,\n            ExprHasProperty(pExpr,EP_Commuted));\n        assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);\n        assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);\n        assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);\n        assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);\n        assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);\n        assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);\n        testcase( regFree1==0 );\n        testcase( regFree2==0 );\n      }\n      break;\n    }\n    case TK_AND:\n    case TK_OR:\n    case TK_PLUS:\n    case TK_STAR:\n    case TK_MINUS:\n    case TK_REM:\n    case TK_BITAND:\n    case TK_BITOR:\n    case TK_SLASH:\n    case TK_LSHIFT:\n    case TK_RSHIFT: \n    case TK_CONCAT: {\n      assert( TK_AND==OP_And );            testcase( op==TK_AND );\n      assert( TK_OR==OP_Or );              testcase( op==TK_OR );\n      assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );\n      assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );\n      assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );\n      assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );\n      assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );\n      assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );\n      assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );\n      assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );\n      assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);\n      sqlite3VdbeAddOp3(v, op, r2, r1, target);\n      testcase( regFree1==0 );\n      testcase( regFree2==0 );\n      break;\n    }\n    case TK_UMINUS: {\n      Expr *pLeft = pExpr->pLeft;\n      assert( pLeft );\n      if( pLeft->op==TK_INTEGER ){\n        codeInteger(pParse, pLeft, 1, target);\n        return target;\n#ifndef SQLITE_OMIT_FLOATING_POINT\n      }else if( pLeft->op==TK_FLOAT ){\n        assert( !ExprHasProperty(pExpr, EP_IntValue) );\n        codeReal(v, pLeft->u.zToken, 1, target);\n        return target;\n#endif\n      }else{\n        tempX.op = TK_INTEGER;\n        tempX.flags = EP_IntValue|EP_TokenOnly;\n        tempX.u.iValue = 0;\n        ExprClearVVAProperties(&tempX);\n        r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);\n        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);\n        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);\n        testcase( regFree2==0 );\n      }\n      break;\n    }\n    case TK_BITNOT:\n    case TK_NOT: {\n      assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );\n      assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      testcase( regFree1==0 );\n      sqlite3VdbeAddOp2(v, op, r1, inReg);\n      break;\n    }\n    case TK_TRUTH: {\n      int isTrue;    /* IS TRUE or IS NOT TRUE */\n      int bNormal;   /* IS TRUE or IS FALSE */\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      testcase( regFree1==0 );\n      isTrue = sqlite3ExprTruthValue(pExpr->pRight);\n      bNormal = pExpr->op2==TK_IS;\n      testcase( isTrue && bNormal);\n      testcase( !isTrue && bNormal);\n      sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);\n      break;\n    }\n    case TK_ISNULL:\n    case TK_NOTNULL: {\n      int addr;\n      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );\n      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );\n      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      testcase( regFree1==0 );\n      addr = sqlite3VdbeAddOp1(v, op, r1);\n      VdbeCoverageIf(v, op==TK_ISNULL);\n      VdbeCoverageIf(v, op==TK_NOTNULL);\n      sqlite3VdbeAddOp2(v, OP_Integer, 0, target);\n      sqlite3VdbeJumpHere(v, addr);\n      break;\n    }\n    case TK_AGG_FUNCTION: {\n      AggInfo *pInfo = pExpr->pAggInfo;\n      if( pInfo==0\n       || NEVER(pExpr->iAgg<0)\n       || NEVER(pExpr->iAgg>=pInfo->nFunc)\n      ){\n        assert( !ExprHasProperty(pExpr, EP_IntValue) );\n        sqlite3ErrorMsg(pParse, \"misuse of aggregate: %s()\", pExpr->u.zToken);\n      }else{\n        return pInfo->aFunc[pExpr->iAgg].iMem;\n      }\n      break;\n    }\n    case TK_FUNCTION: {\n      ExprList *pFarg;       /* List of function arguments */\n      int nFarg;             /* Number of function arguments */\n      FuncDef *pDef;         /* The function definition object */\n      const char *zId;       /* The function name */\n      u32 constMask = 0;     /* Mask of function arguments that are constant */\n      int i;                 /* Loop counter */\n      sqlite3 *db = pParse->db;  /* The database connection */\n      u8 enc = ENC(db);      /* The text encoding used by this database */\n      CollSeq *pColl = 0;    /* A collating sequence */\n\n#ifndef SQLITE_OMIT_WINDOWFUNC\n      if( ExprHasProperty(pExpr, EP_WinFunc) ){\n        return pExpr->y.pWin->regResult;\n      }\n#endif\n\n      if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){\n        /* SQL functions can be expensive. So try to avoid running them\n        ** multiple times if we know they always give the same result */\n        return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);\n      }\n      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );\n      assert( !ExprHasProperty(pExpr, EP_TokenOnly) );\n      pFarg = pExpr->x.pList;\n      nFarg = pFarg ? pFarg->nExpr : 0;\n      assert( !ExprHasProperty(pExpr, EP_IntValue) );\n      zId = pExpr->u.zToken;\n      pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);\n#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION\n      if( pDef==0 && pParse->explain ){\n        pDef = sqlite3FindFunction(db, \"unknown\", nFarg, enc, 0);\n      }\n#endif\n      if( pDef==0 || pDef->xFinalize!=0 ){\n        sqlite3ErrorMsg(pParse, \"unknown function: %s()\", zId);\n        break;\n      }\n      if( pDef->funcFlags & SQLITE_FUNC_INLINE ){\n        assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );\n        assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 );\n        return exprCodeInlineFunction(pParse, pFarg,\n             SQLITE_PTR_TO_INT(pDef->pUserData), target);\n      }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){\n        sqlite3ExprFunctionUsable(pParse, pExpr, pDef);\n      }\n\n      for(i=0; i<nFarg; i++){\n        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){\n          testcase( i==31 );\n          constMask |= MASKBIT32(i);\n        }\n        if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){\n          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);\n        }\n      }\n      if( pFarg ){\n        if( constMask ){\n          r1 = pParse->nMem+1;\n          pParse->nMem += nFarg;\n        }else{\n          r1 = sqlite3GetTempRange(pParse, nFarg);\n        }\n\n        /* For length() and typeof() functions with a column argument,\n        ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG\n        ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data\n        ** loading.\n        */\n        if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){\n          u8 exprOp;\n          assert( nFarg==1 );\n          assert( pFarg->a[0].pExpr!=0 );\n          exprOp = pFarg->a[0].pExpr->op;\n          if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){\n            assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );\n            assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );\n            testcase( pDef->funcFlags & OPFLAG_LENGTHARG );\n            pFarg->a[0].pExpr->op2 = \n                  pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);\n          }\n        }\n\n        sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,\n                                SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);\n      }else{\n        r1 = 0;\n      }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n      /* Possibly overload the function if the first argument is\n      ** a virtual table column.\n      **\n      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the\n      ** second argument, not the first, as the argument to test to\n      ** see if it is a column in a virtual table.  This is done because\n      ** the left operand of infix functions (the operand we want to\n      ** control overloading) ends up as the second argument to the\n      ** function.  The expression \"A glob B\" is equivalent to \n      ** \"glob(B,A).  We want to use the A in \"A glob B\" to test\n      ** for function overloading.  But we use the B term in \"glob(B,A)\".\n      */\n      if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){\n        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);\n      }else if( nFarg>0 ){\n        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);\n      }\n#endif\n      if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){\n        if( !pColl ) pColl = db->pDfltColl; \n        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);\n      }\n#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC\n      if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){\n        Expr *pArg = pFarg->a[0].pExpr;\n        if( pArg->op==TK_COLUMN ){\n          sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);\n        }else{\n          sqlite3VdbeAddOp2(v, OP_Null, 0, target);\n        }\n      }else\n#endif\n      {\n        sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,\n                                   pDef, pExpr->op2);\n      }\n      if( nFarg ){\n        if( constMask==0 ){\n          sqlite3ReleaseTempRange(pParse, r1, nFarg);\n        }else{\n          sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1);\n        }\n      }\n      return target;\n    }\n#ifndef SQLITE_OMIT_SUBQUERY\n    case TK_EXISTS:\n    case TK_SELECT: {\n      int nCol;\n      testcase( op==TK_EXISTS );\n      testcase( op==TK_SELECT );\n      if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){\n        sqlite3SubselectError(pParse, nCol, 1);\n      }else{\n        return sqlite3CodeSubselect(pParse, pExpr);\n      }\n      break;\n    }\n    case TK_SELECT_COLUMN: {\n      int n;\n      if( pExpr->pLeft->iTable==0 ){\n        pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft);\n      }\n      assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );\n      if( pExpr->iTable!=0\n       && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))\n      ){\n        sqlite3ErrorMsg(pParse, \"%d columns assigned %d values\",\n                                pExpr->iTable, n);\n      }\n      return pExpr->pLeft->iTable + pExpr->iColumn;\n    }\n    case TK_IN: {\n      int destIfFalse = sqlite3VdbeMakeLabel(pParse);\n      int destIfNull = sqlite3VdbeMakeLabel(pParse);\n      sqlite3VdbeAddOp2(v, OP_Null, 0, target);\n      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);\n      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);\n      sqlite3VdbeResolveLabel(v, destIfFalse);\n      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);\n      sqlite3VdbeResolveLabel(v, destIfNull);\n      return target;\n    }\n#endif /* SQLITE_OMIT_SUBQUERY */\n\n\n    /*\n    **    x BETWEEN y AND z\n    **\n    ** This is equivalent to\n    **\n    **    x>=y AND x<=z\n    **\n    ** X is stored in pExpr->pLeft.\n    ** Y is stored in pExpr->pList->a[0].pExpr.\n    ** Z is stored in pExpr->pList->a[1].pExpr.\n    */\n    case TK_BETWEEN: {\n      exprCodeBetween(pParse, pExpr, target, 0, 0);\n      return target;\n    }\n    case TK_SPAN:\n    case TK_COLLATE: \n    case TK_UPLUS: {\n      pExpr = pExpr->pLeft;\n      goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */\n    }\n\n    case TK_TRIGGER: {\n      /* If the opcode is TK_TRIGGER, then the expression is a reference\n      ** to a column in the new.* or old.* pseudo-tables available to\n      ** trigger programs. In this case Expr.iTable is set to 1 for the\n      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn\n      ** is set to the column of the pseudo-table to read, or to -1 to\n      ** read the rowid field.\n      **\n      ** The expression is implemented using an OP_Param opcode. The p1\n      ** parameter is set to 0 for an old.rowid reference, or to (i+1)\n      ** to reference another column of the old.* pseudo-table, where \n      ** i is the index of the column. For a new.rowid reference, p1 is\n      ** set to (n+1), where n is the number of columns in each pseudo-table.\n      ** For a reference to any other column in the new.* pseudo-table, p1\n      ** is set to (n+2+i), where n and i are as defined previously. For\n      ** example, if the table on which triggers are being fired is\n      ** declared as:\n      **\n      **   CREATE TABLE t1(a, b);\n      **\n      ** Then p1 is interpreted as follows:\n      **\n      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid\n      **   p1==1   ->    old.a         p1==4   ->    new.a\n      **   p1==2   ->    old.b         p1==5   ->    new.b       \n      */\n      Table *pTab = pExpr->y.pTab;\n      int iCol = pExpr->iColumn;\n      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 \n                     + sqlite3TableColumnToStorage(pTab, iCol);\n\n      assert( pExpr->iTable==0 || pExpr->iTable==1 );\n      assert( iCol>=-1 && iCol<pTab->nCol );\n      assert( pTab->iPKey<0 || iCol!=pTab->iPKey );\n      assert( p1>=0 && p1<(pTab->nCol*2+2) );\n\n      sqlite3VdbeAddOp2(v, OP_Param, p1, target);\n      VdbeComment((v, \"r[%d]=%s.%s\", target,\n        (pExpr->iTable ? \"new\" : \"old\"),\n        (pExpr->iColumn<0 ? \"rowid\" : pExpr->y.pTab->aCol[iCol].zName)\n      ));\n\n#ifndef SQLITE_OMIT_FLOATING_POINT\n      /* If the column has REAL affinity, it may currently be stored as an\n      ** integer. Use OP_RealAffinity to make sure it is really real.\n      **\n      ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to\n      ** floating point when extracting it from the record.  */\n      if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){\n        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);\n      }\n#endif\n      break;\n    }\n\n    case TK_VECTOR: {\n      sqlite3ErrorMsg(pParse, \"row value misused\");\n      break;\n    }\n\n    /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions\n    ** that derive from the right-hand table of a LEFT JOIN.  The\n    ** Expr.iTable value is the table number for the right-hand table.\n    ** The expression is only evaluated if that table is not currently\n    ** on a LEFT JOIN NULL row.\n    */\n    case TK_IF_NULL_ROW: {\n      int addrINR;\n      u8 okConstFactor = pParse->okConstFactor;\n      addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);\n      /* Temporarily disable factoring of constant expressions, since\n      ** even though expressions may appear to be constant, they are not\n      ** really constant because they originate from the right-hand side\n      ** of a LEFT JOIN. */\n      pParse->okConstFactor = 0;\n      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);\n      pParse->okConstFactor = okConstFactor;\n      sqlite3VdbeJumpHere(v, addrINR);\n      sqlite3VdbeChangeP3(v, addrINR, inReg);\n      break;\n    }\n\n    /*\n    ** Form A:\n    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END\n    **\n    ** Form B:\n    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END\n    **\n    ** Form A is can be transformed into the equivalent form B as follows:\n    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...\n    **        WHEN x=eN THEN rN ELSE y END\n    **\n    ** X (if it exists) is in pExpr->pLeft.\n    ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is\n    ** odd.  The Y is also optional.  If the number of elements in x.pList\n    ** is even, then Y is omitted and the \"otherwise\" result is NULL.\n    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].\n    **\n    ** The result of the expression is the Ri for the first matching Ei,\n    ** or if there is no matching Ei, the ELSE term Y, or if there is\n    ** no ELSE term, NULL.\n    */\n    case TK_CASE: {\n      int endLabel;                     /* GOTO label for end of CASE stmt */\n      int nextCase;                     /* GOTO label for next WHEN clause */\n      int nExpr;                        /* 2x number of WHEN terms */\n      int i;                            /* Loop counter */\n      ExprList *pEList;                 /* List of WHEN terms */\n      struct ExprList_item *aListelem;  /* Array of WHEN terms */\n      Expr opCompare;                   /* The X==Ei expression */\n      Expr *pX;                         /* The X expression */\n      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */\n      Expr *pDel = 0;\n      sqlite3 *db = pParse->db;\n\n      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );\n      assert(pExpr->x.pList->nExpr > 0);\n      pEList = pExpr->x.pList;\n      aListelem = pEList->a;\n      nExpr = pEList->nExpr;\n      endLabel = sqlite3VdbeMakeLabel(pParse);\n      if( (pX = pExpr->pLeft)!=0 ){\n        pDel = sqlite3ExprDup(db, pX, 0);\n        if( db->mallocFailed ){\n          sqlite3ExprDelete(db, pDel);\n          break;\n        }\n        testcase( pX->op==TK_COLUMN );\n        exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));\n        testcase( regFree1==0 );\n        memset(&opCompare, 0, sizeof(opCompare));\n        opCompare.op = TK_EQ;\n        opCompare.pLeft = pDel;\n        pTest = &opCompare;\n        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:\n        ** The value in regFree1 might get SCopy-ed into the file result.\n        ** So make sure that the regFree1 register is not reused for other\n        ** purposes and possibly overwritten.  */\n        regFree1 = 0;\n      }\n      for(i=0; i<nExpr-1; i=i+2){\n        if( pX ){\n          assert( pTest!=0 );\n          opCompare.pRight = aListelem[i].pExpr;\n        }else{\n          pTest = aListelem[i].pExpr;\n        }\n        nextCase = sqlite3VdbeMakeLabel(pParse);\n        testcase( pTest->op==TK_COLUMN );\n        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);\n        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );\n        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);\n        sqlite3VdbeGoto(v, endLabel);\n        sqlite3VdbeResolveLabel(v, nextCase);\n      }\n      if( (nExpr&1)!=0 ){\n        sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);\n      }else{\n        sqlite3VdbeAddOp2(v, OP_Null, 0, target);\n      }\n      sqlite3ExprDelete(db, pDel);\n      setDoNotMergeFlagOnCopy(v);\n      sqlite3VdbeResolveLabel(v, endLabel);\n      break;\n    }\n#ifndef SQLITE_OMIT_TRIGGER\n    case TK_RAISE: {\n      assert( pExpr->affExpr==OE_Rollback \n           || pExpr->affExpr==OE_Abort\n           || pExpr->affExpr==OE_Fail\n           || pExpr->affExpr==OE_Ignore\n      );\n      if( !pParse->pTriggerTab && !pParse->nested ){\n        sqlite3ErrorMsg(pParse,\n                       \"RAISE() may only be used within a trigger-program\");\n        return 0;\n      }\n      if( pExpr->affExpr==OE_Abort ){\n        sqlite3MayAbort(pParse);\n      }\n      assert( !ExprHasProperty(pExpr, EP_IntValue) );\n      if( pExpr->affExpr==OE_Ignore ){\n        sqlite3VdbeAddOp4(\n            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);\n        VdbeCoverage(v);\n      }else{\n        sqlite3HaltConstraint(pParse,\n             pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,\n             pExpr->affExpr, pExpr->u.zToken, 0, 0);\n      }\n\n      break;\n    }\n#endif\n  }\n  sqlite3ReleaseTempReg(pParse, regFree1);\n  sqlite3ReleaseTempReg(pParse, regFree2);\n  return inReg;\n}\n\n/*\n** Generate code that will evaluate expression pExpr just one time\n** per prepared statement execution.\n**\n** If the expression uses functions (that might throw an exception) then\n** guard them with an OP_Once opcode to ensure that the code is only executed\n** once. If no functions are involved, then factor the code out and put it at\n** the end of the prepared statement in the initialization section.\n**\n** If regDest>=0 then the result is always stored in that register and the\n** result is not reusable.  If regDest<0 then this routine is free to \n** store the value whereever it wants.  The register where the expression \n** is stored is returned.  When regDest<0, two identical expressions might\n** code to the same register, if they do not contain function calls and hence\n** are factored out into the initialization section at the end of the\n** prepared statement.\n*/\nSQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(\n  Parse *pParse,    /* Parsing context */\n  Expr *pExpr,      /* The expression to code when the VDBE initializes */\n  int regDest       /* Store the value in this register */\n){\n  ExprList *p;\n  assert( ConstFactorOk(pParse) );\n  p = pParse->pConstExpr;\n  if( regDest<0 && p ){\n    struct ExprList_item *pItem;\n    int i;\n    for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){\n      if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){\n        return pItem->u.iConstExprReg;\n      }\n    }\n  }\n  pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);\n  if( pExpr!=0 && ExprHasProperty(pExpr, EP_HasFunc) ){\n    Vdbe *v = pParse->pVdbe;\n    int addr;\n    assert( v );\n    addr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);\n    pParse->okConstFactor = 0;\n    if( !pParse->db->mallocFailed ){\n      if( regDest<0 ) regDest = ++pParse->nMem;\n      sqlite3ExprCode(pParse, pExpr, regDest);\n    }\n    pParse->okConstFactor = 1;\n    sqlite3ExprDelete(pParse->db, pExpr);\n    sqlite3VdbeJumpHere(v, addr);\n  }else{\n    p = sqlite3ExprListAppend(pParse, p, pExpr);\n    if( p ){\n       struct ExprList_item *pItem = &p->a[p->nExpr-1];\n       pItem->reusable = regDest<0;\n       if( regDest<0 ) regDest = ++pParse->nMem;\n       pItem->u.iConstExprReg = regDest;\n    }\n    pParse->pConstExpr = p;\n  }\n  return regDest;\n}\n\n/*\n** Generate code to evaluate an expression and store the results\n** into a register.  Return the register number where the results\n** are stored.\n**\n** If the register is a temporary register that can be deallocated,\n** then write its number into *pReg.  If the result register is not\n** a temporary, then set *pReg to zero.\n**\n** If pExpr is a constant, then this routine might generate this\n** code to fill the register in the initialization section of the\n** VDBE program, in order to factor it out of the evaluation loop.\n*/\nSQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){\n  int r2;\n  pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);\n  if( ConstFactorOk(pParse)\n   && pExpr->op!=TK_REGISTER\n   && sqlite3ExprIsConstantNotJoin(pExpr)\n  ){\n    *pReg  = 0;\n    r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);\n  }else{\n    int r1 = sqlite3GetTempReg(pParse);\n    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);\n    if( r2==r1 ){\n      *pReg = r1;\n    }else{\n      sqlite3ReleaseTempReg(pParse, r1);\n      *pReg = 0;\n    }\n  }\n  return r2;\n}\n\n/*\n** Generate code that will evaluate expression pExpr and store the\n** results in register target.  The results are guaranteed to appear\n** in register target.\n*/\nSQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){\n  int inReg;\n\n  assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) );\n  assert( target>0 && target<=pParse->nMem );\n  inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);\n  assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );\n  if( inReg!=target && pParse->pVdbe ){\n    u8 op;\n    if( ExprHasProperty(pExpr,EP_Subquery) ){\n      op = OP_Copy;\n    }else{\n      op = OP_SCopy;\n    }\n    sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);\n  }\n}\n\n/*\n** Make a transient copy of expression pExpr and then code it using\n** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()\n** except that the input expression is guaranteed to be unchanged.\n*/\nSQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){\n  sqlite3 *db = pParse->db;\n  pExpr = sqlite3ExprDup(db, pExpr, 0);\n  if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);\n  sqlite3ExprDelete(db, pExpr);\n}\n\n/*\n** Generate code that will evaluate expression pExpr and store the\n** results in register target.  The results are guaranteed to appear\n** in register target.  If the expression is constant, then this routine\n** might choose to code the expression at initialization time.\n*/\nSQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){\n  if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){\n    sqlite3ExprCodeRunJustOnce(pParse, pExpr, target);\n  }else{\n    sqlite3ExprCodeCopy(pParse, pExpr, target);\n  }\n}\n\n/*\n** Generate code that pushes the value of every element of the given\n** expression list into a sequence of registers beginning at target.\n**\n** Return the number of elements evaluated.  The number returned will\n** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF\n** is defined.\n**\n** The SQLITE_ECEL_DUP flag prevents the arguments from being\n** filled using OP_SCopy.  OP_Copy must be used instead.\n**\n** The SQLITE_ECEL_FACTOR argument allows constant arguments to be\n** factored out into initialization code.\n**\n** The SQLITE_ECEL_REF flag means that expressions in the list with\n** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored\n** in registers at srcReg, and so the value can be copied from there.\n** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0\n** are simply omitted rather than being copied from srcReg.\n*/\nSQLITE_PRIVATE int sqlite3ExprCodeExprList(\n  Parse *pParse,     /* Parsing context */\n  ExprList *pList,   /* The expression list to be coded */\n  int target,        /* Where to write results */\n  int srcReg,        /* Source registers if SQLITE_ECEL_REF */\n  u8 flags           /* SQLITE_ECEL_* flags */\n){\n  struct ExprList_item *pItem;\n  int i, j, n;\n  u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;\n  Vdbe *v = pParse->pVdbe;\n  assert( pList!=0 );\n  assert( target>0 );\n  assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */\n  n = pList->nExpr;\n  if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;\n  for(pItem=pList->a, i=0; i<n; i++, pItem++){\n    Expr *pExpr = pItem->pExpr;\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n    if( pItem->bSorterRef ){\n      i--;\n      n--;\n    }else\n#endif\n    if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){\n      if( flags & SQLITE_ECEL_OMITREF ){\n        i--;\n        n--;\n      }else{\n        sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);\n      }\n    }else if( (flags & SQLITE_ECEL_FACTOR)!=0\n           && sqlite3ExprIsConstantNotJoin(pExpr)\n    ){\n      sqlite3ExprCodeRunJustOnce(pParse, pExpr, target+i);\n    }else{\n      int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);\n      if( inReg!=target+i ){\n        VdbeOp *pOp;\n        if( copyOp==OP_Copy\n         && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy\n         && pOp->p1+pOp->p3+1==inReg\n         && pOp->p2+pOp->p3+1==target+i\n         && pOp->p5==0  /* The do-not-merge flag must be clear */\n        ){\n          pOp->p3++;\n        }else{\n          sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);\n        }\n      }\n    }\n  }\n  return n;\n}\n\n/*\n** Generate code for a BETWEEN operator.\n**\n**    x BETWEEN y AND z\n**\n** The above is equivalent to \n**\n**    x>=y AND x<=z\n**\n** Code it as such, taking care to do the common subexpression\n** elimination of x.\n**\n** The xJumpIf parameter determines details:\n**\n**    NULL:                   Store the boolean result in reg[dest]\n**    sqlite3ExprIfTrue:      Jump to dest if true\n**    sqlite3ExprIfFalse:     Jump to dest if false\n**\n** The jumpIfNull parameter is ignored if xJumpIf is NULL.\n*/\nstatic void exprCodeBetween(\n  Parse *pParse,    /* Parsing and code generating context */\n  Expr *pExpr,      /* The BETWEEN expression */\n  int dest,         /* Jump destination or storage location */\n  void (*xJump)(Parse*,Expr*,int,int), /* Action to take */\n  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */\n){\n  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */\n  Expr compLeft;    /* The  x>=y  term */\n  Expr compRight;   /* The  x<=z  term */\n  int regFree1 = 0; /* Temporary use register */\n  Expr *pDel = 0;\n  sqlite3 *db = pParse->db;\n\n  memset(&compLeft, 0, sizeof(Expr));\n  memset(&compRight, 0, sizeof(Expr));\n  memset(&exprAnd, 0, sizeof(Expr));\n\n  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );\n  pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);\n  if( db->mallocFailed==0 ){\n    exprAnd.op = TK_AND;\n    exprAnd.pLeft = &compLeft;\n    exprAnd.pRight = &compRight;\n    compLeft.op = TK_GE;\n    compLeft.pLeft = pDel;\n    compLeft.pRight = pExpr->x.pList->a[0].pExpr;\n    compRight.op = TK_LE;\n    compRight.pLeft = pDel;\n    compRight.pRight = pExpr->x.pList->a[1].pExpr;\n    exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));\n    if( xJump ){\n      xJump(pParse, &exprAnd, dest, jumpIfNull);\n    }else{\n      /* Mark the expression is being from the ON or USING clause of a join\n      ** so that the sqlite3ExprCodeTarget() routine will not attempt to move\n      ** it into the Parse.pConstExpr list.  We should use a new bit for this,\n      ** for clarity, but we are out of bits in the Expr.flags field so we\n      ** have to reuse the EP_FromJoin bit.  Bummer. */\n      pDel->flags |= EP_FromJoin;\n      sqlite3ExprCodeTarget(pParse, &exprAnd, dest);\n    }\n    sqlite3ReleaseTempReg(pParse, regFree1);\n  }\n  sqlite3ExprDelete(db, pDel);\n\n  /* Ensure adequate test coverage */\n  testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1==0 );\n  testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1!=0 );\n  testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1==0 );\n  testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1!=0 );\n  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );\n  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );\n  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );\n  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );\n  testcase( xJump==0 );\n}\n\n/*\n** Generate code for a boolean expression such that a jump is made\n** to the label \"dest\" if the expression is true but execution\n** continues straight thru if the expression is false.\n**\n** If the expression evaluates to NULL (neither true nor false), then\n** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.\n**\n** This code depends on the fact that certain token values (ex: TK_EQ)\n** are the same as opcode values (ex: OP_Eq) that implement the corresponding\n** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in\n** the make process cause these values to align.  Assert()s in the code\n** below verify that the numbers are aligned correctly.\n*/\nSQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){\n  Vdbe *v = pParse->pVdbe;\n  int op = 0;\n  int regFree1 = 0;\n  int regFree2 = 0;\n  int r1, r2;\n\n  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );\n  if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */\n  if( NEVER(pExpr==0) ) return;  /* No way this can happen */\n  assert( !ExprHasVVAProperty(pExpr, EP_Immutable) );\n  op = pExpr->op;\n  switch( op ){\n    case TK_AND:\n    case TK_OR: {\n      Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);\n      if( pAlt!=pExpr ){\n        sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);\n      }else if( op==TK_AND ){\n        int d2 = sqlite3VdbeMakeLabel(pParse);\n        testcase( jumpIfNull==0 );\n        sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,\n                           jumpIfNull^SQLITE_JUMPIFNULL);\n        sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);\n        sqlite3VdbeResolveLabel(v, d2);\n      }else{\n        testcase( jumpIfNull==0 );\n        sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);\n        sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);\n      }\n      break;\n    }\n    case TK_NOT: {\n      testcase( jumpIfNull==0 );\n      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);\n      break;\n    }\n    case TK_TRUTH: {\n      int isNot;      /* IS NOT TRUE or IS NOT FALSE */\n      int isTrue;     /* IS TRUE or IS NOT TRUE */\n      testcase( jumpIfNull==0 );\n      isNot = pExpr->op2==TK_ISNOT;\n      isTrue = sqlite3ExprTruthValue(pExpr->pRight);\n      testcase( isTrue && isNot );\n      testcase( !isTrue && isNot );\n      if( isTrue ^ isNot ){\n        sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,\n                          isNot ? SQLITE_JUMPIFNULL : 0);\n      }else{\n        sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,\n                           isNot ? SQLITE_JUMPIFNULL : 0);\n      }\n      break;\n    }\n    case TK_IS:\n    case TK_ISNOT:\n      testcase( op==TK_IS );\n      testcase( op==TK_ISNOT );\n      op = (op==TK_IS) ? TK_EQ : TK_NE;\n      jumpIfNull = SQLITE_NULLEQ;\n      /* Fall thru */\n    case TK_LT:\n    case TK_LE:\n    case TK_GT:\n    case TK_GE:\n    case TK_NE:\n    case TK_EQ: {\n      if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;\n      testcase( jumpIfNull==0 );\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);\n      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,\n                  r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));\n      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);\n      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);\n      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);\n      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);\n      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);\n      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);\n      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);\n      assert(TK_NE==OP_Ne); testcase(op==OP_Ne);\n      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);\n      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);\n      testcase( regFree1==0 );\n      testcase( regFree2==0 );\n      break;\n    }\n    case TK_ISNULL:\n    case TK_NOTNULL: {\n      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );\n      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      sqlite3VdbeAddOp2(v, op, r1, dest);\n      VdbeCoverageIf(v, op==TK_ISNULL);\n      VdbeCoverageIf(v, op==TK_NOTNULL);\n      testcase( regFree1==0 );\n      break;\n    }\n    case TK_BETWEEN: {\n      testcase( jumpIfNull==0 );\n      exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);\n      break;\n    }\n#ifndef SQLITE_OMIT_SUBQUERY\n    case TK_IN: {\n      int destIfFalse = sqlite3VdbeMakeLabel(pParse);\n      int destIfNull = jumpIfNull ? dest : destIfFalse;\n      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);\n      sqlite3VdbeGoto(v, dest);\n      sqlite3VdbeResolveLabel(v, destIfFalse);\n      break;\n    }\n#endif\n    default: {\n    default_expr:\n      if( ExprAlwaysTrue(pExpr) ){\n        sqlite3VdbeGoto(v, dest);\n      }else if( ExprAlwaysFalse(pExpr) ){\n        /* No-op */\n      }else{\n        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);\n        sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);\n        VdbeCoverage(v);\n        testcase( regFree1==0 );\n        testcase( jumpIfNull==0 );\n      }\n      break;\n    }\n  }\n  sqlite3ReleaseTempReg(pParse, regFree1);\n  sqlite3ReleaseTempReg(pParse, regFree2);  \n}\n\n/*\n** Generate code for a boolean expression such that a jump is made\n** to the label \"dest\" if the expression is false but execution\n** continues straight thru if the expression is true.\n**\n** If the expression evaluates to NULL (neither true nor false) then\n** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull\n** is 0.\n*/\nSQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){\n  Vdbe *v = pParse->pVdbe;\n  int op = 0;\n  int regFree1 = 0;\n  int regFree2 = 0;\n  int r1, r2;\n\n  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );\n  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */\n  if( pExpr==0 )    return;\n  assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );\n\n  /* The value of pExpr->op and op are related as follows:\n  **\n  **       pExpr->op            op\n  **       ---------          ----------\n  **       TK_ISNULL          OP_NotNull\n  **       TK_NOTNULL         OP_IsNull\n  **       TK_NE              OP_Eq\n  **       TK_EQ              OP_Ne\n  **       TK_GT              OP_Le\n  **       TK_LE              OP_Gt\n  **       TK_GE              OP_Lt\n  **       TK_LT              OP_Ge\n  **\n  ** For other values of pExpr->op, op is undefined and unused.\n  ** The value of TK_ and OP_ constants are arranged such that we\n  ** can compute the mapping above using the following expression.\n  ** Assert()s verify that the computation is correct.\n  */\n  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);\n\n  /* Verify correct alignment of TK_ and OP_ constants\n  */\n  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );\n  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );\n  assert( pExpr->op!=TK_NE || op==OP_Eq );\n  assert( pExpr->op!=TK_EQ || op==OP_Ne );\n  assert( pExpr->op!=TK_LT || op==OP_Ge );\n  assert( pExpr->op!=TK_LE || op==OP_Gt );\n  assert( pExpr->op!=TK_GT || op==OP_Le );\n  assert( pExpr->op!=TK_GE || op==OP_Lt );\n\n  switch( pExpr->op ){\n    case TK_AND:\n    case TK_OR: {\n      Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);\n      if( pAlt!=pExpr ){\n        sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);\n      }else if( pExpr->op==TK_AND ){\n        testcase( jumpIfNull==0 );\n        sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);\n        sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);\n      }else{\n        int d2 = sqlite3VdbeMakeLabel(pParse);\n        testcase( jumpIfNull==0 );\n        sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,\n                          jumpIfNull^SQLITE_JUMPIFNULL);\n        sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);\n        sqlite3VdbeResolveLabel(v, d2);\n      }\n      break;\n    }\n    case TK_NOT: {\n      testcase( jumpIfNull==0 );\n      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);\n      break;\n    }\n    case TK_TRUTH: {\n      int isNot;   /* IS NOT TRUE or IS NOT FALSE */\n      int isTrue;  /* IS TRUE or IS NOT TRUE */\n      testcase( jumpIfNull==0 );\n      isNot = pExpr->op2==TK_ISNOT;\n      isTrue = sqlite3ExprTruthValue(pExpr->pRight);\n      testcase( isTrue && isNot );\n      testcase( !isTrue && isNot );\n      if( isTrue ^ isNot ){\n        /* IS TRUE and IS NOT FALSE */\n        sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,\n                           isNot ? 0 : SQLITE_JUMPIFNULL);\n\n      }else{\n        /* IS FALSE and IS NOT TRUE */\n        sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,\n                          isNot ? 0 : SQLITE_JUMPIFNULL);\n      }\n      break;\n    }\n    case TK_IS:\n    case TK_ISNOT:\n      testcase( pExpr->op==TK_IS );\n      testcase( pExpr->op==TK_ISNOT );\n      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;\n      jumpIfNull = SQLITE_NULLEQ;\n      /* Fall thru */\n    case TK_LT:\n    case TK_LE:\n    case TK_GT:\n    case TK_GE:\n    case TK_NE:\n    case TK_EQ: {\n      if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;\n      testcase( jumpIfNull==0 );\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);\n      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,\n                  r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));\n      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);\n      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);\n      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);\n      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);\n      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);\n      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);\n      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);\n      assert(TK_NE==OP_Ne); testcase(op==OP_Ne);\n      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);\n      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);\n      testcase( regFree1==0 );\n      testcase( regFree2==0 );\n      break;\n    }\n    case TK_ISNULL:\n    case TK_NOTNULL: {\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      sqlite3VdbeAddOp2(v, op, r1, dest);\n      testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);\n      testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);\n      testcase( regFree1==0 );\n      break;\n    }\n    case TK_BETWEEN: {\n      testcase( jumpIfNull==0 );\n      exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);\n      break;\n    }\n#ifndef SQLITE_OMIT_SUBQUERY\n    case TK_IN: {\n      if( jumpIfNull ){\n        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);\n      }else{\n        int destIfNull = sqlite3VdbeMakeLabel(pParse);\n        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);\n        sqlite3VdbeResolveLabel(v, destIfNull);\n      }\n      break;\n    }\n#endif\n    default: {\n    default_expr: \n      if( ExprAlwaysFalse(pExpr) ){\n        sqlite3VdbeGoto(v, dest);\n      }else if( ExprAlwaysTrue(pExpr) ){\n        /* no-op */\n      }else{\n        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);\n        sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);\n        VdbeCoverage(v);\n        testcase( regFree1==0 );\n        testcase( jumpIfNull==0 );\n      }\n      break;\n    }\n  }\n  sqlite3ReleaseTempReg(pParse, regFree1);\n  sqlite3ReleaseTempReg(pParse, regFree2);\n}\n\n/*\n** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before\n** code generation, and that copy is deleted after code generation. This\n** ensures that the original pExpr is unchanged.\n*/\nSQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){\n  sqlite3 *db = pParse->db;\n  Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);\n  if( db->mallocFailed==0 ){\n    sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);\n  }\n  sqlite3ExprDelete(db, pCopy);\n}\n\n/*\n** Expression pVar is guaranteed to be an SQL variable. pExpr may be any\n** type of expression.\n**\n** If pExpr is a simple SQL value - an integer, real, string, blob\n** or NULL value - then the VDBE currently being prepared is configured\n** to re-prepare each time a new value is bound to variable pVar.\n**\n** Additionally, if pExpr is a simple SQL value and the value is the\n** same as that currently bound to variable pVar, non-zero is returned.\n** Otherwise, if the values are not the same or if pExpr is not a simple\n** SQL value, zero is returned.\n*/\nstatic int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){\n  int res = 0;\n  int iVar;\n  sqlite3_value *pL, *pR = 0;\n  \n  sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);\n  if( pR ){\n    iVar = pVar->iColumn;\n    sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);\n    pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);\n    if( pL ){\n      if( sqlite3_value_type(pL)==SQLITE_TEXT ){\n        sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */\n      }\n      res =  0==sqlite3MemCompare(pL, pR, 0);\n    }\n    sqlite3ValueFree(pR);\n    sqlite3ValueFree(pL);\n  }\n\n  return res;\n}\n\n/*\n** Do a deep comparison of two expression trees.  Return 0 if the two\n** expressions are completely identical.  Return 1 if they differ only\n** by a COLLATE operator at the top level.  Return 2 if there are differences\n** other than the top-level COLLATE operator.\n**\n** If any subelement of pB has Expr.iTable==(-1) then it is allowed\n** to compare equal to an equivalent element in pA with Expr.iTable==iTab.\n**\n** The pA side might be using TK_REGISTER.  If that is the case and pB is\n** not using TK_REGISTER but is otherwise equivalent, then still return 0.\n**\n** Sometimes this routine will return 2 even if the two expressions\n** really are equivalent.  If we cannot prove that the expressions are\n** identical, we return 2 just to be safe.  So if this routine\n** returns 2, then you do not really know for certain if the two\n** expressions are the same.  But if you get a 0 or 1 return, then you\n** can be sure the expressions are the same.  In the places where\n** this routine is used, it does not hurt to get an extra 2 - that\n** just might result in some slightly slower code.  But returning\n** an incorrect 0 or 1 could lead to a malfunction.\n**\n** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in\n** pParse->pReprepare can be matched against literals in pB.  The \n** pParse->pVdbe->expmask bitmask is updated for each variable referenced.\n** If pParse is NULL (the normal case) then any TK_VARIABLE term in \n** Argument pParse should normally be NULL. If it is not NULL and pA or\n** pB causes a return value of 2.\n*/\nSQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){\n  u32 combinedFlags;\n  if( pA==0 || pB==0 ){\n    return pB==pA ? 0 : 2;\n  }\n  if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){\n    return 0;\n  }\n  combinedFlags = pA->flags | pB->flags;\n  if( combinedFlags & EP_IntValue ){\n    if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){\n      return 0;\n    }\n    return 2;\n  }\n  if( pA->op!=pB->op || pA->op==TK_RAISE ){\n    if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){\n      return 1;\n    }\n    if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){\n      return 1;\n    }\n    return 2;\n  }\n  if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){\n    if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){\n      if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;\n#ifndef SQLITE_OMIT_WINDOWFUNC\n      assert( pA->op==pB->op );\n      if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){\n        return 2;\n      }\n      if( ExprHasProperty(pA,EP_WinFunc) ){\n        if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){\n          return 2;\n        }\n      }\n#endif\n    }else if( pA->op==TK_NULL ){\n      return 0;\n    }else if( pA->op==TK_COLLATE ){\n      if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;\n    }else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){\n      return 2;\n    }\n  }\n  if( (pA->flags & (EP_Distinct|EP_Commuted))\n     != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;\n  if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){\n    if( combinedFlags & EP_xIsSelect ) return 2;\n    if( (combinedFlags & EP_FixedCol)==0\n     && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;\n    if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;\n    if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;\n    if( pA->op!=TK_STRING\n     && pA->op!=TK_TRUEFALSE\n     && ALWAYS((combinedFlags & EP_Reduced)==0)\n    ){\n      if( pA->iColumn!=pB->iColumn ) return 2;\n      if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2;\n      if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){\n        return 2;\n      }\n    }\n  }\n  return 0;\n}\n\n/*\n** Compare two ExprList objects.  Return 0 if they are identical, 1\n** if they are certainly different, or 2 if it is not possible to \n** determine if they are identical or not.\n**\n** If any subelement of pB has Expr.iTable==(-1) then it is allowed\n** to compare equal to an equivalent element in pA with Expr.iTable==iTab.\n**\n** This routine might return non-zero for equivalent ExprLists.  The\n** only consequence will be disabled optimizations.  But this routine\n** must never return 0 if the two ExprList objects are different, or\n** a malfunction will result.\n**\n** Two NULL pointers are considered to be the same.  But a NULL pointer\n** always differs from a non-NULL pointer.\n*/\nSQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){\n  int i;\n  if( pA==0 && pB==0 ) return 0;\n  if( pA==0 || pB==0 ) return 1;\n  if( pA->nExpr!=pB->nExpr ) return 1;\n  for(i=0; i<pA->nExpr; i++){\n    int res;\n    Expr *pExprA = pA->a[i].pExpr;\n    Expr *pExprB = pB->a[i].pExpr;\n    if( pA->a[i].sortFlags!=pB->a[i].sortFlags ) return 1;\n    if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res;\n  }\n  return 0;\n}\n\n/*\n** Like sqlite3ExprCompare() except COLLATE operators at the top-level\n** are ignored.\n*/\nSQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){\n  return sqlite3ExprCompare(0,\n             sqlite3ExprSkipCollateAndLikely(pA),\n             sqlite3ExprSkipCollateAndLikely(pB),\n             iTab);\n}\n\n/*\n** Return non-zero if Expr p can only be true if pNN is not NULL.\n**\n** Or if seenNot is true, return non-zero if Expr p can only be\n** non-NULL if pNN is not NULL\n*/\nstatic int exprImpliesNotNull(\n  Parse *pParse,      /* Parsing context */\n  Expr *p,            /* The expression to be checked */\n  Expr *pNN,          /* The expression that is NOT NULL */\n  int iTab,           /* Table being evaluated */\n  int seenNot         /* Return true only if p can be any non-NULL value */\n){\n  assert( p );\n  assert( pNN );\n  if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){\n    return pNN->op!=TK_NULL;\n  }\n  switch( p->op ){\n    case TK_IN: {\n      if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;\n      assert( ExprHasProperty(p,EP_xIsSelect)\n           || (p->x.pList!=0 && p->x.pList->nExpr>0) );\n      return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);\n    }\n    case TK_BETWEEN: {\n      ExprList *pList = p->x.pList;\n      assert( pList!=0 );\n      assert( pList->nExpr==2 );\n      if( seenNot ) return 0;\n      if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)\n       || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)\n      ){\n        return 1;\n      }\n      return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);\n    }\n    case TK_EQ:\n    case TK_NE:\n    case TK_LT:\n    case TK_LE:\n    case TK_GT:\n    case TK_GE:\n    case TK_PLUS:\n    case TK_MINUS:\n    case TK_BITOR:\n    case TK_LSHIFT:\n    case TK_RSHIFT: \n    case TK_CONCAT: \n      seenNot = 1;\n      /* Fall thru */\n    case TK_STAR:\n    case TK_REM:\n    case TK_BITAND:\n    case TK_SLASH: {\n      if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;\n      /* Fall thru into the next case */\n    }\n    case TK_SPAN:\n    case TK_COLLATE:\n    case TK_UPLUS:\n    case TK_UMINUS: {\n      return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);\n    }\n    case TK_TRUTH: {\n      if( seenNot ) return 0;\n      if( p->op2!=TK_IS ) return 0;\n      return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);\n    }\n    case TK_BITNOT:\n    case TK_NOT: {\n      return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);\n    }\n  }\n  return 0;\n}\n\n/*\n** Return true if we can prove the pE2 will always be true if pE1 is\n** true.  Return false if we cannot complete the proof or if pE2 might\n** be false.  Examples:\n**\n**     pE1: x==5       pE2: x==5             Result: true\n**     pE1: x>0        pE2: x==5             Result: false\n**     pE1: x=21       pE2: x=21 OR y=43     Result: true\n**     pE1: x!=123     pE2: x IS NOT NULL    Result: true\n**     pE1: x!=?1      pE2: x IS NOT NULL    Result: true\n**     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false\n**     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false\n**\n** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has\n** Expr.iTable<0 then assume a table number given by iTab.\n**\n** If pParse is not NULL, then the values of bound variables in pE1 are \n** compared against literal values in pE2 and pParse->pVdbe->expmask is\n** modified to record which bound variables are referenced.  If pParse \n** is NULL, then false will be returned if pE1 contains any bound variables.\n**\n** When in doubt, return false.  Returning true might give a performance\n** improvement.  Returning false might cause a performance reduction, but\n** it will always give the correct answer and is hence always safe.\n*/\nSQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){\n  if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){\n    return 1;\n  }\n  if( pE2->op==TK_OR\n   && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)\n             || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )\n  ){\n    return 1;\n  }\n  if( pE2->op==TK_NOTNULL\n   && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)\n  ){\n    return 1;\n  }\n  return 0;\n}\n\n/*\n** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().\n** If the expression node requires that the table at pWalker->iCur\n** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.\n**\n** This routine controls an optimization.  False positives (setting\n** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives\n** (never setting pWalker->eCode) is a harmless missed optimization.\n*/\nstatic int impliesNotNullRow(Walker *pWalker, Expr *pExpr){\n  testcase( pExpr->op==TK_AGG_COLUMN );\n  testcase( pExpr->op==TK_AGG_FUNCTION );\n  if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;\n  switch( pExpr->op ){\n    case TK_ISNOT:\n    case TK_ISNULL:\n    case TK_NOTNULL:\n    case TK_IS:\n    case TK_OR:\n    case TK_VECTOR:\n    case TK_CASE:\n    case TK_IN:\n    case TK_FUNCTION:\n    case TK_TRUTH:\n      testcase( pExpr->op==TK_ISNOT );\n      testcase( pExpr->op==TK_ISNULL );\n      testcase( pExpr->op==TK_NOTNULL );\n      testcase( pExpr->op==TK_IS );\n      testcase( pExpr->op==TK_OR );\n      testcase( pExpr->op==TK_VECTOR );\n      testcase( pExpr->op==TK_CASE );\n      testcase( pExpr->op==TK_IN );\n      testcase( pExpr->op==TK_FUNCTION );\n      testcase( pExpr->op==TK_TRUTH );\n      return WRC_Prune;\n    case TK_COLUMN:\n      if( pWalker->u.iCur==pExpr->iTable ){\n        pWalker->eCode = 1;\n        return WRC_Abort;\n      }\n      return WRC_Prune;\n\n    case TK_AND:\n      if( pWalker->eCode==0 ){\n        sqlite3WalkExpr(pWalker, pExpr->pLeft);\n        if( pWalker->eCode ){\n          pWalker->eCode = 0;\n          sqlite3WalkExpr(pWalker, pExpr->pRight);\n        }\n      }\n      return WRC_Prune;\n\n    case TK_BETWEEN:\n      if( sqlite3WalkExpr(pWalker, pExpr->pLeft)==WRC_Abort ){\n        assert( pWalker->eCode );\n        return WRC_Abort;\n      }\n      return WRC_Prune;\n\n    /* Virtual tables are allowed to use constraints like x=NULL.  So\n    ** a term of the form x=y does not prove that y is not null if x\n    ** is the column of a virtual table */\n    case TK_EQ:\n    case TK_NE:\n    case TK_LT:\n    case TK_LE:\n    case TK_GT:\n    case TK_GE: {\n      Expr *pLeft = pExpr->pLeft;\n      Expr *pRight = pExpr->pRight;\n      testcase( pExpr->op==TK_EQ );\n      testcase( pExpr->op==TK_NE );\n      testcase( pExpr->op==TK_LT );\n      testcase( pExpr->op==TK_LE );\n      testcase( pExpr->op==TK_GT );\n      testcase( pExpr->op==TK_GE );\n      /* The y.pTab=0 assignment in wherecode.c always happens after the\n      ** impliesNotNullRow() test */\n      if( (pLeft->op==TK_COLUMN && ALWAYS(pLeft->y.pTab!=0)\n                               && IsVirtual(pLeft->y.pTab))\n       || (pRight->op==TK_COLUMN && ALWAYS(pRight->y.pTab!=0)\n                               && IsVirtual(pRight->y.pTab))\n      ){\n        return WRC_Prune;\n      }\n    }\n    default:\n      return WRC_Continue;\n  }\n}\n\n/*\n** Return true (non-zero) if expression p can only be true if at least\n** one column of table iTab is non-null.  In other words, return true\n** if expression p will always be NULL or false if every column of iTab\n** is NULL.\n**\n** False negatives are acceptable.  In other words, it is ok to return\n** zero even if expression p will never be true of every column of iTab\n** is NULL.  A false negative is merely a missed optimization opportunity.\n**\n** False positives are not allowed, however.  A false positive may result\n** in an incorrect answer.\n**\n** Terms of p that are marked with EP_FromJoin (and hence that come from\n** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.\n**\n** This routine is used to check if a LEFT JOIN can be converted into\n** an ordinary JOIN.  The p argument is the WHERE clause.  If the WHERE\n** clause requires that some column of the right table of the LEFT JOIN\n** be non-NULL, then the LEFT JOIN can be safely converted into an\n** ordinary join.\n*/\nSQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){\n  Walker w;\n  p = sqlite3ExprSkipCollateAndLikely(p);\n  if( p==0 ) return 0;\n  if( p->op==TK_NOTNULL ){\n    p = p->pLeft;\n  }else{\n    while( p->op==TK_AND ){\n      if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1;\n      p = p->pRight;\n    }\n  }\n  w.xExprCallback = impliesNotNullRow;\n  w.xSelectCallback = 0;\n  w.xSelectCallback2 = 0;\n  w.eCode = 0;\n  w.u.iCur = iTab;\n  sqlite3WalkExpr(&w, p);\n  return w.eCode;\n}\n\n/*\n** An instance of the following structure is used by the tree walker\n** to determine if an expression can be evaluated by reference to the\n** index only, without having to do a search for the corresponding\n** table entry.  The IdxCover.pIdx field is the index.  IdxCover.iCur\n** is the cursor for the table.\n*/\nstruct IdxCover {\n  Index *pIdx;     /* The index to be tested for coverage */\n  int iCur;        /* Cursor number for the table corresponding to the index */\n};\n\n/*\n** Check to see if there are references to columns in table \n** pWalker->u.pIdxCover->iCur can be satisfied using the index\n** pWalker->u.pIdxCover->pIdx.\n*/\nstatic int exprIdxCover(Walker *pWalker, Expr *pExpr){\n  if( pExpr->op==TK_COLUMN\n   && pExpr->iTable==pWalker->u.pIdxCover->iCur\n   && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0\n  ){\n    pWalker->eCode = 1;\n    return WRC_Abort;\n  }\n  return WRC_Continue;\n}\n\n/*\n** Determine if an index pIdx on table with cursor iCur contains will\n** the expression pExpr.  Return true if the index does cover the\n** expression and false if the pExpr expression references table columns\n** that are not found in the index pIdx.\n**\n** An index covering an expression means that the expression can be\n** evaluated using only the index and without having to lookup the\n** corresponding table entry.\n*/\nSQLITE_PRIVATE int sqlite3ExprCoveredByIndex(\n  Expr *pExpr,        /* The index to be tested */\n  int iCur,           /* The cursor number for the corresponding table */\n  Index *pIdx         /* The index that might be used for coverage */\n){\n  Walker w;\n  struct IdxCover xcov;\n  memset(&w, 0, sizeof(w));\n  xcov.iCur = iCur;\n  xcov.pIdx = pIdx;\n  w.xExprCallback = exprIdxCover;\n  w.u.pIdxCover = &xcov;\n  sqlite3WalkExpr(&w, pExpr);\n  return !w.eCode;\n}\n\n\n/*\n** An instance of the following structure is used by the tree walker\n** to count references to table columns in the arguments of an \n** aggregate function, in order to implement the\n** sqlite3FunctionThisSrc() routine.\n*/\nstruct SrcCount {\n  SrcList *pSrc;   /* One particular FROM clause in a nested query */\n  int iSrcInner;   /* Smallest cursor number in this context */\n  int nThis;       /* Number of references to columns in pSrcList */\n  int nOther;      /* Number of references to columns in other FROM clauses */\n};\n\n/*\n** xSelect callback for sqlite3FunctionUsesThisSrc(). If this is the first\n** SELECT with a FROM clause encountered during this iteration, set\n** SrcCount.iSrcInner to the cursor number of the leftmost object in\n** the FROM cause.\n*/\nstatic int selectSrcCount(Walker *pWalker, Select *pSel){\n  struct SrcCount *p = pWalker->u.pSrcCount;\n  if( p->iSrcInner==0x7FFFFFFF && ALWAYS(pSel->pSrc) && pSel->pSrc->nSrc ){\n    pWalker->u.pSrcCount->iSrcInner = pSel->pSrc->a[0].iCursor;\n  }\n  return WRC_Continue;\n}\n\n/*\n** Count the number of references to columns.\n*/\nstatic int exprSrcCount(Walker *pWalker, Expr *pExpr){\n  /* There was once a NEVER() on the second term on the grounds that\n  ** sqlite3FunctionUsesThisSrc() was always called before \n  ** sqlite3ExprAnalyzeAggregates() and so the TK_COLUMNs have not yet \n  ** been converted into TK_AGG_COLUMN. But this is no longer true due\n  ** to window functions - sqlite3WindowRewrite() may now indirectly call\n  ** FunctionUsesThisSrc() when creating a new sub-select. */\n  if( pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN ){\n    int i;\n    struct SrcCount *p = pWalker->u.pSrcCount;\n    SrcList *pSrc = p->pSrc;\n    int nSrc = pSrc ? pSrc->nSrc : 0;\n    for(i=0; i<nSrc; i++){\n      if( pExpr->iTable==pSrc->a[i].iCursor ) break;\n    }\n    if( i<nSrc ){\n      p->nThis++;\n    }else if( pExpr->iTable<p->iSrcInner ){\n      /* In a well-formed parse tree (no name resolution errors),\n      ** TK_COLUMN nodes with smaller Expr.iTable values are in an\n      ** outer context.  Those are the only ones to count as \"other\" */\n      p->nOther++;\n    }\n  }\n  return WRC_Continue;\n}\n\n/*\n** Determine if any of the arguments to the pExpr Function reference\n** pSrcList.  Return true if they do.  Also return true if the function\n** has no arguments or has only constant arguments.  Return false if pExpr\n** references columns but not columns of tables found in pSrcList.\n*/\nSQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){\n  Walker w;\n  struct SrcCount cnt;\n  assert( pExpr->op==TK_AGG_FUNCTION );\n  memset(&w, 0, sizeof(w));\n  w.xExprCallback = exprSrcCount;\n  w.xSelectCallback = selectSrcCount;\n  w.u.pSrcCount = &cnt;\n  cnt.pSrc = pSrcList;\n  cnt.iSrcInner = (pSrcList&&pSrcList->nSrc)?pSrcList->a[0].iCursor:0x7FFFFFFF;\n  cnt.nThis = 0;\n  cnt.nOther = 0;\n  sqlite3WalkExprList(&w, pExpr->x.pList);\n#ifndef SQLITE_OMIT_WINDOWFUNC\n  if( ExprHasProperty(pExpr, EP_WinFunc) ){\n    sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);\n  }\n#endif\n  return cnt.nThis>0 || cnt.nOther==0;\n}\n\n/*\n** This is a Walker expression node callback.\n**\n** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo\n** object that is referenced does not refer directly to the Expr.  If\n** it does, make a copy.  This is done because the pExpr argument is\n** subject to change.\n**\n** The copy is stored on pParse->pConstExpr with a register number of 0.\n** This will cause the expression to be deleted automatically when the\n** Parse object is destroyed, but the zero register number means that it\n** will not generate any code in the preamble.\n*/\nstatic int agginfoPersistExprCb(Walker *pWalker, Expr *pExpr){\n  if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced))\n   && pExpr->pAggInfo!=0\n  ){\n    AggInfo *pAggInfo = pExpr->pAggInfo;\n    int iAgg = pExpr->iAgg;\n    Parse *pParse = pWalker->pParse;\n    sqlite3 *db = pParse->db;\n    assert( pExpr->op==TK_AGG_COLUMN || pExpr->op==TK_AGG_FUNCTION );\n    if( pExpr->op==TK_AGG_COLUMN ){\n      assert( iAgg>=0 && iAgg<pAggInfo->nColumn );\n      if( pAggInfo->aCol[iAgg].pExpr==pExpr ){\n        pExpr = sqlite3ExprDup(db, pExpr, 0);\n        if( pExpr ){\n          pAggInfo->aCol[iAgg].pExpr = pExpr;\n          pParse->pConstExpr = \n             sqlite3ExprListAppend(pParse, pParse->pConstExpr, pExpr);\n        }\n      }\n    }else{\n      assert( iAgg>=0 && iAgg<pAggInfo->nFunc );\n      if( pAggInfo->aFunc[iAgg].pExpr==pExpr ){\n        pExpr = sqlite3ExprDup(db, pExpr, 0);\n        if( pExpr ){\n          pAggInfo->aFunc[iAgg].pExpr = pExpr;\n          pParse->pConstExpr = \n             sqlite3ExprListAppend(pParse, pParse->pConstExpr, pExpr);\n        }\n      }\n    }\n  }\n  return WRC_Continue;\n}\n\n/*\n** Initialize a Walker object so that will persist AggInfo entries referenced\n** by the tree that is walked.\n*/\nSQLITE_PRIVATE void sqlite3AggInfoPersistWalkerInit(Walker *pWalker, Parse *pParse){\n  memset(pWalker, 0, sizeof(*pWalker));\n  pWalker->pParse = pParse;\n  pWalker->xExprCallback = agginfoPersistExprCb;\n  pWalker->xSelectCallback = sqlite3SelectWalkNoop;\n}\n\n/*\n** Add a new element to the pAggInfo->aCol[] array.  Return the index of\n** the new element.  Return a negative number if malloc fails.\n*/\nstatic int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){\n  int i;\n  pInfo->aCol = sqlite3ArrayAllocate(\n       db,\n       pInfo->aCol,\n       sizeof(pInfo->aCol[0]),\n       &pInfo->nColumn,\n       &i\n  );\n  return i;\n}    \n\n/*\n** Add a new element to the pAggInfo->aFunc[] array.  Return the index of\n** the new element.  Return a negative number if malloc fails.\n*/\nstatic int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){\n  int i;\n  pInfo->aFunc = sqlite3ArrayAllocate(\n       db, \n       pInfo->aFunc,\n       sizeof(pInfo->aFunc[0]),\n       &pInfo->nFunc,\n       &i\n  );\n  return i;\n}\n\n/*\n** This is the xExprCallback for a tree walker.  It is used to\n** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates\n** for additional information.\n*/\nstatic int analyzeAggregate(Walker *pWalker, Expr *pExpr){\n  int i;\n  NameContext *pNC = pWalker->u.pNC;\n  Parse *pParse = pNC->pParse;\n  SrcList *pSrcList = pNC->pSrcList;\n  AggInfo *pAggInfo = pNC->uNC.pAggInfo;\n\n  assert( pNC->ncFlags & NC_UAggInfo );\n  switch( pExpr->op ){\n    case TK_AGG_COLUMN:\n    case TK_COLUMN: {\n      testcase( pExpr->op==TK_AGG_COLUMN );\n      testcase( pExpr->op==TK_COLUMN );\n      /* Check to see if the column is in one of the tables in the FROM\n      ** clause of the aggregate query */\n      if( ALWAYS(pSrcList!=0) ){\n        struct SrcList_item *pItem = pSrcList->a;\n        for(i=0; i<pSrcList->nSrc; i++, pItem++){\n          struct AggInfo_col *pCol;\n          assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );\n          if( pExpr->iTable==pItem->iCursor ){\n            /* If we reach this point, it means that pExpr refers to a table\n            ** that is in the FROM clause of the aggregate query.  \n            **\n            ** Make an entry for the column in pAggInfo->aCol[] if there\n            ** is not an entry there already.\n            */\n            int k;\n            pCol = pAggInfo->aCol;\n            for(k=0; k<pAggInfo->nColumn; k++, pCol++){\n              if( pCol->iTable==pExpr->iTable &&\n                  pCol->iColumn==pExpr->iColumn ){\n                break;\n              }\n            }\n            if( (k>=pAggInfo->nColumn)\n             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 \n            ){\n              pCol = &pAggInfo->aCol[k];\n              pCol->pTab = pExpr->y.pTab;\n              pCol->iTable = pExpr->iTable;\n              pCol->iColumn = pExpr->iColumn;\n              pCol->iMem = ++pParse->nMem;\n              pCol->iSorterColumn = -1;\n              pCol->pExpr = pExpr;\n              if( pAggInfo->pGroupBy ){\n                int j, n;\n                ExprList *pGB = pAggInfo->pGroupBy;\n                struct ExprList_item *pTerm = pGB->a;\n                n = pGB->nExpr;\n                for(j=0; j<n; j++, pTerm++){\n                  Expr *pE = pTerm->pExpr;\n                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&\n                      pE->iColumn==pExpr->iColumn ){\n                    pCol->iSorterColumn = j;\n                    break;\n                  }\n                }\n              }\n              if( pCol->iSorterColumn<0 ){\n                pCol->iSorterColumn = pAggInfo->nSortingColumn++;\n              }\n            }\n            /* There is now an entry for pExpr in pAggInfo->aCol[] (either\n            ** because it was there before or because we just created it).\n            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that\n            ** pAggInfo->aCol[] entry.\n            */\n            ExprSetVVAProperty(pExpr, EP_NoReduce);\n            pExpr->pAggInfo = pAggInfo;\n            pExpr->op = TK_AGG_COLUMN;\n            pExpr->iAgg = (i16)k;\n            break;\n          } /* endif pExpr->iTable==pItem->iCursor */\n        } /* end loop over pSrcList */\n      }\n      return WRC_Prune;\n    }\n    case TK_AGG_FUNCTION: {\n      if( (pNC->ncFlags & NC_InAggFunc)==0\n       && pWalker->walkerDepth==pExpr->op2\n      ){\n        /* Check to see if pExpr is a duplicate of another aggregate \n        ** function that is already in the pAggInfo structure\n        */\n        struct AggInfo_func *pItem = pAggInfo->aFunc;\n        for(i=0; i<pAggInfo->nFunc; i++, pItem++){\n          if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){\n            break;\n          }\n        }\n        if( i>=pAggInfo->nFunc ){\n          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]\n          */\n          u8 enc = ENC(pParse->db);\n          i = addAggInfoFunc(pParse->db, pAggInfo);\n          if( i>=0 ){\n            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );\n            pItem = &pAggInfo->aFunc[i];\n            pItem->pExpr = pExpr;\n            pItem->iMem = ++pParse->nMem;\n            assert( !ExprHasProperty(pExpr, EP_IntValue) );\n            pItem->pFunc = sqlite3FindFunction(pParse->db,\n                   pExpr->u.zToken, \n                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);\n            if( pExpr->flags & EP_Distinct ){\n              pItem->iDistinct = pParse->nTab++;\n            }else{\n              pItem->iDistinct = -1;\n            }\n          }\n        }\n        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry\n        */\n        assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );\n        ExprSetVVAProperty(pExpr, EP_NoReduce);\n        pExpr->iAgg = (i16)i;\n        pExpr->pAggInfo = pAggInfo;\n        return WRC_Prune;\n      }else{\n        return WRC_Continue;\n      }\n    }\n  }\n  return WRC_Continue;\n}\n\n/*\n** Analyze the pExpr expression looking for aggregate functions and\n** for variables that need to be added to AggInfo object that pNC->pAggInfo\n** points to.  Additional entries are made on the AggInfo object as\n** necessary.\n**\n** This routine should only be called after the expression has been\n** analyzed by sqlite3ResolveExprNames().\n*/\nSQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){\n  Walker w;\n  w.xExprCallback = analyzeAggregate;\n  w.xSelectCallback = sqlite3WalkerDepthIncrease;\n  w.xSelectCallback2 = sqlite3WalkerDepthDecrease;\n  w.walkerDepth = 0;\n  w.u.pNC = pNC;\n  w.pParse = 0;\n  assert( pNC->pSrcList!=0 );\n  sqlite3WalkExpr(&w, pExpr);\n}\n\n/*\n** Call sqlite3ExprAnalyzeAggregates() for every expression in an\n** expression list.  Return the number of errors.\n**\n** If an error is found, the analysis is cut short.\n*/\nSQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){\n  struct ExprList_item *pItem;\n  int i;\n  if( pList ){\n    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){\n      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);\n    }\n  }\n}\n\n/*\n** Allocate a single new register for use to hold some intermediate result.\n*/\nSQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){\n  if( pParse->nTempReg==0 ){\n    return ++pParse->nMem;\n  }\n  return pParse->aTempReg[--pParse->nTempReg];\n}\n\n/*\n** Deallocate a register, making available for reuse for some other\n** purpose.\n*/\nSQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){\n  if( iReg ){\n    sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0);\n    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){\n      pParse->aTempReg[pParse->nTempReg++] = iReg;\n    }\n  }\n}\n\n/*\n** Allocate or deallocate a block of nReg consecutive registers.\n*/\nSQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){\n  int i, n;\n  if( nReg==1 ) return sqlite3GetTempReg(pParse);\n  i = pParse->iRangeReg;\n  n = pParse->nRangeReg;\n  if( nReg<=n ){\n    pParse->iRangeReg += nReg;\n    pParse->nRangeReg -= nReg;\n  }else{\n    i = pParse->nMem+1;\n    pParse->nMem += nReg;\n  }\n  return i;\n}\nSQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){\n  if( nReg==1 ){\n    sqlite3ReleaseTempReg(pParse, iReg);\n    return;\n  }\n  sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0);\n  if( nReg>pParse->nRangeReg ){\n    pParse->nRangeReg = nReg;\n    pParse->iRangeReg = iReg;\n  }\n}\n\n/*\n** Mark all temporary registers as being unavailable for reuse.\n**\n** Always invoke this procedure after coding a subroutine or co-routine\n** that might be invoked from other parts of the code, to ensure that\n** the sub/co-routine does not use registers in common with the code that\n** invokes the sub/co-routine.\n*/\nSQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){\n  pParse->nTempReg = 0;\n  pParse->nRangeReg = 0;\n}\n\n/*\n** Validate that no temporary register falls within the range of\n** iFirst..iLast, inclusive.  This routine is only call from within assert()\n** statements.\n*/\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){\n  int i;\n  if( pParse->nRangeReg>0\n   && pParse->iRangeReg+pParse->nRangeReg > iFirst\n   && pParse->iRangeReg <= iLast\n  ){\n     return 0;\n  }\n  for(i=0; i<pParse->nTempReg; i++){\n    if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){\n      return 0;\n    }\n  }\n  return 1;\n}\n#endif /* SQLITE_DEBUG */\n\n/************** End of expr.c ************************************************/\n/************** Begin file alter.c *******************************************/\n/*\n** 2005 February 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains C code routines that used to generate VDBE code\n** that implements the ALTER TABLE command.\n*/\n/* #include \"sqliteInt.h\" */\n\n/*\n** The code in this file only exists if we are not omitting the\n** ALTER TABLE logic from the build.\n*/\n#ifndef SQLITE_OMIT_ALTERTABLE\n\n/*\n** Parameter zName is the name of a table that is about to be altered\n** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).\n** If the table is a system table, this function leaves an error message\n** in pParse->zErr (system tables may not be altered) and returns non-zero.\n**\n** Or, if zName is not a system table, zero is returned.\n*/\nstatic int isAlterableTable(Parse *pParse, Table *pTab){\n  if( 0==sqlite3StrNICmp(pTab->zName, \"sqlite_\", 7) \n#ifndef SQLITE_OMIT_VIRTUALTABLE\n   || ( (pTab->tabFlags & TF_Shadow)!=0\n        && sqlite3ReadOnlyShadowTables(pParse->db)\n   )\n#endif\n  ){\n    sqlite3ErrorMsg(pParse, \"table %s may not be altered\", pTab->zName);\n    return 1;\n  }\n  return 0;\n}\n\n/*\n** Generate code to verify that the schemas of database zDb and, if\n** bTemp is not true, database \"temp\", can still be parsed. This is\n** called at the end of the generation of an ALTER TABLE ... RENAME ...\n** statement to ensure that the operation has not rendered any schema\n** objects unusable.\n*/\nstatic void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){\n  sqlite3NestedParse(pParse, \n      \"SELECT 1 \"\n      \"FROM \\\"%w\\\".%s \"\n      \"WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'\"\n      \" AND sql NOT LIKE 'create virtual%%'\"\n      \" AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL \",\n      zDb, MASTER_NAME, \n      zDb, bTemp\n  );\n\n  if( bTemp==0 ){\n    sqlite3NestedParse(pParse, \n        \"SELECT 1 \"\n        \"FROM temp.%s \"\n        \"WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'\"\n        \" AND sql NOT LIKE 'create virtual%%'\"\n        \" AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL \",\n        MASTER_NAME, zDb \n    );\n  }\n}\n\n/*\n** Generate code to reload the schema for database iDb. And, if iDb!=1, for\n** the temp database as well.\n*/\nstatic void renameReloadSchema(Parse *pParse, int iDb){\n  Vdbe *v = pParse->pVdbe;\n  if( v ){\n    sqlite3ChangeCookie(pParse, iDb);\n    sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0);\n    if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0);\n  }\n}\n\n/*\n** Generate code to implement the \"ALTER TABLE xxx RENAME TO yyy\" \n** command. \n*/\nSQLITE_PRIVATE void sqlite3AlterRenameTable(\n  Parse *pParse,            /* Parser context. */\n  SrcList *pSrc,            /* The table to rename. */\n  Token *pName              /* The new table name. */\n){\n  int iDb;                  /* Database that contains the table */\n  char *zDb;                /* Name of database iDb */\n  Table *pTab;              /* Table being renamed */\n  char *zName = 0;          /* NULL-terminated version of pName */ \n  sqlite3 *db = pParse->db; /* Database connection */\n  int nTabName;             /* Number of UTF-8 characters in zTabName */\n  const char *zTabName;     /* Original name of the table */\n  Vdbe *v;\n  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */\n  u32 savedDbFlags;         /* Saved value of db->mDbFlags */\n\n  savedDbFlags = db->mDbFlags;  \n  if( NEVER(db->mallocFailed) ) goto exit_rename_table;\n  assert( pSrc->nSrc==1 );\n  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );\n\n  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);\n  if( !pTab ) goto exit_rename_table;\n  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n  zDb = db->aDb[iDb].zDbSName;\n  db->mDbFlags |= DBFLAG_PreferBuiltin;\n\n  /* Get a NULL terminated version of the new table name. */\n  zName = sqlite3NameFromToken(db, pName);\n  if( !zName ) goto exit_rename_table;\n\n  /* Check that a table or index named 'zName' does not already exist\n  ** in database iDb. If so, this is an error.\n  */\n  if( sqlite3FindTable(db, zName, zDb)\n   || sqlite3FindIndex(db, zName, zDb)\n   || sqlite3IsShadowTableOf(db, pTab, zName)\n  ){\n    sqlite3ErrorMsg(pParse, \n        \"there is already another table or index with this name: %s\", zName);\n    goto exit_rename_table;\n  }\n\n  /* Make sure it is not a system table being altered, or a reserved name\n  ** that the table is being renamed to.\n  */\n  if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){\n    goto exit_rename_table;\n  }\n  if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,\"table\",zName) ){\n    goto exit_rename_table;\n  }\n\n#ifndef SQLITE_OMIT_VIEW\n  if( pTab->pSelect ){\n    sqlite3ErrorMsg(pParse, \"view %s may not be altered\", pTab->zName);\n    goto exit_rename_table;\n  }\n#endif\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  /* Invoke the authorization callback. */\n  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){\n    goto exit_rename_table;\n  }\n#endif\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( sqlite3ViewGetColumnNames(pParse, pTab) ){\n    goto exit_rename_table;\n  }\n  if( IsVirtual(pTab) ){\n    pVTab = sqlite3GetVTable(db, pTab);\n    if( pVTab->pVtab->pModule->xRename==0 ){\n      pVTab = 0;\n    }\n  }\n#endif\n\n  /* Begin a transaction for database iDb. Then modify the schema cookie\n  ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),\n  ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the \n  ** nested SQL may raise an exception.  */\n  v = sqlite3GetVdbe(pParse);\n  if( v==0 ){\n    goto exit_rename_table;\n  }\n  sqlite3MayAbort(pParse);\n\n  /* figure out how many UTF-8 characters are in zName */\n  zTabName = pTab->zName;\n  nTabName = sqlite3Utf8CharLen(zTabName, -1);\n\n  /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in\n  ** the schema to use the new table name.  */\n  sqlite3NestedParse(pParse, \n      \"UPDATE \\\"%w\\\".%s SET \"\n      \"sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) \"\n      \"WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)\"\n      \"AND   name NOT LIKE 'sqliteX_%%' ESCAPE 'X'\"\n      , zDb, MASTER_NAME, zDb, zTabName, zName, (iDb==1), zTabName\n  );\n\n  /* Update the tbl_name and name columns of the sqlite_master table\n  ** as required.  */\n  sqlite3NestedParse(pParse,\n      \"UPDATE %Q.%s SET \"\n          \"tbl_name = %Q, \"\n          \"name = CASE \"\n            \"WHEN type='table' THEN %Q \"\n            \"WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' \"\n            \"     AND type='index' THEN \"\n             \"'sqlite_autoindex_' || %Q || substr(name,%d+18) \"\n            \"ELSE name END \"\n      \"WHERE tbl_name=%Q COLLATE nocase AND \"\n          \"(type='table' OR type='index' OR type='trigger');\", \n      zDb, MASTER_NAME, \n      zName, zName, zName, \n      nTabName, zTabName\n  );\n\n#ifndef SQLITE_OMIT_AUTOINCREMENT\n  /* If the sqlite_sequence table exists in this database, then update \n  ** it with the new table name.\n  */\n  if( sqlite3FindTable(db, \"sqlite_sequence\", zDb) ){\n    sqlite3NestedParse(pParse,\n        \"UPDATE \\\"%w\\\".sqlite_sequence set name = %Q WHERE name = %Q\",\n        zDb, zName, pTab->zName);\n  }\n#endif\n\n  /* If the table being renamed is not itself part of the temp database,\n  ** edit view and trigger definitions within the temp database \n  ** as required.  */\n  if( iDb!=1 ){\n    sqlite3NestedParse(pParse, \n        \"UPDATE sqlite_temp_master SET \"\n            \"sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), \"\n            \"tbl_name = \"\n              \"CASE WHEN tbl_name=%Q COLLATE nocase AND \"\n              \"          sqlite_rename_test(%Q, sql, type, name, 1) \"\n              \"THEN %Q ELSE tbl_name END \"\n            \"WHERE type IN ('view', 'trigger')\"\n        , zDb, zTabName, zName, zTabName, zDb, zName);\n  }\n\n  /* If this is a virtual table, invoke the xRename() function if\n  ** one is defined. The xRename() callback will modify the names\n  ** of any resources used by the v-table implementation (including other\n  ** SQLite tables) that are identified by the name of the virtual table.\n  */\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( pVTab ){\n    int i = ++pParse->nMem;\n    sqlite3VdbeLoadString(v, i, zName);\n    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);\n  }\n#endif\n\n  renameReloadSchema(pParse, iDb);\n  renameTestSchema(pParse, zDb, iDb==1);\n\nexit_rename_table:\n  sqlite3SrcListDelete(db, pSrc);\n  sqlite3DbFree(db, zName);\n  db->mDbFlags = savedDbFlags;\n}\n\n/*\n** Write code that will raise an error if the table described by\n** zDb and zTab is not empty.\n*/\nstatic void sqlite3ErrorIfNotEmpty(\n  Parse *pParse,        /* Parsing context */\n  const char *zDb,      /* Schema holding the table */\n  const char *zTab,     /* Table to check for empty */\n  const char *zErr      /* Error message text */\n){\n  sqlite3NestedParse(pParse,\n     \"SELECT raise(ABORT,%Q) FROM \\\"%w\\\".\\\"%w\\\"\",\n     zErr, zDb, zTab\n  );\n}\n\n/*\n** This function is called after an \"ALTER TABLE ... ADD\" statement\n** has been parsed. Argument pColDef contains the text of the new\n** column definition.\n**\n** The Table structure pParse->pNewTable was extended to include\n** the new column during parsing.\n*/\nSQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){\n  Table *pNew;              /* Copy of pParse->pNewTable */\n  Table *pTab;              /* Table being altered */\n  int iDb;                  /* Database number */\n  const char *zDb;          /* Database name */\n  const char *zTab;         /* Table name */\n  char *zCol;               /* Null-terminated column definition */\n  Column *pCol;             /* The new column */\n  Expr *pDflt;              /* Default value for the new column */\n  sqlite3 *db;              /* The database connection; */\n  Vdbe *v;                  /* The prepared statement under construction */\n  int r1;                   /* Temporary registers */\n\n  db = pParse->db;\n  if( pParse->nErr || db->mallocFailed ) return;\n  pNew = pParse->pNewTable;\n  assert( pNew );\n\n  assert( sqlite3BtreeHoldsAllMutexes(db) );\n  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);\n  zDb = db->aDb[iDb].zDbSName;\n  zTab = &pNew->zName[16];  /* Skip the \"sqlite_altertab_\" prefix on the name */\n  pCol = &pNew->aCol[pNew->nCol-1];\n  pDflt = pCol->pDflt;\n  pTab = sqlite3FindTable(db, zTab, zDb);\n  assert( pTab );\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  /* Invoke the authorization callback. */\n  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){\n    return;\n  }\n#endif\n\n\n  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.\n  ** If there is a NOT NULL constraint, then the default value for the\n  ** column must not be NULL.\n  */\n  if( pCol->colFlags & COLFLAG_PRIMKEY ){\n    sqlite3ErrorMsg(pParse, \"Cannot add a PRIMARY KEY column\");\n    return;\n  }\n  if( pNew->pIndex ){\n    sqlite3ErrorMsg(pParse,\n         \"Cannot add a UNIQUE column\");\n    return;\n  }\n  if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){\n    /* If the default value for the new column was specified with a \n    ** literal NULL, then set pDflt to 0. This simplifies checking\n    ** for an SQL NULL default below.\n    */\n    assert( pDflt==0 || pDflt->op==TK_SPAN );\n    if( pDflt && pDflt->pLeft->op==TK_NULL ){\n      pDflt = 0;\n    }\n    if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){\n      sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,\n          \"Cannot add a REFERENCES column with non-NULL default value\");\n    }\n    if( pCol->notNull && !pDflt ){\n      sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,\n          \"Cannot add a NOT NULL column with default value NULL\");\n    }\n\n\n    /* Ensure the default expression is something that sqlite3ValueFromExpr()\n    ** can handle (i.e. not CURRENT_TIME etc.)\n    */\n    if( pDflt ){\n      sqlite3_value *pVal = 0;\n      int rc;\n      rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);\n      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );\n      if( rc!=SQLITE_OK ){\n        assert( db->mallocFailed == 1 );\n        return;\n      }\n      if( !pVal ){\n        sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,\n           \"Cannot add a column with non-constant default\");\n      }\n      sqlite3ValueFree(pVal);\n    }\n  }else if( pCol->colFlags & COLFLAG_STORED ){\n    sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, \"cannot add a STORED column\");\n  }\n\n\n  /* Modify the CREATE TABLE statement. */\n  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);\n  if( zCol ){\n    char *zEnd = &zCol[pColDef->n-1];\n    u32 savedDbFlags = db->mDbFlags;\n    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){\n      *zEnd-- = '\\0';\n    }\n    db->mDbFlags |= DBFLAG_PreferBuiltin;\n    sqlite3NestedParse(pParse, \n        \"UPDATE \\\"%w\\\".%s SET \"\n          \"sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) \"\n        \"WHERE type = 'table' AND name = %Q\", \n      zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,\n      zTab\n    );\n    sqlite3DbFree(db, zCol);\n    db->mDbFlags = savedDbFlags;\n  }\n\n  /* Make sure the schema version is at least 3.  But do not upgrade\n  ** from less than 3 to 4, as that will corrupt any preexisting DESC\n  ** index.\n  */\n  v = sqlite3GetVdbe(pParse);\n  if( v ){\n    r1 = sqlite3GetTempReg(pParse);\n    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);\n    sqlite3VdbeUsesBtree(v, iDb);\n    sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);\n    sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);\n    VdbeCoverage(v);\n    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);\n    sqlite3ReleaseTempReg(pParse, r1);\n  }\n\n  /* Reload the table definition */\n  renameReloadSchema(pParse, iDb);\n}\n\n/*\n** This function is called by the parser after the table-name in\n** an \"ALTER TABLE <table-name> ADD\" statement is parsed. Argument \n** pSrc is the full-name of the table being altered.\n**\n** This routine makes a (partial) copy of the Table structure\n** for the table being altered and sets Parse.pNewTable to point\n** to it. Routines called by the parser as the column definition\n** is parsed (i.e. sqlite3AddColumn()) add the new Column data to \n** the copy. The copy of the Table structure is deleted by tokenize.c \n** after parsing is finished.\n**\n** Routine sqlite3AlterFinishAddColumn() will be called to complete\n** coding the \"ALTER TABLE ... ADD\" statement.\n*/\nSQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){\n  Table *pNew;\n  Table *pTab;\n  int iDb;\n  int i;\n  int nAlloc;\n  sqlite3 *db = pParse->db;\n\n  /* Look up the table being altered. */\n  assert( pParse->pNewTable==0 );\n  assert( sqlite3BtreeHoldsAllMutexes(db) );\n  if( db->mallocFailed ) goto exit_begin_add_column;\n  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);\n  if( !pTab ) goto exit_begin_add_column;\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( IsVirtual(pTab) ){\n    sqlite3ErrorMsg(pParse, \"virtual tables may not be altered\");\n    goto exit_begin_add_column;\n  }\n#endif\n\n  /* Make sure this is not an attempt to ALTER a view. */\n  if( pTab->pSelect ){\n    sqlite3ErrorMsg(pParse, \"Cannot add a column to a view\");\n    goto exit_begin_add_column;\n  }\n  if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){\n    goto exit_begin_add_column;\n  }\n\n  sqlite3MayAbort(pParse);\n  assert( pTab->addColOffset>0 );\n  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n\n  /* Put a copy of the Table struct in Parse.pNewTable for the\n  ** sqlite3AddColumn() function and friends to modify.  But modify\n  ** the name by adding an \"sqlite_altertab_\" prefix.  By adding this\n  ** prefix, we insure that the name will not collide with an existing\n  ** table because user table are not allowed to have the \"sqlite_\"\n  ** prefix on their name.\n  */\n  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));\n  if( !pNew ) goto exit_begin_add_column;\n  pParse->pNewTable = pNew;\n  pNew->nTabRef = 1;\n  pNew->nCol = pTab->nCol;\n  assert( pNew->nCol>0 );\n  nAlloc = (((pNew->nCol-1)/8)*8)+8;\n  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );\n  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);\n  pNew->zName = sqlite3MPrintf(db, \"sqlite_altertab_%s\", pTab->zName);\n  if( !pNew->aCol || !pNew->zName ){\n    assert( db->mallocFailed );\n    goto exit_begin_add_column;\n  }\n  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);\n  for(i=0; i<pNew->nCol; i++){\n    Column *pCol = &pNew->aCol[i];\n    pCol->zName = sqlite3DbStrDup(db, pCol->zName);\n    pCol->hName = sqlite3StrIHash(pCol->zName);\n    pCol->zColl = 0;\n    pCol->pDflt = 0;\n  }\n  pNew->pSchema = db->aDb[iDb].pSchema;\n  pNew->addColOffset = pTab->addColOffset;\n  pNew->nTabRef = 1;\n\nexit_begin_add_column:\n  sqlite3SrcListDelete(db, pSrc);\n  return;\n}\n\n/*\n** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN\n** command. This function checks if the table is a view or virtual\n** table (columns of views or virtual tables may not be renamed). If so,\n** it loads an error message into pParse and returns non-zero.\n**\n** Or, if pTab is not a view or virtual table, zero is returned.\n*/\n#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)\nstatic int isRealTable(Parse *pParse, Table *pTab){\n  const char *zType = 0;\n#ifndef SQLITE_OMIT_VIEW\n  if( pTab->pSelect ){\n    zType = \"view\";\n  }\n#endif\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( IsVirtual(pTab) ){\n    zType = \"virtual table\";\n  }\n#endif\n  if( zType ){\n    sqlite3ErrorMsg(\n        pParse, \"cannot rename columns of %s \\\"%s\\\"\", zType, pTab->zName\n    );\n    return 1;\n  }\n  return 0;\n}\n#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */\n# define isRealTable(x,y) (0)\n#endif\n\n/*\n** Handles the following parser reduction:\n**\n**  cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew\n*/\nSQLITE_PRIVATE void sqlite3AlterRenameColumn(\n  Parse *pParse,                  /* Parsing context */\n  SrcList *pSrc,                  /* Table being altered.  pSrc->nSrc==1 */\n  Token *pOld,                    /* Name of column being changed */\n  Token *pNew                     /* New column name */\n){\n  sqlite3 *db = pParse->db;       /* Database connection */\n  Table *pTab;                    /* Table being updated */\n  int iCol;                       /* Index of column being renamed */\n  char *zOld = 0;                 /* Old column name */\n  char *zNew = 0;                 /* New column name */\n  const char *zDb;                /* Name of schema containing the table */\n  int iSchema;                    /* Index of the schema */\n  int bQuote;                     /* True to quote the new name */\n\n  /* Locate the table to be altered */\n  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);\n  if( !pTab ) goto exit_rename_column;\n\n  /* Cannot alter a system table */\n  if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;\n  if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;\n\n  /* Which schema holds the table to be altered */  \n  iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);\n  assert( iSchema>=0 );\n  zDb = db->aDb[iSchema].zDbSName;\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  /* Invoke the authorization callback. */\n  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){\n    goto exit_rename_column;\n  }\n#endif\n\n  /* Make sure the old name really is a column name in the table to be\n  ** altered.  Set iCol to be the index of the column being renamed */\n  zOld = sqlite3NameFromToken(db, pOld);\n  if( !zOld ) goto exit_rename_column;\n  for(iCol=0; iCol<pTab->nCol; iCol++){\n    if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;\n  }\n  if( iCol==pTab->nCol ){\n    sqlite3ErrorMsg(pParse, \"no such column: \\\"%s\\\"\", zOld);\n    goto exit_rename_column;\n  }\n\n  /* Do the rename operation using a recursive UPDATE statement that\n  ** uses the sqlite_rename_column() SQL function to compute the new\n  ** CREATE statement text for the sqlite_master table.\n  */\n  sqlite3MayAbort(pParse);\n  zNew = sqlite3NameFromToken(db, pNew);\n  if( !zNew ) goto exit_rename_column;\n  assert( pNew->n>0 );\n  bQuote = sqlite3Isquote(pNew->z[0]);\n  sqlite3NestedParse(pParse, \n      \"UPDATE \\\"%w\\\".%s SET \"\n      \"sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) \"\n      \"WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' \"\n      \" AND (type != 'index' OR tbl_name = %Q)\"\n      \" AND sql NOT LIKE 'create virtual%%'\",\n      zDb, MASTER_NAME, \n      zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,\n      pTab->zName\n  );\n\n  sqlite3NestedParse(pParse, \n      \"UPDATE temp.%s SET \"\n      \"sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) \"\n      \"WHERE type IN ('trigger', 'view')\",\n      MASTER_NAME, \n      zDb, pTab->zName, iCol, zNew, bQuote\n  );\n\n  /* Drop and reload the database schema. */\n  renameReloadSchema(pParse, iSchema);\n  renameTestSchema(pParse, zDb, iSchema==1);\n\n exit_rename_column:\n  sqlite3SrcListDelete(db, pSrc);\n  sqlite3DbFree(db, zOld);\n  sqlite3DbFree(db, zNew);\n  return;\n}\n\n/*\n** Each RenameToken object maps an element of the parse tree into\n** the token that generated that element.  The parse tree element\n** might be one of:\n**\n**     *  A pointer to an Expr that represents an ID\n**     *  The name of a table column in Column.zName\n**\n** A list of RenameToken objects can be constructed during parsing.\n** Each new object is created by sqlite3RenameTokenMap().\n** As the parse tree is transformed, the sqlite3RenameTokenRemap()\n** routine is used to keep the mapping current.\n**\n** After the parse finishes, renameTokenFind() routine can be used\n** to look up the actual token value that created some element in\n** the parse tree.\n*/\nstruct RenameToken {\n  void *p;               /* Parse tree element created by token t */\n  Token t;               /* The token that created parse tree element p */\n  RenameToken *pNext;    /* Next is a list of all RenameToken objects */\n};\n\n/*\n** The context of an ALTER TABLE RENAME COLUMN operation that gets passed\n** down into the Walker.\n*/\ntypedef struct RenameCtx RenameCtx;\nstruct RenameCtx {\n  RenameToken *pList;             /* List of tokens to overwrite */\n  int nList;                      /* Number of tokens in pList */\n  int iCol;                       /* Index of column being renamed */\n  Table *pTab;                    /* Table being ALTERed */ \n  const char *zOld;               /* Old column name */\n};\n\n#ifdef SQLITE_DEBUG\n/*\n** This function is only for debugging. It performs two tasks:\n**\n**   1. Checks that pointer pPtr does not already appear in the \n**      rename-token list.\n**\n**   2. Dereferences each pointer in the rename-token list.\n**\n** The second is most effective when debugging under valgrind or\n** address-sanitizer or similar. If any of these pointers no longer \n** point to valid objects, an exception is raised by the memory-checking \n** tool.\n**\n** The point of this is to prevent comparisons of invalid pointer values.\n** Even though this always seems to work, it is undefined according to the\n** C standard. Example of undefined comparison:\n**\n**     sqlite3_free(x);\n**     if( x==y ) ...\n**\n** Technically, as x no longer points into a valid object or to the byte\n** following a valid object, it may not be used in comparison operations.\n*/\nstatic void renameTokenCheckAll(Parse *pParse, void *pPtr){\n  if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){\n    RenameToken *p;\n    u8 i = 0;\n    for(p=pParse->pRename; p; p=p->pNext){\n      if( p->p ){\n        assert( p->p!=pPtr );\n        i += *(u8*)(p->p);\n      }\n    }\n  }\n}\n#else\n# define renameTokenCheckAll(x,y)\n#endif\n\n/*\n** Remember that the parser tree element pPtr was created using\n** the token pToken.\n**\n** In other words, construct a new RenameToken object and add it\n** to the list of RenameToken objects currently being built up\n** in pParse->pRename.\n**\n** The pPtr argument is returned so that this routine can be used\n** with tail recursion in tokenExpr() routine, for a small performance\n** improvement.\n*/\nSQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){\n  RenameToken *pNew;\n  assert( pPtr || pParse->db->mallocFailed );\n  renameTokenCheckAll(pParse, pPtr);\n  if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){\n    pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));\n    if( pNew ){\n      pNew->p = pPtr;\n      pNew->t = *pToken;\n      pNew->pNext = pParse->pRename;\n      pParse->pRename = pNew;\n    }\n  }\n\n  return pPtr;\n}\n\n/*\n** It is assumed that there is already a RenameToken object associated\n** with parse tree element pFrom. This function remaps the associated token\n** to parse tree element pTo.\n*/\nSQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){\n  RenameToken *p;\n  renameTokenCheckAll(pParse, pTo);\n  for(p=pParse->pRename; p; p=p->pNext){\n    if( p->p==pFrom ){\n      p->p = pTo;\n      break;\n    }\n  }\n}\n\n/*\n** Walker callback used by sqlite3RenameExprUnmap().\n*/\nstatic int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){\n  Parse *pParse = pWalker->pParse;\n  sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);\n  return WRC_Continue;\n}\n\n/*\n** Iterate through the Select objects that are part of WITH clauses attached\n** to select statement pSelect.\n*/\nstatic void renameWalkWith(Walker *pWalker, Select *pSelect){\n  With *pWith = pSelect->pWith;\n  if( pWith ){\n    int i;\n    for(i=0; i<pWith->nCte; i++){\n      Select *p = pWith->a[i].pSelect;\n      NameContext sNC;\n      memset(&sNC, 0, sizeof(sNC));\n      sNC.pParse = pWalker->pParse;\n      sqlite3SelectPrep(sNC.pParse, p, &sNC);\n      sqlite3WalkSelect(pWalker, p);\n      sqlite3RenameExprlistUnmap(pWalker->pParse, pWith->a[i].pCols);\n    }\n  }\n}\n\n/*\n** Unmap all tokens in the IdList object passed as the second argument.\n*/\nstatic void unmapColumnIdlistNames(\n  Parse *pParse,\n  IdList *pIdList\n){\n  if( pIdList ){\n    int ii;\n    for(ii=0; ii<pIdList->nId; ii++){\n      sqlite3RenameTokenRemap(pParse, 0, (void*)pIdList->a[ii].zName);\n    }\n  }\n}\n\n/*\n** Walker callback used by sqlite3RenameExprUnmap().\n*/\nstatic int renameUnmapSelectCb(Walker *pWalker, Select *p){\n  Parse *pParse = pWalker->pParse;\n  int i;\n  if( pParse->nErr ) return WRC_Abort;\n  if( NEVER(p->selFlags & SF_View) ) return WRC_Prune;\n  if( ALWAYS(p->pEList) ){\n    ExprList *pList = p->pEList;\n    for(i=0; i<pList->nExpr; i++){\n      if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){\n        sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);\n      }\n    }\n  }\n  if( ALWAYS(p->pSrc) ){  /* Every Select as a SrcList, even if it is empty */\n    SrcList *pSrc = p->pSrc;\n    for(i=0; i<pSrc->nSrc; i++){\n      sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);\n      if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort;\n      unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing);\n    }\n  }\n\n  renameWalkWith(pWalker, p);\n  return WRC_Continue;\n}\n\n/*\n** Remove all nodes that are part of expression pExpr from the rename list.\n*/\nSQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){\n  u8 eMode = pParse->eParseMode;\n  Walker sWalker;\n  memset(&sWalker, 0, sizeof(Walker));\n  sWalker.pParse = pParse;\n  sWalker.xExprCallback = renameUnmapExprCb;\n  sWalker.xSelectCallback = renameUnmapSelectCb;\n  pParse->eParseMode = PARSE_MODE_UNMAP;\n  sqlite3WalkExpr(&sWalker, pExpr);\n  pParse->eParseMode = eMode;\n}\n\n/*\n** Remove all nodes that are part of expression-list pEList from the \n** rename list.\n*/\nSQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){\n  if( pEList ){\n    int i;\n    Walker sWalker;\n    memset(&sWalker, 0, sizeof(Walker));\n    sWalker.pParse = pParse;\n    sWalker.xExprCallback = renameUnmapExprCb;\n    sqlite3WalkExprList(&sWalker, pEList);\n    for(i=0; i<pEList->nExpr; i++){\n      if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){\n        sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);\n      }\n    }\n  }\n}\n\n/*\n** Free the list of RenameToken objects given in the second argument\n*/\nstatic void renameTokenFree(sqlite3 *db, RenameToken *pToken){\n  RenameToken *pNext;\n  RenameToken *p;\n  for(p=pToken; p; p=pNext){\n    pNext = p->pNext;\n    sqlite3DbFree(db, p);\n  }\n}\n\n/*\n** Search the Parse object passed as the first argument for a RenameToken\n** object associated with parse tree element pPtr. If found, remove it\n** from the Parse object and add it to the list maintained by the\n** RenameCtx object passed as the second argument.\n*/\nstatic void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){\n  RenameToken **pp;\n  assert( pPtr!=0 );\n  for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){\n    if( (*pp)->p==pPtr ){\n      RenameToken *pToken = *pp;\n      *pp = pToken->pNext;\n      pToken->pNext = pCtx->pList;\n      pCtx->pList = pToken;\n      pCtx->nList++;\n      break;\n    }\n  }\n}\n\n/*\n** This is a Walker select callback. It does nothing. It is only required\n** because without a dummy callback, sqlite3WalkExpr() and similar do not\n** descend into sub-select statements.\n*/\nstatic int renameColumnSelectCb(Walker *pWalker, Select *p){\n  if( p->selFlags & SF_View ) return WRC_Prune;\n  renameWalkWith(pWalker, p);\n  return WRC_Continue;\n}\n\n/*\n** This is a Walker expression callback.\n**\n** For every TK_COLUMN node in the expression tree, search to see\n** if the column being references is the column being renamed by an\n** ALTER TABLE statement.  If it is, then attach its associated\n** RenameToken object to the list of RenameToken objects being\n** constructed in RenameCtx object at pWalker->u.pRename.\n*/\nstatic int renameColumnExprCb(Walker *pWalker, Expr *pExpr){\n  RenameCtx *p = pWalker->u.pRename;\n  if( pExpr->op==TK_TRIGGER \n   && pExpr->iColumn==p->iCol \n   && pWalker->pParse->pTriggerTab==p->pTab\n  ){\n    renameTokenFind(pWalker->pParse, p, (void*)pExpr);\n  }else if( pExpr->op==TK_COLUMN \n   && pExpr->iColumn==p->iCol \n   && p->pTab==pExpr->y.pTab\n  ){\n    renameTokenFind(pWalker->pParse, p, (void*)pExpr);\n  }\n  return WRC_Continue;\n}\n\n/*\n** The RenameCtx contains a list of tokens that reference a column that\n** is being renamed by an ALTER TABLE statement.  Return the \"last\"\n** RenameToken in the RenameCtx and remove that RenameToken from the\n** RenameContext.  \"Last\" means the last RenameToken encountered when\n** the input SQL is parsed from left to right.  Repeated calls to this routine\n** return all column name tokens in the order that they are encountered\n** in the SQL statement.\n*/\nstatic RenameToken *renameColumnTokenNext(RenameCtx *pCtx){\n  RenameToken *pBest = pCtx->pList;\n  RenameToken *pToken;\n  RenameToken **pp;\n\n  for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){\n    if( pToken->t.z>pBest->t.z ) pBest = pToken;\n  }\n  for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);\n  *pp = pBest->pNext;\n\n  return pBest;\n}\n\n/*\n** An error occured while parsing or otherwise processing a database\n** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an\n** ALTER TABLE RENAME COLUMN program. The error message emitted by the\n** sub-routine is currently stored in pParse->zErrMsg. This function\n** adds context to the error message and then stores it in pCtx.\n*/\nstatic void renameColumnParseError(\n  sqlite3_context *pCtx, \n  int bPost,\n  sqlite3_value *pType,\n  sqlite3_value *pObject,\n  Parse *pParse\n){\n  const char *zT = (const char*)sqlite3_value_text(pType);\n  const char *zN = (const char*)sqlite3_value_text(pObject);\n  char *zErr;\n\n  zErr = sqlite3_mprintf(\"error in %s %s%s: %s\", \n      zT, zN, (bPost ? \" after rename\" : \"\"),\n      pParse->zErrMsg\n  );\n  sqlite3_result_error(pCtx, zErr, -1);\n  sqlite3_free(zErr);\n}\n\n/*\n** For each name in the the expression-list pEList (i.e. each\n** pEList->a[i].zName) that matches the string in zOld, extract the \n** corresponding rename-token from Parse object pParse and add it\n** to the RenameCtx pCtx.\n*/\nstatic void renameColumnElistNames(\n  Parse *pParse, \n  RenameCtx *pCtx, \n  ExprList *pEList, \n  const char *zOld\n){\n  if( pEList ){\n    int i;\n    for(i=0; i<pEList->nExpr; i++){\n      char *zName = pEList->a[i].zEName;\n      if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)\n       && ALWAYS(zName!=0)\n       && 0==sqlite3_stricmp(zName, zOld)\n      ){\n        renameTokenFind(pParse, pCtx, (void*)zName);\n      }\n    }\n  }\n}\n\n/*\n** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName) \n** that matches the string in zOld, extract the corresponding rename-token \n** from Parse object pParse and add it to the RenameCtx pCtx.\n*/\nstatic void renameColumnIdlistNames(\n  Parse *pParse, \n  RenameCtx *pCtx, \n  IdList *pIdList, \n  const char *zOld\n){\n  if( pIdList ){\n    int i;\n    for(i=0; i<pIdList->nId; i++){\n      char *zName = pIdList->a[i].zName;\n      if( 0==sqlite3_stricmp(zName, zOld) ){\n        renameTokenFind(pParse, pCtx, (void*)zName);\n      }\n    }\n  }\n}\n\n\n/*\n** Parse the SQL statement zSql using Parse object (*p). The Parse object\n** is initialized by this function before it is used.\n*/\nstatic int renameParseSql(\n  Parse *p,                       /* Memory to use for Parse object */\n  const char *zDb,                /* Name of schema SQL belongs to */\n  sqlite3 *db,                    /* Database handle */\n  const char *zSql,               /* SQL to parse */\n  int bTemp                       /* True if SQL is from temp schema */\n){\n  int rc;\n  char *zErr = 0;\n\n  db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);\n\n  /* Parse the SQL statement passed as the first argument. If no error\n  ** occurs and the parse does not result in a new table, index or\n  ** trigger object, the database must be corrupt. */\n  memset(p, 0, sizeof(Parse));\n  p->eParseMode = PARSE_MODE_RENAME;\n  p->db = db;\n  p->nQueryLoop = 1;\n  rc = sqlite3RunParser(p, zSql, &zErr);\n  assert( p->zErrMsg==0 );\n  assert( rc!=SQLITE_OK || zErr==0 );\n  p->zErrMsg = zErr;\n  if( db->mallocFailed ) rc = SQLITE_NOMEM;\n  if( rc==SQLITE_OK \n   && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0 \n  ){\n    rc = SQLITE_CORRUPT_BKPT;\n  }\n\n#ifdef SQLITE_DEBUG\n  /* Ensure that all mappings in the Parse.pRename list really do map to\n  ** a part of the input string.  */\n  if( rc==SQLITE_OK ){\n    int nSql = sqlite3Strlen30(zSql);\n    RenameToken *pToken;\n    for(pToken=p->pRename; pToken; pToken=pToken->pNext){\n      assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );\n    }\n  }\n#endif\n\n  db->init.iDb = 0;\n  return rc;\n}\n\n/*\n** This function edits SQL statement zSql, replacing each token identified\n** by the linked list pRename with the text of zNew. If argument bQuote is\n** true, then zNew is always quoted first. If no error occurs, the result\n** is loaded into context object pCtx as the result.\n**\n** Or, if an error occurs (i.e. an OOM condition), an error is left in\n** pCtx and an SQLite error code returned.\n*/\nstatic int renameEditSql(\n  sqlite3_context *pCtx,          /* Return result here */\n  RenameCtx *pRename,             /* Rename context */\n  const char *zSql,               /* SQL statement to edit */\n  const char *zNew,               /* New token text */\n  int bQuote                      /* True to always quote token */\n){\n  int nNew = sqlite3Strlen30(zNew);\n  int nSql = sqlite3Strlen30(zSql);\n  sqlite3 *db = sqlite3_context_db_handle(pCtx);\n  int rc = SQLITE_OK;\n  char *zQuot;\n  char *zOut;\n  int nQuot;\n\n  /* Set zQuot to point to a buffer containing a quoted copy of the \n  ** identifier zNew. If the corresponding identifier in the original \n  ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to\n  ** point to zQuot so that all substitutions are made using the\n  ** quoted version of the new column name.  */\n  zQuot = sqlite3MPrintf(db, \"\\\"%w\\\"\", zNew);\n  if( zQuot==0 ){\n    return SQLITE_NOMEM;\n  }else{\n    nQuot = sqlite3Strlen30(zQuot);\n  }\n  if( bQuote ){\n    zNew = zQuot;\n    nNew = nQuot;\n  }\n\n  /* At this point pRename->pList contains a list of RenameToken objects\n  ** corresponding to all tokens in the input SQL that must be replaced\n  ** with the new column name. All that remains is to construct and\n  ** return the edited SQL string. */\n  assert( nQuot>=nNew );\n  zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);\n  if( zOut ){\n    int nOut = nSql;\n    memcpy(zOut, zSql, nSql);\n    while( pRename->pList ){\n      int iOff;                   /* Offset of token to replace in zOut */\n      RenameToken *pBest = renameColumnTokenNext(pRename);\n\n      u32 nReplace;\n      const char *zReplace;\n      if( sqlite3IsIdChar(*pBest->t.z) ){\n        nReplace = nNew;\n        zReplace = zNew;\n      }else{\n        nReplace = nQuot;\n        zReplace = zQuot;\n      }\n\n      iOff = pBest->t.z - zSql;\n      if( pBest->t.n!=nReplace ){\n        memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n], \n            nOut - (iOff + pBest->t.n)\n        );\n        nOut += nReplace - pBest->t.n;\n        zOut[nOut] = '\\0';\n      }\n      memcpy(&zOut[iOff], zReplace, nReplace);\n      sqlite3DbFree(db, pBest);\n    }\n\n    sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);\n    sqlite3DbFree(db, zOut);\n  }else{\n    rc = SQLITE_NOMEM;\n  }\n\n  sqlite3_free(zQuot);\n  return rc;\n}\n\n/*\n** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming\n** it was read from the schema of database zDb. Return SQLITE_OK if \n** successful. Otherwise, return an SQLite error code and leave an error\n** message in the Parse object.\n*/\nstatic int renameResolveTrigger(Parse *pParse, const char *zDb){\n  sqlite3 *db = pParse->db;\n  Trigger *pNew = pParse->pNewTrigger;\n  TriggerStep *pStep;\n  NameContext sNC;\n  int rc = SQLITE_OK;\n\n  memset(&sNC, 0, sizeof(sNC));\n  sNC.pParse = pParse;\n  assert( pNew->pTabSchema );\n  pParse->pTriggerTab = sqlite3FindTable(db, pNew->table, \n      db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName\n  );\n  pParse->eTriggerOp = pNew->op;\n  /* ALWAYS() because if the table of the trigger does not exist, the\n  ** error would have been hit before this point */\n  if( ALWAYS(pParse->pTriggerTab) ){\n    rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);\n  }\n\n  /* Resolve symbols in WHEN clause */\n  if( rc==SQLITE_OK && pNew->pWhen ){\n    rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);\n  }\n\n  for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){\n    if( pStep->pSelect ){\n      sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);\n      if( pParse->nErr ) rc = pParse->rc;\n    }\n    if( rc==SQLITE_OK && pStep->zTarget ){\n      Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);\n      if( pTarget==0 ){\n        rc = SQLITE_ERROR;\n      }else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){\n        SrcList sSrc;\n        memset(&sSrc, 0, sizeof(sSrc));\n        sSrc.nSrc = 1;\n        sSrc.a[0].zName = pStep->zTarget;\n        sSrc.a[0].pTab = pTarget;\n        sNC.pSrcList = &sSrc;\n        if( pStep->pWhere ){\n          rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);\n        }\n        if( rc==SQLITE_OK ){\n          rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);\n        }\n        assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );\n        if( pStep->pUpsert ){\n          Upsert *pUpsert = pStep->pUpsert;\n          assert( rc==SQLITE_OK );\n          pUpsert->pUpsertSrc = &sSrc;\n          sNC.uNC.pUpsert = pUpsert;\n          sNC.ncFlags = NC_UUpsert;\n          rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);\n          if( rc==SQLITE_OK ){\n            ExprList *pUpsertSet = pUpsert->pUpsertSet;\n            rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);\n          }\n          if( rc==SQLITE_OK ){\n            rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);\n          }\n          if( rc==SQLITE_OK ){\n            rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);\n          }\n          sNC.ncFlags = 0;\n        }\n        sNC.pSrcList = 0;\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr\n** objects that are part of the trigger passed as the second argument.\n*/\nstatic void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){\n  TriggerStep *pStep;\n\n  /* Find tokens to edit in WHEN clause */\n  sqlite3WalkExpr(pWalker, pTrigger->pWhen);\n\n  /* Find tokens to edit in trigger steps */\n  for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){\n    sqlite3WalkSelect(pWalker, pStep->pSelect);\n    sqlite3WalkExpr(pWalker, pStep->pWhere);\n    sqlite3WalkExprList(pWalker, pStep->pExprList);\n    if( pStep->pUpsert ){\n      Upsert *pUpsert = pStep->pUpsert;\n      sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);\n      sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);\n      sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);\n      sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);\n    }\n  }\n}\n\n/*\n** Free the contents of Parse object (*pParse). Do not free the memory\n** occupied by the Parse object itself.\n*/\nstatic void renameParseCleanup(Parse *pParse){\n  sqlite3 *db = pParse->db;\n  Index *pIdx;\n  if( pParse->pVdbe ){\n    sqlite3VdbeFinalize(pParse->pVdbe);\n  }\n  sqlite3DeleteTable(db, pParse->pNewTable);\n  while( (pIdx = pParse->pNewIndex)!=0 ){\n    pParse->pNewIndex = pIdx->pNext;\n    sqlite3FreeIndex(db, pIdx);\n  }\n  sqlite3DeleteTrigger(db, pParse->pNewTrigger);\n  sqlite3DbFree(db, pParse->zErrMsg);\n  renameTokenFree(db, pParse->pRename);\n  sqlite3ParserReset(pParse);\n}\n\n/*\n** SQL function:\n**\n**     sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)\n**\n**   0. zSql:     SQL statement to rewrite\n**   1. type:     Type of object (\"table\", \"view\" etc.)\n**   2. object:   Name of object\n**   3. Database: Database name (e.g. \"main\")\n**   4. Table:    Table name\n**   5. iCol:     Index of column to rename\n**   6. zNew:     New column name\n**   7. bQuote:   Non-zero if the new column name should be quoted.\n**   8. bTemp:    True if zSql comes from temp schema\n**\n** Do a column rename operation on the CREATE statement given in zSql.\n** The iCol-th column (left-most is 0) of table zTable is renamed from zCol\n** into zNew.  The name should be quoted if bQuote is true.\n**\n** This function is used internally by the ALTER TABLE RENAME COLUMN command.\n** It is only accessible to SQL created using sqlite3NestedParse().  It is\n** not reachable from ordinary SQL passed into sqlite3_prepare().\n*/\nstatic void renameColumnFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **argv\n){\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  RenameCtx sCtx;\n  const char *zSql = (const char*)sqlite3_value_text(argv[0]);\n  const char *zDb = (const char*)sqlite3_value_text(argv[3]);\n  const char *zTable = (const char*)sqlite3_value_text(argv[4]);\n  int iCol = sqlite3_value_int(argv[5]);\n  const char *zNew = (const char*)sqlite3_value_text(argv[6]);\n  int bQuote = sqlite3_value_int(argv[7]);\n  int bTemp = sqlite3_value_int(argv[8]);\n  const char *zOld;\n  int rc;\n  Parse sParse;\n  Walker sWalker;\n  Index *pIdx;\n  int i;\n  Table *pTab;\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  sqlite3_xauth xAuth = db->xAuth;\n#endif\n\n  UNUSED_PARAMETER(NotUsed);\n  if( zSql==0 ) return;\n  if( zTable==0 ) return;\n  if( zNew==0 ) return;\n  if( iCol<0 ) return;\n  sqlite3BtreeEnterAll(db);\n  pTab = sqlite3FindTable(db, zTable, zDb);\n  if( pTab==0 || iCol>=pTab->nCol ){\n    sqlite3BtreeLeaveAll(db);\n    return;\n  }\n  zOld = pTab->aCol[iCol].zName;\n  memset(&sCtx, 0, sizeof(sCtx));\n  sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  db->xAuth = 0;\n#endif\n  rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);\n\n  /* Find tokens that need to be replaced. */\n  memset(&sWalker, 0, sizeof(Walker));\n  sWalker.pParse = &sParse;\n  sWalker.xExprCallback = renameColumnExprCb;\n  sWalker.xSelectCallback = renameColumnSelectCb;\n  sWalker.u.pRename = &sCtx;\n\n  sCtx.pTab = pTab;\n  if( rc!=SQLITE_OK ) goto renameColumnFunc_done;\n  if( sParse.pNewTable ){\n    Select *pSelect = sParse.pNewTable->pSelect;\n    if( pSelect ){\n      pSelect->selFlags &= ~SF_View;\n      sParse.rc = SQLITE_OK;\n      sqlite3SelectPrep(&sParse, pSelect, 0);\n      rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);\n      if( rc==SQLITE_OK ){\n        sqlite3WalkSelect(&sWalker, pSelect);\n      }\n      if( rc!=SQLITE_OK ) goto renameColumnFunc_done;\n    }else{\n      /* A regular table */\n      int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);\n      FKey *pFKey;\n      assert( sParse.pNewTable->pSelect==0 );\n      sCtx.pTab = sParse.pNewTable;\n      if( bFKOnly==0 ){\n        renameTokenFind(\n            &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName\n        );\n        if( sCtx.iCol<0 ){\n          renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);\n        }\n        sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);\n        for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){\n          sqlite3WalkExprList(&sWalker, pIdx->aColExpr);\n        }\n        for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){\n          sqlite3WalkExprList(&sWalker, pIdx->aColExpr);\n        }\n      }\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n      for(i=0; i<sParse.pNewTable->nCol; i++){\n        sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);\n      }\n#endif\n\n      for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){\n        for(i=0; i<pFKey->nCol; i++){\n          if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){\n            renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);\n          }\n          if( 0==sqlite3_stricmp(pFKey->zTo, zTable)\n           && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)\n          ){\n            renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);\n          }\n        }\n      }\n    }\n  }else if( sParse.pNewIndex ){\n    sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);\n    sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);\n  }else{\n    /* A trigger */\n    TriggerStep *pStep;\n    rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));\n    if( rc!=SQLITE_OK ) goto renameColumnFunc_done;\n\n    for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){\n      if( pStep->zTarget ){ \n        Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);\n        if( pTarget==pTab ){\n          if( pStep->pUpsert ){\n            ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;\n            renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);\n          }\n          renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);\n          renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);\n        }\n      }\n    }\n\n\n    /* Find tokens to edit in UPDATE OF clause */\n    if( sParse.pTriggerTab==pTab ){\n      renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);\n    }\n\n    /* Find tokens to edit in various expressions and selects */\n    renameWalkTrigger(&sWalker, sParse.pNewTrigger);\n  }\n\n  assert( rc==SQLITE_OK );\n  rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);\n\nrenameColumnFunc_done:\n  if( rc!=SQLITE_OK ){\n    if( sParse.zErrMsg ){\n      renameColumnParseError(context, 0, argv[1], argv[2], &sParse);\n    }else{\n      sqlite3_result_error_code(context, rc);\n    }\n  }\n\n  renameParseCleanup(&sParse);\n  renameTokenFree(db, sCtx.pList);\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  db->xAuth = xAuth;\n#endif\n  sqlite3BtreeLeaveAll(db);\n}\n\n/*\n** Walker expression callback used by \"RENAME TABLE\". \n*/\nstatic int renameTableExprCb(Walker *pWalker, Expr *pExpr){\n  RenameCtx *p = pWalker->u.pRename;\n  if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){\n    renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);\n  }\n  return WRC_Continue;\n}\n\n/*\n** Walker select callback used by \"RENAME TABLE\". \n*/\nstatic int renameTableSelectCb(Walker *pWalker, Select *pSelect){\n  int i;\n  RenameCtx *p = pWalker->u.pRename;\n  SrcList *pSrc = pSelect->pSrc;\n  if( pSelect->selFlags & SF_View ) return WRC_Prune;\n  if( pSrc==0 ){\n    assert( pWalker->pParse->db->mallocFailed );\n    return WRC_Abort;\n  }\n  for(i=0; i<pSrc->nSrc; i++){\n    struct SrcList_item *pItem = &pSrc->a[i];\n    if( pItem->pTab==p->pTab ){\n      renameTokenFind(pWalker->pParse, p, pItem->zName);\n    }\n  }\n  renameWalkWith(pWalker, pSelect);\n\n  return WRC_Continue;\n}\n\n\n/*\n** This C function implements an SQL user function that is used by SQL code\n** generated by the ALTER TABLE ... RENAME command to modify the definition\n** of any foreign key constraints that use the table being renamed as the \n** parent table. It is passed three arguments:\n**\n**   0: The database containing the table being renamed.\n**   1. type:     Type of object (\"table\", \"view\" etc.)\n**   2. object:   Name of object\n**   3: The complete text of the schema statement being modified,\n**   4: The old name of the table being renamed, and\n**   5: The new name of the table being renamed.\n**   6: True if the schema statement comes from the temp db.\n**\n** It returns the new schema statement. For example:\n**\n** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)\n**       -> 'CREATE TABLE t1(a REFERENCES t3)'\n*/\nstatic void renameTableFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **argv\n){\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  const char *zDb = (const char*)sqlite3_value_text(argv[0]);\n  const char *zInput = (const char*)sqlite3_value_text(argv[3]);\n  const char *zOld = (const char*)sqlite3_value_text(argv[4]);\n  const char *zNew = (const char*)sqlite3_value_text(argv[5]);\n  int bTemp = sqlite3_value_int(argv[6]);\n  UNUSED_PARAMETER(NotUsed);\n\n  if( zInput && zOld && zNew ){\n    Parse sParse;\n    int rc;\n    int bQuote = 1;\n    RenameCtx sCtx;\n    Walker sWalker;\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n    sqlite3_xauth xAuth = db->xAuth;\n    db->xAuth = 0;\n#endif\n\n    sqlite3BtreeEnterAll(db);\n\n    memset(&sCtx, 0, sizeof(RenameCtx));\n    sCtx.pTab = sqlite3FindTable(db, zOld, zDb);\n    memset(&sWalker, 0, sizeof(Walker));\n    sWalker.pParse = &sParse;\n    sWalker.xExprCallback = renameTableExprCb;\n    sWalker.xSelectCallback = renameTableSelectCb;\n    sWalker.u.pRename = &sCtx;\n\n    rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);\n\n    if( rc==SQLITE_OK ){\n      int isLegacy = (db->flags & SQLITE_LegacyAlter);\n      if( sParse.pNewTable ){\n        Table *pTab = sParse.pNewTable;\n\n        if( pTab->pSelect ){\n          if( isLegacy==0 ){\n            Select *pSelect = pTab->pSelect;\n            NameContext sNC;\n            memset(&sNC, 0, sizeof(sNC));\n            sNC.pParse = &sParse;\n\n            assert( pSelect->selFlags & SF_View );\n            pSelect->selFlags &= ~SF_View;\n            sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);\n            if( sParse.nErr ){\n              rc = sParse.rc;\n            }else{\n              sqlite3WalkSelect(&sWalker, pTab->pSelect);\n            }\n          }\n        }else{\n          /* Modify any FK definitions to point to the new table. */\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n          if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){\n            FKey *pFKey;\n            for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){\n              if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){\n                renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);\n              }\n            }\n          }\n#endif\n\n          /* If this is the table being altered, fix any table refs in CHECK\n          ** expressions. Also update the name that appears right after the\n          ** \"CREATE [VIRTUAL] TABLE\" bit. */\n          if( sqlite3_stricmp(zOld, pTab->zName)==0 ){\n            sCtx.pTab = pTab;\n            if( isLegacy==0 ){\n              sqlite3WalkExprList(&sWalker, pTab->pCheck);\n            }\n            renameTokenFind(&sParse, &sCtx, pTab->zName);\n          }\n        }\n      }\n\n      else if( sParse.pNewIndex ){\n        renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);\n        if( isLegacy==0 ){\n          sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);\n        }\n      }\n\n#ifndef SQLITE_OMIT_TRIGGER\n      else{\n        Trigger *pTrigger = sParse.pNewTrigger;\n        TriggerStep *pStep;\n        if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld) \n            && sCtx.pTab->pSchema==pTrigger->pTabSchema\n          ){\n          renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);\n        }\n\n        if( isLegacy==0 ){\n          rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);\n          if( rc==SQLITE_OK ){\n            renameWalkTrigger(&sWalker, pTrigger);\n            for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){\n              if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){\n                renameTokenFind(&sParse, &sCtx, pStep->zTarget);\n              }\n            }\n          }\n        }\n      }\n#endif\n    }\n\n    if( rc==SQLITE_OK ){\n      rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);\n    }\n    if( rc!=SQLITE_OK ){\n      if( sParse.zErrMsg ){\n        renameColumnParseError(context, 0, argv[1], argv[2], &sParse);\n      }else{\n        sqlite3_result_error_code(context, rc);\n      }\n    }\n\n    renameParseCleanup(&sParse);\n    renameTokenFree(db, sCtx.pList);\n    sqlite3BtreeLeaveAll(db);\n#ifndef SQLITE_OMIT_AUTHORIZATION\n    db->xAuth = xAuth;\n#endif\n  }\n\n  return;\n}\n\n/*\n** An SQL user function that checks that there are no parse or symbol\n** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.\n** After an ALTER TABLE .. RENAME operation is performed and the schema\n** reloaded, this function is called on each SQL statement in the schema\n** to ensure that it is still usable.\n**\n**   0: Database name (\"main\", \"temp\" etc.).\n**   1: SQL statement.\n**   2: Object type (\"view\", \"table\", \"trigger\" or \"index\").\n**   3: Object name.\n**   4: True if object is from temp schema.\n**\n** Unless it finds an error, this function normally returns NULL. However, it\n** returns integer value 1 if:\n**\n**   * the SQL argument creates a trigger, and\n**   * the table that the trigger is attached to is in database zDb.\n*/\nstatic void renameTableTest(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **argv\n){\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  char const *zDb = (const char*)sqlite3_value_text(argv[0]);\n  char const *zInput = (const char*)sqlite3_value_text(argv[1]);\n  int bTemp = sqlite3_value_int(argv[4]);\n  int isLegacy = (db->flags & SQLITE_LegacyAlter);\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  sqlite3_xauth xAuth = db->xAuth;\n  db->xAuth = 0;\n#endif\n\n  UNUSED_PARAMETER(NotUsed);\n  if( zDb && zInput ){\n    int rc;\n    Parse sParse;\n    rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);\n    if( rc==SQLITE_OK ){\n      if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){\n        NameContext sNC;\n        memset(&sNC, 0, sizeof(sNC));\n        sNC.pParse = &sParse;\n        sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);\n        if( sParse.nErr ) rc = sParse.rc;\n      }\n\n      else if( sParse.pNewTrigger ){\n        if( isLegacy==0 ){\n          rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);\n        }\n        if( rc==SQLITE_OK ){\n          int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);\n          int i2 = sqlite3FindDbName(db, zDb);\n          if( i1==i2 ) sqlite3_result_int(context, 1);\n        }\n      }\n    }\n\n    if( rc!=SQLITE_OK ){\n      renameColumnParseError(context, 1, argv[2], argv[3], &sParse);\n    }\n    renameParseCleanup(&sParse);\n  }\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  db->xAuth = xAuth;\n#endif\n}\n\n/*\n** Register built-in functions used to help implement ALTER TABLE\n*/\nSQLITE_PRIVATE void sqlite3AlterFunctions(void){\n  static FuncDef aAlterTableFuncs[] = {\n    INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),\n    INTERNAL_FUNCTION(sqlite_rename_table,  7, renameTableFunc),\n    INTERNAL_FUNCTION(sqlite_rename_test,   5, renameTableTest),\n  };\n  sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));\n}\n#endif  /* SQLITE_ALTER_TABLE */\n\n/************** End of alter.c ***********************************************/\n/************** Begin file analyze.c *****************************************/\n/*\n** 2005-07-08\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code associated with the ANALYZE command.\n**\n** The ANALYZE command gather statistics about the content of tables\n** and indices.  These statistics are made available to the query planner\n** to help it make better decisions about how to perform queries.\n**\n** The following system tables are or have been supported:\n**\n**    CREATE TABLE sqlite_stat1(tbl, idx, stat);\n**    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);\n**    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);\n**    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);\n**\n** Additional tables might be added in future releases of SQLite.\n** The sqlite_stat2 table is not created or used unless the SQLite version\n** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled\n** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.\n** The sqlite_stat2 table is superseded by sqlite_stat3, which is only\n** created and used by SQLite versions 3.7.9 through 3.29.0 when\n** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3\n** is a superset of sqlite_stat2 and is also now deprecated.  The\n** sqlite_stat4 is an enhanced version of sqlite_stat3 and is only \n** available when compiled with SQLITE_ENABLE_STAT4 and in SQLite\n** versions 3.8.1 and later.  STAT4 is the only variant that is still\n** supported.\n**\n** For most applications, sqlite_stat1 provides all the statistics required\n** for the query planner to make good choices.\n**\n** Format of sqlite_stat1:\n**\n** There is normally one row per index, with the index identified by the\n** name in the idx column.  The tbl column is the name of the table to\n** which the index belongs.  In each such row, the stat column will be\n** a string consisting of a list of integers.  The first integer in this\n** list is the number of rows in the index.  (This is the same as the\n** number of rows in the table, except for partial indices.)  The second\n** integer is the average number of rows in the index that have the same\n** value in the first column of the index.  The third integer is the average\n** number of rows in the index that have the same value for the first two\n** columns.  The N-th integer (for N>1) is the average number of rows in \n** the index which have the same value for the first N-1 columns.  For\n** a K-column index, there will be K+1 integers in the stat column.  If\n** the index is unique, then the last integer will be 1.\n**\n** The list of integers in the stat column can optionally be followed\n** by the keyword \"unordered\".  The \"unordered\" keyword, if it is present,\n** must be separated from the last integer by a single space.  If the\n** \"unordered\" keyword is present, then the query planner assumes that\n** the index is unordered and will not use the index for a range query.\n** \n** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat\n** column contains a single integer which is the (estimated) number of\n** rows in the table identified by sqlite_stat1.tbl.\n**\n** Format of sqlite_stat2:\n**\n** The sqlite_stat2 is only created and is only used if SQLite is compiled\n** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between\n** 3.6.18 and 3.7.8.  The \"stat2\" table contains additional information\n** about the distribution of keys within an index.  The index is identified by\n** the \"idx\" column and the \"tbl\" column is the name of the table to which\n** the index belongs.  There are usually 10 rows in the sqlite_stat2\n** table for each index.\n**\n** The sqlite_stat2 entries for an index that have sampleno between 0 and 9\n** inclusive are samples of the left-most key value in the index taken at\n** evenly spaced points along the index.  Let the number of samples be S\n** (10 in the standard build) and let C be the number of rows in the index.\n** Then the sampled rows are given by:\n**\n**     rownumber = (i*C*2 + C)/(S*2)\n**\n** For i between 0 and S-1.  Conceptually, the index space is divided into\n** S uniform buckets and the samples are the middle row from each bucket.\n**\n** The format for sqlite_stat2 is recorded here for legacy reference.  This\n** version of SQLite does not support sqlite_stat2.  It neither reads nor\n** writes the sqlite_stat2 table.  This version of SQLite only supports\n** sqlite_stat3.\n**\n** Format for sqlite_stat3:\n**\n** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the\n** sqlite_stat4 format will be described first.  Further information\n** about sqlite_stat3 follows the sqlite_stat4 description.\n**\n** Format for sqlite_stat4:\n**\n** As with sqlite_stat2, the sqlite_stat4 table contains histogram data\n** to aid the query planner in choosing good indices based on the values\n** that indexed columns are compared against in the WHERE clauses of\n** queries.\n**\n** The sqlite_stat4 table contains multiple entries for each index.\n** The idx column names the index and the tbl column is the table of the\n** index.  If the idx and tbl columns are the same, then the sample is\n** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the\n** binary encoding of a key from the index.  The nEq column is a\n** list of integers.  The first integer is the approximate number\n** of entries in the index whose left-most column exactly matches\n** the left-most column of the sample.  The second integer in nEq\n** is the approximate number of entries in the index where the\n** first two columns match the first two columns of the sample.\n** And so forth.  nLt is another list of integers that show the approximate\n** number of entries that are strictly less than the sample.  The first\n** integer in nLt contains the number of entries in the index where the\n** left-most column is less than the left-most column of the sample.\n** The K-th integer in the nLt entry is the number of index entries \n** where the first K columns are less than the first K columns of the\n** sample.  The nDLt column is like nLt except that it contains the \n** number of distinct entries in the index that are less than the\n** sample.\n**\n** There can be an arbitrary number of sqlite_stat4 entries per index.\n** The ANALYZE command will typically generate sqlite_stat4 tables\n** that contain between 10 and 40 samples which are distributed across\n** the key space, though not uniformly, and which include samples with\n** large nEq values.\n**\n** Format for sqlite_stat3 redux:\n**\n** The sqlite_stat3 table is like sqlite_stat4 except that it only\n** looks at the left-most column of the index.  The sqlite_stat3.sample\n** column contains the actual value of the left-most column instead\n** of a blob encoding of the complete index key as is found in\n** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3\n** all contain just a single integer which is the same as the first\n** integer in the equivalent columns in sqlite_stat4.\n*/\n#ifndef SQLITE_OMIT_ANALYZE\n/* #include \"sqliteInt.h\" */\n\n#if defined(SQLITE_ENABLE_STAT4)\n# define IsStat4     1\n#else\n# define IsStat4     0\n# undef SQLITE_STAT4_SAMPLES\n# define SQLITE_STAT4_SAMPLES 1\n#endif\n\n/*\n** This routine generates code that opens the sqlite_statN tables.\n** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now\n** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when\n** appropriate compile-time options are provided.\n**\n** If the sqlite_statN tables do not previously exist, it is created.\n**\n** Argument zWhere may be a pointer to a buffer containing a table name,\n** or it may be a NULL pointer. If it is not NULL, then all entries in\n** the sqlite_statN tables associated with the named table are deleted.\n** If zWhere==0, then code is generated to delete all stat table entries.\n*/\nstatic void openStatTable(\n  Parse *pParse,          /* Parsing context */\n  int iDb,                /* The database we are looking in */\n  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */\n  const char *zWhere,     /* Delete entries for this table or index */\n  const char *zWhereType  /* Either \"tbl\" or \"idx\" */\n){\n  static const struct {\n    const char *zName;\n    const char *zCols;\n  } aTable[] = {\n    { \"sqlite_stat1\", \"tbl,idx,stat\" },\n#if defined(SQLITE_ENABLE_STAT4)\n    { \"sqlite_stat4\", \"tbl,idx,neq,nlt,ndlt,sample\" },\n#else\n    { \"sqlite_stat4\", 0 },\n#endif\n    { \"sqlite_stat3\", 0 },\n  };\n  int i;\n  sqlite3 *db = pParse->db;\n  Db *pDb;\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  int aRoot[ArraySize(aTable)];\n  u8 aCreateTbl[ArraySize(aTable)];\n#ifdef SQLITE_ENABLE_STAT4\n  const int nToOpen = OptimizationEnabled(db,SQLITE_Stat4) ? 2 : 1;\n#else\n  const int nToOpen = 1;\n#endif\n\n  if( v==0 ) return;\n  assert( sqlite3BtreeHoldsAllMutexes(db) );\n  assert( sqlite3VdbeDb(v)==db );\n  pDb = &db->aDb[iDb];\n\n  /* Create new statistic tables if they do not exist, or clear them\n  ** if they do already exist.\n  */\n  for(i=0; i<ArraySize(aTable); i++){\n    const char *zTab = aTable[i].zName;\n    Table *pStat;\n    aCreateTbl[i] = 0;\n    if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){\n      if( i<nToOpen ){\n        /* The sqlite_statN table does not exist. Create it. Note that a \n        ** side-effect of the CREATE TABLE statement is to leave the rootpage \n        ** of the new table in register pParse->regRoot. This is important \n        ** because the OpenWrite opcode below will be needing it. */\n        sqlite3NestedParse(pParse,\n            \"CREATE TABLE %Q.%s(%s)\", pDb->zDbSName, zTab, aTable[i].zCols\n        );\n        aRoot[i] = pParse->regRoot;\n        aCreateTbl[i] = OPFLAG_P2ISREG;\n      }\n    }else{\n      /* The table already exists. If zWhere is not NULL, delete all entries \n      ** associated with the table zWhere. If zWhere is NULL, delete the\n      ** entire contents of the table. */\n      aRoot[i] = pStat->tnum;\n      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);\n      if( zWhere ){\n        sqlite3NestedParse(pParse,\n           \"DELETE FROM %Q.%s WHERE %s=%Q\",\n           pDb->zDbSName, zTab, zWhereType, zWhere\n        );\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n      }else if( db->xPreUpdateCallback ){\n        sqlite3NestedParse(pParse, \"DELETE FROM %Q.%s\", pDb->zDbSName, zTab);\n#endif\n      }else{\n        /* The sqlite_stat[134] table already exists.  Delete all rows. */\n        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);\n      }\n    }\n  }\n\n  /* Open the sqlite_stat[134] tables for writing. */\n  for(i=0; i<nToOpen; i++){\n    assert( i<ArraySize(aTable) );\n    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);\n    sqlite3VdbeChangeP5(v, aCreateTbl[i]);\n    VdbeComment((v, aTable[i].zName));\n  }\n}\n\n/*\n** Recommended number of samples for sqlite_stat4\n*/\n#ifndef SQLITE_STAT4_SAMPLES\n# define SQLITE_STAT4_SAMPLES 24\n#endif\n\n/*\n** Three SQL functions - stat_init(), stat_push(), and stat_get() -\n** share an instance of the following structure to hold their state\n** information.\n*/\ntypedef struct StatAccum StatAccum;\ntypedef struct StatSample StatSample;\nstruct StatSample {\n  tRowcnt *anEq;                  /* sqlite_stat4.nEq */\n  tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */\n#ifdef SQLITE_ENABLE_STAT4\n  tRowcnt *anLt;                  /* sqlite_stat4.nLt */\n  union {\n    i64 iRowid;                     /* Rowid in main table of the key */\n    u8 *aRowid;                     /* Key for WITHOUT ROWID tables */\n  } u;\n  u32 nRowid;                     /* Sizeof aRowid[] */\n  u8 isPSample;                   /* True if a periodic sample */\n  int iCol;                       /* If !isPSample, the reason for inclusion */\n  u32 iHash;                      /* Tiebreaker hash */\n#endif\n};                                                    \nstruct StatAccum {\n  sqlite3 *db;              /* Database connection, for malloc() */\n  tRowcnt nEst;             /* Estimated number of rows */\n  tRowcnt nRow;             /* Number of rows visited so far */\n  int nLimit;               /* Analysis row-scan limit */\n  int nCol;                 /* Number of columns in index + pk/rowid */\n  int nKeyCol;              /* Number of index columns w/o the pk/rowid */\n  u8 nSkipAhead;            /* Number of times of skip-ahead */\n  StatSample current;       /* Current row as a StatSample */\n#ifdef SQLITE_ENABLE_STAT4\n  tRowcnt nPSample;         /* How often to do a periodic sample */\n  int mxSample;             /* Maximum number of samples to accumulate */\n  u32 iPrn;                 /* Pseudo-random number used for sampling */\n  StatSample *aBest;        /* Array of nCol best samples */\n  int iMin;                 /* Index in a[] of entry with minimum score */\n  int nSample;              /* Current number of samples */\n  int nMaxEqZero;           /* Max leading 0 in anEq[] for any a[] entry */\n  int iGet;                 /* Index of current sample accessed by stat_get() */\n  StatSample *a;            /* Array of mxSample StatSample objects */\n#endif\n};\n\n/* Reclaim memory used by a StatSample\n*/\n#ifdef SQLITE_ENABLE_STAT4\nstatic void sampleClear(sqlite3 *db, StatSample *p){\n  assert( db!=0 );\n  if( p->nRowid ){\n    sqlite3DbFree(db, p->u.aRowid);\n    p->nRowid = 0;\n  }\n}\n#endif\n\n/* Initialize the BLOB value of a ROWID\n*/\n#ifdef SQLITE_ENABLE_STAT4\nstatic void sampleSetRowid(sqlite3 *db, StatSample *p, int n, const u8 *pData){\n  assert( db!=0 );\n  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);\n  p->u.aRowid = sqlite3DbMallocRawNN(db, n);\n  if( p->u.aRowid ){\n    p->nRowid = n;\n    memcpy(p->u.aRowid, pData, n);\n  }else{\n    p->nRowid = 0;\n  }\n}\n#endif\n\n/* Initialize the INTEGER value of a ROWID.\n*/\n#ifdef SQLITE_ENABLE_STAT4\nstatic void sampleSetRowidInt64(sqlite3 *db, StatSample *p, i64 iRowid){\n  assert( db!=0 );\n  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);\n  p->nRowid = 0;\n  p->u.iRowid = iRowid;\n}\n#endif\n\n\n/*\n** Copy the contents of object (*pFrom) into (*pTo).\n*/\n#ifdef SQLITE_ENABLE_STAT4\nstatic void sampleCopy(StatAccum *p, StatSample *pTo, StatSample *pFrom){\n  pTo->isPSample = pFrom->isPSample;\n  pTo->iCol = pFrom->iCol;\n  pTo->iHash = pFrom->iHash;\n  memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);\n  memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);\n  memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);\n  if( pFrom->nRowid ){\n    sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);\n  }else{\n    sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);\n  }\n}\n#endif\n\n/*\n** Reclaim all memory of a StatAccum structure.\n*/\nstatic void statAccumDestructor(void *pOld){\n  StatAccum *p = (StatAccum*)pOld;\n#ifdef SQLITE_ENABLE_STAT4\n  if( p->mxSample ){\n    int i;\n    for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);\n    for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);\n    sampleClear(p->db, &p->current);\n  }\n#endif\n  sqlite3DbFree(p->db, p);\n}\n\n/*\n** Implementation of the stat_init(N,K,C,L) SQL function. The four parameters\n** are:\n**     N:    The number of columns in the index including the rowid/pk (note 1)\n**     K:    The number of columns in the index excluding the rowid/pk.\n**     C:    Estimated number of rows in the index\n**     L:    A limit on the number of rows to scan, or 0 for no-limit \n**\n** Note 1:  In the special case of the covering index that implements a\n** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the\n** total number of columns in the table.\n**\n** For indexes on ordinary rowid tables, N==K+1.  But for indexes on\n** WITHOUT ROWID tables, N=K+P where P is the number of columns in the\n** PRIMARY KEY of the table.  The covering index that implements the\n** original WITHOUT ROWID table as N==K as a special case.\n**\n** This routine allocates the StatAccum object in heap memory. The return \n** value is a pointer to the StatAccum object.  The datatype of the\n** return value is BLOB, but it is really just a pointer to the StatAccum\n** object.\n*/\nstatic void statInit(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  StatAccum *p;\n  int nCol;                       /* Number of columns in index being sampled */\n  int nKeyCol;                    /* Number of key columns */\n  int nColUp;                     /* nCol rounded up for alignment */\n  int n;                          /* Bytes of space to allocate */\n  sqlite3 *db = sqlite3_context_db_handle(context);   /* Database connection */\n#ifdef SQLITE_ENABLE_STAT4\n  /* Maximum number of samples.  0 if STAT4 data is not collected */\n  int mxSample = OptimizationEnabled(db,SQLITE_Stat4) ?SQLITE_STAT4_SAMPLES :0;\n#endif\n\n  /* Decode the three function arguments */\n  UNUSED_PARAMETER(argc);\n  nCol = sqlite3_value_int(argv[0]);\n  assert( nCol>0 );\n  nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;\n  nKeyCol = sqlite3_value_int(argv[1]);\n  assert( nKeyCol<=nCol );\n  assert( nKeyCol>0 );\n\n  /* Allocate the space required for the StatAccum object */\n  n = sizeof(*p) \n    + sizeof(tRowcnt)*nColUp                  /* StatAccum.anEq */\n    + sizeof(tRowcnt)*nColUp;                 /* StatAccum.anDLt */\n#ifdef SQLITE_ENABLE_STAT4\n  if( mxSample ){\n    n += sizeof(tRowcnt)*nColUp                  /* StatAccum.anLt */\n      + sizeof(StatSample)*(nCol+mxSample)       /* StatAccum.aBest[], a[] */\n      + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample);\n  }\n#endif\n  db = sqlite3_context_db_handle(context);\n  p = sqlite3DbMallocZero(db, n);\n  if( p==0 ){\n    sqlite3_result_error_nomem(context);\n    return;\n  }\n\n  p->db = db;\n  p->nEst = sqlite3_value_int64(argv[2]);\n  p->nRow = 0;\n  p->nLimit = sqlite3_value_int64(argv[3]);\n  p->nCol = nCol;\n  p->nKeyCol = nKeyCol;\n  p->nSkipAhead = 0;\n  p->current.anDLt = (tRowcnt*)&p[1];\n  p->current.anEq = &p->current.anDLt[nColUp];\n\n#ifdef SQLITE_ENABLE_STAT4\n  p->mxSample = p->nLimit==0 ? mxSample : 0;\n  if( mxSample ){\n    u8 *pSpace;                     /* Allocated space not yet assigned */\n    int i;                          /* Used to iterate through p->aSample[] */\n\n    p->iGet = -1;\n    p->nPSample = (tRowcnt)(p->nEst/(mxSample/3+1) + 1);\n    p->current.anLt = &p->current.anEq[nColUp];\n    p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);\n  \n    /* Set up the StatAccum.a[] and aBest[] arrays */\n    p->a = (struct StatSample*)&p->current.anLt[nColUp];\n    p->aBest = &p->a[mxSample];\n    pSpace = (u8*)(&p->a[mxSample+nCol]);\n    for(i=0; i<(mxSample+nCol); i++){\n      p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);\n      p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);\n      p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);\n    }\n    assert( (pSpace - (u8*)p)==n );\n  \n    for(i=0; i<nCol; i++){\n      p->aBest[i].iCol = i;\n    }\n  }\n#endif\n\n  /* Return a pointer to the allocated object to the caller.  Note that\n  ** only the pointer (the 2nd parameter) matters.  The size of the object\n  ** (given by the 3rd parameter) is never used and can be any positive\n  ** value. */\n  sqlite3_result_blob(context, p, sizeof(*p), statAccumDestructor);\n}\nstatic const FuncDef statInitFuncdef = {\n  4,               /* nArg */\n  SQLITE_UTF8,     /* funcFlags */\n  0,               /* pUserData */\n  0,               /* pNext */\n  statInit,        /* xSFunc */\n  0,               /* xFinalize */\n  0, 0,            /* xValue, xInverse */\n  \"stat_init\",     /* zName */\n  {0}\n};\n\n#ifdef SQLITE_ENABLE_STAT4\n/*\n** pNew and pOld are both candidate non-periodic samples selected for \n** the same column (pNew->iCol==pOld->iCol). Ignoring this column and \n** considering only any trailing columns and the sample hash value, this\n** function returns true if sample pNew is to be preferred over pOld.\n** In other words, if we assume that the cardinalities of the selected\n** column for pNew and pOld are equal, is pNew to be preferred over pOld.\n**\n** This function assumes that for each argument sample, the contents of\n** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid. \n*/\nstatic int sampleIsBetterPost(\n  StatAccum *pAccum, \n  StatSample *pNew, \n  StatSample *pOld\n){\n  int nCol = pAccum->nCol;\n  int i;\n  assert( pNew->iCol==pOld->iCol );\n  for(i=pNew->iCol+1; i<nCol; i++){\n    if( pNew->anEq[i]>pOld->anEq[i] ) return 1;\n    if( pNew->anEq[i]<pOld->anEq[i] ) return 0;\n  }\n  if( pNew->iHash>pOld->iHash ) return 1;\n  return 0;\n}\n#endif\n\n#ifdef SQLITE_ENABLE_STAT4\n/*\n** Return true if pNew is to be preferred over pOld.\n**\n** This function assumes that for each argument sample, the contents of\n** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid. \n*/\nstatic int sampleIsBetter(\n  StatAccum *pAccum, \n  StatSample *pNew, \n  StatSample *pOld\n){\n  tRowcnt nEqNew = pNew->anEq[pNew->iCol];\n  tRowcnt nEqOld = pOld->anEq[pOld->iCol];\n\n  assert( pOld->isPSample==0 && pNew->isPSample==0 );\n  assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );\n\n  if( (nEqNew>nEqOld) ) return 1;\n  if( nEqNew==nEqOld ){\n    if( pNew->iCol<pOld->iCol ) return 1;\n    return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));\n  }\n  return 0;\n}\n\n/*\n** Copy the contents of sample *pNew into the p->a[] array. If necessary,\n** remove the least desirable sample from p->a[] to make room.\n*/\nstatic void sampleInsert(StatAccum *p, StatSample *pNew, int nEqZero){\n  StatSample *pSample = 0;\n  int i;\n\n  assert( IsStat4 || nEqZero==0 );\n\n  /* StatAccum.nMaxEqZero is set to the maximum number of leading 0\n  ** values in the anEq[] array of any sample in StatAccum.a[]. In\n  ** other words, if nMaxEqZero is n, then it is guaranteed that there\n  ** are no samples with StatSample.anEq[m]==0 for (m>=n). */\n  if( nEqZero>p->nMaxEqZero ){\n    p->nMaxEqZero = nEqZero;\n  }\n  if( pNew->isPSample==0 ){\n    StatSample *pUpgrade = 0;\n    assert( pNew->anEq[pNew->iCol]>0 );\n\n    /* This sample is being added because the prefix that ends in column \n    ** iCol occurs many times in the table. However, if we have already\n    ** added a sample that shares this prefix, there is no need to add\n    ** this one. Instead, upgrade the priority of the highest priority\n    ** existing sample that shares this prefix.  */\n    for(i=p->nSample-1; i>=0; i--){\n      StatSample *pOld = &p->a[i];\n      if( pOld->anEq[pNew->iCol]==0 ){\n        if( pOld->isPSample ) return;\n        assert( pOld->iCol>pNew->iCol );\n        assert( sampleIsBetter(p, pNew, pOld) );\n        if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){\n          pUpgrade = pOld;\n        }\n      }\n    }\n    if( pUpgrade ){\n      pUpgrade->iCol = pNew->iCol;\n      pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];\n      goto find_new_min;\n    }\n  }\n\n  /* If necessary, remove sample iMin to make room for the new sample. */\n  if( p->nSample>=p->mxSample ){\n    StatSample *pMin = &p->a[p->iMin];\n    tRowcnt *anEq = pMin->anEq;\n    tRowcnt *anLt = pMin->anLt;\n    tRowcnt *anDLt = pMin->anDLt;\n    sampleClear(p->db, pMin);\n    memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));\n    pSample = &p->a[p->nSample-1];\n    pSample->nRowid = 0;\n    pSample->anEq = anEq;\n    pSample->anDLt = anDLt;\n    pSample->anLt = anLt;\n    p->nSample = p->mxSample-1;\n  }\n\n  /* The \"rows less-than\" for the rowid column must be greater than that\n  ** for the last sample in the p->a[] array. Otherwise, the samples would\n  ** be out of order. */\n  assert( p->nSample==0 \n       || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );\n\n  /* Insert the new sample */\n  pSample = &p->a[p->nSample];\n  sampleCopy(p, pSample, pNew);\n  p->nSample++;\n\n  /* Zero the first nEqZero entries in the anEq[] array. */\n  memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);\n\nfind_new_min:\n  if( p->nSample>=p->mxSample ){\n    int iMin = -1;\n    for(i=0; i<p->mxSample; i++){\n      if( p->a[i].isPSample ) continue;\n      if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){\n        iMin = i;\n      }\n    }\n    assert( iMin>=0 );\n    p->iMin = iMin;\n  }\n}\n#endif /* SQLITE_ENABLE_STAT4 */\n\n#ifdef SQLITE_ENABLE_STAT4\n/*\n** Field iChng of the index being scanned has changed. So at this point\n** p->current contains a sample that reflects the previous row of the\n** index. The value of anEq[iChng] and subsequent anEq[] elements are\n** correct at this point.\n*/\nstatic void samplePushPrevious(StatAccum *p, int iChng){\n  int i;\n\n  /* Check if any samples from the aBest[] array should be pushed\n  ** into IndexSample.a[] at this point.  */\n  for(i=(p->nCol-2); i>=iChng; i--){\n    StatSample *pBest = &p->aBest[i];\n    pBest->anEq[i] = p->current.anEq[i];\n    if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){\n      sampleInsert(p, pBest, i);\n    }\n  }\n\n  /* Check that no sample contains an anEq[] entry with an index of\n  ** p->nMaxEqZero or greater set to zero. */\n  for(i=p->nSample-1; i>=0; i--){\n    int j;\n    for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );\n  }\n\n  /* Update the anEq[] fields of any samples already collected. */\n  if( iChng<p->nMaxEqZero ){\n    for(i=p->nSample-1; i>=0; i--){\n      int j;\n      for(j=iChng; j<p->nCol; j++){\n        if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];\n      }\n    }\n    p->nMaxEqZero = iChng;\n  }\n}\n#endif /* SQLITE_ENABLE_STAT4 */\n\n/*\n** Implementation of the stat_push SQL function:  stat_push(P,C,R)\n** Arguments:\n**\n**    P     Pointer to the StatAccum object created by stat_init()\n**    C     Index of left-most column to differ from previous row\n**    R     Rowid for the current row.  Might be a key record for\n**          WITHOUT ROWID tables.\n**\n** The purpose of this routine is to collect statistical data and/or\n** samples from the index being analyzed into the StatAccum object.\n** The stat_get() SQL function will be used afterwards to\n** retrieve the information gathered.\n**\n** This SQL function usually returns NULL, but might return an integer\n** if it wants the byte-code to do special processing.\n**\n** The R parameter is only used for STAT4\n*/\nstatic void statPush(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  int i;\n\n  /* The three function arguments */\n  StatAccum *p = (StatAccum*)sqlite3_value_blob(argv[0]);\n  int iChng = sqlite3_value_int(argv[1]);\n\n  UNUSED_PARAMETER( argc );\n  UNUSED_PARAMETER( context );\n  assert( p->nCol>0 );\n  assert( iChng<p->nCol );\n\n  if( p->nRow==0 ){\n    /* This is the first call to this function. Do initialization. */\n    for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;\n  }else{\n    /* Second and subsequent calls get processed here */\n#ifdef SQLITE_ENABLE_STAT4\n    if( p->mxSample ) samplePushPrevious(p, iChng);\n#endif\n\n    /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply\n    ** to the current row of the index. */\n    for(i=0; i<iChng; i++){\n      p->current.anEq[i]++;\n    }\n    for(i=iChng; i<p->nCol; i++){\n      p->current.anDLt[i]++;\n#ifdef SQLITE_ENABLE_STAT4\n      if( p->mxSample ) p->current.anLt[i] += p->current.anEq[i];\n#endif\n      p->current.anEq[i] = 1;\n    }\n  }\n\n  p->nRow++;\n#ifdef SQLITE_ENABLE_STAT4\n  if( p->mxSample ){\n    tRowcnt nLt;\n    if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){\n      sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));\n    }else{\n      sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),\n                                         sqlite3_value_blob(argv[2]));\n    }\n    p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;\n\n    nLt = p->current.anLt[p->nCol-1];\n    /* Check if this is to be a periodic sample. If so, add it. */\n    if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){\n      p->current.isPSample = 1;\n      p->current.iCol = 0;\n      sampleInsert(p, &p->current, p->nCol-1);\n      p->current.isPSample = 0;\n    }\n\n    /* Update the aBest[] array. */\n    for(i=0; i<(p->nCol-1); i++){\n      p->current.iCol = i;\n      if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){\n        sampleCopy(p, &p->aBest[i], &p->current);\n      }\n    }\n  }else\n#endif\n  if( p->nLimit && p->nRow>(tRowcnt)p->nLimit*(p->nSkipAhead+1) ){\n    p->nSkipAhead++;\n    sqlite3_result_int(context, p->current.anDLt[0]>0);\n  }\n}\n\nstatic const FuncDef statPushFuncdef = {\n  2+IsStat4,       /* nArg */\n  SQLITE_UTF8,     /* funcFlags */\n  0,               /* pUserData */\n  0,               /* pNext */\n  statPush,        /* xSFunc */\n  0,               /* xFinalize */\n  0, 0,            /* xValue, xInverse */\n  \"stat_push\",     /* zName */\n  {0}\n};\n\n#define STAT_GET_STAT1 0          /* \"stat\" column of stat1 table */\n#define STAT_GET_ROWID 1          /* \"rowid\" column of stat[34] entry */\n#define STAT_GET_NEQ   2          /* \"neq\" column of stat[34] entry */\n#define STAT_GET_NLT   3          /* \"nlt\" column of stat[34] entry */\n#define STAT_GET_NDLT  4          /* \"ndlt\" column of stat[34] entry */\n\n/*\n** Implementation of the stat_get(P,J) SQL function.  This routine is\n** used to query statistical information that has been gathered into\n** the StatAccum object by prior calls to stat_push().  The P parameter\n** has type BLOB but it is really just a pointer to the StatAccum object.\n** The content to returned is determined by the parameter J\n** which is one of the STAT_GET_xxxx values defined above.\n**\n** The stat_get(P,J) function is not available to generic SQL.  It is\n** inserted as part of a manually constructed bytecode program.  (See\n** the callStatGet() routine below.)  It is guaranteed that the P\n** parameter will always be a pointer to a StatAccum object, never a\n** NULL.\n**\n** If STAT4 is not enabled, then J is always\n** STAT_GET_STAT1 and is hence omitted and this routine becomes\n** a one-parameter function, stat_get(P), that always returns the\n** stat1 table entry information.\n*/\nstatic void statGet(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  StatAccum *p = (StatAccum*)sqlite3_value_blob(argv[0]);\n#ifdef SQLITE_ENABLE_STAT4\n  /* STAT4 has a parameter on this routine. */\n  int eCall = sqlite3_value_int(argv[1]);\n  assert( argc==2 );\n  assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ \n       || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT\n       || eCall==STAT_GET_NDLT \n  );\n  assert( eCall==STAT_GET_STAT1 || p->mxSample );\n  if( eCall==STAT_GET_STAT1 )\n#else\n  assert( argc==1 );\n#endif\n  {\n    /* Return the value to store in the \"stat\" column of the sqlite_stat1\n    ** table for this index.\n    **\n    ** The value is a string composed of a list of integers describing \n    ** the index. The first integer in the list is the total number of \n    ** entries in the index. There is one additional integer in the list \n    ** for each indexed column. This additional integer is an estimate of\n    ** the number of rows matched by a equality query on the index using\n    ** a key with the corresponding number of fields. In other words,\n    ** if the index is on columns (a,b) and the sqlite_stat1 value is \n    ** \"100 10 2\", then SQLite estimates that:\n    **\n    **   * the index contains 100 rows,\n    **   * \"WHERE a=?\" matches 10 rows, and\n    **   * \"WHERE a=? AND b=?\" matches 2 rows.\n    **\n    ** If D is the count of distinct values and K is the total number of \n    ** rows, then each estimate is computed as:\n    **\n    **        I = (K+D-1)/D\n    */\n    char *z;\n    int i;\n\n    char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );\n    if( zRet==0 ){\n      sqlite3_result_error_nomem(context);\n      return;\n    }\n\n    sqlite3_snprintf(24, zRet, \"%llu\", \n        p->nSkipAhead ? (u64)p->nEst : (u64)p->nRow);\n    z = zRet + sqlite3Strlen30(zRet);\n    for(i=0; i<p->nKeyCol; i++){\n      u64 nDistinct = p->current.anDLt[i] + 1;\n      u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;\n      sqlite3_snprintf(24, z, \" %llu\", iVal);\n      z += sqlite3Strlen30(z);\n      assert( p->current.anEq[i] );\n    }\n    assert( z[0]=='\\0' && z>zRet );\n\n    sqlite3_result_text(context, zRet, -1, sqlite3_free);\n  }\n#ifdef SQLITE_ENABLE_STAT4\n  else if( eCall==STAT_GET_ROWID ){\n    if( p->iGet<0 ){\n      samplePushPrevious(p, 0);\n      p->iGet = 0;\n    }\n    if( p->iGet<p->nSample ){\n      StatSample *pS = p->a + p->iGet;\n      if( pS->nRowid==0 ){\n        sqlite3_result_int64(context, pS->u.iRowid);\n      }else{\n        sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,\n                            SQLITE_TRANSIENT);\n      }\n    }\n  }else{\n    tRowcnt *aCnt = 0;\n\n    assert( p->iGet<p->nSample );\n    switch( eCall ){\n      case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;\n      case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;\n      default: {\n        aCnt = p->a[p->iGet].anDLt; \n        p->iGet++;\n        break;\n      }\n    }\n\n    {\n      char *zRet = sqlite3MallocZero(p->nCol * 25);\n      if( zRet==0 ){\n        sqlite3_result_error_nomem(context);\n      }else{\n        int i;\n        char *z = zRet;\n        for(i=0; i<p->nCol; i++){\n          sqlite3_snprintf(24, z, \"%llu \", (u64)aCnt[i]);\n          z += sqlite3Strlen30(z);\n        }\n        assert( z[0]=='\\0' && z>zRet );\n        z[-1] = '\\0';\n        sqlite3_result_text(context, zRet, -1, sqlite3_free);\n      }\n    }\n  }\n#endif /* SQLITE_ENABLE_STAT4 */\n#ifndef SQLITE_DEBUG\n  UNUSED_PARAMETER( argc );\n#endif\n}\nstatic const FuncDef statGetFuncdef = {\n  1+IsStat4,       /* nArg */\n  SQLITE_UTF8,     /* funcFlags */\n  0,               /* pUserData */\n  0,               /* pNext */\n  statGet,         /* xSFunc */\n  0,               /* xFinalize */\n  0, 0,            /* xValue, xInverse */\n  \"stat_get\",      /* zName */\n  {0}\n};\n\nstatic void callStatGet(Parse *pParse, int regStat, int iParam, int regOut){\n#ifdef SQLITE_ENABLE_STAT4\n  sqlite3VdbeAddOp2(pParse->pVdbe, OP_Integer, iParam, regStat+1);\n#elif SQLITE_DEBUG\n  assert( iParam==STAT_GET_STAT1 );\n#else\n  UNUSED_PARAMETER( iParam );\n#endif\n  assert( regOut!=regStat && regOut!=regStat+1 );\n  sqlite3VdbeAddFunctionCall(pParse, 0, regStat, regOut, 1+IsStat4,\n                             &statGetFuncdef, 0);\n}\n\n/*\n** Generate code to do an analysis of all indices associated with\n** a single table.\n*/\nstatic void analyzeOneTable(\n  Parse *pParse,   /* Parser context */\n  Table *pTab,     /* Table whose indices are to be analyzed */\n  Index *pOnlyIdx, /* If not NULL, only analyze this one index */\n  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */\n  int iMem,        /* Available memory locations begin here */\n  int iTab         /* Next available cursor */\n){\n  sqlite3 *db = pParse->db;    /* Database handle */\n  Index *pIdx;                 /* An index to being analyzed */\n  int iIdxCur;                 /* Cursor open on index being analyzed */\n  int iTabCur;                 /* Table cursor */\n  Vdbe *v;                     /* The virtual machine being built up */\n  int i;                       /* Loop counter */\n  int jZeroRows = -1;          /* Jump from here if number of rows is zero */\n  int iDb;                     /* Index of database containing pTab */\n  u8 needTableCnt = 1;         /* True to count the table */\n  int regNewRowid = iMem++;    /* Rowid for the inserted record */\n  int regStat = iMem++;        /* Register to hold StatAccum object */\n  int regChng = iMem++;        /* Index of changed index field */\n  int regRowid = iMem++;       /* Rowid argument passed to stat_push() */\n  int regTemp = iMem++;        /* Temporary use register */\n  int regTemp2 = iMem++;       /* Second temporary use register */\n  int regTabname = iMem++;     /* Register containing table name */\n  int regIdxname = iMem++;     /* Register containing index name */\n  int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */\n  int regPrev = iMem;          /* MUST BE LAST (see below) */\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n  Table *pStat1 = 0; \n#endif\n\n  pParse->nMem = MAX(pParse->nMem, iMem);\n  v = sqlite3GetVdbe(pParse);\n  if( v==0 || NEVER(pTab==0) ){\n    return;\n  }\n  if( pTab->tnum==0 ){\n    /* Do not gather statistics on views or virtual tables */\n    return;\n  }\n  if( sqlite3_strlike(\"sqlite\\\\_%\", pTab->zName, '\\\\')==0 ){\n    /* Do not gather statistics on system tables */\n    return;\n  }\n  assert( sqlite3BtreeHoldsAllMutexes(db) );\n  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n  assert( iDb>=0 );\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,\n      db->aDb[iDb].zDbSName ) ){\n    return;\n  }\n#endif\n\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n  if( db->xPreUpdateCallback ){\n    pStat1 = (Table*)sqlite3DbMallocZero(db, sizeof(Table) + 13);\n    if( pStat1==0 ) return;\n    pStat1->zName = (char*)&pStat1[1];\n    memcpy(pStat1->zName, \"sqlite_stat1\", 13);\n    pStat1->nCol = 3;\n    pStat1->iPKey = -1;\n    sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNBLOB);\n  }\n#endif\n\n  /* Establish a read-lock on the table at the shared-cache level. \n  ** Open a read-only cursor on the table. Also allocate a cursor number\n  ** to use for scanning indexes (iIdxCur). No index cursor is opened at\n  ** this time though.  */\n  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);\n  iTabCur = iTab++;\n  iIdxCur = iTab++;\n  pParse->nTab = MAX(pParse->nTab, iTab);\n  sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);\n  sqlite3VdbeLoadString(v, regTabname, pTab->zName);\n\n  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n    int nCol;                     /* Number of columns in pIdx. \"N\" */\n    int addrRewind;               /* Address of \"OP_Rewind iIdxCur\" */\n    int addrNextRow;              /* Address of \"next_row:\" */\n    const char *zIdxName;         /* Name of the index */\n    int nColTest;                 /* Number of columns to test for changes */\n\n    if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;\n    if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;\n    if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){\n      nCol = pIdx->nKeyCol;\n      zIdxName = pTab->zName;\n      nColTest = nCol - 1;\n    }else{\n      nCol = pIdx->nColumn;\n      zIdxName = pIdx->zName;\n      nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;\n    }\n\n    /* Populate the register containing the index name. */\n    sqlite3VdbeLoadString(v, regIdxname, zIdxName);\n    VdbeComment((v, \"Analysis for %s.%s\", pTab->zName, zIdxName));\n\n    /*\n    ** Pseudo-code for loop that calls stat_push():\n    **\n    **   Rewind csr\n    **   if eof(csr) goto end_of_scan;\n    **   regChng = 0\n    **   goto chng_addr_0;\n    **\n    **  next_row:\n    **   regChng = 0\n    **   if( idx(0) != regPrev(0) ) goto chng_addr_0\n    **   regChng = 1\n    **   if( idx(1) != regPrev(1) ) goto chng_addr_1\n    **   ...\n    **   regChng = N\n    **   goto chng_addr_N\n    **\n    **  chng_addr_0:\n    **   regPrev(0) = idx(0)\n    **  chng_addr_1:\n    **   regPrev(1) = idx(1)\n    **  ...\n    **\n    **  endDistinctTest:\n    **   regRowid = idx(rowid)\n    **   stat_push(P, regChng, regRowid)\n    **   Next csr\n    **   if !eof(csr) goto next_row;\n    **\n    **  end_of_scan:\n    */\n\n    /* Make sure there are enough memory cells allocated to accommodate \n    ** the regPrev array and a trailing rowid (the rowid slot is required\n    ** when building a record to insert into the sample column of \n    ** the sqlite_stat4 table.  */\n    pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);\n\n    /* Open a read-only cursor on the index being analyzed. */\n    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );\n    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);\n    sqlite3VdbeSetP4KeyInfo(pParse, pIdx);\n    VdbeComment((v, \"%s\", pIdx->zName));\n\n    /* Invoke the stat_init() function. The arguments are:\n    ** \n    **    (1) the number of columns in the index including the rowid\n    **        (or for a WITHOUT ROWID table, the number of PK columns),\n    **    (2) the number of columns in the key without the rowid/pk\n    **    (3) estimated number of rows in the index,\n    */\n    sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat+1);\n    assert( regRowid==regStat+2 );\n    sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regRowid);\n#ifdef SQLITE_ENABLE_STAT4\n    if( OptimizationEnabled(db, SQLITE_Stat4) ){\n      sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regTemp);\n      addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);\n      VdbeCoverage(v);\n    }else\n#endif\n    {\n      addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);\n      VdbeCoverage(v);\n      sqlite3VdbeAddOp3(v, OP_Count, iIdxCur, regTemp, 1);\n    }\n    assert( regTemp2==regStat+4 );\n    sqlite3VdbeAddOp2(v, OP_Integer, db->nAnalysisLimit, regTemp2);\n    sqlite3VdbeAddFunctionCall(pParse, 0, regStat+1, regStat, 4,\n                               &statInitFuncdef, 0);\n\n    /* Implementation of the following:\n    **\n    **   Rewind csr\n    **   if eof(csr) goto end_of_scan;\n    **   regChng = 0\n    **   goto next_push_0;\n    **\n    */\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);\n    addrNextRow = sqlite3VdbeCurrentAddr(v);\n\n    if( nColTest>0 ){\n      int endDistinctTest = sqlite3VdbeMakeLabel(pParse);\n      int *aGotoChng;               /* Array of jump instruction addresses */\n      aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);\n      if( aGotoChng==0 ) continue;\n\n      /*\n      **  next_row:\n      **   regChng = 0\n      **   if( idx(0) != regPrev(0) ) goto chng_addr_0\n      **   regChng = 1\n      **   if( idx(1) != regPrev(1) ) goto chng_addr_1\n      **   ...\n      **   regChng = N\n      **   goto endDistinctTest\n      */\n      sqlite3VdbeAddOp0(v, OP_Goto);\n      addrNextRow = sqlite3VdbeCurrentAddr(v);\n      if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){\n        /* For a single-column UNIQUE index, once we have found a non-NULL\n        ** row, we know that all the rest will be distinct, so skip \n        ** subsequent distinctness tests. */\n        sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);\n        VdbeCoverage(v);\n      }\n      for(i=0; i<nColTest; i++){\n        char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);\n        sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);\n        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);\n        VdbeComment((v, \"%s.column(%d)\", pIdx->zName, i));\n        aGotoChng[i] = \n        sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);\n        sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);\n        VdbeCoverage(v);\n      }\n      sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);\n      sqlite3VdbeGoto(v, endDistinctTest);\n  \n  \n      /*\n      **  chng_addr_0:\n      **   regPrev(0) = idx(0)\n      **  chng_addr_1:\n      **   regPrev(1) = idx(1)\n      **  ...\n      */\n      sqlite3VdbeJumpHere(v, addrNextRow-1);\n      for(i=0; i<nColTest; i++){\n        sqlite3VdbeJumpHere(v, aGotoChng[i]);\n        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);\n        VdbeComment((v, \"%s.column(%d)\", pIdx->zName, i));\n      }\n      sqlite3VdbeResolveLabel(v, endDistinctTest);\n      sqlite3DbFree(db, aGotoChng);\n    }\n  \n    /*\n    **  chng_addr_N:\n    **   regRowid = idx(rowid)            // STAT4 only\n    **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT4 only\n    **   Next csr\n    **   if !eof(csr) goto next_row;\n    */\n#ifdef SQLITE_ENABLE_STAT4\n    if( OptimizationEnabled(db, SQLITE_Stat4) ){\n      assert( regRowid==(regStat+2) );\n      if( HasRowid(pTab) ){\n        sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);\n      }else{\n        Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);\n        int j, k, regKey;\n        regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);\n        for(j=0; j<pPk->nKeyCol; j++){\n          k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);\n          assert( k>=0 && k<pIdx->nColumn );\n          sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);\n          VdbeComment((v, \"%s.column(%d)\", pIdx->zName, i));\n        }\n        sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);\n        sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);\n      }\n    }\n#endif\n    assert( regChng==(regStat+1) );\n    {\n      sqlite3VdbeAddFunctionCall(pParse, 1, regStat, regTemp, 2+IsStat4,\n                                 &statPushFuncdef, 0);\n      if( db->nAnalysisLimit ){\n        int j1, j2, j3;\n        j1 = sqlite3VdbeAddOp1(v, OP_IsNull, regTemp); VdbeCoverage(v);\n        j2 = sqlite3VdbeAddOp1(v, OP_If, regTemp); VdbeCoverage(v);\n        j3 = sqlite3VdbeAddOp4Int(v, OP_SeekGT, iIdxCur, 0, regPrev, 1);\n        VdbeCoverage(v);\n        sqlite3VdbeJumpHere(v, j1);\n        sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);\n        sqlite3VdbeJumpHere(v, j2);\n        sqlite3VdbeJumpHere(v, j3);\n      }else{\n        sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);\n      }\n    }\n\n    /* Add the entry to the stat1 table. */\n    callStatGet(pParse, regStat, STAT_GET_STAT1, regStat1);\n    assert( \"BBB\"[0]==SQLITE_AFF_TEXT );\n    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, \"BBB\", 0);\n    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);\n    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n    sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);\n#endif\n    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);\n\n    /* Add the entries to the stat4 table. */\n#ifdef SQLITE_ENABLE_STAT4\n    if( OptimizationEnabled(db, SQLITE_Stat4) && db->nAnalysisLimit==0 ){\n      int regEq = regStat1;\n      int regLt = regStat1+1;\n      int regDLt = regStat1+2;\n      int regSample = regStat1+3;\n      int regCol = regStat1+4;\n      int regSampleRowid = regCol + nCol;\n      int addrNext;\n      int addrIsNull;\n      u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;\n\n      pParse->nMem = MAX(pParse->nMem, regCol+nCol);\n\n      addrNext = sqlite3VdbeCurrentAddr(v);\n      callStatGet(pParse, regStat, STAT_GET_ROWID, regSampleRowid);\n      addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);\n      VdbeCoverage(v);\n      callStatGet(pParse, regStat, STAT_GET_NEQ, regEq);\n      callStatGet(pParse, regStat, STAT_GET_NLT, regLt);\n      callStatGet(pParse, regStat, STAT_GET_NDLT, regDLt);\n      sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);\n      VdbeCoverage(v);\n      for(i=0; i<nCol; i++){\n        sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);\n      }\n      sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);\n      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);\n      sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);\n      sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);\n      sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */\n      sqlite3VdbeJumpHere(v, addrIsNull);\n    }\n#endif /* SQLITE_ENABLE_STAT4 */\n\n    /* End of analysis */\n    sqlite3VdbeJumpHere(v, addrRewind);\n  }\n\n\n  /* Create a single sqlite_stat1 entry containing NULL as the index\n  ** name and the row count as the content.\n  */\n  if( pOnlyIdx==0 && needTableCnt ){\n    VdbeComment((v, \"%s\", pTab->zName));\n    sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);\n    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);\n    sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);\n    assert( \"BBB\"[0]==SQLITE_AFF_TEXT );\n    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, \"BBB\", 0);\n    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);\n    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);\n    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n    sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);\n#endif\n    sqlite3VdbeJumpHere(v, jZeroRows);\n  }\n}\n\n\n/*\n** Generate code that will cause the most recent index analysis to\n** be loaded into internal hash tables where is can be used.\n*/\nstatic void loadAnalysis(Parse *pParse, int iDb){\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  if( v ){\n    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);\n  }\n}\n\n/*\n** Generate code that will do an analysis of an entire database\n*/\nstatic void analyzeDatabase(Parse *pParse, int iDb){\n  sqlite3 *db = pParse->db;\n  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */\n  HashElem *k;\n  int iStatCur;\n  int iMem;\n  int iTab;\n\n  sqlite3BeginWriteOperation(pParse, 0, iDb);\n  iStatCur = pParse->nTab;\n  pParse->nTab += 3;\n  openStatTable(pParse, iDb, iStatCur, 0, 0);\n  iMem = pParse->nMem+1;\n  iTab = pParse->nTab;\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){\n    Table *pTab = (Table*)sqliteHashData(k);\n    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);\n  }\n  loadAnalysis(pParse, iDb);\n}\n\n/*\n** Generate code that will do an analysis of a single table in\n** a database.  If pOnlyIdx is not NULL then it is a single index\n** in pTab that should be analyzed.\n*/\nstatic void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){\n  int iDb;\n  int iStatCur;\n\n  assert( pTab!=0 );\n  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );\n  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n  sqlite3BeginWriteOperation(pParse, 0, iDb);\n  iStatCur = pParse->nTab;\n  pParse->nTab += 3;\n  if( pOnlyIdx ){\n    openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, \"idx\");\n  }else{\n    openStatTable(pParse, iDb, iStatCur, pTab->zName, \"tbl\");\n  }\n  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);\n  loadAnalysis(pParse, iDb);\n}\n\n/*\n** Generate code for the ANALYZE command.  The parser calls this routine\n** when it recognizes an ANALYZE command.\n**\n**        ANALYZE                            -- 1\n**        ANALYZE  <database>                -- 2\n**        ANALYZE  ?<database>.?<tablename>  -- 3\n**\n** Form 1 causes all indices in all attached databases to be analyzed.\n** Form 2 analyzes all indices the single database named.\n** Form 3 analyzes all indices associated with the named table.\n*/\nSQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){\n  sqlite3 *db = pParse->db;\n  int iDb;\n  int i;\n  char *z, *zDb;\n  Table *pTab;\n  Index *pIdx;\n  Token *pTableName;\n  Vdbe *v;\n\n  /* Read the database schema. If an error occurs, leave an error message\n  ** and code in pParse and return NULL. */\n  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );\n  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){\n    return;\n  }\n\n  assert( pName2!=0 || pName1==0 );\n  if( pName1==0 ){\n    /* Form 1:  Analyze everything */\n    for(i=0; i<db->nDb; i++){\n      if( i==1 ) continue;  /* Do not analyze the TEMP database */\n      analyzeDatabase(pParse, i);\n    }\n  }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){\n    /* Analyze the schema named as the argument */\n    analyzeDatabase(pParse, iDb);\n  }else{\n    /* Form 3: Analyze the table or index named as an argument */\n    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);\n    if( iDb>=0 ){\n      zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;\n      z = sqlite3NameFromToken(db, pTableName);\n      if( z ){\n        if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){\n          analyzeTable(pParse, pIdx->pTable, pIdx);\n        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){\n          analyzeTable(pParse, pTab, 0);\n        }\n        sqlite3DbFree(db, z);\n      }\n    }\n  }\n  if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){\n    sqlite3VdbeAddOp0(v, OP_Expire);\n  }\n}\n\n/*\n** Used to pass information from the analyzer reader through to the\n** callback routine.\n*/\ntypedef struct analysisInfo analysisInfo;\nstruct analysisInfo {\n  sqlite3 *db;\n  const char *zDatabase;\n};\n\n/*\n** The first argument points to a nul-terminated string containing a\n** list of space separated integers. Read the first nOut of these into\n** the array aOut[].\n*/\nstatic void decodeIntArray(\n  char *zIntArray,       /* String containing int array to decode */\n  int nOut,              /* Number of slots in aOut[] */\n  tRowcnt *aOut,         /* Store integers here */\n  LogEst *aLog,          /* Or, if aOut==0, here */\n  Index *pIndex          /* Handle extra flags for this index, if not NULL */\n){\n  char *z = zIntArray;\n  int c;\n  int i;\n  tRowcnt v;\n\n#ifdef SQLITE_ENABLE_STAT4\n  if( z==0 ) z = \"\";\n#else\n  assert( z!=0 );\n#endif\n  for(i=0; *z && i<nOut; i++){\n    v = 0;\n    while( (c=z[0])>='0' && c<='9' ){\n      v = v*10 + c - '0';\n      z++;\n    }\n#ifdef SQLITE_ENABLE_STAT4\n    if( aOut ) aOut[i] = v;\n    if( aLog ) aLog[i] = sqlite3LogEst(v);\n#else\n    assert( aOut==0 );\n    UNUSED_PARAMETER(aOut);\n    assert( aLog!=0 );\n    aLog[i] = sqlite3LogEst(v);\n#endif\n    if( *z==' ' ) z++;\n  }\n#ifndef SQLITE_ENABLE_STAT4\n  assert( pIndex!=0 ); {\n#else\n  if( pIndex ){\n#endif\n    pIndex->bUnordered = 0;\n    pIndex->noSkipScan = 0;\n    while( z[0] ){\n      if( sqlite3_strglob(\"unordered*\", z)==0 ){\n        pIndex->bUnordered = 1;\n      }else if( sqlite3_strglob(\"sz=[0-9]*\", z)==0 ){\n        int sz = sqlite3Atoi(z+3);\n        if( sz<2 ) sz = 2;\n        pIndex->szIdxRow = sqlite3LogEst(sz);\n      }else if( sqlite3_strglob(\"noskipscan*\", z)==0 ){\n        pIndex->noSkipScan = 1;\n      }\n#ifdef SQLITE_ENABLE_COSTMULT\n      else if( sqlite3_strglob(\"costmult=[0-9]*\",z)==0 ){\n        pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));\n      }\n#endif\n      while( z[0]!=0 && z[0]!=' ' ) z++;\n      while( z[0]==' ' ) z++;\n    }\n  }\n}\n\n/*\n** This callback is invoked once for each index when reading the\n** sqlite_stat1 table.  \n**\n**     argv[0] = name of the table\n**     argv[1] = name of the index (might be NULL)\n**     argv[2] = results of analysis - on integer for each column\n**\n** Entries for which argv[1]==NULL simply record the number of rows in\n** the table.\n*/\nstatic int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){\n  analysisInfo *pInfo = (analysisInfo*)pData;\n  Index *pIndex;\n  Table *pTable;\n  const char *z;\n\n  assert( argc==3 );\n  UNUSED_PARAMETER2(NotUsed, argc);\n\n  if( argv==0 || argv[0]==0 || argv[2]==0 ){\n    return 0;\n  }\n  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);\n  if( pTable==0 ){\n    return 0;\n  }\n  if( argv[1]==0 ){\n    pIndex = 0;\n  }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){\n    pIndex = sqlite3PrimaryKeyIndex(pTable);\n  }else{\n    pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);\n  }\n  z = argv[2];\n\n  if( pIndex ){\n    tRowcnt *aiRowEst = 0;\n    int nCol = pIndex->nKeyCol+1;\n#ifdef SQLITE_ENABLE_STAT4\n    /* Index.aiRowEst may already be set here if there are duplicate \n    ** sqlite_stat1 entries for this index. In that case just clobber\n    ** the old data with the new instead of allocating a new array.  */\n    if( pIndex->aiRowEst==0 ){\n      pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);\n      if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);\n    }\n    aiRowEst = pIndex->aiRowEst;\n#endif\n    pIndex->bUnordered = 0;\n    decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);\n    pIndex->hasStat1 = 1;\n    if( pIndex->pPartIdxWhere==0 ){\n      pTable->nRowLogEst = pIndex->aiRowLogEst[0];\n      pTable->tabFlags |= TF_HasStat1;\n    }\n  }else{\n    Index fakeIdx;\n    fakeIdx.szIdxRow = pTable->szTabRow;\n#ifdef SQLITE_ENABLE_COSTMULT\n    fakeIdx.pTable = pTable;\n#endif\n    decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);\n    pTable->szTabRow = fakeIdx.szIdxRow;\n    pTable->tabFlags |= TF_HasStat1;\n  }\n\n  return 0;\n}\n\n/*\n** If the Index.aSample variable is not NULL, delete the aSample[] array\n** and its contents.\n*/\nSQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){\n#ifdef SQLITE_ENABLE_STAT4\n  if( pIdx->aSample ){\n    int j;\n    for(j=0; j<pIdx->nSample; j++){\n      IndexSample *p = &pIdx->aSample[j];\n      sqlite3DbFree(db, p->p);\n    }\n    sqlite3DbFree(db, pIdx->aSample);\n  }\n  if( db && db->pnBytesFreed==0 ){\n    pIdx->nSample = 0;\n    pIdx->aSample = 0;\n  }\n#else\n  UNUSED_PARAMETER(db);\n  UNUSED_PARAMETER(pIdx);\n#endif /* SQLITE_ENABLE_STAT4 */\n}\n\n#ifdef SQLITE_ENABLE_STAT4\n/*\n** Populate the pIdx->aAvgEq[] array based on the samples currently\n** stored in pIdx->aSample[]. \n*/\nstatic void initAvgEq(Index *pIdx){\n  if( pIdx ){\n    IndexSample *aSample = pIdx->aSample;\n    IndexSample *pFinal = &aSample[pIdx->nSample-1];\n    int iCol;\n    int nCol = 1;\n    if( pIdx->nSampleCol>1 ){\n      /* If this is stat4 data, then calculate aAvgEq[] values for all\n      ** sample columns except the last. The last is always set to 1, as\n      ** once the trailing PK fields are considered all index keys are\n      ** unique.  */\n      nCol = pIdx->nSampleCol-1;\n      pIdx->aAvgEq[nCol] = 1;\n    }\n    for(iCol=0; iCol<nCol; iCol++){\n      int nSample = pIdx->nSample;\n      int i;                    /* Used to iterate through samples */\n      tRowcnt sumEq = 0;        /* Sum of the nEq values */\n      tRowcnt avgEq = 0;\n      tRowcnt nRow;             /* Number of rows in index */\n      i64 nSum100 = 0;          /* Number of terms contributing to sumEq */\n      i64 nDist100;             /* Number of distinct values in index */\n\n      if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){\n        nRow = pFinal->anLt[iCol];\n        nDist100 = (i64)100 * pFinal->anDLt[iCol];\n        nSample--;\n      }else{\n        nRow = pIdx->aiRowEst[0];\n        nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];\n      }\n      pIdx->nRowEst0 = nRow;\n\n      /* Set nSum to the number of distinct (iCol+1) field prefixes that\n      ** occur in the stat4 table for this index. Set sumEq to the sum of \n      ** the nEq values for column iCol for the same set (adding the value \n      ** only once where there exist duplicate prefixes).  */\n      for(i=0; i<nSample; i++){\n        if( i==(pIdx->nSample-1)\n         || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] \n        ){\n          sumEq += aSample[i].anEq[iCol];\n          nSum100 += 100;\n        }\n      }\n\n      if( nDist100>nSum100 && sumEq<nRow ){\n        avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);\n      }\n      if( avgEq==0 ) avgEq = 1;\n      pIdx->aAvgEq[iCol] = avgEq;\n    }\n  }\n}\n\n/*\n** Look up an index by name.  Or, if the name of a WITHOUT ROWID table\n** is supplied instead, find the PRIMARY KEY index for that table.\n*/\nstatic Index *findIndexOrPrimaryKey(\n  sqlite3 *db,\n  const char *zName,\n  const char *zDb\n){\n  Index *pIdx = sqlite3FindIndex(db, zName, zDb);\n  if( pIdx==0 ){\n    Table *pTab = sqlite3FindTable(db, zName, zDb);\n    if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);\n  }\n  return pIdx;\n}\n\n/*\n** Load the content from either the sqlite_stat4\n** into the relevant Index.aSample[] arrays.\n**\n** Arguments zSql1 and zSql2 must point to SQL statements that return\n** data equivalent to the following:\n**\n**    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx\n**    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4\n**\n** where %Q is replaced with the database name before the SQL is executed.\n*/\nstatic int loadStatTbl(\n  sqlite3 *db,                  /* Database handle */\n  const char *zSql1,            /* SQL statement 1 (see above) */\n  const char *zSql2,            /* SQL statement 2 (see above) */\n  const char *zDb               /* Database name (e.g. \"main\") */\n){\n  int rc;                       /* Result codes from subroutines */\n  sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */\n  char *zSql;                   /* Text of the SQL statement */\n  Index *pPrevIdx = 0;          /* Previous index in the loop */\n  IndexSample *pSample;         /* A slot in pIdx->aSample[] */\n\n  assert( db->lookaside.bDisable );\n  zSql = sqlite3MPrintf(db, zSql1, zDb);\n  if( !zSql ){\n    return SQLITE_NOMEM_BKPT;\n  }\n  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);\n  sqlite3DbFree(db, zSql);\n  if( rc ) return rc;\n\n  while( sqlite3_step(pStmt)==SQLITE_ROW ){\n    int nIdxCol = 1;              /* Number of columns in stat4 records */\n\n    char *zIndex;   /* Index name */\n    Index *pIdx;    /* Pointer to the index object */\n    int nSample;    /* Number of samples */\n    int nByte;      /* Bytes of space required */\n    int i;          /* Bytes of space required */\n    tRowcnt *pSpace;\n\n    zIndex = (char *)sqlite3_column_text(pStmt, 0);\n    if( zIndex==0 ) continue;\n    nSample = sqlite3_column_int(pStmt, 1);\n    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);\n    assert( pIdx==0 || pIdx->nSample==0 );\n    if( pIdx==0 ) continue;\n    assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );\n    if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){\n      nIdxCol = pIdx->nKeyCol;\n    }else{\n      nIdxCol = pIdx->nColumn;\n    }\n    pIdx->nSampleCol = nIdxCol;\n    nByte = sizeof(IndexSample) * nSample;\n    nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;\n    nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */\n\n    pIdx->aSample = sqlite3DbMallocZero(db, nByte);\n    if( pIdx->aSample==0 ){\n      sqlite3_finalize(pStmt);\n      return SQLITE_NOMEM_BKPT;\n    }\n    pSpace = (tRowcnt*)&pIdx->aSample[nSample];\n    pIdx->aAvgEq = pSpace; pSpace += nIdxCol;\n    for(i=0; i<nSample; i++){\n      pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;\n      pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;\n      pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;\n    }\n    assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );\n  }\n  rc = sqlite3_finalize(pStmt);\n  if( rc ) return rc;\n\n  zSql = sqlite3MPrintf(db, zSql2, zDb);\n  if( !zSql ){\n    return SQLITE_NOMEM_BKPT;\n  }\n  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);\n  sqlite3DbFree(db, zSql);\n  if( rc ) return rc;\n\n  while( sqlite3_step(pStmt)==SQLITE_ROW ){\n    char *zIndex;                 /* Index name */\n    Index *pIdx;                  /* Pointer to the index object */\n    int nCol = 1;                 /* Number of columns in index */\n\n    zIndex = (char *)sqlite3_column_text(pStmt, 0);\n    if( zIndex==0 ) continue;\n    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);\n    if( pIdx==0 ) continue;\n    /* This next condition is true if data has already been loaded from \n    ** the sqlite_stat4 table. */\n    nCol = pIdx->nSampleCol;\n    if( pIdx!=pPrevIdx ){\n      initAvgEq(pPrevIdx);\n      pPrevIdx = pIdx;\n    }\n    pSample = &pIdx->aSample[pIdx->nSample];\n    decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);\n    decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);\n    decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);\n\n    /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.\n    ** This is in case the sample record is corrupted. In that case, the\n    ** sqlite3VdbeRecordCompare() may read up to two varints past the\n    ** end of the allocated buffer before it realizes it is dealing with\n    ** a corrupt record. Adding the two 0x00 bytes prevents this from causing\n    ** a buffer overread.  */\n    pSample->n = sqlite3_column_bytes(pStmt, 4);\n    pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);\n    if( pSample->p==0 ){\n      sqlite3_finalize(pStmt);\n      return SQLITE_NOMEM_BKPT;\n    }\n    if( pSample->n ){\n      memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);\n    }\n    pIdx->nSample++;\n  }\n  rc = sqlite3_finalize(pStmt);\n  if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);\n  return rc;\n}\n\n/*\n** Load content from the sqlite_stat4 table into \n** the Index.aSample[] arrays of all indices.\n*/\nstatic int loadStat4(sqlite3 *db, const char *zDb){\n  int rc = SQLITE_OK;             /* Result codes from subroutines */\n\n  assert( db->lookaside.bDisable );\n  if( sqlite3FindTable(db, \"sqlite_stat4\", zDb) ){\n    rc = loadStatTbl(db,\n      \"SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx\", \n      \"SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4\",\n      zDb\n    );\n  }\n  return rc;\n}\n#endif /* SQLITE_ENABLE_STAT4 */\n\n/*\n** Load the content of the sqlite_stat1 and sqlite_stat4 tables. The\n** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]\n** arrays. The contents of sqlite_stat4 are used to populate the\n** Index.aSample[] arrays.\n**\n** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR\n** is returned. In this case, even if SQLITE_ENABLE_STAT4 was defined \n** during compilation and the sqlite_stat4 table is present, no data is \n** read from it.\n**\n** If SQLITE_ENABLE_STAT4 was defined during compilation and the \n** sqlite_stat4 table is not present in the database, SQLITE_ERROR is\n** returned. However, in this case, data is read from the sqlite_stat1\n** table (if it is present) before returning.\n**\n** If an OOM error occurs, this function always sets db->mallocFailed.\n** This means if the caller does not care about other errors, the return\n** code may be ignored.\n*/\nSQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){\n  analysisInfo sInfo;\n  HashElem *i;\n  char *zSql;\n  int rc = SQLITE_OK;\n  Schema *pSchema = db->aDb[iDb].pSchema;\n\n  assert( iDb>=0 && iDb<db->nDb );\n  assert( db->aDb[iDb].pBt!=0 );\n\n  /* Clear any prior statistics */\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){\n    Table *pTab = sqliteHashData(i);\n    pTab->tabFlags &= ~TF_HasStat1;\n  }\n  for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){\n    Index *pIdx = sqliteHashData(i);\n    pIdx->hasStat1 = 0;\n#ifdef SQLITE_ENABLE_STAT4\n    sqlite3DeleteIndexSamples(db, pIdx);\n    pIdx->aSample = 0;\n#endif\n  }\n\n  /* Load new statistics out of the sqlite_stat1 table */\n  sInfo.db = db;\n  sInfo.zDatabase = db->aDb[iDb].zDbSName;\n  if( sqlite3FindTable(db, \"sqlite_stat1\", sInfo.zDatabase)!=0 ){\n    zSql = sqlite3MPrintf(db, \n        \"SELECT tbl,idx,stat FROM %Q.sqlite_stat1\", sInfo.zDatabase);\n    if( zSql==0 ){\n      rc = SQLITE_NOMEM_BKPT;\n    }else{\n      rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);\n      sqlite3DbFree(db, zSql);\n    }\n  }\n\n  /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){\n    Index *pIdx = sqliteHashData(i);\n    if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);\n  }\n\n  /* Load the statistics from the sqlite_stat4 table. */\n#ifdef SQLITE_ENABLE_STAT4\n  if( rc==SQLITE_OK ){\n    DisableLookaside;\n    rc = loadStat4(db, sInfo.zDatabase);\n    EnableLookaside;\n  }\n  for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){\n    Index *pIdx = sqliteHashData(i);\n    sqlite3_free(pIdx->aiRowEst);\n    pIdx->aiRowEst = 0;\n  }\n#endif\n\n  if( rc==SQLITE_NOMEM ){\n    sqlite3OomFault(db);\n  }\n  return rc;\n}\n\n\n#endif /* SQLITE_OMIT_ANALYZE */\n\n/************** End of analyze.c *********************************************/\n/************** Begin file attach.c ******************************************/\n/*\n** 2003 April 6\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code used to implement the ATTACH and DETACH commands.\n*/\n/* #include \"sqliteInt.h\" */\n\n#ifndef SQLITE_OMIT_ATTACH\n/*\n** Resolve an expression that was part of an ATTACH or DETACH statement. This\n** is slightly different from resolving a normal SQL expression, because simple\n** identifiers are treated as strings, not possible column names or aliases.\n**\n** i.e. if the parser sees:\n**\n**     ATTACH DATABASE abc AS def\n**\n** it treats the two expressions as literal strings 'abc' and 'def' instead of\n** looking for columns of the same name.\n**\n** This only applies to the root node of pExpr, so the statement:\n**\n**     ATTACH DATABASE abc||def AS 'db2'\n**\n** will fail because neither abc or def can be resolved.\n*/\nstatic int resolveAttachExpr(NameContext *pName, Expr *pExpr)\n{\n  int rc = SQLITE_OK;\n  if( pExpr ){\n    if( pExpr->op!=TK_ID ){\n      rc = sqlite3ResolveExprNames(pName, pExpr);\n    }else{\n      pExpr->op = TK_STRING;\n    }\n  }\n  return rc;\n}\n\n/*\n** Return true if zName points to a name that may be used to refer to\n** database iDb attached to handle db.\n*/\nSQLITE_PRIVATE int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName){\n  return (\n      sqlite3StrICmp(db->aDb[iDb].zDbSName, zName)==0\n   || (iDb==0 && sqlite3StrICmp(\"main\", zName)==0)\n  );\n}\n\n/*\n** An SQL user-function registered to do the work of an ATTACH statement. The\n** three arguments to the function come directly from an attach statement:\n**\n**     ATTACH DATABASE x AS y KEY z\n**\n**     SELECT sqlite_attach(x, y, z)\n**\n** If the optional \"KEY z\" syntax is omitted, an SQL NULL is passed as the\n** third argument.\n**\n** If the db->init.reopenMemdb flags is set, then instead of attaching a\n** new database, close the database on db->init.iDb and reopen it as an\n** empty MemDB.\n*/\nstatic void attachFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **argv\n){\n  int i;\n  int rc = 0;\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  const char *zName;\n  const char *zFile;\n  char *zPath = 0;\n  char *zErr = 0;\n  unsigned int flags;\n  Db *aNew;                 /* New array of Db pointers */\n  Db *pNew;                 /* Db object for the newly attached database */\n  char *zErrDyn = 0;\n  sqlite3_vfs *pVfs;\n\n  UNUSED_PARAMETER(NotUsed);\n  zFile = (const char *)sqlite3_value_text(argv[0]);\n  zName = (const char *)sqlite3_value_text(argv[1]);\n  if( zFile==0 ) zFile = \"\";\n  if( zName==0 ) zName = \"\";\n\n#ifdef SQLITE_ENABLE_DESERIALIZE\n# define REOPEN_AS_MEMDB(db)  (db->init.reopenMemdb)\n#else\n# define REOPEN_AS_MEMDB(db)  (0)\n#endif\n\n  if( REOPEN_AS_MEMDB(db) ){\n    /* This is not a real ATTACH.  Instead, this routine is being called\n    ** from sqlite3_deserialize() to close database db->init.iDb and\n    ** reopen it as a MemDB */\n    pVfs = sqlite3_vfs_find(\"memdb\");\n    if( pVfs==0 ) return;\n    pNew = &db->aDb[db->init.iDb];\n    if( pNew->pBt ) sqlite3BtreeClose(pNew->pBt);\n    pNew->pBt = 0;\n    pNew->pSchema = 0;\n    rc = sqlite3BtreeOpen(pVfs, \"x\\0\", db, &pNew->pBt, 0, SQLITE_OPEN_MAIN_DB);\n  }else{\n    /* This is a real ATTACH\n    **\n    ** Check for the following errors:\n    **\n    **     * Too many attached databases,\n    **     * Transaction currently open\n    **     * Specified database name already being used.\n    */\n    if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){\n      zErrDyn = sqlite3MPrintf(db, \"too many attached databases - max %d\", \n        db->aLimit[SQLITE_LIMIT_ATTACHED]\n      );\n      goto attach_error;\n    }\n    for(i=0; i<db->nDb; i++){\n      assert( zName );\n      if( sqlite3DbIsNamed(db, i, zName) ){\n        zErrDyn = sqlite3MPrintf(db, \"database %s is already in use\", zName);\n        goto attach_error;\n      }\n    }\n  \n    /* Allocate the new entry in the db->aDb[] array and initialize the schema\n    ** hash tables.\n    */\n    if( db->aDb==db->aDbStatic ){\n      aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );\n      if( aNew==0 ) return;\n      memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);\n    }else{\n      aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );\n      if( aNew==0 ) return;\n    }\n    db->aDb = aNew;\n    pNew = &db->aDb[db->nDb];\n    memset(pNew, 0, sizeof(*pNew));\n  \n    /* Open the database file. If the btree is successfully opened, use\n    ** it to obtain the database schema. At this point the schema may\n    ** or may not be initialized.\n    */\n    flags = db->openFlags;\n    rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);\n    if( rc!=SQLITE_OK ){\n      if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);\n      sqlite3_result_error(context, zErr, -1);\n      sqlite3_free(zErr);\n      return;\n    }\n    assert( pVfs );\n    flags |= SQLITE_OPEN_MAIN_DB;\n    rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);\n    db->nDb++;\n    pNew->zDbSName = sqlite3DbStrDup(db, zName);\n  }\n  db->noSharedCache = 0;\n  if( rc==SQLITE_CONSTRAINT ){\n    rc = SQLITE_ERROR;\n    zErrDyn = sqlite3MPrintf(db, \"database is already attached\");\n  }else if( rc==SQLITE_OK ){\n    Pager *pPager;\n    pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);\n    if( !pNew->pSchema ){\n      rc = SQLITE_NOMEM_BKPT;\n    }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){\n      zErrDyn = sqlite3MPrintf(db, \n        \"attached databases must use the same text encoding as main database\");\n      rc = SQLITE_ERROR;\n    }\n    sqlite3BtreeEnter(pNew->pBt);\n    pPager = sqlite3BtreePager(pNew->pBt);\n    sqlite3PagerLockingMode(pPager, db->dfltLockMode);\n    sqlite3BtreeSecureDelete(pNew->pBt,\n                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );\n#ifndef SQLITE_OMIT_PAGER_PRAGMAS\n    sqlite3BtreeSetPagerFlags(pNew->pBt,\n                      PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));\n#endif\n    sqlite3BtreeLeave(pNew->pBt);\n  }\n  pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;\n  if( rc==SQLITE_OK && pNew->zDbSName==0 ){\n    rc = SQLITE_NOMEM_BKPT;\n  }\n  sqlite3_free_filename( zPath );\n\n  /* If the file was opened successfully, read the schema for the new database.\n  ** If this fails, or if opening the file failed, then close the file and \n  ** remove the entry from the db->aDb[] array. i.e. put everything back the\n  ** way we found it.\n  */\n  if( rc==SQLITE_OK ){\n    sqlite3BtreeEnterAll(db);\n    db->init.iDb = 0;\n    db->mDbFlags &= ~(DBFLAG_SchemaKnownOk);\n    if( !REOPEN_AS_MEMDB(db) ){\n      rc = sqlite3Init(db, &zErrDyn);\n    }\n    sqlite3BtreeLeaveAll(db);\n    assert( zErrDyn==0 || rc!=SQLITE_OK );\n  }\n#ifdef SQLITE_USER_AUTHENTICATION\n  if( rc==SQLITE_OK && !REOPEN_AS_MEMDB(db) ){\n    u8 newAuth = 0;\n    rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);\n    if( newAuth<db->auth.authLevel ){\n      rc = SQLITE_AUTH_USER;\n    }\n  }\n#endif\n  if( rc ){\n    if( !REOPEN_AS_MEMDB(db) ){\n      int iDb = db->nDb - 1;\n      assert( iDb>=2 );\n      if( db->aDb[iDb].pBt ){\n        sqlite3BtreeClose(db->aDb[iDb].pBt);\n        db->aDb[iDb].pBt = 0;\n        db->aDb[iDb].pSchema = 0;\n      }\n      sqlite3ResetAllSchemasOfConnection(db);\n      db->nDb = iDb;\n      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){\n        sqlite3OomFault(db);\n        sqlite3DbFree(db, zErrDyn);\n        zErrDyn = sqlite3MPrintf(db, \"out of memory\");\n      }else if( zErrDyn==0 ){\n        zErrDyn = sqlite3MPrintf(db, \"unable to open database: %s\", zFile);\n      }\n    }\n    goto attach_error;\n  }\n  \n  return;\n\nattach_error:\n  /* Return an error if we get here */\n  if( zErrDyn ){\n    sqlite3_result_error(context, zErrDyn, -1);\n    sqlite3DbFree(db, zErrDyn);\n  }\n  if( rc ) sqlite3_result_error_code(context, rc);\n}\n\n/*\n** An SQL user-function registered to do the work of an DETACH statement. The\n** three arguments to the function come directly from a detach statement:\n**\n**     DETACH DATABASE x\n**\n**     SELECT sqlite_detach(x)\n*/\nstatic void detachFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **argv\n){\n  const char *zName = (const char *)sqlite3_value_text(argv[0]);\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  int i;\n  Db *pDb = 0;\n  HashElem *pEntry;\n  char zErr[128];\n\n  UNUSED_PARAMETER(NotUsed);\n\n  if( zName==0 ) zName = \"\";\n  for(i=0; i<db->nDb; i++){\n    pDb = &db->aDb[i];\n    if( pDb->pBt==0 ) continue;\n    if( sqlite3DbIsNamed(db, i, zName) ) break;\n  }\n\n  if( i>=db->nDb ){\n    sqlite3_snprintf(sizeof(zErr),zErr, \"no such database: %s\", zName);\n    goto detach_error;\n  }\n  if( i<2 ){\n    sqlite3_snprintf(sizeof(zErr),zErr, \"cannot detach database %s\", zName);\n    goto detach_error;\n  }\n  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){\n    sqlite3_snprintf(sizeof(zErr),zErr, \"database %s is locked\", zName);\n    goto detach_error;\n  }\n\n  /* If any TEMP triggers reference the schema being detached, move those\n  ** triggers to reference the TEMP schema itself. */\n  assert( db->aDb[1].pSchema );\n  pEntry = sqliteHashFirst(&db->aDb[1].pSchema->trigHash);\n  while( pEntry ){\n    Trigger *pTrig = (Trigger*)sqliteHashData(pEntry);\n    if( pTrig->pTabSchema==pDb->pSchema ){\n      pTrig->pTabSchema = pTrig->pSchema;\n    }\n    pEntry = sqliteHashNext(pEntry);\n  }\n\n  sqlite3BtreeClose(pDb->pBt);\n  pDb->pBt = 0;\n  pDb->pSchema = 0;\n  sqlite3CollapseDatabaseArray(db);\n  return;\n\ndetach_error:\n  sqlite3_result_error(context, zErr, -1);\n}\n\n/*\n** This procedure generates VDBE code for a single invocation of either the\n** sqlite_detach() or sqlite_attach() SQL user functions.\n*/\nstatic void codeAttach(\n  Parse *pParse,       /* The parser context */\n  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */\n  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */\n  Expr *pAuthArg,      /* Expression to pass to authorization callback */\n  Expr *pFilename,     /* Name of database file */\n  Expr *pDbname,       /* Name of the database to use internally */\n  Expr *pKey           /* Database key for encryption extension */\n){\n  int rc;\n  NameContext sName;\n  Vdbe *v;\n  sqlite3* db = pParse->db;\n  int regArgs;\n\n  if( pParse->nErr ) goto attach_end;\n  memset(&sName, 0, sizeof(NameContext));\n  sName.pParse = pParse;\n\n  if( \n      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||\n      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||\n      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))\n  ){\n    goto attach_end;\n  }\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  if( pAuthArg ){\n    char *zAuthArg;\n    if( pAuthArg->op==TK_STRING ){\n      zAuthArg = pAuthArg->u.zToken;\n    }else{\n      zAuthArg = 0;\n    }\n    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);\n    if(rc!=SQLITE_OK ){\n      goto attach_end;\n    }\n  }\n#endif /* SQLITE_OMIT_AUTHORIZATION */\n\n\n  v = sqlite3GetVdbe(pParse);\n  regArgs = sqlite3GetTempRange(pParse, 4);\n  sqlite3ExprCode(pParse, pFilename, regArgs);\n  sqlite3ExprCode(pParse, pDbname, regArgs+1);\n  sqlite3ExprCode(pParse, pKey, regArgs+2);\n\n  assert( v || db->mallocFailed );\n  if( v ){\n    sqlite3VdbeAddFunctionCall(pParse, 0, regArgs+3-pFunc->nArg, regArgs+3,\n                               pFunc->nArg, pFunc, 0);\n    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this\n    ** statement only). For DETACH, set it to false (expire all existing\n    ** statements).\n    */\n    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));\n  }\n  \nattach_end:\n  sqlite3ExprDelete(db, pFilename);\n  sqlite3ExprDelete(db, pDbname);\n  sqlite3ExprDelete(db, pKey);\n}\n\n/*\n** Called by the parser to compile a DETACH statement.\n**\n**     DETACH pDbname\n*/\nSQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){\n  static const FuncDef detach_func = {\n    1,                /* nArg */\n    SQLITE_UTF8,      /* funcFlags */\n    0,                /* pUserData */\n    0,                /* pNext */\n    detachFunc,       /* xSFunc */\n    0,                /* xFinalize */\n    0, 0,             /* xValue, xInverse */\n    \"sqlite_detach\",  /* zName */\n    {0}\n  };\n  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);\n}\n\n/*\n** Called by the parser to compile an ATTACH statement.\n**\n**     ATTACH p AS pDbname KEY pKey\n*/\nSQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){\n  static const FuncDef attach_func = {\n    3,                /* nArg */\n    SQLITE_UTF8,      /* funcFlags */\n    0,                /* pUserData */\n    0,                /* pNext */\n    attachFunc,       /* xSFunc */\n    0,                /* xFinalize */\n    0, 0,             /* xValue, xInverse */\n    \"sqlite_attach\",  /* zName */\n    {0}\n  };\n  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);\n}\n#endif /* SQLITE_OMIT_ATTACH */\n\n/*\n** Initialize a DbFixer structure.  This routine must be called prior\n** to passing the structure to one of the sqliteFixAAAA() routines below.\n*/\nSQLITE_PRIVATE void sqlite3FixInit(\n  DbFixer *pFix,      /* The fixer to be initialized */\n  Parse *pParse,      /* Error messages will be written here */\n  int iDb,            /* This is the database that must be used */\n  const char *zType,  /* \"view\", \"trigger\", or \"index\" */\n  const Token *pName  /* Name of the view, trigger, or index */\n){\n  sqlite3 *db;\n\n  db = pParse->db;\n  assert( db->nDb>iDb );\n  pFix->pParse = pParse;\n  pFix->zDb = db->aDb[iDb].zDbSName;\n  pFix->pSchema = db->aDb[iDb].pSchema;\n  pFix->zType = zType;\n  pFix->pName = pName;\n  pFix->bTemp = (iDb==1);\n}\n\n/*\n** The following set of routines walk through the parse tree and assign\n** a specific database to all table references where the database name\n** was left unspecified in the original SQL statement.  The pFix structure\n** must have been initialized by a prior call to sqlite3FixInit().\n**\n** These routines are used to make sure that an index, trigger, or\n** view in one database does not refer to objects in a different database.\n** (Exception: indices, triggers, and views in the TEMP database are\n** allowed to refer to anything.)  If a reference is explicitly made\n** to an object in a different database, an error message is added to\n** pParse->zErrMsg and these routines return non-zero.  If everything\n** checks out, these routines return 0.\n*/\nSQLITE_PRIVATE int sqlite3FixSrcList(\n  DbFixer *pFix,       /* Context of the fixation */\n  SrcList *pList       /* The Source list to check and modify */\n){\n  int i;\n  struct SrcList_item *pItem;\n  sqlite3 *db = pFix->pParse->db;\n  int iDb = sqlite3FindDbName(db, pFix->zDb);\n\n  if( NEVER(pList==0) ) return 0;\n\n  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){\n    if( pFix->bTemp==0 ){\n      if( pItem->zDatabase && iDb!=sqlite3FindDbName(db, pItem->zDatabase) ){\n        sqlite3ErrorMsg(pFix->pParse,\n            \"%s %T cannot reference objects in database %s\",\n            pFix->zType, pFix->pName, pItem->zDatabase);\n        return 1;\n      }\n      sqlite3DbFree(db, pItem->zDatabase);\n      pItem->zDatabase = 0;\n      pItem->pSchema = pFix->pSchema;\n      pItem->fg.fromDDL = 1;\n    }\n#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)\n    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;\n    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;\n#endif\n    if( pItem->fg.isTabFunc && sqlite3FixExprList(pFix, pItem->u1.pFuncArg) ){\n      return 1;\n    }\n  }\n  return 0;\n}\n#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)\nSQLITE_PRIVATE int sqlite3FixSelect(\n  DbFixer *pFix,       /* Context of the fixation */\n  Select *pSelect      /* The SELECT statement to be fixed to one database */\n){\n  while( pSelect ){\n    if( sqlite3FixExprList(pFix, pSelect->pEList) ){\n      return 1;\n    }\n    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){\n      return 1;\n    }\n    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){\n      return 1;\n    }\n    if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){\n      return 1;\n    }\n    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){\n      return 1;\n    }\n    if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){\n      return 1;\n    }\n    if( sqlite3FixExpr(pFix, pSelect->pLimit) ){\n      return 1;\n    }\n    if( pSelect->pWith ){\n      int i;\n      for(i=0; i<pSelect->pWith->nCte; i++){\n        if( sqlite3FixSelect(pFix, pSelect->pWith->a[i].pSelect) ){\n          return 1;\n        }\n      }\n    }\n    pSelect = pSelect->pPrior;\n  }\n  return 0;\n}\nSQLITE_PRIVATE int sqlite3FixExpr(\n  DbFixer *pFix,     /* Context of the fixation */\n  Expr *pExpr        /* The expression to be fixed to one database */\n){\n  while( pExpr ){\n    if( !pFix->bTemp ) ExprSetProperty(pExpr, EP_FromDDL);\n    if( pExpr->op==TK_VARIABLE ){\n      if( pFix->pParse->db->init.busy ){\n        pExpr->op = TK_NULL;\n      }else{\n        sqlite3ErrorMsg(pFix->pParse, \"%s cannot use variables\", pFix->zType);\n        return 1;\n      }\n    }\n    if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;\n    if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;\n    }else{\n      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;\n    }\n    if( sqlite3FixExpr(pFix, pExpr->pRight) ){\n      return 1;\n    }\n    pExpr = pExpr->pLeft;\n  }\n  return 0;\n}\nSQLITE_PRIVATE int sqlite3FixExprList(\n  DbFixer *pFix,     /* Context of the fixation */\n  ExprList *pList    /* The expression to be fixed to one database */\n){\n  int i;\n  struct ExprList_item *pItem;\n  if( pList==0 ) return 0;\n  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){\n    if( sqlite3FixExpr(pFix, pItem->pExpr) ){\n      return 1;\n    }\n  }\n  return 0;\n}\n#endif\n\n#ifndef SQLITE_OMIT_TRIGGER\nSQLITE_PRIVATE int sqlite3FixTriggerStep(\n  DbFixer *pFix,     /* Context of the fixation */\n  TriggerStep *pStep /* The trigger step be fixed to one database */\n){\n  while( pStep ){\n    if( sqlite3FixSelect(pFix, pStep->pSelect) ){\n      return 1;\n    }\n    if( sqlite3FixExpr(pFix, pStep->pWhere) ){\n      return 1;\n    }\n    if( sqlite3FixExprList(pFix, pStep->pExprList) ){\n      return 1;\n    }\n#ifndef SQLITE_OMIT_UPSERT\n    if( pStep->pUpsert ){\n      Upsert *pUp = pStep->pUpsert;\n      if( sqlite3FixExprList(pFix, pUp->pUpsertTarget)\n       || sqlite3FixExpr(pFix, pUp->pUpsertTargetWhere)\n       || sqlite3FixExprList(pFix, pUp->pUpsertSet)\n       || sqlite3FixExpr(pFix, pUp->pUpsertWhere)\n      ){\n        return 1;\n      }\n    }\n#endif\n    pStep = pStep->pNext;\n  }\n  return 0;\n}\n#endif\n\n/************** End of attach.c **********************************************/\n/************** Begin file auth.c ********************************************/\n/*\n** 2003 January 11\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code used to implement the sqlite3_set_authorizer()\n** API.  This facility is an optional feature of the library.  Embedded\n** systems that do not need this facility may omit it by recompiling\n** the library with -DSQLITE_OMIT_AUTHORIZATION=1\n*/\n/* #include \"sqliteInt.h\" */\n\n/*\n** All of the code in this file may be omitted by defining a single\n** macro.\n*/\n#ifndef SQLITE_OMIT_AUTHORIZATION\n\n/*\n** Set or clear the access authorization function.\n**\n** The access authorization function is be called during the compilation\n** phase to verify that the user has read and/or write access permission on\n** various fields of the database.  The first argument to the auth function\n** is a copy of the 3rd argument to this routine.  The second argument\n** to the auth function is one of these constants:\n**\n**       SQLITE_CREATE_INDEX\n**       SQLITE_CREATE_TABLE\n**       SQLITE_CREATE_TEMP_INDEX\n**       SQLITE_CREATE_TEMP_TABLE\n**       SQLITE_CREATE_TEMP_TRIGGER\n**       SQLITE_CREATE_TEMP_VIEW\n**       SQLITE_CREATE_TRIGGER\n**       SQLITE_CREATE_VIEW\n**       SQLITE_DELETE\n**       SQLITE_DROP_INDEX\n**       SQLITE_DROP_TABLE\n**       SQLITE_DROP_TEMP_INDEX\n**       SQLITE_DROP_TEMP_TABLE\n**       SQLITE_DROP_TEMP_TRIGGER\n**       SQLITE_DROP_TEMP_VIEW\n**       SQLITE_DROP_TRIGGER\n**       SQLITE_DROP_VIEW\n**       SQLITE_INSERT\n**       SQLITE_PRAGMA\n**       SQLITE_READ\n**       SQLITE_SELECT\n**       SQLITE_TRANSACTION\n**       SQLITE_UPDATE\n**\n** The third and fourth arguments to the auth function are the name of\n** the table and the column that are being accessed.  The auth function\n** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If\n** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY\n** means that the SQL statement will never-run - the sqlite3_exec() call\n** will return with an error.  SQLITE_IGNORE means that the SQL statement\n** should run but attempts to read the specified column will return NULL\n** and attempts to write the column will be ignored.\n**\n** Setting the auth function to NULL disables this hook.  The default\n** setting of the auth function is NULL.\n*/\nSQLITE_API int sqlite3_set_authorizer(\n  sqlite3 *db,\n  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),\n  void *pArg\n){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  db->xAuth = (sqlite3_xauth)xAuth;\n  db->pAuthArg = pArg;\n  if( db->xAuth ) sqlite3ExpirePreparedStatements(db, 1);\n  sqlite3_mutex_leave(db->mutex);\n  return SQLITE_OK;\n}\n\n/*\n** Write an error message into pParse->zErrMsg that explains that the\n** user-supplied authorization function returned an illegal value.\n*/\nstatic void sqliteAuthBadReturnCode(Parse *pParse){\n  sqlite3ErrorMsg(pParse, \"authorizer malfunction\");\n  pParse->rc = SQLITE_ERROR;\n}\n\n/*\n** Invoke the authorization callback for permission to read column zCol from\n** table zTab in database zDb. This function assumes that an authorization\n** callback has been registered (i.e. that sqlite3.xAuth is not NULL).\n**\n** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed\n** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE\n** is treated as SQLITE_DENY. In this case an error is left in pParse.\n*/\nSQLITE_PRIVATE int sqlite3AuthReadCol(\n  Parse *pParse,                  /* The parser context */\n  const char *zTab,               /* Table name */\n  const char *zCol,               /* Column name */\n  int iDb                         /* Index of containing database. */\n){\n  sqlite3 *db = pParse->db;          /* Database handle */\n  char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */\n  int rc;                            /* Auth callback return code */\n\n  if( db->init.busy ) return SQLITE_OK;\n  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext\n#ifdef SQLITE_USER_AUTHENTICATION\n                 ,db->auth.zAuthUser\n#endif\n                );\n  if( rc==SQLITE_DENY ){\n    char *z = sqlite3_mprintf(\"%s.%s\", zTab, zCol);\n    if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf(\"%s.%z\", zDb, z);\n    sqlite3ErrorMsg(pParse, \"access to %z is prohibited\", z);\n    pParse->rc = SQLITE_AUTH;\n  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){\n    sqliteAuthBadReturnCode(pParse);\n  }\n  return rc;\n}\n\n/*\n** The pExpr should be a TK_COLUMN expression.  The table referred to\n** is in pTabList or else it is the NEW or OLD table of a trigger.  \n** Check to see if it is OK to read this particular column.\n**\n** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN \n** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,\n** then generate an error.\n*/\nSQLITE_PRIVATE void sqlite3AuthRead(\n  Parse *pParse,        /* The parser context */\n  Expr *pExpr,          /* The expression to check authorization on */\n  Schema *pSchema,      /* The schema of the expression */\n  SrcList *pTabList     /* All table that pExpr might refer to */\n){\n  sqlite3 *db = pParse->db;\n  Table *pTab = 0;      /* The table being read */\n  const char *zCol;     /* Name of the column of the table */\n  int iSrc;             /* Index in pTabList->a[] of table being read */\n  int iDb;              /* The index of the database the expression refers to */\n  int iCol;             /* Index of column in table */\n\n  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );\n  assert( !IN_RENAME_OBJECT || db->xAuth==0 );\n  if( db->xAuth==0 ) return;\n  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);\n  if( iDb<0 ){\n    /* An attempt to read a column out of a subquery or other\n    ** temporary table. */\n    return;\n  }\n\n  if( pExpr->op==TK_TRIGGER ){\n    pTab = pParse->pTriggerTab;\n  }else{\n    assert( pTabList );\n    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){\n      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){\n        pTab = pTabList->a[iSrc].pTab;\n        break;\n      }\n    }\n  }\n  iCol = pExpr->iColumn;\n  if( NEVER(pTab==0) ) return;\n\n  if( iCol>=0 ){\n    assert( iCol<pTab->nCol );\n    zCol = pTab->aCol[iCol].zName;\n  }else if( pTab->iPKey>=0 ){\n    assert( pTab->iPKey<pTab->nCol );\n    zCol = pTab->aCol[pTab->iPKey].zName;\n  }else{\n    zCol = \"ROWID\";\n  }\n  assert( iDb>=0 && iDb<db->nDb );\n  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){\n    pExpr->op = TK_NULL;\n  }\n}\n\n/*\n** Do an authorization check using the code and arguments given.  Return\n** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY\n** is returned, then the error count and error message in pParse are\n** modified appropriately.\n*/\nSQLITE_PRIVATE int sqlite3AuthCheck(\n  Parse *pParse,\n  int code,\n  const char *zArg1,\n  const char *zArg2,\n  const char *zArg3\n){\n  sqlite3 *db = pParse->db;\n  int rc;\n\n  /* Don't do any authorization checks if the database is initialising\n  ** or if the parser is being invoked from within sqlite3_declare_vtab.\n  */\n  assert( !IN_RENAME_OBJECT || db->xAuth==0 );\n  if( db->init.busy || IN_SPECIAL_PARSE ){\n    return SQLITE_OK;\n  }\n\n  if( db->xAuth==0 ){\n    return SQLITE_OK;\n  }\n\n  /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the\n  ** callback are either NULL pointers or zero-terminated strings that\n  ** contain additional details about the action to be authorized.\n  **\n  ** The following testcase() macros show that any of the 3rd through 6th\n  ** parameters can be either NULL or a string. */\n  testcase( zArg1==0 );\n  testcase( zArg2==0 );\n  testcase( zArg3==0 );\n  testcase( pParse->zAuthContext==0 );\n\n  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext\n#ifdef SQLITE_USER_AUTHENTICATION\n                 ,db->auth.zAuthUser\n#endif\n                );\n  if( rc==SQLITE_DENY ){\n    sqlite3ErrorMsg(pParse, \"not authorized\");\n    pParse->rc = SQLITE_AUTH;\n  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){\n    rc = SQLITE_DENY;\n    sqliteAuthBadReturnCode(pParse);\n  }\n  return rc;\n}\n\n/*\n** Push an authorization context.  After this routine is called, the\n** zArg3 argument to authorization callbacks will be zContext until\n** popped.  Or if pParse==0, this routine is a no-op.\n*/\nSQLITE_PRIVATE void sqlite3AuthContextPush(\n  Parse *pParse,\n  AuthContext *pContext, \n  const char *zContext\n){\n  assert( pParse );\n  pContext->pParse = pParse;\n  pContext->zAuthContext = pParse->zAuthContext;\n  pParse->zAuthContext = zContext;\n}\n\n/*\n** Pop an authorization context that was previously pushed\n** by sqlite3AuthContextPush\n*/\nSQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){\n  if( pContext->pParse ){\n    pContext->pParse->zAuthContext = pContext->zAuthContext;\n    pContext->pParse = 0;\n  }\n}\n\n#endif /* SQLITE_OMIT_AUTHORIZATION */\n\n/************** End of auth.c ************************************************/\n/************** Begin file build.c *******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains C code routines that are called by the SQLite parser\n** when syntax rules are reduced.  The routines in this file handle the\n** following kinds of SQL syntax:\n**\n**     CREATE TABLE\n**     DROP TABLE\n**     CREATE INDEX\n**     DROP INDEX\n**     creating ID lists\n**     BEGIN TRANSACTION\n**     COMMIT\n**     ROLLBACK\n*/\n/* #include \"sqliteInt.h\" */\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n/*\n** The TableLock structure is only used by the sqlite3TableLock() and\n** codeTableLocks() functions.\n*/\nstruct TableLock {\n  int iDb;               /* The database containing the table to be locked */\n  int iTab;              /* The root page of the table to be locked */\n  u8 isWriteLock;        /* True for write lock.  False for a read lock */\n  const char *zLockName; /* Name of the table */\n};\n\n/*\n** Record the fact that we want to lock a table at run-time.  \n**\n** The table to be locked has root page iTab and is found in database iDb.\n** A read or a write lock can be taken depending on isWritelock.\n**\n** This routine just records the fact that the lock is desired.  The\n** code to make the lock occur is generated by a later call to\n** codeTableLocks() which occurs during sqlite3FinishCoding().\n*/\nSQLITE_PRIVATE void sqlite3TableLock(\n  Parse *pParse,     /* Parsing context */\n  int iDb,           /* Index of the database containing the table to lock */\n  int iTab,          /* Root page number of the table to be locked */\n  u8 isWriteLock,    /* True for a write lock */\n  const char *zName  /* Name of the table to be locked */\n){\n  Parse *pToplevel = sqlite3ParseToplevel(pParse);\n  int i;\n  int nBytes;\n  TableLock *p;\n  assert( iDb>=0 );\n\n  if( iDb==1 ) return;\n  if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;\n  for(i=0; i<pToplevel->nTableLock; i++){\n    p = &pToplevel->aTableLock[i];\n    if( p->iDb==iDb && p->iTab==iTab ){\n      p->isWriteLock = (p->isWriteLock || isWriteLock);\n      return;\n    }\n  }\n\n  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);\n  pToplevel->aTableLock =\n      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);\n  if( pToplevel->aTableLock ){\n    p = &pToplevel->aTableLock[pToplevel->nTableLock++];\n    p->iDb = iDb;\n    p->iTab = iTab;\n    p->isWriteLock = isWriteLock;\n    p->zLockName = zName;\n  }else{\n    pToplevel->nTableLock = 0;\n    sqlite3OomFault(pToplevel->db);\n  }\n}\n\n/*\n** Code an OP_TableLock instruction for each table locked by the\n** statement (configured by calls to sqlite3TableLock()).\n*/\nstatic void codeTableLocks(Parse *pParse){\n  int i;\n  Vdbe *pVdbe; \n\n  pVdbe = sqlite3GetVdbe(pParse);\n  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */\n\n  for(i=0; i<pParse->nTableLock; i++){\n    TableLock *p = &pParse->aTableLock[i];\n    int p1 = p->iDb;\n    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,\n                      p->zLockName, P4_STATIC);\n  }\n}\n#else\n  #define codeTableLocks(x)\n#endif\n\n/*\n** Return TRUE if the given yDbMask object is empty - if it contains no\n** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()\n** macros when SQLITE_MAX_ATTACHED is greater than 30.\n*/\n#if SQLITE_MAX_ATTACHED>30\nSQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){\n  int i;\n  for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;\n  return 1;\n}\n#endif\n\n/*\n** This routine is called after a single SQL statement has been\n** parsed and a VDBE program to execute that statement has been\n** prepared.  This routine puts the finishing touches on the\n** VDBE program and resets the pParse structure for the next\n** parse.\n**\n** Note that if an error occurred, it might be the case that\n** no VDBE code was generated.\n*/\nSQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){\n  sqlite3 *db;\n  Vdbe *v;\n\n  assert( pParse->pToplevel==0 );\n  db = pParse->db;\n  if( pParse->nested ) return;\n  if( db->mallocFailed || pParse->nErr ){\n    if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;\n    return;\n  }\n\n  /* Begin by generating some termination code at the end of the\n  ** vdbe program\n  */\n  v = sqlite3GetVdbe(pParse);\n  assert( !pParse->isMultiWrite \n       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));\n  if( v ){\n    sqlite3VdbeAddOp0(v, OP_Halt);\n\n#if SQLITE_USER_AUTHENTICATION\n    if( pParse->nTableLock>0 && db->init.busy==0 ){\n      sqlite3UserAuthInit(db);\n      if( db->auth.authLevel<UAUTH_User ){\n        sqlite3ErrorMsg(pParse, \"user not authenticated\");\n        pParse->rc = SQLITE_AUTH_USER;\n        return;\n      }\n    }\n#endif\n\n    /* The cookie mask contains one bit for each database file open.\n    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are\n    ** set for each database that is used.  Generate code to start a\n    ** transaction on each used database and to verify the schema cookie\n    ** on each used database.\n    */\n    if( db->mallocFailed==0 \n     && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)\n    ){\n      int iDb, i;\n      assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );\n      sqlite3VdbeJumpHere(v, 0);\n      for(iDb=0; iDb<db->nDb; iDb++){\n        Schema *pSchema;\n        if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;\n        sqlite3VdbeUsesBtree(v, iDb);\n        pSchema = db->aDb[iDb].pSchema;\n        sqlite3VdbeAddOp4Int(v,\n          OP_Transaction,                    /* Opcode */\n          iDb,                               /* P1 */\n          DbMaskTest(pParse->writeMask,iDb), /* P2 */\n          pSchema->schema_cookie,            /* P3 */\n          pSchema->iGeneration               /* P4 */\n        );\n        if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);\n        VdbeComment((v,\n              \"usesStmtJournal=%d\", pParse->mayAbort && pParse->isMultiWrite));\n      }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n      for(i=0; i<pParse->nVtabLock; i++){\n        char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);\n        sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);\n      }\n      pParse->nVtabLock = 0;\n#endif\n\n      /* Once all the cookies have been verified and transactions opened, \n      ** obtain the required table-locks. This is a no-op unless the \n      ** shared-cache feature is enabled.\n      */\n      codeTableLocks(pParse);\n\n      /* Initialize any AUTOINCREMENT data structures required.\n      */\n      sqlite3AutoincrementBegin(pParse);\n\n      /* Code constant expressions that where factored out of inner loops.\n      **\n      ** The pConstExpr list might also contain expressions that we simply\n      ** want to keep around until the Parse object is deleted.  Such\n      ** expressions have iConstExprReg==0.  Do not generate code for\n      ** those expressions, of course.\n      */\n      if( pParse->pConstExpr ){\n        ExprList *pEL = pParse->pConstExpr;\n        pParse->okConstFactor = 0;\n        for(i=0; i<pEL->nExpr; i++){\n          int iReg = pEL->a[i].u.iConstExprReg;\n          if( iReg>0 ){\n            sqlite3ExprCode(pParse, pEL->a[i].pExpr, iReg);\n          }\n        }\n      }\n\n      /* Finally, jump back to the beginning of the executable code. */\n      sqlite3VdbeGoto(v, 1);\n    }\n  }\n\n\n  /* Get the VDBE program ready for execution\n  */\n  if( v && pParse->nErr==0 && !db->mallocFailed ){\n    /* A minimum of one cursor is required if autoincrement is used\n    *  See ticket [a696379c1f08866] */\n    assert( pParse->pAinc==0 || pParse->nTab>0 );\n    sqlite3VdbeMakeReady(v, pParse);\n    pParse->rc = SQLITE_DONE;\n  }else{\n    pParse->rc = SQLITE_ERROR;\n  }\n}\n\n/*\n** Run the parser and code generator recursively in order to generate\n** code for the SQL statement given onto the end of the pParse context\n** currently under construction.  When the parser is run recursively\n** this way, the final OP_Halt is not appended and other initialization\n** and finalization steps are omitted because those are handling by the\n** outermost parser.\n**\n** Not everything is nestable.  This facility is designed to permit\n** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use\n** care if you decide to try to use this routine for some other purposes.\n*/\nSQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){\n  va_list ap;\n  char *zSql;\n  char *zErrMsg = 0;\n  sqlite3 *db = pParse->db;\n  char saveBuf[PARSE_TAIL_SZ];\n\n  if( pParse->nErr ) return;\n  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */\n  va_start(ap, zFormat);\n  zSql = sqlite3VMPrintf(db, zFormat, ap);\n  va_end(ap);\n  if( zSql==0 ){\n    /* This can result either from an OOM or because the formatted string\n    ** exceeds SQLITE_LIMIT_LENGTH.  In the latter case, we need to set\n    ** an error */\n    if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;\n    pParse->nErr++;\n    return;\n  }\n  pParse->nested++;\n  memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);\n  memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);\n  sqlite3RunParser(pParse, zSql, &zErrMsg);\n  sqlite3DbFree(db, zErrMsg);\n  sqlite3DbFree(db, zSql);\n  memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);\n  pParse->nested--;\n}\n\n#if SQLITE_USER_AUTHENTICATION\n/*\n** Return TRUE if zTable is the name of the system table that stores the\n** list of users and their access credentials.\n*/\nSQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){\n  return sqlite3_stricmp(zTable, \"sqlite_user\")==0;\n}\n#endif\n\n/*\n** Locate the in-memory structure that describes a particular database\n** table given the name of that table and (optionally) the name of the\n** database containing the table.  Return NULL if not found.\n**\n** If zDatabase is 0, all databases are searched for the table and the\n** first matching table is returned.  (No checking for duplicate table\n** names is done.)  The search order is TEMP first, then MAIN, then any\n** auxiliary databases added using the ATTACH command.\n**\n** See also sqlite3LocateTable().\n*/\nSQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){\n  Table *p = 0;\n  int i;\n\n  /* All mutexes are required for schema access.  Make sure we hold them. */\n  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );\n#if SQLITE_USER_AUTHENTICATION\n  /* Only the admin user is allowed to know that the sqlite_user table\n  ** exists */\n  if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){\n    return 0;\n  }\n#endif\n  if( zDatabase ){\n    for(i=0; i<db->nDb; i++){\n      if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break;\n    }\n    if( i>=db->nDb ){\n      /* No match against the official names.  But always match \"main\"\n      ** to schema 0 as a legacy fallback. */\n      if( sqlite3StrICmp(zDatabase,\"main\")==0 ){\n        i = 0;\n      }else{\n        return 0;\n      }\n    }\n    p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);\n    if( p==0 && i==1 && sqlite3StrICmp(zName, MASTER_NAME)==0 ){\n      /* All temp.sqlite_master to be an alias for sqlite_temp_master */\n      p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, TEMP_MASTER_NAME);\n    }\n  }else{\n    /* Match against TEMP first */\n    p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName);\n    if( p ) return p;\n    /* The main database is second */\n    p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName);\n    if( p ) return p;\n    /* Attached databases are in order of attachment */\n    for(i=2; i<db->nDb; i++){\n      assert( sqlite3SchemaMutexHeld(db, i, 0) );\n      p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);\n      if( p ) break;\n    }\n  }\n  return p;\n}\n\n/*\n** Locate the in-memory structure that describes a particular database\n** table given the name of that table and (optionally) the name of the\n** database containing the table.  Return NULL if not found.  Also leave an\n** error message in pParse->zErrMsg.\n**\n** The difference between this routine and sqlite3FindTable() is that this\n** routine leaves an error message in pParse->zErrMsg where\n** sqlite3FindTable() does not.\n*/\nSQLITE_PRIVATE Table *sqlite3LocateTable(\n  Parse *pParse,         /* context in which to report errors */\n  u32 flags,             /* LOCATE_VIEW or LOCATE_NOERR */\n  const char *zName,     /* Name of the table we are looking for */\n  const char *zDbase     /* Name of the database.  Might be NULL */\n){\n  Table *p;\n  sqlite3 *db = pParse->db;\n\n  /* Read the database schema. If an error occurs, leave an error message\n  ** and code in pParse and return NULL. */\n  if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 \n   && SQLITE_OK!=sqlite3ReadSchema(pParse)\n  ){\n    return 0;\n  }\n\n  p = sqlite3FindTable(db, zName, zDbase);\n  if( p==0 ){\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    /* If zName is the not the name of a table in the schema created using\n    ** CREATE, then check to see if it is the name of an virtual table that\n    ** can be an eponymous virtual table. */\n    if( pParse->disableVtab==0 ){\n      Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);\n      if( pMod==0 && sqlite3_strnicmp(zName, \"pragma_\", 7)==0 ){\n        pMod = sqlite3PragmaVtabRegister(db, zName);\n      }\n      if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){\n        return pMod->pEpoTab;\n      }\n    }\n#endif\n    if( flags & LOCATE_NOERR ) return 0;\n    pParse->checkSchema = 1;\n  }else if( IsVirtual(p) && pParse->disableVtab ){\n    p = 0;\n  }\n\n  if( p==0 ){\n    const char *zMsg = flags & LOCATE_VIEW ? \"no such view\" : \"no such table\";\n    if( zDbase ){\n      sqlite3ErrorMsg(pParse, \"%s: %s.%s\", zMsg, zDbase, zName);\n    }else{\n      sqlite3ErrorMsg(pParse, \"%s: %s\", zMsg, zName);\n    }\n  }\n\n  return p;\n}\n\n/*\n** Locate the table identified by *p.\n**\n** This is a wrapper around sqlite3LocateTable(). The difference between\n** sqlite3LocateTable() and this function is that this function restricts\n** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be\n** non-NULL if it is part of a view or trigger program definition. See\n** sqlite3FixSrcList() for details.\n*/\nSQLITE_PRIVATE Table *sqlite3LocateTableItem(\n  Parse *pParse, \n  u32 flags,\n  struct SrcList_item *p\n){\n  const char *zDb;\n  assert( p->pSchema==0 || p->zDatabase==0 );\n  if( p->pSchema ){\n    int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);\n    zDb = pParse->db->aDb[iDb].zDbSName;\n  }else{\n    zDb = p->zDatabase;\n  }\n  return sqlite3LocateTable(pParse, flags, p->zName, zDb);\n}\n\n/*\n** Locate the in-memory structure that describes \n** a particular index given the name of that index\n** and the name of the database that contains the index.\n** Return NULL if not found.\n**\n** If zDatabase is 0, all databases are searched for the\n** table and the first matching index is returned.  (No checking\n** for duplicate index names is done.)  The search order is\n** TEMP first, then MAIN, then any auxiliary databases added\n** using the ATTACH command.\n*/\nSQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){\n  Index *p = 0;\n  int i;\n  /* All mutexes are required for schema access.  Make sure we hold them. */\n  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );\n  for(i=OMIT_TEMPDB; i<db->nDb; i++){\n    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */\n    Schema *pSchema = db->aDb[j].pSchema;\n    assert( pSchema );\n    if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;\n    assert( sqlite3SchemaMutexHeld(db, j, 0) );\n    p = sqlite3HashFind(&pSchema->idxHash, zName);\n    if( p ) break;\n  }\n  return p;\n}\n\n/*\n** Reclaim the memory used by an index\n*/\nSQLITE_PRIVATE void sqlite3FreeIndex(sqlite3 *db, Index *p){\n#ifndef SQLITE_OMIT_ANALYZE\n  sqlite3DeleteIndexSamples(db, p);\n#endif\n  sqlite3ExprDelete(db, p->pPartIdxWhere);\n  sqlite3ExprListDelete(db, p->aColExpr);\n  sqlite3DbFree(db, p->zColAff);\n  if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);\n#ifdef SQLITE_ENABLE_STAT4\n  sqlite3_free(p->aiRowEst);\n#endif\n  sqlite3DbFree(db, p);\n}\n\n/*\n** For the index called zIdxName which is found in the database iDb,\n** unlike that index from its Table then remove the index from\n** the index hash table and free all memory structures associated\n** with the index.\n*/\nSQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){\n  Index *pIndex;\n  Hash *pHash;\n\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  pHash = &db->aDb[iDb].pSchema->idxHash;\n  pIndex = sqlite3HashInsert(pHash, zIdxName, 0);\n  if( ALWAYS(pIndex) ){\n    if( pIndex->pTable->pIndex==pIndex ){\n      pIndex->pTable->pIndex = pIndex->pNext;\n    }else{\n      Index *p;\n      /* Justification of ALWAYS();  The index must be on the list of\n      ** indices. */\n      p = pIndex->pTable->pIndex;\n      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }\n      if( ALWAYS(p && p->pNext==pIndex) ){\n        p->pNext = pIndex->pNext;\n      }\n    }\n    sqlite3FreeIndex(db, pIndex);\n  }\n  db->mDbFlags |= DBFLAG_SchemaChange;\n}\n\n/*\n** Look through the list of open database files in db->aDb[] and if\n** any have been closed, remove them from the list.  Reallocate the\n** db->aDb[] structure to a smaller size, if possible.\n**\n** Entry 0 (the \"main\" database) and entry 1 (the \"temp\" database)\n** are never candidates for being collapsed.\n*/\nSQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){\n  int i, j;\n  for(i=j=2; i<db->nDb; i++){\n    struct Db *pDb = &db->aDb[i];\n    if( pDb->pBt==0 ){\n      sqlite3DbFree(db, pDb->zDbSName);\n      pDb->zDbSName = 0;\n      continue;\n    }\n    if( j<i ){\n      db->aDb[j] = db->aDb[i];\n    }\n    j++;\n  }\n  db->nDb = j;\n  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){\n    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));\n    sqlite3DbFree(db, db->aDb);\n    db->aDb = db->aDbStatic;\n  }\n}\n\n/*\n** Reset the schema for the database at index iDb.  Also reset the\n** TEMP schema.  The reset is deferred if db->nSchemaLock is not zero.\n** Deferred resets may be run by calling with iDb<0.\n*/\nSQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){\n  int i;\n  assert( iDb<db->nDb );\n\n  if( iDb>=0 ){\n    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n    DbSetProperty(db, iDb, DB_ResetWanted);\n    DbSetProperty(db, 1, DB_ResetWanted);\n    db->mDbFlags &= ~DBFLAG_SchemaKnownOk;\n  }\n\n  if( db->nSchemaLock==0 ){\n    for(i=0; i<db->nDb; i++){\n      if( DbHasProperty(db, i, DB_ResetWanted) ){\n        sqlite3SchemaClear(db->aDb[i].pSchema);\n      }\n    }\n  }\n}\n\n/*\n** Erase all schema information from all attached databases (including\n** \"main\" and \"temp\") for a single database connection.\n*/\nSQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){\n  int i;\n  sqlite3BtreeEnterAll(db);\n  for(i=0; i<db->nDb; i++){\n    Db *pDb = &db->aDb[i];\n    if( pDb->pSchema ){\n      if( db->nSchemaLock==0 ){\n        sqlite3SchemaClear(pDb->pSchema);\n      }else{\n        DbSetProperty(db, i, DB_ResetWanted);\n      }\n    }\n  }\n  db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);\n  sqlite3VtabUnlockList(db);\n  sqlite3BtreeLeaveAll(db);\n  if( db->nSchemaLock==0 ){\n    sqlite3CollapseDatabaseArray(db);\n  }\n}\n\n/*\n** This routine is called when a commit occurs.\n*/\nSQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){\n  db->mDbFlags &= ~DBFLAG_SchemaChange;\n}\n\n/*\n** Delete memory allocated for the column names of a table or view (the\n** Table.aCol[] array).\n*/\nSQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){\n  int i;\n  Column *pCol;\n  assert( pTable!=0 );\n  if( (pCol = pTable->aCol)!=0 ){\n    for(i=0; i<pTable->nCol; i++, pCol++){\n      assert( pCol->zName==0 || pCol->hName==sqlite3StrIHash(pCol->zName) );\n      sqlite3DbFree(db, pCol->zName);\n      sqlite3ExprDelete(db, pCol->pDflt);\n      sqlite3DbFree(db, pCol->zColl);\n    }\n    sqlite3DbFree(db, pTable->aCol);\n  }\n}\n\n/*\n** Remove the memory data structures associated with the given\n** Table.  No changes are made to disk by this routine.\n**\n** This routine just deletes the data structure.  It does not unlink\n** the table data structure from the hash table.  But it does destroy\n** memory structures of the indices and foreign keys associated with \n** the table.\n**\n** The db parameter is optional.  It is needed if the Table object \n** contains lookaside memory.  (Table objects in the schema do not use\n** lookaside memory, but some ephemeral Table objects do.)  Or the\n** db parameter can be used with db->pnBytesFreed to measure the memory\n** used by the Table object.\n*/\nstatic void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){\n  Index *pIndex, *pNext;\n\n#ifdef SQLITE_DEBUG\n  /* Record the number of outstanding lookaside allocations in schema Tables\n  ** prior to doing any free() operations. Since schema Tables do not use\n  ** lookaside, this number should not change. \n  **\n  ** If malloc has already failed, it may be that it failed while allocating\n  ** a Table object that was going to be marked ephemeral. So do not check\n  ** that no lookaside memory is used in this case either. */\n  int nLookaside = 0;\n  if( db && !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){\n    nLookaside = sqlite3LookasideUsed(db, 0);\n  }\n#endif\n\n  /* Delete all indices associated with this table. */\n  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){\n    pNext = pIndex->pNext;\n    assert( pIndex->pSchema==pTable->pSchema\n         || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );\n    if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){\n      char *zName = pIndex->zName; \n      TESTONLY ( Index *pOld = ) sqlite3HashInsert(\n         &pIndex->pSchema->idxHash, zName, 0\n      );\n      assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );\n      assert( pOld==pIndex || pOld==0 );\n    }\n    sqlite3FreeIndex(db, pIndex);\n  }\n\n  /* Delete any foreign keys attached to this table. */\n  sqlite3FkDelete(db, pTable);\n\n  /* Delete the Table structure itself.\n  */\n  sqlite3DeleteColumnNames(db, pTable);\n  sqlite3DbFree(db, pTable->zName);\n  sqlite3DbFree(db, pTable->zColAff);\n  sqlite3SelectDelete(db, pTable->pSelect);\n  sqlite3ExprListDelete(db, pTable->pCheck);\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  sqlite3VtabClear(db, pTable);\n#endif\n  sqlite3DbFree(db, pTable);\n\n  /* Verify that no lookaside memory was used by schema tables */\n  assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );\n}\nSQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){\n  /* Do not delete the table until the reference count reaches zero. */\n  if( !pTable ) return;\n  if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;\n  deleteTable(db, pTable);\n}\n\n\n/*\n** Unlink the given table from the hash tables and the delete the\n** table structure with all its indices and foreign keys.\n*/\nSQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){\n  Table *p;\n  Db *pDb;\n\n  assert( db!=0 );\n  assert( iDb>=0 && iDb<db->nDb );\n  assert( zTabName );\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */\n  pDb = &db->aDb[iDb];\n  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);\n  sqlite3DeleteTable(db, p);\n  db->mDbFlags |= DBFLAG_SchemaChange;\n}\n\n/*\n** Given a token, return a string that consists of the text of that\n** token.  Space to hold the returned string\n** is obtained from sqliteMalloc() and must be freed by the calling\n** function.\n**\n** Any quotation marks (ex:  \"name\", 'name', [name], or `name`) that\n** surround the body of the token are removed.\n**\n** Tokens are often just pointers into the original SQL text and so\n** are not \\000 terminated and are not persistent.  The returned string\n** is \\000 terminated and is persistent.\n*/\nSQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){\n  char *zName;\n  if( pName ){\n    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);\n    sqlite3Dequote(zName);\n  }else{\n    zName = 0;\n  }\n  return zName;\n}\n\n/*\n** Open the sqlite_master table stored in database number iDb for\n** writing. The table is opened using cursor 0.\n*/\nSQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){\n  Vdbe *v = sqlite3GetVdbe(p);\n  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);\n  sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);\n  if( p->nTab==0 ){\n    p->nTab = 1;\n  }\n}\n\n/*\n** Parameter zName points to a nul-terminated buffer containing the name\n** of a database (\"main\", \"temp\" or the name of an attached db). This\n** function returns the index of the named database in db->aDb[], or\n** -1 if the named db cannot be found.\n*/\nSQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){\n  int i = -1;         /* Database number */\n  if( zName ){\n    Db *pDb;\n    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){\n      if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;\n      /* \"main\" is always an acceptable alias for the primary database\n      ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */\n      if( i==0 && 0==sqlite3_stricmp(\"main\", zName) ) break;\n    }\n  }\n  return i;\n}\n\n/*\n** The token *pName contains the name of a database (either \"main\" or\n** \"temp\" or the name of an attached db). This routine returns the\n** index of the named database in db->aDb[], or -1 if the named db \n** does not exist.\n*/\nSQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){\n  int i;                               /* Database number */\n  char *zName;                         /* Name we are searching for */\n  zName = sqlite3NameFromToken(db, pName);\n  i = sqlite3FindDbName(db, zName);\n  sqlite3DbFree(db, zName);\n  return i;\n}\n\n/* The table or view or trigger name is passed to this routine via tokens\n** pName1 and pName2. If the table name was fully qualified, for example:\n**\n** CREATE TABLE xxx.yyy (...);\n** \n** Then pName1 is set to \"xxx\" and pName2 \"yyy\". On the other hand if\n** the table name is not fully qualified, i.e.:\n**\n** CREATE TABLE yyy(...);\n**\n** Then pName1 is set to \"yyy\" and pName2 is \"\".\n**\n** This routine sets the *ppUnqual pointer to point at the token (pName1 or\n** pName2) that stores the unqualified table name.  The index of the\n** database \"xxx\" is returned.\n*/\nSQLITE_PRIVATE int sqlite3TwoPartName(\n  Parse *pParse,      /* Parsing and code generating context */\n  Token *pName1,      /* The \"xxx\" in the name \"xxx.yyy\" or \"xxx\" */\n  Token *pName2,      /* The \"yyy\" in the name \"xxx.yyy\" */\n  Token **pUnqual     /* Write the unqualified object name here */\n){\n  int iDb;                    /* Database holding the object */\n  sqlite3 *db = pParse->db;\n\n  assert( pName2!=0 );\n  if( pName2->n>0 ){\n    if( db->init.busy ) {\n      sqlite3ErrorMsg(pParse, \"corrupt database\");\n      return -1;\n    }\n    *pUnqual = pName2;\n    iDb = sqlite3FindDb(db, pName1);\n    if( iDb<0 ){\n      sqlite3ErrorMsg(pParse, \"unknown database %T\", pName1);\n      return -1;\n    }\n  }else{\n    assert( db->init.iDb==0 || db->init.busy || IN_RENAME_OBJECT\n             || (db->mDbFlags & DBFLAG_Vacuum)!=0);\n    iDb = db->init.iDb;\n    *pUnqual = pName1;\n  }\n  return iDb;\n}\n\n/*\n** True if PRAGMA writable_schema is ON\n*/\nSQLITE_PRIVATE int sqlite3WritableSchema(sqlite3 *db){\n  testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );\n  testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==\n               SQLITE_WriteSchema );\n  testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==\n               SQLITE_Defensive );\n  testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==\n               (SQLITE_WriteSchema|SQLITE_Defensive) );\n  return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;\n}\n\n/*\n** This routine is used to check if the UTF-8 string zName is a legal\n** unqualified name for a new schema object (table, index, view or\n** trigger). All names are legal except those that begin with the string\n** \"sqlite_\" (in upper, lower or mixed case). This portion of the namespace\n** is reserved for internal use.\n**\n** When parsing the sqlite_master table, this routine also checks to\n** make sure the \"type\", \"name\", and \"tbl_name\" columns are consistent\n** with the SQL.\n*/\nSQLITE_PRIVATE int sqlite3CheckObjectName(\n  Parse *pParse,            /* Parsing context */\n  const char *zName,        /* Name of the object to check */\n  const char *zType,        /* Type of this object */\n  const char *zTblName      /* Parent table name for triggers and indexes */\n){\n  sqlite3 *db = pParse->db;\n  if( sqlite3WritableSchema(db) || db->init.imposterTable ){\n    /* Skip these error checks for writable_schema=ON */\n    return SQLITE_OK;\n  }\n  if( db->init.busy ){\n    if( sqlite3_stricmp(zType, db->init.azInit[0])\n     || sqlite3_stricmp(zName, db->init.azInit[1])\n     || sqlite3_stricmp(zTblName, db->init.azInit[2])\n    ){\n      if( sqlite3Config.bExtraSchemaChecks ){\n        sqlite3ErrorMsg(pParse, \"\"); /* corruptSchema() will supply the error */\n        return SQLITE_ERROR;\n      }\n    }\n  }else{\n    if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, \"sqlite_\", 7))\n     || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))\n    ){\n      sqlite3ErrorMsg(pParse, \"object name reserved for internal use: %s\",\n                      zName);\n      return SQLITE_ERROR;\n    }\n\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Return the PRIMARY KEY index of a table\n*/\nSQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){\n  Index *p;\n  for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}\n  return p;\n}\n\n/*\n** Convert an table column number into a index column number.  That is,\n** for the column iCol in the table (as defined by the CREATE TABLE statement)\n** find the (first) offset of that column in index pIdx.  Or return -1\n** if column iCol is not used in index pIdx.\n*/\nSQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){\n  int i;\n  for(i=0; i<pIdx->nColumn; i++){\n    if( iCol==pIdx->aiColumn[i] ) return i;\n  }\n  return -1;\n}\n\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n/* Convert a storage column number into a table column number.\n**\n** The storage column number (0,1,2,....) is the index of the value\n** as it appears in the record on disk.  The true column number\n** is the index (0,1,2,...) of the column in the CREATE TABLE statement.\n**\n** The storage column number is less than the table column number if\n** and only there are VIRTUAL columns to the left.\n**\n** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.\n*/\nSQLITE_PRIVATE i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){\n  if( pTab->tabFlags & TF_HasVirtual ){\n    int i;\n    for(i=0; i<=iCol; i++){\n      if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;\n    }\n  }\n  return iCol;\n}\n#endif\n\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n/* Convert a table column number into a storage column number.\n**\n** The storage column number (0,1,2,....) is the index of the value\n** as it appears in the record on disk.  Or, if the input column is\n** the N-th virtual column (zero-based) then the storage number is\n** the number of non-virtual columns in the table plus N.  \n**\n** The true column number is the index (0,1,2,...) of the column in\n** the CREATE TABLE statement.\n**\n** If the input column is a VIRTUAL column, then it should not appear\n** in storage.  But the value sometimes is cached in registers that\n** follow the range of registers used to construct storage.  This\n** avoids computing the same VIRTUAL column multiple times, and provides\n** values for use by OP_Param opcodes in triggers.  Hence, if the\n** input column is a VIRTUAL table, put it after all the other columns.\n**\n** In the following, N means \"normal column\", S means STORED, and\n** V means VIRTUAL.  Suppose the CREATE TABLE has columns like this:\n**\n**        CREATE TABLE ex(N,S,V,N,S,V,N,S,V);\n**                     -- 0 1 2 3 4 5 6 7 8\n**\n** Then the mapping from this function is as follows:\n**\n**    INPUTS:     0 1 2 3 4 5 6 7 8\n**    OUTPUTS:    0 1 6 2 3 7 4 5 8\n**\n** So, in other words, this routine shifts all the virtual columns to\n** the end.\n**\n** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and\n** this routine is a no-op macro.  If the pTab does not have any virtual\n** columns, then this routine is no-op that always return iCol.  If iCol\n** is negative (indicating the ROWID column) then this routine return iCol.\n*/\nSQLITE_PRIVATE i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){\n  int i;\n  i16 n;\n  assert( iCol<pTab->nCol );\n  if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;\n  for(i=0, n=0; i<iCol; i++){\n    if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;\n  }\n  if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){\n    /* iCol is a virtual column itself */\n    return pTab->nNVCol + i - n;\n  }else{\n    /* iCol is a normal or stored column */\n    return n;\n  }\n}\n#endif\n\n/*\n** Begin constructing a new table representation in memory.  This is\n** the first of several action routines that get called in response\n** to a CREATE TABLE statement.  In particular, this routine is called\n** after seeing tokens \"CREATE\" and \"TABLE\" and the table name. The isTemp\n** flag is true if the table should be stored in the auxiliary database\n** file instead of in the main database file.  This is normally the case\n** when the \"TEMP\" or \"TEMPORARY\" keyword occurs in between\n** CREATE and TABLE.\n**\n** The new table record is initialized and put in pParse->pNewTable.\n** As more of the CREATE TABLE statement is parsed, additional action\n** routines will be called to add more information to this record.\n** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine\n** is called to complete the construction of the new table record.\n*/\nSQLITE_PRIVATE void sqlite3StartTable(\n  Parse *pParse,   /* Parser context */\n  Token *pName1,   /* First part of the name of the table or view */\n  Token *pName2,   /* Second part of the name of the table or view */\n  int isTemp,      /* True if this is a TEMP table */\n  int isView,      /* True if this is a VIEW */\n  int isVirtual,   /* True if this is a VIRTUAL table */\n  int noErr        /* Do nothing if table already exists */\n){\n  Table *pTable;\n  char *zName = 0; /* The name of the new table */\n  sqlite3 *db = pParse->db;\n  Vdbe *v;\n  int iDb;         /* Database number to create the table in */\n  Token *pName;    /* Unqualified name of the table to create */\n\n  if( db->init.busy && db->init.newTnum==1 ){\n    /* Special case:  Parsing the sqlite_master or sqlite_temp_master schema */\n    iDb = db->init.iDb;\n    zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));\n    pName = pName1;\n  }else{\n    /* The common case */\n    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);\n    if( iDb<0 ) return;\n    if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){\n      /* If creating a temp table, the name may not be qualified. Unless \n      ** the database name is \"temp\" anyway.  */\n      sqlite3ErrorMsg(pParse, \"temporary table name must be unqualified\");\n      return;\n    }\n    if( !OMIT_TEMPDB && isTemp ) iDb = 1;\n    zName = sqlite3NameFromToken(db, pName);\n    if( IN_RENAME_OBJECT ){\n      sqlite3RenameTokenMap(pParse, (void*)zName, pName);\n    }\n  }\n  pParse->sNameToken = *pName;\n  if( zName==0 ) return;\n  if( sqlite3CheckObjectName(pParse, zName, isView?\"view\":\"table\", zName) ){\n    goto begin_table_error;\n  }\n  if( db->init.iDb==1 ) isTemp = 1;\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  assert( isTemp==0 || isTemp==1 );\n  assert( isView==0 || isView==1 );\n  {\n    static const u8 aCode[] = {\n       SQLITE_CREATE_TABLE,\n       SQLITE_CREATE_TEMP_TABLE,\n       SQLITE_CREATE_VIEW,\n       SQLITE_CREATE_TEMP_VIEW\n    };\n    char *zDb = db->aDb[iDb].zDbSName;\n    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){\n      goto begin_table_error;\n    }\n    if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],\n                                       zName, 0, zDb) ){\n      goto begin_table_error;\n    }\n  }\n#endif\n\n  /* Make sure the new table name does not collide with an existing\n  ** index or table name in the same database.  Issue an error message if\n  ** it does. The exception is if the statement being parsed was passed\n  ** to an sqlite3_declare_vtab() call. In that case only the column names\n  ** and types will be used, so there is no need to test for namespace\n  ** collisions.\n  */\n  if( !IN_SPECIAL_PARSE ){\n    char *zDb = db->aDb[iDb].zDbSName;\n    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){\n      goto begin_table_error;\n    }\n    pTable = sqlite3FindTable(db, zName, zDb);\n    if( pTable ){\n      if( !noErr ){\n        sqlite3ErrorMsg(pParse, \"table %T already exists\", pName);\n      }else{\n        assert( !db->init.busy || CORRUPT_DB );\n        sqlite3CodeVerifySchema(pParse, iDb);\n      }\n      goto begin_table_error;\n    }\n    if( sqlite3FindIndex(db, zName, zDb)!=0 ){\n      sqlite3ErrorMsg(pParse, \"there is already an index named %s\", zName);\n      goto begin_table_error;\n    }\n  }\n\n  pTable = sqlite3DbMallocZero(db, sizeof(Table));\n  if( pTable==0 ){\n    assert( db->mallocFailed );\n    pParse->rc = SQLITE_NOMEM_BKPT;\n    pParse->nErr++;\n    goto begin_table_error;\n  }\n  pTable->zName = zName;\n  pTable->iPKey = -1;\n  pTable->pSchema = db->aDb[iDb].pSchema;\n  pTable->nTabRef = 1;\n#ifdef SQLITE_DEFAULT_ROWEST\n  pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);\n#else\n  pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );\n#endif\n  assert( pParse->pNewTable==0 );\n  pParse->pNewTable = pTable;\n\n  /* If this is the magic sqlite_sequence table used by autoincrement,\n  ** then record a pointer to this table in the main database structure\n  ** so that INSERT can find the table easily.\n  */\n#ifndef SQLITE_OMIT_AUTOINCREMENT\n  if( !pParse->nested && strcmp(zName, \"sqlite_sequence\")==0 ){\n    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n    pTable->pSchema->pSeqTab = pTable;\n  }\n#endif\n\n  /* Begin generating the code that will insert the table record into\n  ** the SQLITE_MASTER table.  Note in particular that we must go ahead\n  ** and allocate the record number for the table entry now.  Before any\n  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause\n  ** indices to be created and the table record must come before the \n  ** indices.  Hence, the record number for the table must be allocated\n  ** now.\n  */\n  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){\n    int addr1;\n    int fileFormat;\n    int reg1, reg2, reg3;\n    /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */\n    static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };\n    sqlite3BeginWriteOperation(pParse, 1, iDb);\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    if( isVirtual ){\n      sqlite3VdbeAddOp0(v, OP_VBegin);\n    }\n#endif\n\n    /* If the file format and encoding in the database have not been set, \n    ** set them now.\n    */\n    reg1 = pParse->regRowid = ++pParse->nMem;\n    reg2 = pParse->regRoot = ++pParse->nMem;\n    reg3 = ++pParse->nMem;\n    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);\n    sqlite3VdbeUsesBtree(v, iDb);\n    addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);\n    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?\n                  1 : SQLITE_MAX_FILE_FORMAT;\n    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);\n    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));\n    sqlite3VdbeJumpHere(v, addr1);\n\n    /* This just creates a place-holder record in the sqlite_master table.\n    ** The record created does not contain anything yet.  It will be replaced\n    ** by the real entry in code generated at sqlite3EndTable().\n    **\n    ** The rowid for the new entry is left in register pParse->regRowid.\n    ** The root page number of the new table is left in reg pParse->regRoot.\n    ** The rowid and root page number values are needed by the code that\n    ** sqlite3EndTable will generate.\n    */\n#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)\n    if( isView || isVirtual ){\n      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);\n    }else\n#endif\n    {\n      pParse->addrCrTab =\n         sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);\n    }\n    sqlite3OpenMasterTable(pParse, iDb);\n    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);\n    sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);\n    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);\n    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);\n    sqlite3VdbeAddOp0(v, OP_Close);\n  }\n\n  /* Normal (non-error) return. */\n  return;\n\n  /* If an error occurs, we jump here */\nbegin_table_error:\n  sqlite3DbFree(db, zName);\n  return;\n}\n\n/* Set properties of a table column based on the (magical)\n** name of the column.\n*/\n#if SQLITE_ENABLE_HIDDEN_COLUMNS\nSQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){\n  if( sqlite3_strnicmp(pCol->zName, \"__hidden__\", 10)==0 ){\n    pCol->colFlags |= COLFLAG_HIDDEN;\n  }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){\n    pTab->tabFlags |= TF_OOOHidden;\n  }\n}\n#endif\n\n\n/*\n** Add a new column to the table currently being constructed.\n**\n** The parser calls this routine once for each column declaration\n** in a CREATE TABLE statement.  sqlite3StartTable() gets called\n** first to get things going.  Then this routine is called for each\n** column.\n*/\nSQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){\n  Table *p;\n  int i;\n  char *z;\n  char *zType;\n  Column *pCol;\n  sqlite3 *db = pParse->db;\n  if( (p = pParse->pNewTable)==0 ) return;\n  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){\n    sqlite3ErrorMsg(pParse, \"too many columns on %s\", p->zName);\n    return;\n  }\n  z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);\n  if( z==0 ) return;\n  if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, pName);\n  memcpy(z, pName->z, pName->n);\n  z[pName->n] = 0;\n  sqlite3Dequote(z);\n  for(i=0; i<p->nCol; i++){\n    if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){\n      sqlite3ErrorMsg(pParse, \"duplicate column name: %s\", z);\n      sqlite3DbFree(db, z);\n      return;\n    }\n  }\n  if( (p->nCol & 0x7)==0 ){\n    Column *aNew;\n    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));\n    if( aNew==0 ){\n      sqlite3DbFree(db, z);\n      return;\n    }\n    p->aCol = aNew;\n  }\n  pCol = &p->aCol[p->nCol];\n  memset(pCol, 0, sizeof(p->aCol[0]));\n  pCol->zName = z;\n  pCol->hName = sqlite3StrIHash(z);\n  sqlite3ColumnPropertiesFromName(p, pCol);\n \n  if( pType->n==0 ){\n    /* If there is no type specified, columns have the default affinity\n    ** 'BLOB' with a default size of 4 bytes. */\n    pCol->affinity = SQLITE_AFF_BLOB;\n    pCol->szEst = 1;\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n    if( 4>=sqlite3GlobalConfig.szSorterRef ){\n      pCol->colFlags |= COLFLAG_SORTERREF;\n    }\n#endif\n  }else{\n    zType = z + sqlite3Strlen30(z) + 1;\n    memcpy(zType, pType->z, pType->n);\n    zType[pType->n] = 0;\n    sqlite3Dequote(zType);\n    pCol->affinity = sqlite3AffinityType(zType, pCol);\n    pCol->colFlags |= COLFLAG_HASTYPE;\n  }\n  p->nCol++;\n  p->nNVCol++;\n  pParse->constraintName.n = 0;\n}\n\n/*\n** This routine is called by the parser while in the middle of\n** parsing a CREATE TABLE statement.  A \"NOT NULL\" constraint has\n** been seen on a column.  This routine sets the notNull flag on\n** the column currently under construction.\n*/\nSQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){\n  Table *p;\n  Column *pCol;\n  p = pParse->pNewTable;\n  if( p==0 || NEVER(p->nCol<1) ) return;\n  pCol = &p->aCol[p->nCol-1];\n  pCol->notNull = (u8)onError;\n  p->tabFlags |= TF_HasNotNull;\n\n  /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created\n  ** on this column.  */\n  if( pCol->colFlags & COLFLAG_UNIQUE ){\n    Index *pIdx;\n    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){\n      assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );\n      if( pIdx->aiColumn[0]==p->nCol-1 ){\n        pIdx->uniqNotNull = 1;\n      }\n    }\n  }\n}\n\n/*\n** Scan the column type name zType (length nType) and return the\n** associated affinity type.\n**\n** This routine does a case-independent search of zType for the \n** substrings in the following table. If one of the substrings is\n** found, the corresponding affinity is returned. If zType contains\n** more than one of the substrings, entries toward the top of \n** the table take priority. For example, if zType is 'BLOBINT', \n** SQLITE_AFF_INTEGER is returned.\n**\n** Substring     | Affinity\n** --------------------------------\n** 'INT'         | SQLITE_AFF_INTEGER\n** 'CHAR'        | SQLITE_AFF_TEXT\n** 'CLOB'        | SQLITE_AFF_TEXT\n** 'TEXT'        | SQLITE_AFF_TEXT\n** 'BLOB'        | SQLITE_AFF_BLOB\n** 'REAL'        | SQLITE_AFF_REAL\n** 'FLOA'        | SQLITE_AFF_REAL\n** 'DOUB'        | SQLITE_AFF_REAL\n**\n** If none of the substrings in the above table are found,\n** SQLITE_AFF_NUMERIC is returned.\n*/\nSQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, Column *pCol){\n  u32 h = 0;\n  char aff = SQLITE_AFF_NUMERIC;\n  const char *zChar = 0;\n\n  assert( zIn!=0 );\n  while( zIn[0] ){\n    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];\n    zIn++;\n    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */\n      aff = SQLITE_AFF_TEXT;\n      zChar = zIn;\n    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */\n      aff = SQLITE_AFF_TEXT;\n    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */\n      aff = SQLITE_AFF_TEXT;\n    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */\n        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){\n      aff = SQLITE_AFF_BLOB;\n      if( zIn[0]=='(' ) zChar = zIn;\n#ifndef SQLITE_OMIT_FLOATING_POINT\n    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */\n        && aff==SQLITE_AFF_NUMERIC ){\n      aff = SQLITE_AFF_REAL;\n    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */\n        && aff==SQLITE_AFF_NUMERIC ){\n      aff = SQLITE_AFF_REAL;\n    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */\n        && aff==SQLITE_AFF_NUMERIC ){\n      aff = SQLITE_AFF_REAL;\n#endif\n    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */\n      aff = SQLITE_AFF_INTEGER;\n      break;\n    }\n  }\n\n  /* If pCol is not NULL, store an estimate of the field size.  The\n  ** estimate is scaled so that the size of an integer is 1.  */\n  if( pCol ){\n    int v = 0;   /* default size is approx 4 bytes */\n    if( aff<SQLITE_AFF_NUMERIC ){\n      if( zChar ){\n        while( zChar[0] ){\n          if( sqlite3Isdigit(zChar[0]) ){\n            /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */\n            sqlite3GetInt32(zChar, &v);\n            break;\n          }\n          zChar++;\n        }\n      }else{\n        v = 16;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/\n      }\n    }\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n    if( v>=sqlite3GlobalConfig.szSorterRef ){\n      pCol->colFlags |= COLFLAG_SORTERREF;\n    }\n#endif\n    v = v/4 + 1;\n    if( v>255 ) v = 255;\n    pCol->szEst = v;\n  }\n  return aff;\n}\n\n/*\n** The expression is the default value for the most recently added column\n** of the table currently under construction.\n**\n** Default value expressions must be constant.  Raise an exception if this\n** is not the case.\n**\n** This routine is called by the parser while in the middle of\n** parsing a CREATE TABLE statement.\n*/\nSQLITE_PRIVATE void sqlite3AddDefaultValue(\n  Parse *pParse,           /* Parsing context */\n  Expr *pExpr,             /* The parsed expression of the default value */\n  const char *zStart,      /* Start of the default value text */\n  const char *zEnd         /* First character past end of defaut value text */\n){\n  Table *p;\n  Column *pCol;\n  sqlite3 *db = pParse->db;\n  p = pParse->pNewTable;\n  if( p!=0 ){\n    int isInit = db->init.busy && db->init.iDb!=1;\n    pCol = &(p->aCol[p->nCol-1]);\n    if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){\n      sqlite3ErrorMsg(pParse, \"default value of column [%s] is not constant\",\n          pCol->zName);\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n    }else if( pCol->colFlags & COLFLAG_GENERATED ){\n      testcase( pCol->colFlags & COLFLAG_VIRTUAL );\n      testcase( pCol->colFlags & COLFLAG_STORED );\n      sqlite3ErrorMsg(pParse, \"cannot use DEFAULT on a generated column\");\n#endif\n    }else{\n      /* A copy of pExpr is used instead of the original, as pExpr contains\n      ** tokens that point to volatile memory.\n      */\n      Expr x;\n      sqlite3ExprDelete(db, pCol->pDflt);\n      memset(&x, 0, sizeof(x));\n      x.op = TK_SPAN;\n      x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);\n      x.pLeft = pExpr;\n      x.flags = EP_Skip;\n      pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);\n      sqlite3DbFree(db, x.u.zToken);\n    }\n  }\n  if( IN_RENAME_OBJECT ){\n    sqlite3RenameExprUnmap(pParse, pExpr);\n  }\n  sqlite3ExprDelete(db, pExpr);\n}\n\n/*\n** Backwards Compatibility Hack:\n** \n** Historical versions of SQLite accepted strings as column names in\n** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:\n**\n**     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)\n**     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);\n**\n** This is goofy.  But to preserve backwards compatibility we continue to\n** accept it.  This routine does the necessary conversion.  It converts\n** the expression given in its argument from a TK_STRING into a TK_ID\n** if the expression is just a TK_STRING with an optional COLLATE clause.\n** If the expression is anything other than TK_STRING, the expression is\n** unchanged.\n*/\nstatic void sqlite3StringToId(Expr *p){\n  if( p->op==TK_STRING ){\n    p->op = TK_ID;\n  }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){\n    p->pLeft->op = TK_ID;\n  }\n}\n\n/*\n** Tag the given column as being part of the PRIMARY KEY\n*/\nstatic void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){\n  pCol->colFlags |= COLFLAG_PRIMKEY;\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n  if( pCol->colFlags & COLFLAG_GENERATED ){\n    testcase( pCol->colFlags & COLFLAG_VIRTUAL );\n    testcase( pCol->colFlags & COLFLAG_STORED );\n    sqlite3ErrorMsg(pParse,\n      \"generated columns cannot be part of the PRIMARY KEY\");\n  }\n#endif          \n}\n\n/*\n** Designate the PRIMARY KEY for the table.  pList is a list of names \n** of columns that form the primary key.  If pList is NULL, then the\n** most recently added column of the table is the primary key.\n**\n** A table can have at most one primary key.  If the table already has\n** a primary key (and this is the second primary key) then create an\n** error.\n**\n** If the PRIMARY KEY is on a single column whose datatype is INTEGER,\n** then we will try to use that column as the rowid.  Set the Table.iPKey\n** field of the table under construction to be the index of the\n** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is\n** no INTEGER PRIMARY KEY.\n**\n** If the key is not an INTEGER PRIMARY KEY, then create a unique\n** index for the key.  No index is created for INTEGER PRIMARY KEYs.\n*/\nSQLITE_PRIVATE void sqlite3AddPrimaryKey(\n  Parse *pParse,    /* Parsing context */\n  ExprList *pList,  /* List of field names to be indexed */\n  int onError,      /* What to do with a uniqueness conflict */\n  int autoInc,      /* True if the AUTOINCREMENT keyword is present */\n  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */\n){\n  Table *pTab = pParse->pNewTable;\n  Column *pCol = 0;\n  int iCol = -1, i;\n  int nTerm;\n  if( pTab==0 ) goto primary_key_exit;\n  if( pTab->tabFlags & TF_HasPrimaryKey ){\n    sqlite3ErrorMsg(pParse, \n      \"table \\\"%s\\\" has more than one primary key\", pTab->zName);\n    goto primary_key_exit;\n  }\n  pTab->tabFlags |= TF_HasPrimaryKey;\n  if( pList==0 ){\n    iCol = pTab->nCol - 1;\n    pCol = &pTab->aCol[iCol];\n    makeColumnPartOfPrimaryKey(pParse, pCol);\n    nTerm = 1;\n  }else{\n    nTerm = pList->nExpr;\n    for(i=0; i<nTerm; i++){\n      Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);\n      assert( pCExpr!=0 );\n      sqlite3StringToId(pCExpr);\n      if( pCExpr->op==TK_ID ){\n        const char *zCName = pCExpr->u.zToken;\n        for(iCol=0; iCol<pTab->nCol; iCol++){\n          if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){\n            pCol = &pTab->aCol[iCol];\n            makeColumnPartOfPrimaryKey(pParse, pCol);\n            break;\n          }\n        }\n      }\n    }\n  }\n  if( nTerm==1\n   && pCol\n   && sqlite3StrICmp(sqlite3ColumnType(pCol,\"\"), \"INTEGER\")==0\n   && sortOrder!=SQLITE_SO_DESC\n  ){\n    if( IN_RENAME_OBJECT && pList ){\n      Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);\n      sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);\n    }\n    pTab->iPKey = iCol;\n    pTab->keyConf = (u8)onError;\n    assert( autoInc==0 || autoInc==1 );\n    pTab->tabFlags |= autoInc*TF_Autoincrement;\n    if( pList ) pParse->iPkSortOrder = pList->a[0].sortFlags;\n    (void)sqlite3HasExplicitNulls(pParse, pList);\n  }else if( autoInc ){\n#ifndef SQLITE_OMIT_AUTOINCREMENT\n    sqlite3ErrorMsg(pParse, \"AUTOINCREMENT is only allowed on an \"\n       \"INTEGER PRIMARY KEY\");\n#endif\n  }else{\n    sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,\n                           0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);\n    pList = 0;\n  }\n\nprimary_key_exit:\n  sqlite3ExprListDelete(pParse->db, pList);\n  return;\n}\n\n/*\n** Add a new CHECK constraint to the table currently under construction.\n*/\nSQLITE_PRIVATE void sqlite3AddCheckConstraint(\n  Parse *pParse,    /* Parsing context */\n  Expr *pCheckExpr  /* The check expression */\n){\n#ifndef SQLITE_OMIT_CHECK\n  Table *pTab = pParse->pNewTable;\n  sqlite3 *db = pParse->db;\n  if( pTab && !IN_DECLARE_VTAB\n   && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)\n  ){\n    pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);\n    if( pParse->constraintName.n ){\n      sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);\n    }\n  }else\n#endif\n  {\n    sqlite3ExprDelete(pParse->db, pCheckExpr);\n  }\n}\n\n/*\n** Set the collation function of the most recently parsed table column\n** to the CollSeq given.\n*/\nSQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){\n  Table *p;\n  int i;\n  char *zColl;              /* Dequoted name of collation sequence */\n  sqlite3 *db;\n\n  if( (p = pParse->pNewTable)==0 ) return;\n  i = p->nCol-1;\n  db = pParse->db;\n  zColl = sqlite3NameFromToken(db, pToken);\n  if( !zColl ) return;\n\n  if( sqlite3LocateCollSeq(pParse, zColl) ){\n    Index *pIdx;\n    sqlite3DbFree(db, p->aCol[i].zColl);\n    p->aCol[i].zColl = zColl;\n  \n    /* If the column is declared as \"<name> PRIMARY KEY COLLATE <type>\",\n    ** then an index may have been created on this column before the\n    ** collation type was added. Correct this if it is the case.\n    */\n    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){\n      assert( pIdx->nKeyCol==1 );\n      if( pIdx->aiColumn[0]==i ){\n        pIdx->azColl[0] = p->aCol[i].zColl;\n      }\n    }\n  }else{\n    sqlite3DbFree(db, zColl);\n  }\n}\n\n/* Change the most recently parsed column to be a GENERATED ALWAYS AS\n** column.\n*/\nSQLITE_PRIVATE void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n  u8 eType = COLFLAG_VIRTUAL;\n  Table *pTab = pParse->pNewTable;\n  Column *pCol;\n  if( pTab==0 ){\n    /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */\n    goto generated_done;\n  }\n  pCol = &(pTab->aCol[pTab->nCol-1]);\n  if( IN_DECLARE_VTAB ){\n    sqlite3ErrorMsg(pParse, \"virtual tables cannot use computed columns\");\n    goto generated_done;\n  }\n  if( pCol->pDflt ) goto generated_error;\n  if( pType ){\n    if( pType->n==7 && sqlite3StrNICmp(\"virtual\",pType->z,7)==0 ){\n      /* no-op */\n    }else if( pType->n==6 && sqlite3StrNICmp(\"stored\",pType->z,6)==0 ){\n      eType = COLFLAG_STORED;\n    }else{\n      goto generated_error;\n    }\n  }\n  if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;\n  pCol->colFlags |= eType;\n  assert( TF_HasVirtual==COLFLAG_VIRTUAL );\n  assert( TF_HasStored==COLFLAG_STORED );\n  pTab->tabFlags |= eType;\n  if( pCol->colFlags & COLFLAG_PRIMKEY ){\n    makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */\n  }\n  pCol->pDflt = pExpr;\n  pExpr = 0;\n  goto generated_done;\n\ngenerated_error:\n  sqlite3ErrorMsg(pParse, \"error in generated column \\\"%s\\\"\",\n                  pCol->zName);\ngenerated_done:\n  sqlite3ExprDelete(pParse->db, pExpr);\n#else\n  /* Throw and error for the GENERATED ALWAYS AS clause if the\n  ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */\n  sqlite3ErrorMsg(pParse, \"generated columns not supported\");\n  sqlite3ExprDelete(pParse->db, pExpr);\n#endif\n}\n\n/*\n** Generate code that will increment the schema cookie.\n**\n** The schema cookie is used to determine when the schema for the\n** database changes.  After each schema change, the cookie value\n** changes.  When a process first reads the schema it records the\n** cookie.  Thereafter, whenever it goes to access the database,\n** it checks the cookie to make sure the schema has not changed\n** since it was last read.\n**\n** This plan is not completely bullet-proof.  It is possible for\n** the schema to change multiple times and for the cookie to be\n** set back to prior value.  But schema changes are infrequent\n** and the probability of hitting the same cookie value is only\n** 1 chance in 2^32.  So we're safe enough.\n**\n** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments\n** the schema-version whenever the schema changes.\n*/\nSQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){\n  sqlite3 *db = pParse->db;\n  Vdbe *v = pParse->pVdbe;\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, \n                   (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));\n}\n\n/*\n** Measure the number of characters needed to output the given\n** identifier.  The number returned includes any quotes used\n** but does not include the null terminator.\n**\n** The estimate is conservative.  It might be larger that what is\n** really needed.\n*/\nstatic int identLength(const char *z){\n  int n;\n  for(n=0; *z; n++, z++){\n    if( *z=='\"' ){ n++; }\n  }\n  return n + 2;\n}\n\n/*\n** The first parameter is a pointer to an output buffer. The second \n** parameter is a pointer to an integer that contains the offset at\n** which to write into the output buffer. This function copies the\n** nul-terminated string pointed to by the third parameter, zSignedIdent,\n** to the specified offset in the buffer and updates *pIdx to refer\n** to the first byte after the last byte written before returning.\n** \n** If the string zSignedIdent consists entirely of alpha-numeric\n** characters, does not begin with a digit and is not an SQL keyword,\n** then it is copied to the output buffer exactly as it is. Otherwise,\n** it is quoted using double-quotes.\n*/\nstatic void identPut(char *z, int *pIdx, char *zSignedIdent){\n  unsigned char *zIdent = (unsigned char*)zSignedIdent;\n  int i, j, needQuote;\n  i = *pIdx;\n\n  for(j=0; zIdent[j]; j++){\n    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;\n  }\n  needQuote = sqlite3Isdigit(zIdent[0])\n            || sqlite3KeywordCode(zIdent, j)!=TK_ID\n            || zIdent[j]!=0\n            || j==0;\n\n  if( needQuote ) z[i++] = '\"';\n  for(j=0; zIdent[j]; j++){\n    z[i++] = zIdent[j];\n    if( zIdent[j]=='\"' ) z[i++] = '\"';\n  }\n  if( needQuote ) z[i++] = '\"';\n  z[i] = 0;\n  *pIdx = i;\n}\n\n/*\n** Generate a CREATE TABLE statement appropriate for the given\n** table.  Memory to hold the text of the statement is obtained\n** from sqliteMalloc() and must be freed by the calling function.\n*/\nstatic char *createTableStmt(sqlite3 *db, Table *p){\n  int i, k, n;\n  char *zStmt;\n  char *zSep, *zSep2, *zEnd;\n  Column *pCol;\n  n = 0;\n  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){\n    n += identLength(pCol->zName) + 5;\n  }\n  n += identLength(p->zName);\n  if( n<50 ){ \n    zSep = \"\";\n    zSep2 = \",\";\n    zEnd = \")\";\n  }else{\n    zSep = \"\\n  \";\n    zSep2 = \",\\n  \";\n    zEnd = \"\\n)\";\n  }\n  n += 35 + 6*p->nCol;\n  zStmt = sqlite3DbMallocRaw(0, n);\n  if( zStmt==0 ){\n    sqlite3OomFault(db);\n    return 0;\n  }\n  sqlite3_snprintf(n, zStmt, \"CREATE TABLE \");\n  k = sqlite3Strlen30(zStmt);\n  identPut(zStmt, &k, p->zName);\n  zStmt[k++] = '(';\n  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){\n    static const char * const azType[] = {\n        /* SQLITE_AFF_BLOB    */ \"\",\n        /* SQLITE_AFF_TEXT    */ \" TEXT\",\n        /* SQLITE_AFF_NUMERIC */ \" NUM\",\n        /* SQLITE_AFF_INTEGER */ \" INT\",\n        /* SQLITE_AFF_REAL    */ \" REAL\"\n    };\n    int len;\n    const char *zType;\n\n    sqlite3_snprintf(n-k, &zStmt[k], zSep);\n    k += sqlite3Strlen30(&zStmt[k]);\n    zSep = zSep2;\n    identPut(zStmt, &k, pCol->zName);\n    assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );\n    assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );\n    testcase( pCol->affinity==SQLITE_AFF_BLOB );\n    testcase( pCol->affinity==SQLITE_AFF_TEXT );\n    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );\n    testcase( pCol->affinity==SQLITE_AFF_INTEGER );\n    testcase( pCol->affinity==SQLITE_AFF_REAL );\n    \n    zType = azType[pCol->affinity - SQLITE_AFF_BLOB];\n    len = sqlite3Strlen30(zType);\n    assert( pCol->affinity==SQLITE_AFF_BLOB \n            || pCol->affinity==sqlite3AffinityType(zType, 0) );\n    memcpy(&zStmt[k], zType, len);\n    k += len;\n    assert( k<=n );\n  }\n  sqlite3_snprintf(n-k, &zStmt[k], \"%s\", zEnd);\n  return zStmt;\n}\n\n/*\n** Resize an Index object to hold N columns total.  Return SQLITE_OK\n** on success and SQLITE_NOMEM on an OOM error.\n*/\nstatic int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){\n  char *zExtra;\n  int nByte;\n  if( pIdx->nColumn>=N ) return SQLITE_OK;\n  assert( pIdx->isResized==0 );\n  nByte = (sizeof(char*) + sizeof(i16) + 1)*N;\n  zExtra = sqlite3DbMallocZero(db, nByte);\n  if( zExtra==0 ) return SQLITE_NOMEM_BKPT;\n  memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);\n  pIdx->azColl = (const char**)zExtra;\n  zExtra += sizeof(char*)*N;\n  memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);\n  pIdx->aiColumn = (i16*)zExtra;\n  zExtra += sizeof(i16)*N;\n  memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);\n  pIdx->aSortOrder = (u8*)zExtra;\n  pIdx->nColumn = N;\n  pIdx->isResized = 1;\n  return SQLITE_OK;\n}\n\n/*\n** Estimate the total row width for a table.\n*/\nstatic void estimateTableWidth(Table *pTab){\n  unsigned wTable = 0;\n  const Column *pTabCol;\n  int i;\n  for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){\n    wTable += pTabCol->szEst;\n  }\n  if( pTab->iPKey<0 ) wTable++;\n  pTab->szTabRow = sqlite3LogEst(wTable*4);\n}\n\n/*\n** Estimate the average size of a row for an index.\n*/\nstatic void estimateIndexWidth(Index *pIdx){\n  unsigned wIndex = 0;\n  int i;\n  const Column *aCol = pIdx->pTable->aCol;\n  for(i=0; i<pIdx->nColumn; i++){\n    i16 x = pIdx->aiColumn[i];\n    assert( x<pIdx->pTable->nCol );\n    wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;\n  }\n  pIdx->szIdxRow = sqlite3LogEst(wIndex*4);\n}\n\n/* Return true if column number x is any of the first nCol entries of aiCol[].\n** This is used to determine if the column number x appears in any of the\n** first nCol entries of an index.\n*/\nstatic int hasColumn(const i16 *aiCol, int nCol, int x){\n  while( nCol-- > 0 ){\n    assert( aiCol[0]>=0 );\n    if( x==*(aiCol++) ){\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/*\n** Return true if any of the first nKey entries of index pIdx exactly\n** match the iCol-th entry of pPk.  pPk is always a WITHOUT ROWID\n** PRIMARY KEY index.  pIdx is an index on the same table.  pIdx may\n** or may not be the same index as pPk.\n**\n** The first nKey entries of pIdx are guaranteed to be ordinary columns,\n** not a rowid or expression.\n**\n** This routine differs from hasColumn() in that both the column and the\n** collating sequence must match for this routine, but for hasColumn() only\n** the column name must match.\n*/\nstatic int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){\n  int i, j;\n  assert( nKey<=pIdx->nColumn );\n  assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );\n  assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );\n  assert( pPk->pTable->tabFlags & TF_WithoutRowid );\n  assert( pPk->pTable==pIdx->pTable );\n  testcase( pPk==pIdx );\n  j = pPk->aiColumn[iCol];\n  assert( j!=XN_ROWID && j!=XN_EXPR );\n  for(i=0; i<nKey; i++){\n    assert( pIdx->aiColumn[i]>=0 || j>=0 );\n    if( pIdx->aiColumn[i]==j \n     && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0\n    ){\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/* Recompute the colNotIdxed field of the Index.\n**\n** colNotIdxed is a bitmask that has a 0 bit representing each indexed\n** columns that are within the first 63 columns of the table.  The\n** high-order bit of colNotIdxed is always 1.  All unindexed columns\n** of the table have a 1.\n**\n** 2019-10-24:  For the purpose of this computation, virtual columns are\n** not considered to be covered by the index, even if they are in the\n** index, because we do not trust the logic in whereIndexExprTrans() to be\n** able to find all instances of a reference to the indexed table column\n** and convert them into references to the index.  Hence we always want\n** the actual table at hand in order to recompute the virtual column, if\n** necessary.\n**\n** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask\n** to determine if the index is covering index.\n*/\nstatic void recomputeColumnsNotIndexed(Index *pIdx){\n  Bitmask m = 0;\n  int j;\n  Table *pTab = pIdx->pTable;\n  for(j=pIdx->nColumn-1; j>=0; j--){\n    int x = pIdx->aiColumn[j];\n    if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){\n      testcase( x==BMS-1 );\n      testcase( x==BMS-2 );\n      if( x<BMS-1 ) m |= MASKBIT(x);\n    }\n  }\n  pIdx->colNotIdxed = ~m;\n  assert( (pIdx->colNotIdxed>>63)==1 );\n}\n\n/*\n** This routine runs at the end of parsing a CREATE TABLE statement that\n** has a WITHOUT ROWID clause.  The job of this routine is to convert both\n** internal schema data structures and the generated VDBE code so that they\n** are appropriate for a WITHOUT ROWID table instead of a rowid table.\n** Changes include:\n**\n**     (1)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.\n**     (2)  Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY \n**          into BTREE_BLOBKEY.\n**     (3)  Bypass the creation of the sqlite_master table entry\n**          for the PRIMARY KEY as the primary key index is now\n**          identified by the sqlite_master table entry of the table itself.\n**     (4)  Set the Index.tnum of the PRIMARY KEY Index object in the\n**          schema to the rootpage from the main table.\n**     (5)  Add all table columns to the PRIMARY KEY Index object\n**          so that the PRIMARY KEY is a covering index.  The surplus\n**          columns are part of KeyInfo.nAllField and are not used for\n**          sorting or lookup or uniqueness checks.\n**     (6)  Replace the rowid tail on all automatically generated UNIQUE\n**          indices with the PRIMARY KEY columns.\n**\n** For virtual tables, only (1) is performed.\n*/\nstatic void convertToWithoutRowidTable(Parse *pParse, Table *pTab){\n  Index *pIdx;\n  Index *pPk;\n  int nPk;\n  int nExtra;\n  int i, j;\n  sqlite3 *db = pParse->db;\n  Vdbe *v = pParse->pVdbe;\n\n  /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)\n  */\n  if( !db->init.imposterTable ){\n    for(i=0; i<pTab->nCol; i++){\n      if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){\n        pTab->aCol[i].notNull = OE_Abort;\n      }\n    }\n    pTab->tabFlags |= TF_HasNotNull;\n  }\n\n  /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY\n  ** into BTREE_BLOBKEY.\n  */\n  if( pParse->addrCrTab ){\n    assert( v );\n    sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);\n  }\n\n  /* Locate the PRIMARY KEY index.  Or, if this table was originally\n  ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. \n  */\n  if( pTab->iPKey>=0 ){\n    ExprList *pList;\n    Token ipkToken;\n    sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);\n    pList = sqlite3ExprListAppend(pParse, 0, \n                  sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));\n    if( pList==0 ) return;\n    if( IN_RENAME_OBJECT ){\n      sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);\n    }\n    pList->a[0].sortFlags = pParse->iPkSortOrder;\n    assert( pParse->pNewTable==pTab );\n    pTab->iPKey = -1;\n    sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,\n                       SQLITE_IDXTYPE_PRIMARYKEY);\n    if( db->mallocFailed || pParse->nErr ) return;\n    pPk = sqlite3PrimaryKeyIndex(pTab);\n    assert( pPk->nKeyCol==1 );\n  }else{\n    pPk = sqlite3PrimaryKeyIndex(pTab);\n    assert( pPk!=0 );\n\n    /*\n    ** Remove all redundant columns from the PRIMARY KEY.  For example, change\n    ** \"PRIMARY KEY(a,b,a,b,c,b,c,d)\" into just \"PRIMARY KEY(a,b,c,d)\".  Later\n    ** code assumes the PRIMARY KEY contains no repeated columns.\n    */\n    for(i=j=1; i<pPk->nKeyCol; i++){\n      if( isDupColumn(pPk, j, pPk, i) ){\n        pPk->nColumn--;\n      }else{\n        testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );\n        pPk->azColl[j] = pPk->azColl[i];\n        pPk->aSortOrder[j] = pPk->aSortOrder[i];\n        pPk->aiColumn[j++] = pPk->aiColumn[i];\n      }\n    }\n    pPk->nKeyCol = j;\n  }\n  assert( pPk!=0 );\n  pPk->isCovering = 1;\n  if( !db->init.imposterTable ) pPk->uniqNotNull = 1;\n  nPk = pPk->nColumn = pPk->nKeyCol;\n\n  /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master\n  ** table entry. This is only required if currently generating VDBE\n  ** code for a CREATE TABLE (not when parsing one as part of reading\n  ** a database schema).  */\n  if( v && pPk->tnum>0 ){\n    assert( db->init.busy==0 );\n    sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);\n  }\n\n  /* The root page of the PRIMARY KEY is the table root page */\n  pPk->tnum = pTab->tnum;\n\n  /* Update the in-memory representation of all UNIQUE indices by converting\n  ** the final rowid column into one or more columns of the PRIMARY KEY.\n  */\n  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n    int n;\n    if( IsPrimaryKeyIndex(pIdx) ) continue;\n    for(i=n=0; i<nPk; i++){\n      if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){\n        testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );\n        n++;\n      }\n    }\n    if( n==0 ){\n      /* This index is a superset of the primary key */\n      pIdx->nColumn = pIdx->nKeyCol;\n      continue;\n    }\n    if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;\n    for(i=0, j=pIdx->nKeyCol; i<nPk; i++){\n      if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){\n        testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );\n        pIdx->aiColumn[j] = pPk->aiColumn[i];\n        pIdx->azColl[j] = pPk->azColl[i];\n        if( pPk->aSortOrder[i] ){\n          /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */\n          pIdx->bAscKeyBug = 1;\n        }\n        j++;\n      }\n    }\n    assert( pIdx->nColumn>=pIdx->nKeyCol+n );\n    assert( pIdx->nColumn>=j );\n  }\n\n  /* Add all table columns to the PRIMARY KEY index\n  */\n  nExtra = 0;\n  for(i=0; i<pTab->nCol; i++){\n    if( !hasColumn(pPk->aiColumn, nPk, i)\n     && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;\n  }\n  if( resizeIndexObject(db, pPk, nPk+nExtra) ) return;\n  for(i=0, j=nPk; i<pTab->nCol; i++){\n    if( !hasColumn(pPk->aiColumn, j, i)\n     && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0\n    ){\n      assert( j<pPk->nColumn );\n      pPk->aiColumn[j] = i;\n      pPk->azColl[j] = sqlite3StrBINARY;\n      j++;\n    }\n  }\n  assert( pPk->nColumn==j );\n  assert( pTab->nNVCol<=j );\n  recomputeColumnsNotIndexed(pPk);\n}\n\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/*\n** Return true if pTab is a virtual table and zName is a shadow table name\n** for that virtual table.\n*/\nSQLITE_PRIVATE int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){\n  int nName;                    /* Length of zName */\n  Module *pMod;                 /* Module for the virtual table */\n\n  if( !IsVirtual(pTab) ) return 0;\n  nName = sqlite3Strlen30(pTab->zName);\n  if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;\n  if( zName[nName]!='_' ) return 0;\n  pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]);\n  if( pMod==0 ) return 0;\n  if( pMod->pModule->iVersion<3 ) return 0;\n  if( pMod->pModule->xShadowName==0 ) return 0;\n  return pMod->pModule->xShadowName(zName+nName+1);\n}\n#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/*\n** Return true if zName is a shadow table name in the current database\n** connection.\n**\n** zName is temporarily modified while this routine is running, but is\n** restored to its original value prior to this routine returning.\n*/\nSQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName){\n  char *zTail;                  /* Pointer to the last \"_\" in zName */\n  Table *pTab;                  /* Table that zName is a shadow of */\n  zTail = strrchr(zName, '_');\n  if( zTail==0 ) return 0;\n  *zTail = 0;\n  pTab = sqlite3FindTable(db, zName, 0);\n  *zTail = '_';\n  if( pTab==0 ) return 0;\n  if( !IsVirtual(pTab) ) return 0;\n  return sqlite3IsShadowTableOf(db, pTab, zName);\n}\n#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */\n\n\n#ifdef SQLITE_DEBUG\n/*\n** Mark all nodes of an expression as EP_Immutable, indicating that\n** they should not be changed.  Expressions attached to a table or\n** index definition are tagged this way to help ensure that we do\n** not pass them into code generator routines by mistake.\n*/\nstatic int markImmutableExprStep(Walker *pWalker, Expr *pExpr){\n  ExprSetVVAProperty(pExpr, EP_Immutable);\n  return WRC_Continue;\n}\nstatic void markExprListImmutable(ExprList *pList){\n  if( pList ){\n    Walker w;\n    memset(&w, 0, sizeof(w));\n    w.xExprCallback = markImmutableExprStep;\n    w.xSelectCallback = sqlite3SelectWalkNoop;\n    w.xSelectCallback2 = 0;\n    sqlite3WalkExprList(&w, pList);\n  }\n}\n#else\n#define markExprListImmutable(X)  /* no-op */\n#endif /* SQLITE_DEBUG */\n\n\n/*\n** This routine is called to report the final \")\" that terminates\n** a CREATE TABLE statement.\n**\n** The table structure that other action routines have been building\n** is added to the internal hash tables, assuming no errors have\n** occurred.\n**\n** An entry for the table is made in the master table on disk, unless\n** this is a temporary table or db->init.busy==1.  When db->init.busy==1\n** it means we are reading the sqlite_master table because we just\n** connected to the database or because the sqlite_master table has\n** recently changed, so the entry for this table already exists in\n** the sqlite_master table.  We do not want to create it again.\n**\n** If the pSelect argument is not NULL, it means that this routine\n** was called to create a table generated from a \n** \"CREATE TABLE ... AS SELECT ...\" statement.  The column names of\n** the new table will match the result set of the SELECT.\n*/\nSQLITE_PRIVATE void sqlite3EndTable(\n  Parse *pParse,          /* Parse context */\n  Token *pCons,           /* The ',' token after the last column defn. */\n  Token *pEnd,            /* The ')' before options in the CREATE TABLE */\n  u8 tabOpts,             /* Extra table options. Usually 0. */\n  Select *pSelect         /* Select from a \"CREATE ... AS SELECT\" */\n){\n  Table *p;                 /* The new table */\n  sqlite3 *db = pParse->db; /* The database connection */\n  int iDb;                  /* Database in which the table lives */\n  Index *pIdx;              /* An implied index of the table */\n\n  if( pEnd==0 && pSelect==0 ){\n    return;\n  }\n  assert( !db->mallocFailed );\n  p = pParse->pNewTable;\n  if( p==0 ) return;\n\n  if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){\n    p->tabFlags |= TF_Shadow;\n  }\n\n  /* If the db->init.busy is 1 it means we are reading the SQL off the\n  ** \"sqlite_master\" or \"sqlite_temp_master\" table on the disk.\n  ** So do not write to the disk again.  Extract the root page number\n  ** for the table from the db->init.newTnum field.  (The page number\n  ** should have been put there by the sqliteOpenCb routine.)\n  **\n  ** If the root page number is 1, that means this is the sqlite_master\n  ** table itself.  So mark it read-only.\n  */\n  if( db->init.busy ){\n    if( pSelect ){\n      sqlite3ErrorMsg(pParse, \"\");\n      return;\n    }\n    p->tnum = db->init.newTnum;\n    if( p->tnum==1 ) p->tabFlags |= TF_Readonly;\n  }\n\n  assert( (p->tabFlags & TF_HasPrimaryKey)==0\n       || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );\n  assert( (p->tabFlags & TF_HasPrimaryKey)!=0\n       || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );\n\n  /* Special processing for WITHOUT ROWID Tables */\n  if( tabOpts & TF_WithoutRowid ){\n    if( (p->tabFlags & TF_Autoincrement) ){\n      sqlite3ErrorMsg(pParse,\n          \"AUTOINCREMENT not allowed on WITHOUT ROWID tables\");\n      return;\n    }\n    if( (p->tabFlags & TF_HasPrimaryKey)==0 ){\n      sqlite3ErrorMsg(pParse, \"PRIMARY KEY missing on table %s\", p->zName);\n      return;\n    }\n    p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;\n    convertToWithoutRowidTable(pParse, p);\n  }\n  iDb = sqlite3SchemaToIndex(db, p->pSchema);\n\n#ifndef SQLITE_OMIT_CHECK\n  /* Resolve names in all CHECK constraint expressions.\n  */\n  if( p->pCheck ){\n    sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);\n    if( pParse->nErr ){\n      /* If errors are seen, delete the CHECK constraints now, else they might\n      ** actually be used if PRAGMA writable_schema=ON is set. */\n      sqlite3ExprListDelete(db, p->pCheck);\n      p->pCheck = 0;\n    }else{\n      markExprListImmutable(p->pCheck);\n    }\n  }\n#endif /* !defined(SQLITE_OMIT_CHECK) */\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n  if( p->tabFlags & TF_HasGenerated ){\n    int ii, nNG = 0;\n    testcase( p->tabFlags & TF_HasVirtual );\n    testcase( p->tabFlags & TF_HasStored );\n    for(ii=0; ii<p->nCol; ii++){\n      u32 colFlags = p->aCol[ii].colFlags;\n      if( (colFlags & COLFLAG_GENERATED)!=0 ){\n        Expr *pX = p->aCol[ii].pDflt;\n        testcase( colFlags & COLFLAG_VIRTUAL );\n        testcase( colFlags & COLFLAG_STORED );\n        if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){\n          /* If there are errors in resolving the expression, change the\n          ** expression to a NULL.  This prevents code generators that operate\n          ** on the expression from inserting extra parts into the expression\n          ** tree that have been allocated from lookaside memory, which is\n          ** illegal in a schema and will lead to errors or heap corruption\n          ** when the database connection closes. */\n          sqlite3ExprDelete(db, pX);\n          p->aCol[ii].pDflt = sqlite3ExprAlloc(db, TK_NULL, 0, 0);\n        }\n      }else{\n        nNG++;\n      }\n    }\n    if( nNG==0 ){\n      sqlite3ErrorMsg(pParse, \"must have at least one non-generated column\");\n      return;\n    }\n  }\n#endif\n\n  /* Estimate the average row size for the table and for all implied indices */\n  estimateTableWidth(p);\n  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){\n    estimateIndexWidth(pIdx);\n  }\n\n  /* If not initializing, then create a record for the new table\n  ** in the SQLITE_MASTER table of the database.\n  **\n  ** If this is a TEMPORARY table, write the entry into the auxiliary\n  ** file instead of into the main database file.\n  */\n  if( !db->init.busy ){\n    int n;\n    Vdbe *v;\n    char *zType;    /* \"view\" or \"table\" */\n    char *zType2;   /* \"VIEW\" or \"TABLE\" */\n    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */\n\n    v = sqlite3GetVdbe(pParse);\n    if( NEVER(v==0) ) return;\n\n    sqlite3VdbeAddOp1(v, OP_Close, 0);\n\n    /* \n    ** Initialize zType for the new view or table.\n    */\n    if( p->pSelect==0 ){\n      /* A regular table */\n      zType = \"table\";\n      zType2 = \"TABLE\";\n#ifndef SQLITE_OMIT_VIEW\n    }else{\n      /* A view */\n      zType = \"view\";\n      zType2 = \"VIEW\";\n#endif\n    }\n\n    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT\n    ** statement to populate the new table. The root-page number for the\n    ** new table is in register pParse->regRoot.\n    **\n    ** Once the SELECT has been coded by sqlite3Select(), it is in a\n    ** suitable state to query for the column names and types to be used\n    ** by the new table.\n    **\n    ** A shared-cache write-lock is not required to write to the new table,\n    ** as a schema-lock must have already been obtained to create it. Since\n    ** a schema-lock excludes all other database users, the write-lock would\n    ** be redundant.\n    */\n    if( pSelect ){\n      SelectDest dest;    /* Where the SELECT should store results */\n      int regYield;       /* Register holding co-routine entry-point */\n      int addrTop;        /* Top of the co-routine */\n      int regRec;         /* A record to be insert into the new table */\n      int regRowid;       /* Rowid of the next row to insert */\n      int addrInsLoop;    /* Top of the loop for inserting rows */\n      Table *pSelTab;     /* A table that describes the SELECT results */\n\n      regYield = ++pParse->nMem;\n      regRec = ++pParse->nMem;\n      regRowid = ++pParse->nMem;\n      assert(pParse->nTab==1);\n      sqlite3MayAbort(pParse);\n      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);\n      sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);\n      pParse->nTab = 2;\n      addrTop = sqlite3VdbeCurrentAddr(v) + 1;\n      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);\n      if( pParse->nErr ) return;\n      pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB);\n      if( pSelTab==0 ) return;\n      assert( p->aCol==0 );\n      p->nCol = p->nNVCol = pSelTab->nCol;\n      p->aCol = pSelTab->aCol;\n      pSelTab->nCol = 0;\n      pSelTab->aCol = 0;\n      sqlite3DeleteTable(db, pSelTab);\n      sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);\n      sqlite3Select(pParse, pSelect, &dest);\n      if( pParse->nErr ) return;\n      sqlite3VdbeEndCoroutine(v, regYield);\n      sqlite3VdbeJumpHere(v, addrTop - 1);\n      addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);\n      VdbeCoverage(v);\n      sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);\n      sqlite3TableAffinity(v, p, 0);\n      sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);\n      sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);\n      sqlite3VdbeGoto(v, addrInsLoop);\n      sqlite3VdbeJumpHere(v, addrInsLoop);\n      sqlite3VdbeAddOp1(v, OP_Close, 1);\n    }\n\n    /* Compute the complete text of the CREATE statement */\n    if( pSelect ){\n      zStmt = createTableStmt(db, p);\n    }else{\n      Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;\n      n = (int)(pEnd2->z - pParse->sNameToken.z);\n      if( pEnd2->z[0]!=';' ) n += pEnd2->n;\n      zStmt = sqlite3MPrintf(db, \n          \"CREATE %s %.*s\", zType2, n, pParse->sNameToken.z\n      );\n    }\n\n    /* A slot for the record has already been allocated in the \n    ** SQLITE_MASTER table.  We just need to update that slot with all\n    ** the information we've collected.\n    */\n    sqlite3NestedParse(pParse,\n      \"UPDATE %Q.%s \"\n         \"SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q \"\n       \"WHERE rowid=#%d\",\n      db->aDb[iDb].zDbSName, MASTER_NAME,\n      zType,\n      p->zName,\n      p->zName,\n      pParse->regRoot,\n      zStmt,\n      pParse->regRowid\n    );\n    sqlite3DbFree(db, zStmt);\n    sqlite3ChangeCookie(pParse, iDb);\n\n#ifndef SQLITE_OMIT_AUTOINCREMENT\n    /* Check to see if we need to create an sqlite_sequence table for\n    ** keeping track of autoincrement keys.\n    */\n    if( (p->tabFlags & TF_Autoincrement)!=0 ){\n      Db *pDb = &db->aDb[iDb];\n      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n      if( pDb->pSchema->pSeqTab==0 ){\n        sqlite3NestedParse(pParse,\n          \"CREATE TABLE %Q.sqlite_sequence(name,seq)\",\n          pDb->zDbSName\n        );\n      }\n    }\n#endif\n\n    /* Reparse everything to update our internal data structures */\n    sqlite3VdbeAddParseSchemaOp(v, iDb,\n           sqlite3MPrintf(db, \"tbl_name='%q' AND type!='trigger'\", p->zName));\n  }\n\n  /* Add the table to the in-memory representation of the database.\n  */\n  if( db->init.busy ){\n    Table *pOld;\n    Schema *pSchema = p->pSchema;\n    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);\n    if( pOld ){\n      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */\n      sqlite3OomFault(db);\n      return;\n    }\n    pParse->pNewTable = 0;\n    db->mDbFlags |= DBFLAG_SchemaChange;\n\n#ifndef SQLITE_OMIT_ALTERTABLE\n    if( !p->pSelect ){\n      const char *zName = (const char *)pParse->sNameToken.z;\n      int nName;\n      assert( !pSelect && pCons && pEnd );\n      if( pCons->z==0 ){\n        pCons = pEnd;\n      }\n      nName = (int)((const char *)pCons->z - zName);\n      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);\n    }\n#endif\n  }\n}\n\n#ifndef SQLITE_OMIT_VIEW\n/*\n** The parser calls this routine in order to create a new VIEW\n*/\nSQLITE_PRIVATE void sqlite3CreateView(\n  Parse *pParse,     /* The parsing context */\n  Token *pBegin,     /* The CREATE token that begins the statement */\n  Token *pName1,     /* The token that holds the name of the view */\n  Token *pName2,     /* The token that holds the name of the view */\n  ExprList *pCNames, /* Optional list of view column names */\n  Select *pSelect,   /* A SELECT statement that will become the new view */\n  int isTemp,        /* TRUE for a TEMPORARY view */\n  int noErr          /* Suppress error messages if VIEW already exists */\n){\n  Table *p;\n  int n;\n  const char *z;\n  Token sEnd;\n  DbFixer sFix;\n  Token *pName = 0;\n  int iDb;\n  sqlite3 *db = pParse->db;\n\n  if( pParse->nVar>0 ){\n    sqlite3ErrorMsg(pParse, \"parameters are not allowed in views\");\n    goto create_view_fail;\n  }\n  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);\n  p = pParse->pNewTable;\n  if( p==0 || pParse->nErr ) goto create_view_fail;\n  sqlite3TwoPartName(pParse, pName1, pName2, &pName);\n  iDb = sqlite3SchemaToIndex(db, p->pSchema);\n  sqlite3FixInit(&sFix, pParse, iDb, \"view\", pName);\n  if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;\n\n  /* Make a copy of the entire SELECT statement that defines the view.\n  ** This will force all the Expr.token.z values to be dynamically\n  ** allocated rather than point to the input string - which means that\n  ** they will persist after the current sqlite3_exec() call returns.\n  */\n  pSelect->selFlags |= SF_View;\n  if( IN_RENAME_OBJECT ){\n    p->pSelect = pSelect;\n    pSelect = 0;\n  }else{\n    p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);\n  }\n  p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);\n  if( db->mallocFailed ) goto create_view_fail;\n\n  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to\n  ** the end.\n  */\n  sEnd = pParse->sLastToken;\n  assert( sEnd.z[0]!=0 || sEnd.n==0 );\n  if( sEnd.z[0]!=';' ){\n    sEnd.z += sEnd.n;\n  }\n  sEnd.n = 0;\n  n = (int)(sEnd.z - pBegin->z);\n  assert( n>0 );\n  z = pBegin->z;\n  while( sqlite3Isspace(z[n-1]) ){ n--; }\n  sEnd.z = &z[n-1];\n  sEnd.n = 1;\n\n  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */\n  sqlite3EndTable(pParse, 0, &sEnd, 0, 0);\n\ncreate_view_fail:\n  sqlite3SelectDelete(db, pSelect);\n  if( IN_RENAME_OBJECT ){\n    sqlite3RenameExprlistUnmap(pParse, pCNames);\n  }\n  sqlite3ExprListDelete(db, pCNames);\n  return;\n}\n#endif /* SQLITE_OMIT_VIEW */\n\n#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)\n/*\n** The Table structure pTable is really a VIEW.  Fill in the names of\n** the columns of the view in the pTable structure.  Return the number\n** of errors.  If an error is seen leave an error message in pParse->zErrMsg.\n*/\nSQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){\n  Table *pSelTab;   /* A fake table from which we get the result set */\n  Select *pSel;     /* Copy of the SELECT that implements the view */\n  int nErr = 0;     /* Number of errors encountered */\n  int n;            /* Temporarily holds the number of cursors assigned */\n  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  int rc;\n#endif\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  sqlite3_xauth xAuth;       /* Saved xAuth pointer */\n#endif\n\n  assert( pTable );\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  db->nSchemaLock++;\n  rc = sqlite3VtabCallConnect(pParse, pTable);\n  db->nSchemaLock--;\n  if( rc ){\n    return 1;\n  }\n  if( IsVirtual(pTable) ) return 0;\n#endif\n\n#ifndef SQLITE_OMIT_VIEW\n  /* A positive nCol means the columns names for this view are\n  ** already known.\n  */\n  if( pTable->nCol>0 ) return 0;\n\n  /* A negative nCol is a special marker meaning that we are currently\n  ** trying to compute the column names.  If we enter this routine with\n  ** a negative nCol, it means two or more views form a loop, like this:\n  **\n  **     CREATE VIEW one AS SELECT * FROM two;\n  **     CREATE VIEW two AS SELECT * FROM one;\n  **\n  ** Actually, the error above is now caught prior to reaching this point.\n  ** But the following test is still important as it does come up\n  ** in the following:\n  ** \n  **     CREATE TABLE main.ex1(a);\n  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;\n  **     SELECT * FROM temp.ex1;\n  */\n  if( pTable->nCol<0 ){\n    sqlite3ErrorMsg(pParse, \"view %s is circularly defined\", pTable->zName);\n    return 1;\n  }\n  assert( pTable->nCol>=0 );\n\n  /* If we get this far, it means we need to compute the table names.\n  ** Note that the call to sqlite3ResultSetOfSelect() will expand any\n  ** \"*\" elements in the results set of the view and will assign cursors\n  ** to the elements of the FROM clause.  But we do not want these changes\n  ** to be permanent.  So the computation is done on a copy of the SELECT\n  ** statement that defines the view.\n  */\n  assert( pTable->pSelect );\n  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);\n  if( pSel ){\n#ifndef SQLITE_OMIT_ALTERTABLE\n    u8 eParseMode = pParse->eParseMode;\n    pParse->eParseMode = PARSE_MODE_NORMAL;\n#endif\n    n = pParse->nTab;\n    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);\n    pTable->nCol = -1;\n    DisableLookaside;\n#ifndef SQLITE_OMIT_AUTHORIZATION\n    xAuth = db->xAuth;\n    db->xAuth = 0;\n    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);\n    db->xAuth = xAuth;\n#else\n    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);\n#endif\n    pParse->nTab = n;\n    if( pSelTab==0 ){\n      pTable->nCol = 0;\n      nErr++;\n    }else if( pTable->pCheck ){\n      /* CREATE VIEW name(arglist) AS ...\n      ** The names of the columns in the table are taken from\n      ** arglist which is stored in pTable->pCheck.  The pCheck field\n      ** normally holds CHECK constraints on an ordinary table, but for\n      ** a VIEW it holds the list of column names.\n      */\n      sqlite3ColumnsFromExprList(pParse, pTable->pCheck, \n                                 &pTable->nCol, &pTable->aCol);\n      if( db->mallocFailed==0 \n       && pParse->nErr==0\n       && pTable->nCol==pSel->pEList->nExpr\n      ){\n        sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel,\n                                               SQLITE_AFF_NONE);\n      }\n    }else{\n      /* CREATE VIEW name AS...  without an argument list.  Construct\n      ** the column names from the SELECT statement that defines the view.\n      */\n      assert( pTable->aCol==0 );\n      pTable->nCol = pSelTab->nCol;\n      pTable->aCol = pSelTab->aCol;\n      pSelTab->nCol = 0;\n      pSelTab->aCol = 0;\n      assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );\n    }\n    pTable->nNVCol = pTable->nCol;\n    sqlite3DeleteTable(db, pSelTab);\n    sqlite3SelectDelete(db, pSel);\n    EnableLookaside;\n#ifndef SQLITE_OMIT_ALTERTABLE\n    pParse->eParseMode = eParseMode;\n#endif\n  } else {\n    nErr++;\n  }\n  pTable->pSchema->schemaFlags |= DB_UnresetViews;\n  if( db->mallocFailed ){\n    sqlite3DeleteColumnNames(db, pTable);\n    pTable->aCol = 0;\n    pTable->nCol = 0;\n  }\n#endif /* SQLITE_OMIT_VIEW */\n  return nErr;  \n}\n#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */\n\n#ifndef SQLITE_OMIT_VIEW\n/*\n** Clear the column names from every VIEW in database idx.\n*/\nstatic void sqliteViewResetAll(sqlite3 *db, int idx){\n  HashElem *i;\n  assert( sqlite3SchemaMutexHeld(db, idx, 0) );\n  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;\n  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){\n    Table *pTab = sqliteHashData(i);\n    if( pTab->pSelect ){\n      sqlite3DeleteColumnNames(db, pTab);\n      pTab->aCol = 0;\n      pTab->nCol = 0;\n    }\n  }\n  DbClearProperty(db, idx, DB_UnresetViews);\n}\n#else\n# define sqliteViewResetAll(A,B)\n#endif /* SQLITE_OMIT_VIEW */\n\n/*\n** This function is called by the VDBE to adjust the internal schema\n** used by SQLite when the btree layer moves a table root page. The\n** root-page of a table or index in database iDb has changed from iFrom\n** to iTo.\n**\n** Ticket #1728:  The symbol table might still contain information\n** on tables and/or indices that are the process of being deleted.\n** If you are unlucky, one of those deleted indices or tables might\n** have the same rootpage number as the real table or index that is\n** being moved.  So we cannot stop searching after the first match \n** because the first match might be for one of the deleted indices\n** or tables and not the table/index that is actually being moved.\n** We must continue looping until all tables and indices with\n** rootpage==iFrom have been converted to have a rootpage of iTo\n** in order to be certain that we got the right one.\n*/\n#ifndef SQLITE_OMIT_AUTOVACUUM\nSQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){\n  HashElem *pElem;\n  Hash *pHash;\n  Db *pDb;\n\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  pDb = &db->aDb[iDb];\n  pHash = &pDb->pSchema->tblHash;\n  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){\n    Table *pTab = sqliteHashData(pElem);\n    if( pTab->tnum==iFrom ){\n      pTab->tnum = iTo;\n    }\n  }\n  pHash = &pDb->pSchema->idxHash;\n  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){\n    Index *pIdx = sqliteHashData(pElem);\n    if( pIdx->tnum==iFrom ){\n      pIdx->tnum = iTo;\n    }\n  }\n}\n#endif\n\n/*\n** Write code to erase the table with root-page iTable from database iDb.\n** Also write code to modify the sqlite_master table and internal schema\n** if a root-page of another table is moved by the btree-layer whilst\n** erasing iTable (this can happen with an auto-vacuum database).\n*/ \nstatic void destroyRootPage(Parse *pParse, int iTable, int iDb){\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  int r1 = sqlite3GetTempReg(pParse);\n  if( iTable<2 ) sqlite3ErrorMsg(pParse, \"corrupt schema\");\n  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);\n  sqlite3MayAbort(pParse);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n  /* OP_Destroy stores an in integer r1. If this integer\n  ** is non-zero, then it is the root page number of a table moved to\n  ** location iTable. The following code modifies the sqlite_master table to\n  ** reflect this.\n  **\n  ** The \"#NNN\" in the SQL is a special constant that means whatever value\n  ** is in register NNN.  See grammar rules associated with the TK_REGISTER\n  ** token for additional information.\n  */\n  sqlite3NestedParse(pParse, \n     \"UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d\",\n     pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);\n#endif\n  sqlite3ReleaseTempReg(pParse, r1);\n}\n\n/*\n** Write VDBE code to erase table pTab and all associated indices on disk.\n** Code to update the sqlite_master tables and internal schema definitions\n** in case a root-page belonging to another table is moved by the btree layer\n** is also added (this can happen with an auto-vacuum database).\n*/\nstatic void destroyTable(Parse *pParse, Table *pTab){\n  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM\n  ** is not defined), then it is important to call OP_Destroy on the\n  ** table and index root-pages in order, starting with the numerically \n  ** largest root-page number. This guarantees that none of the root-pages\n  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the\n  ** following were coded:\n  **\n  ** OP_Destroy 4 0\n  ** ...\n  ** OP_Destroy 5 0\n  **\n  ** and root page 5 happened to be the largest root-page number in the\n  ** database, then root page 5 would be moved to page 4 by the \n  ** \"OP_Destroy 4 0\" opcode. The subsequent \"OP_Destroy 5 0\" would hit\n  ** a free-list page.\n  */\n  int iTab = pTab->tnum;\n  int iDestroyed = 0;\n\n  while( 1 ){\n    Index *pIdx;\n    int iLargest = 0;\n\n    if( iDestroyed==0 || iTab<iDestroyed ){\n      iLargest = iTab;\n    }\n    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n      int iIdx = pIdx->tnum;\n      assert( pIdx->pSchema==pTab->pSchema );\n      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){\n        iLargest = iIdx;\n      }\n    }\n    if( iLargest==0 ){\n      return;\n    }else{\n      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n      assert( iDb>=0 && iDb<pParse->db->nDb );\n      destroyRootPage(pParse, iLargest, iDb);\n      iDestroyed = iLargest;\n    }\n  }\n}\n\n/*\n** Remove entries from the sqlite_statN tables (for N in (1,2,3))\n** after a DROP INDEX or DROP TABLE command.\n*/\nstatic void sqlite3ClearStatTables(\n  Parse *pParse,         /* The parsing context */\n  int iDb,               /* The database number */\n  const char *zType,     /* \"idx\" or \"tbl\" */\n  const char *zName      /* Name of index or table */\n){\n  int i;\n  const char *zDbName = pParse->db->aDb[iDb].zDbSName;\n  for(i=1; i<=4; i++){\n    char zTab[24];\n    sqlite3_snprintf(sizeof(zTab),zTab,\"sqlite_stat%d\",i);\n    if( sqlite3FindTable(pParse->db, zTab, zDbName) ){\n      sqlite3NestedParse(pParse,\n        \"DELETE FROM %Q.%s WHERE %s=%Q\",\n        zDbName, zTab, zType, zName\n      );\n    }\n  }\n}\n\n/*\n** Generate code to drop a table.\n*/\nSQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){\n  Vdbe *v;\n  sqlite3 *db = pParse->db;\n  Trigger *pTrigger;\n  Db *pDb = &db->aDb[iDb];\n\n  v = sqlite3GetVdbe(pParse);\n  assert( v!=0 );\n  sqlite3BeginWriteOperation(pParse, 1, iDb);\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( IsVirtual(pTab) ){\n    sqlite3VdbeAddOp0(v, OP_VBegin);\n  }\n#endif\n\n  /* Drop all triggers associated with the table being dropped. Code\n  ** is generated to remove entries from sqlite_master and/or\n  ** sqlite_temp_master if required.\n  */\n  pTrigger = sqlite3TriggerList(pParse, pTab);\n  while( pTrigger ){\n    assert( pTrigger->pSchema==pTab->pSchema || \n        pTrigger->pSchema==db->aDb[1].pSchema );\n    sqlite3DropTriggerPtr(pParse, pTrigger);\n    pTrigger = pTrigger->pNext;\n  }\n\n#ifndef SQLITE_OMIT_AUTOINCREMENT\n  /* Remove any entries of the sqlite_sequence table associated with\n  ** the table being dropped. This is done before the table is dropped\n  ** at the btree level, in case the sqlite_sequence table needs to\n  ** move as a result of the drop (can happen in auto-vacuum mode).\n  */\n  if( pTab->tabFlags & TF_Autoincrement ){\n    sqlite3NestedParse(pParse,\n      \"DELETE FROM %Q.sqlite_sequence WHERE name=%Q\",\n      pDb->zDbSName, pTab->zName\n    );\n  }\n#endif\n\n  /* Drop all SQLITE_MASTER table and index entries that refer to the\n  ** table. The program name loops through the master table and deletes\n  ** every row that refers to a table of the same name as the one being\n  ** dropped. Triggers are handled separately because a trigger can be\n  ** created in the temp database that refers to a table in another\n  ** database.\n  */\n  sqlite3NestedParse(pParse, \n      \"DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'\",\n      pDb->zDbSName, MASTER_NAME, pTab->zName);\n  if( !isView && !IsVirtual(pTab) ){\n    destroyTable(pParse, pTab);\n  }\n\n  /* Remove the table entry from SQLite's internal schema and modify\n  ** the schema cookie.\n  */\n  if( IsVirtual(pTab) ){\n    sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);\n    sqlite3MayAbort(pParse);\n  }\n  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);\n  sqlite3ChangeCookie(pParse, iDb);\n  sqliteViewResetAll(db, iDb);\n}\n\n/*\n** Return TRUE if shadow tables should be read-only in the current\n** context.\n*/\nSQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db){\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( (db->flags & SQLITE_Defensive)!=0\n   && db->pVtabCtx==0\n   && db->nVdbeExec==0\n  ){\n    return 1;\n  }\n#endif\n  return 0;\n}\n\n/*\n** Return true if it is not allowed to drop the given table\n*/\nstatic int tableMayNotBeDropped(sqlite3 *db, Table *pTab){\n  if( sqlite3StrNICmp(pTab->zName, \"sqlite_\", 7)==0 ){\n    if( sqlite3StrNICmp(pTab->zName+7, \"stat\", 4)==0 ) return 0;\n    if( sqlite3StrNICmp(pTab->zName+7, \"parameters\", 10)==0 ) return 0;\n    return 1;\n  }\n  if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){\n    return 1;\n  }\n  return 0;\n}\n\n/*\n** This routine is called to do the work of a DROP TABLE statement.\n** pName is the name of the table to be dropped.\n*/\nSQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){\n  Table *pTab;\n  Vdbe *v;\n  sqlite3 *db = pParse->db;\n  int iDb;\n\n  if( db->mallocFailed ){\n    goto exit_drop_table;\n  }\n  assert( pParse->nErr==0 );\n  assert( pName->nSrc==1 );\n  if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;\n  if( noErr ) db->suppressErr++;\n  assert( isView==0 || isView==LOCATE_VIEW );\n  pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);\n  if( noErr ) db->suppressErr--;\n\n  if( pTab==0 ){\n    if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);\n    goto exit_drop_table;\n  }\n  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n  assert( iDb>=0 && iDb<db->nDb );\n\n  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure\n  ** it is initialized.\n  */\n  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){\n    goto exit_drop_table;\n  }\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  {\n    int code;\n    const char *zTab = SCHEMA_TABLE(iDb);\n    const char *zDb = db->aDb[iDb].zDbSName;\n    const char *zArg2 = 0;\n    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){\n      goto exit_drop_table;\n    }\n    if( isView ){\n      if( !OMIT_TEMPDB && iDb==1 ){\n        code = SQLITE_DROP_TEMP_VIEW;\n      }else{\n        code = SQLITE_DROP_VIEW;\n      }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    }else if( IsVirtual(pTab) ){\n      code = SQLITE_DROP_VTABLE;\n      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;\n#endif\n    }else{\n      if( !OMIT_TEMPDB && iDb==1 ){\n        code = SQLITE_DROP_TEMP_TABLE;\n      }else{\n        code = SQLITE_DROP_TABLE;\n      }\n    }\n    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){\n      goto exit_drop_table;\n    }\n    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){\n      goto exit_drop_table;\n    }\n  }\n#endif\n  if( tableMayNotBeDropped(db, pTab) ){\n    sqlite3ErrorMsg(pParse, \"table %s may not be dropped\", pTab->zName);\n    goto exit_drop_table;\n  }\n\n#ifndef SQLITE_OMIT_VIEW\n  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used\n  ** on a table.\n  */\n  if( isView && pTab->pSelect==0 ){\n    sqlite3ErrorMsg(pParse, \"use DROP TABLE to delete table %s\", pTab->zName);\n    goto exit_drop_table;\n  }\n  if( !isView && pTab->pSelect ){\n    sqlite3ErrorMsg(pParse, \"use DROP VIEW to delete view %s\", pTab->zName);\n    goto exit_drop_table;\n  }\n#endif\n\n  /* Generate code to remove the table from the master table\n  ** on disk.\n  */\n  v = sqlite3GetVdbe(pParse);\n  if( v ){\n    sqlite3BeginWriteOperation(pParse, 1, iDb);\n    if( !isView ){\n      sqlite3ClearStatTables(pParse, iDb, \"tbl\", pTab->zName);\n      sqlite3FkDropTable(pParse, pName, pTab);\n    }\n    sqlite3CodeDropTable(pParse, pTab, iDb, isView);\n  }\n\nexit_drop_table:\n  sqlite3SrcListDelete(db, pName);\n}\n\n/*\n** This routine is called to create a new foreign key on the table\n** currently under construction.  pFromCol determines which columns\n** in the current table point to the foreign key.  If pFromCol==0 then\n** connect the key to the last column inserted.  pTo is the name of\n** the table referred to (a.k.a the \"parent\" table).  pToCol is a list\n** of tables in the parent pTo table.  flags contains all\n** information about the conflict resolution algorithms specified\n** in the ON DELETE, ON UPDATE and ON INSERT clauses.\n**\n** An FKey structure is created and added to the table currently\n** under construction in the pParse->pNewTable field.\n**\n** The foreign key is set for IMMEDIATE processing.  A subsequent call\n** to sqlite3DeferForeignKey() might change this to DEFERRED.\n*/\nSQLITE_PRIVATE void sqlite3CreateForeignKey(\n  Parse *pParse,       /* Parsing context */\n  ExprList *pFromCol,  /* Columns in this table that point to other table */\n  Token *pTo,          /* Name of the other table */\n  ExprList *pToCol,    /* Columns in the other table */\n  int flags            /* Conflict resolution algorithms. */\n){\n  sqlite3 *db = pParse->db;\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n  FKey *pFKey = 0;\n  FKey *pNextTo;\n  Table *p = pParse->pNewTable;\n  int nByte;\n  int i;\n  int nCol;\n  char *z;\n\n  assert( pTo!=0 );\n  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;\n  if( pFromCol==0 ){\n    int iCol = p->nCol-1;\n    if( NEVER(iCol<0) ) goto fk_end;\n    if( pToCol && pToCol->nExpr!=1 ){\n      sqlite3ErrorMsg(pParse, \"foreign key on %s\"\n         \" should reference only one column of table %T\",\n         p->aCol[iCol].zName, pTo);\n      goto fk_end;\n    }\n    nCol = 1;\n  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){\n    sqlite3ErrorMsg(pParse,\n        \"number of columns in foreign key does not match the number of \"\n        \"columns in the referenced table\");\n    goto fk_end;\n  }else{\n    nCol = pFromCol->nExpr;\n  }\n  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;\n  if( pToCol ){\n    for(i=0; i<pToCol->nExpr; i++){\n      nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;\n    }\n  }\n  pFKey = sqlite3DbMallocZero(db, nByte );\n  if( pFKey==0 ){\n    goto fk_end;\n  }\n  pFKey->pFrom = p;\n  pFKey->pNextFrom = p->pFKey;\n  z = (char*)&pFKey->aCol[nCol];\n  pFKey->zTo = z;\n  if( IN_RENAME_OBJECT ){\n    sqlite3RenameTokenMap(pParse, (void*)z, pTo);\n  }\n  memcpy(z, pTo->z, pTo->n);\n  z[pTo->n] = 0;\n  sqlite3Dequote(z);\n  z += pTo->n+1;\n  pFKey->nCol = nCol;\n  if( pFromCol==0 ){\n    pFKey->aCol[0].iFrom = p->nCol-1;\n  }else{\n    for(i=0; i<nCol; i++){\n      int j;\n      for(j=0; j<p->nCol; j++){\n        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zEName)==0 ){\n          pFKey->aCol[i].iFrom = j;\n          break;\n        }\n      }\n      if( j>=p->nCol ){\n        sqlite3ErrorMsg(pParse, \n          \"unknown column \\\"%s\\\" in foreign key definition\", \n          pFromCol->a[i].zEName);\n        goto fk_end;\n      }\n      if( IN_RENAME_OBJECT ){\n        sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName);\n      }\n    }\n  }\n  if( pToCol ){\n    for(i=0; i<nCol; i++){\n      int n = sqlite3Strlen30(pToCol->a[i].zEName);\n      pFKey->aCol[i].zCol = z;\n      if( IN_RENAME_OBJECT ){\n        sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName);\n      }\n      memcpy(z, pToCol->a[i].zEName, n);\n      z[n] = 0;\n      z += n+1;\n    }\n  }\n  pFKey->isDeferred = 0;\n  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */\n  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */\n\n  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );\n  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, \n      pFKey->zTo, (void *)pFKey\n  );\n  if( pNextTo==pFKey ){\n    sqlite3OomFault(db);\n    goto fk_end;\n  }\n  if( pNextTo ){\n    assert( pNextTo->pPrevTo==0 );\n    pFKey->pNextTo = pNextTo;\n    pNextTo->pPrevTo = pFKey;\n  }\n\n  /* Link the foreign key to the table as the last step.\n  */\n  p->pFKey = pFKey;\n  pFKey = 0;\n\nfk_end:\n  sqlite3DbFree(db, pFKey);\n#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */\n  sqlite3ExprListDelete(db, pFromCol);\n  sqlite3ExprListDelete(db, pToCol);\n}\n\n/*\n** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED\n** clause is seen as part of a foreign key definition.  The isDeferred\n** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.\n** The behavior of the most recently created foreign key is adjusted\n** accordingly.\n*/\nSQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n  Table *pTab;\n  FKey *pFKey;\n  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;\n  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */\n  pFKey->isDeferred = (u8)isDeferred;\n#endif\n}\n\n/*\n** Generate code that will erase and refill index *pIdx.  This is\n** used to initialize a newly created index or to recompute the\n** content of an index in response to a REINDEX command.\n**\n** if memRootPage is not negative, it means that the index is newly\n** created.  The register specified by memRootPage contains the\n** root page number of the index.  If memRootPage is negative, then\n** the index already exists and must be cleared before being refilled and\n** the root page number of the index is taken from pIndex->tnum.\n*/\nstatic void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){\n  Table *pTab = pIndex->pTable;  /* The table that is indexed */\n  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */\n  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */\n  int iSorter;                   /* Cursor opened by OpenSorter (if in use) */\n  int addr1;                     /* Address of top of loop */\n  int addr2;                     /* Address to jump to for next iteration */\n  int tnum;                      /* Root page of index */\n  int iPartIdxLabel;             /* Jump to this label to skip a row */\n  Vdbe *v;                       /* Generate code into this virtual machine */\n  KeyInfo *pKey;                 /* KeyInfo for index */\n  int regRecord;                 /* Register holding assembled index record */\n  sqlite3 *db = pParse->db;      /* The database connection */\n  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,\n      db->aDb[iDb].zDbSName ) ){\n    return;\n  }\n#endif\n\n  /* Require a write-lock on the table to perform this operation */\n  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);\n\n  v = sqlite3GetVdbe(pParse);\n  if( v==0 ) return;\n  if( memRootPage>=0 ){\n    tnum = memRootPage;\n  }else{\n    tnum = pIndex->tnum;\n  }\n  pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);\n  assert( pKey!=0 || db->mallocFailed || pParse->nErr );\n\n  /* Open the sorter cursor if we are to use one. */\n  iSorter = pParse->nTab++;\n  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)\n                    sqlite3KeyInfoRef(pKey), P4_KEYINFO);\n\n  /* Open the table. Loop through all rows of the table, inserting index\n  ** records into the sorter. */\n  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);\n  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);\n  regRecord = sqlite3GetTempReg(pParse);\n  sqlite3MultiWrite(pParse);\n\n  sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);\n  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);\n  sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);\n  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);\n  sqlite3VdbeJumpHere(v, addr1);\n  if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);\n  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, \n                    (char *)pKey, P4_KEYINFO);\n  sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));\n\n  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);\n  if( IsUniqueIndex(pIndex) ){\n    int j2 = sqlite3VdbeGoto(v, 1);\n    addr2 = sqlite3VdbeCurrentAddr(v);\n    sqlite3VdbeVerifyAbortable(v, OE_Abort);\n    sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,\n                         pIndex->nKeyCol); VdbeCoverage(v);\n    sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);\n    sqlite3VdbeJumpHere(v, j2);\n  }else{\n    /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not\n    ** abort. The exception is if one of the indexed expressions contains a\n    ** user function that throws an exception when it is evaluated. But the\n    ** overhead of adding a statement journal to a CREATE INDEX statement is\n    ** very small (since most of the pages written do not contain content that\n    ** needs to be restored if the statement aborts), so we call \n    ** sqlite3MayAbort() for all CREATE INDEX statements.  */\n    sqlite3MayAbort(pParse);\n    addr2 = sqlite3VdbeCurrentAddr(v);\n  }\n  sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);\n  if( !pIndex->bAscKeyBug ){\n    /* This OP_SeekEnd opcode makes index insert for a REINDEX go much\n    ** faster by avoiding unnecessary seeks.  But the optimization does\n    ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables\n    ** with DESC primary keys, since those indexes have there keys in\n    ** a different order from the main table.\n    ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf\n    */\n    sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);\n  }\n  sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);\n  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);\n  sqlite3ReleaseTempReg(pParse, regRecord);\n  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);\n  sqlite3VdbeJumpHere(v, addr1);\n\n  sqlite3VdbeAddOp1(v, OP_Close, iTab);\n  sqlite3VdbeAddOp1(v, OP_Close, iIdx);\n  sqlite3VdbeAddOp1(v, OP_Close, iSorter);\n}\n\n/*\n** Allocate heap space to hold an Index object with nCol columns.\n**\n** Increase the allocation size to provide an extra nExtra bytes\n** of 8-byte aligned space after the Index object and return a\n** pointer to this extra space in *ppExtra.\n*/\nSQLITE_PRIVATE Index *sqlite3AllocateIndexObject(\n  sqlite3 *db,         /* Database connection */\n  i16 nCol,            /* Total number of columns in the index */\n  int nExtra,          /* Number of bytes of extra space to alloc */\n  char **ppExtra       /* Pointer to the \"extra\" space */\n){\n  Index *p;            /* Allocated index object */\n  int nByte;           /* Bytes of space for Index object + arrays */\n\n  nByte = ROUND8(sizeof(Index)) +              /* Index structure  */\n          ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */\n          ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */\n                 sizeof(i16)*nCol +            /* Index.aiColumn   */\n                 sizeof(u8)*nCol);             /* Index.aSortOrder */\n  p = sqlite3DbMallocZero(db, nByte + nExtra);\n  if( p ){\n    char *pExtra = ((char*)p)+ROUND8(sizeof(Index));\n    p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);\n    p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);\n    p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;\n    p->aSortOrder = (u8*)pExtra;\n    p->nColumn = nCol;\n    p->nKeyCol = nCol - 1;\n    *ppExtra = ((char*)p) + nByte;\n  }\n  return p;\n}\n\n/*\n** If expression list pList contains an expression that was parsed with\n** an explicit \"NULLS FIRST\" or \"NULLS LAST\" clause, leave an error in\n** pParse and return non-zero. Otherwise, return zero.\n*/\nSQLITE_PRIVATE int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){\n  if( pList ){\n    int i;\n    for(i=0; i<pList->nExpr; i++){\n      if( pList->a[i].bNulls ){\n        u8 sf = pList->a[i].sortFlags;\n        sqlite3ErrorMsg(pParse, \"unsupported use of NULLS %s\", \n            (sf==0 || sf==3) ? \"FIRST\" : \"LAST\"\n        );\n        return 1;\n      }\n    }\n  }\n  return 0;\n}\n\n/*\n** Create a new index for an SQL table.  pName1.pName2 is the name of the index \n** and pTblList is the name of the table that is to be indexed.  Both will \n** be NULL for a primary key or an index that is created to satisfy a\n** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable\n** as the table to be indexed.  pParse->pNewTable is a table that is\n** currently being constructed by a CREATE TABLE statement.\n**\n** pList is a list of columns to be indexed.  pList will be NULL if this\n** is a primary key or unique-constraint on the most recent column added\n** to the table currently under construction.  \n*/\nSQLITE_PRIVATE void sqlite3CreateIndex(\n  Parse *pParse,     /* All information about this parse */\n  Token *pName1,     /* First part of index name. May be NULL */\n  Token *pName2,     /* Second part of index name. May be NULL */\n  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */\n  ExprList *pList,   /* A list of columns to be indexed */\n  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */\n  Token *pStart,     /* The CREATE token that begins this statement */\n  Expr *pPIWhere,    /* WHERE clause for partial indices */\n  int sortOrder,     /* Sort order of primary key when pList==NULL */\n  int ifNotExist,    /* Omit error if index already exists */\n  u8 idxType         /* The index type */\n){\n  Table *pTab = 0;     /* Table to be indexed */\n  Index *pIndex = 0;   /* The index to be created */\n  char *zName = 0;     /* Name of the index */\n  int nName;           /* Number of characters in zName */\n  int i, j;\n  DbFixer sFix;        /* For assigning database names to pTable */\n  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */\n  sqlite3 *db = pParse->db;\n  Db *pDb;             /* The specific table containing the indexed database */\n  int iDb;             /* Index of the database that is being written */\n  Token *pName = 0;    /* Unqualified name of the index to create */\n  struct ExprList_item *pListItem; /* For looping over pList */\n  int nExtra = 0;                  /* Space allocated for zExtra[] */\n  int nExtraCol;                   /* Number of extra columns needed */\n  char *zExtra = 0;                /* Extra space after the Index object */\n  Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */\n\n  if( db->mallocFailed || pParse->nErr>0 ){\n    goto exit_create_index;\n  }\n  if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){\n    goto exit_create_index;\n  }\n  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){\n    goto exit_create_index;\n  }\n  if( sqlite3HasExplicitNulls(pParse, pList) ){\n    goto exit_create_index;\n  }\n\n  /*\n  ** Find the table that is to be indexed.  Return early if not found.\n  */\n  if( pTblName!=0 ){\n\n    /* Use the two-part index name to determine the database \n    ** to search for the table. 'Fix' the table name to this db\n    ** before looking up the table.\n    */\n    assert( pName1 && pName2 );\n    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);\n    if( iDb<0 ) goto exit_create_index;\n    assert( pName && pName->z );\n\n#ifndef SQLITE_OMIT_TEMPDB\n    /* If the index name was unqualified, check if the table\n    ** is a temp table. If so, set the database to 1. Do not do this\n    ** if initialising a database schema.\n    */\n    if( !db->init.busy ){\n      pTab = sqlite3SrcListLookup(pParse, pTblName);\n      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){\n        iDb = 1;\n      }\n    }\n#endif\n\n    sqlite3FixInit(&sFix, pParse, iDb, \"index\", pName);\n    if( sqlite3FixSrcList(&sFix, pTblName) ){\n      /* Because the parser constructs pTblName from a single identifier,\n      ** sqlite3FixSrcList can never fail. */\n      assert(0);\n    }\n    pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);\n    assert( db->mallocFailed==0 || pTab==0 );\n    if( pTab==0 ) goto exit_create_index;\n    if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){\n      sqlite3ErrorMsg(pParse, \n           \"cannot create a TEMP index on non-TEMP table \\\"%s\\\"\",\n           pTab->zName);\n      goto exit_create_index;\n    }\n    if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);\n  }else{\n    assert( pName==0 );\n    assert( pStart==0 );\n    pTab = pParse->pNewTable;\n    if( !pTab ) goto exit_create_index;\n    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n  }\n  pDb = &db->aDb[iDb];\n\n  assert( pTab!=0 );\n  assert( pParse->nErr==0 );\n  if( sqlite3StrNICmp(pTab->zName, \"sqlite_\", 7)==0 \n       && db->init.busy==0\n       && pTblName!=0\n#if SQLITE_USER_AUTHENTICATION\n       && sqlite3UserAuthTable(pTab->zName)==0\n#endif\n#ifdef SQLITE_ALLOW_SQLITE_MASTER_INDEX\n       && sqlite3StrICmp(&pTab->zName[7],\"master\")!=0\n#endif\n ){\n    sqlite3ErrorMsg(pParse, \"table %s may not be indexed\", pTab->zName);\n    goto exit_create_index;\n  }\n#ifndef SQLITE_OMIT_VIEW\n  if( pTab->pSelect ){\n    sqlite3ErrorMsg(pParse, \"views may not be indexed\");\n    goto exit_create_index;\n  }\n#endif\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( IsVirtual(pTab) ){\n    sqlite3ErrorMsg(pParse, \"virtual tables may not be indexed\");\n    goto exit_create_index;\n  }\n#endif\n\n  /*\n  ** Find the name of the index.  Make sure there is not already another\n  ** index or table with the same name.  \n  **\n  ** Exception:  If we are reading the names of permanent indices from the\n  ** sqlite_master table (because some other process changed the schema) and\n  ** one of the index names collides with the name of a temporary table or\n  ** index, then we will continue to process this index.\n  **\n  ** If pName==0 it means that we are\n  ** dealing with a primary key or UNIQUE constraint.  We have to invent our\n  ** own name.\n  */\n  if( pName ){\n    zName = sqlite3NameFromToken(db, pName);\n    if( zName==0 ) goto exit_create_index;\n    assert( pName->z!=0 );\n    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,\"index\",pTab->zName) ){\n      goto exit_create_index;\n    }\n    if( !IN_RENAME_OBJECT ){\n      if( !db->init.busy ){\n        if( sqlite3FindTable(db, zName, 0)!=0 ){\n          sqlite3ErrorMsg(pParse, \"there is already a table named %s\", zName);\n          goto exit_create_index;\n        }\n      }\n      if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){\n        if( !ifNotExist ){\n          sqlite3ErrorMsg(pParse, \"index %s already exists\", zName);\n        }else{\n          assert( !db->init.busy );\n          sqlite3CodeVerifySchema(pParse, iDb);\n        }\n        goto exit_create_index;\n      }\n    }\n  }else{\n    int n;\n    Index *pLoop;\n    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}\n    zName = sqlite3MPrintf(db, \"sqlite_autoindex_%s_%d\", pTab->zName, n);\n    if( zName==0 ){\n      goto exit_create_index;\n    }\n\n    /* Automatic index names generated from within sqlite3_declare_vtab()\n    ** must have names that are distinct from normal automatic index names.\n    ** The following statement converts \"sqlite3_autoindex...\" into\n    ** \"sqlite3_butoindex...\" in order to make the names distinct.\n    ** The \"vtab_err.test\" test demonstrates the need of this statement. */\n    if( IN_SPECIAL_PARSE ) zName[7]++;\n  }\n\n  /* Check for authorization to create an index.\n  */\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  if( !IN_RENAME_OBJECT ){\n    const char *zDb = pDb->zDbSName;\n    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){\n      goto exit_create_index;\n    }\n    i = SQLITE_CREATE_INDEX;\n    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;\n    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){\n      goto exit_create_index;\n    }\n  }\n#endif\n\n  /* If pList==0, it means this routine was called to make a primary\n  ** key out of the last column added to the table under construction.\n  ** So create a fake list to simulate this.\n  */\n  if( pList==0 ){\n    Token prevCol;\n    Column *pCol = &pTab->aCol[pTab->nCol-1];\n    pCol->colFlags |= COLFLAG_UNIQUE;\n    sqlite3TokenInit(&prevCol, pCol->zName);\n    pList = sqlite3ExprListAppend(pParse, 0,\n              sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));\n    if( pList==0 ) goto exit_create_index;\n    assert( pList->nExpr==1 );\n    sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED);\n  }else{\n    sqlite3ExprListCheckLength(pParse, pList, \"index\");\n    if( pParse->nErr ) goto exit_create_index;\n  }\n\n  /* Figure out how many bytes of space are required to store explicitly\n  ** specified collation sequence names.\n  */\n  for(i=0; i<pList->nExpr; i++){\n    Expr *pExpr = pList->a[i].pExpr;\n    assert( pExpr!=0 );\n    if( pExpr->op==TK_COLLATE ){\n      nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));\n    }\n  }\n\n  /* \n  ** Allocate the index structure. \n  */\n  nName = sqlite3Strlen30(zName);\n  nExtraCol = pPk ? pPk->nKeyCol : 1;\n  assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );\n  pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,\n                                      nName + nExtra + 1, &zExtra);\n  if( db->mallocFailed ){\n    goto exit_create_index;\n  }\n  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );\n  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );\n  pIndex->zName = zExtra;\n  zExtra += nName + 1;\n  memcpy(pIndex->zName, zName, nName+1);\n  pIndex->pTable = pTab;\n  pIndex->onError = (u8)onError;\n  pIndex->uniqNotNull = onError!=OE_None;\n  pIndex->idxType = idxType;\n  pIndex->pSchema = db->aDb[iDb].pSchema;\n  pIndex->nKeyCol = pList->nExpr;\n  if( pPIWhere ){\n    sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);\n    pIndex->pPartIdxWhere = pPIWhere;\n    pPIWhere = 0;\n  }\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n\n  /* Check to see if we should honor DESC requests on index columns\n  */\n  if( pDb->pSchema->file_format>=4 ){\n    sortOrderMask = -1;   /* Honor DESC */\n  }else{\n    sortOrderMask = 0;    /* Ignore DESC */\n  }\n\n  /* Analyze the list of expressions that form the terms of the index and\n  ** report any errors.  In the common case where the expression is exactly\n  ** a table column, store that column in aiColumn[].  For general expressions,\n  ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].\n  **\n  ** TODO: Issue a warning if two or more columns of the index are identical.\n  ** TODO: Issue a warning if the table primary key is used as part of the\n  ** index key.\n  */\n  pListItem = pList->a;\n  if( IN_RENAME_OBJECT ){\n    pIndex->aColExpr = pList;\n    pList = 0;\n  }\n  for(i=0; i<pIndex->nKeyCol; i++, pListItem++){\n    Expr *pCExpr;                  /* The i-th index expression */\n    int requestedSortOrder;        /* ASC or DESC on the i-th expression */\n    const char *zColl;             /* Collation sequence name */\n\n    sqlite3StringToId(pListItem->pExpr);\n    sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);\n    if( pParse->nErr ) goto exit_create_index;\n    pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);\n    if( pCExpr->op!=TK_COLUMN ){\n      if( pTab==pParse->pNewTable ){\n        sqlite3ErrorMsg(pParse, \"expressions prohibited in PRIMARY KEY and \"\n                                \"UNIQUE constraints\");\n        goto exit_create_index;\n      }\n      if( pIndex->aColExpr==0 ){\n        pIndex->aColExpr = pList;\n        pList = 0;\n      }\n      j = XN_EXPR;\n      pIndex->aiColumn[i] = XN_EXPR;\n      pIndex->uniqNotNull = 0;\n    }else{\n      j = pCExpr->iColumn;\n      assert( j<=0x7fff );\n      if( j<0 ){\n        j = pTab->iPKey;\n      }else{\n        if( pTab->aCol[j].notNull==0 ){\n          pIndex->uniqNotNull = 0;\n        }\n        if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){\n          pIndex->bHasVCol = 1;\n        }\n      }\n      pIndex->aiColumn[i] = (i16)j;\n    }\n    zColl = 0;\n    if( pListItem->pExpr->op==TK_COLLATE ){\n      int nColl;\n      zColl = pListItem->pExpr->u.zToken;\n      nColl = sqlite3Strlen30(zColl) + 1;\n      assert( nExtra>=nColl );\n      memcpy(zExtra, zColl, nColl);\n      zColl = zExtra;\n      zExtra += nColl;\n      nExtra -= nColl;\n    }else if( j>=0 ){\n      zColl = pTab->aCol[j].zColl;\n    }\n    if( !zColl ) zColl = sqlite3StrBINARY;\n    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){\n      goto exit_create_index;\n    }\n    pIndex->azColl[i] = zColl;\n    requestedSortOrder = pListItem->sortFlags & sortOrderMask;\n    pIndex->aSortOrder[i] = (u8)requestedSortOrder;\n  }\n\n  /* Append the table key to the end of the index.  For WITHOUT ROWID\n  ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For\n  ** normal tables (when pPk==0) this will be the rowid.\n  */\n  if( pPk ){\n    for(j=0; j<pPk->nKeyCol; j++){\n      int x = pPk->aiColumn[j];\n      assert( x>=0 );\n      if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){\n        pIndex->nColumn--; \n      }else{\n        testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );\n        pIndex->aiColumn[i] = x;\n        pIndex->azColl[i] = pPk->azColl[j];\n        pIndex->aSortOrder[i] = pPk->aSortOrder[j];\n        i++;\n      }\n    }\n    assert( i==pIndex->nColumn );\n  }else{\n    pIndex->aiColumn[i] = XN_ROWID;\n    pIndex->azColl[i] = sqlite3StrBINARY;\n  }\n  sqlite3DefaultRowEst(pIndex);\n  if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);\n\n  /* If this index contains every column of its table, then mark\n  ** it as a covering index */\n  assert( HasRowid(pTab) \n      || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );\n  recomputeColumnsNotIndexed(pIndex);\n  if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){\n    pIndex->isCovering = 1;\n    for(j=0; j<pTab->nCol; j++){\n      if( j==pTab->iPKey ) continue;\n      if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue;\n      pIndex->isCovering = 0;\n      break;\n    }\n  }\n\n  if( pTab==pParse->pNewTable ){\n    /* This routine has been called to create an automatic index as a\n    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or\n    ** a PRIMARY KEY or UNIQUE clause following the column definitions.\n    ** i.e. one of:\n    **\n    ** CREATE TABLE t(x PRIMARY KEY, y);\n    ** CREATE TABLE t(x, y, UNIQUE(x, y));\n    **\n    ** Either way, check to see if the table already has such an index. If\n    ** so, don't bother creating this one. This only applies to\n    ** automatically created indices. Users can do as they wish with\n    ** explicit indices.\n    **\n    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent\n    ** (and thus suppressing the second one) even if they have different\n    ** sort orders.\n    **\n    ** If there are different collating sequences or if the columns of\n    ** the constraint occur in different orders, then the constraints are\n    ** considered distinct and both result in separate indices.\n    */\n    Index *pIdx;\n    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n      int k;\n      assert( IsUniqueIndex(pIdx) );\n      assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );\n      assert( IsUniqueIndex(pIndex) );\n\n      if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;\n      for(k=0; k<pIdx->nKeyCol; k++){\n        const char *z1;\n        const char *z2;\n        assert( pIdx->aiColumn[k]>=0 );\n        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;\n        z1 = pIdx->azColl[k];\n        z2 = pIndex->azColl[k];\n        if( sqlite3StrICmp(z1, z2) ) break;\n      }\n      if( k==pIdx->nKeyCol ){\n        if( pIdx->onError!=pIndex->onError ){\n          /* This constraint creates the same index as a previous\n          ** constraint specified somewhere in the CREATE TABLE statement.\n          ** However the ON CONFLICT clauses are different. If both this \n          ** constraint and the previous equivalent constraint have explicit\n          ** ON CONFLICT clauses this is an error. Otherwise, use the\n          ** explicitly specified behavior for the index.\n          */\n          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){\n            sqlite3ErrorMsg(pParse, \n                \"conflicting ON CONFLICT clauses specified\", 0);\n          }\n          if( pIdx->onError==OE_Default ){\n            pIdx->onError = pIndex->onError;\n          }\n        }\n        if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;\n        if( IN_RENAME_OBJECT ){\n          pIndex->pNext = pParse->pNewIndex;\n          pParse->pNewIndex = pIndex;\n          pIndex = 0;\n        }\n        goto exit_create_index;\n      }\n    }\n  }\n\n  if( !IN_RENAME_OBJECT ){\n\n    /* Link the new Index structure to its table and to the other\n    ** in-memory database structures. \n    */\n    assert( pParse->nErr==0 );\n    if( db->init.busy ){\n      Index *p;\n      assert( !IN_SPECIAL_PARSE );\n      assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );\n      if( pTblName!=0 ){\n        pIndex->tnum = db->init.newTnum;\n        if( sqlite3IndexHasDuplicateRootPage(pIndex) ){\n          sqlite3ErrorMsg(pParse, \"invalid rootpage\");\n          pParse->rc = SQLITE_CORRUPT_BKPT;\n          goto exit_create_index;\n        }\n      }\n      p = sqlite3HashInsert(&pIndex->pSchema->idxHash, \n          pIndex->zName, pIndex);\n      if( p ){\n        assert( p==pIndex );  /* Malloc must have failed */\n        sqlite3OomFault(db);\n        goto exit_create_index;\n      }\n      db->mDbFlags |= DBFLAG_SchemaChange;\n    }\n\n    /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the\n    ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then\n    ** emit code to allocate the index rootpage on disk and make an entry for\n    ** the index in the sqlite_master table and populate the index with\n    ** content.  But, do not do this if we are simply reading the sqlite_master\n    ** table to parse the schema, or if this index is the PRIMARY KEY index\n    ** of a WITHOUT ROWID table.\n    **\n    ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY\n    ** or UNIQUE index in a CREATE TABLE statement.  Since the table\n    ** has just been created, it contains no data and the index initialization\n    ** step can be skipped.\n    */\n    else if( HasRowid(pTab) || pTblName!=0 ){\n      Vdbe *v;\n      char *zStmt;\n      int iMem = ++pParse->nMem;\n\n      v = sqlite3GetVdbe(pParse);\n      if( v==0 ) goto exit_create_index;\n\n      sqlite3BeginWriteOperation(pParse, 1, iDb);\n\n      /* Create the rootpage for the index using CreateIndex. But before\n      ** doing so, code a Noop instruction and store its address in \n      ** Index.tnum. This is required in case this index is actually a \n      ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In \n      ** that case the convertToWithoutRowidTable() routine will replace\n      ** the Noop with a Goto to jump over the VDBE code generated below. */\n      pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);\n      sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);\n\n      /* Gather the complete text of the CREATE INDEX statement into\n      ** the zStmt variable\n      */\n      assert( pName!=0 || pStart==0 );\n      if( pStart ){\n        int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;\n        if( pName->z[n-1]==';' ) n--;\n        /* A named index with an explicit CREATE INDEX statement */\n        zStmt = sqlite3MPrintf(db, \"CREATE%s INDEX %.*s\",\n            onError==OE_None ? \"\" : \" UNIQUE\", n, pName->z);\n      }else{\n        /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */\n        /* zStmt = sqlite3MPrintf(\"\"); */\n        zStmt = 0;\n      }\n\n      /* Add an entry in sqlite_master for this index\n      */\n      sqlite3NestedParse(pParse, \n          \"INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);\",\n          db->aDb[iDb].zDbSName, MASTER_NAME,\n          pIndex->zName,\n          pTab->zName,\n          iMem,\n          zStmt\n          );\n      sqlite3DbFree(db, zStmt);\n\n      /* Fill the index with data and reparse the schema. Code an OP_Expire\n      ** to invalidate all pre-compiled statements.\n      */\n      if( pTblName ){\n        sqlite3RefillIndex(pParse, pIndex, iMem);\n        sqlite3ChangeCookie(pParse, iDb);\n        sqlite3VdbeAddParseSchemaOp(v, iDb,\n            sqlite3MPrintf(db, \"name='%q' AND type='index'\", pIndex->zName));\n        sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);\n      }\n\n      sqlite3VdbeJumpHere(v, pIndex->tnum);\n    }\n  }\n  if( db->init.busy || pTblName==0 ){\n    pIndex->pNext = pTab->pIndex;\n    pTab->pIndex = pIndex;\n    pIndex = 0;\n  }\n  else if( IN_RENAME_OBJECT ){\n    assert( pParse->pNewIndex==0 );\n    pParse->pNewIndex = pIndex;\n    pIndex = 0;\n  }\n\n  /* Clean up before exiting */\nexit_create_index:\n  if( pIndex ) sqlite3FreeIndex(db, pIndex);\n  if( pTab ){  /* Ensure all REPLACE indexes are at the end of the list */\n    Index **ppFrom = &pTab->pIndex;\n    Index *pThis;\n    for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){\n      Index *pNext;\n      if( pThis->onError!=OE_Replace ) continue;\n      while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){\n        *ppFrom = pNext;\n        pThis->pNext = pNext->pNext;\n        pNext->pNext = pThis;\n        ppFrom = &pNext->pNext;\n      }\n      break;\n    }\n  }\n  sqlite3ExprDelete(db, pPIWhere);\n  sqlite3ExprListDelete(db, pList);\n  sqlite3SrcListDelete(db, pTblName);\n  sqlite3DbFree(db, zName);\n}\n\n/*\n** Fill the Index.aiRowEst[] array with default information - information\n** to be used when we have not run the ANALYZE command.\n**\n** aiRowEst[0] is supposed to contain the number of elements in the index.\n** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the\n** number of rows in the table that match any particular value of the\n** first column of the index.  aiRowEst[2] is an estimate of the number\n** of rows that match any particular combination of the first 2 columns\n** of the index.  And so forth.  It must always be the case that\n*\n**           aiRowEst[N]<=aiRowEst[N-1]\n**           aiRowEst[N]>=1\n**\n** Apart from that, we have little to go on besides intuition as to\n** how aiRowEst[] should be initialized.  The numbers generated here\n** are based on typical values found in actual indices.\n*/\nSQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){\n  /*                10,  9,  8,  7,  6 */\n  LogEst aVal[] = { 33, 32, 30, 28, 26 };\n  LogEst *a = pIdx->aiRowLogEst;\n  int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);\n  int i;\n\n  /* Indexes with default row estimates should not have stat1 data */\n  assert( !pIdx->hasStat1 );\n\n  /* Set the first entry (number of rows in the index) to the estimated \n  ** number of rows in the table, or half the number of rows in the table\n  ** for a partial index.   But do not let the estimate drop below 10. */\n  a[0] = pIdx->pTable->nRowLogEst;\n  if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10;  assert( 10==sqlite3LogEst(2) );\n  if( a[0]<33 ) a[0] = 33;                  assert( 33==sqlite3LogEst(10) );\n\n  /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is\n  ** 6 and each subsequent value (if any) is 5.  */\n  memcpy(&a[1], aVal, nCopy*sizeof(LogEst));\n  for(i=nCopy+1; i<=pIdx->nKeyCol; i++){\n    a[i] = 23;                    assert( 23==sqlite3LogEst(5) );\n  }\n\n  assert( 0==sqlite3LogEst(1) );\n  if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;\n}\n\n/*\n** This routine will drop an existing named index.  This routine\n** implements the DROP INDEX statement.\n*/\nSQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){\n  Index *pIndex;\n  Vdbe *v;\n  sqlite3 *db = pParse->db;\n  int iDb;\n\n  assert( pParse->nErr==0 );   /* Never called with prior errors */\n  if( db->mallocFailed ){\n    goto exit_drop_index;\n  }\n  assert( pName->nSrc==1 );\n  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){\n    goto exit_drop_index;\n  }\n  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);\n  if( pIndex==0 ){\n    if( !ifExists ){\n      sqlite3ErrorMsg(pParse, \"no such index: %S\", pName, 0);\n    }else{\n      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);\n    }\n    pParse->checkSchema = 1;\n    goto exit_drop_index;\n  }\n  if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){\n    sqlite3ErrorMsg(pParse, \"index associated with UNIQUE \"\n      \"or PRIMARY KEY constraint cannot be dropped\", 0);\n    goto exit_drop_index;\n  }\n  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  {\n    int code = SQLITE_DROP_INDEX;\n    Table *pTab = pIndex->pTable;\n    const char *zDb = db->aDb[iDb].zDbSName;\n    const char *zTab = SCHEMA_TABLE(iDb);\n    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){\n      goto exit_drop_index;\n    }\n    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;\n    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){\n      goto exit_drop_index;\n    }\n  }\n#endif\n\n  /* Generate code to remove the index and from the master table */\n  v = sqlite3GetVdbe(pParse);\n  if( v ){\n    sqlite3BeginWriteOperation(pParse, 1, iDb);\n    sqlite3NestedParse(pParse,\n       \"DELETE FROM %Q.%s WHERE name=%Q AND type='index'\",\n       db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName\n    );\n    sqlite3ClearStatTables(pParse, iDb, \"idx\", pIndex->zName);\n    sqlite3ChangeCookie(pParse, iDb);\n    destroyRootPage(pParse, pIndex->tnum, iDb);\n    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);\n  }\n\nexit_drop_index:\n  sqlite3SrcListDelete(db, pName);\n}\n\n/*\n** pArray is a pointer to an array of objects. Each object in the\n** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()\n** to extend the array so that there is space for a new object at the end.\n**\n** When this function is called, *pnEntry contains the current size of\n** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes\n** in total).\n**\n** If the realloc() is successful (i.e. if no OOM condition occurs), the\n** space allocated for the new object is zeroed, *pnEntry updated to\n** reflect the new size of the array and a pointer to the new allocation\n** returned. *pIdx is set to the index of the new array entry in this case.\n**\n** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains\n** unchanged and a copy of pArray returned.\n*/\nSQLITE_PRIVATE void *sqlite3ArrayAllocate(\n  sqlite3 *db,      /* Connection to notify of malloc failures */\n  void *pArray,     /* Array of objects.  Might be reallocated */\n  int szEntry,      /* Size of each object in the array */\n  int *pnEntry,     /* Number of objects currently in use */\n  int *pIdx         /* Write the index of a new slot here */\n){\n  char *z;\n  sqlite3_int64 n = *pIdx = *pnEntry;\n  if( (n & (n-1))==0 ){\n    sqlite3_int64 sz = (n==0) ? 1 : 2*n;\n    void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);\n    if( pNew==0 ){\n      *pIdx = -1;\n      return pArray;\n    }\n    pArray = pNew;\n  }\n  z = (char*)pArray;\n  memset(&z[n * szEntry], 0, szEntry);\n  ++*pnEntry;\n  return pArray;\n}\n\n/*\n** Append a new element to the given IdList.  Create a new IdList if\n** need be.\n**\n** A new IdList is returned, or NULL if malloc() fails.\n*/\nSQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){\n  sqlite3 *db = pParse->db;\n  int i;\n  if( pList==0 ){\n    pList = sqlite3DbMallocZero(db, sizeof(IdList) );\n    if( pList==0 ) return 0;\n  }\n  pList->a = sqlite3ArrayAllocate(\n      db,\n      pList->a,\n      sizeof(pList->a[0]),\n      &pList->nId,\n      &i\n  );\n  if( i<0 ){\n    sqlite3IdListDelete(db, pList);\n    return 0;\n  }\n  pList->a[i].zName = sqlite3NameFromToken(db, pToken);\n  if( IN_RENAME_OBJECT && pList->a[i].zName ){\n    sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);\n  }\n  return pList;\n}\n\n/*\n** Delete an IdList.\n*/\nSQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){\n  int i;\n  if( pList==0 ) return;\n  for(i=0; i<pList->nId; i++){\n    sqlite3DbFree(db, pList->a[i].zName);\n  }\n  sqlite3DbFree(db, pList->a);\n  sqlite3DbFreeNN(db, pList);\n}\n\n/*\n** Return the index in pList of the identifier named zId.  Return -1\n** if not found.\n*/\nSQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){\n  int i;\n  if( pList==0 ) return -1;\n  for(i=0; i<pList->nId; i++){\n    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;\n  }\n  return -1;\n}\n\n/*\n** Maximum size of a SrcList object.\n** The SrcList object is used to represent the FROM clause of a\n** SELECT statement, and the query planner cannot deal with more\n** than 64 tables in a join.  So any value larger than 64 here\n** is sufficient for most uses.  Smaller values, like say 10, are\n** appropriate for small and memory-limited applications.\n*/\n#ifndef SQLITE_MAX_SRCLIST\n# define SQLITE_MAX_SRCLIST 200\n#endif\n\n/*\n** Expand the space allocated for the given SrcList object by\n** creating nExtra new slots beginning at iStart.  iStart is zero based.\n** New slots are zeroed.\n**\n** For example, suppose a SrcList initially contains two entries: A,B.\n** To append 3 new entries onto the end, do this:\n**\n**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);\n**\n** After the call above it would contain:  A, B, nil, nil, nil.\n** If the iStart argument had been 1 instead of 2, then the result\n** would have been:  A, nil, nil, nil, B.  To prepend the new slots,\n** the iStart value would be 0.  The result then would\n** be: nil, nil, nil, A, B.\n**\n** If a memory allocation fails or the SrcList becomes too large, leave\n** the original SrcList unchanged, return NULL, and leave an error message\n** in pParse.\n*/\nSQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(\n  Parse *pParse,     /* Parsing context into which errors are reported */\n  SrcList *pSrc,     /* The SrcList to be enlarged */\n  int nExtra,        /* Number of new slots to add to pSrc->a[] */\n  int iStart         /* Index in pSrc->a[] of first new slot */\n){\n  int i;\n\n  /* Sanity checking on calling parameters */\n  assert( iStart>=0 );\n  assert( nExtra>=1 );\n  assert( pSrc!=0 );\n  assert( iStart<=pSrc->nSrc );\n\n  /* Allocate additional space if needed */\n  if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){\n    SrcList *pNew;\n    sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;\n    sqlite3 *db = pParse->db;\n\n    if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){\n      sqlite3ErrorMsg(pParse, \"too many FROM clause terms, max: %d\",\n                      SQLITE_MAX_SRCLIST);\n      return 0;\n    }\n    if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;\n    pNew = sqlite3DbRealloc(db, pSrc,\n               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );\n    if( pNew==0 ){\n      assert( db->mallocFailed );\n      return 0;\n    }\n    pSrc = pNew;\n    pSrc->nAlloc = nAlloc;\n  }\n\n  /* Move existing slots that come after the newly inserted slots\n  ** out of the way */\n  for(i=pSrc->nSrc-1; i>=iStart; i--){\n    pSrc->a[i+nExtra] = pSrc->a[i];\n  }\n  pSrc->nSrc += nExtra;\n\n  /* Zero the newly allocated slots */\n  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);\n  for(i=iStart; i<iStart+nExtra; i++){\n    pSrc->a[i].iCursor = -1;\n  }\n\n  /* Return a pointer to the enlarged SrcList */\n  return pSrc;\n}\n\n\n/*\n** Append a new table name to the given SrcList.  Create a new SrcList if\n** need be.  A new entry is created in the SrcList even if pTable is NULL.\n**\n** A SrcList is returned, or NULL if there is an OOM error or if the\n** SrcList grows to large.  The returned\n** SrcList might be the same as the SrcList that was input or it might be\n** a new one.  If an OOM error does occurs, then the prior value of pList\n** that is input to this routine is automatically freed.\n**\n** If pDatabase is not null, it means that the table has an optional\n** database name prefix.  Like this:  \"database.table\".  The pDatabase\n** points to the table name and the pTable points to the database name.\n** The SrcList.a[].zName field is filled with the table name which might\n** come from pTable (if pDatabase is NULL) or from pDatabase.  \n** SrcList.a[].zDatabase is filled with the database name from pTable,\n** or with NULL if no database is specified.\n**\n** In other words, if call like this:\n**\n**         sqlite3SrcListAppend(D,A,B,0);\n**\n** Then B is a table name and the database name is unspecified.  If called\n** like this:\n**\n**         sqlite3SrcListAppend(D,A,B,C);\n**\n** Then C is the table name and B is the database name.  If C is defined\n** then so is B.  In other words, we never have a case where:\n**\n**         sqlite3SrcListAppend(D,A,0,C);\n**\n** Both pTable and pDatabase are assumed to be quoted.  They are dequoted\n** before being added to the SrcList.\n*/\nSQLITE_PRIVATE SrcList *sqlite3SrcListAppend(\n  Parse *pParse,      /* Parsing context, in which errors are reported */\n  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */\n  Token *pTable,      /* Table to append */\n  Token *pDatabase    /* Database of the table */\n){\n  struct SrcList_item *pItem;\n  sqlite3 *db;\n  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */\n  assert( pParse!=0 );\n  assert( pParse->db!=0 );\n  db = pParse->db;\n  if( pList==0 ){\n    pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );\n    if( pList==0 ) return 0;\n    pList->nAlloc = 1;\n    pList->nSrc = 1;\n    memset(&pList->a[0], 0, sizeof(pList->a[0]));\n    pList->a[0].iCursor = -1;\n  }else{\n    SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);\n    if( pNew==0 ){\n      sqlite3SrcListDelete(db, pList);\n      return 0;\n    }else{\n      pList = pNew;\n    }\n  }\n  pItem = &pList->a[pList->nSrc-1];\n  if( pDatabase && pDatabase->z==0 ){\n    pDatabase = 0;\n  }\n  if( pDatabase ){\n    pItem->zName = sqlite3NameFromToken(db, pDatabase);\n    pItem->zDatabase = sqlite3NameFromToken(db, pTable);\n  }else{\n    pItem->zName = sqlite3NameFromToken(db, pTable);\n    pItem->zDatabase = 0;\n  }\n  return pList;\n}\n\n/*\n** Assign VdbeCursor index numbers to all tables in a SrcList\n*/\nSQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){\n  int i;\n  struct SrcList_item *pItem;\n  assert(pList || pParse->db->mallocFailed );\n  if( pList ){\n    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){\n      if( pItem->iCursor>=0 ) break;\n      pItem->iCursor = pParse->nTab++;\n      if( pItem->pSelect ){\n        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);\n      }\n    }\n  }\n}\n\n/*\n** Delete an entire SrcList including all its substructure.\n*/\nSQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){\n  int i;\n  struct SrcList_item *pItem;\n  if( pList==0 ) return;\n  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){\n    sqlite3DbFree(db, pItem->zDatabase);\n    sqlite3DbFree(db, pItem->zName);\n    sqlite3DbFree(db, pItem->zAlias);\n    if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);\n    if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);\n    sqlite3DeleteTable(db, pItem->pTab);\n    sqlite3SelectDelete(db, pItem->pSelect);\n    sqlite3ExprDelete(db, pItem->pOn);\n    sqlite3IdListDelete(db, pItem->pUsing);\n  }\n  sqlite3DbFreeNN(db, pList);\n}\n\n/*\n** This routine is called by the parser to add a new term to the\n** end of a growing FROM clause.  The \"p\" parameter is the part of\n** the FROM clause that has already been constructed.  \"p\" is NULL\n** if this is the first term of the FROM clause.  pTable and pDatabase\n** are the name of the table and database named in the FROM clause term.\n** pDatabase is NULL if the database name qualifier is missing - the\n** usual case.  If the term has an alias, then pAlias points to the\n** alias token.  If the term is a subquery, then pSubquery is the\n** SELECT statement that the subquery encodes.  The pTable and\n** pDatabase parameters are NULL for subqueries.  The pOn and pUsing\n** parameters are the content of the ON and USING clauses.\n**\n** Return a new SrcList which encodes is the FROM with the new\n** term added.\n*/\nSQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(\n  Parse *pParse,          /* Parsing context */\n  SrcList *p,             /* The left part of the FROM clause already seen */\n  Token *pTable,          /* Name of the table to add to the FROM clause */\n  Token *pDatabase,       /* Name of the database containing pTable */\n  Token *pAlias,          /* The right-hand side of the AS subexpression */\n  Select *pSubquery,      /* A subquery used in place of a table name */\n  Expr *pOn,              /* The ON clause of a join */\n  IdList *pUsing          /* The USING clause of a join */\n){\n  struct SrcList_item *pItem;\n  sqlite3 *db = pParse->db;\n  if( !p && (pOn || pUsing) ){\n    sqlite3ErrorMsg(pParse, \"a JOIN clause is required before %s\", \n      (pOn ? \"ON\" : \"USING\")\n    );\n    goto append_from_error;\n  }\n  p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);\n  if( p==0 ){\n    goto append_from_error;\n  }\n  assert( p->nSrc>0 );\n  pItem = &p->a[p->nSrc-1];\n  assert( (pTable==0)==(pDatabase==0) );\n  assert( pItem->zName==0 || pDatabase!=0 );\n  if( IN_RENAME_OBJECT && pItem->zName ){\n    Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;\n    sqlite3RenameTokenMap(pParse, pItem->zName, pToken);\n  }\n  assert( pAlias!=0 );\n  if( pAlias->n ){\n    pItem->zAlias = sqlite3NameFromToken(db, pAlias);\n  }\n  pItem->pSelect = pSubquery;\n  pItem->pOn = pOn;\n  pItem->pUsing = pUsing;\n  return p;\n\n append_from_error:\n  assert( p==0 );\n  sqlite3ExprDelete(db, pOn);\n  sqlite3IdListDelete(db, pUsing);\n  sqlite3SelectDelete(db, pSubquery);\n  return 0;\n}\n\n/*\n** Add an INDEXED BY or NOT INDEXED clause to the most recently added \n** element of the source-list passed as the second argument.\n*/\nSQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){\n  assert( pIndexedBy!=0 );\n  if( p && pIndexedBy->n>0 ){\n    struct SrcList_item *pItem;\n    assert( p->nSrc>0 );\n    pItem = &p->a[p->nSrc-1];\n    assert( pItem->fg.notIndexed==0 );\n    assert( pItem->fg.isIndexedBy==0 );\n    assert( pItem->fg.isTabFunc==0 );\n    if( pIndexedBy->n==1 && !pIndexedBy->z ){\n      /* A \"NOT INDEXED\" clause was supplied. See parse.y \n      ** construct \"indexed_opt\" for details. */\n      pItem->fg.notIndexed = 1;\n    }else{\n      pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);\n      pItem->fg.isIndexedBy = 1;\n    }\n  }\n}\n\n/*\n** Add the list of function arguments to the SrcList entry for a\n** table-valued-function.\n*/\nSQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){\n  if( p ){\n    struct SrcList_item *pItem = &p->a[p->nSrc-1];\n    assert( pItem->fg.notIndexed==0 );\n    assert( pItem->fg.isIndexedBy==0 );\n    assert( pItem->fg.isTabFunc==0 );\n    pItem->u1.pFuncArg = pList;\n    pItem->fg.isTabFunc = 1;\n  }else{\n    sqlite3ExprListDelete(pParse->db, pList);\n  }\n}\n\n/*\n** When building up a FROM clause in the parser, the join operator\n** is initially attached to the left operand.  But the code generator\n** expects the join operator to be on the right operand.  This routine\n** Shifts all join operators from left to right for an entire FROM\n** clause.\n**\n** Example: Suppose the join is like this:\n**\n**           A natural cross join B\n**\n** The operator is \"natural cross join\".  The A and B operands are stored\n** in p->a[0] and p->a[1], respectively.  The parser initially stores the\n** operator with A.  This routine shifts that operator over to B.\n*/\nSQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){\n  if( p ){\n    int i;\n    for(i=p->nSrc-1; i>0; i--){\n      p->a[i].fg.jointype = p->a[i-1].fg.jointype;\n    }\n    p->a[0].fg.jointype = 0;\n  }\n}\n\n/*\n** Generate VDBE code for a BEGIN statement.\n*/\nSQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){\n  sqlite3 *db;\n  Vdbe *v;\n  int i;\n\n  assert( pParse!=0 );\n  db = pParse->db;\n  assert( db!=0 );\n  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, \"BEGIN\", 0, 0) ){\n    return;\n  }\n  v = sqlite3GetVdbe(pParse);\n  if( !v ) return;\n  if( type!=TK_DEFERRED ){\n    for(i=0; i<db->nDb; i++){\n      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);\n      sqlite3VdbeUsesBtree(v, i);\n    }\n  }\n  sqlite3VdbeAddOp0(v, OP_AutoCommit);\n}\n\n/*\n** Generate VDBE code for a COMMIT or ROLLBACK statement.\n** Code for ROLLBACK is generated if eType==TK_ROLLBACK.  Otherwise\n** code is generated for a COMMIT.\n*/\nSQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){\n  Vdbe *v;\n  int isRollback;\n\n  assert( pParse!=0 );\n  assert( pParse->db!=0 );\n  assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );\n  isRollback = eType==TK_ROLLBACK;\n  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, \n       isRollback ? \"ROLLBACK\" : \"COMMIT\", 0, 0) ){\n    return;\n  }\n  v = sqlite3GetVdbe(pParse);\n  if( v ){\n    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);\n  }\n}\n\n/*\n** This function is called by the parser when it parses a command to create,\n** release or rollback an SQL savepoint. \n*/\nSQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){\n  char *zName = sqlite3NameFromToken(pParse->db, pName);\n  if( zName ){\n    Vdbe *v = sqlite3GetVdbe(pParse);\n#ifndef SQLITE_OMIT_AUTHORIZATION\n    static const char * const az[] = { \"BEGIN\", \"RELEASE\", \"ROLLBACK\" };\n    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );\n#endif\n    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){\n      sqlite3DbFree(pParse->db, zName);\n      return;\n    }\n    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);\n  }\n}\n\n/*\n** Make sure the TEMP database is open and available for use.  Return\n** the number of errors.  Leave any error messages in the pParse structure.\n*/\nSQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){\n  sqlite3 *db = pParse->db;\n  if( db->aDb[1].pBt==0 && !pParse->explain ){\n    int rc;\n    Btree *pBt;\n    static const int flags = \n          SQLITE_OPEN_READWRITE |\n          SQLITE_OPEN_CREATE |\n          SQLITE_OPEN_EXCLUSIVE |\n          SQLITE_OPEN_DELETEONCLOSE |\n          SQLITE_OPEN_TEMP_DB;\n\n    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);\n    if( rc!=SQLITE_OK ){\n      sqlite3ErrorMsg(pParse, \"unable to open a temporary database \"\n        \"file for storing temporary tables\");\n      pParse->rc = rc;\n      return 1;\n    }\n    db->aDb[1].pBt = pBt;\n    assert( db->aDb[1].pSchema );\n    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){\n      sqlite3OomFault(db);\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/*\n** Record the fact that the schema cookie will need to be verified\n** for database iDb.  The code to actually verify the schema cookie\n** will occur at the end of the top-level VDBE and will be generated\n** later, by sqlite3FinishCoding().\n*/\nSQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){\n  Parse *pToplevel = sqlite3ParseToplevel(pParse);\n\n  assert( iDb>=0 && iDb<pParse->db->nDb );\n  assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );\n  assert( iDb<SQLITE_MAX_ATTACHED+2 );\n  assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );\n  if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){\n    DbMaskSet(pToplevel->cookieMask, iDb);\n    if( !OMIT_TEMPDB && iDb==1 ){\n      sqlite3OpenTempDatabase(pToplevel);\n    }\n  }\n}\n\n/*\n** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each \n** attached database. Otherwise, invoke it for the database named zDb only.\n*/\nSQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){\n  sqlite3 *db = pParse->db;\n  int i;\n  for(i=0; i<db->nDb; i++){\n    Db *pDb = &db->aDb[i];\n    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){\n      sqlite3CodeVerifySchema(pParse, i);\n    }\n  }\n}\n\n/*\n** Generate VDBE code that prepares for doing an operation that\n** might change the database.\n**\n** This routine starts a new transaction if we are not already within\n** a transaction.  If we are already within a transaction, then a checkpoint\n** is set if the setStatement parameter is true.  A checkpoint should\n** be set for operations that might fail (due to a constraint) part of\n** the way through and which will need to undo some writes without having to\n** rollback the whole transaction.  For operations where all constraints\n** can be checked before any changes are made to the database, it is never\n** necessary to undo a write and the checkpoint should not be set.\n*/\nSQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){\n  Parse *pToplevel = sqlite3ParseToplevel(pParse);\n  sqlite3CodeVerifySchema(pParse, iDb);\n  DbMaskSet(pToplevel->writeMask, iDb);\n  pToplevel->isMultiWrite |= setStatement;\n}\n\n/*\n** Indicate that the statement currently under construction might write\n** more than one entry (example: deleting one row then inserting another,\n** inserting multiple rows in a table, or inserting a row and index entries.)\n** If an abort occurs after some of these writes have completed, then it will\n** be necessary to undo the completed writes.\n*/\nSQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){\n  Parse *pToplevel = sqlite3ParseToplevel(pParse);\n  pToplevel->isMultiWrite = 1;\n}\n\n/* \n** The code generator calls this routine if is discovers that it is\n** possible to abort a statement prior to completion.  In order to \n** perform this abort without corrupting the database, we need to make\n** sure that the statement is protected by a statement transaction.\n**\n** Technically, we only need to set the mayAbort flag if the\n** isMultiWrite flag was previously set.  There is a time dependency\n** such that the abort must occur after the multiwrite.  This makes\n** some statements involving the REPLACE conflict resolution algorithm\n** go a little faster.  But taking advantage of this time dependency\n** makes it more difficult to prove that the code is correct (in \n** particular, it prevents us from writing an effective\n** implementation of sqlite3AssertMayAbort()) and so we have chosen\n** to take the safe route and skip the optimization.\n*/\nSQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){\n  Parse *pToplevel = sqlite3ParseToplevel(pParse);\n  pToplevel->mayAbort = 1;\n}\n\n/*\n** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT\n** error. The onError parameter determines which (if any) of the statement\n** and/or current transaction is rolled back.\n*/\nSQLITE_PRIVATE void sqlite3HaltConstraint(\n  Parse *pParse,    /* Parsing context */\n  int errCode,      /* extended error code */\n  int onError,      /* Constraint type */\n  char *p4,         /* Error message */\n  i8 p4type,        /* P4_STATIC or P4_TRANSIENT */\n  u8 p5Errmsg       /* P5_ErrMsg type */\n){\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested );\n  if( onError==OE_Abort ){\n    sqlite3MayAbort(pParse);\n  }\n  sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);\n  sqlite3VdbeChangeP5(v, p5Errmsg);\n}\n\n/*\n** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.\n*/\nSQLITE_PRIVATE void sqlite3UniqueConstraint(\n  Parse *pParse,    /* Parsing context */\n  int onError,      /* Constraint type */\n  Index *pIdx       /* The index that triggers the constraint */\n){\n  char *zErr;\n  int j;\n  StrAccum errMsg;\n  Table *pTab = pIdx->pTable;\n\n  sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, \n                      pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);\n  if( pIdx->aColExpr ){\n    sqlite3_str_appendf(&errMsg, \"index '%q'\", pIdx->zName);\n  }else{\n    for(j=0; j<pIdx->nKeyCol; j++){\n      char *zCol;\n      assert( pIdx->aiColumn[j]>=0 );\n      zCol = pTab->aCol[pIdx->aiColumn[j]].zName;\n      if( j ) sqlite3_str_append(&errMsg, \", \", 2);\n      sqlite3_str_appendall(&errMsg, pTab->zName);\n      sqlite3_str_append(&errMsg, \".\", 1);\n      sqlite3_str_appendall(&errMsg, zCol);\n    }\n  }\n  zErr = sqlite3StrAccumFinish(&errMsg);\n  sqlite3HaltConstraint(pParse, \n    IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY \n                            : SQLITE_CONSTRAINT_UNIQUE,\n    onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);\n}\n\n\n/*\n** Code an OP_Halt due to non-unique rowid.\n*/\nSQLITE_PRIVATE void sqlite3RowidConstraint(\n  Parse *pParse,    /* Parsing context */\n  int onError,      /* Conflict resolution algorithm */\n  Table *pTab       /* The table with the non-unique rowid */ \n){\n  char *zMsg;\n  int rc;\n  if( pTab->iPKey>=0 ){\n    zMsg = sqlite3MPrintf(pParse->db, \"%s.%s\", pTab->zName,\n                          pTab->aCol[pTab->iPKey].zName);\n    rc = SQLITE_CONSTRAINT_PRIMARYKEY;\n  }else{\n    zMsg = sqlite3MPrintf(pParse->db, \"%s.rowid\", pTab->zName);\n    rc = SQLITE_CONSTRAINT_ROWID;\n  }\n  sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,\n                        P5_ConstraintUnique);\n}\n\n/*\n** Check to see if pIndex uses the collating sequence pColl.  Return\n** true if it does and false if it does not.\n*/\n#ifndef SQLITE_OMIT_REINDEX\nstatic int collationMatch(const char *zColl, Index *pIndex){\n  int i;\n  assert( zColl!=0 );\n  for(i=0; i<pIndex->nColumn; i++){\n    const char *z = pIndex->azColl[i];\n    assert( z!=0 || pIndex->aiColumn[i]<0 );\n    if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){\n      return 1;\n    }\n  }\n  return 0;\n}\n#endif\n\n/*\n** Recompute all indices of pTab that use the collating sequence pColl.\n** If pColl==0 then recompute all indices of pTab.\n*/\n#ifndef SQLITE_OMIT_REINDEX\nstatic void reindexTable(Parse *pParse, Table *pTab, char const *zColl){\n  if( !IsVirtual(pTab) ){\n    Index *pIndex;              /* An index associated with pTab */\n\n    for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){\n      if( zColl==0 || collationMatch(zColl, pIndex) ){\n        int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n        sqlite3BeginWriteOperation(pParse, 0, iDb);\n        sqlite3RefillIndex(pParse, pIndex, -1);\n      }\n    }\n  }\n}\n#endif\n\n/*\n** Recompute all indices of all tables in all databases where the\n** indices use the collating sequence pColl.  If pColl==0 then recompute\n** all indices everywhere.\n*/\n#ifndef SQLITE_OMIT_REINDEX\nstatic void reindexDatabases(Parse *pParse, char const *zColl){\n  Db *pDb;                    /* A single database */\n  int iDb;                    /* The database index number */\n  sqlite3 *db = pParse->db;   /* The database connection */\n  HashElem *k;                /* For looping over tables in pDb */\n  Table *pTab;                /* A table in the database */\n\n  assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */\n  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){\n    assert( pDb!=0 );\n    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){\n      pTab = (Table*)sqliteHashData(k);\n      reindexTable(pParse, pTab, zColl);\n    }\n  }\n}\n#endif\n\n/*\n** Generate code for the REINDEX command.\n**\n**        REINDEX                            -- 1\n**        REINDEX  <collation>               -- 2\n**        REINDEX  ?<database>.?<tablename>  -- 3\n**        REINDEX  ?<database>.?<indexname>  -- 4\n**\n** Form 1 causes all indices in all attached databases to be rebuilt.\n** Form 2 rebuilds all indices in all databases that use the named\n** collating function.  Forms 3 and 4 rebuild the named index or all\n** indices associated with the named table.\n*/\n#ifndef SQLITE_OMIT_REINDEX\nSQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){\n  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */\n  char *z;                    /* Name of a table or index */\n  const char *zDb;            /* Name of the database */\n  Table *pTab;                /* A table in the database */\n  Index *pIndex;              /* An index associated with pTab */\n  int iDb;                    /* The database index number */\n  sqlite3 *db = pParse->db;   /* The database connection */\n  Token *pObjName;            /* Name of the table or index to be reindexed */\n\n  /* Read the database schema. If an error occurs, leave an error message\n  ** and code in pParse and return NULL. */\n  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){\n    return;\n  }\n\n  if( pName1==0 ){\n    reindexDatabases(pParse, 0);\n    return;\n  }else if( NEVER(pName2==0) || pName2->z==0 ){\n    char *zColl;\n    assert( pName1->z );\n    zColl = sqlite3NameFromToken(pParse->db, pName1);\n    if( !zColl ) return;\n    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);\n    if( pColl ){\n      reindexDatabases(pParse, zColl);\n      sqlite3DbFree(db, zColl);\n      return;\n    }\n    sqlite3DbFree(db, zColl);\n  }\n  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);\n  if( iDb<0 ) return;\n  z = sqlite3NameFromToken(db, pObjName);\n  if( z==0 ) return;\n  zDb = db->aDb[iDb].zDbSName;\n  pTab = sqlite3FindTable(db, z, zDb);\n  if( pTab ){\n    reindexTable(pParse, pTab, 0);\n    sqlite3DbFree(db, z);\n    return;\n  }\n  pIndex = sqlite3FindIndex(db, z, zDb);\n  sqlite3DbFree(db, z);\n  if( pIndex ){\n    sqlite3BeginWriteOperation(pParse, 0, iDb);\n    sqlite3RefillIndex(pParse, pIndex, -1);\n    return;\n  }\n  sqlite3ErrorMsg(pParse, \"unable to identify the object to be reindexed\");\n}\n#endif\n\n/*\n** Return a KeyInfo structure that is appropriate for the given Index.\n**\n** The caller should invoke sqlite3KeyInfoUnref() on the returned object\n** when it has finished using it.\n*/\nSQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){\n  int i;\n  int nCol = pIdx->nColumn;\n  int nKey = pIdx->nKeyCol;\n  KeyInfo *pKey;\n  if( pParse->nErr ) return 0;\n  if( pIdx->uniqNotNull ){\n    pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);\n  }else{\n    pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);\n  }\n  if( pKey ){\n    assert( sqlite3KeyInfoIsWriteable(pKey) );\n    for(i=0; i<nCol; i++){\n      const char *zColl = pIdx->azColl[i];\n      pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :\n                        sqlite3LocateCollSeq(pParse, zColl);\n      pKey->aSortFlags[i] = pIdx->aSortOrder[i];\n      assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );\n    }\n    if( pParse->nErr ){\n      assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );\n      if( pIdx->bNoQuery==0 ){\n        /* Deactivate the index because it contains an unknown collating\n        ** sequence.  The only way to reactive the index is to reload the\n        ** schema.  Adding the missing collating sequence later does not\n        ** reactive the index.  The application had the chance to register\n        ** the missing index using the collation-needed callback.  For\n        ** simplicity, SQLite will not give the application a second chance.\n        */\n        pIdx->bNoQuery = 1;\n        pParse->rc = SQLITE_ERROR_RETRY;\n      }\n      sqlite3KeyInfoUnref(pKey);\n      pKey = 0;\n    }\n  }\n  return pKey;\n}\n\n#ifndef SQLITE_OMIT_CTE\n/* \n** This routine is invoked once per CTE by the parser while parsing a \n** WITH clause. \n*/\nSQLITE_PRIVATE With *sqlite3WithAdd(\n  Parse *pParse,          /* Parsing context */\n  With *pWith,            /* Existing WITH clause, or NULL */\n  Token *pName,           /* Name of the common-table */\n  ExprList *pArglist,     /* Optional column name list for the table */\n  Select *pQuery          /* Query used to initialize the table */\n){\n  sqlite3 *db = pParse->db;\n  With *pNew;\n  char *zName;\n\n  /* Check that the CTE name is unique within this WITH clause. If\n  ** not, store an error in the Parse structure. */\n  zName = sqlite3NameFromToken(pParse->db, pName);\n  if( zName && pWith ){\n    int i;\n    for(i=0; i<pWith->nCte; i++){\n      if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){\n        sqlite3ErrorMsg(pParse, \"duplicate WITH table name: %s\", zName);\n      }\n    }\n  }\n\n  if( pWith ){\n    sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);\n    pNew = sqlite3DbRealloc(db, pWith, nByte);\n  }else{\n    pNew = sqlite3DbMallocZero(db, sizeof(*pWith));\n  }\n  assert( (pNew!=0 && zName!=0) || db->mallocFailed );\n\n  if( db->mallocFailed ){\n    sqlite3ExprListDelete(db, pArglist);\n    sqlite3SelectDelete(db, pQuery);\n    sqlite3DbFree(db, zName);\n    pNew = pWith;\n  }else{\n    pNew->a[pNew->nCte].pSelect = pQuery;\n    pNew->a[pNew->nCte].pCols = pArglist;\n    pNew->a[pNew->nCte].zName = zName;\n    pNew->a[pNew->nCte].zCteErr = 0;\n    pNew->nCte++;\n  }\n\n  return pNew;\n}\n\n/*\n** Free the contents of the With object passed as the second argument.\n*/\nSQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){\n  if( pWith ){\n    int i;\n    for(i=0; i<pWith->nCte; i++){\n      struct Cte *pCte = &pWith->a[i];\n      sqlite3ExprListDelete(db, pCte->pCols);\n      sqlite3SelectDelete(db, pCte->pSelect);\n      sqlite3DbFree(db, pCte->zName);\n    }\n    sqlite3DbFree(db, pWith);\n  }\n}\n#endif /* !defined(SQLITE_OMIT_CTE) */\n\n/************** End of build.c ***********************************************/\n/************** Begin file callback.c ****************************************/\n/*\n** 2005 May 23 \n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains functions used to access the internal hash tables\n** of user defined functions and collation sequences.\n*/\n\n/* #include \"sqliteInt.h\" */\n\n/*\n** Invoke the 'collation needed' callback to request a collation sequence\n** in the encoding enc of name zName, length nName.\n*/\nstatic void callCollNeeded(sqlite3 *db, int enc, const char *zName){\n  assert( !db->xCollNeeded || !db->xCollNeeded16 );\n  if( db->xCollNeeded ){\n    char *zExternal = sqlite3DbStrDup(db, zName);\n    if( !zExternal ) return;\n    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);\n    sqlite3DbFree(db, zExternal);\n  }\n#ifndef SQLITE_OMIT_UTF16\n  if( db->xCollNeeded16 ){\n    char const *zExternal;\n    sqlite3_value *pTmp = sqlite3ValueNew(db);\n    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);\n    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);\n    if( zExternal ){\n      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);\n    }\n    sqlite3ValueFree(pTmp);\n  }\n#endif\n}\n\n/*\n** This routine is called if the collation factory fails to deliver a\n** collation function in the best encoding but there may be other versions\n** of this collation function (for other text encodings) available. Use one\n** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if\n** possible.\n*/\nstatic int synthCollSeq(sqlite3 *db, CollSeq *pColl){\n  CollSeq *pColl2;\n  char *z = pColl->zName;\n  int i;\n  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };\n  for(i=0; i<3; i++){\n    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);\n    if( pColl2->xCmp!=0 ){\n      memcpy(pColl, pColl2, sizeof(CollSeq));\n      pColl->xDel = 0;         /* Do not copy the destructor */\n      return SQLITE_OK;\n    }\n  }\n  return SQLITE_ERROR;\n}\n\n/*\n** This routine is called on a collation sequence before it is used to\n** check that it is defined. An undefined collation sequence exists when\n** a database is loaded that contains references to collation sequences\n** that have not been defined by sqlite3_create_collation() etc.\n**\n** If required, this routine calls the 'collation needed' callback to\n** request a definition of the collating sequence. If this doesn't work, \n** an equivalent collating sequence that uses a text encoding different\n** from the main database is substituted, if one is available.\n*/\nSQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){\n  if( pColl && pColl->xCmp==0 ){\n    const char *zName = pColl->zName;\n    sqlite3 *db = pParse->db;\n    CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);\n    if( !p ){\n      return SQLITE_ERROR;\n    }\n    assert( p==pColl );\n  }\n  return SQLITE_OK;\n}\n\n\n\n/*\n** Locate and return an entry from the db.aCollSeq hash table. If the entry\n** specified by zName and nName is not found and parameter 'create' is\n** true, then create a new entry. Otherwise return NULL.\n**\n** Each pointer stored in the sqlite3.aCollSeq hash table contains an\n** array of three CollSeq structures. The first is the collation sequence\n** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.\n**\n** Stored immediately after the three collation sequences is a copy of\n** the collation sequence name. A pointer to this string is stored in\n** each collation sequence structure.\n*/\nstatic CollSeq *findCollSeqEntry(\n  sqlite3 *db,          /* Database connection */\n  const char *zName,    /* Name of the collating sequence */\n  int create            /* Create a new entry if true */\n){\n  CollSeq *pColl;\n  pColl = sqlite3HashFind(&db->aCollSeq, zName);\n\n  if( 0==pColl && create ){\n    int nName = sqlite3Strlen30(zName) + 1;\n    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName);\n    if( pColl ){\n      CollSeq *pDel = 0;\n      pColl[0].zName = (char*)&pColl[3];\n      pColl[0].enc = SQLITE_UTF8;\n      pColl[1].zName = (char*)&pColl[3];\n      pColl[1].enc = SQLITE_UTF16LE;\n      pColl[2].zName = (char*)&pColl[3];\n      pColl[2].enc = SQLITE_UTF16BE;\n      memcpy(pColl[0].zName, zName, nName);\n      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);\n\n      /* If a malloc() failure occurred in sqlite3HashInsert(), it will \n      ** return the pColl pointer to be deleted (because it wasn't added\n      ** to the hash table).\n      */\n      assert( pDel==0 || pDel==pColl );\n      if( pDel!=0 ){\n        sqlite3OomFault(db);\n        sqlite3DbFree(db, pDel);\n        pColl = 0;\n      }\n    }\n  }\n  return pColl;\n}\n\n/*\n** Parameter zName points to a UTF-8 encoded string nName bytes long.\n** Return the CollSeq* pointer for the collation sequence named zName\n** for the encoding 'enc' from the database 'db'.\n**\n** If the entry specified is not found and 'create' is true, then create a\n** new entry.  Otherwise return NULL.\n**\n** A separate function sqlite3LocateCollSeq() is a wrapper around\n** this routine.  sqlite3LocateCollSeq() invokes the collation factory\n** if necessary and generates an error message if the collating sequence\n** cannot be found.\n**\n** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()\n*/\nSQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(\n  sqlite3 *db,          /* Database connection to search */\n  u8 enc,               /* Desired text encoding */\n  const char *zName,    /* Name of the collating sequence.  Might be NULL */\n  int create            /* True to create CollSeq if doesn't already exist */\n){\n  CollSeq *pColl;\n  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );\n  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );\n  if( zName ){\n    pColl = findCollSeqEntry(db, zName, create);\n    if( pColl ) pColl += enc-1;\n  }else{\n    pColl = db->pDfltColl;\n  }\n  return pColl;\n}\n\n/*\n** Change the text encoding for a database connection. This means that\n** the pDfltColl must change as well.\n*/\nSQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8 enc){\n  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );\n  db->enc = enc;\n  /* EVIDENCE-OF: R-08308-17224 The default collating function for all\n  ** strings is BINARY. \n  */\n  db->pDfltColl = sqlite3FindCollSeq(db, enc, sqlite3StrBINARY, 0);\n}\n\n/*\n** This function is responsible for invoking the collation factory callback\n** or substituting a collation sequence of a different encoding when the\n** requested collation sequence is not available in the desired encoding.\n** \n** If it is not NULL, then pColl must point to the database native encoding \n** collation sequence with name zName, length nName.\n**\n** The return value is either the collation sequence to be used in database\n** db for collation type name zName, length nName, or NULL, if no collation\n** sequence can be found.  If no collation is found, leave an error message.\n**\n** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()\n*/\nSQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(\n  Parse *pParse,        /* Parsing context */\n  u8 enc,               /* The desired encoding for the collating sequence */\n  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */\n  const char *zName     /* Collating sequence name */\n){\n  CollSeq *p;\n  sqlite3 *db = pParse->db;\n\n  p = pColl;\n  if( !p ){\n    p = sqlite3FindCollSeq(db, enc, zName, 0);\n  }\n  if( !p || !p->xCmp ){\n    /* No collation sequence of this type for this encoding is registered.\n    ** Call the collation factory to see if it can supply us with one.\n    */\n    callCollNeeded(db, enc, zName);\n    p = sqlite3FindCollSeq(db, enc, zName, 0);\n  }\n  if( p && !p->xCmp && synthCollSeq(db, p) ){\n    p = 0;\n  }\n  assert( !p || p->xCmp );\n  if( p==0 ){\n    sqlite3ErrorMsg(pParse, \"no such collation sequence: %s\", zName);\n    pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ;\n  }\n  return p;\n}\n\n/*\n** This function returns the collation sequence for database native text\n** encoding identified by the string zName.\n**\n** If the requested collation sequence is not available, or not available\n** in the database native encoding, the collation factory is invoked to\n** request it. If the collation factory does not supply such a sequence,\n** and the sequence is available in another text encoding, then that is\n** returned instead.\n**\n** If no versions of the requested collations sequence are available, or\n** another error occurs, NULL is returned and an error message written into\n** pParse.\n**\n** This routine is a wrapper around sqlite3FindCollSeq().  This routine\n** invokes the collation factory if the named collation cannot be found\n** and generates an error message.\n**\n** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()\n*/\nSQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){\n  sqlite3 *db = pParse->db;\n  u8 enc = ENC(db);\n  u8 initbusy = db->init.busy;\n  CollSeq *pColl;\n\n  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);\n  if( !initbusy && (!pColl || !pColl->xCmp) ){\n    pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);\n  }\n\n  return pColl;\n}\n\n/* During the search for the best function definition, this procedure\n** is called to test how well the function passed as the first argument\n** matches the request for a function with nArg arguments in a system\n** that uses encoding enc. The value returned indicates how well the\n** request is matched. A higher value indicates a better match.\n**\n** If nArg is -1 that means to only return a match (non-zero) if p->nArg\n** is also -1.  In other words, we are searching for a function that\n** takes a variable number of arguments.\n**\n** If nArg is -2 that means that we are searching for any function \n** regardless of the number of arguments it uses, so return a positive\n** match score for any\n**\n** The returned value is always between 0 and 6, as follows:\n**\n** 0: Not a match.\n** 1: UTF8/16 conversion required and function takes any number of arguments.\n** 2: UTF16 byte order change required and function takes any number of args.\n** 3: encoding matches and function takes any number of arguments\n** 4: UTF8/16 conversion required - argument count matches exactly\n** 5: UTF16 byte order conversion required - argument count matches exactly\n** 6: Perfect match:  encoding and argument count match exactly.\n**\n** If nArg==(-2) then any function with a non-null xSFunc is\n** a perfect match and any function with xSFunc NULL is\n** a non-match.\n*/\n#define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */\nstatic int matchQuality(\n  FuncDef *p,     /* The function we are evaluating for match quality */\n  int nArg,       /* Desired number of arguments.  (-1)==any */\n  u8 enc          /* Desired text encoding */\n){\n  int match;\n  assert( p->nArg>=-1 );\n\n  /* Wrong number of arguments means \"no match\" */\n  if( p->nArg!=nArg ){\n    if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;\n    if( p->nArg>=0 ) return 0;\n  }\n\n  /* Give a better score to a function with a specific number of arguments\n  ** than to function that accepts any number of arguments. */\n  if( p->nArg==nArg ){\n    match = 4;\n  }else{\n    match = 1;\n  }\n\n  /* Bonus points if the text encoding matches */\n  if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){\n    match += 2;  /* Exact encoding match */\n  }else if( (enc & p->funcFlags & 2)!=0 ){\n    match += 1;  /* Both are UTF16, but with different byte orders */\n  }\n\n  return match;\n}\n\n/*\n** Search a FuncDefHash for a function with the given name.  Return\n** a pointer to the matching FuncDef if found, or 0 if there is no match.\n*/\nSQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(\n  int h,               /* Hash of the name */\n  const char *zFunc    /* Name of function */\n){\n  FuncDef *p;\n  for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){\n    if( sqlite3StrICmp(p->zName, zFunc)==0 ){\n      return p;\n    }\n  }\n  return 0;\n}\n\n/*\n** Insert a new FuncDef into a FuncDefHash hash table.\n*/\nSQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(\n  FuncDef *aDef,      /* List of global functions to be inserted */\n  int nDef            /* Length of the apDef[] list */\n){\n  int i;\n  for(i=0; i<nDef; i++){\n    FuncDef *pOther;\n    const char *zName = aDef[i].zName;\n    int nName = sqlite3Strlen30(zName);\n    int h = SQLITE_FUNC_HASH(zName[0], nName);\n    assert( zName[0]>='a' && zName[0]<='z' );\n    pOther = sqlite3FunctionSearch(h, zName);\n    if( pOther ){\n      assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );\n      aDef[i].pNext = pOther->pNext;\n      pOther->pNext = &aDef[i];\n    }else{\n      aDef[i].pNext = 0;\n      aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];\n      sqlite3BuiltinFunctions.a[h] = &aDef[i];\n    }\n  }\n}\n  \n  \n\n/*\n** Locate a user function given a name, a number of arguments and a flag\n** indicating whether the function prefers UTF-16 over UTF-8.  Return a\n** pointer to the FuncDef structure that defines that function, or return\n** NULL if the function does not exist.\n**\n** If the createFlag argument is true, then a new (blank) FuncDef\n** structure is created and liked into the \"db\" structure if a\n** no matching function previously existed.\n**\n** If nArg is -2, then the first valid function found is returned.  A\n** function is valid if xSFunc is non-zero.  The nArg==(-2)\n** case is used to see if zName is a valid function name for some number\n** of arguments.  If nArg is -2, then createFlag must be 0.\n**\n** If createFlag is false, then a function with the required name and\n** number of arguments may be returned even if the eTextRep flag does not\n** match that requested.\n*/\nSQLITE_PRIVATE FuncDef *sqlite3FindFunction(\n  sqlite3 *db,       /* An open database */\n  const char *zName, /* Name of the function.  zero-terminated */\n  int nArg,          /* Number of arguments.  -1 means any number */\n  u8 enc,            /* Preferred text encoding */\n  u8 createFlag      /* Create new entry if true and does not otherwise exist */\n){\n  FuncDef *p;         /* Iterator variable */\n  FuncDef *pBest = 0; /* Best match found so far */\n  int bestScore = 0;  /* Score of best match */\n  int h;              /* Hash value */\n  int nName;          /* Length of the name */\n\n  assert( nArg>=(-2) );\n  assert( nArg>=(-1) || createFlag==0 );\n  nName = sqlite3Strlen30(zName);\n\n  /* First search for a match amongst the application-defined functions.\n  */\n  p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);\n  while( p ){\n    int score = matchQuality(p, nArg, enc);\n    if( score>bestScore ){\n      pBest = p;\n      bestScore = score;\n    }\n    p = p->pNext;\n  }\n\n  /* If no match is found, search the built-in functions.\n  **\n  ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in\n  ** functions even if a prior app-defined function was found.  And give\n  ** priority to built-in functions.\n  **\n  ** Except, if createFlag is true, that means that we are trying to\n  ** install a new function.  Whatever FuncDef structure is returned it will\n  ** have fields overwritten with new information appropriate for the\n  ** new function.  But the FuncDefs for built-in functions are read-only.\n  ** So we must not search for built-ins when creating a new function.\n  */ \n  if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){\n    bestScore = 0;\n    h = SQLITE_FUNC_HASH(sqlite3UpperToLower[(u8)zName[0]], nName);\n    p = sqlite3FunctionSearch(h, zName);\n    while( p ){\n      int score = matchQuality(p, nArg, enc);\n      if( score>bestScore ){\n        pBest = p;\n        bestScore = score;\n      }\n      p = p->pNext;\n    }\n  }\n\n  /* If the createFlag parameter is true and the search did not reveal an\n  ** exact match for the name, number of arguments and encoding, then add a\n  ** new entry to the hash table and return it.\n  */\n  if( createFlag && bestScore<FUNC_PERFECT_MATCH && \n      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){\n    FuncDef *pOther;\n    u8 *z;\n    pBest->zName = (const char*)&pBest[1];\n    pBest->nArg = (u16)nArg;\n    pBest->funcFlags = enc;\n    memcpy((char*)&pBest[1], zName, nName+1);\n    for(z=(u8*)pBest->zName; *z; z++) *z = sqlite3UpperToLower[*z];\n    pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);\n    if( pOther==pBest ){\n      sqlite3DbFree(db, pBest);\n      sqlite3OomFault(db);\n      return 0;\n    }else{\n      pBest->pNext = pOther;\n    }\n  }\n\n  if( pBest && (pBest->xSFunc || createFlag) ){\n    return pBest;\n  }\n  return 0;\n}\n\n/*\n** Free all resources held by the schema structure. The void* argument points\n** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the \n** pointer itself, it just cleans up subsidiary resources (i.e. the contents\n** of the schema hash tables).\n**\n** The Schema.cache_size variable is not cleared.\n*/\nSQLITE_PRIVATE void sqlite3SchemaClear(void *p){\n  Hash temp1;\n  Hash temp2;\n  HashElem *pElem;\n  Schema *pSchema = (Schema *)p;\n\n  temp1 = pSchema->tblHash;\n  temp2 = pSchema->trigHash;\n  sqlite3HashInit(&pSchema->trigHash);\n  sqlite3HashClear(&pSchema->idxHash);\n  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){\n    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));\n  }\n  sqlite3HashClear(&temp2);\n  sqlite3HashInit(&pSchema->tblHash);\n  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){\n    Table *pTab = sqliteHashData(pElem);\n    sqlite3DeleteTable(0, pTab);\n  }\n  sqlite3HashClear(&temp1);\n  sqlite3HashClear(&pSchema->fkeyHash);\n  pSchema->pSeqTab = 0;\n  if( pSchema->schemaFlags & DB_SchemaLoaded ){\n    pSchema->iGeneration++;\n  }\n  pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted);\n}\n\n/*\n** Find and return the schema associated with a BTree.  Create\n** a new one if necessary.\n*/\nSQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){\n  Schema * p;\n  if( pBt ){\n    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);\n  }else{\n    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));\n  }\n  if( !p ){\n    sqlite3OomFault(db);\n  }else if ( 0==p->file_format ){\n    sqlite3HashInit(&p->tblHash);\n    sqlite3HashInit(&p->idxHash);\n    sqlite3HashInit(&p->trigHash);\n    sqlite3HashInit(&p->fkeyHash);\n    p->enc = SQLITE_UTF8;\n  }\n  return p;\n}\n\n/************** End of callback.c ********************************************/\n/************** Begin file delete.c ******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains C code routines that are called by the parser\n** in order to generate code for DELETE FROM statements.\n*/\n/* #include \"sqliteInt.h\" */\n\n/*\n** While a SrcList can in general represent multiple tables and subqueries\n** (as in the FROM clause of a SELECT statement) in this case it contains\n** the name of a single table, as one might find in an INSERT, DELETE,\n** or UPDATE statement.  Look up that table in the symbol table and\n** return a pointer.  Set an error message and return NULL if the table \n** name is not found or if any other error occurs.\n**\n** The following fields are initialized appropriate in pSrc:\n**\n**    pSrc->a[0].pTab       Pointer to the Table object\n**    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one\n**\n*/\nSQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){\n  struct SrcList_item *pItem = pSrc->a;\n  Table *pTab;\n  assert( pItem && pSrc->nSrc==1 );\n  pTab = sqlite3LocateTableItem(pParse, 0, pItem);\n  sqlite3DeleteTable(pParse->db, pItem->pTab);\n  pItem->pTab = pTab;\n  if( pTab ){\n    pTab->nTabRef++;\n  }\n  if( sqlite3IndexedByLookup(pParse, pItem) ){\n    pTab = 0;\n  }\n  return pTab;\n}\n\n/* Return true if table pTab is read-only.\n**\n** A table is read-only if any of the following are true:\n**\n**   1) It is a virtual table and no implementation of the xUpdate method\n**      has been provided\n**\n**   2) It is a system table (i.e. sqlite_master), this call is not\n**      part of a nested parse and writable_schema pragma has not \n**      been specified\n**\n**   3) The table is a shadow table, the database connection is in\n**      defensive mode, and the current sqlite3_prepare()\n**      is for a top-level SQL statement.\n*/\nstatic int tabIsReadOnly(Parse *pParse, Table *pTab){\n  sqlite3 *db;\n  if( IsVirtual(pTab) ){\n    return sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0;\n  }\n  if( (pTab->tabFlags & (TF_Readonly|TF_Shadow))==0 ) return 0;\n  db = pParse->db;\n  if( (pTab->tabFlags & TF_Readonly)!=0 ){\n    return sqlite3WritableSchema(db)==0 && pParse->nested==0;\n  }\n  assert( pTab->tabFlags & TF_Shadow );\n  return sqlite3ReadOnlyShadowTables(db);\n}\n\n/*\n** Check to make sure the given table is writable.  If it is not\n** writable, generate an error message and return 1.  If it is\n** writable return 0;\n*/\nSQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){\n  if( tabIsReadOnly(pParse, pTab) ){\n    sqlite3ErrorMsg(pParse, \"table %s may not be modified\", pTab->zName);\n    return 1;\n  }\n#ifndef SQLITE_OMIT_VIEW\n  if( !viewOk && pTab->pSelect ){\n    sqlite3ErrorMsg(pParse,\"cannot modify %s because it is a view\",pTab->zName);\n    return 1;\n  }\n#endif\n  return 0;\n}\n\n\n#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)\n/*\n** Evaluate a view and store its result in an ephemeral table.  The\n** pWhere argument is an optional WHERE clause that restricts the\n** set of rows in the view that are to be added to the ephemeral table.\n*/\nSQLITE_PRIVATE void sqlite3MaterializeView(\n  Parse *pParse,       /* Parsing context */\n  Table *pView,        /* View definition */\n  Expr *pWhere,        /* Optional WHERE clause to be added */\n  ExprList *pOrderBy,  /* Optional ORDER BY clause */\n  Expr *pLimit,        /* Optional LIMIT clause */\n  int iCur             /* Cursor number for ephemeral table */\n){\n  SelectDest dest;\n  Select *pSel;\n  SrcList *pFrom;\n  sqlite3 *db = pParse->db;\n  int iDb = sqlite3SchemaToIndex(db, pView->pSchema);\n  pWhere = sqlite3ExprDup(db, pWhere, 0);\n  pFrom = sqlite3SrcListAppend(pParse, 0, 0, 0);\n  if( pFrom ){\n    assert( pFrom->nSrc==1 );\n    pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);\n    pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);\n    assert( pFrom->a[0].pOn==0 );\n    assert( pFrom->a[0].pUsing==0 );\n  }\n  pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy, \n                          SF_IncludeHidden, pLimit);\n  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);\n  sqlite3Select(pParse, pSel, &dest);\n  sqlite3SelectDelete(db, pSel);\n}\n#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */\n\n#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)\n/*\n** Generate an expression tree to implement the WHERE, ORDER BY,\n** and LIMIT/OFFSET portion of DELETE and UPDATE statements.\n**\n**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;\n**                            \\__________________________/\n**                               pLimitWhere (pInClause)\n*/\nSQLITE_PRIVATE Expr *sqlite3LimitWhere(\n  Parse *pParse,               /* The parser context */\n  SrcList *pSrc,               /* the FROM clause -- which tables to scan */\n  Expr *pWhere,                /* The WHERE clause.  May be null */\n  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */\n  Expr *pLimit,                /* The LIMIT clause.  May be null */\n  char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */\n){\n  sqlite3 *db = pParse->db;\n  Expr *pLhs = NULL;           /* LHS of IN(SELECT...) operator */\n  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */\n  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */\n  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */\n  Select *pSelect = NULL;      /* Complete SELECT tree */\n  Table *pTab;\n\n  /* Check that there isn't an ORDER BY without a LIMIT clause.\n  */\n  if( pOrderBy && pLimit==0 ) {\n    sqlite3ErrorMsg(pParse, \"ORDER BY without LIMIT on %s\", zStmtType);\n    sqlite3ExprDelete(pParse->db, pWhere);\n    sqlite3ExprListDelete(pParse->db, pOrderBy);\n    return 0;\n  }\n\n  /* We only need to generate a select expression if there\n  ** is a limit/offset term to enforce.\n  */\n  if( pLimit == 0 ) {\n    return pWhere;\n  }\n\n  /* Generate a select expression tree to enforce the limit/offset \n  ** term for the DELETE or UPDATE statement.  For example:\n  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1\n  ** becomes:\n  **   DELETE FROM table_a WHERE rowid IN ( \n  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1\n  **   );\n  */\n\n  pTab = pSrc->a[0].pTab;\n  if( HasRowid(pTab) ){\n    pLhs = sqlite3PExpr(pParse, TK_ROW, 0, 0);\n    pEList = sqlite3ExprListAppend(\n        pParse, 0, sqlite3PExpr(pParse, TK_ROW, 0, 0)\n    );\n  }else{\n    Index *pPk = sqlite3PrimaryKeyIndex(pTab);\n    if( pPk->nKeyCol==1 ){\n      const char *zName = pTab->aCol[pPk->aiColumn[0]].zName;\n      pLhs = sqlite3Expr(db, TK_ID, zName);\n      pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, zName));\n    }else{\n      int i;\n      for(i=0; i<pPk->nKeyCol; i++){\n        Expr *p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zName);\n        pEList = sqlite3ExprListAppend(pParse, pEList, p);\n      }\n      pLhs = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);\n      if( pLhs ){\n        pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0);\n      }\n    }\n  }\n\n  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree\n  ** and the SELECT subtree. */\n  pSrc->a[0].pTab = 0;\n  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);\n  pSrc->a[0].pTab = pTab;\n  pSrc->a[0].pIBIndex = 0;\n\n  /* generate the SELECT expression tree. */\n  pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0, \n      pOrderBy,0,pLimit\n  );\n\n  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */\n  pInClause = sqlite3PExpr(pParse, TK_IN, pLhs, 0);\n  sqlite3PExprAddSelect(pParse, pInClause, pSelect);\n  return pInClause;\n}\n#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */\n       /*      && !defined(SQLITE_OMIT_SUBQUERY) */\n\n/*\n** Generate code for a DELETE FROM statement.\n**\n**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;\n**                 \\________/       \\________________/\n**                  pTabList              pWhere\n*/\nSQLITE_PRIVATE void sqlite3DeleteFrom(\n  Parse *pParse,         /* The parser context */\n  SrcList *pTabList,     /* The table from which we should delete things */\n  Expr *pWhere,          /* The WHERE clause.  May be null */\n  ExprList *pOrderBy,    /* ORDER BY clause. May be null */\n  Expr *pLimit           /* LIMIT clause. May be null */\n){\n  Vdbe *v;               /* The virtual database engine */\n  Table *pTab;           /* The table from which records will be deleted */\n  int i;                 /* Loop counter */\n  WhereInfo *pWInfo;     /* Information about the WHERE clause */\n  Index *pIdx;           /* For looping over indices of the table */\n  int iTabCur;           /* Cursor number for the table */\n  int iDataCur = 0;      /* VDBE cursor for the canonical data source */\n  int iIdxCur = 0;       /* Cursor number of the first index */\n  int nIdx;              /* Number of indices */\n  sqlite3 *db;           /* Main database structure */\n  AuthContext sContext;  /* Authorization context */\n  NameContext sNC;       /* Name context to resolve expressions in */\n  int iDb;               /* Database number */\n  int memCnt = 0;        /* Memory cell used for change counting */\n  int rcauth;            /* Value returned by authorization callback */\n  int eOnePass;          /* ONEPASS_OFF or _SINGLE or _MULTI */\n  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */\n  u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */\n  Index *pPk;            /* The PRIMARY KEY index on the table */\n  int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */\n  i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */\n  int iKey;              /* Memory cell holding key of row to be deleted */\n  i16 nKey;              /* Number of memory cells in the row key */\n  int iEphCur = 0;       /* Ephemeral table holding all primary key values */\n  int iRowSet = 0;       /* Register for rowset of rows to delete */\n  int addrBypass = 0;    /* Address of jump over the delete logic */\n  int addrLoop = 0;      /* Top of the delete loop */\n  int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */\n  int bComplex;          /* True if there are triggers or FKs or\n                         ** subqueries in the WHERE clause */\n \n#ifndef SQLITE_OMIT_TRIGGER\n  int isView;                  /* True if attempting to delete from a view */\n  Trigger *pTrigger;           /* List of table triggers, if required */\n#endif\n\n  memset(&sContext, 0, sizeof(sContext));\n  db = pParse->db;\n  if( pParse->nErr || db->mallocFailed ){\n    goto delete_from_cleanup;\n  }\n  assert( pTabList->nSrc==1 );\n\n\n  /* Locate the table which we want to delete.  This table has to be\n  ** put in an SrcList structure because some of the subroutines we\n  ** will be calling are designed to work with multiple tables and expect\n  ** an SrcList* parameter instead of just a Table* parameter.\n  */\n  pTab = sqlite3SrcListLookup(pParse, pTabList);\n  if( pTab==0 )  goto delete_from_cleanup;\n\n  /* Figure out if we have any triggers and if the table being\n  ** deleted from is a view\n  */\n#ifndef SQLITE_OMIT_TRIGGER\n  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);\n  isView = pTab->pSelect!=0;\n#else\n# define pTrigger 0\n# define isView 0\n#endif\n  bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);\n#ifdef SQLITE_OMIT_VIEW\n# undef isView\n# define isView 0\n#endif\n\n#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT\n  if( !isView ){\n    pWhere = sqlite3LimitWhere(\n        pParse, pTabList, pWhere, pOrderBy, pLimit, \"DELETE\"\n    );\n    pOrderBy = 0;\n    pLimit = 0;\n  }\n#endif\n\n  /* If pTab is really a view, make sure it has been initialized.\n  */\n  if( sqlite3ViewGetColumnNames(pParse, pTab) ){\n    goto delete_from_cleanup;\n  }\n\n  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){\n    goto delete_from_cleanup;\n  }\n  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n  assert( iDb<db->nDb );\n  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, \n                            db->aDb[iDb].zDbSName);\n  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );\n  if( rcauth==SQLITE_DENY ){\n    goto delete_from_cleanup;\n  }\n  assert(!isView || pTrigger);\n\n  /* Assign cursor numbers to the table and all its indices.\n  */\n  assert( pTabList->nSrc==1 );\n  iTabCur = pTabList->a[0].iCursor = pParse->nTab++;\n  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){\n    pParse->nTab++;\n  }\n\n  /* Start the view context\n  */\n  if( isView ){\n    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);\n  }\n\n  /* Begin generating code.\n  */\n  v = sqlite3GetVdbe(pParse);\n  if( v==0 ){\n    goto delete_from_cleanup;\n  }\n  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);\n  sqlite3BeginWriteOperation(pParse, bComplex, iDb);\n\n  /* If we are trying to delete from a view, realize that view into\n  ** an ephemeral table.\n  */\n#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)\n  if( isView ){\n    sqlite3MaterializeView(pParse, pTab, \n        pWhere, pOrderBy, pLimit, iTabCur\n    );\n    iDataCur = iIdxCur = iTabCur;\n    pOrderBy = 0;\n    pLimit = 0;\n  }\n#endif\n\n  /* Resolve the column names in the WHERE clause.\n  */\n  memset(&sNC, 0, sizeof(sNC));\n  sNC.pParse = pParse;\n  sNC.pSrcList = pTabList;\n  if( sqlite3ResolveExprNames(&sNC, pWhere) ){\n    goto delete_from_cleanup;\n  }\n\n  /* Initialize the counter of the number of rows deleted, if\n  ** we are counting rows.\n  */\n  if( (db->flags & SQLITE_CountRows)!=0\n   && !pParse->nested\n   && !pParse->pTriggerTab\n  ){\n    memCnt = ++pParse->nMem;\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);\n  }\n\n#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION\n  /* Special case: A DELETE without a WHERE clause deletes everything.\n  ** It is easier just to erase the whole table. Prior to version 3.6.5,\n  ** this optimization caused the row change count (the value returned by \n  ** API function sqlite3_count_changes) to be set incorrectly.\n  **\n  ** The \"rcauth==SQLITE_OK\" terms is the\n  ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and\n  ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but\n  ** the truncate optimization is disabled and all rows are deleted\n  ** individually.\n  */\n  if( rcauth==SQLITE_OK\n   && pWhere==0\n   && !bComplex\n   && !IsVirtual(pTab)\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n   && db->xPreUpdateCallback==0\n#endif\n  ){\n    assert( !isView );\n    sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);\n    if( HasRowid(pTab) ){\n      sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt ? memCnt : -1,\n                        pTab->zName, P4_STATIC);\n    }\n    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n      assert( pIdx->pSchema==pTab->pSchema );\n      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);\n    }\n  }else\n#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */\n  {\n    u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;\n    if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;\n    wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);\n    if( HasRowid(pTab) ){\n      /* For a rowid table, initialize the RowSet to an empty set */\n      pPk = 0;\n      nPk = 1;\n      iRowSet = ++pParse->nMem;\n      sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);\n    }else{\n      /* For a WITHOUT ROWID table, create an ephemeral table used to\n      ** hold all primary keys for rows to be deleted. */\n      pPk = sqlite3PrimaryKeyIndex(pTab);\n      assert( pPk!=0 );\n      nPk = pPk->nKeyCol;\n      iPk = pParse->nMem+1;\n      pParse->nMem += nPk;\n      iEphCur = pParse->nTab++;\n      addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);\n      sqlite3VdbeSetP4KeyInfo(pParse, pPk);\n    }\n  \n    /* Construct a query to find the rowid or primary key for every row\n    ** to be deleted, based on the WHERE clause. Set variable eOnePass\n    ** to indicate the strategy used to implement this delete:\n    **\n    **  ONEPASS_OFF:    Two-pass approach - use a FIFO for rowids/PK values.\n    **  ONEPASS_SINGLE: One-pass approach - at most one row deleted.\n    **  ONEPASS_MULTI:  One-pass approach - any number of rows may be deleted.\n    */\n    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);\n    if( pWInfo==0 ) goto delete_from_cleanup;\n    eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);\n    assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );\n    assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );\n    if( eOnePass!=ONEPASS_SINGLE ) sqlite3MultiWrite(pParse);\n  \n    /* Keep track of the number of rows to be deleted */\n    if( memCnt ){\n      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);\n    }\n  \n    /* Extract the rowid or primary key for the current row */\n    if( pPk ){\n      for(i=0; i<nPk; i++){\n        assert( pPk->aiColumn[i]>=0 );\n        sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,\n                                        pPk->aiColumn[i], iPk+i);\n      }\n      iKey = iPk;\n    }else{\n      iKey = ++pParse->nMem;\n      sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, -1, iKey);\n    }\n  \n    if( eOnePass!=ONEPASS_OFF ){\n      /* For ONEPASS, no need to store the rowid/primary-key. There is only\n      ** one, so just keep it in its register(s) and fall through to the\n      ** delete code.  */\n      nKey = nPk; /* OP_Found will use an unpacked key */\n      aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);\n      if( aToOpen==0 ){\n        sqlite3WhereEnd(pWInfo);\n        goto delete_from_cleanup;\n      }\n      memset(aToOpen, 1, nIdx+1);\n      aToOpen[nIdx+1] = 0;\n      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;\n      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;\n      if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);\n    }else{\n      if( pPk ){\n        /* Add the PK key for this row to the temporary table */\n        iKey = ++pParse->nMem;\n        nKey = 0;   /* Zero tells OP_Found to use a composite key */\n        sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,\n            sqlite3IndexAffinityStr(pParse->db, pPk), nPk);\n        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);\n      }else{\n        /* Add the rowid of the row to be deleted to the RowSet */\n        nKey = 1;  /* OP_DeferredSeek always uses a single rowid */\n        sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);\n      }\n    }\n  \n    /* If this DELETE cannot use the ONEPASS strategy, this is the \n    ** end of the WHERE loop */\n    if( eOnePass!=ONEPASS_OFF ){\n      addrBypass = sqlite3VdbeMakeLabel(pParse);\n    }else{\n      sqlite3WhereEnd(pWInfo);\n    }\n  \n    /* Unless this is a view, open cursors for the table we are \n    ** deleting from and all its indices. If this is a view, then the\n    ** only effect this statement has is to fire the INSTEAD OF \n    ** triggers.\n    */\n    if( !isView ){\n      int iAddrOnce = 0;\n      if( eOnePass==ONEPASS_MULTI ){\n        iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);\n      }\n      testcase( IsVirtual(pTab) );\n      sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,\n                                 iTabCur, aToOpen, &iDataCur, &iIdxCur);\n      assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );\n      assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );\n      if( eOnePass==ONEPASS_MULTI ){\n        sqlite3VdbeJumpHereOrPopInst(v, iAddrOnce);\n      }\n    }\n  \n    /* Set up a loop over the rowids/primary-keys that were found in the\n    ** where-clause loop above.\n    */\n    if( eOnePass!=ONEPASS_OFF ){\n      assert( nKey==nPk );  /* OP_Found will use an unpacked key */\n      if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){\n        assert( pPk!=0 || pTab->pSelect!=0 );\n        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);\n        VdbeCoverage(v);\n      }\n    }else if( pPk ){\n      addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);\n      if( IsVirtual(pTab) ){\n        sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);\n      }else{\n        sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);\n      }\n      assert( nKey==0 );  /* OP_Found will use a composite key */\n    }else{\n      addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);\n      VdbeCoverage(v);\n      assert( nKey==1 );\n    }  \n  \n    /* Delete the row */\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    if( IsVirtual(pTab) ){\n      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);\n      sqlite3VtabMakeWritable(pParse, pTab);\n      assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );\n      sqlite3MayAbort(pParse);\n      if( eOnePass==ONEPASS_SINGLE ){\n        sqlite3VdbeAddOp1(v, OP_Close, iTabCur);\n        if( sqlite3IsToplevel(pParse) ){\n          pParse->isMultiWrite = 0;\n        }\n      }\n      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);\n      sqlite3VdbeChangeP5(v, OE_Abort);\n    }else\n#endif\n    {\n      int count = (pParse->nested==0);    /* True to count changes */\n      sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,\n          iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);\n    }\n  \n    /* End of the loop over all rowids/primary-keys. */\n    if( eOnePass!=ONEPASS_OFF ){\n      sqlite3VdbeResolveLabel(v, addrBypass);\n      sqlite3WhereEnd(pWInfo);\n    }else if( pPk ){\n      sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);\n      sqlite3VdbeJumpHere(v, addrLoop);\n    }else{\n      sqlite3VdbeGoto(v, addrLoop);\n      sqlite3VdbeJumpHere(v, addrLoop);\n    }     \n  } /* End non-truncate path */\n\n  /* Update the sqlite_sequence table by storing the content of the\n  ** maximum rowid counter values recorded while inserting into\n  ** autoincrement tables.\n  */\n  if( pParse->nested==0 && pParse->pTriggerTab==0 ){\n    sqlite3AutoincrementEnd(pParse);\n  }\n\n  /* Return the number of rows that were deleted. If this routine is \n  ** generating code because of a call to sqlite3NestedParse(), do not\n  ** invoke the callback function.\n  */\n  if( memCnt ){\n    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);\n    sqlite3VdbeSetNumCols(v, 1);\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"rows deleted\", SQLITE_STATIC);\n  }\n\ndelete_from_cleanup:\n  sqlite3AuthContextPop(&sContext);\n  sqlite3SrcListDelete(db, pTabList);\n  sqlite3ExprDelete(db, pWhere);\n#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) \n  sqlite3ExprListDelete(db, pOrderBy);\n  sqlite3ExprDelete(db, pLimit);\n#endif\n  sqlite3DbFree(db, aToOpen);\n  return;\n}\n/* Make sure \"isView\" and other macros defined above are undefined. Otherwise\n** they may interfere with compilation of other functions in this file\n** (or in another file, if this file becomes part of the amalgamation).  */\n#ifdef isView\n #undef isView\n#endif\n#ifdef pTrigger\n #undef pTrigger\n#endif\n\n/*\n** This routine generates VDBE code that causes a single row of a\n** single table to be deleted.  Both the original table entry and\n** all indices are removed.\n**\n** Preconditions:\n**\n**   1.  iDataCur is an open cursor on the btree that is the canonical data\n**       store for the table.  (This will be either the table itself,\n**       in the case of a rowid table, or the PRIMARY KEY index in the case\n**       of a WITHOUT ROWID table.)\n**\n**   2.  Read/write cursors for all indices of pTab must be open as\n**       cursor number iIdxCur+i for the i-th index.\n**\n**   3.  The primary key for the row to be deleted must be stored in a\n**       sequence of nPk memory cells starting at iPk.  If nPk==0 that means\n**       that a search record formed from OP_MakeRecord is contained in the\n**       single memory location iPk.\n**\n** eMode:\n**   Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or\n**   ONEPASS_MULTI.  If eMode is not ONEPASS_OFF, then the cursor\n**   iDataCur already points to the row to delete. If eMode is ONEPASS_OFF\n**   then this function must seek iDataCur to the entry identified by iPk\n**   and nPk before reading from it.\n**\n**   If eMode is ONEPASS_MULTI, then this call is being made as part\n**   of a ONEPASS delete that affects multiple rows. In this case, if \n**   iIdxNoSeek is a valid cursor number (>=0) and is not the same as\n**   iDataCur, then its position should be preserved following the delete\n**   operation. Or, if iIdxNoSeek is not a valid cursor number, the\n**   position of iDataCur should be preserved instead.\n**\n** iIdxNoSeek:\n**   If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,\n**   then it identifies an index cursor (from within array of cursors\n**   starting at iIdxCur) that already points to the index entry to be deleted.\n**   Except, this optimization is disabled if there are BEFORE triggers since\n**   the trigger body might have moved the cursor.\n*/\nSQLITE_PRIVATE void sqlite3GenerateRowDelete(\n  Parse *pParse,     /* Parsing context */\n  Table *pTab,       /* Table containing the row to be deleted */\n  Trigger *pTrigger, /* List of triggers to (potentially) fire */\n  int iDataCur,      /* Cursor from which column data is extracted */\n  int iIdxCur,       /* First index cursor */\n  int iPk,           /* First memory cell containing the PRIMARY KEY */\n  i16 nPk,           /* Number of PRIMARY KEY memory cells */\n  u8 count,          /* If non-zero, increment the row change counter */\n  u8 onconf,         /* Default ON CONFLICT policy for triggers */\n  u8 eMode,          /* ONEPASS_OFF, _SINGLE, or _MULTI.  See above */\n  int iIdxNoSeek     /* Cursor number of cursor that does not need seeking */\n){\n  Vdbe *v = pParse->pVdbe;        /* Vdbe */\n  int iOld = 0;                   /* First register in OLD.* array */\n  int iLabel;                     /* Label resolved to end of generated code */\n  u8 opSeek;                      /* Seek opcode */\n\n  /* Vdbe is guaranteed to have been allocated by this stage. */\n  assert( v );\n  VdbeModuleComment((v, \"BEGIN: GenRowDel(%d,%d,%d,%d)\",\n                         iDataCur, iIdxCur, iPk, (int)nPk));\n\n  /* Seek cursor iCur to the row to delete. If this row no longer exists \n  ** (this can happen if a trigger program has already deleted it), do\n  ** not attempt to delete it or fire any DELETE triggers.  */\n  iLabel = sqlite3VdbeMakeLabel(pParse);\n  opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;\n  if( eMode==ONEPASS_OFF ){\n    sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);\n    VdbeCoverageIf(v, opSeek==OP_NotExists);\n    VdbeCoverageIf(v, opSeek==OP_NotFound);\n  }\n \n  /* If there are any triggers to fire, allocate a range of registers to\n  ** use for the old.* references in the triggers.  */\n  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){\n    u32 mask;                     /* Mask of OLD.* columns in use */\n    int iCol;                     /* Iterator used while populating OLD.* */\n    int addrStart;                /* Start of BEFORE trigger programs */\n\n    /* TODO: Could use temporary registers here. Also could attempt to\n    ** avoid copying the contents of the rowid register.  */\n    mask = sqlite3TriggerColmask(\n        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf\n    );\n    mask |= sqlite3FkOldmask(pParse, pTab);\n    iOld = pParse->nMem+1;\n    pParse->nMem += (1 + pTab->nCol);\n\n    /* Populate the OLD.* pseudo-table register array. These values will be \n    ** used by any BEFORE and AFTER triggers that exist.  */\n    sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);\n    for(iCol=0; iCol<pTab->nCol; iCol++){\n      testcase( mask!=0xffffffff && iCol==31 );\n      testcase( mask!=0xffffffff && iCol==32 );\n      if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){\n        int kk = sqlite3TableColumnToStorage(pTab, iCol);\n        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+kk+1);\n      }\n    }\n\n    /* Invoke BEFORE DELETE trigger programs. */\n    addrStart = sqlite3VdbeCurrentAddr(v);\n    sqlite3CodeRowTrigger(pParse, pTrigger, \n        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel\n    );\n\n    /* If any BEFORE triggers were coded, then seek the cursor to the \n    ** row to be deleted again. It may be that the BEFORE triggers moved\n    ** the cursor or already deleted the row that the cursor was\n    ** pointing to.\n    **\n    ** Also disable the iIdxNoSeek optimization since the BEFORE trigger\n    ** may have moved that cursor.\n    */\n    if( addrStart<sqlite3VdbeCurrentAddr(v) ){\n      sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);\n      VdbeCoverageIf(v, opSeek==OP_NotExists);\n      VdbeCoverageIf(v, opSeek==OP_NotFound);\n      testcase( iIdxNoSeek>=0 );\n      iIdxNoSeek = -1;\n    }\n\n    /* Do FK processing. This call checks that any FK constraints that\n    ** refer to this table (i.e. constraints attached to other tables) \n    ** are not violated by deleting this row.  */\n    sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);\n  }\n\n  /* Delete the index and table entries. Skip this step if pTab is really\n  ** a view (in which case the only effect of the DELETE statement is to\n  ** fire the INSTEAD OF triggers).  \n  **\n  ** If variable 'count' is non-zero, then this OP_Delete instruction should\n  ** invoke the update-hook. The pre-update-hook, on the other hand should\n  ** be invoked unless table pTab is a system table. The difference is that\n  ** the update-hook is not invoked for rows removed by REPLACE, but the \n  ** pre-update-hook is.\n  */ \n  if( pTab->pSelect==0 ){\n    u8 p5 = 0;\n    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);\n    sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));\n    if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, \"sqlite_stat1\") ){\n      sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);\n    }\n    if( eMode!=ONEPASS_OFF ){\n      sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);\n    }\n    if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){\n      sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);\n    }\n    if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;\n    sqlite3VdbeChangeP5(v, p5);\n  }\n\n  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to\n  ** handle rows (possibly in other tables) that refer via a foreign key\n  ** to the row just deleted. */ \n  sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);\n\n  /* Invoke AFTER DELETE trigger programs. */\n  sqlite3CodeRowTrigger(pParse, pTrigger, \n      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel\n  );\n\n  /* Jump here if the row had already been deleted before any BEFORE\n  ** trigger programs were invoked. Or if a trigger program throws a \n  ** RAISE(IGNORE) exception.  */\n  sqlite3VdbeResolveLabel(v, iLabel);\n  VdbeModuleComment((v, \"END: GenRowDel()\"));\n}\n\n/*\n** This routine generates VDBE code that causes the deletion of all\n** index entries associated with a single row of a single table, pTab\n**\n** Preconditions:\n**\n**   1.  A read/write cursor \"iDataCur\" must be open on the canonical storage\n**       btree for the table pTab.  (This will be either the table itself\n**       for rowid tables or to the primary key index for WITHOUT ROWID\n**       tables.)\n**\n**   2.  Read/write cursors for all indices of pTab must be open as\n**       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex\n**       index is the 0-th index.)\n**\n**   3.  The \"iDataCur\" cursor must be already be positioned on the row\n**       that is to be deleted.\n*/\nSQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(\n  Parse *pParse,     /* Parsing and code generating context */\n  Table *pTab,       /* Table containing the row to be deleted */\n  int iDataCur,      /* Cursor of table holding data. */\n  int iIdxCur,       /* First index cursor */\n  int *aRegIdx,      /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */\n  int iIdxNoSeek     /* Do not delete from this cursor */\n){\n  int i;             /* Index loop counter */\n  int r1 = -1;       /* Register holding an index key */\n  int iPartIdxLabel; /* Jump destination for skipping partial index entries */\n  Index *pIdx;       /* Current index */\n  Index *pPrior = 0; /* Prior index */\n  Vdbe *v;           /* The prepared statement under construction */\n  Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */\n\n  v = pParse->pVdbe;\n  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);\n  for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){\n    assert( iIdxCur+i!=iDataCur || pPk==pIdx );\n    if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;\n    if( pIdx==pPk ) continue;\n    if( iIdxCur+i==iIdxNoSeek ) continue;\n    VdbeModuleComment((v, \"GenRowIdxDel for %s\", pIdx->zName));\n    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,\n        &iPartIdxLabel, pPrior, r1);\n    sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,\n        pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);\n    sqlite3VdbeChangeP5(v, 1);  /* Cause IdxDelete to error if no entry found */\n    sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);\n    pPrior = pIdx;\n  }\n}\n\n/*\n** Generate code that will assemble an index key and stores it in register\n** regOut.  The key with be for index pIdx which is an index on pTab.\n** iCur is the index of a cursor open on the pTab table and pointing to\n** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then\n** iCur must be the cursor of the PRIMARY KEY index.\n**\n** Return a register number which is the first in a block of\n** registers that holds the elements of the index key.  The\n** block of registers has already been deallocated by the time\n** this routine returns.\n**\n** If *piPartIdxLabel is not NULL, fill it in with a label and jump\n** to that label if pIdx is a partial index that should be skipped.\n** The label should be resolved using sqlite3ResolvePartIdxLabel().\n** A partial index should be skipped if its WHERE clause evaluates\n** to false or null.  If pIdx is not a partial index, *piPartIdxLabel\n** will be set to zero which is an empty label that is ignored by\n** sqlite3ResolvePartIdxLabel().\n**\n** The pPrior and regPrior parameters are used to implement a cache to\n** avoid unnecessary register loads.  If pPrior is not NULL, then it is\n** a pointer to a different index for which an index key has just been\n** computed into register regPrior.  If the current pIdx index is generating\n** its key into the same sequence of registers and if pPrior and pIdx share\n** a column in common, then the register corresponding to that column already\n** holds the correct value and the loading of that register is skipped.\n** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK \n** on a table with multiple indices, and especially with the ROWID or\n** PRIMARY KEY columns of the index.\n*/\nSQLITE_PRIVATE int sqlite3GenerateIndexKey(\n  Parse *pParse,       /* Parsing context */\n  Index *pIdx,         /* The index for which to generate a key */\n  int iDataCur,        /* Cursor number from which to take column data */\n  int regOut,          /* Put the new key into this register if not 0 */\n  int prefixOnly,      /* Compute only a unique prefix of the key */\n  int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */\n  Index *pPrior,       /* Previously generated index key */\n  int regPrior         /* Register holding previous generated key */\n){\n  Vdbe *v = pParse->pVdbe;\n  int j;\n  int regBase;\n  int nCol;\n\n  if( piPartIdxLabel ){\n    if( pIdx->pPartIdxWhere ){\n      *piPartIdxLabel = sqlite3VdbeMakeLabel(pParse);\n      pParse->iSelfTab = iDataCur + 1;\n      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, \n                            SQLITE_JUMPIFNULL);\n      pParse->iSelfTab = 0;\n      pPrior = 0; /* Ticket a9efb42811fa41ee 2019-11-02;\n                  ** pPartIdxWhere may have corrupted regPrior registers */\n    }else{\n      *piPartIdxLabel = 0;\n    }\n  }\n  nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;\n  regBase = sqlite3GetTempRange(pParse, nCol);\n  if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;\n  for(j=0; j<nCol; j++){\n    if( pPrior\n     && pPrior->aiColumn[j]==pIdx->aiColumn[j]\n     && pPrior->aiColumn[j]!=XN_EXPR\n    ){\n      /* This column was already computed by the previous index */\n      continue;\n    }\n    sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);\n    /* If the column affinity is REAL but the number is an integer, then it\n    ** might be stored in the table as an integer (using a compact\n    ** representation) then converted to REAL by an OP_RealAffinity opcode.\n    ** But we are getting ready to store this value back into an index, where\n    ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity\n    ** opcode if it is present */\n    sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);\n  }\n  if( regOut ){\n    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);\n    if( pIdx->pTable->pSelect ){\n      const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);\n      sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);\n    }\n  }\n  sqlite3ReleaseTempRange(pParse, regBase, nCol);\n  return regBase;\n}\n\n/*\n** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label\n** because it was a partial index, then this routine should be called to\n** resolve that label.\n*/\nSQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){\n  if( iLabel ){\n    sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);\n  }\n}\n\n/************** End of delete.c **********************************************/\n/************** Begin file func.c ********************************************/\n/*\n** 2002 February 23\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the C-language implementations for many of the SQL\n** functions of SQLite.  (Some function, and in particular the date and\n** time functions, are implemented separately.)\n*/\n/* #include \"sqliteInt.h\" */\n/* #include <stdlib.h> */\n/* #include <assert.h> */\n#ifndef SQLITE_OMIT_FLOATING_POINT\n/* #include <math.h> */\n#endif\n/* #include \"vdbeInt.h\" */\n\n/*\n** Return the collating function associated with a function.\n*/\nstatic CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){\n  VdbeOp *pOp;\n  assert( context->pVdbe!=0 );\n  pOp = &context->pVdbe->aOp[context->iOp-1];\n  assert( pOp->opcode==OP_CollSeq );\n  assert( pOp->p4type==P4_COLLSEQ );\n  return pOp->p4.pColl;\n}\n\n/*\n** Indicate that the accumulator load should be skipped on this\n** iteration of the aggregate loop.\n*/\nstatic void sqlite3SkipAccumulatorLoad(sqlite3_context *context){\n  assert( context->isError<=0 );\n  context->isError = -1;\n  context->skipFlag = 1;\n}\n\n/*\n** Implementation of the non-aggregate min() and max() functions\n*/\nstatic void minmaxFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  int i;\n  int mask;    /* 0 for min() or 0xffffffff for max() */\n  int iBest;\n  CollSeq *pColl;\n\n  assert( argc>1 );\n  mask = sqlite3_user_data(context)==0 ? 0 : -1;\n  pColl = sqlite3GetFuncCollSeq(context);\n  assert( pColl );\n  assert( mask==-1 || mask==0 );\n  iBest = 0;\n  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;\n  for(i=1; i<argc; i++){\n    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;\n    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){\n      testcase( mask==0 );\n      iBest = i;\n    }\n  }\n  sqlite3_result_value(context, argv[iBest]);\n}\n\n/*\n** Return the type of the argument.\n*/\nstatic void typeofFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **argv\n){\n  static const char *azType[] = { \"integer\", \"real\", \"text\", \"blob\", \"null\" };\n  int i = sqlite3_value_type(argv[0]) - 1;\n  UNUSED_PARAMETER(NotUsed);\n  assert( i>=0 && i<ArraySize(azType) );\n  assert( SQLITE_INTEGER==1 );\n  assert( SQLITE_FLOAT==2 );\n  assert( SQLITE_TEXT==3 );\n  assert( SQLITE_BLOB==4 );\n  assert( SQLITE_NULL==5 );\n  /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns\n  ** the datatype code for the initial datatype of the sqlite3_value object\n  ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,\n  ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */\n  sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);\n}\n\n\n/*\n** Implementation of the length() function\n*/\nstatic void lengthFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  switch( sqlite3_value_type(argv[0]) ){\n    case SQLITE_BLOB:\n    case SQLITE_INTEGER:\n    case SQLITE_FLOAT: {\n      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));\n      break;\n    }\n    case SQLITE_TEXT: {\n      const unsigned char *z = sqlite3_value_text(argv[0]);\n      const unsigned char *z0;\n      unsigned char c;\n      if( z==0 ) return;\n      z0 = z;\n      while( (c = *z)!=0 ){\n        z++;\n        if( c>=0xc0 ){\n          while( (*z & 0xc0)==0x80 ){ z++; z0++; }\n        }\n      }\n      sqlite3_result_int(context, (int)(z-z0));\n      break;\n    }\n    default: {\n      sqlite3_result_null(context);\n      break;\n    }\n  }\n}\n\n/*\n** Implementation of the abs() function.\n**\n** IMP: R-23979-26855 The abs(X) function returns the absolute value of\n** the numeric argument X. \n*/\nstatic void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  switch( sqlite3_value_type(argv[0]) ){\n    case SQLITE_INTEGER: {\n      i64 iVal = sqlite3_value_int64(argv[0]);\n      if( iVal<0 ){\n        if( iVal==SMALLEST_INT64 ){\n          /* IMP: R-31676-45509 If X is the integer -9223372036854775808\n          ** then abs(X) throws an integer overflow error since there is no\n          ** equivalent positive 64-bit two complement value. */\n          sqlite3_result_error(context, \"integer overflow\", -1);\n          return;\n        }\n        iVal = -iVal;\n      } \n      sqlite3_result_int64(context, iVal);\n      break;\n    }\n    case SQLITE_NULL: {\n      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */\n      sqlite3_result_null(context);\n      break;\n    }\n    default: {\n      /* Because sqlite3_value_double() returns 0.0 if the argument is not\n      ** something that can be converted into a number, we have:\n      ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob\n      ** that cannot be converted to a numeric value.\n      */\n      double rVal = sqlite3_value_double(argv[0]);\n      if( rVal<0 ) rVal = -rVal;\n      sqlite3_result_double(context, rVal);\n      break;\n    }\n  }\n}\n\n/*\n** Implementation of the instr() function.\n**\n** instr(haystack,needle) finds the first occurrence of needle\n** in haystack and returns the number of previous characters plus 1,\n** or 0 if needle does not occur within haystack.\n**\n** If both haystack and needle are BLOBs, then the result is one more than\n** the number of bytes in haystack prior to the first occurrence of needle,\n** or 0 if needle never occurs in haystack.\n*/\nstatic void instrFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  const unsigned char *zHaystack;\n  const unsigned char *zNeedle;\n  int nHaystack;\n  int nNeedle;\n  int typeHaystack, typeNeedle;\n  int N = 1;\n  int isText;\n  unsigned char firstChar;\n  sqlite3_value *pC1 = 0;\n  sqlite3_value *pC2 = 0;\n\n  UNUSED_PARAMETER(argc);\n  typeHaystack = sqlite3_value_type(argv[0]);\n  typeNeedle = sqlite3_value_type(argv[1]);\n  if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;\n  nHaystack = sqlite3_value_bytes(argv[0]);\n  nNeedle = sqlite3_value_bytes(argv[1]);\n  if( nNeedle>0 ){\n    if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){\n      zHaystack = sqlite3_value_blob(argv[0]);\n      zNeedle = sqlite3_value_blob(argv[1]);\n      isText = 0;\n    }else if( typeHaystack!=SQLITE_BLOB && typeNeedle!=SQLITE_BLOB ){\n      zHaystack = sqlite3_value_text(argv[0]);\n      zNeedle = sqlite3_value_text(argv[1]);\n      isText = 1;\n    }else{\n      pC1 = sqlite3_value_dup(argv[0]);\n      zHaystack = sqlite3_value_text(pC1);\n      if( zHaystack==0 ) goto endInstrOOM;\n      nHaystack = sqlite3_value_bytes(pC1);\n      pC2 = sqlite3_value_dup(argv[1]);\n      zNeedle = sqlite3_value_text(pC2);\n      if( zNeedle==0 ) goto endInstrOOM;\n      nNeedle = sqlite3_value_bytes(pC2);\n      isText = 1;\n    }\n    if( zNeedle==0 || (nHaystack && zHaystack==0) ) goto endInstrOOM;\n    firstChar = zNeedle[0];\n    while( nNeedle<=nHaystack\n       && (zHaystack[0]!=firstChar || memcmp(zHaystack, zNeedle, nNeedle)!=0)\n    ){\n      N++;\n      do{\n        nHaystack--;\n        zHaystack++;\n      }while( isText && (zHaystack[0]&0xc0)==0x80 );\n    }\n    if( nNeedle>nHaystack ) N = 0;\n  }\n  sqlite3_result_int(context, N);\nendInstr:\n  sqlite3_value_free(pC1);\n  sqlite3_value_free(pC2);\n  return;\nendInstrOOM:\n  sqlite3_result_error_nomem(context);\n  goto endInstr;\n}\n\n/*\n** Implementation of the printf() function.\n*/\nstatic void printfFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  PrintfArguments x;\n  StrAccum str;\n  const char *zFormat;\n  int n;\n  sqlite3 *db = sqlite3_context_db_handle(context);\n\n  if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){\n    x.nArg = argc-1;\n    x.nUsed = 0;\n    x.apArg = argv+1;\n    sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);\n    str.printfFlags = SQLITE_PRINTF_SQLFUNC;\n    sqlite3_str_appendf(&str, zFormat, &x);\n    n = str.nChar;\n    sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,\n                        SQLITE_DYNAMIC);\n  }\n}\n\n/*\n** Implementation of the substr() function.\n**\n** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.\n** p1 is 1-indexed.  So substr(x,1,1) returns the first character\n** of x.  If x is text, then we actually count UTF-8 characters.\n** If x is a blob, then we count bytes.\n**\n** If p1 is negative, then we begin abs(p1) from the end of x[].\n**\n** If p2 is negative, return the p2 characters preceding p1.\n*/\nstatic void substrFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  const unsigned char *z;\n  const unsigned char *z2;\n  int len;\n  int p0type;\n  i64 p1, p2;\n  int negP2 = 0;\n\n  assert( argc==3 || argc==2 );\n  if( sqlite3_value_type(argv[1])==SQLITE_NULL\n   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)\n  ){\n    return;\n  }\n  p0type = sqlite3_value_type(argv[0]);\n  p1 = sqlite3_value_int(argv[1]);\n  if( p0type==SQLITE_BLOB ){\n    len = sqlite3_value_bytes(argv[0]);\n    z = sqlite3_value_blob(argv[0]);\n    if( z==0 ) return;\n    assert( len==sqlite3_value_bytes(argv[0]) );\n  }else{\n    z = sqlite3_value_text(argv[0]);\n    if( z==0 ) return;\n    len = 0;\n    if( p1<0 ){\n      for(z2=z; *z2; len++){\n        SQLITE_SKIP_UTF8(z2);\n      }\n    }\n  }\n#ifdef SQLITE_SUBSTR_COMPATIBILITY\n  /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as\n  ** as substr(X,1,N) - it returns the first N characters of X.  This\n  ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]\n  ** from 2009-02-02 for compatibility of applications that exploited the\n  ** old buggy behavior. */\n  if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */\n#endif\n  if( argc==3 ){\n    p2 = sqlite3_value_int(argv[2]);\n    if( p2<0 ){\n      p2 = -p2;\n      negP2 = 1;\n    }\n  }else{\n    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];\n  }\n  if( p1<0 ){\n    p1 += len;\n    if( p1<0 ){\n      p2 += p1;\n      if( p2<0 ) p2 = 0;\n      p1 = 0;\n    }\n  }else if( p1>0 ){\n    p1--;\n  }else if( p2>0 ){\n    p2--;\n  }\n  if( negP2 ){\n    p1 -= p2;\n    if( p1<0 ){\n      p2 += p1;\n      p1 = 0;\n    }\n  }\n  assert( p1>=0 && p2>=0 );\n  if( p0type!=SQLITE_BLOB ){\n    while( *z && p1 ){\n      SQLITE_SKIP_UTF8(z);\n      p1--;\n    }\n    for(z2=z; *z2 && p2; p2--){\n      SQLITE_SKIP_UTF8(z2);\n    }\n    sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,\n                          SQLITE_UTF8);\n  }else{\n    if( p1+p2>len ){\n      p2 = len-p1;\n      if( p2<0 ) p2 = 0;\n    }\n    sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);\n  }\n}\n\n/*\n** Implementation of the round() function\n*/\n#ifndef SQLITE_OMIT_FLOATING_POINT\nstatic void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){\n  int n = 0;\n  double r;\n  char *zBuf;\n  assert( argc==1 || argc==2 );\n  if( argc==2 ){\n    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;\n    n = sqlite3_value_int(argv[1]);\n    if( n>30 ) n = 30;\n    if( n<0 ) n = 0;\n  }\n  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;\n  r = sqlite3_value_double(argv[0]);\n  /* If Y==0 and X will fit in a 64-bit int,\n  ** handle the rounding directly,\n  ** otherwise use printf.\n  */\n  if( r<-4503599627370496.0 || r>+4503599627370496.0 ){\n    /* The value has no fractional part so there is nothing to round */\n  }else if( n==0 ){  \n    r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5)));\n  }else{\n    zBuf = sqlite3_mprintf(\"%.*f\",n,r);\n    if( zBuf==0 ){\n      sqlite3_result_error_nomem(context);\n      return;\n    }\n    sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);\n    sqlite3_free(zBuf);\n  }\n  sqlite3_result_double(context, r);\n}\n#endif\n\n/*\n** Allocate nByte bytes of space using sqlite3Malloc(). If the\n** allocation fails, call sqlite3_result_error_nomem() to notify\n** the database handle that malloc() has failed and return NULL.\n** If nByte is larger than the maximum string or blob length, then\n** raise an SQLITE_TOOBIG exception and return NULL.\n*/\nstatic void *contextMalloc(sqlite3_context *context, i64 nByte){\n  char *z;\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  assert( nByte>0 );\n  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );\n  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );\n  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){\n    sqlite3_result_error_toobig(context);\n    z = 0;\n  }else{\n    z = sqlite3Malloc(nByte);\n    if( !z ){\n      sqlite3_result_error_nomem(context);\n    }\n  }\n  return z;\n}\n\n/*\n** Implementation of the upper() and lower() SQL functions.\n*/\nstatic void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){\n  char *z1;\n  const char *z2;\n  int i, n;\n  UNUSED_PARAMETER(argc);\n  z2 = (char*)sqlite3_value_text(argv[0]);\n  n = sqlite3_value_bytes(argv[0]);\n  /* Verify that the call to _bytes() does not invalidate the _text() pointer */\n  assert( z2==(char*)sqlite3_value_text(argv[0]) );\n  if( z2 ){\n    z1 = contextMalloc(context, ((i64)n)+1);\n    if( z1 ){\n      for(i=0; i<n; i++){\n        z1[i] = (char)sqlite3Toupper(z2[i]);\n      }\n      sqlite3_result_text(context, z1, n, sqlite3_free);\n    }\n  }\n}\nstatic void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){\n  char *z1;\n  const char *z2;\n  int i, n;\n  UNUSED_PARAMETER(argc);\n  z2 = (char*)sqlite3_value_text(argv[0]);\n  n = sqlite3_value_bytes(argv[0]);\n  /* Verify that the call to _bytes() does not invalidate the _text() pointer */\n  assert( z2==(char*)sqlite3_value_text(argv[0]) );\n  if( z2 ){\n    z1 = contextMalloc(context, ((i64)n)+1);\n    if( z1 ){\n      for(i=0; i<n; i++){\n        z1[i] = sqlite3Tolower(z2[i]);\n      }\n      sqlite3_result_text(context, z1, n, sqlite3_free);\n    }\n  }\n}\n\n/*\n** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented\n** as VDBE code so that unused argument values do not have to be computed.\n** However, we still need some kind of function implementation for this\n** routines in the function table.  The noopFunc macro provides this.\n** noopFunc will never be called so it doesn't matter what the implementation\n** is.  We might as well use the \"version()\" function as a substitute.\n*/\n#define noopFunc versionFunc   /* Substitute function - never called */\n\n/*\n** Implementation of random().  Return a random integer.  \n*/\nstatic void randomFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **NotUsed2\n){\n  sqlite_int64 r;\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  sqlite3_randomness(sizeof(r), &r);\n  if( r<0 ){\n    /* We need to prevent a random number of 0x8000000000000000 \n    ** (or -9223372036854775808) since when you do abs() of that\n    ** number of you get the same value back again.  To do this\n    ** in a way that is testable, mask the sign bit off of negative\n    ** values, resulting in a positive value.  Then take the \n    ** 2s complement of that positive value.  The end result can\n    ** therefore be no less than -9223372036854775807.\n    */\n    r = -(r & LARGEST_INT64);\n  }\n  sqlite3_result_int64(context, r);\n}\n\n/*\n** Implementation of randomblob(N).  Return a random blob\n** that is N bytes long.\n*/\nstatic void randomBlob(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  sqlite3_int64 n;\n  unsigned char *p;\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  n = sqlite3_value_int64(argv[0]);\n  if( n<1 ){\n    n = 1;\n  }\n  p = contextMalloc(context, n);\n  if( p ){\n    sqlite3_randomness(n, p);\n    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);\n  }\n}\n\n/*\n** Implementation of the last_insert_rowid() SQL function.  The return\n** value is the same as the sqlite3_last_insert_rowid() API function.\n*/\nstatic void last_insert_rowid(\n  sqlite3_context *context, \n  int NotUsed, \n  sqlite3_value **NotUsed2\n){\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a\n  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface\n  ** function. */\n  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));\n}\n\n/*\n** Implementation of the changes() SQL function.\n**\n** IMP: R-62073-11209 The changes() SQL function is a wrapper\n** around the sqlite3_changes() C/C++ function and hence follows the same\n** rules for counting changes.\n*/\nstatic void changes(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **NotUsed2\n){\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  sqlite3_result_int(context, sqlite3_changes(db));\n}\n\n/*\n** Implementation of the total_changes() SQL function.  The return value is\n** the same as the sqlite3_total_changes() API function.\n*/\nstatic void total_changes(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **NotUsed2\n){\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  /* IMP: R-52756-41993 This function is a wrapper around the\n  ** sqlite3_total_changes() C/C++ interface. */\n  sqlite3_result_int(context, sqlite3_total_changes(db));\n}\n\n/*\n** A structure defining how to do GLOB-style comparisons.\n*/\nstruct compareInfo {\n  u8 matchAll;          /* \"*\" or \"%\" */\n  u8 matchOne;          /* \"?\" or \"_\" */\n  u8 matchSet;          /* \"[\" or 0 */\n  u8 noCase;            /* true to ignore case differences */\n};\n\n/*\n** For LIKE and GLOB matching on EBCDIC machines, assume that every\n** character is exactly one byte in size.  Also, provde the Utf8Read()\n** macro for fast reading of the next character in the common case where\n** the next character is ASCII.\n*/\n#if defined(SQLITE_EBCDIC)\n# define sqlite3Utf8Read(A)        (*((*A)++))\n# define Utf8Read(A)               (*(A++))\n#else\n# define Utf8Read(A)               (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))\n#endif\n\nstatic const struct compareInfo globInfo = { '*', '?', '[', 0 };\n/* The correct SQL-92 behavior is for the LIKE operator to ignore\n** case.  Thus  'a' LIKE 'A' would be true. */\nstatic const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };\n/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator\n** is case sensitive causing 'a' LIKE 'A' to be false */\nstatic const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };\n\n/*\n** Possible error returns from patternMatch()\n*/\n#define SQLITE_MATCH             0\n#define SQLITE_NOMATCH           1\n#define SQLITE_NOWILDCARDMATCH   2\n\n/*\n** Compare two UTF-8 strings for equality where the first string is\n** a GLOB or LIKE expression.  Return values:\n**\n**    SQLITE_MATCH:            Match\n**    SQLITE_NOMATCH:          No match\n**    SQLITE_NOWILDCARDMATCH:  No match in spite of having * or % wildcards.\n**\n** Globbing rules:\n**\n**      '*'       Matches any sequence of zero or more characters.\n**\n**      '?'       Matches exactly one character.\n**\n**     [...]      Matches one character from the enclosed list of\n**                characters.\n**\n**     [^...]     Matches one character not in the enclosed list.\n**\n** With the [...] and [^...] matching, a ']' character can be included\n** in the list by making it the first character after '[' or '^'.  A\n** range of characters can be specified using '-'.  Example:\n** \"[a-z]\" matches any single lower-case letter.  To match a '-', make\n** it the last character in the list.\n**\n** Like matching rules:\n** \n**      '%'       Matches any sequence of zero or more characters\n**\n***     '_'       Matches any one character\n**\n**      Ec        Where E is the \"esc\" character and c is any other\n**                character, including '%', '_', and esc, match exactly c.\n**\n** The comments within this routine usually assume glob matching.\n**\n** This routine is usually quick, but can be N**2 in the worst case.\n*/\nstatic int patternCompare(\n  const u8 *zPattern,              /* The glob pattern */\n  const u8 *zString,               /* The string to compare against the glob */\n  const struct compareInfo *pInfo, /* Information about how to do the compare */\n  u32 matchOther                   /* The escape char (LIKE) or '[' (GLOB) */\n){\n  u32 c, c2;                       /* Next pattern and input string chars */\n  u32 matchOne = pInfo->matchOne;  /* \"?\" or \"_\" */\n  u32 matchAll = pInfo->matchAll;  /* \"*\" or \"%\" */\n  u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */\n  const u8 *zEscaped = 0;          /* One past the last escaped input char */\n  \n  while( (c = Utf8Read(zPattern))!=0 ){\n    if( c==matchAll ){  /* Match \"*\" */\n      /* Skip over multiple \"*\" characters in the pattern.  If there\n      ** are also \"?\" characters, skip those as well, but consume a\n      ** single character of the input string for each \"?\" skipped */\n      while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){\n        if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){\n          return SQLITE_NOWILDCARDMATCH;\n        }\n      }\n      if( c==0 ){\n        return SQLITE_MATCH;   /* \"*\" at the end of the pattern matches */\n      }else if( c==matchOther ){\n        if( pInfo->matchSet==0 ){\n          c = sqlite3Utf8Read(&zPattern);\n          if( c==0 ) return SQLITE_NOWILDCARDMATCH;\n        }else{\n          /* \"[...]\" immediately follows the \"*\".  We have to do a slow\n          ** recursive search in this case, but it is an unusual case. */\n          assert( matchOther<0x80 );  /* '[' is a single-byte character */\n          while( *zString ){\n            int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);\n            if( bMatch!=SQLITE_NOMATCH ) return bMatch;\n            SQLITE_SKIP_UTF8(zString);\n          }\n          return SQLITE_NOWILDCARDMATCH;\n        }\n      }\n\n      /* At this point variable c contains the first character of the\n      ** pattern string past the \"*\".  Search in the input string for the\n      ** first matching character and recursively continue the match from\n      ** that point.\n      **\n      ** For a case-insensitive search, set variable cx to be the same as\n      ** c but in the other case and search the input string for either\n      ** c or cx.\n      */\n      if( c<=0x80 ){\n        char zStop[3];\n        int bMatch;\n        if( noCase ){\n          zStop[0] = sqlite3Toupper(c);\n          zStop[1] = sqlite3Tolower(c);\n          zStop[2] = 0;\n        }else{\n          zStop[0] = c;\n          zStop[1] = 0;\n        }\n        while(1){\n          zString += strcspn((const char*)zString, zStop);\n          if( zString[0]==0 ) break;\n          zString++;\n          bMatch = patternCompare(zPattern,zString,pInfo,matchOther);\n          if( bMatch!=SQLITE_NOMATCH ) return bMatch;\n        }\n      }else{\n        int bMatch;\n        while( (c2 = Utf8Read(zString))!=0 ){\n          if( c2!=c ) continue;\n          bMatch = patternCompare(zPattern,zString,pInfo,matchOther);\n          if( bMatch!=SQLITE_NOMATCH ) return bMatch;\n        }\n      }\n      return SQLITE_NOWILDCARDMATCH;\n    }\n    if( c==matchOther ){\n      if( pInfo->matchSet==0 ){\n        c = sqlite3Utf8Read(&zPattern);\n        if( c==0 ) return SQLITE_NOMATCH;\n        zEscaped = zPattern;\n      }else{\n        u32 prior_c = 0;\n        int seen = 0;\n        int invert = 0;\n        c = sqlite3Utf8Read(&zString);\n        if( c==0 ) return SQLITE_NOMATCH;\n        c2 = sqlite3Utf8Read(&zPattern);\n        if( c2=='^' ){\n          invert = 1;\n          c2 = sqlite3Utf8Read(&zPattern);\n        }\n        if( c2==']' ){\n          if( c==']' ) seen = 1;\n          c2 = sqlite3Utf8Read(&zPattern);\n        }\n        while( c2 && c2!=']' ){\n          if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){\n            c2 = sqlite3Utf8Read(&zPattern);\n            if( c>=prior_c && c<=c2 ) seen = 1;\n            prior_c = 0;\n          }else{\n            if( c==c2 ){\n              seen = 1;\n            }\n            prior_c = c2;\n          }\n          c2 = sqlite3Utf8Read(&zPattern);\n        }\n        if( c2==0 || (seen ^ invert)==0 ){\n          return SQLITE_NOMATCH;\n        }\n        continue;\n      }\n    }\n    c2 = Utf8Read(zString);\n    if( c==c2 ) continue;\n    if( noCase  && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){\n      continue;\n    }\n    if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;\n    return SQLITE_NOMATCH;\n  }\n  return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;\n}\n\n/*\n** The sqlite3_strglob() interface.  Return 0 on a match (like strcmp()) and\n** non-zero if there is no match.\n*/\nSQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){\n  return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');\n}\n\n/*\n** The sqlite3_strlike() interface.  Return 0 on a match and non-zero for\n** a miss - like strcmp().\n*/\nSQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){\n  return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);\n}\n\n/*\n** Count the number of times that the LIKE operator (or GLOB which is\n** just a variation of LIKE) gets called.  This is used for testing\n** only.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_like_count = 0;\n#endif\n\n\n/*\n** Implementation of the like() SQL function.  This function implements\n** the build-in LIKE operator.  The first argument to the function is the\n** pattern and the second argument is the string.  So, the SQL statements:\n**\n**       A LIKE B\n**\n** is implemented as like(B,A).\n**\n** This same function (with a different compareInfo structure) computes\n** the GLOB operator.\n*/\nstatic void likeFunc(\n  sqlite3_context *context, \n  int argc, \n  sqlite3_value **argv\n){\n  const unsigned char *zA, *zB;\n  u32 escape;\n  int nPat;\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  struct compareInfo *pInfo = sqlite3_user_data(context);\n  struct compareInfo backupInfo;\n\n#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS\n  if( sqlite3_value_type(argv[0])==SQLITE_BLOB\n   || sqlite3_value_type(argv[1])==SQLITE_BLOB\n  ){\n#ifdef SQLITE_TEST\n    sqlite3_like_count++;\n#endif\n    sqlite3_result_int(context, 0);\n    return;\n  }\n#endif\n\n  /* Limit the length of the LIKE or GLOB pattern to avoid problems\n  ** of deep recursion and N*N behavior in patternCompare().\n  */\n  nPat = sqlite3_value_bytes(argv[0]);\n  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );\n  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );\n  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){\n    sqlite3_result_error(context, \"LIKE or GLOB pattern too complex\", -1);\n    return;\n  }\n  if( argc==3 ){\n    /* The escape character string must consist of a single UTF-8 character.\n    ** Otherwise, return an error.\n    */\n    const unsigned char *zEsc = sqlite3_value_text(argv[2]);\n    if( zEsc==0 ) return;\n    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){\n      sqlite3_result_error(context, \n          \"ESCAPE expression must be a single character\", -1);\n      return;\n    }\n    escape = sqlite3Utf8Read(&zEsc);\n    if( escape==pInfo->matchAll || escape==pInfo->matchOne ){\n      memcpy(&backupInfo, pInfo, sizeof(backupInfo));\n      pInfo = &backupInfo;\n      if( escape==pInfo->matchAll ) pInfo->matchAll = 0;\n      if( escape==pInfo->matchOne ) pInfo->matchOne = 0;\n    }\n  }else{\n    escape = pInfo->matchSet;\n  }\n  zB = sqlite3_value_text(argv[0]);\n  zA = sqlite3_value_text(argv[1]);\n  if( zA && zB ){\n#ifdef SQLITE_TEST\n    sqlite3_like_count++;\n#endif\n    sqlite3_result_int(context,\n                      patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);\n  }\n}\n\n/*\n** Implementation of the NULLIF(x,y) function.  The result is the first\n** argument if the arguments are different.  The result is NULL if the\n** arguments are equal to each other.\n*/\nstatic void nullifFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **argv\n){\n  CollSeq *pColl = sqlite3GetFuncCollSeq(context);\n  UNUSED_PARAMETER(NotUsed);\n  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){\n    sqlite3_result_value(context, argv[0]);\n  }\n}\n\n/*\n** Implementation of the sqlite_version() function.  The result is the version\n** of the SQLite library that is running.\n*/\nstatic void versionFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **NotUsed2\n){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  /* IMP: R-48699-48617 This function is an SQL wrapper around the\n  ** sqlite3_libversion() C-interface. */\n  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);\n}\n\n/*\n** Implementation of the sqlite_source_id() function. The result is a string\n** that identifies the particular version of the source code used to build\n** SQLite.\n*/\nstatic void sourceidFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **NotUsed2\n){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  /* IMP: R-24470-31136 This function is an SQL wrapper around the\n  ** sqlite3_sourceid() C interface. */\n  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);\n}\n\n/*\n** Implementation of the sqlite_log() function.  This is a wrapper around\n** sqlite3_log().  The return value is NULL.  The function exists purely for\n** its side-effects.\n*/\nstatic void errlogFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  UNUSED_PARAMETER(argc);\n  UNUSED_PARAMETER(context);\n  sqlite3_log(sqlite3_value_int(argv[0]), \"%s\", sqlite3_value_text(argv[1]));\n}\n\n/*\n** Implementation of the sqlite_compileoption_used() function.\n** The result is an integer that identifies if the compiler option\n** was used to build SQLite.\n*/\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\nstatic void compileoptionusedFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  const char *zOptName;\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL\n  ** function is a wrapper around the sqlite3_compileoption_used() C/C++\n  ** function.\n  */\n  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){\n    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));\n  }\n}\n#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */\n\n/*\n** Implementation of the sqlite_compileoption_get() function. \n** The result is a string that identifies the compiler options \n** used to build SQLite.\n*/\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\nstatic void compileoptiongetFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  int n;\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function\n  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.\n  */\n  n = sqlite3_value_int(argv[0]);\n  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);\n}\n#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */\n\n/* Array for converting from half-bytes (nybbles) into ASCII hex\n** digits. */\nstatic const char hexdigits[] = {\n  '0', '1', '2', '3', '4', '5', '6', '7',\n  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' \n};\n\n/*\n** Implementation of the QUOTE() function.  This function takes a single\n** argument.  If the argument is numeric, the return value is the same as\n** the argument.  If the argument is NULL, the return value is the string\n** \"NULL\".  Otherwise, the argument is enclosed in single quotes with\n** single-quote escapes.\n*/\nstatic void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  switch( sqlite3_value_type(argv[0]) ){\n    case SQLITE_FLOAT: {\n      double r1, r2;\n      char zBuf[50];\n      r1 = sqlite3_value_double(argv[0]);\n      sqlite3_snprintf(sizeof(zBuf), zBuf, \"%!.15g\", r1);\n      sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);\n      if( r1!=r2 ){\n        sqlite3_snprintf(sizeof(zBuf), zBuf, \"%!.20e\", r1);\n      }\n      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);\n      break;\n    }\n    case SQLITE_INTEGER: {\n      sqlite3_result_value(context, argv[0]);\n      break;\n    }\n    case SQLITE_BLOB: {\n      char *zText = 0;\n      char const *zBlob = sqlite3_value_blob(argv[0]);\n      int nBlob = sqlite3_value_bytes(argv[0]);\n      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */\n      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); \n      if( zText ){\n        int i;\n        for(i=0; i<nBlob; i++){\n          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];\n          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];\n        }\n        zText[(nBlob*2)+2] = '\\'';\n        zText[(nBlob*2)+3] = '\\0';\n        zText[0] = 'X';\n        zText[1] = '\\'';\n        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);\n        sqlite3_free(zText);\n      }\n      break;\n    }\n    case SQLITE_TEXT: {\n      int i,j;\n      u64 n;\n      const unsigned char *zArg = sqlite3_value_text(argv[0]);\n      char *z;\n\n      if( zArg==0 ) return;\n      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\\'' ) n++; }\n      z = contextMalloc(context, ((i64)i)+((i64)n)+3);\n      if( z ){\n        z[0] = '\\'';\n        for(i=0, j=1; zArg[i]; i++){\n          z[j++] = zArg[i];\n          if( zArg[i]=='\\'' ){\n            z[j++] = '\\'';\n          }\n        }\n        z[j++] = '\\'';\n        z[j] = 0;\n        sqlite3_result_text(context, z, j, sqlite3_free);\n      }\n      break;\n    }\n    default: {\n      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );\n      sqlite3_result_text(context, \"NULL\", 4, SQLITE_STATIC);\n      break;\n    }\n  }\n}\n\n/*\n** The unicode() function.  Return the integer unicode code-point value\n** for the first character of the input string. \n*/\nstatic void unicodeFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  const unsigned char *z = sqlite3_value_text(argv[0]);\n  (void)argc;\n  if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));\n}\n\n/*\n** The char() function takes zero or more arguments, each of which is\n** an integer.  It constructs a string where each character of the string\n** is the unicode character for the corresponding integer argument.\n*/\nstatic void charFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  unsigned char *z, *zOut;\n  int i;\n  zOut = z = sqlite3_malloc64( argc*4+1 );\n  if( z==0 ){\n    sqlite3_result_error_nomem(context);\n    return;\n  }\n  for(i=0; i<argc; i++){\n    sqlite3_int64 x;\n    unsigned c;\n    x = sqlite3_value_int64(argv[i]);\n    if( x<0 || x>0x10ffff ) x = 0xfffd;\n    c = (unsigned)(x & 0x1fffff);\n    if( c<0x00080 ){\n      *zOut++ = (u8)(c&0xFF);\n    }else if( c<0x00800 ){\n      *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);\n      *zOut++ = 0x80 + (u8)(c & 0x3F);\n    }else if( c<0x10000 ){\n      *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);\n      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);\n      *zOut++ = 0x80 + (u8)(c & 0x3F);\n    }else{\n      *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);\n      *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);\n      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);\n      *zOut++ = 0x80 + (u8)(c & 0x3F);\n    }                                                    \\\n  }\n  sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);\n}\n\n/*\n** The hex() function.  Interpret the argument as a blob.  Return\n** a hexadecimal rendering as text.\n*/\nstatic void hexFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  int i, n;\n  const unsigned char *pBlob;\n  char *zHex, *z;\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  pBlob = sqlite3_value_blob(argv[0]);\n  n = sqlite3_value_bytes(argv[0]);\n  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */\n  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);\n  if( zHex ){\n    for(i=0; i<n; i++, pBlob++){\n      unsigned char c = *pBlob;\n      *(z++) = hexdigits[(c>>4)&0xf];\n      *(z++) = hexdigits[c&0xf];\n    }\n    *z = 0;\n    sqlite3_result_text(context, zHex, n*2, sqlite3_free);\n  }\n}\n\n/*\n** The zeroblob(N) function returns a zero-filled blob of size N bytes.\n*/\nstatic void zeroblobFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  i64 n;\n  int rc;\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  n = sqlite3_value_int64(argv[0]);\n  if( n<0 ) n = 0;\n  rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */\n  if( rc ){\n    sqlite3_result_error_code(context, rc);\n  }\n}\n\n/*\n** The replace() function.  Three arguments are all strings: call\n** them A, B, and C. The result is also a string which is derived\n** from A by replacing every occurrence of B with C.  The match\n** must be exact.  Collating sequences are not used.\n*/\nstatic void replaceFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  const unsigned char *zStr;        /* The input string A */\n  const unsigned char *zPattern;    /* The pattern string B */\n  const unsigned char *zRep;        /* The replacement string C */\n  unsigned char *zOut;              /* The output */\n  int nStr;                /* Size of zStr */\n  int nPattern;            /* Size of zPattern */\n  int nRep;                /* Size of zRep */\n  i64 nOut;                /* Maximum size of zOut */\n  int loopLimit;           /* Last zStr[] that might match zPattern[] */\n  int i, j;                /* Loop counters */\n  unsigned cntExpand;      /* Number zOut expansions */\n  sqlite3 *db = sqlite3_context_db_handle(context);\n\n  assert( argc==3 );\n  UNUSED_PARAMETER(argc);\n  zStr = sqlite3_value_text(argv[0]);\n  if( zStr==0 ) return;\n  nStr = sqlite3_value_bytes(argv[0]);\n  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */\n  zPattern = sqlite3_value_text(argv[1]);\n  if( zPattern==0 ){\n    assert( sqlite3_value_type(argv[1])==SQLITE_NULL\n            || sqlite3_context_db_handle(context)->mallocFailed );\n    return;\n  }\n  if( zPattern[0]==0 ){\n    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );\n    sqlite3_result_value(context, argv[0]);\n    return;\n  }\n  nPattern = sqlite3_value_bytes(argv[1]);\n  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */\n  zRep = sqlite3_value_text(argv[2]);\n  if( zRep==0 ) return;\n  nRep = sqlite3_value_bytes(argv[2]);\n  assert( zRep==sqlite3_value_text(argv[2]) );\n  nOut = nStr + 1;\n  assert( nOut<SQLITE_MAX_LENGTH );\n  zOut = contextMalloc(context, (i64)nOut);\n  if( zOut==0 ){\n    return;\n  }\n  loopLimit = nStr - nPattern;  \n  cntExpand = 0;\n  for(i=j=0; i<=loopLimit; i++){\n    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){\n      zOut[j++] = zStr[i];\n    }else{\n      if( nRep>nPattern ){\n        nOut += nRep - nPattern;\n        testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );\n        testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );\n        if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){\n          sqlite3_result_error_toobig(context);\n          sqlite3_free(zOut);\n          return;\n        }\n        cntExpand++;\n        if( (cntExpand&(cntExpand-1))==0 ){\n          /* Grow the size of the output buffer only on substitutions\n          ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */\n          u8 *zOld;\n          zOld = zOut;\n          zOut = sqlite3Realloc(zOut, (int)nOut + (nOut - nStr - 1));\n          if( zOut==0 ){\n            sqlite3_result_error_nomem(context);\n            sqlite3_free(zOld);\n            return;\n          }\n        }\n      }\n      memcpy(&zOut[j], zRep, nRep);\n      j += nRep;\n      i += nPattern-1;\n    }\n  }\n  assert( j+nStr-i+1<=nOut );\n  memcpy(&zOut[j], &zStr[i], nStr-i);\n  j += nStr - i;\n  assert( j<=nOut );\n  zOut[j] = 0;\n  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);\n}\n\n/*\n** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.\n** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.\n*/\nstatic void trimFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  const unsigned char *zIn;         /* Input string */\n  const unsigned char *zCharSet;    /* Set of characters to trim */\n  int nIn;                          /* Number of bytes in input */\n  int flags;                        /* 1: trimleft  2: trimright  3: trim */\n  int i;                            /* Loop counter */\n  unsigned char *aLen = 0;          /* Length of each character in zCharSet */\n  unsigned char **azChar = 0;       /* Individual characters in zCharSet */\n  int nChar;                        /* Number of characters in zCharSet */\n\n  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){\n    return;\n  }\n  zIn = sqlite3_value_text(argv[0]);\n  if( zIn==0 ) return;\n  nIn = sqlite3_value_bytes(argv[0]);\n  assert( zIn==sqlite3_value_text(argv[0]) );\n  if( argc==1 ){\n    static const unsigned char lenOne[] = { 1 };\n    static unsigned char * const azOne[] = { (u8*)\" \" };\n    nChar = 1;\n    aLen = (u8*)lenOne;\n    azChar = (unsigned char **)azOne;\n    zCharSet = 0;\n  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){\n    return;\n  }else{\n    const unsigned char *z;\n    for(z=zCharSet, nChar=0; *z; nChar++){\n      SQLITE_SKIP_UTF8(z);\n    }\n    if( nChar>0 ){\n      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));\n      if( azChar==0 ){\n        return;\n      }\n      aLen = (unsigned char*)&azChar[nChar];\n      for(z=zCharSet, nChar=0; *z; nChar++){\n        azChar[nChar] = (unsigned char *)z;\n        SQLITE_SKIP_UTF8(z);\n        aLen[nChar] = (u8)(z - azChar[nChar]);\n      }\n    }\n  }\n  if( nChar>0 ){\n    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));\n    if( flags & 1 ){\n      while( nIn>0 ){\n        int len = 0;\n        for(i=0; i<nChar; i++){\n          len = aLen[i];\n          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;\n        }\n        if( i>=nChar ) break;\n        zIn += len;\n        nIn -= len;\n      }\n    }\n    if( flags & 2 ){\n      while( nIn>0 ){\n        int len = 0;\n        for(i=0; i<nChar; i++){\n          len = aLen[i];\n          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;\n        }\n        if( i>=nChar ) break;\n        nIn -= len;\n      }\n    }\n    if( zCharSet ){\n      sqlite3_free(azChar);\n    }\n  }\n  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);\n}\n\n\n#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION\n/*\n** The \"unknown\" function is automatically substituted in place of\n** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN\n** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.\n** When the \"sqlite3\" command-line shell is built using this functionality,\n** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries\n** involving application-defined functions to be examined in a generic\n** sqlite3 shell.\n*/\nstatic void unknownFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  /* no-op */\n}\n#endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/\n\n\n/* IMP: R-25361-16150 This function is omitted from SQLite by default. It\n** is only available if the SQLITE_SOUNDEX compile-time option is used\n** when SQLite is built.\n*/\n#ifdef SQLITE_SOUNDEX\n/*\n** Compute the soundex encoding of a word.\n**\n** IMP: R-59782-00072 The soundex(X) function returns a string that is the\n** soundex encoding of the string X. \n*/\nstatic void soundexFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  char zResult[8];\n  const u8 *zIn;\n  int i, j;\n  static const unsigned char iCode[] = {\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,\n    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,\n    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,\n    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,\n  };\n  assert( argc==1 );\n  zIn = (u8*)sqlite3_value_text(argv[0]);\n  if( zIn==0 ) zIn = (u8*)\"\";\n  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}\n  if( zIn[i] ){\n    u8 prevcode = iCode[zIn[i]&0x7f];\n    zResult[0] = sqlite3Toupper(zIn[i]);\n    for(j=1; j<4 && zIn[i]; i++){\n      int code = iCode[zIn[i]&0x7f];\n      if( code>0 ){\n        if( code!=prevcode ){\n          prevcode = code;\n          zResult[j++] = code + '0';\n        }\n      }else{\n        prevcode = 0;\n      }\n    }\n    while( j<4 ){\n      zResult[j++] = '0';\n    }\n    zResult[j] = 0;\n    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);\n  }else{\n    /* IMP: R-64894-50321 The string \"?000\" is returned if the argument\n    ** is NULL or contains no ASCII alphabetic characters. */\n    sqlite3_result_text(context, \"?000\", 4, SQLITE_STATIC);\n  }\n}\n#endif /* SQLITE_SOUNDEX */\n\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\n/*\n** A function that loads a shared-library extension then returns NULL.\n*/\nstatic void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){\n  const char *zFile = (const char *)sqlite3_value_text(argv[0]);\n  const char *zProc;\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  char *zErrMsg = 0;\n\n  /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc\n  ** flag is set.  See the sqlite3_enable_load_extension() API.\n  */\n  if( (db->flags & SQLITE_LoadExtFunc)==0 ){\n    sqlite3_result_error(context, \"not authorized\", -1);\n    return;\n  }\n\n  if( argc==2 ){\n    zProc = (const char *)sqlite3_value_text(argv[1]);\n  }else{\n    zProc = 0;\n  }\n  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){\n    sqlite3_result_error(context, zErrMsg, -1);\n    sqlite3_free(zErrMsg);\n  }\n}\n#endif\n\n\n/*\n** An instance of the following structure holds the context of a\n** sum() or avg() aggregate computation.\n*/\ntypedef struct SumCtx SumCtx;\nstruct SumCtx {\n  double rSum;      /* Floating point sum */\n  i64 iSum;         /* Integer sum */   \n  i64 cnt;          /* Number of elements summed */\n  u8 overflow;      /* True if integer overflow seen */\n  u8 approx;        /* True if non-integer value was input to the sum */\n};\n\n/*\n** Routines used to compute the sum, average, and total.\n**\n** The SUM() function follows the (broken) SQL standard which means\n** that it returns NULL if it sums over no inputs.  TOTAL returns\n** 0.0 in that case.  In addition, TOTAL always returns a float where\n** SUM might return an integer if it never encounters a floating point\n** value.  TOTAL never fails, but SUM might through an exception if\n** it overflows an integer.\n*/\nstatic void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){\n  SumCtx *p;\n  int type;\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  p = sqlite3_aggregate_context(context, sizeof(*p));\n  type = sqlite3_value_numeric_type(argv[0]);\n  if( p && type!=SQLITE_NULL ){\n    p->cnt++;\n    if( type==SQLITE_INTEGER ){\n      i64 v = sqlite3_value_int64(argv[0]);\n      p->rSum += v;\n      if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){\n        p->approx = p->overflow = 1;\n      }\n    }else{\n      p->rSum += sqlite3_value_double(argv[0]);\n      p->approx = 1;\n    }\n  }\n}\n#ifndef SQLITE_OMIT_WINDOWFUNC\nstatic void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){\n  SumCtx *p;\n  int type;\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  p = sqlite3_aggregate_context(context, sizeof(*p));\n  type = sqlite3_value_numeric_type(argv[0]);\n  /* p is always non-NULL because sumStep() will have been called first\n  ** to initialize it */\n  if( ALWAYS(p) && type!=SQLITE_NULL ){\n    assert( p->cnt>0 );\n    p->cnt--;\n    assert( type==SQLITE_INTEGER || p->approx );\n    if( type==SQLITE_INTEGER && p->approx==0 ){\n      i64 v = sqlite3_value_int64(argv[0]);\n      p->rSum -= v;\n      p->iSum -= v;\n    }else{\n      p->rSum -= sqlite3_value_double(argv[0]);\n    }\n  }\n}\n#else\n# define sumInverse 0\n#endif /* SQLITE_OMIT_WINDOWFUNC */\nstatic void sumFinalize(sqlite3_context *context){\n  SumCtx *p;\n  p = sqlite3_aggregate_context(context, 0);\n  if( p && p->cnt>0 ){\n    if( p->overflow ){\n      sqlite3_result_error(context,\"integer overflow\",-1);\n    }else if( p->approx ){\n      sqlite3_result_double(context, p->rSum);\n    }else{\n      sqlite3_result_int64(context, p->iSum);\n    }\n  }\n}\nstatic void avgFinalize(sqlite3_context *context){\n  SumCtx *p;\n  p = sqlite3_aggregate_context(context, 0);\n  if( p && p->cnt>0 ){\n    sqlite3_result_double(context, p->rSum/(double)p->cnt);\n  }\n}\nstatic void totalFinalize(sqlite3_context *context){\n  SumCtx *p;\n  p = sqlite3_aggregate_context(context, 0);\n  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */\n  sqlite3_result_double(context, p ? p->rSum : (double)0);\n}\n\n/*\n** The following structure keeps track of state information for the\n** count() aggregate function.\n*/\ntypedef struct CountCtx CountCtx;\nstruct CountCtx {\n  i64 n;\n#ifdef SQLITE_DEBUG\n  int bInverse;                   /* True if xInverse() ever called */\n#endif\n};\n\n/*\n** Routines to implement the count() aggregate function.\n*/\nstatic void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){\n  CountCtx *p;\n  p = sqlite3_aggregate_context(context, sizeof(*p));\n  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){\n    p->n++;\n  }\n\n#ifndef SQLITE_OMIT_DEPRECATED\n  /* The sqlite3_aggregate_count() function is deprecated.  But just to make\n  ** sure it still operates correctly, verify that its count agrees with our \n  ** internal count when using count(*) and when the total count can be\n  ** expressed as a 32-bit integer. */\n  assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse\n          || p->n==sqlite3_aggregate_count(context) );\n#endif\n}   \nstatic void countFinalize(sqlite3_context *context){\n  CountCtx *p;\n  p = sqlite3_aggregate_context(context, 0);\n  sqlite3_result_int64(context, p ? p->n : 0);\n}\n#ifndef SQLITE_OMIT_WINDOWFUNC\nstatic void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){\n  CountCtx *p;\n  p = sqlite3_aggregate_context(ctx, sizeof(*p));\n  /* p is always non-NULL since countStep() will have been called first */\n  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && ALWAYS(p) ){\n    p->n--;\n#ifdef SQLITE_DEBUG\n    p->bInverse = 1;\n#endif\n  }\n}   \n#else\n# define countInverse 0\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n\n/*\n** Routines to implement min() and max() aggregate functions.\n*/\nstatic void minmaxStep(\n  sqlite3_context *context, \n  int NotUsed, \n  sqlite3_value **argv\n){\n  Mem *pArg  = (Mem *)argv[0];\n  Mem *pBest;\n  UNUSED_PARAMETER(NotUsed);\n\n  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));\n  if( !pBest ) return;\n\n  if( sqlite3_value_type(pArg)==SQLITE_NULL ){\n    if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);\n  }else if( pBest->flags ){\n    int max;\n    int cmp;\n    CollSeq *pColl = sqlite3GetFuncCollSeq(context);\n    /* This step function is used for both the min() and max() aggregates,\n    ** the only difference between the two being that the sense of the\n    ** comparison is inverted. For the max() aggregate, the\n    ** sqlite3_user_data() function returns (void *)-1. For min() it\n    ** returns (void *)db, where db is the sqlite3* database pointer.\n    ** Therefore the next statement sets variable 'max' to 1 for the max()\n    ** aggregate, or 0 for min().\n    */\n    max = sqlite3_user_data(context)!=0;\n    cmp = sqlite3MemCompare(pBest, pArg, pColl);\n    if( (max && cmp<0) || (!max && cmp>0) ){\n      sqlite3VdbeMemCopy(pBest, pArg);\n    }else{\n      sqlite3SkipAccumulatorLoad(context);\n    }\n  }else{\n    pBest->db = sqlite3_context_db_handle(context);\n    sqlite3VdbeMemCopy(pBest, pArg);\n  }\n}\nstatic void minMaxValueFinalize(sqlite3_context *context, int bValue){\n  sqlite3_value *pRes;\n  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);\n  if( pRes ){\n    if( pRes->flags ){\n      sqlite3_result_value(context, pRes);\n    }\n    if( bValue==0 ) sqlite3VdbeMemRelease(pRes);\n  }\n}\n#ifndef SQLITE_OMIT_WINDOWFUNC\nstatic void minMaxValue(sqlite3_context *context){\n  minMaxValueFinalize(context, 1);\n}\n#else\n# define minMaxValue 0\n#endif /* SQLITE_OMIT_WINDOWFUNC */\nstatic void minMaxFinalize(sqlite3_context *context){\n  minMaxValueFinalize(context, 0);\n}\n\n/*\n** group_concat(EXPR, ?SEPARATOR?)\n*/\nstatic void groupConcatStep(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  const char *zVal;\n  StrAccum *pAccum;\n  const char *zSep;\n  int nVal, nSep;\n  assert( argc==1 || argc==2 );\n  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;\n  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));\n\n  if( pAccum ){\n    sqlite3 *db = sqlite3_context_db_handle(context);\n    int firstTerm = pAccum->mxAlloc==0;\n    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];\n    if( !firstTerm ){\n      if( argc==2 ){\n        zSep = (char*)sqlite3_value_text(argv[1]);\n        nSep = sqlite3_value_bytes(argv[1]);\n      }else{\n        zSep = \",\";\n        nSep = 1;\n      }\n      if( zSep ) sqlite3_str_append(pAccum, zSep, nSep);\n    }\n    zVal = (char*)sqlite3_value_text(argv[0]);\n    nVal = sqlite3_value_bytes(argv[0]);\n    if( zVal ) sqlite3_str_append(pAccum, zVal, nVal);\n  }\n}\n#ifndef SQLITE_OMIT_WINDOWFUNC\nstatic void groupConcatInverse(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  int n;\n  StrAccum *pAccum;\n  assert( argc==1 || argc==2 );\n  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;\n  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));\n  /* pAccum is always non-NULL since groupConcatStep() will have always\n  ** run frist to initialize it */\n  if( ALWAYS(pAccum) ){\n    n = sqlite3_value_bytes(argv[0]);\n    if( argc==2 ){\n      n += sqlite3_value_bytes(argv[1]);\n    }else{\n      n++;\n    }\n    if( n>=(int)pAccum->nChar ){\n      pAccum->nChar = 0;\n    }else{\n      pAccum->nChar -= n;\n      memmove(pAccum->zText, &pAccum->zText[n], pAccum->nChar);\n    }\n    if( pAccum->nChar==0 ) pAccum->mxAlloc = 0;\n  }\n}\n#else\n# define groupConcatInverse 0\n#endif /* SQLITE_OMIT_WINDOWFUNC */\nstatic void groupConcatFinalize(sqlite3_context *context){\n  StrAccum *pAccum;\n  pAccum = sqlite3_aggregate_context(context, 0);\n  if( pAccum ){\n    if( pAccum->accError==SQLITE_TOOBIG ){\n      sqlite3_result_error_toobig(context);\n    }else if( pAccum->accError==SQLITE_NOMEM ){\n      sqlite3_result_error_nomem(context);\n    }else{    \n      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, \n                          sqlite3_free);\n    }\n  }\n}\n#ifndef SQLITE_OMIT_WINDOWFUNC\nstatic void groupConcatValue(sqlite3_context *context){\n  sqlite3_str *pAccum;\n  pAccum = (sqlite3_str*)sqlite3_aggregate_context(context, 0);\n  if( pAccum ){\n    if( pAccum->accError==SQLITE_TOOBIG ){\n      sqlite3_result_error_toobig(context);\n    }else if( pAccum->accError==SQLITE_NOMEM ){\n      sqlite3_result_error_nomem(context);\n    }else{    \n      const char *zText = sqlite3_str_value(pAccum);\n      sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);\n    }\n  }\n}\n#else\n# define groupConcatValue 0\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n\n/*\n** This routine does per-connection function registration.  Most\n** of the built-in functions above are part of the global function set.\n** This routine only deals with those that are not global.\n*/\nSQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){\n  int rc = sqlite3_overload_function(db, \"MATCH\", 2);\n  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );\n  if( rc==SQLITE_NOMEM ){\n    sqlite3OomFault(db);\n  }\n}\n\n/*\n** Re-register the built-in LIKE functions.  The caseSensitive\n** parameter determines whether or not the LIKE operator is case\n** sensitive.\n*/\nSQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){\n  struct compareInfo *pInfo;\n  int flags;\n  if( caseSensitive ){\n    pInfo = (struct compareInfo*)&likeInfoAlt;\n    flags = SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE;\n  }else{\n    pInfo = (struct compareInfo*)&likeInfoNorm;\n    flags = SQLITE_FUNC_LIKE;\n  }\n  sqlite3CreateFunc(db, \"like\", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);\n  sqlite3CreateFunc(db, \"like\", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);\n  sqlite3FindFunction(db, \"like\", 2, SQLITE_UTF8, 0)->funcFlags |= flags;\n  sqlite3FindFunction(db, \"like\", 3, SQLITE_UTF8, 0)->funcFlags |= flags;\n}\n\n/*\n** pExpr points to an expression which implements a function.  If\n** it is appropriate to apply the LIKE optimization to that function\n** then set aWc[0] through aWc[2] to the wildcard characters and the\n** escape character and then return TRUE.  If the function is not a \n** LIKE-style function then return FALSE.\n**\n** The expression \"a LIKE b ESCAPE c\" is only considered a valid LIKE\n** operator if c is a string literal that is exactly one byte in length.\n** That one byte is stored in aWc[3].  aWc[3] is set to zero if there is\n** no ESCAPE clause.\n**\n** *pIsNocase is set to true if uppercase and lowercase are equivalent for\n** the function (default for LIKE).  If the function makes the distinction\n** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to\n** false.\n*/\nSQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){\n  FuncDef *pDef;\n  int nExpr;\n  if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){\n    return 0;\n  }\n  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );\n  nExpr = pExpr->x.pList->nExpr;\n  pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);\n#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION\n  if( pDef==0 ) return 0;\n#endif\n  if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){\n    return 0;\n  }\n\n  /* The memcpy() statement assumes that the wildcard characters are\n  ** the first three statements in the compareInfo structure.  The\n  ** asserts() that follow verify that assumption\n  */\n  memcpy(aWc, pDef->pUserData, 3);\n  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );\n  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );\n  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );\n\n  if( nExpr<3 ){\n    aWc[3] = 0;\n  }else{\n    Expr *pEscape = pExpr->x.pList->a[2].pExpr;\n    char *zEscape;\n    if( pEscape->op!=TK_STRING ) return 0;\n    zEscape = pEscape->u.zToken;\n    if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;\n    if( zEscape[0]==aWc[0] ) return 0;\n    if( zEscape[0]==aWc[1] ) return 0;\n    aWc[3] = zEscape[0];\n  }\n\n  *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;\n  return 1;\n}\n\n/*\n** All of the FuncDef structures in the aBuiltinFunc[] array above\n** to the global function hash table.  This occurs at start-time (as\n** a consequence of calling sqlite3_initialize()).\n**\n** After this routine runs\n*/\nSQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){\n  /*\n  ** The following array holds FuncDef structures for all of the functions\n  ** defined in this file.\n  **\n  ** The array cannot be constant since changes are made to the\n  ** FuncDef.pHash elements at start-time.  The elements of this array\n  ** are read-only after initialization is complete.\n  **\n  ** For peak efficiency, put the most frequently used function last.\n  */\n  static FuncDef aBuiltinFunc[] = {\n/***** Functions only available with SQLITE_TESTCTRL_INTERNAL_FUNCTIONS *****/\n    TEST_FUNC(implies_nonnull_row, 2, INLINEFUNC_implies_nonnull_row, 0),\n    TEST_FUNC(expr_compare,        2, INLINEFUNC_expr_compare,        0),\n    TEST_FUNC(expr_implies_expr,   2, INLINEFUNC_expr_implies_expr,   0),\n#ifdef SQLITE_DEBUG\n    TEST_FUNC(affinity,          1, INLINEFUNC_affinity, 0),\n#endif\n/***** Regular functions *****/\n#ifdef SQLITE_SOUNDEX\n    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),\n#endif\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\n    SFUNCTION(load_extension,    1, 0, 0, loadExt          ),\n    SFUNCTION(load_extension,    2, 0, 0, loadExt          ),\n#endif\n#if SQLITE_USER_AUTHENTICATION\n    FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),\n#endif\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\n    DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),\n    DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),\n#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */\n    INLINE_FUNC(unlikely,        1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),\n    INLINE_FUNC(likelihood,      2, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),\n    INLINE_FUNC(likely,          1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),\n#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC\n    FUNCTION2(sqlite_offset,     1, 0, 0, noopFunc,  SQLITE_FUNC_OFFSET|\n                                                     SQLITE_FUNC_TYPEOF),\n#endif\n    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),\n    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),\n    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),\n    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),\n    FUNCTION(trim,               1, 3, 0, trimFunc         ),\n    FUNCTION(trim,               2, 3, 0, trimFunc         ),\n    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),\n    FUNCTION(min,                0, 0, 1, 0                ),\n    WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,\n                                          SQLITE_FUNC_MINMAX ),\n    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),\n    FUNCTION(max,                0, 1, 1, 0                ),\n    WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,\n                                          SQLITE_FUNC_MINMAX ),\n    FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),\n    FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),\n    FUNCTION(instr,              2, 0, 0, instrFunc        ),\n    FUNCTION(printf,            -1, 0, 0, printfFunc       ),\n    FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),\n    FUNCTION(char,              -1, 0, 0, charFunc         ),\n    FUNCTION(abs,                1, 0, 0, absFunc          ),\n#ifndef SQLITE_OMIT_FLOATING_POINT\n    FUNCTION(round,              1, 0, 0, roundFunc        ),\n    FUNCTION(round,              2, 0, 0, roundFunc        ),\n#endif\n    FUNCTION(upper,              1, 0, 0, upperFunc        ),\n    FUNCTION(lower,              1, 0, 0, lowerFunc        ),\n    FUNCTION(hex,                1, 0, 0, hexFunc          ),\n    INLINE_FUNC(ifnull,          2, INLINEFUNC_coalesce, 0 ),\n    VFUNCTION(random,            0, 0, 0, randomFunc       ),\n    VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),\n    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),\n    DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),\n    DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),\n    FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),\n    FUNCTION(quote,              1, 0, 0, quoteFunc        ),\n    VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),\n    VFUNCTION(changes,           0, 0, 0, changes          ),\n    VFUNCTION(total_changes,     0, 0, 0, total_changes    ),\n    FUNCTION(replace,            3, 0, 0, replaceFunc      ),\n    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),\n    FUNCTION(substr,             2, 0, 0, substrFunc       ),\n    FUNCTION(substr,             3, 0, 0, substrFunc       ),\n    WAGGREGATE(sum,   1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0),\n    WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0),\n    WAGGREGATE(avg,   1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0),\n    WAGGREGATE(count, 0,0,0, countStep, \n        countFinalize, countFinalize, countInverse, SQLITE_FUNC_COUNT  ),\n    WAGGREGATE(count, 1,0,0, countStep, \n        countFinalize, countFinalize, countInverse, 0  ),\n    WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep, \n        groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),\n    WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep, \n        groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),\n  \n    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),\n#ifdef SQLITE_CASE_SENSITIVE_LIKE\n    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),\n    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),\n#else\n    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),\n    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),\n#endif\n#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION\n    FUNCTION(unknown,           -1, 0, 0, unknownFunc      ),\n#endif\n    FUNCTION(coalesce,           1, 0, 0, 0                ),\n    FUNCTION(coalesce,           0, 0, 0, 0                ),\n    INLINE_FUNC(coalesce,       -1, INLINEFUNC_coalesce, 0 ),\n    INLINE_FUNC(iif,             3, INLINEFUNC_iif,      0 ),\n  };\n#ifndef SQLITE_OMIT_ALTERTABLE\n  sqlite3AlterFunctions();\n#endif\n  sqlite3WindowFunctions();\n  sqlite3RegisterDateTimeFunctions();\n  sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));\n\n#if 0  /* Enable to print out how the built-in functions are hashed */\n  {\n    int i;\n    FuncDef *p;\n    for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){\n      printf(\"FUNC-HASH %02d:\", i);\n      for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){\n        int n = sqlite3Strlen30(p->zName);\n        int h = p->zName[0] + n;\n        printf(\" %s(%d)\", p->zName, h);\n      }\n      printf(\"\\n\");\n    }\n  }\n#endif\n}\n\n/************** End of func.c ************************************************/\n/************** Begin file fkey.c ********************************************/\n/*\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code used by the compiler to add foreign key\n** support to compiled SQL statements.\n*/\n/* #include \"sqliteInt.h\" */\n\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n#ifndef SQLITE_OMIT_TRIGGER\n\n/*\n** Deferred and Immediate FKs\n** --------------------------\n**\n** Foreign keys in SQLite come in two flavours: deferred and immediate.\n** If an immediate foreign key constraint is violated,\n** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current\n** statement transaction rolled back. If a \n** deferred foreign key constraint is violated, no action is taken \n** immediately. However if the application attempts to commit the \n** transaction before fixing the constraint violation, the attempt fails.\n**\n** Deferred constraints are implemented using a simple counter associated\n** with the database handle. The counter is set to zero each time a \n** database transaction is opened. Each time a statement is executed \n** that causes a foreign key violation, the counter is incremented. Each\n** time a statement is executed that removes an existing violation from\n** the database, the counter is decremented. When the transaction is\n** committed, the commit fails if the current value of the counter is\n** greater than zero. This scheme has two big drawbacks:\n**\n**   * When a commit fails due to a deferred foreign key constraint, \n**     there is no way to tell which foreign constraint is not satisfied,\n**     or which row it is not satisfied for.\n**\n**   * If the database contains foreign key violations when the \n**     transaction is opened, this may cause the mechanism to malfunction.\n**\n** Despite these problems, this approach is adopted as it seems simpler\n** than the alternatives.\n**\n** INSERT operations:\n**\n**   I.1) For each FK for which the table is the child table, search\n**        the parent table for a match. If none is found increment the\n**        constraint counter.\n**\n**   I.2) For each FK for which the table is the parent table, \n**        search the child table for rows that correspond to the new\n**        row in the parent table. Decrement the counter for each row\n**        found (as the constraint is now satisfied).\n**\n** DELETE operations:\n**\n**   D.1) For each FK for which the table is the child table, \n**        search the parent table for a row that corresponds to the \n**        deleted row in the child table. If such a row is not found, \n**        decrement the counter.\n**\n**   D.2) For each FK for which the table is the parent table, search \n**        the child table for rows that correspond to the deleted row \n**        in the parent table. For each found increment the counter.\n**\n** UPDATE operations:\n**\n**   An UPDATE command requires that all 4 steps above are taken, but only\n**   for FK constraints for which the affected columns are actually \n**   modified (values must be compared at runtime).\n**\n** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.\n** This simplifies the implementation a bit.\n**\n** For the purposes of immediate FK constraints, the OR REPLACE conflict\n** resolution is considered to delete rows before the new row is inserted.\n** If a delete caused by OR REPLACE violates an FK constraint, an exception\n** is thrown, even if the FK constraint would be satisfied after the new \n** row is inserted.\n**\n** Immediate constraints are usually handled similarly. The only difference \n** is that the counter used is stored as part of each individual statement\n** object (struct Vdbe). If, after the statement has run, its immediate\n** constraint counter is greater than zero,\n** it returns SQLITE_CONSTRAINT_FOREIGNKEY\n** and the statement transaction is rolled back. An exception is an INSERT\n** statement that inserts a single row only (no triggers). In this case,\n** instead of using a counter, an exception is thrown immediately if the\n** INSERT violates a foreign key constraint. This is necessary as such\n** an INSERT does not open a statement transaction.\n**\n** TODO: How should dropping a table be handled? How should renaming a \n** table be handled?\n**\n**\n** Query API Notes\n** ---------------\n**\n** Before coding an UPDATE or DELETE row operation, the code-generator\n** for those two operations needs to know whether or not the operation\n** requires any FK processing and, if so, which columns of the original\n** row are required by the FK processing VDBE code (i.e. if FKs were\n** implemented using triggers, which of the old.* columns would be \n** accessed). No information is required by the code-generator before\n** coding an INSERT operation. The functions used by the UPDATE/DELETE\n** generation code to query for this information are:\n**\n**   sqlite3FkRequired() - Test to see if FK processing is required.\n**   sqlite3FkOldmask()  - Query for the set of required old.* columns.\n**\n**\n** Externally accessible module functions\n** --------------------------------------\n**\n**   sqlite3FkCheck()    - Check for foreign key violations.\n**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.\n**   sqlite3FkDelete()   - Delete an FKey structure.\n*/\n\n/*\n** VDBE Calling Convention\n** -----------------------\n**\n** Example:\n**\n**   For the following INSERT statement:\n**\n**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);\n**     INSERT INTO t1 VALUES(1, 2, 3.1);\n**\n**   Register (x):        2    (type integer)\n**   Register (x+1):      1    (type integer)\n**   Register (x+2):      NULL (type NULL)\n**   Register (x+3):      3.1  (type real)\n*/\n\n/*\n** A foreign key constraint requires that the key columns in the parent\n** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.\n** Given that pParent is the parent table for foreign key constraint pFKey, \n** search the schema for a unique index on the parent key columns. \n**\n** If successful, zero is returned. If the parent key is an INTEGER PRIMARY \n** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx \n** is set to point to the unique index. \n** \n** If the parent key consists of a single column (the foreign key constraint\n** is not a composite foreign key), output variable *paiCol is set to NULL.\n** Otherwise, it is set to point to an allocated array of size N, where\n** N is the number of columns in the parent key. The first element of the\n** array is the index of the child table column that is mapped by the FK\n** constraint to the parent table column stored in the left-most column\n** of index *ppIdx. The second element of the array is the index of the\n** child table column that corresponds to the second left-most column of\n** *ppIdx, and so on.\n**\n** If the required index cannot be found, either because:\n**\n**   1) The named parent key columns do not exist, or\n**\n**   2) The named parent key columns do exist, but are not subject to a\n**      UNIQUE or PRIMARY KEY constraint, or\n**\n**   3) No parent key columns were provided explicitly as part of the\n**      foreign key definition, and the parent table does not have a\n**      PRIMARY KEY, or\n**\n**   4) No parent key columns were provided explicitly as part of the\n**      foreign key definition, and the PRIMARY KEY of the parent table \n**      consists of a different number of columns to the child key in \n**      the child table.\n**\n** then non-zero is returned, and a \"foreign key mismatch\" error loaded\n** into pParse. If an OOM error occurs, non-zero is returned and the\n** pParse->db->mallocFailed flag is set.\n*/\nSQLITE_PRIVATE int sqlite3FkLocateIndex(\n  Parse *pParse,                  /* Parse context to store any error in */\n  Table *pParent,                 /* Parent table of FK constraint pFKey */\n  FKey *pFKey,                    /* Foreign key to find index for */\n  Index **ppIdx,                  /* OUT: Unique index on parent table */\n  int **paiCol                    /* OUT: Map of index columns in pFKey */\n){\n  Index *pIdx = 0;                    /* Value to return via *ppIdx */\n  int *aiCol = 0;                     /* Value to return via *paiCol */\n  int nCol = pFKey->nCol;             /* Number of columns in parent key */\n  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */\n\n  /* The caller is responsible for zeroing output parameters. */\n  assert( ppIdx && *ppIdx==0 );\n  assert( !paiCol || *paiCol==0 );\n  assert( pParse );\n\n  /* If this is a non-composite (single column) foreign key, check if it \n  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx \n  ** and *paiCol set to zero and return early. \n  **\n  ** Otherwise, for a composite foreign key (more than one column), allocate\n  ** space for the aiCol array (returned via output parameter *paiCol).\n  ** Non-composite foreign keys do not require the aiCol array.\n  */\n  if( nCol==1 ){\n    /* The FK maps to the IPK if any of the following are true:\n    **\n    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly \n    **      mapped to the primary key of table pParent, or\n    **   2) The FK is explicitly mapped to a column declared as INTEGER\n    **      PRIMARY KEY.\n    */\n    if( pParent->iPKey>=0 ){\n      if( !zKey ) return 0;\n      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;\n    }\n  }else if( paiCol ){\n    assert( nCol>1 );\n    aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));\n    if( !aiCol ) return 1;\n    *paiCol = aiCol;\n  }\n\n  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){\n    if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){ \n      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number\n      ** of columns. If each indexed column corresponds to a foreign key\n      ** column of pFKey, then this index is a winner.  */\n\n      if( zKey==0 ){\n        /* If zKey is NULL, then this foreign key is implicitly mapped to \n        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be \n        ** identified by the test.  */\n        if( IsPrimaryKeyIndex(pIdx) ){\n          if( aiCol ){\n            int i;\n            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;\n          }\n          break;\n        }\n      }else{\n        /* If zKey is non-NULL, then this foreign key was declared to\n        ** map to an explicit list of columns in table pParent. Check if this\n        ** index matches those columns. Also, check that the index uses\n        ** the default collation sequences for each column. */\n        int i, j;\n        for(i=0; i<nCol; i++){\n          i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */\n          const char *zDfltColl;            /* Def. collation for column */\n          char *zIdxCol;                    /* Name of indexed column */\n\n          if( iCol<0 ) break; /* No foreign keys against expression indexes */\n\n          /* If the index uses a collation sequence that is different from\n          ** the default collation sequence for the column, this index is\n          ** unusable. Bail out early in this case.  */\n          zDfltColl = pParent->aCol[iCol].zColl;\n          if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;\n          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;\n\n          zIdxCol = pParent->aCol[iCol].zName;\n          for(j=0; j<nCol; j++){\n            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){\n              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;\n              break;\n            }\n          }\n          if( j==nCol ) break;\n        }\n        if( i==nCol ) break;      /* pIdx is usable */\n      }\n    }\n  }\n\n  if( !pIdx ){\n    if( !pParse->disableTriggers ){\n      sqlite3ErrorMsg(pParse,\n           \"foreign key mismatch - \\\"%w\\\" referencing \\\"%w\\\"\",\n           pFKey->pFrom->zName, pFKey->zTo);\n    }\n    sqlite3DbFree(pParse->db, aiCol);\n    return 1;\n  }\n\n  *ppIdx = pIdx;\n  return 0;\n}\n\n/*\n** This function is called when a row is inserted into or deleted from the \n** child table of foreign key constraint pFKey. If an SQL UPDATE is executed \n** on the child table of pFKey, this function is invoked twice for each row\n** affected - once to \"delete\" the old row, and then again to \"insert\" the\n** new row.\n**\n** Each time it is called, this function generates VDBE code to locate the\n** row in the parent table that corresponds to the row being inserted into \n** or deleted from the child table. If the parent row can be found, no \n** special action is taken. Otherwise, if the parent row can *not* be\n** found in the parent table:\n**\n**   Operation | FK type   | Action taken\n**   --------------------------------------------------------------------------\n**   INSERT      immediate   Increment the \"immediate constraint counter\".\n**\n**   DELETE      immediate   Decrement the \"immediate constraint counter\".\n**\n**   INSERT      deferred    Increment the \"deferred constraint counter\".\n**\n**   DELETE      deferred    Decrement the \"deferred constraint counter\".\n**\n** These operations are identified in the comment at the top of this file \n** (fkey.c) as \"I.1\" and \"D.1\".\n*/\nstatic void fkLookupParent(\n  Parse *pParse,        /* Parse context */\n  int iDb,              /* Index of database housing pTab */\n  Table *pTab,          /* Parent table of FK pFKey */\n  Index *pIdx,          /* Unique index on parent key columns in pTab */\n  FKey *pFKey,          /* Foreign key constraint */\n  int *aiCol,           /* Map from parent key columns to child table columns */\n  int regData,          /* Address of array containing child table row */\n  int nIncr,            /* Increment constraint counter by this */\n  int isIgnore          /* If true, pretend pTab contains all NULL values */\n){\n  int i;                                    /* Iterator variable */\n  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */\n  int iCur = pParse->nTab - 1;              /* Cursor number to use */\n  int iOk = sqlite3VdbeMakeLabel(pParse);   /* jump here if parent key found */\n\n  sqlite3VdbeVerifyAbortable(v,\n    (!pFKey->isDeferred\n      && !(pParse->db->flags & SQLITE_DeferFKs)\n      && !pParse->pToplevel \n      && !pParse->isMultiWrite) ? OE_Abort : OE_Ignore);\n\n  /* If nIncr is less than zero, then check at runtime if there are any\n  ** outstanding constraints to resolve. If there are not, there is no need\n  ** to check if deleting this row resolves any outstanding violations.\n  **\n  ** Check if any of the key columns in the child table row are NULL. If \n  ** any are, then the constraint is considered satisfied. No need to \n  ** search for a matching row in the parent table.  */\n  if( nIncr<0 ){\n    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);\n    VdbeCoverage(v);\n  }\n  for(i=0; i<pFKey->nCol; i++){\n    int iReg = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i]) + regData + 1;\n    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);\n  }\n\n  if( isIgnore==0 ){\n    if( pIdx==0 ){\n      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY\n      ** column of the parent table (table pTab).  */\n      int iMustBeInt;               /* Address of MustBeInt instruction */\n      int regTemp = sqlite3GetTempReg(pParse);\n  \n      /* Invoke MustBeInt to coerce the child key value to an integer (i.e. \n      ** apply the affinity of the parent key). If this fails, then there\n      ** is no matching parent key. Before using MustBeInt, make a copy of\n      ** the value. Otherwise, the value inserted into the child key column\n      ** will have INTEGER affinity applied to it, which may not be correct.  */\n      sqlite3VdbeAddOp2(v, OP_SCopy, \n        sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[0])+1+regData, regTemp);\n      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);\n      VdbeCoverage(v);\n  \n      /* If the parent table is the same as the child table, and we are about\n      ** to increment the constraint-counter (i.e. this is an INSERT operation),\n      ** then check if the row being inserted matches itself. If so, do not\n      ** increment the constraint-counter.  */\n      if( pTab==pFKey->pFrom && nIncr==1 ){\n        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);\n        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);\n      }\n  \n      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);\n      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);\n      sqlite3VdbeGoto(v, iOk);\n      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);\n      sqlite3VdbeJumpHere(v, iMustBeInt);\n      sqlite3ReleaseTempReg(pParse, regTemp);\n    }else{\n      int nCol = pFKey->nCol;\n      int regTemp = sqlite3GetTempRange(pParse, nCol);\n      int regRec = sqlite3GetTempReg(pParse);\n  \n      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);\n      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);\n      for(i=0; i<nCol; i++){\n        sqlite3VdbeAddOp2(v, OP_Copy, \n               sqlite3TableColumnToStorage(pFKey->pFrom, aiCol[i])+1+regData,\n               regTemp+i);\n      }\n  \n      /* If the parent table is the same as the child table, and we are about\n      ** to increment the constraint-counter (i.e. this is an INSERT operation),\n      ** then check if the row being inserted matches itself. If so, do not\n      ** increment the constraint-counter. \n      **\n      ** If any of the parent-key values are NULL, then the row cannot match \n      ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any\n      ** of the parent-key values are NULL (at this point it is known that\n      ** none of the child key values are).\n      */\n      if( pTab==pFKey->pFrom && nIncr==1 ){\n        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;\n        for(i=0; i<nCol; i++){\n          int iChild = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i])\n                              +1+regData;\n          int iParent = 1+regData;\n          iParent += sqlite3TableColumnToStorage(pIdx->pTable,\n                                                 pIdx->aiColumn[i]);\n          assert( pIdx->aiColumn[i]>=0 );\n          assert( aiCol[i]!=pTab->iPKey );\n          if( pIdx->aiColumn[i]==pTab->iPKey ){\n            /* The parent key is a composite key that includes the IPK column */\n            iParent = regData;\n          }\n          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);\n          sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);\n        }\n        sqlite3VdbeGoto(v, iOk);\n      }\n  \n      sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,\n                        sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);\n      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);\n  \n      sqlite3ReleaseTempReg(pParse, regRec);\n      sqlite3ReleaseTempRange(pParse, regTemp, nCol);\n    }\n  }\n\n  if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)\n   && !pParse->pToplevel \n   && !pParse->isMultiWrite \n  ){\n    /* Special case: If this is an INSERT statement that will insert exactly\n    ** one row into the table, raise a constraint immediately instead of\n    ** incrementing a counter. This is necessary as the VM code is being\n    ** generated for will not open a statement transaction.  */\n    assert( nIncr==1 );\n    sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,\n        OE_Abort, 0, P4_STATIC, P5_ConstraintFK);\n  }else{\n    if( nIncr>0 && pFKey->isDeferred==0 ){\n      sqlite3MayAbort(pParse);\n    }\n    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);\n  }\n\n  sqlite3VdbeResolveLabel(v, iOk);\n  sqlite3VdbeAddOp1(v, OP_Close, iCur);\n}\n\n\n/*\n** Return an Expr object that refers to a memory register corresponding\n** to column iCol of table pTab.\n**\n** regBase is the first of an array of register that contains the data\n** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first\n** column.  regBase+2 holds the second column, and so forth.\n*/\nstatic Expr *exprTableRegister(\n  Parse *pParse,     /* Parsing and code generating context */\n  Table *pTab,       /* The table whose content is at r[regBase]... */\n  int regBase,       /* Contents of table pTab */\n  i16 iCol           /* Which column of pTab is desired */\n){\n  Expr *pExpr;\n  Column *pCol;\n  const char *zColl;\n  sqlite3 *db = pParse->db;\n\n  pExpr = sqlite3Expr(db, TK_REGISTER, 0);\n  if( pExpr ){\n    if( iCol>=0 && iCol!=pTab->iPKey ){\n      pCol = &pTab->aCol[iCol];\n      pExpr->iTable = regBase + sqlite3TableColumnToStorage(pTab,iCol) + 1;\n      pExpr->affExpr = pCol->affinity;\n      zColl = pCol->zColl;\n      if( zColl==0 ) zColl = db->pDfltColl->zName;\n      pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);\n    }else{\n      pExpr->iTable = regBase;\n      pExpr->affExpr = SQLITE_AFF_INTEGER;\n    }\n  }\n  return pExpr;\n}\n\n/*\n** Return an Expr object that refers to column iCol of table pTab which\n** has cursor iCur.\n*/\nstatic Expr *exprTableColumn(\n  sqlite3 *db,      /* The database connection */\n  Table *pTab,      /* The table whose column is desired */\n  int iCursor,      /* The open cursor on the table */\n  i16 iCol          /* The column that is wanted */\n){\n  Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);\n  if( pExpr ){\n    pExpr->y.pTab = pTab;\n    pExpr->iTable = iCursor;\n    pExpr->iColumn = iCol;\n  }\n  return pExpr;\n}\n\n/*\n** This function is called to generate code executed when a row is deleted\n** from the parent table of foreign key constraint pFKey and, if pFKey is \n** deferred, when a row is inserted into the same table. When generating\n** code for an SQL UPDATE operation, this function may be called twice -\n** once to \"delete\" the old row and once to \"insert\" the new row.\n**\n** Parameter nIncr is passed -1 when inserting a row (as this may decrease\n** the number of FK violations in the db) or +1 when deleting one (as this\n** may increase the number of FK constraint problems).\n**\n** The code generated by this function scans through the rows in the child\n** table that correspond to the parent table row being deleted or inserted.\n** For each child row found, one of the following actions is taken:\n**\n**   Operation | FK type   | Action taken\n**   --------------------------------------------------------------------------\n**   DELETE      immediate   Increment the \"immediate constraint counter\".\n**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,\n**                           throw a \"FOREIGN KEY constraint failed\" exception.\n**\n**   INSERT      immediate   Decrement the \"immediate constraint counter\".\n**\n**   DELETE      deferred    Increment the \"deferred constraint counter\".\n**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,\n**                           throw a \"FOREIGN KEY constraint failed\" exception.\n**\n**   INSERT      deferred    Decrement the \"deferred constraint counter\".\n**\n** These operations are identified in the comment at the top of this file \n** (fkey.c) as \"I.2\" and \"D.2\".\n*/\nstatic void fkScanChildren(\n  Parse *pParse,                  /* Parse context */\n  SrcList *pSrc,                  /* The child table to be scanned */\n  Table *pTab,                    /* The parent table */\n  Index *pIdx,                    /* Index on parent covering the foreign key */\n  FKey *pFKey,                    /* The foreign key linking pSrc to pTab */\n  int *aiCol,                     /* Map from pIdx cols to child table cols */\n  int regData,                    /* Parent row data starts here */\n  int nIncr                       /* Amount to increment deferred counter by */\n){\n  sqlite3 *db = pParse->db;       /* Database handle */\n  int i;                          /* Iterator variable */\n  Expr *pWhere = 0;               /* WHERE clause to scan with */\n  NameContext sNameContext;       /* Context used to resolve WHERE clause */\n  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */\n  int iFkIfZero = 0;              /* Address of OP_FkIfZero */\n  Vdbe *v = sqlite3GetVdbe(pParse);\n\n  assert( pIdx==0 || pIdx->pTable==pTab );\n  assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );\n  assert( pIdx!=0 || pFKey->nCol==1 );\n  assert( pIdx!=0 || HasRowid(pTab) );\n\n  if( nIncr<0 ){\n    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);\n    VdbeCoverage(v);\n  }\n\n  /* Create an Expr object representing an SQL expression like:\n  **\n  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...\n  **\n  ** The collation sequence used for the comparison should be that of\n  ** the parent key columns. The affinity of the parent key column should\n  ** be applied to each child key value before the comparison takes place.\n  */\n  for(i=0; i<pFKey->nCol; i++){\n    Expr *pLeft;                  /* Value from parent table row */\n    Expr *pRight;                 /* Column ref to child table */\n    Expr *pEq;                    /* Expression (pLeft = pRight) */\n    i16 iCol;                     /* Index of column in child table */ \n    const char *zCol;             /* Name of column in child table */\n\n    iCol = pIdx ? pIdx->aiColumn[i] : -1;\n    pLeft = exprTableRegister(pParse, pTab, regData, iCol);\n    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;\n    assert( iCol>=0 );\n    zCol = pFKey->pFrom->aCol[iCol].zName;\n    pRight = sqlite3Expr(db, TK_ID, zCol);\n    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);\n    pWhere = sqlite3ExprAnd(pParse, pWhere, pEq);\n  }\n\n  /* If the child table is the same as the parent table, then add terms\n  ** to the WHERE clause that prevent this entry from being scanned.\n  ** The added WHERE clause terms are like this:\n  **\n  **     $current_rowid!=rowid\n  **     NOT( $current_a==a AND $current_b==b AND ... )\n  **\n  ** The first form is used for rowid tables.  The second form is used\n  ** for WITHOUT ROWID tables. In the second form, the *parent* key is\n  ** (a,b,...). Either the parent or primary key could be used to \n  ** uniquely identify the current row, but the parent key is more convenient\n  ** as the required values have already been loaded into registers\n  ** by the caller.\n  */\n  if( pTab==pFKey->pFrom && nIncr>0 ){\n    Expr *pNe;                    /* Expression (pLeft != pRight) */\n    Expr *pLeft;                  /* Value from parent table row */\n    Expr *pRight;                 /* Column ref to child table */\n    if( HasRowid(pTab) ){\n      pLeft = exprTableRegister(pParse, pTab, regData, -1);\n      pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);\n      pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);\n    }else{\n      Expr *pEq, *pAll = 0;\n      assert( pIdx!=0 );\n      for(i=0; i<pIdx->nKeyCol; i++){\n        i16 iCol = pIdx->aiColumn[i];\n        assert( iCol>=0 );\n        pLeft = exprTableRegister(pParse, pTab, regData, iCol);\n        pRight = sqlite3Expr(db, TK_ID, pTab->aCol[iCol].zName);\n        pEq = sqlite3PExpr(pParse, TK_IS, pLeft, pRight);\n        pAll = sqlite3ExprAnd(pParse, pAll, pEq);\n      }\n      pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);\n    }\n    pWhere = sqlite3ExprAnd(pParse, pWhere, pNe);\n  }\n\n  /* Resolve the references in the WHERE clause. */\n  memset(&sNameContext, 0, sizeof(NameContext));\n  sNameContext.pSrcList = pSrc;\n  sNameContext.pParse = pParse;\n  sqlite3ResolveExprNames(&sNameContext, pWhere);\n\n  /* Create VDBE to loop through the entries in pSrc that match the WHERE\n  ** clause. For each row found, increment either the deferred or immediate\n  ** foreign key constraint counter. */\n  if( pParse->nErr==0 ){\n    pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);\n    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);\n    if( pWInfo ){\n      sqlite3WhereEnd(pWInfo);\n    }\n  }\n\n  /* Clean up the WHERE clause constructed above. */\n  sqlite3ExprDelete(db, pWhere);\n  if( iFkIfZero ){\n    sqlite3VdbeJumpHereOrPopInst(v, iFkIfZero);\n  }\n}\n\n/*\n** This function returns a linked list of FKey objects (connected by\n** FKey.pNextTo) holding all children of table pTab.  For example,\n** given the following schema:\n**\n**   CREATE TABLE t1(a PRIMARY KEY);\n**   CREATE TABLE t2(b REFERENCES t1(a);\n**\n** Calling this function with table \"t1\" as an argument returns a pointer\n** to the FKey structure representing the foreign key constraint on table\n** \"t2\". Calling this function with \"t2\" as the argument would return a\n** NULL pointer (as there are no FK constraints for which t2 is the parent\n** table).\n*/\nSQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){\n  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);\n}\n\n/*\n** The second argument is a Trigger structure allocated by the \n** fkActionTrigger() routine. This function deletes the Trigger structure\n** and all of its sub-components.\n**\n** The Trigger structure or any of its sub-components may be allocated from\n** the lookaside buffer belonging to database handle dbMem.\n*/\nstatic void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){\n  if( p ){\n    TriggerStep *pStep = p->step_list;\n    sqlite3ExprDelete(dbMem, pStep->pWhere);\n    sqlite3ExprListDelete(dbMem, pStep->pExprList);\n    sqlite3SelectDelete(dbMem, pStep->pSelect);\n    sqlite3ExprDelete(dbMem, p->pWhen);\n    sqlite3DbFree(dbMem, p);\n  }\n}\n\n/*\n** This function is called to generate code that runs when table pTab is\n** being dropped from the database. The SrcList passed as the second argument\n** to this function contains a single entry guaranteed to resolve to\n** table pTab.\n**\n** Normally, no code is required. However, if either\n**\n**   (a) The table is the parent table of a FK constraint, or\n**   (b) The table is the child table of a deferred FK constraint and it is\n**       determined at runtime that there are outstanding deferred FK \n**       constraint violations in the database,\n**\n** then the equivalent of \"DELETE FROM <tbl>\" is executed before dropping\n** the table from the database. Triggers are disabled while running this\n** DELETE, but foreign key actions are not.\n*/\nSQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){\n  sqlite3 *db = pParse->db;\n  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) ){\n    int iSkip = 0;\n    Vdbe *v = sqlite3GetVdbe(pParse);\n\n    assert( v );                  /* VDBE has already been allocated */\n    assert( pTab->pSelect==0 );   /* Not a view */\n    if( sqlite3FkReferences(pTab)==0 ){\n      /* Search for a deferred foreign key constraint for which this table\n      ** is the child table. If one cannot be found, return without \n      ** generating any VDBE code. If one can be found, then jump over\n      ** the entire DELETE if there are no outstanding deferred constraints\n      ** when this statement is run.  */\n      FKey *p;\n      for(p=pTab->pFKey; p; p=p->pNextFrom){\n        if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;\n      }\n      if( !p ) return;\n      iSkip = sqlite3VdbeMakeLabel(pParse);\n      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);\n    }\n\n    pParse->disableTriggers = 1;\n    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0, 0, 0);\n    pParse->disableTriggers = 0;\n\n    /* If the DELETE has generated immediate foreign key constraint \n    ** violations, halt the VDBE and return an error at this point, before\n    ** any modifications to the schema are made. This is because statement\n    ** transactions are not able to rollback schema changes.  \n    **\n    ** If the SQLITE_DeferFKs flag is set, then this is not required, as\n    ** the statement transaction will not be rolled back even if FK\n    ** constraints are violated.\n    */\n    if( (db->flags & SQLITE_DeferFKs)==0 ){\n      sqlite3VdbeVerifyAbortable(v, OE_Abort);\n      sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);\n      VdbeCoverage(v);\n      sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,\n          OE_Abort, 0, P4_STATIC, P5_ConstraintFK);\n    }\n\n    if( iSkip ){\n      sqlite3VdbeResolveLabel(v, iSkip);\n    }\n  }\n}\n\n\n/*\n** The second argument points to an FKey object representing a foreign key\n** for which pTab is the child table. An UPDATE statement against pTab\n** is currently being processed. For each column of the table that is \n** actually updated, the corresponding element in the aChange[] array\n** is zero or greater (if a column is unmodified the corresponding element\n** is set to -1). If the rowid column is modified by the UPDATE statement\n** the bChngRowid argument is non-zero.\n**\n** This function returns true if any of the columns that are part of the\n** child key for FK constraint *p are modified.\n*/\nstatic int fkChildIsModified(\n  Table *pTab,                    /* Table being updated */\n  FKey *p,                        /* Foreign key for which pTab is the child */\n  int *aChange,                   /* Array indicating modified columns */\n  int bChngRowid                  /* True if rowid is modified by this update */\n){\n  int i;\n  for(i=0; i<p->nCol; i++){\n    int iChildKey = p->aCol[i].iFrom;\n    if( aChange[iChildKey]>=0 ) return 1;\n    if( iChildKey==pTab->iPKey && bChngRowid ) return 1;\n  }\n  return 0;\n}\n\n/*\n** The second argument points to an FKey object representing a foreign key\n** for which pTab is the parent table. An UPDATE statement against pTab\n** is currently being processed. For each column of the table that is \n** actually updated, the corresponding element in the aChange[] array\n** is zero or greater (if a column is unmodified the corresponding element\n** is set to -1). If the rowid column is modified by the UPDATE statement\n** the bChngRowid argument is non-zero.\n**\n** This function returns true if any of the columns that are part of the\n** parent key for FK constraint *p are modified.\n*/\nstatic int fkParentIsModified(\n  Table *pTab, \n  FKey *p, \n  int *aChange, \n  int bChngRowid\n){\n  int i;\n  for(i=0; i<p->nCol; i++){\n    char *zKey = p->aCol[i].zCol;\n    int iKey;\n    for(iKey=0; iKey<pTab->nCol; iKey++){\n      if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){\n        Column *pCol = &pTab->aCol[iKey];\n        if( zKey ){\n          if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;\n        }else if( pCol->colFlags & COLFLAG_PRIMKEY ){\n          return 1;\n        }\n      }\n    }\n  }\n  return 0;\n}\n\n/*\n** Return true if the parser passed as the first argument is being\n** used to code a trigger that is really a \"SET NULL\" action belonging\n** to trigger pFKey.\n*/\nstatic int isSetNullAction(Parse *pParse, FKey *pFKey){\n  Parse *pTop = sqlite3ParseToplevel(pParse);\n  if( pTop->pTriggerPrg ){\n    Trigger *p = pTop->pTriggerPrg->pTrigger;\n    if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)\n     || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)\n    ){\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/*\n** This function is called when inserting, deleting or updating a row of\n** table pTab to generate VDBE code to perform foreign key constraint \n** processing for the operation.\n**\n** For a DELETE operation, parameter regOld is passed the index of the\n** first register in an array of (pTab->nCol+1) registers containing the\n** rowid of the row being deleted, followed by each of the column values\n** of the row being deleted, from left to right. Parameter regNew is passed\n** zero in this case.\n**\n** For an INSERT operation, regOld is passed zero and regNew is passed the\n** first register of an array of (pTab->nCol+1) registers containing the new\n** row data.\n**\n** For an UPDATE operation, this function is called twice. Once before\n** the original record is deleted from the table using the calling convention\n** described for DELETE. Then again after the original record is deleted\n** but before the new record is inserted using the INSERT convention. \n*/\nSQLITE_PRIVATE void sqlite3FkCheck(\n  Parse *pParse,                  /* Parse context */\n  Table *pTab,                    /* Row is being deleted from this table */ \n  int regOld,                     /* Previous row data is stored here */\n  int regNew,                     /* New row data is stored here */\n  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */\n  int bChngRowid                  /* True if rowid is UPDATEd */\n){\n  sqlite3 *db = pParse->db;       /* Database handle */\n  FKey *pFKey;                    /* Used to iterate through FKs */\n  int iDb;                        /* Index of database containing pTab */\n  const char *zDb;                /* Name of database containing pTab */\n  int isIgnoreErrors = pParse->disableTriggers;\n\n  /* Exactly one of regOld and regNew should be non-zero. */\n  assert( (regOld==0)!=(regNew==0) );\n\n  /* If foreign-keys are disabled, this function is a no-op. */\n  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;\n\n  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n  zDb = db->aDb[iDb].zDbSName;\n\n  /* Loop through all the foreign key constraints for which pTab is the\n  ** child table (the table that the foreign key definition is part of).  */\n  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){\n    Table *pTo;                   /* Parent table of foreign key pFKey */\n    Index *pIdx = 0;              /* Index on key columns in pTo */\n    int *aiFree = 0;\n    int *aiCol;\n    int iCol;\n    int i;\n    int bIgnore = 0;\n\n    if( aChange \n     && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0\n     && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0 \n    ){\n      continue;\n    }\n\n    /* Find the parent table of this foreign key. Also find a unique index \n    ** on the parent key columns in the parent table. If either of these \n    ** schema items cannot be located, set an error in pParse and return \n    ** early.  */\n    if( pParse->disableTriggers ){\n      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);\n    }else{\n      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);\n    }\n    if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){\n      assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );\n      if( !isIgnoreErrors || db->mallocFailed ) return;\n      if( pTo==0 ){\n        /* If isIgnoreErrors is true, then a table is being dropped. In this\n        ** case SQLite runs a \"DELETE FROM xxx\" on the table being dropped\n        ** before actually dropping it in order to check FK constraints.\n        ** If the parent table of an FK constraint on the current table is\n        ** missing, behave as if it is empty. i.e. decrement the relevant\n        ** FK counter for each row of the current table with non-NULL keys.\n        */\n        Vdbe *v = sqlite3GetVdbe(pParse);\n        int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;\n        for(i=0; i<pFKey->nCol; i++){\n          int iFromCol, iReg;\n          iFromCol = pFKey->aCol[i].iFrom;\n          iReg = sqlite3TableColumnToStorage(pFKey->pFrom,iFromCol) + regOld+1;\n          sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);\n        }\n        sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);\n      }\n      continue;\n    }\n    assert( pFKey->nCol==1 || (aiFree && pIdx) );\n\n    if( aiFree ){\n      aiCol = aiFree;\n    }else{\n      iCol = pFKey->aCol[0].iFrom;\n      aiCol = &iCol;\n    }\n    for(i=0; i<pFKey->nCol; i++){\n      if( aiCol[i]==pTab->iPKey ){\n        aiCol[i] = -1;\n      }\n      assert( pIdx==0 || pIdx->aiColumn[i]>=0 );\n#ifndef SQLITE_OMIT_AUTHORIZATION\n      /* Request permission to read the parent key columns. If the \n      ** authorization callback returns SQLITE_IGNORE, behave as if any\n      ** values read from the parent table are NULL. */\n      if( db->xAuth ){\n        int rcauth;\n        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;\n        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);\n        bIgnore = (rcauth==SQLITE_IGNORE);\n      }\n#endif\n    }\n\n    /* Take a shared-cache advisory read-lock on the parent table. Allocate \n    ** a cursor to use to search the unique index on the parent key columns \n    ** in the parent table.  */\n    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);\n    pParse->nTab++;\n\n    if( regOld!=0 ){\n      /* A row is being removed from the child table. Search for the parent.\n      ** If the parent does not exist, removing the child row resolves an \n      ** outstanding foreign key constraint violation. */\n      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);\n    }\n    if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){\n      /* A row is being added to the child table. If a parent row cannot\n      ** be found, adding the child row has violated the FK constraint. \n      **\n      ** If this operation is being performed as part of a trigger program\n      ** that is actually a \"SET NULL\" action belonging to this very \n      ** foreign key, then omit this scan altogether. As all child key\n      ** values are guaranteed to be NULL, it is not possible for adding\n      ** this row to cause an FK violation.  */\n      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);\n    }\n\n    sqlite3DbFree(db, aiFree);\n  }\n\n  /* Loop through all the foreign key constraints that refer to this table.\n  ** (the \"child\" constraints) */\n  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){\n    Index *pIdx = 0;              /* Foreign key index for pFKey */\n    SrcList *pSrc;\n    int *aiCol = 0;\n\n    if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){\n      continue;\n    }\n\n    if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs) \n     && !pParse->pToplevel && !pParse->isMultiWrite \n    ){\n      assert( regOld==0 && regNew!=0 );\n      /* Inserting a single row into a parent table cannot cause (or fix)\n      ** an immediate foreign key violation. So do nothing in this case.  */\n      continue;\n    }\n\n    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){\n      if( !isIgnoreErrors || db->mallocFailed ) return;\n      continue;\n    }\n    assert( aiCol || pFKey->nCol==1 );\n\n    /* Create a SrcList structure containing the child table.  We need the\n    ** child table as a SrcList for sqlite3WhereBegin() */\n    pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);\n    if( pSrc ){\n      struct SrcList_item *pItem = pSrc->a;\n      pItem->pTab = pFKey->pFrom;\n      pItem->zName = pFKey->pFrom->zName;\n      pItem->pTab->nTabRef++;\n      pItem->iCursor = pParse->nTab++;\n  \n      if( regNew!=0 ){\n        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);\n      }\n      if( regOld!=0 ){\n        int eAction = pFKey->aAction[aChange!=0];\n        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);\n        /* If this is a deferred FK constraint, or a CASCADE or SET NULL\n        ** action applies, then any foreign key violations caused by\n        ** removing the parent key will be rectified by the action trigger.\n        ** So do not set the \"may-abort\" flag in this case.\n        **\n        ** Note 1: If the FK is declared \"ON UPDATE CASCADE\", then the\n        ** may-abort flag will eventually be set on this statement anyway\n        ** (when this function is called as part of processing the UPDATE\n        ** within the action trigger).\n        **\n        ** Note 2: At first glance it may seem like SQLite could simply omit\n        ** all OP_FkCounter related scans when either CASCADE or SET NULL\n        ** applies. The trouble starts if the CASCADE or SET NULL action \n        ** trigger causes other triggers or action rules attached to the \n        ** child table to fire. In these cases the fk constraint counters\n        ** might be set incorrectly if any OP_FkCounter related scans are \n        ** omitted.  */\n        if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){\n          sqlite3MayAbort(pParse);\n        }\n      }\n      pItem->zName = 0;\n      sqlite3SrcListDelete(db, pSrc);\n    }\n    sqlite3DbFree(db, aiCol);\n  }\n}\n\n#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))\n\n/*\n** This function is called before generating code to update or delete a \n** row contained in table pTab.\n*/\nSQLITE_PRIVATE u32 sqlite3FkOldmask(\n  Parse *pParse,                  /* Parse context */\n  Table *pTab                     /* Table being modified */\n){\n  u32 mask = 0;\n  if( pParse->db->flags&SQLITE_ForeignKeys ){\n    FKey *p;\n    int i;\n    for(p=pTab->pFKey; p; p=p->pNextFrom){\n      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);\n    }\n    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){\n      Index *pIdx = 0;\n      sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);\n      if( pIdx ){\n        for(i=0; i<pIdx->nKeyCol; i++){\n          assert( pIdx->aiColumn[i]>=0 );\n          mask |= COLUMN_MASK(pIdx->aiColumn[i]);\n        }\n      }\n    }\n  }\n  return mask;\n}\n\n\n/*\n** This function is called before generating code to update or delete a \n** row contained in table pTab. If the operation is a DELETE, then\n** parameter aChange is passed a NULL value. For an UPDATE, aChange points\n** to an array of size N, where N is the number of columns in table pTab.\n** If the i'th column is not modified by the UPDATE, then the corresponding \n** entry in the aChange[] array is set to -1. If the column is modified,\n** the value is 0 or greater. Parameter chngRowid is set to true if the\n** UPDATE statement modifies the rowid fields of the table.\n**\n** If any foreign key processing will be required, this function returns\n** non-zero. If there is no foreign key related processing, this function \n** returns zero.\n**\n** For an UPDATE, this function returns 2 if:\n**\n**   * There are any FKs for which pTab is the child and the parent table, or\n**   * the UPDATE modifies one or more parent keys for which the action is\n**     not \"NO ACTION\" (i.e. is CASCADE, SET DEFAULT or SET NULL).\n**\n** Or, assuming some other foreign key processing is required, 1.\n*/\nSQLITE_PRIVATE int sqlite3FkRequired(\n  Parse *pParse,                  /* Parse context */\n  Table *pTab,                    /* Table being modified */\n  int *aChange,                   /* Non-NULL for UPDATE operations */\n  int chngRowid                   /* True for UPDATE that affects rowid */\n){\n  int eRet = 0;\n  if( pParse->db->flags&SQLITE_ForeignKeys ){\n    if( !aChange ){\n      /* A DELETE operation. Foreign key processing is required if the \n      ** table in question is either the child or parent table for any \n      ** foreign key constraint.  */\n      eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);\n    }else{\n      /* This is an UPDATE. Foreign key processing is only required if the\n      ** operation modifies one or more child or parent key columns. */\n      FKey *p;\n\n      /* Check if any child key columns are being modified. */\n      for(p=pTab->pFKey; p; p=p->pNextFrom){\n        if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;\n        if( fkChildIsModified(pTab, p, aChange, chngRowid) ){\n          eRet = 1;\n        }\n      }\n\n      /* Check if any parent key columns are being modified. */\n      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){\n        if( fkParentIsModified(pTab, p, aChange, chngRowid) ){\n          if( p->aAction[1]!=OE_None ) return 2;\n          eRet = 1;\n        }\n      }\n    }\n  }\n  return eRet;\n}\n\n/*\n** This function is called when an UPDATE or DELETE operation is being \n** compiled on table pTab, which is the parent table of foreign-key pFKey.\n** If the current operation is an UPDATE, then the pChanges parameter is\n** passed a pointer to the list of columns being modified. If it is a\n** DELETE, pChanges is passed a NULL pointer.\n**\n** It returns a pointer to a Trigger structure containing a trigger\n** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.\n** If the action is \"NO ACTION\" or \"RESTRICT\", then a NULL pointer is\n** returned (these actions require no special handling by the triggers\n** sub-system, code for them is created by fkScanChildren()).\n**\n** For example, if pFKey is the foreign key and pTab is table \"p\" in \n** the following schema:\n**\n**   CREATE TABLE p(pk PRIMARY KEY);\n**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);\n**\n** then the returned trigger structure is equivalent to:\n**\n**   CREATE TRIGGER ... DELETE ON p BEGIN\n**     DELETE FROM c WHERE ck = old.pk;\n**   END;\n**\n** The returned pointer is cached as part of the foreign key object. It\n** is eventually freed along with the rest of the foreign key object by \n** sqlite3FkDelete().\n*/\nstatic Trigger *fkActionTrigger(\n  Parse *pParse,                  /* Parse context */\n  Table *pTab,                    /* Table being updated or deleted from */\n  FKey *pFKey,                    /* Foreign key to get action for */\n  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */\n){\n  sqlite3 *db = pParse->db;       /* Database handle */\n  int action;                     /* One of OE_None, OE_Cascade etc. */\n  Trigger *pTrigger;              /* Trigger definition to return */\n  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */\n\n  action = pFKey->aAction[iAction];\n  if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){\n    return 0;\n  }\n  pTrigger = pFKey->apTrigger[iAction];\n\n  if( action!=OE_None && !pTrigger ){\n    char const *zFrom;            /* Name of child table */\n    int nFrom;                    /* Length in bytes of zFrom */\n    Index *pIdx = 0;              /* Parent key index for this FK */\n    int *aiCol = 0;               /* child table cols -> parent key cols */\n    TriggerStep *pStep = 0;        /* First (only) step of trigger program */\n    Expr *pWhere = 0;             /* WHERE clause of trigger step */\n    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */\n    Select *pSelect = 0;          /* If RESTRICT, \"SELECT RAISE(...)\" */\n    int i;                        /* Iterator variable */\n    Expr *pWhen = 0;              /* WHEN clause for the trigger */\n\n    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;\n    assert( aiCol || pFKey->nCol==1 );\n\n    for(i=0; i<pFKey->nCol; i++){\n      Token tOld = { \"old\", 3 };  /* Literal \"old\" token */\n      Token tNew = { \"new\", 3 };  /* Literal \"new\" token */\n      Token tFromCol;             /* Name of column in child table */\n      Token tToCol;               /* Name of column in parent table */\n      int iFromCol;               /* Idx of column in child table */\n      Expr *pEq;                  /* tFromCol = OLD.tToCol */\n\n      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;\n      assert( iFromCol>=0 );\n      assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );\n      assert( pIdx==0 || pIdx->aiColumn[i]>=0 );\n      sqlite3TokenInit(&tToCol,\n                   pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);\n      sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);\n\n      /* Create the expression \"OLD.zToCol = zFromCol\". It is important\n      ** that the \"OLD.zToCol\" term is on the LHS of the = operator, so\n      ** that the affinity and collation sequence associated with the\n      ** parent table are used for the comparison. */\n      pEq = sqlite3PExpr(pParse, TK_EQ,\n          sqlite3PExpr(pParse, TK_DOT, \n            sqlite3ExprAlloc(db, TK_ID, &tOld, 0),\n            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),\n          sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)\n      );\n      pWhere = sqlite3ExprAnd(pParse, pWhere, pEq);\n\n      /* For ON UPDATE, construct the next term of the WHEN clause.\n      ** The final WHEN clause will be like this:\n      **\n      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)\n      */\n      if( pChanges ){\n        pEq = sqlite3PExpr(pParse, TK_IS,\n            sqlite3PExpr(pParse, TK_DOT, \n              sqlite3ExprAlloc(db, TK_ID, &tOld, 0),\n              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),\n            sqlite3PExpr(pParse, TK_DOT, \n              sqlite3ExprAlloc(db, TK_ID, &tNew, 0),\n              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))\n            );\n        pWhen = sqlite3ExprAnd(pParse, pWhen, pEq);\n      }\n  \n      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){\n        Expr *pNew;\n        if( action==OE_Cascade ){\n          pNew = sqlite3PExpr(pParse, TK_DOT, \n            sqlite3ExprAlloc(db, TK_ID, &tNew, 0),\n            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));\n        }else if( action==OE_SetDflt ){\n          Column *pCol = pFKey->pFrom->aCol + iFromCol;\n          Expr *pDflt;\n          if( pCol->colFlags & COLFLAG_GENERATED ){\n            testcase( pCol->colFlags & COLFLAG_VIRTUAL );\n            testcase( pCol->colFlags & COLFLAG_STORED );\n            pDflt = 0;\n          }else{\n            pDflt = pCol->pDflt;\n          }\n          if( pDflt ){\n            pNew = sqlite3ExprDup(db, pDflt, 0);\n          }else{\n            pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);\n          }\n        }else{\n          pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);\n        }\n        pList = sqlite3ExprListAppend(pParse, pList, pNew);\n        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);\n      }\n    }\n    sqlite3DbFree(db, aiCol);\n\n    zFrom = pFKey->pFrom->zName;\n    nFrom = sqlite3Strlen30(zFrom);\n\n    if( action==OE_Restrict ){\n      Token tFrom;\n      Expr *pRaise; \n\n      tFrom.z = zFrom;\n      tFrom.n = nFrom;\n      pRaise = sqlite3Expr(db, TK_RAISE, \"FOREIGN KEY constraint failed\");\n      if( pRaise ){\n        pRaise->affExpr = OE_Abort;\n      }\n      pSelect = sqlite3SelectNew(pParse, \n          sqlite3ExprListAppend(pParse, 0, pRaise),\n          sqlite3SrcListAppend(pParse, 0, &tFrom, 0),\n          pWhere,\n          0, 0, 0, 0, 0\n      );\n      pWhere = 0;\n    }\n\n    /* Disable lookaside memory allocation */\n    DisableLookaside;\n\n    pTrigger = (Trigger *)sqlite3DbMallocZero(db, \n        sizeof(Trigger) +         /* struct Trigger */\n        sizeof(TriggerStep) +     /* Single step in trigger program */\n        nFrom + 1                 /* Space for pStep->zTarget */\n    );\n    if( pTrigger ){\n      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];\n      pStep->zTarget = (char *)&pStep[1];\n      memcpy((char *)pStep->zTarget, zFrom, nFrom);\n  \n      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);\n      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);\n      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);\n      if( pWhen ){\n        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);\n        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);\n      }\n    }\n\n    /* Re-enable the lookaside buffer, if it was disabled earlier. */\n    EnableLookaside;\n\n    sqlite3ExprDelete(db, pWhere);\n    sqlite3ExprDelete(db, pWhen);\n    sqlite3ExprListDelete(db, pList);\n    sqlite3SelectDelete(db, pSelect);\n    if( db->mallocFailed==1 ){\n      fkTriggerDelete(db, pTrigger);\n      return 0;\n    }\n    assert( pStep!=0 );\n    assert( pTrigger!=0 );\n\n    switch( action ){\n      case OE_Restrict:\n        pStep->op = TK_SELECT; \n        break;\n      case OE_Cascade: \n        if( !pChanges ){ \n          pStep->op = TK_DELETE; \n          break; \n        }\n      default:\n        pStep->op = TK_UPDATE;\n    }\n    pStep->pTrig = pTrigger;\n    pTrigger->pSchema = pTab->pSchema;\n    pTrigger->pTabSchema = pTab->pSchema;\n    pFKey->apTrigger[iAction] = pTrigger;\n    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);\n  }\n\n  return pTrigger;\n}\n\n/*\n** This function is called when deleting or updating a row to implement\n** any required CASCADE, SET NULL or SET DEFAULT actions.\n*/\nSQLITE_PRIVATE void sqlite3FkActions(\n  Parse *pParse,                  /* Parse context */\n  Table *pTab,                    /* Table being updated or deleted from */\n  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */\n  int regOld,                     /* Address of array containing old row */\n  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */\n  int bChngRowid                  /* True if rowid is UPDATEd */\n){\n  /* If foreign-key support is enabled, iterate through all FKs that \n  ** refer to table pTab. If there is an action associated with the FK \n  ** for this operation (either update or delete), invoke the associated \n  ** trigger sub-program.  */\n  if( pParse->db->flags&SQLITE_ForeignKeys ){\n    FKey *pFKey;                  /* Iterator variable */\n    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){\n      if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){\n        Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);\n        if( pAct ){\n          sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);\n        }\n      }\n    }\n  }\n}\n\n#endif /* ifndef SQLITE_OMIT_TRIGGER */\n\n/*\n** Free all memory associated with foreign key definitions attached to\n** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash\n** hash table.\n*/\nSQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){\n  FKey *pFKey;                    /* Iterator variable */\n  FKey *pNext;                    /* Copy of pFKey->pNextFrom */\n\n  assert( db==0 || IsVirtual(pTab)\n         || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );\n  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){\n\n    /* Remove the FK from the fkeyHash hash table. */\n    if( !db || db->pnBytesFreed==0 ){\n      if( pFKey->pPrevTo ){\n        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;\n      }else{\n        void *p = (void *)pFKey->pNextTo;\n        const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);\n        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);\n      }\n      if( pFKey->pNextTo ){\n        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;\n      }\n    }\n\n    /* EV: R-30323-21917 Each foreign key constraint in SQLite is\n    ** classified as either immediate or deferred.\n    */\n    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );\n\n    /* Delete any triggers created to implement actions for this FK. */\n#ifndef SQLITE_OMIT_TRIGGER\n    fkTriggerDelete(db, pFKey->apTrigger[0]);\n    fkTriggerDelete(db, pFKey->apTrigger[1]);\n#endif\n\n    pNext = pFKey->pNextFrom;\n    sqlite3DbFree(db, pFKey);\n  }\n}\n#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */\n\n/************** End of fkey.c ************************************************/\n/************** Begin file insert.c ******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains C code routines that are called by the parser\n** to handle INSERT statements in SQLite.\n*/\n/* #include \"sqliteInt.h\" */\n\n/*\n** Generate code that will \n**\n**   (1) acquire a lock for table pTab then\n**   (2) open pTab as cursor iCur.\n**\n** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index\n** for that table that is actually opened.\n*/\nSQLITE_PRIVATE void sqlite3OpenTable(\n  Parse *pParse,  /* Generate code into this VDBE */\n  int iCur,       /* The cursor number of the table */\n  int iDb,        /* The database index in sqlite3.aDb[] */\n  Table *pTab,    /* The table to be opened */\n  int opcode      /* OP_OpenRead or OP_OpenWrite */\n){\n  Vdbe *v;\n  assert( !IsVirtual(pTab) );\n  v = sqlite3GetVdbe(pParse);\n  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );\n  sqlite3TableLock(pParse, iDb, pTab->tnum, \n                   (opcode==OP_OpenWrite)?1:0, pTab->zName);\n  if( HasRowid(pTab) ){\n    sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol);\n    VdbeComment((v, \"%s\", pTab->zName));\n  }else{\n    Index *pPk = sqlite3PrimaryKeyIndex(pTab);\n    assert( pPk!=0 );\n    assert( pPk->tnum==pTab->tnum );\n    sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);\n    sqlite3VdbeSetP4KeyInfo(pParse, pPk);\n    VdbeComment((v, \"%s\", pTab->zName));\n  }\n}\n\n/*\n** Return a pointer to the column affinity string associated with index\n** pIdx. A column affinity string has one character for each column in \n** the table, according to the affinity of the column:\n**\n**  Character      Column affinity\n**  ------------------------------\n**  'A'            BLOB\n**  'B'            TEXT\n**  'C'            NUMERIC\n**  'D'            INTEGER\n**  'F'            REAL\n**\n** An extra 'D' is appended to the end of the string to cover the\n** rowid that appears as the last column in every index.\n**\n** Memory for the buffer containing the column index affinity string\n** is managed along with the rest of the Index structure. It will be\n** released when sqlite3DeleteIndex() is called.\n*/\nSQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){\n  if( !pIdx->zColAff ){\n    /* The first time a column affinity string for a particular index is\n    ** required, it is allocated and populated here. It is then stored as\n    ** a member of the Index structure for subsequent use.\n    **\n    ** The column affinity string will eventually be deleted by\n    ** sqliteDeleteIndex() when the Index structure itself is cleaned\n    ** up.\n    */\n    int n;\n    Table *pTab = pIdx->pTable;\n    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);\n    if( !pIdx->zColAff ){\n      sqlite3OomFault(db);\n      return 0;\n    }\n    for(n=0; n<pIdx->nColumn; n++){\n      i16 x = pIdx->aiColumn[n];\n      char aff;\n      if( x>=0 ){\n        aff = pTab->aCol[x].affinity;\n      }else if( x==XN_ROWID ){\n        aff = SQLITE_AFF_INTEGER;\n      }else{\n        assert( x==XN_EXPR );\n        assert( pIdx->aColExpr!=0 );\n        aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);\n      }\n      if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB;\n      if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC;\n      pIdx->zColAff[n] = aff;\n    }\n    pIdx->zColAff[n] = 0;\n  }\n \n  return pIdx->zColAff;\n}\n\n/*\n** Compute the affinity string for table pTab, if it has not already been\n** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.\n**\n** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and\n** if iReg>0 then code an OP_Affinity opcode that will set the affinities\n** for register iReg and following.  Or if affinities exists and iReg==0,\n** then just set the P4 operand of the previous opcode (which should  be\n** an OP_MakeRecord) to the affinity string.\n**\n** A column affinity string has one character per column:\n**\n**  Character      Column affinity\n**  ------------------------------\n**  'A'            BLOB\n**  'B'            TEXT\n**  'C'            NUMERIC\n**  'D'            INTEGER\n**  'E'            REAL\n*/\nSQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){\n  int i, j;\n  char *zColAff = pTab->zColAff;\n  if( zColAff==0 ){\n    sqlite3 *db = sqlite3VdbeDb(v);\n    zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);\n    if( !zColAff ){\n      sqlite3OomFault(db);\n      return;\n    }\n\n    for(i=j=0; i<pTab->nCol; i++){\n      assert( pTab->aCol[i].affinity!=0 );\n      if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){\n        zColAff[j++] = pTab->aCol[i].affinity;\n      }\n    }\n    do{\n      zColAff[j--] = 0;\n    }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB );\n    pTab->zColAff = zColAff;\n  }\n  assert( zColAff!=0 );\n  i = sqlite3Strlen30NN(zColAff);\n  if( i ){\n    if( iReg ){\n      sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);\n    }else{\n      sqlite3VdbeChangeP4(v, -1, zColAff, i);\n    }\n  }\n}\n\n/*\n** Return non-zero if the table pTab in database iDb or any of its indices\n** have been opened at any point in the VDBE program. This is used to see if \n** a statement of the form  \"INSERT INTO <iDb, pTab> SELECT ...\" can \n** run without using a temporary table for the results of the SELECT. \n*/\nstatic int readsTable(Parse *p, int iDb, Table *pTab){\n  Vdbe *v = sqlite3GetVdbe(p);\n  int i;\n  int iEnd = sqlite3VdbeCurrentAddr(v);\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;\n#endif\n\n  for(i=1; i<iEnd; i++){\n    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);\n    assert( pOp!=0 );\n    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){\n      Index *pIndex;\n      int tnum = pOp->p2;\n      if( tnum==pTab->tnum ){\n        return 1;\n      }\n      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){\n        if( tnum==pIndex->tnum ){\n          return 1;\n        }\n      }\n    }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){\n      assert( pOp->p4.pVtab!=0 );\n      assert( pOp->p4type==P4_VTAB );\n      return 1;\n    }\n#endif\n  }\n  return 0;\n}\n\n/* This walker callback will compute the union of colFlags flags for all\n** referenced columns in a CHECK constraint or generated column expression.\n*/\nstatic int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){\n  if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){\n    assert( pExpr->iColumn < pWalker->u.pTab->nCol );\n    pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags;\n  }\n  return WRC_Continue;\n}\n\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n/*\n** All regular columns for table pTab have been puts into registers\n** starting with iRegStore.  The registers that correspond to STORED\n** or VIRTUAL columns have not yet been initialized.  This routine goes\n** back and computes the values for those columns based on the previously\n** computed normal columns.\n*/\nSQLITE_PRIVATE void sqlite3ComputeGeneratedColumns(\n  Parse *pParse,    /* Parsing context */\n  int iRegStore,    /* Register holding the first column */\n  Table *pTab       /* The table */\n){\n  int i;\n  Walker w;\n  Column *pRedo;\n  int eProgress;\n  VdbeOp *pOp;\n\n  assert( pTab->tabFlags & TF_HasGenerated );\n  testcase( pTab->tabFlags & TF_HasVirtual );\n  testcase( pTab->tabFlags & TF_HasStored );\n\n  /* Before computing generated columns, first go through and make sure\n  ** that appropriate affinity has been applied to the regular columns\n  */\n  sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore);\n  if( (pTab->tabFlags & TF_HasStored)!=0\n   && (pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1))->opcode==OP_Affinity\n  ){\n    /* Change the OP_Affinity argument to '@' (NONE) for all stored\n    ** columns.  '@' is the no-op affinity and those columns have not\n    ** yet been computed. */\n    int ii, jj;\n    char *zP4 = pOp->p4.z;\n    assert( zP4!=0 );\n    assert( pOp->p4type==P4_DYNAMIC );\n    for(ii=jj=0; zP4[jj]; ii++){\n      if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){\n        continue;\n      }\n      if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){\n        zP4[jj] = SQLITE_AFF_NONE;\n      }\n      jj++;\n    }\n  }\n\n  /* Because there can be multiple generated columns that refer to one another,\n  ** this is a two-pass algorithm.  On the first pass, mark all generated\n  ** columns as \"not available\".\n  */\n  for(i=0; i<pTab->nCol; i++){\n    if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){\n      testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );\n      testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );\n      pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL;\n    }\n  }\n\n  w.u.pTab = pTab;\n  w.xExprCallback = exprColumnFlagUnion;\n  w.xSelectCallback = 0;\n  w.xSelectCallback2 = 0;\n\n  /* On the second pass, compute the value of each NOT-AVAILABLE column.\n  ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will\n  ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as\n  ** they are needed.\n  */\n  pParse->iSelfTab = -iRegStore;\n  do{\n    eProgress = 0;\n    pRedo = 0;\n    for(i=0; i<pTab->nCol; i++){\n      Column *pCol = pTab->aCol + i;\n      if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){\n        int x;\n        pCol->colFlags |= COLFLAG_BUSY;\n        w.eCode = 0;\n        sqlite3WalkExpr(&w, pCol->pDflt);\n        pCol->colFlags &= ~COLFLAG_BUSY;\n        if( w.eCode & COLFLAG_NOTAVAIL ){\n          pRedo = pCol;\n          continue;\n        }\n        eProgress = 1;\n        assert( pCol->colFlags & COLFLAG_GENERATED );\n        x = sqlite3TableColumnToStorage(pTab, i) + iRegStore;\n        sqlite3ExprCodeGeneratedColumn(pParse, pCol, x);\n        pCol->colFlags &= ~COLFLAG_NOTAVAIL;\n      }\n    }\n  }while( pRedo && eProgress );\n  if( pRedo ){\n    sqlite3ErrorMsg(pParse, \"generated column loop on \\\"%s\\\"\", pRedo->zName);\n  }\n  pParse->iSelfTab = 0;\n}\n#endif /* SQLITE_OMIT_GENERATED_COLUMNS */\n\n\n#ifndef SQLITE_OMIT_AUTOINCREMENT\n/*\n** Locate or create an AutoincInfo structure associated with table pTab\n** which is in database iDb.  Return the register number for the register\n** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT\n** table.  (Also return zero when doing a VACUUM since we do not want to\n** update the AUTOINCREMENT counters during a VACUUM.)\n**\n** There is at most one AutoincInfo structure per table even if the\n** same table is autoincremented multiple times due to inserts within\n** triggers.  A new AutoincInfo structure is created if this is the\n** first use of table pTab.  On 2nd and subsequent uses, the original\n** AutoincInfo structure is used.\n**\n** Four consecutive registers are allocated:\n**\n**   (1)  The name of the pTab table.\n**   (2)  The maximum ROWID of pTab.\n**   (3)  The rowid in sqlite_sequence of pTab\n**   (4)  The original value of the max ROWID in pTab, or NULL if none\n**\n** The 2nd register is the one that is returned.  That is all the\n** insert routine needs to know about.\n*/\nstatic int autoIncBegin(\n  Parse *pParse,      /* Parsing context */\n  int iDb,            /* Index of the database holding pTab */\n  Table *pTab         /* The table we are writing to */\n){\n  int memId = 0;      /* Register holding maximum rowid */\n  assert( pParse->db->aDb[iDb].pSchema!=0 );\n  if( (pTab->tabFlags & TF_Autoincrement)!=0\n   && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0\n  ){\n    Parse *pToplevel = sqlite3ParseToplevel(pParse);\n    AutoincInfo *pInfo;\n    Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;\n\n    /* Verify that the sqlite_sequence table exists and is an ordinary\n    ** rowid table with exactly two columns.\n    ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */\n    if( pSeqTab==0\n     || !HasRowid(pSeqTab)\n     || IsVirtual(pSeqTab)\n     || pSeqTab->nCol!=2\n    ){\n      pParse->nErr++;\n      pParse->rc = SQLITE_CORRUPT_SEQUENCE;\n      return 0;\n    }\n\n    pInfo = pToplevel->pAinc;\n    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }\n    if( pInfo==0 ){\n      pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));\n      if( pInfo==0 ) return 0;\n      pInfo->pNext = pToplevel->pAinc;\n      pToplevel->pAinc = pInfo;\n      pInfo->pTab = pTab;\n      pInfo->iDb = iDb;\n      pToplevel->nMem++;                  /* Register to hold name of table */\n      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */\n      pToplevel->nMem +=2;       /* Rowid in sqlite_sequence + orig max val */\n    }\n    memId = pInfo->regCtr;\n  }\n  return memId;\n}\n\n/*\n** This routine generates code that will initialize all of the\n** register used by the autoincrement tracker.  \n*/\nSQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){\n  AutoincInfo *p;            /* Information about an AUTOINCREMENT */\n  sqlite3 *db = pParse->db;  /* The database connection */\n  Db *pDb;                   /* Database only autoinc table */\n  int memId;                 /* Register holding max rowid */\n  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */\n\n  /* This routine is never called during trigger-generation.  It is\n  ** only called from the top-level */\n  assert( pParse->pTriggerTab==0 );\n  assert( sqlite3IsToplevel(pParse) );\n\n  assert( v );   /* We failed long ago if this is not so */\n  for(p = pParse->pAinc; p; p = p->pNext){\n    static const int iLn = VDBE_OFFSET_LINENO(2);\n    static const VdbeOpList autoInc[] = {\n      /* 0  */ {OP_Null,    0,  0, 0},\n      /* 1  */ {OP_Rewind,  0, 10, 0},\n      /* 2  */ {OP_Column,  0,  0, 0},\n      /* 3  */ {OP_Ne,      0,  9, 0},\n      /* 4  */ {OP_Rowid,   0,  0, 0},\n      /* 5  */ {OP_Column,  0,  1, 0},\n      /* 6  */ {OP_AddImm,  0,  0, 0},\n      /* 7  */ {OP_Copy,    0,  0, 0},\n      /* 8  */ {OP_Goto,    0, 11, 0},\n      /* 9  */ {OP_Next,    0,  2, 0},\n      /* 10 */ {OP_Integer, 0,  0, 0},\n      /* 11 */ {OP_Close,   0,  0, 0} \n    };\n    VdbeOp *aOp;\n    pDb = &db->aDb[p->iDb];\n    memId = p->regCtr;\n    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );\n    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);\n    sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);\n    aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);\n    if( aOp==0 ) break;\n    aOp[0].p2 = memId;\n    aOp[0].p3 = memId+2;\n    aOp[2].p3 = memId;\n    aOp[3].p1 = memId-1;\n    aOp[3].p3 = memId;\n    aOp[3].p5 = SQLITE_JUMPIFNULL;\n    aOp[4].p2 = memId+1;\n    aOp[5].p3 = memId;\n    aOp[6].p1 = memId;\n    aOp[7].p2 = memId+2;\n    aOp[7].p1 = memId;\n    aOp[10].p2 = memId;\n    if( pParse->nTab==0 ) pParse->nTab = 1;\n  }\n}\n\n/*\n** Update the maximum rowid for an autoincrement calculation.\n**\n** This routine should be called when the regRowid register holds a\n** new rowid that is about to be inserted.  If that new rowid is\n** larger than the maximum rowid in the memId memory cell, then the\n** memory cell is updated.\n*/\nstatic void autoIncStep(Parse *pParse, int memId, int regRowid){\n  if( memId>0 ){\n    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);\n  }\n}\n\n/*\n** This routine generates the code needed to write autoincrement\n** maximum rowid values back into the sqlite_sequence register.\n** Every statement that might do an INSERT into an autoincrement\n** table (either directly or through triggers) needs to call this\n** routine just before the \"exit\" code.\n*/\nstatic SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){\n  AutoincInfo *p;\n  Vdbe *v = pParse->pVdbe;\n  sqlite3 *db = pParse->db;\n\n  assert( v );\n  for(p = pParse->pAinc; p; p = p->pNext){\n    static const int iLn = VDBE_OFFSET_LINENO(2);\n    static const VdbeOpList autoIncEnd[] = {\n      /* 0 */ {OP_NotNull,     0, 2, 0},\n      /* 1 */ {OP_NewRowid,    0, 0, 0},\n      /* 2 */ {OP_MakeRecord,  0, 2, 0},\n      /* 3 */ {OP_Insert,      0, 0, 0},\n      /* 4 */ {OP_Close,       0, 0, 0}\n    };\n    VdbeOp *aOp;\n    Db *pDb = &db->aDb[p->iDb];\n    int iRec;\n    int memId = p->regCtr;\n\n    iRec = sqlite3GetTempReg(pParse);\n    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );\n    sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);\n    VdbeCoverage(v);\n    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);\n    aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);\n    if( aOp==0 ) break;\n    aOp[0].p1 = memId+1;\n    aOp[1].p2 = memId+1;\n    aOp[2].p1 = memId-1;\n    aOp[2].p3 = iRec;\n    aOp[3].p2 = iRec;\n    aOp[3].p3 = memId+1;\n    aOp[3].p5 = OPFLAG_APPEND;\n    sqlite3ReleaseTempReg(pParse, iRec);\n  }\n}\nSQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){\n  if( pParse->pAinc ) autoIncrementEnd(pParse);\n}\n#else\n/*\n** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines\n** above are all no-ops\n*/\n# define autoIncBegin(A,B,C) (0)\n# define autoIncStep(A,B,C)\n#endif /* SQLITE_OMIT_AUTOINCREMENT */\n\n\n/* Forward declaration */\nstatic int xferOptimization(\n  Parse *pParse,        /* Parser context */\n  Table *pDest,         /* The table we are inserting into */\n  Select *pSelect,      /* A SELECT statement to use as the data source */\n  int onError,          /* How to handle constraint errors */\n  int iDbDest           /* The database of pDest */\n);\n\n/*\n** This routine is called to handle SQL of the following forms:\n**\n**    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...\n**    insert into TABLE (IDLIST) select\n**    insert into TABLE (IDLIST) default values\n**\n** The IDLIST following the table name is always optional.  If omitted,\n** then a list of all (non-hidden) columns for the table is substituted.\n** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST\n** is omitted.\n**\n** For the pSelect parameter holds the values to be inserted for the\n** first two forms shown above.  A VALUES clause is really just short-hand\n** for a SELECT statement that omits the FROM clause and everything else\n** that follows.  If the pSelect parameter is NULL, that means that the\n** DEFAULT VALUES form of the INSERT statement is intended.\n**\n** The code generated follows one of four templates.  For a simple\n** insert with data coming from a single-row VALUES clause, the code executes\n** once straight down through.  Pseudo-code follows (we call this\n** the \"1st template\"):\n**\n**         open write cursor to <table> and its indices\n**         put VALUES clause expressions into registers\n**         write the resulting record into <table>\n**         cleanup\n**\n** The three remaining templates assume the statement is of the form\n**\n**   INSERT INTO <table> SELECT ...\n**\n** If the SELECT clause is of the restricted form \"SELECT * FROM <table2>\" -\n** in other words if the SELECT pulls all columns from a single table\n** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and\n** if <table2> and <table1> are distinct tables but have identical\n** schemas, including all the same indices, then a special optimization\n** is invoked that copies raw records from <table2> over to <table1>.\n** See the xferOptimization() function for the implementation of this\n** template.  This is the 2nd template.\n**\n**         open a write cursor to <table>\n**         open read cursor on <table2>\n**         transfer all records in <table2> over to <table>\n**         close cursors\n**         foreach index on <table>\n**           open a write cursor on the <table> index\n**           open a read cursor on the corresponding <table2> index\n**           transfer all records from the read to the write cursors\n**           close cursors\n**         end foreach\n**\n** The 3rd template is for when the second template does not apply\n** and the SELECT clause does not read from <table> at any time.\n** The generated code follows this template:\n**\n**         X <- A\n**         goto B\n**      A: setup for the SELECT\n**         loop over the rows in the SELECT\n**           load values into registers R..R+n\n**           yield X\n**         end loop\n**         cleanup after the SELECT\n**         end-coroutine X\n**      B: open write cursor to <table> and its indices\n**      C: yield X, at EOF goto D\n**         insert the select result into <table> from R..R+n\n**         goto C\n**      D: cleanup\n**\n** The 4th template is used if the insert statement takes its\n** values from a SELECT but the data is being inserted into a table\n** that is also read as part of the SELECT.  In the third form,\n** we have to use an intermediate table to store the results of\n** the select.  The template is like this:\n**\n**         X <- A\n**         goto B\n**      A: setup for the SELECT\n**         loop over the tables in the SELECT\n**           load value into register R..R+n\n**           yield X\n**         end loop\n**         cleanup after the SELECT\n**         end co-routine R\n**      B: open temp table\n**      L: yield X, at EOF goto M\n**         insert row from R..R+n into temp table\n**         goto L\n**      M: open write cursor to <table> and its indices\n**         rewind temp table\n**      C: loop over rows of intermediate table\n**           transfer values form intermediate table into <table>\n**         end loop\n**      D: cleanup\n*/\nSQLITE_PRIVATE void sqlite3Insert(\n  Parse *pParse,        /* Parser context */\n  SrcList *pTabList,    /* Name of table into which we are inserting */\n  Select *pSelect,      /* A SELECT statement to use as the data source */\n  IdList *pColumn,      /* Column names corresponding to IDLIST, or NULL. */\n  int onError,          /* How to handle constraint errors */\n  Upsert *pUpsert       /* ON CONFLICT clauses for upsert, or NULL */\n){\n  sqlite3 *db;          /* The main database structure */\n  Table *pTab;          /* The table to insert into.  aka TABLE */\n  int i, j;             /* Loop counters */\n  Vdbe *v;              /* Generate code into this virtual machine */\n  Index *pIdx;          /* For looping over indices of the table */\n  int nColumn;          /* Number of columns in the data */\n  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */\n  int iDataCur = 0;     /* VDBE cursor that is the main data repository */\n  int iIdxCur = 0;      /* First index cursor */\n  int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */\n  int endOfLoop;        /* Label for the end of the insertion loop */\n  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */\n  int addrInsTop = 0;   /* Jump to label \"D\" */\n  int addrCont = 0;     /* Top of insert loop. Label \"C\" in templates 3 and 4 */\n  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */\n  int iDb;              /* Index of database holding TABLE */\n  u8 useTempTable = 0;  /* Store SELECT results in intermediate table */\n  u8 appendFlag = 0;    /* True if the insert is likely to be an append */\n  u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */\n  u8 bIdListInOrder;    /* True if IDLIST is in table order */\n  ExprList *pList = 0;  /* List of VALUES() to be inserted  */\n  int iRegStore;        /* Register in which to store next column */\n\n  /* Register allocations */\n  int regFromSelect = 0;/* Base register for data coming from SELECT */\n  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */\n  int regRowCount = 0;  /* Memory cell used for the row counter */\n  int regIns;           /* Block of regs holding rowid+data being inserted */\n  int regRowid;         /* registers holding insert rowid */\n  int regData;          /* register holding first column to insert */\n  int *aRegIdx = 0;     /* One register allocated to each index */\n\n#ifndef SQLITE_OMIT_TRIGGER\n  int isView;                 /* True if attempting to insert into a view */\n  Trigger *pTrigger;          /* List of triggers on pTab, if required */\n  int tmask;                  /* Mask of trigger times */\n#endif\n\n  db = pParse->db;\n  if( pParse->nErr || db->mallocFailed ){\n    goto insert_cleanup;\n  }\n  dest.iSDParm = 0;  /* Suppress a harmless compiler warning */\n\n  /* If the Select object is really just a simple VALUES() list with a\n  ** single row (the common case) then keep that one row of values\n  ** and discard the other (unused) parts of the pSelect object\n  */\n  if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){\n    pList = pSelect->pEList;\n    pSelect->pEList = 0;\n    sqlite3SelectDelete(db, pSelect);\n    pSelect = 0;\n  }\n\n  /* Locate the table into which we will be inserting new information.\n  */\n  assert( pTabList->nSrc==1 );\n  pTab = sqlite3SrcListLookup(pParse, pTabList);\n  if( pTab==0 ){\n    goto insert_cleanup;\n  }\n  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n  assert( iDb<db->nDb );\n  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,\n                       db->aDb[iDb].zDbSName) ){\n    goto insert_cleanup;\n  }\n  withoutRowid = !HasRowid(pTab);\n\n  /* Figure out if we have any triggers and if the table being\n  ** inserted into is a view\n  */\n#ifndef SQLITE_OMIT_TRIGGER\n  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);\n  isView = pTab->pSelect!=0;\n#else\n# define pTrigger 0\n# define tmask 0\n# define isView 0\n#endif\n#ifdef SQLITE_OMIT_VIEW\n# undef isView\n# define isView 0\n#endif\n  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );\n\n  /* If pTab is really a view, make sure it has been initialized.\n  ** ViewGetColumnNames() is a no-op if pTab is not a view.\n  */\n  if( sqlite3ViewGetColumnNames(pParse, pTab) ){\n    goto insert_cleanup;\n  }\n\n  /* Cannot insert into a read-only table.\n  */\n  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){\n    goto insert_cleanup;\n  }\n\n  /* Allocate a VDBE\n  */\n  v = sqlite3GetVdbe(pParse);\n  if( v==0 ) goto insert_cleanup;\n  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);\n  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);\n\n#ifndef SQLITE_OMIT_XFER_OPT\n  /* If the statement is of the form\n  **\n  **       INSERT INTO <table1> SELECT * FROM <table2>;\n  **\n  ** Then special optimizations can be applied that make the transfer\n  ** very fast and which reduce fragmentation of indices.\n  **\n  ** This is the 2nd template.\n  */\n  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){\n    assert( !pTrigger );\n    assert( pList==0 );\n    goto insert_end;\n  }\n#endif /* SQLITE_OMIT_XFER_OPT */\n\n  /* If this is an AUTOINCREMENT table, look up the sequence number in the\n  ** sqlite_sequence table and store it in memory cell regAutoinc.\n  */\n  regAutoinc = autoIncBegin(pParse, iDb, pTab);\n\n  /* Allocate a block registers to hold the rowid and the values\n  ** for all columns of the new row.\n  */\n  regRowid = regIns = pParse->nMem+1;\n  pParse->nMem += pTab->nCol + 1;\n  if( IsVirtual(pTab) ){\n    regRowid++;\n    pParse->nMem++;\n  }\n  regData = regRowid+1;\n\n  /* If the INSERT statement included an IDLIST term, then make sure\n  ** all elements of the IDLIST really are columns of the table and \n  ** remember the column indices.\n  **\n  ** If the table has an INTEGER PRIMARY KEY column and that column\n  ** is named in the IDLIST, then record in the ipkColumn variable\n  ** the index into IDLIST of the primary key column.  ipkColumn is\n  ** the index of the primary key as it appears in IDLIST, not as\n  ** is appears in the original table.  (The index of the INTEGER\n  ** PRIMARY KEY in the original table is pTab->iPKey.)  After this\n  ** loop, if ipkColumn==(-1), that means that integer primary key\n  ** is unspecified, and hence the table is either WITHOUT ROWID or\n  ** it will automatically generated an integer primary key.\n  **\n  ** bIdListInOrder is true if the columns in IDLIST are in storage\n  ** order.  This enables an optimization that avoids shuffling the\n  ** columns into storage order.  False negatives are harmless,\n  ** but false positives will cause database corruption.\n  */\n  bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;\n  if( pColumn ){\n    for(i=0; i<pColumn->nId; i++){\n      pColumn->a[i].idx = -1;\n    }\n    for(i=0; i<pColumn->nId; i++){\n      for(j=0; j<pTab->nCol; j++){\n        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){\n          pColumn->a[i].idx = j;\n          if( i!=j ) bIdListInOrder = 0;\n          if( j==pTab->iPKey ){\n            ipkColumn = i;  assert( !withoutRowid );\n          }\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n          if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){\n            sqlite3ErrorMsg(pParse, \n               \"cannot INSERT into generated column \\\"%s\\\"\",\n               pTab->aCol[j].zName);\n            goto insert_cleanup;\n          }\n#endif\n          break;\n        }\n      }\n      if( j>=pTab->nCol ){\n        if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){\n          ipkColumn = i;\n          bIdListInOrder = 0;\n        }else{\n          sqlite3ErrorMsg(pParse, \"table %S has no column named %s\",\n              pTabList, 0, pColumn->a[i].zName);\n          pParse->checkSchema = 1;\n          goto insert_cleanup;\n        }\n      }\n    }\n  }\n\n  /* Figure out how many columns of data are supplied.  If the data\n  ** is coming from a SELECT statement, then generate a co-routine that\n  ** produces a single row of the SELECT on each invocation.  The\n  ** co-routine is the common header to the 3rd and 4th templates.\n  */\n  if( pSelect ){\n    /* Data is coming from a SELECT or from a multi-row VALUES clause.\n    ** Generate a co-routine to run the SELECT. */\n    int regYield;       /* Register holding co-routine entry-point */\n    int addrTop;        /* Top of the co-routine */\n    int rc;             /* Result code */\n\n    regYield = ++pParse->nMem;\n    addrTop = sqlite3VdbeCurrentAddr(v) + 1;\n    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);\n    sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);\n    dest.iSdst = bIdListInOrder ? regData : 0;\n    dest.nSdst = pTab->nCol;\n    rc = sqlite3Select(pParse, pSelect, &dest);\n    regFromSelect = dest.iSdst;\n    if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;\n    sqlite3VdbeEndCoroutine(v, regYield);\n    sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */\n    assert( pSelect->pEList );\n    nColumn = pSelect->pEList->nExpr;\n\n    /* Set useTempTable to TRUE if the result of the SELECT statement\n    ** should be written into a temporary table (template 4).  Set to\n    ** FALSE if each output row of the SELECT can be written directly into\n    ** the destination table (template 3).\n    **\n    ** A temp table must be used if the table being updated is also one\n    ** of the tables being read by the SELECT statement.  Also use a \n    ** temp table in the case of row triggers.\n    */\n    if( pTrigger || readsTable(pParse, iDb, pTab) ){\n      useTempTable = 1;\n    }\n\n    if( useTempTable ){\n      /* Invoke the coroutine to extract information from the SELECT\n      ** and add it to a transient table srcTab.  The code generated\n      ** here is from the 4th template:\n      **\n      **      B: open temp table\n      **      L: yield X, goto M at EOF\n      **         insert row from R..R+n into temp table\n      **         goto L\n      **      M: ...\n      */\n      int regRec;          /* Register to hold packed record */\n      int regTempRowid;    /* Register to hold temp table ROWID */\n      int addrL;           /* Label \"L\" */\n\n      srcTab = pParse->nTab++;\n      regRec = sqlite3GetTempReg(pParse);\n      regTempRowid = sqlite3GetTempReg(pParse);\n      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);\n      addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);\n      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);\n      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);\n      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);\n      sqlite3VdbeGoto(v, addrL);\n      sqlite3VdbeJumpHere(v, addrL);\n      sqlite3ReleaseTempReg(pParse, regRec);\n      sqlite3ReleaseTempReg(pParse, regTempRowid);\n    }\n  }else{\n    /* This is the case if the data for the INSERT is coming from a \n    ** single-row VALUES clause\n    */\n    NameContext sNC;\n    memset(&sNC, 0, sizeof(sNC));\n    sNC.pParse = pParse;\n    srcTab = -1;\n    assert( useTempTable==0 );\n    if( pList ){\n      nColumn = pList->nExpr;\n      if( sqlite3ResolveExprListNames(&sNC, pList) ){\n        goto insert_cleanup;\n      }\n    }else{\n      nColumn = 0;\n    }\n  }\n\n  /* If there is no IDLIST term but the table has an integer primary\n  ** key, the set the ipkColumn variable to the integer primary key \n  ** column index in the original table definition.\n  */\n  if( pColumn==0 && nColumn>0 ){\n    ipkColumn = pTab->iPKey;\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n    if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){\n      testcase( pTab->tabFlags & TF_HasVirtual );\n      testcase( pTab->tabFlags & TF_HasStored );\n      for(i=ipkColumn-1; i>=0; i--){\n        if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){\n          testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );\n          testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );\n          ipkColumn--;\n        }\n      }\n    }\n#endif\n  }\n\n  /* Make sure the number of columns in the source data matches the number\n  ** of columns to be inserted into the table.\n  */\n  for(i=0; i<pTab->nCol; i++){\n    if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;\n  }\n  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){\n    sqlite3ErrorMsg(pParse, \n       \"table %S has %d columns but %d values were supplied\",\n       pTabList, 0, pTab->nCol-nHidden, nColumn);\n    goto insert_cleanup;\n  }\n  if( pColumn!=0 && nColumn!=pColumn->nId ){\n    sqlite3ErrorMsg(pParse, \"%d values for %d columns\", nColumn, pColumn->nId);\n    goto insert_cleanup;\n  }\n    \n  /* Initialize the count of rows to be inserted\n  */\n  if( (db->flags & SQLITE_CountRows)!=0\n   && !pParse->nested\n   && !pParse->pTriggerTab\n  ){\n    regRowCount = ++pParse->nMem;\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);\n  }\n\n  /* If this is not a view, open the table and and all indices */\n  if( !isView ){\n    int nIdx;\n    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,\n                                      &iDataCur, &iIdxCur);\n    aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));\n    if( aRegIdx==0 ){\n      goto insert_cleanup;\n    }\n    for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){\n      assert( pIdx );\n      aRegIdx[i] = ++pParse->nMem;\n      pParse->nMem += pIdx->nColumn;\n    }\n    aRegIdx[i] = ++pParse->nMem;  /* Register to store the table record */\n  }\n#ifndef SQLITE_OMIT_UPSERT\n  if( pUpsert ){\n    if( IsVirtual(pTab) ){\n      sqlite3ErrorMsg(pParse, \"UPSERT not implemented for virtual table \\\"%s\\\"\",\n              pTab->zName);\n      goto insert_cleanup;\n    }\n    if( pTab->pSelect ){\n      sqlite3ErrorMsg(pParse, \"cannot UPSERT a view\");\n      goto insert_cleanup;\n    }\n    if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){\n      goto insert_cleanup;\n    }\n    pTabList->a[0].iCursor = iDataCur;\n    pUpsert->pUpsertSrc = pTabList;\n    pUpsert->regData = regData;\n    pUpsert->iDataCur = iDataCur;\n    pUpsert->iIdxCur = iIdxCur;\n    if( pUpsert->pUpsertTarget ){\n      sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert);\n    }\n  }\n#endif\n\n\n  /* This is the top of the main insertion loop */\n  if( useTempTable ){\n    /* This block codes the top of loop only.  The complete loop is the\n    ** following pseudocode (template 4):\n    **\n    **         rewind temp table, if empty goto D\n    **      C: loop over rows of intermediate table\n    **           transfer values form intermediate table into <table>\n    **         end loop\n    **      D: ...\n    */\n    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);\n    addrCont = sqlite3VdbeCurrentAddr(v);\n  }else if( pSelect ){\n    /* This block codes the top of loop only.  The complete loop is the\n    ** following pseudocode (template 3):\n    **\n    **      C: yield X, at EOF goto D\n    **         insert the select result into <table> from R..R+n\n    **         goto C\n    **      D: ...\n    */\n    sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);\n    addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);\n    VdbeCoverage(v);\n    if( ipkColumn>=0 ){\n      /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the\n      ** SELECT, go ahead and copy the value into the rowid slot now, so that\n      ** the value does not get overwritten by a NULL at tag-20191021-002. */\n      sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);\n    }\n  }\n\n  /* Compute data for ordinary columns of the new entry.  Values\n  ** are written in storage order into registers starting with regData.\n  ** Only ordinary columns are computed in this loop. The rowid\n  ** (if there is one) is computed later and generated columns are\n  ** computed after the rowid since they might depend on the value\n  ** of the rowid.\n  */\n  nHidden = 0;\n  iRegStore = regData;  assert( regData==regRowid+1 );\n  for(i=0; i<pTab->nCol; i++, iRegStore++){\n    int k;\n    u32 colFlags;\n    assert( i>=nHidden );\n    if( i==pTab->iPKey ){\n      /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled\n      ** using the rowid. So put a NULL in the IPK slot of the record to avoid\n      ** using excess space.  The file format definition requires this extra\n      ** NULL - we cannot optimize further by skipping the column completely */\n      sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);\n      continue;\n    }\n    if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){\n      nHidden++;\n      if( (colFlags & COLFLAG_VIRTUAL)!=0 ){\n        /* Virtual columns do not participate in OP_MakeRecord.  So back up\n        ** iRegStore by one slot to compensate for the iRegStore++ in the\n        ** outer for() loop */\n        iRegStore--;\n        continue;\n      }else if( (colFlags & COLFLAG_STORED)!=0 ){\n        /* Stored columns are computed later.  But if there are BEFORE\n        ** triggers, the slots used for stored columns will be OP_Copy-ed\n        ** to a second block of registers, so the register needs to be\n        ** initialized to NULL to avoid an uninitialized register read */\n        if( tmask & TRIGGER_BEFORE ){\n          sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);\n        }\n        continue;\n      }else if( pColumn==0 ){\n        /* Hidden columns that are not explicitly named in the INSERT\n        ** get there default value */\n        sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);\n        continue;\n      }\n    }\n    if( pColumn ){\n      for(j=0; j<pColumn->nId && pColumn->a[j].idx!=i; j++){}\n      if( j>=pColumn->nId ){\n        /* A column not named in the insert column list gets its\n        ** default value */\n        sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);\n        continue;\n      }\n      k = j;\n    }else if( nColumn==0 ){\n      /* This is INSERT INTO ... DEFAULT VALUES.  Load the default value. */\n      sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);\n      continue;\n    }else{\n      k = i - nHidden;\n    }\n\n    if( useTempTable ){\n      sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore); \n    }else if( pSelect ){\n      if( regFromSelect!=regData ){\n        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore);\n      }\n    }else{\n      sqlite3ExprCode(pParse, pList->a[k].pExpr, iRegStore);\n    }\n  }\n\n\n  /* Run the BEFORE and INSTEAD OF triggers, if there are any\n  */\n  endOfLoop = sqlite3VdbeMakeLabel(pParse);\n  if( tmask & TRIGGER_BEFORE ){\n    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);\n\n    /* build the NEW.* reference row.  Note that if there is an INTEGER\n    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be\n    ** translated into a unique ID for the row.  But on a BEFORE trigger,\n    ** we do not know what the unique ID will be (because the insert has\n    ** not happened yet) so we substitute a rowid of -1\n    */\n    if( ipkColumn<0 ){\n      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);\n    }else{\n      int addr1;\n      assert( !withoutRowid );\n      if( useTempTable ){\n        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);\n      }else{\n        assert( pSelect==0 );  /* Otherwise useTempTable is true */\n        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);\n      }\n      addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);\n      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);\n      sqlite3VdbeJumpHere(v, addr1);\n      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);\n    }\n\n    /* Cannot have triggers on a virtual table. If it were possible,\n    ** this block would have to account for hidden column.\n    */\n    assert( !IsVirtual(pTab) );\n\n    /* Copy the new data already generated. */\n    assert( pTab->nNVCol>0 );\n    sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);\n\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n    /* Compute the new value for generated columns after all other\n    ** columns have already been computed.  This must be done after\n    ** computing the ROWID in case one of the generated columns\n    ** refers to the ROWID. */\n    if( pTab->tabFlags & TF_HasGenerated ){\n      testcase( pTab->tabFlags & TF_HasVirtual );\n      testcase( pTab->tabFlags & TF_HasStored );\n      sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab);\n    }\n#endif\n\n    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,\n    ** do not attempt any conversions before assembling the record.\n    ** If this is a real table, attempt conversions as required by the\n    ** table column affinities.\n    */\n    if( !isView ){\n      sqlite3TableAffinity(v, pTab, regCols+1);\n    }\n\n    /* Fire BEFORE or INSTEAD OF triggers */\n    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, \n        pTab, regCols-pTab->nCol-1, onError, endOfLoop);\n\n    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);\n  }\n\n  if( !isView ){\n    if( IsVirtual(pTab) ){\n      /* The row that the VUpdate opcode will delete: none */\n      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);\n    }\n    if( ipkColumn>=0 ){\n      /* Compute the new rowid */\n      if( useTempTable ){\n        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);\n      }else if( pSelect ){\n        /* Rowid already initialized at tag-20191021-001 */\n      }else{\n        Expr *pIpk = pList->a[ipkColumn].pExpr;\n        if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){\n          sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);\n          appendFlag = 1;\n        }else{\n          sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);\n        }\n      }\n      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid\n      ** to generate a unique primary key value.\n      */\n      if( !appendFlag ){\n        int addr1;\n        if( !IsVirtual(pTab) ){\n          addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);\n          sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);\n          sqlite3VdbeJumpHere(v, addr1);\n        }else{\n          addr1 = sqlite3VdbeCurrentAddr(v);\n          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);\n        }\n        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);\n      }\n    }else if( IsVirtual(pTab) || withoutRowid ){\n      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);\n    }else{\n      sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);\n      appendFlag = 1;\n    }\n    autoIncStep(pParse, regAutoinc, regRowid);\n\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n    /* Compute the new value for generated columns after all other\n    ** columns have already been computed.  This must be done after\n    ** computing the ROWID in case one of the generated columns\n    ** is derived from the INTEGER PRIMARY KEY. */\n    if( pTab->tabFlags & TF_HasGenerated ){\n      sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab);\n    }\n#endif\n\n    /* Generate code to check constraints and generate index keys and\n    ** do the insertion.\n    */\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    if( IsVirtual(pTab) ){\n      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);\n      sqlite3VtabMakeWritable(pParse, pTab);\n      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);\n      sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);\n      sqlite3MayAbort(pParse);\n    }else\n#endif\n    {\n      int isReplace;    /* Set to true if constraints may cause a replace */\n      int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */\n      sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,\n          regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert\n      );\n      sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);\n\n      /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE\n      ** constraints or (b) there are no triggers and this table is not a\n      ** parent table in a foreign key constraint. It is safe to set the\n      ** flag in the second case as if any REPLACE constraint is hit, an\n      ** OP_Delete or OP_IdxDelete instruction will be executed on each \n      ** cursor that is disturbed. And these instructions both clear the\n      ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT\n      ** functionality.  */\n      bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v));\n      sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,\n          regIns, aRegIdx, 0, appendFlag, bUseSeek\n      );\n    }\n  }\n\n  /* Update the count of rows that are inserted\n  */\n  if( regRowCount ){\n    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);\n  }\n\n  if( pTrigger ){\n    /* Code AFTER triggers */\n    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, \n        pTab, regData-2-pTab->nCol, onError, endOfLoop);\n  }\n\n  /* The bottom of the main insertion loop, if the data source\n  ** is a SELECT statement.\n  */\n  sqlite3VdbeResolveLabel(v, endOfLoop);\n  if( useTempTable ){\n    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);\n    sqlite3VdbeJumpHere(v, addrInsTop);\n    sqlite3VdbeAddOp1(v, OP_Close, srcTab);\n  }else if( pSelect ){\n    sqlite3VdbeGoto(v, addrCont);\n#ifdef SQLITE_DEBUG\n    /* If we are jumping back to an OP_Yield that is preceded by an\n    ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the\n    ** OP_ReleaseReg will be included in the loop. */\n    if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){\n      assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );\n      sqlite3VdbeChangeP5(v, 1);\n    }\n#endif\n    sqlite3VdbeJumpHere(v, addrInsTop);\n  }\n\ninsert_end:\n  /* Update the sqlite_sequence table by storing the content of the\n  ** maximum rowid counter values recorded while inserting into\n  ** autoincrement tables.\n  */\n  if( pParse->nested==0 && pParse->pTriggerTab==0 ){\n    sqlite3AutoincrementEnd(pParse);\n  }\n\n  /*\n  ** Return the number of rows inserted. If this routine is \n  ** generating code because of a call to sqlite3NestedParse(), do not\n  ** invoke the callback function.\n  */\n  if( regRowCount ){\n    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);\n    sqlite3VdbeSetNumCols(v, 1);\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"rows inserted\", SQLITE_STATIC);\n  }\n\ninsert_cleanup:\n  sqlite3SrcListDelete(db, pTabList);\n  sqlite3ExprListDelete(db, pList);\n  sqlite3UpsertDelete(db, pUpsert);\n  sqlite3SelectDelete(db, pSelect);\n  sqlite3IdListDelete(db, pColumn);\n  sqlite3DbFree(db, aRegIdx);\n}\n\n/* Make sure \"isView\" and other macros defined above are undefined. Otherwise\n** they may interfere with compilation of other functions in this file\n** (or in another file, if this file becomes part of the amalgamation).  */\n#ifdef isView\n #undef isView\n#endif\n#ifdef pTrigger\n #undef pTrigger\n#endif\n#ifdef tmask\n #undef tmask\n#endif\n\n/*\n** Meanings of bits in of pWalker->eCode for \n** sqlite3ExprReferencesUpdatedColumn()\n*/\n#define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */\n#define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */\n\n/* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().\n*  Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this\n** expression node references any of the\n** columns that are being modifed by an UPDATE statement.\n*/\nstatic int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){\n  if( pExpr->op==TK_COLUMN ){\n    assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );\n    if( pExpr->iColumn>=0 ){\n      if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){\n        pWalker->eCode |= CKCNSTRNT_COLUMN;\n      }\n    }else{\n      pWalker->eCode |= CKCNSTRNT_ROWID;\n    }\n  }\n  return WRC_Continue;\n}\n\n/*\n** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The\n** only columns that are modified by the UPDATE are those for which\n** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.\n**\n** Return true if CHECK constraint pExpr uses any of the\n** changing columns (or the rowid if it is changing).  In other words,\n** return true if this CHECK constraint must be validated for\n** the new row in the UPDATE statement.\n**\n** 2018-09-15: pExpr might also be an expression for an index-on-expressions.\n** The operation of this routine is the same - return true if an only if\n** the expression uses one or more of columns identified by the second and\n** third arguments.\n*/\nSQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(\n  Expr *pExpr,    /* The expression to be checked */\n  int *aiChng,    /* aiChng[x]>=0 if column x changed by the UPDATE */\n  int chngRowid   /* True if UPDATE changes the rowid */\n){\n  Walker w;\n  memset(&w, 0, sizeof(w));\n  w.eCode = 0;\n  w.xExprCallback = checkConstraintExprNode;\n  w.u.aiCol = aiChng;\n  sqlite3WalkExpr(&w, pExpr);\n  if( !chngRowid ){\n    testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );\n    w.eCode &= ~CKCNSTRNT_ROWID;\n  }\n  testcase( w.eCode==0 );\n  testcase( w.eCode==CKCNSTRNT_COLUMN );\n  testcase( w.eCode==CKCNSTRNT_ROWID );\n  testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );\n  return w.eCode!=0;\n}\n\n/*\n** Generate code to do constraint checks prior to an INSERT or an UPDATE\n** on table pTab.\n**\n** The regNewData parameter is the first register in a range that contains\n** the data to be inserted or the data after the update.  There will be\n** pTab->nCol+1 registers in this range.  The first register (the one\n** that regNewData points to) will contain the new rowid, or NULL in the\n** case of a WITHOUT ROWID table.  The second register in the range will\n** contain the content of the first table column.  The third register will\n** contain the content of the second table column.  And so forth.\n**\n** The regOldData parameter is similar to regNewData except that it contains\n** the data prior to an UPDATE rather than afterwards.  regOldData is zero\n** for an INSERT.  This routine can distinguish between UPDATE and INSERT by\n** checking regOldData for zero.\n**\n** For an UPDATE, the pkChng boolean is true if the true primary key (the\n** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)\n** might be modified by the UPDATE.  If pkChng is false, then the key of\n** the iDataCur content table is guaranteed to be unchanged by the UPDATE.\n**\n** For an INSERT, the pkChng boolean indicates whether or not the rowid\n** was explicitly specified as part of the INSERT statement.  If pkChng\n** is zero, it means that the either rowid is computed automatically or\n** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,\n** pkChng will only be true if the INSERT statement provides an integer\n** value for either the rowid column or its INTEGER PRIMARY KEY alias.\n**\n** The code generated by this routine will store new index entries into\n** registers identified by aRegIdx[].  No index entry is created for\n** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is\n** the same as the order of indices on the linked list of indices\n** at pTab->pIndex.\n**\n** (2019-05-07) The generated code also creates a new record for the\n** main table, if pTab is a rowid table, and stores that record in the\n** register identified by aRegIdx[nIdx] - in other words in the first\n** entry of aRegIdx[] past the last index.  It is important that the\n** record be generated during constraint checks to avoid affinity changes\n** to the register content that occur after constraint checks but before\n** the new record is inserted.\n**\n** The caller must have already opened writeable cursors on the main\n** table and all applicable indices (that is to say, all indices for which\n** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when\n** inserting or updating a rowid table, or the cursor for the PRIMARY KEY\n** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor\n** for the first index in the pTab->pIndex list.  Cursors for other indices\n** are at iIdxCur+N for the N-th element of the pTab->pIndex list.\n**\n** This routine also generates code to check constraints.  NOT NULL,\n** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,\n** then the appropriate action is performed.  There are five possible\n** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.\n**\n**  Constraint type  Action       What Happens\n**  ---------------  ----------   ----------------------------------------\n**  any              ROLLBACK     The current transaction is rolled back and\n**                                sqlite3_step() returns immediately with a\n**                                return code of SQLITE_CONSTRAINT.\n**\n**  any              ABORT        Back out changes from the current command\n**                                only (do not do a complete rollback) then\n**                                cause sqlite3_step() to return immediately\n**                                with SQLITE_CONSTRAINT.\n**\n**  any              FAIL         Sqlite3_step() returns immediately with a\n**                                return code of SQLITE_CONSTRAINT.  The\n**                                transaction is not rolled back and any\n**                                changes to prior rows are retained.\n**\n**  any              IGNORE       The attempt in insert or update the current\n**                                row is skipped, without throwing an error.\n**                                Processing continues with the next row.\n**                                (There is an immediate jump to ignoreDest.)\n**\n**  NOT NULL         REPLACE      The NULL value is replace by the default\n**                                value for that column.  If the default value\n**                                is NULL, the action is the same as ABORT.\n**\n**  UNIQUE           REPLACE      The other row that conflicts with the row\n**                                being inserted is removed.\n**\n**  CHECK            REPLACE      Illegal.  The results in an exception.\n**\n** Which action to take is determined by the overrideError parameter.\n** Or if overrideError==OE_Default, then the pParse->onError parameter\n** is used.  Or if pParse->onError==OE_Default then the onError value\n** for the constraint is used.\n*/\nSQLITE_PRIVATE void sqlite3GenerateConstraintChecks(\n  Parse *pParse,       /* The parser context */\n  Table *pTab,         /* The table being inserted or updated */\n  int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */\n  int iDataCur,        /* Canonical data cursor (main table or PK index) */\n  int iIdxCur,         /* First index cursor */\n  int regNewData,      /* First register in a range holding values to insert */\n  int regOldData,      /* Previous content.  0 for INSERTs */\n  u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */\n  u8 overrideError,    /* Override onError to this if not OE_Default */\n  int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */\n  int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */\n  int *aiChng,         /* column i is unchanged if aiChng[i]<0 */\n  Upsert *pUpsert      /* ON CONFLICT clauses, if any.  NULL otherwise */\n){\n  Vdbe *v;             /* VDBE under constrution */\n  Index *pIdx;         /* Pointer to one of the indices */\n  Index *pPk = 0;      /* The PRIMARY KEY index */\n  sqlite3 *db;         /* Database connection */\n  int i;               /* loop counter */\n  int ix;              /* Index loop counter */\n  int nCol;            /* Number of columns */\n  int onError;         /* Conflict resolution strategy */\n  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */\n  int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */\n  Index *pUpIdx = 0;   /* Index to which to apply the upsert */\n  u8 isUpdate;         /* True if this is an UPDATE operation */\n  u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */\n  int upsertBypass = 0;  /* Address of Goto to bypass upsert subroutine */\n  int upsertJump = 0;    /* Address of Goto that jumps into upsert subroutine */\n  int ipkTop = 0;        /* Top of the IPK uniqueness check */\n  int ipkBottom = 0;     /* OP_Goto at the end of the IPK uniqueness check */\n  /* Variables associated with retesting uniqueness constraints after\n  ** replace triggers fire have run */\n  int regTrigCnt;       /* Register used to count replace trigger invocations */\n  int addrRecheck = 0;  /* Jump here to recheck all uniqueness constraints */\n  int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */\n  Trigger *pTrigger;    /* List of DELETE triggers on the table pTab */\n  int nReplaceTrig = 0; /* Number of replace triggers coded */\n\n  isUpdate = regOldData!=0;\n  db = pParse->db;\n  v = sqlite3GetVdbe(pParse);\n  assert( v!=0 );\n  assert( pTab->pSelect==0 );  /* This table is not a VIEW */\n  nCol = pTab->nCol;\n  \n  /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for\n  ** normal rowid tables.  nPkField is the number of key fields in the \n  ** pPk index or 1 for a rowid table.  In other words, nPkField is the\n  ** number of fields in the true primary key of the table. */\n  if( HasRowid(pTab) ){\n    pPk = 0;\n    nPkField = 1;\n  }else{\n    pPk = sqlite3PrimaryKeyIndex(pTab);\n    nPkField = pPk->nKeyCol;\n  }\n\n  /* Record that this module has started */\n  VdbeModuleComment((v, \"BEGIN: GenCnstCks(%d,%d,%d,%d,%d)\",\n                     iDataCur, iIdxCur, regNewData, regOldData, pkChng));\n\n  /* Test all NOT NULL constraints.\n  */\n  if( pTab->tabFlags & TF_HasNotNull ){\n    int b2ndPass = 0;         /* True if currently running 2nd pass */\n    int nSeenReplace = 0;     /* Number of ON CONFLICT REPLACE operations */\n    int nGenerated = 0;       /* Number of generated columns with NOT NULL */\n    while(1){  /* Make 2 passes over columns. Exit loop via \"break\" */\n      for(i=0; i<nCol; i++){\n        int iReg;                        /* Register holding column value */\n        Column *pCol = &pTab->aCol[i];   /* The column to check for NOT NULL */\n        int isGenerated;                 /* non-zero if column is generated */\n        onError = pCol->notNull;\n        if( onError==OE_None ) continue; /* No NOT NULL on this column */\n        if( i==pTab->iPKey ){\n          continue;        /* ROWID is never NULL */\n        }\n        isGenerated = pCol->colFlags & COLFLAG_GENERATED;\n        if( isGenerated && !b2ndPass ){\n          nGenerated++;\n          continue;        /* Generated columns processed on 2nd pass */\n        }\n        if( aiChng && aiChng[i]<0 && !isGenerated ){\n          /* Do not check NOT NULL on columns that do not change */\n          continue;\n        }\n        if( overrideError!=OE_Default ){\n          onError = overrideError;\n        }else if( onError==OE_Default ){\n          onError = OE_Abort;\n        }\n        if( onError==OE_Replace ){\n          if( b2ndPass        /* REPLACE becomes ABORT on the 2nd pass */\n           || pCol->pDflt==0  /* REPLACE is ABORT if no DEFAULT value */\n          ){\n            testcase( pCol->colFlags & COLFLAG_VIRTUAL );\n            testcase( pCol->colFlags & COLFLAG_STORED );\n            testcase( pCol->colFlags & COLFLAG_GENERATED );\n            onError = OE_Abort;\n          }else{\n            assert( !isGenerated );\n          }\n        }else if( b2ndPass && !isGenerated ){\n          continue;\n        }\n        assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail\n            || onError==OE_Ignore || onError==OE_Replace );\n        testcase( i!=sqlite3TableColumnToStorage(pTab, i) );\n        iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1;\n        switch( onError ){\n          case OE_Replace: {\n            int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg);\n            VdbeCoverage(v);\n            assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );\n            nSeenReplace++;\n            sqlite3ExprCodeCopy(pParse, pCol->pDflt, iReg);\n            sqlite3VdbeJumpHere(v, addr1);\n            break;\n          }\n          case OE_Abort:\n            sqlite3MayAbort(pParse);\n            /* Fall through */\n          case OE_Rollback:\n          case OE_Fail: {\n            char *zMsg = sqlite3MPrintf(db, \"%s.%s\", pTab->zName,\n                                        pCol->zName);\n            sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,\n                              onError, iReg);\n            sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);\n            sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);\n            VdbeCoverage(v);\n            break;\n          }\n          default: {\n            assert( onError==OE_Ignore );\n            sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest);\n            VdbeCoverage(v);\n            break;\n          }\n        } /* end switch(onError) */\n      } /* end loop i over columns */\n      if( nGenerated==0 && nSeenReplace==0 ){\n        /* If there are no generated columns with NOT NULL constraints\n        ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single\n        ** pass is sufficient */\n        break;\n      }\n      if( b2ndPass ) break;  /* Never need more than 2 passes */\n      b2ndPass = 1;\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n      if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){\n        /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the\n        ** first pass, recomputed values for all generated columns, as\n        ** those values might depend on columns affected by the REPLACE.\n        */\n        sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab);\n      }\n#endif\n    } /* end of 2-pass loop */\n  } /* end if( has-not-null-constraints ) */\n\n  /* Test all CHECK constraints\n  */\n#ifndef SQLITE_OMIT_CHECK\n  if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){\n    ExprList *pCheck = pTab->pCheck;\n    pParse->iSelfTab = -(regNewData+1);\n    onError = overrideError!=OE_Default ? overrideError : OE_Abort;\n    for(i=0; i<pCheck->nExpr; i++){\n      int allOk;\n      Expr *pCopy;\n      Expr *pExpr = pCheck->a[i].pExpr;\n      if( aiChng\n       && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)\n      ){\n        /* The check constraints do not reference any of the columns being\n        ** updated so there is no point it verifying the check constraint */\n        continue;\n      }\n      if( bAffinityDone==0 ){\n        sqlite3TableAffinity(v, pTab, regNewData+1);\n        bAffinityDone = 1;\n      }\n      allOk = sqlite3VdbeMakeLabel(pParse);\n      sqlite3VdbeVerifyAbortable(v, onError);\n      pCopy = sqlite3ExprDup(db, pExpr, 0);\n      if( !db->mallocFailed ){\n        sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL);\n      }\n      sqlite3ExprDelete(db, pCopy);\n      if( onError==OE_Ignore ){\n        sqlite3VdbeGoto(v, ignoreDest);\n      }else{\n        char *zName = pCheck->a[i].zEName;\n        if( zName==0 ) zName = pTab->zName;\n        if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */\n        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,\n                              onError, zName, P4_TRANSIENT,\n                              P5_ConstraintCheck);\n      }\n      sqlite3VdbeResolveLabel(v, allOk);\n    }\n    pParse->iSelfTab = 0;\n  }\n#endif /* !defined(SQLITE_OMIT_CHECK) */\n\n  /* UNIQUE and PRIMARY KEY constraints should be handled in the following\n  ** order:\n  **\n  **   (1)  OE_Update\n  **   (2)  OE_Abort, OE_Fail, OE_Rollback, OE_Ignore\n  **   (3)  OE_Replace\n  **\n  ** OE_Fail and OE_Ignore must happen before any changes are made.\n  ** OE_Update guarantees that only a single row will change, so it\n  ** must happen before OE_Replace.  Technically, OE_Abort and OE_Rollback\n  ** could happen in any order, but they are grouped up front for\n  ** convenience.\n  **\n  ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43\n  ** The order of constraints used to have OE_Update as (2) and OE_Abort\n  ** and so forth as (1). But apparently PostgreSQL checks the OE_Update\n  ** constraint before any others, so it had to be moved.\n  **\n  ** Constraint checking code is generated in this order:\n  **   (A)  The rowid constraint\n  **   (B)  Unique index constraints that do not have OE_Replace as their\n  **        default conflict resolution strategy\n  **   (C)  Unique index that do use OE_Replace by default.\n  **\n  ** The ordering of (2) and (3) is accomplished by making sure the linked\n  ** list of indexes attached to a table puts all OE_Replace indexes last\n  ** in the list.  See sqlite3CreateIndex() for where that happens.\n  */\n\n  if( pUpsert ){\n    if( pUpsert->pUpsertTarget==0 ){\n      /* An ON CONFLICT DO NOTHING clause, without a constraint-target.\n      ** Make all unique constraint resolution be OE_Ignore */\n      assert( pUpsert->pUpsertSet==0 );\n      overrideError = OE_Ignore;\n      pUpsert = 0;\n    }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){\n      /* If the constraint-target uniqueness check must be run first.\n      ** Jump to that uniqueness check now */\n      upsertJump = sqlite3VdbeAddOp0(v, OP_Goto);\n      VdbeComment((v, \"UPSERT constraint goes first\"));\n    }\n  }\n\n  /* Determine if it is possible that triggers (either explicitly coded\n  ** triggers or FK resolution actions) might run as a result of deletes\n  ** that happen when OE_Replace conflict resolution occurs. (Call these\n  ** \"replace triggers\".)  If any replace triggers run, we will need to\n  ** recheck all of the uniqueness constraints after they have all run.\n  ** But on the recheck, the resolution is OE_Abort instead of OE_Replace.\n  **\n  ** If replace triggers are a possibility, then\n  **\n  **   (1) Allocate register regTrigCnt and initialize it to zero.\n  **       That register will count the number of replace triggers that\n  **       fire.  Constraint recheck only occurs if the number is positive.\n  **   (2) Initialize pTrigger to the list of all DELETE triggers on pTab.\n  **   (3) Initialize addrRecheck and lblRecheckOk\n  **\n  ** The uniqueness rechecking code will create a series of tests to run\n  ** in a second pass.  The addrRecheck and lblRecheckOk variables are\n  ** used to link together these tests which are separated from each other\n  ** in the generate bytecode.\n  */\n  if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){\n    /* There are not DELETE triggers nor FK constraints.  No constraint\n    ** rechecks are needed. */\n    pTrigger = 0;\n    regTrigCnt = 0;\n  }else{\n    if( db->flags&SQLITE_RecTriggers ){\n      pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);\n      regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);\n    }else{\n      pTrigger = 0;\n      regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);\n    }\n    if( regTrigCnt ){\n      /* Replace triggers might exist.  Allocate the counter and\n      ** initialize it to zero. */\n      regTrigCnt = ++pParse->nMem;\n      sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt);\n      VdbeComment((v, \"trigger count\"));\n      lblRecheckOk = sqlite3VdbeMakeLabel(pParse);\n      addrRecheck = lblRecheckOk;\n    }\n  }\n\n  /* If rowid is changing, make sure the new rowid does not previously\n  ** exist in the table.\n  */\n  if( pkChng && pPk==0 ){\n    int addrRowidOk = sqlite3VdbeMakeLabel(pParse);\n\n    /* Figure out what action to take in case of a rowid collision */\n    onError = pTab->keyConf;\n    if( overrideError!=OE_Default ){\n      onError = overrideError;\n    }else if( onError==OE_Default ){\n      onError = OE_Abort;\n    }\n\n    /* figure out whether or not upsert applies in this case */\n    if( pUpsert && pUpsert->pUpsertIdx==0 ){\n      if( pUpsert->pUpsertSet==0 ){\n        onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */\n      }else{\n        onError = OE_Update;  /* DO UPDATE */\n      }\n    }\n\n    /* If the response to a rowid conflict is REPLACE but the response\n    ** to some other UNIQUE constraint is FAIL or IGNORE, then we need\n    ** to defer the running of the rowid conflict checking until after\n    ** the UNIQUE constraints have run.\n    */\n    if( onError==OE_Replace      /* IPK rule is REPLACE */\n     && onError!=overrideError   /* Rules for other contraints are different */\n     && pTab->pIndex             /* There exist other constraints */\n    ){\n      ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;\n      VdbeComment((v, \"defer IPK REPLACE until last\"));\n    }\n\n    if( isUpdate ){\n      /* pkChng!=0 does not mean that the rowid has changed, only that\n      ** it might have changed.  Skip the conflict logic below if the rowid\n      ** is unchanged. */\n      sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);\n      sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);\n      VdbeCoverage(v);\n    }\n\n    /* Check to see if the new rowid already exists in the table.  Skip\n    ** the following conflict logic if it does not. */\n    VdbeNoopComment((v, \"uniqueness check for ROWID\"));\n    sqlite3VdbeVerifyAbortable(v, onError);\n    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);\n    VdbeCoverage(v);\n\n    switch( onError ){\n      default: {\n        onError = OE_Abort;\n        /* Fall thru into the next case */\n      }\n      case OE_Rollback:\n      case OE_Abort:\n      case OE_Fail: {\n        testcase( onError==OE_Rollback );\n        testcase( onError==OE_Abort );\n        testcase( onError==OE_Fail );\n        sqlite3RowidConstraint(pParse, onError, pTab);\n        break;\n      }\n      case OE_Replace: {\n        /* If there are DELETE triggers on this table and the\n        ** recursive-triggers flag is set, call GenerateRowDelete() to\n        ** remove the conflicting row from the table. This will fire\n        ** the triggers and remove both the table and index b-tree entries.\n        **\n        ** Otherwise, if there are no triggers or the recursive-triggers\n        ** flag is not set, but the table has one or more indexes, call \n        ** GenerateRowIndexDelete(). This removes the index b-tree entries \n        ** only. The table b-tree entry will be replaced by the new entry \n        ** when it is inserted.  \n        **\n        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,\n        ** also invoke MultiWrite() to indicate that this VDBE may require\n        ** statement rollback (if the statement is aborted after the delete\n        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,\n        ** but being more selective here allows statements like:\n        **\n        **   REPLACE INTO t(rowid) VALUES($newrowid)\n        **\n        ** to run without a statement journal if there are no indexes on the\n        ** table.\n        */\n        if( regTrigCnt ){\n          sqlite3MultiWrite(pParse);\n          sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,\n                                   regNewData, 1, 0, OE_Replace, 1, -1);\n          sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */\n          nReplaceTrig++;\n        }else{\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n          assert( HasRowid(pTab) );\n          /* This OP_Delete opcode fires the pre-update-hook only. It does\n          ** not modify the b-tree. It is more efficient to let the coming\n          ** OP_Insert replace the existing entry than it is to delete the\n          ** existing entry and then insert a new one. */\n          sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);\n          sqlite3VdbeAppendP4(v, pTab, P4_TABLE);\n#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */\n          if( pTab->pIndex ){\n            sqlite3MultiWrite(pParse);\n            sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);\n          }\n        }\n        seenReplace = 1;\n        break;\n      }\n#ifndef SQLITE_OMIT_UPSERT\n      case OE_Update: {\n        sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);\n        /* Fall through */\n      }\n#endif\n      case OE_Ignore: {\n        testcase( onError==OE_Ignore );\n        sqlite3VdbeGoto(v, ignoreDest);\n        break;\n      }\n    }\n    sqlite3VdbeResolveLabel(v, addrRowidOk);\n    if( ipkTop ){\n      ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);\n      sqlite3VdbeJumpHere(v, ipkTop-1);\n    }\n  }\n\n  /* Test all UNIQUE constraints by creating entries for each UNIQUE\n  ** index and making sure that duplicate entries do not already exist.\n  ** Compute the revised record entries for indices as we go.\n  **\n  ** This loop also handles the case of the PRIMARY KEY index for a\n  ** WITHOUT ROWID table.\n  */\n  for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){\n    int regIdx;          /* Range of registers hold conent for pIdx */\n    int regR;            /* Range of registers holding conflicting PK */\n    int iThisCur;        /* Cursor for this UNIQUE index */\n    int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */\n    int addrConflictCk;  /* First opcode in the conflict check logic */\n\n    if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */\n    if( pUpIdx==pIdx ){\n      addrUniqueOk = upsertJump+1;\n      upsertBypass = sqlite3VdbeGoto(v, 0);\n      VdbeComment((v, \"Skip upsert subroutine\"));\n      sqlite3VdbeJumpHere(v, upsertJump);\n    }else{\n      addrUniqueOk = sqlite3VdbeMakeLabel(pParse);\n    }\n    if( bAffinityDone==0 && (pUpIdx==0 || pUpIdx==pIdx) ){\n      sqlite3TableAffinity(v, pTab, regNewData+1);\n      bAffinityDone = 1;\n    }\n    VdbeNoopComment((v, \"prep index %s\", pIdx->zName));\n    iThisCur = iIdxCur+ix;\n\n\n    /* Skip partial indices for which the WHERE clause is not true */\n    if( pIdx->pPartIdxWhere ){\n      sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);\n      pParse->iSelfTab = -(regNewData+1);\n      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,\n                            SQLITE_JUMPIFNULL);\n      pParse->iSelfTab = 0;\n    }\n\n    /* Create a record for this index entry as it should appear after\n    ** the insert or update.  Store that record in the aRegIdx[ix] register\n    */\n    regIdx = aRegIdx[ix]+1;\n    for(i=0; i<pIdx->nColumn; i++){\n      int iField = pIdx->aiColumn[i];\n      int x;\n      if( iField==XN_EXPR ){\n        pParse->iSelfTab = -(regNewData+1);\n        sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);\n        pParse->iSelfTab = 0;\n        VdbeComment((v, \"%s column %d\", pIdx->zName, i));\n      }else if( iField==XN_ROWID || iField==pTab->iPKey ){\n        x = regNewData;\n        sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i);\n        VdbeComment((v, \"rowid\"));\n      }else{\n        testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );\n        x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;\n        sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);\n        VdbeComment((v, \"%s\", pTab->aCol[iField].zName));\n      }\n    }\n    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);\n    VdbeComment((v, \"for %s\", pIdx->zName));\n#ifdef SQLITE_ENABLE_NULL_TRIM\n    if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){\n      sqlite3SetMakeRecordP5(v, pIdx->pTable);\n    }\n#endif\n    sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);\n\n    /* In an UPDATE operation, if this index is the PRIMARY KEY index \n    ** of a WITHOUT ROWID table and there has been no change the\n    ** primary key, then no collision is possible.  The collision detection\n    ** logic below can all be skipped. */\n    if( isUpdate && pPk==pIdx && pkChng==0 ){\n      sqlite3VdbeResolveLabel(v, addrUniqueOk);\n      continue;\n    }\n\n    /* Find out what action to take in case there is a uniqueness conflict */\n    onError = pIdx->onError;\n    if( onError==OE_None ){ \n      sqlite3VdbeResolveLabel(v, addrUniqueOk);\n      continue;  /* pIdx is not a UNIQUE index */\n    }\n    if( overrideError!=OE_Default ){\n      onError = overrideError;\n    }else if( onError==OE_Default ){\n      onError = OE_Abort;\n    }\n\n    /* Figure out if the upsert clause applies to this index */\n    if( pUpIdx==pIdx ){\n      if( pUpsert->pUpsertSet==0 ){\n        onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */\n      }else{\n        onError = OE_Update;  /* DO UPDATE */\n      }\n    }\n\n    /* Collision detection may be omitted if all of the following are true:\n    **   (1) The conflict resolution algorithm is REPLACE\n    **   (2) The table is a WITHOUT ROWID table\n    **   (3) There are no secondary indexes on the table\n    **   (4) No delete triggers need to be fired if there is a conflict\n    **   (5) No FK constraint counters need to be updated if a conflict occurs.\n    **\n    ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row\n    ** must be explicitly deleted in order to ensure any pre-update hook\n    ** is invoked.  */ \n#ifndef SQLITE_ENABLE_PREUPDATE_HOOK\n    if( (ix==0 && pIdx->pNext==0)                   /* Condition 3 */\n     && pPk==pIdx                                   /* Condition 2 */\n     && onError==OE_Replace                         /* Condition 1 */\n     && ( 0==(db->flags&SQLITE_RecTriggers) ||      /* Condition 4 */\n          0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))\n     && ( 0==(db->flags&SQLITE_ForeignKeys) ||      /* Condition 5 */\n         (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))\n    ){\n      sqlite3VdbeResolveLabel(v, addrUniqueOk);\n      continue;\n    }\n#endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */\n\n    /* Check to see if the new index entry will be unique */\n    sqlite3VdbeVerifyAbortable(v, onError);\n    addrConflictCk = \n      sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,\n                           regIdx, pIdx->nKeyCol); VdbeCoverage(v);\n\n    /* Generate code to handle collisions */\n    regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);\n    if( isUpdate || onError==OE_Replace ){\n      if( HasRowid(pTab) ){\n        sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);\n        /* Conflict only if the rowid of the existing index entry\n        ** is different from old-rowid */\n        if( isUpdate ){\n          sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);\n          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);\n          VdbeCoverage(v);\n        }\n      }else{\n        int x;\n        /* Extract the PRIMARY KEY from the end of the index entry and\n        ** store it in registers regR..regR+nPk-1 */\n        if( pIdx!=pPk ){\n          for(i=0; i<pPk->nKeyCol; i++){\n            assert( pPk->aiColumn[i]>=0 );\n            x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);\n            sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);\n            VdbeComment((v, \"%s.%s\", pTab->zName,\n                         pTab->aCol[pPk->aiColumn[i]].zName));\n          }\n        }\n        if( isUpdate ){\n          /* If currently processing the PRIMARY KEY of a WITHOUT ROWID \n          ** table, only conflict if the new PRIMARY KEY values are actually\n          ** different from the old.\n          **\n          ** For a UNIQUE index, only conflict if the PRIMARY KEY values\n          ** of the matched index row are different from the original PRIMARY\n          ** KEY values of this row before the update.  */\n          int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;\n          int op = OP_Ne;\n          int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);\n  \n          for(i=0; i<pPk->nKeyCol; i++){\n            char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);\n            x = pPk->aiColumn[i];\n            assert( x>=0 );\n            if( i==(pPk->nKeyCol-1) ){\n              addrJump = addrUniqueOk;\n              op = OP_Eq;\n            }\n            x = sqlite3TableColumnToStorage(pTab, x);\n            sqlite3VdbeAddOp4(v, op, \n                regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ\n            );\n            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);\n            VdbeCoverageIf(v, op==OP_Eq);\n            VdbeCoverageIf(v, op==OP_Ne);\n          }\n        }\n      }\n    }\n\n    /* Generate code that executes if the new index entry is not unique */\n    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail\n        || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );\n    switch( onError ){\n      case OE_Rollback:\n      case OE_Abort:\n      case OE_Fail: {\n        testcase( onError==OE_Rollback );\n        testcase( onError==OE_Abort );\n        testcase( onError==OE_Fail );\n        sqlite3UniqueConstraint(pParse, onError, pIdx);\n        break;\n      }\n#ifndef SQLITE_OMIT_UPSERT\n      case OE_Update: {\n        sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);\n        /* Fall through */\n      }\n#endif\n      case OE_Ignore: {\n        testcase( onError==OE_Ignore );\n        sqlite3VdbeGoto(v, ignoreDest);\n        break;\n      }\n      default: {\n        int nConflictCk;   /* Number of opcodes in conflict check logic */\n\n        assert( onError==OE_Replace );\n        nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;\n        assert( nConflictCk>0 );\n        testcase( nConflictCk>1 );\n        if( regTrigCnt ){\n          sqlite3MultiWrite(pParse);\n          nReplaceTrig++;\n        }\n        if( pTrigger && isUpdate ){\n          sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur);\n        }\n        sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,\n            regR, nPkField, 0, OE_Replace,\n            (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);\n        if( pTrigger && isUpdate ){\n          sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);\n        }\n        if( regTrigCnt ){\n          int addrBypass;  /* Jump destination to bypass recheck logic */\n\n          sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */\n          addrBypass = sqlite3VdbeAddOp0(v, OP_Goto);  /* Bypass recheck */\n          VdbeComment((v, \"bypass recheck\"));\n\n          /* Here we insert code that will be invoked after all constraint\n          ** checks have run, if and only if one or more replace triggers\n          ** fired. */\n          sqlite3VdbeResolveLabel(v, lblRecheckOk);\n          lblRecheckOk = sqlite3VdbeMakeLabel(pParse);\n          if( pIdx->pPartIdxWhere ){\n            /* Bypass the recheck if this partial index is not defined\n            ** for the current row */\n            sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);\n            VdbeCoverage(v);\n          }\n          /* Copy the constraint check code from above, except change\n          ** the constraint-ok jump destination to be the address of\n          ** the next retest block */\n          while( nConflictCk>0 ){\n            VdbeOp x;    /* Conflict check opcode to copy */\n            /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.\n            ** Hence, make a complete copy of the opcode, rather than using\n            ** a pointer to the opcode. */\n            x = *sqlite3VdbeGetOp(v, addrConflictCk);\n            if( x.opcode!=OP_IdxRowid ){\n              int p2;      /* New P2 value for copied conflict check opcode */\n              const char *zP4;\n              if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){\n                p2 = lblRecheckOk;\n              }else{\n                p2 = x.p2;\n              }\n              zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;\n              sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);\n              sqlite3VdbeChangeP5(v, x.p5);\n              VdbeCoverageIf(v, p2!=x.p2);\n            }\n            nConflictCk--;\n            addrConflictCk++;\n          }\n          /* If the retest fails, issue an abort */\n          sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);\n\n          sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */\n        }\n        seenReplace = 1;\n        break;\n      }\n    }\n    if( pUpIdx==pIdx ){\n      sqlite3VdbeGoto(v, upsertJump+1);\n      sqlite3VdbeJumpHere(v, upsertBypass);\n    }else{\n      sqlite3VdbeResolveLabel(v, addrUniqueOk);\n    }\n    if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);\n  }\n\n  /* If the IPK constraint is a REPLACE, run it last */\n  if( ipkTop ){\n    sqlite3VdbeGoto(v, ipkTop);\n    VdbeComment((v, \"Do IPK REPLACE\"));\n    sqlite3VdbeJumpHere(v, ipkBottom);\n  }\n\n  /* Recheck all uniqueness constraints after replace triggers have run */\n  testcase( regTrigCnt!=0 && nReplaceTrig==0 );\n  assert( regTrigCnt!=0 || nReplaceTrig==0 );\n  if( nReplaceTrig ){\n    sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v);\n    if( !pPk ){\n      if( isUpdate ){\n        sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData);\n        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);\n        VdbeCoverage(v);\n      }\n      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData);\n      VdbeCoverage(v);\n      sqlite3RowidConstraint(pParse, OE_Abort, pTab);\n    }else{\n      sqlite3VdbeGoto(v, addrRecheck);\n    }\n    sqlite3VdbeResolveLabel(v, lblRecheckOk);\n  }\n\n  /* Generate the table record */\n  if( HasRowid(pTab) ){\n    int regRec = aRegIdx[ix];\n    sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);\n    sqlite3SetMakeRecordP5(v, pTab);\n    if( !bAffinityDone ){\n      sqlite3TableAffinity(v, pTab, 0);\n    }\n  }\n\n  *pbMayReplace = seenReplace;\n  VdbeModuleComment((v, \"END: GenCnstCks(%d)\", seenReplace));\n}\n\n#ifdef SQLITE_ENABLE_NULL_TRIM\n/*\n** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)\n** to be the number of columns in table pTab that must not be NULL-trimmed.\n**\n** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.\n*/\nSQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){\n  u16 i;\n\n  /* Records with omitted columns are only allowed for schema format\n  ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */\n  if( pTab->pSchema->file_format<2 ) return;\n\n  for(i=pTab->nCol-1; i>0; i--){\n    if( pTab->aCol[i].pDflt!=0 ) break;\n    if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;\n  }\n  sqlite3VdbeChangeP5(v, i+1);\n}\n#endif\n\n/*\n** This routine generates code to finish the INSERT or UPDATE operation\n** that was started by a prior call to sqlite3GenerateConstraintChecks.\n** A consecutive range of registers starting at regNewData contains the\n** rowid and the content to be inserted.\n**\n** The arguments to this routine should be the same as the first six\n** arguments to sqlite3GenerateConstraintChecks.\n*/\nSQLITE_PRIVATE void sqlite3CompleteInsertion(\n  Parse *pParse,      /* The parser context */\n  Table *pTab,        /* the table into which we are inserting */\n  int iDataCur,       /* Cursor of the canonical data source */\n  int iIdxCur,        /* First index cursor */\n  int regNewData,     /* Range of content */\n  int *aRegIdx,       /* Register used by each index.  0 for unused indices */\n  int update_flags,   /* True for UPDATE, False for INSERT */\n  int appendBias,     /* True if this is likely to be an append */\n  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */\n){\n  Vdbe *v;            /* Prepared statements under construction */\n  Index *pIdx;        /* An index being inserted or updated */\n  u8 pik_flags;       /* flag values passed to the btree insert */\n  int i;              /* Loop counter */\n\n  assert( update_flags==0\n       || update_flags==OPFLAG_ISUPDATE\n       || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)\n  );\n\n  v = sqlite3GetVdbe(pParse);\n  assert( v!=0 );\n  assert( pTab->pSelect==0 );  /* This table is not a VIEW */\n  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){\n    /* All REPLACE indexes are at the end of the list */\n    assert( pIdx->onError!=OE_Replace\n         || pIdx->pNext==0\n         || pIdx->pNext->onError==OE_Replace );\n    if( aRegIdx[i]==0 ) continue;\n    if( pIdx->pPartIdxWhere ){\n      sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);\n      VdbeCoverage(v);\n    }\n    pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);\n    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){\n      assert( pParse->nested==0 );\n      pik_flags |= OPFLAG_NCHANGE;\n      pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n      if( update_flags==0 ){\n        int r = sqlite3GetTempReg(pParse);\n        sqlite3VdbeAddOp2(v, OP_Integer, 0, r);\n        sqlite3VdbeAddOp4(v, OP_Insert, \n            iIdxCur+i, aRegIdx[i], r, (char*)pTab, P4_TABLE\n        );\n        sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);\n        sqlite3ReleaseTempReg(pParse, r);\n      }\n#endif\n    }\n    sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],\n                         aRegIdx[i]+1,\n                         pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);\n    sqlite3VdbeChangeP5(v, pik_flags);\n  }\n  if( !HasRowid(pTab) ) return;\n  if( pParse->nested ){\n    pik_flags = 0;\n  }else{\n    pik_flags = OPFLAG_NCHANGE;\n    pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);\n  }\n  if( appendBias ){\n    pik_flags |= OPFLAG_APPEND;\n  }\n  if( useSeekResult ){\n    pik_flags |= OPFLAG_USESEEKRESULT;\n  }\n  sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);\n  if( !pParse->nested ){\n    sqlite3VdbeAppendP4(v, pTab, P4_TABLE);\n  }\n  sqlite3VdbeChangeP5(v, pik_flags);\n}\n\n/*\n** Allocate cursors for the pTab table and all its indices and generate\n** code to open and initialized those cursors.\n**\n** The cursor for the object that contains the complete data (normally\n** the table itself, but the PRIMARY KEY index in the case of a WITHOUT\n** ROWID table) is returned in *piDataCur.  The first index cursor is\n** returned in *piIdxCur.  The number of indices is returned.\n**\n** Use iBase as the first cursor (either the *piDataCur for rowid tables\n** or the first index for WITHOUT ROWID tables) if it is non-negative.\n** If iBase is negative, then allocate the next available cursor.\n**\n** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.\n** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range\n** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the\n** pTab->pIndex list.\n**\n** If pTab is a virtual table, then this routine is a no-op and the\n** *piDataCur and *piIdxCur values are left uninitialized.\n*/\nSQLITE_PRIVATE int sqlite3OpenTableAndIndices(\n  Parse *pParse,   /* Parsing context */\n  Table *pTab,     /* Table to be opened */\n  int op,          /* OP_OpenRead or OP_OpenWrite */\n  u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */\n  int iBase,       /* Use this for the table cursor, if there is one */\n  u8 *aToOpen,     /* If not NULL: boolean for each table and index */\n  int *piDataCur,  /* Write the database source cursor number here */\n  int *piIdxCur    /* Write the first index cursor number here */\n){\n  int i;\n  int iDb;\n  int iDataCur;\n  Index *pIdx;\n  Vdbe *v;\n\n  assert( op==OP_OpenRead || op==OP_OpenWrite );\n  assert( op==OP_OpenWrite || p5==0 );\n  if( IsVirtual(pTab) ){\n    /* This routine is a no-op for virtual tables. Leave the output\n    ** variables *piDataCur and *piIdxCur uninitialized so that valgrind\n    ** can detect if they are used by mistake in the caller. */\n    return 0;\n  }\n  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n  v = sqlite3GetVdbe(pParse);\n  assert( v!=0 );\n  if( iBase<0 ) iBase = pParse->nTab;\n  iDataCur = iBase++;\n  if( piDataCur ) *piDataCur = iDataCur;\n  if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){\n    sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);\n  }else{\n    sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);\n  }\n  if( piIdxCur ) *piIdxCur = iBase;\n  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){\n    int iIdxCur = iBase++;\n    assert( pIdx->pSchema==pTab->pSchema );\n    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){\n      if( piDataCur ) *piDataCur = iIdxCur;\n      p5 = 0;\n    }\n    if( aToOpen==0 || aToOpen[i+1] ){\n      sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);\n      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);\n      sqlite3VdbeChangeP5(v, p5);\n      VdbeComment((v, \"%s\", pIdx->zName));\n    }\n  }\n  if( iBase>pParse->nTab ) pParse->nTab = iBase;\n  return i;\n}\n\n\n#ifdef SQLITE_TEST\n/*\n** The following global variable is incremented whenever the\n** transfer optimization is used.  This is used for testing\n** purposes only - to make sure the transfer optimization really\n** is happening when it is supposed to.\n*/\nSQLITE_API int sqlite3_xferopt_count;\n#endif /* SQLITE_TEST */\n\n\n#ifndef SQLITE_OMIT_XFER_OPT\n/*\n** Check to see if index pSrc is compatible as a source of data\n** for index pDest in an insert transfer optimization.  The rules\n** for a compatible index:\n**\n**    *   The index is over the same set of columns\n**    *   The same DESC and ASC markings occurs on all columns\n**    *   The same onError processing (OE_Abort, OE_Ignore, etc)\n**    *   The same collating sequence on each column\n**    *   The index has the exact same WHERE clause\n*/\nstatic int xferCompatibleIndex(Index *pDest, Index *pSrc){\n  int i;\n  assert( pDest && pSrc );\n  assert( pDest->pTable!=pSrc->pTable );\n  if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){\n    return 0;   /* Different number of columns */\n  }\n  if( pDest->onError!=pSrc->onError ){\n    return 0;   /* Different conflict resolution strategies */\n  }\n  for(i=0; i<pSrc->nKeyCol; i++){\n    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){\n      return 0;   /* Different columns indexed */\n    }\n    if( pSrc->aiColumn[i]==XN_EXPR ){\n      assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );\n      if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,\n                             pDest->aColExpr->a[i].pExpr, -1)!=0 ){\n        return 0;   /* Different expressions in the index */\n      }\n    }\n    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){\n      return 0;   /* Different sort orders */\n    }\n    if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){\n      return 0;   /* Different collating sequences */\n    }\n  }\n  if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){\n    return 0;     /* Different WHERE clauses */\n  }\n\n  /* If no test above fails then the indices must be compatible */\n  return 1;\n}\n\n/*\n** Attempt the transfer optimization on INSERTs of the form\n**\n**     INSERT INTO tab1 SELECT * FROM tab2;\n**\n** The xfer optimization transfers raw records from tab2 over to tab1.  \n** Columns are not decoded and reassembled, which greatly improves\n** performance.  Raw index records are transferred in the same way.\n**\n** The xfer optimization is only attempted if tab1 and tab2 are compatible.\n** There are lots of rules for determining compatibility - see comments\n** embedded in the code for details.\n**\n** This routine returns TRUE if the optimization is guaranteed to be used.\n** Sometimes the xfer optimization will only work if the destination table\n** is empty - a factor that can only be determined at run-time.  In that\n** case, this routine generates code for the xfer optimization but also\n** does a test to see if the destination table is empty and jumps over the\n** xfer optimization code if the test fails.  In that case, this routine\n** returns FALSE so that the caller will know to go ahead and generate\n** an unoptimized transfer.  This routine also returns FALSE if there\n** is no chance that the xfer optimization can be applied.\n**\n** This optimization is particularly useful at making VACUUM run faster.\n*/\nstatic int xferOptimization(\n  Parse *pParse,        /* Parser context */\n  Table *pDest,         /* The table we are inserting into */\n  Select *pSelect,      /* A SELECT statement to use as the data source */\n  int onError,          /* How to handle constraint errors */\n  int iDbDest           /* The database of pDest */\n){\n  sqlite3 *db = pParse->db;\n  ExprList *pEList;                /* The result set of the SELECT */\n  Table *pSrc;                     /* The table in the FROM clause of SELECT */\n  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */\n  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */\n  int i;                           /* Loop counter */\n  int iDbSrc;                      /* The database of pSrc */\n  int iSrc, iDest;                 /* Cursors from source and destination */\n  int addr1, addr2;                /* Loop addresses */\n  int emptyDestTest = 0;           /* Address of test for empty pDest */\n  int emptySrcTest = 0;            /* Address of test for empty pSrc */\n  Vdbe *v;                         /* The VDBE we are building */\n  int regAutoinc;                  /* Memory register used by AUTOINC */\n  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */\n  int regData, regRowid;           /* Registers holding data and rowid */\n\n  if( pSelect==0 ){\n    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */\n  }\n  if( pParse->pWith || pSelect->pWith ){\n    /* Do not attempt to process this query if there are an WITH clauses\n    ** attached to it. Proceeding may generate a false \"no such table: xxx\"\n    ** error if pSelect reads from a CTE named \"xxx\".  */\n    return 0;\n  }\n  if( sqlite3TriggerList(pParse, pDest) ){\n    return 0;   /* tab1 must not have triggers */\n  }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( IsVirtual(pDest) ){\n    return 0;   /* tab1 must not be a virtual table */\n  }\n#endif\n  if( onError==OE_Default ){\n    if( pDest->iPKey>=0 ) onError = pDest->keyConf;\n    if( onError==OE_Default ) onError = OE_Abort;\n  }\n  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */\n  if( pSelect->pSrc->nSrc!=1 ){\n    return 0;   /* FROM clause must have exactly one term */\n  }\n  if( pSelect->pSrc->a[0].pSelect ){\n    return 0;   /* FROM clause cannot contain a subquery */\n  }\n  if( pSelect->pWhere ){\n    return 0;   /* SELECT may not have a WHERE clause */\n  }\n  if( pSelect->pOrderBy ){\n    return 0;   /* SELECT may not have an ORDER BY clause */\n  }\n  /* Do not need to test for a HAVING clause.  If HAVING is present but\n  ** there is no ORDER BY, we will get an error. */\n  if( pSelect->pGroupBy ){\n    return 0;   /* SELECT may not have a GROUP BY clause */\n  }\n  if( pSelect->pLimit ){\n    return 0;   /* SELECT may not have a LIMIT clause */\n  }\n  if( pSelect->pPrior ){\n    return 0;   /* SELECT may not be a compound query */\n  }\n  if( pSelect->selFlags & SF_Distinct ){\n    return 0;   /* SELECT may not be DISTINCT */\n  }\n  pEList = pSelect->pEList;\n  assert( pEList!=0 );\n  if( pEList->nExpr!=1 ){\n    return 0;   /* The result set must have exactly one column */\n  }\n  assert( pEList->a[0].pExpr );\n  if( pEList->a[0].pExpr->op!=TK_ASTERISK ){\n    return 0;   /* The result set must be the special operator \"*\" */\n  }\n\n  /* At this point we have established that the statement is of the\n  ** correct syntactic form to participate in this optimization.  Now\n  ** we have to check the semantics.\n  */\n  pItem = pSelect->pSrc->a;\n  pSrc = sqlite3LocateTableItem(pParse, 0, pItem);\n  if( pSrc==0 ){\n    return 0;   /* FROM clause does not contain a real table */\n  }\n  if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){\n    testcase( pSrc!=pDest ); /* Possible due to bad sqlite_master.rootpage */\n    return 0;   /* tab1 and tab2 may not be the same table */\n  }\n  if( HasRowid(pDest)!=HasRowid(pSrc) ){\n    return 0;   /* source and destination must both be WITHOUT ROWID or not */\n  }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( IsVirtual(pSrc) ){\n    return 0;   /* tab2 must not be a virtual table */\n  }\n#endif\n  if( pSrc->pSelect ){\n    return 0;   /* tab2 may not be a view */\n  }\n  if( pDest->nCol!=pSrc->nCol ){\n    return 0;   /* Number of columns must be the same in tab1 and tab2 */\n  }\n  if( pDest->iPKey!=pSrc->iPKey ){\n    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */\n  }\n  for(i=0; i<pDest->nCol; i++){\n    Column *pDestCol = &pDest->aCol[i];\n    Column *pSrcCol = &pSrc->aCol[i];\n#ifdef SQLITE_ENABLE_HIDDEN_COLUMNS\n    if( (db->mDbFlags & DBFLAG_Vacuum)==0 \n     && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN \n    ){\n      return 0;    /* Neither table may have __hidden__ columns */\n    }\n#endif\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n    /* Even if tables t1 and t2 have identical schemas, if they contain\n    ** generated columns, then this statement is semantically incorrect:\n    **\n    **     INSERT INTO t2 SELECT * FROM t1;\n    **\n    ** The reason is that generated column values are returned by the\n    ** the SELECT statement on the right but the INSERT statement on the\n    ** left wants them to be omitted.\n    **\n    ** Nevertheless, this is a useful notational shorthand to tell SQLite\n    ** to do a bulk transfer all of the content from t1 over to t2.\n    ** \n    ** We could, in theory, disable this (except for internal use by the\n    ** VACUUM command where it is actually needed).  But why do that?  It\n    ** seems harmless enough, and provides a useful service.\n    */\n    if( (pDestCol->colFlags & COLFLAG_GENERATED) !=\n        (pSrcCol->colFlags & COLFLAG_GENERATED) ){\n      return 0;    /* Both columns have the same generated-column type */\n    }\n    /* But the transfer is only allowed if both the source and destination\n    ** tables have the exact same expressions for generated columns.\n    ** This requirement could be relaxed for VIRTUAL columns, I suppose.\n    */\n    if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){\n      if( sqlite3ExprCompare(0, pSrcCol->pDflt, pDestCol->pDflt, -1)!=0 ){\n        testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );\n        testcase( pDestCol->colFlags & COLFLAG_STORED );\n        return 0;  /* Different generator expressions */\n      }\n    }\n#endif\n    if( pDestCol->affinity!=pSrcCol->affinity ){\n      return 0;    /* Affinity must be the same on all columns */\n    }\n    if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){\n      return 0;    /* Collating sequence must be the same on all columns */\n    }\n    if( pDestCol->notNull && !pSrcCol->notNull ){\n      return 0;    /* tab2 must be NOT NULL if tab1 is */\n    }\n    /* Default values for second and subsequent columns need to match. */\n    if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){\n      assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );\n      assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );\n      if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) \n       || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,\n                                       pSrcCol->pDflt->u.zToken)!=0)\n      ){\n        return 0;    /* Default values must be the same for all columns */\n      }\n    }\n  }\n  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){\n    if( IsUniqueIndex(pDestIdx) ){\n      destHasUniqueIdx = 1;\n    }\n    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){\n      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;\n    }\n    if( pSrcIdx==0 ){\n      return 0;    /* pDestIdx has no corresponding index in pSrc */\n    }\n    if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema\n         && sqlite3FaultSim(411)==SQLITE_OK ){\n      /* The sqlite3FaultSim() call allows this corruption test to be\n      ** bypassed during testing, in order to exercise other corruption tests\n      ** further downstream. */\n      return 0;   /* Corrupt schema - two indexes on the same btree */\n    }\n  }\n#ifndef SQLITE_OMIT_CHECK\n  if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){\n    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */\n  }\n#endif\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n  /* Disallow the transfer optimization if the destination table constains\n  ** any foreign key constraints.  This is more restrictive than necessary.\n  ** But the main beneficiary of the transfer optimization is the VACUUM \n  ** command, and the VACUUM command disables foreign key constraints.  So\n  ** the extra complication to make this rule less restrictive is probably\n  ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]\n  */\n  if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){\n    return 0;\n  }\n#endif\n  if( (db->flags & SQLITE_CountRows)!=0 ){\n    return 0;  /* xfer opt does not play well with PRAGMA count_changes */\n  }\n\n  /* If we get this far, it means that the xfer optimization is at\n  ** least a possibility, though it might only work if the destination\n  ** table (tab1) is initially empty.\n  */\n#ifdef SQLITE_TEST\n  sqlite3_xferopt_count++;\n#endif\n  iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);\n  v = sqlite3GetVdbe(pParse);\n  sqlite3CodeVerifySchema(pParse, iDbSrc);\n  iSrc = pParse->nTab++;\n  iDest = pParse->nTab++;\n  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);\n  regData = sqlite3GetTempReg(pParse);\n  regRowid = sqlite3GetTempReg(pParse);\n  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);\n  assert( HasRowid(pDest) || destHasUniqueIdx );\n  if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (\n      (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */\n   || destHasUniqueIdx                              /* (2) */\n   || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */\n  )){\n    /* In some circumstances, we are able to run the xfer optimization\n    ** only if the destination table is initially empty. Unless the\n    ** DBFLAG_Vacuum flag is set, this block generates code to make\n    ** that determination. If DBFLAG_Vacuum is set, then the destination\n    ** table is always empty.\n    **\n    ** Conditions under which the destination must be empty:\n    **\n    ** (1) There is no INTEGER PRIMARY KEY but there are indices.\n    **     (If the destination is not initially empty, the rowid fields\n    **     of index entries might need to change.)\n    **\n    ** (2) The destination has a unique index.  (The xfer optimization \n    **     is unable to test uniqueness.)\n    **\n    ** (3) onError is something other than OE_Abort and OE_Rollback.\n    */\n    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);\n    emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);\n    sqlite3VdbeJumpHere(v, addr1);\n  }\n  if( HasRowid(pSrc) ){\n    u8 insFlags;\n    sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);\n    emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);\n    if( pDest->iPKey>=0 ){\n      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);\n      sqlite3VdbeVerifyAbortable(v, onError);\n      addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);\n      VdbeCoverage(v);\n      sqlite3RowidConstraint(pParse, onError, pDest);\n      sqlite3VdbeJumpHere(v, addr2);\n      autoIncStep(pParse, regAutoinc, regRowid);\n    }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){\n      addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);\n    }else{\n      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);\n      assert( (pDest->tabFlags & TF_Autoincrement)==0 );\n    }\n    if( db->mDbFlags & DBFLAG_Vacuum ){\n      sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);\n      insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT;\n    }else{\n      insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;\n    }\n    sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);\n    sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,\n                      (char*)pDest, P4_TABLE);\n    sqlite3VdbeChangeP5(v, insFlags);\n    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);\n    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);\n    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);\n  }else{\n    sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);\n    sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);\n  }\n  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){\n    u8 idxInsFlags = 0;\n    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){\n      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;\n    }\n    assert( pSrcIdx );\n    sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);\n    sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);\n    VdbeComment((v, \"%s\", pSrcIdx->zName));\n    sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);\n    sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);\n    sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);\n    VdbeComment((v, \"%s\", pDestIdx->zName));\n    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);\n    if( db->mDbFlags & DBFLAG_Vacuum ){\n      /* This INSERT command is part of a VACUUM operation, which guarantees\n      ** that the destination table is empty. If all indexed columns use\n      ** collation sequence BINARY, then it can also be assumed that the\n      ** index will be populated by inserting keys in strictly sorted \n      ** order. In this case, instead of seeking within the b-tree as part\n      ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the\n      ** OP_IdxInsert to seek to the point within the b-tree where each key \n      ** should be inserted. This is faster.\n      **\n      ** If any of the indexed columns use a collation sequence other than\n      ** BINARY, this optimization is disabled. This is because the user \n      ** might change the definition of a collation sequence and then run\n      ** a VACUUM command. In that case keys may not be written in strictly\n      ** sorted order.  */\n      for(i=0; i<pSrcIdx->nColumn; i++){\n        const char *zColl = pSrcIdx->azColl[i];\n        if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;\n      }\n      if( i==pSrcIdx->nColumn ){\n        idxInsFlags = OPFLAG_USESEEKRESULT;\n        sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);\n      }\n    }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){\n      idxInsFlags |= OPFLAG_NCHANGE;\n    }\n    sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);\n    sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);\n    sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);\n    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);\n    sqlite3VdbeJumpHere(v, addr1);\n    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);\n    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);\n  }\n  if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);\n  sqlite3ReleaseTempReg(pParse, regRowid);\n  sqlite3ReleaseTempReg(pParse, regData);\n  if( emptyDestTest ){\n    sqlite3AutoincrementEnd(pParse);\n    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);\n    sqlite3VdbeJumpHere(v, emptyDestTest);\n    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);\n    return 0;\n  }else{\n    return 1;\n  }\n}\n#endif /* SQLITE_OMIT_XFER_OPT */\n\n/************** End of insert.c **********************************************/\n/************** Begin file legacy.c ******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** Main file for the SQLite library.  The routines in this file\n** implement the programmer interface to the library.  Routines in\n** other files are for internal use by SQLite and should not be\n** accessed by users of the library.\n*/\n\n/* #include \"sqliteInt.h\" */\n\n/*\n** Execute SQL code.  Return one of the SQLITE_ success/failure\n** codes.  Also write an error message into memory obtained from\n** malloc() and make *pzErrMsg point to that message.\n**\n** If the SQL is a query, then for each row in the query result\n** the xCallback() function is called.  pArg becomes the first\n** argument to xCallback().  If xCallback=NULL then no callback\n** is invoked, even for queries.\n*/\nSQLITE_API int sqlite3_exec(\n  sqlite3 *db,                /* The database on which the SQL executes */\n  const char *zSql,           /* The SQL to be executed */\n  sqlite3_callback xCallback, /* Invoke this callback routine */\n  void *pArg,                 /* First argument to xCallback() */\n  char **pzErrMsg             /* Write error messages here */\n){\n  int rc = SQLITE_OK;         /* Return code */\n  const char *zLeftover;      /* Tail of unprocessed SQL */\n  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */\n  char **azCols = 0;          /* Names of result columns */\n  int callbackIsInit;         /* True if callback data is initialized */\n\n  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;\n  if( zSql==0 ) zSql = \"\";\n\n  sqlite3_mutex_enter(db->mutex);\n  sqlite3Error(db, SQLITE_OK);\n  while( rc==SQLITE_OK && zSql[0] ){\n    int nCol = 0;\n    char **azVals = 0;\n\n    pStmt = 0;\n    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);\n    assert( rc==SQLITE_OK || pStmt==0 );\n    if( rc!=SQLITE_OK ){\n      continue;\n    }\n    if( !pStmt ){\n      /* this happens for a comment or white-space */\n      zSql = zLeftover;\n      continue;\n    }\n    callbackIsInit = 0;\n\n    while( 1 ){\n      int i;\n      rc = sqlite3_step(pStmt);\n\n      /* Invoke the callback function if required */\n      if( xCallback && (SQLITE_ROW==rc || \n          (SQLITE_DONE==rc && !callbackIsInit\n                           && db->flags&SQLITE_NullCallback)) ){\n        if( !callbackIsInit ){\n          nCol = sqlite3_column_count(pStmt);\n          azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));\n          if( azCols==0 ){\n            goto exec_out;\n          }\n          for(i=0; i<nCol; i++){\n            azCols[i] = (char *)sqlite3_column_name(pStmt, i);\n            /* sqlite3VdbeSetColName() installs column names as UTF8\n            ** strings so there is no way for sqlite3_column_name() to fail. */\n            assert( azCols[i]!=0 );\n          }\n          callbackIsInit = 1;\n        }\n        if( rc==SQLITE_ROW ){\n          azVals = &azCols[nCol];\n          for(i=0; i<nCol; i++){\n            azVals[i] = (char *)sqlite3_column_text(pStmt, i);\n            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){\n              sqlite3OomFault(db);\n              goto exec_out;\n            }\n          }\n          azVals[i] = 0;\n        }\n        if( xCallback(pArg, nCol, azVals, azCols) ){\n          /* EVIDENCE-OF: R-38229-40159 If the callback function to\n          ** sqlite3_exec() returns non-zero, then sqlite3_exec() will\n          ** return SQLITE_ABORT. */\n          rc = SQLITE_ABORT;\n          sqlite3VdbeFinalize((Vdbe *)pStmt);\n          pStmt = 0;\n          sqlite3Error(db, SQLITE_ABORT);\n          goto exec_out;\n        }\n      }\n\n      if( rc!=SQLITE_ROW ){\n        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);\n        pStmt = 0;\n        zSql = zLeftover;\n        while( sqlite3Isspace(zSql[0]) ) zSql++;\n        break;\n      }\n    }\n\n    sqlite3DbFree(db, azCols);\n    azCols = 0;\n  }\n\nexec_out:\n  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);\n  sqlite3DbFree(db, azCols);\n\n  rc = sqlite3ApiExit(db, rc);\n  if( rc!=SQLITE_OK && pzErrMsg ){\n    *pzErrMsg = sqlite3DbStrDup(0, sqlite3_errmsg(db));\n    if( *pzErrMsg==0 ){\n      rc = SQLITE_NOMEM_BKPT;\n      sqlite3Error(db, SQLITE_NOMEM);\n    }\n  }else if( pzErrMsg ){\n    *pzErrMsg = 0;\n  }\n\n  assert( (rc&db->errMask)==rc );\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/************** End of legacy.c **********************************************/\n/************** Begin file loadext.c *****************************************/\n/*\n** 2006 June 7\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code used to dynamically load extensions into\n** the SQLite library.\n*/\n\n#ifndef SQLITE_CORE\n  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */\n#endif\n/************** Include sqlite3ext.h in the middle of loadext.c **************/\n/************** Begin file sqlite3ext.h **************************************/\n/*\n** 2006 June 7\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This header file defines the SQLite interface for use by\n** shared libraries that want to be imported as extensions into\n** an SQLite instance.  Shared libraries that intend to be loaded\n** as extensions by SQLite should #include this file instead of \n** sqlite3.h.\n*/\n#ifndef SQLITE3EXT_H\n#define SQLITE3EXT_H\n/* #include \"sqlite3.h\" */\n\n/*\n** The following structure holds pointers to all of the SQLite API\n** routines.\n**\n** WARNING:  In order to maintain backwards compatibility, add new\n** interfaces to the end of this structure only.  If you insert new\n** interfaces in the middle of this structure, then older different\n** versions of SQLite will not be able to load each other's shared\n** libraries!\n*/\nstruct sqlite3_api_routines {\n  void * (*aggregate_context)(sqlite3_context*,int nBytes);\n  int  (*aggregate_count)(sqlite3_context*);\n  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));\n  int  (*bind_double)(sqlite3_stmt*,int,double);\n  int  (*bind_int)(sqlite3_stmt*,int,int);\n  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);\n  int  (*bind_null)(sqlite3_stmt*,int);\n  int  (*bind_parameter_count)(sqlite3_stmt*);\n  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);\n  const char * (*bind_parameter_name)(sqlite3_stmt*,int);\n  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));\n  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));\n  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);\n  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);\n  int  (*busy_timeout)(sqlite3*,int ms);\n  int  (*changes)(sqlite3*);\n  int  (*close)(sqlite3*);\n  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,\n                           int eTextRep,const char*));\n  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,\n                             int eTextRep,const void*));\n  const void * (*column_blob)(sqlite3_stmt*,int iCol);\n  int  (*column_bytes)(sqlite3_stmt*,int iCol);\n  int  (*column_bytes16)(sqlite3_stmt*,int iCol);\n  int  (*column_count)(sqlite3_stmt*pStmt);\n  const char * (*column_database_name)(sqlite3_stmt*,int);\n  const void * (*column_database_name16)(sqlite3_stmt*,int);\n  const char * (*column_decltype)(sqlite3_stmt*,int i);\n  const void * (*column_decltype16)(sqlite3_stmt*,int);\n  double  (*column_double)(sqlite3_stmt*,int iCol);\n  int  (*column_int)(sqlite3_stmt*,int iCol);\n  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);\n  const char * (*column_name)(sqlite3_stmt*,int);\n  const void * (*column_name16)(sqlite3_stmt*,int);\n  const char * (*column_origin_name)(sqlite3_stmt*,int);\n  const void * (*column_origin_name16)(sqlite3_stmt*,int);\n  const char * (*column_table_name)(sqlite3_stmt*,int);\n  const void * (*column_table_name16)(sqlite3_stmt*,int);\n  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);\n  const void * (*column_text16)(sqlite3_stmt*,int iCol);\n  int  (*column_type)(sqlite3_stmt*,int iCol);\n  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);\n  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);\n  int  (*complete)(const char*sql);\n  int  (*complete16)(const void*sql);\n  int  (*create_collation)(sqlite3*,const char*,int,void*,\n                           int(*)(void*,int,const void*,int,const void*));\n  int  (*create_collation16)(sqlite3*,const void*,int,void*,\n                             int(*)(void*,int,const void*,int,const void*));\n  int  (*create_function)(sqlite3*,const char*,int,int,void*,\n                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n                          void (*xFinal)(sqlite3_context*));\n  int  (*create_function16)(sqlite3*,const void*,int,int,void*,\n                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n                            void (*xFinal)(sqlite3_context*));\n  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);\n  int  (*data_count)(sqlite3_stmt*pStmt);\n  sqlite3 * (*db_handle)(sqlite3_stmt*);\n  int (*declare_vtab)(sqlite3*,const char*);\n  int  (*enable_shared_cache)(int);\n  int  (*errcode)(sqlite3*db);\n  const char * (*errmsg)(sqlite3*);\n  const void * (*errmsg16)(sqlite3*);\n  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);\n  int  (*expired)(sqlite3_stmt*);\n  int  (*finalize)(sqlite3_stmt*pStmt);\n  void  (*free)(void*);\n  void  (*free_table)(char**result);\n  int  (*get_autocommit)(sqlite3*);\n  void * (*get_auxdata)(sqlite3_context*,int);\n  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);\n  int  (*global_recover)(void);\n  void  (*interruptx)(sqlite3*);\n  sqlite_int64  (*last_insert_rowid)(sqlite3*);\n  const char * (*libversion)(void);\n  int  (*libversion_number)(void);\n  void *(*malloc)(int);\n  char * (*mprintf)(const char*,...);\n  int  (*open)(const char*,sqlite3**);\n  int  (*open16)(const void*,sqlite3**);\n  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);\n  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);\n  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);\n  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);\n  void *(*realloc)(void*,int);\n  int  (*reset)(sqlite3_stmt*pStmt);\n  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));\n  void  (*result_double)(sqlite3_context*,double);\n  void  (*result_error)(sqlite3_context*,const char*,int);\n  void  (*result_error16)(sqlite3_context*,const void*,int);\n  void  (*result_int)(sqlite3_context*,int);\n  void  (*result_int64)(sqlite3_context*,sqlite_int64);\n  void  (*result_null)(sqlite3_context*);\n  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));\n  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));\n  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));\n  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));\n  void  (*result_value)(sqlite3_context*,sqlite3_value*);\n  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);\n  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,\n                         const char*,const char*),void*);\n  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));\n  char * (*xsnprintf)(int,char*,const char*,...);\n  int  (*step)(sqlite3_stmt*);\n  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,\n                                char const**,char const**,int*,int*,int*);\n  void  (*thread_cleanup)(void);\n  int  (*total_changes)(sqlite3*);\n  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);\n  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);\n  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,\n                                         sqlite_int64),void*);\n  void * (*user_data)(sqlite3_context*);\n  const void * (*value_blob)(sqlite3_value*);\n  int  (*value_bytes)(sqlite3_value*);\n  int  (*value_bytes16)(sqlite3_value*);\n  double  (*value_double)(sqlite3_value*);\n  int  (*value_int)(sqlite3_value*);\n  sqlite_int64  (*value_int64)(sqlite3_value*);\n  int  (*value_numeric_type)(sqlite3_value*);\n  const unsigned char * (*value_text)(sqlite3_value*);\n  const void * (*value_text16)(sqlite3_value*);\n  const void * (*value_text16be)(sqlite3_value*);\n  const void * (*value_text16le)(sqlite3_value*);\n  int  (*value_type)(sqlite3_value*);\n  char *(*vmprintf)(const char*,va_list);\n  /* Added ??? */\n  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);\n  /* Added by 3.3.13 */\n  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);\n  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);\n  int (*clear_bindings)(sqlite3_stmt*);\n  /* Added by 3.4.1 */\n  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,\n                          void (*xDestroy)(void *));\n  /* Added by 3.5.0 */\n  int (*bind_zeroblob)(sqlite3_stmt*,int,int);\n  int (*blob_bytes)(sqlite3_blob*);\n  int (*blob_close)(sqlite3_blob*);\n  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,\n                   int,sqlite3_blob**);\n  int (*blob_read)(sqlite3_blob*,void*,int,int);\n  int (*blob_write)(sqlite3_blob*,const void*,int,int);\n  int (*create_collation_v2)(sqlite3*,const char*,int,void*,\n                             int(*)(void*,int,const void*,int,const void*),\n                             void(*)(void*));\n  int (*file_control)(sqlite3*,const char*,int,void*);\n  sqlite3_int64 (*memory_highwater)(int);\n  sqlite3_int64 (*memory_used)(void);\n  sqlite3_mutex *(*mutex_alloc)(int);\n  void (*mutex_enter)(sqlite3_mutex*);\n  void (*mutex_free)(sqlite3_mutex*);\n  void (*mutex_leave)(sqlite3_mutex*);\n  int (*mutex_try)(sqlite3_mutex*);\n  int (*open_v2)(const char*,sqlite3**,int,const char*);\n  int (*release_memory)(int);\n  void (*result_error_nomem)(sqlite3_context*);\n  void (*result_error_toobig)(sqlite3_context*);\n  int (*sleep)(int);\n  void (*soft_heap_limit)(int);\n  sqlite3_vfs *(*vfs_find)(const char*);\n  int (*vfs_register)(sqlite3_vfs*,int);\n  int (*vfs_unregister)(sqlite3_vfs*);\n  int (*xthreadsafe)(void);\n  void (*result_zeroblob)(sqlite3_context*,int);\n  void (*result_error_code)(sqlite3_context*,int);\n  int (*test_control)(int, ...);\n  void (*randomness)(int,void*);\n  sqlite3 *(*context_db_handle)(sqlite3_context*);\n  int (*extended_result_codes)(sqlite3*,int);\n  int (*limit)(sqlite3*,int,int);\n  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);\n  const char *(*sql)(sqlite3_stmt*);\n  int (*status)(int,int*,int*,int);\n  int (*backup_finish)(sqlite3_backup*);\n  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);\n  int (*backup_pagecount)(sqlite3_backup*);\n  int (*backup_remaining)(sqlite3_backup*);\n  int (*backup_step)(sqlite3_backup*,int);\n  const char *(*compileoption_get)(int);\n  int (*compileoption_used)(const char*);\n  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,\n                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n                            void (*xFinal)(sqlite3_context*),\n                            void(*xDestroy)(void*));\n  int (*db_config)(sqlite3*,int,...);\n  sqlite3_mutex *(*db_mutex)(sqlite3*);\n  int (*db_status)(sqlite3*,int,int*,int*,int);\n  int (*extended_errcode)(sqlite3*);\n  void (*log)(int,const char*,...);\n  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);\n  const char *(*sourceid)(void);\n  int (*stmt_status)(sqlite3_stmt*,int,int);\n  int (*strnicmp)(const char*,const char*,int);\n  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);\n  int (*wal_autocheckpoint)(sqlite3*,int);\n  int (*wal_checkpoint)(sqlite3*,const char*);\n  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);\n  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);\n  int (*vtab_config)(sqlite3*,int op,...);\n  int (*vtab_on_conflict)(sqlite3*);\n  /* Version 3.7.16 and later */\n  int (*close_v2)(sqlite3*);\n  const char *(*db_filename)(sqlite3*,const char*);\n  int (*db_readonly)(sqlite3*,const char*);\n  int (*db_release_memory)(sqlite3*);\n  const char *(*errstr)(int);\n  int (*stmt_busy)(sqlite3_stmt*);\n  int (*stmt_readonly)(sqlite3_stmt*);\n  int (*stricmp)(const char*,const char*);\n  int (*uri_boolean)(const char*,const char*,int);\n  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);\n  const char *(*uri_parameter)(const char*,const char*);\n  char *(*xvsnprintf)(int,char*,const char*,va_list);\n  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);\n  /* Version 3.8.7 and later */\n  int (*auto_extension)(void(*)(void));\n  int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,\n                     void(*)(void*));\n  int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,\n                      void(*)(void*),unsigned char);\n  int (*cancel_auto_extension)(void(*)(void));\n  int (*load_extension)(sqlite3*,const char*,const char*,char**);\n  void *(*malloc64)(sqlite3_uint64);\n  sqlite3_uint64 (*msize)(void*);\n  void *(*realloc64)(void*,sqlite3_uint64);\n  void (*reset_auto_extension)(void);\n  void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,\n                        void(*)(void*));\n  void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,\n                         void(*)(void*), unsigned char);\n  int (*strglob)(const char*,const char*);\n  /* Version 3.8.11 and later */\n  sqlite3_value *(*value_dup)(const sqlite3_value*);\n  void (*value_free)(sqlite3_value*);\n  int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);\n  int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);\n  /* Version 3.9.0 and later */\n  unsigned int (*value_subtype)(sqlite3_value*);\n  void (*result_subtype)(sqlite3_context*,unsigned int);\n  /* Version 3.10.0 and later */\n  int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);\n  int (*strlike)(const char*,const char*,unsigned int);\n  int (*db_cacheflush)(sqlite3*);\n  /* Version 3.12.0 and later */\n  int (*system_errno)(sqlite3*);\n  /* Version 3.14.0 and later */\n  int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);\n  char *(*expanded_sql)(sqlite3_stmt*);\n  /* Version 3.18.0 and later */\n  void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);\n  /* Version 3.20.0 and later */\n  int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,\n                    sqlite3_stmt**,const char**);\n  int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,\n                      sqlite3_stmt**,const void**);\n  int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));\n  void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));\n  void *(*value_pointer)(sqlite3_value*,const char*);\n  int (*vtab_nochange)(sqlite3_context*);\n  int (*value_nochange)(sqlite3_value*);\n  const char *(*vtab_collation)(sqlite3_index_info*,int);\n  /* Version 3.24.0 and later */\n  int (*keyword_count)(void);\n  int (*keyword_name)(int,const char**,int*);\n  int (*keyword_check)(const char*,int);\n  sqlite3_str *(*str_new)(sqlite3*);\n  char *(*str_finish)(sqlite3_str*);\n  void (*str_appendf)(sqlite3_str*, const char *zFormat, ...);\n  void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list);\n  void (*str_append)(sqlite3_str*, const char *zIn, int N);\n  void (*str_appendall)(sqlite3_str*, const char *zIn);\n  void (*str_appendchar)(sqlite3_str*, int N, char C);\n  void (*str_reset)(sqlite3_str*);\n  int (*str_errcode)(sqlite3_str*);\n  int (*str_length)(sqlite3_str*);\n  char *(*str_value)(sqlite3_str*);\n  /* Version 3.25.0 and later */\n  int (*create_window_function)(sqlite3*,const char*,int,int,void*,\n                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n                            void (*xFinal)(sqlite3_context*),\n                            void (*xValue)(sqlite3_context*),\n                            void (*xInv)(sqlite3_context*,int,sqlite3_value**),\n                            void(*xDestroy)(void*));\n  /* Version 3.26.0 and later */\n  const char *(*normalized_sql)(sqlite3_stmt*);\n  /* Version 3.28.0 and later */\n  int (*stmt_isexplain)(sqlite3_stmt*);\n  int (*value_frombind)(sqlite3_value*);\n  /* Version 3.30.0 and later */\n  int (*drop_modules)(sqlite3*,const char**);\n  /* Version 3.31.0 and later */\n  sqlite3_int64 (*hard_heap_limit64)(sqlite3_int64);\n  const char *(*uri_key)(const char*,int);\n  const char *(*filename_database)(const char*);\n  const char *(*filename_journal)(const char*);\n  const char *(*filename_wal)(const char*);\n  /* Version 3.32.0 and later */\n  char *(*create_filename)(const char*,const char*,const char*,\n                           int,const char**);\n  void (*free_filename)(char*);\n  sqlite3_file *(*database_file_object)(const char*);\n};\n\n/*\n** This is the function signature used for all extension entry points.  It\n** is also defined in the file \"loadext.c\".\n*/\ntypedef int (*sqlite3_loadext_entry)(\n  sqlite3 *db,                       /* Handle to the database. */\n  char **pzErrMsg,                   /* Used to set error string on failure. */\n  const sqlite3_api_routines *pThunk /* Extension API function pointers. */\n);\n\n/*\n** The following macros redefine the API routines so that they are\n** redirected through the global sqlite3_api structure.\n**\n** This header file is also used by the loadext.c source file\n** (part of the main SQLite library - not an extension) so that\n** it can get access to the sqlite3_api_routines structure\n** definition.  But the main library does not want to redefine\n** the API.  So the redefinition macros are only valid if the\n** SQLITE_CORE macros is undefined.\n*/\n#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)\n#define sqlite3_aggregate_context      sqlite3_api->aggregate_context\n#ifndef SQLITE_OMIT_DEPRECATED\n#define sqlite3_aggregate_count        sqlite3_api->aggregate_count\n#endif\n#define sqlite3_bind_blob              sqlite3_api->bind_blob\n#define sqlite3_bind_double            sqlite3_api->bind_double\n#define sqlite3_bind_int               sqlite3_api->bind_int\n#define sqlite3_bind_int64             sqlite3_api->bind_int64\n#define sqlite3_bind_null              sqlite3_api->bind_null\n#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count\n#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index\n#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name\n#define sqlite3_bind_text              sqlite3_api->bind_text\n#define sqlite3_bind_text16            sqlite3_api->bind_text16\n#define sqlite3_bind_value             sqlite3_api->bind_value\n#define sqlite3_busy_handler           sqlite3_api->busy_handler\n#define sqlite3_busy_timeout           sqlite3_api->busy_timeout\n#define sqlite3_changes                sqlite3_api->changes\n#define sqlite3_close                  sqlite3_api->close\n#define sqlite3_collation_needed       sqlite3_api->collation_needed\n#define sqlite3_collation_needed16     sqlite3_api->collation_needed16\n#define sqlite3_column_blob            sqlite3_api->column_blob\n#define sqlite3_column_bytes           sqlite3_api->column_bytes\n#define sqlite3_column_bytes16         sqlite3_api->column_bytes16\n#define sqlite3_column_count           sqlite3_api->column_count\n#define sqlite3_column_database_name   sqlite3_api->column_database_name\n#define sqlite3_column_database_name16 sqlite3_api->column_database_name16\n#define sqlite3_column_decltype        sqlite3_api->column_decltype\n#define sqlite3_column_decltype16      sqlite3_api->column_decltype16\n#define sqlite3_column_double          sqlite3_api->column_double\n#define sqlite3_column_int             sqlite3_api->column_int\n#define sqlite3_column_int64           sqlite3_api->column_int64\n#define sqlite3_column_name            sqlite3_api->column_name\n#define sqlite3_column_name16          sqlite3_api->column_name16\n#define sqlite3_column_origin_name     sqlite3_api->column_origin_name\n#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16\n#define sqlite3_column_table_name      sqlite3_api->column_table_name\n#define sqlite3_column_table_name16    sqlite3_api->column_table_name16\n#define sqlite3_column_text            sqlite3_api->column_text\n#define sqlite3_column_text16          sqlite3_api->column_text16\n#define sqlite3_column_type            sqlite3_api->column_type\n#define sqlite3_column_value           sqlite3_api->column_value\n#define sqlite3_commit_hook            sqlite3_api->commit_hook\n#define sqlite3_complete               sqlite3_api->complete\n#define sqlite3_complete16             sqlite3_api->complete16\n#define sqlite3_create_collation       sqlite3_api->create_collation\n#define sqlite3_create_collation16     sqlite3_api->create_collation16\n#define sqlite3_create_function        sqlite3_api->create_function\n#define sqlite3_create_function16      sqlite3_api->create_function16\n#define sqlite3_create_module          sqlite3_api->create_module\n#define sqlite3_create_module_v2       sqlite3_api->create_module_v2\n#define sqlite3_data_count             sqlite3_api->data_count\n#define sqlite3_db_handle              sqlite3_api->db_handle\n#define sqlite3_declare_vtab           sqlite3_api->declare_vtab\n#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache\n#define sqlite3_errcode                sqlite3_api->errcode\n#define sqlite3_errmsg                 sqlite3_api->errmsg\n#define sqlite3_errmsg16               sqlite3_api->errmsg16\n#define sqlite3_exec                   sqlite3_api->exec\n#ifndef SQLITE_OMIT_DEPRECATED\n#define sqlite3_expired                sqlite3_api->expired\n#endif\n#define sqlite3_finalize               sqlite3_api->finalize\n#define sqlite3_free                   sqlite3_api->free\n#define sqlite3_free_table             sqlite3_api->free_table\n#define sqlite3_get_autocommit         sqlite3_api->get_autocommit\n#define sqlite3_get_auxdata            sqlite3_api->get_auxdata\n#define sqlite3_get_table              sqlite3_api->get_table\n#ifndef SQLITE_OMIT_DEPRECATED\n#define sqlite3_global_recover         sqlite3_api->global_recover\n#endif\n#define sqlite3_interrupt              sqlite3_api->interruptx\n#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid\n#define sqlite3_libversion             sqlite3_api->libversion\n#define sqlite3_libversion_number      sqlite3_api->libversion_number\n#define sqlite3_malloc                 sqlite3_api->malloc\n#define sqlite3_mprintf                sqlite3_api->mprintf\n#define sqlite3_open                   sqlite3_api->open\n#define sqlite3_open16                 sqlite3_api->open16\n#define sqlite3_prepare                sqlite3_api->prepare\n#define sqlite3_prepare16              sqlite3_api->prepare16\n#define sqlite3_prepare_v2             sqlite3_api->prepare_v2\n#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2\n#define sqlite3_profile                sqlite3_api->profile\n#define sqlite3_progress_handler       sqlite3_api->progress_handler\n#define sqlite3_realloc                sqlite3_api->realloc\n#define sqlite3_reset                  sqlite3_api->reset\n#define sqlite3_result_blob            sqlite3_api->result_blob\n#define sqlite3_result_double          sqlite3_api->result_double\n#define sqlite3_result_error           sqlite3_api->result_error\n#define sqlite3_result_error16         sqlite3_api->result_error16\n#define sqlite3_result_int             sqlite3_api->result_int\n#define sqlite3_result_int64           sqlite3_api->result_int64\n#define sqlite3_result_null            sqlite3_api->result_null\n#define sqlite3_result_text            sqlite3_api->result_text\n#define sqlite3_result_text16          sqlite3_api->result_text16\n#define sqlite3_result_text16be        sqlite3_api->result_text16be\n#define sqlite3_result_text16le        sqlite3_api->result_text16le\n#define sqlite3_result_value           sqlite3_api->result_value\n#define sqlite3_rollback_hook          sqlite3_api->rollback_hook\n#define sqlite3_set_authorizer         sqlite3_api->set_authorizer\n#define sqlite3_set_auxdata            sqlite3_api->set_auxdata\n#define sqlite3_snprintf               sqlite3_api->xsnprintf\n#define sqlite3_step                   sqlite3_api->step\n#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata\n#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup\n#define sqlite3_total_changes          sqlite3_api->total_changes\n#define sqlite3_trace                  sqlite3_api->trace\n#ifndef SQLITE_OMIT_DEPRECATED\n#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings\n#endif\n#define sqlite3_update_hook            sqlite3_api->update_hook\n#define sqlite3_user_data              sqlite3_api->user_data\n#define sqlite3_value_blob             sqlite3_api->value_blob\n#define sqlite3_value_bytes            sqlite3_api->value_bytes\n#define sqlite3_value_bytes16          sqlite3_api->value_bytes16\n#define sqlite3_value_double           sqlite3_api->value_double\n#define sqlite3_value_int              sqlite3_api->value_int\n#define sqlite3_value_int64            sqlite3_api->value_int64\n#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type\n#define sqlite3_value_text             sqlite3_api->value_text\n#define sqlite3_value_text16           sqlite3_api->value_text16\n#define sqlite3_value_text16be         sqlite3_api->value_text16be\n#define sqlite3_value_text16le         sqlite3_api->value_text16le\n#define sqlite3_value_type             sqlite3_api->value_type\n#define sqlite3_vmprintf               sqlite3_api->vmprintf\n#define sqlite3_vsnprintf              sqlite3_api->xvsnprintf\n#define sqlite3_overload_function      sqlite3_api->overload_function\n#define sqlite3_prepare_v2             sqlite3_api->prepare_v2\n#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2\n#define sqlite3_clear_bindings         sqlite3_api->clear_bindings\n#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob\n#define sqlite3_blob_bytes             sqlite3_api->blob_bytes\n#define sqlite3_blob_close             sqlite3_api->blob_close\n#define sqlite3_blob_open              sqlite3_api->blob_open\n#define sqlite3_blob_read              sqlite3_api->blob_read\n#define sqlite3_blob_write             sqlite3_api->blob_write\n#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2\n#define sqlite3_file_control           sqlite3_api->file_control\n#define sqlite3_memory_highwater       sqlite3_api->memory_highwater\n#define sqlite3_memory_used            sqlite3_api->memory_used\n#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc\n#define sqlite3_mutex_enter            sqlite3_api->mutex_enter\n#define sqlite3_mutex_free             sqlite3_api->mutex_free\n#define sqlite3_mutex_leave            sqlite3_api->mutex_leave\n#define sqlite3_mutex_try              sqlite3_api->mutex_try\n#define sqlite3_open_v2                sqlite3_api->open_v2\n#define sqlite3_release_memory         sqlite3_api->release_memory\n#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem\n#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig\n#define sqlite3_sleep                  sqlite3_api->sleep\n#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit\n#define sqlite3_vfs_find               sqlite3_api->vfs_find\n#define sqlite3_vfs_register           sqlite3_api->vfs_register\n#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister\n#define sqlite3_threadsafe             sqlite3_api->xthreadsafe\n#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob\n#define sqlite3_result_error_code      sqlite3_api->result_error_code\n#define sqlite3_test_control           sqlite3_api->test_control\n#define sqlite3_randomness             sqlite3_api->randomness\n#define sqlite3_context_db_handle      sqlite3_api->context_db_handle\n#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes\n#define sqlite3_limit                  sqlite3_api->limit\n#define sqlite3_next_stmt              sqlite3_api->next_stmt\n#define sqlite3_sql                    sqlite3_api->sql\n#define sqlite3_status                 sqlite3_api->status\n#define sqlite3_backup_finish          sqlite3_api->backup_finish\n#define sqlite3_backup_init            sqlite3_api->backup_init\n#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount\n#define sqlite3_backup_remaining       sqlite3_api->backup_remaining\n#define sqlite3_backup_step            sqlite3_api->backup_step\n#define sqlite3_compileoption_get      sqlite3_api->compileoption_get\n#define sqlite3_compileoption_used     sqlite3_api->compileoption_used\n#define sqlite3_create_function_v2     sqlite3_api->create_function_v2\n#define sqlite3_db_config              sqlite3_api->db_config\n#define sqlite3_db_mutex               sqlite3_api->db_mutex\n#define sqlite3_db_status              sqlite3_api->db_status\n#define sqlite3_extended_errcode       sqlite3_api->extended_errcode\n#define sqlite3_log                    sqlite3_api->log\n#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64\n#define sqlite3_sourceid               sqlite3_api->sourceid\n#define sqlite3_stmt_status            sqlite3_api->stmt_status\n#define sqlite3_strnicmp               sqlite3_api->strnicmp\n#define sqlite3_unlock_notify          sqlite3_api->unlock_notify\n#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint\n#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint\n#define sqlite3_wal_hook               sqlite3_api->wal_hook\n#define sqlite3_blob_reopen            sqlite3_api->blob_reopen\n#define sqlite3_vtab_config            sqlite3_api->vtab_config\n#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict\n/* Version 3.7.16 and later */\n#define sqlite3_close_v2               sqlite3_api->close_v2\n#define sqlite3_db_filename            sqlite3_api->db_filename\n#define sqlite3_db_readonly            sqlite3_api->db_readonly\n#define sqlite3_db_release_memory      sqlite3_api->db_release_memory\n#define sqlite3_errstr                 sqlite3_api->errstr\n#define sqlite3_stmt_busy              sqlite3_api->stmt_busy\n#define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly\n#define sqlite3_stricmp                sqlite3_api->stricmp\n#define sqlite3_uri_boolean            sqlite3_api->uri_boolean\n#define sqlite3_uri_int64              sqlite3_api->uri_int64\n#define sqlite3_uri_parameter          sqlite3_api->uri_parameter\n#define sqlite3_uri_vsnprintf          sqlite3_api->xvsnprintf\n#define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2\n/* Version 3.8.7 and later */\n#define sqlite3_auto_extension         sqlite3_api->auto_extension\n#define sqlite3_bind_blob64            sqlite3_api->bind_blob64\n#define sqlite3_bind_text64            sqlite3_api->bind_text64\n#define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension\n#define sqlite3_load_extension         sqlite3_api->load_extension\n#define sqlite3_malloc64               sqlite3_api->malloc64\n#define sqlite3_msize                  sqlite3_api->msize\n#define sqlite3_realloc64              sqlite3_api->realloc64\n#define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension\n#define sqlite3_result_blob64          sqlite3_api->result_blob64\n#define sqlite3_result_text64          sqlite3_api->result_text64\n#define sqlite3_strglob                sqlite3_api->strglob\n/* Version 3.8.11 and later */\n#define sqlite3_value_dup              sqlite3_api->value_dup\n#define sqlite3_value_free             sqlite3_api->value_free\n#define sqlite3_result_zeroblob64      sqlite3_api->result_zeroblob64\n#define sqlite3_bind_zeroblob64        sqlite3_api->bind_zeroblob64\n/* Version 3.9.0 and later */\n#define sqlite3_value_subtype          sqlite3_api->value_subtype\n#define sqlite3_result_subtype         sqlite3_api->result_subtype\n/* Version 3.10.0 and later */\n#define sqlite3_status64               sqlite3_api->status64\n#define sqlite3_strlike                sqlite3_api->strlike\n#define sqlite3_db_cacheflush          sqlite3_api->db_cacheflush\n/* Version 3.12.0 and later */\n#define sqlite3_system_errno           sqlite3_api->system_errno\n/* Version 3.14.0 and later */\n#define sqlite3_trace_v2               sqlite3_api->trace_v2\n#define sqlite3_expanded_sql           sqlite3_api->expanded_sql\n/* Version 3.18.0 and later */\n#define sqlite3_set_last_insert_rowid  sqlite3_api->set_last_insert_rowid\n/* Version 3.20.0 and later */\n#define sqlite3_prepare_v3             sqlite3_api->prepare_v3\n#define sqlite3_prepare16_v3           sqlite3_api->prepare16_v3\n#define sqlite3_bind_pointer           sqlite3_api->bind_pointer\n#define sqlite3_result_pointer         sqlite3_api->result_pointer\n#define sqlite3_value_pointer          sqlite3_api->value_pointer\n/* Version 3.22.0 and later */\n#define sqlite3_vtab_nochange          sqlite3_api->vtab_nochange\n#define sqlite3_value_nochange         sqlite3_api->value_nochange\n#define sqlite3_vtab_collation         sqlite3_api->vtab_collation\n/* Version 3.24.0 and later */\n#define sqlite3_keyword_count          sqlite3_api->keyword_count\n#define sqlite3_keyword_name           sqlite3_api->keyword_name\n#define sqlite3_keyword_check          sqlite3_api->keyword_check\n#define sqlite3_str_new                sqlite3_api->str_new\n#define sqlite3_str_finish             sqlite3_api->str_finish\n#define sqlite3_str_appendf            sqlite3_api->str_appendf\n#define sqlite3_str_vappendf           sqlite3_api->str_vappendf\n#define sqlite3_str_append             sqlite3_api->str_append\n#define sqlite3_str_appendall          sqlite3_api->str_appendall\n#define sqlite3_str_appendchar         sqlite3_api->str_appendchar\n#define sqlite3_str_reset              sqlite3_api->str_reset\n#define sqlite3_str_errcode            sqlite3_api->str_errcode\n#define sqlite3_str_length             sqlite3_api->str_length\n#define sqlite3_str_value              sqlite3_api->str_value\n/* Version 3.25.0 and later */\n#define sqlite3_create_window_function sqlite3_api->create_window_function\n/* Version 3.26.0 and later */\n#define sqlite3_normalized_sql         sqlite3_api->normalized_sql\n/* Version 3.28.0 and later */\n#define sqlite3_stmt_isexplain         sqlite3_api->stmt_isexplain\n#define sqlite3_value_frombind         sqlite3_api->value_frombind\n/* Version 3.30.0 and later */\n#define sqlite3_drop_modules           sqlite3_api->drop_modules\n/* Version 3.31.0 and later */\n#define sqlite3_hard_heap_limit64      sqlite3_api->hard_heap_limit64\n#define sqlite3_uri_key                sqlite3_api->uri_key\n#define sqlite3_filename_database      sqlite3_api->filename_database\n#define sqlite3_filename_journal       sqlite3_api->filename_journal\n#define sqlite3_filename_wal           sqlite3_api->filename_wal\n/* Version 3.32.0 and later */\n#define sqlite3_create_filename        sqlite3_api->create_filename\n#define sqlite3_free_filename          sqlite3_api->free_filename\n#define sqlite3_database_file_object   sqlite3_api->database_file_object\n#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */\n\n#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)\n  /* This case when the file really is being compiled as a loadable \n  ** extension */\n# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;\n# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;\n# define SQLITE_EXTENSION_INIT3     \\\n    extern const sqlite3_api_routines *sqlite3_api;\n#else\n  /* This case when the file is being statically linked into the \n  ** application */\n# define SQLITE_EXTENSION_INIT1     /*no-op*/\n# define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */\n# define SQLITE_EXTENSION_INIT3     /*no-op*/\n#endif\n\n#endif /* SQLITE3EXT_H */\n\n/************** End of sqlite3ext.h ******************************************/\n/************** Continuing where we left off in loadext.c ********************/\n/* #include \"sqliteInt.h\" */\n\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\n/*\n** Some API routines are omitted when various features are\n** excluded from a build of SQLite.  Substitute a NULL pointer\n** for any missing APIs.\n*/\n#ifndef SQLITE_ENABLE_COLUMN_METADATA\n# define sqlite3_column_database_name   0\n# define sqlite3_column_database_name16 0\n# define sqlite3_column_table_name      0\n# define sqlite3_column_table_name16    0\n# define sqlite3_column_origin_name     0\n# define sqlite3_column_origin_name16   0\n#endif\n\n#ifdef SQLITE_OMIT_AUTHORIZATION\n# define sqlite3_set_authorizer         0\n#endif\n\n#ifdef SQLITE_OMIT_UTF16\n# define sqlite3_bind_text16            0\n# define sqlite3_collation_needed16     0\n# define sqlite3_column_decltype16      0\n# define sqlite3_column_name16          0\n# define sqlite3_column_text16          0\n# define sqlite3_complete16             0\n# define sqlite3_create_collation16     0\n# define sqlite3_create_function16      0\n# define sqlite3_errmsg16               0\n# define sqlite3_open16                 0\n# define sqlite3_prepare16              0\n# define sqlite3_prepare16_v2           0\n# define sqlite3_prepare16_v3           0\n# define sqlite3_result_error16         0\n# define sqlite3_result_text16          0\n# define sqlite3_result_text16be        0\n# define sqlite3_result_text16le        0\n# define sqlite3_value_text16           0\n# define sqlite3_value_text16be         0\n# define sqlite3_value_text16le         0\n# define sqlite3_column_database_name16 0\n# define sqlite3_column_table_name16    0\n# define sqlite3_column_origin_name16   0\n#endif\n\n#ifdef SQLITE_OMIT_COMPLETE\n# define sqlite3_complete 0\n# define sqlite3_complete16 0\n#endif\n\n#ifdef SQLITE_OMIT_DECLTYPE\n# define sqlite3_column_decltype16      0\n# define sqlite3_column_decltype        0\n#endif\n\n#ifdef SQLITE_OMIT_PROGRESS_CALLBACK\n# define sqlite3_progress_handler 0\n#endif\n\n#ifdef SQLITE_OMIT_VIRTUALTABLE\n# define sqlite3_create_module 0\n# define sqlite3_create_module_v2 0\n# define sqlite3_declare_vtab 0\n# define sqlite3_vtab_config 0\n# define sqlite3_vtab_on_conflict 0\n# define sqlite3_vtab_collation 0\n#endif\n\n#ifdef SQLITE_OMIT_SHARED_CACHE\n# define sqlite3_enable_shared_cache 0\n#endif\n\n#if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)\n# define sqlite3_profile       0\n# define sqlite3_trace         0\n#endif\n\n#ifdef SQLITE_OMIT_GET_TABLE\n# define sqlite3_free_table    0\n# define sqlite3_get_table     0\n#endif\n\n#ifdef SQLITE_OMIT_INCRBLOB\n#define sqlite3_bind_zeroblob  0\n#define sqlite3_blob_bytes     0\n#define sqlite3_blob_close     0\n#define sqlite3_blob_open      0\n#define sqlite3_blob_read      0\n#define sqlite3_blob_write     0\n#define sqlite3_blob_reopen    0\n#endif\n\n#if defined(SQLITE_OMIT_TRACE)\n# define sqlite3_trace_v2      0\n#endif\n\n/*\n** The following structure contains pointers to all SQLite API routines.\n** A pointer to this structure is passed into extensions when they are\n** loaded so that the extension can make calls back into the SQLite\n** library.\n**\n** When adding new APIs, add them to the bottom of this structure\n** in order to preserve backwards compatibility.\n**\n** Extensions that use newer APIs should first call the\n** sqlite3_libversion_number() to make sure that the API they\n** intend to use is supported by the library.  Extensions should\n** also check to make sure that the pointer to the function is\n** not NULL before calling it.\n*/\nstatic const sqlite3_api_routines sqlite3Apis = {\n  sqlite3_aggregate_context,\n#ifndef SQLITE_OMIT_DEPRECATED\n  sqlite3_aggregate_count,\n#else\n  0,\n#endif\n  sqlite3_bind_blob,\n  sqlite3_bind_double,\n  sqlite3_bind_int,\n  sqlite3_bind_int64,\n  sqlite3_bind_null,\n  sqlite3_bind_parameter_count,\n  sqlite3_bind_parameter_index,\n  sqlite3_bind_parameter_name,\n  sqlite3_bind_text,\n  sqlite3_bind_text16,\n  sqlite3_bind_value,\n  sqlite3_busy_handler,\n  sqlite3_busy_timeout,\n  sqlite3_changes,\n  sqlite3_close,\n  sqlite3_collation_needed,\n  sqlite3_collation_needed16,\n  sqlite3_column_blob,\n  sqlite3_column_bytes,\n  sqlite3_column_bytes16,\n  sqlite3_column_count,\n  sqlite3_column_database_name,\n  sqlite3_column_database_name16,\n  sqlite3_column_decltype,\n  sqlite3_column_decltype16,\n  sqlite3_column_double,\n  sqlite3_column_int,\n  sqlite3_column_int64,\n  sqlite3_column_name,\n  sqlite3_column_name16,\n  sqlite3_column_origin_name,\n  sqlite3_column_origin_name16,\n  sqlite3_column_table_name,\n  sqlite3_column_table_name16,\n  sqlite3_column_text,\n  sqlite3_column_text16,\n  sqlite3_column_type,\n  sqlite3_column_value,\n  sqlite3_commit_hook,\n  sqlite3_complete,\n  sqlite3_complete16,\n  sqlite3_create_collation,\n  sqlite3_create_collation16,\n  sqlite3_create_function,\n  sqlite3_create_function16,\n  sqlite3_create_module,\n  sqlite3_data_count,\n  sqlite3_db_handle,\n  sqlite3_declare_vtab,\n  sqlite3_enable_shared_cache,\n  sqlite3_errcode,\n  sqlite3_errmsg,\n  sqlite3_errmsg16,\n  sqlite3_exec,\n#ifndef SQLITE_OMIT_DEPRECATED\n  sqlite3_expired,\n#else\n  0,\n#endif\n  sqlite3_finalize,\n  sqlite3_free,\n  sqlite3_free_table,\n  sqlite3_get_autocommit,\n  sqlite3_get_auxdata,\n  sqlite3_get_table,\n  0,     /* Was sqlite3_global_recover(), but that function is deprecated */\n  sqlite3_interrupt,\n  sqlite3_last_insert_rowid,\n  sqlite3_libversion,\n  sqlite3_libversion_number,\n  sqlite3_malloc,\n  sqlite3_mprintf,\n  sqlite3_open,\n  sqlite3_open16,\n  sqlite3_prepare,\n  sqlite3_prepare16,\n  sqlite3_profile,\n  sqlite3_progress_handler,\n  sqlite3_realloc,\n  sqlite3_reset,\n  sqlite3_result_blob,\n  sqlite3_result_double,\n  sqlite3_result_error,\n  sqlite3_result_error16,\n  sqlite3_result_int,\n  sqlite3_result_int64,\n  sqlite3_result_null,\n  sqlite3_result_text,\n  sqlite3_result_text16,\n  sqlite3_result_text16be,\n  sqlite3_result_text16le,\n  sqlite3_result_value,\n  sqlite3_rollback_hook,\n  sqlite3_set_authorizer,\n  sqlite3_set_auxdata,\n  sqlite3_snprintf,\n  sqlite3_step,\n  sqlite3_table_column_metadata,\n#ifndef SQLITE_OMIT_DEPRECATED\n  sqlite3_thread_cleanup,\n#else\n  0,\n#endif\n  sqlite3_total_changes,\n  sqlite3_trace,\n#ifndef SQLITE_OMIT_DEPRECATED\n  sqlite3_transfer_bindings,\n#else\n  0,\n#endif\n  sqlite3_update_hook,\n  sqlite3_user_data,\n  sqlite3_value_blob,\n  sqlite3_value_bytes,\n  sqlite3_value_bytes16,\n  sqlite3_value_double,\n  sqlite3_value_int,\n  sqlite3_value_int64,\n  sqlite3_value_numeric_type,\n  sqlite3_value_text,\n  sqlite3_value_text16,\n  sqlite3_value_text16be,\n  sqlite3_value_text16le,\n  sqlite3_value_type,\n  sqlite3_vmprintf,\n  /*\n  ** The original API set ends here.  All extensions can call any\n  ** of the APIs above provided that the pointer is not NULL.  But\n  ** before calling APIs that follow, extension should check the\n  ** sqlite3_libversion_number() to make sure they are dealing with\n  ** a library that is new enough to support that API.\n  *************************************************************************\n  */\n  sqlite3_overload_function,\n\n  /*\n  ** Added after 3.3.13\n  */\n  sqlite3_prepare_v2,\n  sqlite3_prepare16_v2,\n  sqlite3_clear_bindings,\n\n  /*\n  ** Added for 3.4.1\n  */\n  sqlite3_create_module_v2,\n\n  /*\n  ** Added for 3.5.0\n  */\n  sqlite3_bind_zeroblob,\n  sqlite3_blob_bytes,\n  sqlite3_blob_close,\n  sqlite3_blob_open,\n  sqlite3_blob_read,\n  sqlite3_blob_write,\n  sqlite3_create_collation_v2,\n  sqlite3_file_control,\n  sqlite3_memory_highwater,\n  sqlite3_memory_used,\n#ifdef SQLITE_MUTEX_OMIT\n  0, \n  0, \n  0,\n  0,\n  0,\n#else\n  sqlite3_mutex_alloc,\n  sqlite3_mutex_enter,\n  sqlite3_mutex_free,\n  sqlite3_mutex_leave,\n  sqlite3_mutex_try,\n#endif\n  sqlite3_open_v2,\n  sqlite3_release_memory,\n  sqlite3_result_error_nomem,\n  sqlite3_result_error_toobig,\n  sqlite3_sleep,\n  sqlite3_soft_heap_limit,\n  sqlite3_vfs_find,\n  sqlite3_vfs_register,\n  sqlite3_vfs_unregister,\n\n  /*\n  ** Added for 3.5.8\n  */\n  sqlite3_threadsafe,\n  sqlite3_result_zeroblob,\n  sqlite3_result_error_code,\n  sqlite3_test_control,\n  sqlite3_randomness,\n  sqlite3_context_db_handle,\n\n  /*\n  ** Added for 3.6.0\n  */\n  sqlite3_extended_result_codes,\n  sqlite3_limit,\n  sqlite3_next_stmt,\n  sqlite3_sql,\n  sqlite3_status,\n\n  /*\n  ** Added for 3.7.4\n  */\n  sqlite3_backup_finish,\n  sqlite3_backup_init,\n  sqlite3_backup_pagecount,\n  sqlite3_backup_remaining,\n  sqlite3_backup_step,\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\n  sqlite3_compileoption_get,\n  sqlite3_compileoption_used,\n#else\n  0,\n  0,\n#endif\n  sqlite3_create_function_v2,\n  sqlite3_db_config,\n  sqlite3_db_mutex,\n  sqlite3_db_status,\n  sqlite3_extended_errcode,\n  sqlite3_log,\n  sqlite3_soft_heap_limit64,\n  sqlite3_sourceid,\n  sqlite3_stmt_status,\n  sqlite3_strnicmp,\n#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY\n  sqlite3_unlock_notify,\n#else\n  0,\n#endif\n#ifndef SQLITE_OMIT_WAL\n  sqlite3_wal_autocheckpoint,\n  sqlite3_wal_checkpoint,\n  sqlite3_wal_hook,\n#else\n  0,\n  0,\n  0,\n#endif\n  sqlite3_blob_reopen,\n  sqlite3_vtab_config,\n  sqlite3_vtab_on_conflict,\n  sqlite3_close_v2,\n  sqlite3_db_filename,\n  sqlite3_db_readonly,\n  sqlite3_db_release_memory,\n  sqlite3_errstr,\n  sqlite3_stmt_busy,\n  sqlite3_stmt_readonly,\n  sqlite3_stricmp,\n  sqlite3_uri_boolean,\n  sqlite3_uri_int64,\n  sqlite3_uri_parameter,\n  sqlite3_vsnprintf,\n  sqlite3_wal_checkpoint_v2,\n  /* Version 3.8.7 and later */\n  sqlite3_auto_extension,\n  sqlite3_bind_blob64,\n  sqlite3_bind_text64,\n  sqlite3_cancel_auto_extension,\n  sqlite3_load_extension,\n  sqlite3_malloc64,\n  sqlite3_msize,\n  sqlite3_realloc64,\n  sqlite3_reset_auto_extension,\n  sqlite3_result_blob64,\n  sqlite3_result_text64,\n  sqlite3_strglob,\n  /* Version 3.8.11 and later */\n  (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,\n  sqlite3_value_free,\n  sqlite3_result_zeroblob64,\n  sqlite3_bind_zeroblob64,\n  /* Version 3.9.0 and later */\n  sqlite3_value_subtype,\n  sqlite3_result_subtype,\n  /* Version 3.10.0 and later */\n  sqlite3_status64,\n  sqlite3_strlike,\n  sqlite3_db_cacheflush,\n  /* Version 3.12.0 and later */\n  sqlite3_system_errno,\n  /* Version 3.14.0 and later */\n  sqlite3_trace_v2,\n  sqlite3_expanded_sql,\n  /* Version 3.18.0 and later */\n  sqlite3_set_last_insert_rowid,\n  /* Version 3.20.0 and later */\n  sqlite3_prepare_v3,\n  sqlite3_prepare16_v3,\n  sqlite3_bind_pointer,\n  sqlite3_result_pointer,\n  sqlite3_value_pointer,\n  /* Version 3.22.0 and later */\n  sqlite3_vtab_nochange,\n  sqlite3_value_nochange,\n  sqlite3_vtab_collation,\n  /* Version 3.24.0 and later */\n  sqlite3_keyword_count,\n  sqlite3_keyword_name,\n  sqlite3_keyword_check,\n  sqlite3_str_new,\n  sqlite3_str_finish,\n  sqlite3_str_appendf,\n  sqlite3_str_vappendf,\n  sqlite3_str_append,\n  sqlite3_str_appendall,\n  sqlite3_str_appendchar,\n  sqlite3_str_reset,\n  sqlite3_str_errcode,\n  sqlite3_str_length,\n  sqlite3_str_value,\n  /* Version 3.25.0 and later */\n  sqlite3_create_window_function,\n  /* Version 3.26.0 and later */\n#ifdef SQLITE_ENABLE_NORMALIZE\n  sqlite3_normalized_sql,\n#else\n  0,\n#endif\n  /* Version 3.28.0 and later */\n  sqlite3_stmt_isexplain,\n  sqlite3_value_frombind,\n  /* Version 3.30.0 and later */\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  sqlite3_drop_modules,\n#else\n  0,\n#endif\n  /* Version 3.31.0 and later */\n  sqlite3_hard_heap_limit64,\n  sqlite3_uri_key,\n  sqlite3_filename_database,\n  sqlite3_filename_journal,\n  sqlite3_filename_wal,\n  /* Version 3.32.0 and later */\n  sqlite3_create_filename,\n  sqlite3_free_filename,\n  sqlite3_database_file_object,\n};\n\n/* True if x is the directory separator character\n*/\n#if SQLITE_OS_WIN\n# define DirSep(X)  ((X)=='/'||(X)=='\\\\')\n#else\n# define DirSep(X)  ((X)=='/')\n#endif\n\n/*\n** Attempt to load an SQLite extension library contained in the file\n** zFile.  The entry point is zProc.  zProc may be 0 in which case a\n** default entry point name (sqlite3_extension_init) is used.  Use\n** of the default name is recommended.\n**\n** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.\n**\n** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with \n** error message text.  The calling function should free this memory\n** by calling sqlite3DbFree(db, ).\n*/\nstatic int sqlite3LoadExtension(\n  sqlite3 *db,          /* Load the extension into this database connection */\n  const char *zFile,    /* Name of the shared library containing extension */\n  const char *zProc,    /* Entry point.  Use \"sqlite3_extension_init\" if 0 */\n  char **pzErrMsg       /* Put error message here if not 0 */\n){\n  sqlite3_vfs *pVfs = db->pVfs;\n  void *handle;\n  sqlite3_loadext_entry xInit;\n  char *zErrmsg = 0;\n  const char *zEntry;\n  char *zAltEntry = 0;\n  void **aHandle;\n  u64 nMsg = 300 + sqlite3Strlen30(zFile);\n  int ii;\n  int rc;\n\n  /* Shared library endings to try if zFile cannot be loaded as written */\n  static const char *azEndings[] = {\n#if SQLITE_OS_WIN\n     \"dll\"   \n#elif defined(__APPLE__)\n     \"dylib\"\n#else\n     \"so\"\n#endif\n  };\n\n\n  if( pzErrMsg ) *pzErrMsg = 0;\n\n  /* Ticket #1863.  To avoid a creating security problems for older\n  ** applications that relink against newer versions of SQLite, the\n  ** ability to run load_extension is turned off by default.  One\n  ** must call either sqlite3_enable_load_extension(db) or\n  ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)\n  ** to turn on extension loading.\n  */\n  if( (db->flags & SQLITE_LoadExtension)==0 ){\n    if( pzErrMsg ){\n      *pzErrMsg = sqlite3_mprintf(\"not authorized\");\n    }\n    return SQLITE_ERROR;\n  }\n\n  zEntry = zProc ? zProc : \"sqlite3_extension_init\";\n\n  handle = sqlite3OsDlOpen(pVfs, zFile);\n#if SQLITE_OS_UNIX || SQLITE_OS_WIN\n  for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){\n    char *zAltFile = sqlite3_mprintf(\"%s.%s\", zFile, azEndings[ii]);\n    if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;\n    handle = sqlite3OsDlOpen(pVfs, zAltFile);\n    sqlite3_free(zAltFile);\n  }\n#endif\n  if( handle==0 ){\n    if( pzErrMsg ){\n      *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);\n      if( zErrmsg ){\n        sqlite3_snprintf(nMsg, zErrmsg, \n            \"unable to open shared library [%s]\", zFile);\n        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);\n      }\n    }\n    return SQLITE_ERROR;\n  }\n  xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);\n\n  /* If no entry point was specified and the default legacy\n  ** entry point name \"sqlite3_extension_init\" was not found, then\n  ** construct an entry point name \"sqlite3_X_init\" where the X is\n  ** replaced by the lowercase value of every ASCII alphabetic \n  ** character in the filename after the last \"/\" upto the first \".\",\n  ** and eliding the first three characters if they are \"lib\".  \n  ** Examples:\n  **\n  **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init\n  **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init\n  */\n  if( xInit==0 && zProc==0 ){\n    int iFile, iEntry, c;\n    int ncFile = sqlite3Strlen30(zFile);\n    zAltEntry = sqlite3_malloc64(ncFile+30);\n    if( zAltEntry==0 ){\n      sqlite3OsDlClose(pVfs, handle);\n      return SQLITE_NOMEM_BKPT;\n    }\n    memcpy(zAltEntry, \"sqlite3_\", 8);\n    for(iFile=ncFile-1; iFile>=0 && !DirSep(zFile[iFile]); iFile--){}\n    iFile++;\n    if( sqlite3_strnicmp(zFile+iFile, \"lib\", 3)==0 ) iFile += 3;\n    for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){\n      if( sqlite3Isalpha(c) ){\n        zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];\n      }\n    }\n    memcpy(zAltEntry+iEntry, \"_init\", 6);\n    zEntry = zAltEntry;\n    xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);\n  }\n  if( xInit==0 ){\n    if( pzErrMsg ){\n      nMsg += sqlite3Strlen30(zEntry);\n      *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);\n      if( zErrmsg ){\n        sqlite3_snprintf(nMsg, zErrmsg,\n            \"no entry point [%s] in shared library [%s]\", zEntry, zFile);\n        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);\n      }\n    }\n    sqlite3OsDlClose(pVfs, handle);\n    sqlite3_free(zAltEntry);\n    return SQLITE_ERROR;\n  }\n  sqlite3_free(zAltEntry);\n  rc = xInit(db, &zErrmsg, &sqlite3Apis);\n  if( rc ){\n    if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;\n    if( pzErrMsg ){\n      *pzErrMsg = sqlite3_mprintf(\"error during initialization: %s\", zErrmsg);\n    }\n    sqlite3_free(zErrmsg);\n    sqlite3OsDlClose(pVfs, handle);\n    return SQLITE_ERROR;\n  }\n\n  /* Append the new shared library handle to the db->aExtension array. */\n  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));\n  if( aHandle==0 ){\n    return SQLITE_NOMEM_BKPT;\n  }\n  if( db->nExtension>0 ){\n    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);\n  }\n  sqlite3DbFree(db, db->aExtension);\n  db->aExtension = aHandle;\n\n  db->aExtension[db->nExtension++] = handle;\n  return SQLITE_OK;\n}\nSQLITE_API int sqlite3_load_extension(\n  sqlite3 *db,          /* Load the extension into this database connection */\n  const char *zFile,    /* Name of the shared library containing extension */\n  const char *zProc,    /* Entry point.  Use \"sqlite3_extension_init\" if 0 */\n  char **pzErrMsg       /* Put error message here if not 0 */\n){\n  int rc;\n  sqlite3_mutex_enter(db->mutex);\n  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** Call this routine when the database connection is closing in order\n** to clean up loaded extensions\n*/\nSQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){\n  int i;\n  assert( sqlite3_mutex_held(db->mutex) );\n  for(i=0; i<db->nExtension; i++){\n    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);\n  }\n  sqlite3DbFree(db, db->aExtension);\n}\n\n/*\n** Enable or disable extension loading.  Extension loading is disabled by\n** default so as not to open security holes in older applications.\n*/\nSQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){\n  sqlite3_mutex_enter(db->mutex);\n  if( onoff ){\n    db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;\n  }else{\n    db->flags &= ~(u64)(SQLITE_LoadExtension|SQLITE_LoadExtFunc);\n  }\n  sqlite3_mutex_leave(db->mutex);\n  return SQLITE_OK;\n}\n\n#endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */\n\n/*\n** The following object holds the list of automatically loaded\n** extensions.\n**\n** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER\n** mutex must be held while accessing this list.\n*/\ntypedef struct sqlite3AutoExtList sqlite3AutoExtList;\nstatic SQLITE_WSD struct sqlite3AutoExtList {\n  u32 nExt;              /* Number of entries in aExt[] */          \n  void (**aExt)(void);   /* Pointers to the extension init functions */\n} sqlite3Autoext = { 0, 0 };\n\n/* The \"wsdAutoext\" macro will resolve to the autoextension\n** state vector.  If writable static data is unsupported on the target,\n** we have to locate the state vector at run-time.  In the more common\n** case where writable static data is supported, wsdStat can refer directly\n** to the \"sqlite3Autoext\" state vector declared above.\n*/\n#ifdef SQLITE_OMIT_WSD\n# define wsdAutoextInit \\\n  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)\n# define wsdAutoext x[0]\n#else\n# define wsdAutoextInit\n# define wsdAutoext sqlite3Autoext\n#endif\n\n\n/*\n** Register a statically linked extension that is automatically\n** loaded by every new database connection.\n*/\nSQLITE_API int sqlite3_auto_extension(\n  void (*xInit)(void)\n){\n  int rc = SQLITE_OK;\n#ifndef SQLITE_OMIT_AUTOINIT\n  rc = sqlite3_initialize();\n  if( rc ){\n    return rc;\n  }else\n#endif\n  {\n    u32 i;\n#if SQLITE_THREADSAFE\n    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);\n#endif\n    wsdAutoextInit;\n    sqlite3_mutex_enter(mutex);\n    for(i=0; i<wsdAutoext.nExt; i++){\n      if( wsdAutoext.aExt[i]==xInit ) break;\n    }\n    if( i==wsdAutoext.nExt ){\n      u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);\n      void (**aNew)(void);\n      aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);\n      if( aNew==0 ){\n        rc = SQLITE_NOMEM_BKPT;\n      }else{\n        wsdAutoext.aExt = aNew;\n        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;\n        wsdAutoext.nExt++;\n      }\n    }\n    sqlite3_mutex_leave(mutex);\n    assert( (rc&0xff)==rc );\n    return rc;\n  }\n}\n\n/*\n** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the\n** set of routines that is invoked for each new database connection, if it\n** is currently on the list.  If xInit is not on the list, then this\n** routine is a no-op.\n**\n** Return 1 if xInit was found on the list and removed.  Return 0 if xInit\n** was not on the list.\n*/\nSQLITE_API int sqlite3_cancel_auto_extension(\n  void (*xInit)(void)\n){\n#if SQLITE_THREADSAFE\n  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);\n#endif\n  int i;\n  int n = 0;\n  wsdAutoextInit;\n  sqlite3_mutex_enter(mutex);\n  for(i=(int)wsdAutoext.nExt-1; i>=0; i--){\n    if( wsdAutoext.aExt[i]==xInit ){\n      wsdAutoext.nExt--;\n      wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];\n      n++;\n      break;\n    }\n  }\n  sqlite3_mutex_leave(mutex);\n  return n;\n}\n\n/*\n** Reset the automatic extension loading mechanism.\n*/\nSQLITE_API void sqlite3_reset_auto_extension(void){\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize()==SQLITE_OK )\n#endif\n  {\n#if SQLITE_THREADSAFE\n    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);\n#endif\n    wsdAutoextInit;\n    sqlite3_mutex_enter(mutex);\n    sqlite3_free(wsdAutoext.aExt);\n    wsdAutoext.aExt = 0;\n    wsdAutoext.nExt = 0;\n    sqlite3_mutex_leave(mutex);\n  }\n}\n\n/*\n** Load all automatic extensions.\n**\n** If anything goes wrong, set an error in the database connection.\n*/\nSQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){\n  u32 i;\n  int go = 1;\n  int rc;\n  sqlite3_loadext_entry xInit;\n\n  wsdAutoextInit;\n  if( wsdAutoext.nExt==0 ){\n    /* Common case: early out without every having to acquire a mutex */\n    return;\n  }\n  for(i=0; go; i++){\n    char *zErrmsg;\n#if SQLITE_THREADSAFE\n    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);\n#endif\n#ifdef SQLITE_OMIT_LOAD_EXTENSION\n    const sqlite3_api_routines *pThunk = 0;\n#else\n    const sqlite3_api_routines *pThunk = &sqlite3Apis;\n#endif\n    sqlite3_mutex_enter(mutex);\n    if( i>=wsdAutoext.nExt ){\n      xInit = 0;\n      go = 0;\n    }else{\n      xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];\n    }\n    sqlite3_mutex_leave(mutex);\n    zErrmsg = 0;\n    if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){\n      sqlite3ErrorWithMsg(db, rc,\n            \"automatic extension loading failed: %s\", zErrmsg);\n      go = 0;\n    }\n    sqlite3_free(zErrmsg);\n  }\n}\n\n/************** End of loadext.c *********************************************/\n/************** Begin file pragma.c ******************************************/\n/*\n** 2003 April 6\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code used to implement the PRAGMA command.\n*/\n/* #include \"sqliteInt.h\" */\n\n#if !defined(SQLITE_ENABLE_LOCKING_STYLE)\n#  if defined(__APPLE__)\n#    define SQLITE_ENABLE_LOCKING_STYLE 1\n#  else\n#    define SQLITE_ENABLE_LOCKING_STYLE 0\n#  endif\n#endif\n\n/***************************************************************************\n** The \"pragma.h\" include file is an automatically generated file that\n** that includes the PragType_XXXX macro definitions and the aPragmaName[]\n** object.  This ensures that the aPragmaName[] table is arranged in\n** lexicographical order to facility a binary search of the pragma name.\n** Do not edit pragma.h directly.  Edit and rerun the script in at \n** ../tool/mkpragmatab.tcl. */\n/************** Include pragma.h in the middle of pragma.c *******************/\n/************** Begin file pragma.h ******************************************/\n/* DO NOT EDIT!\n** This file is automatically generated by the script at\n** ../tool/mkpragmatab.tcl.  To update the set of pragmas, edit\n** that script and rerun it.\n*/\n\n/* The various pragma types */\n#define PragTyp_ACTIVATE_EXTENSIONS            0\n#define PragTyp_ANALYSIS_LIMIT                 1\n#define PragTyp_HEADER_VALUE                   2\n#define PragTyp_AUTO_VACUUM                    3\n#define PragTyp_FLAG                           4\n#define PragTyp_BUSY_TIMEOUT                   5\n#define PragTyp_CACHE_SIZE                     6\n#define PragTyp_CACHE_SPILL                    7\n#define PragTyp_CASE_SENSITIVE_LIKE            8\n#define PragTyp_COLLATION_LIST                 9\n#define PragTyp_COMPILE_OPTIONS               10\n#define PragTyp_DATA_STORE_DIRECTORY          11\n#define PragTyp_DATABASE_LIST                 12\n#define PragTyp_DEFAULT_CACHE_SIZE            13\n#define PragTyp_ENCODING                      14\n#define PragTyp_FOREIGN_KEY_CHECK             15\n#define PragTyp_FOREIGN_KEY_LIST              16\n#define PragTyp_FUNCTION_LIST                 17\n#define PragTyp_HARD_HEAP_LIMIT               18\n#define PragTyp_INCREMENTAL_VACUUM            19\n#define PragTyp_INDEX_INFO                    20\n#define PragTyp_INDEX_LIST                    21\n#define PragTyp_INTEGRITY_CHECK               22\n#define PragTyp_JOURNAL_MODE                  23\n#define PragTyp_JOURNAL_SIZE_LIMIT            24\n#define PragTyp_LOCK_PROXY_FILE               25\n#define PragTyp_LOCKING_MODE                  26\n#define PragTyp_PAGE_COUNT                    27\n#define PragTyp_MMAP_SIZE                     28\n#define PragTyp_MODULE_LIST                   29\n#define PragTyp_OPTIMIZE                      30\n#define PragTyp_PAGE_SIZE                     31\n#define PragTyp_PRAGMA_LIST                   32\n#define PragTyp_SECURE_DELETE                 33\n#define PragTyp_SHRINK_MEMORY                 34\n#define PragTyp_SOFT_HEAP_LIMIT               35\n#define PragTyp_SYNCHRONOUS                   36\n#define PragTyp_TABLE_INFO                    37\n#define PragTyp_TEMP_STORE                    38\n#define PragTyp_TEMP_STORE_DIRECTORY          39\n#define PragTyp_THREADS                       40\n#define PragTyp_WAL_AUTOCHECKPOINT            41\n#define PragTyp_WAL_CHECKPOINT                42\n#define PragTyp_LOCK_STATUS                   43\n#define PragTyp_STATS                         44\n\n/* Property flags associated with various pragma. */\n#define PragFlg_NeedSchema 0x01 /* Force schema load before running */\n#define PragFlg_NoColumns  0x02 /* OP_ResultRow called with zero columns */\n#define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */\n#define PragFlg_ReadOnly   0x08 /* Read-only HEADER_VALUE */\n#define PragFlg_Result0    0x10 /* Acts as query when no argument */\n#define PragFlg_Result1    0x20 /* Acts as query when has one argument */\n#define PragFlg_SchemaOpt  0x40 /* Schema restricts name search if present */\n#define PragFlg_SchemaReq  0x80 /* Schema required - \"main\" is default */\n\n/* Names of columns for pragmas that return multi-column result\n** or that return single-column results where the name of the\n** result column is different from the name of the pragma\n*/\nstatic const char *const pragCName[] = {\n  /*   0 */ \"id\",          /* Used by: foreign_key_list */\n  /*   1 */ \"seq\",        \n  /*   2 */ \"table\",      \n  /*   3 */ \"from\",       \n  /*   4 */ \"to\",         \n  /*   5 */ \"on_update\",  \n  /*   6 */ \"on_delete\",  \n  /*   7 */ \"match\",      \n  /*   8 */ \"cid\",         /* Used by: table_xinfo */\n  /*   9 */ \"name\",       \n  /*  10 */ \"type\",       \n  /*  11 */ \"notnull\",    \n  /*  12 */ \"dflt_value\", \n  /*  13 */ \"pk\",         \n  /*  14 */ \"hidden\",     \n                           /* table_info reuses 8 */\n  /*  15 */ \"seqno\",       /* Used by: index_xinfo */\n  /*  16 */ \"cid\",        \n  /*  17 */ \"name\",       \n  /*  18 */ \"desc\",       \n  /*  19 */ \"coll\",       \n  /*  20 */ \"key\",        \n  /*  21 */ \"name\",        /* Used by: function_list */\n  /*  22 */ \"builtin\",    \n  /*  23 */ \"type\",       \n  /*  24 */ \"enc\",        \n  /*  25 */ \"narg\",       \n  /*  26 */ \"flags\",      \n  /*  27 */ \"tbl\",         /* Used by: stats */\n  /*  28 */ \"idx\",        \n  /*  29 */ \"wdth\",       \n  /*  30 */ \"hght\",       \n  /*  31 */ \"flgs\",       \n  /*  32 */ \"seq\",         /* Used by: index_list */\n  /*  33 */ \"name\",       \n  /*  34 */ \"unique\",     \n  /*  35 */ \"origin\",     \n  /*  36 */ \"partial\",    \n  /*  37 */ \"table\",       /* Used by: foreign_key_check */\n  /*  38 */ \"rowid\",      \n  /*  39 */ \"parent\",     \n  /*  40 */ \"fkid\",       \n                           /* index_info reuses 15 */\n  /*  41 */ \"seq\",         /* Used by: database_list */\n  /*  42 */ \"name\",       \n  /*  43 */ \"file\",       \n  /*  44 */ \"busy\",        /* Used by: wal_checkpoint */\n  /*  45 */ \"log\",        \n  /*  46 */ \"checkpointed\",\n                           /* collation_list reuses 32 */\n  /*  47 */ \"database\",    /* Used by: lock_status */\n  /*  48 */ \"status\",     \n  /*  49 */ \"cache_size\",  /* Used by: default_cache_size */\n                           /* module_list pragma_list reuses 9 */\n  /*  50 */ \"timeout\",     /* Used by: busy_timeout */\n};\n\n/* Definitions of all built-in pragmas */\ntypedef struct PragmaName {\n  const char *const zName; /* Name of pragma */\n  u8 ePragTyp;             /* PragTyp_XXX value */\n  u8 mPragFlg;             /* Zero or more PragFlg_XXX values */\n  u8 iPragCName;           /* Start of column names in pragCName[] */\n  u8 nPragCName;           /* Num of col names. 0 means use pragma name */\n  u64 iArg;                /* Extra argument */\n} PragmaName;\nstatic const PragmaName aPragmaName[] = {\n#if defined(SQLITE_ENABLE_CEROD)\n {/* zName:     */ \"activate_extensions\",\n  /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,\n  /* ePragFlg:  */ 0,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n {/* zName:     */ \"analysis_limit\",\n  /* ePragTyp:  */ PragTyp_ANALYSIS_LIMIT,\n  /* ePragFlg:  */ PragFlg_Result0,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)\n {/* zName:     */ \"application_id\",\n  /* ePragTyp:  */ PragTyp_HEADER_VALUE,\n  /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ BTREE_APPLICATION_ID },\n#endif\n#if !defined(SQLITE_OMIT_AUTOVACUUM)\n {/* zName:     */ \"auto_vacuum\",\n  /* ePragTyp:  */ PragTyp_AUTO_VACUUM,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n#if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)\n {/* zName:     */ \"automatic_index\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_AutoIndex },\n#endif\n#endif\n {/* zName:     */ \"busy_timeout\",\n  /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,\n  /* ePragFlg:  */ PragFlg_Result0,\n  /* ColNames:  */ 50, 1,\n  /* iArg:      */ 0 },\n#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)\n {/* zName:     */ \"cache_size\",\n  /* ePragTyp:  */ PragTyp_CACHE_SIZE,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n {/* zName:     */ \"cache_spill\",\n  /* ePragTyp:  */ PragTyp_CACHE_SPILL,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA)\n {/* zName:     */ \"case_sensitive_like\",\n  /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,\n  /* ePragFlg:  */ PragFlg_NoColumns,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n {/* zName:     */ \"cell_size_check\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_CellSizeCk },\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n {/* zName:     */ \"checkpoint_fullfsync\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_CkptFullFSync },\n#endif\n#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)\n {/* zName:     */ \"collation_list\",\n  /* ePragTyp:  */ PragTyp_COLLATION_LIST,\n  /* ePragFlg:  */ PragFlg_Result0,\n  /* ColNames:  */ 32, 2,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)\n {/* zName:     */ \"compile_options\",\n  /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,\n  /* ePragFlg:  */ PragFlg_Result0,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n {/* zName:     */ \"count_changes\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_CountRows },\n#endif\n#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN\n {/* zName:     */ \"data_store_directory\",\n  /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,\n  /* ePragFlg:  */ PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)\n {/* zName:     */ \"data_version\",\n  /* ePragTyp:  */ PragTyp_HEADER_VALUE,\n  /* ePragFlg:  */ PragFlg_ReadOnly|PragFlg_Result0,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ BTREE_DATA_VERSION },\n#endif\n#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)\n {/* zName:     */ \"database_list\",\n  /* ePragTyp:  */ PragTyp_DATABASE_LIST,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0,\n  /* ColNames:  */ 41, 3,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)\n {/* zName:     */ \"default_cache_size\",\n  /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,\n  /* ColNames:  */ 49, 1,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)\n {/* zName:     */ \"defer_foreign_keys\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_DeferFKs },\n#endif\n#endif\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n {/* zName:     */ \"empty_result_callbacks\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_NullCallback },\n#endif\n#if !defined(SQLITE_OMIT_UTF16)\n {/* zName:     */ \"encoding\",\n  /* ePragTyp:  */ PragTyp_ENCODING,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)\n {/* zName:     */ \"foreign_key_check\",\n  /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0,\n  /* ColNames:  */ 37, 4,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_FOREIGN_KEY)\n {/* zName:     */ \"foreign_key_list\",\n  /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,\n  /* ColNames:  */ 0, 8,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)\n {/* zName:     */ \"foreign_keys\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_ForeignKeys },\n#endif\n#endif\n#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)\n {/* zName:     */ \"freelist_count\",\n  /* ePragTyp:  */ PragTyp_HEADER_VALUE,\n  /* ePragFlg:  */ PragFlg_ReadOnly|PragFlg_Result0,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ BTREE_FREE_PAGE_COUNT },\n#endif\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n {/* zName:     */ \"full_column_names\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_FullColNames },\n {/* zName:     */ \"fullfsync\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_FullFSync },\n#endif\n#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)\n#if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)\n {/* zName:     */ \"function_list\",\n  /* ePragTyp:  */ PragTyp_FUNCTION_LIST,\n  /* ePragFlg:  */ PragFlg_Result0,\n  /* ColNames:  */ 21, 6,\n  /* iArg:      */ 0 },\n#endif\n#endif\n {/* zName:     */ \"hard_heap_limit\",\n  /* ePragTyp:  */ PragTyp_HARD_HEAP_LIMIT,\n  /* ePragFlg:  */ PragFlg_Result0,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n#if !defined(SQLITE_OMIT_CHECK)\n {/* zName:     */ \"ignore_check_constraints\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_IgnoreChecks },\n#endif\n#endif\n#if !defined(SQLITE_OMIT_AUTOVACUUM)\n {/* zName:     */ \"incremental_vacuum\",\n  /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_NoColumns,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)\n {/* zName:     */ \"index_info\",\n  /* ePragTyp:  */ PragTyp_INDEX_INFO,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,\n  /* ColNames:  */ 15, 3,\n  /* iArg:      */ 0 },\n {/* zName:     */ \"index_list\",\n  /* ePragTyp:  */ PragTyp_INDEX_LIST,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,\n  /* ColNames:  */ 32, 5,\n  /* iArg:      */ 0 },\n {/* zName:     */ \"index_xinfo\",\n  /* ePragTyp:  */ PragTyp_INDEX_INFO,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,\n  /* ColNames:  */ 15, 6,\n  /* iArg:      */ 1 },\n#endif\n#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)\n {/* zName:     */ \"integrity_check\",\n  /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)\n {/* zName:     */ \"journal_mode\",\n  /* ePragTyp:  */ PragTyp_JOURNAL_MODE,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n {/* zName:     */ \"journal_size_limit\",\n  /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n {/* zName:     */ \"legacy_alter_table\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_LegacyAlter },\n#endif\n#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE\n {/* zName:     */ \"lock_proxy_file\",\n  /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,\n  /* ePragFlg:  */ PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)\n {/* zName:     */ \"lock_status\",\n  /* ePragTyp:  */ PragTyp_LOCK_STATUS,\n  /* ePragFlg:  */ PragFlg_Result0,\n  /* ColNames:  */ 47, 2,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)\n {/* zName:     */ \"locking_mode\",\n  /* ePragTyp:  */ PragTyp_LOCKING_MODE,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n {/* zName:     */ \"max_page_count\",\n  /* ePragTyp:  */ PragTyp_PAGE_COUNT,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n {/* zName:     */ \"mmap_size\",\n  /* ePragTyp:  */ PragTyp_MMAP_SIZE,\n  /* ePragFlg:  */ 0,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)\n#if !defined(SQLITE_OMIT_VIRTUALTABLE)\n#if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)\n {/* zName:     */ \"module_list\",\n  /* ePragTyp:  */ PragTyp_MODULE_LIST,\n  /* ePragFlg:  */ PragFlg_Result0,\n  /* ColNames:  */ 9, 1,\n  /* iArg:      */ 0 },\n#endif\n#endif\n#endif\n {/* zName:     */ \"optimize\",\n  /* ePragTyp:  */ PragTyp_OPTIMIZE,\n  /* ePragFlg:  */ PragFlg_Result1|PragFlg_NeedSchema,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)\n {/* zName:     */ \"page_count\",\n  /* ePragTyp:  */ PragTyp_PAGE_COUNT,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n {/* zName:     */ \"page_size\",\n  /* ePragTyp:  */ PragTyp_PAGE_SIZE,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n#if defined(SQLITE_DEBUG)\n {/* zName:     */ \"parser_trace\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_ParserTrace },\n#endif\n#endif\n#if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)\n {/* zName:     */ \"pragma_list\",\n  /* ePragTyp:  */ PragTyp_PRAGMA_LIST,\n  /* ePragFlg:  */ PragFlg_Result0,\n  /* ColNames:  */ 9, 1,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n {/* zName:     */ \"query_only\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_QueryOnly },\n#endif\n#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)\n {/* zName:     */ \"quick_check\",\n  /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n {/* zName:     */ \"read_uncommitted\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_ReadUncommit },\n {/* zName:     */ \"recursive_triggers\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_RecTriggers },\n {/* zName:     */ \"reverse_unordered_selects\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_ReverseOrder },\n#endif\n#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)\n {/* zName:     */ \"schema_version\",\n  /* ePragTyp:  */ PragTyp_HEADER_VALUE,\n  /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ BTREE_SCHEMA_VERSION },\n#endif\n#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)\n {/* zName:     */ \"secure_delete\",\n  /* ePragTyp:  */ PragTyp_SECURE_DELETE,\n  /* ePragFlg:  */ PragFlg_Result0,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n {/* zName:     */ \"short_column_names\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_ShortColNames },\n#endif\n {/* zName:     */ \"shrink_memory\",\n  /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,\n  /* ePragFlg:  */ PragFlg_NoColumns,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n {/* zName:     */ \"soft_heap_limit\",\n  /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,\n  /* ePragFlg:  */ PragFlg_Result0,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n#if defined(SQLITE_DEBUG)\n {/* zName:     */ \"sql_trace\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_SqlTrace },\n#endif\n#endif\n#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)\n {/* zName:     */ \"stats\",\n  /* ePragTyp:  */ PragTyp_STATS,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,\n  /* ColNames:  */ 27, 5,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)\n {/* zName:     */ \"synchronous\",\n  /* ePragTyp:  */ PragTyp_SYNCHRONOUS,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)\n {/* zName:     */ \"table_info\",\n  /* ePragTyp:  */ PragTyp_TABLE_INFO,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,\n  /* ColNames:  */ 8, 6,\n  /* iArg:      */ 0 },\n {/* zName:     */ \"table_xinfo\",\n  /* ePragTyp:  */ PragTyp_TABLE_INFO,\n  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,\n  /* ColNames:  */ 8, 7,\n  /* iArg:      */ 1 },\n#endif\n#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)\n {/* zName:     */ \"temp_store\",\n  /* ePragTyp:  */ PragTyp_TEMP_STORE,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n {/* zName:     */ \"temp_store_directory\",\n  /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,\n  /* ePragFlg:  */ PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#endif\n {/* zName:     */ \"threads\",\n  /* ePragTyp:  */ PragTyp_THREADS,\n  /* ePragFlg:  */ PragFlg_Result0,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n {/* zName:     */ \"trusted_schema\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_TrustedSchema },\n#endif\n#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)\n {/* zName:     */ \"user_version\",\n  /* ePragTyp:  */ PragTyp_HEADER_VALUE,\n  /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ BTREE_USER_VERSION },\n#endif\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n#if defined(SQLITE_DEBUG)\n {/* zName:     */ \"vdbe_addoptrace\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_VdbeAddopTrace },\n {/* zName:     */ \"vdbe_debug\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },\n {/* zName:     */ \"vdbe_eqp\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_VdbeEQP },\n {/* zName:     */ \"vdbe_listing\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_VdbeListing },\n {/* zName:     */ \"vdbe_trace\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_VdbeTrace },\n#endif\n#endif\n#if !defined(SQLITE_OMIT_WAL)\n {/* zName:     */ \"wal_autocheckpoint\",\n  /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,\n  /* ePragFlg:  */ 0,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ 0 },\n {/* zName:     */ \"wal_checkpoint\",\n  /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,\n  /* ePragFlg:  */ PragFlg_NeedSchema,\n  /* ColNames:  */ 44, 3,\n  /* iArg:      */ 0 },\n#endif\n#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)\n {/* zName:     */ \"writable_schema\",\n  /* ePragTyp:  */ PragTyp_FLAG,\n  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,\n  /* ColNames:  */ 0, 0,\n  /* iArg:      */ SQLITE_WriteSchema|SQLITE_NoSchemaError },\n#endif\n};\n/* Number of pragmas: 67 on by default, 77 total. */\n\n/************** End of pragma.h **********************************************/\n/************** Continuing where we left off in pragma.c *********************/\n\n/*\n** Interpret the given string as a safety level.  Return 0 for OFF,\n** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA.  Return 1 for an empty or \n** unrecognized string argument.  The FULL and EXTRA option is disallowed\n** if the omitFull parameter it 1.\n**\n** Note that the values returned are one less that the values that\n** should be passed into sqlite3BtreeSetSafetyLevel().  The is done\n** to support legacy SQL code.  The safety level used to be boolean\n** and older scripts may have used numbers 0 for OFF and 1 for ON.\n*/\nstatic u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){\n                             /* 123456789 123456789 123 */\n  static const char zText[] = \"onoffalseyestruextrafull\";\n  static const u8 iOffset[] = {0, 1, 2,  4,    9,  12,  15,   20};\n  static const u8 iLength[] = {2, 2, 3,  5,    3,   4,   5,    4};\n  static const u8 iValue[] =  {1, 0, 0,  0,    1,   1,   3,    2};\n                            /* on no off false yes true extra full */\n  int i, n;\n  if( sqlite3Isdigit(*z) ){\n    return (u8)sqlite3Atoi(z);\n  }\n  n = sqlite3Strlen30(z);\n  for(i=0; i<ArraySize(iLength); i++){\n    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0\n     && (!omitFull || iValue[i]<=1)\n    ){\n      return iValue[i];\n    }\n  }\n  return dflt;\n}\n\n/*\n** Interpret the given string as a boolean value.\n*/\nSQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){\n  return getSafetyLevel(z,1,dflt)!=0;\n}\n\n/* The sqlite3GetBoolean() function is used by other modules but the\n** remainder of this file is specific to PRAGMA processing.  So omit\n** the rest of the file if PRAGMAs are omitted from the build.\n*/\n#if !defined(SQLITE_OMIT_PRAGMA)\n\n/*\n** Interpret the given string as a locking mode value.\n*/\nstatic int getLockingMode(const char *z){\n  if( z ){\n    if( 0==sqlite3StrICmp(z, \"exclusive\") ) return PAGER_LOCKINGMODE_EXCLUSIVE;\n    if( 0==sqlite3StrICmp(z, \"normal\") ) return PAGER_LOCKINGMODE_NORMAL;\n  }\n  return PAGER_LOCKINGMODE_QUERY;\n}\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n/*\n** Interpret the given string as an auto-vacuum mode value.\n**\n** The following strings, \"none\", \"full\" and \"incremental\" are \n** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.\n*/\nstatic int getAutoVacuum(const char *z){\n  int i;\n  if( 0==sqlite3StrICmp(z, \"none\") ) return BTREE_AUTOVACUUM_NONE;\n  if( 0==sqlite3StrICmp(z, \"full\") ) return BTREE_AUTOVACUUM_FULL;\n  if( 0==sqlite3StrICmp(z, \"incremental\") ) return BTREE_AUTOVACUUM_INCR;\n  i = sqlite3Atoi(z);\n  return (u8)((i>=0&&i<=2)?i:0);\n}\n#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */\n\n#ifndef SQLITE_OMIT_PAGER_PRAGMAS\n/*\n** Interpret the given string as a temp db location. Return 1 for file\n** backed temporary databases, 2 for the Red-Black tree in memory database\n** and 0 to use the compile-time default.\n*/\nstatic int getTempStore(const char *z){\n  if( z[0]>='0' && z[0]<='2' ){\n    return z[0] - '0';\n  }else if( sqlite3StrICmp(z, \"file\")==0 ){\n    return 1;\n  }else if( sqlite3StrICmp(z, \"memory\")==0 ){\n    return 2;\n  }else{\n    return 0;\n  }\n}\n#endif /* SQLITE_PAGER_PRAGMAS */\n\n#ifndef SQLITE_OMIT_PAGER_PRAGMAS\n/*\n** Invalidate temp storage, either when the temp storage is changed\n** from default, or when 'file' and the temp_store_directory has changed\n*/\nstatic int invalidateTempStorage(Parse *pParse){\n  sqlite3 *db = pParse->db;\n  if( db->aDb[1].pBt!=0 ){\n    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){\n      sqlite3ErrorMsg(pParse, \"temporary storage cannot be changed \"\n        \"from within a transaction\");\n      return SQLITE_ERROR;\n    }\n    sqlite3BtreeClose(db->aDb[1].pBt);\n    db->aDb[1].pBt = 0;\n    sqlite3ResetAllSchemasOfConnection(db);\n  }\n  return SQLITE_OK;\n}\n#endif /* SQLITE_PAGER_PRAGMAS */\n\n#ifndef SQLITE_OMIT_PAGER_PRAGMAS\n/*\n** If the TEMP database is open, close it and mark the database schema\n** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE\n** or DEFAULT_TEMP_STORE pragmas.\n*/\nstatic int changeTempStorage(Parse *pParse, const char *zStorageType){\n  int ts = getTempStore(zStorageType);\n  sqlite3 *db = pParse->db;\n  if( db->temp_store==ts ) return SQLITE_OK;\n  if( invalidateTempStorage( pParse ) != SQLITE_OK ){\n    return SQLITE_ERROR;\n  }\n  db->temp_store = (u8)ts;\n  return SQLITE_OK;\n}\n#endif /* SQLITE_PAGER_PRAGMAS */\n\n/*\n** Set result column names for a pragma.\n*/\nstatic void setPragmaResultColumnNames(\n  Vdbe *v,                     /* The query under construction */\n  const PragmaName *pPragma    /* The pragma */\n){\n  u8 n = pPragma->nPragCName;\n  sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);\n  if( n==0 ){\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);\n  }else{\n    int i, j;\n    for(i=0, j=pPragma->iPragCName; i<n; i++, j++){\n      sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);\n    }\n  }\n}\n\n/*\n** Generate code to return a single integer value.\n*/\nstatic void returnSingleInt(Vdbe *v, i64 value){\n  sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);\n  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);\n}\n\n/*\n** Generate code to return a single text value.\n*/\nstatic void returnSingleText(\n  Vdbe *v,                /* Prepared statement under construction */\n  const char *zValue      /* Value to be returned */\n){\n  if( zValue ){\n    sqlite3VdbeLoadString(v, 1, (const char*)zValue);\n    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);\n  }\n}\n\n\n/*\n** Set the safety_level and pager flags for pager iDb.  Or if iDb<0\n** set these values for all pagers.\n*/\n#ifndef SQLITE_OMIT_PAGER_PRAGMAS\nstatic void setAllPagerFlags(sqlite3 *db){\n  if( db->autoCommit ){\n    Db *pDb = db->aDb;\n    int n = db->nDb;\n    assert( SQLITE_FullFSync==PAGER_FULLFSYNC );\n    assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );\n    assert( SQLITE_CacheSpill==PAGER_CACHESPILL );\n    assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)\n             ==  PAGER_FLAGS_MASK );\n    assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );\n    while( (n--) > 0 ){\n      if( pDb->pBt ){\n        sqlite3BtreeSetPagerFlags(pDb->pBt,\n                 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );\n      }\n      pDb++;\n    }\n  }\n}\n#else\n# define setAllPagerFlags(X)  /* no-op */\n#endif\n\n\n/*\n** Return a human-readable name for a constraint resolution action.\n*/\n#ifndef SQLITE_OMIT_FOREIGN_KEY\nstatic const char *actionName(u8 action){\n  const char *zName;\n  switch( action ){\n    case OE_SetNull:  zName = \"SET NULL\";        break;\n    case OE_SetDflt:  zName = \"SET DEFAULT\";     break;\n    case OE_Cascade:  zName = \"CASCADE\";         break;\n    case OE_Restrict: zName = \"RESTRICT\";        break;\n    default:          zName = \"NO ACTION\";  \n                      assert( action==OE_None ); break;\n  }\n  return zName;\n}\n#endif\n\n\n/*\n** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants\n** defined in pager.h. This function returns the associated lowercase\n** journal-mode name.\n*/\nSQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){\n  static char * const azModeName[] = {\n    \"delete\", \"persist\", \"off\", \"truncate\", \"memory\"\n#ifndef SQLITE_OMIT_WAL\n     , \"wal\"\n#endif\n  };\n  assert( PAGER_JOURNALMODE_DELETE==0 );\n  assert( PAGER_JOURNALMODE_PERSIST==1 );\n  assert( PAGER_JOURNALMODE_OFF==2 );\n  assert( PAGER_JOURNALMODE_TRUNCATE==3 );\n  assert( PAGER_JOURNALMODE_MEMORY==4 );\n  assert( PAGER_JOURNALMODE_WAL==5 );\n  assert( eMode>=0 && eMode<=ArraySize(azModeName) );\n\n  if( eMode==ArraySize(azModeName) ) return 0;\n  return azModeName[eMode];\n}\n\n/*\n** Locate a pragma in the aPragmaName[] array.\n*/\nstatic const PragmaName *pragmaLocate(const char *zName){\n  int upr, lwr, mid = 0, rc;\n  lwr = 0;\n  upr = ArraySize(aPragmaName)-1;\n  while( lwr<=upr ){\n    mid = (lwr+upr)/2;\n    rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);\n    if( rc==0 ) break;\n    if( rc<0 ){\n      upr = mid - 1;\n    }else{\n      lwr = mid + 1;\n    }\n  }\n  return lwr>upr ? 0 : &aPragmaName[mid];\n}\n\n/*\n** Create zero or more entries in the output for the SQL functions\n** defined by FuncDef p.\n*/\nstatic void pragmaFunclistLine(\n  Vdbe *v,               /* The prepared statement being created */\n  FuncDef *p,            /* A particular function definition */\n  int isBuiltin,         /* True if this is a built-in function */\n  int showInternFuncs    /* True if showing internal functions */\n){\n  for(; p; p=p->pNext){\n    const char *zType;\n    static const u32 mask = \n        SQLITE_DETERMINISTIC |\n        SQLITE_DIRECTONLY |\n        SQLITE_SUBTYPE |\n        SQLITE_INNOCUOUS |\n        SQLITE_FUNC_INTERNAL\n    ;\n    static const char *azEnc[] = { 0, \"utf8\", \"utf16le\", \"utf16be\" };\n\n    assert( SQLITE_FUNC_ENCMASK==0x3 );\n    assert( strcmp(azEnc[SQLITE_UTF8],\"utf8\")==0 );\n    assert( strcmp(azEnc[SQLITE_UTF16LE],\"utf16le\")==0 );\n    assert( strcmp(azEnc[SQLITE_UTF16BE],\"utf16be\")==0 );\n\n    if( p->xSFunc==0 ) continue;\n    if( (p->funcFlags & SQLITE_FUNC_INTERNAL)!=0\n     && showInternFuncs==0\n    ){\n      continue;\n    }    \n    if( p->xValue!=0 ){\n      zType = \"w\";\n    }else if( p->xFinalize!=0 ){\n      zType = \"a\";\n    }else{\n      zType = \"s\";\n    }\n    sqlite3VdbeMultiLoad(v, 1, \"sissii\",\n       p->zName, isBuiltin,\n       zType, azEnc[p->funcFlags&SQLITE_FUNC_ENCMASK],\n       p->nArg,\n       (p->funcFlags & mask) ^ SQLITE_INNOCUOUS\n    );\n  }\n}\n\n\n/*\n** Helper subroutine for PRAGMA integrity_check:\n**\n** Generate code to output a single-column result row with a value of the\n** string held in register 3.  Decrement the result count in register 1\n** and halt if the maximum number of result rows have been issued.\n*/\nstatic int integrityCheckResultRow(Vdbe *v){\n  int addr;\n  sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);\n  addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);\n  VdbeCoverage(v);\n  sqlite3VdbeAddOp0(v, OP_Halt);\n  return addr;\n}\n\n/*\n** Process a pragma statement.  \n**\n** Pragmas are of this form:\n**\n**      PRAGMA [schema.]id [= value]\n**\n** The identifier might also be a string.  The value is a string, and\n** identifier, or a number.  If minusFlag is true, then the value is\n** a number that was preceded by a minus sign.\n**\n** If the left side is \"database.id\" then pId1 is the database name\n** and pId2 is the id.  If the left side is just \"id\" then pId1 is the\n** id and pId2 is any empty string.\n*/\nSQLITE_PRIVATE void sqlite3Pragma(\n  Parse *pParse, \n  Token *pId1,        /* First part of [schema.]id field */\n  Token *pId2,        /* Second part of [schema.]id field, or NULL */\n  Token *pValue,      /* Token for <value>, or NULL */\n  int minusFlag       /* True if a '-' sign preceded <value> */\n){\n  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */\n  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */\n  const char *zDb = 0;   /* The database name */\n  Token *pId;            /* Pointer to <id> token */\n  char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */\n  int iDb;               /* Database index for <database> */\n  int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */\n  sqlite3 *db = pParse->db;    /* The database connection */\n  Db *pDb;                     /* The specific database being pragmaed */\n  Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */\n  const PragmaName *pPragma;   /* The pragma */\n\n  if( v==0 ) return;\n  sqlite3VdbeRunOnlyOnce(v);\n  pParse->nMem = 2;\n\n  /* Interpret the [schema.] part of the pragma statement. iDb is the\n  ** index of the database this pragma is being applied to in db.aDb[]. */\n  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);\n  if( iDb<0 ) return;\n  pDb = &db->aDb[iDb];\n\n  /* If the temp database has been explicitly named as part of the \n  ** pragma, make sure it is open. \n  */\n  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){\n    return;\n  }\n\n  zLeft = sqlite3NameFromToken(db, pId);\n  if( !zLeft ) return;\n  if( minusFlag ){\n    zRight = sqlite3MPrintf(db, \"-%T\", pValue);\n  }else{\n    zRight = sqlite3NameFromToken(db, pValue);\n  }\n\n  assert( pId2 );\n  zDb = pId2->n>0 ? pDb->zDbSName : 0;\n  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){\n    goto pragma_out;\n  }\n\n  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS\n  ** connection.  If it returns SQLITE_OK, then assume that the VFS\n  ** handled the pragma and generate a no-op prepared statement.\n  **\n  ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,\n  ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file\n  ** object corresponding to the database file to which the pragma\n  ** statement refers.\n  **\n  ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA\n  ** file control is an array of pointers to strings (char**) in which the\n  ** second element of the array is the name of the pragma and the third\n  ** element is the argument to the pragma or NULL if the pragma has no\n  ** argument.\n  */\n  aFcntl[0] = 0;\n  aFcntl[1] = zLeft;\n  aFcntl[2] = zRight;\n  aFcntl[3] = 0;\n  db->busyHandler.nBusy = 0;\n  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);\n  if( rc==SQLITE_OK ){\n    sqlite3VdbeSetNumCols(v, 1);\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);\n    returnSingleText(v, aFcntl[0]);\n    sqlite3_free(aFcntl[0]);\n    goto pragma_out;\n  }\n  if( rc!=SQLITE_NOTFOUND ){\n    if( aFcntl[0] ){\n      sqlite3ErrorMsg(pParse, \"%s\", aFcntl[0]);\n      sqlite3_free(aFcntl[0]);\n    }\n    pParse->nErr++;\n    pParse->rc = rc;\n    goto pragma_out;\n  }\n\n  /* Locate the pragma in the lookup table */\n  pPragma = pragmaLocate(zLeft);\n  if( pPragma==0 ) goto pragma_out;\n\n  /* Make sure the database schema is loaded if the pragma requires that */\n  if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){\n    if( sqlite3ReadSchema(pParse) ) goto pragma_out;\n  }\n\n  /* Register the result column names for pragmas that return results */\n  if( (pPragma->mPragFlg & PragFlg_NoColumns)==0 \n   && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)\n  ){\n    setPragmaResultColumnNames(v, pPragma);\n  }\n\n  /* Jump to the appropriate pragma handler */\n  switch( pPragma->ePragTyp ){\n  \n#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)\n  /*\n  **  PRAGMA [schema.]default_cache_size\n  **  PRAGMA [schema.]default_cache_size=N\n  **\n  ** The first form reports the current persistent setting for the\n  ** page cache size.  The value returned is the maximum number of\n  ** pages in the page cache.  The second form sets both the current\n  ** page cache size value and the persistent page cache size value\n  ** stored in the database file.\n  **\n  ** Older versions of SQLite would set the default cache size to a\n  ** negative number to indicate synchronous=OFF.  These days, synchronous\n  ** is always on by default regardless of the sign of the default cache\n  ** size.  But continue to take the absolute value of the default cache\n  ** size of historical compatibility.\n  */\n  case PragTyp_DEFAULT_CACHE_SIZE: {\n    static const int iLn = VDBE_OFFSET_LINENO(2);\n    static const VdbeOpList getCacheSize[] = {\n      { OP_Transaction, 0, 0,        0},                         /* 0 */\n      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */\n      { OP_IfPos,       1, 8,        0},\n      { OP_Integer,     0, 2,        0},\n      { OP_Subtract,    1, 2,        1},\n      { OP_IfPos,       1, 8,        0},\n      { OP_Integer,     0, 1,        0},                         /* 6 */\n      { OP_Noop,        0, 0,        0},\n      { OP_ResultRow,   1, 1,        0},\n    };\n    VdbeOp *aOp;\n    sqlite3VdbeUsesBtree(v, iDb);\n    if( !zRight ){\n      pParse->nMem += 2;\n      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));\n      aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);\n      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;\n      aOp[0].p1 = iDb;\n      aOp[1].p1 = iDb;\n      aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;\n    }else{\n      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));\n      sqlite3BeginWriteOperation(pParse, 0, iDb);\n      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);\n      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n      pDb->pSchema->cache_size = size;\n      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);\n    }\n    break;\n  }\n#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */\n\n#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)\n  /*\n  **  PRAGMA [schema.]page_size\n  **  PRAGMA [schema.]page_size=N\n  **\n  ** The first form reports the current setting for the\n  ** database page size in bytes.  The second form sets the\n  ** database page size value.  The value can only be set if\n  ** the database has not yet been created.\n  */\n  case PragTyp_PAGE_SIZE: {\n    Btree *pBt = pDb->pBt;\n    assert( pBt!=0 );\n    if( !zRight ){\n      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;\n      returnSingleInt(v, size);\n    }else{\n      /* Malloc may fail when setting the page-size, as there is an internal\n      ** buffer that the pager module resizes using sqlite3_realloc().\n      */\n      db->nextPagesize = sqlite3Atoi(zRight);\n      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,0,0) ){\n        sqlite3OomFault(db);\n      }\n    }\n    break;\n  }\n\n  /*\n  **  PRAGMA [schema.]secure_delete\n  **  PRAGMA [schema.]secure_delete=ON/OFF/FAST\n  **\n  ** The first form reports the current setting for the\n  ** secure_delete flag.  The second form changes the secure_delete\n  ** flag setting and reports the new value.\n  */\n  case PragTyp_SECURE_DELETE: {\n    Btree *pBt = pDb->pBt;\n    int b = -1;\n    assert( pBt!=0 );\n    if( zRight ){\n      if( sqlite3_stricmp(zRight, \"fast\")==0 ){\n        b = 2;\n      }else{\n        b = sqlite3GetBoolean(zRight, 0);\n      }\n    }\n    if( pId2->n==0 && b>=0 ){\n      int ii;\n      for(ii=0; ii<db->nDb; ii++){\n        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);\n      }\n    }\n    b = sqlite3BtreeSecureDelete(pBt, b);\n    returnSingleInt(v, b);\n    break;\n  }\n\n  /*\n  **  PRAGMA [schema.]max_page_count\n  **  PRAGMA [schema.]max_page_count=N\n  **\n  ** The first form reports the current setting for the\n  ** maximum number of pages in the database file.  The \n  ** second form attempts to change this setting.  Both\n  ** forms return the current setting.\n  **\n  ** The absolute value of N is used.  This is undocumented and might\n  ** change.  The only purpose is to provide an easy way to test\n  ** the sqlite3AbsInt32() function.\n  **\n  **  PRAGMA [schema.]page_count\n  **\n  ** Return the number of pages in the specified database.\n  */\n  case PragTyp_PAGE_COUNT: {\n    int iReg;\n    sqlite3CodeVerifySchema(pParse, iDb);\n    iReg = ++pParse->nMem;\n    if( sqlite3Tolower(zLeft[0])=='p' ){\n      sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);\n    }else{\n      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, \n                        sqlite3AbsInt32(sqlite3Atoi(zRight)));\n    }\n    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);\n    break;\n  }\n\n  /*\n  **  PRAGMA [schema.]locking_mode\n  **  PRAGMA [schema.]locking_mode = (normal|exclusive)\n  */\n  case PragTyp_LOCKING_MODE: {\n    const char *zRet = \"normal\";\n    int eMode = getLockingMode(zRight);\n\n    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){\n      /* Simple \"PRAGMA locking_mode;\" statement. This is a query for\n      ** the current default locking mode (which may be different to\n      ** the locking-mode of the main database).\n      */\n      eMode = db->dfltLockMode;\n    }else{\n      Pager *pPager;\n      if( pId2->n==0 ){\n        /* This indicates that no database name was specified as part\n        ** of the PRAGMA command. In this case the locking-mode must be\n        ** set on all attached databases, as well as the main db file.\n        **\n        ** Also, the sqlite3.dfltLockMode variable is set so that\n        ** any subsequently attached databases also use the specified\n        ** locking mode.\n        */\n        int ii;\n        assert(pDb==&db->aDb[0]);\n        for(ii=2; ii<db->nDb; ii++){\n          pPager = sqlite3BtreePager(db->aDb[ii].pBt);\n          sqlite3PagerLockingMode(pPager, eMode);\n        }\n        db->dfltLockMode = (u8)eMode;\n      }\n      pPager = sqlite3BtreePager(pDb->pBt);\n      eMode = sqlite3PagerLockingMode(pPager, eMode);\n    }\n\n    assert( eMode==PAGER_LOCKINGMODE_NORMAL\n            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );\n    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){\n      zRet = \"exclusive\";\n    }\n    returnSingleText(v, zRet);\n    break;\n  }\n\n  /*\n  **  PRAGMA [schema.]journal_mode\n  **  PRAGMA [schema.]journal_mode =\n  **                      (delete|persist|off|truncate|memory|wal|off)\n  */\n  case PragTyp_JOURNAL_MODE: {\n    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */\n    int ii;           /* Loop counter */\n\n    if( zRight==0 ){\n      /* If there is no \"=MODE\" part of the pragma, do a query for the\n      ** current mode */\n      eMode = PAGER_JOURNALMODE_QUERY;\n    }else{\n      const char *zMode;\n      int n = sqlite3Strlen30(zRight);\n      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){\n        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;\n      }\n      if( !zMode ){\n        /* If the \"=MODE\" part does not match any known journal mode,\n        ** then do a query */\n        eMode = PAGER_JOURNALMODE_QUERY;\n      }\n      if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){\n        /* Do not allow journal-mode \"OFF\" in defensive since the database\n        ** can become corrupted using ordinary SQL when the journal is off */\n        eMode = PAGER_JOURNALMODE_QUERY;\n      }\n    }\n    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){\n      /* Convert \"PRAGMA journal_mode\" into \"PRAGMA main.journal_mode\" */\n      iDb = 0;\n      pId2->n = 1;\n    }\n    for(ii=db->nDb-1; ii>=0; ii--){\n      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){\n        sqlite3VdbeUsesBtree(v, ii);\n        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);\n      }\n    }\n    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);\n    break;\n  }\n\n  /*\n  **  PRAGMA [schema.]journal_size_limit\n  **  PRAGMA [schema.]journal_size_limit=N\n  **\n  ** Get or set the size limit on rollback journal files.\n  */\n  case PragTyp_JOURNAL_SIZE_LIMIT: {\n    Pager *pPager = sqlite3BtreePager(pDb->pBt);\n    i64 iLimit = -2;\n    if( zRight ){\n      sqlite3DecOrHexToI64(zRight, &iLimit);\n      if( iLimit<-1 ) iLimit = -1;\n    }\n    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);\n    returnSingleInt(v, iLimit);\n    break;\n  }\n\n#endif /* SQLITE_OMIT_PAGER_PRAGMAS */\n\n  /*\n  **  PRAGMA [schema.]auto_vacuum\n  **  PRAGMA [schema.]auto_vacuum=N\n  **\n  ** Get or set the value of the database 'auto-vacuum' parameter.\n  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL\n  */\n#ifndef SQLITE_OMIT_AUTOVACUUM\n  case PragTyp_AUTO_VACUUM: {\n    Btree *pBt = pDb->pBt;\n    assert( pBt!=0 );\n    if( !zRight ){\n      returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));\n    }else{\n      int eAuto = getAutoVacuum(zRight);\n      assert( eAuto>=0 && eAuto<=2 );\n      db->nextAutovac = (u8)eAuto;\n      /* Call SetAutoVacuum() to set initialize the internal auto and\n      ** incr-vacuum flags. This is required in case this connection\n      ** creates the database file. It is important that it is created\n      ** as an auto-vacuum capable db.\n      */\n      rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);\n      if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){\n        /* When setting the auto_vacuum mode to either \"full\" or \n        ** \"incremental\", write the value of meta[6] in the database\n        ** file. Before writing to meta[6], check that meta[3] indicates\n        ** that this really is an auto-vacuum capable database.\n        */\n        static const int iLn = VDBE_OFFSET_LINENO(2);\n        static const VdbeOpList setMeta6[] = {\n          { OP_Transaction,    0,         1,                 0},    /* 0 */\n          { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},\n          { OP_If,             1,         0,                 0},    /* 2 */\n          { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */\n          { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 0},    /* 4 */\n        };\n        VdbeOp *aOp;\n        int iAddr = sqlite3VdbeCurrentAddr(v);\n        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));\n        aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);\n        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;\n        aOp[0].p1 = iDb;\n        aOp[1].p1 = iDb;\n        aOp[2].p2 = iAddr+4;\n        aOp[4].p1 = iDb;\n        aOp[4].p3 = eAuto - 1;\n        sqlite3VdbeUsesBtree(v, iDb);\n      }\n    }\n    break;\n  }\n#endif\n\n  /*\n  **  PRAGMA [schema.]incremental_vacuum(N)\n  **\n  ** Do N steps of incremental vacuuming on a database.\n  */\n#ifndef SQLITE_OMIT_AUTOVACUUM\n  case PragTyp_INCREMENTAL_VACUUM: {\n    int iLimit, addr;\n    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){\n      iLimit = 0x7fffffff;\n    }\n    sqlite3BeginWriteOperation(pParse, 0, iDb);\n    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);\n    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);\n    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);\n    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);\n    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);\n    sqlite3VdbeJumpHere(v, addr);\n    break;\n  }\n#endif\n\n#ifndef SQLITE_OMIT_PAGER_PRAGMAS\n  /*\n  **  PRAGMA [schema.]cache_size\n  **  PRAGMA [schema.]cache_size=N\n  **\n  ** The first form reports the current local setting for the\n  ** page cache size. The second form sets the local\n  ** page cache size value.  If N is positive then that is the\n  ** number of pages in the cache.  If N is negative, then the\n  ** number of pages is adjusted so that the cache uses -N kibibytes\n  ** of memory.\n  */\n  case PragTyp_CACHE_SIZE: {\n    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n    if( !zRight ){\n      returnSingleInt(v, pDb->pSchema->cache_size);\n    }else{\n      int size = sqlite3Atoi(zRight);\n      pDb->pSchema->cache_size = size;\n      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);\n    }\n    break;\n  }\n\n  /*\n  **  PRAGMA [schema.]cache_spill\n  **  PRAGMA cache_spill=BOOLEAN\n  **  PRAGMA [schema.]cache_spill=N\n  **\n  ** The first form reports the current local setting for the\n  ** page cache spill size. The second form turns cache spill on\n  ** or off.  When turnning cache spill on, the size is set to the\n  ** current cache_size.  The third form sets a spill size that\n  ** may be different form the cache size.\n  ** If N is positive then that is the\n  ** number of pages in the cache.  If N is negative, then the\n  ** number of pages is adjusted so that the cache uses -N kibibytes\n  ** of memory.\n  **\n  ** If the number of cache_spill pages is less then the number of\n  ** cache_size pages, no spilling occurs until the page count exceeds\n  ** the number of cache_size pages.\n  **\n  ** The cache_spill=BOOLEAN setting applies to all attached schemas,\n  ** not just the schema specified.\n  */\n  case PragTyp_CACHE_SPILL: {\n    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n    if( !zRight ){\n      returnSingleInt(v,\n         (db->flags & SQLITE_CacheSpill)==0 ? 0 : \n            sqlite3BtreeSetSpillSize(pDb->pBt,0));\n    }else{\n      int size = 1;\n      if( sqlite3GetInt32(zRight, &size) ){\n        sqlite3BtreeSetSpillSize(pDb->pBt, size);\n      }\n      if( sqlite3GetBoolean(zRight, size!=0) ){\n        db->flags |= SQLITE_CacheSpill;\n      }else{\n        db->flags &= ~(u64)SQLITE_CacheSpill;\n      }\n      setAllPagerFlags(db);\n    }\n    break;\n  }\n\n  /*\n  **  PRAGMA [schema.]mmap_size(N)\n  **\n  ** Used to set mapping size limit. The mapping size limit is\n  ** used to limit the aggregate size of all memory mapped regions of the\n  ** database file. If this parameter is set to zero, then memory mapping\n  ** is not used at all.  If N is negative, then the default memory map\n  ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.\n  ** The parameter N is measured in bytes.\n  **\n  ** This value is advisory.  The underlying VFS is free to memory map\n  ** as little or as much as it wants.  Except, if N is set to 0 then the\n  ** upper layers will never invoke the xFetch interfaces to the VFS.\n  */\n  case PragTyp_MMAP_SIZE: {\n    sqlite3_int64 sz;\n#if SQLITE_MAX_MMAP_SIZE>0\n    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n    if( zRight ){\n      int ii;\n      sqlite3DecOrHexToI64(zRight, &sz);\n      if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;\n      if( pId2->n==0 ) db->szMmap = sz;\n      for(ii=db->nDb-1; ii>=0; ii--){\n        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){\n          sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);\n        }\n      }\n    }\n    sz = -1;\n    rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);\n#else\n    sz = 0;\n    rc = SQLITE_OK;\n#endif\n    if( rc==SQLITE_OK ){\n      returnSingleInt(v, sz);\n    }else if( rc!=SQLITE_NOTFOUND ){\n      pParse->nErr++;\n      pParse->rc = rc;\n    }\n    break;\n  }\n\n  /*\n  **   PRAGMA temp_store\n  **   PRAGMA temp_store = \"default\"|\"memory\"|\"file\"\n  **\n  ** Return or set the local value of the temp_store flag.  Changing\n  ** the local value does not make changes to the disk file and the default\n  ** value will be restored the next time the database is opened.\n  **\n  ** Note that it is possible for the library compile-time options to\n  ** override this setting\n  */\n  case PragTyp_TEMP_STORE: {\n    if( !zRight ){\n      returnSingleInt(v, db->temp_store);\n    }else{\n      changeTempStorage(pParse, zRight);\n    }\n    break;\n  }\n\n  /*\n  **   PRAGMA temp_store_directory\n  **   PRAGMA temp_store_directory = \"\"|\"directory_name\"\n  **\n  ** Return or set the local value of the temp_store_directory flag.  Changing\n  ** the value sets a specific directory to be used for temporary files.\n  ** Setting to a null string reverts to the default temporary directory search.\n  ** If temporary directory is changed, then invalidateTempStorage.\n  **\n  */\n  case PragTyp_TEMP_STORE_DIRECTORY: {\n    if( !zRight ){\n      returnSingleText(v, sqlite3_temp_directory);\n    }else{\n#ifndef SQLITE_OMIT_WSD\n      if( zRight[0] ){\n        int res;\n        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);\n        if( rc!=SQLITE_OK || res==0 ){\n          sqlite3ErrorMsg(pParse, \"not a writable directory\");\n          goto pragma_out;\n        }\n      }\n      if( SQLITE_TEMP_STORE==0\n       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)\n       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)\n      ){\n        invalidateTempStorage(pParse);\n      }\n      sqlite3_free(sqlite3_temp_directory);\n      if( zRight[0] ){\n        sqlite3_temp_directory = sqlite3_mprintf(\"%s\", zRight);\n      }else{\n        sqlite3_temp_directory = 0;\n      }\n#endif /* SQLITE_OMIT_WSD */\n    }\n    break;\n  }\n\n#if SQLITE_OS_WIN\n  /*\n  **   PRAGMA data_store_directory\n  **   PRAGMA data_store_directory = \"\"|\"directory_name\"\n  **\n  ** Return or set the local value of the data_store_directory flag.  Changing\n  ** the value sets a specific directory to be used for database files that\n  ** were specified with a relative pathname.  Setting to a null string reverts\n  ** to the default database directory, which for database files specified with\n  ** a relative path will probably be based on the current directory for the\n  ** process.  Database file specified with an absolute path are not impacted\n  ** by this setting, regardless of its value.\n  **\n  */\n  case PragTyp_DATA_STORE_DIRECTORY: {\n    if( !zRight ){\n      returnSingleText(v, sqlite3_data_directory);\n    }else{\n#ifndef SQLITE_OMIT_WSD\n      if( zRight[0] ){\n        int res;\n        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);\n        if( rc!=SQLITE_OK || res==0 ){\n          sqlite3ErrorMsg(pParse, \"not a writable directory\");\n          goto pragma_out;\n        }\n      }\n      sqlite3_free(sqlite3_data_directory);\n      if( zRight[0] ){\n        sqlite3_data_directory = sqlite3_mprintf(\"%s\", zRight);\n      }else{\n        sqlite3_data_directory = 0;\n      }\n#endif /* SQLITE_OMIT_WSD */\n    }\n    break;\n  }\n#endif\n\n#if SQLITE_ENABLE_LOCKING_STYLE\n  /*\n  **   PRAGMA [schema.]lock_proxy_file\n  **   PRAGMA [schema.]lock_proxy_file = \":auto:\"|\"lock_file_path\"\n  **\n  ** Return or set the value of the lock_proxy_file flag.  Changing\n  ** the value sets a specific file to be used for database access locks.\n  **\n  */\n  case PragTyp_LOCK_PROXY_FILE: {\n    if( !zRight ){\n      Pager *pPager = sqlite3BtreePager(pDb->pBt);\n      char *proxy_file_path = NULL;\n      sqlite3_file *pFile = sqlite3PagerFile(pPager);\n      sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, \n                           &proxy_file_path);\n      returnSingleText(v, proxy_file_path);\n    }else{\n      Pager *pPager = sqlite3BtreePager(pDb->pBt);\n      sqlite3_file *pFile = sqlite3PagerFile(pPager);\n      int res;\n      if( zRight[0] ){\n        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, \n                                     zRight);\n      } else {\n        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, \n                                     NULL);\n      }\n      if( res!=SQLITE_OK ){\n        sqlite3ErrorMsg(pParse, \"failed to set lock proxy file\");\n        goto pragma_out;\n      }\n    }\n    break;\n  }\n#endif /* SQLITE_ENABLE_LOCKING_STYLE */      \n    \n  /*\n  **   PRAGMA [schema.]synchronous\n  **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA\n  **\n  ** Return or set the local value of the synchronous flag.  Changing\n  ** the local value does not make changes to the disk file and the\n  ** default value will be restored the next time the database is\n  ** opened.\n  */\n  case PragTyp_SYNCHRONOUS: {\n    if( !zRight ){\n      returnSingleInt(v, pDb->safety_level-1);\n    }else{\n      if( !db->autoCommit ){\n        sqlite3ErrorMsg(pParse, \n            \"Safety level may not be changed inside a transaction\");\n      }else if( iDb!=1 ){\n        int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;\n        if( iLevel==0 ) iLevel = 1;\n        pDb->safety_level = iLevel;\n        pDb->bSyncSet = 1;\n        setAllPagerFlags(db);\n      }\n    }\n    break;\n  }\n#endif /* SQLITE_OMIT_PAGER_PRAGMAS */\n\n#ifndef SQLITE_OMIT_FLAG_PRAGMAS\n  case PragTyp_FLAG: {\n    if( zRight==0 ){\n      setPragmaResultColumnNames(v, pPragma);\n      returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );\n    }else{\n      u64 mask = pPragma->iArg;    /* Mask of bits to set or clear. */\n      if( db->autoCommit==0 ){\n        /* Foreign key support may not be enabled or disabled while not\n        ** in auto-commit mode.  */\n        mask &= ~(SQLITE_ForeignKeys);\n      }\n#if SQLITE_USER_AUTHENTICATION\n      if( db->auth.authLevel==UAUTH_User ){\n        /* Do not allow non-admin users to modify the schema arbitrarily */\n        mask &= ~(SQLITE_WriteSchema);\n      }\n#endif\n\n      if( sqlite3GetBoolean(zRight, 0) ){\n        db->flags |= mask;\n      }else{\n        db->flags &= ~mask;\n        if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;\n      }\n\n      /* Many of the flag-pragmas modify the code generated by the SQL \n      ** compiler (eg. count_changes). So add an opcode to expire all\n      ** compiled SQL statements after modifying a pragma value.\n      */\n      sqlite3VdbeAddOp0(v, OP_Expire);\n      setAllPagerFlags(db);\n    }\n    break;\n  }\n#endif /* SQLITE_OMIT_FLAG_PRAGMAS */\n\n#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS\n  /*\n  **   PRAGMA table_info(<table>)\n  **\n  ** Return a single row for each column of the named table. The columns of\n  ** the returned data set are:\n  **\n  ** cid:        Column id (numbered from left to right, starting at 0)\n  ** name:       Column name\n  ** type:       Column declaration type.\n  ** notnull:    True if 'NOT NULL' is part of column declaration\n  ** dflt_value: The default value for the column, if any.\n  ** pk:         Non-zero for PK fields.\n  */\n  case PragTyp_TABLE_INFO: if( zRight ){\n    Table *pTab;\n    pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);\n    if( pTab ){\n      int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n      int i, k;\n      int nHidden = 0;\n      Column *pCol;\n      Index *pPk = sqlite3PrimaryKeyIndex(pTab);\n      pParse->nMem = 7;\n      sqlite3CodeVerifySchema(pParse, iTabDb);\n      sqlite3ViewGetColumnNames(pParse, pTab);\n      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){\n        int isHidden = 0;\n        if( pCol->colFlags & COLFLAG_NOINSERT ){\n          if( pPragma->iArg==0 ){\n            nHidden++;\n            continue;\n          }\n          if( pCol->colFlags & COLFLAG_VIRTUAL ){\n            isHidden = 2;  /* GENERATED ALWAYS AS ... VIRTUAL */\n          }else if( pCol->colFlags & COLFLAG_STORED ){\n            isHidden = 3;  /* GENERATED ALWAYS AS ... STORED */\n          }else{ assert( pCol->colFlags & COLFLAG_HIDDEN );\n            isHidden = 1;  /* HIDDEN */\n          }\n        }\n        if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){\n          k = 0;\n        }else if( pPk==0 ){\n          k = 1;\n        }else{\n          for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}\n        }\n        assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN || isHidden>=2 );\n        sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? \"issisii\" : \"issisi\",\n               i-nHidden,\n               pCol->zName,\n               sqlite3ColumnType(pCol,\"\"),\n               pCol->notNull ? 1 : 0,\n               pCol->pDflt && isHidden<2 ? pCol->pDflt->u.zToken : 0,\n               k,\n               isHidden);\n      }\n    }\n  }\n  break;\n\n#ifdef SQLITE_DEBUG\n  case PragTyp_STATS: {\n    Index *pIdx;\n    HashElem *i;\n    pParse->nMem = 5;\n    sqlite3CodeVerifySchema(pParse, iDb);\n    for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){\n      Table *pTab = sqliteHashData(i);\n      sqlite3VdbeMultiLoad(v, 1, \"ssiii\",\n           pTab->zName,\n           0,\n           pTab->szTabRow,\n           pTab->nRowLogEst,\n           pTab->tabFlags);\n      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n        sqlite3VdbeMultiLoad(v, 2, \"siiiX\",\n           pIdx->zName,\n           pIdx->szIdxRow,\n           pIdx->aiRowLogEst[0],\n           pIdx->hasStat1);\n        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);\n      }\n    }\n  }\n  break;\n#endif\n\n  case PragTyp_INDEX_INFO: if( zRight ){\n    Index *pIdx;\n    Table *pTab;\n    pIdx = sqlite3FindIndex(db, zRight, zDb);\n    if( pIdx==0 ){\n      /* If there is no index named zRight, check to see if there is a\n      ** WITHOUT ROWID table named zRight, and if there is, show the\n      ** structure of the PRIMARY KEY index for that table. */\n      pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);\n      if( pTab && !HasRowid(pTab) ){\n        pIdx = sqlite3PrimaryKeyIndex(pTab);\n      }\n    }\n    if( pIdx ){\n      int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);\n      int i;\n      int mx;\n      if( pPragma->iArg ){\n        /* PRAGMA index_xinfo (newer version with more rows and columns) */\n        mx = pIdx->nColumn;\n        pParse->nMem = 6;\n      }else{\n        /* PRAGMA index_info (legacy version) */\n        mx = pIdx->nKeyCol;\n        pParse->nMem = 3;\n      }\n      pTab = pIdx->pTable;\n      sqlite3CodeVerifySchema(pParse, iIdxDb);\n      assert( pParse->nMem<=pPragma->nPragCName );\n      for(i=0; i<mx; i++){\n        i16 cnum = pIdx->aiColumn[i];\n        sqlite3VdbeMultiLoad(v, 1, \"iisX\", i, cnum,\n                             cnum<0 ? 0 : pTab->aCol[cnum].zName);\n        if( pPragma->iArg ){\n          sqlite3VdbeMultiLoad(v, 4, \"isiX\",\n            pIdx->aSortOrder[i],\n            pIdx->azColl[i],\n            i<pIdx->nKeyCol);\n        }\n        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);\n      }\n    }\n  }\n  break;\n\n  case PragTyp_INDEX_LIST: if( zRight ){\n    Index *pIdx;\n    Table *pTab;\n    int i;\n    pTab = sqlite3FindTable(db, zRight, zDb);\n    if( pTab ){\n      int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n      pParse->nMem = 5;\n      sqlite3CodeVerifySchema(pParse, iTabDb);\n      for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){\n        const char *azOrigin[] = { \"c\", \"u\", \"pk\" };\n        sqlite3VdbeMultiLoad(v, 1, \"isisi\",\n           i,\n           pIdx->zName,\n           IsUniqueIndex(pIdx),\n           azOrigin[pIdx->idxType],\n           pIdx->pPartIdxWhere!=0);\n      }\n    }\n  }\n  break;\n\n  case PragTyp_DATABASE_LIST: {\n    int i;\n    pParse->nMem = 3;\n    for(i=0; i<db->nDb; i++){\n      if( db->aDb[i].pBt==0 ) continue;\n      assert( db->aDb[i].zDbSName!=0 );\n      sqlite3VdbeMultiLoad(v, 1, \"iss\",\n         i,\n         db->aDb[i].zDbSName,\n         sqlite3BtreeGetFilename(db->aDb[i].pBt));\n    }\n  }\n  break;\n\n  case PragTyp_COLLATION_LIST: {\n    int i = 0;\n    HashElem *p;\n    pParse->nMem = 2;\n    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){\n      CollSeq *pColl = (CollSeq *)sqliteHashData(p);\n      sqlite3VdbeMultiLoad(v, 1, \"is\", i++, pColl->zName);\n    }\n  }\n  break;\n\n#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS\n  case PragTyp_FUNCTION_LIST: {\n    int i;\n    HashElem *j;\n    FuncDef *p;\n    int showInternFunc = (db->mDbFlags & DBFLAG_InternalFunc)!=0;\n    pParse->nMem = 6;\n    for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){\n      for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){\n        pragmaFunclistLine(v, p, 1, showInternFunc);\n      }\n    }\n    for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){\n      p = (FuncDef*)sqliteHashData(j);\n      pragmaFunclistLine(v, p, 0, showInternFunc);\n    }\n  }\n  break;\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  case PragTyp_MODULE_LIST: {\n    HashElem *j;\n    pParse->nMem = 1;\n    for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){\n      Module *pMod = (Module*)sqliteHashData(j);\n      sqlite3VdbeMultiLoad(v, 1, \"s\", pMod->zName);\n    }\n  }\n  break;\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n  case PragTyp_PRAGMA_LIST: {\n    int i;\n    for(i=0; i<ArraySize(aPragmaName); i++){\n      sqlite3VdbeMultiLoad(v, 1, \"s\", aPragmaName[i].zName);\n    }\n  }\n  break;\n#endif /* SQLITE_INTROSPECTION_PRAGMAS */\n\n#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */\n\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n  case PragTyp_FOREIGN_KEY_LIST: if( zRight ){\n    FKey *pFK;\n    Table *pTab;\n    pTab = sqlite3FindTable(db, zRight, zDb);\n    if( pTab ){\n      pFK = pTab->pFKey;\n      if( pFK ){\n        int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n        int i = 0; \n        pParse->nMem = 8;\n        sqlite3CodeVerifySchema(pParse, iTabDb);\n        while(pFK){\n          int j;\n          for(j=0; j<pFK->nCol; j++){\n            sqlite3VdbeMultiLoad(v, 1, \"iissssss\",\n                   i,\n                   j,\n                   pFK->zTo,\n                   pTab->aCol[pFK->aCol[j].iFrom].zName,\n                   pFK->aCol[j].zCol,\n                   actionName(pFK->aAction[1]),  /* ON UPDATE */\n                   actionName(pFK->aAction[0]),  /* ON DELETE */\n                   \"NONE\");\n          }\n          ++i;\n          pFK = pFK->pNextFrom;\n        }\n      }\n    }\n  }\n  break;\n#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */\n\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n#ifndef SQLITE_OMIT_TRIGGER\n  case PragTyp_FOREIGN_KEY_CHECK: {\n    FKey *pFK;             /* A foreign key constraint */\n    Table *pTab;           /* Child table contain \"REFERENCES\" keyword */\n    Table *pParent;        /* Parent table that child points to */\n    Index *pIdx;           /* Index in the parent table */\n    int i;                 /* Loop counter:  Foreign key number for pTab */\n    int j;                 /* Loop counter:  Field of the foreign key */\n    HashElem *k;           /* Loop counter:  Next table in schema */\n    int x;                 /* result variable */\n    int regResult;         /* 3 registers to hold a result row */\n    int regKey;            /* Register to hold key for checking the FK */\n    int regRow;            /* Registers to hold a row from pTab */\n    int addrTop;           /* Top of a loop checking foreign keys */\n    int addrOk;            /* Jump here if the key is OK */\n    int *aiCols;           /* child to parent column mapping */\n\n    regResult = pParse->nMem+1;\n    pParse->nMem += 4;\n    regKey = ++pParse->nMem;\n    regRow = ++pParse->nMem;\n    k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);\n    while( k ){\n      int iTabDb;\n      if( zRight ){\n        pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);\n        k = 0;\n      }else{\n        pTab = (Table*)sqliteHashData(k);\n        k = sqliteHashNext(k);\n      }\n      if( pTab==0 || pTab->pFKey==0 ) continue;\n      iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n      sqlite3CodeVerifySchema(pParse, iTabDb);\n      sqlite3TableLock(pParse, iTabDb, pTab->tnum, 0, pTab->zName);\n      if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;\n      sqlite3OpenTable(pParse, 0, iTabDb, pTab, OP_OpenRead);\n      sqlite3VdbeLoadString(v, regResult, pTab->zName);\n      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){\n        pParent = sqlite3FindTable(db, pFK->zTo, zDb);\n        if( pParent==0 ) continue;\n        pIdx = 0;\n        sqlite3TableLock(pParse, iTabDb, pParent->tnum, 0, pParent->zName);\n        x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);\n        if( x==0 ){\n          if( pIdx==0 ){\n            sqlite3OpenTable(pParse, i, iTabDb, pParent, OP_OpenRead);\n          }else{\n            sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iTabDb);\n            sqlite3VdbeSetP4KeyInfo(pParse, pIdx);\n          }\n        }else{\n          k = 0;\n          break;\n        }\n      }\n      assert( pParse->nErr>0 || pFK==0 );\n      if( pFK ) break;\n      if( pParse->nTab<i ) pParse->nTab = i;\n      addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);\n      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){\n        pParent = sqlite3FindTable(db, pFK->zTo, zDb);\n        pIdx = 0;\n        aiCols = 0;\n        if( pParent ){\n          x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);\n          assert( x==0 );\n        }\n        addrOk = sqlite3VdbeMakeLabel(pParse);\n\n        /* Generate code to read the child key values into registers\n        ** regRow..regRow+n. If any of the child key values are NULL, this \n        ** row cannot cause an FK violation. Jump directly to addrOk in \n        ** this case. */\n        for(j=0; j<pFK->nCol; j++){\n          int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;\n          sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);\n          sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);\n        }\n\n        /* Generate code to query the parent index for a matching parent\n        ** key. If a match is found, jump to addrOk. */\n        if( pIdx ){\n          sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,\n              sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);\n          sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);\n          VdbeCoverage(v);\n        }else if( pParent ){\n          int jmp = sqlite3VdbeCurrentAddr(v)+2;\n          sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);\n          sqlite3VdbeGoto(v, addrOk);\n          assert( pFK->nCol==1 );\n        }\n\n        /* Generate code to report an FK violation to the caller. */\n        if( HasRowid(pTab) ){\n          sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);\n        }else{\n          sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);\n        }\n        sqlite3VdbeMultiLoad(v, regResult+2, \"siX\", pFK->zTo, i-1);\n        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);\n        sqlite3VdbeResolveLabel(v, addrOk);\n        sqlite3DbFree(db, aiCols);\n      }\n      sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);\n      sqlite3VdbeJumpHere(v, addrTop);\n    }\n  }\n  break;\n#endif /* !defined(SQLITE_OMIT_TRIGGER) */\n#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */\n\n#ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA\n  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE\n  ** used will be case sensitive or not depending on the RHS.\n  */\n  case PragTyp_CASE_SENSITIVE_LIKE: {\n    if( zRight ){\n      sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));\n    }\n  }\n  break;\n#endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */\n\n#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX\n# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100\n#endif\n\n#ifndef SQLITE_OMIT_INTEGRITY_CHECK\n  /*    PRAGMA integrity_check\n  **    PRAGMA integrity_check(N)\n  **    PRAGMA quick_check\n  **    PRAGMA quick_check(N)\n  **\n  ** Verify the integrity of the database.\n  **\n  ** The \"quick_check\" is reduced version of \n  ** integrity_check designed to detect most database corruption\n  ** without the overhead of cross-checking indexes.  Quick_check\n  ** is linear time wherease integrity_check is O(NlogN).\n  */\n  case PragTyp_INTEGRITY_CHECK: {\n    int i, j, addr, mxErr;\n\n    int isQuick = (sqlite3Tolower(zLeft[0])=='q');\n\n    /* If the PRAGMA command was of the form \"PRAGMA <db>.integrity_check\",\n    ** then iDb is set to the index of the database identified by <db>.\n    ** In this case, the integrity of database iDb only is verified by\n    ** the VDBE created below.\n    **\n    ** Otherwise, if the command was simply \"PRAGMA integrity_check\" (or\n    ** \"PRAGMA quick_check\"), then iDb is set to 0. In this case, set iDb\n    ** to -1 here, to indicate that the VDBE should verify the integrity\n    ** of all attached databases.  */\n    assert( iDb>=0 );\n    assert( iDb==0 || pId2->z );\n    if( pId2->z==0 ) iDb = -1;\n\n    /* Initialize the VDBE program */\n    pParse->nMem = 6;\n\n    /* Set the maximum error count */\n    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;\n    if( zRight ){\n      sqlite3GetInt32(zRight, &mxErr);\n      if( mxErr<=0 ){\n        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;\n      }\n    }\n    sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */\n\n    /* Do an integrity check on each database file */\n    for(i=0; i<db->nDb; i++){\n      HashElem *x;     /* For looping over tables in the schema */\n      Hash *pTbls;     /* Set of all tables in the schema */\n      int *aRoot;      /* Array of root page numbers of all btrees */\n      int cnt = 0;     /* Number of entries in aRoot[] */\n      int mxIdx = 0;   /* Maximum number of indexes for any table */\n\n      if( OMIT_TEMPDB && i==1 ) continue;\n      if( iDb>=0 && i!=iDb ) continue;\n\n      sqlite3CodeVerifySchema(pParse, i);\n\n      /* Do an integrity check of the B-Tree\n      **\n      ** Begin by finding the root pages numbers\n      ** for all tables and indices in the database.\n      */\n      assert( sqlite3SchemaMutexHeld(db, i, 0) );\n      pTbls = &db->aDb[i].pSchema->tblHash;\n      for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){\n        Table *pTab = sqliteHashData(x);  /* Current table */\n        Index *pIdx;                      /* An index on pTab */\n        int nIdx;                         /* Number of indexes on pTab */\n        if( HasRowid(pTab) ) cnt++;\n        for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }\n        if( nIdx>mxIdx ) mxIdx = nIdx;\n      }\n      aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));\n      if( aRoot==0 ) break;\n      for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){\n        Table *pTab = sqliteHashData(x);\n        Index *pIdx;\n        if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;\n        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n          aRoot[++cnt] = pIdx->tnum;\n        }\n      }\n      aRoot[0] = cnt;\n\n      /* Make sure sufficient number of registers have been allocated */\n      pParse->nMem = MAX( pParse->nMem, 8+mxIdx );\n      sqlite3ClearTempRegCache(pParse);\n\n      /* Do the b-tree integrity checks */\n      sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);\n      sqlite3VdbeChangeP5(v, (u8)i);\n      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);\n      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,\n         sqlite3MPrintf(db, \"*** in database %s ***\\n\", db->aDb[i].zDbSName),\n         P4_DYNAMIC);\n      sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);\n      integrityCheckResultRow(v);\n      sqlite3VdbeJumpHere(v, addr);\n\n      /* Make sure all the indices are constructed correctly.\n      */\n      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){\n        Table *pTab = sqliteHashData(x);\n        Index *pIdx, *pPk;\n        Index *pPrior = 0;\n        int loopTop;\n        int iDataCur, iIdxCur;\n        int r1 = -1;\n\n        if( pTab->tnum<1 ) continue;  /* Skip VIEWs or VIRTUAL TABLEs */\n        pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);\n        sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,\n                                   1, 0, &iDataCur, &iIdxCur);\n        /* reg[7] counts the number of entries in the table.\n        ** reg[8+i] counts the number of entries in the i-th index \n        */\n        sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);\n        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){\n          sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */\n        }\n        assert( pParse->nMem>=8+j );\n        assert( sqlite3NoTempsInRange(pParse,1,7+j) );\n        sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);\n        loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);\n        if( !isQuick ){\n          /* Sanity check on record header decoding */\n          sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nNVCol-1,3);\n          sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);\n        }\n        /* Verify that all NOT NULL columns really are NOT NULL */\n        for(j=0; j<pTab->nCol; j++){\n          char *zErr;\n          int jmp2;\n          if( j==pTab->iPKey ) continue;\n          if( pTab->aCol[j].notNull==0 ) continue;\n          sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);\n          if( sqlite3VdbeGetOp(v,-1)->opcode==OP_Column ){\n            sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);\n          }\n          jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);\n          zErr = sqlite3MPrintf(db, \"NULL value in %s.%s\", pTab->zName,\n                              pTab->aCol[j].zName);\n          sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);\n          integrityCheckResultRow(v);\n          sqlite3VdbeJumpHere(v, jmp2);\n        }\n        /* Verify CHECK constraints */\n        if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){\n          ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);\n          if( db->mallocFailed==0 ){\n            int addrCkFault = sqlite3VdbeMakeLabel(pParse);\n            int addrCkOk = sqlite3VdbeMakeLabel(pParse);\n            char *zErr;\n            int k;\n            pParse->iSelfTab = iDataCur + 1;\n            for(k=pCheck->nExpr-1; k>0; k--){\n              sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);\n            }\n            sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk, \n                SQLITE_JUMPIFNULL);\n            sqlite3VdbeResolveLabel(v, addrCkFault);\n            pParse->iSelfTab = 0;\n            zErr = sqlite3MPrintf(db, \"CHECK constraint failed in %s\",\n                pTab->zName);\n            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);\n            integrityCheckResultRow(v);\n            sqlite3VdbeResolveLabel(v, addrCkOk);\n          }\n          sqlite3ExprListDelete(db, pCheck);\n        }\n        if( !isQuick ){ /* Omit the remaining tests for quick_check */\n          /* Validate index entries for the current row */\n          for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){\n            int jmp2, jmp3, jmp4, jmp5;\n            int ckUniq = sqlite3VdbeMakeLabel(pParse);\n            if( pPk==pIdx ) continue;\n            r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,\n                                         pPrior, r1);\n            pPrior = pIdx;\n            sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */\n            /* Verify that an index entry exists for the current table row */\n            jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,\n                                        pIdx->nColumn); VdbeCoverage(v);\n            sqlite3VdbeLoadString(v, 3, \"row \");\n            sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);\n            sqlite3VdbeLoadString(v, 4, \" missing from index \");\n            sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);\n            jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);\n            sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);\n            jmp4 = integrityCheckResultRow(v);\n            sqlite3VdbeJumpHere(v, jmp2);\n            /* For UNIQUE indexes, verify that only one entry exists with the\n            ** current key.  The entry is unique if (1) any column is NULL\n            ** or (2) the next entry has a different key */\n            if( IsUniqueIndex(pIdx) ){\n              int uniqOk = sqlite3VdbeMakeLabel(pParse);\n              int jmp6;\n              int kk;\n              for(kk=0; kk<pIdx->nKeyCol; kk++){\n                int iCol = pIdx->aiColumn[kk];\n                assert( iCol!=XN_ROWID && iCol<pTab->nCol );\n                if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;\n                sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);\n                VdbeCoverage(v);\n              }\n              jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);\n              sqlite3VdbeGoto(v, uniqOk);\n              sqlite3VdbeJumpHere(v, jmp6);\n              sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,\n                                   pIdx->nKeyCol); VdbeCoverage(v);\n              sqlite3VdbeLoadString(v, 3, \"non-unique entry in index \");\n              sqlite3VdbeGoto(v, jmp5);\n              sqlite3VdbeResolveLabel(v, uniqOk);\n            }\n            sqlite3VdbeJumpHere(v, jmp4);\n            sqlite3ResolvePartIdxLabel(pParse, jmp3);\n          }\n        }\n        sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);\n        sqlite3VdbeJumpHere(v, loopTop-1);\n        if( !isQuick ){\n          sqlite3VdbeLoadString(v, 2, \"wrong # of entries in index \");\n          for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){\n            if( pPk==pIdx ) continue;\n            sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);\n            addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);\n            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);\n            sqlite3VdbeLoadString(v, 4, pIdx->zName);\n            sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);\n            integrityCheckResultRow(v);\n            sqlite3VdbeJumpHere(v, addr);\n          }\n        }\n      } \n    }\n    {\n      static const int iLn = VDBE_OFFSET_LINENO(2);\n      static const VdbeOpList endCode[] = {\n        { OP_AddImm,      1, 0,        0},    /* 0 */\n        { OP_IfNotZero,   1, 4,        0},    /* 1 */\n        { OP_String8,     0, 3,        0},    /* 2 */\n        { OP_ResultRow,   3, 1,        0},    /* 3 */\n        { OP_Halt,        0, 0,        0},    /* 4 */\n        { OP_String8,     0, 3,        0},    /* 5 */\n        { OP_Goto,        0, 3,        0},    /* 6 */\n      };\n      VdbeOp *aOp;\n\n      aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);\n      if( aOp ){\n        aOp[0].p2 = 1-mxErr;\n        aOp[2].p4type = P4_STATIC;\n        aOp[2].p4.z = \"ok\";\n        aOp[5].p4type = P4_STATIC;\n        aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);\n      }\n      sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);\n    }\n  }\n  break;\n#endif /* SQLITE_OMIT_INTEGRITY_CHECK */\n\n#ifndef SQLITE_OMIT_UTF16\n  /*\n  **   PRAGMA encoding\n  **   PRAGMA encoding = \"utf-8\"|\"utf-16\"|\"utf-16le\"|\"utf-16be\"\n  **\n  ** In its first form, this pragma returns the encoding of the main\n  ** database. If the database is not initialized, it is initialized now.\n  **\n  ** The second form of this pragma is a no-op if the main database file\n  ** has not already been initialized. In this case it sets the default\n  ** encoding that will be used for the main database file if a new file\n  ** is created. If an existing main database file is opened, then the\n  ** default text encoding for the existing database is used.\n  ** \n  ** In all cases new databases created using the ATTACH command are\n  ** created to use the same default text encoding as the main database. If\n  ** the main database has not been initialized and/or created when ATTACH\n  ** is executed, this is done before the ATTACH operation.\n  **\n  ** In the second form this pragma sets the text encoding to be used in\n  ** new database files created using this database handle. It is only\n  ** useful if invoked immediately after the main database i\n  */\n  case PragTyp_ENCODING: {\n    static const struct EncName {\n      char *zName;\n      u8 enc;\n    } encnames[] = {\n      { \"UTF8\",     SQLITE_UTF8        },\n      { \"UTF-8\",    SQLITE_UTF8        },  /* Must be element [1] */\n      { \"UTF-16le\", SQLITE_UTF16LE     },  /* Must be element [2] */\n      { \"UTF-16be\", SQLITE_UTF16BE     },  /* Must be element [3] */\n      { \"UTF16le\",  SQLITE_UTF16LE     },\n      { \"UTF16be\",  SQLITE_UTF16BE     },\n      { \"UTF-16\",   0                  }, /* SQLITE_UTF16NATIVE */\n      { \"UTF16\",    0                  }, /* SQLITE_UTF16NATIVE */\n      { 0, 0 }\n    };\n    const struct EncName *pEnc;\n    if( !zRight ){    /* \"PRAGMA encoding\" */\n      if( sqlite3ReadSchema(pParse) ) goto pragma_out;\n      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );\n      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );\n      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );\n      returnSingleText(v, encnames[ENC(pParse->db)].zName);\n    }else{                        /* \"PRAGMA encoding = XXX\" */\n      /* Only change the value of sqlite.enc if the database handle is not\n      ** initialized. If the main database exists, the new sqlite.enc value\n      ** will be overwritten when the schema is next loaded. If it does not\n      ** already exists, it will be created to use the new encoding value.\n      */\n      if( (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){\n        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){\n          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){\n            u8 enc = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;\n            SCHEMA_ENC(db) = enc;\n            sqlite3SetTextEncoding(db, enc);\n            break;\n          }\n        }\n        if( !pEnc->zName ){\n          sqlite3ErrorMsg(pParse, \"unsupported encoding: %s\", zRight);\n        }\n      }\n    }\n  }\n  break;\n#endif /* SQLITE_OMIT_UTF16 */\n\n#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS\n  /*\n  **   PRAGMA [schema.]schema_version\n  **   PRAGMA [schema.]schema_version = <integer>\n  **\n  **   PRAGMA [schema.]user_version\n  **   PRAGMA [schema.]user_version = <integer>\n  **\n  **   PRAGMA [schema.]freelist_count\n  **\n  **   PRAGMA [schema.]data_version\n  **\n  **   PRAGMA [schema.]application_id\n  **   PRAGMA [schema.]application_id = <integer>\n  **\n  ** The pragma's schema_version and user_version are used to set or get\n  ** the value of the schema-version and user-version, respectively. Both\n  ** the schema-version and the user-version are 32-bit signed integers\n  ** stored in the database header.\n  **\n  ** The schema-cookie is usually only manipulated internally by SQLite. It\n  ** is incremented by SQLite whenever the database schema is modified (by\n  ** creating or dropping a table or index). The schema version is used by\n  ** SQLite each time a query is executed to ensure that the internal cache\n  ** of the schema used when compiling the SQL query matches the schema of\n  ** the database against which the compiled query is actually executed.\n  ** Subverting this mechanism by using \"PRAGMA schema_version\" to modify\n  ** the schema-version is potentially dangerous and may lead to program\n  ** crashes or database corruption. Use with caution!\n  **\n  ** The user-version is not used internally by SQLite. It may be used by\n  ** applications for any purpose.\n  */\n  case PragTyp_HEADER_VALUE: {\n    int iCookie = pPragma->iArg;  /* Which cookie to read or write */\n    sqlite3VdbeUsesBtree(v, iDb);\n    if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){\n      /* Write the specified cookie value */\n      static const VdbeOpList setCookie[] = {\n        { OP_Transaction,    0,  1,  0},    /* 0 */\n        { OP_SetCookie,      0,  0,  0},    /* 1 */\n      };\n      VdbeOp *aOp;\n      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));\n      aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);\n      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;\n      aOp[0].p1 = iDb;\n      aOp[1].p1 = iDb;\n      aOp[1].p2 = iCookie;\n      aOp[1].p3 = sqlite3Atoi(zRight);\n    }else{\n      /* Read the specified cookie value */\n      static const VdbeOpList readCookie[] = {\n        { OP_Transaction,     0,  0,  0},    /* 0 */\n        { OP_ReadCookie,      0,  1,  0},    /* 1 */\n        { OP_ResultRow,       1,  1,  0}\n      };\n      VdbeOp *aOp;\n      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));\n      aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);\n      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;\n      aOp[0].p1 = iDb;\n      aOp[1].p1 = iDb;\n      aOp[1].p3 = iCookie;\n      sqlite3VdbeReusable(v);\n    }\n  }\n  break;\n#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */\n\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\n  /*\n  **   PRAGMA compile_options\n  **\n  ** Return the names of all compile-time options used in this build,\n  ** one option per row.\n  */\n  case PragTyp_COMPILE_OPTIONS: {\n    int i = 0;\n    const char *zOpt;\n    pParse->nMem = 1;\n    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){\n      sqlite3VdbeLoadString(v, 1, zOpt);\n      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);\n    }\n    sqlite3VdbeReusable(v);\n  }\n  break;\n#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */\n\n#ifndef SQLITE_OMIT_WAL\n  /*\n  **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate\n  **\n  ** Checkpoint the database.\n  */\n  case PragTyp_WAL_CHECKPOINT: {\n    int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);\n    int eMode = SQLITE_CHECKPOINT_PASSIVE;\n    if( zRight ){\n      if( sqlite3StrICmp(zRight, \"full\")==0 ){\n        eMode = SQLITE_CHECKPOINT_FULL;\n      }else if( sqlite3StrICmp(zRight, \"restart\")==0 ){\n        eMode = SQLITE_CHECKPOINT_RESTART;\n      }else if( sqlite3StrICmp(zRight, \"truncate\")==0 ){\n        eMode = SQLITE_CHECKPOINT_TRUNCATE;\n      }\n    }\n    pParse->nMem = 3;\n    sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);\n    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);\n  }\n  break;\n\n  /*\n  **   PRAGMA wal_autocheckpoint\n  **   PRAGMA wal_autocheckpoint = N\n  **\n  ** Configure a database connection to automatically checkpoint a database\n  ** after accumulating N frames in the log. Or query for the current value\n  ** of N.\n  */\n  case PragTyp_WAL_AUTOCHECKPOINT: {\n    if( zRight ){\n      sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));\n    }\n    returnSingleInt(v, \n       db->xWalCallback==sqlite3WalDefaultHook ? \n           SQLITE_PTR_TO_INT(db->pWalArg) : 0);\n  }\n  break;\n#endif\n\n  /*\n  **  PRAGMA shrink_memory\n  **\n  ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database\n  ** connection on which it is invoked to free up as much memory as it\n  ** can, by calling sqlite3_db_release_memory().\n  */\n  case PragTyp_SHRINK_MEMORY: {\n    sqlite3_db_release_memory(db);\n    break;\n  }\n\n  /*\n  **  PRAGMA optimize\n  **  PRAGMA optimize(MASK)\n  **  PRAGMA schema.optimize\n  **  PRAGMA schema.optimize(MASK)\n  **\n  ** Attempt to optimize the database.  All schemas are optimized in the first\n  ** two forms, and only the specified schema is optimized in the latter two.\n  **\n  ** The details of optimizations performed by this pragma are expected\n  ** to change and improve over time.  Applications should anticipate that\n  ** this pragma will perform new optimizations in future releases.\n  **\n  ** The optional argument is a bitmask of optimizations to perform:\n  **\n  **    0x0001    Debugging mode.  Do not actually perform any optimizations\n  **              but instead return one line of text for each optimization\n  **              that would have been done.  Off by default.\n  **\n  **    0x0002    Run ANALYZE on tables that might benefit.  On by default.\n  **              See below for additional information.\n  **\n  **    0x0004    (Not yet implemented) Record usage and performance \n  **              information from the current session in the\n  **              database file so that it will be available to \"optimize\"\n  **              pragmas run by future database connections.\n  **\n  **    0x0008    (Not yet implemented) Create indexes that might have\n  **              been helpful to recent queries\n  **\n  ** The default MASK is and always shall be 0xfffe.  0xfffe means perform all\n  ** of the optimizations listed above except Debug Mode, including new\n  ** optimizations that have not yet been invented.  If new optimizations are\n  ** ever added that should be off by default, those off-by-default \n  ** optimizations will have bitmasks of 0x10000 or larger.\n  **\n  ** DETERMINATION OF WHEN TO RUN ANALYZE\n  **\n  ** In the current implementation, a table is analyzed if only if all of\n  ** the following are true:\n  **\n  ** (1) MASK bit 0x02 is set.\n  **\n  ** (2) The query planner used sqlite_stat1-style statistics for one or\n  **     more indexes of the table at some point during the lifetime of\n  **     the current connection.\n  **\n  ** (3) One or more indexes of the table are currently unanalyzed OR\n  **     the number of rows in the table has increased by 25 times or more\n  **     since the last time ANALYZE was run.\n  **\n  ** The rules for when tables are analyzed are likely to change in\n  ** future releases.\n  */\n  case PragTyp_OPTIMIZE: {\n    int iDbLast;           /* Loop termination point for the schema loop */\n    int iTabCur;           /* Cursor for a table whose size needs checking */\n    HashElem *k;           /* Loop over tables of a schema */\n    Schema *pSchema;       /* The current schema */\n    Table *pTab;           /* A table in the schema */\n    Index *pIdx;           /* An index of the table */\n    LogEst szThreshold;    /* Size threshold above which reanalysis is needd */\n    char *zSubSql;         /* SQL statement for the OP_SqlExec opcode */\n    u32 opMask;            /* Mask of operations to perform */\n\n    if( zRight ){\n      opMask = (u32)sqlite3Atoi(zRight);\n      if( (opMask & 0x02)==0 ) break;\n    }else{\n      opMask = 0xfffe;\n    }\n    iTabCur = pParse->nTab++;\n    for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){\n      if( iDb==1 ) continue;\n      sqlite3CodeVerifySchema(pParse, iDb);\n      pSchema = db->aDb[iDb].pSchema;\n      for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){\n        pTab = (Table*)sqliteHashData(k);\n\n        /* If table pTab has not been used in a way that would benefit from\n        ** having analysis statistics during the current session, then skip it.\n        ** This also has the effect of skipping virtual tables and views */\n        if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;\n\n        /* Reanalyze if the table is 25 times larger than the last analysis */\n        szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );\n        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n          if( !pIdx->hasStat1 ){\n            szThreshold = 0; /* Always analyze if any index lacks statistics */\n            break;\n          }\n        }\n        if( szThreshold ){\n          sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);\n          sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur, \n                         sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);\n          VdbeCoverage(v);\n        }\n        zSubSql = sqlite3MPrintf(db, \"ANALYZE \\\"%w\\\".\\\"%w\\\"\",\n                                 db->aDb[iDb].zDbSName, pTab->zName);\n        if( opMask & 0x01 ){\n          int r1 = sqlite3GetTempReg(pParse);\n          sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);\n          sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);\n        }else{\n          sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);\n        }\n      }\n    }\n    sqlite3VdbeAddOp0(v, OP_Expire);\n    break;\n  }\n\n  /*\n  **   PRAGMA busy_timeout\n  **   PRAGMA busy_timeout = N\n  **\n  ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value\n  ** if one is set.  If no busy handler or a different busy handler is set\n  ** then 0 is returned.  Setting the busy_timeout to 0 or negative\n  ** disables the timeout.\n  */\n  /*case PragTyp_BUSY_TIMEOUT*/ default: {\n    assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );\n    if( zRight ){\n      sqlite3_busy_timeout(db, sqlite3Atoi(zRight));\n    }\n    returnSingleInt(v, db->busyTimeout);\n    break;\n  }\n\n  /*\n  **   PRAGMA soft_heap_limit\n  **   PRAGMA soft_heap_limit = N\n  **\n  ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the\n  ** sqlite3_soft_heap_limit64() interface with the argument N, if N is\n  ** specified and is a non-negative integer.\n  ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always\n  ** returns the same integer that would be returned by the\n  ** sqlite3_soft_heap_limit64(-1) C-language function.\n  */\n  case PragTyp_SOFT_HEAP_LIMIT: {\n    sqlite3_int64 N;\n    if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){\n      sqlite3_soft_heap_limit64(N);\n    }\n    returnSingleInt(v, sqlite3_soft_heap_limit64(-1));\n    break;\n  }\n\n  /*\n  **   PRAGMA hard_heap_limit\n  **   PRAGMA hard_heap_limit = N\n  **\n  ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap\n  ** limit.  The hard heap limit can be activated or lowered by this\n  ** pragma, but not raised or deactivated.  Only the\n  ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate\n  ** the hard heap limit.  This allows an application to set a heap limit\n  ** constraint that cannot be relaxed by an untrusted SQL script.\n  */\n  case PragTyp_HARD_HEAP_LIMIT: {\n    sqlite3_int64 N;\n    if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){\n      sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1);\n      if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N);\n    }\n    returnSingleInt(v, sqlite3_hard_heap_limit64(-1));\n    break;\n  }\n\n  /*\n  **   PRAGMA threads\n  **   PRAGMA threads = N\n  **\n  ** Configure the maximum number of worker threads.  Return the new\n  ** maximum, which might be less than requested.\n  */\n  case PragTyp_THREADS: {\n    sqlite3_int64 N;\n    if( zRight\n     && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK\n     && N>=0\n    ){\n      sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));\n    }\n    returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));\n    break;\n  }\n\n  /*\n  **   PRAGMA analysis_limit\n  **   PRAGMA analysis_limit = N\n  **\n  ** Configure the maximum number of rows that ANALYZE will examine\n  ** in each index that it looks at.  Return the new limit.\n  */\n  case PragTyp_ANALYSIS_LIMIT: {\n    sqlite3_int64 N;\n    if( zRight\n     && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK\n     && N>=0\n    ){\n      db->nAnalysisLimit = (int)(N&0x7fffffff);\n    }\n    returnSingleInt(v, db->nAnalysisLimit);\n    break;\n  }\n\n#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)\n  /*\n  ** Report the current state of file logs for all databases\n  */\n  case PragTyp_LOCK_STATUS: {\n    static const char *const azLockName[] = {\n      \"unlocked\", \"shared\", \"reserved\", \"pending\", \"exclusive\"\n    };\n    int i;\n    pParse->nMem = 2;\n    for(i=0; i<db->nDb; i++){\n      Btree *pBt;\n      const char *zState = \"unknown\";\n      int j;\n      if( db->aDb[i].zDbSName==0 ) continue;\n      pBt = db->aDb[i].pBt;\n      if( pBt==0 || sqlite3BtreePager(pBt)==0 ){\n        zState = \"closed\";\n      }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, \n                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){\n         zState = azLockName[j];\n      }\n      sqlite3VdbeMultiLoad(v, 1, \"ss\", db->aDb[i].zDbSName, zState);\n    }\n    break;\n  }\n#endif\n\n#if defined(SQLITE_ENABLE_CEROD)\n  case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){\n    if( sqlite3StrNICmp(zRight, \"cerod-\", 6)==0 ){\n      sqlite3_activate_cerod(&zRight[6]);\n    }\n  }\n  break;\n#endif\n\n  } /* End of the PRAGMA switch */\n\n  /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only\n  ** purpose is to execute assert() statements to verify that if the\n  ** PragFlg_NoColumns1 flag is set and the caller specified an argument\n  ** to the PRAGMA, the implementation has not added any OP_ResultRow \n  ** instructions to the VM.  */\n  if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){\n    sqlite3VdbeVerifyNoResultRow(v);\n  }\n\npragma_out:\n  sqlite3DbFree(db, zLeft);\n  sqlite3DbFree(db, zRight);\n}\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/*****************************************************************************\n** Implementation of an eponymous virtual table that runs a pragma.\n**\n*/\ntypedef struct PragmaVtab PragmaVtab;\ntypedef struct PragmaVtabCursor PragmaVtabCursor;\nstruct PragmaVtab {\n  sqlite3_vtab base;        /* Base class.  Must be first */\n  sqlite3 *db;              /* The database connection to which it belongs */\n  const PragmaName *pName;  /* Name of the pragma */\n  u8 nHidden;               /* Number of hidden columns */\n  u8 iHidden;               /* Index of the first hidden column */\n};\nstruct PragmaVtabCursor {\n  sqlite3_vtab_cursor base; /* Base class.  Must be first */\n  sqlite3_stmt *pPragma;    /* The pragma statement to run */\n  sqlite_int64 iRowid;      /* Current rowid */\n  char *azArg[2];           /* Value of the argument and schema */\n};\n\n/* \n** Pragma virtual table module xConnect method.\n*/\nstatic int pragmaVtabConnect(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  const PragmaName *pPragma = (const PragmaName*)pAux;\n  PragmaVtab *pTab = 0;\n  int rc;\n  int i, j;\n  char cSep = '(';\n  StrAccum acc;\n  char zBuf[200];\n\n  UNUSED_PARAMETER(argc);\n  UNUSED_PARAMETER(argv);\n  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);\n  sqlite3_str_appendall(&acc, \"CREATE TABLE x\");\n  for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){\n    sqlite3_str_appendf(&acc, \"%c\\\"%s\\\"\", cSep, pragCName[j]);\n    cSep = ',';\n  }\n  if( i==0 ){\n    sqlite3_str_appendf(&acc, \"(\\\"%s\\\"\", pPragma->zName);\n    i++;\n  }\n  j = 0;\n  if( pPragma->mPragFlg & PragFlg_Result1 ){\n    sqlite3_str_appendall(&acc, \",arg HIDDEN\");\n    j++;\n  }\n  if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){\n    sqlite3_str_appendall(&acc, \",schema HIDDEN\");\n    j++;\n  }\n  sqlite3_str_append(&acc, \")\", 1);\n  sqlite3StrAccumFinish(&acc);\n  assert( strlen(zBuf) < sizeof(zBuf)-1 );\n  rc = sqlite3_declare_vtab(db, zBuf);\n  if( rc==SQLITE_OK ){\n    pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));\n    if( pTab==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      memset(pTab, 0, sizeof(PragmaVtab));\n      pTab->pName = pPragma;\n      pTab->db = db;\n      pTab->iHidden = i;\n      pTab->nHidden = j;\n    }\n  }else{\n    *pzErr = sqlite3_mprintf(\"%s\", sqlite3_errmsg(db));\n  }\n\n  *ppVtab = (sqlite3_vtab*)pTab;\n  return rc;\n}\n\n/* \n** Pragma virtual table module xDisconnect method.\n*/\nstatic int pragmaVtabDisconnect(sqlite3_vtab *pVtab){\n  PragmaVtab *pTab = (PragmaVtab*)pVtab;\n  sqlite3_free(pTab);\n  return SQLITE_OK;\n}\n\n/* Figure out the best index to use to search a pragma virtual table.\n**\n** There are not really any index choices.  But we want to encourage the\n** query planner to give == constraints on as many hidden parameters as\n** possible, and especially on the first hidden parameter.  So return a\n** high cost if hidden parameters are unconstrained.\n*/\nstatic int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){\n  PragmaVtab *pTab = (PragmaVtab*)tab;\n  const struct sqlite3_index_constraint *pConstraint;\n  int i, j;\n  int seen[2];\n\n  pIdxInfo->estimatedCost = (double)1;\n  if( pTab->nHidden==0 ){ return SQLITE_OK; }\n  pConstraint = pIdxInfo->aConstraint;\n  seen[0] = 0;\n  seen[1] = 0;\n  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){\n    if( pConstraint->usable==0 ) continue;\n    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;\n    if( pConstraint->iColumn < pTab->iHidden ) continue;\n    j = pConstraint->iColumn - pTab->iHidden;\n    assert( j < 2 );\n    seen[j] = i+1;\n  }\n  if( seen[0]==0 ){\n    pIdxInfo->estimatedCost = (double)2147483647;\n    pIdxInfo->estimatedRows = 2147483647;\n    return SQLITE_OK;\n  }\n  j = seen[0]-1;\n  pIdxInfo->aConstraintUsage[j].argvIndex = 1;\n  pIdxInfo->aConstraintUsage[j].omit = 1;\n  if( seen[1]==0 ) return SQLITE_OK;\n  pIdxInfo->estimatedCost = (double)20;\n  pIdxInfo->estimatedRows = 20;\n  j = seen[1]-1;\n  pIdxInfo->aConstraintUsage[j].argvIndex = 2;\n  pIdxInfo->aConstraintUsage[j].omit = 1;\n  return SQLITE_OK;\n}\n\n/* Create a new cursor for the pragma virtual table */\nstatic int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){\n  PragmaVtabCursor *pCsr;\n  pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));\n  if( pCsr==0 ) return SQLITE_NOMEM;\n  memset(pCsr, 0, sizeof(PragmaVtabCursor));\n  pCsr->base.pVtab = pVtab;\n  *ppCursor = &pCsr->base;\n  return SQLITE_OK;\n}\n\n/* Clear all content from pragma virtual table cursor. */\nstatic void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){\n  int i;\n  sqlite3_finalize(pCsr->pPragma);\n  pCsr->pPragma = 0;\n  for(i=0; i<ArraySize(pCsr->azArg); i++){\n    sqlite3_free(pCsr->azArg[i]);\n    pCsr->azArg[i] = 0;\n  }\n}\n\n/* Close a pragma virtual table cursor */\nstatic int pragmaVtabClose(sqlite3_vtab_cursor *cur){\n  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;\n  pragmaVtabCursorClear(pCsr);\n  sqlite3_free(pCsr);\n  return SQLITE_OK;\n}\n\n/* Advance the pragma virtual table cursor to the next row */\nstatic int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){\n  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;\n  int rc = SQLITE_OK;\n\n  /* Increment the xRowid value */\n  pCsr->iRowid++;\n  assert( pCsr->pPragma );\n  if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){\n    rc = sqlite3_finalize(pCsr->pPragma);\n    pCsr->pPragma = 0;\n    pragmaVtabCursorClear(pCsr);\n  }\n  return rc;\n}\n\n/* \n** Pragma virtual table module xFilter method.\n*/\nstatic int pragmaVtabFilter(\n  sqlite3_vtab_cursor *pVtabCursor, \n  int idxNum, const char *idxStr,\n  int argc, sqlite3_value **argv\n){\n  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;\n  PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);\n  int rc;\n  int i, j;\n  StrAccum acc;\n  char *zSql;\n\n  UNUSED_PARAMETER(idxNum);\n  UNUSED_PARAMETER(idxStr);\n  pragmaVtabCursorClear(pCsr);\n  j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;\n  for(i=0; i<argc; i++, j++){\n    const char *zText = (const char*)sqlite3_value_text(argv[i]);\n    assert( j<ArraySize(pCsr->azArg) );\n    assert( pCsr->azArg[j]==0 );\n    if( zText ){\n      pCsr->azArg[j] = sqlite3_mprintf(\"%s\", zText);\n      if( pCsr->azArg[j]==0 ){\n        return SQLITE_NOMEM;\n      }\n    }\n  }\n  sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);\n  sqlite3_str_appendall(&acc, \"PRAGMA \");\n  if( pCsr->azArg[1] ){\n    sqlite3_str_appendf(&acc, \"%Q.\", pCsr->azArg[1]);\n  }\n  sqlite3_str_appendall(&acc, pTab->pName->zName);\n  if( pCsr->azArg[0] ){\n    sqlite3_str_appendf(&acc, \"=%Q\", pCsr->azArg[0]);\n  }\n  zSql = sqlite3StrAccumFinish(&acc);\n  if( zSql==0 ) return SQLITE_NOMEM;\n  rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);\n  sqlite3_free(zSql);\n  if( rc!=SQLITE_OK ){\n    pTab->base.zErrMsg = sqlite3_mprintf(\"%s\", sqlite3_errmsg(pTab->db));\n    return rc;\n  }\n  return pragmaVtabNext(pVtabCursor);\n}\n\n/*\n** Pragma virtual table module xEof method.\n*/\nstatic int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){\n  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;\n  return (pCsr->pPragma==0);\n}\n\n/* The xColumn method simply returns the corresponding column from\n** the PRAGMA.  \n*/\nstatic int pragmaVtabColumn(\n  sqlite3_vtab_cursor *pVtabCursor, \n  sqlite3_context *ctx, \n  int i\n){\n  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;\n  PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);\n  if( i<pTab->iHidden ){\n    sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));\n  }else{\n    sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);\n  }\n  return SQLITE_OK;\n}\n\n/* \n** Pragma virtual table module xRowid method.\n*/\nstatic int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){\n  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;\n  *p = pCsr->iRowid;\n  return SQLITE_OK;\n}\n\n/* The pragma virtual table object */\nstatic const sqlite3_module pragmaVtabModule = {\n  0,                           /* iVersion */\n  0,                           /* xCreate - create a table */\n  pragmaVtabConnect,           /* xConnect - connect to an existing table */\n  pragmaVtabBestIndex,         /* xBestIndex - Determine search strategy */\n  pragmaVtabDisconnect,        /* xDisconnect - Disconnect from a table */\n  0,                           /* xDestroy - Drop a table */\n  pragmaVtabOpen,              /* xOpen - open a cursor */\n  pragmaVtabClose,             /* xClose - close a cursor */\n  pragmaVtabFilter,            /* xFilter - configure scan constraints */\n  pragmaVtabNext,              /* xNext - advance a cursor */\n  pragmaVtabEof,               /* xEof */\n  pragmaVtabColumn,            /* xColumn - read data */\n  pragmaVtabRowid,             /* xRowid - read data */\n  0,                           /* xUpdate - write data */\n  0,                           /* xBegin - begin transaction */\n  0,                           /* xSync - sync transaction */\n  0,                           /* xCommit - commit transaction */\n  0,                           /* xRollback - rollback transaction */\n  0,                           /* xFindFunction - function overloading */\n  0,                           /* xRename - rename the table */\n  0,                           /* xSavepoint */\n  0,                           /* xRelease */\n  0,                           /* xRollbackTo */\n  0                            /* xShadowName */\n};\n\n/*\n** Check to see if zTabName is really the name of a pragma.  If it is,\n** then register an eponymous virtual table for that pragma and return\n** a pointer to the Module object for the new virtual table.\n*/\nSQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){\n  const PragmaName *pName;\n  assert( sqlite3_strnicmp(zName, \"pragma_\", 7)==0 );\n  pName = pragmaLocate(zName+7);\n  if( pName==0 ) return 0;\n  if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;\n  assert( sqlite3HashFind(&db->aModule, zName)==0 );\n  return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);\n}\n\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#endif /* SQLITE_OMIT_PRAGMA */\n\n/************** End of pragma.c **********************************************/\n/************** Begin file prepare.c *****************************************/\n/*\n** 2005 May 25\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the implementation of the sqlite3_prepare()\n** interface, and routines that contribute to loading the database schema\n** from disk.\n*/\n/* #include \"sqliteInt.h\" */\n\n/*\n** Fill the InitData structure with an error message that indicates\n** that the database is corrupt.\n*/\nstatic void corruptSchema(\n  InitData *pData,     /* Initialization context */\n  const char *zObj,    /* Object being parsed at the point of error */\n  const char *zExtra   /* Error information */\n){\n  sqlite3 *db = pData->db;\n  if( db->mallocFailed ){\n    pData->rc = SQLITE_NOMEM_BKPT;\n  }else if( pData->pzErrMsg[0]!=0 ){\n    /* A error message has already been generated.  Do not overwrite it */\n  }else if( pData->mInitFlags & INITFLAG_AlterTable ){\n    *pData->pzErrMsg = sqlite3DbStrDup(db, zExtra);\n    pData->rc = SQLITE_ERROR;\n  }else if( db->flags & SQLITE_WriteSchema ){\n    pData->rc = SQLITE_CORRUPT_BKPT;\n  }else{\n    char *z;\n    if( zObj==0 ) zObj = \"?\";\n    z = sqlite3MPrintf(db, \"malformed database schema (%s)\", zObj);\n    if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, \"%z - %s\", z, zExtra);\n    *pData->pzErrMsg = z;\n    pData->rc = SQLITE_CORRUPT_BKPT;\n  }\n}\n\n/*\n** Check to see if any sibling index (another index on the same table)\n** of pIndex has the same root page number, and if it does, return true.\n** This would indicate a corrupt schema.\n*/\nSQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index *pIndex){\n  Index *p;\n  for(p=pIndex->pTable->pIndex; p; p=p->pNext){\n    if( p->tnum==pIndex->tnum && p!=pIndex ) return 1;\n  }\n  return 0;\n}\n\n/* forward declaration */\nstatic int sqlite3Prepare(\n  sqlite3 *db,              /* Database handle. */\n  const char *zSql,         /* UTF-8 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */\n  Vdbe *pReprepare,         /* VM being reprepared */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const char **pzTail       /* OUT: End of parsed string */\n);\n\n\n/*\n** This is the callback routine for the code that initializes the\n** database.  See sqlite3Init() below for additional information.\n** This routine is also called from the OP_ParseSchema opcode of the VDBE.\n**\n** Each callback contains the following information:\n**\n**     argv[0] = type of object: \"table\", \"index\", \"trigger\", or \"view\".\n**     argv[1] = name of thing being created\n**     argv[2] = associated table if an index or trigger\n**     argv[3] = root page number for table or index. 0 for trigger or view.\n**     argv[4] = SQL text for the CREATE statement.\n**\n*/\nSQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){\n  InitData *pData = (InitData*)pInit;\n  sqlite3 *db = pData->db;\n  int iDb = pData->iDb;\n\n  assert( argc==5 );\n  UNUSED_PARAMETER2(NotUsed, argc);\n  assert( sqlite3_mutex_held(db->mutex) );\n  db->mDbFlags |= DBFLAG_EncodingFixed;\n  pData->nInitRow++;\n  if( db->mallocFailed ){\n    corruptSchema(pData, argv[1], 0);\n    return 1;\n  }\n\n  assert( iDb>=0 && iDb<db->nDb );\n  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */\n  if( argv[3]==0 ){\n    corruptSchema(pData, argv[1], 0);\n  }else if( sqlite3_strnicmp(argv[4],\"create \",7)==0 ){\n    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.\n    ** But because db->init.busy is set to 1, no VDBE code is generated\n    ** or executed.  All the parser does is build the internal data\n    ** structures that describe the table, index, or view.\n    */\n    int rc;\n    u8 saved_iDb = db->init.iDb;\n    sqlite3_stmt *pStmt;\n    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */\n\n    assert( db->init.busy );\n    db->init.iDb = iDb;\n    db->init.newTnum = sqlite3Atoi(argv[3]);\n    db->init.orphanTrigger = 0;\n    db->init.azInit = argv;\n    pStmt = 0;\n    TESTONLY(rcp = ) sqlite3Prepare(db, argv[4], -1, 0, 0, &pStmt, 0);\n    rc = db->errCode;\n    assert( (rc&0xFF)==(rcp&0xFF) );\n    db->init.iDb = saved_iDb;\n    /* assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 ); */\n    if( SQLITE_OK!=rc ){\n      if( db->init.orphanTrigger ){\n        assert( iDb==1 );\n      }else{\n        if( rc > pData->rc ) pData->rc = rc;\n        if( rc==SQLITE_NOMEM ){\n          sqlite3OomFault(db);\n        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){\n          corruptSchema(pData, argv[1], sqlite3_errmsg(db));\n        }\n      }\n    }\n    sqlite3_finalize(pStmt);\n  }else if( argv[1]==0 || (argv[4]!=0 && argv[4][0]!=0) ){\n    corruptSchema(pData, argv[1], 0);\n  }else{\n    /* If the SQL column is blank it means this is an index that\n    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE\n    ** constraint for a CREATE TABLE.  The index should have already\n    ** been created when we processed the CREATE TABLE.  All we have\n    ** to do here is record the root page number for that index.\n    */\n    Index *pIndex;\n    pIndex = sqlite3FindIndex(db, argv[1], db->aDb[iDb].zDbSName);\n    if( pIndex==0\n     || sqlite3GetInt32(argv[3],&pIndex->tnum)==0\n     || pIndex->tnum<2\n     || sqlite3IndexHasDuplicateRootPage(pIndex)\n    ){\n      corruptSchema(pData, argv[1], pIndex?\"invalid rootpage\":\"orphan index\");\n    }\n  }\n  return 0;\n}\n\n/*\n** Attempt to read the database schema and initialize internal\n** data structures for a single database file.  The index of the\n** database file is given by iDb.  iDb==0 is used for the main\n** database.  iDb==1 should never be used.  iDb>=2 is used for\n** auxiliary databases.  Return one of the SQLITE_ error codes to\n** indicate success or failure.\n*/\nSQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFlags){\n  int rc;\n  int i;\n#ifndef SQLITE_OMIT_DEPRECATED\n  int size;\n#endif\n  Db *pDb;\n  char const *azArg[6];\n  int meta[5];\n  InitData initData;\n  const char *zMasterName;\n  int openedTransaction = 0;\n  int mask = ((db->mDbFlags & DBFLAG_EncodingFixed) | ~DBFLAG_EncodingFixed);\n\n  assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 );\n  assert( iDb>=0 && iDb<db->nDb );\n  assert( db->aDb[iDb].pSchema );\n  assert( sqlite3_mutex_held(db->mutex) );\n  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );\n\n  db->init.busy = 1;\n\n  /* Construct the in-memory representation schema tables (sqlite_master or\n  ** sqlite_temp_master) by invoking the parser directly.  The appropriate\n  ** table name will be inserted automatically by the parser so we can just\n  ** use the abbreviation \"x\" here.  The parser will also automatically tag\n  ** the schema table as read-only. */\n  azArg[0] = \"table\";\n  azArg[1] = zMasterName = SCHEMA_TABLE(iDb);\n  azArg[2] = azArg[1];\n  azArg[3] = \"1\";\n  azArg[4] = \"CREATE TABLE x(type text,name text,tbl_name text,\"\n                            \"rootpage int,sql text)\";\n  azArg[5] = 0;\n  initData.db = db;\n  initData.iDb = iDb;\n  initData.rc = SQLITE_OK;\n  initData.pzErrMsg = pzErrMsg;\n  initData.mInitFlags = mFlags;\n  initData.nInitRow = 0;\n  sqlite3InitCallback(&initData, 5, (char **)azArg, 0);\n  db->mDbFlags &= mask;\n  if( initData.rc ){\n    rc = initData.rc;\n    goto error_out;\n  }\n\n  /* Create a cursor to hold the database open\n  */\n  pDb = &db->aDb[iDb];\n  if( pDb->pBt==0 ){\n    assert( iDb==1 );\n    DbSetProperty(db, 1, DB_SchemaLoaded);\n    rc = SQLITE_OK;\n    goto error_out;\n  }\n\n  /* If there is not already a read-only (or read-write) transaction opened\n  ** on the b-tree database, open one now. If a transaction is opened, it \n  ** will be closed before this function returns.  */\n  sqlite3BtreeEnter(pDb->pBt);\n  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){\n    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0);\n    if( rc!=SQLITE_OK ){\n      sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));\n      goto initone_error_out;\n    }\n    openedTransaction = 1;\n  }\n\n  /* Get the database meta information.\n  **\n  ** Meta values are as follows:\n  **    meta[0]   Schema cookie.  Changes with each schema change.\n  **    meta[1]   File format of schema layer.\n  **    meta[2]   Size of the page cache.\n  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)\n  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE\n  **    meta[5]   User version\n  **    meta[6]   Incremental vacuum mode\n  **    meta[7]   unused\n  **    meta[8]   unused\n  **    meta[9]   unused\n  **\n  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to\n  ** the possible values of meta[4].\n  */\n  for(i=0; i<ArraySize(meta); i++){\n    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);\n  }\n  if( (db->flags & SQLITE_ResetDatabase)!=0 ){\n    memset(meta, 0, sizeof(meta));\n  }\n  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];\n\n  /* If opening a non-empty database, check the text encoding. For the\n  ** main database, set sqlite3.enc to the encoding of the main database.\n  ** For an attached db, it is an error if the encoding is not the same\n  ** as sqlite3.enc.\n  */\n  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */\n    if( iDb==0 && (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){\n      u8 encoding;\n#ifndef SQLITE_OMIT_UTF16\n      /* If opening the main database, set ENC(db). */\n      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;\n      if( encoding==0 ) encoding = SQLITE_UTF8;\n#else\n      encoding = SQLITE_UTF8;\n#endif\n      sqlite3SetTextEncoding(db, encoding);\n    }else{\n      /* If opening an attached database, the encoding much match ENC(db) */\n      if( (meta[BTREE_TEXT_ENCODING-1] & 3)!=ENC(db) ){\n        sqlite3SetString(pzErrMsg, db, \"attached databases must use the same\"\n            \" text encoding as main database\");\n        rc = SQLITE_ERROR;\n        goto initone_error_out;\n      }\n    }\n  }\n  pDb->pSchema->enc = ENC(db);\n\n  if( pDb->pSchema->cache_size==0 ){\n#ifndef SQLITE_OMIT_DEPRECATED\n    size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);\n    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }\n    pDb->pSchema->cache_size = size;\n#else\n    pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;\n#endif\n    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);\n  }\n\n  /*\n  ** file_format==1    Version 3.0.0.\n  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN\n  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults\n  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants\n  */\n  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];\n  if( pDb->pSchema->file_format==0 ){\n    pDb->pSchema->file_format = 1;\n  }\n  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){\n    sqlite3SetString(pzErrMsg, db, \"unsupported file format\");\n    rc = SQLITE_ERROR;\n    goto initone_error_out;\n  }\n\n  /* Ticket #2804:  When we open a database in the newer file format,\n  ** clear the legacy_file_format pragma flag so that a VACUUM will\n  ** not downgrade the database and thus invalidate any descending\n  ** indices that the user might have created.\n  */\n  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){\n    db->flags &= ~(u64)SQLITE_LegacyFileFmt;\n  }\n\n  /* Read the schema information out of the schema tables\n  */\n  assert( db->init.busy );\n  {\n    char *zSql;\n    zSql = sqlite3MPrintf(db, \n        \"SELECT*FROM\\\"%w\\\".%s ORDER BY rowid\",\n        db->aDb[iDb].zDbSName, zMasterName);\n#ifndef SQLITE_OMIT_AUTHORIZATION\n    {\n      sqlite3_xauth xAuth;\n      xAuth = db->xAuth;\n      db->xAuth = 0;\n#endif\n      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);\n#ifndef SQLITE_OMIT_AUTHORIZATION\n      db->xAuth = xAuth;\n    }\n#endif\n    if( rc==SQLITE_OK ) rc = initData.rc;\n    sqlite3DbFree(db, zSql);\n#ifndef SQLITE_OMIT_ANALYZE\n    if( rc==SQLITE_OK ){\n      sqlite3AnalysisLoad(db, iDb);\n    }\n#endif\n  }\n  if( db->mallocFailed ){\n    rc = SQLITE_NOMEM_BKPT;\n    sqlite3ResetAllSchemasOfConnection(db);\n  }\n  if( rc==SQLITE_OK || (db->flags&SQLITE_NoSchemaError)){\n    /* Black magic: If the SQLITE_NoSchemaError flag is set, then consider\n    ** the schema loaded, even if errors occurred. In this situation the \n    ** current sqlite3_prepare() operation will fail, but the following one\n    ** will attempt to compile the supplied statement against whatever subset\n    ** of the schema was loaded before the error occurred. The primary\n    ** purpose of this is to allow access to the sqlite_master table\n    ** even when its contents have been corrupted.\n    */\n    DbSetProperty(db, iDb, DB_SchemaLoaded);\n    rc = SQLITE_OK;\n  }\n\n  /* Jump here for an error that occurs after successfully allocating\n  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs\n  ** before that point, jump to error_out.\n  */\ninitone_error_out:\n  if( openedTransaction ){\n    sqlite3BtreeCommit(pDb->pBt);\n  }\n  sqlite3BtreeLeave(pDb->pBt);\n\nerror_out:\n  if( rc ){\n    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){\n      sqlite3OomFault(db);\n    }\n    sqlite3ResetOneSchema(db, iDb);\n  }\n  db->init.busy = 0;\n  return rc;\n}\n\n/*\n** Initialize all database files - the main database file, the file\n** used to store temporary tables, and any additional database files\n** created using ATTACH statements.  Return a success code.  If an\n** error occurs, write an error message into *pzErrMsg.\n**\n** After a database is initialized, the DB_SchemaLoaded bit is set\n** bit is set in the flags field of the Db structure. \n*/\nSQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){\n  int i, rc;\n  int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);\n  \n  assert( sqlite3_mutex_held(db->mutex) );\n  assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );\n  assert( db->init.busy==0 );\n  ENC(db) = SCHEMA_ENC(db);\n  assert( db->nDb>0 );\n  /* Do the main schema first */\n  if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){\n    rc = sqlite3InitOne(db, 0, pzErrMsg, 0);\n    if( rc ) return rc;\n  }\n  /* All other schemas after the main schema. The \"temp\" schema must be last */\n  for(i=db->nDb-1; i>0; i--){\n    assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) );\n    if( !DbHasProperty(db, i, DB_SchemaLoaded) ){\n      rc = sqlite3InitOne(db, i, pzErrMsg, 0);\n      if( rc ) return rc;\n    }\n  }\n  if( commit_internal ){\n    sqlite3CommitInternalChanges(db);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** This routine is a no-op if the database schema is already initialized.\n** Otherwise, the schema is loaded. An error code is returned.\n*/\nSQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){\n  int rc = SQLITE_OK;\n  sqlite3 *db = pParse->db;\n  assert( sqlite3_mutex_held(db->mutex) );\n  if( !db->init.busy ){\n    rc = sqlite3Init(db, &pParse->zErrMsg);\n    if( rc!=SQLITE_OK ){\n      pParse->rc = rc;\n      pParse->nErr++;\n    }else if( db->noSharedCache ){\n      db->mDbFlags |= DBFLAG_SchemaKnownOk;\n    }\n  }\n  return rc;\n}\n\n\n/*\n** Check schema cookies in all databases.  If any cookie is out\n** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies\n** make no changes to pParse->rc.\n*/\nstatic void schemaIsValid(Parse *pParse){\n  sqlite3 *db = pParse->db;\n  int iDb;\n  int rc;\n  int cookie;\n\n  assert( pParse->checkSchema );\n  assert( sqlite3_mutex_held(db->mutex) );\n  for(iDb=0; iDb<db->nDb; iDb++){\n    int openedTransaction = 0;         /* True if a transaction is opened */\n    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */\n    if( pBt==0 ) continue;\n\n    /* If there is not already a read-only (or read-write) transaction opened\n    ** on the b-tree database, open one now. If a transaction is opened, it \n    ** will be closed immediately after reading the meta-value. */\n    if( !sqlite3BtreeIsInReadTrans(pBt) ){\n      rc = sqlite3BtreeBeginTrans(pBt, 0, 0);\n      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){\n        sqlite3OomFault(db);\n      }\n      if( rc!=SQLITE_OK ) return;\n      openedTransaction = 1;\n    }\n\n    /* Read the schema cookie from the database. If it does not match the \n    ** value stored as part of the in-memory schema representation,\n    ** set Parse.rc to SQLITE_SCHEMA. */\n    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);\n    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){\n      sqlite3ResetOneSchema(db, iDb);\n      pParse->rc = SQLITE_SCHEMA;\n    }\n\n    /* Close the transaction, if one was opened. */\n    if( openedTransaction ){\n      sqlite3BtreeCommit(pBt);\n    }\n  }\n}\n\n/*\n** Convert a schema pointer into the iDb index that indicates\n** which database file in db->aDb[] the schema refers to.\n**\n** If the same database is attached more than once, the first\n** attached database is returned.\n*/\nSQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){\n  int i = -1000000;\n\n  /* If pSchema is NULL, then return -1000000. This happens when code in \n  ** expr.c is trying to resolve a reference to a transient table (i.e. one\n  ** created by a sub-select). In this case the return value of this \n  ** function should never be used.\n  **\n  ** We return -1000000 instead of the more usual -1 simply because using\n  ** -1000000 as the incorrect index into db->aDb[] is much \n  ** more likely to cause a segfault than -1 (of course there are assert()\n  ** statements too, but it never hurts to play the odds).\n  */\n  assert( sqlite3_mutex_held(db->mutex) );\n  if( pSchema ){\n    for(i=0; 1; i++){\n      assert( i<db->nDb );\n      if( db->aDb[i].pSchema==pSchema ){\n        break;\n      }\n    }\n    assert( i>=0 && i<db->nDb );\n  }\n  return i;\n}\n\n/*\n** Deallocate a single AggInfo object\n*/\nstatic void agginfoFree(sqlite3 *db, AggInfo *p){\n  sqlite3DbFree(db, p->aCol);\n  sqlite3DbFree(db, p->aFunc);\n  sqlite3DbFree(db, p);\n}\n\n/*\n** Free all memory allocations in the pParse object\n*/\nSQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){\n  sqlite3 *db = pParse->db;\n  AggInfo *pThis = pParse->pAggList;\n  while( pThis ){\n    AggInfo *pNext = pThis->pNext;\n    agginfoFree(db, pThis);\n    pThis = pNext;\n  }\n  sqlite3DbFree(db, pParse->aLabel);\n  sqlite3ExprListDelete(db, pParse->pConstExpr);\n  if( db ){\n    assert( db->lookaside.bDisable >= pParse->disableLookaside );\n    db->lookaside.bDisable -= pParse->disableLookaside;\n    db->lookaside.sz = db->lookaside.bDisable ? 0 : db->lookaside.szTrue;\n  }\n  pParse->disableLookaside = 0;\n}\n\n/*\n** Compile the UTF-8 encoded SQL statement zSql into a statement handle.\n*/\nstatic int sqlite3Prepare(\n  sqlite3 *db,              /* Database handle. */\n  const char *zSql,         /* UTF-8 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */\n  Vdbe *pReprepare,         /* VM being reprepared */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const char **pzTail       /* OUT: End of parsed string */\n){\n  char *zErrMsg = 0;        /* Error message */\n  int rc = SQLITE_OK;       /* Result code */\n  int i;                    /* Loop counter */\n  Parse sParse;             /* Parsing context */\n\n  memset(&sParse, 0, PARSE_HDR_SZ);\n  memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);\n  sParse.pReprepare = pReprepare;\n  assert( ppStmt && *ppStmt==0 );\n  /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */\n  assert( sqlite3_mutex_held(db->mutex) );\n\n  /* For a long-term use prepared statement avoid the use of\n  ** lookaside memory.\n  */\n  if( prepFlags & SQLITE_PREPARE_PERSISTENT ){\n    sParse.disableLookaside++;\n    DisableLookaside;\n  }\n  sParse.disableVtab = (prepFlags & SQLITE_PREPARE_NO_VTAB)!=0;\n\n  /* Check to verify that it is possible to get a read lock on all\n  ** database schemas.  The inability to get a read lock indicates that\n  ** some other database connection is holding a write-lock, which in\n  ** turn means that the other connection has made uncommitted changes\n  ** to the schema.\n  **\n  ** Were we to proceed and prepare the statement against the uncommitted\n  ** schema changes and if those schema changes are subsequently rolled\n  ** back and different changes are made in their place, then when this\n  ** prepared statement goes to run the schema cookie would fail to detect\n  ** the schema change.  Disaster would follow.\n  **\n  ** This thread is currently holding mutexes on all Btrees (because\n  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it\n  ** is not possible for another thread to start a new schema change\n  ** while this routine is running.  Hence, we do not need to hold \n  ** locks on the schema, we just need to make sure nobody else is \n  ** holding them.\n  **\n  ** Note that setting READ_UNCOMMITTED overrides most lock detection,\n  ** but it does *not* override schema lock detection, so this all still\n  ** works even if READ_UNCOMMITTED is set.\n  */\n  if( !db->noSharedCache ){\n    for(i=0; i<db->nDb; i++) {\n      Btree *pBt = db->aDb[i].pBt;\n      if( pBt ){\n        assert( sqlite3BtreeHoldsMutex(pBt) );\n        rc = sqlite3BtreeSchemaLocked(pBt);\n        if( rc ){\n          const char *zDb = db->aDb[i].zDbSName;\n          sqlite3ErrorWithMsg(db, rc, \"database schema is locked: %s\", zDb);\n          testcase( db->flags & SQLITE_ReadUncommit );\n          goto end_prepare;\n        }\n      }\n    }\n  }\n\n  sqlite3VtabUnlockList(db);\n\n  sParse.db = db;\n  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){\n    char *zSqlCopy;\n    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];\n    testcase( nBytes==mxLen );\n    testcase( nBytes==mxLen+1 );\n    if( nBytes>mxLen ){\n      sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, \"statement too long\");\n      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);\n      goto end_prepare;\n    }\n    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);\n    if( zSqlCopy ){\n      sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);\n      sParse.zTail = &zSql[sParse.zTail-zSqlCopy];\n      sqlite3DbFree(db, zSqlCopy);\n    }else{\n      sParse.zTail = &zSql[nBytes];\n    }\n  }else{\n    sqlite3RunParser(&sParse, zSql, &zErrMsg);\n  }\n  assert( 0==sParse.nQueryLoop );\n\n  if( sParse.rc==SQLITE_DONE ){\n    sParse.rc = SQLITE_OK;\n  }\n  if( sParse.checkSchema ){\n    schemaIsValid(&sParse);\n  }\n  if( pzTail ){\n    *pzTail = sParse.zTail;\n  }\n\n  if( db->init.busy==0 ){\n    sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);\n  }\n  if( db->mallocFailed ){\n    sParse.rc = SQLITE_NOMEM_BKPT;\n  }\n  rc = sParse.rc;\n  if( rc!=SQLITE_OK ){\n    if( sParse.pVdbe ) sqlite3VdbeFinalize(sParse.pVdbe);\n    assert(!(*ppStmt));\n  }else{\n    *ppStmt = (sqlite3_stmt*)sParse.pVdbe;\n  }\n\n  if( zErrMsg ){\n    sqlite3ErrorWithMsg(db, rc, \"%s\", zErrMsg);\n    sqlite3DbFree(db, zErrMsg);\n  }else{\n    sqlite3Error(db, rc);\n  }\n\n  /* Delete any TriggerPrg structures allocated while parsing this statement. */\n  while( sParse.pTriggerPrg ){\n    TriggerPrg *pT = sParse.pTriggerPrg;\n    sParse.pTriggerPrg = pT->pNext;\n    sqlite3DbFree(db, pT);\n  }\n\nend_prepare:\n\n  sqlite3ParserReset(&sParse);\n  return rc;\n}\nstatic int sqlite3LockAndPrepare(\n  sqlite3 *db,              /* Database handle. */\n  const char *zSql,         /* UTF-8 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */\n  Vdbe *pOld,               /* VM being reprepared */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const char **pzTail       /* OUT: End of parsed string */\n){\n  int rc;\n  int cnt = 0;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;\n#endif\n  *ppStmt = 0;\n  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  sqlite3_mutex_enter(db->mutex);\n  sqlite3BtreeEnterAll(db);\n  do{\n    /* Make multiple attempts to compile the SQL, until it either succeeds\n    ** or encounters a permanent error.  A schema problem after one schema\n    ** reset is considered a permanent error. */\n    rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);\n    assert( rc==SQLITE_OK || *ppStmt==0 );\n  }while( rc==SQLITE_ERROR_RETRY\n       || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );\n  sqlite3BtreeLeaveAll(db);\n  rc = sqlite3ApiExit(db, rc);\n  assert( (rc&db->errMask)==rc );\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n\n/*\n** Rerun the compilation of a statement after a schema change.\n**\n** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,\n** if the statement cannot be recompiled because another connection has\n** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error\n** occurs, return SQLITE_SCHEMA.\n*/\nSQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){\n  int rc;\n  sqlite3_stmt *pNew;\n  const char *zSql;\n  sqlite3 *db;\n  u8 prepFlags;\n\n  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );\n  zSql = sqlite3_sql((sqlite3_stmt *)p);\n  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */\n  db = sqlite3VdbeDb(p);\n  assert( sqlite3_mutex_held(db->mutex) );\n  prepFlags = sqlite3VdbePrepareFlags(p);\n  rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);\n  if( rc ){\n    if( rc==SQLITE_NOMEM ){\n      sqlite3OomFault(db);\n    }\n    assert( pNew==0 );\n    return rc;\n  }else{\n    assert( pNew!=0 );\n  }\n  sqlite3VdbeSwap((Vdbe*)pNew, p);\n  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);\n  sqlite3VdbeResetStepResult((Vdbe*)pNew);\n  sqlite3VdbeFinalize((Vdbe*)pNew);\n  return SQLITE_OK;\n}\n\n\n/*\n** Two versions of the official API.  Legacy and new use.  In the legacy\n** version, the original SQL text is not saved in the prepared statement\n** and so if a schema change occurs, SQLITE_SCHEMA is returned by\n** sqlite3_step().  In the new version, the original SQL text is retained\n** and the statement is automatically recompiled if an schema change\n** occurs.\n*/\nSQLITE_API int sqlite3_prepare(\n  sqlite3 *db,              /* Database handle. */\n  const char *zSql,         /* UTF-8 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const char **pzTail       /* OUT: End of parsed string */\n){\n  int rc;\n  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);\n  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */\n  return rc;\n}\nSQLITE_API int sqlite3_prepare_v2(\n  sqlite3 *db,              /* Database handle. */\n  const char *zSql,         /* UTF-8 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const char **pzTail       /* OUT: End of parsed string */\n){\n  int rc;\n  /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works\n  ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags\n  ** parameter.\n  **\n  ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */\n  rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,\n                             ppStmt,pzTail);\n  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );\n  return rc;\n}\nSQLITE_API int sqlite3_prepare_v3(\n  sqlite3 *db,              /* Database handle. */\n  const char *zSql,         /* UTF-8 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const char **pzTail       /* OUT: End of parsed string */\n){\n  int rc;\n  /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from\n  ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,\n  ** which is a bit array consisting of zero or more of the\n  ** SQLITE_PREPARE_* flags.\n  **\n  ** Proof by comparison to the implementation of sqlite3_prepare_v2()\n  ** directly above. */\n  rc = sqlite3LockAndPrepare(db,zSql,nBytes,\n                 SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),\n                 0,ppStmt,pzTail);\n  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );\n  return rc;\n}\n\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** Compile the UTF-16 encoded SQL statement zSql into a statement handle.\n*/\nstatic int sqlite3Prepare16(\n  sqlite3 *db,              /* Database handle. */ \n  const void *zSql,         /* UTF-16 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const void **pzTail       /* OUT: End of parsed string */\n){\n  /* This function currently works by first transforming the UTF-16\n  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The\n  ** tricky bit is figuring out the pointer to return in *pzTail.\n  */\n  char *zSql8;\n  const char *zTail8 = 0;\n  int rc = SQLITE_OK;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;\n#endif\n  *ppStmt = 0;\n  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  if( nBytes>=0 ){\n    int sz;\n    const char *z = (const char*)zSql;\n    for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}\n    nBytes = sz;\n  }\n  sqlite3_mutex_enter(db->mutex);\n  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);\n  if( zSql8 ){\n    rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);\n  }\n\n  if( zTail8 && pzTail ){\n    /* If sqlite3_prepare returns a tail pointer, we calculate the\n    ** equivalent pointer into the UTF-16 string by counting the unicode\n    ** characters between zSql8 and zTail8, and then returning a pointer\n    ** the same number of characters into the UTF-16 string.\n    */\n    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));\n    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);\n  }\n  sqlite3DbFree(db, zSql8); \n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** Two versions of the official API.  Legacy and new use.  In the legacy\n** version, the original SQL text is not saved in the prepared statement\n** and so if a schema change occurs, SQLITE_SCHEMA is returned by\n** sqlite3_step().  In the new version, the original SQL text is retained\n** and the statement is automatically recompiled if an schema change\n** occurs.\n*/\nSQLITE_API int sqlite3_prepare16(\n  sqlite3 *db,              /* Database handle. */ \n  const void *zSql,         /* UTF-16 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const void **pzTail       /* OUT: End of parsed string */\n){\n  int rc;\n  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);\n  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */\n  return rc;\n}\nSQLITE_API int sqlite3_prepare16_v2(\n  sqlite3 *db,              /* Database handle. */ \n  const void *zSql,         /* UTF-16 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const void **pzTail       /* OUT: End of parsed string */\n){\n  int rc;\n  rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);\n  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */\n  return rc;\n}\nSQLITE_API int sqlite3_prepare16_v3(\n  sqlite3 *db,              /* Database handle. */ \n  const void *zSql,         /* UTF-16 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const void **pzTail       /* OUT: End of parsed string */\n){\n  int rc;\n  rc = sqlite3Prepare16(db,zSql,nBytes,\n         SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),\n         ppStmt,pzTail);\n  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */\n  return rc;\n}\n\n#endif /* SQLITE_OMIT_UTF16 */\n\n/************** End of prepare.c *********************************************/\n/************** Begin file select.c ******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains C code routines that are called by the parser\n** to handle SELECT statements in SQLite.\n*/\n/* #include \"sqliteInt.h\" */\n\n/*\n** Trace output macros\n*/\n#if SELECTTRACE_ENABLED\n/***/ int sqlite3SelectTrace = 0;\n# define SELECTTRACE(K,P,S,X)  \\\n  if(sqlite3SelectTrace&(K))   \\\n    sqlite3DebugPrintf(\"%u/%d/%p: \",(S)->selId,(P)->addrExplain,(S)),\\\n    sqlite3DebugPrintf X\n#else\n# define SELECTTRACE(K,P,S,X)\n#endif\n\n\n/*\n** An instance of the following object is used to record information about\n** how to process the DISTINCT keyword, to simplify passing that information\n** into the selectInnerLoop() routine.\n*/\ntypedef struct DistinctCtx DistinctCtx;\nstruct DistinctCtx {\n  u8 isTnct;      /* True if the DISTINCT keyword is present */\n  u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */\n  int tabTnct;    /* Ephemeral table used for DISTINCT processing */\n  int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */\n};\n\n/*\n** An instance of the following object is used to record information about\n** the ORDER BY (or GROUP BY) clause of query is being coded.\n**\n** The aDefer[] array is used by the sorter-references optimization. For\n** example, assuming there is no index that can be used for the ORDER BY,\n** for the query:\n**\n**     SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10;\n**\n** it may be more efficient to add just the \"a\" values to the sorter, and\n** retrieve the associated \"bigblob\" values directly from table t1 as the\n** 10 smallest \"a\" values are extracted from the sorter.\n**\n** When the sorter-reference optimization is used, there is one entry in the\n** aDefer[] array for each database table that may be read as values are\n** extracted from the sorter.\n*/\ntypedef struct SortCtx SortCtx;\nstruct SortCtx {\n  ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */\n  int nOBSat;           /* Number of ORDER BY terms satisfied by indices */\n  int iECursor;         /* Cursor number for the sorter */\n  int regReturn;        /* Register holding block-output return address */\n  int labelBkOut;       /* Start label for the block-output subroutine */\n  int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */\n  int labelDone;        /* Jump here when done, ex: LIMIT reached */\n  int labelOBLopt;      /* Jump here when sorter is full */\n  u8 sortFlags;         /* Zero or more SORTFLAG_* bits */\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n  u8 nDefer;            /* Number of valid entries in aDefer[] */\n  struct DeferredCsr {\n    Table *pTab;        /* Table definition */\n    int iCsr;           /* Cursor number for table */\n    int nKey;           /* Number of PK columns for table pTab (>=1) */\n  } aDefer[4];\n#endif\n  struct RowLoadInfo *pDeferredRowLoad;  /* Deferred row loading info or NULL */\n};\n#define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */\n\n/*\n** Delete all the content of a Select structure.  Deallocate the structure\n** itself depending on the value of bFree\n**\n** If bFree==1, call sqlite3DbFree() on the p object.\n** If bFree==0, Leave the first Select object unfreed\n*/\nstatic void clearSelect(sqlite3 *db, Select *p, int bFree){\n  while( p ){\n    Select *pPrior = p->pPrior;\n    sqlite3ExprListDelete(db, p->pEList);\n    sqlite3SrcListDelete(db, p->pSrc);\n    sqlite3ExprDelete(db, p->pWhere);\n    sqlite3ExprListDelete(db, p->pGroupBy);\n    sqlite3ExprDelete(db, p->pHaving);\n    sqlite3ExprListDelete(db, p->pOrderBy);\n    sqlite3ExprDelete(db, p->pLimit);\n#ifndef SQLITE_OMIT_WINDOWFUNC\n    if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){\n      sqlite3WindowListDelete(db, p->pWinDefn);\n    }\n#endif\n    if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);\n    if( bFree ) sqlite3DbFreeNN(db, p);\n    p = pPrior;\n    bFree = 1;\n  }\n}\n\n/*\n** Initialize a SelectDest structure.\n*/\nSQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){\n  pDest->eDest = (u8)eDest;\n  pDest->iSDParm = iParm;\n  pDest->zAffSdst = 0;\n  pDest->iSdst = 0;\n  pDest->nSdst = 0;\n}\n\n\n/*\n** Allocate a new Select structure and return a pointer to that\n** structure.\n*/\nSQLITE_PRIVATE Select *sqlite3SelectNew(\n  Parse *pParse,        /* Parsing context */\n  ExprList *pEList,     /* which columns to include in the result */\n  SrcList *pSrc,        /* the FROM clause -- which tables to scan */\n  Expr *pWhere,         /* the WHERE clause */\n  ExprList *pGroupBy,   /* the GROUP BY clause */\n  Expr *pHaving,        /* the HAVING clause */\n  ExprList *pOrderBy,   /* the ORDER BY clause */\n  u32 selFlags,         /* Flag parameters, such as SF_Distinct */\n  Expr *pLimit          /* LIMIT value.  NULL means not used */\n){\n  Select *pNew;\n  Select standin;\n  pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );\n  if( pNew==0 ){\n    assert( pParse->db->mallocFailed );\n    pNew = &standin;\n  }\n  if( pEList==0 ){\n    pEList = sqlite3ExprListAppend(pParse, 0,\n                                   sqlite3Expr(pParse->db,TK_ASTERISK,0));\n  }\n  pNew->pEList = pEList;\n  pNew->op = TK_SELECT;\n  pNew->selFlags = selFlags;\n  pNew->iLimit = 0;\n  pNew->iOffset = 0;\n  pNew->selId = ++pParse->nSelect;\n  pNew->addrOpenEphm[0] = -1;\n  pNew->addrOpenEphm[1] = -1;\n  pNew->nSelectRow = 0;\n  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));\n  pNew->pSrc = pSrc;\n  pNew->pWhere = pWhere;\n  pNew->pGroupBy = pGroupBy;\n  pNew->pHaving = pHaving;\n  pNew->pOrderBy = pOrderBy;\n  pNew->pPrior = 0;\n  pNew->pNext = 0;\n  pNew->pLimit = pLimit;\n  pNew->pWith = 0;\n#ifndef SQLITE_OMIT_WINDOWFUNC\n  pNew->pWin = 0;\n  pNew->pWinDefn = 0;\n#endif\n  if( pParse->db->mallocFailed ) {\n    clearSelect(pParse->db, pNew, pNew!=&standin);\n    pNew = 0;\n  }else{\n    assert( pNew->pSrc!=0 || pParse->nErr>0 );\n  }\n  assert( pNew!=&standin );\n  return pNew;\n}\n\n\n/*\n** Delete the given Select structure and all of its substructures.\n*/\nSQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){\n  if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);\n}\n\n/*\n** Delete all the substructure for p, but keep p allocated.  Redefine\n** p to be a single SELECT where every column of the result set has a\n** value of NULL.\n*/\nSQLITE_PRIVATE void sqlite3SelectReset(Parse *pParse, Select *p){\n  if( ALWAYS(p) ){\n    clearSelect(pParse->db, p, 0);\n    memset(&p->iLimit, 0, sizeof(Select) - offsetof(Select,iLimit));\n    p->pEList = sqlite3ExprListAppend(pParse, 0,\n                     sqlite3ExprAlloc(pParse->db,TK_NULL,0,0));\n    p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(SrcList));\n  }\n}\n\n/*\n** Return a pointer to the right-most SELECT statement in a compound.\n*/\nstatic Select *findRightmost(Select *p){\n  while( p->pNext ) p = p->pNext;\n  return p;\n}\n\n/*\n** Given 1 to 3 identifiers preceding the JOIN keyword, determine the\n** type of join.  Return an integer constant that expresses that type\n** in terms of the following bit values:\n**\n**     JT_INNER\n**     JT_CROSS\n**     JT_OUTER\n**     JT_NATURAL\n**     JT_LEFT\n**     JT_RIGHT\n**\n** A full outer join is the combination of JT_LEFT and JT_RIGHT.\n**\n** If an illegal or unsupported join type is seen, then still return\n** a join type, but put an error in the pParse structure.\n*/\nSQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){\n  int jointype = 0;\n  Token *apAll[3];\n  Token *p;\n                             /*   0123456789 123456789 123456789 123 */\n  static const char zKeyText[] = \"naturaleftouterightfullinnercross\";\n  static const struct {\n    u8 i;        /* Beginning of keyword text in zKeyText[] */\n    u8 nChar;    /* Length of the keyword in characters */\n    u8 code;     /* Join type mask */\n  } aKeyword[] = {\n    /* natural */ { 0,  7, JT_NATURAL                },\n    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },\n    /* outer   */ { 10, 5, JT_OUTER                  },\n    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },\n    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },\n    /* inner   */ { 23, 5, JT_INNER                  },\n    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },\n  };\n  int i, j;\n  apAll[0] = pA;\n  apAll[1] = pB;\n  apAll[2] = pC;\n  for(i=0; i<3 && apAll[i]; i++){\n    p = apAll[i];\n    for(j=0; j<ArraySize(aKeyword); j++){\n      if( p->n==aKeyword[j].nChar \n          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){\n        jointype |= aKeyword[j].code;\n        break;\n      }\n    }\n    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );\n    if( j>=ArraySize(aKeyword) ){\n      jointype |= JT_ERROR;\n      break;\n    }\n  }\n  if(\n     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||\n     (jointype & JT_ERROR)!=0\n  ){\n    const char *zSp = \" \";\n    assert( pB!=0 );\n    if( pC==0 ){ zSp++; }\n    sqlite3ErrorMsg(pParse, \"unknown or unsupported join type: \"\n       \"%T %T%s%T\", pA, pB, zSp, pC);\n    jointype = JT_INNER;\n  }else if( (jointype & JT_OUTER)!=0 \n         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){\n    sqlite3ErrorMsg(pParse, \n      \"RIGHT and FULL OUTER JOINs are not currently supported\");\n    jointype = JT_INNER;\n  }\n  return jointype;\n}\n\n/*\n** Return the index of a column in a table.  Return -1 if the column\n** is not contained in the table.\n*/\nstatic int columnIndex(Table *pTab, const char *zCol){\n  int i;\n  for(i=0; i<pTab->nCol; i++){\n    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;\n  }\n  return -1;\n}\n\n/*\n** Search the first N tables in pSrc, from left to right, looking for a\n** table that has a column named zCol.  \n**\n** When found, set *piTab and *piCol to the table index and column index\n** of the matching column and return TRUE.\n**\n** If not found, return FALSE.\n*/\nstatic int tableAndColumnIndex(\n  SrcList *pSrc,       /* Array of tables to search */\n  int N,               /* Number of tables in pSrc->a[] to search */\n  const char *zCol,    /* Name of the column we are looking for */\n  int *piTab,          /* Write index of pSrc->a[] here */\n  int *piCol,          /* Write index of pSrc->a[*piTab].pTab->aCol[] here */\n  int bIgnoreHidden    /* True to ignore hidden columns */\n){\n  int i;               /* For looping over tables in pSrc */\n  int iCol;            /* Index of column matching zCol */\n\n  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */\n  for(i=0; i<N; i++){\n    iCol = columnIndex(pSrc->a[i].pTab, zCol);\n    if( iCol>=0 \n     && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pTab->aCol[iCol])==0)\n    ){\n      if( piTab ){\n        *piTab = i;\n        *piCol = iCol;\n      }\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/*\n** This function is used to add terms implied by JOIN syntax to the\n** WHERE clause expression of a SELECT statement. The new term, which\n** is ANDed with the existing WHERE clause, is of the form:\n**\n**    (tab1.col1 = tab2.col2)\n**\n** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the \n** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is\n** column iColRight of tab2.\n*/\nstatic void addWhereTerm(\n  Parse *pParse,                  /* Parsing context */\n  SrcList *pSrc,                  /* List of tables in FROM clause */\n  int iLeft,                      /* Index of first table to join in pSrc */\n  int iColLeft,                   /* Index of column in first table */\n  int iRight,                     /* Index of second table in pSrc */\n  int iColRight,                  /* Index of column in second table */\n  int isOuterJoin,                /* True if this is an OUTER join */\n  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */\n){\n  sqlite3 *db = pParse->db;\n  Expr *pE1;\n  Expr *pE2;\n  Expr *pEq;\n\n  assert( iLeft<iRight );\n  assert( pSrc->nSrc>iRight );\n  assert( pSrc->a[iLeft].pTab );\n  assert( pSrc->a[iRight].pTab );\n\n  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);\n  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);\n\n  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);\n  if( pEq && isOuterJoin ){\n    ExprSetProperty(pEq, EP_FromJoin);\n    assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );\n    ExprSetVVAProperty(pEq, EP_NoReduce);\n    pEq->iRightJoinTable = (i16)pE2->iTable;\n  }\n  *ppWhere = sqlite3ExprAnd(pParse, *ppWhere, pEq);\n}\n\n/*\n** Set the EP_FromJoin property on all terms of the given expression.\n** And set the Expr.iRightJoinTable to iTable for every term in the\n** expression.\n**\n** The EP_FromJoin property is used on terms of an expression to tell\n** the LEFT OUTER JOIN processing logic that this term is part of the\n** join restriction specified in the ON or USING clause and not a part\n** of the more general WHERE clause.  These terms are moved over to the\n** WHERE clause during join processing but we need to remember that they\n** originated in the ON or USING clause.\n**\n** The Expr.iRightJoinTable tells the WHERE clause processing that the\n** expression depends on table iRightJoinTable even if that table is not\n** explicitly mentioned in the expression.  That information is needed\n** for cases like this:\n**\n**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5\n**\n** The where clause needs to defer the handling of the t1.x=5\n** term until after the t2 loop of the join.  In that way, a\n** NULL t2 row will be inserted whenever t1.x!=5.  If we do not\n** defer the handling of t1.x=5, it will be processed immediately\n** after the t1 loop and rows with t1.x!=5 will never appear in\n** the output, which is incorrect.\n*/\nSQLITE_PRIVATE void sqlite3SetJoinExpr(Expr *p, int iTable){\n  while( p ){\n    ExprSetProperty(p, EP_FromJoin);\n    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );\n    ExprSetVVAProperty(p, EP_NoReduce);\n    p->iRightJoinTable = (i16)iTable;\n    if( p->op==TK_FUNCTION && p->x.pList ){\n      int i;\n      for(i=0; i<p->x.pList->nExpr; i++){\n        sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable);\n      }\n    }\n    sqlite3SetJoinExpr(p->pLeft, iTable);\n    p = p->pRight;\n  } \n}\n\n/* Undo the work of sqlite3SetJoinExpr(). In the expression p, convert every\n** term that is marked with EP_FromJoin and iRightJoinTable==iTable into\n** an ordinary term that omits the EP_FromJoin mark.\n**\n** This happens when a LEFT JOIN is simplified into an ordinary JOIN.\n*/\nstatic void unsetJoinExpr(Expr *p, int iTable){\n  while( p ){\n    if( ExprHasProperty(p, EP_FromJoin)\n     && (iTable<0 || p->iRightJoinTable==iTable) ){\n      ExprClearProperty(p, EP_FromJoin);\n    }\n    if( p->op==TK_FUNCTION && p->x.pList ){\n      int i;\n      for(i=0; i<p->x.pList->nExpr; i++){\n        unsetJoinExpr(p->x.pList->a[i].pExpr, iTable);\n      }\n    }\n    unsetJoinExpr(p->pLeft, iTable);\n    p = p->pRight;\n  } \n}\n\n/*\n** This routine processes the join information for a SELECT statement.\n** ON and USING clauses are converted into extra terms of the WHERE clause.\n** NATURAL joins also create extra WHERE clause terms.\n**\n** The terms of a FROM clause are contained in the Select.pSrc structure.\n** The left most table is the first entry in Select.pSrc.  The right-most\n** table is the last entry.  The join operator is held in the entry to\n** the left.  Thus entry 0 contains the join operator for the join between\n** entries 0 and 1.  Any ON or USING clauses associated with the join are\n** also attached to the left entry.\n**\n** This routine returns the number of errors encountered.\n*/\nstatic int sqliteProcessJoin(Parse *pParse, Select *p){\n  SrcList *pSrc;                  /* All tables in the FROM clause */\n  int i, j;                       /* Loop counters */\n  struct SrcList_item *pLeft;     /* Left table being joined */\n  struct SrcList_item *pRight;    /* Right table being joined */\n\n  pSrc = p->pSrc;\n  pLeft = &pSrc->a[0];\n  pRight = &pLeft[1];\n  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){\n    Table *pRightTab = pRight->pTab;\n    int isOuter;\n\n    if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;\n    isOuter = (pRight->fg.jointype & JT_OUTER)!=0;\n\n    /* When the NATURAL keyword is present, add WHERE clause terms for\n    ** every column that the two tables have in common.\n    */\n    if( pRight->fg.jointype & JT_NATURAL ){\n      if( pRight->pOn || pRight->pUsing ){\n        sqlite3ErrorMsg(pParse, \"a NATURAL join may not have \"\n           \"an ON or USING clause\", 0);\n        return 1;\n      }\n      for(j=0; j<pRightTab->nCol; j++){\n        char *zName;   /* Name of column in the right table */\n        int iLeft;     /* Matching left table */\n        int iLeftCol;  /* Matching column in the left table */\n\n        if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue;\n        zName = pRightTab->aCol[j].zName;\n        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 1) ){\n          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,\n                isOuter, &p->pWhere);\n        }\n      }\n    }\n\n    /* Disallow both ON and USING clauses in the same join\n    */\n    if( pRight->pOn && pRight->pUsing ){\n      sqlite3ErrorMsg(pParse, \"cannot have both ON and USING \"\n        \"clauses in the same join\");\n      return 1;\n    }\n\n    /* Add the ON clause to the end of the WHERE clause, connected by\n    ** an AND operator.\n    */\n    if( pRight->pOn ){\n      if( isOuter ) sqlite3SetJoinExpr(pRight->pOn, pRight->iCursor);\n      p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->pOn);\n      pRight->pOn = 0;\n    }\n\n    /* Create extra terms on the WHERE clause for each column named\n    ** in the USING clause.  Example: If the two tables to be joined are \n    ** A and B and the USING clause names X, Y, and Z, then add this\n    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z\n    ** Report an error if any column mentioned in the USING clause is\n    ** not contained in both tables to be joined.\n    */\n    if( pRight->pUsing ){\n      IdList *pList = pRight->pUsing;\n      for(j=0; j<pList->nId; j++){\n        char *zName;     /* Name of the term in the USING clause */\n        int iLeft;       /* Table on the left with matching column name */\n        int iLeftCol;    /* Column number of matching column on the left */\n        int iRightCol;   /* Column number of matching column on the right */\n\n        zName = pList->a[j].zName;\n        iRightCol = columnIndex(pRightTab, zName);\n        if( iRightCol<0\n         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 0)\n        ){\n          sqlite3ErrorMsg(pParse, \"cannot join using column %s - column \"\n            \"not present in both tables\", zName);\n          return 1;\n        }\n        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,\n                     isOuter, &p->pWhere);\n      }\n    }\n  }\n  return 0;\n}\n\n/*\n** An instance of this object holds information (beyond pParse and pSelect)\n** needed to load the next result row that is to be added to the sorter.\n*/\ntypedef struct RowLoadInfo RowLoadInfo;\nstruct RowLoadInfo {\n  int regResult;               /* Store results in array of registers here */\n  u8 ecelFlags;                /* Flag argument to ExprCodeExprList() */\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n  ExprList *pExtra;            /* Extra columns needed by sorter refs */\n  int regExtraResult;          /* Where to load the extra columns */\n#endif\n};\n\n/*\n** This routine does the work of loading query data into an array of\n** registers so that it can be added to the sorter.\n*/\nstatic void innerLoopLoadRow(\n  Parse *pParse,             /* Statement under construction */\n  Select *pSelect,           /* The query being coded */\n  RowLoadInfo *pInfo         /* Info needed to complete the row load */\n){\n  sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,\n                          0, pInfo->ecelFlags);\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n  if( pInfo->pExtra ){\n    sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);\n    sqlite3ExprListDelete(pParse->db, pInfo->pExtra);\n  }\n#endif\n}\n\n/*\n** Code the OP_MakeRecord instruction that generates the entry to be\n** added into the sorter.\n**\n** Return the register in which the result is stored.\n*/\nstatic int makeSorterRecord(\n  Parse *pParse,\n  SortCtx *pSort,\n  Select *pSelect,\n  int regBase,\n  int nBase\n){\n  int nOBSat = pSort->nOBSat;\n  Vdbe *v = pParse->pVdbe;\n  int regOut = ++pParse->nMem;\n  if( pSort->pDeferredRowLoad ){\n    innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);\n  }\n  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);\n  return regOut;\n}\n\n/*\n** Generate code that will push the record in registers regData\n** through regData+nData-1 onto the sorter.\n*/\nstatic void pushOntoSorter(\n  Parse *pParse,         /* Parser context */\n  SortCtx *pSort,        /* Information about the ORDER BY clause */\n  Select *pSelect,       /* The whole SELECT statement */\n  int regData,           /* First register holding data to be sorted */\n  int regOrigData,       /* First register holding data before packing */\n  int nData,             /* Number of elements in the regData data array */\n  int nPrefixReg         /* No. of reg prior to regData available for use */\n){\n  Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */\n  int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);\n  int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */\n  int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */\n  int regBase;                                     /* Regs for sorter record */\n  int regRecord = 0;                               /* Assembled sorter record */\n  int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */\n  int op;                            /* Opcode to add sorter record to sorter */\n  int iLimit;                        /* LIMIT counter */\n  int iSkip = 0;                     /* End of the sorter insert loop */\n\n  assert( bSeq==0 || bSeq==1 );\n\n  /* Three cases:\n  **   (1) The data to be sorted has already been packed into a Record\n  **       by a prior OP_MakeRecord.  In this case nData==1 and regData\n  **       will be completely unrelated to regOrigData.\n  **   (2) All output columns are included in the sort record.  In that\n  **       case regData==regOrigData.\n  **   (3) Some output columns are omitted from the sort record due to\n  **       the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the\n  **       SQLITE_ECEL_OMITREF optimization, or due to the \n  **       SortCtx.pDeferredRowLoad optimiation.  In any of these cases\n  **       regOrigData is 0 to prevent this routine from trying to copy\n  **       values that might not yet exist.\n  */\n  assert( nData==1 || regData==regOrigData || regOrigData==0 );\n\n  if( nPrefixReg ){\n    assert( nPrefixReg==nExpr+bSeq );\n    regBase = regData - nPrefixReg;\n  }else{\n    regBase = pParse->nMem + 1;\n    pParse->nMem += nBase;\n  }\n  assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );\n  iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;\n  pSort->labelDone = sqlite3VdbeMakeLabel(pParse);\n  sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,\n                          SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));\n  if( bSeq ){\n    sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);\n  }\n  if( nPrefixReg==0 && nData>0 ){\n    sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);\n  }\n  if( nOBSat>0 ){\n    int regPrevKey;   /* The first nOBSat columns of the previous row */\n    int addrFirst;    /* Address of the OP_IfNot opcode */\n    int addrJmp;      /* Address of the OP_Jump opcode */\n    VdbeOp *pOp;      /* Opcode that opens the sorter */\n    int nKey;         /* Number of sorting key columns, including OP_Sequence */\n    KeyInfo *pKI;     /* Original KeyInfo on the sorter table */\n\n    regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);\n    regPrevKey = pParse->nMem+1;\n    pParse->nMem += pSort->nOBSat;\n    nKey = nExpr - pSort->nOBSat + bSeq;\n    if( bSeq ){\n      addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); \n    }else{\n      addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);\n    }\n    VdbeCoverage(v);\n    sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);\n    pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);\n    if( pParse->db->mallocFailed ) return;\n    pOp->p2 = nKey + nData;\n    pKI = pOp->p4.pKeyInfo;\n    memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */\n    sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);\n    testcase( pKI->nAllField > pKI->nKeyField+2 );\n    pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,\n                                           pKI->nAllField-pKI->nKeyField-1);\n    pOp = 0; /* Ensure pOp not used after sqltie3VdbeAddOp3() */\n    addrJmp = sqlite3VdbeCurrentAddr(v);\n    sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);\n    pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);\n    pSort->regReturn = ++pParse->nMem;\n    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);\n    sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);\n    if( iLimit ){\n      sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);\n      VdbeCoverage(v);\n    }\n    sqlite3VdbeJumpHere(v, addrFirst);\n    sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);\n    sqlite3VdbeJumpHere(v, addrJmp);\n  }\n  if( iLimit ){\n    /* At this point the values for the new sorter entry are stored\n    ** in an array of registers. They need to be composed into a record\n    ** and inserted into the sorter if either (a) there are currently\n    ** less than LIMIT+OFFSET items or (b) the new record is smaller than \n    ** the largest record currently in the sorter. If (b) is true and there\n    ** are already LIMIT+OFFSET items in the sorter, delete the largest\n    ** entry before inserting the new one. This way there are never more \n    ** than LIMIT+OFFSET items in the sorter.\n    **\n    ** If the new record does not need to be inserted into the sorter,\n    ** jump to the next iteration of the loop. If the pSort->labelOBLopt\n    ** value is not zero, then it is a label of where to jump.  Otherwise,\n    ** just bypass the row insert logic.  See the header comment on the\n    ** sqlite3WhereOrderByLimitOptLabel() function for additional info.\n    */\n    int iCsr = pSort->iECursor;\n    sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);\n    VdbeCoverage(v);\n    sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);\n    iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,\n                                 iCsr, 0, regBase+nOBSat, nExpr-nOBSat);\n    VdbeCoverage(v);\n    sqlite3VdbeAddOp1(v, OP_Delete, iCsr);\n  }\n  if( regRecord==0 ){\n    regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);\n  }\n  if( pSort->sortFlags & SORTFLAG_UseSorter ){\n    op = OP_SorterInsert;\n  }else{\n    op = OP_IdxInsert;\n  }\n  sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,\n                       regBase+nOBSat, nBase-nOBSat);\n  if( iSkip ){\n    sqlite3VdbeChangeP2(v, iSkip,\n         pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));\n  }\n}\n\n/*\n** Add code to implement the OFFSET\n*/\nstatic void codeOffset(\n  Vdbe *v,          /* Generate code into this VM */\n  int iOffset,      /* Register holding the offset counter */\n  int iContinue     /* Jump here to skip the current record */\n){\n  if( iOffset>0 ){\n    sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);\n    VdbeComment((v, \"OFFSET\"));\n  }\n}\n\n/*\n** Add code that will check to make sure the N registers starting at iMem\n** form a distinct entry.  iTab is a sorting index that holds previously\n** seen combinations of the N values.  A new entry is made in iTab\n** if the current N values are new.\n**\n** A jump to addrRepeat is made and the N+1 values are popped from the\n** stack if the top N elements are not distinct.\n*/\nstatic void codeDistinct(\n  Parse *pParse,     /* Parsing and code generating context */\n  int iTab,          /* A sorting index used to test for distinctness */\n  int addrRepeat,    /* Jump to here if not distinct */\n  int N,             /* Number of elements */\n  int iMem           /* First element */\n){\n  Vdbe *v;\n  int r1;\n\n  v = pParse->pVdbe;\n  r1 = sqlite3GetTempReg(pParse);\n  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);\n  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);\n  sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);\n  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);\n  sqlite3ReleaseTempReg(pParse, r1);\n}\n\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n/*\n** This function is called as part of inner-loop generation for a SELECT\n** statement with an ORDER BY that is not optimized by an index. It \n** determines the expressions, if any, that the sorter-reference \n** optimization should be used for. The sorter-reference optimization\n** is used for SELECT queries like:\n**\n**   SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10\n**\n** If the optimization is used for expression \"bigblob\", then instead of\n** storing values read from that column in the sorter records, the PK of\n** the row from table t1 is stored instead. Then, as records are extracted from\n** the sorter to return to the user, the required value of bigblob is\n** retrieved directly from table t1. If the values are very large, this \n** can be more efficient than storing them directly in the sorter records.\n**\n** The ExprList_item.bSorterRef flag is set for each expression in pEList \n** for which the sorter-reference optimization should be enabled. \n** Additionally, the pSort->aDefer[] array is populated with entries\n** for all cursors required to evaluate all selected expressions. Finally.\n** output variable (*ppExtra) is set to an expression list containing\n** expressions for all extra PK values that should be stored in the\n** sorter records.\n*/\nstatic void selectExprDefer(\n  Parse *pParse,                  /* Leave any error here */\n  SortCtx *pSort,                 /* Sorter context */\n  ExprList *pEList,               /* Expressions destined for sorter */\n  ExprList **ppExtra              /* Expressions to append to sorter record */\n){\n  int i;\n  int nDefer = 0;\n  ExprList *pExtra = 0;\n  for(i=0; i<pEList->nExpr; i++){\n    struct ExprList_item *pItem = &pEList->a[i];\n    if( pItem->u.x.iOrderByCol==0 ){\n      Expr *pExpr = pItem->pExpr;\n      Table *pTab = pExpr->y.pTab;\n      if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab)\n       && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)\n      ){\n        int j;\n        for(j=0; j<nDefer; j++){\n          if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;\n        }\n        if( j==nDefer ){\n          if( nDefer==ArraySize(pSort->aDefer) ){\n            continue;\n          }else{\n            int nKey = 1;\n            int k;\n            Index *pPk = 0;\n            if( !HasRowid(pTab) ){\n              pPk = sqlite3PrimaryKeyIndex(pTab);\n              nKey = pPk->nKeyCol;\n            }\n            for(k=0; k<nKey; k++){\n              Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);\n              if( pNew ){\n                pNew->iTable = pExpr->iTable;\n                pNew->y.pTab = pExpr->y.pTab;\n                pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;\n                pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);\n              }\n            }\n            pSort->aDefer[nDefer].pTab = pExpr->y.pTab;\n            pSort->aDefer[nDefer].iCsr = pExpr->iTable;\n            pSort->aDefer[nDefer].nKey = nKey;\n            nDefer++;\n          }\n        }\n        pItem->bSorterRef = 1;\n      }\n    }\n  }\n  pSort->nDefer = (u8)nDefer;\n  *ppExtra = pExtra;\n}\n#endif\n\n/*\n** This routine generates the code for the inside of the inner loop\n** of a SELECT.\n**\n** If srcTab is negative, then the p->pEList expressions\n** are evaluated in order to get the data for this row.  If srcTab is\n** zero or more, then data is pulled from srcTab and p->pEList is used only \n** to get the number of columns and the collation sequence for each column.\n*/\nstatic void selectInnerLoop(\n  Parse *pParse,          /* The parser context */\n  Select *p,              /* The complete select statement being coded */\n  int srcTab,             /* Pull data from this table if non-negative */\n  SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */\n  DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */\n  SelectDest *pDest,      /* How to dispose of the results */\n  int iContinue,          /* Jump here to continue with next row */\n  int iBreak              /* Jump here to break out of the inner loop */\n){\n  Vdbe *v = pParse->pVdbe;\n  int i;\n  int hasDistinct;            /* True if the DISTINCT keyword is present */\n  int eDest = pDest->eDest;   /* How to dispose of results */\n  int iParm = pDest->iSDParm; /* First argument to disposal method */\n  int nResultCol;             /* Number of result columns */\n  int nPrefixReg = 0;         /* Number of extra registers before regResult */\n  RowLoadInfo sRowLoadInfo;   /* Info for deferred row loading */\n\n  /* Usually, regResult is the first cell in an array of memory cells\n  ** containing the current result row. In this case regOrig is set to the\n  ** same value. However, if the results are being sent to the sorter, the\n  ** values for any expressions that are also part of the sort-key are omitted\n  ** from this array. In this case regOrig is set to zero.  */\n  int regResult;              /* Start of memory holding current results */\n  int regOrig;                /* Start of memory holding full result (or 0) */\n\n  assert( v );\n  assert( p->pEList!=0 );\n  hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;\n  if( pSort && pSort->pOrderBy==0 ) pSort = 0;\n  if( pSort==0 && !hasDistinct ){\n    assert( iContinue!=0 );\n    codeOffset(v, p->iOffset, iContinue);\n  }\n\n  /* Pull the requested columns.\n  */\n  nResultCol = p->pEList->nExpr;\n\n  if( pDest->iSdst==0 ){\n    if( pSort ){\n      nPrefixReg = pSort->pOrderBy->nExpr;\n      if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;\n      pParse->nMem += nPrefixReg;\n    }\n    pDest->iSdst = pParse->nMem+1;\n    pParse->nMem += nResultCol;\n  }else if( pDest->iSdst+nResultCol > pParse->nMem ){\n    /* This is an error condition that can result, for example, when a SELECT\n    ** on the right-hand side of an INSERT contains more result columns than\n    ** there are columns in the table on the left.  The error will be caught\n    ** and reported later.  But we need to make sure enough memory is allocated\n    ** to avoid other spurious errors in the meantime. */\n    pParse->nMem += nResultCol;\n  }\n  pDest->nSdst = nResultCol;\n  regOrig = regResult = pDest->iSdst;\n  if( srcTab>=0 ){\n    for(i=0; i<nResultCol; i++){\n      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);\n      VdbeComment((v, \"%s\", p->pEList->a[i].zEName));\n    }\n  }else if( eDest!=SRT_Exists ){\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n    ExprList *pExtra = 0;\n#endif\n    /* If the destination is an EXISTS(...) expression, the actual\n    ** values returned by the SELECT are not required.\n    */\n    u8 ecelFlags;    /* \"ecel\" is an abbreviation of \"ExprCodeExprList\" */\n    ExprList *pEList;\n    if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){\n      ecelFlags = SQLITE_ECEL_DUP;\n    }else{\n      ecelFlags = 0;\n    }\n    if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){\n      /* For each expression in p->pEList that is a copy of an expression in\n      ** the ORDER BY clause (pSort->pOrderBy), set the associated \n      ** iOrderByCol value to one more than the index of the ORDER BY \n      ** expression within the sort-key that pushOntoSorter() will generate.\n      ** This allows the p->pEList field to be omitted from the sorted record,\n      ** saving space and CPU cycles.  */\n      ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);\n\n      for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){\n        int j;\n        if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){\n          p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;\n        }\n      }\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n      selectExprDefer(pParse, pSort, p->pEList, &pExtra);\n      if( pExtra && pParse->db->mallocFailed==0 ){\n        /* If there are any extra PK columns to add to the sorter records,\n        ** allocate extra memory cells and adjust the OpenEphemeral \n        ** instruction to account for the larger records. This is only\n        ** required if there are one or more WITHOUT ROWID tables with\n        ** composite primary keys in the SortCtx.aDefer[] array.  */\n        VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);\n        pOp->p2 += (pExtra->nExpr - pSort->nDefer);\n        pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);\n        pParse->nMem += pExtra->nExpr;\n      }\n#endif\n\n      /* Adjust nResultCol to account for columns that are omitted\n      ** from the sorter by the optimizations in this branch */\n      pEList = p->pEList;\n      for(i=0; i<pEList->nExpr; i++){\n        if( pEList->a[i].u.x.iOrderByCol>0\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n         || pEList->a[i].bSorterRef\n#endif\n        ){\n          nResultCol--;\n          regOrig = 0;\n        }\n      }\n\n      testcase( regOrig );\n      testcase( eDest==SRT_Set );\n      testcase( eDest==SRT_Mem );\n      testcase( eDest==SRT_Coroutine );\n      testcase( eDest==SRT_Output );\n      assert( eDest==SRT_Set || eDest==SRT_Mem \n           || eDest==SRT_Coroutine || eDest==SRT_Output );\n    }\n    sRowLoadInfo.regResult = regResult;\n    sRowLoadInfo.ecelFlags = ecelFlags;\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n    sRowLoadInfo.pExtra = pExtra;\n    sRowLoadInfo.regExtraResult = regResult + nResultCol;\n    if( pExtra ) nResultCol += pExtra->nExpr;\n#endif\n    if( p->iLimit\n     && (ecelFlags & SQLITE_ECEL_OMITREF)!=0 \n     && nPrefixReg>0\n    ){\n      assert( pSort!=0 );\n      assert( hasDistinct==0 );\n      pSort->pDeferredRowLoad = &sRowLoadInfo;\n      regOrig = 0;\n    }else{\n      innerLoopLoadRow(pParse, p, &sRowLoadInfo);\n    }\n  }\n\n  /* If the DISTINCT keyword was present on the SELECT statement\n  ** and this row has been seen before, then do not make this row\n  ** part of the result.\n  */\n  if( hasDistinct ){\n    switch( pDistinct->eTnctType ){\n      case WHERE_DISTINCT_ORDERED: {\n        VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */\n        int iJump;              /* Jump destination */\n        int regPrev;            /* Previous row content */\n\n        /* Allocate space for the previous row */\n        regPrev = pParse->nMem+1;\n        pParse->nMem += nResultCol;\n\n        /* Change the OP_OpenEphemeral coded earlier to an OP_Null\n        ** sets the MEM_Cleared bit on the first register of the\n        ** previous value.  This will cause the OP_Ne below to always\n        ** fail on the first iteration of the loop even if the first\n        ** row is all NULLs.\n        */\n        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);\n        pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);\n        pOp->opcode = OP_Null;\n        pOp->p1 = 1;\n        pOp->p2 = regPrev;\n        pOp = 0;  /* Ensure pOp is not used after sqlite3VdbeAddOp() */\n\n        iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;\n        for(i=0; i<nResultCol; i++){\n          CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);\n          if( i<nResultCol-1 ){\n            sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);\n            VdbeCoverage(v);\n          }else{\n            sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);\n            VdbeCoverage(v);\n           }\n          sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);\n          sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);\n        }\n        assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );\n        sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);\n        break;\n      }\n\n      case WHERE_DISTINCT_UNIQUE: {\n        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);\n        break;\n      }\n\n      default: {\n        assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );\n        codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,\n                     regResult);\n        break;\n      }\n    }\n    if( pSort==0 ){\n      codeOffset(v, p->iOffset, iContinue);\n    }\n  }\n\n  switch( eDest ){\n    /* In this mode, write each query result to the key of the temporary\n    ** table iParm.\n    */\n#ifndef SQLITE_OMIT_COMPOUND_SELECT\n    case SRT_Union: {\n      int r1;\n      r1 = sqlite3GetTempReg(pParse);\n      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);\n      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);\n      sqlite3ReleaseTempReg(pParse, r1);\n      break;\n    }\n\n    /* Construct a record from the query result, but instead of\n    ** saving that record, use it as a key to delete elements from\n    ** the temporary table iParm.\n    */\n    case SRT_Except: {\n      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);\n      break;\n    }\n#endif /* SQLITE_OMIT_COMPOUND_SELECT */\n\n    /* Store the result as data using a unique key.\n    */\n    case SRT_Fifo:\n    case SRT_DistFifo:\n    case SRT_Table:\n    case SRT_EphemTab: {\n      int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);\n      testcase( eDest==SRT_Table );\n      testcase( eDest==SRT_EphemTab );\n      testcase( eDest==SRT_Fifo );\n      testcase( eDest==SRT_DistFifo );\n      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);\n#ifndef SQLITE_OMIT_CTE\n      if( eDest==SRT_DistFifo ){\n        /* If the destination is DistFifo, then cursor (iParm+1) is open\n        ** on an ephemeral index. If the current row is already present\n        ** in the index, do not write it to the output. If not, add the\n        ** current row to the index and proceed with writing it to the\n        ** output table as well.  */\n        int addr = sqlite3VdbeCurrentAddr(v) + 4;\n        sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);\n        VdbeCoverage(v);\n        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);\n        assert( pSort==0 );\n      }\n#endif\n      if( pSort ){\n        assert( regResult==regOrig );\n        pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);\n      }else{\n        int r2 = sqlite3GetTempReg(pParse);\n        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);\n        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);\n        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);\n        sqlite3ReleaseTempReg(pParse, r2);\n      }\n      sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);\n      break;\n    }\n\n#ifndef SQLITE_OMIT_SUBQUERY\n    /* If we are creating a set for an \"expr IN (SELECT ...)\" construct,\n    ** then there should be a single item on the stack.  Write this\n    ** item into the set table with bogus data.\n    */\n    case SRT_Set: {\n      if( pSort ){\n        /* At first glance you would think we could optimize out the\n        ** ORDER BY in this case since the order of entries in the set\n        ** does not matter.  But there might be a LIMIT clause, in which\n        ** case the order does matter */\n        pushOntoSorter(\n            pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);\n      }else{\n        int r1 = sqlite3GetTempReg(pParse);\n        assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );\n        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol, \n            r1, pDest->zAffSdst, nResultCol);\n        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);\n        sqlite3ReleaseTempReg(pParse, r1);\n      }\n      break;\n    }\n\n    /* If any row exist in the result set, record that fact and abort.\n    */\n    case SRT_Exists: {\n      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);\n      /* The LIMIT clause will terminate the loop for us */\n      break;\n    }\n\n    /* If this is a scalar select that is part of an expression, then\n    ** store the results in the appropriate memory cell or array of \n    ** memory cells and break out of the scan loop.\n    */\n    case SRT_Mem: {\n      if( pSort ){\n        assert( nResultCol<=pDest->nSdst );\n        pushOntoSorter(\n            pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);\n      }else{\n        assert( nResultCol==pDest->nSdst );\n        assert( regResult==iParm );\n        /* The LIMIT clause will jump out of the loop for us */\n      }\n      break;\n    }\n#endif /* #ifndef SQLITE_OMIT_SUBQUERY */\n\n    case SRT_Coroutine:       /* Send data to a co-routine */\n    case SRT_Output: {        /* Return the results */\n      testcase( eDest==SRT_Coroutine );\n      testcase( eDest==SRT_Output );\n      if( pSort ){\n        pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,\n                       nPrefixReg);\n      }else if( eDest==SRT_Coroutine ){\n        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);\n      }else{\n        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);\n      }\n      break;\n    }\n\n#ifndef SQLITE_OMIT_CTE\n    /* Write the results into a priority queue that is order according to\n    ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an\n    ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first\n    ** pSO->nExpr columns, then make sure all keys are unique by adding a\n    ** final OP_Sequence column.  The last column is the record as a blob.\n    */\n    case SRT_DistQueue:\n    case SRT_Queue: {\n      int nKey;\n      int r1, r2, r3;\n      int addrTest = 0;\n      ExprList *pSO;\n      pSO = pDest->pOrderBy;\n      assert( pSO );\n      nKey = pSO->nExpr;\n      r1 = sqlite3GetTempReg(pParse);\n      r2 = sqlite3GetTempRange(pParse, nKey+2);\n      r3 = r2+nKey+1;\n      if( eDest==SRT_DistQueue ){\n        /* If the destination is DistQueue, then cursor (iParm+1) is open\n        ** on a second ephemeral index that holds all values every previously\n        ** added to the queue. */\n        addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, \n                                        regResult, nResultCol);\n        VdbeCoverage(v);\n      }\n      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);\n      if( eDest==SRT_DistQueue ){\n        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);\n        sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);\n      }\n      for(i=0; i<nKey; i++){\n        sqlite3VdbeAddOp2(v, OP_SCopy,\n                          regResult + pSO->a[i].u.x.iOrderByCol - 1,\n                          r2+i);\n      }\n      sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);\n      sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);\n      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);\n      if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);\n      sqlite3ReleaseTempReg(pParse, r1);\n      sqlite3ReleaseTempRange(pParse, r2, nKey+2);\n      break;\n    }\n#endif /* SQLITE_OMIT_CTE */\n\n\n\n#if !defined(SQLITE_OMIT_TRIGGER)\n    /* Discard the results.  This is used for SELECT statements inside\n    ** the body of a TRIGGER.  The purpose of such selects is to call\n    ** user-defined functions that have side effects.  We do not care\n    ** about the actual results of the select.\n    */\n    default: {\n      assert( eDest==SRT_Discard );\n      break;\n    }\n#endif\n  }\n\n  /* Jump to the end of the loop if the LIMIT is reached.  Except, if\n  ** there is a sorter, in which case the sorter has already limited\n  ** the output for us.\n  */\n  if( pSort==0 && p->iLimit ){\n    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);\n  }\n}\n\n/*\n** Allocate a KeyInfo object sufficient for an index of N key columns and\n** X extra columns.\n*/\nSQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){\n  int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);\n  KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);\n  if( p ){\n    p->aSortFlags = (u8*)&p->aColl[N+X];\n    p->nKeyField = (u16)N;\n    p->nAllField = (u16)(N+X);\n    p->enc = ENC(db);\n    p->db = db;\n    p->nRef = 1;\n    memset(&p[1], 0, nExtra);\n  }else{\n    sqlite3OomFault(db);\n  }\n  return p;\n}\n\n/*\n** Deallocate a KeyInfo object\n*/\nSQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){\n  if( p ){\n    assert( p->nRef>0 );\n    p->nRef--;\n    if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);\n  }\n}\n\n/*\n** Make a new pointer to a KeyInfo object\n*/\nSQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){\n  if( p ){\n    assert( p->nRef>0 );\n    p->nRef++;\n  }\n  return p;\n}\n\n#ifdef SQLITE_DEBUG\n/*\n** Return TRUE if a KeyInfo object can be change.  The KeyInfo object\n** can only be changed if this is just a single reference to the object.\n**\n** This routine is used only inside of assert() statements.\n*/\nSQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }\n#endif /* SQLITE_DEBUG */\n\n/*\n** Given an expression list, generate a KeyInfo structure that records\n** the collating sequence for each expression in that expression list.\n**\n** If the ExprList is an ORDER BY or GROUP BY clause then the resulting\n** KeyInfo structure is appropriate for initializing a virtual index to\n** implement that clause.  If the ExprList is the result set of a SELECT\n** then the KeyInfo structure is appropriate for initializing a virtual\n** index to implement a DISTINCT test.\n**\n** Space to hold the KeyInfo structure is obtained from malloc.  The calling\n** function is responsible for seeing that this structure is eventually\n** freed.\n*/\nSQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(\n  Parse *pParse,       /* Parsing context */\n  ExprList *pList,     /* Form the KeyInfo object from this ExprList */\n  int iStart,          /* Begin with this column of pList */\n  int nExtra           /* Add this many extra columns to the end */\n){\n  int nExpr;\n  KeyInfo *pInfo;\n  struct ExprList_item *pItem;\n  sqlite3 *db = pParse->db;\n  int i;\n\n  nExpr = pList->nExpr;\n  pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);\n  if( pInfo ){\n    assert( sqlite3KeyInfoIsWriteable(pInfo) );\n    for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){\n      pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);\n      pInfo->aSortFlags[i-iStart] = pItem->sortFlags;\n    }\n  }\n  return pInfo;\n}\n\n/*\n** Name of the connection operator, used for error messages.\n*/\nstatic const char *selectOpName(int id){\n  char *z;\n  switch( id ){\n    case TK_ALL:       z = \"UNION ALL\";   break;\n    case TK_INTERSECT: z = \"INTERSECT\";   break;\n    case TK_EXCEPT:    z = \"EXCEPT\";      break;\n    default:           z = \"UNION\";       break;\n  }\n  return z;\n}\n\n#ifndef SQLITE_OMIT_EXPLAIN\n/*\n** Unless an \"EXPLAIN QUERY PLAN\" command is being processed, this function\n** is a no-op. Otherwise, it adds a single row of output to the EQP result,\n** where the caption is of the form:\n**\n**   \"USE TEMP B-TREE FOR xxx\"\n**\n** where xxx is one of \"DISTINCT\", \"ORDER BY\" or \"GROUP BY\". Exactly which\n** is determined by the zUsage argument.\n*/\nstatic void explainTempTable(Parse *pParse, const char *zUsage){\n  ExplainQueryPlan((pParse, 0, \"USE TEMP B-TREE FOR %s\", zUsage));\n}\n\n/*\n** Assign expression b to lvalue a. A second, no-op, version of this macro\n** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code\n** in sqlite3Select() to assign values to structure member variables that\n** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the\n** code with #ifndef directives.\n*/\n# define explainSetInteger(a, b) a = b\n\n#else\n/* No-op versions of the explainXXX() functions and macros. */\n# define explainTempTable(y,z)\n# define explainSetInteger(y,z)\n#endif\n\n\n/*\n** If the inner loop was generated using a non-null pOrderBy argument,\n** then the results were placed in a sorter.  After the loop is terminated\n** we need to run the sorter and output the results.  The following\n** routine generates the code needed to do that.\n*/\nstatic void generateSortTail(\n  Parse *pParse,    /* Parsing context */\n  Select *p,        /* The SELECT statement */\n  SortCtx *pSort,   /* Information on the ORDER BY clause */\n  int nColumn,      /* Number of columns of data */\n  SelectDest *pDest /* Write the sorted results here */\n){\n  Vdbe *v = pParse->pVdbe;                     /* The prepared statement */\n  int addrBreak = pSort->labelDone;            /* Jump here to exit loop */\n  int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */\n  int addr;                       /* Top of output loop. Jump for Next. */\n  int addrOnce = 0;\n  int iTab;\n  ExprList *pOrderBy = pSort->pOrderBy;\n  int eDest = pDest->eDest;\n  int iParm = pDest->iSDParm;\n  int regRow;\n  int regRowid;\n  int iCol;\n  int nKey;                       /* Number of key columns in sorter record */\n  int iSortTab;                   /* Sorter cursor to read from */\n  int i;\n  int bSeq;                       /* True if sorter record includes seq. no. */\n  int nRefKey = 0;\n  struct ExprList_item *aOutEx = p->pEList->a;\n\n  assert( addrBreak<0 );\n  if( pSort->labelBkOut ){\n    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);\n    sqlite3VdbeGoto(v, addrBreak);\n    sqlite3VdbeResolveLabel(v, pSort->labelBkOut);\n  }\n\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n  /* Open any cursors needed for sorter-reference expressions */\n  for(i=0; i<pSort->nDefer; i++){\n    Table *pTab = pSort->aDefer[i].pTab;\n    int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n    sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);\n    nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);\n  }\n#endif\n\n  iTab = pSort->iECursor;\n  if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){\n    regRowid = 0;\n    regRow = pDest->iSdst;\n  }else{\n    regRowid = sqlite3GetTempReg(pParse);\n    if( eDest==SRT_EphemTab || eDest==SRT_Table ){\n      regRow = sqlite3GetTempReg(pParse);\n      nColumn = 0;\n    }else{\n      regRow = sqlite3GetTempRange(pParse, nColumn);\n    }\n  }\n  nKey = pOrderBy->nExpr - pSort->nOBSat;\n  if( pSort->sortFlags & SORTFLAG_UseSorter ){\n    int regSortOut = ++pParse->nMem;\n    iSortTab = pParse->nTab++;\n    if( pSort->labelBkOut ){\n      addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);\n    }\n    sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, \n        nKey+1+nColumn+nRefKey);\n    if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);\n    addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);\n    VdbeCoverage(v);\n    codeOffset(v, p->iOffset, addrContinue);\n    sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);\n    bSeq = 0;\n  }else{\n    addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);\n    codeOffset(v, p->iOffset, addrContinue);\n    iSortTab = iTab;\n    bSeq = 1;\n  }\n  for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n    if( aOutEx[i].bSorterRef ) continue;\n#endif\n    if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;\n  }\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n  if( pSort->nDefer ){\n    int iKey = iCol+1;\n    int regKey = sqlite3GetTempRange(pParse, nRefKey);\n\n    for(i=0; i<pSort->nDefer; i++){\n      int iCsr = pSort->aDefer[i].iCsr;\n      Table *pTab = pSort->aDefer[i].pTab;\n      int nKey = pSort->aDefer[i].nKey;\n\n      sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);\n      if( HasRowid(pTab) ){\n        sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);\n        sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr, \n            sqlite3VdbeCurrentAddr(v)+1, regKey);\n      }else{\n        int k;\n        int iJmp;\n        assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );\n        for(k=0; k<nKey; k++){\n          sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);\n        }\n        iJmp = sqlite3VdbeCurrentAddr(v);\n        sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);\n        sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);\n        sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);\n      }\n    }\n    sqlite3ReleaseTempRange(pParse, regKey, nRefKey);\n  }\n#endif\n  for(i=nColumn-1; i>=0; i--){\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n    if( aOutEx[i].bSorterRef ){\n      sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);\n    }else\n#endif\n    {\n      int iRead;\n      if( aOutEx[i].u.x.iOrderByCol ){\n        iRead = aOutEx[i].u.x.iOrderByCol-1;\n      }else{\n        iRead = iCol--;\n      }\n      sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);\n      VdbeComment((v, \"%s\", aOutEx[i].zEName));\n    }\n  }\n  switch( eDest ){\n    case SRT_Table:\n    case SRT_EphemTab: {\n      sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow);\n      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);\n      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);\n      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);\n      break;\n    }\n#ifndef SQLITE_OMIT_SUBQUERY\n    case SRT_Set: {\n      assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );\n      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,\n                        pDest->zAffSdst, nColumn);\n      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);\n      break;\n    }\n    case SRT_Mem: {\n      /* The LIMIT clause will terminate the loop for us */\n      break;\n    }\n#endif\n    default: {\n      assert( eDest==SRT_Output || eDest==SRT_Coroutine ); \n      testcase( eDest==SRT_Output );\n      testcase( eDest==SRT_Coroutine );\n      if( eDest==SRT_Output ){\n        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);\n      }else{\n        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);\n      }\n      break;\n    }\n  }\n  if( regRowid ){\n    if( eDest==SRT_Set ){\n      sqlite3ReleaseTempRange(pParse, regRow, nColumn);\n    }else{\n      sqlite3ReleaseTempReg(pParse, regRow);\n    }\n    sqlite3ReleaseTempReg(pParse, regRowid);\n  }\n  /* The bottom of the loop\n  */\n  sqlite3VdbeResolveLabel(v, addrContinue);\n  if( pSort->sortFlags & SORTFLAG_UseSorter ){\n    sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);\n  }else{\n    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);\n  }\n  if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);\n  sqlite3VdbeResolveLabel(v, addrBreak);\n}\n\n/*\n** Return a pointer to a string containing the 'declaration type' of the\n** expression pExpr. The string may be treated as static by the caller.\n**\n** Also try to estimate the size of the returned value and return that\n** result in *pEstWidth.\n**\n** The declaration type is the exact datatype definition extracted from the\n** original CREATE TABLE statement if the expression is a column. The\n** declaration type for a ROWID field is INTEGER. Exactly when an expression\n** is considered a column can be complex in the presence of subqueries. The\n** result-set expression in all of the following SELECT statements is \n** considered a column by this function.\n**\n**   SELECT col FROM tbl;\n**   SELECT (SELECT col FROM tbl;\n**   SELECT (SELECT col FROM tbl);\n**   SELECT abc FROM (SELECT col AS abc FROM tbl);\n** \n** The declaration type for any expression other than a column is NULL.\n**\n** This routine has either 3 or 6 parameters depending on whether or not\n** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.\n*/\n#ifdef SQLITE_ENABLE_COLUMN_METADATA\n# define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)\n#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */\n# define columnType(A,B,C,D,E) columnTypeImpl(A,B)\n#endif\nstatic const char *columnTypeImpl(\n  NameContext *pNC, \n#ifndef SQLITE_ENABLE_COLUMN_METADATA\n  Expr *pExpr\n#else\n  Expr *pExpr,\n  const char **pzOrigDb,\n  const char **pzOrigTab,\n  const char **pzOrigCol\n#endif\n){\n  char const *zType = 0;\n  int j;\n#ifdef SQLITE_ENABLE_COLUMN_METADATA\n  char const *zOrigDb = 0;\n  char const *zOrigTab = 0;\n  char const *zOrigCol = 0;\n#endif\n\n  assert( pExpr!=0 );\n  assert( pNC->pSrcList!=0 );\n  switch( pExpr->op ){\n    case TK_COLUMN: {\n      /* The expression is a column. Locate the table the column is being\n      ** extracted from in NameContext.pSrcList. This table may be real\n      ** database table or a subquery.\n      */\n      Table *pTab = 0;            /* Table structure column is extracted from */\n      Select *pS = 0;             /* Select the column is extracted from */\n      int iCol = pExpr->iColumn;  /* Index of column in pTab */\n      while( pNC && !pTab ){\n        SrcList *pTabList = pNC->pSrcList;\n        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);\n        if( j<pTabList->nSrc ){\n          pTab = pTabList->a[j].pTab;\n          pS = pTabList->a[j].pSelect;\n        }else{\n          pNC = pNC->pNext;\n        }\n      }\n\n      if( pTab==0 ){\n        /* At one time, code such as \"SELECT new.x\" within a trigger would\n        ** cause this condition to run.  Since then, we have restructured how\n        ** trigger code is generated and so this condition is no longer \n        ** possible. However, it can still be true for statements like\n        ** the following:\n        **\n        **   CREATE TABLE t1(col INTEGER);\n        **   SELECT (SELECT t1.col) FROM FROM t1;\n        **\n        ** when columnType() is called on the expression \"t1.col\" in the \n        ** sub-select. In this case, set the column type to NULL, even\n        ** though it should really be \"INTEGER\".\n        **\n        ** This is not a problem, as the column type of \"t1.col\" is never\n        ** used. When columnType() is called on the expression \n        ** \"(SELECT t1.col)\", the correct type is returned (see the TK_SELECT\n        ** branch below.  */\n        break;\n      }\n\n      assert( pTab && pExpr->y.pTab==pTab );\n      if( pS ){\n        /* The \"table\" is actually a sub-select or a view in the FROM clause\n        ** of the SELECT statement. Return the declaration type and origin\n        ** data for the result-set column of the sub-select.\n        */\n        if( iCol>=0 && iCol<pS->pEList->nExpr ){\n          /* If iCol is less than zero, then the expression requests the\n          ** rowid of the sub-select or view. This expression is legal (see \n          ** test case misc2.2.2) - it always evaluates to NULL.\n          */\n          NameContext sNC;\n          Expr *p = pS->pEList->a[iCol].pExpr;\n          sNC.pSrcList = pS->pSrc;\n          sNC.pNext = pNC;\n          sNC.pParse = pNC->pParse;\n          zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol); \n        }\n      }else{\n        /* A real table or a CTE table */\n        assert( !pS );\n#ifdef SQLITE_ENABLE_COLUMN_METADATA\n        if( iCol<0 ) iCol = pTab->iPKey;\n        assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );\n        if( iCol<0 ){\n          zType = \"INTEGER\";\n          zOrigCol = \"rowid\";\n        }else{\n          zOrigCol = pTab->aCol[iCol].zName;\n          zType = sqlite3ColumnType(&pTab->aCol[iCol],0);\n        }\n        zOrigTab = pTab->zName;\n        if( pNC->pParse && pTab->pSchema ){\n          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);\n          zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;\n        }\n#else\n        assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );\n        if( iCol<0 ){\n          zType = \"INTEGER\";\n        }else{\n          zType = sqlite3ColumnType(&pTab->aCol[iCol],0);\n        }\n#endif\n      }\n      break;\n    }\n#ifndef SQLITE_OMIT_SUBQUERY\n    case TK_SELECT: {\n      /* The expression is a sub-select. Return the declaration type and\n      ** origin info for the single column in the result set of the SELECT\n      ** statement.\n      */\n      NameContext sNC;\n      Select *pS = pExpr->x.pSelect;\n      Expr *p = pS->pEList->a[0].pExpr;\n      assert( ExprHasProperty(pExpr, EP_xIsSelect) );\n      sNC.pSrcList = pS->pSrc;\n      sNC.pNext = pNC;\n      sNC.pParse = pNC->pParse;\n      zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); \n      break;\n    }\n#endif\n  }\n\n#ifdef SQLITE_ENABLE_COLUMN_METADATA  \n  if( pzOrigDb ){\n    assert( pzOrigTab && pzOrigCol );\n    *pzOrigDb = zOrigDb;\n    *pzOrigTab = zOrigTab;\n    *pzOrigCol = zOrigCol;\n  }\n#endif\n  return zType;\n}\n\n/*\n** Generate code that will tell the VDBE the declaration types of columns\n** in the result set.\n*/\nstatic void generateColumnTypes(\n  Parse *pParse,      /* Parser context */\n  SrcList *pTabList,  /* List of tables */\n  ExprList *pEList    /* Expressions defining the result set */\n){\n#ifndef SQLITE_OMIT_DECLTYPE\n  Vdbe *v = pParse->pVdbe;\n  int i;\n  NameContext sNC;\n  sNC.pSrcList = pTabList;\n  sNC.pParse = pParse;\n  sNC.pNext = 0;\n  for(i=0; i<pEList->nExpr; i++){\n    Expr *p = pEList->a[i].pExpr;\n    const char *zType;\n#ifdef SQLITE_ENABLE_COLUMN_METADATA\n    const char *zOrigDb = 0;\n    const char *zOrigTab = 0;\n    const char *zOrigCol = 0;\n    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);\n\n    /* The vdbe must make its own copy of the column-type and other \n    ** column specific strings, in case the schema is reset before this\n    ** virtual machine is deleted.\n    */\n    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);\n    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);\n    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);\n#else\n    zType = columnType(&sNC, p, 0, 0, 0);\n#endif\n    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);\n  }\n#endif /* !defined(SQLITE_OMIT_DECLTYPE) */\n}\n\n\n/*\n** Compute the column names for a SELECT statement.\n**\n** The only guarantee that SQLite makes about column names is that if the\n** column has an AS clause assigning it a name, that will be the name used.\n** That is the only documented guarantee.  However, countless applications\n** developed over the years have made baseless assumptions about column names\n** and will break if those assumptions changes.  Hence, use extreme caution\n** when modifying this routine to avoid breaking legacy.\n**\n** See Also: sqlite3ColumnsFromExprList()\n**\n** The PRAGMA short_column_names and PRAGMA full_column_names settings are\n** deprecated.  The default setting is short=ON, full=OFF.  99.9% of all\n** applications should operate this way.  Nevertheless, we need to support the\n** other modes for legacy:\n**\n**    short=OFF, full=OFF:      Column name is the text of the expression has it\n**                              originally appears in the SELECT statement.  In\n**                              other words, the zSpan of the result expression.\n**\n**    short=ON, full=OFF:       (This is the default setting).  If the result\n**                              refers directly to a table column, then the\n**                              result column name is just the table column\n**                              name: COLUMN.  Otherwise use zSpan.\n**\n**    full=ON, short=ANY:       If the result refers directly to a table column,\n**                              then the result column name with the table name\n**                              prefix, ex: TABLE.COLUMN.  Otherwise use zSpan.\n*/\nstatic void generateColumnNames(\n  Parse *pParse,      /* Parser context */\n  Select *pSelect     /* Generate column names for this SELECT statement */\n){\n  Vdbe *v = pParse->pVdbe;\n  int i;\n  Table *pTab;\n  SrcList *pTabList;\n  ExprList *pEList;\n  sqlite3 *db = pParse->db;\n  int fullName;    /* TABLE.COLUMN if no AS clause and is a direct table ref */\n  int srcName;     /* COLUMN or TABLE.COLUMN if no AS clause and is direct */\n\n#ifndef SQLITE_OMIT_EXPLAIN\n  /* If this is an EXPLAIN, skip this step */\n  if( pParse->explain ){\n    return;\n  }\n#endif\n\n  if( pParse->colNamesSet ) return;\n  /* Column names are determined by the left-most term of a compound select */\n  while( pSelect->pPrior ) pSelect = pSelect->pPrior;\n  SELECTTRACE(1,pParse,pSelect,(\"generating column names\\n\"));\n  pTabList = pSelect->pSrc;\n  pEList = pSelect->pEList;\n  assert( v!=0 );\n  assert( pTabList!=0 );\n  pParse->colNamesSet = 1;\n  fullName = (db->flags & SQLITE_FullColNames)!=0;\n  srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;\n  sqlite3VdbeSetNumCols(v, pEList->nExpr);\n  for(i=0; i<pEList->nExpr; i++){\n    Expr *p = pEList->a[i].pExpr;\n\n    assert( p!=0 );\n    assert( p->op!=TK_AGG_COLUMN );  /* Agg processing has not run yet */\n    assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */\n    if( pEList->a[i].zEName && pEList->a[i].eEName==ENAME_NAME ){\n      /* An AS clause always takes first priority */\n      char *zName = pEList->a[i].zEName;\n      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);\n    }else if( srcName && p->op==TK_COLUMN ){\n      char *zCol;\n      int iCol = p->iColumn;\n      pTab = p->y.pTab;\n      assert( pTab!=0 );\n      if( iCol<0 ) iCol = pTab->iPKey;\n      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );\n      if( iCol<0 ){\n        zCol = \"rowid\";\n      }else{\n        zCol = pTab->aCol[iCol].zName;\n      }\n      if( fullName ){\n        char *zName = 0;\n        zName = sqlite3MPrintf(db, \"%s.%s\", pTab->zName, zCol);\n        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);\n      }else{\n        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);\n      }\n    }else{\n      const char *z = pEList->a[i].zEName;\n      z = z==0 ? sqlite3MPrintf(db, \"column%d\", i+1) : sqlite3DbStrDup(db, z);\n      sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);\n    }\n  }\n  generateColumnTypes(pParse, pTabList, pEList);\n}\n\n/*\n** Given an expression list (which is really the list of expressions\n** that form the result set of a SELECT statement) compute appropriate\n** column names for a table that would hold the expression list.\n**\n** All column names will be unique.\n**\n** Only the column names are computed.  Column.zType, Column.zColl,\n** and other fields of Column are zeroed.\n**\n** Return SQLITE_OK on success.  If a memory allocation error occurs,\n** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.\n**\n** The only guarantee that SQLite makes about column names is that if the\n** column has an AS clause assigning it a name, that will be the name used.\n** That is the only documented guarantee.  However, countless applications\n** developed over the years have made baseless assumptions about column names\n** and will break if those assumptions changes.  Hence, use extreme caution\n** when modifying this routine to avoid breaking legacy.\n**\n** See Also: generateColumnNames()\n*/\nSQLITE_PRIVATE int sqlite3ColumnsFromExprList(\n  Parse *pParse,          /* Parsing context */\n  ExprList *pEList,       /* Expr list from which to derive column names */\n  i16 *pnCol,             /* Write the number of columns here */\n  Column **paCol          /* Write the new column list here */\n){\n  sqlite3 *db = pParse->db;   /* Database connection */\n  int i, j;                   /* Loop counters */\n  u32 cnt;                    /* Index added to make the name unique */\n  Column *aCol, *pCol;        /* For looping over result columns */\n  int nCol;                   /* Number of columns in the result set */\n  char *zName;                /* Column name */\n  int nName;                  /* Size of name in zName[] */\n  Hash ht;                    /* Hash table of column names */\n\n  sqlite3HashInit(&ht);\n  if( pEList ){\n    nCol = pEList->nExpr;\n    aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);\n    testcase( aCol==0 );\n    if( nCol>32767 ) nCol = 32767;\n  }else{\n    nCol = 0;\n    aCol = 0;\n  }\n  assert( nCol==(i16)nCol );\n  *pnCol = nCol;\n  *paCol = aCol;\n\n  for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){\n    /* Get an appropriate name for the column\n    */\n    if( (zName = pEList->a[i].zEName)!=0 && pEList->a[i].eEName==ENAME_NAME ){\n      /* If the column contains an \"AS <name>\" phrase, use <name> as the name */\n    }else{\n      Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pEList->a[i].pExpr);\n      while( pColExpr->op==TK_DOT ){\n        pColExpr = pColExpr->pRight;\n        assert( pColExpr!=0 );\n      }\n      if( pColExpr->op==TK_COLUMN ){\n        /* For columns use the column name name */\n        int iCol = pColExpr->iColumn;\n        Table *pTab = pColExpr->y.pTab;\n        assert( pTab!=0 );\n        if( iCol<0 ) iCol = pTab->iPKey;\n        zName = iCol>=0 ? pTab->aCol[iCol].zName : \"rowid\";\n      }else if( pColExpr->op==TK_ID ){\n        assert( !ExprHasProperty(pColExpr, EP_IntValue) );\n        zName = pColExpr->u.zToken;\n      }else{\n        /* Use the original text of the column expression as its name */\n        zName = pEList->a[i].zEName;\n      }\n    }\n    if( zName && !sqlite3IsTrueOrFalse(zName) ){\n      zName = sqlite3DbStrDup(db, zName);\n    }else{\n      zName = sqlite3MPrintf(db,\"column%d\",i+1);\n    }\n\n    /* Make sure the column name is unique.  If the name is not unique,\n    ** append an integer to the name so that it becomes unique.\n    */\n    cnt = 0;\n    while( zName && sqlite3HashFind(&ht, zName)!=0 ){\n      nName = sqlite3Strlen30(zName);\n      if( nName>0 ){\n        for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}\n        if( zName[j]==':' ) nName = j;\n      }\n      zName = sqlite3MPrintf(db, \"%.*z:%u\", nName, zName, ++cnt);\n      if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);\n    }\n    pCol->zName = zName;\n    pCol->hName = sqlite3StrIHash(zName);\n    sqlite3ColumnPropertiesFromName(0, pCol);\n    if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){\n      sqlite3OomFault(db);\n    }\n  }\n  sqlite3HashClear(&ht);\n  if( db->mallocFailed ){\n    for(j=0; j<i; j++){\n      sqlite3DbFree(db, aCol[j].zName);\n    }\n    sqlite3DbFree(db, aCol);\n    *paCol = 0;\n    *pnCol = 0;\n    return SQLITE_NOMEM_BKPT;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Add type and collation information to a column list based on\n** a SELECT statement.\n** \n** The column list presumably came from selectColumnNamesFromExprList().\n** The column list has only names, not types or collations.  This\n** routine goes through and adds the types and collations.\n**\n** This routine requires that all identifiers in the SELECT\n** statement be resolved.\n*/\nSQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(\n  Parse *pParse,        /* Parsing contexts */\n  Table *pTab,          /* Add column type information to this table */\n  Select *pSelect,      /* SELECT used to determine types and collations */\n  char aff              /* Default affinity for columns */\n){\n  sqlite3 *db = pParse->db;\n  NameContext sNC;\n  Column *pCol;\n  CollSeq *pColl;\n  int i;\n  Expr *p;\n  struct ExprList_item *a;\n\n  assert( pSelect!=0 );\n  assert( (pSelect->selFlags & SF_Resolved)!=0 );\n  assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );\n  if( db->mallocFailed ) return;\n  memset(&sNC, 0, sizeof(sNC));\n  sNC.pSrcList = pSelect->pSrc;\n  a = pSelect->pEList->a;\n  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){\n    const char *zType;\n    int n, m;\n    p = a[i].pExpr;\n    zType = columnType(&sNC, p, 0, 0, 0);\n    /* pCol->szEst = ... // Column size est for SELECT tables never used */\n    pCol->affinity = sqlite3ExprAffinity(p);\n    if( zType ){\n      m = sqlite3Strlen30(zType);\n      n = sqlite3Strlen30(pCol->zName);\n      pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);\n      if( pCol->zName ){\n        memcpy(&pCol->zName[n+1], zType, m+1);\n        pCol->colFlags |= COLFLAG_HASTYPE;\n      }\n    }\n    if( pCol->affinity<=SQLITE_AFF_NONE ) pCol->affinity = aff;\n    pColl = sqlite3ExprCollSeq(pParse, p);\n    if( pColl && pCol->zColl==0 ){\n      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);\n    }\n  }\n  pTab->szTabRow = 1; /* Any non-zero value works */\n}\n\n/*\n** Given a SELECT statement, generate a Table structure that describes\n** the result set of that SELECT.\n*/\nSQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){\n  Table *pTab;\n  sqlite3 *db = pParse->db;\n  u64 savedFlags;\n\n  savedFlags = db->flags;\n  db->flags &= ~(u64)SQLITE_FullColNames;\n  db->flags |= SQLITE_ShortColNames;\n  sqlite3SelectPrep(pParse, pSelect, 0);\n  db->flags = savedFlags;\n  if( pParse->nErr ) return 0;\n  while( pSelect->pPrior ) pSelect = pSelect->pPrior;\n  pTab = sqlite3DbMallocZero(db, sizeof(Table) );\n  if( pTab==0 ){\n    return 0;\n  }\n  pTab->nTabRef = 1;\n  pTab->zName = 0;\n  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );\n  sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);\n  sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect, aff);\n  pTab->iPKey = -1;\n  if( db->mallocFailed ){\n    sqlite3DeleteTable(db, pTab);\n    return 0;\n  }\n  return pTab;\n}\n\n/*\n** Get a VDBE for the given parser context.  Create a new one if necessary.\n** If an error occurs, return NULL and leave a message in pParse.\n*/\nSQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){\n  if( pParse->pVdbe ){\n    return pParse->pVdbe;\n  }\n  if( pParse->pToplevel==0\n   && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)\n  ){\n    pParse->okConstFactor = 1;\n  }\n  return sqlite3VdbeCreate(pParse);\n}\n\n\n/*\n** Compute the iLimit and iOffset fields of the SELECT based on the\n** pLimit expressions.  pLimit->pLeft and pLimit->pRight hold the expressions\n** that appear in the original SQL statement after the LIMIT and OFFSET\n** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset \n** are the integer memory register numbers for counters used to compute \n** the limit and offset.  If there is no limit and/or offset, then \n** iLimit and iOffset are negative.\n**\n** This routine changes the values of iLimit and iOffset only if\n** a limit or offset is defined by pLimit->pLeft and pLimit->pRight.  iLimit\n** and iOffset should have been preset to appropriate default values (zero)\n** prior to calling this routine.\n**\n** The iOffset register (if it exists) is initialized to the value\n** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register\n** iOffset+1 is initialized to LIMIT+OFFSET.\n**\n** Only if pLimit->pLeft!=0 do the limit registers get\n** redefined.  The UNION ALL operator uses this property to force\n** the reuse of the same limit and offset registers across multiple\n** SELECT statements.\n*/\nstatic void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){\n  Vdbe *v = 0;\n  int iLimit = 0;\n  int iOffset;\n  int n;\n  Expr *pLimit = p->pLimit;\n\n  if( p->iLimit ) return;\n\n  /* \n  ** \"LIMIT -1\" always shows all rows.  There is some\n  ** controversy about what the correct behavior should be.\n  ** The current implementation interprets \"LIMIT 0\" to mean\n  ** no rows.\n  */\n  if( pLimit ){\n    assert( pLimit->op==TK_LIMIT );\n    assert( pLimit->pLeft!=0 );\n    p->iLimit = iLimit = ++pParse->nMem;\n    v = sqlite3GetVdbe(pParse);\n    assert( v!=0 );\n    if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){\n      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);\n      VdbeComment((v, \"LIMIT counter\"));\n      if( n==0 ){\n        sqlite3VdbeGoto(v, iBreak);\n      }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){\n        p->nSelectRow = sqlite3LogEst((u64)n);\n        p->selFlags |= SF_FixedLimit;\n      }\n    }else{\n      sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);\n      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);\n      VdbeComment((v, \"LIMIT counter\"));\n      sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);\n    }\n    if( pLimit->pRight ){\n      p->iOffset = iOffset = ++pParse->nMem;\n      pParse->nMem++;   /* Allocate an extra register for limit+offset */\n      sqlite3ExprCode(pParse, pLimit->pRight, iOffset);\n      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);\n      VdbeComment((v, \"OFFSET counter\"));\n      sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);\n      VdbeComment((v, \"LIMIT+OFFSET\"));\n    }\n  }\n}\n\n#ifndef SQLITE_OMIT_COMPOUND_SELECT\n/*\n** Return the appropriate collating sequence for the iCol-th column of\n** the result set for the compound-select statement \"p\".  Return NULL if\n** the column has no default collating sequence.\n**\n** The collating sequence for the compound select is taken from the\n** left-most term of the select that has a collating sequence.\n*/\nstatic CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){\n  CollSeq *pRet;\n  if( p->pPrior ){\n    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);\n  }else{\n    pRet = 0;\n  }\n  assert( iCol>=0 );\n  /* iCol must be less than p->pEList->nExpr.  Otherwise an error would\n  ** have been thrown during name resolution and we would not have gotten\n  ** this far */\n  if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){\n    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);\n  }\n  return pRet;\n}\n\n/*\n** The select statement passed as the second parameter is a compound SELECT\n** with an ORDER BY clause. This function allocates and returns a KeyInfo\n** structure suitable for implementing the ORDER BY.\n**\n** Space to hold the KeyInfo structure is obtained from malloc. The calling\n** function is responsible for ensuring that this structure is eventually\n** freed.\n*/\nstatic KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){\n  ExprList *pOrderBy = p->pOrderBy;\n  int nOrderBy = p->pOrderBy->nExpr;\n  sqlite3 *db = pParse->db;\n  KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);\n  if( pRet ){\n    int i;\n    for(i=0; i<nOrderBy; i++){\n      struct ExprList_item *pItem = &pOrderBy->a[i];\n      Expr *pTerm = pItem->pExpr;\n      CollSeq *pColl;\n\n      if( pTerm->flags & EP_Collate ){\n        pColl = sqlite3ExprCollSeq(pParse, pTerm);\n      }else{\n        pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);\n        if( pColl==0 ) pColl = db->pDfltColl;\n        pOrderBy->a[i].pExpr =\n          sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);\n      }\n      assert( sqlite3KeyInfoIsWriteable(pRet) );\n      pRet->aColl[i] = pColl;\n      pRet->aSortFlags[i] = pOrderBy->a[i].sortFlags;\n    }\n  }\n\n  return pRet;\n}\n\n#ifndef SQLITE_OMIT_CTE\n/*\n** This routine generates VDBE code to compute the content of a WITH RECURSIVE\n** query of the form:\n**\n**   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)\n**                         \\___________/             \\_______________/\n**                           p->pPrior                      p\n**\n**\n** There is exactly one reference to the recursive-table in the FROM clause\n** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.\n**\n** The setup-query runs once to generate an initial set of rows that go\n** into a Queue table.  Rows are extracted from the Queue table one by\n** one.  Each row extracted from Queue is output to pDest.  Then the single\n** extracted row (now in the iCurrent table) becomes the content of the\n** recursive-table for a recursive-query run.  The output of the recursive-query\n** is added back into the Queue table.  Then another row is extracted from Queue\n** and the iteration continues until the Queue table is empty.\n**\n** If the compound query operator is UNION then no duplicate rows are ever\n** inserted into the Queue table.  The iDistinct table keeps a copy of all rows\n** that have ever been inserted into Queue and causes duplicates to be\n** discarded.  If the operator is UNION ALL, then duplicates are allowed.\n** \n** If the query has an ORDER BY, then entries in the Queue table are kept in\n** ORDER BY order and the first entry is extracted for each cycle.  Without\n** an ORDER BY, the Queue table is just a FIFO.\n**\n** If a LIMIT clause is provided, then the iteration stops after LIMIT rows\n** have been output to pDest.  A LIMIT of zero means to output no rows and a\n** negative LIMIT means to output all rows.  If there is also an OFFSET clause\n** with a positive value, then the first OFFSET outputs are discarded rather\n** than being sent to pDest.  The LIMIT count does not begin until after OFFSET\n** rows have been skipped.\n*/\nstatic void generateWithRecursiveQuery(\n  Parse *pParse,        /* Parsing context */\n  Select *p,            /* The recursive SELECT to be coded */\n  SelectDest *pDest     /* What to do with query results */\n){\n  SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */\n  int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */\n  Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */\n  Select *pSetup = p->pPrior;   /* The setup query */\n  int addrTop;                  /* Top of the loop */\n  int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */\n  int iCurrent = 0;             /* The Current table */\n  int regCurrent;               /* Register holding Current table */\n  int iQueue;                   /* The Queue table */\n  int iDistinct = 0;            /* To ensure unique results if UNION */\n  int eDest = SRT_Fifo;         /* How to write to Queue */\n  SelectDest destQueue;         /* SelectDest targetting the Queue table */\n  int i;                        /* Loop counter */\n  int rc;                       /* Result code */\n  ExprList *pOrderBy;           /* The ORDER BY clause */\n  Expr *pLimit;                 /* Saved LIMIT and OFFSET */\n  int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */\n\n#ifndef SQLITE_OMIT_WINDOWFUNC\n  if( p->pWin ){\n    sqlite3ErrorMsg(pParse, \"cannot use window functions in recursive queries\");\n    return;\n  }\n#endif\n\n  /* Obtain authorization to do a recursive query */\n  if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;\n\n  /* Process the LIMIT and OFFSET clauses, if they exist */\n  addrBreak = sqlite3VdbeMakeLabel(pParse);\n  p->nSelectRow = 320;  /* 4 billion rows */\n  computeLimitRegisters(pParse, p, addrBreak);\n  pLimit = p->pLimit;\n  regLimit = p->iLimit;\n  regOffset = p->iOffset;\n  p->pLimit = 0;\n  p->iLimit = p->iOffset = 0;\n  pOrderBy = p->pOrderBy;\n\n  /* Locate the cursor number of the Current table */\n  for(i=0; ALWAYS(i<pSrc->nSrc); i++){\n    if( pSrc->a[i].fg.isRecursive ){\n      iCurrent = pSrc->a[i].iCursor;\n      break;\n    }\n  }\n\n  /* Allocate cursors numbers for Queue and Distinct.  The cursor number for\n  ** the Distinct table must be exactly one greater than Queue in order\n  ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */\n  iQueue = pParse->nTab++;\n  if( p->op==TK_UNION ){\n    eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;\n    iDistinct = pParse->nTab++;\n  }else{\n    eDest = pOrderBy ? SRT_Queue : SRT_Fifo;\n  }\n  sqlite3SelectDestInit(&destQueue, eDest, iQueue);\n\n  /* Allocate cursors for Current, Queue, and Distinct. */\n  regCurrent = ++pParse->nMem;\n  sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);\n  if( pOrderBy ){\n    KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);\n    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,\n                      (char*)pKeyInfo, P4_KEYINFO);\n    destQueue.pOrderBy = pOrderBy;\n  }else{\n    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);\n  }\n  VdbeComment((v, \"Queue table\"));\n  if( iDistinct ){\n    p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);\n    p->selFlags |= SF_UsesEphemeral;\n  }\n\n  /* Detach the ORDER BY clause from the compound SELECT */\n  p->pOrderBy = 0;\n\n  /* Store the results of the setup-query in Queue. */\n  pSetup->pNext = 0;\n  ExplainQueryPlan((pParse, 1, \"SETUP\"));\n  rc = sqlite3Select(pParse, pSetup, &destQueue);\n  pSetup->pNext = p;\n  if( rc ) goto end_of_recursive_query;\n\n  /* Find the next row in the Queue and output that row */\n  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);\n\n  /* Transfer the next row in Queue over to Current */\n  sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */\n  if( pOrderBy ){\n    sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);\n  }else{\n    sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);\n  }\n  sqlite3VdbeAddOp1(v, OP_Delete, iQueue);\n\n  /* Output the single row in Current */\n  addrCont = sqlite3VdbeMakeLabel(pParse);\n  codeOffset(v, regOffset, addrCont);\n  selectInnerLoop(pParse, p, iCurrent,\n      0, 0, pDest, addrCont, addrBreak);\n  if( regLimit ){\n    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);\n    VdbeCoverage(v);\n  }\n  sqlite3VdbeResolveLabel(v, addrCont);\n\n  /* Execute the recursive SELECT taking the single row in Current as\n  ** the value for the recursive-table. Store the results in the Queue.\n  */\n  if( p->selFlags & SF_Aggregate ){\n    sqlite3ErrorMsg(pParse, \"recursive aggregate queries not supported\");\n  }else{\n    p->pPrior = 0;\n    ExplainQueryPlan((pParse, 1, \"RECURSIVE STEP\"));\n    sqlite3Select(pParse, p, &destQueue);\n    assert( p->pPrior==0 );\n    p->pPrior = pSetup;\n  }\n\n  /* Keep running the loop until the Queue is empty */\n  sqlite3VdbeGoto(v, addrTop);\n  sqlite3VdbeResolveLabel(v, addrBreak);\n\nend_of_recursive_query:\n  sqlite3ExprListDelete(pParse->db, p->pOrderBy);\n  p->pOrderBy = pOrderBy;\n  p->pLimit = pLimit;\n  return;\n}\n#endif /* SQLITE_OMIT_CTE */\n\n/* Forward references */\nstatic int multiSelectOrderBy(\n  Parse *pParse,        /* Parsing context */\n  Select *p,            /* The right-most of SELECTs to be coded */\n  SelectDest *pDest     /* What to do with query results */\n);\n\n/*\n** Handle the special case of a compound-select that originates from a\n** VALUES clause.  By handling this as a special case, we avoid deep\n** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT\n** on a VALUES clause.\n**\n** Because the Select object originates from a VALUES clause:\n**   (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1\n**   (2) All terms are UNION ALL\n**   (3) There is no ORDER BY clause\n**\n** The \"LIMIT of exactly 1\" case of condition (1) comes about when a VALUES\n** clause occurs within scalar expression (ex: \"SELECT (VALUES(1),(2),(3))\").\n** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.\n** Since the limit is exactly 1, we only need to evalutes the left-most VALUES.\n*/\nstatic int multiSelectValues(\n  Parse *pParse,        /* Parsing context */\n  Select *p,            /* The right-most of SELECTs to be coded */\n  SelectDest *pDest     /* What to do with query results */\n){\n  int nRow = 1;\n  int rc = 0;\n  int bShowAll = p->pLimit==0;\n  assert( p->selFlags & SF_MultiValue );\n  do{\n    assert( p->selFlags & SF_Values );\n    assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );\n    assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );\n#ifndef SQLITE_OMIT_WINDOWFUNC\n    if( p->pWin ) return -1;\n#endif\n    if( p->pPrior==0 ) break;\n    assert( p->pPrior->pNext==p );\n    p = p->pPrior;\n    nRow += bShowAll;\n  }while(1);\n  ExplainQueryPlan((pParse, 0, \"SCAN %d CONSTANT ROW%s\", nRow,\n                    nRow==1 ? \"\" : \"S\"));\n  while( p ){\n    selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);\n    if( !bShowAll ) break;\n    p->nSelectRow = nRow;\n    p = p->pNext;\n  }\n  return rc;\n}\n\n/*\n** This routine is called to process a compound query form from\n** two or more separate queries using UNION, UNION ALL, EXCEPT, or\n** INTERSECT\n**\n** \"p\" points to the right-most of the two queries.  the query on the\n** left is p->pPrior.  The left query could also be a compound query\n** in which case this routine will be called recursively. \n**\n** The results of the total query are to be written into a destination\n** of type eDest with parameter iParm.\n**\n** Example 1:  Consider a three-way compound SQL statement.\n**\n**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3\n**\n** This statement is parsed up as follows:\n**\n**     SELECT c FROM t3\n**      |\n**      `----->  SELECT b FROM t2\n**                |\n**                `------>  SELECT a FROM t1\n**\n** The arrows in the diagram above represent the Select.pPrior pointer.\n** So if this routine is called with p equal to the t3 query, then\n** pPrior will be the t2 query.  p->op will be TK_UNION in this case.\n**\n** Notice that because of the way SQLite parses compound SELECTs, the\n** individual selects always group from left to right.\n*/\nstatic int multiSelect(\n  Parse *pParse,        /* Parsing context */\n  Select *p,            /* The right-most of SELECTs to be coded */\n  SelectDest *pDest     /* What to do with query results */\n){\n  int rc = SQLITE_OK;   /* Success code from a subroutine */\n  Select *pPrior;       /* Another SELECT immediately to our left */\n  Vdbe *v;              /* Generate code to this VDBE */\n  SelectDest dest;      /* Alternative data destination */\n  Select *pDelete = 0;  /* Chain of simple selects to delete */\n  sqlite3 *db;          /* Database connection */\n\n  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only\n  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.\n  */\n  assert( p && p->pPrior );  /* Calling function guarantees this much */\n  assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );\n  assert( p->selFlags & SF_Compound );\n  db = pParse->db;\n  pPrior = p->pPrior;\n  dest = *pDest;\n  if( pPrior->pOrderBy || pPrior->pLimit ){\n    sqlite3ErrorMsg(pParse,\"%s clause should come after %s not before\",\n      pPrior->pOrderBy!=0 ? \"ORDER BY\" : \"LIMIT\", selectOpName(p->op));\n    rc = 1;\n    goto multi_select_end;\n  }\n\n  v = sqlite3GetVdbe(pParse);\n  assert( v!=0 );  /* The VDBE already created by calling function */\n\n  /* Create the destination temporary table if necessary\n  */\n  if( dest.eDest==SRT_EphemTab ){\n    assert( p->pEList );\n    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);\n    dest.eDest = SRT_Table;\n  }\n\n  /* Special handling for a compound-select that originates as a VALUES clause.\n  */\n  if( p->selFlags & SF_MultiValue ){\n    rc = multiSelectValues(pParse, p, &dest);\n    if( rc>=0 ) goto multi_select_end;\n    rc = SQLITE_OK;\n  }\n\n  /* Make sure all SELECTs in the statement have the same number of elements\n  ** in their result sets.\n  */\n  assert( p->pEList && pPrior->pEList );\n  assert( p->pEList->nExpr==pPrior->pEList->nExpr );\n\n#ifndef SQLITE_OMIT_CTE\n  if( p->selFlags & SF_Recursive ){\n    generateWithRecursiveQuery(pParse, p, &dest);\n  }else\n#endif\n\n  /* Compound SELECTs that have an ORDER BY clause are handled separately.\n  */\n  if( p->pOrderBy ){\n    return multiSelectOrderBy(pParse, p, pDest);\n  }else{\n\n#ifndef SQLITE_OMIT_EXPLAIN\n    if( pPrior->pPrior==0 ){\n      ExplainQueryPlan((pParse, 1, \"COMPOUND QUERY\"));\n      ExplainQueryPlan((pParse, 1, \"LEFT-MOST SUBQUERY\"));\n    }\n#endif\n\n    /* Generate code for the left and right SELECT statements.\n    */\n    switch( p->op ){\n      case TK_ALL: {\n        int addr = 0;\n        int nLimit;\n        assert( !pPrior->pLimit );\n        pPrior->iLimit = p->iLimit;\n        pPrior->iOffset = p->iOffset;\n        pPrior->pLimit = p->pLimit;\n        rc = sqlite3Select(pParse, pPrior, &dest);\n        p->pLimit = 0;\n        if( rc ){\n          goto multi_select_end;\n        }\n        p->pPrior = 0;\n        p->iLimit = pPrior->iLimit;\n        p->iOffset = pPrior->iOffset;\n        if( p->iLimit ){\n          addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);\n          VdbeComment((v, \"Jump ahead if LIMIT reached\"));\n          if( p->iOffset ){\n            sqlite3VdbeAddOp3(v, OP_OffsetLimit,\n                              p->iLimit, p->iOffset+1, p->iOffset);\n          }\n        }\n        ExplainQueryPlan((pParse, 1, \"UNION ALL\"));\n        rc = sqlite3Select(pParse, p, &dest);\n        testcase( rc!=SQLITE_OK );\n        pDelete = p->pPrior;\n        p->pPrior = pPrior;\n        p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);\n        if( pPrior->pLimit\n         && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)\n         && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) \n        ){\n          p->nSelectRow = sqlite3LogEst((u64)nLimit);\n        }\n        if( addr ){\n          sqlite3VdbeJumpHere(v, addr);\n        }\n        break;\n      }\n      case TK_EXCEPT:\n      case TK_UNION: {\n        int unionTab;    /* Cursor number of the temp table holding result */\n        u8 op = 0;       /* One of the SRT_ operations to apply to self */\n        int priorOp;     /* The SRT_ operation to apply to prior selects */\n        Expr *pLimit;    /* Saved values of p->nLimit  */\n        int addr;\n        SelectDest uniondest;\n  \n        testcase( p->op==TK_EXCEPT );\n        testcase( p->op==TK_UNION );\n        priorOp = SRT_Union;\n        if( dest.eDest==priorOp ){\n          /* We can reuse a temporary table generated by a SELECT to our\n          ** right.\n          */\n          assert( p->pLimit==0 );      /* Not allowed on leftward elements */\n          unionTab = dest.iSDParm;\n        }else{\n          /* We will need to create our own temporary table to hold the\n          ** intermediate results.\n          */\n          unionTab = pParse->nTab++;\n          assert( p->pOrderBy==0 );\n          addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);\n          assert( p->addrOpenEphm[0] == -1 );\n          p->addrOpenEphm[0] = addr;\n          findRightmost(p)->selFlags |= SF_UsesEphemeral;\n          assert( p->pEList );\n        }\n  \n        /* Code the SELECT statements to our left\n        */\n        assert( !pPrior->pOrderBy );\n        sqlite3SelectDestInit(&uniondest, priorOp, unionTab);\n        rc = sqlite3Select(pParse, pPrior, &uniondest);\n        if( rc ){\n          goto multi_select_end;\n        }\n  \n        /* Code the current SELECT statement\n        */\n        if( p->op==TK_EXCEPT ){\n          op = SRT_Except;\n        }else{\n          assert( p->op==TK_UNION );\n          op = SRT_Union;\n        }\n        p->pPrior = 0;\n        pLimit = p->pLimit;\n        p->pLimit = 0;\n        uniondest.eDest = op;\n        ExplainQueryPlan((pParse, 1, \"%s USING TEMP B-TREE\",\n                          selectOpName(p->op)));\n        rc = sqlite3Select(pParse, p, &uniondest);\n        testcase( rc!=SQLITE_OK );\n        assert( p->pOrderBy==0 );\n        pDelete = p->pPrior;\n        p->pPrior = pPrior;\n        p->pOrderBy = 0;\n        if( p->op==TK_UNION ){\n          p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);\n        }\n        sqlite3ExprDelete(db, p->pLimit);\n        p->pLimit = pLimit;\n        p->iLimit = 0;\n        p->iOffset = 0;\n  \n        /* Convert the data in the temporary table into whatever form\n        ** it is that we currently need.\n        */\n        assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );\n        assert( p->pEList || db->mallocFailed );\n        if( dest.eDest!=priorOp && db->mallocFailed==0 ){\n          int iCont, iBreak, iStart;\n          iBreak = sqlite3VdbeMakeLabel(pParse);\n          iCont = sqlite3VdbeMakeLabel(pParse);\n          computeLimitRegisters(pParse, p, iBreak);\n          sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);\n          iStart = sqlite3VdbeCurrentAddr(v);\n          selectInnerLoop(pParse, p, unionTab,\n                          0, 0, &dest, iCont, iBreak);\n          sqlite3VdbeResolveLabel(v, iCont);\n          sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);\n          sqlite3VdbeResolveLabel(v, iBreak);\n          sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);\n        }\n        break;\n      }\n      default: assert( p->op==TK_INTERSECT ); {\n        int tab1, tab2;\n        int iCont, iBreak, iStart;\n        Expr *pLimit;\n        int addr;\n        SelectDest intersectdest;\n        int r1;\n  \n        /* INTERSECT is different from the others since it requires\n        ** two temporary tables.  Hence it has its own case.  Begin\n        ** by allocating the tables we will need.\n        */\n        tab1 = pParse->nTab++;\n        tab2 = pParse->nTab++;\n        assert( p->pOrderBy==0 );\n  \n        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);\n        assert( p->addrOpenEphm[0] == -1 );\n        p->addrOpenEphm[0] = addr;\n        findRightmost(p)->selFlags |= SF_UsesEphemeral;\n        assert( p->pEList );\n  \n        /* Code the SELECTs to our left into temporary table \"tab1\".\n        */\n        sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);\n        rc = sqlite3Select(pParse, pPrior, &intersectdest);\n        if( rc ){\n          goto multi_select_end;\n        }\n  \n        /* Code the current SELECT into temporary table \"tab2\"\n        */\n        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);\n        assert( p->addrOpenEphm[1] == -1 );\n        p->addrOpenEphm[1] = addr;\n        p->pPrior = 0;\n        pLimit = p->pLimit;\n        p->pLimit = 0;\n        intersectdest.iSDParm = tab2;\n        ExplainQueryPlan((pParse, 1, \"%s USING TEMP B-TREE\",\n                          selectOpName(p->op)));\n        rc = sqlite3Select(pParse, p, &intersectdest);\n        testcase( rc!=SQLITE_OK );\n        pDelete = p->pPrior;\n        p->pPrior = pPrior;\n        if( p->nSelectRow>pPrior->nSelectRow ){\n          p->nSelectRow = pPrior->nSelectRow;\n        }\n        sqlite3ExprDelete(db, p->pLimit);\n        p->pLimit = pLimit;\n  \n        /* Generate code to take the intersection of the two temporary\n        ** tables.\n        */\n        if( rc ) break;\n        assert( p->pEList );\n        iBreak = sqlite3VdbeMakeLabel(pParse);\n        iCont = sqlite3VdbeMakeLabel(pParse);\n        computeLimitRegisters(pParse, p, iBreak);\n        sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);\n        r1 = sqlite3GetTempReg(pParse);\n        iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);\n        sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);\n        VdbeCoverage(v);\n        sqlite3ReleaseTempReg(pParse, r1);\n        selectInnerLoop(pParse, p, tab1,\n                        0, 0, &dest, iCont, iBreak);\n        sqlite3VdbeResolveLabel(v, iCont);\n        sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);\n        sqlite3VdbeResolveLabel(v, iBreak);\n        sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);\n        sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);\n        break;\n      }\n    }\n  \n  #ifndef SQLITE_OMIT_EXPLAIN\n    if( p->pNext==0 ){\n      ExplainQueryPlanPop(pParse);\n    }\n  #endif\n  }\n  if( pParse->nErr ) goto multi_select_end;\n  \n  /* Compute collating sequences used by \n  ** temporary tables needed to implement the compound select.\n  ** Attach the KeyInfo structure to all temporary tables.\n  **\n  ** This section is run by the right-most SELECT statement only.\n  ** SELECT statements to the left always skip this part.  The right-most\n  ** SELECT might also skip this part if it has no ORDER BY clause and\n  ** no temp tables are required.\n  */\n  if( p->selFlags & SF_UsesEphemeral ){\n    int i;                        /* Loop counter */\n    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */\n    Select *pLoop;                /* For looping through SELECT statements */\n    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */\n    int nCol;                     /* Number of columns in result set */\n\n    assert( p->pNext==0 );\n    nCol = p->pEList->nExpr;\n    pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);\n    if( !pKeyInfo ){\n      rc = SQLITE_NOMEM_BKPT;\n      goto multi_select_end;\n    }\n    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){\n      *apColl = multiSelectCollSeq(pParse, p, i);\n      if( 0==*apColl ){\n        *apColl = db->pDfltColl;\n      }\n    }\n\n    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){\n      for(i=0; i<2; i++){\n        int addr = pLoop->addrOpenEphm[i];\n        if( addr<0 ){\n          /* If [0] is unused then [1] is also unused.  So we can\n          ** always safely abort as soon as the first unused slot is found */\n          assert( pLoop->addrOpenEphm[1]<0 );\n          break;\n        }\n        sqlite3VdbeChangeP2(v, addr, nCol);\n        sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),\n                            P4_KEYINFO);\n        pLoop->addrOpenEphm[i] = -1;\n      }\n    }\n    sqlite3KeyInfoUnref(pKeyInfo);\n  }\n\nmulti_select_end:\n  pDest->iSdst = dest.iSdst;\n  pDest->nSdst = dest.nSdst;\n  sqlite3SelectDelete(db, pDelete);\n  return rc;\n}\n#endif /* SQLITE_OMIT_COMPOUND_SELECT */\n\n/*\n** Error message for when two or more terms of a compound select have different\n** size result sets.\n*/\nSQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){\n  if( p->selFlags & SF_Values ){\n    sqlite3ErrorMsg(pParse, \"all VALUES must have the same number of terms\");\n  }else{\n    sqlite3ErrorMsg(pParse, \"SELECTs to the left and right of %s\"\n      \" do not have the same number of result columns\", selectOpName(p->op));\n  }\n}\n\n/*\n** Code an output subroutine for a coroutine implementation of a\n** SELECT statment.\n**\n** The data to be output is contained in pIn->iSdst.  There are\n** pIn->nSdst columns to be output.  pDest is where the output should\n** be sent.\n**\n** regReturn is the number of the register holding the subroutine\n** return address.\n**\n** If regPrev>0 then it is the first register in a vector that\n** records the previous output.  mem[regPrev] is a flag that is false\n** if there has been no previous output.  If regPrev>0 then code is\n** generated to suppress duplicates.  pKeyInfo is used for comparing\n** keys.\n**\n** If the LIMIT found in p->iLimit is reached, jump immediately to\n** iBreak.\n*/\nstatic int generateOutputSubroutine(\n  Parse *pParse,          /* Parsing context */\n  Select *p,              /* The SELECT statement */\n  SelectDest *pIn,        /* Coroutine supplying data */\n  SelectDest *pDest,      /* Where to send the data */\n  int regReturn,          /* The return address register */\n  int regPrev,            /* Previous result register.  No uniqueness if 0 */\n  KeyInfo *pKeyInfo,      /* For comparing with previous entry */\n  int iBreak              /* Jump here if we hit the LIMIT */\n){\n  Vdbe *v = pParse->pVdbe;\n  int iContinue;\n  int addr;\n\n  addr = sqlite3VdbeCurrentAddr(v);\n  iContinue = sqlite3VdbeMakeLabel(pParse);\n\n  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT \n  */\n  if( regPrev ){\n    int addr1, addr2;\n    addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);\n    addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,\n                              (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);\n    sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);\n    sqlite3VdbeJumpHere(v, addr1);\n    sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);\n    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);\n  }\n  if( pParse->db->mallocFailed ) return 0;\n\n  /* Suppress the first OFFSET entries if there is an OFFSET clause\n  */\n  codeOffset(v, p->iOffset, iContinue);\n\n  assert( pDest->eDest!=SRT_Exists );\n  assert( pDest->eDest!=SRT_Table );\n  switch( pDest->eDest ){\n    /* Store the result as data using a unique key.\n    */\n    case SRT_EphemTab: {\n      int r1 = sqlite3GetTempReg(pParse);\n      int r2 = sqlite3GetTempReg(pParse);\n      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);\n      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);\n      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);\n      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);\n      sqlite3ReleaseTempReg(pParse, r2);\n      sqlite3ReleaseTempReg(pParse, r1);\n      break;\n    }\n\n#ifndef SQLITE_OMIT_SUBQUERY\n    /* If we are creating a set for an \"expr IN (SELECT ...)\".\n    */\n    case SRT_Set: {\n      int r1;\n      testcase( pIn->nSdst>1 );\n      r1 = sqlite3GetTempReg(pParse);\n      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, \n          r1, pDest->zAffSdst, pIn->nSdst);\n      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,\n                           pIn->iSdst, pIn->nSdst);\n      sqlite3ReleaseTempReg(pParse, r1);\n      break;\n    }\n\n    /* If this is a scalar select that is part of an expression, then\n    ** store the results in the appropriate memory cell and break out\n    ** of the scan loop.  Note that the select might return multiple columns\n    ** if it is the RHS of a row-value IN operator.\n    */\n    case SRT_Mem: {\n      if( pParse->nErr==0 ){\n        testcase( pIn->nSdst>1 );\n        sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst);\n      }\n      /* The LIMIT clause will jump out of the loop for us */\n      break;\n    }\n#endif /* #ifndef SQLITE_OMIT_SUBQUERY */\n\n    /* The results are stored in a sequence of registers\n    ** starting at pDest->iSdst.  Then the co-routine yields.\n    */\n    case SRT_Coroutine: {\n      if( pDest->iSdst==0 ){\n        pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);\n        pDest->nSdst = pIn->nSdst;\n      }\n      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);\n      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);\n      break;\n    }\n\n    /* If none of the above, then the result destination must be\n    ** SRT_Output.  This routine is never called with any other\n    ** destination other than the ones handled above or SRT_Output.\n    **\n    ** For SRT_Output, results are stored in a sequence of registers.  \n    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to\n    ** return the next row of result.\n    */\n    default: {\n      assert( pDest->eDest==SRT_Output );\n      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);\n      break;\n    }\n  }\n\n  /* Jump to the end of the loop if the LIMIT is reached.\n  */\n  if( p->iLimit ){\n    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);\n  }\n\n  /* Generate the subroutine return\n  */\n  sqlite3VdbeResolveLabel(v, iContinue);\n  sqlite3VdbeAddOp1(v, OP_Return, regReturn);\n\n  return addr;\n}\n\n/*\n** Alternative compound select code generator for cases when there\n** is an ORDER BY clause.\n**\n** We assume a query of the following form:\n**\n**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>\n**\n** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea\n** is to code both <selectA> and <selectB> with the ORDER BY clause as\n** co-routines.  Then run the co-routines in parallel and merge the results\n** into the output.  In addition to the two coroutines (called selectA and\n** selectB) there are 7 subroutines:\n**\n**    outA:    Move the output of the selectA coroutine into the output\n**             of the compound query.\n**\n**    outB:    Move the output of the selectB coroutine into the output\n**             of the compound query.  (Only generated for UNION and\n**             UNION ALL.  EXCEPT and INSERTSECT never output a row that\n**             appears only in B.)\n**\n**    AltB:    Called when there is data from both coroutines and A<B.\n**\n**    AeqB:    Called when there is data from both coroutines and A==B.\n**\n**    AgtB:    Called when there is data from both coroutines and A>B.\n**\n**    EofA:    Called when data is exhausted from selectA.\n**\n**    EofB:    Called when data is exhausted from selectB.\n**\n** The implementation of the latter five subroutines depend on which \n** <operator> is used:\n**\n**\n**             UNION ALL         UNION            EXCEPT          INTERSECT\n**          -------------  -----------------  --------------  -----------------\n**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA\n**\n**   AeqB:   outA, nextA         nextA             nextA         outA, nextA\n**\n**   AgtB:   outB, nextB      outB, nextB          nextB            nextB\n**\n**   EofA:   outB, nextB      outB, nextB          halt             halt\n**\n**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt\n**\n** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA\n** causes an immediate jump to EofA and an EOF on B following nextB causes\n** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or\n** following nextX causes a jump to the end of the select processing.\n**\n** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled\n** within the output subroutine.  The regPrev register set holds the previously\n** output value.  A comparison is made against this value and the output\n** is skipped if the next results would be the same as the previous.\n**\n** The implementation plan is to implement the two coroutines and seven\n** subroutines first, then put the control logic at the bottom.  Like this:\n**\n**          goto Init\n**     coA: coroutine for left query (A)\n**     coB: coroutine for right query (B)\n**    outA: output one row of A\n**    outB: output one row of B (UNION and UNION ALL only)\n**    EofA: ...\n**    EofB: ...\n**    AltB: ...\n**    AeqB: ...\n**    AgtB: ...\n**    Init: initialize coroutine registers\n**          yield coA\n**          if eof(A) goto EofA\n**          yield coB\n**          if eof(B) goto EofB\n**    Cmpr: Compare A, B\n**          Jump AltB, AeqB, AgtB\n**     End: ...\n**\n** We call AltB, AeqB, AgtB, EofA, and EofB \"subroutines\" but they are not\n** actually called using Gosub and they do not Return.  EofA and EofB loop\n** until all data is exhausted then jump to the \"end\" labe.  AltB, AeqB,\n** and AgtB jump to either L2 or to one of EofA or EofB.\n*/\n#ifndef SQLITE_OMIT_COMPOUND_SELECT\nstatic int multiSelectOrderBy(\n  Parse *pParse,        /* Parsing context */\n  Select *p,            /* The right-most of SELECTs to be coded */\n  SelectDest *pDest     /* What to do with query results */\n){\n  int i, j;             /* Loop counters */\n  Select *pPrior;       /* Another SELECT immediately to our left */\n  Vdbe *v;              /* Generate code to this VDBE */\n  SelectDest destA;     /* Destination for coroutine A */\n  SelectDest destB;     /* Destination for coroutine B */\n  int regAddrA;         /* Address register for select-A coroutine */\n  int regAddrB;         /* Address register for select-B coroutine */\n  int addrSelectA;      /* Address of the select-A coroutine */\n  int addrSelectB;      /* Address of the select-B coroutine */\n  int regOutA;          /* Address register for the output-A subroutine */\n  int regOutB;          /* Address register for the output-B subroutine */\n  int addrOutA;         /* Address of the output-A subroutine */\n  int addrOutB = 0;     /* Address of the output-B subroutine */\n  int addrEofA;         /* Address of the select-A-exhausted subroutine */\n  int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */\n  int addrEofB;         /* Address of the select-B-exhausted subroutine */\n  int addrAltB;         /* Address of the A<B subroutine */\n  int addrAeqB;         /* Address of the A==B subroutine */\n  int addrAgtB;         /* Address of the A>B subroutine */\n  int regLimitA;        /* Limit register for select-A */\n  int regLimitB;        /* Limit register for select-A */\n  int regPrev;          /* A range of registers to hold previous output */\n  int savedLimit;       /* Saved value of p->iLimit */\n  int savedOffset;      /* Saved value of p->iOffset */\n  int labelCmpr;        /* Label for the start of the merge algorithm */\n  int labelEnd;         /* Label for the end of the overall SELECT stmt */\n  int addr1;            /* Jump instructions that get retargetted */\n  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */\n  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */\n  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */\n  sqlite3 *db;          /* Database connection */\n  ExprList *pOrderBy;   /* The ORDER BY clause */\n  int nOrderBy;         /* Number of terms in the ORDER BY clause */\n  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */\n\n  assert( p->pOrderBy!=0 );\n  assert( pKeyDup==0 ); /* \"Managed\" code needs this.  Ticket #3382. */\n  db = pParse->db;\n  v = pParse->pVdbe;\n  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */\n  labelEnd = sqlite3VdbeMakeLabel(pParse);\n  labelCmpr = sqlite3VdbeMakeLabel(pParse);\n\n\n  /* Patch up the ORDER BY clause\n  */\n  op = p->op;  \n  pPrior = p->pPrior;\n  assert( pPrior->pOrderBy==0 );\n  pOrderBy = p->pOrderBy;\n  assert( pOrderBy );\n  nOrderBy = pOrderBy->nExpr;\n\n  /* For operators other than UNION ALL we have to make sure that\n  ** the ORDER BY clause covers every term of the result set.  Add\n  ** terms to the ORDER BY clause as necessary.\n  */\n  if( op!=TK_ALL ){\n    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){\n      struct ExprList_item *pItem;\n      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){\n        assert( pItem->u.x.iOrderByCol>0 );\n        if( pItem->u.x.iOrderByCol==i ) break;\n      }\n      if( j==nOrderBy ){\n        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);\n        if( pNew==0 ) return SQLITE_NOMEM_BKPT;\n        pNew->flags |= EP_IntValue;\n        pNew->u.iValue = i;\n        p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);\n        if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;\n      }\n    }\n  }\n\n  /* Compute the comparison permutation and keyinfo that is used with\n  ** the permutation used to determine if the next\n  ** row of results comes from selectA or selectB.  Also add explicit\n  ** collations to the ORDER BY clause terms so that when the subqueries\n  ** to the right and the left are evaluated, they use the correct\n  ** collation.\n  */\n  aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));\n  if( aPermute ){\n    struct ExprList_item *pItem;\n    aPermute[0] = nOrderBy;\n    for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){\n      assert( pItem->u.x.iOrderByCol>0 );\n      assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );\n      aPermute[i] = pItem->u.x.iOrderByCol - 1;\n    }\n    pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);\n  }else{\n    pKeyMerge = 0;\n  }\n\n  /* Reattach the ORDER BY clause to the query.\n  */\n  p->pOrderBy = pOrderBy;\n  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);\n\n  /* Allocate a range of temporary registers and the KeyInfo needed\n  ** for the logic that removes duplicate result rows when the\n  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).\n  */\n  if( op==TK_ALL ){\n    regPrev = 0;\n  }else{\n    int nExpr = p->pEList->nExpr;\n    assert( nOrderBy>=nExpr || db->mallocFailed );\n    regPrev = pParse->nMem+1;\n    pParse->nMem += nExpr+1;\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);\n    pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);\n    if( pKeyDup ){\n      assert( sqlite3KeyInfoIsWriteable(pKeyDup) );\n      for(i=0; i<nExpr; i++){\n        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);\n        pKeyDup->aSortFlags[i] = 0;\n      }\n    }\n  }\n \n  /* Separate the left and the right query from one another\n  */\n  p->pPrior = 0;\n  pPrior->pNext = 0;\n  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, \"ORDER\");\n  if( pPrior->pPrior==0 ){\n    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, \"ORDER\");\n  }\n\n  /* Compute the limit registers */\n  computeLimitRegisters(pParse, p, labelEnd);\n  if( p->iLimit && op==TK_ALL ){\n    regLimitA = ++pParse->nMem;\n    regLimitB = ++pParse->nMem;\n    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,\n                                  regLimitA);\n    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);\n  }else{\n    regLimitA = regLimitB = 0;\n  }\n  sqlite3ExprDelete(db, p->pLimit);\n  p->pLimit = 0;\n\n  regAddrA = ++pParse->nMem;\n  regAddrB = ++pParse->nMem;\n  regOutA = ++pParse->nMem;\n  regOutB = ++pParse->nMem;\n  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);\n  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);\n\n  ExplainQueryPlan((pParse, 1, \"MERGE (%s)\", selectOpName(p->op)));\n\n  /* Generate a coroutine to evaluate the SELECT statement to the\n  ** left of the compound operator - the \"A\" select.\n  */\n  addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;\n  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);\n  VdbeComment((v, \"left SELECT\"));\n  pPrior->iLimit = regLimitA;\n  ExplainQueryPlan((pParse, 1, \"LEFT\"));\n  sqlite3Select(pParse, pPrior, &destA);\n  sqlite3VdbeEndCoroutine(v, regAddrA);\n  sqlite3VdbeJumpHere(v, addr1);\n\n  /* Generate a coroutine to evaluate the SELECT statement on \n  ** the right - the \"B\" select\n  */\n  addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;\n  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);\n  VdbeComment((v, \"right SELECT\"));\n  savedLimit = p->iLimit;\n  savedOffset = p->iOffset;\n  p->iLimit = regLimitB;\n  p->iOffset = 0;  \n  ExplainQueryPlan((pParse, 1, \"RIGHT\"));\n  sqlite3Select(pParse, p, &destB);\n  p->iLimit = savedLimit;\n  p->iOffset = savedOffset;\n  sqlite3VdbeEndCoroutine(v, regAddrB);\n\n  /* Generate a subroutine that outputs the current row of the A\n  ** select as the next output row of the compound select.\n  */\n  VdbeNoopComment((v, \"Output routine for A\"));\n  addrOutA = generateOutputSubroutine(pParse,\n                 p, &destA, pDest, regOutA,\n                 regPrev, pKeyDup, labelEnd);\n  \n  /* Generate a subroutine that outputs the current row of the B\n  ** select as the next output row of the compound select.\n  */\n  if( op==TK_ALL || op==TK_UNION ){\n    VdbeNoopComment((v, \"Output routine for B\"));\n    addrOutB = generateOutputSubroutine(pParse,\n                 p, &destB, pDest, regOutB,\n                 regPrev, pKeyDup, labelEnd);\n  }\n  sqlite3KeyInfoUnref(pKeyDup);\n\n  /* Generate a subroutine to run when the results from select A\n  ** are exhausted and only data in select B remains.\n  */\n  if( op==TK_EXCEPT || op==TK_INTERSECT ){\n    addrEofA_noB = addrEofA = labelEnd;\n  }else{  \n    VdbeNoopComment((v, \"eof-A subroutine\"));\n    addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);\n    addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);\n                                     VdbeCoverage(v);\n    sqlite3VdbeGoto(v, addrEofA);\n    p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);\n  }\n\n  /* Generate a subroutine to run when the results from select B\n  ** are exhausted and only data in select A remains.\n  */\n  if( op==TK_INTERSECT ){\n    addrEofB = addrEofA;\n    if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;\n  }else{  \n    VdbeNoopComment((v, \"eof-B subroutine\"));\n    addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);\n    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);\n    sqlite3VdbeGoto(v, addrEofB);\n  }\n\n  /* Generate code to handle the case of A<B\n  */\n  VdbeNoopComment((v, \"A-lt-B subroutine\"));\n  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);\n  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);\n  sqlite3VdbeGoto(v, labelCmpr);\n\n  /* Generate code to handle the case of A==B\n  */\n  if( op==TK_ALL ){\n    addrAeqB = addrAltB;\n  }else if( op==TK_INTERSECT ){\n    addrAeqB = addrAltB;\n    addrAltB++;\n  }else{\n    VdbeNoopComment((v, \"A-eq-B subroutine\"));\n    addrAeqB =\n    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);\n    sqlite3VdbeGoto(v, labelCmpr);\n  }\n\n  /* Generate code to handle the case of A>B\n  */\n  VdbeNoopComment((v, \"A-gt-B subroutine\"));\n  addrAgtB = sqlite3VdbeCurrentAddr(v);\n  if( op==TK_ALL || op==TK_UNION ){\n    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);\n  }\n  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);\n  sqlite3VdbeGoto(v, labelCmpr);\n\n  /* This code runs once to initialize everything.\n  */\n  sqlite3VdbeJumpHere(v, addr1);\n  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);\n  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);\n\n  /* Implement the main merge loop\n  */\n  sqlite3VdbeResolveLabel(v, labelCmpr);\n  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);\n  sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,\n                         (char*)pKeyMerge, P4_KEYINFO);\n  sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);\n  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);\n\n  /* Jump to the this point in order to terminate the query.\n  */\n  sqlite3VdbeResolveLabel(v, labelEnd);\n\n  /* Reassembly the compound query so that it will be freed correctly\n  ** by the calling function */\n  if( p->pPrior ){\n    sqlite3SelectDelete(db, p->pPrior);\n  }\n  p->pPrior = pPrior;\n  pPrior->pNext = p;\n\n  /*** TBD:  Insert subroutine calls to close cursors on incomplete\n  **** subqueries ****/\n  ExplainQueryPlanPop(pParse);\n  return pParse->nErr!=0;\n}\n#endif\n\n#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)\n\n/* An instance of the SubstContext object describes an substitution edit\n** to be performed on a parse tree.\n**\n** All references to columns in table iTable are to be replaced by corresponding\n** expressions in pEList.\n*/\ntypedef struct SubstContext {\n  Parse *pParse;            /* The parsing context */\n  int iTable;               /* Replace references to this table */\n  int iNewTable;            /* New table number */\n  int isLeftJoin;           /* Add TK_IF_NULL_ROW opcodes on each replacement */\n  ExprList *pEList;         /* Replacement expressions */\n} SubstContext;\n\n/* Forward Declarations */\nstatic void substExprList(SubstContext*, ExprList*);\nstatic void substSelect(SubstContext*, Select*, int);\n\n/*\n** Scan through the expression pExpr.  Replace every reference to\n** a column in table number iTable with a copy of the iColumn-th\n** entry in pEList.  (But leave references to the ROWID column \n** unchanged.)\n**\n** This routine is part of the flattening procedure.  A subquery\n** whose result set is defined by pEList appears as entry in the\n** FROM clause of a SELECT such that the VDBE cursor assigned to that\n** FORM clause entry is iTable.  This routine makes the necessary \n** changes to pExpr so that it refers directly to the source table\n** of the subquery rather the result set of the subquery.\n*/\nstatic Expr *substExpr(\n  SubstContext *pSubst,  /* Description of the substitution */\n  Expr *pExpr            /* Expr in which substitution occurs */\n){\n  if( pExpr==0 ) return 0;\n  if( ExprHasProperty(pExpr, EP_FromJoin)\n   && pExpr->iRightJoinTable==pSubst->iTable\n  ){\n    pExpr->iRightJoinTable = pSubst->iNewTable;\n  }\n  if( pExpr->op==TK_COLUMN\n   && pExpr->iTable==pSubst->iTable\n   && !ExprHasProperty(pExpr, EP_FixedCol)\n  ){\n    if( pExpr->iColumn<0 ){\n      pExpr->op = TK_NULL;\n    }else{\n      Expr *pNew;\n      Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;\n      Expr ifNullRow;\n      assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );\n      assert( pExpr->pRight==0 );\n      if( sqlite3ExprIsVector(pCopy) ){\n        sqlite3VectorErrorMsg(pSubst->pParse, pCopy);\n      }else{\n        sqlite3 *db = pSubst->pParse->db;\n        if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){\n          memset(&ifNullRow, 0, sizeof(ifNullRow));\n          ifNullRow.op = TK_IF_NULL_ROW;\n          ifNullRow.pLeft = pCopy;\n          ifNullRow.iTable = pSubst->iNewTable;\n          ifNullRow.flags = EP_Skip;\n          pCopy = &ifNullRow;\n        }\n        testcase( ExprHasProperty(pCopy, EP_Subquery) );\n        pNew = sqlite3ExprDup(db, pCopy, 0);\n        if( pNew && pSubst->isLeftJoin ){\n          ExprSetProperty(pNew, EP_CanBeNull);\n        }\n        if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){\n          pNew->iRightJoinTable = pExpr->iRightJoinTable;\n          ExprSetProperty(pNew, EP_FromJoin);\n        }\n        sqlite3ExprDelete(db, pExpr);\n        pExpr = pNew;\n\n        /* Ensure that the expression now has an implicit collation sequence,\n        ** just as it did when it was a column of a view or sub-query. */\n        if( pExpr ){\n          if( pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE ){\n            CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse, pExpr);\n            pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr, \n                (pColl ? pColl->zName : \"BINARY\")\n            );\n          }\n          ExprClearProperty(pExpr, EP_Collate);\n        }\n      }\n    }\n  }else{\n    if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){\n      pExpr->iTable = pSubst->iNewTable;\n    }\n    pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);\n    pExpr->pRight = substExpr(pSubst, pExpr->pRight);\n    if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n      substSelect(pSubst, pExpr->x.pSelect, 1);\n    }else{\n      substExprList(pSubst, pExpr->x.pList);\n    }\n#ifndef SQLITE_OMIT_WINDOWFUNC\n    if( ExprHasProperty(pExpr, EP_WinFunc) ){\n      Window *pWin = pExpr->y.pWin;\n      pWin->pFilter = substExpr(pSubst, pWin->pFilter);\n      substExprList(pSubst, pWin->pPartition);\n      substExprList(pSubst, pWin->pOrderBy);\n    }\n#endif\n  }\n  return pExpr;\n}\nstatic void substExprList(\n  SubstContext *pSubst, /* Description of the substitution */\n  ExprList *pList       /* List to scan and in which to make substitutes */\n){\n  int i;\n  if( pList==0 ) return;\n  for(i=0; i<pList->nExpr; i++){\n    pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);\n  }\n}\nstatic void substSelect(\n  SubstContext *pSubst, /* Description of the substitution */\n  Select *p,            /* SELECT statement in which to make substitutions */\n  int doPrior           /* Do substitutes on p->pPrior too */\n){\n  SrcList *pSrc;\n  struct SrcList_item *pItem;\n  int i;\n  if( !p ) return;\n  do{\n    substExprList(pSubst, p->pEList);\n    substExprList(pSubst, p->pGroupBy);\n    substExprList(pSubst, p->pOrderBy);\n    p->pHaving = substExpr(pSubst, p->pHaving);\n    p->pWhere = substExpr(pSubst, p->pWhere);\n    pSrc = p->pSrc;\n    assert( pSrc!=0 );\n    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){\n      substSelect(pSubst, pItem->pSelect, 1);\n      if( pItem->fg.isTabFunc ){\n        substExprList(pSubst, pItem->u1.pFuncArg);\n      }\n    }\n  }while( doPrior && (p = p->pPrior)!=0 );\n}\n#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */\n\n#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)\n/*\n** pSelect is a SELECT statement and pSrcItem is one item in the FROM\n** clause of that SELECT.\n**\n** This routine scans the entire SELECT statement and recomputes the\n** pSrcItem->colUsed mask.\n*/\nstatic int recomputeColumnsUsedExpr(Walker *pWalker, Expr *pExpr){\n  struct SrcList_item *pItem;\n  if( pExpr->op!=TK_COLUMN ) return WRC_Continue;\n  pItem = pWalker->u.pSrcItem;\n  if( pItem->iCursor!=pExpr->iTable ) return WRC_Continue;\n  if( pExpr->iColumn<0 ) return WRC_Continue;\n  pItem->colUsed |= sqlite3ExprColUsed(pExpr);\n  return WRC_Continue;\n}\nstatic void recomputeColumnsUsed(\n  Select *pSelect,                 /* The complete SELECT statement */\n  struct SrcList_item *pSrcItem    /* Which FROM clause item to recompute */\n){\n  Walker w;\n  if( NEVER(pSrcItem->pTab==0) ) return;\n  memset(&w, 0, sizeof(w));\n  w.xExprCallback = recomputeColumnsUsedExpr;\n  w.xSelectCallback = sqlite3SelectWalkNoop;\n  w.u.pSrcItem = pSrcItem;\n  pSrcItem->colUsed = 0;\n  sqlite3WalkSelect(&w, pSelect);\n}\n#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */\n\n#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)\n/*\n** This routine attempts to flatten subqueries as a performance optimization.\n** This routine returns 1 if it makes changes and 0 if no flattening occurs.\n**\n** To understand the concept of flattening, consider the following\n** query:\n**\n**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5\n**\n** The default way of implementing this query is to execute the\n** subquery first and store the results in a temporary table, then\n** run the outer query on that temporary table.  This requires two\n** passes over the data.  Furthermore, because the temporary table\n** has no indices, the WHERE clause on the outer query cannot be\n** optimized.\n**\n** This routine attempts to rewrite queries such as the above into\n** a single flat select, like this:\n**\n**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5\n**\n** The code generated for this simplification gives the same result\n** but only has to scan the data once.  And because indices might \n** exist on the table t1, a complete scan of the data might be\n** avoided.\n**\n** Flattening is subject to the following constraints:\n**\n**  (**)  We no longer attempt to flatten aggregate subqueries. Was:\n**        The subquery and the outer query cannot both be aggregates.\n**\n**  (**)  We no longer attempt to flatten aggregate subqueries. Was:\n**        (2) If the subquery is an aggregate then\n**        (2a) the outer query must not be a join and\n**        (2b) the outer query must not use subqueries\n**             other than the one FROM-clause subquery that is a candidate\n**             for flattening.  (This is due to ticket [2f7170d73bf9abf80]\n**             from 2015-02-09.)\n**\n**   (3)  If the subquery is the right operand of a LEFT JOIN then\n**        (3a) the subquery may not be a join and\n**        (3b) the FROM clause of the subquery may not contain a virtual\n**             table and\n**        (3c) the outer query may not be an aggregate.\n**        (3d) the outer query may not be DISTINCT.\n**\n**   (4)  The subquery can not be DISTINCT.\n**\n**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT\n**        sub-queries that were excluded from this optimization. Restriction \n**        (4) has since been expanded to exclude all DISTINCT subqueries.\n**\n**  (**)  We no longer attempt to flatten aggregate subqueries.  Was:\n**        If the subquery is aggregate, the outer query may not be DISTINCT.\n**\n**   (7)  The subquery must have a FROM clause.  TODO:  For subqueries without\n**        A FROM clause, consider adding a FROM clause with the special\n**        table sqlite_once that consists of a single row containing a\n**        single NULL.\n**\n**   (8)  If the subquery uses LIMIT then the outer query may not be a join.\n**\n**   (9)  If the subquery uses LIMIT then the outer query may not be aggregate.\n**\n**  (**)  Restriction (10) was removed from the code on 2005-02-05 but we\n**        accidently carried the comment forward until 2014-09-15.  Original\n**        constraint: \"If the subquery is aggregate then the outer query \n**        may not use LIMIT.\"\n**\n**  (11)  The subquery and the outer query may not both have ORDER BY clauses.\n**\n**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously\n**        a separate restriction deriving from ticket #350.\n**\n**  (13)  The subquery and outer query may not both use LIMIT.\n**\n**  (14)  The subquery may not use OFFSET.\n**\n**  (15)  If the outer query is part of a compound select, then the\n**        subquery may not use LIMIT.\n**        (See ticket #2339 and ticket [02a8e81d44]).\n**\n**  (16)  If the outer query is aggregate, then the subquery may not\n**        use ORDER BY.  (Ticket #2942)  This used to not matter\n**        until we introduced the group_concat() function.  \n**\n**  (17)  If the subquery is a compound select, then\n**        (17a) all compound operators must be a UNION ALL, and\n**        (17b) no terms within the subquery compound may be aggregate\n**              or DISTINCT, and\n**        (17c) every term within the subquery compound must have a FROM clause\n**        (17d) the outer query may not be\n**              (17d1) aggregate, or\n**              (17d2) DISTINCT, or\n**              (17d3) a join.\n**        (17e) the subquery may not contain window functions\n**\n**        The parent and sub-query may contain WHERE clauses. Subject to\n**        rules (11), (13) and (14), they may also contain ORDER BY,\n**        LIMIT and OFFSET clauses.  The subquery cannot use any compound\n**        operator other than UNION ALL because all the other compound\n**        operators have an implied DISTINCT which is disallowed by\n**        restriction (4).\n**\n**        Also, each component of the sub-query must return the same number\n**        of result columns. This is actually a requirement for any compound\n**        SELECT statement, but all the code here does is make sure that no\n**        such (illegal) sub-query is flattened. The caller will detect the\n**        syntax error and return a detailed message.\n**\n**  (18)  If the sub-query is a compound select, then all terms of the\n**        ORDER BY clause of the parent must be simple references to \n**        columns of the sub-query.\n**\n**  (19)  If the subquery uses LIMIT then the outer query may not\n**        have a WHERE clause.\n**\n**  (20)  If the sub-query is a compound select, then it must not use\n**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint\n**        somewhat by saying that the terms of the ORDER BY clause must\n**        appear as unmodified result columns in the outer query.  But we\n**        have other optimizations in mind to deal with that case.\n**\n**  (21)  If the subquery uses LIMIT then the outer query may not be\n**        DISTINCT.  (See ticket [752e1646fc]).\n**\n**  (22)  The subquery may not be a recursive CTE.\n**\n**  (**)  Subsumed into restriction (17d3).  Was: If the outer query is\n**        a recursive CTE, then the sub-query may not be a compound query.\n**        This restriction is because transforming the\n**        parent to a compound query confuses the code that handles\n**        recursive queries in multiSelect().\n**\n**  (**)  We no longer attempt to flatten aggregate subqueries.  Was:\n**        The subquery may not be an aggregate that uses the built-in min() or \n**        or max() functions.  (Without this restriction, a query like:\n**        \"SELECT x FROM (SELECT max(y), x FROM t1)\" would not necessarily\n**        return the value X for which Y was maximal.)\n**\n**  (25)  If either the subquery or the parent query contains a window\n**        function in the select list or ORDER BY clause, flattening\n**        is not attempted.\n**\n**\n** In this routine, the \"p\" parameter is a pointer to the outer query.\n** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query\n** uses aggregates.\n**\n** If flattening is not attempted, this routine is a no-op and returns 0.\n** If flattening is attempted this routine returns 1.\n**\n** All of the expression analysis must occur on both the outer query and\n** the subquery before this routine runs.\n*/\nstatic int flattenSubquery(\n  Parse *pParse,       /* Parsing context */\n  Select *p,           /* The parent or outer SELECT statement */\n  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */\n  int isAgg            /* True if outer SELECT uses aggregate functions */\n){\n  const char *zSavedAuthContext = pParse->zAuthContext;\n  Select *pParent;    /* Current UNION ALL term of the other query */\n  Select *pSub;       /* The inner query or \"subquery\" */\n  Select *pSub1;      /* Pointer to the rightmost select in sub-query */\n  SrcList *pSrc;      /* The FROM clause of the outer query */\n  SrcList *pSubSrc;   /* The FROM clause of the subquery */\n  int iParent;        /* VDBE cursor number of the pSub result set temp table */\n  int iNewParent = -1;/* Replacement table for iParent */\n  int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */    \n  int i;              /* Loop counter */\n  Expr *pWhere;                    /* The WHERE clause */\n  struct SrcList_item *pSubitem;   /* The subquery */\n  sqlite3 *db = pParse->db;\n  Walker w;                        /* Walker to persist agginfo data */\n\n  /* Check to see if flattening is permitted.  Return 0 if not.\n  */\n  assert( p!=0 );\n  assert( p->pPrior==0 );\n  if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;\n  pSrc = p->pSrc;\n  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );\n  pSubitem = &pSrc->a[iFrom];\n  iParent = pSubitem->iCursor;\n  pSub = pSubitem->pSelect;\n  assert( pSub!=0 );\n\n#ifndef SQLITE_OMIT_WINDOWFUNC\n  if( p->pWin || pSub->pWin ) return 0;                  /* Restriction (25) */\n#endif\n\n  pSubSrc = pSub->pSrc;\n  assert( pSubSrc );\n  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,\n  ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET\n  ** because they could be computed at compile-time.  But when LIMIT and OFFSET\n  ** became arbitrary expressions, we were forced to add restrictions (13)\n  ** and (14). */\n  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */\n  if( pSub->pLimit && pSub->pLimit->pRight ) return 0;   /* Restriction (14) */\n  if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){\n    return 0;                                            /* Restriction (15) */\n  }\n  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */\n  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (4)  */\n  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){\n     return 0;         /* Restrictions (8)(9) */\n  }\n  if( p->pOrderBy && pSub->pOrderBy ){\n     return 0;                                           /* Restriction (11) */\n  }\n  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */\n  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */\n  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){\n     return 0;         /* Restriction (21) */\n  }\n  if( pSub->selFlags & (SF_Recursive) ){\n    return 0; /* Restrictions (22) */\n  }\n\n  /*\n  ** If the subquery is the right operand of a LEFT JOIN, then the\n  ** subquery may not be a join itself (3a). Example of why this is not\n  ** allowed:\n  **\n  **         t1 LEFT OUTER JOIN (t2 JOIN t3)\n  **\n  ** If we flatten the above, we would get\n  **\n  **         (t1 LEFT OUTER JOIN t2) JOIN t3\n  **\n  ** which is not at all the same thing.\n  **\n  ** If the subquery is the right operand of a LEFT JOIN, then the outer\n  ** query cannot be an aggregate. (3c)  This is an artifact of the way\n  ** aggregates are processed - there is no mechanism to determine if\n  ** the LEFT JOIN table should be all-NULL.\n  **\n  ** See also tickets #306, #350, and #3300.\n  */\n  if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){\n    isLeftJoin = 1;\n    if( pSubSrc->nSrc>1                   /* (3a) */\n     || isAgg                             /* (3b) */\n     || IsVirtual(pSubSrc->a[0].pTab)     /* (3c) */\n     || (p->selFlags & SF_Distinct)!=0    /* (3d) */\n    ){\n      return 0;\n    }\n  }\n#ifdef SQLITE_EXTRA_IFNULLROW\n  else if( iFrom>0 && !isAgg ){\n    /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for\n    ** every reference to any result column from subquery in a join, even\n    ** though they are not necessary.  This will stress-test the OP_IfNullRow \n    ** opcode. */\n    isLeftJoin = -1;\n  }\n#endif\n\n  /* Restriction (17): If the sub-query is a compound SELECT, then it must\n  ** use only the UNION ALL operator. And none of the simple select queries\n  ** that make up the compound SELECT are allowed to be aggregate or distinct\n  ** queries.\n  */\n  if( pSub->pPrior ){\n    if( pSub->pOrderBy ){\n      return 0;  /* Restriction (20) */\n    }\n    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){\n      return 0; /* (17d1), (17d2), or (17d3) */\n    }\n    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){\n      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );\n      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );\n      assert( pSub->pSrc!=0 );\n      assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );\n      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0    /* (17b) */\n       || (pSub1->pPrior && pSub1->op!=TK_ALL)                 /* (17a) */\n       || pSub1->pSrc->nSrc<1                                  /* (17c) */\n#ifndef SQLITE_OMIT_WINDOWFUNC\n       || pSub1->pWin                                          /* (17e) */\n#endif\n      ){\n        return 0;\n      }\n      testcase( pSub1->pSrc->nSrc>1 );\n    }\n\n    /* Restriction (18). */\n    if( p->pOrderBy ){\n      int ii;\n      for(ii=0; ii<p->pOrderBy->nExpr; ii++){\n        if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;\n      }\n    }\n  }\n\n  /* Ex-restriction (23):\n  ** The only way that the recursive part of a CTE can contain a compound\n  ** subquery is for the subquery to be one term of a join.  But if the\n  ** subquery is a join, then the flattening has already been stopped by\n  ** restriction (17d3)\n  */\n  assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );\n\n  /***** If we reach this point, flattening is permitted. *****/\n  SELECTTRACE(1,pParse,p,(\"flatten %u.%p from term %d\\n\",\n                   pSub->selId, pSub, iFrom));\n\n  /* Authorize the subquery */\n  pParse->zAuthContext = pSubitem->zName;\n  TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);\n  testcase( i==SQLITE_DENY );\n  pParse->zAuthContext = zSavedAuthContext;\n\n  /* If the sub-query is a compound SELECT statement, then (by restrictions\n  ** 17 and 18 above) it must be a UNION ALL and the parent query must \n  ** be of the form:\n  **\n  **     SELECT <expr-list> FROM (<sub-query>) <where-clause> \n  **\n  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block\n  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or \n  ** OFFSET clauses and joins them to the left-hand-side of the original\n  ** using UNION ALL operators. In this case N is the number of simple\n  ** select statements in the compound sub-query.\n  **\n  ** Example:\n  **\n  **     SELECT a+1 FROM (\n  **        SELECT x FROM tab\n  **        UNION ALL\n  **        SELECT y FROM tab\n  **        UNION ALL\n  **        SELECT abs(z*2) FROM tab2\n  **     ) WHERE a!=5 ORDER BY 1\n  **\n  ** Transformed into:\n  **\n  **     SELECT x+1 FROM tab WHERE x+1!=5\n  **     UNION ALL\n  **     SELECT y+1 FROM tab WHERE y+1!=5\n  **     UNION ALL\n  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5\n  **     ORDER BY 1\n  **\n  ** We call this the \"compound-subquery flattening\".\n  */\n  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){\n    Select *pNew;\n    ExprList *pOrderBy = p->pOrderBy;\n    Expr *pLimit = p->pLimit;\n    Select *pPrior = p->pPrior;\n    p->pOrderBy = 0;\n    p->pSrc = 0;\n    p->pPrior = 0;\n    p->pLimit = 0;\n    pNew = sqlite3SelectDup(db, p, 0);\n    p->pLimit = pLimit;\n    p->pOrderBy = pOrderBy;\n    p->pSrc = pSrc;\n    p->op = TK_ALL;\n    if( pNew==0 ){\n      p->pPrior = pPrior;\n    }else{\n      pNew->pPrior = pPrior;\n      if( pPrior ) pPrior->pNext = pNew;\n      pNew->pNext = p;\n      p->pPrior = pNew;\n      SELECTTRACE(2,pParse,p,(\"compound-subquery flattener\"\n                              \" creates %u as peer\\n\",pNew->selId));\n    }\n    if( db->mallocFailed ) return 1;\n  }\n\n  /* Begin flattening the iFrom-th entry of the FROM clause \n  ** in the outer query.\n  */\n  pSub = pSub1 = pSubitem->pSelect;\n\n  /* Delete the transient table structure associated with the\n  ** subquery\n  */\n  sqlite3DbFree(db, pSubitem->zDatabase);\n  sqlite3DbFree(db, pSubitem->zName);\n  sqlite3DbFree(db, pSubitem->zAlias);\n  pSubitem->zDatabase = 0;\n  pSubitem->zName = 0;\n  pSubitem->zAlias = 0;\n  pSubitem->pSelect = 0;\n\n  /* Defer deleting the Table object associated with the\n  ** subquery until code generation is\n  ** complete, since there may still exist Expr.pTab entries that\n  ** refer to the subquery even after flattening.  Ticket #3346.\n  **\n  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.\n  */\n  if( ALWAYS(pSubitem->pTab!=0) ){\n    Table *pTabToDel = pSubitem->pTab;\n    if( pTabToDel->nTabRef==1 ){\n      Parse *pToplevel = sqlite3ParseToplevel(pParse);\n      pTabToDel->pNextZombie = pToplevel->pZombieTab;\n      pToplevel->pZombieTab = pTabToDel;\n    }else{\n      pTabToDel->nTabRef--;\n    }\n    pSubitem->pTab = 0;\n  }\n\n  /* The following loop runs once for each term in a compound-subquery\n  ** flattening (as described above).  If we are doing a different kind\n  ** of flattening - a flattening other than a compound-subquery flattening -\n  ** then this loop only runs once.\n  **\n  ** This loop moves all of the FROM elements of the subquery into the\n  ** the FROM clause of the outer query.  Before doing this, remember\n  ** the cursor number for the original outer query FROM element in\n  ** iParent.  The iParent cursor will never be used.  Subsequent code\n  ** will scan expressions looking for iParent references and replace\n  ** those references with expressions that resolve to the subquery FROM\n  ** elements we are now copying in.\n  */\n  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){\n    int nSubSrc;\n    u8 jointype = 0;\n    assert( pSub!=0 );\n    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */\n    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */\n    pSrc = pParent->pSrc;     /* FROM clause of the outer query */\n\n    if( pSrc ){\n      assert( pParent==p );  /* First time through the loop */\n      jointype = pSubitem->fg.jointype;\n    }else{\n      assert( pParent!=p );  /* 2nd and subsequent times through the loop */\n      pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);\n      if( pSrc==0 ) break;\n      pParent->pSrc = pSrc;\n    }\n\n    /* The subquery uses a single slot of the FROM clause of the outer\n    ** query.  If the subquery has more than one element in its FROM clause,\n    ** then expand the outer query to make space for it to hold all elements\n    ** of the subquery.\n    **\n    ** Example:\n    **\n    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;\n    **\n    ** The outer query has 3 slots in its FROM clause.  One slot of the\n    ** outer query (the middle slot) is used by the subquery.  The next\n    ** block of code will expand the outer query FROM clause to 4 slots.\n    ** The middle slot is expanded to two slots in order to make space\n    ** for the two elements in the FROM clause of the subquery.\n    */\n    if( nSubSrc>1 ){\n      pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);\n      if( pSrc==0 ) break;\n      pParent->pSrc = pSrc;\n    }\n\n    /* Transfer the FROM clause terms from the subquery into the\n    ** outer query.\n    */\n    for(i=0; i<nSubSrc; i++){\n      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);\n      assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );\n      pSrc->a[i+iFrom] = pSubSrc->a[i];\n      iNewParent = pSubSrc->a[i].iCursor;\n      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));\n    }\n    pSrc->a[iFrom].fg.jointype = jointype;\n  \n    /* Now begin substituting subquery result set expressions for \n    ** references to the iParent in the outer query.\n    ** \n    ** Example:\n    **\n    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;\n    **   \\                     \\_____________ subquery __________/          /\n    **    \\_____________________ outer query ______________________________/\n    **\n    ** We look at every expression in the outer query and every place we see\n    ** \"a\" we substitute \"x*3\" and every place we see \"b\" we substitute \"y+10\".\n    */\n    if( pSub->pOrderBy && (pParent->selFlags & SF_NoopOrderBy)==0 ){\n      /* At this point, any non-zero iOrderByCol values indicate that the\n      ** ORDER BY column expression is identical to the iOrderByCol'th\n      ** expression returned by SELECT statement pSub. Since these values\n      ** do not necessarily correspond to columns in SELECT statement pParent,\n      ** zero them before transfering the ORDER BY clause.\n      **\n      ** Not doing this may cause an error if a subsequent call to this\n      ** function attempts to flatten a compound sub-query into pParent\n      ** (the only way this can happen is if the compound sub-query is\n      ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */\n      ExprList *pOrderBy = pSub->pOrderBy;\n      for(i=0; i<pOrderBy->nExpr; i++){\n        pOrderBy->a[i].u.x.iOrderByCol = 0;\n      }\n      assert( pParent->pOrderBy==0 );\n      pParent->pOrderBy = pOrderBy;\n      pSub->pOrderBy = 0;\n    }\n    pWhere = pSub->pWhere;\n    pSub->pWhere = 0;\n    if( isLeftJoin>0 ){\n      sqlite3SetJoinExpr(pWhere, iNewParent);\n    }\n    if( pWhere ){\n      if( pParent->pWhere ){\n        pParent->pWhere = sqlite3PExpr(pParse, TK_AND, pWhere, pParent->pWhere);\n      }else{\n        pParent->pWhere = pWhere;\n      }\n    }\n    if( db->mallocFailed==0 ){\n      SubstContext x;\n      x.pParse = pParse;\n      x.iTable = iParent;\n      x.iNewTable = iNewParent;\n      x.isLeftJoin = isLeftJoin;\n      x.pEList = pSub->pEList;\n      substSelect(&x, pParent, 0);\n    }\n  \n    /* The flattened query is a compound if either the inner or the\n    ** outer query is a compound. */\n    pParent->selFlags |= pSub->selFlags & SF_Compound;\n    assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */\n  \n    /*\n    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;\n    **\n    ** One is tempted to try to add a and b to combine the limits.  But this\n    ** does not work if either limit is negative.\n    */\n    if( pSub->pLimit ){\n      pParent->pLimit = pSub->pLimit;\n      pSub->pLimit = 0;\n    }\n\n    /* Recompute the SrcList_item.colUsed masks for the flattened\n    ** tables. */\n    for(i=0; i<nSubSrc; i++){\n      recomputeColumnsUsed(pParent, &pSrc->a[i+iFrom]);\n    }\n  }\n\n  /* Finially, delete what is left of the subquery and return\n  ** success.\n  */\n  sqlite3AggInfoPersistWalkerInit(&w, pParse);\n  sqlite3WalkSelect(&w,pSub1);\n  sqlite3SelectDelete(db, pSub1);\n\n#if SELECTTRACE_ENABLED\n  if( sqlite3SelectTrace & 0x100 ){\n    SELECTTRACE(0x100,pParse,p,(\"After flattening:\\n\"));\n    sqlite3TreeViewSelect(0, p, 0);\n  }\n#endif\n\n  return 1;\n}\n#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */\n\n/*\n** A structure to keep track of all of the column values that are fixed to\n** a known value due to WHERE clause constraints of the form COLUMN=VALUE.\n*/\ntypedef struct WhereConst WhereConst;\nstruct WhereConst {\n  Parse *pParse;   /* Parsing context */\n  int nConst;      /* Number for COLUMN=CONSTANT terms */\n  int nChng;       /* Number of times a constant is propagated */\n  Expr **apExpr;   /* [i*2] is COLUMN and [i*2+1] is VALUE */\n};\n\n/*\n** Add a new entry to the pConst object.  Except, do not add duplicate\n** pColumn entires.  Also, do not add if doing so would not be appropriate.\n**\n** The caller guarantees the pColumn is a column and pValue is a constant.\n** This routine has to do some additional checks before completing the\n** insert.\n*/\nstatic void constInsert(\n  WhereConst *pConst,  /* The WhereConst into which we are inserting */\n  Expr *pColumn,       /* The COLUMN part of the constraint */\n  Expr *pValue,        /* The VALUE part of the constraint */\n  Expr *pExpr          /* Overall expression: COLUMN=VALUE or VALUE=COLUMN */\n){\n  int i;\n  assert( pColumn->op==TK_COLUMN );\n  assert( sqlite3ExprIsConstant(pValue) );\n\n  if( ExprHasProperty(pColumn, EP_FixedCol) ) return;\n  if( sqlite3ExprAffinity(pValue)!=0 ) return;\n  if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){\n    return;\n  }\n\n  /* 2018-10-25 ticket [cf5ed20f]\n  ** Make sure the same pColumn is not inserted more than once */\n  for(i=0; i<pConst->nConst; i++){\n    const Expr *pE2 = pConst->apExpr[i*2];\n    assert( pE2->op==TK_COLUMN );\n    if( pE2->iTable==pColumn->iTable\n     && pE2->iColumn==pColumn->iColumn\n    ){\n      return;  /* Already present.  Return without doing anything. */\n    }\n  }\n\n  pConst->nConst++;\n  pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,\n                         pConst->nConst*2*sizeof(Expr*));\n  if( pConst->apExpr==0 ){\n    pConst->nConst = 0;\n  }else{\n    pConst->apExpr[pConst->nConst*2-2] = pColumn;\n    pConst->apExpr[pConst->nConst*2-1] = pValue;\n  }\n}\n\n/*\n** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE\n** is a constant expression and where the term must be true because it\n** is part of the AND-connected terms of the expression.  For each term\n** found, add it to the pConst structure.\n*/\nstatic void findConstInWhere(WhereConst *pConst, Expr *pExpr){\n  Expr *pRight, *pLeft;\n  if( pExpr==0 ) return;\n  if( ExprHasProperty(pExpr, EP_FromJoin) ) return;\n  if( pExpr->op==TK_AND ){\n    findConstInWhere(pConst, pExpr->pRight);\n    findConstInWhere(pConst, pExpr->pLeft);\n    return;\n  }\n  if( pExpr->op!=TK_EQ ) return;\n  pRight = pExpr->pRight;\n  pLeft = pExpr->pLeft;\n  assert( pRight!=0 );\n  assert( pLeft!=0 );\n  if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pLeft) ){\n    constInsert(pConst,pRight,pLeft,pExpr);\n  }\n  if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pRight) ){\n    constInsert(pConst,pLeft,pRight,pExpr);\n  }\n}\n\n/*\n** This is a Walker expression callback.  pExpr is a candidate expression\n** to be replaced by a value.  If pExpr is equivalent to one of the\n** columns named in pWalker->u.pConst, then overwrite it with its\n** corresponding value.\n*/\nstatic int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){\n  int i;\n  WhereConst *pConst;\n  if( pExpr->op!=TK_COLUMN ) return WRC_Continue;\n  if( ExprHasProperty(pExpr, EP_FixedCol|EP_FromJoin) ){\n    testcase( ExprHasProperty(pExpr, EP_FixedCol) );\n    testcase( ExprHasProperty(pExpr, EP_FromJoin) );\n    return WRC_Continue;\n  }\n  pConst = pWalker->u.pConst;\n  for(i=0; i<pConst->nConst; i++){\n    Expr *pColumn = pConst->apExpr[i*2];\n    if( pColumn==pExpr ) continue;\n    if( pColumn->iTable!=pExpr->iTable ) continue;\n    if( pColumn->iColumn!=pExpr->iColumn ) continue;\n    /* A match is found.  Add the EP_FixedCol property */\n    pConst->nChng++;\n    ExprClearProperty(pExpr, EP_Leaf);\n    ExprSetProperty(pExpr, EP_FixedCol);\n    assert( pExpr->pLeft==0 );\n    pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);\n    break;\n  }\n  return WRC_Prune;\n}\n\n/*\n** The WHERE-clause constant propagation optimization.\n**\n** If the WHERE clause contains terms of the form COLUMN=CONSTANT or\n** CONSTANT=COLUMN that are top-level AND-connected terms that are not\n** part of a ON clause from a LEFT JOIN, then throughout the query\n** replace all other occurrences of COLUMN with CONSTANT.\n**\n** For example, the query:\n**\n**      SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b\n**\n** Is transformed into\n**\n**      SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39\n**\n** Return true if any transformations where made and false if not.\n**\n** Implementation note:  Constant propagation is tricky due to affinity\n** and collating sequence interactions.  Consider this example:\n**\n**    CREATE TABLE t1(a INT,b TEXT);\n**    INSERT INTO t1 VALUES(123,'0123');\n**    SELECT * FROM t1 WHERE a=123 AND b=a;\n**    SELECT * FROM t1 WHERE a=123 AND b=123;\n**\n** The two SELECT statements above should return different answers.  b=a\n** is alway true because the comparison uses numeric affinity, but b=123\n** is false because it uses text affinity and '0123' is not the same as '123'.\n** To work around this, the expression tree is not actually changed from\n** \"b=a\" to \"b=123\" but rather the \"a\" in \"b=a\" is tagged with EP_FixedCol\n** and the \"123\" value is hung off of the pLeft pointer.  Code generator\n** routines know to generate the constant \"123\" instead of looking up the\n** column value.  Also, to avoid collation problems, this optimization is\n** only attempted if the \"a=123\" term uses the default BINARY collation.\n*/\nstatic int propagateConstants(\n  Parse *pParse,   /* The parsing context */\n  Select *p        /* The query in which to propagate constants */\n){\n  WhereConst x;\n  Walker w;\n  int nChng = 0;\n  x.pParse = pParse;\n  do{\n    x.nConst = 0;\n    x.nChng = 0;\n    x.apExpr = 0;\n    findConstInWhere(&x, p->pWhere);\n    if( x.nConst ){\n      memset(&w, 0, sizeof(w));\n      w.pParse = pParse;\n      w.xExprCallback = propagateConstantExprRewrite;\n      w.xSelectCallback = sqlite3SelectWalkNoop;\n      w.xSelectCallback2 = 0;\n      w.walkerDepth = 0;\n      w.u.pConst = &x;\n      sqlite3WalkExpr(&w, p->pWhere);\n      sqlite3DbFree(x.pParse->db, x.apExpr);\n      nChng += x.nChng;\n    }\n  }while( x.nChng );  \n  return nChng;\n}\n\n#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)\n/*\n** Make copies of relevant WHERE clause terms of the outer query into\n** the WHERE clause of subquery.  Example:\n**\n**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;\n**\n** Transformed into:\n**\n**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)\n**     WHERE x=5 AND y=10;\n**\n** The hope is that the terms added to the inner query will make it more\n** efficient.\n**\n** Do not attempt this optimization if:\n**\n**   (1) (** This restriction was removed on 2017-09-29.  We used to\n**           disallow this optimization for aggregate subqueries, but now\n**           it is allowed by putting the extra terms on the HAVING clause.\n**           The added HAVING clause is pointless if the subquery lacks\n**           a GROUP BY clause.  But such a HAVING clause is also harmless\n**           so there does not appear to be any reason to add extra logic\n**           to suppress it. **)\n**\n**   (2) The inner query is the recursive part of a common table expression.\n**\n**   (3) The inner query has a LIMIT clause (since the changes to the WHERE\n**       clause would change the meaning of the LIMIT).\n**\n**   (4) The inner query is the right operand of a LEFT JOIN and the\n**       expression to be pushed down does not come from the ON clause\n**       on that LEFT JOIN.\n**\n**   (5) The WHERE clause expression originates in the ON or USING clause\n**       of a LEFT JOIN where iCursor is not the right-hand table of that\n**       left join.  An example:\n**\n**           SELECT *\n**           FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa\n**           JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)\n**           LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);\n**\n**       The correct answer is three rows:  (1,1,NULL),(2,2,8),(2,2,9).\n**       But if the (b2=2) term were to be pushed down into the bb subquery,\n**       then the (1,1,NULL) row would be suppressed.\n**\n**   (6) The inner query features one or more window-functions (since \n**       changes to the WHERE clause of the inner query could change the \n**       window over which window functions are calculated).\n**\n** Return 0 if no changes are made and non-zero if one or more WHERE clause\n** terms are duplicated into the subquery.\n*/\nstatic int pushDownWhereTerms(\n  Parse *pParse,        /* Parse context (for malloc() and error reporting) */\n  Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */\n  Expr *pWhere,         /* The WHERE clause of the outer query */\n  int iCursor,          /* Cursor number of the subquery */\n  int isLeftJoin        /* True if pSubq is the right term of a LEFT JOIN */\n){\n  Expr *pNew;\n  int nChng = 0;\n  Select *pSel;\n  if( pWhere==0 ) return 0;\n  if( pSubq->selFlags & SF_Recursive ) return 0;  /* restriction (2) */\n\n#ifndef SQLITE_OMIT_WINDOWFUNC\n  for(pSel=pSubq; pSel; pSel=pSel->pPrior){\n    if( pSel->pWin ) return 0;    /* restriction (6) */\n  }\n#endif\n\n#ifdef SQLITE_DEBUG\n  /* Only the first term of a compound can have a WITH clause.  But make\n  ** sure no other terms are marked SF_Recursive in case something changes\n  ** in the future.\n  */\n  {\n    Select *pX;  \n    for(pX=pSubq; pX; pX=pX->pPrior){\n      assert( (pX->selFlags & (SF_Recursive))==0 );\n    }\n  }\n#endif\n\n  if( pSubq->pLimit!=0 ){\n    return 0; /* restriction (3) */\n  }\n  while( pWhere->op==TK_AND ){\n    nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight,\n                                iCursor, isLeftJoin);\n    pWhere = pWhere->pLeft;\n  }\n  if( isLeftJoin\n   && (ExprHasProperty(pWhere,EP_FromJoin)==0\n         || pWhere->iRightJoinTable!=iCursor)\n  ){\n    return 0; /* restriction (4) */\n  }\n  if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){\n    return 0; /* restriction (5) */\n  }\n  if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){\n    nChng++;\n    while( pSubq ){\n      SubstContext x;\n      pNew = sqlite3ExprDup(pParse->db, pWhere, 0);\n      unsetJoinExpr(pNew, -1);\n      x.pParse = pParse;\n      x.iTable = iCursor;\n      x.iNewTable = iCursor;\n      x.isLeftJoin = 0;\n      x.pEList = pSubq->pEList;\n      pNew = substExpr(&x, pNew);\n      if( pSubq->selFlags & SF_Aggregate ){\n        pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);\n      }else{\n        pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew);\n      }\n      pSubq = pSubq->pPrior;\n    }\n  }\n  return nChng;\n}\n#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */\n\n/*\n** The pFunc is the only aggregate function in the query.  Check to see\n** if the query is a candidate for the min/max optimization. \n**\n** If the query is a candidate for the min/max optimization, then set\n** *ppMinMax to be an ORDER BY clause to be used for the optimization\n** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on\n** whether pFunc is a min() or max() function.\n**\n** If the query is not a candidate for the min/max optimization, return\n** WHERE_ORDERBY_NORMAL (which must be zero).\n**\n** This routine must be called after aggregate functions have been\n** located but before their arguments have been subjected to aggregate\n** analysis.\n*/\nstatic u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){\n  int eRet = WHERE_ORDERBY_NORMAL;      /* Return value */\n  ExprList *pEList = pFunc->x.pList;    /* Arguments to agg function */\n  const char *zFunc;                    /* Name of aggregate function pFunc */\n  ExprList *pOrderBy;\n  u8 sortFlags = 0;\n\n  assert( *ppMinMax==0 );\n  assert( pFunc->op==TK_AGG_FUNCTION );\n  assert( !IsWindowFunc(pFunc) );\n  if( pEList==0 || pEList->nExpr!=1 || ExprHasProperty(pFunc, EP_WinFunc) ){\n    return eRet;\n  }\n  zFunc = pFunc->u.zToken;\n  if( sqlite3StrICmp(zFunc, \"min\")==0 ){\n    eRet = WHERE_ORDERBY_MIN;\n    if( sqlite3ExprCanBeNull(pEList->a[0].pExpr) ){\n      sortFlags = KEYINFO_ORDER_BIGNULL;\n    }\n  }else if( sqlite3StrICmp(zFunc, \"max\")==0 ){\n    eRet = WHERE_ORDERBY_MAX;\n    sortFlags = KEYINFO_ORDER_DESC;\n  }else{\n    return eRet;\n  }\n  *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);\n  assert( pOrderBy!=0 || db->mallocFailed );\n  if( pOrderBy ) pOrderBy->a[0].sortFlags = sortFlags;\n  return eRet;\n}\n\n/*\n** The select statement passed as the first argument is an aggregate query.\n** The second argument is the associated aggregate-info object. This \n** function tests if the SELECT is of the form:\n**\n**   SELECT count(*) FROM <tbl>\n**\n** where table is a database table, not a sub-select or view. If the query\n** does match this pattern, then a pointer to the Table object representing\n** <tbl> is returned. Otherwise, 0 is returned.\n*/\nstatic Table *isSimpleCount(Select *p, AggInfo *pAggInfo){\n  Table *pTab;\n  Expr *pExpr;\n\n  assert( !p->pGroupBy );\n\n  if( p->pWhere || p->pEList->nExpr!=1 \n   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect\n  ){\n    return 0;\n  }\n  pTab = p->pSrc->a[0].pTab;\n  pExpr = p->pEList->a[0].pExpr;\n  assert( pTab && !pTab->pSelect && pExpr );\n\n  if( IsVirtual(pTab) ) return 0;\n  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;\n  if( NEVER(pAggInfo->nFunc==0) ) return 0;\n  if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;\n  if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0;\n\n  return pTab;\n}\n\n/*\n** If the source-list item passed as an argument was augmented with an\n** INDEXED BY clause, then try to locate the specified index. If there\n** was such a clause and the named index cannot be found, return \n** SQLITE_ERROR and leave an error in pParse. Otherwise, populate \n** pFrom->pIndex and return SQLITE_OK.\n*/\nSQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){\n  if( pFrom->pTab && pFrom->fg.isIndexedBy ){\n    Table *pTab = pFrom->pTab;\n    char *zIndexedBy = pFrom->u1.zIndexedBy;\n    Index *pIdx;\n    for(pIdx=pTab->pIndex; \n        pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); \n        pIdx=pIdx->pNext\n    );\n    if( !pIdx ){\n      sqlite3ErrorMsg(pParse, \"no such index: %s\", zIndexedBy, 0);\n      pParse->checkSchema = 1;\n      return SQLITE_ERROR;\n    }\n    pFrom->pIBIndex = pIdx;\n  }\n  return SQLITE_OK;\n}\n/*\n** Detect compound SELECT statements that use an ORDER BY clause with \n** an alternative collating sequence.\n**\n**    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...\n**\n** These are rewritten as a subquery:\n**\n**    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)\n**     ORDER BY ... COLLATE ...\n**\n** This transformation is necessary because the multiSelectOrderBy() routine\n** above that generates the code for a compound SELECT with an ORDER BY clause\n** uses a merge algorithm that requires the same collating sequence on the\n** result columns as on the ORDER BY clause.  See ticket\n** http://www.sqlite.org/src/info/6709574d2a\n**\n** This transformation is only needed for EXCEPT, INTERSECT, and UNION.\n** The UNION ALL operator works fine with multiSelectOrderBy() even when\n** there are COLLATE terms in the ORDER BY.\n*/\nstatic int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){\n  int i;\n  Select *pNew;\n  Select *pX;\n  sqlite3 *db;\n  struct ExprList_item *a;\n  SrcList *pNewSrc;\n  Parse *pParse;\n  Token dummy;\n\n  if( p->pPrior==0 ) return WRC_Continue;\n  if( p->pOrderBy==0 ) return WRC_Continue;\n  for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}\n  if( pX==0 ) return WRC_Continue;\n  a = p->pOrderBy->a;\n#ifndef SQLITE_OMIT_WINDOWFUNC\n  /* If iOrderByCol is already non-zero, then it has already been matched\n  ** to a result column of the SELECT statement. This occurs when the\n  ** SELECT is rewritten for window-functions processing and then passed\n  ** to sqlite3SelectPrep() and similar a second time. The rewriting done\n  ** by this function is not required in this case. */\n  if( a[0].u.x.iOrderByCol ) return WRC_Continue;\n#endif\n  for(i=p->pOrderBy->nExpr-1; i>=0; i--){\n    if( a[i].pExpr->flags & EP_Collate ) break;\n  }\n  if( i<0 ) return WRC_Continue;\n\n  /* If we reach this point, that means the transformation is required. */\n\n  pParse = pWalker->pParse;\n  db = pParse->db;\n  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );\n  if( pNew==0 ) return WRC_Abort;\n  memset(&dummy, 0, sizeof(dummy));\n  pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);\n  if( pNewSrc==0 ) return WRC_Abort;\n  *pNew = *p;\n  p->pSrc = pNewSrc;\n  p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));\n  p->op = TK_SELECT;\n  p->pWhere = 0;\n  pNew->pGroupBy = 0;\n  pNew->pHaving = 0;\n  pNew->pOrderBy = 0;\n  p->pPrior = 0;\n  p->pNext = 0;\n  p->pWith = 0;\n#ifndef SQLITE_OMIT_WINDOWFUNC\n  p->pWinDefn = 0;\n#endif\n  p->selFlags &= ~SF_Compound;\n  assert( (p->selFlags & SF_Converted)==0 );\n  p->selFlags |= SF_Converted;\n  assert( pNew->pPrior!=0 );\n  pNew->pPrior->pNext = pNew;\n  pNew->pLimit = 0;\n  return WRC_Continue;\n}\n\n/*\n** Check to see if the FROM clause term pFrom has table-valued function\n** arguments.  If it does, leave an error message in pParse and return\n** non-zero, since pFrom is not allowed to be a table-valued function.\n*/\nstatic int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){\n  if( pFrom->fg.isTabFunc ){\n    sqlite3ErrorMsg(pParse, \"'%s' is not a function\", pFrom->zName);\n    return 1;\n  }\n  return 0;\n}\n\n#ifndef SQLITE_OMIT_CTE\n/*\n** Argument pWith (which may be NULL) points to a linked list of nested \n** WITH contexts, from inner to outermost. If the table identified by \n** FROM clause element pItem is really a common-table-expression (CTE) \n** then return a pointer to the CTE definition for that table. Otherwise\n** return NULL.\n**\n** If a non-NULL value is returned, set *ppContext to point to the With\n** object that the returned CTE belongs to.\n*/\nstatic struct Cte *searchWith(\n  With *pWith,                    /* Current innermost WITH clause */\n  struct SrcList_item *pItem,     /* FROM clause element to resolve */\n  With **ppContext                /* OUT: WITH clause return value belongs to */\n){\n  const char *zName;\n  if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){\n    With *p;\n    for(p=pWith; p; p=p->pOuter){\n      int i;\n      for(i=0; i<p->nCte; i++){\n        if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){\n          *ppContext = p;\n          return &p->a[i];\n        }\n      }\n    }\n  }\n  return 0;\n}\n\n/* The code generator maintains a stack of active WITH clauses\n** with the inner-most WITH clause being at the top of the stack.\n**\n** This routine pushes the WITH clause passed as the second argument\n** onto the top of the stack. If argument bFree is true, then this\n** WITH clause will never be popped from the stack. In this case it\n** should be freed along with the Parse object. In other cases, when\n** bFree==0, the With object will be freed along with the SELECT \n** statement with which it is associated.\n*/\nSQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){\n  assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );\n  if( pWith ){\n    assert( pParse->pWith!=pWith );\n    pWith->pOuter = pParse->pWith;\n    pParse->pWith = pWith;\n    if( bFree ) pParse->pWithToFree = pWith;\n  }\n}\n\n/*\n** This function checks if argument pFrom refers to a CTE declared by \n** a WITH clause on the stack currently maintained by the parser. And,\n** if currently processing a CTE expression, if it is a recursive\n** reference to the current CTE.\n**\n** If pFrom falls into either of the two categories above, pFrom->pTab\n** and other fields are populated accordingly. The caller should check\n** (pFrom->pTab!=0) to determine whether or not a successful match\n** was found.\n**\n** Whether or not a match is found, SQLITE_OK is returned if no error\n** occurs. If an error does occur, an error message is stored in the\n** parser and some error code other than SQLITE_OK returned.\n*/\nstatic int withExpand(\n  Walker *pWalker, \n  struct SrcList_item *pFrom\n){\n  Parse *pParse = pWalker->pParse;\n  sqlite3 *db = pParse->db;\n  struct Cte *pCte;               /* Matched CTE (or NULL if no match) */\n  With *pWith;                    /* WITH clause that pCte belongs to */\n\n  assert( pFrom->pTab==0 );\n  if( pParse->nErr ){\n    return SQLITE_ERROR;\n  }\n\n  pCte = searchWith(pParse->pWith, pFrom, &pWith);\n  if( pCte ){\n    Table *pTab;\n    ExprList *pEList;\n    Select *pSel;\n    Select *pLeft;                /* Left-most SELECT statement */\n    int bMayRecursive;            /* True if compound joined by UNION [ALL] */\n    With *pSavedWith;             /* Initial value of pParse->pWith */\n\n    /* If pCte->zCteErr is non-NULL at this point, then this is an illegal\n    ** recursive reference to CTE pCte. Leave an error in pParse and return\n    ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.\n    ** In this case, proceed.  */\n    if( pCte->zCteErr ){\n      sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);\n      return SQLITE_ERROR;\n    }\n    if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;\n\n    assert( pFrom->pTab==0 );\n    pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));\n    if( pTab==0 ) return WRC_Abort;\n    pTab->nTabRef = 1;\n    pTab->zName = sqlite3DbStrDup(db, pCte->zName);\n    pTab->iPKey = -1;\n    pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );\n    pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;\n    pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);\n    if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;\n    assert( pFrom->pSelect );\n\n    /* Check if this is a recursive CTE. */\n    pSel = pFrom->pSelect;\n    bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );\n    if( bMayRecursive ){\n      int i;\n      SrcList *pSrc = pFrom->pSelect->pSrc;\n      for(i=0; i<pSrc->nSrc; i++){\n        struct SrcList_item *pItem = &pSrc->a[i];\n        if( pItem->zDatabase==0 \n         && pItem->zName!=0 \n         && 0==sqlite3StrICmp(pItem->zName, pCte->zName)\n          ){\n          pItem->pTab = pTab;\n          pItem->fg.isRecursive = 1;\n          pTab->nTabRef++;\n          pSel->selFlags |= SF_Recursive;\n        }\n      }\n    }\n\n    /* Only one recursive reference is permitted. */ \n    if( pTab->nTabRef>2 ){\n      sqlite3ErrorMsg(\n          pParse, \"multiple references to recursive table: %s\", pCte->zName\n      );\n      return SQLITE_ERROR;\n    }\n    assert( pTab->nTabRef==1 || \n            ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));\n\n    pCte->zCteErr = \"circular reference: %s\";\n    pSavedWith = pParse->pWith;\n    pParse->pWith = pWith;\n    if( bMayRecursive ){\n      Select *pPrior = pSel->pPrior;\n      assert( pPrior->pWith==0 );\n      pPrior->pWith = pSel->pWith;\n      sqlite3WalkSelect(pWalker, pPrior);\n      pPrior->pWith = 0;\n    }else{\n      sqlite3WalkSelect(pWalker, pSel);\n    }\n    pParse->pWith = pWith;\n\n    for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);\n    pEList = pLeft->pEList;\n    if( pCte->pCols ){\n      if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){\n        sqlite3ErrorMsg(pParse, \"table %s has %d values for %d columns\",\n            pCte->zName, pEList->nExpr, pCte->pCols->nExpr\n        );\n        pParse->pWith = pSavedWith;\n        return SQLITE_ERROR;\n      }\n      pEList = pCte->pCols;\n    }\n\n    sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);\n    if( bMayRecursive ){\n      if( pSel->selFlags & SF_Recursive ){\n        pCte->zCteErr = \"multiple recursive references: %s\";\n      }else{\n        pCte->zCteErr = \"recursive reference in a subquery: %s\";\n      }\n      sqlite3WalkSelect(pWalker, pSel);\n    }\n    pCte->zCteErr = 0;\n    pParse->pWith = pSavedWith;\n  }\n\n  return SQLITE_OK;\n}\n#endif\n\n#ifndef SQLITE_OMIT_CTE\n/*\n** If the SELECT passed as the second argument has an associated WITH \n** clause, pop it from the stack stored as part of the Parse object.\n**\n** This function is used as the xSelectCallback2() callback by\n** sqlite3SelectExpand() when walking a SELECT tree to resolve table\n** names and other FROM clause elements. \n*/\nstatic void selectPopWith(Walker *pWalker, Select *p){\n  Parse *pParse = pWalker->pParse;\n  if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){\n    With *pWith = findRightmost(p)->pWith;\n    if( pWith!=0 ){\n      assert( pParse->pWith==pWith || pParse->nErr );\n      pParse->pWith = pWith->pOuter;\n    }\n  }\n}\n#else\n#define selectPopWith 0\n#endif\n\n/*\n** The SrcList_item structure passed as the second argument represents a\n** sub-query in the FROM clause of a SELECT statement. This function\n** allocates and populates the SrcList_item.pTab object. If successful,\n** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,\n** SQLITE_NOMEM.\n*/\nSQLITE_PRIVATE int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){\n  Select *pSel = pFrom->pSelect;\n  Table *pTab;\n\n  assert( pSel );\n  pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));\n  if( pTab==0 ) return SQLITE_NOMEM;\n  pTab->nTabRef = 1;\n  if( pFrom->zAlias ){\n    pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);\n  }else{\n    pTab->zName = sqlite3MPrintf(pParse->db, \"subquery_%u\", pSel->selId);\n  }\n  while( pSel->pPrior ){ pSel = pSel->pPrior; }\n  sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);\n  pTab->iPKey = -1;\n  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );\n  pTab->tabFlags |= TF_Ephemeral;\n\n  return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;\n}\n\n/*\n** This routine is a Walker callback for \"expanding\" a SELECT statement.\n** \"Expanding\" means to do the following:\n**\n**    (1)  Make sure VDBE cursor numbers have been assigned to every\n**         element of the FROM clause.\n**\n**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that \n**         defines FROM clause.  When views appear in the FROM clause,\n**         fill pTabList->a[].pSelect with a copy of the SELECT statement\n**         that implements the view.  A copy is made of the view's SELECT\n**         statement so that we can freely modify or delete that statement\n**         without worrying about messing up the persistent representation\n**         of the view.\n**\n**    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword\n**         on joins and the ON and USING clause of joins.\n**\n**    (4)  Scan the list of columns in the result set (pEList) looking\n**         for instances of the \"*\" operator or the TABLE.* operator.\n**         If found, expand each \"*\" to be every column in every table\n**         and TABLE.* to be every column in TABLE.\n**\n*/\nstatic int selectExpander(Walker *pWalker, Select *p){\n  Parse *pParse = pWalker->pParse;\n  int i, j, k;\n  SrcList *pTabList;\n  ExprList *pEList;\n  struct SrcList_item *pFrom;\n  sqlite3 *db = pParse->db;\n  Expr *pE, *pRight, *pExpr;\n  u16 selFlags = p->selFlags;\n  u32 elistFlags = 0;\n\n  p->selFlags |= SF_Expanded;\n  if( db->mallocFailed  ){\n    return WRC_Abort;\n  }\n  assert( p->pSrc!=0 );\n  if( (selFlags & SF_Expanded)!=0 ){\n    return WRC_Prune;\n  }\n  if( pWalker->eCode ){\n    /* Renumber selId because it has been copied from a view */\n    p->selId = ++pParse->nSelect;\n  }\n  pTabList = p->pSrc;\n  pEList = p->pEList;\n  sqlite3WithPush(pParse, p->pWith, 0);\n\n  /* Make sure cursor numbers have been assigned to all entries in\n  ** the FROM clause of the SELECT statement.\n  */\n  sqlite3SrcListAssignCursors(pParse, pTabList);\n\n  /* Look up every table named in the FROM clause of the select.  If\n  ** an entry of the FROM clause is a subquery instead of a table or view,\n  ** then create a transient table structure to describe the subquery.\n  */\n  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){\n    Table *pTab;\n    assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );\n    if( pFrom->fg.isRecursive ) continue;\n    assert( pFrom->pTab==0 );\n#ifndef SQLITE_OMIT_CTE\n    if( withExpand(pWalker, pFrom) ) return WRC_Abort;\n    if( pFrom->pTab ) {} else\n#endif\n    if( pFrom->zName==0 ){\n#ifndef SQLITE_OMIT_SUBQUERY\n      Select *pSel = pFrom->pSelect;\n      /* A sub-query in the FROM clause of a SELECT */\n      assert( pSel!=0 );\n      assert( pFrom->pTab==0 );\n      if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;\n      if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;\n#endif\n    }else{\n      /* An ordinary table or view name in the FROM clause */\n      assert( pFrom->pTab==0 );\n      pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);\n      if( pTab==0 ) return WRC_Abort;\n      if( pTab->nTabRef>=0xffff ){\n        sqlite3ErrorMsg(pParse, \"too many references to \\\"%s\\\": max 65535\",\n           pTab->zName);\n        pFrom->pTab = 0;\n        return WRC_Abort;\n      }\n      pTab->nTabRef++;\n      if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){\n        return WRC_Abort;\n      }\n#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)\n      if( IsVirtual(pTab) || pTab->pSelect ){\n        i16 nCol;\n        u8 eCodeOrig = pWalker->eCode;\n        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;\n        assert( pFrom->pSelect==0 );\n        if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){\n          sqlite3ErrorMsg(pParse, \"access to view \\\"%s\\\" prohibited\",\n            pTab->zName);\n        }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n        if( IsVirtual(pTab)\n         && pFrom->fg.fromDDL\n         && ALWAYS(pTab->pVTable!=0)\n         && pTab->pVTable->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)\n        ){\n          sqlite3ErrorMsg(pParse, \"unsafe use of virtual table \\\"%s\\\"\",\n                                  pTab->zName);\n        }\n#endif\n        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);\n        nCol = pTab->nCol;\n        pTab->nCol = -1;\n        pWalker->eCode = 1;  /* Turn on Select.selId renumbering */\n        sqlite3WalkSelect(pWalker, pFrom->pSelect);\n        pWalker->eCode = eCodeOrig;\n        pTab->nCol = nCol;\n      }\n#endif\n    }\n\n    /* Locate the index named by the INDEXED BY clause, if any. */\n    if( sqlite3IndexedByLookup(pParse, pFrom) ){\n      return WRC_Abort;\n    }\n  }\n\n  /* Process NATURAL keywords, and ON and USING clauses of joins.\n  */\n  if( pParse->nErr || db->mallocFailed || sqliteProcessJoin(pParse, p) ){\n    return WRC_Abort;\n  }\n\n  /* For every \"*\" that occurs in the column list, insert the names of\n  ** all columns in all tables.  And for every TABLE.* insert the names\n  ** of all columns in TABLE.  The parser inserted a special expression\n  ** with the TK_ASTERISK operator for each \"*\" that it found in the column\n  ** list.  The following code just has to locate the TK_ASTERISK\n  ** expressions and expand each one to the list of all columns in\n  ** all tables.\n  **\n  ** The first loop just checks to see if there are any \"*\" operators\n  ** that need expanding.\n  */\n  for(k=0; k<pEList->nExpr; k++){\n    pE = pEList->a[k].pExpr;\n    if( pE->op==TK_ASTERISK ) break;\n    assert( pE->op!=TK_DOT || pE->pRight!=0 );\n    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );\n    if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;\n    elistFlags |= pE->flags;\n  }\n  if( k<pEList->nExpr ){\n    /*\n    ** If we get here it means the result set contains one or more \"*\"\n    ** operators that need to be expanded.  Loop through each expression\n    ** in the result set and expand them one by one.\n    */\n    struct ExprList_item *a = pEList->a;\n    ExprList *pNew = 0;\n    int flags = pParse->db->flags;\n    int longNames = (flags & SQLITE_FullColNames)!=0\n                      && (flags & SQLITE_ShortColNames)==0;\n\n    for(k=0; k<pEList->nExpr; k++){\n      pE = a[k].pExpr;\n      elistFlags |= pE->flags;\n      pRight = pE->pRight;\n      assert( pE->op!=TK_DOT || pRight!=0 );\n      if( pE->op!=TK_ASTERISK\n       && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)\n      ){\n        /* This particular expression does not need to be expanded.\n        */\n        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);\n        if( pNew ){\n          pNew->a[pNew->nExpr-1].zEName = a[k].zEName;\n          pNew->a[pNew->nExpr-1].eEName = a[k].eEName;\n          a[k].zEName = 0;\n        }\n        a[k].pExpr = 0;\n      }else{\n        /* This expression is a \"*\" or a \"TABLE.*\" and needs to be\n        ** expanded. */\n        int tableSeen = 0;      /* Set to 1 when TABLE matches */\n        char *zTName = 0;       /* text of name of TABLE */\n        if( pE->op==TK_DOT ){\n          assert( pE->pLeft!=0 );\n          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );\n          zTName = pE->pLeft->u.zToken;\n        }\n        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){\n          Table *pTab = pFrom->pTab;\n          Select *pSub = pFrom->pSelect;\n          char *zTabName = pFrom->zAlias;\n          const char *zSchemaName = 0;\n          int iDb;\n          if( zTabName==0 ){\n            zTabName = pTab->zName;\n          }\n          if( db->mallocFailed ) break;\n          if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){\n            pSub = 0;\n            if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){\n              continue;\n            }\n            iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n            zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : \"*\";\n          }\n          for(j=0; j<pTab->nCol; j++){\n            char *zName = pTab->aCol[j].zName;\n            char *zColname;  /* The computed column name */\n            char *zToFree;   /* Malloced string that needs to be freed */\n            Token sColname;  /* Computed column name as a token */\n\n            assert( zName );\n            if( zTName && pSub\n             && sqlite3MatchEName(&pSub->pEList->a[j], 0, zTName, 0)==0\n            ){\n              continue;\n            }\n\n            /* If a column is marked as 'hidden', omit it from the expanded\n            ** result-set list unless the SELECT has the SF_IncludeHidden\n            ** bit set.\n            */\n            if( (p->selFlags & SF_IncludeHidden)==0\n             && IsHiddenColumn(&pTab->aCol[j]) \n            ){\n              continue;\n            }\n            tableSeen = 1;\n\n            if( i>0 && zTName==0 ){\n              if( (pFrom->fg.jointype & JT_NATURAL)!=0\n                && tableAndColumnIndex(pTabList, i, zName, 0, 0, 1)\n              ){\n                /* In a NATURAL join, omit the join columns from the \n                ** table to the right of the join */\n                continue;\n              }\n              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){\n                /* In a join with a USING clause, omit columns in the\n                ** using clause from the table on the right. */\n                continue;\n              }\n            }\n            pRight = sqlite3Expr(db, TK_ID, zName);\n            zColname = zName;\n            zToFree = 0;\n            if( longNames || pTabList->nSrc>1 ){\n              Expr *pLeft;\n              pLeft = sqlite3Expr(db, TK_ID, zTabName);\n              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);\n              if( zSchemaName ){\n                pLeft = sqlite3Expr(db, TK_ID, zSchemaName);\n                pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);\n              }\n              if( longNames ){\n                zColname = sqlite3MPrintf(db, \"%s.%s\", zTabName, zName);\n                zToFree = zColname;\n              }\n            }else{\n              pExpr = pRight;\n            }\n            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);\n            sqlite3TokenInit(&sColname, zColname);\n            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);\n            if( pNew && (p->selFlags & SF_NestedFrom)!=0 && !IN_RENAME_OBJECT ){\n              struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];\n              sqlite3DbFree(db, pX->zEName);\n              if( pSub ){\n                pX->zEName = sqlite3DbStrDup(db, pSub->pEList->a[j].zEName);\n                testcase( pX->zEName==0 );\n              }else{\n                pX->zEName = sqlite3MPrintf(db, \"%s.%s.%s\",\n                                           zSchemaName, zTabName, zColname);\n                testcase( pX->zEName==0 );\n              }\n              pX->eEName = ENAME_TAB;\n            }\n            sqlite3DbFree(db, zToFree);\n          }\n        }\n        if( !tableSeen ){\n          if( zTName ){\n            sqlite3ErrorMsg(pParse, \"no such table: %s\", zTName);\n          }else{\n            sqlite3ErrorMsg(pParse, \"no tables specified\");\n          }\n        }\n      }\n    }\n    sqlite3ExprListDelete(db, pEList);\n    p->pEList = pNew;\n  }\n  if( p->pEList ){\n    if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){\n      sqlite3ErrorMsg(pParse, \"too many columns in result set\");\n      return WRC_Abort;\n    }\n    if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){\n      p->selFlags |= SF_ComplexResult;\n    }\n  }\n  return WRC_Continue;\n}\n\n#if SQLITE_DEBUG\n/*\n** Always assert.  This xSelectCallback2 implementation proves that the\n** xSelectCallback2 is never invoked.\n*/\nSQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  assert( 0 );\n}\n#endif\n/*\n** This routine \"expands\" a SELECT statement and all of its subqueries.\n** For additional information on what it means to \"expand\" a SELECT\n** statement, see the comment on the selectExpand worker callback above.\n**\n** Expanding a SELECT statement is the first step in processing a\n** SELECT statement.  The SELECT statement must be expanded before\n** name resolution is performed.\n**\n** If anything goes wrong, an error message is written into pParse.\n** The calling function can detect the problem by looking at pParse->nErr\n** and/or pParse->db->mallocFailed.\n*/\nstatic void sqlite3SelectExpand(Parse *pParse, Select *pSelect){\n  Walker w;\n  w.xExprCallback = sqlite3ExprWalkNoop;\n  w.pParse = pParse;\n  if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){\n    w.xSelectCallback = convertCompoundSelectToSubquery;\n    w.xSelectCallback2 = 0;\n    sqlite3WalkSelect(&w, pSelect);\n  }\n  w.xSelectCallback = selectExpander;\n  w.xSelectCallback2 = selectPopWith;\n  w.eCode = 0;\n  sqlite3WalkSelect(&w, pSelect);\n}\n\n\n#ifndef SQLITE_OMIT_SUBQUERY\n/*\n** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()\n** interface.\n**\n** For each FROM-clause subquery, add Column.zType and Column.zColl\n** information to the Table structure that represents the result set\n** of that subquery.\n**\n** The Table structure that represents the result set was constructed\n** by selectExpander() but the type and collation information was omitted\n** at that point because identifiers had not yet been resolved.  This\n** routine is called after identifier resolution.\n*/\nstatic void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){\n  Parse *pParse;\n  int i;\n  SrcList *pTabList;\n  struct SrcList_item *pFrom;\n\n  assert( p->selFlags & SF_Resolved );\n  if( p->selFlags & SF_HasTypeInfo ) return;\n  p->selFlags |= SF_HasTypeInfo;\n  pParse = pWalker->pParse;\n  pTabList = p->pSrc;\n  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){\n    Table *pTab = pFrom->pTab;\n    assert( pTab!=0 );\n    if( (pTab->tabFlags & TF_Ephemeral)!=0 ){\n      /* A sub-query in the FROM clause of a SELECT */\n      Select *pSel = pFrom->pSelect;\n      if( pSel ){\n        while( pSel->pPrior ) pSel = pSel->pPrior;\n        sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel,\n                                               SQLITE_AFF_NONE);\n      }\n    }\n  }\n}\n#endif\n\n\n/*\n** This routine adds datatype and collating sequence information to\n** the Table structures of all FROM-clause subqueries in a\n** SELECT statement.\n**\n** Use this routine after name resolution.\n*/\nstatic void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){\n#ifndef SQLITE_OMIT_SUBQUERY\n  Walker w;\n  w.xSelectCallback = sqlite3SelectWalkNoop;\n  w.xSelectCallback2 = selectAddSubqueryTypeInfo;\n  w.xExprCallback = sqlite3ExprWalkNoop;\n  w.pParse = pParse;\n  sqlite3WalkSelect(&w, pSelect);\n#endif\n}\n\n\n/*\n** This routine sets up a SELECT statement for processing.  The\n** following is accomplished:\n**\n**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.\n**     *  Ephemeral Table objects are created for all FROM-clause subqueries.\n**     *  ON and USING clauses are shifted into WHERE statements\n**     *  Wildcards \"*\" and \"TABLE.*\" in result sets are expanded.\n**     *  Identifiers in expression are matched to tables.\n**\n** This routine acts recursively on all subqueries within the SELECT.\n*/\nSQLITE_PRIVATE void sqlite3SelectPrep(\n  Parse *pParse,         /* The parser context */\n  Select *p,             /* The SELECT statement being coded. */\n  NameContext *pOuterNC  /* Name context for container */\n){\n  assert( p!=0 || pParse->db->mallocFailed );\n  if( pParse->db->mallocFailed ) return;\n  if( p->selFlags & SF_HasTypeInfo ) return;\n  sqlite3SelectExpand(pParse, p);\n  if( pParse->nErr || pParse->db->mallocFailed ) return;\n  sqlite3ResolveSelectNames(pParse, p, pOuterNC);\n  if( pParse->nErr || pParse->db->mallocFailed ) return;\n  sqlite3SelectAddTypeInfo(pParse, p);\n}\n\n/*\n** Reset the aggregate accumulator.\n**\n** The aggregate accumulator is a set of memory cells that hold\n** intermediate results while calculating an aggregate.  This\n** routine generates code that stores NULLs in all of those memory\n** cells.\n*/\nstatic void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){\n  Vdbe *v = pParse->pVdbe;\n  int i;\n  struct AggInfo_func *pFunc;\n  int nReg = pAggInfo->nFunc + pAggInfo->nColumn;\n  if( nReg==0 ) return;\n  if( pParse->nErr ) return;\n#ifdef SQLITE_DEBUG\n  /* Verify that all AggInfo registers are within the range specified by\n  ** AggInfo.mnReg..AggInfo.mxReg */\n  assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );\n  for(i=0; i<pAggInfo->nColumn; i++){\n    assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg\n         && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );\n  }\n  for(i=0; i<pAggInfo->nFunc; i++){\n    assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg\n         && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );\n  }\n#endif\n  sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);\n  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){\n    if( pFunc->iDistinct>=0 ){\n      Expr *pE = pFunc->pExpr;\n      assert( !ExprHasProperty(pE, EP_xIsSelect) );\n      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){\n        sqlite3ErrorMsg(pParse, \"DISTINCT aggregates must have exactly one \"\n           \"argument\");\n        pFunc->iDistinct = -1;\n      }else{\n        KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);\n        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,\n                          (char*)pKeyInfo, P4_KEYINFO);\n      }\n    }\n  }\n}\n\n/*\n** Invoke the OP_AggFinalize opcode for every aggregate function\n** in the AggInfo structure.\n*/\nstatic void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){\n  Vdbe *v = pParse->pVdbe;\n  int i;\n  struct AggInfo_func *pF;\n  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){\n    ExprList *pList = pF->pExpr->x.pList;\n    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );\n    sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);\n    sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);\n  }\n}\n\n\n/*\n** Update the accumulator memory cells for an aggregate based on\n** the current cursor position.\n**\n** If regAcc is non-zero and there are no min() or max() aggregates\n** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator\n** registers if register regAcc contains 0. The caller will take care\n** of setting and clearing regAcc.\n*/\nstatic void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){\n  Vdbe *v = pParse->pVdbe;\n  int i;\n  int regHit = 0;\n  int addrHitTest = 0;\n  struct AggInfo_func *pF;\n  struct AggInfo_col *pC;\n\n  pAggInfo->directMode = 1;\n  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){\n    int nArg;\n    int addrNext = 0;\n    int regAgg;\n    ExprList *pList = pF->pExpr->x.pList;\n    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );\n    assert( !IsWindowFunc(pF->pExpr) );\n    if( ExprHasProperty(pF->pExpr, EP_WinFunc) ){\n      Expr *pFilter = pF->pExpr->y.pWin->pFilter;\n      if( pAggInfo->nAccumulator \n       && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL) \n      ){\n        if( regHit==0 ) regHit = ++pParse->nMem;\n        /* If this is the first row of the group (regAcc==0), clear the\n        ** \"magnet\" register regHit so that the accumulator registers\n        ** are populated if the FILTER clause jumps over the the \n        ** invocation of min() or max() altogether. Or, if this is not\n        ** the first row (regAcc==1), set the magnet register so that the\n        ** accumulators are not populated unless the min()/max() is invoked and\n        ** indicates that they should be.  */\n        sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit);\n      }\n      addrNext = sqlite3VdbeMakeLabel(pParse);\n      sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL);\n    }\n    if( pList ){\n      nArg = pList->nExpr;\n      regAgg = sqlite3GetTempRange(pParse, nArg);\n      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);\n    }else{\n      nArg = 0;\n      regAgg = 0;\n    }\n    if( pF->iDistinct>=0 ){\n      if( addrNext==0 ){ \n        addrNext = sqlite3VdbeMakeLabel(pParse);\n      }\n      testcase( nArg==0 );  /* Error condition */\n      testcase( nArg>1 );   /* Also an error */\n      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);\n    }\n    if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){\n      CollSeq *pColl = 0;\n      struct ExprList_item *pItem;\n      int j;\n      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */\n      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){\n        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);\n      }\n      if( !pColl ){\n        pColl = pParse->db->pDfltColl;\n      }\n      if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;\n      sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);\n    }\n    sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem);\n    sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);\n    sqlite3VdbeChangeP5(v, (u8)nArg);\n    sqlite3ReleaseTempRange(pParse, regAgg, nArg);\n    if( addrNext ){\n      sqlite3VdbeResolveLabel(v, addrNext);\n    }\n  }\n  if( regHit==0 && pAggInfo->nAccumulator ){\n    regHit = regAcc;\n  }\n  if( regHit ){\n    addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);\n  }\n  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){\n    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);\n  }\n\n  pAggInfo->directMode = 0;\n  if( addrHitTest ){\n    sqlite3VdbeJumpHereOrPopInst(v, addrHitTest);\n  }\n}\n\n/*\n** Add a single OP_Explain instruction to the VDBE to explain a simple\n** count(*) query (\"SELECT count(*) FROM pTab\").\n*/\n#ifndef SQLITE_OMIT_EXPLAIN\nstatic void explainSimpleCount(\n  Parse *pParse,                  /* Parse context */\n  Table *pTab,                    /* Table being queried */\n  Index *pIdx                     /* Index used to optimize scan, or NULL */\n){\n  if( pParse->explain==2 ){\n    int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));\n    sqlite3VdbeExplain(pParse, 0, \"SCAN TABLE %s%s%s\",\n        pTab->zName,\n        bCover ? \" USING COVERING INDEX \" : \"\",\n        bCover ? pIdx->zName : \"\"\n    );\n  }\n}\n#else\n# define explainSimpleCount(a,b,c)\n#endif\n\n/*\n** sqlite3WalkExpr() callback used by havingToWhere().\n**\n** If the node passed to the callback is a TK_AND node, return \n** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.\n**\n** Otherwise, return WRC_Prune. In this case, also check if the \n** sub-expression matches the criteria for being moved to the WHERE\n** clause. If so, add it to the WHERE clause and replace the sub-expression\n** within the HAVING expression with a constant \"1\".\n*/\nstatic int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){\n  if( pExpr->op!=TK_AND ){\n    Select *pS = pWalker->u.pSelect;\n    if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){\n      sqlite3 *db = pWalker->pParse->db;\n      Expr *pNew = sqlite3Expr(db, TK_INTEGER, \"1\");\n      if( pNew ){\n        Expr *pWhere = pS->pWhere;\n        SWAP(Expr, *pNew, *pExpr);\n        pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew);\n        pS->pWhere = pNew;\n        pWalker->eCode = 1;\n      }\n    }\n    return WRC_Prune;\n  }\n  return WRC_Continue;\n}\n\n/*\n** Transfer eligible terms from the HAVING clause of a query, which is\n** processed after grouping, to the WHERE clause, which is processed before\n** grouping. For example, the query:\n**\n**   SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?\n**\n** can be rewritten as:\n**\n**   SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?\n**\n** A term of the HAVING expression is eligible for transfer if it consists\n** entirely of constants and expressions that are also GROUP BY terms that\n** use the \"BINARY\" collation sequence.\n*/\nstatic void havingToWhere(Parse *pParse, Select *p){\n  Walker sWalker;\n  memset(&sWalker, 0, sizeof(sWalker));\n  sWalker.pParse = pParse;\n  sWalker.xExprCallback = havingToWhereExprCb;\n  sWalker.u.pSelect = p;\n  sqlite3WalkExpr(&sWalker, p->pHaving);\n#if SELECTTRACE_ENABLED\n  if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){\n    SELECTTRACE(0x100,pParse,p,(\"Move HAVING terms into WHERE:\\n\"));\n    sqlite3TreeViewSelect(0, p, 0);\n  }\n#endif\n}\n\n/*\n** Check to see if the pThis entry of pTabList is a self-join of a prior view.\n** If it is, then return the SrcList_item for the prior view.  If it is not,\n** then return 0.\n*/\nstatic struct SrcList_item *isSelfJoinView(\n  SrcList *pTabList,           /* Search for self-joins in this FROM clause */\n  struct SrcList_item *pThis   /* Search for prior reference to this subquery */\n){\n  struct SrcList_item *pItem;\n  for(pItem = pTabList->a; pItem<pThis; pItem++){\n    Select *pS1;\n    if( pItem->pSelect==0 ) continue;\n    if( pItem->fg.viaCoroutine ) continue;\n    if( pItem->zName==0 ) continue;\n    assert( pItem->pTab!=0 );\n    assert( pThis->pTab!=0 );\n    if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue;\n    if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;\n    pS1 = pItem->pSelect;\n    if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){\n      /* The query flattener left two different CTE tables with identical\n      ** names in the same FROM clause. */\n      continue;\n    }\n    if( sqlite3ExprCompare(0, pThis->pSelect->pWhere, pS1->pWhere, -1)\n     || sqlite3ExprCompare(0, pThis->pSelect->pHaving, pS1->pHaving, -1) \n    ){\n      /* The view was modified by some other optimization such as\n      ** pushDownWhereTerms() */\n      continue;\n    }\n    return pItem;\n  }\n  return 0;\n}\n\n#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION\n/*\n** Attempt to transform a query of the form\n**\n**    SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)\n**\n** Into this:\n**\n**    SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)\n**\n** The transformation only works if all of the following are true:\n**\n**   *  The subquery is a UNION ALL of two or more terms\n**   *  The subquery does not have a LIMIT clause\n**   *  There is no WHERE or GROUP BY or HAVING clauses on the subqueries\n**   *  The outer query is a simple count(*) with no WHERE clause or other\n**      extraneous syntax.\n**\n** Return TRUE if the optimization is undertaken.\n*/\nstatic int countOfViewOptimization(Parse *pParse, Select *p){\n  Select *pSub, *pPrior;\n  Expr *pExpr;\n  Expr *pCount;\n  sqlite3 *db;\n  if( (p->selFlags & SF_Aggregate)==0 ) return 0;   /* This is an aggregate */\n  if( p->pEList->nExpr!=1 ) return 0;               /* Single result column */\n  if( p->pWhere ) return 0;\n  if( p->pGroupBy ) return 0;\n  pExpr = p->pEList->a[0].pExpr;\n  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;        /* Result is an aggregate */\n  if( sqlite3_stricmp(pExpr->u.zToken,\"count\") ) return 0;  /* Is count() */\n  if( pExpr->x.pList!=0 ) return 0;                 /* Must be count(*) */\n  if( p->pSrc->nSrc!=1 ) return 0;                  /* One table in FROM  */\n  pSub = p->pSrc->a[0].pSelect;\n  if( pSub==0 ) return 0;                           /* The FROM is a subquery */\n  if( pSub->pPrior==0 ) return 0;                   /* Must be a compound ry */\n  do{\n    if( pSub->op!=TK_ALL && pSub->pPrior ) return 0;  /* Must be UNION ALL */\n    if( pSub->pWhere ) return 0;                      /* No WHERE clause */\n    if( pSub->pLimit ) return 0;                      /* No LIMIT clause */\n    if( pSub->selFlags & SF_Aggregate ) return 0;     /* Not an aggregate */\n    pSub = pSub->pPrior;                              /* Repeat over compound */\n  }while( pSub );\n\n  /* If we reach this point then it is OK to perform the transformation */\n\n  db = pParse->db;\n  pCount = pExpr;\n  pExpr = 0;\n  pSub = p->pSrc->a[0].pSelect;\n  p->pSrc->a[0].pSelect = 0;\n  sqlite3SrcListDelete(db, p->pSrc);\n  p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));\n  while( pSub ){\n    Expr *pTerm;\n    pPrior = pSub->pPrior;\n    pSub->pPrior = 0;\n    pSub->pNext = 0;\n    pSub->selFlags |= SF_Aggregate;\n    pSub->selFlags &= ~SF_Compound;\n    pSub->nSelectRow = 0;\n    sqlite3ExprListDelete(db, pSub->pEList);\n    pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;\n    pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);\n    pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);\n    sqlite3PExprAddSelect(pParse, pTerm, pSub);\n    if( pExpr==0 ){\n      pExpr = pTerm;\n    }else{\n      pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);\n    }\n    pSub = pPrior;\n  }\n  p->pEList->a[0].pExpr = pExpr;\n  p->selFlags &= ~SF_Aggregate;\n\n#if SELECTTRACE_ENABLED\n  if( sqlite3SelectTrace & 0x400 ){\n    SELECTTRACE(0x400,pParse,p,(\"After count-of-view optimization:\\n\"));\n    sqlite3TreeViewSelect(0, p, 0);\n  }\n#endif\n  return 1;\n}\n#endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */\n\n/*\n** Generate code for the SELECT statement given in the p argument.  \n**\n** The results are returned according to the SelectDest structure.\n** See comments in sqliteInt.h for further information.\n**\n** This routine returns the number of errors.  If any errors are\n** encountered, then an appropriate error message is left in\n** pParse->zErrMsg.\n**\n** This routine does NOT free the Select structure passed in.  The\n** calling function needs to do that.\n*/\nSQLITE_PRIVATE int sqlite3Select(\n  Parse *pParse,         /* The parser context */\n  Select *p,             /* The SELECT statement being coded. */\n  SelectDest *pDest      /* What to do with the query results */\n){\n  int i, j;              /* Loop counters */\n  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */\n  Vdbe *v;               /* The virtual machine under construction */\n  int isAgg;             /* True for select lists like \"count(*)\" */\n  ExprList *pEList = 0;  /* List of columns to extract. */\n  SrcList *pTabList;     /* List of tables to select from */\n  Expr *pWhere;          /* The WHERE clause.  May be NULL */\n  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */\n  Expr *pHaving;         /* The HAVING clause.  May be NULL */\n  AggInfo *pAggInfo = 0; /* Aggregate information */\n  int rc = 1;            /* Value to return from this function */\n  DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */\n  SortCtx sSort;         /* Info on how to code the ORDER BY clause */\n  int iEnd;              /* Address of the end of the query */\n  sqlite3 *db;           /* The database connection */\n  ExprList *pMinMaxOrderBy = 0;  /* Added ORDER BY for min/max queries */\n  u8 minMaxFlag;                 /* Flag for min/max queries */\n\n  db = pParse->db;\n  v = sqlite3GetVdbe(pParse);\n  if( p==0 || db->mallocFailed || pParse->nErr ){\n    return 1;\n  }\n  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;\n#if SELECTTRACE_ENABLED\n  SELECTTRACE(1,pParse,p, (\"begin processing:\\n\", pParse->addrExplain));\n  if( sqlite3SelectTrace & 0x100 ){\n    sqlite3TreeViewSelect(0, p, 0);\n  }\n#endif\n\n  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );\n  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );\n  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );\n  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );\n  if( IgnorableOrderby(pDest) ){\n    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || \n           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||\n           pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||\n           pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);\n    /* If ORDER BY makes no difference in the output then neither does\n    ** DISTINCT so it can be removed too. */\n    sqlite3ExprListDelete(db, p->pOrderBy);\n    p->pOrderBy = 0;\n    p->selFlags &= ~SF_Distinct;\n    p->selFlags |= SF_NoopOrderBy;\n  }\n  sqlite3SelectPrep(pParse, p, 0);\n  if( pParse->nErr || db->mallocFailed ){\n    goto select_end;\n  }\n  assert( p->pEList!=0 );\n#if SELECTTRACE_ENABLED\n  if( sqlite3SelectTrace & 0x104 ){\n    SELECTTRACE(0x104,pParse,p, (\"after name resolution:\\n\"));\n    sqlite3TreeViewSelect(0, p, 0);\n  }\n#endif\n\n  if( pDest->eDest==SRT_Output ){\n    generateColumnNames(pParse, p);\n  }\n\n#ifndef SQLITE_OMIT_WINDOWFUNC\n  rc = sqlite3WindowRewrite(pParse, p);\n  if( rc ){\n    assert( db->mallocFailed || pParse->nErr>0 );\n    goto select_end;\n  }\n#if SELECTTRACE_ENABLED\n  if( p->pWin && (sqlite3SelectTrace & 0x108)!=0 ){\n    SELECTTRACE(0x104,pParse,p, (\"after window rewrite:\\n\"));\n    sqlite3TreeViewSelect(0, p, 0);\n  }\n#endif\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n  pTabList = p->pSrc;\n  isAgg = (p->selFlags & SF_Aggregate)!=0;\n  memset(&sSort, 0, sizeof(sSort));\n  sSort.pOrderBy = p->pOrderBy;\n\n  /* Try to various optimizations (flattening subqueries, and strength\n  ** reduction of join operators) in the FROM clause up into the main query\n  */\n#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)\n  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){\n    struct SrcList_item *pItem = &pTabList->a[i];\n    Select *pSub = pItem->pSelect;\n    Table *pTab = pItem->pTab;\n\n    /* Convert LEFT JOIN into JOIN if there are terms of the right table\n    ** of the LEFT JOIN used in the WHERE clause.\n    */\n    if( (pItem->fg.jointype & JT_LEFT)!=0\n     && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)\n     && OptimizationEnabled(db, SQLITE_SimplifyJoin)\n    ){\n      SELECTTRACE(0x100,pParse,p,\n                (\"LEFT-JOIN simplifies to JOIN on term %d\\n\",i));\n      pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);\n      unsetJoinExpr(p->pWhere, pItem->iCursor);\n    }\n\n    /* No futher action if this term of the FROM clause is no a subquery */\n    if( pSub==0 ) continue;\n\n    /* Catch mismatch in the declared columns of a view and the number of\n    ** columns in the SELECT on the RHS */\n    if( pTab->nCol!=pSub->pEList->nExpr ){\n      sqlite3ErrorMsg(pParse, \"expected %d columns for '%s' but got %d\",\n                      pTab->nCol, pTab->zName, pSub->pEList->nExpr);\n      goto select_end;\n    }\n\n    /* Do not try to flatten an aggregate subquery.\n    **\n    ** Flattening an aggregate subquery is only possible if the outer query\n    ** is not a join.  But if the outer query is not a join, then the subquery\n    ** will be implemented as a co-routine and there is no advantage to\n    ** flattening in that case.\n    */\n    if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;\n    assert( pSub->pGroupBy==0 );\n\n    /* If the outer query contains a \"complex\" result set (that is,\n    ** if the result set of the outer query uses functions or subqueries)\n    ** and if the subquery contains an ORDER BY clause and if\n    ** it will be implemented as a co-routine, then do not flatten.  This\n    ** restriction allows SQL constructs like this:\n    **\n    **  SELECT expensive_function(x)\n    **    FROM (SELECT x FROM tab ORDER BY y LIMIT 10);\n    **\n    ** The expensive_function() is only computed on the 10 rows that\n    ** are output, rather than every row of the table.\n    **\n    ** The requirement that the outer query have a complex result set\n    ** means that flattening does occur on simpler SQL constraints without\n    ** the expensive_function() like:\n    **\n    **  SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);\n    */\n    if( pSub->pOrderBy!=0\n     && i==0\n     && (p->selFlags & SF_ComplexResult)!=0\n     && (pTabList->nSrc==1\n         || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)\n    ){\n      continue;\n    }\n\n    if( flattenSubquery(pParse, p, i, isAgg) ){\n      if( pParse->nErr ) goto select_end;\n      /* This subquery can be absorbed into its parent. */\n      i = -1;\n    }\n    pTabList = p->pSrc;\n    if( db->mallocFailed ) goto select_end;\n    if( !IgnorableOrderby(pDest) ){\n      sSort.pOrderBy = p->pOrderBy;\n    }\n  }\n#endif\n\n#ifndef SQLITE_OMIT_COMPOUND_SELECT\n  /* Handle compound SELECT statements using the separate multiSelect()\n  ** procedure.\n  */\n  if( p->pPrior ){\n    rc = multiSelect(pParse, p, pDest);\n#if SELECTTRACE_ENABLED\n    SELECTTRACE(0x1,pParse,p,(\"end compound-select processing\\n\"));\n    if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){\n      sqlite3TreeViewSelect(0, p, 0);\n    }\n#endif\n    if( p->pNext==0 ) ExplainQueryPlanPop(pParse);\n    return rc;\n  }\n#endif\n\n  /* Do the WHERE-clause constant propagation optimization if this is\n  ** a join.  No need to speed time on this operation for non-join queries\n  ** as the equivalent optimization will be handled by query planner in\n  ** sqlite3WhereBegin().\n  */\n  if( pTabList->nSrc>1\n   && OptimizationEnabled(db, SQLITE_PropagateConst)\n   && propagateConstants(pParse, p)\n  ){\n#if SELECTTRACE_ENABLED\n    if( sqlite3SelectTrace & 0x100 ){\n      SELECTTRACE(0x100,pParse,p,(\"After constant propagation:\\n\"));\n      sqlite3TreeViewSelect(0, p, 0);\n    }\n#endif\n  }else{\n    SELECTTRACE(0x100,pParse,p,(\"Constant propagation not helpful\\n\"));\n  }\n\n#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION\n  if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)\n   && countOfViewOptimization(pParse, p)\n  ){\n    if( db->mallocFailed ) goto select_end;\n    pEList = p->pEList;\n    pTabList = p->pSrc;\n  }\n#endif\n\n  /* For each term in the FROM clause, do two things:\n  ** (1) Authorized unreferenced tables\n  ** (2) Generate code for all sub-queries\n  */\n  for(i=0; i<pTabList->nSrc; i++){\n    struct SrcList_item *pItem = &pTabList->a[i];\n    SelectDest dest;\n    Select *pSub;\n#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)\n    const char *zSavedAuthContext;\n#endif\n\n    /* Issue SQLITE_READ authorizations with a fake column name for any\n    ** tables that are referenced but from which no values are extracted.\n    ** Examples of where these kinds of null SQLITE_READ authorizations\n    ** would occur:\n    **\n    **     SELECT count(*) FROM t1;   -- SQLITE_READ t1.\"\"\n    **     SELECT t1.* FROM t1, t2;   -- SQLITE_READ t2.\"\"\n    **\n    ** The fake column name is an empty string.  It is possible for a table to\n    ** have a column named by the empty string, in which case there is no way to\n    ** distinguish between an unreferenced table and an actual reference to the\n    ** \"\" column. The original design was for the fake column name to be a NULL,\n    ** which would be unambiguous.  But legacy authorization callbacks might\n    ** assume the column name is non-NULL and segfault.  The use of an empty\n    ** string for the fake column name seems safer.\n    */\n    if( pItem->colUsed==0 && pItem->zName!=0 ){\n      sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, \"\", pItem->zDatabase);\n    }\n\n#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)\n    /* Generate code for all sub-queries in the FROM clause\n    */\n    pSub = pItem->pSelect;\n    if( pSub==0 ) continue;\n\n    /* The code for a subquery should only be generated once, though it is\n    ** technically harmless for it to be generated multiple times. The\n    ** following assert() will detect if something changes to cause\n    ** the same subquery to be coded multiple times, as a signal to the\n    ** developers to try to optimize the situation.\n    **\n    ** Update 2019-07-24:\n    ** See ticket https://sqlite.org/src/tktview/c52b09c7f38903b1311cec40.\n    ** The dbsqlfuzz fuzzer found a case where the same subquery gets\n    ** coded twice.  So this assert() now becomes a testcase().  It should\n    ** be very rare, though.\n    */\n    testcase( pItem->addrFillSub!=0 );\n\n    /* Increment Parse.nHeight by the height of the largest expression\n    ** tree referred to by this, the parent select. The child select\n    ** may contain expression trees of at most\n    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit\n    ** more conservative than necessary, but much easier than enforcing\n    ** an exact limit.\n    */\n    pParse->nHeight += sqlite3SelectExprHeight(p);\n\n    /* Make copies of constant WHERE-clause terms in the outer query down\n    ** inside the subquery.  This can help the subquery to run more efficiently.\n    */\n    if( OptimizationEnabled(db, SQLITE_PushDown)\n     && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor,\n                           (pItem->fg.jointype & JT_OUTER)!=0)\n    ){\n#if SELECTTRACE_ENABLED\n      if( sqlite3SelectTrace & 0x100 ){\n        SELECTTRACE(0x100,pParse,p,\n            (\"After WHERE-clause push-down into subquery %d:\\n\", pSub->selId));\n        sqlite3TreeViewSelect(0, p, 0);\n      }\n#endif\n    }else{\n      SELECTTRACE(0x100,pParse,p,(\"Push-down not possible\\n\"));\n    }\n\n    zSavedAuthContext = pParse->zAuthContext;\n    pParse->zAuthContext = pItem->zName;\n\n    /* Generate code to implement the subquery\n    **\n    ** The subquery is implemented as a co-routine if the subquery is\n    ** guaranteed to be the outer loop (so that it does not need to be\n    ** computed more than once)\n    **\n    ** TODO: Are there other reasons beside (1) to use a co-routine\n    ** implementation?\n    */\n    if( i==0\n     && (pTabList->nSrc==1\n            || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)  /* (1) */\n    ){\n      /* Implement a co-routine that will return a single row of the result\n      ** set on each invocation.\n      */\n      int addrTop = sqlite3VdbeCurrentAddr(v)+1;\n     \n      pItem->regReturn = ++pParse->nMem;\n      sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);\n      VdbeComment((v, \"%s\", pItem->pTab->zName));\n      pItem->addrFillSub = addrTop;\n      sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);\n      ExplainQueryPlan((pParse, 1, \"CO-ROUTINE %u\", pSub->selId));\n      sqlite3Select(pParse, pSub, &dest);\n      pItem->pTab->nRowLogEst = pSub->nSelectRow;\n      pItem->fg.viaCoroutine = 1;\n      pItem->regResult = dest.iSdst;\n      sqlite3VdbeEndCoroutine(v, pItem->regReturn);\n      sqlite3VdbeJumpHere(v, addrTop-1);\n      sqlite3ClearTempRegCache(pParse);\n    }else{\n      /* Generate a subroutine that will fill an ephemeral table with\n      ** the content of this subquery.  pItem->addrFillSub will point\n      ** to the address of the generated subroutine.  pItem->regReturn\n      ** is a register allocated to hold the subroutine return address\n      */\n      int topAddr;\n      int onceAddr = 0;\n      int retAddr;\n      struct SrcList_item *pPrior;\n\n      testcase( pItem->addrFillSub==0 ); /* Ticket c52b09c7f38903b1311 */\n      pItem->regReturn = ++pParse->nMem;\n      topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);\n      pItem->addrFillSub = topAddr+1;\n      if( pItem->fg.isCorrelated==0 ){\n        /* If the subquery is not correlated and if we are not inside of\n        ** a trigger, then we only need to compute the value of the subquery\n        ** once. */\n        onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);\n        VdbeComment((v, \"materialize \\\"%s\\\"\", pItem->pTab->zName));\n      }else{\n        VdbeNoopComment((v, \"materialize \\\"%s\\\"\", pItem->pTab->zName));\n      }\n      pPrior = isSelfJoinView(pTabList, pItem);\n      if( pPrior ){\n        sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);\n        assert( pPrior->pSelect!=0 );\n        pSub->nSelectRow = pPrior->pSelect->nSelectRow;\n      }else{\n        sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);\n        ExplainQueryPlan((pParse, 1, \"MATERIALIZE %u\", pSub->selId));\n        sqlite3Select(pParse, pSub, &dest);\n      }\n      pItem->pTab->nRowLogEst = pSub->nSelectRow;\n      if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);\n      retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);\n      VdbeComment((v, \"end %s\", pItem->pTab->zName));\n      sqlite3VdbeChangeP1(v, topAddr, retAddr);\n      sqlite3ClearTempRegCache(pParse);\n    }\n    if( db->mallocFailed ) goto select_end;\n    pParse->nHeight -= sqlite3SelectExprHeight(p);\n    pParse->zAuthContext = zSavedAuthContext;\n#endif\n  }\n\n  /* Various elements of the SELECT copied into local variables for\n  ** convenience */\n  pEList = p->pEList;\n  pWhere = p->pWhere;\n  pGroupBy = p->pGroupBy;\n  pHaving = p->pHaving;\n  sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;\n\n#if SELECTTRACE_ENABLED\n  if( sqlite3SelectTrace & 0x400 ){\n    SELECTTRACE(0x400,pParse,p,(\"After all FROM-clause analysis:\\n\"));\n    sqlite3TreeViewSelect(0, p, 0);\n  }\n#endif\n\n  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and \n  ** if the select-list is the same as the ORDER BY list, then this query\n  ** can be rewritten as a GROUP BY. In other words, this:\n  **\n  **     SELECT DISTINCT xyz FROM ... ORDER BY xyz\n  **\n  ** is transformed to:\n  **\n  **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz\n  **\n  ** The second form is preferred as a single index (or temp-table) may be \n  ** used for both the ORDER BY and DISTINCT processing. As originally \n  ** written the query must use a temp-table for at least one of the ORDER \n  ** BY and DISTINCT, and an index or separate temp-table for the other.\n  */\n  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct \n   && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0\n#ifndef SQLITE_OMIT_WINDOWFUNC\n   && p->pWin==0\n#endif\n  ){\n    p->selFlags &= ~SF_Distinct;\n    pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);\n    p->selFlags |= SF_Aggregate;\n    /* Notice that even thought SF_Distinct has been cleared from p->selFlags,\n    ** the sDistinct.isTnct is still set.  Hence, isTnct represents the\n    ** original setting of the SF_Distinct flag, not the current setting */\n    assert( sDistinct.isTnct );\n\n#if SELECTTRACE_ENABLED\n    if( sqlite3SelectTrace & 0x400 ){\n      SELECTTRACE(0x400,pParse,p,(\"Transform DISTINCT into GROUP BY:\\n\"));\n      sqlite3TreeViewSelect(0, p, 0);\n    }\n#endif\n  }\n\n  /* If there is an ORDER BY clause, then create an ephemeral index to\n  ** do the sorting.  But this sorting ephemeral index might end up\n  ** being unused if the data can be extracted in pre-sorted order.\n  ** If that is the case, then the OP_OpenEphemeral instruction will be\n  ** changed to an OP_Noop once we figure out that the sorting index is\n  ** not needed.  The sSort.addrSortIndex variable is used to facilitate\n  ** that change.\n  */\n  if( sSort.pOrderBy ){\n    KeyInfo *pKeyInfo;\n    pKeyInfo = sqlite3KeyInfoFromExprList(\n        pParse, sSort.pOrderBy, 0, pEList->nExpr);\n    sSort.iECursor = pParse->nTab++;\n    sSort.addrSortIndex =\n      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,\n          sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,\n          (char*)pKeyInfo, P4_KEYINFO\n      );\n  }else{\n    sSort.addrSortIndex = -1;\n  }\n\n  /* If the output is destined for a temporary table, open that table.\n  */\n  if( pDest->eDest==SRT_EphemTab ){\n    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);\n  }\n\n  /* Set the limiter.\n  */\n  iEnd = sqlite3VdbeMakeLabel(pParse);\n  if( (p->selFlags & SF_FixedLimit)==0 ){\n    p->nSelectRow = 320;  /* 4 billion rows */\n  }\n  computeLimitRegisters(pParse, p, iEnd);\n  if( p->iLimit==0 && sSort.addrSortIndex>=0 ){\n    sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);\n    sSort.sortFlags |= SORTFLAG_UseSorter;\n  }\n\n  /* Open an ephemeral index to use for the distinct set.\n  */\n  if( p->selFlags & SF_Distinct ){\n    sDistinct.tabTnct = pParse->nTab++;\n    sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,\n                       sDistinct.tabTnct, 0, 0,\n                       (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),\n                       P4_KEYINFO);\n    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);\n    sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;\n  }else{\n    sDistinct.eTnctType = WHERE_DISTINCT_NOOP;\n  }\n\n  if( !isAgg && pGroupBy==0 ){\n    /* No aggregate functions and no GROUP BY clause */\n    u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)\n                   | (p->selFlags & SF_FixedLimit);\n#ifndef SQLITE_OMIT_WINDOWFUNC\n    Window *pWin = p->pWin;      /* Master window object (or NULL) */\n    if( pWin ){\n      sqlite3WindowCodeInit(pParse, p);\n    }\n#endif\n    assert( WHERE_USE_LIMIT==SF_FixedLimit );\n\n\n    /* Begin the database scan. */\n    SELECTTRACE(1,pParse,p,(\"WhereBegin\\n\"));\n    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,\n                               p->pEList, wctrlFlags, p->nSelectRow);\n    if( pWInfo==0 ) goto select_end;\n    if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){\n      p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);\n    }\n    if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){\n      sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);\n    }\n    if( sSort.pOrderBy ){\n      sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);\n      sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);\n      if( sSort.nOBSat==sSort.pOrderBy->nExpr ){\n        sSort.pOrderBy = 0;\n      }\n    }\n\n    /* If sorting index that was created by a prior OP_OpenEphemeral \n    ** instruction ended up not being needed, then change the OP_OpenEphemeral\n    ** into an OP_Noop.\n    */\n    if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){\n      sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);\n    }\n\n    assert( p->pEList==pEList );\n#ifndef SQLITE_OMIT_WINDOWFUNC\n    if( pWin ){\n      int addrGosub = sqlite3VdbeMakeLabel(pParse);\n      int iCont = sqlite3VdbeMakeLabel(pParse);\n      int iBreak = sqlite3VdbeMakeLabel(pParse);\n      int regGosub = ++pParse->nMem;\n\n      sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);\n\n      sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);\n      sqlite3VdbeResolveLabel(v, addrGosub);\n      VdbeNoopComment((v, \"inner-loop subroutine\"));\n      sSort.labelOBLopt = 0;\n      selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);\n      sqlite3VdbeResolveLabel(v, iCont);\n      sqlite3VdbeAddOp1(v, OP_Return, regGosub);\n      VdbeComment((v, \"end inner-loop subroutine\"));\n      sqlite3VdbeResolveLabel(v, iBreak);\n    }else\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n    {\n      /* Use the standard inner loop. */\n      selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,\n          sqlite3WhereContinueLabel(pWInfo),\n          sqlite3WhereBreakLabel(pWInfo));\n\n      /* End the database scan loop.\n      */\n      sqlite3WhereEnd(pWInfo);\n    }\n  }else{\n    /* This case when there exist aggregate functions or a GROUP BY clause\n    ** or both */\n    NameContext sNC;    /* Name context for processing aggregate information */\n    int iAMem;          /* First Mem address for storing current GROUP BY */\n    int iBMem;          /* First Mem address for previous GROUP BY */\n    int iUseFlag;       /* Mem address holding flag indicating that at least\n                        ** one row of the input to the aggregator has been\n                        ** processed */\n    int iAbortFlag;     /* Mem address which causes query abort if positive */\n    int groupBySort;    /* Rows come from source in GROUP BY order */\n    int addrEnd;        /* End of processing for this SELECT */\n    int sortPTab = 0;   /* Pseudotable used to decode sorting results */\n    int sortOut = 0;    /* Output register from the sorter */\n    int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */\n\n    /* Remove any and all aliases between the result set and the\n    ** GROUP BY clause.\n    */\n    if( pGroupBy ){\n      int k;                        /* Loop counter */\n      struct ExprList_item *pItem;  /* For looping over expression in a list */\n\n      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){\n        pItem->u.x.iAlias = 0;\n      }\n      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){\n        pItem->u.x.iAlias = 0;\n      }\n      assert( 66==sqlite3LogEst(100) );\n      if( p->nSelectRow>66 ) p->nSelectRow = 66;\n\n      /* If there is both a GROUP BY and an ORDER BY clause and they are\n      ** identical, then it may be possible to disable the ORDER BY clause \n      ** on the grounds that the GROUP BY will cause elements to come out \n      ** in the correct order. It also may not - the GROUP BY might use a\n      ** database index that causes rows to be grouped together as required\n      ** but not actually sorted. Either way, record the fact that the\n      ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp\n      ** variable.  */\n      if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){\n        int ii;\n        /* The GROUP BY processing doesn't care whether rows are delivered in\n        ** ASC or DESC order - only that each group is returned contiguously.\n        ** So set the ASC/DESC flags in the GROUP BY to match those in the \n        ** ORDER BY to maximize the chances of rows being delivered in an \n        ** order that makes the ORDER BY redundant.  */\n        for(ii=0; ii<pGroupBy->nExpr; ii++){\n          u8 sortFlags = sSort.pOrderBy->a[ii].sortFlags & KEYINFO_ORDER_DESC;\n          pGroupBy->a[ii].sortFlags = sortFlags;\n        }\n        if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){\n          orderByGrp = 1;\n        }\n      }\n    }else{\n      assert( 0==sqlite3LogEst(1) );\n      p->nSelectRow = 0;\n    }\n\n    /* Create a label to jump to when we want to abort the query */\n    addrEnd = sqlite3VdbeMakeLabel(pParse);\n\n    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in\n    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the\n    ** SELECT statement.\n    */\n    pAggInfo = sqlite3DbMallocZero(db, sizeof(*pAggInfo) );\n    if( pAggInfo==0 ){\n      goto select_end;\n    }\n    pAggInfo->pNext = pParse->pAggList;\n    pParse->pAggList = pAggInfo;\n    memset(&sNC, 0, sizeof(sNC));\n    sNC.pParse = pParse;\n    sNC.pSrcList = pTabList;\n    sNC.uNC.pAggInfo = pAggInfo;\n    VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )\n    pAggInfo->mnReg = pParse->nMem+1;\n    pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;\n    pAggInfo->pGroupBy = pGroupBy;\n    sqlite3ExprAnalyzeAggList(&sNC, pEList);\n    sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);\n    if( pHaving ){\n      if( pGroupBy ){\n        assert( pWhere==p->pWhere );\n        assert( pHaving==p->pHaving );\n        assert( pGroupBy==p->pGroupBy );\n        havingToWhere(pParse, p);\n        pWhere = p->pWhere;\n      }\n      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);\n    }\n    pAggInfo->nAccumulator = pAggInfo->nColumn;\n    if( p->pGroupBy==0 && p->pHaving==0 && pAggInfo->nFunc==1 ){\n      minMaxFlag = minMaxQuery(db, pAggInfo->aFunc[0].pExpr, &pMinMaxOrderBy);\n    }else{\n      minMaxFlag = WHERE_ORDERBY_NORMAL;\n    }\n    for(i=0; i<pAggInfo->nFunc; i++){\n      Expr *pExpr = pAggInfo->aFunc[i].pExpr;\n      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );\n      sNC.ncFlags |= NC_InAggFunc;\n      sqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList);\n#ifndef SQLITE_OMIT_WINDOWFUNC\n      assert( !IsWindowFunc(pExpr) );\n      if( ExprHasProperty(pExpr, EP_WinFunc) ){\n        sqlite3ExprAnalyzeAggregates(&sNC, pExpr->y.pWin->pFilter);\n      }\n#endif\n      sNC.ncFlags &= ~NC_InAggFunc;\n    }\n    pAggInfo->mxReg = pParse->nMem;\n    if( db->mallocFailed ) goto select_end;\n#if SELECTTRACE_ENABLED\n    if( sqlite3SelectTrace & 0x400 ){\n      int ii;\n      SELECTTRACE(0x400,pParse,p,(\"After aggregate analysis %p:\\n\", pAggInfo));\n      sqlite3TreeViewSelect(0, p, 0);\n      for(ii=0; ii<pAggInfo->nColumn; ii++){\n        sqlite3DebugPrintf(\"agg-column[%d] iMem=%d\\n\",\n            ii, pAggInfo->aCol[ii].iMem);\n        sqlite3TreeViewExpr(0, pAggInfo->aCol[ii].pExpr, 0);\n      }\n      for(ii=0; ii<pAggInfo->nFunc; ii++){\n        sqlite3DebugPrintf(\"agg-func[%d]: iMem=%d\\n\",\n            ii, pAggInfo->aFunc[ii].iMem);\n        sqlite3TreeViewExpr(0, pAggInfo->aFunc[ii].pExpr, 0);\n      }\n    }\n#endif\n\n\n    /* Processing for aggregates with GROUP BY is very different and\n    ** much more complex than aggregates without a GROUP BY.\n    */\n    if( pGroupBy ){\n      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */\n      int addr1;          /* A-vs-B comparision jump */\n      int addrOutputRow;  /* Start of subroutine that outputs a result row */\n      int regOutputRow;   /* Return address register for output subroutine */\n      int addrSetAbort;   /* Set the abort flag and return */\n      int addrTopOfLoop;  /* Top of the input loop */\n      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */\n      int addrReset;      /* Subroutine for resetting the accumulator */\n      int regReset;       /* Return address register for reset subroutine */\n\n      /* If there is a GROUP BY clause we might need a sorting index to\n      ** implement it.  Allocate that sorting index now.  If it turns out\n      ** that we do not need it after all, the OP_SorterOpen instruction\n      ** will be converted into a Noop.  \n      */\n      pAggInfo->sortingIdx = pParse->nTab++;\n      pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pGroupBy,\n                                            0, pAggInfo->nColumn);\n      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, \n          pAggInfo->sortingIdx, pAggInfo->nSortingColumn, \n          0, (char*)pKeyInfo, P4_KEYINFO);\n\n      /* Initialize memory locations used by GROUP BY aggregate processing\n      */\n      iUseFlag = ++pParse->nMem;\n      iAbortFlag = ++pParse->nMem;\n      regOutputRow = ++pParse->nMem;\n      addrOutputRow = sqlite3VdbeMakeLabel(pParse);\n      regReset = ++pParse->nMem;\n      addrReset = sqlite3VdbeMakeLabel(pParse);\n      iAMem = pParse->nMem + 1;\n      pParse->nMem += pGroupBy->nExpr;\n      iBMem = pParse->nMem + 1;\n      pParse->nMem += pGroupBy->nExpr;\n      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);\n      VdbeComment((v, \"clear abort flag\"));\n      sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);\n\n      /* Begin a loop that will extract all source rows in GROUP BY order.\n      ** This might involve two separate loops with an OP_Sort in between, or\n      ** it might be a single loop that uses an index to extract information\n      ** in the right order to begin with.\n      */\n      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);\n      SELECTTRACE(1,pParse,p,(\"WhereBegin\\n\"));\n      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,\n          WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0\n      );\n      if( pWInfo==0 ) goto select_end;\n      if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){\n        /* The optimizer is able to deliver rows in group by order so\n        ** we do not have to sort.  The OP_OpenEphemeral table will be\n        ** cancelled later because we still need to use the pKeyInfo\n        */\n        groupBySort = 0;\n      }else{\n        /* Rows are coming out in undetermined order.  We have to push\n        ** each row into a sorting index, terminate the first loop,\n        ** then loop over the sorting index in order to get the output\n        ** in sorted order\n        */\n        int regBase;\n        int regRecord;\n        int nCol;\n        int nGroupBy;\n\n        explainTempTable(pParse, \n            (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?\n                    \"DISTINCT\" : \"GROUP BY\");\n\n        groupBySort = 1;\n        nGroupBy = pGroupBy->nExpr;\n        nCol = nGroupBy;\n        j = nGroupBy;\n        for(i=0; i<pAggInfo->nColumn; i++){\n          if( pAggInfo->aCol[i].iSorterColumn>=j ){\n            nCol++;\n            j++;\n          }\n        }\n        regBase = sqlite3GetTempRange(pParse, nCol);\n        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);\n        j = nGroupBy;\n        for(i=0; i<pAggInfo->nColumn; i++){\n          struct AggInfo_col *pCol = &pAggInfo->aCol[i];\n          if( pCol->iSorterColumn>=j ){\n            int r1 = j + regBase;\n            sqlite3ExprCodeGetColumnOfTable(v,\n                               pCol->pTab, pCol->iTable, pCol->iColumn, r1);\n            j++;\n          }\n        }\n        regRecord = sqlite3GetTempReg(pParse);\n        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);\n        sqlite3VdbeAddOp2(v, OP_SorterInsert, pAggInfo->sortingIdx, regRecord);\n        sqlite3ReleaseTempReg(pParse, regRecord);\n        sqlite3ReleaseTempRange(pParse, regBase, nCol);\n        sqlite3WhereEnd(pWInfo);\n        pAggInfo->sortingIdxPTab = sortPTab = pParse->nTab++;\n        sortOut = sqlite3GetTempReg(pParse);\n        sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);\n        sqlite3VdbeAddOp2(v, OP_SorterSort, pAggInfo->sortingIdx, addrEnd);\n        VdbeComment((v, \"GROUP BY sort\")); VdbeCoverage(v);\n        pAggInfo->useSortingIdx = 1;\n      }\n\n      /* If the index or temporary table used by the GROUP BY sort\n      ** will naturally deliver rows in the order required by the ORDER BY\n      ** clause, cancel the ephemeral table open coded earlier.\n      **\n      ** This is an optimization - the correct answer should result regardless.\n      ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to \n      ** disable this optimization for testing purposes.  */\n      if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) \n       && (groupBySort || sqlite3WhereIsSorted(pWInfo))\n      ){\n        sSort.pOrderBy = 0;\n        sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);\n      }\n\n      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...\n      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)\n      ** Then compare the current GROUP BY terms against the GROUP BY terms\n      ** from the previous row currently stored in a0, a1, a2...\n      */\n      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);\n      if( groupBySort ){\n        sqlite3VdbeAddOp3(v, OP_SorterData, pAggInfo->sortingIdx,\n                          sortOut, sortPTab);\n      }\n      for(j=0; j<pGroupBy->nExpr; j++){\n        if( groupBySort ){\n          sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);\n        }else{\n          pAggInfo->directMode = 1;\n          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);\n        }\n      }\n      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,\n                          (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);\n      addr1 = sqlite3VdbeCurrentAddr(v);\n      sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);\n\n      /* Generate code that runs whenever the GROUP BY changes.\n      ** Changes in the GROUP BY are detected by the previous code\n      ** block.  If there were no changes, this block is skipped.\n      **\n      ** This code copies current group by terms in b0,b1,b2,...\n      ** over to a0,a1,a2.  It then calls the output subroutine\n      ** and resets the aggregate accumulator registers in preparation\n      ** for the next GROUP BY batch.\n      */\n      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);\n      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);\n      VdbeComment((v, \"output one row\"));\n      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);\n      VdbeComment((v, \"check abort flag\"));\n      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);\n      VdbeComment((v, \"reset accumulator\"));\n\n      /* Update the aggregate accumulators based on the content of\n      ** the current row\n      */\n      sqlite3VdbeJumpHere(v, addr1);\n      updateAccumulator(pParse, iUseFlag, pAggInfo);\n      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);\n      VdbeComment((v, \"indicate data in accumulator\"));\n\n      /* End of the loop\n      */\n      if( groupBySort ){\n        sqlite3VdbeAddOp2(v, OP_SorterNext, pAggInfo->sortingIdx, addrTopOfLoop);\n        VdbeCoverage(v);\n      }else{\n        sqlite3WhereEnd(pWInfo);\n        sqlite3VdbeChangeToNoop(v, addrSortingIdx);\n      }\n\n      /* Output the final row of result\n      */\n      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);\n      VdbeComment((v, \"output final row\"));\n\n      /* Jump over the subroutines\n      */\n      sqlite3VdbeGoto(v, addrEnd);\n\n      /* Generate a subroutine that outputs a single row of the result\n      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag\n      ** is less than or equal to zero, the subroutine is a no-op.  If\n      ** the processing calls for the query to abort, this subroutine\n      ** increments the iAbortFlag memory location before returning in\n      ** order to signal the caller to abort.\n      */\n      addrSetAbort = sqlite3VdbeCurrentAddr(v);\n      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);\n      VdbeComment((v, \"set abort flag\"));\n      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);\n      sqlite3VdbeResolveLabel(v, addrOutputRow);\n      addrOutputRow = sqlite3VdbeCurrentAddr(v);\n      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);\n      VdbeCoverage(v);\n      VdbeComment((v, \"Groupby result generator entry point\"));\n      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);\n      finalizeAggFunctions(pParse, pAggInfo);\n      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);\n      selectInnerLoop(pParse, p, -1, &sSort,\n                      &sDistinct, pDest,\n                      addrOutputRow+1, addrSetAbort);\n      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);\n      VdbeComment((v, \"end groupby result generator\"));\n\n      /* Generate a subroutine that will reset the group-by accumulator\n      */\n      sqlite3VdbeResolveLabel(v, addrReset);\n      resetAccumulator(pParse, pAggInfo);\n      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);\n      VdbeComment((v, \"indicate accumulator empty\"));\n      sqlite3VdbeAddOp1(v, OP_Return, regReset);\n     \n    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */\n    else {\n      Table *pTab;\n      if( (pTab = isSimpleCount(p, pAggInfo))!=0 ){\n        /* If isSimpleCount() returns a pointer to a Table structure, then\n        ** the SQL statement is of the form:\n        **\n        **   SELECT count(*) FROM <tbl>\n        **\n        ** where the Table structure returned represents table <tbl>.\n        **\n        ** This statement is so common that it is optimized specially. The\n        ** OP_Count instruction is executed either on the intkey table that\n        ** contains the data for table <tbl> or on one of its indexes. It\n        ** is better to execute the op on an index, as indexes are almost\n        ** always spread across less pages than their corresponding tables.\n        */\n        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */\n        Index *pIdx;                         /* Iterator variable */\n        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */\n        Index *pBest = 0;                    /* Best index found so far */\n        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */\n\n        sqlite3CodeVerifySchema(pParse, iDb);\n        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);\n\n        /* Search for the index that has the lowest scan cost.\n        **\n        ** (2011-04-15) Do not do a full scan of an unordered index.\n        **\n        ** (2013-10-03) Do not count the entries in a partial index.\n        **\n        ** In practice the KeyInfo structure will not be used. It is only \n        ** passed to keep OP_OpenRead happy.\n        */\n        if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);\n        if( !p->pSrc->a[0].fg.notIndexed ){\n          for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n            if( pIdx->bUnordered==0\n             && pIdx->szIdxRow<pTab->szTabRow\n             && pIdx->pPartIdxWhere==0\n             && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)\n            ){\n              pBest = pIdx;\n            }\n          }\n        }\n        if( pBest ){\n          iRoot = pBest->tnum;\n          pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);\n        }\n\n        /* Open a read-only cursor, execute the OP_Count, close the cursor. */\n        sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);\n        if( pKeyInfo ){\n          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);\n        }\n        sqlite3VdbeAddOp2(v, OP_Count, iCsr, pAggInfo->aFunc[0].iMem);\n        sqlite3VdbeAddOp1(v, OP_Close, iCsr);\n        explainSimpleCount(pParse, pTab, pBest);\n      }else{\n        int regAcc = 0;           /* \"populate accumulators\" flag */\n\n        /* If there are accumulator registers but no min() or max() functions\n        ** without FILTER clauses, allocate register regAcc. Register regAcc\n        ** will contain 0 the first time the inner loop runs, and 1 thereafter.\n        ** The code generated by updateAccumulator() uses this to ensure\n        ** that the accumulator registers are (a) updated only once if\n        ** there are no min() or max functions or (b) always updated for the\n        ** first row visited by the aggregate, so that they are updated at\n        ** least once even if the FILTER clause means the min() or max() \n        ** function visits zero rows.  */\n        if( pAggInfo->nAccumulator ){\n          for(i=0; i<pAggInfo->nFunc; i++){\n            if( ExprHasProperty(pAggInfo->aFunc[i].pExpr, EP_WinFunc) ){\n              continue;\n            }\n            if( pAggInfo->aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ){\n              break;\n            }\n          }\n          if( i==pAggInfo->nFunc ){\n            regAcc = ++pParse->nMem;\n            sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);\n          }\n        }\n\n        /* This case runs if the aggregate has no GROUP BY clause.  The\n        ** processing is much simpler since there is only a single row\n        ** of output.\n        */\n        assert( p->pGroupBy==0 );\n        resetAccumulator(pParse, pAggInfo);\n\n        /* If this query is a candidate for the min/max optimization, then\n        ** minMaxFlag will have been previously set to either\n        ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will\n        ** be an appropriate ORDER BY expression for the optimization.\n        */\n        assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );\n        assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );\n\n        SELECTTRACE(1,pParse,p,(\"WhereBegin\\n\"));\n        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,\n                                   0, minMaxFlag, 0);\n        if( pWInfo==0 ){\n          goto select_end;\n        }\n        updateAccumulator(pParse, regAcc, pAggInfo);\n        if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);\n        if( sqlite3WhereIsOrdered(pWInfo)>0 ){\n          sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));\n          VdbeComment((v, \"%s() by index\",\n                (minMaxFlag==WHERE_ORDERBY_MIN?\"min\":\"max\")));\n        }\n        sqlite3WhereEnd(pWInfo);\n        finalizeAggFunctions(pParse, pAggInfo);\n      }\n\n      sSort.pOrderBy = 0;\n      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);\n      selectInnerLoop(pParse, p, -1, 0, 0, \n                      pDest, addrEnd, addrEnd);\n    }\n    sqlite3VdbeResolveLabel(v, addrEnd);\n    \n  } /* endif aggregate query */\n\n  if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){\n    explainTempTable(pParse, \"DISTINCT\");\n  }\n\n  /* If there is an ORDER BY clause, then we need to sort the results\n  ** and send them to the callback one by one.\n  */\n  if( sSort.pOrderBy ){\n    explainTempTable(pParse,\n                     sSort.nOBSat>0 ? \"RIGHT PART OF ORDER BY\":\"ORDER BY\");\n    assert( p->pEList==pEList );\n    generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);\n  }\n\n  /* Jump here to skip this query\n  */\n  sqlite3VdbeResolveLabel(v, iEnd);\n\n  /* The SELECT has been coded. If there is an error in the Parse structure,\n  ** set the return code to 1. Otherwise 0. */\n  rc = (pParse->nErr>0);\n\n  /* Control jumps to here if an error is encountered above, or upon\n  ** successful coding of the SELECT.\n  */\nselect_end:\n  sqlite3ExprListDelete(db, pMinMaxOrderBy);\n#ifdef SQLITE_DEBUG\n  if( pAggInfo && !db->mallocFailed ){\n    for(i=0; i<pAggInfo->nColumn; i++){\n      Expr *pExpr = pAggInfo->aCol[i].pExpr;\n      assert( pExpr!=0 || db->mallocFailed );\n      if( pExpr==0 ) continue;\n      assert( pExpr->pAggInfo==pAggInfo );\n      assert( pExpr->iAgg==i );\n    }\n    for(i=0; i<pAggInfo->nFunc; i++){\n      Expr *pExpr = pAggInfo->aFunc[i].pExpr;\n      assert( pExpr!=0 || db->mallocFailed );\n      if( pExpr==0 ) continue;\n      assert( pExpr->pAggInfo==pAggInfo );\n      assert( pExpr->iAgg==i );\n    }\n  }\n#endif\n\n#if SELECTTRACE_ENABLED\n  SELECTTRACE(0x1,pParse,p,(\"end processing\\n\"));\n  if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){\n    sqlite3TreeViewSelect(0, p, 0);\n  }\n#endif\n  ExplainQueryPlanPop(pParse);\n  return rc;\n}\n\n/************** End of select.c **********************************************/\n/************** Begin file table.c *******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the sqlite3_get_table() and sqlite3_free_table()\n** interface routines.  These are just wrappers around the main\n** interface routine of sqlite3_exec().\n**\n** These routines are in a separate files so that they will not be linked\n** if they are not used.\n*/\n/* #include \"sqliteInt.h\" */\n\n#ifndef SQLITE_OMIT_GET_TABLE\n\n/*\n** This structure is used to pass data from sqlite3_get_table() through\n** to the callback function is uses to build the result.\n*/\ntypedef struct TabResult {\n  char **azResult;   /* Accumulated output */\n  char *zErrMsg;     /* Error message text, if an error occurs */\n  u32 nAlloc;        /* Slots allocated for azResult[] */\n  u32 nRow;          /* Number of rows in the result */\n  u32 nColumn;       /* Number of columns in the result */\n  u32 nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */\n  int rc;            /* Return code from sqlite3_exec() */\n} TabResult;\n\n/*\n** This routine is called once for each row in the result table.  Its job\n** is to fill in the TabResult structure appropriately, allocating new\n** memory as necessary.\n*/\nstatic int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){\n  TabResult *p = (TabResult*)pArg;  /* Result accumulator */\n  int need;                         /* Slots needed in p->azResult[] */\n  int i;                            /* Loop counter */\n  char *z;                          /* A single column of result */\n\n  /* Make sure there is enough space in p->azResult to hold everything\n  ** we need to remember from this invocation of the callback.\n  */\n  if( p->nRow==0 && argv!=0 ){\n    need = nCol*2;\n  }else{\n    need = nCol;\n  }\n  if( p->nData + need > p->nAlloc ){\n    char **azNew;\n    p->nAlloc = p->nAlloc*2 + need;\n    azNew = sqlite3Realloc( p->azResult, sizeof(char*)*p->nAlloc );\n    if( azNew==0 ) goto malloc_failed;\n    p->azResult = azNew;\n  }\n\n  /* If this is the first row, then generate an extra row containing\n  ** the names of all columns.\n  */\n  if( p->nRow==0 ){\n    p->nColumn = nCol;\n    for(i=0; i<nCol; i++){\n      z = sqlite3_mprintf(\"%s\", colv[i]);\n      if( z==0 ) goto malloc_failed;\n      p->azResult[p->nData++] = z;\n    }\n  }else if( (int)p->nColumn!=nCol ){\n    sqlite3_free(p->zErrMsg);\n    p->zErrMsg = sqlite3_mprintf(\n       \"sqlite3_get_table() called with two or more incompatible queries\"\n    );\n    p->rc = SQLITE_ERROR;\n    return 1;\n  }\n\n  /* Copy over the row data\n  */\n  if( argv!=0 ){\n    for(i=0; i<nCol; i++){\n      if( argv[i]==0 ){\n        z = 0;\n      }else{\n        int n = sqlite3Strlen30(argv[i])+1;\n        z = sqlite3_malloc64( n );\n        if( z==0 ) goto malloc_failed;\n        memcpy(z, argv[i], n);\n      }\n      p->azResult[p->nData++] = z;\n    }\n    p->nRow++;\n  }\n  return 0;\n\nmalloc_failed:\n  p->rc = SQLITE_NOMEM_BKPT;\n  return 1;\n}\n\n/*\n** Query the database.  But instead of invoking a callback for each row,\n** malloc() for space to hold the result and return the entire results\n** at the conclusion of the call.\n**\n** The result that is written to ***pazResult is held in memory obtained\n** from malloc().  But the caller cannot free this memory directly.  \n** Instead, the entire table should be passed to sqlite3_free_table() when\n** the calling procedure is finished using it.\n*/\nSQLITE_API int sqlite3_get_table(\n  sqlite3 *db,                /* The database on which the SQL executes */\n  const char *zSql,           /* The SQL to be executed */\n  char ***pazResult,          /* Write the result table here */\n  int *pnRow,                 /* Write the number of rows in the result here */\n  int *pnColumn,              /* Write the number of columns of result here */\n  char **pzErrMsg             /* Write error messages here */\n){\n  int rc;\n  TabResult res;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;\n#endif\n  *pazResult = 0;\n  if( pnColumn ) *pnColumn = 0;\n  if( pnRow ) *pnRow = 0;\n  if( pzErrMsg ) *pzErrMsg = 0;\n  res.zErrMsg = 0;\n  res.nRow = 0;\n  res.nColumn = 0;\n  res.nData = 1;\n  res.nAlloc = 20;\n  res.rc = SQLITE_OK;\n  res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );\n  if( res.azResult==0 ){\n     db->errCode = SQLITE_NOMEM;\n     return SQLITE_NOMEM_BKPT;\n  }\n  res.azResult[0] = 0;\n  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);\n  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );\n  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);\n  if( (rc&0xff)==SQLITE_ABORT ){\n    sqlite3_free_table(&res.azResult[1]);\n    if( res.zErrMsg ){\n      if( pzErrMsg ){\n        sqlite3_free(*pzErrMsg);\n        *pzErrMsg = sqlite3_mprintf(\"%s\",res.zErrMsg);\n      }\n      sqlite3_free(res.zErrMsg);\n    }\n    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */\n    return res.rc;\n  }\n  sqlite3_free(res.zErrMsg);\n  if( rc!=SQLITE_OK ){\n    sqlite3_free_table(&res.azResult[1]);\n    return rc;\n  }\n  if( res.nAlloc>res.nData ){\n    char **azNew;\n    azNew = sqlite3Realloc( res.azResult, sizeof(char*)*res.nData );\n    if( azNew==0 ){\n      sqlite3_free_table(&res.azResult[1]);\n      db->errCode = SQLITE_NOMEM;\n      return SQLITE_NOMEM_BKPT;\n    }\n    res.azResult = azNew;\n  }\n  *pazResult = &res.azResult[1];\n  if( pnColumn ) *pnColumn = res.nColumn;\n  if( pnRow ) *pnRow = res.nRow;\n  return rc;\n}\n\n/*\n** This routine frees the space the sqlite3_get_table() malloced.\n*/\nSQLITE_API void sqlite3_free_table(\n  char **azResult            /* Result returned from sqlite3_get_table() */\n){\n  if( azResult ){\n    int i, n;\n    azResult--;\n    assert( azResult!=0 );\n    n = SQLITE_PTR_TO_INT(azResult[0]);\n    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }\n    sqlite3_free(azResult);\n  }\n}\n\n#endif /* SQLITE_OMIT_GET_TABLE */\n\n/************** End of table.c ***********************************************/\n/************** Begin file trigger.c *****************************************/\n/*\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the implementation for TRIGGERs\n*/\n/* #include \"sqliteInt.h\" */\n\n#ifndef SQLITE_OMIT_TRIGGER\n/*\n** Delete a linked list of TriggerStep structures.\n*/\nSQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){\n  while( pTriggerStep ){\n    TriggerStep * pTmp = pTriggerStep;\n    pTriggerStep = pTriggerStep->pNext;\n\n    sqlite3ExprDelete(db, pTmp->pWhere);\n    sqlite3ExprListDelete(db, pTmp->pExprList);\n    sqlite3SelectDelete(db, pTmp->pSelect);\n    sqlite3IdListDelete(db, pTmp->pIdList);\n    sqlite3UpsertDelete(db, pTmp->pUpsert);\n    sqlite3DbFree(db, pTmp->zSpan);\n\n    sqlite3DbFree(db, pTmp);\n  }\n}\n\n/*\n** Given table pTab, return a list of all the triggers attached to \n** the table. The list is connected by Trigger.pNext pointers.\n**\n** All of the triggers on pTab that are in the same database as pTab\n** are already attached to pTab->pTrigger.  But there might be additional\n** triggers on pTab in the TEMP schema.  This routine prepends all\n** TEMP triggers on pTab to the beginning of the pTab->pTrigger list\n** and returns the combined list.\n**\n** To state it another way:  This routine returns a list of all triggers\n** that fire off of pTab.  The list will include any TEMP triggers on\n** pTab as well as the triggers lised in pTab->pTrigger.\n*/\nSQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){\n  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;\n  Trigger *pList = 0;                  /* List of triggers to return */\n\n  if( pParse->disableTriggers ){\n    return 0;\n  }\n\n  if( pTmpSchema!=pTab->pSchema ){\n    HashElem *p;\n    assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );\n    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){\n      Trigger *pTrig = (Trigger *)sqliteHashData(p);\n      if( pTrig->pTabSchema==pTab->pSchema\n       && 0==sqlite3StrICmp(pTrig->table, pTab->zName) \n      ){\n        pTrig->pNext = (pList ? pList : pTab->pTrigger);\n        pList = pTrig;\n      }\n    }\n  }\n\n  return (pList ? pList : pTab->pTrigger);\n}\n\n/*\n** This is called by the parser when it sees a CREATE TRIGGER statement\n** up to the point of the BEGIN before the trigger actions.  A Trigger\n** structure is generated based on the information available and stored\n** in pParse->pNewTrigger.  After the trigger actions have been parsed, the\n** sqlite3FinishTrigger() function is called to complete the trigger\n** construction process.\n*/\nSQLITE_PRIVATE void sqlite3BeginTrigger(\n  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */\n  Token *pName1,      /* The name of the trigger */\n  Token *pName2,      /* The name of the trigger */\n  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */\n  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */\n  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */\n  SrcList *pTableName,/* The name of the table/view the trigger applies to */\n  Expr *pWhen,        /* WHEN clause */\n  int isTemp,         /* True if the TEMPORARY keyword is present */\n  int noErr           /* Suppress errors if the trigger already exists */\n){\n  Trigger *pTrigger = 0;  /* The new trigger */\n  Table *pTab;            /* Table that the trigger fires off of */\n  char *zName = 0;        /* Name of the trigger */\n  sqlite3 *db = pParse->db;  /* The database connection */\n  int iDb;                /* The database to store the trigger in */\n  Token *pName;           /* The unqualified db name */\n  DbFixer sFix;           /* State vector for the DB fixer */\n\n  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */\n  assert( pName2!=0 );\n  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );\n  assert( op>0 && op<0xff );\n  if( isTemp ){\n    /* If TEMP was specified, then the trigger name may not be qualified. */\n    if( pName2->n>0 ){\n      sqlite3ErrorMsg(pParse, \"temporary trigger may not have qualified name\");\n      goto trigger_cleanup;\n    }\n    iDb = 1;\n    pName = pName1;\n  }else{\n    /* Figure out the db that the trigger will be created in */\n    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);\n    if( iDb<0 ){\n      goto trigger_cleanup;\n    }\n  }\n  if( !pTableName || db->mallocFailed ){\n    goto trigger_cleanup;\n  }\n\n  /* A long-standing parser bug is that this syntax was allowed:\n  **\n  **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....\n  **                                                 ^^^^^^^^\n  **\n  ** To maintain backwards compatibility, ignore the database\n  ** name on pTableName if we are reparsing out of SQLITE_MASTER.\n  */\n  if( db->init.busy && iDb!=1 ){\n    sqlite3DbFree(db, pTableName->a[0].zDatabase);\n    pTableName->a[0].zDatabase = 0;\n  }\n\n  /* If the trigger name was unqualified, and the table is a temp table,\n  ** then set iDb to 1 to create the trigger in the temporary database.\n  ** If sqlite3SrcListLookup() returns 0, indicating the table does not\n  ** exist, the error is caught by the block below.\n  */\n  pTab = sqlite3SrcListLookup(pParse, pTableName);\n  if( db->init.busy==0 && pName2->n==0 && pTab\n        && pTab->pSchema==db->aDb[1].pSchema ){\n    iDb = 1;\n  }\n\n  /* Ensure the table name matches database name and that the table exists */\n  if( db->mallocFailed ) goto trigger_cleanup;\n  assert( pTableName->nSrc==1 );\n  sqlite3FixInit(&sFix, pParse, iDb, \"trigger\", pName);\n  if( sqlite3FixSrcList(&sFix, pTableName) ){\n    goto trigger_cleanup;\n  }\n  pTab = sqlite3SrcListLookup(pParse, pTableName);\n  if( !pTab ){\n    /* The table does not exist. */\n    if( db->init.iDb==1 ){\n      /* Ticket #3810.\n      ** Normally, whenever a table is dropped, all associated triggers are\n      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table\n      ** and the table is dropped by a different database connection, the\n      ** trigger is not visible to the database connection that does the\n      ** drop so the trigger cannot be dropped.  This results in an\n      ** \"orphaned trigger\" - a trigger whose associated table is missing.\n      */\n      db->init.orphanTrigger = 1;\n    }\n    goto trigger_cleanup;\n  }\n  if( IsVirtual(pTab) ){\n    sqlite3ErrorMsg(pParse, \"cannot create triggers on virtual tables\");\n    goto trigger_cleanup;\n  }\n\n  /* Check that the trigger name is not reserved and that no trigger of the\n  ** specified name exists */\n  zName = sqlite3NameFromToken(db, pName);\n  if( zName==0 ){\n    assert( db->mallocFailed );\n    goto trigger_cleanup;\n  }\n  if( sqlite3CheckObjectName(pParse, zName, \"trigger\", pTab->zName) ){\n    goto trigger_cleanup;\n  }\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  if( !IN_RENAME_OBJECT ){\n    if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){\n      if( !noErr ){\n        sqlite3ErrorMsg(pParse, \"trigger %T already exists\", pName);\n      }else{\n        assert( !db->init.busy );\n        sqlite3CodeVerifySchema(pParse, iDb);\n      }\n      goto trigger_cleanup;\n    }\n  }\n\n  /* Do not create a trigger on a system table */\n  if( sqlite3StrNICmp(pTab->zName, \"sqlite_\", 7)==0 ){\n    sqlite3ErrorMsg(pParse, \"cannot create trigger on system table\");\n    goto trigger_cleanup;\n  }\n\n  /* INSTEAD of triggers are only for views and views only support INSTEAD\n  ** of triggers.\n  */\n  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){\n    sqlite3ErrorMsg(pParse, \"cannot create %s trigger on view: %S\", \n        (tr_tm == TK_BEFORE)?\"BEFORE\":\"AFTER\", pTableName, 0);\n    goto trigger_cleanup;\n  }\n  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){\n    sqlite3ErrorMsg(pParse, \"cannot create INSTEAD OF\"\n        \" trigger on table: %S\", pTableName, 0);\n    goto trigger_cleanup;\n  }\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  if( !IN_RENAME_OBJECT ){\n    int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n    int code = SQLITE_CREATE_TRIGGER;\n    const char *zDb = db->aDb[iTabDb].zDbSName;\n    const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;\n    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;\n    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){\n      goto trigger_cleanup;\n    }\n    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){\n      goto trigger_cleanup;\n    }\n  }\n#endif\n\n  /* INSTEAD OF triggers can only appear on views and BEFORE triggers\n  ** cannot appear on views.  So we might as well translate every\n  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code\n  ** elsewhere.\n  */\n  if (tr_tm == TK_INSTEAD){\n    tr_tm = TK_BEFORE;\n  }\n\n  /* Build the Trigger object */\n  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));\n  if( pTrigger==0 ) goto trigger_cleanup;\n  pTrigger->zName = zName;\n  zName = 0;\n  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);\n  pTrigger->pSchema = db->aDb[iDb].pSchema;\n  pTrigger->pTabSchema = pTab->pSchema;\n  pTrigger->op = (u8)op;\n  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;\n  if( IN_RENAME_OBJECT ){\n    sqlite3RenameTokenRemap(pParse, pTrigger->table, pTableName->a[0].zName);\n    pTrigger->pWhen = pWhen;\n    pWhen = 0;\n  }else{\n    pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);\n  }\n  pTrigger->pColumns = pColumns;\n  pColumns = 0;\n  assert( pParse->pNewTrigger==0 );\n  pParse->pNewTrigger = pTrigger;\n\ntrigger_cleanup:\n  sqlite3DbFree(db, zName);\n  sqlite3SrcListDelete(db, pTableName);\n  sqlite3IdListDelete(db, pColumns);\n  sqlite3ExprDelete(db, pWhen);\n  if( !pParse->pNewTrigger ){\n    sqlite3DeleteTrigger(db, pTrigger);\n  }else{\n    assert( pParse->pNewTrigger==pTrigger );\n  }\n}\n\n/*\n** This routine is called after all of the trigger actions have been parsed\n** in order to complete the process of building the trigger.\n*/\nSQLITE_PRIVATE void sqlite3FinishTrigger(\n  Parse *pParse,          /* Parser context */\n  TriggerStep *pStepList, /* The triggered program */\n  Token *pAll             /* Token that describes the complete CREATE TRIGGER */\n){\n  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */\n  char *zName;                            /* Name of trigger */\n  sqlite3 *db = pParse->db;               /* The database */\n  DbFixer sFix;                           /* Fixer object */\n  int iDb;                                /* Database containing the trigger */\n  Token nameToken;                        /* Trigger name for error reporting */\n\n  pParse->pNewTrigger = 0;\n  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;\n  zName = pTrig->zName;\n  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);\n  pTrig->step_list = pStepList;\n  while( pStepList ){\n    pStepList->pTrig = pTrig;\n    pStepList = pStepList->pNext;\n  }\n  sqlite3TokenInit(&nameToken, pTrig->zName);\n  sqlite3FixInit(&sFix, pParse, iDb, \"trigger\", &nameToken);\n  if( sqlite3FixTriggerStep(&sFix, pTrig->step_list) \n   || sqlite3FixExpr(&sFix, pTrig->pWhen) \n  ){\n    goto triggerfinish_cleanup;\n  }\n\n#ifndef SQLITE_OMIT_ALTERTABLE\n  if( IN_RENAME_OBJECT ){\n    assert( !db->init.busy );\n    pParse->pNewTrigger = pTrig;\n    pTrig = 0;\n  }else\n#endif\n\n  /* if we are not initializing,\n  ** build the sqlite_master entry\n  */\n  if( !db->init.busy ){\n    Vdbe *v;\n    char *z;\n\n    /* Make an entry in the sqlite_master table */\n    v = sqlite3GetVdbe(pParse);\n    if( v==0 ) goto triggerfinish_cleanup;\n    sqlite3BeginWriteOperation(pParse, 0, iDb);\n    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);\n    testcase( z==0 );\n    sqlite3NestedParse(pParse,\n       \"INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')\",\n       db->aDb[iDb].zDbSName, MASTER_NAME, zName,\n       pTrig->table, z);\n    sqlite3DbFree(db, z);\n    sqlite3ChangeCookie(pParse, iDb);\n    sqlite3VdbeAddParseSchemaOp(v, iDb,\n        sqlite3MPrintf(db, \"type='trigger' AND name='%q'\", zName));\n  }\n\n  if( db->init.busy ){\n    Trigger *pLink = pTrig;\n    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;\n    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n    assert( pLink!=0 );\n    pTrig = sqlite3HashInsert(pHash, zName, pTrig);\n    if( pTrig ){\n      sqlite3OomFault(db);\n    }else if( pLink->pSchema==pLink->pTabSchema ){\n      Table *pTab;\n      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);\n      assert( pTab!=0 );\n      pLink->pNext = pTab->pTrigger;\n      pTab->pTrigger = pLink;\n    }\n  }\n\ntriggerfinish_cleanup:\n  sqlite3DeleteTrigger(db, pTrig);\n  assert( IN_RENAME_OBJECT || !pParse->pNewTrigger );\n  sqlite3DeleteTriggerStep(db, pStepList);\n}\n\n/*\n** Duplicate a range of text from an SQL statement, then convert all\n** whitespace characters into ordinary space characters.\n*/\nstatic char *triggerSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){\n  char *z = sqlite3DbSpanDup(db, zStart, zEnd);\n  int i;\n  if( z ) for(i=0; z[i]; i++) if( sqlite3Isspace(z[i]) ) z[i] = ' ';\n  return z;\n}    \n\n/*\n** Turn a SELECT statement (that the pSelect parameter points to) into\n** a trigger step.  Return a pointer to a TriggerStep structure.\n**\n** The parser calls this routine when it finds a SELECT statement in\n** body of a TRIGGER.  \n*/\nSQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(\n  sqlite3 *db,                /* Database connection */\n  Select *pSelect,            /* The SELECT statement */\n  const char *zStart,         /* Start of SQL text */\n  const char *zEnd            /* End of SQL text */\n){\n  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));\n  if( pTriggerStep==0 ) {\n    sqlite3SelectDelete(db, pSelect);\n    return 0;\n  }\n  pTriggerStep->op = TK_SELECT;\n  pTriggerStep->pSelect = pSelect;\n  pTriggerStep->orconf = OE_Default;\n  pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);\n  return pTriggerStep;\n}\n\n/*\n** Allocate space to hold a new trigger step.  The allocated space\n** holds both the TriggerStep object and the TriggerStep.target.z string.\n**\n** If an OOM error occurs, NULL is returned and db->mallocFailed is set.\n*/\nstatic TriggerStep *triggerStepAllocate(\n  Parse *pParse,              /* Parser context */\n  u8 op,                      /* Trigger opcode */\n  Token *pName,               /* The target name */\n  const char *zStart,         /* Start of SQL text */\n  const char *zEnd            /* End of SQL text */\n){\n  sqlite3 *db = pParse->db;\n  TriggerStep *pTriggerStep;\n\n  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);\n  if( pTriggerStep ){\n    char *z = (char*)&pTriggerStep[1];\n    memcpy(z, pName->z, pName->n);\n    sqlite3Dequote(z);\n    pTriggerStep->zTarget = z;\n    pTriggerStep->op = op;\n    pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);\n    if( IN_RENAME_OBJECT ){\n      sqlite3RenameTokenMap(pParse, pTriggerStep->zTarget, pName);\n    }\n  }\n  return pTriggerStep;\n}\n\n/*\n** Build a trigger step out of an INSERT statement.  Return a pointer\n** to the new trigger step.\n**\n** The parser calls this routine when it sees an INSERT inside the\n** body of a trigger.\n*/\nSQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(\n  Parse *pParse,      /* Parser */\n  Token *pTableName,  /* Name of the table into which we insert */\n  IdList *pColumn,    /* List of columns in pTableName to insert into */\n  Select *pSelect,    /* A SELECT statement that supplies values */\n  u8 orconf,          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */\n  Upsert *pUpsert,    /* ON CONFLICT clauses for upsert */\n  const char *zStart, /* Start of SQL text */\n  const char *zEnd    /* End of SQL text */\n){\n  sqlite3 *db = pParse->db;\n  TriggerStep *pTriggerStep;\n\n  assert(pSelect != 0 || db->mallocFailed);\n\n  pTriggerStep = triggerStepAllocate(pParse, TK_INSERT, pTableName,zStart,zEnd);\n  if( pTriggerStep ){\n    if( IN_RENAME_OBJECT ){\n      pTriggerStep->pSelect = pSelect;\n      pSelect = 0;\n    }else{\n      pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);\n    }\n    pTriggerStep->pIdList = pColumn;\n    pTriggerStep->pUpsert = pUpsert;\n    pTriggerStep->orconf = orconf;\n    if( pUpsert ){\n      sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget);\n    }\n  }else{\n    testcase( pColumn );\n    sqlite3IdListDelete(db, pColumn);\n    testcase( pUpsert );\n    sqlite3UpsertDelete(db, pUpsert);\n  }\n  sqlite3SelectDelete(db, pSelect);\n\n  return pTriggerStep;\n}\n\n/*\n** Construct a trigger step that implements an UPDATE statement and return\n** a pointer to that trigger step.  The parser calls this routine when it\n** sees an UPDATE statement inside the body of a CREATE TRIGGER.\n*/\nSQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(\n  Parse *pParse,          /* Parser */\n  Token *pTableName,   /* Name of the table to be updated */\n  ExprList *pEList,    /* The SET clause: list of column and new values */\n  Expr *pWhere,        /* The WHERE clause */\n  u8 orconf,           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */\n  const char *zStart,  /* Start of SQL text */\n  const char *zEnd     /* End of SQL text */\n){\n  sqlite3 *db = pParse->db;\n  TriggerStep *pTriggerStep;\n\n  pTriggerStep = triggerStepAllocate(pParse, TK_UPDATE, pTableName,zStart,zEnd);\n  if( pTriggerStep ){\n    if( IN_RENAME_OBJECT ){\n      pTriggerStep->pExprList = pEList;\n      pTriggerStep->pWhere = pWhere;\n      pEList = 0;\n      pWhere = 0;\n    }else{\n      pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);\n      pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);\n    }\n    pTriggerStep->orconf = orconf;\n  }\n  sqlite3ExprListDelete(db, pEList);\n  sqlite3ExprDelete(db, pWhere);\n  return pTriggerStep;\n}\n\n/*\n** Construct a trigger step that implements a DELETE statement and return\n** a pointer to that trigger step.  The parser calls this routine when it\n** sees a DELETE statement inside the body of a CREATE TRIGGER.\n*/\nSQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(\n  Parse *pParse,          /* Parser */\n  Token *pTableName,      /* The table from which rows are deleted */\n  Expr *pWhere,           /* The WHERE clause */\n  const char *zStart,     /* Start of SQL text */\n  const char *zEnd        /* End of SQL text */\n){\n  sqlite3 *db = pParse->db;\n  TriggerStep *pTriggerStep;\n\n  pTriggerStep = triggerStepAllocate(pParse, TK_DELETE, pTableName,zStart,zEnd);\n  if( pTriggerStep ){\n    if( IN_RENAME_OBJECT ){\n      pTriggerStep->pWhere = pWhere;\n      pWhere = 0;\n    }else{\n      pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);\n    }\n    pTriggerStep->orconf = OE_Default;\n  }\n  sqlite3ExprDelete(db, pWhere);\n  return pTriggerStep;\n}\n\n/* \n** Recursively delete a Trigger structure\n*/\nSQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){\n  if( pTrigger==0 ) return;\n  sqlite3DeleteTriggerStep(db, pTrigger->step_list);\n  sqlite3DbFree(db, pTrigger->zName);\n  sqlite3DbFree(db, pTrigger->table);\n  sqlite3ExprDelete(db, pTrigger->pWhen);\n  sqlite3IdListDelete(db, pTrigger->pColumns);\n  sqlite3DbFree(db, pTrigger);\n}\n\n/*\n** This function is called to drop a trigger from the database schema. \n**\n** This may be called directly from the parser and therefore identifies\n** the trigger by name.  The sqlite3DropTriggerPtr() routine does the\n** same job as this routine except it takes a pointer to the trigger\n** instead of the trigger name.\n**/\nSQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){\n  Trigger *pTrigger = 0;\n  int i;\n  const char *zDb;\n  const char *zName;\n  sqlite3 *db = pParse->db;\n\n  if( db->mallocFailed ) goto drop_trigger_cleanup;\n  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){\n    goto drop_trigger_cleanup;\n  }\n\n  assert( pName->nSrc==1 );\n  zDb = pName->a[0].zDatabase;\n  zName = pName->a[0].zName;\n  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );\n  for(i=OMIT_TEMPDB; i<db->nDb; i++){\n    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */\n    if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;\n    assert( sqlite3SchemaMutexHeld(db, j, 0) );\n    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);\n    if( pTrigger ) break;\n  }\n  if( !pTrigger ){\n    if( !noErr ){\n      sqlite3ErrorMsg(pParse, \"no such trigger: %S\", pName, 0);\n    }else{\n      sqlite3CodeVerifyNamedSchema(pParse, zDb);\n    }\n    pParse->checkSchema = 1;\n    goto drop_trigger_cleanup;\n  }\n  sqlite3DropTriggerPtr(pParse, pTrigger);\n\ndrop_trigger_cleanup:\n  sqlite3SrcListDelete(db, pName);\n}\n\n/*\n** Return a pointer to the Table structure for the table that a trigger\n** is set on.\n*/\nstatic Table *tableOfTrigger(Trigger *pTrigger){\n  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);\n}\n\n\n/*\n** Drop a trigger given a pointer to that trigger. \n*/\nSQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){\n  Table   *pTable;\n  Vdbe *v;\n  sqlite3 *db = pParse->db;\n  int iDb;\n\n  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);\n  assert( iDb>=0 && iDb<db->nDb );\n  pTable = tableOfTrigger(pTrigger);\n  assert( (pTable && pTable->pSchema==pTrigger->pSchema) || iDb==1 );\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  if( pTable ){\n    int code = SQLITE_DROP_TRIGGER;\n    const char *zDb = db->aDb[iDb].zDbSName;\n    const char *zTab = SCHEMA_TABLE(iDb);\n    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;\n    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||\n      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){\n      return;\n    }\n  }\n#endif\n\n  /* Generate code to destroy the database record of the trigger.\n  */\n  if( (v = sqlite3GetVdbe(pParse))!=0 ){\n    sqlite3NestedParse(pParse,\n       \"DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'\",\n       db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName\n    );\n    sqlite3ChangeCookie(pParse, iDb);\n    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);\n  }\n}\n\n/*\n** Remove a trigger from the hash tables of the sqlite* pointer.\n*/\nSQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){\n  Trigger *pTrigger;\n  Hash *pHash;\n\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  pHash = &(db->aDb[iDb].pSchema->trigHash);\n  pTrigger = sqlite3HashInsert(pHash, zName, 0);\n  if( ALWAYS(pTrigger) ){\n    if( pTrigger->pSchema==pTrigger->pTabSchema ){\n      Table *pTab = tableOfTrigger(pTrigger);\n      if( pTab ){\n        Trigger **pp;\n        for(pp=&pTab->pTrigger; *pp; pp=&((*pp)->pNext)){\n          if( *pp==pTrigger ){\n            *pp = (*pp)->pNext;\n            break;\n          }\n        }\n      }\n    }\n    sqlite3DeleteTrigger(db, pTrigger);\n    db->mDbFlags |= DBFLAG_SchemaChange;\n  }\n}\n\n/*\n** pEList is the SET clause of an UPDATE statement.  Each entry\n** in pEList is of the format <id>=<expr>.  If any of the entries\n** in pEList have an <id> which matches an identifier in pIdList,\n** then return TRUE.  If pIdList==NULL, then it is considered a\n** wildcard that matches anything.  Likewise if pEList==NULL then\n** it matches anything so always return true.  Return false only\n** if there is no match.\n*/\nstatic int checkColumnOverlap(IdList *pIdList, ExprList *pEList){\n  int e;\n  if( pIdList==0 || NEVER(pEList==0) ) return 1;\n  for(e=0; e<pEList->nExpr; e++){\n    if( sqlite3IdListIndex(pIdList, pEList->a[e].zEName)>=0 ) return 1;\n  }\n  return 0; \n}\n\n/*\n** Return a list of all triggers on table pTab if there exists at least\n** one trigger that must be fired when an operation of type 'op' is \n** performed on the table, and, if that operation is an UPDATE, if at\n** least one of the columns in pChanges is being modified.\n*/\nSQLITE_PRIVATE Trigger *sqlite3TriggersExist(\n  Parse *pParse,          /* Parse context */\n  Table *pTab,            /* The table the contains the triggers */\n  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */\n  ExprList *pChanges,     /* Columns that change in an UPDATE statement */\n  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */\n){\n  int mask = 0;\n  Trigger *pList = 0;\n  Trigger *p;\n\n  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){\n    pList = sqlite3TriggerList(pParse, pTab);\n  }\n  assert( pList==0 || IsVirtual(pTab)==0 );\n  for(p=pList; p; p=p->pNext){\n    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){\n      mask |= p->tr_tm;\n    }\n  }\n  if( pMask ){\n    *pMask = mask;\n  }\n  return (mask ? pList : 0);\n}\n\n/*\n** Convert the pStep->zTarget string into a SrcList and return a pointer\n** to that SrcList.\n**\n** This routine adds a specific database name, if needed, to the target when\n** forming the SrcList.  This prevents a trigger in one database from\n** referring to a target in another database.  An exception is when the\n** trigger is in TEMP in which case it can refer to any other database it\n** wants.\n*/\nstatic SrcList *targetSrcList(\n  Parse *pParse,       /* The parsing context */\n  TriggerStep *pStep   /* The trigger containing the target token */\n){\n  sqlite3 *db = pParse->db;\n  int iDb;             /* Index of the database to use */\n  SrcList *pSrc;       /* SrcList to be returned */\n\n  pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);\n  if( pSrc ){\n    assert( pSrc->nSrc>0 );\n    pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);\n    iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);\n    if( iDb==0 || iDb>=2 ){\n      const char *zDb;\n      assert( iDb<db->nDb );\n      zDb = db->aDb[iDb].zDbSName;\n      pSrc->a[pSrc->nSrc-1].zDatabase =  sqlite3DbStrDup(db, zDb);\n    }\n  }\n  return pSrc;\n}\n\n/*\n** Generate VDBE code for the statements inside the body of a single \n** trigger.\n*/\nstatic int codeTriggerProgram(\n  Parse *pParse,            /* The parser context */\n  TriggerStep *pStepList,   /* List of statements inside the trigger body */\n  int orconf                /* Conflict algorithm. (OE_Abort, etc) */  \n){\n  TriggerStep *pStep;\n  Vdbe *v = pParse->pVdbe;\n  sqlite3 *db = pParse->db;\n\n  assert( pParse->pTriggerTab && pParse->pToplevel );\n  assert( pStepList );\n  assert( v!=0 );\n  for(pStep=pStepList; pStep; pStep=pStep->pNext){\n    /* Figure out the ON CONFLICT policy that will be used for this step\n    ** of the trigger program. If the statement that caused this trigger\n    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use\n    ** the ON CONFLICT policy that was specified as part of the trigger\n    ** step statement. Example:\n    **\n    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;\n    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);\n    **   END;\n    **\n    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy\n    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy\n    */\n    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;\n    assert( pParse->okConstFactor==0 );\n\n#ifndef SQLITE_OMIT_TRACE\n    if( pStep->zSpan ){\n      sqlite3VdbeAddOp4(v, OP_Trace, 0x7fffffff, 1, 0,\n                        sqlite3MPrintf(db, \"-- %s\", pStep->zSpan),\n                        P4_DYNAMIC);\n    }\n#endif\n\n    switch( pStep->op ){\n      case TK_UPDATE: {\n        sqlite3Update(pParse, \n          targetSrcList(pParse, pStep),\n          sqlite3ExprListDup(db, pStep->pExprList, 0), \n          sqlite3ExprDup(db, pStep->pWhere, 0), \n          pParse->eOrconf, 0, 0, 0\n        );\n        break;\n      }\n      case TK_INSERT: {\n        sqlite3Insert(pParse, \n          targetSrcList(pParse, pStep),\n          sqlite3SelectDup(db, pStep->pSelect, 0), \n          sqlite3IdListDup(db, pStep->pIdList), \n          pParse->eOrconf,\n          sqlite3UpsertDup(db, pStep->pUpsert)\n        );\n        break;\n      }\n      case TK_DELETE: {\n        sqlite3DeleteFrom(pParse, \n          targetSrcList(pParse, pStep),\n          sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0\n        );\n        break;\n      }\n      default: assert( pStep->op==TK_SELECT ); {\n        SelectDest sDest;\n        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);\n        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);\n        sqlite3Select(pParse, pSelect, &sDest);\n        sqlite3SelectDelete(db, pSelect);\n        break;\n      }\n    } \n    if( pStep->op!=TK_SELECT ){\n      sqlite3VdbeAddOp0(v, OP_ResetCount);\n    }\n  }\n\n  return 0;\n}\n\n#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS\n/*\n** This function is used to add VdbeComment() annotations to a VDBE\n** program. It is not used in production code, only for debugging.\n*/\nstatic const char *onErrorText(int onError){\n  switch( onError ){\n    case OE_Abort:    return \"abort\";\n    case OE_Rollback: return \"rollback\";\n    case OE_Fail:     return \"fail\";\n    case OE_Replace:  return \"replace\";\n    case OE_Ignore:   return \"ignore\";\n    case OE_Default:  return \"default\";\n  }\n  return \"n/a\";\n}\n#endif\n\n/*\n** Parse context structure pFrom has just been used to create a sub-vdbe\n** (trigger program). If an error has occurred, transfer error information\n** from pFrom to pTo.\n*/\nstatic void transferParseError(Parse *pTo, Parse *pFrom){\n  assert( pFrom->zErrMsg==0 || pFrom->nErr );\n  assert( pTo->zErrMsg==0 || pTo->nErr );\n  if( pTo->nErr==0 ){\n    pTo->zErrMsg = pFrom->zErrMsg;\n    pTo->nErr = pFrom->nErr;\n    pTo->rc = pFrom->rc;\n  }else{\n    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);\n  }\n}\n\n/*\n** Create and populate a new TriggerPrg object with a sub-program \n** implementing trigger pTrigger with ON CONFLICT policy orconf.\n*/\nstatic TriggerPrg *codeRowTrigger(\n  Parse *pParse,       /* Current parse context */\n  Trigger *pTrigger,   /* Trigger to code */\n  Table *pTab,         /* The table pTrigger is attached to */\n  int orconf           /* ON CONFLICT policy to code trigger program with */\n){\n  Parse *pTop = sqlite3ParseToplevel(pParse);\n  sqlite3 *db = pParse->db;   /* Database handle */\n  TriggerPrg *pPrg;           /* Value to return */\n  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */\n  Vdbe *v;                    /* Temporary VM */\n  NameContext sNC;            /* Name context for sub-vdbe */\n  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */\n  Parse *pSubParse;           /* Parse context for sub-vdbe */\n  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */\n\n  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );\n  assert( pTop->pVdbe );\n\n  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they\n  ** are freed if an error occurs, link them into the Parse.pTriggerPrg \n  ** list of the top-level Parse object sooner rather than later.  */\n  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));\n  if( !pPrg ) return 0;\n  pPrg->pNext = pTop->pTriggerPrg;\n  pTop->pTriggerPrg = pPrg;\n  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));\n  if( !pProgram ) return 0;\n  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);\n  pPrg->pTrigger = pTrigger;\n  pPrg->orconf = orconf;\n  pPrg->aColmask[0] = 0xffffffff;\n  pPrg->aColmask[1] = 0xffffffff;\n\n  /* Allocate and populate a new Parse context to use for coding the \n  ** trigger sub-program.  */\n  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));\n  if( !pSubParse ) return 0;\n  memset(&sNC, 0, sizeof(sNC));\n  sNC.pParse = pSubParse;\n  pSubParse->db = db;\n  pSubParse->pTriggerTab = pTab;\n  pSubParse->pToplevel = pTop;\n  pSubParse->zAuthContext = pTrigger->zName;\n  pSubParse->eTriggerOp = pTrigger->op;\n  pSubParse->nQueryLoop = pParse->nQueryLoop;\n  pSubParse->disableVtab = pParse->disableVtab;\n\n  v = sqlite3GetVdbe(pSubParse);\n  if( v ){\n    VdbeComment((v, \"Start: %s.%s (%s %s%s%s ON %s)\", \n      pTrigger->zName, onErrorText(orconf),\n      (pTrigger->tr_tm==TRIGGER_BEFORE ? \"BEFORE\" : \"AFTER\"),\n        (pTrigger->op==TK_UPDATE ? \"UPDATE\" : \"\"),\n        (pTrigger->op==TK_INSERT ? \"INSERT\" : \"\"),\n        (pTrigger->op==TK_DELETE ? \"DELETE\" : \"\"),\n      pTab->zName\n    ));\n#ifndef SQLITE_OMIT_TRACE\n    if( pTrigger->zName ){\n      sqlite3VdbeChangeP4(v, -1, \n        sqlite3MPrintf(db, \"-- TRIGGER %s\", pTrigger->zName), P4_DYNAMIC\n      );\n    }\n#endif\n\n    /* If one was specified, code the WHEN clause. If it evaluates to false\n    ** (or NULL) the sub-vdbe is immediately halted by jumping to the \n    ** OP_Halt inserted at the end of the program.  */\n    if( pTrigger->pWhen ){\n      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);\n      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) \n       && db->mallocFailed==0 \n      ){\n        iEndTrigger = sqlite3VdbeMakeLabel(pSubParse);\n        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);\n      }\n      sqlite3ExprDelete(db, pWhen);\n    }\n\n    /* Code the trigger program into the sub-vdbe. */\n    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);\n\n    /* Insert an OP_Halt at the end of the sub-program. */\n    if( iEndTrigger ){\n      sqlite3VdbeResolveLabel(v, iEndTrigger);\n    }\n    sqlite3VdbeAddOp0(v, OP_Halt);\n    VdbeComment((v, \"End: %s.%s\", pTrigger->zName, onErrorText(orconf)));\n\n    transferParseError(pParse, pSubParse);\n    if( db->mallocFailed==0 && pParse->nErr==0 ){\n      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);\n    }\n    pProgram->nMem = pSubParse->nMem;\n    pProgram->nCsr = pSubParse->nTab;\n    pProgram->token = (void *)pTrigger;\n    pPrg->aColmask[0] = pSubParse->oldmask;\n    pPrg->aColmask[1] = pSubParse->newmask;\n    sqlite3VdbeDelete(v);\n  }\n\n  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );\n  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );\n  sqlite3ParserReset(pSubParse);\n  sqlite3StackFree(db, pSubParse);\n\n  return pPrg;\n}\n    \n/*\n** Return a pointer to a TriggerPrg object containing the sub-program for\n** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such\n** TriggerPrg object exists, a new object is allocated and populated before\n** being returned.\n*/\nstatic TriggerPrg *getRowTrigger(\n  Parse *pParse,       /* Current parse context */\n  Trigger *pTrigger,   /* Trigger to code */\n  Table *pTab,         /* The table trigger pTrigger is attached to */\n  int orconf           /* ON CONFLICT algorithm. */\n){\n  Parse *pRoot = sqlite3ParseToplevel(pParse);\n  TriggerPrg *pPrg;\n\n  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );\n\n  /* It may be that this trigger has already been coded (or is in the\n  ** process of being coded). If this is the case, then an entry with\n  ** a matching TriggerPrg.pTrigger field will be present somewhere\n  ** in the Parse.pTriggerPrg list. Search for such an entry.  */\n  for(pPrg=pRoot->pTriggerPrg; \n      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); \n      pPrg=pPrg->pNext\n  );\n\n  /* If an existing TriggerPrg could not be located, create a new one. */\n  if( !pPrg ){\n    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);\n  }\n\n  return pPrg;\n}\n\n/*\n** Generate code for the trigger program associated with trigger p on \n** table pTab. The reg, orconf and ignoreJump parameters passed to this\n** function are the same as those described in the header function for\n** sqlite3CodeRowTrigger()\n*/\nSQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(\n  Parse *pParse,       /* Parse context */\n  Trigger *p,          /* Trigger to code */\n  Table *pTab,         /* The table to code triggers from */\n  int reg,             /* Reg array containing OLD.* and NEW.* values */\n  int orconf,          /* ON CONFLICT policy */\n  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */\n){\n  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */\n  TriggerPrg *pPrg;\n  pPrg = getRowTrigger(pParse, p, pTab, orconf);\n  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );\n\n  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program \n  ** is a pointer to the sub-vdbe containing the trigger program.  */\n  if( pPrg ){\n    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));\n\n    sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,\n                      (const char *)pPrg->pProgram, P4_SUBPROGRAM);\n    VdbeComment(\n        (v, \"Call: %s.%s\", (p->zName?p->zName:\"fkey\"), onErrorText(orconf)));\n\n    /* Set the P5 operand of the OP_Program instruction to non-zero if\n    ** recursive invocation of this trigger program is disallowed. Recursive\n    ** invocation is disallowed if (a) the sub-program is really a trigger,\n    ** not a foreign key action, and (b) the flag to enable recursive triggers\n    ** is clear.  */\n    sqlite3VdbeChangeP5(v, (u8)bRecursive);\n  }\n}\n\n/*\n** This is called to code the required FOR EACH ROW triggers for an operation\n** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)\n** is given by the op parameter. The tr_tm parameter determines whether the\n** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then\n** parameter pChanges is passed the list of columns being modified.\n**\n** If there are no triggers that fire at the specified time for the specified\n** operation on pTab, this function is a no-op.\n**\n** The reg argument is the address of the first in an array of registers \n** that contain the values substituted for the new.* and old.* references\n** in the trigger program. If N is the number of columns in table pTab\n** (a copy of pTab->nCol), then registers are populated as follows:\n**\n**   Register       Contains\n**   ------------------------------------------------------\n**   reg+0          OLD.rowid\n**   reg+1          OLD.* value of left-most column of pTab\n**   ...            ...\n**   reg+N          OLD.* value of right-most column of pTab\n**   reg+N+1        NEW.rowid\n**   reg+N+2        OLD.* value of left-most column of pTab\n**   ...            ...\n**   reg+N+N+1      NEW.* value of right-most column of pTab\n**\n** For ON DELETE triggers, the registers containing the NEW.* values will\n** never be accessed by the trigger program, so they are not allocated or \n** populated by the caller (there is no data to populate them with anyway). \n** Similarly, for ON INSERT triggers the values stored in the OLD.* registers\n** are never accessed, and so are not allocated by the caller. So, for an\n** ON INSERT trigger, the value passed to this function as parameter reg\n** is not a readable register, although registers (reg+N) through \n** (reg+N+N+1) are.\n**\n** Parameter orconf is the default conflict resolution algorithm for the\n** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump\n** is the instruction that control should jump to if a trigger program\n** raises an IGNORE exception.\n*/\nSQLITE_PRIVATE void sqlite3CodeRowTrigger(\n  Parse *pParse,       /* Parse context */\n  Trigger *pTrigger,   /* List of triggers on table pTab */\n  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */\n  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */\n  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */\n  Table *pTab,         /* The table to code triggers from */\n  int reg,             /* The first in an array of registers (see above) */\n  int orconf,          /* ON CONFLICT policy */\n  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */\n){\n  Trigger *p;          /* Used to iterate through pTrigger list */\n\n  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );\n  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );\n  assert( (op==TK_UPDATE)==(pChanges!=0) );\n\n  for(p=pTrigger; p; p=p->pNext){\n\n    /* Sanity checking:  The schema for the trigger and for the table are\n    ** always defined.  The trigger must be in the same schema as the table\n    ** or else it must be a TEMP trigger. */\n    assert( p->pSchema!=0 );\n    assert( p->pTabSchema!=0 );\n    assert( p->pSchema==p->pTabSchema \n         || p->pSchema==pParse->db->aDb[1].pSchema );\n\n    /* Determine whether we should code this trigger */\n    if( p->op==op \n     && p->tr_tm==tr_tm \n     && checkColumnOverlap(p->pColumns, pChanges)\n    ){\n      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);\n    }\n  }\n}\n\n/*\n** Triggers may access values stored in the old.* or new.* pseudo-table. \n** This function returns a 32-bit bitmask indicating which columns of the \n** old.* or new.* tables actually are used by triggers. This information \n** may be used by the caller, for example, to avoid having to load the entire\n** old.* record into memory when executing an UPDATE or DELETE command.\n**\n** Bit 0 of the returned mask is set if the left-most column of the\n** table may be accessed using an [old|new].<col> reference. Bit 1 is set if\n** the second leftmost column value is required, and so on. If there\n** are more than 32 columns in the table, and at least one of the columns\n** with an index greater than 32 may be accessed, 0xffffffff is returned.\n**\n** It is not possible to determine if the old.rowid or new.rowid column is \n** accessed by triggers. The caller must always assume that it is.\n**\n** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned\n** applies to the old.* table. If 1, the new.* table.\n**\n** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE\n** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only\n** included in the returned mask if the TRIGGER_BEFORE bit is set in the\n** tr_tm parameter. Similarly, values accessed by AFTER triggers are only\n** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.\n*/\nSQLITE_PRIVATE u32 sqlite3TriggerColmask(\n  Parse *pParse,       /* Parse context */\n  Trigger *pTrigger,   /* List of triggers on table pTab */\n  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */\n  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */\n  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */\n  Table *pTab,         /* The table to code triggers from */\n  int orconf           /* Default ON CONFLICT policy for trigger steps */\n){\n  const int op = pChanges ? TK_UPDATE : TK_DELETE;\n  u32 mask = 0;\n  Trigger *p;\n\n  assert( isNew==1 || isNew==0 );\n  for(p=pTrigger; p; p=p->pNext){\n    if( p->op==op && (tr_tm&p->tr_tm)\n     && checkColumnOverlap(p->pColumns,pChanges)\n    ){\n      TriggerPrg *pPrg;\n      pPrg = getRowTrigger(pParse, p, pTab, orconf);\n      if( pPrg ){\n        mask |= pPrg->aColmask[isNew];\n      }\n    }\n  }\n\n  return mask;\n}\n\n#endif /* !defined(SQLITE_OMIT_TRIGGER) */\n\n/************** End of trigger.c *********************************************/\n/************** Begin file update.c ******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains C code routines that are called by the parser\n** to handle UPDATE statements.\n*/\n/* #include \"sqliteInt.h\" */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Forward declaration */\nstatic void updateVirtualTable(\n  Parse *pParse,       /* The parsing context */\n  SrcList *pSrc,       /* The virtual table to be modified */\n  Table *pTab,         /* The virtual table */\n  ExprList *pChanges,  /* The columns to change in the UPDATE statement */\n  Expr *pRowidExpr,    /* Expression used to recompute the rowid */\n  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */\n  Expr *pWhere,        /* WHERE clause of the UPDATE statement */\n  int onError          /* ON CONFLICT strategy */\n);\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n/*\n** The most recently coded instruction was an OP_Column to retrieve the\n** i-th column of table pTab. This routine sets the P4 parameter of the \n** OP_Column to the default value, if any.\n**\n** The default value of a column is specified by a DEFAULT clause in the \n** column definition. This was either supplied by the user when the table\n** was created, or added later to the table definition by an ALTER TABLE\n** command. If the latter, then the row-records in the table btree on disk\n** may not contain a value for the column and the default value, taken\n** from the P4 parameter of the OP_Column instruction, is returned instead.\n** If the former, then all row-records are guaranteed to include a value\n** for the column and the P4 value is not required.\n**\n** Column definitions created by an ALTER TABLE command may only have \n** literal default values specified: a number, null or a string. (If a more\n** complicated default expression value was provided, it is evaluated \n** when the ALTER TABLE is executed and one of the literal values written\n** into the sqlite_master table.)\n**\n** Therefore, the P4 parameter is only required if the default value for\n** the column is a literal number, string or null. The sqlite3ValueFromExpr()\n** function is capable of transforming these types of expressions into\n** sqlite3_value objects.\n**\n** If column as REAL affinity and the table is an ordinary b-tree table\n** (not a virtual table) then the value might have been stored as an\n** integer.  In that case, add an OP_RealAffinity opcode to make sure\n** it has been converted into REAL.\n*/\nSQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){\n  assert( pTab!=0 );\n  if( !pTab->pSelect ){\n    sqlite3_value *pValue = 0;\n    u8 enc = ENC(sqlite3VdbeDb(v));\n    Column *pCol = &pTab->aCol[i];\n    VdbeComment((v, \"%s.%s\", pTab->zName, pCol->zName));\n    assert( i<pTab->nCol );\n    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, \n                         pCol->affinity, &pValue);\n    if( pValue ){\n      sqlite3VdbeAppendP4(v, pValue, P4_MEM);\n    }\n  }\n#ifndef SQLITE_OMIT_FLOATING_POINT\n  if( pTab->aCol[i].affinity==SQLITE_AFF_REAL && !IsVirtual(pTab) ){\n    sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);\n  }\n#endif\n}\n\n/*\n** Check to see if column iCol of index pIdx references any of the\n** columns defined by aXRef and chngRowid.  Return true if it does\n** and false if not.  This is an optimization.  False-positives are a\n** performance degradation, but false-negatives can result in a corrupt\n** index and incorrect answers.\n**\n** aXRef[j] will be non-negative if column j of the original table is\n** being updated.  chngRowid will be true if the rowid of the table is\n** being updated.\n*/\nstatic int indexColumnIsBeingUpdated(\n  Index *pIdx,      /* The index to check */\n  int iCol,         /* Which column of the index to check */\n  int *aXRef,       /* aXRef[j]>=0 if column j is being updated */\n  int chngRowid     /* true if the rowid is being updated */\n){\n  i16 iIdxCol = pIdx->aiColumn[iCol];\n  assert( iIdxCol!=XN_ROWID ); /* Cannot index rowid */\n  if( iIdxCol>=0 ){\n    return aXRef[iIdxCol]>=0;\n  }\n  assert( iIdxCol==XN_EXPR );\n  assert( pIdx->aColExpr!=0 );\n  assert( pIdx->aColExpr->a[iCol].pExpr!=0 );\n  return sqlite3ExprReferencesUpdatedColumn(pIdx->aColExpr->a[iCol].pExpr,\n                                            aXRef,chngRowid);\n}\n\n/*\n** Check to see if index pIdx is a partial index whose conditional\n** expression might change values due to an UPDATE.  Return true if\n** the index is subject to change and false if the index is guaranteed\n** to be unchanged.  This is an optimization.  False-positives are a\n** performance degradation, but false-negatives can result in a corrupt\n** index and incorrect answers.\n**\n** aXRef[j] will be non-negative if column j of the original table is\n** being updated.  chngRowid will be true if the rowid of the table is\n** being updated.\n*/\nstatic int indexWhereClauseMightChange(\n  Index *pIdx,      /* The index to check */\n  int *aXRef,       /* aXRef[j]>=0 if column j is being updated */\n  int chngRowid     /* true if the rowid is being updated */\n){\n  if( pIdx->pPartIdxWhere==0 ) return 0;\n  return sqlite3ExprReferencesUpdatedColumn(pIdx->pPartIdxWhere,\n                                            aXRef, chngRowid);\n}\n\n/*\n** Process an UPDATE statement.\n**\n**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;\n**          \\_______/ \\________/     \\______/       \\________________/\n*            onError   pTabList      pChanges             pWhere\n*/\nSQLITE_PRIVATE void sqlite3Update(\n  Parse *pParse,         /* The parser context */\n  SrcList *pTabList,     /* The table in which we should change things */\n  ExprList *pChanges,    /* Things to be changed */\n  Expr *pWhere,          /* The WHERE clause.  May be null */\n  int onError,           /* How to handle constraint errors */\n  ExprList *pOrderBy,    /* ORDER BY clause. May be null */\n  Expr *pLimit,          /* LIMIT clause. May be null */\n  Upsert *pUpsert        /* ON CONFLICT clause, or null */\n){\n  int i, j, k;           /* Loop counters */\n  Table *pTab;           /* The table to be updated */\n  int addrTop = 0;       /* VDBE instruction address of the start of the loop */\n  WhereInfo *pWInfo;     /* Information about the WHERE clause */\n  Vdbe *v;               /* The virtual database engine */\n  Index *pIdx;           /* For looping over indices */\n  Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */\n  int nIdx;              /* Number of indices that need updating */\n  int nAllIdx;           /* Total number of indexes */\n  int iBaseCur;          /* Base cursor number */\n  int iDataCur;          /* Cursor for the canonical data btree */\n  int iIdxCur;           /* Cursor for the first index */\n  sqlite3 *db;           /* The database structure */\n  int *aRegIdx = 0;      /* Registers for to each index and the main table */\n  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the\n                         ** an expression for the i-th column of the table.\n                         ** aXRef[i]==-1 if the i-th column is not changed. */\n  u8 *aToOpen;           /* 1 for tables and indices to be opened */\n  u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */\n  u8 chngRowid;          /* Rowid changed in a normal table */\n  u8 chngKey;            /* Either chngPk or chngRowid */\n  Expr *pRowidExpr = 0;  /* Expression defining the new record number */\n  AuthContext sContext;  /* The authorization context */\n  NameContext sNC;       /* The name-context to resolve expressions in */\n  int iDb;               /* Database containing the table being updated */\n  int eOnePass;          /* ONEPASS_XXX value from where.c */\n  int hasFK;             /* True if foreign key processing is required */\n  int labelBreak;        /* Jump here to break out of UPDATE loop */\n  int labelContinue;     /* Jump here to continue next step of UPDATE loop */\n  int flags;             /* Flags for sqlite3WhereBegin() */\n\n#ifndef SQLITE_OMIT_TRIGGER\n  int isView;            /* True when updating a view (INSTEAD OF trigger) */\n  Trigger *pTrigger;     /* List of triggers on pTab, if required */\n  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */\n#endif\n  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */\n  int iEph = 0;          /* Ephemeral table holding all primary key values */\n  int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */\n  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */\n  int addrOpen = 0;      /* Address of OP_OpenEphemeral */\n  int iPk = 0;           /* First of nPk cells holding PRIMARY KEY value */\n  i16 nPk = 0;           /* Number of components of the PRIMARY KEY */\n  int bReplace = 0;      /* True if REPLACE conflict resolution might happen */\n  int bFinishSeek = 1;   /* The OP_FinishSeek opcode is needed */\n\n  /* Register Allocations */\n  int regRowCount = 0;   /* A count of rows changed */\n  int regOldRowid = 0;   /* The old rowid */\n  int regNewRowid = 0;   /* The new rowid */\n  int regNew = 0;        /* Content of the NEW.* table in triggers */\n  int regOld = 0;        /* Content of OLD.* table in triggers */\n  int regRowSet = 0;     /* Rowset of rows to be updated */\n  int regKey = 0;        /* composite PRIMARY KEY value */\n\n  memset(&sContext, 0, sizeof(sContext));\n  db = pParse->db;\n  if( pParse->nErr || db->mallocFailed ){\n    goto update_cleanup;\n  }\n  assert( pTabList->nSrc==1 );\n\n  /* Locate the table which we want to update. \n  */\n  pTab = sqlite3SrcListLookup(pParse, pTabList);\n  if( pTab==0 ) goto update_cleanup;\n  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n\n  /* Figure out if we have any triggers and if the table being\n  ** updated is a view.\n  */\n#ifndef SQLITE_OMIT_TRIGGER\n  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);\n  isView = pTab->pSelect!=0;\n  assert( pTrigger || tmask==0 );\n#else\n# define pTrigger 0\n# define isView 0\n# define tmask 0\n#endif\n#ifdef SQLITE_OMIT_VIEW\n# undef isView\n# define isView 0\n#endif\n\n#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT\n  if( !isView ){\n    pWhere = sqlite3LimitWhere(\n        pParse, pTabList, pWhere, pOrderBy, pLimit, \"UPDATE\"\n    );\n    pOrderBy = 0;\n    pLimit = 0;\n  }\n#endif\n\n  if( sqlite3ViewGetColumnNames(pParse, pTab) ){\n    goto update_cleanup;\n  }\n  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){\n    goto update_cleanup;\n  }\n\n  /* Allocate a cursors for the main database table and for all indices.\n  ** The index cursors might not be used, but if they are used they\n  ** need to occur right after the database cursor.  So go ahead and\n  ** allocate enough space, just in case.\n  */\n  iBaseCur = iDataCur = pParse->nTab++;\n  iIdxCur = iDataCur+1;\n  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);\n  testcase( pPk!=0 && pPk!=pTab->pIndex );\n  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){\n    if( pPk==pIdx ){\n      iDataCur = pParse->nTab;\n    }\n    pParse->nTab++;\n  }\n  if( pUpsert ){\n    /* On an UPSERT, reuse the same cursors already opened by INSERT */\n    iDataCur = pUpsert->iDataCur;\n    iIdxCur = pUpsert->iIdxCur;\n    pParse->nTab = iBaseCur;\n  }\n  pTabList->a[0].iCursor = iDataCur;\n\n  /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].  \n  ** Initialize aXRef[] and aToOpen[] to their default values.\n  */\n  aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx+1) + nIdx+2 );\n  if( aXRef==0 ) goto update_cleanup;\n  aRegIdx = aXRef+pTab->nCol;\n  aToOpen = (u8*)(aRegIdx+nIdx+1);\n  memset(aToOpen, 1, nIdx+1);\n  aToOpen[nIdx+1] = 0;\n  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;\n\n  /* Initialize the name-context */\n  memset(&sNC, 0, sizeof(sNC));\n  sNC.pParse = pParse;\n  sNC.pSrcList = pTabList;\n  sNC.uNC.pUpsert = pUpsert;\n  sNC.ncFlags = NC_UUpsert;\n\n  /* Begin generating code. */\n  v = sqlite3GetVdbe(pParse);\n  if( v==0 ) goto update_cleanup;\n\n  /* Resolve the column names in all the expressions of the\n  ** of the UPDATE statement.  Also find the column index\n  ** for each column to be updated in the pChanges array.  For each\n  ** column to be updated, make sure we have authorization to change\n  ** that column.\n  */\n  chngRowid = chngPk = 0;\n  for(i=0; i<pChanges->nExpr; i++){\n    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){\n      goto update_cleanup;\n    }\n    for(j=0; j<pTab->nCol; j++){\n      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zEName)==0 ){\n        if( j==pTab->iPKey ){\n          chngRowid = 1;\n          pRowidExpr = pChanges->a[i].pExpr;\n        }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){\n          chngPk = 1;\n        }\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n        else if( pTab->aCol[j].colFlags & COLFLAG_GENERATED ){\n          testcase( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL );\n          testcase( pTab->aCol[j].colFlags & COLFLAG_STORED );\n          sqlite3ErrorMsg(pParse, \n             \"cannot UPDATE generated column \\\"%s\\\"\",\n             pTab->aCol[j].zName);\n          goto update_cleanup;\n        }\n#endif\n        aXRef[j] = i;\n        break;\n      }\n    }\n    if( j>=pTab->nCol ){\n      if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zEName) ){\n        j = -1;\n        chngRowid = 1;\n        pRowidExpr = pChanges->a[i].pExpr;\n      }else{\n        sqlite3ErrorMsg(pParse, \"no such column: %s\", pChanges->a[i].zEName);\n        pParse->checkSchema = 1;\n        goto update_cleanup;\n      }\n    }\n#ifndef SQLITE_OMIT_AUTHORIZATION\n    {\n      int rc;\n      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,\n                            j<0 ? \"ROWID\" : pTab->aCol[j].zName,\n                            db->aDb[iDb].zDbSName);\n      if( rc==SQLITE_DENY ){\n        goto update_cleanup;\n      }else if( rc==SQLITE_IGNORE ){\n        aXRef[j] = -1;\n      }\n    }\n#endif\n  }\n  assert( (chngRowid & chngPk)==0 );\n  assert( chngRowid==0 || chngRowid==1 );\n  assert( chngPk==0 || chngPk==1 );\n  chngKey = chngRowid + chngPk;\n\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n  /* Mark generated columns as changing if their generator expressions\n  ** reference any changing column.  The actual aXRef[] value for \n  ** generated expressions is not used, other than to check to see that it\n  ** is non-negative, so the value of aXRef[] for generated columns can be\n  ** set to any non-negative number.  We use 99999 so that the value is\n  ** obvious when looking at aXRef[] in a symbolic debugger. \n  */\n  if( pTab->tabFlags & TF_HasGenerated ){\n    int bProgress;\n    testcase( pTab->tabFlags & TF_HasVirtual );\n    testcase( pTab->tabFlags & TF_HasStored );\n    do{\n      bProgress = 0;\n      for(i=0; i<pTab->nCol; i++){\n        if( aXRef[i]>=0 ) continue;\n        if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ) continue;\n        if( sqlite3ExprReferencesUpdatedColumn(pTab->aCol[i].pDflt,\n                                               aXRef, chngRowid) ){\n          aXRef[i] = 99999;\n          bProgress = 1;\n        }\n      }\n    }while( bProgress );\n  }\n#endif\n\n  /* The SET expressions are not actually used inside the WHERE loop.  \n  ** So reset the colUsed mask. Unless this is a virtual table. In that\n  ** case, set all bits of the colUsed mask (to ensure that the virtual\n  ** table implementation makes all columns available).\n  */\n  pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;\n\n  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);\n\n  /* There is one entry in the aRegIdx[] array for each index on the table\n  ** being updated.  Fill in aRegIdx[] with a register number that will hold\n  ** the key for accessing each index.\n  */\n  if( onError==OE_Replace ) bReplace = 1;\n  for(nAllIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nAllIdx++){\n    int reg;\n    if( chngKey || hasFK>1 || pIdx==pPk\n     || indexWhereClauseMightChange(pIdx,aXRef,chngRowid)\n    ){\n      reg = ++pParse->nMem;\n      pParse->nMem += pIdx->nColumn;\n    }else{\n      reg = 0;\n      for(i=0; i<pIdx->nKeyCol; i++){\n        if( indexColumnIsBeingUpdated(pIdx, i, aXRef, chngRowid) ){\n          reg = ++pParse->nMem;\n          pParse->nMem += pIdx->nColumn;\n          if( onError==OE_Default && pIdx->onError==OE_Replace ){\n            bReplace = 1;\n          }\n          break;\n        }\n      }\n    }\n    if( reg==0 ) aToOpen[nAllIdx+1] = 0;\n    aRegIdx[nAllIdx] = reg;\n  }\n  aRegIdx[nAllIdx] = ++pParse->nMem;  /* Register storing the table record */\n  if( bReplace ){\n    /* If REPLACE conflict resolution might be invoked, open cursors on all \n    ** indexes in case they are needed to delete records.  */\n    memset(aToOpen, 1, nIdx+1);\n  }\n\n  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);\n  sqlite3BeginWriteOperation(pParse, pTrigger || hasFK, iDb);\n\n  /* Allocate required registers. */\n  if( !IsVirtual(pTab) ){\n    /* For now, regRowSet and aRegIdx[nAllIdx] share the same register.\n    ** If regRowSet turns out to be needed, then aRegIdx[nAllIdx] will be\n    ** reallocated.  aRegIdx[nAllIdx] is the register in which the main\n    ** table record is written.  regRowSet holds the RowSet for the\n    ** two-pass update algorithm. */\n    assert( aRegIdx[nAllIdx]==pParse->nMem );\n    regRowSet = aRegIdx[nAllIdx];\n    regOldRowid = regNewRowid = ++pParse->nMem;\n    if( chngPk || pTrigger || hasFK ){\n      regOld = pParse->nMem + 1;\n      pParse->nMem += pTab->nCol;\n    }\n    if( chngKey || pTrigger || hasFK ){\n      regNewRowid = ++pParse->nMem;\n    }\n    regNew = pParse->nMem + 1;\n    pParse->nMem += pTab->nCol;\n  }\n\n  /* Start the view context. */\n  if( isView ){\n    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);\n  }\n\n  /* If we are trying to update a view, realize that view into\n  ** an ephemeral table.\n  */\n#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)\n  if( isView ){\n    sqlite3MaterializeView(pParse, pTab, \n        pWhere, pOrderBy, pLimit, iDataCur\n    );\n    pOrderBy = 0;\n    pLimit = 0;\n  }\n#endif\n\n  /* Resolve the column names in all the expressions in the\n  ** WHERE clause.\n  */\n  if( sqlite3ResolveExprNames(&sNC, pWhere) ){\n    goto update_cleanup;\n  }\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  /* Virtual tables must be handled separately */\n  if( IsVirtual(pTab) ){\n    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,\n                       pWhere, onError);\n    goto update_cleanup;\n  }\n#endif\n\n  /* Jump to labelBreak to abandon further processing of this UPDATE */\n  labelContinue = labelBreak = sqlite3VdbeMakeLabel(pParse);\n\n  /* Not an UPSERT.  Normal processing.  Begin by\n  ** initialize the count of updated rows */\n  if( (db->flags&SQLITE_CountRows)!=0\n   && !pParse->pTriggerTab\n   && !pParse->nested\n   && pUpsert==0\n  ){\n    regRowCount = ++pParse->nMem;\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);\n  }\n\n  if( HasRowid(pTab) ){\n    sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);\n  }else{\n    assert( pPk!=0 );\n    nPk = pPk->nKeyCol;\n    iPk = pParse->nMem+1;\n    pParse->nMem += nPk;\n    regKey = ++pParse->nMem;\n    if( pUpsert==0 ){\n      iEph = pParse->nTab++;\n        sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);\n      addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);\n      sqlite3VdbeSetP4KeyInfo(pParse, pPk);\n    }\n  }\n  \n  if( pUpsert ){\n    /* If this is an UPSERT, then all cursors have already been opened by\n    ** the outer INSERT and the data cursor should be pointing at the row\n    ** that is to be updated.  So bypass the code that searches for the\n    ** row(s) to be updated.\n    */\n    pWInfo = 0;\n    eOnePass = ONEPASS_SINGLE;\n    sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL);\n    bFinishSeek = 0;\n  }else{\n    /* Begin the database scan. \n    **\n    ** Do not consider a single-pass strategy for a multi-row update if\n    ** there are any triggers or foreign keys to process, or rows may\n    ** be deleted as a result of REPLACE conflict handling. Any of these\n    ** things might disturb a cursor being used to scan through the table\n    ** or index, causing a single-pass approach to malfunction.  */\n    flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;\n    if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){\n      flags |= WHERE_ONEPASS_MULTIROW;\n    }\n    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);\n    if( pWInfo==0 ) goto update_cleanup;\n  \n    /* A one-pass strategy that might update more than one row may not\n    ** be used if any column of the index used for the scan is being\n    ** updated. Otherwise, if there is an index on \"b\", statements like\n    ** the following could create an infinite loop:\n    **\n    **   UPDATE t1 SET b=b+1 WHERE b>?\n    **\n    ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI\n    ** strategy that uses an index for which one or more columns are being\n    ** updated.  */\n    eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);\n    bFinishSeek = sqlite3WhereUsesDeferredSeek(pWInfo);\n    if( eOnePass!=ONEPASS_SINGLE ){\n      sqlite3MultiWrite(pParse);\n      if( eOnePass==ONEPASS_MULTI ){\n        int iCur = aiCurOnePass[1];\n        if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){\n          eOnePass = ONEPASS_OFF;\n        }\n        assert( iCur!=iDataCur || !HasRowid(pTab) );\n      }\n    }\n  }\n\n  if( HasRowid(pTab) ){\n    /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF\n    ** mode, write the rowid into the FIFO. In either of the one-pass modes,\n    ** leave it in register regOldRowid.  */\n    sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);\n    if( eOnePass==ONEPASS_OFF ){\n      /* We need to use regRowSet, so reallocate aRegIdx[nAllIdx] */\n      aRegIdx[nAllIdx] = ++pParse->nMem;\n      sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);\n    }\n  }else{\n    /* Read the PK of the current row into an array of registers. In\n    ** ONEPASS_OFF mode, serialize the array into a record and store it in\n    ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change\n    ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table \n    ** is not required) and leave the PK fields in the array of registers.  */\n    for(i=0; i<nPk; i++){\n      assert( pPk->aiColumn[i]>=0 );\n      sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,\n                                      pPk->aiColumn[i], iPk+i);\n    }\n    if( eOnePass ){\n      if( addrOpen ) sqlite3VdbeChangeToNoop(v, addrOpen);\n      nKey = nPk;\n      regKey = iPk;\n    }else{\n      sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,\n                        sqlite3IndexAffinityStr(db, pPk), nPk);\n      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);\n    }\n  }\n\n  if( pUpsert==0 ){\n    if( eOnePass!=ONEPASS_MULTI ){\n      sqlite3WhereEnd(pWInfo);\n    }\n  \n    if( !isView ){\n      int addrOnce = 0;\n  \n      /* Open every index that needs updating. */\n      if( eOnePass!=ONEPASS_OFF ){\n        if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;\n        if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;\n      }\n  \n      if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){\n        addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);\n      }\n      sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur,\n                                 aToOpen, 0, 0);\n      if( addrOnce ){\n        sqlite3VdbeJumpHereOrPopInst(v, addrOnce);\n      }\n    }\n  \n    /* Top of the update loop */\n    if( eOnePass!=ONEPASS_OFF ){\n      if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){\n        assert( pPk );\n        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey,nKey);\n        VdbeCoverage(v);\n      }\n      if( eOnePass!=ONEPASS_SINGLE ){\n        labelContinue = sqlite3VdbeMakeLabel(pParse);\n      }\n      sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);\n      VdbeCoverageIf(v, pPk==0);\n      VdbeCoverageIf(v, pPk!=0);\n    }else if( pPk ){\n      labelContinue = sqlite3VdbeMakeLabel(pParse);\n      sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);\n      addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);\n      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);\n      VdbeCoverage(v);\n    }else{\n      labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet,labelBreak,\n                               regOldRowid);\n      VdbeCoverage(v);\n      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);\n      VdbeCoverage(v);\n    }\n  }\n\n  /* If the rowid value will change, set register regNewRowid to\n  ** contain the new value. If the rowid is not being modified,\n  ** then regNewRowid is the same register as regOldRowid, which is\n  ** already populated.  */\n  assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );\n  if( chngRowid ){\n    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);\n    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);\n  }\n\n  /* Compute the old pre-UPDATE content of the row being changed, if that\n  ** information is needed */\n  if( chngPk || hasFK || pTrigger ){\n    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);\n    oldmask |= sqlite3TriggerColmask(pParse, \n        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError\n    );\n    for(i=0; i<pTab->nCol; i++){\n      u32 colFlags = pTab->aCol[i].colFlags;\n      k = sqlite3TableColumnToStorage(pTab, i) + regOld;\n      if( oldmask==0xffffffff\n       || (i<32 && (oldmask & MASKBIT32(i))!=0)\n       || (colFlags & COLFLAG_PRIMKEY)!=0\n      ){\n        testcase(  oldmask!=0xffffffff && i==31 );\n        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);\n      }else{\n        sqlite3VdbeAddOp2(v, OP_Null, 0, k);\n      }\n    }\n    if( chngRowid==0 && pPk==0 ){\n      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);\n    }\n  }\n\n  /* Populate the array of registers beginning at regNew with the new\n  ** row data. This array is used to check constants, create the new\n  ** table and index records, and as the values for any new.* references\n  ** made by triggers.\n  **\n  ** If there are one or more BEFORE triggers, then do not populate the\n  ** registers associated with columns that are (a) not modified by\n  ** this UPDATE statement and (b) not accessed by new.* references. The\n  ** values for registers not modified by the UPDATE must be reloaded from \n  ** the database after the BEFORE triggers are fired anyway (as the trigger \n  ** may have modified them). So not loading those that are not going to\n  ** be used eliminates some redundant opcodes.\n  */\n  newmask = sqlite3TriggerColmask(\n      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError\n  );\n  for(i=0, k=regNew; i<pTab->nCol; i++, k++){\n    if( i==pTab->iPKey ){\n      sqlite3VdbeAddOp2(v, OP_Null, 0, k);\n    }else if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)!=0 ){\n      if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;\n    }else{\n      j = aXRef[i];\n      if( j>=0 ){\n        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, k);\n      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){\n        /* This branch loads the value of a column that will not be changed \n        ** into a register. This is done if there are no BEFORE triggers, or\n        ** if there are one or more BEFORE triggers that use this value via\n        ** a new.* reference in a trigger program.\n        */\n        testcase( i==31 );\n        testcase( i==32 );\n        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);\n        bFinishSeek = 0;\n      }else{\n        sqlite3VdbeAddOp2(v, OP_Null, 0, k);\n      }\n    }\n  }\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n  if( pTab->tabFlags & TF_HasGenerated ){\n    testcase( pTab->tabFlags & TF_HasVirtual );\n    testcase( pTab->tabFlags & TF_HasStored );\n    sqlite3ComputeGeneratedColumns(pParse, regNew, pTab);\n  }\n#endif\n\n  /* Fire any BEFORE UPDATE triggers. This happens before constraints are\n  ** verified. One could argue that this is wrong.\n  */\n  if( tmask&TRIGGER_BEFORE ){\n    sqlite3TableAffinity(v, pTab, regNew);\n    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, \n        TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);\n\n    /* The row-trigger may have deleted the row being updated. In this\n    ** case, jump to the next row. No updates or AFTER triggers are \n    ** required. This behavior - what happens when the row being updated\n    ** is deleted or renamed by a BEFORE trigger - is left undefined in the\n    ** documentation.\n    */\n    if( pPk ){\n      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);\n      VdbeCoverage(v);\n    }else{\n      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);\n      VdbeCoverage(v);\n    }\n\n    /* After-BEFORE-trigger-reload-loop:\n    ** If it did not delete it, the BEFORE trigger may still have modified \n    ** some of the columns of the row being updated. Load the values for \n    ** all columns not modified by the update statement into their registers\n    ** in case this has happened. Only unmodified columns are reloaded.\n    ** The values computed for modified columns use the values before the\n    ** BEFORE trigger runs.  See test case trigger1-18.0 (added 2018-04-26)\n    ** for an example.\n    */\n    for(i=0, k=regNew; i<pTab->nCol; i++, k++){\n      if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){\n        if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;\n      }else if( aXRef[i]<0 && i!=pTab->iPKey ){\n        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);\n      }\n    }\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n    if( pTab->tabFlags & TF_HasGenerated ){\n      testcase( pTab->tabFlags & TF_HasVirtual );\n      testcase( pTab->tabFlags & TF_HasStored );\n      sqlite3ComputeGeneratedColumns(pParse, regNew, pTab);\n    }\n#endif \n  }\n\n  if( !isView ){\n    /* Do constraint checks. */\n    assert( regOldRowid>0 );\n    sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,\n        regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,\n        aXRef, 0);\n\n    /* If REPLACE conflict handling may have been used, or if the PK of the\n    ** row is changing, then the GenerateConstraintChecks() above may have\n    ** moved cursor iDataCur. Reseek it. */\n    if( bReplace || chngKey ){\n      if( pPk ){\n        sqlite3VdbeAddOp4Int(v, OP_NotFound,iDataCur,labelContinue,regKey,nKey);\n      }else{\n        sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue,regOldRowid);\n      }\n      VdbeCoverageNeverTaken(v);\n    }\n\n    /* Do FK constraint checks. */\n    if( hasFK ){\n      sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);\n    }\n\n    /* Delete the index entries associated with the current record.  */\n    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);\n\n    /* We must run the OP_FinishSeek opcode to resolve a prior\n    ** OP_DeferredSeek if there is any possibility that there have been\n    ** no OP_Column opcodes since the OP_DeferredSeek was issued.  But\n    ** we want to avoid the OP_FinishSeek if possible, as running it\n    ** costs CPU cycles. */\n    if( bFinishSeek ){\n      sqlite3VdbeAddOp1(v, OP_FinishSeek, iDataCur);\n    }\n\n    /* If changing the rowid value, or if there are foreign key constraints\n    ** to process, delete the old record. Otherwise, add a noop OP_Delete\n    ** to invoke the pre-update hook.\n    **\n    ** That (regNew==regnewRowid+1) is true is also important for the \n    ** pre-update hook. If the caller invokes preupdate_new(), the returned\n    ** value is copied from memory cell (regNewRowid+1+iCol), where iCol\n    ** is the column index supplied by the user.\n    */\n    assert( regNew==regNewRowid+1 );\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n    sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,\n        OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),\n        regNewRowid\n    );\n    if( eOnePass==ONEPASS_MULTI ){\n      assert( hasFK==0 && chngKey==0 );\n      sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);\n    }\n    if( !pParse->nested ){\n      sqlite3VdbeAppendP4(v, pTab, P4_TABLE);\n    }\n#else\n    if( hasFK>1 || chngKey ){\n      sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);\n    }\n#endif\n\n    if( hasFK ){\n      sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);\n    }\n  \n    /* Insert the new index entries and the new record. */\n    sqlite3CompleteInsertion(\n        pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx, \n        OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0), \n        0, 0\n    );\n\n    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to\n    ** handle rows (possibly in other tables) that refer via a foreign key\n    ** to the row just updated. */ \n    if( hasFK ){\n      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);\n    }\n  }\n\n  /* Increment the row counter \n  */\n  if( regRowCount ){\n    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);\n  }\n\n  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, \n      TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);\n\n  /* Repeat the above with the next record to be updated, until\n  ** all record selected by the WHERE clause have been updated.\n  */\n  if( eOnePass==ONEPASS_SINGLE ){\n    /* Nothing to do at end-of-loop for a single-pass */\n  }else if( eOnePass==ONEPASS_MULTI ){\n    sqlite3VdbeResolveLabel(v, labelContinue);\n    sqlite3WhereEnd(pWInfo);\n  }else if( pPk ){\n    sqlite3VdbeResolveLabel(v, labelContinue);\n    sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);\n  }else{\n    sqlite3VdbeGoto(v, labelContinue);\n  }\n  sqlite3VdbeResolveLabel(v, labelBreak);\n\n  /* Update the sqlite_sequence table by storing the content of the\n  ** maximum rowid counter values recorded while inserting into\n  ** autoincrement tables.\n  */\n  if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){\n    sqlite3AutoincrementEnd(pParse);\n  }\n\n  /*\n  ** Return the number of rows that were changed, if we are tracking\n  ** that information.\n  */\n  if( regRowCount ){\n    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);\n    sqlite3VdbeSetNumCols(v, 1);\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"rows updated\", SQLITE_STATIC);\n  }\n\nupdate_cleanup:\n  sqlite3AuthContextPop(&sContext);\n  sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */\n  sqlite3SrcListDelete(db, pTabList);\n  sqlite3ExprListDelete(db, pChanges);\n  sqlite3ExprDelete(db, pWhere);\n#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) \n  sqlite3ExprListDelete(db, pOrderBy);\n  sqlite3ExprDelete(db, pLimit);\n#endif\n  return;\n}\n/* Make sure \"isView\" and other macros defined above are undefined. Otherwise\n** they may interfere with compilation of other functions in this file\n** (or in another file, if this file becomes part of the amalgamation).  */\n#ifdef isView\n #undef isView\n#endif\n#ifdef pTrigger\n #undef pTrigger\n#endif\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/*\n** Generate code for an UPDATE of a virtual table.\n**\n** There are two possible strategies - the default and the special \n** \"onepass\" strategy. Onepass is only used if the virtual table \n** implementation indicates that pWhere may match at most one row.\n**\n** The default strategy is to create an ephemeral table that contains\n** for each row to be changed:\n**\n**   (A)  The original rowid of that row.\n**   (B)  The revised rowid for the row.\n**   (C)  The content of every column in the row.\n**\n** Then loop through the contents of this ephemeral table executing a\n** VUpdate for each row. When finished, drop the ephemeral table.\n**\n** The \"onepass\" strategy does not use an ephemeral table. Instead, it\n** stores the same values (A, B and C above) in a register array and\n** makes a single invocation of VUpdate.\n*/\nstatic void updateVirtualTable(\n  Parse *pParse,       /* The parsing context */\n  SrcList *pSrc,       /* The virtual table to be modified */\n  Table *pTab,         /* The virtual table */\n  ExprList *pChanges,  /* The columns to change in the UPDATE statement */\n  Expr *pRowid,        /* Expression used to recompute the rowid */\n  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */\n  Expr *pWhere,        /* WHERE clause of the UPDATE statement */\n  int onError          /* ON CONFLICT strategy */\n){\n  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */\n  int ephemTab;             /* Table holding the result of the SELECT */\n  int i;                    /* Loop counter */\n  sqlite3 *db = pParse->db; /* Database connection */\n  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);\n  WhereInfo *pWInfo;\n  int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */\n  int regArg;                     /* First register in VUpdate arg array */\n  int regRec;                     /* Register in which to assemble record */\n  int regRowid;                   /* Register for ephem table rowid */\n  int iCsr = pSrc->a[0].iCursor;  /* Cursor used for virtual table scan */\n  int aDummy[2];                  /* Unused arg for sqlite3WhereOkOnePass() */\n  int eOnePass;                   /* True to use onepass strategy */\n  int addr;                       /* Address of OP_OpenEphemeral */\n\n  /* Allocate nArg registers in which to gather the arguments for VUpdate. Then\n  ** create and open the ephemeral table in which the records created from\n  ** these arguments will be temporarily stored. */\n  assert( v );\n  ephemTab = pParse->nTab++;\n  addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);\n  regArg = pParse->nMem + 1;\n  pParse->nMem += nArg;\n  regRec = ++pParse->nMem;\n  regRowid = ++pParse->nMem;\n\n  /* Start scanning the virtual table */\n  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);\n  if( pWInfo==0 ) return;\n\n  /* Populate the argument registers. */\n  for(i=0; i<pTab->nCol; i++){\n    assert( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 );\n    if( aXRef[i]>=0 ){\n      sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);\n    }else{\n      sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);\n      sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG);/* Enable sqlite3_vtab_nochange() */\n    }\n  }\n  if( HasRowid(pTab) ){\n    sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);\n    if( pRowid ){\n      sqlite3ExprCode(pParse, pRowid, regArg+1);\n    }else{\n      sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);\n    }\n  }else{\n    Index *pPk;   /* PRIMARY KEY index */\n    i16 iPk;      /* PRIMARY KEY column */\n    pPk = sqlite3PrimaryKeyIndex(pTab);\n    assert( pPk!=0 );\n    assert( pPk->nKeyCol==1 );\n    iPk = pPk->aiColumn[0];\n    sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);\n    sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);\n  }\n\n  eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);\n\n  /* There is no ONEPASS_MULTI on virtual tables */\n  assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );\n\n  if( eOnePass ){\n    /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded\n    ** above. */\n    sqlite3VdbeChangeToNoop(v, addr);\n    sqlite3VdbeAddOp1(v, OP_Close, iCsr);\n  }else{\n    /* Create a record from the argument register contents and insert it into\n    ** the ephemeral table. */\n    sqlite3MultiWrite(pParse);\n    sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);\n#ifdef SQLITE_DEBUG\n    /* Signal an assert() within OP_MakeRecord that it is allowed to\n    ** accept no-change records with serial_type 10 */\n    sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);\n#endif\n    sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);\n    sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);\n  }\n\n\n  if( eOnePass==ONEPASS_OFF ){\n    /* End the virtual table scan */\n    sqlite3WhereEnd(pWInfo);\n\n    /* Begin scannning through the ephemeral table. */\n    addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);\n\n    /* Extract arguments from the current row of the ephemeral table and \n    ** invoke the VUpdate method.  */\n    for(i=0; i<nArg; i++){\n      sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);\n    }\n  }\n  sqlite3VtabMakeWritable(pParse, pTab);\n  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);\n  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);\n  sqlite3MayAbort(pParse);\n\n  /* End of the ephemeral table scan. Or, if using the onepass strategy,\n  ** jump to here if the scan visited zero rows. */\n  if( eOnePass==ONEPASS_OFF ){\n    sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);\n    sqlite3VdbeJumpHere(v, addr);\n    sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);\n  }else{\n    sqlite3WhereEnd(pWInfo);\n  }\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n/************** End of update.c **********************************************/\n/************** Begin file upsert.c ******************************************/\n/*\n** 2018-04-12\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code to implement various aspects of UPSERT\n** processing and handling of the Upsert object.\n*/\n/* #include \"sqliteInt.h\" */\n\n#ifndef SQLITE_OMIT_UPSERT\n/*\n** Free a list of Upsert objects\n*/\nSQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3 *db, Upsert *p){\n  if( p ){\n    sqlite3ExprListDelete(db, p->pUpsertTarget);\n    sqlite3ExprDelete(db, p->pUpsertTargetWhere);\n    sqlite3ExprListDelete(db, p->pUpsertSet);\n    sqlite3ExprDelete(db, p->pUpsertWhere);\n    sqlite3DbFree(db, p);\n  }\n}\n\n/*\n** Duplicate an Upsert object.\n*/\nSQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3 *db, Upsert *p){\n  if( p==0 ) return 0;\n  return sqlite3UpsertNew(db,\n           sqlite3ExprListDup(db, p->pUpsertTarget, 0),\n           sqlite3ExprDup(db, p->pUpsertTargetWhere, 0),\n           sqlite3ExprListDup(db, p->pUpsertSet, 0),\n           sqlite3ExprDup(db, p->pUpsertWhere, 0)\n         );\n}\n\n/*\n** Create a new Upsert object.\n*/\nSQLITE_PRIVATE Upsert *sqlite3UpsertNew(\n  sqlite3 *db,           /* Determines which memory allocator to use */\n  ExprList *pTarget,     /* Target argument to ON CONFLICT, or NULL */\n  Expr *pTargetWhere,    /* Optional WHERE clause on the target */\n  ExprList *pSet,        /* UPDATE columns, or NULL for a DO NOTHING */\n  Expr *pWhere           /* WHERE clause for the ON CONFLICT UPDATE */\n){\n  Upsert *pNew;\n  pNew = sqlite3DbMallocRaw(db, sizeof(Upsert));\n  if( pNew==0 ){\n    sqlite3ExprListDelete(db, pTarget);\n    sqlite3ExprDelete(db, pTargetWhere);\n    sqlite3ExprListDelete(db, pSet);\n    sqlite3ExprDelete(db, pWhere);\n    return 0;\n  }else{\n    pNew->pUpsertTarget = pTarget;\n    pNew->pUpsertTargetWhere = pTargetWhere;\n    pNew->pUpsertSet = pSet;\n    pNew->pUpsertWhere = pWhere;\n    pNew->pUpsertIdx = 0;\n  }\n  return pNew;\n}\n\n/*\n** Analyze the ON CONFLICT clause described by pUpsert.  Resolve all\n** symbols in the conflict-target.\n**\n** Return SQLITE_OK if everything works, or an error code is something\n** is wrong.\n*/\nSQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(\n  Parse *pParse,     /* The parsing context */\n  SrcList *pTabList, /* Table into which we are inserting */\n  Upsert *pUpsert    /* The ON CONFLICT clauses */\n){\n  Table *pTab;            /* That table into which we are inserting */\n  int rc;                 /* Result code */\n  int iCursor;            /* Cursor used by pTab */\n  Index *pIdx;            /* One of the indexes of pTab */\n  ExprList *pTarget;      /* The conflict-target clause */\n  Expr *pTerm;            /* One term of the conflict-target clause */\n  NameContext sNC;        /* Context for resolving symbolic names */\n  Expr sCol[2];           /* Index column converted into an Expr */\n\n  assert( pTabList->nSrc==1 );\n  assert( pTabList->a[0].pTab!=0 );\n  assert( pUpsert!=0 );\n  assert( pUpsert->pUpsertTarget!=0 );\n\n  /* Resolve all symbolic names in the conflict-target clause, which\n  ** includes both the list of columns and the optional partial-index\n  ** WHERE clause.\n  */\n  memset(&sNC, 0, sizeof(sNC));\n  sNC.pParse = pParse;\n  sNC.pSrcList = pTabList;\n  rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);\n  if( rc ) return rc;\n  rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);\n  if( rc ) return rc;\n\n  /* Check to see if the conflict target matches the rowid. */  \n  pTab = pTabList->a[0].pTab;\n  pTarget = pUpsert->pUpsertTarget;\n  iCursor = pTabList->a[0].iCursor;\n  if( HasRowid(pTab) \n   && pTarget->nExpr==1\n   && (pTerm = pTarget->a[0].pExpr)->op==TK_COLUMN\n   && pTerm->iColumn==XN_ROWID\n  ){\n    /* The conflict-target is the rowid of the primary table */\n    assert( pUpsert->pUpsertIdx==0 );\n    return SQLITE_OK;\n  }\n\n  /* Initialize sCol[0..1] to be an expression parse tree for a\n  ** single column of an index.  The sCol[0] node will be the TK_COLLATE\n  ** operator and sCol[1] will be the TK_COLUMN operator.  Code below\n  ** will populate the specific collation and column number values\n  ** prior to comparing against the conflict-target expression.\n  */\n  memset(sCol, 0, sizeof(sCol));\n  sCol[0].op = TK_COLLATE;\n  sCol[0].pLeft = &sCol[1];\n  sCol[1].op = TK_COLUMN;\n  sCol[1].iTable = pTabList->a[0].iCursor;\n\n  /* Check for matches against other indexes */\n  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n    int ii, jj, nn;\n    if( !IsUniqueIndex(pIdx) ) continue;\n    if( pTarget->nExpr!=pIdx->nKeyCol ) continue;\n    if( pIdx->pPartIdxWhere ){\n      if( pUpsert->pUpsertTargetWhere==0 ) continue;\n      if( sqlite3ExprCompare(pParse, pUpsert->pUpsertTargetWhere,\n                             pIdx->pPartIdxWhere, iCursor)!=0 ){\n        continue;\n      }\n    }\n    nn = pIdx->nKeyCol;\n    for(ii=0; ii<nn; ii++){\n      Expr *pExpr;\n      sCol[0].u.zToken = (char*)pIdx->azColl[ii];\n      if( pIdx->aiColumn[ii]==XN_EXPR ){\n        assert( pIdx->aColExpr!=0 );\n        assert( pIdx->aColExpr->nExpr>ii );\n        pExpr = pIdx->aColExpr->a[ii].pExpr;\n        if( pExpr->op!=TK_COLLATE ){\n          sCol[0].pLeft = pExpr;\n          pExpr = &sCol[0];\n        }\n      }else{\n        sCol[0].pLeft = &sCol[1];\n        sCol[1].iColumn = pIdx->aiColumn[ii];\n        pExpr = &sCol[0];\n      }\n      for(jj=0; jj<nn; jj++){\n        if( sqlite3ExprCompare(pParse, pTarget->a[jj].pExpr, pExpr,iCursor)<2 ){\n          break;  /* Column ii of the index matches column jj of target */\n        }\n      }\n      if( jj>=nn ){\n        /* The target contains no match for column jj of the index */\n        break;\n      }\n    }\n    if( ii<nn ){\n      /* Column ii of the index did not match any term of the conflict target.\n      ** Continue the search with the next index. */\n      continue;\n    }\n    pUpsert->pUpsertIdx = pIdx;\n    return SQLITE_OK;\n  }\n  sqlite3ErrorMsg(pParse, \"ON CONFLICT clause does not match any \"\n                          \"PRIMARY KEY or UNIQUE constraint\");\n  return SQLITE_ERROR;\n}\n\n/*\n** Generate bytecode that does an UPDATE as part of an upsert.\n**\n** If pIdx is NULL, then the UNIQUE constraint that failed was the IPK.\n** In this case parameter iCur is a cursor open on the table b-tree that\n** currently points to the conflicting table row. Otherwise, if pIdx\n** is not NULL, then pIdx is the constraint that failed and iCur is a\n** cursor points to the conflicting row.\n*/\nSQLITE_PRIVATE void sqlite3UpsertDoUpdate(\n  Parse *pParse,        /* The parsing and code-generating context */\n  Upsert *pUpsert,      /* The ON CONFLICT clause for the upsert */\n  Table *pTab,          /* The table being updated */\n  Index *pIdx,          /* The UNIQUE constraint that failed */\n  int iCur              /* Cursor for pIdx (or pTab if pIdx==NULL) */\n){\n  Vdbe *v = pParse->pVdbe;\n  sqlite3 *db = pParse->db;\n  SrcList *pSrc;            /* FROM clause for the UPDATE */\n  int iDataCur;\n  int i;\n\n  assert( v!=0 );\n  assert( pUpsert!=0 );\n  VdbeNoopComment((v, \"Begin DO UPDATE of UPSERT\"));\n  iDataCur = pUpsert->iDataCur;\n  if( pIdx && iCur!=iDataCur ){\n    if( HasRowid(pTab) ){\n      int regRowid = sqlite3GetTempReg(pParse);\n      sqlite3VdbeAddOp2(v, OP_IdxRowid, iCur, regRowid);\n      sqlite3VdbeAddOp3(v, OP_SeekRowid, iDataCur, 0, regRowid);\n      VdbeCoverage(v);\n      sqlite3ReleaseTempReg(pParse, regRowid);\n    }else{\n      Index *pPk = sqlite3PrimaryKeyIndex(pTab);\n      int nPk = pPk->nKeyCol;\n      int iPk = pParse->nMem+1;\n      pParse->nMem += nPk;\n      for(i=0; i<nPk; i++){\n        int k;\n        assert( pPk->aiColumn[i]>=0 );\n        k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);\n        sqlite3VdbeAddOp3(v, OP_Column, iCur, k, iPk+i);\n        VdbeComment((v, \"%s.%s\", pIdx->zName,\n                    pTab->aCol[pPk->aiColumn[i]].zName));\n      }\n      sqlite3VdbeVerifyAbortable(v, OE_Abort);\n      i = sqlite3VdbeAddOp4Int(v, OP_Found, iDataCur, 0, iPk, nPk);\n      VdbeCoverage(v);\n      sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CORRUPT, OE_Abort, 0, \n            \"corrupt database\", P4_STATIC);\n      sqlite3MayAbort(pParse);\n      sqlite3VdbeJumpHere(v, i);\n    }\n  }\n  /* pUpsert does not own pUpsertSrc - the outer INSERT statement does.  So\n  ** we have to make a copy before passing it down into sqlite3Update() */\n  pSrc = sqlite3SrcListDup(db, pUpsert->pUpsertSrc, 0);\n  /* excluded.* columns of type REAL need to be converted to a hard real */\n  for(i=0; i<pTab->nCol; i++){\n    if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){\n      sqlite3VdbeAddOp1(v, OP_RealAffinity, pUpsert->regData+i);\n    }\n  }\n  sqlite3Update(pParse, pSrc, pUpsert->pUpsertSet,\n      pUpsert->pUpsertWhere, OE_Abort, 0, 0, pUpsert);\n  pUpsert->pUpsertSet = 0;    /* Will have been deleted by sqlite3Update() */\n  pUpsert->pUpsertWhere = 0;  /* Will have been deleted by sqlite3Update() */\n  VdbeNoopComment((v, \"End DO UPDATE of UPSERT\"));\n}\n\n#endif /* SQLITE_OMIT_UPSERT */\n\n/************** End of upsert.c **********************************************/\n/************** Begin file vacuum.c ******************************************/\n/*\n** 2003 April 6\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code used to implement the VACUUM command.\n**\n** Most of the code in this file may be omitted by defining the\n** SQLITE_OMIT_VACUUM macro.\n*/\n/* #include \"sqliteInt.h\" */\n/* #include \"vdbeInt.h\" */\n\n#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)\n\n/*\n** Execute zSql on database db.\n**\n** If zSql returns rows, then each row will have exactly one\n** column.  (This will only happen if zSql begins with \"SELECT\".)\n** Take each row of result and call execSql() again recursively.\n**\n** The execSqlF() routine does the same thing, except it accepts\n** a format string as its third argument\n*/\nstatic int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){\n  sqlite3_stmt *pStmt;\n  int rc;\n\n  /* printf(\"SQL: [%s]\\n\", zSql); fflush(stdout); */\n  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);\n  if( rc!=SQLITE_OK ) return rc;\n  while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){\n    const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);\n    assert( sqlite3_strnicmp(zSql,\"SELECT\",6)==0 );\n    /* The secondary SQL must be one of CREATE TABLE, CREATE INDEX,\n    ** or INSERT.  Historically there have been attacks that first\n    ** corrupt the sqlite_master.sql field with other kinds of statements\n    ** then run VACUUM to get those statements to execute at inappropriate\n    ** times. */\n    if( zSubSql\n     && (strncmp(zSubSql,\"CRE\",3)==0 || strncmp(zSubSql,\"INS\",3)==0)\n    ){\n      rc = execSql(db, pzErrMsg, zSubSql);\n      if( rc!=SQLITE_OK ) break;\n    }\n  }\n  assert( rc!=SQLITE_ROW );\n  if( rc==SQLITE_DONE ) rc = SQLITE_OK;\n  if( rc ){\n    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));\n  }\n  (void)sqlite3_finalize(pStmt);\n  return rc;\n}\nstatic int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){\n  char *z;\n  va_list ap;\n  int rc;\n  va_start(ap, zSql);\n  z = sqlite3VMPrintf(db, zSql, ap);\n  va_end(ap);\n  if( z==0 ) return SQLITE_NOMEM;\n  rc = execSql(db, pzErrMsg, z);\n  sqlite3DbFree(db, z);\n  return rc;\n}\n\n/*\n** The VACUUM command is used to clean up the database,\n** collapse free space, etc.  It is modelled after the VACUUM command\n** in PostgreSQL.  The VACUUM command works as follows:\n**\n**   (1)  Create a new transient database file\n**   (2)  Copy all content from the database being vacuumed into\n**        the new transient database file\n**   (3)  Copy content from the transient database back into the\n**        original database.\n**\n** The transient database requires temporary disk space approximately\n** equal to the size of the original database.  The copy operation of\n** step (3) requires additional temporary disk space approximately equal\n** to the size of the original database for the rollback journal.\n** Hence, temporary disk space that is approximately 2x the size of the\n** original database is required.  Every page of the database is written\n** approximately 3 times:  Once for step (2) and twice for step (3).\n** Two writes per page are required in step (3) because the original\n** database content must be written into the rollback journal prior to\n** overwriting the database with the vacuumed content.\n**\n** Only 1x temporary space and only 1x writes would be required if\n** the copy of step (3) were replaced by deleting the original database\n** and renaming the transient database as the original.  But that will\n** not work if other processes are attached to the original database.\n** And a power loss in between deleting the original and renaming the\n** transient would cause the database file to appear to be deleted\n** following reboot.\n*/\nSQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm, Expr *pInto){\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  int iDb = 0;\n  if( v==0 ) goto build_vacuum_end;\n  if( pParse->nErr ) goto build_vacuum_end;\n  if( pNm ){\n#ifndef SQLITE_BUG_COMPATIBLE_20160819\n    /* Default behavior:  Report an error if the argument to VACUUM is\n    ** not recognized */\n    iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);\n    if( iDb<0 ) goto build_vacuum_end;\n#else\n    /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments\n    ** to VACUUM are silently ignored.  This is a back-out of a bug fix that\n    ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).\n    ** The buggy behavior is required for binary compatibility with some\n    ** legacy applications. */\n    iDb = sqlite3FindDb(pParse->db, pNm);\n    if( iDb<0 ) iDb = 0;\n#endif\n  }\n  if( iDb!=1 ){\n    int iIntoReg = 0;\n    if( pInto && sqlite3ResolveSelfReference(pParse,0,0,pInto,0)==0 ){\n      iIntoReg = ++pParse->nMem;\n      sqlite3ExprCode(pParse, pInto, iIntoReg);\n    }\n    sqlite3VdbeAddOp2(v, OP_Vacuum, iDb, iIntoReg);\n    sqlite3VdbeUsesBtree(v, iDb);\n  }\nbuild_vacuum_end:\n  sqlite3ExprDelete(pParse->db, pInto);\n  return;\n}\n\n/*\n** This routine implements the OP_Vacuum opcode of the VDBE.\n*/\nSQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum(\n  char **pzErrMsg,        /* Write error message here */\n  sqlite3 *db,            /* Database connection */\n  int iDb,                /* Which attached DB to vacuum */\n  sqlite3_value *pOut     /* Write results here, if not NULL. VACUUM INTO */\n){\n  int rc = SQLITE_OK;     /* Return code from service routines */\n  Btree *pMain;           /* The database being vacuumed */\n  Btree *pTemp;           /* The temporary database we vacuum into */\n  u32 saved_mDbFlags;     /* Saved value of db->mDbFlags */\n  u64 saved_flags;        /* Saved value of db->flags */\n  int saved_nChange;      /* Saved value of db->nChange */\n  int saved_nTotalChange; /* Saved value of db->nTotalChange */\n  u32 saved_openFlags;    /* Saved value of db->openFlags */\n  u8 saved_mTrace;        /* Saved trace settings */\n  Db *pDb = 0;            /* Database to detach at end of vacuum */\n  int isMemDb;            /* True if vacuuming a :memory: database */\n  int nRes;               /* Bytes of reserved space at the end of each page */\n  int nDb;                /* Number of attached databases */\n  const char *zDbMain;    /* Schema name of database to vacuum */\n  const char *zOut;       /* Name of output file */\n\n  if( !db->autoCommit ){\n    sqlite3SetString(pzErrMsg, db, \"cannot VACUUM from within a transaction\");\n    return SQLITE_ERROR; /* IMP: R-12218-18073 */\n  }\n  if( db->nVdbeActive>1 ){\n    sqlite3SetString(pzErrMsg, db,\"cannot VACUUM - SQL statements in progress\");\n    return SQLITE_ERROR; /* IMP: R-15610-35227 */\n  }\n  saved_openFlags = db->openFlags;\n  if( pOut ){\n    if( sqlite3_value_type(pOut)!=SQLITE_TEXT ){\n      sqlite3SetString(pzErrMsg, db, \"non-text filename\");\n      return SQLITE_ERROR;\n    }\n    zOut = (const char*)sqlite3_value_text(pOut);\n    db->openFlags &= ~SQLITE_OPEN_READONLY;\n    db->openFlags |= SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;\n  }else{\n    zOut = \"\";\n  }\n\n  /* Save the current value of the database flags so that it can be \n  ** restored before returning. Then set the writable-schema flag, and\n  ** disable CHECK and foreign key constraints.  */\n  saved_flags = db->flags;\n  saved_mDbFlags = db->mDbFlags;\n  saved_nChange = db->nChange;\n  saved_nTotalChange = db->nTotalChange;\n  saved_mTrace = db->mTrace;\n  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;\n  db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;\n  db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder\n                   | SQLITE_Defensive | SQLITE_CountRows);\n  db->mTrace = 0;\n\n  zDbMain = db->aDb[iDb].zDbSName;\n  pMain = db->aDb[iDb].pBt;\n  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));\n\n  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma\n  ** can be set to 'off' for this file, as it is not recovered if a crash\n  ** occurs anyway. The integrity of the database is maintained by a\n  ** (possibly synchronous) transaction opened on the main database before\n  ** sqlite3BtreeCopyFile() is called.\n  **\n  ** An optimisation would be to use a non-journaled pager.\n  ** (Later:) I tried setting \"PRAGMA vacuum_db.journal_mode=OFF\" but\n  ** that actually made the VACUUM run slower.  Very little journalling\n  ** actually occurs when doing a vacuum since the vacuum_db is initially\n  ** empty.  Only the journal header is written.  Apparently it takes more\n  ** time to parse and run the PRAGMA to turn journalling off than it does\n  ** to write the journal header file.\n  */\n  nDb = db->nDb;\n  rc = execSqlF(db, pzErrMsg, \"ATTACH %Q AS vacuum_db\", zOut);\n  db->openFlags = saved_openFlags;\n  if( rc!=SQLITE_OK ) goto end_of_vacuum;\n  assert( (db->nDb-1)==nDb );\n  pDb = &db->aDb[nDb];\n  assert( strcmp(pDb->zDbSName,\"vacuum_db\")==0 );\n  pTemp = pDb->pBt;\n  if( pOut ){\n    sqlite3_file *id = sqlite3PagerFile(sqlite3BtreePager(pTemp));\n    i64 sz = 0;\n    if( id->pMethods!=0 && (sqlite3OsFileSize(id, &sz)!=SQLITE_OK || sz>0) ){\n      rc = SQLITE_ERROR;\n      sqlite3SetString(pzErrMsg, db, \"output file already exists\");\n      goto end_of_vacuum;\n    }\n    db->mDbFlags |= DBFLAG_VacuumInto;\n  }\n  nRes = sqlite3BtreeGetRequestedReserve(pMain);\n\n  sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);\n  sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));\n  sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);\n\n  /* Begin a transaction and take an exclusive lock on the main database\n  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,\n  ** to ensure that we do not try to change the page-size on a WAL database.\n  */\n  rc = execSql(db, pzErrMsg, \"BEGIN\");\n  if( rc!=SQLITE_OK ) goto end_of_vacuum;\n  rc = sqlite3BtreeBeginTrans(pMain, pOut==0 ? 2 : 0, 0);\n  if( rc!=SQLITE_OK ) goto end_of_vacuum;\n\n  /* Do not attempt to change the page size for a WAL database */\n  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))\n                                               ==PAGER_JOURNALMODE_WAL ){\n    db->nextPagesize = 0;\n  }\n\n  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)\n   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))\n   || NEVER(db->mallocFailed)\n  ){\n    rc = SQLITE_NOMEM_BKPT;\n    goto end_of_vacuum;\n  }\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :\n                                           sqlite3BtreeGetAutoVacuum(pMain));\n#endif\n\n  /* Query the schema of the main database. Create a mirror schema\n  ** in the temporary database.\n  */\n  db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */\n  rc = execSqlF(db, pzErrMsg,\n      \"SELECT sql FROM \\\"%w\\\".sqlite_master\"\n      \" WHERE type='table'AND name<>'sqlite_sequence'\"\n      \" AND coalesce(rootpage,1)>0\",\n      zDbMain\n  );\n  if( rc!=SQLITE_OK ) goto end_of_vacuum;\n  rc = execSqlF(db, pzErrMsg,\n      \"SELECT sql FROM \\\"%w\\\".sqlite_master\"\n      \" WHERE type='index'\",\n      zDbMain\n  );\n  if( rc!=SQLITE_OK ) goto end_of_vacuum;\n  db->init.iDb = 0;\n\n  /* Loop through the tables in the main database. For each, do\n  ** an \"INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;\" to copy\n  ** the contents to the temporary database.\n  */\n  rc = execSqlF(db, pzErrMsg,\n      \"SELECT'INSERT INTO vacuum_db.'||quote(name)\"\n      \"||' SELECT*FROM\\\"%w\\\".'||quote(name)\"\n      \"FROM vacuum_db.sqlite_master \"\n      \"WHERE type='table'AND coalesce(rootpage,1)>0\",\n      zDbMain\n  );\n  assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 );\n  db->mDbFlags &= ~DBFLAG_Vacuum;\n  if( rc!=SQLITE_OK ) goto end_of_vacuum;\n\n  /* Copy the triggers, views, and virtual tables from the main database\n  ** over to the temporary database.  None of these objects has any\n  ** associated storage, so all we have to do is copy their entries\n  ** from the SQLITE_MASTER table.\n  */\n  rc = execSqlF(db, pzErrMsg,\n      \"INSERT INTO vacuum_db.sqlite_master\"\n      \" SELECT*FROM \\\"%w\\\".sqlite_master\"\n      \" WHERE type IN('view','trigger')\"\n      \" OR(type='table'AND rootpage=0)\",\n      zDbMain\n  );\n  if( rc ) goto end_of_vacuum;\n\n  /* At this point, there is a write transaction open on both the \n  ** vacuum database and the main database. Assuming no error occurs,\n  ** both transactions are closed by this block - the main database\n  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit\n  ** call to sqlite3BtreeCommit().\n  */\n  {\n    u32 meta;\n    int i;\n\n    /* This array determines which meta meta values are preserved in the\n    ** vacuum.  Even entries are the meta value number and odd entries\n    ** are an increment to apply to the meta value after the vacuum.\n    ** The increment is used to increase the schema cookie so that other\n    ** connections to the same database will know to reread the schema.\n    */\n    static const unsigned char aCopy[] = {\n       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */\n       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */\n       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */\n       BTREE_USER_VERSION,       0,  /* Preserve the user version */\n       BTREE_APPLICATION_ID,     0,  /* Preserve the application id */\n    };\n\n    assert( 1==sqlite3BtreeIsInTrans(pTemp) );\n    assert( pOut!=0 || 1==sqlite3BtreeIsInTrans(pMain) );\n\n    /* Copy Btree meta values */\n    for(i=0; i<ArraySize(aCopy); i+=2){\n      /* GetMeta() and UpdateMeta() cannot fail in this context because\n      ** we already have page 1 loaded into cache and marked dirty. */\n      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);\n      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);\n      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;\n    }\n\n    if( pOut==0 ){\n      rc = sqlite3BtreeCopyFile(pMain, pTemp);\n    }\n    if( rc!=SQLITE_OK ) goto end_of_vacuum;\n    rc = sqlite3BtreeCommit(pTemp);\n    if( rc!=SQLITE_OK ) goto end_of_vacuum;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( pOut==0 ){\n      sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));\n    }\n#endif\n  }\n\n  assert( rc==SQLITE_OK );\n  if( pOut==0 ){\n    rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);\n  }\n\nend_of_vacuum:\n  /* Restore the original value of db->flags */\n  db->init.iDb = 0;\n  db->mDbFlags = saved_mDbFlags;\n  db->flags = saved_flags;\n  db->nChange = saved_nChange;\n  db->nTotalChange = saved_nTotalChange;\n  db->mTrace = saved_mTrace;\n  sqlite3BtreeSetPageSize(pMain, -1, 0, 1);\n\n  /* Currently there is an SQL level transaction open on the vacuum\n  ** database. No locks are held on any other files (since the main file\n  ** was committed at the btree level). So it safe to end the transaction\n  ** by manually setting the autoCommit flag to true and detaching the\n  ** vacuum database. The vacuum_db journal file is deleted when the pager\n  ** is closed by the DETACH.\n  */\n  db->autoCommit = 1;\n\n  if( pDb ){\n    sqlite3BtreeClose(pDb->pBt);\n    pDb->pBt = 0;\n    pDb->pSchema = 0;\n  }\n\n  /* This both clears the schemas and reduces the size of the db->aDb[]\n  ** array. */ \n  sqlite3ResetAllSchemasOfConnection(db);\n\n  return rc;\n}\n\n#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */\n\n/************** End of vacuum.c **********************************************/\n/************** Begin file vtab.c ********************************************/\n/*\n** 2006 June 10\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code used to help implement virtual tables.\n*/\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* #include \"sqliteInt.h\" */\n\n/*\n** Before a virtual table xCreate() or xConnect() method is invoked, the\n** sqlite3.pVtabCtx member variable is set to point to an instance of\n** this struct allocated on the stack. It is used by the implementation of \n** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which\n** are invoked only from within xCreate and xConnect methods.\n*/\nstruct VtabCtx {\n  VTable *pVTable;    /* The virtual table being constructed */\n  Table *pTab;        /* The Table object to which the virtual table belongs */\n  VtabCtx *pPrior;    /* Parent context (if any) */\n  int bDeclared;      /* True after sqlite3_declare_vtab() is called */\n};\n\n/*\n** Construct and install a Module object for a virtual table.  When this\n** routine is called, it is guaranteed that all appropriate locks are held\n** and the module is not already part of the connection.\n**\n** If there already exists a module with zName, replace it with the new one.\n** If pModule==0, then delete the module zName if it exists.\n*/\nSQLITE_PRIVATE Module *sqlite3VtabCreateModule(\n  sqlite3 *db,                    /* Database in which module is registered */\n  const char *zName,              /* Name assigned to this module */\n  const sqlite3_module *pModule,  /* The definition of the module */\n  void *pAux,                     /* Context pointer for xCreate/xConnect */\n  void (*xDestroy)(void *)        /* Module destructor function */\n){\n  Module *pMod;\n  Module *pDel;\n  char *zCopy;\n  if( pModule==0 ){\n    zCopy = (char*)zName;\n    pMod = 0;\n  }else{\n    int nName = sqlite3Strlen30(zName);\n    pMod = (Module *)sqlite3Malloc(sizeof(Module) + nName + 1);\n    if( pMod==0 ){\n      sqlite3OomFault(db);\n      return 0;\n    }\n    zCopy = (char *)(&pMod[1]);\n    memcpy(zCopy, zName, nName+1);\n    pMod->zName = zCopy;\n    pMod->pModule = pModule;\n    pMod->pAux = pAux;\n    pMod->xDestroy = xDestroy;\n    pMod->pEpoTab = 0;\n    pMod->nRefModule = 1;\n  }\n  pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);\n  if( pDel ){\n    if( pDel==pMod ){\n      sqlite3OomFault(db);\n      sqlite3DbFree(db, pDel);\n      pMod = 0;\n    }else{\n      sqlite3VtabEponymousTableClear(db, pDel);\n      sqlite3VtabModuleUnref(db, pDel);\n    }\n  }\n  return pMod;\n}\n\n/*\n** The actual function that does the work of creating a new module.\n** This function implements the sqlite3_create_module() and\n** sqlite3_create_module_v2() interfaces.\n*/\nstatic int createModule(\n  sqlite3 *db,                    /* Database in which module is registered */\n  const char *zName,              /* Name assigned to this module */\n  const sqlite3_module *pModule,  /* The definition of the module */\n  void *pAux,                     /* Context pointer for xCreate/xConnect */\n  void (*xDestroy)(void *)        /* Module destructor function */\n){\n  int rc = SQLITE_OK;\n\n  sqlite3_mutex_enter(db->mutex);\n  (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);\n  rc = sqlite3ApiExit(db, rc);\n  if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n\n/*\n** External API function used to create a new virtual-table module.\n*/\nSQLITE_API int sqlite3_create_module(\n  sqlite3 *db,                    /* Database in which module is registered */\n  const char *zName,              /* Name assigned to this module */\n  const sqlite3_module *pModule,  /* The definition of the module */\n  void *pAux                      /* Context pointer for xCreate/xConnect */\n){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;\n#endif\n  return createModule(db, zName, pModule, pAux, 0);\n}\n\n/*\n** External API function used to create a new virtual-table module.\n*/\nSQLITE_API int sqlite3_create_module_v2(\n  sqlite3 *db,                    /* Database in which module is registered */\n  const char *zName,              /* Name assigned to this module */\n  const sqlite3_module *pModule,  /* The definition of the module */\n  void *pAux,                     /* Context pointer for xCreate/xConnect */\n  void (*xDestroy)(void *)        /* Module destructor function */\n){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;\n#endif\n  return createModule(db, zName, pModule, pAux, xDestroy);\n}\n\n/*\n** External API to drop all virtual-table modules, except those named\n** on the azNames list.\n*/\nSQLITE_API int sqlite3_drop_modules(sqlite3 *db, const char** azNames){\n  HashElem *pThis, *pNext;\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;\n#endif\n  for(pThis=sqliteHashFirst(&db->aModule); pThis; pThis=pNext){\n    Module *pMod = (Module*)sqliteHashData(pThis);\n    pNext = sqliteHashNext(pThis);\n    if( azNames ){\n      int ii;\n      for(ii=0; azNames[ii]!=0 && strcmp(azNames[ii],pMod->zName)!=0; ii++){}\n      if( azNames[ii]!=0 ) continue;\n    }\n    createModule(db, pMod->zName, 0, 0, 0);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Decrement the reference count on a Module object.  Destroy the\n** module when the reference count reaches zero.\n*/\nSQLITE_PRIVATE void sqlite3VtabModuleUnref(sqlite3 *db, Module *pMod){\n  assert( pMod->nRefModule>0 );\n  pMod->nRefModule--;\n  if( pMod->nRefModule==0 ){\n    if( pMod->xDestroy ){\n      pMod->xDestroy(pMod->pAux);\n    }\n    assert( pMod->pEpoTab==0 );\n    sqlite3DbFree(db, pMod);\n  }\n}\n\n/*\n** Lock the virtual table so that it cannot be disconnected.\n** Locks nest.  Every lock should have a corresponding unlock.\n** If an unlock is omitted, resources leaks will occur.  \n**\n** If a disconnect is attempted while a virtual table is locked,\n** the disconnect is deferred until all locks have been removed.\n*/\nSQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){\n  pVTab->nRef++;\n}\n\n\n/*\n** pTab is a pointer to a Table structure representing a virtual-table.\n** Return a pointer to the VTable object used by connection db to access \n** this virtual-table, if one has been created, or NULL otherwise.\n*/\nSQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){\n  VTable *pVtab;\n  assert( IsVirtual(pTab) );\n  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);\n  return pVtab;\n}\n\n/*\n** Decrement the ref-count on a virtual table object. When the ref-count\n** reaches zero, call the xDisconnect() method to delete the object.\n*/\nSQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){\n  sqlite3 *db = pVTab->db;\n\n  assert( db );\n  assert( pVTab->nRef>0 );\n  assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );\n\n  pVTab->nRef--;\n  if( pVTab->nRef==0 ){\n    sqlite3_vtab *p = pVTab->pVtab;\n    sqlite3VtabModuleUnref(pVTab->db, pVTab->pMod);\n    if( p ){\n      p->pModule->xDisconnect(p);\n    }\n    sqlite3DbFree(db, pVTab);\n  }\n}\n\n/*\n** Table p is a virtual table. This function moves all elements in the\n** p->pVTable list to the sqlite3.pDisconnect lists of their associated\n** database connections to be disconnected at the next opportunity. \n** Except, if argument db is not NULL, then the entry associated with\n** connection db is left in the p->pVTable list.\n*/\nstatic VTable *vtabDisconnectAll(sqlite3 *db, Table *p){\n  VTable *pRet = 0;\n  VTable *pVTable = p->pVTable;\n  p->pVTable = 0;\n\n  /* Assert that the mutex (if any) associated with the BtShared database \n  ** that contains table p is held by the caller. See header comments \n  ** above function sqlite3VtabUnlockList() for an explanation of why\n  ** this makes it safe to access the sqlite3.pDisconnect list of any\n  ** database connection that may have an entry in the p->pVTable list.\n  */\n  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );\n\n  while( pVTable ){\n    sqlite3 *db2 = pVTable->db;\n    VTable *pNext = pVTable->pNext;\n    assert( db2 );\n    if( db2==db ){\n      pRet = pVTable;\n      p->pVTable = pRet;\n      pRet->pNext = 0;\n    }else{\n      pVTable->pNext = db2->pDisconnect;\n      db2->pDisconnect = pVTable;\n    }\n    pVTable = pNext;\n  }\n\n  assert( !db || pRet );\n  return pRet;\n}\n\n/*\n** Table *p is a virtual table. This function removes the VTable object\n** for table *p associated with database connection db from the linked\n** list in p->pVTab. It also decrements the VTable ref count. This is\n** used when closing database connection db to free all of its VTable\n** objects without disturbing the rest of the Schema object (which may\n** be being used by other shared-cache connections).\n*/\nSQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){\n  VTable **ppVTab;\n\n  assert( IsVirtual(p) );\n  assert( sqlite3BtreeHoldsAllMutexes(db) );\n  assert( sqlite3_mutex_held(db->mutex) );\n\n  for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){\n    if( (*ppVTab)->db==db  ){\n      VTable *pVTab = *ppVTab;\n      *ppVTab = pVTab->pNext;\n      sqlite3VtabUnlock(pVTab);\n      break;\n    }\n  }\n}\n\n\n/*\n** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.\n**\n** This function may only be called when the mutexes associated with all\n** shared b-tree databases opened using connection db are held by the \n** caller. This is done to protect the sqlite3.pDisconnect list. The\n** sqlite3.pDisconnect list is accessed only as follows:\n**\n**   1) By this function. In this case, all BtShared mutexes and the mutex\n**      associated with the database handle itself must be held.\n**\n**   2) By function vtabDisconnectAll(), when it adds a VTable entry to\n**      the sqlite3.pDisconnect list. In this case either the BtShared mutex\n**      associated with the database the virtual table is stored in is held\n**      or, if the virtual table is stored in a non-sharable database, then\n**      the database handle mutex is held.\n**\n** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously \n** by multiple threads. It is thread-safe.\n*/\nSQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){\n  VTable *p = db->pDisconnect;\n\n  assert( sqlite3BtreeHoldsAllMutexes(db) );\n  assert( sqlite3_mutex_held(db->mutex) );\n\n  if( p ){\n    db->pDisconnect = 0;\n    sqlite3ExpirePreparedStatements(db, 0);\n    do {\n      VTable *pNext = p->pNext;\n      sqlite3VtabUnlock(p);\n      p = pNext;\n    }while( p );\n  }\n}\n\n/*\n** Clear any and all virtual-table information from the Table record.\n** This routine is called, for example, just before deleting the Table\n** record.\n**\n** Since it is a virtual-table, the Table structure contains a pointer\n** to the head of a linked list of VTable structures. Each VTable \n** structure is associated with a single sqlite3* user of the schema.\n** The reference count of the VTable structure associated with database \n** connection db is decremented immediately (which may lead to the \n** structure being xDisconnected and free). Any other VTable structures\n** in the list are moved to the sqlite3.pDisconnect list of the associated \n** database connection.\n*/\nSQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){\n  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);\n  if( p->azModuleArg ){\n    int i;\n    for(i=0; i<p->nModuleArg; i++){\n      if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);\n    }\n    sqlite3DbFree(db, p->azModuleArg);\n  }\n}\n\n/*\n** Add a new module argument to pTable->azModuleArg[].\n** The string is not copied - the pointer is stored.  The\n** string will be freed automatically when the table is\n** deleted.\n*/\nstatic void addModuleArgument(Parse *pParse, Table *pTable, char *zArg){\n  sqlite3_int64 nBytes = sizeof(char *)*(2+pTable->nModuleArg);\n  char **azModuleArg;\n  sqlite3 *db = pParse->db;\n  if( pTable->nModuleArg+3>=db->aLimit[SQLITE_LIMIT_COLUMN] ){\n    sqlite3ErrorMsg(pParse, \"too many columns on %s\", pTable->zName);\n  }\n  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);\n  if( azModuleArg==0 ){\n    sqlite3DbFree(db, zArg);\n  }else{\n    int i = pTable->nModuleArg++;\n    azModuleArg[i] = zArg;\n    azModuleArg[i+1] = 0;\n    pTable->azModuleArg = azModuleArg;\n  }\n}\n\n/*\n** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE\n** statement.  The module name has been parsed, but the optional list\n** of parameters that follow the module name are still pending.\n*/\nSQLITE_PRIVATE void sqlite3VtabBeginParse(\n  Parse *pParse,        /* Parsing context */\n  Token *pName1,        /* Name of new table, or database name */\n  Token *pName2,        /* Name of new table or NULL */\n  Token *pModuleName,   /* Name of the module for the virtual table */\n  int ifNotExists       /* No error if the table already exists */\n){\n  Table *pTable;        /* The new virtual table */\n  sqlite3 *db;          /* Database connection */\n\n  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);\n  pTable = pParse->pNewTable;\n  if( pTable==0 ) return;\n  assert( 0==pTable->pIndex );\n\n  db = pParse->db;\n\n  assert( pTable->nModuleArg==0 );\n  addModuleArgument(pParse, pTable, sqlite3NameFromToken(db, pModuleName));\n  addModuleArgument(pParse, pTable, 0);\n  addModuleArgument(pParse, pTable, sqlite3DbStrDup(db, pTable->zName));\n  assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)\n       || (pParse->sNameToken.z==pName1->z && pName2->z==0)\n  );\n  pParse->sNameToken.n = (int)(\n      &pModuleName->z[pModuleName->n] - pParse->sNameToken.z\n  );\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  /* Creating a virtual table invokes the authorization callback twice.\n  ** The first invocation, to obtain permission to INSERT a row into the\n  ** sqlite_master table, has already been made by sqlite3StartTable().\n  ** The second call, to obtain permission to create the table, is made now.\n  */\n  if( pTable->azModuleArg ){\n    int iDb = sqlite3SchemaToIndex(db, pTable->pSchema);\n    assert( iDb>=0 ); /* The database the table is being created in */\n    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, \n            pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);\n  }\n#endif\n}\n\n/*\n** This routine takes the module argument that has been accumulating\n** in pParse->zArg[] and appends it to the list of arguments on the\n** virtual table currently under construction in pParse->pTable.\n*/\nstatic void addArgumentToVtab(Parse *pParse){\n  if( pParse->sArg.z && pParse->pNewTable ){\n    const char *z = (const char*)pParse->sArg.z;\n    int n = pParse->sArg.n;\n    sqlite3 *db = pParse->db;\n    addModuleArgument(pParse, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));\n  }\n}\n\n/*\n** The parser calls this routine after the CREATE VIRTUAL TABLE statement\n** has been completely parsed.\n*/\nSQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){\n  Table *pTab = pParse->pNewTable;  /* The table being constructed */\n  sqlite3 *db = pParse->db;         /* The database connection */\n\n  if( pTab==0 ) return;\n  addArgumentToVtab(pParse);\n  pParse->sArg.z = 0;\n  if( pTab->nModuleArg<1 ) return;\n  \n  /* If the CREATE VIRTUAL TABLE statement is being entered for the\n  ** first time (in other words if the virtual table is actually being\n  ** created now instead of just being read out of sqlite_master) then\n  ** do additional initialization work and store the statement text\n  ** in the sqlite_master table.\n  */\n  if( !db->init.busy ){\n    char *zStmt;\n    char *zWhere;\n    int iDb;\n    int iReg;\n    Vdbe *v;\n\n    sqlite3MayAbort(pParse);\n\n    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */\n    if( pEnd ){\n      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;\n    }\n    zStmt = sqlite3MPrintf(db, \"CREATE VIRTUAL TABLE %T\", &pParse->sNameToken);\n\n    /* A slot for the record has already been allocated in the \n    ** SQLITE_MASTER table.  We just need to update that slot with all\n    ** the information we've collected.  \n    **\n    ** The VM register number pParse->regRowid holds the rowid of an\n    ** entry in the sqlite_master table tht was created for this vtab\n    ** by sqlite3StartTable().\n    */\n    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n    sqlite3NestedParse(pParse,\n      \"UPDATE %Q.%s \"\n         \"SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q \"\n       \"WHERE rowid=#%d\",\n      db->aDb[iDb].zDbSName, MASTER_NAME,\n      pTab->zName,\n      pTab->zName,\n      zStmt,\n      pParse->regRowid\n    );\n    v = sqlite3GetVdbe(pParse);\n    sqlite3ChangeCookie(pParse, iDb);\n\n    sqlite3VdbeAddOp0(v, OP_Expire);\n    zWhere = sqlite3MPrintf(db, \"name=%Q AND sql=%Q\", pTab->zName, zStmt);\n    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);\n    sqlite3DbFree(db, zStmt);\n\n    iReg = ++pParse->nMem;\n    sqlite3VdbeLoadString(v, iReg, pTab->zName);\n    sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);\n  }\n\n  /* If we are rereading the sqlite_master table create the in-memory\n  ** record of the table. The xConnect() method is not called until\n  ** the first time the virtual table is used in an SQL statement. This\n  ** allows a schema that contains virtual tables to be loaded before\n  ** the required virtual table implementations are registered.  */\n  else {\n    Table *pOld;\n    Schema *pSchema = pTab->pSchema;\n    const char *zName = pTab->zName;\n    assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );\n    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);\n    if( pOld ){\n      sqlite3OomFault(db);\n      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */\n      return;\n    }\n    pParse->pNewTable = 0;\n  }\n}\n\n/*\n** The parser calls this routine when it sees the first token\n** of an argument to the module name in a CREATE VIRTUAL TABLE statement.\n*/\nSQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){\n  addArgumentToVtab(pParse);\n  pParse->sArg.z = 0;\n  pParse->sArg.n = 0;\n}\n\n/*\n** The parser calls this routine for each token after the first token\n** in an argument to the module name in a CREATE VIRTUAL TABLE statement.\n*/\nSQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){\n  Token *pArg = &pParse->sArg;\n  if( pArg->z==0 ){\n    pArg->z = p->z;\n    pArg->n = p->n;\n  }else{\n    assert(pArg->z <= p->z);\n    pArg->n = (int)(&p->z[p->n] - pArg->z);\n  }\n}\n\n/*\n** Invoke a virtual table constructor (either xCreate or xConnect). The\n** pointer to the function to invoke is passed as the fourth parameter\n** to this procedure.\n*/\nstatic int vtabCallConstructor(\n  sqlite3 *db, \n  Table *pTab,\n  Module *pMod,\n  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),\n  char **pzErr\n){\n  VtabCtx sCtx;\n  VTable *pVTable;\n  int rc;\n  const char *const*azArg = (const char *const*)pTab->azModuleArg;\n  int nArg = pTab->nModuleArg;\n  char *zErr = 0;\n  char *zModuleName;\n  int iDb;\n  VtabCtx *pCtx;\n\n  /* Check that the virtual-table is not already being initialized */\n  for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){\n    if( pCtx->pTab==pTab ){\n      *pzErr = sqlite3MPrintf(db, \n          \"vtable constructor called recursively: %s\", pTab->zName\n      );\n      return SQLITE_LOCKED;\n    }\n  }\n\n  zModuleName = sqlite3DbStrDup(db, pTab->zName);\n  if( !zModuleName ){\n    return SQLITE_NOMEM_BKPT;\n  }\n\n  pVTable = sqlite3MallocZero(sizeof(VTable));\n  if( !pVTable ){\n    sqlite3OomFault(db);\n    sqlite3DbFree(db, zModuleName);\n    return SQLITE_NOMEM_BKPT;\n  }\n  pVTable->db = db;\n  pVTable->pMod = pMod;\n  pVTable->eVtabRisk = SQLITE_VTABRISK_Normal;\n\n  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n  pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;\n\n  /* Invoke the virtual table constructor */\n  assert( &db->pVtabCtx );\n  assert( xConstruct );\n  sCtx.pTab = pTab;\n  sCtx.pVTable = pVTable;\n  sCtx.pPrior = db->pVtabCtx;\n  sCtx.bDeclared = 0;\n  db->pVtabCtx = &sCtx;\n  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);\n  db->pVtabCtx = sCtx.pPrior;\n  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);\n  assert( sCtx.pTab==pTab );\n\n  if( SQLITE_OK!=rc ){\n    if( zErr==0 ){\n      *pzErr = sqlite3MPrintf(db, \"vtable constructor failed: %s\", zModuleName);\n    }else {\n      *pzErr = sqlite3MPrintf(db, \"%s\", zErr);\n      sqlite3_free(zErr);\n    }\n    sqlite3DbFree(db, pVTable);\n  }else if( ALWAYS(pVTable->pVtab) ){\n    /* Justification of ALWAYS():  A correct vtab constructor must allocate\n    ** the sqlite3_vtab object if successful.  */\n    memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));\n    pVTable->pVtab->pModule = pMod->pModule;\n    pMod->nRefModule++;\n    pVTable->nRef = 1;\n    if( sCtx.bDeclared==0 ){\n      const char *zFormat = \"vtable constructor did not declare schema: %s\";\n      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);\n      sqlite3VtabUnlock(pVTable);\n      rc = SQLITE_ERROR;\n    }else{\n      int iCol;\n      u16 oooHidden = 0;\n      /* If everything went according to plan, link the new VTable structure\n      ** into the linked list headed by pTab->pVTable. Then loop through the \n      ** columns of the table to see if any of them contain the token \"hidden\".\n      ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from\n      ** the type string.  */\n      pVTable->pNext = pTab->pVTable;\n      pTab->pVTable = pVTable;\n\n      for(iCol=0; iCol<pTab->nCol; iCol++){\n        char *zType = sqlite3ColumnType(&pTab->aCol[iCol], \"\");\n        int nType;\n        int i = 0;\n        nType = sqlite3Strlen30(zType);\n        for(i=0; i<nType; i++){\n          if( 0==sqlite3StrNICmp(\"hidden\", &zType[i], 6)\n           && (i==0 || zType[i-1]==' ')\n           && (zType[i+6]=='\\0' || zType[i+6]==' ')\n          ){\n            break;\n          }\n        }\n        if( i<nType ){\n          int j;\n          int nDel = 6 + (zType[i+6] ? 1 : 0);\n          for(j=i; (j+nDel)<=nType; j++){\n            zType[j] = zType[j+nDel];\n          }\n          if( zType[i]=='\\0' && i>0 ){\n            assert(zType[i-1]==' ');\n            zType[i-1] = '\\0';\n          }\n          pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;\n          oooHidden = TF_OOOHidden;\n        }else{\n          pTab->tabFlags |= oooHidden;\n        }\n      }\n    }\n  }\n\n  sqlite3DbFree(db, zModuleName);\n  return rc;\n}\n\n/*\n** This function is invoked by the parser to call the xConnect() method\n** of the virtual table pTab. If an error occurs, an error code is returned \n** and an error left in pParse.\n**\n** This call is a no-op if table pTab is not a virtual table.\n*/\nSQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){\n  sqlite3 *db = pParse->db;\n  const char *zMod;\n  Module *pMod;\n  int rc;\n\n  assert( pTab );\n  if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){\n    return SQLITE_OK;\n  }\n\n  /* Locate the required virtual table module */\n  zMod = pTab->azModuleArg[0];\n  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);\n\n  if( !pMod ){\n    const char *zModule = pTab->azModuleArg[0];\n    sqlite3ErrorMsg(pParse, \"no such module: %s\", zModule);\n    rc = SQLITE_ERROR;\n  }else{\n    char *zErr = 0;\n    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);\n    if( rc!=SQLITE_OK ){\n      sqlite3ErrorMsg(pParse, \"%s\", zErr);\n      pParse->rc = rc;\n    }\n    sqlite3DbFree(db, zErr);\n  }\n\n  return rc;\n}\n/*\n** Grow the db->aVTrans[] array so that there is room for at least one\n** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.\n*/\nstatic int growVTrans(sqlite3 *db){\n  const int ARRAY_INCR = 5;\n\n  /* Grow the sqlite3.aVTrans array if required */\n  if( (db->nVTrans%ARRAY_INCR)==0 ){\n    VTable **aVTrans;\n    sqlite3_int64 nBytes = sizeof(sqlite3_vtab*)*\n                                 ((sqlite3_int64)db->nVTrans + ARRAY_INCR);\n    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);\n    if( !aVTrans ){\n      return SQLITE_NOMEM_BKPT;\n    }\n    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);\n    db->aVTrans = aVTrans;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should\n** have already been reserved using growVTrans().\n*/\nstatic void addToVTrans(sqlite3 *db, VTable *pVTab){\n  /* Add pVtab to the end of sqlite3.aVTrans */\n  db->aVTrans[db->nVTrans++] = pVTab;\n  sqlite3VtabLock(pVTab);\n}\n\n/*\n** This function is invoked by the vdbe to call the xCreate method\n** of the virtual table named zTab in database iDb. \n**\n** If an error occurs, *pzErr is set to point to an English language\n** description of the error and an SQLITE_XXX error code is returned.\n** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.\n*/\nSQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){\n  int rc = SQLITE_OK;\n  Table *pTab;\n  Module *pMod;\n  const char *zMod;\n\n  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);\n  assert( pTab && IsVirtual(pTab) && !pTab->pVTable );\n\n  /* Locate the required virtual table module */\n  zMod = pTab->azModuleArg[0];\n  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);\n\n  /* If the module has been registered and includes a Create method, \n  ** invoke it now. If the module has not been registered, return an \n  ** error. Otherwise, do nothing.\n  */\n  if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){\n    *pzErr = sqlite3MPrintf(db, \"no such module: %s\", zMod);\n    rc = SQLITE_ERROR;\n  }else{\n    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);\n  }\n\n  /* Justification of ALWAYS():  The xConstructor method is required to\n  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */\n  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){\n    rc = growVTrans(db);\n    if( rc==SQLITE_OK ){\n      addToVTrans(db, sqlite3GetVTable(db, pTab));\n    }\n  }\n\n  return rc;\n}\n\n/*\n** This function is used to set the schema of a virtual table.  It is only\n** valid to call this function from within the xCreate() or xConnect() of a\n** virtual table module.\n*/\nSQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){\n  VtabCtx *pCtx;\n  int rc = SQLITE_OK;\n  Table *pTab;\n  char *zErr = 0;\n  Parse sParse;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){\n    return SQLITE_MISUSE_BKPT;\n  }\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  pCtx = db->pVtabCtx;\n  if( !pCtx || pCtx->bDeclared ){\n    sqlite3Error(db, SQLITE_MISUSE);\n    sqlite3_mutex_leave(db->mutex);\n    return SQLITE_MISUSE_BKPT;\n  }\n  pTab = pCtx->pTab;\n  assert( IsVirtual(pTab) );\n\n  memset(&sParse, 0, sizeof(sParse));\n  sParse.eParseMode = PARSE_MODE_DECLARE_VTAB;\n  sParse.db = db;\n  sParse.nQueryLoop = 1;\n  if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr) \n   && sParse.pNewTable\n   && !db->mallocFailed\n   && !sParse.pNewTable->pSelect\n   && !IsVirtual(sParse.pNewTable)\n  ){\n    if( !pTab->aCol ){\n      Table *pNew = sParse.pNewTable;\n      Index *pIdx;\n      pTab->aCol = pNew->aCol;\n      pTab->nCol = pNew->nCol;\n      pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);\n      pNew->nCol = 0;\n      pNew->aCol = 0;\n      assert( pTab->pIndex==0 );\n      assert( HasRowid(pNew) || sqlite3PrimaryKeyIndex(pNew)!=0 );\n      if( !HasRowid(pNew)\n       && pCtx->pVTable->pMod->pModule->xUpdate!=0\n       && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1\n      ){\n        /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0)\n        ** or else must have a single-column PRIMARY KEY */\n        rc = SQLITE_ERROR;\n      }\n      pIdx = pNew->pIndex;\n      if( pIdx ){\n        assert( pIdx->pNext==0 );\n        pTab->pIndex = pIdx;\n        pNew->pIndex = 0;\n        pIdx->pTable = pTab;\n      }\n    }\n    pCtx->bDeclared = 1;\n  }else{\n    sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? \"%s\" : 0), zErr);\n    sqlite3DbFree(db, zErr);\n    rc = SQLITE_ERROR;\n  }\n  sParse.eParseMode = PARSE_MODE_NORMAL;\n\n  if( sParse.pVdbe ){\n    sqlite3VdbeFinalize(sParse.pVdbe);\n  }\n  sqlite3DeleteTable(db, sParse.pNewTable);\n  sqlite3ParserReset(&sParse);\n\n  assert( (rc&0xff)==rc );\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** This function is invoked by the vdbe to call the xDestroy method\n** of the virtual table named zTab in database iDb. This occurs\n** when a DROP TABLE is mentioned.\n**\n** This call is a no-op if zTab is not a virtual table.\n*/\nSQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){\n  int rc = SQLITE_OK;\n  Table *pTab;\n\n  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);\n  if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){\n    VTable *p;\n    int (*xDestroy)(sqlite3_vtab *);\n    for(p=pTab->pVTable; p; p=p->pNext){\n      assert( p->pVtab );\n      if( p->pVtab->nRef>0 ){\n        return SQLITE_LOCKED;\n      }\n    }\n    p = vtabDisconnectAll(db, pTab);\n    xDestroy = p->pMod->pModule->xDestroy;\n    if( xDestroy==0 ) xDestroy = p->pMod->pModule->xDisconnect;\n    assert( xDestroy!=0 );\n    pTab->nTabRef++;\n    rc = xDestroy(p->pVtab);\n    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */\n    if( rc==SQLITE_OK ){\n      assert( pTab->pVTable==p && p->pNext==0 );\n      p->pVtab = 0;\n      pTab->pVTable = 0;\n      sqlite3VtabUnlock(p);\n    }\n    sqlite3DeleteTable(db, pTab);\n  }\n\n  return rc;\n}\n\n/*\n** This function invokes either the xRollback or xCommit method\n** of each of the virtual tables in the sqlite3.aVTrans array. The method\n** called is identified by the second argument, \"offset\", which is\n** the offset of the method to call in the sqlite3_module structure.\n**\n** The array is cleared after invoking the callbacks. \n*/\nstatic void callFinaliser(sqlite3 *db, int offset){\n  int i;\n  if( db->aVTrans ){\n    VTable **aVTrans = db->aVTrans;\n    db->aVTrans = 0;\n    for(i=0; i<db->nVTrans; i++){\n      VTable *pVTab = aVTrans[i];\n      sqlite3_vtab *p = pVTab->pVtab;\n      if( p ){\n        int (*x)(sqlite3_vtab *);\n        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);\n        if( x ) x(p);\n      }\n      pVTab->iSavepoint = 0;\n      sqlite3VtabUnlock(pVTab);\n    }\n    sqlite3DbFree(db, aVTrans);\n    db->nVTrans = 0;\n  }\n}\n\n/*\n** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans\n** array. Return the error code for the first error that occurs, or\n** SQLITE_OK if all xSync operations are successful.\n**\n** If an error message is available, leave it in p->zErrMsg.\n*/\nSQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){\n  int i;\n  int rc = SQLITE_OK;\n  VTable **aVTrans = db->aVTrans;\n\n  db->aVTrans = 0;\n  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){\n    int (*x)(sqlite3_vtab *);\n    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;\n    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){\n      rc = x(pVtab);\n      sqlite3VtabImportErrmsg(p, pVtab);\n    }\n  }\n  db->aVTrans = aVTrans;\n  return rc;\n}\n\n/*\n** Invoke the xRollback method of all virtual tables in the \n** sqlite3.aVTrans array. Then clear the array itself.\n*/\nSQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){\n  callFinaliser(db, offsetof(sqlite3_module,xRollback));\n  return SQLITE_OK;\n}\n\n/*\n** Invoke the xCommit method of all virtual tables in the \n** sqlite3.aVTrans array. Then clear the array itself.\n*/\nSQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){\n  callFinaliser(db, offsetof(sqlite3_module,xCommit));\n  return SQLITE_OK;\n}\n\n/*\n** If the virtual table pVtab supports the transaction interface\n** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is\n** not currently open, invoke the xBegin method now.\n**\n** If the xBegin call is successful, place the sqlite3_vtab pointer\n** in the sqlite3.aVTrans array.\n*/\nSQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){\n  int rc = SQLITE_OK;\n  const sqlite3_module *pModule;\n\n  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater\n  ** than zero, then this function is being called from within a\n  ** virtual module xSync() callback. It is illegal to write to \n  ** virtual module tables in this case, so return SQLITE_LOCKED.\n  */\n  if( sqlite3VtabInSync(db) ){\n    return SQLITE_LOCKED;\n  }\n  if( !pVTab ){\n    return SQLITE_OK;\n  } \n  pModule = pVTab->pVtab->pModule;\n\n  if( pModule->xBegin ){\n    int i;\n\n    /* If pVtab is already in the aVTrans array, return early */\n    for(i=0; i<db->nVTrans; i++){\n      if( db->aVTrans[i]==pVTab ){\n        return SQLITE_OK;\n      }\n    }\n\n    /* Invoke the xBegin method. If successful, add the vtab to the \n    ** sqlite3.aVTrans[] array. */\n    rc = growVTrans(db);\n    if( rc==SQLITE_OK ){\n      rc = pModule->xBegin(pVTab->pVtab);\n      if( rc==SQLITE_OK ){\n        int iSvpt = db->nStatement + db->nSavepoint;\n        addToVTrans(db, pVTab);\n        if( iSvpt && pModule->xSavepoint ){\n          pVTab->iSavepoint = iSvpt;\n          rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);\n        }\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** Invoke either the xSavepoint, xRollbackTo or xRelease method of all\n** virtual tables that currently have an open transaction. Pass iSavepoint\n** as the second argument to the virtual table method invoked.\n**\n** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is\n** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is \n** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with\n** an open transaction is invoked.\n**\n** If any virtual table method returns an error code other than SQLITE_OK, \n** processing is abandoned and the error returned to the caller of this\n** function immediately. If all calls to virtual table methods are successful,\n** SQLITE_OK is returned.\n*/\nSQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){\n  int rc = SQLITE_OK;\n\n  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );\n  assert( iSavepoint>=-1 );\n  if( db->aVTrans ){\n    int i;\n    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){\n      VTable *pVTab = db->aVTrans[i];\n      const sqlite3_module *pMod = pVTab->pMod->pModule;\n      if( pVTab->pVtab && pMod->iVersion>=2 ){\n        int (*xMethod)(sqlite3_vtab *, int);\n        sqlite3VtabLock(pVTab);\n        switch( op ){\n          case SAVEPOINT_BEGIN:\n            xMethod = pMod->xSavepoint;\n            pVTab->iSavepoint = iSavepoint+1;\n            break;\n          case SAVEPOINT_ROLLBACK:\n            xMethod = pMod->xRollbackTo;\n            break;\n          default:\n            xMethod = pMod->xRelease;\n            break;\n        }\n        if( xMethod && pVTab->iSavepoint>iSavepoint ){\n          rc = xMethod(pVTab->pVtab, iSavepoint);\n        }\n        sqlite3VtabUnlock(pVTab);\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** The first parameter (pDef) is a function implementation.  The\n** second parameter (pExpr) is the first argument to this function.\n** If pExpr is a column in a virtual table, then let the virtual\n** table implementation have an opportunity to overload the function.\n**\n** This routine is used to allow virtual table implementations to\n** overload MATCH, LIKE, GLOB, and REGEXP operators.\n**\n** Return either the pDef argument (indicating no change) or a \n** new FuncDef structure that is marked as ephemeral using the\n** SQLITE_FUNC_EPHEM flag.\n*/\nSQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(\n  sqlite3 *db,    /* Database connection for reporting malloc problems */\n  FuncDef *pDef,  /* Function to possibly overload */\n  int nArg,       /* Number of arguments to the function */\n  Expr *pExpr     /* First argument to the function */\n){\n  Table *pTab;\n  sqlite3_vtab *pVtab;\n  sqlite3_module *pMod;\n  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;\n  void *pArg = 0;\n  FuncDef *pNew;\n  int rc = 0;\n\n  /* Check to see the left operand is a column in a virtual table */\n  if( NEVER(pExpr==0) ) return pDef;\n  if( pExpr->op!=TK_COLUMN ) return pDef;\n  pTab = pExpr->y.pTab;\n  if( pTab==0 ) return pDef;\n  if( !IsVirtual(pTab) ) return pDef;\n  pVtab = sqlite3GetVTable(db, pTab)->pVtab;\n  assert( pVtab!=0 );\n  assert( pVtab->pModule!=0 );\n  pMod = (sqlite3_module *)pVtab->pModule;\n  if( pMod->xFindFunction==0 ) return pDef;\n \n  /* Call the xFindFunction method on the virtual table implementation\n  ** to see if the implementation wants to overload this function.\n  **\n  ** Though undocumented, we have historically always invoked xFindFunction\n  ** with an all lower-case function name.  Continue in this tradition to\n  ** avoid any chance of an incompatibility.\n  */\n#ifdef SQLITE_DEBUG\n  {\n    int i;\n    for(i=0; pDef->zName[i]; i++){\n      unsigned char x = (unsigned char)pDef->zName[i];\n      assert( x==sqlite3UpperToLower[x] );\n    }\n  }\n#endif\n  rc = pMod->xFindFunction(pVtab, nArg, pDef->zName, &xSFunc, &pArg);\n  if( rc==0 ){\n    return pDef;\n  }\n\n  /* Create a new ephemeral function definition for the overloaded\n  ** function */\n  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)\n                             + sqlite3Strlen30(pDef->zName) + 1);\n  if( pNew==0 ){\n    return pDef;\n  }\n  *pNew = *pDef;\n  pNew->zName = (const char*)&pNew[1];\n  memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);\n  pNew->xSFunc = xSFunc;\n  pNew->pUserData = pArg;\n  pNew->funcFlags |= SQLITE_FUNC_EPHEM;\n  return pNew;\n}\n\n/*\n** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]\n** array so that an OP_VBegin will get generated for it.  Add pTab to the\n** array if it is missing.  If pTab is already in the array, this routine\n** is a no-op.\n*/\nSQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){\n  Parse *pToplevel = sqlite3ParseToplevel(pParse);\n  int i, n;\n  Table **apVtabLock;\n\n  assert( IsVirtual(pTab) );\n  for(i=0; i<pToplevel->nVtabLock; i++){\n    if( pTab==pToplevel->apVtabLock[i] ) return;\n  }\n  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);\n  apVtabLock = sqlite3Realloc(pToplevel->apVtabLock, n);\n  if( apVtabLock ){\n    pToplevel->apVtabLock = apVtabLock;\n    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;\n  }else{\n    sqlite3OomFault(pToplevel->db);\n  }\n}\n\n/*\n** Check to see if virtual table module pMod can be have an eponymous\n** virtual table instance.  If it can, create one if one does not already\n** exist. Return non-zero if the eponymous virtual table instance exists\n** when this routine returns, and return zero if it does not exist.\n**\n** An eponymous virtual table instance is one that is named after its\n** module, and more importantly, does not require a CREATE VIRTUAL TABLE\n** statement in order to come into existance.  Eponymous virtual table\n** instances always exist.  They cannot be DROP-ed.\n**\n** Any virtual table module for which xConnect and xCreate are the same\n** method can have an eponymous virtual table instance.\n*/\nSQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){\n  const sqlite3_module *pModule = pMod->pModule;\n  Table *pTab;\n  char *zErr = 0;\n  int rc;\n  sqlite3 *db = pParse->db;\n  if( pMod->pEpoTab ) return 1;\n  if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;\n  pTab = sqlite3DbMallocZero(db, sizeof(Table));\n  if( pTab==0 ) return 0;\n  pTab->zName = sqlite3DbStrDup(db, pMod->zName);\n  if( pTab->zName==0 ){\n    sqlite3DbFree(db, pTab);\n    return 0;\n  }\n  pMod->pEpoTab = pTab;\n  pTab->nTabRef = 1;\n  pTab->pSchema = db->aDb[0].pSchema;\n  assert( pTab->nModuleArg==0 );\n  pTab->iPKey = -1;\n  addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));\n  addModuleArgument(pParse, pTab, 0);\n  addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));\n  rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);\n  if( rc ){\n    sqlite3ErrorMsg(pParse, \"%s\", zErr);\n    sqlite3DbFree(db, zErr);\n    sqlite3VtabEponymousTableClear(db, pMod);\n    return 0;\n  }\n  return 1;\n}\n\n/*\n** Erase the eponymous virtual table instance associated with\n** virtual table module pMod, if it exists.\n*/\nSQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){\n  Table *pTab = pMod->pEpoTab;\n  if( pTab!=0 ){\n    /* Mark the table as Ephemeral prior to deleting it, so that the\n    ** sqlite3DeleteTable() routine will know that it is not stored in \n    ** the schema. */\n    pTab->tabFlags |= TF_Ephemeral;\n    sqlite3DeleteTable(db, pTab);\n    pMod->pEpoTab = 0;\n  }\n}\n\n/*\n** Return the ON CONFLICT resolution mode in effect for the virtual\n** table update operation currently in progress.\n**\n** The results of this routine are undefined unless it is called from\n** within an xUpdate method.\n*/\nSQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){\n  static const unsigned char aMap[] = { \n    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE \n  };\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;\n#endif\n  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );\n  assert( OE_Ignore==4 && OE_Replace==5 );\n  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );\n  return (int)aMap[db->vtabOnConflict-1];\n}\n\n/*\n** Call from within the xCreate() or xConnect() methods to provide \n** the SQLite core with additional information about the behavior\n** of the virtual table being implemented.\n*/\nSQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){\n  va_list ap;\n  int rc = SQLITE_OK;\n  VtabCtx *p;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  p = db->pVtabCtx;\n  if( !p ){\n    rc = SQLITE_MISUSE_BKPT;\n  }else{\n    assert( p->pTab==0 || IsVirtual(p->pTab) );\n    va_start(ap, op);\n    switch( op ){\n      case SQLITE_VTAB_CONSTRAINT_SUPPORT: {\n        p->pVTable->bConstraint = (u8)va_arg(ap, int);\n        break;\n      }\n      case SQLITE_VTAB_INNOCUOUS: {\n        p->pVTable->eVtabRisk = SQLITE_VTABRISK_Low;\n        break;\n      }\n      case SQLITE_VTAB_DIRECTONLY: {\n        p->pVTable->eVtabRisk = SQLITE_VTABRISK_High;\n        break;\n      }\n      default: {\n        rc = SQLITE_MISUSE_BKPT;\n        break;\n      }\n    }\n    va_end(ap);\n  }\n\n  if( rc!=SQLITE_OK ) sqlite3Error(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n/************** End of vtab.c ************************************************/\n/************** Begin file wherecode.c ***************************************/\n/*\n** 2015-06-06\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This module contains C code that generates VDBE code used to process\n** the WHERE clause of SQL statements.\n**\n** This file was split off from where.c on 2015-06-06 in order to reduce the\n** size of where.c and make it easier to edit.  This file contains the routines\n** that actually generate the bulk of the WHERE loop code.  The original where.c\n** file retains the code that does query planning and analysis.\n*/\n/* #include \"sqliteInt.h\" */\n/************** Include whereInt.h in the middle of wherecode.c **************/\n/************** Begin file whereInt.h ****************************************/\n/*\n** 2013-11-12\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains structure and macro definitions for the query\n** planner logic in \"where.c\".  These definitions are broken out into\n** a separate source file for easier editing.\n*/\n#ifndef SQLITE_WHEREINT_H\n#define SQLITE_WHEREINT_H\n\n/*\n** Trace output macros\n*/\n#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)\n/***/ extern int sqlite3WhereTrace;\n#endif\n#if defined(SQLITE_DEBUG) \\\n    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))\n# define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X\n# define WHERETRACE_ENABLED 1\n#else\n# define WHERETRACE(K,X)\n#endif\n\n/* Forward references\n*/\ntypedef struct WhereClause WhereClause;\ntypedef struct WhereMaskSet WhereMaskSet;\ntypedef struct WhereOrInfo WhereOrInfo;\ntypedef struct WhereAndInfo WhereAndInfo;\ntypedef struct WhereLevel WhereLevel;\ntypedef struct WhereLoop WhereLoop;\ntypedef struct WherePath WherePath;\ntypedef struct WhereTerm WhereTerm;\ntypedef struct WhereLoopBuilder WhereLoopBuilder;\ntypedef struct WhereScan WhereScan;\ntypedef struct WhereOrCost WhereOrCost;\ntypedef struct WhereOrSet WhereOrSet;\n\n/*\n** This object contains information needed to implement a single nested\n** loop in WHERE clause.\n**\n** Contrast this object with WhereLoop.  This object describes the\n** implementation of the loop.  WhereLoop describes the algorithm.\n** This object contains a pointer to the WhereLoop algorithm as one of\n** its elements.\n**\n** The WhereInfo object contains a single instance of this object for\n** each term in the FROM clause (which is to say, for each of the\n** nested loops as implemented).  The order of WhereLevel objects determines\n** the loop nested order, with WhereInfo.a[0] being the outer loop and\n** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.\n*/\nstruct WhereLevel {\n  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */\n  int iTabCur;          /* The VDBE cursor used to access the table */\n  int iIdxCur;          /* The VDBE cursor used to access pIdx */\n  int addrBrk;          /* Jump here to break out of the loop */\n  int addrNxt;          /* Jump here to start the next IN combination */\n  int addrSkip;         /* Jump here for next iteration of skip-scan */\n  int addrCont;         /* Jump here to continue with the next loop cycle */\n  int addrFirst;        /* First instruction of interior of the loop */\n  int addrBody;         /* Beginning of the body of this loop */\n  int regBignull;       /* big-null flag reg. True if a NULL-scan is needed */\n  int addrBignull;      /* Jump here for next part of big-null scan */\n#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS\n  u32 iLikeRepCntr;     /* LIKE range processing counter register (times 2) */\n  int addrLikeRep;      /* LIKE range processing address */\n#endif\n  u8 iFrom;             /* Which entry in the FROM clause */\n  u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */\n  int p1, p2;           /* Operands of the opcode used to end the loop */\n  union {               /* Information that depends on pWLoop->wsFlags */\n    struct {\n      int nIn;              /* Number of entries in aInLoop[] */\n      struct InLoop {\n        int iCur;              /* The VDBE cursor used by this IN operator */\n        int addrInTop;         /* Top of the IN loop */\n        int iBase;             /* Base register of multi-key index record */\n        int nPrefix;           /* Number of prior entires in the key */\n        u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */\n      } *aInLoop;           /* Information about each nested IN operator */\n    } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */\n    Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */\n  } u;\n  struct WhereLoop *pWLoop;  /* The selected WhereLoop object */\n  Bitmask notReady;          /* FROM entries not usable at this level */\n#ifdef SQLITE_ENABLE_STMT_SCANSTATUS\n  int addrVisit;        /* Address at which row is visited */\n#endif\n};\n\n/*\n** Each instance of this object represents an algorithm for evaluating one\n** term of a join.  Every term of the FROM clause will have at least\n** one corresponding WhereLoop object (unless INDEXED BY constraints\n** prevent a query solution - which is an error) and many terms of the\n** FROM clause will have multiple WhereLoop objects, each describing a\n** potential way of implementing that FROM-clause term, together with\n** dependencies and cost estimates for using the chosen algorithm.\n**\n** Query planning consists of building up a collection of these WhereLoop\n** objects, then computing a particular sequence of WhereLoop objects, with\n** one WhereLoop object per FROM clause term, that satisfy all dependencies\n** and that minimize the overall cost.\n*/\nstruct WhereLoop {\n  Bitmask prereq;       /* Bitmask of other loops that must run first */\n  Bitmask maskSelf;     /* Bitmask identifying table iTab */\n#ifdef SQLITE_DEBUG\n  char cId;             /* Symbolic ID of this loop for debugging use */\n#endif\n  u8 iTab;              /* Position in FROM clause of table for this loop */\n  u8 iSortIdx;          /* Sorting index number.  0==None */\n  LogEst rSetup;        /* One-time setup cost (ex: create transient index) */\n  LogEst rRun;          /* Cost of running each loop */\n  LogEst nOut;          /* Estimated number of output rows */\n  union {\n    struct {               /* Information for internal btree tables */\n      u16 nEq;               /* Number of equality constraints */\n      u16 nBtm;              /* Size of BTM vector */\n      u16 nTop;              /* Size of TOP vector */\n      u16 nDistinctCol;      /* Index columns used to sort for DISTINCT */\n      Index *pIndex;         /* Index used, or NULL */\n    } btree;\n    struct {               /* Information for virtual tables */\n      int idxNum;            /* Index number */\n      u8 needFree;           /* True if sqlite3_free(idxStr) is needed */\n      i8 isOrdered;          /* True if satisfies ORDER BY */\n      u16 omitMask;          /* Terms that may be omitted */\n      char *idxStr;          /* Index identifier string */\n    } vtab;\n  } u;\n  u32 wsFlags;          /* WHERE_* flags describing the plan */\n  u16 nLTerm;           /* Number of entries in aLTerm[] */\n  u16 nSkip;            /* Number of NULL aLTerm[] entries */\n  /**** whereLoopXfer() copies fields above ***********************/\n# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)\n  u16 nLSlot;           /* Number of slots allocated for aLTerm[] */\n  WhereTerm **aLTerm;   /* WhereTerms used */\n  WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */\n  WhereTerm *aLTermSpace[3];  /* Initial aLTerm[] space */\n};\n\n/* This object holds the prerequisites and the cost of running a\n** subquery on one operand of an OR operator in the WHERE clause.\n** See WhereOrSet for additional information \n*/\nstruct WhereOrCost {\n  Bitmask prereq;     /* Prerequisites */\n  LogEst rRun;        /* Cost of running this subquery */\n  LogEst nOut;        /* Number of outputs for this subquery */\n};\n\n/* The WhereOrSet object holds a set of possible WhereOrCosts that\n** correspond to the subquery(s) of OR-clause processing.  Only the\n** best N_OR_COST elements are retained.\n*/\n#define N_OR_COST 3\nstruct WhereOrSet {\n  u16 n;                      /* Number of valid a[] entries */\n  WhereOrCost a[N_OR_COST];   /* Set of best costs */\n};\n\n/*\n** Each instance of this object holds a sequence of WhereLoop objects\n** that implement some or all of a query plan.\n**\n** Think of each WhereLoop object as a node in a graph with arcs\n** showing dependencies and costs for travelling between nodes.  (That is\n** not a completely accurate description because WhereLoop costs are a\n** vector, not a scalar, and because dependencies are many-to-one, not\n** one-to-one as are graph nodes.  But it is a useful visualization aid.)\n** Then a WherePath object is a path through the graph that visits some\n** or all of the WhereLoop objects once.\n**\n** The \"solver\" works by creating the N best WherePath objects of length\n** 1.  Then using those as a basis to compute the N best WherePath objects\n** of length 2.  And so forth until the length of WherePaths equals the\n** number of nodes in the FROM clause.  The best (lowest cost) WherePath\n** at the end is the chosen query plan.\n*/\nstruct WherePath {\n  Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */\n  Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */\n  LogEst nRow;          /* Estimated number of rows generated by this path */\n  LogEst rCost;         /* Total cost of this path */\n  LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */\n  i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */\n  WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */\n};\n\n/*\n** The query generator uses an array of instances of this structure to\n** help it analyze the subexpressions of the WHERE clause.  Each WHERE\n** clause subexpression is separated from the others by AND operators,\n** usually, or sometimes subexpressions separated by OR.\n**\n** All WhereTerms are collected into a single WhereClause structure.  \n** The following identity holds:\n**\n**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm\n**\n** When a term is of the form:\n**\n**              X <op> <expr>\n**\n** where X is a column name and <op> is one of certain operators,\n** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the\n** cursor number and column number for X.  WhereTerm.eOperator records\n** the <op> using a bitmask encoding defined by WO_xxx below.  The\n** use of a bitmask encoding for the operator allows us to search\n** quickly for terms that match any of several different operators.\n**\n** A WhereTerm might also be two or more subterms connected by OR:\n**\n**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....\n**\n** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR\n** and the WhereTerm.u.pOrInfo field points to auxiliary information that\n** is collected about the OR clause.\n**\n** If a term in the WHERE clause does not match either of the two previous\n** categories, then eOperator==0.  The WhereTerm.pExpr field is still set\n** to the original subexpression content and wtFlags is set up appropriately\n** but no other fields in the WhereTerm object are meaningful.\n**\n** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,\n** but they do so indirectly.  A single WhereMaskSet structure translates\n** cursor number into bits and the translated bit is stored in the prereq\n** fields.  The translation is used in order to maximize the number of\n** bits that will fit in a Bitmask.  The VDBE cursor numbers might be\n** spread out over the non-negative integers.  For example, the cursor\n** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet\n** translates these sparse cursor numbers into consecutive integers\n** beginning with 0 in order to make the best possible use of the available\n** bits in the Bitmask.  So, in the example above, the cursor numbers\n** would be mapped into integers 0 through 7.\n**\n** The number of terms in a join is limited by the number of bits\n** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite\n** is only able to process joins with 64 or fewer tables.\n*/\nstruct WhereTerm {\n  Expr *pExpr;            /* Pointer to the subexpression that is this term */\n  WhereClause *pWC;       /* The clause this term is part of */\n  LogEst truthProb;       /* Probability of truth for this expression */\n  u16 wtFlags;            /* TERM_xxx bit flags.  See below */\n  u16 eOperator;          /* A WO_xx value describing <op> */\n  u8 nChild;              /* Number of children that must disable us */\n  u8 eMatchOp;            /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */\n  int iParent;            /* Disable pWC->a[iParent] when this term disabled */\n  int leftCursor;         /* Cursor number of X in \"X <op> <expr>\" */\n  int iField;             /* Field in (?,?,?) IN (SELECT...) vector */\n  union {\n    int leftColumn;         /* Column number of X in \"X <op> <expr>\" */\n    WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */\n    WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */\n  } u;\n  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */\n  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */\n};\n\n/*\n** Allowed values of WhereTerm.wtFlags\n*/\n#define TERM_DYNAMIC    0x0001 /* Need to call sqlite3ExprDelete(db, pExpr) */\n#define TERM_VIRTUAL    0x0002 /* Added by the optimizer.  Do not code */\n#define TERM_CODED      0x0004 /* This term is already coded */\n#define TERM_COPIED     0x0008 /* Has a child */\n#define TERM_ORINFO     0x0010 /* Need to free the WhereTerm.u.pOrInfo object */\n#define TERM_ANDINFO    0x0020 /* Need to free the WhereTerm.u.pAndInfo obj */\n#define TERM_OR_OK      0x0040 /* Used during OR-clause processing */\n#ifdef SQLITE_ENABLE_STAT4\n#  define TERM_VNULL    0x0080 /* Manufactured x>NULL or x<=NULL term */\n#else\n#  define TERM_VNULL    0x0000 /* Disabled if not using stat4 */\n#endif\n#define TERM_LIKEOPT    0x0100 /* Virtual terms from the LIKE optimization */\n#define TERM_LIKECOND   0x0200 /* Conditionally this LIKE operator term */\n#define TERM_LIKE       0x0400 /* The original LIKE operator */\n#define TERM_IS         0x0800 /* Term.pExpr is an IS operator */\n#define TERM_VARSELECT  0x1000 /* Term.pExpr contains a correlated sub-query */\n#define TERM_HEURTRUTH  0x2000 /* Heuristic truthProb used */\n#ifdef SQLITE_ENABLE_STAT4\n#  define TERM_HIGHTRUTH  0x4000 /* Term excludes few rows */\n#else\n#  define TERM_HIGHTRUTH  0      /* Only used with STAT4 */\n#endif\n\n/*\n** An instance of the WhereScan object is used as an iterator for locating\n** terms in the WHERE clause that are useful to the query planner.\n*/\nstruct WhereScan {\n  WhereClause *pOrigWC;      /* Original, innermost WhereClause */\n  WhereClause *pWC;          /* WhereClause currently being scanned */\n  const char *zCollName;     /* Required collating sequence, if not NULL */\n  Expr *pIdxExpr;            /* Search for this index expression */\n  char idxaff;               /* Must match this affinity, if zCollName!=NULL */\n  unsigned char nEquiv;      /* Number of entries in aEquiv[] */\n  unsigned char iEquiv;      /* Next unused slot in aEquiv[] */\n  u32 opMask;                /* Acceptable operators */\n  int k;                     /* Resume scanning at this->pWC->a[this->k] */\n  int aiCur[11];             /* Cursors in the equivalence class */\n  i16 aiColumn[11];          /* Corresponding column number in the eq-class */\n};\n\n/*\n** An instance of the following structure holds all information about a\n** WHERE clause.  Mostly this is a container for one or more WhereTerms.\n**\n** Explanation of pOuter:  For a WHERE clause of the form\n**\n**           a AND ((b AND c) OR (d AND e)) AND f\n**\n** There are separate WhereClause objects for the whole clause and for\n** the subclauses \"(b AND c)\" and \"(d AND e)\".  The pOuter field of the\n** subclauses points to the WhereClause object for the whole clause.\n*/\nstruct WhereClause {\n  WhereInfo *pWInfo;       /* WHERE clause processing context */\n  WhereClause *pOuter;     /* Outer conjunction */\n  u8 op;                   /* Split operator.  TK_AND or TK_OR */\n  u8 hasOr;                /* True if any a[].eOperator is WO_OR */\n  int nTerm;               /* Number of terms */\n  int nSlot;               /* Number of entries in a[] */\n  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */\n#if defined(SQLITE_SMALL_STACK)\n  WhereTerm aStatic[1];    /* Initial static space for a[] */\n#else\n  WhereTerm aStatic[8];    /* Initial static space for a[] */\n#endif\n};\n\n/*\n** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to\n** a dynamically allocated instance of the following structure.\n*/\nstruct WhereOrInfo {\n  WhereClause wc;          /* Decomposition into subterms */\n  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */\n};\n\n/*\n** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to\n** a dynamically allocated instance of the following structure.\n*/\nstruct WhereAndInfo {\n  WhereClause wc;          /* The subexpression broken out */\n};\n\n/*\n** An instance of the following structure keeps track of a mapping\n** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.\n**\n** The VDBE cursor numbers are small integers contained in \n** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE \n** clause, the cursor numbers might not begin with 0 and they might\n** contain gaps in the numbering sequence.  But we want to make maximum\n** use of the bits in our bitmasks.  This structure provides a mapping\n** from the sparse cursor numbers into consecutive integers beginning\n** with 0.\n**\n** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask\n** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.\n**\n** For example, if the WHERE clause expression used these VDBE\n** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure\n** would map those cursor numbers into bits 0 through 5.\n**\n** Note that the mapping is not necessarily ordered.  In the example\n** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,\n** 57->5, 73->4.  Or one of 719 other combinations might be used. It\n** does not really matter.  What is important is that sparse cursor\n** numbers all get mapped into bit numbers that begin with 0 and contain\n** no gaps.\n*/\nstruct WhereMaskSet {\n  int bVarSelect;               /* Used by sqlite3WhereExprUsage() */\n  int n;                        /* Number of assigned cursor values */\n  int ix[BMS];                  /* Cursor assigned to each bit */\n};\n\n/*\n** Initialize a WhereMaskSet object\n*/\n#define initMaskSet(P)  (P)->n=0\n\n/*\n** This object is a convenience wrapper holding all information needed\n** to construct WhereLoop objects for a particular query.\n*/\nstruct WhereLoopBuilder {\n  WhereInfo *pWInfo;        /* Information about this WHERE */\n  WhereClause *pWC;         /* WHERE clause terms */\n  ExprList *pOrderBy;       /* ORDER BY clause */\n  WhereLoop *pNew;          /* Template WhereLoop */\n  WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */\n#ifdef SQLITE_ENABLE_STAT4\n  UnpackedRecord *pRec;     /* Probe for stat4 (if required) */\n  int nRecValid;            /* Number of valid fields currently in pRec */\n#endif\n  unsigned char bldFlags1;  /* First set of SQLITE_BLDF_* flags */\n  unsigned char bldFlags2;  /* Second set of SQLITE_BLDF_* flags */\n  unsigned int iPlanLimit;  /* Search limiter */\n};\n\n/* Allowed values for WhereLoopBuider.bldFlags */\n#define SQLITE_BLDF1_INDEXED  0x0001   /* An index is used */\n#define SQLITE_BLDF1_UNIQUE   0x0002   /* All keys of a UNIQUE index used */\n\n#define SQLITE_BLDF2_2NDPASS  0x0004   /* Second builder pass needed */\n\n/* The WhereLoopBuilder.iPlanLimit is used to limit the number of\n** index+constraint combinations the query planner will consider for a\n** particular query.  If this parameter is unlimited, then certain\n** pathological queries can spend excess time in the sqlite3WhereBegin()\n** routine.  The limit is high enough that is should not impact real-world\n** queries.\n**\n** SQLITE_QUERY_PLANNER_LIMIT is the baseline limit.  The limit is\n** increased by SQLITE_QUERY_PLANNER_LIMIT_INCR before each term of the FROM\n** clause is processed, so that every table in a join is guaranteed to be\n** able to propose a some index+constraint combinations even if the initial\n** baseline limit was exhausted by prior tables of the join.\n*/\n#ifndef SQLITE_QUERY_PLANNER_LIMIT\n# define SQLITE_QUERY_PLANNER_LIMIT 20000\n#endif\n#ifndef SQLITE_QUERY_PLANNER_LIMIT_INCR\n# define SQLITE_QUERY_PLANNER_LIMIT_INCR 1000\n#endif\n\n/*\n** Each instance of this object records a change to a single node\n** in an expression tree to cause that node to point to a column\n** of an index rather than an expression or a virtual column.  All\n** such transformations need to be undone at the end of WHERE clause\n** processing.\n*/\ntypedef struct WhereExprMod WhereExprMod;\nstruct WhereExprMod {\n  WhereExprMod *pNext;  /* Next translation on a list of them all */\n  Expr *pExpr;          /* The Expr node that was transformed */\n  Expr orig;            /* Original value of the Expr node */\n};\n\n/*\n** The WHERE clause processing routine has two halves.  The\n** first part does the start of the WHERE loop and the second\n** half does the tail of the WHERE loop.  An instance of\n** this structure is returned by the first half and passed\n** into the second half to give some continuity.\n**\n** An instance of this object holds the complete state of the query\n** planner.\n*/\nstruct WhereInfo {\n  Parse *pParse;            /* Parsing and code generating context */\n  SrcList *pTabList;        /* List of tables in the join */\n  ExprList *pOrderBy;       /* The ORDER BY clause or NULL */\n  ExprList *pResultSet;     /* Result set of the query */\n  Expr *pWhere;             /* The complete WHERE clause */\n  int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */\n  int iContinue;            /* Jump here to continue with next record */\n  int iBreak;               /* Jump here to break out of the loop */\n  int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */\n  u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */\n  LogEst iLimit;            /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */\n  u8 nLevel;                /* Number of nested loop */\n  i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */\n  u8 eOnePass;              /* ONEPASS_OFF, or _SINGLE, or _MULTI */\n  u8 eDistinct;             /* One of the WHERE_DISTINCT_* values */\n  unsigned bDeferredSeek :1;   /* Uses OP_DeferredSeek */\n  unsigned untestedTerms :1;   /* Not all WHERE terms resolved by outer loop */\n  unsigned bOrderedInnerLoop:1;/* True if only the inner-most loop is ordered */\n  unsigned sorted :1;          /* True if really sorted (not just grouped) */\n  LogEst nRowOut;           /* Estimated number of output rows */\n  int iTop;                 /* The very beginning of the WHERE loop */\n  WhereLoop *pLoops;        /* List of all WhereLoop objects */\n  WhereExprMod *pExprMods;  /* Expression modifications */\n  Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */\n  WhereClause sWC;          /* Decomposition of the WHERE clause */\n  WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */\n  WhereLevel a[1];          /* Information about each nest loop in WHERE */\n};\n\n/*\n** Private interfaces - callable only by other where.c routines.\n**\n** where.c:\n*/\nSQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);\n#ifdef WHERETRACE_ENABLED\nSQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);\nSQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm);\nSQLITE_PRIVATE void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC);\n#endif\nSQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(\n  WhereClause *pWC,     /* The WHERE clause to be searched */\n  int iCur,             /* Cursor number of LHS */\n  int iColumn,          /* Column number of LHS */\n  Bitmask notReady,     /* RHS must not overlap with this mask */\n  u32 op,               /* Mask of WO_xx values describing operator */\n  Index *pIdx           /* Must be compatible with this index, if not NULL */\n);\n\n/* wherecode.c: */\n#ifndef SQLITE_OMIT_EXPLAIN\nSQLITE_PRIVATE int sqlite3WhereExplainOneScan(\n  Parse *pParse,                  /* Parse context */\n  SrcList *pTabList,              /* Table list this loop refers to */\n  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */\n  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */\n);\n#else\n# define sqlite3WhereExplainOneScan(u,v,w,x) 0\n#endif /* SQLITE_OMIT_EXPLAIN */\n#ifdef SQLITE_ENABLE_STMT_SCANSTATUS\nSQLITE_PRIVATE void sqlite3WhereAddScanStatus(\n  Vdbe *v,                        /* Vdbe to add scanstatus entry to */\n  SrcList *pSrclist,              /* FROM clause pLvl reads data from */\n  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */\n  int addrExplain                 /* Address of OP_Explain (or 0) */\n);\n#else\n# define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)\n#endif\nSQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(\n  Parse *pParse,       /* Parsing context */\n  Vdbe *v,             /* Prepared statement under construction */\n  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */\n  int iLevel,          /* Which level of pWInfo->a[] should be coded */\n  WhereLevel *pLevel,  /* The current level pointer */\n  Bitmask notReady     /* Which tables are currently available */\n);\n\n/* whereexpr.c: */\nSQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);\nSQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);\nSQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);\nSQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);\nSQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet*, Expr*);\nSQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);\nSQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);\nSQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);\n\n\n\n\n\n/*\n** Bitmasks for the operators on WhereTerm objects.  These are all\n** operators that are of interest to the query planner.  An\n** OR-ed combination of these values can be used when searching for\n** particular WhereTerms within a WhereClause.\n**\n** Value constraints:\n**     WO_EQ    == SQLITE_INDEX_CONSTRAINT_EQ\n**     WO_LT    == SQLITE_INDEX_CONSTRAINT_LT\n**     WO_LE    == SQLITE_INDEX_CONSTRAINT_LE\n**     WO_GT    == SQLITE_INDEX_CONSTRAINT_GT\n**     WO_GE    == SQLITE_INDEX_CONSTRAINT_GE\n*/\n#define WO_IN     0x0001\n#define WO_EQ     0x0002\n#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))\n#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))\n#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))\n#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))\n#define WO_AUX    0x0040       /* Op useful to virtual tables only */\n#define WO_IS     0x0080\n#define WO_ISNULL 0x0100\n#define WO_OR     0x0200       /* Two or more OR-connected terms */\n#define WO_AND    0x0400       /* Two or more AND-connected terms */\n#define WO_EQUIV  0x0800       /* Of the form A==B, both columns */\n#define WO_NOOP   0x1000       /* This term does not restrict search space */\n\n#define WO_ALL    0x1fff       /* Mask of all possible WO_* values */\n#define WO_SINGLE 0x01ff       /* Mask of all non-compound WO_* values */\n\n/*\n** These are definitions of bits in the WhereLoop.wsFlags field.\n** The particular combination of bits in each WhereLoop help to\n** determine the algorithm that WhereLoop represents.\n*/\n#define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */\n#define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */\n#define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */\n#define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */\n#define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */\n#define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */\n#define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */\n#define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */\n#define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */\n#define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */\n#define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */\n#define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */\n#define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */\n#define WHERE_ONEROW       0x00001000  /* Selects no more than one row */\n#define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */\n#define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */\n#define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */\n#define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/\n#define WHERE_PARTIALIDX   0x00020000  /* The automatic index is partial */\n#define WHERE_IN_EARLYOUT  0x00040000  /* Perhaps quit IN loops early */\n#define WHERE_BIGNULL_SORT 0x00080000  /* Column nEq of index is BIGNULL */\n\n#endif /* !defined(SQLITE_WHEREINT_H) */\n\n/************** End of whereInt.h ********************************************/\n/************** Continuing where we left off in wherecode.c ******************/\n\n#ifndef SQLITE_OMIT_EXPLAIN\n\n/*\n** Return the name of the i-th column of the pIdx index.\n*/\nstatic const char *explainIndexColumnName(Index *pIdx, int i){\n  i = pIdx->aiColumn[i];\n  if( i==XN_EXPR ) return \"<expr>\";\n  if( i==XN_ROWID ) return \"rowid\";\n  return pIdx->pTable->aCol[i].zName;\n}\n\n/*\n** This routine is a helper for explainIndexRange() below\n**\n** pStr holds the text of an expression that we are building up one term\n** at a time.  This routine adds a new term to the end of the expression.\n** Terms are separated by AND so add the \"AND\" text for second and subsequent\n** terms only.\n*/\nstatic void explainAppendTerm(\n  StrAccum *pStr,             /* The text expression being built */\n  Index *pIdx,                /* Index to read column names from */\n  int nTerm,                  /* Number of terms */\n  int iTerm,                  /* Zero-based index of first term. */\n  int bAnd,                   /* Non-zero to append \" AND \" */\n  const char *zOp             /* Name of the operator */\n){\n  int i;\n\n  assert( nTerm>=1 );\n  if( bAnd ) sqlite3_str_append(pStr, \" AND \", 5);\n\n  if( nTerm>1 ) sqlite3_str_append(pStr, \"(\", 1);\n  for(i=0; i<nTerm; i++){\n    if( i ) sqlite3_str_append(pStr, \",\", 1);\n    sqlite3_str_appendall(pStr, explainIndexColumnName(pIdx, iTerm+i));\n  }\n  if( nTerm>1 ) sqlite3_str_append(pStr, \")\", 1);\n\n  sqlite3_str_append(pStr, zOp, 1);\n\n  if( nTerm>1 ) sqlite3_str_append(pStr, \"(\", 1);\n  for(i=0; i<nTerm; i++){\n    if( i ) sqlite3_str_append(pStr, \",\", 1);\n    sqlite3_str_append(pStr, \"?\", 1);\n  }\n  if( nTerm>1 ) sqlite3_str_append(pStr, \")\", 1);\n}\n\n/*\n** Argument pLevel describes a strategy for scanning table pTab. This \n** function appends text to pStr that describes the subset of table\n** rows scanned by the strategy in the form of an SQL expression.\n**\n** For example, if the query:\n**\n**   SELECT * FROM t1 WHERE a=1 AND b>2;\n**\n** is run and there is an index on (a, b), then this function returns a\n** string similar to:\n**\n**   \"a=? AND b>?\"\n*/\nstatic void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){\n  Index *pIndex = pLoop->u.btree.pIndex;\n  u16 nEq = pLoop->u.btree.nEq;\n  u16 nSkip = pLoop->nSkip;\n  int i, j;\n\n  if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;\n  sqlite3_str_append(pStr, \" (\", 2);\n  for(i=0; i<nEq; i++){\n    const char *z = explainIndexColumnName(pIndex, i);\n    if( i ) sqlite3_str_append(pStr, \" AND \", 5);\n    sqlite3_str_appendf(pStr, i>=nSkip ? \"%s=?\" : \"ANY(%s)\", z);\n  }\n\n  j = i;\n  if( pLoop->wsFlags&WHERE_BTM_LIMIT ){\n    explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, \">\");\n    i = 1;\n  }\n  if( pLoop->wsFlags&WHERE_TOP_LIMIT ){\n    explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, \"<\");\n  }\n  sqlite3_str_append(pStr, \")\", 1);\n}\n\n/*\n** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN\n** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was\n** defined at compile-time. If it is not a no-op, a single OP_Explain opcode \n** is added to the output to describe the table scan strategy in pLevel.\n**\n** If an OP_Explain opcode is added to the VM, its address is returned.\n** Otherwise, if no OP_Explain is coded, zero is returned.\n*/\nSQLITE_PRIVATE int sqlite3WhereExplainOneScan(\n  Parse *pParse,                  /* Parse context */\n  SrcList *pTabList,              /* Table list this loop refers to */\n  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */\n  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */\n){\n  int ret = 0;\n#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)\n  if( sqlite3ParseToplevel(pParse)->explain==2 )\n#endif\n  {\n    struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];\n    Vdbe *v = pParse->pVdbe;      /* VM being constructed */\n    sqlite3 *db = pParse->db;     /* Database handle */\n    int isSearch;                 /* True for a SEARCH. False for SCAN. */\n    WhereLoop *pLoop;             /* The controlling WhereLoop object */\n    u32 flags;                    /* Flags that describe this loop */\n    char *zMsg;                   /* Text to add to EQP output */\n    StrAccum str;                 /* EQP output string */\n    char zBuf[100];               /* Initial space for EQP output string */\n\n    pLoop = pLevel->pWLoop;\n    flags = pLoop->wsFlags;\n    if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;\n\n    isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0\n            || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))\n            || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));\n\n    sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);\n    sqlite3_str_appendall(&str, isSearch ? \"SEARCH\" : \"SCAN\");\n    if( pItem->pSelect ){\n      sqlite3_str_appendf(&str, \" SUBQUERY %u\", pItem->pSelect->selId);\n    }else{\n      sqlite3_str_appendf(&str, \" TABLE %s\", pItem->zName);\n    }\n\n    if( pItem->zAlias ){\n      sqlite3_str_appendf(&str, \" AS %s\", pItem->zAlias);\n    }\n    if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){\n      const char *zFmt = 0;\n      Index *pIdx;\n\n      assert( pLoop->u.btree.pIndex!=0 );\n      pIdx = pLoop->u.btree.pIndex;\n      assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );\n      if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){\n        if( isSearch ){\n          zFmt = \"PRIMARY KEY\";\n        }\n      }else if( flags & WHERE_PARTIALIDX ){\n        zFmt = \"AUTOMATIC PARTIAL COVERING INDEX\";\n      }else if( flags & WHERE_AUTO_INDEX ){\n        zFmt = \"AUTOMATIC COVERING INDEX\";\n      }else if( flags & WHERE_IDX_ONLY ){\n        zFmt = \"COVERING INDEX %s\";\n      }else{\n        zFmt = \"INDEX %s\";\n      }\n      if( zFmt ){\n        sqlite3_str_append(&str, \" USING \", 7);\n        sqlite3_str_appendf(&str, zFmt, pIdx->zName);\n        explainIndexRange(&str, pLoop);\n      }\n    }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){\n      const char *zRangeOp;\n      if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){\n        zRangeOp = \"=\";\n      }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){\n        zRangeOp = \">? AND rowid<\";\n      }else if( flags&WHERE_BTM_LIMIT ){\n        zRangeOp = \">\";\n      }else{\n        assert( flags&WHERE_TOP_LIMIT);\n        zRangeOp = \"<\";\n      }\n      sqlite3_str_appendf(&str, \n          \" USING INTEGER PRIMARY KEY (rowid%s?)\",zRangeOp);\n    }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    else if( (flags & WHERE_VIRTUALTABLE)!=0 ){\n      sqlite3_str_appendf(&str, \" VIRTUAL TABLE INDEX %d:%s\",\n                  pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);\n    }\n#endif\n#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS\n    if( pLoop->nOut>=10 ){\n      sqlite3_str_appendf(&str, \" (~%llu rows)\",\n             sqlite3LogEstToInt(pLoop->nOut));\n    }else{\n      sqlite3_str_append(&str, \" (~1 row)\", 9);\n    }\n#endif\n    zMsg = sqlite3StrAccumFinish(&str);\n    sqlite3ExplainBreakpoint(\"\",zMsg);\n    ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),\n                            pParse->addrExplain, 0, zMsg,P4_DYNAMIC);\n  }\n  return ret;\n}\n#endif /* SQLITE_OMIT_EXPLAIN */\n\n#ifdef SQLITE_ENABLE_STMT_SCANSTATUS\n/*\n** Configure the VM passed as the first argument with an\n** sqlite3_stmt_scanstatus() entry corresponding to the scan used to \n** implement level pLvl. Argument pSrclist is a pointer to the FROM \n** clause that the scan reads data from.\n**\n** If argument addrExplain is not 0, it must be the address of an \n** OP_Explain instruction that describes the same loop.\n*/\nSQLITE_PRIVATE void sqlite3WhereAddScanStatus(\n  Vdbe *v,                        /* Vdbe to add scanstatus entry to */\n  SrcList *pSrclist,              /* FROM clause pLvl reads data from */\n  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */\n  int addrExplain                 /* Address of OP_Explain (or 0) */\n){\n  const char *zObj = 0;\n  WhereLoop *pLoop = pLvl->pWLoop;\n  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){\n    zObj = pLoop->u.btree.pIndex->zName;\n  }else{\n    zObj = pSrclist->a[pLvl->iFrom].zName;\n  }\n  sqlite3VdbeScanStatus(\n      v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj\n  );\n}\n#endif\n\n\n/*\n** Disable a term in the WHERE clause.  Except, do not disable the term\n** if it controls a LEFT OUTER JOIN and it did not originate in the ON\n** or USING clause of that join.\n**\n** Consider the term t2.z='ok' in the following queries:\n**\n**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'\n**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'\n**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'\n**\n** The t2.z='ok' is disabled in the in (2) because it originates\n** in the ON clause.  The term is disabled in (3) because it is not part\n** of a LEFT OUTER JOIN.  In (1), the term is not disabled.\n**\n** Disabling a term causes that term to not be tested in the inner loop\n** of the join.  Disabling is an optimization.  When terms are satisfied\n** by indices, we disable them to prevent redundant tests in the inner\n** loop.  We would get the correct results if nothing were ever disabled,\n** but joins might run a little slower.  The trick is to disable as much\n** as we can without disabling too much.  If we disabled in (1), we'd get\n** the wrong answer.  See ticket #813.\n**\n** If all the children of a term are disabled, then that term is also\n** automatically disabled.  In this way, terms get disabled if derived\n** virtual terms are tested first.  For example:\n**\n**      x GLOB 'abc*' AND x>='abc' AND x<'acd'\n**      \\___________/     \\______/     \\_____/\n**         parent          child1       child2\n**\n** Only the parent term was in the original WHERE clause.  The child1\n** and child2 terms were added by the LIKE optimization.  If both of\n** the virtual child terms are valid, then testing of the parent can be \n** skipped.\n**\n** Usually the parent term is marked as TERM_CODED.  But if the parent\n** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.\n** The TERM_LIKECOND marking indicates that the term should be coded inside\n** a conditional such that is only evaluated on the second pass of a\n** LIKE-optimization loop, when scanning BLOBs instead of strings.\n*/\nstatic void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){\n  int nLoop = 0;\n  assert( pTerm!=0 );\n  while( (pTerm->wtFlags & TERM_CODED)==0\n      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))\n      && (pLevel->notReady & pTerm->prereqAll)==0\n  ){\n    if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){\n      pTerm->wtFlags |= TERM_LIKECOND;\n    }else{\n      pTerm->wtFlags |= TERM_CODED;\n    }\n    if( pTerm->iParent<0 ) break;\n    pTerm = &pTerm->pWC->a[pTerm->iParent];\n    assert( pTerm!=0 );\n    pTerm->nChild--;\n    if( pTerm->nChild!=0 ) break;\n    nLoop++;\n  }\n}\n\n/*\n** Code an OP_Affinity opcode to apply the column affinity string zAff\n** to the n registers starting at base. \n**\n** As an optimization, SQLITE_AFF_BLOB and SQLITE_AFF_NONE entries (which\n** are no-ops) at the beginning and end of zAff are ignored.  If all entries\n** in zAff are SQLITE_AFF_BLOB or SQLITE_AFF_NONE, then no code gets generated.\n**\n** This routine makes its own copy of zAff so that the caller is free\n** to modify zAff after this routine returns.\n*/\nstatic void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){\n  Vdbe *v = pParse->pVdbe;\n  if( zAff==0 ){\n    assert( pParse->db->mallocFailed );\n    return;\n  }\n  assert( v!=0 );\n\n  /* Adjust base and n to skip over SQLITE_AFF_BLOB and SQLITE_AFF_NONE\n  ** entries at the beginning and end of the affinity string.\n  */\n  assert( SQLITE_AFF_NONE<SQLITE_AFF_BLOB );\n  while( n>0 && zAff[0]<=SQLITE_AFF_BLOB ){\n    n--;\n    base++;\n    zAff++;\n  }\n  while( n>1 && zAff[n-1]<=SQLITE_AFF_BLOB ){\n    n--;\n  }\n\n  /* Code the OP_Affinity opcode if there is anything left to do. */\n  if( n>0 ){\n    sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);\n  }\n}\n\n/*\n** Expression pRight, which is the RHS of a comparison operation, is \n** either a vector of n elements or, if n==1, a scalar expression.\n** Before the comparison operation, affinity zAff is to be applied\n** to the pRight values. This function modifies characters within the\n** affinity string to SQLITE_AFF_BLOB if either:\n**\n**   * the comparison will be performed with no affinity, or\n**   * the affinity change in zAff is guaranteed not to change the value.\n*/\nstatic void updateRangeAffinityStr(\n  Expr *pRight,                   /* RHS of comparison */\n  int n,                          /* Number of vector elements in comparison */\n  char *zAff                      /* Affinity string to modify */\n){\n  int i;\n  for(i=0; i<n; i++){\n    Expr *p = sqlite3VectorFieldSubexpr(pRight, i);\n    if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB\n     || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])\n    ){\n      zAff[i] = SQLITE_AFF_BLOB;\n    }\n  }\n}\n\n\n/*\n** pX is an expression of the form:  (vector) IN (SELECT ...)\n** In other words, it is a vector IN operator with a SELECT clause on the\n** LHS.  But not all terms in the vector are indexable and the terms might\n** not be in the correct order for indexing.\n**\n** This routine makes a copy of the input pX expression and then adjusts\n** the vector on the LHS with corresponding changes to the SELECT so that\n** the vector contains only index terms and those terms are in the correct\n** order.  The modified IN expression is returned.  The caller is responsible\n** for deleting the returned expression.\n**\n** Example:\n**\n**    CREATE TABLE t1(a,b,c,d,e,f);\n**    CREATE INDEX t1x1 ON t1(e,c);\n**    SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2)\n**                           \\_______________________________________/\n**                                     The pX expression\n**\n** Since only columns e and c can be used with the index, in that order,\n** the modified IN expression that is returned will be:\n**\n**        (e,c) IN (SELECT z,x FROM t2)\n**\n** The reduced pX is different from the original (obviously) and thus is\n** only used for indexing, to improve performance.  The original unaltered\n** IN expression must also be run on each output row for correctness.\n*/\nstatic Expr *removeUnindexableInClauseTerms(\n  Parse *pParse,        /* The parsing context */\n  int iEq,              /* Look at loop terms starting here */\n  WhereLoop *pLoop,     /* The current loop */\n  Expr *pX              /* The IN expression to be reduced */\n){\n  sqlite3 *db = pParse->db;\n  Expr *pNew;\n  pNew = sqlite3ExprDup(db, pX, 0);\n  if( db->mallocFailed==0 ){\n    ExprList *pOrigRhs = pNew->x.pSelect->pEList;  /* Original unmodified RHS */\n    ExprList *pOrigLhs = pNew->pLeft->x.pList;     /* Original unmodified LHS */\n    ExprList *pRhs = 0;         /* New RHS after modifications */\n    ExprList *pLhs = 0;         /* New LHS after mods */\n    int i;                      /* Loop counter */\n    Select *pSelect;            /* Pointer to the SELECT on the RHS */\n\n    for(i=iEq; i<pLoop->nLTerm; i++){\n      if( pLoop->aLTerm[i]->pExpr==pX ){\n        int iField = pLoop->aLTerm[i]->iField - 1;\n        if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */\n        pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);\n        pOrigRhs->a[iField].pExpr = 0;\n        assert( pOrigLhs->a[iField].pExpr!=0 );\n        pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr);\n        pOrigLhs->a[iField].pExpr = 0;\n      }\n    }\n    sqlite3ExprListDelete(db, pOrigRhs);\n    sqlite3ExprListDelete(db, pOrigLhs);\n    pNew->pLeft->x.pList = pLhs;\n    pNew->x.pSelect->pEList = pRhs;\n    if( pLhs && pLhs->nExpr==1 ){\n      /* Take care here not to generate a TK_VECTOR containing only a\n      ** single value. Since the parser never creates such a vector, some\n      ** of the subroutines do not handle this case.  */\n      Expr *p = pLhs->a[0].pExpr;\n      pLhs->a[0].pExpr = 0;\n      sqlite3ExprDelete(db, pNew->pLeft);\n      pNew->pLeft = p;\n    }\n    pSelect = pNew->x.pSelect;\n    if( pSelect->pOrderBy ){\n      /* If the SELECT statement has an ORDER BY clause, zero the \n      ** iOrderByCol variables. These are set to non-zero when an \n      ** ORDER BY term exactly matches one of the terms of the \n      ** result-set. Since the result-set of the SELECT statement may\n      ** have been modified or reordered, these variables are no longer \n      ** set correctly.  Since setting them is just an optimization, \n      ** it's easiest just to zero them here.  */\n      ExprList *pOrderBy = pSelect->pOrderBy;\n      for(i=0; i<pOrderBy->nExpr; i++){\n        pOrderBy->a[i].u.x.iOrderByCol = 0;\n      }\n    }\n\n#if 0\n    printf(\"For indexing, change the IN expr:\\n\");\n    sqlite3TreeViewExpr(0, pX, 0);\n    printf(\"Into:\\n\");\n    sqlite3TreeViewExpr(0, pNew, 0);\n#endif\n  }\n  return pNew;\n}\n\n\n/*\n** Generate code for a single equality term of the WHERE clause.  An equality\n** term can be either X=expr or X IN (...).   pTerm is the term to be \n** coded.\n**\n** The current value for the constraint is left in a register, the index\n** of which is returned.  An attempt is made store the result in iTarget but\n** this is only guaranteed for TK_ISNULL and TK_IN constraints.  If the\n** constraint is a TK_EQ or TK_IS, then the current value might be left in\n** some other register and it is the caller's responsibility to compensate.\n**\n** For a constraint of the form X=expr, the expression is evaluated in\n** straight-line code.  For constraints of the form X IN (...)\n** this routine sets up a loop that will iterate over all values of X.\n*/\nstatic int codeEqualityTerm(\n  Parse *pParse,      /* The parsing context */\n  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */\n  WhereLevel *pLevel, /* The level of the FROM clause we are working on */\n  int iEq,            /* Index of the equality term within this level */\n  int bRev,           /* True for reverse-order IN operations */\n  int iTarget         /* Attempt to leave results in this register */\n){\n  Expr *pX = pTerm->pExpr;\n  Vdbe *v = pParse->pVdbe;\n  int iReg;                  /* Register holding results */\n\n  assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );\n  assert( iTarget>0 );\n  if( pX->op==TK_EQ || pX->op==TK_IS ){\n    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);\n  }else if( pX->op==TK_ISNULL ){\n    iReg = iTarget;\n    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);\n#ifndef SQLITE_OMIT_SUBQUERY\n  }else{\n    int eType = IN_INDEX_NOOP;\n    int iTab;\n    struct InLoop *pIn;\n    WhereLoop *pLoop = pLevel->pWLoop;\n    int i;\n    int nEq = 0;\n    int *aiMap = 0;\n\n    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0\n      && pLoop->u.btree.pIndex!=0\n      && pLoop->u.btree.pIndex->aSortOrder[iEq]\n    ){\n      testcase( iEq==0 );\n      testcase( bRev );\n      bRev = !bRev;\n    }\n    assert( pX->op==TK_IN );\n    iReg = iTarget;\n\n    for(i=0; i<iEq; i++){\n      if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){\n        disableTerm(pLevel, pTerm);\n        return iTarget;\n      }\n    }\n    for(i=iEq;i<pLoop->nLTerm; i++){\n      assert( pLoop->aLTerm[i]!=0 );\n      if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;\n    }\n\n    iTab = 0;\n    if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){\n      eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab);\n    }else{\n      sqlite3 *db = pParse->db;\n      pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);\n\n      if( !db->mallocFailed ){\n        aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq);\n        eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab);\n        pTerm->pExpr->iTable = iTab;\n      }\n      sqlite3ExprDelete(db, pX);\n      pX = pTerm->pExpr;\n    }\n\n    if( eType==IN_INDEX_INDEX_DESC ){\n      testcase( bRev );\n      bRev = !bRev;\n    }\n    sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);\n    VdbeCoverageIf(v, bRev);\n    VdbeCoverageIf(v, !bRev);\n    assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );\n\n    pLoop->wsFlags |= WHERE_IN_ABLE;\n    if( pLevel->u.in.nIn==0 ){\n      pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);\n    }\n\n    i = pLevel->u.in.nIn;\n    pLevel->u.in.nIn += nEq;\n    pLevel->u.in.aInLoop =\n       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,\n                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);\n    pIn = pLevel->u.in.aInLoop;\n    if( pIn ){\n      int iMap = 0;               /* Index in aiMap[] */\n      pIn += i;\n      for(i=iEq;i<pLoop->nLTerm; i++){\n        if( pLoop->aLTerm[i]->pExpr==pX ){\n          int iOut = iReg + i - iEq;\n          if( eType==IN_INDEX_ROWID ){\n            pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);\n          }else{\n            int iCol = aiMap ? aiMap[iMap++] : 0;\n            pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);\n          }\n          sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);\n          if( i==iEq ){\n            pIn->iCur = iTab;\n            pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;\n            if( iEq>0 ){\n              pIn->iBase = iReg - i;\n              pIn->nPrefix = i;\n              pLoop->wsFlags |= WHERE_IN_EARLYOUT;\n            }else{\n              pIn->nPrefix = 0;\n            }\n          }else{\n            pIn->eEndLoopOp = OP_Noop;\n          }\n          pIn++;\n        }\n      }\n    }else{\n      pLevel->u.in.nIn = 0;\n    }\n    sqlite3DbFree(pParse->db, aiMap);\n#endif\n  }\n  disableTerm(pLevel, pTerm);\n  return iReg;\n}\n\n/*\n** Generate code that will evaluate all == and IN constraints for an\n** index scan.\n**\n** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).\n** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10\n** The index has as many as three equality constraints, but in this\n** example, the third \"c\" value is an inequality.  So only two \n** constraints are coded.  This routine will generate code to evaluate\n** a==5 and b IN (1,2,3).  The current values for a and b will be stored\n** in consecutive registers and the index of the first register is returned.\n**\n** In the example above nEq==2.  But this subroutine works for any value\n** of nEq including 0.  If nEq==0, this routine is nearly a no-op.\n** The only thing it does is allocate the pLevel->iMem memory cell and\n** compute the affinity string.\n**\n** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints\n** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is\n** an inequality constraint (such as the \"c>=5 AND c<10\" in the example) that\n** occurs after the nEq quality constraints.\n**\n** This routine allocates a range of nEq+nExtraReg memory cells and returns\n** the index of the first memory cell in that range. The code that\n** calls this routine will use that memory range to store keys for\n** start and termination conditions of the loop.\n** key value of the loop.  If one or more IN operators appear, then\n** this routine allocates an additional nEq memory cells for internal\n** use.\n**\n** Before returning, *pzAff is set to point to a buffer containing a\n** copy of the column affinity string of the index allocated using\n** sqlite3DbMalloc(). Except, entries in the copy of the string associated\n** with equality constraints that use BLOB or NONE affinity are set to\n** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:\n**\n**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);\n**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;\n**\n** In the example above, the index on t1(a) has TEXT affinity. But since\n** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,\n** no conversion should be attempted before using a t2.b value as part of\n** a key to search the index. Hence the first byte in the returned affinity\n** string in this example would be set to SQLITE_AFF_BLOB.\n*/\nstatic int codeAllEqualityTerms(\n  Parse *pParse,        /* Parsing context */\n  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */\n  int bRev,             /* Reverse the order of IN operators */\n  int nExtraReg,        /* Number of extra registers to allocate */\n  char **pzAff          /* OUT: Set to point to affinity string */\n){\n  u16 nEq;                      /* The number of == or IN constraints to code */\n  u16 nSkip;                    /* Number of left-most columns to skip */\n  Vdbe *v = pParse->pVdbe;      /* The vm under construction */\n  Index *pIdx;                  /* The index being used for this loop */\n  WhereTerm *pTerm;             /* A single constraint term */\n  WhereLoop *pLoop;             /* The WhereLoop object */\n  int j;                        /* Loop counter */\n  int regBase;                  /* Base register */\n  int nReg;                     /* Number of registers to allocate */\n  char *zAff;                   /* Affinity string to return */\n\n  /* This module is only called on query plans that use an index. */\n  pLoop = pLevel->pWLoop;\n  assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );\n  nEq = pLoop->u.btree.nEq;\n  nSkip = pLoop->nSkip;\n  pIdx = pLoop->u.btree.pIndex;\n  assert( pIdx!=0 );\n\n  /* Figure out how many memory cells we will need then allocate them.\n  */\n  regBase = pParse->nMem + 1;\n  nReg = pLoop->u.btree.nEq + nExtraReg;\n  pParse->nMem += nReg;\n\n  zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));\n  assert( zAff!=0 || pParse->db->mallocFailed );\n\n  if( nSkip ){\n    int iIdxCur = pLevel->iIdxCur;\n    sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);\n    VdbeCoverageIf(v, bRev==0);\n    VdbeCoverageIf(v, bRev!=0);\n    VdbeComment((v, \"begin skip-scan on %s\", pIdx->zName));\n    j = sqlite3VdbeAddOp0(v, OP_Goto);\n    pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),\n                            iIdxCur, 0, regBase, nSkip);\n    VdbeCoverageIf(v, bRev==0);\n    VdbeCoverageIf(v, bRev!=0);\n    sqlite3VdbeJumpHere(v, j);\n    for(j=0; j<nSkip; j++){\n      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);\n      testcase( pIdx->aiColumn[j]==XN_EXPR );\n      VdbeComment((v, \"%s\", explainIndexColumnName(pIdx, j)));\n    }\n  }    \n\n  /* Evaluate the equality constraints\n  */\n  assert( zAff==0 || (int)strlen(zAff)>=nEq );\n  for(j=nSkip; j<nEq; j++){\n    int r1;\n    pTerm = pLoop->aLTerm[j];\n    assert( pTerm!=0 );\n    /* The following testcase is true for indices with redundant columns. \n    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */\n    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );\n    testcase( pTerm->wtFlags & TERM_VIRTUAL );\n    r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);\n    if( r1!=regBase+j ){\n      if( nReg==1 ){\n        sqlite3ReleaseTempReg(pParse, regBase);\n        regBase = r1;\n      }else{\n        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);\n      }\n    }\n    if( pTerm->eOperator & WO_IN ){\n      if( pTerm->pExpr->flags & EP_xIsSelect ){\n        /* No affinity ever needs to be (or should be) applied to a value\n        ** from the RHS of an \"? IN (SELECT ...)\" expression. The \n        ** sqlite3FindInIndex() routine has already ensured that the \n        ** affinity of the comparison has been applied to the value.  */\n        if( zAff ) zAff[j] = SQLITE_AFF_BLOB;\n      }\n    }else if( (pTerm->eOperator & WO_ISNULL)==0 ){\n      Expr *pRight = pTerm->pExpr->pRight;\n      if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){\n        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);\n        VdbeCoverage(v);\n      }\n      if( zAff ){\n        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){\n          zAff[j] = SQLITE_AFF_BLOB;\n        }\n        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){\n          zAff[j] = SQLITE_AFF_BLOB;\n        }\n      }\n    }\n  }\n  *pzAff = zAff;\n  return regBase;\n}\n\n#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS\n/*\n** If the most recently coded instruction is a constant range constraint\n** (a string literal) that originated from the LIKE optimization, then \n** set P3 and P5 on the OP_String opcode so that the string will be cast\n** to a BLOB at appropriate times.\n**\n** The LIKE optimization trys to evaluate \"x LIKE 'abc%'\" as a range\n** expression: \"x>='ABC' AND x<'abd'\".  But this requires that the range\n** scan loop run twice, once for strings and a second time for BLOBs.\n** The OP_String opcodes on the second pass convert the upper and lower\n** bound string constants to blobs.  This routine makes the necessary changes\n** to the OP_String opcodes for that to happen.\n**\n** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then\n** only the one pass through the string space is required, so this routine\n** becomes a no-op.\n*/\nstatic void whereLikeOptimizationStringFixup(\n  Vdbe *v,                /* prepared statement under construction */\n  WhereLevel *pLevel,     /* The loop that contains the LIKE operator */\n  WhereTerm *pTerm        /* The upper or lower bound just coded */\n){\n  if( pTerm->wtFlags & TERM_LIKEOPT ){\n    VdbeOp *pOp;\n    assert( pLevel->iLikeRepCntr>0 );\n    pOp = sqlite3VdbeGetOp(v, -1);\n    assert( pOp!=0 );\n    assert( pOp->opcode==OP_String8 \n            || pTerm->pWC->pWInfo->pParse->db->mallocFailed );\n    pOp->p3 = (int)(pLevel->iLikeRepCntr>>1);  /* Register holding counter */\n    pOp->p5 = (u8)(pLevel->iLikeRepCntr&1);    /* ASC or DESC */\n  }\n}\n#else\n# define whereLikeOptimizationStringFixup(A,B,C)\n#endif\n\n#ifdef SQLITE_ENABLE_CURSOR_HINTS\n/*\n** Information is passed from codeCursorHint() down to individual nodes of\n** the expression tree (by sqlite3WalkExpr()) using an instance of this\n** structure.\n*/\nstruct CCurHint {\n  int iTabCur;    /* Cursor for the main table */\n  int iIdxCur;    /* Cursor for the index, if pIdx!=0.  Unused otherwise */\n  Index *pIdx;    /* The index used to access the table */\n};\n\n/*\n** This function is called for every node of an expression that is a candidate\n** for a cursor hint on an index cursor.  For TK_COLUMN nodes that reference\n** the table CCurHint.iTabCur, verify that the same column can be\n** accessed through the index.  If it cannot, then set pWalker->eCode to 1.\n*/\nstatic int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){\n  struct CCurHint *pHint = pWalker->u.pCCurHint;\n  assert( pHint->pIdx!=0 );\n  if( pExpr->op==TK_COLUMN\n   && pExpr->iTable==pHint->iTabCur\n   && sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn)<0\n  ){\n    pWalker->eCode = 1;\n  }\n  return WRC_Continue;\n}\n\n/*\n** Test whether or not expression pExpr, which was part of a WHERE clause,\n** should be included in the cursor-hint for a table that is on the rhs\n** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the \n** expression is not suitable.\n**\n** An expression is unsuitable if it might evaluate to non NULL even if\n** a TK_COLUMN node that does affect the value of the expression is set\n** to NULL. For example:\n**\n**   col IS NULL\n**   col IS NOT NULL\n**   coalesce(col, 1)\n**   CASE WHEN col THEN 0 ELSE 1 END\n*/\nstatic int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){\n  if( pExpr->op==TK_IS \n   || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT \n   || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE \n  ){\n    pWalker->eCode = 1;\n  }else if( pExpr->op==TK_FUNCTION ){\n    int d1;\n    char d2[4];\n    if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){\n      pWalker->eCode = 1;\n    }\n  }\n\n  return WRC_Continue;\n}\n\n\n/*\n** This function is called on every node of an expression tree used as an\n** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN\n** that accesses any table other than the one identified by\n** CCurHint.iTabCur, then do the following:\n**\n**   1) allocate a register and code an OP_Column instruction to read \n**      the specified column into the new register, and\n**\n**   2) transform the expression node to a TK_REGISTER node that reads \n**      from the newly populated register.\n**\n** Also, if the node is a TK_COLUMN that does access the table idenified\n** by pCCurHint.iTabCur, and an index is being used (which we will\n** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into\n** an access of the index rather than the original table.\n*/\nstatic int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){\n  int rc = WRC_Continue;\n  struct CCurHint *pHint = pWalker->u.pCCurHint;\n  if( pExpr->op==TK_COLUMN ){\n    if( pExpr->iTable!=pHint->iTabCur ){\n      int reg = ++pWalker->pParse->nMem;   /* Register for column value */\n      sqlite3ExprCode(pWalker->pParse, pExpr, reg);\n      pExpr->op = TK_REGISTER;\n      pExpr->iTable = reg;\n    }else if( pHint->pIdx!=0 ){\n      pExpr->iTable = pHint->iIdxCur;\n      pExpr->iColumn = sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn);\n      assert( pExpr->iColumn>=0 );\n    }\n  }else if( pExpr->op==TK_AGG_FUNCTION ){\n    /* An aggregate function in the WHERE clause of a query means this must\n    ** be a correlated sub-query, and expression pExpr is an aggregate from\n    ** the parent context. Do not walk the function arguments in this case.\n    **\n    ** todo: It should be possible to replace this node with a TK_REGISTER\n    ** expression, as the result of the expression must be stored in a \n    ** register at this point. The same holds for TK_AGG_COLUMN nodes. */\n    rc = WRC_Prune;\n  }\n  return rc;\n}\n\n/*\n** Insert an OP_CursorHint instruction if it is appropriate to do so.\n*/\nstatic void codeCursorHint(\n  struct SrcList_item *pTabItem,  /* FROM clause item */\n  WhereInfo *pWInfo,    /* The where clause */\n  WhereLevel *pLevel,   /* Which loop to provide hints for */\n  WhereTerm *pEndRange  /* Hint this end-of-scan boundary term if not NULL */\n){\n  Parse *pParse = pWInfo->pParse;\n  sqlite3 *db = pParse->db;\n  Vdbe *v = pParse->pVdbe;\n  Expr *pExpr = 0;\n  WhereLoop *pLoop = pLevel->pWLoop;\n  int iCur;\n  WhereClause *pWC;\n  WhereTerm *pTerm;\n  int i, j;\n  struct CCurHint sHint;\n  Walker sWalker;\n\n  if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;\n  iCur = pLevel->iTabCur;\n  assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );\n  sHint.iTabCur = iCur;\n  sHint.iIdxCur = pLevel->iIdxCur;\n  sHint.pIdx = pLoop->u.btree.pIndex;\n  memset(&sWalker, 0, sizeof(sWalker));\n  sWalker.pParse = pParse;\n  sWalker.u.pCCurHint = &sHint;\n  pWC = &pWInfo->sWC;\n  for(i=0; i<pWC->nTerm; i++){\n    pTerm = &pWC->a[i];\n    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;\n    if( pTerm->prereqAll & pLevel->notReady ) continue;\n\n    /* Any terms specified as part of the ON(...) clause for any LEFT \n    ** JOIN for which the current table is not the rhs are omitted\n    ** from the cursor-hint. \n    **\n    ** If this table is the rhs of a LEFT JOIN, \"IS\" or \"IS NULL\" terms \n    ** that were specified as part of the WHERE clause must be excluded.\n    ** This is to address the following:\n    **\n    **   SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;\n    **\n    ** Say there is a single row in t2 that matches (t1.a=t2.b), but its\n    ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is \n    ** pushed down to the cursor, this row is filtered out, causing\n    ** SQLite to synthesize a row of NULL values. Which does match the\n    ** WHERE clause, and so the query returns a row. Which is incorrect.\n    **\n    ** For the same reason, WHERE terms such as:\n    **\n    **   WHERE 1 = (t2.c IS NULL)\n    **\n    ** are also excluded. See codeCursorHintIsOrFunction() for details.\n    */\n    if( pTabItem->fg.jointype & JT_LEFT ){\n      Expr *pExpr = pTerm->pExpr;\n      if( !ExprHasProperty(pExpr, EP_FromJoin) \n       || pExpr->iRightJoinTable!=pTabItem->iCursor\n      ){\n        sWalker.eCode = 0;\n        sWalker.xExprCallback = codeCursorHintIsOrFunction;\n        sqlite3WalkExpr(&sWalker, pTerm->pExpr);\n        if( sWalker.eCode ) continue;\n      }\n    }else{\n      if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;\n    }\n\n    /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize\n    ** the cursor.  These terms are not needed as hints for a pure range\n    ** scan (that has no == terms) so omit them. */\n    if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){\n      for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}\n      if( j<pLoop->nLTerm ) continue;\n    }\n\n    /* No subqueries or non-deterministic functions allowed */\n    if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;\n\n    /* For an index scan, make sure referenced columns are actually in\n    ** the index. */\n    if( sHint.pIdx!=0 ){\n      sWalker.eCode = 0;\n      sWalker.xExprCallback = codeCursorHintCheckExpr;\n      sqlite3WalkExpr(&sWalker, pTerm->pExpr);\n      if( sWalker.eCode ) continue;\n    }\n\n    /* If we survive all prior tests, that means this term is worth hinting */\n    pExpr = sqlite3ExprAnd(pParse, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));\n  }\n  if( pExpr!=0 ){\n    sWalker.xExprCallback = codeCursorHintFixExpr;\n    sqlite3WalkExpr(&sWalker, pExpr);\n    sqlite3VdbeAddOp4(v, OP_CursorHint, \n                      (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,\n                      (const char*)pExpr, P4_EXPR);\n  }\n}\n#else\n# define codeCursorHint(A,B,C,D)  /* No-op */\n#endif /* SQLITE_ENABLE_CURSOR_HINTS */\n\n/*\n** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains\n** a rowid value just read from cursor iIdxCur, open on index pIdx. This\n** function generates code to do a deferred seek of cursor iCur to the \n** rowid stored in register iRowid.\n**\n** Normally, this is just:\n**\n**   OP_DeferredSeek $iCur $iRowid\n**\n** However, if the scan currently being coded is a branch of an OR-loop and\n** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek\n** is set to iIdxCur and P4 is set to point to an array of integers\n** containing one entry for each column of the table cursor iCur is open \n** on. For each table column, if the column is the i'th column of the \n** index, then the corresponding array entry is set to (i+1). If the column\n** does not appear in the index at all, the array entry is set to 0.\n*/\nstatic void codeDeferredSeek(\n  WhereInfo *pWInfo,              /* Where clause context */\n  Index *pIdx,                    /* Index scan is using */\n  int iCur,                       /* Cursor for IPK b-tree */\n  int iIdxCur                     /* Index cursor */\n){\n  Parse *pParse = pWInfo->pParse; /* Parse context */\n  Vdbe *v = pParse->pVdbe;        /* Vdbe to generate code within */\n\n  assert( iIdxCur>0 );\n  assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );\n  \n  pWInfo->bDeferredSeek = 1;\n  sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);\n  if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)\n   && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)\n  ){\n    int i;\n    Table *pTab = pIdx->pTable;\n    int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));\n    if( ai ){\n      ai[0] = pTab->nCol;\n      for(i=0; i<pIdx->nColumn-1; i++){\n        int x1, x2;\n        assert( pIdx->aiColumn[i]<pTab->nCol );\n        x1 = pIdx->aiColumn[i];\n        x2 = sqlite3TableColumnToStorage(pTab, x1);\n        testcase( x1!=x2 );\n        if( x1>=0 ) ai[x2+1] = i+1;\n      }\n      sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);\n    }\n  }\n}\n\n/*\n** If the expression passed as the second argument is a vector, generate\n** code to write the first nReg elements of the vector into an array\n** of registers starting with iReg.\n**\n** If the expression is not a vector, then nReg must be passed 1. In\n** this case, generate code to evaluate the expression and leave the\n** result in register iReg.\n*/\nstatic void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){\n  assert( nReg>0 );\n  if( p && sqlite3ExprIsVector(p) ){\n#ifndef SQLITE_OMIT_SUBQUERY\n    if( (p->flags & EP_xIsSelect) ){\n      Vdbe *v = pParse->pVdbe;\n      int iSelect;\n      assert( p->op==TK_SELECT );\n      iSelect = sqlite3CodeSubselect(pParse, p);\n      sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);\n    }else\n#endif\n    {\n      int i;\n      ExprList *pList = p->x.pList;\n      assert( nReg<=pList->nExpr );\n      for(i=0; i<nReg; i++){\n        sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);\n      }\n    }\n  }else{\n    assert( nReg==1 );\n    sqlite3ExprCode(pParse, p, iReg);\n  }\n}\n\n/* An instance of the IdxExprTrans object carries information about a\n** mapping from an expression on table columns into a column in an index\n** down through the Walker.\n*/\ntypedef struct IdxExprTrans {\n  Expr *pIdxExpr;    /* The index expression */\n  int iTabCur;       /* The cursor of the corresponding table */\n  int iIdxCur;       /* The cursor for the index */\n  int iIdxCol;       /* The column for the index */\n  int iTabCol;       /* The column for the table */\n  WhereInfo *pWInfo; /* Complete WHERE clause information */\n  sqlite3 *db;       /* Database connection (for malloc()) */\n} IdxExprTrans;\n\n/*\n** Preserve pExpr on the WhereETrans list of the WhereInfo.\n*/\nstatic void preserveExpr(IdxExprTrans *pTrans, Expr *pExpr){\n  WhereExprMod *pNew;\n  pNew = sqlite3DbMallocRaw(pTrans->db, sizeof(*pNew));\n  if( pNew==0 ) return;\n  pNew->pNext = pTrans->pWInfo->pExprMods;\n  pTrans->pWInfo->pExprMods = pNew;\n  pNew->pExpr = pExpr;\n  memcpy(&pNew->orig, pExpr, sizeof(*pExpr));\n}\n\n/* The walker node callback used to transform matching expressions into\n** a reference to an index column for an index on an expression.\n**\n** If pExpr matches, then transform it into a reference to the index column\n** that contains the value of pExpr.\n*/\nstatic int whereIndexExprTransNode(Walker *p, Expr *pExpr){\n  IdxExprTrans *pX = p->u.pIdxTrans;\n  if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){\n    preserveExpr(pX, pExpr);\n    pExpr->affExpr = sqlite3ExprAffinity(pExpr);\n    pExpr->op = TK_COLUMN;\n    pExpr->iTable = pX->iIdxCur;\n    pExpr->iColumn = pX->iIdxCol;\n    pExpr->y.pTab = 0;\n    testcase( ExprHasProperty(pExpr, EP_Skip) );\n    testcase( ExprHasProperty(pExpr, EP_Unlikely) );\n    ExprClearProperty(pExpr, EP_Skip|EP_Unlikely);\n    return WRC_Prune;\n  }else{\n    return WRC_Continue;\n  }\n}\n\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n/* A walker node callback that translates a column reference to a table\n** into a corresponding column reference of an index.\n*/\nstatic int whereIndexExprTransColumn(Walker *p, Expr *pExpr){\n  if( pExpr->op==TK_COLUMN ){\n    IdxExprTrans *pX = p->u.pIdxTrans;\n    if( pExpr->iTable==pX->iTabCur && pExpr->iColumn==pX->iTabCol ){\n      assert( pExpr->y.pTab!=0 );\n      preserveExpr(pX, pExpr);\n      pExpr->affExpr = sqlite3TableColumnAffinity(pExpr->y.pTab,pExpr->iColumn);\n      pExpr->iTable = pX->iIdxCur;\n      pExpr->iColumn = pX->iIdxCol;\n      pExpr->y.pTab = 0;\n    }\n  }\n  return WRC_Continue;\n}\n#endif /* SQLITE_OMIT_GENERATED_COLUMNS */\n\n/*\n** For an indexes on expression X, locate every instance of expression X\n** in pExpr and change that subexpression into a reference to the appropriate\n** column of the index.\n**\n** 2019-10-24: Updated to also translate references to a VIRTUAL column in\n** the table into references to the corresponding (stored) column of the\n** index.\n*/\nstatic void whereIndexExprTrans(\n  Index *pIdx,      /* The Index */\n  int iTabCur,      /* Cursor of the table that is being indexed */\n  int iIdxCur,      /* Cursor of the index itself */\n  WhereInfo *pWInfo /* Transform expressions in this WHERE clause */\n){\n  int iIdxCol;               /* Column number of the index */\n  ExprList *aColExpr;        /* Expressions that are indexed */\n  Table *pTab;\n  Walker w;\n  IdxExprTrans x;\n  aColExpr = pIdx->aColExpr;\n  if( aColExpr==0 && !pIdx->bHasVCol ){\n    /* The index does not reference any expressions or virtual columns\n    ** so no translations are needed. */\n    return;\n  }\n  pTab = pIdx->pTable;\n  memset(&w, 0, sizeof(w));\n  w.u.pIdxTrans = &x;\n  x.iTabCur = iTabCur;\n  x.iIdxCur = iIdxCur;\n  x.pWInfo = pWInfo;\n  x.db = pWInfo->pParse->db;\n  for(iIdxCol=0; iIdxCol<pIdx->nColumn; iIdxCol++){\n    i16 iRef = pIdx->aiColumn[iIdxCol];\n    if( iRef==XN_EXPR ){\n      assert( aColExpr->a[iIdxCol].pExpr!=0 );\n      x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;\n      if( sqlite3ExprIsConstant(x.pIdxExpr) ) continue;\n      w.xExprCallback = whereIndexExprTransNode;\n#ifndef SQLITE_OMIT_GENERATED_COLUMNS\n    }else if( iRef>=0\n       && (pTab->aCol[iRef].colFlags & COLFLAG_VIRTUAL)!=0\n       && (pTab->aCol[iRef].zColl==0\n           || sqlite3StrICmp(pTab->aCol[iRef].zColl, sqlite3StrBINARY)==0)\n    ){\n      /* Check to see if there are direct references to generated columns\n      ** that are contained in the index.  Pulling the generated column\n      ** out of the index is an optimization only - the main table is always\n      ** available if the index cannot be used.  To avoid unnecessary\n      ** complication, omit this optimization if the collating sequence for\n      ** the column is non-standard */\n      x.iTabCol = iRef;\n      w.xExprCallback = whereIndexExprTransColumn;\n#endif /* SQLITE_OMIT_GENERATED_COLUMNS */\n    }else{\n      continue;\n    }\n    x.iIdxCol = iIdxCol;\n    sqlite3WalkExpr(&w, pWInfo->pWhere);\n    sqlite3WalkExprList(&w, pWInfo->pOrderBy);\n    sqlite3WalkExprList(&w, pWInfo->pResultSet);\n  }\n}\n\n/*\n** The pTruth expression is always true because it is the WHERE clause\n** a partial index that is driving a query loop.  Look through all of the\n** WHERE clause terms on the query, and if any of those terms must be\n** true because pTruth is true, then mark those WHERE clause terms as\n** coded.\n*/\nstatic void whereApplyPartialIndexConstraints(\n  Expr *pTruth,\n  int iTabCur,\n  WhereClause *pWC\n){\n  int i;\n  WhereTerm *pTerm;\n  while( pTruth->op==TK_AND ){\n    whereApplyPartialIndexConstraints(pTruth->pLeft, iTabCur, pWC);\n    pTruth = pTruth->pRight;\n  }\n  for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){\n    Expr *pExpr;\n    if( pTerm->wtFlags & TERM_CODED ) continue;\n    pExpr = pTerm->pExpr;\n    if( sqlite3ExprCompare(0, pExpr, pTruth, iTabCur)==0 ){\n      pTerm->wtFlags |= TERM_CODED;\n    }\n  }\n}\n\n/*\n** Generate code for the start of the iLevel-th loop in the WHERE clause\n** implementation described by pWInfo.\n*/\nSQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(\n  Parse *pParse,       /* Parsing context */\n  Vdbe *v,             /* Prepared statement under construction */\n  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */\n  int iLevel,          /* Which level of pWInfo->a[] should be coded */\n  WhereLevel *pLevel,  /* The current level pointer */\n  Bitmask notReady     /* Which tables are currently available */\n){\n  int j, k;            /* Loop counters */\n  int iCur;            /* The VDBE cursor for the table */\n  int addrNxt;         /* Where to jump to continue with the next IN case */\n  int bRev;            /* True if we need to scan in reverse order */\n  WhereLoop *pLoop;    /* The WhereLoop object being coded */\n  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */\n  WhereTerm *pTerm;               /* A WHERE clause term */\n  sqlite3 *db;                    /* Database connection */\n  struct SrcList_item *pTabItem;  /* FROM clause term being coded */\n  int addrBrk;                    /* Jump here to break out of the loop */\n  int addrHalt;                   /* addrBrk for the outermost loop */\n  int addrCont;                   /* Jump here to continue with next cycle */\n  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */\n  int iReleaseReg = 0;      /* Temp register to free before returning */\n  Index *pIdx = 0;          /* Index used by loop (if any) */\n  int iLoop;                /* Iteration of constraint generator loop */\n\n  pWC = &pWInfo->sWC;\n  db = pParse->db;\n  pLoop = pLevel->pWLoop;\n  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];\n  iCur = pTabItem->iCursor;\n  pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);\n  bRev = (pWInfo->revMask>>iLevel)&1;\n  VdbeModuleComment((v, \"Begin WHERE-loop%d: %s\",iLevel,pTabItem->pTab->zName));\n#if WHERETRACE_ENABLED /* 0x20800 */\n  if( sqlite3WhereTrace & 0x800 ){\n    sqlite3DebugPrintf(\"Coding level %d of %d:  notReady=%llx  iFrom=%d\\n\",\n       iLevel, pWInfo->nLevel, (u64)notReady, pLevel->iFrom);\n    sqlite3WhereLoopPrint(pLoop, pWC);\n  }\n  if( sqlite3WhereTrace & 0x20000 ){\n    if( iLevel==0 ){\n      sqlite3DebugPrintf(\"WHERE clause being coded:\\n\");\n      sqlite3TreeViewExpr(0, pWInfo->pWhere, 0);\n    }\n    sqlite3DebugPrintf(\"All WHERE-clause terms before coding:\\n\");\n    sqlite3WhereClausePrint(pWC);\n  }\n#endif\n\n  /* Create labels for the \"break\" and \"continue\" instructions\n  ** for the current loop.  Jump to addrBrk to break out of a loop.\n  ** Jump to cont to go immediately to the next iteration of the\n  ** loop.\n  **\n  ** When there is an IN operator, we also have a \"addrNxt\" label that\n  ** means to continue with the next IN value combination.  When\n  ** there are no IN operators in the constraints, the \"addrNxt\" label\n  ** is the same as \"addrBrk\".\n  */\n  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);\n  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse);\n\n  /* If this is the right table of a LEFT OUTER JOIN, allocate and\n  ** initialize a memory cell that records if this table matches any\n  ** row of the left table of the join.\n  */\n  assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)\n       || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0\n  );\n  if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){\n    pLevel->iLeftJoin = ++pParse->nMem;\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);\n    VdbeComment((v, \"init LEFT JOIN no-match flag\"));\n  }\n\n  /* Compute a safe address to jump to if we discover that the table for\n  ** this loop is empty and can never contribute content. */\n  for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}\n  addrHalt = pWInfo->a[j].addrBrk;\n\n  /* Special case of a FROM clause subquery implemented as a co-routine */\n  if( pTabItem->fg.viaCoroutine ){\n    int regYield = pTabItem->regReturn;\n    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);\n    pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);\n    VdbeCoverage(v);\n    VdbeComment((v, \"next row of %s\", pTabItem->pTab->zName));\n    pLevel->op = OP_Goto;\n  }else\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){\n    /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext\n    **          to access the data.\n    */\n    int iReg;   /* P3 Value for OP_VFilter */\n    int addrNotFound;\n    int nConstraint = pLoop->nLTerm;\n    int iIn;    /* Counter for IN constraints */\n\n    iReg = sqlite3GetTempRange(pParse, nConstraint+2);\n    addrNotFound = pLevel->addrBrk;\n    for(j=0; j<nConstraint; j++){\n      int iTarget = iReg+j+2;\n      pTerm = pLoop->aLTerm[j];\n      if( NEVER(pTerm==0) ) continue;\n      if( pTerm->eOperator & WO_IN ){\n        codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);\n        addrNotFound = pLevel->addrNxt;\n      }else{\n        Expr *pRight = pTerm->pExpr->pRight;\n        codeExprOrVector(pParse, pRight, iTarget, 1);\n      }\n    }\n    sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);\n    sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);\n    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,\n                      pLoop->u.vtab.idxStr,\n                      pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);\n    VdbeCoverage(v);\n    pLoop->u.vtab.needFree = 0;\n    pLevel->p1 = iCur;\n    pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;\n    pLevel->p2 = sqlite3VdbeCurrentAddr(v);\n    iIn = pLevel->u.in.nIn;\n    for(j=nConstraint-1; j>=0; j--){\n      pTerm = pLoop->aLTerm[j];\n      if( (pTerm->eOperator & WO_IN)!=0 ) iIn--;\n      if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){\n        disableTerm(pLevel, pTerm);\n      }else if( (pTerm->eOperator & WO_IN)!=0\n        && sqlite3ExprVectorSize(pTerm->pExpr->pLeft)==1\n      ){\n        Expr *pCompare;  /* The comparison operator */\n        Expr *pRight;    /* RHS of the comparison */\n        VdbeOp *pOp;     /* Opcode to access the value of the IN constraint */\n\n        /* Reload the constraint value into reg[iReg+j+2].  The same value\n        ** was loaded into the same register prior to the OP_VFilter, but\n        ** the xFilter implementation might have changed the datatype or\n        ** encoding of the value in the register, so it *must* be reloaded. */\n        assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );\n        if( !db->mallocFailed ){\n          assert( iIn>=0 && iIn<pLevel->u.in.nIn );\n          pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[iIn].addrInTop);\n          assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );\n          assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );\n          assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );\n          testcase( pOp->opcode==OP_Rowid );\n          sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);\n        }\n\n        /* Generate code that will continue to the next row if \n        ** the IN constraint is not satisfied */\n        pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);\n        assert( pCompare!=0 || db->mallocFailed );\n        if( pCompare ){\n          pCompare->pLeft = pTerm->pExpr->pLeft;\n          pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);\n          if( pRight ){\n            pRight->iTable = iReg+j+2;\n            sqlite3ExprIfFalse(\n                pParse, pCompare, pLevel->addrCont, SQLITE_JUMPIFNULL\n            );\n          }\n          pCompare->pLeft = 0;\n          sqlite3ExprDelete(db, pCompare);\n        }\n      }\n    }\n    assert( iIn==0 || db->mallocFailed );\n    /* These registers need to be preserved in case there is an IN operator\n    ** loop.  So we could deallocate the registers here (and potentially\n    ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0.  But it seems\n    ** simpler and safer to simply not reuse the registers.\n    **\n    **    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);\n    */\n  }else\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n  if( (pLoop->wsFlags & WHERE_IPK)!=0\n   && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0\n  ){\n    /* Case 2:  We can directly reference a single row using an\n    **          equality comparison against the ROWID field.  Or\n    **          we reference multiple rows using a \"rowid IN (...)\"\n    **          construct.\n    */\n    assert( pLoop->u.btree.nEq==1 );\n    pTerm = pLoop->aLTerm[0];\n    assert( pTerm!=0 );\n    assert( pTerm->pExpr!=0 );\n    testcase( pTerm->wtFlags & TERM_VIRTUAL );\n    iReleaseReg = ++pParse->nMem;\n    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);\n    if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);\n    addrNxt = pLevel->addrNxt;\n    sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);\n    VdbeCoverage(v);\n    pLevel->op = OP_Noop;\n    if( (pTerm->prereqAll & pLevel->notReady)==0 ){\n      pTerm->wtFlags |= TERM_CODED;\n    }\n  }else if( (pLoop->wsFlags & WHERE_IPK)!=0\n         && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0\n  ){\n    /* Case 3:  We have an inequality comparison against the ROWID field.\n    */\n    int testOp = OP_Noop;\n    int start;\n    int memEndValue = 0;\n    WhereTerm *pStart, *pEnd;\n\n    j = 0;\n    pStart = pEnd = 0;\n    if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];\n    if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];\n    assert( pStart!=0 || pEnd!=0 );\n    if( bRev ){\n      pTerm = pStart;\n      pStart = pEnd;\n      pEnd = pTerm;\n    }\n    codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);\n    if( pStart ){\n      Expr *pX;             /* The expression that defines the start bound */\n      int r1, rTemp;        /* Registers for holding the start boundary */\n      int op;               /* Cursor seek operation */\n\n      /* The following constant maps TK_xx codes into corresponding \n      ** seek opcodes.  It depends on a particular ordering of TK_xx\n      */\n      const u8 aMoveOp[] = {\n           /* TK_GT */  OP_SeekGT,\n           /* TK_LE */  OP_SeekLE,\n           /* TK_LT */  OP_SeekLT,\n           /* TK_GE */  OP_SeekGE\n      };\n      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */\n      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */\n      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */\n\n      assert( (pStart->wtFlags & TERM_VNULL)==0 );\n      testcase( pStart->wtFlags & TERM_VIRTUAL );\n      pX = pStart->pExpr;\n      assert( pX!=0 );\n      testcase( pStart->leftCursor!=iCur ); /* transitive constraints */\n      if( sqlite3ExprIsVector(pX->pRight) ){\n        r1 = rTemp = sqlite3GetTempReg(pParse);\n        codeExprOrVector(pParse, pX->pRight, r1, 1);\n        testcase( pX->op==TK_GT );\n        testcase( pX->op==TK_GE );\n        testcase( pX->op==TK_LT );\n        testcase( pX->op==TK_LE );\n        op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1];\n        assert( pX->op!=TK_GT || op==OP_SeekGE );\n        assert( pX->op!=TK_GE || op==OP_SeekGE );\n        assert( pX->op!=TK_LT || op==OP_SeekLE );\n        assert( pX->op!=TK_LE || op==OP_SeekLE );\n      }else{\n        r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);\n        disableTerm(pLevel, pStart);\n        op = aMoveOp[(pX->op - TK_GT)];\n      }\n      sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);\n      VdbeComment((v, \"pk\"));\n      VdbeCoverageIf(v, pX->op==TK_GT);\n      VdbeCoverageIf(v, pX->op==TK_LE);\n      VdbeCoverageIf(v, pX->op==TK_LT);\n      VdbeCoverageIf(v, pX->op==TK_GE);\n      sqlite3ReleaseTempReg(pParse, rTemp);\n    }else{\n      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);\n      VdbeCoverageIf(v, bRev==0);\n      VdbeCoverageIf(v, bRev!=0);\n    }\n    if( pEnd ){\n      Expr *pX;\n      pX = pEnd->pExpr;\n      assert( pX!=0 );\n      assert( (pEnd->wtFlags & TERM_VNULL)==0 );\n      testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */\n      testcase( pEnd->wtFlags & TERM_VIRTUAL );\n      memEndValue = ++pParse->nMem;\n      codeExprOrVector(pParse, pX->pRight, memEndValue, 1);\n      if( 0==sqlite3ExprIsVector(pX->pRight) \n       && (pX->op==TK_LT || pX->op==TK_GT) \n      ){\n        testOp = bRev ? OP_Le : OP_Ge;\n      }else{\n        testOp = bRev ? OP_Lt : OP_Gt;\n      }\n      if( 0==sqlite3ExprIsVector(pX->pRight) ){\n        disableTerm(pLevel, pEnd);\n      }\n    }\n    start = sqlite3VdbeCurrentAddr(v);\n    pLevel->op = bRev ? OP_Prev : OP_Next;\n    pLevel->p1 = iCur;\n    pLevel->p2 = start;\n    assert( pLevel->p5==0 );\n    if( testOp!=OP_Noop ){\n      iRowidReg = ++pParse->nMem;\n      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);\n      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);\n      VdbeCoverageIf(v, testOp==OP_Le);\n      VdbeCoverageIf(v, testOp==OP_Lt);\n      VdbeCoverageIf(v, testOp==OP_Ge);\n      VdbeCoverageIf(v, testOp==OP_Gt);\n      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);\n    }\n  }else if( pLoop->wsFlags & WHERE_INDEXED ){\n    /* Case 4: A scan using an index.\n    **\n    **         The WHERE clause may contain zero or more equality \n    **         terms (\"==\" or \"IN\" operators) that refer to the N\n    **         left-most columns of the index. It may also contain\n    **         inequality constraints (>, <, >= or <=) on the indexed\n    **         column that immediately follows the N equalities. Only \n    **         the right-most column can be an inequality - the rest must\n    **         use the \"==\" and \"IN\" operators. For example, if the \n    **         index is on (x,y,z), then the following clauses are all \n    **         optimized:\n    **\n    **            x=5\n    **            x=5 AND y=10\n    **            x=5 AND y<10\n    **            x=5 AND y>5 AND y<10\n    **            x=5 AND y=5 AND z<=10\n    **\n    **         The z<10 term of the following cannot be used, only\n    **         the x=5 term:\n    **\n    **            x=5 AND z<10\n    **\n    **         N may be zero if there are inequality constraints.\n    **         If there are no inequality constraints, then N is at\n    **         least one.\n    **\n    **         This case is also used when there are no WHERE clause\n    **         constraints but an index is selected anyway, in order\n    **         to force the output order to conform to an ORDER BY.\n    */  \n    static const u8 aStartOp[] = {\n      0,\n      0,\n      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */\n      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */\n      OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */\n      OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */\n      OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */\n      OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */\n    };\n    static const u8 aEndOp[] = {\n      OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */\n      OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */\n      OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */\n      OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */\n    };\n    u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */\n    u16 nBtm = pLoop->u.btree.nBtm;   /* Length of BTM vector */\n    u16 nTop = pLoop->u.btree.nTop;   /* Length of TOP vector */\n    int regBase;                 /* Base register holding constraint values */\n    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */\n    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */\n    int startEq;                 /* True if range start uses ==, >= or <= */\n    int endEq;                   /* True if range end uses ==, >= or <= */\n    int start_constraints;       /* Start of range is constrained */\n    int nConstraint;             /* Number of constraint terms */\n    int iIdxCur;                 /* The VDBE cursor for the index */\n    int nExtraReg = 0;           /* Number of extra registers needed */\n    int op;                      /* Instruction opcode */\n    char *zStartAff;             /* Affinity for start of range constraint */\n    char *zEndAff = 0;           /* Affinity for end of range constraint */\n    u8 bSeekPastNull = 0;        /* True to seek past initial nulls */\n    u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */\n    int omitTable;               /* True if we use the index only */\n    int regBignull = 0;          /* big-null flag register */\n\n    pIdx = pLoop->u.btree.pIndex;\n    iIdxCur = pLevel->iIdxCur;\n    assert( nEq>=pLoop->nSkip );\n\n    /* Find any inequality constraint terms for the start and end \n    ** of the range. \n    */\n    j = nEq;\n    if( pLoop->wsFlags & WHERE_BTM_LIMIT ){\n      pRangeStart = pLoop->aLTerm[j++];\n      nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);\n      /* Like optimization range constraints always occur in pairs */\n      assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || \n              (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );\n    }\n    if( pLoop->wsFlags & WHERE_TOP_LIMIT ){\n      pRangeEnd = pLoop->aLTerm[j++];\n      nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);\n#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS\n      if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){\n        assert( pRangeStart!=0 );                     /* LIKE opt constraints */\n        assert( pRangeStart->wtFlags & TERM_LIKEOPT );   /* occur in pairs */\n        pLevel->iLikeRepCntr = (u32)++pParse->nMem;\n        sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);\n        VdbeComment((v, \"LIKE loop counter\"));\n        pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);\n        /* iLikeRepCntr actually stores 2x the counter register number.  The\n        ** bottom bit indicates whether the search order is ASC or DESC. */\n        testcase( bRev );\n        testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );\n        assert( (bRev & ~1)==0 );\n        pLevel->iLikeRepCntr <<=1;\n        pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);\n      }\n#endif\n      if( pRangeStart==0 ){\n        j = pIdx->aiColumn[nEq];\n        if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){\n          bSeekPastNull = 1;\n        }\n      }\n    }\n    assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );\n\n    /* If the WHERE_BIGNULL_SORT flag is set, then index column nEq uses\n    ** a non-default \"big-null\" sort (either ASC NULLS LAST or DESC NULLS \n    ** FIRST). In both cases separate ordered scans are made of those\n    ** index entries for which the column is null and for those for which\n    ** it is not. For an ASC sort, the non-NULL entries are scanned first.\n    ** For DESC, NULL entries are scanned first.\n    */\n    if( (pLoop->wsFlags & (WHERE_TOP_LIMIT|WHERE_BTM_LIMIT))==0\n     && (pLoop->wsFlags & WHERE_BIGNULL_SORT)!=0\n    ){\n      assert( bSeekPastNull==0 && nExtraReg==0 && nBtm==0 && nTop==0 );\n      assert( pRangeEnd==0 && pRangeStart==0 );\n      testcase( pLoop->nSkip>0 );\n      nExtraReg = 1;\n      bSeekPastNull = 1;\n      pLevel->regBignull = regBignull = ++pParse->nMem;\n      if( pLevel->iLeftJoin ){\n        sqlite3VdbeAddOp2(v, OP_Integer, 0, regBignull);\n      }\n      pLevel->addrBignull = sqlite3VdbeMakeLabel(pParse);\n    }\n\n    /* If we are doing a reverse order scan on an ascending index, or\n    ** a forward order scan on a descending index, interchange the \n    ** start and end terms (pRangeStart and pRangeEnd).\n    */\n    if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))\n     || (bRev && pIdx->nKeyCol==nEq)\n    ){\n      SWAP(WhereTerm *, pRangeEnd, pRangeStart);\n      SWAP(u8, bSeekPastNull, bStopAtNull);\n      SWAP(u8, nBtm, nTop);\n    }\n\n    /* Generate code to evaluate all constraint terms using == or IN\n    ** and store the values of those terms in an array of registers\n    ** starting at regBase.\n    */\n    codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);\n    regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);\n    assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );\n    if( zStartAff && nTop ){\n      zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);\n    }\n    addrNxt = (regBignull ? pLevel->addrBignull : pLevel->addrNxt);\n\n    testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );\n    testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );\n    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );\n    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );\n    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);\n    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);\n    start_constraints = pRangeStart || nEq>0;\n\n    /* Seek the index cursor to the start of the range. */\n    nConstraint = nEq;\n    if( pRangeStart ){\n      Expr *pRight = pRangeStart->pExpr->pRight;\n      codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);\n      whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);\n      if( (pRangeStart->wtFlags & TERM_VNULL)==0\n       && sqlite3ExprCanBeNull(pRight)\n      ){\n        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);\n        VdbeCoverage(v);\n      }\n      if( zStartAff ){\n        updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);\n      }  \n      nConstraint += nBtm;\n      testcase( pRangeStart->wtFlags & TERM_VIRTUAL );\n      if( sqlite3ExprIsVector(pRight)==0 ){\n        disableTerm(pLevel, pRangeStart);\n      }else{\n        startEq = 1;\n      }\n      bSeekPastNull = 0;\n    }else if( bSeekPastNull ){\n      startEq = 0;\n      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);\n      start_constraints = 1;\n      nConstraint++;\n    }else if( regBignull ){\n      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);\n      start_constraints = 1;\n      nConstraint++;\n    }\n    codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);\n    if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){\n      /* The skip-scan logic inside the call to codeAllEqualityConstraints()\n      ** above has already left the cursor sitting on the correct row,\n      ** so no further seeking is needed */\n    }else{\n      if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){\n        sqlite3VdbeAddOp1(v, OP_SeekHit, iIdxCur);\n      }\n      if( regBignull ){\n        sqlite3VdbeAddOp2(v, OP_Integer, 1, regBignull);\n        VdbeComment((v, \"NULL-scan pass ctr\"));\n      }\n\n      op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];\n      assert( op!=0 );\n      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);\n      VdbeCoverage(v);\n      VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );\n      VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );\n      VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );\n      VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );\n      VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );\n      VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );\n\n      assert( bSeekPastNull==0 || bStopAtNull==0 );\n      if( regBignull ){\n        assert( bSeekPastNull==1 || bStopAtNull==1 );\n        assert( bSeekPastNull==!bStopAtNull );\n        assert( bStopAtNull==startEq );\n        sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2);\n        op = aStartOp[(nConstraint>1)*4 + 2 + bRev];\n        sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, \n                             nConstraint-startEq);\n        VdbeCoverage(v);\n        VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );\n        VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );\n        VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );\n        VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );\n        assert( op==OP_Rewind || op==OP_Last || op==OP_SeekGE || op==OP_SeekLE);\n      }\n    }\n\n    /* Load the value for the inequality constraint at the end of the\n    ** range (if any).\n    */\n    nConstraint = nEq;\n    if( pRangeEnd ){\n      Expr *pRight = pRangeEnd->pExpr->pRight;\n      codeExprOrVector(pParse, pRight, regBase+nEq, nTop);\n      whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);\n      if( (pRangeEnd->wtFlags & TERM_VNULL)==0\n       && sqlite3ExprCanBeNull(pRight)\n      ){\n        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);\n        VdbeCoverage(v);\n      }\n      if( zEndAff ){\n        updateRangeAffinityStr(pRight, nTop, zEndAff);\n        codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);\n      }else{\n        assert( pParse->db->mallocFailed );\n      }\n      nConstraint += nTop;\n      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );\n\n      if( sqlite3ExprIsVector(pRight)==0 ){\n        disableTerm(pLevel, pRangeEnd);\n      }else{\n        endEq = 1;\n      }\n    }else if( bStopAtNull ){\n      if( regBignull==0 ){\n        sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);\n        endEq = 0;\n      }\n      nConstraint++;\n    }\n    sqlite3DbFree(db, zStartAff);\n    sqlite3DbFree(db, zEndAff);\n\n    /* Top of the loop body */\n    pLevel->p2 = sqlite3VdbeCurrentAddr(v);\n\n    /* Check if the index cursor is past the end of the range. */\n    if( nConstraint ){\n      if( regBignull ){\n        /* Except, skip the end-of-range check while doing the NULL-scan */\n        sqlite3VdbeAddOp2(v, OP_IfNot, regBignull, sqlite3VdbeCurrentAddr(v)+3);\n        VdbeComment((v, \"If NULL-scan 2nd pass\"));\n        VdbeCoverage(v);\n      }\n      op = aEndOp[bRev*2 + endEq];\n      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);\n      testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );\n      testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );\n      testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );\n      testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );\n    }\n    if( regBignull ){\n      /* During a NULL-scan, check to see if we have reached the end of\n      ** the NULLs */\n      assert( bSeekPastNull==!bStopAtNull );\n      assert( bSeekPastNull+bStopAtNull==1 );\n      assert( nConstraint+bSeekPastNull>0 );\n      sqlite3VdbeAddOp2(v, OP_If, regBignull, sqlite3VdbeCurrentAddr(v)+2);\n      VdbeComment((v, \"If NULL-scan 1st pass\"));\n      VdbeCoverage(v);\n      op = aEndOp[bRev*2 + bSeekPastNull];\n      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase,\n                           nConstraint+bSeekPastNull);\n      testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );\n      testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );\n      testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );\n      testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );\n    }\n\n    if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){\n      sqlite3VdbeAddOp2(v, OP_SeekHit, iIdxCur, 1);\n    }\n\n    /* Seek the table cursor, if required */\n    omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 \n           && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;\n    if( omitTable ){\n      /* pIdx is a covering index.  No need to access the main table. */\n    }else if( HasRowid(pIdx->pTable) ){\n      if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE)\n       || ( (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE)!=0\n           && (pWInfo->eOnePass==ONEPASS_SINGLE || pLoop->nLTerm==0) )\n      ){\n        iRowidReg = ++pParse->nMem;\n        sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);\n        sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);\n        VdbeCoverage(v);\n      }else{\n        codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);\n      }\n    }else if( iCur!=iIdxCur ){\n      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);\n      iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);\n      for(j=0; j<pPk->nKeyCol; j++){\n        k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);\n        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);\n      }\n      sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,\n                           iRowidReg, pPk->nKeyCol); VdbeCoverage(v);\n    }\n\n    if( pLevel->iLeftJoin==0 ){\n      /* If pIdx is an index on one or more expressions, then look through\n      ** all the expressions in pWInfo and try to transform matching expressions\n      ** into reference to index columns.  Also attempt to translate references\n      ** to virtual columns in the table into references to (stored) columns\n      ** of the index.\n      **\n      ** Do not do this for the RHS of a LEFT JOIN. This is because the \n      ** expression may be evaluated after OP_NullRow has been executed on\n      ** the cursor. In this case it is important to do the full evaluation,\n      ** as the result of the expression may not be NULL, even if all table\n      ** column values are.  https://www.sqlite.org/src/info/7fa8049685b50b5a\n      **\n      ** Also, do not do this when processing one index an a multi-index\n      ** OR clause, since the transformation will become invalid once we\n      ** move forward to the next index.\n      ** https://sqlite.org/src/info/4e8e4857d32d401f\n      */\n      if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){\n        whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);\n      }\n  \n      /* If a partial index is driving the loop, try to eliminate WHERE clause\n      ** terms from the query that must be true due to the WHERE clause of\n      ** the partial index.\n      **\n      ** 2019-11-02 ticket 623eff57e76d45f6: This optimization does not work\n      ** for a LEFT JOIN.\n      */\n      if( pIdx->pPartIdxWhere ){\n        whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC);\n      }\n    }else{\n      testcase( pIdx->pPartIdxWhere );\n      /* The following assert() is not a requirement, merely an observation:\n      ** The OR-optimization doesn't work for the right hand table of\n      ** a LEFT JOIN: */\n      assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 );\n    }\n  \n    /* Record the instruction used to terminate the loop. */\n    if( pLoop->wsFlags & WHERE_ONEROW ){\n      pLevel->op = OP_Noop;\n    }else if( bRev ){\n      pLevel->op = OP_Prev;\n    }else{\n      pLevel->op = OP_Next;\n    }\n    pLevel->p1 = iIdxCur;\n    pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;\n    if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){\n      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;\n    }else{\n      assert( pLevel->p5==0 );\n    }\n    if( omitTable ) pIdx = 0;\n  }else\n\n#ifndef SQLITE_OMIT_OR_OPTIMIZATION\n  if( pLoop->wsFlags & WHERE_MULTI_OR ){\n    /* Case 5:  Two or more separately indexed terms connected by OR\n    **\n    ** Example:\n    **\n    **   CREATE TABLE t1(a,b,c,d);\n    **   CREATE INDEX i1 ON t1(a);\n    **   CREATE INDEX i2 ON t1(b);\n    **   CREATE INDEX i3 ON t1(c);\n    **\n    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)\n    **\n    ** In the example, there are three indexed terms connected by OR.\n    ** The top of the loop looks like this:\n    **\n    **          Null       1                # Zero the rowset in reg 1\n    **\n    ** Then, for each indexed term, the following. The arguments to\n    ** RowSetTest are such that the rowid of the current row is inserted\n    ** into the RowSet. If it is already present, control skips the\n    ** Gosub opcode and jumps straight to the code generated by WhereEnd().\n    **\n    **        sqlite3WhereBegin(<term>)\n    **          RowSetTest                  # Insert rowid into rowset\n    **          Gosub      2 A\n    **        sqlite3WhereEnd()\n    **\n    ** Following the above, code to terminate the loop. Label A, the target\n    ** of the Gosub above, jumps to the instruction right after the Goto.\n    **\n    **          Null       1                # Zero the rowset in reg 1\n    **          Goto       B                # The loop is finished.\n    **\n    **       A: <loop body>                 # Return data, whatever.\n    **\n    **          Return     2                # Jump back to the Gosub\n    **\n    **       B: <after the loop>\n    **\n    ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then\n    ** use an ephemeral index instead of a RowSet to record the primary\n    ** keys of the rows we have already seen.\n    **\n    */\n    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */\n    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */\n    Index *pCov = 0;             /* Potential covering index (or NULL) */\n    int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */\n\n    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */\n    int regRowset = 0;                        /* Register for RowSet object */\n    int regRowid = 0;                         /* Register holding rowid */\n    int iLoopBody = sqlite3VdbeMakeLabel(pParse);/* Start of loop body */\n    int iRetInit;                             /* Address of regReturn init */\n    int untestedTerms = 0;             /* Some terms not completely tested */\n    int ii;                            /* Loop counter */\n    u16 wctrlFlags;                    /* Flags for sub-WHERE clause */\n    Expr *pAndExpr = 0;                /* An \".. AND (...)\" expression */\n    Table *pTab = pTabItem->pTab;\n\n    pTerm = pLoop->aLTerm[0];\n    assert( pTerm!=0 );\n    assert( pTerm->eOperator & WO_OR );\n    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );\n    pOrWc = &pTerm->u.pOrInfo->wc;\n    pLevel->op = OP_Return;\n    pLevel->p1 = regReturn;\n\n    /* Set up a new SrcList in pOrTab containing the table being scanned\n    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.\n    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().\n    */\n    if( pWInfo->nLevel>1 ){\n      int nNotReady;                 /* The number of notReady tables */\n      struct SrcList_item *origSrc;     /* Original list of tables */\n      nNotReady = pWInfo->nLevel - iLevel - 1;\n      pOrTab = sqlite3StackAllocRaw(db,\n                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));\n      if( pOrTab==0 ) return notReady;\n      pOrTab->nAlloc = (u8)(nNotReady + 1);\n      pOrTab->nSrc = pOrTab->nAlloc;\n      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));\n      origSrc = pWInfo->pTabList->a;\n      for(k=1; k<=nNotReady; k++){\n        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));\n      }\n    }else{\n      pOrTab = pWInfo->pTabList;\n    }\n\n    /* Initialize the rowset register to contain NULL. An SQL NULL is \n    ** equivalent to an empty rowset.  Or, create an ephemeral index\n    ** capable of holding primary keys in the case of a WITHOUT ROWID.\n    **\n    ** Also initialize regReturn to contain the address of the instruction \n    ** immediately following the OP_Return at the bottom of the loop. This\n    ** is required in a few obscure LEFT JOIN cases where control jumps\n    ** over the top of the loop into the body of it. In this case the \n    ** correct response for the end-of-loop code (the OP_Return) is to \n    ** fall through to the next instruction, just as an OP_Next does if\n    ** called on an uninitialized cursor.\n    */\n    if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){\n      if( HasRowid(pTab) ){\n        regRowset = ++pParse->nMem;\n        sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);\n      }else{\n        Index *pPk = sqlite3PrimaryKeyIndex(pTab);\n        regRowset = pParse->nTab++;\n        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);\n        sqlite3VdbeSetP4KeyInfo(pParse, pPk);\n      }\n      regRowid = ++pParse->nMem;\n    }\n    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);\n\n    /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y\n    ** Then for every term xN, evaluate as the subexpression: xN AND z\n    ** That way, terms in y that are factored into the disjunction will\n    ** be picked up by the recursive calls to sqlite3WhereBegin() below.\n    **\n    ** Actually, each subexpression is converted to \"xN AND w\" where w is\n    ** the \"interesting\" terms of z - terms that did not originate in the\n    ** ON or USING clause of a LEFT JOIN, and terms that are usable as \n    ** indices.\n    **\n    ** This optimization also only applies if the (x1 OR x2 OR ...) term\n    ** is not contained in the ON clause of a LEFT JOIN.\n    ** See ticket http://www.sqlite.org/src/info/f2369304e4\n    */\n    if( pWC->nTerm>1 ){\n      int iTerm;\n      for(iTerm=0; iTerm<pWC->nTerm; iTerm++){\n        Expr *pExpr = pWC->a[iTerm].pExpr;\n        if( &pWC->a[iTerm] == pTerm ) continue;\n        testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );\n        testcase( pWC->a[iTerm].wtFlags & TERM_CODED );\n        if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;\n        if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;\n        testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );\n        pExpr = sqlite3ExprDup(db, pExpr, 0);\n        pAndExpr = sqlite3ExprAnd(pParse, pAndExpr, pExpr);\n      }\n      if( pAndExpr ){\n        /* The extra 0x10000 bit on the opcode is masked off and does not\n        ** become part of the new Expr.op.  However, it does make the\n        ** op==TK_AND comparison inside of sqlite3PExpr() false, and this\n        ** prevents sqlite3PExpr() from implementing AND short-circuit \n        ** optimization, which we do not want here. */\n        pAndExpr = sqlite3PExpr(pParse, TK_AND|0x10000, 0, pAndExpr);\n      }\n    }\n\n    /* Run a separate WHERE clause for each term of the OR clause.  After\n    ** eliminating duplicates from other WHERE clauses, the action for each\n    ** sub-WHERE clause is to to invoke the main loop body as a subroutine.\n    */\n    wctrlFlags =  WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);\n    ExplainQueryPlan((pParse, 1, \"MULTI-INDEX OR\"));\n    for(ii=0; ii<pOrWc->nTerm; ii++){\n      WhereTerm *pOrTerm = &pOrWc->a[ii];\n      if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){\n        WhereInfo *pSubWInfo;           /* Info for single OR-term scan */\n        Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */\n        int jmp1 = 0;                   /* Address of jump operation */\n        testcase( (pTabItem[0].fg.jointype & JT_LEFT)!=0\n               && !ExprHasProperty(pOrExpr, EP_FromJoin)\n        ); /* See TH3 vtab25.400 and ticket 614b25314c766238 */\n        if( pAndExpr ){\n          pAndExpr->pLeft = pOrExpr;\n          pOrExpr = pAndExpr;\n        }\n        /* Loop through table entries that match term pOrTerm. */\n        ExplainQueryPlan((pParse, 1, \"INDEX %d\", ii+1));\n        WHERETRACE(0xffff, (\"Subplan for OR-clause:\\n\"));\n        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,\n                                      wctrlFlags, iCovCur);\n        assert( pSubWInfo || pParse->nErr || db->mallocFailed );\n        if( pSubWInfo ){\n          WhereLoop *pSubLoop;\n          int addrExplain = sqlite3WhereExplainOneScan(\n              pParse, pOrTab, &pSubWInfo->a[0], 0\n          );\n          sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);\n\n          /* This is the sub-WHERE clause body.  First skip over\n          ** duplicate rows from prior sub-WHERE clauses, and record the\n          ** rowid (or PRIMARY KEY) for the current row so that the same\n          ** row will be skipped in subsequent sub-WHERE clauses.\n          */\n          if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){\n            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);\n            if( HasRowid(pTab) ){\n              sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid);\n              jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,\n                                          regRowid, iSet);\n              VdbeCoverage(v);\n            }else{\n              Index *pPk = sqlite3PrimaryKeyIndex(pTab);\n              int nPk = pPk->nKeyCol;\n              int iPk;\n              int r;\n\n              /* Read the PK into an array of temp registers. */\n              r = sqlite3GetTempRange(pParse, nPk);\n              for(iPk=0; iPk<nPk; iPk++){\n                int iCol = pPk->aiColumn[iPk];\n                sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk);\n              }\n\n              /* Check if the temp table already contains this key. If so,\n              ** the row has already been included in the result set and\n              ** can be ignored (by jumping past the Gosub below). Otherwise,\n              ** insert the key into the temp table and proceed with processing\n              ** the row.\n              **\n              ** Use some of the same optimizations as OP_RowSetTest: If iSet\n              ** is zero, assume that the key cannot already be present in\n              ** the temp table. And if iSet is -1, assume that there is no \n              ** need to insert the key into the temp table, as it will never \n              ** be tested for.  */ \n              if( iSet ){\n                jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);\n                VdbeCoverage(v);\n              }\n              if( iSet>=0 ){\n                sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);\n                sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,\n                                     r, nPk);\n                if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);\n              }\n\n              /* Release the array of temp registers */\n              sqlite3ReleaseTempRange(pParse, r, nPk);\n            }\n          }\n\n          /* Invoke the main loop body as a subroutine */\n          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);\n\n          /* Jump here (skipping the main loop body subroutine) if the\n          ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */\n          if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);\n\n          /* The pSubWInfo->untestedTerms flag means that this OR term\n          ** contained one or more AND term from a notReady table.  The\n          ** terms from the notReady table could not be tested and will\n          ** need to be tested later.\n          */\n          if( pSubWInfo->untestedTerms ) untestedTerms = 1;\n\n          /* If all of the OR-connected terms are optimized using the same\n          ** index, and the index is opened using the same cursor number\n          ** by each call to sqlite3WhereBegin() made by this loop, it may\n          ** be possible to use that index as a covering index.\n          **\n          ** If the call to sqlite3WhereBegin() above resulted in a scan that\n          ** uses an index, and this is either the first OR-connected term\n          ** processed or the index is the same as that used by all previous\n          ** terms, set pCov to the candidate covering index. Otherwise, set \n          ** pCov to NULL to indicate that no candidate covering index will \n          ** be available.\n          */\n          pSubLoop = pSubWInfo->a[0].pWLoop;\n          assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );\n          if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0\n           && (ii==0 || pSubLoop->u.btree.pIndex==pCov)\n           && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))\n          ){\n            assert( pSubWInfo->a[0].iIdxCur==iCovCur );\n            pCov = pSubLoop->u.btree.pIndex;\n          }else{\n            pCov = 0;\n          }\n\n          /* Finish the loop through table entries that match term pOrTerm. */\n          sqlite3WhereEnd(pSubWInfo);\n          ExplainQueryPlanPop(pParse);\n        }\n      }\n    }\n    ExplainQueryPlanPop(pParse);\n    pLevel->u.pCovidx = pCov;\n    if( pCov ) pLevel->iIdxCur = iCovCur;\n    if( pAndExpr ){\n      pAndExpr->pLeft = 0;\n      sqlite3ExprDelete(db, pAndExpr);\n    }\n    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));\n    sqlite3VdbeGoto(v, pLevel->addrBrk);\n    sqlite3VdbeResolveLabel(v, iLoopBody);\n\n    if( pWInfo->nLevel>1 ){ sqlite3StackFree(db, pOrTab); }\n    if( !untestedTerms ) disableTerm(pLevel, pTerm);\n  }else\n#endif /* SQLITE_OMIT_OR_OPTIMIZATION */\n\n  {\n    /* Case 6:  There is no usable index.  We must do a complete\n    **          scan of the entire table.\n    */\n    static const u8 aStep[] = { OP_Next, OP_Prev };\n    static const u8 aStart[] = { OP_Rewind, OP_Last };\n    assert( bRev==0 || bRev==1 );\n    if( pTabItem->fg.isRecursive ){\n      /* Tables marked isRecursive have only a single row that is stored in\n      ** a pseudo-cursor.  No need to Rewind or Next such cursors. */\n      pLevel->op = OP_Noop;\n    }else{\n      codeCursorHint(pTabItem, pWInfo, pLevel, 0);\n      pLevel->op = aStep[bRev];\n      pLevel->p1 = iCur;\n      pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);\n      VdbeCoverageIf(v, bRev==0);\n      VdbeCoverageIf(v, bRev!=0);\n      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;\n    }\n  }\n\n#ifdef SQLITE_ENABLE_STMT_SCANSTATUS\n  pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);\n#endif\n\n  /* Insert code to test every subexpression that can be completely\n  ** computed using the current set of tables.\n  **\n  ** This loop may run between one and three times, depending on the\n  ** constraints to be generated. The value of stack variable iLoop\n  ** determines the constraints coded by each iteration, as follows:\n  **\n  ** iLoop==1: Code only expressions that are entirely covered by pIdx.\n  ** iLoop==2: Code remaining expressions that do not contain correlated\n  **           sub-queries.  \n  ** iLoop==3: Code all remaining expressions.\n  **\n  ** An effort is made to skip unnecessary iterations of the loop.\n  */\n  iLoop = (pIdx ? 1 : 2);\n  do{\n    int iNext = 0;                /* Next value for iLoop */\n    for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){\n      Expr *pE;\n      int skipLikeAddr = 0;\n      testcase( pTerm->wtFlags & TERM_VIRTUAL );\n      testcase( pTerm->wtFlags & TERM_CODED );\n      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;\n      if( (pTerm->prereqAll & pLevel->notReady)!=0 ){\n        testcase( pWInfo->untestedTerms==0\n            && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );\n        pWInfo->untestedTerms = 1;\n        continue;\n      }\n      pE = pTerm->pExpr;\n      assert( pE!=0 );\n      if( (pTabItem->fg.jointype&JT_LEFT) && !ExprHasProperty(pE,EP_FromJoin) ){\n        continue;\n      }\n      \n      if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){\n        iNext = 2;\n        continue;\n      }\n      if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){\n        if( iNext==0 ) iNext = 3;\n        continue;\n      }\n\n      if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){\n        /* If the TERM_LIKECOND flag is set, that means that the range search\n        ** is sufficient to guarantee that the LIKE operator is true, so we\n        ** can skip the call to the like(A,B) function.  But this only works\n        ** for strings.  So do not skip the call to the function on the pass\n        ** that compares BLOBs. */\n#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS\n        continue;\n#else\n        u32 x = pLevel->iLikeRepCntr;\n        if( x>0 ){\n          skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1));\n          VdbeCoverageIf(v, (x&1)==1);\n          VdbeCoverageIf(v, (x&1)==0);\n        }\n#endif\n      }\n#ifdef WHERETRACE_ENABLED /* 0xffff */\n      if( sqlite3WhereTrace ){\n        VdbeNoopComment((v, \"WhereTerm[%d] (%p) priority=%d\",\n                         pWC->nTerm-j, pTerm, iLoop));\n      }\n      if( sqlite3WhereTrace & 0x800 ){\n        sqlite3DebugPrintf(\"Coding auxiliary constraint:\\n\");\n        sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);\n      }\n#endif\n      sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);\n      if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);\n      pTerm->wtFlags |= TERM_CODED;\n    }\n    iLoop = iNext;\n  }while( iLoop>0 );\n\n  /* Insert code to test for implied constraints based on transitivity\n  ** of the \"==\" operator.\n  **\n  ** Example: If the WHERE clause contains \"t1.a=t2.b\" and \"t2.b=123\"\n  ** and we are coding the t1 loop and the t2 loop has not yet coded,\n  ** then we cannot use the \"t1.a=t2.b\" constraint, but we can code\n  ** the implied \"t1.a=123\" constraint.\n  */\n  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){\n    Expr *pE, sEAlt;\n    WhereTerm *pAlt;\n    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;\n    if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;\n    if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;\n    if( pTerm->leftCursor!=iCur ) continue;\n    if( pTabItem->fg.jointype & JT_LEFT ) continue;\n    pE = pTerm->pExpr;\n#ifdef WHERETRACE_ENABLED /* 0x800 */\n    if( sqlite3WhereTrace & 0x800 ){\n      sqlite3DebugPrintf(\"Coding transitive constraint:\\n\");\n      sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);\n    }\n#endif\n    assert( !ExprHasProperty(pE, EP_FromJoin) );\n    assert( (pTerm->prereqRight & pLevel->notReady)!=0 );\n    pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,\n                    WO_EQ|WO_IN|WO_IS, 0);\n    if( pAlt==0 ) continue;\n    if( pAlt->wtFlags & (TERM_CODED) ) continue;\n    if( (pAlt->eOperator & WO_IN) \n     && (pAlt->pExpr->flags & EP_xIsSelect)\n     && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)\n    ){\n      continue;\n    }\n    testcase( pAlt->eOperator & WO_EQ );\n    testcase( pAlt->eOperator & WO_IS );\n    testcase( pAlt->eOperator & WO_IN );\n    VdbeModuleComment((v, \"begin transitive constraint\"));\n    sEAlt = *pAlt->pExpr;\n    sEAlt.pLeft = pE->pLeft;\n    sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);\n  }\n\n  /* For a LEFT OUTER JOIN, generate code that will record the fact that\n  ** at least one row of the right table has matched the left table.  \n  */\n  if( pLevel->iLeftJoin ){\n    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);\n    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);\n    VdbeComment((v, \"record LEFT JOIN hit\"));\n    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){\n      testcase( pTerm->wtFlags & TERM_VIRTUAL );\n      testcase( pTerm->wtFlags & TERM_CODED );\n      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;\n      if( (pTerm->prereqAll & pLevel->notReady)!=0 ){\n        assert( pWInfo->untestedTerms );\n        continue;\n      }\n      assert( pTerm->pExpr );\n      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);\n      pTerm->wtFlags |= TERM_CODED;\n    }\n  }\n\n#if WHERETRACE_ENABLED /* 0x20800 */\n  if( sqlite3WhereTrace & 0x20000 ){\n    sqlite3DebugPrintf(\"All WHERE-clause terms after coding level %d:\\n\",\n                       iLevel);\n    sqlite3WhereClausePrint(pWC);\n  }\n  if( sqlite3WhereTrace & 0x800 ){\n    sqlite3DebugPrintf(\"End Coding level %d:  notReady=%llx\\n\",\n       iLevel, (u64)pLevel->notReady);\n  }\n#endif\n  return pLevel->notReady;\n}\n\n/************** End of wherecode.c *******************************************/\n/************** Begin file whereexpr.c ***************************************/\n/*\n** 2015-06-08\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This module contains C code that generates VDBE code used to process\n** the WHERE clause of SQL statements.\n**\n** This file was originally part of where.c but was split out to improve\n** readability and editabiliity.  This file contains utility routines for\n** analyzing Expr objects in the WHERE clause.\n*/\n/* #include \"sqliteInt.h\" */\n/* #include \"whereInt.h\" */\n\n/* Forward declarations */\nstatic void exprAnalyze(SrcList*, WhereClause*, int);\n\n/*\n** Deallocate all memory associated with a WhereOrInfo object.\n*/\nstatic void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){\n  sqlite3WhereClauseClear(&p->wc);\n  sqlite3DbFree(db, p);\n}\n\n/*\n** Deallocate all memory associated with a WhereAndInfo object.\n*/\nstatic void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){\n  sqlite3WhereClauseClear(&p->wc);\n  sqlite3DbFree(db, p);\n}\n\n/*\n** Add a single new WhereTerm entry to the WhereClause object pWC.\n** The new WhereTerm object is constructed from Expr p and with wtFlags.\n** The index in pWC->a[] of the new WhereTerm is returned on success.\n** 0 is returned if the new WhereTerm could not be added due to a memory\n** allocation error.  The memory allocation failure will be recorded in\n** the db->mallocFailed flag so that higher-level functions can detect it.\n**\n** This routine will increase the size of the pWC->a[] array as necessary.\n**\n** If the wtFlags argument includes TERM_DYNAMIC, then responsibility\n** for freeing the expression p is assumed by the WhereClause object pWC.\n** This is true even if this routine fails to allocate a new WhereTerm.\n**\n** WARNING:  This routine might reallocate the space used to store\n** WhereTerms.  All pointers to WhereTerms should be invalidated after\n** calling this routine.  Such pointers may be reinitialized by referencing\n** the pWC->a[] array.\n*/\nstatic int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){\n  WhereTerm *pTerm;\n  int idx;\n  testcase( wtFlags & TERM_VIRTUAL );\n  if( pWC->nTerm>=pWC->nSlot ){\n    WhereTerm *pOld = pWC->a;\n    sqlite3 *db = pWC->pWInfo->pParse->db;\n    pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );\n    if( pWC->a==0 ){\n      if( wtFlags & TERM_DYNAMIC ){\n        sqlite3ExprDelete(db, p);\n      }\n      pWC->a = pOld;\n      return 0;\n    }\n    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);\n    if( pOld!=pWC->aStatic ){\n      sqlite3DbFree(db, pOld);\n    }\n    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);\n  }\n  pTerm = &pWC->a[idx = pWC->nTerm++];\n  if( p && ExprHasProperty(p, EP_Unlikely) ){\n    pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;\n  }else{\n    pTerm->truthProb = 1;\n  }\n  pTerm->pExpr = sqlite3ExprSkipCollateAndLikely(p);\n  pTerm->wtFlags = wtFlags;\n  pTerm->pWC = pWC;\n  pTerm->iParent = -1;\n  memset(&pTerm->eOperator, 0,\n         sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));\n  return idx;\n}\n\n/*\n** Return TRUE if the given operator is one of the operators that is\n** allowed for an indexable WHERE clause term.  The allowed operators are\n** \"=\", \"<\", \">\", \"<=\", \">=\", \"IN\", \"IS\", and \"IS NULL\"\n*/\nstatic int allowedOp(int op){\n  assert( TK_GT>TK_EQ && TK_GT<TK_GE );\n  assert( TK_LT>TK_EQ && TK_LT<TK_GE );\n  assert( TK_LE>TK_EQ && TK_LE<TK_GE );\n  assert( TK_GE==TK_EQ+4 );\n  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;\n}\n\n/*\n** Commute a comparison operator.  Expressions of the form \"X op Y\"\n** are converted into \"Y op X\".\n*/\nstatic u16 exprCommute(Parse *pParse, Expr *pExpr){\n  if( pExpr->pLeft->op==TK_VECTOR\n   || pExpr->pRight->op==TK_VECTOR\n   || sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight) !=\n      sqlite3BinaryCompareCollSeq(pParse, pExpr->pRight, pExpr->pLeft)\n  ){\n    pExpr->flags ^= EP_Commuted;\n  }\n  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);\n  if( pExpr->op>=TK_GT ){\n    assert( TK_LT==TK_GT+2 );\n    assert( TK_GE==TK_LE+2 );\n    assert( TK_GT>TK_EQ );\n    assert( TK_GT<TK_LE );\n    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );\n    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;\n  }\n  return 0;\n}\n\n/*\n** Translate from TK_xx operator to WO_xx bitmask.\n*/\nstatic u16 operatorMask(int op){\n  u16 c;\n  assert( allowedOp(op) );\n  if( op==TK_IN ){\n    c = WO_IN;\n  }else if( op==TK_ISNULL ){\n    c = WO_ISNULL;\n  }else if( op==TK_IS ){\n    c = WO_IS;\n  }else{\n    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );\n    c = (u16)(WO_EQ<<(op-TK_EQ));\n  }\n  assert( op!=TK_ISNULL || c==WO_ISNULL );\n  assert( op!=TK_IN || c==WO_IN );\n  assert( op!=TK_EQ || c==WO_EQ );\n  assert( op!=TK_LT || c==WO_LT );\n  assert( op!=TK_LE || c==WO_LE );\n  assert( op!=TK_GT || c==WO_GT );\n  assert( op!=TK_GE || c==WO_GE );\n  assert( op!=TK_IS || c==WO_IS );\n  return c;\n}\n\n\n#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION\n/*\n** Check to see if the given expression is a LIKE or GLOB operator that\n** can be optimized using inequality constraints.  Return TRUE if it is\n** so and false if not.\n**\n** In order for the operator to be optimizible, the RHS must be a string\n** literal that does not begin with a wildcard.  The LHS must be a column\n** that may only be NULL, a string, or a BLOB, never a number. (This means\n** that virtual tables cannot participate in the LIKE optimization.)  The\n** collating sequence for the column on the LHS must be appropriate for\n** the operator.\n*/\nstatic int isLikeOrGlob(\n  Parse *pParse,    /* Parsing and code generating context */\n  Expr *pExpr,      /* Test this expression */\n  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */\n  int *pisComplete, /* True if the only wildcard is % in the last character */\n  int *pnoCase      /* True if uppercase is equivalent to lowercase */\n){\n  const u8 *z = 0;           /* String on RHS of LIKE operator */\n  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */\n  ExprList *pList;           /* List of operands to the LIKE operator */\n  u8 c;                      /* One character in z[] */\n  int cnt;                   /* Number of non-wildcard prefix characters */\n  u8 wc[4];                  /* Wildcard characters */\n  sqlite3 *db = pParse->db;  /* Database connection */\n  sqlite3_value *pVal = 0;\n  int op;                    /* Opcode of pRight */\n  int rc;                    /* Result code to return */\n\n  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, (char*)wc) ){\n    return 0;\n  }\n#ifdef SQLITE_EBCDIC\n  if( *pnoCase ) return 0;\n#endif\n  pList = pExpr->x.pList;\n  pLeft = pList->a[1].pExpr;\n\n  pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);\n  op = pRight->op;\n  if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){\n    Vdbe *pReprepare = pParse->pReprepare;\n    int iCol = pRight->iColumn;\n    pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);\n    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){\n      z = sqlite3_value_text(pVal);\n    }\n    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);\n    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );\n  }else if( op==TK_STRING ){\n    z = (u8*)pRight->u.zToken;\n  }\n  if( z ){\n\n    /* Count the number of prefix characters prior to the first wildcard */\n    cnt = 0;\n    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){\n      cnt++;\n      if( c==wc[3] && z[cnt]!=0 ) cnt++;\n    }\n\n    /* The optimization is possible only if (1) the pattern does not begin\n    ** with a wildcard and if (2) the non-wildcard prefix does not end with\n    ** an (illegal 0xff) character, or (3) the pattern does not consist of\n    ** a single escape character. The second condition is necessary so\n    ** that we can increment the prefix key to find an upper bound for the\n    ** range search. The third is because the caller assumes that the pattern\n    ** consists of at least one character after all escapes have been\n    ** removed.  */\n    if( cnt!=0 && 255!=(u8)z[cnt-1] && (cnt>1 || z[0]!=wc[3]) ){\n      Expr *pPrefix;\n\n      /* A \"complete\" match if the pattern ends with \"*\" or \"%\" */\n      *pisComplete = c==wc[0] && z[cnt+1]==0;\n\n      /* Get the pattern prefix.  Remove all escapes from the prefix. */\n      pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);\n      if( pPrefix ){\n        int iFrom, iTo;\n        char *zNew = pPrefix->u.zToken;\n        zNew[cnt] = 0;\n        for(iFrom=iTo=0; iFrom<cnt; iFrom++){\n          if( zNew[iFrom]==wc[3] ) iFrom++;\n          zNew[iTo++] = zNew[iFrom];\n        }\n        zNew[iTo] = 0;\n        assert( iTo>0 );\n\n        /* If the LHS is not an ordinary column with TEXT affinity, then the\n        ** pattern prefix boundaries (both the start and end boundaries) must\n        ** not look like a number.  Otherwise the pattern might be treated as\n        ** a number, which will invalidate the LIKE optimization.\n        **\n        ** Getting this right has been a persistent source of bugs in the\n        ** LIKE optimization.  See, for example:\n        **    2018-09-10 https://sqlite.org/src/info/c94369cae9b561b1\n        **    2019-05-02 https://sqlite.org/src/info/b043a54c3de54b28\n        **    2019-06-10 https://sqlite.org/src/info/fd76310a5e843e07\n        **    2019-06-14 https://sqlite.org/src/info/ce8717f0885af975\n        **    2019-09-03 https://sqlite.org/src/info/0f0428096f17252a\n        */\n        if( pLeft->op!=TK_COLUMN \n         || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT \n         || IsVirtual(pLeft->y.pTab)  /* Value might be numeric */\n        ){\n          int isNum;\n          double rDummy;\n          isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8);\n          if( isNum<=0 ){\n            if( iTo==1 && zNew[0]=='-' ){\n              isNum = +1;\n            }else{\n              zNew[iTo-1]++;\n              isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8);\n              zNew[iTo-1]--;\n            }\n          }\n          if( isNum>0 ){\n            sqlite3ExprDelete(db, pPrefix);\n            sqlite3ValueFree(pVal);\n            return 0;\n          }\n        }\n      }\n      *ppPrefix = pPrefix;\n\n      /* If the RHS pattern is a bound parameter, make arrangements to\n      ** reprepare the statement when that parameter is rebound */\n      if( op==TK_VARIABLE ){\n        Vdbe *v = pParse->pVdbe;\n        sqlite3VdbeSetVarmask(v, pRight->iColumn);\n        if( *pisComplete && pRight->u.zToken[1] ){\n          /* If the rhs of the LIKE expression is a variable, and the current\n          ** value of the variable means there is no need to invoke the LIKE\n          ** function, then no OP_Variable will be added to the program.\n          ** This causes problems for the sqlite3_bind_parameter_name()\n          ** API. To work around them, add a dummy OP_Variable here.\n          */ \n          int r1 = sqlite3GetTempReg(pParse);\n          sqlite3ExprCodeTarget(pParse, pRight, r1);\n          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);\n          sqlite3ReleaseTempReg(pParse, r1);\n        }\n      }\n    }else{\n      z = 0;\n    }\n  }\n\n  rc = (z!=0);\n  sqlite3ValueFree(pVal);\n  return rc;\n}\n#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */\n\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/*\n** Check to see if the pExpr expression is a form that needs to be passed\n** to the xBestIndex method of virtual tables.  Forms of interest include:\n**\n**          Expression                   Virtual Table Operator\n**          -----------------------      ---------------------------------\n**      1.  column MATCH expr            SQLITE_INDEX_CONSTRAINT_MATCH\n**      2.  column GLOB expr             SQLITE_INDEX_CONSTRAINT_GLOB\n**      3.  column LIKE expr             SQLITE_INDEX_CONSTRAINT_LIKE\n**      4.  column REGEXP expr           SQLITE_INDEX_CONSTRAINT_REGEXP\n**      5.  column != expr               SQLITE_INDEX_CONSTRAINT_NE\n**      6.  expr != column               SQLITE_INDEX_CONSTRAINT_NE\n**      7.  column IS NOT expr           SQLITE_INDEX_CONSTRAINT_ISNOT\n**      8.  expr IS NOT column           SQLITE_INDEX_CONSTRAINT_ISNOT\n**      9.  column IS NOT NULL           SQLITE_INDEX_CONSTRAINT_ISNOTNULL\n**\n** In every case, \"column\" must be a column of a virtual table.  If there\n** is a match, set *ppLeft to the \"column\" expression, set *ppRight to the \n** \"expr\" expression (even though in forms (6) and (8) the column is on the\n** right and the expression is on the left).  Also set *peOp2 to the\n** appropriate virtual table operator.  The return value is 1 or 2 if there\n** is a match.  The usual return is 1, but if the RHS is also a column\n** of virtual table in forms (5) or (7) then return 2.\n**\n** If the expression matches none of the patterns above, return 0.\n*/\nstatic int isAuxiliaryVtabOperator(\n  sqlite3 *db,                    /* Parsing context */\n  Expr *pExpr,                    /* Test this expression */\n  unsigned char *peOp2,           /* OUT: 0 for MATCH, or else an op2 value */\n  Expr **ppLeft,                  /* Column expression to left of MATCH/op2 */\n  Expr **ppRight                  /* Expression to left of MATCH/op2 */\n){\n  if( pExpr->op==TK_FUNCTION ){\n    static const struct Op2 {\n      const char *zOp;\n      unsigned char eOp2;\n    } aOp[] = {\n      { \"match\",  SQLITE_INDEX_CONSTRAINT_MATCH },\n      { \"glob\",   SQLITE_INDEX_CONSTRAINT_GLOB },\n      { \"like\",   SQLITE_INDEX_CONSTRAINT_LIKE },\n      { \"regexp\", SQLITE_INDEX_CONSTRAINT_REGEXP }\n    };\n    ExprList *pList;\n    Expr *pCol;                     /* Column reference */\n    int i;\n\n    pList = pExpr->x.pList;\n    if( pList==0 || pList->nExpr!=2 ){\n      return 0;\n    }\n\n    /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a\n    ** virtual table on their second argument, which is the same as\n    ** the left-hand side operand in their in-fix form.\n    **\n    **       vtab_column MATCH expression\n    **       MATCH(expression,vtab_column)\n    */\n    pCol = pList->a[1].pExpr;\n    testcase( pCol->op==TK_COLUMN && pCol->y.pTab==0 );\n    if( ExprIsVtab(pCol) ){\n      for(i=0; i<ArraySize(aOp); i++){\n        if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){\n          *peOp2 = aOp[i].eOp2;\n          *ppRight = pList->a[0].pExpr;\n          *ppLeft = pCol;\n          return 1;\n        }\n      }\n    }\n\n    /* We can also match against the first column of overloaded\n    ** functions where xFindFunction returns a value of at least\n    ** SQLITE_INDEX_CONSTRAINT_FUNCTION.\n    **\n    **      OVERLOADED(vtab_column,expression)\n    **\n    ** Historically, xFindFunction expected to see lower-case function\n    ** names.  But for this use case, xFindFunction is expected to deal\n    ** with function names in an arbitrary case.\n    */\n    pCol = pList->a[0].pExpr;\n    testcase( pCol->op==TK_COLUMN && pCol->y.pTab==0 );\n    if( ExprIsVtab(pCol) ){\n      sqlite3_vtab *pVtab;\n      sqlite3_module *pMod;\n      void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**);\n      void *pNotUsed;\n      pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab;\n      assert( pVtab!=0 );\n      assert( pVtab->pModule!=0 );\n      pMod = (sqlite3_module *)pVtab->pModule;\n      if( pMod->xFindFunction!=0 ){\n        i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed);\n        if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){\n          *peOp2 = i;\n          *ppRight = pList->a[1].pExpr;\n          *ppLeft = pCol;\n          return 1;\n        }\n      }\n    }\n  }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){\n    int res = 0;\n    Expr *pLeft = pExpr->pLeft;\n    Expr *pRight = pExpr->pRight;\n    testcase( pLeft->op==TK_COLUMN && pLeft->y.pTab==0 );\n    if( ExprIsVtab(pLeft) ){\n      res++;\n    }\n    testcase( pRight && pRight->op==TK_COLUMN && pRight->y.pTab==0 );\n    if( pRight && ExprIsVtab(pRight) ){\n      res++;\n      SWAP(Expr*, pLeft, pRight);\n    }\n    *ppLeft = pLeft;\n    *ppRight = pRight;\n    if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;\n    if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;\n    if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;\n    return res;\n  }\n  return 0;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n/*\n** If the pBase expression originated in the ON or USING clause of\n** a join, then transfer the appropriate markings over to derived.\n*/\nstatic void transferJoinMarkings(Expr *pDerived, Expr *pBase){\n  if( pDerived ){\n    pDerived->flags |= pBase->flags & EP_FromJoin;\n    pDerived->iRightJoinTable = pBase->iRightJoinTable;\n  }\n}\n\n/*\n** Mark term iChild as being a child of term iParent\n*/\nstatic void markTermAsChild(WhereClause *pWC, int iChild, int iParent){\n  pWC->a[iChild].iParent = iParent;\n  pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;\n  pWC->a[iParent].nChild++;\n}\n\n/*\n** Return the N-th AND-connected subterm of pTerm.  Or if pTerm is not\n** a conjunction, then return just pTerm when N==0.  If N is exceeds\n** the number of available subterms, return NULL.\n*/\nstatic WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){\n  if( pTerm->eOperator!=WO_AND ){\n    return N==0 ? pTerm : 0;\n  }\n  if( N<pTerm->u.pAndInfo->wc.nTerm ){\n    return &pTerm->u.pAndInfo->wc.a[N];\n  }\n  return 0;\n}\n\n/*\n** Subterms pOne and pTwo are contained within WHERE clause pWC.  The\n** two subterms are in disjunction - they are OR-ed together.\n**\n** If these two terms are both of the form:  \"A op B\" with the same\n** A and B values but different operators and if the operators are\n** compatible (if one is = and the other is <, for example) then\n** add a new virtual AND term to pWC that is the combination of the\n** two.\n**\n** Some examples:\n**\n**    x<y OR x=y    -->     x<=y\n**    x=y OR x=y    -->     x=y\n**    x<=y OR x<y   -->     x<=y\n**\n** The following is NOT generated:\n**\n**    x<y OR x>y    -->     x!=y     \n*/\nstatic void whereCombineDisjuncts(\n  SrcList *pSrc,         /* the FROM clause */\n  WhereClause *pWC,      /* The complete WHERE clause */\n  WhereTerm *pOne,       /* First disjunct */\n  WhereTerm *pTwo        /* Second disjunct */\n){\n  u16 eOp = pOne->eOperator | pTwo->eOperator;\n  sqlite3 *db;           /* Database connection (for malloc) */\n  Expr *pNew;            /* New virtual expression */\n  int op;                /* Operator for the combined expression */\n  int idxNew;            /* Index in pWC of the next virtual term */\n\n  if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;\n  if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;\n  if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp\n   && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;\n  assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );\n  assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );\n  if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;\n  if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;\n  /* If we reach this point, it means the two subterms can be combined */\n  if( (eOp & (eOp-1))!=0 ){\n    if( eOp & (WO_LT|WO_LE) ){\n      eOp = WO_LE;\n    }else{\n      assert( eOp & (WO_GT|WO_GE) );\n      eOp = WO_GE;\n    }\n  }\n  db = pWC->pWInfo->pParse->db;\n  pNew = sqlite3ExprDup(db, pOne->pExpr, 0);\n  if( pNew==0 ) return;\n  for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }\n  pNew->op = op;\n  idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);\n  exprAnalyze(pSrc, pWC, idxNew);\n}\n\n#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)\n/*\n** Analyze a term that consists of two or more OR-connected\n** subterms.  So in:\n**\n**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)\n**                          ^^^^^^^^^^^^^^^^^^^^\n**\n** This routine analyzes terms such as the middle term in the above example.\n** A WhereOrTerm object is computed and attached to the term under\n** analysis, regardless of the outcome of the analysis.  Hence:\n**\n**     WhereTerm.wtFlags   |=  TERM_ORINFO\n**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object\n**\n** The term being analyzed must have two or more of OR-connected subterms.\n** A single subterm might be a set of AND-connected sub-subterms.\n** Examples of terms under analysis:\n**\n**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5\n**     (B)     x=expr1 OR expr2=x OR x=expr3\n**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)\n**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')\n**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)\n**     (F)     x>A OR (x=A AND y>=B)\n**\n** CASE 1:\n**\n** If all subterms are of the form T.C=expr for some single column of C and\n** a single table T (as shown in example B above) then create a new virtual\n** term that is an equivalent IN expression.  In other words, if the term\n** being analyzed is:\n**\n**      x = expr1  OR  expr2 = x  OR  x = expr3\n**\n** then create a new virtual term like this:\n**\n**      x IN (expr1,expr2,expr3)\n**\n** CASE 2:\n**\n** If there are exactly two disjuncts and one side has x>A and the other side\n** has x=A (for the same x and A) then add a new virtual conjunct term to the\n** WHERE clause of the form \"x>=A\".  Example:\n**\n**      x>A OR (x=A AND y>B)    adds:    x>=A\n**\n** The added conjunct can sometimes be helpful in query planning.\n**\n** CASE 3:\n**\n** If all subterms are indexable by a single table T, then set\n**\n**     WhereTerm.eOperator              =  WO_OR\n**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T\n**\n** A subterm is \"indexable\" if it is of the form\n** \"T.C <op> <expr>\" where C is any column of table T and \n** <op> is one of \"=\", \"<\", \"<=\", \">\", \">=\", \"IS NULL\", or \"IN\".\n** A subterm is also indexable if it is an AND of two or more\n** subsubterms at least one of which is indexable.  Indexable AND \n** subterms have their eOperator set to WO_AND and they have\n** u.pAndInfo set to a dynamically allocated WhereAndTerm object.\n**\n** From another point of view, \"indexable\" means that the subterm could\n** potentially be used with an index if an appropriate index exists.\n** This analysis does not consider whether or not the index exists; that\n** is decided elsewhere.  This analysis only looks at whether subterms\n** appropriate for indexing exist.\n**\n** All examples A through E above satisfy case 3.  But if a term\n** also satisfies case 1 (such as B) we know that the optimizer will\n** always prefer case 1, so in that case we pretend that case 3 is not\n** satisfied.\n**\n** It might be the case that multiple tables are indexable.  For example,\n** (E) above is indexable on tables P, Q, and R.\n**\n** Terms that satisfy case 3 are candidates for lookup by using\n** separate indices to find rowids for each subterm and composing\n** the union of all rowids using a RowSet object.  This is similar\n** to \"bitmap indices\" in other database engines.\n**\n** OTHERWISE:\n**\n** If none of cases 1, 2, or 3 apply, then leave the eOperator set to\n** zero.  This term is not useful for search.\n*/\nstatic void exprAnalyzeOrTerm(\n  SrcList *pSrc,            /* the FROM clause */\n  WhereClause *pWC,         /* the complete WHERE clause */\n  int idxTerm               /* Index of the OR-term to be analyzed */\n){\n  WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */\n  Parse *pParse = pWInfo->pParse;         /* Parser context */\n  sqlite3 *db = pParse->db;               /* Database connection */\n  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */\n  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */\n  int i;                                  /* Loop counters */\n  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */\n  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */\n  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */\n  Bitmask chngToIN;         /* Tables that might satisfy case 1 */\n  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */\n\n  /*\n  ** Break the OR clause into its separate subterms.  The subterms are\n  ** stored in a WhereClause structure containing within the WhereOrInfo\n  ** object that is attached to the original OR clause term.\n  */\n  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );\n  assert( pExpr->op==TK_OR );\n  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));\n  if( pOrInfo==0 ) return;\n  pTerm->wtFlags |= TERM_ORINFO;\n  pOrWc = &pOrInfo->wc;\n  memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));\n  sqlite3WhereClauseInit(pOrWc, pWInfo);\n  sqlite3WhereSplit(pOrWc, pExpr, TK_OR);\n  sqlite3WhereExprAnalyze(pSrc, pOrWc);\n  if( db->mallocFailed ) return;\n  assert( pOrWc->nTerm>=2 );\n\n  /*\n  ** Compute the set of tables that might satisfy cases 1 or 3.\n  */\n  indexable = ~(Bitmask)0;\n  chngToIN = ~(Bitmask)0;\n  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){\n    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){\n      WhereAndInfo *pAndInfo;\n      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );\n      chngToIN = 0;\n      pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));\n      if( pAndInfo ){\n        WhereClause *pAndWC;\n        WhereTerm *pAndTerm;\n        int j;\n        Bitmask b = 0;\n        pOrTerm->u.pAndInfo = pAndInfo;\n        pOrTerm->wtFlags |= TERM_ANDINFO;\n        pOrTerm->eOperator = WO_AND;\n        pAndWC = &pAndInfo->wc;\n        memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));\n        sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);\n        sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);\n        sqlite3WhereExprAnalyze(pSrc, pAndWC);\n        pAndWC->pOuter = pWC;\n        if( !db->mallocFailed ){\n          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){\n            assert( pAndTerm->pExpr );\n            if( allowedOp(pAndTerm->pExpr->op) \n             || pAndTerm->eOperator==WO_AUX\n            ){\n              b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);\n            }\n          }\n        }\n        indexable &= b;\n      }\n    }else if( pOrTerm->wtFlags & TERM_COPIED ){\n      /* Skip this term for now.  We revisit it when we process the\n      ** corresponding TERM_VIRTUAL term */\n    }else{\n      Bitmask b;\n      b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);\n      if( pOrTerm->wtFlags & TERM_VIRTUAL ){\n        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];\n        b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);\n      }\n      indexable &= b;\n      if( (pOrTerm->eOperator & WO_EQ)==0 ){\n        chngToIN = 0;\n      }else{\n        chngToIN &= b;\n      }\n    }\n  }\n\n  /*\n  ** Record the set of tables that satisfy case 3.  The set might be\n  ** empty.\n  */\n  pOrInfo->indexable = indexable;\n  if( indexable ){\n    pTerm->eOperator = WO_OR;\n    pWC->hasOr = 1;\n  }else{\n    pTerm->eOperator = WO_OR;\n  }\n\n  /* For a two-way OR, attempt to implementation case 2.\n  */\n  if( indexable && pOrWc->nTerm==2 ){\n    int iOne = 0;\n    WhereTerm *pOne;\n    while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){\n      int iTwo = 0;\n      WhereTerm *pTwo;\n      while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){\n        whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);\n      }\n    }\n  }\n\n  /*\n  ** chngToIN holds a set of tables that *might* satisfy case 1.  But\n  ** we have to do some additional checking to see if case 1 really\n  ** is satisfied.\n  **\n  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means\n  ** that there is no possibility of transforming the OR clause into an\n  ** IN operator because one or more terms in the OR clause contain\n  ** something other than == on a column in the single table.  The 1-bit\n  ** case means that every term of the OR clause is of the form\n  ** \"table.column=expr\" for some single table.  The one bit that is set\n  ** will correspond to the common table.  We still need to check to make\n  ** sure the same column is used on all terms.  The 2-bit case is when\n  ** the all terms are of the form \"table1.column=table2.column\".  It\n  ** might be possible to form an IN operator with either table1.column\n  ** or table2.column as the LHS if either is common to every term of\n  ** the OR clause.\n  **\n  ** Note that terms of the form \"table.column1=table.column2\" (the\n  ** same table on both sizes of the ==) cannot be optimized.\n  */\n  if( chngToIN ){\n    int okToChngToIN = 0;     /* True if the conversion to IN is valid */\n    int iColumn = -1;         /* Column index on lhs of IN operator */\n    int iCursor = -1;         /* Table cursor common to all terms */\n    int j = 0;                /* Loop counter */\n\n    /* Search for a table and column that appears on one side or the\n    ** other of the == operator in every subterm.  That table and column\n    ** will be recorded in iCursor and iColumn.  There might not be any\n    ** such table and column.  Set okToChngToIN if an appropriate table\n    ** and column is found but leave okToChngToIN false if not found.\n    */\n    for(j=0; j<2 && !okToChngToIN; j++){\n      Expr *pLeft = 0;\n      pOrTerm = pOrWc->a;\n      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){\n        assert( pOrTerm->eOperator & WO_EQ );\n        pOrTerm->wtFlags &= ~TERM_OR_OK;\n        if( pOrTerm->leftCursor==iCursor ){\n          /* This is the 2-bit case and we are on the second iteration and\n          ** current term is from the first iteration.  So skip this term. */\n          assert( j==1 );\n          continue;\n        }\n        if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,\n                                            pOrTerm->leftCursor))==0 ){\n          /* This term must be of the form t1.a==t2.b where t2 is in the\n          ** chngToIN set but t1 is not.  This term will be either preceded\n          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term \n          ** and use its inversion. */\n          testcase( pOrTerm->wtFlags & TERM_COPIED );\n          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );\n          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );\n          continue;\n        }\n        iColumn = pOrTerm->u.leftColumn;\n        iCursor = pOrTerm->leftCursor;\n        pLeft = pOrTerm->pExpr->pLeft;\n        break;\n      }\n      if( i<0 ){\n        /* No candidate table+column was found.  This can only occur\n        ** on the second iteration */\n        assert( j==1 );\n        assert( IsPowerOfTwo(chngToIN) );\n        assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );\n        break;\n      }\n      testcase( j==1 );\n\n      /* We have found a candidate table and column.  Check to see if that\n      ** table and column is common to every term in the OR clause */\n      okToChngToIN = 1;\n      for(; i>=0 && okToChngToIN; i--, pOrTerm++){\n        assert( pOrTerm->eOperator & WO_EQ );\n        if( pOrTerm->leftCursor!=iCursor ){\n          pOrTerm->wtFlags &= ~TERM_OR_OK;\n        }else if( pOrTerm->u.leftColumn!=iColumn || (iColumn==XN_EXPR \n               && sqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1)\n        )){\n          okToChngToIN = 0;\n        }else{\n          int affLeft, affRight;\n          /* If the right-hand side is also a column, then the affinities\n          ** of both right and left sides must be such that no type\n          ** conversions are required on the right.  (Ticket #2249)\n          */\n          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);\n          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);\n          if( affRight!=0 && affRight!=affLeft ){\n            okToChngToIN = 0;\n          }else{\n            pOrTerm->wtFlags |= TERM_OR_OK;\n          }\n        }\n      }\n    }\n\n    /* At this point, okToChngToIN is true if original pTerm satisfies\n    ** case 1.  In that case, construct a new virtual term that is \n    ** pTerm converted into an IN operator.\n    */\n    if( okToChngToIN ){\n      Expr *pDup;            /* A transient duplicate expression */\n      ExprList *pList = 0;   /* The RHS of the IN operator */\n      Expr *pLeft = 0;       /* The LHS of the IN operator */\n      Expr *pNew;            /* The complete IN operator */\n\n      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){\n        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;\n        assert( pOrTerm->eOperator & WO_EQ );\n        assert( pOrTerm->leftCursor==iCursor );\n        assert( pOrTerm->u.leftColumn==iColumn );\n        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);\n        pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);\n        pLeft = pOrTerm->pExpr->pLeft;\n      }\n      assert( pLeft!=0 );\n      pDup = sqlite3ExprDup(db, pLeft, 0);\n      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);\n      if( pNew ){\n        int idxNew;\n        transferJoinMarkings(pNew, pExpr);\n        assert( !ExprHasProperty(pNew, EP_xIsSelect) );\n        pNew->x.pList = pList;\n        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);\n        testcase( idxNew==0 );\n        exprAnalyze(pSrc, pWC, idxNew);\n        /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where used again */\n        markTermAsChild(pWC, idxNew, idxTerm);\n      }else{\n        sqlite3ExprListDelete(db, pList);\n      }\n    }\n  }\n}\n#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */\n\n/*\n** We already know that pExpr is a binary operator where both operands are\n** column references.  This routine checks to see if pExpr is an equivalence\n** relation:\n**   1.  The SQLITE_Transitive optimization must be enabled\n**   2.  Must be either an == or an IS operator\n**   3.  Not originating in the ON clause of an OUTER JOIN\n**   4.  The affinities of A and B must be compatible\n**   5a. Both operands use the same collating sequence OR\n**   5b. The overall collating sequence is BINARY\n** If this routine returns TRUE, that means that the RHS can be substituted\n** for the LHS anyplace else in the WHERE clause where the LHS column occurs.\n** This is an optimization.  No harm comes from returning 0.  But if 1 is\n** returned when it should not be, then incorrect answers might result.\n*/\nstatic int termIsEquivalence(Parse *pParse, Expr *pExpr){\n  char aff1, aff2;\n  CollSeq *pColl;\n  if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;\n  if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;\n  if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;\n  aff1 = sqlite3ExprAffinity(pExpr->pLeft);\n  aff2 = sqlite3ExprAffinity(pExpr->pRight);\n  if( aff1!=aff2\n   && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))\n  ){\n    return 0;\n  }\n  pColl = sqlite3ExprCompareCollSeq(pParse, pExpr);\n  if( sqlite3IsBinary(pColl) ) return 1;\n  return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);\n}\n\n/*\n** Recursively walk the expressions of a SELECT statement and generate\n** a bitmask indicating which tables are used in that expression\n** tree.\n*/\nstatic Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){\n  Bitmask mask = 0;\n  while( pS ){\n    SrcList *pSrc = pS->pSrc;\n    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);\n    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);\n    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);\n    mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);\n    mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);\n    if( ALWAYS(pSrc!=0) ){\n      int i;\n      for(i=0; i<pSrc->nSrc; i++){\n        mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);\n        mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);\n        if( pSrc->a[i].fg.isTabFunc ){\n          mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg);\n        }\n      }\n    }\n    pS = pS->pPrior;\n  }\n  return mask;\n}\n\n/*\n** Expression pExpr is one operand of a comparison operator that might\n** be useful for indexing.  This routine checks to see if pExpr appears\n** in any index.  Return TRUE (1) if pExpr is an indexed term and return\n** FALSE (0) if not.  If TRUE is returned, also set aiCurCol[0] to the cursor\n** number of the table that is indexed and aiCurCol[1] to the column number\n** of the column that is indexed, or XN_EXPR (-2) if an expression is being\n** indexed.\n**\n** If pExpr is a TK_COLUMN column reference, then this routine always returns\n** true even if that particular column is not indexed, because the column\n** might be added to an automatic index later.\n*/\nstatic SQLITE_NOINLINE int exprMightBeIndexed2(\n  SrcList *pFrom,        /* The FROM clause */\n  Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */\n  int *aiCurCol,         /* Write the referenced table cursor and column here */\n  Expr *pExpr            /* An operand of a comparison operator */\n){\n  Index *pIdx;\n  int i;\n  int iCur;\n  for(i=0; mPrereq>1; i++, mPrereq>>=1){}\n  iCur = pFrom->a[i].iCursor;\n  for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n    if( pIdx->aColExpr==0 ) continue;\n    for(i=0; i<pIdx->nKeyCol; i++){\n      if( pIdx->aiColumn[i]!=XN_EXPR ) continue;\n      if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){\n        aiCurCol[0] = iCur;\n        aiCurCol[1] = XN_EXPR;\n        return 1;\n      }\n    }\n  }\n  return 0;\n}\nstatic int exprMightBeIndexed(\n  SrcList *pFrom,        /* The FROM clause */\n  Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */\n  int *aiCurCol,         /* Write the referenced table cursor & column here */\n  Expr *pExpr,           /* An operand of a comparison operator */\n  int op                 /* The specific comparison operator */\n){\n  /* If this expression is a vector to the left or right of a \n  ** inequality constraint (>, <, >= or <=), perform the processing \n  ** on the first element of the vector.  */\n  assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );\n  assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );\n  assert( op<=TK_GE );\n  if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){\n    pExpr = pExpr->x.pList->a[0].pExpr;\n  }\n\n  if( pExpr->op==TK_COLUMN ){\n    aiCurCol[0] = pExpr->iTable;\n    aiCurCol[1] = pExpr->iColumn;\n    return 1;\n  }\n  if( mPrereq==0 ) return 0;                 /* No table references */\n  if( (mPrereq&(mPrereq-1))!=0 ) return 0;   /* Refs more than one table */\n  return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);\n}\n\n/*\n** The input to this routine is an WhereTerm structure with only the\n** \"pExpr\" field filled in.  The job of this routine is to analyze the\n** subexpression and populate all the other fields of the WhereTerm\n** structure.\n**\n** If the expression is of the form \"<expr> <op> X\" it gets commuted\n** to the standard form of \"X <op> <expr>\".\n**\n** If the expression is of the form \"X <op> Y\" where both X and Y are\n** columns, then the original expression is unchanged and a new virtual\n** term of the form \"Y <op> X\" is added to the WHERE clause and\n** analyzed separately.  The original term is marked with TERM_COPIED\n** and the new term is marked with TERM_DYNAMIC (because it's pExpr\n** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it\n** is a commuted copy of a prior term.)  The original term has nChild=1\n** and the copy has idxParent set to the index of the original term.\n*/\nstatic void exprAnalyze(\n  SrcList *pSrc,            /* the FROM clause */\n  WhereClause *pWC,         /* the WHERE clause */\n  int idxTerm               /* Index of the term to be analyzed */\n){\n  WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */\n  WhereTerm *pTerm;                /* The term to be analyzed */\n  WhereMaskSet *pMaskSet;          /* Set of table index masks */\n  Expr *pExpr;                     /* The expression to be analyzed */\n  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */\n  Bitmask prereqAll;               /* Prerequesites of pExpr */\n  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */\n  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */\n  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */\n  int noCase = 0;                  /* uppercase equivalent to lowercase */\n  int op;                          /* Top-level operator.  pExpr->op */\n  Parse *pParse = pWInfo->pParse;  /* Parsing context */\n  sqlite3 *db = pParse->db;        /* Database connection */\n  unsigned char eOp2 = 0;          /* op2 value for LIKE/REGEXP/GLOB */\n  int nLeft;                       /* Number of elements on left side vector */\n\n  if( db->mallocFailed ){\n    return;\n  }\n  pTerm = &pWC->a[idxTerm];\n  pMaskSet = &pWInfo->sMaskSet;\n  pExpr = pTerm->pExpr;\n  assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );\n  prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);\n  op = pExpr->op;\n  if( op==TK_IN ){\n    assert( pExpr->pRight==0 );\n    if( sqlite3ExprCheckIN(pParse, pExpr) ) return;\n    if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n      pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);\n    }else{\n      pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);\n    }\n  }else if( op==TK_ISNULL ){\n    pTerm->prereqRight = 0;\n  }else{\n    pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);\n  }\n  pMaskSet->bVarSelect = 0;\n  prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr);\n  if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;\n  if( ExprHasProperty(pExpr, EP_FromJoin) ){\n    Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);\n    prereqAll |= x;\n    extraRight = x-1;  /* ON clause terms may not be used with an index\n                       ** on left table of a LEFT JOIN.  Ticket #3015 */\n    if( (prereqAll>>1)>=x ){\n      sqlite3ErrorMsg(pParse, \"ON clause references tables to its right\");\n      return;\n    }\n  }\n  pTerm->prereqAll = prereqAll;\n  pTerm->leftCursor = -1;\n  pTerm->iParent = -1;\n  pTerm->eOperator = 0;\n  if( allowedOp(op) ){\n    int aiCurCol[2];\n    Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);\n    Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);\n    u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;\n\n    if( pTerm->iField>0 ){\n      assert( op==TK_IN );\n      assert( pLeft->op==TK_VECTOR );\n      pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;\n    }\n\n    if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){\n      pTerm->leftCursor = aiCurCol[0];\n      pTerm->u.leftColumn = aiCurCol[1];\n      pTerm->eOperator = operatorMask(op) & opMask;\n    }\n    if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;\n    if( pRight \n     && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)\n    ){\n      WhereTerm *pNew;\n      Expr *pDup;\n      u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */\n      assert( pTerm->iField==0 );\n      if( pTerm->leftCursor>=0 ){\n        int idxNew;\n        pDup = sqlite3ExprDup(db, pExpr, 0);\n        if( db->mallocFailed ){\n          sqlite3ExprDelete(db, pDup);\n          return;\n        }\n        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);\n        if( idxNew==0 ) return;\n        pNew = &pWC->a[idxNew];\n        markTermAsChild(pWC, idxNew, idxTerm);\n        if( op==TK_IS ) pNew->wtFlags |= TERM_IS;\n        pTerm = &pWC->a[idxTerm];\n        pTerm->wtFlags |= TERM_COPIED;\n\n        if( termIsEquivalence(pParse, pDup) ){\n          pTerm->eOperator |= WO_EQUIV;\n          eExtraOp = WO_EQUIV;\n        }\n      }else{\n        pDup = pExpr;\n        pNew = pTerm;\n      }\n      pNew->wtFlags |= exprCommute(pParse, pDup);\n      pNew->leftCursor = aiCurCol[0];\n      pNew->u.leftColumn = aiCurCol[1];\n      testcase( (prereqLeft | extraRight) != prereqLeft );\n      pNew->prereqRight = prereqLeft | extraRight;\n      pNew->prereqAll = prereqAll;\n      pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;\n    }\n  }\n\n#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION\n  /* If a term is the BETWEEN operator, create two new virtual terms\n  ** that define the range that the BETWEEN implements.  For example:\n  **\n  **      a BETWEEN b AND c\n  **\n  ** is converted into:\n  **\n  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)\n  **\n  ** The two new terms are added onto the end of the WhereClause object.\n  ** The new terms are \"dynamic\" and are children of the original BETWEEN\n  ** term.  That means that if the BETWEEN term is coded, the children are\n  ** skipped.  Or, if the children are satisfied by an index, the original\n  ** BETWEEN term is skipped.\n  */\n  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){\n    ExprList *pList = pExpr->x.pList;\n    int i;\n    static const u8 ops[] = {TK_GE, TK_LE};\n    assert( pList!=0 );\n    assert( pList->nExpr==2 );\n    for(i=0; i<2; i++){\n      Expr *pNewExpr;\n      int idxNew;\n      pNewExpr = sqlite3PExpr(pParse, ops[i], \n                             sqlite3ExprDup(db, pExpr->pLeft, 0),\n                             sqlite3ExprDup(db, pList->a[i].pExpr, 0));\n      transferJoinMarkings(pNewExpr, pExpr);\n      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);\n      testcase( idxNew==0 );\n      exprAnalyze(pSrc, pWC, idxNew);\n      pTerm = &pWC->a[idxTerm];\n      markTermAsChild(pWC, idxNew, idxTerm);\n    }\n  }\n#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */\n\n#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)\n  /* Analyze a term that is composed of two or more subterms connected by\n  ** an OR operator.\n  */\n  else if( pExpr->op==TK_OR ){\n    assert( pWC->op==TK_AND );\n    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);\n    pTerm = &pWC->a[idxTerm];\n  }\n#endif /* SQLITE_OMIT_OR_OPTIMIZATION */\n\n#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION\n  /* Add constraints to reduce the search space on a LIKE or GLOB\n  ** operator.\n  **\n  ** A like pattern of the form \"x LIKE 'aBc%'\" is changed into constraints\n  **\n  **          x>='ABC' AND x<'abd' AND x LIKE 'aBc%'\n  **\n  ** The last character of the prefix \"abc\" is incremented to form the\n  ** termination condition \"abd\".  If case is not significant (the default\n  ** for LIKE) then the lower-bound is made all uppercase and the upper-\n  ** bound is made all lowercase so that the bounds also work when comparing\n  ** BLOBs.\n  */\n  if( pWC->op==TK_AND \n   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)\n  ){\n    Expr *pLeft;       /* LHS of LIKE/GLOB operator */\n    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */\n    Expr *pNewExpr1;\n    Expr *pNewExpr2;\n    int idxNew1;\n    int idxNew2;\n    const char *zCollSeqName;     /* Name of collating sequence */\n    const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;\n\n    pLeft = pExpr->x.pList->a[1].pExpr;\n    pStr2 = sqlite3ExprDup(db, pStr1, 0);\n\n    /* Convert the lower bound to upper-case and the upper bound to\n    ** lower-case (upper-case is less than lower-case in ASCII) so that\n    ** the range constraints also work for BLOBs\n    */\n    if( noCase && !pParse->db->mallocFailed ){\n      int i;\n      char c;\n      pTerm->wtFlags |= TERM_LIKE;\n      for(i=0; (c = pStr1->u.zToken[i])!=0; i++){\n        pStr1->u.zToken[i] = sqlite3Toupper(c);\n        pStr2->u.zToken[i] = sqlite3Tolower(c);\n      }\n    }\n\n    if( !db->mallocFailed ){\n      u8 c, *pC;       /* Last character before the first wildcard */\n      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];\n      c = *pC;\n      if( noCase ){\n        /* The point is to increment the last character before the first\n        ** wildcard.  But if we increment '@', that will push it into the\n        ** alphabetic range where case conversions will mess up the \n        ** inequality.  To avoid this, make sure to also run the full\n        ** LIKE on all candidate expressions by clearing the isComplete flag\n        */\n        if( c=='A'-1 ) isComplete = 0;\n        c = sqlite3UpperToLower[c];\n      }\n      *pC = c + 1;\n    }\n    zCollSeqName = noCase ? \"NOCASE\" : sqlite3StrBINARY;\n    pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);\n    pNewExpr1 = sqlite3PExpr(pParse, TK_GE,\n           sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),\n           pStr1);\n    transferJoinMarkings(pNewExpr1, pExpr);\n    idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);\n    testcase( idxNew1==0 );\n    exprAnalyze(pSrc, pWC, idxNew1);\n    pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);\n    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,\n           sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),\n           pStr2);\n    transferJoinMarkings(pNewExpr2, pExpr);\n    idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);\n    testcase( idxNew2==0 );\n    exprAnalyze(pSrc, pWC, idxNew2);\n    pTerm = &pWC->a[idxTerm];\n    if( isComplete ){\n      markTermAsChild(pWC, idxNew1, idxTerm);\n      markTermAsChild(pWC, idxNew2, idxTerm);\n    }\n  }\n#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  /* Add a WO_AUX auxiliary term to the constraint set if the\n  ** current expression is of the form \"column OP expr\" where OP\n  ** is an operator that gets passed into virtual tables but which is\n  ** not normally optimized for ordinary tables.  In other words, OP\n  ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.\n  ** This information is used by the xBestIndex methods of\n  ** virtual tables.  The native query optimizer does not attempt\n  ** to do anything with MATCH functions.\n  */\n  if( pWC->op==TK_AND ){\n    Expr *pRight = 0, *pLeft = 0;\n    int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight);\n    while( res-- > 0 ){\n      int idxNew;\n      WhereTerm *pNewTerm;\n      Bitmask prereqColumn, prereqExpr;\n\n      prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);\n      prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);\n      if( (prereqExpr & prereqColumn)==0 ){\n        Expr *pNewExpr;\n        pNewExpr = sqlite3PExpr(pParse, TK_MATCH, \n            0, sqlite3ExprDup(db, pRight, 0));\n        if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){\n          ExprSetProperty(pNewExpr, EP_FromJoin);\n          pNewExpr->iRightJoinTable = pExpr->iRightJoinTable;\n        }\n        idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);\n        testcase( idxNew==0 );\n        pNewTerm = &pWC->a[idxNew];\n        pNewTerm->prereqRight = prereqExpr;\n        pNewTerm->leftCursor = pLeft->iTable;\n        pNewTerm->u.leftColumn = pLeft->iColumn;\n        pNewTerm->eOperator = WO_AUX;\n        pNewTerm->eMatchOp = eOp2;\n        markTermAsChild(pWC, idxNew, idxTerm);\n        pTerm = &pWC->a[idxTerm];\n        pTerm->wtFlags |= TERM_COPIED;\n        pNewTerm->prereqAll = pTerm->prereqAll;\n      }\n      SWAP(Expr*, pLeft, pRight);\n    }\n  }\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n  /* If there is a vector == or IS term - e.g. \"(a, b) == (?, ?)\" - create\n  ** new terms for each component comparison - \"a = ?\" and \"b = ?\".  The\n  ** new terms completely replace the original vector comparison, which is\n  ** no longer used.\n  **\n  ** This is only required if at least one side of the comparison operation\n  ** is not a sub-select.  */\n  if( pWC->op==TK_AND \n  && (pExpr->op==TK_EQ || pExpr->op==TK_IS)\n  && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1\n  && sqlite3ExprVectorSize(pExpr->pRight)==nLeft\n  && ( (pExpr->pLeft->flags & EP_xIsSelect)==0 \n    || (pExpr->pRight->flags & EP_xIsSelect)==0)\n  ){\n    int i;\n    for(i=0; i<nLeft; i++){\n      int idxNew;\n      Expr *pNew;\n      Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);\n      Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);\n\n      pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);\n      transferJoinMarkings(pNew, pExpr);\n      idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);\n      exprAnalyze(pSrc, pWC, idxNew);\n    }\n    pTerm = &pWC->a[idxTerm];\n    pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL;  /* Disable the original */\n    pTerm->eOperator = 0;\n  }\n\n  /* If there is a vector IN term - e.g. \"(a, b) IN (SELECT ...)\" - create\n  ** a virtual term for each vector component. The expression object\n  ** used by each such virtual term is pExpr (the full vector IN(...) \n  ** expression). The WhereTerm.iField variable identifies the index within\n  ** the vector on the LHS that the virtual term represents.\n  **\n  ** This only works if the RHS is a simple SELECT (not a compound) that does\n  ** not use window functions.\n  */\n  if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0\n   && pExpr->pLeft->op==TK_VECTOR\n   && pExpr->x.pSelect->pPrior==0\n#ifndef SQLITE_OMIT_WINDOWFUNC\n   && pExpr->x.pSelect->pWin==0\n#endif\n  ){\n    int i;\n    for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){\n      int idxNew;\n      idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);\n      pWC->a[idxNew].iField = i+1;\n      exprAnalyze(pSrc, pWC, idxNew);\n      markTermAsChild(pWC, idxNew, idxTerm);\n    }\n  }\n\n#ifdef SQLITE_ENABLE_STAT4\n  /* When sqlite_stat4 histogram data is available an operator of the\n  ** form \"x IS NOT NULL\" can sometimes be evaluated more efficiently\n  ** as \"x>NULL\" if x is not an INTEGER PRIMARY KEY.  So construct a\n  ** virtual term of that form.\n  **\n  ** Note that the virtual term must be tagged with TERM_VNULL.\n  */\n  if( pExpr->op==TK_NOTNULL\n   && pExpr->pLeft->op==TK_COLUMN\n   && pExpr->pLeft->iColumn>=0\n   && !ExprHasProperty(pExpr, EP_FromJoin)\n   && OptimizationEnabled(db, SQLITE_Stat4)\n  ){\n    Expr *pNewExpr;\n    Expr *pLeft = pExpr->pLeft;\n    int idxNew;\n    WhereTerm *pNewTerm;\n\n    pNewExpr = sqlite3PExpr(pParse, TK_GT,\n                            sqlite3ExprDup(db, pLeft, 0),\n                            sqlite3ExprAlloc(db, TK_NULL, 0, 0));\n\n    idxNew = whereClauseInsert(pWC, pNewExpr,\n                              TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);\n    if( idxNew ){\n      pNewTerm = &pWC->a[idxNew];\n      pNewTerm->prereqRight = 0;\n      pNewTerm->leftCursor = pLeft->iTable;\n      pNewTerm->u.leftColumn = pLeft->iColumn;\n      pNewTerm->eOperator = WO_GT;\n      markTermAsChild(pWC, idxNew, idxTerm);\n      pTerm = &pWC->a[idxTerm];\n      pTerm->wtFlags |= TERM_COPIED;\n      pNewTerm->prereqAll = pTerm->prereqAll;\n    }\n  }\n#endif /* SQLITE_ENABLE_STAT4 */\n\n  /* Prevent ON clause terms of a LEFT JOIN from being used to drive\n  ** an index for tables to the left of the join.\n  */\n  testcase( pTerm!=&pWC->a[idxTerm] );\n  pTerm = &pWC->a[idxTerm];\n  pTerm->prereqRight |= extraRight;\n}\n\n/***************************************************************************\n** Routines with file scope above.  Interface to the rest of the where.c\n** subsystem follows.\n***************************************************************************/\n\n/*\n** This routine identifies subexpressions in the WHERE clause where\n** each subexpression is separated by the AND operator or some other\n** operator specified in the op parameter.  The WhereClause structure\n** is filled with pointers to subexpressions.  For example:\n**\n**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)\n**           \\________/     \\_______________/     \\________________/\n**            slot[0]            slot[1]               slot[2]\n**\n** The original WHERE clause in pExpr is unaltered.  All this routine\n** does is make slot[] entries point to substructure within pExpr.\n**\n** In the previous sentence and in the diagram, \"slot[]\" refers to\n** the WhereClause.a[] array.  The slot[] array grows as needed to contain\n** all terms of the WHERE clause.\n*/\nSQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){\n  Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pExpr);\n  pWC->op = op;\n  if( pE2==0 ) return;\n  if( pE2->op!=op ){\n    whereClauseInsert(pWC, pExpr, 0);\n  }else{\n    sqlite3WhereSplit(pWC, pE2->pLeft, op);\n    sqlite3WhereSplit(pWC, pE2->pRight, op);\n  }\n}\n\n/*\n** Initialize a preallocated WhereClause structure.\n*/\nSQLITE_PRIVATE void sqlite3WhereClauseInit(\n  WhereClause *pWC,        /* The WhereClause to be initialized */\n  WhereInfo *pWInfo        /* The WHERE processing context */\n){\n  pWC->pWInfo = pWInfo;\n  pWC->hasOr = 0;\n  pWC->pOuter = 0;\n  pWC->nTerm = 0;\n  pWC->nSlot = ArraySize(pWC->aStatic);\n  pWC->a = pWC->aStatic;\n}\n\n/*\n** Deallocate a WhereClause structure.  The WhereClause structure\n** itself is not freed.  This routine is the inverse of\n** sqlite3WhereClauseInit().\n*/\nSQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){\n  int i;\n  WhereTerm *a;\n  sqlite3 *db = pWC->pWInfo->pParse->db;\n  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){\n    if( a->wtFlags & TERM_DYNAMIC ){\n      sqlite3ExprDelete(db, a->pExpr);\n    }\n    if( a->wtFlags & TERM_ORINFO ){\n      whereOrInfoDelete(db, a->u.pOrInfo);\n    }else if( a->wtFlags & TERM_ANDINFO ){\n      whereAndInfoDelete(db, a->u.pAndInfo);\n    }\n  }\n  if( pWC->a!=pWC->aStatic ){\n    sqlite3DbFree(db, pWC->a);\n  }\n}\n\n\n/*\n** These routines walk (recursively) an expression tree and generate\n** a bitmask indicating which tables are used in that expression\n** tree.\n*/\nSQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){\n  Bitmask mask;\n  if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){\n    return sqlite3WhereGetMask(pMaskSet, p->iTable);\n  }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){\n    assert( p->op!=TK_IF_NULL_ROW );\n    return 0;\n  }\n  mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;\n  if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft);\n  if( p->pRight ){\n    mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pRight);\n    assert( p->x.pList==0 );\n  }else if( ExprHasProperty(p, EP_xIsSelect) ){\n    if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;\n    mask |= exprSelectUsage(pMaskSet, p->x.pSelect);\n  }else if( p->x.pList ){\n    mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);\n  }\n#ifndef SQLITE_OMIT_WINDOWFUNC\n  if( (p->op==TK_FUNCTION || p->op==TK_AGG_FUNCTION) && p->y.pWin ){\n    mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pPartition);\n    mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pOrderBy);\n    mask |= sqlite3WhereExprUsage(pMaskSet, p->y.pWin->pFilter);\n  }\n#endif\n  return mask;\n}\nSQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){\n  return p ? sqlite3WhereExprUsageNN(pMaskSet,p) : 0;\n}\nSQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){\n  int i;\n  Bitmask mask = 0;\n  if( pList ){\n    for(i=0; i<pList->nExpr; i++){\n      mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);\n    }\n  }\n  return mask;\n}\n\n\n/*\n** Call exprAnalyze on all terms in a WHERE clause.  \n**\n** Note that exprAnalyze() might add new virtual terms onto the\n** end of the WHERE clause.  We do not want to analyze these new\n** virtual terms, so start analyzing at the end and work forward\n** so that the added virtual terms are never processed.\n*/\nSQLITE_PRIVATE void sqlite3WhereExprAnalyze(\n  SrcList *pTabList,       /* the FROM clause */\n  WhereClause *pWC         /* the WHERE clause to be analyzed */\n){\n  int i;\n  for(i=pWC->nTerm-1; i>=0; i--){\n    exprAnalyze(pTabList, pWC, i);\n  }\n}\n\n/*\n** For table-valued-functions, transform the function arguments into\n** new WHERE clause terms.  \n**\n** Each function argument translates into an equality constraint against\n** a HIDDEN column in the table.\n*/\nSQLITE_PRIVATE void sqlite3WhereTabFuncArgs(\n  Parse *pParse,                    /* Parsing context */\n  struct SrcList_item *pItem,       /* The FROM clause term to process */\n  WhereClause *pWC                  /* Xfer function arguments to here */\n){\n  Table *pTab;\n  int j, k;\n  ExprList *pArgs;\n  Expr *pColRef;\n  Expr *pTerm;\n  if( pItem->fg.isTabFunc==0 ) return;\n  pTab = pItem->pTab;\n  assert( pTab!=0 );\n  pArgs = pItem->u1.pFuncArg;\n  if( pArgs==0 ) return;\n  for(j=k=0; j<pArgs->nExpr; j++){\n    Expr *pRhs;\n    while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}\n    if( k>=pTab->nCol ){\n      sqlite3ErrorMsg(pParse, \"too many arguments on %s() - max %d\",\n                      pTab->zName, j);\n      return;\n    }\n    pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);\n    if( pColRef==0 ) return;\n    pColRef->iTable = pItem->iCursor;\n    pColRef->iColumn = k++;\n    pColRef->y.pTab = pTab;\n    pRhs = sqlite3PExpr(pParse, TK_UPLUS, \n        sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);\n    pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs);\n    if( pItem->fg.jointype & JT_LEFT ){\n      sqlite3SetJoinExpr(pTerm, pItem->iCursor);\n    }\n    whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);\n  }\n}\n\n/************** End of whereexpr.c *******************************************/\n/************** Begin file where.c *******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This module contains C code that generates VDBE code used to process\n** the WHERE clause of SQL statements.  This module is responsible for\n** generating the code that loops through a table looking for applicable\n** rows.  Indices are selected and used to speed the search when doing\n** so is applicable.  Because this module is responsible for selecting\n** indices, you might also think of this module as the \"query optimizer\".\n*/\n/* #include \"sqliteInt.h\" */\n/* #include \"whereInt.h\" */\n\n/*\n** Extra information appended to the end of sqlite3_index_info but not\n** visible to the xBestIndex function, at least not directly.  The\n** sqlite3_vtab_collation() interface knows how to reach it, however.\n**\n** This object is not an API and can be changed from one release to the\n** next.  As long as allocateIndexInfo() and sqlite3_vtab_collation()\n** agree on the structure, all will be well.\n*/\ntypedef struct HiddenIndexInfo HiddenIndexInfo;\nstruct HiddenIndexInfo {\n  WhereClause *pWC;   /* The Where clause being analyzed */\n  Parse *pParse;      /* The parsing context */\n};\n\n/* Forward declaration of methods */\nstatic int whereLoopResize(sqlite3*, WhereLoop*, int);\n\n/* Test variable that can be set to enable WHERE tracing */\n#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)\n/***/ int sqlite3WhereTrace = 0;\n#endif\n\n\n/*\n** Return the estimated number of output rows from a WHERE clause\n*/\nSQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){\n  return pWInfo->nRowOut;\n}\n\n/*\n** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this\n** WHERE clause returns outputs for DISTINCT processing.\n*/\nSQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){\n  return pWInfo->eDistinct;\n}\n\n/*\n** Return TRUE if the WHERE clause returns rows in ORDER BY order.\n** Return FALSE if the output needs to be sorted.\n*/\nSQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){\n  return pWInfo->nOBSat;\n}\n\n/*\n** In the ORDER BY LIMIT optimization, if the inner-most loop is known\n** to emit rows in increasing order, and if the last row emitted by the\n** inner-most loop did not fit within the sorter, then we can skip all\n** subsequent rows for the current iteration of the inner loop (because they\n** will not fit in the sorter either) and continue with the second inner\n** loop - the loop immediately outside the inner-most.\n**\n** When a row does not fit in the sorter (because the sorter already\n** holds LIMIT+OFFSET rows that are smaller), then a jump is made to the\n** label returned by this function.\n**\n** If the ORDER BY LIMIT optimization applies, the jump destination should\n** be the continuation for the second-inner-most loop.  If the ORDER BY\n** LIMIT optimization does not apply, then the jump destination should\n** be the continuation for the inner-most loop.\n**\n** It is always safe for this routine to return the continuation of the\n** inner-most loop, in the sense that a correct answer will result.  \n** Returning the continuation the second inner loop is an optimization\n** that might make the code run a little faster, but should not change\n** the final answer.\n*/\nSQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){\n  WhereLevel *pInner;\n  if( !pWInfo->bOrderedInnerLoop ){\n    /* The ORDER BY LIMIT optimization does not apply.  Jump to the \n    ** continuation of the inner-most loop. */\n    return pWInfo->iContinue;\n  }\n  pInner = &pWInfo->a[pWInfo->nLevel-1];\n  assert( pInner->addrNxt!=0 );\n  return pInner->addrNxt;\n}\n\n/*\n** Return the VDBE address or label to jump to in order to continue\n** immediately with the next row of a WHERE clause.\n*/\nSQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){\n  assert( pWInfo->iContinue!=0 );\n  return pWInfo->iContinue;\n}\n\n/*\n** Return the VDBE address or label to jump to in order to break\n** out of a WHERE loop.\n*/\nSQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){\n  return pWInfo->iBreak;\n}\n\n/*\n** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to\n** operate directly on the rowids returned by a WHERE clause.  Return\n** ONEPASS_SINGLE (1) if the statement can operation directly because only\n** a single row is to be changed.  Return ONEPASS_MULTI (2) if the one-pass\n** optimization can be used on multiple \n**\n** If the ONEPASS optimization is used (if this routine returns true)\n** then also write the indices of open cursors used by ONEPASS\n** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data\n** table and iaCur[1] gets the cursor used by an auxiliary index.\n** Either value may be -1, indicating that cursor is not used.\n** Any cursors returned will have been opened for writing.\n**\n** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is\n** unable to use the ONEPASS optimization.\n*/\nSQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){\n  memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);\n#ifdef WHERETRACE_ENABLED\n  if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){\n    sqlite3DebugPrintf(\"%s cursors: %d %d\\n\",\n         pWInfo->eOnePass==ONEPASS_SINGLE ? \"ONEPASS_SINGLE\" : \"ONEPASS_MULTI\",\n         aiCur[0], aiCur[1]);\n  }\n#endif\n  return pWInfo->eOnePass;\n}\n\n/*\n** Return TRUE if the WHERE loop uses the OP_DeferredSeek opcode to move\n** the data cursor to the row selected by the index cursor.\n*/\nSQLITE_PRIVATE int sqlite3WhereUsesDeferredSeek(WhereInfo *pWInfo){\n  return pWInfo->bDeferredSeek;\n}\n\n/*\n** Move the content of pSrc into pDest\n*/\nstatic void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){\n  pDest->n = pSrc->n;\n  memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));\n}\n\n/*\n** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.\n**\n** The new entry might overwrite an existing entry, or it might be\n** appended, or it might be discarded.  Do whatever is the right thing\n** so that pSet keeps the N_OR_COST best entries seen so far.\n*/\nstatic int whereOrInsert(\n  WhereOrSet *pSet,      /* The WhereOrSet to be updated */\n  Bitmask prereq,        /* Prerequisites of the new entry */\n  LogEst rRun,           /* Run-cost of the new entry */\n  LogEst nOut            /* Number of outputs for the new entry */\n){\n  u16 i;\n  WhereOrCost *p;\n  for(i=pSet->n, p=pSet->a; i>0; i--, p++){\n    if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){\n      goto whereOrInsert_done;\n    }\n    if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){\n      return 0;\n    }\n  }\n  if( pSet->n<N_OR_COST ){\n    p = &pSet->a[pSet->n++];\n    p->nOut = nOut;\n  }else{\n    p = pSet->a;\n    for(i=1; i<pSet->n; i++){\n      if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;\n    }\n    if( p->rRun<=rRun ) return 0;\n  }\nwhereOrInsert_done:\n  p->prereq = prereq;\n  p->rRun = rRun;\n  if( p->nOut>nOut ) p->nOut = nOut;\n  return 1;\n}\n\n/*\n** Return the bitmask for the given cursor number.  Return 0 if\n** iCursor is not in the set.\n*/\nSQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){\n  int i;\n  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );\n  for(i=0; i<pMaskSet->n; i++){\n    if( pMaskSet->ix[i]==iCursor ){\n      return MASKBIT(i);\n    }\n  }\n  return 0;\n}\n\n/*\n** Create a new mask for cursor iCursor.\n**\n** There is one cursor per table in the FROM clause.  The number of\n** tables in the FROM clause is limited by a test early in the\n** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]\n** array will never overflow.\n*/\nstatic void createMask(WhereMaskSet *pMaskSet, int iCursor){\n  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );\n  pMaskSet->ix[pMaskSet->n++] = iCursor;\n}\n\n/*\n** Advance to the next WhereTerm that matches according to the criteria\n** established when the pScan object was initialized by whereScanInit().\n** Return NULL if there are no more matching WhereTerms.\n*/\nstatic WhereTerm *whereScanNext(WhereScan *pScan){\n  int iCur;            /* The cursor on the LHS of the term */\n  i16 iColumn;         /* The column on the LHS of the term.  -1 for IPK */\n  Expr *pX;            /* An expression being tested */\n  WhereClause *pWC;    /* Shorthand for pScan->pWC */\n  WhereTerm *pTerm;    /* The term being tested */\n  int k = pScan->k;    /* Where to start scanning */\n\n  assert( pScan->iEquiv<=pScan->nEquiv );\n  pWC = pScan->pWC;\n  while(1){\n    iColumn = pScan->aiColumn[pScan->iEquiv-1];\n    iCur = pScan->aiCur[pScan->iEquiv-1];\n    assert( pWC!=0 );\n    do{\n      for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){\n        if( pTerm->leftCursor==iCur\n         && pTerm->u.leftColumn==iColumn\n         && (iColumn!=XN_EXPR\n             || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,\n                                       pScan->pIdxExpr,iCur)==0)\n         && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))\n        ){\n          if( (pTerm->eOperator & WO_EQUIV)!=0\n           && pScan->nEquiv<ArraySize(pScan->aiCur)\n           && (pX = sqlite3ExprSkipCollateAndLikely(pTerm->pExpr->pRight))->op\n               ==TK_COLUMN\n          ){\n            int j;\n            for(j=0; j<pScan->nEquiv; j++){\n              if( pScan->aiCur[j]==pX->iTable\n               && pScan->aiColumn[j]==pX->iColumn ){\n                  break;\n              }\n            }\n            if( j==pScan->nEquiv ){\n              pScan->aiCur[j] = pX->iTable;\n              pScan->aiColumn[j] = pX->iColumn;\n              pScan->nEquiv++;\n            }\n          }\n          if( (pTerm->eOperator & pScan->opMask)!=0 ){\n            /* Verify the affinity and collating sequence match */\n            if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){\n              CollSeq *pColl;\n              Parse *pParse = pWC->pWInfo->pParse;\n              pX = pTerm->pExpr;\n              if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){\n                continue;\n              }\n              assert(pX->pLeft);\n              pColl = sqlite3ExprCompareCollSeq(pParse, pX);\n              if( pColl==0 ) pColl = pParse->db->pDfltColl;\n              if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){\n                continue;\n              }\n            }\n            if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0\n             && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN\n             && pX->iTable==pScan->aiCur[0]\n             && pX->iColumn==pScan->aiColumn[0]\n            ){\n              testcase( pTerm->eOperator & WO_IS );\n              continue;\n            }\n            pScan->pWC = pWC;\n            pScan->k = k+1;\n            return pTerm;\n          }\n        }\n      }\n      pWC = pWC->pOuter;\n      k = 0;\n    }while( pWC!=0 );\n    if( pScan->iEquiv>=pScan->nEquiv ) break;\n    pWC = pScan->pOrigWC;\n    k = 0;\n    pScan->iEquiv++;\n  }\n  return 0;\n}\n\n/*\n** This is whereScanInit() for the case of an index on an expression.\n** It is factored out into a separate tail-recursion subroutine so that\n** the normal whereScanInit() routine, which is a high-runner, does not\n** need to push registers onto the stack as part of its prologue.\n*/\nstatic SQLITE_NOINLINE WhereTerm *whereScanInitIndexExpr(WhereScan *pScan){\n  pScan->idxaff = sqlite3ExprAffinity(pScan->pIdxExpr);\n  return whereScanNext(pScan);\n}\n\n/*\n** Initialize a WHERE clause scanner object.  Return a pointer to the\n** first match.  Return NULL if there are no matches.\n**\n** The scanner will be searching the WHERE clause pWC.  It will look\n** for terms of the form \"X <op> <expr>\" where X is column iColumn of table\n** iCur.   Or if pIdx!=0 then X is column iColumn of index pIdx.  pIdx\n** must be one of the indexes of table iCur.\n**\n** The <op> must be one of the operators described by opMask.\n**\n** If the search is for X and the WHERE clause contains terms of the\n** form X=Y then this routine might also return terms of the form\n** \"Y <op> <expr>\".  The number of levels of transitivity is limited,\n** but is enough to handle most commonly occurring SQL statements.\n**\n** If X is not the INTEGER PRIMARY KEY then X must be compatible with\n** index pIdx.\n*/\nstatic WhereTerm *whereScanInit(\n  WhereScan *pScan,       /* The WhereScan object being initialized */\n  WhereClause *pWC,       /* The WHERE clause to be scanned */\n  int iCur,               /* Cursor to scan for */\n  int iColumn,            /* Column to scan for */\n  u32 opMask,             /* Operator(s) to scan for */\n  Index *pIdx             /* Must be compatible with this index */\n){\n  pScan->pOrigWC = pWC;\n  pScan->pWC = pWC;\n  pScan->pIdxExpr = 0;\n  pScan->idxaff = 0;\n  pScan->zCollName = 0;\n  pScan->opMask = opMask;\n  pScan->k = 0;\n  pScan->aiCur[0] = iCur;\n  pScan->nEquiv = 1;\n  pScan->iEquiv = 1;\n  if( pIdx ){\n    int j = iColumn;\n    iColumn = pIdx->aiColumn[j];\n    if( iColumn==XN_EXPR ){\n      pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;\n      pScan->zCollName = pIdx->azColl[j];\n      pScan->aiColumn[0] = XN_EXPR;\n      return whereScanInitIndexExpr(pScan);\n    }else if( iColumn==pIdx->pTable->iPKey ){\n      iColumn = XN_ROWID;\n    }else if( iColumn>=0 ){\n      pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;\n      pScan->zCollName = pIdx->azColl[j];\n    }\n  }else if( iColumn==XN_EXPR ){\n    return 0;\n  }\n  pScan->aiColumn[0] = iColumn;\n  return whereScanNext(pScan);\n}\n\n/*\n** Search for a term in the WHERE clause that is of the form \"X <op> <expr>\"\n** where X is a reference to the iColumn of table iCur or of index pIdx\n** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by\n** the op parameter.  Return a pointer to the term.  Return 0 if not found.\n**\n** If pIdx!=0 then it must be one of the indexes of table iCur.  \n** Search for terms matching the iColumn-th column of pIdx\n** rather than the iColumn-th column of table iCur.\n**\n** The term returned might by Y=<expr> if there is another constraint in\n** the WHERE clause that specifies that X=Y.  Any such constraints will be\n** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The\n** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11\n** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10\n** other equivalent values.  Hence a search for X will return <expr> if X=A1\n** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.\n**\n** If there are multiple terms in the WHERE clause of the form \"X <op> <expr>\"\n** then try for the one with no dependencies on <expr> - in other words where\n** <expr> is a constant expression of some kind.  Only return entries of\n** the form \"X <op> Y\" where Y is a column in another table if no terms of\n** the form \"X <op> <const-expr>\" exist.   If no terms with a constant RHS\n** exist, try to return a term that does not use WO_EQUIV.\n*/\nSQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(\n  WhereClause *pWC,     /* The WHERE clause to be searched */\n  int iCur,             /* Cursor number of LHS */\n  int iColumn,          /* Column number of LHS */\n  Bitmask notReady,     /* RHS must not overlap with this mask */\n  u32 op,               /* Mask of WO_xx values describing operator */\n  Index *pIdx           /* Must be compatible with this index, if not NULL */\n){\n  WhereTerm *pResult = 0;\n  WhereTerm *p;\n  WhereScan scan;\n\n  p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);\n  op &= WO_EQ|WO_IS;\n  while( p ){\n    if( (p->prereqRight & notReady)==0 ){\n      if( p->prereqRight==0 && (p->eOperator&op)!=0 ){\n        testcase( p->eOperator & WO_IS );\n        return p;\n      }\n      if( pResult==0 ) pResult = p;\n    }\n    p = whereScanNext(&scan);\n  }\n  return pResult;\n}\n\n/*\n** This function searches pList for an entry that matches the iCol-th column\n** of index pIdx.\n**\n** If such an expression is found, its index in pList->a[] is returned. If\n** no expression is found, -1 is returned.\n*/\nstatic int findIndexCol(\n  Parse *pParse,                  /* Parse context */\n  ExprList *pList,                /* Expression list to search */\n  int iBase,                      /* Cursor for table associated with pIdx */\n  Index *pIdx,                    /* Index to match column of */\n  int iCol                        /* Column of index to match */\n){\n  int i;\n  const char *zColl = pIdx->azColl[iCol];\n\n  for(i=0; i<pList->nExpr; i++){\n    Expr *p = sqlite3ExprSkipCollateAndLikely(pList->a[i].pExpr);\n    if( p->op==TK_COLUMN\n     && p->iColumn==pIdx->aiColumn[iCol]\n     && p->iTable==iBase\n    ){\n      CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);\n      if( 0==sqlite3StrICmp(pColl->zName, zColl) ){\n        return i;\n      }\n    }\n  }\n\n  return -1;\n}\n\n/*\n** Return TRUE if the iCol-th column of index pIdx is NOT NULL\n*/\nstatic int indexColumnNotNull(Index *pIdx, int iCol){\n  int j;\n  assert( pIdx!=0 );\n  assert( iCol>=0 && iCol<pIdx->nColumn );\n  j = pIdx->aiColumn[iCol];\n  if( j>=0 ){\n    return pIdx->pTable->aCol[j].notNull;\n  }else if( j==(-1) ){\n    return 1;\n  }else{\n    assert( j==(-2) );\n    return 0;  /* Assume an indexed expression can always yield a NULL */\n\n  }\n}\n\n/*\n** Return true if the DISTINCT expression-list passed as the third argument\n** is redundant.\n**\n** A DISTINCT list is redundant if any subset of the columns in the\n** DISTINCT list are collectively unique and individually non-null.\n*/\nstatic int isDistinctRedundant(\n  Parse *pParse,            /* Parsing context */\n  SrcList *pTabList,        /* The FROM clause */\n  WhereClause *pWC,         /* The WHERE clause */\n  ExprList *pDistinct       /* The result set that needs to be DISTINCT */\n){\n  Table *pTab;\n  Index *pIdx;\n  int i;                          \n  int iBase;\n\n  /* If there is more than one table or sub-select in the FROM clause of\n  ** this query, then it will not be possible to show that the DISTINCT \n  ** clause is redundant. */\n  if( pTabList->nSrc!=1 ) return 0;\n  iBase = pTabList->a[0].iCursor;\n  pTab = pTabList->a[0].pTab;\n\n  /* If any of the expressions is an IPK column on table iBase, then return \n  ** true. Note: The (p->iTable==iBase) part of this test may be false if the\n  ** current SELECT is a correlated sub-query.\n  */\n  for(i=0; i<pDistinct->nExpr; i++){\n    Expr *p = sqlite3ExprSkipCollateAndLikely(pDistinct->a[i].pExpr);\n    if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;\n  }\n\n  /* Loop through all indices on the table, checking each to see if it makes\n  ** the DISTINCT qualifier redundant. It does so if:\n  **\n  **   1. The index is itself UNIQUE, and\n  **\n  **   2. All of the columns in the index are either part of the pDistinct\n  **      list, or else the WHERE clause contains a term of the form \"col=X\",\n  **      where X is a constant value. The collation sequences of the\n  **      comparison and select-list expressions must match those of the index.\n  **\n  **   3. All of those index columns for which the WHERE clause does not\n  **      contain a \"col=X\" term are subject to a NOT NULL constraint.\n  */\n  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n    if( !IsUniqueIndex(pIdx) ) continue;\n    for(i=0; i<pIdx->nKeyCol; i++){\n      if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){\n        if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;\n        if( indexColumnNotNull(pIdx, i)==0 ) break;\n      }\n    }\n    if( i==pIdx->nKeyCol ){\n      /* This index implies that the DISTINCT qualifier is redundant. */\n      return 1;\n    }\n  }\n\n  return 0;\n}\n\n\n/*\n** Estimate the logarithm of the input value to base 2.\n*/\nstatic LogEst estLog(LogEst N){\n  return N<=10 ? 0 : sqlite3LogEst(N) - 33;\n}\n\n/*\n** Convert OP_Column opcodes to OP_Copy in previously generated code.\n**\n** This routine runs over generated VDBE code and translates OP_Column\n** opcodes into OP_Copy when the table is being accessed via co-routine \n** instead of via table lookup.\n**\n** If the iAutoidxCur is not zero, then any OP_Rowid instructions on\n** cursor iTabCur are transformed into OP_Sequence opcode for the\n** iAutoidxCur cursor, in order to generate unique rowids for the\n** automatic index being generated.\n*/\nstatic void translateColumnToCopy(\n  Parse *pParse,      /* Parsing context */\n  int iStart,         /* Translate from this opcode to the end */\n  int iTabCur,        /* OP_Column/OP_Rowid references to this table */\n  int iRegister,      /* The first column is in this register */\n  int iAutoidxCur     /* If non-zero, cursor of autoindex being generated */\n){\n  Vdbe *v = pParse->pVdbe;\n  VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);\n  int iEnd = sqlite3VdbeCurrentAddr(v);\n  if( pParse->db->mallocFailed ) return;\n  for(; iStart<iEnd; iStart++, pOp++){\n    if( pOp->p1!=iTabCur ) continue;\n    if( pOp->opcode==OP_Column ){\n      pOp->opcode = OP_Copy;\n      pOp->p1 = pOp->p2 + iRegister;\n      pOp->p2 = pOp->p3;\n      pOp->p3 = 0;\n    }else if( pOp->opcode==OP_Rowid ){\n      if( iAutoidxCur ){\n        pOp->opcode = OP_Sequence;\n        pOp->p1 = iAutoidxCur;\n      }else{\n        pOp->opcode = OP_Null;\n        pOp->p1 = 0;\n        pOp->p3 = 0;\n      }\n    }\n  }\n}\n\n/*\n** Two routines for printing the content of an sqlite3_index_info\n** structure.  Used for testing and debugging only.  If neither\n** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines\n** are no-ops.\n*/\n#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)\nstatic void whereTraceIndexInfoInputs(sqlite3_index_info *p){\n  int i;\n  if( !sqlite3WhereTrace ) return;\n  for(i=0; i<p->nConstraint; i++){\n    sqlite3DebugPrintf(\"  constraint[%d]: col=%d termid=%d op=%d usabled=%d\\n\",\n       i,\n       p->aConstraint[i].iColumn,\n       p->aConstraint[i].iTermOffset,\n       p->aConstraint[i].op,\n       p->aConstraint[i].usable);\n  }\n  for(i=0; i<p->nOrderBy; i++){\n    sqlite3DebugPrintf(\"  orderby[%d]: col=%d desc=%d\\n\",\n       i,\n       p->aOrderBy[i].iColumn,\n       p->aOrderBy[i].desc);\n  }\n}\nstatic void whereTraceIndexInfoOutputs(sqlite3_index_info *p){\n  int i;\n  if( !sqlite3WhereTrace ) return;\n  for(i=0; i<p->nConstraint; i++){\n    sqlite3DebugPrintf(\"  usage[%d]: argvIdx=%d omit=%d\\n\",\n       i,\n       p->aConstraintUsage[i].argvIndex,\n       p->aConstraintUsage[i].omit);\n  }\n  sqlite3DebugPrintf(\"  idxNum=%d\\n\", p->idxNum);\n  sqlite3DebugPrintf(\"  idxStr=%s\\n\", p->idxStr);\n  sqlite3DebugPrintf(\"  orderByConsumed=%d\\n\", p->orderByConsumed);\n  sqlite3DebugPrintf(\"  estimatedCost=%g\\n\", p->estimatedCost);\n  sqlite3DebugPrintf(\"  estimatedRows=%lld\\n\", p->estimatedRows);\n}\n#else\n#define whereTraceIndexInfoInputs(A)\n#define whereTraceIndexInfoOutputs(A)\n#endif\n\n#ifndef SQLITE_OMIT_AUTOMATIC_INDEX\n/*\n** Return TRUE if the WHERE clause term pTerm is of a form where it\n** could be used with an index to access pSrc, assuming an appropriate\n** index existed.\n*/\nstatic int termCanDriveIndex(\n  WhereTerm *pTerm,              /* WHERE clause term to check */\n  struct SrcList_item *pSrc,     /* Table we are trying to access */\n  Bitmask notReady               /* Tables in outer loops of the join */\n){\n  char aff;\n  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;\n  if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;\n  if( (pSrc->fg.jointype & JT_LEFT) \n   && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)\n   && (pTerm->eOperator & WO_IS)\n  ){\n    /* Cannot use an IS term from the WHERE clause as an index driver for\n    ** the RHS of a LEFT JOIN. Such a term can only be used if it is from\n    ** the ON clause.  */\n    return 0;\n  }\n  if( (pTerm->prereqRight & notReady)!=0 ) return 0;\n  if( pTerm->u.leftColumn<0 ) return 0;\n  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;\n  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;\n  testcase( pTerm->pExpr->op==TK_IS );\n  return 1;\n}\n#endif\n\n\n#ifndef SQLITE_OMIT_AUTOMATIC_INDEX\n/*\n** Generate code to construct the Index object for an automatic index\n** and to set up the WhereLevel object pLevel so that the code generator\n** makes use of the automatic index.\n*/\nstatic void constructAutomaticIndex(\n  Parse *pParse,              /* The parsing context */\n  WhereClause *pWC,           /* The WHERE clause */\n  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */\n  Bitmask notReady,           /* Mask of cursors that are not available */\n  WhereLevel *pLevel          /* Write new index here */\n){\n  int nKeyCol;                /* Number of columns in the constructed index */\n  WhereTerm *pTerm;           /* A single term of the WHERE clause */\n  WhereTerm *pWCEnd;          /* End of pWC->a[] */\n  Index *pIdx;                /* Object describing the transient index */\n  Vdbe *v;                    /* Prepared statement under construction */\n  int addrInit;               /* Address of the initialization bypass jump */\n  Table *pTable;              /* The table being indexed */\n  int addrTop;                /* Top of the index fill loop */\n  int regRecord;              /* Register holding an index record */\n  int n;                      /* Column counter */\n  int i;                      /* Loop counter */\n  int mxBitCol;               /* Maximum column in pSrc->colUsed */\n  CollSeq *pColl;             /* Collating sequence to on a column */\n  WhereLoop *pLoop;           /* The Loop object */\n  char *zNotUsed;             /* Extra space on the end of pIdx */\n  Bitmask idxCols;            /* Bitmap of columns used for indexing */\n  Bitmask extraCols;          /* Bitmap of additional columns */\n  u8 sentWarning = 0;         /* True if a warnning has been issued */\n  Expr *pPartial = 0;         /* Partial Index Expression */\n  int iContinue = 0;          /* Jump here to skip excluded rows */\n  struct SrcList_item *pTabItem;  /* FROM clause term being indexed */\n  int addrCounter = 0;        /* Address where integer counter is initialized */\n  int regBase;                /* Array of registers where record is assembled */\n\n  /* Generate code to skip over the creation and initialization of the\n  ** transient index on 2nd and subsequent iterations of the loop. */\n  v = pParse->pVdbe;\n  assert( v!=0 );\n  addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);\n\n  /* Count the number of columns that will be added to the index\n  ** and used to match WHERE clause constraints */\n  nKeyCol = 0;\n  pTable = pSrc->pTab;\n  pWCEnd = &pWC->a[pWC->nTerm];\n  pLoop = pLevel->pWLoop;\n  idxCols = 0;\n  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){\n    Expr *pExpr = pTerm->pExpr;\n    assert( !ExprHasProperty(pExpr, EP_FromJoin)    /* prereq always non-zero */\n         || pExpr->iRightJoinTable!=pSrc->iCursor   /*   for the right-hand   */\n         || pLoop->prereq!=0 );                     /*   table of a LEFT JOIN */\n    if( pLoop->prereq==0\n     && (pTerm->wtFlags & TERM_VIRTUAL)==0\n     && !ExprHasProperty(pExpr, EP_FromJoin)\n     && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){\n      pPartial = sqlite3ExprAnd(pParse, pPartial,\n                                sqlite3ExprDup(pParse->db, pExpr, 0));\n    }\n    if( termCanDriveIndex(pTerm, pSrc, notReady) ){\n      int iCol = pTerm->u.leftColumn;\n      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);\n      testcase( iCol==BMS );\n      testcase( iCol==BMS-1 );\n      if( !sentWarning ){\n        sqlite3_log(SQLITE_WARNING_AUTOINDEX,\n            \"automatic index on %s(%s)\", pTable->zName,\n            pTable->aCol[iCol].zName);\n        sentWarning = 1;\n      }\n      if( (idxCols & cMask)==0 ){\n        if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){\n          goto end_auto_index_create;\n        }\n        pLoop->aLTerm[nKeyCol++] = pTerm;\n        idxCols |= cMask;\n      }\n    }\n  }\n  assert( nKeyCol>0 );\n  pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;\n  pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED\n                     | WHERE_AUTO_INDEX;\n\n  /* Count the number of additional columns needed to create a\n  ** covering index.  A \"covering index\" is an index that contains all\n  ** columns that are needed by the query.  With a covering index, the\n  ** original table never needs to be accessed.  Automatic indices must\n  ** be a covering index because the index will not be updated if the\n  ** original table changes and the index and table cannot both be used\n  ** if they go out of sync.\n  */\n  extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));\n  mxBitCol = MIN(BMS-1,pTable->nCol);\n  testcase( pTable->nCol==BMS-1 );\n  testcase( pTable->nCol==BMS-2 );\n  for(i=0; i<mxBitCol; i++){\n    if( extraCols & MASKBIT(i) ) nKeyCol++;\n  }\n  if( pSrc->colUsed & MASKBIT(BMS-1) ){\n    nKeyCol += pTable->nCol - BMS + 1;\n  }\n\n  /* Construct the Index object to describe this index */\n  pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);\n  if( pIdx==0 ) goto end_auto_index_create;\n  pLoop->u.btree.pIndex = pIdx;\n  pIdx->zName = \"auto-index\";\n  pIdx->pTable = pTable;\n  n = 0;\n  idxCols = 0;\n  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){\n    if( termCanDriveIndex(pTerm, pSrc, notReady) ){\n      int iCol = pTerm->u.leftColumn;\n      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);\n      testcase( iCol==BMS-1 );\n      testcase( iCol==BMS );\n      if( (idxCols & cMask)==0 ){\n        Expr *pX = pTerm->pExpr;\n        idxCols |= cMask;\n        pIdx->aiColumn[n] = pTerm->u.leftColumn;\n        pColl = sqlite3ExprCompareCollSeq(pParse, pX);\n        assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */\n        pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;\n        n++;\n      }\n    }\n  }\n  assert( (u32)n==pLoop->u.btree.nEq );\n\n  /* Add additional columns needed to make the automatic index into\n  ** a covering index */\n  for(i=0; i<mxBitCol; i++){\n    if( extraCols & MASKBIT(i) ){\n      pIdx->aiColumn[n] = i;\n      pIdx->azColl[n] = sqlite3StrBINARY;\n      n++;\n    }\n  }\n  if( pSrc->colUsed & MASKBIT(BMS-1) ){\n    for(i=BMS-1; i<pTable->nCol; i++){\n      pIdx->aiColumn[n] = i;\n      pIdx->azColl[n] = sqlite3StrBINARY;\n      n++;\n    }\n  }\n  assert( n==nKeyCol );\n  pIdx->aiColumn[n] = XN_ROWID;\n  pIdx->azColl[n] = sqlite3StrBINARY;\n\n  /* Create the automatic index */\n  assert( pLevel->iIdxCur>=0 );\n  pLevel->iIdxCur = pParse->nTab++;\n  sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);\n  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);\n  VdbeComment((v, \"for %s\", pTable->zName));\n\n  /* Fill the automatic index with content */\n  pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];\n  if( pTabItem->fg.viaCoroutine ){\n    int regYield = pTabItem->regReturn;\n    addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);\n    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);\n    addrTop =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);\n    VdbeCoverage(v);\n    VdbeComment((v, \"next row of %s\", pTabItem->pTab->zName));\n  }else{\n    addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);\n  }\n  if( pPartial ){\n    iContinue = sqlite3VdbeMakeLabel(pParse);\n    sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);\n    pLoop->wsFlags |= WHERE_PARTIALIDX;\n  }\n  regRecord = sqlite3GetTempReg(pParse);\n  regBase = sqlite3GenerateIndexKey(\n      pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0\n  );\n  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);\n  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);\n  if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);\n  if( pTabItem->fg.viaCoroutine ){\n    sqlite3VdbeChangeP2(v, addrCounter, regBase+n);\n    testcase( pParse->db->mallocFailed );\n    assert( pLevel->iIdxCur>0 );\n    translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,\n                          pTabItem->regResult, pLevel->iIdxCur);\n    sqlite3VdbeGoto(v, addrTop);\n    pTabItem->fg.viaCoroutine = 0;\n  }else{\n    sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);\n    sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);\n  }\n  sqlite3VdbeJumpHere(v, addrTop);\n  sqlite3ReleaseTempReg(pParse, regRecord);\n  \n  /* Jump here when skipping the initialization */\n  sqlite3VdbeJumpHere(v, addrInit);\n\nend_auto_index_create:\n  sqlite3ExprDelete(pParse->db, pPartial);\n}\n#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/*\n** Allocate and populate an sqlite3_index_info structure. It is the \n** responsibility of the caller to eventually release the structure\n** by passing the pointer returned by this function to sqlite3_free().\n*/\nstatic sqlite3_index_info *allocateIndexInfo(\n  Parse *pParse,                  /* The parsing context */\n  WhereClause *pWC,               /* The WHERE clause being analyzed */\n  Bitmask mUnusable,              /* Ignore terms with these prereqs */\n  struct SrcList_item *pSrc,      /* The FROM clause term that is the vtab */\n  ExprList *pOrderBy,             /* The ORDER BY clause */\n  u16 *pmNoOmit                   /* Mask of terms not to omit */\n){\n  int i, j;\n  int nTerm;\n  struct sqlite3_index_constraint *pIdxCons;\n  struct sqlite3_index_orderby *pIdxOrderBy;\n  struct sqlite3_index_constraint_usage *pUsage;\n  struct HiddenIndexInfo *pHidden;\n  WhereTerm *pTerm;\n  int nOrderBy;\n  sqlite3_index_info *pIdxInfo;\n  u16 mNoOmit = 0;\n\n  /* Count the number of possible WHERE clause constraints referring\n  ** to this virtual table */\n  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){\n    if( pTerm->leftCursor != pSrc->iCursor ) continue;\n    if( pTerm->prereqRight & mUnusable ) continue;\n    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );\n    testcase( pTerm->eOperator & WO_IN );\n    testcase( pTerm->eOperator & WO_ISNULL );\n    testcase( pTerm->eOperator & WO_IS );\n    testcase( pTerm->eOperator & WO_ALL );\n    if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;\n    if( pTerm->wtFlags & TERM_VNULL ) continue;\n    assert( pTerm->u.leftColumn>=(-1) );\n    nTerm++;\n  }\n\n  /* If the ORDER BY clause contains only columns in the current \n  ** virtual table then allocate space for the aOrderBy part of\n  ** the sqlite3_index_info structure.\n  */\n  nOrderBy = 0;\n  if( pOrderBy ){\n    int n = pOrderBy->nExpr;\n    for(i=0; i<n; i++){\n      Expr *pExpr = pOrderBy->a[i].pExpr;\n      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;\n      if( pOrderBy->a[i].sortFlags & KEYINFO_ORDER_BIGNULL ) break;\n    }\n    if( i==n){\n      nOrderBy = n;\n    }\n  }\n\n  /* Allocate the sqlite3_index_info structure\n  */\n  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)\n                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm\n                           + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden) );\n  if( pIdxInfo==0 ){\n    sqlite3ErrorMsg(pParse, \"out of memory\");\n    return 0;\n  }\n  pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];\n  pIdxCons = (struct sqlite3_index_constraint*)&pHidden[1];\n  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];\n  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];\n  pIdxInfo->nOrderBy = nOrderBy;\n  pIdxInfo->aConstraint = pIdxCons;\n  pIdxInfo->aOrderBy = pIdxOrderBy;\n  pIdxInfo->aConstraintUsage = pUsage;\n  pHidden->pWC = pWC;\n  pHidden->pParse = pParse;\n  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){\n    u16 op;\n    if( pTerm->leftCursor != pSrc->iCursor ) continue;\n    if( pTerm->prereqRight & mUnusable ) continue;\n    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );\n    testcase( pTerm->eOperator & WO_IN );\n    testcase( pTerm->eOperator & WO_IS );\n    testcase( pTerm->eOperator & WO_ISNULL );\n    testcase( pTerm->eOperator & WO_ALL );\n    if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;\n    if( pTerm->wtFlags & TERM_VNULL ) continue;\n\n    /* tag-20191211-002: WHERE-clause constraints are not useful to the\n    ** right-hand table of a LEFT JOIN.  See tag-20191211-001 for the\n    ** equivalent restriction for ordinary tables. */\n    if( (pSrc->fg.jointype & JT_LEFT)!=0\n     && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)\n    ){\n      continue;\n    }\n    assert( pTerm->u.leftColumn>=(-1) );\n    pIdxCons[j].iColumn = pTerm->u.leftColumn;\n    pIdxCons[j].iTermOffset = i;\n    op = pTerm->eOperator & WO_ALL;\n    if( op==WO_IN ) op = WO_EQ;\n    if( op==WO_AUX ){\n      pIdxCons[j].op = pTerm->eMatchOp;\n    }else if( op & (WO_ISNULL|WO_IS) ){\n      if( op==WO_ISNULL ){\n        pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;\n      }else{\n        pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;\n      }\n    }else{\n      pIdxCons[j].op = (u8)op;\n      /* The direct assignment in the previous line is possible only because\n      ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The\n      ** following asserts verify this fact. */\n      assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );\n      assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );\n      assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );\n      assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );\n      assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );\n      assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );\n\n      if( op & (WO_LT|WO_LE|WO_GT|WO_GE)\n       && sqlite3ExprIsVector(pTerm->pExpr->pRight) \n      ){\n        testcase( j!=i );\n        if( j<16 ) mNoOmit |= (1 << j);\n        if( op==WO_LT ) pIdxCons[j].op = WO_LE;\n        if( op==WO_GT ) pIdxCons[j].op = WO_GE;\n      }\n    }\n\n    j++;\n  }\n  pIdxInfo->nConstraint = j;\n  for(i=0; i<nOrderBy; i++){\n    Expr *pExpr = pOrderBy->a[i].pExpr;\n    pIdxOrderBy[i].iColumn = pExpr->iColumn;\n    pIdxOrderBy[i].desc = pOrderBy->a[i].sortFlags & KEYINFO_ORDER_DESC;\n  }\n\n  *pmNoOmit = mNoOmit;\n  return pIdxInfo;\n}\n\n/*\n** The table object reference passed as the second argument to this function\n** must represent a virtual table. This function invokes the xBestIndex()\n** method of the virtual table with the sqlite3_index_info object that\n** comes in as the 3rd argument to this function.\n**\n** If an error occurs, pParse is populated with an error message and an\n** appropriate error code is returned.  A return of SQLITE_CONSTRAINT from\n** xBestIndex is not considered an error.  SQLITE_CONSTRAINT indicates that\n** the current configuration of \"unusable\" flags in sqlite3_index_info can\n** not result in a valid plan.\n**\n** Whether or not an error is returned, it is the responsibility of the\n** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates\n** that this is required.\n*/\nstatic int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){\n  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;\n  int rc;\n\n  whereTraceIndexInfoInputs(p);\n  rc = pVtab->pModule->xBestIndex(pVtab, p);\n  whereTraceIndexInfoOutputs(p);\n\n  if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){\n    if( rc==SQLITE_NOMEM ){\n      sqlite3OomFault(pParse->db);\n    }else if( !pVtab->zErrMsg ){\n      sqlite3ErrorMsg(pParse, \"%s\", sqlite3ErrStr(rc));\n    }else{\n      sqlite3ErrorMsg(pParse, \"%s\", pVtab->zErrMsg);\n    }\n  }\n  sqlite3_free(pVtab->zErrMsg);\n  pVtab->zErrMsg = 0;\n  return rc;\n}\n#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */\n\n#ifdef SQLITE_ENABLE_STAT4\n/*\n** Estimate the location of a particular key among all keys in an\n** index.  Store the results in aStat as follows:\n**\n**    aStat[0]      Est. number of rows less than pRec\n**    aStat[1]      Est. number of rows equal to pRec\n**\n** Return the index of the sample that is the smallest sample that\n** is greater than or equal to pRec. Note that this index is not an index\n** into the aSample[] array - it is an index into a virtual set of samples\n** based on the contents of aSample[] and the number of fields in record \n** pRec. \n*/\nstatic int whereKeyStats(\n  Parse *pParse,              /* Database connection */\n  Index *pIdx,                /* Index to consider domain of */\n  UnpackedRecord *pRec,       /* Vector of values to consider */\n  int roundUp,                /* Round up if true.  Round down if false */\n  tRowcnt *aStat              /* OUT: stats written here */\n){\n  IndexSample *aSample = pIdx->aSample;\n  int iCol;                   /* Index of required stats in anEq[] etc. */\n  int i;                      /* Index of first sample >= pRec */\n  int iSample;                /* Smallest sample larger than or equal to pRec */\n  int iMin = 0;               /* Smallest sample not yet tested */\n  int iTest;                  /* Next sample to test */\n  int res;                    /* Result of comparison operation */\n  int nField;                 /* Number of fields in pRec */\n  tRowcnt iLower = 0;         /* anLt[] + anEq[] of largest sample pRec is > */\n\n#ifndef SQLITE_DEBUG\n  UNUSED_PARAMETER( pParse );\n#endif\n  assert( pRec!=0 );\n  assert( pIdx->nSample>0 );\n  assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );\n\n  /* Do a binary search to find the first sample greater than or equal\n  ** to pRec. If pRec contains a single field, the set of samples to search\n  ** is simply the aSample[] array. If the samples in aSample[] contain more\n  ** than one fields, all fields following the first are ignored.\n  **\n  ** If pRec contains N fields, where N is more than one, then as well as the\n  ** samples in aSample[] (truncated to N fields), the search also has to\n  ** consider prefixes of those samples. For example, if the set of samples\n  ** in aSample is:\n  **\n  **     aSample[0] = (a, 5) \n  **     aSample[1] = (a, 10) \n  **     aSample[2] = (b, 5) \n  **     aSample[3] = (c, 100) \n  **     aSample[4] = (c, 105)\n  **\n  ** Then the search space should ideally be the samples above and the \n  ** unique prefixes [a], [b] and [c]. But since that is hard to organize, \n  ** the code actually searches this set:\n  **\n  **     0: (a) \n  **     1: (a, 5) \n  **     2: (a, 10) \n  **     3: (a, 10) \n  **     4: (b) \n  **     5: (b, 5) \n  **     6: (c) \n  **     7: (c, 100) \n  **     8: (c, 105)\n  **     9: (c, 105)\n  **\n  ** For each sample in the aSample[] array, N samples are present in the\n  ** effective sample array. In the above, samples 0 and 1 are based on \n  ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.\n  **\n  ** Often, sample i of each block of N effective samples has (i+1) fields.\n  ** Except, each sample may be extended to ensure that it is greater than or\n  ** equal to the previous sample in the array. For example, in the above, \n  ** sample 2 is the first sample of a block of N samples, so at first it \n  ** appears that it should be 1 field in size. However, that would make it \n  ** smaller than sample 1, so the binary search would not work. As a result, \n  ** it is extended to two fields. The duplicates that this creates do not \n  ** cause any problems.\n  */\n  nField = pRec->nField;\n  iCol = 0;\n  iSample = pIdx->nSample * nField;\n  do{\n    int iSamp;                    /* Index in aSample[] of test sample */\n    int n;                        /* Number of fields in test sample */\n\n    iTest = (iMin+iSample)/2;\n    iSamp = iTest / nField;\n    if( iSamp>0 ){\n      /* The proposed effective sample is a prefix of sample aSample[iSamp].\n      ** Specifically, the shortest prefix of at least (1 + iTest%nField) \n      ** fields that is greater than the previous effective sample.  */\n      for(n=(iTest % nField) + 1; n<nField; n++){\n        if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;\n      }\n    }else{\n      n = iTest + 1;\n    }\n\n    pRec->nField = n;\n    res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);\n    if( res<0 ){\n      iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];\n      iMin = iTest+1;\n    }else if( res==0 && n<nField ){\n      iLower = aSample[iSamp].anLt[n-1];\n      iMin = iTest+1;\n      res = -1;\n    }else{\n      iSample = iTest;\n      iCol = n-1;\n    }\n  }while( res && iMin<iSample );\n  i = iSample / nField;\n\n#ifdef SQLITE_DEBUG\n  /* The following assert statements check that the binary search code\n  ** above found the right answer. This block serves no purpose other\n  ** than to invoke the asserts.  */\n  if( pParse->db->mallocFailed==0 ){\n    if( res==0 ){\n      /* If (res==0) is true, then pRec must be equal to sample i. */\n      assert( i<pIdx->nSample );\n      assert( iCol==nField-1 );\n      pRec->nField = nField;\n      assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) \n           || pParse->db->mallocFailed \n      );\n    }else{\n      /* Unless i==pIdx->nSample, indicating that pRec is larger than\n      ** all samples in the aSample[] array, pRec must be smaller than the\n      ** (iCol+1) field prefix of sample i.  */\n      assert( i<=pIdx->nSample && i>=0 );\n      pRec->nField = iCol+1;\n      assert( i==pIdx->nSample \n           || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0\n           || pParse->db->mallocFailed );\n\n      /* if i==0 and iCol==0, then record pRec is smaller than all samples\n      ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must\n      ** be greater than or equal to the (iCol) field prefix of sample i.\n      ** If (i>0), then pRec must also be greater than sample (i-1).  */\n      if( iCol>0 ){\n        pRec->nField = iCol;\n        assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0\n             || pParse->db->mallocFailed );\n      }\n      if( i>0 ){\n        pRec->nField = nField;\n        assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0\n             || pParse->db->mallocFailed );\n      }\n    }\n  }\n#endif /* ifdef SQLITE_DEBUG */\n\n  if( res==0 ){\n    /* Record pRec is equal to sample i */\n    assert( iCol==nField-1 );\n    aStat[0] = aSample[i].anLt[iCol];\n    aStat[1] = aSample[i].anEq[iCol];\n  }else{\n    /* At this point, the (iCol+1) field prefix of aSample[i] is the first \n    ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec\n    ** is larger than all samples in the array. */\n    tRowcnt iUpper, iGap;\n    if( i>=pIdx->nSample ){\n      iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);\n    }else{\n      iUpper = aSample[i].anLt[iCol];\n    }\n\n    if( iLower>=iUpper ){\n      iGap = 0;\n    }else{\n      iGap = iUpper - iLower;\n    }\n    if( roundUp ){\n      iGap = (iGap*2)/3;\n    }else{\n      iGap = iGap/3;\n    }\n    aStat[0] = iLower + iGap;\n    aStat[1] = pIdx->aAvgEq[nField-1];\n  }\n\n  /* Restore the pRec->nField value before returning.  */\n  pRec->nField = nField;\n  return i;\n}\n#endif /* SQLITE_ENABLE_STAT4 */\n\n/*\n** If it is not NULL, pTerm is a term that provides an upper or lower\n** bound on a range scan. Without considering pTerm, it is estimated \n** that the scan will visit nNew rows. This function returns the number\n** estimated to be visited after taking pTerm into account.\n**\n** If the user explicitly specified a likelihood() value for this term,\n** then the return value is the likelihood multiplied by the number of\n** input rows. Otherwise, this function assumes that an \"IS NOT NULL\" term\n** has a likelihood of 0.50, and any other term a likelihood of 0.25.\n*/\nstatic LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){\n  LogEst nRet = nNew;\n  if( pTerm ){\n    if( pTerm->truthProb<=0 ){\n      nRet += pTerm->truthProb;\n    }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){\n      nRet -= 20;        assert( 20==sqlite3LogEst(4) );\n    }\n  }\n  return nRet;\n}\n\n\n#ifdef SQLITE_ENABLE_STAT4\n/*\n** Return the affinity for a single column of an index.\n*/\nSQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){\n  assert( iCol>=0 && iCol<pIdx->nColumn );\n  if( !pIdx->zColAff ){\n    if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;\n  }\n  assert( pIdx->zColAff[iCol]!=0 );\n  return pIdx->zColAff[iCol];\n}\n#endif\n\n\n#ifdef SQLITE_ENABLE_STAT4\n/* \n** This function is called to estimate the number of rows visited by a\n** range-scan on a skip-scan index. For example:\n**\n**   CREATE INDEX i1 ON t1(a, b, c);\n**   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;\n**\n** Value pLoop->nOut is currently set to the estimated number of rows \n** visited for scanning (a=? AND b=?). This function reduces that estimate \n** by some factor to account for the (c BETWEEN ? AND ?) expression based\n** on the stat4 data for the index. this scan will be peformed multiple \n** times (once for each (a,b) combination that matches a=?) is dealt with \n** by the caller.\n**\n** It does this by scanning through all stat4 samples, comparing values\n** extracted from pLower and pUpper with the corresponding column in each\n** sample. If L and U are the number of samples found to be less than or\n** equal to the values extracted from pLower and pUpper respectively, and\n** N is the total number of samples, the pLoop->nOut value is adjusted\n** as follows:\n**\n**   nOut = nOut * ( min(U - L, 1) / N )\n**\n** If pLower is NULL, or a value cannot be extracted from the term, L is\n** set to zero. If pUpper is NULL, or a value cannot be extracted from it,\n** U is set to N.\n**\n** Normally, this function sets *pbDone to 1 before returning. However,\n** if no value can be extracted from either pLower or pUpper (and so the\n** estimate of the number of rows delivered remains unchanged), *pbDone\n** is left as is.\n**\n** If an error occurs, an SQLite error code is returned. Otherwise, \n** SQLITE_OK.\n*/\nstatic int whereRangeSkipScanEst(\n  Parse *pParse,       /* Parsing & code generating context */\n  WhereTerm *pLower,   /* Lower bound on the range. ex: \"x>123\" Might be NULL */\n  WhereTerm *pUpper,   /* Upper bound on the range. ex: \"x<455\" Might be NULL */\n  WhereLoop *pLoop,    /* Update the .nOut value of this loop */\n  int *pbDone          /* Set to true if at least one expr. value extracted */\n){\n  Index *p = pLoop->u.btree.pIndex;\n  int nEq = pLoop->u.btree.nEq;\n  sqlite3 *db = pParse->db;\n  int nLower = -1;\n  int nUpper = p->nSample+1;\n  int rc = SQLITE_OK;\n  u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);\n  CollSeq *pColl;\n  \n  sqlite3_value *p1 = 0;          /* Value extracted from pLower */\n  sqlite3_value *p2 = 0;          /* Value extracted from pUpper */\n  sqlite3_value *pVal = 0;        /* Value extracted from record */\n\n  pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);\n  if( pLower ){\n    rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);\n    nLower = 0;\n  }\n  if( pUpper && rc==SQLITE_OK ){\n    rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);\n    nUpper = p2 ? 0 : p->nSample;\n  }\n\n  if( p1 || p2 ){\n    int i;\n    int nDiff;\n    for(i=0; rc==SQLITE_OK && i<p->nSample; i++){\n      rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);\n      if( rc==SQLITE_OK && p1 ){\n        int res = sqlite3MemCompare(p1, pVal, pColl);\n        if( res>=0 ) nLower++;\n      }\n      if( rc==SQLITE_OK && p2 ){\n        int res = sqlite3MemCompare(p2, pVal, pColl);\n        if( res>=0 ) nUpper++;\n      }\n    }\n    nDiff = (nUpper - nLower);\n    if( nDiff<=0 ) nDiff = 1;\n\n    /* If there is both an upper and lower bound specified, and the \n    ** comparisons indicate that they are close together, use the fallback\n    ** method (assume that the scan visits 1/64 of the rows) for estimating\n    ** the number of rows visited. Otherwise, estimate the number of rows\n    ** using the method described in the header comment for this function. */\n    if( nDiff!=1 || pUpper==0 || pLower==0 ){\n      int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));\n      pLoop->nOut -= nAdjust;\n      *pbDone = 1;\n      WHERETRACE(0x10, (\"range skip-scan regions: %u..%u  adjust=%d est=%d\\n\",\n                           nLower, nUpper, nAdjust*-1, pLoop->nOut));\n    }\n\n  }else{\n    assert( *pbDone==0 );\n  }\n\n  sqlite3ValueFree(p1);\n  sqlite3ValueFree(p2);\n  sqlite3ValueFree(pVal);\n\n  return rc;\n}\n#endif /* SQLITE_ENABLE_STAT4 */\n\n/*\n** This function is used to estimate the number of rows that will be visited\n** by scanning an index for a range of values. The range may have an upper\n** bound, a lower bound, or both. The WHERE clause terms that set the upper\n** and lower bounds are represented by pLower and pUpper respectively. For\n** example, assuming that index p is on t1(a):\n**\n**   ... FROM t1 WHERE a > ? AND a < ? ...\n**                    |_____|   |_____|\n**                       |         |\n**                     pLower    pUpper\n**\n** If either of the upper or lower bound is not present, then NULL is passed in\n** place of the corresponding WhereTerm.\n**\n** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index\n** column subject to the range constraint. Or, equivalently, the number of\n** equality constraints optimized by the proposed index scan. For example,\n** assuming index p is on t1(a, b), and the SQL query is:\n**\n**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...\n**\n** then nEq is set to 1 (as the range restricted column, b, is the second \n** left-most column of the index). Or, if the query is:\n**\n**   ... FROM t1 WHERE a > ? AND a < ? ...\n**\n** then nEq is set to 0.\n**\n** When this function is called, *pnOut is set to the sqlite3LogEst() of the\n** number of rows that the index scan is expected to visit without \n** considering the range constraints. If nEq is 0, then *pnOut is the number of \n** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)\n** to account for the range constraints pLower and pUpper.\n** \n** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be\n** used, a single range inequality reduces the search space by a factor of 4. \n** and a pair of constraints (x>? AND x<?) reduces the expected number of\n** rows visited by a factor of 64.\n*/\nstatic int whereRangeScanEst(\n  Parse *pParse,       /* Parsing & code generating context */\n  WhereLoopBuilder *pBuilder,\n  WhereTerm *pLower,   /* Lower bound on the range. ex: \"x>123\" Might be NULL */\n  WhereTerm *pUpper,   /* Upper bound on the range. ex: \"x<455\" Might be NULL */\n  WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */\n){\n  int rc = SQLITE_OK;\n  int nOut = pLoop->nOut;\n  LogEst nNew;\n\n#ifdef SQLITE_ENABLE_STAT4\n  Index *p = pLoop->u.btree.pIndex;\n  int nEq = pLoop->u.btree.nEq;\n\n  if( p->nSample>0 && ALWAYS(nEq<p->nSampleCol)\n   && OptimizationEnabled(pParse->db, SQLITE_Stat4)\n  ){\n    if( nEq==pBuilder->nRecValid ){\n      UnpackedRecord *pRec = pBuilder->pRec;\n      tRowcnt a[2];\n      int nBtm = pLoop->u.btree.nBtm;\n      int nTop = pLoop->u.btree.nTop;\n\n      /* Variable iLower will be set to the estimate of the number of rows in \n      ** the index that are less than the lower bound of the range query. The\n      ** lower bound being the concatenation of $P and $L, where $P is the\n      ** key-prefix formed by the nEq values matched against the nEq left-most\n      ** columns of the index, and $L is the value in pLower.\n      **\n      ** Or, if pLower is NULL or $L cannot be extracted from it (because it\n      ** is not a simple variable or literal value), the lower bound of the\n      ** range is $P. Due to a quirk in the way whereKeyStats() works, even\n      ** if $L is available, whereKeyStats() is called for both ($P) and \n      ** ($P:$L) and the larger of the two returned values is used.\n      **\n      ** Similarly, iUpper is to be set to the estimate of the number of rows\n      ** less than the upper bound of the range query. Where the upper bound\n      ** is either ($P) or ($P:$U). Again, even if $U is available, both values\n      ** of iUpper are requested of whereKeyStats() and the smaller used.\n      **\n      ** The number of rows between the two bounds is then just iUpper-iLower.\n      */\n      tRowcnt iLower;     /* Rows less than the lower bound */\n      tRowcnt iUpper;     /* Rows less than the upper bound */\n      int iLwrIdx = -2;   /* aSample[] for the lower bound */\n      int iUprIdx = -1;   /* aSample[] for the upper bound */\n\n      if( pRec ){\n        testcase( pRec->nField!=pBuilder->nRecValid );\n        pRec->nField = pBuilder->nRecValid;\n      }\n      /* Determine iLower and iUpper using ($P) only. */\n      if( nEq==0 ){\n        iLower = 0;\n        iUpper = p->nRowEst0;\n      }else{\n        /* Note: this call could be optimized away - since the same values must \n        ** have been requested when testing key $P in whereEqualScanEst().  */\n        whereKeyStats(pParse, p, pRec, 0, a);\n        iLower = a[0];\n        iUpper = a[0] + a[1];\n      }\n\n      assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );\n      assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );\n      assert( p->aSortOrder!=0 );\n      if( p->aSortOrder[nEq] ){\n        /* The roles of pLower and pUpper are swapped for a DESC index */\n        SWAP(WhereTerm*, pLower, pUpper);\n        SWAP(int, nBtm, nTop);\n      }\n\n      /* If possible, improve on the iLower estimate using ($P:$L). */\n      if( pLower ){\n        int n;                    /* Values extracted from pExpr */\n        Expr *pExpr = pLower->pExpr->pRight;\n        rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);\n        if( rc==SQLITE_OK && n ){\n          tRowcnt iNew;\n          u16 mask = WO_GT|WO_LE;\n          if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);\n          iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);\n          iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);\n          if( iNew>iLower ) iLower = iNew;\n          nOut--;\n          pLower = 0;\n        }\n      }\n\n      /* If possible, improve on the iUpper estimate using ($P:$U). */\n      if( pUpper ){\n        int n;                    /* Values extracted from pExpr */\n        Expr *pExpr = pUpper->pExpr->pRight;\n        rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);\n        if( rc==SQLITE_OK && n ){\n          tRowcnt iNew;\n          u16 mask = WO_GT|WO_LE;\n          if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);\n          iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);\n          iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);\n          if( iNew<iUpper ) iUpper = iNew;\n          nOut--;\n          pUpper = 0;\n        }\n      }\n\n      pBuilder->pRec = pRec;\n      if( rc==SQLITE_OK ){\n        if( iUpper>iLower ){\n          nNew = sqlite3LogEst(iUpper - iLower);\n          /* TUNING:  If both iUpper and iLower are derived from the same\n          ** sample, then assume they are 4x more selective.  This brings\n          ** the estimated selectivity more in line with what it would be\n          ** if estimated without the use of STAT4 tables. */\n          if( iLwrIdx==iUprIdx ) nNew -= 20;  assert( 20==sqlite3LogEst(4) );\n        }else{\n          nNew = 10;        assert( 10==sqlite3LogEst(2) );\n        }\n        if( nNew<nOut ){\n          nOut = nNew;\n        }\n        WHERETRACE(0x10, (\"STAT4 range scan: %u..%u  est=%d\\n\",\n                           (u32)iLower, (u32)iUpper, nOut));\n      }\n    }else{\n      int bDone = 0;\n      rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);\n      if( bDone ) return rc;\n    }\n  }\n#else\n  UNUSED_PARAMETER(pParse);\n  UNUSED_PARAMETER(pBuilder);\n  assert( pLower || pUpper );\n#endif\n  assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );\n  nNew = whereRangeAdjust(pLower, nOut);\n  nNew = whereRangeAdjust(pUpper, nNew);\n\n  /* TUNING: If there is both an upper and lower limit and neither limit\n  ** has an application-defined likelihood(), assume the range is\n  ** reduced by an additional 75%. This means that, by default, an open-ended\n  ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the\n  ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to\n  ** match 1/64 of the index. */ \n  if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){\n    nNew -= 20;\n  }\n\n  nOut -= (pLower!=0) + (pUpper!=0);\n  if( nNew<10 ) nNew = 10;\n  if( nNew<nOut ) nOut = nNew;\n#if defined(WHERETRACE_ENABLED)\n  if( pLoop->nOut>nOut ){\n    WHERETRACE(0x10,(\"Range scan lowers nOut from %d to %d\\n\",\n                    pLoop->nOut, nOut));\n  }\n#endif\n  pLoop->nOut = (LogEst)nOut;\n  return rc;\n}\n\n#ifdef SQLITE_ENABLE_STAT4\n/*\n** Estimate the number of rows that will be returned based on\n** an equality constraint x=VALUE and where that VALUE occurs in\n** the histogram data.  This only works when x is the left-most\n** column of an index and sqlite_stat4 histogram data is available\n** for that index.  When pExpr==NULL that means the constraint is\n** \"x IS NULL\" instead of \"x=VALUE\".\n**\n** Write the estimated row count into *pnRow and return SQLITE_OK. \n** If unable to make an estimate, leave *pnRow unchanged and return\n** non-zero.\n**\n** This routine can fail if it is unable to load a collating sequence\n** required for string comparison, or if unable to allocate memory\n** for a UTF conversion required for comparison.  The error is stored\n** in the pParse structure.\n*/\nstatic int whereEqualScanEst(\n  Parse *pParse,       /* Parsing & code generating context */\n  WhereLoopBuilder *pBuilder,\n  Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */\n  tRowcnt *pnRow       /* Write the revised row estimate here */\n){\n  Index *p = pBuilder->pNew->u.btree.pIndex;\n  int nEq = pBuilder->pNew->u.btree.nEq;\n  UnpackedRecord *pRec = pBuilder->pRec;\n  int rc;                   /* Subfunction return code */\n  tRowcnt a[2];             /* Statistics */\n  int bOk;\n\n  assert( nEq>=1 );\n  assert( nEq<=p->nColumn );\n  assert( p->aSample!=0 );\n  assert( p->nSample>0 );\n  assert( pBuilder->nRecValid<nEq );\n\n  /* If values are not available for all fields of the index to the left\n  ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */\n  if( pBuilder->nRecValid<(nEq-1) ){\n    return SQLITE_NOTFOUND;\n  }\n\n  /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()\n  ** below would return the same value.  */\n  if( nEq>=p->nColumn ){\n    *pnRow = 1;\n    return SQLITE_OK;\n  }\n\n  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);\n  pBuilder->pRec = pRec;\n  if( rc!=SQLITE_OK ) return rc;\n  if( bOk==0 ) return SQLITE_NOTFOUND;\n  pBuilder->nRecValid = nEq;\n\n  whereKeyStats(pParse, p, pRec, 0, a);\n  WHERETRACE(0x10,(\"equality scan regions %s(%d): %d\\n\",\n                   p->zName, nEq-1, (int)a[1]));\n  *pnRow = a[1];\n  \n  return rc;\n}\n#endif /* SQLITE_ENABLE_STAT4 */\n\n#ifdef SQLITE_ENABLE_STAT4\n/*\n** Estimate the number of rows that will be returned based on\n** an IN constraint where the right-hand side of the IN operator\n** is a list of values.  Example:\n**\n**        WHERE x IN (1,2,3,4)\n**\n** Write the estimated row count into *pnRow and return SQLITE_OK. \n** If unable to make an estimate, leave *pnRow unchanged and return\n** non-zero.\n**\n** This routine can fail if it is unable to load a collating sequence\n** required for string comparison, or if unable to allocate memory\n** for a UTF conversion required for comparison.  The error is stored\n** in the pParse structure.\n*/\nstatic int whereInScanEst(\n  Parse *pParse,       /* Parsing & code generating context */\n  WhereLoopBuilder *pBuilder,\n  ExprList *pList,     /* The value list on the RHS of \"x IN (v1,v2,v3,...)\" */\n  tRowcnt *pnRow       /* Write the revised row estimate here */\n){\n  Index *p = pBuilder->pNew->u.btree.pIndex;\n  i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);\n  int nRecValid = pBuilder->nRecValid;\n  int rc = SQLITE_OK;     /* Subfunction return code */\n  tRowcnt nEst;           /* Number of rows for a single term */\n  tRowcnt nRowEst = 0;    /* New estimate of the number of rows */\n  int i;                  /* Loop counter */\n\n  assert( p->aSample!=0 );\n  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){\n    nEst = nRow0;\n    rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);\n    nRowEst += nEst;\n    pBuilder->nRecValid = nRecValid;\n  }\n\n  if( rc==SQLITE_OK ){\n    if( nRowEst > nRow0 ) nRowEst = nRow0;\n    *pnRow = nRowEst;\n    WHERETRACE(0x10,(\"IN row estimate: est=%d\\n\", nRowEst));\n  }\n  assert( pBuilder->nRecValid==nRecValid );\n  return rc;\n}\n#endif /* SQLITE_ENABLE_STAT4 */\n\n\n#ifdef WHERETRACE_ENABLED\n/*\n** Print the content of a WhereTerm object\n*/\nSQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){\n  if( pTerm==0 ){\n    sqlite3DebugPrintf(\"TERM-%-3d NULL\\n\", iTerm);\n  }else{\n    char zType[8];\n    char zLeft[50];\n    memcpy(zType, \"....\", 5);\n    if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';\n    if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';\n    if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';\n    if( pTerm->wtFlags & TERM_CODED  ) zType[3] = 'C';\n    if( pTerm->eOperator & WO_SINGLE ){\n      sqlite3_snprintf(sizeof(zLeft),zLeft,\"left={%d:%d}\",\n                       pTerm->leftCursor, pTerm->u.leftColumn);\n    }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){\n      sqlite3_snprintf(sizeof(zLeft),zLeft,\"indexable=0x%lld\", \n                       pTerm->u.pOrInfo->indexable);\n    }else{\n      sqlite3_snprintf(sizeof(zLeft),zLeft,\"left=%d\", pTerm->leftCursor);\n    }\n    sqlite3DebugPrintf(\n       \"TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x\",\n       iTerm, pTerm, zType, zLeft, pTerm->eOperator, pTerm->wtFlags);\n    /* The 0x10000 .wheretrace flag causes extra information to be\n    ** shown about each Term */\n    if( sqlite3WhereTrace & 0x10000 ){\n      sqlite3DebugPrintf(\" prob=%-3d prereq=%llx,%llx\",\n        pTerm->truthProb, (u64)pTerm->prereqAll, (u64)pTerm->prereqRight);\n    }\n    if( pTerm->iField ){\n      sqlite3DebugPrintf(\" iField=%d\", pTerm->iField);\n    }\n    if( pTerm->iParent>=0 ){\n      sqlite3DebugPrintf(\" iParent=%d\", pTerm->iParent);\n    }\n    sqlite3DebugPrintf(\"\\n\");\n    sqlite3TreeViewExpr(0, pTerm->pExpr, 0);\n  }\n}\n#endif\n\n#ifdef WHERETRACE_ENABLED\n/*\n** Show the complete content of a WhereClause\n*/\nSQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){\n  int i;\n  for(i=0; i<pWC->nTerm; i++){\n    sqlite3WhereTermPrint(&pWC->a[i], i);\n  }\n}\n#endif\n\n#ifdef WHERETRACE_ENABLED\n/*\n** Print a WhereLoop object for debugging purposes\n*/\nSQLITE_PRIVATE void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC){\n  WhereInfo *pWInfo = pWC->pWInfo;\n  int nb = 1+(pWInfo->pTabList->nSrc+3)/4;\n  struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;\n  Table *pTab = pItem->pTab;\n  Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;\n  sqlite3DebugPrintf(\"%c%2d.%0*llx.%0*llx\", p->cId,\n                     p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);\n  sqlite3DebugPrintf(\" %12s\",\n                     pItem->zAlias ? pItem->zAlias : pTab->zName);\n  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){\n    const char *zName;\n    if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){\n      if( strncmp(zName, \"sqlite_autoindex_\", 17)==0 ){\n        int i = sqlite3Strlen30(zName) - 1;\n        while( zName[i]!='_' ) i--;\n        zName += i;\n      }\n      sqlite3DebugPrintf(\".%-16s %2d\", zName, p->u.btree.nEq);\n    }else{\n      sqlite3DebugPrintf(\"%20s\",\"\");\n    }\n  }else{\n    char *z;\n    if( p->u.vtab.idxStr ){\n      z = sqlite3_mprintf(\"(%d,\\\"%s\\\",%#x)\",\n                p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);\n    }else{\n      z = sqlite3_mprintf(\"(%d,%x)\", p->u.vtab.idxNum, p->u.vtab.omitMask);\n    }\n    sqlite3DebugPrintf(\" %-19s\", z);\n    sqlite3_free(z);\n  }\n  if( p->wsFlags & WHERE_SKIPSCAN ){\n    sqlite3DebugPrintf(\" f %05x %d-%d\", p->wsFlags, p->nLTerm,p->nSkip);\n  }else{\n    sqlite3DebugPrintf(\" f %05x N %d\", p->wsFlags, p->nLTerm);\n  }\n  sqlite3DebugPrintf(\" cost %d,%d,%d\\n\", p->rSetup, p->rRun, p->nOut);\n  if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){\n    int i;\n    for(i=0; i<p->nLTerm; i++){\n      sqlite3WhereTermPrint(p->aLTerm[i], i);\n    }\n  }\n}\n#endif\n\n/*\n** Convert bulk memory into a valid WhereLoop that can be passed\n** to whereLoopClear harmlessly.\n*/\nstatic void whereLoopInit(WhereLoop *p){\n  p->aLTerm = p->aLTermSpace;\n  p->nLTerm = 0;\n  p->nLSlot = ArraySize(p->aLTermSpace);\n  p->wsFlags = 0;\n}\n\n/*\n** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.\n*/\nstatic void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){\n  if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){\n    if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){\n      sqlite3_free(p->u.vtab.idxStr);\n      p->u.vtab.needFree = 0;\n      p->u.vtab.idxStr = 0;\n    }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){\n      sqlite3DbFree(db, p->u.btree.pIndex->zColAff);\n      sqlite3DbFreeNN(db, p->u.btree.pIndex);\n      p->u.btree.pIndex = 0;\n    }\n  }\n}\n\n/*\n** Deallocate internal memory used by a WhereLoop object\n*/\nstatic void whereLoopClear(sqlite3 *db, WhereLoop *p){\n  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);\n  whereLoopClearUnion(db, p);\n  whereLoopInit(p);\n}\n\n/*\n** Increase the memory allocation for pLoop->aLTerm[] to be at least n.\n*/\nstatic int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){\n  WhereTerm **paNew;\n  if( p->nLSlot>=n ) return SQLITE_OK;\n  n = (n+7)&~7;\n  paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);\n  if( paNew==0 ) return SQLITE_NOMEM_BKPT;\n  memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);\n  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);\n  p->aLTerm = paNew;\n  p->nLSlot = n;\n  return SQLITE_OK;\n}\n\n/*\n** Transfer content from the second pLoop into the first.\n*/\nstatic int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){\n  whereLoopClearUnion(db, pTo);\n  if( whereLoopResize(db, pTo, pFrom->nLTerm) ){\n    memset(&pTo->u, 0, sizeof(pTo->u));\n    return SQLITE_NOMEM_BKPT;\n  }\n  memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);\n  memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));\n  if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){\n    pFrom->u.vtab.needFree = 0;\n  }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){\n    pFrom->u.btree.pIndex = 0;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Delete a WhereLoop object\n*/\nstatic void whereLoopDelete(sqlite3 *db, WhereLoop *p){\n  whereLoopClear(db, p);\n  sqlite3DbFreeNN(db, p);\n}\n\n/*\n** Free a WhereInfo structure\n*/\nstatic void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){\n  int i;\n  assert( pWInfo!=0 );\n  for(i=0; i<pWInfo->nLevel; i++){\n    WhereLevel *pLevel = &pWInfo->a[i];\n    if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){\n      sqlite3DbFree(db, pLevel->u.in.aInLoop);\n    }\n  }\n  sqlite3WhereClauseClear(&pWInfo->sWC);\n  while( pWInfo->pLoops ){\n    WhereLoop *p = pWInfo->pLoops;\n    pWInfo->pLoops = p->pNextLoop;\n    whereLoopDelete(db, p);\n  }\n  assert( pWInfo->pExprMods==0 );\n  sqlite3DbFreeNN(db, pWInfo);\n}\n\n/*\n** Return TRUE if all of the following are true:\n**\n**   (1)  X has the same or lower cost that Y\n**   (2)  X uses fewer WHERE clause terms than Y\n**   (3)  Every WHERE clause term used by X is also used by Y\n**   (4)  X skips at least as many columns as Y\n**   (5)  If X is a covering index, than Y is too\n**\n** Conditions (2) and (3) mean that X is a \"proper subset\" of Y.\n** If X is a proper subset of Y then Y is a better choice and ought\n** to have a lower cost.  This routine returns TRUE when that cost \n** relationship is inverted and needs to be adjusted.  Constraint (4)\n** was added because if X uses skip-scan less than Y it still might\n** deserve a lower cost even if it is a proper subset of Y.  Constraint (5)\n** was added because a covering index probably deserves to have a lower cost\n** than a non-covering index even if it is a proper subset.\n*/\nstatic int whereLoopCheaperProperSubset(\n  const WhereLoop *pX,       /* First WhereLoop to compare */\n  const WhereLoop *pY        /* Compare against this WhereLoop */\n){\n  int i, j;\n  if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){\n    return 0; /* X is not a subset of Y */\n  }\n  if( pY->nSkip > pX->nSkip ) return 0;\n  if( pX->rRun >= pY->rRun ){\n    if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */\n    if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */\n  }\n  for(i=pX->nLTerm-1; i>=0; i--){\n    if( pX->aLTerm[i]==0 ) continue;\n    for(j=pY->nLTerm-1; j>=0; j--){\n      if( pY->aLTerm[j]==pX->aLTerm[i] ) break;\n    }\n    if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */\n  }\n  if( (pX->wsFlags&WHERE_IDX_ONLY)!=0 \n   && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){\n    return 0;  /* Constraint (5) */\n  }\n  return 1;  /* All conditions meet */\n}\n\n/*\n** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so\n** that:\n**\n**   (1) pTemplate costs less than any other WhereLoops that are a proper\n**       subset of pTemplate\n**\n**   (2) pTemplate costs more than any other WhereLoops for which pTemplate\n**       is a proper subset.\n**\n** To say \"WhereLoop X is a proper subset of Y\" means that X uses fewer\n** WHERE clause terms than Y and that every WHERE clause term used by X is\n** also used by Y.\n*/\nstatic void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){\n  if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;\n  for(; p; p=p->pNextLoop){\n    if( p->iTab!=pTemplate->iTab ) continue;\n    if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;\n    if( whereLoopCheaperProperSubset(p, pTemplate) ){\n      /* Adjust pTemplate cost downward so that it is cheaper than its \n      ** subset p. */\n      WHERETRACE(0x80,(\"subset cost adjustment %d,%d to %d,%d\\n\",\n                       pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));\n      pTemplate->rRun = p->rRun;\n      pTemplate->nOut = p->nOut - 1;\n    }else if( whereLoopCheaperProperSubset(pTemplate, p) ){\n      /* Adjust pTemplate cost upward so that it is costlier than p since\n      ** pTemplate is a proper subset of p */\n      WHERETRACE(0x80,(\"subset cost adjustment %d,%d to %d,%d\\n\",\n                       pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));\n      pTemplate->rRun = p->rRun;\n      pTemplate->nOut = p->nOut + 1;\n    }\n  }\n}\n\n/*\n** Search the list of WhereLoops in *ppPrev looking for one that can be\n** replaced by pTemplate.\n**\n** Return NULL if pTemplate does not belong on the WhereLoop list.\n** In other words if pTemplate ought to be dropped from further consideration.\n**\n** If pX is a WhereLoop that pTemplate can replace, then return the\n** link that points to pX.\n**\n** If pTemplate cannot replace any existing element of the list but needs\n** to be added to the list as a new entry, then return a pointer to the\n** tail of the list.\n*/\nstatic WhereLoop **whereLoopFindLesser(\n  WhereLoop **ppPrev,\n  const WhereLoop *pTemplate\n){\n  WhereLoop *p;\n  for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){\n    if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){\n      /* If either the iTab or iSortIdx values for two WhereLoop are different\n      ** then those WhereLoops need to be considered separately.  Neither is\n      ** a candidate to replace the other. */\n      continue;\n    }\n    /* In the current implementation, the rSetup value is either zero\n    ** or the cost of building an automatic index (NlogN) and the NlogN\n    ** is the same for compatible WhereLoops. */\n    assert( p->rSetup==0 || pTemplate->rSetup==0 \n                 || p->rSetup==pTemplate->rSetup );\n\n    /* whereLoopAddBtree() always generates and inserts the automatic index\n    ** case first.  Hence compatible candidate WhereLoops never have a larger\n    ** rSetup. Call this SETUP-INVARIANT */\n    assert( p->rSetup>=pTemplate->rSetup );\n\n    /* Any loop using an appliation-defined index (or PRIMARY KEY or\n    ** UNIQUE constraint) with one or more == constraints is better\n    ** than an automatic index. Unless it is a skip-scan. */\n    if( (p->wsFlags & WHERE_AUTO_INDEX)!=0\n     && (pTemplate->nSkip)==0\n     && (pTemplate->wsFlags & WHERE_INDEXED)!=0\n     && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0\n     && (p->prereq & pTemplate->prereq)==pTemplate->prereq\n    ){\n      break;\n    }\n\n    /* If existing WhereLoop p is better than pTemplate, pTemplate can be\n    ** discarded.  WhereLoop p is better if:\n    **   (1)  p has no more dependencies than pTemplate, and\n    **   (2)  p has an equal or lower cost than pTemplate\n    */\n    if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */\n     && p->rSetup<=pTemplate->rSetup                  /* (2a) */\n     && p->rRun<=pTemplate->rRun                      /* (2b) */\n     && p->nOut<=pTemplate->nOut                      /* (2c) */\n    ){\n      return 0;  /* Discard pTemplate */\n    }\n\n    /* If pTemplate is always better than p, then cause p to be overwritten\n    ** with pTemplate.  pTemplate is better than p if:\n    **   (1)  pTemplate has no more dependences than p, and\n    **   (2)  pTemplate has an equal or lower cost than p.\n    */\n    if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */\n     && p->rRun>=pTemplate->rRun                             /* (2a) */\n     && p->nOut>=pTemplate->nOut                             /* (2b) */\n    ){\n      assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */\n      break;   /* Cause p to be overwritten by pTemplate */\n    }\n  }\n  return ppPrev;\n}\n\n/*\n** Insert or replace a WhereLoop entry using the template supplied.\n**\n** An existing WhereLoop entry might be overwritten if the new template\n** is better and has fewer dependencies.  Or the template will be ignored\n** and no insert will occur if an existing WhereLoop is faster and has\n** fewer dependencies than the template.  Otherwise a new WhereLoop is\n** added based on the template.\n**\n** If pBuilder->pOrSet is not NULL then we care about only the\n** prerequisites and rRun and nOut costs of the N best loops.  That\n** information is gathered in the pBuilder->pOrSet object.  This special\n** processing mode is used only for OR clause processing.\n**\n** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we\n** still might overwrite similar loops with the new template if the\n** new template is better.  Loops may be overwritten if the following \n** conditions are met:\n**\n**    (1)  They have the same iTab.\n**    (2)  They have the same iSortIdx.\n**    (3)  The template has same or fewer dependencies than the current loop\n**    (4)  The template has the same or lower cost than the current loop\n*/\nstatic int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){\n  WhereLoop **ppPrev, *p;\n  WhereInfo *pWInfo = pBuilder->pWInfo;\n  sqlite3 *db = pWInfo->pParse->db;\n  int rc;\n\n  /* Stop the search once we hit the query planner search limit */\n  if( pBuilder->iPlanLimit==0 ){\n    WHERETRACE(0xffffffff,(\"=== query planner search limit reached ===\\n\"));\n    if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0;\n    return SQLITE_DONE;\n  }\n  pBuilder->iPlanLimit--;\n\n  whereLoopAdjustCost(pWInfo->pLoops, pTemplate);\n\n  /* If pBuilder->pOrSet is defined, then only keep track of the costs\n  ** and prereqs.\n  */\n  if( pBuilder->pOrSet!=0 ){\n    if( pTemplate->nLTerm ){\n#if WHERETRACE_ENABLED\n      u16 n = pBuilder->pOrSet->n;\n      int x =\n#endif\n      whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,\n                                    pTemplate->nOut);\n#if WHERETRACE_ENABLED /* 0x8 */\n      if( sqlite3WhereTrace & 0x8 ){\n        sqlite3DebugPrintf(x?\"   or-%d:  \":\"   or-X:  \", n);\n        sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);\n      }\n#endif\n    }\n    return SQLITE_OK;\n  }\n\n  /* Look for an existing WhereLoop to replace with pTemplate\n  */\n  ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);\n\n  if( ppPrev==0 ){\n    /* There already exists a WhereLoop on the list that is better\n    ** than pTemplate, so just ignore pTemplate */\n#if WHERETRACE_ENABLED /* 0x8 */\n    if( sqlite3WhereTrace & 0x8 ){\n      sqlite3DebugPrintf(\"   skip: \");\n      sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);\n    }\n#endif\n    return SQLITE_OK;  \n  }else{\n    p = *ppPrev;\n  }\n\n  /* If we reach this point it means that either p[] should be overwritten\n  ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new\n  ** WhereLoop and insert it.\n  */\n#if WHERETRACE_ENABLED /* 0x8 */\n  if( sqlite3WhereTrace & 0x8 ){\n    if( p!=0 ){\n      sqlite3DebugPrintf(\"replace: \");\n      sqlite3WhereLoopPrint(p, pBuilder->pWC);\n      sqlite3DebugPrintf(\"   with: \");\n    }else{\n      sqlite3DebugPrintf(\"    add: \");\n    }\n    sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);\n  }\n#endif\n  if( p==0 ){\n    /* Allocate a new WhereLoop to add to the end of the list */\n    *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));\n    if( p==0 ) return SQLITE_NOMEM_BKPT;\n    whereLoopInit(p);\n    p->pNextLoop = 0;\n  }else{\n    /* We will be overwriting WhereLoop p[].  But before we do, first\n    ** go through the rest of the list and delete any other entries besides\n    ** p[] that are also supplated by pTemplate */\n    WhereLoop **ppTail = &p->pNextLoop;\n    WhereLoop *pToDel;\n    while( *ppTail ){\n      ppTail = whereLoopFindLesser(ppTail, pTemplate);\n      if( ppTail==0 ) break;\n      pToDel = *ppTail;\n      if( pToDel==0 ) break;\n      *ppTail = pToDel->pNextLoop;\n#if WHERETRACE_ENABLED /* 0x8 */\n      if( sqlite3WhereTrace & 0x8 ){\n        sqlite3DebugPrintf(\" delete: \");\n        sqlite3WhereLoopPrint(pToDel, pBuilder->pWC);\n      }\n#endif\n      whereLoopDelete(db, pToDel);\n    }\n  }\n  rc = whereLoopXfer(db, p, pTemplate);\n  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){\n    Index *pIndex = p->u.btree.pIndex;\n    if( pIndex && pIndex->idxType==SQLITE_IDXTYPE_IPK ){\n      p->u.btree.pIndex = 0;\n    }\n  }\n  return rc;\n}\n\n/*\n** Adjust the WhereLoop.nOut value downward to account for terms of the\n** WHERE clause that reference the loop but which are not used by an\n** index.\n*\n** For every WHERE clause term that is not used by the index\n** and which has a truth probability assigned by one of the likelihood(),\n** likely(), or unlikely() SQL functions, reduce the estimated number\n** of output rows by the probability specified.\n**\n** TUNING:  For every WHERE clause term that is not used by the index\n** and which does not have an assigned truth probability, heuristics\n** described below are used to try to estimate the truth probability.\n** TODO --> Perhaps this is something that could be improved by better\n** table statistics.\n**\n** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%\n** value corresponds to -1 in LogEst notation, so this means decrement\n** the WhereLoop.nOut field for every such WHERE clause term.\n**\n** Heuristic 2:  If there exists one or more WHERE clause terms of the\n** form \"x==EXPR\" and EXPR is not a constant 0 or 1, then make sure the\n** final output row estimate is no greater than 1/4 of the total number\n** of rows in the table.  In other words, assume that x==EXPR will filter\n** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the\n** \"x\" column is boolean or else -1 or 0 or 1 is a common default value\n** on the \"x\" column and so in that case only cap the output row estimate\n** at 1/2 instead of 1/4.\n*/\nstatic void whereLoopOutputAdjust(\n  WhereClause *pWC,      /* The WHERE clause */\n  WhereLoop *pLoop,      /* The loop to adjust downward */\n  LogEst nRow            /* Number of rows in the entire table */\n){\n  WhereTerm *pTerm, *pX;\n  Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);\n  int i, j;\n  LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */\n\n  assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );\n  for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){\n    assert( pTerm!=0 );\n    if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;\n    if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;\n    if( (pTerm->prereqAll & notAllowed)!=0 ) continue;\n    for(j=pLoop->nLTerm-1; j>=0; j--){\n      pX = pLoop->aLTerm[j];\n      if( pX==0 ) continue;\n      if( pX==pTerm ) break;\n      if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;\n    }\n    if( j<0 ){\n      if( pTerm->truthProb<=0 ){\n        /* If a truth probability is specified using the likelihood() hints,\n        ** then use the probability provided by the application. */\n        pLoop->nOut += pTerm->truthProb;\n      }else{\n        /* In the absence of explicit truth probabilities, use heuristics to\n        ** guess a reasonable truth probability. */\n        pLoop->nOut--;\n        if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0\n         && (pTerm->wtFlags & TERM_HIGHTRUTH)==0  /* tag-20200224-1 */\n        ){\n          Expr *pRight = pTerm->pExpr->pRight;\n          int k = 0;\n          testcase( pTerm->pExpr->op==TK_IS );\n          if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){\n            k = 10;\n          }else{\n            k = 20;\n          }\n          if( iReduce<k ){\n            pTerm->wtFlags |= TERM_HEURTRUTH;\n            iReduce = k;\n          }\n        }\n      }\n    }\n  }\n  if( pLoop->nOut > nRow-iReduce )  pLoop->nOut = nRow - iReduce;\n}\n\n/* \n** Term pTerm is a vector range comparison operation. The first comparison\n** in the vector can be optimized using column nEq of the index. This\n** function returns the total number of vector elements that can be used\n** as part of the range comparison.\n**\n** For example, if the query is:\n**\n**   WHERE a = ? AND (b, c, d) > (?, ?, ?)\n**\n** and the index:\n**\n**   CREATE INDEX ... ON (a, b, c, d, e)\n**\n** then this function would be invoked with nEq=1. The value returned in\n** this case is 3.\n*/\nstatic int whereRangeVectorLen(\n  Parse *pParse,       /* Parsing context */\n  int iCur,            /* Cursor open on pIdx */\n  Index *pIdx,         /* The index to be used for a inequality constraint */\n  int nEq,             /* Number of prior equality constraints on same index */\n  WhereTerm *pTerm     /* The vector inequality constraint */\n){\n  int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);\n  int i;\n\n  nCmp = MIN(nCmp, (pIdx->nColumn - nEq));\n  for(i=1; i<nCmp; i++){\n    /* Test if comparison i of pTerm is compatible with column (i+nEq) \n    ** of the index. If not, exit the loop.  */\n    char aff;                     /* Comparison affinity */\n    char idxaff = 0;              /* Indexed columns affinity */\n    CollSeq *pColl;               /* Comparison collation sequence */\n    Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;\n    Expr *pRhs = pTerm->pExpr->pRight;\n    if( pRhs->flags & EP_xIsSelect ){\n      pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;\n    }else{\n      pRhs = pRhs->x.pList->a[i].pExpr;\n    }\n\n    /* Check that the LHS of the comparison is a column reference to\n    ** the right column of the right source table. And that the sort\n    ** order of the index column is the same as the sort order of the\n    ** leftmost index column.  */\n    if( pLhs->op!=TK_COLUMN \n     || pLhs->iTable!=iCur \n     || pLhs->iColumn!=pIdx->aiColumn[i+nEq] \n     || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]\n    ){\n      break;\n    }\n\n    testcase( pLhs->iColumn==XN_ROWID );\n    aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));\n    idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);\n    if( aff!=idxaff ) break;\n\n    pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);\n    if( pColl==0 ) break;\n    if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;\n  }\n  return i;\n}\n\n/*\n** Adjust the cost C by the costMult facter T.  This only occurs if\n** compiled with -DSQLITE_ENABLE_COSTMULT\n*/\n#ifdef SQLITE_ENABLE_COSTMULT\n# define ApplyCostMultiplier(C,T)  C += T\n#else\n# define ApplyCostMultiplier(C,T)\n#endif\n\n/*\n** We have so far matched pBuilder->pNew->u.btree.nEq terms of the \n** index pIndex. Try to match one more.\n**\n** When this function is called, pBuilder->pNew->nOut contains the \n** number of rows expected to be visited by filtering using the nEq \n** terms only. If it is modified, this value is restored before this \n** function returns.\n**\n** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is \n** a fake index used for the INTEGER PRIMARY KEY.\n*/\nstatic int whereLoopAddBtreeIndex(\n  WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */\n  struct SrcList_item *pSrc,      /* FROM clause term being analyzed */\n  Index *pProbe,                  /* An index on pSrc */\n  LogEst nInMul                   /* log(Number of iterations due to IN) */\n){\n  WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */\n  Parse *pParse = pWInfo->pParse;        /* Parsing context */\n  sqlite3 *db = pParse->db;       /* Database connection malloc context */\n  WhereLoop *pNew;                /* Template WhereLoop under construction */\n  WhereTerm *pTerm;               /* A WhereTerm under consideration */\n  int opMask;                     /* Valid operators for constraints */\n  WhereScan scan;                 /* Iterator for WHERE terms */\n  Bitmask saved_prereq;           /* Original value of pNew->prereq */\n  u16 saved_nLTerm;               /* Original value of pNew->nLTerm */\n  u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */\n  u16 saved_nBtm;                 /* Original value of pNew->u.btree.nBtm */\n  u16 saved_nTop;                 /* Original value of pNew->u.btree.nTop */\n  u16 saved_nSkip;                /* Original value of pNew->nSkip */\n  u32 saved_wsFlags;              /* Original value of pNew->wsFlags */\n  LogEst saved_nOut;              /* Original value of pNew->nOut */\n  int rc = SQLITE_OK;             /* Return code */\n  LogEst rSize;                   /* Number of rows in the table */\n  LogEst rLogSize;                /* Logarithm of table size */\n  WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */\n\n  pNew = pBuilder->pNew;\n  if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;\n  WHERETRACE(0x800, (\"BEGIN %s.addBtreeIdx(%s), nEq=%d, nSkip=%d\\n\",\n                     pProbe->pTable->zName,pProbe->zName,\n                     pNew->u.btree.nEq, pNew->nSkip));\n\n  assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );\n  assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );\n  if( pNew->wsFlags & WHERE_BTM_LIMIT ){\n    opMask = WO_LT|WO_LE;\n  }else{\n    assert( pNew->u.btree.nBtm==0 );\n    opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;\n  }\n  if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);\n\n  assert( pNew->u.btree.nEq<pProbe->nColumn );\n\n  saved_nEq = pNew->u.btree.nEq;\n  saved_nBtm = pNew->u.btree.nBtm;\n  saved_nTop = pNew->u.btree.nTop;\n  saved_nSkip = pNew->nSkip;\n  saved_nLTerm = pNew->nLTerm;\n  saved_wsFlags = pNew->wsFlags;\n  saved_prereq = pNew->prereq;\n  saved_nOut = pNew->nOut;\n  pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,\n                        opMask, pProbe);\n  pNew->rSetup = 0;\n  rSize = pProbe->aiRowLogEst[0];\n  rLogSize = estLog(rSize);\n  for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){\n    u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */\n    LogEst rCostIdx;\n    LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */\n    int nIn = 0;\n#ifdef SQLITE_ENABLE_STAT4\n    int nRecValid = pBuilder->nRecValid;\n#endif\n    if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)\n     && indexColumnNotNull(pProbe, saved_nEq)\n    ){\n      continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */\n    }\n    if( pTerm->prereqRight & pNew->maskSelf ) continue;\n\n    /* Do not allow the upper bound of a LIKE optimization range constraint\n    ** to mix with a lower range bound from some other source */\n    if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;\n\n    /* tag-20191211-001:  Do not allow constraints from the WHERE clause to\n    ** be used by the right table of a LEFT JOIN.  Only constraints in the\n    ** ON clause are allowed.  See tag-20191211-002 for the vtab equivalent. */\n    if( (pSrc->fg.jointype & JT_LEFT)!=0\n     && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)\n    ){\n      continue;\n    }\n\n    if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){\n      pBuilder->bldFlags1 |= SQLITE_BLDF1_UNIQUE;\n    }else{\n      pBuilder->bldFlags1 |= SQLITE_BLDF1_INDEXED;\n    }\n    pNew->wsFlags = saved_wsFlags;\n    pNew->u.btree.nEq = saved_nEq;\n    pNew->u.btree.nBtm = saved_nBtm;\n    pNew->u.btree.nTop = saved_nTop;\n    pNew->nLTerm = saved_nLTerm;\n    if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */\n    pNew->aLTerm[pNew->nLTerm++] = pTerm;\n    pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;\n\n    assert( nInMul==0\n        || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0 \n        || (pNew->wsFlags & WHERE_COLUMN_IN)!=0 \n        || (pNew->wsFlags & WHERE_SKIPSCAN)!=0 \n    );\n\n    if( eOp & WO_IN ){\n      Expr *pExpr = pTerm->pExpr;\n      if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n        /* \"x IN (SELECT ...)\":  TUNING: the SELECT returns 25 rows */\n        int i;\n        nIn = 46;  assert( 46==sqlite3LogEst(25) );\n\n        /* The expression may actually be of the form (x, y) IN (SELECT...).\n        ** In this case there is a separate term for each of (x) and (y).\n        ** However, the nIn multiplier should only be applied once, not once\n        ** for each such term. The following loop checks that pTerm is the\n        ** first such term in use, and sets nIn back to 0 if it is not. */\n        for(i=0; i<pNew->nLTerm-1; i++){\n          if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;\n        }\n      }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){\n        /* \"x IN (value, value, ...)\" */\n        nIn = sqlite3LogEst(pExpr->x.pList->nExpr);\n      }\n      if( pProbe->hasStat1 ){\n        LogEst M, logK, safetyMargin;\n        /* Let:\n        **   N = the total number of rows in the table\n        **   K = the number of entries on the RHS of the IN operator\n        **   M = the number of rows in the table that match terms to the \n        **       to the left in the same index.  If the IN operator is on\n        **       the left-most index column, M==N.\n        **\n        ** Given the definitions above, it is better to omit the IN operator\n        ** from the index lookup and instead do a scan of the M elements,\n        ** testing each scanned row against the IN operator separately, if:\n        **\n        **        M*log(K) < K*log(N)\n        **\n        ** Our estimates for M, K, and N might be inaccurate, so we build in\n        ** a safety margin of 2 (LogEst: 10) that favors using the IN operator\n        ** with the index, as using an index has better worst-case behavior.\n        ** If we do not have real sqlite_stat1 data, always prefer to use\n        ** the index.\n        */\n        M = pProbe->aiRowLogEst[saved_nEq];\n        logK = estLog(nIn);\n        safetyMargin = 10;  /* TUNING: extra weight for indexed IN */\n        if( M + logK + safetyMargin < nIn + rLogSize ){\n          WHERETRACE(0x40,\n            (\"Scan preferred over IN operator on column %d of \\\"%s\\\" (%d<%d)\\n\",\n             saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));\n          continue;\n        }else{\n          WHERETRACE(0x40,\n            (\"IN operator preferred on column %d of \\\"%s\\\" (%d>=%d)\\n\",\n             saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));\n        }\n      }\n      pNew->wsFlags |= WHERE_COLUMN_IN;\n    }else if( eOp & (WO_EQ|WO_IS) ){\n      int iCol = pProbe->aiColumn[saved_nEq];\n      pNew->wsFlags |= WHERE_COLUMN_EQ;\n      assert( saved_nEq==pNew->u.btree.nEq );\n      if( iCol==XN_ROWID \n       || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)\n      ){\n        if( iCol==XN_ROWID || pProbe->uniqNotNull \n         || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ) \n        ){\n          pNew->wsFlags |= WHERE_ONEROW;\n        }else{\n          pNew->wsFlags |= WHERE_UNQ_WANTED;\n        }\n      }\n    }else if( eOp & WO_ISNULL ){\n      pNew->wsFlags |= WHERE_COLUMN_NULL;\n    }else if( eOp & (WO_GT|WO_GE) ){\n      testcase( eOp & WO_GT );\n      testcase( eOp & WO_GE );\n      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;\n      pNew->u.btree.nBtm = whereRangeVectorLen(\n          pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm\n      );\n      pBtm = pTerm;\n      pTop = 0;\n      if( pTerm->wtFlags & TERM_LIKEOPT ){\n        /* Range contraints that come from the LIKE optimization are\n        ** always used in pairs. */\n        pTop = &pTerm[1];\n        assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );\n        assert( pTop->wtFlags & TERM_LIKEOPT );\n        assert( pTop->eOperator==WO_LT );\n        if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */\n        pNew->aLTerm[pNew->nLTerm++] = pTop;\n        pNew->wsFlags |= WHERE_TOP_LIMIT;\n        pNew->u.btree.nTop = 1;\n      }\n    }else{\n      assert( eOp & (WO_LT|WO_LE) );\n      testcase( eOp & WO_LT );\n      testcase( eOp & WO_LE );\n      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;\n      pNew->u.btree.nTop = whereRangeVectorLen(\n          pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm\n      );\n      pTop = pTerm;\n      pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?\n                     pNew->aLTerm[pNew->nLTerm-2] : 0;\n    }\n\n    /* At this point pNew->nOut is set to the number of rows expected to\n    ** be visited by the index scan before considering term pTerm, or the\n    ** values of nIn and nInMul. In other words, assuming that all \n    ** \"x IN(...)\" terms are replaced with \"x = ?\". This block updates\n    ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */\n    assert( pNew->nOut==saved_nOut );\n    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){\n      /* Adjust nOut using stat4 data. Or, if there is no stat4\n      ** data, using some other estimate.  */\n      whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);\n    }else{\n      int nEq = ++pNew->u.btree.nEq;\n      assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );\n\n      assert( pNew->nOut==saved_nOut );\n      if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){\n        assert( (eOp & WO_IN) || nIn==0 );\n        testcase( eOp & WO_IN );\n        pNew->nOut += pTerm->truthProb;\n        pNew->nOut -= nIn;\n      }else{\n#ifdef SQLITE_ENABLE_STAT4\n        tRowcnt nOut = 0;\n        if( nInMul==0 \n         && pProbe->nSample \n         && pNew->u.btree.nEq<=pProbe->nSampleCol\n         && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))\n         && OptimizationEnabled(db, SQLITE_Stat4)\n        ){\n          Expr *pExpr = pTerm->pExpr;\n          if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){\n            testcase( eOp & WO_EQ );\n            testcase( eOp & WO_IS );\n            testcase( eOp & WO_ISNULL );\n            rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);\n          }else{\n            rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);\n          }\n          if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;\n          if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */\n          if( nOut ){\n            pNew->nOut = sqlite3LogEst(nOut);\n            if( nEq==1\n             /* TUNING: Mark terms as \"low selectivity\" if they seem likely\n             ** to be true for half or more of the rows in the table.\n             ** See tag-202002240-1 */\n             && pNew->nOut+10 > pProbe->aiRowLogEst[0]\n            ){\n#if WHERETRACE_ENABLED /* 0x01 */\n              if( sqlite3WhereTrace & 0x01 ){\n                sqlite3DebugPrintf(\n                   \"STAT4 determines term has low selectivity:\\n\");\n                sqlite3WhereTermPrint(pTerm, 999);\n              }\n#endif\n              pTerm->wtFlags |= TERM_HIGHTRUTH;\n              if( pTerm->wtFlags & TERM_HEURTRUTH ){\n                /* If the term has previously been used with an assumption of\n                ** higher selectivity, then set the flag to rerun the\n                ** loop computations. */\n                pBuilder->bldFlags2 |= SQLITE_BLDF2_2NDPASS;\n              }\n            }\n            if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;\n            pNew->nOut -= nIn;\n          }\n        }\n        if( nOut==0 )\n#endif\n        {\n          pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);\n          if( eOp & WO_ISNULL ){\n            /* TUNING: If there is no likelihood() value, assume that a \n            ** \"col IS NULL\" expression matches twice as many rows \n            ** as (col=?). */\n            pNew->nOut += 10;\n          }\n        }\n      }\n    }\n\n    /* Set rCostIdx to the cost of visiting selected rows in index. Add\n    ** it to pNew->rRun, which is currently set to the cost of the index\n    ** seek only. Then, if this is a non-covering index, add the cost of\n    ** visiting the rows in the main table.  */\n    assert( pSrc->pTab->szTabRow>0 );\n    rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;\n    pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);\n    if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){\n      pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);\n    }\n    ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);\n\n    nOutUnadjusted = pNew->nOut;\n    pNew->rRun += nInMul + nIn;\n    pNew->nOut += nInMul + nIn;\n    whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);\n    rc = whereLoopInsert(pBuilder, pNew);\n\n    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){\n      pNew->nOut = saved_nOut;\n    }else{\n      pNew->nOut = nOutUnadjusted;\n    }\n\n    if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0\n     && pNew->u.btree.nEq<pProbe->nColumn\n    ){\n      whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);\n    }\n    pNew->nOut = saved_nOut;\n#ifdef SQLITE_ENABLE_STAT4\n    pBuilder->nRecValid = nRecValid;\n#endif\n  }\n  pNew->prereq = saved_prereq;\n  pNew->u.btree.nEq = saved_nEq;\n  pNew->u.btree.nBtm = saved_nBtm;\n  pNew->u.btree.nTop = saved_nTop;\n  pNew->nSkip = saved_nSkip;\n  pNew->wsFlags = saved_wsFlags;\n  pNew->nOut = saved_nOut;\n  pNew->nLTerm = saved_nLTerm;\n\n  /* Consider using a skip-scan if there are no WHERE clause constraints\n  ** available for the left-most terms of the index, and if the average\n  ** number of repeats in the left-most terms is at least 18. \n  **\n  ** The magic number 18 is selected on the basis that scanning 17 rows\n  ** is almost always quicker than an index seek (even though if the index\n  ** contains fewer than 2^17 rows we assume otherwise in other parts of\n  ** the code). And, even if it is not, it should not be too much slower. \n  ** On the other hand, the extra seeks could end up being significantly\n  ** more expensive.  */\n  assert( 42==sqlite3LogEst(18) );\n  if( saved_nEq==saved_nSkip\n   && saved_nEq+1<pProbe->nKeyCol\n   && saved_nEq==pNew->nLTerm\n   && pProbe->noSkipScan==0\n   && pProbe->hasStat1!=0\n   && OptimizationEnabled(db, SQLITE_SkipScan)\n   && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */\n   && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK\n  ){\n    LogEst nIter;\n    pNew->u.btree.nEq++;\n    pNew->nSkip++;\n    pNew->aLTerm[pNew->nLTerm++] = 0;\n    pNew->wsFlags |= WHERE_SKIPSCAN;\n    nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];\n    pNew->nOut -= nIter;\n    /* TUNING:  Because uncertainties in the estimates for skip-scan queries,\n    ** add a 1.375 fudge factor to make skip-scan slightly less likely. */\n    nIter += 5;\n    whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);\n    pNew->nOut = saved_nOut;\n    pNew->u.btree.nEq = saved_nEq;\n    pNew->nSkip = saved_nSkip;\n    pNew->wsFlags = saved_wsFlags;\n  }\n\n  WHERETRACE(0x800, (\"END %s.addBtreeIdx(%s), nEq=%d, rc=%d\\n\",\n                      pProbe->pTable->zName, pProbe->zName, saved_nEq, rc));\n  return rc;\n}\n\n/*\n** Return True if it is possible that pIndex might be useful in\n** implementing the ORDER BY clause in pBuilder.\n**\n** Return False if pBuilder does not contain an ORDER BY clause or\n** if there is no way for pIndex to be useful in implementing that\n** ORDER BY clause.\n*/\nstatic int indexMightHelpWithOrderBy(\n  WhereLoopBuilder *pBuilder,\n  Index *pIndex,\n  int iCursor\n){\n  ExprList *pOB;\n  ExprList *aColExpr;\n  int ii, jj;\n\n  if( pIndex->bUnordered ) return 0;\n  if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;\n  for(ii=0; ii<pOB->nExpr; ii++){\n    Expr *pExpr = sqlite3ExprSkipCollateAndLikely(pOB->a[ii].pExpr);\n    if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){\n      if( pExpr->iColumn<0 ) return 1;\n      for(jj=0; jj<pIndex->nKeyCol; jj++){\n        if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;\n      }\n    }else if( (aColExpr = pIndex->aColExpr)!=0 ){\n      for(jj=0; jj<pIndex->nKeyCol; jj++){\n        if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;\n        if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){\n          return 1;\n        }\n      }\n    }\n  }\n  return 0;\n}\n\n/* Check to see if a partial index with pPartIndexWhere can be used\n** in the current query.  Return true if it can be and false if not.\n*/\nstatic int whereUsablePartialIndex(\n  int iTab,             /* The table for which we want an index */\n  int isLeft,           /* True if iTab is the right table of a LEFT JOIN */\n  WhereClause *pWC,     /* The WHERE clause of the query */\n  Expr *pWhere          /* The WHERE clause from the partial index */\n){\n  int i;\n  WhereTerm *pTerm;\n  Parse *pParse = pWC->pWInfo->pParse;\n  while( pWhere->op==TK_AND ){\n    if( !whereUsablePartialIndex(iTab,isLeft,pWC,pWhere->pLeft) ) return 0;\n    pWhere = pWhere->pRight;\n  }\n  if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;\n  for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){\n    Expr *pExpr;\n    pExpr = pTerm->pExpr;\n    if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)\n     && (isLeft==0 || ExprHasProperty(pExpr, EP_FromJoin))\n     && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab) \n    ){\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/*\n** Add all WhereLoop objects for a single table of the join where the table\n** is identified by pBuilder->pNew->iTab.  That table is guaranteed to be\n** a b-tree table, not a virtual table.\n**\n** The costs (WhereLoop.rRun) of the b-tree loops added by this function\n** are calculated as follows:\n**\n** For a full scan, assuming the table (or index) contains nRow rows:\n**\n**     cost = nRow * 3.0                    // full-table scan\n**     cost = nRow * K                      // scan of covering index\n**     cost = nRow * (K+3.0)                // scan of non-covering index\n**\n** where K is a value between 1.1 and 3.0 set based on the relative \n** estimated average size of the index and table records.\n**\n** For an index scan, where nVisit is the number of index rows visited\n** by the scan, and nSeek is the number of seek operations required on \n** the index b-tree:\n**\n**     cost = nSeek * (log(nRow) + K * nVisit)          // covering index\n**     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index\n**\n** Normally, nSeek is 1. nSeek values greater than 1 come about if the \n** WHERE clause includes \"x IN (....)\" terms used in place of \"x=?\". Or when \n** implicit \"x IN (SELECT x FROM tbl)\" terms are added for skip-scans.\n**\n** The estimated values (nRow, nVisit, nSeek) often contain a large amount\n** of uncertainty.  For this reason, scoring is designed to pick plans that\n** \"do the least harm\" if the estimates are inaccurate.  For example, a\n** log(nRow) factor is omitted from a non-covering index scan in order to\n** bias the scoring in favor of using an index, since the worst-case\n** performance of using an index is far better than the worst-case performance\n** of a full table scan.\n*/\nstatic int whereLoopAddBtree(\n  WhereLoopBuilder *pBuilder, /* WHERE clause information */\n  Bitmask mPrereq             /* Extra prerequesites for using this table */\n){\n  WhereInfo *pWInfo;          /* WHERE analysis context */\n  Index *pProbe;              /* An index we are evaluating */\n  Index sPk;                  /* A fake index object for the primary key */\n  LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */\n  i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */\n  SrcList *pTabList;          /* The FROM clause */\n  struct SrcList_item *pSrc;  /* The FROM clause btree term to add */\n  WhereLoop *pNew;            /* Template WhereLoop object */\n  int rc = SQLITE_OK;         /* Return code */\n  int iSortIdx = 1;           /* Index number */\n  int b;                      /* A boolean value */\n  LogEst rSize;               /* number of rows in the table */\n  LogEst rLogSize;            /* Logarithm of the number of rows in the table */\n  WhereClause *pWC;           /* The parsed WHERE clause */\n  Table *pTab;                /* Table being queried */\n  \n  pNew = pBuilder->pNew;\n  pWInfo = pBuilder->pWInfo;\n  pTabList = pWInfo->pTabList;\n  pSrc = pTabList->a + pNew->iTab;\n  pTab = pSrc->pTab;\n  pWC = pBuilder->pWC;\n  assert( !IsVirtual(pSrc->pTab) );\n\n  if( pSrc->pIBIndex ){\n    /* An INDEXED BY clause specifies a particular index to use */\n    pProbe = pSrc->pIBIndex;\n  }else if( !HasRowid(pTab) ){\n    pProbe = pTab->pIndex;\n  }else{\n    /* There is no INDEXED BY clause.  Create a fake Index object in local\n    ** variable sPk to represent the rowid primary key index.  Make this\n    ** fake index the first in a chain of Index objects with all of the real\n    ** indices to follow */\n    Index *pFirst;                  /* First of real indices on the table */\n    memset(&sPk, 0, sizeof(Index));\n    sPk.nKeyCol = 1;\n    sPk.nColumn = 1;\n    sPk.aiColumn = &aiColumnPk;\n    sPk.aiRowLogEst = aiRowEstPk;\n    sPk.onError = OE_Replace;\n    sPk.pTable = pTab;\n    sPk.szIdxRow = pTab->szTabRow;\n    sPk.idxType = SQLITE_IDXTYPE_IPK;\n    aiRowEstPk[0] = pTab->nRowLogEst;\n    aiRowEstPk[1] = 0;\n    pFirst = pSrc->pTab->pIndex;\n    if( pSrc->fg.notIndexed==0 ){\n      /* The real indices of the table are only considered if the\n      ** NOT INDEXED qualifier is omitted from the FROM clause */\n      sPk.pNext = pFirst;\n    }\n    pProbe = &sPk;\n  }\n  rSize = pTab->nRowLogEst;\n  rLogSize = estLog(rSize);\n\n#ifndef SQLITE_OMIT_AUTOMATIC_INDEX\n  /* Automatic indexes */\n  if( !pBuilder->pOrSet      /* Not part of an OR optimization */\n   && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0\n   && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0\n   && pSrc->pIBIndex==0      /* Has no INDEXED BY clause */\n   && !pSrc->fg.notIndexed   /* Has no NOT INDEXED clause */\n   && HasRowid(pTab)         /* Not WITHOUT ROWID table. (FIXME: Why not?) */\n   && !pSrc->fg.isCorrelated /* Not a correlated subquery */\n   && !pSrc->fg.isRecursive  /* Not a recursive common table expression. */\n  ){\n    /* Generate auto-index WhereLoops */\n    WhereTerm *pTerm;\n    WhereTerm *pWCEnd = pWC->a + pWC->nTerm;\n    for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){\n      if( pTerm->prereqRight & pNew->maskSelf ) continue;\n      if( termCanDriveIndex(pTerm, pSrc, 0) ){\n        pNew->u.btree.nEq = 1;\n        pNew->nSkip = 0;\n        pNew->u.btree.pIndex = 0;\n        pNew->nLTerm = 1;\n        pNew->aLTerm[0] = pTerm;\n        /* TUNING: One-time cost for computing the automatic index is\n        ** estimated to be X*N*log2(N) where N is the number of rows in\n        ** the table being indexed and where X is 7 (LogEst=28) for normal\n        ** tables or 0.5 (LogEst=-10) for views and subqueries.  The value\n        ** of X is smaller for views and subqueries so that the query planner\n        ** will be more aggressive about generating automatic indexes for\n        ** those objects, since there is no opportunity to add schema\n        ** indexes on subqueries and views. */\n        pNew->rSetup = rLogSize + rSize;\n        if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){\n          pNew->rSetup += 28;\n        }else{\n          pNew->rSetup -= 10;\n        }\n        ApplyCostMultiplier(pNew->rSetup, pTab->costMult);\n        if( pNew->rSetup<0 ) pNew->rSetup = 0;\n        /* TUNING: Each index lookup yields 20 rows in the table.  This\n        ** is more than the usual guess of 10 rows, since we have no way\n        ** of knowing how selective the index will ultimately be.  It would\n        ** not be unreasonable to make this value much larger. */\n        pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );\n        pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);\n        pNew->wsFlags = WHERE_AUTO_INDEX;\n        pNew->prereq = mPrereq | pTerm->prereqRight;\n        rc = whereLoopInsert(pBuilder, pNew);\n      }\n    }\n  }\n#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */\n\n  /* Loop over all indices. If there was an INDEXED BY clause, then only \n  ** consider index pProbe.  */\n  for(; rc==SQLITE_OK && pProbe; \n      pProbe=(pSrc->pIBIndex ? 0 : pProbe->pNext), iSortIdx++\n  ){\n    int isLeft = (pSrc->fg.jointype & JT_OUTER)!=0;\n    if( pProbe->pPartIdxWhere!=0\n     && !whereUsablePartialIndex(pSrc->iCursor, isLeft, pWC,\n                                 pProbe->pPartIdxWhere)\n    ){\n      testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */\n      continue;  /* Partial index inappropriate for this query */\n    }\n    if( pProbe->bNoQuery ) continue;\n    rSize = pProbe->aiRowLogEst[0];\n    pNew->u.btree.nEq = 0;\n    pNew->u.btree.nBtm = 0;\n    pNew->u.btree.nTop = 0;\n    pNew->nSkip = 0;\n    pNew->nLTerm = 0;\n    pNew->iSortIdx = 0;\n    pNew->rSetup = 0;\n    pNew->prereq = mPrereq;\n    pNew->nOut = rSize;\n    pNew->u.btree.pIndex = pProbe;\n    b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);\n    /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */\n    assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );\n    if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){\n      /* Integer primary key index */\n      pNew->wsFlags = WHERE_IPK;\n\n      /* Full table scan */\n      pNew->iSortIdx = b ? iSortIdx : 0;\n      /* TUNING: Cost of full table scan is (N*3.0). */\n      pNew->rRun = rSize + 16;\n      ApplyCostMultiplier(pNew->rRun, pTab->costMult);\n      whereLoopOutputAdjust(pWC, pNew, rSize);\n      rc = whereLoopInsert(pBuilder, pNew);\n      pNew->nOut = rSize;\n      if( rc ) break;\n    }else{\n      Bitmask m;\n      if( pProbe->isCovering ){\n        pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;\n        m = 0;\n      }else{\n        m = pSrc->colUsed & pProbe->colNotIdxed;\n        pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;\n      }\n\n      /* Full scan via index */\n      if( b\n       || !HasRowid(pTab)\n       || pProbe->pPartIdxWhere!=0\n       || ( m==0\n         && pProbe->bUnordered==0\n         && (pProbe->szIdxRow<pTab->szTabRow)\n         && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0\n         && sqlite3GlobalConfig.bUseCis\n         && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)\n          )\n      ){\n        pNew->iSortIdx = b ? iSortIdx : 0;\n\n        /* The cost of visiting the index rows is N*K, where K is\n        ** between 1.1 and 3.0, depending on the relative sizes of the\n        ** index and table rows. */\n        pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;\n        if( m!=0 ){\n          /* If this is a non-covering index scan, add in the cost of\n          ** doing table lookups.  The cost will be 3x the number of\n          ** lookups.  Take into account WHERE clause terms that can be\n          ** satisfied using just the index, and that do not require a\n          ** table lookup. */\n          LogEst nLookup = rSize + 16;  /* Base cost:  N*3 */\n          int ii;\n          int iCur = pSrc->iCursor;\n          WhereClause *pWC2 = &pWInfo->sWC;\n          for(ii=0; ii<pWC2->nTerm; ii++){\n            WhereTerm *pTerm = &pWC2->a[ii];\n            if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){\n              break;\n            }\n            /* pTerm can be evaluated using just the index.  So reduce\n            ** the expected number of table lookups accordingly */\n            if( pTerm->truthProb<=0 ){\n              nLookup += pTerm->truthProb;\n            }else{\n              nLookup--;\n              if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;\n            }\n          }\n          \n          pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);\n        }\n        ApplyCostMultiplier(pNew->rRun, pTab->costMult);\n        whereLoopOutputAdjust(pWC, pNew, rSize);\n        rc = whereLoopInsert(pBuilder, pNew);\n        pNew->nOut = rSize;\n        if( rc ) break;\n      }\n    }\n\n    pBuilder->bldFlags1 = 0;\n    rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);\n    if( pBuilder->bldFlags1==SQLITE_BLDF1_INDEXED ){\n      /* If a non-unique index is used, or if a prefix of the key for\n      ** unique index is used (making the index functionally non-unique)\n      ** then the sqlite_stat1 data becomes important for scoring the\n      ** plan */\n      pTab->tabFlags |= TF_StatsUsed;\n    }\n#ifdef SQLITE_ENABLE_STAT4\n    sqlite3Stat4ProbeFree(pBuilder->pRec);\n    pBuilder->nRecValid = 0;\n    pBuilder->pRec = 0;\n#endif\n  }\n  return rc;\n}\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n\n/*\n** Argument pIdxInfo is already populated with all constraints that may\n** be used by the virtual table identified by pBuilder->pNew->iTab. This\n** function marks a subset of those constraints usable, invokes the\n** xBestIndex method and adds the returned plan to pBuilder.\n**\n** A constraint is marked usable if:\n**\n**   * Argument mUsable indicates that its prerequisites are available, and\n**\n**   * It is not one of the operators specified in the mExclude mask passed\n**     as the fourth argument (which in practice is either WO_IN or 0).\n**\n** Argument mPrereq is a mask of tables that must be scanned before the\n** virtual table in question. These are added to the plans prerequisites\n** before it is added to pBuilder.\n**\n** Output parameter *pbIn is set to true if the plan added to pBuilder\n** uses one or more WO_IN terms, or false otherwise.\n*/\nstatic int whereLoopAddVirtualOne(\n  WhereLoopBuilder *pBuilder,\n  Bitmask mPrereq,                /* Mask of tables that must be used. */\n  Bitmask mUsable,                /* Mask of usable tables */\n  u16 mExclude,                   /* Exclude terms using these operators */\n  sqlite3_index_info *pIdxInfo,   /* Populated object for xBestIndex */\n  u16 mNoOmit,                    /* Do not omit these constraints */\n  int *pbIn                       /* OUT: True if plan uses an IN(...) op */\n){\n  WhereClause *pWC = pBuilder->pWC;\n  struct sqlite3_index_constraint *pIdxCons;\n  struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;\n  int i;\n  int mxTerm;\n  int rc = SQLITE_OK;\n  WhereLoop *pNew = pBuilder->pNew;\n  Parse *pParse = pBuilder->pWInfo->pParse;\n  struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];\n  int nConstraint = pIdxInfo->nConstraint;\n\n  assert( (mUsable & mPrereq)==mPrereq );\n  *pbIn = 0;\n  pNew->prereq = mPrereq;\n\n  /* Set the usable flag on the subset of constraints identified by \n  ** arguments mUsable and mExclude. */\n  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;\n  for(i=0; i<nConstraint; i++, pIdxCons++){\n    WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];\n    pIdxCons->usable = 0;\n    if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight \n     && (pTerm->eOperator & mExclude)==0\n    ){\n      pIdxCons->usable = 1;\n    }\n  }\n\n  /* Initialize the output fields of the sqlite3_index_info structure */\n  memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);\n  assert( pIdxInfo->needToFreeIdxStr==0 );\n  pIdxInfo->idxStr = 0;\n  pIdxInfo->idxNum = 0;\n  pIdxInfo->orderByConsumed = 0;\n  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;\n  pIdxInfo->estimatedRows = 25;\n  pIdxInfo->idxFlags = 0;\n  pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;\n\n  /* Invoke the virtual table xBestIndex() method */\n  rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);\n  if( rc ){\n    if( rc==SQLITE_CONSTRAINT ){\n      /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means\n      ** that the particular combination of parameters provided is unusable.\n      ** Make no entries in the loop table.\n      */\n      WHERETRACE(0xffff, (\"  ^^^^--- non-viable plan rejected!\\n\"));\n      return SQLITE_OK;\n    }\n    return rc;\n  }\n\n  mxTerm = -1;\n  assert( pNew->nLSlot>=nConstraint );\n  for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;\n  pNew->u.vtab.omitMask = 0;\n  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;\n  for(i=0; i<nConstraint; i++, pIdxCons++){\n    int iTerm;\n    if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){\n      WhereTerm *pTerm;\n      int j = pIdxCons->iTermOffset;\n      if( iTerm>=nConstraint\n       || j<0\n       || j>=pWC->nTerm\n       || pNew->aLTerm[iTerm]!=0\n       || pIdxCons->usable==0\n      ){\n        sqlite3ErrorMsg(pParse,\"%s.xBestIndex malfunction\",pSrc->pTab->zName);\n        testcase( pIdxInfo->needToFreeIdxStr );\n        return SQLITE_ERROR;\n      }\n      testcase( iTerm==nConstraint-1 );\n      testcase( j==0 );\n      testcase( j==pWC->nTerm-1 );\n      pTerm = &pWC->a[j];\n      pNew->prereq |= pTerm->prereqRight;\n      assert( iTerm<pNew->nLSlot );\n      pNew->aLTerm[iTerm] = pTerm;\n      if( iTerm>mxTerm ) mxTerm = iTerm;\n      testcase( iTerm==15 );\n      testcase( iTerm==16 );\n      if( pUsage[i].omit ){\n        if( i<16 && ((1<<i)&mNoOmit)==0 ){\n          testcase( i!=iTerm );\n          pNew->u.vtab.omitMask |= 1<<iTerm;\n        }else{\n          testcase( i!=iTerm );\n        }\n      }\n      if( (pTerm->eOperator & WO_IN)!=0 ){\n        /* A virtual table that is constrained by an IN clause may not\n        ** consume the ORDER BY clause because (1) the order of IN terms\n        ** is not necessarily related to the order of output terms and\n        ** (2) Multiple outputs from a single IN value will not merge\n        ** together.  */\n        pIdxInfo->orderByConsumed = 0;\n        pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;\n        *pbIn = 1; assert( (mExclude & WO_IN)==0 );\n      }\n    }\n  }\n\n  pNew->nLTerm = mxTerm+1;\n  for(i=0; i<=mxTerm; i++){\n    if( pNew->aLTerm[i]==0 ){\n      /* The non-zero argvIdx values must be contiguous.  Raise an\n      ** error if they are not */\n      sqlite3ErrorMsg(pParse,\"%s.xBestIndex malfunction\",pSrc->pTab->zName);\n      testcase( pIdxInfo->needToFreeIdxStr );\n      return SQLITE_ERROR;\n    }\n  }\n  assert( pNew->nLTerm<=pNew->nLSlot );\n  pNew->u.vtab.idxNum = pIdxInfo->idxNum;\n  pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;\n  pIdxInfo->needToFreeIdxStr = 0;\n  pNew->u.vtab.idxStr = pIdxInfo->idxStr;\n  pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?\n      pIdxInfo->nOrderBy : 0);\n  pNew->rSetup = 0;\n  pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);\n  pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);\n\n  /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated\n  ** that the scan will visit at most one row. Clear it otherwise. */\n  if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){\n    pNew->wsFlags |= WHERE_ONEROW;\n  }else{\n    pNew->wsFlags &= ~WHERE_ONEROW;\n  }\n  rc = whereLoopInsert(pBuilder, pNew);\n  if( pNew->u.vtab.needFree ){\n    sqlite3_free(pNew->u.vtab.idxStr);\n    pNew->u.vtab.needFree = 0;\n  }\n  WHERETRACE(0xffff, (\"  bIn=%d prereqIn=%04llx prereqOut=%04llx\\n\",\n                      *pbIn, (sqlite3_uint64)mPrereq,\n                      (sqlite3_uint64)(pNew->prereq & ~mPrereq)));\n\n  return rc;\n}\n\n/*\n** If this function is invoked from within an xBestIndex() callback, it\n** returns a pointer to a buffer containing the name of the collation\n** sequence associated with element iCons of the sqlite3_index_info.aConstraint\n** array. Or, if iCons is out of range or there is no active xBestIndex\n** call, return NULL.\n*/\nSQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){\n  HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];\n  const char *zRet = 0;\n  if( iCons>=0 && iCons<pIdxInfo->nConstraint ){\n    CollSeq *pC = 0;\n    int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;\n    Expr *pX = pHidden->pWC->a[iTerm].pExpr;\n    if( pX->pLeft ){\n      pC = sqlite3ExprCompareCollSeq(pHidden->pParse, pX);\n    }\n    zRet = (pC ? pC->zName : sqlite3StrBINARY);\n  }\n  return zRet;\n}\n\n/*\n** Add all WhereLoop objects for a table of the join identified by\n** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.\n**\n** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and\n** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause\n** entries that occur before the virtual table in the FROM clause and are\n** separated from it by at least one LEFT or CROSS JOIN. Similarly, the\n** mUnusable mask contains all FROM clause entries that occur after the\n** virtual table and are separated from it by at least one LEFT or \n** CROSS JOIN. \n**\n** For example, if the query were:\n**\n**   ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;\n**\n** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).\n**\n** All the tables in mPrereq must be scanned before the current virtual \n** table. So any terms for which all prerequisites are satisfied by \n** mPrereq may be specified as \"usable\" in all calls to xBestIndex. \n** Conversely, all tables in mUnusable must be scanned after the current\n** virtual table, so any terms for which the prerequisites overlap with\n** mUnusable should always be configured as \"not-usable\" for xBestIndex.\n*/\nstatic int whereLoopAddVirtual(\n  WhereLoopBuilder *pBuilder,  /* WHERE clause information */\n  Bitmask mPrereq,             /* Tables that must be scanned before this one */\n  Bitmask mUnusable            /* Tables that must be scanned after this one */\n){\n  int rc = SQLITE_OK;          /* Return code */\n  WhereInfo *pWInfo;           /* WHERE analysis context */\n  Parse *pParse;               /* The parsing context */\n  WhereClause *pWC;            /* The WHERE clause */\n  struct SrcList_item *pSrc;   /* The FROM clause term to search */\n  sqlite3_index_info *p;       /* Object to pass to xBestIndex() */\n  int nConstraint;             /* Number of constraints in p */\n  int bIn;                     /* True if plan uses IN(...) operator */\n  WhereLoop *pNew;\n  Bitmask mBest;               /* Tables used by best possible plan */\n  u16 mNoOmit;\n\n  assert( (mPrereq & mUnusable)==0 );\n  pWInfo = pBuilder->pWInfo;\n  pParse = pWInfo->pParse;\n  pWC = pBuilder->pWC;\n  pNew = pBuilder->pNew;\n  pSrc = &pWInfo->pTabList->a[pNew->iTab];\n  assert( IsVirtual(pSrc->pTab) );\n  p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy, \n      &mNoOmit);\n  if( p==0 ) return SQLITE_NOMEM_BKPT;\n  pNew->rSetup = 0;\n  pNew->wsFlags = WHERE_VIRTUALTABLE;\n  pNew->nLTerm = 0;\n  pNew->u.vtab.needFree = 0;\n  nConstraint = p->nConstraint;\n  if( whereLoopResize(pParse->db, pNew, nConstraint) ){\n    sqlite3DbFree(pParse->db, p);\n    return SQLITE_NOMEM_BKPT;\n  }\n\n  /* First call xBestIndex() with all constraints usable. */\n  WHERETRACE(0x800, (\"BEGIN %s.addVirtual()\\n\", pSrc->pTab->zName));\n  WHERETRACE(0x40, (\"  VirtualOne: all usable\\n\"));\n  rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);\n\n  /* If the call to xBestIndex() with all terms enabled produced a plan\n  ** that does not require any source tables (IOW: a plan with mBest==0)\n  ** and does not use an IN(...) operator, then there is no point in making \n  ** any further calls to xBestIndex() since they will all return the same\n  ** result (if the xBestIndex() implementation is sane). */\n  if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){\n    int seenZero = 0;             /* True if a plan with no prereqs seen */\n    int seenZeroNoIN = 0;         /* Plan with no prereqs and no IN(...) seen */\n    Bitmask mPrev = 0;\n    Bitmask mBestNoIn = 0;\n\n    /* If the plan produced by the earlier call uses an IN(...) term, call\n    ** xBestIndex again, this time with IN(...) terms disabled. */\n    if( bIn ){\n      WHERETRACE(0x40, (\"  VirtualOne: all usable w/o IN\\n\"));\n      rc = whereLoopAddVirtualOne(\n          pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);\n      assert( bIn==0 );\n      mBestNoIn = pNew->prereq & ~mPrereq;\n      if( mBestNoIn==0 ){\n        seenZero = 1;\n        seenZeroNoIN = 1;\n      }\n    }\n\n    /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq) \n    ** in the set of terms that apply to the current virtual table.  */\n    while( rc==SQLITE_OK ){\n      int i;\n      Bitmask mNext = ALLBITS;\n      assert( mNext>0 );\n      for(i=0; i<nConstraint; i++){\n        Bitmask mThis = (\n            pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq\n        );\n        if( mThis>mPrev && mThis<mNext ) mNext = mThis;\n      }\n      mPrev = mNext;\n      if( mNext==ALLBITS ) break;\n      if( mNext==mBest || mNext==mBestNoIn ) continue;\n      WHERETRACE(0x40, (\"  VirtualOne: mPrev=%04llx mNext=%04llx\\n\",\n                       (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));\n      rc = whereLoopAddVirtualOne(\n          pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);\n      if( pNew->prereq==mPrereq ){\n        seenZero = 1;\n        if( bIn==0 ) seenZeroNoIN = 1;\n      }\n    }\n\n    /* If the calls to xBestIndex() in the above loop did not find a plan\n    ** that requires no source tables at all (i.e. one guaranteed to be\n    ** usable), make a call here with all source tables disabled */\n    if( rc==SQLITE_OK && seenZero==0 ){\n      WHERETRACE(0x40, (\"  VirtualOne: all disabled\\n\"));\n      rc = whereLoopAddVirtualOne(\n          pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);\n      if( bIn==0 ) seenZeroNoIN = 1;\n    }\n\n    /* If the calls to xBestIndex() have so far failed to find a plan\n    ** that requires no source tables at all and does not use an IN(...)\n    ** operator, make a final call to obtain one here.  */\n    if( rc==SQLITE_OK && seenZeroNoIN==0 ){\n      WHERETRACE(0x40, (\"  VirtualOne: all disabled and w/o IN\\n\"));\n      rc = whereLoopAddVirtualOne(\n          pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);\n    }\n  }\n\n  if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);\n  sqlite3DbFreeNN(pParse->db, p);\n  WHERETRACE(0x800, (\"END %s.addVirtual(), rc=%d\\n\", pSrc->pTab->zName, rc));\n  return rc;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n/*\n** Add WhereLoop entries to handle OR terms.  This works for either\n** btrees or virtual tables.\n*/\nstatic int whereLoopAddOr(\n  WhereLoopBuilder *pBuilder, \n  Bitmask mPrereq, \n  Bitmask mUnusable\n){\n  WhereInfo *pWInfo = pBuilder->pWInfo;\n  WhereClause *pWC;\n  WhereLoop *pNew;\n  WhereTerm *pTerm, *pWCEnd;\n  int rc = SQLITE_OK;\n  int iCur;\n  WhereClause tempWC;\n  WhereLoopBuilder sSubBuild;\n  WhereOrSet sSum, sCur;\n  struct SrcList_item *pItem;\n  \n  pWC = pBuilder->pWC;\n  pWCEnd = pWC->a + pWC->nTerm;\n  pNew = pBuilder->pNew;\n  memset(&sSum, 0, sizeof(sSum));\n  pItem = pWInfo->pTabList->a + pNew->iTab;\n  iCur = pItem->iCursor;\n\n  for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){\n    if( (pTerm->eOperator & WO_OR)!=0\n     && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 \n    ){\n      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;\n      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];\n      WhereTerm *pOrTerm;\n      int once = 1;\n      int i, j;\n    \n      sSubBuild = *pBuilder;\n      sSubBuild.pOrderBy = 0;\n      sSubBuild.pOrSet = &sCur;\n\n      WHERETRACE(0x200, (\"Begin processing OR-clause %p\\n\", pTerm));\n      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){\n        if( (pOrTerm->eOperator & WO_AND)!=0 ){\n          sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;\n        }else if( pOrTerm->leftCursor==iCur ){\n          tempWC.pWInfo = pWC->pWInfo;\n          tempWC.pOuter = pWC;\n          tempWC.op = TK_AND;\n          tempWC.nTerm = 1;\n          tempWC.a = pOrTerm;\n          sSubBuild.pWC = &tempWC;\n        }else{\n          continue;\n        }\n        sCur.n = 0;\n#ifdef WHERETRACE_ENABLED\n        WHERETRACE(0x200, (\"OR-term %d of %p has %d subterms:\\n\", \n                   (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));\n        if( sqlite3WhereTrace & 0x400 ){\n          sqlite3WhereClausePrint(sSubBuild.pWC);\n        }\n#endif\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n        if( IsVirtual(pItem->pTab) ){\n          rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);\n        }else\n#endif\n        {\n          rc = whereLoopAddBtree(&sSubBuild, mPrereq);\n        }\n        if( rc==SQLITE_OK ){\n          rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);\n        }\n        assert( rc==SQLITE_OK || rc==SQLITE_DONE || sCur.n==0 );\n        testcase( rc==SQLITE_DONE );\n        if( sCur.n==0 ){\n          sSum.n = 0;\n          break;\n        }else if( once ){\n          whereOrMove(&sSum, &sCur);\n          once = 0;\n        }else{\n          WhereOrSet sPrev;\n          whereOrMove(&sPrev, &sSum);\n          sSum.n = 0;\n          for(i=0; i<sPrev.n; i++){\n            for(j=0; j<sCur.n; j++){\n              whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,\n                            sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),\n                            sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));\n            }\n          }\n        }\n      }\n      pNew->nLTerm = 1;\n      pNew->aLTerm[0] = pTerm;\n      pNew->wsFlags = WHERE_MULTI_OR;\n      pNew->rSetup = 0;\n      pNew->iSortIdx = 0;\n      memset(&pNew->u, 0, sizeof(pNew->u));\n      for(i=0; rc==SQLITE_OK && i<sSum.n; i++){\n        /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs\n        ** of all sub-scans required by the OR-scan. However, due to rounding\n        ** errors, it may be that the cost of the OR-scan is equal to its\n        ** most expensive sub-scan. Add the smallest possible penalty \n        ** (equivalent to multiplying the cost by 1.07) to ensure that \n        ** this does not happen. Otherwise, for WHERE clauses such as the\n        ** following where there is an index on \"y\":\n        **\n        **     WHERE likelihood(x=?, 0.99) OR y=?\n        **\n        ** the planner may elect to \"OR\" together a full-table scan and an\n        ** index lookup. And other similarly odd results.  */\n        pNew->rRun = sSum.a[i].rRun + 1;\n        pNew->nOut = sSum.a[i].nOut;\n        pNew->prereq = sSum.a[i].prereq;\n        rc = whereLoopInsert(pBuilder, pNew);\n      }\n      WHERETRACE(0x200, (\"End processing OR-clause %p\\n\", pTerm));\n    }\n  }\n  return rc;\n}\n\n/*\n** Add all WhereLoop objects for all tables \n*/\nstatic int whereLoopAddAll(WhereLoopBuilder *pBuilder){\n  WhereInfo *pWInfo = pBuilder->pWInfo;\n  Bitmask mPrereq = 0;\n  Bitmask mPrior = 0;\n  int iTab;\n  SrcList *pTabList = pWInfo->pTabList;\n  struct SrcList_item *pItem;\n  struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];\n  sqlite3 *db = pWInfo->pParse->db;\n  int rc = SQLITE_OK;\n  WhereLoop *pNew;\n  u8 priorJointype = 0;\n\n  /* Loop over the tables in the join, from left to right */\n  pNew = pBuilder->pNew;\n  whereLoopInit(pNew);\n  pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT;\n  for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){\n    Bitmask mUnusable = 0;\n    pNew->iTab = iTab;\n    pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR;\n    pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);\n    if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){\n      /* This condition is true when pItem is the FROM clause term on the\n      ** right-hand-side of a LEFT or CROSS JOIN.  */\n      mPrereq = mPrior;\n    }\n    priorJointype = pItem->fg.jointype;\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    if( IsVirtual(pItem->pTab) ){\n      struct SrcList_item *p;\n      for(p=&pItem[1]; p<pEnd; p++){\n        if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){\n          mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);\n        }\n      }\n      rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);\n    }else\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n    {\n      rc = whereLoopAddBtree(pBuilder, mPrereq);\n    }\n    if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){\n      rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);\n    }\n    mPrior |= pNew->maskSelf;\n    if( rc || db->mallocFailed ){\n      if( rc==SQLITE_DONE ){\n        /* We hit the query planner search limit set by iPlanLimit */\n        sqlite3_log(SQLITE_WARNING, \"abbreviated query algorithm search\");\n        rc = SQLITE_OK;\n      }else{\n        break;\n      }\n    }\n  }\n\n  whereLoopClear(db, pNew);\n  return rc;\n}\n\n/*\n** Examine a WherePath (with the addition of the extra WhereLoop of the 6th\n** parameters) to see if it outputs rows in the requested ORDER BY\n** (or GROUP BY) without requiring a separate sort operation.  Return N:\n** \n**   N>0:   N terms of the ORDER BY clause are satisfied\n**   N==0:  No terms of the ORDER BY clause are satisfied\n**   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.   \n**\n** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as\n** strict.  With GROUP BY and DISTINCT the only requirement is that\n** equivalent rows appear immediately adjacent to one another.  GROUP BY\n** and DISTINCT do not require rows to appear in any particular order as long\n** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT\n** the pOrderBy terms can be matched in any order.  With ORDER BY, the \n** pOrderBy terms must be matched in strict left-to-right order.\n*/\nstatic i8 wherePathSatisfiesOrderBy(\n  WhereInfo *pWInfo,    /* The WHERE clause */\n  ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */\n  WherePath *pPath,     /* The WherePath to check */\n  u16 wctrlFlags,       /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */\n  u16 nLoop,            /* Number of entries in pPath->aLoop[] */\n  WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */\n  Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */\n){\n  u8 revSet;            /* True if rev is known */\n  u8 rev;               /* Composite sort order */\n  u8 revIdx;            /* Index sort order */\n  u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */\n  u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */\n  u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */\n  u16 eqOpMask;         /* Allowed equality operators */\n  u16 nKeyCol;          /* Number of key columns in pIndex */\n  u16 nColumn;          /* Total number of ordered columns in the index */\n  u16 nOrderBy;         /* Number terms in the ORDER BY clause */\n  int iLoop;            /* Index of WhereLoop in pPath being processed */\n  int i, j;             /* Loop counters */\n  int iCur;             /* Cursor number for current WhereLoop */\n  int iColumn;          /* A column number within table iCur */\n  WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */\n  WhereTerm *pTerm;     /* A single term of the WHERE clause */\n  Expr *pOBExpr;        /* An expression from the ORDER BY clause */\n  CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */\n  Index *pIndex;        /* The index associated with pLoop */\n  sqlite3 *db = pWInfo->pParse->db;  /* Database connection */\n  Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */\n  Bitmask obDone;       /* Mask of all ORDER BY terms */\n  Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */\n  Bitmask ready;              /* Mask of inner loops */\n\n  /*\n  ** We say the WhereLoop is \"one-row\" if it generates no more than one\n  ** row of output.  A WhereLoop is one-row if all of the following are true:\n  **  (a) All index columns match with WHERE_COLUMN_EQ.\n  **  (b) The index is unique\n  ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.\n  ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.\n  **\n  ** We say the WhereLoop is \"order-distinct\" if the set of columns from\n  ** that WhereLoop that are in the ORDER BY clause are different for every\n  ** row of the WhereLoop.  Every one-row WhereLoop is automatically\n  ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause\n  ** is not order-distinct. To be order-distinct is not quite the same as being\n  ** UNIQUE since a UNIQUE column or index can have multiple rows that \n  ** are NULL and NULL values are equivalent for the purpose of order-distinct.\n  ** To be order-distinct, the columns must be UNIQUE and NOT NULL.\n  **\n  ** The rowid for a table is always UNIQUE and NOT NULL so whenever the\n  ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is\n  ** automatically order-distinct.\n  */\n\n  assert( pOrderBy!=0 );\n  if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;\n\n  nOrderBy = pOrderBy->nExpr;\n  testcase( nOrderBy==BMS-1 );\n  if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */\n  isOrderDistinct = 1;\n  obDone = MASKBIT(nOrderBy)-1;\n  orderDistinctMask = 0;\n  ready = 0;\n  eqOpMask = WO_EQ | WO_IS | WO_ISNULL;\n  if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;\n  for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){\n    if( iLoop>0 ) ready |= pLoop->maskSelf;\n    if( iLoop<nLoop ){\n      pLoop = pPath->aLoop[iLoop];\n      if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;\n    }else{\n      pLoop = pLast;\n    }\n    if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){\n      if( pLoop->u.vtab.isOrdered && (wctrlFlags & WHERE_DISTINCTBY)==0 ){\n        obSat = obDone;\n      }\n      break;\n    }else if( wctrlFlags & WHERE_DISTINCTBY ){\n      pLoop->u.btree.nDistinctCol = 0;\n    }\n    iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;\n\n    /* Mark off any ORDER BY term X that is a column in the table of\n    ** the current loop for which there is term in the WHERE\n    ** clause of the form X IS NULL or X=? that reference only outer\n    ** loops.\n    */\n    for(i=0; i<nOrderBy; i++){\n      if( MASKBIT(i) & obSat ) continue;\n      pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);\n      if( pOBExpr->op!=TK_COLUMN ) continue;\n      if( pOBExpr->iTable!=iCur ) continue;\n      pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,\n                       ~ready, eqOpMask, 0);\n      if( pTerm==0 ) continue;\n      if( pTerm->eOperator==WO_IN ){\n        /* IN terms are only valid for sorting in the ORDER BY LIMIT \n        ** optimization, and then only if they are actually used\n        ** by the query plan */\n        assert( wctrlFlags & WHERE_ORDERBY_LIMIT );\n        for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}\n        if( j>=pLoop->nLTerm ) continue;\n      }\n      if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){\n        Parse *pParse = pWInfo->pParse;\n        CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[i].pExpr);\n        CollSeq *pColl2 = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr);\n        assert( pColl1 );\n        if( pColl2==0 || sqlite3StrICmp(pColl1->zName, pColl2->zName) ){\n          continue;\n        }\n        testcase( pTerm->pExpr->op==TK_IS );\n      }\n      obSat |= MASKBIT(i);\n    }\n\n    if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){\n      if( pLoop->wsFlags & WHERE_IPK ){\n        pIndex = 0;\n        nKeyCol = 0;\n        nColumn = 1;\n      }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){\n        return 0;\n      }else{\n        nKeyCol = pIndex->nKeyCol;\n        nColumn = pIndex->nColumn;\n        assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );\n        assert( pIndex->aiColumn[nColumn-1]==XN_ROWID\n                          || !HasRowid(pIndex->pTable));\n        isOrderDistinct = IsUniqueIndex(pIndex)\n                          && (pLoop->wsFlags & WHERE_SKIPSCAN)==0;\n      }\n\n      /* Loop through all columns of the index and deal with the ones\n      ** that are not constrained by == or IN.\n      */\n      rev = revSet = 0;\n      distinctColumns = 0;\n      for(j=0; j<nColumn; j++){\n        u8 bOnce = 1; /* True to run the ORDER BY search loop */\n\n        assert( j>=pLoop->u.btree.nEq \n            || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)\n        );\n        if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){\n          u16 eOp = pLoop->aLTerm[j]->eOperator;\n\n          /* Skip over == and IS and ISNULL terms.  (Also skip IN terms when\n          ** doing WHERE_ORDERBY_LIMIT processing).  Except, IS and ISNULL\n          ** terms imply that the index is not UNIQUE NOT NULL in which case\n          ** the loop need to be marked as not order-distinct because it can\n          ** have repeated NULL rows.\n          **\n          ** If the current term is a column of an ((?,?) IN (SELECT...)) \n          ** expression for which the SELECT returns more than one column,\n          ** check that it is the only column used by this loop. Otherwise,\n          ** if it is one of two or more, none of the columns can be\n          ** considered to match an ORDER BY term.\n          */\n          if( (eOp & eqOpMask)!=0 ){\n            if( eOp & (WO_ISNULL|WO_IS) ){\n              testcase( eOp & WO_ISNULL );\n              testcase( eOp & WO_IS );\n              testcase( isOrderDistinct );\n              isOrderDistinct = 0;\n            }\n            continue;  \n          }else if( ALWAYS(eOp & WO_IN) ){\n            /* ALWAYS() justification: eOp is an equality operator due to the\n            ** j<pLoop->u.btree.nEq constraint above.  Any equality other\n            ** than WO_IN is captured by the previous \"if\".  So this one\n            ** always has to be WO_IN. */\n            Expr *pX = pLoop->aLTerm[j]->pExpr;\n            for(i=j+1; i<pLoop->u.btree.nEq; i++){\n              if( pLoop->aLTerm[i]->pExpr==pX ){\n                assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );\n                bOnce = 0;\n                break;\n              }\n            }\n          }\n        }\n\n        /* Get the column number in the table (iColumn) and sort order\n        ** (revIdx) for the j-th column of the index.\n        */\n        if( pIndex ){\n          iColumn = pIndex->aiColumn[j];\n          revIdx = pIndex->aSortOrder[j] & KEYINFO_ORDER_DESC;\n          if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;\n        }else{\n          iColumn = XN_ROWID;\n          revIdx = 0;\n        }\n\n        /* An unconstrained column that might be NULL means that this\n        ** WhereLoop is not well-ordered\n        */\n        if( isOrderDistinct\n         && iColumn>=0\n         && j>=pLoop->u.btree.nEq\n         && pIndex->pTable->aCol[iColumn].notNull==0\n        ){\n          isOrderDistinct = 0;\n        }\n\n        /* Find the ORDER BY term that corresponds to the j-th column\n        ** of the index and mark that ORDER BY term off \n        */\n        isMatch = 0;\n        for(i=0; bOnce && i<nOrderBy; i++){\n          if( MASKBIT(i) & obSat ) continue;\n          pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);\n          testcase( wctrlFlags & WHERE_GROUPBY );\n          testcase( wctrlFlags & WHERE_DISTINCTBY );\n          if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;\n          if( iColumn>=XN_ROWID ){\n            if( pOBExpr->op!=TK_COLUMN ) continue;\n            if( pOBExpr->iTable!=iCur ) continue;\n            if( pOBExpr->iColumn!=iColumn ) continue;\n          }else{\n            Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr;\n            if( sqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){\n              continue;\n            }\n          }\n          if( iColumn!=XN_ROWID ){\n            pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);\n            if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;\n          }\n          if( wctrlFlags & WHERE_DISTINCTBY ){\n            pLoop->u.btree.nDistinctCol = j+1;\n          }\n          isMatch = 1;\n          break;\n        }\n        if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){\n          /* Make sure the sort order is compatible in an ORDER BY clause.\n          ** Sort order is irrelevant for a GROUP BY clause. */\n          if( revSet ){\n            if( (rev ^ revIdx)!=(pOrderBy->a[i].sortFlags&KEYINFO_ORDER_DESC) ){\n              isMatch = 0;\n            }\n          }else{\n            rev = revIdx ^ (pOrderBy->a[i].sortFlags & KEYINFO_ORDER_DESC);\n            if( rev ) *pRevMask |= MASKBIT(iLoop);\n            revSet = 1;\n          }\n        }\n        if( isMatch && (pOrderBy->a[i].sortFlags & KEYINFO_ORDER_BIGNULL) ){\n          if( j==pLoop->u.btree.nEq ){\n            pLoop->wsFlags |= WHERE_BIGNULL_SORT;\n          }else{\n            isMatch = 0;\n          }\n        }\n        if( isMatch ){\n          if( iColumn==XN_ROWID ){\n            testcase( distinctColumns==0 );\n            distinctColumns = 1;\n          }\n          obSat |= MASKBIT(i);\n        }else{\n          /* No match found */\n          if( j==0 || j<nKeyCol ){\n            testcase( isOrderDistinct!=0 );\n            isOrderDistinct = 0;\n          }\n          break;\n        }\n      } /* end Loop over all index columns */\n      if( distinctColumns ){\n        testcase( isOrderDistinct==0 );\n        isOrderDistinct = 1;\n      }\n    } /* end-if not one-row */\n\n    /* Mark off any other ORDER BY terms that reference pLoop */\n    if( isOrderDistinct ){\n      orderDistinctMask |= pLoop->maskSelf;\n      for(i=0; i<nOrderBy; i++){\n        Expr *p;\n        Bitmask mTerm;\n        if( MASKBIT(i) & obSat ) continue;\n        p = pOrderBy->a[i].pExpr;\n        mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);\n        if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;\n        if( (mTerm&~orderDistinctMask)==0 ){\n          obSat |= MASKBIT(i);\n        }\n      }\n    }\n  } /* End the loop over all WhereLoops from outer-most down to inner-most */\n  if( obSat==obDone ) return (i8)nOrderBy;\n  if( !isOrderDistinct ){\n    for(i=nOrderBy-1; i>0; i--){\n      Bitmask m = MASKBIT(i) - 1;\n      if( (obSat&m)==m ) return i;\n    }\n    return 0;\n  }\n  return -1;\n}\n\n\n/*\n** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),\n** the planner assumes that the specified pOrderBy list is actually a GROUP\n** BY clause - and so any order that groups rows as required satisfies the\n** request.\n**\n** Normally, in this case it is not possible for the caller to determine\n** whether or not the rows are really being delivered in sorted order, or\n** just in some other order that provides the required grouping. However,\n** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then\n** this function may be called on the returned WhereInfo object. It returns\n** true if the rows really will be sorted in the specified order, or false\n** otherwise.\n**\n** For example, assuming:\n**\n**   CREATE INDEX i1 ON t1(x, Y);\n**\n** then\n**\n**   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1\n**   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0\n*/\nSQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){\n  assert( pWInfo->wctrlFlags & WHERE_GROUPBY );\n  assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );\n  return pWInfo->sorted;\n}\n\n#ifdef WHERETRACE_ENABLED\n/* For debugging use only: */\nstatic const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){\n  static char zName[65];\n  int i;\n  for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }\n  if( pLast ) zName[i++] = pLast->cId;\n  zName[i] = 0;\n  return zName;\n}\n#endif\n\n/*\n** Return the cost of sorting nRow rows, assuming that the keys have \n** nOrderby columns and that the first nSorted columns are already in\n** order.\n*/\nstatic LogEst whereSortingCost(\n  WhereInfo *pWInfo,\n  LogEst nRow,\n  int nOrderBy,\n  int nSorted\n){\n  /* TUNING: Estimated cost of a full external sort, where N is \n  ** the number of rows to sort is:\n  **\n  **   cost = (3.0 * N * log(N)).\n  ** \n  ** Or, if the order-by clause has X terms but only the last Y \n  ** terms are out of order, then block-sorting will reduce the \n  ** sorting cost to:\n  **\n  **   cost = (3.0 * N * log(N)) * (Y/X)\n  **\n  ** The (Y/X) term is implemented using stack variable rScale\n  ** below.  */\n  LogEst rScale, rSortCost;\n  assert( nOrderBy>0 && 66==sqlite3LogEst(100) );\n  rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;\n  rSortCost = nRow + rScale + 16;\n\n  /* Multiple by log(M) where M is the number of output rows.\n  ** Use the LIMIT for M if it is smaller */\n  if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){\n    nRow = pWInfo->iLimit;\n  }\n  rSortCost += estLog(nRow);\n  return rSortCost;\n}\n\n/*\n** Given the list of WhereLoop objects at pWInfo->pLoops, this routine\n** attempts to find the lowest cost path that visits each WhereLoop\n** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.\n**\n** Assume that the total number of output rows that will need to be sorted\n** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting\n** costs if nRowEst==0.\n**\n** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation\n** error occurs.\n*/\nstatic int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){\n  int mxChoice;             /* Maximum number of simultaneous paths tracked */\n  int nLoop;                /* Number of terms in the join */\n  Parse *pParse;            /* Parsing context */\n  sqlite3 *db;              /* The database connection */\n  int iLoop;                /* Loop counter over the terms of the join */\n  int ii, jj;               /* Loop counters */\n  int mxI = 0;              /* Index of next entry to replace */\n  int nOrderBy;             /* Number of ORDER BY clause terms */\n  LogEst mxCost = 0;        /* Maximum cost of a set of paths */\n  LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */\n  int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */\n  WherePath *aFrom;         /* All nFrom paths at the previous level */\n  WherePath *aTo;           /* The nTo best paths at the current level */\n  WherePath *pFrom;         /* An element of aFrom[] that we are working on */\n  WherePath *pTo;           /* An element of aTo[] that we are working on */\n  WhereLoop *pWLoop;        /* One of the WhereLoop objects */\n  WhereLoop **pX;           /* Used to divy up the pSpace memory */\n  LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */\n  char *pSpace;             /* Temporary memory used by this routine */\n  int nSpace;               /* Bytes of space allocated at pSpace */\n\n  pParse = pWInfo->pParse;\n  db = pParse->db;\n  nLoop = pWInfo->nLevel;\n  /* TUNING: For simple queries, only the best path is tracked.\n  ** For 2-way joins, the 5 best paths are followed.\n  ** For joins of 3 or more tables, track the 10 best paths */\n  mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);\n  assert( nLoop<=pWInfo->pTabList->nSrc );\n  WHERETRACE(0x002, (\"---- begin solver.  (nRowEst=%d)\\n\", nRowEst));\n\n  /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this\n  ** case the purpose of this call is to estimate the number of rows returned\n  ** by the overall query. Once this estimate has been obtained, the caller\n  ** will invoke this function a second time, passing the estimate as the\n  ** nRowEst parameter.  */\n  if( pWInfo->pOrderBy==0 || nRowEst==0 ){\n    nOrderBy = 0;\n  }else{\n    nOrderBy = pWInfo->pOrderBy->nExpr;\n  }\n\n  /* Allocate and initialize space for aTo, aFrom and aSortCost[] */\n  nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;\n  nSpace += sizeof(LogEst) * nOrderBy;\n  pSpace = sqlite3DbMallocRawNN(db, nSpace);\n  if( pSpace==0 ) return SQLITE_NOMEM_BKPT;\n  aTo = (WherePath*)pSpace;\n  aFrom = aTo+mxChoice;\n  memset(aFrom, 0, sizeof(aFrom[0]));\n  pX = (WhereLoop**)(aFrom+mxChoice);\n  for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){\n    pFrom->aLoop = pX;\n  }\n  if( nOrderBy ){\n    /* If there is an ORDER BY clause and it is not being ignored, set up\n    ** space for the aSortCost[] array. Each element of the aSortCost array\n    ** is either zero - meaning it has not yet been initialized - or the\n    ** cost of sorting nRowEst rows of data where the first X terms of\n    ** the ORDER BY clause are already in order, where X is the array \n    ** index.  */\n    aSortCost = (LogEst*)pX;\n    memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);\n  }\n  assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );\n  assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );\n\n  /* Seed the search with a single WherePath containing zero WhereLoops.\n  **\n  ** TUNING: Do not let the number of iterations go above 28.  If the cost\n  ** of computing an automatic index is not paid back within the first 28\n  ** rows, then do not use the automatic index. */\n  aFrom[0].nRow = MIN(pParse->nQueryLoop, 48);  assert( 48==sqlite3LogEst(28) );\n  nFrom = 1;\n  assert( aFrom[0].isOrdered==0 );\n  if( nOrderBy ){\n    /* If nLoop is zero, then there are no FROM terms in the query. Since\n    ** in this case the query may return a maximum of one row, the results\n    ** are already in the requested order. Set isOrdered to nOrderBy to\n    ** indicate this. Or, if nLoop is greater than zero, set isOrdered to\n    ** -1, indicating that the result set may or may not be ordered, \n    ** depending on the loops added to the current plan.  */\n    aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;\n  }\n\n  /* Compute successively longer WherePaths using the previous generation\n  ** of WherePaths as the basis for the next.  Keep track of the mxChoice\n  ** best paths at each generation */\n  for(iLoop=0; iLoop<nLoop; iLoop++){\n    nTo = 0;\n    for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){\n      for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){\n        LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */\n        LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */\n        LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */\n        i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */\n        Bitmask maskNew;                  /* Mask of src visited by (..) */\n        Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */\n\n        if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;\n        if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;\n        if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){\n          /* Do not use an automatic index if the this loop is expected\n          ** to run less than 1.25 times.  It is tempting to also exclude\n          ** automatic index usage on an outer loop, but sometimes an automatic\n          ** index is useful in the outer loop of a correlated subquery. */\n          assert( 10==sqlite3LogEst(2) );\n          continue;\n        }\n\n        /* At this point, pWLoop is a candidate to be the next loop. \n        ** Compute its cost */\n        rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);\n        rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);\n        nOut = pFrom->nRow + pWLoop->nOut;\n        maskNew = pFrom->maskLoop | pWLoop->maskSelf;\n        if( isOrdered<0 ){\n          isOrdered = wherePathSatisfiesOrderBy(pWInfo,\n                       pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,\n                       iLoop, pWLoop, &revMask);\n        }else{\n          revMask = pFrom->revLoop;\n        }\n        if( isOrdered>=0 && isOrdered<nOrderBy ){\n          if( aSortCost[isOrdered]==0 ){\n            aSortCost[isOrdered] = whereSortingCost(\n                pWInfo, nRowEst, nOrderBy, isOrdered\n            );\n          }\n          /* TUNING:  Add a small extra penalty (5) to sorting as an\n          ** extra encouragment to the query planner to select a plan\n          ** where the rows emerge in the correct order without any sorting\n          ** required. */\n          rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 5;\n\n          WHERETRACE(0x002,\n              (\"---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\\n\",\n               aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy, \n               rUnsorted, rCost));\n        }else{\n          rCost = rUnsorted;\n          rUnsorted -= 2;  /* TUNING:  Slight bias in favor of no-sort plans */\n        }\n\n        /* Check to see if pWLoop should be added to the set of\n        ** mxChoice best-so-far paths.\n        **\n        ** First look for an existing path among best-so-far paths\n        ** that covers the same set of loops and has the same isOrdered\n        ** setting as the current path candidate.\n        **\n        ** The term \"((pTo->isOrdered^isOrdered)&0x80)==0\" is equivalent\n        ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))\" for the range\n        ** of legal values for isOrdered, -1..64.\n        */\n        for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){\n          if( pTo->maskLoop==maskNew\n           && ((pTo->isOrdered^isOrdered)&0x80)==0\n          ){\n            testcase( jj==nTo-1 );\n            break;\n          }\n        }\n        if( jj>=nTo ){\n          /* None of the existing best-so-far paths match the candidate. */\n          if( nTo>=mxChoice\n           && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))\n          ){\n            /* The current candidate is no better than any of the mxChoice\n            ** paths currently in the best-so-far buffer.  So discard\n            ** this candidate as not viable. */\n#ifdef WHERETRACE_ENABLED /* 0x4 */\n            if( sqlite3WhereTrace&0x4 ){\n              sqlite3DebugPrintf(\"Skip   %s cost=%-3d,%3d,%3d order=%c\\n\",\n                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,\n                  isOrdered>=0 ? isOrdered+'0' : '?');\n            }\n#endif\n            continue;\n          }\n          /* If we reach this points it means that the new candidate path\n          ** needs to be added to the set of best-so-far paths. */\n          if( nTo<mxChoice ){\n            /* Increase the size of the aTo set by one */\n            jj = nTo++;\n          }else{\n            /* New path replaces the prior worst to keep count below mxChoice */\n            jj = mxI;\n          }\n          pTo = &aTo[jj];\n#ifdef WHERETRACE_ENABLED /* 0x4 */\n          if( sqlite3WhereTrace&0x4 ){\n            sqlite3DebugPrintf(\"New    %s cost=%-3d,%3d,%3d order=%c\\n\",\n                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,\n                isOrdered>=0 ? isOrdered+'0' : '?');\n          }\n#endif\n        }else{\n          /* Control reaches here if best-so-far path pTo=aTo[jj] covers the\n          ** same set of loops and has the same isOrdered setting as the\n          ** candidate path.  Check to see if the candidate should replace\n          ** pTo or if the candidate should be skipped.\n          ** \n          ** The conditional is an expanded vector comparison equivalent to:\n          **   (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)\n          */\n          if( pTo->rCost<rCost \n           || (pTo->rCost==rCost\n               && (pTo->nRow<nOut\n                   || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)\n                  )\n              )\n          ){\n#ifdef WHERETRACE_ENABLED /* 0x4 */\n            if( sqlite3WhereTrace&0x4 ){\n              sqlite3DebugPrintf(\n                  \"Skip   %s cost=%-3d,%3d,%3d order=%c\",\n                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,\n                  isOrdered>=0 ? isOrdered+'0' : '?');\n              sqlite3DebugPrintf(\"   vs %s cost=%-3d,%3d,%3d order=%c\\n\",\n                  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,\n                  pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');\n            }\n#endif\n            /* Discard the candidate path from further consideration */\n            testcase( pTo->rCost==rCost );\n            continue;\n          }\n          testcase( pTo->rCost==rCost+1 );\n          /* Control reaches here if the candidate path is better than the\n          ** pTo path.  Replace pTo with the candidate. */\n#ifdef WHERETRACE_ENABLED /* 0x4 */\n          if( sqlite3WhereTrace&0x4 ){\n            sqlite3DebugPrintf(\n                \"Update %s cost=%-3d,%3d,%3d order=%c\",\n                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,\n                isOrdered>=0 ? isOrdered+'0' : '?');\n            sqlite3DebugPrintf(\"  was %s cost=%-3d,%3d,%3d order=%c\\n\",\n                wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,\n                pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');\n          }\n#endif\n        }\n        /* pWLoop is a winner.  Add it to the set of best so far */\n        pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;\n        pTo->revLoop = revMask;\n        pTo->nRow = nOut;\n        pTo->rCost = rCost;\n        pTo->rUnsorted = rUnsorted;\n        pTo->isOrdered = isOrdered;\n        memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);\n        pTo->aLoop[iLoop] = pWLoop;\n        if( nTo>=mxChoice ){\n          mxI = 0;\n          mxCost = aTo[0].rCost;\n          mxUnsorted = aTo[0].nRow;\n          for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){\n            if( pTo->rCost>mxCost \n             || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted) \n            ){\n              mxCost = pTo->rCost;\n              mxUnsorted = pTo->rUnsorted;\n              mxI = jj;\n            }\n          }\n        }\n      }\n    }\n\n#ifdef WHERETRACE_ENABLED  /* >=2 */\n    if( sqlite3WhereTrace & 0x02 ){\n      sqlite3DebugPrintf(\"---- after round %d ----\\n\", iLoop);\n      for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){\n        sqlite3DebugPrintf(\" %s cost=%-3d nrow=%-3d order=%c\",\n           wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,\n           pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');\n        if( pTo->isOrdered>0 ){\n          sqlite3DebugPrintf(\" rev=0x%llx\\n\", pTo->revLoop);\n        }else{\n          sqlite3DebugPrintf(\"\\n\");\n        }\n      }\n    }\n#endif\n\n    /* Swap the roles of aFrom and aTo for the next generation */\n    pFrom = aTo;\n    aTo = aFrom;\n    aFrom = pFrom;\n    nFrom = nTo;\n  }\n\n  if( nFrom==0 ){\n    sqlite3ErrorMsg(pParse, \"no query solution\");\n    sqlite3DbFreeNN(db, pSpace);\n    return SQLITE_ERROR;\n  }\n  \n  /* Find the lowest cost path.  pFrom will be left pointing to that path */\n  pFrom = aFrom;\n  for(ii=1; ii<nFrom; ii++){\n    if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];\n  }\n  assert( pWInfo->nLevel==nLoop );\n  /* Load the lowest cost path into pWInfo */\n  for(iLoop=0; iLoop<nLoop; iLoop++){\n    WhereLevel *pLevel = pWInfo->a + iLoop;\n    pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];\n    pLevel->iFrom = pWLoop->iTab;\n    pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;\n  }\n  if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0\n   && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0\n   && pWInfo->eDistinct==WHERE_DISTINCT_NOOP\n   && nRowEst\n  ){\n    Bitmask notUsed;\n    int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,\n                 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);\n    if( rc==pWInfo->pResultSet->nExpr ){\n      pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;\n    }\n  }\n  pWInfo->bOrderedInnerLoop = 0;\n  if( pWInfo->pOrderBy ){\n    if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){\n      if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){\n        pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;\n      }\n    }else{\n      pWInfo->nOBSat = pFrom->isOrdered;\n      pWInfo->revMask = pFrom->revLoop;\n      if( pWInfo->nOBSat<=0 ){\n        pWInfo->nOBSat = 0;\n        if( nLoop>0 ){\n          u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;\n          if( (wsFlags & WHERE_ONEROW)==0 \n           && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)\n          ){\n            Bitmask m = 0;\n            int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,\n                      WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);\n            testcase( wsFlags & WHERE_IPK );\n            testcase( wsFlags & WHERE_COLUMN_IN );\n            if( rc==pWInfo->pOrderBy->nExpr ){\n              pWInfo->bOrderedInnerLoop = 1;\n              pWInfo->revMask = m;\n            }\n          }\n        }\n      }\n    }\n    if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)\n        && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0\n    ){\n      Bitmask revMask = 0;\n      int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, \n          pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask\n      );\n      assert( pWInfo->sorted==0 );\n      if( nOrder==pWInfo->pOrderBy->nExpr ){\n        pWInfo->sorted = 1;\n        pWInfo->revMask = revMask;\n      }\n    }\n  }\n\n\n  pWInfo->nRowOut = pFrom->nRow;\n\n  /* Free temporary memory and return success */\n  sqlite3DbFreeNN(db, pSpace);\n  return SQLITE_OK;\n}\n\n/*\n** Most queries use only a single table (they are not joins) and have\n** simple == constraints against indexed fields.  This routine attempts\n** to plan those simple cases using much less ceremony than the\n** general-purpose query planner, and thereby yield faster sqlite3_prepare()\n** times for the common case.\n**\n** Return non-zero on success, if this query can be handled by this\n** no-frills query planner.  Return zero if this query needs the \n** general-purpose query planner.\n*/\nstatic int whereShortCut(WhereLoopBuilder *pBuilder){\n  WhereInfo *pWInfo;\n  struct SrcList_item *pItem;\n  WhereClause *pWC;\n  WhereTerm *pTerm;\n  WhereLoop *pLoop;\n  int iCur;\n  int j;\n  Table *pTab;\n  Index *pIdx;\n\n  pWInfo = pBuilder->pWInfo;\n  if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;\n  assert( pWInfo->pTabList->nSrc>=1 );\n  pItem = pWInfo->pTabList->a;\n  pTab = pItem->pTab;\n  if( IsVirtual(pTab) ) return 0;\n  if( pItem->fg.isIndexedBy ) return 0;\n  iCur = pItem->iCursor;\n  pWC = &pWInfo->sWC;\n  pLoop = pBuilder->pNew;\n  pLoop->wsFlags = 0;\n  pLoop->nSkip = 0;\n  pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);\n  if( pTerm ){\n    testcase( pTerm->eOperator & WO_IS );\n    pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;\n    pLoop->aLTerm[0] = pTerm;\n    pLoop->nLTerm = 1;\n    pLoop->u.btree.nEq = 1;\n    /* TUNING: Cost of a rowid lookup is 10 */\n    pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */\n  }else{\n    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n      int opMask;\n      assert( pLoop->aLTermSpace==pLoop->aLTerm );\n      if( !IsUniqueIndex(pIdx)\n       || pIdx->pPartIdxWhere!=0 \n       || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace) \n      ) continue;\n      opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;\n      for(j=0; j<pIdx->nKeyCol; j++){\n        pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);\n        if( pTerm==0 ) break;\n        testcase( pTerm->eOperator & WO_IS );\n        pLoop->aLTerm[j] = pTerm;\n      }\n      if( j!=pIdx->nKeyCol ) continue;\n      pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;\n      if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){\n        pLoop->wsFlags |= WHERE_IDX_ONLY;\n      }\n      pLoop->nLTerm = j;\n      pLoop->u.btree.nEq = j;\n      pLoop->u.btree.pIndex = pIdx;\n      /* TUNING: Cost of a unique index lookup is 15 */\n      pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */\n      break;\n    }\n  }\n  if( pLoop->wsFlags ){\n    pLoop->nOut = (LogEst)1;\n    pWInfo->a[0].pWLoop = pLoop;\n    assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );\n    pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */\n    pWInfo->a[0].iTabCur = iCur;\n    pWInfo->nRowOut = 1;\n    if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;\n    if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){\n      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;\n    }\n#ifdef SQLITE_DEBUG\n    pLoop->cId = '0';\n#endif\n    return 1;\n  }\n  return 0;\n}\n\n/*\n** Helper function for exprIsDeterministic().\n*/\nstatic int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){\n  if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){\n    pWalker->eCode = 0;\n    return WRC_Abort;\n  }\n  return WRC_Continue;\n}\n\n/*\n** Return true if the expression contains no non-deterministic SQL \n** functions. Do not consider non-deterministic SQL functions that are \n** part of sub-select statements.\n*/\nstatic int exprIsDeterministic(Expr *p){\n  Walker w;\n  memset(&w, 0, sizeof(w));\n  w.eCode = 1;\n  w.xExprCallback = exprNodeIsDeterministic;\n  w.xSelectCallback = sqlite3SelectWalkFail;\n  sqlite3WalkExpr(&w, p);\n  return w.eCode;\n}\n\n  \n#ifdef WHERETRACE_ENABLED\n/*\n** Display all WhereLoops in pWInfo\n*/\nstatic void showAllWhereLoops(WhereInfo *pWInfo, WhereClause *pWC){\n  if( sqlite3WhereTrace ){    /* Display all of the WhereLoop objects */\n    WhereLoop *p;\n    int i;\n    static const char zLabel[] = \"0123456789abcdefghijklmnopqrstuvwyxz\"\n                                           \"ABCDEFGHIJKLMNOPQRSTUVWYXZ\";\n    for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){\n      p->cId = zLabel[i%(sizeof(zLabel)-1)];\n      sqlite3WhereLoopPrint(p, pWC);\n    }\n  }\n}\n# define WHERETRACE_ALL_LOOPS(W,C) showAllWhereLoops(W,C)\n#else\n# define WHERETRACE_ALL_LOOPS(W,C)\n#endif\n\n/*\n** Generate the beginning of the loop used for WHERE clause processing.\n** The return value is a pointer to an opaque structure that contains\n** information needed to terminate the loop.  Later, the calling routine\n** should invoke sqlite3WhereEnd() with the return value of this function\n** in order to complete the WHERE clause processing.\n**\n** If an error occurs, this routine returns NULL.\n**\n** The basic idea is to do a nested loop, one loop for each table in\n** the FROM clause of a select.  (INSERT and UPDATE statements are the\n** same as a SELECT with only a single table in the FROM clause.)  For\n** example, if the SQL is this:\n**\n**       SELECT * FROM t1, t2, t3 WHERE ...;\n**\n** Then the code generated is conceptually like the following:\n**\n**      foreach row1 in t1 do       \\    Code generated\n**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()\n**          foreach row3 in t3 do   /\n**            ...\n**          end                     \\    Code generated\n**        end                        |-- by sqlite3WhereEnd()\n**      end                         /\n**\n** Note that the loops might not be nested in the order in which they\n** appear in the FROM clause if a different order is better able to make\n** use of indices.  Note also that when the IN operator appears in\n** the WHERE clause, it might result in additional nested loops for\n** scanning through all values on the right-hand side of the IN.\n**\n** There are Btree cursors associated with each table.  t1 uses cursor\n** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.\n** And so forth.  This routine generates code to open those VDBE cursors\n** and sqlite3WhereEnd() generates the code to close them.\n**\n** The code that sqlite3WhereBegin() generates leaves the cursors named\n** in pTabList pointing at their appropriate entries.  The [...] code\n** can use OP_Column and OP_Rowid opcodes on these cursors to extract\n** data from the various tables of the loop.\n**\n** If the WHERE clause is empty, the foreach loops must each scan their\n** entire tables.  Thus a three-way join is an O(N^3) operation.  But if\n** the tables have indices and there are terms in the WHERE clause that\n** refer to those indices, a complete table scan can be avoided and the\n** code will run much faster.  Most of the work of this routine is checking\n** to see if there are indices that can be used to speed up the loop.\n**\n** Terms of the WHERE clause are also used to limit which rows actually\n** make it to the \"...\" in the middle of the loop.  After each \"foreach\",\n** terms of the WHERE clause that use only terms in that loop and outer\n** loops are evaluated and if false a jump is made around all subsequent\n** inner loops (or around the \"...\" if the test occurs within the inner-\n** most loop)\n**\n** OUTER JOINS\n**\n** An outer join of tables t1 and t2 is conceptally coded as follows:\n**\n**    foreach row1 in t1 do\n**      flag = 0\n**      foreach row2 in t2 do\n**        start:\n**          ...\n**          flag = 1\n**      end\n**      if flag==0 then\n**        move the row2 cursor to a null row\n**        goto start\n**      fi\n**    end\n**\n** ORDER BY CLAUSE PROCESSING\n**\n** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause\n** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement\n** if there is one.  If there is no ORDER BY clause or if this routine\n** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.\n**\n** The iIdxCur parameter is the cursor number of an index.  If \n** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index\n** to use for OR clause processing.  The WHERE clause should use this\n** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is\n** the first cursor in an array of cursors for all indices.  iIdxCur should\n** be used to compute the appropriate cursor depending on which index is\n** used.\n*/\nSQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(\n  Parse *pParse,          /* The parser context */\n  SrcList *pTabList,      /* FROM clause: A list of all tables to be scanned */\n  Expr *pWhere,           /* The WHERE clause */\n  ExprList *pOrderBy,     /* An ORDER BY (or GROUP BY) clause, or NULL */\n  ExprList *pResultSet,   /* Query result set.  Req'd for DISTINCT */\n  u16 wctrlFlags,         /* The WHERE_* flags defined in sqliteInt.h */\n  int iAuxArg             /* If WHERE_OR_SUBCLAUSE is set, index cursor number\n                          ** If WHERE_USE_LIMIT, then the limit amount */\n){\n  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */\n  int nTabList;              /* Number of elements in pTabList */\n  WhereInfo *pWInfo;         /* Will become the return value of this function */\n  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */\n  Bitmask notReady;          /* Cursors that are not yet positioned */\n  WhereLoopBuilder sWLB;     /* The WhereLoop builder */\n  WhereMaskSet *pMaskSet;    /* The expression mask set */\n  WhereLevel *pLevel;        /* A single level in pWInfo->a[] */\n  WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */\n  int ii;                    /* Loop counter */\n  sqlite3 *db;               /* Database connection */\n  int rc;                    /* Return code */\n  u8 bFordelete = 0;         /* OPFLAG_FORDELETE or zero, as appropriate */\n\n  assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (\n        (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 \n     && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 \n  ));\n\n  /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */\n  assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0\n            || (wctrlFlags & WHERE_USE_LIMIT)==0 );\n\n  /* Variable initialization */\n  db = pParse->db;\n  memset(&sWLB, 0, sizeof(sWLB));\n\n  /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */\n  testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );\n  if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;\n  sWLB.pOrderBy = pOrderBy;\n\n  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via\n  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */\n  if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){\n    wctrlFlags &= ~WHERE_WANT_DISTINCT;\n  }\n\n  /* The number of tables in the FROM clause is limited by the number of\n  ** bits in a Bitmask \n  */\n  testcase( pTabList->nSrc==BMS );\n  if( pTabList->nSrc>BMS ){\n    sqlite3ErrorMsg(pParse, \"at most %d tables in a join\", BMS);\n    return 0;\n  }\n\n  /* This function normally generates a nested loop for all tables in \n  ** pTabList.  But if the WHERE_OR_SUBCLAUSE flag is set, then we should\n  ** only generate code for the first table in pTabList and assume that\n  ** any cursors associated with subsequent tables are uninitialized.\n  */\n  nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;\n\n  /* Allocate and initialize the WhereInfo structure that will become the\n  ** return value. A single allocation is used to store the WhereInfo\n  ** struct, the contents of WhereInfo.a[], the WhereClause structure\n  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte\n  ** field (type Bitmask) it must be aligned on an 8-byte boundary on\n  ** some architectures. Hence the ROUND8() below.\n  */\n  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));\n  pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));\n  if( db->mallocFailed ){\n    sqlite3DbFree(db, pWInfo);\n    pWInfo = 0;\n    goto whereBeginError;\n  }\n  pWInfo->pParse = pParse;\n  pWInfo->pTabList = pTabList;\n  pWInfo->pOrderBy = pOrderBy;\n  pWInfo->pWhere = pWhere;\n  pWInfo->pResultSet = pResultSet;\n  pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;\n  pWInfo->nLevel = nTabList;\n  pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(pParse);\n  pWInfo->wctrlFlags = wctrlFlags;\n  pWInfo->iLimit = iAuxArg;\n  pWInfo->savedNQueryLoop = pParse->nQueryLoop;\n  memset(&pWInfo->nOBSat, 0, \n         offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));\n  memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));\n  assert( pWInfo->eOnePass==ONEPASS_OFF );  /* ONEPASS defaults to OFF */\n  pMaskSet = &pWInfo->sMaskSet;\n  sWLB.pWInfo = pWInfo;\n  sWLB.pWC = &pWInfo->sWC;\n  sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);\n  assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );\n  whereLoopInit(sWLB.pNew);\n#ifdef SQLITE_DEBUG\n  sWLB.pNew->cId = '*';\n#endif\n\n  /* Split the WHERE clause into separate subexpressions where each\n  ** subexpression is separated by an AND operator.\n  */\n  initMaskSet(pMaskSet);\n  sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);\n  sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);\n    \n  /* Special case: No FROM clause\n  */\n  if( nTabList==0 ){\n    if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;\n    if( wctrlFlags & WHERE_WANT_DISTINCT ){\n      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;\n    }\n    ExplainQueryPlan((pParse, 0, \"SCAN CONSTANT ROW\"));\n  }else{\n    /* Assign a bit from the bitmask to every term in the FROM clause.\n    **\n    ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.\n    **\n    ** The rule of the previous sentence ensures thta if X is the bitmask for\n    ** a table T, then X-1 is the bitmask for all other tables to the left of T.\n    ** Knowing the bitmask for all tables to the left of a left join is\n    ** important.  Ticket #3015.\n    **\n    ** Note that bitmasks are created for all pTabList->nSrc tables in\n    ** pTabList, not just the first nTabList tables.  nTabList is normally\n    ** equal to pTabList->nSrc but might be shortened to 1 if the\n    ** WHERE_OR_SUBCLAUSE flag is set.\n    */\n    ii = 0;\n    do{\n      createMask(pMaskSet, pTabList->a[ii].iCursor);\n      sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);\n    }while( (++ii)<pTabList->nSrc );\n  #ifdef SQLITE_DEBUG\n    {\n      Bitmask mx = 0;\n      for(ii=0; ii<pTabList->nSrc; ii++){\n        Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);\n        assert( m>=mx );\n        mx = m;\n      }\n    }\n  #endif\n  }\n  \n  /* Analyze all of the subexpressions. */\n  sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);\n  if( db->mallocFailed ) goto whereBeginError;\n\n  /* Special case: WHERE terms that do not refer to any tables in the join\n  ** (constant expressions). Evaluate each such term, and jump over all the\n  ** generated code if the result is not true.  \n  **\n  ** Do not do this if the expression contains non-deterministic functions\n  ** that are not within a sub-select. This is not strictly required, but\n  ** preserves SQLite's legacy behaviour in the following two cases:\n  **\n  **   FROM ... WHERE random()>0;           -- eval random() once per row\n  **   FROM ... WHERE (SELECT random())>0;  -- eval random() once overall\n  */\n  for(ii=0; ii<sWLB.pWC->nTerm; ii++){\n    WhereTerm *pT = &sWLB.pWC->a[ii];\n    if( pT->wtFlags & TERM_VIRTUAL ) continue;\n    if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){\n      sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);\n      pT->wtFlags |= TERM_CODED;\n    }\n  }\n\n  if( wctrlFlags & WHERE_WANT_DISTINCT ){\n    if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){\n      /* The DISTINCT marking is pointless.  Ignore it. */\n      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;\n    }else if( pOrderBy==0 ){\n      /* Try to ORDER BY the result set to make distinct processing easier */\n      pWInfo->wctrlFlags |= WHERE_DISTINCTBY;\n      pWInfo->pOrderBy = pResultSet;\n    }\n  }\n\n  /* Construct the WhereLoop objects */\n#if defined(WHERETRACE_ENABLED)\n  if( sqlite3WhereTrace & 0xffff ){\n    sqlite3DebugPrintf(\"*** Optimizer Start *** (wctrlFlags: 0x%x\",wctrlFlags);\n    if( wctrlFlags & WHERE_USE_LIMIT ){\n      sqlite3DebugPrintf(\", limit: %d\", iAuxArg);\n    }\n    sqlite3DebugPrintf(\")\\n\");\n    if( sqlite3WhereTrace & 0x100 ){\n      Select sSelect;\n      memset(&sSelect, 0, sizeof(sSelect));\n      sSelect.selFlags = SF_WhereBegin;\n      sSelect.pSrc = pTabList;\n      sSelect.pWhere = pWhere;\n      sSelect.pOrderBy = pOrderBy;\n      sSelect.pEList = pResultSet;\n      sqlite3TreeViewSelect(0, &sSelect, 0);\n    }\n  }\n  if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */\n    sqlite3DebugPrintf(\"---- WHERE clause at start of analysis:\\n\");\n    sqlite3WhereClausePrint(sWLB.pWC);\n  }\n#endif\n\n  if( nTabList!=1 || whereShortCut(&sWLB)==0 ){\n    rc = whereLoopAddAll(&sWLB);\n    if( rc ) goto whereBeginError;\n\n#ifdef SQLITE_ENABLE_STAT4\n    /* If one or more WhereTerm.truthProb values were used in estimating\n    ** loop parameters, but then those truthProb values were subsequently\n    ** changed based on STAT4 information while computing subsequent loops,\n    ** then we need to rerun the whole loop building process so that all\n    ** loops will be built using the revised truthProb values. */\n    if( sWLB.bldFlags2 & SQLITE_BLDF2_2NDPASS ){\n      WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);\n      WHERETRACE(0xffff, \n           (\"**** Redo all loop computations due to\"\n            \" TERM_HIGHTRUTH changes ****\\n\"));\n      while( pWInfo->pLoops ){\n        WhereLoop *p = pWInfo->pLoops;\n        pWInfo->pLoops = p->pNextLoop;\n        whereLoopDelete(db, p);\n      }\n      rc = whereLoopAddAll(&sWLB);\n      if( rc ) goto whereBeginError;\n    }\n#endif\n    WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);\n  \n    wherePathSolver(pWInfo, 0);\n    if( db->mallocFailed ) goto whereBeginError;\n    if( pWInfo->pOrderBy ){\n       wherePathSolver(pWInfo, pWInfo->nRowOut+1);\n       if( db->mallocFailed ) goto whereBeginError;\n    }\n  }\n  if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){\n     pWInfo->revMask = ALLBITS;\n  }\n  if( pParse->nErr || NEVER(db->mallocFailed) ){\n    goto whereBeginError;\n  }\n#ifdef WHERETRACE_ENABLED\n  if( sqlite3WhereTrace ){\n    sqlite3DebugPrintf(\"---- Solution nRow=%d\", pWInfo->nRowOut);\n    if( pWInfo->nOBSat>0 ){\n      sqlite3DebugPrintf(\" ORDERBY=%d,0x%llx\", pWInfo->nOBSat, pWInfo->revMask);\n    }\n    switch( pWInfo->eDistinct ){\n      case WHERE_DISTINCT_UNIQUE: {\n        sqlite3DebugPrintf(\"  DISTINCT=unique\");\n        break;\n      }\n      case WHERE_DISTINCT_ORDERED: {\n        sqlite3DebugPrintf(\"  DISTINCT=ordered\");\n        break;\n      }\n      case WHERE_DISTINCT_UNORDERED: {\n        sqlite3DebugPrintf(\"  DISTINCT=unordered\");\n        break;\n      }\n    }\n    sqlite3DebugPrintf(\"\\n\");\n    for(ii=0; ii<pWInfo->nLevel; ii++){\n      sqlite3WhereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);\n    }\n  }\n#endif\n\n  /* Attempt to omit tables from the join that do not affect the result.\n  ** For a table to not affect the result, the following must be true:\n  **\n  **   1) The query must not be an aggregate.\n  **   2) The table must be the RHS of a LEFT JOIN.\n  **   3) Either the query must be DISTINCT, or else the ON or USING clause\n  **      must contain a constraint that limits the scan of the table to \n  **      at most a single row.\n  **   4) The table must not be referenced by any part of the query apart\n  **      from its own USING or ON clause.\n  **\n  ** For example, given:\n  **\n  **     CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);\n  **     CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);\n  **     CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);\n  **\n  ** then table t2 can be omitted from the following:\n  **\n  **     SELECT v1, v3 FROM t1 \n  **       LEFT JOIN t2 ON (t1.ipk=t2.ipk)\n  **       LEFT JOIN t3 ON (t1.ipk=t3.ipk)\n  **\n  ** or from:\n  **\n  **     SELECT DISTINCT v1, v3 FROM t1 \n  **       LEFT JOIN t2\n  **       LEFT JOIN t3 ON (t1.ipk=t3.ipk)\n  */\n  notReady = ~(Bitmask)0;\n  if( pWInfo->nLevel>=2\n   && pResultSet!=0               /* guarantees condition (1) above */\n   && OptimizationEnabled(db, SQLITE_OmitNoopJoin)\n  ){\n    int i;\n    Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);\n    if( sWLB.pOrderBy ){\n      tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);\n    }\n    for(i=pWInfo->nLevel-1; i>=1; i--){\n      WhereTerm *pTerm, *pEnd;\n      struct SrcList_item *pItem;\n      pLoop = pWInfo->a[i].pWLoop;\n      pItem = &pWInfo->pTabList->a[pLoop->iTab];\n      if( (pItem->fg.jointype & JT_LEFT)==0 ) continue;\n      if( (wctrlFlags & WHERE_WANT_DISTINCT)==0\n       && (pLoop->wsFlags & WHERE_ONEROW)==0\n      ){\n        continue;\n      }\n      if( (tabUsed & pLoop->maskSelf)!=0 ) continue;\n      pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;\n      for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){\n        if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){\n          if( !ExprHasProperty(pTerm->pExpr, EP_FromJoin)\n           || pTerm->pExpr->iRightJoinTable!=pItem->iCursor\n          ){\n            break;\n          }\n        }\n      }\n      if( pTerm<pEnd ) continue;\n      WHERETRACE(0xffff, (\"-> drop loop %c not used\\n\", pLoop->cId));\n      notReady &= ~pLoop->maskSelf;\n      for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){\n        if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){\n          pTerm->wtFlags |= TERM_CODED;\n        }\n      }\n      if( i!=pWInfo->nLevel-1 ){\n        int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);\n        memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);\n      }\n      pWInfo->nLevel--;\n      nTabList--;\n    }\n  }\n#if defined(WHERETRACE_ENABLED)\n  if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */\n    sqlite3DebugPrintf(\"---- WHERE clause at end of analysis:\\n\");\n    sqlite3WhereClausePrint(sWLB.pWC);\n  }\n  WHERETRACE(0xffff,(\"*** Optimizer Finished ***\\n\"));\n#endif\n  pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;\n\n  /* If the caller is an UPDATE or DELETE statement that is requesting\n  ** to use a one-pass algorithm, determine if this is appropriate.\n  **\n  ** A one-pass approach can be used if the caller has requested one\n  ** and either (a) the scan visits at most one row or (b) each\n  ** of the following are true:\n  **\n  **   * the caller has indicated that a one-pass approach can be used\n  **     with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and\n  **   * the table is not a virtual table, and\n  **   * either the scan does not use the OR optimization or the caller\n  **     is a DELETE operation (WHERE_DUPLICATES_OK is only specified\n  **     for DELETE).\n  **\n  ** The last qualification is because an UPDATE statement uses\n  ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can\n  ** use a one-pass approach, and this is not set accurately for scans\n  ** that use the OR optimization.\n  */\n  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );\n  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){\n    int wsFlags = pWInfo->a[0].pWLoop->wsFlags;\n    int bOnerow = (wsFlags & WHERE_ONEROW)!=0;\n    assert( !(wsFlags & WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pTab) );\n    if( bOnerow || (\n        0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW)\n     && !IsVirtual(pTabList->a[0].pTab)\n     && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK))\n    )){\n      pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;\n      if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){\n        if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){\n          bFordelete = OPFLAG_FORDELETE;\n        }\n        pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);\n      }\n    }\n  }\n\n  /* Open all tables in the pTabList and any indices selected for\n  ** searching those tables.\n  */\n  for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){\n    Table *pTab;     /* Table to open */\n    int iDb;         /* Index of database containing table/index */\n    struct SrcList_item *pTabItem;\n\n    pTabItem = &pTabList->a[pLevel->iFrom];\n    pTab = pTabItem->pTab;\n    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n    pLoop = pLevel->pWLoop;\n    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){\n      /* Do nothing */\n    }else\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){\n      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);\n      int iCur = pTabItem->iCursor;\n      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);\n    }else if( IsVirtual(pTab) ){\n      /* noop */\n    }else\n#endif\n    if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0\n         && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){\n      int op = OP_OpenRead;\n      if( pWInfo->eOnePass!=ONEPASS_OFF ){\n        op = OP_OpenWrite;\n        pWInfo->aiCurOnePass[0] = pTabItem->iCursor;\n      };\n      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);\n      assert( pTabItem->iCursor==pLevel->iTabCur );\n      testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );\n      testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );\n      if( pWInfo->eOnePass==ONEPASS_OFF \n       && pTab->nCol<BMS\n       && (pTab->tabFlags & (TF_HasGenerated|TF_WithoutRowid))==0\n      ){\n        /* If we know that only a prefix of the record will be used,\n        ** it is advantageous to reduce the \"column count\" field in\n        ** the P4 operand of the OP_OpenRead/Write opcode. */\n        Bitmask b = pTabItem->colUsed;\n        int n = 0;\n        for(; b; b=b>>1, n++){}\n        sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);\n        assert( n<=pTab->nCol );\n      }\n#ifdef SQLITE_ENABLE_CURSOR_HINTS\n      if( pLoop->u.btree.pIndex!=0 ){\n        sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);\n      }else\n#endif\n      {\n        sqlite3VdbeChangeP5(v, bFordelete);\n      }\n#ifdef SQLITE_ENABLE_COLUMN_USED_MASK\n      sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,\n                            (const u8*)&pTabItem->colUsed, P4_INT64);\n#endif\n    }else{\n      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);\n    }\n    if( pLoop->wsFlags & WHERE_INDEXED ){\n      Index *pIx = pLoop->u.btree.pIndex;\n      int iIndexCur;\n      int op = OP_OpenRead;\n      /* iAuxArg is always set to a positive value if ONEPASS is possible */\n      assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );\n      if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)\n       && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0\n      ){\n        /* This is one term of an OR-optimization using the PRIMARY KEY of a\n        ** WITHOUT ROWID table.  No need for a separate index */\n        iIndexCur = pLevel->iTabCur;\n        op = 0;\n      }else if( pWInfo->eOnePass!=ONEPASS_OFF ){\n        Index *pJ = pTabItem->pTab->pIndex;\n        iIndexCur = iAuxArg;\n        assert( wctrlFlags & WHERE_ONEPASS_DESIRED );\n        while( ALWAYS(pJ) && pJ!=pIx ){\n          iIndexCur++;\n          pJ = pJ->pNext;\n        }\n        op = OP_OpenWrite;\n        pWInfo->aiCurOnePass[1] = iIndexCur;\n      }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){\n        iIndexCur = iAuxArg;\n        op = OP_ReopenIdx;\n      }else{\n        iIndexCur = pParse->nTab++;\n      }\n      pLevel->iIdxCur = iIndexCur;\n      assert( pIx->pSchema==pTab->pSchema );\n      assert( iIndexCur>=0 );\n      if( op ){\n        sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);\n        sqlite3VdbeSetP4KeyInfo(pParse, pIx);\n        if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0\n         && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0\n         && (pLoop->wsFlags & WHERE_BIGNULL_SORT)==0\n         && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0\n         && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED\n        ){\n          sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ);\n        }\n        VdbeComment((v, \"%s\", pIx->zName));\n#ifdef SQLITE_ENABLE_COLUMN_USED_MASK\n        {\n          u64 colUsed = 0;\n          int ii, jj;\n          for(ii=0; ii<pIx->nColumn; ii++){\n            jj = pIx->aiColumn[ii];\n            if( jj<0 ) continue;\n            if( jj>63 ) jj = 63;\n            if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;\n            colUsed |= ((u64)1)<<(ii<63 ? ii : 63);\n          }\n          sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,\n                                (u8*)&colUsed, P4_INT64);\n        }\n#endif /* SQLITE_ENABLE_COLUMN_USED_MASK */\n      }\n    }\n    if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);\n  }\n  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);\n  if( db->mallocFailed ) goto whereBeginError;\n\n  /* Generate the code to do the search.  Each iteration of the for\n  ** loop below generates code for a single nested loop of the VM\n  ** program.\n  */\n  for(ii=0; ii<nTabList; ii++){\n    int addrExplain;\n    int wsFlags;\n    pLevel = &pWInfo->a[ii];\n    wsFlags = pLevel->pWLoop->wsFlags;\n#ifndef SQLITE_OMIT_AUTOMATIC_INDEX\n    if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){\n      constructAutomaticIndex(pParse, &pWInfo->sWC,\n                &pTabList->a[pLevel->iFrom], notReady, pLevel);\n      if( db->mallocFailed ) goto whereBeginError;\n    }\n#endif\n    addrExplain = sqlite3WhereExplainOneScan(\n        pParse, pTabList, pLevel, wctrlFlags\n    );\n    pLevel->addrBody = sqlite3VdbeCurrentAddr(v);\n    notReady = sqlite3WhereCodeOneLoopStart(pParse,v,pWInfo,ii,pLevel,notReady);\n    pWInfo->iContinue = pLevel->addrCont;\n    if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){\n      sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);\n    }\n  }\n\n  /* Done. */\n  VdbeModuleComment((v, \"Begin WHERE-core\"));\n  return pWInfo;\n\n  /* Jump here if malloc fails */\nwhereBeginError:\n  if( pWInfo ){\n    pParse->nQueryLoop = pWInfo->savedNQueryLoop;\n    whereInfoFree(db, pWInfo);\n  }\n  return 0;\n}\n\n/*\n** Part of sqlite3WhereEnd() will rewrite opcodes to reference the\n** index rather than the main table.  In SQLITE_DEBUG mode, we want\n** to trace those changes if PRAGMA vdbe_addoptrace=on.  This routine\n** does that.\n*/\n#ifndef SQLITE_DEBUG\n# define OpcodeRewriteTrace(D,K,P) /* no-op */\n#else\n# define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P)\n  static void sqlite3WhereOpcodeRewriteTrace(\n    sqlite3 *db,\n    int pc,\n    VdbeOp *pOp\n  ){\n    if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return;\n    sqlite3VdbePrintOp(0, pc, pOp);\n  }\n#endif\n\n/*\n** Generate the end of the WHERE loop.  See comments on \n** sqlite3WhereBegin() for additional information.\n*/\nSQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){\n  Parse *pParse = pWInfo->pParse;\n  Vdbe *v = pParse->pVdbe;\n  int i;\n  WhereLevel *pLevel;\n  WhereLoop *pLoop;\n  SrcList *pTabList = pWInfo->pTabList;\n  sqlite3 *db = pParse->db;\n\n  /* Generate loop termination code.\n  */\n  VdbeModuleComment((v, \"End WHERE-core\"));\n  for(i=pWInfo->nLevel-1; i>=0; i--){\n    int addr;\n    pLevel = &pWInfo->a[i];\n    pLoop = pLevel->pWLoop;\n    if( pLevel->op!=OP_Noop ){\n#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT\n      int addrSeek = 0;\n      Index *pIdx;\n      int n;\n      if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED\n       && i==pWInfo->nLevel-1  /* Ticket [ef9318757b152e3] 2017-10-21 */\n       && (pLoop->wsFlags & WHERE_INDEXED)!=0\n       && (pIdx = pLoop->u.btree.pIndex)->hasStat1\n       && (n = pLoop->u.btree.nDistinctCol)>0\n       && pIdx->aiRowLogEst[n]>=36\n      ){\n        int r1 = pParse->nMem+1;\n        int j, op;\n        for(j=0; j<n; j++){\n          sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);\n        }\n        pParse->nMem += n+1;\n        op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;\n        addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);\n        VdbeCoverageIf(v, op==OP_SeekLT);\n        VdbeCoverageIf(v, op==OP_SeekGT);\n        sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);\n      }\n#endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */\n      /* The common case: Advance to the next row */\n      sqlite3VdbeResolveLabel(v, pLevel->addrCont);\n      sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);\n      sqlite3VdbeChangeP5(v, pLevel->p5);\n      VdbeCoverage(v);\n      VdbeCoverageIf(v, pLevel->op==OP_Next);\n      VdbeCoverageIf(v, pLevel->op==OP_Prev);\n      VdbeCoverageIf(v, pLevel->op==OP_VNext);\n      if( pLevel->regBignull ){\n        sqlite3VdbeResolveLabel(v, pLevel->addrBignull);\n        sqlite3VdbeAddOp2(v, OP_DecrJumpZero, pLevel->regBignull, pLevel->p2-1);\n        VdbeCoverage(v);\n      }\n#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT\n      if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);\n#endif\n    }else{\n      sqlite3VdbeResolveLabel(v, pLevel->addrCont);\n    }\n    if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){\n      struct InLoop *pIn;\n      int j;\n      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);\n      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){\n        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);\n        if( pIn->eEndLoopOp!=OP_Noop ){\n          if( pIn->nPrefix ){\n            assert( pLoop->wsFlags & WHERE_IN_EARLYOUT );\n            if( pLevel->iLeftJoin ){\n              /* For LEFT JOIN queries, cursor pIn->iCur may not have been\n              ** opened yet. This occurs for WHERE clauses such as\n              ** \"a = ? AND b IN (...)\", where the index is on (a, b). If\n              ** the RHS of the (a=?) is NULL, then the \"b IN (...)\" may\n              ** never have been coded, but the body of the loop run to\n              ** return the null-row. So, if the cursor is not open yet,\n              ** jump over the OP_Next or OP_Prev instruction about to\n              ** be coded.  */\n              sqlite3VdbeAddOp2(v, OP_IfNotOpen, pIn->iCur, \n                  sqlite3VdbeCurrentAddr(v) + 2 + \n                     ((pLoop->wsFlags & WHERE_VIRTUALTABLE)==0)\n              );\n              VdbeCoverage(v);\n            }\n            if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ){\n              sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,\n                  sqlite3VdbeCurrentAddr(v)+2,\n                  pIn->iBase, pIn->nPrefix);\n              VdbeCoverage(v);\n            }\n          }\n          sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);\n          VdbeCoverage(v);\n          VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);\n          VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);\n        }\n        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);\n      }\n    }\n    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);\n    if( pLevel->addrSkip ){\n      sqlite3VdbeGoto(v, pLevel->addrSkip);\n      VdbeComment((v, \"next skip-scan on %s\", pLoop->u.btree.pIndex->zName));\n      sqlite3VdbeJumpHere(v, pLevel->addrSkip);\n      sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);\n    }\n#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS\n    if( pLevel->addrLikeRep ){\n      sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),\n                        pLevel->addrLikeRep);\n      VdbeCoverage(v);\n    }\n#endif\n    if( pLevel->iLeftJoin ){\n      int ws = pLoop->wsFlags;\n      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);\n      assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );\n      if( (ws & WHERE_IDX_ONLY)==0 ){\n        assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor );\n        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);\n      }\n      if( (ws & WHERE_INDEXED) \n       || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx) \n      ){\n        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);\n      }\n      if( pLevel->op==OP_Return ){\n        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);\n      }else{\n        sqlite3VdbeGoto(v, pLevel->addrFirst);\n      }\n      sqlite3VdbeJumpHere(v, addr);\n    }\n    VdbeModuleComment((v, \"End WHERE-loop%d: %s\", i,\n                     pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));\n  }\n\n  /* The \"break\" point is here, just past the end of the outer loop.\n  ** Set it.\n  */\n  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);\n\n  assert( pWInfo->nLevel<=pTabList->nSrc );\n  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){\n    int k, last;\n    VdbeOp *pOp;\n    Index *pIdx = 0;\n    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];\n    Table *pTab = pTabItem->pTab;\n    assert( pTab!=0 );\n    pLoop = pLevel->pWLoop;\n\n    /* For a co-routine, change all OP_Column references to the table of\n    ** the co-routine into OP_Copy of result contained in a register.\n    ** OP_Rowid becomes OP_Null.\n    */\n    if( pTabItem->fg.viaCoroutine ){\n      testcase( pParse->db->mallocFailed );\n      translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,\n                            pTabItem->regResult, 0);\n      continue;\n    }\n\n#ifdef SQLITE_ENABLE_EARLY_CURSOR_CLOSE\n    /* Close all of the cursors that were opened by sqlite3WhereBegin.\n    ** Except, do not close cursors that will be reused by the OR optimization\n    ** (WHERE_OR_SUBCLAUSE).  And do not close the OP_OpenWrite cursors\n    ** created for the ONEPASS optimization.\n    */\n    if( (pTab->tabFlags & TF_Ephemeral)==0\n     && pTab->pSelect==0\n     && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0\n    ){\n      int ws = pLoop->wsFlags;\n      if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){\n        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);\n      }\n      if( (ws & WHERE_INDEXED)!=0\n       && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 \n       && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]\n      ){\n        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);\n      }\n    }\n#endif\n\n    /* If this scan uses an index, make VDBE code substitutions to read data\n    ** from the index instead of from the table where possible.  In some cases\n    ** this optimization prevents the table from ever being read, which can\n    ** yield a significant performance boost.\n    ** \n    ** Calls to the code generator in between sqlite3WhereBegin and\n    ** sqlite3WhereEnd will have created code that references the table\n    ** directly.  This loop scans all that code looking for opcodes\n    ** that reference the table and converts them into opcodes that\n    ** reference the index.\n    */\n    if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){\n      pIdx = pLoop->u.btree.pIndex;\n    }else if( pLoop->wsFlags & WHERE_MULTI_OR ){\n      pIdx = pLevel->u.pCovidx;\n    }\n    if( pIdx\n     && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))\n     && !db->mallocFailed\n    ){\n      last = sqlite3VdbeCurrentAddr(v);\n      k = pLevel->addrBody;\n#ifdef SQLITE_DEBUG\n      if( db->flags & SQLITE_VdbeAddopTrace ){\n        printf(\"TRANSLATE opcodes in range %d..%d\\n\", k, last-1);\n      }\n#endif\n      pOp = sqlite3VdbeGetOp(v, k);\n      for(; k<last; k++, pOp++){\n        if( pOp->p1!=pLevel->iTabCur ) continue;\n        if( pOp->opcode==OP_Column\n#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC\n         || pOp->opcode==OP_Offset\n#endif\n        ){\n          int x = pOp->p2;\n          assert( pIdx->pTable==pTab );\n          if( !HasRowid(pTab) ){\n            Index *pPk = sqlite3PrimaryKeyIndex(pTab);\n            x = pPk->aiColumn[x];\n            assert( x>=0 );\n          }else{\n            testcase( x!=sqlite3StorageColumnToTable(pTab,x) );\n            x = sqlite3StorageColumnToTable(pTab,x);\n          }\n          x = sqlite3TableColumnToIndex(pIdx, x);\n          if( x>=0 ){\n            pOp->p2 = x;\n            pOp->p1 = pLevel->iIdxCur;\n            OpcodeRewriteTrace(db, k, pOp);\n          }\n          assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 \n              || pWInfo->eOnePass );\n        }else if( pOp->opcode==OP_Rowid ){\n          pOp->p1 = pLevel->iIdxCur;\n          pOp->opcode = OP_IdxRowid;\n          OpcodeRewriteTrace(db, k, pOp);\n        }else if( pOp->opcode==OP_IfNullRow ){\n          pOp->p1 = pLevel->iIdxCur;\n          OpcodeRewriteTrace(db, k, pOp);\n        }\n      }\n#ifdef SQLITE_DEBUG\n      if( db->flags & SQLITE_VdbeAddopTrace ) printf(\"TRANSLATE complete\\n\");\n#endif\n    }\n  }\n\n  /* Undo all Expr node modifications */\n  while( pWInfo->pExprMods ){\n    WhereExprMod *p = pWInfo->pExprMods;\n    pWInfo->pExprMods = p->pNext;\n    memcpy(p->pExpr, &p->orig, sizeof(p->orig));\n    sqlite3DbFree(db, p);\n  }\n\n  /* Final cleanup\n  */\n  pParse->nQueryLoop = pWInfo->savedNQueryLoop;\n  whereInfoFree(db, pWInfo);\n  return;\n}\n\n/************** End of where.c ***********************************************/\n/************** Begin file window.c ******************************************/\n/*\n** 2018 May 08\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n*/\n/* #include \"sqliteInt.h\" */\n\n#ifndef SQLITE_OMIT_WINDOWFUNC\n\n/*\n** SELECT REWRITING\n**\n**   Any SELECT statement that contains one or more window functions in\n**   either the select list or ORDER BY clause (the only two places window\n**   functions may be used) is transformed by function sqlite3WindowRewrite()\n**   in order to support window function processing. For example, with the\n**   schema:\n**\n**     CREATE TABLE t1(a, b, c, d, e, f, g);\n**\n**   the statement:\n**\n**     SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e;\n**\n**   is transformed to:\n**\n**     SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM (\n**         SELECT a, e, c, d, b FROM t1 ORDER BY c, d\n**     ) ORDER BY e;\n**\n**   The flattening optimization is disabled when processing this transformed\n**   SELECT statement. This allows the implementation of the window function\n**   (in this case max()) to process rows sorted in order of (c, d), which\n**   makes things easier for obvious reasons. More generally:\n**\n**     * FROM, WHERE, GROUP BY and HAVING clauses are all moved to \n**       the sub-query.\n**\n**     * ORDER BY, LIMIT and OFFSET remain part of the parent query.\n**\n**     * Terminals from each of the expression trees that make up the \n**       select-list and ORDER BY expressions in the parent query are\n**       selected by the sub-query. For the purposes of the transformation,\n**       terminals are column references and aggregate functions.\n**\n**   If there is more than one window function in the SELECT that uses\n**   the same window declaration (the OVER bit), then a single scan may\n**   be used to process more than one window function. For example:\n**\n**     SELECT max(b) OVER (PARTITION BY c ORDER BY d), \n**            min(e) OVER (PARTITION BY c ORDER BY d) \n**     FROM t1;\n**\n**   is transformed in the same way as the example above. However:\n**\n**     SELECT max(b) OVER (PARTITION BY c ORDER BY d), \n**            min(e) OVER (PARTITION BY a ORDER BY b) \n**     FROM t1;\n**\n**   Must be transformed to:\n**\n**     SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM (\n**         SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM\n**           SELECT a, e, c, d, b FROM t1 ORDER BY a, b\n**         ) ORDER BY c, d\n**     ) ORDER BY e;\n**\n**   so that both min() and max() may process rows in the order defined by\n**   their respective window declarations.\n**\n** INTERFACE WITH SELECT.C\n**\n**   When processing the rewritten SELECT statement, code in select.c calls\n**   sqlite3WhereBegin() to begin iterating through the results of the\n**   sub-query, which is always implemented as a co-routine. It then calls\n**   sqlite3WindowCodeStep() to process rows and finish the scan by calling\n**   sqlite3WhereEnd().\n**\n**   sqlite3WindowCodeStep() generates VM code so that, for each row returned\n**   by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked.\n**   When the sub-routine is invoked:\n**\n**     * The results of all window-functions for the row are stored\n**       in the associated Window.regResult registers.\n**\n**     * The required terminal values are stored in the current row of\n**       temp table Window.iEphCsr.\n**\n**   In some cases, depending on the window frame and the specific window\n**   functions invoked, sqlite3WindowCodeStep() caches each entire partition\n**   in a temp table before returning any rows. In other cases it does not.\n**   This detail is encapsulated within this file, the code generated by\n**   select.c is the same in either case.\n**\n** BUILT-IN WINDOW FUNCTIONS\n**\n**   This implementation features the following built-in window functions:\n**\n**     row_number()\n**     rank()\n**     dense_rank()\n**     percent_rank()\n**     cume_dist()\n**     ntile(N)\n**     lead(expr [, offset [, default]])\n**     lag(expr [, offset [, default]])\n**     first_value(expr)\n**     last_value(expr)\n**     nth_value(expr, N)\n**   \n**   These are the same built-in window functions supported by Postgres. \n**   Although the behaviour of aggregate window functions (functions that\n**   can be used as either aggregates or window funtions) allows them to\n**   be implemented using an API, built-in window functions are much more\n**   esoteric. Additionally, some window functions (e.g. nth_value()) \n**   may only be implemented by caching the entire partition in memory.\n**   As such, some built-in window functions use the same API as aggregate\n**   window functions and some are implemented directly using VDBE \n**   instructions. Additionally, for those functions that use the API, the\n**   window frame is sometimes modified before the SELECT statement is\n**   rewritten. For example, regardless of the specified window frame, the\n**   row_number() function always uses:\n**\n**     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW\n**\n**   See sqlite3WindowUpdate() for details.\n**\n**   As well as some of the built-in window functions, aggregate window\n**   functions min() and max() are implemented using VDBE instructions if\n**   the start of the window frame is declared as anything other than \n**   UNBOUNDED PRECEDING.\n*/\n\n/*\n** Implementation of built-in window function row_number(). Assumes that the\n** window frame has been coerced to:\n**\n**   ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW\n*/\nstatic void row_numberStepFunc(\n  sqlite3_context *pCtx, \n  int nArg,\n  sqlite3_value **apArg\n){\n  i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  if( p ) (*p)++;\n  UNUSED_PARAMETER(nArg);\n  UNUSED_PARAMETER(apArg);\n}\nstatic void row_numberValueFunc(sqlite3_context *pCtx){\n  i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  sqlite3_result_int64(pCtx, (p ? *p : 0));\n}\n\n/*\n** Context object type used by rank(), dense_rank(), percent_rank() and\n** cume_dist().\n*/\nstruct CallCount {\n  i64 nValue;\n  i64 nStep;\n  i64 nTotal;\n};\n\n/*\n** Implementation of built-in window function dense_rank(). Assumes that\n** the window frame has been set to:\n**\n**   RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW \n*/\nstatic void dense_rankStepFunc(\n  sqlite3_context *pCtx, \n  int nArg,\n  sqlite3_value **apArg\n){\n  struct CallCount *p;\n  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  if( p ) p->nStep = 1;\n  UNUSED_PARAMETER(nArg);\n  UNUSED_PARAMETER(apArg);\n}\nstatic void dense_rankValueFunc(sqlite3_context *pCtx){\n  struct CallCount *p;\n  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  if( p ){\n    if( p->nStep ){\n      p->nValue++;\n      p->nStep = 0;\n    }\n    sqlite3_result_int64(pCtx, p->nValue);\n  }\n}\n\n/*\n** Implementation of built-in window function nth_value(). This\n** implementation is used in \"slow mode\" only - when the EXCLUDE clause\n** is not set to the default value \"NO OTHERS\".\n*/\nstruct NthValueCtx {\n  i64 nStep;\n  sqlite3_value *pValue;\n};\nstatic void nth_valueStepFunc(\n  sqlite3_context *pCtx, \n  int nArg,\n  sqlite3_value **apArg\n){\n  struct NthValueCtx *p;\n  p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  if( p ){\n    i64 iVal;\n    switch( sqlite3_value_numeric_type(apArg[1]) ){\n      case SQLITE_INTEGER:\n        iVal = sqlite3_value_int64(apArg[1]);\n        break;\n      case SQLITE_FLOAT: {\n        double fVal = sqlite3_value_double(apArg[1]);\n        if( ((i64)fVal)!=fVal ) goto error_out;\n        iVal = (i64)fVal;\n        break;\n      }\n      default:\n        goto error_out;\n    }\n    if( iVal<=0 ) goto error_out;\n\n    p->nStep++;\n    if( iVal==p->nStep ){\n      p->pValue = sqlite3_value_dup(apArg[0]);\n      if( !p->pValue ){\n        sqlite3_result_error_nomem(pCtx);\n      }\n    }\n  }\n  UNUSED_PARAMETER(nArg);\n  UNUSED_PARAMETER(apArg);\n  return;\n\n error_out:\n  sqlite3_result_error(\n      pCtx, \"second argument to nth_value must be a positive integer\", -1\n  );\n}\nstatic void nth_valueFinalizeFunc(sqlite3_context *pCtx){\n  struct NthValueCtx *p;\n  p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, 0);\n  if( p && p->pValue ){\n    sqlite3_result_value(pCtx, p->pValue);\n    sqlite3_value_free(p->pValue);\n    p->pValue = 0;\n  }\n}\n#define nth_valueInvFunc noopStepFunc\n#define nth_valueValueFunc noopValueFunc\n\nstatic void first_valueStepFunc(\n  sqlite3_context *pCtx, \n  int nArg,\n  sqlite3_value **apArg\n){\n  struct NthValueCtx *p;\n  p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  if( p && p->pValue==0 ){\n    p->pValue = sqlite3_value_dup(apArg[0]);\n    if( !p->pValue ){\n      sqlite3_result_error_nomem(pCtx);\n    }\n  }\n  UNUSED_PARAMETER(nArg);\n  UNUSED_PARAMETER(apArg);\n}\nstatic void first_valueFinalizeFunc(sqlite3_context *pCtx){\n  struct NthValueCtx *p;\n  p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  if( p && p->pValue ){\n    sqlite3_result_value(pCtx, p->pValue);\n    sqlite3_value_free(p->pValue);\n    p->pValue = 0;\n  }\n}\n#define first_valueInvFunc noopStepFunc\n#define first_valueValueFunc noopValueFunc\n\n/*\n** Implementation of built-in window function rank(). Assumes that\n** the window frame has been set to:\n**\n**   RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW \n*/\nstatic void rankStepFunc(\n  sqlite3_context *pCtx, \n  int nArg,\n  sqlite3_value **apArg\n){\n  struct CallCount *p;\n  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  if( p ){\n    p->nStep++;\n    if( p->nValue==0 ){\n      p->nValue = p->nStep;\n    }\n  }\n  UNUSED_PARAMETER(nArg);\n  UNUSED_PARAMETER(apArg);\n}\nstatic void rankValueFunc(sqlite3_context *pCtx){\n  struct CallCount *p;\n  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  if( p ){\n    sqlite3_result_int64(pCtx, p->nValue);\n    p->nValue = 0;\n  }\n}\n\n/*\n** Implementation of built-in window function percent_rank(). Assumes that\n** the window frame has been set to:\n**\n**   GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n*/\nstatic void percent_rankStepFunc(\n  sqlite3_context *pCtx, \n  int nArg,\n  sqlite3_value **apArg\n){\n  struct CallCount *p;\n  UNUSED_PARAMETER(nArg); assert( nArg==0 );\n  UNUSED_PARAMETER(apArg);\n  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  if( p ){\n    p->nTotal++;\n  }\n}\nstatic void percent_rankInvFunc(\n  sqlite3_context *pCtx, \n  int nArg,\n  sqlite3_value **apArg\n){\n  struct CallCount *p;\n  UNUSED_PARAMETER(nArg); assert( nArg==0 );\n  UNUSED_PARAMETER(apArg);\n  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  p->nStep++;\n}\nstatic void percent_rankValueFunc(sqlite3_context *pCtx){\n  struct CallCount *p;\n  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  if( p ){\n    p->nValue = p->nStep;\n    if( p->nTotal>1 ){\n      double r = (double)p->nValue / (double)(p->nTotal-1);\n      sqlite3_result_double(pCtx, r);\n    }else{\n      sqlite3_result_double(pCtx, 0.0);\n    }\n  }\n}\n#define percent_rankFinalizeFunc percent_rankValueFunc\n\n/*\n** Implementation of built-in window function cume_dist(). Assumes that\n** the window frame has been set to:\n**\n**   GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING\n*/\nstatic void cume_distStepFunc(\n  sqlite3_context *pCtx, \n  int nArg,\n  sqlite3_value **apArg\n){\n  struct CallCount *p;\n  UNUSED_PARAMETER(nArg); assert( nArg==0 );\n  UNUSED_PARAMETER(apArg);\n  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  if( p ){\n    p->nTotal++;\n  }\n}\nstatic void cume_distInvFunc(\n  sqlite3_context *pCtx, \n  int nArg,\n  sqlite3_value **apArg\n){\n  struct CallCount *p;\n  UNUSED_PARAMETER(nArg); assert( nArg==0 );\n  UNUSED_PARAMETER(apArg);\n  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  p->nStep++;\n}\nstatic void cume_distValueFunc(sqlite3_context *pCtx){\n  struct CallCount *p;\n  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, 0);\n  if( p ){\n    double r = (double)(p->nStep) / (double)(p->nTotal);\n    sqlite3_result_double(pCtx, r);\n  }\n}\n#define cume_distFinalizeFunc cume_distValueFunc\n\n/*\n** Context object for ntile() window function.\n*/\nstruct NtileCtx {\n  i64 nTotal;                     /* Total rows in partition */\n  i64 nParam;                     /* Parameter passed to ntile(N) */\n  i64 iRow;                       /* Current row */\n};\n\n/*\n** Implementation of ntile(). This assumes that the window frame has\n** been coerced to:\n**\n**   ROWS CURRENT ROW AND UNBOUNDED FOLLOWING\n*/\nstatic void ntileStepFunc(\n  sqlite3_context *pCtx, \n  int nArg,\n  sqlite3_value **apArg\n){\n  struct NtileCtx *p;\n  assert( nArg==1 ); UNUSED_PARAMETER(nArg);\n  p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  if( p ){\n    if( p->nTotal==0 ){\n      p->nParam = sqlite3_value_int64(apArg[0]);\n      if( p->nParam<=0 ){\n        sqlite3_result_error(\n            pCtx, \"argument of ntile must be a positive integer\", -1\n        );\n      }\n    }\n    p->nTotal++;\n  }\n}\nstatic void ntileInvFunc(\n  sqlite3_context *pCtx, \n  int nArg,\n  sqlite3_value **apArg\n){\n  struct NtileCtx *p;\n  assert( nArg==1 ); UNUSED_PARAMETER(nArg);\n  UNUSED_PARAMETER(apArg);\n  p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  p->iRow++;\n}\nstatic void ntileValueFunc(sqlite3_context *pCtx){\n  struct NtileCtx *p;\n  p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  if( p && p->nParam>0 ){\n    int nSize = (p->nTotal / p->nParam);\n    if( nSize==0 ){\n      sqlite3_result_int64(pCtx, p->iRow+1);\n    }else{\n      i64 nLarge = p->nTotal - p->nParam*nSize;\n      i64 iSmall = nLarge*(nSize+1);\n      i64 iRow = p->iRow;\n\n      assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );\n\n      if( iRow<iSmall ){\n        sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));\n      }else{\n        sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);\n      }\n    }\n  }\n}\n#define ntileFinalizeFunc ntileValueFunc\n\n/*\n** Context object for last_value() window function.\n*/\nstruct LastValueCtx {\n  sqlite3_value *pVal;\n  int nVal;\n};\n\n/*\n** Implementation of last_value().\n*/\nstatic void last_valueStepFunc(\n  sqlite3_context *pCtx, \n  int nArg,\n  sqlite3_value **apArg\n){\n  struct LastValueCtx *p;\n  UNUSED_PARAMETER(nArg);\n  p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  if( p ){\n    sqlite3_value_free(p->pVal);\n    p->pVal = sqlite3_value_dup(apArg[0]);\n    if( p->pVal==0 ){\n      sqlite3_result_error_nomem(pCtx);\n    }else{\n      p->nVal++;\n    }\n  }\n}\nstatic void last_valueInvFunc(\n  sqlite3_context *pCtx, \n  int nArg,\n  sqlite3_value **apArg\n){\n  struct LastValueCtx *p;\n  UNUSED_PARAMETER(nArg);\n  UNUSED_PARAMETER(apArg);\n  p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  if( ALWAYS(p) ){\n    p->nVal--;\n    if( p->nVal==0 ){\n      sqlite3_value_free(p->pVal);\n      p->pVal = 0;\n    }\n  }\n}\nstatic void last_valueValueFunc(sqlite3_context *pCtx){\n  struct LastValueCtx *p;\n  p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, 0);\n  if( p && p->pVal ){\n    sqlite3_result_value(pCtx, p->pVal);\n  }\n}\nstatic void last_valueFinalizeFunc(sqlite3_context *pCtx){\n  struct LastValueCtx *p;\n  p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));\n  if( p && p->pVal ){\n    sqlite3_result_value(pCtx, p->pVal);\n    sqlite3_value_free(p->pVal);\n    p->pVal = 0;\n  }\n}\n\n/*\n** Static names for the built-in window function names.  These static\n** names are used, rather than string literals, so that FuncDef objects\n** can be associated with a particular window function by direct\n** comparison of the zName pointer.  Example:\n**\n**       if( pFuncDef->zName==row_valueName ){ ... }\n*/\nstatic const char row_numberName[] =   \"row_number\";\nstatic const char dense_rankName[] =   \"dense_rank\";\nstatic const char rankName[] =         \"rank\";\nstatic const char percent_rankName[] = \"percent_rank\";\nstatic const char cume_distName[] =    \"cume_dist\";\nstatic const char ntileName[] =        \"ntile\";\nstatic const char last_valueName[] =   \"last_value\";\nstatic const char nth_valueName[] =    \"nth_value\";\nstatic const char first_valueName[] =  \"first_value\";\nstatic const char leadName[] =         \"lead\";\nstatic const char lagName[] =          \"lag\";\n\n/*\n** No-op implementations of xStep() and xFinalize().  Used as place-holders\n** for built-in window functions that never call those interfaces.\n**\n** The noopValueFunc() is called but is expected to do nothing.  The\n** noopStepFunc() is never called, and so it is marked with NO_TEST to\n** let the test coverage routine know not to expect this function to be\n** invoked.\n*/\nstatic void noopStepFunc(    /*NO_TEST*/\n  sqlite3_context *p,        /*NO_TEST*/\n  int n,                     /*NO_TEST*/\n  sqlite3_value **a          /*NO_TEST*/\n){                           /*NO_TEST*/\n  UNUSED_PARAMETER(p);       /*NO_TEST*/\n  UNUSED_PARAMETER(n);       /*NO_TEST*/\n  UNUSED_PARAMETER(a);       /*NO_TEST*/\n  assert(0);                 /*NO_TEST*/\n}                            /*NO_TEST*/\nstatic void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }\n\n/* Window functions that use all window interfaces: xStep, xFinal,\n** xValue, and xInverse */\n#define WINDOWFUNCALL(name,nArg,extra) {                                   \\\n  nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,                      \\\n  name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc,               \\\n  name ## InvFunc, name ## Name, {0}                                       \\\n}\n\n/* Window functions that are implemented using bytecode and thus have\n** no-op routines for their methods */\n#define WINDOWFUNCNOOP(name,nArg,extra) {                                  \\\n  nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,                      \\\n  noopStepFunc, noopValueFunc, noopValueFunc,                              \\\n  noopStepFunc, name ## Name, {0}                                          \\\n}\n\n/* Window functions that use all window interfaces: xStep, the\n** same routine for xFinalize and xValue and which never call\n** xInverse. */\n#define WINDOWFUNCX(name,nArg,extra) {                                     \\\n  nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,                      \\\n  name ## StepFunc, name ## ValueFunc, name ## ValueFunc,                  \\\n  noopStepFunc, name ## Name, {0}                                          \\\n}\n\n\n/*\n** Register those built-in window functions that are not also aggregates.\n*/\nSQLITE_PRIVATE void sqlite3WindowFunctions(void){\n  static FuncDef aWindowFuncs[] = {\n    WINDOWFUNCX(row_number, 0, 0),\n    WINDOWFUNCX(dense_rank, 0, 0),\n    WINDOWFUNCX(rank, 0, 0),\n    WINDOWFUNCALL(percent_rank, 0, 0),\n    WINDOWFUNCALL(cume_dist, 0, 0),\n    WINDOWFUNCALL(ntile, 1, 0),\n    WINDOWFUNCALL(last_value, 1, 0),\n    WINDOWFUNCALL(nth_value, 2, 0),\n    WINDOWFUNCALL(first_value, 1, 0),\n    WINDOWFUNCNOOP(lead, 1, 0),\n    WINDOWFUNCNOOP(lead, 2, 0),\n    WINDOWFUNCNOOP(lead, 3, 0),\n    WINDOWFUNCNOOP(lag, 1, 0),\n    WINDOWFUNCNOOP(lag, 2, 0),\n    WINDOWFUNCNOOP(lag, 3, 0),\n  };\n  sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));\n}\n\nstatic Window *windowFind(Parse *pParse, Window *pList, const char *zName){\n  Window *p;\n  for(p=pList; p; p=p->pNextWin){\n    if( sqlite3StrICmp(p->zName, zName)==0 ) break;\n  }\n  if( p==0 ){\n    sqlite3ErrorMsg(pParse, \"no such window: %s\", zName);\n  }\n  return p;\n}\n\n/*\n** This function is called immediately after resolving the function name\n** for a window function within a SELECT statement. Argument pList is a\n** linked list of WINDOW definitions for the current SELECT statement.\n** Argument pFunc is the function definition just resolved and pWin\n** is the Window object representing the associated OVER clause. This\n** function updates the contents of pWin as follows:\n**\n**   * If the OVER clause refered to a named window (as in \"max(x) OVER win\"),\n**     search list pList for a matching WINDOW definition, and update pWin\n**     accordingly. If no such WINDOW clause can be found, leave an error\n**     in pParse.\n**\n**   * If the function is a built-in window function that requires the\n**     window to be coerced (see \"BUILT-IN WINDOW FUNCTIONS\" at the top\n**     of this file), pWin is updated here.\n*/\nSQLITE_PRIVATE void sqlite3WindowUpdate(\n  Parse *pParse, \n  Window *pList,                  /* List of named windows for this SELECT */\n  Window *pWin,                   /* Window frame to update */\n  FuncDef *pFunc                  /* Window function definition */\n){\n  if( pWin->zName && pWin->eFrmType==0 ){\n    Window *p = windowFind(pParse, pList, pWin->zName);\n    if( p==0 ) return;\n    pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);\n    pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);\n    pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);\n    pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);\n    pWin->eStart = p->eStart;\n    pWin->eEnd = p->eEnd;\n    pWin->eFrmType = p->eFrmType;\n    pWin->eExclude = p->eExclude;\n  }else{\n    sqlite3WindowChain(pParse, pWin, pList);\n  }\n  if( (pWin->eFrmType==TK_RANGE)\n   && (pWin->pStart || pWin->pEnd) \n   && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)\n  ){\n    sqlite3ErrorMsg(pParse, \n      \"RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression\"\n    );\n  }else\n  if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){\n    sqlite3 *db = pParse->db;\n    if( pWin->pFilter ){\n      sqlite3ErrorMsg(pParse, \n          \"FILTER clause may only be used with aggregate window functions\"\n      );\n    }else{\n      struct WindowUpdate {\n        const char *zFunc;\n        int eFrmType;\n        int eStart;\n        int eEnd;\n      } aUp[] = {\n        { row_numberName,   TK_ROWS,   TK_UNBOUNDED, TK_CURRENT }, \n        { dense_rankName,   TK_RANGE,  TK_UNBOUNDED, TK_CURRENT }, \n        { rankName,         TK_RANGE,  TK_UNBOUNDED, TK_CURRENT }, \n        { percent_rankName, TK_GROUPS, TK_CURRENT,   TK_UNBOUNDED }, \n        { cume_distName,    TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED }, \n        { ntileName,        TK_ROWS,   TK_CURRENT,   TK_UNBOUNDED }, \n        { leadName,         TK_ROWS,   TK_UNBOUNDED, TK_UNBOUNDED }, \n        { lagName,          TK_ROWS,   TK_UNBOUNDED, TK_CURRENT }, \n      };\n      int i;\n      for(i=0; i<ArraySize(aUp); i++){\n        if( pFunc->zName==aUp[i].zFunc ){\n          sqlite3ExprDelete(db, pWin->pStart);\n          sqlite3ExprDelete(db, pWin->pEnd);\n          pWin->pEnd = pWin->pStart = 0;\n          pWin->eFrmType = aUp[i].eFrmType;\n          pWin->eStart = aUp[i].eStart;\n          pWin->eEnd = aUp[i].eEnd;\n          pWin->eExclude = 0;\n          if( pWin->eStart==TK_FOLLOWING ){\n            pWin->pStart = sqlite3Expr(db, TK_INTEGER, \"1\");\n          }\n          break;\n        }\n      }\n    }\n  }\n  pWin->pFunc = pFunc;\n}\n\n/*\n** Context object passed through sqlite3WalkExprList() to\n** selectWindowRewriteExprCb() by selectWindowRewriteEList().\n*/\ntypedef struct WindowRewrite WindowRewrite;\nstruct WindowRewrite {\n  Window *pWin;\n  SrcList *pSrc;\n  ExprList *pSub;\n  Table *pTab;\n  Select *pSubSelect;             /* Current sub-select, if any */\n};\n\n/*\n** Callback function used by selectWindowRewriteEList(). If necessary,\n** this function appends to the output expression-list and updates \n** expression (*ppExpr) in place.\n*/\nstatic int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){\n  struct WindowRewrite *p = pWalker->u.pRewrite;\n  Parse *pParse = pWalker->pParse;\n  assert( p!=0 );\n  assert( p->pWin!=0 );\n\n  /* If this function is being called from within a scalar sub-select\n  ** that used by the SELECT statement being processed, only process\n  ** TK_COLUMN expressions that refer to it (the outer SELECT). Do\n  ** not process aggregates or window functions at all, as they belong\n  ** to the scalar sub-select.  */\n  if( p->pSubSelect ){\n    if( pExpr->op!=TK_COLUMN ){\n      return WRC_Continue;\n    }else{\n      int nSrc = p->pSrc->nSrc;\n      int i;\n      for(i=0; i<nSrc; i++){\n        if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;\n      }\n      if( i==nSrc ) return WRC_Continue;\n    }\n  }\n\n  switch( pExpr->op ){\n\n    case TK_FUNCTION:\n      if( !ExprHasProperty(pExpr, EP_WinFunc) ){\n        break;\n      }else{\n        Window *pWin;\n        for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){\n          if( pExpr->y.pWin==pWin ){\n            assert( pWin->pOwner==pExpr );\n            return WRC_Prune;\n          }\n        }\n      }\n      /* Fall through.  */\n\n    case TK_AGG_FUNCTION:\n    case TK_COLUMN: {\n      int iCol = -1;\n      if( p->pSub ){\n        int i;\n        for(i=0; i<p->pSub->nExpr; i++){\n          if( 0==sqlite3ExprCompare(0, p->pSub->a[i].pExpr, pExpr, -1) ){\n            iCol = i;\n            break;\n          }\n        }\n      }\n      if( iCol<0 ){\n        Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);\n        if( pDup && pDup->op==TK_AGG_FUNCTION ) pDup->op = TK_FUNCTION;\n        p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);\n      }\n      if( p->pSub ){\n        assert( ExprHasProperty(pExpr, EP_Static)==0 );\n        ExprSetProperty(pExpr, EP_Static);\n        sqlite3ExprDelete(pParse->db, pExpr);\n        ExprClearProperty(pExpr, EP_Static);\n        memset(pExpr, 0, sizeof(Expr));\n\n        pExpr->op = TK_COLUMN;\n        pExpr->iColumn = (iCol<0 ? p->pSub->nExpr-1: iCol);\n        pExpr->iTable = p->pWin->iEphCsr;\n        pExpr->y.pTab = p->pTab;\n      }\n      if( pParse->db->mallocFailed ) return WRC_Abort;\n      break;\n    }\n\n    default: /* no-op */\n      break;\n  }\n\n  return WRC_Continue;\n}\nstatic int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){\n  struct WindowRewrite *p = pWalker->u.pRewrite;\n  Select *pSave = p->pSubSelect;\n  if( pSave==pSelect ){\n    return WRC_Continue;\n  }else{\n    p->pSubSelect = pSelect;\n    sqlite3WalkSelect(pWalker, pSelect);\n    p->pSubSelect = pSave;\n  }\n  return WRC_Prune;\n}\n\n\n/*\n** Iterate through each expression in expression-list pEList. For each:\n**\n**   * TK_COLUMN,\n**   * aggregate function, or\n**   * window function with a Window object that is not a member of the \n**     Window list passed as the second argument (pWin).\n**\n** Append the node to output expression-list (*ppSub). And replace it\n** with a TK_COLUMN that reads the (N-1)th element of table \n** pWin->iEphCsr, where N is the number of elements in (*ppSub) after\n** appending the new one.\n*/\nstatic void selectWindowRewriteEList(\n  Parse *pParse, \n  Window *pWin,\n  SrcList *pSrc,\n  ExprList *pEList,               /* Rewrite expressions in this list */\n  Table *pTab,\n  ExprList **ppSub                /* IN/OUT: Sub-select expression-list */\n){\n  Walker sWalker;\n  WindowRewrite sRewrite;\n\n  assert( pWin!=0 );\n  memset(&sWalker, 0, sizeof(Walker));\n  memset(&sRewrite, 0, sizeof(WindowRewrite));\n\n  sRewrite.pSub = *ppSub;\n  sRewrite.pWin = pWin;\n  sRewrite.pSrc = pSrc;\n  sRewrite.pTab = pTab;\n\n  sWalker.pParse = pParse;\n  sWalker.xExprCallback = selectWindowRewriteExprCb;\n  sWalker.xSelectCallback = selectWindowRewriteSelectCb;\n  sWalker.u.pRewrite = &sRewrite;\n\n  (void)sqlite3WalkExprList(&sWalker, pEList);\n\n  *ppSub = sRewrite.pSub;\n}\n\n/*\n** Append a copy of each expression in expression-list pAppend to\n** expression list pList. Return a pointer to the result list.\n*/\nstatic ExprList *exprListAppendList(\n  Parse *pParse,          /* Parsing context */\n  ExprList *pList,        /* List to which to append. Might be NULL */\n  ExprList *pAppend,      /* List of values to append. Might be NULL */\n  int bIntToNull\n){\n  if( pAppend ){\n    int i;\n    int nInit = pList ? pList->nExpr : 0;\n    for(i=0; i<pAppend->nExpr; i++){\n      Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);\n      assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );\n      if( bIntToNull && pDup ){\n        int iDummy;\n        Expr *pSub;\n        for(pSub=pDup; ExprHasProperty(pSub, EP_Skip); pSub=pSub->pLeft){\n          assert( pSub );\n        }\n        if( sqlite3ExprIsInteger(pSub, &iDummy) ){\n          pSub->op = TK_NULL;\n          pSub->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);\n          pSub->u.zToken = 0;\n        }\n      }\n      pList = sqlite3ExprListAppend(pParse, pList, pDup);\n      if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;\n    }\n  }\n  return pList;\n}\n\n/*\n** When rewriting a query, if the new subquery in the FROM clause\n** contains TK_AGG_FUNCTION nodes that refer to an outer query,\n** then we have to increase the Expr->op2 values of those nodes\n** due to the extra subquery layer that was added.\n**\n** See also the incrAggDepth() routine in resolve.c\n*/\nstatic int sqlite3WindowExtraAggFuncDepth(Walker *pWalker, Expr *pExpr){\n  if( pExpr->op==TK_AGG_FUNCTION\n   && pExpr->op2>=pWalker->walkerDepth\n  ){\n    pExpr->op2++;\n  }\n  return WRC_Continue;\n}\n\n/*\n** If the SELECT statement passed as the second argument does not invoke\n** any SQL window functions, this function is a no-op. Otherwise, it \n** rewrites the SELECT statement so that window function xStep functions\n** are invoked in the correct order as described under \"SELECT REWRITING\"\n** at the top of this file.\n*/\nSQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){\n  int rc = SQLITE_OK;\n  if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){\n    Vdbe *v = sqlite3GetVdbe(pParse);\n    sqlite3 *db = pParse->db;\n    Select *pSub = 0;             /* The subquery */\n    SrcList *pSrc = p->pSrc;\n    Expr *pWhere = p->pWhere;\n    ExprList *pGroupBy = p->pGroupBy;\n    Expr *pHaving = p->pHaving;\n    ExprList *pSort = 0;\n\n    ExprList *pSublist = 0;       /* Expression list for sub-query */\n    Window *pMWin = p->pWin;      /* Master window object */\n    Window *pWin;                 /* Window object iterator */\n    Table *pTab;\n    Walker w;\n\n    u32 selFlags = p->selFlags;\n\n    pTab = sqlite3DbMallocZero(db, sizeof(Table));\n    if( pTab==0 ){\n      return sqlite3ErrorToParser(db, SQLITE_NOMEM);\n    }\n    sqlite3AggInfoPersistWalkerInit(&w, pParse);\n    sqlite3WalkSelect(&w, p);\n\n    p->pSrc = 0;\n    p->pWhere = 0;\n    p->pGroupBy = 0;\n    p->pHaving = 0;\n    p->selFlags &= ~SF_Aggregate;\n    p->selFlags |= SF_WinRewrite;\n\n    /* Create the ORDER BY clause for the sub-select. This is the concatenation\n    ** of the window PARTITION and ORDER BY clauses. Then, if this makes it\n    ** redundant, remove the ORDER BY from the parent SELECT.  */\n    pSort = exprListAppendList(pParse, 0, pMWin->pPartition, 1);\n    pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);\n    if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){\n      int nSave = pSort->nExpr;\n      pSort->nExpr = p->pOrderBy->nExpr;\n      if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){\n        sqlite3ExprListDelete(db, p->pOrderBy);\n        p->pOrderBy = 0;\n      }\n      pSort->nExpr = nSave;\n    }\n\n    /* Assign a cursor number for the ephemeral table used to buffer rows.\n    ** The OpenEphemeral instruction is coded later, after it is known how\n    ** many columns the table will have.  */\n    pMWin->iEphCsr = pParse->nTab++;\n    pParse->nTab += 3;\n\n    selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);\n    selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);\n    pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);\n\n    /* Append the PARTITION BY and ORDER BY expressions to the to the \n    ** sub-select expression list. They are required to figure out where \n    ** boundaries for partitions and sets of peer rows lie.  */\n    pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);\n    pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);\n\n    /* Append the arguments passed to each window function to the\n    ** sub-select expression list. Also allocate two registers for each\n    ** window function - one for the accumulator, another for interim\n    ** results.  */\n    for(pWin=pMWin; pWin; pWin=pWin->pNextWin){\n      ExprList *pArgs = pWin->pOwner->x.pList;\n      if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){\n        selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);\n        pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);\n        pWin->bExprArgs = 1;\n      }else{\n        pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);\n        pSublist = exprListAppendList(pParse, pSublist, pArgs, 0);\n      }\n      if( pWin->pFilter ){\n        Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);\n        pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);\n      }\n      pWin->regAccum = ++pParse->nMem;\n      pWin->regResult = ++pParse->nMem;\n      sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);\n    }\n\n    /* If there is no ORDER BY or PARTITION BY clause, and the window\n    ** function accepts zero arguments, and there are no other columns\n    ** selected (e.g. \"SELECT row_number() OVER () FROM t1\"), it is possible\n    ** that pSublist is still NULL here. Add a constant expression here to \n    ** keep everything legal in this case. \n    */\n    if( pSublist==0 ){\n      pSublist = sqlite3ExprListAppend(pParse, 0, \n        sqlite3Expr(db, TK_INTEGER, \"0\")\n      );\n    }\n\n    pSub = sqlite3SelectNew(\n        pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0\n    );\n    p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);\n    if( p->pSrc ){\n      Table *pTab2;\n      p->pSrc->a[0].pSelect = pSub;\n      sqlite3SrcListAssignCursors(pParse, p->pSrc);\n      pSub->selFlags |= SF_Expanded;\n      pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);\n      pSub->selFlags |= (selFlags & SF_Aggregate);\n      if( pTab2==0 ){\n        /* Might actually be some other kind of error, but in that case\n        ** pParse->nErr will be set, so if SQLITE_NOMEM is set, we will get\n        ** the correct error message regardless. */\n        rc = SQLITE_NOMEM;\n      }else{\n        memcpy(pTab, pTab2, sizeof(Table));\n        pTab->tabFlags |= TF_Ephemeral;\n        p->pSrc->a[0].pTab = pTab;\n        pTab = pTab2;\n        memset(&w, 0, sizeof(w));\n        w.xExprCallback = sqlite3WindowExtraAggFuncDepth;\n        w.xSelectCallback = sqlite3WalkerDepthIncrease;\n        w.xSelectCallback2 = sqlite3WalkerDepthDecrease;\n        sqlite3WalkSelect(&w, pSub);\n      }\n    }else{\n      sqlite3SelectDelete(db, pSub);\n    }\n    if( db->mallocFailed ) rc = SQLITE_NOMEM;\n    sqlite3DbFree(db, pTab);\n  }\n\n  if( rc ){\n    if( pParse->nErr==0 ){\n      assert( pParse->db->mallocFailed );\n      sqlite3ErrorToParser(pParse->db, SQLITE_NOMEM);\n    }\n    sqlite3SelectReset(pParse, p);\n  }\n  return rc;\n}\n\n/*\n** Unlink the Window object from the Select to which it is attached,\n** if it is attached.\n*/\nSQLITE_PRIVATE void sqlite3WindowUnlinkFromSelect(Window *p){\n  if( p->ppThis ){\n    *p->ppThis = p->pNextWin;\n    if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis;\n    p->ppThis = 0;\n  }\n}\n\n/*\n** Free the Window object passed as the second argument.\n*/\nSQLITE_PRIVATE void sqlite3WindowDelete(sqlite3 *db, Window *p){\n  if( p ){\n    sqlite3WindowUnlinkFromSelect(p);\n    sqlite3ExprDelete(db, p->pFilter);\n    sqlite3ExprListDelete(db, p->pPartition);\n    sqlite3ExprListDelete(db, p->pOrderBy);\n    sqlite3ExprDelete(db, p->pEnd);\n    sqlite3ExprDelete(db, p->pStart);\n    sqlite3DbFree(db, p->zName);\n    sqlite3DbFree(db, p->zBase);\n    sqlite3DbFree(db, p);\n  }\n}\n\n/*\n** Free the linked list of Window objects starting at the second argument.\n*/\nSQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p){\n  while( p ){\n    Window *pNext = p->pNextWin;\n    sqlite3WindowDelete(db, p);\n    p = pNext;\n  }\n}\n\n/*\n** The argument expression is an PRECEDING or FOLLOWING offset.  The\n** value should be a non-negative integer.  If the value is not a\n** constant, change it to NULL.  The fact that it is then a non-negative\n** integer will be caught later.  But it is important not to leave\n** variable values in the expression tree.\n*/\nstatic Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){\n  if( 0==sqlite3ExprIsConstant(pExpr) ){\n    if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);\n    sqlite3ExprDelete(pParse->db, pExpr);\n    pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);\n  }\n  return pExpr;\n}\n\n/*\n** Allocate and return a new Window object describing a Window Definition.\n*/\nSQLITE_PRIVATE Window *sqlite3WindowAlloc(\n  Parse *pParse,    /* Parsing context */\n  int eType,        /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */\n  int eStart,       /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */\n  Expr *pStart,     /* Start window size if TK_PRECEDING or FOLLOWING */\n  int eEnd,         /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */\n  Expr *pEnd,       /* End window size if TK_FOLLOWING or PRECEDING */\n  u8 eExclude       /* EXCLUDE clause */\n){\n  Window *pWin = 0;\n  int bImplicitFrame = 0;\n\n  /* Parser assures the following: */\n  assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );\n  assert( eStart==TK_CURRENT || eStart==TK_PRECEDING\n           || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );\n  assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING\n           || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );\n  assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );\n  assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );\n\n  if( eType==0 ){\n    bImplicitFrame = 1;\n    eType = TK_RANGE;\n  }\n\n  /* Additionally, the\n  ** starting boundary type may not occur earlier in the following list than\n  ** the ending boundary type:\n  **\n  **   UNBOUNDED PRECEDING\n  **   <expr> PRECEDING\n  **   CURRENT ROW\n  **   <expr> FOLLOWING\n  **   UNBOUNDED FOLLOWING\n  **\n  ** The parser ensures that \"UNBOUNDED PRECEDING\" cannot be used as an ending\n  ** boundary, and than \"UNBOUNDED FOLLOWING\" cannot be used as a starting\n  ** frame boundary.\n  */\n  if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)\n   || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))\n  ){\n    sqlite3ErrorMsg(pParse, \"unsupported frame specification\");\n    goto windowAllocErr;\n  }\n\n  pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));\n  if( pWin==0 ) goto windowAllocErr;\n  pWin->eFrmType = eType;\n  pWin->eStart = eStart;\n  pWin->eEnd = eEnd;\n  if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){\n    eExclude = TK_NO;\n  }\n  pWin->eExclude = eExclude;\n  pWin->bImplicitFrame = bImplicitFrame;\n  pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);\n  pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);\n  return pWin;\n\nwindowAllocErr:\n  sqlite3ExprDelete(pParse->db, pEnd);\n  sqlite3ExprDelete(pParse->db, pStart);\n  return 0;\n}\n\n/*\n** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window\n** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the\n** equivalent nul-terminated string.\n*/\nSQLITE_PRIVATE Window *sqlite3WindowAssemble(\n  Parse *pParse, \n  Window *pWin, \n  ExprList *pPartition, \n  ExprList *pOrderBy, \n  Token *pBase\n){\n  if( pWin ){\n    pWin->pPartition = pPartition;\n    pWin->pOrderBy = pOrderBy;\n    if( pBase ){\n      pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);\n    }\n  }else{\n    sqlite3ExprListDelete(pParse->db, pPartition);\n    sqlite3ExprListDelete(pParse->db, pOrderBy);\n  }\n  return pWin;\n}\n\n/*\n** Window *pWin has just been created from a WINDOW clause. Tokne pBase\n** is the base window. Earlier windows from the same WINDOW clause are\n** stored in the linked list starting at pWin->pNextWin. This function\n** either updates *pWin according to the base specification, or else\n** leaves an error in pParse.\n*/\nSQLITE_PRIVATE void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){\n  if( pWin->zBase ){\n    sqlite3 *db = pParse->db;\n    Window *pExist = windowFind(pParse, pList, pWin->zBase);\n    if( pExist ){\n      const char *zErr = 0;\n      /* Check for errors */\n      if( pWin->pPartition ){\n        zErr = \"PARTITION clause\";\n      }else if( pExist->pOrderBy && pWin->pOrderBy ){\n        zErr = \"ORDER BY clause\";\n      }else if( pExist->bImplicitFrame==0 ){\n        zErr = \"frame specification\";\n      }\n      if( zErr ){\n        sqlite3ErrorMsg(pParse, \n            \"cannot override %s of window: %s\", zErr, pWin->zBase\n        );\n      }else{\n        pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);\n        if( pExist->pOrderBy ){\n          assert( pWin->pOrderBy==0 );\n          pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);\n        }\n        sqlite3DbFree(db, pWin->zBase);\n        pWin->zBase = 0;\n      }\n    }\n  }\n}\n\n/*\n** Attach window object pWin to expression p.\n*/\nSQLITE_PRIVATE void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){\n  if( p ){\n    assert( p->op==TK_FUNCTION );\n    assert( pWin );\n    p->y.pWin = pWin;\n    ExprSetProperty(p, EP_WinFunc);\n    pWin->pOwner = p;\n    if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){\n      sqlite3ErrorMsg(pParse,\n          \"DISTINCT is not supported for window functions\"\n      );\n    }\n  }else{\n    sqlite3WindowDelete(pParse->db, pWin);\n  }\n}\n\n/*\n** Possibly link window pWin into the list at pSel->pWin (window functions\n** to be processed as part of SELECT statement pSel). The window is linked\n** in if either (a) there are no other windows already linked to this\n** SELECT, or (b) the windows already linked use a compatible window frame.\n*/\nSQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin){\n  if( pSel!=0\n   && (0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0))\n  ){\n    pWin->pNextWin = pSel->pWin;\n    if( pSel->pWin ){\n      pSel->pWin->ppThis = &pWin->pNextWin;\n    }\n    pSel->pWin = pWin;\n    pWin->ppThis = &pSel->pWin;\n  }\n}\n\n/*\n** Return 0 if the two window objects are identical, 1 if they are\n** different, or 2 if it cannot be determined if the objects are identical\n** or not. Identical window objects can be processed in a single scan.\n*/\nSQLITE_PRIVATE int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2, int bFilter){\n  int res;\n  if( NEVER(p1==0) || NEVER(p2==0) ) return 1;\n  if( p1->eFrmType!=p2->eFrmType ) return 1;\n  if( p1->eStart!=p2->eStart ) return 1;\n  if( p1->eEnd!=p2->eEnd ) return 1;\n  if( p1->eExclude!=p2->eExclude ) return 1;\n  if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;\n  if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;\n  if( (res = sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1)) ){\n    return res;\n  }\n  if( (res = sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1)) ){\n    return res;\n  }\n  if( bFilter ){\n    if( (res = sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1)) ){\n      return res;\n    }\n  }\n  return 0;\n}\n\n\n/*\n** This is called by code in select.c before it calls sqlite3WhereBegin()\n** to begin iterating through the sub-query results. It is used to allocate\n** and initialize registers and cursors used by sqlite3WindowCodeStep().\n*/\nSQLITE_PRIVATE void sqlite3WindowCodeInit(Parse *pParse, Select *pSelect){\n  int nEphExpr = pSelect->pSrc->a[0].pSelect->pEList->nExpr;\n  Window *pMWin = pSelect->pWin;\n  Window *pWin;\n  Vdbe *v = sqlite3GetVdbe(pParse);\n\n  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr);\n  sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);\n  sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);\n  sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);\n\n  /* Allocate registers to use for PARTITION BY values, if any. Initialize\n  ** said registers to NULL.  */\n  if( pMWin->pPartition ){\n    int nExpr = pMWin->pPartition->nExpr;\n    pMWin->regPart = pParse->nMem+1;\n    pParse->nMem += nExpr;\n    sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);\n  }\n\n  pMWin->regOne = ++pParse->nMem;\n  sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);\n\n  if( pMWin->eExclude ){\n    pMWin->regStartRowid = ++pParse->nMem;\n    pMWin->regEndRowid = ++pParse->nMem;\n    pMWin->csrApp = pParse->nTab++;\n    sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);\n    sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);\n    return;\n  }\n\n  for(pWin=pMWin; pWin; pWin=pWin->pNextWin){\n    FuncDef *p = pWin->pFunc;\n    if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){\n      /* The inline versions of min() and max() require a single ephemeral\n      ** table and 3 registers. The registers are used as follows:\n      **\n      **   regApp+0: slot to copy min()/max() argument to for MakeRecord\n      **   regApp+1: integer value used to ensure keys are unique\n      **   regApp+2: output of MakeRecord\n      */\n      ExprList *pList = pWin->pOwner->x.pList;\n      KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);\n      pWin->csrApp = pParse->nTab++;\n      pWin->regApp = pParse->nMem+1;\n      pParse->nMem += 3;\n      if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){\n        assert( pKeyInfo->aSortFlags[0]==0 );\n        pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC;\n      }\n      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);\n      sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);\n      sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);\n    }\n    else if( p->zName==nth_valueName || p->zName==first_valueName ){\n      /* Allocate two registers at pWin->regApp. These will be used to\n      ** store the start and end index of the current frame.  */\n      pWin->regApp = pParse->nMem+1;\n      pWin->csrApp = pParse->nTab++;\n      pParse->nMem += 2;\n      sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);\n    }\n    else if( p->zName==leadName || p->zName==lagName ){\n      pWin->csrApp = pParse->nTab++;\n      sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);\n    }\n  }\n}\n\n#define WINDOW_STARTING_INT  0\n#define WINDOW_ENDING_INT    1\n#define WINDOW_NTH_VALUE_INT 2\n#define WINDOW_STARTING_NUM  3\n#define WINDOW_ENDING_NUM    4\n\n/*\n** A \"PRECEDING <expr>\" (eCond==0) or \"FOLLOWING <expr>\" (eCond==1) or the\n** value of the second argument to nth_value() (eCond==2) has just been\n** evaluated and the result left in register reg. This function generates VM\n** code to check that the value is a non-negative integer and throws an\n** exception if it is not.\n*/\nstatic void windowCheckValue(Parse *pParse, int reg, int eCond){\n  static const char *azErr[] = {\n    \"frame starting offset must be a non-negative integer\",\n    \"frame ending offset must be a non-negative integer\",\n    \"second argument to nth_value must be a positive integer\",\n    \"frame starting offset must be a non-negative number\",\n    \"frame ending offset must be a non-negative number\",\n  };\n  static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  int regZero = sqlite3GetTempReg(pParse);\n  assert( eCond>=0 && eCond<ArraySize(azErr) );\n  sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);\n  if( eCond>=WINDOW_STARTING_NUM ){\n    int regString = sqlite3GetTempReg(pParse);\n    sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, \"\", P4_STATIC);\n    sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);\n    sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL);\n    VdbeCoverage(v);\n    assert( eCond==3 || eCond==4 );\n    VdbeCoverageIf(v, eCond==3);\n    VdbeCoverageIf(v, eCond==4);\n  }else{\n    sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);\n    VdbeCoverage(v);\n    assert( eCond==0 || eCond==1 || eCond==2 );\n    VdbeCoverageIf(v, eCond==0);\n    VdbeCoverageIf(v, eCond==1);\n    VdbeCoverageIf(v, eCond==2);\n  }\n  sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);\n  VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */\n  VdbeCoverageNeverNullIf(v, eCond==1); /*   the OP_MustBeInt */\n  VdbeCoverageNeverNullIf(v, eCond==2);\n  VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */\n  VdbeCoverageNeverNullIf(v, eCond==4); /*   the OP_Ge */\n  sqlite3MayAbort(pParse);\n  sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);\n  sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);\n  sqlite3ReleaseTempReg(pParse, regZero);\n}\n\n/*\n** Return the number of arguments passed to the window-function associated\n** with the object passed as the only argument to this function.\n*/\nstatic int windowArgCount(Window *pWin){\n  ExprList *pList = pWin->pOwner->x.pList;\n  return (pList ? pList->nExpr : 0);\n}\n\ntypedef struct WindowCodeArg WindowCodeArg;\ntypedef struct WindowCsrAndReg WindowCsrAndReg;\n\n/*\n** See comments above struct WindowCodeArg.\n*/\nstruct WindowCsrAndReg {\n  int csr;                        /* Cursor number */\n  int reg;                        /* First in array of peer values */\n};\n\n/*\n** A single instance of this structure is allocated on the stack by \n** sqlite3WindowCodeStep() and a pointer to it passed to the various helper\n** routines. This is to reduce the number of arguments required by each\n** helper function.\n**\n** regArg:\n**   Each window function requires an accumulator register (just as an\n**   ordinary aggregate function does). This variable is set to the first\n**   in an array of accumulator registers - one for each window function\n**   in the WindowCodeArg.pMWin list.\n**\n** eDelete:\n**   The window functions implementation sometimes caches the input rows\n**   that it processes in a temporary table. If it is not zero, this\n**   variable indicates when rows may be removed from the temp table (in\n**   order to reduce memory requirements - it would always be safe just\n**   to leave them there). Possible values for eDelete are:\n**\n**      WINDOW_RETURN_ROW:\n**        An input row can be discarded after it is returned to the caller.\n**\n**      WINDOW_AGGINVERSE:\n**        An input row can be discarded after the window functions xInverse()\n**        callbacks have been invoked in it.\n**\n**      WINDOW_AGGSTEP:\n**        An input row can be discarded after the window functions xStep()\n**        callbacks have been invoked in it.\n**\n** start,current,end\n**   Consider a window-frame similar to the following:\n**\n**     (ORDER BY a, b GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING)\n**\n**   The windows functions implmentation caches the input rows in a temp\n**   table, sorted by \"a, b\" (it actually populates the cache lazily, and\n**   aggressively removes rows once they are no longer required, but that's\n**   a mere detail). It keeps three cursors open on the temp table. One\n**   (current) that points to the next row to return to the query engine\n**   once its window function values have been calculated. Another (end)\n**   points to the next row to call the xStep() method of each window function\n**   on (so that it is 2 groups ahead of current). And a third (start) that\n**   points to the next row to call the xInverse() method of each window\n**   function on.\n**\n**   Each cursor (start, current and end) consists of a VDBE cursor\n**   (WindowCsrAndReg.csr) and an array of registers (starting at\n**   WindowCodeArg.reg) that always contains a copy of the peer values \n**   read from the corresponding cursor.\n**\n**   Depending on the window-frame in question, all three cursors may not\n**   be required. In this case both WindowCodeArg.csr and reg are set to\n**   0.\n*/\nstruct WindowCodeArg {\n  Parse *pParse;             /* Parse context */\n  Window *pMWin;             /* First in list of functions being processed */\n  Vdbe *pVdbe;               /* VDBE object */\n  int addrGosub;             /* OP_Gosub to this address to return one row */\n  int regGosub;              /* Register used with OP_Gosub(addrGosub) */\n  int regArg;                /* First in array of accumulator registers */\n  int eDelete;               /* See above */\n\n  WindowCsrAndReg start;\n  WindowCsrAndReg current;\n  WindowCsrAndReg end;\n};\n\n/*\n** Generate VM code to read the window frames peer values from cursor csr into\n** an array of registers starting at reg.\n*/\nstatic void windowReadPeerValues(\n  WindowCodeArg *p,\n  int csr,\n  int reg\n){\n  Window *pMWin = p->pMWin;\n  ExprList *pOrderBy = pMWin->pOrderBy;\n  if( pOrderBy ){\n    Vdbe *v = sqlite3GetVdbe(p->pParse);\n    ExprList *pPart = pMWin->pPartition;\n    int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);\n    int i;\n    for(i=0; i<pOrderBy->nExpr; i++){\n      sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);\n    }\n  }\n}\n\n/*\n** Generate VM code to invoke either xStep() (if bInverse is 0) or \n** xInverse (if bInverse is non-zero) for each window function in the \n** linked list starting at pMWin. Or, for built-in window functions\n** that do not use the standard function API, generate the required\n** inline VM code.\n**\n** If argument csr is greater than or equal to 0, then argument reg is\n** the first register in an array of registers guaranteed to be large\n** enough to hold the array of arguments for each function. In this case\n** the arguments are extracted from the current row of csr into the\n** array of registers before invoking OP_AggStep or OP_AggInverse\n**\n** Or, if csr is less than zero, then the array of registers at reg is\n** already populated with all columns from the current row of the sub-query.\n**\n** If argument regPartSize is non-zero, then it is a register containing the\n** number of rows in the current partition.\n*/\nstatic void windowAggStep(\n  WindowCodeArg *p,\n  Window *pMWin,                  /* Linked list of window functions */\n  int csr,                        /* Read arguments from this cursor */\n  int bInverse,                   /* True to invoke xInverse instead of xStep */\n  int reg                         /* Array of registers */\n){\n  Parse *pParse = p->pParse;\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  Window *pWin;\n  for(pWin=pMWin; pWin; pWin=pWin->pNextWin){\n    FuncDef *pFunc = pWin->pFunc;\n    int regArg;\n    int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin);\n    int i;\n\n    assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED );\n\n    /* All OVER clauses in the same window function aggregate step must\n    ** be the same. */\n    assert( pWin==pMWin || sqlite3WindowCompare(pParse,pWin,pMWin,0)!=1 );\n\n    for(i=0; i<nArg; i++){\n      if( i!=1 || pFunc->zName!=nth_valueName ){\n        sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);\n      }else{\n        sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);\n      }\n    }\n    regArg = reg;\n\n    if( pMWin->regStartRowid==0\n     && (pFunc->funcFlags & SQLITE_FUNC_MINMAX) \n     && (pWin->eStart!=TK_UNBOUNDED)\n    ){\n      int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);\n      VdbeCoverage(v);\n      if( bInverse==0 ){\n        sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);\n        sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);\n        sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);\n        sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);\n      }else{\n        sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);\n        VdbeCoverageNeverTaken(v);\n        sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);\n        sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);\n      }\n      sqlite3VdbeJumpHere(v, addrIsNull);\n    }else if( pWin->regApp ){\n      assert( pFunc->zName==nth_valueName\n           || pFunc->zName==first_valueName\n      );\n      assert( bInverse==0 || bInverse==1 );\n      sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);\n    }else if( pFunc->xSFunc!=noopStepFunc ){\n      int addrIf = 0;\n      if( pWin->pFilter ){\n        int regTmp;\n        assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr );\n        assert( pWin->bExprArgs || nArg  ||pWin->pOwner->x.pList==0 );\n        regTmp = sqlite3GetTempReg(pParse);\n        sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);\n        addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);\n        VdbeCoverage(v);\n        sqlite3ReleaseTempReg(pParse, regTmp);\n      }\n      \n      if( pWin->bExprArgs ){\n        int iStart = sqlite3VdbeCurrentAddr(v);\n        VdbeOp *pOp, *pEnd;\n\n        nArg = pWin->pOwner->x.pList->nExpr;\n        regArg = sqlite3GetTempRange(pParse, nArg);\n        sqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0);\n\n        pEnd = sqlite3VdbeGetOp(v, -1);\n        for(pOp=sqlite3VdbeGetOp(v, iStart); pOp<=pEnd; pOp++){\n          if( pOp->opcode==OP_Column && pOp->p1==pWin->iEphCsr ){\n            pOp->p1 = csr;\n          }\n        }\n      }\n      if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){\n        CollSeq *pColl;\n        assert( nArg>0 );\n        pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);\n        sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);\n      }\n      sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep, \n                        bInverse, regArg, pWin->regAccum);\n      sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);\n      sqlite3VdbeChangeP5(v, (u8)nArg);\n      if( pWin->bExprArgs ){\n        sqlite3ReleaseTempRange(pParse, regArg, nArg);\n      }\n      if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);\n    }\n  }\n}\n\n/*\n** Values that may be passed as the second argument to windowCodeOp().\n*/\n#define WINDOW_RETURN_ROW 1\n#define WINDOW_AGGINVERSE 2\n#define WINDOW_AGGSTEP    3\n\n/*\n** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()\n** (bFin==1) for each window function in the linked list starting at\n** pMWin. Or, for built-in window-functions that do not use the standard\n** API, generate the equivalent VM code.\n*/\nstatic void windowAggFinal(WindowCodeArg *p, int bFin){\n  Parse *pParse = p->pParse;\n  Window *pMWin = p->pMWin;\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  Window *pWin;\n\n  for(pWin=pMWin; pWin; pWin=pWin->pNextWin){\n    if( pMWin->regStartRowid==0\n     && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX) \n     && (pWin->eStart!=TK_UNBOUNDED)\n    ){\n      sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);\n      sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);\n      VdbeCoverage(v);\n      sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);\n      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);\n    }else if( pWin->regApp ){\n      assert( pMWin->regStartRowid==0 );\n    }else{\n      int nArg = windowArgCount(pWin);\n      if( bFin ){\n        sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);\n        sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);\n        sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);\n        sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);\n      }else{\n        sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);\n        sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);\n      }\n    }\n  }\n}\n\n/*\n** Generate code to calculate the current values of all window functions in the\n** p->pMWin list by doing a full scan of the current window frame. Store the\n** results in the Window.regResult registers, ready to return the upper\n** layer.\n*/\nstatic void windowFullScan(WindowCodeArg *p){\n  Window *pWin;\n  Parse *pParse = p->pParse;\n  Window *pMWin = p->pMWin;\n  Vdbe *v = p->pVdbe;\n\n  int regCRowid = 0;              /* Current rowid value */\n  int regCPeer = 0;               /* Current peer values */\n  int regRowid = 0;               /* AggStep rowid value */\n  int regPeer = 0;                /* AggStep peer values */\n\n  int nPeer;\n  int lblNext;\n  int lblBrk;\n  int addrNext;\n  int csr;\n\n  VdbeModuleComment((v, \"windowFullScan begin\"));\n\n  assert( pMWin!=0 );\n  csr = pMWin->csrApp;\n  nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);\n\n  lblNext = sqlite3VdbeMakeLabel(pParse);\n  lblBrk = sqlite3VdbeMakeLabel(pParse);\n\n  regCRowid = sqlite3GetTempReg(pParse);\n  regRowid = sqlite3GetTempReg(pParse);\n  if( nPeer ){\n    regCPeer = sqlite3GetTempRange(pParse, nPeer);\n    regPeer = sqlite3GetTempRange(pParse, nPeer);\n  }\n\n  sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);\n  windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);\n\n  for(pWin=pMWin; pWin; pWin=pWin->pNextWin){\n    sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);\n  }\n\n  sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);\n  VdbeCoverage(v);\n  addrNext = sqlite3VdbeCurrentAddr(v);\n  sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);\n  sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);\n  VdbeCoverageNeverNull(v);\n\n  if( pMWin->eExclude==TK_CURRENT ){\n    sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);\n    VdbeCoverageNeverNull(v);\n  }else if( pMWin->eExclude!=TK_NO ){\n    int addr;\n    int addrEq = 0;\n    KeyInfo *pKeyInfo = 0;\n\n    if( pMWin->pOrderBy ){\n      pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);\n    }\n    if( pMWin->eExclude==TK_TIES ){\n      addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);\n      VdbeCoverageNeverNull(v);\n    }\n    if( pKeyInfo ){\n      windowReadPeerValues(p, csr, regPeer);\n      sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);\n      sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);\n      addr = sqlite3VdbeCurrentAddr(v)+1;\n      sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);\n      VdbeCoverageEqNe(v);\n    }else{\n      sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);\n    }\n    if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);\n  }\n\n  windowAggStep(p, pMWin, csr, 0, p->regArg);\n\n  sqlite3VdbeResolveLabel(v, lblNext);\n  sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);\n  VdbeCoverage(v);\n  sqlite3VdbeJumpHere(v, addrNext-1);\n  sqlite3VdbeJumpHere(v, addrNext+1);\n  sqlite3ReleaseTempReg(pParse, regRowid);\n  sqlite3ReleaseTempReg(pParse, regCRowid);\n  if( nPeer ){\n    sqlite3ReleaseTempRange(pParse, regPeer, nPeer);\n    sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);\n  }\n\n  windowAggFinal(p, 1);\n  VdbeModuleComment((v, \"windowFullScan end\"));\n}\n\n/*\n** Invoke the sub-routine at regGosub (generated by code in select.c) to\n** return the current row of Window.iEphCsr. If all window functions are\n** aggregate window functions that use the standard API, a single\n** OP_Gosub instruction is all that this routine generates. Extra VM code\n** for per-row processing is only generated for the following built-in window\n** functions:\n**\n**   nth_value()\n**   first_value()\n**   lag()\n**   lead()\n*/\nstatic void windowReturnOneRow(WindowCodeArg *p){\n  Window *pMWin = p->pMWin;\n  Vdbe *v = p->pVdbe;\n\n  if( pMWin->regStartRowid ){\n    windowFullScan(p);\n  }else{\n    Parse *pParse = p->pParse;\n    Window *pWin;\n\n    for(pWin=pMWin; pWin; pWin=pWin->pNextWin){\n      FuncDef *pFunc = pWin->pFunc;\n      if( pFunc->zName==nth_valueName\n       || pFunc->zName==first_valueName\n      ){\n        int csr = pWin->csrApp;\n        int lbl = sqlite3VdbeMakeLabel(pParse);\n        int tmpReg = sqlite3GetTempReg(pParse);\n        sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);\n  \n        if( pFunc->zName==nth_valueName ){\n          sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);\n          windowCheckValue(pParse, tmpReg, 2);\n        }else{\n          sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);\n        }\n        sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);\n        sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);\n        VdbeCoverageNeverNull(v);\n        sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);\n        VdbeCoverageNeverTaken(v);\n        sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);\n        sqlite3VdbeResolveLabel(v, lbl);\n        sqlite3ReleaseTempReg(pParse, tmpReg);\n      }\n      else if( pFunc->zName==leadName || pFunc->zName==lagName ){\n        int nArg = pWin->pOwner->x.pList->nExpr;\n        int csr = pWin->csrApp;\n        int lbl = sqlite3VdbeMakeLabel(pParse);\n        int tmpReg = sqlite3GetTempReg(pParse);\n        int iEph = pMWin->iEphCsr;\n  \n        if( nArg<3 ){\n          sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);\n        }else{\n          sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);\n        }\n        sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);\n        if( nArg<2 ){\n          int val = (pFunc->zName==leadName ? 1 : -1);\n          sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);\n        }else{\n          int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);\n          int tmpReg2 = sqlite3GetTempReg(pParse);\n          sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);\n          sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);\n          sqlite3ReleaseTempReg(pParse, tmpReg2);\n        }\n  \n        sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);\n        VdbeCoverage(v);\n        sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);\n        sqlite3VdbeResolveLabel(v, lbl);\n        sqlite3ReleaseTempReg(pParse, tmpReg);\n      }\n    }\n  }\n  sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);\n}\n\n/*\n** Generate code to set the accumulator register for each window function\n** in the linked list passed as the second argument to NULL. And perform\n** any equivalent initialization required by any built-in window functions\n** in the list.\n*/\nstatic int windowInitAccum(Parse *pParse, Window *pMWin){\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  int regArg;\n  int nArg = 0;\n  Window *pWin;\n  for(pWin=pMWin; pWin; pWin=pWin->pNextWin){\n    FuncDef *pFunc = pWin->pFunc;\n    assert( pWin->regAccum );\n    sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);\n    nArg = MAX(nArg, windowArgCount(pWin));\n    if( pMWin->regStartRowid==0 ){\n      if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){\n        sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);\n        sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);\n      }\n\n      if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){\n        assert( pWin->eStart!=TK_UNBOUNDED );\n        sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);\n        sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);\n      }\n    }\n  }\n  regArg = pParse->nMem+1;\n  pParse->nMem += nArg;\n  return regArg;\n}\n\n/* \n** Return true if the current frame should be cached in the ephemeral table,\n** even if there are no xInverse() calls required.\n*/\nstatic int windowCacheFrame(Window *pMWin){\n  Window *pWin;\n  if( pMWin->regStartRowid ) return 1;\n  for(pWin=pMWin; pWin; pWin=pWin->pNextWin){\n    FuncDef *pFunc = pWin->pFunc;\n    if( (pFunc->zName==nth_valueName)\n     || (pFunc->zName==first_valueName)\n     || (pFunc->zName==leadName)\n     || (pFunc->zName==lagName)\n    ){\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/*\n** regOld and regNew are each the first register in an array of size\n** pOrderBy->nExpr. This function generates code to compare the two\n** arrays of registers using the collation sequences and other comparison\n** parameters specified by pOrderBy. \n**\n** If the two arrays are not equal, the contents of regNew is copied to \n** regOld and control falls through. Otherwise, if the contents of the arrays\n** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.\n*/\nstatic void windowIfNewPeer(\n  Parse *pParse,\n  ExprList *pOrderBy,\n  int regNew,                     /* First in array of new values */\n  int regOld,                     /* First in array of old values */\n  int addr                        /* Jump here */\n){\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  if( pOrderBy ){\n    int nVal = pOrderBy->nExpr;\n    KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);\n    sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);\n    sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);\n    sqlite3VdbeAddOp3(v, OP_Jump, \n      sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1\n    );\n    VdbeCoverageEqNe(v);\n    sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);\n  }else{\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);\n  }\n}\n\n/*\n** This function is called as part of generating VM programs for RANGE\n** offset PRECEDING/FOLLOWING frame boundaries. Assuming \"ASC\" order for\n** the ORDER BY term in the window, and that argument op is OP_Ge, it generates\n** code equivalent to:\n**\n**   if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;\n**\n** The value of parameter op may also be OP_Gt or OP_Le. In these cases the\n** operator in the above pseudo-code is replaced with \">\" or \"<=\", respectively.\n**\n** If the sort-order for the ORDER BY term in the window is DESC, then the\n** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is\n** subtracted. And the comparison operator is inverted to - \">=\" becomes \"<=\",\n** \">\" becomes \"<\", and so on. So, with DESC sort order, if the argument op\n** is OP_Ge, the generated code is equivalent to:\n**\n**   if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;\n**\n** A special type of arithmetic is used such that if csr1.peerVal is not\n** a numeric type (real or integer), then the result of the addition addition\n** or subtraction is a a copy of csr1.peerVal.\n*/\nstatic void windowCodeRangeTest(\n  WindowCodeArg *p, \n  int op,                         /* OP_Ge, OP_Gt, or OP_Le */\n  int csr1,                       /* Cursor number for cursor 1 */\n  int regVal,                     /* Register containing non-negative number */\n  int csr2,                       /* Cursor number for cursor 2 */\n  int lbl                         /* Jump destination if condition is true */\n){\n  Parse *pParse = p->pParse;\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  ExprList *pOrderBy = p->pMWin->pOrderBy;  /* ORDER BY clause for window */\n  int reg1 = sqlite3GetTempReg(pParse);     /* Reg. for csr1.peerVal+regVal */\n  int reg2 = sqlite3GetTempReg(pParse);     /* Reg. for csr2.peerVal */\n  int regString = ++pParse->nMem;           /* Reg. for constant value '' */\n  int arith = OP_Add;                       /* OP_Add or OP_Subtract */\n  int addrGe;                               /* Jump destination */\n\n  assert( op==OP_Ge || op==OP_Gt || op==OP_Le );\n  assert( pOrderBy && pOrderBy->nExpr==1 );\n  if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_DESC ){\n    switch( op ){\n      case OP_Ge: op = OP_Le; break;\n      case OP_Gt: op = OP_Lt; break;\n      default: assert( op==OP_Le ); op = OP_Ge; break;\n    }\n    arith = OP_Subtract;\n  }\n\n  /* Read the peer-value from each cursor into a register */\n  windowReadPeerValues(p, csr1, reg1);\n  windowReadPeerValues(p, csr2, reg2);\n\n  VdbeModuleComment((v, \"CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl\",\n      reg1, (arith==OP_Add ? \"+\" : \"-\"), regVal,\n      ((op==OP_Ge) ? \">=\" : (op==OP_Le) ? \"<=\" : (op==OP_Gt) ? \">\" : \"<\"), reg2\n  ));\n\n  /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).\n  ** This block adds (or subtracts for DESC) the numeric value in regVal\n  ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob),\n  ** then leave reg1 as it is. In pseudo-code, this is implemented as:\n  **\n  **   if( reg1>='' ) goto addrGe;\n  **   reg1 = reg1 +/- regVal\n  **   addrGe:\n  **\n  ** Since all strings and blobs are greater-than-or-equal-to an empty string,\n  ** the add/subtract is skipped for these, as required. If reg1 is a NULL,\n  ** then the arithmetic is performed, but since adding or subtracting from\n  ** NULL is always NULL anyway, this case is handled as required too.  */\n  sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, \"\", P4_STATIC);\n  addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);\n  VdbeCoverage(v);\n  sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);\n  sqlite3VdbeJumpHere(v, addrGe);\n\n  /* If the BIGNULL flag is set for the ORDER BY, then it is required to \n  ** consider NULL values to be larger than all other values, instead of \n  ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this\n  ** (and adding that capability causes a performance regression), so\n  ** instead if the BIGNULL flag is set then cases where either reg1 or\n  ** reg2 are NULL are handled separately in the following block. The code\n  ** generated is equivalent to:\n  **\n  **   if( reg1 IS NULL ){\n  **     if( op==OP_Ge ) goto lbl;\n  **     if( op==OP_Gt && reg2 IS NOT NULL ) goto lbl;\n  **     if( op==OP_Le && reg2 IS NULL ) goto lbl;\n  **   }else if( reg2 IS NULL ){\n  **     if( op==OP_Le ) goto lbl;\n  **   }\n  **\n  ** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is \n  ** not taken, control jumps over the comparison operator coded below this\n  ** block.  */\n  if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_BIGNULL ){\n    /* This block runs if reg1 contains a NULL. */\n    int addr = sqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v);\n    switch( op ){\n      case OP_Ge: \n        sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl); \n        break;\n      case OP_Gt: \n        sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl); \n        VdbeCoverage(v); \n        break;\n      case OP_Le: \n        sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); \n        VdbeCoverage(v); \n        break;\n      default: assert( op==OP_Lt ); /* no-op */ break;\n    }\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);\n\n    /* This block runs if reg1 is not NULL, but reg2 is. */\n    sqlite3VdbeJumpHere(v, addr);\n    sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); VdbeCoverage(v);\n    if( op==OP_Gt || op==OP_Ge ){\n      sqlite3VdbeChangeP2(v, -1, sqlite3VdbeCurrentAddr(v)+1);\n    }\n  }\n\n  /* Compare registers reg2 and reg1, taking the jump if required. Note that\n  ** control skips over this test if the BIGNULL flag is set and either\n  ** reg1 or reg2 contain a NULL value.  */\n  sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);\n  sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);\n\n  assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );\n  testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);\n  testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt);\n  testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le);\n  testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt);\n  sqlite3ReleaseTempReg(pParse, reg1);\n  sqlite3ReleaseTempReg(pParse, reg2);\n\n  VdbeModuleComment((v, \"CodeRangeTest: end\"));\n}\n\n/*\n** Helper function for sqlite3WindowCodeStep(). Each call to this function\n** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE \n** operation. Refer to the header comment for sqlite3WindowCodeStep() for\n** details.\n*/\nstatic int windowCodeOp(\n WindowCodeArg *p,                /* Context object */\n int op,                          /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */\n int regCountdown,                /* Register for OP_IfPos countdown */\n int jumpOnEof                    /* Jump here if stepped cursor reaches EOF */\n){\n  int csr, reg;\n  Parse *pParse = p->pParse;\n  Window *pMWin = p->pMWin;\n  int ret = 0;\n  Vdbe *v = p->pVdbe;\n  int addrContinue = 0;\n  int bPeer = (pMWin->eFrmType!=TK_ROWS);\n\n  int lblDone = sqlite3VdbeMakeLabel(pParse);\n  int addrNextRange = 0;\n\n  /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame\n  ** starts with UNBOUNDED PRECEDING. */\n  if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){\n    assert( regCountdown==0 && jumpOnEof==0 );\n    return 0;\n  }\n\n  if( regCountdown>0 ){\n    if( pMWin->eFrmType==TK_RANGE ){\n      addrNextRange = sqlite3VdbeCurrentAddr(v);\n      assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );\n      if( op==WINDOW_AGGINVERSE ){\n        if( pMWin->eStart==TK_FOLLOWING ){\n          windowCodeRangeTest(\n              p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone\n          );\n        }else{\n          windowCodeRangeTest(\n              p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone\n          );\n        }\n      }else{\n        windowCodeRangeTest(\n            p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone\n        );\n      }\n    }else{\n      sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, lblDone, 1);\n      VdbeCoverage(v);\n    }\n  }\n\n  if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){\n    windowAggFinal(p, 0);\n  }\n  addrContinue = sqlite3VdbeCurrentAddr(v);\n\n  /* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or\n  ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the \n  ** start cursor does not advance past the end cursor within the \n  ** temporary table. It otherwise might, if (a>b).  */\n  if( pMWin->eStart==pMWin->eEnd && regCountdown\n   && pMWin->eFrmType==TK_RANGE && op==WINDOW_AGGINVERSE\n  ){\n    int regRowid1 = sqlite3GetTempReg(pParse);\n    int regRowid2 = sqlite3GetTempReg(pParse);\n    sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1);\n    sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2);\n    sqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1);\n    VdbeCoverage(v);\n    sqlite3ReleaseTempReg(pParse, regRowid1);\n    sqlite3ReleaseTempReg(pParse, regRowid2);\n    assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING );\n  }\n\n  switch( op ){\n    case WINDOW_RETURN_ROW:\n      csr = p->current.csr;\n      reg = p->current.reg;\n      windowReturnOneRow(p);\n      break;\n\n    case WINDOW_AGGINVERSE:\n      csr = p->start.csr;\n      reg = p->start.reg;\n      if( pMWin->regStartRowid ){\n        assert( pMWin->regEndRowid );\n        sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);\n      }else{\n        windowAggStep(p, pMWin, csr, 1, p->regArg);\n      }\n      break;\n\n    default:\n      assert( op==WINDOW_AGGSTEP );\n      csr = p->end.csr;\n      reg = p->end.reg;\n      if( pMWin->regStartRowid ){\n        assert( pMWin->regEndRowid );\n        sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);\n      }else{\n        windowAggStep(p, pMWin, csr, 0, p->regArg);\n      }\n      break;\n  }\n\n  if( op==p->eDelete ){\n    sqlite3VdbeAddOp1(v, OP_Delete, csr);\n    sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);\n  }\n\n  if( jumpOnEof ){\n    sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);\n    VdbeCoverage(v);\n    ret = sqlite3VdbeAddOp0(v, OP_Goto);\n  }else{\n    sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);\n    VdbeCoverage(v);\n    if( bPeer ){\n      sqlite3VdbeAddOp2(v, OP_Goto, 0, lblDone);\n    }\n  }\n\n  if( bPeer ){\n    int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);\n    int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);\n    windowReadPeerValues(p, csr, regTmp);\n    windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);\n    sqlite3ReleaseTempRange(pParse, regTmp, nReg);\n  }\n\n  if( addrNextRange ){\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);\n  }\n  sqlite3VdbeResolveLabel(v, lblDone);\n  return ret;\n}\n\n\n/*\n** Allocate and return a duplicate of the Window object indicated by the\n** third argument. Set the Window.pOwner field of the new object to\n** pOwner.\n*/\nSQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){\n  Window *pNew = 0;\n  if( ALWAYS(p) ){\n    pNew = sqlite3DbMallocZero(db, sizeof(Window));\n    if( pNew ){\n      pNew->zName = sqlite3DbStrDup(db, p->zName);\n      pNew->zBase = sqlite3DbStrDup(db, p->zBase);\n      pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);\n      pNew->pFunc = p->pFunc;\n      pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);\n      pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);\n      pNew->eFrmType = p->eFrmType;\n      pNew->eEnd = p->eEnd;\n      pNew->eStart = p->eStart;\n      pNew->eExclude = p->eExclude;\n      pNew->regResult = p->regResult;\n      pNew->regAccum = p->regAccum;\n      pNew->iArgCol = p->iArgCol;\n      pNew->iEphCsr = p->iEphCsr;\n      pNew->bExprArgs = p->bExprArgs;\n      pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);\n      pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);\n      pNew->pOwner = pOwner;\n      pNew->bImplicitFrame = p->bImplicitFrame;\n    }\n  }\n  return pNew;\n}\n\n/*\n** Return a copy of the linked list of Window objects passed as the\n** second argument.\n*/\nSQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p){\n  Window *pWin;\n  Window *pRet = 0;\n  Window **pp = &pRet;\n\n  for(pWin=p; pWin; pWin=pWin->pNextWin){\n    *pp = sqlite3WindowDup(db, 0, pWin);\n    if( *pp==0 ) break;\n    pp = &((*pp)->pNextWin);\n  }\n\n  return pRet;\n}\n\n/*\n** Return true if it can be determined at compile time that expression \n** pExpr evaluates to a value that, when cast to an integer, is greater \n** than zero. False otherwise.\n**\n** If an OOM error occurs, this function sets the Parse.db.mallocFailed \n** flag and returns zero.\n*/\nstatic int windowExprGtZero(Parse *pParse, Expr *pExpr){\n  int ret = 0;\n  sqlite3 *db = pParse->db;\n  sqlite3_value *pVal = 0;\n  sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);\n  if( pVal && sqlite3_value_int(pVal)>0 ){\n    ret = 1;\n  }\n  sqlite3ValueFree(pVal);\n  return ret;\n}\n\n/*\n** sqlite3WhereBegin() has already been called for the SELECT statement \n** passed as the second argument when this function is invoked. It generates\n** code to populate the Window.regResult register for each window function \n** and invoke the sub-routine at instruction addrGosub once for each row.\n** sqlite3WhereEnd() is always called before returning. \n**\n** This function handles several different types of window frames, which\n** require slightly different processing. The following pseudo code is\n** used to implement window frames of the form:\n**\n**   ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING\n**\n** Other window frame types use variants of the following:\n**\n**     ... loop started by sqlite3WhereBegin() ...\n**       if( new partition ){\n**         Gosub flush\n**       }\n**       Insert new row into eph table.\n**       \n**       if( first row of partition ){\n**         // Rewind three cursors, all open on the eph table.\n**         Rewind(csrEnd);\n**         Rewind(csrStart);\n**         Rewind(csrCurrent);\n**       \n**         regEnd = <expr2>          // FOLLOWING expression\n**         regStart = <expr1>        // PRECEDING expression\n**       }else{\n**         // First time this branch is taken, the eph table contains two \n**         // rows. The first row in the partition, which all three cursors\n**         // currently point to, and the following row.\n**         AGGSTEP\n**         if( (regEnd--)<=0 ){\n**           RETURN_ROW\n**           if( (regStart--)<=0 ){\n**             AGGINVERSE\n**           }\n**         }\n**       }\n**     }\n**     flush:\n**       AGGSTEP\n**       while( 1 ){\n**         RETURN ROW\n**         if( csrCurrent is EOF ) break;\n**         if( (regStart--)<=0 ){\n**           AggInverse(csrStart)\n**           Next(csrStart)\n**         }\n**       }\n**\n** The pseudo-code above uses the following shorthand:\n**\n**   AGGSTEP:    invoke the aggregate xStep() function for each window function\n**               with arguments read from the current row of cursor csrEnd, then\n**               step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).\n**\n**   RETURN_ROW: return a row to the caller based on the contents of the \n**               current row of csrCurrent and the current state of all \n**               aggregates. Then step cursor csrCurrent forward one row.\n**\n**   AGGINVERSE: invoke the aggregate xInverse() function for each window \n**               functions with arguments read from the current row of cursor\n**               csrStart. Then step csrStart forward one row.\n**\n** There are two other ROWS window frames that are handled significantly\n** differently from the above - \"BETWEEN <expr> PRECEDING AND <expr> PRECEDING\"\n** and \"BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING\". These are special \n** cases because they change the order in which the three cursors (csrStart,\n** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that\n** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these\n** three.\n**\n**   ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING\n**\n**     ... loop started by sqlite3WhereBegin() ...\n**       if( new partition ){\n**         Gosub flush\n**       }\n**       Insert new row into eph table.\n**       if( first row of partition ){\n**         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)\n**         regEnd = <expr2>\n**         regStart = <expr1>\n**       }else{\n**         if( (regEnd--)<=0 ){\n**           AGGSTEP\n**         }\n**         RETURN_ROW\n**         if( (regStart--)<=0 ){\n**           AGGINVERSE\n**         }\n**       }\n**     }\n**     flush:\n**       if( (regEnd--)<=0 ){\n**         AGGSTEP\n**       }\n**       RETURN_ROW\n**\n**\n**   ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING\n**\n**     ... loop started by sqlite3WhereBegin() ...\n**     if( new partition ){\n**       Gosub flush\n**     }\n**     Insert new row into eph table.\n**     if( first row of partition ){\n**       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)\n**       regEnd = <expr2>\n**       regStart = regEnd - <expr1>\n**     }else{\n**       AGGSTEP\n**       if( (regEnd--)<=0 ){\n**         RETURN_ROW\n**       }\n**       if( (regStart--)<=0 ){\n**         AGGINVERSE\n**       }\n**     }\n**   }\n**   flush:\n**     AGGSTEP\n**     while( 1 ){\n**       if( (regEnd--)<=0 ){\n**         RETURN_ROW\n**         if( eof ) break;\n**       }\n**       if( (regStart--)<=0 ){\n**         AGGINVERSE\n**         if( eof ) break\n**       }\n**     }\n**     while( !eof csrCurrent ){\n**       RETURN_ROW\n**     }\n**\n** For the most part, the patterns above are adapted to support UNBOUNDED by\n** assuming that it is equivalent to \"infinity PRECEDING/FOLLOWING\" and\n** CURRENT ROW by assuming that it is equivilent to \"0 PRECEDING/FOLLOWING\".\n** This is optimized of course - branches that will never be taken and\n** conditions that are always true are omitted from the VM code. The only\n** exceptional case is:\n**\n**   ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING\n**\n**     ... loop started by sqlite3WhereBegin() ...\n**     if( new partition ){\n**       Gosub flush\n**     }\n**     Insert new row into eph table.\n**     if( first row of partition ){\n**       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)\n**       regStart = <expr1>\n**     }else{\n**       AGGSTEP\n**     }\n**   }\n**   flush:\n**     AGGSTEP\n**     while( 1 ){\n**       if( (regStart--)<=0 ){\n**         AGGINVERSE\n**         if( eof ) break\n**       }\n**       RETURN_ROW\n**     }\n**     while( !eof csrCurrent ){\n**       RETURN_ROW\n**     }\n**\n** Also requiring special handling are the cases:\n**\n**   ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING\n**   ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING\n**\n** when (expr1 < expr2). This is detected at runtime, not by this function.\n** To handle this case, the pseudo-code programs depicted above are modified\n** slightly to be:\n**\n**     ... loop started by sqlite3WhereBegin() ...\n**     if( new partition ){\n**       Gosub flush\n**     }\n**     Insert new row into eph table.\n**     if( first row of partition ){\n**       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)\n**       regEnd = <expr2>\n**       regStart = <expr1>\n**       if( regEnd < regStart ){\n**         RETURN_ROW\n**         delete eph table contents\n**         continue\n**       }\n**     ...\n**\n** The new \"continue\" statement in the above jumps to the next iteration\n** of the outer loop - the one started by sqlite3WhereBegin().\n**\n** The various GROUPS cases are implemented using the same patterns as\n** ROWS. The VM code is modified slightly so that:\n**\n**   1. The else branch in the main loop is only taken if the row just\n**      added to the ephemeral table is the start of a new group. In\n**      other words, it becomes:\n**\n**         ... loop started by sqlite3WhereBegin() ...\n**         if( new partition ){\n**           Gosub flush\n**         }\n**         Insert new row into eph table.\n**         if( first row of partition ){\n**           Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)\n**           regEnd = <expr2>\n**           regStart = <expr1>\n**         }else if( new group ){\n**           ... \n**         }\n**       }\n**\n**   2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or \n**      AGGINVERSE step processes the current row of the relevant cursor and\n**      all subsequent rows belonging to the same group.\n**\n** RANGE window frames are a little different again. As for GROUPS, the \n** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE\n** deal in groups instead of rows. As for ROWS and GROUPS, there are three\n** basic cases:\n**\n**   RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING\n**\n**     ... loop started by sqlite3WhereBegin() ...\n**       if( new partition ){\n**         Gosub flush\n**       }\n**       Insert new row into eph table.\n**       if( first row of partition ){\n**         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)\n**         regEnd = <expr2>\n**         regStart = <expr1>\n**       }else{\n**         AGGSTEP\n**         while( (csrCurrent.key + regEnd) < csrEnd.key ){\n**           RETURN_ROW\n**           while( csrStart.key + regStart) < csrCurrent.key ){\n**             AGGINVERSE\n**           }\n**         }\n**       }\n**     }\n**     flush:\n**       AGGSTEP\n**       while( 1 ){\n**         RETURN ROW\n**         if( csrCurrent is EOF ) break;\n**           while( csrStart.key + regStart) < csrCurrent.key ){\n**             AGGINVERSE\n**           }\n**         }\n**       }\n**\n** In the above notation, \"csr.key\" means the current value of the ORDER BY \n** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING\n** or <expr PRECEDING) read from cursor csr.\n**\n**   RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING\n**\n**     ... loop started by sqlite3WhereBegin() ...\n**       if( new partition ){\n**         Gosub flush\n**       }\n**       Insert new row into eph table.\n**       if( first row of partition ){\n**         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)\n**         regEnd = <expr2>\n**         regStart = <expr1>\n**       }else{\n**         while( (csrEnd.key + regEnd) <= csrCurrent.key ){\n**           AGGSTEP\n**         }\n**         while( (csrStart.key + regStart) < csrCurrent.key ){\n**           AGGINVERSE\n**         }\n**         RETURN_ROW\n**       }\n**     }\n**     flush:\n**       while( (csrEnd.key + regEnd) <= csrCurrent.key ){\n**         AGGSTEP\n**       }\n**       while( (csrStart.key + regStart) < csrCurrent.key ){\n**         AGGINVERSE\n**       }\n**       RETURN_ROW\n**\n**   RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING\n**\n**     ... loop started by sqlite3WhereBegin() ...\n**       if( new partition ){\n**         Gosub flush\n**       }\n**       Insert new row into eph table.\n**       if( first row of partition ){\n**         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)\n**         regEnd = <expr2>\n**         regStart = <expr1>\n**       }else{\n**         AGGSTEP\n**         while( (csrCurrent.key + regEnd) < csrEnd.key ){\n**           while( (csrCurrent.key + regStart) > csrStart.key ){\n**             AGGINVERSE\n**           }\n**           RETURN_ROW\n**         }\n**       }\n**     }\n**     flush:\n**       AGGSTEP\n**       while( 1 ){\n**         while( (csrCurrent.key + regStart) > csrStart.key ){\n**           AGGINVERSE\n**           if( eof ) break \"while( 1 )\" loop.\n**         }\n**         RETURN_ROW\n**       }\n**       while( !eof csrCurrent ){\n**         RETURN_ROW\n**       }\n**\n** The text above leaves out many details. Refer to the code and comments\n** below for a more complete picture.\n*/\nSQLITE_PRIVATE void sqlite3WindowCodeStep(\n  Parse *pParse,                  /* Parse context */\n  Select *p,                      /* Rewritten SELECT statement */\n  WhereInfo *pWInfo,              /* Context returned by sqlite3WhereBegin() */\n  int regGosub,                   /* Register for OP_Gosub */\n  int addrGosub                   /* OP_Gosub here to return each row */\n){\n  Window *pMWin = p->pWin;\n  ExprList *pOrderBy = pMWin->pOrderBy;\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  int csrWrite;                   /* Cursor used to write to eph. table */\n  int csrInput = p->pSrc->a[0].iCursor;     /* Cursor of sub-select */\n  int nInput = p->pSrc->a[0].pTab->nCol;    /* Number of cols returned by sub */\n  int iInput;                               /* To iterate through sub cols */\n  int addrNe;                     /* Address of OP_Ne */\n  int addrGosubFlush = 0;         /* Address of OP_Gosub to flush: */\n  int addrInteger = 0;            /* Address of OP_Integer */\n  int addrEmpty;                  /* Address of OP_Rewind in flush: */\n  int regNew;                     /* Array of registers holding new input row */\n  int regRecord;                  /* regNew array in record form */\n  int regRowid;                   /* Rowid for regRecord in eph table */\n  int regNewPeer = 0;             /* Peer values for new row (part of regNew) */\n  int regPeer = 0;                /* Peer values for current row */\n  int regFlushPart = 0;           /* Register for \"Gosub flush_partition\" */\n  WindowCodeArg s;                /* Context object for sub-routines */\n  int lblWhereEnd;                /* Label just before sqlite3WhereEnd() code */\n  int regStart = 0;               /* Value of <expr> PRECEDING */\n  int regEnd = 0;                 /* Value of <expr> FOLLOWING */\n\n  assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT \n       || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED \n  );\n  assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT \n       || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING \n  );\n  assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT\n       || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES\n       || pMWin->eExclude==TK_NO\n  );\n\n  lblWhereEnd = sqlite3VdbeMakeLabel(pParse);\n\n  /* Fill in the context object */\n  memset(&s, 0, sizeof(WindowCodeArg));\n  s.pParse = pParse;\n  s.pMWin = pMWin;\n  s.pVdbe = v;\n  s.regGosub = regGosub;\n  s.addrGosub = addrGosub;\n  s.current.csr = pMWin->iEphCsr;\n  csrWrite = s.current.csr+1;\n  s.start.csr = s.current.csr+2;\n  s.end.csr = s.current.csr+3;\n\n  /* Figure out when rows may be deleted from the ephemeral table. There\n  ** are four options - they may never be deleted (eDelete==0), they may \n  ** be deleted as soon as they are no longer part of the window frame\n  ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row \n  ** has been returned to the caller (WINDOW_RETURN_ROW), or they may\n  ** be deleted after they enter the frame (WINDOW_AGGSTEP). */\n  switch( pMWin->eStart ){\n    case TK_FOLLOWING:\n      if( pMWin->eFrmType!=TK_RANGE\n       && windowExprGtZero(pParse, pMWin->pStart)\n      ){\n        s.eDelete = WINDOW_RETURN_ROW;\n      }\n      break;\n    case TK_UNBOUNDED:\n      if( windowCacheFrame(pMWin)==0 ){\n        if( pMWin->eEnd==TK_PRECEDING ){\n          if( pMWin->eFrmType!=TK_RANGE\n           && windowExprGtZero(pParse, pMWin->pEnd)\n          ){\n            s.eDelete = WINDOW_AGGSTEP;\n          }\n        }else{\n          s.eDelete = WINDOW_RETURN_ROW;\n        }\n      }\n      break;\n    default:\n      s.eDelete = WINDOW_AGGINVERSE;\n      break;\n  }\n\n  /* Allocate registers for the array of values from the sub-query, the\n  ** samve values in record form, and the rowid used to insert said record\n  ** into the ephemeral table.  */\n  regNew = pParse->nMem+1;\n  pParse->nMem += nInput;\n  regRecord = ++pParse->nMem;\n  regRowid = ++pParse->nMem;\n\n  /* If the window frame contains an \"<expr> PRECEDING\" or \"<expr> FOLLOWING\"\n  ** clause, allocate registers to store the results of evaluating each\n  ** <expr>.  */\n  if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){\n    regStart = ++pParse->nMem;\n  }\n  if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){\n    regEnd = ++pParse->nMem;\n  }\n\n  /* If this is not a \"ROWS BETWEEN ...\" frame, then allocate arrays of\n  ** registers to store copies of the ORDER BY expressions (peer values) \n  ** for the main loop, and for each cursor (start, current and end). */\n  if( pMWin->eFrmType!=TK_ROWS ){\n    int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);\n    regNewPeer = regNew + pMWin->nBufferCol;\n    if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;\n    regPeer = pParse->nMem+1;       pParse->nMem += nPeer;\n    s.start.reg = pParse->nMem+1;   pParse->nMem += nPeer;\n    s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;\n    s.end.reg = pParse->nMem+1;     pParse->nMem += nPeer;\n  }\n\n  /* Load the column values for the row returned by the sub-select\n  ** into an array of registers starting at regNew. Assemble them into\n  ** a record in register regRecord. */\n  for(iInput=0; iInput<nInput; iInput++){\n    sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);\n  }\n  sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);\n\n  /* An input row has just been read into an array of registers starting\n  ** at regNew. If the window has a PARTITION clause, this block generates \n  ** VM code to check if the input row is the start of a new partition.\n  ** If so, it does an OP_Gosub to an address to be filled in later. The\n  ** address of the OP_Gosub is stored in local variable addrGosubFlush. */\n  if( pMWin->pPartition ){\n    int addr;\n    ExprList *pPart = pMWin->pPartition;\n    int nPart = pPart->nExpr;\n    int regNewPart = regNew + pMWin->nBufferCol;\n    KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);\n\n    regFlushPart = ++pParse->nMem;\n    addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);\n    sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);\n    sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);\n    VdbeCoverageEqNe(v);\n    addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);\n    VdbeComment((v, \"call flush_partition\"));\n    sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);\n  }\n\n  /* Insert the new row into the ephemeral table */\n  sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid);\n  sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid);\n  addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid);\n  VdbeCoverageNeverNull(v);\n\n  /* This block is run for the first row of each partition */\n  s.regArg = windowInitAccum(pParse, pMWin);\n\n  if( regStart ){\n    sqlite3ExprCode(pParse, pMWin->pStart, regStart);\n    windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE?3:0));\n  }\n  if( regEnd ){\n    sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);\n    windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE?3:0));\n  }\n\n  if( pMWin->eFrmType!=TK_RANGE && pMWin->eStart==pMWin->eEnd && regStart ){\n    int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);\n    int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);\n    VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */\n    VdbeCoverageNeverNullIf(v, op==OP_Le); /*   values previously checked */\n    windowAggFinal(&s, 0);\n    sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);\n    VdbeCoverageNeverTaken(v);\n    windowReturnOneRow(&s);\n    sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);\n    sqlite3VdbeJumpHere(v, addrGe);\n  }\n  if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){\n    assert( pMWin->eEnd==TK_FOLLOWING );\n    sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);\n  }\n\n  if( pMWin->eStart!=TK_UNBOUNDED ){\n    sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1);\n    VdbeCoverageNeverTaken(v);\n  }\n  sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);\n  VdbeCoverageNeverTaken(v);\n  sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1);\n  VdbeCoverageNeverTaken(v);\n  if( regPeer && pOrderBy ){\n    sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);\n    sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);\n    sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);\n    sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);\n  }\n\n  sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);\n\n  sqlite3VdbeJumpHere(v, addrNe);\n\n  /* Beginning of the block executed for the second and subsequent rows. */\n  if( regPeer ){\n    windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);\n  }\n  if( pMWin->eStart==TK_FOLLOWING ){\n    windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);\n    if( pMWin->eEnd!=TK_UNBOUNDED ){\n      if( pMWin->eFrmType==TK_RANGE ){\n        int lbl = sqlite3VdbeMakeLabel(pParse);\n        int addrNext = sqlite3VdbeCurrentAddr(v);\n        windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);\n        windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);\n        windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);\n        sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);\n        sqlite3VdbeResolveLabel(v, lbl);\n      }else{\n        windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);\n        windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);\n      }\n    }\n  }else\n  if( pMWin->eEnd==TK_PRECEDING ){\n    int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);\n    windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);\n    if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);\n    windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);\n    if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);\n  }else{\n    int addr = 0;\n    windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);\n    if( pMWin->eEnd!=TK_UNBOUNDED ){\n      if( pMWin->eFrmType==TK_RANGE ){\n        int lbl = 0;\n        addr = sqlite3VdbeCurrentAddr(v);\n        if( regEnd ){\n          lbl = sqlite3VdbeMakeLabel(pParse);\n          windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);\n        }\n        windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);\n        windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);\n        if( regEnd ){\n          sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);\n          sqlite3VdbeResolveLabel(v, lbl);\n        }\n      }else{\n        if( regEnd ){\n          addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);\n          VdbeCoverage(v);\n        }\n        windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);\n        windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);\n        if( regEnd ) sqlite3VdbeJumpHere(v, addr);\n      }\n    }\n  }\n\n  /* End of the main input loop */\n  sqlite3VdbeResolveLabel(v, lblWhereEnd);\n  sqlite3WhereEnd(pWInfo);\n\n  /* Fall through */\n  if( pMWin->pPartition ){\n    addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);\n    sqlite3VdbeJumpHere(v, addrGosubFlush);\n  }\n\n  addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);\n  VdbeCoverage(v);\n  if( pMWin->eEnd==TK_PRECEDING ){\n    int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);\n    windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);\n    if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);\n    windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);\n  }else if( pMWin->eStart==TK_FOLLOWING ){\n    int addrStart;\n    int addrBreak1;\n    int addrBreak2;\n    int addrBreak3;\n    windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);\n    if( pMWin->eFrmType==TK_RANGE ){\n      addrStart = sqlite3VdbeCurrentAddr(v);\n      addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);\n      addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);\n    }else\n    if( pMWin->eEnd==TK_UNBOUNDED ){\n      addrStart = sqlite3VdbeCurrentAddr(v);\n      addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);\n      addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);\n    }else{\n      assert( pMWin->eEnd==TK_FOLLOWING );\n      addrStart = sqlite3VdbeCurrentAddr(v);\n      addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);\n      addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);\n    }\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);\n    sqlite3VdbeJumpHere(v, addrBreak2);\n    addrStart = sqlite3VdbeCurrentAddr(v);\n    addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);\n    sqlite3VdbeJumpHere(v, addrBreak1);\n    sqlite3VdbeJumpHere(v, addrBreak3);\n  }else{\n    int addrBreak;\n    int addrStart;\n    windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);\n    addrStart = sqlite3VdbeCurrentAddr(v);\n    addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);\n    windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);\n    sqlite3VdbeJumpHere(v, addrBreak);\n  }\n  sqlite3VdbeJumpHere(v, addrEmpty);\n\n  sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);\n  if( pMWin->pPartition ){\n    if( pMWin->regStartRowid ){\n      sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);\n      sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);\n    }\n    sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));\n    sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);\n  }\n}\n\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n\n/************** End of window.c **********************************************/\n/************** Begin file parse.c *******************************************/\n/*\n** 2000-05-29\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** Driver template for the LEMON parser generator.\n**\n** The \"lemon\" program processes an LALR(1) input grammar file, then uses\n** this template to construct a parser.  The \"lemon\" program inserts text\n** at each \"%%\" line.  Also, any \"P-a-r-s-e\" identifer prefix (without the\n** interstitial \"-\" characters) contained in this template is changed into\n** the value of the %name directive from the grammar.  Otherwise, the content\n** of this template is copied straight through into the generate parser\n** source file.\n**\n** The following is the concatenation of all %include directives from the\n** input grammar file:\n*/\n/* #include <stdio.h> */\n/* #include <assert.h> */\n/************ Begin %include sections from the grammar ************************/\n\n/* #include \"sqliteInt.h\" */\n\n/*\n** Disable all error recovery processing in the parser push-down\n** automaton.\n*/\n#define YYNOERRORRECOVERY 1\n\n/*\n** Make yytestcase() the same as testcase()\n*/\n#define yytestcase(X) testcase(X)\n\n/*\n** Indicate that sqlite3ParserFree() will never be called with a null\n** pointer.\n*/\n#define YYPARSEFREENEVERNULL 1\n\n/*\n** In the amalgamation, the parse.c file generated by lemon and the\n** tokenize.c file are concatenated.  In that case, sqlite3RunParser()\n** has access to the the size of the yyParser object and so the parser\n** engine can be allocated from stack.  In that case, only the\n** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked\n** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be\n** omitted.\n*/\n#ifdef SQLITE_AMALGAMATION\n# define sqlite3Parser_ENGINEALWAYSONSTACK 1\n#endif\n\n/*\n** Alternative datatype for the argument to the malloc() routine passed\n** into sqlite3ParserAlloc().  The default is size_t.\n*/\n#define YYMALLOCARGTYPE  u64\n\n/*\n** An instance of the following structure describes the event of a\n** TRIGGER.  \"a\" is the event type, one of TK_UPDATE, TK_INSERT,\n** TK_DELETE, or TK_INSTEAD.  If the event is of the form\n**\n**      UPDATE ON (a,b,c)\n**\n** Then the \"b\" IdList records the list \"a,b,c\".\n*/\nstruct TrigEvent { int a; IdList * b; };\n\nstruct FrameBound     { int eType; Expr *pExpr; };\n\n/*\n** Disable lookaside memory allocation for objects that might be\n** shared across database connections.\n*/\nstatic void disableLookaside(Parse *pParse){\n  sqlite3 *db = pParse->db;\n  pParse->disableLookaside++;\n  DisableLookaside;\n}\n\n\n  /*\n  ** For a compound SELECT statement, make sure p->pPrior->pNext==p for\n  ** all elements in the list.  And make sure list length does not exceed\n  ** SQLITE_LIMIT_COMPOUND_SELECT.\n  */\n  static void parserDoubleLinkSelect(Parse *pParse, Select *p){\n    assert( p!=0 );\n    if( p->pPrior ){\n      Select *pNext = 0, *pLoop;\n      int mxSelect, cnt = 0;\n      for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){\n        pLoop->pNext = pNext;\n        pLoop->selFlags |= SF_Compound;\n      }\n      if( (p->selFlags & SF_MultiValue)==0 && \n        (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&\n        cnt>mxSelect\n      ){\n        sqlite3ErrorMsg(pParse, \"too many terms in compound SELECT\");\n      }\n    }\n  }\n\n\n  /* Construct a new Expr object from a single identifier.  Use the\n  ** new Expr to populate pOut.  Set the span of pOut to be the identifier\n  ** that created the expression.\n  */\n  static Expr *tokenExpr(Parse *pParse, int op, Token t){\n    Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);\n    if( p ){\n      /* memset(p, 0, sizeof(Expr)); */\n      p->op = (u8)op;\n      p->affExpr = 0;\n      p->flags = EP_Leaf;\n      ExprClearVVAProperties(p);\n      p->iAgg = -1;\n      p->pLeft = p->pRight = 0;\n      p->x.pList = 0;\n      p->pAggInfo = 0;\n      p->y.pTab = 0;\n      p->op2 = 0;\n      p->iTable = 0;\n      p->iColumn = 0;\n      p->u.zToken = (char*)&p[1];\n      memcpy(p->u.zToken, t.z, t.n);\n      p->u.zToken[t.n] = 0;\n      if( sqlite3Isquote(p->u.zToken[0]) ){\n        sqlite3DequoteExpr(p);\n      }\n#if SQLITE_MAX_EXPR_DEPTH>0\n      p->nHeight = 1;\n#endif  \n      if( IN_RENAME_OBJECT ){\n        return (Expr*)sqlite3RenameTokenMap(pParse, (void*)p, &t);\n      }\n    }\n    return p;\n  }\n\n\n  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a\n  ** unary TK_ISNULL or TK_NOTNULL expression. */\n  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){\n    sqlite3 *db = pParse->db;\n    if( pA && pY && pY->op==TK_NULL && !IN_RENAME_OBJECT ){\n      pA->op = (u8)op;\n      sqlite3ExprDelete(db, pA->pRight);\n      pA->pRight = 0;\n    }\n  }\n\n  /* Add a single new term to an ExprList that is used to store a\n  ** list of identifiers.  Report an error if the ID list contains\n  ** a COLLATE clause or an ASC or DESC keyword, except ignore the\n  ** error while parsing a legacy schema.\n  */\n  static ExprList *parserAddExprIdListTerm(\n    Parse *pParse,\n    ExprList *pPrior,\n    Token *pIdToken,\n    int hasCollate,\n    int sortOrder\n  ){\n    ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);\n    if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)\n        && pParse->db->init.busy==0\n    ){\n      sqlite3ErrorMsg(pParse, \"syntax error after column name \\\"%.*s\\\"\",\n                         pIdToken->n, pIdToken->z);\n    }\n    sqlite3ExprListSetName(pParse, p, pIdToken, 1);\n    return p;\n  }\n\n#if TK_SPAN>255\n# error too many tokens in the grammar\n#endif\n/**************** End of %include directives **********************************/\n/* These constants specify the various numeric values for terminal symbols\n** in a format understandable to \"makeheaders\".  This section is blank unless\n** \"lemon\" is run with the \"-m\" command-line option.\n***************** Begin makeheaders token definitions *************************/\n/**************** End makeheaders token definitions ***************************/\n\n/* The next sections is a series of control #defines.\n** various aspects of the generated parser.\n**    YYCODETYPE         is the data type used to store the integer codes\n**                       that represent terminal and non-terminal symbols.\n**                       \"unsigned char\" is used if there are fewer than\n**                       256 symbols.  Larger types otherwise.\n**    YYNOCODE           is a number of type YYCODETYPE that is not used for\n**                       any terminal or nonterminal symbol.\n**    YYFALLBACK         If defined, this indicates that one or more tokens\n**                       (also known as: \"terminal symbols\") have fall-back\n**                       values which should be used if the original symbol\n**                       would not parse.  This permits keywords to sometimes\n**                       be used as identifiers, for example.\n**    YYACTIONTYPE       is the data type used for \"action codes\" - numbers\n**                       that indicate what to do in response to the next\n**                       token.\n**    sqlite3ParserTOKENTYPE     is the data type used for minor type for terminal\n**                       symbols.  Background: A \"minor type\" is a semantic\n**                       value associated with a terminal or non-terminal\n**                       symbols.  For example, for an \"ID\" terminal symbol,\n**                       the minor type might be the name of the identifier.\n**                       Each non-terminal can have a different minor type.\n**                       Terminal symbols all have the same minor type, though.\n**                       This macros defines the minor type for terminal \n**                       symbols.\n**    YYMINORTYPE        is the data type used for all minor types.\n**                       This is typically a union of many types, one of\n**                       which is sqlite3ParserTOKENTYPE.  The entry in the union\n**                       for terminal symbols is called \"yy0\".\n**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If\n**                       zero the stack is dynamically sized using realloc()\n**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument\n**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument\n**    sqlite3ParserARG_PARAM     Code to pass %extra_argument as a subroutine parameter\n**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser\n**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser\n**    sqlite3ParserCTX_*         As sqlite3ParserARG_ except for %extra_context\n**    YYERRORSYMBOL      is the code number of the error symbol.  If not\n**                       defined, then do no error processing.\n**    YYNSTATE           the combined number of states.\n**    YYNRULE            the number of rules in the grammar\n**    YYNTOKEN           Number of terminal symbols\n**    YY_MAX_SHIFT       Maximum value for shift actions\n**    YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions\n**    YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions\n**    YY_ERROR_ACTION    The yy_action[] code for syntax error\n**    YY_ACCEPT_ACTION   The yy_action[] code for accept\n**    YY_NO_ACTION       The yy_action[] code for no-op\n**    YY_MIN_REDUCE      Minimum value for reduce actions\n**    YY_MAX_REDUCE      Maximum value for reduce actions\n*/\n#ifndef INTERFACE\n# define INTERFACE 1\n#endif\n/************* Begin control #defines *****************************************/\n#define YYCODETYPE unsigned short int\n#define YYNOCODE 310\n#define YYACTIONTYPE unsigned short int\n#define YYWILDCARD 100\n#define sqlite3ParserTOKENTYPE Token\ntypedef union {\n  int yyinit;\n  sqlite3ParserTOKENTYPE yy0;\n  SrcList* yy47;\n  u8 yy58;\n  struct FrameBound yy77;\n  With* yy131;\n  int yy192;\n  Expr* yy202;\n  struct {int value; int mask;} yy207;\n  struct TrigEvent yy230;\n  ExprList* yy242;\n  Window* yy303;\n  Upsert* yy318;\n  const char* yy436;\n  TriggerStep* yy447;\n  Select* yy539;\n  IdList* yy600;\n} YYMINORTYPE;\n#ifndef YYSTACKDEPTH\n#define YYSTACKDEPTH 100\n#endif\n#define sqlite3ParserARG_SDECL\n#define sqlite3ParserARG_PDECL\n#define sqlite3ParserARG_PARAM\n#define sqlite3ParserARG_FETCH\n#define sqlite3ParserARG_STORE\n#define sqlite3ParserCTX_SDECL Parse *pParse;\n#define sqlite3ParserCTX_PDECL ,Parse *pParse\n#define sqlite3ParserCTX_PARAM ,pParse\n#define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse;\n#define sqlite3ParserCTX_STORE yypParser->pParse=pParse;\n#define YYFALLBACK 1\n#define YYNSTATE             551\n#define YYNRULE              385\n#define YYNRULE_WITH_ACTION  325\n#define YYNTOKEN             181\n#define YY_MAX_SHIFT         550\n#define YY_MIN_SHIFTREDUCE   801\n#define YY_MAX_SHIFTREDUCE   1185\n#define YY_ERROR_ACTION      1186\n#define YY_ACCEPT_ACTION     1187\n#define YY_NO_ACTION         1188\n#define YY_MIN_REDUCE        1189\n#define YY_MAX_REDUCE        1573\n/************* End control #defines *******************************************/\n#define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])))\n\n/* Define the yytestcase() macro to be a no-op if is not already defined\n** otherwise.\n**\n** Applications can choose to define yytestcase() in the %include section\n** to a macro that can assist in verifying code coverage.  For production\n** code the yytestcase() macro should be turned off.  But it is useful\n** for testing.\n*/\n#ifndef yytestcase\n# define yytestcase(X)\n#endif\n\n\n/* Next are the tables used to determine what action to take based on the\n** current state and lookahead token.  These tables are used to implement\n** functions that take a state number and lookahead value and return an\n** action integer.  \n**\n** Suppose the action integer is N.  Then the action is determined as\n** follows\n**\n**   0 <= N <= YY_MAX_SHIFT             Shift N.  That is, push the lookahead\n**                                      token onto the stack and goto state N.\n**\n**   N between YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then\n**     and YY_MAX_SHIFTREDUCE           reduce by rule N-YY_MIN_SHIFTREDUCE.\n**\n**   N == YY_ERROR_ACTION               A syntax error has occurred.\n**\n**   N == YY_ACCEPT_ACTION              The parser accepts its input.\n**\n**   N == YY_NO_ACTION                  No such action.  Denotes unused\n**                                      slots in the yy_action[] table.\n**\n**   N between YY_MIN_REDUCE            Reduce by rule N-YY_MIN_REDUCE\n**     and YY_MAX_REDUCE\n**\n** The action table is constructed as a single large table named yy_action[].\n** Given state S and lookahead X, the action is computed as either:\n**\n**    (A)   N = yy_action[ yy_shift_ofst[S] + X ]\n**    (B)   N = yy_default[S]\n**\n** The (A) formula is preferred.  The B formula is used instead if\n** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X.\n**\n** The formulas above are for computing the action when the lookahead is\n** a terminal symbol.  If the lookahead is a non-terminal (as occurs after\n** a reduce action) then the yy_reduce_ofst[] array is used in place of\n** the yy_shift_ofst[] array.\n**\n** The following are the tables generated in this section:\n**\n**  yy_action[]        A single table containing all actions.\n**  yy_lookahead[]     A table containing the lookahead for each entry in\n**                     yy_action.  Used to detect hash collisions.\n**  yy_shift_ofst[]    For each state, the offset into yy_action for\n**                     shifting terminals.\n**  yy_reduce_ofst[]   For each state, the offset into yy_action for\n**                     shifting non-terminals after a reduce.\n**  yy_default[]       Default action for each state.\n**\n*********** Begin parsing tables **********************************************/\n#define YY_ACTTAB_COUNT (1958)\nstatic const YYACTIONTYPE yy_action[] = {\n /*     0 */   544, 1220,  544,  449, 1258,  544, 1237,  544,  114,  111,\n /*    10 */   211,  544, 1535,  544, 1258,  521,  114,  111,  211,  390,\n /*    20 */  1230,  342,   42,   42,   42,   42, 1223,   42,   42,   71,\n /*    30 */    71,  935, 1222,   71,   71,   71,   71, 1460, 1491,  936,\n /*    40 */   818,  451,    6,  121,  122,  112, 1163, 1163, 1004, 1007,\n /*    50 */   997,  997,  119,  119,  120,  120,  120,  120, 1541,  390,\n /*    60 */  1356, 1515,  550,    2, 1191,  194,  526,  434,  143,  291,\n /*    70 */   526,  136,  526,  369,  261,  502,  272,  383, 1271,  525,\n /*    80 */   501,  491,  164,  121,  122,  112, 1163, 1163, 1004, 1007,\n /*    90 */   997,  997,  119,  119,  120,  120,  120,  120, 1356,  440,\n /*   100 */  1512,  118,  118,  118,  118,  117,  117,  116,  116,  116,\n /*   110 */   115,  422,  266,  266,  266,  266, 1496,  356, 1498,  433,\n /*   120 */   355, 1496,  515,  522, 1483,  541, 1112,  541, 1112,  390,\n /*   130 */   403,  241,  208,  114,  111,  211,   98,  290,  535,  221,\n /*   140 */  1027,  118,  118,  118,  118,  117,  117,  116,  116,  116,\n /*   150 */   115,  422, 1140,  121,  122,  112, 1163, 1163, 1004, 1007,\n /*   160 */   997,  997,  119,  119,  120,  120,  120,  120,  404,  426,\n /*   170 */   117,  117,  116,  116,  116,  115,  422, 1416,  466,  123,\n /*   180 */   118,  118,  118,  118,  117,  117,  116,  116,  116,  115,\n /*   190 */   422,  116,  116,  116,  115,  422,  538,  538,  538,  390,\n /*   200 */   503,  120,  120,  120,  120,  113, 1049, 1140, 1141, 1142,\n /*   210 */  1049,  118,  118,  118,  118,  117,  117,  116,  116,  116,\n /*   220 */   115,  422, 1459,  121,  122,  112, 1163, 1163, 1004, 1007,\n /*   230 */   997,  997,  119,  119,  120,  120,  120,  120,  390,  442,\n /*   240 */   314,   83,  461,   81,  357,  380, 1140,   80,  118,  118,\n /*   250 */   118,  118,  117,  117,  116,  116,  116,  115,  422,  179,\n /*   260 */   432,  422,  121,  122,  112, 1163, 1163, 1004, 1007,  997,\n /*   270 */   997,  119,  119,  120,  120,  120,  120,  432,  431,  266,\n /*   280 */   266,  118,  118,  118,  118,  117,  117,  116,  116,  116,\n /*   290 */   115,  422,  541, 1107,  901,  504, 1140,  114,  111,  211,\n /*   300 */  1429, 1140, 1141, 1142,  206,  489, 1107,  390,  447, 1107,\n /*   310 */   543,  328,  120,  120,  120,  120,  298, 1429, 1431,   17,\n /*   320 */   118,  118,  118,  118,  117,  117,  116,  116,  116,  115,\n /*   330 */   422,  121,  122,  112, 1163, 1163, 1004, 1007,  997,  997,\n /*   340 */   119,  119,  120,  120,  120,  120,  390, 1356,  432, 1140,\n /*   350 */   480, 1140, 1141, 1142,  994,  994, 1005, 1008,  443,  118,\n /*   360 */   118,  118,  118,  117,  117,  116,  116,  116,  115,  422,\n /*   370 */   121,  122,  112, 1163, 1163, 1004, 1007,  997,  997,  119,\n /*   380 */   119,  120,  120,  120,  120, 1052, 1052,  463, 1429,  118,\n /*   390 */   118,  118,  118,  117,  117,  116,  116,  116,  115,  422,\n /*   400 */  1140,  449,  544, 1424, 1140, 1141, 1142,  233,  964, 1140,\n /*   410 */   479,  476,  475,  171,  358,  390,  164,  405,  412,  840,\n /*   420 */   474,  164,  185,  332,   71,   71, 1241,  998,  118,  118,\n /*   430 */   118,  118,  117,  117,  116,  116,  116,  115,  422,  121,\n /*   440 */   122,  112, 1163, 1163, 1004, 1007,  997,  997,  119,  119,\n /*   450 */   120,  120,  120,  120,  390, 1140, 1141, 1142,  833,   12,\n /*   460 */   313,  507,  163,  354, 1140, 1141, 1142,  114,  111,  211,\n /*   470 */   506,  290,  535,  544,  276,  180,  290,  535,  121,  122,\n /*   480 */   112, 1163, 1163, 1004, 1007,  997,  997,  119,  119,  120,\n /*   490 */   120,  120,  120,  343,  482,   71,   71,  118,  118,  118,\n /*   500 */   118,  117,  117,  116,  116,  116,  115,  422, 1140,  209,\n /*   510 */   409,  521, 1140, 1107, 1569,  376,  252,  269,  340,  485,\n /*   520 */   335,  484,  238,  390,  511,  362, 1107, 1125,  331, 1107,\n /*   530 */   191,  407,  286,   32,  455,  441,  118,  118,  118,  118,\n /*   540 */   117,  117,  116,  116,  116,  115,  422,  121,  122,  112,\n /*   550 */  1163, 1163, 1004, 1007,  997,  997,  119,  119,  120,  120,\n /*   560 */   120,  120,  390, 1140, 1141, 1142,  985, 1140, 1141, 1142,\n /*   570 */  1140,  233,  490, 1490,  479,  476,  475,    6,  163,  544,\n /*   580 */   510,  544,  115,  422,  474,    5,  121,  122,  112, 1163,\n /*   590 */  1163, 1004, 1007,  997,  997,  119,  119,  120,  120,  120,\n /*   600 */   120,   13,   13,   13,   13,  118,  118,  118,  118,  117,\n /*   610 */   117,  116,  116,  116,  115,  422,  401,  500,  406,  544,\n /*   620 */  1484,  542, 1140,  890,  890, 1140, 1141, 1142, 1471, 1140,\n /*   630 */   275,  390,  806,  807,  808,  969,  420,  420,  420,   16,\n /*   640 */    16,   55,   55, 1240,  118,  118,  118,  118,  117,  117,\n /*   650 */   116,  116,  116,  115,  422,  121,  122,  112, 1163, 1163,\n /*   660 */  1004, 1007,  997,  997,  119,  119,  120,  120,  120,  120,\n /*   670 */   390, 1187,    1,    1,  550,    2, 1191, 1140, 1141, 1142,\n /*   680 */   194,  291,  896,  136, 1140, 1141, 1142,  895,  519, 1490,\n /*   690 */  1271,    3,  378,    6,  121,  122,  112, 1163, 1163, 1004,\n /*   700 */  1007,  997,  997,  119,  119,  120,  120,  120,  120,  856,\n /*   710 */   544,  922,  544,  118,  118,  118,  118,  117,  117,  116,\n /*   720 */   116,  116,  115,  422,  266,  266, 1090, 1567, 1140,  549,\n /*   730 */  1567, 1191,   13,   13,   13,   13,  291,  541,  136,  390,\n /*   740 */   483,  419,  418,  964,  342, 1271,  466,  408,  857,  279,\n /*   750 */   140,  221,  118,  118,  118,  118,  117,  117,  116,  116,\n /*   760 */   116,  115,  422,  121,  122,  112, 1163, 1163, 1004, 1007,\n /*   770 */   997,  997,  119,  119,  120,  120,  120,  120,  544,  266,\n /*   780 */   266,  426,  390, 1140, 1141, 1142, 1170,  828, 1170,  466,\n /*   790 */   429,  145,  541, 1144,  399,  313,  437,  301,  836, 1488,\n /*   800 */    71,   71,  410,    6, 1088,  471,  221,  100,  112, 1163,\n /*   810 */  1163, 1004, 1007,  997,  997,  119,  119,  120,  120,  120,\n /*   820 */   120,  118,  118,  118,  118,  117,  117,  116,  116,  116,\n /*   830 */   115,  422,  237, 1423,  544,  449,  426,  287,  984,  544,\n /*   840 */   236,  235,  234,  828,   97,  527,  427, 1263, 1263, 1144,\n /*   850 */   492,  306,  428,  836,  975,  544,   71,   71,  974, 1239,\n /*   860 */   544,   51,   51,  300,  118,  118,  118,  118,  117,  117,\n /*   870 */   116,  116,  116,  115,  422,  194,  103,   70,   70,  266,\n /*   880 */   266,  544,   71,   71,  266,  266,   30,  389,  342,  974,\n /*   890 */   974,  976,  541,  526, 1107,  326,  390,  541,  493,  395,\n /*   900 */  1468,  195,  528,   13,   13, 1356,  240, 1107,  277,  280,\n /*   910 */  1107,  280,  303,  455,  305,  331,  390,   31,  188,  417,\n /*   920 */   121,  122,  112, 1163, 1163, 1004, 1007,  997,  997,  119,\n /*   930 */   119,  120,  120,  120,  120,  142,  390,  363,  455,  984,\n /*   940 */   121,  122,  112, 1163, 1163, 1004, 1007,  997,  997,  119,\n /*   950 */   119,  120,  120,  120,  120,  975,  321, 1140,  324,  974,\n /*   960 */   121,  110,  112, 1163, 1163, 1004, 1007,  997,  997,  119,\n /*   970 */   119,  120,  120,  120,  120,  462,  375, 1183,  118,  118,\n /*   980 */   118,  118,  117,  117,  116,  116,  116,  115,  422, 1140,\n /*   990 */   974,  974,  976,  304,    9,  364,  244,  360,  118,  118,\n /*  1000 */   118,  118,  117,  117,  116,  116,  116,  115,  422,  312,\n /*  1010 */   544,  342, 1140, 1141, 1142,  299,  290,  535,  118,  118,\n /*  1020 */   118,  118,  117,  117,  116,  116,  116,  115,  422, 1261,\n /*  1030 */  1261, 1161,   13,   13,  278,  419,  418,  466,  390,  921,\n /*  1040 */   260,  260,  289, 1167, 1140, 1141, 1142,  189, 1169,  266,\n /*  1050 */   266,  466,  388,  541, 1184,  544, 1168,  263,  144,  487,\n /*  1060 */   920,  544,  541,  122,  112, 1163, 1163, 1004, 1007,  997,\n /*  1070 */   997,  119,  119,  120,  120,  120,  120,   71,   71, 1140,\n /*  1080 */  1170, 1270, 1170,   13,   13,  896, 1068, 1161,  544,  466,\n /*  1090 */   895,  107,  536, 1489,    4, 1266, 1107,    6,  523, 1047,\n /*  1100 */    12, 1069, 1090, 1568,  311,  453, 1568,  518,  539, 1107,\n /*  1110 */    56,   56, 1107, 1487,  421, 1356, 1070,    6,  343,  285,\n /*  1120 */   118,  118,  118,  118,  117,  117,  116,  116,  116,  115,\n /*  1130 */   422,  423, 1269,  319, 1140, 1141, 1142,  876,  266,  266,\n /*  1140 */  1275,  107,  536,  533,    4, 1486,  293,  877, 1209,    6,\n /*  1150 */   210,  541,  541,  164, 1540,  494,  414,  865,  539,  267,\n /*  1160 */   267, 1212,  396,  509,  497,  204,  266,  266,  394,  529,\n /*  1170 */     8,  984,  541,  517,  544,  920,  456,  105,  105,  541,\n /*  1180 */  1088,  423,  266,  266,  106,  415,  423,  546,  545,  266,\n /*  1190 */   266,  974,  516,  533, 1371,  541,   15,   15,  266,  266,\n /*  1200 */   454, 1118,  541,  266,  266, 1068, 1370,  513,  290,  535,\n /*  1210 */   544,  541,  512,   97,  442,  314,  541,  544,  920,  125,\n /*  1220 */  1069,  984,  974,  974,  976,  977,   27,  105,  105,  399,\n /*  1230 */   341, 1509,   44,   44,  106, 1070,  423,  546,  545,   57,\n /*  1240 */    57,  974,  341, 1509,  107,  536,  544,    4,  460,  399,\n /*  1250 */   214, 1118,  457,  294,  375, 1089,  532,  297,  544,  537,\n /*  1260 */   396,  539,  290,  535,  104,  244,  102,  524,   58,   58,\n /*  1270 */   544,  109,  974,  974,  976,  977,   27, 1514, 1129,  425,\n /*  1280 */    59,   59,  270,  237,  423,  138,   95,  373,  373,  372,\n /*  1290 */   255,  370,   60,   60,  815, 1178,  533,  544,  273,  544,\n /*  1300 */  1161,  843,  387,  386,  544, 1307,  544,  215,  210,  296,\n /*  1310 */   513,  847,  544,  265,  208,  514, 1306,  295,  274,   61,\n /*  1320 */    61,   62,   62,  436,  984, 1160,   45,   45,   46,   46,\n /*  1330 */   105,  105, 1184,  920,   47,   47, 1474,  106,  544,  423,\n /*  1340 */   546,  545,  218,  544,  974,  935, 1085,  217,  544,  377,\n /*  1350 */   395,  107,  536,  936,    4,  156, 1161,  843,  158,  544,\n /*  1360 */    49,   49,  141,  544,   38,   50,   50,  544,  539,  307,\n /*  1370 */    63,   63,  544, 1448,  216,  974,  974,  976,  977,   27,\n /*  1380 */   444,   64,   64,  544, 1447,   65,   65,  544,  524,   14,\n /*  1390 */    14,  423,  458,  544,   66,   66,  310,  544,  316,   97,\n /*  1400 */  1034,  544,  961,  533,  268,  127,  127,  544,  391,   67,\n /*  1410 */    67,  544,  978,  290,  535,   52,   52,  513,  544,   68,\n /*  1420 */    68, 1294,  512,   69,   69,  397,  165,  855,  854,   53,\n /*  1430 */    53,  984,  966,  151,  151,  243,  430,  105,  105,  199,\n /*  1440 */   152,  152,  448, 1303,  106,  243,  423,  546,  545, 1129,\n /*  1450 */   425,  974,  320,  270,  862,  863, 1034,  220,  373,  373,\n /*  1460 */   372,  255,  370,  450,  323,  815,  243,  544,  978,  544,\n /*  1470 */   107,  536,  544,    4,  544,  938,  939,  325,  215, 1046,\n /*  1480 */   296, 1046,  974,  974,  976,  977,   27,  539,  295,   76,\n /*  1490 */    76,   54,   54,  327,   72,   72,  128,  128, 1503, 1254,\n /*  1500 */   107,  536,  544,    4, 1045,  544, 1045,  531, 1238,  544,\n /*  1510 */   423,  544,  315,  334,  544,   97,  544,  539,  217,  544,\n /*  1520 */   472, 1528,  533,  239,   73,   73,  156,  129,  129,  158,\n /*  1530 */   467,  130,  130,  126,  126,  344,  150,  150,  149,  149,\n /*  1540 */   423,  134,  134,  329, 1030,  216,   97,  239,  929,  345,\n /*  1550 */   984,  243,  533, 1315,  339,  544,  105,  105,  900, 1355,\n /*  1560 */   544, 1290,  258,  106,  338,  423,  546,  545,  544, 1301,\n /*  1570 */   974,  893,   99,  536,  109,    4,  544,  133,  133,  391,\n /*  1580 */   984,  197,  131,  131,  290,  535,  105,  105,  530,  539,\n /*  1590 */   132,  132, 1361,  106, 1219,  423,  546,  545,   75,   75,\n /*  1600 */   974,  974,  974,  976,  977,   27,  544,  430,  826, 1211,\n /*  1610 */   894,  139,  423,  109,  544, 1200, 1199, 1201, 1522,  544,\n /*  1620 */   201,  544,   11,  374,  533, 1287,  347,  349,   77,   77,\n /*  1630 */  1340,  974,  974,  976,  977,   27,   74,   74,  351,  213,\n /*  1640 */   435,   43,   43,   48,   48,  302,  477,  309, 1348,  382,\n /*  1650 */   353,  452,  984,  337, 1237, 1420, 1419,  205,  105,  105,\n /*  1660 */   192,  367,  193,  534, 1525,  106, 1178,  423,  546,  545,\n /*  1670 */   247,  167,  974,  270, 1467,  200, 1465, 1175,  373,  373,\n /*  1680 */   372,  255,  370,  398,   79,  815,   83,   82, 1425,  446,\n /*  1690 */   161,  177,  169,   95, 1337,  438,  172,  173,  215,  174,\n /*  1700 */   296,  175,   35,  974,  974,  976,  977,   27,  295, 1345,\n /*  1710 */   439,  470,  223,   36,  379,  445, 1414,  381,  459, 1351,\n /*  1720 */   181,  227,   88,  465,  259,  229, 1436,  318,  186,  468,\n /*  1730 */   322,  230,  384, 1202,  231,  486, 1257, 1256,  217,  411,\n /*  1740 */  1255, 1248,   90,  847,  206,  413,  156,  505, 1539,  158,\n /*  1750 */  1226, 1538,  283, 1508, 1227,  336,  385,  284, 1225,  496,\n /*  1760 */  1537, 1298,   94,  346,  348,  216, 1247,  499, 1299,  245,\n /*  1770 */   246, 1297,  416,  350, 1494,  124, 1493,   10,  524,  361,\n /*  1780 */  1400,  101,   96,  288,  508,  253, 1135, 1208,   34, 1296,\n /*  1790 */   547,  254,  256,  257,  392,  548, 1197, 1192,  359,  391,\n /*  1800 */  1280, 1279,  196,  365,  290,  535,  366,  352, 1452, 1322,\n /*  1810 */  1321, 1453,  153,  137,  281,  154,  802,  424,  155, 1451,\n /*  1820 */  1450,  198,  292,  202,  203,   78,  212,  430,  271,  135,\n /*  1830 */  1044, 1042,  958,  168,  219,  157,  170,  879,  308,  222,\n /*  1840 */  1058,  176,  159,  962,  400,   84,  402,  178,   85,   86,\n /*  1850 */    87,  166,  160,  393, 1061,  224,  225, 1057,  146,   18,\n /*  1860 */   226,  317, 1050, 1172,  243,  464,  182,  228,   37,  183,\n /*  1870 */   817,  469,  338,  232,  330,  481,  184,   89,  845,   19,\n /*  1880 */    20,   92,  473,  478,  333,   91,  162,  858,  147,  488,\n /*  1890 */   282, 1123,  148, 1010,  928, 1093,   39,   93,   40,  495,\n /*  1900 */  1094,  187,  498,  207,  262,  264,  923,  242, 1109,  109,\n /*  1910 */  1113, 1111, 1097,   33,   21, 1117,  520, 1025,   22,   23,\n /*  1920 */    24, 1116,   25,  190,   97, 1011, 1009,   26, 1013, 1067,\n /*  1930 */   248,    7, 1066,  249, 1014,   28,   41,  889,  979,  827,\n /*  1940 */   108,   29,  250,  540,  251, 1530,  371,  368, 1131, 1130,\n /*  1950 */  1188, 1188, 1188, 1188, 1188, 1188, 1188, 1529,\n};\nstatic const YYCODETYPE yy_lookahead[] = {\n /*     0 */   189,  211,  189,  189,  218,  189,  220,  189,  267,  268,\n /*    10 */   269,  189,  210,  189,  228,  189,  267,  268,  269,   19,\n /*    20 */   218,  189,  211,  212,  211,  212,  211,  211,  212,  211,\n /*    30 */   212,   31,  211,  211,  212,  211,  212,  288,  300,   39,\n /*    40 */    21,  189,  304,   43,   44,   45,   46,   47,   48,   49,\n /*    50 */    50,   51,   52,   53,   54,   55,   56,   57,  225,   19,\n /*    60 */   189,  183,  184,  185,  186,  189,  248,  263,  236,  191,\n /*    70 */   248,  193,  248,  197,  208,  257,  262,  201,  200,  257,\n /*    80 */   200,  257,   81,   43,   44,   45,   46,   47,   48,   49,\n /*    90 */    50,   51,   52,   53,   54,   55,   56,   57,  189,   80,\n /*   100 */   189,  101,  102,  103,  104,  105,  106,  107,  108,  109,\n /*   110 */   110,  111,  234,  235,  234,  235,  305,  306,  305,  118,\n /*   120 */   307,  305,  306,  297,  298,  247,   86,  247,   88,   19,\n /*   130 */   259,  251,  252,  267,  268,  269,   26,  136,  137,  261,\n /*   140 */   121,  101,  102,  103,  104,  105,  106,  107,  108,  109,\n /*   150 */   110,  111,   59,   43,   44,   45,   46,   47,   48,   49,\n /*   160 */    50,   51,   52,   53,   54,   55,   56,   57,  259,  291,\n /*   170 */   105,  106,  107,  108,  109,  110,  111,  158,  189,   69,\n /*   180 */   101,  102,  103,  104,  105,  106,  107,  108,  109,  110,\n /*   190 */   111,  107,  108,  109,  110,  111,  205,  206,  207,   19,\n /*   200 */    19,   54,   55,   56,   57,   58,   29,  114,  115,  116,\n /*   210 */    33,  101,  102,  103,  104,  105,  106,  107,  108,  109,\n /*   220 */   110,  111,  233,   43,   44,   45,   46,   47,   48,   49,\n /*   230 */    50,   51,   52,   53,   54,   55,   56,   57,   19,  126,\n /*   240 */   127,  148,   65,   24,  214,  200,   59,   67,  101,  102,\n /*   250 */   103,  104,  105,  106,  107,  108,  109,  110,  111,   22,\n /*   260 */   189,  111,   43,   44,   45,   46,   47,   48,   49,   50,\n /*   270 */    51,   52,   53,   54,   55,   56,   57,  206,  207,  234,\n /*   280 */   235,  101,  102,  103,  104,  105,  106,  107,  108,  109,\n /*   290 */   110,  111,  247,   76,  107,  114,   59,  267,  268,  269,\n /*   300 */   189,  114,  115,  116,  162,  163,   89,   19,  263,   92,\n /*   310 */   189,   23,   54,   55,   56,   57,  189,  206,  207,   22,\n /*   320 */   101,  102,  103,  104,  105,  106,  107,  108,  109,  110,\n /*   330 */   111,   43,   44,   45,   46,   47,   48,   49,   50,   51,\n /*   340 */    52,   53,   54,   55,   56,   57,   19,  189,  277,   59,\n /*   350 */    23,  114,  115,  116,   46,   47,   48,   49,   61,  101,\n /*   360 */   102,  103,  104,  105,  106,  107,  108,  109,  110,  111,\n /*   370 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,\n /*   380 */    53,   54,   55,   56,   57,  125,  126,  127,  277,  101,\n /*   390 */   102,  103,  104,  105,  106,  107,  108,  109,  110,  111,\n /*   400 */    59,  189,  189,  276,  114,  115,  116,  117,   73,   59,\n /*   410 */   120,  121,  122,   72,  214,   19,   81,  259,   19,   23,\n /*   420 */   130,   81,   72,   24,  211,  212,  221,  119,  101,  102,\n /*   430 */   103,  104,  105,  106,  107,  108,  109,  110,  111,   43,\n /*   440 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,\n /*   450 */    54,   55,   56,   57,   19,  114,  115,  116,   23,  208,\n /*   460 */   125,  248,  189,  189,  114,  115,  116,  267,  268,  269,\n /*   470 */   189,  136,  137,  189,  262,   22,  136,  137,   43,   44,\n /*   480 */    45,   46,   47,   48,   49,   50,   51,   52,   53,   54,\n /*   490 */    55,   56,   57,  189,   95,  211,  212,  101,  102,  103,\n /*   500 */   104,  105,  106,  107,  108,  109,  110,  111,   59,  189,\n /*   510 */   111,  189,   59,   76,  294,  295,  117,  118,  119,  120,\n /*   520 */   121,  122,  123,   19,   87,  189,   89,   23,  129,   92,\n /*   530 */   279,  227,  248,   22,  189,  284,  101,  102,  103,  104,\n /*   540 */   105,  106,  107,  108,  109,  110,  111,   43,   44,   45,\n /*   550 */    46,   47,   48,   49,   50,   51,   52,   53,   54,   55,\n /*   560 */    56,   57,   19,  114,  115,  116,   23,  114,  115,  116,\n /*   570 */    59,  117,  299,  300,  120,  121,  122,  304,  189,  189,\n /*   580 */   143,  189,  110,  111,  130,   22,   43,   44,   45,   46,\n /*   590 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,\n /*   600 */    57,  211,  212,  211,  212,  101,  102,  103,  104,  105,\n /*   610 */   106,  107,  108,  109,  110,  111,  226,  189,  226,  189,\n /*   620 */   298,  132,   59,  134,  135,  114,  115,  116,  189,   59,\n /*   630 */   285,   19,    7,    8,    9,   23,  205,  206,  207,  211,\n /*   640 */   212,  211,  212,  221,  101,  102,  103,  104,  105,  106,\n /*   650 */   107,  108,  109,  110,  111,   43,   44,   45,   46,   47,\n /*   660 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,\n /*   670 */    19,  181,  182,  183,  184,  185,  186,  114,  115,  116,\n /*   680 */   189,  191,  133,  193,  114,  115,  116,  138,  299,  300,\n /*   690 */   200,   22,  201,  304,   43,   44,   45,   46,   47,   48,\n /*   700 */    49,   50,   51,   52,   53,   54,   55,   56,   57,   35,\n /*   710 */   189,  141,  189,  101,  102,  103,  104,  105,  106,  107,\n /*   720 */   108,  109,  110,  111,  234,  235,   22,   23,   59,  184,\n /*   730 */    26,  186,  211,  212,  211,  212,  191,  247,  193,   19,\n /*   740 */    66,  105,  106,   73,  189,  200,  189,  226,   74,  226,\n /*   750 */    22,  261,  101,  102,  103,  104,  105,  106,  107,  108,\n /*   760 */   109,  110,  111,   43,   44,   45,   46,   47,   48,   49,\n /*   770 */    50,   51,   52,   53,   54,   55,   56,   57,  189,  234,\n /*   780 */   235,  291,   19,  114,  115,  116,  150,   59,  152,  189,\n /*   790 */   233,  236,  247,   59,  189,  125,  126,  127,   59,  300,\n /*   800 */   211,  212,  128,  304,  100,   19,  261,  156,   45,   46,\n /*   810 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,\n /*   820 */    57,  101,  102,  103,  104,  105,  106,  107,  108,  109,\n /*   830 */   110,  111,   46,  233,  189,  189,  291,  248,   99,  189,\n /*   840 */   125,  126,  127,  115,   26,  200,  289,  230,  231,  115,\n /*   850 */   200,   16,  189,  114,  115,  189,  211,  212,  119,  221,\n /*   860 */   189,  211,  212,  258,  101,  102,  103,  104,  105,  106,\n /*   870 */   107,  108,  109,  110,  111,  189,  156,  211,  212,  234,\n /*   880 */   235,  189,  211,  212,  234,  235,   22,  201,  189,  150,\n /*   890 */   151,  152,  247,  248,   76,   16,   19,  247,  248,  113,\n /*   900 */   189,   24,  257,  211,  212,  189,   26,   89,  262,  223,\n /*   910 */    92,  225,   77,  189,   79,  129,   19,   53,  226,  248,\n /*   920 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,\n /*   930 */    53,   54,   55,   56,   57,  236,   19,  271,  189,   99,\n /*   940 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,\n /*   950 */    53,   54,   55,   56,   57,  115,   77,   59,   79,  119,\n /*   960 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,\n /*   970 */    53,   54,   55,   56,   57,  259,   22,   23,  101,  102,\n /*   980 */   103,  104,  105,  106,  107,  108,  109,  110,  111,   59,\n /*   990 */   150,  151,  152,  158,   22,  244,   24,  246,  101,  102,\n /*  1000 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  285,\n /*  1010 */   189,  189,  114,  115,  116,  200,  136,  137,  101,  102,\n /*  1020 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  230,\n /*  1030 */   231,   59,  211,  212,  285,  105,  106,  189,   19,  141,\n /*  1040 */   234,  235,  239,  113,  114,  115,  116,  226,  118,  234,\n /*  1050 */   235,  189,  249,  247,  100,  189,  126,   23,  236,  107,\n /*  1060 */    26,  189,  247,   44,   45,   46,   47,   48,   49,   50,\n /*  1070 */    51,   52,   53,   54,   55,   56,   57,  211,  212,   59,\n /*  1080 */   150,  233,  152,  211,  212,  133,   12,  115,  189,  189,\n /*  1090 */   138,   19,   20,  300,   22,  233,   76,  304,  226,   11,\n /*  1100 */   208,   27,   22,   23,  200,   19,   26,   87,   36,   89,\n /*  1110 */   211,  212,   92,  300,  248,  189,   42,  304,  189,  250,\n /*  1120 */   101,  102,  103,  104,  105,  106,  107,  108,  109,  110,\n /*  1130 */   111,   59,  200,  233,  114,  115,  116,   63,  234,  235,\n /*  1140 */   235,   19,   20,   71,   22,  300,  189,   73,  200,  304,\n /*  1150 */   116,  247,  247,   81,   23,  200,  227,   26,   36,  234,\n /*  1160 */   235,  203,  204,  143,  200,   26,  234,  235,  194,  200,\n /*  1170 */    48,   99,  247,   66,  189,  141,  284,  105,  106,  247,\n /*  1180 */   100,   59,  234,  235,  112,  259,  114,  115,  116,  234,\n /*  1190 */   235,  119,   85,   71,  266,  247,  211,  212,  234,  235,\n /*  1200 */   114,   94,  247,  234,  235,   12,  266,   85,  136,  137,\n /*  1210 */   189,  247,   90,   26,  126,  127,  247,  189,   26,   22,\n /*  1220 */    27,   99,  150,  151,  152,  153,  154,  105,  106,  189,\n /*  1230 */   302,  303,  211,  212,  112,   42,  114,  115,  116,  211,\n /*  1240 */   212,  119,  302,  303,   19,   20,  189,   22,  274,  189,\n /*  1250 */    15,  144,  278,  189,   22,   23,   63,  189,  189,  203,\n /*  1260 */   204,   36,  136,  137,  155,   24,  157,  143,  211,  212,\n /*  1270 */   189,   26,  150,  151,  152,  153,  154,    0,    1,    2,\n /*  1280 */   211,  212,    5,   46,   59,  161,  147,   10,   11,   12,\n /*  1290 */    13,   14,  211,  212,   17,   60,   71,  189,  258,  189,\n /*  1300 */    59,   59,  105,  106,  189,  189,  189,   30,  116,   32,\n /*  1310 */    85,  124,  189,  251,  252,   90,  189,   40,  258,  211,\n /*  1320 */   212,  211,  212,  189,   99,   26,  211,  212,  211,  212,\n /*  1330 */   105,  106,  100,  141,  211,  212,  189,  112,  189,  114,\n /*  1340 */   115,  116,   24,  189,  119,   31,   23,   70,  189,   26,\n /*  1350 */   113,   19,   20,   39,   22,   78,  115,  115,   81,  189,\n /*  1360 */   211,  212,   22,  189,   24,  211,  212,  189,   36,  189,\n /*  1370 */   211,  212,  189,  189,   97,  150,  151,  152,  153,  154,\n /*  1380 */   127,  211,  212,  189,  189,  211,  212,  189,  143,  211,\n /*  1390 */   212,   59,  189,  189,  211,  212,   23,  189,  189,   26,\n /*  1400 */    59,  189,  149,   71,   22,  211,  212,  189,  131,  211,\n /*  1410 */   212,  189,   59,  136,  137,  211,  212,   85,  189,  211,\n /*  1420 */   212,  253,   90,  211,  212,  292,  293,  118,  119,  211,\n /*  1430 */   212,   99,   23,  211,  212,   26,  159,  105,  106,  140,\n /*  1440 */   211,  212,   23,  189,  112,   26,  114,  115,  116,    1,\n /*  1450 */     2,  119,  189,    5,    7,    8,  115,  139,   10,   11,\n /*  1460 */    12,   13,   14,   23,  189,   17,   26,  189,  115,  189,\n /*  1470 */    19,   20,  189,   22,  189,   83,   84,  189,   30,  150,\n /*  1480 */    32,  152,  150,  151,  152,  153,  154,   36,   40,  211,\n /*  1490 */   212,  211,  212,  189,  211,  212,  211,  212,  309,  189,\n /*  1500 */    19,   20,  189,   22,  150,  189,  152,  231,  189,  189,\n /*  1510 */    59,  189,   23,  189,  189,   26,  189,   36,   70,  189,\n /*  1520 */    23,  139,   71,   26,  211,  212,   78,  211,  212,   81,\n /*  1530 */   281,  211,  212,  211,  212,  189,  211,  212,  211,  212,\n /*  1540 */    59,  211,  212,   23,   23,   97,   26,   26,   23,  189,\n /*  1550 */    99,   26,   71,  189,  119,  189,  105,  106,  107,  189,\n /*  1560 */   189,  189,  280,  112,  129,  114,  115,  116,  189,  189,\n /*  1570 */   119,   23,   19,   20,   26,   22,  189,  211,  212,  131,\n /*  1580 */    99,  237,  211,  212,  136,  137,  105,  106,  189,   36,\n /*  1590 */   211,  212,  189,  112,  189,  114,  115,  116,  211,  212,\n /*  1600 */   119,  150,  151,  152,  153,  154,  189,  159,   23,  189,\n /*  1610 */    23,   26,   59,   26,  189,  189,  189,  189,  189,  189,\n /*  1620 */   209,  189,  238,  187,   71,  250,  250,  250,  211,  212,\n /*  1630 */   241,  150,  151,  152,  153,  154,  211,  212,  250,  290,\n /*  1640 */   254,  211,  212,  211,  212,  254,  215,  286,  241,  241,\n /*  1650 */   254,  286,   99,  214,  220,  214,  214,  224,  105,  106,\n /*  1660 */   244,  240,  244,  273,  192,  112,   60,  114,  115,  116,\n /*  1670 */   139,  290,  119,    5,  196,  238,  196,   38,   10,   11,\n /*  1680 */    12,   13,   14,  196,  287,   17,  148,  287,  276,  113,\n /*  1690 */    43,   22,  229,  147,  241,   18,  232,  232,   30,  232,\n /*  1700 */    32,  232,  264,  150,  151,  152,  153,  154,   40,  265,\n /*  1710 */   196,   18,  195,  264,  241,  241,  241,  265,  196,  229,\n /*  1720 */   229,  195,  155,   62,  196,  195,  283,  282,   22,  216,\n /*  1730 */   196,  195,  216,  196,  195,  113,  213,  213,   70,   64,\n /*  1740 */   213,  222,   22,  124,  162,  111,   78,  142,  219,   81,\n /*  1750 */   215,  219,  275,  303,  213,  213,  216,  275,  213,  216,\n /*  1760 */   213,  256,  113,  255,  255,   97,  222,  216,  256,  196,\n /*  1770 */    91,  256,   82,  255,  308,  146,  308,   22,  143,  196,\n /*  1780 */   270,  155,  145,  272,  144,   25,   13,  199,   26,  256,\n /*  1790 */   198,  190,  190,    6,  296,  188,  188,  188,  244,  131,\n /*  1800 */   245,  245,  243,  242,  136,  137,  241,  255,  208,  260,\n /*  1810 */   260,  208,  202,  217,  217,  202,    4,    3,  202,  208,\n /*  1820 */   208,   22,  160,  209,  209,  208,   15,  159,   98,   16,\n /*  1830 */    23,   23,  137,  148,   24,  128,  140,   20,   16,  142,\n /*  1840 */     1,  140,  128,  149,   61,   53,   37,  148,   53,   53,\n /*  1850 */    53,  293,  128,  296,  114,   34,  139,    1,    5,   22,\n /*  1860 */   113,  158,   68,   75,   26,   41,   68,  139,   24,  113,\n /*  1870 */    20,   19,  129,  123,   23,   96,   22,   22,   59,   22,\n /*  1880 */    22,  147,   67,   67,   24,   22,   37,   28,   23,   22,\n /*  1890 */    67,   23,   23,   23,  114,   23,   22,   26,   22,   24,\n /*  1900 */    23,   22,   24,  139,   23,   23,  141,   34,   88,   26,\n /*  1910 */    75,   86,   23,   22,   34,   75,   24,   23,   34,   34,\n /*  1920 */    34,   93,   34,   26,   26,   23,   23,   34,   23,   23,\n /*  1930 */    26,   44,   23,   22,   11,   22,   22,  133,   23,   23,\n /*  1940 */    22,   22,  139,   26,  139,  139,   15,   23,    1,    1,\n /*  1950 */   310,  310,  310,  310,  310,  310,  310,  139,  310,  310,\n /*  1960 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  1970 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  1980 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  1990 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  2000 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  2010 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  2020 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  2030 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  2040 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  2050 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  2060 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  2070 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  2080 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  2090 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  2100 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  2110 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  2120 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,\n /*  2130 */   310,  310,  310,  310,  310,  310,  310,  310,  310,\n};\n#define YY_SHIFT_COUNT    (550)\n#define YY_SHIFT_MIN      (0)\n#define YY_SHIFT_MAX      (1948)\nstatic const unsigned short int yy_shift_ofst[] = {\n /*     0 */  1448, 1277, 1668, 1072, 1072,  340, 1122, 1225, 1332, 1481,\n /*    10 */  1481, 1481,  335,    0,    0,  180,  897, 1481, 1481, 1481,\n /*    20 */  1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481,\n /*    30 */   930,  930, 1020, 1020,  290,    1,  340,  340,  340,  340,\n /*    40 */   340,  340,   40,  110,  219,  288,  327,  396,  435,  504,\n /*    50 */   543,  612,  651,  720,  877,  897,  897,  897,  897,  897,\n /*    60 */   897,  897,  897,  897,  897,  897,  897,  897,  897,  897,\n /*    70 */   897,  897,  897,  917,  897, 1019,  763,  763, 1451, 1481,\n /*    80 */  1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481,\n /*    90 */  1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481,\n /*   100 */  1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481,\n /*   110 */  1481, 1481, 1553, 1481, 1481, 1481, 1481, 1481, 1481, 1481,\n /*   120 */  1481, 1481, 1481, 1481, 1481, 1481,  147,  258,  258,  258,\n /*   130 */   258,  258,   79,   65,   84,  449,   19,  786,  449,  636,\n /*   140 */   636,  449,  880,  880,  880,  880,  113,  142,  142,  472,\n /*   150 */   150, 1958, 1958,  399,  399,  399,   93,  237,  341,  237,\n /*   160 */   237, 1074, 1074,  437,  350,  704, 1080,  449,  449,  449,\n /*   170 */   449,  449,  449,  449,  449,  449,  449,  449,  449,  449,\n /*   180 */   449,  449,  449,  449,  449,  449,  449,  449,  818,  818,\n /*   190 */   449, 1088,  217,  217,  734,  734, 1124, 1126, 1958, 1958,\n /*   200 */  1958,  739,  840,  840,  453,  454,  511,  187,  563,  570,\n /*   210 */   898,  669,  449,  449,  449,  449,  449,  449,  449,  449,\n /*   220 */   449,  670,  449,  449,  449,  449,  449,  449,  449,  449,\n /*   230 */   449,  449,  449,  449,  674,  674,  674,  449,  449,  449,\n /*   240 */   449, 1034,  449,  449,  449,  972, 1107,  449,  449, 1193,\n /*   250 */   449,  449,  449,  449,  449,  449,  449,  449,  260,  177,\n /*   260 */   489, 1241, 1241, 1241, 1241, 1192,  489,  489,  952, 1197,\n /*   270 */   625, 1235, 1139,  181,  181, 1086, 1139, 1139, 1086, 1187,\n /*   280 */  1131, 1237, 1314, 1314, 1314,  181, 1245, 1245, 1109, 1299,\n /*   290 */   549, 1340, 1606, 1531, 1531, 1639, 1639, 1531, 1538, 1576,\n /*   300 */  1669, 1647, 1546, 1677, 1677, 1677, 1677, 1531, 1693, 1546,\n /*   310 */  1546, 1576, 1669, 1647, 1647, 1546, 1531, 1693, 1567, 1661,\n /*   320 */  1531, 1693, 1706, 1531, 1693, 1531, 1693, 1706, 1622, 1622,\n /*   330 */  1622, 1675, 1720, 1720, 1706, 1622, 1619, 1622, 1675, 1622,\n /*   340 */  1622, 1582, 1706, 1634, 1634, 1706, 1605, 1649, 1605, 1649,\n /*   350 */  1605, 1649, 1605, 1649, 1531, 1679, 1679, 1690, 1690, 1629,\n /*   360 */  1635, 1755, 1531, 1626, 1629, 1637, 1640, 1546, 1760, 1762,\n /*   370 */  1773, 1773, 1787, 1787, 1787, 1958, 1958, 1958, 1958, 1958,\n /*   380 */  1958, 1958, 1958, 1958, 1958, 1958, 1958, 1958, 1958, 1958,\n /*   390 */   308,  835,  954, 1232,  879,  715,  728, 1323,  864, 1318,\n /*   400 */  1253, 1373,  297, 1409, 1419, 1440, 1489, 1497, 1520, 1242,\n /*   410 */  1309, 1447, 1435, 1341, 1521, 1525, 1392, 1548, 1329, 1354,\n /*   420 */  1585, 1587, 1353, 1382, 1812, 1814, 1799, 1662, 1811, 1730,\n /*   430 */  1813, 1807, 1808, 1695, 1685, 1707, 1810, 1696, 1817, 1697,\n /*   440 */  1822, 1839, 1701, 1694, 1714, 1783, 1809, 1699, 1792, 1795,\n /*   450 */  1796, 1797, 1724, 1740, 1821, 1717, 1856, 1853, 1837, 1747,\n /*   460 */  1703, 1794, 1838, 1798, 1788, 1824, 1728, 1756, 1844, 1850,\n /*   470 */  1852, 1743, 1750, 1854, 1815, 1855, 1857, 1851, 1858, 1816,\n /*   480 */  1819, 1860, 1779, 1859, 1863, 1823, 1849, 1865, 1734, 1867,\n /*   490 */  1868, 1869, 1870, 1871, 1872, 1874, 1875, 1877, 1876, 1878,\n /*   500 */  1764, 1881, 1882, 1780, 1873, 1879, 1765, 1883, 1880, 1884,\n /*   510 */  1885, 1886, 1820, 1835, 1825, 1887, 1840, 1828, 1888, 1889,\n /*   520 */  1891, 1892, 1897, 1898, 1893, 1894, 1883, 1902, 1903, 1905,\n /*   530 */  1906, 1904, 1909, 1911, 1923, 1913, 1914, 1915, 1916, 1918,\n /*   540 */  1919, 1917, 1804, 1803, 1805, 1806, 1818, 1924, 1931, 1947,\n /*   550 */  1948,\n};\n#define YY_REDUCE_COUNT (389)\n#define YY_REDUCE_MIN   (-262)\n#define YY_REDUCE_MAX   (1617)\nstatic const short yy_reduce_ofst[] = {\n /*     0 */   490, -122,  545,  645,  650, -120, -189, -187, -184, -182,\n /*    10 */  -178, -176,   45,   30,  200, -251, -134,  390,  392,  521,\n /*    20 */   523,  213,  692,  821,  284,  589,  872,  666,  671,  866,\n /*    30 */    71,  111,  273,  389,  686,  815,  904,  932,  948,  955,\n /*    40 */   964,  969, -259, -259, -259, -259, -259, -259, -259, -259,\n /*    50 */  -259, -259, -259, -259, -259, -259, -259, -259, -259, -259,\n /*    60 */  -259, -259, -259, -259, -259, -259, -259, -259, -259, -259,\n /*    70 */  -259, -259, -259, -259, -259, -259, -259, -259,  428,  430,\n /*    80 */   899,  985, 1021, 1028, 1057, 1069, 1081, 1108, 1110, 1115,\n /*    90 */  1117, 1123, 1149, 1154, 1159, 1170, 1174, 1178, 1183, 1194,\n /*   100 */  1198, 1204, 1208, 1212, 1218, 1222, 1229, 1278, 1280, 1283,\n /*   110 */  1285, 1313, 1316, 1320, 1322, 1325, 1327, 1330, 1366, 1371,\n /*   120 */  1379, 1387, 1417, 1425, 1430, 1432, -259, -259, -259, -259,\n /*   130 */  -259, -259, -259, -259, -259,  557,  974, -214, -174,   -9,\n /*   140 */   431, -124,  806,  925,  806,  925,  251,  928,  940, -259,\n /*   150 */  -259, -259, -259, -198, -198, -198,  127, -186, -168,  212,\n /*   160 */   646,  617,  799, -262,  555,  220,  220,  491,  605, 1040,\n /*   170 */  1060,  699,  -11,  600,  848,  862,  345, -129,  724,  -91,\n /*   180 */   158,  749,  716,  900,  304,  822,  929,  926,  499,  793,\n /*   190 */   322,  892,  813,  845,  958, 1056,  751,  905, 1133, 1062,\n /*   200 */   803, -210, -185, -179, -148, -167,  -89,  121,  274,  281,\n /*   210 */   320,  336,  439,  663,  711,  957, 1064, 1068, 1116, 1127,\n /*   220 */  1134, -196, 1147, 1180, 1184, 1195, 1203, 1209, 1254, 1263,\n /*   230 */  1275, 1288, 1304, 1310,  205,  422,  638, 1319, 1324, 1346,\n /*   240 */  1360, 1168, 1364, 1370, 1372,  869, 1189, 1380, 1399, 1276,\n /*   250 */  1403,  121, 1405, 1420, 1426, 1427, 1428, 1429, 1249, 1282,\n /*   260 */  1344, 1375, 1376, 1377, 1388, 1168, 1344, 1344, 1384, 1411,\n /*   270 */  1436, 1349, 1389, 1386, 1391, 1361, 1407, 1408, 1365, 1431,\n /*   280 */  1433, 1434, 1439, 1441, 1442, 1396, 1416, 1418, 1390, 1421,\n /*   290 */  1437, 1472, 1381, 1478, 1480, 1397, 1400, 1487, 1412, 1444,\n /*   300 */  1438, 1463, 1453, 1464, 1465, 1467, 1469, 1514, 1517, 1473,\n /*   310 */  1474, 1452, 1449, 1490, 1491, 1475, 1522, 1526, 1443, 1445,\n /*   320 */  1528, 1530, 1513, 1534, 1536, 1537, 1539, 1516, 1523, 1524,\n /*   330 */  1527, 1519, 1529, 1532, 1540, 1541, 1535, 1542, 1544, 1545,\n /*   340 */  1547, 1450, 1543, 1477, 1482, 1551, 1505, 1508, 1512, 1509,\n /*   350 */  1515, 1518, 1533, 1552, 1573, 1466, 1468, 1549, 1550, 1555,\n /*   360 */  1554, 1510, 1583, 1511, 1556, 1559, 1561, 1565, 1588, 1592,\n /*   370 */  1601, 1602, 1607, 1608, 1609, 1498, 1557, 1558, 1610, 1600,\n /*   380 */  1603, 1611, 1612, 1613, 1596, 1597, 1614, 1615, 1617, 1616,\n};\nstatic const YYACTIONTYPE yy_default[] = {\n /*     0 */  1573, 1573, 1573, 1409, 1186, 1295, 1186, 1186, 1186, 1409,\n /*    10 */  1409, 1409, 1186, 1325, 1325, 1462, 1217, 1186, 1186, 1186,\n /*    20 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1408, 1186, 1186,\n /*    30 */  1186, 1186, 1492, 1492, 1186, 1186, 1186, 1186, 1186, 1186,\n /*    40 */  1186, 1186, 1186, 1334, 1186, 1186, 1186, 1186, 1186, 1186,\n /*    50 */  1410, 1411, 1186, 1186, 1186, 1461, 1463, 1426, 1344, 1343,\n /*    60 */  1342, 1341, 1444, 1312, 1339, 1332, 1336, 1404, 1405, 1403,\n /*    70 */  1407, 1411, 1410, 1186, 1335, 1375, 1389, 1374, 1186, 1186,\n /*    80 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,\n /*    90 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,\n /*   100 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,\n /*   110 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,\n /*   120 */  1186, 1186, 1186, 1186, 1186, 1186, 1383, 1388, 1394, 1387,\n /*   130 */  1384, 1377, 1376, 1378, 1379, 1186, 1207, 1259, 1186, 1186,\n /*   140 */  1186, 1186, 1480, 1479, 1186, 1186, 1217, 1369, 1368, 1380,\n /*   150 */  1381, 1391, 1390, 1469, 1527, 1526, 1427, 1186, 1186, 1186,\n /*   160 */  1186, 1186, 1186, 1492, 1186, 1186, 1186, 1186, 1186, 1186,\n /*   170 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,\n /*   180 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1492, 1492,\n /*   190 */  1186, 1217, 1492, 1492, 1213, 1213, 1319, 1186, 1475, 1295,\n /*   200 */  1286, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,\n /*   210 */  1186, 1186, 1186, 1186, 1186, 1466, 1464, 1186, 1186, 1186,\n /*   220 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,\n /*   230 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,\n /*   240 */  1186, 1186, 1186, 1186, 1186, 1291, 1186, 1186, 1186, 1186,\n /*   250 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1521, 1186, 1439,\n /*   260 */  1273, 1291, 1291, 1291, 1291, 1293, 1274, 1272, 1285, 1218,\n /*   270 */  1193, 1565, 1338, 1314, 1314, 1562, 1338, 1338, 1562, 1234,\n /*   280 */  1543, 1229, 1325, 1325, 1325, 1314, 1319, 1319, 1406, 1292,\n /*   290 */  1285, 1186, 1565, 1300, 1300, 1564, 1564, 1300, 1427, 1347,\n /*   300 */  1353, 1262, 1338, 1268, 1268, 1268, 1268, 1300, 1204, 1338,\n /*   310 */  1338, 1347, 1353, 1262, 1262, 1338, 1300, 1204, 1443, 1559,\n /*   320 */  1300, 1204, 1417, 1300, 1204, 1300, 1204, 1417, 1260, 1260,\n /*   330 */  1260, 1249, 1186, 1186, 1417, 1260, 1234, 1260, 1249, 1260,\n /*   340 */  1260, 1510, 1417, 1421, 1421, 1417, 1318, 1313, 1318, 1313,\n /*   350 */  1318, 1313, 1318, 1313, 1300, 1502, 1502, 1328, 1328, 1333,\n /*   360 */  1319, 1412, 1300, 1186, 1333, 1331, 1329, 1338, 1210, 1252,\n /*   370 */  1524, 1524, 1520, 1520, 1520, 1570, 1570, 1475, 1536, 1217,\n /*   380 */  1217, 1217, 1217, 1536, 1236, 1236, 1218, 1218, 1217, 1536,\n /*   390 */  1186, 1186, 1186, 1186, 1186, 1186, 1531, 1186, 1428, 1304,\n /*   400 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,\n /*   410 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,\n /*   420 */  1186, 1186, 1186, 1358, 1186, 1189, 1472, 1186, 1186, 1470,\n /*   430 */  1186, 1186, 1186, 1186, 1186, 1186, 1305, 1186, 1186, 1186,\n /*   440 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,\n /*   450 */  1186, 1186, 1186, 1186, 1186, 1561, 1186, 1186, 1186, 1186,\n /*   460 */  1186, 1186, 1442, 1441, 1186, 1186, 1302, 1186, 1186, 1186,\n /*   470 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,\n /*   480 */  1232, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,\n /*   490 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,\n /*   500 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1330, 1186, 1186,\n /*   510 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,\n /*   520 */  1186, 1186, 1507, 1320, 1186, 1186, 1552, 1186, 1186, 1186,\n /*   530 */  1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,\n /*   540 */  1186, 1547, 1276, 1360, 1186, 1359, 1363, 1186, 1198, 1186,\n /*   550 */  1186,\n};\n/********** End of lemon-generated parsing tables *****************************/\n\n/* The next table maps tokens (terminal symbols) into fallback tokens.  \n** If a construct like the following:\n** \n**      %fallback ID X Y Z.\n**\n** appears in the grammar, then ID becomes a fallback token for X, Y,\n** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser\n** but it does not parse, the type of the token is changed to ID and\n** the parse is retried before an error is thrown.\n**\n** This feature can be used, for example, to cause some keywords in a language\n** to revert to identifiers if they keyword does not apply in the context where\n** it appears.\n*/\n#ifdef YYFALLBACK\nstatic const YYCODETYPE yyFallback[] = {\n    0,  /*          $ => nothing */\n    0,  /*       SEMI => nothing */\n   59,  /*    EXPLAIN => ID */\n   59,  /*      QUERY => ID */\n   59,  /*       PLAN => ID */\n   59,  /*      BEGIN => ID */\n    0,  /* TRANSACTION => nothing */\n   59,  /*   DEFERRED => ID */\n   59,  /*  IMMEDIATE => ID */\n   59,  /*  EXCLUSIVE => ID */\n    0,  /*     COMMIT => nothing */\n   59,  /*        END => ID */\n   59,  /*   ROLLBACK => ID */\n   59,  /*  SAVEPOINT => ID */\n   59,  /*    RELEASE => ID */\n    0,  /*         TO => nothing */\n    0,  /*      TABLE => nothing */\n    0,  /*     CREATE => nothing */\n   59,  /*         IF => ID */\n    0,  /*        NOT => nothing */\n    0,  /*     EXISTS => nothing */\n   59,  /*       TEMP => ID */\n    0,  /*         LP => nothing */\n    0,  /*         RP => nothing */\n    0,  /*         AS => nothing */\n   59,  /*    WITHOUT => ID */\n    0,  /*      COMMA => nothing */\n   59,  /*      ABORT => ID */\n   59,  /*     ACTION => ID */\n   59,  /*      AFTER => ID */\n   59,  /*    ANALYZE => ID */\n   59,  /*        ASC => ID */\n   59,  /*     ATTACH => ID */\n   59,  /*     BEFORE => ID */\n   59,  /*         BY => ID */\n   59,  /*    CASCADE => ID */\n   59,  /*       CAST => ID */\n   59,  /*   CONFLICT => ID */\n   59,  /*   DATABASE => ID */\n   59,  /*       DESC => ID */\n   59,  /*     DETACH => ID */\n   59,  /*       EACH => ID */\n   59,  /*       FAIL => ID */\n    0,  /*         OR => nothing */\n    0,  /*        AND => nothing */\n    0,  /*         IS => nothing */\n   59,  /*      MATCH => ID */\n   59,  /*    LIKE_KW => ID */\n    0,  /*    BETWEEN => nothing */\n    0,  /*         IN => nothing */\n    0,  /*     ISNULL => nothing */\n    0,  /*    NOTNULL => nothing */\n    0,  /*         NE => nothing */\n    0,  /*         EQ => nothing */\n    0,  /*         GT => nothing */\n    0,  /*         LE => nothing */\n    0,  /*         LT => nothing */\n    0,  /*         GE => nothing */\n    0,  /*     ESCAPE => nothing */\n    0,  /*         ID => nothing */\n   59,  /*   COLUMNKW => ID */\n   59,  /*         DO => ID */\n   59,  /*        FOR => ID */\n   59,  /*     IGNORE => ID */\n   59,  /*  INITIALLY => ID */\n   59,  /*    INSTEAD => ID */\n   59,  /*         NO => ID */\n   59,  /*        KEY => ID */\n   59,  /*         OF => ID */\n   59,  /*     OFFSET => ID */\n   59,  /*     PRAGMA => ID */\n   59,  /*      RAISE => ID */\n   59,  /*  RECURSIVE => ID */\n   59,  /*    REPLACE => ID */\n   59,  /*   RESTRICT => ID */\n   59,  /*        ROW => ID */\n   59,  /*       ROWS => ID */\n   59,  /*    TRIGGER => ID */\n   59,  /*     VACUUM => ID */\n   59,  /*       VIEW => ID */\n   59,  /*    VIRTUAL => ID */\n   59,  /*       WITH => ID */\n   59,  /*      NULLS => ID */\n   59,  /*      FIRST => ID */\n   59,  /*       LAST => ID */\n   59,  /*    CURRENT => ID */\n   59,  /*  FOLLOWING => ID */\n   59,  /*  PARTITION => ID */\n   59,  /*  PRECEDING => ID */\n   59,  /*      RANGE => ID */\n   59,  /*  UNBOUNDED => ID */\n   59,  /*    EXCLUDE => ID */\n   59,  /*     GROUPS => ID */\n   59,  /*     OTHERS => ID */\n   59,  /*       TIES => ID */\n   59,  /*  GENERATED => ID */\n   59,  /*     ALWAYS => ID */\n   59,  /*    REINDEX => ID */\n   59,  /*     RENAME => ID */\n   59,  /*   CTIME_KW => ID */\n    0,  /*        ANY => nothing */\n    0,  /*     BITAND => nothing */\n    0,  /*      BITOR => nothing */\n    0,  /*     LSHIFT => nothing */\n    0,  /*     RSHIFT => nothing */\n    0,  /*       PLUS => nothing */\n    0,  /*      MINUS => nothing */\n    0,  /*       STAR => nothing */\n    0,  /*      SLASH => nothing */\n    0,  /*        REM => nothing */\n    0,  /*     CONCAT => nothing */\n    0,  /*    COLLATE => nothing */\n    0,  /*     BITNOT => nothing */\n    0,  /*         ON => nothing */\n    0,  /*    INDEXED => nothing */\n    0,  /*     STRING => nothing */\n    0,  /*    JOIN_KW => nothing */\n    0,  /* CONSTRAINT => nothing */\n    0,  /*    DEFAULT => nothing */\n    0,  /*       NULL => nothing */\n    0,  /*    PRIMARY => nothing */\n    0,  /*     UNIQUE => nothing */\n    0,  /*      CHECK => nothing */\n    0,  /* REFERENCES => nothing */\n    0,  /*   AUTOINCR => nothing */\n    0,  /*     INSERT => nothing */\n    0,  /*     DELETE => nothing */\n    0,  /*     UPDATE => nothing */\n    0,  /*        SET => nothing */\n    0,  /* DEFERRABLE => nothing */\n    0,  /*    FOREIGN => nothing */\n    0,  /*       DROP => nothing */\n    0,  /*      UNION => nothing */\n    0,  /*        ALL => nothing */\n    0,  /*     EXCEPT => nothing */\n    0,  /*  INTERSECT => nothing */\n    0,  /*     SELECT => nothing */\n    0,  /*     VALUES => nothing */\n    0,  /*   DISTINCT => nothing */\n    0,  /*        DOT => nothing */\n    0,  /*       FROM => nothing */\n    0,  /*       JOIN => nothing */\n    0,  /*      USING => nothing */\n    0,  /*      ORDER => nothing */\n    0,  /*      GROUP => nothing */\n    0,  /*     HAVING => nothing */\n    0,  /*      LIMIT => nothing */\n    0,  /*      WHERE => nothing */\n    0,  /*       INTO => nothing */\n    0,  /*    NOTHING => nothing */\n    0,  /*      FLOAT => nothing */\n    0,  /*       BLOB => nothing */\n    0,  /*    INTEGER => nothing */\n    0,  /*   VARIABLE => nothing */\n    0,  /*       CASE => nothing */\n    0,  /*       WHEN => nothing */\n    0,  /*       THEN => nothing */\n    0,  /*       ELSE => nothing */\n    0,  /*      INDEX => nothing */\n    0,  /*      ALTER => nothing */\n    0,  /*        ADD => nothing */\n    0,  /*     WINDOW => nothing */\n    0,  /*       OVER => nothing */\n    0,  /*     FILTER => nothing */\n    0,  /*     COLUMN => nothing */\n    0,  /* AGG_FUNCTION => nothing */\n    0,  /* AGG_COLUMN => nothing */\n    0,  /*  TRUEFALSE => nothing */\n    0,  /*      ISNOT => nothing */\n    0,  /*   FUNCTION => nothing */\n    0,  /*     UMINUS => nothing */\n    0,  /*      UPLUS => nothing */\n    0,  /*      TRUTH => nothing */\n    0,  /*   REGISTER => nothing */\n    0,  /*     VECTOR => nothing */\n    0,  /* SELECT_COLUMN => nothing */\n    0,  /* IF_NULL_ROW => nothing */\n    0,  /*   ASTERISK => nothing */\n    0,  /*       SPAN => nothing */\n    0,  /*      SPACE => nothing */\n    0,  /*    ILLEGAL => nothing */\n};\n#endif /* YYFALLBACK */\n\n/* The following structure represents a single element of the\n** parser's stack.  Information stored includes:\n**\n**   +  The state number for the parser at this level of the stack.\n**\n**   +  The value of the token stored at this level of the stack.\n**      (In other words, the \"major\" token.)\n**\n**   +  The semantic value stored at this level of the stack.  This is\n**      the information used by the action routines in the grammar.\n**      It is sometimes called the \"minor\" token.\n**\n** After the \"shift\" half of a SHIFTREDUCE action, the stateno field\n** actually contains the reduce action for the second half of the\n** SHIFTREDUCE.\n*/\nstruct yyStackEntry {\n  YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */\n  YYCODETYPE major;      /* The major token value.  This is the code\n                         ** number for the token at this stack level */\n  YYMINORTYPE minor;     /* The user-supplied minor token value.  This\n                         ** is the value of the token  */\n};\ntypedef struct yyStackEntry yyStackEntry;\n\n/* The state of the parser is completely contained in an instance of\n** the following structure */\nstruct yyParser {\n  yyStackEntry *yytos;          /* Pointer to top element of the stack */\n#ifdef YYTRACKMAXSTACKDEPTH\n  int yyhwm;                    /* High-water mark of the stack */\n#endif\n#ifndef YYNOERRORRECOVERY\n  int yyerrcnt;                 /* Shifts left before out of the error */\n#endif\n  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */\n  sqlite3ParserCTX_SDECL                /* A place to hold %extra_context */\n#if YYSTACKDEPTH<=0\n  int yystksz;                  /* Current side of the stack */\n  yyStackEntry *yystack;        /* The parser's stack */\n  yyStackEntry yystk0;          /* First stack entry */\n#else\n  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */\n  yyStackEntry *yystackEnd;            /* Last entry in the stack */\n#endif\n};\ntypedef struct yyParser yyParser;\n\n#ifndef NDEBUG\n/* #include <stdio.h> */\nstatic FILE *yyTraceFILE = 0;\nstatic char *yyTracePrompt = 0;\n#endif /* NDEBUG */\n\n#ifndef NDEBUG\n/* \n** Turn parser tracing on by giving a stream to which to write the trace\n** and a prompt to preface each trace message.  Tracing is turned off\n** by making either argument NULL \n**\n** Inputs:\n** <ul>\n** <li> A FILE* to which trace output should be written.\n**      If NULL, then tracing is turned off.\n** <li> A prefix string written at the beginning of every\n**      line of trace output.  If NULL, then tracing is\n**      turned off.\n** </ul>\n**\n** Outputs:\n** None.\n*/\nSQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){\n  yyTraceFILE = TraceFILE;\n  yyTracePrompt = zTracePrompt;\n  if( yyTraceFILE==0 ) yyTracePrompt = 0;\n  else if( yyTracePrompt==0 ) yyTraceFILE = 0;\n}\n#endif /* NDEBUG */\n\n#if defined(YYCOVERAGE) || !defined(NDEBUG)\n/* For tracing shifts, the names of all terminals and nonterminals\n** are required.  The following table supplies these names */\nstatic const char *const yyTokenName[] = { \n  /*    0 */ \"$\",\n  /*    1 */ \"SEMI\",\n  /*    2 */ \"EXPLAIN\",\n  /*    3 */ \"QUERY\",\n  /*    4 */ \"PLAN\",\n  /*    5 */ \"BEGIN\",\n  /*    6 */ \"TRANSACTION\",\n  /*    7 */ \"DEFERRED\",\n  /*    8 */ \"IMMEDIATE\",\n  /*    9 */ \"EXCLUSIVE\",\n  /*   10 */ \"COMMIT\",\n  /*   11 */ \"END\",\n  /*   12 */ \"ROLLBACK\",\n  /*   13 */ \"SAVEPOINT\",\n  /*   14 */ \"RELEASE\",\n  /*   15 */ \"TO\",\n  /*   16 */ \"TABLE\",\n  /*   17 */ \"CREATE\",\n  /*   18 */ \"IF\",\n  /*   19 */ \"NOT\",\n  /*   20 */ \"EXISTS\",\n  /*   21 */ \"TEMP\",\n  /*   22 */ \"LP\",\n  /*   23 */ \"RP\",\n  /*   24 */ \"AS\",\n  /*   25 */ \"WITHOUT\",\n  /*   26 */ \"COMMA\",\n  /*   27 */ \"ABORT\",\n  /*   28 */ \"ACTION\",\n  /*   29 */ \"AFTER\",\n  /*   30 */ \"ANALYZE\",\n  /*   31 */ \"ASC\",\n  /*   32 */ \"ATTACH\",\n  /*   33 */ \"BEFORE\",\n  /*   34 */ \"BY\",\n  /*   35 */ \"CASCADE\",\n  /*   36 */ \"CAST\",\n  /*   37 */ \"CONFLICT\",\n  /*   38 */ \"DATABASE\",\n  /*   39 */ \"DESC\",\n  /*   40 */ \"DETACH\",\n  /*   41 */ \"EACH\",\n  /*   42 */ \"FAIL\",\n  /*   43 */ \"OR\",\n  /*   44 */ \"AND\",\n  /*   45 */ \"IS\",\n  /*   46 */ \"MATCH\",\n  /*   47 */ \"LIKE_KW\",\n  /*   48 */ \"BETWEEN\",\n  /*   49 */ \"IN\",\n  /*   50 */ \"ISNULL\",\n  /*   51 */ \"NOTNULL\",\n  /*   52 */ \"NE\",\n  /*   53 */ \"EQ\",\n  /*   54 */ \"GT\",\n  /*   55 */ \"LE\",\n  /*   56 */ \"LT\",\n  /*   57 */ \"GE\",\n  /*   58 */ \"ESCAPE\",\n  /*   59 */ \"ID\",\n  /*   60 */ \"COLUMNKW\",\n  /*   61 */ \"DO\",\n  /*   62 */ \"FOR\",\n  /*   63 */ \"IGNORE\",\n  /*   64 */ \"INITIALLY\",\n  /*   65 */ \"INSTEAD\",\n  /*   66 */ \"NO\",\n  /*   67 */ \"KEY\",\n  /*   68 */ \"OF\",\n  /*   69 */ \"OFFSET\",\n  /*   70 */ \"PRAGMA\",\n  /*   71 */ \"RAISE\",\n  /*   72 */ \"RECURSIVE\",\n  /*   73 */ \"REPLACE\",\n  /*   74 */ \"RESTRICT\",\n  /*   75 */ \"ROW\",\n  /*   76 */ \"ROWS\",\n  /*   77 */ \"TRIGGER\",\n  /*   78 */ \"VACUUM\",\n  /*   79 */ \"VIEW\",\n  /*   80 */ \"VIRTUAL\",\n  /*   81 */ \"WITH\",\n  /*   82 */ \"NULLS\",\n  /*   83 */ \"FIRST\",\n  /*   84 */ \"LAST\",\n  /*   85 */ \"CURRENT\",\n  /*   86 */ \"FOLLOWING\",\n  /*   87 */ \"PARTITION\",\n  /*   88 */ \"PRECEDING\",\n  /*   89 */ \"RANGE\",\n  /*   90 */ \"UNBOUNDED\",\n  /*   91 */ \"EXCLUDE\",\n  /*   92 */ \"GROUPS\",\n  /*   93 */ \"OTHERS\",\n  /*   94 */ \"TIES\",\n  /*   95 */ \"GENERATED\",\n  /*   96 */ \"ALWAYS\",\n  /*   97 */ \"REINDEX\",\n  /*   98 */ \"RENAME\",\n  /*   99 */ \"CTIME_KW\",\n  /*  100 */ \"ANY\",\n  /*  101 */ \"BITAND\",\n  /*  102 */ \"BITOR\",\n  /*  103 */ \"LSHIFT\",\n  /*  104 */ \"RSHIFT\",\n  /*  105 */ \"PLUS\",\n  /*  106 */ \"MINUS\",\n  /*  107 */ \"STAR\",\n  /*  108 */ \"SLASH\",\n  /*  109 */ \"REM\",\n  /*  110 */ \"CONCAT\",\n  /*  111 */ \"COLLATE\",\n  /*  112 */ \"BITNOT\",\n  /*  113 */ \"ON\",\n  /*  114 */ \"INDEXED\",\n  /*  115 */ \"STRING\",\n  /*  116 */ \"JOIN_KW\",\n  /*  117 */ \"CONSTRAINT\",\n  /*  118 */ \"DEFAULT\",\n  /*  119 */ \"NULL\",\n  /*  120 */ \"PRIMARY\",\n  /*  121 */ \"UNIQUE\",\n  /*  122 */ \"CHECK\",\n  /*  123 */ \"REFERENCES\",\n  /*  124 */ \"AUTOINCR\",\n  /*  125 */ \"INSERT\",\n  /*  126 */ \"DELETE\",\n  /*  127 */ \"UPDATE\",\n  /*  128 */ \"SET\",\n  /*  129 */ \"DEFERRABLE\",\n  /*  130 */ \"FOREIGN\",\n  /*  131 */ \"DROP\",\n  /*  132 */ \"UNION\",\n  /*  133 */ \"ALL\",\n  /*  134 */ \"EXCEPT\",\n  /*  135 */ \"INTERSECT\",\n  /*  136 */ \"SELECT\",\n  /*  137 */ \"VALUES\",\n  /*  138 */ \"DISTINCT\",\n  /*  139 */ \"DOT\",\n  /*  140 */ \"FROM\",\n  /*  141 */ \"JOIN\",\n  /*  142 */ \"USING\",\n  /*  143 */ \"ORDER\",\n  /*  144 */ \"GROUP\",\n  /*  145 */ \"HAVING\",\n  /*  146 */ \"LIMIT\",\n  /*  147 */ \"WHERE\",\n  /*  148 */ \"INTO\",\n  /*  149 */ \"NOTHING\",\n  /*  150 */ \"FLOAT\",\n  /*  151 */ \"BLOB\",\n  /*  152 */ \"INTEGER\",\n  /*  153 */ \"VARIABLE\",\n  /*  154 */ \"CASE\",\n  /*  155 */ \"WHEN\",\n  /*  156 */ \"THEN\",\n  /*  157 */ \"ELSE\",\n  /*  158 */ \"INDEX\",\n  /*  159 */ \"ALTER\",\n  /*  160 */ \"ADD\",\n  /*  161 */ \"WINDOW\",\n  /*  162 */ \"OVER\",\n  /*  163 */ \"FILTER\",\n  /*  164 */ \"COLUMN\",\n  /*  165 */ \"AGG_FUNCTION\",\n  /*  166 */ \"AGG_COLUMN\",\n  /*  167 */ \"TRUEFALSE\",\n  /*  168 */ \"ISNOT\",\n  /*  169 */ \"FUNCTION\",\n  /*  170 */ \"UMINUS\",\n  /*  171 */ \"UPLUS\",\n  /*  172 */ \"TRUTH\",\n  /*  173 */ \"REGISTER\",\n  /*  174 */ \"VECTOR\",\n  /*  175 */ \"SELECT_COLUMN\",\n  /*  176 */ \"IF_NULL_ROW\",\n  /*  177 */ \"ASTERISK\",\n  /*  178 */ \"SPAN\",\n  /*  179 */ \"SPACE\",\n  /*  180 */ \"ILLEGAL\",\n  /*  181 */ \"input\",\n  /*  182 */ \"cmdlist\",\n  /*  183 */ \"ecmd\",\n  /*  184 */ \"cmdx\",\n  /*  185 */ \"explain\",\n  /*  186 */ \"cmd\",\n  /*  187 */ \"transtype\",\n  /*  188 */ \"trans_opt\",\n  /*  189 */ \"nm\",\n  /*  190 */ \"savepoint_opt\",\n  /*  191 */ \"create_table\",\n  /*  192 */ \"create_table_args\",\n  /*  193 */ \"createkw\",\n  /*  194 */ \"temp\",\n  /*  195 */ \"ifnotexists\",\n  /*  196 */ \"dbnm\",\n  /*  197 */ \"columnlist\",\n  /*  198 */ \"conslist_opt\",\n  /*  199 */ \"table_options\",\n  /*  200 */ \"select\",\n  /*  201 */ \"columnname\",\n  /*  202 */ \"carglist\",\n  /*  203 */ \"typetoken\",\n  /*  204 */ \"typename\",\n  /*  205 */ \"signed\",\n  /*  206 */ \"plus_num\",\n  /*  207 */ \"minus_num\",\n  /*  208 */ \"scanpt\",\n  /*  209 */ \"scantok\",\n  /*  210 */ \"ccons\",\n  /*  211 */ \"term\",\n  /*  212 */ \"expr\",\n  /*  213 */ \"onconf\",\n  /*  214 */ \"sortorder\",\n  /*  215 */ \"autoinc\",\n  /*  216 */ \"eidlist_opt\",\n  /*  217 */ \"refargs\",\n  /*  218 */ \"defer_subclause\",\n  /*  219 */ \"generated\",\n  /*  220 */ \"refarg\",\n  /*  221 */ \"refact\",\n  /*  222 */ \"init_deferred_pred_opt\",\n  /*  223 */ \"conslist\",\n  /*  224 */ \"tconscomma\",\n  /*  225 */ \"tcons\",\n  /*  226 */ \"sortlist\",\n  /*  227 */ \"eidlist\",\n  /*  228 */ \"defer_subclause_opt\",\n  /*  229 */ \"orconf\",\n  /*  230 */ \"resolvetype\",\n  /*  231 */ \"raisetype\",\n  /*  232 */ \"ifexists\",\n  /*  233 */ \"fullname\",\n  /*  234 */ \"selectnowith\",\n  /*  235 */ \"oneselect\",\n  /*  236 */ \"wqlist\",\n  /*  237 */ \"multiselect_op\",\n  /*  238 */ \"distinct\",\n  /*  239 */ \"selcollist\",\n  /*  240 */ \"from\",\n  /*  241 */ \"where_opt\",\n  /*  242 */ \"groupby_opt\",\n  /*  243 */ \"having_opt\",\n  /*  244 */ \"orderby_opt\",\n  /*  245 */ \"limit_opt\",\n  /*  246 */ \"window_clause\",\n  /*  247 */ \"values\",\n  /*  248 */ \"nexprlist\",\n  /*  249 */ \"sclp\",\n  /*  250 */ \"as\",\n  /*  251 */ \"seltablist\",\n  /*  252 */ \"stl_prefix\",\n  /*  253 */ \"joinop\",\n  /*  254 */ \"indexed_opt\",\n  /*  255 */ \"on_opt\",\n  /*  256 */ \"using_opt\",\n  /*  257 */ \"exprlist\",\n  /*  258 */ \"xfullname\",\n  /*  259 */ \"idlist\",\n  /*  260 */ \"nulls\",\n  /*  261 */ \"with\",\n  /*  262 */ \"setlist\",\n  /*  263 */ \"insert_cmd\",\n  /*  264 */ \"idlist_opt\",\n  /*  265 */ \"upsert\",\n  /*  266 */ \"filter_over\",\n  /*  267 */ \"likeop\",\n  /*  268 */ \"between_op\",\n  /*  269 */ \"in_op\",\n  /*  270 */ \"paren_exprlist\",\n  /*  271 */ \"case_operand\",\n  /*  272 */ \"case_exprlist\",\n  /*  273 */ \"case_else\",\n  /*  274 */ \"uniqueflag\",\n  /*  275 */ \"collate\",\n  /*  276 */ \"vinto\",\n  /*  277 */ \"nmnum\",\n  /*  278 */ \"trigger_decl\",\n  /*  279 */ \"trigger_cmd_list\",\n  /*  280 */ \"trigger_time\",\n  /*  281 */ \"trigger_event\",\n  /*  282 */ \"foreach_clause\",\n  /*  283 */ \"when_clause\",\n  /*  284 */ \"trigger_cmd\",\n  /*  285 */ \"trnm\",\n  /*  286 */ \"tridxby\",\n  /*  287 */ \"database_kw_opt\",\n  /*  288 */ \"key_opt\",\n  /*  289 */ \"add_column_fullname\",\n  /*  290 */ \"kwcolumn_opt\",\n  /*  291 */ \"create_vtab\",\n  /*  292 */ \"vtabarglist\",\n  /*  293 */ \"vtabarg\",\n  /*  294 */ \"vtabargtoken\",\n  /*  295 */ \"lp\",\n  /*  296 */ \"anylist\",\n  /*  297 */ \"windowdefn_list\",\n  /*  298 */ \"windowdefn\",\n  /*  299 */ \"window\",\n  /*  300 */ \"frame_opt\",\n  /*  301 */ \"part_opt\",\n  /*  302 */ \"filter_clause\",\n  /*  303 */ \"over_clause\",\n  /*  304 */ \"range_or_rows\",\n  /*  305 */ \"frame_bound\",\n  /*  306 */ \"frame_bound_s\",\n  /*  307 */ \"frame_bound_e\",\n  /*  308 */ \"frame_exclude_opt\",\n  /*  309 */ \"frame_exclude\",\n};\n#endif /* defined(YYCOVERAGE) || !defined(NDEBUG) */\n\n#ifndef NDEBUG\n/* For tracing reduce actions, the names of all rules are required.\n*/\nstatic const char *const yyRuleName[] = {\n /*   0 */ \"explain ::= EXPLAIN\",\n /*   1 */ \"explain ::= EXPLAIN QUERY PLAN\",\n /*   2 */ \"cmdx ::= cmd\",\n /*   3 */ \"cmd ::= BEGIN transtype trans_opt\",\n /*   4 */ \"transtype ::=\",\n /*   5 */ \"transtype ::= DEFERRED\",\n /*   6 */ \"transtype ::= IMMEDIATE\",\n /*   7 */ \"transtype ::= EXCLUSIVE\",\n /*   8 */ \"cmd ::= COMMIT|END trans_opt\",\n /*   9 */ \"cmd ::= ROLLBACK trans_opt\",\n /*  10 */ \"cmd ::= SAVEPOINT nm\",\n /*  11 */ \"cmd ::= RELEASE savepoint_opt nm\",\n /*  12 */ \"cmd ::= ROLLBACK trans_opt TO savepoint_opt nm\",\n /*  13 */ \"create_table ::= createkw temp TABLE ifnotexists nm dbnm\",\n /*  14 */ \"createkw ::= CREATE\",\n /*  15 */ \"ifnotexists ::=\",\n /*  16 */ \"ifnotexists ::= IF NOT EXISTS\",\n /*  17 */ \"temp ::= TEMP\",\n /*  18 */ \"temp ::=\",\n /*  19 */ \"create_table_args ::= LP columnlist conslist_opt RP table_options\",\n /*  20 */ \"create_table_args ::= AS select\",\n /*  21 */ \"table_options ::=\",\n /*  22 */ \"table_options ::= WITHOUT nm\",\n /*  23 */ \"columnname ::= nm typetoken\",\n /*  24 */ \"typetoken ::=\",\n /*  25 */ \"typetoken ::= typename LP signed RP\",\n /*  26 */ \"typetoken ::= typename LP signed COMMA signed RP\",\n /*  27 */ \"typename ::= typename ID|STRING\",\n /*  28 */ \"scanpt ::=\",\n /*  29 */ \"scantok ::=\",\n /*  30 */ \"ccons ::= CONSTRAINT nm\",\n /*  31 */ \"ccons ::= DEFAULT scantok term\",\n /*  32 */ \"ccons ::= DEFAULT LP expr RP\",\n /*  33 */ \"ccons ::= DEFAULT PLUS scantok term\",\n /*  34 */ \"ccons ::= DEFAULT MINUS scantok term\",\n /*  35 */ \"ccons ::= DEFAULT scantok ID|INDEXED\",\n /*  36 */ \"ccons ::= NOT NULL onconf\",\n /*  37 */ \"ccons ::= PRIMARY KEY sortorder onconf autoinc\",\n /*  38 */ \"ccons ::= UNIQUE onconf\",\n /*  39 */ \"ccons ::= CHECK LP expr RP\",\n /*  40 */ \"ccons ::= REFERENCES nm eidlist_opt refargs\",\n /*  41 */ \"ccons ::= defer_subclause\",\n /*  42 */ \"ccons ::= COLLATE ID|STRING\",\n /*  43 */ \"generated ::= LP expr RP\",\n /*  44 */ \"generated ::= LP expr RP ID\",\n /*  45 */ \"autoinc ::=\",\n /*  46 */ \"autoinc ::= AUTOINCR\",\n /*  47 */ \"refargs ::=\",\n /*  48 */ \"refargs ::= refargs refarg\",\n /*  49 */ \"refarg ::= MATCH nm\",\n /*  50 */ \"refarg ::= ON INSERT refact\",\n /*  51 */ \"refarg ::= ON DELETE refact\",\n /*  52 */ \"refarg ::= ON UPDATE refact\",\n /*  53 */ \"refact ::= SET NULL\",\n /*  54 */ \"refact ::= SET DEFAULT\",\n /*  55 */ \"refact ::= CASCADE\",\n /*  56 */ \"refact ::= RESTRICT\",\n /*  57 */ \"refact ::= NO ACTION\",\n /*  58 */ \"defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt\",\n /*  59 */ \"defer_subclause ::= DEFERRABLE init_deferred_pred_opt\",\n /*  60 */ \"init_deferred_pred_opt ::=\",\n /*  61 */ \"init_deferred_pred_opt ::= INITIALLY DEFERRED\",\n /*  62 */ \"init_deferred_pred_opt ::= INITIALLY IMMEDIATE\",\n /*  63 */ \"conslist_opt ::=\",\n /*  64 */ \"tconscomma ::= COMMA\",\n /*  65 */ \"tcons ::= CONSTRAINT nm\",\n /*  66 */ \"tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf\",\n /*  67 */ \"tcons ::= UNIQUE LP sortlist RP onconf\",\n /*  68 */ \"tcons ::= CHECK LP expr RP onconf\",\n /*  69 */ \"tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt\",\n /*  70 */ \"defer_subclause_opt ::=\",\n /*  71 */ \"onconf ::=\",\n /*  72 */ \"onconf ::= ON CONFLICT resolvetype\",\n /*  73 */ \"orconf ::=\",\n /*  74 */ \"orconf ::= OR resolvetype\",\n /*  75 */ \"resolvetype ::= IGNORE\",\n /*  76 */ \"resolvetype ::= REPLACE\",\n /*  77 */ \"cmd ::= DROP TABLE ifexists fullname\",\n /*  78 */ \"ifexists ::= IF EXISTS\",\n /*  79 */ \"ifexists ::=\",\n /*  80 */ \"cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select\",\n /*  81 */ \"cmd ::= DROP VIEW ifexists fullname\",\n /*  82 */ \"cmd ::= select\",\n /*  83 */ \"select ::= WITH wqlist selectnowith\",\n /*  84 */ \"select ::= WITH RECURSIVE wqlist selectnowith\",\n /*  85 */ \"select ::= selectnowith\",\n /*  86 */ \"selectnowith ::= selectnowith multiselect_op oneselect\",\n /*  87 */ \"multiselect_op ::= UNION\",\n /*  88 */ \"multiselect_op ::= UNION ALL\",\n /*  89 */ \"multiselect_op ::= EXCEPT|INTERSECT\",\n /*  90 */ \"oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt\",\n /*  91 */ \"oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt\",\n /*  92 */ \"values ::= VALUES LP nexprlist RP\",\n /*  93 */ \"values ::= values COMMA LP nexprlist RP\",\n /*  94 */ \"distinct ::= DISTINCT\",\n /*  95 */ \"distinct ::= ALL\",\n /*  96 */ \"distinct ::=\",\n /*  97 */ \"sclp ::=\",\n /*  98 */ \"selcollist ::= sclp scanpt expr scanpt as\",\n /*  99 */ \"selcollist ::= sclp scanpt STAR\",\n /* 100 */ \"selcollist ::= sclp scanpt nm DOT STAR\",\n /* 101 */ \"as ::= AS nm\",\n /* 102 */ \"as ::=\",\n /* 103 */ \"from ::=\",\n /* 104 */ \"from ::= FROM seltablist\",\n /* 105 */ \"stl_prefix ::= seltablist joinop\",\n /* 106 */ \"stl_prefix ::=\",\n /* 107 */ \"seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt\",\n /* 108 */ \"seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt\",\n /* 109 */ \"seltablist ::= stl_prefix LP select RP as on_opt using_opt\",\n /* 110 */ \"seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt\",\n /* 111 */ \"dbnm ::=\",\n /* 112 */ \"dbnm ::= DOT nm\",\n /* 113 */ \"fullname ::= nm\",\n /* 114 */ \"fullname ::= nm DOT nm\",\n /* 115 */ \"xfullname ::= nm\",\n /* 116 */ \"xfullname ::= nm DOT nm\",\n /* 117 */ \"xfullname ::= nm DOT nm AS nm\",\n /* 118 */ \"xfullname ::= nm AS nm\",\n /* 119 */ \"joinop ::= COMMA|JOIN\",\n /* 120 */ \"joinop ::= JOIN_KW JOIN\",\n /* 121 */ \"joinop ::= JOIN_KW nm JOIN\",\n /* 122 */ \"joinop ::= JOIN_KW nm nm JOIN\",\n /* 123 */ \"on_opt ::= ON expr\",\n /* 124 */ \"on_opt ::=\",\n /* 125 */ \"indexed_opt ::=\",\n /* 126 */ \"indexed_opt ::= INDEXED BY nm\",\n /* 127 */ \"indexed_opt ::= NOT INDEXED\",\n /* 128 */ \"using_opt ::= USING LP idlist RP\",\n /* 129 */ \"using_opt ::=\",\n /* 130 */ \"orderby_opt ::=\",\n /* 131 */ \"orderby_opt ::= ORDER BY sortlist\",\n /* 132 */ \"sortlist ::= sortlist COMMA expr sortorder nulls\",\n /* 133 */ \"sortlist ::= expr sortorder nulls\",\n /* 134 */ \"sortorder ::= ASC\",\n /* 135 */ \"sortorder ::= DESC\",\n /* 136 */ \"sortorder ::=\",\n /* 137 */ \"nulls ::= NULLS FIRST\",\n /* 138 */ \"nulls ::= NULLS LAST\",\n /* 139 */ \"nulls ::=\",\n /* 140 */ \"groupby_opt ::=\",\n /* 141 */ \"groupby_opt ::= GROUP BY nexprlist\",\n /* 142 */ \"having_opt ::=\",\n /* 143 */ \"having_opt ::= HAVING expr\",\n /* 144 */ \"limit_opt ::=\",\n /* 145 */ \"limit_opt ::= LIMIT expr\",\n /* 146 */ \"limit_opt ::= LIMIT expr OFFSET expr\",\n /* 147 */ \"limit_opt ::= LIMIT expr COMMA expr\",\n /* 148 */ \"cmd ::= with DELETE FROM xfullname indexed_opt where_opt\",\n /* 149 */ \"where_opt ::=\",\n /* 150 */ \"where_opt ::= WHERE expr\",\n /* 151 */ \"cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt\",\n /* 152 */ \"setlist ::= setlist COMMA nm EQ expr\",\n /* 153 */ \"setlist ::= setlist COMMA LP idlist RP EQ expr\",\n /* 154 */ \"setlist ::= nm EQ expr\",\n /* 155 */ \"setlist ::= LP idlist RP EQ expr\",\n /* 156 */ \"cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert\",\n /* 157 */ \"cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES\",\n /* 158 */ \"upsert ::=\",\n /* 159 */ \"upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt\",\n /* 160 */ \"upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING\",\n /* 161 */ \"upsert ::= ON CONFLICT DO NOTHING\",\n /* 162 */ \"insert_cmd ::= INSERT orconf\",\n /* 163 */ \"insert_cmd ::= REPLACE\",\n /* 164 */ \"idlist_opt ::=\",\n /* 165 */ \"idlist_opt ::= LP idlist RP\",\n /* 166 */ \"idlist ::= idlist COMMA nm\",\n /* 167 */ \"idlist ::= nm\",\n /* 168 */ \"expr ::= LP expr RP\",\n /* 169 */ \"expr ::= ID|INDEXED\",\n /* 170 */ \"expr ::= JOIN_KW\",\n /* 171 */ \"expr ::= nm DOT nm\",\n /* 172 */ \"expr ::= nm DOT nm DOT nm\",\n /* 173 */ \"term ::= NULL|FLOAT|BLOB\",\n /* 174 */ \"term ::= STRING\",\n /* 175 */ \"term ::= INTEGER\",\n /* 176 */ \"expr ::= VARIABLE\",\n /* 177 */ \"expr ::= expr COLLATE ID|STRING\",\n /* 178 */ \"expr ::= CAST LP expr AS typetoken RP\",\n /* 179 */ \"expr ::= ID|INDEXED LP distinct exprlist RP\",\n /* 180 */ \"expr ::= ID|INDEXED LP STAR RP\",\n /* 181 */ \"expr ::= ID|INDEXED LP distinct exprlist RP filter_over\",\n /* 182 */ \"expr ::= ID|INDEXED LP STAR RP filter_over\",\n /* 183 */ \"term ::= CTIME_KW\",\n /* 184 */ \"expr ::= LP nexprlist COMMA expr RP\",\n /* 185 */ \"expr ::= expr AND expr\",\n /* 186 */ \"expr ::= expr OR expr\",\n /* 187 */ \"expr ::= expr LT|GT|GE|LE expr\",\n /* 188 */ \"expr ::= expr EQ|NE expr\",\n /* 189 */ \"expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr\",\n /* 190 */ \"expr ::= expr PLUS|MINUS expr\",\n /* 191 */ \"expr ::= expr STAR|SLASH|REM expr\",\n /* 192 */ \"expr ::= expr CONCAT expr\",\n /* 193 */ \"likeop ::= NOT LIKE_KW|MATCH\",\n /* 194 */ \"expr ::= expr likeop expr\",\n /* 195 */ \"expr ::= expr likeop expr ESCAPE expr\",\n /* 196 */ \"expr ::= expr ISNULL|NOTNULL\",\n /* 197 */ \"expr ::= expr NOT NULL\",\n /* 198 */ \"expr ::= expr IS expr\",\n /* 199 */ \"expr ::= expr IS NOT expr\",\n /* 200 */ \"expr ::= NOT expr\",\n /* 201 */ \"expr ::= BITNOT expr\",\n /* 202 */ \"expr ::= PLUS|MINUS expr\",\n /* 203 */ \"between_op ::= BETWEEN\",\n /* 204 */ \"between_op ::= NOT BETWEEN\",\n /* 205 */ \"expr ::= expr between_op expr AND expr\",\n /* 206 */ \"in_op ::= IN\",\n /* 207 */ \"in_op ::= NOT IN\",\n /* 208 */ \"expr ::= expr in_op LP exprlist RP\",\n /* 209 */ \"expr ::= LP select RP\",\n /* 210 */ \"expr ::= expr in_op LP select RP\",\n /* 211 */ \"expr ::= expr in_op nm dbnm paren_exprlist\",\n /* 212 */ \"expr ::= EXISTS LP select RP\",\n /* 213 */ \"expr ::= CASE case_operand case_exprlist case_else END\",\n /* 214 */ \"case_exprlist ::= case_exprlist WHEN expr THEN expr\",\n /* 215 */ \"case_exprlist ::= WHEN expr THEN expr\",\n /* 216 */ \"case_else ::= ELSE expr\",\n /* 217 */ \"case_else ::=\",\n /* 218 */ \"case_operand ::= expr\",\n /* 219 */ \"case_operand ::=\",\n /* 220 */ \"exprlist ::=\",\n /* 221 */ \"nexprlist ::= nexprlist COMMA expr\",\n /* 222 */ \"nexprlist ::= expr\",\n /* 223 */ \"paren_exprlist ::=\",\n /* 224 */ \"paren_exprlist ::= LP exprlist RP\",\n /* 225 */ \"cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt\",\n /* 226 */ \"uniqueflag ::= UNIQUE\",\n /* 227 */ \"uniqueflag ::=\",\n /* 228 */ \"eidlist_opt ::=\",\n /* 229 */ \"eidlist_opt ::= LP eidlist RP\",\n /* 230 */ \"eidlist ::= eidlist COMMA nm collate sortorder\",\n /* 231 */ \"eidlist ::= nm collate sortorder\",\n /* 232 */ \"collate ::=\",\n /* 233 */ \"collate ::= COLLATE ID|STRING\",\n /* 234 */ \"cmd ::= DROP INDEX ifexists fullname\",\n /* 235 */ \"cmd ::= VACUUM vinto\",\n /* 236 */ \"cmd ::= VACUUM nm vinto\",\n /* 237 */ \"vinto ::= INTO expr\",\n /* 238 */ \"vinto ::=\",\n /* 239 */ \"cmd ::= PRAGMA nm dbnm\",\n /* 240 */ \"cmd ::= PRAGMA nm dbnm EQ nmnum\",\n /* 241 */ \"cmd ::= PRAGMA nm dbnm LP nmnum RP\",\n /* 242 */ \"cmd ::= PRAGMA nm dbnm EQ minus_num\",\n /* 243 */ \"cmd ::= PRAGMA nm dbnm LP minus_num RP\",\n /* 244 */ \"plus_num ::= PLUS INTEGER|FLOAT\",\n /* 245 */ \"minus_num ::= MINUS INTEGER|FLOAT\",\n /* 246 */ \"cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END\",\n /* 247 */ \"trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause\",\n /* 248 */ \"trigger_time ::= BEFORE|AFTER\",\n /* 249 */ \"trigger_time ::= INSTEAD OF\",\n /* 250 */ \"trigger_time ::=\",\n /* 251 */ \"trigger_event ::= DELETE|INSERT\",\n /* 252 */ \"trigger_event ::= UPDATE\",\n /* 253 */ \"trigger_event ::= UPDATE OF idlist\",\n /* 254 */ \"when_clause ::=\",\n /* 255 */ \"when_clause ::= WHEN expr\",\n /* 256 */ \"trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI\",\n /* 257 */ \"trigger_cmd_list ::= trigger_cmd SEMI\",\n /* 258 */ \"trnm ::= nm DOT nm\",\n /* 259 */ \"tridxby ::= INDEXED BY nm\",\n /* 260 */ \"tridxby ::= NOT INDEXED\",\n /* 261 */ \"trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt\",\n /* 262 */ \"trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt\",\n /* 263 */ \"trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt\",\n /* 264 */ \"trigger_cmd ::= scanpt select scanpt\",\n /* 265 */ \"expr ::= RAISE LP IGNORE RP\",\n /* 266 */ \"expr ::= RAISE LP raisetype COMMA nm RP\",\n /* 267 */ \"raisetype ::= ROLLBACK\",\n /* 268 */ \"raisetype ::= ABORT\",\n /* 269 */ \"raisetype ::= FAIL\",\n /* 270 */ \"cmd ::= DROP TRIGGER ifexists fullname\",\n /* 271 */ \"cmd ::= ATTACH database_kw_opt expr AS expr key_opt\",\n /* 272 */ \"cmd ::= DETACH database_kw_opt expr\",\n /* 273 */ \"key_opt ::=\",\n /* 274 */ \"key_opt ::= KEY expr\",\n /* 275 */ \"cmd ::= REINDEX\",\n /* 276 */ \"cmd ::= REINDEX nm dbnm\",\n /* 277 */ \"cmd ::= ANALYZE\",\n /* 278 */ \"cmd ::= ANALYZE nm dbnm\",\n /* 279 */ \"cmd ::= ALTER TABLE fullname RENAME TO nm\",\n /* 280 */ \"cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist\",\n /* 281 */ \"add_column_fullname ::= fullname\",\n /* 282 */ \"cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm\",\n /* 283 */ \"cmd ::= create_vtab\",\n /* 284 */ \"cmd ::= create_vtab LP vtabarglist RP\",\n /* 285 */ \"create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm\",\n /* 286 */ \"vtabarg ::=\",\n /* 287 */ \"vtabargtoken ::= ANY\",\n /* 288 */ \"vtabargtoken ::= lp anylist RP\",\n /* 289 */ \"lp ::= LP\",\n /* 290 */ \"with ::= WITH wqlist\",\n /* 291 */ \"with ::= WITH RECURSIVE wqlist\",\n /* 292 */ \"wqlist ::= nm eidlist_opt AS LP select RP\",\n /* 293 */ \"wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP\",\n /* 294 */ \"windowdefn_list ::= windowdefn\",\n /* 295 */ \"windowdefn_list ::= windowdefn_list COMMA windowdefn\",\n /* 296 */ \"windowdefn ::= nm AS LP window RP\",\n /* 297 */ \"window ::= PARTITION BY nexprlist orderby_opt frame_opt\",\n /* 298 */ \"window ::= nm PARTITION BY nexprlist orderby_opt frame_opt\",\n /* 299 */ \"window ::= ORDER BY sortlist frame_opt\",\n /* 300 */ \"window ::= nm ORDER BY sortlist frame_opt\",\n /* 301 */ \"window ::= frame_opt\",\n /* 302 */ \"window ::= nm frame_opt\",\n /* 303 */ \"frame_opt ::=\",\n /* 304 */ \"frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt\",\n /* 305 */ \"frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt\",\n /* 306 */ \"range_or_rows ::= RANGE|ROWS|GROUPS\",\n /* 307 */ \"frame_bound_s ::= frame_bound\",\n /* 308 */ \"frame_bound_s ::= UNBOUNDED PRECEDING\",\n /* 309 */ \"frame_bound_e ::= frame_bound\",\n /* 310 */ \"frame_bound_e ::= UNBOUNDED FOLLOWING\",\n /* 311 */ \"frame_bound ::= expr PRECEDING|FOLLOWING\",\n /* 312 */ \"frame_bound ::= CURRENT ROW\",\n /* 313 */ \"frame_exclude_opt ::=\",\n /* 314 */ \"frame_exclude_opt ::= EXCLUDE frame_exclude\",\n /* 315 */ \"frame_exclude ::= NO OTHERS\",\n /* 316 */ \"frame_exclude ::= CURRENT ROW\",\n /* 317 */ \"frame_exclude ::= GROUP|TIES\",\n /* 318 */ \"window_clause ::= WINDOW windowdefn_list\",\n /* 319 */ \"filter_over ::= filter_clause over_clause\",\n /* 320 */ \"filter_over ::= over_clause\",\n /* 321 */ \"filter_over ::= filter_clause\",\n /* 322 */ \"over_clause ::= OVER LP window RP\",\n /* 323 */ \"over_clause ::= OVER nm\",\n /* 324 */ \"filter_clause ::= FILTER LP WHERE expr RP\",\n /* 325 */ \"input ::= cmdlist\",\n /* 326 */ \"cmdlist ::= cmdlist ecmd\",\n /* 327 */ \"cmdlist ::= ecmd\",\n /* 328 */ \"ecmd ::= SEMI\",\n /* 329 */ \"ecmd ::= cmdx SEMI\",\n /* 330 */ \"ecmd ::= explain cmdx SEMI\",\n /* 331 */ \"trans_opt ::=\",\n /* 332 */ \"trans_opt ::= TRANSACTION\",\n /* 333 */ \"trans_opt ::= TRANSACTION nm\",\n /* 334 */ \"savepoint_opt ::= SAVEPOINT\",\n /* 335 */ \"savepoint_opt ::=\",\n /* 336 */ \"cmd ::= create_table create_table_args\",\n /* 337 */ \"columnlist ::= columnlist COMMA columnname carglist\",\n /* 338 */ \"columnlist ::= columnname carglist\",\n /* 339 */ \"nm ::= ID|INDEXED\",\n /* 340 */ \"nm ::= STRING\",\n /* 341 */ \"nm ::= JOIN_KW\",\n /* 342 */ \"typetoken ::= typename\",\n /* 343 */ \"typename ::= ID|STRING\",\n /* 344 */ \"signed ::= plus_num\",\n /* 345 */ \"signed ::= minus_num\",\n /* 346 */ \"carglist ::= carglist ccons\",\n /* 347 */ \"carglist ::=\",\n /* 348 */ \"ccons ::= NULL onconf\",\n /* 349 */ \"ccons ::= GENERATED ALWAYS AS generated\",\n /* 350 */ \"ccons ::= AS generated\",\n /* 351 */ \"conslist_opt ::= COMMA conslist\",\n /* 352 */ \"conslist ::= conslist tconscomma tcons\",\n /* 353 */ \"conslist ::= tcons\",\n /* 354 */ \"tconscomma ::=\",\n /* 355 */ \"defer_subclause_opt ::= defer_subclause\",\n /* 356 */ \"resolvetype ::= raisetype\",\n /* 357 */ \"selectnowith ::= oneselect\",\n /* 358 */ \"oneselect ::= values\",\n /* 359 */ \"sclp ::= selcollist COMMA\",\n /* 360 */ \"as ::= ID|STRING\",\n /* 361 */ \"expr ::= term\",\n /* 362 */ \"likeop ::= LIKE_KW|MATCH\",\n /* 363 */ \"exprlist ::= nexprlist\",\n /* 364 */ \"nmnum ::= plus_num\",\n /* 365 */ \"nmnum ::= nm\",\n /* 366 */ \"nmnum ::= ON\",\n /* 367 */ \"nmnum ::= DELETE\",\n /* 368 */ \"nmnum ::= DEFAULT\",\n /* 369 */ \"plus_num ::= INTEGER|FLOAT\",\n /* 370 */ \"foreach_clause ::=\",\n /* 371 */ \"foreach_clause ::= FOR EACH ROW\",\n /* 372 */ \"trnm ::= nm\",\n /* 373 */ \"tridxby ::=\",\n /* 374 */ \"database_kw_opt ::= DATABASE\",\n /* 375 */ \"database_kw_opt ::=\",\n /* 376 */ \"kwcolumn_opt ::=\",\n /* 377 */ \"kwcolumn_opt ::= COLUMNKW\",\n /* 378 */ \"vtabarglist ::= vtabarg\",\n /* 379 */ \"vtabarglist ::= vtabarglist COMMA vtabarg\",\n /* 380 */ \"vtabarg ::= vtabarg vtabargtoken\",\n /* 381 */ \"anylist ::=\",\n /* 382 */ \"anylist ::= anylist LP anylist RP\",\n /* 383 */ \"anylist ::= anylist ANY\",\n /* 384 */ \"with ::=\",\n};\n#endif /* NDEBUG */\n\n\n#if YYSTACKDEPTH<=0\n/*\n** Try to increase the size of the parser stack.  Return the number\n** of errors.  Return 0 on success.\n*/\nstatic int yyGrowStack(yyParser *p){\n  int newSize;\n  int idx;\n  yyStackEntry *pNew;\n\n  newSize = p->yystksz*2 + 100;\n  idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;\n  if( p->yystack==&p->yystk0 ){\n    pNew = malloc(newSize*sizeof(pNew[0]));\n    if( pNew ) pNew[0] = p->yystk0;\n  }else{\n    pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));\n  }\n  if( pNew ){\n    p->yystack = pNew;\n    p->yytos = &p->yystack[idx];\n#ifndef NDEBUG\n    if( yyTraceFILE ){\n      fprintf(yyTraceFILE,\"%sStack grows from %d to %d entries.\\n\",\n              yyTracePrompt, p->yystksz, newSize);\n    }\n#endif\n    p->yystksz = newSize;\n  }\n  return pNew==0; \n}\n#endif\n\n/* Datatype of the argument to the memory allocated passed as the\n** second argument to sqlite3ParserAlloc() below.  This can be changed by\n** putting an appropriate #define in the %include section of the input\n** grammar.\n*/\n#ifndef YYMALLOCARGTYPE\n# define YYMALLOCARGTYPE size_t\n#endif\n\n/* Initialize a new parser that has already been allocated.\n*/\nSQLITE_PRIVATE void sqlite3ParserInit(void *yypRawParser sqlite3ParserCTX_PDECL){\n  yyParser *yypParser = (yyParser*)yypRawParser;\n  sqlite3ParserCTX_STORE\n#ifdef YYTRACKMAXSTACKDEPTH\n  yypParser->yyhwm = 0;\n#endif\n#if YYSTACKDEPTH<=0\n  yypParser->yytos = NULL;\n  yypParser->yystack = NULL;\n  yypParser->yystksz = 0;\n  if( yyGrowStack(yypParser) ){\n    yypParser->yystack = &yypParser->yystk0;\n    yypParser->yystksz = 1;\n  }\n#endif\n#ifndef YYNOERRORRECOVERY\n  yypParser->yyerrcnt = -1;\n#endif\n  yypParser->yytos = yypParser->yystack;\n  yypParser->yystack[0].stateno = 0;\n  yypParser->yystack[0].major = 0;\n#if YYSTACKDEPTH>0\n  yypParser->yystackEnd = &yypParser->yystack[YYSTACKDEPTH-1];\n#endif\n}\n\n#ifndef sqlite3Parser_ENGINEALWAYSONSTACK\n/* \n** This function allocates a new parser.\n** The only argument is a pointer to a function which works like\n** malloc.\n**\n** Inputs:\n** A pointer to the function used to allocate memory.\n**\n** Outputs:\n** A pointer to a parser.  This pointer is used in subsequent calls\n** to sqlite3Parser and sqlite3ParserFree.\n*/\nSQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE) sqlite3ParserCTX_PDECL){\n  yyParser *yypParser;\n  yypParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );\n  if( yypParser ){\n    sqlite3ParserCTX_STORE\n    sqlite3ParserInit(yypParser sqlite3ParserCTX_PARAM);\n  }\n  return (void*)yypParser;\n}\n#endif /* sqlite3Parser_ENGINEALWAYSONSTACK */\n\n\n/* The following function deletes the \"minor type\" or semantic value\n** associated with a symbol.  The symbol can be either a terminal\n** or nonterminal. \"yymajor\" is the symbol code, and \"yypminor\" is\n** a pointer to the value to be deleted.  The code used to do the \n** deletions is derived from the %destructor and/or %token_destructor\n** directives of the input grammar.\n*/\nstatic void yy_destructor(\n  yyParser *yypParser,    /* The parser */\n  YYCODETYPE yymajor,     /* Type code for object to destroy */\n  YYMINORTYPE *yypminor   /* The object to be destroyed */\n){\n  sqlite3ParserARG_FETCH\n  sqlite3ParserCTX_FETCH\n  switch( yymajor ){\n    /* Here is inserted the actions which take place when a\n    ** terminal or non-terminal is destroyed.  This can happen\n    ** when the symbol is popped from the stack during a\n    ** reduce or during error processing or when a parser is \n    ** being destroyed before it is finished parsing.\n    **\n    ** Note: during a reduce, the only symbols destroyed are those\n    ** which appear on the RHS of the rule, but which are *not* used\n    ** inside the C code.\n    */\n/********* Begin destructor definitions ***************************************/\n    case 200: /* select */\n    case 234: /* selectnowith */\n    case 235: /* oneselect */\n    case 247: /* values */\n{\nsqlite3SelectDelete(pParse->db, (yypminor->yy539));\n}\n      break;\n    case 211: /* term */\n    case 212: /* expr */\n    case 241: /* where_opt */\n    case 243: /* having_opt */\n    case 255: /* on_opt */\n    case 271: /* case_operand */\n    case 273: /* case_else */\n    case 276: /* vinto */\n    case 283: /* when_clause */\n    case 288: /* key_opt */\n    case 302: /* filter_clause */\n{\nsqlite3ExprDelete(pParse->db, (yypminor->yy202));\n}\n      break;\n    case 216: /* eidlist_opt */\n    case 226: /* sortlist */\n    case 227: /* eidlist */\n    case 239: /* selcollist */\n    case 242: /* groupby_opt */\n    case 244: /* orderby_opt */\n    case 248: /* nexprlist */\n    case 249: /* sclp */\n    case 257: /* exprlist */\n    case 262: /* setlist */\n    case 270: /* paren_exprlist */\n    case 272: /* case_exprlist */\n    case 301: /* part_opt */\n{\nsqlite3ExprListDelete(pParse->db, (yypminor->yy242));\n}\n      break;\n    case 233: /* fullname */\n    case 240: /* from */\n    case 251: /* seltablist */\n    case 252: /* stl_prefix */\n    case 258: /* xfullname */\n{\nsqlite3SrcListDelete(pParse->db, (yypminor->yy47));\n}\n      break;\n    case 236: /* wqlist */\n{\nsqlite3WithDelete(pParse->db, (yypminor->yy131));\n}\n      break;\n    case 246: /* window_clause */\n    case 297: /* windowdefn_list */\n{\nsqlite3WindowListDelete(pParse->db, (yypminor->yy303));\n}\n      break;\n    case 256: /* using_opt */\n    case 259: /* idlist */\n    case 264: /* idlist_opt */\n{\nsqlite3IdListDelete(pParse->db, (yypminor->yy600));\n}\n      break;\n    case 266: /* filter_over */\n    case 298: /* windowdefn */\n    case 299: /* window */\n    case 300: /* frame_opt */\n    case 303: /* over_clause */\n{\nsqlite3WindowDelete(pParse->db, (yypminor->yy303));\n}\n      break;\n    case 279: /* trigger_cmd_list */\n    case 284: /* trigger_cmd */\n{\nsqlite3DeleteTriggerStep(pParse->db, (yypminor->yy447));\n}\n      break;\n    case 281: /* trigger_event */\n{\nsqlite3IdListDelete(pParse->db, (yypminor->yy230).b);\n}\n      break;\n    case 305: /* frame_bound */\n    case 306: /* frame_bound_s */\n    case 307: /* frame_bound_e */\n{\nsqlite3ExprDelete(pParse->db, (yypminor->yy77).pExpr);\n}\n      break;\n/********* End destructor definitions *****************************************/\n    default:  break;   /* If no destructor action specified: do nothing */\n  }\n}\n\n/*\n** Pop the parser's stack once.\n**\n** If there is a destructor routine associated with the token which\n** is popped from the stack, then call it.\n*/\nstatic void yy_pop_parser_stack(yyParser *pParser){\n  yyStackEntry *yytos;\n  assert( pParser->yytos!=0 );\n  assert( pParser->yytos > pParser->yystack );\n  yytos = pParser->yytos--;\n#ifndef NDEBUG\n  if( yyTraceFILE ){\n    fprintf(yyTraceFILE,\"%sPopping %s\\n\",\n      yyTracePrompt,\n      yyTokenName[yytos->major]);\n  }\n#endif\n  yy_destructor(pParser, yytos->major, &yytos->minor);\n}\n\n/*\n** Clear all secondary memory allocations from the parser\n*/\nSQLITE_PRIVATE void sqlite3ParserFinalize(void *p){\n  yyParser *pParser = (yyParser*)p;\n  while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);\n#if YYSTACKDEPTH<=0\n  if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);\n#endif\n}\n\n#ifndef sqlite3Parser_ENGINEALWAYSONSTACK\n/* \n** Deallocate and destroy a parser.  Destructors are called for\n** all stack elements before shutting the parser down.\n**\n** If the YYPARSEFREENEVERNULL macro exists (for example because it\n** is defined in a %include section of the input grammar) then it is\n** assumed that the input pointer is never NULL.\n*/\nSQLITE_PRIVATE void sqlite3ParserFree(\n  void *p,                    /* The parser to be deleted */\n  void (*freeProc)(void*)     /* Function used to reclaim memory */\n){\n#ifndef YYPARSEFREENEVERNULL\n  if( p==0 ) return;\n#endif\n  sqlite3ParserFinalize(p);\n  (*freeProc)(p);\n}\n#endif /* sqlite3Parser_ENGINEALWAYSONSTACK */\n\n/*\n** Return the peak depth of the stack for a parser.\n*/\n#ifdef YYTRACKMAXSTACKDEPTH\nSQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){\n  yyParser *pParser = (yyParser*)p;\n  return pParser->yyhwm;\n}\n#endif\n\n/* This array of booleans keeps track of the parser statement\n** coverage.  The element yycoverage[X][Y] is set when the parser\n** is in state X and has a lookahead token Y.  In a well-tested\n** systems, every element of this matrix should end up being set.\n*/\n#if defined(YYCOVERAGE)\nstatic unsigned char yycoverage[YYNSTATE][YYNTOKEN];\n#endif\n\n/*\n** Write into out a description of every state/lookahead combination that\n**\n**   (1)  has not been used by the parser, and\n**   (2)  is not a syntax error.\n**\n** Return the number of missed state/lookahead combinations.\n*/\n#if defined(YYCOVERAGE)\nSQLITE_PRIVATE int sqlite3ParserCoverage(FILE *out){\n  int stateno, iLookAhead, i;\n  int nMissed = 0;\n  for(stateno=0; stateno<YYNSTATE; stateno++){\n    i = yy_shift_ofst[stateno];\n    for(iLookAhead=0; iLookAhead<YYNTOKEN; iLookAhead++){\n      if( yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;\n      if( yycoverage[stateno][iLookAhead]==0 ) nMissed++;\n      if( out ){\n        fprintf(out,\"State %d lookahead %s %s\\n\", stateno,\n                yyTokenName[iLookAhead],\n                yycoverage[stateno][iLookAhead] ? \"ok\" : \"missed\");\n      }\n    }\n  }\n  return nMissed;\n}\n#endif\n\n/*\n** Find the appropriate action for a parser given the terminal\n** look-ahead token iLookAhead.\n*/\nstatic YYACTIONTYPE yy_find_shift_action(\n  YYCODETYPE iLookAhead,    /* The look-ahead token */\n  YYACTIONTYPE stateno      /* Current state number */\n){\n  int i;\n\n  if( stateno>YY_MAX_SHIFT ) return stateno;\n  assert( stateno <= YY_SHIFT_COUNT );\n#if defined(YYCOVERAGE)\n  yycoverage[stateno][iLookAhead] = 1;\n#endif\n  do{\n    i = yy_shift_ofst[stateno];\n    assert( i>=0 );\n    assert( i<=YY_ACTTAB_COUNT );\n    assert( i+YYNTOKEN<=(int)YY_NLOOKAHEAD );\n    assert( iLookAhead!=YYNOCODE );\n    assert( iLookAhead < YYNTOKEN );\n    i += iLookAhead;\n    assert( i<(int)YY_NLOOKAHEAD );\n    if( yy_lookahead[i]!=iLookAhead ){\n#ifdef YYFALLBACK\n      YYCODETYPE iFallback;            /* Fallback token */\n      assert( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0]) );\n      iFallback = yyFallback[iLookAhead];\n      if( iFallback!=0 ){\n#ifndef NDEBUG\n        if( yyTraceFILE ){\n          fprintf(yyTraceFILE, \"%sFALLBACK %s => %s\\n\",\n             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);\n        }\n#endif\n        assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */\n        iLookAhead = iFallback;\n        continue;\n      }\n#endif\n#ifdef YYWILDCARD\n      {\n        int j = i - iLookAhead + YYWILDCARD;\n        assert( j<(int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])) );\n        if( yy_lookahead[j]==YYWILDCARD && iLookAhead>0 ){\n#ifndef NDEBUG\n          if( yyTraceFILE ){\n            fprintf(yyTraceFILE, \"%sWILDCARD %s => %s\\n\",\n               yyTracePrompt, yyTokenName[iLookAhead],\n               yyTokenName[YYWILDCARD]);\n          }\n#endif /* NDEBUG */\n          return yy_action[j];\n        }\n      }\n#endif /* YYWILDCARD */\n      return yy_default[stateno];\n    }else{\n      assert( i>=0 && i<sizeof(yy_action)/sizeof(yy_action[0]) );\n      return yy_action[i];\n    }\n  }while(1);\n}\n\n/*\n** Find the appropriate action for a parser given the non-terminal\n** look-ahead token iLookAhead.\n*/\nstatic YYACTIONTYPE yy_find_reduce_action(\n  YYACTIONTYPE stateno,     /* Current state number */\n  YYCODETYPE iLookAhead     /* The look-ahead token */\n){\n  int i;\n#ifdef YYERRORSYMBOL\n  if( stateno>YY_REDUCE_COUNT ){\n    return yy_default[stateno];\n  }\n#else\n  assert( stateno<=YY_REDUCE_COUNT );\n#endif\n  i = yy_reduce_ofst[stateno];\n  assert( iLookAhead!=YYNOCODE );\n  i += iLookAhead;\n#ifdef YYERRORSYMBOL\n  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){\n    return yy_default[stateno];\n  }\n#else\n  assert( i>=0 && i<YY_ACTTAB_COUNT );\n  assert( yy_lookahead[i]==iLookAhead );\n#endif\n  return yy_action[i];\n}\n\n/*\n** The following routine is called if the stack overflows.\n*/\nstatic void yyStackOverflow(yyParser *yypParser){\n   sqlite3ParserARG_FETCH\n   sqlite3ParserCTX_FETCH\n#ifndef NDEBUG\n   if( yyTraceFILE ){\n     fprintf(yyTraceFILE,\"%sStack Overflow!\\n\",yyTracePrompt);\n   }\n#endif\n   while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);\n   /* Here code is inserted which will execute if the parser\n   ** stack every overflows */\n/******** Begin %stack_overflow code ******************************************/\n\n  sqlite3ErrorMsg(pParse, \"parser stack overflow\");\n/******** End %stack_overflow code ********************************************/\n   sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument var */\n   sqlite3ParserCTX_STORE\n}\n\n/*\n** Print tracing information for a SHIFT action\n*/\n#ifndef NDEBUG\nstatic void yyTraceShift(yyParser *yypParser, int yyNewState, const char *zTag){\n  if( yyTraceFILE ){\n    if( yyNewState<YYNSTATE ){\n      fprintf(yyTraceFILE,\"%s%s '%s', go to state %d\\n\",\n         yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],\n         yyNewState);\n    }else{\n      fprintf(yyTraceFILE,\"%s%s '%s', pending reduce %d\\n\",\n         yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],\n         yyNewState - YY_MIN_REDUCE);\n    }\n  }\n}\n#else\n# define yyTraceShift(X,Y,Z)\n#endif\n\n/*\n** Perform a shift action.\n*/\nstatic void yy_shift(\n  yyParser *yypParser,          /* The parser to be shifted */\n  YYACTIONTYPE yyNewState,      /* The new state to shift in */\n  YYCODETYPE yyMajor,           /* The major token to shift in */\n  sqlite3ParserTOKENTYPE yyMinor        /* The minor token to shift in */\n){\n  yyStackEntry *yytos;\n  yypParser->yytos++;\n#ifdef YYTRACKMAXSTACKDEPTH\n  if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){\n    yypParser->yyhwm++;\n    assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );\n  }\n#endif\n#if YYSTACKDEPTH>0 \n  if( yypParser->yytos>yypParser->yystackEnd ){\n    yypParser->yytos--;\n    yyStackOverflow(yypParser);\n    return;\n  }\n#else\n  if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){\n    if( yyGrowStack(yypParser) ){\n      yypParser->yytos--;\n      yyStackOverflow(yypParser);\n      return;\n    }\n  }\n#endif\n  if( yyNewState > YY_MAX_SHIFT ){\n    yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;\n  }\n  yytos = yypParser->yytos;\n  yytos->stateno = yyNewState;\n  yytos->major = yyMajor;\n  yytos->minor.yy0 = yyMinor;\n  yyTraceShift(yypParser, yyNewState, \"Shift\");\n}\n\n/* For rule J, yyRuleInfoLhs[J] contains the symbol on the left-hand side\n** of that rule */\nstatic const YYCODETYPE yyRuleInfoLhs[] = {\n   185,  /* (0) explain ::= EXPLAIN */\n   185,  /* (1) explain ::= EXPLAIN QUERY PLAN */\n   184,  /* (2) cmdx ::= cmd */\n   186,  /* (3) cmd ::= BEGIN transtype trans_opt */\n   187,  /* (4) transtype ::= */\n   187,  /* (5) transtype ::= DEFERRED */\n   187,  /* (6) transtype ::= IMMEDIATE */\n   187,  /* (7) transtype ::= EXCLUSIVE */\n   186,  /* (8) cmd ::= COMMIT|END trans_opt */\n   186,  /* (9) cmd ::= ROLLBACK trans_opt */\n   186,  /* (10) cmd ::= SAVEPOINT nm */\n   186,  /* (11) cmd ::= RELEASE savepoint_opt nm */\n   186,  /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */\n   191,  /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */\n   193,  /* (14) createkw ::= CREATE */\n   195,  /* (15) ifnotexists ::= */\n   195,  /* (16) ifnotexists ::= IF NOT EXISTS */\n   194,  /* (17) temp ::= TEMP */\n   194,  /* (18) temp ::= */\n   192,  /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */\n   192,  /* (20) create_table_args ::= AS select */\n   199,  /* (21) table_options ::= */\n   199,  /* (22) table_options ::= WITHOUT nm */\n   201,  /* (23) columnname ::= nm typetoken */\n   203,  /* (24) typetoken ::= */\n   203,  /* (25) typetoken ::= typename LP signed RP */\n   203,  /* (26) typetoken ::= typename LP signed COMMA signed RP */\n   204,  /* (27) typename ::= typename ID|STRING */\n   208,  /* (28) scanpt ::= */\n   209,  /* (29) scantok ::= */\n   210,  /* (30) ccons ::= CONSTRAINT nm */\n   210,  /* (31) ccons ::= DEFAULT scantok term */\n   210,  /* (32) ccons ::= DEFAULT LP expr RP */\n   210,  /* (33) ccons ::= DEFAULT PLUS scantok term */\n   210,  /* (34) ccons ::= DEFAULT MINUS scantok term */\n   210,  /* (35) ccons ::= DEFAULT scantok ID|INDEXED */\n   210,  /* (36) ccons ::= NOT NULL onconf */\n   210,  /* (37) ccons ::= PRIMARY KEY sortorder onconf autoinc */\n   210,  /* (38) ccons ::= UNIQUE onconf */\n   210,  /* (39) ccons ::= CHECK LP expr RP */\n   210,  /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */\n   210,  /* (41) ccons ::= defer_subclause */\n   210,  /* (42) ccons ::= COLLATE ID|STRING */\n   219,  /* (43) generated ::= LP expr RP */\n   219,  /* (44) generated ::= LP expr RP ID */\n   215,  /* (45) autoinc ::= */\n   215,  /* (46) autoinc ::= AUTOINCR */\n   217,  /* (47) refargs ::= */\n   217,  /* (48) refargs ::= refargs refarg */\n   220,  /* (49) refarg ::= MATCH nm */\n   220,  /* (50) refarg ::= ON INSERT refact */\n   220,  /* (51) refarg ::= ON DELETE refact */\n   220,  /* (52) refarg ::= ON UPDATE refact */\n   221,  /* (53) refact ::= SET NULL */\n   221,  /* (54) refact ::= SET DEFAULT */\n   221,  /* (55) refact ::= CASCADE */\n   221,  /* (56) refact ::= RESTRICT */\n   221,  /* (57) refact ::= NO ACTION */\n   218,  /* (58) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */\n   218,  /* (59) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */\n   222,  /* (60) init_deferred_pred_opt ::= */\n   222,  /* (61) init_deferred_pred_opt ::= INITIALLY DEFERRED */\n   222,  /* (62) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */\n   198,  /* (63) conslist_opt ::= */\n   224,  /* (64) tconscomma ::= COMMA */\n   225,  /* (65) tcons ::= CONSTRAINT nm */\n   225,  /* (66) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */\n   225,  /* (67) tcons ::= UNIQUE LP sortlist RP onconf */\n   225,  /* (68) tcons ::= CHECK LP expr RP onconf */\n   225,  /* (69) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */\n   228,  /* (70) defer_subclause_opt ::= */\n   213,  /* (71) onconf ::= */\n   213,  /* (72) onconf ::= ON CONFLICT resolvetype */\n   229,  /* (73) orconf ::= */\n   229,  /* (74) orconf ::= OR resolvetype */\n   230,  /* (75) resolvetype ::= IGNORE */\n   230,  /* (76) resolvetype ::= REPLACE */\n   186,  /* (77) cmd ::= DROP TABLE ifexists fullname */\n   232,  /* (78) ifexists ::= IF EXISTS */\n   232,  /* (79) ifexists ::= */\n   186,  /* (80) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */\n   186,  /* (81) cmd ::= DROP VIEW ifexists fullname */\n   186,  /* (82) cmd ::= select */\n   200,  /* (83) select ::= WITH wqlist selectnowith */\n   200,  /* (84) select ::= WITH RECURSIVE wqlist selectnowith */\n   200,  /* (85) select ::= selectnowith */\n   234,  /* (86) selectnowith ::= selectnowith multiselect_op oneselect */\n   237,  /* (87) multiselect_op ::= UNION */\n   237,  /* (88) multiselect_op ::= UNION ALL */\n   237,  /* (89) multiselect_op ::= EXCEPT|INTERSECT */\n   235,  /* (90) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */\n   235,  /* (91) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */\n   247,  /* (92) values ::= VALUES LP nexprlist RP */\n   247,  /* (93) values ::= values COMMA LP nexprlist RP */\n   238,  /* (94) distinct ::= DISTINCT */\n   238,  /* (95) distinct ::= ALL */\n   238,  /* (96) distinct ::= */\n   249,  /* (97) sclp ::= */\n   239,  /* (98) selcollist ::= sclp scanpt expr scanpt as */\n   239,  /* (99) selcollist ::= sclp scanpt STAR */\n   239,  /* (100) selcollist ::= sclp scanpt nm DOT STAR */\n   250,  /* (101) as ::= AS nm */\n   250,  /* (102) as ::= */\n   240,  /* (103) from ::= */\n   240,  /* (104) from ::= FROM seltablist */\n   252,  /* (105) stl_prefix ::= seltablist joinop */\n   252,  /* (106) stl_prefix ::= */\n   251,  /* (107) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */\n   251,  /* (108) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */\n   251,  /* (109) seltablist ::= stl_prefix LP select RP as on_opt using_opt */\n   251,  /* (110) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */\n   196,  /* (111) dbnm ::= */\n   196,  /* (112) dbnm ::= DOT nm */\n   233,  /* (113) fullname ::= nm */\n   233,  /* (114) fullname ::= nm DOT nm */\n   258,  /* (115) xfullname ::= nm */\n   258,  /* (116) xfullname ::= nm DOT nm */\n   258,  /* (117) xfullname ::= nm DOT nm AS nm */\n   258,  /* (118) xfullname ::= nm AS nm */\n   253,  /* (119) joinop ::= COMMA|JOIN */\n   253,  /* (120) joinop ::= JOIN_KW JOIN */\n   253,  /* (121) joinop ::= JOIN_KW nm JOIN */\n   253,  /* (122) joinop ::= JOIN_KW nm nm JOIN */\n   255,  /* (123) on_opt ::= ON expr */\n   255,  /* (124) on_opt ::= */\n   254,  /* (125) indexed_opt ::= */\n   254,  /* (126) indexed_opt ::= INDEXED BY nm */\n   254,  /* (127) indexed_opt ::= NOT INDEXED */\n   256,  /* (128) using_opt ::= USING LP idlist RP */\n   256,  /* (129) using_opt ::= */\n   244,  /* (130) orderby_opt ::= */\n   244,  /* (131) orderby_opt ::= ORDER BY sortlist */\n   226,  /* (132) sortlist ::= sortlist COMMA expr sortorder nulls */\n   226,  /* (133) sortlist ::= expr sortorder nulls */\n   214,  /* (134) sortorder ::= ASC */\n   214,  /* (135) sortorder ::= DESC */\n   214,  /* (136) sortorder ::= */\n   260,  /* (137) nulls ::= NULLS FIRST */\n   260,  /* (138) nulls ::= NULLS LAST */\n   260,  /* (139) nulls ::= */\n   242,  /* (140) groupby_opt ::= */\n   242,  /* (141) groupby_opt ::= GROUP BY nexprlist */\n   243,  /* (142) having_opt ::= */\n   243,  /* (143) having_opt ::= HAVING expr */\n   245,  /* (144) limit_opt ::= */\n   245,  /* (145) limit_opt ::= LIMIT expr */\n   245,  /* (146) limit_opt ::= LIMIT expr OFFSET expr */\n   245,  /* (147) limit_opt ::= LIMIT expr COMMA expr */\n   186,  /* (148) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */\n   241,  /* (149) where_opt ::= */\n   241,  /* (150) where_opt ::= WHERE expr */\n   186,  /* (151) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */\n   262,  /* (152) setlist ::= setlist COMMA nm EQ expr */\n   262,  /* (153) setlist ::= setlist COMMA LP idlist RP EQ expr */\n   262,  /* (154) setlist ::= nm EQ expr */\n   262,  /* (155) setlist ::= LP idlist RP EQ expr */\n   186,  /* (156) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */\n   186,  /* (157) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */\n   265,  /* (158) upsert ::= */\n   265,  /* (159) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */\n   265,  /* (160) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */\n   265,  /* (161) upsert ::= ON CONFLICT DO NOTHING */\n   263,  /* (162) insert_cmd ::= INSERT orconf */\n   263,  /* (163) insert_cmd ::= REPLACE */\n   264,  /* (164) idlist_opt ::= */\n   264,  /* (165) idlist_opt ::= LP idlist RP */\n   259,  /* (166) idlist ::= idlist COMMA nm */\n   259,  /* (167) idlist ::= nm */\n   212,  /* (168) expr ::= LP expr RP */\n   212,  /* (169) expr ::= ID|INDEXED */\n   212,  /* (170) expr ::= JOIN_KW */\n   212,  /* (171) expr ::= nm DOT nm */\n   212,  /* (172) expr ::= nm DOT nm DOT nm */\n   211,  /* (173) term ::= NULL|FLOAT|BLOB */\n   211,  /* (174) term ::= STRING */\n   211,  /* (175) term ::= INTEGER */\n   212,  /* (176) expr ::= VARIABLE */\n   212,  /* (177) expr ::= expr COLLATE ID|STRING */\n   212,  /* (178) expr ::= CAST LP expr AS typetoken RP */\n   212,  /* (179) expr ::= ID|INDEXED LP distinct exprlist RP */\n   212,  /* (180) expr ::= ID|INDEXED LP STAR RP */\n   212,  /* (181) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */\n   212,  /* (182) expr ::= ID|INDEXED LP STAR RP filter_over */\n   211,  /* (183) term ::= CTIME_KW */\n   212,  /* (184) expr ::= LP nexprlist COMMA expr RP */\n   212,  /* (185) expr ::= expr AND expr */\n   212,  /* (186) expr ::= expr OR expr */\n   212,  /* (187) expr ::= expr LT|GT|GE|LE expr */\n   212,  /* (188) expr ::= expr EQ|NE expr */\n   212,  /* (189) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */\n   212,  /* (190) expr ::= expr PLUS|MINUS expr */\n   212,  /* (191) expr ::= expr STAR|SLASH|REM expr */\n   212,  /* (192) expr ::= expr CONCAT expr */\n   267,  /* (193) likeop ::= NOT LIKE_KW|MATCH */\n   212,  /* (194) expr ::= expr likeop expr */\n   212,  /* (195) expr ::= expr likeop expr ESCAPE expr */\n   212,  /* (196) expr ::= expr ISNULL|NOTNULL */\n   212,  /* (197) expr ::= expr NOT NULL */\n   212,  /* (198) expr ::= expr IS expr */\n   212,  /* (199) expr ::= expr IS NOT expr */\n   212,  /* (200) expr ::= NOT expr */\n   212,  /* (201) expr ::= BITNOT expr */\n   212,  /* (202) expr ::= PLUS|MINUS expr */\n   268,  /* (203) between_op ::= BETWEEN */\n   268,  /* (204) between_op ::= NOT BETWEEN */\n   212,  /* (205) expr ::= expr between_op expr AND expr */\n   269,  /* (206) in_op ::= IN */\n   269,  /* (207) in_op ::= NOT IN */\n   212,  /* (208) expr ::= expr in_op LP exprlist RP */\n   212,  /* (209) expr ::= LP select RP */\n   212,  /* (210) expr ::= expr in_op LP select RP */\n   212,  /* (211) expr ::= expr in_op nm dbnm paren_exprlist */\n   212,  /* (212) expr ::= EXISTS LP select RP */\n   212,  /* (213) expr ::= CASE case_operand case_exprlist case_else END */\n   272,  /* (214) case_exprlist ::= case_exprlist WHEN expr THEN expr */\n   272,  /* (215) case_exprlist ::= WHEN expr THEN expr */\n   273,  /* (216) case_else ::= ELSE expr */\n   273,  /* (217) case_else ::= */\n   271,  /* (218) case_operand ::= expr */\n   271,  /* (219) case_operand ::= */\n   257,  /* (220) exprlist ::= */\n   248,  /* (221) nexprlist ::= nexprlist COMMA expr */\n   248,  /* (222) nexprlist ::= expr */\n   270,  /* (223) paren_exprlist ::= */\n   270,  /* (224) paren_exprlist ::= LP exprlist RP */\n   186,  /* (225) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */\n   274,  /* (226) uniqueflag ::= UNIQUE */\n   274,  /* (227) uniqueflag ::= */\n   216,  /* (228) eidlist_opt ::= */\n   216,  /* (229) eidlist_opt ::= LP eidlist RP */\n   227,  /* (230) eidlist ::= eidlist COMMA nm collate sortorder */\n   227,  /* (231) eidlist ::= nm collate sortorder */\n   275,  /* (232) collate ::= */\n   275,  /* (233) collate ::= COLLATE ID|STRING */\n   186,  /* (234) cmd ::= DROP INDEX ifexists fullname */\n   186,  /* (235) cmd ::= VACUUM vinto */\n   186,  /* (236) cmd ::= VACUUM nm vinto */\n   276,  /* (237) vinto ::= INTO expr */\n   276,  /* (238) vinto ::= */\n   186,  /* (239) cmd ::= PRAGMA nm dbnm */\n   186,  /* (240) cmd ::= PRAGMA nm dbnm EQ nmnum */\n   186,  /* (241) cmd ::= PRAGMA nm dbnm LP nmnum RP */\n   186,  /* (242) cmd ::= PRAGMA nm dbnm EQ minus_num */\n   186,  /* (243) cmd ::= PRAGMA nm dbnm LP minus_num RP */\n   206,  /* (244) plus_num ::= PLUS INTEGER|FLOAT */\n   207,  /* (245) minus_num ::= MINUS INTEGER|FLOAT */\n   186,  /* (246) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */\n   278,  /* (247) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */\n   280,  /* (248) trigger_time ::= BEFORE|AFTER */\n   280,  /* (249) trigger_time ::= INSTEAD OF */\n   280,  /* (250) trigger_time ::= */\n   281,  /* (251) trigger_event ::= DELETE|INSERT */\n   281,  /* (252) trigger_event ::= UPDATE */\n   281,  /* (253) trigger_event ::= UPDATE OF idlist */\n   283,  /* (254) when_clause ::= */\n   283,  /* (255) when_clause ::= WHEN expr */\n   279,  /* (256) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */\n   279,  /* (257) trigger_cmd_list ::= trigger_cmd SEMI */\n   285,  /* (258) trnm ::= nm DOT nm */\n   286,  /* (259) tridxby ::= INDEXED BY nm */\n   286,  /* (260) tridxby ::= NOT INDEXED */\n   284,  /* (261) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */\n   284,  /* (262) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */\n   284,  /* (263) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */\n   284,  /* (264) trigger_cmd ::= scanpt select scanpt */\n   212,  /* (265) expr ::= RAISE LP IGNORE RP */\n   212,  /* (266) expr ::= RAISE LP raisetype COMMA nm RP */\n   231,  /* (267) raisetype ::= ROLLBACK */\n   231,  /* (268) raisetype ::= ABORT */\n   231,  /* (269) raisetype ::= FAIL */\n   186,  /* (270) cmd ::= DROP TRIGGER ifexists fullname */\n   186,  /* (271) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */\n   186,  /* (272) cmd ::= DETACH database_kw_opt expr */\n   288,  /* (273) key_opt ::= */\n   288,  /* (274) key_opt ::= KEY expr */\n   186,  /* (275) cmd ::= REINDEX */\n   186,  /* (276) cmd ::= REINDEX nm dbnm */\n   186,  /* (277) cmd ::= ANALYZE */\n   186,  /* (278) cmd ::= ANALYZE nm dbnm */\n   186,  /* (279) cmd ::= ALTER TABLE fullname RENAME TO nm */\n   186,  /* (280) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */\n   289,  /* (281) add_column_fullname ::= fullname */\n   186,  /* (282) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */\n   186,  /* (283) cmd ::= create_vtab */\n   186,  /* (284) cmd ::= create_vtab LP vtabarglist RP */\n   291,  /* (285) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */\n   293,  /* (286) vtabarg ::= */\n   294,  /* (287) vtabargtoken ::= ANY */\n   294,  /* (288) vtabargtoken ::= lp anylist RP */\n   295,  /* (289) lp ::= LP */\n   261,  /* (290) with ::= WITH wqlist */\n   261,  /* (291) with ::= WITH RECURSIVE wqlist */\n   236,  /* (292) wqlist ::= nm eidlist_opt AS LP select RP */\n   236,  /* (293) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */\n   297,  /* (294) windowdefn_list ::= windowdefn */\n   297,  /* (295) windowdefn_list ::= windowdefn_list COMMA windowdefn */\n   298,  /* (296) windowdefn ::= nm AS LP window RP */\n   299,  /* (297) window ::= PARTITION BY nexprlist orderby_opt frame_opt */\n   299,  /* (298) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */\n   299,  /* (299) window ::= ORDER BY sortlist frame_opt */\n   299,  /* (300) window ::= nm ORDER BY sortlist frame_opt */\n   299,  /* (301) window ::= frame_opt */\n   299,  /* (302) window ::= nm frame_opt */\n   300,  /* (303) frame_opt ::= */\n   300,  /* (304) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */\n   300,  /* (305) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */\n   304,  /* (306) range_or_rows ::= RANGE|ROWS|GROUPS */\n   306,  /* (307) frame_bound_s ::= frame_bound */\n   306,  /* (308) frame_bound_s ::= UNBOUNDED PRECEDING */\n   307,  /* (309) frame_bound_e ::= frame_bound */\n   307,  /* (310) frame_bound_e ::= UNBOUNDED FOLLOWING */\n   305,  /* (311) frame_bound ::= expr PRECEDING|FOLLOWING */\n   305,  /* (312) frame_bound ::= CURRENT ROW */\n   308,  /* (313) frame_exclude_opt ::= */\n   308,  /* (314) frame_exclude_opt ::= EXCLUDE frame_exclude */\n   309,  /* (315) frame_exclude ::= NO OTHERS */\n   309,  /* (316) frame_exclude ::= CURRENT ROW */\n   309,  /* (317) frame_exclude ::= GROUP|TIES */\n   246,  /* (318) window_clause ::= WINDOW windowdefn_list */\n   266,  /* (319) filter_over ::= filter_clause over_clause */\n   266,  /* (320) filter_over ::= over_clause */\n   266,  /* (321) filter_over ::= filter_clause */\n   303,  /* (322) over_clause ::= OVER LP window RP */\n   303,  /* (323) over_clause ::= OVER nm */\n   302,  /* (324) filter_clause ::= FILTER LP WHERE expr RP */\n   181,  /* (325) input ::= cmdlist */\n   182,  /* (326) cmdlist ::= cmdlist ecmd */\n   182,  /* (327) cmdlist ::= ecmd */\n   183,  /* (328) ecmd ::= SEMI */\n   183,  /* (329) ecmd ::= cmdx SEMI */\n   183,  /* (330) ecmd ::= explain cmdx SEMI */\n   188,  /* (331) trans_opt ::= */\n   188,  /* (332) trans_opt ::= TRANSACTION */\n   188,  /* (333) trans_opt ::= TRANSACTION nm */\n   190,  /* (334) savepoint_opt ::= SAVEPOINT */\n   190,  /* (335) savepoint_opt ::= */\n   186,  /* (336) cmd ::= create_table create_table_args */\n   197,  /* (337) columnlist ::= columnlist COMMA columnname carglist */\n   197,  /* (338) columnlist ::= columnname carglist */\n   189,  /* (339) nm ::= ID|INDEXED */\n   189,  /* (340) nm ::= STRING */\n   189,  /* (341) nm ::= JOIN_KW */\n   203,  /* (342) typetoken ::= typename */\n   204,  /* (343) typename ::= ID|STRING */\n   205,  /* (344) signed ::= plus_num */\n   205,  /* (345) signed ::= minus_num */\n   202,  /* (346) carglist ::= carglist ccons */\n   202,  /* (347) carglist ::= */\n   210,  /* (348) ccons ::= NULL onconf */\n   210,  /* (349) ccons ::= GENERATED ALWAYS AS generated */\n   210,  /* (350) ccons ::= AS generated */\n   198,  /* (351) conslist_opt ::= COMMA conslist */\n   223,  /* (352) conslist ::= conslist tconscomma tcons */\n   223,  /* (353) conslist ::= tcons */\n   224,  /* (354) tconscomma ::= */\n   228,  /* (355) defer_subclause_opt ::= defer_subclause */\n   230,  /* (356) resolvetype ::= raisetype */\n   234,  /* (357) selectnowith ::= oneselect */\n   235,  /* (358) oneselect ::= values */\n   249,  /* (359) sclp ::= selcollist COMMA */\n   250,  /* (360) as ::= ID|STRING */\n   212,  /* (361) expr ::= term */\n   267,  /* (362) likeop ::= LIKE_KW|MATCH */\n   257,  /* (363) exprlist ::= nexprlist */\n   277,  /* (364) nmnum ::= plus_num */\n   277,  /* (365) nmnum ::= nm */\n   277,  /* (366) nmnum ::= ON */\n   277,  /* (367) nmnum ::= DELETE */\n   277,  /* (368) nmnum ::= DEFAULT */\n   206,  /* (369) plus_num ::= INTEGER|FLOAT */\n   282,  /* (370) foreach_clause ::= */\n   282,  /* (371) foreach_clause ::= FOR EACH ROW */\n   285,  /* (372) trnm ::= nm */\n   286,  /* (373) tridxby ::= */\n   287,  /* (374) database_kw_opt ::= DATABASE */\n   287,  /* (375) database_kw_opt ::= */\n   290,  /* (376) kwcolumn_opt ::= */\n   290,  /* (377) kwcolumn_opt ::= COLUMNKW */\n   292,  /* (378) vtabarglist ::= vtabarg */\n   292,  /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */\n   293,  /* (380) vtabarg ::= vtabarg vtabargtoken */\n   296,  /* (381) anylist ::= */\n   296,  /* (382) anylist ::= anylist LP anylist RP */\n   296,  /* (383) anylist ::= anylist ANY */\n   261,  /* (384) with ::= */\n};\n\n/* For rule J, yyRuleInfoNRhs[J] contains the negative of the number\n** of symbols on the right-hand side of that rule. */\nstatic const signed char yyRuleInfoNRhs[] = {\n   -1,  /* (0) explain ::= EXPLAIN */\n   -3,  /* (1) explain ::= EXPLAIN QUERY PLAN */\n   -1,  /* (2) cmdx ::= cmd */\n   -3,  /* (3) cmd ::= BEGIN transtype trans_opt */\n    0,  /* (4) transtype ::= */\n   -1,  /* (5) transtype ::= DEFERRED */\n   -1,  /* (6) transtype ::= IMMEDIATE */\n   -1,  /* (7) transtype ::= EXCLUSIVE */\n   -2,  /* (8) cmd ::= COMMIT|END trans_opt */\n   -2,  /* (9) cmd ::= ROLLBACK trans_opt */\n   -2,  /* (10) cmd ::= SAVEPOINT nm */\n   -3,  /* (11) cmd ::= RELEASE savepoint_opt nm */\n   -5,  /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */\n   -6,  /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */\n   -1,  /* (14) createkw ::= CREATE */\n    0,  /* (15) ifnotexists ::= */\n   -3,  /* (16) ifnotexists ::= IF NOT EXISTS */\n   -1,  /* (17) temp ::= TEMP */\n    0,  /* (18) temp ::= */\n   -5,  /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */\n   -2,  /* (20) create_table_args ::= AS select */\n    0,  /* (21) table_options ::= */\n   -2,  /* (22) table_options ::= WITHOUT nm */\n   -2,  /* (23) columnname ::= nm typetoken */\n    0,  /* (24) typetoken ::= */\n   -4,  /* (25) typetoken ::= typename LP signed RP */\n   -6,  /* (26) typetoken ::= typename LP signed COMMA signed RP */\n   -2,  /* (27) typename ::= typename ID|STRING */\n    0,  /* (28) scanpt ::= */\n    0,  /* (29) scantok ::= */\n   -2,  /* (30) ccons ::= CONSTRAINT nm */\n   -3,  /* (31) ccons ::= DEFAULT scantok term */\n   -4,  /* (32) ccons ::= DEFAULT LP expr RP */\n   -4,  /* (33) ccons ::= DEFAULT PLUS scantok term */\n   -4,  /* (34) ccons ::= DEFAULT MINUS scantok term */\n   -3,  /* (35) ccons ::= DEFAULT scantok ID|INDEXED */\n   -3,  /* (36) ccons ::= NOT NULL onconf */\n   -5,  /* (37) ccons ::= PRIMARY KEY sortorder onconf autoinc */\n   -2,  /* (38) ccons ::= UNIQUE onconf */\n   -4,  /* (39) ccons ::= CHECK LP expr RP */\n   -4,  /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */\n   -1,  /* (41) ccons ::= defer_subclause */\n   -2,  /* (42) ccons ::= COLLATE ID|STRING */\n   -3,  /* (43) generated ::= LP expr RP */\n   -4,  /* (44) generated ::= LP expr RP ID */\n    0,  /* (45) autoinc ::= */\n   -1,  /* (46) autoinc ::= AUTOINCR */\n    0,  /* (47) refargs ::= */\n   -2,  /* (48) refargs ::= refargs refarg */\n   -2,  /* (49) refarg ::= MATCH nm */\n   -3,  /* (50) refarg ::= ON INSERT refact */\n   -3,  /* (51) refarg ::= ON DELETE refact */\n   -3,  /* (52) refarg ::= ON UPDATE refact */\n   -2,  /* (53) refact ::= SET NULL */\n   -2,  /* (54) refact ::= SET DEFAULT */\n   -1,  /* (55) refact ::= CASCADE */\n   -1,  /* (56) refact ::= RESTRICT */\n   -2,  /* (57) refact ::= NO ACTION */\n   -3,  /* (58) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */\n   -2,  /* (59) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */\n    0,  /* (60) init_deferred_pred_opt ::= */\n   -2,  /* (61) init_deferred_pred_opt ::= INITIALLY DEFERRED */\n   -2,  /* (62) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */\n    0,  /* (63) conslist_opt ::= */\n   -1,  /* (64) tconscomma ::= COMMA */\n   -2,  /* (65) tcons ::= CONSTRAINT nm */\n   -7,  /* (66) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */\n   -5,  /* (67) tcons ::= UNIQUE LP sortlist RP onconf */\n   -5,  /* (68) tcons ::= CHECK LP expr RP onconf */\n  -10,  /* (69) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */\n    0,  /* (70) defer_subclause_opt ::= */\n    0,  /* (71) onconf ::= */\n   -3,  /* (72) onconf ::= ON CONFLICT resolvetype */\n    0,  /* (73) orconf ::= */\n   -2,  /* (74) orconf ::= OR resolvetype */\n   -1,  /* (75) resolvetype ::= IGNORE */\n   -1,  /* (76) resolvetype ::= REPLACE */\n   -4,  /* (77) cmd ::= DROP TABLE ifexists fullname */\n   -2,  /* (78) ifexists ::= IF EXISTS */\n    0,  /* (79) ifexists ::= */\n   -9,  /* (80) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */\n   -4,  /* (81) cmd ::= DROP VIEW ifexists fullname */\n   -1,  /* (82) cmd ::= select */\n   -3,  /* (83) select ::= WITH wqlist selectnowith */\n   -4,  /* (84) select ::= WITH RECURSIVE wqlist selectnowith */\n   -1,  /* (85) select ::= selectnowith */\n   -3,  /* (86) selectnowith ::= selectnowith multiselect_op oneselect */\n   -1,  /* (87) multiselect_op ::= UNION */\n   -2,  /* (88) multiselect_op ::= UNION ALL */\n   -1,  /* (89) multiselect_op ::= EXCEPT|INTERSECT */\n   -9,  /* (90) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */\n  -10,  /* (91) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */\n   -4,  /* (92) values ::= VALUES LP nexprlist RP */\n   -5,  /* (93) values ::= values COMMA LP nexprlist RP */\n   -1,  /* (94) distinct ::= DISTINCT */\n   -1,  /* (95) distinct ::= ALL */\n    0,  /* (96) distinct ::= */\n    0,  /* (97) sclp ::= */\n   -5,  /* (98) selcollist ::= sclp scanpt expr scanpt as */\n   -3,  /* (99) selcollist ::= sclp scanpt STAR */\n   -5,  /* (100) selcollist ::= sclp scanpt nm DOT STAR */\n   -2,  /* (101) as ::= AS nm */\n    0,  /* (102) as ::= */\n    0,  /* (103) from ::= */\n   -2,  /* (104) from ::= FROM seltablist */\n   -2,  /* (105) stl_prefix ::= seltablist joinop */\n    0,  /* (106) stl_prefix ::= */\n   -7,  /* (107) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */\n   -9,  /* (108) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */\n   -7,  /* (109) seltablist ::= stl_prefix LP select RP as on_opt using_opt */\n   -7,  /* (110) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */\n    0,  /* (111) dbnm ::= */\n   -2,  /* (112) dbnm ::= DOT nm */\n   -1,  /* (113) fullname ::= nm */\n   -3,  /* (114) fullname ::= nm DOT nm */\n   -1,  /* (115) xfullname ::= nm */\n   -3,  /* (116) xfullname ::= nm DOT nm */\n   -5,  /* (117) xfullname ::= nm DOT nm AS nm */\n   -3,  /* (118) xfullname ::= nm AS nm */\n   -1,  /* (119) joinop ::= COMMA|JOIN */\n   -2,  /* (120) joinop ::= JOIN_KW JOIN */\n   -3,  /* (121) joinop ::= JOIN_KW nm JOIN */\n   -4,  /* (122) joinop ::= JOIN_KW nm nm JOIN */\n   -2,  /* (123) on_opt ::= ON expr */\n    0,  /* (124) on_opt ::= */\n    0,  /* (125) indexed_opt ::= */\n   -3,  /* (126) indexed_opt ::= INDEXED BY nm */\n   -2,  /* (127) indexed_opt ::= NOT INDEXED */\n   -4,  /* (128) using_opt ::= USING LP idlist RP */\n    0,  /* (129) using_opt ::= */\n    0,  /* (130) orderby_opt ::= */\n   -3,  /* (131) orderby_opt ::= ORDER BY sortlist */\n   -5,  /* (132) sortlist ::= sortlist COMMA expr sortorder nulls */\n   -3,  /* (133) sortlist ::= expr sortorder nulls */\n   -1,  /* (134) sortorder ::= ASC */\n   -1,  /* (135) sortorder ::= DESC */\n    0,  /* (136) sortorder ::= */\n   -2,  /* (137) nulls ::= NULLS FIRST */\n   -2,  /* (138) nulls ::= NULLS LAST */\n    0,  /* (139) nulls ::= */\n    0,  /* (140) groupby_opt ::= */\n   -3,  /* (141) groupby_opt ::= GROUP BY nexprlist */\n    0,  /* (142) having_opt ::= */\n   -2,  /* (143) having_opt ::= HAVING expr */\n    0,  /* (144) limit_opt ::= */\n   -2,  /* (145) limit_opt ::= LIMIT expr */\n   -4,  /* (146) limit_opt ::= LIMIT expr OFFSET expr */\n   -4,  /* (147) limit_opt ::= LIMIT expr COMMA expr */\n   -6,  /* (148) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */\n    0,  /* (149) where_opt ::= */\n   -2,  /* (150) where_opt ::= WHERE expr */\n   -8,  /* (151) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */\n   -5,  /* (152) setlist ::= setlist COMMA nm EQ expr */\n   -7,  /* (153) setlist ::= setlist COMMA LP idlist RP EQ expr */\n   -3,  /* (154) setlist ::= nm EQ expr */\n   -5,  /* (155) setlist ::= LP idlist RP EQ expr */\n   -7,  /* (156) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */\n   -7,  /* (157) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */\n    0,  /* (158) upsert ::= */\n  -11,  /* (159) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */\n   -8,  /* (160) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */\n   -4,  /* (161) upsert ::= ON CONFLICT DO NOTHING */\n   -2,  /* (162) insert_cmd ::= INSERT orconf */\n   -1,  /* (163) insert_cmd ::= REPLACE */\n    0,  /* (164) idlist_opt ::= */\n   -3,  /* (165) idlist_opt ::= LP idlist RP */\n   -3,  /* (166) idlist ::= idlist COMMA nm */\n   -1,  /* (167) idlist ::= nm */\n   -3,  /* (168) expr ::= LP expr RP */\n   -1,  /* (169) expr ::= ID|INDEXED */\n   -1,  /* (170) expr ::= JOIN_KW */\n   -3,  /* (171) expr ::= nm DOT nm */\n   -5,  /* (172) expr ::= nm DOT nm DOT nm */\n   -1,  /* (173) term ::= NULL|FLOAT|BLOB */\n   -1,  /* (174) term ::= STRING */\n   -1,  /* (175) term ::= INTEGER */\n   -1,  /* (176) expr ::= VARIABLE */\n   -3,  /* (177) expr ::= expr COLLATE ID|STRING */\n   -6,  /* (178) expr ::= CAST LP expr AS typetoken RP */\n   -5,  /* (179) expr ::= ID|INDEXED LP distinct exprlist RP */\n   -4,  /* (180) expr ::= ID|INDEXED LP STAR RP */\n   -6,  /* (181) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */\n   -5,  /* (182) expr ::= ID|INDEXED LP STAR RP filter_over */\n   -1,  /* (183) term ::= CTIME_KW */\n   -5,  /* (184) expr ::= LP nexprlist COMMA expr RP */\n   -3,  /* (185) expr ::= expr AND expr */\n   -3,  /* (186) expr ::= expr OR expr */\n   -3,  /* (187) expr ::= expr LT|GT|GE|LE expr */\n   -3,  /* (188) expr ::= expr EQ|NE expr */\n   -3,  /* (189) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */\n   -3,  /* (190) expr ::= expr PLUS|MINUS expr */\n   -3,  /* (191) expr ::= expr STAR|SLASH|REM expr */\n   -3,  /* (192) expr ::= expr CONCAT expr */\n   -2,  /* (193) likeop ::= NOT LIKE_KW|MATCH */\n   -3,  /* (194) expr ::= expr likeop expr */\n   -5,  /* (195) expr ::= expr likeop expr ESCAPE expr */\n   -2,  /* (196) expr ::= expr ISNULL|NOTNULL */\n   -3,  /* (197) expr ::= expr NOT NULL */\n   -3,  /* (198) expr ::= expr IS expr */\n   -4,  /* (199) expr ::= expr IS NOT expr */\n   -2,  /* (200) expr ::= NOT expr */\n   -2,  /* (201) expr ::= BITNOT expr */\n   -2,  /* (202) expr ::= PLUS|MINUS expr */\n   -1,  /* (203) between_op ::= BETWEEN */\n   -2,  /* (204) between_op ::= NOT BETWEEN */\n   -5,  /* (205) expr ::= expr between_op expr AND expr */\n   -1,  /* (206) in_op ::= IN */\n   -2,  /* (207) in_op ::= NOT IN */\n   -5,  /* (208) expr ::= expr in_op LP exprlist RP */\n   -3,  /* (209) expr ::= LP select RP */\n   -5,  /* (210) expr ::= expr in_op LP select RP */\n   -5,  /* (211) expr ::= expr in_op nm dbnm paren_exprlist */\n   -4,  /* (212) expr ::= EXISTS LP select RP */\n   -5,  /* (213) expr ::= CASE case_operand case_exprlist case_else END */\n   -5,  /* (214) case_exprlist ::= case_exprlist WHEN expr THEN expr */\n   -4,  /* (215) case_exprlist ::= WHEN expr THEN expr */\n   -2,  /* (216) case_else ::= ELSE expr */\n    0,  /* (217) case_else ::= */\n   -1,  /* (218) case_operand ::= expr */\n    0,  /* (219) case_operand ::= */\n    0,  /* (220) exprlist ::= */\n   -3,  /* (221) nexprlist ::= nexprlist COMMA expr */\n   -1,  /* (222) nexprlist ::= expr */\n    0,  /* (223) paren_exprlist ::= */\n   -3,  /* (224) paren_exprlist ::= LP exprlist RP */\n  -12,  /* (225) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */\n   -1,  /* (226) uniqueflag ::= UNIQUE */\n    0,  /* (227) uniqueflag ::= */\n    0,  /* (228) eidlist_opt ::= */\n   -3,  /* (229) eidlist_opt ::= LP eidlist RP */\n   -5,  /* (230) eidlist ::= eidlist COMMA nm collate sortorder */\n   -3,  /* (231) eidlist ::= nm collate sortorder */\n    0,  /* (232) collate ::= */\n   -2,  /* (233) collate ::= COLLATE ID|STRING */\n   -4,  /* (234) cmd ::= DROP INDEX ifexists fullname */\n   -2,  /* (235) cmd ::= VACUUM vinto */\n   -3,  /* (236) cmd ::= VACUUM nm vinto */\n   -2,  /* (237) vinto ::= INTO expr */\n    0,  /* (238) vinto ::= */\n   -3,  /* (239) cmd ::= PRAGMA nm dbnm */\n   -5,  /* (240) cmd ::= PRAGMA nm dbnm EQ nmnum */\n   -6,  /* (241) cmd ::= PRAGMA nm dbnm LP nmnum RP */\n   -5,  /* (242) cmd ::= PRAGMA nm dbnm EQ minus_num */\n   -6,  /* (243) cmd ::= PRAGMA nm dbnm LP minus_num RP */\n   -2,  /* (244) plus_num ::= PLUS INTEGER|FLOAT */\n   -2,  /* (245) minus_num ::= MINUS INTEGER|FLOAT */\n   -5,  /* (246) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */\n  -11,  /* (247) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */\n   -1,  /* (248) trigger_time ::= BEFORE|AFTER */\n   -2,  /* (249) trigger_time ::= INSTEAD OF */\n    0,  /* (250) trigger_time ::= */\n   -1,  /* (251) trigger_event ::= DELETE|INSERT */\n   -1,  /* (252) trigger_event ::= UPDATE */\n   -3,  /* (253) trigger_event ::= UPDATE OF idlist */\n    0,  /* (254) when_clause ::= */\n   -2,  /* (255) when_clause ::= WHEN expr */\n   -3,  /* (256) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */\n   -2,  /* (257) trigger_cmd_list ::= trigger_cmd SEMI */\n   -3,  /* (258) trnm ::= nm DOT nm */\n   -3,  /* (259) tridxby ::= INDEXED BY nm */\n   -2,  /* (260) tridxby ::= NOT INDEXED */\n   -8,  /* (261) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */\n   -8,  /* (262) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */\n   -6,  /* (263) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */\n   -3,  /* (264) trigger_cmd ::= scanpt select scanpt */\n   -4,  /* (265) expr ::= RAISE LP IGNORE RP */\n   -6,  /* (266) expr ::= RAISE LP raisetype COMMA nm RP */\n   -1,  /* (267) raisetype ::= ROLLBACK */\n   -1,  /* (268) raisetype ::= ABORT */\n   -1,  /* (269) raisetype ::= FAIL */\n   -4,  /* (270) cmd ::= DROP TRIGGER ifexists fullname */\n   -6,  /* (271) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */\n   -3,  /* (272) cmd ::= DETACH database_kw_opt expr */\n    0,  /* (273) key_opt ::= */\n   -2,  /* (274) key_opt ::= KEY expr */\n   -1,  /* (275) cmd ::= REINDEX */\n   -3,  /* (276) cmd ::= REINDEX nm dbnm */\n   -1,  /* (277) cmd ::= ANALYZE */\n   -3,  /* (278) cmd ::= ANALYZE nm dbnm */\n   -6,  /* (279) cmd ::= ALTER TABLE fullname RENAME TO nm */\n   -7,  /* (280) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */\n   -1,  /* (281) add_column_fullname ::= fullname */\n   -8,  /* (282) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */\n   -1,  /* (283) cmd ::= create_vtab */\n   -4,  /* (284) cmd ::= create_vtab LP vtabarglist RP */\n   -8,  /* (285) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */\n    0,  /* (286) vtabarg ::= */\n   -1,  /* (287) vtabargtoken ::= ANY */\n   -3,  /* (288) vtabargtoken ::= lp anylist RP */\n   -1,  /* (289) lp ::= LP */\n   -2,  /* (290) with ::= WITH wqlist */\n   -3,  /* (291) with ::= WITH RECURSIVE wqlist */\n   -6,  /* (292) wqlist ::= nm eidlist_opt AS LP select RP */\n   -8,  /* (293) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */\n   -1,  /* (294) windowdefn_list ::= windowdefn */\n   -3,  /* (295) windowdefn_list ::= windowdefn_list COMMA windowdefn */\n   -5,  /* (296) windowdefn ::= nm AS LP window RP */\n   -5,  /* (297) window ::= PARTITION BY nexprlist orderby_opt frame_opt */\n   -6,  /* (298) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */\n   -4,  /* (299) window ::= ORDER BY sortlist frame_opt */\n   -5,  /* (300) window ::= nm ORDER BY sortlist frame_opt */\n   -1,  /* (301) window ::= frame_opt */\n   -2,  /* (302) window ::= nm frame_opt */\n    0,  /* (303) frame_opt ::= */\n   -3,  /* (304) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */\n   -6,  /* (305) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */\n   -1,  /* (306) range_or_rows ::= RANGE|ROWS|GROUPS */\n   -1,  /* (307) frame_bound_s ::= frame_bound */\n   -2,  /* (308) frame_bound_s ::= UNBOUNDED PRECEDING */\n   -1,  /* (309) frame_bound_e ::= frame_bound */\n   -2,  /* (310) frame_bound_e ::= UNBOUNDED FOLLOWING */\n   -2,  /* (311) frame_bound ::= expr PRECEDING|FOLLOWING */\n   -2,  /* (312) frame_bound ::= CURRENT ROW */\n    0,  /* (313) frame_exclude_opt ::= */\n   -2,  /* (314) frame_exclude_opt ::= EXCLUDE frame_exclude */\n   -2,  /* (315) frame_exclude ::= NO OTHERS */\n   -2,  /* (316) frame_exclude ::= CURRENT ROW */\n   -1,  /* (317) frame_exclude ::= GROUP|TIES */\n   -2,  /* (318) window_clause ::= WINDOW windowdefn_list */\n   -2,  /* (319) filter_over ::= filter_clause over_clause */\n   -1,  /* (320) filter_over ::= over_clause */\n   -1,  /* (321) filter_over ::= filter_clause */\n   -4,  /* (322) over_clause ::= OVER LP window RP */\n   -2,  /* (323) over_clause ::= OVER nm */\n   -5,  /* (324) filter_clause ::= FILTER LP WHERE expr RP */\n   -1,  /* (325) input ::= cmdlist */\n   -2,  /* (326) cmdlist ::= cmdlist ecmd */\n   -1,  /* (327) cmdlist ::= ecmd */\n   -1,  /* (328) ecmd ::= SEMI */\n   -2,  /* (329) ecmd ::= cmdx SEMI */\n   -3,  /* (330) ecmd ::= explain cmdx SEMI */\n    0,  /* (331) trans_opt ::= */\n   -1,  /* (332) trans_opt ::= TRANSACTION */\n   -2,  /* (333) trans_opt ::= TRANSACTION nm */\n   -1,  /* (334) savepoint_opt ::= SAVEPOINT */\n    0,  /* (335) savepoint_opt ::= */\n   -2,  /* (336) cmd ::= create_table create_table_args */\n   -4,  /* (337) columnlist ::= columnlist COMMA columnname carglist */\n   -2,  /* (338) columnlist ::= columnname carglist */\n   -1,  /* (339) nm ::= ID|INDEXED */\n   -1,  /* (340) nm ::= STRING */\n   -1,  /* (341) nm ::= JOIN_KW */\n   -1,  /* (342) typetoken ::= typename */\n   -1,  /* (343) typename ::= ID|STRING */\n   -1,  /* (344) signed ::= plus_num */\n   -1,  /* (345) signed ::= minus_num */\n   -2,  /* (346) carglist ::= carglist ccons */\n    0,  /* (347) carglist ::= */\n   -2,  /* (348) ccons ::= NULL onconf */\n   -4,  /* (349) ccons ::= GENERATED ALWAYS AS generated */\n   -2,  /* (350) ccons ::= AS generated */\n   -2,  /* (351) conslist_opt ::= COMMA conslist */\n   -3,  /* (352) conslist ::= conslist tconscomma tcons */\n   -1,  /* (353) conslist ::= tcons */\n    0,  /* (354) tconscomma ::= */\n   -1,  /* (355) defer_subclause_opt ::= defer_subclause */\n   -1,  /* (356) resolvetype ::= raisetype */\n   -1,  /* (357) selectnowith ::= oneselect */\n   -1,  /* (358) oneselect ::= values */\n   -2,  /* (359) sclp ::= selcollist COMMA */\n   -1,  /* (360) as ::= ID|STRING */\n   -1,  /* (361) expr ::= term */\n   -1,  /* (362) likeop ::= LIKE_KW|MATCH */\n   -1,  /* (363) exprlist ::= nexprlist */\n   -1,  /* (364) nmnum ::= plus_num */\n   -1,  /* (365) nmnum ::= nm */\n   -1,  /* (366) nmnum ::= ON */\n   -1,  /* (367) nmnum ::= DELETE */\n   -1,  /* (368) nmnum ::= DEFAULT */\n   -1,  /* (369) plus_num ::= INTEGER|FLOAT */\n    0,  /* (370) foreach_clause ::= */\n   -3,  /* (371) foreach_clause ::= FOR EACH ROW */\n   -1,  /* (372) trnm ::= nm */\n    0,  /* (373) tridxby ::= */\n   -1,  /* (374) database_kw_opt ::= DATABASE */\n    0,  /* (375) database_kw_opt ::= */\n    0,  /* (376) kwcolumn_opt ::= */\n   -1,  /* (377) kwcolumn_opt ::= COLUMNKW */\n   -1,  /* (378) vtabarglist ::= vtabarg */\n   -3,  /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */\n   -2,  /* (380) vtabarg ::= vtabarg vtabargtoken */\n    0,  /* (381) anylist ::= */\n   -4,  /* (382) anylist ::= anylist LP anylist RP */\n   -2,  /* (383) anylist ::= anylist ANY */\n    0,  /* (384) with ::= */\n};\n\nstatic void yy_accept(yyParser*);  /* Forward Declaration */\n\n/*\n** Perform a reduce action and the shift that must immediately\n** follow the reduce.\n**\n** The yyLookahead and yyLookaheadToken parameters provide reduce actions\n** access to the lookahead token (if any).  The yyLookahead will be YYNOCODE\n** if the lookahead token has already been consumed.  As this procedure is\n** only called from one place, optimizing compilers will in-line it, which\n** means that the extra parameters have no performance impact.\n*/\nstatic YYACTIONTYPE yy_reduce(\n  yyParser *yypParser,         /* The parser */\n  unsigned int yyruleno,       /* Number of the rule by which to reduce */\n  int yyLookahead,             /* Lookahead token, or YYNOCODE if none */\n  sqlite3ParserTOKENTYPE yyLookaheadToken  /* Value of the lookahead token */\n  sqlite3ParserCTX_PDECL                   /* %extra_context */\n){\n  int yygoto;                     /* The next state */\n  YYACTIONTYPE yyact;             /* The next action */\n  yyStackEntry *yymsp;            /* The top of the parser's stack */\n  int yysize;                     /* Amount to pop the stack */\n  sqlite3ParserARG_FETCH\n  (void)yyLookahead;\n  (void)yyLookaheadToken;\n  yymsp = yypParser->yytos;\n#ifndef NDEBUG\n  if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){\n    yysize = yyRuleInfoNRhs[yyruleno];\n    if( yysize ){\n      fprintf(yyTraceFILE, \"%sReduce %d [%s]%s, pop back to state %d.\\n\",\n        yyTracePrompt,\n        yyruleno, yyRuleName[yyruleno],\n        yyruleno<YYNRULE_WITH_ACTION ? \"\" : \" without external action\",\n        yymsp[yysize].stateno);\n    }else{\n      fprintf(yyTraceFILE, \"%sReduce %d [%s]%s.\\n\",\n        yyTracePrompt, yyruleno, yyRuleName[yyruleno],\n        yyruleno<YYNRULE_WITH_ACTION ? \"\" : \" without external action\");\n    }\n  }\n#endif /* NDEBUG */\n\n  /* Check that the stack is large enough to grow by a single entry\n  ** if the RHS of the rule is empty.  This ensures that there is room\n  ** enough on the stack to push the LHS value */\n  if( yyRuleInfoNRhs[yyruleno]==0 ){\n#ifdef YYTRACKMAXSTACKDEPTH\n    if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){\n      yypParser->yyhwm++;\n      assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));\n    }\n#endif\n#if YYSTACKDEPTH>0 \n    if( yypParser->yytos>=yypParser->yystackEnd ){\n      yyStackOverflow(yypParser);\n      /* The call to yyStackOverflow() above pops the stack until it is\n      ** empty, causing the main parser loop to exit.  So the return value\n      ** is never used and does not matter. */\n      return 0;\n    }\n#else\n    if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){\n      if( yyGrowStack(yypParser) ){\n        yyStackOverflow(yypParser);\n        /* The call to yyStackOverflow() above pops the stack until it is\n        ** empty, causing the main parser loop to exit.  So the return value\n        ** is never used and does not matter. */\n        return 0;\n      }\n      yymsp = yypParser->yytos;\n    }\n#endif\n  }\n\n  switch( yyruleno ){\n  /* Beginning here are the reduction cases.  A typical example\n  ** follows:\n  **   case 0:\n  **  #line <lineno> <grammarfile>\n  **     { ... }           // User supplied code\n  **  #line <lineno> <thisfile>\n  **     break;\n  */\n/********** Begin reduce actions **********************************************/\n        YYMINORTYPE yylhsminor;\n      case 0: /* explain ::= EXPLAIN */\n{ pParse->explain = 1; }\n        break;\n      case 1: /* explain ::= EXPLAIN QUERY PLAN */\n{ pParse->explain = 2; }\n        break;\n      case 2: /* cmdx ::= cmd */\n{ sqlite3FinishCoding(pParse); }\n        break;\n      case 3: /* cmd ::= BEGIN transtype trans_opt */\n{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy192);}\n        break;\n      case 4: /* transtype ::= */\n{yymsp[1].minor.yy192 = TK_DEFERRED;}\n        break;\n      case 5: /* transtype ::= DEFERRED */\n      case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);\n      case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);\n      case 306: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==306);\n{yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-X*/}\n        break;\n      case 8: /* cmd ::= COMMIT|END trans_opt */\n      case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);\n{sqlite3EndTransaction(pParse,yymsp[-1].major);}\n        break;\n      case 10: /* cmd ::= SAVEPOINT nm */\n{\n  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);\n}\n        break;\n      case 11: /* cmd ::= RELEASE savepoint_opt nm */\n{\n  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);\n}\n        break;\n      case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */\n{\n  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);\n}\n        break;\n      case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */\n{\n   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy192,0,0,yymsp[-2].minor.yy192);\n}\n        break;\n      case 14: /* createkw ::= CREATE */\n{disableLookaside(pParse);}\n        break;\n      case 15: /* ifnotexists ::= */\n      case 18: /* temp ::= */ yytestcase(yyruleno==18);\n      case 21: /* table_options ::= */ yytestcase(yyruleno==21);\n      case 45: /* autoinc ::= */ yytestcase(yyruleno==45);\n      case 60: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==60);\n      case 70: /* defer_subclause_opt ::= */ yytestcase(yyruleno==70);\n      case 79: /* ifexists ::= */ yytestcase(yyruleno==79);\n      case 96: /* distinct ::= */ yytestcase(yyruleno==96);\n      case 232: /* collate ::= */ yytestcase(yyruleno==232);\n{yymsp[1].minor.yy192 = 0;}\n        break;\n      case 16: /* ifnotexists ::= IF NOT EXISTS */\n{yymsp[-2].minor.yy192 = 1;}\n        break;\n      case 17: /* temp ::= TEMP */\n      case 46: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==46);\n{yymsp[0].minor.yy192 = 1;}\n        break;\n      case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */\n{\n  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy192,0);\n}\n        break;\n      case 20: /* create_table_args ::= AS select */\n{\n  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy539);\n  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy539);\n}\n        break;\n      case 22: /* table_options ::= WITHOUT nm */\n{\n  if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,\"rowid\",5)==0 ){\n    yymsp[-1].minor.yy192 = TF_WithoutRowid | TF_NoVisibleRowid;\n  }else{\n    yymsp[-1].minor.yy192 = 0;\n    sqlite3ErrorMsg(pParse, \"unknown table option: %.*s\", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);\n  }\n}\n        break;\n      case 23: /* columnname ::= nm typetoken */\n{sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}\n        break;\n      case 24: /* typetoken ::= */\n      case 63: /* conslist_opt ::= */ yytestcase(yyruleno==63);\n      case 102: /* as ::= */ yytestcase(yyruleno==102);\n{yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}\n        break;\n      case 25: /* typetoken ::= typename LP signed RP */\n{\n  yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);\n}\n        break;\n      case 26: /* typetoken ::= typename LP signed COMMA signed RP */\n{\n  yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);\n}\n        break;\n      case 27: /* typename ::= typename ID|STRING */\n{yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}\n        break;\n      case 28: /* scanpt ::= */\n{\n  assert( yyLookahead!=YYNOCODE );\n  yymsp[1].minor.yy436 = yyLookaheadToken.z;\n}\n        break;\n      case 29: /* scantok ::= */\n{\n  assert( yyLookahead!=YYNOCODE );\n  yymsp[1].minor.yy0 = yyLookaheadToken;\n}\n        break;\n      case 30: /* ccons ::= CONSTRAINT nm */\n      case 65: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==65);\n{pParse->constraintName = yymsp[0].minor.yy0;}\n        break;\n      case 31: /* ccons ::= DEFAULT scantok term */\n{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy202,yymsp[-1].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}\n        break;\n      case 32: /* ccons ::= DEFAULT LP expr RP */\n{sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy202,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);}\n        break;\n      case 33: /* ccons ::= DEFAULT PLUS scantok term */\n{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy202,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}\n        break;\n      case 34: /* ccons ::= DEFAULT MINUS scantok term */\n{\n  Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy202, 0);\n  sqlite3AddDefaultValue(pParse,p,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);\n}\n        break;\n      case 35: /* ccons ::= DEFAULT scantok ID|INDEXED */\n{\n  Expr *p = tokenExpr(pParse, TK_STRING, yymsp[0].minor.yy0);\n  if( p ){\n    sqlite3ExprIdToTrueFalse(p);\n    testcase( p->op==TK_TRUEFALSE && sqlite3ExprTruthValue(p) );\n  }\n    sqlite3AddDefaultValue(pParse,p,yymsp[0].minor.yy0.z,yymsp[0].minor.yy0.z+yymsp[0].minor.yy0.n);\n}\n        break;\n      case 36: /* ccons ::= NOT NULL onconf */\n{sqlite3AddNotNull(pParse, yymsp[0].minor.yy192);}\n        break;\n      case 37: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */\n{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy192,yymsp[0].minor.yy192,yymsp[-2].minor.yy192);}\n        break;\n      case 38: /* ccons ::= UNIQUE onconf */\n{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy192,0,0,0,0,\n                                   SQLITE_IDXTYPE_UNIQUE);}\n        break;\n      case 39: /* ccons ::= CHECK LP expr RP */\n{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy202);}\n        break;\n      case 40: /* ccons ::= REFERENCES nm eidlist_opt refargs */\n{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy242,yymsp[0].minor.yy192);}\n        break;\n      case 41: /* ccons ::= defer_subclause */\n{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy192);}\n        break;\n      case 42: /* ccons ::= COLLATE ID|STRING */\n{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}\n        break;\n      case 43: /* generated ::= LP expr RP */\n{sqlite3AddGenerated(pParse,yymsp[-1].minor.yy202,0);}\n        break;\n      case 44: /* generated ::= LP expr RP ID */\n{sqlite3AddGenerated(pParse,yymsp[-2].minor.yy202,&yymsp[0].minor.yy0);}\n        break;\n      case 47: /* refargs ::= */\n{ yymsp[1].minor.yy192 = OE_None*0x0101; /* EV: R-19803-45884 */}\n        break;\n      case 48: /* refargs ::= refargs refarg */\n{ yymsp[-1].minor.yy192 = (yymsp[-1].minor.yy192 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }\n        break;\n      case 49: /* refarg ::= MATCH nm */\n{ yymsp[-1].minor.yy207.value = 0;     yymsp[-1].minor.yy207.mask = 0x000000; }\n        break;\n      case 50: /* refarg ::= ON INSERT refact */\n{ yymsp[-2].minor.yy207.value = 0;     yymsp[-2].minor.yy207.mask = 0x000000; }\n        break;\n      case 51: /* refarg ::= ON DELETE refact */\n{ yymsp[-2].minor.yy207.value = yymsp[0].minor.yy192;     yymsp[-2].minor.yy207.mask = 0x0000ff; }\n        break;\n      case 52: /* refarg ::= ON UPDATE refact */\n{ yymsp[-2].minor.yy207.value = yymsp[0].minor.yy192<<8;  yymsp[-2].minor.yy207.mask = 0x00ff00; }\n        break;\n      case 53: /* refact ::= SET NULL */\n{ yymsp[-1].minor.yy192 = OE_SetNull;  /* EV: R-33326-45252 */}\n        break;\n      case 54: /* refact ::= SET DEFAULT */\n{ yymsp[-1].minor.yy192 = OE_SetDflt;  /* EV: R-33326-45252 */}\n        break;\n      case 55: /* refact ::= CASCADE */\n{ yymsp[0].minor.yy192 = OE_Cascade;  /* EV: R-33326-45252 */}\n        break;\n      case 56: /* refact ::= RESTRICT */\n{ yymsp[0].minor.yy192 = OE_Restrict; /* EV: R-33326-45252 */}\n        break;\n      case 57: /* refact ::= NO ACTION */\n{ yymsp[-1].minor.yy192 = OE_None;     /* EV: R-33326-45252 */}\n        break;\n      case 58: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */\n{yymsp[-2].minor.yy192 = 0;}\n        break;\n      case 59: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */\n      case 74: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==74);\n      case 162: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==162);\n{yymsp[-1].minor.yy192 = yymsp[0].minor.yy192;}\n        break;\n      case 61: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */\n      case 78: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==78);\n      case 204: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==204);\n      case 207: /* in_op ::= NOT IN */ yytestcase(yyruleno==207);\n      case 233: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==233);\n{yymsp[-1].minor.yy192 = 1;}\n        break;\n      case 62: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */\n{yymsp[-1].minor.yy192 = 0;}\n        break;\n      case 64: /* tconscomma ::= COMMA */\n{pParse->constraintName.n = 0;}\n        break;\n      case 66: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */\n{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy242,yymsp[0].minor.yy192,yymsp[-2].minor.yy192,0);}\n        break;\n      case 67: /* tcons ::= UNIQUE LP sortlist RP onconf */\n{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy242,yymsp[0].minor.yy192,0,0,0,0,\n                                       SQLITE_IDXTYPE_UNIQUE);}\n        break;\n      case 68: /* tcons ::= CHECK LP expr RP onconf */\n{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy202);}\n        break;\n      case 69: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */\n{\n    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy242, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy242, yymsp[-1].minor.yy192);\n    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy192);\n}\n        break;\n      case 71: /* onconf ::= */\n      case 73: /* orconf ::= */ yytestcase(yyruleno==73);\n{yymsp[1].minor.yy192 = OE_Default;}\n        break;\n      case 72: /* onconf ::= ON CONFLICT resolvetype */\n{yymsp[-2].minor.yy192 = yymsp[0].minor.yy192;}\n        break;\n      case 75: /* resolvetype ::= IGNORE */\n{yymsp[0].minor.yy192 = OE_Ignore;}\n        break;\n      case 76: /* resolvetype ::= REPLACE */\n      case 163: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==163);\n{yymsp[0].minor.yy192 = OE_Replace;}\n        break;\n      case 77: /* cmd ::= DROP TABLE ifexists fullname */\n{\n  sqlite3DropTable(pParse, yymsp[0].minor.yy47, 0, yymsp[-1].minor.yy192);\n}\n        break;\n      case 80: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */\n{\n  sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy242, yymsp[0].minor.yy539, yymsp[-7].minor.yy192, yymsp[-5].minor.yy192);\n}\n        break;\n      case 81: /* cmd ::= DROP VIEW ifexists fullname */\n{\n  sqlite3DropTable(pParse, yymsp[0].minor.yy47, 1, yymsp[-1].minor.yy192);\n}\n        break;\n      case 82: /* cmd ::= select */\n{\n  SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};\n  sqlite3Select(pParse, yymsp[0].minor.yy539, &dest);\n  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy539);\n}\n        break;\n      case 83: /* select ::= WITH wqlist selectnowith */\n{\n  Select *p = yymsp[0].minor.yy539;\n  if( p ){\n    p->pWith = yymsp[-1].minor.yy131;\n    parserDoubleLinkSelect(pParse, p);\n  }else{\n    sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy131);\n  }\n  yymsp[-2].minor.yy539 = p;\n}\n        break;\n      case 84: /* select ::= WITH RECURSIVE wqlist selectnowith */\n{\n  Select *p = yymsp[0].minor.yy539;\n  if( p ){\n    p->pWith = yymsp[-1].minor.yy131;\n    parserDoubleLinkSelect(pParse, p);\n  }else{\n    sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy131);\n  }\n  yymsp[-3].minor.yy539 = p;\n}\n        break;\n      case 85: /* select ::= selectnowith */\n{\n  Select *p = yymsp[0].minor.yy539;\n  if( p ){\n    parserDoubleLinkSelect(pParse, p);\n  }\n  yymsp[0].minor.yy539 = p; /*A-overwrites-X*/\n}\n        break;\n      case 86: /* selectnowith ::= selectnowith multiselect_op oneselect */\n{\n  Select *pRhs = yymsp[0].minor.yy539;\n  Select *pLhs = yymsp[-2].minor.yy539;\n  if( pRhs && pRhs->pPrior ){\n    SrcList *pFrom;\n    Token x;\n    x.n = 0;\n    parserDoubleLinkSelect(pParse, pRhs);\n    pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);\n    pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);\n  }\n  if( pRhs ){\n    pRhs->op = (u8)yymsp[-1].minor.yy192;\n    pRhs->pPrior = pLhs;\n    if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;\n    pRhs->selFlags &= ~SF_MultiValue;\n    if( yymsp[-1].minor.yy192!=TK_ALL ) pParse->hasCompound = 1;\n  }else{\n    sqlite3SelectDelete(pParse->db, pLhs);\n  }\n  yymsp[-2].minor.yy539 = pRhs;\n}\n        break;\n      case 87: /* multiselect_op ::= UNION */\n      case 89: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==89);\n{yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-OP*/}\n        break;\n      case 88: /* multiselect_op ::= UNION ALL */\n{yymsp[-1].minor.yy192 = TK_ALL;}\n        break;\n      case 90: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */\n{\n  yymsp[-8].minor.yy539 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy242,yymsp[-5].minor.yy47,yymsp[-4].minor.yy202,yymsp[-3].minor.yy242,yymsp[-2].minor.yy202,yymsp[-1].minor.yy242,yymsp[-7].minor.yy192,yymsp[0].minor.yy202);\n}\n        break;\n      case 91: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */\n{\n  yymsp[-9].minor.yy539 = sqlite3SelectNew(pParse,yymsp[-7].minor.yy242,yymsp[-6].minor.yy47,yymsp[-5].minor.yy202,yymsp[-4].minor.yy242,yymsp[-3].minor.yy202,yymsp[-1].minor.yy242,yymsp[-8].minor.yy192,yymsp[0].minor.yy202);\n  if( yymsp[-9].minor.yy539 ){\n    yymsp[-9].minor.yy539->pWinDefn = yymsp[-2].minor.yy303;\n  }else{\n    sqlite3WindowListDelete(pParse->db, yymsp[-2].minor.yy303);\n  }\n}\n        break;\n      case 92: /* values ::= VALUES LP nexprlist RP */\n{\n  yymsp[-3].minor.yy539 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy242,0,0,0,0,0,SF_Values,0);\n}\n        break;\n      case 93: /* values ::= values COMMA LP nexprlist RP */\n{\n  Select *pRight, *pLeft = yymsp[-4].minor.yy539;\n  pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy242,0,0,0,0,0,SF_Values|SF_MultiValue,0);\n  if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;\n  if( pRight ){\n    pRight->op = TK_ALL;\n    pRight->pPrior = pLeft;\n    yymsp[-4].minor.yy539 = pRight;\n  }else{\n    yymsp[-4].minor.yy539 = pLeft;\n  }\n}\n        break;\n      case 94: /* distinct ::= DISTINCT */\n{yymsp[0].minor.yy192 = SF_Distinct;}\n        break;\n      case 95: /* distinct ::= ALL */\n{yymsp[0].minor.yy192 = SF_All;}\n        break;\n      case 97: /* sclp ::= */\n      case 130: /* orderby_opt ::= */ yytestcase(yyruleno==130);\n      case 140: /* groupby_opt ::= */ yytestcase(yyruleno==140);\n      case 220: /* exprlist ::= */ yytestcase(yyruleno==220);\n      case 223: /* paren_exprlist ::= */ yytestcase(yyruleno==223);\n      case 228: /* eidlist_opt ::= */ yytestcase(yyruleno==228);\n{yymsp[1].minor.yy242 = 0;}\n        break;\n      case 98: /* selcollist ::= sclp scanpt expr scanpt as */\n{\n   yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy242, yymsp[-2].minor.yy202);\n   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy242, &yymsp[0].minor.yy0, 1);\n   sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy242,yymsp[-3].minor.yy436,yymsp[-1].minor.yy436);\n}\n        break;\n      case 99: /* selcollist ::= sclp scanpt STAR */\n{\n  Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);\n  yymsp[-2].minor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy242, p);\n}\n        break;\n      case 100: /* selcollist ::= sclp scanpt nm DOT STAR */\n{\n  Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);\n  Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);\n  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);\n  yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, pDot);\n}\n        break;\n      case 101: /* as ::= AS nm */\n      case 112: /* dbnm ::= DOT nm */ yytestcase(yyruleno==112);\n      case 244: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==244);\n      case 245: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==245);\n{yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}\n        break;\n      case 103: /* from ::= */\n{yymsp[1].minor.yy47 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy47));}\n        break;\n      case 104: /* from ::= FROM seltablist */\n{\n  yymsp[-1].minor.yy47 = yymsp[0].minor.yy47;\n  sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy47);\n}\n        break;\n      case 105: /* stl_prefix ::= seltablist joinop */\n{\n   if( ALWAYS(yymsp[-1].minor.yy47 && yymsp[-1].minor.yy47->nSrc>0) ) yymsp[-1].minor.yy47->a[yymsp[-1].minor.yy47->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy192;\n}\n        break;\n      case 106: /* stl_prefix ::= */\n{yymsp[1].minor.yy47 = 0;}\n        break;\n      case 107: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */\n{\n  yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);\n  sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy47, &yymsp[-2].minor.yy0);\n}\n        break;\n      case 108: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */\n{\n  yymsp[-8].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy47,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);\n  sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy47, yymsp[-4].minor.yy242);\n}\n        break;\n      case 109: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */\n{\n    yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy539,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);\n  }\n        break;\n      case 110: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */\n{\n    if( yymsp[-6].minor.yy47==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy202==0 && yymsp[0].minor.yy600==0 ){\n      yymsp[-6].minor.yy47 = yymsp[-4].minor.yy47;\n    }else if( yymsp[-4].minor.yy47->nSrc==1 ){\n      yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);\n      if( yymsp[-6].minor.yy47 ){\n        struct SrcList_item *pNew = &yymsp[-6].minor.yy47->a[yymsp[-6].minor.yy47->nSrc-1];\n        struct SrcList_item *pOld = yymsp[-4].minor.yy47->a;\n        pNew->zName = pOld->zName;\n        pNew->zDatabase = pOld->zDatabase;\n        pNew->pSelect = pOld->pSelect;\n        if( pOld->fg.isTabFunc ){\n          pNew->u1.pFuncArg = pOld->u1.pFuncArg;\n          pOld->u1.pFuncArg = 0;\n          pOld->fg.isTabFunc = 0;\n          pNew->fg.isTabFunc = 1;\n        }\n        pOld->zName = pOld->zDatabase = 0;\n        pOld->pSelect = 0;\n      }\n      sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy47);\n    }else{\n      Select *pSubquery;\n      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy47);\n      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy47,0,0,0,0,SF_NestedFrom,0);\n      yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);\n    }\n  }\n        break;\n      case 111: /* dbnm ::= */\n      case 125: /* indexed_opt ::= */ yytestcase(yyruleno==125);\n{yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}\n        break;\n      case 113: /* fullname ::= nm */\n{\n  yylhsminor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0);\n  if( IN_RENAME_OBJECT && yylhsminor.yy47 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy47->a[0].zName, &yymsp[0].minor.yy0);\n}\n  yymsp[0].minor.yy47 = yylhsminor.yy47;\n        break;\n      case 114: /* fullname ::= nm DOT nm */\n{\n  yylhsminor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);\n  if( IN_RENAME_OBJECT && yylhsminor.yy47 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy47->a[0].zName, &yymsp[0].minor.yy0);\n}\n  yymsp[-2].minor.yy47 = yylhsminor.yy47;\n        break;\n      case 115: /* xfullname ::= nm */\n{yymsp[0].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/}\n        break;\n      case 116: /* xfullname ::= nm DOT nm */\n{yymsp[-2].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}\n        break;\n      case 117: /* xfullname ::= nm DOT nm AS nm */\n{\n   yymsp[-4].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); /*A-overwrites-X*/\n   if( yymsp[-4].minor.yy47 ) yymsp[-4].minor.yy47->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);\n}\n        break;\n      case 118: /* xfullname ::= nm AS nm */\n{  \n   yymsp[-2].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/\n   if( yymsp[-2].minor.yy47 ) yymsp[-2].minor.yy47->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);\n}\n        break;\n      case 119: /* joinop ::= COMMA|JOIN */\n{ yymsp[0].minor.yy192 = JT_INNER; }\n        break;\n      case 120: /* joinop ::= JOIN_KW JOIN */\n{yymsp[-1].minor.yy192 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0);  /*X-overwrites-A*/}\n        break;\n      case 121: /* joinop ::= JOIN_KW nm JOIN */\n{yymsp[-2].minor.yy192 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}\n        break;\n      case 122: /* joinop ::= JOIN_KW nm nm JOIN */\n{yymsp[-3].minor.yy192 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}\n        break;\n      case 123: /* on_opt ::= ON expr */\n      case 143: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==143);\n      case 150: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==150);\n      case 216: /* case_else ::= ELSE expr */ yytestcase(yyruleno==216);\n      case 237: /* vinto ::= INTO expr */ yytestcase(yyruleno==237);\n{yymsp[-1].minor.yy202 = yymsp[0].minor.yy202;}\n        break;\n      case 124: /* on_opt ::= */\n      case 142: /* having_opt ::= */ yytestcase(yyruleno==142);\n      case 144: /* limit_opt ::= */ yytestcase(yyruleno==144);\n      case 149: /* where_opt ::= */ yytestcase(yyruleno==149);\n      case 217: /* case_else ::= */ yytestcase(yyruleno==217);\n      case 219: /* case_operand ::= */ yytestcase(yyruleno==219);\n      case 238: /* vinto ::= */ yytestcase(yyruleno==238);\n{yymsp[1].minor.yy202 = 0;}\n        break;\n      case 126: /* indexed_opt ::= INDEXED BY nm */\n{yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}\n        break;\n      case 127: /* indexed_opt ::= NOT INDEXED */\n{yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}\n        break;\n      case 128: /* using_opt ::= USING LP idlist RP */\n{yymsp[-3].minor.yy600 = yymsp[-1].minor.yy600;}\n        break;\n      case 129: /* using_opt ::= */\n      case 164: /* idlist_opt ::= */ yytestcase(yyruleno==164);\n{yymsp[1].minor.yy600 = 0;}\n        break;\n      case 131: /* orderby_opt ::= ORDER BY sortlist */\n      case 141: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==141);\n{yymsp[-2].minor.yy242 = yymsp[0].minor.yy242;}\n        break;\n      case 132: /* sortlist ::= sortlist COMMA expr sortorder nulls */\n{\n  yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242,yymsp[-2].minor.yy202);\n  sqlite3ExprListSetSortOrder(yymsp[-4].minor.yy242,yymsp[-1].minor.yy192,yymsp[0].minor.yy192);\n}\n        break;\n      case 133: /* sortlist ::= expr sortorder nulls */\n{\n  yymsp[-2].minor.yy242 = sqlite3ExprListAppend(pParse,0,yymsp[-2].minor.yy202); /*A-overwrites-Y*/\n  sqlite3ExprListSetSortOrder(yymsp[-2].minor.yy242,yymsp[-1].minor.yy192,yymsp[0].minor.yy192);\n}\n        break;\n      case 134: /* sortorder ::= ASC */\n{yymsp[0].minor.yy192 = SQLITE_SO_ASC;}\n        break;\n      case 135: /* sortorder ::= DESC */\n{yymsp[0].minor.yy192 = SQLITE_SO_DESC;}\n        break;\n      case 136: /* sortorder ::= */\n      case 139: /* nulls ::= */ yytestcase(yyruleno==139);\n{yymsp[1].minor.yy192 = SQLITE_SO_UNDEFINED;}\n        break;\n      case 137: /* nulls ::= NULLS FIRST */\n{yymsp[-1].minor.yy192 = SQLITE_SO_ASC;}\n        break;\n      case 138: /* nulls ::= NULLS LAST */\n{yymsp[-1].minor.yy192 = SQLITE_SO_DESC;}\n        break;\n      case 145: /* limit_opt ::= LIMIT expr */\n{yymsp[-1].minor.yy202 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy202,0);}\n        break;\n      case 146: /* limit_opt ::= LIMIT expr OFFSET expr */\n{yymsp[-3].minor.yy202 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);}\n        break;\n      case 147: /* limit_opt ::= LIMIT expr COMMA expr */\n{yymsp[-3].minor.yy202 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy202,yymsp[-2].minor.yy202);}\n        break;\n      case 148: /* cmd ::= with DELETE FROM xfullname indexed_opt where_opt */\n{\n  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy47, &yymsp[-1].minor.yy0);\n  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy47,yymsp[0].minor.yy202,0,0);\n}\n        break;\n      case 151: /* cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */\n{\n  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy47, &yymsp[-3].minor.yy0);\n  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy242,\"set list\"); \n  sqlite3Update(pParse,yymsp[-4].minor.yy47,yymsp[-1].minor.yy242,yymsp[0].minor.yy202,yymsp[-5].minor.yy192,0,0,0);\n}\n        break;\n      case 152: /* setlist ::= setlist COMMA nm EQ expr */\n{\n  yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy242, yymsp[0].minor.yy202);\n  sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy242, &yymsp[-2].minor.yy0, 1);\n}\n        break;\n      case 153: /* setlist ::= setlist COMMA LP idlist RP EQ expr */\n{\n  yymsp[-6].minor.yy242 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy242, yymsp[-3].minor.yy600, yymsp[0].minor.yy202);\n}\n        break;\n      case 154: /* setlist ::= nm EQ expr */\n{\n  yylhsminor.yy242 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy202);\n  sqlite3ExprListSetName(pParse, yylhsminor.yy242, &yymsp[-2].minor.yy0, 1);\n}\n  yymsp[-2].minor.yy242 = yylhsminor.yy242;\n        break;\n      case 155: /* setlist ::= LP idlist RP EQ expr */\n{\n  yymsp[-4].minor.yy242 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy600, yymsp[0].minor.yy202);\n}\n        break;\n      case 156: /* cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */\n{\n  sqlite3Insert(pParse, yymsp[-3].minor.yy47, yymsp[-1].minor.yy539, yymsp[-2].minor.yy600, yymsp[-5].minor.yy192, yymsp[0].minor.yy318);\n}\n        break;\n      case 157: /* cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */\n{\n  sqlite3Insert(pParse, yymsp[-3].minor.yy47, 0, yymsp[-2].minor.yy600, yymsp[-5].minor.yy192, 0);\n}\n        break;\n      case 158: /* upsert ::= */\n{ yymsp[1].minor.yy318 = 0; }\n        break;\n      case 159: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */\n{ yymsp[-10].minor.yy318 = sqlite3UpsertNew(pParse->db,yymsp[-7].minor.yy242,yymsp[-5].minor.yy202,yymsp[-1].minor.yy242,yymsp[0].minor.yy202);}\n        break;\n      case 160: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */\n{ yymsp[-7].minor.yy318 = sqlite3UpsertNew(pParse->db,yymsp[-4].minor.yy242,yymsp[-2].minor.yy202,0,0); }\n        break;\n      case 161: /* upsert ::= ON CONFLICT DO NOTHING */\n{ yymsp[-3].minor.yy318 = sqlite3UpsertNew(pParse->db,0,0,0,0); }\n        break;\n      case 165: /* idlist_opt ::= LP idlist RP */\n{yymsp[-2].minor.yy600 = yymsp[-1].minor.yy600;}\n        break;\n      case 166: /* idlist ::= idlist COMMA nm */\n{yymsp[-2].minor.yy600 = sqlite3IdListAppend(pParse,yymsp[-2].minor.yy600,&yymsp[0].minor.yy0);}\n        break;\n      case 167: /* idlist ::= nm */\n{yymsp[0].minor.yy600 = sqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}\n        break;\n      case 168: /* expr ::= LP expr RP */\n{yymsp[-2].minor.yy202 = yymsp[-1].minor.yy202;}\n        break;\n      case 169: /* expr ::= ID|INDEXED */\n      case 170: /* expr ::= JOIN_KW */ yytestcase(yyruleno==170);\n{yymsp[0].minor.yy202=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}\n        break;\n      case 171: /* expr ::= nm DOT nm */\n{\n  Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);\n  Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);\n  if( IN_RENAME_OBJECT ){\n    sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[0].minor.yy0);\n    sqlite3RenameTokenMap(pParse, (void*)temp1, &yymsp[-2].minor.yy0);\n  }\n  yylhsminor.yy202 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);\n}\n  yymsp[-2].minor.yy202 = yylhsminor.yy202;\n        break;\n      case 172: /* expr ::= nm DOT nm DOT nm */\n{\n  Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);\n  Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);\n  Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);\n  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);\n  if( IN_RENAME_OBJECT ){\n    sqlite3RenameTokenMap(pParse, (void*)temp3, &yymsp[0].minor.yy0);\n    sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[-2].minor.yy0);\n  }\n  yylhsminor.yy202 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);\n}\n  yymsp[-4].minor.yy202 = yylhsminor.yy202;\n        break;\n      case 173: /* term ::= NULL|FLOAT|BLOB */\n      case 174: /* term ::= STRING */ yytestcase(yyruleno==174);\n{yymsp[0].minor.yy202=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}\n        break;\n      case 175: /* term ::= INTEGER */\n{\n  yylhsminor.yy202 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);\n}\n  yymsp[0].minor.yy202 = yylhsminor.yy202;\n        break;\n      case 176: /* expr ::= VARIABLE */\n{\n  if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){\n    u32 n = yymsp[0].minor.yy0.n;\n    yymsp[0].minor.yy202 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);\n    sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy202, n);\n  }else{\n    /* When doing a nested parse, one can include terms in an expression\n    ** that look like this:   #1 #2 ...  These terms refer to registers\n    ** in the virtual machine.  #N is the N-th register. */\n    Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/\n    assert( t.n>=2 );\n    if( pParse->nested==0 ){\n      sqlite3ErrorMsg(pParse, \"near \\\"%T\\\": syntax error\", &t);\n      yymsp[0].minor.yy202 = 0;\n    }else{\n      yymsp[0].minor.yy202 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);\n      if( yymsp[0].minor.yy202 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy202->iTable);\n    }\n  }\n}\n        break;\n      case 177: /* expr ::= expr COLLATE ID|STRING */\n{\n  yymsp[-2].minor.yy202 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy202, &yymsp[0].minor.yy0, 1);\n}\n        break;\n      case 178: /* expr ::= CAST LP expr AS typetoken RP */\n{\n  yymsp[-5].minor.yy202 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);\n  sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy202, yymsp[-3].minor.yy202, 0);\n}\n        break;\n      case 179: /* expr ::= ID|INDEXED LP distinct exprlist RP */\n{\n  yylhsminor.yy202 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy242, &yymsp[-4].minor.yy0, yymsp[-2].minor.yy192);\n}\n  yymsp[-4].minor.yy202 = yylhsminor.yy202;\n        break;\n      case 180: /* expr ::= ID|INDEXED LP STAR RP */\n{\n  yylhsminor.yy202 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0);\n}\n  yymsp[-3].minor.yy202 = yylhsminor.yy202;\n        break;\n      case 181: /* expr ::= ID|INDEXED LP distinct exprlist RP filter_over */\n{\n  yylhsminor.yy202 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy242, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy192);\n  sqlite3WindowAttach(pParse, yylhsminor.yy202, yymsp[0].minor.yy303);\n}\n  yymsp[-5].minor.yy202 = yylhsminor.yy202;\n        break;\n      case 182: /* expr ::= ID|INDEXED LP STAR RP filter_over */\n{\n  yylhsminor.yy202 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0);\n  sqlite3WindowAttach(pParse, yylhsminor.yy202, yymsp[0].minor.yy303);\n}\n  yymsp[-4].minor.yy202 = yylhsminor.yy202;\n        break;\n      case 183: /* term ::= CTIME_KW */\n{\n  yylhsminor.yy202 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0);\n}\n  yymsp[0].minor.yy202 = yylhsminor.yy202;\n        break;\n      case 184: /* expr ::= LP nexprlist COMMA expr RP */\n{\n  ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy242, yymsp[-1].minor.yy202);\n  yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);\n  if( yymsp[-4].minor.yy202 ){\n    yymsp[-4].minor.yy202->x.pList = pList;\n    if( ALWAYS(pList->nExpr) ){\n      yymsp[-4].minor.yy202->flags |= pList->a[0].pExpr->flags & EP_Propagate;\n    }\n  }else{\n    sqlite3ExprListDelete(pParse->db, pList);\n  }\n}\n        break;\n      case 185: /* expr ::= expr AND expr */\n{yymsp[-2].minor.yy202=sqlite3ExprAnd(pParse,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);}\n        break;\n      case 186: /* expr ::= expr OR expr */\n      case 187: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==187);\n      case 188: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==188);\n      case 189: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==189);\n      case 190: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==190);\n      case 191: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==191);\n      case 192: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==192);\n{yymsp[-2].minor.yy202=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);}\n        break;\n      case 193: /* likeop ::= NOT LIKE_KW|MATCH */\n{yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}\n        break;\n      case 194: /* expr ::= expr likeop expr */\n{\n  ExprList *pList;\n  int bNot = yymsp[-1].minor.yy0.n & 0x80000000;\n  yymsp[-1].minor.yy0.n &= 0x7fffffff;\n  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy202);\n  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy202);\n  yymsp[-2].minor.yy202 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);\n  if( bNot ) yymsp[-2].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy202, 0);\n  if( yymsp[-2].minor.yy202 ) yymsp[-2].minor.yy202->flags |= EP_InfixFunc;\n}\n        break;\n      case 195: /* expr ::= expr likeop expr ESCAPE expr */\n{\n  ExprList *pList;\n  int bNot = yymsp[-3].minor.yy0.n & 0x80000000;\n  yymsp[-3].minor.yy0.n &= 0x7fffffff;\n  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202);\n  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy202);\n  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy202);\n  yymsp[-4].minor.yy202 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0);\n  if( bNot ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);\n  if( yymsp[-4].minor.yy202 ) yymsp[-4].minor.yy202->flags |= EP_InfixFunc;\n}\n        break;\n      case 196: /* expr ::= expr ISNULL|NOTNULL */\n{yymsp[-1].minor.yy202 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy202,0);}\n        break;\n      case 197: /* expr ::= expr NOT NULL */\n{yymsp[-2].minor.yy202 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy202,0);}\n        break;\n      case 198: /* expr ::= expr IS expr */\n{\n  yymsp[-2].minor.yy202 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);\n  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy202, yymsp[-2].minor.yy202, TK_ISNULL);\n}\n        break;\n      case 199: /* expr ::= expr IS NOT expr */\n{\n  yymsp[-3].minor.yy202 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy202,yymsp[0].minor.yy202);\n  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy202, yymsp[-3].minor.yy202, TK_NOTNULL);\n}\n        break;\n      case 200: /* expr ::= NOT expr */\n      case 201: /* expr ::= BITNOT expr */ yytestcase(yyruleno==201);\n{yymsp[-1].minor.yy202 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy202, 0);/*A-overwrites-B*/}\n        break;\n      case 202: /* expr ::= PLUS|MINUS expr */\n{\n  yymsp[-1].minor.yy202 = sqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yymsp[0].minor.yy202, 0);\n  /*A-overwrites-B*/\n}\n        break;\n      case 203: /* between_op ::= BETWEEN */\n      case 206: /* in_op ::= IN */ yytestcase(yyruleno==206);\n{yymsp[0].minor.yy192 = 0;}\n        break;\n      case 205: /* expr ::= expr between_op expr AND expr */\n{\n  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202);\n  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy202);\n  yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy202, 0);\n  if( yymsp[-4].minor.yy202 ){\n    yymsp[-4].minor.yy202->x.pList = pList;\n  }else{\n    sqlite3ExprListDelete(pParse->db, pList);\n  } \n  if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);\n}\n        break;\n      case 208: /* expr ::= expr in_op LP exprlist RP */\n{\n    if( yymsp[-1].minor.yy242==0 ){\n      /* Expressions of the form\n      **\n      **      expr1 IN ()\n      **      expr1 NOT IN ()\n      **\n      ** simplify to constants 0 (false) and 1 (true), respectively,\n      ** regardless of the value of expr1.\n      */\n      sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy202);\n      yymsp[-4].minor.yy202 = sqlite3Expr(pParse->db, TK_INTEGER, yymsp[-3].minor.yy192 ? \"1\" : \"0\");\n    }else if( yymsp[-1].minor.yy242->nExpr==1 && sqlite3ExprIsConstant(yymsp[-1].minor.yy242->a[0].pExpr) ){\n      Expr *pRHS = yymsp[-1].minor.yy242->a[0].pExpr;\n      yymsp[-1].minor.yy242->a[0].pExpr = 0;\n      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy242);\n      pRHS = sqlite3PExpr(pParse, TK_UPLUS, pRHS, 0);\n      yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_EQ, yymsp[-4].minor.yy202, pRHS);\n      if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);\n    }else{\n      yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0);\n      if( yymsp[-4].minor.yy202 ){\n        yymsp[-4].minor.yy202->x.pList = yymsp[-1].minor.yy242;\n        sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy202);\n      }else{\n        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy242);\n      }\n      if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);\n    }\n  }\n        break;\n      case 209: /* expr ::= LP select RP */\n{\n    yymsp[-2].minor.yy202 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);\n    sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy202, yymsp[-1].minor.yy539);\n  }\n        break;\n      case 210: /* expr ::= expr in_op LP select RP */\n{\n    yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0);\n    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy202, yymsp[-1].minor.yy539);\n    if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);\n  }\n        break;\n      case 211: /* expr ::= expr in_op nm dbnm paren_exprlist */\n{\n    SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);\n    Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);\n    if( yymsp[0].minor.yy242 )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy242);\n    yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0);\n    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy202, pSelect);\n    if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);\n  }\n        break;\n      case 212: /* expr ::= EXISTS LP select RP */\n{\n    Expr *p;\n    p = yymsp[-3].minor.yy202 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);\n    sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy539);\n  }\n        break;\n      case 213: /* expr ::= CASE case_operand case_exprlist case_else END */\n{\n  yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy202, 0);\n  if( yymsp[-4].minor.yy202 ){\n    yymsp[-4].minor.yy202->x.pList = yymsp[-1].minor.yy202 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy242,yymsp[-1].minor.yy202) : yymsp[-2].minor.yy242;\n    sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy202);\n  }else{\n    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy242);\n    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy202);\n  }\n}\n        break;\n      case 214: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */\n{\n  yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, yymsp[-2].minor.yy202);\n  yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, yymsp[0].minor.yy202);\n}\n        break;\n      case 215: /* case_exprlist ::= WHEN expr THEN expr */\n{\n  yymsp[-3].minor.yy242 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202);\n  yymsp[-3].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy242, yymsp[0].minor.yy202);\n}\n        break;\n      case 218: /* case_operand ::= expr */\n{yymsp[0].minor.yy202 = yymsp[0].minor.yy202; /*A-overwrites-X*/}\n        break;\n      case 221: /* nexprlist ::= nexprlist COMMA expr */\n{yymsp[-2].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy242,yymsp[0].minor.yy202);}\n        break;\n      case 222: /* nexprlist ::= expr */\n{yymsp[0].minor.yy242 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy202); /*A-overwrites-Y*/}\n        break;\n      case 224: /* paren_exprlist ::= LP exprlist RP */\n      case 229: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==229);\n{yymsp[-2].minor.yy242 = yymsp[-1].minor.yy242;}\n        break;\n      case 225: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */\n{\n  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, \n                     sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy242, yymsp[-10].minor.yy192,\n                      &yymsp[-11].minor.yy0, yymsp[0].minor.yy202, SQLITE_SO_ASC, yymsp[-8].minor.yy192, SQLITE_IDXTYPE_APPDEF);\n  if( IN_RENAME_OBJECT && pParse->pNewIndex ){\n    sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &yymsp[-4].minor.yy0);\n  }\n}\n        break;\n      case 226: /* uniqueflag ::= UNIQUE */\n      case 268: /* raisetype ::= ABORT */ yytestcase(yyruleno==268);\n{yymsp[0].minor.yy192 = OE_Abort;}\n        break;\n      case 227: /* uniqueflag ::= */\n{yymsp[1].minor.yy192 = OE_None;}\n        break;\n      case 230: /* eidlist ::= eidlist COMMA nm collate sortorder */\n{\n  yymsp[-4].minor.yy242 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy242, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy192, yymsp[0].minor.yy192);\n}\n        break;\n      case 231: /* eidlist ::= nm collate sortorder */\n{\n  yymsp[-2].minor.yy242 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy192, yymsp[0].minor.yy192); /*A-overwrites-Y*/\n}\n        break;\n      case 234: /* cmd ::= DROP INDEX ifexists fullname */\n{sqlite3DropIndex(pParse, yymsp[0].minor.yy47, yymsp[-1].minor.yy192);}\n        break;\n      case 235: /* cmd ::= VACUUM vinto */\n{sqlite3Vacuum(pParse,0,yymsp[0].minor.yy202);}\n        break;\n      case 236: /* cmd ::= VACUUM nm vinto */\n{sqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy202);}\n        break;\n      case 239: /* cmd ::= PRAGMA nm dbnm */\n{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}\n        break;\n      case 240: /* cmd ::= PRAGMA nm dbnm EQ nmnum */\n{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}\n        break;\n      case 241: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */\n{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}\n        break;\n      case 242: /* cmd ::= PRAGMA nm dbnm EQ minus_num */\n{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}\n        break;\n      case 243: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */\n{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}\n        break;\n      case 246: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */\n{\n  Token all;\n  all.z = yymsp[-3].minor.yy0.z;\n  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;\n  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy447, &all);\n}\n        break;\n      case 247: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */\n{\n  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy192, yymsp[-4].minor.yy230.a, yymsp[-4].minor.yy230.b, yymsp[-2].minor.yy47, yymsp[0].minor.yy202, yymsp[-10].minor.yy192, yymsp[-8].minor.yy192);\n  yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/\n}\n        break;\n      case 248: /* trigger_time ::= BEFORE|AFTER */\n{ yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-X*/ }\n        break;\n      case 249: /* trigger_time ::= INSTEAD OF */\n{ yymsp[-1].minor.yy192 = TK_INSTEAD;}\n        break;\n      case 250: /* trigger_time ::= */\n{ yymsp[1].minor.yy192 = TK_BEFORE; }\n        break;\n      case 251: /* trigger_event ::= DELETE|INSERT */\n      case 252: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==252);\n{yymsp[0].minor.yy230.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy230.b = 0;}\n        break;\n      case 253: /* trigger_event ::= UPDATE OF idlist */\n{yymsp[-2].minor.yy230.a = TK_UPDATE; yymsp[-2].minor.yy230.b = yymsp[0].minor.yy600;}\n        break;\n      case 254: /* when_clause ::= */\n      case 273: /* key_opt ::= */ yytestcase(yyruleno==273);\n{ yymsp[1].minor.yy202 = 0; }\n        break;\n      case 255: /* when_clause ::= WHEN expr */\n      case 274: /* key_opt ::= KEY expr */ yytestcase(yyruleno==274);\n{ yymsp[-1].minor.yy202 = yymsp[0].minor.yy202; }\n        break;\n      case 256: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */\n{\n  assert( yymsp[-2].minor.yy447!=0 );\n  yymsp[-2].minor.yy447->pLast->pNext = yymsp[-1].minor.yy447;\n  yymsp[-2].minor.yy447->pLast = yymsp[-1].minor.yy447;\n}\n        break;\n      case 257: /* trigger_cmd_list ::= trigger_cmd SEMI */\n{ \n  assert( yymsp[-1].minor.yy447!=0 );\n  yymsp[-1].minor.yy447->pLast = yymsp[-1].minor.yy447;\n}\n        break;\n      case 258: /* trnm ::= nm DOT nm */\n{\n  yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;\n  sqlite3ErrorMsg(pParse, \n        \"qualified table names are not allowed on INSERT, UPDATE, and DELETE \"\n        \"statements within triggers\");\n}\n        break;\n      case 259: /* tridxby ::= INDEXED BY nm */\n{\n  sqlite3ErrorMsg(pParse,\n        \"the INDEXED BY clause is not allowed on UPDATE or DELETE statements \"\n        \"within triggers\");\n}\n        break;\n      case 260: /* tridxby ::= NOT INDEXED */\n{\n  sqlite3ErrorMsg(pParse,\n        \"the NOT INDEXED clause is not allowed on UPDATE or DELETE statements \"\n        \"within triggers\");\n}\n        break;\n      case 261: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */\n{yylhsminor.yy447 = sqlite3TriggerUpdateStep(pParse, &yymsp[-5].minor.yy0, yymsp[-2].minor.yy242, yymsp[-1].minor.yy202, yymsp[-6].minor.yy192, yymsp[-7].minor.yy0.z, yymsp[0].minor.yy436);}\n  yymsp[-7].minor.yy447 = yylhsminor.yy447;\n        break;\n      case 262: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */\n{\n   yylhsminor.yy447 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy600,yymsp[-2].minor.yy539,yymsp[-6].minor.yy192,yymsp[-1].minor.yy318,yymsp[-7].minor.yy436,yymsp[0].minor.yy436);/*yylhsminor.yy447-overwrites-yymsp[-6].minor.yy192*/\n}\n  yymsp[-7].minor.yy447 = yylhsminor.yy447;\n        break;\n      case 263: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */\n{yylhsminor.yy447 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy202, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy436);}\n  yymsp[-5].minor.yy447 = yylhsminor.yy447;\n        break;\n      case 264: /* trigger_cmd ::= scanpt select scanpt */\n{yylhsminor.yy447 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy539, yymsp[-2].minor.yy436, yymsp[0].minor.yy436); /*yylhsminor.yy447-overwrites-yymsp[-1].minor.yy539*/}\n  yymsp[-2].minor.yy447 = yylhsminor.yy447;\n        break;\n      case 265: /* expr ::= RAISE LP IGNORE RP */\n{\n  yymsp[-3].minor.yy202 = sqlite3PExpr(pParse, TK_RAISE, 0, 0); \n  if( yymsp[-3].minor.yy202 ){\n    yymsp[-3].minor.yy202->affExpr = OE_Ignore;\n  }\n}\n        break;\n      case 266: /* expr ::= RAISE LP raisetype COMMA nm RP */\n{\n  yymsp[-5].minor.yy202 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1); \n  if( yymsp[-5].minor.yy202 ) {\n    yymsp[-5].minor.yy202->affExpr = (char)yymsp[-3].minor.yy192;\n  }\n}\n        break;\n      case 267: /* raisetype ::= ROLLBACK */\n{yymsp[0].minor.yy192 = OE_Rollback;}\n        break;\n      case 269: /* raisetype ::= FAIL */\n{yymsp[0].minor.yy192 = OE_Fail;}\n        break;\n      case 270: /* cmd ::= DROP TRIGGER ifexists fullname */\n{\n  sqlite3DropTrigger(pParse,yymsp[0].minor.yy47,yymsp[-1].minor.yy192);\n}\n        break;\n      case 271: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */\n{\n  sqlite3Attach(pParse, yymsp[-3].minor.yy202, yymsp[-1].minor.yy202, yymsp[0].minor.yy202);\n}\n        break;\n      case 272: /* cmd ::= DETACH database_kw_opt expr */\n{\n  sqlite3Detach(pParse, yymsp[0].minor.yy202);\n}\n        break;\n      case 275: /* cmd ::= REINDEX */\n{sqlite3Reindex(pParse, 0, 0);}\n        break;\n      case 276: /* cmd ::= REINDEX nm dbnm */\n{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}\n        break;\n      case 277: /* cmd ::= ANALYZE */\n{sqlite3Analyze(pParse, 0, 0);}\n        break;\n      case 278: /* cmd ::= ANALYZE nm dbnm */\n{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}\n        break;\n      case 279: /* cmd ::= ALTER TABLE fullname RENAME TO nm */\n{\n  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy47,&yymsp[0].minor.yy0);\n}\n        break;\n      case 280: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */\n{\n  yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;\n  sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);\n}\n        break;\n      case 281: /* add_column_fullname ::= fullname */\n{\n  disableLookaside(pParse);\n  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy47);\n}\n        break;\n      case 282: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */\n{\n  sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy47, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);\n}\n        break;\n      case 283: /* cmd ::= create_vtab */\n{sqlite3VtabFinishParse(pParse,0);}\n        break;\n      case 284: /* cmd ::= create_vtab LP vtabarglist RP */\n{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}\n        break;\n      case 285: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */\n{\n    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy192);\n}\n        break;\n      case 286: /* vtabarg ::= */\n{sqlite3VtabArgInit(pParse);}\n        break;\n      case 287: /* vtabargtoken ::= ANY */\n      case 288: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==288);\n      case 289: /* lp ::= LP */ yytestcase(yyruleno==289);\n{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}\n        break;\n      case 290: /* with ::= WITH wqlist */\n      case 291: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==291);\n{ sqlite3WithPush(pParse, yymsp[0].minor.yy131, 1); }\n        break;\n      case 292: /* wqlist ::= nm eidlist_opt AS LP select RP */\n{\n  yymsp[-5].minor.yy131 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy242, yymsp[-1].minor.yy539); /*A-overwrites-X*/\n}\n        break;\n      case 293: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */\n{\n  yymsp[-7].minor.yy131 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy131, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy242, yymsp[-1].minor.yy539);\n}\n        break;\n      case 294: /* windowdefn_list ::= windowdefn */\n{ yylhsminor.yy303 = yymsp[0].minor.yy303; }\n  yymsp[0].minor.yy303 = yylhsminor.yy303;\n        break;\n      case 295: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */\n{\n  assert( yymsp[0].minor.yy303!=0 );\n  sqlite3WindowChain(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy303);\n  yymsp[0].minor.yy303->pNextWin = yymsp[-2].minor.yy303;\n  yylhsminor.yy303 = yymsp[0].minor.yy303;\n}\n  yymsp[-2].minor.yy303 = yylhsminor.yy303;\n        break;\n      case 296: /* windowdefn ::= nm AS LP window RP */\n{\n  if( ALWAYS(yymsp[-1].minor.yy303) ){\n    yymsp[-1].minor.yy303->zName = sqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.yy0.n);\n  }\n  yylhsminor.yy303 = yymsp[-1].minor.yy303;\n}\n  yymsp[-4].minor.yy303 = yylhsminor.yy303;\n        break;\n      case 297: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */\n{\n  yymsp[-4].minor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy242, yymsp[-1].minor.yy242, 0);\n}\n        break;\n      case 298: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */\n{\n  yylhsminor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy242, yymsp[-1].minor.yy242, &yymsp[-5].minor.yy0);\n}\n  yymsp[-5].minor.yy303 = yylhsminor.yy303;\n        break;\n      case 299: /* window ::= ORDER BY sortlist frame_opt */\n{\n  yymsp[-3].minor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, yymsp[-1].minor.yy242, 0);\n}\n        break;\n      case 300: /* window ::= nm ORDER BY sortlist frame_opt */\n{\n  yylhsminor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, yymsp[-1].minor.yy242, &yymsp[-4].minor.yy0);\n}\n  yymsp[-4].minor.yy303 = yylhsminor.yy303;\n        break;\n      case 301: /* window ::= frame_opt */\n      case 320: /* filter_over ::= over_clause */ yytestcase(yyruleno==320);\n{\n  yylhsminor.yy303 = yymsp[0].minor.yy303;\n}\n  yymsp[0].minor.yy303 = yylhsminor.yy303;\n        break;\n      case 302: /* window ::= nm frame_opt */\n{\n  yylhsminor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, 0, &yymsp[-1].minor.yy0);\n}\n  yymsp[-1].minor.yy303 = yylhsminor.yy303;\n        break;\n      case 303: /* frame_opt ::= */\n{ \n  yymsp[1].minor.yy303 = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0);\n}\n        break;\n      case 304: /* frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */\n{ \n  yylhsminor.yy303 = sqlite3WindowAlloc(pParse, yymsp[-2].minor.yy192, yymsp[-1].minor.yy77.eType, yymsp[-1].minor.yy77.pExpr, TK_CURRENT, 0, yymsp[0].minor.yy58);\n}\n  yymsp[-2].minor.yy303 = yylhsminor.yy303;\n        break;\n      case 305: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */\n{ \n  yylhsminor.yy303 = sqlite3WindowAlloc(pParse, yymsp[-5].minor.yy192, yymsp[-3].minor.yy77.eType, yymsp[-3].minor.yy77.pExpr, yymsp[-1].minor.yy77.eType, yymsp[-1].minor.yy77.pExpr, yymsp[0].minor.yy58);\n}\n  yymsp[-5].minor.yy303 = yylhsminor.yy303;\n        break;\n      case 307: /* frame_bound_s ::= frame_bound */\n      case 309: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==309);\n{yylhsminor.yy77 = yymsp[0].minor.yy77;}\n  yymsp[0].minor.yy77 = yylhsminor.yy77;\n        break;\n      case 308: /* frame_bound_s ::= UNBOUNDED PRECEDING */\n      case 310: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==310);\n      case 312: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==312);\n{yylhsminor.yy77.eType = yymsp[-1].major; yylhsminor.yy77.pExpr = 0;}\n  yymsp[-1].minor.yy77 = yylhsminor.yy77;\n        break;\n      case 311: /* frame_bound ::= expr PRECEDING|FOLLOWING */\n{yylhsminor.yy77.eType = yymsp[0].major; yylhsminor.yy77.pExpr = yymsp[-1].minor.yy202;}\n  yymsp[-1].minor.yy77 = yylhsminor.yy77;\n        break;\n      case 313: /* frame_exclude_opt ::= */\n{yymsp[1].minor.yy58 = 0;}\n        break;\n      case 314: /* frame_exclude_opt ::= EXCLUDE frame_exclude */\n{yymsp[-1].minor.yy58 = yymsp[0].minor.yy58;}\n        break;\n      case 315: /* frame_exclude ::= NO OTHERS */\n      case 316: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==316);\n{yymsp[-1].minor.yy58 = yymsp[-1].major; /*A-overwrites-X*/}\n        break;\n      case 317: /* frame_exclude ::= GROUP|TIES */\n{yymsp[0].minor.yy58 = yymsp[0].major; /*A-overwrites-X*/}\n        break;\n      case 318: /* window_clause ::= WINDOW windowdefn_list */\n{ yymsp[-1].minor.yy303 = yymsp[0].minor.yy303; }\n        break;\n      case 319: /* filter_over ::= filter_clause over_clause */\n{\n  yymsp[0].minor.yy303->pFilter = yymsp[-1].minor.yy202;\n  yylhsminor.yy303 = yymsp[0].minor.yy303;\n}\n  yymsp[-1].minor.yy303 = yylhsminor.yy303;\n        break;\n      case 321: /* filter_over ::= filter_clause */\n{\n  yylhsminor.yy303 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));\n  if( yylhsminor.yy303 ){\n    yylhsminor.yy303->eFrmType = TK_FILTER;\n    yylhsminor.yy303->pFilter = yymsp[0].minor.yy202;\n  }else{\n    sqlite3ExprDelete(pParse->db, yymsp[0].minor.yy202);\n  }\n}\n  yymsp[0].minor.yy303 = yylhsminor.yy303;\n        break;\n      case 322: /* over_clause ::= OVER LP window RP */\n{\n  yymsp[-3].minor.yy303 = yymsp[-1].minor.yy303;\n  assert( yymsp[-3].minor.yy303!=0 );\n}\n        break;\n      case 323: /* over_clause ::= OVER nm */\n{\n  yymsp[-1].minor.yy303 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));\n  if( yymsp[-1].minor.yy303 ){\n    yymsp[-1].minor.yy303->zName = sqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n);\n  }\n}\n        break;\n      case 324: /* filter_clause ::= FILTER LP WHERE expr RP */\n{ yymsp[-4].minor.yy202 = yymsp[-1].minor.yy202; }\n        break;\n      default:\n      /* (325) input ::= cmdlist */ yytestcase(yyruleno==325);\n      /* (326) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==326);\n      /* (327) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=327);\n      /* (328) ecmd ::= SEMI */ yytestcase(yyruleno==328);\n      /* (329) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==329);\n      /* (330) ecmd ::= explain cmdx SEMI (NEVER REDUCES) */ assert(yyruleno!=330);\n      /* (331) trans_opt ::= */ yytestcase(yyruleno==331);\n      /* (332) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==332);\n      /* (333) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==333);\n      /* (334) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==334);\n      /* (335) savepoint_opt ::= */ yytestcase(yyruleno==335);\n      /* (336) cmd ::= create_table create_table_args */ yytestcase(yyruleno==336);\n      /* (337) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==337);\n      /* (338) columnlist ::= columnname carglist */ yytestcase(yyruleno==338);\n      /* (339) nm ::= ID|INDEXED */ yytestcase(yyruleno==339);\n      /* (340) nm ::= STRING */ yytestcase(yyruleno==340);\n      /* (341) nm ::= JOIN_KW */ yytestcase(yyruleno==341);\n      /* (342) typetoken ::= typename */ yytestcase(yyruleno==342);\n      /* (343) typename ::= ID|STRING */ yytestcase(yyruleno==343);\n      /* (344) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=344);\n      /* (345) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=345);\n      /* (346) carglist ::= carglist ccons */ yytestcase(yyruleno==346);\n      /* (347) carglist ::= */ yytestcase(yyruleno==347);\n      /* (348) ccons ::= NULL onconf */ yytestcase(yyruleno==348);\n      /* (349) ccons ::= GENERATED ALWAYS AS generated */ yytestcase(yyruleno==349);\n      /* (350) ccons ::= AS generated */ yytestcase(yyruleno==350);\n      /* (351) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==351);\n      /* (352) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==352);\n      /* (353) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=353);\n      /* (354) tconscomma ::= */ yytestcase(yyruleno==354);\n      /* (355) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=355);\n      /* (356) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=356);\n      /* (357) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=357);\n      /* (358) oneselect ::= values */ yytestcase(yyruleno==358);\n      /* (359) sclp ::= selcollist COMMA */ yytestcase(yyruleno==359);\n      /* (360) as ::= ID|STRING */ yytestcase(yyruleno==360);\n      /* (361) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=361);\n      /* (362) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==362);\n      /* (363) exprlist ::= nexprlist */ yytestcase(yyruleno==363);\n      /* (364) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=364);\n      /* (365) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=365);\n      /* (366) nmnum ::= ON */ yytestcase(yyruleno==366);\n      /* (367) nmnum ::= DELETE */ yytestcase(yyruleno==367);\n      /* (368) nmnum ::= DEFAULT */ yytestcase(yyruleno==368);\n      /* (369) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==369);\n      /* (370) foreach_clause ::= */ yytestcase(yyruleno==370);\n      /* (371) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==371);\n      /* (372) trnm ::= nm */ yytestcase(yyruleno==372);\n      /* (373) tridxby ::= */ yytestcase(yyruleno==373);\n      /* (374) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==374);\n      /* (375) database_kw_opt ::= */ yytestcase(yyruleno==375);\n      /* (376) kwcolumn_opt ::= */ yytestcase(yyruleno==376);\n      /* (377) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==377);\n      /* (378) vtabarglist ::= vtabarg */ yytestcase(yyruleno==378);\n      /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==379);\n      /* (380) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==380);\n      /* (381) anylist ::= */ yytestcase(yyruleno==381);\n      /* (382) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==382);\n      /* (383) anylist ::= anylist ANY */ yytestcase(yyruleno==383);\n      /* (384) with ::= */ yytestcase(yyruleno==384);\n        break;\n/********** End reduce actions ************************************************/\n  };\n  assert( yyruleno<sizeof(yyRuleInfoLhs)/sizeof(yyRuleInfoLhs[0]) );\n  yygoto = yyRuleInfoLhs[yyruleno];\n  yysize = yyRuleInfoNRhs[yyruleno];\n  yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);\n\n  /* There are no SHIFTREDUCE actions on nonterminals because the table\n  ** generator has simplified them to pure REDUCE actions. */\n  assert( !(yyact>YY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) );\n\n  /* It is not possible for a REDUCE to be followed by an error */\n  assert( yyact!=YY_ERROR_ACTION );\n\n  yymsp += yysize+1;\n  yypParser->yytos = yymsp;\n  yymsp->stateno = (YYACTIONTYPE)yyact;\n  yymsp->major = (YYCODETYPE)yygoto;\n  yyTraceShift(yypParser, yyact, \"... then shift\");\n  return yyact;\n}\n\n/*\n** The following code executes when the parse fails\n*/\n#ifndef YYNOERRORRECOVERY\nstatic void yy_parse_failed(\n  yyParser *yypParser           /* The parser */\n){\n  sqlite3ParserARG_FETCH\n  sqlite3ParserCTX_FETCH\n#ifndef NDEBUG\n  if( yyTraceFILE ){\n    fprintf(yyTraceFILE,\"%sFail!\\n\",yyTracePrompt);\n  }\n#endif\n  while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);\n  /* Here code is inserted which will be executed whenever the\n  ** parser fails */\n/************ Begin %parse_failure code ***************************************/\n/************ End %parse_failure code *****************************************/\n  sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */\n  sqlite3ParserCTX_STORE\n}\n#endif /* YYNOERRORRECOVERY */\n\n/*\n** The following code executes when a syntax error first occurs.\n*/\nstatic void yy_syntax_error(\n  yyParser *yypParser,           /* The parser */\n  int yymajor,                   /* The major type of the error token */\n  sqlite3ParserTOKENTYPE yyminor         /* The minor type of the error token */\n){\n  sqlite3ParserARG_FETCH\n  sqlite3ParserCTX_FETCH\n#define TOKEN yyminor\n/************ Begin %syntax_error code ****************************************/\n\n  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */\n  if( TOKEN.z[0] ){\n    sqlite3ErrorMsg(pParse, \"near \\\"%T\\\": syntax error\", &TOKEN);\n  }else{\n    sqlite3ErrorMsg(pParse, \"incomplete input\");\n  }\n/************ End %syntax_error code ******************************************/\n  sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */\n  sqlite3ParserCTX_STORE\n}\n\n/*\n** The following is executed when the parser accepts\n*/\nstatic void yy_accept(\n  yyParser *yypParser           /* The parser */\n){\n  sqlite3ParserARG_FETCH\n  sqlite3ParserCTX_FETCH\n#ifndef NDEBUG\n  if( yyTraceFILE ){\n    fprintf(yyTraceFILE,\"%sAccept!\\n\",yyTracePrompt);\n  }\n#endif\n#ifndef YYNOERRORRECOVERY\n  yypParser->yyerrcnt = -1;\n#endif\n  assert( yypParser->yytos==yypParser->yystack );\n  /* Here code is inserted which will be executed whenever the\n  ** parser accepts */\n/*********** Begin %parse_accept code *****************************************/\n/*********** End %parse_accept code *******************************************/\n  sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */\n  sqlite3ParserCTX_STORE\n}\n\n/* The main parser program.\n** The first argument is a pointer to a structure obtained from\n** \"sqlite3ParserAlloc\" which describes the current state of the parser.\n** The second argument is the major token number.  The third is\n** the minor token.  The fourth optional argument is whatever the\n** user wants (and specified in the grammar) and is available for\n** use by the action routines.\n**\n** Inputs:\n** <ul>\n** <li> A pointer to the parser (an opaque structure.)\n** <li> The major token number.\n** <li> The minor token number.\n** <li> An option argument of a grammar-specified type.\n** </ul>\n**\n** Outputs:\n** None.\n*/\nSQLITE_PRIVATE void sqlite3Parser(\n  void *yyp,                   /* The parser */\n  int yymajor,                 /* The major token code number */\n  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */\n  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */\n){\n  YYMINORTYPE yyminorunion;\n  YYACTIONTYPE yyact;   /* The parser action. */\n#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)\n  int yyendofinput;     /* True if we are at the end of input */\n#endif\n#ifdef YYERRORSYMBOL\n  int yyerrorhit = 0;   /* True if yymajor has invoked an error */\n#endif\n  yyParser *yypParser = (yyParser*)yyp;  /* The parser */\n  sqlite3ParserCTX_FETCH\n  sqlite3ParserARG_STORE\n\n  assert( yypParser->yytos!=0 );\n#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)\n  yyendofinput = (yymajor==0);\n#endif\n\n  yyact = yypParser->yytos->stateno;\n#ifndef NDEBUG\n  if( yyTraceFILE ){\n    if( yyact < YY_MIN_REDUCE ){\n      fprintf(yyTraceFILE,\"%sInput '%s' in state %d\\n\",\n              yyTracePrompt,yyTokenName[yymajor],yyact);\n    }else{\n      fprintf(yyTraceFILE,\"%sInput '%s' with pending reduce %d\\n\",\n              yyTracePrompt,yyTokenName[yymajor],yyact-YY_MIN_REDUCE);\n    }\n  }\n#endif\n\n  do{\n    assert( yyact==yypParser->yytos->stateno );\n    yyact = yy_find_shift_action((YYCODETYPE)yymajor,yyact);\n    if( yyact >= YY_MIN_REDUCE ){\n      yyact = yy_reduce(yypParser,yyact-YY_MIN_REDUCE,yymajor,\n                        yyminor sqlite3ParserCTX_PARAM);\n    }else if( yyact <= YY_MAX_SHIFTREDUCE ){\n      yy_shift(yypParser,yyact,(YYCODETYPE)yymajor,yyminor);\n#ifndef YYNOERRORRECOVERY\n      yypParser->yyerrcnt--;\n#endif\n      break;\n    }else if( yyact==YY_ACCEPT_ACTION ){\n      yypParser->yytos--;\n      yy_accept(yypParser);\n      return;\n    }else{\n      assert( yyact == YY_ERROR_ACTION );\n      yyminorunion.yy0 = yyminor;\n#ifdef YYERRORSYMBOL\n      int yymx;\n#endif\n#ifndef NDEBUG\n      if( yyTraceFILE ){\n        fprintf(yyTraceFILE,\"%sSyntax Error!\\n\",yyTracePrompt);\n      }\n#endif\n#ifdef YYERRORSYMBOL\n      /* A syntax error has occurred.\n      ** The response to an error depends upon whether or not the\n      ** grammar defines an error token \"ERROR\".  \n      **\n      ** This is what we do if the grammar does define ERROR:\n      **\n      **  * Call the %syntax_error function.\n      **\n      **  * Begin popping the stack until we enter a state where\n      **    it is legal to shift the error symbol, then shift\n      **    the error symbol.\n      **\n      **  * Set the error count to three.\n      **\n      **  * Begin accepting and shifting new tokens.  No new error\n      **    processing will occur until three tokens have been\n      **    shifted successfully.\n      **\n      */\n      if( yypParser->yyerrcnt<0 ){\n        yy_syntax_error(yypParser,yymajor,yyminor);\n      }\n      yymx = yypParser->yytos->major;\n      if( yymx==YYERRORSYMBOL || yyerrorhit ){\n#ifndef NDEBUG\n        if( yyTraceFILE ){\n          fprintf(yyTraceFILE,\"%sDiscard input token %s\\n\",\n             yyTracePrompt,yyTokenName[yymajor]);\n        }\n#endif\n        yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);\n        yymajor = YYNOCODE;\n      }else{\n        while( yypParser->yytos >= yypParser->yystack\n            && (yyact = yy_find_reduce_action(\n                        yypParser->yytos->stateno,\n                        YYERRORSYMBOL)) > YY_MAX_SHIFTREDUCE\n        ){\n          yy_pop_parser_stack(yypParser);\n        }\n        if( yypParser->yytos < yypParser->yystack || yymajor==0 ){\n          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);\n          yy_parse_failed(yypParser);\n#ifndef YYNOERRORRECOVERY\n          yypParser->yyerrcnt = -1;\n#endif\n          yymajor = YYNOCODE;\n        }else if( yymx!=YYERRORSYMBOL ){\n          yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);\n        }\n      }\n      yypParser->yyerrcnt = 3;\n      yyerrorhit = 1;\n      if( yymajor==YYNOCODE ) break;\n      yyact = yypParser->yytos->stateno;\n#elif defined(YYNOERRORRECOVERY)\n      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to\n      ** do any kind of error recovery.  Instead, simply invoke the syntax\n      ** error routine and continue going as if nothing had happened.\n      **\n      ** Applications can set this macro (for example inside %include) if\n      ** they intend to abandon the parse upon the first syntax error seen.\n      */\n      yy_syntax_error(yypParser,yymajor, yyminor);\n      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);\n      break;\n#else  /* YYERRORSYMBOL is not defined */\n      /* This is what we do if the grammar does not define ERROR:\n      **\n      **  * Report an error message, and throw away the input token.\n      **\n      **  * If the input token is $, then fail the parse.\n      **\n      ** As before, subsequent error messages are suppressed until\n      ** three input tokens have been successfully shifted.\n      */\n      if( yypParser->yyerrcnt<=0 ){\n        yy_syntax_error(yypParser,yymajor, yyminor);\n      }\n      yypParser->yyerrcnt = 3;\n      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);\n      if( yyendofinput ){\n        yy_parse_failed(yypParser);\n#ifndef YYNOERRORRECOVERY\n        yypParser->yyerrcnt = -1;\n#endif\n      }\n      break;\n#endif\n    }\n  }while( yypParser->yytos>yypParser->yystack );\n#ifndef NDEBUG\n  if( yyTraceFILE ){\n    yyStackEntry *i;\n    char cDiv = '[';\n    fprintf(yyTraceFILE,\"%sReturn. Stack=\",yyTracePrompt);\n    for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){\n      fprintf(yyTraceFILE,\"%c%s\", cDiv, yyTokenName[i->major]);\n      cDiv = ' ';\n    }\n    fprintf(yyTraceFILE,\"]\\n\");\n  }\n#endif\n  return;\n}\n\n/*\n** Return the fallback token corresponding to canonical token iToken, or\n** 0 if iToken has no fallback.\n*/\nSQLITE_PRIVATE int sqlite3ParserFallback(int iToken){\n#ifdef YYFALLBACK\n  assert( iToken<(int)(sizeof(yyFallback)/sizeof(yyFallback[0])) );\n  return yyFallback[iToken];\n#else\n  (void)iToken;\n  return 0;\n#endif\n}\n\n/************** End of parse.c ***********************************************/\n/************** Begin file tokenize.c ****************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** An tokenizer for SQL\n**\n** This file contains C code that splits an SQL input string up into\n** individual tokens and sends those tokens one-by-one over to the\n** parser for analysis.\n*/\n/* #include \"sqliteInt.h\" */\n/* #include <stdlib.h> */\n\n/* Character classes for tokenizing\n**\n** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented\n** using a lookup table, whereas a switch() directly on c uses a binary search.\n** The lookup table is much faster.  To maximize speed, and to ensure that\n** a lookup table is used, all of the classes need to be small integers and\n** all of them need to be used within the switch.\n*/\n#define CC_X          0    /* The letter 'x', or start of BLOB literal */\n#define CC_KYWD       1    /* Alphabetics or '_'.  Usable in a keyword */\n#define CC_ID         2    /* unicode characters usable in IDs */\n#define CC_DIGIT      3    /* Digits */\n#define CC_DOLLAR     4    /* '$' */\n#define CC_VARALPHA   5    /* '@', '#', ':'.  Alphabetic SQL variables */\n#define CC_VARNUM     6    /* '?'.  Numeric SQL variables */\n#define CC_SPACE      7    /* Space characters */\n#define CC_QUOTE      8    /* '\"', '\\'', or '`'.  String literals, quoted ids */\n#define CC_QUOTE2     9    /* '['.   [...] style quoted ids */\n#define CC_PIPE      10    /* '|'.   Bitwise OR or concatenate */\n#define CC_MINUS     11    /* '-'.  Minus or SQL-style comment */\n#define CC_LT        12    /* '<'.  Part of < or <= or <> */\n#define CC_GT        13    /* '>'.  Part of > or >= */\n#define CC_EQ        14    /* '='.  Part of = or == */\n#define CC_BANG      15    /* '!'.  Part of != */\n#define CC_SLASH     16    /* '/'.  / or c-style comment */\n#define CC_LP        17    /* '(' */\n#define CC_RP        18    /* ')' */\n#define CC_SEMI      19    /* ';' */\n#define CC_PLUS      20    /* '+' */\n#define CC_STAR      21    /* '*' */\n#define CC_PERCENT   22    /* '%' */\n#define CC_COMMA     23    /* ',' */\n#define CC_AND       24    /* '&' */\n#define CC_TILDA     25    /* '~' */\n#define CC_DOT       26    /* '.' */\n#define CC_ILLEGAL   27    /* Illegal character */\n#define CC_NUL       28    /* 0x00 */\n\nstatic const unsigned char aiClass[] = {\n#ifdef SQLITE_ASCII\n/*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */\n/* 0x */   28, 27, 27, 27, 27, 27, 27, 27, 27,  7,  7, 27,  7,  7, 27, 27,\n/* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,\n/* 2x */    7, 15,  8,  5,  4, 22, 24,  8, 17, 18, 21, 20, 23, 11, 26, 16,\n/* 3x */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  5, 19, 12, 14, 13,  6,\n/* 4x */    5,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,\n/* 5x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  9, 27, 27, 27,  1,\n/* 6x */    8,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,\n/* 7x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1, 27, 10, 27, 25, 27,\n/* 8x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,\n/* 9x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,\n/* Ax */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,\n/* Bx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,\n/* Cx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,\n/* Dx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,\n/* Ex */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,\n/* Fx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2\n#endif\n#ifdef SQLITE_EBCDIC\n/*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */\n/* 0x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27,  7,  7, 27, 27,\n/* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,\n/* 2x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,\n/* 3x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,\n/* 4x */    7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,\n/* 5x */   24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15,  4, 21, 18, 19, 27,\n/* 6x */   11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22,  1, 13,  6,\n/* 7x */   27, 27, 27, 27, 27, 27, 27, 27, 27,  8,  5,  5,  5,  8, 14,  8,\n/* 8x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,\n/* 9x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,\n/* Ax */   27, 25,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,\n/* Bx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  9, 27, 27, 27, 27, 27,\n/* Cx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,\n/* Dx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,\n/* Ex */   27, 27,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,\n/* Fx */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3, 27, 27, 27, 27, 27, 27,\n#endif\n};\n\n/*\n** The charMap() macro maps alphabetic characters (only) into their\n** lower-case ASCII equivalent.  On ASCII machines, this is just\n** an upper-to-lower case map.  On EBCDIC machines we also need\n** to adjust the encoding.  The mapping is only valid for alphabetics\n** which are the only characters for which this feature is used. \n**\n** Used by keywordhash.h\n*/\n#ifdef SQLITE_ASCII\n# define charMap(X) sqlite3UpperToLower[(unsigned char)X]\n#endif\n#ifdef SQLITE_EBCDIC\n# define charMap(X) ebcdicToAscii[(unsigned char)X]\nconst unsigned char ebcdicToAscii[] = {\n/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */\n   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */\n   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */\n   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */\n   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */\n   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */\n   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */\n};\n#endif\n\n/*\n** The sqlite3KeywordCode function looks up an identifier to determine if\n** it is a keyword.  If it is a keyword, the token code of that keyword is \n** returned.  If the input is not a keyword, TK_ID is returned.\n**\n** The implementation of this routine was generated by a program,\n** mkkeywordhash.c, located in the tool subdirectory of the distribution.\n** The output of the mkkeywordhash.c program is written into a file\n** named keywordhash.h and then included into this source file by\n** the #include below.\n*/\n/************** Include keywordhash.h in the middle of tokenize.c ************/\n/************** Begin file keywordhash.h *************************************/\n/***** This file contains automatically generated code ******\n**\n** The code in this file has been automatically generated by\n**\n**   sqlite/tool/mkkeywordhash.c\n**\n** The code in this file implements a function that determines whether\n** or not a given identifier is really an SQL keyword.  The same thing\n** might be implemented more directly using a hand-written hash table.\n** But by using this automatically generated code, the size of the code\n** is substantially reduced.  This is important for embedded applications\n** on platforms with limited memory.\n*/\n/* Hash score: 227 */\n/* zKWText[] encodes 984 bytes of keyword text in 648 bytes */\n/*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */\n/*   ABLEFTHENDEFERRABLELSEXCLUDELETEMPORARYISNULLSAVEPOINTERSECT       */\n/*   IESNOTNULLIKEXCEPTRANSACTIONATURALTERAISEXCLUSIVEXISTS             */\n/*   CONSTRAINTOFFSETRIGGERANGENERATEDETACHAVINGLOBEGINNEREFERENCES     */\n/*   UNIQUERYWITHOUTERELEASEATTACHBETWEENOTHINGROUPSCASCADEFAULT        */\n/*   CASECOLLATECREATECURRENT_DATEIMMEDIATEJOINSERTMATCHPLANALYZE       */\n/*   PRAGMABORTUPDATEVALUESVIRTUALWAYSWHENWHERECURSIVEAFTERENAMEAND     */\n/*   EFERREDISTINCTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS           */\n/*   CURRENT_TIMESTAMPARTITIONDROPRECEDINGFAILASTFILTEREPLACEFIRST      */\n/*   FOLLOWINGFROMFULLIMITIFORDERESTRICTOTHERSOVERIGHTROLLBACKROWS      */\n/*   UNBOUNDEDUNIONUSINGVACUUMVIEWINDOWBYINITIALLYPRIMARY               */\nstatic const char zKWText[647] = {\n  'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',\n  'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',\n  'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',\n  'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',\n  'E','R','R','A','B','L','E','L','S','E','X','C','L','U','D','E','L','E',\n  'T','E','M','P','O','R','A','R','Y','I','S','N','U','L','L','S','A','V',\n  'E','P','O','I','N','T','E','R','S','E','C','T','I','E','S','N','O','T',\n  'N','U','L','L','I','K','E','X','C','E','P','T','R','A','N','S','A','C',\n  'T','I','O','N','A','T','U','R','A','L','T','E','R','A','I','S','E','X',\n  'C','L','U','S','I','V','E','X','I','S','T','S','C','O','N','S','T','R',\n  'A','I','N','T','O','F','F','S','E','T','R','I','G','G','E','R','A','N',\n  'G','E','N','E','R','A','T','E','D','E','T','A','C','H','A','V','I','N',\n  'G','L','O','B','E','G','I','N','N','E','R','E','F','E','R','E','N','C',\n  'E','S','U','N','I','Q','U','E','R','Y','W','I','T','H','O','U','T','E',\n  'R','E','L','E','A','S','E','A','T','T','A','C','H','B','E','T','W','E',\n  'E','N','O','T','H','I','N','G','R','O','U','P','S','C','A','S','C','A',\n  'D','E','F','A','U','L','T','C','A','S','E','C','O','L','L','A','T','E',\n  'C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A','T','E',\n  'I','M','M','E','D','I','A','T','E','J','O','I','N','S','E','R','T','M',\n  'A','T','C','H','P','L','A','N','A','L','Y','Z','E','P','R','A','G','M',\n  'A','B','O','R','T','U','P','D','A','T','E','V','A','L','U','E','S','V',\n  'I','R','T','U','A','L','W','A','Y','S','W','H','E','N','W','H','E','R',\n  'E','C','U','R','S','I','V','E','A','F','T','E','R','E','N','A','M','E',\n  'A','N','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','A',\n  'U','T','O','I','N','C','R','E','M','E','N','T','C','A','S','T','C','O',\n  'L','U','M','N','C','O','M','M','I','T','C','O','N','F','L','I','C','T',\n  'C','R','O','S','S','C','U','R','R','E','N','T','_','T','I','M','E','S',\n  'T','A','M','P','A','R','T','I','T','I','O','N','D','R','O','P','R','E',\n  'C','E','D','I','N','G','F','A','I','L','A','S','T','F','I','L','T','E',\n  'R','E','P','L','A','C','E','F','I','R','S','T','F','O','L','L','O','W',\n  'I','N','G','F','R','O','M','F','U','L','L','I','M','I','T','I','F','O',\n  'R','D','E','R','E','S','T','R','I','C','T','O','T','H','E','R','S','O',\n  'V','E','R','I','G','H','T','R','O','L','L','B','A','C','K','R','O','W',\n  'S','U','N','B','O','U','N','D','E','D','U','N','I','O','N','U','S','I',\n  'N','G','V','A','C','U','U','M','V','I','E','W','I','N','D','O','W','B',\n  'Y','I','N','I','T','I','A','L','L','Y','P','R','I','M','A','R','Y',\n};\n/* aKWHash[i] is the hash value for the i-th keyword */\nstatic const unsigned char aKWHash[127] = {\n    84, 102, 132,  82, 114,  29,   0,   0,  91,   0,  85,  72,   0,\n    53,  35,  86,  15,   0,  42,  94,  54, 126, 133,  19,   0,   0,\n   138,   0,  40, 128,   0,  22, 104,   0,   9,   0,   0, 122,  80,\n     0,  78,   6,   0,  65,  99, 145,   0, 134, 112,   0,   0,  48,\n     0, 100,  24,   0,  17,   0,  27,  70,  23,  26,   5,  60, 140,\n   107, 121,   0,  73, 101,  71, 143,  61, 119,  74,   0,  49,   0,\n    11,  41,   0, 110,   0,   0,   0, 106,  10, 108, 113, 124,  14,\n    50, 123,   0,  89,   0,  18, 120, 142,  56, 129, 137,  88,  83,\n    37,  30, 125,   0,   0, 105,  51, 130, 127,   0,  34,   0,   0,\n    44,   0,  95,  38,  39,   0,  20,  45, 116,  90,\n};\n/* aKWNext[] forms the hash collision chain.  If aKWHash[i]==0\n** then the i-th keyword has no more hash collisions.  Otherwise,\n** the next keyword with the same hash is aKWHash[i]-1. */\nstatic const unsigned char aKWNext[145] = {\n     0,   0,   0,   0,   4,   0,  43,   0,   0, 103, 111,   0,   0,\n     0,   2,   0,   0, 141,   0,   0,   0,  13,   0,   0,   0,   0,\n   139,   0,   0, 118,  52,   0,   0, 135,  12,   0,   0,  62,   0,\n   136,   0, 131,   0,   0,  36,   0,   0,  28,  77,   0,   0,   0,\n     0,  59,   0,  47,   0,   0,   0,   0,   0,   0,   0,   0,   0,\n     0,  69,   0,   0,   0,   0,   0, 144,   3,   0,  58,   0,   1,\n    75,   0,   0,   0,  31,   0,   0,   0,   0,   0,   0,  64,  66,\n    63,   0,   0,   0,   0,  46,   0,  16,   0, 115,   0,   0,   0,\n     0,   0,   0,   0,   0,   0,   0,  81,  97,   0,   8,   0, 109,\n    21,   7,  67,   0,  79,  93, 117,   0,   0,  68,   0,   0,  96,\n     0,  55,   0,  76,   0,  92,  32,  33,  57,  25,   0,  98,   0,\n     0,  87,\n};\n/* aKWLen[i] is the length (in bytes) of the i-th keyword */\nstatic const unsigned char aKWLen[145] = {\n     7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,\n     7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   7,\n     6,   9,   4,   2,   6,   5,   9,   9,   4,   7,   3,   2,   4,\n     4,   6,  11,   6,   2,   7,   5,   5,   9,   6,  10,   4,   6,\n     2,   3,   7,   5,   9,   6,   6,   4,   5,   5,  10,   6,   5,\n     7,   4,   5,   7,   6,   7,   7,   6,   5,   7,   3,   7,   4,\n     7,   6,  12,   9,   4,   6,   5,   4,   7,   6,   5,   6,   6,\n     7,   6,   4,   5,   9,   5,   6,   3,   8,   8,   2,  13,   2,\n     2,   4,   6,   6,   8,   5,  17,  12,   7,   9,   4,   9,   4,\n     4,   6,   7,   5,   9,   4,   4,   5,   2,   5,   8,   6,   4,\n     5,   8,   4,   3,   9,   5,   5,   6,   4,   6,   2,   2,   9,\n     3,   7,\n};\n/* aKWOffset[i] is the index into zKWText[] of the start of\n** the text for the i-th keyword. */\nstatic const unsigned short int aKWOffset[145] = {\n     0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,\n    36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,\n    86,  90,  90,  94,  99, 101, 105, 111, 119, 123, 123, 123, 126,\n   129, 132, 137, 142, 146, 147, 152, 156, 160, 168, 174, 181, 184,\n   184, 187, 189, 195, 198, 206, 211, 216, 219, 222, 226, 236, 239,\n   244, 244, 248, 252, 259, 265, 271, 277, 277, 283, 284, 288, 295,\n   299, 306, 312, 324, 333, 335, 341, 346, 348, 355, 360, 365, 371,\n   377, 382, 388, 392, 395, 404, 408, 414, 416, 423, 424, 431, 433,\n   435, 444, 448, 454, 460, 468, 473, 473, 473, 489, 498, 501, 510,\n   513, 517, 522, 529, 534, 543, 547, 550, 555, 557, 561, 569, 575,\n   578, 583, 591, 591, 595, 604, 609, 614, 620, 623, 626, 629, 631,\n   636, 640,\n};\n/* aKWCode[i] is the parser symbol code for the i-th keyword */\nstatic const unsigned char aKWCode[145] = {\n  TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     \n  TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    \n  TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    \n  TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      \n  TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       \n  TK_EXCLUDE,    TK_DELETE,     TK_TEMP,       TK_TEMP,       TK_OR,         \n  TK_ISNULL,     TK_NULLS,      TK_SAVEPOINT,  TK_INTERSECT,  TK_TIES,       \n  TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,    \n  TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    \n  TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_CONSTRAINT, \n  TK_INTO,       TK_OFFSET,     TK_OF,         TK_SET,        TK_TRIGGER,    \n  TK_RANGE,      TK_GENERATED,  TK_DETACH,     TK_HAVING,     TK_LIKE_KW,    \n  TK_BEGIN,      TK_JOIN_KW,    TK_REFERENCES, TK_UNIQUE,     TK_QUERY,      \n  TK_WITHOUT,    TK_WITH,       TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     \n  TK_BETWEEN,    TK_NOTHING,    TK_GROUPS,     TK_GROUP,      TK_CASCADE,    \n  TK_ASC,        TK_DEFAULT,    TK_CASE,       TK_COLLATE,    TK_CREATE,     \n  TK_CTIME_KW,   TK_IMMEDIATE,  TK_JOIN,       TK_INSERT,     TK_MATCH,      \n  TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,     TK_ABORT,      TK_UPDATE,     \n  TK_VALUES,     TK_VIRTUAL,    TK_ALWAYS,     TK_WHEN,       TK_WHERE,      \n  TK_RECURSIVE,  TK_AFTER,      TK_RENAME,     TK_AND,        TK_DEFERRED,   \n  TK_DISTINCT,   TK_IS,         TK_AUTOINCR,   TK_TO,         TK_IN,         \n  TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    \n  TK_CTIME_KW,   TK_CTIME_KW,   TK_CURRENT,    TK_PARTITION,  TK_DROP,       \n  TK_PRECEDING,  TK_FAIL,       TK_LAST,       TK_FILTER,     TK_REPLACE,    \n  TK_FIRST,      TK_FOLLOWING,  TK_FROM,       TK_JOIN_KW,    TK_LIMIT,      \n  TK_IF,         TK_ORDER,      TK_RESTRICT,   TK_OTHERS,     TK_OVER,       \n  TK_JOIN_KW,    TK_ROLLBACK,   TK_ROWS,       TK_ROW,        TK_UNBOUNDED,  \n  TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_WINDOW,     \n  TK_DO,         TK_BY,         TK_INITIALLY,  TK_ALL,        TK_PRIMARY,    \n};\n/* Hash table decoded:\n**   0: INSERT\n**   1: IS\n**   2: ROLLBACK TRIGGER\n**   3: IMMEDIATE\n**   4: PARTITION\n**   5: TEMP\n**   6:\n**   7:\n**   8: VALUES WITHOUT\n**   9:\n**  10: MATCH\n**  11: NOTHING\n**  12:\n**  13: OF\n**  14: TIES IGNORE\n**  15: PLAN\n**  16: INSTEAD INDEXED\n**  17:\n**  18: TRANSACTION RIGHT\n**  19: WHEN\n**  20: SET HAVING\n**  21: IF\n**  22: ROWS\n**  23: SELECT\n**  24:\n**  25:\n**  26: VACUUM SAVEPOINT\n**  27:\n**  28: LIKE UNION VIRTUAL REFERENCES\n**  29: RESTRICT\n**  30:\n**  31: THEN REGEXP\n**  32: TO\n**  33:\n**  34: BEFORE\n**  35:\n**  36:\n**  37: FOLLOWING COLLATE CASCADE\n**  38: CREATE\n**  39:\n**  40: CASE REINDEX\n**  41: EACH\n**  42:\n**  43: QUERY\n**  44: AND ADD\n**  45: PRIMARY ANALYZE\n**  46:\n**  47: ROW ASC DETACH\n**  48: CURRENT_TIME CURRENT_DATE\n**  49:\n**  50:\n**  51: EXCLUSIVE TEMPORARY\n**  52:\n**  53: DEFERRED\n**  54: DEFERRABLE\n**  55:\n**  56: DATABASE\n**  57:\n**  58: DELETE VIEW GENERATED\n**  59: ATTACH\n**  60: END\n**  61: EXCLUDE\n**  62: ESCAPE DESC\n**  63: GLOB\n**  64: WINDOW ELSE\n**  65: COLUMN\n**  66: FIRST\n**  67:\n**  68: GROUPS ALL\n**  69: DISTINCT DROP KEY\n**  70: BETWEEN\n**  71: INITIALLY\n**  72: BEGIN\n**  73: FILTER CHECK ACTION\n**  74: GROUP INDEX\n**  75:\n**  76: EXISTS DEFAULT\n**  77:\n**  78: FOR CURRENT_TIMESTAMP\n**  79: EXCEPT\n**  80:\n**  81: CROSS\n**  82:\n**  83:\n**  84:\n**  85: CAST\n**  86: FOREIGN AUTOINCREMENT\n**  87: COMMIT\n**  88: CURRENT AFTER ALTER\n**  89: FULL FAIL CONFLICT\n**  90: EXPLAIN\n**  91: CONSTRAINT\n**  92: FROM ALWAYS\n**  93:\n**  94: ABORT\n**  95:\n**  96: AS DO\n**  97: REPLACE WITH RELEASE\n**  98: BY RENAME\n**  99: RANGE RAISE\n** 100: OTHERS\n** 101: USING NULLS\n** 102: PRAGMA\n** 103: JOIN ISNULL OFFSET\n** 104: NOT\n** 105: OR LAST LEFT\n** 106: LIMIT\n** 107:\n** 108:\n** 109: IN\n** 110: INTO\n** 111: OVER RECURSIVE\n** 112: ORDER OUTER\n** 113:\n** 114: INTERSECT UNBOUNDED\n** 115:\n** 116:\n** 117: ON\n** 118:\n** 119: WHERE\n** 120: NO INNER\n** 121: NULL\n** 122:\n** 123: TABLE\n** 124: NATURAL NOTNULL\n** 125: PRECEDING\n** 126: UPDATE UNIQUE\n*/\n/* Check to see if z[0..n-1] is a keyword. If it is, write the\n** parser symbol code for that keyword into *pType.  Always\n** return the integer n (the length of the token). */\nstatic int keywordCode(const char *z, int n, int *pType){\n  int i, j;\n  const char *zKW;\n  if( n>=2 ){\n    i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;\n    for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){\n      if( aKWLen[i]!=n ) continue;\n      zKW = &zKWText[aKWOffset[i]];\n#ifdef SQLITE_ASCII\n      if( (z[0]&~0x20)!=zKW[0] ) continue;\n      if( (z[1]&~0x20)!=zKW[1] ) continue;\n      j = 2;\n      while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }\n#endif\n#ifdef SQLITE_EBCDIC\n      if( toupper(z[0])!=zKW[0] ) continue;\n      if( toupper(z[1])!=zKW[1] ) continue;\n      j = 2;\n      while( j<n && toupper(z[j])==zKW[j] ){ j++; }\n#endif\n      if( j<n ) continue;\n      testcase( i==0 ); /* REINDEX */\n      testcase( i==1 ); /* INDEXED */\n      testcase( i==2 ); /* INDEX */\n      testcase( i==3 ); /* DESC */\n      testcase( i==4 ); /* ESCAPE */\n      testcase( i==5 ); /* EACH */\n      testcase( i==6 ); /* CHECK */\n      testcase( i==7 ); /* KEY */\n      testcase( i==8 ); /* BEFORE */\n      testcase( i==9 ); /* FOREIGN */\n      testcase( i==10 ); /* FOR */\n      testcase( i==11 ); /* IGNORE */\n      testcase( i==12 ); /* REGEXP */\n      testcase( i==13 ); /* EXPLAIN */\n      testcase( i==14 ); /* INSTEAD */\n      testcase( i==15 ); /* ADD */\n      testcase( i==16 ); /* DATABASE */\n      testcase( i==17 ); /* AS */\n      testcase( i==18 ); /* SELECT */\n      testcase( i==19 ); /* TABLE */\n      testcase( i==20 ); /* LEFT */\n      testcase( i==21 ); /* THEN */\n      testcase( i==22 ); /* END */\n      testcase( i==23 ); /* DEFERRABLE */\n      testcase( i==24 ); /* ELSE */\n      testcase( i==25 ); /* EXCLUDE */\n      testcase( i==26 ); /* DELETE */\n      testcase( i==27 ); /* TEMPORARY */\n      testcase( i==28 ); /* TEMP */\n      testcase( i==29 ); /* OR */\n      testcase( i==30 ); /* ISNULL */\n      testcase( i==31 ); /* NULLS */\n      testcase( i==32 ); /* SAVEPOINT */\n      testcase( i==33 ); /* INTERSECT */\n      testcase( i==34 ); /* TIES */\n      testcase( i==35 ); /* NOTNULL */\n      testcase( i==36 ); /* NOT */\n      testcase( i==37 ); /* NO */\n      testcase( i==38 ); /* NULL */\n      testcase( i==39 ); /* LIKE */\n      testcase( i==40 ); /* EXCEPT */\n      testcase( i==41 ); /* TRANSACTION */\n      testcase( i==42 ); /* ACTION */\n      testcase( i==43 ); /* ON */\n      testcase( i==44 ); /* NATURAL */\n      testcase( i==45 ); /* ALTER */\n      testcase( i==46 ); /* RAISE */\n      testcase( i==47 ); /* EXCLUSIVE */\n      testcase( i==48 ); /* EXISTS */\n      testcase( i==49 ); /* CONSTRAINT */\n      testcase( i==50 ); /* INTO */\n      testcase( i==51 ); /* OFFSET */\n      testcase( i==52 ); /* OF */\n      testcase( i==53 ); /* SET */\n      testcase( i==54 ); /* TRIGGER */\n      testcase( i==55 ); /* RANGE */\n      testcase( i==56 ); /* GENERATED */\n      testcase( i==57 ); /* DETACH */\n      testcase( i==58 ); /* HAVING */\n      testcase( i==59 ); /* GLOB */\n      testcase( i==60 ); /* BEGIN */\n      testcase( i==61 ); /* INNER */\n      testcase( i==62 ); /* REFERENCES */\n      testcase( i==63 ); /* UNIQUE */\n      testcase( i==64 ); /* QUERY */\n      testcase( i==65 ); /* WITHOUT */\n      testcase( i==66 ); /* WITH */\n      testcase( i==67 ); /* OUTER */\n      testcase( i==68 ); /* RELEASE */\n      testcase( i==69 ); /* ATTACH */\n      testcase( i==70 ); /* BETWEEN */\n      testcase( i==71 ); /* NOTHING */\n      testcase( i==72 ); /* GROUPS */\n      testcase( i==73 ); /* GROUP */\n      testcase( i==74 ); /* CASCADE */\n      testcase( i==75 ); /* ASC */\n      testcase( i==76 ); /* DEFAULT */\n      testcase( i==77 ); /* CASE */\n      testcase( i==78 ); /* COLLATE */\n      testcase( i==79 ); /* CREATE */\n      testcase( i==80 ); /* CURRENT_DATE */\n      testcase( i==81 ); /* IMMEDIATE */\n      testcase( i==82 ); /* JOIN */\n      testcase( i==83 ); /* INSERT */\n      testcase( i==84 ); /* MATCH */\n      testcase( i==85 ); /* PLAN */\n      testcase( i==86 ); /* ANALYZE */\n      testcase( i==87 ); /* PRAGMA */\n      testcase( i==88 ); /* ABORT */\n      testcase( i==89 ); /* UPDATE */\n      testcase( i==90 ); /* VALUES */\n      testcase( i==91 ); /* VIRTUAL */\n      testcase( i==92 ); /* ALWAYS */\n      testcase( i==93 ); /* WHEN */\n      testcase( i==94 ); /* WHERE */\n      testcase( i==95 ); /* RECURSIVE */\n      testcase( i==96 ); /* AFTER */\n      testcase( i==97 ); /* RENAME */\n      testcase( i==98 ); /* AND */\n      testcase( i==99 ); /* DEFERRED */\n      testcase( i==100 ); /* DISTINCT */\n      testcase( i==101 ); /* IS */\n      testcase( i==102 ); /* AUTOINCREMENT */\n      testcase( i==103 ); /* TO */\n      testcase( i==104 ); /* IN */\n      testcase( i==105 ); /* CAST */\n      testcase( i==106 ); /* COLUMN */\n      testcase( i==107 ); /* COMMIT */\n      testcase( i==108 ); /* CONFLICT */\n      testcase( i==109 ); /* CROSS */\n      testcase( i==110 ); /* CURRENT_TIMESTAMP */\n      testcase( i==111 ); /* CURRENT_TIME */\n      testcase( i==112 ); /* CURRENT */\n      testcase( i==113 ); /* PARTITION */\n      testcase( i==114 ); /* DROP */\n      testcase( i==115 ); /* PRECEDING */\n      testcase( i==116 ); /* FAIL */\n      testcase( i==117 ); /* LAST */\n      testcase( i==118 ); /* FILTER */\n      testcase( i==119 ); /* REPLACE */\n      testcase( i==120 ); /* FIRST */\n      testcase( i==121 ); /* FOLLOWING */\n      testcase( i==122 ); /* FROM */\n      testcase( i==123 ); /* FULL */\n      testcase( i==124 ); /* LIMIT */\n      testcase( i==125 ); /* IF */\n      testcase( i==126 ); /* ORDER */\n      testcase( i==127 ); /* RESTRICT */\n      testcase( i==128 ); /* OTHERS */\n      testcase( i==129 ); /* OVER */\n      testcase( i==130 ); /* RIGHT */\n      testcase( i==131 ); /* ROLLBACK */\n      testcase( i==132 ); /* ROWS */\n      testcase( i==133 ); /* ROW */\n      testcase( i==134 ); /* UNBOUNDED */\n      testcase( i==135 ); /* UNION */\n      testcase( i==136 ); /* USING */\n      testcase( i==137 ); /* VACUUM */\n      testcase( i==138 ); /* VIEW */\n      testcase( i==139 ); /* WINDOW */\n      testcase( i==140 ); /* DO */\n      testcase( i==141 ); /* BY */\n      testcase( i==142 ); /* INITIALLY */\n      testcase( i==143 ); /* ALL */\n      testcase( i==144 ); /* PRIMARY */\n      *pType = aKWCode[i];\n      break;\n    }\n  }\n  return n;\n}\nSQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){\n  int id = TK_ID;\n  keywordCode((char*)z, n, &id);\n  return id;\n}\n#define SQLITE_N_KEYWORD 145\nSQLITE_API int sqlite3_keyword_name(int i,const char **pzName,int *pnName){\n  if( i<0 || i>=SQLITE_N_KEYWORD ) return SQLITE_ERROR;\n  *pzName = zKWText + aKWOffset[i];\n  *pnName = aKWLen[i];\n  return SQLITE_OK;\n}\nSQLITE_API int sqlite3_keyword_count(void){ return SQLITE_N_KEYWORD; }\nSQLITE_API int sqlite3_keyword_check(const char *zName, int nName){\n  return TK_ID!=sqlite3KeywordCode((const u8*)zName, nName);\n}\n\n/************** End of keywordhash.h *****************************************/\n/************** Continuing where we left off in tokenize.c *******************/\n\n\n/*\n** If X is a character that can be used in an identifier then\n** IdChar(X) will be true.  Otherwise it is false.\n**\n** For ASCII, any character with the high-order bit set is\n** allowed in an identifier.  For 7-bit characters, \n** sqlite3IsIdChar[X] must be 1.\n**\n** For EBCDIC, the rules are more complex but have the same\n** end result.\n**\n** Ticket #1066.  the SQL standard does not allow '$' in the\n** middle of identifiers.  But many SQL implementations do. \n** SQLite will allow '$' in identifiers for compatibility.\n** But the feature is undocumented.\n*/\n#ifdef SQLITE_ASCII\n#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)\n#endif\n#ifdef SQLITE_EBCDIC\nSQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {\n/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */\n    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */\n    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */\n    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */\n    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */\n    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */\n    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */\n    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */\n    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */\n    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */\n    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */\n};\n#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))\n#endif\n\n/* Make the IdChar function accessible from ctime.c and alter.c */\nSQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }\n\n#ifndef SQLITE_OMIT_WINDOWFUNC\n/*\n** Return the id of the next token in string (*pz). Before returning, set\n** (*pz) to point to the byte following the parsed token.\n*/\nstatic int getToken(const unsigned char **pz){\n  const unsigned char *z = *pz;\n  int t;                          /* Token type to return */\n  do {\n    z += sqlite3GetToken(z, &t);\n  }while( t==TK_SPACE );\n  if( t==TK_ID \n   || t==TK_STRING \n   || t==TK_JOIN_KW \n   || t==TK_WINDOW \n   || t==TK_OVER \n   || sqlite3ParserFallback(t)==TK_ID \n  ){\n    t = TK_ID;\n  }\n  *pz = z;\n  return t;\n}\n\n/*\n** The following three functions are called immediately after the tokenizer\n** reads the keywords WINDOW, OVER and FILTER, respectively, to determine\n** whether the token should be treated as a keyword or an SQL identifier.\n** This cannot be handled by the usual lemon %fallback method, due to\n** the ambiguity in some constructions. e.g.\n**\n**   SELECT sum(x) OVER ...\n**\n** In the above, \"OVER\" might be a keyword, or it might be an alias for the \n** sum(x) expression. If a \"%fallback ID OVER\" directive were added to \n** grammar, then SQLite would always treat \"OVER\" as an alias, making it\n** impossible to call a window-function without a FILTER clause.\n**\n** WINDOW is treated as a keyword if:\n**\n**   * the following token is an identifier, or a keyword that can fallback\n**     to being an identifier, and\n**   * the token after than one is TK_AS.\n**\n** OVER is a keyword if:\n**\n**   * the previous token was TK_RP, and\n**   * the next token is either TK_LP or an identifier.\n**\n** FILTER is a keyword if:\n**\n**   * the previous token was TK_RP, and\n**   * the next token is TK_LP.\n*/\nstatic int analyzeWindowKeyword(const unsigned char *z){\n  int t;\n  t = getToken(&z);\n  if( t!=TK_ID ) return TK_ID;\n  t = getToken(&z);\n  if( t!=TK_AS ) return TK_ID;\n  return TK_WINDOW;\n}\nstatic int analyzeOverKeyword(const unsigned char *z, int lastToken){\n  if( lastToken==TK_RP ){\n    int t = getToken(&z);\n    if( t==TK_LP || t==TK_ID ) return TK_OVER;\n  }\n  return TK_ID;\n}\nstatic int analyzeFilterKeyword(const unsigned char *z, int lastToken){\n  if( lastToken==TK_RP && getToken(&z)==TK_LP ){\n    return TK_FILTER;\n  }\n  return TK_ID;\n}\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n\n/*\n** Return the length (in bytes) of the token that begins at z[0]. \n** Store the token type in *tokenType before returning.\n*/\nSQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){\n  int i, c;\n  switch( aiClass[*z] ){  /* Switch on the character-class of the first byte\n                          ** of the token. See the comment on the CC_ defines\n                          ** above. */\n    case CC_SPACE: {\n      testcase( z[0]==' ' );\n      testcase( z[0]=='\\t' );\n      testcase( z[0]=='\\n' );\n      testcase( z[0]=='\\f' );\n      testcase( z[0]=='\\r' );\n      for(i=1; sqlite3Isspace(z[i]); i++){}\n      *tokenType = TK_SPACE;\n      return i;\n    }\n    case CC_MINUS: {\n      if( z[1]=='-' ){\n        for(i=2; (c=z[i])!=0 && c!='\\n'; i++){}\n        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */\n        return i;\n      }\n      *tokenType = TK_MINUS;\n      return 1;\n    }\n    case CC_LP: {\n      *tokenType = TK_LP;\n      return 1;\n    }\n    case CC_RP: {\n      *tokenType = TK_RP;\n      return 1;\n    }\n    case CC_SEMI: {\n      *tokenType = TK_SEMI;\n      return 1;\n    }\n    case CC_PLUS: {\n      *tokenType = TK_PLUS;\n      return 1;\n    }\n    case CC_STAR: {\n      *tokenType = TK_STAR;\n      return 1;\n    }\n    case CC_SLASH: {\n      if( z[1]!='*' || z[2]==0 ){\n        *tokenType = TK_SLASH;\n        return 1;\n      }\n      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}\n      if( c ) i++;\n      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */\n      return i;\n    }\n    case CC_PERCENT: {\n      *tokenType = TK_REM;\n      return 1;\n    }\n    case CC_EQ: {\n      *tokenType = TK_EQ;\n      return 1 + (z[1]=='=');\n    }\n    case CC_LT: {\n      if( (c=z[1])=='=' ){\n        *tokenType = TK_LE;\n        return 2;\n      }else if( c=='>' ){\n        *tokenType = TK_NE;\n        return 2;\n      }else if( c=='<' ){\n        *tokenType = TK_LSHIFT;\n        return 2;\n      }else{\n        *tokenType = TK_LT;\n        return 1;\n      }\n    }\n    case CC_GT: {\n      if( (c=z[1])=='=' ){\n        *tokenType = TK_GE;\n        return 2;\n      }else if( c=='>' ){\n        *tokenType = TK_RSHIFT;\n        return 2;\n      }else{\n        *tokenType = TK_GT;\n        return 1;\n      }\n    }\n    case CC_BANG: {\n      if( z[1]!='=' ){\n        *tokenType = TK_ILLEGAL;\n        return 1;\n      }else{\n        *tokenType = TK_NE;\n        return 2;\n      }\n    }\n    case CC_PIPE: {\n      if( z[1]!='|' ){\n        *tokenType = TK_BITOR;\n        return 1;\n      }else{\n        *tokenType = TK_CONCAT;\n        return 2;\n      }\n    }\n    case CC_COMMA: {\n      *tokenType = TK_COMMA;\n      return 1;\n    }\n    case CC_AND: {\n      *tokenType = TK_BITAND;\n      return 1;\n    }\n    case CC_TILDA: {\n      *tokenType = TK_BITNOT;\n      return 1;\n    }\n    case CC_QUOTE: {\n      int delim = z[0];\n      testcase( delim=='`' );\n      testcase( delim=='\\'' );\n      testcase( delim=='\"' );\n      for(i=1; (c=z[i])!=0; i++){\n        if( c==delim ){\n          if( z[i+1]==delim ){\n            i++;\n          }else{\n            break;\n          }\n        }\n      }\n      if( c=='\\'' ){\n        *tokenType = TK_STRING;\n        return i+1;\n      }else if( c!=0 ){\n        *tokenType = TK_ID;\n        return i+1;\n      }else{\n        *tokenType = TK_ILLEGAL;\n        return i;\n      }\n    }\n    case CC_DOT: {\n#ifndef SQLITE_OMIT_FLOATING_POINT\n      if( !sqlite3Isdigit(z[1]) )\n#endif\n      {\n        *tokenType = TK_DOT;\n        return 1;\n      }\n      /* If the next character is a digit, this is a floating point\n      ** number that begins with \".\".  Fall thru into the next case */\n    }\n    case CC_DIGIT: {\n      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );\n      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );\n      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );\n      testcase( z[0]=='9' );\n      *tokenType = TK_INTEGER;\n#ifndef SQLITE_OMIT_HEX_INTEGER\n      if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){\n        for(i=3; sqlite3Isxdigit(z[i]); i++){}\n        return i;\n      }\n#endif\n      for(i=0; sqlite3Isdigit(z[i]); i++){}\n#ifndef SQLITE_OMIT_FLOATING_POINT\n      if( z[i]=='.' ){\n        i++;\n        while( sqlite3Isdigit(z[i]) ){ i++; }\n        *tokenType = TK_FLOAT;\n      }\n      if( (z[i]=='e' || z[i]=='E') &&\n           ( sqlite3Isdigit(z[i+1]) \n            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))\n           )\n      ){\n        i += 2;\n        while( sqlite3Isdigit(z[i]) ){ i++; }\n        *tokenType = TK_FLOAT;\n      }\n#endif\n      while( IdChar(z[i]) ){\n        *tokenType = TK_ILLEGAL;\n        i++;\n      }\n      return i;\n    }\n    case CC_QUOTE2: {\n      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}\n      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;\n      return i;\n    }\n    case CC_VARNUM: {\n      *tokenType = TK_VARIABLE;\n      for(i=1; sqlite3Isdigit(z[i]); i++){}\n      return i;\n    }\n    case CC_DOLLAR:\n    case CC_VARALPHA: {\n      int n = 0;\n      testcase( z[0]=='$' );  testcase( z[0]=='@' );\n      testcase( z[0]==':' );  testcase( z[0]=='#' );\n      *tokenType = TK_VARIABLE;\n      for(i=1; (c=z[i])!=0; i++){\n        if( IdChar(c) ){\n          n++;\n#ifndef SQLITE_OMIT_TCL_VARIABLE\n        }else if( c=='(' && n>0 ){\n          do{\n            i++;\n          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );\n          if( c==')' ){\n            i++;\n          }else{\n            *tokenType = TK_ILLEGAL;\n          }\n          break;\n        }else if( c==':' && z[i+1]==':' ){\n          i++;\n#endif\n        }else{\n          break;\n        }\n      }\n      if( n==0 ) *tokenType = TK_ILLEGAL;\n      return i;\n    }\n    case CC_KYWD: {\n      for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}\n      if( IdChar(z[i]) ){\n        /* This token started out using characters that can appear in keywords,\n        ** but z[i] is a character not allowed within keywords, so this must\n        ** be an identifier instead */\n        i++;\n        break;\n      }\n      *tokenType = TK_ID;\n      return keywordCode((char*)z, i, tokenType);\n    }\n    case CC_X: {\n#ifndef SQLITE_OMIT_BLOB_LITERAL\n      testcase( z[0]=='x' ); testcase( z[0]=='X' );\n      if( z[1]=='\\'' ){\n        *tokenType = TK_BLOB;\n        for(i=2; sqlite3Isxdigit(z[i]); i++){}\n        if( z[i]!='\\'' || i%2 ){\n          *tokenType = TK_ILLEGAL;\n          while( z[i] && z[i]!='\\'' ){ i++; }\n        }\n        if( z[i] ) i++;\n        return i;\n      }\n#endif\n      /* If it is not a BLOB literal, then it must be an ID, since no\n      ** SQL keywords start with the letter 'x'.  Fall through */\n    }\n    case CC_ID: {\n      i = 1;\n      break;\n    }\n    case CC_NUL: {\n      *tokenType = TK_ILLEGAL;\n      return 0;\n    }\n    default: {\n      *tokenType = TK_ILLEGAL;\n      return 1;\n    }\n  }\n  while( IdChar(z[i]) ){ i++; }\n  *tokenType = TK_ID;\n  return i;\n}\n\n/*\n** Run the parser on the given SQL string.  The parser structure is\n** passed in.  An SQLITE_ status code is returned.  If an error occurs\n** then an and attempt is made to write an error message into \n** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that\n** error message.\n*/\nSQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){\n  int nErr = 0;                   /* Number of errors encountered */\n  void *pEngine;                  /* The LEMON-generated LALR(1) parser */\n  int n = 0;                      /* Length of the next token token */\n  int tokenType;                  /* type of the next token */\n  int lastTokenParsed = -1;       /* type of the previous token */\n  sqlite3 *db = pParse->db;       /* The database connection */\n  int mxSqlLen;                   /* Max length of an SQL string */\n#ifdef sqlite3Parser_ENGINEALWAYSONSTACK\n  yyParser sEngine;    /* Space to hold the Lemon-generated Parser object */\n#endif\n  VVA_ONLY( u8 startedWithOom = db->mallocFailed );\n\n  assert( zSql!=0 );\n  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];\n  if( db->nVdbeActive==0 ){\n    AtomicStore(&db->u1.isInterrupted, 0);\n  }\n  pParse->rc = SQLITE_OK;\n  pParse->zTail = zSql;\n  assert( pzErrMsg!=0 );\n#ifdef SQLITE_DEBUG\n  if( db->flags & SQLITE_ParserTrace ){\n    printf(\"parser: [[[%s]]]\\n\", zSql);\n    sqlite3ParserTrace(stdout, \"parser: \");\n  }else{\n    sqlite3ParserTrace(0, 0);\n  }\n#endif\n#ifdef sqlite3Parser_ENGINEALWAYSONSTACK\n  pEngine = &sEngine;\n  sqlite3ParserInit(pEngine, pParse);\n#else\n  pEngine = sqlite3ParserAlloc(sqlite3Malloc, pParse);\n  if( pEngine==0 ){\n    sqlite3OomFault(db);\n    return SQLITE_NOMEM_BKPT;\n  }\n#endif\n  assert( pParse->pNewTable==0 );\n  assert( pParse->pNewTrigger==0 );\n  assert( pParse->nVar==0 );\n  assert( pParse->pVList==0 );\n  pParse->pParentParse = db->pParse;\n  db->pParse = pParse;\n  while( 1 ){\n    n = sqlite3GetToken((u8*)zSql, &tokenType);\n    mxSqlLen -= n;\n    if( mxSqlLen<0 ){\n      pParse->rc = SQLITE_TOOBIG;\n      break;\n    }\n#ifndef SQLITE_OMIT_WINDOWFUNC\n    if( tokenType>=TK_WINDOW ){\n      assert( tokenType==TK_SPACE || tokenType==TK_OVER || tokenType==TK_FILTER\n           || tokenType==TK_ILLEGAL || tokenType==TK_WINDOW \n      );\n#else\n    if( tokenType>=TK_SPACE ){\n      assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n      if( AtomicLoad(&db->u1.isInterrupted) ){\n        pParse->rc = SQLITE_INTERRUPT;\n        break;\n      }\n      if( tokenType==TK_SPACE ){\n        zSql += n;\n        continue;\n      }\n      if( zSql[0]==0 ){\n        /* Upon reaching the end of input, call the parser two more times\n        ** with tokens TK_SEMI and 0, in that order. */\n        if( lastTokenParsed==TK_SEMI ){\n          tokenType = 0;\n        }else if( lastTokenParsed==0 ){\n          break;\n        }else{\n          tokenType = TK_SEMI;\n        }\n        n = 0;\n#ifndef SQLITE_OMIT_WINDOWFUNC\n      }else if( tokenType==TK_WINDOW ){\n        assert( n==6 );\n        tokenType = analyzeWindowKeyword((const u8*)&zSql[6]);\n      }else if( tokenType==TK_OVER ){\n        assert( n==4 );\n        tokenType = analyzeOverKeyword((const u8*)&zSql[4], lastTokenParsed);\n      }else if( tokenType==TK_FILTER ){\n        assert( n==6 );\n        tokenType = analyzeFilterKeyword((const u8*)&zSql[6], lastTokenParsed);\n#endif /* SQLITE_OMIT_WINDOWFUNC */\n      }else{\n        sqlite3ErrorMsg(pParse, \"unrecognized token: \\\"%.*s\\\"\", n, zSql);\n        break;\n      }\n    }\n    pParse->sLastToken.z = zSql;\n    pParse->sLastToken.n = n;\n    sqlite3Parser(pEngine, tokenType, pParse->sLastToken);\n    lastTokenParsed = tokenType;\n    zSql += n;\n    assert( db->mallocFailed==0 || pParse->rc!=SQLITE_OK || startedWithOom );\n    if( pParse->rc!=SQLITE_OK ) break;\n  }\n  assert( nErr==0 );\n#ifdef YYTRACKMAXSTACKDEPTH\n  sqlite3_mutex_enter(sqlite3MallocMutex());\n  sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,\n      sqlite3ParserStackPeak(pEngine)\n  );\n  sqlite3_mutex_leave(sqlite3MallocMutex());\n#endif /* YYDEBUG */\n#ifdef sqlite3Parser_ENGINEALWAYSONSTACK\n  sqlite3ParserFinalize(pEngine);\n#else\n  sqlite3ParserFree(pEngine, sqlite3_free);\n#endif\n  if( db->mallocFailed ){\n    pParse->rc = SQLITE_NOMEM_BKPT;\n  }\n  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){\n    pParse->zErrMsg = sqlite3MPrintf(db, \"%s\", sqlite3ErrStr(pParse->rc));\n  }\n  assert( pzErrMsg!=0 );\n  if( pParse->zErrMsg ){\n    *pzErrMsg = pParse->zErrMsg;\n    sqlite3_log(pParse->rc, \"%s in \\\"%s\\\"\", \n                *pzErrMsg, pParse->zTail);\n    pParse->zErrMsg = 0;\n    nErr++;\n  }\n  pParse->zTail = zSql;\n  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){\n    sqlite3VdbeDelete(pParse->pVdbe);\n    pParse->pVdbe = 0;\n  }\n#ifndef SQLITE_OMIT_SHARED_CACHE\n  if( pParse->nested==0 ){\n    sqlite3DbFree(db, pParse->aTableLock);\n    pParse->aTableLock = 0;\n    pParse->nTableLock = 0;\n  }\n#endif\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  sqlite3_free(pParse->apVtabLock);\n#endif\n\n  if( !IN_SPECIAL_PARSE ){\n    /* If the pParse->declareVtab flag is set, do not delete any table \n    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)\n    ** will take responsibility for freeing the Table structure.\n    */\n    sqlite3DeleteTable(db, pParse->pNewTable);\n  }\n  if( !IN_RENAME_OBJECT ){\n    sqlite3DeleteTrigger(db, pParse->pNewTrigger);\n  }\n\n  if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);\n  sqlite3DbFree(db, pParse->pVList);\n  while( pParse->pAinc ){\n    AutoincInfo *p = pParse->pAinc;\n    pParse->pAinc = p->pNext;\n    sqlite3DbFreeNN(db, p);\n  }\n  while( pParse->pZombieTab ){\n    Table *p = pParse->pZombieTab;\n    pParse->pZombieTab = p->pNextZombie;\n    sqlite3DeleteTable(db, p);\n  }\n  db->pParse = pParse->pParentParse;\n  pParse->pParentParse = 0;\n  assert( nErr==0 || pParse->rc!=SQLITE_OK );\n  return nErr;\n}\n\n\n#ifdef SQLITE_ENABLE_NORMALIZE\n/*\n** Insert a single space character into pStr if the current string\n** ends with an identifier\n*/\nstatic void addSpaceSeparator(sqlite3_str *pStr){\n  if( pStr->nChar && sqlite3IsIdChar(pStr->zText[pStr->nChar-1]) ){\n    sqlite3_str_append(pStr, \" \", 1);\n  }\n}\n\n/*\n** Compute a normalization of the SQL given by zSql[0..nSql-1].  Return\n** the normalization in space obtained from sqlite3DbMalloc().  Or return\n** NULL if anything goes wrong or if zSql is NULL.\n*/\nSQLITE_PRIVATE char *sqlite3Normalize(\n  Vdbe *pVdbe,       /* VM being reprepared */\n  const char *zSql   /* The original SQL string */\n){\n  sqlite3 *db;       /* The database connection */\n  int i;             /* Next unread byte of zSql[] */\n  int n;             /* length of current token */\n  int tokenType;     /* type of current token */\n  int prevType = 0;  /* Previous non-whitespace token */\n  int nParen;        /* Number of nested levels of parentheses */\n  int iStartIN;      /* Start of RHS of IN operator in z[] */\n  int nParenAtIN;    /* Value of nParent at start of RHS of IN operator */\n  u32 j;             /* Bytes of normalized SQL generated so far */\n  sqlite3_str *pStr; /* The normalized SQL string under construction */\n\n  db = sqlite3VdbeDb(pVdbe);\n  tokenType = -1;\n  nParen = iStartIN = nParenAtIN = 0;\n  pStr = sqlite3_str_new(db);\n  assert( pStr!=0 );  /* sqlite3_str_new() never returns NULL */\n  for(i=0; zSql[i] && pStr->accError==0; i+=n){\n    if( tokenType!=TK_SPACE ){\n      prevType = tokenType;\n    }\n    n = sqlite3GetToken((unsigned char*)zSql+i, &tokenType);\n    if( NEVER(n<=0) ) break;\n    switch( tokenType ){\n      case TK_SPACE: {\n        break;\n      }\n      case TK_NULL: {\n        if( prevType==TK_IS || prevType==TK_NOT ){\n          sqlite3_str_append(pStr, \" NULL\", 5);\n          break;\n        }\n        /* Fall through */\n      }\n      case TK_STRING:\n      case TK_INTEGER:\n      case TK_FLOAT:\n      case TK_VARIABLE:\n      case TK_BLOB: {\n        sqlite3_str_append(pStr, \"?\", 1);\n        break;\n      }\n      case TK_LP: {\n        nParen++;\n        if( prevType==TK_IN ){\n          iStartIN = pStr->nChar;\n          nParenAtIN = nParen;\n        }\n        sqlite3_str_append(pStr, \"(\", 1);\n        break;\n      }\n      case TK_RP: {\n        if( iStartIN>0 && nParen==nParenAtIN ){\n          assert( pStr->nChar>=(u32)iStartIN );\n          pStr->nChar = iStartIN+1;\n          sqlite3_str_append(pStr, \"?,?,?\", 5);\n          iStartIN = 0;\n        }\n        nParen--;\n        sqlite3_str_append(pStr, \")\", 1);\n        break;\n      }\n      case TK_ID: {\n        iStartIN = 0;\n        j = pStr->nChar;\n        if( sqlite3Isquote(zSql[i]) ){\n          char *zId = sqlite3DbStrNDup(db, zSql+i, n);\n          int nId;\n          int eType = 0;\n          if( zId==0 ) break;\n          sqlite3Dequote(zId);\n          if( zSql[i]=='\"' && sqlite3VdbeUsesDoubleQuotedString(pVdbe, zId) ){\n            sqlite3_str_append(pStr, \"?\", 1);\n            sqlite3DbFree(db, zId);\n            break;\n          }\n          nId = sqlite3Strlen30(zId);\n          if( sqlite3GetToken((u8*)zId, &eType)==nId && eType==TK_ID ){\n            addSpaceSeparator(pStr);\n            sqlite3_str_append(pStr, zId, nId);\n          }else{\n            sqlite3_str_appendf(pStr, \"\\\"%w\\\"\", zId);\n          }\n          sqlite3DbFree(db, zId);\n        }else{\n          addSpaceSeparator(pStr);\n          sqlite3_str_append(pStr, zSql+i, n);\n        }\n        while( j<pStr->nChar ){\n          pStr->zText[j] = sqlite3Tolower(pStr->zText[j]);\n          j++;\n        }\n        break;\n      }\n      case TK_SELECT: {\n        iStartIN = 0;\n        /* fall through */\n      }\n      default: {\n        if( sqlite3IsIdChar(zSql[i]) ) addSpaceSeparator(pStr);\n        j = pStr->nChar;\n        sqlite3_str_append(pStr, zSql+i, n);\n        while( j<pStr->nChar ){\n          pStr->zText[j] = sqlite3Toupper(pStr->zText[j]);\n          j++;\n        }\n        break;\n      }\n    }\n  }\n  if( tokenType!=TK_SEMI ) sqlite3_str_append(pStr, \";\", 1);\n  return sqlite3_str_finish(pStr);\n}\n#endif /* SQLITE_ENABLE_NORMALIZE */\n\n/************** End of tokenize.c ********************************************/\n/************** Begin file complete.c ****************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** An tokenizer for SQL\n**\n** This file contains C code that implements the sqlite3_complete() API.\n** This code used to be part of the tokenizer.c source file.  But by\n** separating it out, the code will be automatically omitted from\n** static links that do not use it.\n*/\n/* #include \"sqliteInt.h\" */\n#ifndef SQLITE_OMIT_COMPLETE\n\n/*\n** This is defined in tokenize.c.  We just have to import the definition.\n*/\n#ifndef SQLITE_AMALGAMATION\n#ifdef SQLITE_ASCII\n#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)\n#endif\n#ifdef SQLITE_EBCDIC\nSQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];\n#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))\n#endif\n#endif /* SQLITE_AMALGAMATION */\n\n\n/*\n** Token types used by the sqlite3_complete() routine.  See the header\n** comments on that procedure for additional information.\n*/\n#define tkSEMI    0\n#define tkWS      1\n#define tkOTHER   2\n#ifndef SQLITE_OMIT_TRIGGER\n#define tkEXPLAIN 3\n#define tkCREATE  4\n#define tkTEMP    5\n#define tkTRIGGER 6\n#define tkEND     7\n#endif\n\n/*\n** Return TRUE if the given SQL string ends in a semicolon.\n**\n** Special handling is require for CREATE TRIGGER statements.\n** Whenever the CREATE TRIGGER keywords are seen, the statement\n** must end with \";END;\".\n**\n** This implementation uses a state machine with 8 states:\n**\n**   (0) INVALID   We have not yet seen a non-whitespace character.\n**\n**   (1) START     At the beginning or end of an SQL statement.  This routine\n**                 returns 1 if it ends in the START state and 0 if it ends\n**                 in any other state.\n**\n**   (2) NORMAL    We are in the middle of statement which ends with a single\n**                 semicolon.\n**\n**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of \n**                 a statement.\n**\n**   (4) CREATE    The keyword CREATE has been seen at the beginning of a\n**                 statement, possibly preceded by EXPLAIN and/or followed by\n**                 TEMP or TEMPORARY\n**\n**   (5) TRIGGER   We are in the middle of a trigger definition that must be\n**                 ended by a semicolon, the keyword END, and another semicolon.\n**\n**   (6) SEMI      We've seen the first semicolon in the \";END;\" that occurs at\n**                 the end of a trigger definition.\n**\n**   (7) END       We've seen the \";END\" of the \";END;\" that occurs at the end\n**                 of a trigger definition.\n**\n** Transitions between states above are determined by tokens extracted\n** from the input.  The following tokens are significant:\n**\n**   (0) tkSEMI      A semicolon.\n**   (1) tkWS        Whitespace.\n**   (2) tkOTHER     Any other SQL token.\n**   (3) tkEXPLAIN   The \"explain\" keyword.\n**   (4) tkCREATE    The \"create\" keyword.\n**   (5) tkTEMP      The \"temp\" or \"temporary\" keyword.\n**   (6) tkTRIGGER   The \"trigger\" keyword.\n**   (7) tkEND       The \"end\" keyword.\n**\n** Whitespace never causes a state transition and is always ignored.\n** This means that a SQL string of all whitespace is invalid.\n**\n** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed\n** to recognize the end of a trigger can be omitted.  All we have to do\n** is look for a semicolon that is not part of an string or comment.\n*/\nSQLITE_API int sqlite3_complete(const char *zSql){\n  u8 state = 0;   /* Current state, using numbers defined in header comment */\n  u8 token;       /* Value of the next token */\n\n#ifndef SQLITE_OMIT_TRIGGER\n  /* A complex statement machine used to detect the end of a CREATE TRIGGER\n  ** statement.  This is the normal case.\n  */\n  static const u8 trans[8][8] = {\n                     /* Token:                                                */\n     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */\n     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },\n     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },\n     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },\n     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },\n     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },\n     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },\n     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },\n     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },\n  };\n#else\n  /* If triggers are not supported by this compile then the statement machine\n  ** used to detect the end of a statement is much simpler\n  */\n  static const u8 trans[3][3] = {\n                     /* Token:           */\n     /* State:       **  SEMI  WS  OTHER */\n     /* 0 INVALID: */ {    1,  0,     2, },\n     /* 1   START: */ {    1,  1,     2, },\n     /* 2  NORMAL: */ {    1,  2,     2, },\n  };\n#endif /* SQLITE_OMIT_TRIGGER */\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( zSql==0 ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n\n  while( *zSql ){\n    switch( *zSql ){\n      case ';': {  /* A semicolon */\n        token = tkSEMI;\n        break;\n      }\n      case ' ':\n      case '\\r':\n      case '\\t':\n      case '\\n':\n      case '\\f': {  /* White space is ignored */\n        token = tkWS;\n        break;\n      }\n      case '/': {   /* C-style comments */\n        if( zSql[1]!='*' ){\n          token = tkOTHER;\n          break;\n        }\n        zSql += 2;\n        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }\n        if( zSql[0]==0 ) return 0;\n        zSql++;\n        token = tkWS;\n        break;\n      }\n      case '-': {   /* SQL-style comments from \"--\" to end of line */\n        if( zSql[1]!='-' ){\n          token = tkOTHER;\n          break;\n        }\n        while( *zSql && *zSql!='\\n' ){ zSql++; }\n        if( *zSql==0 ) return state==1;\n        token = tkWS;\n        break;\n      }\n      case '[': {   /* Microsoft-style identifiers in [...] */\n        zSql++;\n        while( *zSql && *zSql!=']' ){ zSql++; }\n        if( *zSql==0 ) return 0;\n        token = tkOTHER;\n        break;\n      }\n      case '`':     /* Grave-accent quoted symbols used by MySQL */\n      case '\"':     /* single- and double-quoted strings */\n      case '\\'': {\n        int c = *zSql;\n        zSql++;\n        while( *zSql && *zSql!=c ){ zSql++; }\n        if( *zSql==0 ) return 0;\n        token = tkOTHER;\n        break;\n      }\n      default: {\n#ifdef SQLITE_EBCDIC\n        unsigned char c;\n#endif\n        if( IdChar((u8)*zSql) ){\n          /* Keywords and unquoted identifiers */\n          int nId;\n          for(nId=1; IdChar(zSql[nId]); nId++){}\n#ifdef SQLITE_OMIT_TRIGGER\n          token = tkOTHER;\n#else\n          switch( *zSql ){\n            case 'c': case 'C': {\n              if( nId==6 && sqlite3StrNICmp(zSql, \"create\", 6)==0 ){\n                token = tkCREATE;\n              }else{\n                token = tkOTHER;\n              }\n              break;\n            }\n            case 't': case 'T': {\n              if( nId==7 && sqlite3StrNICmp(zSql, \"trigger\", 7)==0 ){\n                token = tkTRIGGER;\n              }else if( nId==4 && sqlite3StrNICmp(zSql, \"temp\", 4)==0 ){\n                token = tkTEMP;\n              }else if( nId==9 && sqlite3StrNICmp(zSql, \"temporary\", 9)==0 ){\n                token = tkTEMP;\n              }else{\n                token = tkOTHER;\n              }\n              break;\n            }\n            case 'e':  case 'E': {\n              if( nId==3 && sqlite3StrNICmp(zSql, \"end\", 3)==0 ){\n                token = tkEND;\n              }else\n#ifndef SQLITE_OMIT_EXPLAIN\n              if( nId==7 && sqlite3StrNICmp(zSql, \"explain\", 7)==0 ){\n                token = tkEXPLAIN;\n              }else\n#endif\n              {\n                token = tkOTHER;\n              }\n              break;\n            }\n            default: {\n              token = tkOTHER;\n              break;\n            }\n          }\n#endif /* SQLITE_OMIT_TRIGGER */\n          zSql += nId-1;\n        }else{\n          /* Operators and special symbols */\n          token = tkOTHER;\n        }\n        break;\n      }\n    }\n    state = trans[state][token];\n    zSql++;\n  }\n  return state==1;\n}\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** This routine is the same as the sqlite3_complete() routine described\n** above, except that the parameter is required to be UTF-16 encoded, not\n** UTF-8.\n*/\nSQLITE_API int sqlite3_complete16(const void *zSql){\n  sqlite3_value *pVal;\n  char const *zSql8;\n  int rc;\n\n#ifndef SQLITE_OMIT_AUTOINIT\n  rc = sqlite3_initialize();\n  if( rc ) return rc;\n#endif\n  pVal = sqlite3ValueNew(0);\n  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);\n  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);\n  if( zSql8 ){\n    rc = sqlite3_complete(zSql8);\n  }else{\n    rc = SQLITE_NOMEM_BKPT;\n  }\n  sqlite3ValueFree(pVal);\n  return rc & 0xff;\n}\n#endif /* SQLITE_OMIT_UTF16 */\n#endif /* SQLITE_OMIT_COMPLETE */\n\n/************** End of complete.c ********************************************/\n/************** Begin file main.c ********************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** Main file for the SQLite library.  The routines in this file\n** implement the programmer interface to the library.  Routines in\n** other files are for internal use by SQLite and should not be\n** accessed by users of the library.\n*/\n/* #include \"sqliteInt.h\" */\n\n#ifdef SQLITE_ENABLE_FTS3\n/************** Include fts3.h in the middle of main.c ***********************/\n/************** Begin file fts3.h ********************************************/\n/*\n** 2006 Oct 10\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This header file is used by programs that want to link against the\n** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.\n*/\n/* #include \"sqlite3.h\" */\n\n#if 0\nextern \"C\" {\n#endif  /* __cplusplus */\n\nSQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);\n\n#if 0\n}  /* extern \"C\" */\n#endif  /* __cplusplus */\n\n/************** End of fts3.h ************************************************/\n/************** Continuing where we left off in main.c ***********************/\n#endif\n#ifdef SQLITE_ENABLE_RTREE\n/************** Include rtree.h in the middle of main.c **********************/\n/************** Begin file rtree.h *******************************************/\n/*\n** 2008 May 26\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This header file is used by programs that want to link against the\n** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.\n*/\n/* #include \"sqlite3.h\" */\n\n#ifdef SQLITE_OMIT_VIRTUALTABLE\n# undef SQLITE_ENABLE_RTREE\n#endif\n\n#if 0\nextern \"C\" {\n#endif  /* __cplusplus */\n\nSQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);\n\n#if 0\n}  /* extern \"C\" */\n#endif  /* __cplusplus */\n\n/************** End of rtree.h ***********************************************/\n/************** Continuing where we left off in main.c ***********************/\n#endif\n#if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)\n/************** Include sqliteicu.h in the middle of main.c ******************/\n/************** Begin file sqliteicu.h ***************************************/\n/*\n** 2008 May 26\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This header file is used by programs that want to link against the\n** ICU extension.  All it does is declare the sqlite3IcuInit() interface.\n*/\n/* #include \"sqlite3.h\" */\n\n#if 0\nextern \"C\" {\n#endif  /* __cplusplus */\n\nSQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);\n\n#if 0\n}  /* extern \"C\" */\n#endif  /* __cplusplus */\n\n\n/************** End of sqliteicu.h *******************************************/\n/************** Continuing where we left off in main.c ***********************/\n#endif\n\n/*\n** This is an extension initializer that is a no-op and always\n** succeeds, except that it fails if the fault-simulation is set\n** to 500.\n*/\nstatic int sqlite3TestExtInit(sqlite3 *db){\n  (void)db;\n  return sqlite3FaultSim(500);\n}\n\n\n/*\n** Forward declarations of external module initializer functions\n** for modules that need them.\n*/\n#ifdef SQLITE_ENABLE_FTS1\nSQLITE_PRIVATE int sqlite3Fts1Init(sqlite3*);\n#endif\n#ifdef SQLITE_ENABLE_FTS2\nSQLITE_PRIVATE int sqlite3Fts2Init(sqlite3*);\n#endif\n#ifdef SQLITE_ENABLE_FTS5\nSQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);\n#endif\n#ifdef SQLITE_ENABLE_JSON1\nSQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);\n#endif\n#ifdef SQLITE_ENABLE_STMTVTAB\nSQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);\n#endif\n\n/*\n** An array of pointers to extension initializer functions for\n** built-in extensions.\n*/\nstatic int (*const sqlite3BuiltinExtensions[])(sqlite3*) = {\n#ifdef SQLITE_ENABLE_FTS1\n  sqlite3Fts1Init,\n#endif\n#ifdef SQLITE_ENABLE_FTS2\n  sqlite3Fts2Init,\n#endif\n#ifdef SQLITE_ENABLE_FTS3\n  sqlite3Fts3Init,\n#endif\n#ifdef SQLITE_ENABLE_FTS5\n  sqlite3Fts5Init,\n#endif\n#if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)\n  sqlite3IcuInit,\n#endif\n#ifdef SQLITE_ENABLE_RTREE\n  sqlite3RtreeInit,\n#endif\n#ifdef SQLITE_ENABLE_DBPAGE_VTAB\n  sqlite3DbpageRegister,\n#endif\n#ifdef SQLITE_ENABLE_DBSTAT_VTAB\n  sqlite3DbstatRegister,\n#endif\n  sqlite3TestExtInit,\n#ifdef SQLITE_ENABLE_JSON1\n  sqlite3Json1Init,\n#endif\n#ifdef SQLITE_ENABLE_STMTVTAB\n  sqlite3StmtVtabInit,\n#endif\n#ifdef SQLITE_ENABLE_BYTECODE_VTAB\n  sqlite3VdbeBytecodeVtabInit,\n#endif\n};\n\n#ifndef SQLITE_AMALGAMATION\n/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant\n** contains the text of SQLITE_VERSION macro. \n*/\nSQLITE_API const char sqlite3_version[] = SQLITE_VERSION;\n#endif\n\n/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns\n** a pointer to the to the sqlite3_version[] string constant. \n*/\nSQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }\n\n/* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a\n** pointer to a string constant whose value is the same as the\n** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using\n** an edited copy of the amalgamation, then the last four characters of\n** the hash might be different from SQLITE_SOURCE_ID.\n*/\n/* SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } */\n\n/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function\n** returns an integer equal to SQLITE_VERSION_NUMBER.\n*/\nSQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }\n\n/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns\n** zero if and only if SQLite was compiled with mutexing code omitted due to\n** the SQLITE_THREADSAFE compile-time option being set to 0.\n*/\nSQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }\n\n/*\n** When compiling the test fixture or with debugging enabled (on Win32),\n** this variable being set to non-zero will cause OSTRACE macros to emit\n** extra diagnostic information.\n*/\n#ifdef SQLITE_HAVE_OS_TRACE\n# ifndef SQLITE_DEBUG_OS_TRACE\n#   define SQLITE_DEBUG_OS_TRACE 0\n# endif\n  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;\n#endif\n\n#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)\n/*\n** If the following function pointer is not NULL and if\n** SQLITE_ENABLE_IOTRACE is enabled, then messages describing\n** I/O active are written using this function.  These messages\n** are intended for debugging activity only.\n*/\nSQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;\n#endif\n\n/*\n** If the following global variable points to a string which is the\n** name of a directory, then that directory will be used to store\n** temporary files.\n**\n** See also the \"PRAGMA temp_store_directory\" SQL command.\n*/\nSQLITE_API char *sqlite3_temp_directory = 0;\n\n/*\n** If the following global variable points to a string which is the\n** name of a directory, then that directory will be used to store\n** all database files specified with a relative pathname.\n**\n** See also the \"PRAGMA data_store_directory\" SQL command.\n*/\nSQLITE_API char *sqlite3_data_directory = 0;\n\n/*\n** Initialize SQLite.  \n**\n** This routine must be called to initialize the memory allocation,\n** VFS, and mutex subsystems prior to doing any serious work with\n** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT\n** this routine will be called automatically by key routines such as\n** sqlite3_open().  \n**\n** This routine is a no-op except on its very first call for the process,\n** or for the first call after a call to sqlite3_shutdown.\n**\n** The first thread to call this routine runs the initialization to\n** completion.  If subsequent threads call this routine before the first\n** thread has finished the initialization process, then the subsequent\n** threads must block until the first thread finishes with the initialization.\n**\n** The first thread might call this routine recursively.  Recursive\n** calls to this routine should not block, of course.  Otherwise the\n** initialization process would never complete.\n**\n** Let X be the first thread to enter this routine.  Let Y be some other\n** thread.  Then while the initial invocation of this routine by X is\n** incomplete, it is required that:\n**\n**    *  Calls to this routine from Y must block until the outer-most\n**       call by X completes.\n**\n**    *  Recursive calls to this routine from thread X return immediately\n**       without blocking.\n*/\nSQLITE_API int sqlite3_initialize(void){\n  MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */\n  int rc;                                      /* Result code */\n#ifdef SQLITE_EXTRA_INIT\n  int bRunExtraInit = 0;                       /* Extra initialization needed */\n#endif\n\n#ifdef SQLITE_OMIT_WSD\n  rc = sqlite3_wsd_init(4096, 24);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n#endif\n\n  /* If the following assert() fails on some obscure processor/compiler\n  ** combination, the work-around is to set the correct pointer\n  ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */\n  assert( SQLITE_PTRSIZE==sizeof(char*) );\n\n  /* If SQLite is already completely initialized, then this call\n  ** to sqlite3_initialize() should be a no-op.  But the initialization\n  ** must be complete.  So isInit must not be set until the very end\n  ** of this routine.\n  */\n  if( sqlite3GlobalConfig.isInit ){\n    sqlite3MemoryBarrier();\n    return SQLITE_OK;\n  }\n\n  /* Make sure the mutex subsystem is initialized.  If unable to \n  ** initialize the mutex subsystem, return early with the error.\n  ** If the system is so sick that we are unable to allocate a mutex,\n  ** there is not much SQLite is going to be able to do.\n  **\n  ** The mutex subsystem must take care of serializing its own\n  ** initialization.\n  */\n  rc = sqlite3MutexInit();\n  if( rc ) return rc;\n\n  /* Initialize the malloc() system and the recursive pInitMutex mutex.\n  ** This operation is protected by the STATIC_MASTER mutex.  Note that\n  ** MutexAlloc() is called for a static mutex prior to initializing the\n  ** malloc subsystem - this implies that the allocation of a static\n  ** mutex must not require support from the malloc subsystem.\n  */\n  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )\n  sqlite3_mutex_enter(pMaster);\n  sqlite3GlobalConfig.isMutexInit = 1;\n  if( !sqlite3GlobalConfig.isMallocInit ){\n    rc = sqlite3MallocInit();\n  }\n  if( rc==SQLITE_OK ){\n    sqlite3GlobalConfig.isMallocInit = 1;\n    if( !sqlite3GlobalConfig.pInitMutex ){\n      sqlite3GlobalConfig.pInitMutex =\n           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);\n      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){\n        rc = SQLITE_NOMEM_BKPT;\n      }\n    }\n  }\n  if( rc==SQLITE_OK ){\n    sqlite3GlobalConfig.nRefInitMutex++;\n  }\n  sqlite3_mutex_leave(pMaster);\n\n  /* If rc is not SQLITE_OK at this point, then either the malloc\n  ** subsystem could not be initialized or the system failed to allocate\n  ** the pInitMutex mutex. Return an error in either case.  */\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  /* Do the rest of the initialization under the recursive mutex so\n  ** that we will be able to handle recursive calls into\n  ** sqlite3_initialize().  The recursive calls normally come through\n  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other\n  ** recursive calls might also be possible.\n  **\n  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls\n  ** to the xInit method, so the xInit method need not be threadsafe.\n  **\n  ** The following mutex is what serializes access to the appdef pcache xInit\n  ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the\n  ** call to sqlite3PcacheInitialize().\n  */\n  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);\n  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){\n    sqlite3GlobalConfig.inProgress = 1;\n#ifdef SQLITE_ENABLE_SQLLOG\n    {\n      extern void sqlite3_init_sqllog(void);\n      sqlite3_init_sqllog();\n    }\n#endif\n    memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));\n    sqlite3RegisterBuiltinFunctions();\n    if( sqlite3GlobalConfig.isPCacheInit==0 ){\n      rc = sqlite3PcacheInitialize();\n    }\n    if( rc==SQLITE_OK ){\n      sqlite3GlobalConfig.isPCacheInit = 1;\n      rc = sqlite3OsInit();\n    }\n#ifdef SQLITE_ENABLE_DESERIALIZE\n    if( rc==SQLITE_OK ){\n      rc = sqlite3MemdbInit();\n    }\n#endif\n    if( rc==SQLITE_OK ){\n      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, \n          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);\n      sqlite3MemoryBarrier();\n      sqlite3GlobalConfig.isInit = 1;\n#ifdef SQLITE_EXTRA_INIT\n      bRunExtraInit = 1;\n#endif\n    }\n    sqlite3GlobalConfig.inProgress = 0;\n  }\n  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);\n\n  /* Go back under the static mutex and clean up the recursive\n  ** mutex to prevent a resource leak.\n  */\n  sqlite3_mutex_enter(pMaster);\n  sqlite3GlobalConfig.nRefInitMutex--;\n  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){\n    assert( sqlite3GlobalConfig.nRefInitMutex==0 );\n    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);\n    sqlite3GlobalConfig.pInitMutex = 0;\n  }\n  sqlite3_mutex_leave(pMaster);\n\n  /* The following is just a sanity check to make sure SQLite has\n  ** been compiled correctly.  It is important to run this code, but\n  ** we don't want to run it too often and soak up CPU cycles for no\n  ** reason.  So we run it once during initialization.\n  */\n#ifndef NDEBUG\n#ifndef SQLITE_OMIT_FLOATING_POINT\n  /* This section of code's only \"output\" is via assert() statements. */\n  if( rc==SQLITE_OK ){\n    u64 x = (((u64)1)<<63)-1;\n    double y;\n    assert(sizeof(x)==8);\n    assert(sizeof(x)==sizeof(y));\n    memcpy(&y, &x, 8);\n    assert( sqlite3IsNaN(y) );\n  }\n#endif\n#endif\n\n  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT\n  ** compile-time option.\n  */\n#ifdef SQLITE_EXTRA_INIT\n  if( bRunExtraInit ){\n    int SQLITE_EXTRA_INIT(const char*);\n    rc = SQLITE_EXTRA_INIT(0);\n  }\n#endif\n\n  return rc;\n}\n\n/*\n** Undo the effects of sqlite3_initialize().  Must not be called while\n** there are outstanding database connections or memory allocations or\n** while any part of SQLite is otherwise in use in any thread.  This\n** routine is not threadsafe.  But it is safe to invoke this routine\n** on when SQLite is already shut down.  If SQLite is already shut down\n** when this routine is invoked, then this routine is a harmless no-op.\n*/\nSQLITE_API int sqlite3_shutdown(void){\n#ifdef SQLITE_OMIT_WSD\n  int rc = sqlite3_wsd_init(4096, 24);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n#endif\n\n  if( sqlite3GlobalConfig.isInit ){\n#ifdef SQLITE_EXTRA_SHUTDOWN\n    void SQLITE_EXTRA_SHUTDOWN(void);\n    SQLITE_EXTRA_SHUTDOWN();\n#endif\n    sqlite3_os_end();\n    sqlite3_reset_auto_extension();\n    sqlite3GlobalConfig.isInit = 0;\n  }\n  if( sqlite3GlobalConfig.isPCacheInit ){\n    sqlite3PcacheShutdown();\n    sqlite3GlobalConfig.isPCacheInit = 0;\n  }\n  if( sqlite3GlobalConfig.isMallocInit ){\n    sqlite3MallocEnd();\n    sqlite3GlobalConfig.isMallocInit = 0;\n\n#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES\n    /* The heap subsystem has now been shutdown and these values are supposed\n    ** to be NULL or point to memory that was obtained from sqlite3_malloc(),\n    ** which would rely on that heap subsystem; therefore, make sure these\n    ** values cannot refer to heap memory that was just invalidated when the\n    ** heap subsystem was shutdown.  This is only done if the current call to\n    ** this function resulted in the heap subsystem actually being shutdown.\n    */\n    sqlite3_data_directory = 0;\n    sqlite3_temp_directory = 0;\n#endif\n  }\n  if( sqlite3GlobalConfig.isMutexInit ){\n    sqlite3MutexEnd();\n    sqlite3GlobalConfig.isMutexInit = 0;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** This API allows applications to modify the global configuration of\n** the SQLite library at run-time.\n**\n** This routine should only be called when there are no outstanding\n** database connections or memory allocations.  This routine is not\n** threadsafe.  Failure to heed these warnings can lead to unpredictable\n** behavior.\n*/\nSQLITE_API int sqlite3_config(int op, ...){\n  va_list ap;\n  int rc = SQLITE_OK;\n\n  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while\n  ** the SQLite library is in use. */\n  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;\n\n  va_start(ap, op);\n  switch( op ){\n\n    /* Mutex configuration options are only available in a threadsafe\n    ** compile.\n    */\n#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */\n    case SQLITE_CONFIG_SINGLETHREAD: {\n      /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to\n      ** Single-thread. */\n      sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */\n      sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */\n      break;\n    }\n#endif\n#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */\n    case SQLITE_CONFIG_MULTITHREAD: {\n      /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to\n      ** Multi-thread. */\n      sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */\n      sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */\n      break;\n    }\n#endif\n#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */\n    case SQLITE_CONFIG_SERIALIZED: {\n      /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to\n      ** Serialized. */\n      sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */\n      sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */\n      break;\n    }\n#endif\n#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */\n    case SQLITE_CONFIG_MUTEX: {\n      /* Specify an alternative mutex implementation */\n      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);\n      break;\n    }\n#endif\n#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */\n    case SQLITE_CONFIG_GETMUTEX: {\n      /* Retrieve the current mutex implementation */\n      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;\n      break;\n    }\n#endif\n\n    case SQLITE_CONFIG_MALLOC: {\n      /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a\n      ** single argument which is a pointer to an instance of the\n      ** sqlite3_mem_methods structure. The argument specifies alternative\n      ** low-level memory allocation routines to be used in place of the memory\n      ** allocation routines built into SQLite. */\n      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);\n      break;\n    }\n    case SQLITE_CONFIG_GETMALLOC: {\n      /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a\n      ** single argument which is a pointer to an instance of the\n      ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is\n      ** filled with the currently defined memory allocation routines. */\n      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();\n      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;\n      break;\n    }\n    case SQLITE_CONFIG_MEMSTATUS: {\n      /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes\n      ** single argument of type int, interpreted as a boolean, which enables\n      ** or disables the collection of memory allocation statistics. */\n      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);\n      break;\n    }\n    case SQLITE_CONFIG_SMALL_MALLOC: {\n      sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);\n      break;\n    }\n    case SQLITE_CONFIG_PAGECACHE: {\n      /* EVIDENCE-OF: R-18761-36601 There are three arguments to\n      ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),\n      ** the size of each page cache line (sz), and the number of cache lines\n      ** (N). */\n      sqlite3GlobalConfig.pPage = va_arg(ap, void*);\n      sqlite3GlobalConfig.szPage = va_arg(ap, int);\n      sqlite3GlobalConfig.nPage = va_arg(ap, int);\n      break;\n    }\n    case SQLITE_CONFIG_PCACHE_HDRSZ: {\n      /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes\n      ** a single parameter which is a pointer to an integer and writes into\n      ** that integer the number of extra bytes per page required for each page\n      ** in SQLITE_CONFIG_PAGECACHE. */\n      *va_arg(ap, int*) = \n          sqlite3HeaderSizeBtree() +\n          sqlite3HeaderSizePcache() +\n          sqlite3HeaderSizePcache1();\n      break;\n    }\n\n    case SQLITE_CONFIG_PCACHE: {\n      /* no-op */\n      break;\n    }\n    case SQLITE_CONFIG_GETPCACHE: {\n      /* now an error */\n      rc = SQLITE_ERROR;\n      break;\n    }\n\n    case SQLITE_CONFIG_PCACHE2: {\n      /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a\n      ** single argument which is a pointer to an sqlite3_pcache_methods2\n      ** object. This object specifies the interface to a custom page cache\n      ** implementation. */\n      sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);\n      break;\n    }\n    case SQLITE_CONFIG_GETPCACHE2: {\n      /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a\n      ** single argument which is a pointer to an sqlite3_pcache_methods2\n      ** object. SQLite copies of the current page cache implementation into\n      ** that object. */\n      if( sqlite3GlobalConfig.pcache2.xInit==0 ){\n        sqlite3PCacheSetDefault();\n      }\n      *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;\n      break;\n    }\n\n/* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only\n** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or\n** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */\n#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)\n    case SQLITE_CONFIG_HEAP: {\n      /* EVIDENCE-OF: R-19854-42126 There are three arguments to\n      ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the\n      ** number of bytes in the memory buffer, and the minimum allocation size.\n      */\n      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);\n      sqlite3GlobalConfig.nHeap = va_arg(ap, int);\n      sqlite3GlobalConfig.mnReq = va_arg(ap, int);\n\n      if( sqlite3GlobalConfig.mnReq<1 ){\n        sqlite3GlobalConfig.mnReq = 1;\n      }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){\n        /* cap min request size at 2^12 */\n        sqlite3GlobalConfig.mnReq = (1<<12);\n      }\n\n      if( sqlite3GlobalConfig.pHeap==0 ){\n        /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)\n        ** is NULL, then SQLite reverts to using its default memory allocator\n        ** (the system malloc() implementation), undoing any prior invocation of\n        ** SQLITE_CONFIG_MALLOC.\n        **\n        ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to\n        ** revert to its default implementation when sqlite3_initialize() is run\n        */\n        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));\n      }else{\n        /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the\n        ** alternative memory allocator is engaged to handle all of SQLites\n        ** memory allocation needs. */\n#ifdef SQLITE_ENABLE_MEMSYS3\n        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();\n#endif\n#ifdef SQLITE_ENABLE_MEMSYS5\n        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();\n#endif\n      }\n      break;\n    }\n#endif\n\n    case SQLITE_CONFIG_LOOKASIDE: {\n      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);\n      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);\n      break;\n    }\n    \n    /* Record a pointer to the logger function and its first argument.\n    ** The default is NULL.  Logging is disabled if the function pointer is\n    ** NULL.\n    */\n    case SQLITE_CONFIG_LOG: {\n      /* MSVC is picky about pulling func ptrs from va lists.\n      ** http://support.microsoft.com/kb/47961\n      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));\n      */\n      typedef void(*LOGFUNC_t)(void*,int,const char*);\n      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);\n      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);\n      break;\n    }\n\n    /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames\n    ** can be changed at start-time using the\n    ** sqlite3_config(SQLITE_CONFIG_URI,1) or\n    ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.\n    */\n    case SQLITE_CONFIG_URI: {\n      /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single\n      ** argument of type int. If non-zero, then URI handling is globally\n      ** enabled. If the parameter is zero, then URI handling is globally\n      ** disabled. */\n      sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);\n      break;\n    }\n\n    case SQLITE_CONFIG_COVERING_INDEX_SCAN: {\n      /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN\n      ** option takes a single integer argument which is interpreted as a\n      ** boolean in order to enable or disable the use of covering indices for\n      ** full table scans in the query optimizer. */\n      sqlite3GlobalConfig.bUseCis = va_arg(ap, int);\n      break;\n    }\n\n#ifdef SQLITE_ENABLE_SQLLOG\n    case SQLITE_CONFIG_SQLLOG: {\n      typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);\n      sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);\n      sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);\n      break;\n    }\n#endif\n\n    case SQLITE_CONFIG_MMAP_SIZE: {\n      /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit\n      ** integer (sqlite3_int64) values that are the default mmap size limit\n      ** (the default setting for PRAGMA mmap_size) and the maximum allowed\n      ** mmap size limit. */\n      sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);\n      sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);\n      /* EVIDENCE-OF: R-53367-43190 If either argument to this option is\n      ** negative, then that argument is changed to its compile-time default.\n      **\n      ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be\n      ** silently truncated if necessary so that it does not exceed the\n      ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE\n      ** compile-time option.\n      */\n      if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){\n        mxMmap = SQLITE_MAX_MMAP_SIZE;\n      }\n      if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;\n      if( szMmap>mxMmap) szMmap = mxMmap;\n      sqlite3GlobalConfig.mxMmap = mxMmap;\n      sqlite3GlobalConfig.szMmap = szMmap;\n      break;\n    }\n\n#if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */\n    case SQLITE_CONFIG_WIN32_HEAPSIZE: {\n      /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit\n      ** unsigned integer value that specifies the maximum size of the created\n      ** heap. */\n      sqlite3GlobalConfig.nHeap = va_arg(ap, int);\n      break;\n    }\n#endif\n\n    case SQLITE_CONFIG_PMASZ: {\n      sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);\n      break;\n    }\n\n    case SQLITE_CONFIG_STMTJRNL_SPILL: {\n      sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);\n      break;\n    }\n\n#ifdef SQLITE_ENABLE_SORTER_REFERENCES\n    case SQLITE_CONFIG_SORTERREF_SIZE: {\n      int iVal = va_arg(ap, int);\n      if( iVal<0 ){\n        iVal = SQLITE_DEFAULT_SORTERREF_SIZE;\n      }\n      sqlite3GlobalConfig.szSorterRef = (u32)iVal;\n      break;\n    }\n#endif /* SQLITE_ENABLE_SORTER_REFERENCES */\n\n#ifdef SQLITE_ENABLE_DESERIALIZE\n    case SQLITE_CONFIG_MEMDB_MAXSIZE: {\n      sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64);\n      break;\n    }\n#endif /* SQLITE_ENABLE_DESERIALIZE */\n\n    default: {\n      rc = SQLITE_ERROR;\n      break;\n    }\n  }\n  va_end(ap);\n  return rc;\n}\n\n/*\n** Set up the lookaside buffers for a database connection.\n** Return SQLITE_OK on success.  \n** If lookaside is already active, return SQLITE_BUSY.\n**\n** The sz parameter is the number of bytes in each lookaside slot.\n** The cnt parameter is the number of slots.  If pStart is NULL the\n** space for the lookaside memory is obtained from sqlite3_malloc().\n** If pStart is not NULL then it is sz*cnt bytes of memory to use for\n** the lookaside memory.\n*/\nstatic int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){\n#ifndef SQLITE_OMIT_LOOKASIDE\n  void *pStart;\n  sqlite3_int64 szAlloc = sz*(sqlite3_int64)cnt;\n  int nBig;   /* Number of full-size slots */\n  int nSm;    /* Number smaller LOOKASIDE_SMALL-byte slots */\n  \n  if( sqlite3LookasideUsed(db,0)>0 ){\n    return SQLITE_BUSY;\n  }\n  /* Free any existing lookaside buffer for this handle before\n  ** allocating a new one so we don't have to have space for \n  ** both at the same time.\n  */\n  if( db->lookaside.bMalloced ){\n    sqlite3_free(db->lookaside.pStart);\n  }\n  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger\n  ** than a pointer to be useful.\n  */\n  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */\n  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;\n  if( cnt<0 ) cnt = 0;\n  if( sz==0 || cnt==0 ){\n    sz = 0;\n    pStart = 0;\n  }else if( pBuf==0 ){\n    sqlite3BeginBenignMalloc();\n    pStart = sqlite3Malloc( szAlloc );  /* IMP: R-61949-35727 */\n    sqlite3EndBenignMalloc();\n    if( pStart ) szAlloc = sqlite3MallocSize(pStart);\n  }else{\n    pStart = pBuf;\n  }\n#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE\n  if( sz>=LOOKASIDE_SMALL*3 ){\n    nBig = szAlloc/(3*LOOKASIDE_SMALL+sz);\n    nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;\n  }else if( sz>=LOOKASIDE_SMALL*2 ){\n    nBig = szAlloc/(LOOKASIDE_SMALL+sz);\n    nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;\n  }else\n#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */\n  if( sz>0 ){\n    nBig = szAlloc/sz;\n    nSm = 0;\n  }else{\n    nBig = nSm = 0;\n  }\n  db->lookaside.pStart = pStart;\n  db->lookaside.pInit = 0;\n  db->lookaside.pFree = 0;\n  db->lookaside.sz = (u16)sz;\n  db->lookaside.szTrue = (u16)sz;\n  if( pStart ){\n    int i;\n    LookasideSlot *p;\n    assert( sz > (int)sizeof(LookasideSlot*) );\n    p = (LookasideSlot*)pStart;\n    for(i=0; i<nBig; i++){\n      p->pNext = db->lookaside.pInit;\n      db->lookaside.pInit = p;\n      p = (LookasideSlot*)&((u8*)p)[sz];\n    }\n#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE\n    db->lookaside.pSmallInit = 0;\n    db->lookaside.pSmallFree = 0;\n    db->lookaside.pMiddle = p;\n    for(i=0; i<nSm; i++){\n      p->pNext = db->lookaside.pSmallInit;\n      db->lookaside.pSmallInit = p;\n      p = (LookasideSlot*)&((u8*)p)[LOOKASIDE_SMALL];\n    }\n#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */\n    assert( ((uptr)p)<=szAlloc + (uptr)pStart );\n    db->lookaside.pEnd = p;\n    db->lookaside.bDisable = 0;\n    db->lookaside.bMalloced = pBuf==0 ?1:0;\n    db->lookaside.nSlot = nBig+nSm;\n  }else{\n    db->lookaside.pStart = db;\n#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE\n    db->lookaside.pSmallInit = 0;\n    db->lookaside.pSmallFree = 0;\n    db->lookaside.pMiddle = db;\n#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */\n    db->lookaside.pEnd = db;\n    db->lookaside.bDisable = 1;\n    db->lookaside.sz = 0;\n    db->lookaside.bMalloced = 0;\n    db->lookaside.nSlot = 0;\n  }\n  assert( sqlite3LookasideUsed(db,0)==0 );\n#endif /* SQLITE_OMIT_LOOKASIDE */\n  return SQLITE_OK;\n}\n\n/*\n** Return the mutex associated with a database connection.\n*/\nSQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  return db->mutex;\n}\n\n/*\n** Free up as much memory as we can from the given database\n** connection.\n*/\nSQLITE_API int sqlite3_db_release_memory(sqlite3 *db){\n  int i;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  sqlite3BtreeEnterAll(db);\n  for(i=0; i<db->nDb; i++){\n    Btree *pBt = db->aDb[i].pBt;\n    if( pBt ){\n      Pager *pPager = sqlite3BtreePager(pBt);\n      sqlite3PagerShrink(pPager);\n    }\n  }\n  sqlite3BtreeLeaveAll(db);\n  sqlite3_mutex_leave(db->mutex);\n  return SQLITE_OK;\n}\n\n/*\n** Flush any dirty pages in the pager-cache for any attached database\n** to disk.\n*/\nSQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){\n  int i;\n  int rc = SQLITE_OK;\n  int bSeenBusy = 0;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  sqlite3BtreeEnterAll(db);\n  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){\n    Btree *pBt = db->aDb[i].pBt;\n    if( pBt && sqlite3BtreeIsInTrans(pBt) ){\n      Pager *pPager = sqlite3BtreePager(pBt);\n      rc = sqlite3PagerFlush(pPager);\n      if( rc==SQLITE_BUSY ){\n        bSeenBusy = 1;\n        rc = SQLITE_OK;\n      }\n    }\n  }\n  sqlite3BtreeLeaveAll(db);\n  sqlite3_mutex_leave(db->mutex);\n  return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);\n}\n\n/*\n** Configuration settings for an individual database connection\n*/\nSQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){\n  va_list ap;\n  int rc;\n  va_start(ap, op);\n  switch( op ){\n    case SQLITE_DBCONFIG_MAINDBNAME: {\n      /* IMP: R-06824-28531 */\n      /* IMP: R-36257-52125 */\n      db->aDb[0].zDbSName = va_arg(ap,char*);\n      rc = SQLITE_OK;\n      break;\n    }\n    case SQLITE_DBCONFIG_LOOKASIDE: {\n      void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */\n      int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */\n      int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */\n      rc = setupLookaside(db, pBuf, sz, cnt);\n      break;\n    }\n    default: {\n      static const struct {\n        int op;      /* The opcode */\n        u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */\n      } aFlagOp[] = {\n        { SQLITE_DBCONFIG_ENABLE_FKEY,           SQLITE_ForeignKeys    },\n        { SQLITE_DBCONFIG_ENABLE_TRIGGER,        SQLITE_EnableTrigger  },\n        { SQLITE_DBCONFIG_ENABLE_VIEW,           SQLITE_EnableView     },\n        { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer  },\n        { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension  },\n        { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,      SQLITE_NoCkptOnClose  },\n        { SQLITE_DBCONFIG_ENABLE_QPSG,           SQLITE_EnableQPSG     },\n        { SQLITE_DBCONFIG_TRIGGER_EQP,           SQLITE_TriggerEQP     },\n        { SQLITE_DBCONFIG_RESET_DATABASE,        SQLITE_ResetDatabase  },\n        { SQLITE_DBCONFIG_DEFENSIVE,             SQLITE_Defensive      },\n        { SQLITE_DBCONFIG_WRITABLE_SCHEMA,       SQLITE_WriteSchema|\n                                                 SQLITE_NoSchemaError  },\n        { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE,    SQLITE_LegacyAlter    },\n        { SQLITE_DBCONFIG_DQS_DDL,               SQLITE_DqsDDL         },\n        { SQLITE_DBCONFIG_DQS_DML,               SQLITE_DqsDML         },\n        { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT,    SQLITE_LegacyFileFmt  },\n        { SQLITE_DBCONFIG_TRUSTED_SCHEMA,        SQLITE_TrustedSchema  },\n      };\n      unsigned int i;\n      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */\n      for(i=0; i<ArraySize(aFlagOp); i++){\n        if( aFlagOp[i].op==op ){\n          int onoff = va_arg(ap, int);\n          int *pRes = va_arg(ap, int*);\n          u64 oldFlags = db->flags;\n          if( onoff>0 ){\n            db->flags |= aFlagOp[i].mask;\n          }else if( onoff==0 ){\n            db->flags &= ~(u64)aFlagOp[i].mask;\n          }\n          if( oldFlags!=db->flags ){\n            sqlite3ExpirePreparedStatements(db, 0);\n          }\n          if( pRes ){\n            *pRes = (db->flags & aFlagOp[i].mask)!=0;\n          }\n          rc = SQLITE_OK;\n          break;\n        }\n      }\n      break;\n    }\n  }\n  va_end(ap);\n  return rc;\n}\n\n/*\n** This is the default collating function named \"BINARY\" which is always\n** available.\n*/\nstatic int binCollFunc(\n  void *NotUsed,\n  int nKey1, const void *pKey1,\n  int nKey2, const void *pKey2\n){\n  int rc, n;\n  UNUSED_PARAMETER(NotUsed);\n  n = nKey1<nKey2 ? nKey1 : nKey2;\n  /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares\n  ** strings byte by byte using the memcmp() function from the standard C\n  ** library. */\n  assert( pKey1 && pKey2 );\n  rc = memcmp(pKey1, pKey2, n);\n  if( rc==0 ){\n    rc = nKey1 - nKey2;\n  }\n  return rc;\n}\n\n/*\n** This is the collating function named \"RTRIM\" which is always\n** available.  Ignore trailing spaces.\n*/\nstatic int rtrimCollFunc(\n  void *pUser,\n  int nKey1, const void *pKey1,\n  int nKey2, const void *pKey2\n){\n  const u8 *pK1 = (const u8*)pKey1;\n  const u8 *pK2 = (const u8*)pKey2;\n  while( nKey1 && pK1[nKey1-1]==' ' ) nKey1--;\n  while( nKey2 && pK2[nKey2-1]==' ' ) nKey2--;\n  return binCollFunc(pUser, nKey1, pKey1, nKey2, pKey2);\n}\n\n/*\n** Return true if CollSeq is the default built-in BINARY.\n*/\nSQLITE_PRIVATE int sqlite3IsBinary(const CollSeq *p){\n  assert( p==0 || p->xCmp!=binCollFunc || strcmp(p->zName,\"BINARY\")==0 );\n  return p==0 || p->xCmp==binCollFunc;\n}\n\n/*\n** Another built-in collating sequence: NOCASE. \n**\n** This collating sequence is intended to be used for \"case independent\n** comparison\". SQLite's knowledge of upper and lower case equivalents\n** extends only to the 26 characters used in the English language.\n**\n** At the moment there is only a UTF-8 implementation.\n*/\nstatic int nocaseCollatingFunc(\n  void *NotUsed,\n  int nKey1, const void *pKey1,\n  int nKey2, const void *pKey2\n){\n  int r = sqlite3StrNICmp(\n      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);\n  UNUSED_PARAMETER(NotUsed);\n  if( 0==r ){\n    r = nKey1-nKey2;\n  }\n  return r;\n}\n\n/*\n** Return the ROWID of the most recent insert\n*/\nSQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  return db->lastRowid;\n}\n\n/*\n** Set the value returned by the sqlite3_last_insert_rowid() API function.\n*/\nSQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return;\n  }\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  db->lastRowid = iRowid;\n  sqlite3_mutex_leave(db->mutex);\n}\n\n/*\n** Return the number of changes in the most recent call to sqlite3_exec().\n*/\nSQLITE_API int sqlite3_changes(sqlite3 *db){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  return db->nChange;\n}\n\n/*\n** Return the number of changes since the database handle was opened.\n*/\nSQLITE_API int sqlite3_total_changes(sqlite3 *db){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  return db->nTotalChange;\n}\n\n/*\n** Close all open savepoints. This function only manipulates fields of the\n** database handle object, it does not close any savepoints that may be open\n** at the b-tree/pager level.\n*/\nSQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){\n  while( db->pSavepoint ){\n    Savepoint *pTmp = db->pSavepoint;\n    db->pSavepoint = pTmp->pNext;\n    sqlite3DbFree(db, pTmp);\n  }\n  db->nSavepoint = 0;\n  db->nStatement = 0;\n  db->isTransactionSavepoint = 0;\n}\n\n/*\n** Invoke the destructor function associated with FuncDef p, if any. Except,\n** if this is not the last copy of the function, do not invoke it. Multiple\n** copies of a single function are created when create_function() is called\n** with SQLITE_ANY as the encoding.\n*/\nstatic void functionDestroy(sqlite3 *db, FuncDef *p){\n  FuncDestructor *pDestructor = p->u.pDestructor;\n  if( pDestructor ){\n    pDestructor->nRef--;\n    if( pDestructor->nRef==0 ){\n      pDestructor->xDestroy(pDestructor->pUserData);\n      sqlite3DbFree(db, pDestructor);\n    }\n  }\n}\n\n/*\n** Disconnect all sqlite3_vtab objects that belong to database connection\n** db. This is called when db is being closed.\n*/\nstatic void disconnectAllVtab(sqlite3 *db){\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  int i;\n  HashElem *p;\n  sqlite3BtreeEnterAll(db);\n  for(i=0; i<db->nDb; i++){\n    Schema *pSchema = db->aDb[i].pSchema;\n    if( pSchema ){\n      for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){\n        Table *pTab = (Table *)sqliteHashData(p);\n        if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);\n      }\n    }\n  }\n  for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){\n    Module *pMod = (Module *)sqliteHashData(p);\n    if( pMod->pEpoTab ){\n      sqlite3VtabDisconnect(db, pMod->pEpoTab);\n    }\n  }\n  sqlite3VtabUnlockList(db);\n  sqlite3BtreeLeaveAll(db);\n#else\n  UNUSED_PARAMETER(db);\n#endif\n}\n\n/*\n** Return TRUE if database connection db has unfinalized prepared\n** statements or unfinished sqlite3_backup objects.  \n*/\nstatic int connectionIsBusy(sqlite3 *db){\n  int j;\n  assert( sqlite3_mutex_held(db->mutex) );\n  if( db->pVdbe ) return 1;\n  for(j=0; j<db->nDb; j++){\n    Btree *pBt = db->aDb[j].pBt;\n    if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;\n  }\n  return 0;\n}\n\n/*\n** Close an existing SQLite database\n*/\nstatic int sqlite3Close(sqlite3 *db, int forceZombie){\n  if( !db ){\n    /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or\n    ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */\n    return SQLITE_OK;\n  }\n  if( !sqlite3SafetyCheckSickOrOk(db) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  sqlite3_mutex_enter(db->mutex);\n  if( db->mTrace & SQLITE_TRACE_CLOSE ){\n    db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);\n  }\n\n  /* Force xDisconnect calls on all virtual tables */\n  disconnectAllVtab(db);\n\n  /* If a transaction is open, the disconnectAllVtab() call above\n  ** will not have called the xDisconnect() method on any virtual\n  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()\n  ** call will do so. We need to do this before the check for active\n  ** SQL statements below, as the v-table implementation may be storing\n  ** some prepared statements internally.\n  */\n  sqlite3VtabRollback(db);\n\n  /* Legacy behavior (sqlite3_close() behavior) is to return\n  ** SQLITE_BUSY if the connection can not be closed immediately.\n  */\n  if( !forceZombie && connectionIsBusy(db) ){\n    sqlite3ErrorWithMsg(db, SQLITE_BUSY, \"unable to close due to unfinalized \"\n       \"statements or unfinished backups\");\n    sqlite3_mutex_leave(db->mutex);\n    return SQLITE_BUSY;\n  }\n\n#ifdef SQLITE_ENABLE_SQLLOG\n  if( sqlite3GlobalConfig.xSqllog ){\n    /* Closing the handle. Fourth parameter is passed the value 2. */\n    sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);\n  }\n#endif\n\n  /* Convert the connection into a zombie and then close it.\n  */\n  db->magic = SQLITE_MAGIC_ZOMBIE;\n  sqlite3LeaveMutexAndCloseZombie(db);\n  return SQLITE_OK;\n}\n\n/*\n** Two variations on the public interface for closing a database\n** connection. The sqlite3_close() version returns SQLITE_BUSY and\n** leaves the connection option if there are unfinalized prepared\n** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()\n** version forces the connection to become a zombie if there are\n** unclosed resources, and arranges for deallocation when the last\n** prepare statement or sqlite3_backup closes.\n*/\nSQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }\nSQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }\n\n\n/*\n** Close the mutex on database connection db.\n**\n** Furthermore, if database connection db is a zombie (meaning that there\n** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and\n** every sqlite3_stmt has now been finalized and every sqlite3_backup has\n** finished, then free all resources.\n*/\nSQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){\n  HashElem *i;                    /* Hash table iterator */\n  int j;\n\n  /* If there are outstanding sqlite3_stmt or sqlite3_backup objects\n  ** or if the connection has not yet been closed by sqlite3_close_v2(),\n  ** then just leave the mutex and return.\n  */\n  if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){\n    sqlite3_mutex_leave(db->mutex);\n    return;\n  }\n\n  /* If we reach this point, it means that the database connection has\n  ** closed all sqlite3_stmt and sqlite3_backup objects and has been\n  ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,\n  ** go ahead and free all resources.\n  */\n\n  /* If a transaction is open, roll it back. This also ensures that if\n  ** any database schemas have been modified by an uncommitted transaction\n  ** they are reset. And that the required b-tree mutex is held to make\n  ** the pager rollback and schema reset an atomic operation. */\n  sqlite3RollbackAll(db, SQLITE_OK);\n\n  /* Free any outstanding Savepoint structures. */\n  sqlite3CloseSavepoints(db);\n\n  /* Close all database connections */\n  for(j=0; j<db->nDb; j++){\n    struct Db *pDb = &db->aDb[j];\n    if( pDb->pBt ){\n      sqlite3BtreeClose(pDb->pBt);\n      pDb->pBt = 0;\n      if( j!=1 ){\n        pDb->pSchema = 0;\n      }\n    }\n  }\n  /* Clear the TEMP schema separately and last */\n  if( db->aDb[1].pSchema ){\n    sqlite3SchemaClear(db->aDb[1].pSchema);\n  }\n  sqlite3VtabUnlockList(db);\n\n  /* Free up the array of auxiliary databases */\n  sqlite3CollapseDatabaseArray(db);\n  assert( db->nDb<=2 );\n  assert( db->aDb==db->aDbStatic );\n\n  /* Tell the code in notify.c that the connection no longer holds any\n  ** locks and does not require any further unlock-notify callbacks.\n  */\n  sqlite3ConnectionClosed(db);\n\n  for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){\n    FuncDef *pNext, *p;\n    p = sqliteHashData(i);\n    do{\n      functionDestroy(db, p);\n      pNext = p->pNext;\n      sqlite3DbFree(db, p);\n      p = pNext;\n    }while( p );\n  }\n  sqlite3HashClear(&db->aFunc);\n  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){\n    CollSeq *pColl = (CollSeq *)sqliteHashData(i);\n    /* Invoke any destructors registered for collation sequence user data. */\n    for(j=0; j<3; j++){\n      if( pColl[j].xDel ){\n        pColl[j].xDel(pColl[j].pUser);\n      }\n    }\n    sqlite3DbFree(db, pColl);\n  }\n  sqlite3HashClear(&db->aCollSeq);\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){\n    Module *pMod = (Module *)sqliteHashData(i);\n    sqlite3VtabEponymousTableClear(db, pMod);\n    sqlite3VtabModuleUnref(db, pMod);\n  }\n  sqlite3HashClear(&db->aModule);\n#endif\n\n  sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */\n  sqlite3ValueFree(db->pErr);\n  sqlite3CloseExtensions(db);\n#if SQLITE_USER_AUTHENTICATION\n  sqlite3_free(db->auth.zAuthUser);\n  sqlite3_free(db->auth.zAuthPW);\n#endif\n\n  db->magic = SQLITE_MAGIC_ERROR;\n\n  /* The temp-database schema is allocated differently from the other schema\n  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).\n  ** So it needs to be freed here. Todo: Why not roll the temp schema into\n  ** the same sqliteMalloc() as the one that allocates the database \n  ** structure?\n  */\n  sqlite3DbFree(db, db->aDb[1].pSchema);\n  sqlite3_mutex_leave(db->mutex);\n  db->magic = SQLITE_MAGIC_CLOSED;\n  sqlite3_mutex_free(db->mutex);\n  assert( sqlite3LookasideUsed(db,0)==0 );\n  if( db->lookaside.bMalloced ){\n    sqlite3_free(db->lookaside.pStart);\n  }\n  sqlite3_free(db);\n}\n\n/*\n** Rollback all database files.  If tripCode is not SQLITE_OK, then\n** any write cursors are invalidated (\"tripped\" - as in \"tripping a circuit\n** breaker\") and made to return tripCode if there are any further\n** attempts to use that cursor.  Read cursors remain open and valid\n** but are \"saved\" in case the table pages are moved around.\n*/\nSQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){\n  int i;\n  int inTrans = 0;\n  int schemaChange;\n  assert( sqlite3_mutex_held(db->mutex) );\n  sqlite3BeginBenignMalloc();\n\n  /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). \n  ** This is important in case the transaction being rolled back has\n  ** modified the database schema. If the b-tree mutexes are not taken\n  ** here, then another shared-cache connection might sneak in between\n  ** the database rollback and schema reset, which can cause false\n  ** corruption reports in some cases.  */\n  sqlite3BtreeEnterAll(db);\n  schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;\n\n  for(i=0; i<db->nDb; i++){\n    Btree *p = db->aDb[i].pBt;\n    if( p ){\n      if( sqlite3BtreeIsInTrans(p) ){\n        inTrans = 1;\n      }\n      sqlite3BtreeRollback(p, tripCode, !schemaChange);\n    }\n  }\n  sqlite3VtabRollback(db);\n  sqlite3EndBenignMalloc();\n\n  if( schemaChange ){\n    sqlite3ExpirePreparedStatements(db, 0);\n    sqlite3ResetAllSchemasOfConnection(db);\n  }\n  sqlite3BtreeLeaveAll(db);\n\n  /* Any deferred constraint violations have now been resolved. */\n  db->nDeferredCons = 0;\n  db->nDeferredImmCons = 0;\n  db->flags &= ~(u64)SQLITE_DeferFKs;\n\n  /* If one has been configured, invoke the rollback-hook callback */\n  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){\n    db->xRollbackCallback(db->pRollbackArg);\n  }\n}\n\n/*\n** Return a static string containing the name corresponding to the error code\n** specified in the argument.\n*/\n#if defined(SQLITE_NEED_ERR_NAME)\nSQLITE_PRIVATE const char *sqlite3ErrName(int rc){\n  const char *zName = 0;\n  int i, origRc = rc;\n  for(i=0; i<2 && zName==0; i++, rc &= 0xff){\n    switch( rc ){\n      case SQLITE_OK:                 zName = \"SQLITE_OK\";                break;\n      case SQLITE_ERROR:              zName = \"SQLITE_ERROR\";             break;\n      case SQLITE_ERROR_SNAPSHOT:     zName = \"SQLITE_ERROR_SNAPSHOT\";    break;\n      case SQLITE_INTERNAL:           zName = \"SQLITE_INTERNAL\";          break;\n      case SQLITE_PERM:               zName = \"SQLITE_PERM\";              break;\n      case SQLITE_ABORT:              zName = \"SQLITE_ABORT\";             break;\n      case SQLITE_ABORT_ROLLBACK:     zName = \"SQLITE_ABORT_ROLLBACK\";    break;\n      case SQLITE_BUSY:               zName = \"SQLITE_BUSY\";              break;\n      case SQLITE_BUSY_RECOVERY:      zName = \"SQLITE_BUSY_RECOVERY\";     break;\n      case SQLITE_BUSY_SNAPSHOT:      zName = \"SQLITE_BUSY_SNAPSHOT\";     break;\n      case SQLITE_LOCKED:             zName = \"SQLITE_LOCKED\";            break;\n      case SQLITE_LOCKED_SHAREDCACHE: zName = \"SQLITE_LOCKED_SHAREDCACHE\";break;\n      case SQLITE_NOMEM:              zName = \"SQLITE_NOMEM\";             break;\n      case SQLITE_READONLY:           zName = \"SQLITE_READONLY\";          break;\n      case SQLITE_READONLY_RECOVERY:  zName = \"SQLITE_READONLY_RECOVERY\"; break;\n      case SQLITE_READONLY_CANTINIT:  zName = \"SQLITE_READONLY_CANTINIT\"; break;\n      case SQLITE_READONLY_ROLLBACK:  zName = \"SQLITE_READONLY_ROLLBACK\"; break;\n      case SQLITE_READONLY_DBMOVED:   zName = \"SQLITE_READONLY_DBMOVED\";  break;\n      case SQLITE_READONLY_DIRECTORY: zName = \"SQLITE_READONLY_DIRECTORY\";break;\n      case SQLITE_INTERRUPT:          zName = \"SQLITE_INTERRUPT\";         break;\n      case SQLITE_IOERR:              zName = \"SQLITE_IOERR\";             break;\n      case SQLITE_IOERR_READ:         zName = \"SQLITE_IOERR_READ\";        break;\n      case SQLITE_IOERR_SHORT_READ:   zName = \"SQLITE_IOERR_SHORT_READ\";  break;\n      case SQLITE_IOERR_WRITE:        zName = \"SQLITE_IOERR_WRITE\";       break;\n      case SQLITE_IOERR_FSYNC:        zName = \"SQLITE_IOERR_FSYNC\";       break;\n      case SQLITE_IOERR_DIR_FSYNC:    zName = \"SQLITE_IOERR_DIR_FSYNC\";   break;\n      case SQLITE_IOERR_TRUNCATE:     zName = \"SQLITE_IOERR_TRUNCATE\";    break;\n      case SQLITE_IOERR_FSTAT:        zName = \"SQLITE_IOERR_FSTAT\";       break;\n      case SQLITE_IOERR_UNLOCK:       zName = \"SQLITE_IOERR_UNLOCK\";      break;\n      case SQLITE_IOERR_RDLOCK:       zName = \"SQLITE_IOERR_RDLOCK\";      break;\n      case SQLITE_IOERR_DELETE:       zName = \"SQLITE_IOERR_DELETE\";      break;\n      case SQLITE_IOERR_NOMEM:        zName = \"SQLITE_IOERR_NOMEM\";       break;\n      case SQLITE_IOERR_ACCESS:       zName = \"SQLITE_IOERR_ACCESS\";      break;\n      case SQLITE_IOERR_CHECKRESERVEDLOCK:\n                                zName = \"SQLITE_IOERR_CHECKRESERVEDLOCK\"; break;\n      case SQLITE_IOERR_LOCK:         zName = \"SQLITE_IOERR_LOCK\";        break;\n      case SQLITE_IOERR_CLOSE:        zName = \"SQLITE_IOERR_CLOSE\";       break;\n      case SQLITE_IOERR_DIR_CLOSE:    zName = \"SQLITE_IOERR_DIR_CLOSE\";   break;\n      case SQLITE_IOERR_SHMOPEN:      zName = \"SQLITE_IOERR_SHMOPEN\";     break;\n      case SQLITE_IOERR_SHMSIZE:      zName = \"SQLITE_IOERR_SHMSIZE\";     break;\n      case SQLITE_IOERR_SHMLOCK:      zName = \"SQLITE_IOERR_SHMLOCK\";     break;\n      case SQLITE_IOERR_SHMMAP:       zName = \"SQLITE_IOERR_SHMMAP\";      break;\n      case SQLITE_IOERR_SEEK:         zName = \"SQLITE_IOERR_SEEK\";        break;\n      case SQLITE_IOERR_DELETE_NOENT: zName = \"SQLITE_IOERR_DELETE_NOENT\";break;\n      case SQLITE_IOERR_MMAP:         zName = \"SQLITE_IOERR_MMAP\";        break;\n      case SQLITE_IOERR_GETTEMPPATH:  zName = \"SQLITE_IOERR_GETTEMPPATH\"; break;\n      case SQLITE_IOERR_CONVPATH:     zName = \"SQLITE_IOERR_CONVPATH\";    break;\n      case SQLITE_CORRUPT:            zName = \"SQLITE_CORRUPT\";           break;\n      case SQLITE_CORRUPT_VTAB:       zName = \"SQLITE_CORRUPT_VTAB\";      break;\n      case SQLITE_NOTFOUND:           zName = \"SQLITE_NOTFOUND\";          break;\n      case SQLITE_FULL:               zName = \"SQLITE_FULL\";              break;\n      case SQLITE_CANTOPEN:           zName = \"SQLITE_CANTOPEN\";          break;\n      case SQLITE_CANTOPEN_NOTEMPDIR: zName = \"SQLITE_CANTOPEN_NOTEMPDIR\";break;\n      case SQLITE_CANTOPEN_ISDIR:     zName = \"SQLITE_CANTOPEN_ISDIR\";    break;\n      case SQLITE_CANTOPEN_FULLPATH:  zName = \"SQLITE_CANTOPEN_FULLPATH\"; break;\n      case SQLITE_CANTOPEN_CONVPATH:  zName = \"SQLITE_CANTOPEN_CONVPATH\"; break;\n      case SQLITE_CANTOPEN_SYMLINK:   zName = \"SQLITE_CANTOPEN_SYMLINK\";  break;\n      case SQLITE_PROTOCOL:           zName = \"SQLITE_PROTOCOL\";          break;\n      case SQLITE_EMPTY:              zName = \"SQLITE_EMPTY\";             break;\n      case SQLITE_SCHEMA:             zName = \"SQLITE_SCHEMA\";            break;\n      case SQLITE_TOOBIG:             zName = \"SQLITE_TOOBIG\";            break;\n      case SQLITE_CONSTRAINT:         zName = \"SQLITE_CONSTRAINT\";        break;\n      case SQLITE_CONSTRAINT_UNIQUE:  zName = \"SQLITE_CONSTRAINT_UNIQUE\"; break;\n      case SQLITE_CONSTRAINT_TRIGGER: zName = \"SQLITE_CONSTRAINT_TRIGGER\";break;\n      case SQLITE_CONSTRAINT_FOREIGNKEY:\n                                zName = \"SQLITE_CONSTRAINT_FOREIGNKEY\";   break;\n      case SQLITE_CONSTRAINT_CHECK:   zName = \"SQLITE_CONSTRAINT_CHECK\";  break;\n      case SQLITE_CONSTRAINT_PRIMARYKEY:\n                                zName = \"SQLITE_CONSTRAINT_PRIMARYKEY\";   break;\n      case SQLITE_CONSTRAINT_NOTNULL: zName = \"SQLITE_CONSTRAINT_NOTNULL\";break;\n      case SQLITE_CONSTRAINT_COMMITHOOK:\n                                zName = \"SQLITE_CONSTRAINT_COMMITHOOK\";   break;\n      case SQLITE_CONSTRAINT_VTAB:    zName = \"SQLITE_CONSTRAINT_VTAB\";   break;\n      case SQLITE_CONSTRAINT_FUNCTION:\n                                zName = \"SQLITE_CONSTRAINT_FUNCTION\";     break;\n      case SQLITE_CONSTRAINT_ROWID:   zName = \"SQLITE_CONSTRAINT_ROWID\";  break;\n      case SQLITE_MISMATCH:           zName = \"SQLITE_MISMATCH\";          break;\n      case SQLITE_MISUSE:             zName = \"SQLITE_MISUSE\";            break;\n      case SQLITE_NOLFS:              zName = \"SQLITE_NOLFS\";             break;\n      case SQLITE_AUTH:               zName = \"SQLITE_AUTH\";              break;\n      case SQLITE_FORMAT:             zName = \"SQLITE_FORMAT\";            break;\n      case SQLITE_RANGE:              zName = \"SQLITE_RANGE\";             break;\n      case SQLITE_NOTADB:             zName = \"SQLITE_NOTADB\";            break;\n      case SQLITE_ROW:                zName = \"SQLITE_ROW\";               break;\n      case SQLITE_NOTICE:             zName = \"SQLITE_NOTICE\";            break;\n      case SQLITE_NOTICE_RECOVER_WAL: zName = \"SQLITE_NOTICE_RECOVER_WAL\";break;\n      case SQLITE_NOTICE_RECOVER_ROLLBACK:\n                                zName = \"SQLITE_NOTICE_RECOVER_ROLLBACK\"; break;\n      case SQLITE_WARNING:            zName = \"SQLITE_WARNING\";           break;\n      case SQLITE_WARNING_AUTOINDEX:  zName = \"SQLITE_WARNING_AUTOINDEX\"; break;\n      case SQLITE_DONE:               zName = \"SQLITE_DONE\";              break;\n    }\n  }\n  if( zName==0 ){\n    static char zBuf[50];\n    sqlite3_snprintf(sizeof(zBuf), zBuf, \"SQLITE_UNKNOWN(%d)\", origRc);\n    zName = zBuf;\n  }\n  return zName;\n}\n#endif\n\n/*\n** Return a static string that describes the kind of error specified in the\n** argument.\n*/\nSQLITE_PRIVATE const char *sqlite3ErrStr(int rc){\n  static const char* const aMsg[] = {\n    /* SQLITE_OK          */ \"not an error\",\n    /* SQLITE_ERROR       */ \"SQL logic error\",\n    /* SQLITE_INTERNAL    */ 0,\n    /* SQLITE_PERM        */ \"access permission denied\",\n    /* SQLITE_ABORT       */ \"query aborted\",\n    /* SQLITE_BUSY        */ \"database is locked\",\n    /* SQLITE_LOCKED      */ \"database table is locked\",\n    /* SQLITE_NOMEM       */ \"out of memory\",\n    /* SQLITE_READONLY    */ \"attempt to write a readonly database\",\n    /* SQLITE_INTERRUPT   */ \"interrupted\",\n    /* SQLITE_IOERR       */ \"disk I/O error\",\n    /* SQLITE_CORRUPT     */ \"database disk image is malformed\",\n    /* SQLITE_NOTFOUND    */ \"unknown operation\",\n    /* SQLITE_FULL        */ \"database or disk is full\",\n    /* SQLITE_CANTOPEN    */ \"unable to open database file\",\n    /* SQLITE_PROTOCOL    */ \"locking protocol\",\n    /* SQLITE_EMPTY       */ 0,\n    /* SQLITE_SCHEMA      */ \"database schema has changed\",\n    /* SQLITE_TOOBIG      */ \"string or blob too big\",\n    /* SQLITE_CONSTRAINT  */ \"constraint failed\",\n    /* SQLITE_MISMATCH    */ \"datatype mismatch\",\n    /* SQLITE_MISUSE      */ \"bad parameter or other API misuse\",\n#ifdef SQLITE_DISABLE_LFS\n    /* SQLITE_NOLFS       */ \"large file support is disabled\",\n#else\n    /* SQLITE_NOLFS       */ 0,\n#endif\n    /* SQLITE_AUTH        */ \"authorization denied\",\n    /* SQLITE_FORMAT      */ 0,\n    /* SQLITE_RANGE       */ \"column index out of range\",\n    /* SQLITE_NOTADB      */ \"file is not a database\",\n    /* SQLITE_NOTICE      */ \"notification message\",\n    /* SQLITE_WARNING     */ \"warning message\",\n  };\n  const char *zErr = \"unknown error\";\n  switch( rc ){\n    case SQLITE_ABORT_ROLLBACK: {\n      zErr = \"abort due to ROLLBACK\";\n      break;\n    }\n    case SQLITE_ROW: {\n      zErr = \"another row available\";\n      break;\n    }\n    case SQLITE_DONE: {\n      zErr = \"no more rows available\";\n      break;\n    }\n    default: {\n      rc &= 0xff;\n      if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){\n        zErr = aMsg[rc];\n      }\n      break;\n    }\n  }\n  return zErr;\n}\n\n/*\n** This routine implements a busy callback that sleeps and tries\n** again until a timeout value is reached.  The timeout value is\n** an integer number of milliseconds passed in as the first\n** argument.\n**\n** Return non-zero to retry the lock.  Return zero to stop trying\n** and cause SQLite to return SQLITE_BUSY.\n*/\nstatic int sqliteDefaultBusyCallback(\n  void *ptr,               /* Database connection */\n  int count                /* Number of times table has been busy */\n){\n#if SQLITE_OS_WIN || HAVE_USLEEP\n  /* This case is for systems that have support for sleeping for fractions of\n  ** a second.  Examples:  All windows systems, unix systems with usleep() */\n  static const u8 delays[] =\n     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };\n  static const u8 totals[] =\n     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };\n# define NDELAY ArraySize(delays)\n  sqlite3 *db = (sqlite3 *)ptr;\n  int tmout = db->busyTimeout;\n  int delay, prior;\n\n  assert( count>=0 );\n  if( count < NDELAY ){\n    delay = delays[count];\n    prior = totals[count];\n  }else{\n    delay = delays[NDELAY-1];\n    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));\n  }\n  if( prior + delay > tmout ){\n    delay = tmout - prior;\n    if( delay<=0 ) return 0;\n  }\n  sqlite3OsSleep(db->pVfs, delay*1000);\n  return 1;\n#else\n  /* This case for unix systems that lack usleep() support.  Sleeping\n  ** must be done in increments of whole seconds */\n  sqlite3 *db = (sqlite3 *)ptr;\n  int tmout = ((sqlite3 *)ptr)->busyTimeout;\n  if( (count+1)*1000 > tmout ){\n    return 0;\n  }\n  sqlite3OsSleep(db->pVfs, 1000000);\n  return 1;\n#endif\n}\n\n/*\n** Invoke the given busy handler.\n**\n** This routine is called when an operation failed to acquire a\n** lock on VFS file pFile.\n**\n** If this routine returns non-zero, the lock is retried.  If it\n** returns 0, the operation aborts with an SQLITE_BUSY error.\n*/\nSQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){\n  int rc;\n  if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;\n  rc = p->xBusyHandler(p->pBusyArg, p->nBusy);\n  if( rc==0 ){\n    p->nBusy = -1;\n  }else{\n    p->nBusy++;\n  }\n  return rc; \n}\n\n/*\n** This routine sets the busy callback for an Sqlite database to the\n** given callback function with the given argument.\n*/\nSQLITE_API int sqlite3_busy_handler(\n  sqlite3 *db,\n  int (*xBusy)(void*,int),\n  void *pArg\n){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  db->busyHandler.xBusyHandler = xBusy;\n  db->busyHandler.pBusyArg = pArg;\n  db->busyHandler.nBusy = 0;\n  db->busyTimeout = 0;\n  sqlite3_mutex_leave(db->mutex);\n  return SQLITE_OK;\n}\n\n#ifndef SQLITE_OMIT_PROGRESS_CALLBACK\n/*\n** This routine sets the progress callback for an Sqlite database to the\n** given callback function with the given argument. The progress callback will\n** be invoked every nOps opcodes.\n*/\nSQLITE_API void sqlite3_progress_handler(\n  sqlite3 *db, \n  int nOps,\n  int (*xProgress)(void*), \n  void *pArg\n){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return;\n  }\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  if( nOps>0 ){\n    db->xProgress = xProgress;\n    db->nProgressOps = (unsigned)nOps;\n    db->pProgressArg = pArg;\n  }else{\n    db->xProgress = 0;\n    db->nProgressOps = 0;\n    db->pProgressArg = 0;\n  }\n  sqlite3_mutex_leave(db->mutex);\n}\n#endif\n\n\n/*\n** This routine installs a default busy handler that waits for the\n** specified number of milliseconds before returning 0.\n*/\nSQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;\n#endif\n  if( ms>0 ){\n    sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,\n                             (void*)db);\n    db->busyTimeout = ms;\n  }else{\n    sqlite3_busy_handler(db, 0, 0);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Cause any pending operation to stop at its earliest opportunity.\n*/\nSQLITE_API void sqlite3_interrupt(sqlite3 *db){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return;\n  }\n#endif\n  AtomicStore(&db->u1.isInterrupted, 1);\n}\n\n\n/*\n** This function is exactly the same as sqlite3_create_function(), except\n** that it is designed to be called by internal code. The difference is\n** that if a malloc() fails in sqlite3_create_function(), an error code\n** is returned and the mallocFailed flag cleared. \n*/\nSQLITE_PRIVATE int sqlite3CreateFunc(\n  sqlite3 *db,\n  const char *zFunctionName,\n  int nArg,\n  int enc,\n  void *pUserData,\n  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value **),\n  void (*xFinal)(sqlite3_context*),\n  void (*xValue)(sqlite3_context*),\n  void (*xInverse)(sqlite3_context*,int,sqlite3_value **),\n  FuncDestructor *pDestructor\n){\n  FuncDef *p;\n  int nName;\n  int extraFlags;\n\n  assert( sqlite3_mutex_held(db->mutex) );\n  assert( xValue==0 || xSFunc==0 );\n  if( zFunctionName==0                /* Must have a valid name */\n   || (xSFunc!=0 && xFinal!=0)        /* Not both xSFunc and xFinal */\n   || ((xFinal==0)!=(xStep==0))       /* Both or neither of xFinal and xStep */\n   || ((xValue==0)!=(xInverse==0))    /* Both or neither of xValue, xInverse */\n   || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)\n   || (255<(nName = sqlite3Strlen30( zFunctionName)))\n  ){\n    return SQLITE_MISUSE_BKPT;\n  }\n\n  assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );\n  assert( SQLITE_FUNC_DIRECT==SQLITE_DIRECTONLY );\n  extraFlags = enc &  (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY|\n                       SQLITE_SUBTYPE|SQLITE_INNOCUOUS);\n  enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);\n\n  /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE.  But\n  ** the meaning is inverted.  So flip the bit. */\n  assert( SQLITE_FUNC_UNSAFE==SQLITE_INNOCUOUS );\n  extraFlags ^= SQLITE_FUNC_UNSAFE;\n\n  \n#ifndef SQLITE_OMIT_UTF16\n  /* If SQLITE_UTF16 is specified as the encoding type, transform this\n  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the\n  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.\n  **\n  ** If SQLITE_ANY is specified, add three versions of the function\n  ** to the hash table.\n  */\n  if( enc==SQLITE_UTF16 ){\n    enc = SQLITE_UTF16NATIVE;\n  }else if( enc==SQLITE_ANY ){\n    int rc;\n    rc = sqlite3CreateFunc(db, zFunctionName, nArg,\n         (SQLITE_UTF8|extraFlags)^SQLITE_FUNC_UNSAFE,\n         pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);\n    if( rc==SQLITE_OK ){\n      rc = sqlite3CreateFunc(db, zFunctionName, nArg,\n           (SQLITE_UTF16LE|extraFlags)^SQLITE_FUNC_UNSAFE,\n           pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);\n    }\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    enc = SQLITE_UTF16BE;\n  }\n#else\n  enc = SQLITE_UTF8;\n#endif\n  \n  /* Check if an existing function is being overridden or deleted. If so,\n  ** and there are active VMs, then return SQLITE_BUSY. If a function\n  ** is being overridden/deleted but there are no active VMs, allow the\n  ** operation to continue but invalidate all precompiled statements.\n  */\n  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);\n  if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){\n    if( db->nVdbeActive ){\n      sqlite3ErrorWithMsg(db, SQLITE_BUSY, \n        \"unable to delete/modify user-function due to active statements\");\n      assert( !db->mallocFailed );\n      return SQLITE_BUSY;\n    }else{\n      sqlite3ExpirePreparedStatements(db, 0);\n    }\n  }\n\n  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);\n  assert(p || db->mallocFailed);\n  if( !p ){\n    return SQLITE_NOMEM_BKPT;\n  }\n\n  /* If an older version of the function with a configured destructor is\n  ** being replaced invoke the destructor function here. */\n  functionDestroy(db, p);\n\n  if( pDestructor ){\n    pDestructor->nRef++;\n  }\n  p->u.pDestructor = pDestructor;\n  p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;\n  testcase( p->funcFlags & SQLITE_DETERMINISTIC );\n  testcase( p->funcFlags & SQLITE_DIRECTONLY );\n  p->xSFunc = xSFunc ? xSFunc : xStep;\n  p->xFinalize = xFinal;\n  p->xValue = xValue;\n  p->xInverse = xInverse;\n  p->pUserData = pUserData;\n  p->nArg = (u16)nArg;\n  return SQLITE_OK;\n}\n\n/*\n** Worker function used by utf-8 APIs that create new functions:\n**\n**    sqlite3_create_function()\n**    sqlite3_create_function_v2()\n**    sqlite3_create_window_function()\n*/\nstatic int createFunctionApi(\n  sqlite3 *db,\n  const char *zFunc,\n  int nArg,\n  int enc,\n  void *p,\n  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*),\n  void (*xValue)(sqlite3_context*),\n  void (*xInverse)(sqlite3_context*,int,sqlite3_value**),\n  void(*xDestroy)(void*)\n){\n  int rc = SQLITE_ERROR;\n  FuncDestructor *pArg = 0;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  if( xDestroy ){\n    pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));\n    if( !pArg ){\n      sqlite3OomFault(db);\n      xDestroy(p);\n      goto out;\n    }\n    pArg->nRef = 0;\n    pArg->xDestroy = xDestroy;\n    pArg->pUserData = p;\n  }\n  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, \n      xSFunc, xStep, xFinal, xValue, xInverse, pArg\n  );\n  if( pArg && pArg->nRef==0 ){\n    assert( rc!=SQLITE_OK );\n    xDestroy(p);\n    sqlite3_free(pArg);\n  }\n\n out:\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** Create new user functions.\n*/\nSQLITE_API int sqlite3_create_function(\n  sqlite3 *db,\n  const char *zFunc,\n  int nArg,\n  int enc,\n  void *p,\n  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value **),\n  void (*xFinal)(sqlite3_context*)\n){\n  return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,\n                                    xFinal, 0, 0, 0);\n}\nSQLITE_API int sqlite3_create_function_v2(\n  sqlite3 *db,\n  const char *zFunc,\n  int nArg,\n  int enc,\n  void *p,\n  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value **),\n  void (*xFinal)(sqlite3_context*),\n  void (*xDestroy)(void *)\n){\n  return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,\n                                    xFinal, 0, 0, xDestroy);\n}\nSQLITE_API int sqlite3_create_window_function(\n  sqlite3 *db,\n  const char *zFunc,\n  int nArg,\n  int enc,\n  void *p,\n  void (*xStep)(sqlite3_context*,int,sqlite3_value **),\n  void (*xFinal)(sqlite3_context*),\n  void (*xValue)(sqlite3_context*),\n  void (*xInverse)(sqlite3_context*,int,sqlite3_value **),\n  void (*xDestroy)(void *)\n){\n  return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep,\n                                    xFinal, xValue, xInverse, xDestroy);\n}\n\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API int sqlite3_create_function16(\n  sqlite3 *db,\n  const void *zFunctionName,\n  int nArg,\n  int eTextRep,\n  void *p,\n  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*)\n){\n  int rc;\n  char *zFunc8;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  assert( !db->mallocFailed );\n  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);\n  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0);\n  sqlite3DbFree(db, zFunc8);\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n#endif\n\n\n/*\n** The following is the implementation of an SQL function that always\n** fails with an error message stating that the function is used in the\n** wrong context.  The sqlite3_overload_function() API might construct\n** SQL function that use this routine so that the functions will exist\n** for name resolution but are actually overloaded by the xFindFunction\n** method of virtual tables.\n*/\nstatic void sqlite3InvalidFunction(\n  sqlite3_context *context,  /* The function calling context */\n  int NotUsed,               /* Number of arguments to the function */\n  sqlite3_value **NotUsed2   /* Value of each argument */\n){\n  const char *zName = (const char*)sqlite3_user_data(context);\n  char *zErr;\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  zErr = sqlite3_mprintf(\n      \"unable to use function %s in the requested context\", zName);\n  sqlite3_result_error(context, zErr, -1);\n  sqlite3_free(zErr);\n}\n\n/*\n** Declare that a function has been overloaded by a virtual table.\n**\n** If the function already exists as a regular global function, then\n** this routine is a no-op.  If the function does not exist, then create\n** a new one that always throws a run-time error.  \n**\n** When virtual tables intend to provide an overloaded function, they\n** should call this routine to make sure the global function exists.\n** A global function must exist in order for name resolution to work\n** properly.\n*/\nSQLITE_API int sqlite3_overload_function(\n  sqlite3 *db,\n  const char *zName,\n  int nArg\n){\n  int rc;\n  char *zCopy;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){\n    return SQLITE_MISUSE_BKPT;\n  }\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;\n  sqlite3_mutex_leave(db->mutex);\n  if( rc ) return SQLITE_OK;\n  zCopy = sqlite3_mprintf(zName);\n  if( zCopy==0 ) return SQLITE_NOMEM;\n  return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,\n                           zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);\n}\n\n#ifndef SQLITE_OMIT_TRACE\n/*\n** Register a trace function.  The pArg from the previously registered trace\n** is returned.  \n**\n** A NULL trace function means that no tracing is executes.  A non-NULL\n** trace is a pointer to a function that is invoked at the start of each\n** SQL statement.\n*/\n#ifndef SQLITE_OMIT_DEPRECATED\nSQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){\n  void *pOld;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  pOld = db->pTraceArg;\n  db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;\n  db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;\n  db->pTraceArg = pArg;\n  sqlite3_mutex_leave(db->mutex);\n  return pOld;\n}\n#endif /* SQLITE_OMIT_DEPRECATED */\n\n/* Register a trace callback using the version-2 interface.\n*/\nSQLITE_API int sqlite3_trace_v2(\n  sqlite3 *db,                               /* Trace this connection */\n  unsigned mTrace,                           /* Mask of events to be traced */\n  int(*xTrace)(unsigned,void*,void*,void*),  /* Callback to invoke */\n  void *pArg                                 /* Context */\n){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  if( mTrace==0 ) xTrace = 0;\n  if( xTrace==0 ) mTrace = 0;\n  db->mTrace = mTrace;\n  db->xTrace = xTrace;\n  db->pTraceArg = pArg;\n  sqlite3_mutex_leave(db->mutex);\n  return SQLITE_OK;\n}\n\n#ifndef SQLITE_OMIT_DEPRECATED\n/*\n** Register a profile function.  The pArg from the previously registered \n** profile function is returned.  \n**\n** A NULL profile function means that no profiling is executes.  A non-NULL\n** profile is a pointer to a function that is invoked at the conclusion of\n** each SQL statement that is run.\n*/\nSQLITE_API void *sqlite3_profile(\n  sqlite3 *db,\n  void (*xProfile)(void*,const char*,sqlite_uint64),\n  void *pArg\n){\n  void *pOld;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  pOld = db->pProfileArg;\n  db->xProfile = xProfile;\n  db->pProfileArg = pArg;\n  db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK;\n  if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE;\n  sqlite3_mutex_leave(db->mutex);\n  return pOld;\n}\n#endif /* SQLITE_OMIT_DEPRECATED */\n#endif /* SQLITE_OMIT_TRACE */\n\n/*\n** Register a function to be invoked when a transaction commits.\n** If the invoked function returns non-zero, then the commit becomes a\n** rollback.\n*/\nSQLITE_API void *sqlite3_commit_hook(\n  sqlite3 *db,              /* Attach the hook to this database */\n  int (*xCallback)(void*),  /* Function to invoke on each commit */\n  void *pArg                /* Argument to the function */\n){\n  void *pOld;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  pOld = db->pCommitArg;\n  db->xCommitCallback = xCallback;\n  db->pCommitArg = pArg;\n  sqlite3_mutex_leave(db->mutex);\n  return pOld;\n}\n\n/*\n** Register a callback to be invoked each time a row is updated,\n** inserted or deleted using this database connection.\n*/\nSQLITE_API void *sqlite3_update_hook(\n  sqlite3 *db,              /* Attach the hook to this database */\n  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),\n  void *pArg                /* Argument to the function */\n){\n  void *pRet;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  pRet = db->pUpdateArg;\n  db->xUpdateCallback = xCallback;\n  db->pUpdateArg = pArg;\n  sqlite3_mutex_leave(db->mutex);\n  return pRet;\n}\n\n/*\n** Register a callback to be invoked each time a transaction is rolled\n** back by this database connection.\n*/\nSQLITE_API void *sqlite3_rollback_hook(\n  sqlite3 *db,              /* Attach the hook to this database */\n  void (*xCallback)(void*), /* Callback function */\n  void *pArg                /* Argument to the function */\n){\n  void *pRet;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  pRet = db->pRollbackArg;\n  db->xRollbackCallback = xCallback;\n  db->pRollbackArg = pArg;\n  sqlite3_mutex_leave(db->mutex);\n  return pRet;\n}\n\n#ifdef SQLITE_ENABLE_PREUPDATE_HOOK\n/*\n** Register a callback to be invoked each time a row is updated,\n** inserted or deleted using this database connection.\n*/\nSQLITE_API void *sqlite3_preupdate_hook(\n  sqlite3 *db,              /* Attach the hook to this database */\n  void(*xCallback)(         /* Callback function */\n    void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),\n  void *pArg                /* First callback argument */\n){\n  void *pRet;\n  sqlite3_mutex_enter(db->mutex);\n  pRet = db->pPreUpdateArg;\n  db->xPreUpdateCallback = xCallback;\n  db->pPreUpdateArg = pArg;\n  sqlite3_mutex_leave(db->mutex);\n  return pRet;\n}\n#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */\n\n#ifndef SQLITE_OMIT_WAL\n/*\n** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().\n** Invoke sqlite3_wal_checkpoint if the number of frames in the log file\n** is greater than sqlite3.pWalArg cast to an integer (the value configured by\n** wal_autocheckpoint()).\n*/ \nSQLITE_PRIVATE int sqlite3WalDefaultHook(\n  void *pClientData,     /* Argument */\n  sqlite3 *db,           /* Connection */\n  const char *zDb,       /* Database */\n  int nFrame             /* Size of WAL */\n){\n  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){\n    sqlite3BeginBenignMalloc();\n    sqlite3_wal_checkpoint(db, zDb);\n    sqlite3EndBenignMalloc();\n  }\n  return SQLITE_OK;\n}\n#endif /* SQLITE_OMIT_WAL */\n\n/*\n** Configure an sqlite3_wal_hook() callback to automatically checkpoint\n** a database after committing a transaction if there are nFrame or\n** more frames in the log file. Passing zero or a negative value as the\n** nFrame parameter disables automatic checkpoints entirely.\n**\n** The callback registered by this function replaces any existing callback\n** registered using sqlite3_wal_hook(). Likewise, registering a callback\n** using sqlite3_wal_hook() disables the automatic checkpoint mechanism\n** configured by this function.\n*/\nSQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){\n#ifdef SQLITE_OMIT_WAL\n  UNUSED_PARAMETER(db);\n  UNUSED_PARAMETER(nFrame);\n#else\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;\n#endif\n  if( nFrame>0 ){\n    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));\n  }else{\n    sqlite3_wal_hook(db, 0, 0);\n  }\n#endif\n  return SQLITE_OK;\n}\n\n/*\n** Register a callback to be invoked each time a transaction is written\n** into the write-ahead-log by this database connection.\n*/\nSQLITE_API void *sqlite3_wal_hook(\n  sqlite3 *db,                    /* Attach the hook to this db handle */\n  int(*xCallback)(void *, sqlite3*, const char*, int),\n  void *pArg                      /* First argument passed to xCallback() */\n){\n#ifndef SQLITE_OMIT_WAL\n  void *pRet;\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  pRet = db->pWalArg;\n  db->xWalCallback = xCallback;\n  db->pWalArg = pArg;\n  sqlite3_mutex_leave(db->mutex);\n  return pRet;\n#else\n  return 0;\n#endif\n}\n\n/*\n** Checkpoint database zDb.\n*/\nSQLITE_API int sqlite3_wal_checkpoint_v2(\n  sqlite3 *db,                    /* Database handle */\n  const char *zDb,                /* Name of attached database (or NULL) */\n  int eMode,                      /* SQLITE_CHECKPOINT_* value */\n  int *pnLog,                     /* OUT: Size of WAL log in frames */\n  int *pnCkpt                     /* OUT: Total number of frames checkpointed */\n){\n#ifdef SQLITE_OMIT_WAL\n  return SQLITE_OK;\n#else\n  int rc;                         /* Return code */\n  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;\n#endif\n\n  /* Initialize the output variables to -1 in case an error occurs. */\n  if( pnLog ) *pnLog = -1;\n  if( pnCkpt ) *pnCkpt = -1;\n\n  assert( SQLITE_CHECKPOINT_PASSIVE==0 );\n  assert( SQLITE_CHECKPOINT_FULL==1 );\n  assert( SQLITE_CHECKPOINT_RESTART==2 );\n  assert( SQLITE_CHECKPOINT_TRUNCATE==3 );\n  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){\n    /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint\n    ** mode: */\n    return SQLITE_MISUSE;\n  }\n\n  sqlite3_mutex_enter(db->mutex);\n  if( zDb && zDb[0] ){\n    iDb = sqlite3FindDbName(db, zDb);\n  }\n  if( iDb<0 ){\n    rc = SQLITE_ERROR;\n    sqlite3ErrorWithMsg(db, SQLITE_ERROR, \"unknown database: %s\", zDb);\n  }else{\n    db->busyHandler.nBusy = 0;\n    rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);\n    sqlite3Error(db, rc);\n  }\n  rc = sqlite3ApiExit(db, rc);\n\n  /* If there are no active statements, clear the interrupt flag at this\n  ** point.  */\n  if( db->nVdbeActive==0 ){\n    AtomicStore(&db->u1.isInterrupted, 0);\n  }\n\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n#endif\n}\n\n\n/*\n** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points\n** to contains a zero-length string, all attached databases are \n** checkpointed.\n*/\nSQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){\n  /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to\n  ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */\n  return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);\n}\n\n#ifndef SQLITE_OMIT_WAL\n/*\n** Run a checkpoint on database iDb. This is a no-op if database iDb is\n** not currently open in WAL mode.\n**\n** If a transaction is open on the database being checkpointed, this \n** function returns SQLITE_LOCKED and a checkpoint is not attempted. If \n** an error occurs while running the checkpoint, an SQLite error code is \n** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.\n**\n** The mutex on database handle db should be held by the caller. The mutex\n** associated with the specific b-tree being checkpointed is taken by\n** this function while the checkpoint is running.\n**\n** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are\n** checkpointed. If an error is encountered it is returned immediately -\n** no attempt is made to checkpoint any remaining databases.\n**\n** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART\n** or TRUNCATE.\n*/\nSQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){\n  int rc = SQLITE_OK;             /* Return code */\n  int i;                          /* Used to iterate through attached dbs */\n  int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */\n\n  assert( sqlite3_mutex_held(db->mutex) );\n  assert( !pnLog || *pnLog==-1 );\n  assert( !pnCkpt || *pnCkpt==-1 );\n\n  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){\n    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){\n      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);\n      pnLog = 0;\n      pnCkpt = 0;\n      if( rc==SQLITE_BUSY ){\n        bBusy = 1;\n        rc = SQLITE_OK;\n      }\n    }\n  }\n\n  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;\n}\n#endif /* SQLITE_OMIT_WAL */\n\n/*\n** This function returns true if main-memory should be used instead of\n** a temporary file for transient pager files and statement journals.\n** The value returned depends on the value of db->temp_store (runtime\n** parameter) and the compile time value of SQLITE_TEMP_STORE. The\n** following table describes the relationship between these two values\n** and this functions return value.\n**\n**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database\n**   -----------------     --------------     ------------------------------\n**   0                     any                file      (return 0)\n**   1                     1                  file      (return 0)\n**   1                     2                  memory    (return 1)\n**   1                     0                  file      (return 0)\n**   2                     1                  file      (return 0)\n**   2                     2                  memory    (return 1)\n**   2                     0                  memory    (return 1)\n**   3                     any                memory    (return 1)\n*/\nSQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){\n#if SQLITE_TEMP_STORE==1\n  return ( db->temp_store==2 );\n#endif\n#if SQLITE_TEMP_STORE==2\n  return ( db->temp_store!=1 );\n#endif\n#if SQLITE_TEMP_STORE==3\n  UNUSED_PARAMETER(db);\n  return 1;\n#endif\n#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3\n  UNUSED_PARAMETER(db);\n  return 0;\n#endif\n}\n\n/*\n** Return UTF-8 encoded English language explanation of the most recent\n** error.\n*/\nSQLITE_API const char *sqlite3_errmsg(sqlite3 *db){\n  const char *z;\n  if( !db ){\n    return sqlite3ErrStr(SQLITE_NOMEM_BKPT);\n  }\n  if( !sqlite3SafetyCheckSickOrOk(db) ){\n    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);\n  }\n  sqlite3_mutex_enter(db->mutex);\n  if( db->mallocFailed ){\n    z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);\n  }else{\n    testcase( db->pErr==0 );\n    z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0;\n    assert( !db->mallocFailed );\n    if( z==0 ){\n      z = sqlite3ErrStr(db->errCode);\n    }\n  }\n  sqlite3_mutex_leave(db->mutex);\n  return z;\n}\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** Return UTF-16 encoded English language explanation of the most recent\n** error.\n*/\nSQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){\n  static const u16 outOfMem[] = {\n    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0\n  };\n  static const u16 misuse[] = {\n    'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',\n    'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',\n    'm', 'i', 's', 'u', 's', 'e', 0\n  };\n\n  const void *z;\n  if( !db ){\n    return (void *)outOfMem;\n  }\n  if( !sqlite3SafetyCheckSickOrOk(db) ){\n    return (void *)misuse;\n  }\n  sqlite3_mutex_enter(db->mutex);\n  if( db->mallocFailed ){\n    z = (void *)outOfMem;\n  }else{\n    z = sqlite3_value_text16(db->pErr);\n    if( z==0 ){\n      sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));\n      z = sqlite3_value_text16(db->pErr);\n    }\n    /* A malloc() may have failed within the call to sqlite3_value_text16()\n    ** above. If this is the case, then the db->mallocFailed flag needs to\n    ** be cleared before returning. Do this directly, instead of via\n    ** sqlite3ApiExit(), to avoid setting the database handle error message.\n    */\n    sqlite3OomClear(db);\n  }\n  sqlite3_mutex_leave(db->mutex);\n  return z;\n}\n#endif /* SQLITE_OMIT_UTF16 */\n\n/*\n** Return the most recent error code generated by an SQLite routine. If NULL is\n** passed to this function, we assume a malloc() failed during sqlite3_open().\n*/\nSQLITE_API int sqlite3_errcode(sqlite3 *db){\n  if( db && !sqlite3SafetyCheckSickOrOk(db) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  if( !db || db->mallocFailed ){\n    return SQLITE_NOMEM_BKPT;\n  }\n  return db->errCode & db->errMask;\n}\nSQLITE_API int sqlite3_extended_errcode(sqlite3 *db){\n  if( db && !sqlite3SafetyCheckSickOrOk(db) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  if( !db || db->mallocFailed ){\n    return SQLITE_NOMEM_BKPT;\n  }\n  return db->errCode;\n}\nSQLITE_API int sqlite3_system_errno(sqlite3 *db){\n  return db ? db->iSysErrno : 0;\n}  \n\n/*\n** Return a string that describes the kind of error specified in the\n** argument.  For now, this simply calls the internal sqlite3ErrStr()\n** function.\n*/\nSQLITE_API const char *sqlite3_errstr(int rc){\n  return sqlite3ErrStr(rc);\n}\n\n/*\n** Create a new collating function for database \"db\".  The name is zName\n** and the encoding is enc.\n*/\nstatic int createCollation(\n  sqlite3* db,\n  const char *zName, \n  u8 enc,\n  void* pCtx,\n  int(*xCompare)(void*,int,const void*,int,const void*),\n  void(*xDel)(void*)\n){\n  CollSeq *pColl;\n  int enc2;\n  \n  assert( sqlite3_mutex_held(db->mutex) );\n\n  /* If SQLITE_UTF16 is specified as the encoding type, transform this\n  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the\n  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.\n  */\n  enc2 = enc;\n  testcase( enc2==SQLITE_UTF16 );\n  testcase( enc2==SQLITE_UTF16_ALIGNED );\n  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){\n    enc2 = SQLITE_UTF16NATIVE;\n  }\n  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){\n    return SQLITE_MISUSE_BKPT;\n  }\n\n  /* Check if this call is removing or replacing an existing collation \n  ** sequence. If so, and there are active VMs, return busy. If there\n  ** are no active VMs, invalidate any pre-compiled statements.\n  */\n  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);\n  if( pColl && pColl->xCmp ){\n    if( db->nVdbeActive ){\n      sqlite3ErrorWithMsg(db, SQLITE_BUSY, \n        \"unable to delete/modify collation sequence due to active statements\");\n      return SQLITE_BUSY;\n    }\n    sqlite3ExpirePreparedStatements(db, 0);\n\n    /* If collation sequence pColl was created directly by a call to\n    ** sqlite3_create_collation, and not generated by synthCollSeq(),\n    ** then any copies made by synthCollSeq() need to be invalidated.\n    ** Also, collation destructor - CollSeq.xDel() - function may need\n    ** to be called.\n    */ \n    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){\n      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);\n      int j;\n      for(j=0; j<3; j++){\n        CollSeq *p = &aColl[j];\n        if( p->enc==pColl->enc ){\n          if( p->xDel ){\n            p->xDel(p->pUser);\n          }\n          p->xCmp = 0;\n        }\n      }\n    }\n  }\n\n  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);\n  if( pColl==0 ) return SQLITE_NOMEM_BKPT;\n  pColl->xCmp = xCompare;\n  pColl->pUser = pCtx;\n  pColl->xDel = xDel;\n  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));\n  sqlite3Error(db, SQLITE_OK);\n  return SQLITE_OK;\n}\n\n\n/*\n** This array defines hard upper bounds on limit values.  The\n** initializer must be kept in sync with the SQLITE_LIMIT_*\n** #defines in sqlite3.h.\n*/\nstatic const int aHardLimit[] = {\n  SQLITE_MAX_LENGTH,\n  SQLITE_MAX_SQL_LENGTH,\n  SQLITE_MAX_COLUMN,\n  SQLITE_MAX_EXPR_DEPTH,\n  SQLITE_MAX_COMPOUND_SELECT,\n  SQLITE_MAX_VDBE_OP,\n  SQLITE_MAX_FUNCTION_ARG,\n  SQLITE_MAX_ATTACHED,\n  SQLITE_MAX_LIKE_PATTERN_LENGTH,\n  SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */\n  SQLITE_MAX_TRIGGER_DEPTH,\n  SQLITE_MAX_WORKER_THREADS,\n};\n\n/*\n** Make sure the hard limits are set to reasonable values\n*/\n#if SQLITE_MAX_LENGTH<100\n# error SQLITE_MAX_LENGTH must be at least 100\n#endif\n#if SQLITE_MAX_SQL_LENGTH<100\n# error SQLITE_MAX_SQL_LENGTH must be at least 100\n#endif\n#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH\n# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH\n#endif\n#if SQLITE_MAX_COMPOUND_SELECT<2\n# error SQLITE_MAX_COMPOUND_SELECT must be at least 2\n#endif\n#if SQLITE_MAX_VDBE_OP<40\n# error SQLITE_MAX_VDBE_OP must be at least 40\n#endif\n#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127\n# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127\n#endif\n#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125\n# error SQLITE_MAX_ATTACHED must be between 0 and 125\n#endif\n#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1\n# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1\n#endif\n#if SQLITE_MAX_COLUMN>32767\n# error SQLITE_MAX_COLUMN must not exceed 32767\n#endif\n#if SQLITE_MAX_TRIGGER_DEPTH<1\n# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1\n#endif\n#if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50\n# error SQLITE_MAX_WORKER_THREADS must be between 0 and 50\n#endif\n\n\n/*\n** Change the value of a limit.  Report the old value.\n** If an invalid limit index is supplied, report -1.\n** Make no changes but still report the old value if the\n** new limit is negative.\n**\n** A new lower limit does not shrink existing constructs.\n** It merely prevents new constructs that exceed the limit\n** from forming.\n*/\nSQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){\n  int oldLimit;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return -1;\n  }\n#endif\n\n  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME\n  ** there is a hard upper bound set at compile-time by a C preprocessor\n  ** macro called SQLITE_MAX_NAME. (The \"_LIMIT_\" in the name is changed to\n  ** \"_MAX_\".)\n  */\n  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );\n  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );\n  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );\n  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );\n  assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);\n  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );\n  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );\n  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );\n  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==\n                                               SQLITE_MAX_LIKE_PATTERN_LENGTH );\n  assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);\n  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );\n  assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );\n  assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );\n\n\n  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){\n    return -1;\n  }\n  oldLimit = db->aLimit[limitId];\n  if( newLimit>=0 ){                   /* IMP: R-52476-28732 */\n    if( newLimit>aHardLimit[limitId] ){\n      newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */\n    }\n    db->aLimit[limitId] = newLimit;\n  }\n  return oldLimit;                     /* IMP: R-53341-35419 */\n}\n\n/*\n** This function is used to parse both URIs and non-URI filenames passed by the\n** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database\n** URIs specified as part of ATTACH statements.\n**\n** The first argument to this function is the name of the VFS to use (or\n** a NULL to signify the default VFS) if the URI does not contain a \"vfs=xxx\"\n** query parameter. The second argument contains the URI (or non-URI filename)\n** itself. When this function is called the *pFlags variable should contain\n** the default flags to open the database handle with. The value stored in\n** *pFlags may be updated before returning if the URI filename contains \n** \"cache=xxx\" or \"mode=xxx\" query parameters.\n**\n** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to\n** the VFS that should be used to open the database file. *pzFile is set to\n** point to a buffer containing the name of the file to open.  The value\n** stored in *pzFile is a database name acceptable to sqlite3_uri_parameter()\n** and is in the same format as names created using sqlite3_create_filename().\n** The caller must invoke sqlite3_free_filename() (not sqlite3_free()!) on\n** the value returned in *pzFile to avoid a memory leak.\n**\n** If an error occurs, then an SQLite error code is returned and *pzErrMsg\n** may be set to point to a buffer containing an English language error \n** message. It is the responsibility of the caller to eventually release\n** this buffer by calling sqlite3_free().\n*/\nSQLITE_PRIVATE int sqlite3ParseUri(\n  const char *zDefaultVfs,        /* VFS to use if no \"vfs=xxx\" query option */\n  const char *zUri,               /* Nul-terminated URI to parse */\n  unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */\n  sqlite3_vfs **ppVfs,            /* OUT: VFS to use */ \n  char **pzFile,                  /* OUT: Filename component of URI */\n  char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */\n){\n  int rc = SQLITE_OK;\n  unsigned int flags = *pFlags;\n  const char *zVfs = zDefaultVfs;\n  char *zFile;\n  char c;\n  int nUri = sqlite3Strlen30(zUri);\n\n  assert( *pzErrMsg==0 );\n\n  if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */\n            || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */\n   && nUri>=5 && memcmp(zUri, \"file:\", 5)==0 /* IMP: R-57884-37496 */\n  ){\n    char *zOpt;\n    int eState;                   /* Parser state when parsing URI */\n    int iIn;                      /* Input character index */\n    int iOut = 0;                 /* Output character index */\n    u64 nByte = nUri+8;           /* Bytes of space to allocate */\n\n    /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen \n    ** method that there may be extra parameters following the file-name.  */\n    flags |= SQLITE_OPEN_URI;\n\n    for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');\n    zFile = sqlite3_malloc64(nByte);\n    if( !zFile ) return SQLITE_NOMEM_BKPT;\n\n    memset(zFile, 0, 4);  /* 4-byte of 0x00 is the start of DB name marker */\n    zFile += 4;\n\n    iIn = 5;\n#ifdef SQLITE_ALLOW_URI_AUTHORITY\n    if( strncmp(zUri+5, \"///\", 3)==0 ){\n      iIn = 7;\n      /* The following condition causes URIs with five leading / characters\n      ** like file://///host/path to be converted into UNCs like //host/path.\n      ** The correct URI for that UNC has only two or four leading / characters\n      ** file://host/path or file:////host/path.  But 5 leading slashes is a \n      ** common error, we are told, so we handle it as a special case. */\n      if( strncmp(zUri+7, \"///\", 3)==0 ){ iIn++; }\n    }else if( strncmp(zUri+5, \"//localhost/\", 12)==0 ){\n      iIn = 16;\n    }\n#else\n    /* Discard the scheme and authority segments of the URI. */\n    if( zUri[5]=='/' && zUri[6]=='/' ){\n      iIn = 7;\n      while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;\n      if( iIn!=7 && (iIn!=16 || memcmp(\"localhost\", &zUri[7], 9)) ){\n        *pzErrMsg = sqlite3_mprintf(\"invalid uri authority: %.*s\", \n            iIn-7, &zUri[7]);\n        rc = SQLITE_ERROR;\n        goto parse_uri_out;\n      }\n    }\n#endif\n\n    /* Copy the filename and any query parameters into the zFile buffer. \n    ** Decode %HH escape codes along the way. \n    **\n    ** Within this loop, variable eState may be set to 0, 1 or 2, depending\n    ** on the parsing context. As follows:\n    **\n    **   0: Parsing file-name.\n    **   1: Parsing name section of a name=value query parameter.\n    **   2: Parsing value section of a name=value query parameter.\n    */\n    eState = 0;\n    while( (c = zUri[iIn])!=0 && c!='#' ){\n      iIn++;\n      if( c=='%' \n       && sqlite3Isxdigit(zUri[iIn]) \n       && sqlite3Isxdigit(zUri[iIn+1]) \n      ){\n        int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);\n        octet += sqlite3HexToInt(zUri[iIn++]);\n\n        assert( octet>=0 && octet<256 );\n        if( octet==0 ){\n#ifndef SQLITE_ENABLE_URI_00_ERROR\n          /* This branch is taken when \"%00\" appears within the URI. In this\n          ** case we ignore all text in the remainder of the path, name or\n          ** value currently being parsed. So ignore the current character\n          ** and skip to the next \"?\", \"=\" or \"&\", as appropriate. */\n          while( (c = zUri[iIn])!=0 && c!='#' \n              && (eState!=0 || c!='?')\n              && (eState!=1 || (c!='=' && c!='&'))\n              && (eState!=2 || c!='&')\n          ){\n            iIn++;\n          }\n          continue;\n#else\n          /* If ENABLE_URI_00_ERROR is defined, \"%00\" in a URI is an error. */\n          *pzErrMsg = sqlite3_mprintf(\"unexpected %%00 in uri\");\n          rc = SQLITE_ERROR;\n          goto parse_uri_out;\n#endif\n        }\n        c = octet;\n      }else if( eState==1 && (c=='&' || c=='=') ){\n        if( zFile[iOut-1]==0 ){\n          /* An empty option name. Ignore this option altogether. */\n          while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;\n          continue;\n        }\n        if( c=='&' ){\n          zFile[iOut++] = '\\0';\n        }else{\n          eState = 2;\n        }\n        c = 0;\n      }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){\n        c = 0;\n        eState = 1;\n      }\n      zFile[iOut++] = c;\n    }\n    if( eState==1 ) zFile[iOut++] = '\\0';\n    memset(zFile+iOut, 0, 4); /* end-of-options + empty journal filenames */\n\n    /* Check if there were any options specified that should be interpreted \n    ** here. Options that are interpreted here include \"vfs\" and those that\n    ** correspond to flags that may be passed to the sqlite3_open_v2()\n    ** method. */\n    zOpt = &zFile[sqlite3Strlen30(zFile)+1];\n    while( zOpt[0] ){\n      int nOpt = sqlite3Strlen30(zOpt);\n      char *zVal = &zOpt[nOpt+1];\n      int nVal = sqlite3Strlen30(zVal);\n\n      if( nOpt==3 && memcmp(\"vfs\", zOpt, 3)==0 ){\n        zVfs = zVal;\n      }else{\n        struct OpenMode {\n          const char *z;\n          int mode;\n        } *aMode = 0;\n        char *zModeType = 0;\n        int mask = 0;\n        int limit = 0;\n\n        if( nOpt==5 && memcmp(\"cache\", zOpt, 5)==0 ){\n          static struct OpenMode aCacheMode[] = {\n            { \"shared\",  SQLITE_OPEN_SHAREDCACHE },\n            { \"private\", SQLITE_OPEN_PRIVATECACHE },\n            { 0, 0 }\n          };\n\n          mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;\n          aMode = aCacheMode;\n          limit = mask;\n          zModeType = \"cache\";\n        }\n        if( nOpt==4 && memcmp(\"mode\", zOpt, 4)==0 ){\n          static struct OpenMode aOpenMode[] = {\n            { \"ro\",  SQLITE_OPEN_READONLY },\n            { \"rw\",  SQLITE_OPEN_READWRITE }, \n            { \"rwc\", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },\n            { \"memory\", SQLITE_OPEN_MEMORY },\n            { 0, 0 }\n          };\n\n          mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE\n                   | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;\n          aMode = aOpenMode;\n          limit = mask & flags;\n          zModeType = \"access\";\n        }\n\n        if( aMode ){\n          int i;\n          int mode = 0;\n          for(i=0; aMode[i].z; i++){\n            const char *z = aMode[i].z;\n            if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){\n              mode = aMode[i].mode;\n              break;\n            }\n          }\n          if( mode==0 ){\n            *pzErrMsg = sqlite3_mprintf(\"no such %s mode: %s\", zModeType, zVal);\n            rc = SQLITE_ERROR;\n            goto parse_uri_out;\n          }\n          if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){\n            *pzErrMsg = sqlite3_mprintf(\"%s mode not allowed: %s\",\n                                        zModeType, zVal);\n            rc = SQLITE_PERM;\n            goto parse_uri_out;\n          }\n          flags = (flags & ~mask) | mode;\n        }\n      }\n\n      zOpt = &zVal[nVal+1];\n    }\n\n  }else{\n    zFile = sqlite3_malloc64(nUri+8);\n    if( !zFile ) return SQLITE_NOMEM_BKPT;\n    memset(zFile, 0, 4);\n    zFile += 4;\n    if( nUri ){\n      memcpy(zFile, zUri, nUri);\n    }\n    memset(zFile+nUri, 0, 4);\n    flags &= ~SQLITE_OPEN_URI;\n  }\n\n  *ppVfs = sqlite3_vfs_find(zVfs);\n  if( *ppVfs==0 ){\n    *pzErrMsg = sqlite3_mprintf(\"no such vfs: %s\", zVfs);\n    rc = SQLITE_ERROR;\n  }\n parse_uri_out:\n  if( rc!=SQLITE_OK ){\n    sqlite3_free_filename(zFile);\n    zFile = 0;\n  }\n  *pFlags = flags;\n  *pzFile = zFile;\n  return rc;\n}\n\n/*\n** This routine does the core work of extracting URI parameters from a\n** database filename for the sqlite3_uri_parameter() interface.\n*/\nstatic const char *uriParameter(const char *zFilename, const char *zParam){\n  zFilename += sqlite3Strlen30(zFilename) + 1;\n  while( zFilename[0] ){\n    int x = strcmp(zFilename, zParam);\n    zFilename += sqlite3Strlen30(zFilename) + 1;\n    if( x==0 ) return zFilename;\n    zFilename += sqlite3Strlen30(zFilename) + 1;\n  }\n  return 0;\n}\n\n\n\n/*\n** This routine does the work of opening a database on behalf of\n** sqlite3_open() and sqlite3_open16(). The database filename \"zFilename\"  \n** is UTF-8 encoded.\n*/\nstatic int openDatabase(\n  const char *zFilename, /* Database filename UTF-8 encoded */\n  sqlite3 **ppDb,        /* OUT: Returned database handle */\n  unsigned int flags,    /* Operational flags */\n  const char *zVfs       /* Name of the VFS to use */\n){\n  sqlite3 *db;                    /* Store allocated handle here */\n  int rc;                         /* Return code */\n  int isThreadsafe;               /* True for threadsafe connections */\n  char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */\n  char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */\n  int i;                          /* Loop counter */\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;\n#endif\n  *ppDb = 0;\n#ifndef SQLITE_OMIT_AUTOINIT\n  rc = sqlite3_initialize();\n  if( rc ) return rc;\n#endif\n\n  if( sqlite3GlobalConfig.bCoreMutex==0 ){\n    isThreadsafe = 0;\n  }else if( flags & SQLITE_OPEN_NOMUTEX ){\n    isThreadsafe = 0;\n  }else if( flags & SQLITE_OPEN_FULLMUTEX ){\n    isThreadsafe = 1;\n  }else{\n    isThreadsafe = sqlite3GlobalConfig.bFullMutex;\n  }\n\n  if( flags & SQLITE_OPEN_PRIVATECACHE ){\n    flags &= ~SQLITE_OPEN_SHAREDCACHE;\n  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){\n    flags |= SQLITE_OPEN_SHAREDCACHE;\n  }\n\n  /* Remove harmful bits from the flags parameter\n  **\n  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were\n  ** dealt with in the previous code block.  Besides these, the only\n  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,\n  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,\n  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask\n  ** off all other flags.\n  */\n  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |\n               SQLITE_OPEN_EXCLUSIVE |\n               SQLITE_OPEN_MAIN_DB |\n               SQLITE_OPEN_TEMP_DB | \n               SQLITE_OPEN_TRANSIENT_DB | \n               SQLITE_OPEN_MAIN_JOURNAL | \n               SQLITE_OPEN_TEMP_JOURNAL | \n               SQLITE_OPEN_SUBJOURNAL | \n               SQLITE_OPEN_MASTER_JOURNAL |\n               SQLITE_OPEN_NOMUTEX |\n               SQLITE_OPEN_FULLMUTEX |\n               SQLITE_OPEN_WAL\n             );\n\n  /* Allocate the sqlite data structure */\n  db = sqlite3MallocZero( sizeof(sqlite3) );\n  if( db==0 ) goto opendb_out;\n  if( isThreadsafe \n#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS\n   || sqlite3GlobalConfig.bCoreMutex\n#endif\n  ){\n    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);\n    if( db->mutex==0 ){\n      sqlite3_free(db);\n      db = 0;\n      goto opendb_out;\n    }\n    if( isThreadsafe==0 ){\n      sqlite3MutexWarnOnContention(db->mutex);\n    }\n  }\n  sqlite3_mutex_enter(db->mutex);\n  db->errMask = 0xff;\n  db->nDb = 2;\n  db->magic = SQLITE_MAGIC_BUSY;\n  db->aDb = db->aDbStatic;\n  db->lookaside.bDisable = 1;\n  db->lookaside.sz = 0;\n\n  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );\n  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));\n  db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;\n  db->autoCommit = 1;\n  db->nextAutovac = -1;\n  db->szMmap = sqlite3GlobalConfig.szMmap;\n  db->nextPagesize = 0;\n  db->nMaxSorterMmap = 0x7FFFFFFF;\n  db->flags |= SQLITE_ShortColNames\n                 | SQLITE_EnableTrigger\n                 | SQLITE_EnableView\n                 | SQLITE_CacheSpill\n#if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0\n                 | SQLITE_TrustedSchema\n#endif\n/* The SQLITE_DQS compile-time option determines the default settings\n** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.\n**\n**    SQLITE_DQS     SQLITE_DBCONFIG_DQS_DDL    SQLITE_DBCONFIG_DQS_DML\n**    ----------     -----------------------    -----------------------\n**     undefined               on                          on   \n**         3                   on                          on\n**         2                   on                         off\n**         1                  off                          on\n**         0                  off                         off\n**\n** Legacy behavior is 3 (double-quoted string literals are allowed anywhere)\n** and so that is the default.  But developers are encouranged to use\n** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible.\n*/\n#if !defined(SQLITE_DQS)\n# define SQLITE_DQS 3\n#endif\n#if (SQLITE_DQS&1)==1\n                 | SQLITE_DqsDML\n#endif\n#if (SQLITE_DQS&2)==2\n                 | SQLITE_DqsDDL\n#endif\n\n#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX\n                 | SQLITE_AutoIndex\n#endif\n#if SQLITE_DEFAULT_CKPTFULLFSYNC\n                 | SQLITE_CkptFullFSync\n#endif\n#if SQLITE_DEFAULT_FILE_FORMAT<4\n                 | SQLITE_LegacyFileFmt\n#endif\n#ifdef SQLITE_ENABLE_LOAD_EXTENSION\n                 | SQLITE_LoadExtension\n#endif\n#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS\n                 | SQLITE_RecTriggers\n#endif\n#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS\n                 | SQLITE_ForeignKeys\n#endif\n#if defined(SQLITE_REVERSE_UNORDERED_SELECTS)\n                 | SQLITE_ReverseOrder\n#endif\n#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)\n                 | SQLITE_CellSizeCk\n#endif\n#if defined(SQLITE_ENABLE_FTS3_TOKENIZER)\n                 | SQLITE_Fts3Tokenizer\n#endif\n#if defined(SQLITE_ENABLE_QPSG)\n                 | SQLITE_EnableQPSG\n#endif\n#if defined(SQLITE_DEFAULT_DEFENSIVE)\n                 | SQLITE_Defensive\n#endif\n#if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)\n                 | SQLITE_LegacyAlter\n#endif\n      ;\n  sqlite3HashInit(&db->aCollSeq);\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  sqlite3HashInit(&db->aModule);\n#endif\n\n  /* Add the default collation sequence BINARY. BINARY works for both UTF-8\n  ** and UTF-16, so add a version for each to avoid any unnecessary\n  ** conversions. The only error that can occur here is a malloc() failure.\n  **\n  ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating\n  ** functions:\n  */\n  createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);\n  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);\n  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);\n  createCollation(db, \"NOCASE\", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);\n  createCollation(db, \"RTRIM\", SQLITE_UTF8, 0, rtrimCollFunc, 0);\n  if( db->mallocFailed ){\n    goto opendb_out;\n  }\n\n  /* Parse the filename/URI argument\n  **\n  ** Only allow sensible combinations of bits in the flags argument.  \n  ** Throw an error if any non-sense combination is used.  If we\n  ** do not block illegal combinations here, it could trigger\n  ** assert() statements in deeper layers.  Sensible combinations\n  ** are:\n  **\n  **  1:  SQLITE_OPEN_READONLY\n  **  2:  SQLITE_OPEN_READWRITE\n  **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE\n  */\n  db->openFlags = flags;\n  assert( SQLITE_OPEN_READONLY  == 0x01 );\n  assert( SQLITE_OPEN_READWRITE == 0x02 );\n  assert( SQLITE_OPEN_CREATE    == 0x04 );\n  testcase( (1<<(flags&7))==0x02 ); /* READONLY */\n  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */\n  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */\n  if( ((1<<(flags&7)) & 0x46)==0 ){\n    rc = SQLITE_MISUSE_BKPT;  /* IMP: R-18321-05872 */\n  }else{\n    rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);\n  }\n  if( rc!=SQLITE_OK ){\n    if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);\n    sqlite3ErrorWithMsg(db, rc, zErrMsg ? \"%s\" : 0, zErrMsg);\n    sqlite3_free(zErrMsg);\n    goto opendb_out;\n  }\n\n  /* Open the backend database driver */\n  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,\n                        flags | SQLITE_OPEN_MAIN_DB);\n  if( rc!=SQLITE_OK ){\n    if( rc==SQLITE_IOERR_NOMEM ){\n      rc = SQLITE_NOMEM_BKPT;\n    }\n    sqlite3Error(db, rc);\n    goto opendb_out;\n  }\n  sqlite3BtreeEnter(db->aDb[0].pBt);\n  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);\n  if( !db->mallocFailed ){\n    sqlite3SetTextEncoding(db, SCHEMA_ENC(db));\n  }\n  sqlite3BtreeLeave(db->aDb[0].pBt);\n  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);\n\n  /* The default safety_level for the main database is FULL; for the temp\n  ** database it is OFF. This matches the pager layer defaults.  \n  */\n  db->aDb[0].zDbSName = \"main\";\n  db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;\n  db->aDb[1].zDbSName = \"temp\";\n  db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;\n\n  db->magic = SQLITE_MAGIC_OPEN;\n  if( db->mallocFailed ){\n    goto opendb_out;\n  }\n\n  /* Register all built-in functions, but do not attempt to read the\n  ** database schema yet. This is delayed until the first time the database\n  ** is accessed.\n  */\n  sqlite3Error(db, SQLITE_OK);\n  sqlite3RegisterPerConnectionBuiltinFunctions(db);\n  rc = sqlite3_errcode(db);\n\n\n  /* Load compiled-in extensions */\n  for(i=0; rc==SQLITE_OK && i<ArraySize(sqlite3BuiltinExtensions); i++){\n    rc = sqlite3BuiltinExtensions[i](db);\n  }\n\n  /* Load automatic extensions - extensions that have been registered\n  ** using the sqlite3_automatic_extension() API.\n  */\n  if( rc==SQLITE_OK ){\n    sqlite3AutoLoadExtensions(db);\n    rc = sqlite3_errcode(db);\n    if( rc!=SQLITE_OK ){\n      goto opendb_out;\n    }\n  }\n\n#ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS\n  /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time\n  ** option gives access to internal functions by default.  \n  ** Testing use only!!! */\n  db->mDbFlags |= DBFLAG_InternalFunc;\n#endif\n\n  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking\n  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking\n  ** mode.  Doing nothing at all also makes NORMAL the default.\n  */\n#ifdef SQLITE_DEFAULT_LOCKING_MODE\n  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;\n  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),\n                          SQLITE_DEFAULT_LOCKING_MODE);\n#endif\n\n  if( rc ) sqlite3Error(db, rc);\n\n  /* Enable the lookaside-malloc subsystem */\n  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,\n                        sqlite3GlobalConfig.nLookaside);\n\n  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);\n\nopendb_out:\n  if( db ){\n    assert( db->mutex!=0 || isThreadsafe==0\n           || sqlite3GlobalConfig.bFullMutex==0 );\n    sqlite3_mutex_leave(db->mutex);\n  }\n  rc = sqlite3_errcode(db);\n  assert( db!=0 || rc==SQLITE_NOMEM );\n  if( rc==SQLITE_NOMEM ){\n    sqlite3_close(db);\n    db = 0;\n  }else if( rc!=SQLITE_OK ){\n    db->magic = SQLITE_MAGIC_SICK;\n  }\n  *ppDb = db;\n#ifdef SQLITE_ENABLE_SQLLOG\n  if( sqlite3GlobalConfig.xSqllog ){\n    /* Opening a db handle. Fourth parameter is passed 0. */\n    void *pArg = sqlite3GlobalConfig.pSqllogArg;\n    sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);\n  }\n#endif\n  sqlite3_free_filename(zOpen);\n  return rc & 0xff;\n}\n\n\n/*\n** Open a new database handle.\n*/\nSQLITE_API int sqlite3_open(\n  const char *zFilename, \n  sqlite3 **ppDb \n){\n  return openDatabase(zFilename, ppDb,\n                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);\n}\nSQLITE_API int sqlite3_open_v2(\n  const char *filename,   /* Database filename (UTF-8) */\n  sqlite3 **ppDb,         /* OUT: SQLite db handle */\n  int flags,              /* Flags */\n  const char *zVfs        /* Name of VFS module to use */\n){\n  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);\n}\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** Open a new database handle.\n*/\nSQLITE_API int sqlite3_open16(\n  const void *zFilename, \n  sqlite3 **ppDb\n){\n  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */\n  sqlite3_value *pVal;\n  int rc;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;\n#endif\n  *ppDb = 0;\n#ifndef SQLITE_OMIT_AUTOINIT\n  rc = sqlite3_initialize();\n  if( rc ) return rc;\n#endif\n  if( zFilename==0 ) zFilename = \"\\000\\000\";\n  pVal = sqlite3ValueNew(0);\n  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);\n  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);\n  if( zFilename8 ){\n    rc = openDatabase(zFilename8, ppDb,\n                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);\n    assert( *ppDb || rc==SQLITE_NOMEM );\n    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){\n      SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;\n    }\n  }else{\n    rc = SQLITE_NOMEM_BKPT;\n  }\n  sqlite3ValueFree(pVal);\n\n  return rc & 0xff;\n}\n#endif /* SQLITE_OMIT_UTF16 */\n\n/*\n** Register a new collation sequence with the database handle db.\n*/\nSQLITE_API int sqlite3_create_collation(\n  sqlite3* db, \n  const char *zName, \n  int enc, \n  void* pCtx,\n  int(*xCompare)(void*,int,const void*,int,const void*)\n){\n  return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);\n}\n\n/*\n** Register a new collation sequence with the database handle db.\n*/\nSQLITE_API int sqlite3_create_collation_v2(\n  sqlite3* db, \n  const char *zName, \n  int enc, \n  void* pCtx,\n  int(*xCompare)(void*,int,const void*,int,const void*),\n  void(*xDel)(void*)\n){\n  int rc;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  assert( !db->mallocFailed );\n  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** Register a new collation sequence with the database handle db.\n*/\nSQLITE_API int sqlite3_create_collation16(\n  sqlite3* db, \n  const void *zName,\n  int enc, \n  void* pCtx,\n  int(*xCompare)(void*,int,const void*,int,const void*)\n){\n  int rc = SQLITE_OK;\n  char *zName8;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  assert( !db->mallocFailed );\n  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);\n  if( zName8 ){\n    rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);\n    sqlite3DbFree(db, zName8);\n  }\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n#endif /* SQLITE_OMIT_UTF16 */\n\n/*\n** Register a collation sequence factory callback with the database handle\n** db. Replace any previously installed collation sequence factory.\n*/\nSQLITE_API int sqlite3_collation_needed(\n  sqlite3 *db, \n  void *pCollNeededArg, \n  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)\n){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  db->xCollNeeded = xCollNeeded;\n  db->xCollNeeded16 = 0;\n  db->pCollNeededArg = pCollNeededArg;\n  sqlite3_mutex_leave(db->mutex);\n  return SQLITE_OK;\n}\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** Register a collation sequence factory callback with the database handle\n** db. Replace any previously installed collation sequence factory.\n*/\nSQLITE_API int sqlite3_collation_needed16(\n  sqlite3 *db, \n  void *pCollNeededArg, \n  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)\n){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  db->xCollNeeded = 0;\n  db->xCollNeeded16 = xCollNeeded16;\n  db->pCollNeededArg = pCollNeededArg;\n  sqlite3_mutex_leave(db->mutex);\n  return SQLITE_OK;\n}\n#endif /* SQLITE_OMIT_UTF16 */\n\n#ifndef SQLITE_OMIT_DEPRECATED\n/*\n** This function is now an anachronism. It used to be used to recover from a\n** malloc() failure, but SQLite now does this automatically.\n*/\nSQLITE_API int sqlite3_global_recover(void){\n  return SQLITE_OK;\n}\n#endif\n\n/*\n** Test to see whether or not the database connection is in autocommit\n** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on\n** by default.  Autocommit is disabled by a BEGIN statement and reenabled\n** by the next COMMIT or ROLLBACK.\n*/\nSQLITE_API int sqlite3_get_autocommit(sqlite3 *db){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  return db->autoCommit;\n}\n\n/*\n** The following routines are substitutes for constants SQLITE_CORRUPT,\n** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error\n** constants.  They serve two purposes:\n**\n**   1.  Serve as a convenient place to set a breakpoint in a debugger\n**       to detect when version error conditions occurs.\n**\n**   2.  Invoke sqlite3_log() to provide the source code location where\n**       a low-level error is first detected.\n*/\nSQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType){\n  sqlite3_log(iErr, \"%s at line %d of [%.10s]\",\n              zType, lineno, 20+sqlite3_sourceid());\n  return iErr;\n}\nSQLITE_PRIVATE int sqlite3CorruptError(int lineno){\n  testcase( sqlite3GlobalConfig.xLog!=0 );\n  return sqlite3ReportError(SQLITE_CORRUPT, lineno, \"database corruption\");\n}\nSQLITE_PRIVATE int sqlite3MisuseError(int lineno){\n  testcase( sqlite3GlobalConfig.xLog!=0 );\n  return sqlite3ReportError(SQLITE_MISUSE, lineno, \"misuse\");\n}\nSQLITE_PRIVATE int sqlite3CantopenError(int lineno){\n  testcase( sqlite3GlobalConfig.xLog!=0 );\n  return sqlite3ReportError(SQLITE_CANTOPEN, lineno, \"cannot open file\");\n}\n#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)\nSQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){\n  char zMsg[100];\n  sqlite3_snprintf(sizeof(zMsg), zMsg, \"database corruption page %d\", pgno);\n  testcase( sqlite3GlobalConfig.xLog!=0 );\n  return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);\n}\n#endif\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE int sqlite3NomemError(int lineno){\n  testcase( sqlite3GlobalConfig.xLog!=0 );\n  return sqlite3ReportError(SQLITE_NOMEM, lineno, \"OOM\");\n}\nSQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){\n  testcase( sqlite3GlobalConfig.xLog!=0 );\n  return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, \"I/O OOM error\");\n}\n#endif\n\n#ifndef SQLITE_OMIT_DEPRECATED\n/*\n** This is a convenience routine that makes sure that all thread-specific\n** data for this thread has been deallocated.\n**\n** SQLite no longer uses thread-specific data so this routine is now a\n** no-op.  It is retained for historical compatibility.\n*/\nSQLITE_API void sqlite3_thread_cleanup(void){\n}\n#endif\n\n/*\n** Return meta information about a specific column of a database table.\n** See comment in sqlite3.h (sqlite.h.in) for details.\n*/\nSQLITE_API int sqlite3_table_column_metadata(\n  sqlite3 *db,                /* Connection handle */\n  const char *zDbName,        /* Database name or NULL */\n  const char *zTableName,     /* Table name */\n  const char *zColumnName,    /* Column name */\n  char const **pzDataType,    /* OUTPUT: Declared data type */\n  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */\n  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */\n  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */\n  int *pAutoinc               /* OUTPUT: True if column is auto-increment */\n){\n  int rc;\n  char *zErrMsg = 0;\n  Table *pTab = 0;\n  Column *pCol = 0;\n  int iCol = 0;\n  char const *zDataType = 0;\n  char const *zCollSeq = 0;\n  int notnull = 0;\n  int primarykey = 0;\n  int autoinc = 0;\n\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){\n    return SQLITE_MISUSE_BKPT;\n  }\n#endif\n\n  /* Ensure the database schema has been loaded */\n  sqlite3_mutex_enter(db->mutex);\n  sqlite3BtreeEnterAll(db);\n  rc = sqlite3Init(db, &zErrMsg);\n  if( SQLITE_OK!=rc ){\n    goto error_out;\n  }\n\n  /* Locate the table in question */\n  pTab = sqlite3FindTable(db, zTableName, zDbName);\n  if( !pTab || pTab->pSelect ){\n    pTab = 0;\n    goto error_out;\n  }\n\n  /* Find the column for which info is requested */\n  if( zColumnName==0 ){\n    /* Query for existance of table only */\n  }else{\n    for(iCol=0; iCol<pTab->nCol; iCol++){\n      pCol = &pTab->aCol[iCol];\n      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){\n        break;\n      }\n    }\n    if( iCol==pTab->nCol ){\n      if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){\n        iCol = pTab->iPKey;\n        pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;\n      }else{\n        pTab = 0;\n        goto error_out;\n      }\n    }\n  }\n\n  /* The following block stores the meta information that will be returned\n  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey\n  ** and autoinc. At this point there are two possibilities:\n  ** \n  **     1. The specified column name was rowid\", \"oid\" or \"_rowid_\" \n  **        and there is no explicitly declared IPK column. \n  **\n  **     2. The table is not a view and the column name identified an \n  **        explicitly declared column. Copy meta information from *pCol.\n  */ \n  if( pCol ){\n    zDataType = sqlite3ColumnType(pCol,0);\n    zCollSeq = pCol->zColl;\n    notnull = pCol->notNull!=0;\n    primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;\n    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;\n  }else{\n    zDataType = \"INTEGER\";\n    primarykey = 1;\n  }\n  if( !zCollSeq ){\n    zCollSeq = sqlite3StrBINARY;\n  }\n\nerror_out:\n  sqlite3BtreeLeaveAll(db);\n\n  /* Whether the function call succeeded or failed, set the output parameters\n  ** to whatever their local counterparts contain. If an error did occur,\n  ** this has the effect of zeroing all output parameters.\n  */\n  if( pzDataType ) *pzDataType = zDataType;\n  if( pzCollSeq ) *pzCollSeq = zCollSeq;\n  if( pNotNull ) *pNotNull = notnull;\n  if( pPrimaryKey ) *pPrimaryKey = primarykey;\n  if( pAutoinc ) *pAutoinc = autoinc;\n\n  if( SQLITE_OK==rc && !pTab ){\n    sqlite3DbFree(db, zErrMsg);\n    zErrMsg = sqlite3MPrintf(db, \"no such table column: %s.%s\", zTableName,\n        zColumnName);\n    rc = SQLITE_ERROR;\n  }\n  sqlite3ErrorWithMsg(db, rc, (zErrMsg?\"%s\":0), zErrMsg);\n  sqlite3DbFree(db, zErrMsg);\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** Sleep for a little while.  Return the amount of time slept.\n*/\nSQLITE_API int sqlite3_sleep(int ms){\n  sqlite3_vfs *pVfs;\n  int rc;\n  pVfs = sqlite3_vfs_find(0);\n  if( pVfs==0 ) return 0;\n\n  /* This function works in milliseconds, but the underlying OsSleep() \n  ** API uses microseconds. Hence the 1000's.\n  */\n  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);\n  return rc;\n}\n\n/*\n** Enable or disable the extended result codes.\n*/\nSQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  db->errMask = onoff ? 0xffffffff : 0xff;\n  sqlite3_mutex_leave(db->mutex);\n  return SQLITE_OK;\n}\n\n/*\n** Invoke the xFileControl method on a particular database.\n*/\nSQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){\n  int rc = SQLITE_ERROR;\n  Btree *pBtree;\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  pBtree = sqlite3DbNameToBtree(db, zDbName);\n  if( pBtree ){\n    Pager *pPager;\n    sqlite3_file *fd;\n    sqlite3BtreeEnter(pBtree);\n    pPager = sqlite3BtreePager(pBtree);\n    assert( pPager!=0 );\n    fd = sqlite3PagerFile(pPager);\n    assert( fd!=0 );\n    if( op==SQLITE_FCNTL_FILE_POINTER ){\n      *(sqlite3_file**)pArg = fd;\n      rc = SQLITE_OK;\n    }else if( op==SQLITE_FCNTL_VFS_POINTER ){\n      *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);\n      rc = SQLITE_OK;\n    }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){\n      *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);\n      rc = SQLITE_OK;\n    }else if( op==SQLITE_FCNTL_DATA_VERSION ){\n      *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);\n      rc = SQLITE_OK;\n    }else if( op==SQLITE_FCNTL_RESERVE_BYTES ){\n      int iNew = *(int*)pArg;\n      *(int*)pArg = sqlite3BtreeGetRequestedReserve(pBtree);\n      if( iNew>=0 && iNew<=255 ){\n        sqlite3BtreeSetPageSize(pBtree, 0, iNew, 0);\n      }\n      rc = SQLITE_OK;\n    }else{\n      rc = sqlite3OsFileControl(fd, op, pArg);\n    }\n    sqlite3BtreeLeave(pBtree);\n  }\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** Interface to the testing logic.\n*/\nSQLITE_API int sqlite3_test_control(int op, ...){\n  int rc = 0;\n#ifdef SQLITE_UNTESTABLE\n  UNUSED_PARAMETER(op);\n#else\n  va_list ap;\n  va_start(ap, op);\n  switch( op ){\n\n    /*\n    ** Save the current state of the PRNG.\n    */\n    case SQLITE_TESTCTRL_PRNG_SAVE: {\n      sqlite3PrngSaveState();\n      break;\n    }\n\n    /*\n    ** Restore the state of the PRNG to the last state saved using\n    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then\n    ** this verb acts like PRNG_RESET.\n    */\n    case SQLITE_TESTCTRL_PRNG_RESTORE: {\n      sqlite3PrngRestoreState();\n      break;\n    }\n\n    /*  sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db);\n    **\n    ** Control the seed for the pseudo-random number generator (PRNG) that\n    ** is built into SQLite.  Cases:\n    **\n    **    x!=0 && db!=0       Seed the PRNG to the current value of the\n    **                        schema cookie in the main database for db, or\n    **                        x if the schema cookie is zero.  This case\n    **                        is convenient to use with database fuzzers\n    **                        as it allows the fuzzer some control over the\n    **                        the PRNG seed.\n    **\n    **    x!=0 && db==0       Seed the PRNG to the value of x.\n    **\n    **    x==0 && db==0       Revert to default behavior of using the\n    **                        xRandomness method on the primary VFS.\n    **\n    ** This test-control also resets the PRNG so that the new seed will\n    ** be used for the next call to sqlite3_randomness().\n    */\n#ifndef SQLITE_OMIT_WSD\n    case SQLITE_TESTCTRL_PRNG_SEED: {\n      int x = va_arg(ap, int);\n      int y;\n      sqlite3 *db = va_arg(ap, sqlite3*);\n      assert( db==0 || db->aDb[0].pSchema!=0 );\n      if( db && (y = db->aDb[0].pSchema->schema_cookie)!=0 ){ x = y; }\n      sqlite3Config.iPrngSeed = x;\n      sqlite3_randomness(0,0);\n      break;\n    }\n#endif\n\n    /*\n    **  sqlite3_test_control(BITVEC_TEST, size, program)\n    **\n    ** Run a test against a Bitvec object of size.  The program argument\n    ** is an array of integers that defines the test.  Return -1 on a\n    ** memory allocation error, 0 on success, or non-zero for an error.\n    ** See the sqlite3BitvecBuiltinTest() for additional information.\n    */\n    case SQLITE_TESTCTRL_BITVEC_TEST: {\n      int sz = va_arg(ap, int);\n      int *aProg = va_arg(ap, int*);\n      rc = sqlite3BitvecBuiltinTest(sz, aProg);\n      break;\n    }\n\n    /*\n    **  sqlite3_test_control(FAULT_INSTALL, xCallback)\n    **\n    ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,\n    ** if xCallback is not NULL.\n    **\n    ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)\n    ** is called immediately after installing the new callback and the return\n    ** value from sqlite3FaultSim(0) becomes the return from\n    ** sqlite3_test_control().\n    */\n    case SQLITE_TESTCTRL_FAULT_INSTALL: {\n      /* MSVC is picky about pulling func ptrs from va lists.\n      ** http://support.microsoft.com/kb/47961\n      ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));\n      */\n      typedef int(*TESTCALLBACKFUNC_t)(int);\n      sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);\n      rc = sqlite3FaultSim(0);\n      break;\n    }\n\n    /*\n    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)\n    **\n    ** Register hooks to call to indicate which malloc() failures \n    ** are benign.\n    */\n    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {\n      typedef void (*void_function)(void);\n      void_function xBenignBegin;\n      void_function xBenignEnd;\n      xBenignBegin = va_arg(ap, void_function);\n      xBenignEnd = va_arg(ap, void_function);\n      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);\n      break;\n    }\n\n    /*\n    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)\n    **\n    ** Set the PENDING byte to the value in the argument, if X>0.\n    ** Make no changes if X==0.  Return the value of the pending byte\n    ** as it existing before this routine was called.\n    **\n    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in\n    ** an incompatible database file format.  Changing the PENDING byte\n    ** while any database connection is open results in undefined and\n    ** deleterious behavior.\n    */\n    case SQLITE_TESTCTRL_PENDING_BYTE: {\n      rc = PENDING_BYTE;\n#ifndef SQLITE_OMIT_WSD\n      {\n        unsigned int newVal = va_arg(ap, unsigned int);\n        if( newVal ) sqlite3PendingByte = newVal;\n      }\n#endif\n      break;\n    }\n\n    /*\n    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)\n    **\n    ** This action provides a run-time test to see whether or not\n    ** assert() was enabled at compile-time.  If X is true and assert()\n    ** is enabled, then the return value is true.  If X is true and\n    ** assert() is disabled, then the return value is zero.  If X is\n    ** false and assert() is enabled, then the assertion fires and the\n    ** process aborts.  If X is false and assert() is disabled, then the\n    ** return value is zero.\n    */\n    case SQLITE_TESTCTRL_ASSERT: {\n      volatile int x = 0;\n      assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );\n      rc = x;\n      break;\n    }\n\n\n    /*\n    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)\n    **\n    ** This action provides a run-time test to see how the ALWAYS and\n    ** NEVER macros were defined at compile-time.\n    **\n    ** The return value is ALWAYS(X) if X is true, or 0 if X is false.\n    **\n    ** The recommended test is X==2.  If the return value is 2, that means\n    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the\n    ** default setting.  If the return value is 1, then ALWAYS() is either\n    ** hard-coded to true or else it asserts if its argument is false.\n    ** The first behavior (hard-coded to true) is the case if\n    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second\n    ** behavior (assert if the argument to ALWAYS() is false) is the case if\n    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.\n    **\n    ** The run-time test procedure might look something like this:\n    **\n    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){\n    **      // ALWAYS() and NEVER() are no-op pass-through macros\n    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){\n    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.\n    **    }else{\n    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.\n    **    }\n    */\n    case SQLITE_TESTCTRL_ALWAYS: {\n      int x = va_arg(ap,int);\n      rc = x ? ALWAYS(x) : 0;\n      break;\n    }\n\n    /*\n    **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);\n    **\n    ** The integer returned reveals the byte-order of the computer on which\n    ** SQLite is running:\n    **\n    **       1     big-endian,    determined at run-time\n    **      10     little-endian, determined at run-time\n    **  432101     big-endian,    determined at compile-time\n    **  123410     little-endian, determined at compile-time\n    */ \n    case SQLITE_TESTCTRL_BYTEORDER: {\n      rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;\n      break;\n    }\n\n    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)\n    **\n    ** Enable or disable various optimizations for testing purposes.  The \n    ** argument N is a bitmask of optimizations to be disabled.  For normal\n    ** operation N should be 0.  The idea is that a test program (like the\n    ** SQL Logic Test or SLT test module) can run the same SQL multiple times\n    ** with various optimizations disabled to verify that the same answer\n    ** is obtained in every case.\n    */\n    case SQLITE_TESTCTRL_OPTIMIZATIONS: {\n      sqlite3 *db = va_arg(ap, sqlite3*);\n      db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);\n      break;\n    }\n\n    /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);\n    **\n    ** If parameter onoff is non-zero, subsequent calls to localtime()\n    ** and its variants fail. If onoff is zero, undo this setting.\n    */\n    case SQLITE_TESTCTRL_LOCALTIME_FAULT: {\n      sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);\n      break;\n    }\n\n    /*   sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*);\n    **\n    ** Toggle the ability to use internal functions on or off for\n    ** the database connection given in the argument.\n    */\n    case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {\n      sqlite3 *db = va_arg(ap, sqlite3*);\n      db->mDbFlags ^= DBFLAG_InternalFunc;\n      break;\n    }\n\n    /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);\n    **\n    ** Set or clear a flag that indicates that the database file is always well-\n    ** formed and never corrupt.  This flag is clear by default, indicating that\n    ** database files might have arbitrary corruption.  Setting the flag during\n    ** testing causes certain assert() statements in the code to be activated\n    ** that demonstrat invariants on well-formed database files.\n    */\n    case SQLITE_TESTCTRL_NEVER_CORRUPT: {\n      sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);\n      break;\n    }\n\n    /*   sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int);\n    **\n    ** Set or clear a flag that causes SQLite to verify that type, name,\n    ** and tbl_name fields of the sqlite_master table.  This is normally\n    ** on, but it is sometimes useful to turn it off for testing.\n    */\n    case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: {\n      sqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int);\n      break;\n    }\n\n    /* Set the threshold at which OP_Once counters reset back to zero.\n    ** By default this is 0x7ffffffe (over 2 billion), but that value is\n    ** too big to test in a reasonable amount of time, so this control is\n    ** provided to set a small and easily reachable reset value.\n    */\n    case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {\n      sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);\n      break;\n    }\n\n    /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);\n    **\n    ** Set the VDBE coverage callback function to xCallback with context \n    ** pointer ptr.\n    */\n    case SQLITE_TESTCTRL_VDBE_COVERAGE: {\n#ifdef SQLITE_VDBE_COVERAGE\n      typedef void (*branch_callback)(void*,unsigned int,\n                                      unsigned char,unsigned char);\n      sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);\n      sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);\n#endif\n      break;\n    }\n\n    /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */\n    case SQLITE_TESTCTRL_SORTER_MMAP: {\n      sqlite3 *db = va_arg(ap, sqlite3*);\n      db->nMaxSorterMmap = va_arg(ap, int);\n      break;\n    }\n\n    /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);\n    **\n    ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if\n    ** not.\n    */\n    case SQLITE_TESTCTRL_ISINIT: {\n      if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;\n      break;\n    }\n\n    /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);\n    **\n    ** This test control is used to create imposter tables.  \"db\" is a pointer\n    ** to the database connection.  dbName is the database name (ex: \"main\" or\n    ** \"temp\") which will receive the imposter.  \"onOff\" turns imposter mode on\n    ** or off.  \"tnum\" is the root page of the b-tree to which the imposter\n    ** table should connect.\n    **\n    ** Enable imposter mode only when the schema has already been parsed.  Then\n    ** run a single CREATE TABLE statement to construct the imposter table in\n    ** the parsed schema.  Then turn imposter mode back off again.\n    **\n    ** If onOff==0 and tnum>0 then reset the schema for all databases, causing\n    ** the schema to be reparsed the next time it is needed.  This has the\n    ** effect of erasing all imposter tables.\n    */\n    case SQLITE_TESTCTRL_IMPOSTER: {\n      sqlite3 *db = va_arg(ap, sqlite3*);\n      sqlite3_mutex_enter(db->mutex);\n      db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));\n      db->init.busy = db->init.imposterTable = va_arg(ap,int);\n      db->init.newTnum = va_arg(ap,int);\n      if( db->init.busy==0 && db->init.newTnum>0 ){\n        sqlite3ResetAllSchemasOfConnection(db);\n      }\n      sqlite3_mutex_leave(db->mutex);\n      break;\n    }\n\n#if defined(YYCOVERAGE)\n    /*  sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)\n    **\n    ** This test control (only available when SQLite is compiled with\n    ** -DYYCOVERAGE) writes a report onto \"out\" that shows all\n    ** state/lookahead combinations in the parser state machine\n    ** which are never exercised.  If any state is missed, make the\n    ** return code SQLITE_ERROR.\n    */\n    case SQLITE_TESTCTRL_PARSER_COVERAGE: {\n      FILE *out = va_arg(ap, FILE*);\n      if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;\n      break;\n    }\n#endif /* defined(YYCOVERAGE) */\n\n    /*  sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*);\n    **\n    ** This test-control causes the most recent sqlite3_result_int64() value\n    ** to be interpreted as a MEM_IntReal instead of as an MEM_Int.  Normally,\n    ** MEM_IntReal values only arise during an INSERT operation of integer\n    ** values into a REAL column, so they can be challenging to test.  This\n    ** test-control enables us to write an intreal() SQL function that can\n    ** inject an intreal() value at arbitrary places in an SQL statement,\n    ** for testing purposes.\n    */\n    case SQLITE_TESTCTRL_RESULT_INTREAL: {\n      sqlite3_context *pCtx = va_arg(ap, sqlite3_context*);\n      sqlite3ResultIntReal(pCtx);\n      break;\n    }\n  }\n  va_end(ap);\n#endif /* SQLITE_UNTESTABLE */\n  return rc;\n}\n\n/*\n** The Pager stores the Database filename, Journal filename, and WAL filename\n** consecutively in memory, in that order.  The database filename is prefixed\n** by four zero bytes.  Locate the start of the database filename by searching\n** backwards for the first byte following four consecutive zero bytes.\n**\n** This only works if the filename passed in was obtained from the Pager.\n*/\nstatic const char *databaseName(const char *zName){\n  while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){\n    zName--;\n  }\n  return zName;\n}\n\n/*\n** Append text z[] to the end of p[].  Return a pointer to the first\n** character after then zero terminator on the new text in p[].\n*/\nstatic char *appendText(char *p, const char *z){\n  size_t n = strlen(z);\n  memcpy(p, z, n+1);\n  return p+n+1;\n}\n\n/*\n** Allocate memory to hold names for a database, journal file, WAL file,\n** and query parameters.  The pointer returned is valid for use by\n** sqlite3_filename_database() and sqlite3_uri_parameter() and related\n** functions.\n**\n** Memory layout must be compatible with that generated by the pager\n** and expected by sqlite3_uri_parameter() and databaseName().\n*/\nSQLITE_API char *sqlite3_create_filename(\n  const char *zDatabase,\n  const char *zJournal,\n  const char *zWal,\n  int nParam,\n  const char **azParam\n){\n  sqlite3_int64 nByte;\n  int i;\n  char *pResult, *p;\n  nByte = strlen(zDatabase) + strlen(zJournal) + strlen(zWal) + 10;\n  for(i=0; i<nParam*2; i++){\n    nByte += strlen(azParam[i])+1;\n  }\n  pResult = p = sqlite3_malloc64( nByte );\n  if( p==0 ) return 0;\n  memset(p, 0, 4);\n  p += 4;\n  p = appendText(p, zDatabase);\n  for(i=0; i<nParam*2; i++){\n    p = appendText(p, azParam[i]);\n  }\n  *(p++) = 0;\n  p = appendText(p, zJournal);\n  p = appendText(p, zWal);\n  *(p++) = 0;\n  *(p++) = 0;\n  assert( (sqlite3_int64)(p - pResult)==nByte );\n  return pResult + 4;\n}\n\n/*\n** Free memory obtained from sqlite3_create_filename().  It is a severe\n** error to call this routine with any parameter other than a pointer\n** previously obtained from sqlite3_create_filename() or a NULL pointer.\n*/\nSQLITE_API void sqlite3_free_filename(char *p){\n  if( p==0 ) return;\n  p = (char*)databaseName(p);\n  sqlite3_free(p - 4);\n}\n\n\n/*\n** This is a utility routine, useful to VFS implementations, that checks\n** to see if a database file was a URI that contained a specific query \n** parameter, and if so obtains the value of the query parameter.\n**\n** The zFilename argument is the filename pointer passed into the xOpen()\n** method of a VFS implementation.  The zParam argument is the name of the\n** query parameter we seek.  This routine returns the value of the zParam\n** parameter if it exists.  If the parameter does not exist, this routine\n** returns a NULL pointer.\n*/\nSQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){\n  if( zFilename==0 || zParam==0 ) return 0;\n  zFilename = databaseName(zFilename);\n  return uriParameter(zFilename, zParam);\n}\n\n/*\n** Return a pointer to the name of Nth query parameter of the filename.\n*/\nSQLITE_API const char *sqlite3_uri_key(const char *zFilename, int N){\n  if( zFilename==0 || N<0 ) return 0;\n  zFilename = databaseName(zFilename);\n  zFilename += sqlite3Strlen30(zFilename) + 1;\n  while( zFilename[0] && (N--)>0 ){\n    zFilename += sqlite3Strlen30(zFilename) + 1;\n    zFilename += sqlite3Strlen30(zFilename) + 1;\n  }\n  return zFilename[0] ? zFilename : 0;\n}\n\n/*\n** Return a boolean value for a query parameter.\n*/\nSQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){\n  const char *z = sqlite3_uri_parameter(zFilename, zParam);\n  bDflt = bDflt!=0;\n  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;\n}\n\n/*\n** Return a 64-bit integer value for a query parameter.\n*/\nSQLITE_API sqlite3_int64 sqlite3_uri_int64(\n  const char *zFilename,    /* Filename as passed to xOpen */\n  const char *zParam,       /* URI parameter sought */\n  sqlite3_int64 bDflt       /* return if parameter is missing */\n){\n  const char *z = sqlite3_uri_parameter(zFilename, zParam);\n  sqlite3_int64 v;\n  if( z && sqlite3DecOrHexToI64(z, &v)==0 ){\n    bDflt = v;\n  }\n  return bDflt;\n}\n\n/*\n** Translate a filename that was handed to a VFS routine into the corresponding\n** database, journal, or WAL file.\n**\n** It is an error to pass this routine a filename string that was not\n** passed into the VFS from the SQLite core.  Doing so is similar to\n** passing free() a pointer that was not obtained from malloc() - it is\n** an error that we cannot easily detect but that will likely cause memory\n** corruption.\n*/\nSQLITE_API const char *sqlite3_filename_database(const char *zFilename){\n  return databaseName(zFilename);\n}\nSQLITE_API const char *sqlite3_filename_journal(const char *zFilename){\n  zFilename = databaseName(zFilename);\n  zFilename += sqlite3Strlen30(zFilename) + 1;\n  while( zFilename[0] ){\n    zFilename += sqlite3Strlen30(zFilename) + 1;\n    zFilename += sqlite3Strlen30(zFilename) + 1;\n  }\n  return zFilename + 1;\n}\nSQLITE_API const char *sqlite3_filename_wal(const char *zFilename){\n#ifdef SQLITE_OMIT_WAL\n  return 0;\n#else\n  zFilename = sqlite3_filename_journal(zFilename);\n  zFilename += sqlite3Strlen30(zFilename) + 1;\n  return zFilename;\n#endif\n}\n\n/*\n** Return the Btree pointer identified by zDbName.  Return NULL if not found.\n*/\nSQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){\n  int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;\n  return iDb<0 ? 0 : db->aDb[iDb].pBt;\n}\n\n/*\n** Return the filename of the database associated with a database\n** connection.\n*/\nSQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){\n  Btree *pBt;\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n  pBt = sqlite3DbNameToBtree(db, zDbName);\n  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;\n}\n\n/*\n** Return 1 if database is read-only or 0 if read/write.  Return -1 if\n** no such database exists.\n*/\nSQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){\n  Btree *pBt;\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    (void)SQLITE_MISUSE_BKPT;\n    return -1;\n  }\n#endif\n  pBt = sqlite3DbNameToBtree(db, zDbName);\n  return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;\n}\n\n#ifdef SQLITE_ENABLE_SNAPSHOT\n/*\n** Obtain a snapshot handle for the snapshot of database zDb currently \n** being read by handle db.\n*/\nSQLITE_API int sqlite3_snapshot_get(\n  sqlite3 *db, \n  const char *zDb,\n  sqlite3_snapshot **ppSnapshot\n){\n  int rc = SQLITE_ERROR;\n#ifndef SQLITE_OMIT_WAL\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n#endif\n  sqlite3_mutex_enter(db->mutex);\n\n  if( db->autoCommit==0 ){\n    int iDb = sqlite3FindDbName(db, zDb);\n    if( iDb==0 || iDb>1 ){\n      Btree *pBt = db->aDb[iDb].pBt;\n      if( 0==sqlite3BtreeIsInTrans(pBt) ){\n        rc = sqlite3BtreeBeginTrans(pBt, 0, 0);\n        if( rc==SQLITE_OK ){\n          rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);\n        }\n      }\n    }\n  }\n\n  sqlite3_mutex_leave(db->mutex);\n#endif   /* SQLITE_OMIT_WAL */\n  return rc;\n}\n\n/*\n** Open a read-transaction on the snapshot idendified by pSnapshot.\n*/\nSQLITE_API int sqlite3_snapshot_open(\n  sqlite3 *db, \n  const char *zDb, \n  sqlite3_snapshot *pSnapshot\n){\n  int rc = SQLITE_ERROR;\n#ifndef SQLITE_OMIT_WAL\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n#endif\n  sqlite3_mutex_enter(db->mutex);\n  if( db->autoCommit==0 ){\n    int iDb;\n    iDb = sqlite3FindDbName(db, zDb);\n    if( iDb==0 || iDb>1 ){\n      Btree *pBt = db->aDb[iDb].pBt;\n      if( sqlite3BtreeIsInTrans(pBt)==0 ){\n        Pager *pPager = sqlite3BtreePager(pBt);\n        int bUnlock = 0;\n        if( sqlite3BtreeIsInReadTrans(pBt) ){\n          if( db->nVdbeActive==0 ){\n            rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);\n            if( rc==SQLITE_OK ){\n              bUnlock = 1;\n              rc = sqlite3BtreeCommit(pBt);\n            }\n          }\n        }else{\n          rc = SQLITE_OK;\n        }\n        if( rc==SQLITE_OK ){\n          rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);\n        }\n        if( rc==SQLITE_OK ){\n          rc = sqlite3BtreeBeginTrans(pBt, 0, 0);\n          sqlite3PagerSnapshotOpen(pPager, 0);\n        }\n        if( bUnlock ){\n          sqlite3PagerSnapshotUnlock(pPager);\n        }\n      }\n    }\n  }\n\n  sqlite3_mutex_leave(db->mutex);\n#endif   /* SQLITE_OMIT_WAL */\n  return rc;\n}\n\n/*\n** Recover as many snapshots as possible from the wal file associated with\n** schema zDb of database db.\n*/\nSQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){\n  int rc = SQLITE_ERROR;\n  int iDb;\n#ifndef SQLITE_OMIT_WAL\n\n#ifdef SQLITE_ENABLE_API_ARMOR\n  if( !sqlite3SafetyCheckOk(db) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n#endif\n\n  sqlite3_mutex_enter(db->mutex);\n  iDb = sqlite3FindDbName(db, zDb);\n  if( iDb==0 || iDb>1 ){\n    Btree *pBt = db->aDb[iDb].pBt;\n    if( 0==sqlite3BtreeIsInReadTrans(pBt) ){\n      rc = sqlite3BtreeBeginTrans(pBt, 0, 0);\n      if( rc==SQLITE_OK ){\n        rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));\n        sqlite3BtreeCommit(pBt);\n      }\n    }\n  }\n  sqlite3_mutex_leave(db->mutex);\n#endif   /* SQLITE_OMIT_WAL */\n  return rc;\n}\n\n/*\n** Free a snapshot handle obtained from sqlite3_snapshot_get().\n*/\nSQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){\n  sqlite3_free(pSnapshot);\n}\n#endif /* SQLITE_ENABLE_SNAPSHOT */\n\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\n/*\n** Given the name of a compile-time option, return true if that option\n** was used and false if not.\n**\n** The name can optionally begin with \"SQLITE_\" but the \"SQLITE_\" prefix\n** is not required for a match.\n*/\nSQLITE_API int sqlite3_compileoption_used(const char *zOptName){\n  int i, n;\n  int nOpt;\n  const char **azCompileOpt;\n \n#if SQLITE_ENABLE_API_ARMOR\n  if( zOptName==0 ){\n    (void)SQLITE_MISUSE_BKPT;\n    return 0;\n  }\n#endif\n\n  azCompileOpt = sqlite3CompileOptions(&nOpt);\n\n  if( sqlite3StrNICmp(zOptName, \"SQLITE_\", 7)==0 ) zOptName += 7;\n  n = sqlite3Strlen30(zOptName);\n\n  /* Since nOpt is normally in single digits, a linear search is \n  ** adequate. No need for a binary search. */\n  for(i=0; i<nOpt; i++){\n    if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0\n     && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0\n    ){\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/*\n** Return the N-th compile-time option string.  If N is out of range,\n** return a NULL pointer.\n*/\nSQLITE_API const char *sqlite3_compileoption_get(int N){\n  int nOpt;\n  const char **azCompileOpt;\n  azCompileOpt = sqlite3CompileOptions(&nOpt);\n  if( N>=0 && N<nOpt ){\n    return azCompileOpt[N];\n  }\n  return 0;\n}\n#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */\n\n/************** End of main.c ************************************************/\n/************** Begin file notify.c ******************************************/\n/*\n** 2009 March 3\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains the implementation of the sqlite3_unlock_notify()\n** API method and its associated functionality.\n*/\n/* #include \"sqliteInt.h\" */\n/* #include \"btreeInt.h\" */\n\n/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */\n#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY\n\n/*\n** Public interfaces:\n**\n**   sqlite3ConnectionBlocked()\n**   sqlite3ConnectionUnlocked()\n**   sqlite3ConnectionClosed()\n**   sqlite3_unlock_notify()\n*/\n\n#define assertMutexHeld() \\\n  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )\n\n/*\n** Head of a linked list of all sqlite3 objects created by this process\n** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection\n** is not NULL. This variable may only accessed while the STATIC_MASTER\n** mutex is held.\n*/\nstatic sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;\n\n#ifndef NDEBUG\n/*\n** This function is a complex assert() that verifies the following \n** properties of the blocked connections list:\n**\n**   1) Each entry in the list has a non-NULL value for either \n**      pUnlockConnection or pBlockingConnection, or both.\n**\n**   2) All entries in the list that share a common value for \n**      xUnlockNotify are grouped together.\n**\n**   3) If the argument db is not NULL, then none of the entries in the\n**      blocked connections list have pUnlockConnection or pBlockingConnection\n**      set to db. This is used when closing connection db.\n*/\nstatic void checkListProperties(sqlite3 *db){\n  sqlite3 *p;\n  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){\n    int seen = 0;\n    sqlite3 *p2;\n\n    /* Verify property (1) */\n    assert( p->pUnlockConnection || p->pBlockingConnection );\n\n    /* Verify property (2) */\n    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){\n      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;\n      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );\n      assert( db==0 || p->pUnlockConnection!=db );\n      assert( db==0 || p->pBlockingConnection!=db );\n    }\n  }\n}\n#else\n# define checkListProperties(x)\n#endif\n\n/*\n** Remove connection db from the blocked connections list. If connection\n** db is not currently a part of the list, this function is a no-op.\n*/\nstatic void removeFromBlockedList(sqlite3 *db){\n  sqlite3 **pp;\n  assertMutexHeld();\n  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){\n    if( *pp==db ){\n      *pp = (*pp)->pNextBlocked;\n      break;\n    }\n  }\n}\n\n/*\n** Add connection db to the blocked connections list. It is assumed\n** that it is not already a part of the list.\n*/\nstatic void addToBlockedList(sqlite3 *db){\n  sqlite3 **pp;\n  assertMutexHeld();\n  for(\n    pp=&sqlite3BlockedList; \n    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; \n    pp=&(*pp)->pNextBlocked\n  );\n  db->pNextBlocked = *pp;\n  *pp = db;\n}\n\n/*\n** Obtain the STATIC_MASTER mutex.\n*/\nstatic void enterMutex(void){\n  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));\n  checkListProperties(0);\n}\n\n/*\n** Release the STATIC_MASTER mutex.\n*/\nstatic void leaveMutex(void){\n  assertMutexHeld();\n  checkListProperties(0);\n  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));\n}\n\n/*\n** Register an unlock-notify callback.\n**\n** This is called after connection \"db\" has attempted some operation\n** but has received an SQLITE_LOCKED error because another connection\n** (call it pOther) in the same process was busy using the same shared\n** cache.  pOther is found by looking at db->pBlockingConnection.\n**\n** If there is no blocking connection, the callback is invoked immediately,\n** before this routine returns.\n**\n** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate\n** a deadlock.\n**\n** Otherwise, make arrangements to invoke xNotify when pOther drops\n** its locks.\n**\n** Each call to this routine overrides any prior callbacks registered\n** on the same \"db\".  If xNotify==0 then any prior callbacks are immediately\n** cancelled.\n*/\nSQLITE_API int sqlite3_unlock_notify(\n  sqlite3 *db,\n  void (*xNotify)(void **, int),\n  void *pArg\n){\n  int rc = SQLITE_OK;\n\n  sqlite3_mutex_enter(db->mutex);\n  enterMutex();\n\n  if( xNotify==0 ){\n    removeFromBlockedList(db);\n    db->pBlockingConnection = 0;\n    db->pUnlockConnection = 0;\n    db->xUnlockNotify = 0;\n    db->pUnlockArg = 0;\n  }else if( 0==db->pBlockingConnection ){\n    /* The blocking transaction has been concluded. Or there never was a \n    ** blocking transaction. In either case, invoke the notify callback\n    ** immediately. \n    */\n    xNotify(&pArg, 1);\n  }else{\n    sqlite3 *p;\n\n    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}\n    if( p ){\n      rc = SQLITE_LOCKED;              /* Deadlock detected. */\n    }else{\n      db->pUnlockConnection = db->pBlockingConnection;\n      db->xUnlockNotify = xNotify;\n      db->pUnlockArg = pArg;\n      removeFromBlockedList(db);\n      addToBlockedList(db);\n    }\n  }\n\n  leaveMutex();\n  assert( !db->mallocFailed );\n  sqlite3ErrorWithMsg(db, rc, (rc?\"database is deadlocked\":0));\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** This function is called while stepping or preparing a statement \n** associated with connection db. The operation will return SQLITE_LOCKED\n** to the user because it requires a lock that will not be available\n** until connection pBlocker concludes its current transaction.\n*/\nSQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){\n  enterMutex();\n  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){\n    addToBlockedList(db);\n  }\n  db->pBlockingConnection = pBlocker;\n  leaveMutex();\n}\n\n/*\n** This function is called when\n** the transaction opened by database db has just finished. Locks held \n** by database connection db have been released.\n**\n** This function loops through each entry in the blocked connections\n** list and does the following:\n**\n**   1) If the sqlite3.pBlockingConnection member of a list entry is\n**      set to db, then set pBlockingConnection=0.\n**\n**   2) If the sqlite3.pUnlockConnection member of a list entry is\n**      set to db, then invoke the configured unlock-notify callback and\n**      set pUnlockConnection=0.\n**\n**   3) If the two steps above mean that pBlockingConnection==0 and\n**      pUnlockConnection==0, remove the entry from the blocked connections\n**      list.\n*/\nSQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){\n  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */\n  int nArg = 0;                            /* Number of entries in aArg[] */\n  sqlite3 **pp;                            /* Iterator variable */\n  void **aArg;               /* Arguments to the unlock callback */\n  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */\n  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */\n\n  aArg = aStatic;\n  enterMutex();         /* Enter STATIC_MASTER mutex */\n\n  /* This loop runs once for each entry in the blocked-connections list. */\n  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){\n    sqlite3 *p = *pp;\n\n    /* Step 1. */\n    if( p->pBlockingConnection==db ){\n      p->pBlockingConnection = 0;\n    }\n\n    /* Step 2. */\n    if( p->pUnlockConnection==db ){\n      assert( p->xUnlockNotify );\n      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){\n        xUnlockNotify(aArg, nArg);\n        nArg = 0;\n      }\n\n      sqlite3BeginBenignMalloc();\n      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );\n      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );\n      if( (!aDyn && nArg==(int)ArraySize(aStatic))\n       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))\n      ){\n        /* The aArg[] array needs to grow. */\n        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);\n        if( pNew ){\n          memcpy(pNew, aArg, nArg*sizeof(void *));\n          sqlite3_free(aDyn);\n          aDyn = aArg = pNew;\n        }else{\n          /* This occurs when the array of context pointers that need to\n          ** be passed to the unlock-notify callback is larger than the\n          ** aStatic[] array allocated on the stack and the attempt to \n          ** allocate a larger array from the heap has failed.\n          **\n          ** This is a difficult situation to handle. Returning an error\n          ** code to the caller is insufficient, as even if an error code\n          ** is returned the transaction on connection db will still be\n          ** closed and the unlock-notify callbacks on blocked connections\n          ** will go unissued. This might cause the application to wait\n          ** indefinitely for an unlock-notify callback that will never \n          ** arrive.\n          **\n          ** Instead, invoke the unlock-notify callback with the context\n          ** array already accumulated. We can then clear the array and\n          ** begin accumulating any further context pointers without \n          ** requiring any dynamic allocation. This is sub-optimal because\n          ** it means that instead of one callback with a large array of\n          ** context pointers the application will receive two or more\n          ** callbacks with smaller arrays of context pointers, which will\n          ** reduce the applications ability to prioritize multiple \n          ** connections. But it is the best that can be done under the\n          ** circumstances.\n          */\n          xUnlockNotify(aArg, nArg);\n          nArg = 0;\n        }\n      }\n      sqlite3EndBenignMalloc();\n\n      aArg[nArg++] = p->pUnlockArg;\n      xUnlockNotify = p->xUnlockNotify;\n      p->pUnlockConnection = 0;\n      p->xUnlockNotify = 0;\n      p->pUnlockArg = 0;\n    }\n\n    /* Step 3. */\n    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){\n      /* Remove connection p from the blocked connections list. */\n      *pp = p->pNextBlocked;\n      p->pNextBlocked = 0;\n    }else{\n      pp = &p->pNextBlocked;\n    }\n  }\n\n  if( nArg!=0 ){\n    xUnlockNotify(aArg, nArg);\n  }\n  sqlite3_free(aDyn);\n  leaveMutex();         /* Leave STATIC_MASTER mutex */\n}\n\n/*\n** This is called when the database connection passed as an argument is \n** being closed. The connection is removed from the blocked list.\n*/\nSQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){\n  sqlite3ConnectionUnlocked(db);\n  enterMutex();\n  removeFromBlockedList(db);\n  checkListProperties(db);\n  leaveMutex();\n}\n#endif\n\n/************** End of notify.c **********************************************/\n/************** Begin file fts3.c ********************************************/\n/*\n** 2006 Oct 10\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This is an SQLite module implementing full-text search.\n*/\n\n/*\n** The code in this file is only compiled if:\n**\n**     * The FTS3 module is being built as an extension\n**       (in which case SQLITE_CORE is not defined), or\n**\n**     * The FTS3 module is being built into the core of\n**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).\n*/\n\n/* The full-text index is stored in a series of b+tree (-like)\n** structures called segments which map terms to doclists.  The\n** structures are like b+trees in layout, but are constructed from the\n** bottom up in optimal fashion and are not updatable.  Since trees\n** are built from the bottom up, things will be described from the\n** bottom up.\n**\n**\n**** Varints ****\n** The basic unit of encoding is a variable-length integer called a\n** varint.  We encode variable-length integers in little-endian order\n** using seven bits * per byte as follows:\n**\n** KEY:\n**         A = 0xxxxxxx    7 bits of data and one flag bit\n**         B = 1xxxxxxx    7 bits of data and one flag bit\n**\n**  7 bits - A\n** 14 bits - BA\n** 21 bits - BBA\n** and so on.\n**\n** This is similar in concept to how sqlite encodes \"varints\" but\n** the encoding is not the same.  SQLite varints are big-endian\n** are are limited to 9 bytes in length whereas FTS3 varints are\n** little-endian and can be up to 10 bytes in length (in theory).\n**\n** Example encodings:\n**\n**     1:    0x01\n**   127:    0x7f\n**   128:    0x81 0x00\n**\n**\n**** Document lists ****\n** A doclist (document list) holds a docid-sorted list of hits for a\n** given term.  Doclists hold docids and associated token positions.\n** A docid is the unique integer identifier for a single document.\n** A position is the index of a word within the document.  The first \n** word of the document has a position of 0.\n**\n** FTS3 used to optionally store character offsets using a compile-time\n** option.  But that functionality is no longer supported.\n**\n** A doclist is stored like this:\n**\n** array {\n**   varint docid;          (delta from previous doclist)\n**   array {                (position list for column 0)\n**     varint position;     (2 more than the delta from previous position)\n**   }\n**   array {\n**     varint POS_COLUMN;   (marks start of position list for new column)\n**     varint column;       (index of new column)\n**     array {\n**       varint position;   (2 more than the delta from previous position)\n**     }\n**   }\n**   varint POS_END;        (marks end of positions for this document.\n** }\n**\n** Here, array { X } means zero or more occurrences of X, adjacent in\n** memory.  A \"position\" is an index of a token in the token stream\n** generated by the tokenizer. Note that POS_END and POS_COLUMN occur \n** in the same logical place as the position element, and act as sentinals\n** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.\n** The positions numbers are not stored literally but rather as two more\n** than the difference from the prior position, or the just the position plus\n** 2 for the first position.  Example:\n**\n**   label:       A B C D E  F  G H   I  J K\n**   value:     123 5 9 1 1 14 35 0 234 72 0\n**\n** The 123 value is the first docid.  For column zero in this document\n** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1\n** at D signals the start of a new column; the 1 at E indicates that the\n** new column is column number 1.  There are two positions at 12 and 45\n** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The\n** 234 at I is the delta to next docid (357).  It has one position 70\n** (72-2) and then terminates with the 0 at K.\n**\n** A \"position-list\" is the list of positions for multiple columns for\n** a single docid.  A \"column-list\" is the set of positions for a single\n** column.  Hence, a position-list consists of one or more column-lists,\n** a document record consists of a docid followed by a position-list and\n** a doclist consists of one or more document records.\n**\n** A bare doclist omits the position information, becoming an \n** array of varint-encoded docids.\n**\n**** Segment leaf nodes ****\n** Segment leaf nodes store terms and doclists, ordered by term.  Leaf\n** nodes are written using LeafWriter, and read using LeafReader (to\n** iterate through a single leaf node's data) and LeavesReader (to\n** iterate through a segment's entire leaf layer).  Leaf nodes have\n** the format:\n**\n** varint iHeight;             (height from leaf level, always 0)\n** varint nTerm;               (length of first term)\n** char pTerm[nTerm];          (content of first term)\n** varint nDoclist;            (length of term's associated doclist)\n** char pDoclist[nDoclist];    (content of doclist)\n** array {\n**                             (further terms are delta-encoded)\n**   varint nPrefix;           (length of prefix shared with previous term)\n**   varint nSuffix;           (length of unshared suffix)\n**   char pTermSuffix[nSuffix];(unshared suffix of next term)\n**   varint nDoclist;          (length of term's associated doclist)\n**   char pDoclist[nDoclist];  (content of doclist)\n** }\n**\n** Here, array { X } means zero or more occurrences of X, adjacent in\n** memory.\n**\n** Leaf nodes are broken into blocks which are stored contiguously in\n** the %_segments table in sorted order.  This means that when the end\n** of a node is reached, the next term is in the node with the next\n** greater node id.\n**\n** New data is spilled to a new leaf node when the current node\n** exceeds LEAF_MAX bytes (default 2048).  New data which itself is\n** larger than STANDALONE_MIN (default 1024) is placed in a standalone\n** node (a leaf node with a single term and doclist).  The goal of\n** these settings is to pack together groups of small doclists while\n** making it efficient to directly access large doclists.  The\n** assumption is that large doclists represent terms which are more\n** likely to be query targets.\n**\n** TODO(shess) It may be useful for blocking decisions to be more\n** dynamic.  For instance, it may make more sense to have a 2.5k leaf\n** node rather than splitting into 2k and .5k nodes.  My intuition is\n** that this might extend through 2x or 4x the pagesize.\n**\n**\n**** Segment interior nodes ****\n** Segment interior nodes store blockids for subtree nodes and terms\n** to describe what data is stored by the each subtree.  Interior\n** nodes are written using InteriorWriter, and read using\n** InteriorReader.  InteriorWriters are created as needed when\n** SegmentWriter creates new leaf nodes, or when an interior node\n** itself grows too big and must be split.  The format of interior\n** nodes:\n**\n** varint iHeight;           (height from leaf level, always >0)\n** varint iBlockid;          (block id of node's leftmost subtree)\n** optional {\n**   varint nTerm;           (length of first term)\n**   char pTerm[nTerm];      (content of first term)\n**   array {\n**                                (further terms are delta-encoded)\n**     varint nPrefix;            (length of shared prefix with previous term)\n**     varint nSuffix;            (length of unshared suffix)\n**     char pTermSuffix[nSuffix]; (unshared suffix of next term)\n**   }\n** }\n**\n** Here, optional { X } means an optional element, while array { X }\n** means zero or more occurrences of X, adjacent in memory.\n**\n** An interior node encodes n terms separating n+1 subtrees.  The\n** subtree blocks are contiguous, so only the first subtree's blockid\n** is encoded.  The subtree at iBlockid will contain all terms less\n** than the first term encoded (or all terms if no term is encoded).\n** Otherwise, for terms greater than or equal to pTerm[i] but less\n** than pTerm[i+1], the subtree for that term will be rooted at\n** iBlockid+i.  Interior nodes only store enough term data to\n** distinguish adjacent children (if the rightmost term of the left\n** child is \"something\", and the leftmost term of the right child is\n** \"wicked\", only \"w\" is stored).\n**\n** New data is spilled to a new interior node at the same height when\n** the current node exceeds INTERIOR_MAX bytes (default 2048).\n** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing\n** interior nodes and making the tree too skinny.  The interior nodes\n** at a given height are naturally tracked by interior nodes at\n** height+1, and so on.\n**\n**\n**** Segment directory ****\n** The segment directory in table %_segdir stores meta-information for\n** merging and deleting segments, and also the root node of the\n** segment's tree.\n**\n** The root node is the top node of the segment's tree after encoding\n** the entire segment, restricted to ROOT_MAX bytes (default 1024).\n** This could be either a leaf node or an interior node.  If the top\n** node requires more than ROOT_MAX bytes, it is flushed to %_segments\n** and a new root interior node is generated (which should always fit\n** within ROOT_MAX because it only needs space for 2 varints, the\n** height and the blockid of the previous root).\n**\n** The meta-information in the segment directory is:\n**   level               - segment level (see below)\n**   idx                 - index within level\n**                       - (level,idx uniquely identify a segment)\n**   start_block         - first leaf node\n**   leaves_end_block    - last leaf node\n**   end_block           - last block (including interior nodes)\n**   root                - contents of root node\n**\n** If the root node is a leaf node, then start_block,\n** leaves_end_block, and end_block are all 0.\n**\n**\n**** Segment merging ****\n** To amortize update costs, segments are grouped into levels and\n** merged in batches.  Each increase in level represents exponentially\n** more documents.\n**\n** New documents (actually, document updates) are tokenized and\n** written individually (using LeafWriter) to a level 0 segment, with\n** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all\n** level 0 segments are merged into a single level 1 segment.  Level 1\n** is populated like level 0, and eventually MERGE_COUNT level 1\n** segments are merged to a single level 2 segment (representing\n** MERGE_COUNT^2 updates), and so on.\n**\n** A segment merge traverses all segments at a given level in\n** parallel, performing a straightforward sorted merge.  Since segment\n** leaf nodes are written in to the %_segments table in order, this\n** merge traverses the underlying sqlite disk structures efficiently.\n** After the merge, all segment blocks from the merged level are\n** deleted.\n**\n** MERGE_COUNT controls how often we merge segments.  16 seems to be\n** somewhat of a sweet spot for insertion performance.  32 and 64 show\n** very similar performance numbers to 16 on insertion, though they're\n** a tiny bit slower (perhaps due to more overhead in merge-time\n** sorting).  8 is about 20% slower than 16, 4 about 50% slower than\n** 16, 2 about 66% slower than 16.\n**\n** At query time, high MERGE_COUNT increases the number of segments\n** which need to be scanned and merged.  For instance, with 100k docs\n** inserted:\n**\n**    MERGE_COUNT   segments\n**       16           25\n**        8           12\n**        4           10\n**        2            6\n**\n** This appears to have only a moderate impact on queries for very\n** frequent terms (which are somewhat dominated by segment merge\n** costs), and infrequent and non-existent terms still seem to be fast\n** even with many segments.\n**\n** TODO(shess) That said, it would be nice to have a better query-side\n** argument for MERGE_COUNT of 16.  Also, it is possible/likely that\n** optimizations to things like doclist merging will swing the sweet\n** spot around.\n**\n**\n**\n**** Handling of deletions and updates ****\n** Since we're using a segmented structure, with no docid-oriented\n** index into the term index, we clearly cannot simply update the term\n** index when a document is deleted or updated.  For deletions, we\n** write an empty doclist (varint(docid) varint(POS_END)), for updates\n** we simply write the new doclist.  Segment merges overwrite older\n** data for a particular docid with newer data, so deletes or updates\n** will eventually overtake the earlier data and knock it out.  The\n** query logic likewise merges doclists so that newer data knocks out\n** older data.\n*/\n\n/************** Include fts3Int.h in the middle of fts3.c ********************/\n/************** Begin file fts3Int.h *****************************************/\n/*\n** 2009 Nov 12\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n*/\n#ifndef _FTSINT_H\n#define _FTSINT_H\n\n#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) \n# define NDEBUG 1\n#endif\n\n/* FTS3/FTS4 require virtual tables */\n#ifdef SQLITE_OMIT_VIRTUALTABLE\n# undef SQLITE_ENABLE_FTS3\n# undef SQLITE_ENABLE_FTS4\n#endif\n\n/*\n** FTS4 is really an extension for FTS3.  It is enabled using the\n** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all\n** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.\n*/\n#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)\n# define SQLITE_ENABLE_FTS3\n#endif\n\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* If not building as part of the core, include sqlite3ext.h. */\n#ifndef SQLITE_CORE\n/* # include \"sqlite3ext.h\"  */\nSQLITE_EXTENSION_INIT3\n#endif\n\n/* #include \"sqlite3.h\" */\n/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/\n/************** Begin file fts3_tokenizer.h **********************************/\n/*\n** 2006 July 10\n**\n** The author disclaims copyright to this source code.\n**\n*************************************************************************\n** Defines the interface to tokenizers used by fulltext-search.  There\n** are three basic components:\n**\n** sqlite3_tokenizer_module is a singleton defining the tokenizer\n** interface functions.  This is essentially the class structure for\n** tokenizers.\n**\n** sqlite3_tokenizer is used to define a particular tokenizer, perhaps\n** including customization information defined at creation time.\n**\n** sqlite3_tokenizer_cursor is generated by a tokenizer to generate\n** tokens from a particular input.\n*/\n#ifndef _FTS3_TOKENIZER_H_\n#define _FTS3_TOKENIZER_H_\n\n/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.\n** If tokenizers are to be allowed to call sqlite3_*() functions, then\n** we will need a way to register the API consistently.\n*/\n/* #include \"sqlite3.h\" */\n\n/*\n** Structures used by the tokenizer interface. When a new tokenizer\n** implementation is registered, the caller provides a pointer to\n** an sqlite3_tokenizer_module containing pointers to the callback\n** functions that make up an implementation.\n**\n** When an fts3 table is created, it passes any arguments passed to\n** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the\n** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer\n** implementation. The xCreate() function in turn returns an \n** sqlite3_tokenizer structure representing the specific tokenizer to\n** be used for the fts3 table (customized by the tokenizer clause arguments).\n**\n** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()\n** method is called. It returns an sqlite3_tokenizer_cursor object\n** that may be used to tokenize a specific input buffer based on\n** the tokenization rules supplied by a specific sqlite3_tokenizer\n** object.\n*/\ntypedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;\ntypedef struct sqlite3_tokenizer sqlite3_tokenizer;\ntypedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;\n\nstruct sqlite3_tokenizer_module {\n\n  /*\n  ** Structure version. Should always be set to 0 or 1.\n  */\n  int iVersion;\n\n  /*\n  ** Create a new tokenizer. The values in the argv[] array are the\n  ** arguments passed to the \"tokenizer\" clause of the CREATE VIRTUAL\n  ** TABLE statement that created the fts3 table. For example, if\n  ** the following SQL is executed:\n  **\n  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)\n  **\n  ** then argc is set to 2, and the argv[] array contains pointers\n  ** to the strings \"arg1\" and \"arg2\".\n  **\n  ** This method should return either SQLITE_OK (0), or an SQLite error \n  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set\n  ** to point at the newly created tokenizer structure. The generic\n  ** sqlite3_tokenizer.pModule variable should not be initialized by\n  ** this callback. The caller will do so.\n  */\n  int (*xCreate)(\n    int argc,                           /* Size of argv array */\n    const char *const*argv,             /* Tokenizer argument strings */\n    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */\n  );\n\n  /*\n  ** Destroy an existing tokenizer. The fts3 module calls this method\n  ** exactly once for each successful call to xCreate().\n  */\n  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);\n\n  /*\n  ** Create a tokenizer cursor to tokenize an input buffer. The caller\n  ** is responsible for ensuring that the input buffer remains valid\n  ** until the cursor is closed (using the xClose() method). \n  */\n  int (*xOpen)(\n    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */\n    const char *pInput, int nBytes,      /* Input buffer */\n    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */\n  );\n\n  /*\n  ** Destroy an existing tokenizer cursor. The fts3 module calls this \n  ** method exactly once for each successful call to xOpen().\n  */\n  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);\n\n  /*\n  ** Retrieve the next token from the tokenizer cursor pCursor. This\n  ** method should either return SQLITE_OK and set the values of the\n  ** \"OUT\" variables identified below, or SQLITE_DONE to indicate that\n  ** the end of the buffer has been reached, or an SQLite error code.\n  **\n  ** *ppToken should be set to point at a buffer containing the \n  ** normalized version of the token (i.e. after any case-folding and/or\n  ** stemming has been performed). *pnBytes should be set to the length\n  ** of this buffer in bytes. The input text that generated the token is\n  ** identified by the byte offsets returned in *piStartOffset and\n  ** *piEndOffset. *piStartOffset should be set to the index of the first\n  ** byte of the token in the input buffer. *piEndOffset should be set\n  ** to the index of the first byte just past the end of the token in\n  ** the input buffer.\n  **\n  ** The buffer *ppToken is set to point at is managed by the tokenizer\n  ** implementation. It is only required to be valid until the next call\n  ** to xNext() or xClose(). \n  */\n  /* TODO(shess) current implementation requires pInput to be\n  ** nul-terminated.  This should either be fixed, or pInput/nBytes\n  ** should be converted to zInput.\n  */\n  int (*xNext)(\n    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */\n    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */\n    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */\n    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */\n    int *piPosition      /* OUT: Number of tokens returned before this one */\n  );\n\n  /***********************************************************************\n  ** Methods below this point are only available if iVersion>=1.\n  */\n\n  /* \n  ** Configure the language id of a tokenizer cursor.\n  */\n  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);\n};\n\nstruct sqlite3_tokenizer {\n  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */\n  /* Tokenizer implementations will typically add additional fields */\n};\n\nstruct sqlite3_tokenizer_cursor {\n  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */\n  /* Tokenizer implementations will typically add additional fields */\n};\n\nint fts3_global_term_cnt(int iTerm, int iCol);\nint fts3_term_cnt(int iTerm, int iCol);\n\n\n#endif /* _FTS3_TOKENIZER_H_ */\n\n/************** End of fts3_tokenizer.h **************************************/\n/************** Continuing where we left off in fts3Int.h ********************/\n/************** Include fts3_hash.h in the middle of fts3Int.h ***************/\n/************** Begin file fts3_hash.h ***************************************/\n/*\n** 2001 September 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This is the header file for the generic hash-table implementation\n** used in SQLite.  We've modified it slightly to serve as a standalone\n** hash table implementation for the full-text indexing module.\n**\n*/\n#ifndef _FTS3_HASH_H_\n#define _FTS3_HASH_H_\n\n/* Forward declarations of structures. */\ntypedef struct Fts3Hash Fts3Hash;\ntypedef struct Fts3HashElem Fts3HashElem;\n\n/* A complete hash table is an instance of the following structure.\n** The internals of this structure are intended to be opaque -- client\n** code should not attempt to access or modify the fields of this structure\n** directly.  Change this structure only by using the routines below.\n** However, many of the \"procedures\" and \"functions\" for modifying and\n** accessing this structure are really macros, so we can't really make\n** this structure opaque.\n*/\nstruct Fts3Hash {\n  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */\n  char copyKey;           /* True if copy of key made on insert */\n  int count;              /* Number of entries in this table */\n  Fts3HashElem *first;    /* The first element of the array */\n  int htsize;             /* Number of buckets in the hash table */\n  struct _fts3ht {        /* the hash table */\n    int count;               /* Number of entries with this hash */\n    Fts3HashElem *chain;     /* Pointer to first entry with this hash */\n  } *ht;\n};\n\n/* Each element in the hash table is an instance of the following \n** structure.  All elements are stored on a single doubly-linked list.\n**\n** Again, this structure is intended to be opaque, but it can't really\n** be opaque because it is used by macros.\n*/\nstruct Fts3HashElem {\n  Fts3HashElem *next, *prev; /* Next and previous elements in the table */\n  void *data;                /* Data associated with this element */\n  void *pKey; int nKey;      /* Key associated with this element */\n};\n\n/*\n** There are 2 different modes of operation for a hash table:\n**\n**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long\n**                           (including the null-terminator, if any).  Case\n**                           is respected in comparisons.\n**\n**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. \n**                           memcmp() is used to compare keys.\n**\n** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  \n*/\n#define FTS3_HASH_STRING    1\n#define FTS3_HASH_BINARY    2\n\n/*\n** Access routines.  To delete, insert a NULL pointer.\n*/\nSQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);\nSQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);\nSQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);\nSQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);\nSQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);\n\n/*\n** Shorthand for the functions above\n*/\n#define fts3HashInit     sqlite3Fts3HashInit\n#define fts3HashInsert   sqlite3Fts3HashInsert\n#define fts3HashFind     sqlite3Fts3HashFind\n#define fts3HashClear    sqlite3Fts3HashClear\n#define fts3HashFindElem sqlite3Fts3HashFindElem\n\n/*\n** Macros for looping over all elements of a hash table.  The idiom is\n** like this:\n**\n**   Fts3Hash h;\n**   Fts3HashElem *p;\n**   ...\n**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){\n**     SomeStructure *pData = fts3HashData(p);\n**     // do something with pData\n**   }\n*/\n#define fts3HashFirst(H)  ((H)->first)\n#define fts3HashNext(E)   ((E)->next)\n#define fts3HashData(E)   ((E)->data)\n#define fts3HashKey(E)    ((E)->pKey)\n#define fts3HashKeysize(E) ((E)->nKey)\n\n/*\n** Number of entries in a hash table\n*/\n#define fts3HashCount(H)  ((H)->count)\n\n#endif /* _FTS3_HASH_H_ */\n\n/************** End of fts3_hash.h *******************************************/\n/************** Continuing where we left off in fts3Int.h ********************/\n\n/*\n** This constant determines the maximum depth of an FTS expression tree\n** that the library will create and use. FTS uses recursion to perform \n** various operations on the query tree, so the disadvantage of a large\n** limit is that it may allow very large queries to use large amounts\n** of stack space (perhaps causing a stack overflow).\n*/\n#ifndef SQLITE_FTS3_MAX_EXPR_DEPTH\n# define SQLITE_FTS3_MAX_EXPR_DEPTH 12\n#endif\n\n\n/*\n** This constant controls how often segments are merged. Once there are\n** FTS3_MERGE_COUNT segments of level N, they are merged into a single\n** segment of level N+1.\n*/\n#define FTS3_MERGE_COUNT 16\n\n/*\n** This is the maximum amount of data (in bytes) to store in the \n** Fts3Table.pendingTerms hash table. Normally, the hash table is\n** populated as documents are inserted/updated/deleted in a transaction\n** and used to create a new segment when the transaction is committed.\n** However if this limit is reached midway through a transaction, a new \n** segment is created and the hash table cleared immediately.\n*/\n#define FTS3_MAX_PENDING_DATA (1*1024*1024)\n\n/*\n** Macro to return the number of elements in an array. SQLite has a\n** similar macro called ArraySize(). Use a different name to avoid\n** a collision when building an amalgamation with built-in FTS3.\n*/\n#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))\n\n\n#ifndef MIN\n# define MIN(x,y) ((x)<(y)?(x):(y))\n#endif\n#ifndef MAX\n# define MAX(x,y) ((x)>(y)?(x):(y))\n#endif\n\n/*\n** Maximum length of a varint encoded integer. The varint format is different\n** from that used by SQLite, so the maximum length is 10, not 9.\n*/\n#define FTS3_VARINT_MAX 10\n\n#define FTS3_BUFFER_PADDING 8\n\n/*\n** FTS4 virtual tables may maintain multiple indexes - one index of all terms\n** in the document set and zero or more prefix indexes. All indexes are stored\n** as one or more b+-trees in the %_segments and %_segdir tables. \n**\n** It is possible to determine which index a b+-tree belongs to based on the\n** value stored in the \"%_segdir.level\" column. Given this value L, the index\n** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with\n** level values between 0 and 1023 (inclusive) belong to index 0, all levels\n** between 1024 and 2047 to index 1, and so on.\n**\n** It is considered impossible for an index to use more than 1024 levels. In \n** theory though this may happen, but only after at least \n** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.\n*/\n#define FTS3_SEGDIR_MAXLEVEL      1024\n#define FTS3_SEGDIR_MAXLEVEL_STR \"1024\"\n\n/*\n** The testcase() macro is only used by the amalgamation.  If undefined,\n** make it a no-op.\n*/\n#ifndef testcase\n# define testcase(X)\n#endif\n\n/*\n** Terminator values for position-lists and column-lists.\n*/\n#define POS_COLUMN  (1)     /* Column-list terminator */\n#define POS_END     (0)     /* Position-list terminator */ \n\n/*\n** The assert_fts3_nc() macro is similar to the assert() macro, except that it\n** is used for assert() conditions that are true only if it can be \n** guranteed that the database is not corrupt.\n*/\n#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)\nSQLITE_API extern int sqlite3_fts3_may_be_corrupt;\n# define assert_fts3_nc(x) assert(sqlite3_fts3_may_be_corrupt || (x))\n#else\n# define assert_fts3_nc(x) assert(x)\n#endif\n\n/*\n** This section provides definitions to allow the\n** FTS3 extension to be compiled outside of the \n** amalgamation.\n*/\n#ifndef SQLITE_AMALGAMATION\n/*\n** Macros indicating that conditional expressions are always true or\n** false.\n*/\n#ifdef SQLITE_COVERAGE_TEST\n# define ALWAYS(x) (1)\n# define NEVER(X)  (0)\n#elif defined(SQLITE_DEBUG)\n# define ALWAYS(x) sqlite3Fts3Always((x)!=0)\n# define NEVER(x) sqlite3Fts3Never((x)!=0)\nSQLITE_PRIVATE int sqlite3Fts3Always(int b);\nSQLITE_PRIVATE int sqlite3Fts3Never(int b);\n#else\n# define ALWAYS(x) (x)\n# define NEVER(x)  (x)\n#endif\n\n/*\n** Internal types used by SQLite.\n*/\ntypedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */\ntypedef short int i16;            /* 2-byte (or larger) signed integer */\ntypedef unsigned int u32;         /* 4-byte unsigned integer */\ntypedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */\ntypedef sqlite3_int64 i64;        /* 8-byte signed integer */\n\n/*\n** Macro used to suppress compiler warnings for unused parameters.\n*/\n#define UNUSED_PARAMETER(x) (void)(x)\n\n/*\n** Activate assert() only if SQLITE_TEST is enabled.\n*/\n#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) \n# define NDEBUG 1\n#endif\n\n/*\n** The TESTONLY macro is used to enclose variable declarations or\n** other bits of code that are needed to support the arguments\n** within testcase() and assert() macros.\n*/\n#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)\n# define TESTONLY(X)  X\n#else\n# define TESTONLY(X)\n#endif\n\n#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))\n#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)\n\n#endif /* SQLITE_AMALGAMATION */\n\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE int sqlite3Fts3Corrupt(void);\n# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()\n#else\n# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB\n#endif\n\ntypedef struct Fts3Table Fts3Table;\ntypedef struct Fts3Cursor Fts3Cursor;\ntypedef struct Fts3Expr Fts3Expr;\ntypedef struct Fts3Phrase Fts3Phrase;\ntypedef struct Fts3PhraseToken Fts3PhraseToken;\n\ntypedef struct Fts3Doclist Fts3Doclist;\ntypedef struct Fts3SegFilter Fts3SegFilter;\ntypedef struct Fts3DeferredToken Fts3DeferredToken;\ntypedef struct Fts3SegReader Fts3SegReader;\ntypedef struct Fts3MultiSegReader Fts3MultiSegReader;\n\ntypedef struct MatchinfoBuffer MatchinfoBuffer;\n\n/*\n** A connection to a fulltext index is an instance of the following\n** structure. The xCreate and xConnect methods create an instance\n** of this structure and xDestroy and xDisconnect free that instance.\n** All other methods receive a pointer to the structure as one of their\n** arguments.\n*/\nstruct Fts3Table {\n  sqlite3_vtab base;              /* Base class used by SQLite core */\n  sqlite3 *db;                    /* The database connection */\n  const char *zDb;                /* logical database name */\n  const char *zName;              /* virtual table name */\n  int nColumn;                    /* number of named columns in virtual table */\n  char **azColumn;                /* column names.  malloced */\n  u8 *abNotindexed;               /* True for 'notindexed' columns */\n  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */\n  char *zContentTbl;              /* content=xxx option, or NULL */\n  char *zLanguageid;              /* languageid=xxx option, or NULL */\n  int nAutoincrmerge;             /* Value configured by 'automerge' */\n  u32 nLeafAdd;                   /* Number of leaf blocks added this trans */\n  int bLock;                      /* Used to prevent recursive content= tbls */\n\n  /* Precompiled statements used by the implementation. Each of these \n  ** statements is run and reset within a single virtual table API call. \n  */\n  sqlite3_stmt *aStmt[40];\n  sqlite3_stmt *pSeekStmt;        /* Cache for fts3CursorSeekStmt() */\n\n  char *zReadExprlist;\n  char *zWriteExprlist;\n\n  int nNodeSize;                  /* Soft limit for node size */\n  u8 bFts4;                       /* True for FTS4, false for FTS3 */\n  u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */\n  u8 bHasDocsize;                 /* True if %_docsize table exists */\n  u8 bDescIdx;                    /* True if doclists are in reverse order */\n  u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */\n  int nPgsz;                      /* Page size for host database */\n  char *zSegmentsTbl;             /* Name of %_segments table */\n  sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */\n\n  /* \n  ** The following array of hash tables is used to buffer pending index \n  ** updates during transactions. All pending updates buffered at any one\n  ** time must share a common language-id (see the FTS4 langid= feature).\n  ** The current language id is stored in variable iPrevLangid.\n  **\n  ** A single FTS4 table may have multiple full-text indexes. For each index\n  ** there is an entry in the aIndex[] array. Index 0 is an index of all the\n  ** terms that appear in the document set. Each subsequent index in aIndex[]\n  ** is an index of prefixes of a specific length.\n  **\n  ** Variable nPendingData contains an estimate the memory consumed by the \n  ** pending data structures, including hash table overhead, but not including\n  ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash\n  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most \n  ** recently inserted record.\n  */\n  int nIndex;                     /* Size of aIndex[] */\n  struct Fts3Index {\n    int nPrefix;                  /* Prefix length (0 for main terms index) */\n    Fts3Hash hPending;            /* Pending terms table for this index */\n  } *aIndex;\n  int nMaxPendingData;            /* Max pending data before flush to disk */\n  int nPendingData;               /* Current bytes of pending data */\n  sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */\n  int iPrevLangid;                /* Langid of recently inserted document */\n  int bPrevDelete;                /* True if last operation was a delete */\n\n#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)\n  /* State variables used for validating that the transaction control\n  ** methods of the virtual table are called at appropriate times.  These\n  ** values do not contribute to FTS functionality; they are used for\n  ** verifying the operation of the SQLite core.\n  */\n  int inTransaction;     /* True after xBegin but before xCommit/xRollback */\n  int mxSavepoint;       /* Largest valid xSavepoint integer */\n#endif\n\n#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)\n  /* True to disable the incremental doclist optimization. This is controled\n  ** by special insert command 'test-no-incr-doclist'.  */\n  int bNoIncrDoclist;\n\n  /* Number of segments in a level */\n  int nMergeCount;\n#endif\n};\n\n/* Macro to find the number of segments to merge */\n#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)\n# define MergeCount(P) ((P)->nMergeCount)\n#else\n# define MergeCount(P) FTS3_MERGE_COUNT\n#endif\n\n/*\n** When the core wants to read from the virtual table, it creates a\n** virtual table cursor (an instance of the following structure) using\n** the xOpen method. Cursors are destroyed using the xClose method.\n*/\nstruct Fts3Cursor {\n  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */\n  i16 eSearch;                    /* Search strategy (see below) */\n  u8 isEof;                       /* True if at End Of Results */\n  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */\n  u8 bSeekStmt;                   /* True if pStmt is a seek */\n  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */\n  Fts3Expr *pExpr;                /* Parsed MATCH query string */\n  int iLangid;                    /* Language being queried for */\n  int nPhrase;                    /* Number of matchable phrases in query */\n  Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */\n  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */\n  char *pNextId;                  /* Pointer into the body of aDoclist */\n  char *aDoclist;                 /* List of docids for full-text queries */\n  int nDoclist;                   /* Size of buffer at aDoclist */\n  u8 bDesc;                       /* True to sort in descending order */\n  int eEvalmode;                  /* An FTS3_EVAL_XX constant */\n  int nRowAvg;                    /* Average size of database rows, in pages */\n  sqlite3_int64 nDoc;             /* Documents in table */\n  i64 iMinDocid;                  /* Minimum docid to return */\n  i64 iMaxDocid;                  /* Maximum docid to return */\n  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */\n  MatchinfoBuffer *pMIBuffer;     /* Buffer for matchinfo data */\n};\n\n#define FTS3_EVAL_FILTER    0\n#define FTS3_EVAL_NEXT      1\n#define FTS3_EVAL_MATCHINFO 2\n\n/*\n** The Fts3Cursor.eSearch member is always set to one of the following.\n** Actualy, Fts3Cursor.eSearch can be greater than or equal to\n** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index\n** of the column to be searched.  For example, in\n**\n**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);\n**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';\n** \n** Because the LHS of the MATCH operator is 2nd column \"b\",\n** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,\n** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were \"ex1\" \n** indicating that all columns should be searched,\n** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.\n*/\n#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */\n#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */\n#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */\n\n/*\n** The lower 16-bits of the sqlite3_index_info.idxNum value set by\n** the xBestIndex() method contains the Fts3Cursor.eSearch value described\n** above. The upper 16-bits contain a combination of the following\n** bits, used to describe extra constraints on full-text searches.\n*/\n#define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */\n#define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */\n#define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */\n\nstruct Fts3Doclist {\n  char *aAll;                    /* Array containing doclist (or NULL) */\n  int nAll;                      /* Size of a[] in bytes */\n  char *pNextDocid;              /* Pointer to next docid */\n\n  sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */\n  int bFreeList;                 /* True if pList should be sqlite3_free()d */\n  char *pList;                   /* Pointer to position list following iDocid */\n  int nList;                     /* Length of position list */\n};\n\n/*\n** A \"phrase\" is a sequence of one or more tokens that must match in\n** sequence.  A single token is the base case and the most common case.\n** For a sequence of tokens contained in double-quotes (i.e. \"one two three\")\n** nToken will be the number of tokens in the string.\n*/\nstruct Fts3PhraseToken {\n  char *z;                        /* Text of the token */\n  int n;                          /* Number of bytes in buffer z */\n  int isPrefix;                   /* True if token ends with a \"*\" character */\n  int bFirst;                     /* True if token must appear at position 0 */\n\n  /* Variables above this point are populated when the expression is\n  ** parsed (by code in fts3_expr.c). Below this point the variables are\n  ** used when evaluating the expression. */\n  Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */\n  Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */\n};\n\nstruct Fts3Phrase {\n  /* Cache of doclist for this phrase. */\n  Fts3Doclist doclist;\n  int bIncr;                 /* True if doclist is loaded incrementally */\n  int iDoclistToken;\n\n  /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an\n  ** OR condition.  */\n  char *pOrPoslist;\n  i64 iOrDocid;\n\n  /* Variables below this point are populated by fts3_expr.c when parsing \n  ** a MATCH expression. Everything above is part of the evaluation phase. \n  */\n  int nToken;                /* Number of tokens in the phrase */\n  int iColumn;               /* Index of column this phrase must match */\n  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */\n};\n\n/*\n** A tree of these objects forms the RHS of a MATCH operator.\n**\n** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist \n** points to a malloced buffer, size nDoclist bytes, containing the results \n** of this phrase query in FTS3 doclist format. As usual, the initial \n** \"Length\" field found in doclists stored on disk is omitted from this \n** buffer.\n**\n** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global\n** matchinfo data. If it is not NULL, it points to an array of size nCol*3,\n** where nCol is the number of columns in the queried FTS table. The array\n** is populated as follows:\n**\n**   aMI[iCol*3 + 0] = Undefined\n**   aMI[iCol*3 + 1] = Number of occurrences\n**   aMI[iCol*3 + 2] = Number of rows containing at least one instance\n**\n** The aMI array is allocated using sqlite3_malloc(). It should be freed \n** when the expression node is.\n*/\nstruct Fts3Expr {\n  int eType;                 /* One of the FTSQUERY_XXX values defined below */\n  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */\n  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */\n  Fts3Expr *pLeft;           /* Left operand */\n  Fts3Expr *pRight;          /* Right operand */\n  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */\n\n  /* The following are used by the fts3_eval.c module. */\n  sqlite3_int64 iDocid;      /* Current docid */\n  u8 bEof;                   /* True this expression is at EOF already */\n  u8 bStart;                 /* True if iDocid is valid */\n  u8 bDeferred;              /* True if this expression is entirely deferred */\n\n  /* The following are used by the fts3_snippet.c module. */\n  int iPhrase;               /* Index of this phrase in matchinfo() results */\n  u32 *aMI;                  /* See above */\n};\n\n/*\n** Candidate values for Fts3Query.eType. Note that the order of the first\n** four values is in order of precedence when parsing expressions. For \n** example, the following:\n**\n**   \"a OR b AND c NOT d NEAR e\"\n**\n** is equivalent to:\n**\n**   \"a OR (b AND (c NOT (d NEAR e)))\"\n*/\n#define FTSQUERY_NEAR   1\n#define FTSQUERY_NOT    2\n#define FTSQUERY_AND    3\n#define FTSQUERY_OR     4\n#define FTSQUERY_PHRASE 5\n\n\n/* fts3_write.c */\nSQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);\nSQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);\nSQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);\nSQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);\nSQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,\n  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);\nSQLITE_PRIVATE int sqlite3Fts3SegReaderPending(\n  Fts3Table*,int,const char*,int,int,Fts3SegReader**);\nSQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);\nSQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);\nSQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);\n\nSQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);\nSQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);\n\n#ifndef SQLITE_DISABLE_FTS4_DEFERRED\nSQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);\nSQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);\nSQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);\nSQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);\nSQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);\n#else\n# define sqlite3Fts3FreeDeferredTokens(x)\n# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK\n# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK\n# define sqlite3Fts3FreeDeferredDoclists(x)\n# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK\n#endif\n\nSQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);\nSQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);\n\n/* Special values interpreted by sqlite3SegReaderCursor() */\n#define FTS3_SEGCURSOR_PENDING        -1\n#define FTS3_SEGCURSOR_ALL            -2\n\nSQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);\nSQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);\nSQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);\n\nSQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, \n    int, int, int, const char *, int, int, int, Fts3MultiSegReader *);\n\n/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */\n#define FTS3_SEGMENT_REQUIRE_POS   0x00000001\n#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002\n#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004\n#define FTS3_SEGMENT_PREFIX        0x00000008\n#define FTS3_SEGMENT_SCAN          0x00000010\n#define FTS3_SEGMENT_FIRST         0x00000020\n\n/* Type passed as 4th argument to SegmentReaderIterate() */\nstruct Fts3SegFilter {\n  const char *zTerm;\n  int nTerm;\n  int iCol;\n  int flags;\n};\n\nstruct Fts3MultiSegReader {\n  /* Used internally by sqlite3Fts3SegReaderXXX() calls */\n  Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */\n  int nSegment;                   /* Size of apSegment array */\n  int nAdvance;                   /* How many seg-readers to advance */\n  Fts3SegFilter *pFilter;         /* Pointer to filter object */\n  char *aBuffer;                  /* Buffer to merge doclists in */\n  int nBuffer;                    /* Allocated size of aBuffer[] in bytes */\n\n  int iColFilter;                 /* If >=0, filter for this column */\n  int bRestart;\n\n  /* Used by fts3.c only. */\n  int nCost;                      /* Cost of running iterator */\n  int bLookup;                    /* True if a lookup of a single entry. */\n\n  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */\n  char *zTerm;                    /* Pointer to term buffer */\n  int nTerm;                      /* Size of zTerm in bytes */\n  char *aDoclist;                 /* Pointer to doclist buffer */\n  int nDoclist;                   /* Size of aDoclist[] in bytes */\n};\n\nSQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);\n\n#define fts3GetVarint32(p, piVal) (                                           \\\n  (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \\\n)\n\n/* fts3.c */\nSQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);\nSQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);\nSQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);\nSQLITE_PRIVATE int sqlite3Fts3GetVarintU(const char *, sqlite_uint64 *);\nSQLITE_PRIVATE int sqlite3Fts3GetVarintBounded(const char*,const char*,sqlite3_int64*);\nSQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);\nSQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);\nSQLITE_PRIVATE void sqlite3Fts3Dequote(char *);\nSQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);\nSQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);\nSQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);\nSQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);\nSQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);\nSQLITE_PRIVATE int sqlite3Fts3ReadInt(const char *z, int *pnOut);\n\n/* fts3_tokenizer.c */\nSQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);\nSQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);\nSQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, \n    sqlite3_tokenizer **, char **\n);\nSQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);\n\n/* fts3_snippet.c */\nSQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);\nSQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,\n  const char *, const char *, int, int\n);\nSQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);\nSQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);\n\n/* fts3_expr.c */\nSQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,\n  char **, int, int, int, const char *, int, Fts3Expr **, char **\n);\nSQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);\n#ifdef SQLITE_TEST\nSQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash*);\nSQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);\n#endif\n\nSQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,\n  sqlite3_tokenizer_cursor **\n);\n\n/* fts3_aux.c */\nSQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);\n\nSQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);\n\nSQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(\n    Fts3Table*, Fts3MultiSegReader*, int, const char*, int);\nSQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(\n    Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);\nSQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); \nSQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);\nSQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);\n\n/* fts3_tokenize_vtab.c */\nSQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);\n\n/* fts3_unicode2.c (functions generated by parsing unicode text files) */\n#ifndef SQLITE_DISABLE_FTS3_UNICODE\nSQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);\nSQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);\nSQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);\n#endif\n\n#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */\n#endif /* _FTSINT_H */\n\n/************** End of fts3Int.h *********************************************/\n/************** Continuing where we left off in fts3.c ***********************/\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)\n# define SQLITE_CORE 1\n#endif\n\n/* #include <assert.h> */\n/* #include <stdlib.h> */\n/* #include <stddef.h> */\n/* #include <stdio.h> */\n/* #include <string.h> */\n/* #include <stdarg.h> */\n\n/* #include \"fts3.h\" */\n#ifndef SQLITE_CORE \n/* # include \"sqlite3ext.h\" */\n  SQLITE_EXTENSION_INIT1\n#endif\n\nstatic int fts3EvalNext(Fts3Cursor *pCsr);\nstatic int fts3EvalStart(Fts3Cursor *pCsr);\nstatic int fts3TermSegReaderCursor(\n    Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);\n\n#ifndef SQLITE_AMALGAMATION\n# if defined(SQLITE_DEBUG)\nSQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }\nSQLITE_PRIVATE int sqlite3Fts3Never(int b)  { assert( !b ); return b; }\n# endif\n#endif\n\n/*\n** This variable is set to false when running tests for which the on disk\n** structures should not be corrupt. Otherwise, true. If it is false, extra\n** assert() conditions in the fts3 code are activated - conditions that are\n** only true if it is guaranteed that the fts3 database is not corrupt.\n*/\nSQLITE_API int sqlite3_fts3_may_be_corrupt = 1;\n\n/* \n** Write a 64-bit variable-length integer to memory starting at p[0].\n** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.\n** The number of bytes written is returned.\n*/\nSQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){\n  unsigned char *q = (unsigned char *) p;\n  sqlite_uint64 vu = v;\n  do{\n    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);\n    vu >>= 7;\n  }while( vu!=0 );\n  q[-1] &= 0x7f;  /* turn off high bit in final byte */\n  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );\n  return (int) (q - (unsigned char *)p);\n}\n\n#define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \\\n  v = (v & mask1) | ( (*(const unsigned char*)(ptr++)) << shift );  \\\n  if( (v & mask2)==0 ){ var = v; return ret; }\n#define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \\\n  v = (*ptr++);                                               \\\n  if( (v & mask2)==0 ){ var = v; return ret; }\n\nSQLITE_PRIVATE int sqlite3Fts3GetVarintU(const char *pBuf, sqlite_uint64 *v){\n  const unsigned char *p = (const unsigned char*)pBuf;\n  const unsigned char *pStart = p;\n  u32 a;\n  u64 b;\n  int shift;\n\n  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);\n  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);\n  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);\n  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);\n  b = (a & 0x0FFFFFFF );\n\n  for(shift=28; shift<=63; shift+=7){\n    u64 c = *p++;\n    b += (c&0x7F) << shift;\n    if( (c & 0x80)==0 ) break;\n  }\n  *v = b;\n  return (int)(p - pStart);\n}\n\n/* \n** Read a 64-bit variable-length integer from memory starting at p[0].\n** Return the number of bytes read, or 0 on error.\n** The value is stored in *v.\n*/\nSQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){\n  return sqlite3Fts3GetVarintU(pBuf, (sqlite3_uint64*)v);\n}\n\n/* \n** Read a 64-bit variable-length integer from memory starting at p[0] and\n** not extending past pEnd[-1].\n** Return the number of bytes read, or 0 on error.\n** The value is stored in *v.\n*/\nSQLITE_PRIVATE int sqlite3Fts3GetVarintBounded(\n  const char *pBuf,\n  const char *pEnd,\n  sqlite_int64 *v\n){\n  const unsigned char *p = (const unsigned char*)pBuf;\n  const unsigned char *pStart = p;\n  const unsigned char *pX = (const unsigned char*)pEnd;\n  u64 b = 0;\n  int shift;\n  for(shift=0; shift<=63; shift+=7){\n    u64 c = p<pX ? *p : 0;\n    p++;\n    b += (c&0x7F) << shift;\n    if( (c & 0x80)==0 ) break;\n  }\n  *v = b;\n  return (int)(p - pStart);\n}\n\n/*\n** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to \n** a non-negative 32-bit integer before it is returned.\n*/\nSQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){\n  const unsigned char *ptr = (const unsigned char*)p;\n  u32 a;\n\n#ifndef fts3GetVarint32\n  GETVARINT_INIT(a, ptr, 0,  0x00,     0x80, *pi, 1);\n#else\n  a = (*ptr++);\n  assert( a & 0x80 );\n#endif\n\n  GETVARINT_STEP(a, ptr, 7,  0x7F,     0x4000, *pi, 2);\n  GETVARINT_STEP(a, ptr, 14, 0x3FFF,   0x200000, *pi, 3);\n  GETVARINT_STEP(a, ptr, 21, 0x1FFFFF, 0x10000000, *pi, 4);\n  a = (a & 0x0FFFFFFF );\n  *pi = (int)(a | ((u32)(*ptr & 0x07) << 28));\n  assert( 0==(a & 0x80000000) );\n  assert( *pi>=0 );\n  return 5;\n}\n\n/*\n** Return the number of bytes required to encode v as a varint\n*/\nSQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){\n  int i = 0;\n  do{\n    i++;\n    v >>= 7;\n  }while( v!=0 );\n  return i;\n}\n\n/*\n** Convert an SQL-style quoted string into a normal string by removing\n** the quote characters.  The conversion is done in-place.  If the\n** input does not begin with a quote character, then this routine\n** is a no-op.\n**\n** Examples:\n**\n**     \"abc\"   becomes   abc\n**     'xyz'   becomes   xyz\n**     [pqr]   becomes   pqr\n**     `mno`   becomes   mno\n**\n*/\nSQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){\n  char quote;                     /* Quote character (if any ) */\n\n  quote = z[0];\n  if( quote=='[' || quote=='\\'' || quote=='\"' || quote=='`' ){\n    int iIn = 1;                  /* Index of next byte to read from input */\n    int iOut = 0;                 /* Index of next byte to write to output */\n\n    /* If the first byte was a '[', then the close-quote character is a ']' */\n    if( quote=='[' ) quote = ']';  \n\n    while( z[iIn] ){\n      if( z[iIn]==quote ){\n        if( z[iIn+1]!=quote ) break;\n        z[iOut++] = quote;\n        iIn += 2;\n      }else{\n        z[iOut++] = z[iIn++];\n      }\n    }\n    z[iOut] = '\\0';\n  }\n}\n\n/*\n** Read a single varint from the doclist at *pp and advance *pp to point\n** to the first byte past the end of the varint.  Add the value of the varint\n** to *pVal.\n*/\nstatic void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){\n  sqlite3_int64 iVal;\n  *pp += sqlite3Fts3GetVarint(*pp, &iVal);\n  *pVal += iVal;\n}\n\n/*\n** When this function is called, *pp points to the first byte following a\n** varint that is part of a doclist (or position-list, or any other list\n** of varints). This function moves *pp to point to the start of that varint,\n** and sets *pVal by the varint value.\n**\n** Argument pStart points to the first byte of the doclist that the\n** varint is part of.\n*/\nstatic void fts3GetReverseVarint(\n  char **pp, \n  char *pStart, \n  sqlite3_int64 *pVal\n){\n  sqlite3_int64 iVal;\n  char *p;\n\n  /* Pointer p now points at the first byte past the varint we are \n  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is\n  ** clear on character p[-1]. */\n  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);\n  p++;\n  *pp = p;\n\n  sqlite3Fts3GetVarint(p, &iVal);\n  *pVal = iVal;\n}\n\n/*\n** The xDisconnect() virtual table method.\n*/\nstatic int fts3DisconnectMethod(sqlite3_vtab *pVtab){\n  Fts3Table *p = (Fts3Table *)pVtab;\n  int i;\n\n  assert( p->nPendingData==0 );\n  assert( p->pSegments==0 );\n\n  /* Free any prepared statements held */\n  sqlite3_finalize(p->pSeekStmt);\n  for(i=0; i<SizeofArray(p->aStmt); i++){\n    sqlite3_finalize(p->aStmt[i]);\n  }\n  sqlite3_free(p->zSegmentsTbl);\n  sqlite3_free(p->zReadExprlist);\n  sqlite3_free(p->zWriteExprlist);\n  sqlite3_free(p->zContentTbl);\n  sqlite3_free(p->zLanguageid);\n\n  /* Invoke the tokenizer destructor to free the tokenizer. */\n  p->pTokenizer->pModule->xDestroy(p->pTokenizer);\n\n  sqlite3_free(p);\n  return SQLITE_OK;\n}\n\n/*\n** Write an error message into *pzErr\n*/\nSQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){\n  va_list ap;\n  sqlite3_free(*pzErr);\n  va_start(ap, zFormat);\n  *pzErr = sqlite3_vmprintf(zFormat, ap);\n  va_end(ap);\n}\n\n/*\n** Construct one or more SQL statements from the format string given\n** and then evaluate those statements. The success code is written\n** into *pRc.\n**\n** If *pRc is initially non-zero then this routine is a no-op.\n*/\nstatic void fts3DbExec(\n  int *pRc,              /* Success code */\n  sqlite3 *db,           /* Database in which to run SQL */\n  const char *zFormat,   /* Format string for SQL */\n  ...                    /* Arguments to the format string */\n){\n  va_list ap;\n  char *zSql;\n  if( *pRc ) return;\n  va_start(ap, zFormat);\n  zSql = sqlite3_vmprintf(zFormat, ap);\n  va_end(ap);\n  if( zSql==0 ){\n    *pRc = SQLITE_NOMEM;\n  }else{\n    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);\n    sqlite3_free(zSql);\n  }\n}\n\n/*\n** The xDestroy() virtual table method.\n*/\nstatic int fts3DestroyMethod(sqlite3_vtab *pVtab){\n  Fts3Table *p = (Fts3Table *)pVtab;\n  int rc = SQLITE_OK;              /* Return code */\n  const char *zDb = p->zDb;        /* Name of database (e.g. \"main\", \"temp\") */\n  sqlite3 *db = p->db;             /* Database handle */\n\n  /* Drop the shadow tables */\n  fts3DbExec(&rc, db, \n    \"DROP TABLE IF EXISTS %Q.'%q_segments';\"\n    \"DROP TABLE IF EXISTS %Q.'%q_segdir';\"\n    \"DROP TABLE IF EXISTS %Q.'%q_docsize';\"\n    \"DROP TABLE IF EXISTS %Q.'%q_stat';\"\n    \"%s DROP TABLE IF EXISTS %Q.'%q_content';\",\n    zDb, p->zName,\n    zDb, p->zName,\n    zDb, p->zName,\n    zDb, p->zName,\n    (p->zContentTbl ? \"--\" : \"\"), zDb,p->zName\n  );\n\n  /* If everything has worked, invoke fts3DisconnectMethod() to free the\n  ** memory associated with the Fts3Table structure and return SQLITE_OK.\n  ** Otherwise, return an SQLite error code.\n  */\n  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);\n}\n\n\n/*\n** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table\n** passed as the first argument. This is done as part of the xConnect()\n** and xCreate() methods.\n**\n** If *pRc is non-zero when this function is called, it is a no-op. \n** Otherwise, if an error occurs, an SQLite error code is stored in *pRc\n** before returning.\n*/\nstatic void fts3DeclareVtab(int *pRc, Fts3Table *p){\n  if( *pRc==SQLITE_OK ){\n    int i;                        /* Iterator variable */\n    int rc;                       /* Return code */\n    char *zSql;                   /* SQL statement passed to declare_vtab() */\n    char *zCols;                  /* List of user defined columns */\n    const char *zLanguageid;\n\n    zLanguageid = (p->zLanguageid ? p->zLanguageid : \"__langid\");\n    sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);\n\n    /* Create a list of user columns for the virtual table */\n    zCols = sqlite3_mprintf(\"%Q, \", p->azColumn[0]);\n    for(i=1; zCols && i<p->nColumn; i++){\n      zCols = sqlite3_mprintf(\"%z%Q, \", zCols, p->azColumn[i]);\n    }\n\n    /* Create the whole \"CREATE TABLE\" statement to pass to SQLite */\n    zSql = sqlite3_mprintf(\n        \"CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)\", \n        zCols, p->zName, zLanguageid\n    );\n    if( !zCols || !zSql ){\n      rc = SQLITE_NOMEM;\n    }else{\n      rc = sqlite3_declare_vtab(p->db, zSql);\n    }\n\n    sqlite3_free(zSql);\n    sqlite3_free(zCols);\n    *pRc = rc;\n  }\n}\n\n/*\n** Create the %_stat table if it does not already exist.\n*/\nSQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){\n  fts3DbExec(pRc, p->db, \n      \"CREATE TABLE IF NOT EXISTS %Q.'%q_stat'\"\n          \"(id INTEGER PRIMARY KEY, value BLOB);\",\n      p->zDb, p->zName\n  );\n  if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;\n}\n\n/*\n** Create the backing store tables (%_content, %_segments and %_segdir)\n** required by the FTS3 table passed as the only argument. This is done\n** as part of the vtab xCreate() method.\n**\n** If the p->bHasDocsize boolean is true (indicating that this is an\n** FTS4 table, not an FTS3 table) then also create the %_docsize and\n** %_stat tables required by FTS4.\n*/\nstatic int fts3CreateTables(Fts3Table *p){\n  int rc = SQLITE_OK;             /* Return code */\n  int i;                          /* Iterator variable */\n  sqlite3 *db = p->db;            /* The database connection */\n\n  if( p->zContentTbl==0 ){\n    const char *zLanguageid = p->zLanguageid;\n    char *zContentCols;           /* Columns of %_content table */\n\n    /* Create a list of user columns for the content table */\n    zContentCols = sqlite3_mprintf(\"docid INTEGER PRIMARY KEY\");\n    for(i=0; zContentCols && i<p->nColumn; i++){\n      char *z = p->azColumn[i];\n      zContentCols = sqlite3_mprintf(\"%z, 'c%d%q'\", zContentCols, i, z);\n    }\n    if( zLanguageid && zContentCols ){\n      zContentCols = sqlite3_mprintf(\"%z, langid\", zContentCols, zLanguageid);\n    }\n    if( zContentCols==0 ) rc = SQLITE_NOMEM;\n  \n    /* Create the content table */\n    fts3DbExec(&rc, db, \n       \"CREATE TABLE %Q.'%q_content'(%s)\",\n       p->zDb, p->zName, zContentCols\n    );\n    sqlite3_free(zContentCols);\n  }\n\n  /* Create other tables */\n  fts3DbExec(&rc, db, \n      \"CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);\",\n      p->zDb, p->zName\n  );\n  fts3DbExec(&rc, db, \n      \"CREATE TABLE %Q.'%q_segdir'(\"\n        \"level INTEGER,\"\n        \"idx INTEGER,\"\n        \"start_block INTEGER,\"\n        \"leaves_end_block INTEGER,\"\n        \"end_block INTEGER,\"\n        \"root BLOB,\"\n        \"PRIMARY KEY(level, idx)\"\n      \");\",\n      p->zDb, p->zName\n  );\n  if( p->bHasDocsize ){\n    fts3DbExec(&rc, db, \n        \"CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);\",\n        p->zDb, p->zName\n    );\n  }\n  assert( p->bHasStat==p->bFts4 );\n  if( p->bHasStat ){\n    sqlite3Fts3CreateStatTable(&rc, p);\n  }\n  return rc;\n}\n\n/*\n** Store the current database page-size in bytes in p->nPgsz.\n**\n** If *pRc is non-zero when this function is called, it is a no-op. \n** Otherwise, if an error occurs, an SQLite error code is stored in *pRc\n** before returning.\n*/\nstatic void fts3DatabasePageSize(int *pRc, Fts3Table *p){\n  if( *pRc==SQLITE_OK ){\n    int rc;                       /* Return code */\n    char *zSql;                   /* SQL text \"PRAGMA %Q.page_size\" */\n    sqlite3_stmt *pStmt;          /* Compiled \"PRAGMA %Q.page_size\" statement */\n  \n    zSql = sqlite3_mprintf(\"PRAGMA %Q.page_size\", p->zDb);\n    if( !zSql ){\n      rc = SQLITE_NOMEM;\n    }else{\n      rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);\n      if( rc==SQLITE_OK ){\n        sqlite3_step(pStmt);\n        p->nPgsz = sqlite3_column_int(pStmt, 0);\n        rc = sqlite3_finalize(pStmt);\n      }else if( rc==SQLITE_AUTH ){\n        p->nPgsz = 1024;\n        rc = SQLITE_OK;\n      }\n    }\n    assert( p->nPgsz>0 || rc!=SQLITE_OK );\n    sqlite3_free(zSql);\n    *pRc = rc;\n  }\n}\n\n/*\n** \"Special\" FTS4 arguments are column specifications of the following form:\n**\n**   <key> = <value>\n**\n** There may not be whitespace surrounding the \"=\" character. The <value> \n** term may be quoted, but the <key> may not.\n*/\nstatic int fts3IsSpecialColumn(\n  const char *z, \n  int *pnKey,\n  char **pzValue\n){\n  char *zValue;\n  const char *zCsr = z;\n\n  while( *zCsr!='=' ){\n    if( *zCsr=='\\0' ) return 0;\n    zCsr++;\n  }\n\n  *pnKey = (int)(zCsr-z);\n  zValue = sqlite3_mprintf(\"%s\", &zCsr[1]);\n  if( zValue ){\n    sqlite3Fts3Dequote(zValue);\n  }\n  *pzValue = zValue;\n  return 1;\n}\n\n/*\n** Append the output of a printf() style formatting to an existing string.\n*/\nstatic void fts3Appendf(\n  int *pRc,                       /* IN/OUT: Error code */\n  char **pz,                      /* IN/OUT: Pointer to string buffer */\n  const char *zFormat,            /* Printf format string to append */\n  ...                             /* Arguments for printf format string */\n){\n  if( *pRc==SQLITE_OK ){\n    va_list ap;\n    char *z;\n    va_start(ap, zFormat);\n    z = sqlite3_vmprintf(zFormat, ap);\n    va_end(ap);\n    if( z && *pz ){\n      char *z2 = sqlite3_mprintf(\"%s%s\", *pz, z);\n      sqlite3_free(z);\n      z = z2;\n    }\n    if( z==0 ) *pRc = SQLITE_NOMEM;\n    sqlite3_free(*pz);\n    *pz = z;\n  }\n}\n\n/*\n** Return a copy of input string zInput enclosed in double-quotes (\") and\n** with all double quote characters escaped. For example:\n**\n**     fts3QuoteId(\"un \\\"zip\\\"\")   ->    \"un \\\"\\\"zip\\\"\\\"\"\n**\n** The pointer returned points to memory obtained from sqlite3_malloc(). It\n** is the callers responsibility to call sqlite3_free() to release this\n** memory.\n*/\nstatic char *fts3QuoteId(char const *zInput){\n  sqlite3_int64 nRet;\n  char *zRet;\n  nRet = 2 + (int)strlen(zInput)*2 + 1;\n  zRet = sqlite3_malloc64(nRet);\n  if( zRet ){\n    int i;\n    char *z = zRet;\n    *(z++) = '\"';\n    for(i=0; zInput[i]; i++){\n      if( zInput[i]=='\"' ) *(z++) = '\"';\n      *(z++) = zInput[i];\n    }\n    *(z++) = '\"';\n    *(z++) = '\\0';\n  }\n  return zRet;\n}\n\n/*\n** Return a list of comma separated SQL expressions and a FROM clause that \n** could be used in a SELECT statement such as the following:\n**\n**     SELECT <list of expressions> FROM %_content AS x ...\n**\n** to return the docid, followed by each column of text data in order\n** from left to write. If parameter zFunc is not NULL, then instead of\n** being returned directly each column of text data is passed to an SQL\n** function named zFunc first. For example, if zFunc is \"unzip\" and the\n** table has the three user-defined columns \"a\", \"b\", and \"c\", the following\n** string is returned:\n**\n**     \"docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x\"\n**\n** The pointer returned points to a buffer allocated by sqlite3_malloc(). It\n** is the responsibility of the caller to eventually free it.\n**\n** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and\n** a NULL pointer is returned). Otherwise, if an OOM error is encountered\n** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If\n** no error occurs, *pRc is left unmodified.\n*/\nstatic char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){\n  char *zRet = 0;\n  char *zFree = 0;\n  char *zFunction;\n  int i;\n\n  if( p->zContentTbl==0 ){\n    if( !zFunc ){\n      zFunction = \"\";\n    }else{\n      zFree = zFunction = fts3QuoteId(zFunc);\n    }\n    fts3Appendf(pRc, &zRet, \"docid\");\n    for(i=0; i<p->nColumn; i++){\n      fts3Appendf(pRc, &zRet, \",%s(x.'c%d%q')\", zFunction, i, p->azColumn[i]);\n    }\n    if( p->zLanguageid ){\n      fts3Appendf(pRc, &zRet, \", x.%Q\", \"langid\");\n    }\n    sqlite3_free(zFree);\n  }else{\n    fts3Appendf(pRc, &zRet, \"rowid\");\n    for(i=0; i<p->nColumn; i++){\n      fts3Appendf(pRc, &zRet, \", x.'%q'\", p->azColumn[i]);\n    }\n    if( p->zLanguageid ){\n      fts3Appendf(pRc, &zRet, \", x.%Q\", p->zLanguageid);\n    }\n  }\n  fts3Appendf(pRc, &zRet, \" FROM '%q'.'%q%s' AS x\", \n      p->zDb,\n      (p->zContentTbl ? p->zContentTbl : p->zName),\n      (p->zContentTbl ? \"\" : \"_content\")\n  );\n  return zRet;\n}\n\n/*\n** Return a list of N comma separated question marks, where N is the number\n** of columns in the %_content table (one for the docid plus one for each\n** user-defined text column).\n**\n** If argument zFunc is not NULL, then all but the first question mark\n** is preceded by zFunc and an open bracket, and followed by a closed\n** bracket. For example, if zFunc is \"zip\" and the FTS3 table has three \n** user-defined text columns, the following string is returned:\n**\n**     \"?, zip(?), zip(?), zip(?)\"\n**\n** The pointer returned points to a buffer allocated by sqlite3_malloc(). It\n** is the responsibility of the caller to eventually free it.\n**\n** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and\n** a NULL pointer is returned). Otherwise, if an OOM error is encountered\n** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If\n** no error occurs, *pRc is left unmodified.\n*/\nstatic char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){\n  char *zRet = 0;\n  char *zFree = 0;\n  char *zFunction;\n  int i;\n\n  if( !zFunc ){\n    zFunction = \"\";\n  }else{\n    zFree = zFunction = fts3QuoteId(zFunc);\n  }\n  fts3Appendf(pRc, &zRet, \"?\");\n  for(i=0; i<p->nColumn; i++){\n    fts3Appendf(pRc, &zRet, \",%s(?)\", zFunction);\n  }\n  if( p->zLanguageid ){\n    fts3Appendf(pRc, &zRet, \", ?\");\n  }\n  sqlite3_free(zFree);\n  return zRet;\n}\n\n/*\n** Buffer z contains a positive integer value encoded as utf-8 text.\n** Decode this value and store it in *pnOut, returning the number of bytes\n** consumed. If an overflow error occurs return a negative value.\n*/\nSQLITE_PRIVATE int sqlite3Fts3ReadInt(const char *z, int *pnOut){\n  u64 iVal = 0;\n  int i;\n  for(i=0; z[i]>='0' && z[i]<='9'; i++){\n    iVal = iVal*10 + (z[i] - '0');\n    if( iVal>0x7FFFFFFF ) return -1;\n  }\n  *pnOut = (int)iVal;\n  return i;\n}\n\n/*\n** This function interprets the string at (*pp) as a non-negative integer\n** value. It reads the integer and sets *pnOut to the value read, then \n** sets *pp to point to the byte immediately following the last byte of\n** the integer value.\n**\n** Only decimal digits ('0'..'9') may be part of an integer value. \n**\n** If *pp does not being with a decimal digit SQLITE_ERROR is returned and\n** the output value undefined. Otherwise SQLITE_OK is returned.\n**\n** This function is used when parsing the \"prefix=\" FTS4 parameter.\n*/\nstatic int fts3GobbleInt(const char **pp, int *pnOut){\n  const int MAX_NPREFIX = 10000000;\n  int nInt = 0;                   /* Output value */\n  int nByte;\n  nByte = sqlite3Fts3ReadInt(*pp, &nInt);\n  if( nInt>MAX_NPREFIX ){\n    nInt = 0;\n  }\n  if( nByte==0 ){\n    return SQLITE_ERROR;\n  }\n  *pnOut = nInt;\n  *pp += nByte;\n  return SQLITE_OK;\n}\n\n/*\n** This function is called to allocate an array of Fts3Index structures\n** representing the indexes maintained by the current FTS table. FTS tables\n** always maintain the main \"terms\" index, but may also maintain one or\n** more \"prefix\" indexes, depending on the value of the \"prefix=\" parameter\n** (if any) specified as part of the CREATE VIRTUAL TABLE statement.\n**\n** Argument zParam is passed the value of the \"prefix=\" option if one was\n** specified, or NULL otherwise.\n**\n** If no error occurs, SQLITE_OK is returned and *apIndex set to point to\n** the allocated array. *pnIndex is set to the number of elements in the\n** array. If an error does occur, an SQLite error code is returned.\n**\n** Regardless of whether or not an error is returned, it is the responsibility\n** of the caller to call sqlite3_free() on the output array to free it.\n*/\nstatic int fts3PrefixParameter(\n  const char *zParam,             /* ABC in prefix=ABC parameter to parse */\n  int *pnIndex,                   /* OUT: size of *apIndex[] array */\n  struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */\n){\n  struct Fts3Index *aIndex;       /* Allocated array */\n  int nIndex = 1;                 /* Number of entries in array */\n\n  if( zParam && zParam[0] ){\n    const char *p;\n    nIndex++;\n    for(p=zParam; *p; p++){\n      if( *p==',' ) nIndex++;\n    }\n  }\n\n  aIndex = sqlite3_malloc64(sizeof(struct Fts3Index) * nIndex);\n  *apIndex = aIndex;\n  if( !aIndex ){\n    return SQLITE_NOMEM;\n  }\n\n  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);\n  if( zParam ){\n    const char *p = zParam;\n    int i;\n    for(i=1; i<nIndex; i++){\n      int nPrefix = 0;\n      if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;\n      assert( nPrefix>=0 );\n      if( nPrefix==0 ){\n        nIndex--;\n        i--;\n      }else{\n        aIndex[i].nPrefix = nPrefix;\n      }\n      p++;\n    }\n  }\n\n  *pnIndex = nIndex;\n  return SQLITE_OK;\n}\n\n/*\n** This function is called when initializing an FTS4 table that uses the\n** content=xxx option. It determines the number of and names of the columns\n** of the new FTS4 table.\n**\n** The third argument passed to this function is the value passed to the\n** config=xxx option (i.e. \"xxx\"). This function queries the database for\n** a table of that name. If found, the output variables are populated\n** as follows:\n**\n**   *pnCol:   Set to the number of columns table xxx has,\n**\n**   *pnStr:   Set to the total amount of space required to store a copy\n**             of each columns name, including the nul-terminator.\n**\n**   *pazCol:  Set to point to an array of *pnCol strings. Each string is\n**             the name of the corresponding column in table xxx. The array\n**             and its contents are allocated using a single allocation. It\n**             is the responsibility of the caller to free this allocation\n**             by eventually passing the *pazCol value to sqlite3_free().\n**\n** If the table cannot be found, an error code is returned and the output\n** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is\n** returned (and the output variables are undefined).\n*/\nstatic int fts3ContentColumns(\n  sqlite3 *db,                    /* Database handle */\n  const char *zDb,                /* Name of db (i.e. \"main\", \"temp\" etc.) */\n  const char *zTbl,               /* Name of content table */\n  const char ***pazCol,           /* OUT: Malloc'd array of column names */\n  int *pnCol,                     /* OUT: Size of array *pazCol */\n  int *pnStr,                     /* OUT: Bytes of string content */\n  char **pzErr                    /* OUT: error message */\n){\n  int rc = SQLITE_OK;             /* Return code */\n  char *zSql;                     /* \"SELECT *\" statement on zTbl */  \n  sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */\n\n  zSql = sqlite3_mprintf(\"SELECT * FROM %Q.%Q\", zDb, zTbl);\n  if( !zSql ){\n    rc = SQLITE_NOMEM;\n  }else{\n    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);\n    if( rc!=SQLITE_OK ){\n      sqlite3Fts3ErrMsg(pzErr, \"%s\", sqlite3_errmsg(db));\n    }\n  }\n  sqlite3_free(zSql);\n\n  if( rc==SQLITE_OK ){\n    const char **azCol;           /* Output array */\n    sqlite3_int64 nStr = 0;       /* Size of all column names (incl. 0x00) */\n    int nCol;                     /* Number of table columns */\n    int i;                        /* Used to iterate through columns */\n\n    /* Loop through the returned columns. Set nStr to the number of bytes of\n    ** space required to store a copy of each column name, including the\n    ** nul-terminator byte.  */\n    nCol = sqlite3_column_count(pStmt);\n    for(i=0; i<nCol; i++){\n      const char *zCol = sqlite3_column_name(pStmt, i);\n      nStr += strlen(zCol) + 1;\n    }\n\n    /* Allocate and populate the array to return. */\n    azCol = (const char **)sqlite3_malloc64(sizeof(char *) * nCol + nStr);\n    if( azCol==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      char *p = (char *)&azCol[nCol];\n      for(i=0; i<nCol; i++){\n        const char *zCol = sqlite3_column_name(pStmt, i);\n        int n = (int)strlen(zCol)+1;\n        memcpy(p, zCol, n);\n        azCol[i] = p;\n        p += n;\n      }\n    }\n    sqlite3_finalize(pStmt);\n\n    /* Set the output variables. */\n    *pnCol = nCol;\n    *pnStr = nStr;\n    *pazCol = azCol;\n  }\n\n  return rc;\n}\n\n/*\n** This function is the implementation of both the xConnect and xCreate\n** methods of the FTS3 virtual table.\n**\n** The argv[] array contains the following:\n**\n**   argv[0]   -> module name  (\"fts3\" or \"fts4\")\n**   argv[1]   -> database name\n**   argv[2]   -> table name\n**   argv[...] -> \"column name\" and other module argument fields.\n*/\nstatic int fts3InitVtab(\n  int isCreate,                   /* True for xCreate, false for xConnect */\n  sqlite3 *db,                    /* The SQLite database connection */\n  void *pAux,                     /* Hash table containing tokenizers */\n  int argc,                       /* Number of elements in argv array */\n  const char * const *argv,       /* xCreate/xConnect argument array */\n  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */\n  char **pzErr                    /* Write any error message here */\n){\n  Fts3Hash *pHash = (Fts3Hash *)pAux;\n  Fts3Table *p = 0;               /* Pointer to allocated vtab */\n  int rc = SQLITE_OK;             /* Return code */\n  int i;                          /* Iterator variable */\n  sqlite3_int64 nByte;            /* Size of allocation used for *p */\n  int iCol;                       /* Column index */\n  int nString = 0;                /* Bytes required to hold all column names */\n  int nCol = 0;                   /* Number of columns in the FTS table */\n  char *zCsr;                     /* Space for holding column names */\n  int nDb;                        /* Bytes required to hold database name */\n  int nName;                      /* Bytes required to hold table name */\n  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */\n  const char **aCol;              /* Array of column names */\n  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */\n\n  int nIndex = 0;                 /* Size of aIndex[] array */\n  struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */\n\n  /* The results of parsing supported FTS4 key=value options: */\n  int bNoDocsize = 0;             /* True to omit %_docsize table */\n  int bDescIdx = 0;               /* True to store descending indexes */\n  char *zPrefix = 0;              /* Prefix parameter value (or NULL) */\n  char *zCompress = 0;            /* compress=? parameter (or NULL) */\n  char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */\n  char *zContent = 0;             /* content=? parameter (or NULL) */\n  char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */\n  char **azNotindexed = 0;        /* The set of notindexed= columns */\n  int nNotindexed = 0;            /* Size of azNotindexed[] array */\n\n  assert( strlen(argv[0])==4 );\n  assert( (sqlite3_strnicmp(argv[0], \"fts4\", 4)==0 && isFts4)\n       || (sqlite3_strnicmp(argv[0], \"fts3\", 4)==0 && !isFts4)\n  );\n\n  nDb = (int)strlen(argv[1]) + 1;\n  nName = (int)strlen(argv[2]) + 1;\n\n  nByte = sizeof(const char *) * (argc-2);\n  aCol = (const char **)sqlite3_malloc64(nByte);\n  if( aCol ){\n    memset((void*)aCol, 0, nByte);\n    azNotindexed = (char **)sqlite3_malloc64(nByte);\n  }\n  if( azNotindexed ){\n    memset(azNotindexed, 0, nByte);\n  }\n  if( !aCol || !azNotindexed ){\n    rc = SQLITE_NOMEM;\n    goto fts3_init_out;\n  }\n\n  /* Loop through all of the arguments passed by the user to the FTS3/4\n  ** module (i.e. all the column names and special arguments). This loop\n  ** does the following:\n  **\n  **   + Figures out the number of columns the FTSX table will have, and\n  **     the number of bytes of space that must be allocated to store copies\n  **     of the column names.\n  **\n  **   + If there is a tokenizer specification included in the arguments,\n  **     initializes the tokenizer pTokenizer.\n  */\n  for(i=3; rc==SQLITE_OK && i<argc; i++){\n    char const *z = argv[i];\n    int nKey;\n    char *zVal;\n\n    /* Check if this is a tokenizer specification */\n    if( !pTokenizer \n     && strlen(z)>8\n     && 0==sqlite3_strnicmp(z, \"tokenize\", 8) \n     && 0==sqlite3Fts3IsIdChar(z[8])\n    ){\n      rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);\n    }\n\n    /* Check if it is an FTS4 special argument. */\n    else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){\n      struct Fts4Option {\n        const char *zOpt;\n        int nOpt;\n      } aFts4Opt[] = {\n        { \"matchinfo\",   9 },     /* 0 -> MATCHINFO */\n        { \"prefix\",      6 },     /* 1 -> PREFIX */\n        { \"compress\",    8 },     /* 2 -> COMPRESS */\n        { \"uncompress\", 10 },     /* 3 -> UNCOMPRESS */\n        { \"order\",       5 },     /* 4 -> ORDER */\n        { \"content\",     7 },     /* 5 -> CONTENT */\n        { \"languageid\", 10 },     /* 6 -> LANGUAGEID */\n        { \"notindexed\", 10 }      /* 7 -> NOTINDEXED */\n      };\n\n      int iOpt;\n      if( !zVal ){\n        rc = SQLITE_NOMEM;\n      }else{\n        for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){\n          struct Fts4Option *pOp = &aFts4Opt[iOpt];\n          if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){\n            break;\n          }\n        }\n        switch( iOpt ){\n          case 0:               /* MATCHINFO */\n            if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, \"fts3\", 4) ){\n              sqlite3Fts3ErrMsg(pzErr, \"unrecognized matchinfo: %s\", zVal);\n              rc = SQLITE_ERROR;\n            }\n            bNoDocsize = 1;\n            break;\n\n          case 1:               /* PREFIX */\n            sqlite3_free(zPrefix);\n            zPrefix = zVal;\n            zVal = 0;\n            break;\n\n          case 2:               /* COMPRESS */\n            sqlite3_free(zCompress);\n            zCompress = zVal;\n            zVal = 0;\n            break;\n\n          case 3:               /* UNCOMPRESS */\n            sqlite3_free(zUncompress);\n            zUncompress = zVal;\n            zVal = 0;\n            break;\n\n          case 4:               /* ORDER */\n            if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, \"asc\", 3)) \n             && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, \"desc\", 4)) \n            ){\n              sqlite3Fts3ErrMsg(pzErr, \"unrecognized order: %s\", zVal);\n              rc = SQLITE_ERROR;\n            }\n            bDescIdx = (zVal[0]=='d' || zVal[0]=='D');\n            break;\n\n          case 5:              /* CONTENT */\n            sqlite3_free(zContent);\n            zContent = zVal;\n            zVal = 0;\n            break;\n\n          case 6:              /* LANGUAGEID */\n            assert( iOpt==6 );\n            sqlite3_free(zLanguageid);\n            zLanguageid = zVal;\n            zVal = 0;\n            break;\n\n          case 7:              /* NOTINDEXED */\n            azNotindexed[nNotindexed++] = zVal;\n            zVal = 0;\n            break;\n\n          default:\n            assert( iOpt==SizeofArray(aFts4Opt) );\n            sqlite3Fts3ErrMsg(pzErr, \"unrecognized parameter: %s\", z);\n            rc = SQLITE_ERROR;\n            break;\n        }\n        sqlite3_free(zVal);\n      }\n    }\n\n    /* Otherwise, the argument is a column name. */\n    else {\n      nString += (int)(strlen(z) + 1);\n      aCol[nCol++] = z;\n    }\n  }\n\n  /* If a content=xxx option was specified, the following:\n  **\n  **   1. Ignore any compress= and uncompress= options.\n  **\n  **   2. If no column names were specified as part of the CREATE VIRTUAL\n  **      TABLE statement, use all columns from the content table.\n  */\n  if( rc==SQLITE_OK && zContent ){\n    sqlite3_free(zCompress); \n    sqlite3_free(zUncompress); \n    zCompress = 0;\n    zUncompress = 0;\n    if( nCol==0 ){\n      sqlite3_free((void*)aCol); \n      aCol = 0;\n      rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);\n\n      /* If a languageid= option was specified, remove the language id\n      ** column from the aCol[] array. */ \n      if( rc==SQLITE_OK && zLanguageid ){\n        int j;\n        for(j=0; j<nCol; j++){\n          if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){\n            int k;\n            for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];\n            nCol--;\n            break;\n          }\n        }\n      }\n    }\n  }\n  if( rc!=SQLITE_OK ) goto fts3_init_out;\n\n  if( nCol==0 ){\n    assert( nString==0 );\n    aCol[0] = \"content\";\n    nString = 8;\n    nCol = 1;\n  }\n\n  if( pTokenizer==0 ){\n    rc = sqlite3Fts3InitTokenizer(pHash, \"simple\", &pTokenizer, pzErr);\n    if( rc!=SQLITE_OK ) goto fts3_init_out;\n  }\n  assert( pTokenizer );\n\n  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);\n  if( rc==SQLITE_ERROR ){\n    assert( zPrefix );\n    sqlite3Fts3ErrMsg(pzErr, \"error parsing prefix parameter: %s\", zPrefix);\n  }\n  if( rc!=SQLITE_OK ) goto fts3_init_out;\n\n  /* Allocate and populate the Fts3Table structure. */\n  nByte = sizeof(Fts3Table) +                  /* Fts3Table */\n          nCol * sizeof(char *) +              /* azColumn */\n          nIndex * sizeof(struct Fts3Index) +  /* aIndex */\n          nCol * sizeof(u8) +                  /* abNotindexed */\n          nName +                              /* zName */\n          nDb +                                /* zDb */\n          nString;                             /* Space for azColumn strings */\n  p = (Fts3Table*)sqlite3_malloc64(nByte);\n  if( p==0 ){\n    rc = SQLITE_NOMEM;\n    goto fts3_init_out;\n  }\n  memset(p, 0, nByte);\n  p->db = db;\n  p->nColumn = nCol;\n  p->nPendingData = 0;\n  p->azColumn = (char **)&p[1];\n  p->pTokenizer = pTokenizer;\n  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;\n  p->bHasDocsize = (isFts4 && bNoDocsize==0);\n  p->bHasStat = (u8)isFts4;\n  p->bFts4 = (u8)isFts4;\n  p->bDescIdx = (u8)bDescIdx;\n  p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */\n  p->zContentTbl = zContent;\n  p->zLanguageid = zLanguageid;\n  zContent = 0;\n  zLanguageid = 0;\n  TESTONLY( p->inTransaction = -1 );\n  TESTONLY( p->mxSavepoint = -1 );\n\n  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];\n  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);\n  p->nIndex = nIndex;\n  for(i=0; i<nIndex; i++){\n    fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);\n  }\n  p->abNotindexed = (u8 *)&p->aIndex[nIndex];\n\n  /* Fill in the zName and zDb fields of the vtab structure. */\n  zCsr = (char *)&p->abNotindexed[nCol];\n  p->zName = zCsr;\n  memcpy(zCsr, argv[2], nName);\n  zCsr += nName;\n  p->zDb = zCsr;\n  memcpy(zCsr, argv[1], nDb);\n  zCsr += nDb;\n\n  /* Fill in the azColumn array */\n  for(iCol=0; iCol<nCol; iCol++){\n    char *z; \n    int n = 0;\n    z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);\n    if( n>0 ){\n      memcpy(zCsr, z, n);\n    }\n    zCsr[n] = '\\0';\n    sqlite3Fts3Dequote(zCsr);\n    p->azColumn[iCol] = zCsr;\n    zCsr += n+1;\n    assert( zCsr <= &((char *)p)[nByte] );\n  }\n\n  /* Fill in the abNotindexed array */\n  for(iCol=0; iCol<nCol; iCol++){\n    int n = (int)strlen(p->azColumn[iCol]);\n    for(i=0; i<nNotindexed; i++){\n      char *zNot = azNotindexed[i];\n      if( zNot && n==(int)strlen(zNot)\n       && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n) \n      ){\n        p->abNotindexed[iCol] = 1;\n        sqlite3_free(zNot);\n        azNotindexed[i] = 0;\n      }\n    }\n  }\n  for(i=0; i<nNotindexed; i++){\n    if( azNotindexed[i] ){\n      sqlite3Fts3ErrMsg(pzErr, \"no such column: %s\", azNotindexed[i]);\n      rc = SQLITE_ERROR;\n    }\n  }\n\n  if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){\n    char const *zMiss = (zCompress==0 ? \"compress\" : \"uncompress\");\n    rc = SQLITE_ERROR;\n    sqlite3Fts3ErrMsg(pzErr, \"missing %s parameter in fts4 constructor\", zMiss);\n  }\n  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);\n  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);\n  if( rc!=SQLITE_OK ) goto fts3_init_out;\n\n  /* If this is an xCreate call, create the underlying tables in the \n  ** database. TODO: For xConnect(), it could verify that said tables exist.\n  */\n  if( isCreate ){\n    rc = fts3CreateTables(p);\n  }\n\n  /* Check to see if a legacy fts3 table has been \"upgraded\" by the\n  ** addition of a %_stat table so that it can use incremental merge.\n  */\n  if( !isFts4 && !isCreate ){\n    p->bHasStat = 2;\n  }\n\n  /* Figure out the page-size for the database. This is required in order to\n  ** estimate the cost of loading large doclists from the database.  */\n  fts3DatabasePageSize(&rc, p);\n  p->nNodeSize = p->nPgsz-35;\n\n#if defined(SQLITE_DEBUG)||defined(SQLITE_TEST)\n  p->nMergeCount = FTS3_MERGE_COUNT;\n#endif\n\n  /* Declare the table schema to SQLite. */\n  fts3DeclareVtab(&rc, p);\n\nfts3_init_out:\n  sqlite3_free(zPrefix);\n  sqlite3_free(aIndex);\n  sqlite3_free(zCompress);\n  sqlite3_free(zUncompress);\n  sqlite3_free(zContent);\n  sqlite3_free(zLanguageid);\n  for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);\n  sqlite3_free((void *)aCol);\n  sqlite3_free((void *)azNotindexed);\n  if( rc!=SQLITE_OK ){\n    if( p ){\n      fts3DisconnectMethod((sqlite3_vtab *)p);\n    }else if( pTokenizer ){\n      pTokenizer->pModule->xDestroy(pTokenizer);\n    }\n  }else{\n    assert( p->pSegments==0 );\n    *ppVTab = &p->base;\n  }\n  return rc;\n}\n\n/*\n** The xConnect() and xCreate() methods for the virtual table. All the\n** work is done in function fts3InitVtab().\n*/\nstatic int fts3ConnectMethod(\n  sqlite3 *db,                    /* Database connection */\n  void *pAux,                     /* Pointer to tokenizer hash table */\n  int argc,                       /* Number of elements in argv array */\n  const char * const *argv,       /* xCreate/xConnect argument array */\n  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */\n  char **pzErr                    /* OUT: sqlite3_malloc'd error message */\n){\n  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);\n}\nstatic int fts3CreateMethod(\n  sqlite3 *db,                    /* Database connection */\n  void *pAux,                     /* Pointer to tokenizer hash table */\n  int argc,                       /* Number of elements in argv array */\n  const char * const *argv,       /* xCreate/xConnect argument array */\n  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */\n  char **pzErr                    /* OUT: sqlite3_malloc'd error message */\n){\n  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);\n}\n\n/*\n** Set the pIdxInfo->estimatedRows variable to nRow. Unless this\n** extension is currently being used by a version of SQLite too old to\n** support estimatedRows. In that case this function is a no-op.\n*/\nstatic void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){\n#if SQLITE_VERSION_NUMBER>=3008002\n  if( sqlite3_libversion_number()>=3008002 ){\n    pIdxInfo->estimatedRows = nRow;\n  }\n#endif\n}\n\n/*\n** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this\n** extension is currently being used by a version of SQLite too old to\n** support index-info flags. In that case this function is a no-op.\n*/\nstatic void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){\n#if SQLITE_VERSION_NUMBER>=3008012\n  if( sqlite3_libversion_number()>=3008012 ){\n    pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;\n  }\n#endif\n}\n\n/* \n** Implementation of the xBestIndex method for FTS3 tables. There\n** are three possible strategies, in order of preference:\n**\n**   1. Direct lookup by rowid or docid. \n**   2. Full-text search using a MATCH operator on a non-docid column.\n**   3. Linear scan of %_content table.\n*/\nstatic int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){\n  Fts3Table *p = (Fts3Table *)pVTab;\n  int i;                          /* Iterator variable */\n  int iCons = -1;                 /* Index of constraint to use */\n\n  int iLangidCons = -1;           /* Index of langid=x constraint, if present */\n  int iDocidGe = -1;              /* Index of docid>=x constraint, if present */\n  int iDocidLe = -1;              /* Index of docid<=x constraint, if present */\n  int iIdx;\n\n  if( p->bLock ){\n    return SQLITE_ERROR;\n  }\n\n  /* By default use a full table scan. This is an expensive option,\n  ** so search through the constraints to see if a more efficient \n  ** strategy is possible.\n  */\n  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;\n  pInfo->estimatedCost = 5000000;\n  for(i=0; i<pInfo->nConstraint; i++){\n    int bDocid;                 /* True if this constraint is on docid */\n    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];\n    if( pCons->usable==0 ){\n      if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){\n        /* There exists an unusable MATCH constraint. This means that if\n        ** the planner does elect to use the results of this call as part\n        ** of the overall query plan the user will see an \"unable to use\n        ** function MATCH in the requested context\" error. To discourage\n        ** this, return a very high cost here.  */\n        pInfo->idxNum = FTS3_FULLSCAN_SEARCH;\n        pInfo->estimatedCost = 1e50;\n        fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);\n        return SQLITE_OK;\n      }\n      continue;\n    }\n\n    bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);\n\n    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */\n    if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){\n      pInfo->idxNum = FTS3_DOCID_SEARCH;\n      pInfo->estimatedCost = 1.0;\n      iCons = i;\n    }\n\n    /* A MATCH constraint. Use a full-text search.\n    **\n    ** If there is more than one MATCH constraint available, use the first\n    ** one encountered. If there is both a MATCH constraint and a direct\n    ** rowid/docid lookup, prefer the MATCH strategy. This is done even \n    ** though the rowid/docid lookup is faster than a MATCH query, selecting\n    ** it would lead to an \"unable to use function MATCH in the requested \n    ** context\" error.\n    */\n    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH \n     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn\n    ){\n      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;\n      pInfo->estimatedCost = 2.0;\n      iCons = i;\n    }\n\n    /* Equality constraint on the langid column */\n    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ \n     && pCons->iColumn==p->nColumn + 2\n    ){\n      iLangidCons = i;\n    }\n\n    if( bDocid ){\n      switch( pCons->op ){\n        case SQLITE_INDEX_CONSTRAINT_GE:\n        case SQLITE_INDEX_CONSTRAINT_GT:\n          iDocidGe = i;\n          break;\n\n        case SQLITE_INDEX_CONSTRAINT_LE:\n        case SQLITE_INDEX_CONSTRAINT_LT:\n          iDocidLe = i;\n          break;\n      }\n    }\n  }\n\n  /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */\n  if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);\n\n  iIdx = 1;\n  if( iCons>=0 ){\n    pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;\n    pInfo->aConstraintUsage[iCons].omit = 1;\n  } \n  if( iLangidCons>=0 ){\n    pInfo->idxNum |= FTS3_HAVE_LANGID;\n    pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;\n  } \n  if( iDocidGe>=0 ){\n    pInfo->idxNum |= FTS3_HAVE_DOCID_GE;\n    pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;\n  } \n  if( iDocidLe>=0 ){\n    pInfo->idxNum |= FTS3_HAVE_DOCID_LE;\n    pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;\n  } \n\n  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or\n  ** docid) order. Both ascending and descending are possible. \n  */\n  if( pInfo->nOrderBy==1 ){\n    struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];\n    if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){\n      if( pOrder->desc ){\n        pInfo->idxStr = \"DESC\";\n      }else{\n        pInfo->idxStr = \"ASC\";\n      }\n      pInfo->orderByConsumed = 1;\n    }\n  }\n\n  assert( p->pSegments==0 );\n  return SQLITE_OK;\n}\n\n/*\n** Implementation of xOpen method.\n*/\nstatic int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){\n  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */\n\n  UNUSED_PARAMETER(pVTab);\n\n  /* Allocate a buffer large enough for an Fts3Cursor structure. If the\n  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, \n  ** if the allocation fails, return SQLITE_NOMEM.\n  */\n  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));\n  if( !pCsr ){\n    return SQLITE_NOMEM;\n  }\n  memset(pCsr, 0, sizeof(Fts3Cursor));\n  return SQLITE_OK;\n}\n\n/*\n** Finalize the statement handle at pCsr->pStmt.\n**\n** Or, if that statement handle is one created by fts3CursorSeekStmt(),\n** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement\n** pointer there instead of finalizing it.\n*/\nstatic void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){\n  if( pCsr->bSeekStmt ){\n    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;\n    if( p->pSeekStmt==0 ){\n      p->pSeekStmt = pCsr->pStmt;\n      sqlite3_reset(pCsr->pStmt);\n      pCsr->pStmt = 0;\n    }\n    pCsr->bSeekStmt = 0;\n  }\n  sqlite3_finalize(pCsr->pStmt);\n}\n\n/*\n** Free all resources currently held by the cursor passed as the only\n** argument.\n*/\nstatic void fts3ClearCursor(Fts3Cursor *pCsr){\n  fts3CursorFinalizeStmt(pCsr);\n  sqlite3Fts3FreeDeferredTokens(pCsr);\n  sqlite3_free(pCsr->aDoclist);\n  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);\n  sqlite3Fts3ExprFree(pCsr->pExpr);\n  memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));\n}\n\n/*\n** Close the cursor.  For additional information see the documentation\n** on the xClose method of the virtual table interface.\n*/\nstatic int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){\n  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;\n  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );\n  fts3ClearCursor(pCsr);\n  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );\n  sqlite3_free(pCsr);\n  return SQLITE_OK;\n}\n\n/*\n** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then\n** compose and prepare an SQL statement of the form:\n**\n**    \"SELECT <columns> FROM %_content WHERE rowid = ?\"\n**\n** (or the equivalent for a content=xxx table) and set pCsr->pStmt to\n** it. If an error occurs, return an SQLite error code.\n*/\nstatic int fts3CursorSeekStmt(Fts3Cursor *pCsr){\n  int rc = SQLITE_OK;\n  if( pCsr->pStmt==0 ){\n    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;\n    char *zSql;\n    if( p->pSeekStmt ){\n      pCsr->pStmt = p->pSeekStmt;\n      p->pSeekStmt = 0;\n    }else{\n      zSql = sqlite3_mprintf(\"SELECT %s WHERE rowid = ?\", p->zReadExprlist);\n      if( !zSql ) return SQLITE_NOMEM;\n      p->bLock++;\n      rc = sqlite3_prepare_v3(\n          p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0\n      );\n      p->bLock--;\n      sqlite3_free(zSql);\n    }\n    if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;\n  }\n  return rc;\n}\n\n/*\n** Position the pCsr->pStmt statement so that it is on the row\n** of the %_content table that contains the last match.  Return\n** SQLITE_OK on success.  \n*/\nstatic int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){\n  int rc = SQLITE_OK;\n  if( pCsr->isRequireSeek ){\n    rc = fts3CursorSeekStmt(pCsr);\n    if( rc==SQLITE_OK ){\n      Fts3Table *pTab = (Fts3Table*)pCsr->base.pVtab;\n      pTab->bLock++;\n      sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);\n      pCsr->isRequireSeek = 0;\n      if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){\n        pTab->bLock--;\n        return SQLITE_OK;\n      }else{\n        pTab->bLock--;\n        rc = sqlite3_reset(pCsr->pStmt);\n        if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){\n          /* If no row was found and no error has occurred, then the %_content\n          ** table is missing a row that is present in the full-text index.\n          ** The data structures are corrupt.  */\n          rc = FTS_CORRUPT_VTAB;\n          pCsr->isEof = 1;\n        }\n      }\n    }\n  }\n\n  if( rc!=SQLITE_OK && pContext ){\n    sqlite3_result_error_code(pContext, rc);\n  }\n  return rc;\n}\n\n/*\n** This function is used to process a single interior node when searching\n** a b-tree for a term or term prefix. The node data is passed to this \n** function via the zNode/nNode parameters. The term to search for is\n** passed in zTerm/nTerm.\n**\n** If piFirst is not NULL, then this function sets *piFirst to the blockid\n** of the child node that heads the sub-tree that may contain the term.\n**\n** If piLast is not NULL, then *piLast is set to the right-most child node\n** that heads a sub-tree that may contain a term for which zTerm/nTerm is\n** a prefix.\n**\n** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.\n*/\nstatic int fts3ScanInteriorNode(\n  const char *zTerm,              /* Term to select leaves for */\n  int nTerm,                      /* Size of term zTerm in bytes */\n  const char *zNode,              /* Buffer containing segment interior node */\n  int nNode,                      /* Size of buffer at zNode */\n  sqlite3_int64 *piFirst,         /* OUT: Selected child node */\n  sqlite3_int64 *piLast           /* OUT: Selected child node */\n){\n  int rc = SQLITE_OK;             /* Return code */\n  const char *zCsr = zNode;       /* Cursor to iterate through node */\n  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */\n  char *zBuffer = 0;              /* Buffer to load terms into */\n  i64 nAlloc = 0;                 /* Size of allocated buffer */\n  int isFirstTerm = 1;            /* True when processing first term on page */\n  sqlite3_int64 iChild;           /* Block id of child node to descend to */\n  int nBuffer = 0;                /* Total term size */\n\n  /* Skip over the 'height' varint that occurs at the start of every \n  ** interior node. Then load the blockid of the left-child of the b-tree\n  ** node into variable iChild.  \n  **\n  ** Even if the data structure on disk is corrupted, this (reading two\n  ** varints from the buffer) does not risk an overread. If zNode is a\n  ** root node, then the buffer comes from a SELECT statement. SQLite does\n  ** not make this guarantee explicitly, but in practice there are always\n  ** either more than 20 bytes of allocated space following the nNode bytes of\n  ** contents, or two zero bytes. Or, if the node is read from the %_segments\n  ** table, then there are always 20 bytes of zeroed padding following the\n  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).\n  */\n  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);\n  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);\n  if( zCsr>zEnd ){\n    return FTS_CORRUPT_VTAB;\n  }\n  \n  while( zCsr<zEnd && (piFirst || piLast) ){\n    int cmp;                      /* memcmp() result */\n    int nSuffix;                  /* Size of term suffix */\n    int nPrefix = 0;              /* Size of term prefix */\n  \n    /* Load the next term on the node into zBuffer. Use realloc() to expand\n    ** the size of zBuffer if required.  */\n    if( !isFirstTerm ){\n      zCsr += fts3GetVarint32(zCsr, &nPrefix);\n      if( nPrefix>nBuffer ){\n        rc = FTS_CORRUPT_VTAB;\n        goto finish_scan;\n      }\n    }\n    isFirstTerm = 0;\n    zCsr += fts3GetVarint32(zCsr, &nSuffix);\n    \n    assert( nPrefix>=0 && nSuffix>=0 );\n    if( nPrefix>zCsr-zNode || nSuffix>zEnd-zCsr || nSuffix==0 ){\n      rc = FTS_CORRUPT_VTAB;\n      goto finish_scan;\n    }\n    if( (i64)nPrefix+nSuffix>nAlloc ){\n      char *zNew;\n      nAlloc = ((i64)nPrefix+nSuffix) * 2;\n      zNew = (char *)sqlite3_realloc64(zBuffer, nAlloc);\n      if( !zNew ){\n        rc = SQLITE_NOMEM;\n        goto finish_scan;\n      }\n      zBuffer = zNew;\n    }\n    assert( zBuffer );\n    memcpy(&zBuffer[nPrefix], zCsr, nSuffix);\n    nBuffer = nPrefix + nSuffix;\n    zCsr += nSuffix;\n\n    /* Compare the term we are searching for with the term just loaded from\n    ** the interior node. If the specified term is greater than or equal\n    ** to the term from the interior node, then all terms on the sub-tree \n    ** headed by node iChild are smaller than zTerm. No need to search \n    ** iChild.\n    **\n    ** If the interior node term is larger than the specified term, then\n    ** the tree headed by iChild may contain the specified term.\n    */\n    cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));\n    if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){\n      *piFirst = iChild;\n      piFirst = 0;\n    }\n\n    if( piLast && cmp<0 ){\n      *piLast = iChild;\n      piLast = 0;\n    }\n\n    iChild++;\n  };\n\n  if( piFirst ) *piFirst = iChild;\n  if( piLast ) *piLast = iChild;\n\n finish_scan:\n  sqlite3_free(zBuffer);\n  return rc;\n}\n\n\n/*\n** The buffer pointed to by argument zNode (size nNode bytes) contains an\n** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)\n** contains a term. This function searches the sub-tree headed by the zNode\n** node for the range of leaf nodes that may contain the specified term\n** or terms for which the specified term is a prefix.\n**\n** If piLeaf is not NULL, then *piLeaf is set to the blockid of the \n** left-most leaf node in the tree that may contain the specified term.\n** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the\n** right-most leaf node that may contain a term for which the specified\n** term is a prefix.\n**\n** It is possible that the range of returned leaf nodes does not contain \n** the specified term or any terms for which it is a prefix. However, if the \n** segment does contain any such terms, they are stored within the identified\n** range. Because this function only inspects interior segment nodes (and\n** never loads leaf nodes into memory), it is not possible to be sure.\n**\n** If an error occurs, an error code other than SQLITE_OK is returned.\n*/ \nstatic int fts3SelectLeaf(\n  Fts3Table *p,                   /* Virtual table handle */\n  const char *zTerm,              /* Term to select leaves for */\n  int nTerm,                      /* Size of term zTerm in bytes */\n  const char *zNode,              /* Buffer containing segment interior node */\n  int nNode,                      /* Size of buffer at zNode */\n  sqlite3_int64 *piLeaf,          /* Selected leaf node */\n  sqlite3_int64 *piLeaf2          /* Selected leaf node */\n){\n  int rc = SQLITE_OK;             /* Return code */\n  int iHeight;                    /* Height of this node in tree */\n\n  assert( piLeaf || piLeaf2 );\n\n  fts3GetVarint32(zNode, &iHeight);\n  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);\n  assert_fts3_nc( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );\n\n  if( rc==SQLITE_OK && iHeight>1 ){\n    char *zBlob = 0;              /* Blob read from %_segments table */\n    int nBlob = 0;                /* Size of zBlob in bytes */\n\n    if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){\n      rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);\n      if( rc==SQLITE_OK ){\n        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);\n      }\n      sqlite3_free(zBlob);\n      piLeaf = 0;\n      zBlob = 0;\n    }\n\n    if( rc==SQLITE_OK ){\n      rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);\n    }\n    if( rc==SQLITE_OK ){\n      int iNewHeight = 0;\n      fts3GetVarint32(zBlob, &iNewHeight);\n      if( iNewHeight>=iHeight ){\n        rc = FTS_CORRUPT_VTAB;\n      }else{\n        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);\n      }\n    }\n    sqlite3_free(zBlob);\n  }\n\n  return rc;\n}\n\n/*\n** This function is used to create delta-encoded serialized lists of FTS3 \n** varints. Each call to this function appends a single varint to a list.\n*/\nstatic void fts3PutDeltaVarint(\n  char **pp,                      /* IN/OUT: Output pointer */\n  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */\n  sqlite3_int64 iVal              /* Write this value to the list */\n){\n  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );\n  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);\n  *piPrev = iVal;\n}\n\n/*\n** When this function is called, *ppPoslist is assumed to point to the \n** start of a position-list. After it returns, *ppPoslist points to the\n** first byte after the position-list.\n**\n** A position list is list of positions (delta encoded) and columns for \n** a single document record of a doclist.  So, in other words, this\n** routine advances *ppPoslist so that it points to the next docid in\n** the doclist, or to the first byte past the end of the doclist.\n**\n** If pp is not NULL, then the contents of the position list are copied\n** to *pp. *pp is set to point to the first byte past the last byte copied\n** before this function returns.\n*/\nstatic void fts3PoslistCopy(char **pp, char **ppPoslist){\n  char *pEnd = *ppPoslist;\n  char c = 0;\n\n  /* The end of a position list is marked by a zero encoded as an FTS3 \n  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by\n  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail\n  ** of some other, multi-byte, value.\n  **\n  ** The following while-loop moves pEnd to point to the first byte that is not \n  ** immediately preceded by a byte with the 0x80 bit set. Then increments\n  ** pEnd once more so that it points to the byte immediately following the\n  ** last byte in the position-list.\n  */\n  while( *pEnd | c ){\n    c = *pEnd++ & 0x80;\n    testcase( c!=0 && (*pEnd)==0 );\n  }\n  pEnd++;  /* Advance past the POS_END terminator byte */\n\n  if( pp ){\n    int n = (int)(pEnd - *ppPoslist);\n    char *p = *pp;\n    memcpy(p, *ppPoslist, n);\n    p += n;\n    *pp = p;\n  }\n  *ppPoslist = pEnd;\n}\n\n/*\n** When this function is called, *ppPoslist is assumed to point to the \n** start of a column-list. After it returns, *ppPoslist points to the\n** to the terminator (POS_COLUMN or POS_END) byte of the column-list.\n**\n** A column-list is list of delta-encoded positions for a single column\n** within a single document within a doclist.\n**\n** The column-list is terminated either by a POS_COLUMN varint (1) or\n** a POS_END varint (0).  This routine leaves *ppPoslist pointing to\n** the POS_COLUMN or POS_END that terminates the column-list.\n**\n** If pp is not NULL, then the contents of the column-list are copied\n** to *pp. *pp is set to point to the first byte past the last byte copied\n** before this function returns.  The POS_COLUMN or POS_END terminator\n** is not copied into *pp.\n*/\nstatic void fts3ColumnlistCopy(char **pp, char **ppPoslist){\n  char *pEnd = *ppPoslist;\n  char c = 0;\n\n  /* A column-list is terminated by either a 0x01 or 0x00 byte that is\n  ** not part of a multi-byte varint.\n  */\n  while( 0xFE & (*pEnd | c) ){\n    c = *pEnd++ & 0x80;\n    testcase( c!=0 && ((*pEnd)&0xfe)==0 );\n  }\n  if( pp ){\n    int n = (int)(pEnd - *ppPoslist);\n    char *p = *pp;\n    memcpy(p, *ppPoslist, n);\n    p += n;\n    *pp = p;\n  }\n  *ppPoslist = pEnd;\n}\n\n/*\n** Value used to signify the end of an position-list. This must be\n** as large or larger than any value that might appear on the\n** position-list, even a position list that has been corrupted.\n*/\n#define POSITION_LIST_END LARGEST_INT64\n\n/*\n** This function is used to help parse position-lists. When this function is\n** called, *pp may point to the start of the next varint in the position-list\n** being parsed, or it may point to 1 byte past the end of the position-list\n** (in which case **pp will be a terminator bytes POS_END (0) or\n** (1)).\n**\n** If *pp points past the end of the current position-list, set *pi to \n** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,\n** increment the current value of *pi by the value read, and set *pp to\n** point to the next value before returning.\n**\n** Before calling this routine *pi must be initialized to the value of\n** the previous position, or zero if we are reading the first position\n** in the position-list.  Because positions are delta-encoded, the value\n** of the previous position is needed in order to compute the value of\n** the next position.\n*/\nstatic void fts3ReadNextPos(\n  char **pp,                    /* IN/OUT: Pointer into position-list buffer */\n  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */\n){\n  if( (**pp)&0xFE ){\n    int iVal;\n    *pp += fts3GetVarint32((*pp), &iVal);\n    *pi += iVal;\n    *pi -= 2;\n  }else{\n    *pi = POSITION_LIST_END;\n  }\n}\n\n/*\n** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by\n** the value of iCol encoded as a varint to *pp.   This will start a new\n** column list.\n**\n** Set *pp to point to the byte just after the last byte written before \n** returning (do not modify it if iCol==0). Return the total number of bytes\n** written (0 if iCol==0).\n*/\nstatic int fts3PutColNumber(char **pp, int iCol){\n  int n = 0;                      /* Number of bytes written */\n  if( iCol ){\n    char *p = *pp;                /* Output pointer */\n    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);\n    *p = 0x01;\n    *pp = &p[n];\n  }\n  return n;\n}\n\n/*\n** Compute the union of two position lists.  The output written\n** into *pp contains all positions of both *pp1 and *pp2 in sorted\n** order and with any duplicates removed.  All pointers are\n** updated appropriately.   The caller is responsible for insuring\n** that there is enough space in *pp to hold the complete output.\n*/\nstatic int fts3PoslistMerge(\n  char **pp,                      /* Output buffer */\n  char **pp1,                     /* Left input list */\n  char **pp2                      /* Right input list */\n){\n  char *p = *pp;\n  char *p1 = *pp1;\n  char *p2 = *pp2;\n\n  while( *p1 || *p2 ){\n    int iCol1;         /* The current column index in pp1 */\n    int iCol2;         /* The current column index in pp2 */\n\n    if( *p1==POS_COLUMN ){ \n      fts3GetVarint32(&p1[1], &iCol1);\n      if( iCol1==0 ) return FTS_CORRUPT_VTAB;\n    }\n    else if( *p1==POS_END ) iCol1 = 0x7fffffff;\n    else iCol1 = 0;\n\n    if( *p2==POS_COLUMN ){\n      fts3GetVarint32(&p2[1], &iCol2);\n      if( iCol2==0 ) return FTS_CORRUPT_VTAB;\n    }\n    else if( *p2==POS_END ) iCol2 = 0x7fffffff;\n    else iCol2 = 0;\n\n    if( iCol1==iCol2 ){\n      sqlite3_int64 i1 = 0;       /* Last position from pp1 */\n      sqlite3_int64 i2 = 0;       /* Last position from pp2 */\n      sqlite3_int64 iPrev = 0;\n      int n = fts3PutColNumber(&p, iCol1);\n      p1 += n;\n      p2 += n;\n\n      /* At this point, both p1 and p2 point to the start of column-lists\n      ** for the same column (the column with index iCol1 and iCol2).\n      ** A column-list is a list of non-negative delta-encoded varints, each \n      ** incremented by 2 before being stored. Each list is terminated by a\n      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists\n      ** and writes the results to buffer p. p is left pointing to the byte\n      ** after the list written. No terminator (POS_END or POS_COLUMN) is\n      ** written to the output.\n      */\n      fts3GetDeltaVarint(&p1, &i1);\n      fts3GetDeltaVarint(&p2, &i2);\n      if( i1<2 || i2<2 ){\n        break;\n      }\n      do {\n        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); \n        iPrev -= 2;\n        if( i1==i2 ){\n          fts3ReadNextPos(&p1, &i1);\n          fts3ReadNextPos(&p2, &i2);\n        }else if( i1<i2 ){\n          fts3ReadNextPos(&p1, &i1);\n        }else{\n          fts3ReadNextPos(&p2, &i2);\n        }\n      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );\n    }else if( iCol1<iCol2 ){\n      p1 += fts3PutColNumber(&p, iCol1);\n      fts3ColumnlistCopy(&p, &p1);\n    }else{\n      p2 += fts3PutColNumber(&p, iCol2);\n      fts3ColumnlistCopy(&p, &p2);\n    }\n  }\n\n  *p++ = POS_END;\n  *pp = p;\n  *pp1 = p1 + 1;\n  *pp2 = p2 + 1;\n  return SQLITE_OK;\n}\n\n/*\n** This function is used to merge two position lists into one. When it is\n** called, *pp1 and *pp2 must both point to position lists. A position-list is\n** the part of a doclist that follows each document id. For example, if a row\n** contains:\n**\n**     'a b c'|'x y z'|'a b b a'\n**\n** Then the position list for this row for token 'b' would consist of:\n**\n**     0x02 0x01 0x02 0x03 0x03 0x00\n**\n** When this function returns, both *pp1 and *pp2 are left pointing to the\n** byte following the 0x00 terminator of their respective position lists.\n**\n** If isSaveLeft is 0, an entry is added to the output position list for \n** each position in *pp2 for which there exists one or more positions in\n** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.\n** when the *pp1 token appears before the *pp2 token, but not more than nToken\n** slots before it.\n**\n** e.g. nToken==1 searches for adjacent positions.\n*/\nstatic int fts3PoslistPhraseMerge(\n  char **pp,                      /* IN/OUT: Preallocated output buffer */\n  int nToken,                     /* Maximum difference in token positions */\n  int isSaveLeft,                 /* Save the left position */\n  int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */\n  char **pp1,                     /* IN/OUT: Left input list */\n  char **pp2                      /* IN/OUT: Right input list */\n){\n  char *p = *pp;\n  char *p1 = *pp1;\n  char *p2 = *pp2;\n  int iCol1 = 0;\n  int iCol2 = 0;\n\n  /* Never set both isSaveLeft and isExact for the same invocation. */\n  assert( isSaveLeft==0 || isExact==0 );\n\n  assert_fts3_nc( p!=0 && *p1!=0 && *p2!=0 );\n  if( *p1==POS_COLUMN ){ \n    p1++;\n    p1 += fts3GetVarint32(p1, &iCol1);\n  }\n  if( *p2==POS_COLUMN ){ \n    p2++;\n    p2 += fts3GetVarint32(p2, &iCol2);\n  }\n\n  while( 1 ){\n    if( iCol1==iCol2 ){\n      char *pSave = p;\n      sqlite3_int64 iPrev = 0;\n      sqlite3_int64 iPos1 = 0;\n      sqlite3_int64 iPos2 = 0;\n\n      if( iCol1 ){\n        *p++ = POS_COLUMN;\n        p += sqlite3Fts3PutVarint(p, iCol1);\n      }\n\n      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;\n      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;\n      if( iPos1<0 || iPos2<0 ) break;\n\n      while( 1 ){\n        if( iPos2==iPos1+nToken \n         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) \n        ){\n          sqlite3_int64 iSave;\n          iSave = isSaveLeft ? iPos1 : iPos2;\n          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;\n          pSave = 0;\n          assert( p );\n        }\n        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){\n          if( (*p2&0xFE)==0 ) break;\n          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;\n        }else{\n          if( (*p1&0xFE)==0 ) break;\n          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;\n        }\n      }\n\n      if( pSave ){\n        assert( pp && p );\n        p = pSave;\n      }\n\n      fts3ColumnlistCopy(0, &p1);\n      fts3ColumnlistCopy(0, &p2);\n      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );\n      if( 0==*p1 || 0==*p2 ) break;\n\n      p1++;\n      p1 += fts3GetVarint32(p1, &iCol1);\n      p2++;\n      p2 += fts3GetVarint32(p2, &iCol2);\n    }\n\n    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of\n    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the\n    ** end of the position list, or the 0x01 that precedes the next \n    ** column-number in the position list. \n    */\n    else if( iCol1<iCol2 ){\n      fts3ColumnlistCopy(0, &p1);\n      if( 0==*p1 ) break;\n      p1++;\n      p1 += fts3GetVarint32(p1, &iCol1);\n    }else{\n      fts3ColumnlistCopy(0, &p2);\n      if( 0==*p2 ) break;\n      p2++;\n      p2 += fts3GetVarint32(p2, &iCol2);\n    }\n  }\n\n  fts3PoslistCopy(0, &p2);\n  fts3PoslistCopy(0, &p1);\n  *pp1 = p1;\n  *pp2 = p2;\n  if( *pp==p ){\n    return 0;\n  }\n  *p++ = 0x00;\n  *pp = p;\n  return 1;\n}\n\n/*\n** Merge two position-lists as required by the NEAR operator. The argument\n** position lists correspond to the left and right phrases of an expression \n** like:\n**\n**     \"phrase 1\" NEAR \"phrase number 2\"\n**\n** Position list *pp1 corresponds to the left-hand side of the NEAR \n** expression and *pp2 to the right. As usual, the indexes in the position \n** lists are the offsets of the last token in each phrase (tokens \"1\" and \"2\" \n** in the example above).\n**\n** The output position list - written to *pp - is a copy of *pp2 with those\n** entries that are not sufficiently NEAR entries in *pp1 removed.\n*/\nstatic int fts3PoslistNearMerge(\n  char **pp,                      /* Output buffer */\n  char *aTmp,                     /* Temporary buffer space */\n  int nRight,                     /* Maximum difference in token positions */\n  int nLeft,                      /* Maximum difference in token positions */\n  char **pp1,                     /* IN/OUT: Left input list */\n  char **pp2                      /* IN/OUT: Right input list */\n){\n  char *p1 = *pp1;\n  char *p2 = *pp2;\n\n  char *pTmp1 = aTmp;\n  char *pTmp2;\n  char *aTmp2;\n  int res = 1;\n\n  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);\n  aTmp2 = pTmp2 = pTmp1;\n  *pp1 = p1;\n  *pp2 = p2;\n  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);\n  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){\n    fts3PoslistMerge(pp, &aTmp, &aTmp2);\n  }else if( pTmp1!=aTmp ){\n    fts3PoslistCopy(pp, &aTmp);\n  }else if( pTmp2!=aTmp2 ){\n    fts3PoslistCopy(pp, &aTmp2);\n  }else{\n    res = 0;\n  }\n\n  return res;\n}\n\n/* \n** An instance of this function is used to merge together the (potentially\n** large number of) doclists for each term that matches a prefix query.\n** See function fts3TermSelectMerge() for details.\n*/\ntypedef struct TermSelect TermSelect;\nstruct TermSelect {\n  char *aaOutput[16];             /* Malloc'd output buffers */\n  int anOutput[16];               /* Size each output buffer in bytes */\n};\n\n/*\n** This function is used to read a single varint from a buffer. Parameter\n** pEnd points 1 byte past the end of the buffer. When this function is\n** called, if *pp points to pEnd or greater, then the end of the buffer\n** has been reached. In this case *pp is set to 0 and the function returns.\n**\n** If *pp does not point to or past pEnd, then a single varint is read\n** from *pp. *pp is then set to point 1 byte past the end of the read varint.\n**\n** If bDescIdx is false, the value read is added to *pVal before returning.\n** If it is true, the value read is subtracted from *pVal before this \n** function returns.\n*/\nstatic void fts3GetDeltaVarint3(\n  char **pp,                      /* IN/OUT: Point to read varint from */\n  char *pEnd,                     /* End of buffer */\n  int bDescIdx,                   /* True if docids are descending */\n  sqlite3_int64 *pVal             /* IN/OUT: Integer value */\n){\n  if( *pp>=pEnd ){\n    *pp = 0;\n  }else{\n    u64 iVal;\n    *pp += sqlite3Fts3GetVarintU(*pp, &iVal);\n    if( bDescIdx ){\n      *pVal = (i64)((u64)*pVal - iVal);\n    }else{\n      *pVal = (i64)((u64)*pVal + iVal);\n    }\n  }\n}\n\n/*\n** This function is used to write a single varint to a buffer. The varint\n** is written to *pp. Before returning, *pp is set to point 1 byte past the\n** end of the value written.\n**\n** If *pbFirst is zero when this function is called, the value written to\n** the buffer is that of parameter iVal. \n**\n** If *pbFirst is non-zero when this function is called, then the value \n** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)\n** (if bDescIdx is non-zero).\n**\n** Before returning, this function always sets *pbFirst to 1 and *piPrev\n** to the value of parameter iVal.\n*/\nstatic void fts3PutDeltaVarint3(\n  char **pp,                      /* IN/OUT: Output pointer */\n  int bDescIdx,                   /* True for descending docids */\n  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */\n  int *pbFirst,                   /* IN/OUT: True after first int written */\n  sqlite3_int64 iVal              /* Write this value to the list */\n){\n  sqlite3_uint64 iWrite;\n  if( bDescIdx==0 || *pbFirst==0 ){\n    assert_fts3_nc( *pbFirst==0 || iVal>=*piPrev );\n    iWrite = (u64)iVal - (u64)*piPrev;\n  }else{\n    assert_fts3_nc( *piPrev>=iVal );\n    iWrite = (u64)*piPrev - (u64)iVal;\n  }\n  assert( *pbFirst || *piPrev==0 );\n  assert_fts3_nc( *pbFirst==0 || iWrite>0 );\n  *pp += sqlite3Fts3PutVarint(*pp, iWrite);\n  *piPrev = iVal;\n  *pbFirst = 1;\n}\n\n\n/*\n** This macro is used by various functions that merge doclists. The two\n** arguments are 64-bit docid values. If the value of the stack variable\n** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). \n** Otherwise, (i2-i1).\n**\n** Using this makes it easier to write code that can merge doclists that are\n** sorted in either ascending or descending order.\n*/\n/* #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i64)((u64)i1-i2)) */\n#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1>i2?1:((i1==i2)?0:-1)))\n\n/*\n** This function does an \"OR\" merge of two doclists (output contains all\n** positions contained in either argument doclist). If the docids in the \n** input doclists are sorted in ascending order, parameter bDescDoclist\n** should be false. If they are sorted in ascending order, it should be\n** passed a non-zero value.\n**\n** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer\n** containing the output doclist and SQLITE_OK is returned. In this case\n** *pnOut is set to the number of bytes in the output doclist.\n**\n** If an error occurs, an SQLite error code is returned. The output values\n** are undefined in this case.\n*/\nstatic int fts3DoclistOrMerge(\n  int bDescDoclist,               /* True if arguments are desc */\n  char *a1, int n1,               /* First doclist */\n  char *a2, int n2,               /* Second doclist */\n  char **paOut, int *pnOut        /* OUT: Malloc'd doclist */\n){\n  int rc = SQLITE_OK;\n  sqlite3_int64 i1 = 0;\n  sqlite3_int64 i2 = 0;\n  sqlite3_int64 iPrev = 0;\n  char *pEnd1 = &a1[n1];\n  char *pEnd2 = &a2[n2];\n  char *p1 = a1;\n  char *p2 = a2;\n  char *p;\n  char *aOut;\n  int bFirstOut = 0;\n\n  *paOut = 0;\n  *pnOut = 0;\n\n  /* Allocate space for the output. Both the input and output doclists\n  ** are delta encoded. If they are in ascending order (bDescDoclist==0),\n  ** then the first docid in each list is simply encoded as a varint. For\n  ** each subsequent docid, the varint stored is the difference between the\n  ** current and previous docid (a positive number - since the list is in\n  ** ascending order).\n  **\n  ** The first docid written to the output is therefore encoded using the \n  ** same number of bytes as it is in whichever of the input lists it is\n  ** read from. And each subsequent docid read from the same input list \n  ** consumes either the same or less bytes as it did in the input (since\n  ** the difference between it and the previous value in the output must\n  ** be a positive value less than or equal to the delta value read from \n  ** the input list). The same argument applies to all but the first docid\n  ** read from the 'other' list. And to the contents of all position lists\n  ** that will be copied and merged from the input to the output.\n  **\n  ** However, if the first docid copied to the output is a negative number,\n  ** then the encoding of the first docid from the 'other' input list may\n  ** be larger in the output than it was in the input (since the delta value\n  ** may be a larger positive integer than the actual docid).\n  **\n  ** The space required to store the output is therefore the sum of the\n  ** sizes of the two inputs, plus enough space for exactly one of the input\n  ** docids to grow. \n  **\n  ** A symetric argument may be made if the doclists are in descending \n  ** order.\n  */\n  aOut = sqlite3_malloc64((i64)n1+n2+FTS3_VARINT_MAX-1+FTS3_BUFFER_PADDING);\n  if( !aOut ) return SQLITE_NOMEM;\n\n  p = aOut;\n  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);\n  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);\n  while( p1 || p2 ){\n    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);\n\n    if( p2 && p1 && iDiff==0 ){\n      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);\n      rc = fts3PoslistMerge(&p, &p1, &p2);\n      if( rc ) break;\n      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);\n      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);\n    }else if( !p2 || (p1 && iDiff<0) ){\n      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);\n      fts3PoslistCopy(&p, &p1);\n      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);\n    }else{\n      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);\n      fts3PoslistCopy(&p, &p2);\n      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);\n    }\n    \n    assert( (p-aOut)<=((p1?(p1-a1):n1)+(p2?(p2-a2):n2)+FTS3_VARINT_MAX-1) );\n  }\n\n  if( rc!=SQLITE_OK ){\n    sqlite3_free(aOut);\n    p = aOut = 0;\n  }else{\n    assert( (p-aOut)<=n1+n2+FTS3_VARINT_MAX-1 );\n    memset(&aOut[(p-aOut)], 0, FTS3_BUFFER_PADDING);\n  }\n  *paOut = aOut;\n  *pnOut = (int)(p-aOut);\n  return rc;\n}\n\n/*\n** This function does a \"phrase\" merge of two doclists. In a phrase merge,\n** the output contains a copy of each position from the right-hand input\n** doclist for which there is a position in the left-hand input doclist\n** exactly nDist tokens before it.\n**\n** If the docids in the input doclists are sorted in ascending order,\n** parameter bDescDoclist should be false. If they are sorted in ascending \n** order, it should be passed a non-zero value.\n**\n** The right-hand input doclist is overwritten by this function.\n*/\nstatic int fts3DoclistPhraseMerge(\n  int bDescDoclist,               /* True if arguments are desc */\n  int nDist,                      /* Distance from left to right (1=adjacent) */\n  char *aLeft, int nLeft,         /* Left doclist */\n  char **paRight, int *pnRight    /* IN/OUT: Right/output doclist */\n){\n  sqlite3_int64 i1 = 0;\n  sqlite3_int64 i2 = 0;\n  sqlite3_int64 iPrev = 0;\n  char *aRight = *paRight;\n  char *pEnd1 = &aLeft[nLeft];\n  char *pEnd2 = &aRight[*pnRight];\n  char *p1 = aLeft;\n  char *p2 = aRight;\n  char *p;\n  int bFirstOut = 0;\n  char *aOut;\n\n  assert( nDist>0 );\n  if( bDescDoclist ){\n    aOut = sqlite3_malloc64((sqlite3_int64)*pnRight + FTS3_VARINT_MAX);\n    if( aOut==0 ) return SQLITE_NOMEM;\n  }else{\n    aOut = aRight;\n  }\n  p = aOut;\n\n  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);\n  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);\n\n  while( p1 && p2 ){\n    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);\n    if( iDiff==0 ){\n      char *pSave = p;\n      sqlite3_int64 iPrevSave = iPrev;\n      int bFirstOutSave = bFirstOut;\n\n      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);\n      if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){\n        p = pSave;\n        iPrev = iPrevSave;\n        bFirstOut = bFirstOutSave;\n      }\n      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);\n      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);\n    }else if( iDiff<0 ){\n      fts3PoslistCopy(0, &p1);\n      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);\n    }else{\n      fts3PoslistCopy(0, &p2);\n      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);\n    }\n  }\n\n  *pnRight = (int)(p - aOut);\n  if( bDescDoclist ){\n    sqlite3_free(aRight);\n    *paRight = aOut;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Argument pList points to a position list nList bytes in size. This\n** function checks to see if the position list contains any entries for\n** a token in position 0 (of any column). If so, it writes argument iDelta\n** to the output buffer pOut, followed by a position list consisting only\n** of the entries from pList at position 0, and terminated by an 0x00 byte.\n** The value returned is the number of bytes written to pOut (if any).\n*/\nSQLITE_PRIVATE int sqlite3Fts3FirstFilter(\n  sqlite3_int64 iDelta,           /* Varint that may be written to pOut */\n  char *pList,                    /* Position list (no 0x00 term) */\n  int nList,                      /* Size of pList in bytes */\n  char *pOut                      /* Write output here */\n){\n  int nOut = 0;\n  int bWritten = 0;               /* True once iDelta has been written */\n  char *p = pList;\n  char *pEnd = &pList[nList];\n\n  if( *p!=0x01 ){\n    if( *p==0x02 ){\n      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);\n      pOut[nOut++] = 0x02;\n      bWritten = 1;\n    }\n    fts3ColumnlistCopy(0, &p);\n  }\n\n  while( p<pEnd ){\n    sqlite3_int64 iCol;\n    p++;\n    p += sqlite3Fts3GetVarint(p, &iCol);\n    if( *p==0x02 ){\n      if( bWritten==0 ){\n        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);\n        bWritten = 1;\n      }\n      pOut[nOut++] = 0x01;\n      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);\n      pOut[nOut++] = 0x02;\n    }\n    fts3ColumnlistCopy(0, &p);\n  }\n  if( bWritten ){\n    pOut[nOut++] = 0x00;\n  }\n\n  return nOut;\n}\n\n\n/*\n** Merge all doclists in the TermSelect.aaOutput[] array into a single\n** doclist stored in TermSelect.aaOutput[0]. If successful, delete all\n** other doclists (except the aaOutput[0] one) and return SQLITE_OK.\n**\n** If an OOM error occurs, return SQLITE_NOMEM. In this case it is\n** the responsibility of the caller to free any doclists left in the\n** TermSelect.aaOutput[] array.\n*/\nstatic int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){\n  char *aOut = 0;\n  int nOut = 0;\n  int i;\n\n  /* Loop through the doclists in the aaOutput[] array. Merge them all\n  ** into a single doclist.\n  */\n  for(i=0; i<SizeofArray(pTS->aaOutput); i++){\n    if( pTS->aaOutput[i] ){\n      if( !aOut ){\n        aOut = pTS->aaOutput[i];\n        nOut = pTS->anOutput[i];\n        pTS->aaOutput[i] = 0;\n      }else{\n        int nNew;\n        char *aNew;\n\n        int rc = fts3DoclistOrMerge(p->bDescIdx, \n            pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew\n        );\n        if( rc!=SQLITE_OK ){\n          sqlite3_free(aOut);\n          return rc;\n        }\n\n        sqlite3_free(pTS->aaOutput[i]);\n        sqlite3_free(aOut);\n        pTS->aaOutput[i] = 0;\n        aOut = aNew;\n        nOut = nNew;\n      }\n    }\n  }\n\n  pTS->aaOutput[0] = aOut;\n  pTS->anOutput[0] = nOut;\n  return SQLITE_OK;\n}\n\n/*\n** Merge the doclist aDoclist/nDoclist into the TermSelect object passed\n** as the first argument. The merge is an \"OR\" merge (see function\n** fts3DoclistOrMerge() for details).\n**\n** This function is called with the doclist for each term that matches\n** a queried prefix. It merges all these doclists into one, the doclist\n** for the specified prefix. Since there can be a very large number of\n** doclists to merge, the merging is done pair-wise using the TermSelect\n** object.\n**\n** This function returns SQLITE_OK if the merge is successful, or an\n** SQLite error code (SQLITE_NOMEM) if an error occurs.\n*/\nstatic int fts3TermSelectMerge(\n  Fts3Table *p,                   /* FTS table handle */\n  TermSelect *pTS,                /* TermSelect object to merge into */\n  char *aDoclist,                 /* Pointer to doclist */\n  int nDoclist                    /* Size of aDoclist in bytes */\n){\n  if( pTS->aaOutput[0]==0 ){\n    /* If this is the first term selected, copy the doclist to the output\n    ** buffer using memcpy(). \n    **\n    ** Add FTS3_VARINT_MAX bytes of unused space to the end of the \n    ** allocation. This is so as to ensure that the buffer is big enough\n    ** to hold the current doclist AND'd with any other doclist. If the\n    ** doclists are stored in order=ASC order, this padding would not be\n    ** required (since the size of [doclistA AND doclistB] is always less\n    ** than or equal to the size of [doclistA] in that case). But this is\n    ** not true for order=DESC. For example, a doclist containing (1, -1) \n    ** may be smaller than (-1), as in the first example the -1 may be stored\n    ** as a single-byte delta, whereas in the second it must be stored as a\n    ** FTS3_VARINT_MAX byte varint.\n    **\n    ** Similar padding is added in the fts3DoclistOrMerge() function.\n    */\n    pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);\n    pTS->anOutput[0] = nDoclist;\n    if( pTS->aaOutput[0] ){\n      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);\n      memset(&pTS->aaOutput[0][nDoclist], 0, FTS3_VARINT_MAX);\n    }else{\n      return SQLITE_NOMEM;\n    }\n  }else{\n    char *aMerge = aDoclist;\n    int nMerge = nDoclist;\n    int iOut;\n\n    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){\n      if( pTS->aaOutput[iOut]==0 ){\n        assert( iOut>0 );\n        pTS->aaOutput[iOut] = aMerge;\n        pTS->anOutput[iOut] = nMerge;\n        break;\n      }else{\n        char *aNew;\n        int nNew;\n\n        int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, \n            pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew\n        );\n        if( rc!=SQLITE_OK ){\n          if( aMerge!=aDoclist ) sqlite3_free(aMerge);\n          return rc;\n        }\n\n        if( aMerge!=aDoclist ) sqlite3_free(aMerge);\n        sqlite3_free(pTS->aaOutput[iOut]);\n        pTS->aaOutput[iOut] = 0;\n  \n        aMerge = aNew;\n        nMerge = nNew;\n        if( (iOut+1)==SizeofArray(pTS->aaOutput) ){\n          pTS->aaOutput[iOut] = aMerge;\n          pTS->anOutput[iOut] = nMerge;\n        }\n      }\n    }\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Append SegReader object pNew to the end of the pCsr->apSegment[] array.\n*/\nstatic int fts3SegReaderCursorAppend(\n  Fts3MultiSegReader *pCsr, \n  Fts3SegReader *pNew\n){\n  if( (pCsr->nSegment%16)==0 ){\n    Fts3SegReader **apNew;\n    sqlite3_int64 nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);\n    apNew = (Fts3SegReader **)sqlite3_realloc64(pCsr->apSegment, nByte);\n    if( !apNew ){\n      sqlite3Fts3SegReaderFree(pNew);\n      return SQLITE_NOMEM;\n    }\n    pCsr->apSegment = apNew;\n  }\n  pCsr->apSegment[pCsr->nSegment++] = pNew;\n  return SQLITE_OK;\n}\n\n/*\n** Add seg-reader objects to the Fts3MultiSegReader object passed as the\n** 8th argument.\n**\n** This function returns SQLITE_OK if successful, or an SQLite error code\n** otherwise.\n*/\nstatic int fts3SegReaderCursor(\n  Fts3Table *p,                   /* FTS3 table handle */\n  int iLangid,                    /* Language id */\n  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */\n  int iLevel,                     /* Level of segments to scan */\n  const char *zTerm,              /* Term to query for */\n  int nTerm,                      /* Size of zTerm in bytes */\n  int isPrefix,                   /* True for a prefix search */\n  int isScan,                     /* True to scan from zTerm to EOF */\n  Fts3MultiSegReader *pCsr        /* Cursor object to populate */\n){\n  int rc = SQLITE_OK;             /* Error code */\n  sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */\n  int rc2;                        /* Result of sqlite3_reset() */\n\n  /* If iLevel is less than 0 and this is not a scan, include a seg-reader \n  ** for the pending-terms. If this is a scan, then this call must be being\n  ** made by an fts4aux module, not an FTS table. In this case calling\n  ** Fts3SegReaderPending might segfault, as the data structures used by \n  ** fts4aux are not completely populated. So it's easiest to filter these\n  ** calls out here.  */\n  if( iLevel<0 && p->aIndex && p->iPrevLangid==iLangid ){\n    Fts3SegReader *pSeg = 0;\n    rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);\n    if( rc==SQLITE_OK && pSeg ){\n      rc = fts3SegReaderCursorAppend(pCsr, pSeg);\n    }\n  }\n\n  if( iLevel!=FTS3_SEGCURSOR_PENDING ){\n    if( rc==SQLITE_OK ){\n      rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);\n    }\n\n    while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){\n      Fts3SegReader *pSeg = 0;\n\n      /* Read the values returned by the SELECT into local variables. */\n      sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);\n      sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);\n      sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);\n      int nRoot = sqlite3_column_bytes(pStmt, 4);\n      char const *zRoot = sqlite3_column_blob(pStmt, 4);\n\n      /* If zTerm is not NULL, and this segment is not stored entirely on its\n      ** root node, the range of leaves scanned can be reduced. Do this. */\n      if( iStartBlock && zTerm && zRoot ){\n        sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);\n        rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);\n        if( rc!=SQLITE_OK ) goto finished;\n        if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;\n      }\n \n      rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, \n          (isPrefix==0 && isScan==0),\n          iStartBlock, iLeavesEndBlock, \n          iEndBlock, zRoot, nRoot, &pSeg\n      );\n      if( rc!=SQLITE_OK ) goto finished;\n      rc = fts3SegReaderCursorAppend(pCsr, pSeg);\n    }\n  }\n\n finished:\n  rc2 = sqlite3_reset(pStmt);\n  if( rc==SQLITE_DONE ) rc = rc2;\n\n  return rc;\n}\n\n/*\n** Set up a cursor object for iterating through a full-text index or a \n** single level therein.\n*/\nSQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(\n  Fts3Table *p,                   /* FTS3 table handle */\n  int iLangid,                    /* Language-id to search */\n  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */\n  int iLevel,                     /* Level of segments to scan */\n  const char *zTerm,              /* Term to query for */\n  int nTerm,                      /* Size of zTerm in bytes */\n  int isPrefix,                   /* True for a prefix search */\n  int isScan,                     /* True to scan from zTerm to EOF */\n  Fts3MultiSegReader *pCsr       /* Cursor object to populate */\n){\n  assert( iIndex>=0 && iIndex<p->nIndex );\n  assert( iLevel==FTS3_SEGCURSOR_ALL\n      ||  iLevel==FTS3_SEGCURSOR_PENDING \n      ||  iLevel>=0\n  );\n  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );\n  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );\n  assert( isPrefix==0 || isScan==0 );\n\n  memset(pCsr, 0, sizeof(Fts3MultiSegReader));\n  return fts3SegReaderCursor(\n      p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr\n  );\n}\n\n/*\n** In addition to its current configuration, have the Fts3MultiSegReader\n** passed as the 4th argument also scan the doclist for term zTerm/nTerm.\n**\n** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.\n*/\nstatic int fts3SegReaderCursorAddZero(\n  Fts3Table *p,                   /* FTS virtual table handle */\n  int iLangid,\n  const char *zTerm,              /* Term to scan doclist of */\n  int nTerm,                      /* Number of bytes in zTerm */\n  Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */\n){\n  return fts3SegReaderCursor(p, \n      iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr\n  );\n}\n\n/*\n** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,\n** if isPrefix is true, to scan the doclist for all terms for which \n** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write\n** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return\n** an SQLite error code.\n**\n** It is the responsibility of the caller to free this object by eventually\n** passing it to fts3SegReaderCursorFree() \n**\n** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.\n** Output parameter *ppSegcsr is set to 0 if an error occurs.\n*/\nstatic int fts3TermSegReaderCursor(\n  Fts3Cursor *pCsr,               /* Virtual table cursor handle */\n  const char *zTerm,              /* Term to query for */\n  int nTerm,                      /* Size of zTerm in bytes */\n  int isPrefix,                   /* True for a prefix search */\n  Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */\n){\n  Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */\n  int rc = SQLITE_NOMEM;          /* Return code */\n\n  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));\n  if( pSegcsr ){\n    int i;\n    int bFound = 0;               /* True once an index has been found */\n    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;\n\n    if( isPrefix ){\n      for(i=1; bFound==0 && i<p->nIndex; i++){\n        if( p->aIndex[i].nPrefix==nTerm ){\n          bFound = 1;\n          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, \n              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr\n          );\n          pSegcsr->bLookup = 1;\n        }\n      }\n\n      for(i=1; bFound==0 && i<p->nIndex; i++){\n        if( p->aIndex[i].nPrefix==nTerm+1 ){\n          bFound = 1;\n          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, \n              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr\n          );\n          if( rc==SQLITE_OK ){\n            rc = fts3SegReaderCursorAddZero(\n                p, pCsr->iLangid, zTerm, nTerm, pSegcsr\n            );\n          }\n        }\n      }\n    }\n\n    if( bFound==0 ){\n      rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, \n          0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr\n      );\n      pSegcsr->bLookup = !isPrefix;\n    }\n  }\n\n  *ppSegcsr = pSegcsr;\n  return rc;\n}\n\n/*\n** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().\n*/\nstatic void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){\n  sqlite3Fts3SegReaderFinish(pSegcsr);\n  sqlite3_free(pSegcsr);\n}\n\n/*\n** This function retrieves the doclist for the specified term (or term\n** prefix) from the database.\n*/\nstatic int fts3TermSelect(\n  Fts3Table *p,                   /* Virtual table handle */\n  Fts3PhraseToken *pTok,          /* Token to query for */\n  int iColumn,                    /* Column to query (or -ve for all columns) */\n  int *pnOut,                     /* OUT: Size of buffer at *ppOut */\n  char **ppOut                    /* OUT: Malloced result buffer */\n){\n  int rc;                         /* Return code */\n  Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */\n  TermSelect tsc;                 /* Object for pair-wise doclist merging */\n  Fts3SegFilter filter;           /* Segment term filter configuration */\n\n  pSegcsr = pTok->pSegcsr;\n  memset(&tsc, 0, sizeof(TermSelect));\n\n  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS\n        | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)\n        | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)\n        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);\n  filter.iCol = iColumn;\n  filter.zTerm = pTok->z;\n  filter.nTerm = pTok->n;\n\n  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);\n  while( SQLITE_OK==rc\n      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) \n  ){\n    rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = fts3TermSelectFinishMerge(p, &tsc);\n  }\n  if( rc==SQLITE_OK ){\n    *ppOut = tsc.aaOutput[0];\n    *pnOut = tsc.anOutput[0];\n  }else{\n    int i;\n    for(i=0; i<SizeofArray(tsc.aaOutput); i++){\n      sqlite3_free(tsc.aaOutput[i]);\n    }\n  }\n\n  fts3SegReaderCursorFree(pSegcsr);\n  pTok->pSegcsr = 0;\n  return rc;\n}\n\n/*\n** This function counts the total number of docids in the doclist stored\n** in buffer aList[], size nList bytes.\n**\n** If the isPoslist argument is true, then it is assumed that the doclist\n** contains a position-list following each docid. Otherwise, it is assumed\n** that the doclist is simply a list of docids stored as delta encoded \n** varints.\n*/\nstatic int fts3DoclistCountDocids(char *aList, int nList){\n  int nDoc = 0;                   /* Return value */\n  if( aList ){\n    char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */\n    char *p = aList;              /* Cursor */\n    while( p<aEnd ){\n      nDoc++;\n      while( (*p++)&0x80 );     /* Skip docid varint */\n      fts3PoslistCopy(0, &p);   /* Skip over position list */\n    }\n  }\n\n  return nDoc;\n}\n\n/*\n** Advance the cursor to the next row in the %_content table that\n** matches the search criteria.  For a MATCH search, this will be\n** the next row that matches. For a full-table scan, this will be\n** simply the next row in the %_content table.  For a docid lookup,\n** this routine simply sets the EOF flag.\n**\n** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned\n** even if we reach end-of-file.  The fts3EofMethod() will be called\n** subsequently to determine whether or not an EOF was hit.\n*/\nstatic int fts3NextMethod(sqlite3_vtab_cursor *pCursor){\n  int rc;\n  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;\n  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){\n    Fts3Table *pTab = (Fts3Table*)pCursor->pVtab;\n    pTab->bLock++;\n    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){\n      pCsr->isEof = 1;\n      rc = sqlite3_reset(pCsr->pStmt);\n    }else{\n      pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);\n      rc = SQLITE_OK;\n    }\n    pTab->bLock--;\n  }else{\n    rc = fts3EvalNext((Fts3Cursor *)pCursor);\n  }\n  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );\n  return rc;\n}\n\n/*\n** If the numeric type of argument pVal is \"integer\", then return it\n** converted to a 64-bit signed integer. Otherwise, return a copy of\n** the second parameter, iDefault.\n*/\nstatic sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){\n  if( pVal ){\n    int eType = sqlite3_value_numeric_type(pVal);\n    if( eType==SQLITE_INTEGER ){\n      return sqlite3_value_int64(pVal);\n    }\n  }\n  return iDefault;\n}\n\n/*\n** This is the xFilter interface for the virtual table.  See\n** the virtual table xFilter method documentation for additional\n** information.\n**\n** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against\n** the %_content table.\n**\n** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry\n** in the %_content table.\n**\n** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The\n** column on the left-hand side of the MATCH operator is column\n** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand\n** side of the MATCH operator.\n*/\nstatic int fts3FilterMethod(\n  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */\n  int idxNum,                     /* Strategy index */\n  const char *idxStr,             /* Unused */\n  int nVal,                       /* Number of elements in apVal */\n  sqlite3_value **apVal           /* Arguments for the indexing scheme */\n){\n  int rc = SQLITE_OK;\n  char *zSql;                     /* SQL statement used to access %_content */\n  int eSearch;\n  Fts3Table *p = (Fts3Table *)pCursor->pVtab;\n  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;\n\n  sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */\n  sqlite3_value *pLangid = 0;     /* The \"langid = ?\" constraint, if any */\n  sqlite3_value *pDocidGe = 0;    /* The \"docid >= ?\" constraint, if any */\n  sqlite3_value *pDocidLe = 0;    /* The \"docid <= ?\" constraint, if any */\n  int iIdx;\n\n  UNUSED_PARAMETER(idxStr);\n  UNUSED_PARAMETER(nVal);\n\n  if( p->bLock ){\n    return SQLITE_ERROR;\n  }\n\n  eSearch = (idxNum & 0x0000FFFF);\n  assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );\n  assert( p->pSegments==0 );\n\n  /* Collect arguments into local variables */\n  iIdx = 0;\n  if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];\n  if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];\n  if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];\n  if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];\n  assert( iIdx==nVal );\n\n  /* In case the cursor has been used before, clear it now. */\n  fts3ClearCursor(pCsr);\n\n  /* Set the lower and upper bounds on docids to return */\n  pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);\n  pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);\n\n  if( idxStr ){\n    pCsr->bDesc = (idxStr[0]=='D');\n  }else{\n    pCsr->bDesc = p->bDescIdx;\n  }\n  pCsr->eSearch = (i16)eSearch;\n\n  if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){\n    int iCol = eSearch-FTS3_FULLTEXT_SEARCH;\n    const char *zQuery = (const char *)sqlite3_value_text(pCons);\n\n    if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){\n      return SQLITE_NOMEM;\n    }\n\n    pCsr->iLangid = 0;\n    if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);\n\n    assert( p->base.zErrMsg==0 );\n    rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,\n        p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr, \n        &p->base.zErrMsg\n    );\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n\n    rc = fts3EvalStart(pCsr);\n    sqlite3Fts3SegmentsClose(p);\n    if( rc!=SQLITE_OK ) return rc;\n    pCsr->pNextId = pCsr->aDoclist;\n    pCsr->iPrevId = 0;\n  }\n\n  /* Compile a SELECT statement for this cursor. For a full-table-scan, the\n  ** statement loops through all rows of the %_content table. For a\n  ** full-text query or docid lookup, the statement retrieves a single\n  ** row by docid.\n  */\n  if( eSearch==FTS3_FULLSCAN_SEARCH ){\n    if( pDocidGe || pDocidLe ){\n      zSql = sqlite3_mprintf(\n          \"SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s\",\n          p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,\n          (pCsr->bDesc ? \"DESC\" : \"ASC\")\n      );\n    }else{\n      zSql = sqlite3_mprintf(\"SELECT %s ORDER BY rowid %s\", \n          p->zReadExprlist, (pCsr->bDesc ? \"DESC\" : \"ASC\")\n      );\n    }\n    if( zSql ){\n      p->bLock++;\n      rc = sqlite3_prepare_v3(\n          p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0\n      );\n      p->bLock--;\n      sqlite3_free(zSql);\n    }else{\n      rc = SQLITE_NOMEM;\n    }\n  }else if( eSearch==FTS3_DOCID_SEARCH ){\n    rc = fts3CursorSeekStmt(pCsr);\n    if( rc==SQLITE_OK ){\n      rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);\n    }\n  }\n  if( rc!=SQLITE_OK ) return rc;\n\n  return fts3NextMethod(pCursor);\n}\n\n/* \n** This is the xEof method of the virtual table. SQLite calls this \n** routine to find out if it has reached the end of a result set.\n*/\nstatic int fts3EofMethod(sqlite3_vtab_cursor *pCursor){\n  Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;\n  if( pCsr->isEof ){\n    fts3ClearCursor(pCsr);\n    pCsr->isEof = 1;\n  }\n  return pCsr->isEof;\n}\n\n/* \n** This is the xRowid method. The SQLite core calls this routine to\n** retrieve the rowid for the current row of the result set. fts3\n** exposes %_content.docid as the rowid for the virtual table. The\n** rowid should be written to *pRowid.\n*/\nstatic int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){\n  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;\n  *pRowid = pCsr->iPrevId;\n  return SQLITE_OK;\n}\n\n/* \n** This is the xColumn method, called by SQLite to request a value from\n** the row that the supplied cursor currently points to.\n**\n** If:\n**\n**   (iCol <  p->nColumn)   -> The value of the iCol'th user column.\n**   (iCol == p->nColumn)   -> Magic column with the same name as the table.\n**   (iCol == p->nColumn+1) -> Docid column\n**   (iCol == p->nColumn+2) -> Langid column\n*/\nstatic int fts3ColumnMethod(\n  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */\n  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */\n  int iCol                        /* Index of column to read value from */\n){\n  int rc = SQLITE_OK;             /* Return Code */\n  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;\n  Fts3Table *p = (Fts3Table *)pCursor->pVtab;\n\n  /* The column value supplied by SQLite must be in range. */\n  assert( iCol>=0 && iCol<=p->nColumn+2 );\n\n  switch( iCol-p->nColumn ){\n    case 0:\n      /* The special 'table-name' column */\n      sqlite3_result_pointer(pCtx, pCsr, \"fts3cursor\", 0);\n      break;\n\n    case 1:\n      /* The docid column */\n      sqlite3_result_int64(pCtx, pCsr->iPrevId);\n      break;\n\n    case 2:\n      if( pCsr->pExpr ){\n        sqlite3_result_int64(pCtx, pCsr->iLangid);\n        break;\n      }else if( p->zLanguageid==0 ){\n        sqlite3_result_int(pCtx, 0);\n        break;\n      }else{\n        iCol = p->nColumn;\n        /* fall-through */\n      }\n\n    default:\n      /* A user column. Or, if this is a full-table scan, possibly the\n      ** language-id column. Seek the cursor. */\n      rc = fts3CursorSeek(0, pCsr);\n      if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){\n        sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));\n      }\n      break;\n  }\n\n  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );\n  return rc;\n}\n\n/* \n** This function is the implementation of the xUpdate callback used by \n** FTS3 virtual tables. It is invoked by SQLite each time a row is to be\n** inserted, updated or deleted.\n*/\nstatic int fts3UpdateMethod(\n  sqlite3_vtab *pVtab,            /* Virtual table handle */\n  int nArg,                       /* Size of argument array */\n  sqlite3_value **apVal,          /* Array of arguments */\n  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */\n){\n  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);\n}\n\n/*\n** Implementation of xSync() method. Flush the contents of the pending-terms\n** hash-table to the database.\n*/\nstatic int fts3SyncMethod(sqlite3_vtab *pVtab){\n\n  /* Following an incremental-merge operation, assuming that the input\n  ** segments are not completely consumed (the usual case), they are updated\n  ** in place to remove the entries that have already been merged. This\n  ** involves updating the leaf block that contains the smallest unmerged\n  ** entry and each block (if any) between the leaf and the root node. So\n  ** if the height of the input segment b-trees is N, and input segments\n  ** are merged eight at a time, updating the input segments at the end\n  ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually\n  ** small - often between 0 and 2. So the overhead of the incremental\n  ** merge is somewhere between 8 and 24 blocks. To avoid this overhead\n  ** dwarfing the actual productive work accomplished, the incremental merge\n  ** is only attempted if it will write at least 64 leaf blocks. Hence\n  ** nMinMerge.\n  **\n  ** Of course, updating the input segments also involves deleting a bunch\n  ** of blocks from the segments table. But this is not considered overhead\n  ** as it would also be required by a crisis-merge that used the same input \n  ** segments.\n  */\n  const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */\n\n  Fts3Table *p = (Fts3Table*)pVtab;\n  int rc;\n  i64 iLastRowid = sqlite3_last_insert_rowid(p->db);\n\n  rc = sqlite3Fts3PendingTermsFlush(p);\n  if( rc==SQLITE_OK \n   && p->nLeafAdd>(nMinMerge/16) \n   && p->nAutoincrmerge && p->nAutoincrmerge!=0xff\n  ){\n    int mxLevel = 0;              /* Maximum relative level value in db */\n    int A;                        /* Incr-merge parameter A */\n\n    rc = sqlite3Fts3MaxLevel(p, &mxLevel);\n    assert( rc==SQLITE_OK || mxLevel==0 );\n    A = p->nLeafAdd * mxLevel;\n    A += (A/2);\n    if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);\n  }\n  sqlite3Fts3SegmentsClose(p);\n  sqlite3_set_last_insert_rowid(p->db, iLastRowid);\n  return rc;\n}\n\n/*\n** If it is currently unknown whether or not the FTS table has an %_stat\n** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat\n** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code\n** if an error occurs.\n*/\nstatic int fts3SetHasStat(Fts3Table *p){\n  int rc = SQLITE_OK;\n  if( p->bHasStat==2 ){\n    char *zTbl = sqlite3_mprintf(\"%s_stat\", p->zName);\n    if( zTbl ){\n      int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);\n      sqlite3_free(zTbl);\n      p->bHasStat = (res==SQLITE_OK);\n    }else{\n      rc = SQLITE_NOMEM;\n    }\n  }\n  return rc;\n}\n\n/*\n** Implementation of xBegin() method. \n*/\nstatic int fts3BeginMethod(sqlite3_vtab *pVtab){\n  Fts3Table *p = (Fts3Table*)pVtab;\n  UNUSED_PARAMETER(pVtab);\n  assert( p->pSegments==0 );\n  assert( p->nPendingData==0 );\n  assert( p->inTransaction!=1 );\n  TESTONLY( p->inTransaction = 1 );\n  TESTONLY( p->mxSavepoint = -1; );\n  p->nLeafAdd = 0;\n  return fts3SetHasStat(p);\n}\n\n/*\n** Implementation of xCommit() method. This is a no-op. The contents of\n** the pending-terms hash-table have already been flushed into the database\n** by fts3SyncMethod().\n*/\nstatic int fts3CommitMethod(sqlite3_vtab *pVtab){\n  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );\n  UNUSED_PARAMETER(pVtab);\n  assert( p->nPendingData==0 );\n  assert( p->inTransaction!=0 );\n  assert( p->pSegments==0 );\n  TESTONLY( p->inTransaction = 0 );\n  TESTONLY( p->mxSavepoint = -1; );\n  return SQLITE_OK;\n}\n\n/*\n** Implementation of xRollback(). Discard the contents of the pending-terms\n** hash-table. Any changes made to the database are reverted by SQLite.\n*/\nstatic int fts3RollbackMethod(sqlite3_vtab *pVtab){\n  Fts3Table *p = (Fts3Table*)pVtab;\n  sqlite3Fts3PendingTermsClear(p);\n  assert( p->inTransaction!=0 );\n  TESTONLY( p->inTransaction = 0 );\n  TESTONLY( p->mxSavepoint = -1; );\n  return SQLITE_OK;\n}\n\n/*\n** When called, *ppPoslist must point to the byte immediately following the\n** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function\n** moves *ppPoslist so that it instead points to the first byte of the\n** same position list.\n*/\nstatic void fts3ReversePoslist(char *pStart, char **ppPoslist){\n  char *p = &(*ppPoslist)[-2];\n  char c = 0;\n\n  /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */\n  while( p>pStart && (c=*p--)==0 );\n\n  /* Search backwards for a varint with value zero (the end of the previous \n  ** poslist). This is an 0x00 byte preceded by some byte that does not\n  ** have the 0x80 bit set.  */\n  while( p>pStart && (*p & 0x80) | c ){ \n    c = *p--; \n  }\n  assert( p==pStart || c==0 );\n\n  /* At this point p points to that preceding byte without the 0x80 bit\n  ** set. So to find the start of the poslist, skip forward 2 bytes then\n  ** over a varint. \n  **\n  ** Normally. The other case is that p==pStart and the poslist to return\n  ** is the first in the doclist. In this case do not skip forward 2 bytes.\n  ** The second part of the if condition (c==0 && *ppPoslist>&p[2])\n  ** is required for cases where the first byte of a doclist and the\n  ** doclist is empty. For example, if the first docid is 10, a doclist\n  ** that begins with:\n  **\n  **   0x0A 0x00 <next docid delta varint>\n  */\n  if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }\n  while( *p++&0x80 );\n  *ppPoslist = p;\n}\n\n/*\n** Helper function used by the implementation of the overloaded snippet(),\n** offsets() and optimize() SQL functions.\n**\n** If the value passed as the third argument is a blob of size\n** sizeof(Fts3Cursor*), then the blob contents are copied to the \n** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error\n** message is written to context pContext and SQLITE_ERROR returned. The\n** string passed via zFunc is used as part of the error message.\n*/\nstatic int fts3FunctionArg(\n  sqlite3_context *pContext,      /* SQL function call context */\n  const char *zFunc,              /* Function name */\n  sqlite3_value *pVal,            /* argv[0] passed to function */\n  Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */\n){\n  int rc;\n  *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, \"fts3cursor\");\n  if( (*ppCsr)!=0 ){\n    rc = SQLITE_OK;\n  }else{\n    char *zErr = sqlite3_mprintf(\"illegal first argument to %s\", zFunc);\n    sqlite3_result_error(pContext, zErr, -1);\n    sqlite3_free(zErr);\n    rc = SQLITE_ERROR;\n  }\n  return rc;\n}\n\n/*\n** Implementation of the snippet() function for FTS3\n*/\nstatic void fts3SnippetFunc(\n  sqlite3_context *pContext,      /* SQLite function call context */\n  int nVal,                       /* Size of apVal[] array */\n  sqlite3_value **apVal           /* Array of arguments */\n){\n  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */\n  const char *zStart = \"<b>\";\n  const char *zEnd = \"</b>\";\n  const char *zEllipsis = \"<b>...</b>\";\n  int iCol = -1;\n  int nToken = 15;                /* Default number of tokens in snippet */\n\n  /* There must be at least one argument passed to this function (otherwise\n  ** the non-overloaded version would have been called instead of this one).\n  */\n  assert( nVal>=1 );\n\n  if( nVal>6 ){\n    sqlite3_result_error(pContext, \n        \"wrong number of arguments to function snippet()\", -1);\n    return;\n  }\n  if( fts3FunctionArg(pContext, \"snippet\", apVal[0], &pCsr) ) return;\n\n  switch( nVal ){\n    case 6: nToken = sqlite3_value_int(apVal[5]);\n    case 5: iCol = sqlite3_value_int(apVal[4]);\n    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);\n    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);\n    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);\n  }\n  if( !zEllipsis || !zEnd || !zStart ){\n    sqlite3_result_error_nomem(pContext);\n  }else if( nToken==0 ){\n    sqlite3_result_text(pContext, \"\", -1, SQLITE_STATIC);\n  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){\n    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);\n  }\n}\n\n/*\n** Implementation of the offsets() function for FTS3\n*/\nstatic void fts3OffsetsFunc(\n  sqlite3_context *pContext,      /* SQLite function call context */\n  int nVal,                       /* Size of argument array */\n  sqlite3_value **apVal           /* Array of arguments */\n){\n  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */\n\n  UNUSED_PARAMETER(nVal);\n\n  assert( nVal==1 );\n  if( fts3FunctionArg(pContext, \"offsets\", apVal[0], &pCsr) ) return;\n  assert( pCsr );\n  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){\n    sqlite3Fts3Offsets(pContext, pCsr);\n  }\n}\n\n/* \n** Implementation of the special optimize() function for FTS3. This \n** function merges all segments in the database to a single segment.\n** Example usage is:\n**\n**   SELECT optimize(t) FROM t LIMIT 1;\n**\n** where 't' is the name of an FTS3 table.\n*/\nstatic void fts3OptimizeFunc(\n  sqlite3_context *pContext,      /* SQLite function call context */\n  int nVal,                       /* Size of argument array */\n  sqlite3_value **apVal           /* Array of arguments */\n){\n  int rc;                         /* Return code */\n  Fts3Table *p;                   /* Virtual table handle */\n  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */\n\n  UNUSED_PARAMETER(nVal);\n\n  assert( nVal==1 );\n  if( fts3FunctionArg(pContext, \"optimize\", apVal[0], &pCursor) ) return;\n  p = (Fts3Table *)pCursor->base.pVtab;\n  assert( p );\n\n  rc = sqlite3Fts3Optimize(p);\n\n  switch( rc ){\n    case SQLITE_OK:\n      sqlite3_result_text(pContext, \"Index optimized\", -1, SQLITE_STATIC);\n      break;\n    case SQLITE_DONE:\n      sqlite3_result_text(pContext, \"Index already optimal\", -1, SQLITE_STATIC);\n      break;\n    default:\n      sqlite3_result_error_code(pContext, rc);\n      break;\n  }\n}\n\n/*\n** Implementation of the matchinfo() function for FTS3\n*/\nstatic void fts3MatchinfoFunc(\n  sqlite3_context *pContext,      /* SQLite function call context */\n  int nVal,                       /* Size of argument array */\n  sqlite3_value **apVal           /* Array of arguments */\n){\n  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */\n  assert( nVal==1 || nVal==2 );\n  if( SQLITE_OK==fts3FunctionArg(pContext, \"matchinfo\", apVal[0], &pCsr) ){\n    const char *zArg = 0;\n    if( nVal>1 ){\n      zArg = (const char *)sqlite3_value_text(apVal[1]);\n    }\n    sqlite3Fts3Matchinfo(pContext, pCsr, zArg);\n  }\n}\n\n/*\n** This routine implements the xFindFunction method for the FTS3\n** virtual table.\n*/\nstatic int fts3FindFunctionMethod(\n  sqlite3_vtab *pVtab,            /* Virtual table handle */\n  int nArg,                       /* Number of SQL function arguments */\n  const char *zName,              /* Name of SQL function */\n  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */\n  void **ppArg                    /* Unused */\n){\n  struct Overloaded {\n    const char *zName;\n    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);\n  } aOverload[] = {\n    { \"snippet\", fts3SnippetFunc },\n    { \"offsets\", fts3OffsetsFunc },\n    { \"optimize\", fts3OptimizeFunc },\n    { \"matchinfo\", fts3MatchinfoFunc },\n  };\n  int i;                          /* Iterator variable */\n\n  UNUSED_PARAMETER(pVtab);\n  UNUSED_PARAMETER(nArg);\n  UNUSED_PARAMETER(ppArg);\n\n  for(i=0; i<SizeofArray(aOverload); i++){\n    if( strcmp(zName, aOverload[i].zName)==0 ){\n      *pxFunc = aOverload[i].xFunc;\n      return 1;\n    }\n  }\n\n  /* No function of the specified name was found. Return 0. */\n  return 0;\n}\n\n/*\n** Implementation of FTS3 xRename method. Rename an fts3 table.\n*/\nstatic int fts3RenameMethod(\n  sqlite3_vtab *pVtab,            /* Virtual table handle */\n  const char *zName               /* New name of table */\n){\n  Fts3Table *p = (Fts3Table *)pVtab;\n  sqlite3 *db = p->db;            /* Database connection */\n  int rc;                         /* Return Code */\n\n  /* At this point it must be known if the %_stat table exists or not.\n  ** So bHasStat may not be 2.  */\n  rc = fts3SetHasStat(p);\n  \n  /* As it happens, the pending terms table is always empty here. This is\n  ** because an \"ALTER TABLE RENAME TABLE\" statement inside a transaction \n  ** always opens a savepoint transaction. And the xSavepoint() method \n  ** flushes the pending terms table. But leave the (no-op) call to\n  ** PendingTermsFlush() in in case that changes.\n  */\n  assert( p->nPendingData==0 );\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts3PendingTermsFlush(p);\n  }\n\n  if( p->zContentTbl==0 ){\n    fts3DbExec(&rc, db,\n      \"ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';\",\n      p->zDb, p->zName, zName\n    );\n  }\n\n  if( p->bHasDocsize ){\n    fts3DbExec(&rc, db,\n      \"ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';\",\n      p->zDb, p->zName, zName\n    );\n  }\n  if( p->bHasStat ){\n    fts3DbExec(&rc, db,\n      \"ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';\",\n      p->zDb, p->zName, zName\n    );\n  }\n  fts3DbExec(&rc, db,\n    \"ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';\",\n    p->zDb, p->zName, zName\n  );\n  fts3DbExec(&rc, db,\n    \"ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';\",\n    p->zDb, p->zName, zName\n  );\n  return rc;\n}\n\n/*\n** The xSavepoint() method.\n**\n** Flush the contents of the pending-terms table to disk.\n*/\nstatic int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){\n  int rc = SQLITE_OK;\n  UNUSED_PARAMETER(iSavepoint);\n  assert( ((Fts3Table *)pVtab)->inTransaction );\n  assert( ((Fts3Table *)pVtab)->mxSavepoint <= iSavepoint );\n  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );\n  if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){\n    rc = fts3SyncMethod(pVtab);\n  }\n  return rc;\n}\n\n/*\n** The xRelease() method.\n**\n** This is a no-op.\n*/\nstatic int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){\n  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );\n  UNUSED_PARAMETER(iSavepoint);\n  UNUSED_PARAMETER(pVtab);\n  assert( p->inTransaction );\n  assert( p->mxSavepoint >= iSavepoint );\n  TESTONLY( p->mxSavepoint = iSavepoint-1 );\n  return SQLITE_OK;\n}\n\n/*\n** The xRollbackTo() method.\n**\n** Discard the contents of the pending terms table.\n*/\nstatic int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){\n  Fts3Table *p = (Fts3Table*)pVtab;\n  UNUSED_PARAMETER(iSavepoint);\n  assert( p->inTransaction );\n  TESTONLY( p->mxSavepoint = iSavepoint );\n  sqlite3Fts3PendingTermsClear(p);\n  return SQLITE_OK;\n}\n\n/*\n** Return true if zName is the extension on one of the shadow tables used\n** by this module.\n*/\nstatic int fts3ShadowName(const char *zName){\n  static const char *azName[] = {\n    \"content\", \"docsize\", \"segdir\", \"segments\", \"stat\", \n  };\n  unsigned int i;\n  for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){\n    if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;\n  }\n  return 0;\n}\n\nstatic const sqlite3_module fts3Module = {\n  /* iVersion      */ 3,\n  /* xCreate       */ fts3CreateMethod,\n  /* xConnect      */ fts3ConnectMethod,\n  /* xBestIndex    */ fts3BestIndexMethod,\n  /* xDisconnect   */ fts3DisconnectMethod,\n  /* xDestroy      */ fts3DestroyMethod,\n  /* xOpen         */ fts3OpenMethod,\n  /* xClose        */ fts3CloseMethod,\n  /* xFilter       */ fts3FilterMethod,\n  /* xNext         */ fts3NextMethod,\n  /* xEof          */ fts3EofMethod,\n  /* xColumn       */ fts3ColumnMethod,\n  /* xRowid        */ fts3RowidMethod,\n  /* xUpdate       */ fts3UpdateMethod,\n  /* xBegin        */ fts3BeginMethod,\n  /* xSync         */ fts3SyncMethod,\n  /* xCommit       */ fts3CommitMethod,\n  /* xRollback     */ fts3RollbackMethod,\n  /* xFindFunction */ fts3FindFunctionMethod,\n  /* xRename */       fts3RenameMethod,\n  /* xSavepoint    */ fts3SavepointMethod,\n  /* xRelease      */ fts3ReleaseMethod,\n  /* xRollbackTo   */ fts3RollbackToMethod,\n  /* xShadowName   */ fts3ShadowName,\n};\n\n/*\n** This function is registered as the module destructor (called when an\n** FTS3 enabled database connection is closed). It frees the memory\n** allocated for the tokenizer hash table.\n*/\nstatic void hashDestroy(void *p){\n  Fts3Hash *pHash = (Fts3Hash *)p;\n  sqlite3Fts3HashClear(pHash);\n  sqlite3_free(pHash);\n}\n\n/*\n** The fts3 built-in tokenizers - \"simple\", \"porter\" and \"icu\"- are \n** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c\n** respectively. The following three forward declarations are for functions\n** declared in these files used to retrieve the respective implementations.\n**\n** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed\n** to by the argument to point to the \"simple\" tokenizer implementation.\n** And so on.\n*/\nSQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);\nSQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);\n#ifndef SQLITE_DISABLE_FTS3_UNICODE\nSQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);\n#endif\n#ifdef SQLITE_ENABLE_ICU\nSQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);\n#endif\n\n/*\n** Initialize the fts3 extension. If this extension is built as part\n** of the sqlite library, then this function is called directly by\n** SQLite. If fts3 is built as a dynamically loadable extension, this\n** function is called by the sqlite3_extension_init() entry point.\n*/\nSQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){\n  int rc = SQLITE_OK;\n  Fts3Hash *pHash = 0;\n  const sqlite3_tokenizer_module *pSimple = 0;\n  const sqlite3_tokenizer_module *pPorter = 0;\n#ifndef SQLITE_DISABLE_FTS3_UNICODE\n  const sqlite3_tokenizer_module *pUnicode = 0;\n#endif\n\n#ifdef SQLITE_ENABLE_ICU\n  const sqlite3_tokenizer_module *pIcu = 0;\n  sqlite3Fts3IcuTokenizerModule(&pIcu);\n#endif\n\n#ifndef SQLITE_DISABLE_FTS3_UNICODE\n  sqlite3Fts3UnicodeTokenizer(&pUnicode);\n#endif\n\n#ifdef SQLITE_TEST\n  rc = sqlite3Fts3InitTerm(db);\n  if( rc!=SQLITE_OK ) return rc;\n#endif\n\n  rc = sqlite3Fts3InitAux(db);\n  if( rc!=SQLITE_OK ) return rc;\n\n  sqlite3Fts3SimpleTokenizerModule(&pSimple);\n  sqlite3Fts3PorterTokenizerModule(&pPorter);\n\n  /* Allocate and initialize the hash-table used to store tokenizers. */\n  pHash = sqlite3_malloc(sizeof(Fts3Hash));\n  if( !pHash ){\n    rc = SQLITE_NOMEM;\n  }else{\n    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);\n  }\n\n  /* Load the built-in tokenizers into the hash table */\n  if( rc==SQLITE_OK ){\n    if( sqlite3Fts3HashInsert(pHash, \"simple\", 7, (void *)pSimple)\n     || sqlite3Fts3HashInsert(pHash, \"porter\", 7, (void *)pPorter) \n\n#ifndef SQLITE_DISABLE_FTS3_UNICODE\n     || sqlite3Fts3HashInsert(pHash, \"unicode61\", 10, (void *)pUnicode) \n#endif\n#ifdef SQLITE_ENABLE_ICU\n     || (pIcu && sqlite3Fts3HashInsert(pHash, \"icu\", 4, (void *)pIcu))\n#endif\n    ){\n      rc = SQLITE_NOMEM;\n    }\n  }\n\n#ifdef SQLITE_TEST\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts3ExprInitTestInterface(db, pHash);\n  }\n#endif\n\n  /* Create the virtual table wrapper around the hash-table and overload \n  ** the four scalar functions. If this is successful, register the\n  ** module with sqlite.\n  */\n  if( SQLITE_OK==rc \n   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, \"fts3_tokenizer\"))\n   && SQLITE_OK==(rc = sqlite3_overload_function(db, \"snippet\", -1))\n   && SQLITE_OK==(rc = sqlite3_overload_function(db, \"offsets\", 1))\n   && SQLITE_OK==(rc = sqlite3_overload_function(db, \"matchinfo\", 1))\n   && SQLITE_OK==(rc = sqlite3_overload_function(db, \"matchinfo\", 2))\n   && SQLITE_OK==(rc = sqlite3_overload_function(db, \"optimize\", 1))\n  ){\n    rc = sqlite3_create_module_v2(\n        db, \"fts3\", &fts3Module, (void *)pHash, hashDestroy\n    );\n    if( rc==SQLITE_OK ){\n      rc = sqlite3_create_module_v2(\n          db, \"fts4\", &fts3Module, (void *)pHash, 0\n      );\n    }\n    if( rc==SQLITE_OK ){\n      rc = sqlite3Fts3InitTok(db, (void *)pHash);\n    }\n    return rc;\n  }\n\n\n  /* An error has occurred. Delete the hash table and return the error code. */\n  assert( rc!=SQLITE_OK );\n  if( pHash ){\n    sqlite3Fts3HashClear(pHash);\n    sqlite3_free(pHash);\n  }\n  return rc;\n}\n\n/*\n** Allocate an Fts3MultiSegReader for each token in the expression headed\n** by pExpr. \n**\n** An Fts3SegReader object is a cursor that can seek or scan a range of\n** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple\n** Fts3SegReader objects internally to provide an interface to seek or scan\n** within the union of all segments of a b-tree. Hence the name.\n**\n** If the allocated Fts3MultiSegReader just seeks to a single entry in a\n** segment b-tree (if the term is not a prefix or it is a prefix for which\n** there exists prefix b-tree of the right length) then it may be traversed\n** and merged incrementally. Otherwise, it has to be merged into an in-memory \n** doclist and then traversed.\n*/\nstatic void fts3EvalAllocateReaders(\n  Fts3Cursor *pCsr,               /* FTS cursor handle */\n  Fts3Expr *pExpr,                /* Allocate readers for this expression */\n  int *pnToken,                   /* OUT: Total number of tokens in phrase. */\n  int *pnOr,                      /* OUT: Total number of OR nodes in expr. */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  if( pExpr && SQLITE_OK==*pRc ){\n    if( pExpr->eType==FTSQUERY_PHRASE ){\n      int i;\n      int nToken = pExpr->pPhrase->nToken;\n      *pnToken += nToken;\n      for(i=0; i<nToken; i++){\n        Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];\n        int rc = fts3TermSegReaderCursor(pCsr, \n            pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr\n        );\n        if( rc!=SQLITE_OK ){\n          *pRc = rc;\n          return;\n        }\n      }\n      assert( pExpr->pPhrase->iDoclistToken==0 );\n      pExpr->pPhrase->iDoclistToken = -1;\n    }else{\n      *pnOr += (pExpr->eType==FTSQUERY_OR);\n      fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);\n      fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);\n    }\n  }\n}\n\n/*\n** Arguments pList/nList contain the doclist for token iToken of phrase p.\n** It is merged into the main doclist stored in p->doclist.aAll/nAll.\n**\n** This function assumes that pList points to a buffer allocated using\n** sqlite3_malloc(). This function takes responsibility for eventually\n** freeing the buffer.\n**\n** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.\n*/\nstatic int fts3EvalPhraseMergeToken(\n  Fts3Table *pTab,                /* FTS Table pointer */\n  Fts3Phrase *p,                  /* Phrase to merge pList/nList into */\n  int iToken,                     /* Token pList/nList corresponds to */\n  char *pList,                    /* Pointer to doclist */\n  int nList                       /* Number of bytes in pList */\n){\n  int rc = SQLITE_OK;\n  assert( iToken!=p->iDoclistToken );\n\n  if( pList==0 ){\n    sqlite3_free(p->doclist.aAll);\n    p->doclist.aAll = 0;\n    p->doclist.nAll = 0;\n  }\n\n  else if( p->iDoclistToken<0 ){\n    p->doclist.aAll = pList;\n    p->doclist.nAll = nList;\n  }\n\n  else if( p->doclist.aAll==0 ){\n    sqlite3_free(pList);\n  }\n\n  else {\n    char *pLeft;\n    char *pRight;\n    int nLeft;\n    int nRight;\n    int nDiff;\n\n    if( p->iDoclistToken<iToken ){\n      pLeft = p->doclist.aAll;\n      nLeft = p->doclist.nAll;\n      pRight = pList;\n      nRight = nList;\n      nDiff = iToken - p->iDoclistToken;\n    }else{\n      pRight = p->doclist.aAll;\n      nRight = p->doclist.nAll;\n      pLeft = pList;\n      nLeft = nList;\n      nDiff = p->iDoclistToken - iToken;\n    }\n\n    rc = fts3DoclistPhraseMerge(\n        pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight\n    );\n    sqlite3_free(pLeft);\n    p->doclist.aAll = pRight;\n    p->doclist.nAll = nRight;\n  }\n\n  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;\n  return rc;\n}\n\n/*\n** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist\n** does not take deferred tokens into account.\n**\n** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.\n*/\nstatic int fts3EvalPhraseLoad(\n  Fts3Cursor *pCsr,               /* FTS Cursor handle */\n  Fts3Phrase *p                   /* Phrase object */\n){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  int iToken;\n  int rc = SQLITE_OK;\n\n  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){\n    Fts3PhraseToken *pToken = &p->aToken[iToken];\n    assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );\n\n    if( pToken->pSegcsr ){\n      int nThis = 0;\n      char *pThis = 0;\n      rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);\n      if( rc==SQLITE_OK ){\n        rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);\n      }\n    }\n    assert( pToken->pSegcsr==0 );\n  }\n\n  return rc;\n}\n\n#ifndef SQLITE_DISABLE_FTS4_DEFERRED\n/*\n** This function is called on each phrase after the position lists for\n** any deferred tokens have been loaded into memory. It updates the phrases\n** current position list to include only those positions that are really\n** instances of the phrase (after considering deferred tokens). If this\n** means that the phrase does not appear in the current row, doclist.pList\n** and doclist.nList are both zeroed.\n**\n** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.\n*/\nstatic int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){\n  int iToken;                     /* Used to iterate through phrase tokens */\n  char *aPoslist = 0;             /* Position list for deferred tokens */\n  int nPoslist = 0;               /* Number of bytes in aPoslist */\n  int iPrev = -1;                 /* Token number of previous deferred token */\n\n  assert( pPhrase->doclist.bFreeList==0 );\n\n  for(iToken=0; iToken<pPhrase->nToken; iToken++){\n    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];\n    Fts3DeferredToken *pDeferred = pToken->pDeferred;\n\n    if( pDeferred ){\n      char *pList;\n      int nList;\n      int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);\n      if( rc!=SQLITE_OK ) return rc;\n\n      if( pList==0 ){\n        sqlite3_free(aPoslist);\n        pPhrase->doclist.pList = 0;\n        pPhrase->doclist.nList = 0;\n        return SQLITE_OK;\n\n      }else if( aPoslist==0 ){\n        aPoslist = pList;\n        nPoslist = nList;\n\n      }else{\n        char *aOut = pList;\n        char *p1 = aPoslist;\n        char *p2 = aOut;\n\n        assert( iPrev>=0 );\n        fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);\n        sqlite3_free(aPoslist);\n        aPoslist = pList;\n        nPoslist = (int)(aOut - aPoslist);\n        if( nPoslist==0 ){\n          sqlite3_free(aPoslist);\n          pPhrase->doclist.pList = 0;\n          pPhrase->doclist.nList = 0;\n          return SQLITE_OK;\n        }\n      }\n      iPrev = iToken;\n    }\n  }\n\n  if( iPrev>=0 ){\n    int nMaxUndeferred = pPhrase->iDoclistToken;\n    if( nMaxUndeferred<0 ){\n      pPhrase->doclist.pList = aPoslist;\n      pPhrase->doclist.nList = nPoslist;\n      pPhrase->doclist.iDocid = pCsr->iPrevId;\n      pPhrase->doclist.bFreeList = 1;\n    }else{\n      int nDistance;\n      char *p1;\n      char *p2;\n      char *aOut;\n\n      if( nMaxUndeferred>iPrev ){\n        p1 = aPoslist;\n        p2 = pPhrase->doclist.pList;\n        nDistance = nMaxUndeferred - iPrev;\n      }else{\n        p1 = pPhrase->doclist.pList;\n        p2 = aPoslist;\n        nDistance = iPrev - nMaxUndeferred;\n      }\n\n      aOut = (char *)sqlite3_malloc(nPoslist+8);\n      if( !aOut ){\n        sqlite3_free(aPoslist);\n        return SQLITE_NOMEM;\n      }\n      \n      pPhrase->doclist.pList = aOut;\n      if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){\n        pPhrase->doclist.bFreeList = 1;\n        pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);\n      }else{\n        sqlite3_free(aOut);\n        pPhrase->doclist.pList = 0;\n        pPhrase->doclist.nList = 0;\n      }\n      sqlite3_free(aPoslist);\n    }\n  }\n\n  return SQLITE_OK;\n}\n#endif /* SQLITE_DISABLE_FTS4_DEFERRED */\n\n/*\n** Maximum number of tokens a phrase may have to be considered for the\n** incremental doclists strategy.\n*/\n#define MAX_INCR_PHRASE_TOKENS 4\n\n/*\n** This function is called for each Fts3Phrase in a full-text query \n** expression to initialize the mechanism for returning rows. Once this\n** function has been called successfully on an Fts3Phrase, it may be\n** used with fts3EvalPhraseNext() to iterate through the matching docids.\n**\n** If parameter bOptOk is true, then the phrase may (or may not) use the\n** incremental loading strategy. Otherwise, the entire doclist is loaded into\n** memory within this call.\n**\n** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.\n*/\nstatic int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  int rc = SQLITE_OK;             /* Error code */\n  int i;\n\n  /* Determine if doclists may be loaded from disk incrementally. This is\n  ** possible if the bOptOk argument is true, the FTS doclists will be\n  ** scanned in forward order, and the phrase consists of \n  ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are \"^first\"\n  ** tokens or prefix tokens that cannot use a prefix-index.  */\n  int bHaveIncr = 0;\n  int bIncrOk = (bOptOk \n   && pCsr->bDesc==pTab->bDescIdx \n   && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0\n#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)\n   && pTab->bNoIncrDoclist==0\n#endif\n  );\n  for(i=0; bIncrOk==1 && i<p->nToken; i++){\n    Fts3PhraseToken *pToken = &p->aToken[i];\n    if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){\n      bIncrOk = 0;\n    }\n    if( pToken->pSegcsr ) bHaveIncr = 1;\n  }\n\n  if( bIncrOk && bHaveIncr ){\n    /* Use the incremental approach. */\n    int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);\n    for(i=0; rc==SQLITE_OK && i<p->nToken; i++){\n      Fts3PhraseToken *pToken = &p->aToken[i];\n      Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;\n      if( pSegcsr ){\n        rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);\n      }\n    }\n    p->bIncr = 1;\n  }else{\n    /* Load the full doclist for the phrase into memory. */\n    rc = fts3EvalPhraseLoad(pCsr, p);\n    p->bIncr = 0;\n  }\n\n  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );\n  return rc;\n}\n\n/*\n** This function is used to iterate backwards (from the end to start) \n** through doclists. It is used by this module to iterate through phrase\n** doclists in reverse and by the fts3_write.c module to iterate through\n** pending-terms lists when writing to databases with \"order=desc\".\n**\n** The doclist may be sorted in ascending (parameter bDescIdx==0) or \n** descending (parameter bDescIdx==1) order of docid. Regardless, this\n** function iterates from the end of the doclist to the beginning.\n*/\nSQLITE_PRIVATE void sqlite3Fts3DoclistPrev(\n  int bDescIdx,                   /* True if the doclist is desc */\n  char *aDoclist,                 /* Pointer to entire doclist */\n  int nDoclist,                   /* Length of aDoclist in bytes */\n  char **ppIter,                  /* IN/OUT: Iterator pointer */\n  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */\n  int *pnList,                    /* OUT: List length pointer */\n  u8 *pbEof                       /* OUT: End-of-file flag */\n){\n  char *p = *ppIter;\n\n  assert( nDoclist>0 );\n  assert( *pbEof==0 );\n  assert( p || *piDocid==0 );\n  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );\n\n  if( p==0 ){\n    sqlite3_int64 iDocid = 0;\n    char *pNext = 0;\n    char *pDocid = aDoclist;\n    char *pEnd = &aDoclist[nDoclist];\n    int iMul = 1;\n\n    while( pDocid<pEnd ){\n      sqlite3_int64 iDelta;\n      pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);\n      iDocid += (iMul * iDelta);\n      pNext = pDocid;\n      fts3PoslistCopy(0, &pDocid);\n      while( pDocid<pEnd && *pDocid==0 ) pDocid++;\n      iMul = (bDescIdx ? -1 : 1);\n    }\n\n    *pnList = (int)(pEnd - pNext);\n    *ppIter = pNext;\n    *piDocid = iDocid;\n  }else{\n    int iMul = (bDescIdx ? -1 : 1);\n    sqlite3_int64 iDelta;\n    fts3GetReverseVarint(&p, aDoclist, &iDelta);\n    *piDocid -= (iMul * iDelta);\n\n    if( p==aDoclist ){\n      *pbEof = 1;\n    }else{\n      char *pSave = p;\n      fts3ReversePoslist(aDoclist, &p);\n      *pnList = (int)(pSave - p);\n    }\n    *ppIter = p;\n  }\n}\n\n/*\n** Iterate forwards through a doclist.\n*/\nSQLITE_PRIVATE void sqlite3Fts3DoclistNext(\n  int bDescIdx,                   /* True if the doclist is desc */\n  char *aDoclist,                 /* Pointer to entire doclist */\n  int nDoclist,                   /* Length of aDoclist in bytes */\n  char **ppIter,                  /* IN/OUT: Iterator pointer */\n  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */\n  u8 *pbEof                       /* OUT: End-of-file flag */\n){\n  char *p = *ppIter;\n\n  assert( nDoclist>0 );\n  assert( *pbEof==0 );\n  assert_fts3_nc( p || *piDocid==0 );\n  assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );\n\n  if( p==0 ){\n    p = aDoclist;\n    p += sqlite3Fts3GetVarint(p, piDocid);\n  }else{\n    fts3PoslistCopy(0, &p);\n    while( p<&aDoclist[nDoclist] && *p==0 ) p++; \n    if( p>=&aDoclist[nDoclist] ){\n      *pbEof = 1;\n    }else{\n      sqlite3_int64 iVar;\n      p += sqlite3Fts3GetVarint(p, &iVar);\n      *piDocid += ((bDescIdx ? -1 : 1) * iVar);\n    }\n  }\n\n  *ppIter = p;\n}\n\n/*\n** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof\n** to true if EOF is reached.\n*/\nstatic void fts3EvalDlPhraseNext(\n  Fts3Table *pTab,\n  Fts3Doclist *pDL,\n  u8 *pbEof\n){\n  char *pIter;                            /* Used to iterate through aAll */\n  char *pEnd;                             /* 1 byte past end of aAll */\n \n  if( pDL->pNextDocid ){\n    pIter = pDL->pNextDocid;\n    assert( pDL->aAll!=0 || pIter==0 );\n  }else{\n    pIter = pDL->aAll;\n  }\n\n  if( pIter==0 || pIter>=(pEnd = pDL->aAll + pDL->nAll) ){\n    /* We have already reached the end of this doclist. EOF. */\n    *pbEof = 1;\n  }else{\n    sqlite3_int64 iDelta;\n    pIter += sqlite3Fts3GetVarint(pIter, &iDelta);\n    if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){\n      pDL->iDocid += iDelta;\n    }else{\n      pDL->iDocid -= iDelta;\n    }\n    pDL->pList = pIter;\n    fts3PoslistCopy(0, &pIter);\n    pDL->nList = (int)(pIter - pDL->pList);\n\n    /* pIter now points just past the 0x00 that terminates the position-\n    ** list for document pDL->iDocid. However, if this position-list was\n    ** edited in place by fts3EvalNearTrim(), then pIter may not actually\n    ** point to the start of the next docid value. The following line deals\n    ** with this case by advancing pIter past the zero-padding added by\n    ** fts3EvalNearTrim().  */\n    while( pIter<pEnd && *pIter==0 ) pIter++;\n\n    pDL->pNextDocid = pIter;\n    assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );\n    *pbEof = 0;\n  }\n}\n\n/*\n** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().\n*/\ntypedef struct TokenDoclist TokenDoclist;\nstruct TokenDoclist {\n  int bIgnore;\n  sqlite3_int64 iDocid;\n  char *pList;\n  int nList;\n};\n\n/*\n** Token pToken is an incrementally loaded token that is part of a \n** multi-token phrase. Advance it to the next matching document in the\n** database and populate output variable *p with the details of the new\n** entry. Or, if the iterator has reached EOF, set *pbEof to true.\n**\n** If an error occurs, return an SQLite error code. Otherwise, return \n** SQLITE_OK.\n*/\nstatic int incrPhraseTokenNext(\n  Fts3Table *pTab,                /* Virtual table handle */\n  Fts3Phrase *pPhrase,            /* Phrase to advance token of */\n  int iToken,                     /* Specific token to advance */\n  TokenDoclist *p,                /* OUT: Docid and doclist for new entry */\n  u8 *pbEof                       /* OUT: True if iterator is at EOF */\n){\n  int rc = SQLITE_OK;\n\n  if( pPhrase->iDoclistToken==iToken ){\n    assert( p->bIgnore==0 );\n    assert( pPhrase->aToken[iToken].pSegcsr==0 );\n    fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);\n    p->pList = pPhrase->doclist.pList;\n    p->nList = pPhrase->doclist.nList;\n    p->iDocid = pPhrase->doclist.iDocid;\n  }else{\n    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];\n    assert( pToken->pDeferred==0 );\n    assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );\n    if( pToken->pSegcsr ){\n      assert( p->bIgnore==0 );\n      rc = sqlite3Fts3MsrIncrNext(\n          pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList\n      );\n      if( p->pList==0 ) *pbEof = 1;\n    }else{\n      p->bIgnore = 1;\n    }\n  }\n\n  return rc;\n}\n\n\n/*\n** The phrase iterator passed as the second argument:\n**\n**   * features at least one token that uses an incremental doclist, and \n**\n**   * does not contain any deferred tokens.\n**\n** Advance it to the next matching documnent in the database and populate\n** the Fts3Doclist.pList and nList fields. \n**\n** If there is no \"next\" entry and no error occurs, then *pbEof is set to\n** 1 before returning. Otherwise, if no error occurs and the iterator is\n** successfully advanced, *pbEof is set to 0.\n**\n** If an error occurs, return an SQLite error code. Otherwise, return \n** SQLITE_OK.\n*/\nstatic int fts3EvalIncrPhraseNext(\n  Fts3Cursor *pCsr,               /* FTS Cursor handle */\n  Fts3Phrase *p,                  /* Phrase object to advance to next docid */\n  u8 *pbEof                       /* OUT: Set to 1 if EOF */\n){\n  int rc = SQLITE_OK;\n  Fts3Doclist *pDL = &p->doclist;\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  u8 bEof = 0;\n\n  /* This is only called if it is guaranteed that the phrase has at least\n  ** one incremental token. In which case the bIncr flag is set. */\n  assert( p->bIncr==1 );\n\n  if( p->nToken==1 ){\n    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, \n        &pDL->iDocid, &pDL->pList, &pDL->nList\n    );\n    if( pDL->pList==0 ) bEof = 1;\n  }else{\n    int bDescDoclist = pCsr->bDesc;\n    struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];\n\n    memset(a, 0, sizeof(a));\n    assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );\n    assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );\n\n    while( bEof==0 ){\n      int bMaxSet = 0;\n      sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */\n      int i;                      /* Used to iterate through tokens */\n\n      /* Advance the iterator for each token in the phrase once. */\n      for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){\n        rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);\n        if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){\n          iMax = a[i].iDocid;\n          bMaxSet = 1;\n        }\n      }\n      assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );\n      assert( rc!=SQLITE_OK || bMaxSet );\n\n      /* Keep advancing iterators until they all point to the same document */\n      for(i=0; i<p->nToken; i++){\n        while( rc==SQLITE_OK && bEof==0 \n            && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0 \n        ){\n          rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);\n          if( DOCID_CMP(a[i].iDocid, iMax)>0 ){\n            iMax = a[i].iDocid;\n            i = 0;\n          }\n        }\n      }\n\n      /* Check if the current entries really are a phrase match */\n      if( bEof==0 ){\n        int nList = 0;\n        int nByte = a[p->nToken-1].nList;\n        char *aDoclist = sqlite3_malloc(nByte+FTS3_BUFFER_PADDING);\n        if( !aDoclist ) return SQLITE_NOMEM;\n        memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);\n        memset(&aDoclist[nByte], 0, FTS3_BUFFER_PADDING);\n\n        for(i=0; i<(p->nToken-1); i++){\n          if( a[i].bIgnore==0 ){\n            char *pL = a[i].pList;\n            char *pR = aDoclist;\n            char *pOut = aDoclist;\n            int nDist = p->nToken-1-i;\n            int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);\n            if( res==0 ) break;\n            nList = (int)(pOut - aDoclist);\n          }\n        }\n        if( i==(p->nToken-1) ){\n          pDL->iDocid = iMax;\n          pDL->pList = aDoclist;\n          pDL->nList = nList;\n          pDL->bFreeList = 1;\n          break;\n        }\n        sqlite3_free(aDoclist);\n      }\n    }\n  }\n\n  *pbEof = bEof;\n  return rc;\n}\n\n/*\n** Attempt to move the phrase iterator to point to the next matching docid. \n** If an error occurs, return an SQLite error code. Otherwise, return \n** SQLITE_OK.\n**\n** If there is no \"next\" entry and no error occurs, then *pbEof is set to\n** 1 before returning. Otherwise, if no error occurs and the iterator is\n** successfully advanced, *pbEof is set to 0.\n*/\nstatic int fts3EvalPhraseNext(\n  Fts3Cursor *pCsr,               /* FTS Cursor handle */\n  Fts3Phrase *p,                  /* Phrase object to advance to next docid */\n  u8 *pbEof                       /* OUT: Set to 1 if EOF */\n){\n  int rc = SQLITE_OK;\n  Fts3Doclist *pDL = &p->doclist;\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n\n  if( p->bIncr ){\n    rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);\n  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){\n    sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, \n        &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof\n    );\n    pDL->pList = pDL->pNextDocid;\n  }else{\n    fts3EvalDlPhraseNext(pTab, pDL, pbEof);\n  }\n\n  return rc;\n}\n\n/*\n**\n** If *pRc is not SQLITE_OK when this function is called, it is a no-op.\n** Otherwise, fts3EvalPhraseStart() is called on all phrases within the\n** expression. Also the Fts3Expr.bDeferred variable is set to true for any\n** expressions for which all descendent tokens are deferred.\n**\n** If parameter bOptOk is zero, then it is guaranteed that the\n** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for\n** each phrase in the expression (subject to deferred token processing).\n** Or, if bOptOk is non-zero, then one or more tokens within the expression\n** may be loaded incrementally, meaning doclist.aAll/nAll is not available.\n**\n** If an error occurs within this function, *pRc is set to an SQLite error\n** code before returning.\n*/\nstatic void fts3EvalStartReaders(\n  Fts3Cursor *pCsr,               /* FTS Cursor handle */\n  Fts3Expr *pExpr,                /* Expression to initialize phrases in */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  if( pExpr && SQLITE_OK==*pRc ){\n    if( pExpr->eType==FTSQUERY_PHRASE ){\n      int nToken = pExpr->pPhrase->nToken;\n      if( nToken ){\n        int i;\n        for(i=0; i<nToken; i++){\n          if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;\n        }\n        pExpr->bDeferred = (i==nToken);\n      }\n      *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);\n    }else{\n      fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);\n      fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);\n      pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);\n    }\n  }\n}\n\n/*\n** An array of the following structures is assembled as part of the process\n** of selecting tokens to defer before the query starts executing (as part\n** of the xFilter() method). There is one element in the array for each\n** token in the FTS expression.\n**\n** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong\n** to phrases that are connected only by AND and NEAR operators (not OR or\n** NOT). When determining tokens to defer, each AND/NEAR cluster is considered\n** separately. The root of a tokens AND/NEAR cluster is stored in \n** Fts3TokenAndCost.pRoot.\n*/\ntypedef struct Fts3TokenAndCost Fts3TokenAndCost;\nstruct Fts3TokenAndCost {\n  Fts3Phrase *pPhrase;            /* The phrase the token belongs to */\n  int iToken;                     /* Position of token in phrase */\n  Fts3PhraseToken *pToken;        /* The token itself */\n  Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */\n  int nOvfl;                      /* Number of overflow pages to load doclist */\n  int iCol;                       /* The column the token must match */\n};\n\n/*\n** This function is used to populate an allocated Fts3TokenAndCost array.\n**\n** If *pRc is not SQLITE_OK when this function is called, it is a no-op.\n** Otherwise, if an error occurs during execution, *pRc is set to an\n** SQLite error code.\n*/\nstatic void fts3EvalTokenCosts(\n  Fts3Cursor *pCsr,               /* FTS Cursor handle */\n  Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */\n  Fts3Expr *pExpr,                /* Expression to consider */\n  Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */\n  Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  if( *pRc==SQLITE_OK ){\n    if( pExpr->eType==FTSQUERY_PHRASE ){\n      Fts3Phrase *pPhrase = pExpr->pPhrase;\n      int i;\n      for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){\n        Fts3TokenAndCost *pTC = (*ppTC)++;\n        pTC->pPhrase = pPhrase;\n        pTC->iToken = i;\n        pTC->pRoot = pRoot;\n        pTC->pToken = &pPhrase->aToken[i];\n        pTC->iCol = pPhrase->iColumn;\n        *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);\n      }\n    }else if( pExpr->eType!=FTSQUERY_NOT ){\n      assert( pExpr->eType==FTSQUERY_OR\n           || pExpr->eType==FTSQUERY_AND\n           || pExpr->eType==FTSQUERY_NEAR\n      );\n      assert( pExpr->pLeft && pExpr->pRight );\n      if( pExpr->eType==FTSQUERY_OR ){\n        pRoot = pExpr->pLeft;\n        **ppOr = pRoot;\n        (*ppOr)++;\n      }\n      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);\n      if( pExpr->eType==FTSQUERY_OR ){\n        pRoot = pExpr->pRight;\n        **ppOr = pRoot;\n        (*ppOr)++;\n      }\n      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);\n    }\n  }\n}\n\n/*\n** Determine the average document (row) size in pages. If successful,\n** write this value to *pnPage and return SQLITE_OK. Otherwise, return\n** an SQLite error code.\n**\n** The average document size in pages is calculated by first calculating \n** determining the average size in bytes, B. If B is less than the amount\n** of data that will fit on a single leaf page of an intkey table in\n** this database, then the average docsize is 1. Otherwise, it is 1 plus\n** the number of overflow pages consumed by a record B bytes in size.\n*/\nstatic int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){\n  int rc = SQLITE_OK;\n  if( pCsr->nRowAvg==0 ){\n    /* The average document size, which is required to calculate the cost\n    ** of each doclist, has not yet been determined. Read the required \n    ** data from the %_stat table to calculate it.\n    **\n    ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 \n    ** varints, where nCol is the number of columns in the FTS3 table.\n    ** The first varint is the number of documents currently stored in\n    ** the table. The following nCol varints contain the total amount of\n    ** data stored in all rows of each column of the table, from left\n    ** to right.\n    */\n    Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;\n    sqlite3_stmt *pStmt;\n    sqlite3_int64 nDoc = 0;\n    sqlite3_int64 nByte = 0;\n    const char *pEnd;\n    const char *a;\n\n    rc = sqlite3Fts3SelectDoctotal(p, &pStmt);\n    if( rc!=SQLITE_OK ) return rc;\n    a = sqlite3_column_blob(pStmt, 0);\n    testcase( a==0 );  /* If %_stat.value set to X'' */\n    if( a ){\n      pEnd = &a[sqlite3_column_bytes(pStmt, 0)];\n      a += sqlite3Fts3GetVarintBounded(a, pEnd, &nDoc);\n      while( a<pEnd ){\n        a += sqlite3Fts3GetVarintBounded(a, pEnd, &nByte);\n      }\n    }\n    if( nDoc==0 || nByte==0 ){\n      sqlite3_reset(pStmt);\n      return FTS_CORRUPT_VTAB;\n    }\n\n    pCsr->nDoc = nDoc;\n    pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);\n    assert( pCsr->nRowAvg>0 ); \n    rc = sqlite3_reset(pStmt);\n  }\n\n  *pnPage = pCsr->nRowAvg;\n  return rc;\n}\n\n/*\n** This function is called to select the tokens (if any) that will be \n** deferred. The array aTC[] has already been populated when this is\n** called.\n**\n** This function is called once for each AND/NEAR cluster in the \n** expression. Each invocation determines which tokens to defer within\n** the cluster with root node pRoot. See comments above the definition\n** of struct Fts3TokenAndCost for more details.\n**\n** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()\n** called on each token to defer. Otherwise, an SQLite error code is\n** returned.\n*/\nstatic int fts3EvalSelectDeferred(\n  Fts3Cursor *pCsr,               /* FTS Cursor handle */\n  Fts3Expr *pRoot,                /* Consider tokens with this root node */\n  Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */\n  int nTC                         /* Number of entries in aTC[] */\n){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  int nDocSize = 0;               /* Number of pages per doc loaded */\n  int rc = SQLITE_OK;             /* Return code */\n  int ii;                         /* Iterator variable for various purposes */\n  int nOvfl = 0;                  /* Total overflow pages used by doclists */\n  int nToken = 0;                 /* Total number of tokens in cluster */\n\n  int nMinEst = 0;                /* The minimum count for any phrase so far. */\n  int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */\n\n  /* Tokens are never deferred for FTS tables created using the content=xxx\n  ** option. The reason being that it is not guaranteed that the content\n  ** table actually contains the same data as the index. To prevent this from\n  ** causing any problems, the deferred token optimization is completely\n  ** disabled for content=xxx tables. */\n  if( pTab->zContentTbl ){\n    return SQLITE_OK;\n  }\n\n  /* Count the tokens in this AND/NEAR cluster. If none of the doclists\n  ** associated with the tokens spill onto overflow pages, or if there is\n  ** only 1 token, exit early. No tokens to defer in this case. */\n  for(ii=0; ii<nTC; ii++){\n    if( aTC[ii].pRoot==pRoot ){\n      nOvfl += aTC[ii].nOvfl;\n      nToken++;\n    }\n  }\n  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;\n\n  /* Obtain the average docsize (in pages). */\n  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);\n  assert( rc!=SQLITE_OK || nDocSize>0 );\n\n\n  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order \n  ** of the number of overflow pages that will be loaded by the pager layer \n  ** to retrieve the entire doclist for the token from the full-text index.\n  ** Load the doclists for tokens that are either:\n  **\n  **   a. The cheapest token in the entire query (i.e. the one visited by the\n  **      first iteration of this loop), or\n  **\n  **   b. Part of a multi-token phrase.\n  **\n  ** After each token doclist is loaded, merge it with the others from the\n  ** same phrase and count the number of documents that the merged doclist\n  ** contains. Set variable \"nMinEst\" to the smallest number of documents in \n  ** any phrase doclist for which 1 or more token doclists have been loaded.\n  ** Let nOther be the number of other phrases for which it is certain that\n  ** one or more tokens will not be deferred.\n  **\n  ** Then, for each token, defer it if loading the doclist would result in\n  ** loading N or more overflow pages into memory, where N is computed as:\n  **\n  **    (nMinEst + 4^nOther - 1) / (4^nOther)\n  */\n  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){\n    int iTC;                      /* Used to iterate through aTC[] array. */\n    Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */\n\n    /* Set pTC to point to the cheapest remaining token. */\n    for(iTC=0; iTC<nTC; iTC++){\n      if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot \n       && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl) \n      ){\n        pTC = &aTC[iTC];\n      }\n    }\n    assert( pTC );\n\n    if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){\n      /* The number of overflow pages to load for this (and therefore all\n      ** subsequent) tokens is greater than the estimated number of pages \n      ** that will be loaded if all subsequent tokens are deferred.\n      */\n      Fts3PhraseToken *pToken = pTC->pToken;\n      rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);\n      fts3SegReaderCursorFree(pToken->pSegcsr);\n      pToken->pSegcsr = 0;\n    }else{\n      /* Set nLoad4 to the value of (4^nOther) for the next iteration of the\n      ** for-loop. Except, limit the value to 2^24 to prevent it from \n      ** overflowing the 32-bit integer it is stored in. */\n      if( ii<12 ) nLoad4 = nLoad4*4;\n\n      if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){\n        /* Either this is the cheapest token in the entire query, or it is\n        ** part of a multi-token phrase. Either way, the entire doclist will\n        ** (eventually) be loaded into memory. It may as well be now. */\n        Fts3PhraseToken *pToken = pTC->pToken;\n        int nList = 0;\n        char *pList = 0;\n        rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);\n        assert( rc==SQLITE_OK || pList==0 );\n        if( rc==SQLITE_OK ){\n          rc = fts3EvalPhraseMergeToken(\n              pTab, pTC->pPhrase, pTC->iToken,pList,nList\n          );\n        }\n        if( rc==SQLITE_OK ){\n          int nCount;\n          nCount = fts3DoclistCountDocids(\n              pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll\n          );\n          if( ii==0 || nCount<nMinEst ) nMinEst = nCount;\n        }\n      }\n    }\n    pTC->pToken = 0;\n  }\n\n  return rc;\n}\n\n/*\n** This function is called from within the xFilter method. It initializes\n** the full-text query currently stored in pCsr->pExpr. To iterate through\n** the results of a query, the caller does:\n**\n**    fts3EvalStart(pCsr);\n**    while( 1 ){\n**      fts3EvalNext(pCsr);\n**      if( pCsr->bEof ) break;\n**      ... return row pCsr->iPrevId to the caller ...\n**    }\n*/\nstatic int fts3EvalStart(Fts3Cursor *pCsr){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  int rc = SQLITE_OK;\n  int nToken = 0;\n  int nOr = 0;\n\n  /* Allocate a MultiSegReader for each token in the expression. */\n  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);\n\n  /* Determine which, if any, tokens in the expression should be deferred. */\n#ifndef SQLITE_DISABLE_FTS4_DEFERRED\n  if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){\n    Fts3TokenAndCost *aTC;\n    Fts3Expr **apOr;\n    aTC = (Fts3TokenAndCost *)sqlite3_malloc64(\n        sizeof(Fts3TokenAndCost) * nToken\n      + sizeof(Fts3Expr *) * nOr * 2\n    );\n    apOr = (Fts3Expr **)&aTC[nToken];\n\n    if( !aTC ){\n      rc = SQLITE_NOMEM;\n    }else{\n      int ii;\n      Fts3TokenAndCost *pTC = aTC;\n      Fts3Expr **ppOr = apOr;\n\n      fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);\n      nToken = (int)(pTC-aTC);\n      nOr = (int)(ppOr-apOr);\n\n      if( rc==SQLITE_OK ){\n        rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);\n        for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){\n          rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);\n        }\n      }\n\n      sqlite3_free(aTC);\n    }\n  }\n#endif\n\n  fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);\n  return rc;\n}\n\n/*\n** Invalidate the current position list for phrase pPhrase.\n*/\nstatic void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){\n  if( pPhrase->doclist.bFreeList ){\n    sqlite3_free(pPhrase->doclist.pList);\n  }\n  pPhrase->doclist.pList = 0;\n  pPhrase->doclist.nList = 0;\n  pPhrase->doclist.bFreeList = 0;\n}\n\n/*\n** This function is called to edit the position list associated with\n** the phrase object passed as the fifth argument according to a NEAR\n** condition. For example:\n**\n**     abc NEAR/5 \"def ghi\"\n**\n** Parameter nNear is passed the NEAR distance of the expression (5 in\n** the example above). When this function is called, *paPoslist points to\n** the position list, and *pnToken is the number of phrase tokens in the\n** phrase on the other side of the NEAR operator to pPhrase. For example,\n** if pPhrase refers to the \"def ghi\" phrase, then *paPoslist points to\n** the position list associated with phrase \"abc\".\n**\n** All positions in the pPhrase position list that are not sufficiently\n** close to a position in the *paPoslist position list are removed. If this\n** leaves 0 positions, zero is returned. Otherwise, non-zero.\n**\n** Before returning, *paPoslist is set to point to the position lsit \n** associated with pPhrase. And *pnToken is set to the number of tokens in\n** pPhrase.\n*/\nstatic int fts3EvalNearTrim(\n  int nNear,                      /* NEAR distance. As in \"NEAR/nNear\". */\n  char *aTmp,                     /* Temporary space to use */\n  char **paPoslist,               /* IN/OUT: Position list */\n  int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */\n  Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */\n){\n  int nParam1 = nNear + pPhrase->nToken;\n  int nParam2 = nNear + *pnToken;\n  int nNew;\n  char *p2; \n  char *pOut; \n  int res;\n\n  assert( pPhrase->doclist.pList );\n\n  p2 = pOut = pPhrase->doclist.pList;\n  res = fts3PoslistNearMerge(\n    &pOut, aTmp, nParam1, nParam2, paPoslist, &p2\n  );\n  if( res ){\n    nNew = (int)(pOut - pPhrase->doclist.pList) - 1;\n    assert( pPhrase->doclist.pList[nNew]=='\\0' );\n    assert( nNew<=pPhrase->doclist.nList && nNew>0 );\n    memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);\n    pPhrase->doclist.nList = nNew;\n    *paPoslist = pPhrase->doclist.pList;\n    *pnToken = pPhrase->nToken;\n  }\n\n  return res;\n}\n\n/*\n** This function is a no-op if *pRc is other than SQLITE_OK when it is called.\n** Otherwise, it advances the expression passed as the second argument to\n** point to the next matching row in the database. Expressions iterate through\n** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,\n** or descending if it is non-zero.\n**\n** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if\n** successful, the following variables in pExpr are set:\n**\n**   Fts3Expr.bEof                (non-zero if EOF - there is no next row)\n**   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)\n**\n** If the expression is of type FTSQUERY_PHRASE, and the expression is not\n** at EOF, then the following variables are populated with the position list\n** for the phrase for the visited row:\n**\n**   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)\n**   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)\n**\n** It says above that this function advances the expression to the next\n** matching row. This is usually true, but there are the following exceptions:\n**\n**   1. Deferred tokens are not taken into account. If a phrase consists\n**      entirely of deferred tokens, it is assumed to match every row in\n**      the db. In this case the position-list is not populated at all. \n**\n**      Or, if a phrase contains one or more deferred tokens and one or\n**      more non-deferred tokens, then the expression is advanced to the \n**      next possible match, considering only non-deferred tokens. In other\n**      words, if the phrase is \"A B C\", and \"B\" is deferred, the expression\n**      is advanced to the next row that contains an instance of \"A * C\", \n**      where \"*\" may match any single token. The position list in this case\n**      is populated as for \"A * C\" before returning.\n**\n**   2. NEAR is treated as AND. If the expression is \"x NEAR y\", it is \n**      advanced to point to the next row that matches \"x AND y\".\n** \n** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is\n** really a match, taking into account deferred tokens and NEAR operators.\n*/\nstatic void fts3EvalNextRow(\n  Fts3Cursor *pCsr,               /* FTS Cursor handle */\n  Fts3Expr *pExpr,                /* Expr. to advance to next matching row */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  if( *pRc==SQLITE_OK ){\n    int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */\n    assert( pExpr->bEof==0 );\n    pExpr->bStart = 1;\n\n    switch( pExpr->eType ){\n      case FTSQUERY_NEAR:\n      case FTSQUERY_AND: {\n        Fts3Expr *pLeft = pExpr->pLeft;\n        Fts3Expr *pRight = pExpr->pRight;\n        assert( !pLeft->bDeferred || !pRight->bDeferred );\n\n        if( pLeft->bDeferred ){\n          /* LHS is entirely deferred. So we assume it matches every row.\n          ** Advance the RHS iterator to find the next row visited. */\n          fts3EvalNextRow(pCsr, pRight, pRc);\n          pExpr->iDocid = pRight->iDocid;\n          pExpr->bEof = pRight->bEof;\n        }else if( pRight->bDeferred ){\n          /* RHS is entirely deferred. So we assume it matches every row.\n          ** Advance the LHS iterator to find the next row visited. */\n          fts3EvalNextRow(pCsr, pLeft, pRc);\n          pExpr->iDocid = pLeft->iDocid;\n          pExpr->bEof = pLeft->bEof;\n        }else{\n          /* Neither the RHS or LHS are deferred. */\n          fts3EvalNextRow(pCsr, pLeft, pRc);\n          fts3EvalNextRow(pCsr, pRight, pRc);\n          while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){\n            sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);\n            if( iDiff==0 ) break;\n            if( iDiff<0 ){\n              fts3EvalNextRow(pCsr, pLeft, pRc);\n            }else{\n              fts3EvalNextRow(pCsr, pRight, pRc);\n            }\n          }\n          pExpr->iDocid = pLeft->iDocid;\n          pExpr->bEof = (pLeft->bEof || pRight->bEof);\n          if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){\n            assert( pRight->eType==FTSQUERY_PHRASE );\n            if( pRight->pPhrase->doclist.aAll ){\n              Fts3Doclist *pDl = &pRight->pPhrase->doclist;\n              while( *pRc==SQLITE_OK && pRight->bEof==0 ){\n                memset(pDl->pList, 0, pDl->nList);\n                fts3EvalNextRow(pCsr, pRight, pRc);\n              }\n            }\n            if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){\n              Fts3Doclist *pDl = &pLeft->pPhrase->doclist;\n              while( *pRc==SQLITE_OK && pLeft->bEof==0 ){\n                memset(pDl->pList, 0, pDl->nList);\n                fts3EvalNextRow(pCsr, pLeft, pRc);\n              }\n            }\n            pRight->bEof = pLeft->bEof = 1;\n          }\n        }\n        break;\n      }\n  \n      case FTSQUERY_OR: {\n        Fts3Expr *pLeft = pExpr->pLeft;\n        Fts3Expr *pRight = pExpr->pRight;\n        sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);\n\n        assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );\n        assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );\n\n        if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){\n          fts3EvalNextRow(pCsr, pLeft, pRc);\n        }else if( pLeft->bEof || iCmp>0 ){\n          fts3EvalNextRow(pCsr, pRight, pRc);\n        }else{\n          fts3EvalNextRow(pCsr, pLeft, pRc);\n          fts3EvalNextRow(pCsr, pRight, pRc);\n        }\n\n        pExpr->bEof = (pLeft->bEof && pRight->bEof);\n        iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);\n        if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){\n          pExpr->iDocid = pLeft->iDocid;\n        }else{\n          pExpr->iDocid = pRight->iDocid;\n        }\n\n        break;\n      }\n\n      case FTSQUERY_NOT: {\n        Fts3Expr *pLeft = pExpr->pLeft;\n        Fts3Expr *pRight = pExpr->pRight;\n\n        if( pRight->bStart==0 ){\n          fts3EvalNextRow(pCsr, pRight, pRc);\n          assert( *pRc!=SQLITE_OK || pRight->bStart );\n        }\n\n        fts3EvalNextRow(pCsr, pLeft, pRc);\n        if( pLeft->bEof==0 ){\n          while( !*pRc \n              && !pRight->bEof \n              && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 \n          ){\n            fts3EvalNextRow(pCsr, pRight, pRc);\n          }\n        }\n        pExpr->iDocid = pLeft->iDocid;\n        pExpr->bEof = pLeft->bEof;\n        break;\n      }\n\n      default: {\n        Fts3Phrase *pPhrase = pExpr->pPhrase;\n        fts3EvalInvalidatePoslist(pPhrase);\n        *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);\n        pExpr->iDocid = pPhrase->doclist.iDocid;\n        break;\n      }\n    }\n  }\n}\n\n/*\n** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR\n** cluster, then this function returns 1 immediately.\n**\n** Otherwise, it checks if the current row really does match the NEAR \n** expression, using the data currently stored in the position lists \n** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. \n**\n** If the current row is a match, the position list associated with each\n** phrase in the NEAR expression is edited in place to contain only those\n** phrase instances sufficiently close to their peers to satisfy all NEAR\n** constraints. In this case it returns 1. If the NEAR expression does not \n** match the current row, 0 is returned. The position lists may or may not\n** be edited if 0 is returned.\n*/\nstatic int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){\n  int res = 1;\n\n  /* The following block runs if pExpr is the root of a NEAR query.\n  ** For example, the query:\n  **\n  **         \"w\" NEAR \"x\" NEAR \"y\" NEAR \"z\"\n  **\n  ** which is represented in tree form as:\n  **\n  **                               |\n  **                          +--NEAR--+      <-- root of NEAR query\n  **                          |        |\n  **                     +--NEAR--+   \"z\"\n  **                     |        |\n  **                +--NEAR--+   \"y\"\n  **                |        |\n  **               \"w\"      \"x\"\n  **\n  ** The right-hand child of a NEAR node is always a phrase. The \n  ** left-hand child may be either a phrase or a NEAR node. There are\n  ** no exceptions to this - it's the way the parser in fts3_expr.c works.\n  */\n  if( *pRc==SQLITE_OK \n   && pExpr->eType==FTSQUERY_NEAR \n   && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)\n  ){\n    Fts3Expr *p; \n    sqlite3_int64 nTmp = 0;       /* Bytes of temp space */\n    char *aTmp;                   /* Temp space for PoslistNearMerge() */\n\n    /* Allocate temporary working space. */\n    for(p=pExpr; p->pLeft; p=p->pLeft){\n      assert( p->pRight->pPhrase->doclist.nList>0 );\n      nTmp += p->pRight->pPhrase->doclist.nList;\n    }\n    nTmp += p->pPhrase->doclist.nList;\n    aTmp = sqlite3_malloc64(nTmp*2);\n    if( !aTmp ){\n      *pRc = SQLITE_NOMEM;\n      res = 0;\n    }else{\n      char *aPoslist = p->pPhrase->doclist.pList;\n      int nToken = p->pPhrase->nToken;\n\n      for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){\n        Fts3Phrase *pPhrase = p->pRight->pPhrase;\n        int nNear = p->nNear;\n        res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);\n      }\n\n      aPoslist = pExpr->pRight->pPhrase->doclist.pList;\n      nToken = pExpr->pRight->pPhrase->nToken;\n      for(p=pExpr->pLeft; p && res; p=p->pLeft){\n        int nNear;\n        Fts3Phrase *pPhrase;\n        assert( p->pParent && p->pParent->pLeft==p );\n        nNear = p->pParent->nNear;\n        pPhrase = (\n            p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase\n        );\n        res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);\n      }\n    }\n\n    sqlite3_free(aTmp);\n  }\n\n  return res;\n}\n\n/*\n** This function is a helper function for sqlite3Fts3EvalTestDeferred().\n** Assuming no error occurs or has occurred, It returns non-zero if the\n** expression passed as the second argument matches the row that pCsr \n** currently points to, or zero if it does not.\n**\n** If *pRc is not SQLITE_OK when this function is called, it is a no-op.\n** If an error occurs during execution of this function, *pRc is set to \n** the appropriate SQLite error code. In this case the returned value is \n** undefined.\n*/\nstatic int fts3EvalTestExpr(\n  Fts3Cursor *pCsr,               /* FTS cursor handle */\n  Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  int bHit = 1;                   /* Return value */\n  if( *pRc==SQLITE_OK ){\n    switch( pExpr->eType ){\n      case FTSQUERY_NEAR:\n      case FTSQUERY_AND:\n        bHit = (\n            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)\n         && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)\n         && fts3EvalNearTest(pExpr, pRc)\n        );\n\n        /* If the NEAR expression does not match any rows, zero the doclist for \n        ** all phrases involved in the NEAR. This is because the snippet(),\n        ** offsets() and matchinfo() functions are not supposed to recognize \n        ** any instances of phrases that are part of unmatched NEAR queries. \n        ** For example if this expression:\n        **\n        **    ... MATCH 'a OR (b NEAR c)'\n        **\n        ** is matched against a row containing:\n        **\n        **        'a b d e'\n        **\n        ** then any snippet() should ony highlight the \"a\" term, not the \"b\"\n        ** (as \"b\" is part of a non-matching NEAR clause).\n        */\n        if( bHit==0 \n         && pExpr->eType==FTSQUERY_NEAR \n         && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)\n        ){\n          Fts3Expr *p;\n          for(p=pExpr; p->pPhrase==0; p=p->pLeft){\n            if( p->pRight->iDocid==pCsr->iPrevId ){\n              fts3EvalInvalidatePoslist(p->pRight->pPhrase);\n            }\n          }\n          if( p->iDocid==pCsr->iPrevId ){\n            fts3EvalInvalidatePoslist(p->pPhrase);\n          }\n        }\n\n        break;\n\n      case FTSQUERY_OR: {\n        int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);\n        int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);\n        bHit = bHit1 || bHit2;\n        break;\n      }\n\n      case FTSQUERY_NOT:\n        bHit = (\n            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)\n         && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)\n        );\n        break;\n\n      default: {\n#ifndef SQLITE_DISABLE_FTS4_DEFERRED\n        if( pCsr->pDeferred \n         && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)\n        ){\n          Fts3Phrase *pPhrase = pExpr->pPhrase;\n          assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );\n          if( pExpr->bDeferred ){\n            fts3EvalInvalidatePoslist(pPhrase);\n          }\n          *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);\n          bHit = (pPhrase->doclist.pList!=0);\n          pExpr->iDocid = pCsr->iPrevId;\n        }else\n#endif\n        {\n          bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);\n        }\n        break;\n      }\n    }\n  }\n  return bHit;\n}\n\n/*\n** This function is called as the second part of each xNext operation when\n** iterating through the results of a full-text query. At this point the\n** cursor points to a row that matches the query expression, with the\n** following caveats:\n**\n**   * Up until this point, \"NEAR\" operators in the expression have been\n**     treated as \"AND\".\n**\n**   * Deferred tokens have not yet been considered.\n**\n** If *pRc is not SQLITE_OK when this function is called, it immediately\n** returns 0. Otherwise, it tests whether or not after considering NEAR\n** operators and deferred tokens the current row is still a match for the\n** expression. It returns 1 if both of the following are true:\n**\n**   1. *pRc is SQLITE_OK when this function returns, and\n**\n**   2. After scanning the current FTS table row for the deferred tokens,\n**      it is determined that the row does *not* match the query.\n**\n** Or, if no error occurs and it seems the current row does match the FTS\n** query, return 0.\n*/\nSQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){\n  int rc = *pRc;\n  int bMiss = 0;\n  if( rc==SQLITE_OK ){\n\n    /* If there are one or more deferred tokens, load the current row into\n    ** memory and scan it to determine the position list for each deferred\n    ** token. Then, see if this row is really a match, considering deferred\n    ** tokens and NEAR operators (neither of which were taken into account\n    ** earlier, by fts3EvalNextRow()). \n    */\n    if( pCsr->pDeferred ){\n      rc = fts3CursorSeek(0, pCsr);\n      if( rc==SQLITE_OK ){\n        rc = sqlite3Fts3CacheDeferredDoclists(pCsr);\n      }\n    }\n    bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));\n\n    /* Free the position-lists accumulated for each deferred token above. */\n    sqlite3Fts3FreeDeferredDoclists(pCsr);\n    *pRc = rc;\n  }\n  return (rc==SQLITE_OK && bMiss);\n}\n\n/*\n** Advance to the next document that matches the FTS expression in\n** Fts3Cursor.pExpr.\n*/\nstatic int fts3EvalNext(Fts3Cursor *pCsr){\n  int rc = SQLITE_OK;             /* Return Code */\n  Fts3Expr *pExpr = pCsr->pExpr;\n  assert( pCsr->isEof==0 );\n  if( pExpr==0 ){\n    pCsr->isEof = 1;\n  }else{\n    do {\n      if( pCsr->isRequireSeek==0 ){\n        sqlite3_reset(pCsr->pStmt);\n      }\n      assert( sqlite3_data_count(pCsr->pStmt)==0 );\n      fts3EvalNextRow(pCsr, pExpr, &rc);\n      pCsr->isEof = pExpr->bEof;\n      pCsr->isRequireSeek = 1;\n      pCsr->isMatchinfoNeeded = 1;\n      pCsr->iPrevId = pExpr->iDocid;\n    }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );\n  }\n\n  /* Check if the cursor is past the end of the docid range specified\n  ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */\n  if( rc==SQLITE_OK && (\n        (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)\n     || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)\n  )){\n    pCsr->isEof = 1;\n  }\n\n  return rc;\n}\n\n/*\n** Restart interation for expression pExpr so that the next call to\n** fts3EvalNext() visits the first row. Do not allow incremental \n** loading or merging of phrase doclists for this iteration.\n**\n** If *pRc is other than SQLITE_OK when this function is called, it is\n** a no-op. If an error occurs within this function, *pRc is set to an\n** SQLite error code before returning.\n*/\nstatic void fts3EvalRestart(\n  Fts3Cursor *pCsr,\n  Fts3Expr *pExpr,\n  int *pRc\n){\n  if( pExpr && *pRc==SQLITE_OK ){\n    Fts3Phrase *pPhrase = pExpr->pPhrase;\n\n    if( pPhrase ){\n      fts3EvalInvalidatePoslist(pPhrase);\n      if( pPhrase->bIncr ){\n        int i;\n        for(i=0; i<pPhrase->nToken; i++){\n          Fts3PhraseToken *pToken = &pPhrase->aToken[i];\n          assert( pToken->pDeferred==0 );\n          if( pToken->pSegcsr ){\n            sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);\n          }\n        }\n        *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);\n      }\n      pPhrase->doclist.pNextDocid = 0;\n      pPhrase->doclist.iDocid = 0;\n      pPhrase->pOrPoslist = 0;\n    }\n\n    pExpr->iDocid = 0;\n    pExpr->bEof = 0;\n    pExpr->bStart = 0;\n\n    fts3EvalRestart(pCsr, pExpr->pLeft, pRc);\n    fts3EvalRestart(pCsr, pExpr->pRight, pRc);\n  }\n}\n\n/*\n** After allocating the Fts3Expr.aMI[] array for each phrase in the \n** expression rooted at pExpr, the cursor iterates through all rows matched\n** by pExpr, calling this function for each row. This function increments\n** the values in Fts3Expr.aMI[] according to the position-list currently\n** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase \n** expression nodes.\n*/\nstatic void fts3EvalUpdateCounts(Fts3Expr *pExpr, int nCol){\n  if( pExpr ){\n    Fts3Phrase *pPhrase = pExpr->pPhrase;\n    if( pPhrase && pPhrase->doclist.pList ){\n      int iCol = 0;\n      char *p = pPhrase->doclist.pList;\n\n      do{\n        u8 c = 0;\n        int iCnt = 0;\n        while( 0xFE & (*p | c) ){\n          if( (c&0x80)==0 ) iCnt++;\n          c = *p++ & 0x80;\n        }\n\n        /* aMI[iCol*3 + 1] = Number of occurrences\n        ** aMI[iCol*3 + 2] = Number of rows containing at least one instance\n        */\n        pExpr->aMI[iCol*3 + 1] += iCnt;\n        pExpr->aMI[iCol*3 + 2] += (iCnt>0);\n        if( *p==0x00 ) break;\n        p++;\n        p += fts3GetVarint32(p, &iCol);\n      }while( iCol<nCol );\n    }\n\n    fts3EvalUpdateCounts(pExpr->pLeft, nCol);\n    fts3EvalUpdateCounts(pExpr->pRight, nCol);\n  }\n}\n\n/*\n** Expression pExpr must be of type FTSQUERY_PHRASE.\n**\n** If it is not already allocated and populated, this function allocates and\n** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part\n** of a NEAR expression, then it also allocates and populates the same array\n** for all other phrases that are part of the NEAR expression.\n**\n** SQLITE_OK is returned if the aMI[] array is successfully allocated and\n** populated. Otherwise, if an error occurs, an SQLite error code is returned.\n*/\nstatic int fts3EvalGatherStats(\n  Fts3Cursor *pCsr,               /* Cursor object */\n  Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */\n){\n  int rc = SQLITE_OK;             /* Return code */\n\n  assert( pExpr->eType==FTSQUERY_PHRASE );\n  if( pExpr->aMI==0 ){\n    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n    Fts3Expr *pRoot;                /* Root of NEAR expression */\n    Fts3Expr *p;                    /* Iterator used for several purposes */\n\n    sqlite3_int64 iPrevId = pCsr->iPrevId;\n    sqlite3_int64 iDocid;\n    u8 bEof;\n\n    /* Find the root of the NEAR expression */\n    pRoot = pExpr;\n    while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){\n      pRoot = pRoot->pParent;\n    }\n    iDocid = pRoot->iDocid;\n    bEof = pRoot->bEof;\n    assert( pRoot->bStart );\n\n    /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */\n    for(p=pRoot; p; p=p->pLeft){\n      Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);\n      assert( pE->aMI==0 );\n      pE->aMI = (u32 *)sqlite3_malloc64(pTab->nColumn * 3 * sizeof(u32));\n      if( !pE->aMI ) return SQLITE_NOMEM;\n      memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));\n    }\n\n    fts3EvalRestart(pCsr, pRoot, &rc);\n\n    while( pCsr->isEof==0 && rc==SQLITE_OK ){\n\n      do {\n        /* Ensure the %_content statement is reset. */\n        if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);\n        assert( sqlite3_data_count(pCsr->pStmt)==0 );\n\n        /* Advance to the next document */\n        fts3EvalNextRow(pCsr, pRoot, &rc);\n        pCsr->isEof = pRoot->bEof;\n        pCsr->isRequireSeek = 1;\n        pCsr->isMatchinfoNeeded = 1;\n        pCsr->iPrevId = pRoot->iDocid;\n      }while( pCsr->isEof==0 \n           && pRoot->eType==FTSQUERY_NEAR \n           && sqlite3Fts3EvalTestDeferred(pCsr, &rc) \n      );\n\n      if( rc==SQLITE_OK && pCsr->isEof==0 ){\n        fts3EvalUpdateCounts(pRoot, pTab->nColumn);\n      }\n    }\n\n    pCsr->isEof = 0;\n    pCsr->iPrevId = iPrevId;\n\n    if( bEof ){\n      pRoot->bEof = bEof;\n    }else{\n      /* Caution: pRoot may iterate through docids in ascending or descending\n      ** order. For this reason, even though it seems more defensive, the \n      ** do loop can not be written:\n      **\n      **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );\n      */\n      fts3EvalRestart(pCsr, pRoot, &rc);\n      do {\n        fts3EvalNextRow(pCsr, pRoot, &rc);\n        assert( pRoot->bEof==0 );\n      }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );\n    }\n  }\n  return rc;\n}\n\n/*\n** This function is used by the matchinfo() module to query a phrase \n** expression node for the following information:\n**\n**   1. The total number of occurrences of the phrase in each column of \n**      the FTS table (considering all rows), and\n**\n**   2. For each column, the number of rows in the table for which the\n**      column contains at least one instance of the phrase.\n**\n** If no error occurs, SQLITE_OK is returned and the values for each column\n** written into the array aiOut as follows:\n**\n**   aiOut[iCol*3 + 1] = Number of occurrences\n**   aiOut[iCol*3 + 2] = Number of rows containing at least one instance\n**\n** Caveats:\n**\n**   * If a phrase consists entirely of deferred tokens, then all output \n**     values are set to the number of documents in the table. In other\n**     words we assume that very common tokens occur exactly once in each \n**     column of each row of the table.\n**\n**   * If a phrase contains some deferred tokens (and some non-deferred \n**     tokens), count the potential occurrence identified by considering\n**     the non-deferred tokens instead of actual phrase occurrences.\n**\n**   * If the phrase is part of a NEAR expression, then only phrase instances\n**     that meet the NEAR constraint are included in the counts.\n*/\nSQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(\n  Fts3Cursor *pCsr,               /* FTS cursor handle */\n  Fts3Expr *pExpr,                /* Phrase expression */\n  u32 *aiOut                      /* Array to write results into (see above) */\n){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  int rc = SQLITE_OK;\n  int iCol;\n\n  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){\n    assert( pCsr->nDoc>0 );\n    for(iCol=0; iCol<pTab->nColumn; iCol++){\n      aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;\n      aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;\n    }\n  }else{\n    rc = fts3EvalGatherStats(pCsr, pExpr);\n    if( rc==SQLITE_OK ){\n      assert( pExpr->aMI );\n      for(iCol=0; iCol<pTab->nColumn; iCol++){\n        aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];\n        aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];\n      }\n    }\n  }\n\n  return rc;\n}\n\n/*\n** The expression pExpr passed as the second argument to this function\n** must be of type FTSQUERY_PHRASE. \n**\n** The returned value is either NULL or a pointer to a buffer containing\n** a position-list indicating the occurrences of the phrase in column iCol\n** of the current row. \n**\n** More specifically, the returned buffer contains 1 varint for each \n** occurrence of the phrase in the column, stored using the normal (delta+2) \n** compression and is terminated by either an 0x01 or 0x00 byte. For example,\n** if the requested column contains \"a b X c d X X\" and the position-list\n** for 'X' is requested, the buffer returned may contain:\n**\n**     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00\n**\n** This function works regardless of whether or not the phrase is deferred,\n** incremental, or neither.\n*/\nSQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(\n  Fts3Cursor *pCsr,               /* FTS3 cursor object */\n  Fts3Expr *pExpr,                /* Phrase to return doclist for */\n  int iCol,                       /* Column to return position list for */\n  char **ppOut                    /* OUT: Pointer to position list */\n){\n  Fts3Phrase *pPhrase = pExpr->pPhrase;\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  char *pIter;\n  int iThis;\n  sqlite3_int64 iDocid;\n\n  /* If this phrase is applies specifically to some column other than \n  ** column iCol, return a NULL pointer.  */\n  *ppOut = 0;\n  assert( iCol>=0 && iCol<pTab->nColumn );\n  if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){\n    return SQLITE_OK;\n  }\n\n  iDocid = pExpr->iDocid;\n  pIter = pPhrase->doclist.pList;\n  if( iDocid!=pCsr->iPrevId || pExpr->bEof ){\n    int rc = SQLITE_OK;\n    int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */\n    int bOr = 0;\n    u8 bTreeEof = 0;\n    Fts3Expr *p;                  /* Used to iterate from pExpr to root */\n    Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */\n    int bMatch;\n\n    /* Check if this phrase descends from an OR expression node. If not, \n    ** return NULL. Otherwise, the entry that corresponds to docid \n    ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the\n    ** tree that the node is part of has been marked as EOF, but the node\n    ** itself is not EOF, then it may point to an earlier entry. */\n    pNear = pExpr;\n    for(p=pExpr->pParent; p; p=p->pParent){\n      if( p->eType==FTSQUERY_OR ) bOr = 1;\n      if( p->eType==FTSQUERY_NEAR ) pNear = p;\n      if( p->bEof ) bTreeEof = 1;\n    }\n    if( bOr==0 ) return SQLITE_OK;\n\n    /* This is the descendent of an OR node. In this case we cannot use\n    ** an incremental phrase. Load the entire doclist for the phrase\n    ** into memory in this case.  */\n    if( pPhrase->bIncr ){\n      int bEofSave = pNear->bEof;\n      fts3EvalRestart(pCsr, pNear, &rc);\n      while( rc==SQLITE_OK && !pNear->bEof ){\n        fts3EvalNextRow(pCsr, pNear, &rc);\n        if( bEofSave==0 && pNear->iDocid==iDocid ) break;\n      }\n      assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );\n    }\n    if( bTreeEof ){\n      while( rc==SQLITE_OK && !pNear->bEof ){\n        fts3EvalNextRow(pCsr, pNear, &rc);\n      }\n    }\n    if( rc!=SQLITE_OK ) return rc;\n\n    bMatch = 1;\n    for(p=pNear; p; p=p->pLeft){\n      u8 bEof = 0;\n      Fts3Expr *pTest = p;\n      Fts3Phrase *pPh;\n      assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );\n      if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;\n      assert( pTest->eType==FTSQUERY_PHRASE );\n      pPh = pTest->pPhrase;\n\n      pIter = pPh->pOrPoslist;\n      iDocid = pPh->iOrDocid;\n      if( pCsr->bDesc==bDescDoclist ){\n        bEof = !pPh->doclist.nAll ||\n          (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));\n        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){\n          sqlite3Fts3DoclistNext(\n              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, \n              &pIter, &iDocid, &bEof\n          );\n        }\n      }else{\n        bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);\n        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){\n          int dummy;\n          sqlite3Fts3DoclistPrev(\n              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, \n              &pIter, &iDocid, &dummy, &bEof\n              );\n        }\n      }\n      pPh->pOrPoslist = pIter;\n      pPh->iOrDocid = iDocid;\n      if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;\n    }\n\n    if( bMatch ){\n      pIter = pPhrase->pOrPoslist;\n    }else{\n      pIter = 0;\n    }\n  }\n  if( pIter==0 ) return SQLITE_OK;\n\n  if( *pIter==0x01 ){\n    pIter++;\n    pIter += fts3GetVarint32(pIter, &iThis);\n  }else{\n    iThis = 0;\n  }\n  while( iThis<iCol ){\n    fts3ColumnlistCopy(0, &pIter);\n    if( *pIter==0x00 ) return SQLITE_OK;\n    pIter++;\n    pIter += fts3GetVarint32(pIter, &iThis);\n  }\n  if( *pIter==0x00 ){\n    pIter = 0;\n  }\n\n  *ppOut = ((iCol==iThis)?pIter:0);\n  return SQLITE_OK;\n}\n\n/*\n** Free all components of the Fts3Phrase structure that were allocated by\n** the eval module. Specifically, this means to free:\n**\n**   * the contents of pPhrase->doclist, and\n**   * any Fts3MultiSegReader objects held by phrase tokens.\n*/\nSQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){\n  if( pPhrase ){\n    int i;\n    sqlite3_free(pPhrase->doclist.aAll);\n    fts3EvalInvalidatePoslist(pPhrase);\n    memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));\n    for(i=0; i<pPhrase->nToken; i++){\n      fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);\n      pPhrase->aToken[i].pSegcsr = 0;\n    }\n  }\n}\n\n\n/*\n** Return SQLITE_CORRUPT_VTAB.\n*/\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE int sqlite3Fts3Corrupt(){\n  return SQLITE_CORRUPT_VTAB;\n}\n#endif\n\n#if !SQLITE_CORE\n/*\n** Initialize API pointer table, if required.\n*/\n#ifdef _WIN32\n__declspec(dllexport)\n#endif\nSQLITE_API int sqlite3_fts3_init(\n  sqlite3 *db, \n  char **pzErrMsg,\n  const sqlite3_api_routines *pApi\n){\n  SQLITE_EXTENSION_INIT2(pApi)\n  return sqlite3Fts3Init(db);\n}\n#endif\n\n#endif\n\n/************** End of fts3.c ************************************************/\n/************** Begin file fts3_aux.c ****************************************/\n/*\n** 2011 Jan 27\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n*/\n/* #include \"fts3Int.h\" */\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <string.h> */\n/* #include <assert.h> */\n\ntypedef struct Fts3auxTable Fts3auxTable;\ntypedef struct Fts3auxCursor Fts3auxCursor;\n\nstruct Fts3auxTable {\n  sqlite3_vtab base;              /* Base class used by SQLite core */\n  Fts3Table *pFts3Tab;\n};\n\nstruct Fts3auxCursor {\n  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */\n  Fts3MultiSegReader csr;        /* Must be right after \"base\" */\n  Fts3SegFilter filter;\n  char *zStop;\n  int nStop;                      /* Byte-length of string zStop */\n  int iLangid;                    /* Language id to query */\n  int isEof;                      /* True if cursor is at EOF */\n  sqlite3_int64 iRowid;           /* Current rowid */\n\n  int iCol;                       /* Current value of 'col' column */\n  int nStat;                      /* Size of aStat[] array */\n  struct Fts3auxColstats {\n    sqlite3_int64 nDoc;           /* 'documents' values for current csr row */\n    sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */\n  } *aStat;\n};\n\n/*\n** Schema of the terms table.\n*/\n#define FTS3_AUX_SCHEMA \\\n  \"CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)\"\n\n/*\n** This function does all the work for both the xConnect and xCreate methods.\n** These tables have no persistent representation of their own, so xConnect\n** and xCreate are identical operations.\n*/\nstatic int fts3auxConnectMethod(\n  sqlite3 *db,                    /* Database connection */\n  void *pUnused,                  /* Unused */\n  int argc,                       /* Number of elements in argv array */\n  const char * const *argv,       /* xCreate/xConnect argument array */\n  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */\n  char **pzErr                    /* OUT: sqlite3_malloc'd error message */\n){\n  char const *zDb;                /* Name of database (e.g. \"main\") */\n  char const *zFts3;              /* Name of fts3 table */\n  int nDb;                        /* Result of strlen(zDb) */\n  int nFts3;                      /* Result of strlen(zFts3) */\n  sqlite3_int64 nByte;            /* Bytes of space to allocate here */\n  int rc;                         /* value returned by declare_vtab() */\n  Fts3auxTable *p;                /* Virtual table object to return */\n\n  UNUSED_PARAMETER(pUnused);\n\n  /* The user should invoke this in one of two forms:\n  **\n  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);\n  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);\n  */\n  if( argc!=4 && argc!=5 ) goto bad_args;\n\n  zDb = argv[1]; \n  nDb = (int)strlen(zDb);\n  if( argc==5 ){\n    if( nDb==4 && 0==sqlite3_strnicmp(\"temp\", zDb, 4) ){\n      zDb = argv[3]; \n      nDb = (int)strlen(zDb);\n      zFts3 = argv[4];\n    }else{\n      goto bad_args;\n    }\n  }else{\n    zFts3 = argv[3];\n  }\n  nFts3 = (int)strlen(zFts3);\n\n  rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);\n  if( rc!=SQLITE_OK ) return rc;\n\n  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;\n  p = (Fts3auxTable *)sqlite3_malloc64(nByte);\n  if( !p ) return SQLITE_NOMEM;\n  memset(p, 0, nByte);\n\n  p->pFts3Tab = (Fts3Table *)&p[1];\n  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];\n  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];\n  p->pFts3Tab->db = db;\n  p->pFts3Tab->nIndex = 1;\n\n  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);\n  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);\n  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);\n\n  *ppVtab = (sqlite3_vtab *)p;\n  return SQLITE_OK;\n\n bad_args:\n  sqlite3Fts3ErrMsg(pzErr, \"invalid arguments to fts4aux constructor\");\n  return SQLITE_ERROR;\n}\n\n/*\n** This function does the work for both the xDisconnect and xDestroy methods.\n** These tables have no persistent representation of their own, so xDisconnect\n** and xDestroy are identical operations.\n*/\nstatic int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){\n  Fts3auxTable *p = (Fts3auxTable *)pVtab;\n  Fts3Table *pFts3 = p->pFts3Tab;\n  int i;\n\n  /* Free any prepared statements held */\n  for(i=0; i<SizeofArray(pFts3->aStmt); i++){\n    sqlite3_finalize(pFts3->aStmt[i]);\n  }\n  sqlite3_free(pFts3->zSegmentsTbl);\n  sqlite3_free(p);\n  return SQLITE_OK;\n}\n\n#define FTS4AUX_EQ_CONSTRAINT 1\n#define FTS4AUX_GE_CONSTRAINT 2\n#define FTS4AUX_LE_CONSTRAINT 4\n\n/*\n** xBestIndex - Analyze a WHERE and ORDER BY clause.\n*/\nstatic int fts3auxBestIndexMethod(\n  sqlite3_vtab *pVTab, \n  sqlite3_index_info *pInfo\n){\n  int i;\n  int iEq = -1;\n  int iGe = -1;\n  int iLe = -1;\n  int iLangid = -1;\n  int iNext = 1;                  /* Next free argvIndex value */\n\n  UNUSED_PARAMETER(pVTab);\n\n  /* This vtab delivers always results in \"ORDER BY term ASC\" order. */\n  if( pInfo->nOrderBy==1 \n   && pInfo->aOrderBy[0].iColumn==0 \n   && pInfo->aOrderBy[0].desc==0\n  ){\n    pInfo->orderByConsumed = 1;\n  }\n\n  /* Search for equality and range constraints on the \"term\" column. \n  ** And equality constraints on the hidden \"languageid\" column. */\n  for(i=0; i<pInfo->nConstraint; i++){\n    if( pInfo->aConstraint[i].usable ){\n      int op = pInfo->aConstraint[i].op;\n      int iCol = pInfo->aConstraint[i].iColumn;\n\n      if( iCol==0 ){\n        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;\n        if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;\n        if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;\n        if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;\n        if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;\n      }\n      if( iCol==4 ){\n        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;\n      }\n    }\n  }\n\n  if( iEq>=0 ){\n    pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;\n    pInfo->aConstraintUsage[iEq].argvIndex = iNext++;\n    pInfo->estimatedCost = 5;\n  }else{\n    pInfo->idxNum = 0;\n    pInfo->estimatedCost = 20000;\n    if( iGe>=0 ){\n      pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;\n      pInfo->aConstraintUsage[iGe].argvIndex = iNext++;\n      pInfo->estimatedCost /= 2;\n    }\n    if( iLe>=0 ){\n      pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;\n      pInfo->aConstraintUsage[iLe].argvIndex = iNext++;\n      pInfo->estimatedCost /= 2;\n    }\n  }\n  if( iLangid>=0 ){\n    pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;\n    pInfo->estimatedCost--;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** xOpen - Open a cursor.\n*/\nstatic int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){\n  Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */\n\n  UNUSED_PARAMETER(pVTab);\n\n  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));\n  if( !pCsr ) return SQLITE_NOMEM;\n  memset(pCsr, 0, sizeof(Fts3auxCursor));\n\n  *ppCsr = (sqlite3_vtab_cursor *)pCsr;\n  return SQLITE_OK;\n}\n\n/*\n** xClose - Close a cursor.\n*/\nstatic int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){\n  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;\n  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;\n\n  sqlite3Fts3SegmentsClose(pFts3);\n  sqlite3Fts3SegReaderFinish(&pCsr->csr);\n  sqlite3_free((void *)pCsr->filter.zTerm);\n  sqlite3_free(pCsr->zStop);\n  sqlite3_free(pCsr->aStat);\n  sqlite3_free(pCsr);\n  return SQLITE_OK;\n}\n\nstatic int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){\n  if( nSize>pCsr->nStat ){\n    struct Fts3auxColstats *aNew;\n    aNew = (struct Fts3auxColstats *)sqlite3_realloc64(pCsr->aStat, \n        sizeof(struct Fts3auxColstats) * nSize\n    );\n    if( aNew==0 ) return SQLITE_NOMEM;\n    memset(&aNew[pCsr->nStat], 0, \n        sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)\n    );\n    pCsr->aStat = aNew;\n    pCsr->nStat = nSize;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** xNext - Advance the cursor to the next row, if any.\n*/\nstatic int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){\n  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;\n  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;\n  int rc;\n\n  /* Increment our pretend rowid value. */\n  pCsr->iRowid++;\n\n  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){\n    if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;\n  }\n\n  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);\n  if( rc==SQLITE_ROW ){\n    int i = 0;\n    int nDoclist = pCsr->csr.nDoclist;\n    char *aDoclist = pCsr->csr.aDoclist;\n    int iCol;\n\n    int eState = 0;\n\n    if( pCsr->zStop ){\n      int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;\n      int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);\n      if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){\n        pCsr->isEof = 1;\n        return SQLITE_OK;\n      }\n    }\n\n    if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;\n    memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);\n    iCol = 0;\n\n    while( i<nDoclist ){\n      sqlite3_int64 v = 0;\n\n      i += sqlite3Fts3GetVarint(&aDoclist[i], &v);\n      switch( eState ){\n        /* State 0. In this state the integer just read was a docid. */\n        case 0:\n          pCsr->aStat[0].nDoc++;\n          eState = 1;\n          iCol = 0;\n          break;\n\n        /* State 1. In this state we are expecting either a 1, indicating\n        ** that the following integer will be a column number, or the\n        ** start of a position list for column 0.  \n        ** \n        ** The only difference between state 1 and state 2 is that if the\n        ** integer encountered in state 1 is not 0 or 1, then we need to\n        ** increment the column 0 \"nDoc\" count for this term.\n        */\n        case 1:\n          assert( iCol==0 );\n          if( v>1 ){\n            pCsr->aStat[1].nDoc++;\n          }\n          eState = 2;\n          /* fall through */\n\n        case 2:\n          if( v==0 ){       /* 0x00. Next integer will be a docid. */\n            eState = 0;\n          }else if( v==1 ){ /* 0x01. Next integer will be a column number. */\n            eState = 3;\n          }else{            /* 2 or greater. A position. */\n            pCsr->aStat[iCol+1].nOcc++;\n            pCsr->aStat[0].nOcc++;\n          }\n          break;\n\n        /* State 3. The integer just read is a column number. */\n        default: assert( eState==3 );\n          iCol = (int)v;\n          if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;\n          pCsr->aStat[iCol+1].nDoc++;\n          eState = 2;\n          break;\n      }\n    }\n\n    pCsr->iCol = 0;\n    rc = SQLITE_OK;\n  }else{\n    pCsr->isEof = 1;\n  }\n  return rc;\n}\n\n/*\n** xFilter - Initialize a cursor to point at the start of its data.\n*/\nstatic int fts3auxFilterMethod(\n  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */\n  int idxNum,                     /* Strategy index */\n  const char *idxStr,             /* Unused */\n  int nVal,                       /* Number of elements in apVal */\n  sqlite3_value **apVal           /* Arguments for the indexing scheme */\n){\n  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;\n  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;\n  int rc;\n  int isScan = 0;\n  int iLangVal = 0;               /* Language id to query */\n\n  int iEq = -1;                   /* Index of term=? value in apVal */\n  int iGe = -1;                   /* Index of term>=? value in apVal */\n  int iLe = -1;                   /* Index of term<=? value in apVal */\n  int iLangid = -1;               /* Index of languageid=? value in apVal */\n  int iNext = 0;\n\n  UNUSED_PARAMETER(nVal);\n  UNUSED_PARAMETER(idxStr);\n\n  assert( idxStr==0 );\n  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0\n       || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT\n       || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)\n  );\n\n  if( idxNum==FTS4AUX_EQ_CONSTRAINT ){\n    iEq = iNext++;\n  }else{\n    isScan = 1;\n    if( idxNum & FTS4AUX_GE_CONSTRAINT ){\n      iGe = iNext++;\n    }\n    if( idxNum & FTS4AUX_LE_CONSTRAINT ){\n      iLe = iNext++;\n    }\n  }\n  if( iNext<nVal ){\n    iLangid = iNext++;\n  }\n\n  /* In case this cursor is being reused, close and zero it. */\n  testcase(pCsr->filter.zTerm);\n  sqlite3Fts3SegReaderFinish(&pCsr->csr);\n  sqlite3_free((void *)pCsr->filter.zTerm);\n  sqlite3_free(pCsr->aStat);\n  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);\n\n  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;\n  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;\n\n  if( iEq>=0 || iGe>=0 ){\n    const unsigned char *zStr = sqlite3_value_text(apVal[0]);\n    assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );\n    if( zStr ){\n      pCsr->filter.zTerm = sqlite3_mprintf(\"%s\", zStr);\n      if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;\n      pCsr->filter.nTerm = (int)strlen(pCsr->filter.zTerm);\n    }\n  }\n\n  if( iLe>=0 ){\n    pCsr->zStop = sqlite3_mprintf(\"%s\", sqlite3_value_text(apVal[iLe]));\n    if( pCsr->zStop==0 ) return SQLITE_NOMEM;\n    pCsr->nStop = (int)strlen(pCsr->zStop);\n  }\n  \n  if( iLangid>=0 ){\n    iLangVal = sqlite3_value_int(apVal[iLangid]);\n\n    /* If the user specified a negative value for the languageid, use zero\n    ** instead. This works, as the \"languageid=?\" constraint will also\n    ** be tested by the VDBE layer. The test will always be false (since\n    ** this module will not return a row with a negative languageid), and\n    ** so the overall query will return zero rows.  */\n    if( iLangVal<0 ) iLangVal = 0;\n  }\n  pCsr->iLangid = iLangVal;\n\n  rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,\n      pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr\n  );\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);\n  }\n\n  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);\n  return rc;\n}\n\n/*\n** xEof - Return true if the cursor is at EOF, or false otherwise.\n*/\nstatic int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){\n  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;\n  return pCsr->isEof;\n}\n\n/*\n** xColumn - Return a column value.\n*/\nstatic int fts3auxColumnMethod(\n  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */\n  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */\n  int iCol                        /* Index of column to read value from */\n){\n  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;\n\n  assert( p->isEof==0 );\n  switch( iCol ){\n    case 0: /* term */\n      sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);\n      break;\n\n    case 1: /* col */\n      if( p->iCol ){\n        sqlite3_result_int(pCtx, p->iCol-1);\n      }else{\n        sqlite3_result_text(pCtx, \"*\", -1, SQLITE_STATIC);\n      }\n      break;\n\n    case 2: /* documents */\n      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);\n      break;\n\n    case 3: /* occurrences */\n      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);\n      break;\n\n    default: /* languageid */\n      assert( iCol==4 );\n      sqlite3_result_int(pCtx, p->iLangid);\n      break;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** xRowid - Return the current rowid for the cursor.\n*/\nstatic int fts3auxRowidMethod(\n  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */\n  sqlite_int64 *pRowid            /* OUT: Rowid value */\n){\n  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;\n  *pRowid = pCsr->iRowid;\n  return SQLITE_OK;\n}\n\n/*\n** Register the fts3aux module with database connection db. Return SQLITE_OK\n** if successful or an error code if sqlite3_create_module() fails.\n*/\nSQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){\n  static const sqlite3_module fts3aux_module = {\n     0,                           /* iVersion      */\n     fts3auxConnectMethod,        /* xCreate       */\n     fts3auxConnectMethod,        /* xConnect      */\n     fts3auxBestIndexMethod,      /* xBestIndex    */\n     fts3auxDisconnectMethod,     /* xDisconnect   */\n     fts3auxDisconnectMethod,     /* xDestroy      */\n     fts3auxOpenMethod,           /* xOpen         */\n     fts3auxCloseMethod,          /* xClose        */\n     fts3auxFilterMethod,         /* xFilter       */\n     fts3auxNextMethod,           /* xNext         */\n     fts3auxEofMethod,            /* xEof          */\n     fts3auxColumnMethod,         /* xColumn       */\n     fts3auxRowidMethod,          /* xRowid        */\n     0,                           /* xUpdate       */\n     0,                           /* xBegin        */\n     0,                           /* xSync         */\n     0,                           /* xCommit       */\n     0,                           /* xRollback     */\n     0,                           /* xFindFunction */\n     0,                           /* xRename       */\n     0,                           /* xSavepoint    */\n     0,                           /* xRelease      */\n     0,                           /* xRollbackTo   */\n     0                            /* xShadowName   */\n  };\n  int rc;                         /* Return code */\n\n  rc = sqlite3_create_module(db, \"fts4aux\", &fts3aux_module, 0);\n  return rc;\n}\n\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n\n/************** End of fts3_aux.c ********************************************/\n/************** Begin file fts3_expr.c ***************************************/\n/*\n** 2008 Nov 28\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This module contains code that implements a parser for fts3 query strings\n** (the right-hand argument to the MATCH operator). Because the supported \n** syntax is relatively simple, the whole tokenizer/parser system is\n** hand-coded. \n*/\n/* #include \"fts3Int.h\" */\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/*\n** By default, this module parses the legacy syntax that has been \n** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS\n** is defined, then it uses the new syntax. The differences between\n** the new and the old syntaxes are:\n**\n**  a) The new syntax supports parenthesis. The old does not.\n**\n**  b) The new syntax supports the AND and NOT operators. The old does not.\n**\n**  c) The old syntax supports the \"-\" token qualifier. This is not \n**     supported by the new syntax (it is replaced by the NOT operator).\n**\n**  d) When using the old syntax, the OR operator has a greater precedence\n**     than an implicit AND. When using the new, both implicity and explicit\n**     AND operators have a higher precedence than OR.\n**\n** If compiled with SQLITE_TEST defined, then this module exports the\n** symbol \"int sqlite3_fts3_enable_parentheses\". Setting this variable\n** to zero causes the module to use the old syntax. If it is set to \n** non-zero the new syntax is activated. This is so both syntaxes can\n** be tested using a single build of testfixture.\n**\n** The following describes the syntax supported by the fts3 MATCH\n** operator in a similar format to that used by the lemon parser\n** generator. This module does not use actually lemon, it uses a\n** custom parser.\n**\n**   query ::= andexpr (OR andexpr)*.\n**\n**   andexpr ::= notexpr (AND? notexpr)*.\n**\n**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.\n**   notexpr ::= LP query RP.\n**\n**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.\n**\n**   distance_opt ::= .\n**   distance_opt ::= / INTEGER.\n**\n**   phrase ::= TOKEN.\n**   phrase ::= COLUMN:TOKEN.\n**   phrase ::= \"TOKEN TOKEN TOKEN...\".\n*/\n\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_fts3_enable_parentheses = 0;\n#else\n# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS \n#  define sqlite3_fts3_enable_parentheses 1\n# else\n#  define sqlite3_fts3_enable_parentheses 0\n# endif\n#endif\n\n/*\n** Default span for NEAR operators.\n*/\n#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10\n\n/* #include <string.h> */\n/* #include <assert.h> */\n\n/*\n** isNot:\n**   This variable is used by function getNextNode(). When getNextNode() is\n**   called, it sets ParseContext.isNot to true if the 'next node' is a \n**   FTSQUERY_PHRASE with a unary \"-\" attached to it. i.e. \"mysql\" in the\n**   FTS3 query \"sqlite -mysql\". Otherwise, ParseContext.isNot is set to\n**   zero.\n*/\ntypedef struct ParseContext ParseContext;\nstruct ParseContext {\n  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */\n  int iLangid;                        /* Language id used with tokenizer */\n  const char **azCol;                 /* Array of column names for fts3 table */\n  int bFts4;                          /* True to allow FTS4-only syntax */\n  int nCol;                           /* Number of entries in azCol[] */\n  int iDefaultCol;                    /* Default column to query */\n  int isNot;                          /* True if getNextNode() sees a unary - */\n  sqlite3_context *pCtx;              /* Write error message here */\n  int nNest;                          /* Number of nested brackets */\n};\n\n/*\n** This function is equivalent to the standard isspace() function. \n**\n** The standard isspace() can be awkward to use safely, because although it\n** is defined to accept an argument of type int, its behavior when passed\n** an integer that falls outside of the range of the unsigned char type\n** is undefined (and sometimes, \"undefined\" means segfault). This wrapper\n** is defined to accept an argument of type char, and always returns 0 for\n** any values that fall outside of the range of the unsigned char type (i.e.\n** negative values).\n*/\nstatic int fts3isspace(char c){\n  return c==' ' || c=='\\t' || c=='\\n' || c=='\\r' || c=='\\v' || c=='\\f';\n}\n\n/*\n** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,\n** zero the memory before returning a pointer to it. If unsuccessful, \n** return NULL.\n*/\nstatic void *fts3MallocZero(sqlite3_int64 nByte){\n  void *pRet = sqlite3_malloc64(nByte);\n  if( pRet ) memset(pRet, 0, nByte);\n  return pRet;\n}\n\nSQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(\n  sqlite3_tokenizer *pTokenizer,\n  int iLangid,\n  const char *z,\n  int n,\n  sqlite3_tokenizer_cursor **ppCsr\n){\n  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;\n  sqlite3_tokenizer_cursor *pCsr = 0;\n  int rc;\n\n  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);\n  assert( rc==SQLITE_OK || pCsr==0 );\n  if( rc==SQLITE_OK ){\n    pCsr->pTokenizer = pTokenizer;\n    if( pModule->iVersion>=1 ){\n      rc = pModule->xLanguageid(pCsr, iLangid);\n      if( rc!=SQLITE_OK ){\n        pModule->xClose(pCsr);\n        pCsr = 0;\n      }\n    }\n  }\n  *ppCsr = pCsr;\n  return rc;\n}\n\n/*\n** Function getNextNode(), which is called by fts3ExprParse(), may itself\n** call fts3ExprParse(). So this forward declaration is required.\n*/\nstatic int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);\n\n/*\n** Extract the next token from buffer z (length n) using the tokenizer\n** and other information (column names etc.) in pParse. Create an Fts3Expr\n** structure of type FTSQUERY_PHRASE containing a phrase consisting of this\n** single token and set *ppExpr to point to it. If the end of the buffer is\n** reached before a token is found, set *ppExpr to zero. It is the\n** responsibility of the caller to eventually deallocate the allocated \n** Fts3Expr structure (if any) by passing it to sqlite3_free().\n**\n** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation\n** fails.\n*/\nstatic int getNextToken(\n  ParseContext *pParse,                   /* fts3 query parse context */\n  int iCol,                               /* Value for Fts3Phrase.iColumn */\n  const char *z, int n,                   /* Input string */\n  Fts3Expr **ppExpr,                      /* OUT: expression */\n  int *pnConsumed                         /* OUT: Number of bytes consumed */\n){\n  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;\n  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;\n  int rc;\n  sqlite3_tokenizer_cursor *pCursor;\n  Fts3Expr *pRet = 0;\n  int i = 0;\n\n  /* Set variable i to the maximum number of bytes of input to tokenize. */\n  for(i=0; i<n; i++){\n    if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;\n    if( z[i]=='\"' ) break;\n  }\n\n  *pnConsumed = i;\n  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);\n  if( rc==SQLITE_OK ){\n    const char *zToken;\n    int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;\n    sqlite3_int64 nByte;                    /* total space to allocate */\n\n    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);\n    if( rc==SQLITE_OK ){\n      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;\n      pRet = (Fts3Expr *)fts3MallocZero(nByte);\n      if( !pRet ){\n        rc = SQLITE_NOMEM;\n      }else{\n        pRet->eType = FTSQUERY_PHRASE;\n        pRet->pPhrase = (Fts3Phrase *)&pRet[1];\n        pRet->pPhrase->nToken = 1;\n        pRet->pPhrase->iColumn = iCol;\n        pRet->pPhrase->aToken[0].n = nToken;\n        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];\n        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);\n\n        if( iEnd<n && z[iEnd]=='*' ){\n          pRet->pPhrase->aToken[0].isPrefix = 1;\n          iEnd++;\n        }\n\n        while( 1 ){\n          if( !sqlite3_fts3_enable_parentheses \n           && iStart>0 && z[iStart-1]=='-' \n          ){\n            pParse->isNot = 1;\n            iStart--;\n          }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){\n            pRet->pPhrase->aToken[0].bFirst = 1;\n            iStart--;\n          }else{\n            break;\n          }\n        }\n\n      }\n      *pnConsumed = iEnd;\n    }else if( i && rc==SQLITE_DONE ){\n      rc = SQLITE_OK;\n    }\n\n    pModule->xClose(pCursor);\n  }\n  \n  *ppExpr = pRet;\n  return rc;\n}\n\n\n/*\n** Enlarge a memory allocation.  If an out-of-memory allocation occurs,\n** then free the old allocation.\n*/\nstatic void *fts3ReallocOrFree(void *pOrig, sqlite3_int64 nNew){\n  void *pRet = sqlite3_realloc64(pOrig, nNew);\n  if( !pRet ){\n    sqlite3_free(pOrig);\n  }\n  return pRet;\n}\n\n/*\n** Buffer zInput, length nInput, contains the contents of a quoted string\n** that appeared as part of an fts3 query expression. Neither quote character\n** is included in the buffer. This function attempts to tokenize the entire\n** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE \n** containing the results.\n**\n** If successful, SQLITE_OK is returned and *ppExpr set to point at the\n** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory\n** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set\n** to 0.\n*/\nstatic int getNextString(\n  ParseContext *pParse,                   /* fts3 query parse context */\n  const char *zInput, int nInput,         /* Input string */\n  Fts3Expr **ppExpr                       /* OUT: expression */\n){\n  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;\n  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;\n  int rc;\n  Fts3Expr *p = 0;\n  sqlite3_tokenizer_cursor *pCursor = 0;\n  char *zTemp = 0;\n  int nTemp = 0;\n\n  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);\n  int nToken = 0;\n\n  /* The final Fts3Expr data structure, including the Fts3Phrase,\n  ** Fts3PhraseToken structures token buffers are all stored as a single \n  ** allocation so that the expression can be freed with a single call to\n  ** sqlite3_free(). Setting this up requires a two pass approach.\n  **\n  ** The first pass, in the block below, uses a tokenizer cursor to iterate\n  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()\n  ** to assemble data in two dynamic buffers:\n  **\n  **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase\n  **             structure, followed by the array of Fts3PhraseToken \n  **             structures. This pass only populates the Fts3PhraseToken array.\n  **\n  **   Buffer zTemp: Contains copies of all tokens.\n  **\n  ** The second pass, in the block that begins \"if( rc==SQLITE_DONE )\" below,\n  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase\n  ** structures.\n  */\n  rc = sqlite3Fts3OpenTokenizer(\n      pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);\n  if( rc==SQLITE_OK ){\n    int ii;\n    for(ii=0; rc==SQLITE_OK; ii++){\n      const char *zByte;\n      int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;\n      rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);\n      if( rc==SQLITE_OK ){\n        Fts3PhraseToken *pToken;\n\n        p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));\n        if( !p ) goto no_mem;\n\n        zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);\n        if( !zTemp ) goto no_mem;\n\n        assert( nToken==ii );\n        pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];\n        memset(pToken, 0, sizeof(Fts3PhraseToken));\n\n        memcpy(&zTemp[nTemp], zByte, nByte);\n        nTemp += nByte;\n\n        pToken->n = nByte;\n        pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');\n        pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');\n        nToken = ii+1;\n      }\n    }\n\n    pModule->xClose(pCursor);\n    pCursor = 0;\n  }\n\n  if( rc==SQLITE_DONE ){\n    int jj;\n    char *zBuf = 0;\n\n    p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);\n    if( !p ) goto no_mem;\n    memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);\n    p->eType = FTSQUERY_PHRASE;\n    p->pPhrase = (Fts3Phrase *)&p[1];\n    p->pPhrase->iColumn = pParse->iDefaultCol;\n    p->pPhrase->nToken = nToken;\n\n    zBuf = (char *)&p->pPhrase->aToken[nToken];\n    if( zTemp ){\n      memcpy(zBuf, zTemp, nTemp);\n      sqlite3_free(zTemp);\n    }else{\n      assert( nTemp==0 );\n    }\n\n    for(jj=0; jj<p->pPhrase->nToken; jj++){\n      p->pPhrase->aToken[jj].z = zBuf;\n      zBuf += p->pPhrase->aToken[jj].n;\n    }\n    rc = SQLITE_OK;\n  }\n\n  *ppExpr = p;\n  return rc;\nno_mem:\n\n  if( pCursor ){\n    pModule->xClose(pCursor);\n  }\n  sqlite3_free(zTemp);\n  sqlite3_free(p);\n  *ppExpr = 0;\n  return SQLITE_NOMEM;\n}\n\n/*\n** The output variable *ppExpr is populated with an allocated Fts3Expr \n** structure, or set to 0 if the end of the input buffer is reached.\n**\n** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM\n** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.\n** If SQLITE_ERROR is returned, pContext is populated with an error message.\n*/\nstatic int getNextNode(\n  ParseContext *pParse,                   /* fts3 query parse context */\n  const char *z, int n,                   /* Input string */\n  Fts3Expr **ppExpr,                      /* OUT: expression */\n  int *pnConsumed                         /* OUT: Number of bytes consumed */\n){\n  static const struct Fts3Keyword {\n    char *z;                              /* Keyword text */\n    unsigned char n;                      /* Length of the keyword */\n    unsigned char parenOnly;              /* Only valid in paren mode */\n    unsigned char eType;                  /* Keyword code */\n  } aKeyword[] = {\n    { \"OR\" ,  2, 0, FTSQUERY_OR   },\n    { \"AND\",  3, 1, FTSQUERY_AND  },\n    { \"NOT\",  3, 1, FTSQUERY_NOT  },\n    { \"NEAR\", 4, 0, FTSQUERY_NEAR }\n  };\n  int ii;\n  int iCol;\n  int iColLen;\n  int rc;\n  Fts3Expr *pRet = 0;\n\n  const char *zInput = z;\n  int nInput = n;\n\n  pParse->isNot = 0;\n\n  /* Skip over any whitespace before checking for a keyword, an open or\n  ** close bracket, or a quoted string. \n  */\n  while( nInput>0 && fts3isspace(*zInput) ){\n    nInput--;\n    zInput++;\n  }\n  if( nInput==0 ){\n    return SQLITE_DONE;\n  }\n\n  /* See if we are dealing with a keyword. */\n  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){\n    const struct Fts3Keyword *pKey = &aKeyword[ii];\n\n    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){\n      continue;\n    }\n\n    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){\n      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;\n      int nKey = pKey->n;\n      char cNext;\n\n      /* If this is a \"NEAR\" keyword, check for an explicit nearness. */\n      if( pKey->eType==FTSQUERY_NEAR ){\n        assert( nKey==4 );\n        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){\n          nKey += 1+sqlite3Fts3ReadInt(&zInput[nKey+1], &nNear);\n        }\n      }\n\n      /* At this point this is probably a keyword. But for that to be true,\n      ** the next byte must contain either whitespace, an open or close\n      ** parenthesis, a quote character, or EOF. \n      */\n      cNext = zInput[nKey];\n      if( fts3isspace(cNext) \n       || cNext=='\"' || cNext=='(' || cNext==')' || cNext==0\n      ){\n        pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));\n        if( !pRet ){\n          return SQLITE_NOMEM;\n        }\n        pRet->eType = pKey->eType;\n        pRet->nNear = nNear;\n        *ppExpr = pRet;\n        *pnConsumed = (int)((zInput - z) + nKey);\n        return SQLITE_OK;\n      }\n\n      /* Turns out that wasn't a keyword after all. This happens if the\n      ** user has supplied a token such as \"ORacle\". Continue.\n      */\n    }\n  }\n\n  /* See if we are dealing with a quoted phrase. If this is the case, then\n  ** search for the closing quote and pass the whole string to getNextString()\n  ** for processing. This is easy to do, as fts3 has no syntax for escaping\n  ** a quote character embedded in a string.\n  */\n  if( *zInput=='\"' ){\n    for(ii=1; ii<nInput && zInput[ii]!='\"'; ii++);\n    *pnConsumed = (int)((zInput - z) + ii + 1);\n    if( ii==nInput ){\n      return SQLITE_ERROR;\n    }\n    return getNextString(pParse, &zInput[1], ii-1, ppExpr);\n  }\n\n  if( sqlite3_fts3_enable_parentheses ){\n    if( *zInput=='(' ){\n      int nConsumed = 0;\n      pParse->nNest++;\n      rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);\n      *pnConsumed = (int)(zInput - z) + 1 + nConsumed;\n      return rc;\n    }else if( *zInput==')' ){\n      pParse->nNest--;\n      *pnConsumed = (int)((zInput - z) + 1);\n      *ppExpr = 0;\n      return SQLITE_DONE;\n    }\n  }\n\n  /* If control flows to this point, this must be a regular token, or \n  ** the end of the input. Read a regular token using the sqlite3_tokenizer\n  ** interface. Before doing so, figure out if there is an explicit\n  ** column specifier for the token. \n  **\n  ** TODO: Strangely, it is not possible to associate a column specifier\n  ** with a quoted phrase, only with a single token. Not sure if this was\n  ** an implementation artifact or an intentional decision when fts3 was\n  ** first implemented. Whichever it was, this module duplicates the \n  ** limitation.\n  */\n  iCol = pParse->iDefaultCol;\n  iColLen = 0;\n  for(ii=0; ii<pParse->nCol; ii++){\n    const char *zStr = pParse->azCol[ii];\n    int nStr = (int)strlen(zStr);\n    if( nInput>nStr && zInput[nStr]==':' \n     && sqlite3_strnicmp(zStr, zInput, nStr)==0 \n    ){\n      iCol = ii;\n      iColLen = (int)((zInput - z) + nStr + 1);\n      break;\n    }\n  }\n  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);\n  *pnConsumed += iColLen;\n  return rc;\n}\n\n/*\n** The argument is an Fts3Expr structure for a binary operator (any type\n** except an FTSQUERY_PHRASE). Return an integer value representing the\n** precedence of the operator. Lower values have a higher precedence (i.e.\n** group more tightly). For example, in the C language, the == operator\n** groups more tightly than ||, and would therefore have a higher precedence.\n**\n** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS\n** is defined), the order of the operators in precedence from highest to\n** lowest is:\n**\n**   NEAR\n**   NOT\n**   AND (including implicit ANDs)\n**   OR\n**\n** Note that when using the old query syntax, the OR operator has a higher\n** precedence than the AND operator.\n*/\nstatic int opPrecedence(Fts3Expr *p){\n  assert( p->eType!=FTSQUERY_PHRASE );\n  if( sqlite3_fts3_enable_parentheses ){\n    return p->eType;\n  }else if( p->eType==FTSQUERY_NEAR ){\n    return 1;\n  }else if( p->eType==FTSQUERY_OR ){\n    return 2;\n  }\n  assert( p->eType==FTSQUERY_AND );\n  return 3;\n}\n\n/*\n** Argument ppHead contains a pointer to the current head of a query \n** expression tree being parsed. pPrev is the expression node most recently\n** inserted into the tree. This function adds pNew, which is always a binary\n** operator node, into the expression tree based on the relative precedence\n** of pNew and the existing nodes of the tree. This may result in the head\n** of the tree changing, in which case *ppHead is set to the new root node.\n*/\nstatic void insertBinaryOperator(\n  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */\n  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */\n  Fts3Expr *pNew           /* New binary node to insert into expression tree */\n){\n  Fts3Expr *pSplit = pPrev;\n  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){\n    pSplit = pSplit->pParent;\n  }\n\n  if( pSplit->pParent ){\n    assert( pSplit->pParent->pRight==pSplit );\n    pSplit->pParent->pRight = pNew;\n    pNew->pParent = pSplit->pParent;\n  }else{\n    *ppHead = pNew;\n  }\n  pNew->pLeft = pSplit;\n  pSplit->pParent = pNew;\n}\n\n/*\n** Parse the fts3 query expression found in buffer z, length n. This function\n** returns either when the end of the buffer is reached or an unmatched \n** closing bracket - ')' - is encountered.\n**\n** If successful, SQLITE_OK is returned, *ppExpr is set to point to the\n** parsed form of the expression and *pnConsumed is set to the number of\n** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM\n** (out of memory error) or SQLITE_ERROR (parse error) is returned.\n*/\nstatic int fts3ExprParse(\n  ParseContext *pParse,                   /* fts3 query parse context */\n  const char *z, int n,                   /* Text of MATCH query */\n  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */\n  int *pnConsumed                         /* OUT: Number of bytes consumed */\n){\n  Fts3Expr *pRet = 0;\n  Fts3Expr *pPrev = 0;\n  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */\n  int nIn = n;\n  const char *zIn = z;\n  int rc = SQLITE_OK;\n  int isRequirePhrase = 1;\n\n  while( rc==SQLITE_OK ){\n    Fts3Expr *p = 0;\n    int nByte = 0;\n\n    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);\n    assert( nByte>0 || (rc!=SQLITE_OK && p==0) );\n    if( rc==SQLITE_OK ){\n      if( p ){\n        int isPhrase;\n\n        if( !sqlite3_fts3_enable_parentheses \n            && p->eType==FTSQUERY_PHRASE && pParse->isNot \n        ){\n          /* Create an implicit NOT operator. */\n          Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));\n          if( !pNot ){\n            sqlite3Fts3ExprFree(p);\n            rc = SQLITE_NOMEM;\n            goto exprparse_out;\n          }\n          pNot->eType = FTSQUERY_NOT;\n          pNot->pRight = p;\n          p->pParent = pNot;\n          if( pNotBranch ){\n            pNot->pLeft = pNotBranch;\n            pNotBranch->pParent = pNot;\n          }\n          pNotBranch = pNot;\n          p = pPrev;\n        }else{\n          int eType = p->eType;\n          isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);\n\n          /* The isRequirePhrase variable is set to true if a phrase or\n          ** an expression contained in parenthesis is required. If a\n          ** binary operator (AND, OR, NOT or NEAR) is encounted when\n          ** isRequirePhrase is set, this is a syntax error.\n          */\n          if( !isPhrase && isRequirePhrase ){\n            sqlite3Fts3ExprFree(p);\n            rc = SQLITE_ERROR;\n            goto exprparse_out;\n          }\n\n          if( isPhrase && !isRequirePhrase ){\n            /* Insert an implicit AND operator. */\n            Fts3Expr *pAnd;\n            assert( pRet && pPrev );\n            pAnd = fts3MallocZero(sizeof(Fts3Expr));\n            if( !pAnd ){\n              sqlite3Fts3ExprFree(p);\n              rc = SQLITE_NOMEM;\n              goto exprparse_out;\n            }\n            pAnd->eType = FTSQUERY_AND;\n            insertBinaryOperator(&pRet, pPrev, pAnd);\n            pPrev = pAnd;\n          }\n\n          /* This test catches attempts to make either operand of a NEAR\n           ** operator something other than a phrase. For example, either of\n           ** the following:\n           **\n           **    (bracketed expression) NEAR phrase\n           **    phrase NEAR (bracketed expression)\n           **\n           ** Return an error in either case.\n           */\n          if( pPrev && (\n            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)\n         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)\n          )){\n            sqlite3Fts3ExprFree(p);\n            rc = SQLITE_ERROR;\n            goto exprparse_out;\n          }\n\n          if( isPhrase ){\n            if( pRet ){\n              assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );\n              pPrev->pRight = p;\n              p->pParent = pPrev;\n            }else{\n              pRet = p;\n            }\n          }else{\n            insertBinaryOperator(&pRet, pPrev, p);\n          }\n          isRequirePhrase = !isPhrase;\n        }\n        pPrev = p;\n      }\n      assert( nByte>0 );\n    }\n    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );\n    nIn -= nByte;\n    zIn += nByte;\n  }\n\n  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){\n    rc = SQLITE_ERROR;\n  }\n\n  if( rc==SQLITE_DONE ){\n    rc = SQLITE_OK;\n    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){\n      if( !pRet ){\n        rc = SQLITE_ERROR;\n      }else{\n        Fts3Expr *pIter = pNotBranch;\n        while( pIter->pLeft ){\n          pIter = pIter->pLeft;\n        }\n        pIter->pLeft = pRet;\n        pRet->pParent = pIter;\n        pRet = pNotBranch;\n      }\n    }\n  }\n  *pnConsumed = n - nIn;\n\nexprparse_out:\n  if( rc!=SQLITE_OK ){\n    sqlite3Fts3ExprFree(pRet);\n    sqlite3Fts3ExprFree(pNotBranch);\n    pRet = 0;\n  }\n  *ppExpr = pRet;\n  return rc;\n}\n\n/*\n** Return SQLITE_ERROR if the maximum depth of the expression tree passed \n** as the only argument is more than nMaxDepth.\n*/\nstatic int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){\n  int rc = SQLITE_OK;\n  if( p ){\n    if( nMaxDepth<0 ){ \n      rc = SQLITE_TOOBIG;\n    }else{\n      rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);\n      if( rc==SQLITE_OK ){\n        rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** This function attempts to transform the expression tree at (*pp) to\n** an equivalent but more balanced form. The tree is modified in place.\n** If successful, SQLITE_OK is returned and (*pp) set to point to the \n** new root expression node. \n**\n** nMaxDepth is the maximum allowable depth of the balanced sub-tree.\n**\n** Otherwise, if an error occurs, an SQLite error code is returned and \n** expression (*pp) freed.\n*/\nstatic int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){\n  int rc = SQLITE_OK;             /* Return code */\n  Fts3Expr *pRoot = *pp;          /* Initial root node */\n  Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */\n  int eType = pRoot->eType;       /* Type of node in this tree */\n\n  if( nMaxDepth==0 ){\n    rc = SQLITE_ERROR;\n  }\n\n  if( rc==SQLITE_OK ){\n    if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){\n      Fts3Expr **apLeaf;\n      apLeaf = (Fts3Expr **)sqlite3_malloc64(sizeof(Fts3Expr *) * nMaxDepth);\n      if( 0==apLeaf ){\n        rc = SQLITE_NOMEM;\n      }else{\n        memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);\n      }\n\n      if( rc==SQLITE_OK ){\n        int i;\n        Fts3Expr *p;\n\n        /* Set $p to point to the left-most leaf in the tree of eType nodes. */\n        for(p=pRoot; p->eType==eType; p=p->pLeft){\n          assert( p->pParent==0 || p->pParent->pLeft==p );\n          assert( p->pLeft && p->pRight );\n        }\n\n        /* This loop runs once for each leaf in the tree of eType nodes. */\n        while( 1 ){\n          int iLvl;\n          Fts3Expr *pParent = p->pParent;     /* Current parent of p */\n\n          assert( pParent==0 || pParent->pLeft==p );\n          p->pParent = 0;\n          if( pParent ){\n            pParent->pLeft = 0;\n          }else{\n            pRoot = 0;\n          }\n          rc = fts3ExprBalance(&p, nMaxDepth-1);\n          if( rc!=SQLITE_OK ) break;\n\n          for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){\n            if( apLeaf[iLvl]==0 ){\n              apLeaf[iLvl] = p;\n              p = 0;\n            }else{\n              assert( pFree );\n              pFree->pLeft = apLeaf[iLvl];\n              pFree->pRight = p;\n              pFree->pLeft->pParent = pFree;\n              pFree->pRight->pParent = pFree;\n\n              p = pFree;\n              pFree = pFree->pParent;\n              p->pParent = 0;\n              apLeaf[iLvl] = 0;\n            }\n          }\n          if( p ){\n            sqlite3Fts3ExprFree(p);\n            rc = SQLITE_TOOBIG;\n            break;\n          }\n\n          /* If that was the last leaf node, break out of the loop */\n          if( pParent==0 ) break;\n\n          /* Set $p to point to the next leaf in the tree of eType nodes */\n          for(p=pParent->pRight; p->eType==eType; p=p->pLeft);\n\n          /* Remove pParent from the original tree. */\n          assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );\n          pParent->pRight->pParent = pParent->pParent;\n          if( pParent->pParent ){\n            pParent->pParent->pLeft = pParent->pRight;\n          }else{\n            assert( pParent==pRoot );\n            pRoot = pParent->pRight;\n          }\n\n          /* Link pParent into the free node list. It will be used as an\n          ** internal node of the new tree.  */\n          pParent->pParent = pFree;\n          pFree = pParent;\n        }\n\n        if( rc==SQLITE_OK ){\n          p = 0;\n          for(i=0; i<nMaxDepth; i++){\n            if( apLeaf[i] ){\n              if( p==0 ){\n                p = apLeaf[i];\n                p->pParent = 0;\n              }else{\n                assert( pFree!=0 );\n                pFree->pRight = p;\n                pFree->pLeft = apLeaf[i];\n                pFree->pLeft->pParent = pFree;\n                pFree->pRight->pParent = pFree;\n\n                p = pFree;\n                pFree = pFree->pParent;\n                p->pParent = 0;\n              }\n            }\n          }\n          pRoot = p;\n        }else{\n          /* An error occurred. Delete the contents of the apLeaf[] array \n          ** and pFree list. Everything else is cleaned up by the call to\n          ** sqlite3Fts3ExprFree(pRoot) below.  */\n          Fts3Expr *pDel;\n          for(i=0; i<nMaxDepth; i++){\n            sqlite3Fts3ExprFree(apLeaf[i]);\n          }\n          while( (pDel=pFree)!=0 ){\n            pFree = pDel->pParent;\n            sqlite3_free(pDel);\n          }\n        }\n\n        assert( pFree==0 );\n        sqlite3_free( apLeaf );\n      }\n    }else if( eType==FTSQUERY_NOT ){\n      Fts3Expr *pLeft = pRoot->pLeft;\n      Fts3Expr *pRight = pRoot->pRight;\n\n      pRoot->pLeft = 0;\n      pRoot->pRight = 0;\n      pLeft->pParent = 0;\n      pRight->pParent = 0;\n\n      rc = fts3ExprBalance(&pLeft, nMaxDepth-1);\n      if( rc==SQLITE_OK ){\n        rc = fts3ExprBalance(&pRight, nMaxDepth-1);\n      }\n\n      if( rc!=SQLITE_OK ){\n        sqlite3Fts3ExprFree(pRight);\n        sqlite3Fts3ExprFree(pLeft);\n      }else{\n        assert( pLeft && pRight );\n        pRoot->pLeft = pLeft;\n        pLeft->pParent = pRoot;\n        pRoot->pRight = pRight;\n        pRight->pParent = pRoot;\n      }\n    }\n  }\n  \n  if( rc!=SQLITE_OK ){\n    sqlite3Fts3ExprFree(pRoot);\n    pRoot = 0;\n  }\n  *pp = pRoot;\n  return rc;\n}\n\n/*\n** This function is similar to sqlite3Fts3ExprParse(), with the following\n** differences:\n**\n**   1. It does not do expression rebalancing.\n**   2. It does not check that the expression does not exceed the \n**      maximum allowable depth.\n**   3. Even if it fails, *ppExpr may still be set to point to an \n**      expression tree. It should be deleted using sqlite3Fts3ExprFree()\n**      in this case.\n*/\nstatic int fts3ExprParseUnbalanced(\n  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */\n  int iLangid,                        /* Language id for tokenizer */\n  char **azCol,                       /* Array of column names for fts3 table */\n  int bFts4,                          /* True to allow FTS4-only syntax */\n  int nCol,                           /* Number of entries in azCol[] */\n  int iDefaultCol,                    /* Default column to query */\n  const char *z, int n,               /* Text of MATCH query */\n  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */\n){\n  int nParsed;\n  int rc;\n  ParseContext sParse;\n\n  memset(&sParse, 0, sizeof(ParseContext));\n  sParse.pTokenizer = pTokenizer;\n  sParse.iLangid = iLangid;\n  sParse.azCol = (const char **)azCol;\n  sParse.nCol = nCol;\n  sParse.iDefaultCol = iDefaultCol;\n  sParse.bFts4 = bFts4;\n  if( z==0 ){\n    *ppExpr = 0;\n    return SQLITE_OK;\n  }\n  if( n<0 ){\n    n = (int)strlen(z);\n  }\n  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);\n  assert( rc==SQLITE_OK || *ppExpr==0 );\n\n  /* Check for mismatched parenthesis */\n  if( rc==SQLITE_OK && sParse.nNest ){\n    rc = SQLITE_ERROR;\n  }\n  \n  return rc;\n}\n\n/*\n** Parameters z and n contain a pointer to and length of a buffer containing\n** an fts3 query expression, respectively. This function attempts to parse the\n** query expression and create a tree of Fts3Expr structures representing the\n** parsed expression. If successful, *ppExpr is set to point to the head\n** of the parsed expression tree and SQLITE_OK is returned. If an error\n** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse\n** error) is returned and *ppExpr is set to 0.\n**\n** If parameter n is a negative number, then z is assumed to point to a\n** nul-terminated string and the length is determined using strlen().\n**\n** The first parameter, pTokenizer, is passed the fts3 tokenizer module to\n** use to normalize query tokens while parsing the expression. The azCol[]\n** array, which is assumed to contain nCol entries, should contain the names\n** of each column in the target fts3 table, in order from left to right. \n** Column names must be nul-terminated strings.\n**\n** The iDefaultCol parameter should be passed the index of the table column\n** that appears on the left-hand-side of the MATCH operator (the default\n** column to match against for tokens for which a column name is not explicitly\n** specified as part of the query string), or -1 if tokens may by default\n** match any table column.\n*/\nSQLITE_PRIVATE int sqlite3Fts3ExprParse(\n  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */\n  int iLangid,                        /* Language id for tokenizer */\n  char **azCol,                       /* Array of column names for fts3 table */\n  int bFts4,                          /* True to allow FTS4-only syntax */\n  int nCol,                           /* Number of entries in azCol[] */\n  int iDefaultCol,                    /* Default column to query */\n  const char *z, int n,               /* Text of MATCH query */\n  Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */\n  char **pzErr                        /* OUT: Error message (sqlite3_malloc) */\n){\n  int rc = fts3ExprParseUnbalanced(\n      pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr\n  );\n  \n  /* Rebalance the expression. And check that its depth does not exceed\n  ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */\n  if( rc==SQLITE_OK && *ppExpr ){\n    rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);\n    if( rc==SQLITE_OK ){\n      rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);\n    }\n  }\n\n  if( rc!=SQLITE_OK ){\n    sqlite3Fts3ExprFree(*ppExpr);\n    *ppExpr = 0;\n    if( rc==SQLITE_TOOBIG ){\n      sqlite3Fts3ErrMsg(pzErr,\n          \"FTS expression tree is too large (maximum depth %d)\", \n          SQLITE_FTS3_MAX_EXPR_DEPTH\n      );\n      rc = SQLITE_ERROR;\n    }else if( rc==SQLITE_ERROR ){\n      sqlite3Fts3ErrMsg(pzErr, \"malformed MATCH expression: [%s]\", z);\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Free a single node of an expression tree.\n*/\nstatic void fts3FreeExprNode(Fts3Expr *p){\n  assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );\n  sqlite3Fts3EvalPhraseCleanup(p->pPhrase);\n  sqlite3_free(p->aMI);\n  sqlite3_free(p);\n}\n\n/*\n** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().\n**\n** This function would be simpler if it recursively called itself. But\n** that would mean passing a sufficiently large expression to ExprParse()\n** could cause a stack overflow.\n*/\nSQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){\n  Fts3Expr *p;\n  assert( pDel==0 || pDel->pParent==0 );\n  for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){\n    assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );\n  }\n  while( p ){\n    Fts3Expr *pParent = p->pParent;\n    fts3FreeExprNode(p);\n    if( pParent && p==pParent->pLeft && pParent->pRight ){\n      p = pParent->pRight;\n      while( p && (p->pLeft || p->pRight) ){\n        assert( p==p->pParent->pRight || p==p->pParent->pLeft );\n        p = (p->pLeft ? p->pLeft : p->pRight);\n      }\n    }else{\n      p = pParent;\n    }\n  }\n}\n\n/****************************************************************************\n*****************************************************************************\n** Everything after this point is just test code.\n*/\n\n#ifdef SQLITE_TEST\n\n/* #include <stdio.h> */\n\n/*\n** Return a pointer to a buffer containing a text representation of the\n** expression passed as the first argument. The buffer is obtained from\n** sqlite3_malloc(). It is the responsibility of the caller to use \n** sqlite3_free() to release the memory. If an OOM condition is encountered,\n** NULL is returned.\n**\n** If the second argument is not NULL, then its contents are prepended to \n** the returned expression text and then freed using sqlite3_free().\n*/\nstatic char *exprToString(Fts3Expr *pExpr, char *zBuf){\n  if( pExpr==0 ){\n    return sqlite3_mprintf(\"\");\n  }\n  switch( pExpr->eType ){\n    case FTSQUERY_PHRASE: {\n      Fts3Phrase *pPhrase = pExpr->pPhrase;\n      int i;\n      zBuf = sqlite3_mprintf(\n          \"%zPHRASE %d 0\", zBuf, pPhrase->iColumn);\n      for(i=0; zBuf && i<pPhrase->nToken; i++){\n        zBuf = sqlite3_mprintf(\"%z %.*s%s\", zBuf, \n            pPhrase->aToken[i].n, pPhrase->aToken[i].z,\n            (pPhrase->aToken[i].isPrefix?\"+\":\"\")\n        );\n      }\n      return zBuf;\n    }\n\n    case FTSQUERY_NEAR:\n      zBuf = sqlite3_mprintf(\"%zNEAR/%d \", zBuf, pExpr->nNear);\n      break;\n    case FTSQUERY_NOT:\n      zBuf = sqlite3_mprintf(\"%zNOT \", zBuf);\n      break;\n    case FTSQUERY_AND:\n      zBuf = sqlite3_mprintf(\"%zAND \", zBuf);\n      break;\n    case FTSQUERY_OR:\n      zBuf = sqlite3_mprintf(\"%zOR \", zBuf);\n      break;\n  }\n\n  if( zBuf ) zBuf = sqlite3_mprintf(\"%z{\", zBuf);\n  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);\n  if( zBuf ) zBuf = sqlite3_mprintf(\"%z} {\", zBuf);\n\n  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);\n  if( zBuf ) zBuf = sqlite3_mprintf(\"%z}\", zBuf);\n\n  return zBuf;\n}\n\n/*\n** This is the implementation of a scalar SQL function used to test the \n** expression parser. It should be called as follows:\n**\n**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);\n**\n** The first argument, <tokenizer>, is the name of the fts3 tokenizer used\n** to parse the query expression (see README.tokenizers). The second argument\n** is the query expression to parse. Each subsequent argument is the name\n** of a column of the fts3 table that the query expression may refer to.\n** For example:\n**\n**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');\n*/\nstatic void fts3ExprTestCommon(\n  int bRebalance,\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  sqlite3_tokenizer *pTokenizer = 0;\n  int rc;\n  char **azCol = 0;\n  const char *zExpr;\n  int nExpr;\n  int nCol;\n  int ii;\n  Fts3Expr *pExpr;\n  char *zBuf = 0;\n  Fts3Hash *pHash = (Fts3Hash*)sqlite3_user_data(context);\n  const char *zTokenizer = 0;\n  char *zErr = 0;\n\n  if( argc<3 ){\n    sqlite3_result_error(context, \n        \"Usage: fts3_exprtest(tokenizer, expr, col1, ...\", -1\n    );\n    return;\n  }\n\n  zTokenizer = (const char*)sqlite3_value_text(argv[0]);\n  rc = sqlite3Fts3InitTokenizer(pHash, zTokenizer, &pTokenizer, &zErr);\n  if( rc!=SQLITE_OK ){\n    if( rc==SQLITE_NOMEM ){\n      sqlite3_result_error_nomem(context);\n    }else{\n      sqlite3_result_error(context, zErr, -1);\n    }\n    sqlite3_free(zErr);\n    return;\n  }\n\n  zExpr = (const char *)sqlite3_value_text(argv[1]);\n  nExpr = sqlite3_value_bytes(argv[1]);\n  nCol = argc-2;\n  azCol = (char **)sqlite3_malloc64(nCol*sizeof(char *));\n  if( !azCol ){\n    sqlite3_result_error_nomem(context);\n    goto exprtest_out;\n  }\n  for(ii=0; ii<nCol; ii++){\n    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);\n  }\n\n  if( bRebalance ){\n    char *zDummy = 0;\n    rc = sqlite3Fts3ExprParse(\n        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy\n    );\n    assert( rc==SQLITE_OK || pExpr==0 );\n    sqlite3_free(zDummy);\n  }else{\n    rc = fts3ExprParseUnbalanced(\n        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr\n    );\n  }\n\n  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){\n    sqlite3Fts3ExprFree(pExpr);\n    sqlite3_result_error(context, \"Error parsing expression\", -1);\n  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){\n    sqlite3_result_error_nomem(context);\n  }else{\n    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);\n    sqlite3_free(zBuf);\n  }\n\n  sqlite3Fts3ExprFree(pExpr);\n\nexprtest_out:\n  if( pTokenizer ){\n    rc = pTokenizer->pModule->xDestroy(pTokenizer);\n  }\n  sqlite3_free(azCol);\n}\n\nstatic void fts3ExprTest(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  fts3ExprTestCommon(0, context, argc, argv);\n}\nstatic void fts3ExprTestRebalance(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  fts3ExprTestCommon(1, context, argc, argv);\n}\n\n/*\n** Register the query expression parser test function fts3_exprtest() \n** with database connection db. \n*/\nSQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash *pHash){\n  int rc = sqlite3_create_function(\n      db, \"fts3_exprtest\", -1, SQLITE_UTF8, (void*)pHash, fts3ExprTest, 0, 0\n  );\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_function(db, \"fts3_exprtest_rebalance\", \n        -1, SQLITE_UTF8, (void*)pHash, fts3ExprTestRebalance, 0, 0\n    );\n  }\n  return rc;\n}\n\n#endif\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n\n/************** End of fts3_expr.c *******************************************/\n/************** Begin file fts3_hash.c ***************************************/\n/*\n** 2001 September 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This is the implementation of generic hash-tables used in SQLite.\n** We've modified it slightly to serve as a standalone hash table\n** implementation for the full-text indexing module.\n*/\n\n/*\n** The code in this file is only compiled if:\n**\n**     * The FTS3 module is being built as an extension\n**       (in which case SQLITE_CORE is not defined), or\n**\n**     * The FTS3 module is being built into the core of\n**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).\n*/\n/* #include \"fts3Int.h\" */\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <assert.h> */\n/* #include <stdlib.h> */\n/* #include <string.h> */\n\n/* #include \"fts3_hash.h\" */\n\n/*\n** Malloc and Free functions\n*/\nstatic void *fts3HashMalloc(sqlite3_int64 n){\n  void *p = sqlite3_malloc64(n);\n  if( p ){\n    memset(p, 0, n);\n  }\n  return p;\n}\nstatic void fts3HashFree(void *p){\n  sqlite3_free(p);\n}\n\n/* Turn bulk memory into a hash table object by initializing the\n** fields of the Hash structure.\n**\n** \"pNew\" is a pointer to the hash table that is to be initialized.\n** keyClass is one of the constants \n** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass \n** determines what kind of key the hash table will use.  \"copyKey\" is\n** true if the hash table should make its own private copy of keys and\n** false if it should just use the supplied pointer.\n*/\nSQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){\n  assert( pNew!=0 );\n  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );\n  pNew->keyClass = keyClass;\n  pNew->copyKey = copyKey;\n  pNew->first = 0;\n  pNew->count = 0;\n  pNew->htsize = 0;\n  pNew->ht = 0;\n}\n\n/* Remove all entries from a hash table.  Reclaim all memory.\n** Call this routine to delete a hash table or to reset a hash table\n** to the empty state.\n*/\nSQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){\n  Fts3HashElem *elem;         /* For looping over all elements of the table */\n\n  assert( pH!=0 );\n  elem = pH->first;\n  pH->first = 0;\n  fts3HashFree(pH->ht);\n  pH->ht = 0;\n  pH->htsize = 0;\n  while( elem ){\n    Fts3HashElem *next_elem = elem->next;\n    if( pH->copyKey && elem->pKey ){\n      fts3HashFree(elem->pKey);\n    }\n    fts3HashFree(elem);\n    elem = next_elem;\n  }\n  pH->count = 0;\n}\n\n/*\n** Hash and comparison functions when the mode is FTS3_HASH_STRING\n*/\nstatic int fts3StrHash(const void *pKey, int nKey){\n  const char *z = (const char *)pKey;\n  unsigned h = 0;\n  if( nKey<=0 ) nKey = (int) strlen(z);\n  while( nKey > 0  ){\n    h = (h<<3) ^ h ^ *z++;\n    nKey--;\n  }\n  return (int)(h & 0x7fffffff);\n}\nstatic int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){\n  if( n1!=n2 ) return 1;\n  return strncmp((const char*)pKey1,(const char*)pKey2,n1);\n}\n\n/*\n** Hash and comparison functions when the mode is FTS3_HASH_BINARY\n*/\nstatic int fts3BinHash(const void *pKey, int nKey){\n  int h = 0;\n  const char *z = (const char *)pKey;\n  while( nKey-- > 0 ){\n    h = (h<<3) ^ h ^ *(z++);\n  }\n  return h & 0x7fffffff;\n}\nstatic int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){\n  if( n1!=n2 ) return 1;\n  return memcmp(pKey1,pKey2,n1);\n}\n\n/*\n** Return a pointer to the appropriate hash function given the key class.\n**\n** The C syntax in this function definition may be unfamilar to some \n** programmers, so we provide the following additional explanation:\n**\n** The name of the function is \"ftsHashFunction\".  The function takes a\n** single parameter \"keyClass\".  The return value of ftsHashFunction()\n** is a pointer to another function.  Specifically, the return value\n** of ftsHashFunction() is a pointer to a function that takes two parameters\n** with types \"const void*\" and \"int\" and returns an \"int\".\n*/\nstatic int (*ftsHashFunction(int keyClass))(const void*,int){\n  if( keyClass==FTS3_HASH_STRING ){\n    return &fts3StrHash;\n  }else{\n    assert( keyClass==FTS3_HASH_BINARY );\n    return &fts3BinHash;\n  }\n}\n\n/*\n** Return a pointer to the appropriate hash function given the key class.\n**\n** For help in interpreted the obscure C code in the function definition,\n** see the header comment on the previous function.\n*/\nstatic int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){\n  if( keyClass==FTS3_HASH_STRING ){\n    return &fts3StrCompare;\n  }else{\n    assert( keyClass==FTS3_HASH_BINARY );\n    return &fts3BinCompare;\n  }\n}\n\n/* Link an element into the hash table\n*/\nstatic void fts3HashInsertElement(\n  Fts3Hash *pH,            /* The complete hash table */\n  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */\n  Fts3HashElem *pNew       /* The element to be inserted */\n){\n  Fts3HashElem *pHead;     /* First element already in pEntry */\n  pHead = pEntry->chain;\n  if( pHead ){\n    pNew->next = pHead;\n    pNew->prev = pHead->prev;\n    if( pHead->prev ){ pHead->prev->next = pNew; }\n    else             { pH->first = pNew; }\n    pHead->prev = pNew;\n  }else{\n    pNew->next = pH->first;\n    if( pH->first ){ pH->first->prev = pNew; }\n    pNew->prev = 0;\n    pH->first = pNew;\n  }\n  pEntry->count++;\n  pEntry->chain = pNew;\n}\n\n\n/* Resize the hash table so that it cantains \"new_size\" buckets.\n** \"new_size\" must be a power of 2.  The hash table might fail \n** to resize if sqliteMalloc() fails.\n**\n** Return non-zero if a memory allocation error occurs.\n*/\nstatic int fts3Rehash(Fts3Hash *pH, int new_size){\n  struct _fts3ht *new_ht;          /* The new hash table */\n  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */\n  int (*xHash)(const void*,int);   /* The hash function */\n\n  assert( (new_size & (new_size-1))==0 );\n  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );\n  if( new_ht==0 ) return 1;\n  fts3HashFree(pH->ht);\n  pH->ht = new_ht;\n  pH->htsize = new_size;\n  xHash = ftsHashFunction(pH->keyClass);\n  for(elem=pH->first, pH->first=0; elem; elem = next_elem){\n    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);\n    next_elem = elem->next;\n    fts3HashInsertElement(pH, &new_ht[h], elem);\n  }\n  return 0;\n}\n\n/* This function (for internal use only) locates an element in an\n** hash table that matches the given key.  The hash for this key has\n** already been computed and is passed as the 4th parameter.\n*/\nstatic Fts3HashElem *fts3FindElementByHash(\n  const Fts3Hash *pH, /* The pH to be searched */\n  const void *pKey,   /* The key we are searching for */\n  int nKey,\n  int h               /* The hash for this key. */\n){\n  Fts3HashElem *elem;            /* Used to loop thru the element list */\n  int count;                     /* Number of elements left to test */\n  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */\n\n  if( pH->ht ){\n    struct _fts3ht *pEntry = &pH->ht[h];\n    elem = pEntry->chain;\n    count = pEntry->count;\n    xCompare = ftsCompareFunction(pH->keyClass);\n    while( count-- && elem ){\n      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ \n        return elem;\n      }\n      elem = elem->next;\n    }\n  }\n  return 0;\n}\n\n/* Remove a single entry from the hash table given a pointer to that\n** element and a hash on the element's key.\n*/\nstatic void fts3RemoveElementByHash(\n  Fts3Hash *pH,         /* The pH containing \"elem\" */\n  Fts3HashElem* elem,   /* The element to be removed from the pH */\n  int h                 /* Hash value for the element */\n){\n  struct _fts3ht *pEntry;\n  if( elem->prev ){\n    elem->prev->next = elem->next; \n  }else{\n    pH->first = elem->next;\n  }\n  if( elem->next ){\n    elem->next->prev = elem->prev;\n  }\n  pEntry = &pH->ht[h];\n  if( pEntry->chain==elem ){\n    pEntry->chain = elem->next;\n  }\n  pEntry->count--;\n  if( pEntry->count<=0 ){\n    pEntry->chain = 0;\n  }\n  if( pH->copyKey && elem->pKey ){\n    fts3HashFree(elem->pKey);\n  }\n  fts3HashFree( elem );\n  pH->count--;\n  if( pH->count<=0 ){\n    assert( pH->first==0 );\n    assert( pH->count==0 );\n    fts3HashClear(pH);\n  }\n}\n\nSQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(\n  const Fts3Hash *pH, \n  const void *pKey, \n  int nKey\n){\n  int h;                          /* A hash on key */\n  int (*xHash)(const void*,int);  /* The hash function */\n\n  if( pH==0 || pH->ht==0 ) return 0;\n  xHash = ftsHashFunction(pH->keyClass);\n  assert( xHash!=0 );\n  h = (*xHash)(pKey,nKey);\n  assert( (pH->htsize & (pH->htsize-1))==0 );\n  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));\n}\n\n/* \n** Attempt to locate an element of the hash table pH with a key\n** that matches pKey,nKey.  Return the data for this element if it is\n** found, or NULL if there is no match.\n*/\nSQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){\n  Fts3HashElem *pElem;            /* The element that matches key (if any) */\n\n  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);\n  return pElem ? pElem->data : 0;\n}\n\n/* Insert an element into the hash table pH.  The key is pKey,nKey\n** and the data is \"data\".\n**\n** If no element exists with a matching key, then a new\n** element is created.  A copy of the key is made if the copyKey\n** flag is set.  NULL is returned.\n**\n** If another element already exists with the same key, then the\n** new data replaces the old data and the old data is returned.\n** The key is not copied in this instance.  If a malloc fails, then\n** the new data is returned and the hash table is unchanged.\n**\n** If the \"data\" parameter to this function is NULL, then the\n** element corresponding to \"key\" is removed from the hash table.\n*/\nSQLITE_PRIVATE void *sqlite3Fts3HashInsert(\n  Fts3Hash *pH,        /* The hash table to insert into */\n  const void *pKey,    /* The key */\n  int nKey,            /* Number of bytes in the key */\n  void *data           /* The data */\n){\n  int hraw;                 /* Raw hash value of the key */\n  int h;                    /* the hash of the key modulo hash table size */\n  Fts3HashElem *elem;       /* Used to loop thru the element list */\n  Fts3HashElem *new_elem;   /* New element added to the pH */\n  int (*xHash)(const void*,int);  /* The hash function */\n\n  assert( pH!=0 );\n  xHash = ftsHashFunction(pH->keyClass);\n  assert( xHash!=0 );\n  hraw = (*xHash)(pKey, nKey);\n  assert( (pH->htsize & (pH->htsize-1))==0 );\n  h = hraw & (pH->htsize-1);\n  elem = fts3FindElementByHash(pH,pKey,nKey,h);\n  if( elem ){\n    void *old_data = elem->data;\n    if( data==0 ){\n      fts3RemoveElementByHash(pH,elem,h);\n    }else{\n      elem->data = data;\n    }\n    return old_data;\n  }\n  if( data==0 ) return 0;\n  if( (pH->htsize==0 && fts3Rehash(pH,8))\n   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))\n  ){\n    pH->count = 0;\n    return data;\n  }\n  assert( pH->htsize>0 );\n  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );\n  if( new_elem==0 ) return data;\n  if( pH->copyKey && pKey!=0 ){\n    new_elem->pKey = fts3HashMalloc( nKey );\n    if( new_elem->pKey==0 ){\n      fts3HashFree(new_elem);\n      return data;\n    }\n    memcpy((void*)new_elem->pKey, pKey, nKey);\n  }else{\n    new_elem->pKey = (void*)pKey;\n  }\n  new_elem->nKey = nKey;\n  pH->count++;\n  assert( pH->htsize>0 );\n  assert( (pH->htsize & (pH->htsize-1))==0 );\n  h = hraw & (pH->htsize-1);\n  fts3HashInsertElement(pH, &pH->ht[h], new_elem);\n  new_elem->data = data;\n  return 0;\n}\n\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n\n/************** End of fts3_hash.c *******************************************/\n/************** Begin file fts3_porter.c *************************************/\n/*\n** 2006 September 30\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** Implementation of the full-text-search tokenizer that implements\n** a Porter stemmer.\n*/\n\n/*\n** The code in this file is only compiled if:\n**\n**     * The FTS3 module is being built as an extension\n**       (in which case SQLITE_CORE is not defined), or\n**\n**     * The FTS3 module is being built into the core of\n**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).\n*/\n/* #include \"fts3Int.h\" */\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <assert.h> */\n/* #include <stdlib.h> */\n/* #include <stdio.h> */\n/* #include <string.h> */\n\n/* #include \"fts3_tokenizer.h\" */\n\n/*\n** Class derived from sqlite3_tokenizer\n*/\ntypedef struct porter_tokenizer {\n  sqlite3_tokenizer base;      /* Base class */\n} porter_tokenizer;\n\n/*\n** Class derived from sqlite3_tokenizer_cursor\n*/\ntypedef struct porter_tokenizer_cursor {\n  sqlite3_tokenizer_cursor base;\n  const char *zInput;          /* input we are tokenizing */\n  int nInput;                  /* size of the input */\n  int iOffset;                 /* current position in zInput */\n  int iToken;                  /* index of next token to be returned */\n  char *zToken;                /* storage for current token */\n  int nAllocated;              /* space allocated to zToken buffer */\n} porter_tokenizer_cursor;\n\n\n/*\n** Create a new tokenizer instance.\n*/\nstatic int porterCreate(\n  int argc, const char * const *argv,\n  sqlite3_tokenizer **ppTokenizer\n){\n  porter_tokenizer *t;\n\n  UNUSED_PARAMETER(argc);\n  UNUSED_PARAMETER(argv);\n\n  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));\n  if( t==NULL ) return SQLITE_NOMEM;\n  memset(t, 0, sizeof(*t));\n  *ppTokenizer = &t->base;\n  return SQLITE_OK;\n}\n\n/*\n** Destroy a tokenizer\n*/\nstatic int porterDestroy(sqlite3_tokenizer *pTokenizer){\n  sqlite3_free(pTokenizer);\n  return SQLITE_OK;\n}\n\n/*\n** Prepare to begin tokenizing a particular string.  The input\n** string to be tokenized is zInput[0..nInput-1].  A cursor\n** used to incrementally tokenize this string is returned in \n** *ppCursor.\n*/\nstatic int porterOpen(\n  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */\n  const char *zInput, int nInput,        /* String to be tokenized */\n  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */\n){\n  porter_tokenizer_cursor *c;\n\n  UNUSED_PARAMETER(pTokenizer);\n\n  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));\n  if( c==NULL ) return SQLITE_NOMEM;\n\n  c->zInput = zInput;\n  if( zInput==0 ){\n    c->nInput = 0;\n  }else if( nInput<0 ){\n    c->nInput = (int)strlen(zInput);\n  }else{\n    c->nInput = nInput;\n  }\n  c->iOffset = 0;                 /* start tokenizing at the beginning */\n  c->iToken = 0;\n  c->zToken = NULL;               /* no space allocated, yet. */\n  c->nAllocated = 0;\n\n  *ppCursor = &c->base;\n  return SQLITE_OK;\n}\n\n/*\n** Close a tokenization cursor previously opened by a call to\n** porterOpen() above.\n*/\nstatic int porterClose(sqlite3_tokenizer_cursor *pCursor){\n  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;\n  sqlite3_free(c->zToken);\n  sqlite3_free(c);\n  return SQLITE_OK;\n}\n/*\n** Vowel or consonant\n*/\nstatic const char cType[] = {\n   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,\n   1, 1, 1, 2, 1\n};\n\n/*\n** isConsonant() and isVowel() determine if their first character in\n** the string they point to is a consonant or a vowel, according\n** to Porter ruls.  \n**\n** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.\n** 'Y' is a consonant unless it follows another consonant,\n** in which case it is a vowel.\n**\n** In these routine, the letters are in reverse order.  So the 'y' rule\n** is that 'y' is a consonant unless it is followed by another\n** consonent.\n*/\nstatic int isVowel(const char*);\nstatic int isConsonant(const char *z){\n  int j;\n  char x = *z;\n  if( x==0 ) return 0;\n  assert( x>='a' && x<='z' );\n  j = cType[x-'a'];\n  if( j<2 ) return j;\n  return z[1]==0 || isVowel(z + 1);\n}\nstatic int isVowel(const char *z){\n  int j;\n  char x = *z;\n  if( x==0 ) return 0;\n  assert( x>='a' && x<='z' );\n  j = cType[x-'a'];\n  if( j<2 ) return 1-j;\n  return isConsonant(z + 1);\n}\n\n/*\n** Let any sequence of one or more vowels be represented by V and let\n** C be sequence of one or more consonants.  Then every word can be\n** represented as:\n**\n**           [C] (VC){m} [V]\n**\n** In prose:  A word is an optional consonant followed by zero or\n** vowel-consonant pairs followed by an optional vowel.  \"m\" is the\n** number of vowel consonant pairs.  This routine computes the value\n** of m for the first i bytes of a word.\n**\n** Return true if the m-value for z is 1 or more.  In other words,\n** return true if z contains at least one vowel that is followed\n** by a consonant.\n**\n** In this routine z[] is in reverse order.  So we are really looking\n** for an instance of a consonant followed by a vowel.\n*/\nstatic int m_gt_0(const char *z){\n  while( isVowel(z) ){ z++; }\n  if( *z==0 ) return 0;\n  while( isConsonant(z) ){ z++; }\n  return *z!=0;\n}\n\n/* Like mgt0 above except we are looking for a value of m which is\n** exactly 1\n*/\nstatic int m_eq_1(const char *z){\n  while( isVowel(z) ){ z++; }\n  if( *z==0 ) return 0;\n  while( isConsonant(z) ){ z++; }\n  if( *z==0 ) return 0;\n  while( isVowel(z) ){ z++; }\n  if( *z==0 ) return 1;\n  while( isConsonant(z) ){ z++; }\n  return *z==0;\n}\n\n/* Like mgt0 above except we are looking for a value of m>1 instead\n** or m>0\n*/\nstatic int m_gt_1(const char *z){\n  while( isVowel(z) ){ z++; }\n  if( *z==0 ) return 0;\n  while( isConsonant(z) ){ z++; }\n  if( *z==0 ) return 0;\n  while( isVowel(z) ){ z++; }\n  if( *z==0 ) return 0;\n  while( isConsonant(z) ){ z++; }\n  return *z!=0;\n}\n\n/*\n** Return TRUE if there is a vowel anywhere within z[0..n-1]\n*/\nstatic int hasVowel(const char *z){\n  while( isConsonant(z) ){ z++; }\n  return *z!=0;\n}\n\n/*\n** Return TRUE if the word ends in a double consonant.\n**\n** The text is reversed here. So we are really looking at\n** the first two characters of z[].\n*/\nstatic int doubleConsonant(const char *z){\n  return isConsonant(z) && z[0]==z[1];\n}\n\n/*\n** Return TRUE if the word ends with three letters which\n** are consonant-vowel-consonent and where the final consonant\n** is not 'w', 'x', or 'y'.\n**\n** The word is reversed here.  So we are really checking the\n** first three letters and the first one cannot be in [wxy].\n*/\nstatic int star_oh(const char *z){\n  return\n    isConsonant(z) &&\n    z[0]!='w' && z[0]!='x' && z[0]!='y' &&\n    isVowel(z+1) &&\n    isConsonant(z+2);\n}\n\n/*\n** If the word ends with zFrom and xCond() is true for the stem\n** of the word that preceeds the zFrom ending, then change the \n** ending to zTo.\n**\n** The input word *pz and zFrom are both in reverse order.  zTo\n** is in normal order. \n**\n** Return TRUE if zFrom matches.  Return FALSE if zFrom does not\n** match.  Not that TRUE is returned even if xCond() fails and\n** no substitution occurs.\n*/\nstatic int stem(\n  char **pz,             /* The word being stemmed (Reversed) */\n  const char *zFrom,     /* If the ending matches this... (Reversed) */\n  const char *zTo,       /* ... change the ending to this (not reversed) */\n  int (*xCond)(const char*)   /* Condition that must be true */\n){\n  char *z = *pz;\n  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }\n  if( *zFrom!=0 ) return 0;\n  if( xCond && !xCond(z) ) return 1;\n  while( *zTo ){\n    *(--z) = *(zTo++);\n  }\n  *pz = z;\n  return 1;\n}\n\n/*\n** This is the fallback stemmer used when the porter stemmer is\n** inappropriate.  The input word is copied into the output with\n** US-ASCII case folding.  If the input word is too long (more\n** than 20 bytes if it contains no digits or more than 6 bytes if\n** it contains digits) then word is truncated to 20 or 6 bytes\n** by taking 10 or 3 bytes from the beginning and end.\n*/\nstatic void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){\n  int i, mx, j;\n  int hasDigit = 0;\n  for(i=0; i<nIn; i++){\n    char c = zIn[i];\n    if( c>='A' && c<='Z' ){\n      zOut[i] = c - 'A' + 'a';\n    }else{\n      if( c>='0' && c<='9' ) hasDigit = 1;\n      zOut[i] = c;\n    }\n  }\n  mx = hasDigit ? 3 : 10;\n  if( nIn>mx*2 ){\n    for(j=mx, i=nIn-mx; i<nIn; i++, j++){\n      zOut[j] = zOut[i];\n    }\n    i = j;\n  }\n  zOut[i] = 0;\n  *pnOut = i;\n}\n\n\n/*\n** Stem the input word zIn[0..nIn-1].  Store the output in zOut.\n** zOut is at least big enough to hold nIn bytes.  Write the actual\n** size of the output word (exclusive of the '\\0' terminator) into *pnOut.\n**\n** Any upper-case characters in the US-ASCII character set ([A-Z])\n** are converted to lower case.  Upper-case UTF characters are\n** unchanged.\n**\n** Words that are longer than about 20 bytes are stemmed by retaining\n** a few bytes from the beginning and the end of the word.  If the\n** word contains digits, 3 bytes are taken from the beginning and\n** 3 bytes from the end.  For long words without digits, 10 bytes\n** are taken from each end.  US-ASCII case folding still applies.\n** \n** If the input word contains not digits but does characters not \n** in [a-zA-Z] then no stemming is attempted and this routine just \n** copies the input into the input into the output with US-ASCII\n** case folding.\n**\n** Stemming never increases the length of the word.  So there is\n** no chance of overflowing the zOut buffer.\n*/\nstatic void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){\n  int i, j;\n  char zReverse[28];\n  char *z, *z2;\n  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){\n    /* The word is too big or too small for the porter stemmer.\n    ** Fallback to the copy stemmer */\n    copy_stemmer(zIn, nIn, zOut, pnOut);\n    return;\n  }\n  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){\n    char c = zIn[i];\n    if( c>='A' && c<='Z' ){\n      zReverse[j] = c + 'a' - 'A';\n    }else if( c>='a' && c<='z' ){\n      zReverse[j] = c;\n    }else{\n      /* The use of a character not in [a-zA-Z] means that we fallback\n      ** to the copy stemmer */\n      copy_stemmer(zIn, nIn, zOut, pnOut);\n      return;\n    }\n  }\n  memset(&zReverse[sizeof(zReverse)-5], 0, 5);\n  z = &zReverse[j+1];\n\n\n  /* Step 1a */\n  if( z[0]=='s' ){\n    if(\n     !stem(&z, \"sess\", \"ss\", 0) &&\n     !stem(&z, \"sei\", \"i\", 0)  &&\n     !stem(&z, \"ss\", \"ss\", 0)\n    ){\n      z++;\n    }\n  }\n\n  /* Step 1b */  \n  z2 = z;\n  if( stem(&z, \"dee\", \"ee\", m_gt_0) ){\n    /* Do nothing.  The work was all in the test */\n  }else if( \n     (stem(&z, \"gni\", \"\", hasVowel) || stem(&z, \"de\", \"\", hasVowel))\n      && z!=z2\n  ){\n     if( stem(&z, \"ta\", \"ate\", 0) ||\n         stem(&z, \"lb\", \"ble\", 0) ||\n         stem(&z, \"zi\", \"ize\", 0) ){\n       /* Do nothing.  The work was all in the test */\n     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){\n       z++;\n     }else if( m_eq_1(z) && star_oh(z) ){\n       *(--z) = 'e';\n     }\n  }\n\n  /* Step 1c */\n  if( z[0]=='y' && hasVowel(z+1) ){\n    z[0] = 'i';\n  }\n\n  /* Step 2 */\n  switch( z[1] ){\n   case 'a':\n     if( !stem(&z, \"lanoita\", \"ate\", m_gt_0) ){\n       stem(&z, \"lanoit\", \"tion\", m_gt_0);\n     }\n     break;\n   case 'c':\n     if( !stem(&z, \"icne\", \"ence\", m_gt_0) ){\n       stem(&z, \"icna\", \"ance\", m_gt_0);\n     }\n     break;\n   case 'e':\n     stem(&z, \"rezi\", \"ize\", m_gt_0);\n     break;\n   case 'g':\n     stem(&z, \"igol\", \"log\", m_gt_0);\n     break;\n   case 'l':\n     if( !stem(&z, \"ilb\", \"ble\", m_gt_0) \n      && !stem(&z, \"illa\", \"al\", m_gt_0)\n      && !stem(&z, \"iltne\", \"ent\", m_gt_0)\n      && !stem(&z, \"ile\", \"e\", m_gt_0)\n     ){\n       stem(&z, \"ilsuo\", \"ous\", m_gt_0);\n     }\n     break;\n   case 'o':\n     if( !stem(&z, \"noitazi\", \"ize\", m_gt_0)\n      && !stem(&z, \"noita\", \"ate\", m_gt_0)\n     ){\n       stem(&z, \"rota\", \"ate\", m_gt_0);\n     }\n     break;\n   case 's':\n     if( !stem(&z, \"msila\", \"al\", m_gt_0)\n      && !stem(&z, \"ssenevi\", \"ive\", m_gt_0)\n      && !stem(&z, \"ssenluf\", \"ful\", m_gt_0)\n     ){\n       stem(&z, \"ssensuo\", \"ous\", m_gt_0);\n     }\n     break;\n   case 't':\n     if( !stem(&z, \"itila\", \"al\", m_gt_0)\n      && !stem(&z, \"itivi\", \"ive\", m_gt_0)\n     ){\n       stem(&z, \"itilib\", \"ble\", m_gt_0);\n     }\n     break;\n  }\n\n  /* Step 3 */\n  switch( z[0] ){\n   case 'e':\n     if( !stem(&z, \"etaci\", \"ic\", m_gt_0)\n      && !stem(&z, \"evita\", \"\", m_gt_0)\n     ){\n       stem(&z, \"ezila\", \"al\", m_gt_0);\n     }\n     break;\n   case 'i':\n     stem(&z, \"itici\", \"ic\", m_gt_0);\n     break;\n   case 'l':\n     if( !stem(&z, \"laci\", \"ic\", m_gt_0) ){\n       stem(&z, \"luf\", \"\", m_gt_0);\n     }\n     break;\n   case 's':\n     stem(&z, \"ssen\", \"\", m_gt_0);\n     break;\n  }\n\n  /* Step 4 */\n  switch( z[1] ){\n   case 'a':\n     if( z[0]=='l' && m_gt_1(z+2) ){\n       z += 2;\n     }\n     break;\n   case 'c':\n     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){\n       z += 4;\n     }\n     break;\n   case 'e':\n     if( z[0]=='r' && m_gt_1(z+2) ){\n       z += 2;\n     }\n     break;\n   case 'i':\n     if( z[0]=='c' && m_gt_1(z+2) ){\n       z += 2;\n     }\n     break;\n   case 'l':\n     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){\n       z += 4;\n     }\n     break;\n   case 'n':\n     if( z[0]=='t' ){\n       if( z[2]=='a' ){\n         if( m_gt_1(z+3) ){\n           z += 3;\n         }\n       }else if( z[2]=='e' ){\n         if( !stem(&z, \"tneme\", \"\", m_gt_1)\n          && !stem(&z, \"tnem\", \"\", m_gt_1)\n         ){\n           stem(&z, \"tne\", \"\", m_gt_1);\n         }\n       }\n     }\n     break;\n   case 'o':\n     if( z[0]=='u' ){\n       if( m_gt_1(z+2) ){\n         z += 2;\n       }\n     }else if( z[3]=='s' || z[3]=='t' ){\n       stem(&z, \"noi\", \"\", m_gt_1);\n     }\n     break;\n   case 's':\n     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){\n       z += 3;\n     }\n     break;\n   case 't':\n     if( !stem(&z, \"eta\", \"\", m_gt_1) ){\n       stem(&z, \"iti\", \"\", m_gt_1);\n     }\n     break;\n   case 'u':\n     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){\n       z += 3;\n     }\n     break;\n   case 'v':\n   case 'z':\n     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){\n       z += 3;\n     }\n     break;\n  }\n\n  /* Step 5a */\n  if( z[0]=='e' ){\n    if( m_gt_1(z+1) ){\n      z++;\n    }else if( m_eq_1(z+1) && !star_oh(z+1) ){\n      z++;\n    }\n  }\n\n  /* Step 5b */\n  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){\n    z++;\n  }\n\n  /* z[] is now the stemmed word in reverse order.  Flip it back\n  ** around into forward order and return.\n  */\n  *pnOut = i = (int)strlen(z);\n  zOut[i] = 0;\n  while( *z ){\n    zOut[--i] = *(z++);\n  }\n}\n\n/*\n** Characters that can be part of a token.  We assume any character\n** whose value is greater than 0x80 (any UTF character) can be\n** part of a token.  In other words, delimiters all must have\n** values of 0x7f or lower.\n*/\nstatic const char porterIdChar[] = {\n/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */\n    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */\n    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */\n};\n#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))\n\n/*\n** Extract the next token from a tokenization cursor.  The cursor must\n** have been opened by a prior call to porterOpen().\n*/\nstatic int porterNext(\n  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */\n  const char **pzToken,               /* OUT: *pzToken is the token text */\n  int *pnBytes,                       /* OUT: Number of bytes in token */\n  int *piStartOffset,                 /* OUT: Starting offset of token */\n  int *piEndOffset,                   /* OUT: Ending offset of token */\n  int *piPosition                     /* OUT: Position integer of token */\n){\n  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;\n  const char *z = c->zInput;\n\n  while( c->iOffset<c->nInput ){\n    int iStartOffset, ch;\n\n    /* Scan past delimiter characters */\n    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){\n      c->iOffset++;\n    }\n\n    /* Count non-delimiter characters. */\n    iStartOffset = c->iOffset;\n    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){\n      c->iOffset++;\n    }\n\n    if( c->iOffset>iStartOffset ){\n      int n = c->iOffset-iStartOffset;\n      if( n>c->nAllocated ){\n        char *pNew;\n        c->nAllocated = n+20;\n        pNew = sqlite3_realloc(c->zToken, c->nAllocated);\n        if( !pNew ) return SQLITE_NOMEM;\n        c->zToken = pNew;\n      }\n      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);\n      *pzToken = c->zToken;\n      *piStartOffset = iStartOffset;\n      *piEndOffset = c->iOffset;\n      *piPosition = c->iToken++;\n      return SQLITE_OK;\n    }\n  }\n  return SQLITE_DONE;\n}\n\n/*\n** The set of routines that implement the porter-stemmer tokenizer\n*/\nstatic const sqlite3_tokenizer_module porterTokenizerModule = {\n  0,\n  porterCreate,\n  porterDestroy,\n  porterOpen,\n  porterClose,\n  porterNext,\n  0\n};\n\n/*\n** Allocate a new porter tokenizer.  Return a pointer to the new\n** tokenizer in *ppModule\n*/\nSQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(\n  sqlite3_tokenizer_module const**ppModule\n){\n  *ppModule = &porterTokenizerModule;\n}\n\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n\n/************** End of fts3_porter.c *****************************************/\n/************** Begin file fts3_tokenizer.c **********************************/\n/*\n** 2007 June 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This is part of an SQLite module implementing full-text search.\n** This particular file implements the generic tokenizer interface.\n*/\n\n/*\n** The code in this file is only compiled if:\n**\n**     * The FTS3 module is being built as an extension\n**       (in which case SQLITE_CORE is not defined), or\n**\n**     * The FTS3 module is being built into the core of\n**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).\n*/\n/* #include \"fts3Int.h\" */\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <assert.h> */\n/* #include <string.h> */\n\n/*\n** Return true if the two-argument version of fts3_tokenizer()\n** has been activated via a prior call to sqlite3_db_config(db,\n** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);\n*/\nstatic int fts3TokenizerEnabled(sqlite3_context *context){\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  int isEnabled = 0;\n  sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);\n  return isEnabled;\n}\n\n/*\n** Implementation of the SQL scalar function for accessing the underlying \n** hash table. This function may be called as follows:\n**\n**   SELECT <function-name>(<key-name>);\n**   SELECT <function-name>(<key-name>, <pointer>);\n**\n** where <function-name> is the name passed as the second argument\n** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').\n**\n** If the <pointer> argument is specified, it must be a blob value\n** containing a pointer to be stored as the hash data corresponding\n** to the string <key-name>. If <pointer> is not specified, then\n** the string <key-name> must already exist in the has table. Otherwise,\n** an error is returned.\n**\n** Whether or not the <pointer> argument is specified, the value returned\n** is a blob containing the pointer stored as the hash data corresponding\n** to string <key-name> (after the hash-table is updated, if applicable).\n*/\nstatic void fts3TokenizerFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  Fts3Hash *pHash;\n  void *pPtr = 0;\n  const unsigned char *zName;\n  int nName;\n\n  assert( argc==1 || argc==2 );\n\n  pHash = (Fts3Hash *)sqlite3_user_data(context);\n\n  zName = sqlite3_value_text(argv[0]);\n  nName = sqlite3_value_bytes(argv[0])+1;\n\n  if( argc==2 ){\n    if( fts3TokenizerEnabled(context) || sqlite3_value_frombind(argv[1]) ){\n      void *pOld;\n      int n = sqlite3_value_bytes(argv[1]);\n      if( zName==0 || n!=sizeof(pPtr) ){\n        sqlite3_result_error(context, \"argument type mismatch\", -1);\n        return;\n      }\n      pPtr = *(void **)sqlite3_value_blob(argv[1]);\n      pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);\n      if( pOld==pPtr ){\n        sqlite3_result_error(context, \"out of memory\", -1);\n      }\n    }else{\n      sqlite3_result_error(context, \"fts3tokenize disabled\", -1);\n      return;\n    }\n  }else{\n    if( zName ){\n      pPtr = sqlite3Fts3HashFind(pHash, zName, nName);\n    }\n    if( !pPtr ){\n      char *zErr = sqlite3_mprintf(\"unknown tokenizer: %s\", zName);\n      sqlite3_result_error(context, zErr, -1);\n      sqlite3_free(zErr);\n      return;\n    }\n  }\n  if( fts3TokenizerEnabled(context) || sqlite3_value_frombind(argv[0]) ){\n    sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);\n  }\n}\n\nSQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){\n  static const char isFtsIdChar[] = {\n      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */\n      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */\n      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */\n      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */\n      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */\n      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */\n      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */\n      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */\n  };\n  return (c&0x80 || isFtsIdChar[(int)(c)]);\n}\n\nSQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){\n  const char *z1;\n  const char *z2 = 0;\n\n  /* Find the start of the next token. */\n  z1 = zStr;\n  while( z2==0 ){\n    char c = *z1;\n    switch( c ){\n      case '\\0': return 0;        /* No more tokens here */\n      case '\\'':\n      case '\"':\n      case '`': {\n        z2 = z1;\n        while( *++z2 && (*z2!=c || *++z2==c) );\n        break;\n      }\n      case '[':\n        z2 = &z1[1];\n        while( *z2 && z2[0]!=']' ) z2++;\n        if( *z2 ) z2++;\n        break;\n\n      default:\n        if( sqlite3Fts3IsIdChar(*z1) ){\n          z2 = &z1[1];\n          while( sqlite3Fts3IsIdChar(*z2) ) z2++;\n        }else{\n          z1++;\n        }\n    }\n  }\n\n  *pn = (int)(z2-z1);\n  return z1;\n}\n\nSQLITE_PRIVATE int sqlite3Fts3InitTokenizer(\n  Fts3Hash *pHash,                /* Tokenizer hash table */\n  const char *zArg,               /* Tokenizer name */\n  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */\n  char **pzErr                    /* OUT: Set to malloced error message */\n){\n  int rc;\n  char *z = (char *)zArg;\n  int n = 0;\n  char *zCopy;\n  char *zEnd;                     /* Pointer to nul-term of zCopy */\n  sqlite3_tokenizer_module *m;\n\n  zCopy = sqlite3_mprintf(\"%s\", zArg);\n  if( !zCopy ) return SQLITE_NOMEM;\n  zEnd = &zCopy[strlen(zCopy)];\n\n  z = (char *)sqlite3Fts3NextToken(zCopy, &n);\n  if( z==0 ){\n    assert( n==0 );\n    z = zCopy;\n  }\n  z[n] = '\\0';\n  sqlite3Fts3Dequote(z);\n\n  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);\n  if( !m ){\n    sqlite3Fts3ErrMsg(pzErr, \"unknown tokenizer: %s\", z);\n    rc = SQLITE_ERROR;\n  }else{\n    char const **aArg = 0;\n    int iArg = 0;\n    z = &z[n+1];\n    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){\n      sqlite3_int64 nNew = sizeof(char *)*(iArg+1);\n      char const **aNew = (const char **)sqlite3_realloc64((void *)aArg, nNew);\n      if( !aNew ){\n        sqlite3_free(zCopy);\n        sqlite3_free((void *)aArg);\n        return SQLITE_NOMEM;\n      }\n      aArg = aNew;\n      aArg[iArg++] = z;\n      z[n] = '\\0';\n      sqlite3Fts3Dequote(z);\n      z = &z[n+1];\n    }\n    rc = m->xCreate(iArg, aArg, ppTok);\n    assert( rc!=SQLITE_OK || *ppTok );\n    if( rc!=SQLITE_OK ){\n      sqlite3Fts3ErrMsg(pzErr, \"unknown tokenizer\");\n    }else{\n      (*ppTok)->pModule = m; \n    }\n    sqlite3_free((void *)aArg);\n  }\n\n  sqlite3_free(zCopy);\n  return rc;\n}\n\n\n#ifdef SQLITE_TEST\n\n#if defined(INCLUDE_SQLITE_TCL_H)\n#  include \"sqlite_tcl.h\"\n#else\n#  include \"tcl.h\"\n#endif\n/* #include <string.h> */\n\n/*\n** Implementation of a special SQL scalar function for testing tokenizers \n** designed to be used in concert with the Tcl testing framework. This\n** function must be called with two or more arguments:\n**\n**   SELECT <function-name>(<key-name>, ..., <input-string>);\n**\n** where <function-name> is the name passed as the second argument\n** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')\n** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').\n**\n** The return value is a string that may be interpreted as a Tcl\n** list. For each token in the <input-string>, three elements are\n** added to the returned list. The first is the token position, the \n** second is the token text (folded, stemmed, etc.) and the third is the\n** substring of <input-string> associated with the token. For example, \n** using the built-in \"simple\" tokenizer:\n**\n**   SELECT fts_tokenizer_test('simple', 'I don't see how');\n**\n** will return the string:\n**\n**   \"{0 i I 1 dont don't 2 see see 3 how how}\"\n**   \n*/\nstatic void testFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  Fts3Hash *pHash;\n  sqlite3_tokenizer_module *p;\n  sqlite3_tokenizer *pTokenizer = 0;\n  sqlite3_tokenizer_cursor *pCsr = 0;\n\n  const char *zErr = 0;\n\n  const char *zName;\n  int nName;\n  const char *zInput;\n  int nInput;\n\n  const char *azArg[64];\n\n  const char *zToken;\n  int nToken = 0;\n  int iStart = 0;\n  int iEnd = 0;\n  int iPos = 0;\n  int i;\n\n  Tcl_Obj *pRet;\n\n  if( argc<2 ){\n    sqlite3_result_error(context, \"insufficient arguments\", -1);\n    return;\n  }\n\n  nName = sqlite3_value_bytes(argv[0]);\n  zName = (const char *)sqlite3_value_text(argv[0]);\n  nInput = sqlite3_value_bytes(argv[argc-1]);\n  zInput = (const char *)sqlite3_value_text(argv[argc-1]);\n\n  pHash = (Fts3Hash *)sqlite3_user_data(context);\n  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);\n\n  if( !p ){\n    char *zErr2 = sqlite3_mprintf(\"unknown tokenizer: %s\", zName);\n    sqlite3_result_error(context, zErr2, -1);\n    sqlite3_free(zErr2);\n    return;\n  }\n\n  pRet = Tcl_NewObj();\n  Tcl_IncrRefCount(pRet);\n\n  for(i=1; i<argc-1; i++){\n    azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);\n  }\n\n  if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){\n    zErr = \"error in xCreate()\";\n    goto finish;\n  }\n  pTokenizer->pModule = p;\n  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){\n    zErr = \"error in xOpen()\";\n    goto finish;\n  }\n\n  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){\n    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));\n    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));\n    zToken = &zInput[iStart];\n    nToken = iEnd-iStart;\n    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));\n  }\n\n  if( SQLITE_OK!=p->xClose(pCsr) ){\n    zErr = \"error in xClose()\";\n    goto finish;\n  }\n  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){\n    zErr = \"error in xDestroy()\";\n    goto finish;\n  }\n\nfinish:\n  if( zErr ){\n    sqlite3_result_error(context, zErr, -1);\n  }else{\n    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);\n  }\n  Tcl_DecrRefCount(pRet);\n}\n\nstatic\nint registerTokenizer(\n  sqlite3 *db, \n  char *zName, \n  const sqlite3_tokenizer_module *p\n){\n  int rc;\n  sqlite3_stmt *pStmt;\n  const char zSql[] = \"SELECT fts3_tokenizer(?, ?)\";\n\n  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);\n  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);\n  sqlite3_step(pStmt);\n\n  return sqlite3_finalize(pStmt);\n}\n\n\nstatic\nint queryTokenizer(\n  sqlite3 *db, \n  char *zName,  \n  const sqlite3_tokenizer_module **pp\n){\n  int rc;\n  sqlite3_stmt *pStmt;\n  const char zSql[] = \"SELECT fts3_tokenizer(?)\";\n\n  *pp = 0;\n  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);\n  if( SQLITE_ROW==sqlite3_step(pStmt) ){\n    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB\n     && sqlite3_column_bytes(pStmt, 0)==sizeof(*pp)\n    ){\n      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));\n    }\n  }\n\n  return sqlite3_finalize(pStmt);\n}\n\nSQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);\n\n/*\n** Implementation of the scalar function fts3_tokenizer_internal_test().\n** This function is used for testing only, it is not included in the\n** build unless SQLITE_TEST is defined.\n**\n** The purpose of this is to test that the fts3_tokenizer() function\n** can be used as designed by the C-code in the queryTokenizer and\n** registerTokenizer() functions above. These two functions are repeated\n** in the README.tokenizer file as an example, so it is important to\n** test them.\n**\n** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar\n** function with no arguments. An assert() will fail if a problem is\n** detected. i.e.:\n**\n**     SELECT fts3_tokenizer_internal_test();\n**\n*/\nstatic void intTestFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  int rc;\n  const sqlite3_tokenizer_module *p1;\n  const sqlite3_tokenizer_module *p2;\n  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);\n\n  UNUSED_PARAMETER(argc);\n  UNUSED_PARAMETER(argv);\n\n  /* Test the query function */\n  sqlite3Fts3SimpleTokenizerModule(&p1);\n  rc = queryTokenizer(db, \"simple\", &p2);\n  assert( rc==SQLITE_OK );\n  assert( p1==p2 );\n  rc = queryTokenizer(db, \"nosuchtokenizer\", &p2);\n  assert( rc==SQLITE_ERROR );\n  assert( p2==0 );\n  assert( 0==strcmp(sqlite3_errmsg(db), \"unknown tokenizer: nosuchtokenizer\") );\n\n  /* Test the storage function */\n  if( fts3TokenizerEnabled(context) ){\n    rc = registerTokenizer(db, \"nosuchtokenizer\", p1);\n    assert( rc==SQLITE_OK );\n    rc = queryTokenizer(db, \"nosuchtokenizer\", &p2);\n    assert( rc==SQLITE_OK );\n    assert( p2==p1 );\n  }\n\n  sqlite3_result_text(context, \"ok\", -1, SQLITE_STATIC);\n}\n\n#endif\n\n/*\n** Set up SQL objects in database db used to access the contents of\n** the hash table pointed to by argument pHash. The hash table must\n** been initialized to use string keys, and to take a private copy \n** of the key when a value is inserted. i.e. by a call similar to:\n**\n**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);\n**\n** This function adds a scalar function (see header comment above\n** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is\n** defined at compilation time, a temporary virtual table (see header \n** comment above struct HashTableVtab) to the database schema. Both \n** provide read/write access to the contents of *pHash.\n**\n** The third argument to this function, zName, is used as the name\n** of both the scalar and, if created, the virtual table.\n*/\nSQLITE_PRIVATE int sqlite3Fts3InitHashTable(\n  sqlite3 *db, \n  Fts3Hash *pHash, \n  const char *zName\n){\n  int rc = SQLITE_OK;\n  void *p = (void *)pHash;\n  const int any = SQLITE_UTF8|SQLITE_DIRECTONLY;\n\n#ifdef SQLITE_TEST\n  char *zTest = 0;\n  char *zTest2 = 0;\n  void *pdb = (void *)db;\n  zTest = sqlite3_mprintf(\"%s_test\", zName);\n  zTest2 = sqlite3_mprintf(\"%s_internal_test\", zName);\n  if( !zTest || !zTest2 ){\n    rc = SQLITE_NOMEM;\n  }\n#endif\n\n  if( SQLITE_OK==rc ){\n    rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);\n  }\n  if( SQLITE_OK==rc ){\n    rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);\n  }\n#ifdef SQLITE_TEST\n  if( SQLITE_OK==rc ){\n    rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);\n  }\n  if( SQLITE_OK==rc ){\n    rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);\n  }\n#endif\n\n#ifdef SQLITE_TEST\n  sqlite3_free(zTest);\n  sqlite3_free(zTest2);\n#endif\n\n  return rc;\n}\n\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n\n/************** End of fts3_tokenizer.c **************************************/\n/************** Begin file fts3_tokenizer1.c *********************************/\n/*\n** 2006 Oct 10\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** Implementation of the \"simple\" full-text-search tokenizer.\n*/\n\n/*\n** The code in this file is only compiled if:\n**\n**     * The FTS3 module is being built as an extension\n**       (in which case SQLITE_CORE is not defined), or\n**\n**     * The FTS3 module is being built into the core of\n**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).\n*/\n/* #include \"fts3Int.h\" */\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <assert.h> */\n/* #include <stdlib.h> */\n/* #include <stdio.h> */\n/* #include <string.h> */\n\n/* #include \"fts3_tokenizer.h\" */\n\ntypedef struct simple_tokenizer {\n  sqlite3_tokenizer base;\n  char delim[128];             /* flag ASCII delimiters */\n} simple_tokenizer;\n\ntypedef struct simple_tokenizer_cursor {\n  sqlite3_tokenizer_cursor base;\n  const char *pInput;          /* input we are tokenizing */\n  int nBytes;                  /* size of the input */\n  int iOffset;                 /* current position in pInput */\n  int iToken;                  /* index of next token to be returned */\n  char *pToken;                /* storage for current token */\n  int nTokenAllocated;         /* space allocated to zToken buffer */\n} simple_tokenizer_cursor;\n\n\nstatic int simpleDelim(simple_tokenizer *t, unsigned char c){\n  return c<0x80 && t->delim[c];\n}\nstatic int fts3_isalnum(int x){\n  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');\n}\n\n/*\n** Create a new tokenizer instance.\n*/\nstatic int simpleCreate(\n  int argc, const char * const *argv,\n  sqlite3_tokenizer **ppTokenizer\n){\n  simple_tokenizer *t;\n\n  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));\n  if( t==NULL ) return SQLITE_NOMEM;\n  memset(t, 0, sizeof(*t));\n\n  /* TODO(shess) Delimiters need to remain the same from run to run,\n  ** else we need to reindex.  One solution would be a meta-table to\n  ** track such information in the database, then we'd only want this\n  ** information on the initial create.\n  */\n  if( argc>1 ){\n    int i, n = (int)strlen(argv[1]);\n    for(i=0; i<n; i++){\n      unsigned char ch = argv[1][i];\n      /* We explicitly don't support UTF-8 delimiters for now. */\n      if( ch>=0x80 ){\n        sqlite3_free(t);\n        return SQLITE_ERROR;\n      }\n      t->delim[ch] = 1;\n    }\n  } else {\n    /* Mark non-alphanumeric ASCII characters as delimiters */\n    int i;\n    for(i=1; i<0x80; i++){\n      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;\n    }\n  }\n\n  *ppTokenizer = &t->base;\n  return SQLITE_OK;\n}\n\n/*\n** Destroy a tokenizer\n*/\nstatic int simpleDestroy(sqlite3_tokenizer *pTokenizer){\n  sqlite3_free(pTokenizer);\n  return SQLITE_OK;\n}\n\n/*\n** Prepare to begin tokenizing a particular string.  The input\n** string to be tokenized is pInput[0..nBytes-1].  A cursor\n** used to incrementally tokenize this string is returned in \n** *ppCursor.\n*/\nstatic int simpleOpen(\n  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */\n  const char *pInput, int nBytes,        /* String to be tokenized */\n  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */\n){\n  simple_tokenizer_cursor *c;\n\n  UNUSED_PARAMETER(pTokenizer);\n\n  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));\n  if( c==NULL ) return SQLITE_NOMEM;\n\n  c->pInput = pInput;\n  if( pInput==0 ){\n    c->nBytes = 0;\n  }else if( nBytes<0 ){\n    c->nBytes = (int)strlen(pInput);\n  }else{\n    c->nBytes = nBytes;\n  }\n  c->iOffset = 0;                 /* start tokenizing at the beginning */\n  c->iToken = 0;\n  c->pToken = NULL;               /* no space allocated, yet. */\n  c->nTokenAllocated = 0;\n\n  *ppCursor = &c->base;\n  return SQLITE_OK;\n}\n\n/*\n** Close a tokenization cursor previously opened by a call to\n** simpleOpen() above.\n*/\nstatic int simpleClose(sqlite3_tokenizer_cursor *pCursor){\n  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;\n  sqlite3_free(c->pToken);\n  sqlite3_free(c);\n  return SQLITE_OK;\n}\n\n/*\n** Extract the next token from a tokenization cursor.  The cursor must\n** have been opened by a prior call to simpleOpen().\n*/\nstatic int simpleNext(\n  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */\n  const char **ppToken,               /* OUT: *ppToken is the token text */\n  int *pnBytes,                       /* OUT: Number of bytes in token */\n  int *piStartOffset,                 /* OUT: Starting offset of token */\n  int *piEndOffset,                   /* OUT: Ending offset of token */\n  int *piPosition                     /* OUT: Position integer of token */\n){\n  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;\n  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;\n  unsigned char *p = (unsigned char *)c->pInput;\n\n  while( c->iOffset<c->nBytes ){\n    int iStartOffset;\n\n    /* Scan past delimiter characters */\n    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){\n      c->iOffset++;\n    }\n\n    /* Count non-delimiter characters. */\n    iStartOffset = c->iOffset;\n    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){\n      c->iOffset++;\n    }\n\n    if( c->iOffset>iStartOffset ){\n      int i, n = c->iOffset-iStartOffset;\n      if( n>c->nTokenAllocated ){\n        char *pNew;\n        c->nTokenAllocated = n+20;\n        pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);\n        if( !pNew ) return SQLITE_NOMEM;\n        c->pToken = pNew;\n      }\n      for(i=0; i<n; i++){\n        /* TODO(shess) This needs expansion to handle UTF-8\n        ** case-insensitivity.\n        */\n        unsigned char ch = p[iStartOffset+i];\n        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);\n      }\n      *ppToken = c->pToken;\n      *pnBytes = n;\n      *piStartOffset = iStartOffset;\n      *piEndOffset = c->iOffset;\n      *piPosition = c->iToken++;\n\n      return SQLITE_OK;\n    }\n  }\n  return SQLITE_DONE;\n}\n\n/*\n** The set of routines that implement the simple tokenizer\n*/\nstatic const sqlite3_tokenizer_module simpleTokenizerModule = {\n  0,\n  simpleCreate,\n  simpleDestroy,\n  simpleOpen,\n  simpleClose,\n  simpleNext,\n  0,\n};\n\n/*\n** Allocate a new simple tokenizer.  Return a pointer to the new\n** tokenizer in *ppModule\n*/\nSQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(\n  sqlite3_tokenizer_module const**ppModule\n){\n  *ppModule = &simpleTokenizerModule;\n}\n\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n\n/************** End of fts3_tokenizer1.c *************************************/\n/************** Begin file fts3_tokenize_vtab.c ******************************/\n/*\n** 2013 Apr 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains code for the \"fts3tokenize\" virtual table module.\n** An fts3tokenize virtual table is created as follows:\n**\n**   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(\n**       <tokenizer-name>, <arg-1>, ...\n**   );\n**\n** The table created has the following schema:\n**\n**   CREATE TABLE <tbl>(input, token, start, end, position)\n**\n** When queried, the query must include a WHERE clause of type:\n**\n**   input = <string>\n**\n** The virtual table module tokenizes this <string>, using the FTS3 \n** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE \n** statement and returns one row for each token in the result. With\n** fields set as follows:\n**\n**   input:   Always set to a copy of <string>\n**   token:   A token from the input.\n**   start:   Byte offset of the token within the input <string>.\n**   end:     Byte offset of the byte immediately following the end of the\n**            token within the input string.\n**   pos:     Token offset of token within input.\n**\n*/\n/* #include \"fts3Int.h\" */\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <string.h> */\n/* #include <assert.h> */\n\ntypedef struct Fts3tokTable Fts3tokTable;\ntypedef struct Fts3tokCursor Fts3tokCursor;\n\n/*\n** Virtual table structure.\n*/\nstruct Fts3tokTable {\n  sqlite3_vtab base;              /* Base class used by SQLite core */\n  const sqlite3_tokenizer_module *pMod;\n  sqlite3_tokenizer *pTok;\n};\n\n/*\n** Virtual table cursor structure.\n*/\nstruct Fts3tokCursor {\n  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */\n  char *zInput;                   /* Input string */\n  sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */\n  int iRowid;                     /* Current 'rowid' value */\n  const char *zToken;             /* Current 'token' value */\n  int nToken;                     /* Size of zToken in bytes */\n  int iStart;                     /* Current 'start' value */\n  int iEnd;                       /* Current 'end' value */\n  int iPos;                       /* Current 'pos' value */\n};\n\n/*\n** Query FTS for the tokenizer implementation named zName.\n*/\nstatic int fts3tokQueryTokenizer(\n  Fts3Hash *pHash,\n  const char *zName,\n  const sqlite3_tokenizer_module **pp,\n  char **pzErr\n){\n  sqlite3_tokenizer_module *p;\n  int nName = (int)strlen(zName);\n\n  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);\n  if( !p ){\n    sqlite3Fts3ErrMsg(pzErr, \"unknown tokenizer: %s\", zName);\n    return SQLITE_ERROR;\n  }\n\n  *pp = p;\n  return SQLITE_OK;\n}\n\n/*\n** The second argument, argv[], is an array of pointers to nul-terminated\n** strings. This function makes a copy of the array and strings into a \n** single block of memory. It then dequotes any of the strings that appear\n** to be quoted.\n**\n** If successful, output parameter *pazDequote is set to point at the\n** array of dequoted strings and SQLITE_OK is returned. The caller is\n** responsible for eventually calling sqlite3_free() to free the array\n** in this case. Or, if an error occurs, an SQLite error code is returned.\n** The final value of *pazDequote is undefined in this case.\n*/\nstatic int fts3tokDequoteArray(\n  int argc,                       /* Number of elements in argv[] */\n  const char * const *argv,       /* Input array */\n  char ***pazDequote              /* Output array */\n){\n  int rc = SQLITE_OK;             /* Return code */\n  if( argc==0 ){\n    *pazDequote = 0;\n  }else{\n    int i;\n    int nByte = 0;\n    char **azDequote;\n\n    for(i=0; i<argc; i++){\n      nByte += (int)(strlen(argv[i]) + 1);\n    }\n\n    *pazDequote = azDequote = sqlite3_malloc64(sizeof(char *)*argc + nByte);\n    if( azDequote==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      char *pSpace = (char *)&azDequote[argc];\n      for(i=0; i<argc; i++){\n        int n = (int)strlen(argv[i]);\n        azDequote[i] = pSpace;\n        memcpy(pSpace, argv[i], n+1);\n        sqlite3Fts3Dequote(pSpace);\n        pSpace += (n+1);\n      }\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Schema of the tokenizer table.\n*/\n#define FTS3_TOK_SCHEMA \"CREATE TABLE x(input, token, start, end, position)\"\n\n/*\n** This function does all the work for both the xConnect and xCreate methods.\n** These tables have no persistent representation of their own, so xConnect\n** and xCreate are identical operations.\n**\n**   argv[0]: module name\n**   argv[1]: database name \n**   argv[2]: table name\n**   argv[3]: first argument (tokenizer name)\n*/\nstatic int fts3tokConnectMethod(\n  sqlite3 *db,                    /* Database connection */\n  void *pHash,                    /* Hash table of tokenizers */\n  int argc,                       /* Number of elements in argv array */\n  const char * const *argv,       /* xCreate/xConnect argument array */\n  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */\n  char **pzErr                    /* OUT: sqlite3_malloc'd error message */\n){\n  Fts3tokTable *pTab = 0;\n  const sqlite3_tokenizer_module *pMod = 0;\n  sqlite3_tokenizer *pTok = 0;\n  int rc;\n  char **azDequote = 0;\n  int nDequote;\n\n  rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);\n  if( rc!=SQLITE_OK ) return rc;\n\n  nDequote = argc-3;\n  rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);\n\n  if( rc==SQLITE_OK ){\n    const char *zModule;\n    if( nDequote<1 ){\n      zModule = \"simple\";\n    }else{\n      zModule = azDequote[0];\n    }\n    rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);\n  }\n\n  assert( (rc==SQLITE_OK)==(pMod!=0) );\n  if( rc==SQLITE_OK ){\n    const char * const *azArg = (const char * const *)&azDequote[1];\n    rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);\n  }\n\n  if( rc==SQLITE_OK ){\n    pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));\n    if( pTab==0 ){\n      rc = SQLITE_NOMEM;\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    memset(pTab, 0, sizeof(Fts3tokTable));\n    pTab->pMod = pMod;\n    pTab->pTok = pTok;\n    *ppVtab = &pTab->base;\n  }else{\n    if( pTok ){\n      pMod->xDestroy(pTok);\n    }\n  }\n\n  sqlite3_free(azDequote);\n  return rc;\n}\n\n/*\n** This function does the work for both the xDisconnect and xDestroy methods.\n** These tables have no persistent representation of their own, so xDisconnect\n** and xDestroy are identical operations.\n*/\nstatic int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){\n  Fts3tokTable *pTab = (Fts3tokTable *)pVtab;\n\n  pTab->pMod->xDestroy(pTab->pTok);\n  sqlite3_free(pTab);\n  return SQLITE_OK;\n}\n\n/*\n** xBestIndex - Analyze a WHERE and ORDER BY clause.\n*/\nstatic int fts3tokBestIndexMethod(\n  sqlite3_vtab *pVTab, \n  sqlite3_index_info *pInfo\n){\n  int i;\n  UNUSED_PARAMETER(pVTab);\n\n  for(i=0; i<pInfo->nConstraint; i++){\n    if( pInfo->aConstraint[i].usable \n     && pInfo->aConstraint[i].iColumn==0 \n     && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ \n    ){\n      pInfo->idxNum = 1;\n      pInfo->aConstraintUsage[i].argvIndex = 1;\n      pInfo->aConstraintUsage[i].omit = 1;\n      pInfo->estimatedCost = 1;\n      return SQLITE_OK;\n    }\n  }\n\n  pInfo->idxNum = 0;\n  assert( pInfo->estimatedCost>1000000.0 );\n\n  return SQLITE_OK;\n}\n\n/*\n** xOpen - Open a cursor.\n*/\nstatic int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){\n  Fts3tokCursor *pCsr;\n  UNUSED_PARAMETER(pVTab);\n\n  pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));\n  if( pCsr==0 ){\n    return SQLITE_NOMEM;\n  }\n  memset(pCsr, 0, sizeof(Fts3tokCursor));\n\n  *ppCsr = (sqlite3_vtab_cursor *)pCsr;\n  return SQLITE_OK;\n}\n\n/*\n** Reset the tokenizer cursor passed as the only argument. As if it had\n** just been returned by fts3tokOpenMethod().\n*/\nstatic void fts3tokResetCursor(Fts3tokCursor *pCsr){\n  if( pCsr->pCsr ){\n    Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);\n    pTab->pMod->xClose(pCsr->pCsr);\n    pCsr->pCsr = 0;\n  }\n  sqlite3_free(pCsr->zInput);\n  pCsr->zInput = 0;\n  pCsr->zToken = 0;\n  pCsr->nToken = 0;\n  pCsr->iStart = 0;\n  pCsr->iEnd = 0;\n  pCsr->iPos = 0;\n  pCsr->iRowid = 0;\n}\n\n/*\n** xClose - Close a cursor.\n*/\nstatic int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){\n  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;\n\n  fts3tokResetCursor(pCsr);\n  sqlite3_free(pCsr);\n  return SQLITE_OK;\n}\n\n/*\n** xNext - Advance the cursor to the next row, if any.\n*/\nstatic int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){\n  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;\n  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);\n  int rc;                         /* Return code */\n\n  pCsr->iRowid++;\n  rc = pTab->pMod->xNext(pCsr->pCsr,\n      &pCsr->zToken, &pCsr->nToken,\n      &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos\n  );\n\n  if( rc!=SQLITE_OK ){\n    fts3tokResetCursor(pCsr);\n    if( rc==SQLITE_DONE ) rc = SQLITE_OK;\n  }\n\n  return rc;\n}\n\n/*\n** xFilter - Initialize a cursor to point at the start of its data.\n*/\nstatic int fts3tokFilterMethod(\n  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */\n  int idxNum,                     /* Strategy index */\n  const char *idxStr,             /* Unused */\n  int nVal,                       /* Number of elements in apVal */\n  sqlite3_value **apVal           /* Arguments for the indexing scheme */\n){\n  int rc = SQLITE_ERROR;\n  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;\n  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);\n  UNUSED_PARAMETER(idxStr);\n  UNUSED_PARAMETER(nVal);\n\n  fts3tokResetCursor(pCsr);\n  if( idxNum==1 ){\n    const char *zByte = (const char *)sqlite3_value_text(apVal[0]);\n    int nByte = sqlite3_value_bytes(apVal[0]);\n    pCsr->zInput = sqlite3_malloc64(nByte+1);\n    if( pCsr->zInput==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      if( nByte>0 ) memcpy(pCsr->zInput, zByte, nByte);\n      pCsr->zInput[nByte] = 0;\n      rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);\n      if( rc==SQLITE_OK ){\n        pCsr->pCsr->pTokenizer = pTab->pTok;\n      }\n    }\n  }\n\n  if( rc!=SQLITE_OK ) return rc;\n  return fts3tokNextMethod(pCursor);\n}\n\n/*\n** xEof - Return true if the cursor is at EOF, or false otherwise.\n*/\nstatic int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){\n  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;\n  return (pCsr->zToken==0);\n}\n\n/*\n** xColumn - Return a column value.\n*/\nstatic int fts3tokColumnMethod(\n  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */\n  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */\n  int iCol                        /* Index of column to read value from */\n){\n  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;\n\n  /* CREATE TABLE x(input, token, start, end, position) */\n  switch( iCol ){\n    case 0:\n      sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);\n      break;\n    case 1:\n      sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);\n      break;\n    case 2:\n      sqlite3_result_int(pCtx, pCsr->iStart);\n      break;\n    case 3:\n      sqlite3_result_int(pCtx, pCsr->iEnd);\n      break;\n    default:\n      assert( iCol==4 );\n      sqlite3_result_int(pCtx, pCsr->iPos);\n      break;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** xRowid - Return the current rowid for the cursor.\n*/\nstatic int fts3tokRowidMethod(\n  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */\n  sqlite_int64 *pRowid            /* OUT: Rowid value */\n){\n  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;\n  *pRowid = (sqlite3_int64)pCsr->iRowid;\n  return SQLITE_OK;\n}\n\n/*\n** Register the fts3tok module with database connection db. Return SQLITE_OK\n** if successful or an error code if sqlite3_create_module() fails.\n*/\nSQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){\n  static const sqlite3_module fts3tok_module = {\n     0,                           /* iVersion      */\n     fts3tokConnectMethod,        /* xCreate       */\n     fts3tokConnectMethod,        /* xConnect      */\n     fts3tokBestIndexMethod,      /* xBestIndex    */\n     fts3tokDisconnectMethod,     /* xDisconnect   */\n     fts3tokDisconnectMethod,     /* xDestroy      */\n     fts3tokOpenMethod,           /* xOpen         */\n     fts3tokCloseMethod,          /* xClose        */\n     fts3tokFilterMethod,         /* xFilter       */\n     fts3tokNextMethod,           /* xNext         */\n     fts3tokEofMethod,            /* xEof          */\n     fts3tokColumnMethod,         /* xColumn       */\n     fts3tokRowidMethod,          /* xRowid        */\n     0,                           /* xUpdate       */\n     0,                           /* xBegin        */\n     0,                           /* xSync         */\n     0,                           /* xCommit       */\n     0,                           /* xRollback     */\n     0,                           /* xFindFunction */\n     0,                           /* xRename       */\n     0,                           /* xSavepoint    */\n     0,                           /* xRelease      */\n     0,                           /* xRollbackTo   */\n     0                            /* xShadowName   */\n  };\n  int rc;                         /* Return code */\n\n  rc = sqlite3_create_module(db, \"fts3tokenize\", &fts3tok_module, (void*)pHash);\n  return rc;\n}\n\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n\n/************** End of fts3_tokenize_vtab.c **********************************/\n/************** Begin file fts3_write.c **************************************/\n/*\n** 2009 Oct 23\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file is part of the SQLite FTS3 extension module. Specifically,\n** this file contains code to insert, update and delete rows from FTS3\n** tables. It also contains code to merge FTS3 b-tree segments. Some\n** of the sub-routines used to merge segments are also used by the query \n** code in fts3.c.\n*/\n\n/* #include \"fts3Int.h\" */\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <string.h> */\n/* #include <assert.h> */\n/* #include <stdlib.h> */\n/* #include <stdio.h> */\n\n#define FTS_MAX_APPENDABLE_HEIGHT 16\n\n/*\n** When full-text index nodes are loaded from disk, the buffer that they\n** are loaded into has the following number of bytes of padding at the end \n** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer\n** of 920 bytes is allocated for it.\n**\n** This means that if we have a pointer into a buffer containing node data,\n** it is always safe to read up to two varints from it without risking an\n** overread, even if the node data is corrupted.\n*/\n#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)\n\n/*\n** Under certain circumstances, b-tree nodes (doclists) can be loaded into\n** memory incrementally instead of all at once. This can be a big performance\n** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()\n** method before retrieving all query results (as may happen, for example,\n** if a query has a LIMIT clause).\n**\n** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD \n** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.\n** The code is written so that the hard lower-limit for each of these values \n** is 1. Clearly such small values would be inefficient, but can be useful \n** for testing purposes.\n**\n** If this module is built with SQLITE_TEST defined, these constants may\n** be overridden at runtime for testing purposes. File fts3_test.c contains\n** a Tcl interface to read and write the values.\n*/\n#ifdef SQLITE_TEST\nint test_fts3_node_chunksize = (4*1024);\nint test_fts3_node_chunk_threshold = (4*1024)*4;\n# define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize\n# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold\n#else\n# define FTS3_NODE_CHUNKSIZE (4*1024) \n# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)\n#endif\n\n/*\n** The values that may be meaningfully bound to the :1 parameter in\n** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.\n*/\n#define FTS_STAT_DOCTOTAL      0\n#define FTS_STAT_INCRMERGEHINT 1\n#define FTS_STAT_AUTOINCRMERGE 2\n\n/*\n** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic\n** and incremental merge operation that takes place. This is used for \n** debugging FTS only, it should not usually be turned on in production\n** systems.\n*/\n#ifdef FTS3_LOG_MERGES\nstatic void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){\n  sqlite3_log(SQLITE_OK, \"%d-way merge from level %d\", nMerge, (int)iAbsLevel);\n}\n#else\n#define fts3LogMerge(x, y)\n#endif\n\n\ntypedef struct PendingList PendingList;\ntypedef struct SegmentNode SegmentNode;\ntypedef struct SegmentWriter SegmentWriter;\n\n/*\n** An instance of the following data structure is used to build doclists\n** incrementally. See function fts3PendingListAppend() for details.\n*/\nstruct PendingList {\n  int nData;\n  char *aData;\n  int nSpace;\n  sqlite3_int64 iLastDocid;\n  sqlite3_int64 iLastCol;\n  sqlite3_int64 iLastPos;\n};\n\n\n/*\n** Each cursor has a (possibly empty) linked list of the following objects.\n*/\nstruct Fts3DeferredToken {\n  Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */\n  int iCol;                       /* Column token must occur in */\n  Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */\n  PendingList *pList;             /* Doclist is assembled here */\n};\n\n/*\n** An instance of this structure is used to iterate through the terms on\n** a contiguous set of segment b-tree leaf nodes. Although the details of\n** this structure are only manipulated by code in this file, opaque handles\n** of type Fts3SegReader* are also used by code in fts3.c to iterate through\n** terms when querying the full-text index. See functions:\n**\n**   sqlite3Fts3SegReaderNew()\n**   sqlite3Fts3SegReaderFree()\n**   sqlite3Fts3SegReaderIterate()\n**\n** Methods used to manipulate Fts3SegReader structures:\n**\n**   fts3SegReaderNext()\n**   fts3SegReaderFirstDocid()\n**   fts3SegReaderNextDocid()\n*/\nstruct Fts3SegReader {\n  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */\n  u8 bLookup;                     /* True for a lookup only */\n  u8 rootOnly;                    /* True for a root-only reader */\n\n  sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */\n  sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */\n  sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */\n  sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */\n\n  char *aNode;                    /* Pointer to node data (or NULL) */\n  int nNode;                      /* Size of buffer at aNode (or 0) */\n  int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */\n  sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */\n\n  Fts3HashElem **ppNextElem;\n\n  /* Variables set by fts3SegReaderNext(). These may be read directly\n  ** by the caller. They are valid from the time SegmentReaderNew() returns\n  ** until SegmentReaderNext() returns something other than SQLITE_OK\n  ** (i.e. SQLITE_DONE).\n  */\n  int nTerm;                      /* Number of bytes in current term */\n  char *zTerm;                    /* Pointer to current term */\n  int nTermAlloc;                 /* Allocated size of zTerm buffer */\n  char *aDoclist;                 /* Pointer to doclist of current entry */\n  int nDoclist;                   /* Size of doclist in current entry */\n\n  /* The following variables are used by fts3SegReaderNextDocid() to iterate \n  ** through the current doclist (aDoclist/nDoclist).\n  */\n  char *pOffsetList;\n  int nOffsetList;                /* For descending pending seg-readers only */\n  sqlite3_int64 iDocid;\n};\n\n#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)\n#define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)\n\n/*\n** An instance of this structure is used to create a segment b-tree in the\n** database. The internal details of this type are only accessed by the\n** following functions:\n**\n**   fts3SegWriterAdd()\n**   fts3SegWriterFlush()\n**   fts3SegWriterFree()\n*/\nstruct SegmentWriter {\n  SegmentNode *pTree;             /* Pointer to interior tree structure */\n  sqlite3_int64 iFirst;           /* First slot in %_segments written */\n  sqlite3_int64 iFree;            /* Next free slot in %_segments */\n  char *zTerm;                    /* Pointer to previous term buffer */\n  int nTerm;                      /* Number of bytes in zTerm */\n  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */\n  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */\n  int nSize;                      /* Size of allocation at aData */\n  int nData;                      /* Bytes of data in aData */\n  char *aData;                    /* Pointer to block from malloc() */\n  i64 nLeafData;                  /* Number of bytes of leaf data written */\n};\n\n/*\n** Type SegmentNode is used by the following three functions to create\n** the interior part of the segment b+-tree structures (everything except\n** the leaf nodes). These functions and type are only ever used by code\n** within the fts3SegWriterXXX() family of functions described above.\n**\n**   fts3NodeAddTerm()\n**   fts3NodeWrite()\n**   fts3NodeFree()\n**\n** When a b+tree is written to the database (either as a result of a merge\n** or the pending-terms table being flushed), leaves are written into the \n** database file as soon as they are completely populated. The interior of\n** the tree is assembled in memory and written out only once all leaves have\n** been populated and stored. This is Ok, as the b+-tree fanout is usually\n** very large, meaning that the interior of the tree consumes relatively \n** little memory.\n*/\nstruct SegmentNode {\n  SegmentNode *pParent;           /* Parent node (or NULL for root node) */\n  SegmentNode *pRight;            /* Pointer to right-sibling */\n  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */\n  int nEntry;                     /* Number of terms written to node so far */\n  char *zTerm;                    /* Pointer to previous term buffer */\n  int nTerm;                      /* Number of bytes in zTerm */\n  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */\n  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */\n  int nData;                      /* Bytes of valid data so far */\n  char *aData;                    /* Node data */\n};\n\n/*\n** Valid values for the second argument to fts3SqlStmt().\n*/\n#define SQL_DELETE_CONTENT             0\n#define SQL_IS_EMPTY                   1\n#define SQL_DELETE_ALL_CONTENT         2 \n#define SQL_DELETE_ALL_SEGMENTS        3\n#define SQL_DELETE_ALL_SEGDIR          4\n#define SQL_DELETE_ALL_DOCSIZE         5\n#define SQL_DELETE_ALL_STAT            6\n#define SQL_SELECT_CONTENT_BY_ROWID    7\n#define SQL_NEXT_SEGMENT_INDEX         8\n#define SQL_INSERT_SEGMENTS            9\n#define SQL_NEXT_SEGMENTS_ID          10\n#define SQL_INSERT_SEGDIR             11\n#define SQL_SELECT_LEVEL              12\n#define SQL_SELECT_LEVEL_RANGE        13\n#define SQL_SELECT_LEVEL_COUNT        14\n#define SQL_SELECT_SEGDIR_MAX_LEVEL   15\n#define SQL_DELETE_SEGDIR_LEVEL       16\n#define SQL_DELETE_SEGMENTS_RANGE     17\n#define SQL_CONTENT_INSERT            18\n#define SQL_DELETE_DOCSIZE            19\n#define SQL_REPLACE_DOCSIZE           20\n#define SQL_SELECT_DOCSIZE            21\n#define SQL_SELECT_STAT               22\n#define SQL_REPLACE_STAT              23\n\n#define SQL_SELECT_ALL_PREFIX_LEVEL   24\n#define SQL_DELETE_ALL_TERMS_SEGDIR   25\n#define SQL_DELETE_SEGDIR_RANGE       26\n#define SQL_SELECT_ALL_LANGID         27\n#define SQL_FIND_MERGE_LEVEL          28\n#define SQL_MAX_LEAF_NODE_ESTIMATE    29\n#define SQL_DELETE_SEGDIR_ENTRY       30\n#define SQL_SHIFT_SEGDIR_ENTRY        31\n#define SQL_SELECT_SEGDIR             32\n#define SQL_CHOMP_SEGDIR              33\n#define SQL_SEGMENT_IS_APPENDABLE     34\n#define SQL_SELECT_INDEXES            35\n#define SQL_SELECT_MXLEVEL            36\n\n#define SQL_SELECT_LEVEL_RANGE2       37\n#define SQL_UPDATE_LEVEL_IDX          38\n#define SQL_UPDATE_LEVEL              39\n\n/*\n** This function is used to obtain an SQLite prepared statement handle\n** for the statement identified by the second argument. If successful,\n** *pp is set to the requested statement handle and SQLITE_OK returned.\n** Otherwise, an SQLite error code is returned and *pp is set to 0.\n**\n** If argument apVal is not NULL, then it must point to an array with\n** at least as many entries as the requested statement has bound \n** parameters. The values are bound to the statements parameters before\n** returning.\n*/\nstatic int fts3SqlStmt(\n  Fts3Table *p,                   /* Virtual table handle */\n  int eStmt,                      /* One of the SQL_XXX constants above */\n  sqlite3_stmt **pp,              /* OUT: Statement handle */\n  sqlite3_value **apVal           /* Values to bind to statement */\n){\n  const char *azSql[] = {\n/* 0  */  \"DELETE FROM %Q.'%q_content' WHERE rowid = ?\",\n/* 1  */  \"SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)\",\n/* 2  */  \"DELETE FROM %Q.'%q_content'\",\n/* 3  */  \"DELETE FROM %Q.'%q_segments'\",\n/* 4  */  \"DELETE FROM %Q.'%q_segdir'\",\n/* 5  */  \"DELETE FROM %Q.'%q_docsize'\",\n/* 6  */  \"DELETE FROM %Q.'%q_stat'\",\n/* 7  */  \"SELECT %s WHERE rowid=?\",\n/* 8  */  \"SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1\",\n/* 9  */  \"REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)\",\n/* 10 */  \"SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)\",\n/* 11 */  \"REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)\",\n\n          /* Return segments in order from oldest to newest.*/ \n/* 12 */  \"SELECT idx, start_block, leaves_end_block, end_block, root \"\n            \"FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC\",\n/* 13 */  \"SELECT idx, start_block, leaves_end_block, end_block, root \"\n            \"FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?\"\n            \"ORDER BY level DESC, idx ASC\",\n\n/* 14 */  \"SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?\",\n/* 15 */  \"SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?\",\n\n/* 16 */  \"DELETE FROM %Q.'%q_segdir' WHERE level = ?\",\n/* 17 */  \"DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?\",\n/* 18 */  \"INSERT INTO %Q.'%q_content' VALUES(%s)\",\n/* 19 */  \"DELETE FROM %Q.'%q_docsize' WHERE docid = ?\",\n/* 20 */  \"REPLACE INTO %Q.'%q_docsize' VALUES(?,?)\",\n/* 21 */  \"SELECT size FROM %Q.'%q_docsize' WHERE docid=?\",\n/* 22 */  \"SELECT value FROM %Q.'%q_stat' WHERE id=?\",\n/* 23 */  \"REPLACE INTO %Q.'%q_stat' VALUES(?,?)\",\n/* 24 */  \"\",\n/* 25 */  \"\",\n\n/* 26 */ \"DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?\",\n/* 27 */ \"SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'\",\n\n/* This statement is used to determine which level to read the input from\n** when performing an incremental merge. It returns the absolute level number\n** of the oldest level in the db that contains at least ? segments. Or,\n** if no level in the FTS index contains more than ? segments, the statement\n** returns zero rows.  */\n/* 28 */ \"SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' \"\n         \"  GROUP BY level HAVING cnt>=?\"\n         \"  ORDER BY (level %% 1024) ASC, 2 DESC LIMIT 1\",\n\n/* Estimate the upper limit on the number of leaf nodes in a new segment\n** created by merging the oldest :2 segments from absolute level :1. See \n** function sqlite3Fts3Incrmerge() for details.  */\n/* 29 */ \"SELECT 2 * total(1 + leaves_end_block - start_block) \"\n         \"  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?\",\n\n/* SQL_DELETE_SEGDIR_ENTRY\n**   Delete the %_segdir entry on absolute level :1 with index :2.  */\n/* 30 */ \"DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?\",\n\n/* SQL_SHIFT_SEGDIR_ENTRY\n**   Modify the idx value for the segment with idx=:3 on absolute level :2\n**   to :1.  */\n/* 31 */ \"UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?\",\n\n/* SQL_SELECT_SEGDIR\n**   Read a single entry from the %_segdir table. The entry from absolute \n**   level :1 with index value :2.  */\n/* 32 */  \"SELECT idx, start_block, leaves_end_block, end_block, root \"\n            \"FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?\",\n\n/* SQL_CHOMP_SEGDIR\n**   Update the start_block (:1) and root (:2) fields of the %_segdir\n**   entry located on absolute level :3 with index :4.  */\n/* 33 */  \"UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?\"\n            \"WHERE level = ? AND idx = ?\",\n\n/* SQL_SEGMENT_IS_APPENDABLE\n**   Return a single row if the segment with end_block=? is appendable. Or\n**   no rows otherwise.  */\n/* 34 */  \"SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL\",\n\n/* SQL_SELECT_INDEXES\n**   Return the list of valid segment indexes for absolute level ?  */\n/* 35 */  \"SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC\",\n\n/* SQL_SELECT_MXLEVEL\n**   Return the largest relative level in the FTS index or indexes.  */\n/* 36 */  \"SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'\",\n\n          /* Return segments in order from oldest to newest.*/ \n/* 37 */  \"SELECT level, idx, end_block \"\n            \"FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? \"\n            \"ORDER BY level DESC, idx ASC\",\n\n          /* Update statements used while promoting segments */\n/* 38 */  \"UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? \"\n            \"WHERE level=? AND idx=?\",\n/* 39 */  \"UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1\"\n\n  };\n  int rc = SQLITE_OK;\n  sqlite3_stmt *pStmt;\n\n  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );\n  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );\n  \n  pStmt = p->aStmt[eStmt];\n  if( !pStmt ){\n    int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;\n    char *zSql;\n    if( eStmt==SQL_CONTENT_INSERT ){\n      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);\n    }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){\n      f &= ~SQLITE_PREPARE_NO_VTAB;\n      zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);\n    }else{\n      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);\n    }\n    if( !zSql ){\n      rc = SQLITE_NOMEM;\n    }else{\n      rc = sqlite3_prepare_v3(p->db, zSql, -1, f, &pStmt, NULL);\n      sqlite3_free(zSql);\n      assert( rc==SQLITE_OK || pStmt==0 );\n      p->aStmt[eStmt] = pStmt;\n    }\n  }\n  if( apVal ){\n    int i;\n    int nParam = sqlite3_bind_parameter_count(pStmt);\n    for(i=0; rc==SQLITE_OK && i<nParam; i++){\n      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);\n    }\n  }\n  *pp = pStmt;\n  return rc;\n}\n\n\nstatic int fts3SelectDocsize(\n  Fts3Table *pTab,                /* FTS3 table handle */\n  sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */\n  sqlite3_stmt **ppStmt           /* OUT: Statement handle */\n){\n  sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */\n  int rc;                         /* Return code */\n\n  rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pStmt, 1, iDocid);\n    rc = sqlite3_step(pStmt);\n    if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){\n      rc = sqlite3_reset(pStmt);\n      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;\n      pStmt = 0;\n    }else{\n      rc = SQLITE_OK;\n    }\n  }\n\n  *ppStmt = pStmt;\n  return rc;\n}\n\nSQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(\n  Fts3Table *pTab,                /* Fts3 table handle */\n  sqlite3_stmt **ppStmt           /* OUT: Statement handle */\n){\n  sqlite3_stmt *pStmt = 0;\n  int rc;\n  rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);\n    if( sqlite3_step(pStmt)!=SQLITE_ROW\n     || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB\n    ){\n      rc = sqlite3_reset(pStmt);\n      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;\n      pStmt = 0;\n    }\n  }\n  *ppStmt = pStmt;\n  return rc;\n}\n\nSQLITE_PRIVATE int sqlite3Fts3SelectDocsize(\n  Fts3Table *pTab,                /* Fts3 table handle */\n  sqlite3_int64 iDocid,           /* Docid to read size data for */\n  sqlite3_stmt **ppStmt           /* OUT: Statement handle */\n){\n  return fts3SelectDocsize(pTab, iDocid, ppStmt);\n}\n\n/*\n** Similar to fts3SqlStmt(). Except, after binding the parameters in\n** array apVal[] to the SQL statement identified by eStmt, the statement\n** is executed.\n**\n** Returns SQLITE_OK if the statement is successfully executed, or an\n** SQLite error code otherwise.\n*/\nstatic void fts3SqlExec(\n  int *pRC,                /* Result code */\n  Fts3Table *p,            /* The FTS3 table */\n  int eStmt,               /* Index of statement to evaluate */\n  sqlite3_value **apVal    /* Parameters to bind */\n){\n  sqlite3_stmt *pStmt;\n  int rc;\n  if( *pRC ) return;\n  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); \n  if( rc==SQLITE_OK ){\n    sqlite3_step(pStmt);\n    rc = sqlite3_reset(pStmt);\n  }\n  *pRC = rc;\n}\n\n\n/*\n** This function ensures that the caller has obtained an exclusive \n** shared-cache table-lock on the %_segdir table. This is required before \n** writing data to the fts3 table. If this lock is not acquired first, then\n** the caller may end up attempting to take this lock as part of committing\n** a transaction, causing SQLite to return SQLITE_LOCKED or \n** LOCKED_SHAREDCACHEto a COMMIT command.\n**\n** It is best to avoid this because if FTS3 returns any error when \n** committing a transaction, the whole transaction will be rolled back. \n** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. \n** It can still happen if the user locks the underlying tables directly \n** instead of accessing them via FTS.\n*/\nstatic int fts3Writelock(Fts3Table *p){\n  int rc = SQLITE_OK;\n  \n  if( p->nPendingData==0 ){\n    sqlite3_stmt *pStmt;\n    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_null(pStmt, 1);\n      sqlite3_step(pStmt);\n      rc = sqlite3_reset(pStmt);\n    }\n  }\n\n  return rc;\n}\n\n/*\n** FTS maintains a separate indexes for each language-id (a 32-bit integer).\n** Within each language id, a separate index is maintained to store the\n** document terms, and each configured prefix size (configured the FTS \n** \"prefix=\" option). And each index consists of multiple levels (\"relative\n** levels\").\n**\n** All three of these values (the language id, the specific index and the\n** level within the index) are encoded in 64-bit integer values stored\n** in the %_segdir table on disk. This function is used to convert three\n** separate component values into the single 64-bit integer value that\n** can be used to query the %_segdir table.\n**\n** Specifically, each language-id/index combination is allocated 1024 \n** 64-bit integer level values (\"absolute levels\"). The main terms index\n** for language-id 0 is allocate values 0-1023. The first prefix index\n** (if any) for language-id 0 is allocated values 1024-2047. And so on.\n** Language 1 indexes are allocated immediately following language 0.\n**\n** So, for a system with nPrefix prefix indexes configured, the block of\n** absolute levels that corresponds to language-id iLangid and index \n** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).\n*/\nstatic sqlite3_int64 getAbsoluteLevel(\n  Fts3Table *p,                   /* FTS3 table handle */\n  int iLangid,                    /* Language id */\n  int iIndex,                     /* Index in p->aIndex[] */\n  int iLevel                      /* Level of segments */\n){\n  sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */\n  assert_fts3_nc( iLangid>=0 );\n  assert( p->nIndex>0 );\n  assert( iIndex>=0 && iIndex<p->nIndex );\n\n  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;\n  return iBase + iLevel;\n}\n\n/*\n** Set *ppStmt to a statement handle that may be used to iterate through\n** all rows in the %_segdir table, from oldest to newest. If successful,\n** return SQLITE_OK. If an error occurs while preparing the statement, \n** return an SQLite error code.\n**\n** There is only ever one instance of this SQL statement compiled for\n** each FTS3 table.\n**\n** The statement returns the following columns from the %_segdir table:\n**\n**   0: idx\n**   1: start_block\n**   2: leaves_end_block\n**   3: end_block\n**   4: root\n*/\nSQLITE_PRIVATE int sqlite3Fts3AllSegdirs(\n  Fts3Table *p,                   /* FTS3 table */\n  int iLangid,                    /* Language being queried */\n  int iIndex,                     /* Index for p->aIndex[] */\n  int iLevel,                     /* Level to select (relative level) */\n  sqlite3_stmt **ppStmt           /* OUT: Compiled statement */\n){\n  int rc;\n  sqlite3_stmt *pStmt = 0;\n\n  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );\n  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );\n  assert( iIndex>=0 && iIndex<p->nIndex );\n\n  if( iLevel<0 ){\n    /* \"SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ...\" */\n    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);\n    if( rc==SQLITE_OK ){ \n      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));\n      sqlite3_bind_int64(pStmt, 2, \n          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)\n      );\n    }\n  }else{\n    /* \"SELECT * FROM %_segdir WHERE level = ? ORDER BY ...\" */\n    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);\n    if( rc==SQLITE_OK ){ \n      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));\n    }\n  }\n  *ppStmt = pStmt;\n  return rc;\n}\n\n\n/*\n** Append a single varint to a PendingList buffer. SQLITE_OK is returned\n** if successful, or an SQLite error code otherwise.\n**\n** This function also serves to allocate the PendingList structure itself.\n** For example, to create a new PendingList structure containing two\n** varints:\n**\n**   PendingList *p = 0;\n**   fts3PendingListAppendVarint(&p, 1);\n**   fts3PendingListAppendVarint(&p, 2);\n*/\nstatic int fts3PendingListAppendVarint(\n  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */\n  sqlite3_int64 i                 /* Value to append to data */\n){\n  PendingList *p = *pp;\n\n  /* Allocate or grow the PendingList as required. */\n  if( !p ){\n    p = sqlite3_malloc(sizeof(*p) + 100);\n    if( !p ){\n      return SQLITE_NOMEM;\n    }\n    p->nSpace = 100;\n    p->aData = (char *)&p[1];\n    p->nData = 0;\n  }\n  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){\n    int nNew = p->nSpace * 2;\n    p = sqlite3_realloc(p, sizeof(*p) + nNew);\n    if( !p ){\n      sqlite3_free(*pp);\n      *pp = 0;\n      return SQLITE_NOMEM;\n    }\n    p->nSpace = nNew;\n    p->aData = (char *)&p[1];\n  }\n\n  /* Append the new serialized varint to the end of the list. */\n  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);\n  p->aData[p->nData] = '\\0';\n  *pp = p;\n  return SQLITE_OK;\n}\n\n/*\n** Add a docid/column/position entry to a PendingList structure. Non-zero\n** is returned if the structure is sqlite3_realloced as part of adding\n** the entry. Otherwise, zero.\n**\n** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.\n** Zero is always returned in this case. Otherwise, if no OOM error occurs,\n** it is set to SQLITE_OK.\n*/\nstatic int fts3PendingListAppend(\n  PendingList **pp,               /* IN/OUT: PendingList structure */\n  sqlite3_int64 iDocid,           /* Docid for entry to add */\n  sqlite3_int64 iCol,             /* Column for entry to add */\n  sqlite3_int64 iPos,             /* Position of term for entry to add */\n  int *pRc                        /* OUT: Return code */\n){\n  PendingList *p = *pp;\n  int rc = SQLITE_OK;\n\n  assert( !p || p->iLastDocid<=iDocid );\n\n  if( !p || p->iLastDocid!=iDocid ){\n    u64 iDelta = (u64)iDocid - (u64)(p ? p->iLastDocid : 0);\n    if( p ){\n      assert( p->nData<p->nSpace );\n      assert( p->aData[p->nData]==0 );\n      p->nData++;\n    }\n    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){\n      goto pendinglistappend_out;\n    }\n    p->iLastCol = -1;\n    p->iLastPos = 0;\n    p->iLastDocid = iDocid;\n  }\n  if( iCol>0 && p->iLastCol!=iCol ){\n    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))\n     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))\n    ){\n      goto pendinglistappend_out;\n    }\n    p->iLastCol = iCol;\n    p->iLastPos = 0;\n  }\n  if( iCol>=0 ){\n    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );\n    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);\n    if( rc==SQLITE_OK ){\n      p->iLastPos = iPos;\n    }\n  }\n\n pendinglistappend_out:\n  *pRc = rc;\n  if( p!=*pp ){\n    *pp = p;\n    return 1;\n  }\n  return 0;\n}\n\n/*\n** Free a PendingList object allocated by fts3PendingListAppend().\n*/\nstatic void fts3PendingListDelete(PendingList *pList){\n  sqlite3_free(pList);\n}\n\n/*\n** Add an entry to one of the pending-terms hash tables.\n*/\nstatic int fts3PendingTermsAddOne(\n  Fts3Table *p,\n  int iCol,\n  int iPos,\n  Fts3Hash *pHash,                /* Pending terms hash table to add entry to */\n  const char *zToken,\n  int nToken\n){\n  PendingList *pList;\n  int rc = SQLITE_OK;\n\n  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);\n  if( pList ){\n    p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));\n  }\n  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){\n    if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){\n      /* Malloc failed while inserting the new entry. This can only \n      ** happen if there was no previous entry for this token.\n      */\n      assert( 0==fts3HashFind(pHash, zToken, nToken) );\n      sqlite3_free(pList);\n      rc = SQLITE_NOMEM;\n    }\n  }\n  if( rc==SQLITE_OK ){\n    p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));\n  }\n  return rc;\n}\n\n/*\n** Tokenize the nul-terminated string zText and add all tokens to the\n** pending-terms hash-table. The docid used is that currently stored in\n** p->iPrevDocid, and the column is specified by argument iCol.\n**\n** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.\n*/\nstatic int fts3PendingTermsAdd(\n  Fts3Table *p,                   /* Table into which text will be inserted */\n  int iLangid,                    /* Language id to use */\n  const char *zText,              /* Text of document to be inserted */\n  int iCol,                       /* Column into which text is being inserted */\n  u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */\n){\n  int rc;\n  int iStart = 0;\n  int iEnd = 0;\n  int iPos = 0;\n  int nWord = 0;\n\n  char const *zToken;\n  int nToken = 0;\n\n  sqlite3_tokenizer *pTokenizer = p->pTokenizer;\n  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;\n  sqlite3_tokenizer_cursor *pCsr;\n  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,\n      const char**,int*,int*,int*,int*);\n\n  assert( pTokenizer && pModule );\n\n  /* If the user has inserted a NULL value, this function may be called with\n  ** zText==0. In this case, add zero token entries to the hash table and \n  ** return early. */\n  if( zText==0 ){\n    *pnWord = 0;\n    return SQLITE_OK;\n  }\n\n  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  xNext = pModule->xNext;\n  while( SQLITE_OK==rc\n      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))\n  ){\n    int i;\n    if( iPos>=nWord ) nWord = iPos+1;\n\n    /* Positions cannot be negative; we use -1 as a terminator internally.\n    ** Tokens must have a non-zero length.\n    */\n    if( iPos<0 || !zToken || nToken<=0 ){\n      rc = SQLITE_ERROR;\n      break;\n    }\n\n    /* Add the term to the terms index */\n    rc = fts3PendingTermsAddOne(\n        p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken\n    );\n    \n    /* Add the term to each of the prefix indexes that it is not too \n    ** short for. */\n    for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){\n      struct Fts3Index *pIndex = &p->aIndex[i];\n      if( nToken<pIndex->nPrefix ) continue;\n      rc = fts3PendingTermsAddOne(\n          p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix\n      );\n    }\n  }\n\n  pModule->xClose(pCsr);\n  *pnWord += nWord;\n  return (rc==SQLITE_DONE ? SQLITE_OK : rc);\n}\n\n/* \n** Calling this function indicates that subsequent calls to \n** fts3PendingTermsAdd() are to add term/position-list pairs for the\n** contents of the document with docid iDocid.\n*/\nstatic int fts3PendingTermsDocid(\n  Fts3Table *p,                   /* Full-text table handle */\n  int bDelete,                    /* True if this op is a delete */\n  int iLangid,                    /* Language id of row being written */\n  sqlite_int64 iDocid             /* Docid of row being written */\n){\n  assert( iLangid>=0 );\n  assert( bDelete==1 || bDelete==0 );\n\n  /* TODO(shess) Explore whether partially flushing the buffer on\n  ** forced-flush would provide better performance.  I suspect that if\n  ** we ordered the doclists by size and flushed the largest until the\n  ** buffer was half empty, that would let the less frequent terms\n  ** generate longer doclists.\n  */\n  if( iDocid<p->iPrevDocid \n   || (iDocid==p->iPrevDocid && p->bPrevDelete==0)\n   || p->iPrevLangid!=iLangid\n   || p->nPendingData>p->nMaxPendingData \n  ){\n    int rc = sqlite3Fts3PendingTermsFlush(p);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n  p->iPrevDocid = iDocid;\n  p->iPrevLangid = iLangid;\n  p->bPrevDelete = bDelete;\n  return SQLITE_OK;\n}\n\n/*\n** Discard the contents of the pending-terms hash tables. \n*/\nSQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){\n  int i;\n  for(i=0; i<p->nIndex; i++){\n    Fts3HashElem *pElem;\n    Fts3Hash *pHash = &p->aIndex[i].hPending;\n    for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){\n      PendingList *pList = (PendingList *)fts3HashData(pElem);\n      fts3PendingListDelete(pList);\n    }\n    fts3HashClear(pHash);\n  }\n  p->nPendingData = 0;\n}\n\n/*\n** This function is called by the xUpdate() method as part of an INSERT\n** operation. It adds entries for each term in the new record to the\n** pendingTerms hash table.\n**\n** Argument apVal is the same as the similarly named argument passed to\n** fts3InsertData(). Parameter iDocid is the docid of the new row.\n*/\nstatic int fts3InsertTerms(\n  Fts3Table *p, \n  int iLangid, \n  sqlite3_value **apVal, \n  u32 *aSz\n){\n  int i;                          /* Iterator variable */\n  for(i=2; i<p->nColumn+2; i++){\n    int iCol = i-2;\n    if( p->abNotindexed[iCol]==0 ){\n      const char *zText = (const char *)sqlite3_value_text(apVal[i]);\n      int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n      aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);\n    }\n  }\n  return SQLITE_OK;\n}\n\n/*\n** This function is called by the xUpdate() method for an INSERT operation.\n** The apVal parameter is passed a copy of the apVal argument passed by\n** SQLite to the xUpdate() method. i.e:\n**\n**   apVal[0]                Not used for INSERT.\n**   apVal[1]                rowid\n**   apVal[2]                Left-most user-defined column\n**   ...\n**   apVal[p->nColumn+1]     Right-most user-defined column\n**   apVal[p->nColumn+2]     Hidden column with same name as table\n**   apVal[p->nColumn+3]     Hidden \"docid\" column (alias for rowid)\n**   apVal[p->nColumn+4]     Hidden languageid column\n*/\nstatic int fts3InsertData(\n  Fts3Table *p,                   /* Full-text table */\n  sqlite3_value **apVal,          /* Array of values to insert */\n  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */\n){\n  int rc;                         /* Return code */\n  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */\n\n  if( p->zContentTbl ){\n    sqlite3_value *pRowid = apVal[p->nColumn+3];\n    if( sqlite3_value_type(pRowid)==SQLITE_NULL ){\n      pRowid = apVal[1];\n    }\n    if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){\n      return SQLITE_CONSTRAINT;\n    }\n    *piDocid = sqlite3_value_int64(pRowid);\n    return SQLITE_OK;\n  }\n\n  /* Locate the statement handle used to insert data into the %_content\n  ** table. The SQL for this statement is:\n  **\n  **   INSERT INTO %_content VALUES(?, ?, ?, ...)\n  **\n  ** The statement features N '?' variables, where N is the number of user\n  ** defined columns in the FTS3 table, plus one for the docid field.\n  */\n  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);\n  if( rc==SQLITE_OK && p->zLanguageid ){\n    rc = sqlite3_bind_int(\n        pContentInsert, p->nColumn+2, \n        sqlite3_value_int(apVal[p->nColumn+4])\n    );\n  }\n  if( rc!=SQLITE_OK ) return rc;\n\n  /* There is a quirk here. The users INSERT statement may have specified\n  ** a value for the \"rowid\" field, for the \"docid\" field, or for both.\n  ** Which is a problem, since \"rowid\" and \"docid\" are aliases for the\n  ** same value. For example:\n  **\n  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);\n  **\n  ** In FTS3, this is an error. It is an error to specify non-NULL values\n  ** for both docid and some other rowid alias.\n  */\n  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){\n    if( SQLITE_NULL==sqlite3_value_type(apVal[0])\n     && SQLITE_NULL!=sqlite3_value_type(apVal[1])\n    ){\n      /* A rowid/docid conflict. */\n      return SQLITE_ERROR;\n    }\n    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n\n  /* Execute the statement to insert the record. Set *piDocid to the \n  ** new docid value. \n  */\n  sqlite3_step(pContentInsert);\n  rc = sqlite3_reset(pContentInsert);\n\n  *piDocid = sqlite3_last_insert_rowid(p->db);\n  return rc;\n}\n\n\n\n/*\n** Remove all data from the FTS3 table. Clear the hash table containing\n** pending terms.\n*/\nstatic int fts3DeleteAll(Fts3Table *p, int bContent){\n  int rc = SQLITE_OK;             /* Return code */\n\n  /* Discard the contents of the pending-terms hash table. */\n  sqlite3Fts3PendingTermsClear(p);\n\n  /* Delete everything from the shadow tables. Except, leave %_content as\n  ** is if bContent is false.  */\n  assert( p->zContentTbl==0 || bContent==0 );\n  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);\n  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);\n  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);\n  if( p->bHasDocsize ){\n    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);\n  }\n  if( p->bHasStat ){\n    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);\n  }\n  return rc;\n}\n\n/*\n**\n*/\nstatic int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){\n  int iLangid = 0;\n  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);\n  return iLangid;\n}\n\n/*\n** The first element in the apVal[] array is assumed to contain the docid\n** (an integer) of a row about to be deleted. Remove all terms from the\n** full-text index.\n*/\nstatic void fts3DeleteTerms( \n  int *pRC,               /* Result code */\n  Fts3Table *p,           /* The FTS table to delete from */\n  sqlite3_value *pRowid,  /* The docid to be deleted */\n  u32 *aSz,               /* Sizes of deleted document written here */\n  int *pbFound            /* OUT: Set to true if row really does exist */\n){\n  int rc;\n  sqlite3_stmt *pSelect;\n\n  assert( *pbFound==0 );\n  if( *pRC ) return;\n  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);\n  if( rc==SQLITE_OK ){\n    if( SQLITE_ROW==sqlite3_step(pSelect) ){\n      int i;\n      int iLangid = langidFromSelect(p, pSelect);\n      i64 iDocid = sqlite3_column_int64(pSelect, 0);\n      rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);\n      for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){\n        int iCol = i-1;\n        if( p->abNotindexed[iCol]==0 ){\n          const char *zText = (const char *)sqlite3_column_text(pSelect, i);\n          rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);\n          aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);\n        }\n      }\n      if( rc!=SQLITE_OK ){\n        sqlite3_reset(pSelect);\n        *pRC = rc;\n        return;\n      }\n      *pbFound = 1;\n    }\n    rc = sqlite3_reset(pSelect);\n  }else{\n    sqlite3_reset(pSelect);\n  }\n  *pRC = rc;\n}\n\n/*\n** Forward declaration to account for the circular dependency between\n** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().\n*/\nstatic int fts3SegmentMerge(Fts3Table *, int, int, int);\n\n/* \n** This function allocates a new level iLevel index in the segdir table.\n** Usually, indexes are allocated within a level sequentially starting\n** with 0, so the allocated index is one greater than the value returned\n** by:\n**\n**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel\n**\n** However, if there are already FTS3_MERGE_COUNT indexes at the requested\n** level, they are merged into a single level (iLevel+1) segment and the \n** allocated index is 0.\n**\n** If successful, *piIdx is set to the allocated index slot and SQLITE_OK\n** returned. Otherwise, an SQLite error code is returned.\n*/\nstatic int fts3AllocateSegdirIdx(\n  Fts3Table *p, \n  int iLangid,                    /* Language id */\n  int iIndex,                     /* Index for p->aIndex */\n  int iLevel, \n  int *piIdx\n){\n  int rc;                         /* Return Code */\n  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */\n  int iNext = 0;                  /* Result of query pNextIdx */\n\n  assert( iLangid>=0 );\n  assert( p->nIndex>=1 );\n\n  /* Set variable iNext to the next available segdir index at level iLevel. */\n  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(\n        pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)\n    );\n    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){\n      iNext = sqlite3_column_int(pNextIdx, 0);\n    }\n    rc = sqlite3_reset(pNextIdx);\n  }\n\n  if( rc==SQLITE_OK ){\n    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already\n    ** full, merge all segments in level iLevel into a single iLevel+1\n    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,\n    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.\n    */\n    if( iNext>=MergeCount(p) ){\n      fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));\n      rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);\n      *piIdx = 0;\n    }else{\n      *piIdx = iNext;\n    }\n  }\n\n  return rc;\n}\n\n/*\n** The %_segments table is declared as follows:\n**\n**   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)\n**\n** This function reads data from a single row of the %_segments table. The\n** specific row is identified by the iBlockid parameter. If paBlob is not\n** NULL, then a buffer is allocated using sqlite3_malloc() and populated\n** with the contents of the blob stored in the \"block\" column of the \n** identified table row is. Whether or not paBlob is NULL, *pnBlob is set\n** to the size of the blob in bytes before returning.\n**\n** If an error occurs, or the table does not contain the specified row,\n** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If\n** paBlob is non-NULL, then it is the responsibility of the caller to\n** eventually free the returned buffer.\n**\n** This function may leave an open sqlite3_blob* handle in the\n** Fts3Table.pSegments variable. This handle is reused by subsequent calls\n** to this function. The handle may be closed by calling the\n** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy\n** performance improvement, but the blob handle should always be closed\n** before control is returned to the user (to prevent a lock being held\n** on the database file for longer than necessary). Thus, any virtual table\n** method (xFilter etc.) that may directly or indirectly call this function\n** must call sqlite3Fts3SegmentsClose() before returning.\n*/\nSQLITE_PRIVATE int sqlite3Fts3ReadBlock(\n  Fts3Table *p,                   /* FTS3 table handle */\n  sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */\n  char **paBlob,                  /* OUT: Blob data in malloc'd buffer */\n  int *pnBlob,                    /* OUT: Size of blob data */\n  int *pnLoad                     /* OUT: Bytes actually loaded */\n){\n  int rc;                         /* Return code */\n\n  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */\n  assert( pnBlob );\n\n  if( p->pSegments ){\n    rc = sqlite3_blob_reopen(p->pSegments, iBlockid);\n  }else{\n    if( 0==p->zSegmentsTbl ){\n      p->zSegmentsTbl = sqlite3_mprintf(\"%s_segments\", p->zName);\n      if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;\n    }\n    rc = sqlite3_blob_open(\n       p->db, p->zDb, p->zSegmentsTbl, \"block\", iBlockid, 0, &p->pSegments\n    );\n  }\n\n  if( rc==SQLITE_OK ){\n    int nByte = sqlite3_blob_bytes(p->pSegments);\n    *pnBlob = nByte;\n    if( paBlob ){\n      char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);\n      if( !aByte ){\n        rc = SQLITE_NOMEM;\n      }else{\n        if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){\n          nByte = FTS3_NODE_CHUNKSIZE;\n          *pnLoad = nByte;\n        }\n        rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);\n        memset(&aByte[nByte], 0, FTS3_NODE_PADDING);\n        if( rc!=SQLITE_OK ){\n          sqlite3_free(aByte);\n          aByte = 0;\n        }\n      }\n      *paBlob = aByte;\n    }\n  }else if( rc==SQLITE_ERROR ){\n    rc = FTS_CORRUPT_VTAB;\n  }\n\n  return rc;\n}\n\n/*\n** Close the blob handle at p->pSegments, if it is open. See comments above\n** the sqlite3Fts3ReadBlock() function for details.\n*/\nSQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){\n  sqlite3_blob_close(p->pSegments);\n  p->pSegments = 0;\n}\n    \nstatic int fts3SegReaderIncrRead(Fts3SegReader *pReader){\n  int nRead;                      /* Number of bytes to read */\n  int rc;                         /* Return code */\n\n  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);\n  rc = sqlite3_blob_read(\n      pReader->pBlob, \n      &pReader->aNode[pReader->nPopulate],\n      nRead,\n      pReader->nPopulate\n  );\n\n  if( rc==SQLITE_OK ){\n    pReader->nPopulate += nRead;\n    memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);\n    if( pReader->nPopulate==pReader->nNode ){\n      sqlite3_blob_close(pReader->pBlob);\n      pReader->pBlob = 0;\n      pReader->nPopulate = 0;\n    }\n  }\n  return rc;\n}\n\nstatic int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){\n  int rc = SQLITE_OK;\n  assert( !pReader->pBlob \n       || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])\n  );\n  while( pReader->pBlob && rc==SQLITE_OK \n     &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate\n  ){\n    rc = fts3SegReaderIncrRead(pReader);\n  }\n  return rc;\n}\n\n/*\n** Set an Fts3SegReader cursor to point at EOF.\n*/\nstatic void fts3SegReaderSetEof(Fts3SegReader *pSeg){\n  if( !fts3SegReaderIsRootOnly(pSeg) ){\n    sqlite3_free(pSeg->aNode);\n    sqlite3_blob_close(pSeg->pBlob);\n    pSeg->pBlob = 0;\n  }\n  pSeg->aNode = 0;\n}\n\n/*\n** Move the iterator passed as the first argument to the next term in the\n** segment. If successful, SQLITE_OK is returned. If there is no next term,\n** SQLITE_DONE. Otherwise, an SQLite error code.\n*/\nstatic int fts3SegReaderNext(\n  Fts3Table *p, \n  Fts3SegReader *pReader,\n  int bIncr\n){\n  int rc;                         /* Return code of various sub-routines */\n  char *pNext;                    /* Cursor variable */\n  int nPrefix;                    /* Number of bytes in term prefix */\n  int nSuffix;                    /* Number of bytes in term suffix */\n\n  if( !pReader->aDoclist ){\n    pNext = pReader->aNode;\n  }else{\n    pNext = &pReader->aDoclist[pReader->nDoclist];\n  }\n\n  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){\n\n    if( fts3SegReaderIsPending(pReader) ){\n      Fts3HashElem *pElem = *(pReader->ppNextElem);\n      sqlite3_free(pReader->aNode);\n      pReader->aNode = 0;\n      if( pElem ){\n        char *aCopy;\n        PendingList *pList = (PendingList *)fts3HashData(pElem);\n        int nCopy = pList->nData+1;\n        pReader->zTerm = (char *)fts3HashKey(pElem);\n        pReader->nTerm = fts3HashKeysize(pElem);\n        aCopy = (char*)sqlite3_malloc(nCopy);\n        if( !aCopy ) return SQLITE_NOMEM;\n        memcpy(aCopy, pList->aData, nCopy);\n        pReader->nNode = pReader->nDoclist = nCopy;\n        pReader->aNode = pReader->aDoclist = aCopy;\n        pReader->ppNextElem++;\n        assert( pReader->aNode );\n      }\n      return SQLITE_OK;\n    }\n\n    fts3SegReaderSetEof(pReader);\n\n    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf \n    ** blocks have already been traversed.  */\n#ifdef CORRUPT_DB\n    assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock || CORRUPT_DB );\n#endif\n    if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){\n      return SQLITE_OK;\n    }\n\n    rc = sqlite3Fts3ReadBlock(\n        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, \n        (bIncr ? &pReader->nPopulate : 0)\n    );\n    if( rc!=SQLITE_OK ) return rc;\n    assert( pReader->pBlob==0 );\n    if( bIncr && pReader->nPopulate<pReader->nNode ){\n      pReader->pBlob = p->pSegments;\n      p->pSegments = 0;\n    }\n    pNext = pReader->aNode;\n  }\n\n  assert( !fts3SegReaderIsPending(pReader) );\n\n  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);\n  if( rc!=SQLITE_OK ) return rc;\n  \n  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is \n  ** safe (no risk of overread) even if the node data is corrupted. */\n  pNext += fts3GetVarint32(pNext, &nPrefix);\n  pNext += fts3GetVarint32(pNext, &nSuffix);\n  if( nSuffix<=0 \n   || (&pReader->aNode[pReader->nNode] - pNext)<nSuffix\n   || nPrefix>pReader->nTerm\n  ){\n    return FTS_CORRUPT_VTAB;\n  }\n\n  /* Both nPrefix and nSuffix were read by fts3GetVarint32() and so are\n  ** between 0 and 0x7FFFFFFF. But the sum of the two may cause integer\n  ** overflow - hence the (i64) casts.  */\n  if( (i64)nPrefix+nSuffix>(i64)pReader->nTermAlloc ){\n    i64 nNew = ((i64)nPrefix+nSuffix)*2;\n    char *zNew = sqlite3_realloc64(pReader->zTerm, nNew);\n    if( !zNew ){\n      return SQLITE_NOMEM;\n    }\n    pReader->zTerm = zNew;\n    pReader->nTermAlloc = nNew;\n  }\n\n  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);\n  if( rc!=SQLITE_OK ) return rc;\n\n  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);\n  pReader->nTerm = nPrefix+nSuffix;\n  pNext += nSuffix;\n  pNext += fts3GetVarint32(pNext, &pReader->nDoclist);\n  pReader->aDoclist = pNext;\n  pReader->pOffsetList = 0;\n\n  /* Check that the doclist does not appear to extend past the end of the\n  ** b-tree node. And that the final byte of the doclist is 0x00. If either \n  ** of these statements is untrue, then the data structure is corrupt.\n  */\n  if( pReader->nDoclist > pReader->nNode-(pReader->aDoclist-pReader->aNode)\n   || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])\n   || pReader->nDoclist==0\n  ){\n    return FTS_CORRUPT_VTAB;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Set the SegReader to point to the first docid in the doclist associated\n** with the current term.\n*/\nstatic int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){\n  int rc = SQLITE_OK;\n  assert( pReader->aDoclist );\n  assert( !pReader->pOffsetList );\n  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){\n    u8 bEof = 0;\n    pReader->iDocid = 0;\n    pReader->nOffsetList = 0;\n    sqlite3Fts3DoclistPrev(0,\n        pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, \n        &pReader->iDocid, &pReader->nOffsetList, &bEof\n    );\n  }else{\n    rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);\n    if( rc==SQLITE_OK ){\n      int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);\n      pReader->pOffsetList = &pReader->aDoclist[n];\n    }\n  }\n  return rc;\n}\n\n/*\n** Advance the SegReader to point to the next docid in the doclist\n** associated with the current term.\n** \n** If arguments ppOffsetList and pnOffsetList are not NULL, then \n** *ppOffsetList is set to point to the first column-offset list\n** in the doclist entry (i.e. immediately past the docid varint).\n** *pnOffsetList is set to the length of the set of column-offset\n** lists, not including the nul-terminator byte. For example:\n*/\nstatic int fts3SegReaderNextDocid(\n  Fts3Table *pTab,\n  Fts3SegReader *pReader,         /* Reader to advance to next docid */\n  char **ppOffsetList,            /* OUT: Pointer to current position-list */\n  int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */\n){\n  int rc = SQLITE_OK;\n  char *p = pReader->pOffsetList;\n  char c = 0;\n\n  assert( p );\n\n  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){\n    /* A pending-terms seg-reader for an FTS4 table that uses order=desc.\n    ** Pending-terms doclists are always built up in ascending order, so\n    ** we have to iterate through them backwards here. */\n    u8 bEof = 0;\n    if( ppOffsetList ){\n      *ppOffsetList = pReader->pOffsetList;\n      *pnOffsetList = pReader->nOffsetList - 1;\n    }\n    sqlite3Fts3DoclistPrev(0,\n        pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,\n        &pReader->nOffsetList, &bEof\n    );\n    if( bEof ){\n      pReader->pOffsetList = 0;\n    }else{\n      pReader->pOffsetList = p;\n    }\n  }else{\n    char *pEnd = &pReader->aDoclist[pReader->nDoclist];\n\n    /* Pointer p currently points at the first byte of an offset list. The\n    ** following block advances it to point one byte past the end of\n    ** the same offset list. */\n    while( 1 ){\n  \n      /* The following line of code (and the \"p++\" below the while() loop) is\n      ** normally all that is required to move pointer p to the desired \n      ** position. The exception is if this node is being loaded from disk\n      ** incrementally and pointer \"p\" now points to the first byte past\n      ** the populated part of pReader->aNode[].\n      */\n      while( *p | c ) c = *p++ & 0x80;\n      assert( *p==0 );\n  \n      if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;\n      rc = fts3SegReaderIncrRead(pReader);\n      if( rc!=SQLITE_OK ) return rc;\n    }\n    p++;\n  \n    /* If required, populate the output variables with a pointer to and the\n    ** size of the previous offset-list.\n    */\n    if( ppOffsetList ){\n      *ppOffsetList = pReader->pOffsetList;\n      *pnOffsetList = (int)(p - pReader->pOffsetList - 1);\n    }\n\n    /* List may have been edited in place by fts3EvalNearTrim() */\n    while( p<pEnd && *p==0 ) p++;\n  \n    /* If there are no more entries in the doclist, set pOffsetList to\n    ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and\n    ** Fts3SegReader.pOffsetList to point to the next offset list before\n    ** returning.\n    */\n    if( p>=pEnd ){\n      pReader->pOffsetList = 0;\n    }else{\n      rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);\n      if( rc==SQLITE_OK ){\n        u64 iDelta;\n        pReader->pOffsetList = p + sqlite3Fts3GetVarintU(p, &iDelta);\n        if( pTab->bDescIdx ){\n          pReader->iDocid = (i64)((u64)pReader->iDocid - iDelta);\n        }else{\n          pReader->iDocid = (i64)((u64)pReader->iDocid + iDelta);\n        }\n      }\n    }\n  }\n\n  return rc;\n}\n\n\nSQLITE_PRIVATE int sqlite3Fts3MsrOvfl(\n  Fts3Cursor *pCsr, \n  Fts3MultiSegReader *pMsr,\n  int *pnOvfl\n){\n  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;\n  int nOvfl = 0;\n  int ii;\n  int rc = SQLITE_OK;\n  int pgsz = p->nPgsz;\n\n  assert( p->bFts4 );\n  assert( pgsz>0 );\n\n  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){\n    Fts3SegReader *pReader = pMsr->apSegment[ii];\n    if( !fts3SegReaderIsPending(pReader) \n     && !fts3SegReaderIsRootOnly(pReader) \n    ){\n      sqlite3_int64 jj;\n      for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){\n        int nBlob;\n        rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);\n        if( rc!=SQLITE_OK ) break;\n        if( (nBlob+35)>pgsz ){\n          nOvfl += (nBlob + 34)/pgsz;\n        }\n      }\n    }\n  }\n  *pnOvfl = nOvfl;\n  return rc;\n}\n\n/*\n** Free all allocations associated with the iterator passed as the \n** second argument.\n*/\nSQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){\n  if( pReader ){\n    if( !fts3SegReaderIsPending(pReader) ){\n      sqlite3_free(pReader->zTerm);\n    }\n    if( !fts3SegReaderIsRootOnly(pReader) ){\n      sqlite3_free(pReader->aNode);\n    }\n    sqlite3_blob_close(pReader->pBlob);\n  }\n  sqlite3_free(pReader);\n}\n\n/*\n** Allocate a new SegReader object.\n*/\nSQLITE_PRIVATE int sqlite3Fts3SegReaderNew(\n  int iAge,                       /* Segment \"age\". */\n  int bLookup,                    /* True for a lookup only */\n  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */\n  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */\n  sqlite3_int64 iEndBlock,        /* Final block of segment */\n  const char *zRoot,              /* Buffer containing root node */\n  int nRoot,                      /* Size of buffer containing root node */\n  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */\n){\n  Fts3SegReader *pReader;         /* Newly allocated SegReader object */\n  int nExtra = 0;                 /* Bytes to allocate segment root node */\n\n  assert( zRoot!=0 || nRoot==0 );\n#ifdef CORRUPT_DB\n  assert( zRoot!=0 || CORRUPT_DB );\n#endif\n\n  if( iStartLeaf==0 ){\n    if( iEndLeaf!=0 ) return FTS_CORRUPT_VTAB;\n    nExtra = nRoot + FTS3_NODE_PADDING;\n  }\n\n  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);\n  if( !pReader ){\n    return SQLITE_NOMEM;\n  }\n  memset(pReader, 0, sizeof(Fts3SegReader));\n  pReader->iIdx = iAge;\n  pReader->bLookup = bLookup!=0;\n  pReader->iStartBlock = iStartLeaf;\n  pReader->iLeafEndBlock = iEndLeaf;\n  pReader->iEndBlock = iEndBlock;\n\n  if( nExtra ){\n    /* The entire segment is stored in the root node. */\n    pReader->aNode = (char *)&pReader[1];\n    pReader->rootOnly = 1;\n    pReader->nNode = nRoot;\n    if( nRoot ) memcpy(pReader->aNode, zRoot, nRoot);\n    memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);\n  }else{\n    pReader->iCurrentBlock = iStartLeaf-1;\n  }\n  *ppReader = pReader;\n  return SQLITE_OK;\n}\n\n/*\n** This is a comparison function used as a qsort() callback when sorting\n** an array of pending terms by term. This occurs as part of flushing\n** the contents of the pending-terms hash table to the database.\n*/\nstatic int SQLITE_CDECL fts3CompareElemByTerm(\n  const void *lhs,\n  const void *rhs\n){\n  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);\n  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);\n  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);\n  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);\n\n  int n = (n1<n2 ? n1 : n2);\n  int c = memcmp(z1, z2, n);\n  if( c==0 ){\n    c = n1 - n2;\n  }\n  return c;\n}\n\n/*\n** This function is used to allocate an Fts3SegReader that iterates through\n** a subset of the terms stored in the Fts3Table.pendingTerms array.\n**\n** If the isPrefixIter parameter is zero, then the returned SegReader iterates\n** through each term in the pending-terms table. Or, if isPrefixIter is\n** non-zero, it iterates through each term and its prefixes. For example, if\n** the pending terms hash table contains the terms \"sqlite\", \"mysql\" and\n** \"firebird\", then the iterator visits the following 'terms' (in the order\n** shown):\n**\n**   f fi fir fire fireb firebi firebir firebird\n**   m my mys mysq mysql\n**   s sq sql sqli sqlit sqlite\n**\n** Whereas if isPrefixIter is zero, the terms visited are:\n**\n**   firebird mysql sqlite\n*/\nSQLITE_PRIVATE int sqlite3Fts3SegReaderPending(\n  Fts3Table *p,                   /* Virtual table handle */\n  int iIndex,                     /* Index for p->aIndex */\n  const char *zTerm,              /* Term to search for */\n  int nTerm,                      /* Size of buffer zTerm */\n  int bPrefix,                    /* True for a prefix iterator */\n  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */\n){\n  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */\n  Fts3HashElem *pE;               /* Iterator variable */\n  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */\n  int nElem = 0;                  /* Size of array at aElem */\n  int rc = SQLITE_OK;             /* Return Code */\n  Fts3Hash *pHash;\n\n  pHash = &p->aIndex[iIndex].hPending;\n  if( bPrefix ){\n    int nAlloc = 0;               /* Size of allocated array at aElem */\n\n    for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){\n      char *zKey = (char *)fts3HashKey(pE);\n      int nKey = fts3HashKeysize(pE);\n      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){\n        if( nElem==nAlloc ){\n          Fts3HashElem **aElem2;\n          nAlloc += 16;\n          aElem2 = (Fts3HashElem **)sqlite3_realloc(\n              aElem, nAlloc*sizeof(Fts3HashElem *)\n          );\n          if( !aElem2 ){\n            rc = SQLITE_NOMEM;\n            nElem = 0;\n            break;\n          }\n          aElem = aElem2;\n        }\n\n        aElem[nElem++] = pE;\n      }\n    }\n\n    /* If more than one term matches the prefix, sort the Fts3HashElem\n    ** objects in term order using qsort(). This uses the same comparison\n    ** callback as is used when flushing terms to disk.\n    */\n    if( nElem>1 ){\n      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);\n    }\n\n  }else{\n    /* The query is a simple term lookup that matches at most one term in\n    ** the index. All that is required is a straight hash-lookup. \n    **\n    ** Because the stack address of pE may be accessed via the aElem pointer\n    ** below, the \"Fts3HashElem *pE\" must be declared so that it is valid\n    ** within this entire function, not just this \"else{...}\" block.\n    */\n    pE = fts3HashFindElem(pHash, zTerm, nTerm);\n    if( pE ){\n      aElem = &pE;\n      nElem = 1;\n    }\n  }\n\n  if( nElem>0 ){\n    sqlite3_int64 nByte;\n    nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);\n    pReader = (Fts3SegReader *)sqlite3_malloc64(nByte);\n    if( !pReader ){\n      rc = SQLITE_NOMEM;\n    }else{\n      memset(pReader, 0, nByte);\n      pReader->iIdx = 0x7FFFFFFF;\n      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];\n      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));\n    }\n  }\n\n  if( bPrefix ){\n    sqlite3_free(aElem);\n  }\n  *ppReader = pReader;\n  return rc;\n}\n\n/*\n** Compare the entries pointed to by two Fts3SegReader structures. \n** Comparison is as follows:\n**\n**   1) EOF is greater than not EOF.\n**\n**   2) The current terms (if any) are compared using memcmp(). If one\n**      term is a prefix of another, the longer term is considered the\n**      larger.\n**\n**   3) By segment age. An older segment is considered larger.\n*/\nstatic int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){\n  int rc;\n  if( pLhs->aNode && pRhs->aNode ){\n    int rc2 = pLhs->nTerm - pRhs->nTerm;\n    if( rc2<0 ){\n      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);\n    }else{\n      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);\n    }\n    if( rc==0 ){\n      rc = rc2;\n    }\n  }else{\n    rc = (pLhs->aNode==0) - (pRhs->aNode==0);\n  }\n  if( rc==0 ){\n    rc = pRhs->iIdx - pLhs->iIdx;\n  }\n  assert( rc!=0 );\n  return rc;\n}\n\n/*\n** A different comparison function for SegReader structures. In this\n** version, it is assumed that each SegReader points to an entry in\n** a doclist for identical terms. Comparison is made as follows:\n**\n**   1) EOF (end of doclist in this case) is greater than not EOF.\n**\n**   2) By current docid.\n**\n**   3) By segment age. An older segment is considered larger.\n*/\nstatic int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){\n  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);\n  if( rc==0 ){\n    if( pLhs->iDocid==pRhs->iDocid ){\n      rc = pRhs->iIdx - pLhs->iIdx;\n    }else{\n      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;\n    }\n  }\n  assert( pLhs->aNode && pRhs->aNode );\n  return rc;\n}\nstatic int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){\n  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);\n  if( rc==0 ){\n    if( pLhs->iDocid==pRhs->iDocid ){\n      rc = pRhs->iIdx - pLhs->iIdx;\n    }else{\n      rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;\n    }\n  }\n  assert( pLhs->aNode && pRhs->aNode );\n  return rc;\n}\n\n/*\n** Compare the term that the Fts3SegReader object passed as the first argument\n** points to with the term specified by arguments zTerm and nTerm. \n**\n** If the pSeg iterator is already at EOF, return 0. Otherwise, return\n** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are\n** equal, or +ve if the pSeg term is greater than zTerm/nTerm.\n*/\nstatic int fts3SegReaderTermCmp(\n  Fts3SegReader *pSeg,            /* Segment reader object */\n  const char *zTerm,              /* Term to compare to */\n  int nTerm                       /* Size of term zTerm in bytes */\n){\n  int res = 0;\n  if( pSeg->aNode ){\n    if( pSeg->nTerm>nTerm ){\n      res = memcmp(pSeg->zTerm, zTerm, nTerm);\n    }else{\n      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);\n    }\n    if( res==0 ){\n      res = pSeg->nTerm-nTerm;\n    }\n  }\n  return res;\n}\n\n/*\n** Argument apSegment is an array of nSegment elements. It is known that\n** the final (nSegment-nSuspect) members are already in sorted order\n** (according to the comparison function provided). This function shuffles\n** the array around until all entries are in sorted order.\n*/\nstatic void fts3SegReaderSort(\n  Fts3SegReader **apSegment,                     /* Array to sort entries of */\n  int nSegment,                                  /* Size of apSegment array */\n  int nSuspect,                                  /* Unsorted entry count */\n  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */\n){\n  int i;                          /* Iterator variable */\n\n  assert( nSuspect<=nSegment );\n\n  if( nSuspect==nSegment ) nSuspect--;\n  for(i=nSuspect-1; i>=0; i--){\n    int j;\n    for(j=i; j<(nSegment-1); j++){\n      Fts3SegReader *pTmp;\n      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;\n      pTmp = apSegment[j+1];\n      apSegment[j+1] = apSegment[j];\n      apSegment[j] = pTmp;\n    }\n  }\n\n#ifndef NDEBUG\n  /* Check that the list really is sorted now. */\n  for(i=0; i<(nSuspect-1); i++){\n    assert( xCmp(apSegment[i], apSegment[i+1])<0 );\n  }\n#endif\n}\n\n/* \n** Insert a record into the %_segments table.\n*/\nstatic int fts3WriteSegment(\n  Fts3Table *p,                   /* Virtual table handle */\n  sqlite3_int64 iBlock,           /* Block id for new block */\n  char *z,                        /* Pointer to buffer containing block data */\n  int n                           /* Size of buffer z in bytes */\n){\n  sqlite3_stmt *pStmt;\n  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pStmt, 1, iBlock);\n    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);\n    sqlite3_step(pStmt);\n    rc = sqlite3_reset(pStmt);\n    sqlite3_bind_null(pStmt, 2);\n  }\n  return rc;\n}\n\n/*\n** Find the largest relative level number in the table. If successful, set\n** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,\n** set *pnMax to zero and return an SQLite error code.\n*/\nSQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){\n  int rc;\n  int mxLevel = 0;\n  sqlite3_stmt *pStmt = 0;\n\n  rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);\n  if( rc==SQLITE_OK ){\n    if( SQLITE_ROW==sqlite3_step(pStmt) ){\n      mxLevel = sqlite3_column_int(pStmt, 0);\n    }\n    rc = sqlite3_reset(pStmt);\n  }\n  *pnMax = mxLevel;\n  return rc;\n}\n\n/* \n** Insert a record into the %_segdir table.\n*/\nstatic int fts3WriteSegdir(\n  Fts3Table *p,                   /* Virtual table handle */\n  sqlite3_int64 iLevel,           /* Value for \"level\" field (absolute level) */\n  int iIdx,                       /* Value for \"idx\" field */\n  sqlite3_int64 iStartBlock,      /* Value for \"start_block\" field */\n  sqlite3_int64 iLeafEndBlock,    /* Value for \"leaves_end_block\" field */\n  sqlite3_int64 iEndBlock,        /* Value for \"end_block\" field */\n  sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */\n  char *zRoot,                    /* Blob value for \"root\" field */\n  int nRoot                       /* Number of bytes in buffer zRoot */\n){\n  sqlite3_stmt *pStmt;\n  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pStmt, 1, iLevel);\n    sqlite3_bind_int(pStmt, 2, iIdx);\n    sqlite3_bind_int64(pStmt, 3, iStartBlock);\n    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);\n    if( nLeafData==0 ){\n      sqlite3_bind_int64(pStmt, 5, iEndBlock);\n    }else{\n      char *zEnd = sqlite3_mprintf(\"%lld %lld\", iEndBlock, nLeafData);\n      if( !zEnd ) return SQLITE_NOMEM;\n      sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);\n    }\n    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);\n    sqlite3_step(pStmt);\n    rc = sqlite3_reset(pStmt);\n    sqlite3_bind_null(pStmt, 6);\n  }\n  return rc;\n}\n\n/*\n** Return the size of the common prefix (if any) shared by zPrev and\n** zNext, in bytes. For example, \n**\n**   fts3PrefixCompress(\"abc\", 3, \"abcdef\", 6)   // returns 3\n**   fts3PrefixCompress(\"abX\", 3, \"abcdef\", 6)   // returns 2\n**   fts3PrefixCompress(\"abX\", 3, \"Xbcdef\", 6)   // returns 0\n*/\nstatic int fts3PrefixCompress(\n  const char *zPrev,              /* Buffer containing previous term */\n  int nPrev,                      /* Size of buffer zPrev in bytes */\n  const char *zNext,              /* Buffer containing next term */\n  int nNext                       /* Size of buffer zNext in bytes */\n){\n  int n;\n  UNUSED_PARAMETER(nNext);\n  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);\n  return n;\n}\n\n/*\n** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger\n** (according to memcmp) than the previous term.\n*/\nstatic int fts3NodeAddTerm(\n  Fts3Table *p,                   /* Virtual table handle */\n  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ \n  int isCopyTerm,                 /* True if zTerm/nTerm is transient */\n  const char *zTerm,              /* Pointer to buffer containing term */\n  int nTerm                       /* Size of term in bytes */\n){\n  SegmentNode *pTree = *ppTree;\n  int rc;\n  SegmentNode *pNew;\n\n  /* First try to append the term to the current node. Return early if \n  ** this is possible.\n  */\n  if( pTree ){\n    int nData = pTree->nData;     /* Current size of node in bytes */\n    int nReq = nData;             /* Required space after adding zTerm */\n    int nPrefix;                  /* Number of bytes of prefix compression */\n    int nSuffix;                  /* Suffix length */\n\n    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);\n    nSuffix = nTerm-nPrefix;\n\n    /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of \n    ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when\n    ** compared with BINARY collation. This indicates corruption.  */\n    if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;\n\n    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;\n    if( nReq<=p->nNodeSize || !pTree->zTerm ){\n\n      if( nReq>p->nNodeSize ){\n        /* An unusual case: this is the first term to be added to the node\n        ** and the static node buffer (p->nNodeSize bytes) is not large\n        ** enough. Use a separately malloced buffer instead This wastes\n        ** p->nNodeSize bytes, but since this scenario only comes about when\n        ** the database contain two terms that share a prefix of almost 2KB, \n        ** this is not expected to be a serious problem. \n        */\n        assert( pTree->aData==(char *)&pTree[1] );\n        pTree->aData = (char *)sqlite3_malloc(nReq);\n        if( !pTree->aData ){\n          return SQLITE_NOMEM;\n        }\n      }\n\n      if( pTree->zTerm ){\n        /* There is no prefix-length field for first term in a node */\n        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);\n      }\n\n      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);\n      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);\n      pTree->nData = nData + nSuffix;\n      pTree->nEntry++;\n\n      if( isCopyTerm ){\n        if( pTree->nMalloc<nTerm ){\n          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);\n          if( !zNew ){\n            return SQLITE_NOMEM;\n          }\n          pTree->nMalloc = nTerm*2;\n          pTree->zMalloc = zNew;\n        }\n        pTree->zTerm = pTree->zMalloc;\n        memcpy(pTree->zTerm, zTerm, nTerm);\n        pTree->nTerm = nTerm;\n      }else{\n        pTree->zTerm = (char *)zTerm;\n        pTree->nTerm = nTerm;\n      }\n      return SQLITE_OK;\n    }\n  }\n\n  /* If control flows to here, it was not possible to append zTerm to the\n  ** current node. Create a new node (a right-sibling of the current node).\n  ** If this is the first node in the tree, the term is added to it.\n  **\n  ** Otherwise, the term is not added to the new node, it is left empty for\n  ** now. Instead, the term is inserted into the parent of pTree. If pTree \n  ** has no parent, one is created here.\n  */\n  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);\n  if( !pNew ){\n    return SQLITE_NOMEM;\n  }\n  memset(pNew, 0, sizeof(SegmentNode));\n  pNew->nData = 1 + FTS3_VARINT_MAX;\n  pNew->aData = (char *)&pNew[1];\n\n  if( pTree ){\n    SegmentNode *pParent = pTree->pParent;\n    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);\n    if( pTree->pParent==0 ){\n      pTree->pParent = pParent;\n    }\n    pTree->pRight = pNew;\n    pNew->pLeftmost = pTree->pLeftmost;\n    pNew->pParent = pParent;\n    pNew->zMalloc = pTree->zMalloc;\n    pNew->nMalloc = pTree->nMalloc;\n    pTree->zMalloc = 0;\n  }else{\n    pNew->pLeftmost = pNew;\n    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); \n  }\n\n  *ppTree = pNew;\n  return rc;\n}\n\n/*\n** Helper function for fts3NodeWrite().\n*/\nstatic int fts3TreeFinishNode(\n  SegmentNode *pTree, \n  int iHeight, \n  sqlite3_int64 iLeftChild\n){\n  int nStart;\n  assert( iHeight>=1 && iHeight<128 );\n  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);\n  pTree->aData[nStart] = (char)iHeight;\n  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);\n  return nStart;\n}\n\n/*\n** Write the buffer for the segment node pTree and all of its peers to the\n** database. Then call this function recursively to write the parent of \n** pTree and its peers to the database. \n**\n** Except, if pTree is a root node, do not write it to the database. Instead,\n** set output variables *paRoot and *pnRoot to contain the root node.\n**\n** If successful, SQLITE_OK is returned and output variable *piLast is\n** set to the largest blockid written to the database (or zero if no\n** blocks were written to the db). Otherwise, an SQLite error code is \n** returned.\n*/\nstatic int fts3NodeWrite(\n  Fts3Table *p,                   /* Virtual table handle */\n  SegmentNode *pTree,             /* SegmentNode handle */\n  int iHeight,                    /* Height of this node in tree */\n  sqlite3_int64 iLeaf,            /* Block id of first leaf node */\n  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */\n  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */\n  char **paRoot,                  /* OUT: Data for root node */\n  int *pnRoot                     /* OUT: Size of root node in bytes */\n){\n  int rc = SQLITE_OK;\n\n  if( !pTree->pParent ){\n    /* Root node of the tree. */\n    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);\n    *piLast = iFree-1;\n    *pnRoot = pTree->nData - nStart;\n    *paRoot = &pTree->aData[nStart];\n  }else{\n    SegmentNode *pIter;\n    sqlite3_int64 iNextFree = iFree;\n    sqlite3_int64 iNextLeaf = iLeaf;\n    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){\n      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);\n      int nWrite = pIter->nData - nStart;\n  \n      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);\n      iNextFree++;\n      iNextLeaf += (pIter->nEntry+1);\n    }\n    if( rc==SQLITE_OK ){\n      assert( iNextLeaf==iFree );\n      rc = fts3NodeWrite(\n          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot\n      );\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Free all memory allocations associated with the tree pTree.\n*/\nstatic void fts3NodeFree(SegmentNode *pTree){\n  if( pTree ){\n    SegmentNode *p = pTree->pLeftmost;\n    fts3NodeFree(p->pParent);\n    while( p ){\n      SegmentNode *pRight = p->pRight;\n      if( p->aData!=(char *)&p[1] ){\n        sqlite3_free(p->aData);\n      }\n      assert( pRight==0 || p->zMalloc==0 );\n      sqlite3_free(p->zMalloc);\n      sqlite3_free(p);\n      p = pRight;\n    }\n  }\n}\n\n/*\n** Add a term to the segment being constructed by the SegmentWriter object\n** *ppWriter. When adding the first term to a segment, *ppWriter should\n** be passed NULL. This function will allocate a new SegmentWriter object\n** and return it via the input/output variable *ppWriter in this case.\n**\n** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.\n*/\nstatic int fts3SegWriterAdd(\n  Fts3Table *p,                   /* Virtual table handle */\n  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ \n  int isCopyTerm,                 /* True if buffer zTerm must be copied */\n  const char *zTerm,              /* Pointer to buffer containing term */\n  int nTerm,                      /* Size of term in bytes */\n  const char *aDoclist,           /* Pointer to buffer containing doclist */\n  int nDoclist                    /* Size of doclist in bytes */\n){\n  int nPrefix;                    /* Size of term prefix in bytes */\n  int nSuffix;                    /* Size of term suffix in bytes */\n  int nReq;                       /* Number of bytes required on leaf page */\n  int nData;\n  SegmentWriter *pWriter = *ppWriter;\n\n  if( !pWriter ){\n    int rc;\n    sqlite3_stmt *pStmt;\n\n    /* Allocate the SegmentWriter structure */\n    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));\n    if( !pWriter ) return SQLITE_NOMEM;\n    memset(pWriter, 0, sizeof(SegmentWriter));\n    *ppWriter = pWriter;\n\n    /* Allocate a buffer in which to accumulate data */\n    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);\n    if( !pWriter->aData ) return SQLITE_NOMEM;\n    pWriter->nSize = p->nNodeSize;\n\n    /* Find the next free blockid in the %_segments table */\n    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);\n    if( rc!=SQLITE_OK ) return rc;\n    if( SQLITE_ROW==sqlite3_step(pStmt) ){\n      pWriter->iFree = sqlite3_column_int64(pStmt, 0);\n      pWriter->iFirst = pWriter->iFree;\n    }\n    rc = sqlite3_reset(pStmt);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n  nData = pWriter->nData;\n\n  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);\n  nSuffix = nTerm-nPrefix;\n\n  /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of \n  ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when\n  ** compared with BINARY collation. This indicates corruption.  */\n  if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;\n\n  /* Figure out how many bytes are required by this new entry */\n  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */\n    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */\n    nSuffix +                               /* Term suffix */\n    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */\n    nDoclist;                               /* Doclist data */\n\n  if( nData>0 && nData+nReq>p->nNodeSize ){\n    int rc;\n\n    /* The current leaf node is full. Write it out to the database. */\n    if( pWriter->iFree==LARGEST_INT64 ) return FTS_CORRUPT_VTAB;\n    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);\n    if( rc!=SQLITE_OK ) return rc;\n    p->nLeafAdd++;\n\n    /* Add the current term to the interior node tree. The term added to\n    ** the interior tree must:\n    **\n    **   a) be greater than the largest term on the leaf node just written\n    **      to the database (still available in pWriter->zTerm), and\n    **\n    **   b) be less than or equal to the term about to be added to the new\n    **      leaf node (zTerm/nTerm).\n    **\n    ** In other words, it must be the prefix of zTerm 1 byte longer than\n    ** the common prefix (if any) of zTerm and pWriter->zTerm.\n    */\n    assert( nPrefix<nTerm );\n    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);\n    if( rc!=SQLITE_OK ) return rc;\n\n    nData = 0;\n    pWriter->nTerm = 0;\n\n    nPrefix = 0;\n    nSuffix = nTerm;\n    nReq = 1 +                              /* varint containing prefix size */\n      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */\n      nTerm +                               /* Term suffix */\n      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */\n      nDoclist;                             /* Doclist data */\n  }\n\n  /* Increase the total number of bytes written to account for the new entry. */\n  pWriter->nLeafData += nReq;\n\n  /* If the buffer currently allocated is too small for this entry, realloc\n  ** the buffer to make it large enough.\n  */\n  if( nReq>pWriter->nSize ){\n    char *aNew = sqlite3_realloc(pWriter->aData, nReq);\n    if( !aNew ) return SQLITE_NOMEM;\n    pWriter->aData = aNew;\n    pWriter->nSize = nReq;\n  }\n  assert( nData+nReq<=pWriter->nSize );\n\n  /* Append the prefix-compressed term and doclist to the buffer. */\n  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);\n  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);\n  assert( nSuffix>0 );\n  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);\n  nData += nSuffix;\n  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);\n  assert( nDoclist>0 );\n  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);\n  pWriter->nData = nData + nDoclist;\n\n  /* Save the current term so that it can be used to prefix-compress the next.\n  ** If the isCopyTerm parameter is true, then the buffer pointed to by\n  ** zTerm is transient, so take a copy of the term data. Otherwise, just\n  ** store a copy of the pointer.\n  */\n  if( isCopyTerm ){\n    if( nTerm>pWriter->nMalloc ){\n      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);\n      if( !zNew ){\n        return SQLITE_NOMEM;\n      }\n      pWriter->nMalloc = nTerm*2;\n      pWriter->zMalloc = zNew;\n      pWriter->zTerm = zNew;\n    }\n    assert( pWriter->zTerm==pWriter->zMalloc );\n    assert( nTerm>0 );\n    memcpy(pWriter->zTerm, zTerm, nTerm);\n  }else{\n    pWriter->zTerm = (char *)zTerm;\n  }\n  pWriter->nTerm = nTerm;\n\n  return SQLITE_OK;\n}\n\n/*\n** Flush all data associated with the SegmentWriter object pWriter to the\n** database. This function must be called after all terms have been added\n** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is\n** returned. Otherwise, an SQLite error code.\n*/\nstatic int fts3SegWriterFlush(\n  Fts3Table *p,                   /* Virtual table handle */\n  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */\n  sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */\n  int iIdx                        /* Value for 'idx' column of %_segdir */\n){\n  int rc;                         /* Return code */\n  if( pWriter->pTree ){\n    sqlite3_int64 iLast = 0;      /* Largest block id written to database */\n    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */\n    char *zRoot = NULL;           /* Pointer to buffer containing root node */\n    int nRoot = 0;                /* Size of buffer zRoot */\n\n    iLastLeaf = pWriter->iFree;\n    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);\n    if( rc==SQLITE_OK ){\n      rc = fts3NodeWrite(p, pWriter->pTree, 1,\n          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);\n    }\n    if( rc==SQLITE_OK ){\n      rc = fts3WriteSegdir(p, iLevel, iIdx, \n          pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);\n    }\n  }else{\n    /* The entire tree fits on the root node. Write it to the segdir table. */\n    rc = fts3WriteSegdir(p, iLevel, iIdx, \n        0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);\n  }\n  p->nLeafAdd++;\n  return rc;\n}\n\n/*\n** Release all memory held by the SegmentWriter object passed as the \n** first argument.\n*/\nstatic void fts3SegWriterFree(SegmentWriter *pWriter){\n  if( pWriter ){\n    sqlite3_free(pWriter->aData);\n    sqlite3_free(pWriter->zMalloc);\n    fts3NodeFree(pWriter->pTree);\n    sqlite3_free(pWriter);\n  }\n}\n\n/*\n** The first value in the apVal[] array is assumed to contain an integer.\n** This function tests if there exist any documents with docid values that\n** are different from that integer. i.e. if deleting the document with docid\n** pRowid would mean the FTS3 table were empty.\n**\n** If successful, *pisEmpty is set to true if the table is empty except for\n** document pRowid, or false otherwise, and SQLITE_OK is returned. If an\n** error occurs, an SQLite error code is returned.\n*/\nstatic int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){\n  sqlite3_stmt *pStmt;\n  int rc;\n  if( p->zContentTbl ){\n    /* If using the content=xxx option, assume the table is never empty */\n    *pisEmpty = 0;\n    rc = SQLITE_OK;\n  }else{\n    rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);\n    if( rc==SQLITE_OK ){\n      if( SQLITE_ROW==sqlite3_step(pStmt) ){\n        *pisEmpty = sqlite3_column_int(pStmt, 0);\n      }\n      rc = sqlite3_reset(pStmt);\n    }\n  }\n  return rc;\n}\n\n/*\n** Set *pnMax to the largest segment level in the database for the index\n** iIndex.\n**\n** Segment levels are stored in the 'level' column of the %_segdir table.\n**\n** Return SQLITE_OK if successful, or an SQLite error code if not.\n*/\nstatic int fts3SegmentMaxLevel(\n  Fts3Table *p, \n  int iLangid,\n  int iIndex, \n  sqlite3_int64 *pnMax\n){\n  sqlite3_stmt *pStmt;\n  int rc;\n  assert( iIndex>=0 && iIndex<p->nIndex );\n\n  /* Set pStmt to the compiled version of:\n  **\n  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?\n  **\n  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).\n  */\n  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);\n  if( rc!=SQLITE_OK ) return rc;\n  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));\n  sqlite3_bind_int64(pStmt, 2, \n      getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)\n  );\n  if( SQLITE_ROW==sqlite3_step(pStmt) ){\n    *pnMax = sqlite3_column_int64(pStmt, 0);\n  }\n  return sqlite3_reset(pStmt);\n}\n\n/*\n** iAbsLevel is an absolute level that may be assumed to exist within\n** the database. This function checks if it is the largest level number\n** within its index. Assuming no error occurs, *pbMax is set to 1 if\n** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK\n** is returned. If an error occurs, an error code is returned and the\n** final value of *pbMax is undefined.\n*/\nstatic int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){\n\n  /* Set pStmt to the compiled version of:\n  **\n  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?\n  **\n  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).\n  */\n  sqlite3_stmt *pStmt;\n  int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);\n  if( rc!=SQLITE_OK ) return rc;\n  sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);\n  sqlite3_bind_int64(pStmt, 2, \n      (((u64)iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL\n  );\n\n  *pbMax = 0;\n  if( SQLITE_ROW==sqlite3_step(pStmt) ){\n    *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;\n  }\n  return sqlite3_reset(pStmt);\n}\n\n/*\n** Delete all entries in the %_segments table associated with the segment\n** opened with seg-reader pSeg. This function does not affect the contents\n** of the %_segdir table.\n*/\nstatic int fts3DeleteSegment(\n  Fts3Table *p,                   /* FTS table handle */\n  Fts3SegReader *pSeg             /* Segment to delete */\n){\n  int rc = SQLITE_OK;             /* Return code */\n  if( pSeg->iStartBlock ){\n    sqlite3_stmt *pDelete;        /* SQL statement to delete rows */\n    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);\n      sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);\n      sqlite3_step(pDelete);\n      rc = sqlite3_reset(pDelete);\n    }\n  }\n  return rc;\n}\n\n/*\n** This function is used after merging multiple segments into a single large\n** segment to delete the old, now redundant, segment b-trees. Specifically,\n** it:\n** \n**   1) Deletes all %_segments entries for the segments associated with \n**      each of the SegReader objects in the array passed as the third \n**      argument, and\n**\n**   2) deletes all %_segdir entries with level iLevel, or all %_segdir\n**      entries regardless of level if (iLevel<0).\n**\n** SQLITE_OK is returned if successful, otherwise an SQLite error code.\n*/\nstatic int fts3DeleteSegdir(\n  Fts3Table *p,                   /* Virtual table handle */\n  int iLangid,                    /* Language id */\n  int iIndex,                     /* Index for p->aIndex */\n  int iLevel,                     /* Level of %_segdir entries to delete */\n  Fts3SegReader **apSegment,      /* Array of SegReader objects */\n  int nReader                     /* Size of array apSegment */\n){\n  int rc = SQLITE_OK;             /* Return Code */\n  int i;                          /* Iterator variable */\n  sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */\n\n  for(i=0; rc==SQLITE_OK && i<nReader; i++){\n    rc = fts3DeleteSegment(p, apSegment[i]);\n  }\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );\n  if( iLevel==FTS3_SEGCURSOR_ALL ){\n    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));\n      sqlite3_bind_int64(pDelete, 2, \n          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)\n      );\n    }\n  }else{\n    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int64(\n          pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)\n      );\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    sqlite3_step(pDelete);\n    rc = sqlite3_reset(pDelete);\n  }\n\n  return rc;\n}\n\n/*\n** When this function is called, buffer *ppList (size *pnList bytes) contains \n** a position list that may (or may not) feature multiple columns. This\n** function adjusts the pointer *ppList and the length *pnList so that they\n** identify the subset of the position list that corresponds to column iCol.\n**\n** If there are no entries in the input position list for column iCol, then\n** *pnList is set to zero before returning.\n**\n** If parameter bZero is non-zero, then any part of the input list following\n** the end of the output list is zeroed before returning.\n*/\nstatic void fts3ColumnFilter(\n  int iCol,                       /* Column to filter on */\n  int bZero,                      /* Zero out anything following *ppList */\n  char **ppList,                  /* IN/OUT: Pointer to position list */\n  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */\n){\n  char *pList = *ppList;\n  int nList = *pnList;\n  char *pEnd = &pList[nList];\n  int iCurrent = 0;\n  char *p = pList;\n\n  assert( iCol>=0 );\n  while( 1 ){\n    char c = 0;\n    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;\n  \n    if( iCol==iCurrent ){\n      nList = (int)(p - pList);\n      break;\n    }\n\n    nList -= (int)(p - pList);\n    pList = p;\n    if( nList<=0 ){\n      break;\n    }\n    p = &pList[1];\n    p += fts3GetVarint32(p, &iCurrent);\n  }\n\n  if( bZero && (pEnd - &pList[nList])>0){\n    memset(&pList[nList], 0, pEnd - &pList[nList]);\n  }\n  *ppList = pList;\n  *pnList = nList;\n}\n\n/*\n** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any\n** existing data). Grow the buffer if required.\n**\n** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered\n** trying to resize the buffer, return SQLITE_NOMEM.\n*/\nstatic int fts3MsrBufferData(\n  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */\n  char *pList,\n  int nList\n){\n  if( nList>pMsr->nBuffer ){\n    char *pNew;\n    pMsr->nBuffer = nList*2;\n    pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);\n    if( !pNew ) return SQLITE_NOMEM;\n    pMsr->aBuffer = pNew;\n  }\n\n  assert( nList>0 );\n  memcpy(pMsr->aBuffer, pList, nList);\n  return SQLITE_OK;\n}\n\nSQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(\n  Fts3Table *p,                   /* Virtual table handle */\n  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */\n  sqlite3_int64 *piDocid,         /* OUT: Docid value */\n  char **paPoslist,               /* OUT: Pointer to position list */\n  int *pnPoslist                  /* OUT: Size of position list in bytes */\n){\n  int nMerge = pMsr->nAdvance;\n  Fts3SegReader **apSegment = pMsr->apSegment;\n  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (\n    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp\n  );\n\n  if( nMerge==0 ){\n    *paPoslist = 0;\n    return SQLITE_OK;\n  }\n\n  while( 1 ){\n    Fts3SegReader *pSeg;\n    pSeg = pMsr->apSegment[0];\n\n    if( pSeg->pOffsetList==0 ){\n      *paPoslist = 0;\n      break;\n    }else{\n      int rc;\n      char *pList;\n      int nList;\n      int j;\n      sqlite3_int64 iDocid = apSegment[0]->iDocid;\n\n      rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);\n      j = 1;\n      while( rc==SQLITE_OK \n        && j<nMerge\n        && apSegment[j]->pOffsetList\n        && apSegment[j]->iDocid==iDocid\n      ){\n        rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);\n        j++;\n      }\n      if( rc!=SQLITE_OK ) return rc;\n      fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);\n\n      if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){\n        rc = fts3MsrBufferData(pMsr, pList, nList+1);\n        if( rc!=SQLITE_OK ) return rc;\n        assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );\n        pList = pMsr->aBuffer;\n      }\n\n      if( pMsr->iColFilter>=0 ){\n        fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);\n      }\n\n      if( nList>0 ){\n        *paPoslist = pList;\n        *piDocid = iDocid;\n        *pnPoslist = nList;\n        break;\n      }\n    }\n  }\n\n  return SQLITE_OK;\n}\n\nstatic int fts3SegReaderStart(\n  Fts3Table *p,                   /* Virtual table handle */\n  Fts3MultiSegReader *pCsr,       /* Cursor object */\n  const char *zTerm,              /* Term searched for (or NULL) */\n  int nTerm                       /* Length of zTerm in bytes */\n){\n  int i;\n  int nSeg = pCsr->nSegment;\n\n  /* If the Fts3SegFilter defines a specific term (or term prefix) to search \n  ** for, then advance each segment iterator until it points to a term of\n  ** equal or greater value than the specified term. This prevents many\n  ** unnecessary merge/sort operations for the case where single segment\n  ** b-tree leaf nodes contain more than one term.\n  */\n  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){\n    int res = 0;\n    Fts3SegReader *pSeg = pCsr->apSegment[i];\n    do {\n      int rc = fts3SegReaderNext(p, pSeg, 0);\n      if( rc!=SQLITE_OK ) return rc;\n    }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );\n\n    if( pSeg->bLookup && res!=0 ){\n      fts3SegReaderSetEof(pSeg);\n    }\n  }\n  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);\n\n  return SQLITE_OK;\n}\n\nSQLITE_PRIVATE int sqlite3Fts3SegReaderStart(\n  Fts3Table *p,                   /* Virtual table handle */\n  Fts3MultiSegReader *pCsr,       /* Cursor object */\n  Fts3SegFilter *pFilter          /* Restrictions on range of iteration */\n){\n  pCsr->pFilter = pFilter;\n  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);\n}\n\nSQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(\n  Fts3Table *p,                   /* Virtual table handle */\n  Fts3MultiSegReader *pCsr,       /* Cursor object */\n  int iCol,                       /* Column to match on. */\n  const char *zTerm,              /* Term to iterate through a doclist for */\n  int nTerm                       /* Number of bytes in zTerm */\n){\n  int i;\n  int rc;\n  int nSegment = pCsr->nSegment;\n  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (\n    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp\n  );\n\n  assert( pCsr->pFilter==0 );\n  assert( zTerm && nTerm>0 );\n\n  /* Advance each segment iterator until it points to the term zTerm/nTerm. */\n  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);\n  if( rc!=SQLITE_OK ) return rc;\n\n  /* Determine how many of the segments actually point to zTerm/nTerm. */\n  for(i=0; i<nSegment; i++){\n    Fts3SegReader *pSeg = pCsr->apSegment[i];\n    if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){\n      break;\n    }\n  }\n  pCsr->nAdvance = i;\n\n  /* Advance each of the segments to point to the first docid. */\n  for(i=0; i<pCsr->nAdvance; i++){\n    rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);\n\n  assert( iCol<0 || iCol<p->nColumn );\n  pCsr->iColFilter = iCol;\n\n  return SQLITE_OK;\n}\n\n/*\n** This function is called on a MultiSegReader that has been started using\n** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also\n** have been made. Calling this function puts the MultiSegReader in such\n** a state that if the next two calls are:\n**\n**   sqlite3Fts3SegReaderStart()\n**   sqlite3Fts3SegReaderStep()\n**\n** then the entire doclist for the term is available in \n** MultiSegReader.aDoclist/nDoclist.\n*/\nSQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){\n  int i;                          /* Used to iterate through segment-readers */\n\n  assert( pCsr->zTerm==0 );\n  assert( pCsr->nTerm==0 );\n  assert( pCsr->aDoclist==0 );\n  assert( pCsr->nDoclist==0 );\n\n  pCsr->nAdvance = 0;\n  pCsr->bRestart = 1;\n  for(i=0; i<pCsr->nSegment; i++){\n    pCsr->apSegment[i]->pOffsetList = 0;\n    pCsr->apSegment[i]->nOffsetList = 0;\n    pCsr->apSegment[i]->iDocid = 0;\n  }\n\n  return SQLITE_OK;\n}\n\n\nSQLITE_PRIVATE int sqlite3Fts3SegReaderStep(\n  Fts3Table *p,                   /* Virtual table handle */\n  Fts3MultiSegReader *pCsr        /* Cursor object */\n){\n  int rc = SQLITE_OK;\n\n  int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);\n  int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);\n  int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);\n  int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);\n  int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);\n  int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);\n\n  Fts3SegReader **apSegment = pCsr->apSegment;\n  int nSegment = pCsr->nSegment;\n  Fts3SegFilter *pFilter = pCsr->pFilter;\n  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (\n    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp\n  );\n\n  if( pCsr->nSegment==0 ) return SQLITE_OK;\n\n  do {\n    int nMerge;\n    int i;\n  \n    /* Advance the first pCsr->nAdvance entries in the apSegment[] array\n    ** forward. Then sort the list in order of current term again.  \n    */\n    for(i=0; i<pCsr->nAdvance; i++){\n      Fts3SegReader *pSeg = apSegment[i];\n      if( pSeg->bLookup ){\n        fts3SegReaderSetEof(pSeg);\n      }else{\n        rc = fts3SegReaderNext(p, pSeg, 0);\n      }\n      if( rc!=SQLITE_OK ) return rc;\n    }\n    fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);\n    pCsr->nAdvance = 0;\n\n    /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */\n    assert( rc==SQLITE_OK );\n    if( apSegment[0]->aNode==0 ) break;\n\n    pCsr->nTerm = apSegment[0]->nTerm;\n    pCsr->zTerm = apSegment[0]->zTerm;\n\n    /* If this is a prefix-search, and if the term that apSegment[0] points\n    ** to does not share a suffix with pFilter->zTerm/nTerm, then all \n    ** required callbacks have been made. In this case exit early.\n    **\n    ** Similarly, if this is a search for an exact match, and the first term\n    ** of segment apSegment[0] is not a match, exit early.\n    */\n    if( pFilter->zTerm && !isScan ){\n      if( pCsr->nTerm<pFilter->nTerm \n       || (!isPrefix && pCsr->nTerm>pFilter->nTerm)\n       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) \n      ){\n        break;\n      }\n    }\n\n    nMerge = 1;\n    while( nMerge<nSegment \n        && apSegment[nMerge]->aNode\n        && apSegment[nMerge]->nTerm==pCsr->nTerm \n        && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)\n    ){\n      nMerge++;\n    }\n\n    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );\n    if( nMerge==1 \n     && !isIgnoreEmpty \n     && !isFirst \n     && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)\n    ){\n      pCsr->nDoclist = apSegment[0]->nDoclist;\n      if( fts3SegReaderIsPending(apSegment[0]) ){\n        rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);\n        pCsr->aDoclist = pCsr->aBuffer;\n      }else{\n        pCsr->aDoclist = apSegment[0]->aDoclist;\n      }\n      if( rc==SQLITE_OK ) rc = SQLITE_ROW;\n    }else{\n      int nDoclist = 0;           /* Size of doclist */\n      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */\n\n      /* The current term of the first nMerge entries in the array\n      ** of Fts3SegReader objects is the same. The doclists must be merged\n      ** and a single term returned with the merged doclist.\n      */\n      for(i=0; i<nMerge; i++){\n        fts3SegReaderFirstDocid(p, apSegment[i]);\n      }\n      fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);\n      while( apSegment[0]->pOffsetList ){\n        int j;                    /* Number of segments that share a docid */\n        char *pList = 0;\n        int nList = 0;\n        int nByte;\n        sqlite3_int64 iDocid = apSegment[0]->iDocid;\n        fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);\n        j = 1;\n        while( j<nMerge\n            && apSegment[j]->pOffsetList\n            && apSegment[j]->iDocid==iDocid\n        ){\n          fts3SegReaderNextDocid(p, apSegment[j], 0, 0);\n          j++;\n        }\n\n        if( isColFilter ){\n          fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);\n        }\n\n        if( !isIgnoreEmpty || nList>0 ){\n\n          /* Calculate the 'docid' delta value to write into the merged \n          ** doclist. */\n          sqlite3_int64 iDelta;\n          if( p->bDescIdx && nDoclist>0 ){\n            if( iPrev<=iDocid ) return FTS_CORRUPT_VTAB;\n            iDelta = (i64)((u64)iPrev - (u64)iDocid);\n          }else{\n            if( nDoclist>0 && iPrev>=iDocid ) return FTS_CORRUPT_VTAB;\n            iDelta = (i64)((u64)iDocid - (u64)iPrev);\n          }\n\n          nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);\n          if( nDoclist+nByte>pCsr->nBuffer ){\n            char *aNew;\n            pCsr->nBuffer = (nDoclist+nByte)*2;\n            aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);\n            if( !aNew ){\n              return SQLITE_NOMEM;\n            }\n            pCsr->aBuffer = aNew;\n          }\n\n          if( isFirst ){\n            char *a = &pCsr->aBuffer[nDoclist];\n            int nWrite;\n           \n            nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);\n            if( nWrite ){\n              iPrev = iDocid;\n              nDoclist += nWrite;\n            }\n          }else{\n            nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);\n            iPrev = iDocid;\n            if( isRequirePos ){\n              memcpy(&pCsr->aBuffer[nDoclist], pList, nList);\n              nDoclist += nList;\n              pCsr->aBuffer[nDoclist++] = '\\0';\n            }\n          }\n        }\n\n        fts3SegReaderSort(apSegment, nMerge, j, xCmp);\n      }\n      if( nDoclist>0 ){\n        pCsr->aDoclist = pCsr->aBuffer;\n        pCsr->nDoclist = nDoclist;\n        rc = SQLITE_ROW;\n      }\n    }\n    pCsr->nAdvance = nMerge;\n  }while( rc==SQLITE_OK );\n\n  return rc;\n}\n\n\nSQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(\n  Fts3MultiSegReader *pCsr       /* Cursor object */\n){\n  if( pCsr ){\n    int i;\n    for(i=0; i<pCsr->nSegment; i++){\n      sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);\n    }\n    sqlite3_free(pCsr->apSegment);\n    sqlite3_free(pCsr->aBuffer);\n\n    pCsr->nSegment = 0;\n    pCsr->apSegment = 0;\n    pCsr->aBuffer = 0;\n  }\n}\n\n/*\n** Decode the \"end_block\" field, selected by column iCol of the SELECT \n** statement passed as the first argument. \n**\n** The \"end_block\" field may contain either an integer, or a text field\n** containing the text representation of two non-negative integers separated \n** by one or more space (0x20) characters. In the first case, set *piEndBlock \n** to the integer value and *pnByte to zero before returning. In the second, \n** set *piEndBlock to the first value and *pnByte to the second.\n*/\nstatic void fts3ReadEndBlockField(\n  sqlite3_stmt *pStmt, \n  int iCol, \n  i64 *piEndBlock,\n  i64 *pnByte\n){\n  const unsigned char *zText = sqlite3_column_text(pStmt, iCol);\n  if( zText ){\n    int i;\n    int iMul = 1;\n    u64 iVal = 0;\n    for(i=0; zText[i]>='0' && zText[i]<='9'; i++){\n      iVal = iVal*10 + (zText[i] - '0');\n    }\n    *piEndBlock = (i64)iVal;\n    while( zText[i]==' ' ) i++;\n    iVal = 0;\n    if( zText[i]=='-' ){\n      i++;\n      iMul = -1;\n    }\n    for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){\n      iVal = iVal*10 + (zText[i] - '0');\n    }\n    *pnByte = ((i64)iVal * (i64)iMul);\n  }\n}\n\n\n/*\n** A segment of size nByte bytes has just been written to absolute level\n** iAbsLevel. Promote any segments that should be promoted as a result.\n*/\nstatic int fts3PromoteSegments(\n  Fts3Table *p,                   /* FTS table handle */\n  sqlite3_int64 iAbsLevel,        /* Absolute level just updated */\n  sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */\n){\n  int rc = SQLITE_OK;\n  sqlite3_stmt *pRange;\n\n  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);\n\n  if( rc==SQLITE_OK ){\n    int bOk = 0;\n    i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;\n    i64 nLimit = (nByte*3)/2;\n\n    /* Loop through all entries in the %_segdir table corresponding to \n    ** segments in this index on levels greater than iAbsLevel. If there is\n    ** at least one such segment, and it is possible to determine that all \n    ** such segments are smaller than nLimit bytes in size, they will be \n    ** promoted to level iAbsLevel.  */\n    sqlite3_bind_int64(pRange, 1, iAbsLevel+1);\n    sqlite3_bind_int64(pRange, 2, iLast);\n    while( SQLITE_ROW==sqlite3_step(pRange) ){\n      i64 nSize = 0, dummy;\n      fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);\n      if( nSize<=0 || nSize>nLimit ){\n        /* If nSize==0, then the %_segdir.end_block field does not not \n        ** contain a size value. This happens if it was written by an\n        ** old version of FTS. In this case it is not possible to determine\n        ** the size of the segment, and so segment promotion does not\n        ** take place.  */\n        bOk = 0;\n        break;\n      }\n      bOk = 1;\n    }\n    rc = sqlite3_reset(pRange);\n\n    if( bOk ){\n      int iIdx = 0;\n      sqlite3_stmt *pUpdate1 = 0;\n      sqlite3_stmt *pUpdate2 = 0;\n\n      if( rc==SQLITE_OK ){\n        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);\n      }\n      if( rc==SQLITE_OK ){\n        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);\n      }\n\n      if( rc==SQLITE_OK ){\n\n        /* Loop through all %_segdir entries for segments in this index with\n        ** levels equal to or greater than iAbsLevel. As each entry is visited,\n        ** updated it to set (level = -1) and (idx = N), where N is 0 for the\n        ** oldest segment in the range, 1 for the next oldest, and so on.\n        **\n        ** In other words, move all segments being promoted to level -1,\n        ** setting the \"idx\" fields as appropriate to keep them in the same\n        ** order. The contents of level -1 (which is never used, except\n        ** transiently here), will be moved back to level iAbsLevel below.  */\n        sqlite3_bind_int64(pRange, 1, iAbsLevel);\n        while( SQLITE_ROW==sqlite3_step(pRange) ){\n          sqlite3_bind_int(pUpdate1, 1, iIdx++);\n          sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));\n          sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));\n          sqlite3_step(pUpdate1);\n          rc = sqlite3_reset(pUpdate1);\n          if( rc!=SQLITE_OK ){\n            sqlite3_reset(pRange);\n            break;\n          }\n        }\n      }\n      if( rc==SQLITE_OK ){\n        rc = sqlite3_reset(pRange);\n      }\n\n      /* Move level -1 to level iAbsLevel */\n      if( rc==SQLITE_OK ){\n        sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);\n        sqlite3_step(pUpdate2);\n        rc = sqlite3_reset(pUpdate2);\n      }\n    }\n  }\n\n\n  return rc;\n}\n\n/*\n** Merge all level iLevel segments in the database into a single \n** iLevel+1 segment. Or, if iLevel<0, merge all segments into a\n** single segment with a level equal to the numerically largest level \n** currently present in the database.\n**\n** If this function is called with iLevel<0, but there is only one\n** segment in the database, SQLITE_DONE is returned immediately. \n** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, \n** an SQLite error code is returned.\n*/\nstatic int fts3SegmentMerge(\n  Fts3Table *p, \n  int iLangid,                    /* Language id to merge */\n  int iIndex,                     /* Index in p->aIndex[] to merge */\n  int iLevel                      /* Level to merge */\n){\n  int rc;                         /* Return code */\n  int iIdx = 0;                   /* Index of new segment */\n  sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */\n  SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */\n  Fts3SegFilter filter;           /* Segment term filter condition */\n  Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */\n  int bIgnoreEmpty = 0;           /* True to ignore empty segments */\n  i64 iMaxLevel = 0;              /* Max level number for this index/langid */\n\n  assert( iLevel==FTS3_SEGCURSOR_ALL\n       || iLevel==FTS3_SEGCURSOR_PENDING\n       || iLevel>=0\n  );\n  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );\n  assert( iIndex>=0 && iIndex<p->nIndex );\n\n  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);\n  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;\n\n  if( iLevel!=FTS3_SEGCURSOR_PENDING ){\n    rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);\n    if( rc!=SQLITE_OK ) goto finished;\n  }\n\n  if( iLevel==FTS3_SEGCURSOR_ALL ){\n    /* This call is to merge all segments in the database to a single\n    ** segment. The level of the new segment is equal to the numerically\n    ** greatest segment level currently present in the database for this\n    ** index. The idx of the new segment is always 0.  */\n    if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){\n      rc = SQLITE_DONE;\n      goto finished;\n    }\n    iNewLevel = iMaxLevel;\n    bIgnoreEmpty = 1;\n\n  }else{\n    /* This call is to merge all segments at level iLevel. find the next\n    ** available segment index at level iLevel+1. The call to\n    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to \n    ** a single iLevel+2 segment if necessary.  */\n    assert( FTS3_SEGCURSOR_PENDING==-1 );\n    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);\n    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);\n    bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);\n  }\n  if( rc!=SQLITE_OK ) goto finished;\n\n  assert( csr.nSegment>0 );\n  assert_fts3_nc( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );\n  assert_fts3_nc( \n    iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) \n  );\n\n  memset(&filter, 0, sizeof(Fts3SegFilter));\n  filter.flags = FTS3_SEGMENT_REQUIRE_POS;\n  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);\n\n  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);\n  while( SQLITE_OK==rc ){\n    rc = sqlite3Fts3SegReaderStep(p, &csr);\n    if( rc!=SQLITE_ROW ) break;\n    rc = fts3SegWriterAdd(p, &pWriter, 1, \n        csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);\n  }\n  if( rc!=SQLITE_OK ) goto finished;\n  assert_fts3_nc( pWriter || bIgnoreEmpty );\n\n  if( iLevel!=FTS3_SEGCURSOR_PENDING ){\n    rc = fts3DeleteSegdir(\n        p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment\n    );\n    if( rc!=SQLITE_OK ) goto finished;\n  }\n  if( pWriter ){\n    rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);\n    if( rc==SQLITE_OK ){\n      if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){\n        rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);\n      }\n    }\n  }\n\n finished:\n  fts3SegWriterFree(pWriter);\n  sqlite3Fts3SegReaderFinish(&csr);\n  return rc;\n}\n\n\n/* \n** Flush the contents of pendingTerms to level 0 segments. \n*/\nSQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){\n  int rc = SQLITE_OK;\n  int i;\n        \n  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){\n    rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);\n    if( rc==SQLITE_DONE ) rc = SQLITE_OK;\n  }\n  sqlite3Fts3PendingTermsClear(p);\n\n  /* Determine the auto-incr-merge setting if unknown.  If enabled,\n  ** estimate the number of leaf blocks of content to be written\n  */\n  if( rc==SQLITE_OK && p->bHasStat\n   && p->nAutoincrmerge==0xff && p->nLeafAdd>0\n  ){\n    sqlite3_stmt *pStmt = 0;\n    rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);\n      rc = sqlite3_step(pStmt);\n      if( rc==SQLITE_ROW ){\n        p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);\n        if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;\n      }else if( rc==SQLITE_DONE ){\n        p->nAutoincrmerge = 0;\n      }\n      rc = sqlite3_reset(pStmt);\n    }\n  }\n  return rc;\n}\n\n/*\n** Encode N integers as varints into a blob.\n*/\nstatic void fts3EncodeIntArray(\n  int N,             /* The number of integers to encode */\n  u32 *a,            /* The integer values */\n  char *zBuf,        /* Write the BLOB here */\n  int *pNBuf         /* Write number of bytes if zBuf[] used here */\n){\n  int i, j;\n  for(i=j=0; i<N; i++){\n    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);\n  }\n  *pNBuf = j;\n}\n\n/*\n** Decode a blob of varints into N integers\n*/\nstatic void fts3DecodeIntArray(\n  int N,             /* The number of integers to decode */\n  u32 *a,            /* Write the integer values */\n  const char *zBuf,  /* The BLOB containing the varints */\n  int nBuf           /* size of the BLOB */\n){\n  int i = 0;\n  if( nBuf && (zBuf[nBuf-1]&0x80)==0 ){\n    int j;\n    for(i=j=0; i<N && j<nBuf; i++){\n      sqlite3_int64 x;\n      j += sqlite3Fts3GetVarint(&zBuf[j], &x);\n      a[i] = (u32)(x & 0xffffffff);\n    }\n  }\n  while( i<N ) a[i++] = 0;\n}\n\n/*\n** Insert the sizes (in tokens) for each column of the document\n** with docid equal to p->iPrevDocid.  The sizes are encoded as\n** a blob of varints.\n*/\nstatic void fts3InsertDocsize(\n  int *pRC,                       /* Result code */\n  Fts3Table *p,                   /* Table into which to insert */\n  u32 *aSz                        /* Sizes of each column, in tokens */\n){\n  char *pBlob;             /* The BLOB encoding of the document size */\n  int nBlob;               /* Number of bytes in the BLOB */\n  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */\n  int rc;                  /* Result code from subfunctions */\n\n  if( *pRC ) return;\n  pBlob = sqlite3_malloc64( 10*(sqlite3_int64)p->nColumn );\n  if( pBlob==0 ){\n    *pRC = SQLITE_NOMEM;\n    return;\n  }\n  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);\n  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);\n  if( rc ){\n    sqlite3_free(pBlob);\n    *pRC = rc;\n    return;\n  }\n  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);\n  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);\n  sqlite3_step(pStmt);\n  *pRC = sqlite3_reset(pStmt);\n}\n\n/*\n** Record 0 of the %_stat table contains a blob consisting of N varints,\n** where N is the number of user defined columns in the fts3 table plus\n** two. If nCol is the number of user defined columns, then values of the \n** varints are set as follows:\n**\n**   Varint 0:       Total number of rows in the table.\n**\n**   Varint 1..nCol: For each column, the total number of tokens stored in\n**                   the column for all rows of the table.\n**\n**   Varint 1+nCol:  The total size, in bytes, of all text values in all\n**                   columns of all rows of the table.\n**\n*/\nstatic void fts3UpdateDocTotals(\n  int *pRC,                       /* The result code */\n  Fts3Table *p,                   /* Table being updated */\n  u32 *aSzIns,                    /* Size increases */\n  u32 *aSzDel,                    /* Size decreases */\n  int nChng                       /* Change in the number of documents */\n){\n  char *pBlob;             /* Storage for BLOB written into %_stat */\n  int nBlob;               /* Size of BLOB written into %_stat */\n  u32 *a;                  /* Array of integers that becomes the BLOB */\n  sqlite3_stmt *pStmt;     /* Statement for reading and writing */\n  int i;                   /* Loop counter */\n  int rc;                  /* Result code from subfunctions */\n\n  const int nStat = p->nColumn+2;\n\n  if( *pRC ) return;\n  a = sqlite3_malloc64( (sizeof(u32)+10)*(sqlite3_int64)nStat );\n  if( a==0 ){\n    *pRC = SQLITE_NOMEM;\n    return;\n  }\n  pBlob = (char*)&a[nStat];\n  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);\n  if( rc ){\n    sqlite3_free(a);\n    *pRC = rc;\n    return;\n  }\n  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);\n  if( sqlite3_step(pStmt)==SQLITE_ROW ){\n    fts3DecodeIntArray(nStat, a,\n         sqlite3_column_blob(pStmt, 0),\n         sqlite3_column_bytes(pStmt, 0));\n  }else{\n    memset(a, 0, sizeof(u32)*(nStat) );\n  }\n  rc = sqlite3_reset(pStmt);\n  if( rc!=SQLITE_OK ){\n    sqlite3_free(a);\n    *pRC = rc;\n    return;\n  }\n  if( nChng<0 && a[0]<(u32)(-nChng) ){\n    a[0] = 0;\n  }else{\n    a[0] += nChng;\n  }\n  for(i=0; i<p->nColumn+1; i++){\n    u32 x = a[i+1];\n    if( x+aSzIns[i] < aSzDel[i] ){\n      x = 0;\n    }else{\n      x = x + aSzIns[i] - aSzDel[i];\n    }\n    a[i+1] = x;\n  }\n  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);\n  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);\n  if( rc ){\n    sqlite3_free(a);\n    *pRC = rc;\n    return;\n  }\n  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);\n  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);\n  sqlite3_step(pStmt);\n  *pRC = sqlite3_reset(pStmt);\n  sqlite3_bind_null(pStmt, 2);\n  sqlite3_free(a);\n}\n\n/*\n** Merge the entire database so that there is one segment for each \n** iIndex/iLangid combination.\n*/\nstatic int fts3DoOptimize(Fts3Table *p, int bReturnDone){\n  int bSeenDone = 0;\n  int rc;\n  sqlite3_stmt *pAllLangid = 0;\n\n  rc = sqlite3Fts3PendingTermsFlush(p);\n  if( rc==SQLITE_OK ){\n    rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);\n  }\n  if( rc==SQLITE_OK ){\n    int rc2;\n    sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);\n    sqlite3_bind_int(pAllLangid, 2, p->nIndex);\n    while( sqlite3_step(pAllLangid)==SQLITE_ROW ){\n      int i;\n      int iLangid = sqlite3_column_int(pAllLangid, 0);\n      for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){\n        rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);\n        if( rc==SQLITE_DONE ){\n          bSeenDone = 1;\n          rc = SQLITE_OK;\n        }\n      }\n    }\n    rc2 = sqlite3_reset(pAllLangid);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n\n  sqlite3Fts3SegmentsClose(p);\n\n  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;\n}\n\n/*\n** This function is called when the user executes the following statement:\n**\n**     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');\n**\n** The entire FTS index is discarded and rebuilt. If the table is one \n** created using the content=xxx option, then the new index is based on\n** the current contents of the xxx table. Otherwise, it is rebuilt based\n** on the contents of the %_content table.\n*/\nstatic int fts3DoRebuild(Fts3Table *p){\n  int rc;                         /* Return Code */\n\n  rc = fts3DeleteAll(p, 0);\n  if( rc==SQLITE_OK ){\n    u32 *aSz = 0;\n    u32 *aSzIns = 0;\n    u32 *aSzDel = 0;\n    sqlite3_stmt *pStmt = 0;\n    int nEntry = 0;\n\n    /* Compose and prepare an SQL statement to loop through the content table */\n    char *zSql = sqlite3_mprintf(\"SELECT %s\" , p->zReadExprlist);\n    if( !zSql ){\n      rc = SQLITE_NOMEM;\n    }else{\n      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);\n      sqlite3_free(zSql);\n    }\n\n    if( rc==SQLITE_OK ){\n      sqlite3_int64 nByte = sizeof(u32) * ((sqlite3_int64)p->nColumn+1)*3;\n      aSz = (u32 *)sqlite3_malloc64(nByte);\n      if( aSz==0 ){\n        rc = SQLITE_NOMEM;\n      }else{\n        memset(aSz, 0, nByte);\n        aSzIns = &aSz[p->nColumn+1];\n        aSzDel = &aSzIns[p->nColumn+1];\n      }\n    }\n\n    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){\n      int iCol;\n      int iLangid = langidFromSelect(p, pStmt);\n      rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));\n      memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));\n      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){\n        if( p->abNotindexed[iCol]==0 ){\n          const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);\n          rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);\n          aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);\n        }\n      }\n      if( p->bHasDocsize ){\n        fts3InsertDocsize(&rc, p, aSz);\n      }\n      if( rc!=SQLITE_OK ){\n        sqlite3_finalize(pStmt);\n        pStmt = 0;\n      }else{\n        nEntry++;\n        for(iCol=0; iCol<=p->nColumn; iCol++){\n          aSzIns[iCol] += aSz[iCol];\n        }\n      }\n    }\n    if( p->bFts4 ){\n      fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);\n    }\n    sqlite3_free(aSz);\n\n    if( pStmt ){\n      int rc2 = sqlite3_finalize(pStmt);\n      if( rc==SQLITE_OK ){\n        rc = rc2;\n      }\n    }\n  }\n\n  return rc;\n}\n\n\n/*\n** This function opens a cursor used to read the input data for an \n** incremental merge operation. Specifically, it opens a cursor to scan\n** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute \n** level iAbsLevel.\n*/\nstatic int fts3IncrmergeCsr(\n  Fts3Table *p,                   /* FTS3 table handle */\n  sqlite3_int64 iAbsLevel,        /* Absolute level to open */\n  int nSeg,                       /* Number of segments to merge */\n  Fts3MultiSegReader *pCsr        /* Cursor object to populate */\n){\n  int rc;                         /* Return Code */\n  sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */  \n  sqlite3_int64 nByte;            /* Bytes allocated at pCsr->apSegment[] */\n\n  /* Allocate space for the Fts3MultiSegReader.aCsr[] array */\n  memset(pCsr, 0, sizeof(*pCsr));\n  nByte = sizeof(Fts3SegReader *) * nSeg;\n  pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc64(nByte);\n\n  if( pCsr->apSegment==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    memset(pCsr->apSegment, 0, nByte);\n    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);\n  }\n  if( rc==SQLITE_OK ){\n    int i;\n    int rc2;\n    sqlite3_bind_int64(pStmt, 1, iAbsLevel);\n    assert( pCsr->nSegment==0 );\n    for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){\n      rc = sqlite3Fts3SegReaderNew(i, 0,\n          sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */\n          sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */\n          sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */\n          sqlite3_column_blob(pStmt, 4),         /* segdir.root */\n          sqlite3_column_bytes(pStmt, 4),        /* segdir.root */\n          &pCsr->apSegment[i]\n      );\n      pCsr->nSegment++;\n    }\n    rc2 = sqlite3_reset(pStmt);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n\n  return rc;\n}\n\ntypedef struct IncrmergeWriter IncrmergeWriter;\ntypedef struct NodeWriter NodeWriter;\ntypedef struct Blob Blob;\ntypedef struct NodeReader NodeReader;\n\n/*\n** An instance of the following structure is used as a dynamic buffer\n** to build up nodes or other blobs of data in.\n**\n** The function blobGrowBuffer() is used to extend the allocation.\n*/\nstruct Blob {\n  char *a;                        /* Pointer to allocation */\n  int n;                          /* Number of valid bytes of data in a[] */\n  int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */\n};\n\n/*\n** This structure is used to build up buffers containing segment b-tree \n** nodes (blocks).\n*/\nstruct NodeWriter {\n  sqlite3_int64 iBlock;           /* Current block id */\n  Blob key;                       /* Last key written to the current block */\n  Blob block;                     /* Current block image */\n};\n\n/*\n** An object of this type contains the state required to create or append\n** to an appendable b-tree segment.\n*/\nstruct IncrmergeWriter {\n  int nLeafEst;                   /* Space allocated for leaf blocks */\n  int nWork;                      /* Number of leaf pages flushed */\n  sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */\n  int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */\n  sqlite3_int64 iStart;           /* Block number of first allocated block */\n  sqlite3_int64 iEnd;             /* Block number of last allocated block */\n  sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */\n  u8 bNoLeafData;                 /* If true, store 0 for segment size */\n  NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];\n};\n\n/*\n** An object of the following type is used to read data from a single\n** FTS segment node. See the following functions:\n**\n**     nodeReaderInit()\n**     nodeReaderNext()\n**     nodeReaderRelease()\n*/\nstruct NodeReader {\n  const char *aNode;\n  int nNode;\n  int iOff;                       /* Current offset within aNode[] */\n\n  /* Output variables. Containing the current node entry. */\n  sqlite3_int64 iChild;           /* Pointer to child node */\n  Blob term;                      /* Current term */\n  const char *aDoclist;           /* Pointer to doclist */\n  int nDoclist;                   /* Size of doclist in bytes */\n};\n\n/*\n** If *pRc is not SQLITE_OK when this function is called, it is a no-op.\n** Otherwise, if the allocation at pBlob->a is not already at least nMin\n** bytes in size, extend (realloc) it to be so.\n**\n** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a\n** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc\n** to reflect the new size of the pBlob->a[] buffer.\n*/\nstatic void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){\n  if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){\n    int nAlloc = nMin;\n    char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);\n    if( a ){\n      pBlob->nAlloc = nAlloc;\n      pBlob->a = a;\n    }else{\n      *pRc = SQLITE_NOMEM;\n    }\n  }\n}\n\n/*\n** Attempt to advance the node-reader object passed as the first argument to\n** the next entry on the node. \n**\n** Return an error code if an error occurs (SQLITE_NOMEM is possible). \n** Otherwise return SQLITE_OK. If there is no next entry on the node\n** (e.g. because the current entry is the last) set NodeReader->aNode to\n** NULL to indicate EOF. Otherwise, populate the NodeReader structure output \n** variables for the new entry.\n*/\nstatic int nodeReaderNext(NodeReader *p){\n  int bFirst = (p->term.n==0);    /* True for first term on the node */\n  int nPrefix = 0;                /* Bytes to copy from previous term */\n  int nSuffix = 0;                /* Bytes to append to the prefix */\n  int rc = SQLITE_OK;             /* Return code */\n\n  assert( p->aNode );\n  if( p->iChild && bFirst==0 ) p->iChild++;\n  if( p->iOff>=p->nNode ){\n    /* EOF */\n    p->aNode = 0;\n  }else{\n    if( bFirst==0 ){\n      p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);\n    }\n    p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);\n\n    if( nPrefix>p->term.n || nSuffix>p->nNode-p->iOff || nSuffix==0 ){\n      return FTS_CORRUPT_VTAB;\n    }\n    blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);\n    if( rc==SQLITE_OK ){\n      memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);\n      p->term.n = nPrefix+nSuffix;\n      p->iOff += nSuffix;\n      if( p->iChild==0 ){\n        p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);\n        if( (p->nNode-p->iOff)<p->nDoclist ){\n          return FTS_CORRUPT_VTAB;\n        }\n        p->aDoclist = &p->aNode[p->iOff];\n        p->iOff += p->nDoclist;\n      }\n    }\n  }\n\n  assert_fts3_nc( p->iOff<=p->nNode );\n  return rc;\n}\n\n/*\n** Release all dynamic resources held by node-reader object *p.\n*/\nstatic void nodeReaderRelease(NodeReader *p){\n  sqlite3_free(p->term.a);\n}\n\n/*\n** Initialize a node-reader object to read the node in buffer aNode/nNode.\n**\n** If successful, SQLITE_OK is returned and the NodeReader object set to \n** point to the first entry on the node (if any). Otherwise, an SQLite\n** error code is returned.\n*/\nstatic int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){\n  memset(p, 0, sizeof(NodeReader));\n  p->aNode = aNode;\n  p->nNode = nNode;\n\n  /* Figure out if this is a leaf or an internal node. */\n  if( aNode && aNode[0] ){\n    /* An internal node. */\n    p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);\n  }else{\n    p->iOff = 1;\n  }\n\n  return aNode ? nodeReaderNext(p) : SQLITE_OK;\n}\n\n/*\n** This function is called while writing an FTS segment each time a leaf o\n** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed\n** to be greater than the largest key on the node just written, but smaller\n** than or equal to the first key that will be written to the next leaf\n** node.\n**\n** The block id of the leaf node just written to disk may be found in\n** (pWriter->aNodeWriter[0].iBlock) when this function is called.\n*/\nstatic int fts3IncrmergePush(\n  Fts3Table *p,                   /* Fts3 table handle */\n  IncrmergeWriter *pWriter,       /* Writer object */\n  const char *zTerm,              /* Term to write to internal node */\n  int nTerm                       /* Bytes at zTerm */\n){\n  sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;\n  int iLayer;\n\n  assert( nTerm>0 );\n  for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){\n    sqlite3_int64 iNextPtr = 0;\n    NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];\n    int rc = SQLITE_OK;\n    int nPrefix;\n    int nSuffix;\n    int nSpace;\n\n    /* Figure out how much space the key will consume if it is written to\n    ** the current node of layer iLayer. Due to the prefix compression, \n    ** the space required changes depending on which node the key is to\n    ** be added to.  */\n    nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);\n    nSuffix = nTerm - nPrefix;\n    if(nSuffix<=0 ) return FTS_CORRUPT_VTAB;\n    nSpace  = sqlite3Fts3VarintLen(nPrefix);\n    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;\n\n    if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ \n      /* If the current node of layer iLayer contains zero keys, or if adding\n      ** the key to it will not cause it to grow to larger than nNodeSize \n      ** bytes in size, write the key here.  */\n\n      Blob *pBlk = &pNode->block;\n      if( pBlk->n==0 ){\n        blobGrowBuffer(pBlk, p->nNodeSize, &rc);\n        if( rc==SQLITE_OK ){\n          pBlk->a[0] = (char)iLayer;\n          pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);\n        }\n      }\n      blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);\n      blobGrowBuffer(&pNode->key, nTerm, &rc);\n\n      if( rc==SQLITE_OK ){\n        if( pNode->key.n ){\n          pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);\n        }\n        pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);\n        memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);\n        pBlk->n += nSuffix;\n\n        memcpy(pNode->key.a, zTerm, nTerm);\n        pNode->key.n = nTerm;\n      }\n    }else{\n      /* Otherwise, flush the current node of layer iLayer to disk.\n      ** Then allocate a new, empty sibling node. The key will be written\n      ** into the parent of this node. */\n      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);\n\n      assert( pNode->block.nAlloc>=p->nNodeSize );\n      pNode->block.a[0] = (char)iLayer;\n      pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);\n\n      iNextPtr = pNode->iBlock;\n      pNode->iBlock++;\n      pNode->key.n = 0;\n    }\n\n    if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;\n    iPtr = iNextPtr;\n  }\n\n  assert( 0 );\n  return 0;\n}\n\n/*\n** Append a term and (optionally) doclist to the FTS segment node currently\n** stored in blob *pNode. The node need not contain any terms, but the\n** header must be written before this function is called.\n**\n** A node header is a single 0x00 byte for a leaf node, or a height varint\n** followed by the left-hand-child varint for an internal node.\n**\n** The term to be appended is passed via arguments zTerm/nTerm. For a \n** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal\n** node, both aDoclist and nDoclist must be passed 0.\n**\n** If the size of the value in blob pPrev is zero, then this is the first\n** term written to the node. Otherwise, pPrev contains a copy of the \n** previous term. Before this function returns, it is updated to contain a\n** copy of zTerm/nTerm.\n**\n** It is assumed that the buffer associated with pNode is already large\n** enough to accommodate the new entry. The buffer associated with pPrev\n** is extended by this function if requrired.\n**\n** If an error (i.e. OOM condition) occurs, an SQLite error code is\n** returned. Otherwise, SQLITE_OK.\n*/\nstatic int fts3AppendToNode(\n  Blob *pNode,                    /* Current node image to append to */\n  Blob *pPrev,                    /* Buffer containing previous term written */\n  const char *zTerm,              /* New term to write */\n  int nTerm,                      /* Size of zTerm in bytes */\n  const char *aDoclist,           /* Doclist (or NULL) to write */\n  int nDoclist                    /* Size of aDoclist in bytes */ \n){\n  int rc = SQLITE_OK;             /* Return code */\n  int bFirst = (pPrev->n==0);     /* True if this is the first term written */\n  int nPrefix;                    /* Size of term prefix in bytes */\n  int nSuffix;                    /* Size of term suffix in bytes */\n\n  /* Node must have already been started. There must be a doclist for a\n  ** leaf node, and there must not be a doclist for an internal node.  */\n  assert( pNode->n>0 );\n  assert_fts3_nc( (pNode->a[0]=='\\0')==(aDoclist!=0) );\n\n  blobGrowBuffer(pPrev, nTerm, &rc);\n  if( rc!=SQLITE_OK ) return rc;\n\n  nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);\n  nSuffix = nTerm - nPrefix;\n  if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;\n  memcpy(pPrev->a, zTerm, nTerm);\n  pPrev->n = nTerm;\n\n  if( bFirst==0 ){\n    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);\n  }\n  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);\n  memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);\n  pNode->n += nSuffix;\n\n  if( aDoclist ){\n    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);\n    memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);\n    pNode->n += nDoclist;\n  }\n\n  assert( pNode->n<=pNode->nAlloc );\n\n  return SQLITE_OK;\n}\n\n/*\n** Append the current term and doclist pointed to by cursor pCsr to the\n** appendable b-tree segment opened for writing by pWriter.\n**\n** Return SQLITE_OK if successful, or an SQLite error code otherwise.\n*/\nstatic int fts3IncrmergeAppend(\n  Fts3Table *p,                   /* Fts3 table handle */\n  IncrmergeWriter *pWriter,       /* Writer object */\n  Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */\n){\n  const char *zTerm = pCsr->zTerm;\n  int nTerm = pCsr->nTerm;\n  const char *aDoclist = pCsr->aDoclist;\n  int nDoclist = pCsr->nDoclist;\n  int rc = SQLITE_OK;           /* Return code */\n  int nSpace;                   /* Total space in bytes required on leaf */\n  int nPrefix;                  /* Size of prefix shared with previous term */\n  int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */\n  NodeWriter *pLeaf;            /* Object used to write leaf nodes */\n\n  pLeaf = &pWriter->aNodeWriter[0];\n  nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);\n  nSuffix = nTerm - nPrefix;\n\n  nSpace  = sqlite3Fts3VarintLen(nPrefix);\n  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;\n  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;\n\n  /* If the current block is not empty, and if adding this term/doclist\n  ** to the current block would make it larger than Fts3Table.nNodeSize\n  ** bytes, write this block out to the database. */\n  if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){\n    rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);\n    pWriter->nWork++;\n\n    /* Add the current term to the parent node. The term added to the \n    ** parent must:\n    **\n    **   a) be greater than the largest term on the leaf node just written\n    **      to the database (still available in pLeaf->key), and\n    **\n    **   b) be less than or equal to the term about to be added to the new\n    **      leaf node (zTerm/nTerm).\n    **\n    ** In other words, it must be the prefix of zTerm 1 byte longer than\n    ** the common prefix (if any) of zTerm and pWriter->zTerm.\n    */\n    if( rc==SQLITE_OK ){\n      rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);\n    }\n\n    /* Advance to the next output block */\n    pLeaf->iBlock++;\n    pLeaf->key.n = 0;\n    pLeaf->block.n = 0;\n\n    nSuffix = nTerm;\n    nSpace  = 1;\n    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;\n    nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;\n  }\n\n  pWriter->nLeafData += nSpace;\n  blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);\n  if( rc==SQLITE_OK ){\n    if( pLeaf->block.n==0 ){\n      pLeaf->block.n = 1;\n      pLeaf->block.a[0] = '\\0';\n    }\n    rc = fts3AppendToNode(\n        &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist\n    );\n  }\n\n  return rc;\n}\n\n/*\n** This function is called to release all dynamic resources held by the\n** merge-writer object pWriter, and if no error has occurred, to flush\n** all outstanding node buffers held by pWriter to disk.\n**\n** If *pRc is not SQLITE_OK when this function is called, then no attempt\n** is made to write any data to disk. Instead, this function serves only\n** to release outstanding resources.\n**\n** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while\n** flushing buffers to disk, *pRc is set to an SQLite error code before\n** returning.\n*/\nstatic void fts3IncrmergeRelease(\n  Fts3Table *p,                   /* FTS3 table handle */\n  IncrmergeWriter *pWriter,       /* Merge-writer object */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  int i;                          /* Used to iterate through non-root layers */\n  int iRoot;                      /* Index of root in pWriter->aNodeWriter */\n  NodeWriter *pRoot;              /* NodeWriter for root node */\n  int rc = *pRc;                  /* Error code */\n\n  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment \n  ** root node. If the segment fits entirely on a single leaf node, iRoot\n  ** will be set to 0. If the root node is the parent of the leaves, iRoot\n  ** will be 1. And so on.  */\n  for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){\n    NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];\n    if( pNode->block.n>0 ) break;\n    assert( *pRc || pNode->block.nAlloc==0 );\n    assert( *pRc || pNode->key.nAlloc==0 );\n    sqlite3_free(pNode->block.a);\n    sqlite3_free(pNode->key.a);\n  }\n\n  /* Empty output segment. This is a no-op. */\n  if( iRoot<0 ) return;\n\n  /* The entire output segment fits on a single node. Normally, this means\n  ** the node would be stored as a blob in the \"root\" column of the %_segdir\n  ** table. However, this is not permitted in this case. The problem is that \n  ** space has already been reserved in the %_segments table, and so the \n  ** start_block and end_block fields of the %_segdir table must be populated. \n  ** And, by design or by accident, released versions of FTS cannot handle \n  ** segments that fit entirely on the root node with start_block!=0.\n  **\n  ** Instead, create a synthetic root node that contains nothing but a \n  ** pointer to the single content node. So that the segment consists of a\n  ** single leaf and a single interior (root) node.\n  **\n  ** Todo: Better might be to defer allocating space in the %_segments \n  ** table until we are sure it is needed.\n  */\n  if( iRoot==0 ){\n    Blob *pBlock = &pWriter->aNodeWriter[1].block;\n    blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);\n    if( rc==SQLITE_OK ){\n      pBlock->a[0] = 0x01;\n      pBlock->n = 1 + sqlite3Fts3PutVarint(\n          &pBlock->a[1], pWriter->aNodeWriter[0].iBlock\n      );\n    }\n    iRoot = 1;\n  }\n  pRoot = &pWriter->aNodeWriter[iRoot];\n\n  /* Flush all currently outstanding nodes to disk. */\n  for(i=0; i<iRoot; i++){\n    NodeWriter *pNode = &pWriter->aNodeWriter[i];\n    if( pNode->block.n>0 && rc==SQLITE_OK ){\n      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);\n    }\n    sqlite3_free(pNode->block.a);\n    sqlite3_free(pNode->key.a);\n  }\n\n  /* Write the %_segdir record. */\n  if( rc==SQLITE_OK ){\n    rc = fts3WriteSegdir(p, \n        pWriter->iAbsLevel+1,               /* level */\n        pWriter->iIdx,                      /* idx */\n        pWriter->iStart,                    /* start_block */\n        pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */\n        pWriter->iEnd,                      /* end_block */\n        (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */\n        pRoot->block.a, pRoot->block.n      /* root */\n    );\n  }\n  sqlite3_free(pRoot->block.a);\n  sqlite3_free(pRoot->key.a);\n\n  *pRc = rc;\n}\n\n/*\n** Compare the term in buffer zLhs (size in bytes nLhs) with that in\n** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of\n** the other, it is considered to be smaller than the other.\n**\n** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve\n** if it is greater.\n*/\nstatic int fts3TermCmp(\n  const char *zLhs, int nLhs,     /* LHS of comparison */\n  const char *zRhs, int nRhs      /* RHS of comparison */\n){\n  int nCmp = MIN(nLhs, nRhs);\n  int res;\n\n  res = (nCmp ? memcmp(zLhs, zRhs, nCmp) : 0);\n  if( res==0 ) res = nLhs - nRhs;\n\n  return res;\n}\n\n\n/*\n** Query to see if the entry in the %_segments table with blockid iEnd is \n** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before\n** returning. Otherwise, set *pbRes to 0. \n**\n** Or, if an error occurs while querying the database, return an SQLite \n** error code. The final value of *pbRes is undefined in this case.\n**\n** This is used to test if a segment is an \"appendable\" segment. If it\n** is, then a NULL entry has been inserted into the %_segments table\n** with blockid %_segdir.end_block.\n*/\nstatic int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){\n  int bRes = 0;                   /* Result to set *pbRes to */\n  sqlite3_stmt *pCheck = 0;       /* Statement to query database with */\n  int rc;                         /* Return code */\n\n  rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pCheck, 1, iEnd);\n    if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;\n    rc = sqlite3_reset(pCheck);\n  }\n  \n  *pbRes = bRes;\n  return rc;\n}\n\n/*\n** This function is called when initializing an incremental-merge operation.\n** It checks if the existing segment with index value iIdx at absolute level \n** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the\n** merge-writer object *pWriter is initialized to write to it.\n**\n** An existing segment can be appended to by an incremental merge if:\n**\n**   * It was initially created as an appendable segment (with all required\n**     space pre-allocated), and\n**\n**   * The first key read from the input (arguments zKey and nKey) is \n**     greater than the largest key currently stored in the potential\n**     output segment.\n*/\nstatic int fts3IncrmergeLoad(\n  Fts3Table *p,                   /* Fts3 table handle */\n  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */\n  int iIdx,                       /* Index of candidate output segment */\n  const char *zKey,               /* First key to write */\n  int nKey,                       /* Number of bytes in nKey */\n  IncrmergeWriter *pWriter        /* Populate this object */\n){\n  int rc;                         /* Return code */\n  sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */\n\n  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */\n    sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */\n    sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */\n    const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */\n    int nRoot = 0;                /* Size of aRoot[] in bytes */\n    int rc2;                      /* Return code from sqlite3_reset() */\n    int bAppendable = 0;          /* Set to true if segment is appendable */\n\n    /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */\n    sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);\n    sqlite3_bind_int(pSelect, 2, iIdx);\n    if( sqlite3_step(pSelect)==SQLITE_ROW ){\n      iStart = sqlite3_column_int64(pSelect, 1);\n      iLeafEnd = sqlite3_column_int64(pSelect, 2);\n      fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);\n      if( pWriter->nLeafData<0 ){\n        pWriter->nLeafData = pWriter->nLeafData * -1;\n      }\n      pWriter->bNoLeafData = (pWriter->nLeafData==0);\n      nRoot = sqlite3_column_bytes(pSelect, 4);\n      aRoot = sqlite3_column_blob(pSelect, 4);\n      if( aRoot==0 ){\n        sqlite3_reset(pSelect);\n        return nRoot ? SQLITE_NOMEM : FTS_CORRUPT_VTAB;\n      }\n    }else{\n      return sqlite3_reset(pSelect);\n    }\n\n    /* Check for the zero-length marker in the %_segments table */\n    rc = fts3IsAppendable(p, iEnd, &bAppendable);\n\n    /* Check that zKey/nKey is larger than the largest key the candidate */\n    if( rc==SQLITE_OK && bAppendable ){\n      char *aLeaf = 0;\n      int nLeaf = 0;\n\n      rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);\n      if( rc==SQLITE_OK ){\n        NodeReader reader;\n        for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);\n            rc==SQLITE_OK && reader.aNode;\n            rc = nodeReaderNext(&reader)\n        ){\n          assert( reader.aNode );\n        }\n        if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){\n          bAppendable = 0;\n        }\n        nodeReaderRelease(&reader);\n      }\n      sqlite3_free(aLeaf);\n    }\n\n    if( rc==SQLITE_OK && bAppendable ){\n      /* It is possible to append to this segment. Set up the IncrmergeWriter\n      ** object to do so.  */\n      int i;\n      int nHeight = (int)aRoot[0];\n      NodeWriter *pNode;\n      if( nHeight<1 || nHeight>FTS_MAX_APPENDABLE_HEIGHT ){\n        sqlite3_reset(pSelect);\n        return FTS_CORRUPT_VTAB;\n      }\n\n      pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;\n      pWriter->iStart = iStart;\n      pWriter->iEnd = iEnd;\n      pWriter->iAbsLevel = iAbsLevel;\n      pWriter->iIdx = iIdx;\n\n      for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){\n        pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;\n      }\n\n      pNode = &pWriter->aNodeWriter[nHeight];\n      pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;\n      blobGrowBuffer(&pNode->block, \n          MAX(nRoot, p->nNodeSize)+FTS3_NODE_PADDING, &rc\n      );\n      if( rc==SQLITE_OK ){\n        memcpy(pNode->block.a, aRoot, nRoot);\n        pNode->block.n = nRoot;\n        memset(&pNode->block.a[nRoot], 0, FTS3_NODE_PADDING);\n      }\n\n      for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){\n        NodeReader reader;\n        pNode = &pWriter->aNodeWriter[i];\n\n        if( pNode->block.a){\n          rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);\n          while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);\n          blobGrowBuffer(&pNode->key, reader.term.n, &rc);\n          if( rc==SQLITE_OK ){\n            memcpy(pNode->key.a, reader.term.a, reader.term.n);\n            pNode->key.n = reader.term.n;\n            if( i>0 ){\n              char *aBlock = 0;\n              int nBlock = 0;\n              pNode = &pWriter->aNodeWriter[i-1];\n              pNode->iBlock = reader.iChild;\n              rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);\n              blobGrowBuffer(&pNode->block, \n                  MAX(nBlock, p->nNodeSize)+FTS3_NODE_PADDING, &rc\n              );\n              if( rc==SQLITE_OK ){\n                memcpy(pNode->block.a, aBlock, nBlock);\n                pNode->block.n = nBlock;\n                memset(&pNode->block.a[nBlock], 0, FTS3_NODE_PADDING);\n              }\n              sqlite3_free(aBlock);\n            }\n          }\n        }\n        nodeReaderRelease(&reader);\n      }\n    }\n\n    rc2 = sqlite3_reset(pSelect);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n\n  return rc;\n}\n\n/*\n** Determine the largest segment index value that exists within absolute\n** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus\n** one before returning SQLITE_OK. Or, if there are no segments at all \n** within level iAbsLevel, set *piIdx to zero.\n**\n** If an error occurs, return an SQLite error code. The final value of\n** *piIdx is undefined in this case.\n*/\nstatic int fts3IncrmergeOutputIdx( \n  Fts3Table *p,                   /* FTS Table handle */\n  sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */\n  int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */\n){\n  int rc;\n  sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */\n\n  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);\n    sqlite3_step(pOutputIdx);\n    *piIdx = sqlite3_column_int(pOutputIdx, 0);\n    rc = sqlite3_reset(pOutputIdx);\n  }\n\n  return rc;\n}\n\n/* \n** Allocate an appendable output segment on absolute level iAbsLevel+1\n** with idx value iIdx.\n**\n** In the %_segdir table, a segment is defined by the values in three\n** columns:\n**\n**     start_block\n**     leaves_end_block\n**     end_block\n**\n** When an appendable segment is allocated, it is estimated that the\n** maximum number of leaf blocks that may be required is the sum of the\n** number of leaf blocks consumed by the input segments, plus the number\n** of input segments, multiplied by two. This value is stored in stack \n** variable nLeafEst.\n**\n** A total of 16*nLeafEst blocks are allocated when an appendable segment\n** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous\n** array of leaf nodes starts at the first block allocated. The array\n** of interior nodes that are parents of the leaf nodes start at block\n** (start_block + (1 + end_block - start_block) / 16). And so on.\n**\n** In the actual code below, the value \"16\" is replaced with the \n** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.\n*/\nstatic int fts3IncrmergeWriter( \n  Fts3Table *p,                   /* Fts3 table handle */\n  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */\n  int iIdx,                       /* Index of new output segment */\n  Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */\n  IncrmergeWriter *pWriter        /* Populate this object */\n){\n  int rc;                         /* Return Code */\n  int i;                          /* Iterator variable */\n  int nLeafEst = 0;               /* Blocks allocated for leaf nodes */\n  sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */\n  sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */\n\n  /* Calculate nLeafEst. */\n  rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);\n    sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);\n    if( SQLITE_ROW==sqlite3_step(pLeafEst) ){\n      nLeafEst = sqlite3_column_int(pLeafEst, 0);\n    }\n    rc = sqlite3_reset(pLeafEst);\n  }\n  if( rc!=SQLITE_OK ) return rc;\n\n  /* Calculate the first block to use in the output segment */\n  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);\n  if( rc==SQLITE_OK ){\n    if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){\n      pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);\n      pWriter->iEnd = pWriter->iStart - 1;\n      pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;\n    }\n    rc = sqlite3_reset(pFirstBlock);\n  }\n  if( rc!=SQLITE_OK ) return rc;\n\n  /* Insert the marker in the %_segments table to make sure nobody tries\n  ** to steal the space just allocated. This is also used to identify \n  ** appendable segments.  */\n  rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);\n  if( rc!=SQLITE_OK ) return rc;\n\n  pWriter->iAbsLevel = iAbsLevel;\n  pWriter->nLeafEst = nLeafEst;\n  pWriter->iIdx = iIdx;\n\n  /* Set up the array of NodeWriter objects */\n  for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){\n    pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Remove an entry from the %_segdir table. This involves running the \n** following two statements:\n**\n**   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx\n**   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx\n**\n** The DELETE statement removes the specific %_segdir level. The UPDATE \n** statement ensures that the remaining segments have contiguously allocated\n** idx values.\n*/\nstatic int fts3RemoveSegdirEntry(\n  Fts3Table *p,                   /* FTS3 table handle */\n  sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */\n  int iIdx                        /* Index of %_segdir entry to delete */\n){\n  int rc;                         /* Return code */\n  sqlite3_stmt *pDelete = 0;      /* DELETE statement */\n\n  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pDelete, 1, iAbsLevel);\n    sqlite3_bind_int(pDelete, 2, iIdx);\n    sqlite3_step(pDelete);\n    rc = sqlite3_reset(pDelete);\n  }\n\n  return rc;\n}\n\n/*\n** One or more segments have just been removed from absolute level iAbsLevel.\n** Update the 'idx' values of the remaining segments in the level so that\n** the idx values are a contiguous sequence starting from 0.\n*/\nstatic int fts3RepackSegdirLevel(\n  Fts3Table *p,                   /* FTS3 table handle */\n  sqlite3_int64 iAbsLevel         /* Absolute level to repack */\n){\n  int rc;                         /* Return code */\n  int *aIdx = 0;                  /* Array of remaining idx values */\n  int nIdx = 0;                   /* Valid entries in aIdx[] */\n  int nAlloc = 0;                 /* Allocated size of aIdx[] */\n  int i;                          /* Iterator variable */\n  sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */\n  sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */\n\n  rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);\n  if( rc==SQLITE_OK ){\n    int rc2;\n    sqlite3_bind_int64(pSelect, 1, iAbsLevel);\n    while( SQLITE_ROW==sqlite3_step(pSelect) ){\n      if( nIdx>=nAlloc ){\n        int *aNew;\n        nAlloc += 16;\n        aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));\n        if( !aNew ){\n          rc = SQLITE_NOMEM;\n          break;\n        }\n        aIdx = aNew;\n      }\n      aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);\n    }\n    rc2 = sqlite3_reset(pSelect);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);\n  }\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pUpdate, 2, iAbsLevel);\n  }\n\n  assert( p->bIgnoreSavepoint==0 );\n  p->bIgnoreSavepoint = 1;\n  for(i=0; rc==SQLITE_OK && i<nIdx; i++){\n    if( aIdx[i]!=i ){\n      sqlite3_bind_int(pUpdate, 3, aIdx[i]);\n      sqlite3_bind_int(pUpdate, 1, i);\n      sqlite3_step(pUpdate);\n      rc = sqlite3_reset(pUpdate);\n    }\n  }\n  p->bIgnoreSavepoint = 0;\n\n  sqlite3_free(aIdx);\n  return rc;\n}\n\nstatic void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){\n  pNode->a[0] = (char)iHeight;\n  if( iChild ){\n    assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );\n    pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);\n  }else{\n    assert( pNode->nAlloc>=1 );\n    pNode->n = 1;\n  }\n}\n\n/*\n** The first two arguments are a pointer to and the size of a segment b-tree\n** node. The node may be a leaf or an internal node.\n**\n** This function creates a new node image in blob object *pNew by copying\n** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)\n** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.\n*/\nstatic int fts3TruncateNode(\n  const char *aNode,              /* Current node image */\n  int nNode,                      /* Size of aNode in bytes */\n  Blob *pNew,                     /* OUT: Write new node image here */\n  const char *zTerm,              /* Omit all terms smaller than this */\n  int nTerm,                      /* Size of zTerm in bytes */\n  sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */\n){\n  NodeReader reader;              /* Reader object */\n  Blob prev = {0, 0, 0};          /* Previous term written to new node */\n  int rc = SQLITE_OK;             /* Return code */\n  int bLeaf;                       /* True for a leaf node */\n\n  if( nNode<1 ) return FTS_CORRUPT_VTAB;\n  bLeaf = aNode[0]=='\\0';\n\n  /* Allocate required output space */\n  blobGrowBuffer(pNew, nNode, &rc);\n  if( rc!=SQLITE_OK ) return rc;\n  pNew->n = 0;\n\n  /* Populate new node buffer */\n  for(rc = nodeReaderInit(&reader, aNode, nNode); \n      rc==SQLITE_OK && reader.aNode; \n      rc = nodeReaderNext(&reader)\n  ){\n    if( pNew->n==0 ){\n      int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);\n      if( res<0 || (bLeaf==0 && res==0) ) continue;\n      fts3StartNode(pNew, (int)aNode[0], reader.iChild);\n      *piBlock = reader.iChild;\n    }\n    rc = fts3AppendToNode(\n        pNew, &prev, reader.term.a, reader.term.n,\n        reader.aDoclist, reader.nDoclist\n    );\n    if( rc!=SQLITE_OK ) break;\n  }\n  if( pNew->n==0 ){\n    fts3StartNode(pNew, (int)aNode[0], reader.iChild);\n    *piBlock = reader.iChild;\n  }\n  assert( pNew->n<=pNew->nAlloc );\n\n  nodeReaderRelease(&reader);\n  sqlite3_free(prev.a);\n  return rc;\n}\n\n/*\n** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute \n** level iAbsLevel. This may involve deleting entries from the %_segments\n** table, and modifying existing entries in both the %_segments and %_segdir\n** tables.\n**\n** SQLITE_OK is returned if the segment is updated successfully. Or an\n** SQLite error code otherwise.\n*/\nstatic int fts3TruncateSegment(\n  Fts3Table *p,                   /* FTS3 table handle */\n  sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */\n  int iIdx,                       /* Index within level of segment to modify */\n  const char *zTerm,              /* Remove terms smaller than this */\n  int nTerm                      /* Number of bytes in buffer zTerm */\n){\n  int rc = SQLITE_OK;             /* Return code */\n  Blob root = {0,0,0};            /* New root page image */\n  Blob block = {0,0,0};           /* Buffer used for any other block */\n  sqlite3_int64 iBlock = 0;       /* Block id */\n  sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */\n  sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */\n  sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */\n\n  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);\n  if( rc==SQLITE_OK ){\n    int rc2;                      /* sqlite3_reset() return code */\n    sqlite3_bind_int64(pFetch, 1, iAbsLevel);\n    sqlite3_bind_int(pFetch, 2, iIdx);\n    if( SQLITE_ROW==sqlite3_step(pFetch) ){\n      const char *aRoot = sqlite3_column_blob(pFetch, 4);\n      int nRoot = sqlite3_column_bytes(pFetch, 4);\n      iOldStart = sqlite3_column_int64(pFetch, 1);\n      rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);\n    }\n    rc2 = sqlite3_reset(pFetch);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n\n  while( rc==SQLITE_OK && iBlock ){\n    char *aBlock = 0;\n    int nBlock = 0;\n    iNewStart = iBlock;\n\n    rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);\n    if( rc==SQLITE_OK ){\n      rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);\n    }\n    if( rc==SQLITE_OK ){\n      rc = fts3WriteSegment(p, iNewStart, block.a, block.n);\n    }\n    sqlite3_free(aBlock);\n  }\n\n  /* Variable iNewStart now contains the first valid leaf node. */\n  if( rc==SQLITE_OK && iNewStart ){\n    sqlite3_stmt *pDel = 0;\n    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int64(pDel, 1, iOldStart);\n      sqlite3_bind_int64(pDel, 2, iNewStart-1);\n      sqlite3_step(pDel);\n      rc = sqlite3_reset(pDel);\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    sqlite3_stmt *pChomp = 0;\n    rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int64(pChomp, 1, iNewStart);\n      sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);\n      sqlite3_bind_int64(pChomp, 3, iAbsLevel);\n      sqlite3_bind_int(pChomp, 4, iIdx);\n      sqlite3_step(pChomp);\n      rc = sqlite3_reset(pChomp);\n      sqlite3_bind_null(pChomp, 2);\n    }\n  }\n\n  sqlite3_free(root.a);\n  sqlite3_free(block.a);\n  return rc;\n}\n\n/*\n** This function is called after an incrmental-merge operation has run to\n** merge (or partially merge) two or more segments from absolute level\n** iAbsLevel.\n**\n** Each input segment is either removed from the db completely (if all of\n** its data was copied to the output segment by the incrmerge operation)\n** or modified in place so that it no longer contains those entries that\n** have been duplicated in the output segment.\n*/\nstatic int fts3IncrmergeChomp(\n  Fts3Table *p,                   /* FTS table handle */\n  sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */\n  Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */\n  int *pnRem                      /* Number of segments not deleted */\n){\n  int i;\n  int nRem = 0;\n  int rc = SQLITE_OK;\n\n  for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){\n    Fts3SegReader *pSeg = 0;\n    int j;\n\n    /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding\n    ** somewhere in the pCsr->apSegment[] array.  */\n    for(j=0; ALWAYS(j<pCsr->nSegment); j++){\n      pSeg = pCsr->apSegment[j];\n      if( pSeg->iIdx==i ) break;\n    }\n    assert( j<pCsr->nSegment && pSeg->iIdx==i );\n\n    if( pSeg->aNode==0 ){\n      /* Seg-reader is at EOF. Remove the entire input segment. */\n      rc = fts3DeleteSegment(p, pSeg);\n      if( rc==SQLITE_OK ){\n        rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);\n      }\n      *pnRem = 0;\n    }else{\n      /* The incremental merge did not copy all the data from this \n      ** segment to the upper level. The segment is modified in place\n      ** so that it contains no keys smaller than zTerm/nTerm. */ \n      const char *zTerm = pSeg->zTerm;\n      int nTerm = pSeg->nTerm;\n      rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);\n      nRem++;\n    }\n  }\n\n  if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){\n    rc = fts3RepackSegdirLevel(p, iAbsLevel);\n  }\n\n  *pnRem = nRem;\n  return rc;\n}\n\n/*\n** Store an incr-merge hint in the database.\n*/\nstatic int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){\n  sqlite3_stmt *pReplace = 0;\n  int rc;                         /* Return code */\n\n  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);\n    sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);\n    sqlite3_step(pReplace);\n    rc = sqlite3_reset(pReplace);\n    sqlite3_bind_null(pReplace, 2);\n  }\n\n  return rc;\n}\n\n/*\n** Load an incr-merge hint from the database. The incr-merge hint, if one \n** exists, is stored in the rowid==1 row of the %_stat table.\n**\n** If successful, populate blob *pHint with the value read from the %_stat\n** table and return SQLITE_OK. Otherwise, if an error occurs, return an\n** SQLite error code.\n*/\nstatic int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){\n  sqlite3_stmt *pSelect = 0;\n  int rc;\n\n  pHint->n = 0;\n  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);\n  if( rc==SQLITE_OK ){\n    int rc2;\n    sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);\n    if( SQLITE_ROW==sqlite3_step(pSelect) ){\n      const char *aHint = sqlite3_column_blob(pSelect, 0);\n      int nHint = sqlite3_column_bytes(pSelect, 0);\n      if( aHint ){\n        blobGrowBuffer(pHint, nHint, &rc);\n        if( rc==SQLITE_OK ){\n          memcpy(pHint->a, aHint, nHint);\n          pHint->n = nHint;\n        }\n      }\n    }\n    rc2 = sqlite3_reset(pSelect);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n\n  return rc;\n}\n\n/*\n** If *pRc is not SQLITE_OK when this function is called, it is a no-op.\n** Otherwise, append an entry to the hint stored in blob *pHint. Each entry\n** consists of two varints, the absolute level number of the input segments \n** and the number of input segments.\n**\n** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,\n** set *pRc to an SQLite error code before returning.\n*/\nstatic void fts3IncrmergeHintPush(\n  Blob *pHint,                    /* Hint blob to append to */\n  i64 iAbsLevel,                  /* First varint to store in hint */\n  int nInput,                     /* Second varint to store in hint */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);\n  if( *pRc==SQLITE_OK ){\n    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);\n    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);\n  }\n}\n\n/*\n** Read the last entry (most recently pushed) from the hint blob *pHint\n** and then remove the entry. Write the two values read to *piAbsLevel and \n** *pnInput before returning.\n**\n** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does\n** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.\n*/\nstatic int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){\n  const int nHint = pHint->n;\n  int i;\n\n  i = pHint->n-1;\n  if( (pHint->a[i] & 0x80) ) return FTS_CORRUPT_VTAB;\n  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;\n  if( i==0 ) return FTS_CORRUPT_VTAB;\n  i--;\n  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;\n\n  pHint->n = i;\n  i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);\n  i += fts3GetVarint32(&pHint->a[i], pnInput);\n  assert( i<=nHint );\n  if( i!=nHint ) return FTS_CORRUPT_VTAB;\n\n  return SQLITE_OK;\n}\n\n\n/*\n** Attempt an incremental merge that writes nMerge leaf blocks.\n**\n** Incremental merges happen nMin segments at a time. The segments \n** to be merged are the nMin oldest segments (the ones with the smallest \n** values for the _segdir.idx field) in the highest level that contains \n** at least nMin segments. Multiple merges might occur in an attempt to \n** write the quota of nMerge leaf blocks.\n*/\nSQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){\n  int rc;                         /* Return code */\n  int nRem = nMerge;              /* Number of leaf pages yet to  be written */\n  Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */\n  Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */\n  IncrmergeWriter *pWriter;       /* Writer object */\n  int nSeg = 0;                   /* Number of input segments */\n  sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */\n  Blob hint = {0, 0, 0};          /* Hint read from %_stat table */\n  int bDirtyHint = 0;             /* True if blob 'hint' has been modified */\n\n  /* Allocate space for the cursor, filter and writer objects */\n  const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);\n  pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);\n  if( !pWriter ) return SQLITE_NOMEM;\n  pFilter = (Fts3SegFilter *)&pWriter[1];\n  pCsr = (Fts3MultiSegReader *)&pFilter[1];\n\n  rc = fts3IncrmergeHintLoad(p, &hint);\n  while( rc==SQLITE_OK && nRem>0 ){\n    const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;\n    sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */\n    int bUseHint = 0;             /* True if attempting to append */\n    int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */\n\n    /* Search the %_segdir table for the absolute level with the smallest\n    ** relative level number that contains at least nMin segments, if any.\n    ** If one is found, set iAbsLevel to the absolute level number and\n    ** nSeg to nMin. If no level with at least nMin segments can be found, \n    ** set nSeg to -1.\n    */\n    rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);\n    sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));\n    if( sqlite3_step(pFindLevel)==SQLITE_ROW ){\n      iAbsLevel = sqlite3_column_int64(pFindLevel, 0);\n      nSeg = sqlite3_column_int(pFindLevel, 1);\n      assert( nSeg>=2 );\n    }else{\n      nSeg = -1;\n    }\n    rc = sqlite3_reset(pFindLevel);\n\n    /* If the hint read from the %_stat table is not empty, check if the\n    ** last entry in it specifies a relative level smaller than or equal\n    ** to the level identified by the block above (if any). If so, this \n    ** iteration of the loop will work on merging at the hinted level.\n    */\n    if( rc==SQLITE_OK && hint.n ){\n      int nHint = hint.n;\n      sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */\n      int nHintSeg = 0;                     /* Hint number of segments */\n\n      rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);\n      if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){\n        /* Based on the scan in the block above, it is known that there\n        ** are no levels with a relative level smaller than that of\n        ** iAbsLevel with more than nSeg segments, or if nSeg is -1, \n        ** no levels with more than nMin segments. Use this to limit the\n        ** value of nHintSeg to avoid a large memory allocation in case the \n        ** merge-hint is corrupt*/\n        iAbsLevel = iHintAbsLevel;\n        nSeg = MIN(MAX(nMin,nSeg), nHintSeg);\n        bUseHint = 1;\n        bDirtyHint = 1;\n      }else{\n        /* This undoes the effect of the HintPop() above - so that no entry\n        ** is removed from the hint blob.  */\n        hint.n = nHint;\n      }\n    }\n\n    /* If nSeg is less that zero, then there is no level with at least\n    ** nMin segments and no hint in the %_stat table. No work to do.\n    ** Exit early in this case.  */\n    if( nSeg<=0 ) break;\n\n    assert( nMod<=0x7FFFFFFF );\n    if( iAbsLevel<0 || iAbsLevel>(nMod<<32) ){\n      rc = FTS_CORRUPT_VTAB;\n      break;\n    }\n\n    /* Open a cursor to iterate through the contents of the oldest nSeg \n    ** indexes of absolute level iAbsLevel. If this cursor is opened using \n    ** the 'hint' parameters, it is possible that there are less than nSeg\n    ** segments available in level iAbsLevel. In this case, no work is\n    ** done on iAbsLevel - fall through to the next iteration of the loop \n    ** to start work on some other level.  */\n    memset(pWriter, 0, nAlloc);\n    pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;\n\n    if( rc==SQLITE_OK ){\n      rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);\n      assert( bUseHint==1 || bUseHint==0 );\n      if( iIdx==0 || (bUseHint && iIdx==1) ){\n        int bIgnore = 0;\n        rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);\n        if( bIgnore ){\n          pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;\n        }\n      }\n    }\n\n    if( rc==SQLITE_OK ){\n      rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);\n    }\n    if( SQLITE_OK==rc && pCsr->nSegment==nSeg\n     && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))\n    ){\n      int bEmpty = 0;\n      rc = sqlite3Fts3SegReaderStep(p, pCsr);\n      if( rc==SQLITE_OK ){\n        bEmpty = 1;\n      }else if( rc!=SQLITE_ROW ){\n        sqlite3Fts3SegReaderFinish(pCsr);\n        break;\n      }\n      if( bUseHint && iIdx>0 ){\n        const char *zKey = pCsr->zTerm;\n        int nKey = pCsr->nTerm;\n        rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);\n      }else{\n        rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);\n      }\n\n      if( rc==SQLITE_OK && pWriter->nLeafEst ){\n        fts3LogMerge(nSeg, iAbsLevel);\n        if( bEmpty==0 ){\n          do {\n            rc = fts3IncrmergeAppend(p, pWriter, pCsr);\n            if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);\n            if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;\n          }while( rc==SQLITE_ROW );\n        }\n\n        /* Update or delete the input segments */\n        if( rc==SQLITE_OK ){\n          nRem -= (1 + pWriter->nWork);\n          rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);\n          if( nSeg!=0 ){\n            bDirtyHint = 1;\n            fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);\n          }\n        }\n      }\n\n      if( nSeg!=0 ){\n        pWriter->nLeafData = pWriter->nLeafData * -1;\n      }\n      fts3IncrmergeRelease(p, pWriter, &rc);\n      if( nSeg==0 && pWriter->bNoLeafData==0 ){\n        fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);\n      }\n    }\n\n    sqlite3Fts3SegReaderFinish(pCsr);\n  }\n\n  /* Write the hint values into the %_stat table for the next incr-merger */\n  if( bDirtyHint && rc==SQLITE_OK ){\n    rc = fts3IncrmergeHintStore(p, &hint);\n  }\n\n  sqlite3_free(pWriter);\n  sqlite3_free(hint.a);\n  return rc;\n}\n\n/*\n** Convert the text beginning at *pz into an integer and return\n** its value.  Advance *pz to point to the first character past\n** the integer.\n**\n** This function used for parameters to merge= and incrmerge=\n** commands. \n*/\nstatic int fts3Getint(const char **pz){\n  const char *z = *pz;\n  int i = 0;\n  while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';\n  *pz = z;\n  return i;\n}\n\n/*\n** Process statements of the form:\n**\n**    INSERT INTO table(table) VALUES('merge=A,B');\n**\n** A and B are integers that decode to be the number of leaf pages\n** written for the merge, and the minimum number of segments on a level\n** before it will be selected for a merge, respectively.\n*/\nstatic int fts3DoIncrmerge(\n  Fts3Table *p,                   /* FTS3 table handle */\n  const char *zParam              /* Nul-terminated string containing \"A,B\" */\n){\n  int rc;\n  int nMin = (MergeCount(p) / 2);\n  int nMerge = 0;\n  const char *z = zParam;\n\n  /* Read the first integer value */\n  nMerge = fts3Getint(&z);\n\n  /* If the first integer value is followed by a ',',  read the second\n  ** integer value. */\n  if( z[0]==',' && z[1]!='\\0' ){\n    z++;\n    nMin = fts3Getint(&z);\n  }\n\n  if( z[0]!='\\0' || nMin<2 ){\n    rc = SQLITE_ERROR;\n  }else{\n    rc = SQLITE_OK;\n    if( !p->bHasStat ){\n      assert( p->bFts4==0 );\n      sqlite3Fts3CreateStatTable(&rc, p);\n    }\n    if( rc==SQLITE_OK ){\n      rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);\n    }\n    sqlite3Fts3SegmentsClose(p);\n  }\n  return rc;\n}\n\n/*\n** Process statements of the form:\n**\n**    INSERT INTO table(table) VALUES('automerge=X');\n**\n** where X is an integer.  X==0 means to turn automerge off.  X!=0 means\n** turn it on.  The setting is persistent.\n*/\nstatic int fts3DoAutoincrmerge(\n  Fts3Table *p,                   /* FTS3 table handle */\n  const char *zParam              /* Nul-terminated string containing boolean */\n){\n  int rc = SQLITE_OK;\n  sqlite3_stmt *pStmt = 0;\n  p->nAutoincrmerge = fts3Getint(&zParam);\n  if( p->nAutoincrmerge==1 || p->nAutoincrmerge>MergeCount(p) ){\n    p->nAutoincrmerge = 8;\n  }\n  if( !p->bHasStat ){\n    assert( p->bFts4==0 );\n    sqlite3Fts3CreateStatTable(&rc, p);\n    if( rc ) return rc;\n  }\n  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);\n  if( rc ) return rc;\n  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);\n  sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);\n  sqlite3_step(pStmt);\n  rc = sqlite3_reset(pStmt);\n  return rc;\n}\n\n/*\n** Return a 64-bit checksum for the FTS index entry specified by the\n** arguments to this function.\n*/\nstatic u64 fts3ChecksumEntry(\n  const char *zTerm,              /* Pointer to buffer containing term */\n  int nTerm,                      /* Size of zTerm in bytes */\n  int iLangid,                    /* Language id for current row */\n  int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */\n  i64 iDocid,                     /* Docid for current row. */\n  int iCol,                       /* Column number */\n  int iPos                        /* Position */\n){\n  int i;\n  u64 ret = (u64)iDocid;\n\n  ret += (ret<<3) + iLangid;\n  ret += (ret<<3) + iIndex;\n  ret += (ret<<3) + iCol;\n  ret += (ret<<3) + iPos;\n  for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];\n\n  return ret;\n}\n\n/*\n** Return a checksum of all entries in the FTS index that correspond to\n** language id iLangid. The checksum is calculated by XORing the checksums\n** of each individual entry (see fts3ChecksumEntry()) together.\n**\n** If successful, the checksum value is returned and *pRc set to SQLITE_OK.\n** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The\n** return value is undefined in this case.\n*/\nstatic u64 fts3ChecksumIndex(\n  Fts3Table *p,                   /* FTS3 table handle */\n  int iLangid,                    /* Language id to return cksum for */\n  int iIndex,                     /* Index to cksum (0..p->nIndex-1) */\n  int *pRc                        /* OUT: Return code */\n){\n  Fts3SegFilter filter;\n  Fts3MultiSegReader csr;\n  int rc;\n  u64 cksum = 0;\n\n  assert( *pRc==SQLITE_OK );\n\n  memset(&filter, 0, sizeof(filter));\n  memset(&csr, 0, sizeof(csr));\n  filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;\n  filter.flags |= FTS3_SEGMENT_SCAN;\n\n  rc = sqlite3Fts3SegReaderCursor(\n      p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr\n  );\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);\n  }\n\n  if( rc==SQLITE_OK ){\n    while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){\n      char *pCsr = csr.aDoclist;\n      char *pEnd = &pCsr[csr.nDoclist];\n\n      i64 iDocid = 0;\n      i64 iCol = 0;\n      u64 iPos = 0;\n\n      pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);\n      while( pCsr<pEnd ){\n        u64 iVal = 0;\n        pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal);\n        if( pCsr<pEnd ){\n          if( iVal==0 || iVal==1 ){\n            iCol = 0;\n            iPos = 0;\n            if( iVal ){\n              pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);\n            }else{\n              pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal);\n              if( p->bDescIdx ){\n                iDocid = (i64)((u64)iDocid - iVal);\n              }else{\n                iDocid = (i64)((u64)iDocid + iVal);\n              }\n            }\n          }else{\n            iPos += (iVal - 2);\n            cksum = cksum ^ fts3ChecksumEntry(\n                csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,\n                (int)iCol, (int)iPos\n            );\n          }\n        }\n      }\n    }\n  }\n  sqlite3Fts3SegReaderFinish(&csr);\n\n  *pRc = rc;\n  return cksum;\n}\n\n/*\n** Check if the contents of the FTS index match the current contents of the\n** content table. If no error occurs and the contents do match, set *pbOk\n** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk\n** to false before returning.\n**\n** If an error occurs (e.g. an OOM or IO error), return an SQLite error \n** code. The final value of *pbOk is undefined in this case.\n*/\nstatic int fts3IntegrityCheck(Fts3Table *p, int *pbOk){\n  int rc = SQLITE_OK;             /* Return code */\n  u64 cksum1 = 0;                 /* Checksum based on FTS index contents */\n  u64 cksum2 = 0;                 /* Checksum based on %_content contents */\n  sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */\n\n  /* This block calculates the checksum according to the FTS index. */\n  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);\n  if( rc==SQLITE_OK ){\n    int rc2;\n    sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);\n    sqlite3_bind_int(pAllLangid, 2, p->nIndex);\n    while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){\n      int iLangid = sqlite3_column_int(pAllLangid, 0);\n      int i;\n      for(i=0; i<p->nIndex; i++){\n        cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);\n      }\n    }\n    rc2 = sqlite3_reset(pAllLangid);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n\n  /* This block calculates the checksum according to the %_content table */\n  if( rc==SQLITE_OK ){\n    sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;\n    sqlite3_stmt *pStmt = 0;\n    char *zSql;\n   \n    zSql = sqlite3_mprintf(\"SELECT %s\" , p->zReadExprlist);\n    if( !zSql ){\n      rc = SQLITE_NOMEM;\n    }else{\n      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);\n      sqlite3_free(zSql);\n    }\n\n    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){\n      i64 iDocid = sqlite3_column_int64(pStmt, 0);\n      int iLang = langidFromSelect(p, pStmt);\n      int iCol;\n\n      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){\n        if( p->abNotindexed[iCol]==0 ){\n          const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);\n          sqlite3_tokenizer_cursor *pT = 0;\n\n          rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, -1, &pT);\n          while( rc==SQLITE_OK ){\n            char const *zToken;       /* Buffer containing token */\n            int nToken = 0;           /* Number of bytes in token */\n            int iDum1 = 0, iDum2 = 0; /* Dummy variables */\n            int iPos = 0;             /* Position of token in zText */\n\n            rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);\n            if( rc==SQLITE_OK ){\n              int i;\n              cksum2 = cksum2 ^ fts3ChecksumEntry(\n                  zToken, nToken, iLang, 0, iDocid, iCol, iPos\n              );\n              for(i=1; i<p->nIndex; i++){\n                if( p->aIndex[i].nPrefix<=nToken ){\n                  cksum2 = cksum2 ^ fts3ChecksumEntry(\n                      zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos\n                  );\n                }\n              }\n            }\n          }\n          if( pT ) pModule->xClose(pT);\n          if( rc==SQLITE_DONE ) rc = SQLITE_OK;\n        }\n      }\n    }\n\n    sqlite3_finalize(pStmt);\n  }\n\n  *pbOk = (cksum1==cksum2);\n  return rc;\n}\n\n/*\n** Run the integrity-check. If no error occurs and the current contents of\n** the FTS index are correct, return SQLITE_OK. Or, if the contents of the\n** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.\n**\n** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite \n** error code.\n**\n** The integrity-check works as follows. For each token and indexed token\n** prefix in the document set, a 64-bit checksum is calculated (by code\n** in fts3ChecksumEntry()) based on the following:\n**\n**     + The index number (0 for the main index, 1 for the first prefix\n**       index etc.),\n**     + The token (or token prefix) text itself, \n**     + The language-id of the row it appears in,\n**     + The docid of the row it appears in,\n**     + The column it appears in, and\n**     + The tokens position within that column.\n**\n** The checksums for all entries in the index are XORed together to create\n** a single checksum for the entire index.\n**\n** The integrity-check code calculates the same checksum in two ways:\n**\n**     1. By scanning the contents of the FTS index, and \n**     2. By scanning and tokenizing the content table.\n**\n** If the two checksums are identical, the integrity-check is deemed to have\n** passed.\n*/\nstatic int fts3DoIntegrityCheck(\n  Fts3Table *p                    /* FTS3 table handle */\n){\n  int rc;\n  int bOk = 0;\n  rc = fts3IntegrityCheck(p, &bOk);\n  if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;\n  return rc;\n}\n\n/*\n** Handle a 'special' INSERT of the form:\n**\n**   \"INSERT INTO tbl(tbl) VALUES(<expr>)\"\n**\n** Argument pVal contains the result of <expr>. Currently the only \n** meaningful value to insert is the text 'optimize'.\n*/\nstatic int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){\n  int rc = SQLITE_ERROR;           /* Return Code */\n  const char *zVal = (const char *)sqlite3_value_text(pVal);\n  int nVal = sqlite3_value_bytes(pVal);\n\n  if( !zVal ){\n    return SQLITE_NOMEM;\n  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, \"optimize\", 8) ){\n    rc = fts3DoOptimize(p, 0);\n  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, \"rebuild\", 7) ){\n    rc = fts3DoRebuild(p);\n  }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, \"integrity-check\", 15) ){\n    rc = fts3DoIntegrityCheck(p);\n  }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, \"merge=\", 6) ){\n    rc = fts3DoIncrmerge(p, &zVal[6]);\n  }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, \"automerge=\", 10) ){\n    rc = fts3DoAutoincrmerge(p, &zVal[10]);\n#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)\n  }else{\n    int v;\n    if( nVal>9 && 0==sqlite3_strnicmp(zVal, \"nodesize=\", 9) ){\n      v = atoi(&zVal[9]);\n      if( v>=24 && v<=p->nPgsz-35 ) p->nNodeSize = v;\n      rc = SQLITE_OK;\n    }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, \"maxpending=\", 9) ){\n      v = atoi(&zVal[11]);\n      if( v>=64 && v<=FTS3_MAX_PENDING_DATA ) p->nMaxPendingData = v;\n      rc = SQLITE_OK;\n    }else if( nVal>21 && 0==sqlite3_strnicmp(zVal,\"test-no-incr-doclist=\",21) ){\n      p->bNoIncrDoclist = atoi(&zVal[21]);\n      rc = SQLITE_OK;\n    }else if( nVal>11 && 0==sqlite3_strnicmp(zVal,\"mergecount=\",11) ){\n      v = atoi(&zVal[11]);\n      if( v>=4 && v<=FTS3_MERGE_COUNT && (v&1)==0 ) p->nMergeCount = v;\n      rc = SQLITE_OK;\n    }\n#endif\n  }\n  return rc;\n}\n\n#ifndef SQLITE_DISABLE_FTS4_DEFERRED\n/*\n** Delete all cached deferred doclists. Deferred doclists are cached\n** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.\n*/\nSQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){\n  Fts3DeferredToken *pDef;\n  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){\n    fts3PendingListDelete(pDef->pList);\n    pDef->pList = 0;\n  }\n}\n\n/*\n** Free all entries in the pCsr->pDeffered list. Entries are added to \n** this list using sqlite3Fts3DeferToken().\n*/\nSQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){\n  Fts3DeferredToken *pDef;\n  Fts3DeferredToken *pNext;\n  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){\n    pNext = pDef->pNext;\n    fts3PendingListDelete(pDef->pList);\n    sqlite3_free(pDef);\n  }\n  pCsr->pDeferred = 0;\n}\n\n/*\n** Generate deferred-doclists for all tokens in the pCsr->pDeferred list\n** based on the row that pCsr currently points to.\n**\n** A deferred-doclist is like any other doclist with position information\n** included, except that it only contains entries for a single row of the\n** table, not for all rows.\n*/\nSQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){\n  int rc = SQLITE_OK;             /* Return code */\n  if( pCsr->pDeferred ){\n    int i;                        /* Used to iterate through table columns */\n    sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */\n    Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */\n  \n    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;\n    sqlite3_tokenizer *pT = p->pTokenizer;\n    sqlite3_tokenizer_module const *pModule = pT->pModule;\n   \n    assert( pCsr->isRequireSeek==0 );\n    iDocid = sqlite3_column_int64(pCsr->pStmt, 0);\n  \n    for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){\n      if( p->abNotindexed[i]==0 ){\n        const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);\n        sqlite3_tokenizer_cursor *pTC = 0;\n\n        rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);\n        while( rc==SQLITE_OK ){\n          char const *zToken;       /* Buffer containing token */\n          int nToken = 0;           /* Number of bytes in token */\n          int iDum1 = 0, iDum2 = 0; /* Dummy variables */\n          int iPos = 0;             /* Position of token in zText */\n\n          rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);\n          for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){\n            Fts3PhraseToken *pPT = pDef->pToken;\n            if( (pDef->iCol>=p->nColumn || pDef->iCol==i)\n                && (pPT->bFirst==0 || iPos==0)\n                && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))\n                && (0==memcmp(zToken, pPT->z, pPT->n))\n              ){\n              fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);\n            }\n          }\n        }\n        if( pTC ) pModule->xClose(pTC);\n        if( rc==SQLITE_DONE ) rc = SQLITE_OK;\n      }\n    }\n\n    for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){\n      if( pDef->pList ){\n        rc = fts3PendingListAppendVarint(&pDef->pList, 0);\n      }\n    }\n  }\n\n  return rc;\n}\n\nSQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(\n  Fts3DeferredToken *p, \n  char **ppData, \n  int *pnData\n){\n  char *pRet;\n  int nSkip;\n  sqlite3_int64 dummy;\n\n  *ppData = 0;\n  *pnData = 0;\n\n  if( p->pList==0 ){\n    return SQLITE_OK;\n  }\n\n  pRet = (char *)sqlite3_malloc(p->pList->nData);\n  if( !pRet ) return SQLITE_NOMEM;\n\n  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);\n  *pnData = p->pList->nData - nSkip;\n  *ppData = pRet;\n  \n  memcpy(pRet, &p->pList->aData[nSkip], *pnData);\n  return SQLITE_OK;\n}\n\n/*\n** Add an entry for token pToken to the pCsr->pDeferred list.\n*/\nSQLITE_PRIVATE int sqlite3Fts3DeferToken(\n  Fts3Cursor *pCsr,               /* Fts3 table cursor */\n  Fts3PhraseToken *pToken,        /* Token to defer */\n  int iCol                        /* Column that token must appear in (or -1) */\n){\n  Fts3DeferredToken *pDeferred;\n  pDeferred = sqlite3_malloc(sizeof(*pDeferred));\n  if( !pDeferred ){\n    return SQLITE_NOMEM;\n  }\n  memset(pDeferred, 0, sizeof(*pDeferred));\n  pDeferred->pToken = pToken;\n  pDeferred->pNext = pCsr->pDeferred; \n  pDeferred->iCol = iCol;\n  pCsr->pDeferred = pDeferred;\n\n  assert( pToken->pDeferred==0 );\n  pToken->pDeferred = pDeferred;\n\n  return SQLITE_OK;\n}\n#endif\n\n/*\n** SQLite value pRowid contains the rowid of a row that may or may not be\n** present in the FTS3 table. If it is, delete it and adjust the contents\n** of subsiduary data structures accordingly.\n*/\nstatic int fts3DeleteByRowid(\n  Fts3Table *p, \n  sqlite3_value *pRowid, \n  int *pnChng,                    /* IN/OUT: Decrement if row is deleted */\n  u32 *aSzDel\n){\n  int rc = SQLITE_OK;             /* Return code */\n  int bFound = 0;                 /* True if *pRowid really is in the table */\n\n  fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);\n  if( bFound && rc==SQLITE_OK ){\n    int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */\n    rc = fts3IsEmpty(p, pRowid, &isEmpty);\n    if( rc==SQLITE_OK ){\n      if( isEmpty ){\n        /* Deleting this row means the whole table is empty. In this case\n        ** delete the contents of all three tables and throw away any\n        ** data in the pendingTerms hash table.  */\n        rc = fts3DeleteAll(p, 1);\n        *pnChng = 0;\n        memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);\n      }else{\n        *pnChng = *pnChng - 1;\n        if( p->zContentTbl==0 ){\n          fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);\n        }\n        if( p->bHasDocsize ){\n          fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);\n        }\n      }\n    }\n  }\n\n  return rc;\n}\n\n/*\n** This function does the work for the xUpdate method of FTS3 virtual\n** tables. The schema of the virtual table being:\n**\n**     CREATE TABLE <table name>( \n**       <user columns>,\n**       <table name> HIDDEN, \n**       docid HIDDEN, \n**       <langid> HIDDEN\n**     );\n**\n** \n*/\nSQLITE_PRIVATE int sqlite3Fts3UpdateMethod(\n  sqlite3_vtab *pVtab,            /* FTS3 vtab object */\n  int nArg,                       /* Size of argument array */\n  sqlite3_value **apVal,          /* Array of arguments */\n  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */\n){\n  Fts3Table *p = (Fts3Table *)pVtab;\n  int rc = SQLITE_OK;             /* Return Code */\n  u32 *aSzIns = 0;                /* Sizes of inserted documents */\n  u32 *aSzDel = 0;                /* Sizes of deleted documents */\n  int nChng = 0;                  /* Net change in number of documents */\n  int bInsertDone = 0;\n\n  /* At this point it must be known if the %_stat table exists or not.\n  ** So bHasStat may not be 2.  */\n  assert( p->bHasStat==0 || p->bHasStat==1 );\n\n  assert( p->pSegments==0 );\n  assert( \n      nArg==1                     /* DELETE operations */\n   || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */\n  );\n\n  /* Check for a \"special\" INSERT operation. One of the form:\n  **\n  **   INSERT INTO xyz(xyz) VALUES('command');\n  */\n  if( nArg>1 \n   && sqlite3_value_type(apVal[0])==SQLITE_NULL \n   && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL \n  ){\n    rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);\n    goto update_out;\n  }\n\n  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){\n    rc = SQLITE_CONSTRAINT;\n    goto update_out;\n  }\n\n  /* Allocate space to hold the change in document sizes */\n  aSzDel = sqlite3_malloc64(sizeof(aSzDel[0])*((sqlite3_int64)p->nColumn+1)*2);\n  if( aSzDel==0 ){\n    rc = SQLITE_NOMEM;\n    goto update_out;\n  }\n  aSzIns = &aSzDel[p->nColumn+1];\n  memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);\n\n  rc = fts3Writelock(p);\n  if( rc!=SQLITE_OK ) goto update_out;\n\n  /* If this is an INSERT operation, or an UPDATE that modifies the rowid\n  ** value, then this operation requires constraint handling.\n  **\n  ** If the on-conflict mode is REPLACE, this means that the existing row\n  ** should be deleted from the database before inserting the new row. Or,\n  ** if the on-conflict mode is other than REPLACE, then this method must\n  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to\n  ** modify the database file.\n  */\n  if( nArg>1 && p->zContentTbl==0 ){\n    /* Find the value object that holds the new rowid value. */\n    sqlite3_value *pNewRowid = apVal[3+p->nColumn];\n    if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){\n      pNewRowid = apVal[1];\n    }\n\n    if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( \n        sqlite3_value_type(apVal[0])==SQLITE_NULL\n     || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)\n    )){\n      /* The new rowid is not NULL (in this case the rowid will be\n      ** automatically assigned and there is no chance of a conflict), and \n      ** the statement is either an INSERT or an UPDATE that modifies the\n      ** rowid column. So if the conflict mode is REPLACE, then delete any\n      ** existing row with rowid=pNewRowid. \n      **\n      ** Or, if the conflict mode is not REPLACE, insert the new record into \n      ** the %_content table. If we hit the duplicate rowid constraint (or any\n      ** other error) while doing so, return immediately.\n      **\n      ** This branch may also run if pNewRowid contains a value that cannot\n      ** be losslessly converted to an integer. In this case, the eventual \n      ** call to fts3InsertData() (either just below or further on in this\n      ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is \n      ** invoked, it will delete zero rows (since no row will have\n      ** docid=$pNewRowid if $pNewRowid is not an integer value).\n      */\n      if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){\n        rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);\n      }else{\n        rc = fts3InsertData(p, apVal, pRowid);\n        bInsertDone = 1;\n      }\n    }\n  }\n  if( rc!=SQLITE_OK ){\n    goto update_out;\n  }\n\n  /* If this is a DELETE or UPDATE operation, remove the old record. */\n  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){\n    assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );\n    rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);\n  }\n  \n  /* If this is an INSERT or UPDATE operation, insert the new record. */\n  if( nArg>1 && rc==SQLITE_OK ){\n    int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);\n    if( bInsertDone==0 ){\n      rc = fts3InsertData(p, apVal, pRowid);\n      if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){\n        rc = FTS_CORRUPT_VTAB;\n      }\n    }\n    if( rc==SQLITE_OK ){\n      rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);\n    }\n    if( rc==SQLITE_OK ){\n      assert( p->iPrevDocid==*pRowid );\n      rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);\n    }\n    if( p->bHasDocsize ){\n      fts3InsertDocsize(&rc, p, aSzIns);\n    }\n    nChng++;\n  }\n\n  if( p->bFts4 ){\n    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);\n  }\n\n update_out:\n  sqlite3_free(aSzDel);\n  sqlite3Fts3SegmentsClose(p);\n  return rc;\n}\n\n/* \n** Flush any data in the pending-terms hash table to disk. If successful,\n** merge all segments in the database (including the new segment, if \n** there was any data to flush) into a single segment. \n*/\nSQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){\n  int rc;\n  rc = sqlite3_exec(p->db, \"SAVEPOINT fts3\", 0, 0, 0);\n  if( rc==SQLITE_OK ){\n    rc = fts3DoOptimize(p, 1);\n    if( rc==SQLITE_OK || rc==SQLITE_DONE ){\n      int rc2 = sqlite3_exec(p->db, \"RELEASE fts3\", 0, 0, 0);\n      if( rc2!=SQLITE_OK ) rc = rc2;\n    }else{\n      sqlite3_exec(p->db, \"ROLLBACK TO fts3\", 0, 0, 0);\n      sqlite3_exec(p->db, \"RELEASE fts3\", 0, 0, 0);\n    }\n  }\n  sqlite3Fts3SegmentsClose(p);\n  return rc;\n}\n\n#endif\n\n/************** End of fts3_write.c ******************************************/\n/************** Begin file fts3_snippet.c ************************************/\n/*\n** 2009 Oct 23\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n*/\n\n/* #include \"fts3Int.h\" */\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <string.h> */\n/* #include <assert.h> */\n\n/*\n** Characters that may appear in the second argument to matchinfo().\n*/\n#define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */\n#define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */\n#define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */\n#define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */\n#define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */\n#define FTS3_MATCHINFO_LCS       's'        /* nCol values */\n#define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */\n#define FTS3_MATCHINFO_LHITS     'y'        /* nCol*nPhrase values */\n#define FTS3_MATCHINFO_LHITS_BM  'b'        /* nCol*nPhrase values */\n\n/*\n** The default value for the second argument to matchinfo(). \n*/\n#define FTS3_MATCHINFO_DEFAULT   \"pcx\"\n\n\n/*\n** Used as an fts3ExprIterate() context when loading phrase doclists to\n** Fts3Expr.aDoclist[]/nDoclist.\n*/\ntypedef struct LoadDoclistCtx LoadDoclistCtx;\nstruct LoadDoclistCtx {\n  Fts3Cursor *pCsr;               /* FTS3 Cursor */\n  int nPhrase;                    /* Number of phrases seen so far */\n  int nToken;                     /* Number of tokens seen so far */\n};\n\n/*\n** The following types are used as part of the implementation of the \n** fts3BestSnippet() routine.\n*/\ntypedef struct SnippetIter SnippetIter;\ntypedef struct SnippetPhrase SnippetPhrase;\ntypedef struct SnippetFragment SnippetFragment;\n\nstruct SnippetIter {\n  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */\n  int iCol;                       /* Extract snippet from this column */\n  int nSnippet;                   /* Requested snippet length (in tokens) */\n  int nPhrase;                    /* Number of phrases in query */\n  SnippetPhrase *aPhrase;         /* Array of size nPhrase */\n  int iCurrent;                   /* First token of current snippet */\n};\n\nstruct SnippetPhrase {\n  int nToken;                     /* Number of tokens in phrase */\n  char *pList;                    /* Pointer to start of phrase position list */\n  int iHead;                      /* Next value in position list */\n  char *pHead;                    /* Position list data following iHead */\n  int iTail;                      /* Next value in trailing position list */\n  char *pTail;                    /* Position list data following iTail */\n};\n\nstruct SnippetFragment {\n  int iCol;                       /* Column snippet is extracted from */\n  int iPos;                       /* Index of first token in snippet */\n  u64 covered;                    /* Mask of query phrases covered */\n  u64 hlmask;                     /* Mask of snippet terms to highlight */\n};\n\n/*\n** This type is used as an fts3ExprIterate() context object while \n** accumulating the data returned by the matchinfo() function.\n*/\ntypedef struct MatchInfo MatchInfo;\nstruct MatchInfo {\n  Fts3Cursor *pCursor;            /* FTS3 Cursor */\n  int nCol;                       /* Number of columns in table */\n  int nPhrase;                    /* Number of matchable phrases in query */\n  sqlite3_int64 nDoc;             /* Number of docs in database */\n  char flag;\n  u32 *aMatchinfo;                /* Pre-allocated buffer */\n};\n\n/*\n** An instance of this structure is used to manage a pair of buffers, each\n** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below\n** for details.\n*/\nstruct MatchinfoBuffer {\n  u8 aRef[3];\n  int nElem;\n  int bGlobal;                    /* Set if global data is loaded */\n  char *zMatchinfo;\n  u32 aMatchinfo[1];\n};\n\n\n/*\n** The snippet() and offsets() functions both return text values. An instance\n** of the following structure is used to accumulate those values while the\n** functions are running. See fts3StringAppend() for details.\n*/\ntypedef struct StrBuffer StrBuffer;\nstruct StrBuffer {\n  char *z;                        /* Pointer to buffer containing string */\n  int n;                          /* Length of z in bytes (excl. nul-term) */\n  int nAlloc;                     /* Allocated size of buffer z in bytes */\n};\n\n\n/*************************************************************************\n** Start of MatchinfoBuffer code.\n*/\n\n/*\n** Allocate a two-slot MatchinfoBuffer object.\n*/\nstatic MatchinfoBuffer *fts3MIBufferNew(size_t nElem, const char *zMatchinfo){\n  MatchinfoBuffer *pRet;\n  sqlite3_int64 nByte = sizeof(u32) * (2*(sqlite3_int64)nElem + 1)\n                           + sizeof(MatchinfoBuffer);\n  sqlite3_int64 nStr = strlen(zMatchinfo);\n\n  pRet = sqlite3_malloc64(nByte + nStr+1);\n  if( pRet ){\n    memset(pRet, 0, nByte);\n    pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;\n    pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0]\n                                      + sizeof(u32)*((int)nElem+1);\n    pRet->nElem = (int)nElem;\n    pRet->zMatchinfo = ((char*)pRet) + nByte;\n    memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);\n    pRet->aRef[0] = 1;\n  }\n\n  return pRet;\n}\n\nstatic void fts3MIBufferFree(void *p){\n  MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);\n\n  assert( (u32*)p==&pBuf->aMatchinfo[1] \n       || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2] \n  );\n  if( (u32*)p==&pBuf->aMatchinfo[1] ){\n    pBuf->aRef[1] = 0;\n  }else{\n    pBuf->aRef[2] = 0;\n  }\n\n  if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){\n    sqlite3_free(pBuf);\n  }\n}\n\nstatic void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){\n  void (*xRet)(void*) = 0;\n  u32 *aOut = 0;\n\n  if( p->aRef[1]==0 ){\n    p->aRef[1] = 1;\n    aOut = &p->aMatchinfo[1];\n    xRet = fts3MIBufferFree;\n  }\n  else if( p->aRef[2]==0 ){\n    p->aRef[2] = 1;\n    aOut = &p->aMatchinfo[p->nElem+2];\n    xRet = fts3MIBufferFree;\n  }else{\n    aOut = (u32*)sqlite3_malloc64(p->nElem * sizeof(u32));\n    if( aOut ){\n      xRet = sqlite3_free;\n      if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));\n    }\n  }\n\n  *paOut = aOut;\n  return xRet;\n}\n\nstatic void fts3MIBufferSetGlobal(MatchinfoBuffer *p){\n  p->bGlobal = 1;\n  memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));\n}\n\n/*\n** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()\n*/\nSQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){\n  if( p ){\n    assert( p->aRef[0]==1 );\n    p->aRef[0] = 0;\n    if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){\n      sqlite3_free(p);\n    }\n  }\n}\n\n/* \n** End of MatchinfoBuffer code.\n*************************************************************************/\n\n\n/*\n** This function is used to help iterate through a position-list. A position\n** list is a list of unique integers, sorted from smallest to largest. Each\n** element of the list is represented by an FTS3 varint that takes the value\n** of the difference between the current element and the previous one plus\n** two. For example, to store the position-list:\n**\n**     4 9 113\n**\n** the three varints:\n**\n**     6 7 106\n**\n** are encoded.\n**\n** When this function is called, *pp points to the start of an element of\n** the list. *piPos contains the value of the previous entry in the list.\n** After it returns, *piPos contains the value of the next element of the\n** list and *pp is advanced to the following varint.\n*/\nstatic void fts3GetDeltaPosition(char **pp, int *piPos){\n  int iVal;\n  *pp += fts3GetVarint32(*pp, &iVal);\n  *piPos += (iVal-2);\n}\n\n/*\n** Helper function for fts3ExprIterate() (see below).\n*/\nstatic int fts3ExprIterate2(\n  Fts3Expr *pExpr,                /* Expression to iterate phrases of */\n  int *piPhrase,                  /* Pointer to phrase counter */\n  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */\n  void *pCtx                      /* Second argument to pass to callback */\n){\n  int rc;                         /* Return code */\n  int eType = pExpr->eType;     /* Type of expression node pExpr */\n\n  if( eType!=FTSQUERY_PHRASE ){\n    assert( pExpr->pLeft && pExpr->pRight );\n    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);\n    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){\n      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);\n    }\n  }else{\n    rc = x(pExpr, *piPhrase, pCtx);\n    (*piPhrase)++;\n  }\n  return rc;\n}\n\n/*\n** Iterate through all phrase nodes in an FTS3 query, except those that\n** are part of a sub-tree that is the right-hand-side of a NOT operator.\n** For each phrase node found, the supplied callback function is invoked.\n**\n** If the callback function returns anything other than SQLITE_OK, \n** the iteration is abandoned and the error code returned immediately.\n** Otherwise, SQLITE_OK is returned after a callback has been made for\n** all eligible phrase nodes.\n*/\nstatic int fts3ExprIterate(\n  Fts3Expr *pExpr,                /* Expression to iterate phrases of */\n  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */\n  void *pCtx                      /* Second argument to pass to callback */\n){\n  int iPhrase = 0;                /* Variable used as the phrase counter */\n  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);\n}\n\n\n/*\n** This is an fts3ExprIterate() callback used while loading the doclists\n** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also\n** fts3ExprLoadDoclists().\n*/\nstatic int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){\n  int rc = SQLITE_OK;\n  Fts3Phrase *pPhrase = pExpr->pPhrase;\n  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;\n\n  UNUSED_PARAMETER(iPhrase);\n\n  p->nPhrase++;\n  p->nToken += pPhrase->nToken;\n\n  return rc;\n}\n\n/*\n** Load the doclists for each phrase in the query associated with FTS3 cursor\n** pCsr. \n**\n** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable \n** phrases in the expression (all phrases except those directly or \n** indirectly descended from the right-hand-side of a NOT operator). If \n** pnToken is not NULL, then it is set to the number of tokens in all\n** matchable phrases of the expression.\n*/\nstatic int fts3ExprLoadDoclists(\n  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */\n  int *pnPhrase,                  /* OUT: Number of phrases in query */\n  int *pnToken                    /* OUT: Number of tokens in query */\n){\n  int rc;                         /* Return Code */\n  LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */\n  sCtx.pCsr = pCsr;\n  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);\n  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;\n  if( pnToken ) *pnToken = sCtx.nToken;\n  return rc;\n}\n\nstatic int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){\n  (*(int *)ctx)++;\n  pExpr->iPhrase = iPhrase;\n  return SQLITE_OK;\n}\nstatic int fts3ExprPhraseCount(Fts3Expr *pExpr){\n  int nPhrase = 0;\n  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);\n  return nPhrase;\n}\n\n/*\n** Advance the position list iterator specified by the first two \n** arguments so that it points to the first element with a value greater\n** than or equal to parameter iNext.\n*/\nstatic void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){\n  char *pIter = *ppIter;\n  if( pIter ){\n    int iIter = *piIter;\n\n    while( iIter<iNext ){\n      if( 0==(*pIter & 0xFE) ){\n        iIter = -1;\n        pIter = 0;\n        break;\n      }\n      fts3GetDeltaPosition(&pIter, &iIter);\n    }\n\n    *piIter = iIter;\n    *ppIter = pIter;\n  }\n}\n\n/*\n** Advance the snippet iterator to the next candidate snippet.\n*/\nstatic int fts3SnippetNextCandidate(SnippetIter *pIter){\n  int i;                          /* Loop counter */\n\n  if( pIter->iCurrent<0 ){\n    /* The SnippetIter object has just been initialized. The first snippet\n    ** candidate always starts at offset 0 (even if this candidate has a\n    ** score of 0.0).\n    */\n    pIter->iCurrent = 0;\n\n    /* Advance the 'head' iterator of each phrase to the first offset that\n    ** is greater than or equal to (iNext+nSnippet).\n    */\n    for(i=0; i<pIter->nPhrase; i++){\n      SnippetPhrase *pPhrase = &pIter->aPhrase[i];\n      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);\n    }\n  }else{\n    int iStart;\n    int iEnd = 0x7FFFFFFF;\n\n    for(i=0; i<pIter->nPhrase; i++){\n      SnippetPhrase *pPhrase = &pIter->aPhrase[i];\n      if( pPhrase->pHead && pPhrase->iHead<iEnd ){\n        iEnd = pPhrase->iHead;\n      }\n    }\n    if( iEnd==0x7FFFFFFF ){\n      return 1;\n    }\n\n    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;\n    for(i=0; i<pIter->nPhrase; i++){\n      SnippetPhrase *pPhrase = &pIter->aPhrase[i];\n      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);\n      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);\n    }\n  }\n\n  return 0;\n}\n\n/*\n** Retrieve information about the current candidate snippet of snippet \n** iterator pIter.\n*/\nstatic void fts3SnippetDetails(\n  SnippetIter *pIter,             /* Snippet iterator */\n  u64 mCovered,                   /* Bitmask of phrases already covered */\n  int *piToken,                   /* OUT: First token of proposed snippet */\n  int *piScore,                   /* OUT: \"Score\" for this snippet */\n  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */\n  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */\n){\n  int iStart = pIter->iCurrent;   /* First token of snippet */\n  int iScore = 0;                 /* Score of this snippet */\n  int i;                          /* Loop counter */\n  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */\n  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */\n\n  for(i=0; i<pIter->nPhrase; i++){\n    SnippetPhrase *pPhrase = &pIter->aPhrase[i];\n    if( pPhrase->pTail ){\n      char *pCsr = pPhrase->pTail;\n      int iCsr = pPhrase->iTail;\n\n      while( iCsr<(iStart+pIter->nSnippet) && iCsr>=iStart ){\n        int j;\n        u64 mPhrase = (u64)1 << (i%64);\n        u64 mPos = (u64)1 << (iCsr - iStart);\n        assert( iCsr>=iStart && (iCsr - iStart)<=64 );\n        assert( i>=0 );\n        if( (mCover|mCovered)&mPhrase ){\n          iScore++;\n        }else{\n          iScore += 1000;\n        }\n        mCover |= mPhrase;\n\n        for(j=0; j<pPhrase->nToken; j++){\n          mHighlight |= (mPos>>j);\n        }\n\n        if( 0==(*pCsr & 0x0FE) ) break;\n        fts3GetDeltaPosition(&pCsr, &iCsr);\n      }\n    }\n  }\n\n  /* Set the output variables before returning. */\n  *piToken = iStart;\n  *piScore = iScore;\n  *pmCover = mCover;\n  *pmHighlight = mHighlight;\n}\n\n/*\n** This function is an fts3ExprIterate() callback used by fts3BestSnippet().\n** Each invocation populates an element of the SnippetIter.aPhrase[] array.\n*/\nstatic int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){\n  SnippetIter *p = (SnippetIter *)ctx;\n  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];\n  char *pCsr;\n  int rc;\n\n  pPhrase->nToken = pExpr->pPhrase->nToken;\n  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);\n  assert( rc==SQLITE_OK || pCsr==0 );\n  if( pCsr ){\n    int iFirst = 0;\n    pPhrase->pList = pCsr;\n    fts3GetDeltaPosition(&pCsr, &iFirst);\n    if( iFirst<0 ){\n      rc = FTS_CORRUPT_VTAB;\n    }else{\n      pPhrase->pHead = pCsr;\n      pPhrase->pTail = pCsr;\n      pPhrase->iHead = iFirst;\n      pPhrase->iTail = iFirst;\n    }\n  }else{\n    assert( rc!=SQLITE_OK || (\n       pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 \n    ));\n  }\n\n  return rc;\n}\n\n/*\n** Select the fragment of text consisting of nFragment contiguous tokens \n** from column iCol that represent the \"best\" snippet. The best snippet\n** is the snippet with the highest score, where scores are calculated\n** by adding:\n**\n**   (a) +1 point for each occurrence of a matchable phrase in the snippet.\n**\n**   (b) +1000 points for the first occurrence of each matchable phrase in \n**       the snippet for which the corresponding mCovered bit is not set.\n**\n** The selected snippet parameters are stored in structure *pFragment before\n** returning. The score of the selected snippet is stored in *piScore\n** before returning.\n*/\nstatic int fts3BestSnippet(\n  int nSnippet,                   /* Desired snippet length */\n  Fts3Cursor *pCsr,               /* Cursor to create snippet for */\n  int iCol,                       /* Index of column to create snippet from */\n  u64 mCovered,                   /* Mask of phrases already covered */\n  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */\n  SnippetFragment *pFragment,     /* OUT: Best snippet found */\n  int *piScore                    /* OUT: Score of snippet pFragment */\n){\n  int rc;                         /* Return Code */\n  int nList;                      /* Number of phrases in expression */\n  SnippetIter sIter;              /* Iterates through snippet candidates */\n  sqlite3_int64 nByte;            /* Number of bytes of space to allocate */\n  int iBestScore = -1;            /* Best snippet score found so far */\n  int i;                          /* Loop counter */\n\n  memset(&sIter, 0, sizeof(sIter));\n\n  /* Iterate through the phrases in the expression to count them. The same\n  ** callback makes sure the doclists are loaded for each phrase.\n  */\n  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  /* Now that it is known how many phrases there are, allocate and zero\n  ** the required space using malloc().\n  */\n  nByte = sizeof(SnippetPhrase) * nList;\n  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc64(nByte);\n  if( !sIter.aPhrase ){\n    return SQLITE_NOMEM;\n  }\n  memset(sIter.aPhrase, 0, nByte);\n\n  /* Initialize the contents of the SnippetIter object. Then iterate through\n  ** the set of phrases in the expression to populate the aPhrase[] array.\n  */\n  sIter.pCsr = pCsr;\n  sIter.iCol = iCol;\n  sIter.nSnippet = nSnippet;\n  sIter.nPhrase = nList;\n  sIter.iCurrent = -1;\n  rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);\n  if( rc==SQLITE_OK ){\n\n    /* Set the *pmSeen output variable. */\n    for(i=0; i<nList; i++){\n      if( sIter.aPhrase[i].pHead ){\n        *pmSeen |= (u64)1 << (i%64);\n      }\n    }\n\n    /* Loop through all candidate snippets. Store the best snippet in \n     ** *pFragment. Store its associated 'score' in iBestScore.\n     */\n    pFragment->iCol = iCol;\n    while( !fts3SnippetNextCandidate(&sIter) ){\n      int iPos;\n      int iScore;\n      u64 mCover;\n      u64 mHighlite;\n      fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);\n      assert( iScore>=0 );\n      if( iScore>iBestScore ){\n        pFragment->iPos = iPos;\n        pFragment->hlmask = mHighlite;\n        pFragment->covered = mCover;\n        iBestScore = iScore;\n      }\n    }\n\n    *piScore = iBestScore;\n  }\n  sqlite3_free(sIter.aPhrase);\n  return rc;\n}\n\n\n/*\n** Append a string to the string-buffer passed as the first argument.\n**\n** If nAppend is negative, then the length of the string zAppend is\n** determined using strlen().\n*/\nstatic int fts3StringAppend(\n  StrBuffer *pStr,                /* Buffer to append to */\n  const char *zAppend,            /* Pointer to data to append to buffer */\n  int nAppend                     /* Size of zAppend in bytes (or -1) */\n){\n  if( nAppend<0 ){\n    nAppend = (int)strlen(zAppend);\n  }\n\n  /* If there is insufficient space allocated at StrBuffer.z, use realloc()\n  ** to grow the buffer until so that it is big enough to accomadate the\n  ** appended data.\n  */\n  if( pStr->n+nAppend+1>=pStr->nAlloc ){\n    sqlite3_int64 nAlloc = pStr->nAlloc+(sqlite3_int64)nAppend+100;\n    char *zNew = sqlite3_realloc64(pStr->z, nAlloc);\n    if( !zNew ){\n      return SQLITE_NOMEM;\n    }\n    pStr->z = zNew;\n    pStr->nAlloc = nAlloc;\n  }\n  assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );\n\n  /* Append the data to the string buffer. */\n  memcpy(&pStr->z[pStr->n], zAppend, nAppend);\n  pStr->n += nAppend;\n  pStr->z[pStr->n] = '\\0';\n\n  return SQLITE_OK;\n}\n\n/*\n** The fts3BestSnippet() function often selects snippets that end with a\n** query term. That is, the final term of the snippet is always a term\n** that requires highlighting. For example, if 'X' is a highlighted term\n** and '.' is a non-highlighted term, BestSnippet() may select:\n**\n**     ........X.....X\n**\n** This function \"shifts\" the beginning of the snippet forward in the \n** document so that there are approximately the same number of \n** non-highlighted terms to the right of the final highlighted term as there\n** are to the left of the first highlighted term. For example, to this:\n**\n**     ....X.....X....\n**\n** This is done as part of extracting the snippet text, not when selecting\n** the snippet. Snippet selection is done based on doclists only, so there\n** is no way for fts3BestSnippet() to know whether or not the document \n** actually contains terms that follow the final highlighted term. \n*/\nstatic int fts3SnippetShift(\n  Fts3Table *pTab,                /* FTS3 table snippet comes from */\n  int iLangid,                    /* Language id to use in tokenizing */\n  int nSnippet,                   /* Number of tokens desired for snippet */\n  const char *zDoc,               /* Document text to extract snippet from */\n  int nDoc,                       /* Size of buffer zDoc in bytes */\n  int *piPos,                     /* IN/OUT: First token of snippet */\n  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */\n){\n  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */\n\n  if( hlmask ){\n    int nLeft;                    /* Tokens to the left of first highlight */\n    int nRight;                   /* Tokens to the right of last highlight */\n    int nDesired;                 /* Ideal number of tokens to shift forward */\n\n    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);\n    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);\n    assert( (nSnippet-1-nRight)<=63 && (nSnippet-1-nRight)>=0 );\n    nDesired = (nLeft-nRight)/2;\n\n    /* Ideally, the start of the snippet should be pushed forward in the\n    ** document nDesired tokens. This block checks if there are actually\n    ** nDesired tokens to the right of the snippet. If so, *piPos and\n    ** *pHlMask are updated to shift the snippet nDesired tokens to the\n    ** right. Otherwise, the snippet is shifted by the number of tokens\n    ** available.\n    */\n    if( nDesired>0 ){\n      int nShift;                 /* Number of tokens to shift snippet by */\n      int iCurrent = 0;           /* Token counter */\n      int rc;                     /* Return Code */\n      sqlite3_tokenizer_module *pMod;\n      sqlite3_tokenizer_cursor *pC;\n      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;\n\n      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)\n      ** or more tokens in zDoc/nDoc.\n      */\n      rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){\n        const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;\n        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);\n      }\n      pMod->xClose(pC);\n      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }\n\n      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;\n      assert( nShift<=nDesired );\n      if( nShift>0 ){\n        *piPos += nShift;\n        *pHlmask = hlmask >> nShift;\n      }\n    }\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Extract the snippet text for fragment pFragment from cursor pCsr and\n** append it to string buffer pOut.\n*/\nstatic int fts3SnippetText(\n  Fts3Cursor *pCsr,               /* FTS3 Cursor */\n  SnippetFragment *pFragment,     /* Snippet to extract */\n  int iFragment,                  /* Fragment number */\n  int isLast,                     /* True for final fragment in snippet */\n  int nSnippet,                   /* Number of tokens in extracted snippet */\n  const char *zOpen,              /* String inserted before highlighted term */\n  const char *zClose,             /* String inserted after highlighted term */\n  const char *zEllipsis,          /* String inserted between snippets */\n  StrBuffer *pOut                 /* Write output here */\n){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  int rc;                         /* Return code */\n  const char *zDoc;               /* Document text to extract snippet from */\n  int nDoc;                       /* Size of zDoc in bytes */\n  int iCurrent = 0;               /* Current token number of document */\n  int iEnd = 0;                   /* Byte offset of end of current token */\n  int isShiftDone = 0;            /* True after snippet is shifted */\n  int iPos = pFragment->iPos;     /* First token of snippet */\n  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */\n  int iCol = pFragment->iCol+1;   /* Query column to extract text from */\n  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */\n  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */\n  \n  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);\n  if( zDoc==0 ){\n    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){\n      return SQLITE_NOMEM;\n    }\n    return SQLITE_OK;\n  }\n  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);\n\n  /* Open a token cursor on the document. */\n  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;\n  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  while( rc==SQLITE_OK ){\n    const char *ZDUMMY;           /* Dummy argument used with tokenizer */\n    int DUMMY1 = -1;              /* Dummy argument used with tokenizer */\n    int iBegin = 0;               /* Offset in zDoc of start of token */\n    int iFin = 0;                 /* Offset in zDoc of end of token */\n    int isHighlight = 0;          /* True for highlighted terms */\n\n    /* Variable DUMMY1 is initialized to a negative value above. Elsewhere\n    ** in the FTS code the variable that the third argument to xNext points to\n    ** is initialized to zero before the first (*but not necessarily\n    ** subsequent*) call to xNext(). This is done for a particular application\n    ** that needs to know whether or not the tokenizer is being used for\n    ** snippet generation or for some other purpose.\n    **\n    ** Extreme care is required when writing code to depend on this\n    ** initialization. It is not a documented part of the tokenizer interface.\n    ** If a tokenizer is used directly by any code outside of FTS, this\n    ** convention might not be respected.  */\n    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);\n    if( rc!=SQLITE_OK ){\n      if( rc==SQLITE_DONE ){\n        /* Special case - the last token of the snippet is also the last token\n        ** of the column. Append any punctuation that occurred between the end\n        ** of the previous token and the end of the document to the output. \n        ** Then break out of the loop. */\n        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);\n      }\n      break;\n    }\n    if( iCurrent<iPos ){ continue; }\n\n    if( !isShiftDone ){\n      int n = nDoc - iBegin;\n      rc = fts3SnippetShift(\n          pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask\n      );\n      isShiftDone = 1;\n\n      /* Now that the shift has been done, check if the initial \"...\" are\n      ** required. They are required if (a) this is not the first fragment,\n      ** or (b) this fragment does not begin at position 0 of its column. \n      */\n      if( rc==SQLITE_OK ){\n        if( iPos>0 || iFragment>0 ){\n          rc = fts3StringAppend(pOut, zEllipsis, -1);\n        }else if( iBegin ){\n          rc = fts3StringAppend(pOut, zDoc, iBegin);\n        }\n      }\n      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;\n    }\n\n    if( iCurrent>=(iPos+nSnippet) ){\n      if( isLast ){\n        rc = fts3StringAppend(pOut, zEllipsis, -1);\n      }\n      break;\n    }\n\n    /* Set isHighlight to true if this term should be highlighted. */\n    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;\n\n    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);\n    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);\n    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);\n    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);\n\n    iEnd = iFin;\n  }\n\n  pMod->xClose(pC);\n  return rc;\n}\n\n\n/*\n** This function is used to count the entries in a column-list (a \n** delta-encoded list of term offsets within a single column of a single \n** row). When this function is called, *ppCollist should point to the\n** beginning of the first varint in the column-list (the varint that\n** contains the position of the first matching term in the column data).\n** Before returning, *ppCollist is set to point to the first byte after\n** the last varint in the column-list (either the 0x00 signifying the end\n** of the position-list, or the 0x01 that precedes the column number of\n** the next column in the position-list).\n**\n** The number of elements in the column-list is returned.\n*/\nstatic int fts3ColumnlistCount(char **ppCollist){\n  char *pEnd = *ppCollist;\n  char c = 0;\n  int nEntry = 0;\n\n  /* A column-list is terminated by either a 0x01 or 0x00. */\n  while( 0xFE & (*pEnd | c) ){\n    c = *pEnd++ & 0x80;\n    if( !c ) nEntry++;\n  }\n\n  *ppCollist = pEnd;\n  return nEntry;\n}\n\n/*\n** This function gathers 'y' or 'b' data for a single phrase.\n*/\nstatic int fts3ExprLHits(\n  Fts3Expr *pExpr,                /* Phrase expression node */\n  MatchInfo *p                    /* Matchinfo context */\n){\n  Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;\n  int iStart;\n  Fts3Phrase *pPhrase = pExpr->pPhrase;\n  char *pIter = pPhrase->doclist.pList;\n  int iCol = 0;\n\n  assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );\n  if( p->flag==FTS3_MATCHINFO_LHITS ){\n    iStart = pExpr->iPhrase * p->nCol;\n  }else{\n    iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);\n  }\n\n  if( pIter ) while( 1 ){\n    int nHit = fts3ColumnlistCount(&pIter);\n    if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){\n      if( p->flag==FTS3_MATCHINFO_LHITS ){\n        p->aMatchinfo[iStart + iCol] = (u32)nHit;\n      }else if( nHit ){\n        p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));\n      }\n    }\n    assert( *pIter==0x00 || *pIter==0x01 );\n    if( *pIter!=0x01 ) break;\n    pIter++;\n    pIter += fts3GetVarint32(pIter, &iCol);\n    if( iCol>=p->nCol ) return FTS_CORRUPT_VTAB;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Gather the results for matchinfo directives 'y' and 'b'.\n*/\nstatic int fts3ExprLHitGather(\n  Fts3Expr *pExpr,\n  MatchInfo *p\n){\n  int rc = SQLITE_OK;\n  assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );\n  if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){\n    if( pExpr->pLeft ){\n      rc = fts3ExprLHitGather(pExpr->pLeft, p);\n      if( rc==SQLITE_OK ) rc = fts3ExprLHitGather(pExpr->pRight, p);\n    }else{\n      rc = fts3ExprLHits(pExpr, p);\n    }\n  }\n  return rc;\n}\n\n/*\n** fts3ExprIterate() callback used to collect the \"global\" matchinfo stats\n** for a single query. \n**\n** fts3ExprIterate() callback to load the 'global' elements of a\n** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements \n** of the matchinfo array that are constant for all rows returned by the \n** current query.\n**\n** Argument pCtx is actually a pointer to a struct of type MatchInfo. This\n** function populates Matchinfo.aMatchinfo[] as follows:\n**\n**   for(iCol=0; iCol<nCol; iCol++){\n**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;\n**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;\n**   }\n**\n** where X is the number of matches for phrase iPhrase is column iCol of all\n** rows of the table. Y is the number of rows for which column iCol contains\n** at least one instance of phrase iPhrase.\n**\n** If the phrase pExpr consists entirely of deferred tokens, then all X and\n** Y values are set to nDoc, where nDoc is the number of documents in the \n** file system. This is done because the full-text index doclist is required\n** to calculate these values properly, and the full-text index doclist is\n** not available for deferred tokens.\n*/\nstatic int fts3ExprGlobalHitsCb(\n  Fts3Expr *pExpr,                /* Phrase expression node */\n  int iPhrase,                    /* Phrase number (numbered from zero) */\n  void *pCtx                      /* Pointer to MatchInfo structure */\n){\n  MatchInfo *p = (MatchInfo *)pCtx;\n  return sqlite3Fts3EvalPhraseStats(\n      p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]\n  );\n}\n\n/*\n** fts3ExprIterate() callback used to collect the \"local\" part of the\n** FTS3_MATCHINFO_HITS array. The local stats are those elements of the \n** array that are different for each row returned by the query.\n*/\nstatic int fts3ExprLocalHitsCb(\n  Fts3Expr *pExpr,                /* Phrase expression node */\n  int iPhrase,                    /* Phrase number */\n  void *pCtx                      /* Pointer to MatchInfo structure */\n){\n  int rc = SQLITE_OK;\n  MatchInfo *p = (MatchInfo *)pCtx;\n  int iStart = iPhrase * p->nCol * 3;\n  int i;\n\n  for(i=0; i<p->nCol && rc==SQLITE_OK; i++){\n    char *pCsr;\n    rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);\n    if( pCsr ){\n      p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);\n    }else{\n      p->aMatchinfo[iStart+i*3] = 0;\n    }\n  }\n\n  return rc;\n}\n\nstatic int fts3MatchinfoCheck(\n  Fts3Table *pTab, \n  char cArg,\n  char **pzErr\n){\n  if( (cArg==FTS3_MATCHINFO_NPHRASE)\n   || (cArg==FTS3_MATCHINFO_NCOL)\n   || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)\n   || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)\n   || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)\n   || (cArg==FTS3_MATCHINFO_LCS)\n   || (cArg==FTS3_MATCHINFO_HITS)\n   || (cArg==FTS3_MATCHINFO_LHITS)\n   || (cArg==FTS3_MATCHINFO_LHITS_BM)\n  ){\n    return SQLITE_OK;\n  }\n  sqlite3Fts3ErrMsg(pzErr, \"unrecognized matchinfo request: %c\", cArg);\n  return SQLITE_ERROR;\n}\n\nstatic size_t fts3MatchinfoSize(MatchInfo *pInfo, char cArg){\n  size_t nVal;                      /* Number of integers output by cArg */\n\n  switch( cArg ){\n    case FTS3_MATCHINFO_NDOC:\n    case FTS3_MATCHINFO_NPHRASE: \n    case FTS3_MATCHINFO_NCOL: \n      nVal = 1;\n      break;\n\n    case FTS3_MATCHINFO_AVGLENGTH:\n    case FTS3_MATCHINFO_LENGTH:\n    case FTS3_MATCHINFO_LCS:\n      nVal = pInfo->nCol;\n      break;\n\n    case FTS3_MATCHINFO_LHITS:\n      nVal = pInfo->nCol * pInfo->nPhrase;\n      break;\n\n    case FTS3_MATCHINFO_LHITS_BM:\n      nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);\n      break;\n\n    default:\n      assert( cArg==FTS3_MATCHINFO_HITS );\n      nVal = pInfo->nCol * pInfo->nPhrase * 3;\n      break;\n  }\n\n  return nVal;\n}\n\nstatic int fts3MatchinfoSelectDoctotal(\n  Fts3Table *pTab,\n  sqlite3_stmt **ppStmt,\n  sqlite3_int64 *pnDoc,\n  const char **paLen,\n  const char **ppEnd\n){\n  sqlite3_stmt *pStmt;\n  const char *a;\n  const char *pEnd;\n  sqlite3_int64 nDoc;\n  int n;\n\n\n  if( !*ppStmt ){\n    int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n  pStmt = *ppStmt;\n  assert( sqlite3_data_count(pStmt)==1 );\n\n  n = sqlite3_column_bytes(pStmt, 0);\n  a = sqlite3_column_blob(pStmt, 0);\n  if( a==0 ){\n    return FTS_CORRUPT_VTAB;\n  }\n  pEnd = a + n;\n  a += sqlite3Fts3GetVarintBounded(a, pEnd, &nDoc);\n  if( nDoc<=0 || a>pEnd ){\n    return FTS_CORRUPT_VTAB;\n  }\n  *pnDoc = nDoc;\n\n  if( paLen ) *paLen = a;\n  if( ppEnd ) *ppEnd = pEnd;\n  return SQLITE_OK;\n}\n\n/*\n** An instance of the following structure is used to store state while \n** iterating through a multi-column position-list corresponding to the\n** hits for a single phrase on a single row in order to calculate the\n** values for a matchinfo() FTS3_MATCHINFO_LCS request.\n*/\ntypedef struct LcsIterator LcsIterator;\nstruct LcsIterator {\n  Fts3Expr *pExpr;                /* Pointer to phrase expression */\n  int iPosOffset;                 /* Tokens count up to end of this phrase */\n  char *pRead;                    /* Cursor used to iterate through aDoclist */\n  int iPos;                       /* Current position */\n};\n\n/* \n** If LcsIterator.iCol is set to the following value, the iterator has\n** finished iterating through all offsets for all columns.\n*/\n#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;\n\nstatic int fts3MatchinfoLcsCb(\n  Fts3Expr *pExpr,                /* Phrase expression node */\n  int iPhrase,                    /* Phrase number (numbered from zero) */\n  void *pCtx                      /* Pointer to MatchInfo structure */\n){\n  LcsIterator *aIter = (LcsIterator *)pCtx;\n  aIter[iPhrase].pExpr = pExpr;\n  return SQLITE_OK;\n}\n\n/*\n** Advance the iterator passed as an argument to the next position. Return\n** 1 if the iterator is at EOF or if it now points to the start of the\n** position list for the next column.\n*/\nstatic int fts3LcsIteratorAdvance(LcsIterator *pIter){\n  char *pRead = pIter->pRead;\n  sqlite3_int64 iRead;\n  int rc = 0;\n\n  pRead += sqlite3Fts3GetVarint(pRead, &iRead);\n  if( iRead==0 || iRead==1 ){\n    pRead = 0;\n    rc = 1;\n  }else{\n    pIter->iPos += (int)(iRead-2);\n  }\n\n  pIter->pRead = pRead;\n  return rc;\n}\n  \n/*\n** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. \n**\n** If the call is successful, the longest-common-substring lengths for each\n** column are written into the first nCol elements of the pInfo->aMatchinfo[] \n** array before returning. SQLITE_OK is returned in this case.\n**\n** Otherwise, if an error occurs, an SQLite error code is returned and the\n** data written to the first nCol elements of pInfo->aMatchinfo[] is \n** undefined.\n*/\nstatic int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){\n  LcsIterator *aIter;\n  int i;\n  int iCol;\n  int nToken = 0;\n  int rc = SQLITE_OK;\n\n  /* Allocate and populate the array of LcsIterator objects. The array\n  ** contains one element for each matchable phrase in the query.\n  **/\n  aIter = sqlite3_malloc64(sizeof(LcsIterator) * pCsr->nPhrase);\n  if( !aIter ) return SQLITE_NOMEM;\n  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);\n  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);\n\n  for(i=0; i<pInfo->nPhrase; i++){\n    LcsIterator *pIter = &aIter[i];\n    nToken -= pIter->pExpr->pPhrase->nToken;\n    pIter->iPosOffset = nToken;\n  }\n\n  for(iCol=0; iCol<pInfo->nCol; iCol++){\n    int nLcs = 0;                 /* LCS value for this column */\n    int nLive = 0;                /* Number of iterators in aIter not at EOF */\n\n    for(i=0; i<pInfo->nPhrase; i++){\n      LcsIterator *pIt = &aIter[i];\n      rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);\n      if( rc!=SQLITE_OK ) goto matchinfo_lcs_out;\n      if( pIt->pRead ){\n        pIt->iPos = pIt->iPosOffset;\n        fts3LcsIteratorAdvance(pIt);\n        if( pIt->pRead==0 ){\n          rc = FTS_CORRUPT_VTAB;\n          goto matchinfo_lcs_out;\n        }\n        nLive++;\n      }\n    }\n\n    while( nLive>0 ){\n      LcsIterator *pAdv = 0;      /* The iterator to advance by one position */\n      int nThisLcs = 0;           /* LCS for the current iterator positions */\n\n      for(i=0; i<pInfo->nPhrase; i++){\n        LcsIterator *pIter = &aIter[i];\n        if( pIter->pRead==0 ){\n          /* This iterator is already at EOF for this column. */\n          nThisLcs = 0;\n        }else{\n          if( pAdv==0 || pIter->iPos<pAdv->iPos ){\n            pAdv = pIter;\n          }\n          if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){\n            nThisLcs++;\n          }else{\n            nThisLcs = 1;\n          }\n          if( nThisLcs>nLcs ) nLcs = nThisLcs;\n        }\n      }\n      if( fts3LcsIteratorAdvance(pAdv) ) nLive--;\n    }\n\n    pInfo->aMatchinfo[iCol] = nLcs;\n  }\n\n matchinfo_lcs_out:\n  sqlite3_free(aIter);\n  return rc;\n}\n\n/*\n** Populate the buffer pInfo->aMatchinfo[] with an array of integers to\n** be returned by the matchinfo() function. Argument zArg contains the \n** format string passed as the second argument to matchinfo (or the\n** default value \"pcx\" if no second argument was specified). The format\n** string has already been validated and the pInfo->aMatchinfo[] array\n** is guaranteed to be large enough for the output.\n**\n** If bGlobal is true, then populate all fields of the matchinfo() output.\n** If it is false, then assume that those fields that do not change between\n** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)\n** have already been populated.\n**\n** Return SQLITE_OK if successful, or an SQLite error code if an error \n** occurs. If a value other than SQLITE_OK is returned, the state the\n** pInfo->aMatchinfo[] buffer is left in is undefined.\n*/\nstatic int fts3MatchinfoValues(\n  Fts3Cursor *pCsr,               /* FTS3 cursor object */\n  int bGlobal,                    /* True to grab the global stats */\n  MatchInfo *pInfo,               /* Matchinfo context object */\n  const char *zArg                /* Matchinfo format string */\n){\n  int rc = SQLITE_OK;\n  int i;\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  sqlite3_stmt *pSelect = 0;\n\n  for(i=0; rc==SQLITE_OK && zArg[i]; i++){\n    pInfo->flag = zArg[i];\n    switch( zArg[i] ){\n      case FTS3_MATCHINFO_NPHRASE:\n        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;\n        break;\n\n      case FTS3_MATCHINFO_NCOL:\n        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;\n        break;\n        \n      case FTS3_MATCHINFO_NDOC:\n        if( bGlobal ){\n          sqlite3_int64 nDoc = 0;\n          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0, 0);\n          pInfo->aMatchinfo[0] = (u32)nDoc;\n        }\n        break;\n\n      case FTS3_MATCHINFO_AVGLENGTH: \n        if( bGlobal ){\n          sqlite3_int64 nDoc;     /* Number of rows in table */\n          const char *a;          /* Aggregate column length array */\n          const char *pEnd;       /* First byte past end of length array */\n\n          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a, &pEnd);\n          if( rc==SQLITE_OK ){\n            int iCol;\n            for(iCol=0; iCol<pInfo->nCol; iCol++){\n              u32 iVal;\n              sqlite3_int64 nToken;\n              a += sqlite3Fts3GetVarint(a, &nToken);\n              if( a>pEnd ){\n                rc = SQLITE_CORRUPT_VTAB;\n                break;\n              }\n              iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);\n              pInfo->aMatchinfo[iCol] = iVal;\n            }\n          }\n        }\n        break;\n\n      case FTS3_MATCHINFO_LENGTH: {\n        sqlite3_stmt *pSelectDocsize = 0;\n        rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);\n        if( rc==SQLITE_OK ){\n          int iCol;\n          const char *a = sqlite3_column_blob(pSelectDocsize, 0);\n          const char *pEnd = a + sqlite3_column_bytes(pSelectDocsize, 0);\n          for(iCol=0; iCol<pInfo->nCol; iCol++){\n            sqlite3_int64 nToken;\n            a += sqlite3Fts3GetVarintBounded(a, pEnd, &nToken);\n            if( a>pEnd ){\n              rc = SQLITE_CORRUPT_VTAB;\n              break;\n            }\n            pInfo->aMatchinfo[iCol] = (u32)nToken;\n          }\n        }\n        sqlite3_reset(pSelectDocsize);\n        break;\n      }\n\n      case FTS3_MATCHINFO_LCS:\n        rc = fts3ExprLoadDoclists(pCsr, 0, 0);\n        if( rc==SQLITE_OK ){\n          rc = fts3MatchinfoLcs(pCsr, pInfo);\n        }\n        break;\n\n      case FTS3_MATCHINFO_LHITS_BM:\n      case FTS3_MATCHINFO_LHITS: {\n        size_t nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);\n        memset(pInfo->aMatchinfo, 0, nZero);\n        rc = fts3ExprLHitGather(pCsr->pExpr, pInfo);\n        break;\n      }\n\n      default: {\n        Fts3Expr *pExpr;\n        assert( zArg[i]==FTS3_MATCHINFO_HITS );\n        pExpr = pCsr->pExpr;\n        rc = fts3ExprLoadDoclists(pCsr, 0, 0);\n        if( rc!=SQLITE_OK ) break;\n        if( bGlobal ){\n          if( pCsr->pDeferred ){\n            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc,0,0);\n            if( rc!=SQLITE_OK ) break;\n          }\n          rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);\n          sqlite3Fts3EvalTestDeferred(pCsr, &rc);\n          if( rc!=SQLITE_OK ) break;\n        }\n        (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);\n        break;\n      }\n    }\n\n    pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);\n  }\n\n  sqlite3_reset(pSelect);\n  return rc;\n}\n\n\n/*\n** Populate pCsr->aMatchinfo[] with data for the current row. The \n** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).\n*/\nstatic void fts3GetMatchinfo(\n  sqlite3_context *pCtx,        /* Return results here */\n  Fts3Cursor *pCsr,               /* FTS3 Cursor object */\n  const char *zArg                /* Second argument to matchinfo() function */\n){\n  MatchInfo sInfo;\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  int rc = SQLITE_OK;\n  int bGlobal = 0;                /* Collect 'global' stats as well as local */\n\n  u32 *aOut = 0;\n  void (*xDestroyOut)(void*) = 0;\n\n  memset(&sInfo, 0, sizeof(MatchInfo));\n  sInfo.pCursor = pCsr;\n  sInfo.nCol = pTab->nColumn;\n\n  /* If there is cached matchinfo() data, but the format string for the \n  ** cache does not match the format string for this request, discard \n  ** the cached data. */\n  if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){\n    sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);\n    pCsr->pMIBuffer = 0;\n  }\n\n  /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the\n  ** matchinfo function has been called for this query. In this case \n  ** allocate the array used to accumulate the matchinfo data and\n  ** initialize those elements that are constant for every row.\n  */\n  if( pCsr->pMIBuffer==0 ){\n    size_t nMatchinfo = 0;        /* Number of u32 elements in match-info */\n    int i;                        /* Used to iterate through zArg */\n\n    /* Determine the number of phrases in the query */\n    pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);\n    sInfo.nPhrase = pCsr->nPhrase;\n\n    /* Determine the number of integers in the buffer returned by this call. */\n    for(i=0; zArg[i]; i++){\n      char *zErr = 0;\n      if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){\n        sqlite3_result_error(pCtx, zErr, -1);\n        sqlite3_free(zErr);\n        return;\n      }\n      nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);\n    }\n\n    /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */\n    pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);\n    if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;\n\n    pCsr->isMatchinfoNeeded = 1;\n    bGlobal = 1;\n  }\n\n  if( rc==SQLITE_OK ){\n    xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);\n    if( xDestroyOut==0 ){\n      rc = SQLITE_NOMEM;\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    sInfo.aMatchinfo = aOut;\n    sInfo.nPhrase = pCsr->nPhrase;\n    rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);\n    if( bGlobal ){\n      fts3MIBufferSetGlobal(pCsr->pMIBuffer);\n    }\n  }\n\n  if( rc!=SQLITE_OK ){\n    sqlite3_result_error_code(pCtx, rc);\n    if( xDestroyOut ) xDestroyOut(aOut);\n  }else{\n    int n = pCsr->pMIBuffer->nElem * sizeof(u32);\n    sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);\n  }\n}\n\n/*\n** Implementation of snippet() function.\n*/\nSQLITE_PRIVATE void sqlite3Fts3Snippet(\n  sqlite3_context *pCtx,          /* SQLite function call context */\n  Fts3Cursor *pCsr,               /* Cursor object */\n  const char *zStart,             /* Snippet start text - \"<b>\" */\n  const char *zEnd,               /* Snippet end text - \"</b>\" */\n  const char *zEllipsis,          /* Snippet ellipsis text - \"<b>...</b>\" */\n  int iCol,                       /* Extract snippet from this column */\n  int nToken                      /* Approximate number of tokens in snippet */\n){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  int rc = SQLITE_OK;\n  int i;\n  StrBuffer res = {0, 0, 0};\n\n  /* The returned text includes up to four fragments of text extracted from\n  ** the data in the current row. The first iteration of the for(...) loop\n  ** below attempts to locate a single fragment of text nToken tokens in \n  ** size that contains at least one instance of all phrases in the query\n  ** expression that appear in the current row. If such a fragment of text\n  ** cannot be found, the second iteration of the loop attempts to locate\n  ** a pair of fragments, and so on.\n  */\n  int nSnippet = 0;               /* Number of fragments in this snippet */\n  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */\n  int nFToken = -1;               /* Number of tokens in each fragment */\n\n  if( !pCsr->pExpr ){\n    sqlite3_result_text(pCtx, \"\", 0, SQLITE_STATIC);\n    return;\n  }\n\n  /* Limit the snippet length to 64 tokens. */\n  if( nToken<-64 ) nToken = -64;\n  if( nToken>+64 ) nToken = +64;\n\n  for(nSnippet=1; 1; nSnippet++){\n\n    int iSnip;                    /* Loop counter 0..nSnippet-1 */\n    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */\n    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */\n\n    if( nToken>=0 ){\n      nFToken = (nToken+nSnippet-1) / nSnippet;\n    }else{\n      nFToken = -1 * nToken;\n    }\n\n    for(iSnip=0; iSnip<nSnippet; iSnip++){\n      int iBestScore = -1;        /* Best score of columns checked so far */\n      int iRead;                  /* Used to iterate through columns */\n      SnippetFragment *pFragment = &aSnippet[iSnip];\n\n      memset(pFragment, 0, sizeof(*pFragment));\n\n      /* Loop through all columns of the table being considered for snippets.\n      ** If the iCol argument to this function was negative, this means all\n      ** columns of the FTS3 table. Otherwise, only column iCol is considered.\n      */\n      for(iRead=0; iRead<pTab->nColumn; iRead++){\n        SnippetFragment sF = {0, 0, 0, 0};\n        int iS = 0;\n        if( iCol>=0 && iRead!=iCol ) continue;\n\n        /* Find the best snippet of nFToken tokens in column iRead. */\n        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);\n        if( rc!=SQLITE_OK ){\n          goto snippet_out;\n        }\n        if( iS>iBestScore ){\n          *pFragment = sF;\n          iBestScore = iS;\n        }\n      }\n\n      mCovered |= pFragment->covered;\n    }\n\n    /* If all query phrases seen by fts3BestSnippet() are present in at least\n    ** one of the nSnippet snippet fragments, break out of the loop.\n    */\n    assert( (mCovered&mSeen)==mCovered );\n    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;\n  }\n\n  assert( nFToken>0 );\n\n  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){\n    rc = fts3SnippetText(pCsr, &aSnippet[i], \n        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res\n    );\n  }\n\n snippet_out:\n  sqlite3Fts3SegmentsClose(pTab);\n  if( rc!=SQLITE_OK ){\n    sqlite3_result_error_code(pCtx, rc);\n    sqlite3_free(res.z);\n  }else{\n    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);\n  }\n}\n\n\ntypedef struct TermOffset TermOffset;\ntypedef struct TermOffsetCtx TermOffsetCtx;\n\nstruct TermOffset {\n  char *pList;                    /* Position-list */\n  int iPos;                       /* Position just read from pList */\n  int iOff;                       /* Offset of this term from read positions */\n};\n\nstruct TermOffsetCtx {\n  Fts3Cursor *pCsr;\n  int iCol;                       /* Column of table to populate aTerm for */\n  int iTerm;\n  sqlite3_int64 iDocid;\n  TermOffset *aTerm;\n};\n\n/*\n** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().\n*/\nstatic int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){\n  TermOffsetCtx *p = (TermOffsetCtx *)ctx;\n  int nTerm;                      /* Number of tokens in phrase */\n  int iTerm;                      /* For looping through nTerm phrase terms */\n  char *pList;                    /* Pointer to position list for phrase */\n  int iPos = 0;                   /* First position in position-list */\n  int rc;\n\n  UNUSED_PARAMETER(iPhrase);\n  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);\n  nTerm = pExpr->pPhrase->nToken;\n  if( pList ){\n    fts3GetDeltaPosition(&pList, &iPos);\n    assert_fts3_nc( iPos>=0 );\n  }\n\n  for(iTerm=0; iTerm<nTerm; iTerm++){\n    TermOffset *pT = &p->aTerm[p->iTerm++];\n    pT->iOff = nTerm-iTerm-1;\n    pT->pList = pList;\n    pT->iPos = iPos;\n  }\n\n  return rc;\n}\n\n/*\n** Implementation of offsets() function.\n*/\nSQLITE_PRIVATE void sqlite3Fts3Offsets(\n  sqlite3_context *pCtx,          /* SQLite function call context */\n  Fts3Cursor *pCsr                /* Cursor object */\n){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;\n  int rc;                         /* Return Code */\n  int nToken;                     /* Number of tokens in query */\n  int iCol;                       /* Column currently being processed */\n  StrBuffer res = {0, 0, 0};      /* Result string */\n  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */\n\n  if( !pCsr->pExpr ){\n    sqlite3_result_text(pCtx, \"\", 0, SQLITE_STATIC);\n    return;\n  }\n\n  memset(&sCtx, 0, sizeof(sCtx));\n  assert( pCsr->isRequireSeek==0 );\n\n  /* Count the number of terms in the query */\n  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);\n  if( rc!=SQLITE_OK ) goto offsets_out;\n\n  /* Allocate the array of TermOffset iterators. */\n  sCtx.aTerm = (TermOffset *)sqlite3_malloc64(sizeof(TermOffset)*nToken);\n  if( 0==sCtx.aTerm ){\n    rc = SQLITE_NOMEM;\n    goto offsets_out;\n  }\n  sCtx.iDocid = pCsr->iPrevId;\n  sCtx.pCsr = pCsr;\n\n  /* Loop through the table columns, appending offset information to \n  ** string-buffer res for each column.\n  */\n  for(iCol=0; iCol<pTab->nColumn; iCol++){\n    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */\n    const char *ZDUMMY;           /* Dummy argument used with xNext() */\n    int NDUMMY = 0;               /* Dummy argument used with xNext() */\n    int iStart = 0;\n    int iEnd = 0;\n    int iCurrent = 0;\n    const char *zDoc;\n    int nDoc;\n\n    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is \n    ** no way that this operation can fail, so the return code from\n    ** fts3ExprIterate() can be discarded.\n    */\n    sCtx.iCol = iCol;\n    sCtx.iTerm = 0;\n    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);\n\n    /* Retreive the text stored in column iCol. If an SQL NULL is stored \n    ** in column iCol, jump immediately to the next iteration of the loop.\n    ** If an OOM occurs while retrieving the data (this can happen if SQLite\n    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM \n    ** to the caller. \n    */\n    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);\n    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);\n    if( zDoc==0 ){\n      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){\n        continue;\n      }\n      rc = SQLITE_NOMEM;\n      goto offsets_out;\n    }\n\n    /* Initialize a tokenizer iterator to iterate through column iCol. */\n    rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,\n        zDoc, nDoc, &pC\n    );\n    if( rc!=SQLITE_OK ) goto offsets_out;\n\n    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);\n    while( rc==SQLITE_OK ){\n      int i;                      /* Used to loop through terms */\n      int iMinPos = 0x7FFFFFFF;   /* Position of next token */\n      TermOffset *pTerm = 0;      /* TermOffset associated with next token */\n\n      for(i=0; i<nToken; i++){\n        TermOffset *pT = &sCtx.aTerm[i];\n        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){\n          iMinPos = pT->iPos-pT->iOff;\n          pTerm = pT;\n        }\n      }\n\n      if( !pTerm ){\n        /* All offsets for this column have been gathered. */\n        rc = SQLITE_DONE;\n      }else{\n        assert_fts3_nc( iCurrent<=iMinPos );\n        if( 0==(0xFE&*pTerm->pList) ){\n          pTerm->pList = 0;\n        }else{\n          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);\n        }\n        while( rc==SQLITE_OK && iCurrent<iMinPos ){\n          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);\n        }\n        if( rc==SQLITE_OK ){\n          char aBuffer[64];\n          sqlite3_snprintf(sizeof(aBuffer), aBuffer, \n              \"%d %d %d %d \", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart\n          );\n          rc = fts3StringAppend(&res, aBuffer, -1);\n        }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){\n          rc = FTS_CORRUPT_VTAB;\n        }\n      }\n    }\n    if( rc==SQLITE_DONE ){\n      rc = SQLITE_OK;\n    }\n\n    pMod->xClose(pC);\n    if( rc!=SQLITE_OK ) goto offsets_out;\n  }\n\n offsets_out:\n  sqlite3_free(sCtx.aTerm);\n  assert( rc!=SQLITE_DONE );\n  sqlite3Fts3SegmentsClose(pTab);\n  if( rc!=SQLITE_OK ){\n    sqlite3_result_error_code(pCtx,  rc);\n    sqlite3_free(res.z);\n  }else{\n    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);\n  }\n  return;\n}\n\n/*\n** Implementation of matchinfo() function.\n*/\nSQLITE_PRIVATE void sqlite3Fts3Matchinfo(\n  sqlite3_context *pContext,      /* Function call context */\n  Fts3Cursor *pCsr,               /* FTS3 table cursor */\n  const char *zArg                /* Second arg to matchinfo() function */\n){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  const char *zFormat;\n\n  if( zArg ){\n    zFormat = zArg;\n  }else{\n    zFormat = FTS3_MATCHINFO_DEFAULT;\n  }\n\n  if( !pCsr->pExpr ){\n    sqlite3_result_blob(pContext, \"\", 0, SQLITE_STATIC);\n    return;\n  }else{\n    /* Retrieve matchinfo() data. */\n    fts3GetMatchinfo(pContext, pCsr, zFormat);\n    sqlite3Fts3SegmentsClose(pTab);\n  }\n}\n\n#endif\n\n/************** End of fts3_snippet.c ****************************************/\n/************** Begin file fts3_unicode.c ************************************/\n/*\n** 2012 May 24\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** Implementation of the \"unicode\" full-text-search tokenizer.\n*/\n\n#ifndef SQLITE_DISABLE_FTS3_UNICODE\n\n/* #include \"fts3Int.h\" */\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <assert.h> */\n/* #include <stdlib.h> */\n/* #include <stdio.h> */\n/* #include <string.h> */\n\n/* #include \"fts3_tokenizer.h\" */\n\n/*\n** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied\n** from the sqlite3 source file utf.c. If this file is compiled as part\n** of the amalgamation, they are not required.\n*/\n#ifndef SQLITE_AMALGAMATION\n\nstatic const unsigned char sqlite3Utf8Trans1[] = {\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,\n  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,\n  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,\n};\n\n#define READ_UTF8(zIn, zTerm, c)                           \\\n  c = *(zIn++);                                            \\\n  if( c>=0xc0 ){                                           \\\n    c = sqlite3Utf8Trans1[c-0xc0];                         \\\n    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \\\n      c = (c<<6) + (0x3f & *(zIn++));                      \\\n    }                                                      \\\n    if( c<0x80                                             \\\n        || (c&0xFFFFF800)==0xD800                          \\\n        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \\\n  }\n\n#define WRITE_UTF8(zOut, c) {                          \\\n  if( c<0x00080 ){                                     \\\n    *zOut++ = (u8)(c&0xFF);                            \\\n  }                                                    \\\n  else if( c<0x00800 ){                                \\\n    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \\\n    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \\\n  }                                                    \\\n  else if( c<0x10000 ){                                \\\n    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \\\n    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \\\n    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \\\n  }else{                                               \\\n    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \\\n    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \\\n    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \\\n    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \\\n  }                                                    \\\n}\n\n#endif /* ifndef SQLITE_AMALGAMATION */\n\ntypedef struct unicode_tokenizer unicode_tokenizer;\ntypedef struct unicode_cursor unicode_cursor;\n\nstruct unicode_tokenizer {\n  sqlite3_tokenizer base;\n  int eRemoveDiacritic;\n  int nException;\n  int *aiException;\n};\n\nstruct unicode_cursor {\n  sqlite3_tokenizer_cursor base;\n  const unsigned char *aInput;    /* Input text being tokenized */\n  int nInput;                     /* Size of aInput[] in bytes */\n  int iOff;                       /* Current offset within aInput[] */\n  int iToken;                     /* Index of next token to be returned */\n  char *zToken;                   /* storage for current token */\n  int nAlloc;                     /* space allocated at zToken */\n};\n\n\n/*\n** Destroy a tokenizer allocated by unicodeCreate().\n*/\nstatic int unicodeDestroy(sqlite3_tokenizer *pTokenizer){\n  if( pTokenizer ){\n    unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;\n    sqlite3_free(p->aiException);\n    sqlite3_free(p);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE\n** statement has specified that the tokenizer for this table shall consider\n** all characters in string zIn/nIn to be separators (if bAlnum==0) or\n** token characters (if bAlnum==1).\n**\n** For each codepoint in the zIn/nIn string, this function checks if the\n** sqlite3FtsUnicodeIsalnum() function already returns the desired result.\n** If so, no action is taken. Otherwise, the codepoint is added to the \n** unicode_tokenizer.aiException[] array. For the purposes of tokenization,\n** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all\n** codepoints in the aiException[] array.\n**\n** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()\n** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.\n** It is not possible to change the behavior of the tokenizer with respect\n** to these codepoints.\n*/\nstatic int unicodeAddExceptions(\n  unicode_tokenizer *p,           /* Tokenizer to add exceptions to */\n  int bAlnum,                     /* Replace Isalnum() return value with this */\n  const char *zIn,                /* Array of characters to make exceptions */\n  int nIn                         /* Length of z in bytes */\n){\n  const unsigned char *z = (const unsigned char *)zIn;\n  const unsigned char *zTerm = &z[nIn];\n  unsigned int iCode;\n  int nEntry = 0;\n\n  assert( bAlnum==0 || bAlnum==1 );\n\n  while( z<zTerm ){\n    READ_UTF8(z, zTerm, iCode);\n    assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );\n    if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum \n     && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0 \n    ){\n      nEntry++;\n    }\n  }\n\n  if( nEntry ){\n    int *aNew;                    /* New aiException[] array */\n    int nNew;                     /* Number of valid entries in array aNew[] */\n\n    aNew = sqlite3_realloc64(p->aiException,(p->nException+nEntry)*sizeof(int));\n    if( aNew==0 ) return SQLITE_NOMEM;\n    nNew = p->nException;\n\n    z = (const unsigned char *)zIn;\n    while( z<zTerm ){\n      READ_UTF8(z, zTerm, iCode);\n      if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum \n       && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0\n      ){\n        int i, j;\n        for(i=0; i<nNew && aNew[i]<(int)iCode; i++);\n        for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];\n        aNew[i] = (int)iCode;\n        nNew++;\n      }\n    }\n    p->aiException = aNew;\n    p->nException = nNew;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Return true if the p->aiException[] array contains the value iCode.\n*/\nstatic int unicodeIsException(unicode_tokenizer *p, int iCode){\n  if( p->nException>0 ){\n    int *a = p->aiException;\n    int iLo = 0;\n    int iHi = p->nException-1;\n\n    while( iHi>=iLo ){\n      int iTest = (iHi + iLo) / 2;\n      if( iCode==a[iTest] ){\n        return 1;\n      }else if( iCode>a[iTest] ){\n        iLo = iTest+1;\n      }else{\n        iHi = iTest-1;\n      }\n    }\n  }\n\n  return 0;\n}\n\n/*\n** Return true if, for the purposes of tokenization, codepoint iCode is\n** considered a token character (not a separator).\n*/\nstatic int unicodeIsAlnum(unicode_tokenizer *p, int iCode){\n  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );\n  return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);\n}\n\n/*\n** Create a new tokenizer instance.\n*/\nstatic int unicodeCreate(\n  int nArg,                       /* Size of array argv[] */\n  const char * const *azArg,      /* Tokenizer creation arguments */\n  sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */\n){\n  unicode_tokenizer *pNew;        /* New tokenizer object */\n  int i;\n  int rc = SQLITE_OK;\n\n  pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));\n  if( pNew==NULL ) return SQLITE_NOMEM;\n  memset(pNew, 0, sizeof(unicode_tokenizer));\n  pNew->eRemoveDiacritic = 1;\n\n  for(i=0; rc==SQLITE_OK && i<nArg; i++){\n    const char *z = azArg[i];\n    int n = (int)strlen(z);\n\n    if( n==19 && memcmp(\"remove_diacritics=1\", z, 19)==0 ){\n      pNew->eRemoveDiacritic = 1;\n    }\n    else if( n==19 && memcmp(\"remove_diacritics=0\", z, 19)==0 ){\n      pNew->eRemoveDiacritic = 0;\n    }\n    else if( n==19 && memcmp(\"remove_diacritics=2\", z, 19)==0 ){\n      pNew->eRemoveDiacritic = 2;\n    }\n    else if( n>=11 && memcmp(\"tokenchars=\", z, 11)==0 ){\n      rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);\n    }\n    else if( n>=11 && memcmp(\"separators=\", z, 11)==0 ){\n      rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);\n    }\n    else{\n      /* Unrecognized argument */\n      rc  = SQLITE_ERROR;\n    }\n  }\n\n  if( rc!=SQLITE_OK ){\n    unicodeDestroy((sqlite3_tokenizer *)pNew);\n    pNew = 0;\n  }\n  *pp = (sqlite3_tokenizer *)pNew;\n  return rc;\n}\n\n/*\n** Prepare to begin tokenizing a particular string.  The input\n** string to be tokenized is pInput[0..nBytes-1].  A cursor\n** used to incrementally tokenize this string is returned in \n** *ppCursor.\n*/\nstatic int unicodeOpen(\n  sqlite3_tokenizer *p,           /* The tokenizer */\n  const char *aInput,             /* Input string */\n  int nInput,                     /* Size of string aInput in bytes */\n  sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */\n){\n  unicode_cursor *pCsr;\n\n  pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));\n  if( pCsr==0 ){\n    return SQLITE_NOMEM;\n  }\n  memset(pCsr, 0, sizeof(unicode_cursor));\n\n  pCsr->aInput = (const unsigned char *)aInput;\n  if( aInput==0 ){\n    pCsr->nInput = 0;\n  }else if( nInput<0 ){\n    pCsr->nInput = (int)strlen(aInput);\n  }else{\n    pCsr->nInput = nInput;\n  }\n\n  *pp = &pCsr->base;\n  UNUSED_PARAMETER(p);\n  return SQLITE_OK;\n}\n\n/*\n** Close a tokenization cursor previously opened by a call to\n** simpleOpen() above.\n*/\nstatic int unicodeClose(sqlite3_tokenizer_cursor *pCursor){\n  unicode_cursor *pCsr = (unicode_cursor *) pCursor;\n  sqlite3_free(pCsr->zToken);\n  sqlite3_free(pCsr);\n  return SQLITE_OK;\n}\n\n/*\n** Extract the next token from a tokenization cursor.  The cursor must\n** have been opened by a prior call to simpleOpen().\n*/\nstatic int unicodeNext(\n  sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */\n  const char **paToken,           /* OUT: Token text */\n  int *pnToken,                   /* OUT: Number of bytes at *paToken */\n  int *piStart,                   /* OUT: Starting offset of token */\n  int *piEnd,                     /* OUT: Ending offset of token */\n  int *piPos                      /* OUT: Position integer of token */\n){\n  unicode_cursor *pCsr = (unicode_cursor *)pC;\n  unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);\n  unsigned int iCode = 0;\n  char *zOut;\n  const unsigned char *z = &pCsr->aInput[pCsr->iOff];\n  const unsigned char *zStart = z;\n  const unsigned char *zEnd;\n  const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];\n\n  /* Scan past any delimiter characters before the start of the next token.\n  ** Return SQLITE_DONE early if this takes us all the way to the end of \n  ** the input.  */\n  while( z<zTerm ){\n    READ_UTF8(z, zTerm, iCode);\n    if( unicodeIsAlnum(p, (int)iCode) ) break;\n    zStart = z;\n  }\n  if( zStart>=zTerm ) return SQLITE_DONE;\n\n  zOut = pCsr->zToken;\n  do {\n    int iOut;\n\n    /* Grow the output buffer if required. */\n    if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){\n      char *zNew = sqlite3_realloc64(pCsr->zToken, pCsr->nAlloc+64);\n      if( !zNew ) return SQLITE_NOMEM;\n      zOut = &zNew[zOut - pCsr->zToken];\n      pCsr->zToken = zNew;\n      pCsr->nAlloc += 64;\n    }\n\n    /* Write the folded case of the last character read to the output */\n    zEnd = z;\n    iOut = sqlite3FtsUnicodeFold((int)iCode, p->eRemoveDiacritic);\n    if( iOut ){\n      WRITE_UTF8(zOut, iOut);\n    }\n\n    /* If the cursor is not at EOF, read the next character */\n    if( z>=zTerm ) break;\n    READ_UTF8(z, zTerm, iCode);\n  }while( unicodeIsAlnum(p, (int)iCode) \n       || sqlite3FtsUnicodeIsdiacritic((int)iCode)\n  );\n\n  /* Set the output variables and return. */\n  pCsr->iOff = (int)(z - pCsr->aInput);\n  *paToken = pCsr->zToken;\n  *pnToken = (int)(zOut - pCsr->zToken);\n  *piStart = (int)(zStart - pCsr->aInput);\n  *piEnd = (int)(zEnd - pCsr->aInput);\n  *piPos = pCsr->iToken++;\n  return SQLITE_OK;\n}\n\n/*\n** Set *ppModule to a pointer to the sqlite3_tokenizer_module \n** structure for the unicode tokenizer.\n*/\nSQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){\n  static const sqlite3_tokenizer_module module = {\n    0,\n    unicodeCreate,\n    unicodeDestroy,\n    unicodeOpen,\n    unicodeClose,\n    unicodeNext,\n    0,\n  };\n  *ppModule = &module;\n}\n\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n#endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */\n\n/************** End of fts3_unicode.c ****************************************/\n/************** Begin file fts3_unicode2.c ***********************************/\n/*\n** 2012-05-25\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n*/\n\n/*\n** DO NOT EDIT THIS MACHINE GENERATED FILE.\n*/\n\n#ifndef SQLITE_DISABLE_FTS3_UNICODE\n#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)\n\n/* #include <assert.h> */\n\n/*\n** Return true if the argument corresponds to a unicode codepoint\n** classified as either a letter or a number. Otherwise false.\n**\n** The results are undefined if the value passed to this function\n** is less than zero.\n*/\nSQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){\n  /* Each unsigned integer in the following array corresponds to a contiguous\n  ** range of unicode codepoints that are not either letters or numbers (i.e.\n  ** codepoints for which this function should return 0).\n  **\n  ** The most significant 22 bits in each 32-bit value contain the first \n  ** codepoint in the range. The least significant 10 bits are used to store\n  ** the size of the range (always at least 1). In other words, the value \n  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint \n  ** C. It is not possible to represent a range larger than 1023 codepoints \n  ** using this format.\n  */\n  static const unsigned int aEntry[] = {\n    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,\n    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,\n    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,\n    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,\n    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,\n    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,\n    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,\n    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,\n    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,\n    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,\n    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,\n    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,\n    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,\n    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,\n    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,\n    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,\n    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,\n    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,\n    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,\n    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,\n    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,\n    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,\n    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,\n    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,\n    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,\n    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,\n    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,\n    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,\n    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,\n    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,\n    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,\n    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,\n    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,\n    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,\n    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,\n    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,\n    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,\n    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,\n    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,\n    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,\n    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,\n    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,\n    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,\n    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,\n    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,\n    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,\n    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,\n    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,\n    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,\n    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,\n    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,\n    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,\n    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,\n    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,\n    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,\n    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,\n    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,\n    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,\n    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,\n    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,\n    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,\n    0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,\n    0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,\n    0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,\n    0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,\n    0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,\n    0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,\n    0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,\n    0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,\n    0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,\n    0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,\n    0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,\n    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,\n    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,\n    0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,\n    0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,\n    0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,\n    0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,\n    0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,\n    0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,\n    0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,\n    0x380400F0,\n  };\n  static const unsigned int aAscii[4] = {\n    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,\n  };\n\n  if( (unsigned int)c<128 ){\n    return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );\n  }else if( (unsigned int)c<(1<<22) ){\n    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;\n    int iRes = 0;\n    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;\n    int iLo = 0;\n    while( iHi>=iLo ){\n      int iTest = (iHi + iLo) / 2;\n      if( key >= aEntry[iTest] ){\n        iRes = iTest;\n        iLo = iTest+1;\n      }else{\n        iHi = iTest-1;\n      }\n    }\n    assert( aEntry[0]<key );\n    assert( key>=aEntry[iRes] );\n    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));\n  }\n  return 1;\n}\n\n\n/*\n** If the argument is a codepoint corresponding to a lowercase letter\n** in the ASCII range with a diacritic added, return the codepoint\n** of the ASCII letter only. For example, if passed 235 - \"LATIN\n** SMALL LETTER E WITH DIAERESIS\" - return 65 (\"LATIN SMALL LETTER\n** E\"). The resuls of passing a codepoint that corresponds to an\n** uppercase letter are undefined.\n*/\nstatic int remove_diacritic(int c, int bComplex){\n  unsigned short aDia[] = {\n        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, \n     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, \n     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, \n     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, \n     3456,  3696,  3712,  3728,  3744,  3766,  3832,  3896, \n     3912,  3928,  3944,  3968,  4008,  4040,  4056,  4106, \n     4138,  4170,  4202,  4234,  4266,  4296,  4312,  4344, \n     4408,  4424,  4442,  4472,  4488,  4504,  6148,  6198, \n     6264,  6280,  6360,  6429,  6505,  6529, 61448, 61468, \n    61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704, \n    61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914, \n    61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218, \n    62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554, \n    62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766, \n    62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118, \n    63182, 63242, 63274, 63310, 63368, 63390, \n  };\n#define HIBIT ((unsigned char)0x80)\n  unsigned char aChar[] = {\n    '\\0',      'a',       'c',       'e',       'i',       'n',       \n    'o',       'u',       'y',       'y',       'a',       'c',       \n    'd',       'e',       'e',       'g',       'h',       'i',       \n    'j',       'k',       'l',       'n',       'o',       'r',       \n    's',       't',       'u',       'u',       'w',       'y',       \n    'z',       'o',       'u',       'a',       'i',       'o',       \n    'u',       'u'|HIBIT, 'a'|HIBIT, 'g',       'k',       'o',       \n    'o'|HIBIT, 'j',       'g',       'n',       'a'|HIBIT, 'a',       \n    'e',       'i',       'o',       'r',       'u',       's',       \n    't',       'h',       'a',       'e',       'o'|HIBIT, 'o',       \n    'o'|HIBIT, 'y',       '\\0',      '\\0',      '\\0',      '\\0',      \n    '\\0',      '\\0',      '\\0',      '\\0',      'a',       'b',       \n    'c'|HIBIT, 'd',       'd',       'e'|HIBIT, 'e',       'e'|HIBIT, \n    'f',       'g',       'h',       'h',       'i',       'i'|HIBIT, \n    'k',       'l',       'l'|HIBIT, 'l',       'm',       'n',       \n    'o'|HIBIT, 'p',       'r',       'r'|HIBIT, 'r',       's',       \n    's'|HIBIT, 't',       'u',       'u'|HIBIT, 'v',       'w',       \n    'w',       'x',       'y',       'z',       'h',       't',       \n    'w',       'y',       'a',       'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT, \n    'e',       'e'|HIBIT, 'e'|HIBIT, 'i',       'o',       'o'|HIBIT, \n    'o'|HIBIT, 'o'|HIBIT, 'u',       'u'|HIBIT, 'u'|HIBIT, 'y',       \n  };\n\n  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;\n  int iRes = 0;\n  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;\n  int iLo = 0;\n  while( iHi>=iLo ){\n    int iTest = (iHi + iLo) / 2;\n    if( key >= aDia[iTest] ){\n      iRes = iTest;\n      iLo = iTest+1;\n    }else{\n      iHi = iTest-1;\n    }\n  }\n  assert( key>=aDia[iRes] );\n  if( bComplex==0 && (aChar[iRes] & 0x80) ) return c;\n  return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F);\n}\n\n\n/*\n** Return true if the argument interpreted as a unicode codepoint\n** is a diacritical modifier character.\n*/\nSQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){\n  unsigned int mask0 = 0x08029FDF;\n  unsigned int mask1 = 0x000361F8;\n  if( c<768 || c>817 ) return 0;\n  return (c < 768+32) ?\n      (mask0 & ((unsigned int)1 << (c-768))) :\n      (mask1 & ((unsigned int)1 << (c-768-32)));\n}\n\n\n/*\n** Interpret the argument as a unicode codepoint. If the codepoint\n** is an upper case character that has a lower case equivalent,\n** return the codepoint corresponding to the lower case version.\n** Otherwise, return a copy of the argument.\n**\n** The results are undefined if the value passed to this function\n** is less than zero.\n*/\nSQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){\n  /* Each entry in the following array defines a rule for folding a range\n  ** of codepoints to lower case. The rule applies to a range of nRange\n  ** codepoints starting at codepoint iCode.\n  **\n  ** If the least significant bit in flags is clear, then the rule applies\n  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and\n  ** need to be folded). Or, if it is set, then the rule only applies to\n  ** every second codepoint in the range, starting with codepoint C.\n  **\n  ** The 7 most significant bits in flags are an index into the aiOff[]\n  ** array. If a specific codepoint C does require folding, then its lower\n  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).\n  **\n  ** The contents of this array are generated by parsing the CaseFolding.txt\n  ** file distributed as part of the \"Unicode Character Database\". See\n  ** http://www.unicode.org for details.\n  */\n  static const struct TableEntry {\n    unsigned short iCode;\n    unsigned char flags;\n    unsigned char nRange;\n  } aEntry[] = {\n    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},\n    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},\n    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},\n    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},\n    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},\n    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},\n    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},\n    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},\n    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},\n    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},\n    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},\n    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},\n    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},\n    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},\n    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},\n    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},\n    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},\n    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},\n    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},\n    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},\n    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},\n    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},\n    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},\n    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},\n    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},\n    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},\n    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},\n    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},\n    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},\n    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},\n    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},\n    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},\n    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},\n    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},\n    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},\n    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},\n    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},\n    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},\n    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},\n    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},\n    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},\n    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},\n    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},\n    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},\n    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},\n    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},\n    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},\n    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},\n    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},\n    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},\n    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},\n    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},\n    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},\n    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},\n    {65313, 14, 26},       \n  };\n  static const unsigned short aiOff[] = {\n   1,     2,     8,     15,    16,    26,    28,    32,    \n   37,    38,    40,    48,    63,    64,    69,    71,    \n   79,    80,    116,   202,   203,   205,   206,   207,   \n   209,   210,   211,   213,   214,   217,   218,   219,   \n   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721, \n   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, \n   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, \n   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, \n   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, \n   65514, 65521, 65527, 65528, 65529, \n  };\n\n  int ret = c;\n\n  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );\n\n  if( c<128 ){\n    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');\n  }else if( c<65536 ){\n    const struct TableEntry *p;\n    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;\n    int iLo = 0;\n    int iRes = -1;\n\n    assert( c>aEntry[0].iCode );\n    while( iHi>=iLo ){\n      int iTest = (iHi + iLo) / 2;\n      int cmp = (c - aEntry[iTest].iCode);\n      if( cmp>=0 ){\n        iRes = iTest;\n        iLo = iTest+1;\n      }else{\n        iHi = iTest-1;\n      }\n    }\n\n    assert( iRes>=0 && c>=aEntry[iRes].iCode );\n    p = &aEntry[iRes];\n    if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){\n      ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;\n      assert( ret>0 );\n    }\n\n    if( eRemoveDiacritic ){\n      ret = remove_diacritic(ret, eRemoveDiacritic==2);\n    }\n  }\n  \n  else if( c>=66560 && c<66600 ){\n    ret = c + 40;\n  }\n\n  return ret;\n}\n#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */\n#endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */\n\n/************** End of fts3_unicode2.c ***************************************/\n/************** Begin file json1.c *******************************************/\n/*\n** 2015-08-12\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This SQLite extension implements JSON functions.  The interface is\n** modeled after MySQL JSON functions:\n**\n**     https://dev.mysql.com/doc/refman/5.7/en/json.html\n**\n** For the time being, all JSON is stored as pure text.  (We might add\n** a JSONB type in the future which stores a binary encoding of JSON in\n** a BLOB, but there is no support for JSONB in the current implementation.\n** This implementation parses JSON text at 250 MB/s, so it is hard to see\n** how JSONB might improve on that.)\n*/\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)\n#if !defined(SQLITEINT_H)\n/* #include \"sqlite3ext.h\" */\n#endif\nSQLITE_EXTENSION_INIT1\n/* #include <assert.h> */\n/* #include <string.h> */\n/* #include <stdlib.h> */\n/* #include <stdarg.h> */\n\n/* Mark a function parameter as unused, to suppress nuisance compiler\n** warnings. */\n#ifndef UNUSED_PARAM\n# define UNUSED_PARAM(X)  (void)(X)\n#endif\n\n#ifndef LARGEST_INT64\n# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))\n# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)\n#endif\n\n/*\n** Versions of isspace(), isalnum() and isdigit() to which it is safe\n** to pass signed char values.\n*/\n#ifdef sqlite3Isdigit\n   /* Use the SQLite core versions if this routine is part of the\n   ** SQLite amalgamation */\n#  define safe_isdigit(x)  sqlite3Isdigit(x)\n#  define safe_isalnum(x)  sqlite3Isalnum(x)\n#  define safe_isxdigit(x) sqlite3Isxdigit(x)\n#else\n   /* Use the standard library for separate compilation */\n#include <ctype.h>  /* amalgamator: keep */\n#  define safe_isdigit(x)  isdigit((unsigned char)(x))\n#  define safe_isalnum(x)  isalnum((unsigned char)(x))\n#  define safe_isxdigit(x) isxdigit((unsigned char)(x))\n#endif\n\n/*\n** Growing our own isspace() routine this way is twice as fast as\n** the library isspace() function, resulting in a 7% overall performance\n** increase for the parser.  (Ubuntu14.10 gcc 4.8.4 x64 with -Os).\n*/\nstatic const char jsonIsSpace[] = {\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 1, 1, 0, 0, 1, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  1, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n};\n#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])\n\n#ifndef SQLITE_AMALGAMATION\n  /* Unsigned integer types.  These are already defined in the sqliteInt.h,\n  ** but the definitions need to be repeated for separate compilation. */\n  typedef sqlite3_uint64 u64;\n  typedef unsigned int u32;\n  typedef unsigned short int u16;\n  typedef unsigned char u8;\n#endif\n\n/* Objects */\ntypedef struct JsonString JsonString;\ntypedef struct JsonNode JsonNode;\ntypedef struct JsonParse JsonParse;\n\n/* An instance of this object represents a JSON string\n** under construction.  Really, this is a generic string accumulator\n** that can be and is used to create strings other than JSON.\n*/\nstruct JsonString {\n  sqlite3_context *pCtx;   /* Function context - put error messages here */\n  char *zBuf;              /* Append JSON content here */\n  u64 nAlloc;              /* Bytes of storage available in zBuf[] */\n  u64 nUsed;               /* Bytes of zBuf[] currently used */\n  u8 bStatic;              /* True if zBuf is static space */\n  u8 bErr;                 /* True if an error has been encountered */\n  char zSpace[100];        /* Initial static space */\n};\n\n/* JSON type values\n*/\n#define JSON_NULL     0\n#define JSON_TRUE     1\n#define JSON_FALSE    2\n#define JSON_INT      3\n#define JSON_REAL     4\n#define JSON_STRING   5\n#define JSON_ARRAY    6\n#define JSON_OBJECT   7\n\n/* The \"subtype\" set for JSON values */\n#define JSON_SUBTYPE  74    /* Ascii for \"J\" */\n\n/*\n** Names of the various JSON types:\n*/\nstatic const char * const jsonType[] = {\n  \"null\", \"true\", \"false\", \"integer\", \"real\", \"text\", \"array\", \"object\"\n};\n\n/* Bit values for the JsonNode.jnFlag field\n*/\n#define JNODE_RAW     0x01         /* Content is raw, not JSON encoded */\n#define JNODE_ESCAPE  0x02         /* Content is text with \\ escapes */\n#define JNODE_REMOVE  0x04         /* Do not output */\n#define JNODE_REPLACE 0x08         /* Replace with JsonNode.u.iReplace */\n#define JNODE_PATCH   0x10         /* Patch with JsonNode.u.pPatch */\n#define JNODE_APPEND  0x20         /* More ARRAY/OBJECT entries at u.iAppend */\n#define JNODE_LABEL   0x40         /* Is a label of an object */\n\n\n/* A single node of parsed JSON\n*/\nstruct JsonNode {\n  u8 eType;              /* One of the JSON_ type values */\n  u8 jnFlags;            /* JNODE flags */\n  u32 n;                 /* Bytes of content, or number of sub-nodes */\n  union {\n    const char *zJContent; /* Content for INT, REAL, and STRING */\n    u32 iAppend;           /* More terms for ARRAY and OBJECT */\n    u32 iKey;              /* Key for ARRAY objects in json_tree() */\n    u32 iReplace;          /* Replacement content for JNODE_REPLACE */\n    JsonNode *pPatch;      /* Node chain of patch for JNODE_PATCH */\n  } u;\n};\n\n/* A completely parsed JSON string\n*/\nstruct JsonParse {\n  u32 nNode;         /* Number of slots of aNode[] used */\n  u32 nAlloc;        /* Number of slots of aNode[] allocated */\n  JsonNode *aNode;   /* Array of nodes containing the parse */\n  const char *zJson; /* Original JSON string */\n  u32 *aUp;          /* Index of parent of each node */\n  u8 oom;            /* Set to true if out of memory */\n  u8 nErr;           /* Number of errors seen */\n  u16 iDepth;        /* Nesting depth */\n  int nJson;         /* Length of the zJson string in bytes */\n  u32 iHold;         /* Replace cache line with the lowest iHold value */\n};\n\n/*\n** Maximum nesting depth of JSON for this implementation.\n**\n** This limit is needed to avoid a stack overflow in the recursive\n** descent parser.  A depth of 2000 is far deeper than any sane JSON\n** should go.\n*/\n#define JSON_MAX_DEPTH  2000\n\n/**************************************************************************\n** Utility routines for dealing with JsonString objects\n**************************************************************************/\n\n/* Set the JsonString object to an empty string\n*/\nstatic void jsonZero(JsonString *p){\n  p->zBuf = p->zSpace;\n  p->nAlloc = sizeof(p->zSpace);\n  p->nUsed = 0;\n  p->bStatic = 1;\n}\n\n/* Initialize the JsonString object\n*/\nstatic void jsonInit(JsonString *p, sqlite3_context *pCtx){\n  p->pCtx = pCtx;\n  p->bErr = 0;\n  jsonZero(p);\n}\n\n\n/* Free all allocated memory and reset the JsonString object back to its\n** initial state.\n*/\nstatic void jsonReset(JsonString *p){\n  if( !p->bStatic ) sqlite3_free(p->zBuf);\n  jsonZero(p);\n}\n\n\n/* Report an out-of-memory (OOM) condition \n*/\nstatic void jsonOom(JsonString *p){\n  p->bErr = 1;\n  sqlite3_result_error_nomem(p->pCtx);\n  jsonReset(p);\n}\n\n/* Enlarge pJson->zBuf so that it can hold at least N more bytes.\n** Return zero on success.  Return non-zero on an OOM error\n*/\nstatic int jsonGrow(JsonString *p, u32 N){\n  u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;\n  char *zNew;\n  if( p->bStatic ){\n    if( p->bErr ) return 1;\n    zNew = sqlite3_malloc64(nTotal);\n    if( zNew==0 ){\n      jsonOom(p);\n      return SQLITE_NOMEM;\n    }\n    memcpy(zNew, p->zBuf, (size_t)p->nUsed);\n    p->zBuf = zNew;\n    p->bStatic = 0;\n  }else{\n    zNew = sqlite3_realloc64(p->zBuf, nTotal);\n    if( zNew==0 ){\n      jsonOom(p);\n      return SQLITE_NOMEM;\n    }\n    p->zBuf = zNew;\n  }\n  p->nAlloc = nTotal;\n  return SQLITE_OK;\n}\n\n/* Append N bytes from zIn onto the end of the JsonString string.\n*/\nstatic void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){\n  if( N==0 ) return;\n  if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;\n  memcpy(p->zBuf+p->nUsed, zIn, N);\n  p->nUsed += N;\n}\n\n/* Append formatted text (not to exceed N bytes) to the JsonString.\n*/\nstatic void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){\n  va_list ap;\n  if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;\n  va_start(ap, zFormat);\n  sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);\n  va_end(ap);\n  p->nUsed += (int)strlen(p->zBuf+p->nUsed);\n}\n\n/* Append a single character\n*/\nstatic void jsonAppendChar(JsonString *p, char c){\n  if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;\n  p->zBuf[p->nUsed++] = c;\n}\n\n/* Append a comma separator to the output buffer, if the previous\n** character is not '[' or '{'.\n*/\nstatic void jsonAppendSeparator(JsonString *p){\n  char c;\n  if( p->nUsed==0 ) return;\n  c = p->zBuf[p->nUsed-1];\n  if( c!='[' && c!='{' ) jsonAppendChar(p, ',');\n}\n\n/* Append the N-byte string in zIn to the end of the JsonString string\n** under construction.  Enclose the string in \"...\" and escape\n** any double-quotes or backslash characters contained within the\n** string.\n*/\nstatic void jsonAppendString(JsonString *p, const char *zIn, u32 N){\n  u32 i;\n  if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;\n  p->zBuf[p->nUsed++] = '\"';\n  for(i=0; i<N; i++){\n    unsigned char c = ((unsigned const char*)zIn)[i];\n    if( c=='\"' || c=='\\\\' ){\n      json_simple_escape:\n      if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;\n      p->zBuf[p->nUsed++] = '\\\\';\n    }else if( c<=0x1f ){\n      static const char aSpecial[] = {\n         0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,\n         0, 0, 0, 0, 0, 0, 0, 0,   0,   0,   0, 0,   0,   0, 0, 0\n      };\n      assert( sizeof(aSpecial)==32 );\n      assert( aSpecial['\\b']=='b' );\n      assert( aSpecial['\\f']=='f' );\n      assert( aSpecial['\\n']=='n' );\n      assert( aSpecial['\\r']=='r' );\n      assert( aSpecial['\\t']=='t' );\n      if( aSpecial[c] ){\n        c = aSpecial[c];\n        goto json_simple_escape;\n      }\n      if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;\n      p->zBuf[p->nUsed++] = '\\\\';\n      p->zBuf[p->nUsed++] = 'u';\n      p->zBuf[p->nUsed++] = '0';\n      p->zBuf[p->nUsed++] = '0';\n      p->zBuf[p->nUsed++] = '0' + (c>>4);\n      c = \"0123456789abcdef\"[c&0xf];\n    }\n    p->zBuf[p->nUsed++] = c;\n  }\n  p->zBuf[p->nUsed++] = '\"';\n  assert( p->nUsed<p->nAlloc );\n}\n\n/*\n** Append a function parameter value to the JSON string under \n** construction.\n*/\nstatic void jsonAppendValue(\n  JsonString *p,                 /* Append to this JSON string */\n  sqlite3_value *pValue          /* Value to append */\n){\n  switch( sqlite3_value_type(pValue) ){\n    case SQLITE_NULL: {\n      jsonAppendRaw(p, \"null\", 4);\n      break;\n    }\n    case SQLITE_INTEGER:\n    case SQLITE_FLOAT: {\n      const char *z = (const char*)sqlite3_value_text(pValue);\n      u32 n = (u32)sqlite3_value_bytes(pValue);\n      jsonAppendRaw(p, z, n);\n      break;\n    }\n    case SQLITE_TEXT: {\n      const char *z = (const char*)sqlite3_value_text(pValue);\n      u32 n = (u32)sqlite3_value_bytes(pValue);\n      if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){\n        jsonAppendRaw(p, z, n);\n      }else{\n        jsonAppendString(p, z, n);\n      }\n      break;\n    }\n    default: {\n      if( p->bErr==0 ){\n        sqlite3_result_error(p->pCtx, \"JSON cannot hold BLOB values\", -1);\n        p->bErr = 2;\n        jsonReset(p);\n      }\n      break;\n    }\n  }\n}\n\n\n/* Make the JSON in p the result of the SQL function.\n*/\nstatic void jsonResult(JsonString *p){\n  if( p->bErr==0 ){\n    sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed, \n                          p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,\n                          SQLITE_UTF8);\n    jsonZero(p);\n  }\n  assert( p->bStatic );\n}\n\n/**************************************************************************\n** Utility routines for dealing with JsonNode and JsonParse objects\n**************************************************************************/\n\n/*\n** Return the number of consecutive JsonNode slots need to represent\n** the parsed JSON at pNode.  The minimum answer is 1.  For ARRAY and\n** OBJECT types, the number might be larger.\n**\n** Appended elements are not counted.  The value returned is the number\n** by which the JsonNode counter should increment in order to go to the\n** next peer value.\n*/\nstatic u32 jsonNodeSize(JsonNode *pNode){\n  return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;\n}\n\n/*\n** Reclaim all memory allocated by a JsonParse object.  But do not\n** delete the JsonParse object itself.\n*/\nstatic void jsonParseReset(JsonParse *pParse){\n  sqlite3_free(pParse->aNode);\n  pParse->aNode = 0;\n  pParse->nNode = 0;\n  pParse->nAlloc = 0;\n  sqlite3_free(pParse->aUp);\n  pParse->aUp = 0;\n}\n\n/*\n** Free a JsonParse object that was obtained from sqlite3_malloc().\n*/\nstatic void jsonParseFree(JsonParse *pParse){\n  jsonParseReset(pParse);\n  sqlite3_free(pParse);\n}\n\n/*\n** Convert the JsonNode pNode into a pure JSON string and\n** append to pOut.  Subsubstructure is also included.  Return\n** the number of JsonNode objects that are encoded.\n*/\nstatic void jsonRenderNode(\n  JsonNode *pNode,               /* The node to render */\n  JsonString *pOut,              /* Write JSON here */\n  sqlite3_value **aReplace       /* Replacement values */\n){\n  if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){\n    if( pNode->jnFlags & JNODE_REPLACE ){\n      jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);\n      return;\n    }\n    pNode = pNode->u.pPatch;\n  }\n  switch( pNode->eType ){\n    default: {\n      assert( pNode->eType==JSON_NULL );\n      jsonAppendRaw(pOut, \"null\", 4);\n      break;\n    }\n    case JSON_TRUE: {\n      jsonAppendRaw(pOut, \"true\", 4);\n      break;\n    }\n    case JSON_FALSE: {\n      jsonAppendRaw(pOut, \"false\", 5);\n      break;\n    }\n    case JSON_STRING: {\n      if( pNode->jnFlags & JNODE_RAW ){\n        jsonAppendString(pOut, pNode->u.zJContent, pNode->n);\n        break;\n      }\n      /* Fall through into the next case */\n    }\n    case JSON_REAL:\n    case JSON_INT: {\n      jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);\n      break;\n    }\n    case JSON_ARRAY: {\n      u32 j = 1;\n      jsonAppendChar(pOut, '[');\n      for(;;){\n        while( j<=pNode->n ){\n          if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){\n            jsonAppendSeparator(pOut);\n            jsonRenderNode(&pNode[j], pOut, aReplace);\n          }\n          j += jsonNodeSize(&pNode[j]);\n        }\n        if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;\n        pNode = &pNode[pNode->u.iAppend];\n        j = 1;\n      }\n      jsonAppendChar(pOut, ']');\n      break;\n    }\n    case JSON_OBJECT: {\n      u32 j = 1;\n      jsonAppendChar(pOut, '{');\n      for(;;){\n        while( j<=pNode->n ){\n          if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){\n            jsonAppendSeparator(pOut);\n            jsonRenderNode(&pNode[j], pOut, aReplace);\n            jsonAppendChar(pOut, ':');\n            jsonRenderNode(&pNode[j+1], pOut, aReplace);\n          }\n          j += 1 + jsonNodeSize(&pNode[j+1]);\n        }\n        if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;\n        pNode = &pNode[pNode->u.iAppend];\n        j = 1;\n      }\n      jsonAppendChar(pOut, '}');\n      break;\n    }\n  }\n}\n\n/*\n** Return a JsonNode and all its descendents as a JSON string.\n*/\nstatic void jsonReturnJson(\n  JsonNode *pNode,            /* Node to return */\n  sqlite3_context *pCtx,      /* Return value for this function */\n  sqlite3_value **aReplace    /* Array of replacement values */\n){\n  JsonString s;\n  jsonInit(&s, pCtx);\n  jsonRenderNode(pNode, &s, aReplace);\n  jsonResult(&s);\n  sqlite3_result_subtype(pCtx, JSON_SUBTYPE);\n}\n\n/*\n** Translate a single byte of Hex into an integer.\n** This routine only works if h really is a valid hexadecimal\n** character:  0..9a..fA..F\n*/\nstatic u8 jsonHexToInt(int h){\n  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );\n#ifdef SQLITE_EBCDIC\n  h += 9*(1&~(h>>4));\n#else\n  h += 9*(1&(h>>6));\n#endif\n  return (u8)(h & 0xf);\n}\n\n/*\n** Convert a 4-byte hex string into an integer\n*/\nstatic u32 jsonHexToInt4(const char *z){\n  u32 v;\n  assert( safe_isxdigit(z[0]) );\n  assert( safe_isxdigit(z[1]) );\n  assert( safe_isxdigit(z[2]) );\n  assert( safe_isxdigit(z[3]) );\n  v = (jsonHexToInt(z[0])<<12)\n    + (jsonHexToInt(z[1])<<8)\n    + (jsonHexToInt(z[2])<<4)\n    + jsonHexToInt(z[3]);\n  return v;\n}\n\n/*\n** Make the JsonNode the return value of the function.\n*/\nstatic void jsonReturn(\n  JsonNode *pNode,            /* Node to return */\n  sqlite3_context *pCtx,      /* Return value for this function */\n  sqlite3_value **aReplace    /* Array of replacement values */\n){\n  switch( pNode->eType ){\n    default: {\n      assert( pNode->eType==JSON_NULL );\n      sqlite3_result_null(pCtx);\n      break;\n    }\n    case JSON_TRUE: {\n      sqlite3_result_int(pCtx, 1);\n      break;\n    }\n    case JSON_FALSE: {\n      sqlite3_result_int(pCtx, 0);\n      break;\n    }\n    case JSON_INT: {\n      sqlite3_int64 i = 0;\n      const char *z = pNode->u.zJContent;\n      if( z[0]=='-' ){ z++; }\n      while( z[0]>='0' && z[0]<='9' ){\n        unsigned v = *(z++) - '0';\n        if( i>=LARGEST_INT64/10 ){\n          if( i>LARGEST_INT64/10 ) goto int_as_real;\n          if( z[0]>='0' && z[0]<='9' ) goto int_as_real;\n          if( v==9 ) goto int_as_real;\n          if( v==8 ){\n            if( pNode->u.zJContent[0]=='-' ){\n              sqlite3_result_int64(pCtx, SMALLEST_INT64);\n              goto int_done;\n            }else{\n              goto int_as_real;\n            }\n          }\n        }\n        i = i*10 + v;\n      }\n      if( pNode->u.zJContent[0]=='-' ){ i = -i; }\n      sqlite3_result_int64(pCtx, i);\n      int_done:\n      break;\n      int_as_real: /* fall through to real */;\n    }\n    case JSON_REAL: {\n      double r;\n#ifdef SQLITE_AMALGAMATION\n      const char *z = pNode->u.zJContent;\n      sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);\n#else\n      r = strtod(pNode->u.zJContent, 0);\n#endif\n      sqlite3_result_double(pCtx, r);\n      break;\n    }\n    case JSON_STRING: {\n#if 0 /* Never happens because JNODE_RAW is only set by json_set(),\n      ** json_insert() and json_replace() and those routines do not\n      ** call jsonReturn() */\n      if( pNode->jnFlags & JNODE_RAW ){\n        sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,\n                            SQLITE_TRANSIENT);\n      }else \n#endif\n      assert( (pNode->jnFlags & JNODE_RAW)==0 );\n      if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){\n        /* JSON formatted without any backslash-escapes */\n        sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,\n                            SQLITE_TRANSIENT);\n      }else{\n        /* Translate JSON formatted string into raw text */\n        u32 i;\n        u32 n = pNode->n;\n        const char *z = pNode->u.zJContent;\n        char *zOut;\n        u32 j;\n        zOut = sqlite3_malloc( n+1 );\n        if( zOut==0 ){\n          sqlite3_result_error_nomem(pCtx);\n          break;\n        }\n        for(i=1, j=0; i<n-1; i++){\n          char c = z[i];\n          if( c!='\\\\' ){\n            zOut[j++] = c;\n          }else{\n            c = z[++i];\n            if( c=='u' ){\n              u32 v = jsonHexToInt4(z+i+1);\n              i += 4;\n              if( v==0 ) break;\n              if( v<=0x7f ){\n                zOut[j++] = (char)v;\n              }else if( v<=0x7ff ){\n                zOut[j++] = (char)(0xc0 | (v>>6));\n                zOut[j++] = 0x80 | (v&0x3f);\n              }else{\n                u32 vlo;\n                if( (v&0xfc00)==0xd800\n                  && i<n-6\n                  && z[i+1]=='\\\\'\n                  && z[i+2]=='u'\n                  && ((vlo = jsonHexToInt4(z+i+3))&0xfc00)==0xdc00\n                ){\n                  /* We have a surrogate pair */\n                  v = ((v&0x3ff)<<10) + (vlo&0x3ff) + 0x10000;\n                  i += 6;\n                  zOut[j++] = 0xf0 | (v>>18);\n                  zOut[j++] = 0x80 | ((v>>12)&0x3f);\n                  zOut[j++] = 0x80 | ((v>>6)&0x3f);\n                  zOut[j++] = 0x80 | (v&0x3f);\n                }else{\n                  zOut[j++] = 0xe0 | (v>>12);\n                  zOut[j++] = 0x80 | ((v>>6)&0x3f);\n                  zOut[j++] = 0x80 | (v&0x3f);\n                }\n              }\n            }else{\n              if( c=='b' ){\n                c = '\\b';\n              }else if( c=='f' ){\n                c = '\\f';\n              }else if( c=='n' ){\n                c = '\\n';\n              }else if( c=='r' ){\n                c = '\\r';\n              }else if( c=='t' ){\n                c = '\\t';\n              }\n              zOut[j++] = c;\n            }\n          }\n        }\n        zOut[j] = 0;\n        sqlite3_result_text(pCtx, zOut, j, sqlite3_free);\n      }\n      break;\n    }\n    case JSON_ARRAY:\n    case JSON_OBJECT: {\n      jsonReturnJson(pNode, pCtx, aReplace);\n      break;\n    }\n  }\n}\n\n/* Forward reference */\nstatic int jsonParseAddNode(JsonParse*,u32,u32,const char*);\n\n/*\n** A macro to hint to the compiler that a function should not be\n** inlined.\n*/\n#if defined(__GNUC__)\n#  define JSON_NOINLINE  __attribute__((noinline))\n#elif defined(_MSC_VER) && _MSC_VER>=1310\n#  define JSON_NOINLINE  __declspec(noinline)\n#else\n#  define JSON_NOINLINE\n#endif\n\n\nstatic JSON_NOINLINE int jsonParseAddNodeExpand(\n  JsonParse *pParse,        /* Append the node to this object */\n  u32 eType,                /* Node type */\n  u32 n,                    /* Content size or sub-node count */\n  const char *zContent      /* Content */\n){\n  u32 nNew;\n  JsonNode *pNew;\n  assert( pParse->nNode>=pParse->nAlloc );\n  if( pParse->oom ) return -1;\n  nNew = pParse->nAlloc*2 + 10;\n  pNew = sqlite3_realloc64(pParse->aNode, sizeof(JsonNode)*nNew);\n  if( pNew==0 ){\n    pParse->oom = 1;\n    return -1;\n  }\n  pParse->nAlloc = nNew;\n  pParse->aNode = pNew;\n  assert( pParse->nNode<pParse->nAlloc );\n  return jsonParseAddNode(pParse, eType, n, zContent);\n}\n\n/*\n** Create a new JsonNode instance based on the arguments and append that\n** instance to the JsonParse.  Return the index in pParse->aNode[] of the\n** new node, or -1 if a memory allocation fails.\n*/\nstatic int jsonParseAddNode(\n  JsonParse *pParse,        /* Append the node to this object */\n  u32 eType,                /* Node type */\n  u32 n,                    /* Content size or sub-node count */\n  const char *zContent      /* Content */\n){\n  JsonNode *p;\n  if( pParse->nNode>=pParse->nAlloc ){\n    return jsonParseAddNodeExpand(pParse, eType, n, zContent);\n  }\n  p = &pParse->aNode[pParse->nNode];\n  p->eType = (u8)eType;\n  p->jnFlags = 0;\n  p->n = n;\n  p->u.zJContent = zContent;\n  return pParse->nNode++;\n}\n\n/*\n** Return true if z[] begins with 4 (or more) hexadecimal digits\n*/\nstatic int jsonIs4Hex(const char *z){\n  int i;\n  for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;\n  return 1;\n}\n\n/*\n** Parse a single JSON value which begins at pParse->zJson[i].  Return the\n** index of the first character past the end of the value parsed.\n**\n** Return negative for a syntax error.  Special cases:  return -2 if the\n** first non-whitespace character is '}' and return -3 if the first\n** non-whitespace character is ']'.\n*/\nstatic int jsonParseValue(JsonParse *pParse, u32 i){\n  char c;\n  u32 j;\n  int iThis;\n  int x;\n  JsonNode *pNode;\n  const char *z = pParse->zJson;\n  while( safe_isspace(z[i]) ){ i++; }\n  if( (c = z[i])=='{' ){\n    /* Parse object */\n    iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);\n    if( iThis<0 ) return -1;\n    for(j=i+1;;j++){\n      while( safe_isspace(z[j]) ){ j++; }\n      if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;\n      x = jsonParseValue(pParse, j);\n      if( x<0 ){\n        pParse->iDepth--;\n        if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;\n        return -1;\n      }\n      if( pParse->oom ) return -1;\n      pNode = &pParse->aNode[pParse->nNode-1];\n      if( pNode->eType!=JSON_STRING ) return -1;\n      pNode->jnFlags |= JNODE_LABEL;\n      j = x;\n      while( safe_isspace(z[j]) ){ j++; }\n      if( z[j]!=':' ) return -1;\n      j++;\n      x = jsonParseValue(pParse, j);\n      pParse->iDepth--;\n      if( x<0 ) return -1;\n      j = x;\n      while( safe_isspace(z[j]) ){ j++; }\n      c = z[j];\n      if( c==',' ) continue;\n      if( c!='}' ) return -1;\n      break;\n    }\n    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;\n    return j+1;\n  }else if( c=='[' ){\n    /* Parse array */\n    iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);\n    if( iThis<0 ) return -1;\n    for(j=i+1;;j++){\n      while( safe_isspace(z[j]) ){ j++; }\n      if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;\n      x = jsonParseValue(pParse, j);\n      pParse->iDepth--;\n      if( x<0 ){\n        if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;\n        return -1;\n      }\n      j = x;\n      while( safe_isspace(z[j]) ){ j++; }\n      c = z[j];\n      if( c==',' ) continue;\n      if( c!=']' ) return -1;\n      break;\n    }\n    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;\n    return j+1;\n  }else if( c=='\"' ){\n    /* Parse string */\n    u8 jnFlags = 0;\n    j = i+1;\n    for(;;){\n      c = z[j];\n      if( (c & ~0x1f)==0 ){\n        /* Control characters are not allowed in strings */\n        return -1;\n      }\n      if( c=='\\\\' ){\n        c = z[++j];\n        if( c=='\"' || c=='\\\\' || c=='/' || c=='b' || c=='f'\n           || c=='n' || c=='r' || c=='t'\n           || (c=='u' && jsonIs4Hex(z+j+1)) ){\n          jnFlags = JNODE_ESCAPE;\n        }else{\n          return -1;\n        }\n      }else if( c=='\"' ){\n        break;\n      }\n      j++;\n    }\n    jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);\n    if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;\n    return j+1;\n  }else if( c=='n'\n         && strncmp(z+i,\"null\",4)==0\n         && !safe_isalnum(z[i+4]) ){\n    jsonParseAddNode(pParse, JSON_NULL, 0, 0);\n    return i+4;\n  }else if( c=='t'\n         && strncmp(z+i,\"true\",4)==0\n         && !safe_isalnum(z[i+4]) ){\n    jsonParseAddNode(pParse, JSON_TRUE, 0, 0);\n    return i+4;\n  }else if( c=='f'\n         && strncmp(z+i,\"false\",5)==0\n         && !safe_isalnum(z[i+5]) ){\n    jsonParseAddNode(pParse, JSON_FALSE, 0, 0);\n    return i+5;\n  }else if( c=='-' || (c>='0' && c<='9') ){\n    /* Parse number */\n    u8 seenDP = 0;\n    u8 seenE = 0;\n    assert( '-' < '0' );\n    if( c<='0' ){\n      j = c=='-' ? i+1 : i;\n      if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;\n    }\n    j = i+1;\n    for(;; j++){\n      c = z[j];\n      if( c>='0' && c<='9' ) continue;\n      if( c=='.' ){\n        if( z[j-1]=='-' ) return -1;\n        if( seenDP ) return -1;\n        seenDP = 1;\n        continue;\n      }\n      if( c=='e' || c=='E' ){\n        if( z[j-1]<'0' ) return -1;\n        if( seenE ) return -1;\n        seenDP = seenE = 1;\n        c = z[j+1];\n        if( c=='+' || c=='-' ){\n          j++;\n          c = z[j+1];\n        }\n        if( c<'0' || c>'9' ) return -1;\n        continue;\n      }\n      break;\n    }\n    if( z[j-1]<'0' ) return -1;\n    jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,\n                        j - i, &z[i]);\n    return j;\n  }else if( c=='}' ){\n    return -2;  /* End of {...} */\n  }else if( c==']' ){\n    return -3;  /* End of [...] */\n  }else if( c==0 ){\n    return 0;   /* End of file */\n  }else{\n    return -1;  /* Syntax error */\n  }\n}\n\n/*\n** Parse a complete JSON string.  Return 0 on success or non-zero if there\n** are any errors.  If an error occurs, free all memory associated with\n** pParse.\n**\n** pParse is uninitialized when this routine is called.\n*/\nstatic int jsonParse(\n  JsonParse *pParse,           /* Initialize and fill this JsonParse object */\n  sqlite3_context *pCtx,       /* Report errors here */\n  const char *zJson            /* Input JSON text to be parsed */\n){\n  int i;\n  memset(pParse, 0, sizeof(*pParse));\n  if( zJson==0 ) return 1;\n  pParse->zJson = zJson;\n  i = jsonParseValue(pParse, 0);\n  if( pParse->oom ) i = -1;\n  if( i>0 ){\n    assert( pParse->iDepth==0 );\n    while( safe_isspace(zJson[i]) ) i++;\n    if( zJson[i] ) i = -1;\n  }\n  if( i<=0 ){\n    if( pCtx!=0 ){\n      if( pParse->oom ){\n        sqlite3_result_error_nomem(pCtx);\n      }else{\n        sqlite3_result_error(pCtx, \"malformed JSON\", -1);\n      }\n    }\n    jsonParseReset(pParse);\n    return 1;\n  }\n  return 0;\n}\n\n/* Mark node i of pParse as being a child of iParent.  Call recursively\n** to fill in all the descendants of node i.\n*/\nstatic void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){\n  JsonNode *pNode = &pParse->aNode[i];\n  u32 j;\n  pParse->aUp[i] = iParent;\n  switch( pNode->eType ){\n    case JSON_ARRAY: {\n      for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){\n        jsonParseFillInParentage(pParse, i+j, i);\n      }\n      break;\n    }\n    case JSON_OBJECT: {\n      for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){\n        pParse->aUp[i+j] = i;\n        jsonParseFillInParentage(pParse, i+j+1, i);\n      }\n      break;\n    }\n    default: {\n      break;\n    }\n  }\n}\n\n/*\n** Compute the parentage of all nodes in a completed parse.\n*/\nstatic int jsonParseFindParents(JsonParse *pParse){\n  u32 *aUp;\n  assert( pParse->aUp==0 );\n  aUp = pParse->aUp = sqlite3_malloc64( sizeof(u32)*pParse->nNode );\n  if( aUp==0 ){\n    pParse->oom = 1;\n    return SQLITE_NOMEM;\n  }\n  jsonParseFillInParentage(pParse, 0, 0);\n  return SQLITE_OK;\n}\n\n/*\n** Magic number used for the JSON parse cache in sqlite3_get_auxdata()\n*/\n#define JSON_CACHE_ID  (-429938)  /* First cache entry */\n#define JSON_CACHE_SZ  4          /* Max number of cache entries */\n\n/*\n** Obtain a complete parse of the JSON found in the first argument\n** of the argv array.  Use the sqlite3_get_auxdata() cache for this\n** parse if it is available.  If the cache is not available or if it\n** is no longer valid, parse the JSON again and return the new parse,\n** and also register the new parse so that it will be available for\n** future sqlite3_get_auxdata() calls.\n*/\nstatic JsonParse *jsonParseCached(\n  sqlite3_context *pCtx,\n  sqlite3_value **argv,\n  sqlite3_context *pErrCtx\n){\n  const char *zJson = (const char*)sqlite3_value_text(argv[0]);\n  int nJson = sqlite3_value_bytes(argv[0]);\n  JsonParse *p;\n  JsonParse *pMatch = 0;\n  int iKey;\n  int iMinKey = 0;\n  u32 iMinHold = 0xffffffff;\n  u32 iMaxHold = 0;\n  if( zJson==0 ) return 0;\n  for(iKey=0; iKey<JSON_CACHE_SZ; iKey++){\n    p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iKey);\n    if( p==0 ){\n      iMinKey = iKey;\n      break;\n    }\n    if( pMatch==0\n     && p->nJson==nJson\n     && memcmp(p->zJson,zJson,nJson)==0\n    ){\n      p->nErr = 0;\n      pMatch = p;\n    }else if( p->iHold<iMinHold ){\n      iMinHold = p->iHold;\n      iMinKey = iKey;\n    }\n    if( p->iHold>iMaxHold ){\n      iMaxHold = p->iHold;\n    }\n  }\n  if( pMatch ){\n    pMatch->nErr = 0;\n    pMatch->iHold = iMaxHold+1;\n    return pMatch;\n  }\n  p = sqlite3_malloc64( sizeof(*p) + nJson + 1 );\n  if( p==0 ){\n    sqlite3_result_error_nomem(pCtx);\n    return 0;\n  }\n  memset(p, 0, sizeof(*p));\n  p->zJson = (char*)&p[1];\n  memcpy((char*)p->zJson, zJson, nJson+1);\n  if( jsonParse(p, pErrCtx, p->zJson) ){\n    sqlite3_free(p);\n    return 0;\n  }\n  p->nJson = nJson;\n  p->iHold = iMaxHold+1;\n  sqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p,\n                      (void(*)(void*))jsonParseFree);\n  return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey);\n}\n\n/*\n** Compare the OBJECT label at pNode against zKey,nKey.  Return true on\n** a match.\n*/\nstatic int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){\n  if( pNode->jnFlags & JNODE_RAW ){\n    if( pNode->n!=nKey ) return 0;\n    return strncmp(pNode->u.zJContent, zKey, nKey)==0;\n  }else{\n    if( pNode->n!=nKey+2 ) return 0;\n    return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;\n  }\n}\n\n/* forward declaration */\nstatic JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);\n\n/*\n** Search along zPath to find the node specified.  Return a pointer\n** to that node, or NULL if zPath is malformed or if there is no such\n** node.\n**\n** If pApnd!=0, then try to append new nodes to complete zPath if it is\n** possible to do so and if no existing node corresponds to zPath.  If\n** new nodes are appended *pApnd is set to 1.\n*/\nstatic JsonNode *jsonLookupStep(\n  JsonParse *pParse,      /* The JSON to search */\n  u32 iRoot,              /* Begin the search at this node */\n  const char *zPath,      /* The path to search */\n  int *pApnd,             /* Append nodes to complete path if not NULL */\n  const char **pzErr      /* Make *pzErr point to any syntax error in zPath */\n){\n  u32 i, j, nKey;\n  const char *zKey;\n  JsonNode *pRoot = &pParse->aNode[iRoot];\n  if( zPath[0]==0 ) return pRoot;\n  if( pRoot->jnFlags & JNODE_REPLACE ) return 0;\n  if( zPath[0]=='.' ){\n    if( pRoot->eType!=JSON_OBJECT ) return 0;\n    zPath++;\n    if( zPath[0]=='\"' ){\n      zKey = zPath + 1;\n      for(i=1; zPath[i] && zPath[i]!='\"'; i++){}\n      nKey = i-1;\n      if( zPath[i] ){\n        i++;\n      }else{\n        *pzErr = zPath;\n        return 0;\n      }\n    }else{\n      zKey = zPath;\n      for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}\n      nKey = i;\n    }\n    if( nKey==0 ){\n      *pzErr = zPath;\n      return 0;\n    }\n    j = 1;\n    for(;;){\n      while( j<=pRoot->n ){\n        if( jsonLabelCompare(pRoot+j, zKey, nKey) ){\n          return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);\n        }\n        j++;\n        j += jsonNodeSize(&pRoot[j]);\n      }\n      if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;\n      iRoot += pRoot->u.iAppend;\n      pRoot = &pParse->aNode[iRoot];\n      j = 1;\n    }\n    if( pApnd ){\n      u32 iStart, iLabel;\n      JsonNode *pNode;\n      iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);\n      iLabel = jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);\n      zPath += i;\n      pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);\n      if( pParse->oom ) return 0;\n      if( pNode ){\n        pRoot = &pParse->aNode[iRoot];\n        pRoot->u.iAppend = iStart - iRoot;\n        pRoot->jnFlags |= JNODE_APPEND;\n        pParse->aNode[iLabel].jnFlags |= JNODE_RAW;\n      }\n      return pNode;\n    }\n  }else if( zPath[0]=='[' ){\n    i = 0;\n    j = 1;\n    while( safe_isdigit(zPath[j]) ){\n      i = i*10 + zPath[j] - '0';\n      j++;\n    }\n    if( j<2 || zPath[j]!=']' ){\n      if( zPath[1]=='#' ){\n        JsonNode *pBase = pRoot;\n        int iBase = iRoot;\n        if( pRoot->eType!=JSON_ARRAY ) return 0;\n        for(;;){\n          while( j<=pBase->n ){\n            if( (pBase[j].jnFlags & JNODE_REMOVE)==0 ) i++;\n            j += jsonNodeSize(&pBase[j]);\n          }\n          if( (pBase->jnFlags & JNODE_APPEND)==0 ) break;\n          iBase += pBase->u.iAppend;\n          pBase = &pParse->aNode[iBase];\n          j = 1;\n        }\n        j = 2;\n        if( zPath[2]=='-' && safe_isdigit(zPath[3]) ){\n          unsigned int x = 0;\n          j = 3;\n          do{\n            x = x*10 + zPath[j] - '0';\n            j++;\n          }while( safe_isdigit(zPath[j]) );\n          if( x>i ) return 0;\n          i -= x;\n        }\n        if( zPath[j]!=']' ){\n          *pzErr = zPath;\n          return 0;\n        }\n      }else{\n        *pzErr = zPath;\n        return 0;\n      }\n    }\n    if( pRoot->eType!=JSON_ARRAY ) return 0;\n    zPath += j + 1;\n    j = 1;\n    for(;;){\n      while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){\n        if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;\n        j += jsonNodeSize(&pRoot[j]);\n      }\n      if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;\n      iRoot += pRoot->u.iAppend;\n      pRoot = &pParse->aNode[iRoot];\n      j = 1;\n    }\n    if( j<=pRoot->n ){\n      return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);\n    }\n    if( i==0 && pApnd ){\n      u32 iStart;\n      JsonNode *pNode;\n      iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);\n      pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);\n      if( pParse->oom ) return 0;\n      if( pNode ){\n        pRoot = &pParse->aNode[iRoot];\n        pRoot->u.iAppend = iStart - iRoot;\n        pRoot->jnFlags |= JNODE_APPEND;\n      }\n      return pNode;\n    }\n  }else{\n    *pzErr = zPath;\n  }\n  return 0;\n}\n\n/*\n** Append content to pParse that will complete zPath.  Return a pointer\n** to the inserted node, or return NULL if the append fails.\n*/\nstatic JsonNode *jsonLookupAppend(\n  JsonParse *pParse,     /* Append content to the JSON parse */\n  const char *zPath,     /* Description of content to append */\n  int *pApnd,            /* Set this flag to 1 */\n  const char **pzErr     /* Make this point to any syntax error */\n){\n  *pApnd = 1;\n  if( zPath[0]==0 ){\n    jsonParseAddNode(pParse, JSON_NULL, 0, 0);\n    return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];\n  }\n  if( zPath[0]=='.' ){\n    jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);\n  }else if( strncmp(zPath,\"[0]\",3)==0 ){\n    jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);\n  }else{\n    return 0;\n  }\n  if( pParse->oom ) return 0;\n  return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);\n}\n\n/*\n** Return the text of a syntax error message on a JSON path.  Space is\n** obtained from sqlite3_malloc().\n*/\nstatic char *jsonPathSyntaxError(const char *zErr){\n  return sqlite3_mprintf(\"JSON path error near '%q'\", zErr);\n}\n\n/*\n** Do a node lookup using zPath.  Return a pointer to the node on success.\n** Return NULL if not found or if there is an error.\n**\n** On an error, write an error message into pCtx and increment the\n** pParse->nErr counter.\n**\n** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if\n** nodes are appended.\n*/\nstatic JsonNode *jsonLookup(\n  JsonParse *pParse,      /* The JSON to search */\n  const char *zPath,      /* The path to search */\n  int *pApnd,             /* Append nodes to complete path if not NULL */\n  sqlite3_context *pCtx   /* Report errors here, if not NULL */\n){\n  const char *zErr = 0;\n  JsonNode *pNode = 0;\n  char *zMsg;\n\n  if( zPath==0 ) return 0;\n  if( zPath[0]!='$' ){\n    zErr = zPath;\n    goto lookup_err;\n  }\n  zPath++;\n  pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);\n  if( zErr==0 ) return pNode;\n\nlookup_err:\n  pParse->nErr++;\n  assert( zErr!=0 && pCtx!=0 );\n  zMsg = jsonPathSyntaxError(zErr);\n  if( zMsg ){\n    sqlite3_result_error(pCtx, zMsg, -1);\n    sqlite3_free(zMsg);\n  }else{\n    sqlite3_result_error_nomem(pCtx);\n  }\n  return 0;\n}\n\n\n/*\n** Report the wrong number of arguments for json_insert(), json_replace()\n** or json_set().\n*/\nstatic void jsonWrongNumArgs(\n  sqlite3_context *pCtx,\n  const char *zFuncName\n){\n  char *zMsg = sqlite3_mprintf(\"json_%s() needs an odd number of arguments\",\n                               zFuncName);\n  sqlite3_result_error(pCtx, zMsg, -1);\n  sqlite3_free(zMsg);     \n}\n\n/*\n** Mark all NULL entries in the Object passed in as JNODE_REMOVE.\n*/\nstatic void jsonRemoveAllNulls(JsonNode *pNode){\n  int i, n;\n  assert( pNode->eType==JSON_OBJECT );\n  n = pNode->n;\n  for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){\n    switch( pNode[i].eType ){\n      case JSON_NULL:\n        pNode[i].jnFlags |= JNODE_REMOVE;\n        break;\n      case JSON_OBJECT:\n        jsonRemoveAllNulls(&pNode[i]);\n        break;\n    }\n  }\n}\n\n\n/****************************************************************************\n** SQL functions used for testing and debugging\n****************************************************************************/\n\n#ifdef SQLITE_DEBUG\n/*\n** The json_parse(JSON) function returns a string which describes\n** a parse of the JSON provided.  Or it returns NULL if JSON is not\n** well-formed.\n*/\nstatic void jsonParseFunc(\n  sqlite3_context *ctx,\n  int argc,\n  sqlite3_value **argv\n){\n  JsonString s;       /* Output string - not real JSON */\n  JsonParse x;        /* The parse */\n  u32 i;\n\n  assert( argc==1 );\n  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;\n  jsonParseFindParents(&x);\n  jsonInit(&s, ctx);\n  for(i=0; i<x.nNode; i++){\n    const char *zType;\n    if( x.aNode[i].jnFlags & JNODE_LABEL ){\n      assert( x.aNode[i].eType==JSON_STRING );\n      zType = \"label\";\n    }else{\n      zType = jsonType[x.aNode[i].eType];\n    }\n    jsonPrintf(100, &s,\"node %3u: %7s n=%-4d up=%-4d\",\n               i, zType, x.aNode[i].n, x.aUp[i]);\n    if( x.aNode[i].u.zJContent!=0 ){\n      jsonAppendRaw(&s, \" \", 1);\n      jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);\n    }\n    jsonAppendRaw(&s, \"\\n\", 1);\n  }\n  jsonParseReset(&x);\n  jsonResult(&s);\n}\n\n/*\n** The json_test1(JSON) function return true (1) if the input is JSON\n** text generated by another json function.  It returns (0) if the input\n** is not known to be JSON.\n*/\nstatic void jsonTest1Func(\n  sqlite3_context *ctx,\n  int argc,\n  sqlite3_value **argv\n){\n  UNUSED_PARAM(argc);\n  sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);\n}\n#endif /* SQLITE_DEBUG */\n\n/****************************************************************************\n** Scalar SQL function implementations\n****************************************************************************/\n\n/*\n** Implementation of the json_QUOTE(VALUE) function.  Return a JSON value\n** corresponding to the SQL value input.  Mostly this means putting \n** double-quotes around strings and returning the unquoted string \"null\"\n** when given a NULL input.\n*/\nstatic void jsonQuoteFunc(\n  sqlite3_context *ctx,\n  int argc,\n  sqlite3_value **argv\n){\n  JsonString jx;\n  UNUSED_PARAM(argc);\n\n  jsonInit(&jx, ctx);\n  jsonAppendValue(&jx, argv[0]);\n  jsonResult(&jx);\n  sqlite3_result_subtype(ctx, JSON_SUBTYPE);\n}\n\n/*\n** Implementation of the json_array(VALUE,...) function.  Return a JSON\n** array that contains all values given in arguments.  Or if any argument\n** is a BLOB, throw an error.\n*/\nstatic void jsonArrayFunc(\n  sqlite3_context *ctx,\n  int argc,\n  sqlite3_value **argv\n){\n  int i;\n  JsonString jx;\n\n  jsonInit(&jx, ctx);\n  jsonAppendChar(&jx, '[');\n  for(i=0; i<argc; i++){\n    jsonAppendSeparator(&jx);\n    jsonAppendValue(&jx, argv[i]);\n  }\n  jsonAppendChar(&jx, ']');\n  jsonResult(&jx);\n  sqlite3_result_subtype(ctx, JSON_SUBTYPE);\n}\n\n\n/*\n** json_array_length(JSON)\n** json_array_length(JSON, PATH)\n**\n** Return the number of elements in the top-level JSON array.  \n** Return 0 if the input is not a well-formed JSON array.\n*/\nstatic void jsonArrayLengthFunc(\n  sqlite3_context *ctx,\n  int argc,\n  sqlite3_value **argv\n){\n  JsonParse *p;          /* The parse */\n  sqlite3_int64 n = 0;\n  u32 i;\n  JsonNode *pNode;\n\n  p = jsonParseCached(ctx, argv, ctx);\n  if( p==0 ) return;\n  assert( p->nNode );\n  if( argc==2 ){\n    const char *zPath = (const char*)sqlite3_value_text(argv[1]);\n    pNode = jsonLookup(p, zPath, 0, ctx);\n  }else{\n    pNode = p->aNode;\n  }\n  if( pNode==0 ){\n    return;\n  }\n  if( pNode->eType==JSON_ARRAY ){\n    assert( (pNode->jnFlags & JNODE_APPEND)==0 );\n    for(i=1; i<=pNode->n; n++){\n      i += jsonNodeSize(&pNode[i]);\n    }\n  }\n  sqlite3_result_int64(ctx, n);\n}\n\n/*\n** json_extract(JSON, PATH, ...)\n**\n** Return the element described by PATH.  Return NULL if there is no\n** PATH element.  If there are multiple PATHs, then return a JSON array\n** with the result from each path.  Throw an error if the JSON or any PATH\n** is malformed.\n*/\nstatic void jsonExtractFunc(\n  sqlite3_context *ctx,\n  int argc,\n  sqlite3_value **argv\n){\n  JsonParse *p;          /* The parse */\n  JsonNode *pNode;\n  const char *zPath;\n  JsonString jx;\n  int i;\n\n  if( argc<2 ) return;\n  p = jsonParseCached(ctx, argv, ctx);\n  if( p==0 ) return;\n  jsonInit(&jx, ctx);\n  jsonAppendChar(&jx, '[');\n  for(i=1; i<argc; i++){\n    zPath = (const char*)sqlite3_value_text(argv[i]);\n    pNode = jsonLookup(p, zPath, 0, ctx);\n    if( p->nErr ) break;\n    if( argc>2 ){\n      jsonAppendSeparator(&jx);\n      if( pNode ){\n        jsonRenderNode(pNode, &jx, 0);\n      }else{\n        jsonAppendRaw(&jx, \"null\", 4);\n      }\n    }else if( pNode ){\n      jsonReturn(pNode, ctx, 0);\n    }\n  }\n  if( argc>2 && i==argc ){\n    jsonAppendChar(&jx, ']');\n    jsonResult(&jx);\n    sqlite3_result_subtype(ctx, JSON_SUBTYPE);\n  }\n  jsonReset(&jx);\n}\n\n/* This is the RFC 7396 MergePatch algorithm.\n*/\nstatic JsonNode *jsonMergePatch(\n  JsonParse *pParse,   /* The JSON parser that contains the TARGET */\n  u32 iTarget,         /* Node of the TARGET in pParse */\n  JsonNode *pPatch     /* The PATCH */\n){\n  u32 i, j;\n  u32 iRoot;\n  JsonNode *pTarget;\n  if( pPatch->eType!=JSON_OBJECT ){\n    return pPatch;\n  }\n  assert( iTarget>=0 && iTarget<pParse->nNode );\n  pTarget = &pParse->aNode[iTarget];\n  assert( (pPatch->jnFlags & JNODE_APPEND)==0 );\n  if( pTarget->eType!=JSON_OBJECT ){\n    jsonRemoveAllNulls(pPatch);\n    return pPatch;\n  }\n  iRoot = iTarget;\n  for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){\n    u32 nKey;\n    const char *zKey;\n    assert( pPatch[i].eType==JSON_STRING );\n    assert( pPatch[i].jnFlags & JNODE_LABEL );\n    nKey = pPatch[i].n;\n    zKey = pPatch[i].u.zJContent;\n    assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );\n    for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){\n      assert( pTarget[j].eType==JSON_STRING );\n      assert( pTarget[j].jnFlags & JNODE_LABEL );\n      assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );\n      if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){\n        if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;\n        if( pPatch[i+1].eType==JSON_NULL ){\n          pTarget[j+1].jnFlags |= JNODE_REMOVE;\n        }else{\n          JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);\n          if( pNew==0 ) return 0;\n          pTarget = &pParse->aNode[iTarget];\n          if( pNew!=&pTarget[j+1] ){\n            pTarget[j+1].u.pPatch = pNew;\n            pTarget[j+1].jnFlags |= JNODE_PATCH;\n          }\n        }\n        break;\n      }\n    }\n    if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){\n      int iStart, iPatch;\n      iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);\n      jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);\n      iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);\n      if( pParse->oom ) return 0;\n      jsonRemoveAllNulls(pPatch);\n      pTarget = &pParse->aNode[iTarget];\n      pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;\n      pParse->aNode[iRoot].u.iAppend = iStart - iRoot;\n      iRoot = iStart;\n      pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;\n      pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];\n    }\n  }\n  return pTarget;\n}\n\n/*\n** Implementation of the json_mergepatch(JSON1,JSON2) function.  Return a JSON\n** object that is the result of running the RFC 7396 MergePatch() algorithm\n** on the two arguments.\n*/\nstatic void jsonPatchFunc(\n  sqlite3_context *ctx,\n  int argc,\n  sqlite3_value **argv\n){\n  JsonParse x;     /* The JSON that is being patched */\n  JsonParse y;     /* The patch */\n  JsonNode *pResult;   /* The result of the merge */\n\n  UNUSED_PARAM(argc);\n  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;\n  if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){\n    jsonParseReset(&x);\n    return;\n  }\n  pResult = jsonMergePatch(&x, 0, y.aNode);\n  assert( pResult!=0 || x.oom );\n  if( pResult ){\n    jsonReturnJson(pResult, ctx, 0);\n  }else{\n    sqlite3_result_error_nomem(ctx);\n  }\n  jsonParseReset(&x);\n  jsonParseReset(&y);\n}\n\n\n/*\n** Implementation of the json_object(NAME,VALUE,...) function.  Return a JSON\n** object that contains all name/value given in arguments.  Or if any name\n** is not a string or if any value is a BLOB, throw an error.\n*/\nstatic void jsonObjectFunc(\n  sqlite3_context *ctx,\n  int argc,\n  sqlite3_value **argv\n){\n  int i;\n  JsonString jx;\n  const char *z;\n  u32 n;\n\n  if( argc&1 ){\n    sqlite3_result_error(ctx, \"json_object() requires an even number \"\n                                  \"of arguments\", -1);\n    return;\n  }\n  jsonInit(&jx, ctx);\n  jsonAppendChar(&jx, '{');\n  for(i=0; i<argc; i+=2){\n    if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){\n      sqlite3_result_error(ctx, \"json_object() labels must be TEXT\", -1);\n      jsonReset(&jx);\n      return;\n    }\n    jsonAppendSeparator(&jx);\n    z = (const char*)sqlite3_value_text(argv[i]);\n    n = (u32)sqlite3_value_bytes(argv[i]);\n    jsonAppendString(&jx, z, n);\n    jsonAppendChar(&jx, ':');\n    jsonAppendValue(&jx, argv[i+1]);\n  }\n  jsonAppendChar(&jx, '}');\n  jsonResult(&jx);\n  sqlite3_result_subtype(ctx, JSON_SUBTYPE);\n}\n\n\n/*\n** json_remove(JSON, PATH, ...)\n**\n** Remove the named elements from JSON and return the result.  malformed\n** JSON or PATH arguments result in an error.\n*/\nstatic void jsonRemoveFunc(\n  sqlite3_context *ctx,\n  int argc,\n  sqlite3_value **argv\n){\n  JsonParse x;          /* The parse */\n  JsonNode *pNode;\n  const char *zPath;\n  u32 i;\n\n  if( argc<1 ) return;\n  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;\n  assert( x.nNode );\n  for(i=1; i<(u32)argc; i++){\n    zPath = (const char*)sqlite3_value_text(argv[i]);\n    if( zPath==0 ) goto remove_done;\n    pNode = jsonLookup(&x, zPath, 0, ctx);\n    if( x.nErr ) goto remove_done;\n    if( pNode ) pNode->jnFlags |= JNODE_REMOVE;\n  }\n  if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){\n    jsonReturnJson(x.aNode, ctx, 0);\n  }\nremove_done:\n  jsonParseReset(&x);\n}\n\n/*\n** json_replace(JSON, PATH, VALUE, ...)\n**\n** Replace the value at PATH with VALUE.  If PATH does not already exist,\n** this routine is a no-op.  If JSON or PATH is malformed, throw an error.\n*/\nstatic void jsonReplaceFunc(\n  sqlite3_context *ctx,\n  int argc,\n  sqlite3_value **argv\n){\n  JsonParse x;          /* The parse */\n  JsonNode *pNode;\n  const char *zPath;\n  u32 i;\n\n  if( argc<1 ) return;\n  if( (argc&1)==0 ) {\n    jsonWrongNumArgs(ctx, \"replace\");\n    return;\n  }\n  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;\n  assert( x.nNode );\n  for(i=1; i<(u32)argc; i+=2){\n    zPath = (const char*)sqlite3_value_text(argv[i]);\n    pNode = jsonLookup(&x, zPath, 0, ctx);\n    if( x.nErr ) goto replace_err;\n    if( pNode ){\n      pNode->jnFlags |= (u8)JNODE_REPLACE;\n      pNode->u.iReplace = i + 1;\n    }\n  }\n  if( x.aNode[0].jnFlags & JNODE_REPLACE ){\n    sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);\n  }else{\n    jsonReturnJson(x.aNode, ctx, argv);\n  }\nreplace_err:\n  jsonParseReset(&x);\n}\n\n/*\n** json_set(JSON, PATH, VALUE, ...)\n**\n** Set the value at PATH to VALUE.  Create the PATH if it does not already\n** exist.  Overwrite existing values that do exist.\n** If JSON or PATH is malformed, throw an error.\n**\n** json_insert(JSON, PATH, VALUE, ...)\n**\n** Create PATH and initialize it to VALUE.  If PATH already exists, this\n** routine is a no-op.  If JSON or PATH is malformed, throw an error.\n*/\nstatic void jsonSetFunc(\n  sqlite3_context *ctx,\n  int argc,\n  sqlite3_value **argv\n){\n  JsonParse x;          /* The parse */\n  JsonNode *pNode;\n  const char *zPath;\n  u32 i;\n  int bApnd;\n  int bIsSet = *(int*)sqlite3_user_data(ctx);\n\n  if( argc<1 ) return;\n  if( (argc&1)==0 ) {\n    jsonWrongNumArgs(ctx, bIsSet ? \"set\" : \"insert\");\n    return;\n  }\n  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;\n  assert( x.nNode );\n  for(i=1; i<(u32)argc; i+=2){\n    zPath = (const char*)sqlite3_value_text(argv[i]);\n    bApnd = 0;\n    pNode = jsonLookup(&x, zPath, &bApnd, ctx);\n    if( x.oom ){\n      sqlite3_result_error_nomem(ctx);\n      goto jsonSetDone;\n    }else if( x.nErr ){\n      goto jsonSetDone;\n    }else if( pNode && (bApnd || bIsSet) ){\n      pNode->jnFlags |= (u8)JNODE_REPLACE;\n      pNode->u.iReplace = i + 1;\n    }\n  }\n  if( x.aNode[0].jnFlags & JNODE_REPLACE ){\n    sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);\n  }else{\n    jsonReturnJson(x.aNode, ctx, argv);\n  }\njsonSetDone:\n  jsonParseReset(&x);\n}\n\n/*\n** json_type(JSON)\n** json_type(JSON, PATH)\n**\n** Return the top-level \"type\" of a JSON string.  Throw an error if\n** either the JSON or PATH inputs are not well-formed.\n*/\nstatic void jsonTypeFunc(\n  sqlite3_context *ctx,\n  int argc,\n  sqlite3_value **argv\n){\n  JsonParse *p;          /* The parse */\n  const char *zPath;\n  JsonNode *pNode;\n\n  p = jsonParseCached(ctx, argv, ctx);\n  if( p==0 ) return;\n  if( argc==2 ){\n    zPath = (const char*)sqlite3_value_text(argv[1]);\n    pNode = jsonLookup(p, zPath, 0, ctx);\n  }else{\n    pNode = p->aNode;\n  }\n  if( pNode ){\n    sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);\n  }\n}\n\n/*\n** json_valid(JSON)\n**\n** Return 1 if JSON is a well-formed JSON string according to RFC-7159.\n** Return 0 otherwise.\n*/\nstatic void jsonValidFunc(\n  sqlite3_context *ctx,\n  int argc,\n  sqlite3_value **argv\n){\n  JsonParse *p;          /* The parse */\n  UNUSED_PARAM(argc);\n  p = jsonParseCached(ctx, argv, 0);\n  sqlite3_result_int(ctx, p!=0);\n}\n\n\n/****************************************************************************\n** Aggregate SQL function implementations\n****************************************************************************/\n/*\n** json_group_array(VALUE)\n**\n** Return a JSON array composed of all values in the aggregate.\n*/\nstatic void jsonArrayStep(\n  sqlite3_context *ctx,\n  int argc,\n  sqlite3_value **argv\n){\n  JsonString *pStr;\n  UNUSED_PARAM(argc);\n  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));\n  if( pStr ){\n    if( pStr->zBuf==0 ){\n      jsonInit(pStr, ctx);\n      jsonAppendChar(pStr, '[');\n    }else if( pStr->nUsed>1 ){\n      jsonAppendChar(pStr, ',');\n      pStr->pCtx = ctx;\n    }\n    jsonAppendValue(pStr, argv[0]);\n  }\n}\nstatic void jsonArrayCompute(sqlite3_context *ctx, int isFinal){\n  JsonString *pStr;\n  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);\n  if( pStr ){\n    pStr->pCtx = ctx;\n    jsonAppendChar(pStr, ']');\n    if( pStr->bErr ){\n      if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);\n      assert( pStr->bStatic );\n    }else if( isFinal ){\n      sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,\n                          pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);\n      pStr->bStatic = 1;\n    }else{\n      sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);\n      pStr->nUsed--;\n    }\n  }else{\n    sqlite3_result_text(ctx, \"[]\", 2, SQLITE_STATIC);\n  }\n  sqlite3_result_subtype(ctx, JSON_SUBTYPE);\n}\nstatic void jsonArrayValue(sqlite3_context *ctx){\n  jsonArrayCompute(ctx, 0);\n}\nstatic void jsonArrayFinal(sqlite3_context *ctx){\n  jsonArrayCompute(ctx, 1);\n}\n\n#ifndef SQLITE_OMIT_WINDOWFUNC\n/*\n** This method works for both json_group_array() and json_group_object().\n** It works by removing the first element of the group by searching forward\n** to the first comma (\",\") that is not within a string and deleting all\n** text through that comma.\n*/\nstatic void jsonGroupInverse(\n  sqlite3_context *ctx,\n  int argc,\n  sqlite3_value **argv\n){\n  unsigned int i;\n  int inStr = 0;\n  int nNest = 0;\n  char *z;\n  char c;\n  JsonString *pStr;\n  UNUSED_PARAM(argc);\n  UNUSED_PARAM(argv);\n  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);\n#ifdef NEVER\n  /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will\n  ** always have been called to initalize it */\n  if( NEVER(!pStr) ) return;\n#endif\n  z = pStr->zBuf;\n  for(i=1; (c = z[i])!=',' || inStr || nNest; i++){\n    if( i>=pStr->nUsed ){\n      pStr->nUsed = 1;\n      return;\n    }\n    if( c=='\"' ){\n      inStr = !inStr;\n    }else if( c=='\\\\' ){\n      i++;\n    }else if( !inStr ){\n      if( c=='{' || c=='[' ) nNest++;\n      if( c=='}' || c==']' ) nNest--;\n    }\n  }\n  pStr->nUsed -= i;      \n  memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);\n}\n#else\n# define jsonGroupInverse 0\n#endif\n\n\n/*\n** json_group_obj(NAME,VALUE)\n**\n** Return a JSON object composed of all names and values in the aggregate.\n*/\nstatic void jsonObjectStep(\n  sqlite3_context *ctx,\n  int argc,\n  sqlite3_value **argv\n){\n  JsonString *pStr;\n  const char *z;\n  u32 n;\n  UNUSED_PARAM(argc);\n  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));\n  if( pStr ){\n    if( pStr->zBuf==0 ){\n      jsonInit(pStr, ctx);\n      jsonAppendChar(pStr, '{');\n    }else if( pStr->nUsed>1 ){\n      jsonAppendChar(pStr, ',');\n      pStr->pCtx = ctx;\n    }\n    z = (const char*)sqlite3_value_text(argv[0]);\n    n = (u32)sqlite3_value_bytes(argv[0]);\n    jsonAppendString(pStr, z, n);\n    jsonAppendChar(pStr, ':');\n    jsonAppendValue(pStr, argv[1]);\n  }\n}\nstatic void jsonObjectCompute(sqlite3_context *ctx, int isFinal){\n  JsonString *pStr;\n  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);\n  if( pStr ){\n    jsonAppendChar(pStr, '}');\n    if( pStr->bErr ){\n      if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);\n      assert( pStr->bStatic );\n    }else if( isFinal ){\n      sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,\n                          pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);\n      pStr->bStatic = 1;\n    }else{\n      sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);\n      pStr->nUsed--;\n    }\n  }else{\n    sqlite3_result_text(ctx, \"{}\", 2, SQLITE_STATIC);\n  }\n  sqlite3_result_subtype(ctx, JSON_SUBTYPE);\n}\nstatic void jsonObjectValue(sqlite3_context *ctx){\n  jsonObjectCompute(ctx, 0);\n}\nstatic void jsonObjectFinal(sqlite3_context *ctx){\n  jsonObjectCompute(ctx, 1);\n}\n\n\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/****************************************************************************\n** The json_each virtual table\n****************************************************************************/\ntypedef struct JsonEachCursor JsonEachCursor;\nstruct JsonEachCursor {\n  sqlite3_vtab_cursor base;  /* Base class - must be first */\n  u32 iRowid;                /* The rowid */\n  u32 iBegin;                /* The first node of the scan */\n  u32 i;                     /* Index in sParse.aNode[] of current row */\n  u32 iEnd;                  /* EOF when i equals or exceeds this value */\n  u8 eType;                  /* Type of top-level element */\n  u8 bRecursive;             /* True for json_tree().  False for json_each() */\n  char *zJson;               /* Input JSON */\n  char *zRoot;               /* Path by which to filter zJson */\n  JsonParse sParse;          /* Parse of the input JSON */\n};\n\n/* Constructor for the json_each virtual table */\nstatic int jsonEachConnect(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  sqlite3_vtab *pNew;\n  int rc;\n\n/* Column numbers */\n#define JEACH_KEY     0\n#define JEACH_VALUE   1\n#define JEACH_TYPE    2\n#define JEACH_ATOM    3\n#define JEACH_ID      4\n#define JEACH_PARENT  5\n#define JEACH_FULLKEY 6\n#define JEACH_PATH    7\n/* The xBestIndex method assumes that the JSON and ROOT columns are\n** the last two columns in the table.  Should this ever changes, be\n** sure to update the xBestIndex method. */\n#define JEACH_JSON    8\n#define JEACH_ROOT    9\n\n  UNUSED_PARAM(pzErr);\n  UNUSED_PARAM(argv);\n  UNUSED_PARAM(argc);\n  UNUSED_PARAM(pAux);\n  rc = sqlite3_declare_vtab(db, \n     \"CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,\"\n                    \"json HIDDEN,root HIDDEN)\");\n  if( rc==SQLITE_OK ){\n    pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );\n    if( pNew==0 ) return SQLITE_NOMEM;\n    memset(pNew, 0, sizeof(*pNew));\n    sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);\n  }\n  return rc;\n}\n\n/* destructor for json_each virtual table */\nstatic int jsonEachDisconnect(sqlite3_vtab *pVtab){\n  sqlite3_free(pVtab);\n  return SQLITE_OK;\n}\n\n/* constructor for a JsonEachCursor object for json_each(). */\nstatic int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){\n  JsonEachCursor *pCur;\n\n  UNUSED_PARAM(p);\n  pCur = sqlite3_malloc( sizeof(*pCur) );\n  if( pCur==0 ) return SQLITE_NOMEM;\n  memset(pCur, 0, sizeof(*pCur));\n  *ppCursor = &pCur->base;\n  return SQLITE_OK;\n}\n\n/* constructor for a JsonEachCursor object for json_tree(). */\nstatic int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){\n  int rc = jsonEachOpenEach(p, ppCursor);\n  if( rc==SQLITE_OK ){\n    JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;\n    pCur->bRecursive = 1;\n  }\n  return rc;\n}\n\n/* Reset a JsonEachCursor back to its original state.  Free any memory\n** held. */\nstatic void jsonEachCursorReset(JsonEachCursor *p){\n  sqlite3_free(p->zJson);\n  sqlite3_free(p->zRoot);\n  jsonParseReset(&p->sParse);\n  p->iRowid = 0;\n  p->i = 0;\n  p->iEnd = 0;\n  p->eType = 0;\n  p->zJson = 0;\n  p->zRoot = 0;\n}\n\n/* Destructor for a jsonEachCursor object */\nstatic int jsonEachClose(sqlite3_vtab_cursor *cur){\n  JsonEachCursor *p = (JsonEachCursor*)cur;\n  jsonEachCursorReset(p);\n  sqlite3_free(cur);\n  return SQLITE_OK;\n}\n\n/* Return TRUE if the jsonEachCursor object has been advanced off the end\n** of the JSON object */\nstatic int jsonEachEof(sqlite3_vtab_cursor *cur){\n  JsonEachCursor *p = (JsonEachCursor*)cur;\n  return p->i >= p->iEnd;\n}\n\n/* Advance the cursor to the next element for json_tree() */\nstatic int jsonEachNext(sqlite3_vtab_cursor *cur){\n  JsonEachCursor *p = (JsonEachCursor*)cur;\n  if( p->bRecursive ){\n    if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;\n    p->i++;\n    p->iRowid++;\n    if( p->i<p->iEnd ){\n      u32 iUp = p->sParse.aUp[p->i];\n      JsonNode *pUp = &p->sParse.aNode[iUp];\n      p->eType = pUp->eType;\n      if( pUp->eType==JSON_ARRAY ){\n        if( iUp==p->i-1 ){\n          pUp->u.iKey = 0;\n        }else{\n          pUp->u.iKey++;\n        }\n      }\n    }\n  }else{\n    switch( p->eType ){\n      case JSON_ARRAY: {\n        p->i += jsonNodeSize(&p->sParse.aNode[p->i]);\n        p->iRowid++;\n        break;\n      }\n      case JSON_OBJECT: {\n        p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);\n        p->iRowid++;\n        break;\n      }\n      default: {\n        p->i = p->iEnd;\n        break;\n      }\n    }\n  }\n  return SQLITE_OK;\n}\n\n/* Append the name of the path for element i to pStr\n*/\nstatic void jsonEachComputePath(\n  JsonEachCursor *p,       /* The cursor */\n  JsonString *pStr,        /* Write the path here */\n  u32 i                    /* Path to this element */\n){\n  JsonNode *pNode, *pUp;\n  u32 iUp;\n  if( i==0 ){\n    jsonAppendChar(pStr, '$');\n    return;\n  }\n  iUp = p->sParse.aUp[i];\n  jsonEachComputePath(p, pStr, iUp);\n  pNode = &p->sParse.aNode[i];\n  pUp = &p->sParse.aNode[iUp];\n  if( pUp->eType==JSON_ARRAY ){\n    jsonPrintf(30, pStr, \"[%d]\", pUp->u.iKey);\n  }else{\n    assert( pUp->eType==JSON_OBJECT );\n    if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;\n    assert( pNode->eType==JSON_STRING );\n    assert( pNode->jnFlags & JNODE_LABEL );\n    jsonPrintf(pNode->n+1, pStr, \".%.*s\", pNode->n-2, pNode->u.zJContent+1);\n  }\n}\n\n/* Return the value of a column */\nstatic int jsonEachColumn(\n  sqlite3_vtab_cursor *cur,   /* The cursor */\n  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */\n  int i                       /* Which column to return */\n){\n  JsonEachCursor *p = (JsonEachCursor*)cur;\n  JsonNode *pThis = &p->sParse.aNode[p->i];\n  switch( i ){\n    case JEACH_KEY: {\n      if( p->i==0 ) break;\n      if( p->eType==JSON_OBJECT ){\n        jsonReturn(pThis, ctx, 0);\n      }else if( p->eType==JSON_ARRAY ){\n        u32 iKey;\n        if( p->bRecursive ){\n          if( p->iRowid==0 ) break;\n          iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;\n        }else{\n          iKey = p->iRowid;\n        }\n        sqlite3_result_int64(ctx, (sqlite3_int64)iKey);\n      }\n      break;\n    }\n    case JEACH_VALUE: {\n      if( pThis->jnFlags & JNODE_LABEL ) pThis++;\n      jsonReturn(pThis, ctx, 0);\n      break;\n    }\n    case JEACH_TYPE: {\n      if( pThis->jnFlags & JNODE_LABEL ) pThis++;\n      sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);\n      break;\n    }\n    case JEACH_ATOM: {\n      if( pThis->jnFlags & JNODE_LABEL ) pThis++;\n      if( pThis->eType>=JSON_ARRAY ) break;\n      jsonReturn(pThis, ctx, 0);\n      break;\n    }\n    case JEACH_ID: {\n      sqlite3_result_int64(ctx, \n         (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));\n      break;\n    }\n    case JEACH_PARENT: {\n      if( p->i>p->iBegin && p->bRecursive ){\n        sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);\n      }\n      break;\n    }\n    case JEACH_FULLKEY: {\n      JsonString x;\n      jsonInit(&x, ctx);\n      if( p->bRecursive ){\n        jsonEachComputePath(p, &x, p->i);\n      }else{\n        if( p->zRoot ){\n          jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));\n        }else{\n          jsonAppendChar(&x, '$');\n        }\n        if( p->eType==JSON_ARRAY ){\n          jsonPrintf(30, &x, \"[%d]\", p->iRowid);\n        }else if( p->eType==JSON_OBJECT ){\n          jsonPrintf(pThis->n, &x, \".%.*s\", pThis->n-2, pThis->u.zJContent+1);\n        }\n      }\n      jsonResult(&x);\n      break;\n    }\n    case JEACH_PATH: {\n      if( p->bRecursive ){\n        JsonString x;\n        jsonInit(&x, ctx);\n        jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);\n        jsonResult(&x);\n        break;\n      }\n      /* For json_each() path and root are the same so fall through\n      ** into the root case */\n    }\n    default: {\n      const char *zRoot = p->zRoot;\n      if( zRoot==0 ) zRoot = \"$\";\n      sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);\n      break;\n    }\n    case JEACH_JSON: {\n      assert( i==JEACH_JSON );\n      sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);\n      break;\n    }\n  }\n  return SQLITE_OK;\n}\n\n/* Return the current rowid value */\nstatic int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){\n  JsonEachCursor *p = (JsonEachCursor*)cur;\n  *pRowid = p->iRowid;\n  return SQLITE_OK;\n}\n\n/* The query strategy is to look for an equality constraint on the json\n** column.  Without such a constraint, the table cannot operate.  idxNum is\n** 1 if the constraint is found, 3 if the constraint and zRoot are found,\n** and 0 otherwise.\n*/\nstatic int jsonEachBestIndex(\n  sqlite3_vtab *tab,\n  sqlite3_index_info *pIdxInfo\n){\n  int i;                     /* Loop counter or computed array index */\n  int aIdx[2];               /* Index of constraints for JSON and ROOT */\n  int unusableMask = 0;      /* Mask of unusable JSON and ROOT constraints */\n  int idxMask = 0;           /* Mask of usable == constraints JSON and ROOT */\n  const struct sqlite3_index_constraint *pConstraint;\n\n  /* This implementation assumes that JSON and ROOT are the last two\n  ** columns in the table */\n  assert( JEACH_ROOT == JEACH_JSON+1 );\n  UNUSED_PARAM(tab);\n  aIdx[0] = aIdx[1] = -1;\n  pConstraint = pIdxInfo->aConstraint;\n  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){\n    int iCol;\n    int iMask;\n    if( pConstraint->iColumn < JEACH_JSON ) continue;\n    iCol = pConstraint->iColumn - JEACH_JSON;\n    assert( iCol==0 || iCol==1 );\n    iMask = 1 << iCol;\n    if( pConstraint->usable==0 ){\n      unusableMask |= iMask;\n    }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){\n      aIdx[iCol] = i;\n      idxMask |= iMask;\n    }\n  }\n  if( (unusableMask & ~idxMask)!=0 ){\n    /* If there are any unusable constraints on JSON or ROOT, then reject\n    ** this entire plan */\n    return SQLITE_CONSTRAINT;\n  }\n  if( aIdx[0]<0 ){\n    /* No JSON input.  Leave estimatedCost at the huge value that it was\n    ** initialized to to discourage the query planner from selecting this\n    ** plan. */\n    pIdxInfo->idxNum = 0;\n  }else{\n    pIdxInfo->estimatedCost = 1.0;\n    i = aIdx[0];\n    pIdxInfo->aConstraintUsage[i].argvIndex = 1;\n    pIdxInfo->aConstraintUsage[i].omit = 1;\n    if( aIdx[1]<0 ){\n      pIdxInfo->idxNum = 1;  /* Only JSON supplied.  Plan 1 */\n    }else{\n      i = aIdx[1];\n      pIdxInfo->aConstraintUsage[i].argvIndex = 2;\n      pIdxInfo->aConstraintUsage[i].omit = 1;\n      pIdxInfo->idxNum = 3;  /* Both JSON and ROOT are supplied.  Plan 3 */\n    }\n  }\n  return SQLITE_OK;\n}\n\n/* Start a search on a new JSON string */\nstatic int jsonEachFilter(\n  sqlite3_vtab_cursor *cur,\n  int idxNum, const char *idxStr,\n  int argc, sqlite3_value **argv\n){\n  JsonEachCursor *p = (JsonEachCursor*)cur;\n  const char *z;\n  const char *zRoot = 0;\n  sqlite3_int64 n;\n\n  UNUSED_PARAM(idxStr);\n  UNUSED_PARAM(argc);\n  jsonEachCursorReset(p);\n  if( idxNum==0 ) return SQLITE_OK;\n  z = (const char*)sqlite3_value_text(argv[0]);\n  if( z==0 ) return SQLITE_OK;\n  n = sqlite3_value_bytes(argv[0]);\n  p->zJson = sqlite3_malloc64( n+1 );\n  if( p->zJson==0 ) return SQLITE_NOMEM;\n  memcpy(p->zJson, z, (size_t)n+1);\n  if( jsonParse(&p->sParse, 0, p->zJson) ){\n    int rc = SQLITE_NOMEM;\n    if( p->sParse.oom==0 ){\n      sqlite3_free(cur->pVtab->zErrMsg);\n      cur->pVtab->zErrMsg = sqlite3_mprintf(\"malformed JSON\");\n      if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;\n    }\n    jsonEachCursorReset(p);\n    return rc;\n  }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){\n    jsonEachCursorReset(p);\n    return SQLITE_NOMEM;\n  }else{\n    JsonNode *pNode = 0;\n    if( idxNum==3 ){\n      const char *zErr = 0;\n      zRoot = (const char*)sqlite3_value_text(argv[1]);\n      if( zRoot==0 ) return SQLITE_OK;\n      n = sqlite3_value_bytes(argv[1]);\n      p->zRoot = sqlite3_malloc64( n+1 );\n      if( p->zRoot==0 ) return SQLITE_NOMEM;\n      memcpy(p->zRoot, zRoot, (size_t)n+1);\n      if( zRoot[0]!='$' ){\n        zErr = zRoot;\n      }else{\n        pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);\n      }\n      if( zErr ){\n        sqlite3_free(cur->pVtab->zErrMsg);\n        cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);\n        jsonEachCursorReset(p);\n        return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;\n      }else if( pNode==0 ){\n        return SQLITE_OK;\n      }\n    }else{\n      pNode = p->sParse.aNode;\n    }\n    p->iBegin = p->i = (int)(pNode - p->sParse.aNode);\n    p->eType = pNode->eType;\n    if( p->eType>=JSON_ARRAY ){\n      pNode->u.iKey = 0;\n      p->iEnd = p->i + pNode->n + 1;\n      if( p->bRecursive ){\n        p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;\n        if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){\n          p->i--;\n        }\n      }else{\n        p->i++;\n      }\n    }else{\n      p->iEnd = p->i+1;\n    }\n  }\n  return SQLITE_OK;\n}\n\n/* The methods of the json_each virtual table */\nstatic sqlite3_module jsonEachModule = {\n  0,                         /* iVersion */\n  0,                         /* xCreate */\n  jsonEachConnect,           /* xConnect */\n  jsonEachBestIndex,         /* xBestIndex */\n  jsonEachDisconnect,        /* xDisconnect */\n  0,                         /* xDestroy */\n  jsonEachOpenEach,          /* xOpen - open a cursor */\n  jsonEachClose,             /* xClose - close a cursor */\n  jsonEachFilter,            /* xFilter - configure scan constraints */\n  jsonEachNext,              /* xNext - advance a cursor */\n  jsonEachEof,               /* xEof - check for end of scan */\n  jsonEachColumn,            /* xColumn - read data */\n  jsonEachRowid,             /* xRowid - read data */\n  0,                         /* xUpdate */\n  0,                         /* xBegin */\n  0,                         /* xSync */\n  0,                         /* xCommit */\n  0,                         /* xRollback */\n  0,                         /* xFindMethod */\n  0,                         /* xRename */\n  0,                         /* xSavepoint */\n  0,                         /* xRelease */\n  0,                         /* xRollbackTo */\n  0                          /* xShadowName */\n};\n\n/* The methods of the json_tree virtual table. */\nstatic sqlite3_module jsonTreeModule = {\n  0,                         /* iVersion */\n  0,                         /* xCreate */\n  jsonEachConnect,           /* xConnect */\n  jsonEachBestIndex,         /* xBestIndex */\n  jsonEachDisconnect,        /* xDisconnect */\n  0,                         /* xDestroy */\n  jsonEachOpenTree,          /* xOpen - open a cursor */\n  jsonEachClose,             /* xClose - close a cursor */\n  jsonEachFilter,            /* xFilter - configure scan constraints */\n  jsonEachNext,              /* xNext - advance a cursor */\n  jsonEachEof,               /* xEof - check for end of scan */\n  jsonEachColumn,            /* xColumn - read data */\n  jsonEachRowid,             /* xRowid - read data */\n  0,                         /* xUpdate */\n  0,                         /* xBegin */\n  0,                         /* xSync */\n  0,                         /* xCommit */\n  0,                         /* xRollback */\n  0,                         /* xFindMethod */\n  0,                         /* xRename */\n  0,                         /* xSavepoint */\n  0,                         /* xRelease */\n  0,                         /* xRollbackTo */\n  0                          /* xShadowName */\n};\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n/****************************************************************************\n** The following routines are the only publically visible identifiers in this\n** file.  Call the following routines in order to register the various SQL\n** functions and the virtual table implemented by this file.\n****************************************************************************/\n\nSQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){\n  int rc = SQLITE_OK;\n  unsigned int i;\n  static const struct {\n     const char *zName;\n     int nArg;\n     int flag;\n     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);\n  } aFunc[] = {\n    { \"json\",                 1, 0,   jsonRemoveFunc        },\n    { \"json_array\",          -1, 0,   jsonArrayFunc         },\n    { \"json_array_length\",    1, 0,   jsonArrayLengthFunc   },\n    { \"json_array_length\",    2, 0,   jsonArrayLengthFunc   },\n    { \"json_extract\",        -1, 0,   jsonExtractFunc       },\n    { \"json_insert\",         -1, 0,   jsonSetFunc           },\n    { \"json_object\",         -1, 0,   jsonObjectFunc        },\n    { \"json_patch\",           2, 0,   jsonPatchFunc         },\n    { \"json_quote\",           1, 0,   jsonQuoteFunc         },\n    { \"json_remove\",         -1, 0,   jsonRemoveFunc        },\n    { \"json_replace\",        -1, 0,   jsonReplaceFunc       },\n    { \"json_set\",            -1, 1,   jsonSetFunc           },\n    { \"json_type\",            1, 0,   jsonTypeFunc          },\n    { \"json_type\",            2, 0,   jsonTypeFunc          },\n    { \"json_valid\",           1, 0,   jsonValidFunc         },\n\n#if SQLITE_DEBUG\n    /* DEBUG and TESTING functions */\n    { \"json_parse\",           1, 0,   jsonParseFunc         },\n    { \"json_test1\",           1, 0,   jsonTest1Func         },\n#endif\n  };\n  static const struct {\n     const char *zName;\n     int nArg;\n     void (*xStep)(sqlite3_context*,int,sqlite3_value**);\n     void (*xFinal)(sqlite3_context*);\n     void (*xValue)(sqlite3_context*);\n  } aAgg[] = {\n    { \"json_group_array\",     1,\n      jsonArrayStep,   jsonArrayFinal,  jsonArrayValue  },\n    { \"json_group_object\",    2,\n      jsonObjectStep,  jsonObjectFinal, jsonObjectValue },\n  };\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  static const struct {\n     const char *zName;\n     sqlite3_module *pModule;\n  } aMod[] = {\n    { \"json_each\",            &jsonEachModule               },\n    { \"json_tree\",            &jsonTreeModule               },\n  };\n#endif\n  static const int enc = \n       SQLITE_UTF8 |\n       SQLITE_DETERMINISTIC |\n       SQLITE_INNOCUOUS;\n  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){\n    rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg, enc,\n                                 (void*)&aFunc[i].flag,\n                                 aFunc[i].xFunc, 0, 0);\n  }\n#ifndef SQLITE_OMIT_WINDOWFUNC\n  for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){\n    rc = sqlite3_create_window_function(db, aAgg[i].zName, aAgg[i].nArg,\n                                 SQLITE_SUBTYPE | enc, 0,\n                                 aAgg[i].xStep, aAgg[i].xFinal,\n                                 aAgg[i].xValue, jsonGroupInverse, 0);\n  }\n#endif\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){\n    rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);\n  }\n#endif\n  return rc;\n}\n\n\n#ifndef SQLITE_CORE\n#ifdef _WIN32\n__declspec(dllexport)\n#endif\nSQLITE_API int sqlite3_json_init(\n  sqlite3 *db, \n  char **pzErrMsg, \n  const sqlite3_api_routines *pApi\n){\n  SQLITE_EXTENSION_INIT2(pApi);\n  (void)pzErrMsg;  /* Unused parameter */\n  return sqlite3Json1Init(db);\n}\n#endif\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */\n\n/************** End of json1.c ***********************************************/\n/************** Begin file rtree.c *******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code for implementations of the r-tree and r*-tree\n** algorithms packaged as an SQLite virtual table module.\n*/\n\n/*\n** Database Format of R-Tree Tables\n** --------------------------------\n**\n** The data structure for a single virtual r-tree table is stored in three \n** native SQLite tables declared as follows. In each case, the '%' character\n** in the table name is replaced with the user-supplied name of the r-tree\n** table.\n**\n**   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)\n**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)\n**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)\n**\n** The data for each node of the r-tree structure is stored in the %_node\n** table. For each node that is not the root node of the r-tree, there is\n** an entry in the %_parent table associating the node with its parent.\n** And for each row of data in the table, there is an entry in the %_rowid\n** table that maps from the entries rowid to the id of the node that it\n** is stored on.  If the r-tree contains auxiliary columns, those are stored\n** on the end of the %_rowid table.\n**\n** The root node of an r-tree always exists, even if the r-tree table is\n** empty. The nodeno of the root node is always 1. All other nodes in the\n** table must be the same size as the root node. The content of each node\n** is formatted as follows:\n**\n**   1. If the node is the root node (node 1), then the first 2 bytes\n**      of the node contain the tree depth as a big-endian integer.\n**      For non-root nodes, the first 2 bytes are left unused.\n**\n**   2. The next 2 bytes contain the number of entries currently \n**      stored in the node.\n**\n**   3. The remainder of the node contains the node entries. Each entry\n**      consists of a single 8-byte integer followed by an even number\n**      of 4-byte coordinates. For leaf nodes the integer is the rowid\n**      of a record. For internal nodes it is the node number of a\n**      child page.\n*/\n\n#if !defined(SQLITE_CORE) \\\n  || (defined(SQLITE_ENABLE_RTREE) && !defined(SQLITE_OMIT_VIRTUALTABLE))\n\n#ifndef SQLITE_CORE\n/*   #include \"sqlite3ext.h\" */\n  SQLITE_EXTENSION_INIT1\n#else\n/*   #include \"sqlite3.h\" */\n#endif\nSQLITE_PRIVATE int sqlite3GetToken(const unsigned char*,int*); /* In the SQLite core */\n\n#ifndef SQLITE_AMALGAMATION\n#include \"sqlite3rtree.h\"\ntypedef sqlite3_int64 i64;\ntypedef sqlite3_uint64 u64;\ntypedef unsigned char u8;\ntypedef unsigned short u16;\ntypedef unsigned int u32;\n#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)\n# define NDEBUG 1\n#endif\n#if defined(NDEBUG) && defined(SQLITE_DEBUG)\n# undef NDEBUG\n#endif\n#endif\n\n/* #include <string.h> */\n/* #include <stdio.h> */\n/* #include <assert.h> */\n\n/*  The following macro is used to suppress compiler warnings.\n*/\n#ifndef UNUSED_PARAMETER\n# define UNUSED_PARAMETER(x) (void)(x)\n#endif\n\ntypedef struct Rtree Rtree;\ntypedef struct RtreeCursor RtreeCursor;\ntypedef struct RtreeNode RtreeNode;\ntypedef struct RtreeCell RtreeCell;\ntypedef struct RtreeConstraint RtreeConstraint;\ntypedef struct RtreeMatchArg RtreeMatchArg;\ntypedef struct RtreeGeomCallback RtreeGeomCallback;\ntypedef union RtreeCoord RtreeCoord;\ntypedef struct RtreeSearchPoint RtreeSearchPoint;\n\n/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */\n#define RTREE_MAX_DIMENSIONS 5\n\n/* Maximum number of auxiliary columns */\n#define RTREE_MAX_AUX_COLUMN 100\n\n/* Size of hash table Rtree.aHash. This hash table is not expected to\n** ever contain very many entries, so a fixed number of buckets is \n** used.\n*/\n#define HASHSIZE 97\n\n/* The xBestIndex method of this virtual table requires an estimate of\n** the number of rows in the virtual table to calculate the costs of\n** various strategies. If possible, this estimate is loaded from the\n** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).\n** Otherwise, if no sqlite_stat1 entry is available, use \n** RTREE_DEFAULT_ROWEST.\n*/\n#define RTREE_DEFAULT_ROWEST 1048576\n#define RTREE_MIN_ROWEST         100\n\n/* \n** An rtree virtual-table object.\n*/\nstruct Rtree {\n  sqlite3_vtab base;          /* Base class.  Must be first */\n  sqlite3 *db;                /* Host database connection */\n  int iNodeSize;              /* Size in bytes of each node in the node table */\n  u8 nDim;                    /* Number of dimensions */\n  u8 nDim2;                   /* Twice the number of dimensions */\n  u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */\n  u8 nBytesPerCell;           /* Bytes consumed per cell */\n  u8 inWrTrans;               /* True if inside write transaction */\n  u8 nAux;                    /* # of auxiliary columns in %_rowid */\n  u8 nAuxNotNull;             /* Number of initial not-null aux columns */\n#ifdef SQLITE_DEBUG\n  u8 bCorrupt;                /* Shadow table corruption detected */\n#endif\n  int iDepth;                 /* Current depth of the r-tree structure */\n  char *zDb;                  /* Name of database containing r-tree table */\n  char *zName;                /* Name of r-tree table */ \n  u32 nBusy;                  /* Current number of users of this structure */\n  i64 nRowEst;                /* Estimated number of rows in this table */\n  u32 nCursor;                /* Number of open cursors */\n  u32 nNodeRef;               /* Number RtreeNodes with positive nRef */\n  char *zReadAuxSql;          /* SQL for statement to read aux data */\n\n  /* List of nodes removed during a CondenseTree operation. List is\n  ** linked together via the pointer normally used for hash chains -\n  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree \n  ** headed by the node (leaf nodes have RtreeNode.iNode==0).\n  */\n  RtreeNode *pDeleted;\n  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */\n\n  /* Blob I/O on xxx_node */\n  sqlite3_blob *pNodeBlob;\n\n  /* Statements to read/write/delete a record from xxx_node */\n  sqlite3_stmt *pWriteNode;\n  sqlite3_stmt *pDeleteNode;\n\n  /* Statements to read/write/delete a record from xxx_rowid */\n  sqlite3_stmt *pReadRowid;\n  sqlite3_stmt *pWriteRowid;\n  sqlite3_stmt *pDeleteRowid;\n\n  /* Statements to read/write/delete a record from xxx_parent */\n  sqlite3_stmt *pReadParent;\n  sqlite3_stmt *pWriteParent;\n  sqlite3_stmt *pDeleteParent;\n\n  /* Statement for writing to the \"aux:\" fields, if there are any */\n  sqlite3_stmt *pWriteAux;\n\n  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ \n};\n\n/* Possible values for Rtree.eCoordType: */\n#define RTREE_COORD_REAL32 0\n#define RTREE_COORD_INT32  1\n\n/*\n** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will\n** only deal with integer coordinates.  No floating point operations\n** will be done.\n*/\n#ifdef SQLITE_RTREE_INT_ONLY\n  typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */\n  typedef int RtreeValue;                  /* Low accuracy coordinate */\n# define RTREE_ZERO 0\n#else\n  typedef double RtreeDValue;              /* High accuracy coordinate */\n  typedef float RtreeValue;                /* Low accuracy coordinate */\n# define RTREE_ZERO 0.0\n#endif\n\n/*\n** Set the Rtree.bCorrupt flag\n*/\n#ifdef SQLITE_DEBUG\n# define RTREE_IS_CORRUPT(X) ((X)->bCorrupt = 1)\n#else\n# define RTREE_IS_CORRUPT(X)\n#endif\n\n/*\n** When doing a search of an r-tree, instances of the following structure\n** record intermediate results from the tree walk.\n**\n** The id is always a node-id.  For iLevel>=1 the id is the node-id of\n** the node that the RtreeSearchPoint represents.  When iLevel==0, however,\n** the id is of the parent node and the cell that RtreeSearchPoint\n** represents is the iCell-th entry in the parent node.\n*/\nstruct RtreeSearchPoint {\n  RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */\n  sqlite3_int64 id;      /* Node ID */\n  u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */\n  u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */\n  u8 iCell;              /* Cell index within the node */\n};\n\n/*\n** The minimum number of cells allowed for a node is a third of the \n** maximum. In Gutman's notation:\n**\n**     m = M/3\n**\n** If an R*-tree \"Reinsert\" operation is required, the same number of\n** cells are removed from the overfull node and reinserted into the tree.\n*/\n#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)\n#define RTREE_REINSERT(p) RTREE_MINCELLS(p)\n#define RTREE_MAXCELLS 51\n\n/*\n** The smallest possible node-size is (512-64)==448 bytes. And the largest\n** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).\n** Therefore all non-root nodes must contain at least 3 entries. Since \n** 3^40 is greater than 2^64, an r-tree structure always has a depth of\n** 40 or less.\n*/\n#define RTREE_MAX_DEPTH 40\n\n\n/*\n** Number of entries in the cursor RtreeNode cache.  The first entry is\n** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining\n** entries cache the RtreeNode for the first elements of the priority queue.\n*/\n#define RTREE_CACHE_SZ  5\n\n/* \n** An rtree cursor object.\n*/\nstruct RtreeCursor {\n  sqlite3_vtab_cursor base;         /* Base class.  Must be first */\n  u8 atEOF;                         /* True if at end of search */\n  u8 bPoint;                        /* True if sPoint is valid */\n  u8 bAuxValid;                     /* True if pReadAux is valid */\n  int iStrategy;                    /* Copy of idxNum search parameter */\n  int nConstraint;                  /* Number of entries in aConstraint */\n  RtreeConstraint *aConstraint;     /* Search constraints. */\n  int nPointAlloc;                  /* Number of slots allocated for aPoint[] */\n  int nPoint;                       /* Number of slots used in aPoint[] */\n  int mxLevel;                      /* iLevel value for root of the tree */\n  RtreeSearchPoint *aPoint;         /* Priority queue for search points */\n  sqlite3_stmt *pReadAux;           /* Statement to read aux-data */\n  RtreeSearchPoint sPoint;          /* Cached next search point */\n  RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */\n  u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */\n};\n\n/* Return the Rtree of a RtreeCursor */\n#define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))\n\n/*\n** A coordinate can be either a floating point number or a integer.  All\n** coordinates within a single R-Tree are always of the same time.\n*/\nunion RtreeCoord {\n  RtreeValue f;      /* Floating point value */\n  int i;             /* Integer value */\n  u32 u;             /* Unsigned for byte-order conversions */\n};\n\n/*\n** The argument is an RtreeCoord. Return the value stored within the RtreeCoord\n** formatted as a RtreeDValue (double or int64). This macro assumes that local\n** variable pRtree points to the Rtree structure associated with the\n** RtreeCoord.\n*/\n#ifdef SQLITE_RTREE_INT_ONLY\n# define DCOORD(coord) ((RtreeDValue)coord.i)\n#else\n# define DCOORD(coord) (                           \\\n    (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \\\n      ((double)coord.f) :                           \\\n      ((double)coord.i)                             \\\n  )\n#endif\n\n/*\n** A search constraint.\n*/\nstruct RtreeConstraint {\n  int iCoord;                     /* Index of constrained coordinate */\n  int op;                         /* Constraining operation */\n  union {\n    RtreeDValue rValue;             /* Constraint value. */\n    int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);\n    int (*xQueryFunc)(sqlite3_rtree_query_info*);\n  } u;\n  sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */\n};\n\n/* Possible values for RtreeConstraint.op */\n#define RTREE_EQ    0x41  /* A */\n#define RTREE_LE    0x42  /* B */\n#define RTREE_LT    0x43  /* C */\n#define RTREE_GE    0x44  /* D */\n#define RTREE_GT    0x45  /* E */\n#define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */\n#define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */\n\n/* Special operators available only on cursors.  Needs to be consecutive\n** with the normal values above, but must be less than RTREE_MATCH.  These\n** are used in the cursor for contraints such as x=NULL (RTREE_FALSE) or\n** x<'xyz' (RTREE_TRUE) */\n#define RTREE_TRUE  0x3f  /* ? */\n#define RTREE_FALSE 0x40  /* @ */\n\n/* \n** An rtree structure node.\n*/\nstruct RtreeNode {\n  RtreeNode *pParent;         /* Parent node */\n  i64 iNode;                  /* The node number */\n  int nRef;                   /* Number of references to this node */\n  int isDirty;                /* True if the node needs to be written to disk */\n  u8 *zData;                  /* Content of the node, as should be on disk */\n  RtreeNode *pNext;           /* Next node in this hash collision chain */\n};\n\n/* Return the number of cells in a node  */\n#define NCELL(pNode) readInt16(&(pNode)->zData[2])\n\n/* \n** A single cell from a node, deserialized\n*/\nstruct RtreeCell {\n  i64 iRowid;                                 /* Node or entry ID */\n  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */\n};\n\n\n/*\n** This object becomes the sqlite3_user_data() for the SQL functions\n** that are created by sqlite3_rtree_geometry_callback() and\n** sqlite3_rtree_query_callback() and which appear on the right of MATCH\n** operators in order to constrain a search.\n**\n** xGeom and xQueryFunc are the callback functions.  Exactly one of \n** xGeom and xQueryFunc fields is non-NULL, depending on whether the\n** SQL function was created using sqlite3_rtree_geometry_callback() or\n** sqlite3_rtree_query_callback().\n** \n** This object is deleted automatically by the destructor mechanism in\n** sqlite3_create_function_v2().\n*/\nstruct RtreeGeomCallback {\n  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);\n  int (*xQueryFunc)(sqlite3_rtree_query_info*);\n  void (*xDestructor)(void*);\n  void *pContext;\n};\n\n/*\n** An instance of this structure (in the form of a BLOB) is returned by\n** the SQL functions that sqlite3_rtree_geometry_callback() and\n** sqlite3_rtree_query_callback() create, and is read as the right-hand\n** operand to the MATCH operator of an R-Tree.\n*/\nstruct RtreeMatchArg {\n  u32 iSize;                  /* Size of this object */\n  RtreeGeomCallback cb;       /* Info about the callback functions */\n  int nParam;                 /* Number of parameters to the SQL function */\n  sqlite3_value **apSqlParam; /* Original SQL parameter values */\n  RtreeDValue aParam[1];      /* Values for parameters to the SQL function */\n};\n\n#ifndef MAX\n# define MAX(x,y) ((x) < (y) ? (y) : (x))\n#endif\n#ifndef MIN\n# define MIN(x,y) ((x) > (y) ? (y) : (x))\n#endif\n\n/* What version of GCC is being used.  0 means GCC is not being used .\n** Note that the GCC_VERSION macro will also be set correctly when using\n** clang, since clang works hard to be gcc compatible.  So the gcc\n** optimizations will also work when compiling with clang.\n*/\n#ifndef GCC_VERSION\n#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)\n# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)\n#else\n# define GCC_VERSION 0\n#endif\n#endif\n\n/* The testcase() macro should already be defined in the amalgamation.  If\n** it is not, make it a no-op.\n*/\n#ifndef SQLITE_AMALGAMATION\n# define testcase(X)\n#endif\n\n/*\n** Macros to determine whether the machine is big or little endian,\n** and whether or not that determination is run-time or compile-time.\n**\n** For best performance, an attempt is made to guess at the byte-order\n** using C-preprocessor macros.  If that is unsuccessful, or if\n** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined\n** at run-time.\n*/\n#ifndef SQLITE_BYTEORDER\n#if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \\\n    defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \\\n    defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \\\n    defined(__arm__)\n# define SQLITE_BYTEORDER    1234\n#elif defined(sparc)    || defined(__ppc__)\n# define SQLITE_BYTEORDER    4321\n#else\n# define SQLITE_BYTEORDER    0     /* 0 means \"unknown at compile-time\" */\n#endif\n#endif\n\n\n/* What version of MSVC is being used.  0 means MSVC is not being used */\n#ifndef MSVC_VERSION\n#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)\n# define MSVC_VERSION _MSC_VER\n#else\n# define MSVC_VERSION 0\n#endif\n#endif\n\n/*\n** Functions to deserialize a 16 bit integer, 32 bit real number and\n** 64 bit integer. The deserialized value is returned.\n*/\nstatic int readInt16(u8 *p){\n  return (p[0]<<8) + p[1];\n}\nstatic void readCoord(u8 *p, RtreeCoord *pCoord){\n  assert( ((((char*)p) - (char*)0)&3)==0 );  /* p is always 4-byte aligned */\n#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300\n  pCoord->u = _byteswap_ulong(*(u32*)p);\n#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000\n  pCoord->u = __builtin_bswap32(*(u32*)p);\n#elif SQLITE_BYTEORDER==4321\n  pCoord->u = *(u32*)p;\n#else\n  pCoord->u = (\n    (((u32)p[0]) << 24) + \n    (((u32)p[1]) << 16) + \n    (((u32)p[2]) <<  8) + \n    (((u32)p[3]) <<  0)\n  );\n#endif\n}\nstatic i64 readInt64(u8 *p){\n#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300\n  u64 x;\n  memcpy(&x, p, 8);\n  return (i64)_byteswap_uint64(x);\n#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000\n  u64 x;\n  memcpy(&x, p, 8);\n  return (i64)__builtin_bswap64(x);\n#elif SQLITE_BYTEORDER==4321\n  i64 x;\n  memcpy(&x, p, 8);\n  return x;\n#else\n  return (i64)(\n    (((u64)p[0]) << 56) + \n    (((u64)p[1]) << 48) + \n    (((u64)p[2]) << 40) + \n    (((u64)p[3]) << 32) + \n    (((u64)p[4]) << 24) + \n    (((u64)p[5]) << 16) + \n    (((u64)p[6]) <<  8) + \n    (((u64)p[7]) <<  0)\n  );\n#endif\n}\n\n/*\n** Functions to serialize a 16 bit integer, 32 bit real number and\n** 64 bit integer. The value returned is the number of bytes written\n** to the argument buffer (always 2, 4 and 8 respectively).\n*/\nstatic void writeInt16(u8 *p, int i){\n  p[0] = (i>> 8)&0xFF;\n  p[1] = (i>> 0)&0xFF;\n}\nstatic int writeCoord(u8 *p, RtreeCoord *pCoord){\n  u32 i;\n  assert( ((((char*)p) - (char*)0)&3)==0 );  /* p is always 4-byte aligned */\n  assert( sizeof(RtreeCoord)==4 );\n  assert( sizeof(u32)==4 );\n#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000\n  i = __builtin_bswap32(pCoord->u);\n  memcpy(p, &i, 4);\n#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300\n  i = _byteswap_ulong(pCoord->u);\n  memcpy(p, &i, 4);\n#elif SQLITE_BYTEORDER==4321\n  i = pCoord->u;\n  memcpy(p, &i, 4);\n#else\n  i = pCoord->u;\n  p[0] = (i>>24)&0xFF;\n  p[1] = (i>>16)&0xFF;\n  p[2] = (i>> 8)&0xFF;\n  p[3] = (i>> 0)&0xFF;\n#endif\n  return 4;\n}\nstatic int writeInt64(u8 *p, i64 i){\n#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000\n  i = (i64)__builtin_bswap64((u64)i);\n  memcpy(p, &i, 8);\n#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300\n  i = (i64)_byteswap_uint64((u64)i);\n  memcpy(p, &i, 8);\n#elif SQLITE_BYTEORDER==4321\n  memcpy(p, &i, 8);\n#else\n  p[0] = (i>>56)&0xFF;\n  p[1] = (i>>48)&0xFF;\n  p[2] = (i>>40)&0xFF;\n  p[3] = (i>>32)&0xFF;\n  p[4] = (i>>24)&0xFF;\n  p[5] = (i>>16)&0xFF;\n  p[6] = (i>> 8)&0xFF;\n  p[7] = (i>> 0)&0xFF;\n#endif\n  return 8;\n}\n\n/*\n** Increment the reference count of node p.\n*/\nstatic void nodeReference(RtreeNode *p){\n  if( p ){\n    assert( p->nRef>0 );\n    p->nRef++;\n  }\n}\n\n/*\n** Clear the content of node p (set all bytes to 0x00).\n*/\nstatic void nodeZero(Rtree *pRtree, RtreeNode *p){\n  memset(&p->zData[2], 0, pRtree->iNodeSize-2);\n  p->isDirty = 1;\n}\n\n/*\n** Given a node number iNode, return the corresponding key to use\n** in the Rtree.aHash table.\n*/\nstatic unsigned int nodeHash(i64 iNode){\n  return ((unsigned)iNode) % HASHSIZE;\n}\n\n/*\n** Search the node hash table for node iNode. If found, return a pointer\n** to it. Otherwise, return 0.\n*/\nstatic RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){\n  RtreeNode *p;\n  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);\n  return p;\n}\n\n/*\n** Add node pNode to the node hash table.\n*/\nstatic void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){\n  int iHash;\n  assert( pNode->pNext==0 );\n  iHash = nodeHash(pNode->iNode);\n  pNode->pNext = pRtree->aHash[iHash];\n  pRtree->aHash[iHash] = pNode;\n}\n\n/*\n** Remove node pNode from the node hash table.\n*/\nstatic void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){\n  RtreeNode **pp;\n  if( pNode->iNode!=0 ){\n    pp = &pRtree->aHash[nodeHash(pNode->iNode)];\n    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }\n    *pp = pNode->pNext;\n    pNode->pNext = 0;\n  }\n}\n\n/*\n** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),\n** indicating that node has not yet been assigned a node number. It is\n** assigned a node number when nodeWrite() is called to write the\n** node contents out to the database.\n*/\nstatic RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){\n  RtreeNode *pNode;\n  pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode) + pRtree->iNodeSize);\n  if( pNode ){\n    memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);\n    pNode->zData = (u8 *)&pNode[1];\n    pNode->nRef = 1;\n    pRtree->nNodeRef++;\n    pNode->pParent = pParent;\n    pNode->isDirty = 1;\n    nodeReference(pParent);\n  }\n  return pNode;\n}\n\n/*\n** Clear the Rtree.pNodeBlob object\n*/\nstatic void nodeBlobReset(Rtree *pRtree){\n  if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){\n    sqlite3_blob *pBlob = pRtree->pNodeBlob;\n    pRtree->pNodeBlob = 0;\n    sqlite3_blob_close(pBlob);\n  }\n}\n\n/*\n** Check to see if pNode is the same as pParent or any of the parents\n** of pParent.\n*/\nstatic int nodeInParentChain(const RtreeNode *pNode, const RtreeNode *pParent){\n  do{\n    if( pNode==pParent ) return 1;\n    pParent = pParent->pParent;\n  }while( pParent );\n  return 0;\n}\n\n/*\n** Obtain a reference to an r-tree node.\n*/\nstatic int nodeAcquire(\n  Rtree *pRtree,             /* R-tree structure */\n  i64 iNode,                 /* Node number to load */\n  RtreeNode *pParent,        /* Either the parent node or NULL */\n  RtreeNode **ppNode         /* OUT: Acquired node */\n){\n  int rc = SQLITE_OK;\n  RtreeNode *pNode = 0;\n\n  /* Check if the requested node is already in the hash table. If so,\n  ** increase its reference count and return it.\n  */\n  if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){\n    if( pParent && !pNode->pParent ){\n      if( nodeInParentChain(pNode, pParent) ){\n        RTREE_IS_CORRUPT(pRtree);\n        return SQLITE_CORRUPT_VTAB;\n      }\n      pParent->nRef++;\n      pNode->pParent = pParent;\n    }else if( pParent && pNode->pParent && pParent!=pNode->pParent ){\n      RTREE_IS_CORRUPT(pRtree);\n      return SQLITE_CORRUPT_VTAB;\n    }\n    pNode->nRef++;\n    *ppNode = pNode;\n    return SQLITE_OK;\n  }\n\n  if( pRtree->pNodeBlob ){\n    sqlite3_blob *pBlob = pRtree->pNodeBlob;\n    pRtree->pNodeBlob = 0;\n    rc = sqlite3_blob_reopen(pBlob, iNode);\n    pRtree->pNodeBlob = pBlob;\n    if( rc ){\n      nodeBlobReset(pRtree);\n      if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;\n    }\n  }\n  if( pRtree->pNodeBlob==0 ){\n    char *zTab = sqlite3_mprintf(\"%s_node\", pRtree->zName);\n    if( zTab==0 ) return SQLITE_NOMEM;\n    rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, \"data\", iNode, 0,\n                           &pRtree->pNodeBlob);\n    sqlite3_free(zTab);\n  }\n  if( rc ){\n    nodeBlobReset(pRtree);\n    *ppNode = 0;\n    /* If unable to open an sqlite3_blob on the desired row, that can only\n    ** be because the shadow tables hold erroneous data. */\n    if( rc==SQLITE_ERROR ){\n      rc = SQLITE_CORRUPT_VTAB;\n      RTREE_IS_CORRUPT(pRtree);\n    }\n  }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){\n    pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize);\n    if( !pNode ){\n      rc = SQLITE_NOMEM;\n    }else{\n      pNode->pParent = pParent;\n      pNode->zData = (u8 *)&pNode[1];\n      pNode->nRef = 1;\n      pRtree->nNodeRef++;\n      pNode->iNode = iNode;\n      pNode->isDirty = 0;\n      pNode->pNext = 0;\n      rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,\n                             pRtree->iNodeSize, 0);\n    }\n  }\n\n  /* If the root node was just loaded, set pRtree->iDepth to the height\n  ** of the r-tree structure. A height of zero means all data is stored on\n  ** the root node. A height of one means the children of the root node\n  ** are the leaves, and so on. If the depth as specified on the root node\n  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.\n  */\n  if( pNode && iNode==1 ){\n    pRtree->iDepth = readInt16(pNode->zData);\n    if( pRtree->iDepth>RTREE_MAX_DEPTH ){\n      rc = SQLITE_CORRUPT_VTAB;\n      RTREE_IS_CORRUPT(pRtree);\n    }\n  }\n\n  /* If no error has occurred so far, check if the \"number of entries\"\n  ** field on the node is too large. If so, set the return code to \n  ** SQLITE_CORRUPT_VTAB.\n  */\n  if( pNode && rc==SQLITE_OK ){\n    if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){\n      rc = SQLITE_CORRUPT_VTAB;\n      RTREE_IS_CORRUPT(pRtree);\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    if( pNode!=0 ){\n      nodeReference(pParent);\n      nodeHashInsert(pRtree, pNode);\n    }else{\n      rc = SQLITE_CORRUPT_VTAB;\n      RTREE_IS_CORRUPT(pRtree);\n    }\n    *ppNode = pNode;\n  }else{\n    if( pNode ){\n      pRtree->nNodeRef--;\n      sqlite3_free(pNode);\n    }\n    *ppNode = 0;\n  }\n\n  return rc;\n}\n\n/*\n** Overwrite cell iCell of node pNode with the contents of pCell.\n*/\nstatic void nodeOverwriteCell(\n  Rtree *pRtree,             /* The overall R-Tree */\n  RtreeNode *pNode,          /* The node into which the cell is to be written */\n  RtreeCell *pCell,          /* The cell to write */\n  int iCell                  /* Index into pNode into which pCell is written */\n){\n  int ii;\n  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];\n  p += writeInt64(p, pCell->iRowid);\n  for(ii=0; ii<pRtree->nDim2; ii++){\n    p += writeCoord(p, &pCell->aCoord[ii]);\n  }\n  pNode->isDirty = 1;\n}\n\n/*\n** Remove the cell with index iCell from node pNode.\n*/\nstatic void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){\n  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];\n  u8 *pSrc = &pDst[pRtree->nBytesPerCell];\n  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;\n  memmove(pDst, pSrc, nByte);\n  writeInt16(&pNode->zData[2], NCELL(pNode)-1);\n  pNode->isDirty = 1;\n}\n\n/*\n** Insert the contents of cell pCell into node pNode. If the insert\n** is successful, return SQLITE_OK.\n**\n** If there is not enough free space in pNode, return SQLITE_FULL.\n*/\nstatic int nodeInsertCell(\n  Rtree *pRtree,                /* The overall R-Tree */\n  RtreeNode *pNode,             /* Write new cell into this node */\n  RtreeCell *pCell              /* The cell to be inserted */\n){\n  int nCell;                    /* Current number of cells in pNode */\n  int nMaxCell;                 /* Maximum number of cells for pNode */\n\n  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;\n  nCell = NCELL(pNode);\n\n  assert( nCell<=nMaxCell );\n  if( nCell<nMaxCell ){\n    nodeOverwriteCell(pRtree, pNode, pCell, nCell);\n    writeInt16(&pNode->zData[2], nCell+1);\n    pNode->isDirty = 1;\n  }\n\n  return (nCell==nMaxCell);\n}\n\n/*\n** If the node is dirty, write it out to the database.\n*/\nstatic int nodeWrite(Rtree *pRtree, RtreeNode *pNode){\n  int rc = SQLITE_OK;\n  if( pNode->isDirty ){\n    sqlite3_stmt *p = pRtree->pWriteNode;\n    if( pNode->iNode ){\n      sqlite3_bind_int64(p, 1, pNode->iNode);\n    }else{\n      sqlite3_bind_null(p, 1);\n    }\n    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);\n    sqlite3_step(p);\n    pNode->isDirty = 0;\n    rc = sqlite3_reset(p);\n    sqlite3_bind_null(p, 2);\n    if( pNode->iNode==0 && rc==SQLITE_OK ){\n      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);\n      nodeHashInsert(pRtree, pNode);\n    }\n  }\n  return rc;\n}\n\n/*\n** Release a reference to a node. If the node is dirty and the reference\n** count drops to zero, the node data is written to the database.\n*/\nstatic int nodeRelease(Rtree *pRtree, RtreeNode *pNode){\n  int rc = SQLITE_OK;\n  if( pNode ){\n    assert( pNode->nRef>0 );\n    assert( pRtree->nNodeRef>0 );\n    pNode->nRef--;\n    if( pNode->nRef==0 ){\n      pRtree->nNodeRef--;\n      if( pNode->iNode==1 ){\n        pRtree->iDepth = -1;\n      }\n      if( pNode->pParent ){\n        rc = nodeRelease(pRtree, pNode->pParent);\n      }\n      if( rc==SQLITE_OK ){\n        rc = nodeWrite(pRtree, pNode);\n      }\n      nodeHashDelete(pRtree, pNode);\n      sqlite3_free(pNode);\n    }\n  }\n  return rc;\n}\n\n/*\n** Return the 64-bit integer value associated with cell iCell of\n** node pNode. If pNode is a leaf node, this is a rowid. If it is\n** an internal node, then the 64-bit integer is a child page number.\n*/\nstatic i64 nodeGetRowid(\n  Rtree *pRtree,       /* The overall R-Tree */\n  RtreeNode *pNode,    /* The node from which to extract the ID */\n  int iCell            /* The cell index from which to extract the ID */\n){\n  assert( iCell<NCELL(pNode) );\n  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);\n}\n\n/*\n** Return coordinate iCoord from cell iCell in node pNode.\n*/\nstatic void nodeGetCoord(\n  Rtree *pRtree,               /* The overall R-Tree */\n  RtreeNode *pNode,            /* The node from which to extract a coordinate */\n  int iCell,                   /* The index of the cell within the node */\n  int iCoord,                  /* Which coordinate to extract */\n  RtreeCoord *pCoord           /* OUT: Space to write result to */\n){\n  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);\n}\n\n/*\n** Deserialize cell iCell of node pNode. Populate the structure pointed\n** to by pCell with the results.\n*/\nstatic void nodeGetCell(\n  Rtree *pRtree,               /* The overall R-Tree */\n  RtreeNode *pNode,            /* The node containing the cell to be read */\n  int iCell,                   /* Index of the cell within the node */\n  RtreeCell *pCell             /* OUT: Write the cell contents here */\n){\n  u8 *pData;\n  RtreeCoord *pCoord;\n  int ii = 0;\n  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);\n  pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);\n  pCoord = pCell->aCoord;\n  do{\n    readCoord(pData, &pCoord[ii]);\n    readCoord(pData+4, &pCoord[ii+1]);\n    pData += 8;\n    ii += 2;\n  }while( ii<pRtree->nDim2 );\n}\n\n\n/* Forward declaration for the function that does the work of\n** the virtual table module xCreate() and xConnect() methods.\n*/\nstatic int rtreeInit(\n  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int\n);\n\n/* \n** Rtree virtual table module xCreate method.\n*/\nstatic int rtreeCreate(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);\n}\n\n/* \n** Rtree virtual table module xConnect method.\n*/\nstatic int rtreeConnect(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);\n}\n\n/*\n** Increment the r-tree reference count.\n*/\nstatic void rtreeReference(Rtree *pRtree){\n  pRtree->nBusy++;\n}\n\n/*\n** Decrement the r-tree reference count. When the reference count reaches\n** zero the structure is deleted.\n*/\nstatic void rtreeRelease(Rtree *pRtree){\n  pRtree->nBusy--;\n  if( pRtree->nBusy==0 ){\n    pRtree->inWrTrans = 0;\n    assert( pRtree->nCursor==0 );\n    nodeBlobReset(pRtree);\n    assert( pRtree->nNodeRef==0 || pRtree->bCorrupt );\n    sqlite3_finalize(pRtree->pWriteNode);\n    sqlite3_finalize(pRtree->pDeleteNode);\n    sqlite3_finalize(pRtree->pReadRowid);\n    sqlite3_finalize(pRtree->pWriteRowid);\n    sqlite3_finalize(pRtree->pDeleteRowid);\n    sqlite3_finalize(pRtree->pReadParent);\n    sqlite3_finalize(pRtree->pWriteParent);\n    sqlite3_finalize(pRtree->pDeleteParent);\n    sqlite3_finalize(pRtree->pWriteAux);\n    sqlite3_free(pRtree->zReadAuxSql);\n    sqlite3_free(pRtree);\n  }\n}\n\n/* \n** Rtree virtual table module xDisconnect method.\n*/\nstatic int rtreeDisconnect(sqlite3_vtab *pVtab){\n  rtreeRelease((Rtree *)pVtab);\n  return SQLITE_OK;\n}\n\n/* \n** Rtree virtual table module xDestroy method.\n*/\nstatic int rtreeDestroy(sqlite3_vtab *pVtab){\n  Rtree *pRtree = (Rtree *)pVtab;\n  int rc;\n  char *zCreate = sqlite3_mprintf(\n    \"DROP TABLE '%q'.'%q_node';\"\n    \"DROP TABLE '%q'.'%q_rowid';\"\n    \"DROP TABLE '%q'.'%q_parent';\",\n    pRtree->zDb, pRtree->zName, \n    pRtree->zDb, pRtree->zName,\n    pRtree->zDb, pRtree->zName\n  );\n  if( !zCreate ){\n    rc = SQLITE_NOMEM;\n  }else{\n    nodeBlobReset(pRtree);\n    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);\n    sqlite3_free(zCreate);\n  }\n  if( rc==SQLITE_OK ){\n    rtreeRelease(pRtree);\n  }\n\n  return rc;\n}\n\n/* \n** Rtree virtual table module xOpen method.\n*/\nstatic int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){\n  int rc = SQLITE_NOMEM;\n  Rtree *pRtree = (Rtree *)pVTab;\n  RtreeCursor *pCsr;\n\n  pCsr = (RtreeCursor *)sqlite3_malloc64(sizeof(RtreeCursor));\n  if( pCsr ){\n    memset(pCsr, 0, sizeof(RtreeCursor));\n    pCsr->base.pVtab = pVTab;\n    rc = SQLITE_OK;\n    pRtree->nCursor++;\n  }\n  *ppCursor = (sqlite3_vtab_cursor *)pCsr;\n\n  return rc;\n}\n\n\n/*\n** Reset a cursor back to its initial state.\n*/\nstatic void resetCursor(RtreeCursor *pCsr){\n  Rtree *pRtree = (Rtree *)(pCsr->base.pVtab);\n  int ii;\n  sqlite3_stmt *pStmt;\n  if( pCsr->aConstraint ){\n    int i;                        /* Used to iterate through constraint array */\n    for(i=0; i<pCsr->nConstraint; i++){\n      sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;\n      if( pInfo ){\n        if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);\n        sqlite3_free(pInfo);\n      }\n    }\n    sqlite3_free(pCsr->aConstraint);\n    pCsr->aConstraint = 0;\n  }\n  for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);\n  sqlite3_free(pCsr->aPoint);\n  pStmt = pCsr->pReadAux;\n  memset(pCsr, 0, sizeof(RtreeCursor));\n  pCsr->base.pVtab = (sqlite3_vtab*)pRtree;\n  pCsr->pReadAux = pStmt;\n\n}\n\n/* \n** Rtree virtual table module xClose method.\n*/\nstatic int rtreeClose(sqlite3_vtab_cursor *cur){\n  Rtree *pRtree = (Rtree *)(cur->pVtab);\n  RtreeCursor *pCsr = (RtreeCursor *)cur;\n  assert( pRtree->nCursor>0 );\n  resetCursor(pCsr);\n  sqlite3_finalize(pCsr->pReadAux);\n  sqlite3_free(pCsr);\n  pRtree->nCursor--;\n  nodeBlobReset(pRtree);\n  return SQLITE_OK;\n}\n\n/*\n** Rtree virtual table module xEof method.\n**\n** Return non-zero if the cursor does not currently point to a valid \n** record (i.e if the scan has finished), or zero otherwise.\n*/\nstatic int rtreeEof(sqlite3_vtab_cursor *cur){\n  RtreeCursor *pCsr = (RtreeCursor *)cur;\n  return pCsr->atEOF;\n}\n\n/*\n** Convert raw bits from the on-disk RTree record into a coordinate value.\n** The on-disk format is big-endian and needs to be converted for little-\n** endian platforms.  The on-disk record stores integer coordinates if\n** eInt is true and it stores 32-bit floating point records if eInt is\n** false.  a[] is the four bytes of the on-disk record to be decoded.\n** Store the results in \"r\".\n**\n** There are five versions of this macro.  The last one is generic.  The\n** other four are various architectures-specific optimizations.\n*/\n#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300\n#define RTREE_DECODE_COORD(eInt, a, r) {                        \\\n    RtreeCoord c;    /* Coordinate decoded */                   \\\n    c.u = _byteswap_ulong(*(u32*)a);                            \\\n    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \\\n}\n#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000\n#define RTREE_DECODE_COORD(eInt, a, r) {                        \\\n    RtreeCoord c;    /* Coordinate decoded */                   \\\n    c.u = __builtin_bswap32(*(u32*)a);                          \\\n    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \\\n}\n#elif SQLITE_BYTEORDER==1234\n#define RTREE_DECODE_COORD(eInt, a, r) {                        \\\n    RtreeCoord c;    /* Coordinate decoded */                   \\\n    memcpy(&c.u,a,4);                                           \\\n    c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \\\n          ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \\\n    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \\\n}\n#elif SQLITE_BYTEORDER==4321\n#define RTREE_DECODE_COORD(eInt, a, r) {                        \\\n    RtreeCoord c;    /* Coordinate decoded */                   \\\n    memcpy(&c.u,a,4);                                           \\\n    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \\\n}\n#else\n#define RTREE_DECODE_COORD(eInt, a, r) {                        \\\n    RtreeCoord c;    /* Coordinate decoded */                   \\\n    c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \\\n           +((u32)a[2]<<8) + a[3];                              \\\n    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \\\n}\n#endif\n\n/*\n** Check the RTree node or entry given by pCellData and p against the MATCH\n** constraint pConstraint.  \n*/\nstatic int rtreeCallbackConstraint(\n  RtreeConstraint *pConstraint,  /* The constraint to test */\n  int eInt,                      /* True if RTree holding integer coordinates */\n  u8 *pCellData,                 /* Raw cell content */\n  RtreeSearchPoint *pSearch,     /* Container of this cell */\n  sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */\n  int *peWithin                  /* OUT: visibility of the cell */\n){\n  sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */\n  int nCoord = pInfo->nCoord;                           /* No. of coordinates */\n  int rc;                                             /* Callback return code */\n  RtreeCoord c;                                       /* Translator union */\n  sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */\n\n  assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );\n  assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );\n\n  if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){\n    pInfo->iRowid = readInt64(pCellData);\n  }\n  pCellData += 8;\n#ifndef SQLITE_RTREE_INT_ONLY\n  if( eInt==0 ){\n    switch( nCoord ){\n      case 10:  readCoord(pCellData+36, &c); aCoord[9] = c.f;\n                readCoord(pCellData+32, &c); aCoord[8] = c.f;\n      case 8:   readCoord(pCellData+28, &c); aCoord[7] = c.f;\n                readCoord(pCellData+24, &c); aCoord[6] = c.f;\n      case 6:   readCoord(pCellData+20, &c); aCoord[5] = c.f;\n                readCoord(pCellData+16, &c); aCoord[4] = c.f;\n      case 4:   readCoord(pCellData+12, &c); aCoord[3] = c.f;\n                readCoord(pCellData+8,  &c); aCoord[2] = c.f;\n      default:  readCoord(pCellData+4,  &c); aCoord[1] = c.f;\n                readCoord(pCellData,    &c); aCoord[0] = c.f;\n    }\n  }else\n#endif\n  {\n    switch( nCoord ){\n      case 10:  readCoord(pCellData+36, &c); aCoord[9] = c.i;\n                readCoord(pCellData+32, &c); aCoord[8] = c.i;\n      case 8:   readCoord(pCellData+28, &c); aCoord[7] = c.i;\n                readCoord(pCellData+24, &c); aCoord[6] = c.i;\n      case 6:   readCoord(pCellData+20, &c); aCoord[5] = c.i;\n                readCoord(pCellData+16, &c); aCoord[4] = c.i;\n      case 4:   readCoord(pCellData+12, &c); aCoord[3] = c.i;\n                readCoord(pCellData+8,  &c); aCoord[2] = c.i;\n      default:  readCoord(pCellData+4,  &c); aCoord[1] = c.i;\n                readCoord(pCellData,    &c); aCoord[0] = c.i;\n    }\n  }\n  if( pConstraint->op==RTREE_MATCH ){\n    int eWithin = 0;\n    rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,\n                              nCoord, aCoord, &eWithin);\n    if( eWithin==0 ) *peWithin = NOT_WITHIN;\n    *prScore = RTREE_ZERO;\n  }else{\n    pInfo->aCoord = aCoord;\n    pInfo->iLevel = pSearch->iLevel - 1;\n    pInfo->rScore = pInfo->rParentScore = pSearch->rScore;\n    pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;\n    rc = pConstraint->u.xQueryFunc(pInfo);\n    if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;\n    if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){\n      *prScore = pInfo->rScore;\n    }\n  }\n  return rc;\n}\n\n/* \n** Check the internal RTree node given by pCellData against constraint p.\n** If this constraint cannot be satisfied by any child within the node,\n** set *peWithin to NOT_WITHIN.\n*/\nstatic void rtreeNonleafConstraint(\n  RtreeConstraint *p,        /* The constraint to test */\n  int eInt,                  /* True if RTree holds integer coordinates */\n  u8 *pCellData,             /* Raw cell content as appears on disk */\n  int *peWithin              /* Adjust downward, as appropriate */\n){\n  sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */\n\n  /* p->iCoord might point to either a lower or upper bound coordinate\n  ** in a coordinate pair.  But make pCellData point to the lower bound.\n  */\n  pCellData += 8 + 4*(p->iCoord&0xfe);\n\n  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE \n      || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE\n      || p->op==RTREE_FALSE );\n  assert( ((((char*)pCellData) - (char*)0)&3)==0 );  /* 4-byte aligned */\n  switch( p->op ){\n    case RTREE_TRUE:  return;   /* Always satisfied */\n    case RTREE_FALSE: break;    /* Never satisfied */\n    case RTREE_LE:\n    case RTREE_LT:\n    case RTREE_EQ:\n      RTREE_DECODE_COORD(eInt, pCellData, val);\n      /* val now holds the lower bound of the coordinate pair */\n      if( p->u.rValue>=val ) return;\n      if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */\n      /* Fall through for the RTREE_EQ case */\n\n    default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */\n      pCellData += 4;\n      RTREE_DECODE_COORD(eInt, pCellData, val);\n      /* val now holds the upper bound of the coordinate pair */\n      if( p->u.rValue<=val ) return;\n  }\n  *peWithin = NOT_WITHIN;\n}\n\n/*\n** Check the leaf RTree cell given by pCellData against constraint p.\n** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.\n** If the constraint is satisfied, leave *peWithin unchanged.\n**\n** The constraint is of the form:  xN op $val\n**\n** The op is given by p->op.  The xN is p->iCoord-th coordinate in\n** pCellData.  $val is given by p->u.rValue.\n*/\nstatic void rtreeLeafConstraint(\n  RtreeConstraint *p,        /* The constraint to test */\n  int eInt,                  /* True if RTree holds integer coordinates */\n  u8 *pCellData,             /* Raw cell content as appears on disk */\n  int *peWithin              /* Adjust downward, as appropriate */\n){\n  RtreeDValue xN;      /* Coordinate value converted to a double */\n\n  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE \n      || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE\n      || p->op==RTREE_FALSE );\n  pCellData += 8 + p->iCoord*4;\n  assert( ((((char*)pCellData) - (char*)0)&3)==0 );  /* 4-byte aligned */\n  RTREE_DECODE_COORD(eInt, pCellData, xN);\n  switch( p->op ){\n    case RTREE_TRUE:  return;   /* Always satisfied */\n    case RTREE_FALSE: break;    /* Never satisfied */\n    case RTREE_LE:    if( xN <= p->u.rValue ) return;  break;\n    case RTREE_LT:    if( xN <  p->u.rValue ) return;  break;\n    case RTREE_GE:    if( xN >= p->u.rValue ) return;  break;\n    case RTREE_GT:    if( xN >  p->u.rValue ) return;  break;\n    default:          if( xN == p->u.rValue ) return;  break;\n  }\n  *peWithin = NOT_WITHIN;\n}\n\n/*\n** One of the cells in node pNode is guaranteed to have a 64-bit \n** integer value equal to iRowid. Return the index of this cell.\n*/\nstatic int nodeRowidIndex(\n  Rtree *pRtree, \n  RtreeNode *pNode, \n  i64 iRowid,\n  int *piIndex\n){\n  int ii;\n  int nCell = NCELL(pNode);\n  assert( nCell<200 );\n  for(ii=0; ii<nCell; ii++){\n    if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){\n      *piIndex = ii;\n      return SQLITE_OK;\n    }\n  }\n  RTREE_IS_CORRUPT(pRtree);\n  return SQLITE_CORRUPT_VTAB;\n}\n\n/*\n** Return the index of the cell containing a pointer to node pNode\n** in its parent. If pNode is the root node, return -1.\n*/\nstatic int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){\n  RtreeNode *pParent = pNode->pParent;\n  if( pParent ){\n    return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);\n  }\n  *piIndex = -1;\n  return SQLITE_OK;\n}\n\n/*\n** Compare two search points.  Return negative, zero, or positive if the first\n** is less than, equal to, or greater than the second.\n**\n** The rScore is the primary key.  Smaller rScore values come first.\n** If the rScore is a tie, then use iLevel as the tie breaker with smaller\n** iLevel values coming first.  In this way, if rScore is the same for all\n** SearchPoints, then iLevel becomes the deciding factor and the result\n** is a depth-first search, which is the desired default behavior.\n*/\nstatic int rtreeSearchPointCompare(\n  const RtreeSearchPoint *pA,\n  const RtreeSearchPoint *pB\n){\n  if( pA->rScore<pB->rScore ) return -1;\n  if( pA->rScore>pB->rScore ) return +1;\n  if( pA->iLevel<pB->iLevel ) return -1;\n  if( pA->iLevel>pB->iLevel ) return +1;\n  return 0;\n}\n\n/*\n** Interchange two search points in a cursor.\n*/\nstatic void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){\n  RtreeSearchPoint t = p->aPoint[i];\n  assert( i<j );\n  p->aPoint[i] = p->aPoint[j];\n  p->aPoint[j] = t;\n  i++; j++;\n  if( i<RTREE_CACHE_SZ ){\n    if( j>=RTREE_CACHE_SZ ){\n      nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);\n      p->aNode[i] = 0;\n    }else{\n      RtreeNode *pTemp = p->aNode[i];\n      p->aNode[i] = p->aNode[j];\n      p->aNode[j] = pTemp;\n    }\n  }\n}\n\n/*\n** Return the search point with the lowest current score.\n*/\nstatic RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){\n  return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;\n}\n\n/*\n** Get the RtreeNode for the search point with the lowest score.\n*/\nstatic RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){\n  sqlite3_int64 id;\n  int ii = 1 - pCur->bPoint;\n  assert( ii==0 || ii==1 );\n  assert( pCur->bPoint || pCur->nPoint );\n  if( pCur->aNode[ii]==0 ){\n    assert( pRC!=0 );\n    id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;\n    *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);\n  }\n  return pCur->aNode[ii];\n}\n\n/*\n** Push a new element onto the priority queue\n*/\nstatic RtreeSearchPoint *rtreeEnqueue(\n  RtreeCursor *pCur,    /* The cursor */\n  RtreeDValue rScore,   /* Score for the new search point */\n  u8 iLevel             /* Level for the new search point */\n){\n  int i, j;\n  RtreeSearchPoint *pNew;\n  if( pCur->nPoint>=pCur->nPointAlloc ){\n    int nNew = pCur->nPointAlloc*2 + 8;\n    pNew = sqlite3_realloc64(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));\n    if( pNew==0 ) return 0;\n    pCur->aPoint = pNew;\n    pCur->nPointAlloc = nNew;\n  }\n  i = pCur->nPoint++;\n  pNew = pCur->aPoint + i;\n  pNew->rScore = rScore;\n  pNew->iLevel = iLevel;\n  assert( iLevel<=RTREE_MAX_DEPTH );\n  while( i>0 ){\n    RtreeSearchPoint *pParent;\n    j = (i-1)/2;\n    pParent = pCur->aPoint + j;\n    if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;\n    rtreeSearchPointSwap(pCur, j, i);\n    i = j;\n    pNew = pParent;\n  }\n  return pNew;\n}\n\n/*\n** Allocate a new RtreeSearchPoint and return a pointer to it.  Return\n** NULL if malloc fails.\n*/\nstatic RtreeSearchPoint *rtreeSearchPointNew(\n  RtreeCursor *pCur,    /* The cursor */\n  RtreeDValue rScore,   /* Score for the new search point */\n  u8 iLevel             /* Level for the new search point */\n){\n  RtreeSearchPoint *pNew, *pFirst;\n  pFirst = rtreeSearchPointFirst(pCur);\n  pCur->anQueue[iLevel]++;\n  if( pFirst==0\n   || pFirst->rScore>rScore \n   || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)\n  ){\n    if( pCur->bPoint ){\n      int ii;\n      pNew = rtreeEnqueue(pCur, rScore, iLevel);\n      if( pNew==0 ) return 0;\n      ii = (int)(pNew - pCur->aPoint) + 1;\n      if( ii<RTREE_CACHE_SZ ){\n        assert( pCur->aNode[ii]==0 );\n        pCur->aNode[ii] = pCur->aNode[0];\n      }else{\n        nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);\n      }\n      pCur->aNode[0] = 0;\n      *pNew = pCur->sPoint;\n    }\n    pCur->sPoint.rScore = rScore;\n    pCur->sPoint.iLevel = iLevel;\n    pCur->bPoint = 1;\n    return &pCur->sPoint;\n  }else{\n    return rtreeEnqueue(pCur, rScore, iLevel);\n  }\n}\n\n#if 0\n/* Tracing routines for the RtreeSearchPoint queue */\nstatic void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){\n  if( idx<0 ){ printf(\" s\"); }else{ printf(\"%2d\", idx); }\n  printf(\" %d.%05lld.%02d %g %d\",\n    p->iLevel, p->id, p->iCell, p->rScore, p->eWithin\n  );\n  idx++;\n  if( idx<RTREE_CACHE_SZ ){\n    printf(\" %p\\n\", pCur->aNode[idx]);\n  }else{\n    printf(\"\\n\");\n  }\n}\nstatic void traceQueue(RtreeCursor *pCur, const char *zPrefix){\n  int ii;\n  printf(\"=== %9s \", zPrefix);\n  if( pCur->bPoint ){\n    tracePoint(&pCur->sPoint, -1, pCur);\n  }\n  for(ii=0; ii<pCur->nPoint; ii++){\n    if( ii>0 || pCur->bPoint ) printf(\"              \");\n    tracePoint(&pCur->aPoint[ii], ii, pCur);\n  }\n}\n# define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)\n#else\n# define RTREE_QUEUE_TRACE(A,B)   /* no-op */\n#endif\n\n/* Remove the search point with the lowest current score.\n*/\nstatic void rtreeSearchPointPop(RtreeCursor *p){\n  int i, j, k, n;\n  i = 1 - p->bPoint;\n  assert( i==0 || i==1 );\n  if( p->aNode[i] ){\n    nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);\n    p->aNode[i] = 0;\n  }\n  if( p->bPoint ){\n    p->anQueue[p->sPoint.iLevel]--;\n    p->bPoint = 0;\n  }else if( p->nPoint ){\n    p->anQueue[p->aPoint[0].iLevel]--;\n    n = --p->nPoint;\n    p->aPoint[0] = p->aPoint[n];\n    if( n<RTREE_CACHE_SZ-1 ){\n      p->aNode[1] = p->aNode[n+1];\n      p->aNode[n+1] = 0;\n    }\n    i = 0;\n    while( (j = i*2+1)<n ){\n      k = j+1;\n      if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){\n        if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){\n          rtreeSearchPointSwap(p, i, k);\n          i = k;\n        }else{\n          break;\n        }\n      }else{\n        if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){\n          rtreeSearchPointSwap(p, i, j);\n          i = j;\n        }else{\n          break;\n        }\n      }\n    }\n  }\n}\n\n\n/*\n** Continue the search on cursor pCur until the front of the queue\n** contains an entry suitable for returning as a result-set row,\n** or until the RtreeSearchPoint queue is empty, indicating that the\n** query has completed.\n*/\nstatic int rtreeStepToLeaf(RtreeCursor *pCur){\n  RtreeSearchPoint *p;\n  Rtree *pRtree = RTREE_OF_CURSOR(pCur);\n  RtreeNode *pNode;\n  int eWithin;\n  int rc = SQLITE_OK;\n  int nCell;\n  int nConstraint = pCur->nConstraint;\n  int ii;\n  int eInt;\n  RtreeSearchPoint x;\n\n  eInt = pRtree->eCoordType==RTREE_COORD_INT32;\n  while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){\n    u8 *pCellData;\n    pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);\n    if( rc ) return rc;\n    nCell = NCELL(pNode);\n    assert( nCell<200 );\n    pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);\n    while( p->iCell<nCell ){\n      sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;\n      eWithin = FULLY_WITHIN;\n      for(ii=0; ii<nConstraint; ii++){\n        RtreeConstraint *pConstraint = pCur->aConstraint + ii;\n        if( pConstraint->op>=RTREE_MATCH ){\n          rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,\n                                       &rScore, &eWithin);\n          if( rc ) return rc;\n        }else if( p->iLevel==1 ){\n          rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);\n        }else{\n          rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);\n        }\n        if( eWithin==NOT_WITHIN ){\n          p->iCell++;\n          pCellData += pRtree->nBytesPerCell;\n          break;\n        }\n      }\n      if( eWithin==NOT_WITHIN ) continue;\n      p->iCell++;\n      x.iLevel = p->iLevel - 1;\n      if( x.iLevel ){\n        x.id = readInt64(pCellData);\n        for(ii=0; ii<pCur->nPoint; ii++){\n          if( pCur->aPoint[ii].id==x.id ){\n            RTREE_IS_CORRUPT(pRtree);\n            return SQLITE_CORRUPT_VTAB;\n          }\n        }\n        x.iCell = 0;\n      }else{\n        x.id = p->id;\n        x.iCell = p->iCell - 1;\n      }\n      if( p->iCell>=nCell ){\n        RTREE_QUEUE_TRACE(pCur, \"POP-S:\");\n        rtreeSearchPointPop(pCur);\n      }\n      if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;\n      p = rtreeSearchPointNew(pCur, rScore, x.iLevel);\n      if( p==0 ) return SQLITE_NOMEM;\n      p->eWithin = (u8)eWithin;\n      p->id = x.id;\n      p->iCell = x.iCell;\n      RTREE_QUEUE_TRACE(pCur, \"PUSH-S:\");\n      break;\n    }\n    if( p->iCell>=nCell ){\n      RTREE_QUEUE_TRACE(pCur, \"POP-Se:\");\n      rtreeSearchPointPop(pCur);\n    }\n  }\n  pCur->atEOF = p==0;\n  return SQLITE_OK;\n}\n\n/* \n** Rtree virtual table module xNext method.\n*/\nstatic int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){\n  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;\n  int rc = SQLITE_OK;\n\n  /* Move to the next entry that matches the configured constraints. */\n  RTREE_QUEUE_TRACE(pCsr, \"POP-Nx:\");\n  if( pCsr->bAuxValid ){\n    pCsr->bAuxValid = 0;\n    sqlite3_reset(pCsr->pReadAux);\n  }\n  rtreeSearchPointPop(pCsr);\n  rc = rtreeStepToLeaf(pCsr);\n  return rc;\n}\n\n/* \n** Rtree virtual table module xRowid method.\n*/\nstatic int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){\n  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;\n  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);\n  int rc = SQLITE_OK;\n  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);\n  if( rc==SQLITE_OK && p ){\n    *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);\n  }\n  return rc;\n}\n\n/* \n** Rtree virtual table module xColumn method.\n*/\nstatic int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){\n  Rtree *pRtree = (Rtree *)cur->pVtab;\n  RtreeCursor *pCsr = (RtreeCursor *)cur;\n  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);\n  RtreeCoord c;\n  int rc = SQLITE_OK;\n  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);\n\n  if( rc ) return rc;\n  if( p==0 ) return SQLITE_OK;\n  if( i==0 ){\n    sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));\n  }else if( i<=pRtree->nDim2 ){\n    nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);\n#ifndef SQLITE_RTREE_INT_ONLY\n    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){\n      sqlite3_result_double(ctx, c.f);\n    }else\n#endif\n    {\n      assert( pRtree->eCoordType==RTREE_COORD_INT32 );\n      sqlite3_result_int(ctx, c.i);\n    }\n  }else{\n    if( !pCsr->bAuxValid ){\n      if( pCsr->pReadAux==0 ){\n        rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,\n                                &pCsr->pReadAux, 0);\n        if( rc ) return rc;\n      }\n      sqlite3_bind_int64(pCsr->pReadAux, 1, \n          nodeGetRowid(pRtree, pNode, p->iCell));\n      rc = sqlite3_step(pCsr->pReadAux);\n      if( rc==SQLITE_ROW ){\n        pCsr->bAuxValid = 1;\n      }else{\n        sqlite3_reset(pCsr->pReadAux);\n        if( rc==SQLITE_DONE ) rc = SQLITE_OK;\n        return rc;\n      }\n    }\n    sqlite3_result_value(ctx,\n         sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1));\n  }  \n  return SQLITE_OK;\n}\n\n/* \n** Use nodeAcquire() to obtain the leaf node containing the record with \n** rowid iRowid. If successful, set *ppLeaf to point to the node and\n** return SQLITE_OK. If there is no such record in the table, set\n** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf\n** to zero and return an SQLite error code.\n*/\nstatic int findLeafNode(\n  Rtree *pRtree,              /* RTree to search */\n  i64 iRowid,                 /* The rowid searching for */\n  RtreeNode **ppLeaf,         /* Write the node here */\n  sqlite3_int64 *piNode       /* Write the node-id here */\n){\n  int rc;\n  *ppLeaf = 0;\n  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);\n  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){\n    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);\n    if( piNode ) *piNode = iNode;\n    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);\n    sqlite3_reset(pRtree->pReadRowid);\n  }else{\n    rc = sqlite3_reset(pRtree->pReadRowid);\n  }\n  return rc;\n}\n\n/*\n** This function is called to configure the RtreeConstraint object passed\n** as the second argument for a MATCH constraint. The value passed as the\n** first argument to this function is the right-hand operand to the MATCH\n** operator.\n*/\nstatic int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){\n  RtreeMatchArg *pBlob, *pSrc;       /* BLOB returned by geometry function */\n  sqlite3_rtree_query_info *pInfo;   /* Callback information */\n\n  pSrc = sqlite3_value_pointer(pValue, \"RtreeMatchArg\");\n  if( pSrc==0 ) return SQLITE_ERROR;\n  pInfo = (sqlite3_rtree_query_info*)\n                sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );\n  if( !pInfo ) return SQLITE_NOMEM;\n  memset(pInfo, 0, sizeof(*pInfo));\n  pBlob = (RtreeMatchArg*)&pInfo[1];\n  memcpy(pBlob, pSrc, pSrc->iSize);\n  pInfo->pContext = pBlob->cb.pContext;\n  pInfo->nParam = pBlob->nParam;\n  pInfo->aParam = pBlob->aParam;\n  pInfo->apSqlParam = pBlob->apSqlParam;\n\n  if( pBlob->cb.xGeom ){\n    pCons->u.xGeom = pBlob->cb.xGeom;\n  }else{\n    pCons->op = RTREE_QUERY;\n    pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;\n  }\n  pCons->pInfo = pInfo;\n  return SQLITE_OK;\n}\n\n/* \n** Rtree virtual table module xFilter method.\n*/\nstatic int rtreeFilter(\n  sqlite3_vtab_cursor *pVtabCursor, \n  int idxNum, const char *idxStr,\n  int argc, sqlite3_value **argv\n){\n  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;\n  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;\n  RtreeNode *pRoot = 0;\n  int ii;\n  int rc = SQLITE_OK;\n  int iCell = 0;\n\n  rtreeReference(pRtree);\n\n  /* Reset the cursor to the same state as rtreeOpen() leaves it in. */\n  resetCursor(pCsr);\n\n  pCsr->iStrategy = idxNum;\n  if( idxNum==1 ){\n    /* Special case - lookup by rowid. */\n    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */\n    RtreeSearchPoint *p;     /* Search point for the leaf */\n    i64 iRowid = sqlite3_value_int64(argv[0]);\n    i64 iNode = 0;\n    int eType = sqlite3_value_numeric_type(argv[0]);\n    if( eType==SQLITE_INTEGER\n     || (eType==SQLITE_FLOAT && sqlite3_value_double(argv[0])==iRowid)\n    ){\n      rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);\n    }else{\n      rc = SQLITE_OK;\n      pLeaf = 0;\n    }\n    if( rc==SQLITE_OK && pLeaf!=0 ){\n      p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);\n      assert( p!=0 );  /* Always returns pCsr->sPoint */\n      pCsr->aNode[0] = pLeaf;\n      p->id = iNode;\n      p->eWithin = PARTLY_WITHIN;\n      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);\n      p->iCell = (u8)iCell;\n      RTREE_QUEUE_TRACE(pCsr, \"PUSH-F1:\");\n    }else{\n      pCsr->atEOF = 1;\n    }\n  }else{\n    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array \n    ** with the configured constraints. \n    */\n    rc = nodeAcquire(pRtree, 1, 0, &pRoot);\n    if( rc==SQLITE_OK && argc>0 ){\n      pCsr->aConstraint = sqlite3_malloc64(sizeof(RtreeConstraint)*argc);\n      pCsr->nConstraint = argc;\n      if( !pCsr->aConstraint ){\n        rc = SQLITE_NOMEM;\n      }else{\n        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);\n        memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));\n        assert( (idxStr==0 && argc==0)\n                || (idxStr && (int)strlen(idxStr)==argc*2) );\n        for(ii=0; ii<argc; ii++){\n          RtreeConstraint *p = &pCsr->aConstraint[ii];\n          int eType = sqlite3_value_numeric_type(argv[ii]);\n          p->op = idxStr[ii*2];\n          p->iCoord = idxStr[ii*2+1]-'0';\n          if( p->op>=RTREE_MATCH ){\n            /* A MATCH operator. The right-hand-side must be a blob that\n            ** can be cast into an RtreeMatchArg object. One created using\n            ** an sqlite3_rtree_geometry_callback() SQL user function.\n            */\n            rc = deserializeGeometry(argv[ii], p);\n            if( rc!=SQLITE_OK ){\n              break;\n            }\n            p->pInfo->nCoord = pRtree->nDim2;\n            p->pInfo->anQueue = pCsr->anQueue;\n            p->pInfo->mxLevel = pRtree->iDepth + 1;\n          }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){\n#ifdef SQLITE_RTREE_INT_ONLY\n            p->u.rValue = sqlite3_value_int64(argv[ii]);\n#else\n            p->u.rValue = sqlite3_value_double(argv[ii]);\n#endif\n          }else{\n            p->u.rValue = RTREE_ZERO;\n            if( eType==SQLITE_NULL ){\n              p->op = RTREE_FALSE;\n            }else if( p->op==RTREE_LT || p->op==RTREE_LE ){\n              p->op = RTREE_TRUE;\n            }else{\n              p->op = RTREE_FALSE;\n            }\n          }\n        }\n      }\n    }\n    if( rc==SQLITE_OK ){\n      RtreeSearchPoint *pNew;\n      pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));\n      if( pNew==0 ) return SQLITE_NOMEM;\n      pNew->id = 1;\n      pNew->iCell = 0;\n      pNew->eWithin = PARTLY_WITHIN;\n      assert( pCsr->bPoint==1 );\n      pCsr->aNode[0] = pRoot;\n      pRoot = 0;\n      RTREE_QUEUE_TRACE(pCsr, \"PUSH-Fm:\");\n      rc = rtreeStepToLeaf(pCsr);\n    }\n  }\n\n  nodeRelease(pRtree, pRoot);\n  rtreeRelease(pRtree);\n  return rc;\n}\n\n/*\n** Rtree virtual table module xBestIndex method. There are three\n** table scan strategies to choose from (in order from most to \n** least desirable):\n**\n**   idxNum     idxStr        Strategy\n**   ------------------------------------------------\n**     1        Unused        Direct lookup by rowid.\n**     2        See below     R-tree query or full-table scan.\n**   ------------------------------------------------\n**\n** If strategy 1 is used, then idxStr is not meaningful. If strategy\n** 2 is used, idxStr is formatted to contain 2 bytes for each \n** constraint used. The first two bytes of idxStr correspond to \n** the constraint in sqlite3_index_info.aConstraintUsage[] with\n** (argvIndex==1) etc.\n**\n** The first of each pair of bytes in idxStr identifies the constraint\n** operator as follows:\n**\n**   Operator    Byte Value\n**   ----------------------\n**      =        0x41 ('A')\n**     <=        0x42 ('B')\n**      <        0x43 ('C')\n**     >=        0x44 ('D')\n**      >        0x45 ('E')\n**   MATCH       0x46 ('F')\n**   ----------------------\n**\n** The second of each pair of bytes identifies the coordinate column\n** to which the constraint applies. The leftmost coordinate column\n** is 'a', the second from the left 'b' etc.\n*/\nstatic int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){\n  Rtree *pRtree = (Rtree*)tab;\n  int rc = SQLITE_OK;\n  int ii;\n  int bMatch = 0;                 /* True if there exists a MATCH constraint */\n  i64 nRow;                       /* Estimated rows returned by this scan */\n\n  int iIdx = 0;\n  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];\n  memset(zIdxStr, 0, sizeof(zIdxStr));\n\n  /* Check if there exists a MATCH constraint - even an unusable one. If there\n  ** is, do not consider the lookup-by-rowid plan as using such a plan would\n  ** require the VDBE to evaluate the MATCH constraint, which is not currently\n  ** possible. */\n  for(ii=0; ii<pIdxInfo->nConstraint; ii++){\n    if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){\n      bMatch = 1;\n    }\n  }\n\n  assert( pIdxInfo->idxStr==0 );\n  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){\n    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];\n\n    if( bMatch==0 && p->usable \n     && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ \n    ){\n      /* We have an equality constraint on the rowid. Use strategy 1. */\n      int jj;\n      for(jj=0; jj<ii; jj++){\n        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;\n        pIdxInfo->aConstraintUsage[jj].omit = 0;\n      }\n      pIdxInfo->idxNum = 1;\n      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;\n      pIdxInfo->aConstraintUsage[jj].omit = 1;\n\n      /* This strategy involves a two rowid lookups on an B-Tree structures\n      ** and then a linear search of an R-Tree node. This should be \n      ** considered almost as quick as a direct rowid lookup (for which \n      ** sqlite uses an internal cost of 0.0). It is expected to return\n      ** a single row.\n      */ \n      pIdxInfo->estimatedCost = 30.0;\n      pIdxInfo->estimatedRows = 1;\n      pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;\n      return SQLITE_OK;\n    }\n\n    if( p->usable\n    && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2)\n        || p->op==SQLITE_INDEX_CONSTRAINT_MATCH)\n    ){\n      u8 op;\n      switch( p->op ){\n        case SQLITE_INDEX_CONSTRAINT_EQ:    op = RTREE_EQ;    break;\n        case SQLITE_INDEX_CONSTRAINT_GT:    op = RTREE_GT;    break;\n        case SQLITE_INDEX_CONSTRAINT_LE:    op = RTREE_LE;    break;\n        case SQLITE_INDEX_CONSTRAINT_LT:    op = RTREE_LT;    break;\n        case SQLITE_INDEX_CONSTRAINT_GE:    op = RTREE_GE;    break;\n        case SQLITE_INDEX_CONSTRAINT_MATCH: op = RTREE_MATCH; break;\n        default:                            op = 0;           break;\n      }\n      if( op ){\n        zIdxStr[iIdx++] = op;\n        zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');\n        pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);\n        pIdxInfo->aConstraintUsage[ii].omit = 1;\n      }\n    }\n  }\n\n  pIdxInfo->idxNum = 2;\n  pIdxInfo->needToFreeIdxStr = 1;\n  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf(\"%s\", zIdxStr)) ){\n    return SQLITE_NOMEM;\n  }\n\n  nRow = pRtree->nRowEst >> (iIdx/2);\n  pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;\n  pIdxInfo->estimatedRows = nRow;\n\n  return rc;\n}\n\n/*\n** Return the N-dimensional volumn of the cell stored in *p.\n*/\nstatic RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){\n  RtreeDValue area = (RtreeDValue)1;\n  assert( pRtree->nDim>=1 && pRtree->nDim<=5 );\n#ifndef SQLITE_RTREE_INT_ONLY\n  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){\n    switch( pRtree->nDim ){\n      case 5:  area  = p->aCoord[9].f - p->aCoord[8].f;\n      case 4:  area *= p->aCoord[7].f - p->aCoord[6].f;\n      case 3:  area *= p->aCoord[5].f - p->aCoord[4].f;\n      case 2:  area *= p->aCoord[3].f - p->aCoord[2].f;\n      default: area *= p->aCoord[1].f - p->aCoord[0].f;\n    }\n  }else\n#endif\n  {\n    switch( pRtree->nDim ){\n      case 5:  area  = (i64)p->aCoord[9].i - (i64)p->aCoord[8].i;\n      case 4:  area *= (i64)p->aCoord[7].i - (i64)p->aCoord[6].i;\n      case 3:  area *= (i64)p->aCoord[5].i - (i64)p->aCoord[4].i;\n      case 2:  area *= (i64)p->aCoord[3].i - (i64)p->aCoord[2].i;\n      default: area *= (i64)p->aCoord[1].i - (i64)p->aCoord[0].i;\n    }\n  }\n  return area;\n}\n\n/*\n** Return the margin length of cell p. The margin length is the sum\n** of the objects size in each dimension.\n*/\nstatic RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){\n  RtreeDValue margin = 0;\n  int ii = pRtree->nDim2 - 2;\n  do{\n    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));\n    ii -= 2;\n  }while( ii>=0 );\n  return margin;\n}\n\n/*\n** Store the union of cells p1 and p2 in p1.\n*/\nstatic void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){\n  int ii = 0;\n  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){\n    do{\n      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);\n      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);\n      ii += 2;\n    }while( ii<pRtree->nDim2 );\n  }else{\n    do{\n      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);\n      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);\n      ii += 2;\n    }while( ii<pRtree->nDim2 );\n  }\n}\n\n/*\n** Return true if the area covered by p2 is a subset of the area covered\n** by p1. False otherwise.\n*/\nstatic int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){\n  int ii;\n  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);\n  for(ii=0; ii<pRtree->nDim2; ii+=2){\n    RtreeCoord *a1 = &p1->aCoord[ii];\n    RtreeCoord *a2 = &p2->aCoord[ii];\n    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) \n     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) \n    ){\n      return 0;\n    }\n  }\n  return 1;\n}\n\n/*\n** Return the amount cell p would grow by if it were unioned with pCell.\n*/\nstatic RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){\n  RtreeDValue area;\n  RtreeCell cell;\n  memcpy(&cell, p, sizeof(RtreeCell));\n  area = cellArea(pRtree, &cell);\n  cellUnion(pRtree, &cell, pCell);\n  return (cellArea(pRtree, &cell)-area);\n}\n\nstatic RtreeDValue cellOverlap(\n  Rtree *pRtree, \n  RtreeCell *p, \n  RtreeCell *aCell, \n  int nCell\n){\n  int ii;\n  RtreeDValue overlap = RTREE_ZERO;\n  for(ii=0; ii<nCell; ii++){\n    int jj;\n    RtreeDValue o = (RtreeDValue)1;\n    for(jj=0; jj<pRtree->nDim2; jj+=2){\n      RtreeDValue x1, x2;\n      x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));\n      x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));\n      if( x2<x1 ){\n        o = (RtreeDValue)0;\n        break;\n      }else{\n        o = o * (x2-x1);\n      }\n    }\n    overlap += o;\n  }\n  return overlap;\n}\n\n\n/*\n** This function implements the ChooseLeaf algorithm from Gutman[84].\n** ChooseSubTree in r*tree terminology.\n*/\nstatic int ChooseLeaf(\n  Rtree *pRtree,               /* Rtree table */\n  RtreeCell *pCell,            /* Cell to insert into rtree */\n  int iHeight,                 /* Height of sub-tree rooted at pCell */\n  RtreeNode **ppLeaf           /* OUT: Selected leaf page */\n){\n  int rc;\n  int ii;\n  RtreeNode *pNode = 0;\n  rc = nodeAcquire(pRtree, 1, 0, &pNode);\n\n  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){\n    int iCell;\n    sqlite3_int64 iBest = 0;\n\n    RtreeDValue fMinGrowth = RTREE_ZERO;\n    RtreeDValue fMinArea = RTREE_ZERO;\n\n    int nCell = NCELL(pNode);\n    RtreeCell cell;\n    RtreeNode *pChild;\n\n    RtreeCell *aCell = 0;\n\n    /* Select the child node which will be enlarged the least if pCell\n    ** is inserted into it. Resolve ties by choosing the entry with\n    ** the smallest area.\n    */\n    for(iCell=0; iCell<nCell; iCell++){\n      int bBest = 0;\n      RtreeDValue growth;\n      RtreeDValue area;\n      nodeGetCell(pRtree, pNode, iCell, &cell);\n      growth = cellGrowth(pRtree, &cell, pCell);\n      area = cellArea(pRtree, &cell);\n      if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){\n        bBest = 1;\n      }\n      if( bBest ){\n        fMinGrowth = growth;\n        fMinArea = area;\n        iBest = cell.iRowid;\n      }\n    }\n\n    sqlite3_free(aCell);\n    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);\n    nodeRelease(pRtree, pNode);\n    pNode = pChild;\n  }\n\n  *ppLeaf = pNode;\n  return rc;\n}\n\n/*\n** A cell with the same content as pCell has just been inserted into\n** the node pNode. This function updates the bounding box cells in\n** all ancestor elements.\n*/\nstatic int AdjustTree(\n  Rtree *pRtree,                    /* Rtree table */\n  RtreeNode *pNode,                 /* Adjust ancestry of this node. */\n  RtreeCell *pCell                  /* This cell was just inserted */\n){\n  RtreeNode *p = pNode;\n  int cnt = 0;\n  while( p->pParent ){\n    RtreeNode *pParent = p->pParent;\n    RtreeCell cell;\n    int iCell;\n\n    if( (++cnt)>1000 || nodeParentIndex(pRtree, p, &iCell)  ){\n      RTREE_IS_CORRUPT(pRtree);\n      return SQLITE_CORRUPT_VTAB;\n    }\n\n    nodeGetCell(pRtree, pParent, iCell, &cell);\n    if( !cellContains(pRtree, &cell, pCell) ){\n      cellUnion(pRtree, &cell, pCell);\n      nodeOverwriteCell(pRtree, pParent, &cell, iCell);\n    }\n \n    p = pParent;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Write mapping (iRowid->iNode) to the <rtree>_rowid table.\n*/\nstatic int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){\n  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);\n  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);\n  sqlite3_step(pRtree->pWriteRowid);\n  return sqlite3_reset(pRtree->pWriteRowid);\n}\n\n/*\n** Write mapping (iNode->iPar) to the <rtree>_parent table.\n*/\nstatic int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){\n  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);\n  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);\n  sqlite3_step(pRtree->pWriteParent);\n  return sqlite3_reset(pRtree->pWriteParent);\n}\n\nstatic int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);\n\n\n/*\n** Arguments aIdx, aDistance and aSpare all point to arrays of size\n** nIdx. The aIdx array contains the set of integers from 0 to \n** (nIdx-1) in no particular order. This function sorts the values\n** in aIdx according to the indexed values in aDistance. For\n** example, assuming the inputs:\n**\n**   aIdx      = { 0,   1,   2,   3 }\n**   aDistance = { 5.0, 2.0, 7.0, 6.0 }\n**\n** this function sets the aIdx array to contain:\n**\n**   aIdx      = { 0,   1,   2,   3 }\n**\n** The aSpare array is used as temporary working space by the\n** sorting algorithm.\n*/\nstatic void SortByDistance(\n  int *aIdx, \n  int nIdx, \n  RtreeDValue *aDistance, \n  int *aSpare\n){\n  if( nIdx>1 ){\n    int iLeft = 0;\n    int iRight = 0;\n\n    int nLeft = nIdx/2;\n    int nRight = nIdx-nLeft;\n    int *aLeft = aIdx;\n    int *aRight = &aIdx[nLeft];\n\n    SortByDistance(aLeft, nLeft, aDistance, aSpare);\n    SortByDistance(aRight, nRight, aDistance, aSpare);\n\n    memcpy(aSpare, aLeft, sizeof(int)*nLeft);\n    aLeft = aSpare;\n\n    while( iLeft<nLeft || iRight<nRight ){\n      if( iLeft==nLeft ){\n        aIdx[iLeft+iRight] = aRight[iRight];\n        iRight++;\n      }else if( iRight==nRight ){\n        aIdx[iLeft+iRight] = aLeft[iLeft];\n        iLeft++;\n      }else{\n        RtreeDValue fLeft = aDistance[aLeft[iLeft]];\n        RtreeDValue fRight = aDistance[aRight[iRight]];\n        if( fLeft<fRight ){\n          aIdx[iLeft+iRight] = aLeft[iLeft];\n          iLeft++;\n        }else{\n          aIdx[iLeft+iRight] = aRight[iRight];\n          iRight++;\n        }\n      }\n    }\n\n#if 0\n    /* Check that the sort worked */\n    {\n      int jj;\n      for(jj=1; jj<nIdx; jj++){\n        RtreeDValue left = aDistance[aIdx[jj-1]];\n        RtreeDValue right = aDistance[aIdx[jj]];\n        assert( left<=right );\n      }\n    }\n#endif\n  }\n}\n\n/*\n** Arguments aIdx, aCell and aSpare all point to arrays of size\n** nIdx. The aIdx array contains the set of integers from 0 to \n** (nIdx-1) in no particular order. This function sorts the values\n** in aIdx according to dimension iDim of the cells in aCell. The\n** minimum value of dimension iDim is considered first, the\n** maximum used to break ties.\n**\n** The aSpare array is used as temporary working space by the\n** sorting algorithm.\n*/\nstatic void SortByDimension(\n  Rtree *pRtree,\n  int *aIdx, \n  int nIdx, \n  int iDim, \n  RtreeCell *aCell, \n  int *aSpare\n){\n  if( nIdx>1 ){\n\n    int iLeft = 0;\n    int iRight = 0;\n\n    int nLeft = nIdx/2;\n    int nRight = nIdx-nLeft;\n    int *aLeft = aIdx;\n    int *aRight = &aIdx[nLeft];\n\n    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);\n    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);\n\n    memcpy(aSpare, aLeft, sizeof(int)*nLeft);\n    aLeft = aSpare;\n    while( iLeft<nLeft || iRight<nRight ){\n      RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);\n      RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);\n      RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);\n      RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);\n      if( (iLeft!=nLeft) && ((iRight==nRight)\n       || (xleft1<xright1)\n       || (xleft1==xright1 && xleft2<xright2)\n      )){\n        aIdx[iLeft+iRight] = aLeft[iLeft];\n        iLeft++;\n      }else{\n        aIdx[iLeft+iRight] = aRight[iRight];\n        iRight++;\n      }\n    }\n\n#if 0\n    /* Check that the sort worked */\n    {\n      int jj;\n      for(jj=1; jj<nIdx; jj++){\n        RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];\n        RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];\n        RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];\n        RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];\n        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );\n      }\n    }\n#endif\n  }\n}\n\n/*\n** Implementation of the R*-tree variant of SplitNode from Beckman[1990].\n*/\nstatic int splitNodeStartree(\n  Rtree *pRtree,\n  RtreeCell *aCell,\n  int nCell,\n  RtreeNode *pLeft,\n  RtreeNode *pRight,\n  RtreeCell *pBboxLeft,\n  RtreeCell *pBboxRight\n){\n  int **aaSorted;\n  int *aSpare;\n  int ii;\n\n  int iBestDim = 0;\n  int iBestSplit = 0;\n  RtreeDValue fBestMargin = RTREE_ZERO;\n\n  sqlite3_int64 nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));\n\n  aaSorted = (int **)sqlite3_malloc64(nByte);\n  if( !aaSorted ){\n    return SQLITE_NOMEM;\n  }\n\n  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];\n  memset(aaSorted, 0, nByte);\n  for(ii=0; ii<pRtree->nDim; ii++){\n    int jj;\n    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];\n    for(jj=0; jj<nCell; jj++){\n      aaSorted[ii][jj] = jj;\n    }\n    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);\n  }\n\n  for(ii=0; ii<pRtree->nDim; ii++){\n    RtreeDValue margin = RTREE_ZERO;\n    RtreeDValue fBestOverlap = RTREE_ZERO;\n    RtreeDValue fBestArea = RTREE_ZERO;\n    int iBestLeft = 0;\n    int nLeft;\n\n    for(\n      nLeft=RTREE_MINCELLS(pRtree); \n      nLeft<=(nCell-RTREE_MINCELLS(pRtree)); \n      nLeft++\n    ){\n      RtreeCell left;\n      RtreeCell right;\n      int kk;\n      RtreeDValue overlap;\n      RtreeDValue area;\n\n      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));\n      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));\n      for(kk=1; kk<(nCell-1); kk++){\n        if( kk<nLeft ){\n          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);\n        }else{\n          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);\n        }\n      }\n      margin += cellMargin(pRtree, &left);\n      margin += cellMargin(pRtree, &right);\n      overlap = cellOverlap(pRtree, &left, &right, 1);\n      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);\n      if( (nLeft==RTREE_MINCELLS(pRtree))\n       || (overlap<fBestOverlap)\n       || (overlap==fBestOverlap && area<fBestArea)\n      ){\n        iBestLeft = nLeft;\n        fBestOverlap = overlap;\n        fBestArea = area;\n      }\n    }\n\n    if( ii==0 || margin<fBestMargin ){\n      iBestDim = ii;\n      fBestMargin = margin;\n      iBestSplit = iBestLeft;\n    }\n  }\n\n  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));\n  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));\n  for(ii=0; ii<nCell; ii++){\n    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;\n    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;\n    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];\n    nodeInsertCell(pRtree, pTarget, pCell);\n    cellUnion(pRtree, pBbox, pCell);\n  }\n\n  sqlite3_free(aaSorted);\n  return SQLITE_OK;\n}\n\n\nstatic int updateMapping(\n  Rtree *pRtree, \n  i64 iRowid, \n  RtreeNode *pNode, \n  int iHeight\n){\n  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);\n  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);\n  if( iHeight>0 ){\n    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);\n    if( pChild ){\n      nodeRelease(pRtree, pChild->pParent);\n      nodeReference(pNode);\n      pChild->pParent = pNode;\n    }\n  }\n  return xSetMapping(pRtree, iRowid, pNode->iNode);\n}\n\nstatic int SplitNode(\n  Rtree *pRtree,\n  RtreeNode *pNode,\n  RtreeCell *pCell,\n  int iHeight\n){\n  int i;\n  int newCellIsRight = 0;\n\n  int rc = SQLITE_OK;\n  int nCell = NCELL(pNode);\n  RtreeCell *aCell;\n  int *aiUsed;\n\n  RtreeNode *pLeft = 0;\n  RtreeNode *pRight = 0;\n\n  RtreeCell leftbbox;\n  RtreeCell rightbbox;\n\n  /* Allocate an array and populate it with a copy of pCell and \n  ** all cells from node pLeft. Then zero the original node.\n  */\n  aCell = sqlite3_malloc64((sizeof(RtreeCell)+sizeof(int))*(nCell+1));\n  if( !aCell ){\n    rc = SQLITE_NOMEM;\n    goto splitnode_out;\n  }\n  aiUsed = (int *)&aCell[nCell+1];\n  memset(aiUsed, 0, sizeof(int)*(nCell+1));\n  for(i=0; i<nCell; i++){\n    nodeGetCell(pRtree, pNode, i, &aCell[i]);\n  }\n  nodeZero(pRtree, pNode);\n  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));\n  nCell++;\n\n  if( pNode->iNode==1 ){\n    pRight = nodeNew(pRtree, pNode);\n    pLeft = nodeNew(pRtree, pNode);\n    pRtree->iDepth++;\n    pNode->isDirty = 1;\n    writeInt16(pNode->zData, pRtree->iDepth);\n  }else{\n    pLeft = pNode;\n    pRight = nodeNew(pRtree, pLeft->pParent);\n    pLeft->nRef++;\n  }\n\n  if( !pLeft || !pRight ){\n    rc = SQLITE_NOMEM;\n    goto splitnode_out;\n  }\n\n  memset(pLeft->zData, 0, pRtree->iNodeSize);\n  memset(pRight->zData, 0, pRtree->iNodeSize);\n\n  rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,\n                         &leftbbox, &rightbbox);\n  if( rc!=SQLITE_OK ){\n    goto splitnode_out;\n  }\n\n  /* Ensure both child nodes have node numbers assigned to them by calling\n  ** nodeWrite(). Node pRight always needs a node number, as it was created\n  ** by nodeNew() above. But node pLeft sometimes already has a node number.\n  ** In this case avoid the all to nodeWrite().\n  */\n  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))\n   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))\n  ){\n    goto splitnode_out;\n  }\n\n  rightbbox.iRowid = pRight->iNode;\n  leftbbox.iRowid = pLeft->iNode;\n\n  if( pNode->iNode==1 ){\n    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);\n    if( rc!=SQLITE_OK ){\n      goto splitnode_out;\n    }\n  }else{\n    RtreeNode *pParent = pLeft->pParent;\n    int iCell;\n    rc = nodeParentIndex(pRtree, pLeft, &iCell);\n    if( rc==SQLITE_OK ){\n      nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);\n      rc = AdjustTree(pRtree, pParent, &leftbbox);\n    }\n    if( rc!=SQLITE_OK ){\n      goto splitnode_out;\n    }\n  }\n  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){\n    goto splitnode_out;\n  }\n\n  for(i=0; i<NCELL(pRight); i++){\n    i64 iRowid = nodeGetRowid(pRtree, pRight, i);\n    rc = updateMapping(pRtree, iRowid, pRight, iHeight);\n    if( iRowid==pCell->iRowid ){\n      newCellIsRight = 1;\n    }\n    if( rc!=SQLITE_OK ){\n      goto splitnode_out;\n    }\n  }\n  if( pNode->iNode==1 ){\n    for(i=0; i<NCELL(pLeft); i++){\n      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);\n      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);\n      if( rc!=SQLITE_OK ){\n        goto splitnode_out;\n      }\n    }\n  }else if( newCellIsRight==0 ){\n    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = nodeRelease(pRtree, pRight);\n    pRight = 0;\n  }\n  if( rc==SQLITE_OK ){\n    rc = nodeRelease(pRtree, pLeft);\n    pLeft = 0;\n  }\n\nsplitnode_out:\n  nodeRelease(pRtree, pRight);\n  nodeRelease(pRtree, pLeft);\n  sqlite3_free(aCell);\n  return rc;\n}\n\n/*\n** If node pLeaf is not the root of the r-tree and its pParent pointer is \n** still NULL, load all ancestor nodes of pLeaf into memory and populate\n** the pLeaf->pParent chain all the way up to the root node.\n**\n** This operation is required when a row is deleted (or updated - an update\n** is implemented as a delete followed by an insert). SQLite provides the\n** rowid of the row to delete, which can be used to find the leaf on which\n** the entry resides (argument pLeaf). Once the leaf is located, this \n** function is called to determine its ancestry.\n*/\nstatic int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){\n  int rc = SQLITE_OK;\n  RtreeNode *pChild = pLeaf;\n  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){\n    int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */\n    sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);\n    rc = sqlite3_step(pRtree->pReadParent);\n    if( rc==SQLITE_ROW ){\n      RtreeNode *pTest;           /* Used to test for reference loops */\n      i64 iNode;                  /* Node number of parent node */\n\n      /* Before setting pChild->pParent, test that we are not creating a\n      ** loop of references (as we would if, say, pChild==pParent). We don't\n      ** want to do this as it leads to a memory leak when trying to delete\n      ** the referenced counted node structures.\n      */\n      iNode = sqlite3_column_int64(pRtree->pReadParent, 0);\n      for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);\n      if( !pTest ){\n        rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);\n      }\n    }\n    rc = sqlite3_reset(pRtree->pReadParent);\n    if( rc==SQLITE_OK ) rc = rc2;\n    if( rc==SQLITE_OK && !pChild->pParent ){\n      RTREE_IS_CORRUPT(pRtree);\n      rc = SQLITE_CORRUPT_VTAB;\n    }\n    pChild = pChild->pParent;\n  }\n  return rc;\n}\n\nstatic int deleteCell(Rtree *, RtreeNode *, int, int);\n\nstatic int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){\n  int rc;\n  int rc2;\n  RtreeNode *pParent = 0;\n  int iCell;\n\n  assert( pNode->nRef==1 );\n\n  /* Remove the entry in the parent cell. */\n  rc = nodeParentIndex(pRtree, pNode, &iCell);\n  if( rc==SQLITE_OK ){\n    pParent = pNode->pParent;\n    pNode->pParent = 0;\n    rc = deleteCell(pRtree, pParent, iCell, iHeight+1);\n  }\n  rc2 = nodeRelease(pRtree, pParent);\n  if( rc==SQLITE_OK ){\n    rc = rc2;\n  }\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  /* Remove the xxx_node entry. */\n  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);\n  sqlite3_step(pRtree->pDeleteNode);\n  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){\n    return rc;\n  }\n\n  /* Remove the xxx_parent entry. */\n  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);\n  sqlite3_step(pRtree->pDeleteParent);\n  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){\n    return rc;\n  }\n  \n  /* Remove the node from the in-memory hash table and link it into\n  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.\n  */\n  nodeHashDelete(pRtree, pNode);\n  pNode->iNode = iHeight;\n  pNode->pNext = pRtree->pDeleted;\n  pNode->nRef++;\n  pRtree->pDeleted = pNode;\n\n  return SQLITE_OK;\n}\n\nstatic int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){\n  RtreeNode *pParent = pNode->pParent;\n  int rc = SQLITE_OK; \n  if( pParent ){\n    int ii; \n    int nCell = NCELL(pNode);\n    RtreeCell box;                            /* Bounding box for pNode */\n    nodeGetCell(pRtree, pNode, 0, &box);\n    for(ii=1; ii<nCell; ii++){\n      RtreeCell cell;\n      nodeGetCell(pRtree, pNode, ii, &cell);\n      cellUnion(pRtree, &box, &cell);\n    }\n    box.iRowid = pNode->iNode;\n    rc = nodeParentIndex(pRtree, pNode, &ii);\n    if( rc==SQLITE_OK ){\n      nodeOverwriteCell(pRtree, pParent, &box, ii);\n      rc = fixBoundingBox(pRtree, pParent);\n    }\n  }\n  return rc;\n}\n\n/*\n** Delete the cell at index iCell of node pNode. After removing the\n** cell, adjust the r-tree data structure if required.\n*/\nstatic int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){\n  RtreeNode *pParent;\n  int rc;\n\n  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){\n    return rc;\n  }\n\n  /* Remove the cell from the node. This call just moves bytes around\n  ** the in-memory node image, so it cannot fail.\n  */\n  nodeDeleteCell(pRtree, pNode, iCell);\n\n  /* If the node is not the tree root and now has less than the minimum\n  ** number of cells, remove it from the tree. Otherwise, update the\n  ** cell in the parent node so that it tightly contains the updated\n  ** node.\n  */\n  pParent = pNode->pParent;\n  assert( pParent || pNode->iNode==1 );\n  if( pParent ){\n    if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){\n      rc = removeNode(pRtree, pNode, iHeight);\n    }else{\n      rc = fixBoundingBox(pRtree, pNode);\n    }\n  }\n\n  return rc;\n}\n\nstatic int Reinsert(\n  Rtree *pRtree, \n  RtreeNode *pNode, \n  RtreeCell *pCell, \n  int iHeight\n){\n  int *aOrder;\n  int *aSpare;\n  RtreeCell *aCell;\n  RtreeDValue *aDistance;\n  int nCell;\n  RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];\n  int iDim;\n  int ii;\n  int rc = SQLITE_OK;\n  int n;\n\n  memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);\n\n  nCell = NCELL(pNode)+1;\n  n = (nCell+1)&(~1);\n\n  /* Allocate the buffers used by this operation. The allocation is\n  ** relinquished before this function returns.\n  */\n  aCell = (RtreeCell *)sqlite3_malloc64(n * (\n    sizeof(RtreeCell)     +         /* aCell array */\n    sizeof(int)           +         /* aOrder array */\n    sizeof(int)           +         /* aSpare array */\n    sizeof(RtreeDValue)             /* aDistance array */\n  ));\n  if( !aCell ){\n    return SQLITE_NOMEM;\n  }\n  aOrder    = (int *)&aCell[n];\n  aSpare    = (int *)&aOrder[n];\n  aDistance = (RtreeDValue *)&aSpare[n];\n\n  for(ii=0; ii<nCell; ii++){\n    if( ii==(nCell-1) ){\n      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));\n    }else{\n      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);\n    }\n    aOrder[ii] = ii;\n    for(iDim=0; iDim<pRtree->nDim; iDim++){\n      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);\n      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);\n    }\n  }\n  for(iDim=0; iDim<pRtree->nDim; iDim++){\n    aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));\n  }\n\n  for(ii=0; ii<nCell; ii++){\n    aDistance[ii] = RTREE_ZERO;\n    for(iDim=0; iDim<pRtree->nDim; iDim++){\n      RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - \n                               DCOORD(aCell[ii].aCoord[iDim*2]));\n      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);\n    }\n  }\n\n  SortByDistance(aOrder, nCell, aDistance, aSpare);\n  nodeZero(pRtree, pNode);\n\n  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){\n    RtreeCell *p = &aCell[aOrder[ii]];\n    nodeInsertCell(pRtree, pNode, p);\n    if( p->iRowid==pCell->iRowid ){\n      if( iHeight==0 ){\n        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);\n      }else{\n        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);\n      }\n    }\n  }\n  if( rc==SQLITE_OK ){\n    rc = fixBoundingBox(pRtree, pNode);\n  }\n  for(; rc==SQLITE_OK && ii<nCell; ii++){\n    /* Find a node to store this cell in. pNode->iNode currently contains\n    ** the height of the sub-tree headed by the cell.\n    */\n    RtreeNode *pInsert;\n    RtreeCell *p = &aCell[aOrder[ii]];\n    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);\n    if( rc==SQLITE_OK ){\n      int rc2;\n      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);\n      rc2 = nodeRelease(pRtree, pInsert);\n      if( rc==SQLITE_OK ){\n        rc = rc2;\n      }\n    }\n  }\n\n  sqlite3_free(aCell);\n  return rc;\n}\n\n/*\n** Insert cell pCell into node pNode. Node pNode is the head of a \n** subtree iHeight high (leaf nodes have iHeight==0).\n*/\nstatic int rtreeInsertCell(\n  Rtree *pRtree,\n  RtreeNode *pNode,\n  RtreeCell *pCell,\n  int iHeight\n){\n  int rc = SQLITE_OK;\n  if( iHeight>0 ){\n    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);\n    if( pChild ){\n      nodeRelease(pRtree, pChild->pParent);\n      nodeReference(pNode);\n      pChild->pParent = pNode;\n    }\n  }\n  if( nodeInsertCell(pRtree, pNode, pCell) ){\n    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){\n      rc = SplitNode(pRtree, pNode, pCell, iHeight);\n    }else{\n      pRtree->iReinsertHeight = iHeight;\n      rc = Reinsert(pRtree, pNode, pCell, iHeight);\n    }\n  }else{\n    rc = AdjustTree(pRtree, pNode, pCell);\n    if( rc==SQLITE_OK ){\n      if( iHeight==0 ){\n        rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);\n      }else{\n        rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);\n      }\n    }\n  }\n  return rc;\n}\n\nstatic int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){\n  int ii;\n  int rc = SQLITE_OK;\n  int nCell = NCELL(pNode);\n\n  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){\n    RtreeNode *pInsert;\n    RtreeCell cell;\n    nodeGetCell(pRtree, pNode, ii, &cell);\n\n    /* Find a node to store this cell in. pNode->iNode currently contains\n    ** the height of the sub-tree headed by the cell.\n    */\n    rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);\n    if( rc==SQLITE_OK ){\n      int rc2;\n      rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);\n      rc2 = nodeRelease(pRtree, pInsert);\n      if( rc==SQLITE_OK ){\n        rc = rc2;\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** Select a currently unused rowid for a new r-tree record.\n*/\nstatic int rtreeNewRowid(Rtree *pRtree, i64 *piRowid){\n  int rc;\n  sqlite3_bind_null(pRtree->pWriteRowid, 1);\n  sqlite3_bind_null(pRtree->pWriteRowid, 2);\n  sqlite3_step(pRtree->pWriteRowid);\n  rc = sqlite3_reset(pRtree->pWriteRowid);\n  *piRowid = sqlite3_last_insert_rowid(pRtree->db);\n  return rc;\n}\n\n/*\n** Remove the entry with rowid=iDelete from the r-tree structure.\n*/\nstatic int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){\n  int rc;                         /* Return code */\n  RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */\n  int iCell;                      /* Index of iDelete cell in pLeaf */\n  RtreeNode *pRoot = 0;           /* Root node of rtree structure */\n\n\n  /* Obtain a reference to the root node to initialize Rtree.iDepth */\n  rc = nodeAcquire(pRtree, 1, 0, &pRoot);\n\n  /* Obtain a reference to the leaf node that contains the entry \n  ** about to be deleted. \n  */\n  if( rc==SQLITE_OK ){\n    rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);\n  }\n\n#ifdef CORRUPT_DB\n  assert( pLeaf!=0 || rc!=SQLITE_OK || CORRUPT_DB );\n#endif\n\n  /* Delete the cell in question from the leaf node. */\n  if( rc==SQLITE_OK && pLeaf ){\n    int rc2;\n    rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);\n    if( rc==SQLITE_OK ){\n      rc = deleteCell(pRtree, pLeaf, iCell, 0);\n    }\n    rc2 = nodeRelease(pRtree, pLeaf);\n    if( rc==SQLITE_OK ){\n      rc = rc2;\n    }\n  }\n\n  /* Delete the corresponding entry in the <rtree>_rowid table. */\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);\n    sqlite3_step(pRtree->pDeleteRowid);\n    rc = sqlite3_reset(pRtree->pDeleteRowid);\n  }\n\n  /* Check if the root node now has exactly one child. If so, remove\n  ** it, schedule the contents of the child for reinsertion and \n  ** reduce the tree height by one.\n  **\n  ** This is equivalent to copying the contents of the child into\n  ** the root node (the operation that Gutman's paper says to perform \n  ** in this scenario).\n  */\n  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){\n    int rc2;\n    RtreeNode *pChild = 0;\n    i64 iChild = nodeGetRowid(pRtree, pRoot, 0);\n    rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);\n    if( rc==SQLITE_OK ){\n      rc = removeNode(pRtree, pChild, pRtree->iDepth-1);\n    }\n    rc2 = nodeRelease(pRtree, pChild);\n    if( rc==SQLITE_OK ) rc = rc2;\n    if( rc==SQLITE_OK ){\n      pRtree->iDepth--;\n      writeInt16(pRoot->zData, pRtree->iDepth);\n      pRoot->isDirty = 1;\n    }\n  }\n\n  /* Re-insert the contents of any underfull nodes removed from the tree. */\n  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){\n    if( rc==SQLITE_OK ){\n      rc = reinsertNodeContent(pRtree, pLeaf);\n    }\n    pRtree->pDeleted = pLeaf->pNext;\n    pRtree->nNodeRef--;\n    sqlite3_free(pLeaf);\n  }\n\n  /* Release the reference to the root node. */\n  if( rc==SQLITE_OK ){\n    rc = nodeRelease(pRtree, pRoot);\n  }else{\n    nodeRelease(pRtree, pRoot);\n  }\n\n  return rc;\n}\n\n/*\n** Rounding constants for float->double conversion.\n*/\n#define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */\n#define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */\n\n#if !defined(SQLITE_RTREE_INT_ONLY)\n/*\n** Convert an sqlite3_value into an RtreeValue (presumably a float)\n** while taking care to round toward negative or positive, respectively.\n*/\nstatic RtreeValue rtreeValueDown(sqlite3_value *v){\n  double d = sqlite3_value_double(v);\n  float f = (float)d;\n  if( f>d ){\n    f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));\n  }\n  return f;\n}\nstatic RtreeValue rtreeValueUp(sqlite3_value *v){\n  double d = sqlite3_value_double(v);\n  float f = (float)d;\n  if( f<d ){\n    f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));\n  }\n  return f;\n}\n#endif /* !defined(SQLITE_RTREE_INT_ONLY) */\n\n/*\n** A constraint has failed while inserting a row into an rtree table. \n** Assuming no OOM error occurs, this function sets the error message \n** (at pRtree->base.zErrMsg) to an appropriate value and returns\n** SQLITE_CONSTRAINT.\n**\n** Parameter iCol is the index of the leftmost column involved in the\n** constraint failure. If it is 0, then the constraint that failed is\n** the unique constraint on the id column. Otherwise, it is the rtree\n** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.\n**\n** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.\n*/\nstatic int rtreeConstraintError(Rtree *pRtree, int iCol){\n  sqlite3_stmt *pStmt = 0;\n  char *zSql; \n  int rc;\n\n  assert( iCol==0 || iCol%2 );\n  zSql = sqlite3_mprintf(\"SELECT * FROM %Q.%Q\", pRtree->zDb, pRtree->zName);\n  if( zSql ){\n    rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);\n  }else{\n    rc = SQLITE_NOMEM;\n  }\n  sqlite3_free(zSql);\n\n  if( rc==SQLITE_OK ){\n    if( iCol==0 ){\n      const char *zCol = sqlite3_column_name(pStmt, 0);\n      pRtree->base.zErrMsg = sqlite3_mprintf(\n          \"UNIQUE constraint failed: %s.%s\", pRtree->zName, zCol\n      );\n    }else{\n      const char *zCol1 = sqlite3_column_name(pStmt, iCol);\n      const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);\n      pRtree->base.zErrMsg = sqlite3_mprintf(\n          \"rtree constraint failed: %s.(%s<=%s)\", pRtree->zName, zCol1, zCol2\n      );\n    }\n  }\n\n  sqlite3_finalize(pStmt);\n  return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);\n}\n\n\n\n/*\n** The xUpdate method for rtree module virtual tables.\n*/\nstatic int rtreeUpdate(\n  sqlite3_vtab *pVtab, \n  int nData, \n  sqlite3_value **aData, \n  sqlite_int64 *pRowid\n){\n  Rtree *pRtree = (Rtree *)pVtab;\n  int rc = SQLITE_OK;\n  RtreeCell cell;                 /* New cell to insert if nData>1 */\n  int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */\n\n  if( pRtree->nNodeRef ){\n    /* Unable to write to the btree while another cursor is reading from it,\n    ** since the write might do a rebalance which would disrupt the read\n    ** cursor. */\n    return SQLITE_LOCKED_VTAB;\n  }\n  rtreeReference(pRtree);\n  assert(nData>=1);\n\n  cell.iRowid = 0;  /* Used only to suppress a compiler warning */\n\n  /* Constraint handling. A write operation on an r-tree table may return\n  ** SQLITE_CONSTRAINT for two reasons:\n  **\n  **   1. A duplicate rowid value, or\n  **   2. The supplied data violates the \"x2>=x1\" constraint.\n  **\n  ** In the first case, if the conflict-handling mode is REPLACE, then\n  ** the conflicting row can be removed before proceeding. In the second\n  ** case, SQLITE_CONSTRAINT must be returned regardless of the\n  ** conflict-handling mode specified by the user.\n  */\n  if( nData>1 ){\n    int ii;\n    int nn = nData - 4;\n\n    if( nn > pRtree->nDim2 ) nn = pRtree->nDim2;\n    /* Populate the cell.aCoord[] array. The first coordinate is aData[3].\n    **\n    ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared\n    ** with \"column\" that are interpreted as table constraints.\n    ** Example:  CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));\n    ** This problem was discovered after years of use, so we silently ignore\n    ** these kinds of misdeclared tables to avoid breaking any legacy.\n    */\n\n#ifndef SQLITE_RTREE_INT_ONLY\n    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){\n      for(ii=0; ii<nn; ii+=2){\n        cell.aCoord[ii].f = rtreeValueDown(aData[ii+3]);\n        cell.aCoord[ii+1].f = rtreeValueUp(aData[ii+4]);\n        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){\n          rc = rtreeConstraintError(pRtree, ii+1);\n          goto constraint;\n        }\n      }\n    }else\n#endif\n    {\n      for(ii=0; ii<nn; ii+=2){\n        cell.aCoord[ii].i = sqlite3_value_int(aData[ii+3]);\n        cell.aCoord[ii+1].i = sqlite3_value_int(aData[ii+4]);\n        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){\n          rc = rtreeConstraintError(pRtree, ii+1);\n          goto constraint;\n        }\n      }\n    }\n\n    /* If a rowid value was supplied, check if it is already present in \n    ** the table. If so, the constraint has failed. */\n    if( sqlite3_value_type(aData[2])!=SQLITE_NULL ){\n      cell.iRowid = sqlite3_value_int64(aData[2]);\n      if( sqlite3_value_type(aData[0])==SQLITE_NULL\n       || sqlite3_value_int64(aData[0])!=cell.iRowid\n      ){\n        int steprc;\n        sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);\n        steprc = sqlite3_step(pRtree->pReadRowid);\n        rc = sqlite3_reset(pRtree->pReadRowid);\n        if( SQLITE_ROW==steprc ){\n          if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){\n            rc = rtreeDeleteRowid(pRtree, cell.iRowid);\n          }else{\n            rc = rtreeConstraintError(pRtree, 0);\n            goto constraint;\n          }\n        }\n      }\n      bHaveRowid = 1;\n    }\n  }\n\n  /* If aData[0] is not an SQL NULL value, it is the rowid of a\n  ** record to delete from the r-tree table. The following block does\n  ** just that.\n  */\n  if( sqlite3_value_type(aData[0])!=SQLITE_NULL ){\n    rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(aData[0]));\n  }\n\n  /* If the aData[] array contains more than one element, elements\n  ** (aData[2]..aData[argc-1]) contain a new record to insert into\n  ** the r-tree structure.\n  */\n  if( rc==SQLITE_OK && nData>1 ){\n    /* Insert the new record into the r-tree */\n    RtreeNode *pLeaf = 0;\n\n    /* Figure out the rowid of the new row. */\n    if( bHaveRowid==0 ){\n      rc = rtreeNewRowid(pRtree, &cell.iRowid);\n    }\n    *pRowid = cell.iRowid;\n\n    if( rc==SQLITE_OK ){\n      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);\n    }\n    if( rc==SQLITE_OK ){\n      int rc2;\n      pRtree->iReinsertHeight = -1;\n      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);\n      rc2 = nodeRelease(pRtree, pLeaf);\n      if( rc==SQLITE_OK ){\n        rc = rc2;\n      }\n    }\n    if( rc==SQLITE_OK && pRtree->nAux ){\n      sqlite3_stmt *pUp = pRtree->pWriteAux;\n      int jj;\n      sqlite3_bind_int64(pUp, 1, *pRowid);\n      for(jj=0; jj<pRtree->nAux; jj++){\n        sqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]);\n      }\n      sqlite3_step(pUp);\n      rc = sqlite3_reset(pUp);\n    }\n  }\n\nconstraint:\n  rtreeRelease(pRtree);\n  return rc;\n}\n\n/*\n** Called when a transaction starts.\n*/\nstatic int rtreeBeginTransaction(sqlite3_vtab *pVtab){\n  Rtree *pRtree = (Rtree *)pVtab;\n  assert( pRtree->inWrTrans==0 );\n  pRtree->inWrTrans++;\n  return SQLITE_OK;\n}\n\n/*\n** Called when a transaction completes (either by COMMIT or ROLLBACK).\n** The sqlite3_blob object should be released at this point.\n*/\nstatic int rtreeEndTransaction(sqlite3_vtab *pVtab){\n  Rtree *pRtree = (Rtree *)pVtab;\n  pRtree->inWrTrans = 0;\n  nodeBlobReset(pRtree);\n  return SQLITE_OK;\n}\n\n/*\n** The xRename method for rtree module virtual tables.\n*/\nstatic int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){\n  Rtree *pRtree = (Rtree *)pVtab;\n  int rc = SQLITE_NOMEM;\n  char *zSql = sqlite3_mprintf(\n    \"ALTER TABLE %Q.'%q_node'   RENAME TO \\\"%w_node\\\";\"\n    \"ALTER TABLE %Q.'%q_parent' RENAME TO \\\"%w_parent\\\";\"\n    \"ALTER TABLE %Q.'%q_rowid'  RENAME TO \\\"%w_rowid\\\";\"\n    , pRtree->zDb, pRtree->zName, zNewName \n    , pRtree->zDb, pRtree->zName, zNewName \n    , pRtree->zDb, pRtree->zName, zNewName\n  );\n  if( zSql ){\n    nodeBlobReset(pRtree);\n    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);\n    sqlite3_free(zSql);\n  }\n  return rc;\n}\n\n/*\n** The xSavepoint method.\n**\n** This module does not need to do anything to support savepoints. However,\n** it uses this hook to close any open blob handle. This is done because a \n** DROP TABLE command - which fortunately always opens a savepoint - cannot \n** succeed if there are any open blob handles. i.e. if the blob handle were\n** not closed here, the following would fail:\n**\n**   BEGIN;\n**     INSERT INTO rtree...\n**     DROP TABLE <tablename>;    -- Would fail with SQLITE_LOCKED\n**   COMMIT;\n*/\nstatic int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){\n  Rtree *pRtree = (Rtree *)pVtab;\n  u8 iwt = pRtree->inWrTrans;\n  UNUSED_PARAMETER(iSavepoint);\n  pRtree->inWrTrans = 0;\n  nodeBlobReset(pRtree);\n  pRtree->inWrTrans = iwt;\n  return SQLITE_OK;\n}\n\n/*\n** This function populates the pRtree->nRowEst variable with an estimate\n** of the number of rows in the virtual table. If possible, this is based\n** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.\n*/\nstatic int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){\n  const char *zFmt = \"SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'\";\n  char *zSql;\n  sqlite3_stmt *p;\n  int rc;\n  i64 nRow = 0;\n\n  rc = sqlite3_table_column_metadata(\n      db, pRtree->zDb, \"sqlite_stat1\",0,0,0,0,0,0\n  );\n  if( rc!=SQLITE_OK ){\n    pRtree->nRowEst = RTREE_DEFAULT_ROWEST;\n    return rc==SQLITE_ERROR ? SQLITE_OK : rc;\n  }\n  zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);\n  if( zSql==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);\n    if( rc==SQLITE_OK ){\n      if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);\n      rc = sqlite3_finalize(p);\n    }else if( rc!=SQLITE_NOMEM ){\n      rc = SQLITE_OK;\n    }\n\n    if( rc==SQLITE_OK ){\n      if( nRow==0 ){\n        pRtree->nRowEst = RTREE_DEFAULT_ROWEST;\n      }else{\n        pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);\n      }\n    }\n    sqlite3_free(zSql);\n  }\n\n  return rc;\n}\n\n\n/*\n** Return true if zName is the extension on one of the shadow tables used\n** by this module.\n*/\nstatic int rtreeShadowName(const char *zName){\n  static const char *azName[] = {\n    \"node\", \"parent\", \"rowid\"\n  };\n  unsigned int i;\n  for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){\n    if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;\n  }\n  return 0;\n}\n\nstatic sqlite3_module rtreeModule = {\n  3,                          /* iVersion */\n  rtreeCreate,                /* xCreate - create a table */\n  rtreeConnect,               /* xConnect - connect to an existing table */\n  rtreeBestIndex,             /* xBestIndex - Determine search strategy */\n  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */\n  rtreeDestroy,               /* xDestroy - Drop a table */\n  rtreeOpen,                  /* xOpen - open a cursor */\n  rtreeClose,                 /* xClose - close a cursor */\n  rtreeFilter,                /* xFilter - configure scan constraints */\n  rtreeNext,                  /* xNext - advance a cursor */\n  rtreeEof,                   /* xEof */\n  rtreeColumn,                /* xColumn - read data */\n  rtreeRowid,                 /* xRowid - read data */\n  rtreeUpdate,                /* xUpdate - write data */\n  rtreeBeginTransaction,      /* xBegin - begin transaction */\n  rtreeEndTransaction,        /* xSync - sync transaction */\n  rtreeEndTransaction,        /* xCommit - commit transaction */\n  rtreeEndTransaction,        /* xRollback - rollback transaction */\n  0,                          /* xFindFunction - function overloading */\n  rtreeRename,                /* xRename - rename the table */\n  rtreeSavepoint,             /* xSavepoint */\n  0,                          /* xRelease */\n  0,                          /* xRollbackTo */\n  rtreeShadowName             /* xShadowName */\n};\n\nstatic int rtreeSqlInit(\n  Rtree *pRtree, \n  sqlite3 *db, \n  const char *zDb, \n  const char *zPrefix, \n  int isCreate\n){\n  int rc = SQLITE_OK;\n\n  #define N_STATEMENT 8\n  static const char *azSql[N_STATEMENT] = {\n    /* Write the xxx_node table */\n    \"INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(?1, ?2)\",\n    \"DELETE FROM '%q'.'%q_node' WHERE nodeno = ?1\",\n\n    /* Read and write the xxx_rowid table */\n    \"SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = ?1\",\n    \"INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(?1, ?2)\",\n    \"DELETE FROM '%q'.'%q_rowid' WHERE rowid = ?1\",\n\n    /* Read and write the xxx_parent table */\n    \"SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = ?1\",\n    \"INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(?1, ?2)\",\n    \"DELETE FROM '%q'.'%q_parent' WHERE nodeno = ?1\"\n  };\n  sqlite3_stmt **appStmt[N_STATEMENT];\n  int i;\n  const int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;\n\n  pRtree->db = db;\n\n  if( isCreate ){\n    char *zCreate;\n    sqlite3_str *p = sqlite3_str_new(db);\n    int ii;\n    sqlite3_str_appendf(p,\n       \"CREATE TABLE \\\"%w\\\".\\\"%w_rowid\\\"(rowid INTEGER PRIMARY KEY,nodeno\",\n       zDb, zPrefix);\n    for(ii=0; ii<pRtree->nAux; ii++){\n      sqlite3_str_appendf(p,\",a%d\",ii);\n    }\n    sqlite3_str_appendf(p,\n      \");CREATE TABLE \\\"%w\\\".\\\"%w_node\\\"(nodeno INTEGER PRIMARY KEY,data);\",\n      zDb, zPrefix);\n    sqlite3_str_appendf(p,\n    \"CREATE TABLE \\\"%w\\\".\\\"%w_parent\\\"(nodeno INTEGER PRIMARY KEY,parentnode);\",\n      zDb, zPrefix);\n    sqlite3_str_appendf(p,\n       \"INSERT INTO \\\"%w\\\".\\\"%w_node\\\"VALUES(1,zeroblob(%d))\",\n       zDb, zPrefix, pRtree->iNodeSize);\n    zCreate = sqlite3_str_finish(p);\n    if( !zCreate ){\n      return SQLITE_NOMEM;\n    }\n    rc = sqlite3_exec(db, zCreate, 0, 0, 0);\n    sqlite3_free(zCreate);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n  }\n\n  appStmt[0] = &pRtree->pWriteNode;\n  appStmt[1] = &pRtree->pDeleteNode;\n  appStmt[2] = &pRtree->pReadRowid;\n  appStmt[3] = &pRtree->pWriteRowid;\n  appStmt[4] = &pRtree->pDeleteRowid;\n  appStmt[5] = &pRtree->pReadParent;\n  appStmt[6] = &pRtree->pWriteParent;\n  appStmt[7] = &pRtree->pDeleteParent;\n\n  rc = rtreeQueryStat1(db, pRtree);\n  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){\n    char *zSql;\n    const char *zFormat;\n    if( i!=3 || pRtree->nAux==0 ){\n       zFormat = azSql[i];\n    }else {\n       /* An UPSERT is very slightly slower than REPLACE, but it is needed\n       ** if there are auxiliary columns */\n       zFormat = \"INSERT INTO\\\"%w\\\".\\\"%w_rowid\\\"(rowid,nodeno)VALUES(?1,?2)\"\n                  \"ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno\";\n    }\n    zSql = sqlite3_mprintf(zFormat, zDb, zPrefix);\n    if( zSql ){\n      rc = sqlite3_prepare_v3(db, zSql, -1, f, appStmt[i], 0); \n    }else{\n      rc = SQLITE_NOMEM;\n    }\n    sqlite3_free(zSql);\n  }\n  if( pRtree->nAux ){\n    pRtree->zReadAuxSql = sqlite3_mprintf(\n       \"SELECT * FROM \\\"%w\\\".\\\"%w_rowid\\\" WHERE rowid=?1\",\n       zDb, zPrefix);\n    if( pRtree->zReadAuxSql==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      sqlite3_str *p = sqlite3_str_new(db);\n      int ii;\n      char *zSql;\n      sqlite3_str_appendf(p, \"UPDATE \\\"%w\\\".\\\"%w_rowid\\\"SET \", zDb, zPrefix);\n      for(ii=0; ii<pRtree->nAux; ii++){\n        if( ii ) sqlite3_str_append(p, \",\", 1);\n        if( ii<pRtree->nAuxNotNull ){\n          sqlite3_str_appendf(p,\"a%d=coalesce(?%d,a%d)\",ii,ii+2,ii);\n        }else{\n          sqlite3_str_appendf(p,\"a%d=?%d\",ii,ii+2);\n        }\n      }\n      sqlite3_str_appendf(p, \" WHERE rowid=?1\");\n      zSql = sqlite3_str_finish(p);\n      if( zSql==0 ){\n        rc = SQLITE_NOMEM;\n      }else{\n        rc = sqlite3_prepare_v3(db, zSql, -1, f, &pRtree->pWriteAux, 0); \n        sqlite3_free(zSql);\n      }\n    }\n  }\n\n  return rc;\n}\n\n/*\n** The second argument to this function contains the text of an SQL statement\n** that returns a single integer value. The statement is compiled and executed\n** using database connection db. If successful, the integer value returned\n** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error\n** code is returned and the value of *piVal after returning is not defined.\n*/\nstatic int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){\n  int rc = SQLITE_NOMEM;\n  if( zSql ){\n    sqlite3_stmt *pStmt = 0;\n    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);\n    if( rc==SQLITE_OK ){\n      if( SQLITE_ROW==sqlite3_step(pStmt) ){\n        *piVal = sqlite3_column_int(pStmt, 0);\n      }\n      rc = sqlite3_finalize(pStmt);\n    }\n  }\n  return rc;\n}\n\n/*\n** This function is called from within the xConnect() or xCreate() method to\n** determine the node-size used by the rtree table being created or connected\n** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.\n** Otherwise, an SQLite error code is returned.\n**\n** If this function is being called as part of an xConnect(), then the rtree\n** table already exists. In this case the node-size is determined by inspecting\n** the root node of the tree.\n**\n** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. \n** This ensures that each node is stored on a single database page. If the \n** database page-size is so large that more than RTREE_MAXCELLS entries \n** would fit in a single node, use a smaller node-size.\n*/\nstatic int getNodeSize(\n  sqlite3 *db,                    /* Database handle */\n  Rtree *pRtree,                  /* Rtree handle */\n  int isCreate,                   /* True for xCreate, false for xConnect */\n  char **pzErr                    /* OUT: Error message, if any */\n){\n  int rc;\n  char *zSql;\n  if( isCreate ){\n    int iPageSize = 0;\n    zSql = sqlite3_mprintf(\"PRAGMA %Q.page_size\", pRtree->zDb);\n    rc = getIntFromStmt(db, zSql, &iPageSize);\n    if( rc==SQLITE_OK ){\n      pRtree->iNodeSize = iPageSize-64;\n      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){\n        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;\n      }\n    }else{\n      *pzErr = sqlite3_mprintf(\"%s\", sqlite3_errmsg(db));\n    }\n  }else{\n    zSql = sqlite3_mprintf(\n        \"SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1\",\n        pRtree->zDb, pRtree->zName\n    );\n    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);\n    if( rc!=SQLITE_OK ){\n      *pzErr = sqlite3_mprintf(\"%s\", sqlite3_errmsg(db));\n    }else if( pRtree->iNodeSize<(512-64) ){\n      rc = SQLITE_CORRUPT_VTAB;\n      RTREE_IS_CORRUPT(pRtree);\n      *pzErr = sqlite3_mprintf(\"undersize RTree blobs in \\\"%q_node\\\"\",\n                               pRtree->zName);\n    }\n  }\n\n  sqlite3_free(zSql);\n  return rc;\n}\n\n/*\n** Return the length of a token\n*/\nstatic int rtreeTokenLength(const char *z){\n  int dummy = 0;\n  return sqlite3GetToken((const unsigned char*)z,&dummy);\n}\n\n/* \n** This function is the implementation of both the xConnect and xCreate\n** methods of the r-tree virtual table.\n**\n**   argv[0]   -> module name\n**   argv[1]   -> database name\n**   argv[2]   -> table name\n**   argv[...] -> column names...\n*/\nstatic int rtreeInit(\n  sqlite3 *db,                        /* Database connection */\n  void *pAux,                         /* One of the RTREE_COORD_* constants */\n  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */\n  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */\n  char **pzErr,                       /* OUT: Error message, if any */\n  int isCreate                        /* True for xCreate, false for xConnect */\n){\n  int rc = SQLITE_OK;\n  Rtree *pRtree;\n  int nDb;              /* Length of string argv[1] */\n  int nName;            /* Length of string argv[2] */\n  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);\n  sqlite3_str *pSql;\n  char *zSql;\n  int ii = 4;\n  int iErr;\n\n  const char *aErrMsg[] = {\n    0,                                                    /* 0 */\n    \"Wrong number of columns for an rtree table\",         /* 1 */\n    \"Too few columns for an rtree table\",                 /* 2 */\n    \"Too many columns for an rtree table\",                /* 3 */\n    \"Auxiliary rtree columns must be last\"                /* 4 */\n  };\n\n  assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */\n  if( argc<6 || argc>RTREE_MAX_AUX_COLUMN+3 ){\n    *pzErr = sqlite3_mprintf(\"%s\", aErrMsg[2 + (argc>=6)]);\n    return SQLITE_ERROR;\n  }\n\n  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);\n\n  /* Allocate the sqlite3_vtab structure */\n  nDb = (int)strlen(argv[1]);\n  nName = (int)strlen(argv[2]);\n  pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2);\n  if( !pRtree ){\n    return SQLITE_NOMEM;\n  }\n  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);\n  pRtree->nBusy = 1;\n  pRtree->base.pModule = &rtreeModule;\n  pRtree->zDb = (char *)&pRtree[1];\n  pRtree->zName = &pRtree->zDb[nDb+1];\n  pRtree->eCoordType = (u8)eCoordType;\n  memcpy(pRtree->zDb, argv[1], nDb);\n  memcpy(pRtree->zName, argv[2], nName);\n\n\n  /* Create/Connect to the underlying relational database schema. If\n  ** that is successful, call sqlite3_declare_vtab() to configure\n  ** the r-tree table schema.\n  */\n  pSql = sqlite3_str_new(db);\n  sqlite3_str_appendf(pSql, \"CREATE TABLE x(%.*s INT\", \n                      rtreeTokenLength(argv[3]), argv[3]);\n  for(ii=4; ii<argc; ii++){\n    const char *zArg = argv[ii];\n    if( zArg[0]=='+' ){\n      pRtree->nAux++;\n      sqlite3_str_appendf(pSql, \",%.*s\", rtreeTokenLength(zArg+1), zArg+1);\n    }else if( pRtree->nAux>0 ){\n      break;\n    }else{\n      static const char *azFormat[] = {\",%.*s REAL\", \",%.*s INT\"};\n      pRtree->nDim2++;\n      sqlite3_str_appendf(pSql, azFormat[eCoordType],\n                          rtreeTokenLength(zArg), zArg);\n    }\n  }\n  sqlite3_str_appendf(pSql, \");\");\n  zSql = sqlite3_str_finish(pSql);\n  if( !zSql ){\n    rc = SQLITE_NOMEM;\n  }else if( ii<argc ){\n    *pzErr = sqlite3_mprintf(\"%s\", aErrMsg[4]);\n    rc = SQLITE_ERROR;\n  }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){\n    *pzErr = sqlite3_mprintf(\"%s\", sqlite3_errmsg(db));\n  }\n  sqlite3_free(zSql);\n  if( rc ) goto rtreeInit_fail;\n  pRtree->nDim = pRtree->nDim2/2;\n  if( pRtree->nDim<1 ){\n    iErr = 2;\n  }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){\n    iErr = 3;\n  }else if( pRtree->nDim2 % 2 ){\n    iErr = 1;\n  }else{\n    iErr = 0;\n  }\n  if( iErr ){\n    *pzErr = sqlite3_mprintf(\"%s\", aErrMsg[iErr]);\n    goto rtreeInit_fail;\n  }\n  pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;\n\n  /* Figure out the node size to use. */\n  rc = getNodeSize(db, pRtree, isCreate, pzErr);\n  if( rc ) goto rtreeInit_fail;\n  rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);\n  if( rc ){\n    *pzErr = sqlite3_mprintf(\"%s\", sqlite3_errmsg(db));\n    goto rtreeInit_fail;\n  }\n\n  *ppVtab = (sqlite3_vtab *)pRtree;\n  return SQLITE_OK;\n\nrtreeInit_fail:\n  if( rc==SQLITE_OK ) rc = SQLITE_ERROR;\n  assert( *ppVtab==0 );\n  assert( pRtree->nBusy==1 );\n  rtreeRelease(pRtree);\n  return rc;\n}\n\n\n/*\n** Implementation of a scalar function that decodes r-tree nodes to\n** human readable strings. This can be used for debugging and analysis.\n**\n** The scalar function takes two arguments: (1) the number of dimensions\n** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing\n** an r-tree node.  For a two-dimensional r-tree structure called \"rt\", to\n** deserialize all nodes, a statement like:\n**\n**   SELECT rtreenode(2, data) FROM rt_node;\n**\n** The human readable string takes the form of a Tcl list with one\n** entry for each cell in the r-tree node. Each entry is itself a\n** list, containing the 8-byte rowid/pageno followed by the \n** <num-dimension>*2 coordinates.\n*/\nstatic void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){\n  RtreeNode node;\n  Rtree tree;\n  int ii;\n  int nData;\n  int errCode;\n  sqlite3_str *pOut;\n\n  UNUSED_PARAMETER(nArg);\n  memset(&node, 0, sizeof(RtreeNode));\n  memset(&tree, 0, sizeof(Rtree));\n  tree.nDim = (u8)sqlite3_value_int(apArg[0]);\n  if( tree.nDim<1 || tree.nDim>5 ) return;\n  tree.nDim2 = tree.nDim*2;\n  tree.nBytesPerCell = 8 + 8 * tree.nDim;\n  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);\n  nData = sqlite3_value_bytes(apArg[1]);\n  if( nData<4 ) return;\n  if( nData<NCELL(&node)*tree.nBytesPerCell ) return;\n\n  pOut = sqlite3_str_new(0);\n  for(ii=0; ii<NCELL(&node); ii++){\n    RtreeCell cell;\n    int jj;\n\n    nodeGetCell(&tree, &node, ii, &cell);\n    if( ii>0 ) sqlite3_str_append(pOut, \" \", 1);\n    sqlite3_str_appendf(pOut, \"{%lld\", cell.iRowid);\n    for(jj=0; jj<tree.nDim2; jj++){\n#ifndef SQLITE_RTREE_INT_ONLY\n      sqlite3_str_appendf(pOut, \" %g\", (double)cell.aCoord[jj].f);\n#else\n      sqlite3_str_appendf(pOut, \" %d\", cell.aCoord[jj].i);\n#endif\n    }\n    sqlite3_str_append(pOut, \"}\", 1);\n  }\n  errCode = sqlite3_str_errcode(pOut);\n  sqlite3_result_text(ctx, sqlite3_str_finish(pOut), -1, sqlite3_free);\n  sqlite3_result_error_code(ctx, errCode);\n}\n\n/* This routine implements an SQL function that returns the \"depth\" parameter\n** from the front of a blob that is an r-tree node.  For example:\n**\n**     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;\n**\n** The depth value is 0 for all nodes other than the root node, and the root\n** node always has nodeno=1, so the example above is the primary use for this\n** routine.  This routine is intended for testing and analysis only.\n*/\nstatic void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){\n  UNUSED_PARAMETER(nArg);\n  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB \n   || sqlite3_value_bytes(apArg[0])<2\n  ){\n    sqlite3_result_error(ctx, \"Invalid argument to rtreedepth()\", -1); \n  }else{\n    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);\n    sqlite3_result_int(ctx, readInt16(zBlob));\n  }\n}\n\n/*\n** Context object passed between the various routines that make up the\n** implementation of integrity-check function rtreecheck().\n*/\ntypedef struct RtreeCheck RtreeCheck;\nstruct RtreeCheck {\n  sqlite3 *db;                    /* Database handle */\n  const char *zDb;                /* Database containing rtree table */\n  const char *zTab;               /* Name of rtree table */\n  int bInt;                       /* True for rtree_i32 table */\n  int nDim;                       /* Number of dimensions for this rtree tbl */\n  sqlite3_stmt *pGetNode;         /* Statement used to retrieve nodes */\n  sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */\n  int nLeaf;                      /* Number of leaf cells in table */\n  int nNonLeaf;                   /* Number of non-leaf cells in table */\n  int rc;                         /* Return code */\n  char *zReport;                  /* Message to report */\n  int nErr;                       /* Number of lines in zReport */\n};\n\n#define RTREE_CHECK_MAX_ERROR 100\n\n/*\n** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error,\n** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code.\n*/\nstatic void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){\n  int rc = sqlite3_reset(pStmt);\n  if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc;\n}\n\n/*\n** The second and subsequent arguments to this function are a format string\n** and printf style arguments. This function formats the string and attempts\n** to compile it as an SQL statement.\n**\n** If successful, a pointer to the new SQL statement is returned. Otherwise,\n** NULL is returned and an error code left in RtreeCheck.rc.\n*/\nstatic sqlite3_stmt *rtreeCheckPrepare(\n  RtreeCheck *pCheck,             /* RtreeCheck object */\n  const char *zFmt, ...           /* Format string and trailing args */\n){\n  va_list ap;\n  char *z;\n  sqlite3_stmt *pRet = 0;\n\n  va_start(ap, zFmt);\n  z = sqlite3_vmprintf(zFmt, ap);\n\n  if( pCheck->rc==SQLITE_OK ){\n    if( z==0 ){\n      pCheck->rc = SQLITE_NOMEM;\n    }else{\n      pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0);\n    }\n  }\n\n  sqlite3_free(z);\n  va_end(ap);\n  return pRet;\n}\n\n/*\n** The second and subsequent arguments to this function are a printf()\n** style format string and arguments. This function formats the string and\n** appends it to the report being accumuated in pCheck.\n*/\nstatic void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){\n  va_list ap;\n  va_start(ap, zFmt);\n  if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){\n    char *z = sqlite3_vmprintf(zFmt, ap);\n    if( z==0 ){\n      pCheck->rc = SQLITE_NOMEM;\n    }else{\n      pCheck->zReport = sqlite3_mprintf(\"%z%s%z\", \n          pCheck->zReport, (pCheck->zReport ? \"\\n\" : \"\"), z\n      );\n      if( pCheck->zReport==0 ){\n        pCheck->rc = SQLITE_NOMEM;\n      }\n    }\n    pCheck->nErr++;\n  }\n  va_end(ap);\n}\n\n/*\n** This function is a no-op if there is already an error code stored\n** in the RtreeCheck object indicated by the first argument. NULL is\n** returned in this case.\n**\n** Otherwise, the contents of rtree table node iNode are loaded from\n** the database and copied into a buffer obtained from sqlite3_malloc().\n** If no error occurs, a pointer to the buffer is returned and (*pnNode)\n** is set to the size of the buffer in bytes.\n**\n** Or, if an error does occur, NULL is returned and an error code left\n** in the RtreeCheck object. The final value of *pnNode is undefined in\n** this case.\n*/\nstatic u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){\n  u8 *pRet = 0;                   /* Return value */\n\n  if( pCheck->rc==SQLITE_OK && pCheck->pGetNode==0 ){\n    pCheck->pGetNode = rtreeCheckPrepare(pCheck,\n        \"SELECT data FROM %Q.'%q_node' WHERE nodeno=?\", \n        pCheck->zDb, pCheck->zTab\n    );\n  }\n\n  if( pCheck->rc==SQLITE_OK ){\n    sqlite3_bind_int64(pCheck->pGetNode, 1, iNode);\n    if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){\n      int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0);\n      const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0);\n      pRet = sqlite3_malloc64(nNode);\n      if( pRet==0 ){\n        pCheck->rc = SQLITE_NOMEM;\n      }else{\n        memcpy(pRet, pNode, nNode);\n        *pnNode = nNode;\n      }\n    }\n    rtreeCheckReset(pCheck, pCheck->pGetNode);\n    if( pCheck->rc==SQLITE_OK && pRet==0 ){\n      rtreeCheckAppendMsg(pCheck, \"Node %lld missing from database\", iNode);\n    }\n  }\n\n  return pRet;\n}\n\n/*\n** This function is used to check that the %_parent (if bLeaf==0) or %_rowid\n** (if bLeaf==1) table contains a specified entry. The schemas of the\n** two tables are:\n**\n**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)\n**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)\n**\n** In both cases, this function checks that there exists an entry with\n** IPK value iKey and the second column set to iVal.\n**\n*/\nstatic void rtreeCheckMapping(\n  RtreeCheck *pCheck,             /* RtreeCheck object */\n  int bLeaf,                      /* True for a leaf cell, false for interior */\n  i64 iKey,                       /* Key for mapping */\n  i64 iVal                        /* Expected value for mapping */\n){\n  int rc;\n  sqlite3_stmt *pStmt;\n  const char *azSql[2] = {\n    \"SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1\",\n    \"SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1\"\n  };\n\n  assert( bLeaf==0 || bLeaf==1 );\n  if( pCheck->aCheckMapping[bLeaf]==0 ){\n    pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,\n        azSql[bLeaf], pCheck->zDb, pCheck->zTab\n    );\n  }\n  if( pCheck->rc!=SQLITE_OK ) return;\n\n  pStmt = pCheck->aCheckMapping[bLeaf];\n  sqlite3_bind_int64(pStmt, 1, iKey);\n  rc = sqlite3_step(pStmt);\n  if( rc==SQLITE_DONE ){\n    rtreeCheckAppendMsg(pCheck, \"Mapping (%lld -> %lld) missing from %s table\",\n        iKey, iVal, (bLeaf ? \"%_rowid\" : \"%_parent\")\n    );\n  }else if( rc==SQLITE_ROW ){\n    i64 ii = sqlite3_column_int64(pStmt, 0);\n    if( ii!=iVal ){\n      rtreeCheckAppendMsg(pCheck, \n          \"Found (%lld -> %lld) in %s table, expected (%lld -> %lld)\",\n          iKey, ii, (bLeaf ? \"%_rowid\" : \"%_parent\"), iKey, iVal\n      );\n    }\n  }\n  rtreeCheckReset(pCheck, pStmt);\n}\n\n/*\n** Argument pCell points to an array of coordinates stored on an rtree page.\n** This function checks that the coordinates are internally consistent (no\n** x1>x2 conditions) and adds an error message to the RtreeCheck object\n** if they are not.\n**\n** Additionally, if pParent is not NULL, then it is assumed to point to\n** the array of coordinates on the parent page that bound the page \n** containing pCell. In this case it is also verified that the two\n** sets of coordinates are mutually consistent and an error message added\n** to the RtreeCheck object if they are not.\n*/\nstatic void rtreeCheckCellCoord(\n  RtreeCheck *pCheck, \n  i64 iNode,                      /* Node id to use in error messages */\n  int iCell,                      /* Cell number to use in error messages */\n  u8 *pCell,                      /* Pointer to cell coordinates */\n  u8 *pParent                     /* Pointer to parent coordinates */\n){\n  RtreeCoord c1, c2;\n  RtreeCoord p1, p2;\n  int i;\n\n  for(i=0; i<pCheck->nDim; i++){\n    readCoord(&pCell[4*2*i], &c1);\n    readCoord(&pCell[4*(2*i + 1)], &c2);\n\n    /* printf(\"%e, %e\\n\", c1.u.f, c2.u.f); */\n    if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){\n      rtreeCheckAppendMsg(pCheck, \n          \"Dimension %d of cell %d on node %lld is corrupt\", i, iCell, iNode\n      );\n    }\n\n    if( pParent ){\n      readCoord(&pParent[4*2*i], &p1);\n      readCoord(&pParent[4*(2*i + 1)], &p2);\n\n      if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f) \n       || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)\n      ){\n        rtreeCheckAppendMsg(pCheck, \n            \"Dimension %d of cell %d on node %lld is corrupt relative to parent\"\n            , i, iCell, iNode\n        );\n      }\n    }\n  }\n}\n\n/*\n** Run rtreecheck() checks on node iNode, which is at depth iDepth within\n** the r-tree structure. Argument aParent points to the array of coordinates\n** that bound node iNode on the parent node.\n**\n** If any problems are discovered, an error message is appended to the\n** report accumulated in the RtreeCheck object.\n*/\nstatic void rtreeCheckNode(\n  RtreeCheck *pCheck,\n  int iDepth,                     /* Depth of iNode (0==leaf) */\n  u8 *aParent,                    /* Buffer containing parent coords */\n  i64 iNode                       /* Node to check */\n){\n  u8 *aNode = 0;\n  int nNode = 0;\n\n  assert( iNode==1 || aParent!=0 );\n  assert( pCheck->nDim>0 );\n\n  aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);\n  if( aNode ){\n    if( nNode<4 ){\n      rtreeCheckAppendMsg(pCheck, \n          \"Node %lld is too small (%d bytes)\", iNode, nNode\n      );\n    }else{\n      int nCell;                  /* Number of cells on page */\n      int i;                      /* Used to iterate through cells */\n      if( aParent==0 ){\n        iDepth = readInt16(aNode);\n        if( iDepth>RTREE_MAX_DEPTH ){\n          rtreeCheckAppendMsg(pCheck, \"Rtree depth out of range (%d)\", iDepth);\n          sqlite3_free(aNode);\n          return;\n        }\n      }\n      nCell = readInt16(&aNode[2]);\n      if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){\n        rtreeCheckAppendMsg(pCheck, \n            \"Node %lld is too small for cell count of %d (%d bytes)\", \n            iNode, nCell, nNode\n        );\n      }else{\n        for(i=0; i<nCell; i++){\n          u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)];\n          i64 iVal = readInt64(pCell);\n          rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent);\n\n          if( iDepth>0 ){\n            rtreeCheckMapping(pCheck, 0, iVal, iNode);\n            rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal);\n            pCheck->nNonLeaf++;\n          }else{\n            rtreeCheckMapping(pCheck, 1, iVal, iNode);\n            pCheck->nLeaf++;\n          }\n        }\n      }\n    }\n    sqlite3_free(aNode);\n  }\n}\n\n/*\n** The second argument to this function must be either \"_rowid\" or\n** \"_parent\". This function checks that the number of entries in the\n** %_rowid or %_parent table is exactly nExpect. If not, it adds\n** an error message to the report in the RtreeCheck object indicated\n** by the first argument.\n*/\nstatic void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){\n  if( pCheck->rc==SQLITE_OK ){\n    sqlite3_stmt *pCount;\n    pCount = rtreeCheckPrepare(pCheck, \"SELECT count(*) FROM %Q.'%q%s'\",\n        pCheck->zDb, pCheck->zTab, zTbl\n    );\n    if( pCount ){\n      if( sqlite3_step(pCount)==SQLITE_ROW ){\n        i64 nActual = sqlite3_column_int64(pCount, 0);\n        if( nActual!=nExpect ){\n          rtreeCheckAppendMsg(pCheck, \"Wrong number of entries in %%%s table\"\n              \" - expected %lld, actual %lld\" , zTbl, nExpect, nActual\n          );\n        }\n      }\n      pCheck->rc = sqlite3_finalize(pCount);\n    }\n  }\n}\n\n/*\n** This function does the bulk of the work for the rtree integrity-check.\n** It is called by rtreecheck(), which is the SQL function implementation.\n*/\nstatic int rtreeCheckTable(\n  sqlite3 *db,                    /* Database handle to access db through */\n  const char *zDb,                /* Name of db (\"main\", \"temp\" etc.) */\n  const char *zTab,               /* Name of rtree table to check */\n  char **pzReport                 /* OUT: sqlite3_malloc'd report text */\n){\n  RtreeCheck check;               /* Common context for various routines */\n  sqlite3_stmt *pStmt = 0;        /* Used to find column count of rtree table */\n  int bEnd = 0;                   /* True if transaction should be closed */\n  int nAux = 0;                   /* Number of extra columns. */\n\n  /* Initialize the context object */\n  memset(&check, 0, sizeof(check));\n  check.db = db;\n  check.zDb = zDb;\n  check.zTab = zTab;\n\n  /* If there is not already an open transaction, open one now. This is\n  ** to ensure that the queries run as part of this integrity-check operate\n  ** on a consistent snapshot.  */\n  if( sqlite3_get_autocommit(db) ){\n    check.rc = sqlite3_exec(db, \"BEGIN\", 0, 0, 0);\n    bEnd = 1;\n  }\n\n  /* Find the number of auxiliary columns */\n  if( check.rc==SQLITE_OK ){\n    pStmt = rtreeCheckPrepare(&check, \"SELECT * FROM %Q.'%q_rowid'\", zDb, zTab);\n    if( pStmt ){\n      nAux = sqlite3_column_count(pStmt) - 2;\n      sqlite3_finalize(pStmt);\n    }\n    check.rc = SQLITE_OK;\n  }\n\n  /* Find number of dimensions in the rtree table. */\n  pStmt = rtreeCheckPrepare(&check, \"SELECT * FROM %Q.%Q\", zDb, zTab);\n  if( pStmt ){\n    int rc;\n    check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2;\n    if( check.nDim<1 ){\n      rtreeCheckAppendMsg(&check, \"Schema corrupt or not an rtree\");\n    }else if( SQLITE_ROW==sqlite3_step(pStmt) ){\n      check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);\n    }\n    rc = sqlite3_finalize(pStmt);\n    if( rc!=SQLITE_CORRUPT ) check.rc = rc;\n  }\n\n  /* Do the actual integrity-check */\n  if( check.nDim>=1 ){\n    if( check.rc==SQLITE_OK ){\n      rtreeCheckNode(&check, 0, 0, 1);\n    }\n    rtreeCheckCount(&check, \"_rowid\", check.nLeaf);\n    rtreeCheckCount(&check, \"_parent\", check.nNonLeaf);\n  }\n\n  /* Finalize SQL statements used by the integrity-check */\n  sqlite3_finalize(check.pGetNode);\n  sqlite3_finalize(check.aCheckMapping[0]);\n  sqlite3_finalize(check.aCheckMapping[1]);\n\n  /* If one was opened, close the transaction */\n  if( bEnd ){\n    int rc = sqlite3_exec(db, \"END\", 0, 0, 0);\n    if( check.rc==SQLITE_OK ) check.rc = rc;\n  }\n  *pzReport = check.zReport;\n  return check.rc;\n}\n\n/*\n** Usage:\n**\n**   rtreecheck(<rtree-table>);\n**   rtreecheck(<database>, <rtree-table>);\n**\n** Invoking this SQL function runs an integrity-check on the named rtree\n** table. The integrity-check verifies the following:\n**\n**   1. For each cell in the r-tree structure (%_node table), that:\n**\n**       a) for each dimension, (coord1 <= coord2).\n**\n**       b) unless the cell is on the root node, that the cell is bounded\n**          by the parent cell on the parent node.\n**\n**       c) for leaf nodes, that there is an entry in the %_rowid \n**          table corresponding to the cell's rowid value that \n**          points to the correct node.\n**\n**       d) for cells on non-leaf nodes, that there is an entry in the \n**          %_parent table mapping from the cell's child node to the\n**          node that it resides on.\n**\n**   2. That there are the same number of entries in the %_rowid table\n**      as there are leaf cells in the r-tree structure, and that there\n**      is a leaf cell that corresponds to each entry in the %_rowid table.\n**\n**   3. That there are the same number of entries in the %_parent table\n**      as there are non-leaf cells in the r-tree structure, and that \n**      there is a non-leaf cell that corresponds to each entry in the \n**      %_parent table.\n*/\nstatic void rtreecheck(\n  sqlite3_context *ctx, \n  int nArg, \n  sqlite3_value **apArg\n){\n  if( nArg!=1 && nArg!=2 ){\n    sqlite3_result_error(ctx, \n        \"wrong number of arguments to function rtreecheck()\", -1\n    );\n  }else{\n    int rc;\n    char *zReport = 0;\n    const char *zDb = (const char*)sqlite3_value_text(apArg[0]);\n    const char *zTab;\n    if( nArg==1 ){\n      zTab = zDb;\n      zDb = \"main\";\n    }else{\n      zTab = (const char*)sqlite3_value_text(apArg[1]);\n    }\n    rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport);\n    if( rc==SQLITE_OK ){\n      sqlite3_result_text(ctx, zReport ? zReport : \"ok\", -1, SQLITE_TRANSIENT);\n    }else{\n      sqlite3_result_error_code(ctx, rc);\n    }\n    sqlite3_free(zReport);\n  }\n}\n\n/* Conditionally include the geopoly code */\n#ifdef SQLITE_ENABLE_GEOPOLY\n/************** Include geopoly.c in the middle of rtree.c *******************/\n/************** Begin file geopoly.c *****************************************/\n/*\n** 2018-05-25\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file implements an alternative R-Tree virtual table that\n** uses polygons to express the boundaries of 2-dimensional objects.\n**\n** This file is #include-ed onto the end of \"rtree.c\" so that it has\n** access to all of the R-Tree internals.\n*/\n/* #include <stdlib.h> */\n\n/* Enable -DGEOPOLY_ENABLE_DEBUG for debugging facilities */\n#ifdef GEOPOLY_ENABLE_DEBUG\n  static int geo_debug = 0;\n# define GEODEBUG(X) if(geo_debug)printf X\n#else\n# define GEODEBUG(X)\n#endif\n\n#ifndef JSON_NULL   /* The following stuff repeats things found in json1 */\n/*\n** Versions of isspace(), isalnum() and isdigit() to which it is safe\n** to pass signed char values.\n*/\n#ifdef sqlite3Isdigit\n   /* Use the SQLite core versions if this routine is part of the\n   ** SQLite amalgamation */\n#  define safe_isdigit(x)  sqlite3Isdigit(x)\n#  define safe_isalnum(x)  sqlite3Isalnum(x)\n#  define safe_isxdigit(x) sqlite3Isxdigit(x)\n#else\n   /* Use the standard library for separate compilation */\n#include <ctype.h>  /* amalgamator: keep */\n#  define safe_isdigit(x)  isdigit((unsigned char)(x))\n#  define safe_isalnum(x)  isalnum((unsigned char)(x))\n#  define safe_isxdigit(x) isxdigit((unsigned char)(x))\n#endif\n\n/*\n** Growing our own isspace() routine this way is twice as fast as\n** the library isspace() function.\n*/\nstatic const char geopolyIsSpace[] = {\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 1, 1, 0, 0, 1, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  1, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,\n};\n#define safe_isspace(x) (geopolyIsSpace[(unsigned char)x])\n#endif /* JSON NULL - back to original code */\n\n/* Compiler and version */\n#ifndef GCC_VERSION\n#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)\n# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)\n#else\n# define GCC_VERSION 0\n#endif\n#endif\n#ifndef MSVC_VERSION\n#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)\n# define MSVC_VERSION _MSC_VER\n#else\n# define MSVC_VERSION 0\n#endif\n#endif\n\n/* Datatype for coordinates\n*/\ntypedef float GeoCoord;\n\n/*\n** Internal representation of a polygon.\n**\n** The polygon consists of a sequence of vertexes.  There is a line\n** segment between each pair of vertexes, and one final segment from\n** the last vertex back to the first.  (This differs from the GeoJSON\n** standard in which the final vertex is a repeat of the first.)\n**\n** The polygon follows the right-hand rule.  The area to the right of\n** each segment is \"outside\" and the area to the left is \"inside\".\n**\n** The on-disk representation consists of a 4-byte header followed by\n** the values.  The 4-byte header is:\n**\n**      encoding    (1 byte)   0=big-endian, 1=little-endian\n**      nvertex     (3 bytes)  Number of vertexes as a big-endian integer\n**\n** Enough space is allocated for 4 coordinates, to work around over-zealous\n** warnings coming from some compiler (notably, clang). In reality, the size\n** of each GeoPoly memory allocate is adjusted as necessary so that the\n** GeoPoly.a[] array at the end is the appropriate size.\n*/\ntypedef struct GeoPoly GeoPoly;\nstruct GeoPoly {\n  int nVertex;          /* Number of vertexes */\n  unsigned char hdr[4]; /* Header for on-disk representation */\n  GeoCoord a[8];        /* 2*nVertex values. X (longitude) first, then Y */\n};\n\n/* The size of a memory allocation needed for a GeoPoly object sufficient\n** to hold N coordinate pairs.\n*/\n#define GEOPOLY_SZ(N)  (sizeof(GeoPoly) + sizeof(GeoCoord)*2*((N)-4))\n\n/* Macros to access coordinates of a GeoPoly.\n** We have to use these macros, rather than just say p->a[i] in order\n** to silence (incorrect) UBSAN warnings if the array index is too large.\n*/\n#define GeoX(P,I)  (((GeoCoord*)(P)->a)[(I)*2])\n#define GeoY(P,I)  (((GeoCoord*)(P)->a)[(I)*2+1])\n\n\n/*\n** State of a parse of a GeoJSON input.\n*/\ntypedef struct GeoParse GeoParse;\nstruct GeoParse {\n  const unsigned char *z;   /* Unparsed input */\n  int nVertex;              /* Number of vertexes in a[] */\n  int nAlloc;               /* Space allocated to a[] */\n  int nErr;                 /* Number of errors encountered */\n  GeoCoord *a;          /* Array of vertexes.  From sqlite3_malloc64() */\n};\n\n/* Do a 4-byte byte swap */\nstatic void geopolySwab32(unsigned char *a){\n  unsigned char t = a[0];\n  a[0] = a[3];\n  a[3] = t;\n  t = a[1];\n  a[1] = a[2];\n  a[2] = t;\n}\n\n/* Skip whitespace.  Return the next non-whitespace character. */\nstatic char geopolySkipSpace(GeoParse *p){\n  while( safe_isspace(p->z[0]) ) p->z++;\n  return p->z[0];\n}\n\n/* Parse out a number.  Write the value into *pVal if pVal!=0.\n** return non-zero on success and zero if the next token is not a number.\n*/\nstatic int geopolyParseNumber(GeoParse *p, GeoCoord *pVal){\n  char c = geopolySkipSpace(p);\n  const unsigned char *z = p->z;\n  int j = 0;\n  int seenDP = 0;\n  int seenE = 0;\n  if( c=='-' ){\n    j = 1;\n    c = z[j];\n  }\n  if( c=='0' && z[j+1]>='0' && z[j+1]<='9' ) return 0;\n  for(;; j++){\n    c = z[j];\n    if( safe_isdigit(c) ) continue;\n    if( c=='.' ){\n      if( z[j-1]=='-' ) return 0;\n      if( seenDP ) return 0;\n      seenDP = 1;\n      continue;\n    }\n    if( c=='e' || c=='E' ){\n      if( z[j-1]<'0' ) return 0;\n      if( seenE ) return -1;\n      seenDP = seenE = 1;\n      c = z[j+1];\n      if( c=='+' || c=='-' ){\n        j++;\n        c = z[j+1];\n      }\n      if( c<'0' || c>'9' ) return 0;\n      continue;\n    }\n    break;\n  }\n  if( z[j-1]<'0' ) return 0;\n  if( pVal ){\n#ifdef SQLITE_AMALGAMATION\n     /* The sqlite3AtoF() routine is much much faster than atof(), if it\n     ** is available */\n     double r;\n     (void)sqlite3AtoF((const char*)p->z, &r, j, SQLITE_UTF8);\n     *pVal = r;\n#else\n     *pVal = (GeoCoord)atof((const char*)p->z);\n#endif\n  }\n  p->z += j;\n  return 1;\n}\n\n/*\n** If the input is a well-formed JSON array of coordinates with at least\n** four coordinates and where each coordinate is itself a two-value array,\n** then convert the JSON into a GeoPoly object and return a pointer to\n** that object.\n**\n** If any error occurs, return NULL.\n*/\nstatic GeoPoly *geopolyParseJson(const unsigned char *z, int *pRc){\n  GeoParse s;\n  int rc = SQLITE_OK;\n  memset(&s, 0, sizeof(s));\n  s.z = z;\n  if( geopolySkipSpace(&s)=='[' ){\n    s.z++;\n    while( geopolySkipSpace(&s)=='[' ){\n      int ii = 0;\n      char c;\n      s.z++;\n      if( s.nVertex>=s.nAlloc ){\n        GeoCoord *aNew;\n        s.nAlloc = s.nAlloc*2 + 16;\n        aNew = sqlite3_realloc64(s.a, s.nAlloc*sizeof(GeoCoord)*2 );\n        if( aNew==0 ){\n          rc = SQLITE_NOMEM;\n          s.nErr++;\n          break;\n        }\n        s.a = aNew;\n      }\n      while( geopolyParseNumber(&s, ii<=1 ? &s.a[s.nVertex*2+ii] : 0) ){\n        ii++;\n        if( ii==2 ) s.nVertex++;\n        c = geopolySkipSpace(&s);\n        s.z++;\n        if( c==',' ) continue;\n        if( c==']' && ii>=2 ) break;\n        s.nErr++;\n        rc = SQLITE_ERROR;\n        goto parse_json_err;\n      }\n      if( geopolySkipSpace(&s)==',' ){\n        s.z++;\n        continue;\n      }\n      break;\n    }\n    if( geopolySkipSpace(&s)==']'\n     && s.nVertex>=4\n     && s.a[0]==s.a[s.nVertex*2-2]\n     && s.a[1]==s.a[s.nVertex*2-1]\n     && (s.z++, geopolySkipSpace(&s)==0)\n    ){\n      GeoPoly *pOut;\n      int x = 1;\n      s.nVertex--;  /* Remove the redundant vertex at the end */\n      pOut = sqlite3_malloc64( GEOPOLY_SZ((sqlite3_int64)s.nVertex) );\n      x = 1;\n      if( pOut==0 ) goto parse_json_err;\n      pOut->nVertex = s.nVertex;\n      memcpy(pOut->a, s.a, s.nVertex*2*sizeof(GeoCoord));\n      pOut->hdr[0] = *(unsigned char*)&x;\n      pOut->hdr[1] = (s.nVertex>>16)&0xff;\n      pOut->hdr[2] = (s.nVertex>>8)&0xff;\n      pOut->hdr[3] = s.nVertex&0xff;\n      sqlite3_free(s.a);\n      if( pRc ) *pRc = SQLITE_OK;\n      return pOut;\n    }else{\n      s.nErr++;\n      rc = SQLITE_ERROR;\n    }\n  }\nparse_json_err:\n  if( pRc ) *pRc = rc;\n  sqlite3_free(s.a);\n  return 0;\n}\n\n/*\n** Given a function parameter, try to interpret it as a polygon, either\n** in the binary format or JSON text.  Compute a GeoPoly object and\n** return a pointer to that object.  Or if the input is not a well-formed\n** polygon, put an error message in sqlite3_context and return NULL.\n*/\nstatic GeoPoly *geopolyFuncParam(\n  sqlite3_context *pCtx,      /* Context for error messages */\n  sqlite3_value *pVal,        /* The value to decode */\n  int *pRc                    /* Write error here */\n){\n  GeoPoly *p = 0;\n  int nByte;\n  if( sqlite3_value_type(pVal)==SQLITE_BLOB\n   && (nByte = sqlite3_value_bytes(pVal))>=(4+6*sizeof(GeoCoord))\n  ){\n    const unsigned char *a = sqlite3_value_blob(pVal);\n    int nVertex;\n    nVertex = (a[1]<<16) + (a[2]<<8) + a[3];\n    if( (a[0]==0 || a[0]==1)\n     && (nVertex*2*sizeof(GeoCoord) + 4)==(unsigned int)nByte\n    ){\n      p = sqlite3_malloc64( sizeof(*p) + (nVertex-1)*2*sizeof(GeoCoord) );\n      if( p==0 ){\n        if( pRc ) *pRc = SQLITE_NOMEM;\n        if( pCtx ) sqlite3_result_error_nomem(pCtx);\n      }else{\n        int x = 1;\n        p->nVertex = nVertex;\n        memcpy(p->hdr, a, nByte);\n        if( a[0] != *(unsigned char*)&x ){\n          int ii;\n          for(ii=0; ii<nVertex; ii++){\n            geopolySwab32((unsigned char*)&GeoX(p,ii));\n            geopolySwab32((unsigned char*)&GeoY(p,ii));\n          }\n          p->hdr[0] ^= 1;\n        }\n      }\n    }\n    if( pRc ) *pRc = SQLITE_OK;\n    return p;\n  }else if( sqlite3_value_type(pVal)==SQLITE_TEXT ){\n    const unsigned char *zJson = sqlite3_value_text(pVal);\n    if( zJson==0 ){\n      if( pRc ) *pRc = SQLITE_NOMEM;\n      return 0;\n    }\n    return geopolyParseJson(zJson, pRc);\n  }else{\n    if( pRc ) *pRc = SQLITE_ERROR;\n    return 0;\n  }\n}\n\n/*\n** Implementation of the geopoly_blob(X) function.\n**\n** If the input is a well-formed Geopoly BLOB or JSON string\n** then return the BLOB representation of the polygon.  Otherwise\n** return NULL.\n*/\nstatic void geopolyBlobFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  GeoPoly *p = geopolyFuncParam(context, argv[0], 0);\n  if( p ){\n    sqlite3_result_blob(context, p->hdr, \n       4+8*p->nVertex, SQLITE_TRANSIENT);\n    sqlite3_free(p);\n  }\n}\n\n/*\n** SQL function:     geopoly_json(X)\n**\n** Interpret X as a polygon and render it as a JSON array\n** of coordinates.  Or, if X is not a valid polygon, return NULL.\n*/\nstatic void geopolyJsonFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  GeoPoly *p = geopolyFuncParam(context, argv[0], 0);\n  if( p ){\n    sqlite3 *db = sqlite3_context_db_handle(context);\n    sqlite3_str *x = sqlite3_str_new(db);\n    int i;\n    sqlite3_str_append(x, \"[\", 1);\n    for(i=0; i<p->nVertex; i++){\n      sqlite3_str_appendf(x, \"[%!g,%!g],\", GeoX(p,i), GeoY(p,i));\n    }\n    sqlite3_str_appendf(x, \"[%!g,%!g]]\", GeoX(p,0), GeoY(p,0));\n    sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);\n    sqlite3_free(p);\n  }\n}\n\n/*\n** SQL function:     geopoly_svg(X, ....)\n**\n** Interpret X as a polygon and render it as a SVG <polyline>.\n** Additional arguments are added as attributes to the <polyline>.\n*/\nstatic void geopolySvgFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  GeoPoly *p;\n  if( argc<1 ) return;\n  p = geopolyFuncParam(context, argv[0], 0);\n  if( p ){\n    sqlite3 *db = sqlite3_context_db_handle(context);\n    sqlite3_str *x = sqlite3_str_new(db);\n    int i;\n    char cSep = '\\'';\n    sqlite3_str_appendf(x, \"<polyline points=\");\n    for(i=0; i<p->nVertex; i++){\n      sqlite3_str_appendf(x, \"%c%g,%g\", cSep, GeoX(p,i), GeoY(p,i));\n      cSep = ' ';\n    }\n    sqlite3_str_appendf(x, \" %g,%g'\", GeoX(p,0), GeoY(p,0));\n    for(i=1; i<argc; i++){\n      const char *z = (const char*)sqlite3_value_text(argv[i]);\n      if( z && z[0] ){\n        sqlite3_str_appendf(x, \" %s\", z);\n      }\n    }\n    sqlite3_str_appendf(x, \"></polyline>\");\n    sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);\n    sqlite3_free(p);\n  }\n}\n\n/*\n** SQL Function:      geopoly_xform(poly, A, B, C, D, E, F)\n**\n** Transform and/or translate a polygon as follows:\n**\n**      x1 = A*x0 + B*y0 + E\n**      y1 = C*x0 + D*y0 + F\n**\n** For a translation:\n**\n**      geopoly_xform(poly, 1, 0, 0, 1, x-offset, y-offset)\n**\n** Rotate by R around the point (0,0):\n**\n**      geopoly_xform(poly, cos(R), sin(R), -sin(R), cos(R), 0, 0)\n*/\nstatic void geopolyXformFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  GeoPoly *p = geopolyFuncParam(context, argv[0], 0);\n  double A = sqlite3_value_double(argv[1]);\n  double B = sqlite3_value_double(argv[2]);\n  double C = sqlite3_value_double(argv[3]);\n  double D = sqlite3_value_double(argv[4]);\n  double E = sqlite3_value_double(argv[5]);\n  double F = sqlite3_value_double(argv[6]);\n  GeoCoord x1, y1, x0, y0;\n  int ii;\n  if( p ){\n    for(ii=0; ii<p->nVertex; ii++){\n      x0 = GeoX(p,ii);\n      y0 = GeoY(p,ii);\n      x1 = (GeoCoord)(A*x0 + B*y0 + E);\n      y1 = (GeoCoord)(C*x0 + D*y0 + F);\n      GeoX(p,ii) = x1;\n      GeoY(p,ii) = y1;\n    }\n    sqlite3_result_blob(context, p->hdr, \n       4+8*p->nVertex, SQLITE_TRANSIENT);\n    sqlite3_free(p);\n  }\n}\n\n/*\n** Compute the area enclosed by the polygon.\n**\n** This routine can also be used to detect polygons that rotate in\n** the wrong direction.  Polygons are suppose to be counter-clockwise (CCW).\n** This routine returns a negative value for clockwise (CW) polygons.\n*/\nstatic double geopolyArea(GeoPoly *p){\n  double rArea = 0.0;\n  int ii;\n  for(ii=0; ii<p->nVertex-1; ii++){\n    rArea += (GeoX(p,ii) - GeoX(p,ii+1))           /* (x0 - x1) */\n              * (GeoY(p,ii) + GeoY(p,ii+1))        /* (y0 + y1) */\n              * 0.5;\n  }\n  rArea += (GeoX(p,ii) - GeoX(p,0))                /* (xN - x0) */\n           * (GeoY(p,ii) + GeoY(p,0))              /* (yN + y0) */\n           * 0.5;\n  return rArea;\n}\n\n/*\n** Implementation of the geopoly_area(X) function.\n**\n** If the input is a well-formed Geopoly BLOB then return the area\n** enclosed by the polygon.  If the polygon circulates clockwise instead\n** of counterclockwise (as it should) then return the negative of the\n** enclosed area.  Otherwise return NULL.\n*/\nstatic void geopolyAreaFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  GeoPoly *p = geopolyFuncParam(context, argv[0], 0);\n  if( p ){\n    sqlite3_result_double(context, geopolyArea(p));\n    sqlite3_free(p);\n  }            \n}\n\n/*\n** Implementation of the geopoly_ccw(X) function.\n**\n** If the rotation of polygon X is clockwise (incorrect) instead of\n** counter-clockwise (the correct winding order according to RFC7946)\n** then reverse the order of the vertexes in polygon X.  \n**\n** In other words, this routine returns a CCW polygon regardless of the\n** winding order of its input.\n**\n** Use this routine to sanitize historical inputs that that sometimes\n** contain polygons that wind in the wrong direction.\n*/\nstatic void geopolyCcwFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  GeoPoly *p = geopolyFuncParam(context, argv[0], 0);\n  if( p ){\n    if( geopolyArea(p)<0.0 ){\n      int ii, jj;\n      for(ii=1, jj=p->nVertex-1; ii<jj; ii++, jj--){\n        GeoCoord t = GeoX(p,ii);\n        GeoX(p,ii) = GeoX(p,jj);\n        GeoX(p,jj) = t;\n        t = GeoY(p,ii);\n        GeoY(p,ii) = GeoY(p,jj);\n        GeoY(p,jj) = t;\n      }\n    }\n    sqlite3_result_blob(context, p->hdr, \n       4+8*p->nVertex, SQLITE_TRANSIENT);\n    sqlite3_free(p);\n  }            \n}\n\n#define GEOPOLY_PI 3.1415926535897932385\n\n/* Fast approximation for sine(X) for X between -0.5*pi and 2*pi\n*/\nstatic double geopolySine(double r){\n  assert( r>=-0.5*GEOPOLY_PI && r<=2.0*GEOPOLY_PI );\n  if( r>=1.5*GEOPOLY_PI ){\n    r -= 2.0*GEOPOLY_PI;\n  }\n  if( r>=0.5*GEOPOLY_PI ){\n    return -geopolySine(r-GEOPOLY_PI);\n  }else{\n    double r2 = r*r;\n    double r3 = r2*r;\n    double r5 = r3*r2;\n    return 0.9996949*r - 0.1656700*r3 + 0.0075134*r5;\n  }\n}\n\n/*\n** Function:   geopoly_regular(X,Y,R,N)\n**\n** Construct a simple, convex, regular polygon centered at X, Y\n** with circumradius R and with N sides.\n*/\nstatic void geopolyRegularFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  double x = sqlite3_value_double(argv[0]);\n  double y = sqlite3_value_double(argv[1]);\n  double r = sqlite3_value_double(argv[2]);\n  int n = sqlite3_value_int(argv[3]);\n  int i;\n  GeoPoly *p;\n\n  if( n<3 || r<=0.0 ) return;\n  if( n>1000 ) n = 1000;\n  p = sqlite3_malloc64( sizeof(*p) + (n-1)*2*sizeof(GeoCoord) );\n  if( p==0 ){\n    sqlite3_result_error_nomem(context);\n    return;\n  }\n  i = 1;\n  p->hdr[0] = *(unsigned char*)&i;\n  p->hdr[1] = 0;\n  p->hdr[2] = (n>>8)&0xff;\n  p->hdr[3] = n&0xff;\n  for(i=0; i<n; i++){\n    double rAngle = 2.0*GEOPOLY_PI*i/n;\n    GeoX(p,i) = x - r*geopolySine(rAngle-0.5*GEOPOLY_PI);\n    GeoY(p,i) = y + r*geopolySine(rAngle);\n  }\n  sqlite3_result_blob(context, p->hdr, 4+8*n, SQLITE_TRANSIENT);\n  sqlite3_free(p);\n}\n\n/*\n** If pPoly is a polygon, compute its bounding box. Then:\n**\n**    (1) if aCoord!=0 store the bounding box in aCoord, returning NULL\n**    (2) otherwise, compute a GeoPoly for the bounding box and return the\n**        new GeoPoly\n**\n** If pPoly is NULL but aCoord is not NULL, then compute a new GeoPoly from\n** the bounding box in aCoord and return a pointer to that GeoPoly.\n*/\nstatic GeoPoly *geopolyBBox(\n  sqlite3_context *context,   /* For recording the error */\n  sqlite3_value *pPoly,       /* The polygon */\n  RtreeCoord *aCoord,         /* Results here */\n  int *pRc                    /* Error code here */\n){\n  GeoPoly *pOut = 0;\n  GeoPoly *p;\n  float mnX, mxX, mnY, mxY;\n  if( pPoly==0 && aCoord!=0 ){\n    p = 0;\n    mnX = aCoord[0].f;\n    mxX = aCoord[1].f;\n    mnY = aCoord[2].f;\n    mxY = aCoord[3].f;\n    goto geopolyBboxFill;\n  }else{\n    p = geopolyFuncParam(context, pPoly, pRc);\n  }\n  if( p ){\n    int ii;\n    mnX = mxX = GeoX(p,0);\n    mnY = mxY = GeoY(p,0);\n    for(ii=1; ii<p->nVertex; ii++){\n      double r = GeoX(p,ii);\n      if( r<mnX ) mnX = (float)r;\n      else if( r>mxX ) mxX = (float)r;\n      r = GeoY(p,ii);\n      if( r<mnY ) mnY = (float)r;\n      else if( r>mxY ) mxY = (float)r;\n    }\n    if( pRc ) *pRc = SQLITE_OK;\n    if( aCoord==0 ){\n      geopolyBboxFill:\n      pOut = sqlite3_realloc64(p, GEOPOLY_SZ(4));\n      if( pOut==0 ){\n        sqlite3_free(p);\n        if( context ) sqlite3_result_error_nomem(context);\n        if( pRc ) *pRc = SQLITE_NOMEM;\n        return 0;\n      }\n      pOut->nVertex = 4;\n      ii = 1;\n      pOut->hdr[0] = *(unsigned char*)&ii;\n      pOut->hdr[1] = 0;\n      pOut->hdr[2] = 0;\n      pOut->hdr[3] = 4;\n      GeoX(pOut,0) = mnX;\n      GeoY(pOut,0) = mnY;\n      GeoX(pOut,1) = mxX;\n      GeoY(pOut,1) = mnY;\n      GeoX(pOut,2) = mxX;\n      GeoY(pOut,2) = mxY;\n      GeoX(pOut,3) = mnX;\n      GeoY(pOut,3) = mxY;\n    }else{\n      sqlite3_free(p);\n      aCoord[0].f = mnX;\n      aCoord[1].f = mxX;\n      aCoord[2].f = mnY;\n      aCoord[3].f = mxY;\n    }\n  }\n  return pOut;\n}\n\n/*\n** Implementation of the geopoly_bbox(X) SQL function.\n*/\nstatic void geopolyBBoxFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  GeoPoly *p = geopolyBBox(context, argv[0], 0, 0);\n  if( p ){\n    sqlite3_result_blob(context, p->hdr, \n       4+8*p->nVertex, SQLITE_TRANSIENT);\n    sqlite3_free(p);\n  }\n}\n\n/*\n** State vector for the geopoly_group_bbox() aggregate function.\n*/\ntypedef struct GeoBBox GeoBBox;\nstruct GeoBBox {\n  int isInit;\n  RtreeCoord a[4];\n};\n\n\n/*\n** Implementation of the geopoly_group_bbox(X) aggregate SQL function.\n*/\nstatic void geopolyBBoxStep(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  RtreeCoord a[4];\n  int rc = SQLITE_OK;\n  (void)geopolyBBox(context, argv[0], a, &rc);\n  if( rc==SQLITE_OK ){\n    GeoBBox *pBBox;\n    pBBox = (GeoBBox*)sqlite3_aggregate_context(context, sizeof(*pBBox));\n    if( pBBox==0 ) return;\n    if( pBBox->isInit==0 ){\n      pBBox->isInit = 1;\n      memcpy(pBBox->a, a, sizeof(RtreeCoord)*4);\n    }else{\n      if( a[0].f < pBBox->a[0].f ) pBBox->a[0] = a[0];\n      if( a[1].f > pBBox->a[1].f ) pBBox->a[1] = a[1];\n      if( a[2].f < pBBox->a[2].f ) pBBox->a[2] = a[2];\n      if( a[3].f > pBBox->a[3].f ) pBBox->a[3] = a[3];\n    }\n  }\n}\nstatic void geopolyBBoxFinal(\n  sqlite3_context *context\n){\n  GeoPoly *p;\n  GeoBBox *pBBox;\n  pBBox = (GeoBBox*)sqlite3_aggregate_context(context, 0);\n  if( pBBox==0 ) return;\n  p = geopolyBBox(context, 0, pBBox->a, 0);\n  if( p ){\n    sqlite3_result_blob(context, p->hdr, \n       4+8*p->nVertex, SQLITE_TRANSIENT);\n    sqlite3_free(p);\n  }\n}\n\n\n/*\n** Determine if point (x0,y0) is beneath line segment (x1,y1)->(x2,y2).\n** Returns:\n**\n**    +2  x0,y0 is on the line segement\n**\n**    +1  x0,y0 is beneath line segment\n**\n**    0   x0,y0 is not on or beneath the line segment or the line segment\n**        is vertical and x0,y0 is not on the line segment\n**\n** The left-most coordinate min(x1,x2) is not considered to be part of\n** the line segment for the purposes of this analysis.\n*/\nstatic int pointBeneathLine(\n  double x0, double y0,\n  double x1, double y1,\n  double x2, double y2\n){\n  double y;\n  if( x0==x1 && y0==y1 ) return 2;\n  if( x1<x2 ){\n    if( x0<=x1 || x0>x2 ) return 0;\n  }else if( x1>x2 ){\n    if( x0<=x2 || x0>x1 ) return 0;\n  }else{\n    /* Vertical line segment */\n    if( x0!=x1 ) return 0;\n    if( y0<y1 && y0<y2 ) return 0;\n    if( y0>y1 && y0>y2 ) return 0;\n    return 2;\n  }\n  y = y1 + (y2-y1)*(x0-x1)/(x2-x1);\n  if( y0==y ) return 2;\n  if( y0<y ) return 1;\n  return 0;\n}\n\n/*\n** SQL function:    geopoly_contains_point(P,X,Y)\n**\n** Return +2 if point X,Y is within polygon P.\n** Return +1 if point X,Y is on the polygon boundary.\n** Return 0 if point X,Y is outside the polygon\n*/\nstatic void geopolyContainsPointFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);\n  double x0 = sqlite3_value_double(argv[1]);\n  double y0 = sqlite3_value_double(argv[2]);\n  int v = 0;\n  int cnt = 0;\n  int ii;\n  if( p1==0 ) return;\n  for(ii=0; ii<p1->nVertex-1; ii++){\n    v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii),\n                               GeoX(p1,ii+1),GeoY(p1,ii+1));\n    if( v==2 ) break;\n    cnt += v;\n  }\n  if( v!=2 ){\n    v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii),\n                               GeoX(p1,0),  GeoY(p1,0));\n  }\n  if( v==2 ){\n    sqlite3_result_int(context, 1);\n  }else if( ((v+cnt)&1)==0 ){\n    sqlite3_result_int(context, 0);\n  }else{\n    sqlite3_result_int(context, 2);\n  }\n  sqlite3_free(p1);\n}\n\n/* Forward declaration */\nstatic int geopolyOverlap(GeoPoly *p1, GeoPoly *p2);\n\n/*\n** SQL function:    geopoly_within(P1,P2)\n**\n** Return +2 if P1 and P2 are the same polygon\n** Return +1 if P2 is contained within P1\n** Return 0 if any part of P2 is on the outside of P1\n**\n*/\nstatic void geopolyWithinFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);\n  GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0);\n  if( p1 && p2 ){\n    int x = geopolyOverlap(p1, p2);\n    if( x<0 ){\n      sqlite3_result_error_nomem(context);\n    }else{\n      sqlite3_result_int(context, x==2 ? 1 : x==4 ? 2 : 0);\n    }\n  }\n  sqlite3_free(p1);\n  sqlite3_free(p2);\n}\n\n/* Objects used by the overlap algorihm. */\ntypedef struct GeoEvent GeoEvent;\ntypedef struct GeoSegment GeoSegment;\ntypedef struct GeoOverlap GeoOverlap;\nstruct GeoEvent {\n  double x;              /* X coordinate at which event occurs */\n  int eType;             /* 0 for ADD, 1 for REMOVE */\n  GeoSegment *pSeg;      /* The segment to be added or removed */\n  GeoEvent *pNext;       /* Next event in the sorted list */\n};\nstruct GeoSegment {\n  double C, B;           /* y = C*x + B */\n  double y;              /* Current y value */\n  float y0;              /* Initial y value */\n  unsigned char side;    /* 1 for p1, 2 for p2 */\n  unsigned int idx;      /* Which segment within the side */\n  GeoSegment *pNext;     /* Next segment in a list sorted by y */\n};\nstruct GeoOverlap {\n  GeoEvent *aEvent;          /* Array of all events */\n  GeoSegment *aSegment;      /* Array of all segments */\n  int nEvent;                /* Number of events */\n  int nSegment;              /* Number of segments */\n};\n\n/*\n** Add a single segment and its associated events.\n*/\nstatic void geopolyAddOneSegment(\n  GeoOverlap *p,\n  GeoCoord x0,\n  GeoCoord y0,\n  GeoCoord x1,\n  GeoCoord y1,\n  unsigned char side,\n  unsigned int idx\n){\n  GeoSegment *pSeg;\n  GeoEvent *pEvent;\n  if( x0==x1 ) return;  /* Ignore vertical segments */\n  if( x0>x1 ){\n    GeoCoord t = x0;\n    x0 = x1;\n    x1 = t;\n    t = y0;\n    y0 = y1;\n    y1 = t;\n  }\n  pSeg = p->aSegment + p->nSegment;\n  p->nSegment++;\n  pSeg->C = (y1-y0)/(x1-x0);\n  pSeg->B = y1 - x1*pSeg->C;\n  pSeg->y0 = y0;\n  pSeg->side = side;\n  pSeg->idx = idx;\n  pEvent = p->aEvent + p->nEvent;\n  p->nEvent++;\n  pEvent->x = x0;\n  pEvent->eType = 0;\n  pEvent->pSeg = pSeg;\n  pEvent = p->aEvent + p->nEvent;\n  p->nEvent++;\n  pEvent->x = x1;\n  pEvent->eType = 1;\n  pEvent->pSeg = pSeg;\n}\n  \n\n\n/*\n** Insert all segments and events for polygon pPoly.\n*/\nstatic void geopolyAddSegments(\n  GeoOverlap *p,          /* Add segments to this Overlap object */\n  GeoPoly *pPoly,         /* Take all segments from this polygon */\n  unsigned char side      /* The side of pPoly */\n){\n  unsigned int i;\n  GeoCoord *x;\n  for(i=0; i<(unsigned)pPoly->nVertex-1; i++){\n    x = &GeoX(pPoly,i);\n    geopolyAddOneSegment(p, x[0], x[1], x[2], x[3], side, i);\n  }\n  x = &GeoX(pPoly,i);\n  geopolyAddOneSegment(p, x[0], x[1], pPoly->a[0], pPoly->a[1], side, i);\n}\n\n/*\n** Merge two lists of sorted events by X coordinate\n*/\nstatic GeoEvent *geopolyEventMerge(GeoEvent *pLeft, GeoEvent *pRight){\n  GeoEvent head, *pLast;\n  head.pNext = 0;\n  pLast = &head;\n  while( pRight && pLeft ){\n    if( pRight->x <= pLeft->x ){\n      pLast->pNext = pRight;\n      pLast = pRight;\n      pRight = pRight->pNext;\n    }else{\n      pLast->pNext = pLeft;\n      pLast = pLeft;\n      pLeft = pLeft->pNext;\n    }\n  }\n  pLast->pNext = pRight ? pRight : pLeft;\n  return head.pNext;  \n}\n\n/*\n** Sort an array of nEvent event objects into a list.\n*/\nstatic GeoEvent *geopolySortEventsByX(GeoEvent *aEvent, int nEvent){\n  int mx = 0;\n  int i, j;\n  GeoEvent *p;\n  GeoEvent *a[50];\n  for(i=0; i<nEvent; i++){\n    p = &aEvent[i];\n    p->pNext = 0;\n    for(j=0; j<mx && a[j]; j++){\n      p = geopolyEventMerge(a[j], p);\n      a[j] = 0;\n    }\n    a[j] = p;\n    if( j>=mx ) mx = j+1;\n  }\n  p = 0;\n  for(i=0; i<mx; i++){\n    p = geopolyEventMerge(a[i], p);\n  }\n  return p;\n}\n\n/*\n** Merge two lists of sorted segments by Y, and then by C.\n*/\nstatic GeoSegment *geopolySegmentMerge(GeoSegment *pLeft, GeoSegment *pRight){\n  GeoSegment head, *pLast;\n  head.pNext = 0;\n  pLast = &head;\n  while( pRight && pLeft ){\n    double r = pRight->y - pLeft->y;\n    if( r==0.0 ) r = pRight->C - pLeft->C;\n    if( r<0.0 ){\n      pLast->pNext = pRight;\n      pLast = pRight;\n      pRight = pRight->pNext;\n    }else{\n      pLast->pNext = pLeft;\n      pLast = pLeft;\n      pLeft = pLeft->pNext;\n    }\n  }\n  pLast->pNext = pRight ? pRight : pLeft;\n  return head.pNext;  \n}\n\n/*\n** Sort a list of GeoSegments in order of increasing Y and in the event of\n** a tie, increasing C (slope).\n*/\nstatic GeoSegment *geopolySortSegmentsByYAndC(GeoSegment *pList){\n  int mx = 0;\n  int i;\n  GeoSegment *p;\n  GeoSegment *a[50];\n  while( pList ){\n    p = pList;\n    pList = pList->pNext;\n    p->pNext = 0;\n    for(i=0; i<mx && a[i]; i++){\n      p = geopolySegmentMerge(a[i], p);\n      a[i] = 0;\n    }\n    a[i] = p;\n    if( i>=mx ) mx = i+1;\n  }\n  p = 0;\n  for(i=0; i<mx; i++){\n    p = geopolySegmentMerge(a[i], p);\n  }\n  return p;\n}\n\n/*\n** Determine the overlap between two polygons\n*/\nstatic int geopolyOverlap(GeoPoly *p1, GeoPoly *p2){\n  sqlite3_int64 nVertex = p1->nVertex + p2->nVertex + 2;\n  GeoOverlap *p;\n  sqlite3_int64 nByte;\n  GeoEvent *pThisEvent;\n  double rX;\n  int rc = 0;\n  int needSort = 0;\n  GeoSegment *pActive = 0;\n  GeoSegment *pSeg;\n  unsigned char aOverlap[4];\n\n  nByte = sizeof(GeoEvent)*nVertex*2 \n           + sizeof(GeoSegment)*nVertex \n           + sizeof(GeoOverlap);\n  p = sqlite3_malloc64( nByte );\n  if( p==0 ) return -1;\n  p->aEvent = (GeoEvent*)&p[1];\n  p->aSegment = (GeoSegment*)&p->aEvent[nVertex*2];\n  p->nEvent = p->nSegment = 0;\n  geopolyAddSegments(p, p1, 1);\n  geopolyAddSegments(p, p2, 2);\n  pThisEvent = geopolySortEventsByX(p->aEvent, p->nEvent);\n  rX = pThisEvent->x==0.0 ? -1.0 : 0.0;\n  memset(aOverlap, 0, sizeof(aOverlap));\n  while( pThisEvent ){\n    if( pThisEvent->x!=rX ){\n      GeoSegment *pPrev = 0;\n      int iMask = 0;\n      GEODEBUG((\"Distinct X: %g\\n\", pThisEvent->x));\n      rX = pThisEvent->x;\n      if( needSort ){\n        GEODEBUG((\"SORT\\n\"));\n        pActive = geopolySortSegmentsByYAndC(pActive);\n        needSort = 0;\n      }\n      for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){\n        if( pPrev ){\n          if( pPrev->y!=pSeg->y ){\n            GEODEBUG((\"MASK: %d\\n\", iMask));\n            aOverlap[iMask] = 1;\n          }\n        }\n        iMask ^= pSeg->side;\n        pPrev = pSeg;\n      }\n      pPrev = 0;\n      for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){\n        double y = pSeg->C*rX + pSeg->B;\n        GEODEBUG((\"Segment %d.%d %g->%g\\n\", pSeg->side, pSeg->idx, pSeg->y, y));\n        pSeg->y = y;\n        if( pPrev ){\n          if( pPrev->y>pSeg->y && pPrev->side!=pSeg->side ){\n            rc = 1;\n            GEODEBUG((\"Crossing: %d.%d and %d.%d\\n\",\n                    pPrev->side, pPrev->idx,\n                    pSeg->side, pSeg->idx));\n            goto geopolyOverlapDone;\n          }else if( pPrev->y!=pSeg->y ){\n            GEODEBUG((\"MASK: %d\\n\", iMask));\n            aOverlap[iMask] = 1;\n          }\n        }\n        iMask ^= pSeg->side;\n        pPrev = pSeg;\n      }\n    }\n    GEODEBUG((\"%s %d.%d C=%g B=%g\\n\",\n      pThisEvent->eType ? \"RM \" : \"ADD\",\n      pThisEvent->pSeg->side, pThisEvent->pSeg->idx,\n      pThisEvent->pSeg->C,\n      pThisEvent->pSeg->B));\n    if( pThisEvent->eType==0 ){\n      /* Add a segment */\n      pSeg = pThisEvent->pSeg;\n      pSeg->y = pSeg->y0;\n      pSeg->pNext = pActive;\n      pActive = pSeg;\n      needSort = 1;\n    }else{\n      /* Remove a segment */\n      if( pActive==pThisEvent->pSeg ){\n        pActive = pActive->pNext;\n      }else{\n        for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){\n          if( pSeg->pNext==pThisEvent->pSeg ){\n            pSeg->pNext = pSeg->pNext->pNext;\n            break;\n          }\n        }\n      }\n    }\n    pThisEvent = pThisEvent->pNext;\n  }\n  if( aOverlap[3]==0 ){\n    rc = 0;\n  }else if( aOverlap[1]!=0 && aOverlap[2]==0 ){\n    rc = 3;\n  }else if( aOverlap[1]==0 && aOverlap[2]!=0 ){\n    rc = 2;\n  }else if( aOverlap[1]==0 && aOverlap[2]==0 ){\n    rc = 4;\n  }else{\n    rc = 1;\n  }\n\ngeopolyOverlapDone:\n  sqlite3_free(p);\n  return rc;\n}\n\n/*\n** SQL function:    geopoly_overlap(P1,P2)\n**\n** Determine whether or not P1 and P2 overlap. Return value:\n**\n**   0     The two polygons are disjoint\n**   1     They overlap\n**   2     P1 is completely contained within P2\n**   3     P2 is completely contained within P1\n**   4     P1 and P2 are the same polygon\n**   NULL  Either P1 or P2 or both are not valid polygons\n*/\nstatic void geopolyOverlapFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);\n  GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0);\n  if( p1 && p2 ){\n    int x = geopolyOverlap(p1, p2);\n    if( x<0 ){\n      sqlite3_result_error_nomem(context);\n    }else{\n      sqlite3_result_int(context, x);\n    }\n  }\n  sqlite3_free(p1);\n  sqlite3_free(p2);\n}\n\n/*\n** Enable or disable debugging output\n*/\nstatic void geopolyDebugFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n#ifdef GEOPOLY_ENABLE_DEBUG\n  geo_debug = sqlite3_value_int(argv[0]);\n#endif\n}\n\n/* \n** This function is the implementation of both the xConnect and xCreate\n** methods of the geopoly virtual table.\n**\n**   argv[0]   -> module name\n**   argv[1]   -> database name\n**   argv[2]   -> table name\n**   argv[...] -> column names...\n*/\nstatic int geopolyInit(\n  sqlite3 *db,                        /* Database connection */\n  void *pAux,                         /* One of the RTREE_COORD_* constants */\n  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */\n  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */\n  char **pzErr,                       /* OUT: Error message, if any */\n  int isCreate                        /* True for xCreate, false for xConnect */\n){\n  int rc = SQLITE_OK;\n  Rtree *pRtree;\n  sqlite3_int64 nDb;              /* Length of string argv[1] */\n  sqlite3_int64 nName;            /* Length of string argv[2] */\n  sqlite3_str *pSql;\n  char *zSql;\n  int ii;\n\n  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);\n\n  /* Allocate the sqlite3_vtab structure */\n  nDb = strlen(argv[1]);\n  nName = strlen(argv[2]);\n  pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2);\n  if( !pRtree ){\n    return SQLITE_NOMEM;\n  }\n  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);\n  pRtree->nBusy = 1;\n  pRtree->base.pModule = &rtreeModule;\n  pRtree->zDb = (char *)&pRtree[1];\n  pRtree->zName = &pRtree->zDb[nDb+1];\n  pRtree->eCoordType = RTREE_COORD_REAL32;\n  pRtree->nDim = 2;\n  pRtree->nDim2 = 4;\n  memcpy(pRtree->zDb, argv[1], nDb);\n  memcpy(pRtree->zName, argv[2], nName);\n\n\n  /* Create/Connect to the underlying relational database schema. If\n  ** that is successful, call sqlite3_declare_vtab() to configure\n  ** the r-tree table schema.\n  */\n  pSql = sqlite3_str_new(db);\n  sqlite3_str_appendf(pSql, \"CREATE TABLE x(_shape\");\n  pRtree->nAux = 1;         /* Add one for _shape */\n  pRtree->nAuxNotNull = 1;  /* The _shape column is always not-null */\n  for(ii=3; ii<argc; ii++){\n    pRtree->nAux++;\n    sqlite3_str_appendf(pSql, \",%s\", argv[ii]);\n  }\n  sqlite3_str_appendf(pSql, \");\");\n  zSql = sqlite3_str_finish(pSql);\n  if( !zSql ){\n    rc = SQLITE_NOMEM;\n  }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){\n    *pzErr = sqlite3_mprintf(\"%s\", sqlite3_errmsg(db));\n  }\n  sqlite3_free(zSql);\n  if( rc ) goto geopolyInit_fail;\n  pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;\n\n  /* Figure out the node size to use. */\n  rc = getNodeSize(db, pRtree, isCreate, pzErr);\n  if( rc ) goto geopolyInit_fail;\n  rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);\n  if( rc ){\n    *pzErr = sqlite3_mprintf(\"%s\", sqlite3_errmsg(db));\n    goto geopolyInit_fail;\n  }\n\n  *ppVtab = (sqlite3_vtab *)pRtree;\n  return SQLITE_OK;\n\ngeopolyInit_fail:\n  if( rc==SQLITE_OK ) rc = SQLITE_ERROR;\n  assert( *ppVtab==0 );\n  assert( pRtree->nBusy==1 );\n  rtreeRelease(pRtree);\n  return rc;\n}\n\n\n/* \n** GEOPOLY virtual table module xCreate method.\n*/\nstatic int geopolyCreate(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 1);\n}\n\n/* \n** GEOPOLY virtual table module xConnect method.\n*/\nstatic int geopolyConnect(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 0);\n}\n\n\n/* \n** GEOPOLY virtual table module xFilter method.\n**\n** Query plans:\n**\n**      1         rowid lookup\n**      2         search for objects overlapping the same bounding box\n**                that contains polygon argv[0]\n**      3         search for objects overlapping the same bounding box\n**                that contains polygon argv[0]\n**      4         full table scan\n*/\nstatic int geopolyFilter(\n  sqlite3_vtab_cursor *pVtabCursor,     /* The cursor to initialize */\n  int idxNum,                           /* Query plan */\n  const char *idxStr,                   /* Not Used */\n  int argc, sqlite3_value **argv        /* Parameters to the query plan */\n){\n  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;\n  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;\n  RtreeNode *pRoot = 0;\n  int rc = SQLITE_OK;\n  int iCell = 0;\n\n  rtreeReference(pRtree);\n\n  /* Reset the cursor to the same state as rtreeOpen() leaves it in. */\n  resetCursor(pCsr);\n\n  pCsr->iStrategy = idxNum;\n  if( idxNum==1 ){\n    /* Special case - lookup by rowid. */\n    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */\n    RtreeSearchPoint *p;     /* Search point for the leaf */\n    i64 iRowid = sqlite3_value_int64(argv[0]);\n    i64 iNode = 0;\n    rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);\n    if( rc==SQLITE_OK && pLeaf!=0 ){\n      p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);\n      assert( p!=0 );  /* Always returns pCsr->sPoint */\n      pCsr->aNode[0] = pLeaf;\n      p->id = iNode;\n      p->eWithin = PARTLY_WITHIN;\n      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);\n      p->iCell = (u8)iCell;\n      RTREE_QUEUE_TRACE(pCsr, \"PUSH-F1:\");\n    }else{\n      pCsr->atEOF = 1;\n    }\n  }else{\n    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array \n    ** with the configured constraints. \n    */\n    rc = nodeAcquire(pRtree, 1, 0, &pRoot);\n    if( rc==SQLITE_OK && idxNum<=3 ){\n      RtreeCoord bbox[4];\n      RtreeConstraint *p;\n      assert( argc==1 );\n      geopolyBBox(0, argv[0], bbox, &rc);\n      if( rc ){\n        goto geopoly_filter_end;\n      }\n      pCsr->aConstraint = p = sqlite3_malloc(sizeof(RtreeConstraint)*4);\n      pCsr->nConstraint = 4;\n      if( p==0 ){\n        rc = SQLITE_NOMEM;\n      }else{\n        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*4);\n        memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));\n        if( idxNum==2 ){\n          /* Overlap query */\n          p->op = 'B';\n          p->iCoord = 0;\n          p->u.rValue = bbox[1].f;\n          p++;\n          p->op = 'D';\n          p->iCoord = 1;\n          p->u.rValue = bbox[0].f;\n          p++;\n          p->op = 'B';\n          p->iCoord = 2;\n          p->u.rValue = bbox[3].f;\n          p++;\n          p->op = 'D';\n          p->iCoord = 3;\n          p->u.rValue = bbox[2].f;\n        }else{\n          /* Within query */\n          p->op = 'D';\n          p->iCoord = 0;\n          p->u.rValue = bbox[0].f;\n          p++;\n          p->op = 'B';\n          p->iCoord = 1;\n          p->u.rValue = bbox[1].f;\n          p++;\n          p->op = 'D';\n          p->iCoord = 2;\n          p->u.rValue = bbox[2].f;\n          p++;\n          p->op = 'B';\n          p->iCoord = 3;\n          p->u.rValue = bbox[3].f;\n        }\n      }\n    }\n    if( rc==SQLITE_OK ){\n      RtreeSearchPoint *pNew;\n      pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));\n      if( pNew==0 ){\n        rc = SQLITE_NOMEM;\n        goto geopoly_filter_end;\n      }\n      pNew->id = 1;\n      pNew->iCell = 0;\n      pNew->eWithin = PARTLY_WITHIN;\n      assert( pCsr->bPoint==1 );\n      pCsr->aNode[0] = pRoot;\n      pRoot = 0;\n      RTREE_QUEUE_TRACE(pCsr, \"PUSH-Fm:\");\n      rc = rtreeStepToLeaf(pCsr);\n    }\n  }\n\ngeopoly_filter_end:\n  nodeRelease(pRtree, pRoot);\n  rtreeRelease(pRtree);\n  return rc;\n}\n\n/*\n** Rtree virtual table module xBestIndex method. There are three\n** table scan strategies to choose from (in order from most to \n** least desirable):\n**\n**   idxNum     idxStr        Strategy\n**   ------------------------------------------------\n**     1        \"rowid\"       Direct lookup by rowid.\n**     2        \"rtree\"       R-tree overlap query using geopoly_overlap()\n**     3        \"rtree\"       R-tree within query using geopoly_within()\n**     4        \"fullscan\"    full-table scan.\n**   ------------------------------------------------\n*/\nstatic int geopolyBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){\n  int ii;\n  int iRowidTerm = -1;\n  int iFuncTerm = -1;\n  int idxNum = 0;\n\n  for(ii=0; ii<pIdxInfo->nConstraint; ii++){\n    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];\n    if( !p->usable ) continue;\n    if( p->iColumn<0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ  ){\n      iRowidTerm = ii;\n      break;\n    }\n    if( p->iColumn==0 && p->op>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){\n      /* p->op==SQLITE_INDEX_CONSTRAINT_FUNCTION for geopoly_overlap()\n      ** p->op==(SQLITE_INDEX_CONTRAINT_FUNCTION+1) for geopoly_within().\n      ** See geopolyFindFunction() */\n      iFuncTerm = ii;\n      idxNum = p->op - SQLITE_INDEX_CONSTRAINT_FUNCTION + 2;\n    }\n  }\n\n  if( iRowidTerm>=0 ){\n    pIdxInfo->idxNum = 1;\n    pIdxInfo->idxStr = \"rowid\";\n    pIdxInfo->aConstraintUsage[iRowidTerm].argvIndex = 1;\n    pIdxInfo->aConstraintUsage[iRowidTerm].omit = 1;\n    pIdxInfo->estimatedCost = 30.0;\n    pIdxInfo->estimatedRows = 1;\n    pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;\n    return SQLITE_OK;\n  }\n  if( iFuncTerm>=0 ){\n    pIdxInfo->idxNum = idxNum;\n    pIdxInfo->idxStr = \"rtree\";\n    pIdxInfo->aConstraintUsage[iFuncTerm].argvIndex = 1;\n    pIdxInfo->aConstraintUsage[iFuncTerm].omit = 0;\n    pIdxInfo->estimatedCost = 300.0;\n    pIdxInfo->estimatedRows = 10;\n    return SQLITE_OK;\n  }\n  pIdxInfo->idxNum = 4;\n  pIdxInfo->idxStr = \"fullscan\";\n  pIdxInfo->estimatedCost = 3000000.0;\n  pIdxInfo->estimatedRows = 100000;\n  return SQLITE_OK;\n}\n\n\n/* \n** GEOPOLY virtual table module xColumn method.\n*/\nstatic int geopolyColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){\n  Rtree *pRtree = (Rtree *)cur->pVtab;\n  RtreeCursor *pCsr = (RtreeCursor *)cur;\n  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);\n  int rc = SQLITE_OK;\n  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);\n\n  if( rc ) return rc;\n  if( p==0 ) return SQLITE_OK;\n  if( i==0 && sqlite3_vtab_nochange(ctx) ) return SQLITE_OK;\n  if( i<=pRtree->nAux ){\n    if( !pCsr->bAuxValid ){\n      if( pCsr->pReadAux==0 ){\n        rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,\n                                &pCsr->pReadAux, 0);\n        if( rc ) return rc;\n      }\n      sqlite3_bind_int64(pCsr->pReadAux, 1, \n          nodeGetRowid(pRtree, pNode, p->iCell));\n      rc = sqlite3_step(pCsr->pReadAux);\n      if( rc==SQLITE_ROW ){\n        pCsr->bAuxValid = 1;\n      }else{\n        sqlite3_reset(pCsr->pReadAux);\n        if( rc==SQLITE_DONE ) rc = SQLITE_OK;\n        return rc;\n      }\n    }\n    sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pReadAux, i+2));\n  }\n  return SQLITE_OK;\n}\n\n\n/*\n** The xUpdate method for GEOPOLY module virtual tables.\n**\n** For DELETE:\n**\n**     argv[0] = the rowid to be deleted\n**\n** For INSERT:\n**\n**     argv[0] = SQL NULL\n**     argv[1] = rowid to insert, or an SQL NULL to select automatically\n**     argv[2] = _shape column\n**     argv[3] = first application-defined column....\n**\n** For UPDATE:\n**\n**     argv[0] = rowid to modify.  Never NULL\n**     argv[1] = rowid after the change.  Never NULL\n**     argv[2] = new value for _shape\n**     argv[3] = new value for first application-defined column....\n*/\nstatic int geopolyUpdate(\n  sqlite3_vtab *pVtab, \n  int nData, \n  sqlite3_value **aData, \n  sqlite_int64 *pRowid\n){\n  Rtree *pRtree = (Rtree *)pVtab;\n  int rc = SQLITE_OK;\n  RtreeCell cell;                 /* New cell to insert if nData>1 */\n  i64 oldRowid;                   /* The old rowid */\n  int oldRowidValid;              /* True if oldRowid is valid */\n  i64 newRowid;                   /* The new rowid */\n  int newRowidValid;              /* True if newRowid is valid */\n  int coordChange = 0;            /* Change in coordinates */\n\n  if( pRtree->nNodeRef ){\n    /* Unable to write to the btree while another cursor is reading from it,\n    ** since the write might do a rebalance which would disrupt the read\n    ** cursor. */\n    return SQLITE_LOCKED_VTAB;\n  }\n  rtreeReference(pRtree);\n  assert(nData>=1);\n\n  oldRowidValid = sqlite3_value_type(aData[0])!=SQLITE_NULL;;\n  oldRowid = oldRowidValid ? sqlite3_value_int64(aData[0]) : 0;\n  newRowidValid = nData>1 && sqlite3_value_type(aData[1])!=SQLITE_NULL;\n  newRowid = newRowidValid ? sqlite3_value_int64(aData[1]) : 0;\n  cell.iRowid = newRowid;\n\n  if( nData>1                                 /* not a DELETE */\n   && (!oldRowidValid                         /* INSERT */\n        || !sqlite3_value_nochange(aData[2])  /* UPDATE _shape */\n        || oldRowid!=newRowid)                /* Rowid change */\n  ){\n    geopolyBBox(0, aData[2], cell.aCoord, &rc);\n    if( rc ){\n      if( rc==SQLITE_ERROR ){\n        pVtab->zErrMsg =\n          sqlite3_mprintf(\"_shape does not contain a valid polygon\");\n      }\n      goto geopoly_update_end;\n    }\n    coordChange = 1;\n\n    /* If a rowid value was supplied, check if it is already present in \n    ** the table. If so, the constraint has failed. */\n    if( newRowidValid && (!oldRowidValid || oldRowid!=newRowid) ){\n      int steprc;\n      sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);\n      steprc = sqlite3_step(pRtree->pReadRowid);\n      rc = sqlite3_reset(pRtree->pReadRowid);\n      if( SQLITE_ROW==steprc ){\n        if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){\n          rc = rtreeDeleteRowid(pRtree, cell.iRowid);\n        }else{\n          rc = rtreeConstraintError(pRtree, 0);\n        }\n      }\n    }\n  }\n\n  /* If aData[0] is not an SQL NULL value, it is the rowid of a\n  ** record to delete from the r-tree table. The following block does\n  ** just that.\n  */\n  if( rc==SQLITE_OK && (nData==1 || (coordChange && oldRowidValid)) ){\n    rc = rtreeDeleteRowid(pRtree, oldRowid);\n  }\n\n  /* If the aData[] array contains more than one element, elements\n  ** (aData[2]..aData[argc-1]) contain a new record to insert into\n  ** the r-tree structure.\n  */\n  if( rc==SQLITE_OK && nData>1 && coordChange ){\n    /* Insert the new record into the r-tree */\n    RtreeNode *pLeaf = 0;\n    if( !newRowidValid ){\n      rc = rtreeNewRowid(pRtree, &cell.iRowid);\n    }\n    *pRowid = cell.iRowid;\n    if( rc==SQLITE_OK ){\n      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);\n    }\n    if( rc==SQLITE_OK ){\n      int rc2;\n      pRtree->iReinsertHeight = -1;\n      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);\n      rc2 = nodeRelease(pRtree, pLeaf);\n      if( rc==SQLITE_OK ){\n        rc = rc2;\n      }\n    }\n  }\n\n  /* Change the data */\n  if( rc==SQLITE_OK && nData>1 ){\n    sqlite3_stmt *pUp = pRtree->pWriteAux;\n    int jj;\n    int nChange = 0;\n    sqlite3_bind_int64(pUp, 1, cell.iRowid);\n    assert( pRtree->nAux>=1 );\n    if( sqlite3_value_nochange(aData[2]) ){\n      sqlite3_bind_null(pUp, 2);\n    }else{\n      GeoPoly *p = 0;\n      if( sqlite3_value_type(aData[2])==SQLITE_TEXT\n       && (p = geopolyFuncParam(0, aData[2], &rc))!=0\n       && rc==SQLITE_OK\n      ){\n        sqlite3_bind_blob(pUp, 2, p->hdr, 4+8*p->nVertex, SQLITE_TRANSIENT);\n      }else{\n        sqlite3_bind_value(pUp, 2, aData[2]);\n      }\n      sqlite3_free(p);\n      nChange = 1;\n    }\n    for(jj=1; jj<pRtree->nAux; jj++){\n      nChange++;\n      sqlite3_bind_value(pUp, jj+2, aData[jj+2]);\n    }\n    if( nChange ){\n      sqlite3_step(pUp);\n      rc = sqlite3_reset(pUp);\n    }\n  }\n\ngeopoly_update_end:\n  rtreeRelease(pRtree);\n  return rc;\n}\n\n/*\n** Report that geopoly_overlap() is an overloaded function suitable\n** for use in xBestIndex.\n*/\nstatic int geopolyFindFunction(\n  sqlite3_vtab *pVtab,\n  int nArg,\n  const char *zName,\n  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),\n  void **ppArg\n){\n  if( sqlite3_stricmp(zName, \"geopoly_overlap\")==0 ){\n    *pxFunc = geopolyOverlapFunc;\n    *ppArg = 0;\n    return SQLITE_INDEX_CONSTRAINT_FUNCTION;\n  }\n  if( sqlite3_stricmp(zName, \"geopoly_within\")==0 ){\n    *pxFunc = geopolyWithinFunc;\n    *ppArg = 0;\n    return SQLITE_INDEX_CONSTRAINT_FUNCTION+1;\n  }\n  return 0;\n}\n\n\nstatic sqlite3_module geopolyModule = {\n  3,                          /* iVersion */\n  geopolyCreate,              /* xCreate - create a table */\n  geopolyConnect,             /* xConnect - connect to an existing table */\n  geopolyBestIndex,           /* xBestIndex - Determine search strategy */\n  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */\n  rtreeDestroy,               /* xDestroy - Drop a table */\n  rtreeOpen,                  /* xOpen - open a cursor */\n  rtreeClose,                 /* xClose - close a cursor */\n  geopolyFilter,              /* xFilter - configure scan constraints */\n  rtreeNext,                  /* xNext - advance a cursor */\n  rtreeEof,                   /* xEof */\n  geopolyColumn,              /* xColumn - read data */\n  rtreeRowid,                 /* xRowid - read data */\n  geopolyUpdate,              /* xUpdate - write data */\n  rtreeBeginTransaction,      /* xBegin - begin transaction */\n  rtreeEndTransaction,        /* xSync - sync transaction */\n  rtreeEndTransaction,        /* xCommit - commit transaction */\n  rtreeEndTransaction,        /* xRollback - rollback transaction */\n  geopolyFindFunction,        /* xFindFunction - function overloading */\n  rtreeRename,                /* xRename - rename the table */\n  rtreeSavepoint,             /* xSavepoint */\n  0,                          /* xRelease */\n  0,                          /* xRollbackTo */\n  rtreeShadowName             /* xShadowName */\n};\n\nstatic int sqlite3_geopoly_init(sqlite3 *db){\n  int rc = SQLITE_OK;\n  static const struct {\n    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);\n    signed char nArg;\n    unsigned char bPure;\n    const char *zName;\n  } aFunc[] = {\n     { geopolyAreaFunc,          1, 1,    \"geopoly_area\"             },\n     { geopolyBlobFunc,          1, 1,    \"geopoly_blob\"             },\n     { geopolyJsonFunc,          1, 1,    \"geopoly_json\"             },\n     { geopolySvgFunc,          -1, 1,    \"geopoly_svg\"              },\n     { geopolyWithinFunc,        2, 1,    \"geopoly_within\"           },\n     { geopolyContainsPointFunc, 3, 1,    \"geopoly_contains_point\"   },\n     { geopolyOverlapFunc,       2, 1,    \"geopoly_overlap\"          },\n     { geopolyDebugFunc,         1, 0,    \"geopoly_debug\"            },\n     { geopolyBBoxFunc,          1, 1,    \"geopoly_bbox\"             },\n     { geopolyXformFunc,         7, 1,    \"geopoly_xform\"            },\n     { geopolyRegularFunc,       4, 1,    \"geopoly_regular\"          },\n     { geopolyCcwFunc,           1, 1,    \"geopoly_ccw\"              },\n  };\n  static const struct {\n    void (*xStep)(sqlite3_context*,int,sqlite3_value**);\n    void (*xFinal)(sqlite3_context*);\n    const char *zName;\n  } aAgg[] = {\n     { geopolyBBoxStep, geopolyBBoxFinal, \"geopoly_group_bbox\"    },\n  };\n  int i;\n  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){\n    int enc;\n    if( aFunc[i].bPure ){\n      enc = SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS;\n    }else{\n      enc = SQLITE_UTF8|SQLITE_DIRECTONLY;\n    }\n    rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,\n                                 enc, 0,\n                                 aFunc[i].xFunc, 0, 0);\n  }\n  for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){\n    rc = sqlite3_create_function(db, aAgg[i].zName, 1, \n              SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS, 0,\n              0, aAgg[i].xStep, aAgg[i].xFinal);\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_module_v2(db, \"geopoly\", &geopolyModule, 0, 0);\n  }\n  return rc;\n}\n\n/************** End of geopoly.c *********************************************/\n/************** Continuing where we left off in rtree.c **********************/\n#endif\n\n/*\n** Register the r-tree module with database handle db. This creates the\n** virtual table module \"rtree\" and the debugging/analysis scalar \n** function \"rtreenode\".\n*/\nSQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){\n  const int utf8 = SQLITE_UTF8;\n  int rc;\n\n  rc = sqlite3_create_function(db, \"rtreenode\", 2, utf8, 0, rtreenode, 0, 0);\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_function(db, \"rtreedepth\", 1, utf8, 0,rtreedepth, 0, 0);\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_function(db, \"rtreecheck\", -1, utf8, 0,rtreecheck, 0,0);\n  }\n  if( rc==SQLITE_OK ){\n#ifdef SQLITE_RTREE_INT_ONLY\n    void *c = (void *)RTREE_COORD_INT32;\n#else\n    void *c = (void *)RTREE_COORD_REAL32;\n#endif\n    rc = sqlite3_create_module_v2(db, \"rtree\", &rtreeModule, c, 0);\n  }\n  if( rc==SQLITE_OK ){\n    void *c = (void *)RTREE_COORD_INT32;\n    rc = sqlite3_create_module_v2(db, \"rtree_i32\", &rtreeModule, c, 0);\n  }\n#ifdef SQLITE_ENABLE_GEOPOLY\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_geopoly_init(db);\n  }\n#endif\n\n  return rc;\n}\n\n/*\n** This routine deletes the RtreeGeomCallback object that was attached\n** one of the SQL functions create by sqlite3_rtree_geometry_callback()\n** or sqlite3_rtree_query_callback().  In other words, this routine is the\n** destructor for an RtreeGeomCallback objecct.  This routine is called when\n** the corresponding SQL function is deleted.\n*/\nstatic void rtreeFreeCallback(void *p){\n  RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;\n  if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);\n  sqlite3_free(p);\n}\n\n/*\n** This routine frees the BLOB that is returned by geomCallback().\n*/\nstatic void rtreeMatchArgFree(void *pArg){\n  int i;\n  RtreeMatchArg *p = (RtreeMatchArg*)pArg;\n  for(i=0; i<p->nParam; i++){\n    sqlite3_value_free(p->apSqlParam[i]);\n  }\n  sqlite3_free(p);\n}\n\n/*\n** Each call to sqlite3_rtree_geometry_callback() or\n** sqlite3_rtree_query_callback() creates an ordinary SQLite\n** scalar function that is implemented by this routine.\n**\n** All this function does is construct an RtreeMatchArg object that\n** contains the geometry-checking callback routines and a list of\n** parameters to this function, then return that RtreeMatchArg object\n** as a BLOB.\n**\n** The R-Tree MATCH operator will read the returned BLOB, deserialize\n** the RtreeMatchArg object, and use the RtreeMatchArg object to figure\n** out which elements of the R-Tree should be returned by the query.\n*/\nstatic void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){\n  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);\n  RtreeMatchArg *pBlob;\n  sqlite3_int64 nBlob;\n  int memErr = 0;\n\n  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)\n           + nArg*sizeof(sqlite3_value*);\n  pBlob = (RtreeMatchArg *)sqlite3_malloc64(nBlob);\n  if( !pBlob ){\n    sqlite3_result_error_nomem(ctx);\n  }else{\n    int i;\n    pBlob->iSize = nBlob;\n    pBlob->cb = pGeomCtx[0];\n    pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];\n    pBlob->nParam = nArg;\n    for(i=0; i<nArg; i++){\n      pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);\n      if( pBlob->apSqlParam[i]==0 ) memErr = 1;\n#ifdef SQLITE_RTREE_INT_ONLY\n      pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);\n#else\n      pBlob->aParam[i] = sqlite3_value_double(aArg[i]);\n#endif\n    }\n    if( memErr ){\n      sqlite3_result_error_nomem(ctx);\n      rtreeMatchArgFree(pBlob);\n    }else{\n      sqlite3_result_pointer(ctx, pBlob, \"RtreeMatchArg\", rtreeMatchArgFree);\n    }\n  }\n}\n\n/*\n** Register a new geometry function for use with the r-tree MATCH operator.\n*/\nSQLITE_API int sqlite3_rtree_geometry_callback(\n  sqlite3 *db,                  /* Register SQL function on this connection */\n  const char *zGeom,            /* Name of the new SQL function */\n  int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */\n  void *pContext                /* Extra data associated with the callback */\n){\n  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */\n\n  /* Allocate and populate the context object. */\n  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));\n  if( !pGeomCtx ) return SQLITE_NOMEM;\n  pGeomCtx->xGeom = xGeom;\n  pGeomCtx->xQueryFunc = 0;\n  pGeomCtx->xDestructor = 0;\n  pGeomCtx->pContext = pContext;\n  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, \n      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback\n  );\n}\n\n/*\n** Register a new 2nd-generation geometry function for use with the\n** r-tree MATCH operator.\n*/\nSQLITE_API int sqlite3_rtree_query_callback(\n  sqlite3 *db,                 /* Register SQL function on this connection */\n  const char *zQueryFunc,      /* Name of new SQL function */\n  int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */\n  void *pContext,              /* Extra data passed into the callback */\n  void (*xDestructor)(void*)   /* Destructor for the extra data */\n){\n  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */\n\n  /* Allocate and populate the context object. */\n  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));\n  if( !pGeomCtx ) return SQLITE_NOMEM;\n  pGeomCtx->xGeom = 0;\n  pGeomCtx->xQueryFunc = xQueryFunc;\n  pGeomCtx->xDestructor = xDestructor;\n  pGeomCtx->pContext = pContext;\n  return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY, \n      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback\n  );\n}\n\n#if !SQLITE_CORE\n#ifdef _WIN32\n__declspec(dllexport)\n#endif\nSQLITE_API int sqlite3_rtree_init(\n  sqlite3 *db,\n  char **pzErrMsg,\n  const sqlite3_api_routines *pApi\n){\n  SQLITE_EXTENSION_INIT2(pApi)\n  return sqlite3RtreeInit(db);\n}\n#endif\n\n#endif\n\n/************** End of rtree.c ***********************************************/\n/************** Begin file icu.c *********************************************/\n/*\n** 2007 May 6\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $\n**\n** This file implements an integration between the ICU library \n** (\"International Components for Unicode\", an open-source library \n** for handling unicode data) and SQLite. The integration uses \n** ICU to provide the following to SQLite:\n**\n**   * An implementation of the SQL regexp() function (and hence REGEXP\n**     operator) using the ICU uregex_XX() APIs.\n**\n**   * Implementations of the SQL scalar upper() and lower() functions\n**     for case mapping.\n**\n**   * Integration of ICU and SQLite collation sequences.\n**\n**   * An implementation of the LIKE operator that uses ICU to \n**     provide case-independent matching.\n*/\n\n#if !defined(SQLITE_CORE)                  \\\n || defined(SQLITE_ENABLE_ICU)             \\\n || defined(SQLITE_ENABLE_ICU_COLLATIONS)\n\n/* Include ICU headers */\n#include <unicode/utypes.h>\n#include <unicode/uregex.h>\n#include <unicode/ustring.h>\n#include <unicode/ucol.h>\n\n/* #include <assert.h> */\n\n#ifndef SQLITE_CORE\n/*   #include \"sqlite3ext.h\" */\n  SQLITE_EXTENSION_INIT1\n#else\n/*   #include \"sqlite3.h\" */\n#endif\n\n/*\n** This function is called when an ICU function called from within\n** the implementation of an SQL scalar function returns an error.\n**\n** The scalar function context passed as the first argument is \n** loaded with an error message based on the following two args.\n*/\nstatic void icuFunctionError(\n  sqlite3_context *pCtx,       /* SQLite scalar function context */\n  const char *zName,           /* Name of ICU function that failed */\n  UErrorCode e                 /* Error code returned by ICU function */\n){\n  char zBuf[128];\n  sqlite3_snprintf(128, zBuf, \"ICU error: %s(): %s\", zName, u_errorName(e));\n  zBuf[127] = '\\0';\n  sqlite3_result_error(pCtx, zBuf, -1);\n}\n\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)\n\n/*\n** Maximum length (in bytes) of the pattern in a LIKE or GLOB\n** operator.\n*/\n#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH\n# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000\n#endif\n\n/*\n** Version of sqlite3_free() that is always a function, never a macro.\n*/\nstatic void xFree(void *p){\n  sqlite3_free(p);\n}\n\n/*\n** This lookup table is used to help decode the first byte of\n** a multi-byte UTF8 character. It is copied here from SQLite source\n** code file utf8.c.\n*/\nstatic const unsigned char icuUtf8Trans1[] = {\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,\n  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,\n  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,\n};\n\n#define SQLITE_ICU_READ_UTF8(zIn, c)                       \\\n  c = *(zIn++);                                            \\\n  if( c>=0xc0 ){                                           \\\n    c = icuUtf8Trans1[c-0xc0];                             \\\n    while( (*zIn & 0xc0)==0x80 ){                          \\\n      c = (c<<6) + (0x3f & *(zIn++));                      \\\n    }                                                      \\\n  }\n\n#define SQLITE_ICU_SKIP_UTF8(zIn)                          \\\n  assert( *zIn );                                          \\\n  if( *(zIn++)>=0xc0 ){                                    \\\n    while( (*zIn & 0xc0)==0x80 ){zIn++;}                   \\\n  }\n\n\n/*\n** Compare two UTF-8 strings for equality where the first string is\n** a \"LIKE\" expression. Return true (1) if they are the same and \n** false (0) if they are different.\n*/\nstatic int icuLikeCompare(\n  const uint8_t *zPattern,   /* LIKE pattern */\n  const uint8_t *zString,    /* The UTF-8 string to compare against */\n  const UChar32 uEsc         /* The escape character */\n){\n  static const uint32_t MATCH_ONE = (uint32_t)'_';\n  static const uint32_t MATCH_ALL = (uint32_t)'%';\n\n  int prevEscape = 0;     /* True if the previous character was uEsc */\n\n  while( 1 ){\n\n    /* Read (and consume) the next character from the input pattern. */\n    uint32_t uPattern;\n    SQLITE_ICU_READ_UTF8(zPattern, uPattern);\n    if( uPattern==0 ) break;\n\n    /* There are now 4 possibilities:\n    **\n    **     1. uPattern is an unescaped match-all character \"%\",\n    **     2. uPattern is an unescaped match-one character \"_\",\n    **     3. uPattern is an unescaped escape character, or\n    **     4. uPattern is to be handled as an ordinary character\n    */\n    if( uPattern==MATCH_ALL && !prevEscape && uPattern!=(uint32_t)uEsc ){\n      /* Case 1. */\n      uint8_t c;\n\n      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a\n      ** MATCH_ALL. For each MATCH_ONE, skip one character in the \n      ** test string.\n      */\n      while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){\n        if( c==MATCH_ONE ){\n          if( *zString==0 ) return 0;\n          SQLITE_ICU_SKIP_UTF8(zString);\n        }\n        zPattern++;\n      }\n\n      if( *zPattern==0 ) return 1;\n\n      while( *zString ){\n        if( icuLikeCompare(zPattern, zString, uEsc) ){\n          return 1;\n        }\n        SQLITE_ICU_SKIP_UTF8(zString);\n      }\n      return 0;\n\n    }else if( uPattern==MATCH_ONE && !prevEscape && uPattern!=(uint32_t)uEsc ){\n      /* Case 2. */\n      if( *zString==0 ) return 0;\n      SQLITE_ICU_SKIP_UTF8(zString);\n\n    }else if( uPattern==(uint32_t)uEsc && !prevEscape ){\n      /* Case 3. */\n      prevEscape = 1;\n\n    }else{\n      /* Case 4. */\n      uint32_t uString;\n      SQLITE_ICU_READ_UTF8(zString, uString);\n      uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT);\n      uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT);\n      if( uString!=uPattern ){\n        return 0;\n      }\n      prevEscape = 0;\n    }\n  }\n\n  return *zString==0;\n}\n\n/*\n** Implementation of the like() SQL function.  This function implements\n** the build-in LIKE operator.  The first argument to the function is the\n** pattern and the second argument is the string.  So, the SQL statements:\n**\n**       A LIKE B\n**\n** is implemented as like(B, A). If there is an escape character E, \n**\n**       A LIKE B ESCAPE E\n**\n** is mapped to like(B, A, E).\n*/\nstatic void icuLikeFunc(\n  sqlite3_context *context, \n  int argc, \n  sqlite3_value **argv\n){\n  const unsigned char *zA = sqlite3_value_text(argv[0]);\n  const unsigned char *zB = sqlite3_value_text(argv[1]);\n  UChar32 uEsc = 0;\n\n  /* Limit the length of the LIKE or GLOB pattern to avoid problems\n  ** of deep recursion and N*N behavior in patternCompare().\n  */\n  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){\n    sqlite3_result_error(context, \"LIKE or GLOB pattern too complex\", -1);\n    return;\n  }\n\n\n  if( argc==3 ){\n    /* The escape character string must consist of a single UTF-8 character.\n    ** Otherwise, return an error.\n    */\n    int nE= sqlite3_value_bytes(argv[2]);\n    const unsigned char *zE = sqlite3_value_text(argv[2]);\n    int i = 0;\n    if( zE==0 ) return;\n    U8_NEXT(zE, i, nE, uEsc);\n    if( i!=nE){\n      sqlite3_result_error(context, \n          \"ESCAPE expression must be a single character\", -1);\n      return;\n    }\n  }\n\n  if( zA && zB ){\n    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));\n  }\n}\n\n/*\n** Function to delete compiled regexp objects. Registered as\n** a destructor function with sqlite3_set_auxdata().\n*/\nstatic void icuRegexpDelete(void *p){\n  URegularExpression *pExpr = (URegularExpression *)p;\n  uregex_close(pExpr);\n}\n\n/*\n** Implementation of SQLite REGEXP operator. This scalar function takes\n** two arguments. The first is a regular expression pattern to compile\n** the second is a string to match against that pattern. If either \n** argument is an SQL NULL, then NULL Is returned. Otherwise, the result\n** is 1 if the string matches the pattern, or 0 otherwise.\n**\n** SQLite maps the regexp() function to the regexp() operator such\n** that the following two are equivalent:\n**\n**     zString REGEXP zPattern\n**     regexp(zPattern, zString)\n**\n** Uses the following ICU regexp APIs:\n**\n**     uregex_open()\n**     uregex_matches()\n**     uregex_close()\n*/\nstatic void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){\n  UErrorCode status = U_ZERO_ERROR;\n  URegularExpression *pExpr;\n  UBool res;\n  const UChar *zString = sqlite3_value_text16(apArg[1]);\n\n  (void)nArg;  /* Unused parameter */\n\n  /* If the left hand side of the regexp operator is NULL, \n  ** then the result is also NULL. \n  */\n  if( !zString ){\n    return;\n  }\n\n  pExpr = sqlite3_get_auxdata(p, 0);\n  if( !pExpr ){\n    const UChar *zPattern = sqlite3_value_text16(apArg[0]);\n    if( !zPattern ){\n      return;\n    }\n    pExpr = uregex_open(zPattern, -1, 0, 0, &status);\n\n    if( U_SUCCESS(status) ){\n      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);\n    }else{\n      assert(!pExpr);\n      icuFunctionError(p, \"uregex_open\", status);\n      return;\n    }\n  }\n\n  /* Configure the text that the regular expression operates on. */\n  uregex_setText(pExpr, zString, -1, &status);\n  if( !U_SUCCESS(status) ){\n    icuFunctionError(p, \"uregex_setText\", status);\n    return;\n  }\n\n  /* Attempt the match */\n  res = uregex_matches(pExpr, 0, &status);\n  if( !U_SUCCESS(status) ){\n    icuFunctionError(p, \"uregex_matches\", status);\n    return;\n  }\n\n  /* Set the text that the regular expression operates on to a NULL\n  ** pointer. This is not really necessary, but it is tidier than \n  ** leaving the regular expression object configured with an invalid\n  ** pointer after this function returns.\n  */\n  uregex_setText(pExpr, 0, 0, &status);\n\n  /* Return 1 or 0. */\n  sqlite3_result_int(p, res ? 1 : 0);\n}\n\n/*\n** Implementations of scalar functions for case mapping - upper() and \n** lower(). Function upper() converts its input to upper-case (ABC).\n** Function lower() converts to lower-case (abc).\n**\n** ICU provides two types of case mapping, \"general\" case mapping and\n** \"language specific\". Refer to ICU documentation for the differences\n** between the two.\n**\n** To utilise \"general\" case mapping, the upper() or lower() scalar \n** functions are invoked with one argument:\n**\n**     upper('ABC') -> 'abc'\n**     lower('abc') -> 'ABC'\n**\n** To access ICU \"language specific\" case mapping, upper() or lower()\n** should be invoked with two arguments. The second argument is the name\n** of the locale to use. Passing an empty string (\"\") or SQL NULL value\n** as the second argument is the same as invoking the 1 argument version\n** of upper() or lower().\n**\n**     lower('I', 'en_us') -> 'i'\n**     lower('I', 'tr_tr') -> '\\u131' (small dotless i)\n**\n** http://www.icu-project.org/userguide/posix.html#case_mappings\n*/\nstatic void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){\n  const UChar *zInput;            /* Pointer to input string */\n  UChar *zOutput = 0;             /* Pointer to output buffer */\n  int nInput;                     /* Size of utf-16 input string in bytes */\n  int nOut;                       /* Size of output buffer in bytes */\n  int cnt;\n  int bToUpper;                   /* True for toupper(), false for tolower() */\n  UErrorCode status;\n  const char *zLocale = 0;\n\n  assert(nArg==1 || nArg==2);\n  bToUpper = (sqlite3_user_data(p)!=0);\n  if( nArg==2 ){\n    zLocale = (const char *)sqlite3_value_text(apArg[1]);\n  }\n\n  zInput = sqlite3_value_text16(apArg[0]);\n  if( !zInput ){\n    return;\n  }\n  nOut = nInput = sqlite3_value_bytes16(apArg[0]);\n  if( nOut==0 ){\n    sqlite3_result_text16(p, \"\", 0, SQLITE_STATIC);\n    return;\n  }\n\n  for(cnt=0; cnt<2; cnt++){\n    UChar *zNew = sqlite3_realloc(zOutput, nOut);\n    if( zNew==0 ){\n      sqlite3_free(zOutput);\n      sqlite3_result_error_nomem(p);\n      return;\n    }\n    zOutput = zNew;\n    status = U_ZERO_ERROR;\n    if( bToUpper ){\n      nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);\n    }else{\n      nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);\n    }\n\n    if( U_SUCCESS(status) ){\n      sqlite3_result_text16(p, zOutput, nOut, xFree);\n    }else if( status==U_BUFFER_OVERFLOW_ERROR ){\n      assert( cnt==0 );\n      continue;\n    }else{\n      icuFunctionError(p, bToUpper ? \"u_strToUpper\" : \"u_strToLower\", status);\n    }\n    return;\n  }\n  assert( 0 );     /* Unreachable */\n}\n\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */\n\n/*\n** Collation sequence destructor function. The pCtx argument points to\n** a UCollator structure previously allocated using ucol_open().\n*/\nstatic void icuCollationDel(void *pCtx){\n  UCollator *p = (UCollator *)pCtx;\n  ucol_close(p);\n}\n\n/*\n** Collation sequence comparison function. The pCtx argument points to\n** a UCollator structure previously allocated using ucol_open().\n*/\nstatic int icuCollationColl(\n  void *pCtx,\n  int nLeft,\n  const void *zLeft,\n  int nRight,\n  const void *zRight\n){\n  UCollationResult res;\n  UCollator *p = (UCollator *)pCtx;\n  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);\n  switch( res ){\n    case UCOL_LESS:    return -1;\n    case UCOL_GREATER: return +1;\n    case UCOL_EQUAL:   return 0;\n  }\n  assert(!\"Unexpected return value from ucol_strcoll()\");\n  return 0;\n}\n\n/*\n** Implementation of the scalar function icu_load_collation().\n**\n** This scalar function is used to add ICU collation based collation \n** types to an SQLite database connection. It is intended to be called\n** as follows:\n**\n**     SELECT icu_load_collation(<locale>, <collation-name>);\n**\n** Where <locale> is a string containing an ICU locale identifier (i.e.\n** \"en_AU\", \"tr_TR\" etc.) and <collation-name> is the name of the\n** collation sequence to create.\n*/\nstatic void icuLoadCollation(\n  sqlite3_context *p, \n  int nArg, \n  sqlite3_value **apArg\n){\n  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);\n  UErrorCode status = U_ZERO_ERROR;\n  const char *zLocale;      /* Locale identifier - (eg. \"jp_JP\") */\n  const char *zName;        /* SQL Collation sequence name (eg. \"japanese\") */\n  UCollator *pUCollator;    /* ICU library collation object */\n  int rc;                   /* Return code from sqlite3_create_collation_x() */\n\n  assert(nArg==2);\n  (void)nArg; /* Unused parameter */\n  zLocale = (const char *)sqlite3_value_text(apArg[0]);\n  zName = (const char *)sqlite3_value_text(apArg[1]);\n\n  if( !zLocale || !zName ){\n    return;\n  }\n\n  pUCollator = ucol_open(zLocale, &status);\n  if( !U_SUCCESS(status) ){\n    icuFunctionError(p, \"ucol_open\", status);\n    return;\n  }\n  assert(p);\n\n  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, \n      icuCollationColl, icuCollationDel\n  );\n  if( rc!=SQLITE_OK ){\n    ucol_close(pUCollator);\n    sqlite3_result_error(p, \"Error registering collation function\", -1);\n  }\n}\n\n/*\n** Register the ICU extension functions with database db.\n*/\nSQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){\n# define SQLITEICU_EXTRAFLAGS (SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS)\n  static const struct IcuScalar {\n    const char *zName;                        /* Function name */\n    unsigned char nArg;                       /* Number of arguments */\n    unsigned int enc;                         /* Optimal text encoding */\n    unsigned char iContext;                   /* sqlite3_user_data() context */\n    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);\n  } scalars[] = {\n    {\"icu_load_collation\",2,SQLITE_UTF8|SQLITE_DIRECTONLY,1, icuLoadCollation},\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)\n    {\"regexp\", 2, SQLITE_ANY|SQLITEICU_EXTRAFLAGS,         0, icuRegexpFunc},\n    {\"lower\",  1, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS,       0, icuCaseFunc16},\n    {\"lower\",  2, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS,       0, icuCaseFunc16},\n    {\"upper\",  1, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS,       1, icuCaseFunc16},\n    {\"upper\",  2, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS,       1, icuCaseFunc16},\n    {\"lower\",  1, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        0, icuCaseFunc16},\n    {\"lower\",  2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        0, icuCaseFunc16},\n    {\"upper\",  1, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        1, icuCaseFunc16},\n    {\"upper\",  2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        1, icuCaseFunc16},\n    {\"like\",   2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        0, icuLikeFunc},\n    {\"like\",   3, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        0, icuLikeFunc},\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */\n  };\n  int rc = SQLITE_OK;\n  int i;\n  \n  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){\n    const struct IcuScalar *p = &scalars[i];\n    rc = sqlite3_create_function(\n        db, p->zName, p->nArg, p->enc, \n        p->iContext ? (void*)db : (void*)0,\n        p->xFunc, 0, 0\n    );\n  }\n\n  return rc;\n}\n\n#if !SQLITE_CORE\n#ifdef _WIN32\n__declspec(dllexport)\n#endif\nSQLITE_API int sqlite3_icu_init(\n  sqlite3 *db, \n  char **pzErrMsg,\n  const sqlite3_api_routines *pApi\n){\n  SQLITE_EXTENSION_INIT2(pApi)\n  return sqlite3IcuInit(db);\n}\n#endif\n\n#endif\n\n/************** End of icu.c *************************************************/\n/************** Begin file fts3_icu.c ****************************************/\n/*\n** 2007 June 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file implements a tokenizer for fts3 based on the ICU library.\n*/\n/* #include \"fts3Int.h\" */\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n#ifdef SQLITE_ENABLE_ICU\n\n/* #include <assert.h> */\n/* #include <string.h> */\n/* #include \"fts3_tokenizer.h\" */\n\n#include <unicode/ubrk.h>\n/* #include <unicode/ucol.h> */\n/* #include <unicode/ustring.h> */\n#include <unicode/utf16.h>\n\ntypedef struct IcuTokenizer IcuTokenizer;\ntypedef struct IcuCursor IcuCursor;\n\nstruct IcuTokenizer {\n  sqlite3_tokenizer base;\n  char *zLocale;\n};\n\nstruct IcuCursor {\n  sqlite3_tokenizer_cursor base;\n\n  UBreakIterator *pIter;      /* ICU break-iterator object */\n  int nChar;                  /* Number of UChar elements in pInput */\n  UChar *aChar;               /* Copy of input using utf-16 encoding */\n  int *aOffset;               /* Offsets of each character in utf-8 input */\n\n  int nBuffer;\n  char *zBuffer;\n\n  int iToken;\n};\n\n/*\n** Create a new tokenizer instance.\n*/\nstatic int icuCreate(\n  int argc,                            /* Number of entries in argv[] */\n  const char * const *argv,            /* Tokenizer creation arguments */\n  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */\n){\n  IcuTokenizer *p;\n  int n = 0;\n\n  if( argc>0 ){\n    n = strlen(argv[0])+1;\n  }\n  p = (IcuTokenizer *)sqlite3_malloc64(sizeof(IcuTokenizer)+n);\n  if( !p ){\n    return SQLITE_NOMEM;\n  }\n  memset(p, 0, sizeof(IcuTokenizer));\n\n  if( n ){\n    p->zLocale = (char *)&p[1];\n    memcpy(p->zLocale, argv[0], n);\n  }\n\n  *ppTokenizer = (sqlite3_tokenizer *)p;\n\n  return SQLITE_OK;\n}\n\n/*\n** Destroy a tokenizer\n*/\nstatic int icuDestroy(sqlite3_tokenizer *pTokenizer){\n  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;\n  sqlite3_free(p);\n  return SQLITE_OK;\n}\n\n/*\n** Prepare to begin tokenizing a particular string.  The input\n** string to be tokenized is pInput[0..nBytes-1].  A cursor\n** used to incrementally tokenize this string is returned in \n** *ppCursor.\n*/\nstatic int icuOpen(\n  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */\n  const char *zInput,                    /* Input string */\n  int nInput,                            /* Length of zInput in bytes */\n  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */\n){\n  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;\n  IcuCursor *pCsr;\n\n  const int32_t opt = U_FOLD_CASE_DEFAULT;\n  UErrorCode status = U_ZERO_ERROR;\n  int nChar;\n\n  UChar32 c;\n  int iInput = 0;\n  int iOut = 0;\n\n  *ppCursor = 0;\n\n  if( zInput==0 ){\n    nInput = 0;\n    zInput = \"\";\n  }else if( nInput<0 ){\n    nInput = strlen(zInput);\n  }\n  nChar = nInput+1;\n  pCsr = (IcuCursor *)sqlite3_malloc64(\n      sizeof(IcuCursor) +                /* IcuCursor */\n      ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */\n      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */\n  );\n  if( !pCsr ){\n    return SQLITE_NOMEM;\n  }\n  memset(pCsr, 0, sizeof(IcuCursor));\n  pCsr->aChar = (UChar *)&pCsr[1];\n  pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];\n\n  pCsr->aOffset[iOut] = iInput;\n  U8_NEXT(zInput, iInput, nInput, c); \n  while( c>0 ){\n    int isError = 0;\n    c = u_foldCase(c, opt);\n    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);\n    if( isError ){\n      sqlite3_free(pCsr);\n      return SQLITE_ERROR;\n    }\n    pCsr->aOffset[iOut] = iInput;\n\n    if( iInput<nInput ){\n      U8_NEXT(zInput, iInput, nInput, c);\n    }else{\n      c = 0;\n    }\n  }\n\n  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);\n  if( !U_SUCCESS(status) ){\n    sqlite3_free(pCsr);\n    return SQLITE_ERROR;\n  }\n  pCsr->nChar = iOut;\n\n  ubrk_first(pCsr->pIter);\n  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;\n  return SQLITE_OK;\n}\n\n/*\n** Close a tokenization cursor previously opened by a call to icuOpen().\n*/\nstatic int icuClose(sqlite3_tokenizer_cursor *pCursor){\n  IcuCursor *pCsr = (IcuCursor *)pCursor;\n  ubrk_close(pCsr->pIter);\n  sqlite3_free(pCsr->zBuffer);\n  sqlite3_free(pCsr);\n  return SQLITE_OK;\n}\n\n/*\n** Extract the next token from a tokenization cursor.\n*/\nstatic int icuNext(\n  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */\n  const char **ppToken,               /* OUT: *ppToken is the token text */\n  int *pnBytes,                       /* OUT: Number of bytes in token */\n  int *piStartOffset,                 /* OUT: Starting offset of token */\n  int *piEndOffset,                   /* OUT: Ending offset of token */\n  int *piPosition                     /* OUT: Position integer of token */\n){\n  IcuCursor *pCsr = (IcuCursor *)pCursor;\n\n  int iStart = 0;\n  int iEnd = 0;\n  int nByte = 0;\n\n  while( iStart==iEnd ){\n    UChar32 c;\n\n    iStart = ubrk_current(pCsr->pIter);\n    iEnd = ubrk_next(pCsr->pIter);\n    if( iEnd==UBRK_DONE ){\n      return SQLITE_DONE;\n    }\n\n    while( iStart<iEnd ){\n      int iWhite = iStart;\n      U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);\n      if( u_isspace(c) ){\n        iStart = iWhite;\n      }else{\n        break;\n      }\n    }\n    assert(iStart<=iEnd);\n  }\n\n  do {\n    UErrorCode status = U_ZERO_ERROR;\n    if( nByte ){\n      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);\n      if( !zNew ){\n        return SQLITE_NOMEM;\n      }\n      pCsr->zBuffer = zNew;\n      pCsr->nBuffer = nByte;\n    }\n\n    u_strToUTF8(\n        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */\n        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */\n        &status                                  /* Output success/failure */\n    );\n  } while( nByte>pCsr->nBuffer );\n\n  *ppToken = pCsr->zBuffer;\n  *pnBytes = nByte;\n  *piStartOffset = pCsr->aOffset[iStart];\n  *piEndOffset = pCsr->aOffset[iEnd];\n  *piPosition = pCsr->iToken++;\n\n  return SQLITE_OK;\n}\n\n/*\n** The set of routines that implement the simple tokenizer\n*/\nstatic const sqlite3_tokenizer_module icuTokenizerModule = {\n  0,                           /* iVersion    */\n  icuCreate,                   /* xCreate     */\n  icuDestroy,                  /* xCreate     */\n  icuOpen,                     /* xOpen       */\n  icuClose,                    /* xClose      */\n  icuNext,                     /* xNext       */\n  0,                           /* xLanguageid */\n};\n\n/*\n** Set *ppModule to point at the implementation of the ICU tokenizer.\n*/\nSQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(\n  sqlite3_tokenizer_module const**ppModule\n){\n  *ppModule = &icuTokenizerModule;\n}\n\n#endif /* defined(SQLITE_ENABLE_ICU) */\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n\n/************** End of fts3_icu.c ********************************************/\n/************** Begin file sqlite3rbu.c **************************************/\n/*\n** 2014 August 30\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n**\n** OVERVIEW \n**\n**  The RBU extension requires that the RBU update be packaged as an\n**  SQLite database. The tables it expects to find are described in\n**  sqlite3rbu.h.  Essentially, for each table xyz in the target database\n**  that the user wishes to write to, a corresponding data_xyz table is\n**  created in the RBU database and populated with one row for each row to\n**  update, insert or delete from the target table.\n** \n**  The update proceeds in three stages:\n** \n**  1) The database is updated. The modified database pages are written\n**     to a *-oal file. A *-oal file is just like a *-wal file, except\n**     that it is named \"<database>-oal\" instead of \"<database>-wal\".\n**     Because regular SQLite clients do not look for file named\n**     \"<database>-oal\", they go on using the original database in\n**     rollback mode while the *-oal file is being generated.\n** \n**     During this stage RBU does not update the database by writing\n**     directly to the target tables. Instead it creates \"imposter\"\n**     tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses\n**     to update each b-tree individually. All updates required by each\n**     b-tree are completed before moving on to the next, and all\n**     updates are done in sorted key order.\n** \n**  2) The \"<database>-oal\" file is moved to the equivalent \"<database>-wal\"\n**     location using a call to rename(2). Before doing this the RBU\n**     module takes an EXCLUSIVE lock on the database file, ensuring\n**     that there are no other active readers.\n** \n**     Once the EXCLUSIVE lock is released, any other database readers\n**     detect the new *-wal file and read the database in wal mode. At\n**     this point they see the new version of the database - including\n**     the updates made as part of the RBU update.\n** \n**  3) The new *-wal file is checkpointed. This proceeds in the same way \n**     as a regular database checkpoint, except that a single frame is\n**     checkpointed each time sqlite3rbu_step() is called. If the RBU\n**     handle is closed before the entire *-wal file is checkpointed,\n**     the checkpoint progress is saved in the RBU database and the\n**     checkpoint can be resumed by another RBU client at some point in\n**     the future.\n**\n** POTENTIAL PROBLEMS\n** \n**  The rename() call might not be portable. And RBU is not currently\n**  syncing the directory after renaming the file.\n**\n**  When state is saved, any commit to the *-oal file and the commit to\n**  the RBU update database are not atomic. So if the power fails at the\n**  wrong moment they might get out of sync. As the main database will be\n**  committed before the RBU update database this will likely either just\n**  pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE\n**  constraint violations).\n**\n**  If some client does modify the target database mid RBU update, or some\n**  other error occurs, the RBU extension will keep throwing errors. It's\n**  not really clear how to get out of this state. The system could just\n**  by delete the RBU update database and *-oal file and have the device\n**  download the update again and start over.\n**\n**  At present, for an UPDATE, both the new.* and old.* records are\n**  collected in the rbu_xyz table. And for both UPDATEs and DELETEs all\n**  fields are collected.  This means we're probably writing a lot more\n**  data to disk when saving the state of an ongoing update to the RBU\n**  update database than is strictly necessary.\n** \n*/\n\n/* #include <assert.h> */\n/* #include <string.h> */\n/* #include <stdio.h> */\n\n/* #include \"sqlite3.h\" */\n\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)\n/************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/\n/************** Begin file sqlite3rbu.h **************************************/\n/*\n** 2014 August 30\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains the public interface for the RBU extension. \n*/\n\n/*\n** SUMMARY\n**\n** Writing a transaction containing a large number of operations on \n** b-tree indexes that are collectively larger than the available cache\n** memory can be very inefficient. \n**\n** The problem is that in order to update a b-tree, the leaf page (at least)\n** containing the entry being inserted or deleted must be modified. If the\n** working set of leaves is larger than the available cache memory, then a \n** single leaf that is modified more than once as part of the transaction \n** may be loaded from or written to the persistent media multiple times.\n** Additionally, because the index updates are likely to be applied in\n** random order, access to pages within the database is also likely to be in \n** random order, which is itself quite inefficient.\n**\n** One way to improve the situation is to sort the operations on each index\n** by index key before applying them to the b-tree. This leads to an IO\n** pattern that resembles a single linear scan through the index b-tree,\n** and all but guarantees each modified leaf page is loaded and stored \n** exactly once. SQLite uses this trick to improve the performance of\n** CREATE INDEX commands. This extension allows it to be used to improve\n** the performance of large transactions on existing databases.\n**\n** Additionally, this extension allows the work involved in writing the \n** large transaction to be broken down into sub-transactions performed \n** sequentially by separate processes. This is useful if the system cannot \n** guarantee that a single update process will run for long enough to apply \n** the entire update, for example because the update is being applied on a \n** mobile device that is frequently rebooted. Even after the writer process \n** has committed one or more sub-transactions, other database clients continue\n** to read from the original database snapshot. In other words, partially \n** applied transactions are not visible to other clients. \n**\n** \"RBU\" stands for \"Resumable Bulk Update\". As in a large database update\n** transmitted via a wireless network to a mobile device. A transaction\n** applied using this extension is hence refered to as an \"RBU update\".\n**\n**\n** LIMITATIONS\n**\n** An \"RBU update\" transaction is subject to the following limitations:\n**\n**   * The transaction must consist of INSERT, UPDATE and DELETE operations\n**     only.\n**\n**   * INSERT statements may not use any default values.\n**\n**   * UPDATE and DELETE statements must identify their target rows by \n**     non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY\n**     KEY fields may not be updated or deleted. If the table being written \n**     has no PRIMARY KEY, affected rows must be identified by rowid.\n**\n**   * UPDATE statements may not modify PRIMARY KEY columns.\n**\n**   * No triggers will be fired.\n**\n**   * No foreign key violations are detected or reported.\n**\n**   * CHECK constraints are not enforced.\n**\n**   * No constraint handling mode except for \"OR ROLLBACK\" is supported.\n**\n**\n** PREPARATION\n**\n** An \"RBU update\" is stored as a separate SQLite database. A database\n** containing an RBU update is an \"RBU database\". For each table in the \n** target database to be updated, the RBU database should contain a table\n** named \"data_<target name>\" containing the same set of columns as the\n** target table, and one more - \"rbu_control\". The data_% table should \n** have no PRIMARY KEY or UNIQUE constraints, but each column should have\n** the same type as the corresponding column in the target database.\n** The \"rbu_control\" column should have no type at all. For example, if\n** the target database contains:\n**\n**   CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);\n**\n** Then the RBU database should contain:\n**\n**   CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);\n**\n** The order of the columns in the data_% table does not matter.\n**\n** Instead of a regular table, the RBU database may also contain virtual\n** tables or view named using the data_<target> naming scheme. \n**\n** Instead of the plain data_<target> naming scheme, RBU database tables \n** may also be named data<integer>_<target>, where <integer> is any sequence\n** of zero or more numeric characters (0-9). This can be significant because\n** tables within the RBU database are always processed in order sorted by \n** name. By judicious selection of the <integer> portion of the names\n** of the RBU tables the user can therefore control the order in which they\n** are processed. This can be useful, for example, to ensure that \"external\n** content\" FTS4 tables are updated before their underlying content tables.\n**\n** If the target database table is a virtual table or a table that has no\n** PRIMARY KEY declaration, the data_% table must also contain a column \n** named \"rbu_rowid\". This column is mapped to the tables implicit primary \n** key column - \"rowid\". Virtual tables for which the \"rowid\" column does \n** not function like a primary key value cannot be updated using RBU. For \n** example, if the target db contains either of the following:\n**\n**   CREATE VIRTUAL TABLE x1 USING fts3(a, b);\n**   CREATE TABLE x1(a, b)\n**\n** then the RBU database should contain:\n**\n**   CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);\n**\n** All non-hidden columns (i.e. all columns matched by \"SELECT *\") of the\n** target table must be present in the input table. For virtual tables,\n** hidden columns are optional - they are updated by RBU if present in\n** the input table, or not otherwise. For example, to write to an fts4\n** table with a hidden languageid column such as:\n**\n**   CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');\n**\n** Either of the following input table schemas may be used:\n**\n**   CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);\n**   CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);\n**\n** For each row to INSERT into the target database as part of the RBU \n** update, the corresponding data_% table should contain a single record\n** with the \"rbu_control\" column set to contain integer value 0. The\n** other columns should be set to the values that make up the new record \n** to insert. \n**\n** If the target database table has an INTEGER PRIMARY KEY, it is not \n** possible to insert a NULL value into the IPK column. Attempting to \n** do so results in an SQLITE_MISMATCH error.\n**\n** For each row to DELETE from the target database as part of the RBU \n** update, the corresponding data_% table should contain a single record\n** with the \"rbu_control\" column set to contain integer value 1. The\n** real primary key values of the row to delete should be stored in the\n** corresponding columns of the data_% table. The values stored in the\n** other columns are not used.\n**\n** For each row to UPDATE from the target database as part of the RBU \n** update, the corresponding data_% table should contain a single record\n** with the \"rbu_control\" column set to contain a value of type text.\n** The real primary key values identifying the row to update should be \n** stored in the corresponding columns of the data_% table row, as should\n** the new values of all columns being update. The text value in the \n** \"rbu_control\" column must contain the same number of characters as\n** there are columns in the target database table, and must consist entirely\n** of 'x' and '.' characters (or in some special cases 'd' - see below). For \n** each column that is being updated, the corresponding character is set to\n** 'x'. For those that remain as they are, the corresponding character of the\n** rbu_control value should be set to '.'. For example, given the tables \n** above, the update statement:\n**\n**   UPDATE t1 SET c = 'usa' WHERE a = 4;\n**\n** is represented by the data_t1 row created by:\n**\n**   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');\n**\n** Instead of an 'x' character, characters of the rbu_control value specified\n** for UPDATEs may also be set to 'd'. In this case, instead of updating the\n** target table with the value stored in the corresponding data_% column, the\n** user-defined SQL function \"rbu_delta()\" is invoked and the result stored in\n** the target table column. rbu_delta() is invoked with two arguments - the\n** original value currently stored in the target table column and the \n** value specified in the data_xxx table.\n**\n** For example, this row:\n**\n**   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');\n**\n** is similar to an UPDATE statement such as: \n**\n**   UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;\n**\n** Finally, if an 'f' character appears in place of a 'd' or 's' in an \n** ota_control string, the contents of the data_xxx table column is assumed\n** to be a \"fossil delta\" - a patch to be applied to a blob value in the\n** format used by the fossil source-code management system. In this case\n** the existing value within the target database table must be of type BLOB. \n** It is replaced by the result of applying the specified fossil delta to\n** itself.\n**\n** If the target database table is a virtual table or a table with no PRIMARY\n** KEY, the rbu_control value should not include a character corresponding \n** to the rbu_rowid value. For example, this:\n**\n**   INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control) \n**       VALUES(NULL, 'usa', 12, '.x');\n**\n** causes a result similar to:\n**\n**   UPDATE ft1 SET b = 'usa' WHERE rowid = 12;\n**\n** The data_xxx tables themselves should have no PRIMARY KEY declarations.\n** However, RBU is more efficient if reading the rows in from each data_xxx\n** table in \"rowid\" order is roughly the same as reading them sorted by\n** the PRIMARY KEY of the corresponding target database table. In other \n** words, rows should be sorted using the destination table PRIMARY KEY \n** fields before they are inserted into the data_xxx tables.\n**\n** USAGE\n**\n** The API declared below allows an application to apply an RBU update \n** stored on disk to an existing target database. Essentially, the \n** application:\n**\n**     1) Opens an RBU handle using the sqlite3rbu_open() function.\n**\n**     2) Registers any required virtual table modules with the database\n**        handle returned by sqlite3rbu_db(). Also, if required, register\n**        the rbu_delta() implementation.\n**\n**     3) Calls the sqlite3rbu_step() function one or more times on\n**        the new handle. Each call to sqlite3rbu_step() performs a single\n**        b-tree operation, so thousands of calls may be required to apply \n**        a complete update.\n**\n**     4) Calls sqlite3rbu_close() to close the RBU update handle. If\n**        sqlite3rbu_step() has been called enough times to completely\n**        apply the update to the target database, then the RBU database\n**        is marked as fully applied. Otherwise, the state of the RBU \n**        update application is saved in the RBU database for later \n**        resumption.\n**\n** See comments below for more detail on APIs.\n**\n** If an update is only partially applied to the target database by the\n** time sqlite3rbu_close() is called, various state information is saved \n** within the RBU database. This allows subsequent processes to automatically\n** resume the RBU update from where it left off.\n**\n** To remove all RBU extension state information, returning an RBU database \n** to its original contents, it is sufficient to drop all tables that begin\n** with the prefix \"rbu_\"\n**\n** DATABASE LOCKING\n**\n** An RBU update may not be applied to a database in WAL mode. Attempting\n** to do so is an error (SQLITE_ERROR).\n**\n** While an RBU handle is open, a SHARED lock may be held on the target\n** database file. This means it is possible for other clients to read the\n** database, but not to write it.\n**\n** If an RBU update is started and then suspended before it is completed,\n** then an external client writes to the database, then attempting to resume\n** the suspended RBU update is also an error (SQLITE_BUSY).\n*/\n\n#ifndef _SQLITE3RBU_H\n#define _SQLITE3RBU_H\n\n/* #include \"sqlite3.h\"              ** Required for error code definitions ** */\n\n#if 0\nextern \"C\" {\n#endif\n\ntypedef struct sqlite3rbu sqlite3rbu;\n\n/*\n** Open an RBU handle.\n**\n** Argument zTarget is the path to the target database. Argument zRbu is\n** the path to the RBU database. Each call to this function must be matched\n** by a call to sqlite3rbu_close(). When opening the databases, RBU passes\n** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget\n** or zRbu begin with \"file:\", it will be interpreted as an SQLite \n** database URI, not a regular file name.\n**\n** If the zState argument is passed a NULL value, the RBU extension stores \n** the current state of the update (how many rows have been updated, which \n** indexes are yet to be updated etc.) within the RBU database itself. This\n** can be convenient, as it means that the RBU application does not need to\n** organize removing a separate state file after the update is concluded. \n** Or, if zState is non-NULL, it must be a path to a database file in which \n** the RBU extension can store the state of the update.\n**\n** When resuming an RBU update, the zState argument must be passed the same\n** value as when the RBU update was started.\n**\n** Once the RBU update is finished, the RBU extension does not \n** automatically remove any zState database file, even if it created it.\n**\n** By default, RBU uses the default VFS to access the files on disk. To\n** use a VFS other than the default, an SQLite \"file:\" URI containing a\n** \"vfs=...\" option may be passed as the zTarget option.\n**\n** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of\n** SQLite's built-in VFSs, including the multiplexor VFS. However it does\n** not work out of the box with zipvfs. Refer to the comment describing\n** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.\n*/\nSQLITE_API sqlite3rbu *sqlite3rbu_open(\n  const char *zTarget, \n  const char *zRbu,\n  const char *zState\n);\n\n/*\n** Open an RBU handle to perform an RBU vacuum on database file zTarget.\n** An RBU vacuum is similar to SQLite's built-in VACUUM command, except\n** that it can be suspended and resumed like an RBU update.\n**\n** The second argument to this function identifies a database in which \n** to store the state of the RBU vacuum operation if it is suspended. The \n** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum\n** operation, the state database should either not exist or be empty\n** (contain no tables). If an RBU vacuum is suspended by calling \n** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has\n** returned SQLITE_DONE, the vacuum state is stored in the state database. \n** The vacuum can be resumed by calling this function to open a new RBU\n** handle specifying the same target and state databases.\n**\n** If the second argument passed to this function is NULL, then the\n** name of the state database is \"<database>-vacuum\", where <database>\n** is the name of the target database file. In this case, on UNIX, if the\n** state database is not already present in the file-system, it is created\n** with the same permissions as the target db is made. \n**\n** With an RBU vacuum, it is an SQLITE_MISUSE error if the name of the \n** state database ends with \"-vactmp\". This name is reserved for internal \n** use.\n**\n** This function does not delete the state database after an RBU vacuum\n** is completed, even if it created it. However, if the call to\n** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents\n** of the state tables within the state database are zeroed. This way,\n** the next call to sqlite3rbu_vacuum() opens a handle that starts a \n** new RBU vacuum operation.\n**\n** As with sqlite3rbu_open(), Zipvfs users should rever to the comment\n** describing the sqlite3rbu_create_vfs() API function below for \n** a description of the complications associated with using RBU with \n** zipvfs databases.\n*/\nSQLITE_API sqlite3rbu *sqlite3rbu_vacuum(\n  const char *zTarget, \n  const char *zState\n);\n\n/*\n** Configure a limit for the amount of temp space that may be used by\n** the RBU handle passed as the first argument. The new limit is specified\n** in bytes by the second parameter. If it is positive, the limit is updated.\n** If the second parameter to this function is passed zero, then the limit\n** is removed entirely. If the second parameter is negative, the limit is\n** not modified (this is useful for querying the current limit).\n**\n** In all cases the returned value is the current limit in bytes (zero \n** indicates unlimited).\n**\n** If the temp space limit is exceeded during operation, an SQLITE_FULL\n** error is returned.\n*/\nSQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu*, sqlite3_int64);\n\n/*\n** Return the current amount of temp file space, in bytes, currently used by \n** the RBU handle passed as the only argument.\n*/\nSQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);\n\n/*\n** Internally, each RBU connection uses a separate SQLite database \n** connection to access the target and rbu update databases. This\n** API allows the application direct access to these database handles.\n**\n** The first argument passed to this function must be a valid, open, RBU\n** handle. The second argument should be passed zero to access the target\n** database handle, or non-zero to access the rbu update database handle.\n** Accessing the underlying database handles may be useful in the\n** following scenarios:\n**\n**   * If any target tables are virtual tables, it may be necessary to\n**     call sqlite3_create_module() on the target database handle to \n**     register the required virtual table implementations.\n**\n**   * If the data_xxx tables in the RBU source database are virtual \n**     tables, the application may need to call sqlite3_create_module() on\n**     the rbu update db handle to any required virtual table\n**     implementations.\n**\n**   * If the application uses the \"rbu_delta()\" feature described above,\n**     it must use sqlite3_create_function() or similar to register the\n**     rbu_delta() implementation with the target database handle.\n**\n** If an error has occurred, either while opening or stepping the RBU object,\n** this function may return NULL. The error code and message may be collected\n** when sqlite3rbu_close() is called.\n**\n** Database handles returned by this function remain valid until the next\n** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().\n*/\nSQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);\n\n/*\n** Do some work towards applying the RBU update to the target db. \n**\n** Return SQLITE_DONE if the update has been completely applied, or \n** SQLITE_OK if no error occurs but there remains work to do to apply\n** the RBU update. If an error does occur, some other error code is \n** returned. \n**\n** Once a call to sqlite3rbu_step() has returned a value other than\n** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops\n** that immediately return the same value.\n*/\nSQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);\n\n/*\n** Force RBU to save its state to disk.\n**\n** If a power failure or application crash occurs during an update, following\n** system recovery RBU may resume the update from the point at which the state\n** was last saved. In other words, from the most recent successful call to \n** sqlite3rbu_close() or this function.\n**\n** SQLITE_OK is returned if successful, or an SQLite error code otherwise.\n*/\nSQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);\n\n/*\n** Close an RBU handle. \n**\n** If the RBU update has been completely applied, mark the RBU database\n** as fully applied. Otherwise, assuming no error has occurred, save the\n** current state of the RBU update appliation to the RBU database.\n**\n** If an error has already occurred as part of an sqlite3rbu_step()\n** or sqlite3rbu_open() call, or if one occurs within this function, an\n** SQLite error code is returned. Additionally, if pzErrmsg is not NULL,\n** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted\n** English language error message. It is the responsibility of the caller to\n** eventually free any such buffer using sqlite3_free().\n**\n** Otherwise, if no error occurs, this function returns SQLITE_OK if the\n** update has been partially applied, or SQLITE_DONE if it has been \n** completely applied.\n*/\nSQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);\n\n/*\n** Return the total number of key-value operations (inserts, deletes or \n** updates) that have been performed on the target database since the\n** current RBU update was started.\n*/\nSQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);\n\n/*\n** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100) \n** progress indications for the two stages of an RBU update. This API may\n** be useful for driving GUI progress indicators and similar.\n**\n** An RBU update is divided into two stages:\n**\n**   * Stage 1, in which changes are accumulated in an oal/wal file, and\n**   * Stage 2, in which the contents of the wal file are copied into the\n**     main database.\n**\n** The update is visible to non-RBU clients during stage 2. During stage 1\n** non-RBU reader clients may see the original database.\n**\n** If this API is called during stage 2 of the update, output variable \n** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)\n** to a value between 0 and 10000 to indicate the permyriadage progress of\n** stage 2. A value of 5000 indicates that stage 2 is half finished, \n** 9000 indicates that it is 90% finished, and so on.\n**\n** If this API is called during stage 1 of the update, output variable \n** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The\n** value to which (*pnOne) is set depends on whether or not the RBU \n** database contains an \"rbu_count\" table. The rbu_count table, if it \n** exists, must contain the same columns as the following:\n**\n**   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;\n**\n** There must be one row in the table for each source (data_xxx) table within\n** the RBU database. The 'tbl' column should contain the name of the source\n** table. The 'cnt' column should contain the number of rows within the\n** source table.\n**\n** If the rbu_count table is present and populated correctly and this\n** API is called during stage 1, the *pnOne output variable is set to the\n** permyriadage progress of the same stage. If the rbu_count table does\n** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count\n** table exists but is not correctly populated, the value of the *pnOne\n** output variable during stage 1 is undefined.\n*/\nSQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int*pnTwo);\n\n/*\n** Obtain an indication as to the current stage of an RBU update or vacuum.\n** This function always returns one of the SQLITE_RBU_STATE_XXX constants\n** defined in this file. Return values should be interpreted as follows:\n**\n** SQLITE_RBU_STATE_OAL:\n**   RBU is currently building a *-oal file. The next call to sqlite3rbu_step()\n**   may either add further data to the *-oal file, or compute data that will\n**   be added by a subsequent call.\n**\n** SQLITE_RBU_STATE_MOVE:\n**   RBU has finished building the *-oal file. The next call to sqlite3rbu_step()\n**   will move the *-oal file to the equivalent *-wal path. If the current\n**   operation is an RBU update, then the updated version of the database\n**   file will become visible to ordinary SQLite clients following the next\n**   call to sqlite3rbu_step().\n**\n** SQLITE_RBU_STATE_CHECKPOINT:\n**   RBU is currently performing an incremental checkpoint. The next call to\n**   sqlite3rbu_step() will copy a page of data from the *-wal file into\n**   the target database file.\n**\n** SQLITE_RBU_STATE_DONE:\n**   The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()\n**   will immediately return SQLITE_DONE.\n**\n** SQLITE_RBU_STATE_ERROR:\n**   An error has occurred. Any subsequent calls to sqlite3rbu_step() will\n**   immediately return the SQLite error code associated with the error.\n*/\n#define SQLITE_RBU_STATE_OAL        1\n#define SQLITE_RBU_STATE_MOVE       2\n#define SQLITE_RBU_STATE_CHECKPOINT 3\n#define SQLITE_RBU_STATE_DONE       4\n#define SQLITE_RBU_STATE_ERROR      5\n\nSQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);\n\n/*\n** Create an RBU VFS named zName that accesses the underlying file-system\n** via existing VFS zParent. Or, if the zParent parameter is passed NULL, \n** then the new RBU VFS uses the default system VFS to access the file-system.\n** The new object is registered as a non-default VFS with SQLite before \n** returning.\n**\n** Part of the RBU implementation uses a custom VFS object. Usually, this\n** object is created and deleted automatically by RBU. \n**\n** The exception is for applications that also use zipvfs. In this case,\n** the custom VFS must be explicitly created by the user before the RBU\n** handle is opened. The RBU VFS should be installed so that the zipvfs\n** VFS uses the RBU VFS, which in turn uses any other VFS layers in use \n** (for example multiplexor) to access the file-system. For example,\n** to assemble an RBU enabled VFS stack that uses both zipvfs and \n** multiplexor (error checking omitted):\n**\n**     // Create a VFS named \"multiplex\" (not the default).\n**     sqlite3_multiplex_initialize(0, 0);\n**\n**     // Create an rbu VFS named \"rbu\" that uses multiplexor. If the\n**     // second argument were replaced with NULL, the \"rbu\" VFS would\n**     // access the file-system via the system default VFS, bypassing the\n**     // multiplexor.\n**     sqlite3rbu_create_vfs(\"rbu\", \"multiplex\");\n**\n**     // Create a zipvfs VFS named \"zipvfs\" that uses rbu.\n**     zipvfs_create_vfs_v3(\"zipvfs\", \"rbu\", 0, xCompressorAlgorithmDetector);\n**\n**     // Make zipvfs the default VFS.\n**     sqlite3_vfs_register(sqlite3_vfs_find(\"zipvfs\"), 1);\n**\n** Because the default VFS created above includes a RBU functionality, it\n** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack\n** that does not include the RBU layer results in an error.\n**\n** The overhead of adding the \"rbu\" VFS to the system is negligible for \n** non-RBU users. There is no harm in an application accessing the \n** file-system via \"rbu\" all the time, even if it only uses RBU functionality \n** occasionally.\n*/\nSQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);\n\n/*\n** Deregister and destroy an RBU vfs created by an earlier call to\n** sqlite3rbu_create_vfs().\n**\n** VFS objects are not reference counted. If a VFS object is destroyed\n** before all database handles that use it have been closed, the results\n** are undefined.\n*/\nSQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);\n\n#if 0\n}  /* end of the 'extern \"C\"' block */\n#endif\n\n#endif /* _SQLITE3RBU_H */\n\n/************** End of sqlite3rbu.h ******************************************/\n/************** Continuing where we left off in sqlite3rbu.c *****************/\n\n#if defined(_WIN32_WCE)\n/* #include \"windows.h\" */\n#endif\n\n/* Maximum number of prepared UPDATE statements held by this module */\n#define SQLITE_RBU_UPDATE_CACHESIZE 16\n\n/* Delta checksums disabled by default.  Compile with -DRBU_ENABLE_DELTA_CKSUM\n** to enable checksum verification.\n*/\n#ifndef RBU_ENABLE_DELTA_CKSUM\n# define RBU_ENABLE_DELTA_CKSUM 0\n#endif\n\n/*\n** Swap two objects of type TYPE.\n*/\n#if !defined(SQLITE_AMALGAMATION)\n# define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}\n#endif\n\n/*\n** The rbu_state table is used to save the state of a partially applied\n** update so that it can be resumed later. The table consists of integer\n** keys mapped to values as follows:\n**\n** RBU_STATE_STAGE:\n**   May be set to integer values 1, 2, 4 or 5. As follows:\n**       1: the *-rbu file is currently under construction.\n**       2: the *-rbu file has been constructed, but not yet moved \n**          to the *-wal path.\n**       4: the checkpoint is underway.\n**       5: the rbu update has been checkpointed.\n**\n** RBU_STATE_TBL:\n**   Only valid if STAGE==1. The target database name of the table \n**   currently being written.\n**\n** RBU_STATE_IDX:\n**   Only valid if STAGE==1. The target database name of the index \n**   currently being written, or NULL if the main table is currently being\n**   updated.\n**\n** RBU_STATE_ROW:\n**   Only valid if STAGE==1. Number of rows already processed for the current\n**   table/index.\n**\n** RBU_STATE_PROGRESS:\n**   Trbul number of sqlite3rbu_step() calls made so far as part of this\n**   rbu update.\n**\n** RBU_STATE_CKPT:\n**   Valid if STAGE==4. The 64-bit checksum associated with the wal-index\n**   header created by recovering the *-wal file. This is used to detect\n**   cases when another client appends frames to the *-wal file in the\n**   middle of an incremental checkpoint (an incremental checkpoint cannot\n**   be continued if this happens).\n**\n** RBU_STATE_COOKIE:\n**   Valid if STAGE==1. The current change-counter cookie value in the \n**   target db file.\n**\n** RBU_STATE_OALSZ:\n**   Valid if STAGE==1. The size in bytes of the *-oal file.\n**\n** RBU_STATE_DATATBL:\n**   Only valid if STAGE==1. The RBU database name of the table \n**   currently being read.\n*/\n#define RBU_STATE_STAGE        1\n#define RBU_STATE_TBL          2\n#define RBU_STATE_IDX          3\n#define RBU_STATE_ROW          4\n#define RBU_STATE_PROGRESS     5\n#define RBU_STATE_CKPT         6\n#define RBU_STATE_COOKIE       7\n#define RBU_STATE_OALSZ        8\n#define RBU_STATE_PHASEONESTEP 9\n#define RBU_STATE_DATATBL     10\n\n#define RBU_STAGE_OAL         1\n#define RBU_STAGE_MOVE        2\n#define RBU_STAGE_CAPTURE     3\n#define RBU_STAGE_CKPT        4\n#define RBU_STAGE_DONE        5\n\n\n#define RBU_CREATE_STATE \\\n  \"CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)\"\n\ntypedef struct RbuFrame RbuFrame;\ntypedef struct RbuObjIter RbuObjIter;\ntypedef struct RbuState RbuState;\ntypedef struct RbuSpan RbuSpan;\ntypedef struct rbu_vfs rbu_vfs;\ntypedef struct rbu_file rbu_file;\ntypedef struct RbuUpdateStmt RbuUpdateStmt;\n\n#if !defined(SQLITE_AMALGAMATION)\ntypedef unsigned int u32;\ntypedef unsigned short u16;\ntypedef unsigned char u8;\ntypedef sqlite3_int64 i64;\n#endif\n\n/*\n** These values must match the values defined in wal.c for the equivalent\n** locks. These are not magic numbers as they are part of the SQLite file\n** format.\n*/\n#define WAL_LOCK_WRITE  0\n#define WAL_LOCK_CKPT   1\n#define WAL_LOCK_READ0  3\n\n#define SQLITE_FCNTL_RBUCNT    5149216\n\n/*\n** A structure to store values read from the rbu_state table in memory.\n*/\nstruct RbuState {\n  int eStage;\n  char *zTbl;\n  char *zDataTbl;\n  char *zIdx;\n  i64 iWalCksum;\n  int nRow;\n  i64 nProgress;\n  u32 iCookie;\n  i64 iOalSz;\n  i64 nPhaseOneStep;\n};\n\nstruct RbuUpdateStmt {\n  char *zMask;                    /* Copy of update mask used with pUpdate */\n  sqlite3_stmt *pUpdate;          /* Last update statement (or NULL) */\n  RbuUpdateStmt *pNext;\n};\n\nstruct RbuSpan {\n  const char *zSpan;\n  int nSpan;\n};\n\n/*\n** An iterator of this type is used to iterate through all objects in\n** the target database that require updating. For each such table, the\n** iterator visits, in order:\n**\n**     * the table itself, \n**     * each index of the table (zero or more points to visit), and\n**     * a special \"cleanup table\" state.\n**\n** abIndexed:\n**   If the table has no indexes on it, abIndexed is set to NULL. Otherwise,\n**   it points to an array of flags nTblCol elements in size. The flag is\n**   set for each column that is either a part of the PK or a part of an\n**   index. Or clear otherwise.\n**\n**   If there are one or more partial indexes on the table, all fields of\n**   this array set set to 1. This is because in that case, the module has\n**   no way to tell which fields will be required to add and remove entries\n**   from the partial indexes.\n**   \n*/\nstruct RbuObjIter {\n  sqlite3_stmt *pTblIter;         /* Iterate through tables */\n  sqlite3_stmt *pIdxIter;         /* Index iterator */\n  int nTblCol;                    /* Size of azTblCol[] array */\n  char **azTblCol;                /* Array of unquoted target column names */\n  char **azTblType;               /* Array of target column types */\n  int *aiSrcOrder;                /* src table col -> target table col */\n  u8 *abTblPk;                    /* Array of flags, set on target PK columns */\n  u8 *abNotNull;                  /* Array of flags, set on NOT NULL columns */\n  u8 *abIndexed;                  /* Array of flags, set on indexed & PK cols */\n  int eType;                      /* Table type - an RBU_PK_XXX value */\n\n  /* Output variables. zTbl==0 implies EOF. */\n  int bCleanup;                   /* True in \"cleanup\" state */\n  const char *zTbl;               /* Name of target db table */\n  const char *zDataTbl;           /* Name of rbu db table (or null) */\n  const char *zIdx;               /* Name of target db index (or null) */\n  int iTnum;                      /* Root page of current object */\n  int iPkTnum;                    /* If eType==EXTERNAL, root of PK index */\n  int bUnique;                    /* Current index is unique */\n  int nIndex;                     /* Number of aux. indexes on table zTbl */\n\n  /* Statements created by rbuObjIterPrepareAll() */\n  int nCol;                       /* Number of columns in current object */\n  sqlite3_stmt *pSelect;          /* Source data */\n  sqlite3_stmt *pInsert;          /* Statement for INSERT operations */\n  sqlite3_stmt *pDelete;          /* Statement for DELETE ops */\n  sqlite3_stmt *pTmpInsert;       /* Insert into rbu_tmp_$zDataTbl */\n  int nIdxCol;\n  RbuSpan *aIdxCol;\n  char *zIdxSql;\n\n  /* Last UPDATE used (for PK b-tree updates only), or NULL. */\n  RbuUpdateStmt *pRbuUpdate;\n};\n\n/*\n** Values for RbuObjIter.eType\n**\n**     0: Table does not exist (error)\n**     1: Table has an implicit rowid.\n**     2: Table has an explicit IPK column.\n**     3: Table has an external PK index.\n**     4: Table is WITHOUT ROWID.\n**     5: Table is a virtual table.\n*/\n#define RBU_PK_NOTABLE        0\n#define RBU_PK_NONE           1\n#define RBU_PK_IPK            2\n#define RBU_PK_EXTERNAL       3\n#define RBU_PK_WITHOUT_ROWID  4\n#define RBU_PK_VTAB           5\n\n\n/*\n** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs\n** one of the following operations.\n*/\n#define RBU_INSERT     1          /* Insert on a main table b-tree */\n#define RBU_DELETE     2          /* Delete a row from a main table b-tree */\n#define RBU_REPLACE    3          /* Delete and then insert a row */\n#define RBU_IDX_DELETE 4          /* Delete a row from an aux. index b-tree */\n#define RBU_IDX_INSERT 5          /* Insert on an aux. index b-tree */\n\n#define RBU_UPDATE     6          /* Update a row in a main table b-tree */\n\n/*\n** A single step of an incremental checkpoint - frame iWalFrame of the wal\n** file should be copied to page iDbPage of the database file.\n*/\nstruct RbuFrame {\n  u32 iDbPage;\n  u32 iWalFrame;\n};\n\n/*\n** RBU handle.\n**\n** nPhaseOneStep:\n**   If the RBU database contains an rbu_count table, this value is set to\n**   a running estimate of the number of b-tree operations required to \n**   finish populating the *-oal file. This allows the sqlite3_bp_progress()\n**   API to calculate the permyriadage progress of populating the *-oal file\n**   using the formula:\n**\n**     permyriadage = (10000 * nProgress) / nPhaseOneStep\n**\n**   nPhaseOneStep is initialized to the sum of:\n**\n**     nRow * (nIndex + 1)\n**\n**   for all source tables in the RBU database, where nRow is the number\n**   of rows in the source table and nIndex the number of indexes on the\n**   corresponding target database table.\n**\n**   This estimate is accurate if the RBU update consists entirely of\n**   INSERT operations. However, it is inaccurate if:\n**\n**     * the RBU update contains any UPDATE operations. If the PK specified\n**       for an UPDATE operation does not exist in the target table, then\n**       no b-tree operations are required on index b-trees. Or if the \n**       specified PK does exist, then (nIndex*2) such operations are\n**       required (one delete and one insert on each index b-tree).\n**\n**     * the RBU update contains any DELETE operations for which the specified\n**       PK does not exist. In this case no operations are required on index\n**       b-trees.\n**\n**     * the RBU update contains REPLACE operations. These are similar to\n**       UPDATE operations.\n**\n**   nPhaseOneStep is updated to account for the conditions above during the\n**   first pass of each source table. The updated nPhaseOneStep value is\n**   stored in the rbu_state table if the RBU update is suspended.\n*/\nstruct sqlite3rbu {\n  int eStage;                     /* Value of RBU_STATE_STAGE field */\n  sqlite3 *dbMain;                /* target database handle */\n  sqlite3 *dbRbu;                 /* rbu database handle */\n  char *zTarget;                  /* Path to target db */\n  char *zRbu;                     /* Path to rbu db */\n  char *zState;                   /* Path to state db (or NULL if zRbu) */\n  char zStateDb[5];               /* Db name for state (\"stat\" or \"main\") */\n  int rc;                         /* Value returned by last rbu_step() call */\n  char *zErrmsg;                  /* Error message if rc!=SQLITE_OK */\n  int nStep;                      /* Rows processed for current object */\n  int nProgress;                  /* Rows processed for all objects */\n  RbuObjIter objiter;             /* Iterator for skipping through tbl/idx */\n  const char *zVfsName;           /* Name of automatically created rbu vfs */\n  rbu_file *pTargetFd;            /* File handle open on target db */\n  int nPagePerSector;             /* Pages per sector for pTargetFd */\n  i64 iOalSz;\n  i64 nPhaseOneStep;\n\n  /* The following state variables are used as part of the incremental\n  ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding\n  ** function rbuSetupCheckpoint() for details.  */\n  u32 iMaxFrame;                  /* Largest iWalFrame value in aFrame[] */\n  u32 mLock;\n  int nFrame;                     /* Entries in aFrame[] array */\n  int nFrameAlloc;                /* Allocated size of aFrame[] array */\n  RbuFrame *aFrame;\n  int pgsz;\n  u8 *aBuf;\n  i64 iWalCksum;\n  i64 szTemp;                     /* Current size of all temp files in use */\n  i64 szTempLimit;                /* Total size limit for temp files */\n\n  /* Used in RBU vacuum mode only */\n  int nRbu;                       /* Number of RBU VFS in the stack */\n  rbu_file *pRbuFd;               /* Fd for main db of dbRbu */\n};\n\n/*\n** An rbu VFS is implemented using an instance of this structure.\n**\n** Variable pRbu is only non-NULL for automatically created RBU VFS objects.\n** It is NULL for RBU VFS objects created explicitly using\n** sqlite3rbu_create_vfs(). It is used to track the total amount of temp\n** space used by the RBU handle.\n*/\nstruct rbu_vfs {\n  sqlite3_vfs base;               /* rbu VFS shim methods */\n  sqlite3_vfs *pRealVfs;          /* Underlying VFS */\n  sqlite3_mutex *mutex;           /* Mutex to protect pMain */\n  sqlite3rbu *pRbu;               /* Owner RBU object */\n  rbu_file *pMain;                /* List of main db files */\n  rbu_file *pMainRbu;             /* List of main db files with pRbu!=0 */\n};\n\n/*\n** Each file opened by an rbu VFS is represented by an instance of\n** the following structure.\n**\n** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable\n** \"sz\" is set to the current size of the database file.\n*/\nstruct rbu_file {\n  sqlite3_file base;              /* sqlite3_file methods */\n  sqlite3_file *pReal;            /* Underlying file handle */\n  rbu_vfs *pRbuVfs;               /* Pointer to the rbu_vfs object */\n  sqlite3rbu *pRbu;               /* Pointer to rbu object (rbu target only) */\n  i64 sz;                         /* Size of file in bytes (temp only) */\n\n  int openFlags;                  /* Flags this file was opened with */\n  u32 iCookie;                    /* Cookie value for main db files */\n  u8 iWriteVer;                   /* \"write-version\" value for main db files */\n  u8 bNolock;                     /* True to fail EXCLUSIVE locks */\n\n  int nShm;                       /* Number of entries in apShm[] array */\n  char **apShm;                   /* Array of mmap'd *-shm regions */\n  char *zDel;                     /* Delete this when closing file */\n\n  const char *zWal;               /* Wal filename for this main db file */\n  rbu_file *pWalFd;               /* Wal file descriptor for this main db */\n  rbu_file *pMainNext;            /* Next MAIN_DB file */\n  rbu_file *pMainRbuNext;         /* Next MAIN_DB file with pRbu!=0 */\n};\n\n/*\n** True for an RBU vacuum handle, or false otherwise.\n*/\n#define rbuIsVacuum(p) ((p)->zTarget==0)\n\n\n/*************************************************************************\n** The following three functions, found below:\n**\n**   rbuDeltaGetInt()\n**   rbuDeltaChecksum()\n**   rbuDeltaApply()\n**\n** are lifted from the fossil source code (http://fossil-scm.org). They\n** are used to implement the scalar SQL function rbu_fossil_delta().\n*/\n\n/*\n** Read bytes from *pz and convert them into a positive integer.  When\n** finished, leave *pz pointing to the first character past the end of\n** the integer.  The *pLen parameter holds the length of the string\n** in *pz and is decremented once for each character in the integer.\n*/\nstatic unsigned int rbuDeltaGetInt(const char **pz, int *pLen){\n  static const signed char zValue[] = {\n    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,\n    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,\n    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,\n     0,  1,  2,  3,  4,  5,  6,  7,    8,  9, -1, -1, -1, -1, -1, -1,\n    -1, 10, 11, 12, 13, 14, 15, 16,   17, 18, 19, 20, 21, 22, 23, 24,\n    25, 26, 27, 28, 29, 30, 31, 32,   33, 34, 35, -1, -1, -1, -1, 36,\n    -1, 37, 38, 39, 40, 41, 42, 43,   44, 45, 46, 47, 48, 49, 50, 51,\n    52, 53, 54, 55, 56, 57, 58, 59,   60, 61, 62, -1, -1, -1, 63, -1,\n  };\n  unsigned int v = 0;\n  int c;\n  unsigned char *z = (unsigned char*)*pz;\n  unsigned char *zStart = z;\n  while( (c = zValue[0x7f&*(z++)])>=0 ){\n     v = (v<<6) + c;\n  }\n  z--;\n  *pLen -= z - zStart;\n  *pz = (char*)z;\n  return v;\n}\n\n#if RBU_ENABLE_DELTA_CKSUM\n/*\n** Compute a 32-bit checksum on the N-byte buffer.  Return the result.\n*/\nstatic unsigned int rbuDeltaChecksum(const char *zIn, size_t N){\n  const unsigned char *z = (const unsigned char *)zIn;\n  unsigned sum0 = 0;\n  unsigned sum1 = 0;\n  unsigned sum2 = 0;\n  unsigned sum3 = 0;\n  while(N >= 16){\n    sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);\n    sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);\n    sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);\n    sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);\n    z += 16;\n    N -= 16;\n  }\n  while(N >= 4){\n    sum0 += z[0];\n    sum1 += z[1];\n    sum2 += z[2];\n    sum3 += z[3];\n    z += 4;\n    N -= 4;\n  }\n  sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);\n  switch(N){\n    case 3:   sum3 += (z[2] << 8);\n    case 2:   sum3 += (z[1] << 16);\n    case 1:   sum3 += (z[0] << 24);\n    default:  ;\n  }\n  return sum3;\n}\n#endif\n\n/*\n** Apply a delta.\n**\n** The output buffer should be big enough to hold the whole output\n** file and a NUL terminator at the end.  The delta_output_size()\n** routine will determine this size for you.\n**\n** The delta string should be null-terminated.  But the delta string\n** may contain embedded NUL characters (if the input and output are\n** binary files) so we also have to pass in the length of the delta in\n** the lenDelta parameter.\n**\n** This function returns the size of the output file in bytes (excluding\n** the final NUL terminator character).  Except, if the delta string is\n** malformed or intended for use with a source file other than zSrc,\n** then this routine returns -1.\n**\n** Refer to the delta_create() documentation above for a description\n** of the delta file format.\n*/\nstatic int rbuDeltaApply(\n  const char *zSrc,      /* The source or pattern file */\n  int lenSrc,            /* Length of the source file */\n  const char *zDelta,    /* Delta to apply to the pattern */\n  int lenDelta,          /* Length of the delta */\n  char *zOut             /* Write the output into this preallocated buffer */\n){\n  unsigned int limit;\n  unsigned int total = 0;\n#if RBU_ENABLE_DELTA_CKSUM\n  char *zOrigOut = zOut;\n#endif\n\n  limit = rbuDeltaGetInt(&zDelta, &lenDelta);\n  if( *zDelta!='\\n' ){\n    /* ERROR: size integer not terminated by \"\\n\" */\n    return -1;\n  }\n  zDelta++; lenDelta--;\n  while( *zDelta && lenDelta>0 ){\n    unsigned int cnt, ofst;\n    cnt = rbuDeltaGetInt(&zDelta, &lenDelta);\n    switch( zDelta[0] ){\n      case '@': {\n        zDelta++; lenDelta--;\n        ofst = rbuDeltaGetInt(&zDelta, &lenDelta);\n        if( lenDelta>0 && zDelta[0]!=',' ){\n          /* ERROR: copy command not terminated by ',' */\n          return -1;\n        }\n        zDelta++; lenDelta--;\n        total += cnt;\n        if( total>limit ){\n          /* ERROR: copy exceeds output file size */\n          return -1;\n        }\n        if( (int)(ofst+cnt) > lenSrc ){\n          /* ERROR: copy extends past end of input */\n          return -1;\n        }\n        memcpy(zOut, &zSrc[ofst], cnt);\n        zOut += cnt;\n        break;\n      }\n      case ':': {\n        zDelta++; lenDelta--;\n        total += cnt;\n        if( total>limit ){\n          /* ERROR:  insert command gives an output larger than predicted */\n          return -1;\n        }\n        if( (int)cnt>lenDelta ){\n          /* ERROR: insert count exceeds size of delta */\n          return -1;\n        }\n        memcpy(zOut, zDelta, cnt);\n        zOut += cnt;\n        zDelta += cnt;\n        lenDelta -= cnt;\n        break;\n      }\n      case ';': {\n        zDelta++; lenDelta--;\n        zOut[0] = 0;\n#if RBU_ENABLE_DELTA_CKSUM\n        if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){\n          /* ERROR:  bad checksum */\n          return -1;\n        }\n#endif\n        if( total!=limit ){\n          /* ERROR: generated size does not match predicted size */\n          return -1;\n        }\n        return total;\n      }\n      default: {\n        /* ERROR: unknown delta operator */\n        return -1;\n      }\n    }\n  }\n  /* ERROR: unterminated delta */\n  return -1;\n}\n\nstatic int rbuDeltaOutputSize(const char *zDelta, int lenDelta){\n  int size;\n  size = rbuDeltaGetInt(&zDelta, &lenDelta);\n  if( *zDelta!='\\n' ){\n    /* ERROR: size integer not terminated by \"\\n\" */\n    return -1;\n  }\n  return size;\n}\n\n/*\n** End of code taken from fossil.\n*************************************************************************/\n\n/*\n** Implementation of SQL scalar function rbu_fossil_delta().\n**\n** This function applies a fossil delta patch to a blob. Exactly two\n** arguments must be passed to this function. The first is the blob to\n** patch and the second the patch to apply. If no error occurs, this\n** function returns the patched blob.\n*/\nstatic void rbuFossilDeltaFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  const char *aDelta;\n  int nDelta;\n  const char *aOrig;\n  int nOrig;\n\n  int nOut;\n  int nOut2;\n  char *aOut;\n\n  assert( argc==2 );\n\n  nOrig = sqlite3_value_bytes(argv[0]);\n  aOrig = (const char*)sqlite3_value_blob(argv[0]);\n  nDelta = sqlite3_value_bytes(argv[1]);\n  aDelta = (const char*)sqlite3_value_blob(argv[1]);\n\n  /* Figure out the size of the output */\n  nOut = rbuDeltaOutputSize(aDelta, nDelta);\n  if( nOut<0 ){\n    sqlite3_result_error(context, \"corrupt fossil delta\", -1);\n    return;\n  }\n\n  aOut = sqlite3_malloc(nOut+1);\n  if( aOut==0 ){\n    sqlite3_result_error_nomem(context);\n  }else{\n    nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);\n    if( nOut2!=nOut ){\n      sqlite3_free(aOut);\n      sqlite3_result_error(context, \"corrupt fossil delta\", -1);\n    }else{\n      sqlite3_result_blob(context, aOut, nOut, sqlite3_free);\n    }\n  }\n}\n\n\n/*\n** Prepare the SQL statement in buffer zSql against database handle db.\n** If successful, set *ppStmt to point to the new statement and return\n** SQLITE_OK. \n**\n** Otherwise, if an error does occur, set *ppStmt to NULL and return\n** an SQLite error code. Additionally, set output variable *pzErrmsg to\n** point to a buffer containing an error message. It is the responsibility\n** of the caller to (eventually) free this buffer using sqlite3_free().\n*/\nstatic int prepareAndCollectError(\n  sqlite3 *db, \n  sqlite3_stmt **ppStmt,\n  char **pzErrmsg,\n  const char *zSql\n){\n  int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);\n  if( rc!=SQLITE_OK ){\n    *pzErrmsg = sqlite3_mprintf(\"%s\", sqlite3_errmsg(db));\n    *ppStmt = 0;\n  }\n  return rc;\n}\n\n/*\n** Reset the SQL statement passed as the first argument. Return a copy\n** of the value returned by sqlite3_reset().\n**\n** If an error has occurred, then set *pzErrmsg to point to a buffer\n** containing an error message. It is the responsibility of the caller\n** to eventually free this buffer using sqlite3_free().\n*/\nstatic int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){\n  int rc = sqlite3_reset(pStmt);\n  if( rc!=SQLITE_OK ){\n    *pzErrmsg = sqlite3_mprintf(\"%s\", sqlite3_errmsg(sqlite3_db_handle(pStmt)));\n  }\n  return rc;\n}\n\n/*\n** Unless it is NULL, argument zSql points to a buffer allocated using\n** sqlite3_malloc containing an SQL statement. This function prepares the SQL\n** statement against database db and frees the buffer. If statement \n** compilation is successful, *ppStmt is set to point to the new statement \n** handle and SQLITE_OK is returned. \n**\n** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code\n** returned. In this case, *pzErrmsg may also be set to point to an error\n** message. It is the responsibility of the caller to free this error message\n** buffer using sqlite3_free().\n**\n** If argument zSql is NULL, this function assumes that an OOM has occurred.\n** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.\n*/\nstatic int prepareFreeAndCollectError(\n  sqlite3 *db, \n  sqlite3_stmt **ppStmt,\n  char **pzErrmsg,\n  char *zSql\n){\n  int rc;\n  assert( *pzErrmsg==0 );\n  if( zSql==0 ){\n    rc = SQLITE_NOMEM;\n    *ppStmt = 0;\n  }else{\n    rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);\n    sqlite3_free(zSql);\n  }\n  return rc;\n}\n\n/*\n** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated\n** by an earlier call to rbuObjIterCacheTableInfo().\n*/\nstatic void rbuObjIterFreeCols(RbuObjIter *pIter){\n  int i;\n  for(i=0; i<pIter->nTblCol; i++){\n    sqlite3_free(pIter->azTblCol[i]);\n    sqlite3_free(pIter->azTblType[i]);\n  }\n  sqlite3_free(pIter->azTblCol);\n  pIter->azTblCol = 0;\n  pIter->azTblType = 0;\n  pIter->aiSrcOrder = 0;\n  pIter->abTblPk = 0;\n  pIter->abNotNull = 0;\n  pIter->nTblCol = 0;\n  pIter->eType = 0;               /* Invalid value */\n}\n\n/*\n** Finalize all statements and free all allocations that are specific to\n** the current object (table/index pair).\n*/\nstatic void rbuObjIterClearStatements(RbuObjIter *pIter){\n  RbuUpdateStmt *pUp;\n\n  sqlite3_finalize(pIter->pSelect);\n  sqlite3_finalize(pIter->pInsert);\n  sqlite3_finalize(pIter->pDelete);\n  sqlite3_finalize(pIter->pTmpInsert);\n  pUp = pIter->pRbuUpdate;\n  while( pUp ){\n    RbuUpdateStmt *pTmp = pUp->pNext;\n    sqlite3_finalize(pUp->pUpdate);\n    sqlite3_free(pUp);\n    pUp = pTmp;\n  }\n  sqlite3_free(pIter->aIdxCol);\n  sqlite3_free(pIter->zIdxSql);\n  \n  pIter->pSelect = 0;\n  pIter->pInsert = 0;\n  pIter->pDelete = 0;\n  pIter->pRbuUpdate = 0;\n  pIter->pTmpInsert = 0;\n  pIter->nCol = 0;\n  pIter->nIdxCol = 0;\n  pIter->aIdxCol = 0;\n  pIter->zIdxSql = 0;\n}\n\n/*\n** Clean up any resources allocated as part of the iterator object passed\n** as the only argument.\n*/\nstatic void rbuObjIterFinalize(RbuObjIter *pIter){\n  rbuObjIterClearStatements(pIter);\n  sqlite3_finalize(pIter->pTblIter);\n  sqlite3_finalize(pIter->pIdxIter);\n  rbuObjIterFreeCols(pIter);\n  memset(pIter, 0, sizeof(RbuObjIter));\n}\n\n/*\n** Advance the iterator to the next position.\n**\n** If no error occurs, SQLITE_OK is returned and the iterator is left \n** pointing to the next entry. Otherwise, an error code and message is \n** left in the RBU handle passed as the first argument. A copy of the \n** error code is returned.\n*/\nstatic int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){\n  int rc = p->rc;\n  if( rc==SQLITE_OK ){\n\n    /* Free any SQLite statements used while processing the previous object */ \n    rbuObjIterClearStatements(pIter);\n    if( pIter->zIdx==0 ){\n      rc = sqlite3_exec(p->dbMain,\n          \"DROP TRIGGER IF EXISTS temp.rbu_insert_tr;\"\n          \"DROP TRIGGER IF EXISTS temp.rbu_update1_tr;\"\n          \"DROP TRIGGER IF EXISTS temp.rbu_update2_tr;\"\n          \"DROP TRIGGER IF EXISTS temp.rbu_delete_tr;\"\n          , 0, 0, &p->zErrmsg\n      );\n    }\n\n    if( rc==SQLITE_OK ){\n      if( pIter->bCleanup ){\n        rbuObjIterFreeCols(pIter);\n        pIter->bCleanup = 0;\n        rc = sqlite3_step(pIter->pTblIter);\n        if( rc!=SQLITE_ROW ){\n          rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);\n          pIter->zTbl = 0;\n        }else{\n          pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);\n          pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);\n          rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;\n        }\n      }else{\n        if( pIter->zIdx==0 ){\n          sqlite3_stmt *pIdx = pIter->pIdxIter;\n          rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);\n        }\n        if( rc==SQLITE_OK ){\n          rc = sqlite3_step(pIter->pIdxIter);\n          if( rc!=SQLITE_ROW ){\n            rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);\n            pIter->bCleanup = 1;\n            pIter->zIdx = 0;\n          }else{\n            pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);\n            pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);\n            pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);\n            rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;\n          }\n        }\n      }\n    }\n  }\n\n  if( rc!=SQLITE_OK ){\n    rbuObjIterFinalize(pIter);\n    p->rc = rc;\n  }\n  return rc;\n}\n\n\n/*\n** The implementation of the rbu_target_name() SQL function. This function\n** accepts one or two arguments. The first argument is the name of a table -\n** the name of a table in the RBU database.  The second, if it is present, is 1\n** for a view or 0 for a table. \n**\n** For a non-vacuum RBU handle, if the table name matches the pattern:\n**\n**     data[0-9]_<name>\n**\n** where <name> is any sequence of 1 or more characters, <name> is returned.\n** Otherwise, if the only argument does not match the above pattern, an SQL\n** NULL is returned.\n**\n**     \"data_t1\"     -> \"t1\"\n**     \"data0123_t2\" -> \"t2\"\n**     \"dataAB_t3\"   -> NULL\n**\n** For an rbu vacuum handle, a copy of the first argument is returned if\n** the second argument is either missing or 0 (not a view).\n*/\nstatic void rbuTargetNameFunc(\n  sqlite3_context *pCtx,\n  int argc,\n  sqlite3_value **argv\n){\n  sqlite3rbu *p = sqlite3_user_data(pCtx);\n  const char *zIn;\n  assert( argc==1 || argc==2 );\n\n  zIn = (const char*)sqlite3_value_text(argv[0]);\n  if( zIn ){\n    if( rbuIsVacuum(p) ){\n      assert( argc==2 || argc==1 );\n      if( argc==1 || 0==sqlite3_value_int(argv[1]) ){\n        sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);\n      }\n    }else{\n      if( strlen(zIn)>4 && memcmp(\"data\", zIn, 4)==0 ){\n        int i;\n        for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);\n        if( zIn[i]=='_' && zIn[i+1] ){\n          sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);\n        }\n      }\n    }\n  }\n}\n\n/*\n** Initialize the iterator structure passed as the second argument.\n**\n** If no error occurs, SQLITE_OK is returned and the iterator is left \n** pointing to the first entry. Otherwise, an error code and message is \n** left in the RBU handle passed as the first argument. A copy of the \n** error code is returned.\n*/\nstatic int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){\n  int rc;\n  memset(pIter, 0, sizeof(RbuObjIter));\n\n  rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg, \n    sqlite3_mprintf(\n      \"SELECT rbu_target_name(name, type='view') AS target, name \"\n      \"FROM sqlite_master \"\n      \"WHERE type IN ('table', 'view') AND target IS NOT NULL \"\n      \" %s \"\n      \"ORDER BY name\"\n  , rbuIsVacuum(p) ? \"AND rootpage!=0 AND rootpage IS NOT NULL\" : \"\"));\n\n  if( rc==SQLITE_OK ){\n    rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,\n        \"SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' \"\n        \"  FROM main.sqlite_master \"\n        \"  WHERE type='index' AND tbl_name = ?\"\n    );\n  }\n\n  pIter->bCleanup = 1;\n  p->rc = rc;\n  return rbuObjIterNext(p, pIter);\n}\n\n/*\n** This is a wrapper around \"sqlite3_mprintf(zFmt, ...)\". If an OOM occurs,\n** an error code is stored in the RBU handle passed as the first argument.\n**\n** If an error has already occurred (p->rc is already set to something other\n** than SQLITE_OK), then this function returns NULL without modifying the\n** stored error code. In this case it still calls sqlite3_free() on any \n** printf() parameters associated with %z conversions.\n*/\nstatic char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){\n  char *zSql = 0;\n  va_list ap;\n  va_start(ap, zFmt);\n  zSql = sqlite3_vmprintf(zFmt, ap);\n  if( p->rc==SQLITE_OK ){\n    if( zSql==0 ) p->rc = SQLITE_NOMEM;\n  }else{\n    sqlite3_free(zSql);\n    zSql = 0;\n  }\n  va_end(ap);\n  return zSql;\n}\n\n/*\n** Argument zFmt is a sqlite3_mprintf() style format string. The trailing\n** arguments are the usual subsitution values. This function performs\n** the printf() style substitutions and executes the result as an SQL\n** statement on the RBU handles database.\n**\n** If an error occurs, an error code and error message is stored in the\n** RBU handle. If an error has already occurred when this function is\n** called, it is a no-op.\n*/\nstatic int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){\n  va_list ap;\n  char *zSql;\n  va_start(ap, zFmt);\n  zSql = sqlite3_vmprintf(zFmt, ap);\n  if( p->rc==SQLITE_OK ){\n    if( zSql==0 ){\n      p->rc = SQLITE_NOMEM;\n    }else{\n      p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);\n    }\n  }\n  sqlite3_free(zSql);\n  va_end(ap);\n  return p->rc;\n}\n\n/*\n** Attempt to allocate and return a pointer to a zeroed block of nByte \n** bytes. \n**\n** If an error (i.e. an OOM condition) occurs, return NULL and leave an \n** error code in the rbu handle passed as the first argument. Or, if an \n** error has already occurred when this function is called, return NULL \n** immediately without attempting the allocation or modifying the stored\n** error code.\n*/\nstatic void *rbuMalloc(sqlite3rbu *p, sqlite3_int64 nByte){\n  void *pRet = 0;\n  if( p->rc==SQLITE_OK ){\n    assert( nByte>0 );\n    pRet = sqlite3_malloc64(nByte);\n    if( pRet==0 ){\n      p->rc = SQLITE_NOMEM;\n    }else{\n      memset(pRet, 0, nByte);\n    }\n  }\n  return pRet;\n}\n\n\n/*\n** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that\n** there is room for at least nCol elements. If an OOM occurs, store an\n** error code in the RBU handle passed as the first argument.\n*/\nstatic void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){\n  sqlite3_int64 nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;\n  char **azNew;\n\n  azNew = (char**)rbuMalloc(p, nByte);\n  if( azNew ){\n    pIter->azTblCol = azNew;\n    pIter->azTblType = &azNew[nCol];\n    pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];\n    pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];\n    pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];\n    pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];\n  }\n}\n\n/*\n** The first argument must be a nul-terminated string. This function\n** returns a copy of the string in memory obtained from sqlite3_malloc().\n** It is the responsibility of the caller to eventually free this memory\n** using sqlite3_free().\n**\n** If an OOM condition is encountered when attempting to allocate memory,\n** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,\n** if the allocation succeeds, (*pRc) is left unchanged.\n*/\nstatic char *rbuStrndup(const char *zStr, int *pRc){\n  char *zRet = 0;\n\n  if( *pRc==SQLITE_OK ){\n    if( zStr ){\n      size_t nCopy = strlen(zStr) + 1;\n      zRet = (char*)sqlite3_malloc64(nCopy);\n      if( zRet ){\n        memcpy(zRet, zStr, nCopy);\n      }else{\n        *pRc = SQLITE_NOMEM;\n      }\n    }\n  }\n\n  return zRet;\n}\n\n/*\n** Finalize the statement passed as the second argument.\n**\n** If the sqlite3_finalize() call indicates that an error occurs, and the\n** rbu handle error code is not already set, set the error code and error\n** message accordingly.\n*/\nstatic void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){\n  sqlite3 *db = sqlite3_db_handle(pStmt);\n  int rc = sqlite3_finalize(pStmt);\n  if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){\n    p->rc = rc;\n    p->zErrmsg = sqlite3_mprintf(\"%s\", sqlite3_errmsg(db));\n  }\n}\n\n/* Determine the type of a table.\n**\n**   peType is of type (int*), a pointer to an output parameter of type\n**   (int). This call sets the output parameter as follows, depending\n**   on the type of the table specified by parameters dbName and zTbl.\n**\n**     RBU_PK_NOTABLE:       No such table.\n**     RBU_PK_NONE:          Table has an implicit rowid.\n**     RBU_PK_IPK:           Table has an explicit IPK column.\n**     RBU_PK_EXTERNAL:      Table has an external PK index.\n**     RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.\n**     RBU_PK_VTAB:          Table is a virtual table.\n**\n**   Argument *piPk is also of type (int*), and also points to an output\n**   parameter. Unless the table has an external primary key index \n**   (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,\n**   if the table does have an external primary key index, then *piPk\n**   is set to the root page number of the primary key index before\n**   returning.\n**\n** ALGORITHM:\n**\n**   if( no entry exists in sqlite_master ){\n**     return RBU_PK_NOTABLE\n**   }else if( sql for the entry starts with \"CREATE VIRTUAL\" ){\n**     return RBU_PK_VTAB\n**   }else if( \"PRAGMA index_list()\" for the table contains a \"pk\" index ){\n**     if( the index that is the pk exists in sqlite_master ){\n**       *piPK = rootpage of that index.\n**       return RBU_PK_EXTERNAL\n**     }else{\n**       return RBU_PK_WITHOUT_ROWID\n**     }\n**   }else if( \"PRAGMA table_info()\" lists one or more \"pk\" columns ){\n**     return RBU_PK_IPK\n**   }else{\n**     return RBU_PK_NONE\n**   }\n*/\nstatic void rbuTableType(\n  sqlite3rbu *p,\n  const char *zTab,\n  int *peType,\n  int *piTnum,\n  int *piPk\n){\n  /*\n  ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)\n  ** 1) PRAGMA index_list = ?\n  ** 2) SELECT count(*) FROM sqlite_master where name=%Q \n  ** 3) PRAGMA table_info = ?\n  */\n  sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};\n\n  *peType = RBU_PK_NOTABLE;\n  *piPk = 0;\n\n  assert( p->rc==SQLITE_OK );\n  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg, \n    sqlite3_mprintf(\n          \"SELECT (sql LIKE 'create virtual%%'), rootpage\"\n          \"  FROM sqlite_master\"\n          \" WHERE name=%Q\", zTab\n  ));\n  if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){\n    /* Either an error, or no such table. */\n    goto rbuTableType_end;\n  }\n  if( sqlite3_column_int(aStmt[0], 0) ){\n    *peType = RBU_PK_VTAB;                     /* virtual table */\n    goto rbuTableType_end;\n  }\n  *piTnum = sqlite3_column_int(aStmt[0], 1);\n\n  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg, \n    sqlite3_mprintf(\"PRAGMA index_list=%Q\",zTab)\n  );\n  if( p->rc ) goto rbuTableType_end;\n  while( sqlite3_step(aStmt[1])==SQLITE_ROW ){\n    const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);\n    const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);\n    if( zOrig && zIdx && zOrig[0]=='p' ){\n      p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg, \n          sqlite3_mprintf(\n            \"SELECT rootpage FROM sqlite_master WHERE name = %Q\", zIdx\n      ));\n      if( p->rc==SQLITE_OK ){\n        if( sqlite3_step(aStmt[2])==SQLITE_ROW ){\n          *piPk = sqlite3_column_int(aStmt[2], 0);\n          *peType = RBU_PK_EXTERNAL;\n        }else{\n          *peType = RBU_PK_WITHOUT_ROWID;\n        }\n      }\n      goto rbuTableType_end;\n    }\n  }\n\n  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg, \n    sqlite3_mprintf(\"PRAGMA table_info=%Q\",zTab)\n  );\n  if( p->rc==SQLITE_OK ){\n    while( sqlite3_step(aStmt[3])==SQLITE_ROW ){\n      if( sqlite3_column_int(aStmt[3],5)>0 ){\n        *peType = RBU_PK_IPK;                /* explicit IPK column */\n        goto rbuTableType_end;\n      }\n    }\n    *peType = RBU_PK_NONE;\n  }\n\nrbuTableType_end: {\n    unsigned int i;\n    for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){\n      rbuFinalize(p, aStmt[i]);\n    }\n  }\n}\n\n/*\n** This is a helper function for rbuObjIterCacheTableInfo(). It populates\n** the pIter->abIndexed[] array.\n*/\nstatic void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){\n  sqlite3_stmt *pList = 0;\n  int bIndex = 0;\n\n  if( p->rc==SQLITE_OK ){\n    memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);\n    p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,\n        sqlite3_mprintf(\"PRAGMA main.index_list = %Q\", pIter->zTbl)\n    );\n  }\n\n  pIter->nIndex = 0;\n  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){\n    const char *zIdx = (const char*)sqlite3_column_text(pList, 1);\n    int bPartial = sqlite3_column_int(pList, 4);\n    sqlite3_stmt *pXInfo = 0;\n    if( zIdx==0 ) break;\n    if( bPartial ){\n      memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol);\n    }\n    p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,\n        sqlite3_mprintf(\"PRAGMA main.index_xinfo = %Q\", zIdx)\n    );\n    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){\n      int iCid = sqlite3_column_int(pXInfo, 1);\n      if( iCid>=0 ) pIter->abIndexed[iCid] = 1;\n      if( iCid==-2 ){\n        memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol);\n      }\n    }\n    rbuFinalize(p, pXInfo);\n    bIndex = 1;\n    pIter->nIndex++;\n  }\n\n  if( pIter->eType==RBU_PK_WITHOUT_ROWID ){\n    /* \"PRAGMA index_list\" includes the main PK b-tree */\n    pIter->nIndex--;\n  }\n\n  rbuFinalize(p, pList);\n  if( bIndex==0 ) pIter->abIndexed = 0;\n}\n\n\n/*\n** If they are not already populated, populate the pIter->azTblCol[],\n** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to\n** the table (not index) that the iterator currently points to.\n**\n** Return SQLITE_OK if successful, or an SQLite error code otherwise. If\n** an error does occur, an error code and error message are also left in \n** the RBU handle.\n*/\nstatic int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){\n  if( pIter->azTblCol==0 ){\n    sqlite3_stmt *pStmt = 0;\n    int nCol = 0;\n    int i;                        /* for() loop iterator variable */\n    int bRbuRowid = 0;            /* If input table has column \"rbu_rowid\" */\n    int iOrder = 0;\n    int iTnum = 0;\n\n    /* Figure out the type of table this step will deal with. */\n    assert( pIter->eType==0 );\n    rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);\n    if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){\n      p->rc = SQLITE_ERROR;\n      p->zErrmsg = sqlite3_mprintf(\"no such table: %s\", pIter->zTbl);\n    }\n    if( p->rc ) return p->rc;\n    if( pIter->zIdx==0 ) pIter->iTnum = iTnum;\n\n    assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK \n         || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID\n         || pIter->eType==RBU_PK_VTAB\n    );\n\n    /* Populate the azTblCol[] and nTblCol variables based on the columns\n    ** of the input table. Ignore any input table columns that begin with\n    ** \"rbu_\".  */\n    p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, \n        sqlite3_mprintf(\"SELECT * FROM '%q'\", pIter->zDataTbl)\n    );\n    if( p->rc==SQLITE_OK ){\n      nCol = sqlite3_column_count(pStmt);\n      rbuAllocateIterArrays(p, pIter, nCol);\n    }\n    for(i=0; p->rc==SQLITE_OK && i<nCol; i++){\n      const char *zName = (const char*)sqlite3_column_name(pStmt, i);\n      if( sqlite3_strnicmp(\"rbu_\", zName, 4) ){\n        char *zCopy = rbuStrndup(zName, &p->rc);\n        pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;\n        pIter->azTblCol[pIter->nTblCol++] = zCopy;\n      }\n      else if( 0==sqlite3_stricmp(\"rbu_rowid\", zName) ){\n        bRbuRowid = 1;\n      }\n    }\n    sqlite3_finalize(pStmt);\n    pStmt = 0;\n\n    if( p->rc==SQLITE_OK\n     && rbuIsVacuum(p)==0\n     && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)\n    ){\n      p->rc = SQLITE_ERROR;\n      p->zErrmsg = sqlite3_mprintf(\n          \"table %q %s rbu_rowid column\", pIter->zDataTbl,\n          (bRbuRowid ? \"may not have\" : \"requires\")\n      );\n    }\n\n    /* Check that all non-HIDDEN columns in the destination table are also\n    ** present in the input table. Populate the abTblPk[], azTblType[] and\n    ** aiTblOrder[] arrays at the same time.  */\n    if( p->rc==SQLITE_OK ){\n      p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, \n          sqlite3_mprintf(\"PRAGMA table_info(%Q)\", pIter->zTbl)\n      );\n    }\n    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){\n      const char *zName = (const char*)sqlite3_column_text(pStmt, 1);\n      if( zName==0 ) break;  /* An OOM - finalize() below returns S_NOMEM */\n      for(i=iOrder; i<pIter->nTblCol; i++){\n        if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;\n      }\n      if( i==pIter->nTblCol ){\n        p->rc = SQLITE_ERROR;\n        p->zErrmsg = sqlite3_mprintf(\"column missing from %q: %s\",\n            pIter->zDataTbl, zName\n        );\n      }else{\n        int iPk = sqlite3_column_int(pStmt, 5);\n        int bNotNull = sqlite3_column_int(pStmt, 3);\n        const char *zType = (const char*)sqlite3_column_text(pStmt, 2);\n\n        if( i!=iOrder ){\n          SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);\n          SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);\n        }\n\n        pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);\n        assert( iPk>=0 );\n        pIter->abTblPk[iOrder] = (u8)iPk;\n        pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);\n        iOrder++;\n      }\n    }\n\n    rbuFinalize(p, pStmt);\n    rbuObjIterCacheIndexedCols(p, pIter);\n    assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );\n    assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );\n  }\n\n  return p->rc;\n}\n\n/*\n** This function constructs and returns a pointer to a nul-terminated \n** string containing some SQL clause or list based on one or more of the \n** column names currently stored in the pIter->azTblCol[] array.\n*/\nstatic char *rbuObjIterGetCollist(\n  sqlite3rbu *p,                  /* RBU object */\n  RbuObjIter *pIter               /* Object iterator for column names */\n){\n  char *zList = 0;\n  const char *zSep = \"\";\n  int i;\n  for(i=0; i<pIter->nTblCol; i++){\n    const char *z = pIter->azTblCol[i];\n    zList = rbuMPrintf(p, \"%z%s\\\"%w\\\"\", zList, zSep, z);\n    zSep = \", \";\n  }\n  return zList;\n}\n\n/*\n** Return a comma separated list of the quoted PRIMARY KEY column names,\n** in order, for the current table. Before each column name, add the text\n** zPre. After each column name, add the zPost text. Use zSeparator as\n** the separator text (usually \", \").\n*/\nstatic char *rbuObjIterGetPkList(\n  sqlite3rbu *p,                  /* RBU object */\n  RbuObjIter *pIter,              /* Object iterator for column names */\n  const char *zPre,               /* Before each quoted column name */\n  const char *zSeparator,         /* Separator to use between columns */\n  const char *zPost               /* After each quoted column name */\n){\n  int iPk = 1;\n  char *zRet = 0;\n  const char *zSep = \"\";\n  while( 1 ){\n    int i;\n    for(i=0; i<pIter->nTblCol; i++){\n      if( (int)pIter->abTblPk[i]==iPk ){\n        const char *zCol = pIter->azTblCol[i];\n        zRet = rbuMPrintf(p, \"%z%s%s\\\"%w\\\"%s\", zRet, zSep, zPre, zCol, zPost);\n        zSep = zSeparator;\n        break;\n      }\n    }\n    if( i==pIter->nTblCol ) break;\n    iPk++;\n  }\n  return zRet;\n}\n\n/*\n** This function is called as part of restarting an RBU vacuum within \n** stage 1 of the process (while the *-oal file is being built) while\n** updating a table (not an index). The table may be a rowid table or\n** a WITHOUT ROWID table. It queries the target database to find the \n** largest key that has already been written to the target table and\n** constructs a WHERE clause that can be used to extract the remaining\n** rows from the source table. For a rowid table, the WHERE clause\n** is of the form:\n**\n**     \"WHERE _rowid_ > ?\"\n**\n** and for WITHOUT ROWID tables:\n**\n**     \"WHERE (key1, key2) > (?, ?)\"\n**\n** Instead of \"?\" placeholders, the actual WHERE clauses created by\n** this function contain literal SQL values.\n*/\nstatic char *rbuVacuumTableStart(\n  sqlite3rbu *p,                  /* RBU handle */\n  RbuObjIter *pIter,              /* RBU iterator object */\n  int bRowid,                     /* True for a rowid table */\n  const char *zWrite              /* Target table name prefix */\n){\n  sqlite3_stmt *pMax = 0;\n  char *zRet = 0;\n  if( bRowid ){\n    p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg, \n        sqlite3_mprintf(\n          \"SELECT max(_rowid_) FROM \\\"%s%w\\\"\", zWrite, pIter->zTbl\n        )\n    );\n    if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){\n      sqlite3_int64 iMax = sqlite3_column_int64(pMax, 0);\n      zRet = rbuMPrintf(p, \" WHERE _rowid_ > %lld \", iMax);\n    }\n    rbuFinalize(p, pMax);\n  }else{\n    char *zOrder = rbuObjIterGetPkList(p, pIter, \"\", \", \", \" DESC\");\n    char *zSelect = rbuObjIterGetPkList(p, pIter, \"quote(\", \"||','||\", \")\");\n    char *zList = rbuObjIterGetPkList(p, pIter, \"\", \", \", \"\");\n\n    if( p->rc==SQLITE_OK ){\n      p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg, \n          sqlite3_mprintf(\n            \"SELECT %s FROM \\\"%s%w\\\" ORDER BY %s LIMIT 1\", \n                zSelect, zWrite, pIter->zTbl, zOrder\n          )\n      );\n      if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){\n        const char *zVal = (const char*)sqlite3_column_text(pMax, 0);\n        zRet = rbuMPrintf(p, \" WHERE (%s) > (%s) \", zList, zVal);\n      }\n      rbuFinalize(p, pMax);\n    }\n\n    sqlite3_free(zOrder);\n    sqlite3_free(zSelect);\n    sqlite3_free(zList);\n  }\n  return zRet;\n}\n\n/*\n** This function is called as part of restating an RBU vacuum when the\n** current operation is writing content to an index. If possible, it\n** queries the target index b-tree for the largest key already written to\n** it, then composes and returns an expression that can be used in a WHERE \n** clause to select the remaining required rows from the source table. \n** It is only possible to return such an expression if:\n**\n**   * The index contains no DESC columns, and\n**   * The last key written to the index before the operation was \n**     suspended does not contain any NULL values.\n**\n** The expression is of the form:\n**\n**   (index-field1, index-field2, ...) > (?, ?, ...)\n**\n** except that the \"?\" placeholders are replaced with literal values.\n**\n** If the expression cannot be created, NULL is returned. In this case,\n** the caller has to use an OFFSET clause to extract only the required \n** rows from the sourct table, just as it does for an RBU update operation.\n*/\nchar *rbuVacuumIndexStart(\n  sqlite3rbu *p,                  /* RBU handle */\n  RbuObjIter *pIter               /* RBU iterator object */\n){\n  char *zOrder = 0;\n  char *zLhs = 0;\n  char *zSelect = 0;\n  char *zVector = 0;\n  char *zRet = 0;\n  int bFailed = 0;\n  const char *zSep = \"\";\n  int iCol = 0;\n  sqlite3_stmt *pXInfo = 0;\n\n  p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,\n      sqlite3_mprintf(\"PRAGMA main.index_xinfo = %Q\", pIter->zIdx)\n  );\n  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){\n    int iCid = sqlite3_column_int(pXInfo, 1);\n    const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);\n    const char *zCol;\n    if( sqlite3_column_int(pXInfo, 3) ){\n      bFailed = 1;\n      break;\n    }\n\n    if( iCid<0 ){\n      if( pIter->eType==RBU_PK_IPK ){\n        int i;\n        for(i=0; pIter->abTblPk[i]==0; i++);\n        assert( i<pIter->nTblCol );\n        zCol = pIter->azTblCol[i];\n      }else{\n        zCol = \"_rowid_\";\n      }\n    }else{\n      zCol = pIter->azTblCol[iCid];\n    }\n\n    zLhs = rbuMPrintf(p, \"%z%s \\\"%w\\\" COLLATE %Q\",\n        zLhs, zSep, zCol, zCollate\n        );\n    zOrder = rbuMPrintf(p, \"%z%s \\\"rbu_imp_%d%w\\\" COLLATE %Q DESC\",\n        zOrder, zSep, iCol, zCol, zCollate\n        );\n    zSelect = rbuMPrintf(p, \"%z%s quote(\\\"rbu_imp_%d%w\\\")\",\n        zSelect, zSep, iCol, zCol\n        );\n    zSep = \", \";\n    iCol++;\n  }\n  rbuFinalize(p, pXInfo);\n  if( bFailed ) goto index_start_out;\n\n  if( p->rc==SQLITE_OK ){\n    sqlite3_stmt *pSel = 0;\n\n    p->rc = prepareFreeAndCollectError(p->dbMain, &pSel, &p->zErrmsg,\n        sqlite3_mprintf(\"SELECT %s FROM \\\"rbu_imp_%w\\\" ORDER BY %s LIMIT 1\",\n          zSelect, pIter->zTbl, zOrder\n        )\n    );\n    if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSel) ){\n      zSep = \"\";\n      for(iCol=0; iCol<pIter->nCol; iCol++){\n        const char *zQuoted = (const char*)sqlite3_column_text(pSel, iCol);\n        if( zQuoted[0]=='N' ){\n          bFailed = 1;\n          break;\n        }\n        zVector = rbuMPrintf(p, \"%z%s%s\", zVector, zSep, zQuoted);\n        zSep = \", \";\n      }\n\n      if( !bFailed ){\n        zRet = rbuMPrintf(p, \"(%s) > (%s)\", zLhs, zVector);\n      }\n    }\n    rbuFinalize(p, pSel);\n  }\n\n index_start_out:\n  sqlite3_free(zOrder);\n  sqlite3_free(zSelect);\n  sqlite3_free(zVector);\n  sqlite3_free(zLhs);\n  return zRet;\n}\n\n/*\n** This function is used to create a SELECT list (the list of SQL \n** expressions that follows a SELECT keyword) for a SELECT statement \n** used to read from an data_xxx or rbu_tmp_xxx table while updating the \n** index object currently indicated by the iterator object passed as the \n** second argument. A \"PRAGMA index_xinfo = <idxname>\" statement is used \n** to obtain the required information.\n**\n** If the index is of the following form:\n**\n**   CREATE INDEX i1 ON t1(c, b COLLATE nocase);\n**\n** and \"t1\" is a table with an explicit INTEGER PRIMARY KEY column \n** \"ipk\", the returned string is:\n**\n**   \"`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'\"\n**\n** As well as the returned string, three other malloc'd strings are \n** returned via output parameters. As follows:\n**\n**   pzImposterCols: ...\n**   pzImposterPk: ...\n**   pzWhere: ...\n*/\nstatic char *rbuObjIterGetIndexCols(\n  sqlite3rbu *p,                  /* RBU object */\n  RbuObjIter *pIter,              /* Object iterator for column names */\n  char **pzImposterCols,          /* OUT: Columns for imposter table */\n  char **pzImposterPk,            /* OUT: Imposter PK clause */\n  char **pzWhere,                 /* OUT: WHERE clause */\n  int *pnBind                     /* OUT: Trbul number of columns */\n){\n  int rc = p->rc;                 /* Error code */\n  int rc2;                        /* sqlite3_finalize() return code */\n  char *zRet = 0;                 /* String to return */\n  char *zImpCols = 0;             /* String to return via *pzImposterCols */\n  char *zImpPK = 0;               /* String to return via *pzImposterPK */\n  char *zWhere = 0;               /* String to return via *pzWhere */\n  int nBind = 0;                  /* Value to return via *pnBind */\n  const char *zCom = \"\";          /* Set to \", \" later on */\n  const char *zAnd = \"\";          /* Set to \" AND \" later on */\n  sqlite3_stmt *pXInfo = 0;       /* PRAGMA index_xinfo = ? */\n\n  if( rc==SQLITE_OK ){\n    assert( p->zErrmsg==0 );\n    rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,\n        sqlite3_mprintf(\"PRAGMA main.index_xinfo = %Q\", pIter->zIdx)\n    );\n  }\n\n  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){\n    int iCid = sqlite3_column_int(pXInfo, 1);\n    int bDesc = sqlite3_column_int(pXInfo, 3);\n    const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);\n    const char *zCol = 0;\n    const char *zType;\n\n    if( iCid==-2 ){\n      int iSeq = sqlite3_column_int(pXInfo, 0);\n      zRet = sqlite3_mprintf(\"%z%s(%.*s) COLLATE %Q\", zRet, zCom,\n          pIter->aIdxCol[iSeq].nSpan, pIter->aIdxCol[iSeq].zSpan, zCollate\n      );\n      zType = \"\";\n    }else {\n      if( iCid<0 ){\n        /* An integer primary key. If the table has an explicit IPK, use\n        ** its name. Otherwise, use \"rbu_rowid\".  */\n        if( pIter->eType==RBU_PK_IPK ){\n          int i;\n          for(i=0; pIter->abTblPk[i]==0; i++);\n          assert( i<pIter->nTblCol );\n          zCol = pIter->azTblCol[i];\n        }else if( rbuIsVacuum(p) ){\n          zCol = \"_rowid_\";\n        }else{\n          zCol = \"rbu_rowid\";\n        }\n        zType = \"INTEGER\";\n      }else{\n        zCol = pIter->azTblCol[iCid];\n        zType = pIter->azTblType[iCid];\n      }\n      zRet = sqlite3_mprintf(\"%z%s\\\"%w\\\" COLLATE %Q\", zRet, zCom,zCol,zCollate);\n    }\n\n    if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){\n      const char *zOrder = (bDesc ? \" DESC\" : \"\");\n      zImpPK = sqlite3_mprintf(\"%z%s\\\"rbu_imp_%d%w\\\"%s\", \n          zImpPK, zCom, nBind, zCol, zOrder\n      );\n    }\n    zImpCols = sqlite3_mprintf(\"%z%s\\\"rbu_imp_%d%w\\\" %s COLLATE %Q\", \n        zImpCols, zCom, nBind, zCol, zType, zCollate\n    );\n    zWhere = sqlite3_mprintf(\n        \"%z%s\\\"rbu_imp_%d%w\\\" IS ?\", zWhere, zAnd, nBind, zCol\n    );\n    if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;\n    zCom = \", \";\n    zAnd = \" AND \";\n    nBind++;\n  }\n\n  rc2 = sqlite3_finalize(pXInfo);\n  if( rc==SQLITE_OK ) rc = rc2;\n\n  if( rc!=SQLITE_OK ){\n    sqlite3_free(zRet);\n    sqlite3_free(zImpCols);\n    sqlite3_free(zImpPK);\n    sqlite3_free(zWhere);\n    zRet = 0;\n    zImpCols = 0;\n    zImpPK = 0;\n    zWhere = 0;\n    p->rc = rc;\n  }\n\n  *pzImposterCols = zImpCols;\n  *pzImposterPk = zImpPK;\n  *pzWhere = zWhere;\n  *pnBind = nBind;\n  return zRet;\n}\n\n/*\n** Assuming the current table columns are \"a\", \"b\" and \"c\", and the zObj\n** paramter is passed \"old\", return a string of the form:\n**\n**     \"old.a, old.b, old.b\"\n**\n** With the column names escaped.\n**\n** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append\n** the text \", old._rowid_\" to the returned value.\n*/\nstatic char *rbuObjIterGetOldlist(\n  sqlite3rbu *p, \n  RbuObjIter *pIter,\n  const char *zObj\n){\n  char *zList = 0;\n  if( p->rc==SQLITE_OK && pIter->abIndexed ){\n    const char *zS = \"\";\n    int i;\n    for(i=0; i<pIter->nTblCol; i++){\n      if( pIter->abIndexed[i] ){\n        const char *zCol = pIter->azTblCol[i];\n        zList = sqlite3_mprintf(\"%z%s%s.\\\"%w\\\"\", zList, zS, zObj, zCol);\n      }else{\n        zList = sqlite3_mprintf(\"%z%sNULL\", zList, zS);\n      }\n      zS = \", \";\n      if( zList==0 ){\n        p->rc = SQLITE_NOMEM;\n        break;\n      }\n    }\n\n    /* For a table with implicit rowids, append \"old._rowid_\" to the list. */\n    if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){\n      zList = rbuMPrintf(p, \"%z, %s._rowid_\", zList, zObj);\n    }\n  }\n  return zList;\n}\n\n/*\n** Return an expression that can be used in a WHERE clause to match the\n** primary key of the current table. For example, if the table is:\n**\n**   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));\n**\n** Return the string:\n**\n**   \"b = ?1 AND c = ?2\"\n*/\nstatic char *rbuObjIterGetWhere(\n  sqlite3rbu *p, \n  RbuObjIter *pIter\n){\n  char *zList = 0;\n  if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){\n    zList = rbuMPrintf(p, \"_rowid_ = ?%d\", pIter->nTblCol+1);\n  }else if( pIter->eType==RBU_PK_EXTERNAL ){\n    const char *zSep = \"\";\n    int i;\n    for(i=0; i<pIter->nTblCol; i++){\n      if( pIter->abTblPk[i] ){\n        zList = rbuMPrintf(p, \"%z%sc%d=?%d\", zList, zSep, i, i+1);\n        zSep = \" AND \";\n      }\n    }\n    zList = rbuMPrintf(p, \n        \"_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)\", zList\n    );\n\n  }else{\n    const char *zSep = \"\";\n    int i;\n    for(i=0; i<pIter->nTblCol; i++){\n      if( pIter->abTblPk[i] ){\n        const char *zCol = pIter->azTblCol[i];\n        zList = rbuMPrintf(p, \"%z%s\\\"%w\\\"=?%d\", zList, zSep, zCol, i+1);\n        zSep = \" AND \";\n      }\n    }\n  }\n  return zList;\n}\n\n/*\n** The SELECT statement iterating through the keys for the current object\n** (p->objiter.pSelect) currently points to a valid row. However, there\n** is something wrong with the rbu_control value in the rbu_control value\n** stored in the (p->nCol+1)'th column. Set the error code and error message\n** of the RBU handle to something reflecting this.\n*/\nstatic void rbuBadControlError(sqlite3rbu *p){\n  p->rc = SQLITE_ERROR;\n  p->zErrmsg = sqlite3_mprintf(\"invalid rbu_control value\");\n}\n\n\n/*\n** Return a nul-terminated string containing the comma separated list of\n** assignments that should be included following the \"SET\" keyword of\n** an UPDATE statement used to update the table object that the iterator\n** passed as the second argument currently points to if the rbu_control\n** column of the data_xxx table entry is set to zMask.\n**\n** The memory for the returned string is obtained from sqlite3_malloc().\n** It is the responsibility of the caller to eventually free it using\n** sqlite3_free(). \n**\n** If an OOM error is encountered when allocating space for the new\n** string, an error code is left in the rbu handle passed as the first\n** argument and NULL is returned. Or, if an error has already occurred\n** when this function is called, NULL is returned immediately, without\n** attempting the allocation or modifying the stored error code.\n*/\nstatic char *rbuObjIterGetSetlist(\n  sqlite3rbu *p,\n  RbuObjIter *pIter,\n  const char *zMask\n){\n  char *zList = 0;\n  if( p->rc==SQLITE_OK ){\n    int i;\n\n    if( (int)strlen(zMask)!=pIter->nTblCol ){\n      rbuBadControlError(p);\n    }else{\n      const char *zSep = \"\";\n      for(i=0; i<pIter->nTblCol; i++){\n        char c = zMask[pIter->aiSrcOrder[i]];\n        if( c=='x' ){\n          zList = rbuMPrintf(p, \"%z%s\\\"%w\\\"=?%d\", \n              zList, zSep, pIter->azTblCol[i], i+1\n          );\n          zSep = \", \";\n        }\n        else if( c=='d' ){\n          zList = rbuMPrintf(p, \"%z%s\\\"%w\\\"=rbu_delta(\\\"%w\\\", ?%d)\", \n              zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1\n          );\n          zSep = \", \";\n        }\n        else if( c=='f' ){\n          zList = rbuMPrintf(p, \"%z%s\\\"%w\\\"=rbu_fossil_delta(\\\"%w\\\", ?%d)\", \n              zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1\n          );\n          zSep = \", \";\n        }\n      }\n    }\n  }\n  return zList;\n}\n\n/*\n** Return a nul-terminated string consisting of nByte comma separated\n** \"?\" expressions. For example, if nByte is 3, return a pointer to\n** a buffer containing the string \"?,?,?\".\n**\n** The memory for the returned string is obtained from sqlite3_malloc().\n** It is the responsibility of the caller to eventually free it using\n** sqlite3_free(). \n**\n** If an OOM error is encountered when allocating space for the new\n** string, an error code is left in the rbu handle passed as the first\n** argument and NULL is returned. Or, if an error has already occurred\n** when this function is called, NULL is returned immediately, without\n** attempting the allocation or modifying the stored error code.\n*/\nstatic char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){\n  char *zRet = 0;\n  sqlite3_int64 nByte = 2*(sqlite3_int64)nBind + 1;\n\n  zRet = (char*)rbuMalloc(p, nByte);\n  if( zRet ){\n    int i;\n    for(i=0; i<nBind; i++){\n      zRet[i*2] = '?';\n      zRet[i*2+1] = (i+1==nBind) ? '\\0' : ',';\n    }\n  }\n  return zRet;\n}\n\n/*\n** The iterator currently points to a table (not index) of type \n** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY \n** declaration for the corresponding imposter table. For example,\n** if the iterator points to a table created as:\n**\n**   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID\n**\n** this function returns:\n**\n**   PRIMARY KEY(\"b\", \"a\" DESC)\n*/\nstatic char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){\n  char *z = 0;\n  assert( pIter->zIdx==0 );\n  if( p->rc==SQLITE_OK ){\n    const char *zSep = \"PRIMARY KEY(\";\n    sqlite3_stmt *pXList = 0;     /* PRAGMA index_list = (pIter->zTbl) */\n    sqlite3_stmt *pXInfo = 0;     /* PRAGMA index_xinfo = <pk-index> */\n   \n    p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,\n        sqlite3_mprintf(\"PRAGMA main.index_list = %Q\", pIter->zTbl)\n    );\n    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){\n      const char *zOrig = (const char*)sqlite3_column_text(pXList,3);\n      if( zOrig && strcmp(zOrig, \"pk\")==0 ){\n        const char *zIdx = (const char*)sqlite3_column_text(pXList,1);\n        if( zIdx ){\n          p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,\n              sqlite3_mprintf(\"PRAGMA main.index_xinfo = %Q\", zIdx)\n          );\n        }\n        break;\n      }\n    }\n    rbuFinalize(p, pXList);\n\n    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){\n      if( sqlite3_column_int(pXInfo, 5) ){\n        /* int iCid = sqlite3_column_int(pXInfo, 0); */\n        const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);\n        const char *zDesc = sqlite3_column_int(pXInfo, 3) ? \" DESC\" : \"\";\n        z = rbuMPrintf(p, \"%z%s\\\"%w\\\"%s\", z, zSep, zCol, zDesc);\n        zSep = \", \";\n      }\n    }\n    z = rbuMPrintf(p, \"%z)\", z);\n    rbuFinalize(p, pXInfo);\n  }\n  return z;\n}\n\n/*\n** This function creates the second imposter table used when writing to\n** a table b-tree where the table has an external primary key. If the\n** iterator passed as the second argument does not currently point to\n** a table (not index) with an external primary key, this function is a\n** no-op. \n**\n** Assuming the iterator does point to a table with an external PK, this\n** function creates a WITHOUT ROWID imposter table named \"rbu_imposter2\"\n** used to access that PK index. For example, if the target table is\n** declared as follows:\n**\n**   CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));\n**\n** then the imposter table schema is:\n**\n**   CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;\n**\n*/\nstatic void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){\n  if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){\n    int tnum = pIter->iPkTnum;    /* Root page of PK index */\n    sqlite3_stmt *pQuery = 0;     /* SELECT name ... WHERE rootpage = $tnum */\n    const char *zIdx = 0;         /* Name of PK index */\n    sqlite3_stmt *pXInfo = 0;     /* PRAGMA main.index_xinfo = $zIdx */\n    const char *zComma = \"\";\n    char *zCols = 0;              /* Used to build up list of table cols */\n    char *zPk = 0;                /* Used to build up table PK declaration */\n\n    /* Figure out the name of the primary key index for the current table.\n    ** This is needed for the argument to \"PRAGMA index_xinfo\". Set\n    ** zIdx to point to a nul-terminated string containing this name. */\n    p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg, \n        \"SELECT name FROM sqlite_master WHERE rootpage = ?\"\n    );\n    if( p->rc==SQLITE_OK ){\n      sqlite3_bind_int(pQuery, 1, tnum);\n      if( SQLITE_ROW==sqlite3_step(pQuery) ){\n        zIdx = (const char*)sqlite3_column_text(pQuery, 0);\n      }\n    }\n    if( zIdx ){\n      p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,\n          sqlite3_mprintf(\"PRAGMA main.index_xinfo = %Q\", zIdx)\n      );\n    }\n    rbuFinalize(p, pQuery);\n\n    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){\n      int bKey = sqlite3_column_int(pXInfo, 5);\n      if( bKey ){\n        int iCid = sqlite3_column_int(pXInfo, 1);\n        int bDesc = sqlite3_column_int(pXInfo, 3);\n        const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);\n        zCols = rbuMPrintf(p, \"%z%sc%d %s COLLATE %Q\", zCols, zComma, \n            iCid, pIter->azTblType[iCid], zCollate\n        );\n        zPk = rbuMPrintf(p, \"%z%sc%d%s\", zPk, zComma, iCid, bDesc?\" DESC\":\"\");\n        zComma = \", \";\n      }\n    }\n    zCols = rbuMPrintf(p, \"%z, id INTEGER\", zCols);\n    rbuFinalize(p, pXInfo);\n\n    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, \"main\", 1, tnum);\n    rbuMPrintfExec(p, p->dbMain,\n        \"CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID\", \n        zCols, zPk\n    );\n    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, \"main\", 0, 0);\n  }\n}\n\n/*\n** If an error has already occurred when this function is called, it \n** immediately returns zero (without doing any work). Or, if an error\n** occurs during the execution of this function, it sets the error code\n** in the sqlite3rbu object indicated by the first argument and returns\n** zero.\n**\n** The iterator passed as the second argument is guaranteed to point to\n** a table (not an index) when this function is called. This function\n** attempts to create any imposter table required to write to the main\n** table b-tree of the table before returning. Non-zero is returned if\n** an imposter table are created, or zero otherwise.\n**\n** An imposter table is required in all cases except RBU_PK_VTAB. Only\n** virtual tables are written to directly. The imposter table has the \n** same schema as the actual target table (less any UNIQUE constraints). \n** More precisely, the \"same schema\" means the same columns, types, \n** collation sequences. For tables that do not have an external PRIMARY\n** KEY, it also means the same PRIMARY KEY declaration.\n*/\nstatic void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){\n  if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){\n    int tnum = pIter->iTnum;\n    const char *zComma = \"\";\n    char *zSql = 0;\n    int iCol;\n    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, \"main\", 0, 1);\n\n    for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){\n      const char *zPk = \"\";\n      const char *zCol = pIter->azTblCol[iCol];\n      const char *zColl = 0;\n\n      p->rc = sqlite3_table_column_metadata(\n          p->dbMain, \"main\", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0\n      );\n\n      if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){\n        /* If the target table column is an \"INTEGER PRIMARY KEY\", add\n        ** \"PRIMARY KEY\" to the imposter table column declaration. */\n        zPk = \"PRIMARY KEY \";\n      }\n      zSql = rbuMPrintf(p, \"%z%s\\\"%w\\\" %s %sCOLLATE %Q%s\", \n          zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,\n          (pIter->abNotNull[iCol] ? \" NOT NULL\" : \"\")\n      );\n      zComma = \", \";\n    }\n\n    if( pIter->eType==RBU_PK_WITHOUT_ROWID ){\n      char *zPk = rbuWithoutRowidPK(p, pIter);\n      if( zPk ){\n        zSql = rbuMPrintf(p, \"%z, %z\", zSql, zPk);\n      }\n    }\n\n    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, \"main\", 1, tnum);\n    rbuMPrintfExec(p, p->dbMain, \"CREATE TABLE \\\"rbu_imp_%w\\\"(%z)%s\", \n        pIter->zTbl, zSql, \n        (pIter->eType==RBU_PK_WITHOUT_ROWID ? \" WITHOUT ROWID\" : \"\")\n    );\n    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, \"main\", 0, 0);\n  }\n}\n\n/*\n** Prepare a statement used to insert rows into the \"rbu_tmp_xxx\" table.\n** Specifically a statement of the form:\n**\n**     INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);\n**\n** The number of bound variables is equal to the number of columns in\n** the target table, plus one (for the rbu_control column), plus one more \n** (for the rbu_rowid column) if the target table is an implicit IPK or \n** virtual table.\n*/\nstatic void rbuObjIterPrepareTmpInsert(\n  sqlite3rbu *p, \n  RbuObjIter *pIter,\n  const char *zCollist,\n  const char *zRbuRowid\n){\n  int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);\n  char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);\n  if( zBind ){\n    assert( pIter->pTmpInsert==0 );\n    p->rc = prepareFreeAndCollectError(\n        p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(\n          \"INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)\", \n          p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind\n    ));\n  }\n}\n\nstatic void rbuTmpInsertFunc(\n  sqlite3_context *pCtx, \n  int nVal,\n  sqlite3_value **apVal\n){\n  sqlite3rbu *p = sqlite3_user_data(pCtx);\n  int rc = SQLITE_OK;\n  int i;\n\n  assert( sqlite3_value_int(apVal[0])!=0\n      || p->objiter.eType==RBU_PK_EXTERNAL \n      || p->objiter.eType==RBU_PK_NONE \n  );\n  if( sqlite3_value_int(apVal[0])!=0 ){\n    p->nPhaseOneStep += p->objiter.nIndex;\n  }\n\n  for(i=0; rc==SQLITE_OK && i<nVal; i++){\n    rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);\n  }\n  if( rc==SQLITE_OK ){\n    sqlite3_step(p->objiter.pTmpInsert);\n    rc = sqlite3_reset(p->objiter.pTmpInsert);\n  }\n\n  if( rc!=SQLITE_OK ){\n    sqlite3_result_error_code(pCtx, rc);\n  }\n}\n\nstatic char *rbuObjIterGetIndexWhere(sqlite3rbu *p, RbuObjIter *pIter){\n  sqlite3_stmt *pStmt = 0;\n  int rc = p->rc;\n  char *zRet = 0;\n\n  assert( pIter->zIdxSql==0 && pIter->nIdxCol==0 && pIter->aIdxCol==0 );\n\n  if( rc==SQLITE_OK ){\n    rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,\n        \"SELECT trim(sql) FROM sqlite_master WHERE type='index' AND name=?\"\n    );\n  }\n  if( rc==SQLITE_OK ){\n    int rc2;\n    rc = sqlite3_bind_text(pStmt, 1, pIter->zIdx, -1, SQLITE_STATIC);\n    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){\n      char *zSql = (char*)sqlite3_column_text(pStmt, 0);\n      if( zSql ){\n        pIter->zIdxSql = zSql = rbuStrndup(zSql, &rc);\n      }\n      if( zSql ){\n        int nParen = 0;           /* Number of open parenthesis */\n        int i;\n        int iIdxCol = 0;\n        int nIdxAlloc = 0;\n        for(i=0; zSql[i]; i++){\n          char c = zSql[i];\n\n          /* If necessary, grow the pIter->aIdxCol[] array */\n          if( iIdxCol==nIdxAlloc ){\n            RbuSpan *aIdxCol = (RbuSpan*)sqlite3_realloc(\n                pIter->aIdxCol, (nIdxAlloc+16)*sizeof(RbuSpan)\n            );\n            if( aIdxCol==0 ){\n              rc = SQLITE_NOMEM;\n              break;\n            }\n            pIter->aIdxCol = aIdxCol;\n            nIdxAlloc += 16;\n          }\n\n          if( c=='(' ){\n            if( nParen==0 ){\n              assert( iIdxCol==0 );\n              pIter->aIdxCol[0].zSpan = &zSql[i+1];\n            }\n            nParen++;\n          }\n          else if( c==')' ){\n            nParen--;\n            if( nParen==0 ){\n              int nSpan = &zSql[i] - pIter->aIdxCol[iIdxCol].zSpan;\n              pIter->aIdxCol[iIdxCol++].nSpan = nSpan;\n              i++;\n              break;\n            }\n          }else if( c==',' && nParen==1 ){\n            int nSpan = &zSql[i] - pIter->aIdxCol[iIdxCol].zSpan;\n            pIter->aIdxCol[iIdxCol++].nSpan = nSpan;\n            pIter->aIdxCol[iIdxCol].zSpan = &zSql[i+1];\n          }else if( c=='\"' || c=='\\'' || c=='`' ){\n            for(i++; 1; i++){\n              if( zSql[i]==c ){\n                if( zSql[i+1]!=c ) break;\n                i++;\n              }\n            }\n          }else if( c=='[' ){\n            for(i++; 1; i++){\n              if( zSql[i]==']' ) break;\n            }\n          }else if( c=='-' && zSql[i+1]=='-' ){\n            for(i=i+2; zSql[i] && zSql[i]!='\\n'; i++);\n            if( zSql[i]=='\\0' ) break;\n          }else if( c=='/' && zSql[i+1]=='*' ){\n            for(i=i+2; zSql[i] && (zSql[i]!='*' || zSql[i+1]!='/'); i++);\n            if( zSql[i]=='\\0' ) break;\n            i++;\n          }\n        }\n        if( zSql[i] ){\n          zRet = rbuStrndup(&zSql[i], &rc);\n        }\n        pIter->nIdxCol = iIdxCol;\n      }\n    }\n\n    rc2 = sqlite3_finalize(pStmt);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n\n  p->rc = rc;\n  return zRet;\n}\n\n/*\n** Ensure that the SQLite statement handles required to update the \n** target database object currently indicated by the iterator passed \n** as the second argument are available.\n*/\nstatic int rbuObjIterPrepareAll(\n  sqlite3rbu *p, \n  RbuObjIter *pIter,\n  int nOffset                     /* Add \"LIMIT -1 OFFSET $nOffset\" to SELECT */\n){\n  assert( pIter->bCleanup==0 );\n  if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){\n    const int tnum = pIter->iTnum;\n    char *zCollist = 0;           /* List of indexed columns */\n    char **pz = &p->zErrmsg;\n    const char *zIdx = pIter->zIdx;\n    char *zLimit = 0;\n\n    if( nOffset ){\n      zLimit = sqlite3_mprintf(\" LIMIT -1 OFFSET %d\", nOffset);\n      if( !zLimit ) p->rc = SQLITE_NOMEM;\n    }\n\n    if( zIdx ){\n      const char *zTbl = pIter->zTbl;\n      char *zImposterCols = 0;    /* Columns for imposter table */\n      char *zImposterPK = 0;      /* Primary key declaration for imposter */\n      char *zWhere = 0;           /* WHERE clause on PK columns */\n      char *zBind = 0;\n      char *zPart = 0;\n      int nBind = 0;\n\n      assert( pIter->eType!=RBU_PK_VTAB );\n      zPart = rbuObjIterGetIndexWhere(p, pIter);\n      zCollist = rbuObjIterGetIndexCols(\n          p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind\n      );\n      zBind = rbuObjIterGetBindlist(p, nBind);\n\n      /* Create the imposter table used to write to this index. */\n      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, \"main\", 0, 1);\n      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, \"main\", 1,tnum);\n      rbuMPrintfExec(p, p->dbMain,\n          \"CREATE TABLE \\\"rbu_imp_%w\\\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID\",\n          zTbl, zImposterCols, zImposterPK\n      );\n      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, \"main\", 0, 0);\n\n      /* Create the statement to insert index entries */\n      pIter->nCol = nBind;\n      if( p->rc==SQLITE_OK ){\n        p->rc = prepareFreeAndCollectError(\n            p->dbMain, &pIter->pInsert, &p->zErrmsg,\n          sqlite3_mprintf(\"INSERT INTO \\\"rbu_imp_%w\\\" VALUES(%s)\", zTbl, zBind)\n        );\n      }\n\n      /* And to delete index entries */\n      if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){\n        p->rc = prepareFreeAndCollectError(\n            p->dbMain, &pIter->pDelete, &p->zErrmsg,\n          sqlite3_mprintf(\"DELETE FROM \\\"rbu_imp_%w\\\" WHERE %s\", zTbl, zWhere)\n        );\n      }\n\n      /* Create the SELECT statement to read keys in sorted order */\n      if( p->rc==SQLITE_OK ){\n        char *zSql;\n        if( rbuIsVacuum(p) ){\n          char *zStart = 0;\n          if( nOffset ){\n            zStart = rbuVacuumIndexStart(p, pIter);\n            if( zStart ){\n              sqlite3_free(zLimit);\n              zLimit = 0;\n            }\n          }\n\n          zSql = sqlite3_mprintf(\n              \"SELECT %s, 0 AS rbu_control FROM '%q' %s %s %s ORDER BY %s%s\",\n              zCollist, \n              pIter->zDataTbl,\n              zPart, \n              (zStart ? (zPart ? \"AND\" : \"WHERE\") : \"\"), zStart,\n              zCollist, zLimit\n          );\n          sqlite3_free(zStart);\n        }else\n\n        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){\n          zSql = sqlite3_mprintf(\n              \"SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s ORDER BY %s%s\",\n              zCollist, p->zStateDb, pIter->zDataTbl,\n              zPart, zCollist, zLimit\n          );\n        }else{\n          zSql = sqlite3_mprintf(\n              \"SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s \"\n              \"UNION ALL \"\n              \"SELECT %s, rbu_control FROM '%q' \"\n              \"%s %s typeof(rbu_control)='integer' AND rbu_control!=1 \"\n              \"ORDER BY %s%s\",\n              zCollist, p->zStateDb, pIter->zDataTbl, zPart,\n              zCollist, pIter->zDataTbl, \n              zPart,\n              (zPart ? \"AND\" : \"WHERE\"),\n              zCollist, zLimit\n          );\n        }\n        if( p->rc==SQLITE_OK ){\n          p->rc = prepareFreeAndCollectError(p->dbRbu,&pIter->pSelect,pz,zSql);\n        }else{\n          sqlite3_free(zSql);\n        }\n      }\n\n      sqlite3_free(zImposterCols);\n      sqlite3_free(zImposterPK);\n      sqlite3_free(zWhere);\n      sqlite3_free(zBind);\n      sqlite3_free(zPart);\n    }else{\n      int bRbuRowid = (pIter->eType==RBU_PK_VTAB)\n                    ||(pIter->eType==RBU_PK_NONE)\n                    ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));\n      const char *zTbl = pIter->zTbl;       /* Table this step applies to */\n      const char *zWrite;                   /* Imposter table name */\n\n      char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);\n      char *zWhere = rbuObjIterGetWhere(p, pIter);\n      char *zOldlist = rbuObjIterGetOldlist(p, pIter, \"old\");\n      char *zNewlist = rbuObjIterGetOldlist(p, pIter, \"new\");\n\n      zCollist = rbuObjIterGetCollist(p, pIter);\n      pIter->nCol = pIter->nTblCol;\n\n      /* Create the imposter table or tables (if required). */\n      rbuCreateImposterTable(p, pIter);\n      rbuCreateImposterTable2(p, pIter);\n      zWrite = (pIter->eType==RBU_PK_VTAB ? \"\" : \"rbu_imp_\");\n\n      /* Create the INSERT statement to write to the target PK b-tree */\n      if( p->rc==SQLITE_OK ){\n        p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,\n            sqlite3_mprintf(\n              \"INSERT INTO \\\"%s%w\\\"(%s%s) VALUES(%s)\", \n              zWrite, zTbl, zCollist, (bRbuRowid ? \", _rowid_\" : \"\"), zBindings\n            )\n        );\n      }\n\n      /* Create the DELETE statement to write to the target PK b-tree.\n      ** Because it only performs INSERT operations, this is not required for\n      ** an rbu vacuum handle.  */\n      if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){\n        p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,\n            sqlite3_mprintf(\n              \"DELETE FROM \\\"%s%w\\\" WHERE %s\", zWrite, zTbl, zWhere\n            )\n        );\n      }\n\n      if( rbuIsVacuum(p)==0 && pIter->abIndexed ){\n        const char *zRbuRowid = \"\";\n        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){\n          zRbuRowid = \", rbu_rowid\";\n        }\n\n        /* Create the rbu_tmp_xxx table and the triggers to populate it. */\n        rbuMPrintfExec(p, p->dbRbu,\n            \"CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS \"\n            \"SELECT *%s FROM '%q' WHERE 0;\"\n            , p->zStateDb, pIter->zDataTbl\n            , (pIter->eType==RBU_PK_EXTERNAL ? \", 0 AS rbu_rowid\" : \"\")\n            , pIter->zDataTbl\n        );\n\n        rbuMPrintfExec(p, p->dbMain,\n            \"CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \\\"%s%w\\\" \"\n            \"BEGIN \"\n            \"  SELECT rbu_tmp_insert(3, %s);\"\n            \"END;\"\n\n            \"CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \\\"%s%w\\\" \"\n            \"BEGIN \"\n            \"  SELECT rbu_tmp_insert(3, %s);\"\n            \"END;\"\n\n            \"CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \\\"%s%w\\\" \"\n            \"BEGIN \"\n            \"  SELECT rbu_tmp_insert(4, %s);\"\n            \"END;\",\n            zWrite, zTbl, zOldlist,\n            zWrite, zTbl, zOldlist,\n            zWrite, zTbl, zNewlist\n        );\n\n        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){\n          rbuMPrintfExec(p, p->dbMain,\n              \"CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \\\"%s%w\\\" \"\n              \"BEGIN \"\n              \"  SELECT rbu_tmp_insert(0, %s);\"\n              \"END;\",\n              zWrite, zTbl, zNewlist\n          );\n        }\n\n        rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);\n      }\n\n      /* Create the SELECT statement to read keys from data_xxx */\n      if( p->rc==SQLITE_OK ){\n        const char *zRbuRowid = \"\";\n        char *zStart = 0;\n        char *zOrder = 0;\n        if( bRbuRowid ){\n          zRbuRowid = rbuIsVacuum(p) ? \",_rowid_ \" : \",rbu_rowid\";\n        }\n\n        if( rbuIsVacuum(p) ){\n          if( nOffset ){\n            zStart = rbuVacuumTableStart(p, pIter, bRbuRowid, zWrite);\n            if( zStart ){\n              sqlite3_free(zLimit);\n              zLimit = 0;\n            }\n          }\n          if( bRbuRowid ){\n            zOrder = rbuMPrintf(p, \"_rowid_\");\n          }else{\n            zOrder = rbuObjIterGetPkList(p, pIter, \"\", \", \", \"\");\n          }\n        }\n\n        if( p->rc==SQLITE_OK ){\n          p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,\n              sqlite3_mprintf(\n                \"SELECT %s,%s rbu_control%s FROM '%q'%s %s %s %s\",\n                zCollist, \n                (rbuIsVacuum(p) ? \"0 AS \" : \"\"),\n                zRbuRowid,\n                pIter->zDataTbl, (zStart ? zStart : \"\"), \n                (zOrder ? \"ORDER BY\" : \"\"), zOrder,\n                zLimit\n              )\n          );\n        }\n        sqlite3_free(zStart);\n        sqlite3_free(zOrder);\n      }\n\n      sqlite3_free(zWhere);\n      sqlite3_free(zOldlist);\n      sqlite3_free(zNewlist);\n      sqlite3_free(zBindings);\n    }\n    sqlite3_free(zCollist);\n    sqlite3_free(zLimit);\n  }\n  \n  return p->rc;\n}\n\n/*\n** Set output variable *ppStmt to point to an UPDATE statement that may\n** be used to update the imposter table for the main table b-tree of the\n** table object that pIter currently points to, assuming that the \n** rbu_control column of the data_xyz table contains zMask.\n** \n** If the zMask string does not specify any columns to update, then this\n** is not an error. Output variable *ppStmt is set to NULL in this case.\n*/\nstatic int rbuGetUpdateStmt(\n  sqlite3rbu *p,                  /* RBU handle */\n  RbuObjIter *pIter,              /* Object iterator */\n  const char *zMask,              /* rbu_control value ('x.x.') */\n  sqlite3_stmt **ppStmt           /* OUT: UPDATE statement handle */\n){\n  RbuUpdateStmt **pp;\n  RbuUpdateStmt *pUp = 0;\n  int nUp = 0;\n\n  /* In case an error occurs */\n  *ppStmt = 0;\n\n  /* Search for an existing statement. If one is found, shift it to the front\n  ** of the LRU queue and return immediately. Otherwise, leave nUp pointing\n  ** to the number of statements currently in the cache and pUp to the\n  ** last object in the list.  */\n  for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){\n    pUp = *pp;\n    if( strcmp(pUp->zMask, zMask)==0 ){\n      *pp = pUp->pNext;\n      pUp->pNext = pIter->pRbuUpdate;\n      pIter->pRbuUpdate = pUp;\n      *ppStmt = pUp->pUpdate; \n      return SQLITE_OK;\n    }\n    nUp++;\n  }\n  assert( pUp==0 || pUp->pNext==0 );\n\n  if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){\n    for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));\n    *pp = 0;\n    sqlite3_finalize(pUp->pUpdate);\n    pUp->pUpdate = 0;\n  }else{\n    pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);\n  }\n\n  if( pUp ){\n    char *zWhere = rbuObjIterGetWhere(p, pIter);\n    char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);\n    char *zUpdate = 0;\n\n    pUp->zMask = (char*)&pUp[1];\n    memcpy(pUp->zMask, zMask, pIter->nTblCol);\n    pUp->pNext = pIter->pRbuUpdate;\n    pIter->pRbuUpdate = pUp;\n\n    if( zSet ){\n      const char *zPrefix = \"\";\n\n      if( pIter->eType!=RBU_PK_VTAB ) zPrefix = \"rbu_imp_\";\n      zUpdate = sqlite3_mprintf(\"UPDATE \\\"%s%w\\\" SET %s WHERE %s\", \n          zPrefix, pIter->zTbl, zSet, zWhere\n      );\n      p->rc = prepareFreeAndCollectError(\n          p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate\n      );\n      *ppStmt = pUp->pUpdate;\n    }\n    sqlite3_free(zWhere);\n    sqlite3_free(zSet);\n  }\n\n  return p->rc;\n}\n\nstatic sqlite3 *rbuOpenDbhandle(\n  sqlite3rbu *p, \n  const char *zName, \n  int bUseVfs\n){\n  sqlite3 *db = 0;\n  if( p->rc==SQLITE_OK ){\n    const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;\n    p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);\n    if( p->rc ){\n      p->zErrmsg = sqlite3_mprintf(\"%s\", sqlite3_errmsg(db));\n      sqlite3_close(db);\n      db = 0;\n    }\n  }\n  return db;\n}\n\n/*\n** Free an RbuState object allocated by rbuLoadState().\n*/\nstatic void rbuFreeState(RbuState *p){\n  if( p ){\n    sqlite3_free(p->zTbl);\n    sqlite3_free(p->zDataTbl);\n    sqlite3_free(p->zIdx);\n    sqlite3_free(p);\n  }\n}\n\n/*\n** Allocate an RbuState object and load the contents of the rbu_state \n** table into it. Return a pointer to the new object. It is the \n** responsibility of the caller to eventually free the object using\n** sqlite3_free().\n**\n** If an error occurs, leave an error code and message in the rbu handle\n** and return NULL.\n*/\nstatic RbuState *rbuLoadState(sqlite3rbu *p){\n  RbuState *pRet = 0;\n  sqlite3_stmt *pStmt = 0;\n  int rc;\n  int rc2;\n\n  pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));\n  if( pRet==0 ) return 0;\n\n  rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, \n      sqlite3_mprintf(\"SELECT k, v FROM %s.rbu_state\", p->zStateDb)\n  );\n  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){\n    switch( sqlite3_column_int(pStmt, 0) ){\n      case RBU_STATE_STAGE:\n        pRet->eStage = sqlite3_column_int(pStmt, 1);\n        if( pRet->eStage!=RBU_STAGE_OAL\n         && pRet->eStage!=RBU_STAGE_MOVE\n         && pRet->eStage!=RBU_STAGE_CKPT\n        ){\n          p->rc = SQLITE_CORRUPT;\n        }\n        break;\n\n      case RBU_STATE_TBL:\n        pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);\n        break;\n\n      case RBU_STATE_IDX:\n        pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);\n        break;\n\n      case RBU_STATE_ROW:\n        pRet->nRow = sqlite3_column_int(pStmt, 1);\n        break;\n\n      case RBU_STATE_PROGRESS:\n        pRet->nProgress = sqlite3_column_int64(pStmt, 1);\n        break;\n\n      case RBU_STATE_CKPT:\n        pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);\n        break;\n\n      case RBU_STATE_COOKIE:\n        pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);\n        break;\n\n      case RBU_STATE_OALSZ:\n        pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);\n        break;\n\n      case RBU_STATE_PHASEONESTEP:\n        pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);\n        break;\n\n      case RBU_STATE_DATATBL:\n        pRet->zDataTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);\n        break;\n\n      default:\n        rc = SQLITE_CORRUPT;\n        break;\n    }\n  }\n  rc2 = sqlite3_finalize(pStmt);\n  if( rc==SQLITE_OK ) rc = rc2;\n\n  p->rc = rc;\n  return pRet;\n}\n\n\n/*\n** Open the database handle and attach the RBU database as \"rbu\". If an\n** error occurs, leave an error code and message in the RBU handle.\n*/\nstatic void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){\n  assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );\n  assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );\n\n  /* Open the RBU database */\n  p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);\n\n  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){\n    sqlite3_file_control(p->dbRbu, \"main\", SQLITE_FCNTL_RBUCNT, (void*)p);\n    if( p->zState==0 ){\n      const char *zFile = sqlite3_db_filename(p->dbRbu, \"main\");\n      p->zState = rbuMPrintf(p, \"file://%s-vacuum?modeof=%s\", zFile, zFile);\n    }\n  }\n\n  /* If using separate RBU and state databases, attach the state database to\n  ** the RBU db handle now.  */\n  if( p->zState ){\n    rbuMPrintfExec(p, p->dbRbu, \"ATTACH %Q AS stat\", p->zState);\n    memcpy(p->zStateDb, \"stat\", 4);\n  }else{\n    memcpy(p->zStateDb, \"main\", 4);\n  }\n\n#if 0\n  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){\n    p->rc = sqlite3_exec(p->dbRbu, \"BEGIN\", 0, 0, 0);\n  }\n#endif\n\n  /* If it has not already been created, create the rbu_state table */\n  rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);\n\n#if 0\n  if( rbuIsVacuum(p) ){\n    if( p->rc==SQLITE_OK ){\n      int rc2;\n      int bOk = 0;\n      sqlite3_stmt *pCnt = 0;\n      p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,\n          \"SELECT count(*) FROM stat.sqlite_master\"\n      );\n      if( p->rc==SQLITE_OK \n       && sqlite3_step(pCnt)==SQLITE_ROW\n       && 1==sqlite3_column_int(pCnt, 0)\n      ){\n        bOk = 1;\n      }\n      rc2 = sqlite3_finalize(pCnt);\n      if( p->rc==SQLITE_OK ) p->rc = rc2;\n\n      if( p->rc==SQLITE_OK && bOk==0 ){\n        p->rc = SQLITE_ERROR;\n        p->zErrmsg = sqlite3_mprintf(\"invalid state database\");\n      }\n    \n      if( p->rc==SQLITE_OK ){\n        p->rc = sqlite3_exec(p->dbRbu, \"COMMIT\", 0, 0, 0);\n      }\n    }\n  }\n#endif\n\n  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){\n    int bOpen = 0;\n    int rc;\n    p->nRbu = 0;\n    p->pRbuFd = 0;\n    rc = sqlite3_file_control(p->dbRbu, \"main\", SQLITE_FCNTL_RBUCNT, (void*)p);\n    if( rc!=SQLITE_NOTFOUND ) p->rc = rc;\n    if( p->eStage>=RBU_STAGE_MOVE ){\n      bOpen = 1;\n    }else{\n      RbuState *pState = rbuLoadState(p);\n      if( pState ){\n        bOpen = (pState->eStage>=RBU_STAGE_MOVE);\n        rbuFreeState(pState);\n      }\n    }\n    if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);\n  }\n\n  p->eStage = 0;\n  if( p->rc==SQLITE_OK && p->dbMain==0 ){\n    if( !rbuIsVacuum(p) ){\n      p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);\n    }else if( p->pRbuFd->pWalFd ){\n      if( pbRetry ){\n        p->pRbuFd->bNolock = 0;\n        sqlite3_close(p->dbRbu);\n        sqlite3_close(p->dbMain);\n        p->dbMain = 0;\n        p->dbRbu = 0;\n        *pbRetry = 1;\n        return;\n      }\n      p->rc = SQLITE_ERROR;\n      p->zErrmsg = sqlite3_mprintf(\"cannot vacuum wal mode database\");\n    }else{\n      char *zTarget;\n      char *zExtra = 0;\n      if( strlen(p->zRbu)>=5 && 0==memcmp(\"file:\", p->zRbu, 5) ){\n        zExtra = &p->zRbu[5];\n        while( *zExtra ){\n          if( *zExtra++=='?' ) break;\n        }\n        if( *zExtra=='\\0' ) zExtra = 0;\n      }\n\n      zTarget = sqlite3_mprintf(\"file:%s-vactmp?rbu_memory=1%s%s\", \n          sqlite3_db_filename(p->dbRbu, \"main\"),\n          (zExtra==0 ? \"\" : \"&\"), (zExtra==0 ? \"\" : zExtra)\n      );\n\n      if( zTarget==0 ){\n        p->rc = SQLITE_NOMEM;\n        return;\n      }\n      p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);\n      sqlite3_free(zTarget);\n    }\n  }\n\n  if( p->rc==SQLITE_OK ){\n    p->rc = sqlite3_create_function(p->dbMain, \n        \"rbu_tmp_insert\", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0\n    );\n  }\n\n  if( p->rc==SQLITE_OK ){\n    p->rc = sqlite3_create_function(p->dbMain, \n        \"rbu_fossil_delta\", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0\n    );\n  }\n\n  if( p->rc==SQLITE_OK ){\n    p->rc = sqlite3_create_function(p->dbRbu, \n        \"rbu_target_name\", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0\n    );\n  }\n\n  if( p->rc==SQLITE_OK ){\n    p->rc = sqlite3_file_control(p->dbMain, \"main\", SQLITE_FCNTL_RBU, (void*)p);\n  }\n  rbuMPrintfExec(p, p->dbMain, \"SELECT * FROM sqlite_master\");\n\n  /* Mark the database file just opened as an RBU target database. If \n  ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.\n  ** This is an error.  */\n  if( p->rc==SQLITE_OK ){\n    p->rc = sqlite3_file_control(p->dbMain, \"main\", SQLITE_FCNTL_RBU, (void*)p);\n  }\n\n  if( p->rc==SQLITE_NOTFOUND ){\n    p->rc = SQLITE_ERROR;\n    p->zErrmsg = sqlite3_mprintf(\"rbu vfs not found\");\n  }\n}\n\n/*\n** This routine is a copy of the sqlite3FileSuffix3() routine from the core.\n** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.\n**\n** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database\n** filename in zBaseFilename is a URI with the \"8_3_names=1\" parameter and\n** if filename in z[] has a suffix (a.k.a. \"extension\") that is longer than\n** three characters, then shorten the suffix on z[] to be the last three\n** characters of the original suffix.\n**\n** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always\n** do the suffix shortening regardless of URI parameter.\n**\n** Examples:\n**\n**     test.db-journal    =>   test.nal\n**     test.db-wal        =>   test.wal\n**     test.db-shm        =>   test.shm\n**     test.db-mj7f3319fa =>   test.9fa\n*/\nstatic void rbuFileSuffix3(const char *zBase, char *z){\n#ifdef SQLITE_ENABLE_8_3_NAMES\n#if SQLITE_ENABLE_8_3_NAMES<2\n  if( sqlite3_uri_boolean(zBase, \"8_3_names\", 0) )\n#endif\n  {\n    int i, sz;\n    sz = (int)strlen(z)&0xffffff;\n    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}\n    if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);\n  }\n#endif\n}\n\n/*\n** Return the current wal-index header checksum for the target database \n** as a 64-bit integer.\n**\n** The checksum is store in the first page of xShmMap memory as an 8-byte \n** blob starting at byte offset 40.\n*/\nstatic i64 rbuShmChecksum(sqlite3rbu *p){\n  i64 iRet = 0;\n  if( p->rc==SQLITE_OK ){\n    sqlite3_file *pDb = p->pTargetFd->pReal;\n    u32 volatile *ptr;\n    p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);\n    if( p->rc==SQLITE_OK ){\n      iRet = ((i64)ptr[10] << 32) + ptr[11];\n    }\n  }\n  return iRet;\n}\n\n/*\n** This function is called as part of initializing or reinitializing an\n** incremental checkpoint. \n**\n** It populates the sqlite3rbu.aFrame[] array with the set of \n** (wal frame -> db page) copy operations required to checkpoint the \n** current wal file, and obtains the set of shm locks required to safely \n** perform the copy operations directly on the file-system.\n**\n** If argument pState is not NULL, then the incremental checkpoint is\n** being resumed. In this case, if the checksum of the wal-index-header\n** following recovery is not the same as the checksum saved in the RbuState\n** object, then the rbu handle is set to DONE state. This occurs if some\n** other client appends a transaction to the wal file in the middle of\n** an incremental checkpoint.\n*/\nstatic void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){\n\n  /* If pState is NULL, then the wal file may not have been opened and\n  ** recovered. Running a read-statement here to ensure that doing so\n  ** does not interfere with the \"capture\" process below.  */\n  if( pState==0 ){\n    p->eStage = 0;\n    if( p->rc==SQLITE_OK ){\n      p->rc = sqlite3_exec(p->dbMain, \"SELECT * FROM sqlite_master\", 0, 0, 0);\n    }\n  }\n\n  /* Assuming no error has occurred, run a \"restart\" checkpoint with the\n  ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following\n  ** special behaviour in the rbu VFS:\n  **\n  **   * If the exclusive shm WRITER or READ0 lock cannot be obtained,\n  **     the checkpoint fails with SQLITE_BUSY (normally SQLite would\n  **     proceed with running a passive checkpoint instead of failing).\n  **\n  **   * Attempts to read from the *-wal file or write to the database file\n  **     do not perform any IO. Instead, the frame/page combinations that\n  **     would be read/written are recorded in the sqlite3rbu.aFrame[]\n  **     array.\n  **\n  **   * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER, \n  **     READ0 and CHECKPOINT locks taken as part of the checkpoint are\n  **     no-ops. These locks will not be released until the connection\n  **     is closed.\n  **\n  **   * Attempting to xSync() the database file causes an SQLITE_INTERNAL \n  **     error.\n  **\n  ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the\n  ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]\n  ** array populated with a set of (frame -> page) mappings. Because the \n  ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy \n  ** data from the wal file into the database file according to the \n  ** contents of aFrame[].\n  */\n  if( p->rc==SQLITE_OK ){\n    int rc2;\n    p->eStage = RBU_STAGE_CAPTURE;\n    rc2 = sqlite3_exec(p->dbMain, \"PRAGMA main.wal_checkpoint=restart\", 0, 0,0);\n    if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;\n  }\n\n  if( p->rc==SQLITE_OK && p->nFrame>0 ){\n    p->eStage = RBU_STAGE_CKPT;\n    p->nStep = (pState ? pState->nRow : 0);\n    p->aBuf = rbuMalloc(p, p->pgsz);\n    p->iWalCksum = rbuShmChecksum(p);\n  }\n\n  if( p->rc==SQLITE_OK ){\n    if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){\n      p->rc = SQLITE_DONE;\n      p->eStage = RBU_STAGE_DONE;\n    }else{\n      int nSectorSize;\n      sqlite3_file *pDb = p->pTargetFd->pReal;\n      sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;\n      assert( p->nPagePerSector==0 );\n      nSectorSize = pDb->pMethods->xSectorSize(pDb);\n      if( nSectorSize>p->pgsz ){\n        p->nPagePerSector = nSectorSize / p->pgsz;\n      }else{\n        p->nPagePerSector = 1;\n      }\n\n      /* Call xSync() on the wal file. This causes SQLite to sync the \n      ** directory in which the target database and the wal file reside, in \n      ** case it has not been synced since the rename() call in \n      ** rbuMoveOalFile(). */\n      p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);\n    }\n  }\n}\n\n/*\n** Called when iAmt bytes are read from offset iOff of the wal file while\n** the rbu object is in capture mode. Record the frame number of the frame\n** being read in the aFrame[] array.\n*/\nstatic int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){\n  const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);\n  u32 iFrame;\n\n  if( pRbu->mLock!=mReq ){\n    pRbu->rc = SQLITE_BUSY;\n    return SQLITE_INTERNAL;\n  }\n\n  pRbu->pgsz = iAmt;\n  if( pRbu->nFrame==pRbu->nFrameAlloc ){\n    int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;\n    RbuFrame *aNew;\n    aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));\n    if( aNew==0 ) return SQLITE_NOMEM;\n    pRbu->aFrame = aNew;\n    pRbu->nFrameAlloc = nNew;\n  }\n\n  iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;\n  if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;\n  pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;\n  pRbu->aFrame[pRbu->nFrame].iDbPage = 0;\n  pRbu->nFrame++;\n  return SQLITE_OK;\n}\n\n/*\n** Called when a page of data is written to offset iOff of the database\n** file while the rbu handle is in capture mode. Record the page number \n** of the page being written in the aFrame[] array.\n*/\nstatic int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){\n  pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;\n  return SQLITE_OK;\n}\n\n/*\n** This is called as part of an incremental checkpoint operation. Copy\n** a single frame of data from the wal file into the database file, as\n** indicated by the RbuFrame object.\n*/\nstatic void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){\n  sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;\n  sqlite3_file *pDb = p->pTargetFd->pReal;\n  i64 iOff;\n\n  assert( p->rc==SQLITE_OK );\n  iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;\n  p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);\n  if( p->rc ) return;\n\n  iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;\n  p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);\n}\n\n\n/*\n** Take an EXCLUSIVE lock on the database file.\n*/\nstatic void rbuLockDatabase(sqlite3rbu *p){\n  sqlite3_file *pReal = p->pTargetFd->pReal;\n  assert( p->rc==SQLITE_OK );\n  p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);\n  if( p->rc==SQLITE_OK ){\n    p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);\n  }\n}\n\n#if defined(_WIN32_WCE)\nstatic LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){\n  int nChar;\n  LPWSTR zWideFilename;\n\n  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);\n  if( nChar==0 ){\n    return 0;\n  }\n  zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );\n  if( zWideFilename==0 ){\n    return 0;\n  }\n  memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));\n  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,\n                                nChar);\n  if( nChar==0 ){\n    sqlite3_free(zWideFilename);\n    zWideFilename = 0;\n  }\n  return zWideFilename;\n}\n#endif\n\n/*\n** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock\n** on the database file. This proc moves the *-oal file to the *-wal path,\n** then reopens the database file (this time in vanilla, non-oal, WAL mode).\n** If an error occurs, leave an error code and error message in the rbu \n** handle.\n*/\nstatic void rbuMoveOalFile(sqlite3rbu *p){\n  const char *zBase = sqlite3_db_filename(p->dbMain, \"main\");\n  const char *zMove = zBase;\n  char *zOal;\n  char *zWal;\n\n  if( rbuIsVacuum(p) ){\n    zMove = sqlite3_db_filename(p->dbRbu, \"main\");\n  }\n  zOal = sqlite3_mprintf(\"%s-oal\", zMove);\n  zWal = sqlite3_mprintf(\"%s-wal\", zMove);\n\n  assert( p->eStage==RBU_STAGE_MOVE );\n  assert( p->rc==SQLITE_OK && p->zErrmsg==0 );\n  if( zWal==0 || zOal==0 ){\n    p->rc = SQLITE_NOMEM;\n  }else{\n    /* Move the *-oal file to *-wal. At this point connection p->db is\n    ** holding a SHARED lock on the target database file (because it is\n    ** in WAL mode). So no other connection may be writing the db. \n    **\n    ** In order to ensure that there are no database readers, an EXCLUSIVE\n    ** lock is obtained here before the *-oal is moved to *-wal.\n    */\n    rbuLockDatabase(p);\n    if( p->rc==SQLITE_OK ){\n      rbuFileSuffix3(zBase, zWal);\n      rbuFileSuffix3(zBase, zOal);\n\n      /* Re-open the databases. */\n      rbuObjIterFinalize(&p->objiter);\n      sqlite3_close(p->dbRbu);\n      sqlite3_close(p->dbMain);\n      p->dbMain = 0;\n      p->dbRbu = 0;\n\n#if defined(_WIN32_WCE)\n      {\n        LPWSTR zWideOal;\n        LPWSTR zWideWal;\n\n        zWideOal = rbuWinUtf8ToUnicode(zOal);\n        if( zWideOal ){\n          zWideWal = rbuWinUtf8ToUnicode(zWal);\n          if( zWideWal ){\n            if( MoveFileW(zWideOal, zWideWal) ){\n              p->rc = SQLITE_OK;\n            }else{\n              p->rc = SQLITE_IOERR;\n            }\n            sqlite3_free(zWideWal);\n          }else{\n            p->rc = SQLITE_IOERR_NOMEM;\n          }\n          sqlite3_free(zWideOal);\n        }else{\n          p->rc = SQLITE_IOERR_NOMEM;\n        }\n      }\n#else\n      p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;\n#endif\n\n      if( p->rc==SQLITE_OK ){\n        rbuOpenDatabase(p, 0);\n        rbuSetupCheckpoint(p, 0);\n      }\n    }\n  }\n\n  sqlite3_free(zWal);\n  sqlite3_free(zOal);\n}\n\n/*\n** The SELECT statement iterating through the keys for the current object\n** (p->objiter.pSelect) currently points to a valid row. This function\n** determines the type of operation requested by this row and returns\n** one of the following values to indicate the result:\n**\n**     * RBU_INSERT\n**     * RBU_DELETE\n**     * RBU_IDX_DELETE\n**     * RBU_UPDATE\n**\n** If RBU_UPDATE is returned, then output variable *pzMask is set to\n** point to the text value indicating the columns to update.\n**\n** If the rbu_control field contains an invalid value, an error code and\n** message are left in the RBU handle and zero returned.\n*/\nstatic int rbuStepType(sqlite3rbu *p, const char **pzMask){\n  int iCol = p->objiter.nCol;     /* Index of rbu_control column */\n  int res = 0;                    /* Return value */\n\n  switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){\n    case SQLITE_INTEGER: {\n      int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);\n      switch( iVal ){\n        case 0: res = RBU_INSERT;     break;\n        case 1: res = RBU_DELETE;     break;\n        case 2: res = RBU_REPLACE;    break;\n        case 3: res = RBU_IDX_DELETE; break;\n        case 4: res = RBU_IDX_INSERT; break;\n      }\n      break;\n    }\n\n    case SQLITE_TEXT: {\n      const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);\n      if( z==0 ){\n        p->rc = SQLITE_NOMEM;\n      }else{\n        *pzMask = (const char*)z;\n      }\n      res = RBU_UPDATE;\n\n      break;\n    }\n\n    default:\n      break;\n  }\n\n  if( res==0 ){\n    rbuBadControlError(p);\n  }\n  return res;\n}\n\n#ifdef SQLITE_DEBUG\n/*\n** Assert that column iCol of statement pStmt is named zName.\n*/\nstatic void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){\n  const char *zCol = sqlite3_column_name(pStmt, iCol);\n  assert( 0==sqlite3_stricmp(zName, zCol) );\n}\n#else\n# define assertColumnName(x,y,z)\n#endif\n\n/*\n** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or\n** RBU_IDX_DELETE. This function performs the work of a single\n** sqlite3rbu_step() call for the type of operation specified by eType.\n*/\nstatic void rbuStepOneOp(sqlite3rbu *p, int eType){\n  RbuObjIter *pIter = &p->objiter;\n  sqlite3_value *pVal;\n  sqlite3_stmt *pWriter;\n  int i;\n\n  assert( p->rc==SQLITE_OK );\n  assert( eType!=RBU_DELETE || pIter->zIdx==0 );\n  assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE\n       || eType==RBU_INSERT || eType==RBU_IDX_INSERT\n  );\n\n  /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE\n  ** statement below does actually delete a row, nPhaseOneStep will be\n  ** incremented by the same amount when SQL function rbu_tmp_insert()\n  ** is invoked by the trigger.  */\n  if( eType==RBU_DELETE ){\n    p->nPhaseOneStep -= p->objiter.nIndex;\n  }\n\n  if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){\n    pWriter = pIter->pDelete;\n  }else{\n    pWriter = pIter->pInsert;\n  }\n\n  for(i=0; i<pIter->nCol; i++){\n    /* If this is an INSERT into a table b-tree and the table has an\n    ** explicit INTEGER PRIMARY KEY, check that this is not an attempt\n    ** to write a NULL into the IPK column. That is not permitted.  */\n    if( eType==RBU_INSERT \n     && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i] \n     && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL\n    ){\n      p->rc = SQLITE_MISMATCH;\n      p->zErrmsg = sqlite3_mprintf(\"datatype mismatch\");\n      return;\n    }\n\n    if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){\n      continue;\n    }\n\n    pVal = sqlite3_column_value(pIter->pSelect, i);\n    p->rc = sqlite3_bind_value(pWriter, i+1, pVal);\n    if( p->rc ) return;\n  }\n  if( pIter->zIdx==0 ){\n    if( pIter->eType==RBU_PK_VTAB \n     || pIter->eType==RBU_PK_NONE \n     || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p)) \n    ){\n      /* For a virtual table, or a table with no primary key, the \n      ** SELECT statement is:\n      **\n      **   SELECT <cols>, rbu_control, rbu_rowid FROM ....\n      **\n      ** Hence column_value(pIter->nCol+1).\n      */\n      assertColumnName(pIter->pSelect, pIter->nCol+1, \n          rbuIsVacuum(p) ? \"rowid\" : \"rbu_rowid\"\n      );\n      pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);\n      p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);\n    }\n  }\n  if( p->rc==SQLITE_OK ){\n    sqlite3_step(pWriter);\n    p->rc = resetAndCollectError(pWriter, &p->zErrmsg);\n  }\n}\n\n/*\n** This function does the work for an sqlite3rbu_step() call.\n**\n** The object-iterator (p->objiter) currently points to a valid object,\n** and the input cursor (p->objiter.pSelect) currently points to a valid\n** input row. Perform whatever processing is required and return.\n**\n** If no  error occurs, SQLITE_OK is returned. Otherwise, an error code\n** and message is left in the RBU handle and a copy of the error code\n** returned.\n*/\nstatic int rbuStep(sqlite3rbu *p){\n  RbuObjIter *pIter = &p->objiter;\n  const char *zMask = 0;\n  int eType = rbuStepType(p, &zMask);\n\n  if( eType ){\n    assert( eType==RBU_INSERT     || eType==RBU_DELETE\n         || eType==RBU_REPLACE    || eType==RBU_IDX_DELETE\n         || eType==RBU_IDX_INSERT || eType==RBU_UPDATE\n    );\n    assert( eType!=RBU_UPDATE || pIter->zIdx==0 );\n\n    if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){\n      rbuBadControlError(p);\n    }\n    else if( eType==RBU_REPLACE ){\n      if( pIter->zIdx==0 ){\n        p->nPhaseOneStep += p->objiter.nIndex;\n        rbuStepOneOp(p, RBU_DELETE);\n      }\n      if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);\n    }\n    else if( eType!=RBU_UPDATE ){\n      rbuStepOneOp(p, eType);\n    }\n    else{\n      sqlite3_value *pVal;\n      sqlite3_stmt *pUpdate = 0;\n      assert( eType==RBU_UPDATE );\n      p->nPhaseOneStep -= p->objiter.nIndex;\n      rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);\n      if( pUpdate ){\n        int i;\n        for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){\n          char c = zMask[pIter->aiSrcOrder[i]];\n          pVal = sqlite3_column_value(pIter->pSelect, i);\n          if( pIter->abTblPk[i] || c!='.' ){\n            p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);\n          }\n        }\n        if( p->rc==SQLITE_OK \n         && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE) \n        ){\n          /* Bind the rbu_rowid value to column _rowid_ */\n          assertColumnName(pIter->pSelect, pIter->nCol+1, \"rbu_rowid\");\n          pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);\n          p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);\n        }\n        if( p->rc==SQLITE_OK ){\n          sqlite3_step(pUpdate);\n          p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);\n        }\n      }\n    }\n  }\n  return p->rc;\n}\n\n/*\n** Increment the schema cookie of the main database opened by p->dbMain.\n**\n** Or, if this is an RBU vacuum, set the schema cookie of the main db\n** opened by p->dbMain to one more than the schema cookie of the main\n** db opened by p->dbRbu.\n*/\nstatic void rbuIncrSchemaCookie(sqlite3rbu *p){\n  if( p->rc==SQLITE_OK ){\n    sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);\n    int iCookie = 1000000;\n    sqlite3_stmt *pStmt;\n\n    p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg, \n        \"PRAGMA schema_version\"\n    );\n    if( p->rc==SQLITE_OK ){\n      /* Coverage: it may be that this sqlite3_step() cannot fail. There\n      ** is already a transaction open, so the prepared statement cannot\n      ** throw an SQLITE_SCHEMA exception. The only database page the\n      ** statement reads is page 1, which is guaranteed to be in the cache.\n      ** And no memory allocations are required.  */\n      if( SQLITE_ROW==sqlite3_step(pStmt) ){\n        iCookie = sqlite3_column_int(pStmt, 0);\n      }\n      rbuFinalize(p, pStmt);\n    }\n    if( p->rc==SQLITE_OK ){\n      rbuMPrintfExec(p, p->dbMain, \"PRAGMA schema_version = %d\", iCookie+1);\n    }\n  }\n}\n\n/*\n** Update the contents of the rbu_state table within the rbu database. The\n** value stored in the RBU_STATE_STAGE column is eStage. All other values\n** are determined by inspecting the rbu handle passed as the first argument.\n*/\nstatic void rbuSaveState(sqlite3rbu *p, int eStage){\n  if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){\n    sqlite3_stmt *pInsert = 0;\n    rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);\n    int rc;\n\n    assert( p->zErrmsg==0 );\n    rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg, \n        sqlite3_mprintf(\n          \"INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES \"\n          \"(%d, %d), \"\n          \"(%d, %Q), \"\n          \"(%d, %Q), \"\n          \"(%d, %d), \"\n          \"(%d, %d), \"\n          \"(%d, %lld), \"\n          \"(%d, %lld), \"\n          \"(%d, %lld), \"\n          \"(%d, %lld), \"\n          \"(%d, %Q)  \",\n          p->zStateDb,\n          RBU_STATE_STAGE, eStage,\n          RBU_STATE_TBL, p->objiter.zTbl, \n          RBU_STATE_IDX, p->objiter.zIdx, \n          RBU_STATE_ROW, p->nStep, \n          RBU_STATE_PROGRESS, p->nProgress,\n          RBU_STATE_CKPT, p->iWalCksum,\n          RBU_STATE_COOKIE, (i64)pFd->iCookie,\n          RBU_STATE_OALSZ, p->iOalSz,\n          RBU_STATE_PHASEONESTEP, p->nPhaseOneStep,\n          RBU_STATE_DATATBL, p->objiter.zDataTbl\n      )\n    );\n    assert( pInsert==0 || rc==SQLITE_OK );\n\n    if( rc==SQLITE_OK ){\n      sqlite3_step(pInsert);\n      rc = sqlite3_finalize(pInsert);\n    }\n    if( rc!=SQLITE_OK ) p->rc = rc;\n  }\n}\n\n\n/*\n** The second argument passed to this function is the name of a PRAGMA \n** setting - \"page_size\", \"auto_vacuum\", \"user_version\" or \"application_id\".\n** This function executes the following on sqlite3rbu.dbRbu:\n**\n**   \"PRAGMA main.$zPragma\"\n**\n** where $zPragma is the string passed as the second argument, then\n** on sqlite3rbu.dbMain:\n**\n**   \"PRAGMA main.$zPragma = $val\"\n**\n** where $val is the value returned by the first PRAGMA invocation.\n**\n** In short, it copies the value  of the specified PRAGMA setting from\n** dbRbu to dbMain.\n*/\nstatic void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){\n  if( p->rc==SQLITE_OK ){\n    sqlite3_stmt *pPragma = 0;\n    p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg, \n        sqlite3_mprintf(\"PRAGMA main.%s\", zPragma)\n    );\n    if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){\n      p->rc = rbuMPrintfExec(p, p->dbMain, \"PRAGMA main.%s = %d\",\n          zPragma, sqlite3_column_int(pPragma, 0)\n      );\n    }\n    rbuFinalize(p, pPragma);\n  }\n}\n\n/*\n** The RBU handle passed as the only argument has just been opened and \n** the state database is empty. If this RBU handle was opened for an\n** RBU vacuum operation, create the schema in the target db.\n*/\nstatic void rbuCreateTargetSchema(sqlite3rbu *p){\n  sqlite3_stmt *pSql = 0;\n  sqlite3_stmt *pInsert = 0;\n\n  assert( rbuIsVacuum(p) );\n  p->rc = sqlite3_exec(p->dbMain, \"PRAGMA writable_schema=1\", 0,0, &p->zErrmsg);\n  if( p->rc==SQLITE_OK ){\n    p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg, \n      \"SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0\"\n      \" AND name!='sqlite_sequence' \"\n      \" ORDER BY type DESC\"\n    );\n  }\n\n  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){\n    const char *zSql = (const char*)sqlite3_column_text(pSql, 0);\n    p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);\n  }\n  rbuFinalize(p, pSql);\n  if( p->rc!=SQLITE_OK ) return;\n\n  if( p->rc==SQLITE_OK ){\n    p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg, \n        \"SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL\" \n    );\n  }\n\n  if( p->rc==SQLITE_OK ){\n    p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg, \n        \"INSERT INTO sqlite_master VALUES(?,?,?,?,?)\"\n    );\n  }\n\n  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){\n    int i;\n    for(i=0; i<5; i++){\n      sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));\n    }\n    sqlite3_step(pInsert);\n    p->rc = sqlite3_reset(pInsert);\n  }\n  if( p->rc==SQLITE_OK ){\n    p->rc = sqlite3_exec(p->dbMain, \"PRAGMA writable_schema=0\",0,0,&p->zErrmsg);\n  }\n\n  rbuFinalize(p, pSql);\n  rbuFinalize(p, pInsert);\n}\n\n/*\n** Step the RBU object.\n*/\nSQLITE_API int sqlite3rbu_step(sqlite3rbu *p){\n  if( p ){\n    switch( p->eStage ){\n      case RBU_STAGE_OAL: {\n        RbuObjIter *pIter = &p->objiter;\n\n        /* If this is an RBU vacuum operation and the state table was empty\n        ** when this handle was opened, create the target database schema. */\n        if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){\n          rbuCreateTargetSchema(p);\n          rbuCopyPragma(p, \"user_version\");\n          rbuCopyPragma(p, \"application_id\");\n        }\n\n        while( p->rc==SQLITE_OK && pIter->zTbl ){\n\n          if( pIter->bCleanup ){\n            /* Clean up the rbu_tmp_xxx table for the previous table. It \n            ** cannot be dropped as there are currently active SQL statements.\n            ** But the contents can be deleted.  */\n            if( rbuIsVacuum(p)==0 && pIter->abIndexed ){\n              rbuMPrintfExec(p, p->dbRbu, \n                  \"DELETE FROM %s.'rbu_tmp_%q'\", p->zStateDb, pIter->zDataTbl\n              );\n            }\n          }else{\n            rbuObjIterPrepareAll(p, pIter, 0);\n\n            /* Advance to the next row to process. */\n            if( p->rc==SQLITE_OK ){\n              int rc = sqlite3_step(pIter->pSelect);\n              if( rc==SQLITE_ROW ){\n                p->nProgress++;\n                p->nStep++;\n                return rbuStep(p);\n              }\n              p->rc = sqlite3_reset(pIter->pSelect);\n              p->nStep = 0;\n            }\n          }\n\n          rbuObjIterNext(p, pIter);\n        }\n\n        if( p->rc==SQLITE_OK ){\n          assert( pIter->zTbl==0 );\n          rbuSaveState(p, RBU_STAGE_MOVE);\n          rbuIncrSchemaCookie(p);\n          if( p->rc==SQLITE_OK ){\n            p->rc = sqlite3_exec(p->dbMain, \"COMMIT\", 0, 0, &p->zErrmsg);\n          }\n          if( p->rc==SQLITE_OK ){\n            p->rc = sqlite3_exec(p->dbRbu, \"COMMIT\", 0, 0, &p->zErrmsg);\n          }\n          p->eStage = RBU_STAGE_MOVE;\n        }\n        break;\n      }\n\n      case RBU_STAGE_MOVE: {\n        if( p->rc==SQLITE_OK ){\n          rbuMoveOalFile(p);\n          p->nProgress++;\n        }\n        break;\n      }\n\n      case RBU_STAGE_CKPT: {\n        if( p->rc==SQLITE_OK ){\n          if( p->nStep>=p->nFrame ){\n            sqlite3_file *pDb = p->pTargetFd->pReal;\n  \n            /* Sync the db file */\n            p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);\n  \n            /* Update nBackfill */\n            if( p->rc==SQLITE_OK ){\n              void volatile *ptr;\n              p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);\n              if( p->rc==SQLITE_OK ){\n                ((u32 volatile*)ptr)[24] = p->iMaxFrame;\n              }\n            }\n  \n            if( p->rc==SQLITE_OK ){\n              p->eStage = RBU_STAGE_DONE;\n              p->rc = SQLITE_DONE;\n            }\n          }else{\n            /* At one point the following block copied a single frame from the\n            ** wal file to the database file. So that one call to sqlite3rbu_step()\n            ** checkpointed a single frame. \n            **\n            ** However, if the sector-size is larger than the page-size, and the\n            ** application calls sqlite3rbu_savestate() or close() immediately\n            ** after this step, then rbu_step() again, then a power failure occurs,\n            ** then the database page written here may be damaged. Work around\n            ** this by checkpointing frames until the next page in the aFrame[]\n            ** lies on a different disk sector to the current one. */\n            u32 iSector;\n            do{\n              RbuFrame *pFrame = &p->aFrame[p->nStep];\n              iSector = (pFrame->iDbPage-1) / p->nPagePerSector;\n              rbuCheckpointFrame(p, pFrame);\n              p->nStep++;\n            }while( p->nStep<p->nFrame \n                 && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)\n                 && p->rc==SQLITE_OK\n            );\n          }\n          p->nProgress++;\n        }\n        break;\n      }\n\n      default:\n        break;\n    }\n    return p->rc;\n  }else{\n    return SQLITE_NOMEM;\n  }\n}\n\n/*\n** Compare strings z1 and z2, returning 0 if they are identical, or non-zero\n** otherwise. Either or both argument may be NULL. Two NULL values are\n** considered equal, and NULL is considered distinct from all other values.\n*/\nstatic int rbuStrCompare(const char *z1, const char *z2){\n  if( z1==0 && z2==0 ) return 0;\n  if( z1==0 || z2==0 ) return 1;\n  return (sqlite3_stricmp(z1, z2)!=0);\n}\n\n/*\n** This function is called as part of sqlite3rbu_open() when initializing\n** an rbu handle in OAL stage. If the rbu update has not started (i.e.\n** the rbu_state table was empty) it is a no-op. Otherwise, it arranges\n** things so that the next call to sqlite3rbu_step() continues on from\n** where the previous rbu handle left off.\n**\n** If an error occurs, an error code and error message are left in the\n** rbu handle passed as the first argument.\n*/\nstatic void rbuSetupOal(sqlite3rbu *p, RbuState *pState){\n  assert( p->rc==SQLITE_OK );\n  if( pState->zTbl ){\n    RbuObjIter *pIter = &p->objiter;\n    int rc = SQLITE_OK;\n\n    while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup \n       || rbuStrCompare(pIter->zIdx, pState->zIdx)\n       || (pState->zDataTbl==0 && rbuStrCompare(pIter->zTbl, pState->zTbl))\n       || (pState->zDataTbl && rbuStrCompare(pIter->zDataTbl, pState->zDataTbl))\n    )){\n      rc = rbuObjIterNext(p, pIter);\n    }\n\n    if( rc==SQLITE_OK && !pIter->zTbl ){\n      rc = SQLITE_ERROR;\n      p->zErrmsg = sqlite3_mprintf(\"rbu_state mismatch error\");\n    }\n\n    if( rc==SQLITE_OK ){\n      p->nStep = pState->nRow;\n      rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);\n    }\n\n    p->rc = rc;\n  }\n}\n\n/*\n** If there is a \"*-oal\" file in the file-system corresponding to the\n** target database in the file-system, delete it. If an error occurs,\n** leave an error code and error message in the rbu handle.\n*/\nstatic void rbuDeleteOalFile(sqlite3rbu *p){\n  char *zOal = rbuMPrintf(p, \"%s-oal\", p->zTarget);\n  if( zOal ){\n    sqlite3_vfs *pVfs = sqlite3_vfs_find(0);\n    assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );\n    pVfs->xDelete(pVfs, zOal, 0);\n    sqlite3_free(zOal);\n  }\n}\n\n/*\n** Allocate a private rbu VFS for the rbu handle passed as the only\n** argument. This VFS will be used unless the call to sqlite3rbu_open()\n** specified a URI with a vfs=? option in place of a target database\n** file name.\n*/\nstatic void rbuCreateVfs(sqlite3rbu *p){\n  int rnd;\n  char zRnd[64];\n\n  assert( p->rc==SQLITE_OK );\n  sqlite3_randomness(sizeof(int), (void*)&rnd);\n  sqlite3_snprintf(sizeof(zRnd), zRnd, \"rbu_vfs_%d\", rnd);\n  p->rc = sqlite3rbu_create_vfs(zRnd, 0);\n  if( p->rc==SQLITE_OK ){\n    sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);\n    assert( pVfs );\n    p->zVfsName = pVfs->zName;\n    ((rbu_vfs*)pVfs)->pRbu = p;\n  }\n}\n\n/*\n** Destroy the private VFS created for the rbu handle passed as the only\n** argument by an earlier call to rbuCreateVfs().\n*/\nstatic void rbuDeleteVfs(sqlite3rbu *p){\n  if( p->zVfsName ){\n    sqlite3rbu_destroy_vfs(p->zVfsName);\n    p->zVfsName = 0;\n  }\n}\n\n/*\n** This user-defined SQL function is invoked with a single argument - the\n** name of a table expected to appear in the target database. It returns\n** the number of auxilliary indexes on the table.\n*/\nstatic void rbuIndexCntFunc(\n  sqlite3_context *pCtx, \n  int nVal,\n  sqlite3_value **apVal\n){\n  sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);\n  sqlite3_stmt *pStmt = 0;\n  char *zErrmsg = 0;\n  int rc;\n  sqlite3 *db = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);\n\n  assert( nVal==1 );\n  \n  rc = prepareFreeAndCollectError(db, &pStmt, &zErrmsg, \n      sqlite3_mprintf(\"SELECT count(*) FROM sqlite_master \"\n        \"WHERE type='index' AND tbl_name = %Q\", sqlite3_value_text(apVal[0]))\n  );\n  if( rc!=SQLITE_OK ){\n    sqlite3_result_error(pCtx, zErrmsg, -1);\n  }else{\n    int nIndex = 0;\n    if( SQLITE_ROW==sqlite3_step(pStmt) ){\n      nIndex = sqlite3_column_int(pStmt, 0);\n    }\n    rc = sqlite3_finalize(pStmt);\n    if( rc==SQLITE_OK ){\n      sqlite3_result_int(pCtx, nIndex);\n    }else{\n      sqlite3_result_error(pCtx, sqlite3_errmsg(db), -1);\n    }\n  }\n\n  sqlite3_free(zErrmsg);\n}\n\n/*\n** If the RBU database contains the rbu_count table, use it to initialize\n** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table\n** is assumed to contain the same columns as:\n**\n**   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;\n**\n** There should be one row in the table for each data_xxx table in the\n** database. The 'tbl' column should contain the name of a data_xxx table,\n** and the cnt column the number of rows it contains.\n**\n** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt\n** for all rows in the rbu_count table, where nIndex is the number of \n** indexes on the corresponding target database table.\n*/\nstatic void rbuInitPhaseOneSteps(sqlite3rbu *p){\n  if( p->rc==SQLITE_OK ){\n    sqlite3_stmt *pStmt = 0;\n    int bExists = 0;                /* True if rbu_count exists */\n\n    p->nPhaseOneStep = -1;\n\n    p->rc = sqlite3_create_function(p->dbRbu, \n        \"rbu_index_cnt\", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0\n    );\n  \n    /* Check for the rbu_count table. If it does not exist, or if an error\n    ** occurs, nPhaseOneStep will be left set to -1. */\n    if( p->rc==SQLITE_OK ){\n      p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,\n          \"SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'\"\n      );\n    }\n    if( p->rc==SQLITE_OK ){\n      if( SQLITE_ROW==sqlite3_step(pStmt) ){\n        bExists = 1;\n      }\n      p->rc = sqlite3_finalize(pStmt);\n    }\n  \n    if( p->rc==SQLITE_OK && bExists ){\n      p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,\n          \"SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))\"\n          \"FROM rbu_count\"\n      );\n      if( p->rc==SQLITE_OK ){\n        if( SQLITE_ROW==sqlite3_step(pStmt) ){\n          p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);\n        }\n        p->rc = sqlite3_finalize(pStmt);\n      }\n    }\n  }\n}\n\n\nstatic sqlite3rbu *openRbuHandle(\n  const char *zTarget, \n  const char *zRbu,\n  const char *zState\n){\n  sqlite3rbu *p;\n  size_t nTarget = zTarget ? strlen(zTarget) : 0;\n  size_t nRbu = strlen(zRbu);\n  size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;\n\n  p = (sqlite3rbu*)sqlite3_malloc64(nByte);\n  if( p ){\n    RbuState *pState = 0;\n\n    /* Create the custom VFS. */\n    memset(p, 0, sizeof(sqlite3rbu));\n    rbuCreateVfs(p);\n\n    /* Open the target, RBU and state databases */\n    if( p->rc==SQLITE_OK ){\n      char *pCsr = (char*)&p[1];\n      int bRetry = 0;\n      if( zTarget ){\n        p->zTarget = pCsr;\n        memcpy(p->zTarget, zTarget, nTarget+1);\n        pCsr += nTarget+1;\n      }\n      p->zRbu = pCsr;\n      memcpy(p->zRbu, zRbu, nRbu+1);\n      pCsr += nRbu+1;\n      if( zState ){\n        p->zState = rbuMPrintf(p, \"%s\", zState);\n      }\n\n      /* If the first attempt to open the database file fails and the bRetry\n      ** flag it set, this means that the db was not opened because it seemed\n      ** to be a wal-mode db. But, this may have happened due to an earlier\n      ** RBU vacuum operation leaving an old wal file in the directory.\n      ** If this is the case, it will have been checkpointed and deleted\n      ** when the handle was closed and a second attempt to open the \n      ** database may succeed.  */\n      rbuOpenDatabase(p, &bRetry);\n      if( bRetry ){\n        rbuOpenDatabase(p, 0);\n      }\n    }\n\n    if( p->rc==SQLITE_OK ){\n      pState = rbuLoadState(p);\n      assert( pState || p->rc!=SQLITE_OK );\n      if( p->rc==SQLITE_OK ){\n\n        if( pState->eStage==0 ){ \n          rbuDeleteOalFile(p);\n          rbuInitPhaseOneSteps(p);\n          p->eStage = RBU_STAGE_OAL;\n        }else{\n          p->eStage = pState->eStage;\n          p->nPhaseOneStep = pState->nPhaseOneStep;\n        }\n        p->nProgress = pState->nProgress;\n        p->iOalSz = pState->iOalSz;\n      }\n    }\n    assert( p->rc!=SQLITE_OK || p->eStage!=0 );\n\n    if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){\n      if( p->eStage==RBU_STAGE_OAL ){\n        p->rc = SQLITE_ERROR;\n        p->zErrmsg = sqlite3_mprintf(\"cannot update wal mode database\");\n      }else if( p->eStage==RBU_STAGE_MOVE ){\n        p->eStage = RBU_STAGE_CKPT;\n        p->nStep = 0;\n      }\n    }\n\n    if( p->rc==SQLITE_OK \n     && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)\n     && pState->eStage!=0\n    ){\n      rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);\n      if( pFd->iCookie!=pState->iCookie ){   \n        /* At this point (pTargetFd->iCookie) contains the value of the\n        ** change-counter cookie (the thing that gets incremented when a \n        ** transaction is committed in rollback mode) currently stored on \n        ** page 1 of the database file. */\n        p->rc = SQLITE_BUSY;\n        p->zErrmsg = sqlite3_mprintf(\"database modified during rbu %s\",\n            (rbuIsVacuum(p) ? \"vacuum\" : \"update\")\n        );\n      }\n    }\n\n    if( p->rc==SQLITE_OK ){\n      if( p->eStage==RBU_STAGE_OAL ){\n        sqlite3 *db = p->dbMain;\n        p->rc = sqlite3_exec(p->dbRbu, \"BEGIN\", 0, 0, &p->zErrmsg);\n\n        /* Point the object iterator at the first object */\n        if( p->rc==SQLITE_OK ){\n          p->rc = rbuObjIterFirst(p, &p->objiter);\n        }\n\n        /* If the RBU database contains no data_xxx tables, declare the RBU\n        ** update finished.  */\n        if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){\n          p->rc = SQLITE_DONE;\n          p->eStage = RBU_STAGE_DONE;\n        }else{\n          if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){\n            rbuCopyPragma(p, \"page_size\");\n            rbuCopyPragma(p, \"auto_vacuum\");\n          }\n\n          /* Open transactions both databases. The *-oal file is opened or\n          ** created at this point. */\n          if( p->rc==SQLITE_OK ){\n            p->rc = sqlite3_exec(db, \"BEGIN IMMEDIATE\", 0, 0, &p->zErrmsg);\n          }\n\n          /* Check if the main database is a zipvfs db. If it is, set the upper\n          ** level pager to use \"journal_mode=off\". This prevents it from \n          ** generating a large journal using a temp file.  */\n          if( p->rc==SQLITE_OK ){\n            int frc = sqlite3_file_control(db, \"main\", SQLITE_FCNTL_ZIPVFS, 0);\n            if( frc==SQLITE_OK ){\n              p->rc = sqlite3_exec(\n                db, \"PRAGMA journal_mode=off\",0,0,&p->zErrmsg);\n            }\n          }\n\n          if( p->rc==SQLITE_OK ){\n            rbuSetupOal(p, pState);\n          }\n        }\n      }else if( p->eStage==RBU_STAGE_MOVE ){\n        /* no-op */\n      }else if( p->eStage==RBU_STAGE_CKPT ){\n        rbuSetupCheckpoint(p, pState);\n      }else if( p->eStage==RBU_STAGE_DONE ){\n        p->rc = SQLITE_DONE;\n      }else{\n        p->rc = SQLITE_CORRUPT;\n      }\n    }\n\n    rbuFreeState(pState);\n  }\n\n  return p;\n}\n\n/*\n** Allocate and return an RBU handle with all fields zeroed except for the\n** error code, which is set to SQLITE_MISUSE.\n*/\nstatic sqlite3rbu *rbuMisuseError(void){\n  sqlite3rbu *pRet;\n  pRet = sqlite3_malloc64(sizeof(sqlite3rbu));\n  if( pRet ){\n    memset(pRet, 0, sizeof(sqlite3rbu));\n    pRet->rc = SQLITE_MISUSE;\n  }\n  return pRet;\n}\n\n/*\n** Open and return a new RBU handle. \n*/\nSQLITE_API sqlite3rbu *sqlite3rbu_open(\n  const char *zTarget, \n  const char *zRbu,\n  const char *zState\n){\n  if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }\n  /* TODO: Check that zTarget and zRbu are non-NULL */\n  return openRbuHandle(zTarget, zRbu, zState);\n}\n\n/*\n** Open a handle to begin or resume an RBU VACUUM operation.\n*/\nSQLITE_API sqlite3rbu *sqlite3rbu_vacuum(\n  const char *zTarget, \n  const char *zState\n){\n  if( zTarget==0 ){ return rbuMisuseError(); }\n  if( zState ){\n    int n = strlen(zState);\n    if( n>=7 && 0==memcmp(\"-vactmp\", &zState[n-7], 7) ){\n      return rbuMisuseError();\n    }\n  }\n  /* TODO: Check that both arguments are non-NULL */\n  return openRbuHandle(0, zTarget, zState);\n}\n\n/*\n** Return the database handle used by pRbu.\n*/\nSQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){\n  sqlite3 *db = 0;\n  if( pRbu ){\n    db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);\n  }\n  return db;\n}\n\n\n/*\n** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,\n** then edit any error message string so as to remove all occurrences of\n** the pattern \"rbu_imp_[0-9]*\".\n*/\nstatic void rbuEditErrmsg(sqlite3rbu *p){\n  if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){\n    unsigned int i;\n    size_t nErrmsg = strlen(p->zErrmsg);\n    for(i=0; i<(nErrmsg-8); i++){\n      if( memcmp(&p->zErrmsg[i], \"rbu_imp_\", 8)==0 ){\n        int nDel = 8;\n        while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;\n        memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);\n        nErrmsg -= nDel;\n      }\n    }\n  }\n}\n\n/*\n** Close the RBU handle.\n*/\nSQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){\n  int rc;\n  if( p ){\n\n    /* Commit the transaction to the *-oal file. */\n    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){\n      p->rc = sqlite3_exec(p->dbMain, \"COMMIT\", 0, 0, &p->zErrmsg);\n    }\n\n    /* Sync the db file if currently doing an incremental checkpoint */\n    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){\n      sqlite3_file *pDb = p->pTargetFd->pReal;\n      p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);\n    }\n\n    rbuSaveState(p, p->eStage);\n\n    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){\n      p->rc = sqlite3_exec(p->dbRbu, \"COMMIT\", 0, 0, &p->zErrmsg);\n    }\n\n    /* Close any open statement handles. */\n    rbuObjIterFinalize(&p->objiter);\n\n    /* If this is an RBU vacuum handle and the vacuum has either finished\n    ** successfully or encountered an error, delete the contents of the \n    ** state table. This causes the next call to sqlite3rbu_vacuum() \n    ** specifying the current target and state databases to start a new\n    ** vacuum from scratch.  */\n    if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){\n      int rc2 = sqlite3_exec(p->dbRbu, \"DELETE FROM stat.rbu_state\", 0, 0, 0);\n      if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;\n    }\n\n    /* Close the open database handle and VFS object. */\n    sqlite3_close(p->dbRbu);\n    sqlite3_close(p->dbMain);\n    assert( p->szTemp==0 );\n    rbuDeleteVfs(p);\n    sqlite3_free(p->aBuf);\n    sqlite3_free(p->aFrame);\n\n    rbuEditErrmsg(p);\n    rc = p->rc;\n    if( pzErrmsg ){\n      *pzErrmsg = p->zErrmsg;\n    }else{\n      sqlite3_free(p->zErrmsg);\n    }\n    sqlite3_free(p->zState);\n    sqlite3_free(p);\n  }else{\n    rc = SQLITE_NOMEM;\n    *pzErrmsg = 0;\n  }\n  return rc;\n}\n\n/*\n** Return the total number of key-value operations (inserts, deletes or \n** updates) that have been performed on the target database since the\n** current RBU update was started.\n*/\nSQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){\n  return pRbu->nProgress;\n}\n\n/*\n** Return permyriadage progress indications for the two main stages of\n** an RBU update.\n*/\nSQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){\n  const int MAX_PROGRESS = 10000;\n  switch( p->eStage ){\n    case RBU_STAGE_OAL:\n      if( p->nPhaseOneStep>0 ){\n        *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);\n      }else{\n        *pnOne = -1;\n      }\n      *pnTwo = 0;\n      break;\n\n    case RBU_STAGE_MOVE:\n      *pnOne = MAX_PROGRESS;\n      *pnTwo = 0;\n      break;\n\n    case RBU_STAGE_CKPT:\n      *pnOne = MAX_PROGRESS;\n      *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);\n      break;\n\n    case RBU_STAGE_DONE:\n      *pnOne = MAX_PROGRESS;\n      *pnTwo = MAX_PROGRESS;\n      break;\n\n    default:\n      assert( 0 );\n  }\n}\n\n/*\n** Return the current state of the RBU vacuum or update operation.\n*/\nSQLITE_API int sqlite3rbu_state(sqlite3rbu *p){\n  int aRes[] = {\n    0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,\n    0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE\n  };\n\n  assert( RBU_STAGE_OAL==1 );\n  assert( RBU_STAGE_MOVE==2 );\n  assert( RBU_STAGE_CKPT==4 );\n  assert( RBU_STAGE_DONE==5 );\n  assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );\n  assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );\n  assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );\n  assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );\n\n  if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){\n    return SQLITE_RBU_STATE_ERROR;\n  }else{\n    assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );\n    assert( p->eStage==RBU_STAGE_OAL\n         || p->eStage==RBU_STAGE_MOVE\n         || p->eStage==RBU_STAGE_CKPT\n         || p->eStage==RBU_STAGE_DONE\n    );\n    return aRes[p->eStage];\n  }\n}\n\nSQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){\n  int rc = p->rc;\n  if( rc==SQLITE_DONE ) return SQLITE_OK;\n\n  assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );\n  if( p->eStage==RBU_STAGE_OAL ){\n    assert( rc!=SQLITE_DONE );\n    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, \"COMMIT\", 0, 0, 0);\n  }\n\n  /* Sync the db file */\n  if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){\n    sqlite3_file *pDb = p->pTargetFd->pReal;\n    rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);\n  }\n\n  p->rc = rc;\n  rbuSaveState(p, p->eStage);\n  rc = p->rc;\n\n  if( p->eStage==RBU_STAGE_OAL ){\n    assert( rc!=SQLITE_DONE );\n    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, \"COMMIT\", 0, 0, 0);\n    if( rc==SQLITE_OK ){ \n      const char *zBegin = rbuIsVacuum(p) ? \"BEGIN\" : \"BEGIN IMMEDIATE\";\n      rc = sqlite3_exec(p->dbRbu, zBegin, 0, 0, 0);\n    }\n    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, \"BEGIN IMMEDIATE\", 0, 0,0);\n  }\n\n  p->rc = rc;\n  return rc;\n}\n\n/**************************************************************************\n** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour\n** of a standard VFS in the following ways:\n**\n** 1. Whenever the first page of a main database file is read or \n**    written, the value of the change-counter cookie is stored in\n**    rbu_file.iCookie. Similarly, the value of the \"write-version\"\n**    database header field is stored in rbu_file.iWriteVer. This ensures\n**    that the values are always trustworthy within an open transaction.\n**\n** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)\n**    member variable of the associated database file descriptor is set\n**    to point to the new file. A mutex protected linked list of all main \n**    db fds opened using a particular RBU VFS is maintained at \n**    rbu_vfs.pMain to facilitate this.\n**\n** 3. Using a new file-control \"SQLITE_FCNTL_RBU\", a main db rbu_file \n**    object can be marked as the target database of an RBU update. This\n**    turns on the following extra special behaviour:\n**\n** 3a. If xAccess() is called to check if there exists a *-wal file \n**     associated with an RBU target database currently in RBU_STAGE_OAL\n**     stage (preparing the *-oal file), the following special handling\n**     applies:\n**\n**      * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU\n**        target database may not be in wal mode already.\n**\n**      * if the *-wal file does not exist, set the output parameter to\n**        non-zero (to tell SQLite that it does exist) anyway.\n**\n**     Then, when xOpen() is called to open the *-wal file associated with\n**     the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal\n**     file, the rbu vfs opens the corresponding *-oal file instead. \n**\n** 3b. The *-shm pages returned by xShmMap() for a target db file in\n**     RBU_STAGE_OAL mode are actually stored in heap memory. This is to\n**     avoid creating a *-shm file on disk. Additionally, xShmLock() calls\n**     are no-ops on target database files in RBU_STAGE_OAL mode. This is\n**     because assert() statements in some VFS implementations fail if \n**     xShmLock() is called before xShmMap().\n**\n** 3c. If an EXCLUSIVE lock is attempted on a target database file in any\n**     mode except RBU_STAGE_DONE (all work completed and checkpointed), it \n**     fails with an SQLITE_BUSY error. This is to stop RBU connections\n**     from automatically checkpointing a *-wal (or *-oal) file from within\n**     sqlite3_close().\n**\n** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and\n**     all xWrite() calls on the target database file perform no IO. \n**     Instead the frame and page numbers that would be read and written\n**     are recorded. Additionally, successful attempts to obtain exclusive\n**     xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target \n**     database file are recorded. xShmLock() calls to unlock the same\n**     locks are no-ops (so that once obtained, these locks are never\n**     relinquished). Finally, calls to xSync() on the target database\n**     file fail with SQLITE_INTERNAL errors.\n*/\n\nstatic void rbuUnlockShm(rbu_file *p){\n  assert( p->openFlags & SQLITE_OPEN_MAIN_DB );\n  if( p->pRbu ){\n    int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;\n    int i;\n    for(i=0; i<SQLITE_SHM_NLOCK;i++){\n      if( (1<<i) & p->pRbu->mLock ){\n        xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);\n      }\n    }\n    p->pRbu->mLock = 0;\n  }\n}\n\n/*\n*/\nstatic int rbuUpdateTempSize(rbu_file *pFd, sqlite3_int64 nNew){\n  sqlite3rbu *pRbu = pFd->pRbu;\n  i64 nDiff = nNew - pFd->sz;\n  pRbu->szTemp += nDiff;\n  pFd->sz = nNew;\n  assert( pRbu->szTemp>=0 );\n  if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL;\n  return SQLITE_OK;\n}\n\n/*\n** Add an item to the main-db lists, if it is not already present.\n**\n** There are two main-db lists. One for all file descriptors, and one\n** for all file descriptors with rbu_file.pDb!=0. If the argument has\n** rbu_file.pDb!=0, then it is assumed to already be present on the\n** main list and is only added to the pDb!=0 list.\n*/\nstatic void rbuMainlistAdd(rbu_file *p){\n  rbu_vfs *pRbuVfs = p->pRbuVfs;\n  rbu_file *pIter;\n  assert( (p->openFlags & SQLITE_OPEN_MAIN_DB) );\n  sqlite3_mutex_enter(pRbuVfs->mutex);\n  if( p->pRbu==0 ){\n    for(pIter=pRbuVfs->pMain; pIter; pIter=pIter->pMainNext);\n    p->pMainNext = pRbuVfs->pMain;\n    pRbuVfs->pMain = p;\n  }else{\n    for(pIter=pRbuVfs->pMainRbu; pIter && pIter!=p; pIter=pIter->pMainRbuNext){}\n    if( pIter==0 ){\n      p->pMainRbuNext = pRbuVfs->pMainRbu;\n      pRbuVfs->pMainRbu = p;\n    }\n  }\n  sqlite3_mutex_leave(pRbuVfs->mutex);\n}\n\n/*\n** Remove an item from the main-db lists.\n*/\nstatic void rbuMainlistRemove(rbu_file *p){\n  rbu_file **pp;\n  sqlite3_mutex_enter(p->pRbuVfs->mutex);\n  for(pp=&p->pRbuVfs->pMain; *pp && *pp!=p; pp=&((*pp)->pMainNext)){}\n  if( *pp ) *pp = p->pMainNext;\n  p->pMainNext = 0;\n  for(pp=&p->pRbuVfs->pMainRbu; *pp && *pp!=p; pp=&((*pp)->pMainRbuNext)){}\n  if( *pp ) *pp = p->pMainRbuNext;\n  p->pMainRbuNext = 0;\n  sqlite3_mutex_leave(p->pRbuVfs->mutex);\n}\n\n/*\n** Given that zWal points to a buffer containing a wal file name passed to \n** either the xOpen() or xAccess() VFS method, search the main-db list for\n** a file-handle opened by the same database connection on the corresponding\n** database file.\n**\n** If parameter bRbu is true, only search for file-descriptors with\n** rbu_file.pDb!=0.\n*/\nstatic rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal, int bRbu){\n  rbu_file *pDb;\n  sqlite3_mutex_enter(pRbuVfs->mutex);\n  if( bRbu ){\n    for(pDb=pRbuVfs->pMainRbu; pDb && pDb->zWal!=zWal; pDb=pDb->pMainRbuNext){}\n  }else{\n    for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}\n  }\n  sqlite3_mutex_leave(pRbuVfs->mutex);\n  return pDb;\n}\n\n/*\n** Close an rbu file.\n*/\nstatic int rbuVfsClose(sqlite3_file *pFile){\n  rbu_file *p = (rbu_file*)pFile;\n  int rc;\n  int i;\n\n  /* Free the contents of the apShm[] array. And the array itself. */\n  for(i=0; i<p->nShm; i++){\n    sqlite3_free(p->apShm[i]);\n  }\n  sqlite3_free(p->apShm);\n  p->apShm = 0;\n  sqlite3_free(p->zDel);\n\n  if( p->openFlags & SQLITE_OPEN_MAIN_DB ){\n    rbuMainlistRemove(p);\n    rbuUnlockShm(p);\n    p->pReal->pMethods->xShmUnmap(p->pReal, 0);\n  }\n  else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){\n    rbuUpdateTempSize(p, 0);\n  }\n  assert( p->pMainNext==0 && p->pRbuVfs->pMain!=p );\n\n  /* Close the underlying file handle */\n  rc = p->pReal->pMethods->xClose(p->pReal);\n  return rc;\n}\n\n\n/*\n** Read and return an unsigned 32-bit big-endian integer from the buffer \n** passed as the only argument.\n*/\nstatic u32 rbuGetU32(u8 *aBuf){\n  return ((u32)aBuf[0] << 24)\n       + ((u32)aBuf[1] << 16)\n       + ((u32)aBuf[2] <<  8)\n       + ((u32)aBuf[3]);\n}\n\n/*\n** Write an unsigned 32-bit value in big-endian format to the supplied\n** buffer.\n*/\nstatic void rbuPutU32(u8 *aBuf, u32 iVal){\n  aBuf[0] = (iVal >> 24) & 0xFF;\n  aBuf[1] = (iVal >> 16) & 0xFF;\n  aBuf[2] = (iVal >>  8) & 0xFF;\n  aBuf[3] = (iVal >>  0) & 0xFF;\n}\n\nstatic void rbuPutU16(u8 *aBuf, u16 iVal){\n  aBuf[0] = (iVal >>  8) & 0xFF;\n  aBuf[1] = (iVal >>  0) & 0xFF;\n}\n\n/*\n** Read data from an rbuVfs-file.\n*/\nstatic int rbuVfsRead(\n  sqlite3_file *pFile, \n  void *zBuf, \n  int iAmt, \n  sqlite_int64 iOfst\n){\n  rbu_file *p = (rbu_file*)pFile;\n  sqlite3rbu *pRbu = p->pRbu;\n  int rc;\n\n  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){\n    assert( p->openFlags & SQLITE_OPEN_WAL );\n    rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);\n  }else{\n    if( pRbu && pRbu->eStage==RBU_STAGE_OAL \n     && (p->openFlags & SQLITE_OPEN_WAL) \n     && iOfst>=pRbu->iOalSz \n    ){\n      rc = SQLITE_OK;\n      memset(zBuf, 0, iAmt);\n    }else{\n      rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);\n#if 1\n      /* If this is being called to read the first page of the target \n      ** database as part of an rbu vacuum operation, synthesize the \n      ** contents of the first page if it does not yet exist. Otherwise,\n      ** SQLite will not check for a *-wal file.  */\n      if( pRbu && rbuIsVacuum(pRbu) \n          && rc==SQLITE_IOERR_SHORT_READ && iOfst==0\n          && (p->openFlags & SQLITE_OPEN_MAIN_DB)\n          && pRbu->rc==SQLITE_OK\n      ){\n        sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;\n        rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);\n        if( rc==SQLITE_OK ){\n          u8 *aBuf = (u8*)zBuf;\n          u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;\n          rbuPutU32(&aBuf[52], iRoot);      /* largest root page number */\n          rbuPutU32(&aBuf[36], 0);          /* number of free pages */\n          rbuPutU32(&aBuf[32], 0);          /* first page on free list trunk */\n          rbuPutU32(&aBuf[28], 1);          /* size of db file in pages */\n          rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1);  /* Change counter */\n\n          if( iAmt>100 ){\n            memset(&aBuf[100], 0, iAmt-100);\n            rbuPutU16(&aBuf[105], iAmt & 0xFFFF);\n            aBuf[100] = 0x0D;\n          }\n        }\n      }\n#endif\n    }\n    if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){\n      /* These look like magic numbers. But they are stable, as they are part\n       ** of the definition of the SQLite file format, which may not change. */\n      u8 *pBuf = (u8*)zBuf;\n      p->iCookie = rbuGetU32(&pBuf[24]);\n      p->iWriteVer = pBuf[19];\n    }\n  }\n  return rc;\n}\n\n/*\n** Write data to an rbuVfs-file.\n*/\nstatic int rbuVfsWrite(\n  sqlite3_file *pFile, \n  const void *zBuf, \n  int iAmt, \n  sqlite_int64 iOfst\n){\n  rbu_file *p = (rbu_file*)pFile;\n  sqlite3rbu *pRbu = p->pRbu;\n  int rc;\n\n  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){\n    assert( p->openFlags & SQLITE_OPEN_MAIN_DB );\n    rc = rbuCaptureDbWrite(p->pRbu, iOfst);\n  }else{\n    if( pRbu ){\n      if( pRbu->eStage==RBU_STAGE_OAL \n       && (p->openFlags & SQLITE_OPEN_WAL) \n       && iOfst>=pRbu->iOalSz\n      ){\n        pRbu->iOalSz = iAmt + iOfst;\n      }else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){\n        i64 szNew = iAmt+iOfst;\n        if( szNew>p->sz ){\n          rc = rbuUpdateTempSize(p, szNew);\n          if( rc!=SQLITE_OK ) return rc;\n        }\n      }\n    }\n    rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);\n    if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){\n      /* These look like magic numbers. But they are stable, as they are part\n      ** of the definition of the SQLite file format, which may not change. */\n      u8 *pBuf = (u8*)zBuf;\n      p->iCookie = rbuGetU32(&pBuf[24]);\n      p->iWriteVer = pBuf[19];\n    }\n  }\n  return rc;\n}\n\n/*\n** Truncate an rbuVfs-file.\n*/\nstatic int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){\n  rbu_file *p = (rbu_file*)pFile;\n  if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){\n    int rc = rbuUpdateTempSize(p, size);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n  return p->pReal->pMethods->xTruncate(p->pReal, size);\n}\n\n/*\n** Sync an rbuVfs-file.\n*/\nstatic int rbuVfsSync(sqlite3_file *pFile, int flags){\n  rbu_file *p = (rbu_file *)pFile;\n  if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){\n    if( p->openFlags & SQLITE_OPEN_MAIN_DB ){\n      return SQLITE_INTERNAL;\n    }\n    return SQLITE_OK;\n  }\n  return p->pReal->pMethods->xSync(p->pReal, flags);\n}\n\n/*\n** Return the current file-size of an rbuVfs-file.\n*/\nstatic int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){\n  rbu_file *p = (rbu_file *)pFile;\n  int rc;\n  rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);\n\n  /* If this is an RBU vacuum operation and this is the target database,\n  ** pretend that it has at least one page. Otherwise, SQLite will not\n  ** check for the existance of a *-wal file. rbuVfsRead() contains \n  ** similar logic.  */\n  if( rc==SQLITE_OK && *pSize==0 \n   && p->pRbu && rbuIsVacuum(p->pRbu) \n   && (p->openFlags & SQLITE_OPEN_MAIN_DB)\n  ){\n    *pSize = 1024;\n  }\n  return rc;\n}\n\n/*\n** Lock an rbuVfs-file.\n*/\nstatic int rbuVfsLock(sqlite3_file *pFile, int eLock){\n  rbu_file *p = (rbu_file*)pFile;\n  sqlite3rbu *pRbu = p->pRbu;\n  int rc = SQLITE_OK;\n\n  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );\n  if( eLock==SQLITE_LOCK_EXCLUSIVE \n   && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))\n  ){\n    /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this \n    ** prevents it from checkpointing the database from sqlite3_close(). */\n    rc = SQLITE_BUSY;\n  }else{\n    rc = p->pReal->pMethods->xLock(p->pReal, eLock);\n  }\n\n  return rc;\n}\n\n/*\n** Unlock an rbuVfs-file.\n*/\nstatic int rbuVfsUnlock(sqlite3_file *pFile, int eLock){\n  rbu_file *p = (rbu_file *)pFile;\n  return p->pReal->pMethods->xUnlock(p->pReal, eLock);\n}\n\n/*\n** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.\n*/\nstatic int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){\n  rbu_file *p = (rbu_file *)pFile;\n  return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);\n}\n\n/*\n** File control method. For custom operations on an rbuVfs-file.\n*/\nstatic int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){\n  rbu_file *p = (rbu_file *)pFile;\n  int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;\n  int rc;\n\n  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)\n       || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)\n  );\n  if( op==SQLITE_FCNTL_RBU ){\n    sqlite3rbu *pRbu = (sqlite3rbu*)pArg;\n\n    /* First try to find another RBU vfs lower down in the vfs stack. If\n    ** one is found, this vfs will operate in pass-through mode. The lower\n    ** level vfs will do the special RBU handling.  */\n    rc = xControl(p->pReal, op, pArg);\n\n    if( rc==SQLITE_NOTFOUND ){\n      /* Now search for a zipvfs instance lower down in the VFS stack. If\n      ** one is found, this is an error.  */\n      void *dummy = 0;\n      rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);\n      if( rc==SQLITE_OK ){\n        rc = SQLITE_ERROR;\n        pRbu->zErrmsg = sqlite3_mprintf(\"rbu/zipvfs setup error\");\n      }else if( rc==SQLITE_NOTFOUND ){\n        pRbu->pTargetFd = p;\n        p->pRbu = pRbu;\n        rbuMainlistAdd(p);\n        if( p->pWalFd ) p->pWalFd->pRbu = pRbu;\n        rc = SQLITE_OK;\n      }\n    }\n    return rc;\n  }\n  else if( op==SQLITE_FCNTL_RBUCNT ){\n    sqlite3rbu *pRbu = (sqlite3rbu*)pArg;\n    pRbu->nRbu++;\n    pRbu->pRbuFd = p;\n    p->bNolock = 1;\n  }\n\n  rc = xControl(p->pReal, op, pArg);\n  if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){\n    rbu_vfs *pRbuVfs = p->pRbuVfs;\n    char *zIn = *(char**)pArg;\n    char *zOut = sqlite3_mprintf(\"rbu(%s)/%z\", pRbuVfs->base.zName, zIn);\n    *(char**)pArg = zOut;\n    if( zOut==0 ) rc = SQLITE_NOMEM;\n  }\n\n  return rc;\n}\n\n/*\n** Return the sector-size in bytes for an rbuVfs-file.\n*/\nstatic int rbuVfsSectorSize(sqlite3_file *pFile){\n  rbu_file *p = (rbu_file *)pFile;\n  return p->pReal->pMethods->xSectorSize(p->pReal);\n}\n\n/*\n** Return the device characteristic flags supported by an rbuVfs-file.\n*/\nstatic int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){\n  rbu_file *p = (rbu_file *)pFile;\n  return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);\n}\n\n/*\n** Take or release a shared-memory lock.\n*/\nstatic int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){\n  rbu_file *p = (rbu_file*)pFile;\n  sqlite3rbu *pRbu = p->pRbu;\n  int rc = SQLITE_OK;\n\n#ifdef SQLITE_AMALGAMATION\n    assert( WAL_CKPT_LOCK==1 );\n#endif\n\n  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );\n  if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){\n    /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from\n    ** taking this lock also prevents any checkpoints from occurring. \n    ** todo: really, it's not clear why this might occur, as \n    ** wal_autocheckpoint ought to be turned off.  */\n    if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;\n  }else{\n    int bCapture = 0;\n    if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){\n      bCapture = 1;\n    }\n\n    if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){\n      rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);\n      if( bCapture && rc==SQLITE_OK ){\n        pRbu->mLock |= (1 << ofst);\n      }\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.\n*/\nstatic int rbuVfsShmMap(\n  sqlite3_file *pFile, \n  int iRegion, \n  int szRegion, \n  int isWrite, \n  void volatile **pp\n){\n  rbu_file *p = (rbu_file*)pFile;\n  int rc = SQLITE_OK;\n  int eStage = (p->pRbu ? p->pRbu->eStage : 0);\n\n  /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this\n  ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space \n  ** instead of a file on disk.  */\n  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );\n  if( eStage==RBU_STAGE_OAL ){\n    sqlite3_int64 nByte = (iRegion+1) * sizeof(char*);\n    char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);\n\n    /* This is an RBU connection that uses its own heap memory for the\n    ** pages of the *-shm file. Since no other process can have run\n    ** recovery, the connection must request *-shm pages in order\n    ** from start to finish.  */\n    assert( iRegion==p->nShm );\n    if( apNew==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));\n      p->apShm = apNew;\n      p->nShm = iRegion+1;\n    }\n\n    if( rc==SQLITE_OK ){\n      char *pNew = (char*)sqlite3_malloc64(szRegion);\n      if( pNew==0 ){\n        rc = SQLITE_NOMEM;\n      }else{\n        memset(pNew, 0, szRegion);\n        p->apShm[iRegion] = pNew;\n      }\n    }\n\n    if( rc==SQLITE_OK ){\n      *pp = p->apShm[iRegion];\n    }else{\n      *pp = 0;\n    }\n  }else{\n    assert( p->apShm==0 );\n    rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);\n  }\n\n  return rc;\n}\n\n/*\n** Memory barrier.\n*/\nstatic void rbuVfsShmBarrier(sqlite3_file *pFile){\n  rbu_file *p = (rbu_file *)pFile;\n  p->pReal->pMethods->xShmBarrier(p->pReal);\n}\n\n/*\n** The xShmUnmap method.\n*/\nstatic int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){\n  rbu_file *p = (rbu_file*)pFile;\n  int rc = SQLITE_OK;\n  int eStage = (p->pRbu ? p->pRbu->eStage : 0);\n\n  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );\n  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){\n    /* no-op */\n  }else{\n    /* Release the checkpointer and writer locks */\n    rbuUnlockShm(p);\n    rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);\n  }\n  return rc;\n}\n\n/*\n** Open an rbu file handle.\n*/\nstatic int rbuVfsOpen(\n  sqlite3_vfs *pVfs,\n  const char *zName,\n  sqlite3_file *pFile,\n  int flags,\n  int *pOutFlags\n){\n  static sqlite3_io_methods rbuvfs_io_methods = {\n    2,                            /* iVersion */\n    rbuVfsClose,                  /* xClose */\n    rbuVfsRead,                   /* xRead */\n    rbuVfsWrite,                  /* xWrite */\n    rbuVfsTruncate,               /* xTruncate */\n    rbuVfsSync,                   /* xSync */\n    rbuVfsFileSize,               /* xFileSize */\n    rbuVfsLock,                   /* xLock */\n    rbuVfsUnlock,                 /* xUnlock */\n    rbuVfsCheckReservedLock,      /* xCheckReservedLock */\n    rbuVfsFileControl,            /* xFileControl */\n    rbuVfsSectorSize,             /* xSectorSize */\n    rbuVfsDeviceCharacteristics,  /* xDeviceCharacteristics */\n    rbuVfsShmMap,                 /* xShmMap */\n    rbuVfsShmLock,                /* xShmLock */\n    rbuVfsShmBarrier,             /* xShmBarrier */\n    rbuVfsShmUnmap,               /* xShmUnmap */\n    0, 0                          /* xFetch, xUnfetch */\n  };\n  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;\n  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;\n  rbu_file *pFd = (rbu_file *)pFile;\n  int rc = SQLITE_OK;\n  const char *zOpen = zName;\n  int oflags = flags;\n\n  memset(pFd, 0, sizeof(rbu_file));\n  pFd->pReal = (sqlite3_file*)&pFd[1];\n  pFd->pRbuVfs = pRbuVfs;\n  pFd->openFlags = flags;\n  if( zName ){\n    if( flags & SQLITE_OPEN_MAIN_DB ){\n      /* A main database has just been opened. The following block sets\n      ** (pFd->zWal) to point to a buffer owned by SQLite that contains\n      ** the name of the *-wal file this db connection will use. SQLite\n      ** happens to pass a pointer to this buffer when using xAccess()\n      ** or xOpen() to operate on the *-wal file.  */\n      pFd->zWal = sqlite3_filename_wal(zName);\n    }\n    else if( flags & SQLITE_OPEN_WAL ){\n      rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName, 0);\n      if( pDb ){\n        if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){\n          /* This call is to open a *-wal file. Intead, open the *-oal. This\n          ** code ensures that the string passed to xOpen() is terminated by a\n          ** pair of '\\0' bytes in case the VFS attempts to extract a URI \n          ** parameter from it.  */\n          const char *zBase = zName;\n          size_t nCopy;\n          char *zCopy;\n          if( rbuIsVacuum(pDb->pRbu) ){\n            zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, \"main\");\n            zBase = sqlite3_filename_wal(zBase);\n          }\n          nCopy = strlen(zBase);\n          zCopy = sqlite3_malloc64(nCopy+2);\n          if( zCopy ){\n            memcpy(zCopy, zBase, nCopy);\n            zCopy[nCopy-3] = 'o';\n            zCopy[nCopy] = '\\0';\n            zCopy[nCopy+1] = '\\0';\n            zOpen = (const char*)(pFd->zDel = zCopy);\n          }else{\n            rc = SQLITE_NOMEM;\n          }\n          pFd->pRbu = pDb->pRbu;\n        }\n        pDb->pWalFd = pFd;\n      }\n    }\n  }else{\n    pFd->pRbu = pRbuVfs->pRbu;\n  }\n\n  if( oflags & SQLITE_OPEN_MAIN_DB \n   && sqlite3_uri_boolean(zName, \"rbu_memory\", 0) \n  ){\n    assert( oflags & SQLITE_OPEN_MAIN_DB );\n    oflags =  SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |\n              SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;\n    zOpen = 0;\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);\n  }\n  if( pFd->pReal->pMethods ){\n    /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods\n    ** pointer and, if the file is a main database file, link it into the\n    ** mutex protected linked list of all such files.  */\n    pFile->pMethods = &rbuvfs_io_methods;\n    if( flags & SQLITE_OPEN_MAIN_DB ){\n      rbuMainlistAdd(pFd);\n    }\n  }else{\n    sqlite3_free(pFd->zDel);\n  }\n\n  return rc;\n}\n\n/*\n** Delete the file located at zPath.\n*/\nstatic int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){\n  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;\n  return pRealVfs->xDelete(pRealVfs, zPath, dirSync);\n}\n\n/*\n** Test for access permissions. Return true if the requested permission\n** is available, or false otherwise.\n*/\nstatic int rbuVfsAccess(\n  sqlite3_vfs *pVfs, \n  const char *zPath, \n  int flags, \n  int *pResOut\n){\n  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;\n  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;\n  int rc;\n\n  rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);\n\n  /* If this call is to check if a *-wal file associated with an RBU target\n  ** database connection exists, and the RBU update is in RBU_STAGE_OAL,\n  ** the following special handling is activated:\n  **\n  **   a) if the *-wal file does exist, return SQLITE_CANTOPEN. This\n  **      ensures that the RBU extension never tries to update a database\n  **      in wal mode, even if the first page of the database file has\n  **      been damaged. \n  **\n  **   b) if the *-wal file does not exist, claim that it does anyway,\n  **      causing SQLite to call xOpen() to open it. This call will also\n  **      be intercepted (see the rbuVfsOpen() function) and the *-oal\n  **      file opened instead.\n  */\n  if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){\n    rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath, 1);\n    if( pDb && pDb->pRbu->eStage==RBU_STAGE_OAL ){\n      assert( pDb->pRbu );\n      if( *pResOut ){\n        rc = SQLITE_CANTOPEN;\n      }else{\n        sqlite3_int64 sz = 0;\n        rc = rbuVfsFileSize(&pDb->base, &sz);\n        *pResOut = (sz>0);\n      }\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Populate buffer zOut with the full canonical pathname corresponding\n** to the pathname in zPath. zOut is guaranteed to point to a buffer\n** of at least (DEVSYM_MAX_PATHNAME+1) bytes.\n*/\nstatic int rbuVfsFullPathname(\n  sqlite3_vfs *pVfs, \n  const char *zPath, \n  int nOut, \n  char *zOut\n){\n  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;\n  return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);\n}\n\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\n/*\n** Open the dynamic library located at zPath and return a handle.\n*/\nstatic void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){\n  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;\n  return pRealVfs->xDlOpen(pRealVfs, zPath);\n}\n\n/*\n** Populate the buffer zErrMsg (size nByte bytes) with a human readable\n** utf-8 string describing the most recent error encountered associated \n** with dynamic libraries.\n*/\nstatic void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){\n  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;\n  pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);\n}\n\n/*\n** Return a pointer to the symbol zSymbol in the dynamic library pHandle.\n*/\nstatic void (*rbuVfsDlSym(\n  sqlite3_vfs *pVfs, \n  void *pArg, \n  const char *zSym\n))(void){\n  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;\n  return pRealVfs->xDlSym(pRealVfs, pArg, zSym);\n}\n\n/*\n** Close the dynamic library handle pHandle.\n*/\nstatic void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){\n  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;\n  pRealVfs->xDlClose(pRealVfs, pHandle);\n}\n#endif /* SQLITE_OMIT_LOAD_EXTENSION */\n\n/*\n** Populate the buffer pointed to by zBufOut with nByte bytes of \n** random data.\n*/\nstatic int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){\n  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;\n  return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);\n}\n\n/*\n** Sleep for nMicro microseconds. Return the number of microseconds \n** actually slept.\n*/\nstatic int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){\n  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;\n  return pRealVfs->xSleep(pRealVfs, nMicro);\n}\n\n/*\n** Return the current time as a Julian Day number in *pTimeOut.\n*/\nstatic int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){\n  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;\n  return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);\n}\n\n/*\n** No-op.\n*/\nstatic int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){\n  return 0;\n}\n\n/*\n** Deregister and destroy an RBU vfs created by an earlier call to\n** sqlite3rbu_create_vfs().\n*/\nSQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){\n  sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);\n  if( pVfs && pVfs->xOpen==rbuVfsOpen ){\n    sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);\n    sqlite3_vfs_unregister(pVfs);\n    sqlite3_free(pVfs);\n  }\n}\n\n/*\n** Create an RBU VFS named zName that accesses the underlying file-system\n** via existing VFS zParent. The new object is registered as a non-default\n** VFS with SQLite before returning.\n*/\nSQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){\n\n  /* Template for VFS */\n  static sqlite3_vfs vfs_template = {\n    1,                            /* iVersion */\n    0,                            /* szOsFile */\n    0,                            /* mxPathname */\n    0,                            /* pNext */\n    0,                            /* zName */\n    0,                            /* pAppData */\n    rbuVfsOpen,                   /* xOpen */\n    rbuVfsDelete,                 /* xDelete */\n    rbuVfsAccess,                 /* xAccess */\n    rbuVfsFullPathname,           /* xFullPathname */\n\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\n    rbuVfsDlOpen,                 /* xDlOpen */\n    rbuVfsDlError,                /* xDlError */\n    rbuVfsDlSym,                  /* xDlSym */\n    rbuVfsDlClose,                /* xDlClose */\n#else\n    0, 0, 0, 0,\n#endif\n\n    rbuVfsRandomness,             /* xRandomness */\n    rbuVfsSleep,                  /* xSleep */\n    rbuVfsCurrentTime,            /* xCurrentTime */\n    rbuVfsGetLastError,           /* xGetLastError */\n    0,                            /* xCurrentTimeInt64 (version 2) */\n    0, 0, 0                       /* Unimplemented version 3 methods */\n  };\n\n  rbu_vfs *pNew = 0;              /* Newly allocated VFS */\n  int rc = SQLITE_OK;\n  size_t nName;\n  size_t nByte;\n\n  nName = strlen(zName);\n  nByte = sizeof(rbu_vfs) + nName + 1;\n  pNew = (rbu_vfs*)sqlite3_malloc64(nByte);\n  if( pNew==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    sqlite3_vfs *pParent;           /* Parent VFS */\n    memset(pNew, 0, nByte);\n    pParent = sqlite3_vfs_find(zParent);\n    if( pParent==0 ){\n      rc = SQLITE_NOTFOUND;\n    }else{\n      char *zSpace;\n      memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));\n      pNew->base.mxPathname = pParent->mxPathname;\n      pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;\n      pNew->pRealVfs = pParent;\n      pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);\n      memcpy(zSpace, zName, nName);\n\n      /* Allocate the mutex and register the new VFS (not as the default) */\n      pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);\n      if( pNew->mutex==0 ){\n        rc = SQLITE_NOMEM;\n      }else{\n        rc = sqlite3_vfs_register(&pNew->base, 0);\n      }\n    }\n\n    if( rc!=SQLITE_OK ){\n      sqlite3_mutex_free(pNew->mutex);\n      sqlite3_free(pNew);\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Configure the aggregate temp file size limit for this RBU handle.\n*/\nSQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu *pRbu, sqlite3_int64 n){\n  if( n>=0 ){\n    pRbu->szTempLimit = n;\n  }\n  return pRbu->szTempLimit;\n}\n\nSQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){\n  return pRbu->szTemp;\n}\n\n\n/**************************************************************************/\n\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */\n\n/************** End of sqlite3rbu.c ******************************************/\n/************** Begin file dbstat.c ******************************************/\n/*\n** 2010 July 12\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains an implementation of the \"dbstat\" virtual table.\n**\n** The dbstat virtual table is used to extract low-level storage\n** information from an SQLite database in order to implement the\n** \"sqlite3_analyzer\" utility.  See the ../tool/spaceanal.tcl script\n** for an example implementation.\n**\n** Additional information is available on the \"dbstat.html\" page of the\n** official SQLite documentation.\n*/\n\n/* #include \"sqliteInt.h\"   ** Requires access to internal data structures ** */\n#if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \\\n    && !defined(SQLITE_OMIT_VIRTUALTABLE)\n\n/*\n** Page paths:\n** \n**   The value of the 'path' column describes the path taken from the \n**   root-node of the b-tree structure to each page. The value of the \n**   root-node path is '/'.\n**\n**   The value of the path for the left-most child page of the root of\n**   a b-tree is '/000/'. (Btrees store content ordered from left to right\n**   so the pages to the left have smaller keys than the pages to the right.)\n**   The next to left-most child of the root page is\n**   '/001', and so on, each sibling page identified by a 3-digit hex \n**   value. The children of the 451st left-most sibling have paths such\n**   as '/1c2/000/, '/1c2/001/' etc.\n**\n**   Overflow pages are specified by appending a '+' character and a \n**   six-digit hexadecimal value to the path to the cell they are linked\n**   from. For example, the three overflow pages in a chain linked from \n**   the left-most cell of the 450th child of the root page are identified\n**   by the paths:\n**\n**      '/1c2/000+000000'         // First page in overflow chain\n**      '/1c2/000+000001'         // Second page in overflow chain\n**      '/1c2/000+000002'         // Third page in overflow chain\n**\n**   If the paths are sorted using the BINARY collation sequence, then\n**   the overflow pages associated with a cell will appear earlier in the\n**   sort-order than its child page:\n**\n**      '/1c2/000/'               // Left-most child of 451st child of root\n*/\nstatic const char zDbstatSchema[] = \n  \"CREATE TABLE x(\"\n  \" name       TEXT,\"          /*  0 Name of table or index */\n  \" path       TEXT,\"          /*  1 Path to page from root (NULL for agg) */\n  \" pageno     INTEGER,\"       /*  2 Page number (page count for aggregates) */\n  \" pagetype   TEXT,\"          /*  3 'internal', 'leaf', 'overflow', or NULL */\n  \" ncell      INTEGER,\"       /*  4 Cells on page (0 for overflow) */\n  \" payload    INTEGER,\"       /*  5 Bytes of payload on this page */\n  \" unused     INTEGER,\"       /*  6 Bytes of unused space on this page */\n  \" mx_payload INTEGER,\"       /*  7 Largest payload size of all cells */\n  \" pgoffset   INTEGER,\"       /*  8 Offset of page in file (NULL for agg) */\n  \" pgsize     INTEGER,\"       /*  9 Size of the page (sum for aggregate) */\n  \" schema     TEXT HIDDEN,\"   /* 10 Database schema being analyzed */\n  \" aggregate  BOOLEAN HIDDEN\" /* 11 aggregate info for each table */\n  \")\"\n;\n\n/* Forward reference to data structured used in this module */\ntypedef struct StatTable StatTable;\ntypedef struct StatCursor StatCursor;\ntypedef struct StatPage StatPage;\ntypedef struct StatCell StatCell;\n\n/* Size information for a single cell within a btree page */\nstruct StatCell {\n  int nLocal;                     /* Bytes of local payload */\n  u32 iChildPg;                   /* Child node (or 0 if this is a leaf) */\n  int nOvfl;                      /* Entries in aOvfl[] */\n  u32 *aOvfl;                     /* Array of overflow page numbers */\n  int nLastOvfl;                  /* Bytes of payload on final overflow page */\n  int iOvfl;                      /* Iterates through aOvfl[] */\n};\n\n/* Size information for a single btree page */\nstruct StatPage {\n  u32 iPgno;                      /* Page number */\n  DbPage *pPg;                    /* Page content */\n  int iCell;                      /* Current cell */\n\n  char *zPath;                    /* Path to this page */\n\n  /* Variables populated by statDecodePage(): */\n  u8 flags;                       /* Copy of flags byte */\n  int nCell;                      /* Number of cells on page */\n  int nUnused;                    /* Number of unused bytes on page */\n  StatCell *aCell;                /* Array of parsed cells */\n  u32 iRightChildPg;              /* Right-child page number (or 0) */\n  int nMxPayload;                 /* Largest payload of any cell on the page */\n};\n\n/* The cursor for scanning the dbstat virtual table */\nstruct StatCursor {\n  sqlite3_vtab_cursor base;       /* base class.  MUST BE FIRST! */\n  sqlite3_stmt *pStmt;            /* Iterates through set of root pages */\n  u8 isEof;                       /* After pStmt has returned SQLITE_DONE */\n  u8 isAgg;                       /* Aggregate results for each table */\n  int iDb;                        /* Schema used for this query */\n\n  StatPage aPage[32];             /* Pages in path to current page */\n  int iPage;                      /* Current entry in aPage[] */\n\n  /* Values to return. */\n  u32 iPageno;                    /* Value of 'pageno' column */\n  char *zName;                    /* Value of 'name' column */\n  char *zPath;                    /* Value of 'path' column */\n  char *zPagetype;                /* Value of 'pagetype' column */\n  int nPage;                      /* Number of pages in current btree */\n  int nCell;                      /* Value of 'ncell' column */\n  int nMxPayload;                 /* Value of 'mx_payload' column */\n  i64 nUnused;                    /* Value of 'unused' column */\n  i64 nPayload;                   /* Value of 'payload' column */\n  i64 iOffset;                    /* Value of 'pgOffset' column */\n  i64 szPage;                     /* Value of 'pgSize' column */\n};\n\n/* An instance of the DBSTAT virtual table */\nstruct StatTable {\n  sqlite3_vtab base;              /* base class.  MUST BE FIRST! */\n  sqlite3 *db;                    /* Database connection that owns this vtab */\n  int iDb;                        /* Index of database to analyze */\n};\n\n#ifndef get2byte\n# define get2byte(x)   ((x)[0]<<8 | (x)[1])\n#endif\n\n/*\n** Connect to or create a new DBSTAT virtual table.\n*/\nstatic int statConnect(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  StatTable *pTab = 0;\n  int rc = SQLITE_OK;\n  int iDb;\n\n  if( argc>=4 ){\n    Token nm;\n    sqlite3TokenInit(&nm, (char*)argv[3]);\n    iDb = sqlite3FindDb(db, &nm);\n    if( iDb<0 ){\n      *pzErr = sqlite3_mprintf(\"no such database: %s\", argv[3]);\n      return SQLITE_ERROR;\n    }\n  }else{\n    iDb = 0;\n  }\n  sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);\n  rc = sqlite3_declare_vtab(db, zDbstatSchema);\n  if( rc==SQLITE_OK ){\n    pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));\n    if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;\n  }\n\n  assert( rc==SQLITE_OK || pTab==0 );\n  if( rc==SQLITE_OK ){\n    memset(pTab, 0, sizeof(StatTable));\n    pTab->db = db;\n    pTab->iDb = iDb;\n  }\n\n  *ppVtab = (sqlite3_vtab*)pTab;\n  return rc;\n}\n\n/*\n** Disconnect from or destroy the DBSTAT virtual table.\n*/\nstatic int statDisconnect(sqlite3_vtab *pVtab){\n  sqlite3_free(pVtab);\n  return SQLITE_OK;\n}\n\n/*\n** Compute the best query strategy and return the result in idxNum.\n**\n**   idxNum-Bit        Meaning\n**   ----------        ----------------------------------------------\n**      0x01           There is a schema=? term in the WHERE clause\n**      0x02           There is a name=? term in the WHERE clause\n**      0x04           There is an aggregate=? term in the WHERE clause\n**      0x08           Output should be ordered by name and path\n*/\nstatic int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){\n  int i;\n  int iSchema = -1;\n  int iName = -1;\n  int iAgg = -1;\n\n  /* Look for a valid schema=? constraint.  If found, change the idxNum to\n  ** 1 and request the value of that constraint be sent to xFilter.  And\n  ** lower the cost estimate to encourage the constrained version to be\n  ** used.\n  */\n  for(i=0; i<pIdxInfo->nConstraint; i++){\n    if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;\n    if( pIdxInfo->aConstraint[i].usable==0 ){\n      /* Force DBSTAT table should always be the right-most table in a join */\n      return SQLITE_CONSTRAINT;\n    }\n    switch( pIdxInfo->aConstraint[i].iColumn ){\n      case 0: {    /* name */\n        iName = i;\n        break;\n      }\n      case 10: {   /* schema */\n        iSchema = i;\n        break;\n      }\n      case 11: {   /* aggregate */\n        iAgg = i;\n        break;\n      }\n    }\n  }\n  i = 0;\n  if( iSchema>=0 ){\n    pIdxInfo->aConstraintUsage[iSchema].argvIndex = ++i;\n    pIdxInfo->aConstraintUsage[iSchema].omit = 1;\n    pIdxInfo->idxNum |= 0x01;\n  }\n  if( iName>=0 ){\n    pIdxInfo->aConstraintUsage[iName].argvIndex = ++i;\n    pIdxInfo->idxNum |= 0x02;\n  }\n  if( iAgg>=0 ){\n    pIdxInfo->aConstraintUsage[iAgg].argvIndex = ++i;\n    pIdxInfo->idxNum |= 0x04;\n  }\n  pIdxInfo->estimatedCost = 1.0;\n\n  /* Records are always returned in ascending order of (name, path). \n  ** If this will satisfy the client, set the orderByConsumed flag so that \n  ** SQLite does not do an external sort.\n  */\n  if( ( pIdxInfo->nOrderBy==1\n     && pIdxInfo->aOrderBy[0].iColumn==0\n     && pIdxInfo->aOrderBy[0].desc==0\n     ) ||\n      ( pIdxInfo->nOrderBy==2\n     && pIdxInfo->aOrderBy[0].iColumn==0\n     && pIdxInfo->aOrderBy[0].desc==0\n     && pIdxInfo->aOrderBy[1].iColumn==1\n     && pIdxInfo->aOrderBy[1].desc==0\n     )\n  ){\n    pIdxInfo->orderByConsumed = 1;\n    pIdxInfo->idxNum |= 0x08;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Open a new DBSTAT cursor.\n*/\nstatic int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){\n  StatTable *pTab = (StatTable *)pVTab;\n  StatCursor *pCsr;\n\n  pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));\n  if( pCsr==0 ){\n    return SQLITE_NOMEM_BKPT;\n  }else{\n    memset(pCsr, 0, sizeof(StatCursor));\n    pCsr->base.pVtab = pVTab;\n    pCsr->iDb = pTab->iDb;\n  }\n\n  *ppCursor = (sqlite3_vtab_cursor *)pCsr;\n  return SQLITE_OK;\n}\n\nstatic void statClearCells(StatPage *p){\n  int i;\n  if( p->aCell ){\n    for(i=0; i<p->nCell; i++){\n      sqlite3_free(p->aCell[i].aOvfl);\n    }\n    sqlite3_free(p->aCell);\n  }\n  p->nCell = 0;\n  p->aCell = 0;\n}\n\nstatic void statClearPage(StatPage *p){\n  statClearCells(p);\n  sqlite3PagerUnref(p->pPg);\n  sqlite3_free(p->zPath);\n  memset(p, 0, sizeof(StatPage));\n}\n\nstatic void statResetCsr(StatCursor *pCsr){\n  int i;\n  sqlite3_reset(pCsr->pStmt);\n  for(i=0; i<ArraySize(pCsr->aPage); i++){\n    statClearPage(&pCsr->aPage[i]);\n  }\n  pCsr->iPage = 0;\n  sqlite3_free(pCsr->zPath);\n  pCsr->zPath = 0;\n  pCsr->isEof = 0;\n}\n\n/* Resize the space-used counters inside of the cursor */\nstatic void statResetCounts(StatCursor *pCsr){\n  pCsr->nCell = 0;\n  pCsr->nMxPayload = 0;\n  pCsr->nUnused = 0;\n  pCsr->nPayload = 0;\n  pCsr->szPage = 0;\n  pCsr->nPage = 0;\n}\n\n/*\n** Close a DBSTAT cursor.\n*/\nstatic int statClose(sqlite3_vtab_cursor *pCursor){\n  StatCursor *pCsr = (StatCursor *)pCursor;\n  statResetCsr(pCsr);\n  sqlite3_finalize(pCsr->pStmt);\n  sqlite3_free(pCsr);\n  return SQLITE_OK;\n}\n\n/*\n** For a single cell on a btree page, compute the number of bytes of\n** content (payload) stored on that page.  That is to say, compute the\n** number of bytes of content not found on overflow pages.\n*/\nstatic int getLocalPayload(\n  int nUsable,                    /* Usable bytes per page */\n  u8 flags,                       /* Page flags */\n  int nTotal                      /* Total record (payload) size */\n){\n  int nLocal;\n  int nMinLocal;\n  int nMaxLocal;\n \n  if( flags==0x0D ){              /* Table leaf node */\n    nMinLocal = (nUsable - 12) * 32 / 255 - 23;\n    nMaxLocal = nUsable - 35;\n  }else{                          /* Index interior and leaf nodes */\n    nMinLocal = (nUsable - 12) * 32 / 255 - 23;\n    nMaxLocal = (nUsable - 12) * 64 / 255 - 23;\n  }\n\n  nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);\n  if( nLocal>nMaxLocal ) nLocal = nMinLocal;\n  return nLocal;\n}\n\n/* Populate the StatPage object with information about the all\n** cells found on the page currently under analysis.\n*/\nstatic int statDecodePage(Btree *pBt, StatPage *p){\n  int nUnused;\n  int iOff;\n  int nHdr;\n  int isLeaf;\n  int szPage;\n\n  u8 *aData = sqlite3PagerGetData(p->pPg);\n  u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];\n\n  p->flags = aHdr[0];\n  if( p->flags==0x0A || p->flags==0x0D ){\n    isLeaf = 1;\n    nHdr = 8;\n  }else if( p->flags==0x05 || p->flags==0x02 ){\n    isLeaf = 0;\n    nHdr = 12;\n  }else{\n    goto statPageIsCorrupt;\n  }\n  if( p->iPgno==1 ) nHdr += 100;\n  p->nCell = get2byte(&aHdr[3]);\n  p->nMxPayload = 0;\n  szPage = sqlite3BtreeGetPageSize(pBt);\n\n  nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;\n  nUnused += (int)aHdr[7];\n  iOff = get2byte(&aHdr[1]);\n  while( iOff ){\n    int iNext;\n    if( iOff>=szPage ) goto statPageIsCorrupt;\n    nUnused += get2byte(&aData[iOff+2]);\n    iNext = get2byte(&aData[iOff]);\n    if( iNext<iOff+4 && iNext>0 ) goto statPageIsCorrupt;\n    iOff = iNext;\n  }\n  p->nUnused = nUnused;\n  p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);\n\n  if( p->nCell ){\n    int i;                        /* Used to iterate through cells */\n    int nUsable;                  /* Usable bytes per page */\n\n    sqlite3BtreeEnter(pBt);\n    nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);\n    sqlite3BtreeLeave(pBt);\n    p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));\n    if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;\n    memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));\n\n    for(i=0; i<p->nCell; i++){\n      StatCell *pCell = &p->aCell[i];\n\n      iOff = get2byte(&aData[nHdr+i*2]);\n      if( iOff<nHdr || iOff>=szPage ) goto statPageIsCorrupt;\n      if( !isLeaf ){\n        pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);\n        iOff += 4;\n      }\n      if( p->flags==0x05 ){\n        /* A table interior node. nPayload==0. */\n      }else{\n        u32 nPayload;             /* Bytes of payload total (local+overflow) */\n        int nLocal;               /* Bytes of payload stored locally */\n        iOff += getVarint32(&aData[iOff], nPayload);\n        if( p->flags==0x0D ){\n          u64 dummy;\n          iOff += sqlite3GetVarint(&aData[iOff], &dummy);\n        }\n        if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;\n        nLocal = getLocalPayload(nUsable, p->flags, nPayload);\n        if( nLocal<0 ) goto statPageIsCorrupt;\n        pCell->nLocal = nLocal;\n        assert( nPayload>=(u32)nLocal );\n        assert( nLocal<=(nUsable-35) );\n        if( nPayload>(u32)nLocal ){\n          int j;\n          int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);\n          if( iOff+nLocal>nUsable || nPayload>0x7fffffff ){\n            goto statPageIsCorrupt;\n          }\n          pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);\n          pCell->nOvfl = nOvfl;\n          pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);\n          if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;\n          pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);\n          for(j=1; j<nOvfl; j++){\n            int rc;\n            u32 iPrev = pCell->aOvfl[j-1];\n            DbPage *pPg = 0;\n            rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);\n            if( rc!=SQLITE_OK ){\n              assert( pPg==0 );\n              return rc;\n            } \n            pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));\n            sqlite3PagerUnref(pPg);\n          }\n        }\n      }\n    }\n  }\n\n  return SQLITE_OK;\n\nstatPageIsCorrupt:\n  p->flags = 0;\n  statClearCells(p);\n  return SQLITE_OK;\n}\n\n/*\n** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on\n** the current value of pCsr->iPageno.\n*/\nstatic void statSizeAndOffset(StatCursor *pCsr){\n  StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;\n  Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;\n  Pager *pPager = sqlite3BtreePager(pBt);\n  sqlite3_file *fd;\n  sqlite3_int64 x[2];\n\n  /* If connected to a ZIPVFS backend, find the page size and\n  ** offset from ZIPVFS.\n  */\n  fd = sqlite3PagerFile(pPager);\n  x[0] = pCsr->iPageno;\n  if( sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){\n    pCsr->iOffset = x[0];\n    pCsr->szPage += x[1];\n  }else{\n    /* Not ZIPVFS: The default page size and offset */\n    pCsr->szPage += sqlite3BtreeGetPageSize(pBt);\n    pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);\n  }\n}\n\n/*\n** Move a DBSTAT cursor to the next entry.  Normally, the next\n** entry will be the next page, but in aggregated mode (pCsr->isAgg!=0),\n** the next entry is the next btree.\n*/\nstatic int statNext(sqlite3_vtab_cursor *pCursor){\n  int rc;\n  int nPayload;\n  char *z;\n  StatCursor *pCsr = (StatCursor *)pCursor;\n  StatTable *pTab = (StatTable *)pCursor->pVtab;\n  Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;\n  Pager *pPager = sqlite3BtreePager(pBt);\n\n  sqlite3_free(pCsr->zPath);\n  pCsr->zPath = 0;\n\nstatNextRestart:\n  if( pCsr->aPage[0].pPg==0 ){\n    /* Start measuring space on the next btree */\n    statResetCounts(pCsr);\n    rc = sqlite3_step(pCsr->pStmt);\n    if( rc==SQLITE_ROW ){\n      int nPage;\n      u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);\n      sqlite3PagerPagecount(pPager, &nPage);\n      if( nPage==0 ){\n        pCsr->isEof = 1;\n        return sqlite3_reset(pCsr->pStmt);\n      }\n      rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);\n      pCsr->aPage[0].iPgno = iRoot;\n      pCsr->aPage[0].iCell = 0;\n      if( !pCsr->isAgg ){\n        pCsr->aPage[0].zPath = z = sqlite3_mprintf(\"/\");\n        if( z==0 ) rc = SQLITE_NOMEM_BKPT;\n      }\n      pCsr->iPage = 0;\n      pCsr->nPage = 1;\n    }else{\n      pCsr->isEof = 1;\n      return sqlite3_reset(pCsr->pStmt);\n    }\n  }else{\n    /* Continue analyzing the btree previously started */\n    StatPage *p = &pCsr->aPage[pCsr->iPage];\n    if( !pCsr->isAgg ) statResetCounts(pCsr);\n    while( p->iCell<p->nCell ){\n      StatCell *pCell = &p->aCell[p->iCell];\n      while( pCell->iOvfl<pCell->nOvfl ){\n        int nUsable, iOvfl;\n        sqlite3BtreeEnter(pBt);\n        nUsable = sqlite3BtreeGetPageSize(pBt) - \n                        sqlite3BtreeGetReserveNoMutex(pBt);\n        sqlite3BtreeLeave(pBt);\n        pCsr->nPage++;\n        statSizeAndOffset(pCsr);\n        if( pCell->iOvfl<pCell->nOvfl-1 ){\n          pCsr->nPayload += nUsable - 4;\n        }else{\n          pCsr->nPayload += pCell->nLastOvfl;\n          pCsr->nUnused += nUsable - 4 - pCell->nLastOvfl;\n        }\n        iOvfl = pCell->iOvfl;\n        pCell->iOvfl++;\n        if( !pCsr->isAgg ){\n          pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);\n          pCsr->iPageno = pCell->aOvfl[iOvfl];\n          pCsr->zPagetype = \"overflow\";\n          pCsr->zPath = z = sqlite3_mprintf(\n              \"%s%.3x+%.6x\", p->zPath, p->iCell, iOvfl\n          );\n          return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;\n        }\n      }\n      if( p->iRightChildPg ) break;\n      p->iCell++;\n    }\n\n    if( !p->iRightChildPg || p->iCell>p->nCell ){\n      statClearPage(p);\n      if( pCsr->iPage>0 ){\n        pCsr->iPage--;\n      }else if( pCsr->isAgg ){\n        /* label-statNext-done:  When computing aggregate space usage over\n        ** an entire btree, this is the exit point from this function */\n        return SQLITE_OK;\n      }\n      goto statNextRestart; /* Tail recursion */\n    }\n    pCsr->iPage++;\n    if( pCsr->iPage>=ArraySize(pCsr->aPage) ){\n      statResetCsr(pCsr);\n      return SQLITE_CORRUPT_BKPT;\n    }\n    assert( p==&pCsr->aPage[pCsr->iPage-1] );\n\n    if( p->iCell==p->nCell ){\n      p[1].iPgno = p->iRightChildPg;\n    }else{\n      p[1].iPgno = p->aCell[p->iCell].iChildPg;\n    }\n    rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);\n    pCsr->nPage++;\n    p[1].iCell = 0;\n    if( !pCsr->isAgg ){\n      p[1].zPath = z = sqlite3_mprintf(\"%s%.3x/\", p->zPath, p->iCell);\n      if( z==0 ) rc = SQLITE_NOMEM_BKPT;\n    }\n    p->iCell++;\n  }\n\n\n  /* Populate the StatCursor fields with the values to be returned\n  ** by the xColumn() and xRowid() methods.\n  */\n  if( rc==SQLITE_OK ){\n    int i;\n    StatPage *p = &pCsr->aPage[pCsr->iPage];\n    pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);\n    pCsr->iPageno = p->iPgno;\n\n    rc = statDecodePage(pBt, p);\n    if( rc==SQLITE_OK ){\n      statSizeAndOffset(pCsr);\n\n      switch( p->flags ){\n        case 0x05:             /* table internal */\n        case 0x02:             /* index internal */\n          pCsr->zPagetype = \"internal\";\n          break;\n        case 0x0D:             /* table leaf */\n        case 0x0A:             /* index leaf */\n          pCsr->zPagetype = \"leaf\";\n          break;\n        default:\n          pCsr->zPagetype = \"corrupted\";\n          break;\n      }\n      pCsr->nCell += p->nCell;\n      pCsr->nUnused += p->nUnused;\n      if( p->nMxPayload>pCsr->nMxPayload ) pCsr->nMxPayload = p->nMxPayload;\n      if( !pCsr->isAgg ){\n        pCsr->zPath = z = sqlite3_mprintf(\"%s\", p->zPath);\n        if( z==0 ) rc = SQLITE_NOMEM_BKPT;\n      }\n      nPayload = 0;\n      for(i=0; i<p->nCell; i++){\n        nPayload += p->aCell[i].nLocal;\n      }\n      pCsr->nPayload += nPayload;\n\n      /* If computing aggregate space usage by btree, continue with the\n      ** next page.  The loop will exit via the return at label-statNext-done\n      */\n      if( pCsr->isAgg ) goto statNextRestart;\n    }\n  }\n\n  return rc;\n}\n\nstatic int statEof(sqlite3_vtab_cursor *pCursor){\n  StatCursor *pCsr = (StatCursor *)pCursor;\n  return pCsr->isEof;\n}\n\n/* Initialize a cursor according to the query plan idxNum using the\n** arguments in argv[0].  See statBestIndex() for a description of the\n** meaning of the bits in idxNum.\n*/\nstatic int statFilter(\n  sqlite3_vtab_cursor *pCursor, \n  int idxNum, const char *idxStr,\n  int argc, sqlite3_value **argv\n){\n  StatCursor *pCsr = (StatCursor *)pCursor;\n  StatTable *pTab = (StatTable*)(pCursor->pVtab);\n  sqlite3_str *pSql;      /* Query of btrees to analyze */\n  char *zSql;             /* String value of pSql */\n  int iArg = 0;           /* Count of argv[] parameters used so far */\n  int rc = SQLITE_OK;     /* Result of this operation */\n  const char *zName = 0;  /* Only provide analysis of this table */\n\n  statResetCsr(pCsr);\n  sqlite3_finalize(pCsr->pStmt);\n  pCsr->pStmt = 0;\n  if( idxNum & 0x01 ){\n    /* schema=? constraint is present.  Get its value */\n    const char *zDbase = (const char*)sqlite3_value_text(argv[iArg++]);\n    pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);\n    if( pCsr->iDb<0 ){\n      pCsr->iDb = 0;\n      pCsr->isEof = 1;\n      return SQLITE_OK;\n    }\n  }else{\n    pCsr->iDb = pTab->iDb;\n  }\n  if( idxNum & 0x02 ){\n    /* name=? constraint is present */\n    zName = (const char*)sqlite3_value_text(argv[iArg++]);\n  }\n  if( idxNum & 0x04 ){\n    /* aggregate=? constraint is present */\n    pCsr->isAgg = sqlite3_value_double(argv[iArg++])!=0.0;\n  }else{\n    pCsr->isAgg = 0;\n  }\n  pSql = sqlite3_str_new(pTab->db);\n  sqlite3_str_appendf(pSql,\n      \"SELECT * FROM (\"\n        \"SELECT 'sqlite_master' AS name,1 AS rootpage,'table' AS type\"\n        \" UNION ALL \"\n        \"SELECT name,rootpage,type\"\n        \" FROM \\\"%w\\\".sqlite_master WHERE rootpage!=0)\",\n      pTab->db->aDb[pCsr->iDb].zDbSName);\n  if( zName ){\n    sqlite3_str_appendf(pSql, \"WHERE name=%Q\", zName);\n  }\n  if( idxNum & 0x08 ){\n    sqlite3_str_appendf(pSql, \" ORDER BY name\");\n  }\n  zSql = sqlite3_str_finish(pSql);\n  if( zSql==0 ){\n    return SQLITE_NOMEM_BKPT;\n  }else{\n    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);\n    sqlite3_free(zSql);\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = statNext(pCursor);\n  }\n  return rc;\n}\n\nstatic int statColumn(\n  sqlite3_vtab_cursor *pCursor, \n  sqlite3_context *ctx, \n  int i\n){\n  StatCursor *pCsr = (StatCursor *)pCursor;\n  switch( i ){\n    case 0:            /* name */\n      sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);\n      break;\n    case 1:            /* path */\n      if( !pCsr->isAgg ){\n        sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);\n      }\n      break;\n    case 2:            /* pageno */\n      if( pCsr->isAgg ){\n        sqlite3_result_int64(ctx, pCsr->nPage);\n      }else{\n        sqlite3_result_int64(ctx, pCsr->iPageno);\n      }\n      break;\n    case 3:            /* pagetype */\n      if( !pCsr->isAgg ){\n        sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);\n      }\n      break;\n    case 4:            /* ncell */\n      sqlite3_result_int(ctx, pCsr->nCell);\n      break;\n    case 5:            /* payload */\n      sqlite3_result_int(ctx, pCsr->nPayload);\n      break;\n    case 6:            /* unused */\n      sqlite3_result_int(ctx, pCsr->nUnused);\n      break;\n    case 7:            /* mx_payload */\n      sqlite3_result_int(ctx, pCsr->nMxPayload);\n      break;\n    case 8:            /* pgoffset */\n      if( !pCsr->isAgg ){\n        sqlite3_result_int64(ctx, pCsr->iOffset);\n      }\n      break;\n    case 9:            /* pgsize */\n      sqlite3_result_int(ctx, pCsr->szPage);\n      break;\n    case 10: {         /* schema */\n      sqlite3 *db = sqlite3_context_db_handle(ctx);\n      int iDb = pCsr->iDb;\n      sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);\n      break;\n    }\n    default: {         /* aggregate */\n      sqlite3_result_int(ctx, pCsr->isAgg);\n      break;\n    }\n  }\n  return SQLITE_OK;\n}\n\nstatic int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){\n  StatCursor *pCsr = (StatCursor *)pCursor;\n  *pRowid = pCsr->iPageno;\n  return SQLITE_OK;\n}\n\n/*\n** Invoke this routine to register the \"dbstat\" virtual table module\n*/\nSQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){\n  static sqlite3_module dbstat_module = {\n    0,                            /* iVersion */\n    statConnect,                  /* xCreate */\n    statConnect,                  /* xConnect */\n    statBestIndex,                /* xBestIndex */\n    statDisconnect,               /* xDisconnect */\n    statDisconnect,               /* xDestroy */\n    statOpen,                     /* xOpen - open a cursor */\n    statClose,                    /* xClose - close a cursor */\n    statFilter,                   /* xFilter - configure scan constraints */\n    statNext,                     /* xNext - advance a cursor */\n    statEof,                      /* xEof - check for end of scan */\n    statColumn,                   /* xColumn - read data */\n    statRowid,                    /* xRowid - read data */\n    0,                            /* xUpdate */\n    0,                            /* xBegin */\n    0,                            /* xSync */\n    0,                            /* xCommit */\n    0,                            /* xRollback */\n    0,                            /* xFindMethod */\n    0,                            /* xRename */\n    0,                            /* xSavepoint */\n    0,                            /* xRelease */\n    0,                            /* xRollbackTo */\n    0                             /* xShadowName */\n  };\n  return sqlite3_create_module(db, \"dbstat\", &dbstat_module, 0);\n}\n#elif defined(SQLITE_ENABLE_DBSTAT_VTAB)\nSQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }\n#endif /* SQLITE_ENABLE_DBSTAT_VTAB */\n\n/************** End of dbstat.c **********************************************/\n/************** Begin file dbpage.c ******************************************/\n/*\n** 2017-10-11\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains an implementation of the \"sqlite_dbpage\" virtual table.\n**\n** The sqlite_dbpage virtual table is used to read or write whole raw\n** pages of the database file.  The pager interface is used so that \n** uncommitted changes and changes recorded in the WAL file are correctly\n** retrieved.\n**\n** Usage example:\n**\n**    SELECT data FROM sqlite_dbpage('aux1') WHERE pgno=123;\n**\n** This is an eponymous virtual table so it does not need to be created before\n** use.  The optional argument to the sqlite_dbpage() table name is the\n** schema for the database file that is to be read.  The default schema is\n** \"main\".\n**\n** The data field of sqlite_dbpage table can be updated.  The new\n** value must be a BLOB which is the correct page size, otherwise the\n** update fails.  Rows may not be deleted or inserted.\n*/\n\n/* #include \"sqliteInt.h\"   ** Requires access to internal data structures ** */\n#if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \\\n    && !defined(SQLITE_OMIT_VIRTUALTABLE)\n\ntypedef struct DbpageTable DbpageTable;\ntypedef struct DbpageCursor DbpageCursor;\n\nstruct DbpageCursor {\n  sqlite3_vtab_cursor base;       /* Base class.  Must be first */\n  int pgno;                       /* Current page number */\n  int mxPgno;                     /* Last page to visit on this scan */\n  Pager *pPager;                  /* Pager being read/written */\n  DbPage *pPage1;                 /* Page 1 of the database */\n  int iDb;                        /* Index of database to analyze */\n  int szPage;                     /* Size of each page in bytes */\n};\n\nstruct DbpageTable {\n  sqlite3_vtab base;              /* Base class.  Must be first */\n  sqlite3 *db;                    /* The database */\n};\n\n/* Columns */\n#define DBPAGE_COLUMN_PGNO    0\n#define DBPAGE_COLUMN_DATA    1\n#define DBPAGE_COLUMN_SCHEMA  2\n\n\n\n/*\n** Connect to or create a dbpagevfs virtual table.\n*/\nstatic int dbpageConnect(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  DbpageTable *pTab = 0;\n  int rc = SQLITE_OK;\n\n  sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);\n  rc = sqlite3_declare_vtab(db, \n          \"CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)\");\n  if( rc==SQLITE_OK ){\n    pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));\n    if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;\n  }\n\n  assert( rc==SQLITE_OK || pTab==0 );\n  if( rc==SQLITE_OK ){\n    memset(pTab, 0, sizeof(DbpageTable));\n    pTab->db = db;\n  }\n\n  *ppVtab = (sqlite3_vtab*)pTab;\n  return rc;\n}\n\n/*\n** Disconnect from or destroy a dbpagevfs virtual table.\n*/\nstatic int dbpageDisconnect(sqlite3_vtab *pVtab){\n  sqlite3_free(pVtab);\n  return SQLITE_OK;\n}\n\n/*\n** idxNum:\n**\n**     0     schema=main, full table scan\n**     1     schema=main, pgno=?1\n**     2     schema=?1, full table scan\n**     3     schema=?1, pgno=?2\n*/\nstatic int dbpageBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){\n  int i;\n  int iPlan = 0;\n\n  /* If there is a schema= constraint, it must be honored.  Report a\n  ** ridiculously large estimated cost if the schema= constraint is\n  ** unavailable\n  */\n  for(i=0; i<pIdxInfo->nConstraint; i++){\n    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];\n    if( p->iColumn!=DBPAGE_COLUMN_SCHEMA ) continue;\n    if( p->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;\n    if( !p->usable ){\n      /* No solution. */\n      return SQLITE_CONSTRAINT;\n    }\n    iPlan = 2;\n    pIdxInfo->aConstraintUsage[i].argvIndex = 1;\n    pIdxInfo->aConstraintUsage[i].omit = 1;\n    break;\n  }\n\n  /* If we reach this point, it means that either there is no schema=\n  ** constraint (in which case we use the \"main\" schema) or else the\n  ** schema constraint was accepted.  Lower the estimated cost accordingly\n  */\n  pIdxInfo->estimatedCost = 1.0e6;\n\n  /* Check for constraints against pgno */\n  for(i=0; i<pIdxInfo->nConstraint; i++){\n    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];\n    if( p->usable && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){\n      pIdxInfo->estimatedRows = 1;\n      pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;\n      pIdxInfo->estimatedCost = 1.0;\n      pIdxInfo->aConstraintUsage[i].argvIndex = iPlan ? 2 : 1;\n      pIdxInfo->aConstraintUsage[i].omit = 1;\n      iPlan |= 1;\n      break;\n    }\n  }\n  pIdxInfo->idxNum = iPlan;\n\n  if( pIdxInfo->nOrderBy>=1\n   && pIdxInfo->aOrderBy[0].iColumn<=0\n   && pIdxInfo->aOrderBy[0].desc==0\n  ){\n    pIdxInfo->orderByConsumed = 1;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Open a new dbpagevfs cursor.\n*/\nstatic int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){\n  DbpageCursor *pCsr;\n\n  pCsr = (DbpageCursor *)sqlite3_malloc64(sizeof(DbpageCursor));\n  if( pCsr==0 ){\n    return SQLITE_NOMEM_BKPT;\n  }else{\n    memset(pCsr, 0, sizeof(DbpageCursor));\n    pCsr->base.pVtab = pVTab;\n    pCsr->pgno = -1;\n  }\n\n  *ppCursor = (sqlite3_vtab_cursor *)pCsr;\n  return SQLITE_OK;\n}\n\n/*\n** Close a dbpagevfs cursor.\n*/\nstatic int dbpageClose(sqlite3_vtab_cursor *pCursor){\n  DbpageCursor *pCsr = (DbpageCursor *)pCursor;\n  if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);\n  sqlite3_free(pCsr);\n  return SQLITE_OK;\n}\n\n/*\n** Move a dbpagevfs cursor to the next entry in the file.\n*/\nstatic int dbpageNext(sqlite3_vtab_cursor *pCursor){\n  int rc = SQLITE_OK;\n  DbpageCursor *pCsr = (DbpageCursor *)pCursor;\n  pCsr->pgno++;\n  return rc;\n}\n\nstatic int dbpageEof(sqlite3_vtab_cursor *pCursor){\n  DbpageCursor *pCsr = (DbpageCursor *)pCursor;\n  return pCsr->pgno > pCsr->mxPgno;\n}\n\n/*\n** idxNum:\n**\n**     0     schema=main, full table scan\n**     1     schema=main, pgno=?1\n**     2     schema=?1, full table scan\n**     3     schema=?1, pgno=?2\n**\n** idxStr is not used\n*/\nstatic int dbpageFilter(\n  sqlite3_vtab_cursor *pCursor, \n  int idxNum, const char *idxStr,\n  int argc, sqlite3_value **argv\n){\n  DbpageCursor *pCsr = (DbpageCursor *)pCursor;\n  DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;\n  int rc;\n  sqlite3 *db = pTab->db;\n  Btree *pBt;\n\n  /* Default setting is no rows of result */\n  pCsr->pgno = 1; \n  pCsr->mxPgno = 0;\n\n  if( idxNum & 2 ){\n    const char *zSchema;\n    assert( argc>=1 );\n    zSchema = (const char*)sqlite3_value_text(argv[0]);\n    pCsr->iDb = sqlite3FindDbName(db, zSchema);\n    if( pCsr->iDb<0 ) return SQLITE_OK;\n  }else{\n    pCsr->iDb = 0;\n  }\n  pBt = db->aDb[pCsr->iDb].pBt;\n  if( pBt==0 ) return SQLITE_OK;\n  pCsr->pPager = sqlite3BtreePager(pBt);\n  pCsr->szPage = sqlite3BtreeGetPageSize(pBt);\n  pCsr->mxPgno = sqlite3BtreeLastPage(pBt);\n  if( idxNum & 1 ){\n    assert( argc>(idxNum>>1) );\n    pCsr->pgno = sqlite3_value_int(argv[idxNum>>1]);\n    if( pCsr->pgno<1 || pCsr->pgno>pCsr->mxPgno ){\n      pCsr->pgno = 1;\n      pCsr->mxPgno = 0;\n    }else{\n      pCsr->mxPgno = pCsr->pgno;\n    }\n  }else{\n    assert( pCsr->pgno==1 );\n  }\n  if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);\n  rc = sqlite3PagerGet(pCsr->pPager, 1, &pCsr->pPage1, 0);\n  return rc;\n}\n\nstatic int dbpageColumn(\n  sqlite3_vtab_cursor *pCursor, \n  sqlite3_context *ctx, \n  int i\n){\n  DbpageCursor *pCsr = (DbpageCursor *)pCursor;\n  int rc = SQLITE_OK;\n  switch( i ){\n    case 0: {           /* pgno */\n      sqlite3_result_int(ctx, pCsr->pgno);\n      break;\n    }\n    case 1: {           /* data */\n      DbPage *pDbPage = 0;\n      rc = sqlite3PagerGet(pCsr->pPager, pCsr->pgno, (DbPage**)&pDbPage, 0);\n      if( rc==SQLITE_OK ){\n        sqlite3_result_blob(ctx, sqlite3PagerGetData(pDbPage), pCsr->szPage,\n                            SQLITE_TRANSIENT);\n      }\n      sqlite3PagerUnref(pDbPage);\n      break;\n    }\n    default: {          /* schema */\n      sqlite3 *db = sqlite3_context_db_handle(ctx);\n      sqlite3_result_text(ctx, db->aDb[pCsr->iDb].zDbSName, -1, SQLITE_STATIC);\n      break;\n    }\n  }\n  return SQLITE_OK;\n}\n\nstatic int dbpageRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){\n  DbpageCursor *pCsr = (DbpageCursor *)pCursor;\n  *pRowid = pCsr->pgno;\n  return SQLITE_OK;\n}\n\nstatic int dbpageUpdate(\n  sqlite3_vtab *pVtab,\n  int argc,\n  sqlite3_value **argv,\n  sqlite_int64 *pRowid\n){\n  DbpageTable *pTab = (DbpageTable *)pVtab;\n  Pgno pgno;\n  DbPage *pDbPage = 0;\n  int rc = SQLITE_OK;\n  char *zErr = 0;\n  const char *zSchema;\n  int iDb;\n  Btree *pBt;\n  Pager *pPager;\n  int szPage;\n\n  if( pTab->db->flags & SQLITE_Defensive ){\n    zErr = \"read-only\";\n    goto update_fail;\n  }\n  if( argc==1 ){\n    zErr = \"cannot delete\";\n    goto update_fail;\n  }\n  pgno = sqlite3_value_int(argv[0]);\n  if( (Pgno)sqlite3_value_int(argv[1])!=pgno ){\n    zErr = \"cannot insert\";\n    goto update_fail;\n  }\n  zSchema = (const char*)sqlite3_value_text(argv[4]);\n  iDb = zSchema ? sqlite3FindDbName(pTab->db, zSchema) : -1;\n  if( iDb<0 ){\n    zErr = \"no such schema\";\n    goto update_fail;\n  }\n  pBt = pTab->db->aDb[iDb].pBt;\n  if( pgno<1 || pBt==0 || pgno>(int)sqlite3BtreeLastPage(pBt) ){\n    zErr = \"bad page number\";\n    goto update_fail;\n  }\n  szPage = sqlite3BtreeGetPageSize(pBt);\n  if( sqlite3_value_type(argv[3])!=SQLITE_BLOB \n   || sqlite3_value_bytes(argv[3])!=szPage\n  ){\n    zErr = \"bad page value\";\n    goto update_fail;\n  }\n  pPager = sqlite3BtreePager(pBt);\n  rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pDbPage, 0);\n  if( rc==SQLITE_OK ){\n    rc = sqlite3PagerWrite(pDbPage);\n    if( rc==SQLITE_OK ){\n      memcpy(sqlite3PagerGetData(pDbPage),\n             sqlite3_value_blob(argv[3]),\n             szPage);\n    }\n  }\n  sqlite3PagerUnref(pDbPage);\n  return rc;\n\nupdate_fail:\n  sqlite3_free(pVtab->zErrMsg);\n  pVtab->zErrMsg = sqlite3_mprintf(\"%s\", zErr);\n  return SQLITE_ERROR;\n}\n\n/* Since we do not know in advance which database files will be\n** written by the sqlite_dbpage virtual table, start a write transaction\n** on them all.\n*/\nstatic int dbpageBegin(sqlite3_vtab *pVtab){\n  DbpageTable *pTab = (DbpageTable *)pVtab;\n  sqlite3 *db = pTab->db;\n  int i;\n  for(i=0; i<db->nDb; i++){\n    Btree *pBt = db->aDb[i].pBt;\n    if( pBt ) sqlite3BtreeBeginTrans(pBt, 1, 0);\n  }\n  return SQLITE_OK;\n}\n\n\n/*\n** Invoke this routine to register the \"dbpage\" virtual table module\n*/\nSQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){\n  static sqlite3_module dbpage_module = {\n    0,                            /* iVersion */\n    dbpageConnect,                /* xCreate */\n    dbpageConnect,                /* xConnect */\n    dbpageBestIndex,              /* xBestIndex */\n    dbpageDisconnect,             /* xDisconnect */\n    dbpageDisconnect,             /* xDestroy */\n    dbpageOpen,                   /* xOpen - open a cursor */\n    dbpageClose,                  /* xClose - close a cursor */\n    dbpageFilter,                 /* xFilter - configure scan constraints */\n    dbpageNext,                   /* xNext - advance a cursor */\n    dbpageEof,                    /* xEof - check for end of scan */\n    dbpageColumn,                 /* xColumn - read data */\n    dbpageRowid,                  /* xRowid - read data */\n    dbpageUpdate,                 /* xUpdate */\n    dbpageBegin,                  /* xBegin */\n    0,                            /* xSync */\n    0,                            /* xCommit */\n    0,                            /* xRollback */\n    0,                            /* xFindMethod */\n    0,                            /* xRename */\n    0,                            /* xSavepoint */\n    0,                            /* xRelease */\n    0,                            /* xRollbackTo */\n    0                             /* xShadowName */\n  };\n  return sqlite3_create_module(db, \"sqlite_dbpage\", &dbpage_module, 0);\n}\n#elif defined(SQLITE_ENABLE_DBPAGE_VTAB)\nSQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }\n#endif /* SQLITE_ENABLE_DBSTAT_VTAB */\n\n/************** End of dbpage.c **********************************************/\n/************** Begin file sqlite3session.c **********************************/\n\n#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)\n/* #include \"sqlite3session.h\" */\n/* #include <assert.h> */\n/* #include <string.h> */\n\n#ifndef SQLITE_AMALGAMATION\n/* # include \"sqliteInt.h\" */\n/* # include \"vdbeInt.h\" */\n#endif\n\ntypedef struct SessionTable SessionTable;\ntypedef struct SessionChange SessionChange;\ntypedef struct SessionBuffer SessionBuffer;\ntypedef struct SessionInput SessionInput;\n\n/*\n** Minimum chunk size used by streaming versions of functions.\n*/\n#ifndef SESSIONS_STRM_CHUNK_SIZE\n# ifdef SQLITE_TEST\n#   define SESSIONS_STRM_CHUNK_SIZE 64\n# else\n#   define SESSIONS_STRM_CHUNK_SIZE 1024\n# endif\n#endif\n\nstatic int sessions_strm_chunk_size = SESSIONS_STRM_CHUNK_SIZE;\n\ntypedef struct SessionHook SessionHook;\nstruct SessionHook {\n  void *pCtx;\n  int (*xOld)(void*,int,sqlite3_value**);\n  int (*xNew)(void*,int,sqlite3_value**);\n  int (*xCount)(void*);\n  int (*xDepth)(void*);\n};\n\n/*\n** Session handle structure.\n*/\nstruct sqlite3_session {\n  sqlite3 *db;                    /* Database handle session is attached to */\n  char *zDb;                      /* Name of database session is attached to */\n  int bEnable;                    /* True if currently recording */\n  int bIndirect;                  /* True if all changes are indirect */\n  int bAutoAttach;                /* True to auto-attach tables */\n  int rc;                         /* Non-zero if an error has occurred */\n  void *pFilterCtx;               /* First argument to pass to xTableFilter */\n  int (*xTableFilter)(void *pCtx, const char *zTab);\n  sqlite3_value *pZeroBlob;       /* Value containing X'' */\n  sqlite3_session *pNext;         /* Next session object on same db. */\n  SessionTable *pTable;           /* List of attached tables */\n  SessionHook hook;               /* APIs to grab new and old data with */\n};\n\n/*\n** Instances of this structure are used to build strings or binary records.\n*/\nstruct SessionBuffer {\n  u8 *aBuf;                       /* Pointer to changeset buffer */\n  int nBuf;                       /* Size of buffer aBuf */\n  int nAlloc;                     /* Size of allocation containing aBuf */\n};\n\n/*\n** An object of this type is used internally as an abstraction for \n** input data. Input data may be supplied either as a single large buffer\n** (e.g. sqlite3changeset_start()) or using a stream function (e.g.\n**  sqlite3changeset_start_strm()).\n*/\nstruct SessionInput {\n  int bNoDiscard;                 /* If true, do not discard in InputBuffer() */\n  int iCurrent;                   /* Offset in aData[] of current change */\n  int iNext;                      /* Offset in aData[] of next change */\n  u8 *aData;                      /* Pointer to buffer containing changeset */\n  int nData;                      /* Number of bytes in aData */\n\n  SessionBuffer buf;              /* Current read buffer */\n  int (*xInput)(void*, void*, int*);        /* Input stream call (or NULL) */\n  void *pIn;                                /* First argument to xInput */\n  int bEof;                       /* Set to true after xInput finished */\n};\n\n/*\n** Structure for changeset iterators.\n*/\nstruct sqlite3_changeset_iter {\n  SessionInput in;                /* Input buffer or stream */\n  SessionBuffer tblhdr;           /* Buffer to hold apValue/zTab/abPK/ */\n  int bPatchset;                  /* True if this is a patchset */\n  int bInvert;                    /* True to invert changeset */\n  int rc;                         /* Iterator error code */\n  sqlite3_stmt *pConflict;        /* Points to conflicting row, if any */\n  char *zTab;                     /* Current table */\n  int nCol;                       /* Number of columns in zTab */\n  int op;                         /* Current operation */\n  int bIndirect;                  /* True if current change was indirect */\n  u8 *abPK;                       /* Primary key array */\n  sqlite3_value **apValue;        /* old.* and new.* values */\n};\n\n/*\n** Each session object maintains a set of the following structures, one\n** for each table the session object is monitoring. The structures are\n** stored in a linked list starting at sqlite3_session.pTable.\n**\n** The keys of the SessionTable.aChange[] hash table are all rows that have\n** been modified in any way since the session object was attached to the\n** table.\n**\n** The data associated with each hash-table entry is a structure containing\n** a subset of the initial values that the modified row contained at the\n** start of the session. Or no initial values if the row was inserted.\n*/\nstruct SessionTable {\n  SessionTable *pNext;\n  char *zName;                    /* Local name of table */\n  int nCol;                       /* Number of columns in table zName */\n  int bStat1;                     /* True if this is sqlite_stat1 */\n  const char **azCol;             /* Column names */\n  u8 *abPK;                       /* Array of primary key flags */\n  int nEntry;                     /* Total number of entries in hash table */\n  int nChange;                    /* Size of apChange[] array */\n  SessionChange **apChange;       /* Hash table buckets */\n};\n\n/* \n** RECORD FORMAT:\n**\n** The following record format is similar to (but not compatible with) that \n** used in SQLite database files. This format is used as part of the \n** change-set binary format, and so must be architecture independent.\n**\n** Unlike the SQLite database record format, each field is self-contained -\n** there is no separation of header and data. Each field begins with a\n** single byte describing its type, as follows:\n**\n**       0x00: Undefined value.\n**       0x01: Integer value.\n**       0x02: Real value.\n**       0x03: Text value.\n**       0x04: Blob value.\n**       0x05: SQL NULL value.\n**\n** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT\n** and so on in sqlite3.h. For undefined and NULL values, the field consists\n** only of the single type byte. For other types of values, the type byte\n** is followed by:\n**\n**   Text values:\n**     A varint containing the number of bytes in the value (encoded using\n**     UTF-8). Followed by a buffer containing the UTF-8 representation\n**     of the text value. There is no nul terminator.\n**\n**   Blob values:\n**     A varint containing the number of bytes in the value, followed by\n**     a buffer containing the value itself.\n**\n**   Integer values:\n**     An 8-byte big-endian integer value.\n**\n**   Real values:\n**     An 8-byte big-endian IEEE 754-2008 real value.\n**\n** Varint values are encoded in the same way as varints in the SQLite \n** record format.\n**\n** CHANGESET FORMAT:\n**\n** A changeset is a collection of DELETE, UPDATE and INSERT operations on\n** one or more tables. Operations on a single table are grouped together,\n** but may occur in any order (i.e. deletes, updates and inserts are all\n** mixed together).\n**\n** Each group of changes begins with a table header:\n**\n**   1 byte: Constant 0x54 (capital 'T')\n**   Varint: Number of columns in the table.\n**   nCol bytes: 0x01 for PK columns, 0x00 otherwise.\n**   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.\n**\n** Followed by one or more changes to the table.\n**\n**   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).\n**   1 byte: The \"indirect-change\" flag.\n**   old.* record: (delete and update only)\n**   new.* record: (insert and update only)\n**\n** The \"old.*\" and \"new.*\" records, if present, are N field records in the\n** format described above under \"RECORD FORMAT\", where N is the number of\n** columns in the table. The i'th field of each record is associated with\n** the i'th column of the table, counting from left to right in the order\n** in which columns were declared in the CREATE TABLE statement.\n**\n** The new.* record that is part of each INSERT change contains the values\n** that make up the new row. Similarly, the old.* record that is part of each\n** DELETE change contains the values that made up the row that was deleted \n** from the database. In the changeset format, the records that are part\n** of INSERT or DELETE changes never contain any undefined (type byte 0x00)\n** fields.\n**\n** Within the old.* record associated with an UPDATE change, all fields\n** associated with table columns that are not PRIMARY KEY columns and are\n** not modified by the UPDATE change are set to \"undefined\". Other fields\n** are set to the values that made up the row before the UPDATE that the\n** change records took place. Within the new.* record, fields associated \n** with table columns modified by the UPDATE change contain the new \n** values. Fields associated with table columns that are not modified\n** are set to \"undefined\".\n**\n** PATCHSET FORMAT:\n**\n** A patchset is also a collection of changes. It is similar to a changeset,\n** but leaves undefined those fields that are not useful if no conflict\n** resolution is required when applying the changeset.\n**\n** Each group of changes begins with a table header:\n**\n**   1 byte: Constant 0x50 (capital 'P')\n**   Varint: Number of columns in the table.\n**   nCol bytes: 0x01 for PK columns, 0x00 otherwise.\n**   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.\n**\n** Followed by one or more changes to the table.\n**\n**   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).\n**   1 byte: The \"indirect-change\" flag.\n**   single record: (PK fields for DELETE, PK and modified fields for UPDATE,\n**                   full record for INSERT).\n**\n** As in the changeset format, each field of the single record that is part\n** of a patchset change is associated with the correspondingly positioned\n** table column, counting from left to right within the CREATE TABLE \n** statement.\n**\n** For a DELETE change, all fields within the record except those associated\n** with PRIMARY KEY columns are omitted. The PRIMARY KEY fields contain the\n** values identifying the row to delete.\n**\n** For an UPDATE change, all fields except those associated with PRIMARY KEY\n** columns and columns that are modified by the UPDATE are set to \"undefined\".\n** PRIMARY KEY fields contain the values identifying the table row to update,\n** and fields associated with modified columns contain the new column values.\n**\n** The records associated with INSERT changes are in the same format as for\n** changesets. It is not possible for a record associated with an INSERT\n** change to contain a field set to \"undefined\".\n**\n** REBASE BLOB FORMAT:\n**\n** A rebase blob may be output by sqlite3changeset_apply_v2() and its \n** streaming equivalent for use with the sqlite3_rebaser APIs to rebase\n** existing changesets. A rebase blob contains one entry for each conflict\n** resolved using either the OMIT or REPLACE strategies within the apply_v2()\n** call.\n**\n** The format used for a rebase blob is very similar to that used for\n** changesets. All entries related to a single table are grouped together.\n**\n** Each group of entries begins with a table header in changeset format:\n**\n**   1 byte: Constant 0x54 (capital 'T')\n**   Varint: Number of columns in the table.\n**   nCol bytes: 0x01 for PK columns, 0x00 otherwise.\n**   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.\n**\n** Followed by one or more entries associated with the table.\n**\n**   1 byte: Either SQLITE_INSERT (0x12), DELETE (0x09).\n**   1 byte: Flag. 0x01 for REPLACE, 0x00 for OMIT.\n**   record: (in the record format defined above).\n**\n** In a rebase blob, the first field is set to SQLITE_INSERT if the change\n** that caused the conflict was an INSERT or UPDATE, or to SQLITE_DELETE if\n** it was a DELETE. The second field is set to 0x01 if the conflict \n** resolution strategy was REPLACE, or 0x00 if it was OMIT.\n**\n** If the change that caused the conflict was a DELETE, then the single\n** record is a copy of the old.* record from the original changeset. If it\n** was an INSERT, then the single record is a copy of the new.* record. If\n** the conflicting change was an UPDATE, then the single record is a copy\n** of the new.* record with the PK fields filled in based on the original\n** old.* record.\n*/\n\n/*\n** For each row modified during a session, there exists a single instance of\n** this structure stored in a SessionTable.aChange[] hash table.\n*/\nstruct SessionChange {\n  int op;                         /* One of UPDATE, DELETE, INSERT */\n  int bIndirect;                  /* True if this change is \"indirect\" */\n  int nRecord;                    /* Number of bytes in buffer aRecord[] */\n  u8 *aRecord;                    /* Buffer containing old.* record */\n  SessionChange *pNext;           /* For hash-table collisions */\n};\n\n/*\n** Write a varint with value iVal into the buffer at aBuf. Return the \n** number of bytes written.\n*/\nstatic int sessionVarintPut(u8 *aBuf, int iVal){\n  return putVarint32(aBuf, iVal);\n}\n\n/*\n** Return the number of bytes required to store value iVal as a varint.\n*/\nstatic int sessionVarintLen(int iVal){\n  return sqlite3VarintLen(iVal);\n}\n\n/*\n** Read a varint value from aBuf[] into *piVal. Return the number of \n** bytes read.\n*/\nstatic int sessionVarintGet(u8 *aBuf, int *piVal){\n  return getVarint32(aBuf, *piVal);\n}\n\n/* Load an unaligned and unsigned 32-bit integer */\n#define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])\n\n/*\n** Read a 64-bit big-endian integer value from buffer aRec[]. Return\n** the value read.\n*/\nstatic sqlite3_int64 sessionGetI64(u8 *aRec){\n  u64 x = SESSION_UINT32(aRec);\n  u32 y = SESSION_UINT32(aRec+4);\n  x = (x<<32) + y;\n  return (sqlite3_int64)x;\n}\n\n/*\n** Write a 64-bit big-endian integer value to the buffer aBuf[].\n*/\nstatic void sessionPutI64(u8 *aBuf, sqlite3_int64 i){\n  aBuf[0] = (i>>56) & 0xFF;\n  aBuf[1] = (i>>48) & 0xFF;\n  aBuf[2] = (i>>40) & 0xFF;\n  aBuf[3] = (i>>32) & 0xFF;\n  aBuf[4] = (i>>24) & 0xFF;\n  aBuf[5] = (i>>16) & 0xFF;\n  aBuf[6] = (i>> 8) & 0xFF;\n  aBuf[7] = (i>> 0) & 0xFF;\n}\n\n/*\n** This function is used to serialize the contents of value pValue (see\n** comment titled \"RECORD FORMAT\" above).\n**\n** If it is non-NULL, the serialized form of the value is written to \n** buffer aBuf. *pnWrite is set to the number of bytes written before\n** returning. Or, if aBuf is NULL, the only thing this function does is\n** set *pnWrite.\n**\n** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs\n** within a call to sqlite3_value_text() (may fail if the db is utf-16)) \n** SQLITE_NOMEM is returned.\n*/\nstatic int sessionSerializeValue(\n  u8 *aBuf,                       /* If non-NULL, write serialized value here */\n  sqlite3_value *pValue,          /* Value to serialize */\n  sqlite3_int64 *pnWrite          /* IN/OUT: Increment by bytes written */\n){\n  int nByte;                      /* Size of serialized value in bytes */\n\n  if( pValue ){\n    int eType;                    /* Value type (SQLITE_NULL, TEXT etc.) */\n  \n    eType = sqlite3_value_type(pValue);\n    if( aBuf ) aBuf[0] = eType;\n  \n    switch( eType ){\n      case SQLITE_NULL: \n        nByte = 1;\n        break;\n  \n      case SQLITE_INTEGER: \n      case SQLITE_FLOAT:\n        if( aBuf ){\n          /* TODO: SQLite does something special to deal with mixed-endian\n          ** floating point values (e.g. ARM7). This code probably should\n          ** too.  */\n          u64 i;\n          if( eType==SQLITE_INTEGER ){\n            i = (u64)sqlite3_value_int64(pValue);\n          }else{\n            double r;\n            assert( sizeof(double)==8 && sizeof(u64)==8 );\n            r = sqlite3_value_double(pValue);\n            memcpy(&i, &r, 8);\n          }\n          sessionPutI64(&aBuf[1], i);\n        }\n        nByte = 9; \n        break;\n  \n      default: {\n        u8 *z;\n        int n;\n        int nVarint;\n  \n        assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );\n        if( eType==SQLITE_TEXT ){\n          z = (u8 *)sqlite3_value_text(pValue);\n        }else{\n          z = (u8 *)sqlite3_value_blob(pValue);\n        }\n        n = sqlite3_value_bytes(pValue);\n        if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;\n        nVarint = sessionVarintLen(n);\n  \n        if( aBuf ){\n          sessionVarintPut(&aBuf[1], n);\n          if( n ) memcpy(&aBuf[nVarint + 1], z, n);\n        }\n  \n        nByte = 1 + nVarint + n;\n        break;\n      }\n    }\n  }else{\n    nByte = 1;\n    if( aBuf ) aBuf[0] = '\\0';\n  }\n\n  if( pnWrite ) *pnWrite += nByte;\n  return SQLITE_OK;\n}\n\n\n/*\n** This macro is used to calculate hash key values for data structures. In\n** order to use this macro, the entire data structure must be represented\n** as a series of unsigned integers. In order to calculate a hash-key value\n** for a data structure represented as three such integers, the macro may\n** then be used as follows:\n**\n**    int hash_key_value;\n**    hash_key_value = HASH_APPEND(0, <value 1>);\n**    hash_key_value = HASH_APPEND(hash_key_value, <value 2>);\n**    hash_key_value = HASH_APPEND(hash_key_value, <value 3>);\n**\n** In practice, the data structures this macro is used for are the primary\n** key values of modified rows.\n*/\n#define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)\n\n/*\n** Append the hash of the 64-bit integer passed as the second argument to the\n** hash-key value passed as the first. Return the new hash-key value.\n*/\nstatic unsigned int sessionHashAppendI64(unsigned int h, i64 i){\n  h = HASH_APPEND(h, i & 0xFFFFFFFF);\n  return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);\n}\n\n/*\n** Append the hash of the blob passed via the second and third arguments to \n** the hash-key value passed as the first. Return the new hash-key value.\n*/\nstatic unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){\n  int i;\n  for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);\n  return h;\n}\n\n/*\n** Append the hash of the data type passed as the second argument to the\n** hash-key value passed as the first. Return the new hash-key value.\n*/\nstatic unsigned int sessionHashAppendType(unsigned int h, int eType){\n  return HASH_APPEND(h, eType);\n}\n\n/*\n** This function may only be called from within a pre-update callback.\n** It calculates a hash based on the primary key values of the old.* or \n** new.* row currently available and, assuming no error occurs, writes it to\n** *piHash before returning. If the primary key contains one or more NULL\n** values, *pbNullPK is set to true before returning.\n**\n** If an error occurs, an SQLite error code is returned and the final values\n** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned\n** and the output variables are set as described above.\n*/\nstatic int sessionPreupdateHash(\n  sqlite3_session *pSession,      /* Session object that owns pTab */\n  SessionTable *pTab,             /* Session table handle */\n  int bNew,                       /* True to hash the new.* PK */\n  int *piHash,                    /* OUT: Hash value */\n  int *pbNullPK                   /* OUT: True if there are NULL values in PK */\n){\n  unsigned int h = 0;             /* Hash value to return */\n  int i;                          /* Used to iterate through columns */\n\n  assert( *pbNullPK==0 );\n  assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );\n  for(i=0; i<pTab->nCol; i++){\n    if( pTab->abPK[i] ){\n      int rc;\n      int eType;\n      sqlite3_value *pVal;\n\n      if( bNew ){\n        rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);\n      }else{\n        rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);\n      }\n      if( rc!=SQLITE_OK ) return rc;\n\n      eType = sqlite3_value_type(pVal);\n      h = sessionHashAppendType(h, eType);\n      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){\n        i64 iVal;\n        if( eType==SQLITE_INTEGER ){\n          iVal = sqlite3_value_int64(pVal);\n        }else{\n          double rVal = sqlite3_value_double(pVal);\n          assert( sizeof(iVal)==8 && sizeof(rVal)==8 );\n          memcpy(&iVal, &rVal, 8);\n        }\n        h = sessionHashAppendI64(h, iVal);\n      }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){\n        const u8 *z;\n        int n;\n        if( eType==SQLITE_TEXT ){\n          z = (const u8 *)sqlite3_value_text(pVal);\n        }else{\n          z = (const u8 *)sqlite3_value_blob(pVal);\n        }\n        n = sqlite3_value_bytes(pVal);\n        if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;\n        h = sessionHashAppendBlob(h, n, z);\n      }else{\n        assert( eType==SQLITE_NULL );\n        assert( pTab->bStat1==0 || i!=1 );\n        *pbNullPK = 1;\n      }\n    }\n  }\n\n  *piHash = (h % pTab->nChange);\n  return SQLITE_OK;\n}\n\n/*\n** The buffer that the argument points to contains a serialized SQL value.\n** Return the number of bytes of space occupied by the value (including\n** the type byte).\n*/\nstatic int sessionSerialLen(u8 *a){\n  int e = *a;\n  int n;\n  if( e==0 || e==0xFF ) return 1;\n  if( e==SQLITE_NULL ) return 1;\n  if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;\n  return sessionVarintGet(&a[1], &n) + 1 + n;\n}\n\n/*\n** Based on the primary key values stored in change aRecord, calculate a\n** hash key. Assume the has table has nBucket buckets. The hash keys\n** calculated by this function are compatible with those calculated by\n** sessionPreupdateHash().\n**\n** The bPkOnly argument is non-zero if the record at aRecord[] is from\n** a patchset DELETE. In this case the non-PK fields are omitted entirely.\n*/\nstatic unsigned int sessionChangeHash(\n  SessionTable *pTab,             /* Table handle */\n  int bPkOnly,                    /* Record consists of PK fields only */\n  u8 *aRecord,                    /* Change record */\n  int nBucket                     /* Assume this many buckets in hash table */\n){\n  unsigned int h = 0;             /* Value to return */\n  int i;                          /* Used to iterate through columns */\n  u8 *a = aRecord;                /* Used to iterate through change record */\n\n  for(i=0; i<pTab->nCol; i++){\n    int eType = *a;\n    int isPK = pTab->abPK[i];\n    if( bPkOnly && isPK==0 ) continue;\n\n    /* It is not possible for eType to be SQLITE_NULL here. The session \n    ** module does not record changes for rows with NULL values stored in\n    ** primary key columns. */\n    assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT \n         || eType==SQLITE_TEXT || eType==SQLITE_BLOB \n         || eType==SQLITE_NULL || eType==0 \n    );\n    assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );\n\n    if( isPK ){\n      a++;\n      h = sessionHashAppendType(h, eType);\n      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){\n        h = sessionHashAppendI64(h, sessionGetI64(a));\n        a += 8;\n      }else{\n        int n; \n        a += sessionVarintGet(a, &n);\n        h = sessionHashAppendBlob(h, n, a);\n        a += n;\n      }\n    }else{\n      a += sessionSerialLen(a);\n    }\n  }\n  return (h % nBucket);\n}\n\n/*\n** Arguments aLeft and aRight are pointers to change records for table pTab.\n** This function returns true if the two records apply to the same row (i.e.\n** have the same values stored in the primary key columns), or false \n** otherwise.\n*/\nstatic int sessionChangeEqual(\n  SessionTable *pTab,             /* Table used for PK definition */\n  int bLeftPkOnly,                /* True if aLeft[] contains PK fields only */\n  u8 *aLeft,                      /* Change record */\n  int bRightPkOnly,               /* True if aRight[] contains PK fields only */\n  u8 *aRight                      /* Change record */\n){\n  u8 *a1 = aLeft;                 /* Cursor to iterate through aLeft */\n  u8 *a2 = aRight;                /* Cursor to iterate through aRight */\n  int iCol;                       /* Used to iterate through table columns */\n\n  for(iCol=0; iCol<pTab->nCol; iCol++){\n    if( pTab->abPK[iCol] ){\n      int n1 = sessionSerialLen(a1);\n      int n2 = sessionSerialLen(a2);\n\n      if( n1!=n2 || memcmp(a1, a2, n1) ){\n        return 0;\n      }\n      a1 += n1;\n      a2 += n2;\n    }else{\n      if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);\n      if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);\n    }\n  }\n\n  return 1;\n}\n\n/*\n** Arguments aLeft and aRight both point to buffers containing change\n** records with nCol columns. This function \"merges\" the two records into\n** a single records which is written to the buffer at *paOut. *paOut is\n** then set to point to one byte after the last byte written before \n** returning.\n**\n** The merging of records is done as follows: For each column, if the \n** aRight record contains a value for the column, copy the value from\n** their. Otherwise, if aLeft contains a value, copy it. If neither\n** record contains a value for a given column, then neither does the\n** output record.\n*/\nstatic void sessionMergeRecord(\n  u8 **paOut, \n  int nCol,\n  u8 *aLeft,\n  u8 *aRight\n){\n  u8 *a1 = aLeft;                 /* Cursor used to iterate through aLeft */\n  u8 *a2 = aRight;                /* Cursor used to iterate through aRight */\n  u8 *aOut = *paOut;              /* Output cursor */\n  int iCol;                       /* Used to iterate from 0 to nCol */\n\n  for(iCol=0; iCol<nCol; iCol++){\n    int n1 = sessionSerialLen(a1);\n    int n2 = sessionSerialLen(a2);\n    if( *a2 ){\n      memcpy(aOut, a2, n2);\n      aOut += n2;\n    }else{\n      memcpy(aOut, a1, n1);\n      aOut += n1;\n    }\n    a1 += n1;\n    a2 += n2;\n  }\n\n  *paOut = aOut;\n}\n\n/*\n** This is a helper function used by sessionMergeUpdate().\n**\n** When this function is called, both *paOne and *paTwo point to a value \n** within a change record. Before it returns, both have been advanced so \n** as to point to the next value in the record.\n**\n** If, when this function is called, *paTwo points to a valid value (i.e.\n** *paTwo[0] is not 0x00 - the \"no value\" placeholder), a copy of the *paTwo\n** pointer is returned and *pnVal is set to the number of bytes in the \n** serialized value. Otherwise, a copy of *paOne is returned and *pnVal\n** set to the number of bytes in the value at *paOne. If *paOne points\n** to the \"no value\" placeholder, *pnVal is set to 1. In other words:\n**\n**   if( *paTwo is valid ) return *paTwo;\n**   return *paOne;\n**\n*/\nstatic u8 *sessionMergeValue(\n  u8 **paOne,                     /* IN/OUT: Left-hand buffer pointer */\n  u8 **paTwo,                     /* IN/OUT: Right-hand buffer pointer */\n  int *pnVal                      /* OUT: Bytes in returned value */\n){\n  u8 *a1 = *paOne;\n  u8 *a2 = *paTwo;\n  u8 *pRet = 0;\n  int n1;\n\n  assert( a1 );\n  if( a2 ){\n    int n2 = sessionSerialLen(a2);\n    if( *a2 ){\n      *pnVal = n2;\n      pRet = a2;\n    }\n    *paTwo = &a2[n2];\n  }\n\n  n1 = sessionSerialLen(a1);\n  if( pRet==0 ){\n    *pnVal = n1;\n    pRet = a1;\n  }\n  *paOne = &a1[n1];\n\n  return pRet;\n}\n\n/*\n** This function is used by changeset_concat() to merge two UPDATE changes\n** on the same row.\n*/\nstatic int sessionMergeUpdate(\n  u8 **paOut,                     /* IN/OUT: Pointer to output buffer */\n  SessionTable *pTab,             /* Table change pertains to */\n  int bPatchset,                  /* True if records are patchset records */\n  u8 *aOldRecord1,                /* old.* record for first change */\n  u8 *aOldRecord2,                /* old.* record for second change */\n  u8 *aNewRecord1,                /* new.* record for first change */\n  u8 *aNewRecord2                 /* new.* record for second change */\n){\n  u8 *aOld1 = aOldRecord1;\n  u8 *aOld2 = aOldRecord2;\n  u8 *aNew1 = aNewRecord1;\n  u8 *aNew2 = aNewRecord2;\n\n  u8 *aOut = *paOut;\n  int i;\n\n  if( bPatchset==0 ){\n    int bRequired = 0;\n\n    assert( aOldRecord1 && aNewRecord1 );\n\n    /* Write the old.* vector first. */\n    for(i=0; i<pTab->nCol; i++){\n      int nOld;\n      u8 *aOld;\n      int nNew;\n      u8 *aNew;\n\n      aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);\n      aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);\n      if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){\n        if( pTab->abPK[i]==0 ) bRequired = 1;\n        memcpy(aOut, aOld, nOld);\n        aOut += nOld;\n      }else{\n        *(aOut++) = '\\0';\n      }\n    }\n\n    if( !bRequired ) return 0;\n  }\n\n  /* Write the new.* vector */\n  aOld1 = aOldRecord1;\n  aOld2 = aOldRecord2;\n  aNew1 = aNewRecord1;\n  aNew2 = aNewRecord2;\n  for(i=0; i<pTab->nCol; i++){\n    int nOld;\n    u8 *aOld;\n    int nNew;\n    u8 *aNew;\n\n    aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);\n    aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);\n    if( bPatchset==0 \n     && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew))) \n    ){\n      *(aOut++) = '\\0';\n    }else{\n      memcpy(aOut, aNew, nNew);\n      aOut += nNew;\n    }\n  }\n\n  *paOut = aOut;\n  return 1;\n}\n\n/*\n** This function is only called from within a pre-update-hook callback.\n** It determines if the current pre-update-hook change affects the same row\n** as the change stored in argument pChange. If so, it returns true. Otherwise\n** if the pre-update-hook does not affect the same row as pChange, it returns\n** false.\n*/\nstatic int sessionPreupdateEqual(\n  sqlite3_session *pSession,      /* Session object that owns SessionTable */\n  SessionTable *pTab,             /* Table associated with change */\n  SessionChange *pChange,         /* Change to compare to */\n  int op                          /* Current pre-update operation */\n){\n  int iCol;                       /* Used to iterate through columns */\n  u8 *a = pChange->aRecord;       /* Cursor used to scan change record */\n\n  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );\n  for(iCol=0; iCol<pTab->nCol; iCol++){\n    if( !pTab->abPK[iCol] ){\n      a += sessionSerialLen(a);\n    }else{\n      sqlite3_value *pVal;        /* Value returned by preupdate_new/old */\n      int rc;                     /* Error code from preupdate_new/old */\n      int eType = *a++;           /* Type of value from change record */\n\n      /* The following calls to preupdate_new() and preupdate_old() can not\n      ** fail. This is because they cache their return values, and by the\n      ** time control flows to here they have already been called once from\n      ** within sessionPreupdateHash(). The first two asserts below verify\n      ** this (that the method has already been called). */\n      if( op==SQLITE_INSERT ){\n        /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */\n        rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);\n      }else{\n        /* assert( db->pPreUpdate->pUnpacked ); */\n        rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);\n      }\n      assert( rc==SQLITE_OK );\n      if( sqlite3_value_type(pVal)!=eType ) return 0;\n\n      /* A SessionChange object never has a NULL value in a PK column */\n      assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT\n           || eType==SQLITE_BLOB    || eType==SQLITE_TEXT\n      );\n\n      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){\n        i64 iVal = sessionGetI64(a);\n        a += 8;\n        if( eType==SQLITE_INTEGER ){\n          if( sqlite3_value_int64(pVal)!=iVal ) return 0;\n        }else{\n          double rVal;\n          assert( sizeof(iVal)==8 && sizeof(rVal)==8 );\n          memcpy(&rVal, &iVal, 8);\n          if( sqlite3_value_double(pVal)!=rVal ) return 0;\n        }\n      }else{\n        int n;\n        const u8 *z;\n        a += sessionVarintGet(a, &n);\n        if( sqlite3_value_bytes(pVal)!=n ) return 0;\n        if( eType==SQLITE_TEXT ){\n          z = sqlite3_value_text(pVal);\n        }else{\n          z = sqlite3_value_blob(pVal);\n        }\n        if( n>0 && memcmp(a, z, n) ) return 0;\n        a += n;\n      }\n    }\n  }\n\n  return 1;\n}\n\n/*\n** If required, grow the hash table used to store changes on table pTab \n** (part of the session pSession). If a fatal OOM error occurs, set the\n** session object to failed and return SQLITE_ERROR. Otherwise, return\n** SQLITE_OK.\n**\n** It is possible that a non-fatal OOM error occurs in this function. In\n** that case the hash-table does not grow, but SQLITE_OK is returned anyway.\n** Growing the hash table in this case is a performance optimization only,\n** it is not required for correct operation.\n*/\nstatic int sessionGrowHash(int bPatchset, SessionTable *pTab){\n  if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){\n    int i;\n    SessionChange **apNew;\n    sqlite3_int64 nNew = 2*(sqlite3_int64)(pTab->nChange ? pTab->nChange : 128);\n\n    apNew = (SessionChange **)sqlite3_malloc64(sizeof(SessionChange *) * nNew);\n    if( apNew==0 ){\n      if( pTab->nChange==0 ){\n        return SQLITE_ERROR;\n      }\n      return SQLITE_OK;\n    }\n    memset(apNew, 0, sizeof(SessionChange *) * nNew);\n\n    for(i=0; i<pTab->nChange; i++){\n      SessionChange *p;\n      SessionChange *pNext;\n      for(p=pTab->apChange[i]; p; p=pNext){\n        int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);\n        int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);\n        pNext = p->pNext;\n        p->pNext = apNew[iHash];\n        apNew[iHash] = p;\n      }\n    }\n\n    sqlite3_free(pTab->apChange);\n    pTab->nChange = nNew;\n    pTab->apChange = apNew;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** This function queries the database for the names of the columns of table\n** zThis, in schema zDb.\n**\n** Otherwise, if they are not NULL, variable *pnCol is set to the number\n** of columns in the database table and variable *pzTab is set to point to a\n** nul-terminated copy of the table name. *pazCol (if not NULL) is set to\n** point to an array of pointers to column names. And *pabPK (again, if not\n** NULL) is set to point to an array of booleans - true if the corresponding\n** column is part of the primary key.\n**\n** For example, if the table is declared as:\n**\n**     CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));\n**\n** Then the four output variables are populated as follows:\n**\n**     *pnCol  = 4\n**     *pzTab  = \"tbl1\"\n**     *pazCol = {\"w\", \"x\", \"y\", \"z\"}\n**     *pabPK  = {1, 0, 0, 1}\n**\n** All returned buffers are part of the same single allocation, which must\n** be freed using sqlite3_free() by the caller\n*/\nstatic int sessionTableInfo(\n  sqlite3 *db,                    /* Database connection */\n  const char *zDb,                /* Name of attached database (e.g. \"main\") */\n  const char *zThis,              /* Table name */\n  int *pnCol,                     /* OUT: number of columns */\n  const char **pzTab,             /* OUT: Copy of zThis */\n  const char ***pazCol,           /* OUT: Array of column names for table */\n  u8 **pabPK                      /* OUT: Array of booleans - true for PK col */\n){\n  char *zPragma;\n  sqlite3_stmt *pStmt;\n  int rc;\n  sqlite3_int64 nByte;\n  int nDbCol = 0;\n  int nThis;\n  int i;\n  u8 *pAlloc = 0;\n  char **azCol = 0;\n  u8 *abPK = 0;\n\n  assert( pazCol && pabPK );\n\n  nThis = sqlite3Strlen30(zThis);\n  if( nThis==12 && 0==sqlite3_stricmp(\"sqlite_stat1\", zThis) ){\n    rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);\n    if( rc==SQLITE_OK ){\n      /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */\n      zPragma = sqlite3_mprintf(\n          \"SELECT 0, 'tbl',  '', 0, '', 1     UNION ALL \"\n          \"SELECT 1, 'idx',  '', 0, '', 2     UNION ALL \"\n          \"SELECT 2, 'stat', '', 0, '', 0\"\n      );\n    }else if( rc==SQLITE_ERROR ){\n      zPragma = sqlite3_mprintf(\"\");\n    }else{\n      return rc;\n    }\n  }else{\n    zPragma = sqlite3_mprintf(\"PRAGMA '%q'.table_info('%q')\", zDb, zThis);\n  }\n  if( !zPragma ) return SQLITE_NOMEM;\n\n  rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);\n  sqlite3_free(zPragma);\n  if( rc!=SQLITE_OK ) return rc;\n\n  nByte = nThis + 1;\n  while( SQLITE_ROW==sqlite3_step(pStmt) ){\n    nByte += sqlite3_column_bytes(pStmt, 1);\n    nDbCol++;\n  }\n  rc = sqlite3_reset(pStmt);\n\n  if( rc==SQLITE_OK ){\n    nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);\n    pAlloc = sqlite3_malloc64(nByte);\n    if( pAlloc==0 ){\n      rc = SQLITE_NOMEM;\n    }\n  }\n  if( rc==SQLITE_OK ){\n    azCol = (char **)pAlloc;\n    pAlloc = (u8 *)&azCol[nDbCol];\n    abPK = (u8 *)pAlloc;\n    pAlloc = &abPK[nDbCol];\n    if( pzTab ){\n      memcpy(pAlloc, zThis, nThis+1);\n      *pzTab = (char *)pAlloc;\n      pAlloc += nThis+1;\n    }\n  \n    i = 0;\n    while( SQLITE_ROW==sqlite3_step(pStmt) ){\n      int nName = sqlite3_column_bytes(pStmt, 1);\n      const unsigned char *zName = sqlite3_column_text(pStmt, 1);\n      if( zName==0 ) break;\n      memcpy(pAlloc, zName, nName+1);\n      azCol[i] = (char *)pAlloc;\n      pAlloc += nName+1;\n      abPK[i] = sqlite3_column_int(pStmt, 5);\n      i++;\n    }\n    rc = sqlite3_reset(pStmt);\n  \n  }\n\n  /* If successful, populate the output variables. Otherwise, zero them and\n  ** free any allocation made. An error code will be returned in this case.\n  */\n  if( rc==SQLITE_OK ){\n    *pazCol = (const char **)azCol;\n    *pabPK = abPK;\n    *pnCol = nDbCol;\n  }else{\n    *pazCol = 0;\n    *pabPK = 0;\n    *pnCol = 0;\n    if( pzTab ) *pzTab = 0;\n    sqlite3_free(azCol);\n  }\n  sqlite3_finalize(pStmt);\n  return rc;\n}\n\n/*\n** This function is only called from within a pre-update handler for a\n** write to table pTab, part of session pSession. If this is the first\n** write to this table, initalize the SessionTable.nCol, azCol[] and\n** abPK[] arrays accordingly.\n**\n** If an error occurs, an error code is stored in sqlite3_session.rc and\n** non-zero returned. Or, if no error occurs but the table has no primary\n** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to\n** indicate that updates on this table should be ignored. SessionTable.abPK \n** is set to NULL in this case.\n*/\nstatic int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){\n  if( pTab->nCol==0 ){\n    u8 *abPK;\n    assert( pTab->azCol==0 || pTab->abPK==0 );\n    pSession->rc = sessionTableInfo(pSession->db, pSession->zDb, \n        pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK\n    );\n    if( pSession->rc==SQLITE_OK ){\n      int i;\n      for(i=0; i<pTab->nCol; i++){\n        if( abPK[i] ){\n          pTab->abPK = abPK;\n          break;\n        }\n      }\n      if( 0==sqlite3_stricmp(\"sqlite_stat1\", pTab->zName) ){\n        pTab->bStat1 = 1;\n      }\n    }\n  }\n  return (pSession->rc || pTab->abPK==0);\n}\n\n/*\n** Versions of the four methods in object SessionHook for use with the\n** sqlite_stat1 table. The purpose of this is to substitute a zero-length\n** blob each time a NULL value is read from the \"idx\" column of the\n** sqlite_stat1 table.\n*/\ntypedef struct SessionStat1Ctx SessionStat1Ctx;\nstruct SessionStat1Ctx {\n  SessionHook hook;\n  sqlite3_session *pSession;\n};\nstatic int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal){\n  SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;\n  sqlite3_value *pVal = 0;\n  int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal);\n  if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){\n    pVal = p->pSession->pZeroBlob;\n  }\n  *ppVal = pVal;\n  return rc;\n}\nstatic int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal){\n  SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;\n  sqlite3_value *pVal = 0;\n  int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal);\n  if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){\n    pVal = p->pSession->pZeroBlob;\n  }\n  *ppVal = pVal;\n  return rc;\n}\nstatic int sessionStat1Count(void *pCtx){\n  SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;\n  return p->hook.xCount(p->hook.pCtx);\n}\nstatic int sessionStat1Depth(void *pCtx){\n  SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;\n  return p->hook.xDepth(p->hook.pCtx);\n}\n\n\n/*\n** This function is only called from with a pre-update-hook reporting a \n** change on table pTab (attached to session pSession). The type of change\n** (UPDATE, INSERT, DELETE) is specified by the first argument.\n**\n** Unless one is already present or an error occurs, an entry is added\n** to the changed-rows hash table associated with table pTab.\n*/\nstatic void sessionPreupdateOneChange(\n  int op,                         /* One of SQLITE_UPDATE, INSERT, DELETE */\n  sqlite3_session *pSession,      /* Session object pTab is attached to */\n  SessionTable *pTab              /* Table that change applies to */\n){\n  int iHash; \n  int bNull = 0; \n  int rc = SQLITE_OK;\n  SessionStat1Ctx stat1 = {{0,0,0,0,0},0};\n\n  if( pSession->rc ) return;\n\n  /* Load table details if required */\n  if( sessionInitTable(pSession, pTab) ) return;\n\n  /* Check the number of columns in this xPreUpdate call matches the \n  ** number of columns in the table.  */\n  if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){\n    pSession->rc = SQLITE_SCHEMA;\n    return;\n  }\n\n  /* Grow the hash table if required */\n  if( sessionGrowHash(0, pTab) ){\n    pSession->rc = SQLITE_NOMEM;\n    return;\n  }\n\n  if( pTab->bStat1 ){\n    stat1.hook = pSession->hook;\n    stat1.pSession = pSession;\n    pSession->hook.pCtx = (void*)&stat1;\n    pSession->hook.xNew = sessionStat1New;\n    pSession->hook.xOld = sessionStat1Old;\n    pSession->hook.xCount = sessionStat1Count;\n    pSession->hook.xDepth = sessionStat1Depth;\n    if( pSession->pZeroBlob==0 ){\n      sqlite3_value *p = sqlite3ValueNew(0);\n      if( p==0 ){\n        rc = SQLITE_NOMEM;\n        goto error_out;\n      }\n      sqlite3ValueSetStr(p, 0, \"\", 0, SQLITE_STATIC);\n      pSession->pZeroBlob = p;\n    }\n  }\n\n  /* Calculate the hash-key for this change. If the primary key of the row\n  ** includes a NULL value, exit early. Such changes are ignored by the\n  ** session module. */\n  rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);\n  if( rc!=SQLITE_OK ) goto error_out;\n\n  if( bNull==0 ){\n    /* Search the hash table for an existing record for this row. */\n    SessionChange *pC;\n    for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){\n      if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;\n    }\n\n    if( pC==0 ){\n      /* Create a new change object containing all the old values (if\n      ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK\n      ** values (if this is an INSERT). */\n      SessionChange *pChange; /* New change object */\n      sqlite3_int64 nByte;    /* Number of bytes to allocate */\n      int i;                  /* Used to iterate through columns */\n  \n      assert( rc==SQLITE_OK );\n      pTab->nEntry++;\n  \n      /* Figure out how large an allocation is required */\n      nByte = sizeof(SessionChange);\n      for(i=0; i<pTab->nCol; i++){\n        sqlite3_value *p = 0;\n        if( op!=SQLITE_INSERT ){\n          TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);\n          assert( trc==SQLITE_OK );\n        }else if( pTab->abPK[i] ){\n          TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);\n          assert( trc==SQLITE_OK );\n        }\n\n        /* This may fail if SQLite value p contains a utf-16 string that must\n        ** be converted to utf-8 and an OOM error occurs while doing so. */\n        rc = sessionSerializeValue(0, p, &nByte);\n        if( rc!=SQLITE_OK ) goto error_out;\n      }\n  \n      /* Allocate the change object */\n      pChange = (SessionChange *)sqlite3_malloc64(nByte);\n      if( !pChange ){\n        rc = SQLITE_NOMEM;\n        goto error_out;\n      }else{\n        memset(pChange, 0, sizeof(SessionChange));\n        pChange->aRecord = (u8 *)&pChange[1];\n      }\n  \n      /* Populate the change object. None of the preupdate_old(),\n      ** preupdate_new() or SerializeValue() calls below may fail as all\n      ** required values and encodings have already been cached in memory.\n      ** It is not possible for an OOM to occur in this block. */\n      nByte = 0;\n      for(i=0; i<pTab->nCol; i++){\n        sqlite3_value *p = 0;\n        if( op!=SQLITE_INSERT ){\n          pSession->hook.xOld(pSession->hook.pCtx, i, &p);\n        }else if( pTab->abPK[i] ){\n          pSession->hook.xNew(pSession->hook.pCtx, i, &p);\n        }\n        sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);\n      }\n\n      /* Add the change to the hash-table */\n      if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){\n        pChange->bIndirect = 1;\n      }\n      pChange->nRecord = nByte;\n      pChange->op = op;\n      pChange->pNext = pTab->apChange[iHash];\n      pTab->apChange[iHash] = pChange;\n\n    }else if( pC->bIndirect ){\n      /* If the existing change is considered \"indirect\", but this current\n      ** change is \"direct\", mark the change object as direct. */\n      if( pSession->hook.xDepth(pSession->hook.pCtx)==0 \n       && pSession->bIndirect==0 \n      ){\n        pC->bIndirect = 0;\n      }\n    }\n  }\n\n  /* If an error has occurred, mark the session object as failed. */\n error_out:\n  if( pTab->bStat1 ){\n    pSession->hook = stat1.hook;\n  }\n  if( rc!=SQLITE_OK ){\n    pSession->rc = rc;\n  }\n}\n\nstatic int sessionFindTable(\n  sqlite3_session *pSession, \n  const char *zName,\n  SessionTable **ppTab\n){\n  int rc = SQLITE_OK;\n  int nName = sqlite3Strlen30(zName);\n  SessionTable *pRet;\n\n  /* Search for an existing table */\n  for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){\n    if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;\n  }\n\n  if( pRet==0 && pSession->bAutoAttach ){\n    /* If there is a table-filter configured, invoke it. If it returns 0,\n    ** do not automatically add the new table. */\n    if( pSession->xTableFilter==0\n     || pSession->xTableFilter(pSession->pFilterCtx, zName) \n    ){\n      rc = sqlite3session_attach(pSession, zName);\n      if( rc==SQLITE_OK ){\n        for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);\n        assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );\n      }\n    }\n  }\n\n  assert( rc==SQLITE_OK || pRet==0 );\n  *ppTab = pRet;\n  return rc;\n}\n\n/*\n** The 'pre-update' hook registered by this module with SQLite databases.\n*/\nstatic void xPreUpdate(\n  void *pCtx,                     /* Copy of third arg to preupdate_hook() */\n  sqlite3 *db,                    /* Database handle */\n  int op,                         /* SQLITE_UPDATE, DELETE or INSERT */\n  char const *zDb,                /* Database name */\n  char const *zName,              /* Table name */\n  sqlite3_int64 iKey1,            /* Rowid of row about to be deleted/updated */\n  sqlite3_int64 iKey2             /* New rowid value (for a rowid UPDATE) */\n){\n  sqlite3_session *pSession;\n  int nDb = sqlite3Strlen30(zDb);\n\n  assert( sqlite3_mutex_held(db->mutex) );\n\n  for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){\n    SessionTable *pTab;\n\n    /* If this session is attached to a different database (\"main\", \"temp\" \n    ** etc.), or if it is not currently enabled, there is nothing to do. Skip \n    ** to the next session object attached to this database. */\n    if( pSession->bEnable==0 ) continue;\n    if( pSession->rc ) continue;\n    if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;\n\n    pSession->rc = sessionFindTable(pSession, zName, &pTab);\n    if( pTab ){\n      assert( pSession->rc==SQLITE_OK );\n      sessionPreupdateOneChange(op, pSession, pTab);\n      if( op==SQLITE_UPDATE ){\n        sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);\n      }\n    }\n  }\n}\n\n/*\n** The pre-update hook implementations.\n*/\nstatic int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){\n  return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);\n}\nstatic int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){\n  return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);\n}\nstatic int sessionPreupdateCount(void *pCtx){\n  return sqlite3_preupdate_count((sqlite3*)pCtx);\n}\nstatic int sessionPreupdateDepth(void *pCtx){\n  return sqlite3_preupdate_depth((sqlite3*)pCtx);\n}\n\n/*\n** Install the pre-update hooks on the session object passed as the only\n** argument.\n*/\nstatic void sessionPreupdateHooks(\n  sqlite3_session *pSession\n){\n  pSession->hook.pCtx = (void*)pSession->db;\n  pSession->hook.xOld = sessionPreupdateOld;\n  pSession->hook.xNew = sessionPreupdateNew;\n  pSession->hook.xCount = sessionPreupdateCount;\n  pSession->hook.xDepth = sessionPreupdateDepth;\n}\n\ntypedef struct SessionDiffCtx SessionDiffCtx;\nstruct SessionDiffCtx {\n  sqlite3_stmt *pStmt;\n  int nOldOff;\n};\n\n/*\n** The diff hook implementations.\n*/\nstatic int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){\n  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;\n  *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);\n  return SQLITE_OK;\n}\nstatic int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){\n  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;\n  *ppVal = sqlite3_column_value(p->pStmt, iVal);\n   return SQLITE_OK;\n}\nstatic int sessionDiffCount(void *pCtx){\n  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;\n  return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);\n}\nstatic int sessionDiffDepth(void *pCtx){\n  return 0;\n}\n\n/*\n** Install the diff hooks on the session object passed as the only\n** argument.\n*/\nstatic void sessionDiffHooks(\n  sqlite3_session *pSession,\n  SessionDiffCtx *pDiffCtx\n){\n  pSession->hook.pCtx = (void*)pDiffCtx;\n  pSession->hook.xOld = sessionDiffOld;\n  pSession->hook.xNew = sessionDiffNew;\n  pSession->hook.xCount = sessionDiffCount;\n  pSession->hook.xDepth = sessionDiffDepth;\n}\n\nstatic char *sessionExprComparePK(\n  int nCol,\n  const char *zDb1, const char *zDb2, \n  const char *zTab,\n  const char **azCol, u8 *abPK\n){\n  int i;\n  const char *zSep = \"\";\n  char *zRet = 0;\n\n  for(i=0; i<nCol; i++){\n    if( abPK[i] ){\n      zRet = sqlite3_mprintf(\"%z%s\\\"%w\\\".\\\"%w\\\".\\\"%w\\\"=\\\"%w\\\".\\\"%w\\\".\\\"%w\\\"\",\n          zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]\n      );\n      zSep = \" AND \";\n      if( zRet==0 ) break;\n    }\n  }\n\n  return zRet;\n}\n\nstatic char *sessionExprCompareOther(\n  int nCol,\n  const char *zDb1, const char *zDb2, \n  const char *zTab,\n  const char **azCol, u8 *abPK\n){\n  int i;\n  const char *zSep = \"\";\n  char *zRet = 0;\n  int bHave = 0;\n\n  for(i=0; i<nCol; i++){\n    if( abPK[i]==0 ){\n      bHave = 1;\n      zRet = sqlite3_mprintf(\n          \"%z%s\\\"%w\\\".\\\"%w\\\".\\\"%w\\\" IS NOT \\\"%w\\\".\\\"%w\\\".\\\"%w\\\"\",\n          zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]\n      );\n      zSep = \" OR \";\n      if( zRet==0 ) break;\n    }\n  }\n\n  if( bHave==0 ){\n    assert( zRet==0 );\n    zRet = sqlite3_mprintf(\"0\");\n  }\n\n  return zRet;\n}\n\nstatic char *sessionSelectFindNew(\n  int nCol,\n  const char *zDb1,      /* Pick rows in this db only */\n  const char *zDb2,      /* But not in this one */\n  const char *zTbl,      /* Table name */\n  const char *zExpr\n){\n  char *zRet = sqlite3_mprintf(\n      \"SELECT * FROM \\\"%w\\\".\\\"%w\\\" WHERE NOT EXISTS (\"\n      \"  SELECT 1 FROM \\\"%w\\\".\\\"%w\\\" WHERE %s\"\n      \")\",\n      zDb1, zTbl, zDb2, zTbl, zExpr\n  );\n  return zRet;\n}\n\nstatic int sessionDiffFindNew(\n  int op,\n  sqlite3_session *pSession,\n  SessionTable *pTab,\n  const char *zDb1,\n  const char *zDb2,\n  char *zExpr\n){\n  int rc = SQLITE_OK;\n  char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);\n\n  if( zStmt==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    sqlite3_stmt *pStmt;\n    rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);\n    if( rc==SQLITE_OK ){\n      SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;\n      pDiffCtx->pStmt = pStmt;\n      pDiffCtx->nOldOff = 0;\n      while( SQLITE_ROW==sqlite3_step(pStmt) ){\n        sessionPreupdateOneChange(op, pSession, pTab);\n      }\n      rc = sqlite3_finalize(pStmt);\n    }\n    sqlite3_free(zStmt);\n  }\n\n  return rc;\n}\n\nstatic int sessionDiffFindModified(\n  sqlite3_session *pSession, \n  SessionTable *pTab, \n  const char *zFrom, \n  const char *zExpr\n){\n  int rc = SQLITE_OK;\n\n  char *zExpr2 = sessionExprCompareOther(pTab->nCol,\n      pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK\n  );\n  if( zExpr2==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    char *zStmt = sqlite3_mprintf(\n        \"SELECT * FROM \\\"%w\\\".\\\"%w\\\", \\\"%w\\\".\\\"%w\\\" WHERE %s AND (%z)\",\n        pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2\n    );\n    if( zStmt==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      sqlite3_stmt *pStmt;\n      rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);\n\n      if( rc==SQLITE_OK ){\n        SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;\n        pDiffCtx->pStmt = pStmt;\n        pDiffCtx->nOldOff = pTab->nCol;\n        while( SQLITE_ROW==sqlite3_step(pStmt) ){\n          sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);\n        }\n        rc = sqlite3_finalize(pStmt);\n      }\n      sqlite3_free(zStmt);\n    }\n  }\n\n  return rc;\n}\n\nSQLITE_API int sqlite3session_diff(\n  sqlite3_session *pSession,\n  const char *zFrom,\n  const char *zTbl,\n  char **pzErrMsg\n){\n  const char *zDb = pSession->zDb;\n  int rc = pSession->rc;\n  SessionDiffCtx d;\n\n  memset(&d, 0, sizeof(d));\n  sessionDiffHooks(pSession, &d);\n\n  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));\n  if( pzErrMsg ) *pzErrMsg = 0;\n  if( rc==SQLITE_OK ){\n    char *zExpr = 0;\n    sqlite3 *db = pSession->db;\n    SessionTable *pTo;            /* Table zTbl */\n\n    /* Locate and if necessary initialize the target table object */\n    rc = sessionFindTable(pSession, zTbl, &pTo);\n    if( pTo==0 ) goto diff_out;\n    if( sessionInitTable(pSession, pTo) ){\n      rc = pSession->rc;\n      goto diff_out;\n    }\n\n    /* Check the table schemas match */\n    if( rc==SQLITE_OK ){\n      int bHasPk = 0;\n      int bMismatch = 0;\n      int nCol;                   /* Columns in zFrom.zTbl */\n      u8 *abPK;\n      const char **azCol = 0;\n      rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);\n      if( rc==SQLITE_OK ){\n        if( pTo->nCol!=nCol ){\n          bMismatch = 1;\n        }else{\n          int i;\n          for(i=0; i<nCol; i++){\n            if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;\n            if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;\n            if( abPK[i] ) bHasPk = 1;\n          }\n        }\n      }\n      sqlite3_free((char*)azCol);\n      if( bMismatch ){\n        if( pzErrMsg ){\n          *pzErrMsg = sqlite3_mprintf(\"table schemas do not match\");\n        }\n        rc = SQLITE_SCHEMA;\n      }\n      if( bHasPk==0 ){\n        /* Ignore tables with no primary keys */\n        goto diff_out;\n      }\n    }\n\n    if( rc==SQLITE_OK ){\n      zExpr = sessionExprComparePK(pTo->nCol, \n          zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK\n      );\n    }\n\n    /* Find new rows */\n    if( rc==SQLITE_OK ){\n      rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);\n    }\n\n    /* Find old rows */\n    if( rc==SQLITE_OK ){\n      rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);\n    }\n\n    /* Find modified rows */\n    if( rc==SQLITE_OK ){\n      rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);\n    }\n\n    sqlite3_free(zExpr);\n  }\n\n diff_out:\n  sessionPreupdateHooks(pSession);\n  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));\n  return rc;\n}\n\n/*\n** Create a session object. This session object will record changes to\n** database zDb attached to connection db.\n*/\nSQLITE_API int sqlite3session_create(\n  sqlite3 *db,                    /* Database handle */\n  const char *zDb,                /* Name of db (e.g. \"main\") */\n  sqlite3_session **ppSession     /* OUT: New session object */\n){\n  sqlite3_session *pNew;          /* Newly allocated session object */\n  sqlite3_session *pOld;          /* Session object already attached to db */\n  int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */\n\n  /* Zero the output value in case an error occurs. */\n  *ppSession = 0;\n\n  /* Allocate and populate the new session object. */\n  pNew = (sqlite3_session *)sqlite3_malloc64(sizeof(sqlite3_session) + nDb + 1);\n  if( !pNew ) return SQLITE_NOMEM;\n  memset(pNew, 0, sizeof(sqlite3_session));\n  pNew->db = db;\n  pNew->zDb = (char *)&pNew[1];\n  pNew->bEnable = 1;\n  memcpy(pNew->zDb, zDb, nDb+1);\n  sessionPreupdateHooks(pNew);\n\n  /* Add the new session object to the linked list of session objects \n  ** attached to database handle $db. Do this under the cover of the db\n  ** handle mutex.  */\n  sqlite3_mutex_enter(sqlite3_db_mutex(db));\n  pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);\n  pNew->pNext = pOld;\n  sqlite3_mutex_leave(sqlite3_db_mutex(db));\n\n  *ppSession = pNew;\n  return SQLITE_OK;\n}\n\n/*\n** Free the list of table objects passed as the first argument. The contents\n** of the changed-rows hash tables are also deleted.\n*/\nstatic void sessionDeleteTable(SessionTable *pList){\n  SessionTable *pNext;\n  SessionTable *pTab;\n\n  for(pTab=pList; pTab; pTab=pNext){\n    int i;\n    pNext = pTab->pNext;\n    for(i=0; i<pTab->nChange; i++){\n      SessionChange *p;\n      SessionChange *pNextChange;\n      for(p=pTab->apChange[i]; p; p=pNextChange){\n        pNextChange = p->pNext;\n        sqlite3_free(p);\n      }\n    }\n    sqlite3_free((char*)pTab->azCol);  /* cast works around VC++ bug */\n    sqlite3_free(pTab->apChange);\n    sqlite3_free(pTab);\n  }\n}\n\n/*\n** Delete a session object previously allocated using sqlite3session_create().\n*/\nSQLITE_API void sqlite3session_delete(sqlite3_session *pSession){\n  sqlite3 *db = pSession->db;\n  sqlite3_session *pHead;\n  sqlite3_session **pp;\n\n  /* Unlink the session from the linked list of sessions attached to the\n  ** database handle. Hold the db mutex while doing so.  */\n  sqlite3_mutex_enter(sqlite3_db_mutex(db));\n  pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);\n  for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){\n    if( (*pp)==pSession ){\n      *pp = (*pp)->pNext;\n      if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);\n      break;\n    }\n  }\n  sqlite3_mutex_leave(sqlite3_db_mutex(db));\n  sqlite3ValueFree(pSession->pZeroBlob);\n\n  /* Delete all attached table objects. And the contents of their \n  ** associated hash-tables. */\n  sessionDeleteTable(pSession->pTable);\n\n  /* Free the session object itself. */\n  sqlite3_free(pSession);\n}\n\n/*\n** Set a table filter on a Session Object.\n*/\nSQLITE_API void sqlite3session_table_filter(\n  sqlite3_session *pSession, \n  int(*xFilter)(void*, const char*),\n  void *pCtx                      /* First argument passed to xFilter */\n){\n  pSession->bAutoAttach = 1;\n  pSession->pFilterCtx = pCtx;\n  pSession->xTableFilter = xFilter;\n}\n\n/*\n** Attach a table to a session. All subsequent changes made to the table\n** while the session object is enabled will be recorded.\n**\n** Only tables that have a PRIMARY KEY defined may be attached. It does\n** not matter if the PRIMARY KEY is an \"INTEGER PRIMARY KEY\" (rowid alias)\n** or not.\n*/\nSQLITE_API int sqlite3session_attach(\n  sqlite3_session *pSession,      /* Session object */\n  const char *zName               /* Table name */\n){\n  int rc = SQLITE_OK;\n  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));\n\n  if( !zName ){\n    pSession->bAutoAttach = 1;\n  }else{\n    SessionTable *pTab;           /* New table object (if required) */\n    int nName;                    /* Number of bytes in string zName */\n\n    /* First search for an existing entry. If one is found, this call is\n    ** a no-op. Return early. */\n    nName = sqlite3Strlen30(zName);\n    for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){\n      if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;\n    }\n\n    if( !pTab ){\n      /* Allocate new SessionTable object. */\n      pTab = (SessionTable *)sqlite3_malloc64(sizeof(SessionTable) + nName + 1);\n      if( !pTab ){\n        rc = SQLITE_NOMEM;\n      }else{\n        /* Populate the new SessionTable object and link it into the list.\n        ** The new object must be linked onto the end of the list, not \n        ** simply added to the start of it in order to ensure that tables\n        ** appear in the correct order when a changeset or patchset is\n        ** eventually generated. */\n        SessionTable **ppTab;\n        memset(pTab, 0, sizeof(SessionTable));\n        pTab->zName = (char *)&pTab[1];\n        memcpy(pTab->zName, zName, nName+1);\n        for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);\n        *ppTab = pTab;\n      }\n    }\n  }\n\n  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));\n  return rc;\n}\n\n/*\n** Ensure that there is room in the buffer to append nByte bytes of data.\n** If not, use sqlite3_realloc() to grow the buffer so that there is.\n**\n** If successful, return zero. Otherwise, if an OOM condition is encountered,\n** set *pRc to SQLITE_NOMEM and return non-zero.\n*/\nstatic int sessionBufferGrow(SessionBuffer *p, size_t nByte, int *pRc){\n  if( *pRc==SQLITE_OK && (size_t)(p->nAlloc-p->nBuf)<nByte ){\n    u8 *aNew;\n    i64 nNew = p->nAlloc ? p->nAlloc : 128;\n    do {\n      nNew = nNew*2;\n    }while( (size_t)(nNew-p->nBuf)<nByte );\n\n    aNew = (u8 *)sqlite3_realloc64(p->aBuf, nNew);\n    if( 0==aNew ){\n      *pRc = SQLITE_NOMEM;\n    }else{\n      p->aBuf = aNew;\n      p->nAlloc = nNew;\n    }\n  }\n  return (*pRc!=SQLITE_OK);\n}\n\n/*\n** Append the value passed as the second argument to the buffer passed\n** as the first.\n**\n** This function is a no-op if *pRc is non-zero when it is called.\n** Otherwise, if an error occurs, *pRc is set to an SQLite error code\n** before returning.\n*/\nstatic void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){\n  int rc = *pRc;\n  if( rc==SQLITE_OK ){\n    sqlite3_int64 nByte = 0;\n    rc = sessionSerializeValue(0, pVal, &nByte);\n    sessionBufferGrow(p, nByte, &rc);\n    if( rc==SQLITE_OK ){\n      rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);\n      p->nBuf += nByte;\n    }else{\n      *pRc = rc;\n    }\n  }\n}\n\n/*\n** This function is a no-op if *pRc is other than SQLITE_OK when it is \n** called. Otherwise, append a single byte to the buffer. \n**\n** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before\n** returning.\n*/\nstatic void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){\n  if( 0==sessionBufferGrow(p, 1, pRc) ){\n    p->aBuf[p->nBuf++] = v;\n  }\n}\n\n/*\n** This function is a no-op if *pRc is other than SQLITE_OK when it is \n** called. Otherwise, append a single varint to the buffer. \n**\n** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before\n** returning.\n*/\nstatic void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){\n  if( 0==sessionBufferGrow(p, 9, pRc) ){\n    p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);\n  }\n}\n\n/*\n** This function is a no-op if *pRc is other than SQLITE_OK when it is \n** called. Otherwise, append a blob of data to the buffer. \n**\n** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before\n** returning.\n*/\nstatic void sessionAppendBlob(\n  SessionBuffer *p, \n  const u8 *aBlob, \n  int nBlob, \n  int *pRc\n){\n  if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){\n    memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);\n    p->nBuf += nBlob;\n  }\n}\n\n/*\n** This function is a no-op if *pRc is other than SQLITE_OK when it is \n** called. Otherwise, append a string to the buffer. All bytes in the string\n** up to (but not including) the nul-terminator are written to the buffer.\n**\n** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before\n** returning.\n*/\nstatic void sessionAppendStr(\n  SessionBuffer *p, \n  const char *zStr, \n  int *pRc\n){\n  int nStr = sqlite3Strlen30(zStr);\n  if( 0==sessionBufferGrow(p, nStr, pRc) ){\n    memcpy(&p->aBuf[p->nBuf], zStr, nStr);\n    p->nBuf += nStr;\n  }\n}\n\n/*\n** This function is a no-op if *pRc is other than SQLITE_OK when it is \n** called. Otherwise, append the string representation of integer iVal\n** to the buffer. No nul-terminator is written.\n**\n** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before\n** returning.\n*/\nstatic void sessionAppendInteger(\n  SessionBuffer *p,               /* Buffer to append to */\n  int iVal,                       /* Value to write the string rep. of */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  char aBuf[24];\n  sqlite3_snprintf(sizeof(aBuf)-1, aBuf, \"%d\", iVal);\n  sessionAppendStr(p, aBuf, pRc);\n}\n\n/*\n** This function is a no-op if *pRc is other than SQLITE_OK when it is \n** called. Otherwise, append the string zStr enclosed in quotes (\") and\n** with any embedded quote characters escaped to the buffer. No \n** nul-terminator byte is written.\n**\n** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before\n** returning.\n*/\nstatic void sessionAppendIdent(\n  SessionBuffer *p,               /* Buffer to a append to */\n  const char *zStr,               /* String to quote, escape and append */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;\n  if( 0==sessionBufferGrow(p, nStr, pRc) ){\n    char *zOut = (char *)&p->aBuf[p->nBuf];\n    const char *zIn = zStr;\n    *zOut++ = '\"';\n    while( *zIn ){\n      if( *zIn=='\"' ) *zOut++ = '\"';\n      *zOut++ = *(zIn++);\n    }\n    *zOut++ = '\"';\n    p->nBuf = (int)((u8 *)zOut - p->aBuf);\n  }\n}\n\n/*\n** This function is a no-op if *pRc is other than SQLITE_OK when it is\n** called. Otherwse, it appends the serialized version of the value stored\n** in column iCol of the row that SQL statement pStmt currently points\n** to to the buffer.\n*/\nstatic void sessionAppendCol(\n  SessionBuffer *p,               /* Buffer to append to */\n  sqlite3_stmt *pStmt,            /* Handle pointing to row containing value */\n  int iCol,                       /* Column to read value from */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  if( *pRc==SQLITE_OK ){\n    int eType = sqlite3_column_type(pStmt, iCol);\n    sessionAppendByte(p, (u8)eType, pRc);\n    if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){\n      sqlite3_int64 i;\n      u8 aBuf[8];\n      if( eType==SQLITE_INTEGER ){\n        i = sqlite3_column_int64(pStmt, iCol);\n      }else{\n        double r = sqlite3_column_double(pStmt, iCol);\n        memcpy(&i, &r, 8);\n      }\n      sessionPutI64(aBuf, i);\n      sessionAppendBlob(p, aBuf, 8, pRc);\n    }\n    if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){\n      u8 *z;\n      int nByte;\n      if( eType==SQLITE_BLOB ){\n        z = (u8 *)sqlite3_column_blob(pStmt, iCol);\n      }else{\n        z = (u8 *)sqlite3_column_text(pStmt, iCol);\n      }\n      nByte = sqlite3_column_bytes(pStmt, iCol);\n      if( z || (eType==SQLITE_BLOB && nByte==0) ){\n        sessionAppendVarint(p, nByte, pRc);\n        sessionAppendBlob(p, z, nByte, pRc);\n      }else{\n        *pRc = SQLITE_NOMEM;\n      }\n    }\n  }\n}\n\n/*\n**\n** This function appends an update change to the buffer (see the comments \n** under \"CHANGESET FORMAT\" at the top of the file). An update change \n** consists of:\n**\n**   1 byte:  SQLITE_UPDATE (0x17)\n**   n bytes: old.* record (see RECORD FORMAT)\n**   m bytes: new.* record (see RECORD FORMAT)\n**\n** The SessionChange object passed as the third argument contains the\n** values that were stored in the row when the session began (the old.*\n** values). The statement handle passed as the second argument points\n** at the current version of the row (the new.* values).\n**\n** If all of the old.* values are equal to their corresponding new.* value\n** (i.e. nothing has changed), then no data at all is appended to the buffer.\n**\n** Otherwise, the old.* record contains all primary key values and the \n** original values of any fields that have been modified. The new.* record \n** contains the new values of only those fields that have been modified.\n*/ \nstatic int sessionAppendUpdate(\n  SessionBuffer *pBuf,            /* Buffer to append to */\n  int bPatchset,                  /* True for \"patchset\", 0 for \"changeset\" */\n  sqlite3_stmt *pStmt,            /* Statement handle pointing at new row */\n  SessionChange *p,               /* Object containing old values */\n  u8 *abPK                        /* Boolean array - true for PK columns */\n){\n  int rc = SQLITE_OK;\n  SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */\n  int bNoop = 1;                /* Set to zero if any values are modified */\n  int nRewind = pBuf->nBuf;     /* Set to zero if any values are modified */\n  int i;                        /* Used to iterate through columns */\n  u8 *pCsr = p->aRecord;        /* Used to iterate through old.* values */\n\n  sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);\n  sessionAppendByte(pBuf, p->bIndirect, &rc);\n  for(i=0; i<sqlite3_column_count(pStmt); i++){\n    int bChanged = 0;\n    int nAdvance;\n    int eType = *pCsr;\n    switch( eType ){\n      case SQLITE_NULL:\n        nAdvance = 1;\n        if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){\n          bChanged = 1;\n        }\n        break;\n\n      case SQLITE_FLOAT:\n      case SQLITE_INTEGER: {\n        nAdvance = 9;\n        if( eType==sqlite3_column_type(pStmt, i) ){\n          sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);\n          if( eType==SQLITE_INTEGER ){\n            if( iVal==sqlite3_column_int64(pStmt, i) ) break;\n          }else{\n            double dVal;\n            memcpy(&dVal, &iVal, 8);\n            if( dVal==sqlite3_column_double(pStmt, i) ) break;\n          }\n        }\n        bChanged = 1;\n        break;\n      }\n\n      default: {\n        int n;\n        int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);\n        assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );\n        nAdvance = nHdr + n;\n        if( eType==sqlite3_column_type(pStmt, i) \n         && n==sqlite3_column_bytes(pStmt, i) \n         && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))\n        ){\n          break;\n        }\n        bChanged = 1;\n      }\n    }\n\n    /* If at least one field has been modified, this is not a no-op. */\n    if( bChanged ) bNoop = 0;\n\n    /* Add a field to the old.* record. This is omitted if this modules is\n    ** currently generating a patchset. */\n    if( bPatchset==0 ){\n      if( bChanged || abPK[i] ){\n        sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);\n      }else{\n        sessionAppendByte(pBuf, 0, &rc);\n      }\n    }\n\n    /* Add a field to the new.* record. Or the only record if currently\n    ** generating a patchset.  */\n    if( bChanged || (bPatchset && abPK[i]) ){\n      sessionAppendCol(&buf2, pStmt, i, &rc);\n    }else{\n      sessionAppendByte(&buf2, 0, &rc);\n    }\n\n    pCsr += nAdvance;\n  }\n\n  if( bNoop ){\n    pBuf->nBuf = nRewind;\n  }else{\n    sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);\n  }\n  sqlite3_free(buf2.aBuf);\n\n  return rc;\n}\n\n/*\n** Append a DELETE change to the buffer passed as the first argument. Use\n** the changeset format if argument bPatchset is zero, or the patchset\n** format otherwise.\n*/\nstatic int sessionAppendDelete(\n  SessionBuffer *pBuf,            /* Buffer to append to */\n  int bPatchset,                  /* True for \"patchset\", 0 for \"changeset\" */\n  SessionChange *p,               /* Object containing old values */\n  int nCol,                       /* Number of columns in table */\n  u8 *abPK                        /* Boolean array - true for PK columns */\n){\n  int rc = SQLITE_OK;\n\n  sessionAppendByte(pBuf, SQLITE_DELETE, &rc);\n  sessionAppendByte(pBuf, p->bIndirect, &rc);\n\n  if( bPatchset==0 ){\n    sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);\n  }else{\n    int i;\n    u8 *a = p->aRecord;\n    for(i=0; i<nCol; i++){\n      u8 *pStart = a;\n      int eType = *a++;\n\n      switch( eType ){\n        case 0:\n        case SQLITE_NULL:\n          assert( abPK[i]==0 );\n          break;\n\n        case SQLITE_FLOAT:\n        case SQLITE_INTEGER:\n          a += 8;\n          break;\n\n        default: {\n          int n;\n          a += sessionVarintGet(a, &n);\n          a += n;\n          break;\n        }\n      }\n      if( abPK[i] ){\n        sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);\n      }\n    }\n    assert( (a - p->aRecord)==p->nRecord );\n  }\n\n  return rc;\n}\n\n/*\n** Formulate and prepare a SELECT statement to retrieve a row from table\n** zTab in database zDb based on its primary key. i.e.\n**\n**   SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...\n*/\nstatic int sessionSelectStmt(\n  sqlite3 *db,                    /* Database handle */\n  const char *zDb,                /* Database name */\n  const char *zTab,               /* Table name */\n  int nCol,                       /* Number of columns in table */\n  const char **azCol,             /* Names of table columns */\n  u8 *abPK,                       /* PRIMARY KEY  array */\n  sqlite3_stmt **ppStmt           /* OUT: Prepared SELECT statement */\n){\n  int rc = SQLITE_OK;\n  char *zSql = 0;\n  int nSql = -1;\n\n  if( 0==sqlite3_stricmp(\"sqlite_stat1\", zTab) ){\n    zSql = sqlite3_mprintf(\n        \"SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND \"\n        \"idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)\", zDb\n    );\n    if( zSql==0 ) rc = SQLITE_NOMEM;\n  }else{\n    int i;\n    const char *zSep = \"\";\n    SessionBuffer buf = {0, 0, 0};\n\n    sessionAppendStr(&buf, \"SELECT * FROM \", &rc);\n    sessionAppendIdent(&buf, zDb, &rc);\n    sessionAppendStr(&buf, \".\", &rc);\n    sessionAppendIdent(&buf, zTab, &rc);\n    sessionAppendStr(&buf, \" WHERE \", &rc);\n    for(i=0; i<nCol; i++){\n      if( abPK[i] ){\n        sessionAppendStr(&buf, zSep, &rc);\n        sessionAppendIdent(&buf, azCol[i], &rc);\n        sessionAppendStr(&buf, \" IS ?\", &rc);\n        sessionAppendInteger(&buf, i+1, &rc);\n        zSep = \" AND \";\n      }\n    }\n    zSql = (char*)buf.aBuf;\n    nSql = buf.nBuf;\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);\n  }\n  sqlite3_free(zSql);\n  return rc;\n}\n\n/*\n** Bind the PRIMARY KEY values from the change passed in argument pChange\n** to the SELECT statement passed as the first argument. The SELECT statement\n** is as prepared by function sessionSelectStmt().\n**\n** Return SQLITE_OK if all PK values are successfully bound, or an SQLite\n** error code (e.g. SQLITE_NOMEM) otherwise.\n*/\nstatic int sessionSelectBind(\n  sqlite3_stmt *pSelect,          /* SELECT from sessionSelectStmt() */\n  int nCol,                       /* Number of columns in table */\n  u8 *abPK,                       /* PRIMARY KEY array */\n  SessionChange *pChange          /* Change structure */\n){\n  int i;\n  int rc = SQLITE_OK;\n  u8 *a = pChange->aRecord;\n\n  for(i=0; i<nCol && rc==SQLITE_OK; i++){\n    int eType = *a++;\n\n    switch( eType ){\n      case 0:\n      case SQLITE_NULL:\n        assert( abPK[i]==0 );\n        break;\n\n      case SQLITE_INTEGER: {\n        if( abPK[i] ){\n          i64 iVal = sessionGetI64(a);\n          rc = sqlite3_bind_int64(pSelect, i+1, iVal);\n        }\n        a += 8;\n        break;\n      }\n\n      case SQLITE_FLOAT: {\n        if( abPK[i] ){\n          double rVal;\n          i64 iVal = sessionGetI64(a);\n          memcpy(&rVal, &iVal, 8);\n          rc = sqlite3_bind_double(pSelect, i+1, rVal);\n        }\n        a += 8;\n        break;\n      }\n\n      case SQLITE_TEXT: {\n        int n;\n        a += sessionVarintGet(a, &n);\n        if( abPK[i] ){\n          rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);\n        }\n        a += n;\n        break;\n      }\n\n      default: {\n        int n;\n        assert( eType==SQLITE_BLOB );\n        a += sessionVarintGet(a, &n);\n        if( abPK[i] ){\n          rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);\n        }\n        a += n;\n        break;\n      }\n    }\n  }\n\n  return rc;\n}\n\n/*\n** This function is a no-op if *pRc is set to other than SQLITE_OK when it\n** is called. Otherwise, append a serialized table header (part of the binary \n** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an\n** SQLite error code before returning.\n*/\nstatic void sessionAppendTableHdr(\n  SessionBuffer *pBuf,            /* Append header to this buffer */\n  int bPatchset,                  /* Use the patchset format if true */\n  SessionTable *pTab,             /* Table object to append header for */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  /* Write a table header */\n  sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);\n  sessionAppendVarint(pBuf, pTab->nCol, pRc);\n  sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);\n  sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);\n}\n\n/*\n** Generate either a changeset (if argument bPatchset is zero) or a patchset\n** (if it is non-zero) based on the current contents of the session object\n** passed as the first argument.\n**\n** If no error occurs, SQLITE_OK is returned and the new changeset/patchset\n** stored in output variables *pnChangeset and *ppChangeset. Or, if an error\n** occurs, an SQLite error code is returned and both output variables set \n** to 0.\n*/\nstatic int sessionGenerateChangeset(\n  sqlite3_session *pSession,      /* Session object */\n  int bPatchset,                  /* True for patchset, false for changeset */\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut,                     /* First argument for xOutput */\n  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */\n  void **ppChangeset              /* OUT: Buffer containing changeset */\n){\n  sqlite3 *db = pSession->db;     /* Source database handle */\n  SessionTable *pTab;             /* Used to iterate through attached tables */\n  SessionBuffer buf = {0,0,0};    /* Buffer in which to accumlate changeset */\n  int rc;                         /* Return code */\n\n  assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );\n\n  /* Zero the output variables in case an error occurs. If this session\n  ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),\n  ** this call will be a no-op.  */\n  if( xOutput==0 ){\n    *pnChangeset = 0;\n    *ppChangeset = 0;\n  }\n\n  if( pSession->rc ) return pSession->rc;\n  rc = sqlite3_exec(pSession->db, \"SAVEPOINT changeset\", 0, 0, 0);\n  if( rc!=SQLITE_OK ) return rc;\n\n  sqlite3_mutex_enter(sqlite3_db_mutex(db));\n\n  for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){\n    if( pTab->nEntry ){\n      const char *zName = pTab->zName;\n      int nCol;                   /* Number of columns in table */\n      u8 *abPK;                   /* Primary key array */\n      const char **azCol = 0;     /* Table columns */\n      int i;                      /* Used to iterate through hash buckets */\n      sqlite3_stmt *pSel = 0;     /* SELECT statement to query table pTab */\n      int nRewind = buf.nBuf;     /* Initial size of write buffer */\n      int nNoop;                  /* Size of buffer after writing tbl header */\n\n      /* Check the table schema is still Ok. */\n      rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);\n      if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){\n        rc = SQLITE_SCHEMA;\n      }\n\n      /* Write a table header */\n      sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);\n\n      /* Build and compile a statement to execute: */\n      if( rc==SQLITE_OK ){\n        rc = sessionSelectStmt(\n            db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);\n      }\n\n      nNoop = buf.nBuf;\n      for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){\n        SessionChange *p;         /* Used to iterate through changes */\n\n        for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){\n          rc = sessionSelectBind(pSel, nCol, abPK, p);\n          if( rc!=SQLITE_OK ) continue;\n          if( sqlite3_step(pSel)==SQLITE_ROW ){\n            if( p->op==SQLITE_INSERT ){\n              int iCol;\n              sessionAppendByte(&buf, SQLITE_INSERT, &rc);\n              sessionAppendByte(&buf, p->bIndirect, &rc);\n              for(iCol=0; iCol<nCol; iCol++){\n                sessionAppendCol(&buf, pSel, iCol, &rc);\n              }\n            }else{\n              rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);\n            }\n          }else if( p->op!=SQLITE_INSERT ){\n            rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);\n          }\n          if( rc==SQLITE_OK ){\n            rc = sqlite3_reset(pSel);\n          }\n\n          /* If the buffer is now larger than sessions_strm_chunk_size, pass\n          ** its contents to the xOutput() callback. */\n          if( xOutput \n           && rc==SQLITE_OK \n           && buf.nBuf>nNoop \n           && buf.nBuf>sessions_strm_chunk_size \n          ){\n            rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);\n            nNoop = -1;\n            buf.nBuf = 0;\n          }\n\n        }\n      }\n\n      sqlite3_finalize(pSel);\n      if( buf.nBuf==nNoop ){\n        buf.nBuf = nRewind;\n      }\n      sqlite3_free((char*)azCol);  /* cast works around VC++ bug */\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    if( xOutput==0 ){\n      *pnChangeset = buf.nBuf;\n      *ppChangeset = buf.aBuf;\n      buf.aBuf = 0;\n    }else if( buf.nBuf>0 ){\n      rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);\n    }\n  }\n\n  sqlite3_free(buf.aBuf);\n  sqlite3_exec(db, \"RELEASE changeset\", 0, 0, 0);\n  sqlite3_mutex_leave(sqlite3_db_mutex(db));\n  return rc;\n}\n\n/*\n** Obtain a changeset object containing all changes recorded by the \n** session object passed as the first argument.\n**\n** It is the responsibility of the caller to eventually free the buffer \n** using sqlite3_free().\n*/\nSQLITE_API int sqlite3session_changeset(\n  sqlite3_session *pSession,      /* Session object */\n  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */\n  void **ppChangeset              /* OUT: Buffer containing changeset */\n){\n  return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);\n}\n\n/*\n** Streaming version of sqlite3session_changeset().\n*/\nSQLITE_API int sqlite3session_changeset_strm(\n  sqlite3_session *pSession,\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut\n){\n  return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);\n}\n\n/*\n** Streaming version of sqlite3session_patchset().\n*/\nSQLITE_API int sqlite3session_patchset_strm(\n  sqlite3_session *pSession,\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut\n){\n  return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);\n}\n\n/*\n** Obtain a patchset object containing all changes recorded by the \n** session object passed as the first argument.\n**\n** It is the responsibility of the caller to eventually free the buffer \n** using sqlite3_free().\n*/\nSQLITE_API int sqlite3session_patchset(\n  sqlite3_session *pSession,      /* Session object */\n  int *pnPatchset,                /* OUT: Size of buffer at *ppChangeset */\n  void **ppPatchset               /* OUT: Buffer containing changeset */\n){\n  return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);\n}\n\n/*\n** Enable or disable the session object passed as the first argument.\n*/\nSQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){\n  int ret;\n  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));\n  if( bEnable>=0 ){\n    pSession->bEnable = bEnable;\n  }\n  ret = pSession->bEnable;\n  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));\n  return ret;\n}\n\n/*\n** Enable or disable the session object passed as the first argument.\n*/\nSQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){\n  int ret;\n  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));\n  if( bIndirect>=0 ){\n    pSession->bIndirect = bIndirect;\n  }\n  ret = pSession->bIndirect;\n  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));\n  return ret;\n}\n\n/*\n** Return true if there have been no changes to monitored tables recorded\n** by the session object passed as the only argument.\n*/\nSQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){\n  int ret = 0;\n  SessionTable *pTab;\n\n  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));\n  for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){\n    ret = (pTab->nEntry>0);\n  }\n  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));\n\n  return (ret==0);\n}\n\n/*\n** Do the work for either sqlite3changeset_start() or start_strm().\n*/\nstatic int sessionChangesetStart(\n  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */\n  int (*xInput)(void *pIn, void *pData, int *pnData),\n  void *pIn,\n  int nChangeset,                 /* Size of buffer pChangeset in bytes */\n  void *pChangeset,               /* Pointer to buffer containing changeset */\n  int bInvert                     /* True to invert changeset */\n){\n  sqlite3_changeset_iter *pRet;   /* Iterator to return */\n  int nByte;                      /* Number of bytes to allocate for iterator */\n\n  assert( xInput==0 || (pChangeset==0 && nChangeset==0) );\n\n  /* Zero the output variable in case an error occurs. */\n  *pp = 0;\n\n  /* Allocate and initialize the iterator structure. */\n  nByte = sizeof(sqlite3_changeset_iter);\n  pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);\n  if( !pRet ) return SQLITE_NOMEM;\n  memset(pRet, 0, sizeof(sqlite3_changeset_iter));\n  pRet->in.aData = (u8 *)pChangeset;\n  pRet->in.nData = nChangeset;\n  pRet->in.xInput = xInput;\n  pRet->in.pIn = pIn;\n  pRet->in.bEof = (xInput ? 0 : 1);\n  pRet->bInvert = bInvert;\n\n  /* Populate the output variable and return success. */\n  *pp = pRet;\n  return SQLITE_OK;\n}\n\n/*\n** Create an iterator used to iterate through the contents of a changeset.\n*/\nSQLITE_API int sqlite3changeset_start(\n  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */\n  int nChangeset,                 /* Size of buffer pChangeset in bytes */\n  void *pChangeset                /* Pointer to buffer containing changeset */\n){\n  return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, 0);\n}\nSQLITE_API int sqlite3changeset_start_v2(\n  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */\n  int nChangeset,                 /* Size of buffer pChangeset in bytes */\n  void *pChangeset,               /* Pointer to buffer containing changeset */\n  int flags\n){\n  int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);\n  return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, bInvert);\n}\n\n/*\n** Streaming version of sqlite3changeset_start().\n*/\nSQLITE_API int sqlite3changeset_start_strm(\n  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */\n  int (*xInput)(void *pIn, void *pData, int *pnData),\n  void *pIn\n){\n  return sessionChangesetStart(pp, xInput, pIn, 0, 0, 0);\n}\nSQLITE_API int sqlite3changeset_start_v2_strm(\n  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */\n  int (*xInput)(void *pIn, void *pData, int *pnData),\n  void *pIn,\n  int flags\n){\n  int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);\n  return sessionChangesetStart(pp, xInput, pIn, 0, 0, bInvert);\n}\n\n/*\n** If the SessionInput object passed as the only argument is a streaming\n** object and the buffer is full, discard some data to free up space.\n*/\nstatic void sessionDiscardData(SessionInput *pIn){\n  if( pIn->xInput && pIn->iNext>=sessions_strm_chunk_size ){\n    int nMove = pIn->buf.nBuf - pIn->iNext;\n    assert( nMove>=0 );\n    if( nMove>0 ){\n      memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);\n    }\n    pIn->buf.nBuf -= pIn->iNext;\n    pIn->iNext = 0;\n    pIn->nData = pIn->buf.nBuf;\n  }\n}\n\n/*\n** Ensure that there are at least nByte bytes available in the buffer. Or,\n** if there are not nByte bytes remaining in the input, that all available\n** data is in the buffer.\n**\n** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.\n*/\nstatic int sessionInputBuffer(SessionInput *pIn, int nByte){\n  int rc = SQLITE_OK;\n  if( pIn->xInput ){\n    while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){\n      int nNew = sessions_strm_chunk_size;\n\n      if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);\n      if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){\n        rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);\n        if( nNew==0 ){\n          pIn->bEof = 1;\n        }else{\n          pIn->buf.nBuf += nNew;\n        }\n      }\n\n      pIn->aData = pIn->buf.aBuf;\n      pIn->nData = pIn->buf.nBuf;\n    }\n  }\n  return rc;\n}\n\n/*\n** When this function is called, *ppRec points to the start of a record\n** that contains nCol values. This function advances the pointer *ppRec\n** until it points to the byte immediately following that record.\n*/\nstatic void sessionSkipRecord(\n  u8 **ppRec,                     /* IN/OUT: Record pointer */\n  int nCol                        /* Number of values in record */\n){\n  u8 *aRec = *ppRec;\n  int i;\n  for(i=0; i<nCol; i++){\n    int eType = *aRec++;\n    if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){\n      int nByte;\n      aRec += sessionVarintGet((u8*)aRec, &nByte);\n      aRec += nByte;\n    }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){\n      aRec += 8;\n    }\n  }\n\n  *ppRec = aRec;\n}\n\n/*\n** This function sets the value of the sqlite3_value object passed as the\n** first argument to a copy of the string or blob held in the aData[] \n** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM\n** error occurs.\n*/\nstatic int sessionValueSetStr(\n  sqlite3_value *pVal,            /* Set the value of this object */\n  u8 *aData,                      /* Buffer containing string or blob data */\n  int nData,                      /* Size of buffer aData[] in bytes */\n  u8 enc                          /* String encoding (0 for blobs) */\n){\n  /* In theory this code could just pass SQLITE_TRANSIENT as the final\n  ** argument to sqlite3ValueSetStr() and have the copy created \n  ** automatically. But doing so makes it difficult to detect any OOM\n  ** error. Hence the code to create the copy externally. */\n  u8 *aCopy = sqlite3_malloc64((sqlite3_int64)nData+1);\n  if( aCopy==0 ) return SQLITE_NOMEM;\n  memcpy(aCopy, aData, nData);\n  sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);\n  return SQLITE_OK;\n}\n\n/*\n** Deserialize a single record from a buffer in memory. See \"RECORD FORMAT\"\n** for details.\n**\n** When this function is called, *paChange points to the start of the record\n** to deserialize. Assuming no error occurs, *paChange is set to point to\n** one byte after the end of the same record before this function returns.\n** If the argument abPK is NULL, then the record contains nCol values. Or,\n** if abPK is other than NULL, then the record contains only the PK fields\n** (in other words, it is a patchset DELETE record).\n**\n** If successful, each element of the apOut[] array (allocated by the caller)\n** is set to point to an sqlite3_value object containing the value read\n** from the corresponding position in the record. If that value is not\n** included in the record (i.e. because the record is part of an UPDATE change\n** and the field was not modified), the corresponding element of apOut[] is\n** set to NULL.\n**\n** It is the responsibility of the caller to free all sqlite_value structures\n** using sqlite3_free().\n**\n** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.\n** The apOut[] array may have been partially populated in this case.\n*/\nstatic int sessionReadRecord(\n  SessionInput *pIn,              /* Input data */\n  int nCol,                       /* Number of values in record */\n  u8 *abPK,                       /* Array of primary key flags, or NULL */\n  sqlite3_value **apOut           /* Write values to this array */\n){\n  int i;                          /* Used to iterate through columns */\n  int rc = SQLITE_OK;\n\n  for(i=0; i<nCol && rc==SQLITE_OK; i++){\n    int eType = 0;                /* Type of value (SQLITE_NULL, TEXT etc.) */\n    if( abPK && abPK[i]==0 ) continue;\n    rc = sessionInputBuffer(pIn, 9);\n    if( rc==SQLITE_OK ){\n      if( pIn->iNext>=pIn->nData ){\n        rc = SQLITE_CORRUPT_BKPT;\n      }else{\n        eType = pIn->aData[pIn->iNext++];\n        assert( apOut[i]==0 );\n        if( eType ){\n          apOut[i] = sqlite3ValueNew(0);\n          if( !apOut[i] ) rc = SQLITE_NOMEM;\n        }\n      }\n    }\n\n    if( rc==SQLITE_OK ){\n      u8 *aVal = &pIn->aData[pIn->iNext];\n      if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){\n        int nByte;\n        pIn->iNext += sessionVarintGet(aVal, &nByte);\n        rc = sessionInputBuffer(pIn, nByte);\n        if( rc==SQLITE_OK ){\n          if( nByte<0 || nByte>pIn->nData-pIn->iNext ){\n            rc = SQLITE_CORRUPT_BKPT;\n          }else{\n            u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);\n            rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);\n            pIn->iNext += nByte;\n          }\n        }\n      }\n      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){\n        sqlite3_int64 v = sessionGetI64(aVal);\n        if( eType==SQLITE_INTEGER ){\n          sqlite3VdbeMemSetInt64(apOut[i], v);\n        }else{\n          double d;\n          memcpy(&d, &v, 8);\n          sqlite3VdbeMemSetDouble(apOut[i], d);\n        }\n        pIn->iNext += 8;\n      }\n    }\n  }\n\n  return rc;\n}\n\n/*\n** The input pointer currently points to the second byte of a table-header.\n** Specifically, to the following:\n**\n**   + number of columns in table (varint)\n**   + array of PK flags (1 byte per column),\n**   + table name (nul terminated).\n**\n** This function ensures that all of the above is present in the input \n** buffer (i.e. that it can be accessed without any calls to xInput()).\n** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.\n** The input pointer is not moved.\n*/\nstatic int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){\n  int rc = SQLITE_OK;\n  int nCol = 0;\n  int nRead = 0;\n\n  rc = sessionInputBuffer(pIn, 9);\n  if( rc==SQLITE_OK ){\n    nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);\n    /* The hard upper limit for the number of columns in an SQLite\n    ** database table is, according to sqliteLimit.h, 32676. So \n    ** consider any table-header that purports to have more than 65536 \n    ** columns to be corrupt. This is convenient because otherwise, \n    ** if the (nCol>65536) condition below were omitted, a sufficiently \n    ** large value for nCol may cause nRead to wrap around and become \n    ** negative. Leading to a crash. */\n    if( nCol<0 || nCol>65536 ){\n      rc = SQLITE_CORRUPT_BKPT;\n    }else{\n      rc = sessionInputBuffer(pIn, nRead+nCol+100);\n      nRead += nCol;\n    }\n  }\n\n  while( rc==SQLITE_OK ){\n    while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){\n      nRead++;\n    }\n    if( (pIn->iNext + nRead)<pIn->nData ) break;\n    rc = sessionInputBuffer(pIn, nRead + 100);\n  }\n  *pnByte = nRead+1;\n  return rc;\n}\n\n/*\n** The input pointer currently points to the first byte of the first field\n** of a record consisting of nCol columns. This function ensures the entire\n** record is buffered. It does not move the input pointer.\n**\n** If successful, SQLITE_OK is returned and *pnByte is set to the size of\n** the record in bytes. Otherwise, an SQLite error code is returned. The\n** final value of *pnByte is undefined in this case.\n*/\nstatic int sessionChangesetBufferRecord(\n  SessionInput *pIn,              /* Input data */\n  int nCol,                       /* Number of columns in record */\n  int *pnByte                     /* OUT: Size of record in bytes */\n){\n  int rc = SQLITE_OK;\n  int nByte = 0;\n  int i;\n  for(i=0; rc==SQLITE_OK && i<nCol; i++){\n    int eType;\n    rc = sessionInputBuffer(pIn, nByte + 10);\n    if( rc==SQLITE_OK ){\n      eType = pIn->aData[pIn->iNext + nByte++];\n      if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){\n        int n;\n        nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);\n        nByte += n;\n        rc = sessionInputBuffer(pIn, nByte);\n      }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){\n        nByte += 8;\n      }\n    }\n  }\n  *pnByte = nByte;\n  return rc;\n}\n\n/*\n** The input pointer currently points to the second byte of a table-header.\n** Specifically, to the following:\n**\n**   + number of columns in table (varint)\n**   + array of PK flags (1 byte per column),\n**   + table name (nul terminated).\n**\n** This function decodes the table-header and populates the p->nCol, \n** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is \n** also allocated or resized according to the new value of p->nCol. The\n** input pointer is left pointing to the byte following the table header.\n**\n** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code\n** is returned and the final values of the various fields enumerated above\n** are undefined.\n*/\nstatic int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){\n  int rc;\n  int nCopy;\n  assert( p->rc==SQLITE_OK );\n\n  rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);\n  if( rc==SQLITE_OK ){\n    int nByte;\n    int nVarint;\n    nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);\n    if( p->nCol>0 ){\n      nCopy -= nVarint;\n      p->in.iNext += nVarint;\n      nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;\n      p->tblhdr.nBuf = 0;\n      sessionBufferGrow(&p->tblhdr, nByte, &rc);\n    }else{\n      rc = SQLITE_CORRUPT_BKPT;\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    size_t iPK = sizeof(sqlite3_value*)*p->nCol*2;\n    memset(p->tblhdr.aBuf, 0, iPK);\n    memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);\n    p->in.iNext += nCopy;\n  }\n\n  p->apValue = (sqlite3_value**)p->tblhdr.aBuf;\n  p->abPK = (u8*)&p->apValue[p->nCol*2];\n  p->zTab = (char*)&p->abPK[p->nCol];\n  return (p->rc = rc);\n}\n\n/*\n** Advance the changeset iterator to the next change.\n**\n** If both paRec and pnRec are NULL, then this function works like the public\n** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the\n** sqlite3changeset_new() and old() APIs may be used to query for values.\n**\n** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change\n** record is written to *paRec before returning and the number of bytes in\n** the record to *pnRec.\n**\n** Either way, this function returns SQLITE_ROW if the iterator is \n** successfully advanced to the next change in the changeset, an SQLite \n** error code if an error occurs, or SQLITE_DONE if there are no further \n** changes in the changeset.\n*/\nstatic int sessionChangesetNext(\n  sqlite3_changeset_iter *p,      /* Changeset iterator */\n  u8 **paRec,                     /* If non-NULL, store record pointer here */\n  int *pnRec,                     /* If non-NULL, store size of record here */\n  int *pbNew                      /* If non-NULL, true if new table */\n){\n  int i;\n  u8 op;\n\n  assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );\n\n  /* If the iterator is in the error-state, return immediately. */\n  if( p->rc!=SQLITE_OK ) return p->rc;\n\n  /* Free the current contents of p->apValue[], if any. */\n  if( p->apValue ){\n    for(i=0; i<p->nCol*2; i++){\n      sqlite3ValueFree(p->apValue[i]);\n    }\n    memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);\n  }\n\n  /* Make sure the buffer contains at least 10 bytes of input data, or all\n  ** remaining data if there are less than 10 bytes available. This is\n  ** sufficient either for the 'T' or 'P' byte and the varint that follows\n  ** it, or for the two single byte values otherwise. */\n  p->rc = sessionInputBuffer(&p->in, 2);\n  if( p->rc!=SQLITE_OK ) return p->rc;\n\n  /* If the iterator is already at the end of the changeset, return DONE. */\n  if( p->in.iNext>=p->in.nData ){\n    return SQLITE_DONE;\n  }\n\n  sessionDiscardData(&p->in);\n  p->in.iCurrent = p->in.iNext;\n\n  op = p->in.aData[p->in.iNext++];\n  while( op=='T' || op=='P' ){\n    if( pbNew ) *pbNew = 1;\n    p->bPatchset = (op=='P');\n    if( sessionChangesetReadTblhdr(p) ) return p->rc;\n    if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;\n    p->in.iCurrent = p->in.iNext;\n    if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;\n    op = p->in.aData[p->in.iNext++];\n  }\n\n  if( p->zTab==0 || (p->bPatchset && p->bInvert) ){\n    /* The first record in the changeset is not a table header. Must be a\n    ** corrupt changeset. */\n    assert( p->in.iNext==1 || p->zTab );\n    return (p->rc = SQLITE_CORRUPT_BKPT);\n  }\n\n  p->op = op;\n  p->bIndirect = p->in.aData[p->in.iNext++];\n  if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){\n    return (p->rc = SQLITE_CORRUPT_BKPT);\n  }\n\n  if( paRec ){ \n    int nVal;                     /* Number of values to buffer */\n    if( p->bPatchset==0 && op==SQLITE_UPDATE ){\n      nVal = p->nCol * 2;\n    }else if( p->bPatchset && op==SQLITE_DELETE ){\n      nVal = 0;\n      for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;\n    }else{\n      nVal = p->nCol;\n    }\n    p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);\n    if( p->rc!=SQLITE_OK ) return p->rc;\n    *paRec = &p->in.aData[p->in.iNext];\n    p->in.iNext += *pnRec;\n  }else{\n    sqlite3_value **apOld = (p->bInvert ? &p->apValue[p->nCol] : p->apValue);\n    sqlite3_value **apNew = (p->bInvert ? p->apValue : &p->apValue[p->nCol]);\n\n    /* If this is an UPDATE or DELETE, read the old.* record. */\n    if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){\n      u8 *abPK = p->bPatchset ? p->abPK : 0;\n      p->rc = sessionReadRecord(&p->in, p->nCol, abPK, apOld);\n      if( p->rc!=SQLITE_OK ) return p->rc;\n    }\n\n    /* If this is an INSERT or UPDATE, read the new.* record. */\n    if( p->op!=SQLITE_DELETE ){\n      p->rc = sessionReadRecord(&p->in, p->nCol, 0, apNew);\n      if( p->rc!=SQLITE_OK ) return p->rc;\n    }\n\n    if( (p->bPatchset || p->bInvert) && p->op==SQLITE_UPDATE ){\n      /* If this is an UPDATE that is part of a patchset, then all PK and\n      ** modified fields are present in the new.* record. The old.* record\n      ** is currently completely empty. This block shifts the PK fields from\n      ** new.* to old.*, to accommodate the code that reads these arrays.  */\n      for(i=0; i<p->nCol; i++){\n        assert( p->bPatchset==0 || p->apValue[i]==0 );\n        if( p->abPK[i] ){\n          assert( p->apValue[i]==0 );\n          p->apValue[i] = p->apValue[i+p->nCol];\n          if( p->apValue[i]==0 ) return (p->rc = SQLITE_CORRUPT_BKPT);\n          p->apValue[i+p->nCol] = 0;\n        }\n      }\n    }else if( p->bInvert ){\n      if( p->op==SQLITE_INSERT ) p->op = SQLITE_DELETE;\n      else if( p->op==SQLITE_DELETE ) p->op = SQLITE_INSERT;\n    }\n  }\n\n  return SQLITE_ROW;\n}\n\n/*\n** Advance an iterator created by sqlite3changeset_start() to the next\n** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE\n** or SQLITE_CORRUPT.\n**\n** This function may not be called on iterators passed to a conflict handler\n** callback by changeset_apply().\n*/\nSQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){\n  return sessionChangesetNext(p, 0, 0, 0);\n}\n\n/*\n** The following function extracts information on the current change\n** from a changeset iterator. It may only be called after changeset_next()\n** has returned SQLITE_ROW.\n*/\nSQLITE_API int sqlite3changeset_op(\n  sqlite3_changeset_iter *pIter,  /* Iterator handle */\n  const char **pzTab,             /* OUT: Pointer to table name */\n  int *pnCol,                     /* OUT: Number of columns in table */\n  int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */\n  int *pbIndirect                 /* OUT: True if change is indirect */\n){\n  *pOp = pIter->op;\n  *pnCol = pIter->nCol;\n  *pzTab = pIter->zTab;\n  if( pbIndirect ) *pbIndirect = pIter->bIndirect;\n  return SQLITE_OK;\n}\n\n/*\n** Return information regarding the PRIMARY KEY and number of columns in\n** the database table affected by the change that pIter currently points\n** to. This function may only be called after changeset_next() returns\n** SQLITE_ROW.\n*/\nSQLITE_API int sqlite3changeset_pk(\n  sqlite3_changeset_iter *pIter,  /* Iterator object */\n  unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */\n  int *pnCol                      /* OUT: Number of entries in output array */\n){\n  *pabPK = pIter->abPK;\n  if( pnCol ) *pnCol = pIter->nCol;\n  return SQLITE_OK;\n}\n\n/*\n** This function may only be called while the iterator is pointing to an\n** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).\n** Otherwise, SQLITE_MISUSE is returned.\n**\n** It sets *ppValue to point to an sqlite3_value structure containing the\n** iVal'th value in the old.* record. Or, if that particular value is not\n** included in the record (because the change is an UPDATE and the field\n** was not modified and is not a PK column), set *ppValue to NULL.\n**\n** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is\n** not modified. Otherwise, SQLITE_OK.\n*/\nSQLITE_API int sqlite3changeset_old(\n  sqlite3_changeset_iter *pIter,  /* Changeset iterator */\n  int iVal,                       /* Index of old.* value to retrieve */\n  sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */\n){\n  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){\n    return SQLITE_MISUSE;\n  }\n  if( iVal<0 || iVal>=pIter->nCol ){\n    return SQLITE_RANGE;\n  }\n  *ppValue = pIter->apValue[iVal];\n  return SQLITE_OK;\n}\n\n/*\n** This function may only be called while the iterator is pointing to an\n** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).\n** Otherwise, SQLITE_MISUSE is returned.\n**\n** It sets *ppValue to point to an sqlite3_value structure containing the\n** iVal'th value in the new.* record. Or, if that particular value is not\n** included in the record (because the change is an UPDATE and the field\n** was not modified), set *ppValue to NULL.\n**\n** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is\n** not modified. Otherwise, SQLITE_OK.\n*/\nSQLITE_API int sqlite3changeset_new(\n  sqlite3_changeset_iter *pIter,  /* Changeset iterator */\n  int iVal,                       /* Index of new.* value to retrieve */\n  sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */\n){\n  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){\n    return SQLITE_MISUSE;\n  }\n  if( iVal<0 || iVal>=pIter->nCol ){\n    return SQLITE_RANGE;\n  }\n  *ppValue = pIter->apValue[pIter->nCol+iVal];\n  return SQLITE_OK;\n}\n\n/*\n** The following two macros are used internally. They are similar to the\n** sqlite3changeset_new() and sqlite3changeset_old() functions, except that\n** they omit all error checking and return a pointer to the requested value.\n*/\n#define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]\n#define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]\n\n/*\n** This function may only be called with a changeset iterator that has been\n** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT \n** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.\n**\n** If successful, *ppValue is set to point to an sqlite3_value structure\n** containing the iVal'th value of the conflicting record.\n**\n** If value iVal is out-of-range or some other error occurs, an SQLite error\n** code is returned. Otherwise, SQLITE_OK.\n*/\nSQLITE_API int sqlite3changeset_conflict(\n  sqlite3_changeset_iter *pIter,  /* Changeset iterator */\n  int iVal,                       /* Index of conflict record value to fetch */\n  sqlite3_value **ppValue         /* OUT: Value from conflicting row */\n){\n  if( !pIter->pConflict ){\n    return SQLITE_MISUSE;\n  }\n  if( iVal<0 || iVal>=pIter->nCol ){\n    return SQLITE_RANGE;\n  }\n  *ppValue = sqlite3_column_value(pIter->pConflict, iVal);\n  return SQLITE_OK;\n}\n\n/*\n** This function may only be called with an iterator passed to an\n** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case\n** it sets the output variable to the total number of known foreign key\n** violations in the destination database and returns SQLITE_OK.\n**\n** In all other cases this function returns SQLITE_MISUSE.\n*/\nSQLITE_API int sqlite3changeset_fk_conflicts(\n  sqlite3_changeset_iter *pIter,  /* Changeset iterator */\n  int *pnOut                      /* OUT: Number of FK violations */\n){\n  if( pIter->pConflict || pIter->apValue ){\n    return SQLITE_MISUSE;\n  }\n  *pnOut = pIter->nCol;\n  return SQLITE_OK;\n}\n\n\n/*\n** Finalize an iterator allocated with sqlite3changeset_start().\n**\n** This function may not be called on iterators passed to a conflict handler\n** callback by changeset_apply().\n*/\nSQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){\n  int rc = SQLITE_OK;\n  if( p ){\n    int i;                        /* Used to iterate through p->apValue[] */\n    rc = p->rc;\n    if( p->apValue ){\n      for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);\n    }\n    sqlite3_free(p->tblhdr.aBuf);\n    sqlite3_free(p->in.buf.aBuf);\n    sqlite3_free(p);\n  }\n  return rc;\n}\n\nstatic int sessionChangesetInvert(\n  SessionInput *pInput,           /* Input changeset */\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut,\n  int *pnInverted,                /* OUT: Number of bytes in output changeset */\n  void **ppInverted               /* OUT: Inverse of pChangeset */\n){\n  int rc = SQLITE_OK;             /* Return value */\n  SessionBuffer sOut;             /* Output buffer */\n  int nCol = 0;                   /* Number of cols in current table */\n  u8 *abPK = 0;                   /* PK array for current table */\n  sqlite3_value **apVal = 0;      /* Space for values for UPDATE inversion */\n  SessionBuffer sPK = {0, 0, 0};  /* PK array for current table */\n\n  /* Initialize the output buffer */\n  memset(&sOut, 0, sizeof(SessionBuffer));\n\n  /* Zero the output variables in case an error occurs. */\n  if( ppInverted ){\n    *ppInverted = 0;\n    *pnInverted = 0;\n  }\n\n  while( 1 ){\n    u8 eType;\n\n    /* Test for EOF. */\n    if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;\n    if( pInput->iNext>=pInput->nData ) break;\n    eType = pInput->aData[pInput->iNext];\n\n    switch( eType ){\n      case 'T': {\n        /* A 'table' record consists of:\n        **\n        **   * A constant 'T' character,\n        **   * Number of columns in said table (a varint),\n        **   * An array of nCol bytes (sPK),\n        **   * A nul-terminated table name.\n        */\n        int nByte;\n        int nVar;\n        pInput->iNext++;\n        if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){\n          goto finished_invert;\n        }\n        nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);\n        sPK.nBuf = 0;\n        sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);\n        sessionAppendByte(&sOut, eType, &rc);\n        sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);\n        if( rc ) goto finished_invert;\n\n        pInput->iNext += nByte;\n        sqlite3_free(apVal);\n        apVal = 0;\n        abPK = sPK.aBuf;\n        break;\n      }\n\n      case SQLITE_INSERT:\n      case SQLITE_DELETE: {\n        int nByte;\n        int bIndirect = pInput->aData[pInput->iNext+1];\n        int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);\n        pInput->iNext += 2;\n        assert( rc==SQLITE_OK );\n        rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);\n        sessionAppendByte(&sOut, eType2, &rc);\n        sessionAppendByte(&sOut, bIndirect, &rc);\n        sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);\n        pInput->iNext += nByte;\n        if( rc ) goto finished_invert;\n        break;\n      }\n\n      case SQLITE_UPDATE: {\n        int iCol;\n\n        if( 0==apVal ){\n          apVal = (sqlite3_value **)sqlite3_malloc64(sizeof(apVal[0])*nCol*2);\n          if( 0==apVal ){\n            rc = SQLITE_NOMEM;\n            goto finished_invert;\n          }\n          memset(apVal, 0, sizeof(apVal[0])*nCol*2);\n        }\n\n        /* Write the header for the new UPDATE change. Same as the original. */\n        sessionAppendByte(&sOut, eType, &rc);\n        sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);\n\n        /* Read the old.* and new.* records for the update change. */\n        pInput->iNext += 2;\n        rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);\n        if( rc==SQLITE_OK ){\n          rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);\n        }\n\n        /* Write the new old.* record. Consists of the PK columns from the\n        ** original old.* record, and the other values from the original\n        ** new.* record. */\n        for(iCol=0; iCol<nCol; iCol++){\n          sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];\n          sessionAppendValue(&sOut, pVal, &rc);\n        }\n\n        /* Write the new new.* record. Consists of a copy of all values\n        ** from the original old.* record, except for the PK columns, which\n        ** are set to \"undefined\". */\n        for(iCol=0; iCol<nCol; iCol++){\n          sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);\n          sessionAppendValue(&sOut, pVal, &rc);\n        }\n\n        for(iCol=0; iCol<nCol*2; iCol++){\n          sqlite3ValueFree(apVal[iCol]);\n        }\n        memset(apVal, 0, sizeof(apVal[0])*nCol*2);\n        if( rc!=SQLITE_OK ){\n          goto finished_invert;\n        }\n\n        break;\n      }\n\n      default:\n        rc = SQLITE_CORRUPT_BKPT;\n        goto finished_invert;\n    }\n\n    assert( rc==SQLITE_OK );\n    if( xOutput && sOut.nBuf>=sessions_strm_chunk_size ){\n      rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);\n      sOut.nBuf = 0;\n      if( rc!=SQLITE_OK ) goto finished_invert;\n    }\n  }\n\n  assert( rc==SQLITE_OK );\n  if( pnInverted ){\n    *pnInverted = sOut.nBuf;\n    *ppInverted = sOut.aBuf;\n    sOut.aBuf = 0;\n  }else if( sOut.nBuf>0 ){\n    rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);\n  }\n\n finished_invert:\n  sqlite3_free(sOut.aBuf);\n  sqlite3_free(apVal);\n  sqlite3_free(sPK.aBuf);\n  return rc;\n}\n\n\n/*\n** Invert a changeset object.\n*/\nSQLITE_API int sqlite3changeset_invert(\n  int nChangeset,                 /* Number of bytes in input */\n  const void *pChangeset,         /* Input changeset */\n  int *pnInverted,                /* OUT: Number of bytes in output changeset */\n  void **ppInverted               /* OUT: Inverse of pChangeset */\n){\n  SessionInput sInput;\n\n  /* Set up the input stream */\n  memset(&sInput, 0, sizeof(SessionInput));\n  sInput.nData = nChangeset;\n  sInput.aData = (u8*)pChangeset;\n\n  return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);\n}\n\n/*\n** Streaming version of sqlite3changeset_invert().\n*/\nSQLITE_API int sqlite3changeset_invert_strm(\n  int (*xInput)(void *pIn, void *pData, int *pnData),\n  void *pIn,\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut\n){\n  SessionInput sInput;\n  int rc;\n\n  /* Set up the input stream */\n  memset(&sInput, 0, sizeof(SessionInput));\n  sInput.xInput = xInput;\n  sInput.pIn = pIn;\n\n  rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);\n  sqlite3_free(sInput.buf.aBuf);\n  return rc;\n}\n\ntypedef struct SessionApplyCtx SessionApplyCtx;\nstruct SessionApplyCtx {\n  sqlite3 *db;\n  sqlite3_stmt *pDelete;          /* DELETE statement */\n  sqlite3_stmt *pUpdate;          /* UPDATE statement */\n  sqlite3_stmt *pInsert;          /* INSERT statement */\n  sqlite3_stmt *pSelect;          /* SELECT statement */\n  int nCol;                       /* Size of azCol[] and abPK[] arrays */\n  const char **azCol;             /* Array of column names */\n  u8 *abPK;                       /* Boolean array - true if column is in PK */\n  int bStat1;                     /* True if table is sqlite_stat1 */\n  int bDeferConstraints;          /* True to defer constraints */\n  SessionBuffer constraints;      /* Deferred constraints are stored here */\n  SessionBuffer rebase;           /* Rebase information (if any) here */\n  u8 bRebaseStarted;              /* If table header is already in rebase */\n  u8 bRebase;                     /* True to collect rebase information */\n};\n\n/*\n** Formulate a statement to DELETE a row from database db. Assuming a table\n** structure like this:\n**\n**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));\n**\n** The DELETE statement looks like this:\n**\n**     DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)\n**\n** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require\n** matching b and d values, or 1 otherwise. The second case comes up if the\n** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.\n**\n** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left\n** pointing to the prepared version of the SQL statement.\n*/\nstatic int sessionDeleteRow(\n  sqlite3 *db,                    /* Database handle */\n  const char *zTab,               /* Table name */\n  SessionApplyCtx *p              /* Session changeset-apply context */\n){\n  int i;\n  const char *zSep = \"\";\n  int rc = SQLITE_OK;\n  SessionBuffer buf = {0, 0, 0};\n  int nPk = 0;\n\n  sessionAppendStr(&buf, \"DELETE FROM main.\", &rc);\n  sessionAppendIdent(&buf, zTab, &rc);\n  sessionAppendStr(&buf, \" WHERE \", &rc);\n\n  for(i=0; i<p->nCol; i++){\n    if( p->abPK[i] ){\n      nPk++;\n      sessionAppendStr(&buf, zSep, &rc);\n      sessionAppendIdent(&buf, p->azCol[i], &rc);\n      sessionAppendStr(&buf, \" = ?\", &rc);\n      sessionAppendInteger(&buf, i+1, &rc);\n      zSep = \" AND \";\n    }\n  }\n\n  if( nPk<p->nCol ){\n    sessionAppendStr(&buf, \" AND (?\", &rc);\n    sessionAppendInteger(&buf, p->nCol+1, &rc);\n    sessionAppendStr(&buf, \" OR \", &rc);\n\n    zSep = \"\";\n    for(i=0; i<p->nCol; i++){\n      if( !p->abPK[i] ){\n        sessionAppendStr(&buf, zSep, &rc);\n        sessionAppendIdent(&buf, p->azCol[i], &rc);\n        sessionAppendStr(&buf, \" IS ?\", &rc);\n        sessionAppendInteger(&buf, i+1, &rc);\n        zSep = \"AND \";\n      }\n    }\n    sessionAppendStr(&buf, \")\", &rc);\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);\n  }\n  sqlite3_free(buf.aBuf);\n\n  return rc;\n}\n\n/*\n** Formulate and prepare a statement to UPDATE a row from database db. \n** Assuming a table structure like this:\n**\n**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));\n**\n** The UPDATE statement looks like this:\n**\n**     UPDATE x SET\n**     a = CASE WHEN ?2  THEN ?3  ELSE a END,\n**     b = CASE WHEN ?5  THEN ?6  ELSE b END,\n**     c = CASE WHEN ?8  THEN ?9  ELSE c END,\n**     d = CASE WHEN ?11 THEN ?12 ELSE d END\n**     WHERE a = ?1 AND c = ?7 AND (?13 OR \n**       (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND\n**     )\n**\n** For each column in the table, there are three variables to bind:\n**\n**     ?(i*3+1)    The old.* value of the column, if any.\n**     ?(i*3+2)    A boolean flag indicating that the value is being modified.\n**     ?(i*3+3)    The new.* value of the column, if any.\n**\n** Also, a boolean flag that, if set to true, causes the statement to update\n** a row even if the non-PK values do not match. This is required if the\n** conflict-handler is invoked with CHANGESET_DATA and returns\n** CHANGESET_REPLACE. This is variable \"?(nCol*3+1)\".\n**\n** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left\n** pointing to the prepared version of the SQL statement.\n*/\nstatic int sessionUpdateRow(\n  sqlite3 *db,                    /* Database handle */\n  const char *zTab,               /* Table name */\n  SessionApplyCtx *p              /* Session changeset-apply context */\n){\n  int rc = SQLITE_OK;\n  int i;\n  const char *zSep = \"\";\n  SessionBuffer buf = {0, 0, 0};\n\n  /* Append \"UPDATE tbl SET \" */\n  sessionAppendStr(&buf, \"UPDATE main.\", &rc);\n  sessionAppendIdent(&buf, zTab, &rc);\n  sessionAppendStr(&buf, \" SET \", &rc);\n\n  /* Append the assignments */\n  for(i=0; i<p->nCol; i++){\n    sessionAppendStr(&buf, zSep, &rc);\n    sessionAppendIdent(&buf, p->azCol[i], &rc);\n    sessionAppendStr(&buf, \" = CASE WHEN ?\", &rc);\n    sessionAppendInteger(&buf, i*3+2, &rc);\n    sessionAppendStr(&buf, \" THEN ?\", &rc);\n    sessionAppendInteger(&buf, i*3+3, &rc);\n    sessionAppendStr(&buf, \" ELSE \", &rc);\n    sessionAppendIdent(&buf, p->azCol[i], &rc);\n    sessionAppendStr(&buf, \" END\", &rc);\n    zSep = \", \";\n  }\n\n  /* Append the PK part of the WHERE clause */\n  sessionAppendStr(&buf, \" WHERE \", &rc);\n  for(i=0; i<p->nCol; i++){\n    if( p->abPK[i] ){\n      sessionAppendIdent(&buf, p->azCol[i], &rc);\n      sessionAppendStr(&buf, \" = ?\", &rc);\n      sessionAppendInteger(&buf, i*3+1, &rc);\n      sessionAppendStr(&buf, \" AND \", &rc);\n    }\n  }\n\n  /* Append the non-PK part of the WHERE clause */\n  sessionAppendStr(&buf, \" (?\", &rc);\n  sessionAppendInteger(&buf, p->nCol*3+1, &rc);\n  sessionAppendStr(&buf, \" OR 1\", &rc);\n  for(i=0; i<p->nCol; i++){\n    if( !p->abPK[i] ){\n      sessionAppendStr(&buf, \" AND (?\", &rc);\n      sessionAppendInteger(&buf, i*3+2, &rc);\n      sessionAppendStr(&buf, \"=0 OR \", &rc);\n      sessionAppendIdent(&buf, p->azCol[i], &rc);\n      sessionAppendStr(&buf, \" IS ?\", &rc);\n      sessionAppendInteger(&buf, i*3+1, &rc);\n      sessionAppendStr(&buf, \")\", &rc);\n    }\n  }\n  sessionAppendStr(&buf, \")\", &rc);\n\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);\n  }\n  sqlite3_free(buf.aBuf);\n\n  return rc;\n}\n\n\n/*\n** Formulate and prepare an SQL statement to query table zTab by primary\n** key. Assuming the following table structure:\n**\n**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));\n**\n** The SELECT statement looks like this:\n**\n**     SELECT * FROM x WHERE a = ?1 AND c = ?3\n**\n** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left\n** pointing to the prepared version of the SQL statement.\n*/\nstatic int sessionSelectRow(\n  sqlite3 *db,                    /* Database handle */\n  const char *zTab,               /* Table name */\n  SessionApplyCtx *p              /* Session changeset-apply context */\n){\n  return sessionSelectStmt(\n      db, \"main\", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);\n}\n\n/*\n** Formulate and prepare an INSERT statement to add a record to table zTab.\n** For example:\n**\n**     INSERT INTO main.\"zTab\" VALUES(?1, ?2, ?3 ...);\n**\n** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left\n** pointing to the prepared version of the SQL statement.\n*/\nstatic int sessionInsertRow(\n  sqlite3 *db,                    /* Database handle */\n  const char *zTab,               /* Table name */\n  SessionApplyCtx *p              /* Session changeset-apply context */\n){\n  int rc = SQLITE_OK;\n  int i;\n  SessionBuffer buf = {0, 0, 0};\n\n  sessionAppendStr(&buf, \"INSERT INTO main.\", &rc);\n  sessionAppendIdent(&buf, zTab, &rc);\n  sessionAppendStr(&buf, \"(\", &rc);\n  for(i=0; i<p->nCol; i++){\n    if( i!=0 ) sessionAppendStr(&buf, \", \", &rc);\n    sessionAppendIdent(&buf, p->azCol[i], &rc);\n  }\n\n  sessionAppendStr(&buf, \") VALUES(?\", &rc);\n  for(i=1; i<p->nCol; i++){\n    sessionAppendStr(&buf, \", ?\", &rc);\n  }\n  sessionAppendStr(&buf, \")\", &rc);\n\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);\n  }\n  sqlite3_free(buf.aBuf);\n  return rc;\n}\n\nstatic int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){\n  return sqlite3_prepare_v2(db, zSql, -1, pp, 0);\n}\n\n/*\n** Prepare statements for applying changes to the sqlite_stat1 table.\n** These are similar to those created by sessionSelectRow(),\n** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for \n** other tables.\n*/\nstatic int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){\n  int rc = sessionSelectRow(db, \"sqlite_stat1\", p);\n  if( rc==SQLITE_OK ){\n    rc = sessionPrepare(db, &p->pInsert,\n        \"INSERT INTO main.sqlite_stat1 VALUES(?1, \"\n        \"CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, \"\n        \"?3)\"\n    );\n  }\n  if( rc==SQLITE_OK ){\n    rc = sessionPrepare(db, &p->pUpdate,\n        \"UPDATE main.sqlite_stat1 SET \"\n        \"tbl = CASE WHEN ?2 THEN ?3 ELSE tbl END, \"\n        \"idx = CASE WHEN ?5 THEN ?6 ELSE idx END, \"\n        \"stat = CASE WHEN ?8 THEN ?9 ELSE stat END  \"\n        \"WHERE tbl=?1 AND idx IS \"\n        \"CASE WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL ELSE ?4 END \"\n        \"AND (?10 OR ?8=0 OR stat IS ?7)\"\n    );\n  }\n  if( rc==SQLITE_OK ){\n    rc = sessionPrepare(db, &p->pDelete,\n        \"DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS \"\n        \"CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END \"\n        \"AND (?4 OR stat IS ?3)\"\n    );\n  }\n  return rc;\n}\n\n/*\n** A wrapper around sqlite3_bind_value() that detects an extra problem. \n** See comments in the body of this function for details.\n*/\nstatic int sessionBindValue(\n  sqlite3_stmt *pStmt,            /* Statement to bind value to */\n  int i,                          /* Parameter number to bind to */\n  sqlite3_value *pVal             /* Value to bind */\n){\n  int eType = sqlite3_value_type(pVal);\n  /* COVERAGE: The (pVal->z==0) branch is never true using current versions\n  ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either\n  ** the (pVal->z) variable remains as it was or the type of the value is\n  ** set to SQLITE_NULL.  */\n  if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){\n    /* This condition occurs when an earlier OOM in a call to\n    ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within\n    ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */\n    return SQLITE_NOMEM;\n  }\n  return sqlite3_bind_value(pStmt, i, pVal);\n}\n\n/*\n** Iterator pIter must point to an SQLITE_INSERT entry. This function \n** transfers new.* values from the current iterator entry to statement\n** pStmt. The table being inserted into has nCol columns.\n**\n** New.* value $i from the iterator is bound to variable ($i+1) of \n** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)\n** are transfered to the statement. Otherwise, if abPK is not NULL, it points\n** to an array nCol elements in size. In this case only those values for \n** which abPK[$i] is true are read from the iterator and bound to the \n** statement.\n**\n** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.\n*/\nstatic int sessionBindRow(\n  sqlite3_changeset_iter *pIter,  /* Iterator to read values from */\n  int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),\n  int nCol,                       /* Number of columns */\n  u8 *abPK,                       /* If not NULL, bind only if true */\n  sqlite3_stmt *pStmt             /* Bind values to this statement */\n){\n  int i;\n  int rc = SQLITE_OK;\n\n  /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the\n  ** argument iterator points to a suitable entry. Make sure that xValue \n  ** is one of these to guarantee that it is safe to ignore the return \n  ** in the code below. */\n  assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );\n\n  for(i=0; rc==SQLITE_OK && i<nCol; i++){\n    if( !abPK || abPK[i] ){\n      sqlite3_value *pVal;\n      (void)xValue(pIter, i, &pVal);\n      if( pVal==0 ){\n        /* The value in the changeset was \"undefined\". This indicates a\n        ** corrupt changeset blob.  */\n        rc = SQLITE_CORRUPT_BKPT;\n      }else{\n        rc = sessionBindValue(pStmt, i+1, pVal);\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** SQL statement pSelect is as generated by the sessionSelectRow() function.\n** This function binds the primary key values from the change that changeset\n** iterator pIter points to to the SELECT and attempts to seek to the table\n** entry. If a row is found, the SELECT statement left pointing at the row \n** and SQLITE_ROW is returned. Otherwise, if no row is found and no error\n** has occured, the statement is reset and SQLITE_OK is returned. If an\n** error occurs, the statement is reset and an SQLite error code is returned.\n**\n** If this function returns SQLITE_ROW, the caller must eventually reset() \n** statement pSelect. If any other value is returned, the statement does\n** not require a reset().\n**\n** If the iterator currently points to an INSERT record, bind values from the\n** new.* record to the SELECT statement. Or, if it points to a DELETE or\n** UPDATE, bind values from the old.* record. \n*/\nstatic int sessionSeekToRow(\n  sqlite3 *db,                    /* Database handle */\n  sqlite3_changeset_iter *pIter,  /* Changeset iterator */\n  u8 *abPK,                       /* Primary key flags array */\n  sqlite3_stmt *pSelect           /* SELECT statement from sessionSelectRow() */\n){\n  int rc;                         /* Return code */\n  int nCol;                       /* Number of columns in table */\n  int op;                         /* Changset operation (SQLITE_UPDATE etc.) */\n  const char *zDummy;             /* Unused */\n\n  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);\n  rc = sessionBindRow(pIter, \n      op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,\n      nCol, abPK, pSelect\n  );\n\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_step(pSelect);\n    if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);\n  }\n\n  return rc;\n}\n\n/*\n** This function is called from within sqlite3changeset_apply_v2() when\n** a conflict is encountered and resolved using conflict resolution\n** mode eType (either SQLITE_CHANGESET_OMIT or SQLITE_CHANGESET_REPLACE)..\n** It adds a conflict resolution record to the buffer in \n** SessionApplyCtx.rebase, which will eventually be returned to the caller\n** of apply_v2() as the \"rebase\" buffer.\n**\n** Return SQLITE_OK if successful, or an SQLite error code otherwise.\n*/\nstatic int sessionRebaseAdd(\n  SessionApplyCtx *p,             /* Apply context */\n  int eType,                      /* Conflict resolution (OMIT or REPLACE) */\n  sqlite3_changeset_iter *pIter   /* Iterator pointing at current change */\n){\n  int rc = SQLITE_OK;\n  if( p->bRebase ){\n    int i;\n    int eOp = pIter->op;\n    if( p->bRebaseStarted==0 ){\n      /* Append a table-header to the rebase buffer */\n      const char *zTab = pIter->zTab;\n      sessionAppendByte(&p->rebase, 'T', &rc);\n      sessionAppendVarint(&p->rebase, p->nCol, &rc);\n      sessionAppendBlob(&p->rebase, p->abPK, p->nCol, &rc);\n      sessionAppendBlob(&p->rebase, (u8*)zTab, (int)strlen(zTab)+1, &rc);\n      p->bRebaseStarted = 1;\n    }\n\n    assert( eType==SQLITE_CHANGESET_REPLACE||eType==SQLITE_CHANGESET_OMIT );\n    assert( eOp==SQLITE_DELETE || eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE );\n\n    sessionAppendByte(&p->rebase, \n        (eOp==SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), &rc\n        );\n    sessionAppendByte(&p->rebase, (eType==SQLITE_CHANGESET_REPLACE), &rc);\n    for(i=0; i<p->nCol; i++){\n      sqlite3_value *pVal = 0;\n      if( eOp==SQLITE_DELETE || (eOp==SQLITE_UPDATE && p->abPK[i]) ){\n        sqlite3changeset_old(pIter, i, &pVal);\n      }else{\n        sqlite3changeset_new(pIter, i, &pVal);\n      }\n      sessionAppendValue(&p->rebase, pVal, &rc);\n    }\n  }\n  return rc;\n}\n\n/*\n** Invoke the conflict handler for the change that the changeset iterator\n** currently points to.\n**\n** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.\n** If argument pbReplace is NULL, then the type of conflict handler invoked\n** depends solely on eType, as follows:\n**\n**    eType value                 Value passed to xConflict\n**    -------------------------------------------------\n**    CHANGESET_DATA              CHANGESET_NOTFOUND\n**    CHANGESET_CONFLICT          CHANGESET_CONSTRAINT\n**\n** Or, if pbReplace is not NULL, then an attempt is made to find an existing\n** record with the same primary key as the record about to be deleted, updated\n** or inserted. If such a record can be found, it is available to the conflict\n** handler as the \"conflicting\" record. In this case the type of conflict\n** handler invoked is as follows:\n**\n**    eType value         PK Record found?   Value passed to xConflict\n**    ----------------------------------------------------------------\n**    CHANGESET_DATA      Yes                CHANGESET_DATA\n**    CHANGESET_DATA      No                 CHANGESET_NOTFOUND\n**    CHANGESET_CONFLICT  Yes                CHANGESET_CONFLICT\n**    CHANGESET_CONFLICT  No                 CHANGESET_CONSTRAINT\n**\n** If pbReplace is not NULL, and a record with a matching PK is found, and\n** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace\n** is set to non-zero before returning SQLITE_OK.\n**\n** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is\n** returned. Or, if the conflict handler returns an invalid value, \n** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,\n** this function returns SQLITE_OK.\n*/\nstatic int sessionConflictHandler(\n  int eType,                      /* Either CHANGESET_DATA or CONFLICT */\n  SessionApplyCtx *p,             /* changeset_apply() context */\n  sqlite3_changeset_iter *pIter,  /* Changeset iterator */\n  int(*xConflict)(void *, int, sqlite3_changeset_iter*),\n  void *pCtx,                     /* First argument for conflict handler */\n  int *pbReplace                  /* OUT: Set to true if PK row is found */\n){\n  int res = 0;                    /* Value returned by conflict handler */\n  int rc;\n  int nCol;\n  int op;\n  const char *zDummy;\n\n  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);\n\n  assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );\n  assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );\n  assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );\n\n  /* Bind the new.* PRIMARY KEY values to the SELECT statement. */\n  if( pbReplace ){\n    rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);\n  }else{\n    rc = SQLITE_OK;\n  }\n\n  if( rc==SQLITE_ROW ){\n    /* There exists another row with the new.* primary key. */\n    pIter->pConflict = p->pSelect;\n    res = xConflict(pCtx, eType, pIter);\n    pIter->pConflict = 0;\n    rc = sqlite3_reset(p->pSelect);\n  }else if( rc==SQLITE_OK ){\n    if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){\n      /* Instead of invoking the conflict handler, append the change blob\n      ** to the SessionApplyCtx.constraints buffer. */\n      u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];\n      int nBlob = pIter->in.iNext - pIter->in.iCurrent;\n      sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);\n      return SQLITE_OK;\n    }else{\n      /* No other row with the new.* primary key. */\n      res = xConflict(pCtx, eType+1, pIter);\n      if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    switch( res ){\n      case SQLITE_CHANGESET_REPLACE:\n        assert( pbReplace );\n        *pbReplace = 1;\n        break;\n\n      case SQLITE_CHANGESET_OMIT:\n        break;\n\n      case SQLITE_CHANGESET_ABORT:\n        rc = SQLITE_ABORT;\n        break;\n\n      default:\n        rc = SQLITE_MISUSE;\n        break;\n    }\n    if( rc==SQLITE_OK ){\n      rc = sessionRebaseAdd(p, res, pIter);\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Attempt to apply the change that the iterator passed as the first argument\n** currently points to to the database. If a conflict is encountered, invoke\n** the conflict handler callback.\n**\n** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If\n** one is encountered, update or delete the row with the matching primary key\n** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,\n** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry\n** to true before returning. In this case the caller will invoke this function\n** again, this time with pbRetry set to NULL.\n**\n** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is \n** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.\n** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such\n** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true\n** before retrying. In this case the caller attempts to remove the conflicting\n** row before invoking this function again, this time with pbReplace set \n** to NULL.\n**\n** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function\n** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is \n** returned.\n*/\nstatic int sessionApplyOneOp(\n  sqlite3_changeset_iter *pIter,  /* Changeset iterator */\n  SessionApplyCtx *p,             /* changeset_apply() context */\n  int(*xConflict)(void *, int, sqlite3_changeset_iter *),\n  void *pCtx,                     /* First argument for the conflict handler */\n  int *pbReplace,                 /* OUT: True to remove PK row and retry */\n  int *pbRetry                    /* OUT: True to retry. */\n){\n  const char *zDummy;\n  int op;\n  int nCol;\n  int rc = SQLITE_OK;\n\n  assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );\n  assert( p->azCol && p->abPK );\n  assert( !pbReplace || *pbReplace==0 );\n\n  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);\n\n  if( op==SQLITE_DELETE ){\n\n    /* Bind values to the DELETE statement. If conflict handling is required,\n    ** bind values for all columns and set bound variable (nCol+1) to true.\n    ** Or, if conflict handling is not required, bind just the PK column\n    ** values and, if it exists, set (nCol+1) to false. Conflict handling\n    ** is not required if:\n    **\n    **   * this is a patchset, or\n    **   * (pbRetry==0), or\n    **   * all columns of the table are PK columns (in this case there is\n    **     no (nCol+1) variable to bind to).\n    */\n    u8 *abPK = (pIter->bPatchset ? p->abPK : 0);\n    rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);\n    if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){\n      rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));\n    }\n    if( rc!=SQLITE_OK ) return rc;\n\n    sqlite3_step(p->pDelete);\n    rc = sqlite3_reset(p->pDelete);\n    if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){\n      rc = sessionConflictHandler(\n          SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry\n      );\n    }else if( (rc&0xff)==SQLITE_CONSTRAINT ){\n      rc = sessionConflictHandler(\n          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0\n      );\n    }\n\n  }else if( op==SQLITE_UPDATE ){\n    int i;\n\n    /* Bind values to the UPDATE statement. */\n    for(i=0; rc==SQLITE_OK && i<nCol; i++){\n      sqlite3_value *pOld = sessionChangesetOld(pIter, i);\n      sqlite3_value *pNew = sessionChangesetNew(pIter, i);\n\n      sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);\n      if( pOld ){\n        rc = sessionBindValue(p->pUpdate, i*3+1, pOld);\n      }\n      if( rc==SQLITE_OK && pNew ){\n        rc = sessionBindValue(p->pUpdate, i*3+3, pNew);\n      }\n    }\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);\n    }\n    if( rc!=SQLITE_OK ) return rc;\n\n    /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,\n    ** the result will be SQLITE_OK with 0 rows modified. */\n    sqlite3_step(p->pUpdate);\n    rc = sqlite3_reset(p->pUpdate);\n\n    if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){\n      /* A NOTFOUND or DATA error. Search the table to see if it contains\n      ** a row with a matching primary key. If so, this is a DATA conflict.\n      ** Otherwise, if there is no primary key match, it is a NOTFOUND. */\n\n      rc = sessionConflictHandler(\n          SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry\n      );\n\n    }else if( (rc&0xff)==SQLITE_CONSTRAINT ){\n      /* This is always a CONSTRAINT conflict. */\n      rc = sessionConflictHandler(\n          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0\n      );\n    }\n\n  }else{\n    assert( op==SQLITE_INSERT );\n    if( p->bStat1 ){\n      /* Check if there is a conflicting row. For sqlite_stat1, this needs\n      ** to be done using a SELECT, as there is no PRIMARY KEY in the \n      ** database schema to throw an exception if a duplicate is inserted.  */\n      rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);\n      if( rc==SQLITE_ROW ){\n        rc = SQLITE_CONSTRAINT;\n        sqlite3_reset(p->pSelect);\n      }\n    }\n\n    if( rc==SQLITE_OK ){\n      rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);\n      if( rc!=SQLITE_OK ) return rc;\n\n      sqlite3_step(p->pInsert);\n      rc = sqlite3_reset(p->pInsert);\n    }\n\n    if( (rc&0xff)==SQLITE_CONSTRAINT ){\n      rc = sessionConflictHandler(\n          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace\n      );\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Attempt to apply the change that the iterator passed as the first argument\n** currently points to to the database. If a conflict is encountered, invoke\n** the conflict handler callback.\n**\n** The difference between this function and sessionApplyOne() is that this\n** function handles the case where the conflict-handler is invoked and \n** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be\n** retried in some manner.\n*/\nstatic int sessionApplyOneWithRetry(\n  sqlite3 *db,                    /* Apply change to \"main\" db of this handle */\n  sqlite3_changeset_iter *pIter,  /* Changeset iterator to read change from */\n  SessionApplyCtx *pApply,        /* Apply context */\n  int(*xConflict)(void*, int, sqlite3_changeset_iter*),\n  void *pCtx                      /* First argument passed to xConflict */\n){\n  int bReplace = 0;\n  int bRetry = 0;\n  int rc;\n\n  rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);\n  if( rc==SQLITE_OK ){\n    /* If the bRetry flag is set, the change has not been applied due to an\n    ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and\n    ** a row with the correct PK is present in the db, but one or more other\n    ** fields do not contain the expected values) and the conflict handler \n    ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,\n    ** but pass NULL as the final argument so that sessionApplyOneOp() ignores\n    ** the SQLITE_CHANGESET_DATA problem.  */\n    if( bRetry ){\n      assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );\n      rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);\n    }\n\n    /* If the bReplace flag is set, the change is an INSERT that has not\n    ** been performed because the database already contains a row with the\n    ** specified primary key and the conflict handler returned\n    ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row\n    ** before reattempting the INSERT.  */\n    else if( bReplace ){\n      assert( pIter->op==SQLITE_INSERT );\n      rc = sqlite3_exec(db, \"SAVEPOINT replace_op\", 0, 0, 0);\n      if( rc==SQLITE_OK ){\n        rc = sessionBindRow(pIter, \n            sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);\n        sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);\n      }\n      if( rc==SQLITE_OK ){\n        sqlite3_step(pApply->pDelete);\n        rc = sqlite3_reset(pApply->pDelete);\n      }\n      if( rc==SQLITE_OK ){\n        rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);\n      }\n      if( rc==SQLITE_OK ){\n        rc = sqlite3_exec(db, \"RELEASE replace_op\", 0, 0, 0);\n      }\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Retry the changes accumulated in the pApply->constraints buffer.\n*/\nstatic int sessionRetryConstraints(\n  sqlite3 *db, \n  int bPatchset,\n  const char *zTab,\n  SessionApplyCtx *pApply,\n  int(*xConflict)(void*, int, sqlite3_changeset_iter*),\n  void *pCtx                      /* First argument passed to xConflict */\n){\n  int rc = SQLITE_OK;\n\n  while( pApply->constraints.nBuf ){\n    sqlite3_changeset_iter *pIter2 = 0;\n    SessionBuffer cons = pApply->constraints;\n    memset(&pApply->constraints, 0, sizeof(SessionBuffer));\n\n    rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf, 0);\n    if( rc==SQLITE_OK ){\n      size_t nByte = 2*pApply->nCol*sizeof(sqlite3_value*);\n      int rc2;\n      pIter2->bPatchset = bPatchset;\n      pIter2->zTab = (char*)zTab;\n      pIter2->nCol = pApply->nCol;\n      pIter2->abPK = pApply->abPK;\n      sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);\n      pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;\n      if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);\n\n      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){\n        rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);\n      }\n\n      rc2 = sqlite3changeset_finalize(pIter2);\n      if( rc==SQLITE_OK ) rc = rc2;\n    }\n    assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );\n\n    sqlite3_free(cons.aBuf);\n    if( rc!=SQLITE_OK ) break;\n    if( pApply->constraints.nBuf>=cons.nBuf ){\n      /* No progress was made on the last round. */\n      pApply->bDeferConstraints = 0;\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Argument pIter is a changeset iterator that has been initialized, but\n** not yet passed to sqlite3changeset_next(). This function applies the \n** changeset to the main database attached to handle \"db\". The supplied\n** conflict handler callback is invoked to resolve any conflicts encountered\n** while applying the change.\n*/\nstatic int sessionChangesetApply(\n  sqlite3 *db,                    /* Apply change to \"main\" db of this handle */\n  sqlite3_changeset_iter *pIter,  /* Changeset to apply */\n  int(*xFilter)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    const char *zTab              /* Table name */\n  ),\n  int(*xConflict)(\n    void *pCtx,                   /* Copy of fifth arg to _apply() */\n    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */\n    sqlite3_changeset_iter *p     /* Handle describing change and conflict */\n  ),\n  void *pCtx,                     /* First argument passed to xConflict */\n  void **ppRebase, int *pnRebase, /* OUT: Rebase information */\n  int flags                       /* SESSION_APPLY_XXX flags */\n){\n  int schemaMismatch = 0;\n  int rc = SQLITE_OK;             /* Return code */\n  const char *zTab = 0;           /* Name of current table */\n  int nTab = 0;                   /* Result of sqlite3Strlen30(zTab) */\n  SessionApplyCtx sApply;         /* changeset_apply() context object */\n  int bPatchset;\n\n  assert( xConflict!=0 );\n\n  pIter->in.bNoDiscard = 1;\n  memset(&sApply, 0, sizeof(sApply));\n  sApply.bRebase = (ppRebase && pnRebase);\n  sqlite3_mutex_enter(sqlite3_db_mutex(db));\n  if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){\n    rc = sqlite3_exec(db, \"SAVEPOINT changeset_apply\", 0, 0, 0);\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_exec(db, \"PRAGMA defer_foreign_keys = 1\", 0, 0, 0);\n  }\n  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){\n    int nCol;\n    int op;\n    const char *zNew;\n    \n    sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);\n\n    if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){\n      u8 *abPK;\n\n      rc = sessionRetryConstraints(\n          db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx\n      );\n      if( rc!=SQLITE_OK ) break;\n\n      sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */\n      sqlite3_finalize(sApply.pDelete);\n      sqlite3_finalize(sApply.pUpdate); \n      sqlite3_finalize(sApply.pInsert);\n      sqlite3_finalize(sApply.pSelect);\n      sApply.db = db;\n      sApply.pDelete = 0;\n      sApply.pUpdate = 0;\n      sApply.pInsert = 0;\n      sApply.pSelect = 0;\n      sApply.nCol = 0;\n      sApply.azCol = 0;\n      sApply.abPK = 0;\n      sApply.bStat1 = 0;\n      sApply.bDeferConstraints = 1;\n      sApply.bRebaseStarted = 0;\n      memset(&sApply.constraints, 0, sizeof(SessionBuffer));\n\n      /* If an xFilter() callback was specified, invoke it now. If the \n      ** xFilter callback returns zero, skip this table. If it returns\n      ** non-zero, proceed. */\n      schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));\n      if( schemaMismatch ){\n        zTab = sqlite3_mprintf(\"%s\", zNew);\n        if( zTab==0 ){\n          rc = SQLITE_NOMEM;\n          break;\n        }\n        nTab = (int)strlen(zTab);\n        sApply.azCol = (const char **)zTab;\n      }else{\n        int nMinCol = 0;\n        int i;\n\n        sqlite3changeset_pk(pIter, &abPK, 0);\n        rc = sessionTableInfo(\n            db, \"main\", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK\n        );\n        if( rc!=SQLITE_OK ) break;\n        for(i=0; i<sApply.nCol; i++){\n          if( sApply.abPK[i] ) nMinCol = i+1;\n        }\n  \n        if( sApply.nCol==0 ){\n          schemaMismatch = 1;\n          sqlite3_log(SQLITE_SCHEMA, \n              \"sqlite3changeset_apply(): no such table: %s\", zTab\n          );\n        }\n        else if( sApply.nCol<nCol ){\n          schemaMismatch = 1;\n          sqlite3_log(SQLITE_SCHEMA, \n              \"sqlite3changeset_apply(): table %s has %d columns, \"\n              \"expected %d or more\", \n              zTab, sApply.nCol, nCol\n          );\n        }\n        else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){\n          schemaMismatch = 1;\n          sqlite3_log(SQLITE_SCHEMA, \"sqlite3changeset_apply(): \"\n              \"primary key mismatch for table %s\", zTab\n          );\n        }\n        else{\n          sApply.nCol = nCol;\n          if( 0==sqlite3_stricmp(zTab, \"sqlite_stat1\") ){\n            if( (rc = sessionStat1Sql(db, &sApply) ) ){\n              break;\n            }\n            sApply.bStat1 = 1;\n          }else{\n            if((rc = sessionSelectRow(db, zTab, &sApply))\n                || (rc = sessionUpdateRow(db, zTab, &sApply))\n                || (rc = sessionDeleteRow(db, zTab, &sApply))\n                || (rc = sessionInsertRow(db, zTab, &sApply))\n              ){\n              break;\n            }\n            sApply.bStat1 = 0;\n          }\n        }\n        nTab = sqlite3Strlen30(zTab);\n      }\n    }\n\n    /* If there is a schema mismatch on the current table, proceed to the\n    ** next change. A log message has already been issued. */\n    if( schemaMismatch ) continue;\n\n    rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);\n  }\n\n  bPatchset = pIter->bPatchset;\n  if( rc==SQLITE_OK ){\n    rc = sqlite3changeset_finalize(pIter);\n  }else{\n    sqlite3changeset_finalize(pIter);\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);\n  }\n\n  if( rc==SQLITE_OK ){\n    int nFk, notUsed;\n    sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);\n    if( nFk!=0 ){\n      int res = SQLITE_CHANGESET_ABORT;\n      sqlite3_changeset_iter sIter;\n      memset(&sIter, 0, sizeof(sIter));\n      sIter.nCol = nFk;\n      res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);\n      if( res!=SQLITE_CHANGESET_OMIT ){\n        rc = SQLITE_CONSTRAINT;\n      }\n    }\n  }\n  sqlite3_exec(db, \"PRAGMA defer_foreign_keys = 0\", 0, 0, 0);\n\n  if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){\n    if( rc==SQLITE_OK ){\n      rc = sqlite3_exec(db, \"RELEASE changeset_apply\", 0, 0, 0);\n    }else{\n      sqlite3_exec(db, \"ROLLBACK TO changeset_apply\", 0, 0, 0);\n      sqlite3_exec(db, \"RELEASE changeset_apply\", 0, 0, 0);\n    }\n  }\n\n  assert( sApply.bRebase || sApply.rebase.nBuf==0 );\n  if( rc==SQLITE_OK && bPatchset==0 && sApply.bRebase ){\n    *ppRebase = (void*)sApply.rebase.aBuf;\n    *pnRebase = sApply.rebase.nBuf;\n    sApply.rebase.aBuf = 0;\n  }\n  sqlite3_finalize(sApply.pInsert);\n  sqlite3_finalize(sApply.pDelete);\n  sqlite3_finalize(sApply.pUpdate);\n  sqlite3_finalize(sApply.pSelect);\n  sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */\n  sqlite3_free((char*)sApply.constraints.aBuf);\n  sqlite3_free((char*)sApply.rebase.aBuf);\n  sqlite3_mutex_leave(sqlite3_db_mutex(db));\n  return rc;\n}\n\n/*\n** Apply the changeset passed via pChangeset/nChangeset to the main \n** database attached to handle \"db\".\n*/\nSQLITE_API int sqlite3changeset_apply_v2(\n  sqlite3 *db,                    /* Apply change to \"main\" db of this handle */\n  int nChangeset,                 /* Size of changeset in bytes */\n  void *pChangeset,               /* Changeset blob */\n  int(*xFilter)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    const char *zTab              /* Table name */\n  ),\n  int(*xConflict)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */\n    sqlite3_changeset_iter *p     /* Handle describing change and conflict */\n  ),\n  void *pCtx,                     /* First argument passed to xConflict */\n  void **ppRebase, int *pnRebase,\n  int flags\n){\n  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */  \n  int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);\n  int rc = sessionChangesetStart(&pIter, 0, 0, nChangeset, pChangeset,bInverse);\n  if( rc==SQLITE_OK ){\n    rc = sessionChangesetApply(\n        db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags\n    );\n  }\n  return rc;\n}\n\n/*\n** Apply the changeset passed via pChangeset/nChangeset to the main database\n** attached to handle \"db\". Invoke the supplied conflict handler callback\n** to resolve any conflicts encountered while applying the change.\n*/\nSQLITE_API int sqlite3changeset_apply(\n  sqlite3 *db,                    /* Apply change to \"main\" db of this handle */\n  int nChangeset,                 /* Size of changeset in bytes */\n  void *pChangeset,               /* Changeset blob */\n  int(*xFilter)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    const char *zTab              /* Table name */\n  ),\n  int(*xConflict)(\n    void *pCtx,                   /* Copy of fifth arg to _apply() */\n    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */\n    sqlite3_changeset_iter *p     /* Handle describing change and conflict */\n  ),\n  void *pCtx                      /* First argument passed to xConflict */\n){\n  return sqlite3changeset_apply_v2(\n      db, nChangeset, pChangeset, xFilter, xConflict, pCtx, 0, 0, 0\n  );\n}\n\n/*\n** Apply the changeset passed via xInput/pIn to the main database\n** attached to handle \"db\". Invoke the supplied conflict handler callback\n** to resolve any conflicts encountered while applying the change.\n*/\nSQLITE_API int sqlite3changeset_apply_v2_strm(\n  sqlite3 *db,                    /* Apply change to \"main\" db of this handle */\n  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */\n  void *pIn,                                          /* First arg for xInput */\n  int(*xFilter)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    const char *zTab              /* Table name */\n  ),\n  int(*xConflict)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */\n    sqlite3_changeset_iter *p     /* Handle describing change and conflict */\n  ),\n  void *pCtx,                     /* First argument passed to xConflict */\n  void **ppRebase, int *pnRebase,\n  int flags\n){\n  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */  \n  int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);\n  int rc = sessionChangesetStart(&pIter, xInput, pIn, 0, 0, bInverse);\n  if( rc==SQLITE_OK ){\n    rc = sessionChangesetApply(\n        db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags\n    );\n  }\n  return rc;\n}\nSQLITE_API int sqlite3changeset_apply_strm(\n  sqlite3 *db,                    /* Apply change to \"main\" db of this handle */\n  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */\n  void *pIn,                                          /* First arg for xInput */\n  int(*xFilter)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    const char *zTab              /* Table name */\n  ),\n  int(*xConflict)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */\n    sqlite3_changeset_iter *p     /* Handle describing change and conflict */\n  ),\n  void *pCtx                      /* First argument passed to xConflict */\n){\n  return sqlite3changeset_apply_v2_strm(\n      db, xInput, pIn, xFilter, xConflict, pCtx, 0, 0, 0\n  );\n}\n\n/*\n** sqlite3_changegroup handle.\n*/\nstruct sqlite3_changegroup {\n  int rc;                         /* Error code */\n  int bPatch;                     /* True to accumulate patchsets */\n  SessionTable *pList;            /* List of tables in current patch */\n};\n\n/*\n** This function is called to merge two changes to the same row together as\n** part of an sqlite3changeset_concat() operation. A new change object is\n** allocated and a pointer to it stored in *ppNew.\n*/\nstatic int sessionChangeMerge(\n  SessionTable *pTab,             /* Table structure */\n  int bRebase,                    /* True for a rebase hash-table */\n  int bPatchset,                  /* True for patchsets */\n  SessionChange *pExist,          /* Existing change */\n  int op2,                        /* Second change operation */\n  int bIndirect,                  /* True if second change is indirect */\n  u8 *aRec,                       /* Second change record */\n  int nRec,                       /* Number of bytes in aRec */\n  SessionChange **ppNew           /* OUT: Merged change */\n){\n  SessionChange *pNew = 0;\n  int rc = SQLITE_OK;\n\n  if( !pExist ){\n    pNew = (SessionChange *)sqlite3_malloc64(sizeof(SessionChange) + nRec);\n    if( !pNew ){\n      return SQLITE_NOMEM;\n    }\n    memset(pNew, 0, sizeof(SessionChange));\n    pNew->op = op2;\n    pNew->bIndirect = bIndirect;\n    pNew->aRecord = (u8*)&pNew[1];\n    if( bIndirect==0 || bRebase==0 ){\n      pNew->nRecord = nRec;\n      memcpy(pNew->aRecord, aRec, nRec);\n    }else{\n      int i;\n      u8 *pIn = aRec;\n      u8 *pOut = pNew->aRecord;\n      for(i=0; i<pTab->nCol; i++){\n        int nIn = sessionSerialLen(pIn);\n        if( *pIn==0 ){\n          *pOut++ = 0;\n        }else if( pTab->abPK[i]==0 ){\n          *pOut++ = 0xFF;\n        }else{\n          memcpy(pOut, pIn, nIn);\n          pOut += nIn;\n        }\n        pIn += nIn;\n      }\n      pNew->nRecord = pOut - pNew->aRecord;\n    }\n  }else if( bRebase ){\n    if( pExist->op==SQLITE_DELETE && pExist->bIndirect ){\n      *ppNew = pExist;\n    }else{\n      sqlite3_int64 nByte = nRec + pExist->nRecord + sizeof(SessionChange);\n      pNew = (SessionChange*)sqlite3_malloc64(nByte);\n      if( pNew==0 ){\n        rc = SQLITE_NOMEM;\n      }else{\n        int i;\n        u8 *a1 = pExist->aRecord;\n        u8 *a2 = aRec;\n        u8 *pOut;\n\n        memset(pNew, 0, nByte);\n        pNew->bIndirect = bIndirect || pExist->bIndirect;\n        pNew->op = op2;\n        pOut = pNew->aRecord = (u8*)&pNew[1];\n\n        for(i=0; i<pTab->nCol; i++){\n          int n1 = sessionSerialLen(a1);\n          int n2 = sessionSerialLen(a2);\n          if( *a1==0xFF || (pTab->abPK[i]==0 && bIndirect) ){\n            *pOut++ = 0xFF;\n          }else if( *a2==0 ){\n            memcpy(pOut, a1, n1);\n            pOut += n1;\n          }else{\n            memcpy(pOut, a2, n2);\n            pOut += n2;\n          }\n          a1 += n1;\n          a2 += n2;\n        }\n        pNew->nRecord = pOut - pNew->aRecord;\n      }\n      sqlite3_free(pExist);\n    }\n  }else{\n    int op1 = pExist->op;\n\n    /* \n    **   op1=INSERT, op2=INSERT      ->      Unsupported. Discard op2.\n    **   op1=INSERT, op2=UPDATE      ->      INSERT.\n    **   op1=INSERT, op2=DELETE      ->      (none)\n    **\n    **   op1=UPDATE, op2=INSERT      ->      Unsupported. Discard op2.\n    **   op1=UPDATE, op2=UPDATE      ->      UPDATE.\n    **   op1=UPDATE, op2=DELETE      ->      DELETE.\n    **\n    **   op1=DELETE, op2=INSERT      ->      UPDATE.\n    **   op1=DELETE, op2=UPDATE      ->      Unsupported. Discard op2.\n    **   op1=DELETE, op2=DELETE      ->      Unsupported. Discard op2.\n    */   \n    if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)\n     || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)\n     || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)\n     || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)\n    ){\n      pNew = pExist;\n    }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){\n      sqlite3_free(pExist);\n      assert( pNew==0 );\n    }else{\n      u8 *aExist = pExist->aRecord;\n      sqlite3_int64 nByte;\n      u8 *aCsr;\n\n      /* Allocate a new SessionChange object. Ensure that the aRecord[]\n      ** buffer of the new object is large enough to hold any record that\n      ** may be generated by combining the input records.  */\n      nByte = sizeof(SessionChange) + pExist->nRecord + nRec;\n      pNew = (SessionChange *)sqlite3_malloc64(nByte);\n      if( !pNew ){\n        sqlite3_free(pExist);\n        return SQLITE_NOMEM;\n      }\n      memset(pNew, 0, sizeof(SessionChange));\n      pNew->bIndirect = (bIndirect && pExist->bIndirect);\n      aCsr = pNew->aRecord = (u8 *)&pNew[1];\n\n      if( op1==SQLITE_INSERT ){             /* INSERT + UPDATE */\n        u8 *a1 = aRec;\n        assert( op2==SQLITE_UPDATE );\n        pNew->op = SQLITE_INSERT;\n        if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);\n        sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);\n      }else if( op1==SQLITE_DELETE ){       /* DELETE + INSERT */\n        assert( op2==SQLITE_INSERT );\n        pNew->op = SQLITE_UPDATE;\n        if( bPatchset ){\n          memcpy(aCsr, aRec, nRec);\n          aCsr += nRec;\n        }else{\n          if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){\n            sqlite3_free(pNew);\n            pNew = 0;\n          }\n        }\n      }else if( op2==SQLITE_UPDATE ){       /* UPDATE + UPDATE */\n        u8 *a1 = aExist;\n        u8 *a2 = aRec;\n        assert( op1==SQLITE_UPDATE );\n        if( bPatchset==0 ){\n          sessionSkipRecord(&a1, pTab->nCol);\n          sessionSkipRecord(&a2, pTab->nCol);\n        }\n        pNew->op = SQLITE_UPDATE;\n        if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){\n          sqlite3_free(pNew);\n          pNew = 0;\n        }\n      }else{                                /* UPDATE + DELETE */\n        assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );\n        pNew->op = SQLITE_DELETE;\n        if( bPatchset ){\n          memcpy(aCsr, aRec, nRec);\n          aCsr += nRec;\n        }else{\n          sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);\n        }\n      }\n\n      if( pNew ){\n        pNew->nRecord = (int)(aCsr - pNew->aRecord);\n      }\n      sqlite3_free(pExist);\n    }\n  }\n\n  *ppNew = pNew;\n  return rc;\n}\n\n/*\n** Add all changes in the changeset traversed by the iterator passed as\n** the first argument to the changegroup hash tables.\n*/\nstatic int sessionChangesetToHash(\n  sqlite3_changeset_iter *pIter,   /* Iterator to read from */\n  sqlite3_changegroup *pGrp,       /* Changegroup object to add changeset to */\n  int bRebase                      /* True if hash table is for rebasing */\n){\n  u8 *aRec;\n  int nRec;\n  int rc = SQLITE_OK;\n  SessionTable *pTab = 0;\n\n  while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, 0) ){\n    const char *zNew;\n    int nCol;\n    int op;\n    int iHash;\n    int bIndirect;\n    SessionChange *pChange;\n    SessionChange *pExist = 0;\n    SessionChange **pp;\n\n    if( pGrp->pList==0 ){\n      pGrp->bPatch = pIter->bPatchset;\n    }else if( pIter->bPatchset!=pGrp->bPatch ){\n      rc = SQLITE_ERROR;\n      break;\n    }\n\n    sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);\n    if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){\n      /* Search the list for a matching table */\n      int nNew = (int)strlen(zNew);\n      u8 *abPK;\n\n      sqlite3changeset_pk(pIter, &abPK, 0);\n      for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){\n        if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;\n      }\n      if( !pTab ){\n        SessionTable **ppTab;\n\n        pTab = sqlite3_malloc64(sizeof(SessionTable) + nCol + nNew+1);\n        if( !pTab ){\n          rc = SQLITE_NOMEM;\n          break;\n        }\n        memset(pTab, 0, sizeof(SessionTable));\n        pTab->nCol = nCol;\n        pTab->abPK = (u8*)&pTab[1];\n        memcpy(pTab->abPK, abPK, nCol);\n        pTab->zName = (char*)&pTab->abPK[nCol];\n        memcpy(pTab->zName, zNew, nNew+1);\n\n        /* The new object must be linked on to the end of the list, not\n        ** simply added to the start of it. This is to ensure that the\n        ** tables within the output of sqlite3changegroup_output() are in \n        ** the right order.  */\n        for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);\n        *ppTab = pTab;\n      }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){\n        rc = SQLITE_SCHEMA;\n        break;\n      }\n    }\n\n    if( sessionGrowHash(pIter->bPatchset, pTab) ){\n      rc = SQLITE_NOMEM;\n      break;\n    }\n    iHash = sessionChangeHash(\n        pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange\n    );\n\n    /* Search for existing entry. If found, remove it from the hash table. \n    ** Code below may link it back in.\n    */\n    for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){\n      int bPkOnly1 = 0;\n      int bPkOnly2 = 0;\n      if( pIter->bPatchset ){\n        bPkOnly1 = (*pp)->op==SQLITE_DELETE;\n        bPkOnly2 = op==SQLITE_DELETE;\n      }\n      if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){\n        pExist = *pp;\n        *pp = (*pp)->pNext;\n        pTab->nEntry--;\n        break;\n      }\n    }\n\n    rc = sessionChangeMerge(pTab, bRebase, \n        pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange\n    );\n    if( rc ) break;\n    if( pChange ){\n      pChange->pNext = pTab->apChange[iHash];\n      pTab->apChange[iHash] = pChange;\n      pTab->nEntry++;\n    }\n  }\n\n  if( rc==SQLITE_OK ) rc = pIter->rc;\n  return rc;\n}\n\n/*\n** Serialize a changeset (or patchset) based on all changesets (or patchsets)\n** added to the changegroup object passed as the first argument.\n**\n** If xOutput is not NULL, then the changeset/patchset is returned to the\n** user via one or more calls to xOutput, as with the other streaming\n** interfaces. \n**\n** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a\n** buffer containing the output changeset before this function returns. In\n** this case (*pnOut) is set to the size of the output buffer in bytes. It\n** is the responsibility of the caller to free the output buffer using\n** sqlite3_free() when it is no longer required.\n**\n** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite\n** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)\n** are both set to 0 before returning.\n*/\nstatic int sessionChangegroupOutput(\n  sqlite3_changegroup *pGrp,\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut,\n  int *pnOut,\n  void **ppOut\n){\n  int rc = SQLITE_OK;\n  SessionBuffer buf = {0, 0, 0};\n  SessionTable *pTab;\n  assert( xOutput==0 || (ppOut==0 && pnOut==0) );\n\n  /* Create the serialized output changeset based on the contents of the\n  ** hash tables attached to the SessionTable objects in list p->pList. \n  */\n  for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){\n    int i;\n    if( pTab->nEntry==0 ) continue;\n\n    sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);\n    for(i=0; i<pTab->nChange; i++){\n      SessionChange *p;\n      for(p=pTab->apChange[i]; p; p=p->pNext){\n        sessionAppendByte(&buf, p->op, &rc);\n        sessionAppendByte(&buf, p->bIndirect, &rc);\n        sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);\n        if( rc==SQLITE_OK && xOutput && buf.nBuf>=sessions_strm_chunk_size ){\n          rc = xOutput(pOut, buf.aBuf, buf.nBuf);\n          buf.nBuf = 0;\n        }\n      }\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    if( xOutput ){\n      if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);\n    }else{\n      *ppOut = buf.aBuf;\n      *pnOut = buf.nBuf;\n      buf.aBuf = 0;\n    }\n  }\n  sqlite3_free(buf.aBuf);\n\n  return rc;\n}\n\n/*\n** Allocate a new, empty, sqlite3_changegroup.\n*/\nSQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){\n  int rc = SQLITE_OK;             /* Return code */\n  sqlite3_changegroup *p;         /* New object */\n  p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));\n  if( p==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    memset(p, 0, sizeof(sqlite3_changegroup));\n  }\n  *pp = p;\n  return rc;\n}\n\n/*\n** Add the changeset currently stored in buffer pData, size nData bytes,\n** to changeset-group p.\n*/\nSQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){\n  sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */\n  int rc;                         /* Return code */\n\n  rc = sqlite3changeset_start(&pIter, nData, pData);\n  if( rc==SQLITE_OK ){\n    rc = sessionChangesetToHash(pIter, pGrp, 0);\n  }\n  sqlite3changeset_finalize(pIter);\n  return rc;\n}\n\n/*\n** Obtain a buffer containing a changeset representing the concatenation\n** of all changesets added to the group so far.\n*/\nSQLITE_API int sqlite3changegroup_output(\n    sqlite3_changegroup *pGrp,\n    int *pnData,\n    void **ppData\n){\n  return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);\n}\n\n/*\n** Streaming versions of changegroup_add().\n*/\nSQLITE_API int sqlite3changegroup_add_strm(\n  sqlite3_changegroup *pGrp,\n  int (*xInput)(void *pIn, void *pData, int *pnData),\n  void *pIn\n){\n  sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */\n  int rc;                         /* Return code */\n\n  rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);\n  if( rc==SQLITE_OK ){\n    rc = sessionChangesetToHash(pIter, pGrp, 0);\n  }\n  sqlite3changeset_finalize(pIter);\n  return rc;\n}\n\n/*\n** Streaming versions of changegroup_output().\n*/\nSQLITE_API int sqlite3changegroup_output_strm(\n  sqlite3_changegroup *pGrp,\n  int (*xOutput)(void *pOut, const void *pData, int nData), \n  void *pOut\n){\n  return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);\n}\n\n/*\n** Delete a changegroup object.\n*/\nSQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){\n  if( pGrp ){\n    sessionDeleteTable(pGrp->pList);\n    sqlite3_free(pGrp);\n  }\n}\n\n/* \n** Combine two changesets together.\n*/\nSQLITE_API int sqlite3changeset_concat(\n  int nLeft,                      /* Number of bytes in lhs input */\n  void *pLeft,                    /* Lhs input changeset */\n  int nRight                      /* Number of bytes in rhs input */,\n  void *pRight,                   /* Rhs input changeset */\n  int *pnOut,                     /* OUT: Number of bytes in output changeset */\n  void **ppOut                    /* OUT: changeset (left <concat> right) */\n){\n  sqlite3_changegroup *pGrp;\n  int rc;\n\n  rc = sqlite3changegroup_new(&pGrp);\n  if( rc==SQLITE_OK ){\n    rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3changegroup_add(pGrp, nRight, pRight);\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);\n  }\n  sqlite3changegroup_delete(pGrp);\n\n  return rc;\n}\n\n/*\n** Streaming version of sqlite3changeset_concat().\n*/\nSQLITE_API int sqlite3changeset_concat_strm(\n  int (*xInputA)(void *pIn, void *pData, int *pnData),\n  void *pInA,\n  int (*xInputB)(void *pIn, void *pData, int *pnData),\n  void *pInB,\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut\n){\n  sqlite3_changegroup *pGrp;\n  int rc;\n\n  rc = sqlite3changegroup_new(&pGrp);\n  if( rc==SQLITE_OK ){\n    rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);\n  }\n  sqlite3changegroup_delete(pGrp);\n\n  return rc;\n}\n\n/*\n** Changeset rebaser handle.\n*/\nstruct sqlite3_rebaser {\n  sqlite3_changegroup grp;        /* Hash table */\n};\n\n/*\n** Buffers a1 and a2 must both contain a sessions module record nCol\n** fields in size. This function appends an nCol sessions module \n** record to buffer pBuf that is a copy of a1, except that for\n** each field that is undefined in a1[], swap in the field from a2[].\n*/\nstatic void sessionAppendRecordMerge(\n  SessionBuffer *pBuf,            /* Buffer to append to */\n  int nCol,                       /* Number of columns in each record */\n  u8 *a1, int n1,                 /* Record 1 */\n  u8 *a2, int n2,                 /* Record 2 */\n  int *pRc                        /* IN/OUT: error code */\n){\n  sessionBufferGrow(pBuf, n1+n2, pRc);\n  if( *pRc==SQLITE_OK ){\n    int i;\n    u8 *pOut = &pBuf->aBuf[pBuf->nBuf];\n    for(i=0; i<nCol; i++){\n      int nn1 = sessionSerialLen(a1);\n      int nn2 = sessionSerialLen(a2);\n      if( *a1==0 || *a1==0xFF ){\n        memcpy(pOut, a2, nn2);\n        pOut += nn2;\n      }else{\n        memcpy(pOut, a1, nn1);\n        pOut += nn1;\n      }\n      a1 += nn1;\n      a2 += nn2;\n    }\n\n    pBuf->nBuf = pOut-pBuf->aBuf;\n    assert( pBuf->nBuf<=pBuf->nAlloc );\n  }\n}\n\n/*\n** This function is called when rebasing a local UPDATE change against one \n** or more remote UPDATE changes. The aRec/nRec buffer contains the current\n** old.* and new.* records for the change. The rebase buffer (a single\n** record) is in aChange/nChange. The rebased change is appended to buffer\n** pBuf.\n**\n** Rebasing the UPDATE involves: \n**\n**   * Removing any changes to fields for which the corresponding field\n**     in the rebase buffer is set to \"replaced\" (type 0xFF). If this\n**     means the UPDATE change updates no fields, nothing is appended\n**     to the output buffer.\n**\n**   * For each field modified by the local change for which the \n**     corresponding field in the rebase buffer is not \"undefined\" (0x00)\n**     or \"replaced\" (0xFF), the old.* value is replaced by the value\n**     in the rebase buffer.\n*/\nstatic void sessionAppendPartialUpdate(\n  SessionBuffer *pBuf,            /* Append record here */\n  sqlite3_changeset_iter *pIter,  /* Iterator pointed at local change */\n  u8 *aRec, int nRec,             /* Local change */\n  u8 *aChange, int nChange,       /* Record to rebase against */\n  int *pRc                        /* IN/OUT: Return Code */\n){\n  sessionBufferGrow(pBuf, 2+nRec+nChange, pRc);\n  if( *pRc==SQLITE_OK ){\n    int bData = 0;\n    u8 *pOut = &pBuf->aBuf[pBuf->nBuf];\n    int i;\n    u8 *a1 = aRec;\n    u8 *a2 = aChange;\n\n    *pOut++ = SQLITE_UPDATE;\n    *pOut++ = pIter->bIndirect;\n    for(i=0; i<pIter->nCol; i++){\n      int n1 = sessionSerialLen(a1);\n      int n2 = sessionSerialLen(a2);\n      if( pIter->abPK[i] || a2[0]==0 ){\n        if( !pIter->abPK[i] ) bData = 1;\n        memcpy(pOut, a1, n1);\n        pOut += n1;\n      }else if( a2[0]!=0xFF ){\n        bData = 1;\n        memcpy(pOut, a2, n2);\n        pOut += n2;\n      }else{\n        *pOut++ = '\\0';\n      }\n      a1 += n1;\n      a2 += n2;\n    }\n    if( bData ){\n      a2 = aChange;\n      for(i=0; i<pIter->nCol; i++){\n        int n1 = sessionSerialLen(a1);\n        int n2 = sessionSerialLen(a2);\n        if( pIter->abPK[i] || a2[0]!=0xFF ){\n          memcpy(pOut, a1, n1);\n          pOut += n1;\n        }else{\n          *pOut++ = '\\0';\n        }\n        a1 += n1;\n        a2 += n2;\n      }\n      pBuf->nBuf = (pOut - pBuf->aBuf);\n    }\n  }\n}\n\n/*\n** pIter is configured to iterate through a changeset. This function rebases \n** that changeset according to the current configuration of the rebaser \n** object passed as the first argument. If no error occurs and argument xOutput\n** is not NULL, then the changeset is returned to the caller by invoking\n** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL,\n** then (*ppOut) is set to point to a buffer containing the rebased changeset\n** before this function returns. In this case (*pnOut) is set to the size of\n** the buffer in bytes.  It is the responsibility of the caller to eventually\n** free the (*ppOut) buffer using sqlite3_free(). \n**\n** If an error occurs, an SQLite error code is returned. If ppOut and\n** pnOut are not NULL, then the two output parameters are set to 0 before\n** returning.\n*/\nstatic int sessionRebase(\n  sqlite3_rebaser *p,             /* Rebaser hash table */\n  sqlite3_changeset_iter *pIter,  /* Input data */\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut,                     /* Context for xOutput callback */\n  int *pnOut,                     /* OUT: Number of bytes in output changeset */\n  void **ppOut                    /* OUT: Inverse of pChangeset */\n){\n  int rc = SQLITE_OK;\n  u8 *aRec = 0;\n  int nRec = 0;\n  int bNew = 0;\n  SessionTable *pTab = 0;\n  SessionBuffer sOut = {0,0,0};\n\n  while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, &bNew) ){\n    SessionChange *pChange = 0;\n    int bDone = 0;\n\n    if( bNew ){\n      const char *zTab = pIter->zTab;\n      for(pTab=p->grp.pList; pTab; pTab=pTab->pNext){\n        if( 0==sqlite3_stricmp(pTab->zName, zTab) ) break;\n      }\n      bNew = 0;\n\n      /* A patchset may not be rebased */\n      if( pIter->bPatchset ){\n        rc = SQLITE_ERROR;\n      }\n\n      /* Append a table header to the output for this new table */\n      sessionAppendByte(&sOut, pIter->bPatchset ? 'P' : 'T', &rc);\n      sessionAppendVarint(&sOut, pIter->nCol, &rc);\n      sessionAppendBlob(&sOut, pIter->abPK, pIter->nCol, &rc);\n      sessionAppendBlob(&sOut,(u8*)pIter->zTab,(int)strlen(pIter->zTab)+1,&rc);\n    }\n\n    if( pTab && rc==SQLITE_OK ){\n      int iHash = sessionChangeHash(pTab, 0, aRec, pTab->nChange);\n\n      for(pChange=pTab->apChange[iHash]; pChange; pChange=pChange->pNext){\n        if( sessionChangeEqual(pTab, 0, aRec, 0, pChange->aRecord) ){\n          break;\n        }\n      }\n    }\n\n    if( pChange ){\n      assert( pChange->op==SQLITE_DELETE || pChange->op==SQLITE_INSERT );\n      switch( pIter->op ){\n        case SQLITE_INSERT:\n          if( pChange->op==SQLITE_INSERT ){\n            bDone = 1;\n            if( pChange->bIndirect==0 ){\n              sessionAppendByte(&sOut, SQLITE_UPDATE, &rc);\n              sessionAppendByte(&sOut, pIter->bIndirect, &rc);\n              sessionAppendBlob(&sOut, pChange->aRecord, pChange->nRecord, &rc);\n              sessionAppendBlob(&sOut, aRec, nRec, &rc);\n            }\n          }\n          break;\n\n        case SQLITE_UPDATE:\n          bDone = 1;\n          if( pChange->op==SQLITE_DELETE ){\n            if( pChange->bIndirect==0 ){\n              u8 *pCsr = aRec;\n              sessionSkipRecord(&pCsr, pIter->nCol);\n              sessionAppendByte(&sOut, SQLITE_INSERT, &rc);\n              sessionAppendByte(&sOut, pIter->bIndirect, &rc);\n              sessionAppendRecordMerge(&sOut, pIter->nCol,\n                  pCsr, nRec-(pCsr-aRec), \n                  pChange->aRecord, pChange->nRecord, &rc\n              );\n            }\n          }else{\n            sessionAppendPartialUpdate(&sOut, pIter,\n                aRec, nRec, pChange->aRecord, pChange->nRecord, &rc\n            );\n          }\n          break;\n\n        default:\n          assert( pIter->op==SQLITE_DELETE );\n          bDone = 1;\n          if( pChange->op==SQLITE_INSERT ){\n            sessionAppendByte(&sOut, SQLITE_DELETE, &rc);\n            sessionAppendByte(&sOut, pIter->bIndirect, &rc);\n            sessionAppendRecordMerge(&sOut, pIter->nCol,\n                pChange->aRecord, pChange->nRecord, aRec, nRec, &rc\n            );\n          }\n          break;\n      }\n    }\n\n    if( bDone==0 ){\n      sessionAppendByte(&sOut, pIter->op, &rc);\n      sessionAppendByte(&sOut, pIter->bIndirect, &rc);\n      sessionAppendBlob(&sOut, aRec, nRec, &rc);\n    }\n    if( rc==SQLITE_OK && xOutput && sOut.nBuf>sessions_strm_chunk_size ){\n      rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);\n      sOut.nBuf = 0;\n    }\n    if( rc ) break;\n  }\n\n  if( rc!=SQLITE_OK ){\n    sqlite3_free(sOut.aBuf);\n    memset(&sOut, 0, sizeof(sOut));\n  }\n\n  if( rc==SQLITE_OK ){\n    if( xOutput ){\n      if( sOut.nBuf>0 ){\n        rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);\n      }\n    }else{\n      *ppOut = (void*)sOut.aBuf;\n      *pnOut = sOut.nBuf;\n      sOut.aBuf = 0;\n    }\n  }\n  sqlite3_free(sOut.aBuf);\n  return rc;\n}\n\n/* \n** Create a new rebaser object.\n*/\nSQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew){\n  int rc = SQLITE_OK;\n  sqlite3_rebaser *pNew;\n\n  pNew = sqlite3_malloc(sizeof(sqlite3_rebaser));\n  if( pNew==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    memset(pNew, 0, sizeof(sqlite3_rebaser));\n  }\n  *ppNew = pNew;\n  return rc;\n}\n\n/* \n** Call this one or more times to configure a rebaser.\n*/\nSQLITE_API int sqlite3rebaser_configure(\n  sqlite3_rebaser *p, \n  int nRebase, const void *pRebase\n){\n  sqlite3_changeset_iter *pIter = 0;   /* Iterator opened on pData/nData */\n  int rc;                              /* Return code */\n  rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase);\n  if( rc==SQLITE_OK ){\n    rc = sessionChangesetToHash(pIter, &p->grp, 1);\n  }\n  sqlite3changeset_finalize(pIter);\n  return rc;\n}\n\n/* \n** Rebase a changeset according to current rebaser configuration \n*/\nSQLITE_API int sqlite3rebaser_rebase(\n  sqlite3_rebaser *p,\n  int nIn, const void *pIn, \n  int *pnOut, void **ppOut \n){\n  sqlite3_changeset_iter *pIter = 0;   /* Iterator to skip through input */  \n  int rc = sqlite3changeset_start(&pIter, nIn, (void*)pIn);\n\n  if( rc==SQLITE_OK ){\n    rc = sessionRebase(p, pIter, 0, 0, pnOut, ppOut);\n    sqlite3changeset_finalize(pIter);\n  }\n\n  return rc;\n}\n\n/* \n** Rebase a changeset according to current rebaser configuration \n*/\nSQLITE_API int sqlite3rebaser_rebase_strm(\n  sqlite3_rebaser *p,\n  int (*xInput)(void *pIn, void *pData, int *pnData),\n  void *pIn,\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut\n){\n  sqlite3_changeset_iter *pIter = 0;   /* Iterator to skip through input */  \n  int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);\n\n  if( rc==SQLITE_OK ){\n    rc = sessionRebase(p, pIter, xOutput, pOut, 0, 0);\n    sqlite3changeset_finalize(pIter);\n  }\n\n  return rc;\n}\n\n/* \n** Destroy a rebaser object \n*/\nSQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p){\n  if( p ){\n    sessionDeleteTable(p->grp.pList);\n    sqlite3_free(p);\n  }\n}\n\n/* \n** Global configuration\n*/\nSQLITE_API int sqlite3session_config(int op, void *pArg){\n  int rc = SQLITE_OK;\n  switch( op ){\n    case SQLITE_SESSION_CONFIG_STRMSIZE: {\n      int *pInt = (int*)pArg;\n      if( *pInt>0 ){\n        sessions_strm_chunk_size = *pInt;\n      }\n      *pInt = sessions_strm_chunk_size;\n      break;\n    }\n    default:\n      rc = SQLITE_MISUSE;\n      break;\n  }\n  return rc;\n}\n\n#endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */\n\n/************** End of sqlite3session.c **************************************/\n/************** Begin file fts5.c ********************************************/\n\n\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) \n\n#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) \n# define NDEBUG 1\n#endif\n#if defined(NDEBUG) && defined(SQLITE_DEBUG)\n# undef NDEBUG\n#endif\n\n/*\n** 2014 May 31\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** Interfaces to extend FTS5. Using the interfaces defined in this file, \n** FTS5 may be extended with:\n**\n**     * custom tokenizers, and\n**     * custom auxiliary functions.\n*/\n\n\n#ifndef _FTS5_H\n#define _FTS5_H\n\n/* #include \"sqlite3.h\" */\n\n#if 0\nextern \"C\" {\n#endif\n\n/*************************************************************************\n** CUSTOM AUXILIARY FUNCTIONS\n**\n** Virtual table implementations may overload SQL functions by implementing\n** the sqlite3_module.xFindFunction() method.\n*/\n\ntypedef struct Fts5ExtensionApi Fts5ExtensionApi;\ntypedef struct Fts5Context Fts5Context;\ntypedef struct Fts5PhraseIter Fts5PhraseIter;\n\ntypedef void (*fts5_extension_function)(\n  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */\n  Fts5Context *pFts,              /* First arg to pass to pApi functions */\n  sqlite3_context *pCtx,          /* Context for returning result/error */\n  int nVal,                       /* Number of values in apVal[] array */\n  sqlite3_value **apVal           /* Array of trailing arguments */\n);\n\nstruct Fts5PhraseIter {\n  const unsigned char *a;\n  const unsigned char *b;\n};\n\n/*\n** EXTENSION API FUNCTIONS\n**\n** xUserData(pFts):\n**   Return a copy of the context pointer the extension function was \n**   registered with.\n**\n** xColumnTotalSize(pFts, iCol, pnToken):\n**   If parameter iCol is less than zero, set output variable *pnToken\n**   to the total number of tokens in the FTS5 table. Or, if iCol is\n**   non-negative but less than the number of columns in the table, return\n**   the total number of tokens in column iCol, considering all rows in \n**   the FTS5 table.\n**\n**   If parameter iCol is greater than or equal to the number of columns\n**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.\n**   an OOM condition or IO error), an appropriate SQLite error code is \n**   returned.\n**\n** xColumnCount(pFts):\n**   Return the number of columns in the table.\n**\n** xColumnSize(pFts, iCol, pnToken):\n**   If parameter iCol is less than zero, set output variable *pnToken\n**   to the total number of tokens in the current row. Or, if iCol is\n**   non-negative but less than the number of columns in the table, set\n**   *pnToken to the number of tokens in column iCol of the current row.\n**\n**   If parameter iCol is greater than or equal to the number of columns\n**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.\n**   an OOM condition or IO error), an appropriate SQLite error code is \n**   returned.\n**\n**   This function may be quite inefficient if used with an FTS5 table\n**   created with the \"columnsize=0\" option.\n**\n** xColumnText:\n**   This function attempts to retrieve the text of column iCol of the\n**   current document. If successful, (*pz) is set to point to a buffer\n**   containing the text in utf-8 encoding, (*pn) is set to the size in bytes\n**   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,\n**   if an error occurs, an SQLite error code is returned and the final values\n**   of (*pz) and (*pn) are undefined.\n**\n** xPhraseCount:\n**   Returns the number of phrases in the current query expression.\n**\n** xPhraseSize:\n**   Returns the number of tokens in phrase iPhrase of the query. Phrases\n**   are numbered starting from zero.\n**\n** xInstCount:\n**   Set *pnInst to the total number of occurrences of all phrases within\n**   the query within the current row. Return SQLITE_OK if successful, or\n**   an error code (i.e. SQLITE_NOMEM) if an error occurs.\n**\n**   This API can be quite slow if used with an FTS5 table created with the\n**   \"detail=none\" or \"detail=column\" option. If the FTS5 table is created \n**   with either \"detail=none\" or \"detail=column\" and \"content=\" option \n**   (i.e. if it is a contentless table), then this API always returns 0.\n**\n** xInst:\n**   Query for the details of phrase match iIdx within the current row.\n**   Phrase matches are numbered starting from zero, so the iIdx argument\n**   should be greater than or equal to zero and smaller than the value\n**   output by xInstCount().\n**\n**   Usually, output parameter *piPhrase is set to the phrase number, *piCol\n**   to the column in which it occurs and *piOff the token offset of the\n**   first token of the phrase. Returns SQLITE_OK if successful, or an error\n**   code (i.e. SQLITE_NOMEM) if an error occurs.\n**\n**   This API can be quite slow if used with an FTS5 table created with the\n**   \"detail=none\" or \"detail=column\" option. \n**\n** xRowid:\n**   Returns the rowid of the current row.\n**\n** xTokenize:\n**   Tokenize text using the tokenizer belonging to the FTS5 table.\n**\n** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):\n**   This API function is used to query the FTS table for phrase iPhrase\n**   of the current query. Specifically, a query equivalent to:\n**\n**       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid\n**\n**   with $p set to a phrase equivalent to the phrase iPhrase of the\n**   current query is executed. Any column filter that applies to\n**   phrase iPhrase of the current query is included in $p. For each \n**   row visited, the callback function passed as the fourth argument \n**   is invoked. The context and API objects passed to the callback \n**   function may be used to access the properties of each matched row.\n**   Invoking Api.xUserData() returns a copy of the pointer passed as \n**   the third argument to pUserData.\n**\n**   If the callback function returns any value other than SQLITE_OK, the\n**   query is abandoned and the xQueryPhrase function returns immediately.\n**   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.\n**   Otherwise, the error code is propagated upwards.\n**\n**   If the query runs to completion without incident, SQLITE_OK is returned.\n**   Or, if some error occurs before the query completes or is aborted by\n**   the callback, an SQLite error code is returned.\n**\n**\n** xSetAuxdata(pFts5, pAux, xDelete)\n**\n**   Save the pointer passed as the second argument as the extension function's \n**   \"auxiliary data\". The pointer may then be retrieved by the current or any\n**   future invocation of the same fts5 extension function made as part of\n**   the same MATCH query using the xGetAuxdata() API.\n**\n**   Each extension function is allocated a single auxiliary data slot for\n**   each FTS query (MATCH expression). If the extension function is invoked \n**   more than once for a single FTS query, then all invocations share a \n**   single auxiliary data context.\n**\n**   If there is already an auxiliary data pointer when this function is\n**   invoked, then it is replaced by the new pointer. If an xDelete callback\n**   was specified along with the original pointer, it is invoked at this\n**   point.\n**\n**   The xDelete callback, if one is specified, is also invoked on the\n**   auxiliary data pointer after the FTS5 query has finished.\n**\n**   If an error (e.g. an OOM condition) occurs within this function,\n**   the auxiliary data is set to NULL and an error code returned. If the\n**   xDelete parameter was not NULL, it is invoked on the auxiliary data\n**   pointer before returning.\n**\n**\n** xGetAuxdata(pFts5, bClear)\n**\n**   Returns the current auxiliary data pointer for the fts5 extension \n**   function. See the xSetAuxdata() method for details.\n**\n**   If the bClear argument is non-zero, then the auxiliary data is cleared\n**   (set to NULL) before this function returns. In this case the xDelete,\n**   if any, is not invoked.\n**\n**\n** xRowCount(pFts5, pnRow)\n**\n**   This function is used to retrieve the total number of rows in the table.\n**   In other words, the same value that would be returned by:\n**\n**        SELECT count(*) FROM ftstable;\n**\n** xPhraseFirst()\n**   This function is used, along with type Fts5PhraseIter and the xPhraseNext\n**   method, to iterate through all instances of a single query phrase within\n**   the current row. This is the same information as is accessible via the\n**   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient\n**   to use, this API may be faster under some circumstances. To iterate \n**   through instances of phrase iPhrase, use the following code:\n**\n**       Fts5PhraseIter iter;\n**       int iCol, iOff;\n**       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);\n**           iCol>=0;\n**           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)\n**       ){\n**         // An instance of phrase iPhrase at offset iOff of column iCol\n**       }\n**\n**   The Fts5PhraseIter structure is defined above. Applications should not\n**   modify this structure directly - it should only be used as shown above\n**   with the xPhraseFirst() and xPhraseNext() API methods (and by\n**   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).\n**\n**   This API can be quite slow if used with an FTS5 table created with the\n**   \"detail=none\" or \"detail=column\" option. If the FTS5 table is created \n**   with either \"detail=none\" or \"detail=column\" and \"content=\" option \n**   (i.e. if it is a contentless table), then this API always iterates\n**   through an empty set (all calls to xPhraseFirst() set iCol to -1).\n**\n** xPhraseNext()\n**   See xPhraseFirst above.\n**\n** xPhraseFirstColumn()\n**   This function and xPhraseNextColumn() are similar to the xPhraseFirst()\n**   and xPhraseNext() APIs described above. The difference is that instead\n**   of iterating through all instances of a phrase in the current row, these\n**   APIs are used to iterate through the set of columns in the current row\n**   that contain one or more instances of a specified phrase. For example:\n**\n**       Fts5PhraseIter iter;\n**       int iCol;\n**       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);\n**           iCol>=0;\n**           pApi->xPhraseNextColumn(pFts, &iter, &iCol)\n**       ){\n**         // Column iCol contains at least one instance of phrase iPhrase\n**       }\n**\n**   This API can be quite slow if used with an FTS5 table created with the\n**   \"detail=none\" option. If the FTS5 table is created with either \n**   \"detail=none\" \"content=\" option (i.e. if it is a contentless table), \n**   then this API always iterates through an empty set (all calls to \n**   xPhraseFirstColumn() set iCol to -1).\n**\n**   The information accessed using this API and its companion\n**   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext\n**   (or xInst/xInstCount). The chief advantage of this API is that it is\n**   significantly more efficient than those alternatives when used with\n**   \"detail=column\" tables.  \n**\n** xPhraseNextColumn()\n**   See xPhraseFirstColumn above.\n*/\nstruct Fts5ExtensionApi {\n  int iVersion;                   /* Currently always set to 3 */\n\n  void *(*xUserData)(Fts5Context*);\n\n  int (*xColumnCount)(Fts5Context*);\n  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);\n  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);\n\n  int (*xTokenize)(Fts5Context*, \n    const char *pText, int nText, /* Text to tokenize */\n    void *pCtx,                   /* Context passed to xToken() */\n    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */\n  );\n\n  int (*xPhraseCount)(Fts5Context*);\n  int (*xPhraseSize)(Fts5Context*, int iPhrase);\n\n  int (*xInstCount)(Fts5Context*, int *pnInst);\n  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);\n\n  sqlite3_int64 (*xRowid)(Fts5Context*);\n  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);\n  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);\n\n  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,\n    int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)\n  );\n  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));\n  void *(*xGetAuxdata)(Fts5Context*, int bClear);\n\n  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);\n  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);\n\n  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);\n  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);\n};\n\n/* \n** CUSTOM AUXILIARY FUNCTIONS\n*************************************************************************/\n\n/*************************************************************************\n** CUSTOM TOKENIZERS\n**\n** Applications may also register custom tokenizer types. A tokenizer \n** is registered by providing fts5 with a populated instance of the \n** following structure. All structure methods must be defined, setting\n** any member of the fts5_tokenizer struct to NULL leads to undefined\n** behaviour. The structure methods are expected to function as follows:\n**\n** xCreate:\n**   This function is used to allocate and initialize a tokenizer instance.\n**   A tokenizer instance is required to actually tokenize text.\n**\n**   The first argument passed to this function is a copy of the (void*)\n**   pointer provided by the application when the fts5_tokenizer object\n**   was registered with FTS5 (the third argument to xCreateTokenizer()). \n**   The second and third arguments are an array of nul-terminated strings\n**   containing the tokenizer arguments, if any, specified following the\n**   tokenizer name as part of the CREATE VIRTUAL TABLE statement used\n**   to create the FTS5 table.\n**\n**   The final argument is an output variable. If successful, (*ppOut) \n**   should be set to point to the new tokenizer handle and SQLITE_OK\n**   returned. If an error occurs, some value other than SQLITE_OK should\n**   be returned. In this case, fts5 assumes that the final value of *ppOut \n**   is undefined.\n**\n** xDelete:\n**   This function is invoked to delete a tokenizer handle previously\n**   allocated using xCreate(). Fts5 guarantees that this function will\n**   be invoked exactly once for each successful call to xCreate().\n**\n** xTokenize:\n**   This function is expected to tokenize the nText byte string indicated \n**   by argument pText. pText may or may not be nul-terminated. The first\n**   argument passed to this function is a pointer to an Fts5Tokenizer object\n**   returned by an earlier call to xCreate().\n**\n**   The second argument indicates the reason that FTS5 is requesting\n**   tokenization of the supplied text. This is always one of the following\n**   four values:\n**\n**   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into\n**            or removed from the FTS table. The tokenizer is being invoked to\n**            determine the set of tokens to add to (or delete from) the\n**            FTS index.\n**\n**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed \n**            against the FTS index. The tokenizer is being called to tokenize \n**            a bareword or quoted string specified as part of the query.\n**\n**       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as\n**            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is\n**            followed by a \"*\" character, indicating that the last token\n**            returned by the tokenizer will be treated as a token prefix.\n**\n**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to \n**            satisfy an fts5_api.xTokenize() request made by an auxiliary\n**            function. Or an fts5_api.xColumnSize() request made by the same\n**            on a columnsize=0 database.  \n**   </ul>\n**\n**   For each token in the input string, the supplied callback xToken() must\n**   be invoked. The first argument to it should be a copy of the pointer\n**   passed as the second argument to xTokenize(). The third and fourth\n**   arguments are a pointer to a buffer containing the token text, and the\n**   size of the token in bytes. The 4th and 5th arguments are the byte offsets\n**   of the first byte of and first byte immediately following the text from\n**   which the token is derived within the input.\n**\n**   The second argument passed to the xToken() callback (\"tflags\") should\n**   normally be set to 0. The exception is if the tokenizer supports \n**   synonyms. In this case see the discussion below for details.\n**\n**   FTS5 assumes the xToken() callback is invoked for each token in the \n**   order that they occur within the input text.\n**\n**   If an xToken() callback returns any value other than SQLITE_OK, then\n**   the tokenization should be abandoned and the xTokenize() method should\n**   immediately return a copy of the xToken() return value. Or, if the\n**   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,\n**   if an error occurs with the xTokenize() implementation itself, it\n**   may abandon the tokenization and return any error code other than\n**   SQLITE_OK or SQLITE_DONE.\n**\n** SYNONYM SUPPORT\n**\n**   Custom tokenizers may also support synonyms. Consider a case in which a\n**   user wishes to query for a phrase such as \"first place\". Using the \n**   built-in tokenizers, the FTS5 query 'first + place' will match instances\n**   of \"first place\" within the document set, but not alternative forms\n**   such as \"1st place\". In some applications, it would be better to match\n**   all instances of \"first place\" or \"1st place\" regardless of which form\n**   the user specified in the MATCH query text.\n**\n**   There are several ways to approach this in FTS5:\n**\n**   <ol><li> By mapping all synonyms to a single token. In this case, using\n**            the above example, this means that the tokenizer returns the\n**            same token for inputs \"first\" and \"1st\". Say that token is in\n**            fact \"first\", so that when the user inserts the document \"I won\n**            1st place\" entries are added to the index for tokens \"i\", \"won\",\n**            \"first\" and \"place\". If the user then queries for '1st + place',\n**            the tokenizer substitutes \"first\" for \"1st\" and the query works\n**            as expected.\n**\n**       <li> By querying the index for all synonyms of each query term\n**            separately. In this case, when tokenizing query text, the\n**            tokenizer may provide multiple synonyms for a single term \n**            within the document. FTS5 then queries the index for each \n**            synonym individually. For example, faced with the query:\n**\n**   <codeblock>\n**     ... MATCH 'first place'</codeblock>\n**\n**            the tokenizer offers both \"1st\" and \"first\" as synonyms for the\n**            first token in the MATCH query and FTS5 effectively runs a query \n**            similar to:\n**\n**   <codeblock>\n**     ... MATCH '(first OR 1st) place'</codeblock>\n**\n**            except that, for the purposes of auxiliary functions, the query\n**            still appears to contain just two phrases - \"(first OR 1st)\" \n**            being treated as a single phrase.\n**\n**       <li> By adding multiple synonyms for a single term to the FTS index.\n**            Using this method, when tokenizing document text, the tokenizer\n**            provides multiple synonyms for each token. So that when a \n**            document such as \"I won first place\" is tokenized, entries are\n**            added to the FTS index for \"i\", \"won\", \"first\", \"1st\" and\n**            \"place\".\n**\n**            This way, even if the tokenizer does not provide synonyms\n**            when tokenizing query text (it should not - to do so would be\n**            inefficient), it doesn't matter if the user queries for \n**            'first + place' or '1st + place', as there are entries in the\n**            FTS index corresponding to both forms of the first token.\n**   </ol>\n**\n**   Whether it is parsing document or query text, any call to xToken that\n**   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit\n**   is considered to supply a synonym for the previous token. For example,\n**   when parsing the document \"I won first place\", a tokenizer that supports\n**   synonyms would call xToken() 5 times, as follows:\n**\n**   <codeblock>\n**       xToken(pCtx, 0, \"i\",                      1,  0,  1);\n**       xToken(pCtx, 0, \"won\",                    3,  2,  5);\n**       xToken(pCtx, 0, \"first\",                  5,  6, 11);\n**       xToken(pCtx, FTS5_TOKEN_COLOCATED, \"1st\", 3,  6, 11);\n**       xToken(pCtx, 0, \"place\",                  5, 12, 17);\n**</codeblock>\n**\n**   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time\n**   xToken() is called. Multiple synonyms may be specified for a single token\n**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. \n**   There is no limit to the number of synonyms that may be provided for a\n**   single token.\n**\n**   In many cases, method (1) above is the best approach. It does not add \n**   extra data to the FTS index or require FTS5 to query for multiple terms,\n**   so it is efficient in terms of disk space and query speed. However, it\n**   does not support prefix queries very well. If, as suggested above, the\n**   token \"first\" is substituted for \"1st\" by the tokenizer, then the query:\n**\n**   <codeblock>\n**     ... MATCH '1s*'</codeblock>\n**\n**   will not match documents that contain the token \"1st\" (as the tokenizer\n**   will probably not map \"1s\" to any prefix of \"first\").\n**\n**   For full prefix support, method (3) may be preferred. In this case, \n**   because the index contains entries for both \"first\" and \"1st\", prefix\n**   queries such as 'fi*' or '1s*' will match correctly. However, because\n**   extra entries are added to the FTS index, this method uses more space\n**   within the database.\n**\n**   Method (2) offers a midpoint between (1) and (3). Using this method,\n**   a query such as '1s*' will match documents that contain the literal \n**   token \"1st\", but not \"first\" (assuming the tokenizer is not able to\n**   provide synonyms for prefixes). However, a non-prefix query like '1st'\n**   will match against \"1st\" and \"first\". This method does not require\n**   extra disk space, as no extra entries are added to the FTS index. \n**   On the other hand, it may require more CPU cycles to run MATCH queries,\n**   as separate queries of the FTS index are required for each synonym.\n**\n**   When using methods (2) or (3), it is important that the tokenizer only\n**   provide synonyms when tokenizing document text (method (2)) or query\n**   text (method (3)), not both. Doing so will not cause any errors, but is\n**   inefficient.\n*/\ntypedef struct Fts5Tokenizer Fts5Tokenizer;\ntypedef struct fts5_tokenizer fts5_tokenizer;\nstruct fts5_tokenizer {\n  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);\n  void (*xDelete)(Fts5Tokenizer*);\n  int (*xTokenize)(Fts5Tokenizer*, \n      void *pCtx,\n      int flags,            /* Mask of FTS5_TOKENIZE_* flags */\n      const char *pText, int nText, \n      int (*xToken)(\n        void *pCtx,         /* Copy of 2nd argument to xTokenize() */\n        int tflags,         /* Mask of FTS5_TOKEN_* flags */\n        const char *pToken, /* Pointer to buffer containing token */\n        int nToken,         /* Size of token in bytes */\n        int iStart,         /* Byte offset of token within input text */\n        int iEnd            /* Byte offset of end of token within input text */\n      )\n  );\n};\n\n/* Flags that may be passed as the third argument to xTokenize() */\n#define FTS5_TOKENIZE_QUERY     0x0001\n#define FTS5_TOKENIZE_PREFIX    0x0002\n#define FTS5_TOKENIZE_DOCUMENT  0x0004\n#define FTS5_TOKENIZE_AUX       0x0008\n\n/* Flags that may be passed by the tokenizer implementation back to FTS5\n** as the third argument to the supplied xToken callback. */\n#define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */\n\n/*\n** END OF CUSTOM TOKENIZERS\n*************************************************************************/\n\n/*************************************************************************\n** FTS5 EXTENSION REGISTRATION API\n*/\ntypedef struct fts5_api fts5_api;\nstruct fts5_api {\n  int iVersion;                   /* Currently always set to 2 */\n\n  /* Create a new tokenizer */\n  int (*xCreateTokenizer)(\n    fts5_api *pApi,\n    const char *zName,\n    void *pContext,\n    fts5_tokenizer *pTokenizer,\n    void (*xDestroy)(void*)\n  );\n\n  /* Find an existing tokenizer */\n  int (*xFindTokenizer)(\n    fts5_api *pApi,\n    const char *zName,\n    void **ppContext,\n    fts5_tokenizer *pTokenizer\n  );\n\n  /* Create a new auxiliary function */\n  int (*xCreateFunction)(\n    fts5_api *pApi,\n    const char *zName,\n    void *pContext,\n    fts5_extension_function xFunction,\n    void (*xDestroy)(void*)\n  );\n};\n\n/*\n** END OF REGISTRATION API\n*************************************************************************/\n\n#if 0\n}  /* end of the 'extern \"C\"' block */\n#endif\n\n#endif /* _FTS5_H */\n\n/*\n** 2014 May 31\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n*/\n#ifndef _FTS5INT_H\n#define _FTS5INT_H\n\n/* #include \"fts5.h\" */\n/* #include \"sqlite3ext.h\" */\nSQLITE_EXTENSION_INIT1\n\n/* #include <string.h> */\n/* #include <assert.h> */\n\n#ifndef SQLITE_AMALGAMATION\n\ntypedef unsigned char  u8;\ntypedef unsigned int   u32;\ntypedef unsigned short u16;\ntypedef short i16;\ntypedef sqlite3_int64 i64;\ntypedef sqlite3_uint64 u64;\n\n#ifndef ArraySize\n# define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))\n#endif\n\n#define testcase(x)\n#define ALWAYS(x) 1\n#define NEVER(x) 0\n\n#define MIN(x,y) (((x) < (y)) ? (x) : (y))\n#define MAX(x,y) (((x) > (y)) ? (x) : (y))\n\n/*\n** Constants for the largest and smallest possible 64-bit signed integers.\n*/\n# define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))\n# define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)\n\n#endif\n\n/* Truncate very long tokens to this many bytes. Hard limit is \n** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset\n** field that occurs at the start of each leaf page (see fts5_index.c). */\n#define FTS5_MAX_TOKEN_SIZE 32768\n\n/*\n** Maximum number of prefix indexes on single FTS5 table. This must be\n** less than 32. If it is set to anything large than that, an #error\n** directive in fts5_index.c will cause the build to fail.\n*/\n#define FTS5_MAX_PREFIX_INDEXES 31\n\n/*\n** Maximum segments permitted in a single index \n*/\n#define FTS5_MAX_SEGMENT 2000\n\n#define FTS5_DEFAULT_NEARDIST 10\n#define FTS5_DEFAULT_RANK     \"bm25\"\n\n/* Name of rank and rowid columns */\n#define FTS5_RANK_NAME \"rank\"\n#define FTS5_ROWID_NAME \"rowid\"\n\n#ifdef SQLITE_DEBUG\n# define FTS5_CORRUPT sqlite3Fts5Corrupt()\nstatic int sqlite3Fts5Corrupt(void);\n#else\n# define FTS5_CORRUPT SQLITE_CORRUPT_VTAB\n#endif\n\n/*\n** The assert_nc() macro is similar to the assert() macro, except that it\n** is used for assert() conditions that are true only if it can be \n** guranteed that the database is not corrupt.\n*/\n#ifdef SQLITE_DEBUG\nSQLITE_API extern int sqlite3_fts5_may_be_corrupt;\n# define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))\n#else\n# define assert_nc(x) assert(x)\n#endif\n\n/*\n** A version of memcmp() that does not cause asan errors if one of the pointer\n** parameters is NULL and the number of bytes to compare is zero.\n*/\n#define fts5Memcmp(s1, s2, n) ((n)==0 ? 0 : memcmp((s1), (s2), (n)))\n\n/* Mark a function parameter as unused, to suppress nuisance compiler\n** warnings. */\n#ifndef UNUSED_PARAM\n# define UNUSED_PARAM(X)  (void)(X)\n#endif\n\n#ifndef UNUSED_PARAM2\n# define UNUSED_PARAM2(X, Y)  (void)(X), (void)(Y)\n#endif\n\ntypedef struct Fts5Global Fts5Global;\ntypedef struct Fts5Colset Fts5Colset;\n\n/* If a NEAR() clump or phrase may only match a specific set of columns, \n** then an object of the following type is used to record the set of columns.\n** Each entry in the aiCol[] array is a column that may be matched.\n**\n** This object is used by fts5_expr.c and fts5_index.c.\n*/\nstruct Fts5Colset {\n  int nCol;\n  int aiCol[1];\n};\n\n\n\n/**************************************************************************\n** Interface to code in fts5_config.c. fts5_config.c contains contains code\n** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.\n*/\n\ntypedef struct Fts5Config Fts5Config;\n\n/*\n** An instance of the following structure encodes all information that can\n** be gleaned from the CREATE VIRTUAL TABLE statement.\n**\n** And all information loaded from the %_config table.\n**\n** nAutomerge:\n**   The minimum number of segments that an auto-merge operation should\n**   attempt to merge together. A value of 1 sets the object to use the \n**   compile time default. Zero disables auto-merge altogether.\n**\n** zContent:\n**\n** zContentRowid:\n**   The value of the content_rowid= option, if one was specified. Or \n**   the string \"rowid\" otherwise. This text is not quoted - if it is\n**   used as part of an SQL statement it needs to be quoted appropriately.\n**\n** zContentExprlist:\n**\n** pzErrmsg:\n**   This exists in order to allow the fts5_index.c module to return a \n**   decent error message if it encounters a file-format version it does\n**   not understand.\n**\n** bColumnsize:\n**   True if the %_docsize table is created.\n**\n** bPrefixIndex:\n**   This is only used for debugging. If set to false, any prefix indexes\n**   are ignored. This value is configured using:\n**\n**       INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);\n**\n*/\nstruct Fts5Config {\n  sqlite3 *db;                    /* Database handle */\n  char *zDb;                      /* Database holding FTS index (e.g. \"main\") */\n  char *zName;                    /* Name of FTS index */\n  int nCol;                       /* Number of columns */\n  char **azCol;                   /* Column names */\n  u8 *abUnindexed;                /* True for unindexed columns */\n  int nPrefix;                    /* Number of prefix indexes */\n  int *aPrefix;                   /* Sizes in bytes of nPrefix prefix indexes */\n  int eContent;                   /* An FTS5_CONTENT value */\n  char *zContent;                 /* content table */ \n  char *zContentRowid;            /* \"content_rowid=\" option value */ \n  int bColumnsize;                /* \"columnsize=\" option value (dflt==1) */\n  int eDetail;                    /* FTS5_DETAIL_XXX value */\n  char *zContentExprlist;\n  Fts5Tokenizer *pTok;\n  fts5_tokenizer *pTokApi;\n  int bLock;                      /* True when table is preparing statement */\n\n  /* Values loaded from the %_config table */\n  int iCookie;                    /* Incremented when %_config is modified */\n  int pgsz;                       /* Approximate page size used in %_data */\n  int nAutomerge;                 /* 'automerge' setting */\n  int nCrisisMerge;               /* Maximum allowed segments per level */\n  int nUsermerge;                 /* 'usermerge' setting */\n  int nHashSize;                  /* Bytes of memory for in-memory hash */\n  char *zRank;                    /* Name of rank function */\n  char *zRankArgs;                /* Arguments to rank function */\n\n  /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */\n  char **pzErrmsg;\n\n#ifdef SQLITE_DEBUG\n  int bPrefixIndex;               /* True to use prefix-indexes */\n#endif\n};\n\n/* Current expected value of %_config table 'version' field */\n#define FTS5_CURRENT_VERSION 4\n\n#define FTS5_CONTENT_NORMAL   0\n#define FTS5_CONTENT_NONE     1\n#define FTS5_CONTENT_EXTERNAL 2\n\n#define FTS5_DETAIL_FULL    0\n#define FTS5_DETAIL_NONE    1\n#define FTS5_DETAIL_COLUMNS 2\n\n\n\nstatic int sqlite3Fts5ConfigParse(\n    Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**\n);\nstatic void sqlite3Fts5ConfigFree(Fts5Config*);\n\nstatic int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);\n\nstatic int sqlite3Fts5Tokenize(\n  Fts5Config *pConfig,            /* FTS5 Configuration object */\n  int flags,                      /* FTS5_TOKENIZE_* flags */\n  const char *pText, int nText,   /* Text to tokenize */\n  void *pCtx,                     /* Context passed to xToken() */\n  int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */\n);\n\nstatic void sqlite3Fts5Dequote(char *z);\n\n/* Load the contents of the %_config table */\nstatic int sqlite3Fts5ConfigLoad(Fts5Config*, int);\n\n/* Set the value of a single config attribute */\nstatic int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);\n\nstatic int sqlite3Fts5ConfigParseRank(const char*, char**, char**);\n\n/*\n** End of interface to code in fts5_config.c.\n**************************************************************************/\n\n/**************************************************************************\n** Interface to code in fts5_buffer.c.\n*/\n\n/*\n** Buffer object for the incremental building of string data.\n*/\ntypedef struct Fts5Buffer Fts5Buffer;\nstruct Fts5Buffer {\n  u8 *p;\n  int n;\n  int nSpace;\n};\n\nstatic int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);\nstatic void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);\nstatic void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);\nstatic void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);\nstatic void sqlite3Fts5BufferFree(Fts5Buffer*);\nstatic void sqlite3Fts5BufferZero(Fts5Buffer*);\nstatic void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);\nstatic void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);\n\nstatic char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);\n\n#define fts5BufferZero(x)             sqlite3Fts5BufferZero(x)\n#define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)\n#define fts5BufferFree(a)             sqlite3Fts5BufferFree(a)\n#define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)\n#define fts5BufferSet(a,b,c,d)        sqlite3Fts5BufferSet(a,b,c,d)\n\n#define fts5BufferGrow(pRc,pBuf,nn) ( \\\n  (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \\\n    sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \\\n)\n\n/* Write and decode big-endian 32-bit integer values */\nstatic void sqlite3Fts5Put32(u8*, int);\nstatic int sqlite3Fts5Get32(const u8*);\n\n#define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)\n#define FTS5_POS2OFFSET(iPos) (int)(iPos & 0x7FFFFFFF)\n\ntypedef struct Fts5PoslistReader Fts5PoslistReader;\nstruct Fts5PoslistReader {\n  /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */\n  const u8 *a;                    /* Position list to iterate through */\n  int n;                          /* Size of buffer at a[] in bytes */\n  int i;                          /* Current offset in a[] */\n\n  u8 bFlag;                       /* For client use (any custom purpose) */\n\n  /* Output variables */\n  u8 bEof;                        /* Set to true at EOF */\n  i64 iPos;                       /* (iCol<<32) + iPos */\n};\nstatic int sqlite3Fts5PoslistReaderInit(\n  const u8 *a, int n,             /* Poslist buffer to iterate through */\n  Fts5PoslistReader *pIter        /* Iterator object to initialize */\n);\nstatic int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);\n\ntypedef struct Fts5PoslistWriter Fts5PoslistWriter;\nstruct Fts5PoslistWriter {\n  i64 iPrev;\n};\nstatic int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);\nstatic void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);\n\nstatic int sqlite3Fts5PoslistNext64(\n  const u8 *a, int n,             /* Buffer containing poslist */\n  int *pi,                        /* IN/OUT: Offset within a[] */\n  i64 *piOff                      /* IN/OUT: Current offset */\n);\n\n/* Malloc utility */\nstatic void *sqlite3Fts5MallocZero(int *pRc, sqlite3_int64 nByte);\nstatic char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);\n\n/* Character set tests (like isspace(), isalpha() etc.) */\nstatic int sqlite3Fts5IsBareword(char t);\n\n\n/* Bucket of terms object used by the integrity-check in offsets=0 mode. */\ntypedef struct Fts5Termset Fts5Termset;\nstatic int sqlite3Fts5TermsetNew(Fts5Termset**);\nstatic int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);\nstatic void sqlite3Fts5TermsetFree(Fts5Termset*);\n\n/*\n** End of interface to code in fts5_buffer.c.\n**************************************************************************/\n\n/**************************************************************************\n** Interface to code in fts5_index.c. fts5_index.c contains contains code\n** to access the data stored in the %_data table.\n*/\n\ntypedef struct Fts5Index Fts5Index;\ntypedef struct Fts5IndexIter Fts5IndexIter;\n\nstruct Fts5IndexIter {\n  i64 iRowid;\n  const u8 *pData;\n  int nData;\n  u8 bEof;\n};\n\n#define sqlite3Fts5IterEof(x) ((x)->bEof)\n\n/*\n** Values used as part of the flags argument passed to IndexQuery().\n*/\n#define FTS5INDEX_QUERY_PREFIX     0x0001   /* Prefix query */\n#define FTS5INDEX_QUERY_DESC       0x0002   /* Docs in descending rowid order */\n#define FTS5INDEX_QUERY_TEST_NOIDX 0x0004   /* Do not use prefix index */\n#define FTS5INDEX_QUERY_SCAN       0x0008   /* Scan query (fts5vocab) */\n\n/* The following are used internally by the fts5_index.c module. They are\n** defined here only to make it easier to avoid clashes with the flags\n** above. */\n#define FTS5INDEX_QUERY_SKIPEMPTY  0x0010\n#define FTS5INDEX_QUERY_NOOUTPUT   0x0020\n\n/*\n** Create/destroy an Fts5Index object.\n*/\nstatic int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);\nstatic int sqlite3Fts5IndexClose(Fts5Index *p);\n\n/*\n** Return a simple checksum value based on the arguments.\n*/\nstatic u64 sqlite3Fts5IndexEntryCksum(\n  i64 iRowid, \n  int iCol, \n  int iPos, \n  int iIdx,\n  const char *pTerm,\n  int nTerm\n);\n\n/*\n** Argument p points to a buffer containing utf-8 text that is n bytes in \n** size. Return the number of bytes in the nChar character prefix of the\n** buffer, or 0 if there are less than nChar characters in total.\n*/\nstatic int sqlite3Fts5IndexCharlenToBytelen(\n  const char *p, \n  int nByte, \n  int nChar\n);\n\n/*\n** Open a new iterator to iterate though all rowids that match the \n** specified token or token prefix.\n*/\nstatic int sqlite3Fts5IndexQuery(\n  Fts5Index *p,                   /* FTS index to query */\n  const char *pToken, int nToken, /* Token (or prefix) to query for */\n  int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */\n  Fts5Colset *pColset,            /* Match these columns only */\n  Fts5IndexIter **ppIter          /* OUT: New iterator object */\n);\n\n/*\n** The various operations on open token or token prefix iterators opened\n** using sqlite3Fts5IndexQuery().\n*/\nstatic int sqlite3Fts5IterNext(Fts5IndexIter*);\nstatic int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);\n\n/*\n** Close an iterator opened by sqlite3Fts5IndexQuery().\n*/\nstatic void sqlite3Fts5IterClose(Fts5IndexIter*);\n\n/*\n** Close the reader blob handle, if it is open.\n*/\nstatic void sqlite3Fts5IndexCloseReader(Fts5Index*);\n\n/*\n** This interface is used by the fts5vocab module.\n*/\nstatic const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);\nstatic int sqlite3Fts5IterNextScan(Fts5IndexIter*);\n\n\n/*\n** Insert or remove data to or from the index. Each time a document is \n** added to or removed from the index, this function is called one or more\n** times.\n**\n** For an insert, it must be called once for each token in the new document.\n** If the operation is a delete, it must be called (at least) once for each\n** unique token in the document with an iCol value less than zero. The iPos\n** argument is ignored for a delete.\n*/\nstatic int sqlite3Fts5IndexWrite(\n  Fts5Index *p,                   /* Index to write to */\n  int iCol,                       /* Column token appears in (-ve -> delete) */\n  int iPos,                       /* Position of token within column */\n  const char *pToken, int nToken  /* Token to add or remove to or from index */\n);\n\n/*\n** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to\n** document iDocid.\n*/\nstatic int sqlite3Fts5IndexBeginWrite(\n  Fts5Index *p,                   /* Index to write to */\n  int bDelete,                    /* True if current operation is a delete */\n  i64 iDocid                      /* Docid to add or remove data from */\n);\n\n/*\n** Flush any data stored in the in-memory hash tables to the database.\n** Also close any open blob handles.\n*/\nstatic int sqlite3Fts5IndexSync(Fts5Index *p);\n\n/*\n** Discard any data stored in the in-memory hash tables. Do not write it\n** to the database. Additionally, assume that the contents of the %_data\n** table may have changed on disk. So any in-memory caches of %_data \n** records must be invalidated.\n*/\nstatic int sqlite3Fts5IndexRollback(Fts5Index *p);\n\n/*\n** Get or set the \"averages\" values.\n*/\nstatic int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);\nstatic int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);\n\n/*\n** Functions called by the storage module as part of integrity-check.\n*/\nstatic int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);\n\n/* \n** Called during virtual module initialization to register UDF \n** fts5_decode() with SQLite \n*/\nstatic int sqlite3Fts5IndexInit(sqlite3*);\n\nstatic int sqlite3Fts5IndexSetCookie(Fts5Index*, int);\n\n/*\n** Return the total number of entries read from the %_data table by \n** this connection since it was created.\n*/\nstatic int sqlite3Fts5IndexReads(Fts5Index *p);\n\nstatic int sqlite3Fts5IndexReinit(Fts5Index *p);\nstatic int sqlite3Fts5IndexOptimize(Fts5Index *p);\nstatic int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);\nstatic int sqlite3Fts5IndexReset(Fts5Index *p);\n\nstatic int sqlite3Fts5IndexLoadConfig(Fts5Index *p);\n\n/*\n** End of interface to code in fts5_index.c.\n**************************************************************************/\n\n/**************************************************************************\n** Interface to code in fts5_varint.c. \n*/\nstatic int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);\nstatic int sqlite3Fts5GetVarintLen(u32 iVal);\nstatic u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);\nstatic int sqlite3Fts5PutVarint(unsigned char *p, u64 v);\n\n#define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)\n#define fts5GetVarint    sqlite3Fts5GetVarint\n\n#define fts5FastGetVarint32(a, iOff, nVal) {      \\\n  nVal = (a)[iOff++];                             \\\n  if( nVal & 0x80 ){                              \\\n    iOff--;                                       \\\n    iOff += fts5GetVarint32(&(a)[iOff], nVal);    \\\n  }                                               \\\n}\n\n\n/*\n** End of interface to code in fts5_varint.c.\n**************************************************************************/\n\n\n/**************************************************************************\n** Interface to code in fts5_main.c. \n*/\n\n/*\n** Virtual-table object.\n*/\ntypedef struct Fts5Table Fts5Table;\nstruct Fts5Table {\n  sqlite3_vtab base;              /* Base class used by SQLite core */\n  Fts5Config *pConfig;            /* Virtual table configuration */\n  Fts5Index *pIndex;              /* Full-text index */\n};\n\nstatic int sqlite3Fts5GetTokenizer(\n  Fts5Global*, \n  const char **azArg,\n  int nArg,\n  Fts5Tokenizer**,\n  fts5_tokenizer**,\n  char **pzErr\n);\n\nstatic Fts5Table *sqlite3Fts5TableFromCsrid(Fts5Global*, i64);\n\nstatic int sqlite3Fts5FlushToDisk(Fts5Table*);\n\n/*\n** End of interface to code in fts5.c.\n**************************************************************************/\n\n/**************************************************************************\n** Interface to code in fts5_hash.c. \n*/\ntypedef struct Fts5Hash Fts5Hash;\n\n/*\n** Create a hash table, free a hash table.\n*/\nstatic int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);\nstatic void sqlite3Fts5HashFree(Fts5Hash*);\n\nstatic int sqlite3Fts5HashWrite(\n  Fts5Hash*,\n  i64 iRowid,                     /* Rowid for this entry */\n  int iCol,                       /* Column token appears in (-ve -> delete) */\n  int iPos,                       /* Position of token within column */\n  char bByte,\n  const char *pToken, int nToken  /* Token to add or remove to or from index */\n);\n\n/*\n** Empty (but do not delete) a hash table.\n*/\nstatic void sqlite3Fts5HashClear(Fts5Hash*);\n\nstatic int sqlite3Fts5HashQuery(\n  Fts5Hash*,                      /* Hash table to query */\n  int nPre,\n  const char *pTerm, int nTerm,   /* Query term */\n  void **ppObj,                   /* OUT: Pointer to doclist for pTerm */\n  int *pnDoclist                  /* OUT: Size of doclist in bytes */\n);\n\nstatic int sqlite3Fts5HashScanInit(\n  Fts5Hash*,                      /* Hash table to query */\n  const char *pTerm, int nTerm    /* Query prefix */\n);\nstatic void sqlite3Fts5HashScanNext(Fts5Hash*);\nstatic int sqlite3Fts5HashScanEof(Fts5Hash*);\nstatic void sqlite3Fts5HashScanEntry(Fts5Hash *,\n  const char **pzTerm,            /* OUT: term (nul-terminated) */\n  const u8 **ppDoclist,           /* OUT: pointer to doclist */\n  int *pnDoclist                  /* OUT: size of doclist in bytes */\n);\n\n\n/*\n** End of interface to code in fts5_hash.c.\n**************************************************************************/\n\n/**************************************************************************\n** Interface to code in fts5_storage.c. fts5_storage.c contains contains \n** code to access the data stored in the %_content and %_docsize tables.\n*/\n\n#define FTS5_STMT_SCAN_ASC  0     /* SELECT rowid, * FROM ... ORDER BY 1 ASC */\n#define FTS5_STMT_SCAN_DESC 1     /* SELECT rowid, * FROM ... ORDER BY 1 DESC */\n#define FTS5_STMT_LOOKUP    2     /* SELECT rowid, * FROM ... WHERE rowid=? */\n\ntypedef struct Fts5Storage Fts5Storage;\n\nstatic int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);\nstatic int sqlite3Fts5StorageClose(Fts5Storage *p);\nstatic int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);\n\nstatic int sqlite3Fts5DropAll(Fts5Config*);\nstatic int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);\n\nstatic int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);\nstatic int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);\nstatic int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);\n\nstatic int sqlite3Fts5StorageIntegrity(Fts5Storage *p);\n\nstatic int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);\nstatic void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);\n\nstatic int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);\nstatic int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);\nstatic int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);\n\nstatic int sqlite3Fts5StorageSync(Fts5Storage *p);\nstatic int sqlite3Fts5StorageRollback(Fts5Storage *p);\n\nstatic int sqlite3Fts5StorageConfigValue(\n    Fts5Storage *p, const char*, sqlite3_value*, int\n);\n\nstatic int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);\nstatic int sqlite3Fts5StorageRebuild(Fts5Storage *p);\nstatic int sqlite3Fts5StorageOptimize(Fts5Storage *p);\nstatic int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);\nstatic int sqlite3Fts5StorageReset(Fts5Storage *p);\n\n/*\n** End of interface to code in fts5_storage.c.\n**************************************************************************/\n\n\n/**************************************************************************\n** Interface to code in fts5_expr.c. \n*/\ntypedef struct Fts5Expr Fts5Expr;\ntypedef struct Fts5ExprNode Fts5ExprNode;\ntypedef struct Fts5Parse Fts5Parse;\ntypedef struct Fts5Token Fts5Token;\ntypedef struct Fts5ExprPhrase Fts5ExprPhrase;\ntypedef struct Fts5ExprNearset Fts5ExprNearset;\n\nstruct Fts5Token {\n  const char *p;                  /* Token text (not NULL terminated) */\n  int n;                          /* Size of buffer p in bytes */\n};\n\n/* Parse a MATCH expression. */\nstatic int sqlite3Fts5ExprNew(\n  Fts5Config *pConfig, \n  int iCol,                       /* Column on LHS of MATCH operator */\n  const char *zExpr,\n  Fts5Expr **ppNew, \n  char **pzErr\n);\n\n/*\n** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);\n**     rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);\n**     rc = sqlite3Fts5ExprNext(pExpr)\n** ){\n**   // The document with rowid iRowid matches the expression!\n**   i64 iRowid = sqlite3Fts5ExprRowid(pExpr);\n** }\n*/\nstatic int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);\nstatic int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);\nstatic int sqlite3Fts5ExprEof(Fts5Expr*);\nstatic i64 sqlite3Fts5ExprRowid(Fts5Expr*);\n\nstatic void sqlite3Fts5ExprFree(Fts5Expr*);\nstatic int sqlite3Fts5ExprAnd(Fts5Expr **pp1, Fts5Expr *p2);\n\n/* Called during startup to register a UDF with SQLite */\nstatic int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);\n\nstatic int sqlite3Fts5ExprPhraseCount(Fts5Expr*);\nstatic int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);\nstatic int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);\n\ntypedef struct Fts5PoslistPopulator Fts5PoslistPopulator;\nstatic Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);\nstatic int sqlite3Fts5ExprPopulatePoslists(\n    Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int\n);\nstatic void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);\n\nstatic int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);\n\nstatic int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);\n\n/*******************************************\n** The fts5_expr.c API above this point is used by the other hand-written\n** C code in this module. The interfaces below this point are called by\n** the parser code in fts5parse.y.  */\n\nstatic void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);\n\nstatic Fts5ExprNode *sqlite3Fts5ParseNode(\n  Fts5Parse *pParse,\n  int eType,\n  Fts5ExprNode *pLeft,\n  Fts5ExprNode *pRight,\n  Fts5ExprNearset *pNear\n);\n\nstatic Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(\n  Fts5Parse *pParse,\n  Fts5ExprNode *pLeft,\n  Fts5ExprNode *pRight\n);\n\nstatic Fts5ExprPhrase *sqlite3Fts5ParseTerm(\n  Fts5Parse *pParse, \n  Fts5ExprPhrase *pPhrase, \n  Fts5Token *pToken,\n  int bPrefix\n);\n\nstatic void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase*);\n\nstatic Fts5ExprNearset *sqlite3Fts5ParseNearset(\n  Fts5Parse*, \n  Fts5ExprNearset*,\n  Fts5ExprPhrase* \n);\n\nstatic Fts5Colset *sqlite3Fts5ParseColset(\n  Fts5Parse*, \n  Fts5Colset*, \n  Fts5Token *\n);\n\nstatic void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);\nstatic void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);\nstatic void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);\n\nstatic void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);\nstatic void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);\nstatic Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);\nstatic void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);\nstatic void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);\n\n/*\n** End of interface to code in fts5_expr.c.\n**************************************************************************/\n\n\n\n/**************************************************************************\n** Interface to code in fts5_aux.c. \n*/\n\nstatic int sqlite3Fts5AuxInit(fts5_api*);\n/*\n** End of interface to code in fts5_aux.c.\n**************************************************************************/\n\n/**************************************************************************\n** Interface to code in fts5_tokenizer.c. \n*/\n\nstatic int sqlite3Fts5TokenizerInit(fts5_api*);\n/*\n** End of interface to code in fts5_tokenizer.c.\n**************************************************************************/\n\n/**************************************************************************\n** Interface to code in fts5_vocab.c. \n*/\n\nstatic int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);\n\n/*\n** End of interface to code in fts5_vocab.c.\n**************************************************************************/\n\n\n/**************************************************************************\n** Interface to automatically generated code in fts5_unicode2.c. \n*/\nstatic int sqlite3Fts5UnicodeIsdiacritic(int c);\nstatic int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);\n\nstatic int sqlite3Fts5UnicodeCatParse(const char*, u8*);\nstatic int sqlite3Fts5UnicodeCategory(u32 iCode);\nstatic void sqlite3Fts5UnicodeAscii(u8*, u8*);\n/*\n** End of interface to code in fts5_unicode2.c.\n**************************************************************************/\n\n#endif\n\n#define FTS5_OR                               1\n#define FTS5_AND                              2\n#define FTS5_NOT                              3\n#define FTS5_TERM                             4\n#define FTS5_COLON                            5\n#define FTS5_MINUS                            6\n#define FTS5_LCP                              7\n#define FTS5_RCP                              8\n#define FTS5_STRING                           9\n#define FTS5_LP                              10\n#define FTS5_RP                              11\n#define FTS5_CARET                           12\n#define FTS5_COMMA                           13\n#define FTS5_PLUS                            14\n#define FTS5_STAR                            15\n\n/*\n** 2000-05-29\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** Driver template for the LEMON parser generator.\n**\n** The \"lemon\" program processes an LALR(1) input grammar file, then uses\n** this template to construct a parser.  The \"lemon\" program inserts text\n** at each \"%%\" line.  Also, any \"P-a-r-s-e\" identifer prefix (without the\n** interstitial \"-\" characters) contained in this template is changed into\n** the value of the %name directive from the grammar.  Otherwise, the content\n** of this template is copied straight through into the generate parser\n** source file.\n**\n** The following is the concatenation of all %include directives from the\n** input grammar file:\n*/\n/* #include <stdio.h> */\n/* #include <assert.h> */\n/************ Begin %include sections from the grammar ************************/\n\n/* #include \"fts5Int.h\" */\n/* #include \"fts5parse.h\" */\n\n/*\n** Disable all error recovery processing in the parser push-down\n** automaton.\n*/\n#define fts5YYNOERRORRECOVERY 1\n\n/*\n** Make fts5yytestcase() the same as testcase()\n*/\n#define fts5yytestcase(X) testcase(X)\n\n/*\n** Indicate that sqlite3ParserFree() will never be called with a null\n** pointer.\n*/\n#define fts5YYPARSEFREENOTNULL 1\n\n/*\n** Alternative datatype for the argument to the malloc() routine passed\n** into sqlite3ParserAlloc().  The default is size_t.\n*/\n#define fts5YYMALLOCARGTYPE  u64\n\n/**************** End of %include directives **********************************/\n/* These constants specify the various numeric values for terminal symbols\n** in a format understandable to \"makeheaders\".  This section is blank unless\n** \"lemon\" is run with the \"-m\" command-line option.\n***************** Begin makeheaders token definitions *************************/\n/**************** End makeheaders token definitions ***************************/\n\n/* The next sections is a series of control #defines.\n** various aspects of the generated parser.\n**    fts5YYCODETYPE         is the data type used to store the integer codes\n**                       that represent terminal and non-terminal symbols.\n**                       \"unsigned char\" is used if there are fewer than\n**                       256 symbols.  Larger types otherwise.\n**    fts5YYNOCODE           is a number of type fts5YYCODETYPE that is not used for\n**                       any terminal or nonterminal symbol.\n**    fts5YYFALLBACK         If defined, this indicates that one or more tokens\n**                       (also known as: \"terminal symbols\") have fall-back\n**                       values which should be used if the original symbol\n**                       would not parse.  This permits keywords to sometimes\n**                       be used as identifiers, for example.\n**    fts5YYACTIONTYPE       is the data type used for \"action codes\" - numbers\n**                       that indicate what to do in response to the next\n**                       token.\n**    sqlite3Fts5ParserFTS5TOKENTYPE     is the data type used for minor type for terminal\n**                       symbols.  Background: A \"minor type\" is a semantic\n**                       value associated with a terminal or non-terminal\n**                       symbols.  For example, for an \"ID\" terminal symbol,\n**                       the minor type might be the name of the identifier.\n**                       Each non-terminal can have a different minor type.\n**                       Terminal symbols all have the same minor type, though.\n**                       This macros defines the minor type for terminal \n**                       symbols.\n**    fts5YYMINORTYPE        is the data type used for all minor types.\n**                       This is typically a union of many types, one of\n**                       which is sqlite3Fts5ParserFTS5TOKENTYPE.  The entry in the union\n**                       for terminal symbols is called \"fts5yy0\".\n**    fts5YYSTACKDEPTH       is the maximum depth of the parser's stack.  If\n**                       zero the stack is dynamically sized using realloc()\n**    sqlite3Fts5ParserARG_SDECL     A static variable declaration for the %extra_argument\n**    sqlite3Fts5ParserARG_PDECL     A parameter declaration for the %extra_argument\n**    sqlite3Fts5ParserARG_PARAM     Code to pass %extra_argument as a subroutine parameter\n**    sqlite3Fts5ParserARG_STORE     Code to store %extra_argument into fts5yypParser\n**    sqlite3Fts5ParserARG_FETCH     Code to extract %extra_argument from fts5yypParser\n**    sqlite3Fts5ParserCTX_*         As sqlite3Fts5ParserARG_ except for %extra_context\n**    fts5YYERRORSYMBOL      is the code number of the error symbol.  If not\n**                       defined, then do no error processing.\n**    fts5YYNSTATE           the combined number of states.\n**    fts5YYNRULE            the number of rules in the grammar\n**    fts5YYNFTS5TOKEN           Number of terminal symbols\n**    fts5YY_MAX_SHIFT       Maximum value for shift actions\n**    fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions\n**    fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions\n**    fts5YY_ERROR_ACTION    The fts5yy_action[] code for syntax error\n**    fts5YY_ACCEPT_ACTION   The fts5yy_action[] code for accept\n**    fts5YY_NO_ACTION       The fts5yy_action[] code for no-op\n**    fts5YY_MIN_REDUCE      Minimum value for reduce actions\n**    fts5YY_MAX_REDUCE      Maximum value for reduce actions\n*/\n#ifndef INTERFACE\n# define INTERFACE 1\n#endif\n/************* Begin control #defines *****************************************/\n#define fts5YYCODETYPE unsigned char\n#define fts5YYNOCODE 27\n#define fts5YYACTIONTYPE unsigned char\n#define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token\ntypedef union {\n  int fts5yyinit;\n  sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;\n  int fts5yy4;\n  Fts5Colset* fts5yy11;\n  Fts5ExprNode* fts5yy24;\n  Fts5ExprNearset* fts5yy46;\n  Fts5ExprPhrase* fts5yy53;\n} fts5YYMINORTYPE;\n#ifndef fts5YYSTACKDEPTH\n#define fts5YYSTACKDEPTH 100\n#endif\n#define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;\n#define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse\n#define sqlite3Fts5ParserARG_PARAM ,pParse\n#define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse=fts5yypParser->pParse;\n#define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse=pParse;\n#define sqlite3Fts5ParserCTX_SDECL\n#define sqlite3Fts5ParserCTX_PDECL\n#define sqlite3Fts5ParserCTX_PARAM\n#define sqlite3Fts5ParserCTX_FETCH\n#define sqlite3Fts5ParserCTX_STORE\n#define fts5YYNSTATE             35\n#define fts5YYNRULE              28\n#define fts5YYNRULE_WITH_ACTION  28\n#define fts5YYNFTS5TOKEN             16\n#define fts5YY_MAX_SHIFT         34\n#define fts5YY_MIN_SHIFTREDUCE   52\n#define fts5YY_MAX_SHIFTREDUCE   79\n#define fts5YY_ERROR_ACTION      80\n#define fts5YY_ACCEPT_ACTION     81\n#define fts5YY_NO_ACTION         82\n#define fts5YY_MIN_REDUCE        83\n#define fts5YY_MAX_REDUCE        110\n/************* End control #defines *******************************************/\n#define fts5YY_NLOOKAHEAD ((int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])))\n\n/* Define the fts5yytestcase() macro to be a no-op if is not already defined\n** otherwise.\n**\n** Applications can choose to define fts5yytestcase() in the %include section\n** to a macro that can assist in verifying code coverage.  For production\n** code the fts5yytestcase() macro should be turned off.  But it is useful\n** for testing.\n*/\n#ifndef fts5yytestcase\n# define fts5yytestcase(X)\n#endif\n\n\n/* Next are the tables used to determine what action to take based on the\n** current state and lookahead token.  These tables are used to implement\n** functions that take a state number and lookahead value and return an\n** action integer.  \n**\n** Suppose the action integer is N.  Then the action is determined as\n** follows\n**\n**   0 <= N <= fts5YY_MAX_SHIFT             Shift N.  That is, push the lookahead\n**                                      token onto the stack and goto state N.\n**\n**   N between fts5YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then\n**     and fts5YY_MAX_SHIFTREDUCE           reduce by rule N-fts5YY_MIN_SHIFTREDUCE.\n**\n**   N == fts5YY_ERROR_ACTION               A syntax error has occurred.\n**\n**   N == fts5YY_ACCEPT_ACTION              The parser accepts its input.\n**\n**   N == fts5YY_NO_ACTION                  No such action.  Denotes unused\n**                                      slots in the fts5yy_action[] table.\n**\n**   N between fts5YY_MIN_REDUCE            Reduce by rule N-fts5YY_MIN_REDUCE\n**     and fts5YY_MAX_REDUCE\n**\n** The action table is constructed as a single large table named fts5yy_action[].\n** Given state S and lookahead X, the action is computed as either:\n**\n**    (A)   N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]\n**    (B)   N = fts5yy_default[S]\n**\n** The (A) formula is preferred.  The B formula is used instead if\n** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X.\n**\n** The formulas above are for computing the action when the lookahead is\n** a terminal symbol.  If the lookahead is a non-terminal (as occurs after\n** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of\n** the fts5yy_shift_ofst[] array.\n**\n** The following are the tables generated in this section:\n**\n**  fts5yy_action[]        A single table containing all actions.\n**  fts5yy_lookahead[]     A table containing the lookahead for each entry in\n**                     fts5yy_action.  Used to detect hash collisions.\n**  fts5yy_shift_ofst[]    For each state, the offset into fts5yy_action for\n**                     shifting terminals.\n**  fts5yy_reduce_ofst[]   For each state, the offset into fts5yy_action for\n**                     shifting non-terminals after a reduce.\n**  fts5yy_default[]       Default action for each state.\n**\n*********** Begin parsing tables **********************************************/\n#define fts5YY_ACTTAB_COUNT (105)\nstatic const fts5YYACTIONTYPE fts5yy_action[] = {\n /*     0 */    81,   20,   96,    6,   28,   99,   98,   26,   26,   18,\n /*    10 */    96,    6,   28,   17,   98,   56,   26,   19,   96,    6,\n /*    20 */    28,   14,   98,   14,   26,   31,   92,   96,    6,   28,\n /*    30 */   108,   98,   25,   26,   21,   96,    6,   28,   78,   98,\n /*    40 */    58,   26,   29,   96,    6,   28,  107,   98,   22,   26,\n /*    50 */    24,   16,   12,   11,    1,   13,   13,   24,   16,   23,\n /*    60 */    11,   33,   34,   13,   97,    8,   27,   32,   98,    7,\n /*    70 */    26,    3,    4,    5,    3,    4,    5,    3,   83,    4,\n /*    80 */     5,    3,   63,    5,    3,   62,   12,    2,   86,   13,\n /*    90 */     9,   30,   10,   10,   54,   57,   75,   78,   78,   53,\n /*   100 */    57,   15,   82,   82,   71,\n};\nstatic const fts5YYCODETYPE fts5yy_lookahead[] = {\n /*     0 */    16,   17,   18,   19,   20,   22,   22,   24,   24,   17,\n /*    10 */    18,   19,   20,    7,   22,    9,   24,   17,   18,   19,\n /*    20 */    20,    9,   22,    9,   24,   13,   17,   18,   19,   20,\n /*    30 */    26,   22,   24,   24,   17,   18,   19,   20,   15,   22,\n /*    40 */     9,   24,   17,   18,   19,   20,   26,   22,   21,   24,\n /*    50 */     6,    7,    9,    9,   10,   12,   12,    6,    7,   21,\n /*    60 */     9,   24,   25,   12,   18,    5,   20,   14,   22,    5,\n /*    70 */    24,    3,    1,    2,    3,    1,    2,    3,    0,    1,\n /*    80 */     2,    3,   11,    2,    3,   11,    9,   10,    5,   12,\n /*    90 */    23,   24,   10,   10,    8,    9,    9,   15,   15,    8,\n /*   100 */     9,    9,   27,   27,   11,   27,   27,   27,   27,   27,\n /*   110 */    27,   27,   27,   27,   27,   27,   27,   27,   27,   27,\n /*   120 */    27,\n};\n#define fts5YY_SHIFT_COUNT    (34)\n#define fts5YY_SHIFT_MIN      (0)\n#define fts5YY_SHIFT_MAX      (93)\nstatic const unsigned char fts5yy_shift_ofst[] = {\n /*     0 */    44,   44,   44,   44,   44,   44,   51,   77,   43,   12,\n /*    10 */    14,   83,   82,   14,   23,   23,   31,   31,   71,   74,\n /*    20 */    78,   81,   86,   91,    6,   53,   53,   60,   64,   68,\n /*    30 */    53,   87,   92,   53,   93,\n};\n#define fts5YY_REDUCE_COUNT (17)\n#define fts5YY_REDUCE_MIN   (-17)\n#define fts5YY_REDUCE_MAX   (67)\nstatic const signed char fts5yy_reduce_ofst[] = {\n /*     0 */   -16,   -8,    0,    9,   17,   25,   46,  -17,  -17,   37,\n /*    10 */    67,    4,    4,    8,    4,   20,   27,   38,\n};\nstatic const fts5YYACTIONTYPE fts5yy_default[] = {\n /*     0 */    80,   80,   80,   80,   80,   80,   95,   80,   80,  105,\n /*    10 */    80,  110,  110,   80,  110,  110,   80,   80,   80,   80,\n /*    20 */    80,   91,   80,   80,   80,  101,  100,   80,   80,   90,\n /*    30 */   103,   80,   80,  104,   80,\n};\n/********** End of lemon-generated parsing tables *****************************/\n\n/* The next table maps tokens (terminal symbols) into fallback tokens.  \n** If a construct like the following:\n** \n**      %fallback ID X Y Z.\n**\n** appears in the grammar, then ID becomes a fallback token for X, Y,\n** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser\n** but it does not parse, the type of the token is changed to ID and\n** the parse is retried before an error is thrown.\n**\n** This feature can be used, for example, to cause some keywords in a language\n** to revert to identifiers if they keyword does not apply in the context where\n** it appears.\n*/\n#ifdef fts5YYFALLBACK\nstatic const fts5YYCODETYPE fts5yyFallback[] = {\n};\n#endif /* fts5YYFALLBACK */\n\n/* The following structure represents a single element of the\n** parser's stack.  Information stored includes:\n**\n**   +  The state number for the parser at this level of the stack.\n**\n**   +  The value of the token stored at this level of the stack.\n**      (In other words, the \"major\" token.)\n**\n**   +  The semantic value stored at this level of the stack.  This is\n**      the information used by the action routines in the grammar.\n**      It is sometimes called the \"minor\" token.\n**\n** After the \"shift\" half of a SHIFTREDUCE action, the stateno field\n** actually contains the reduce action for the second half of the\n** SHIFTREDUCE.\n*/\nstruct fts5yyStackEntry {\n  fts5YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */\n  fts5YYCODETYPE major;      /* The major token value.  This is the code\n                         ** number for the token at this stack level */\n  fts5YYMINORTYPE minor;     /* The user-supplied minor token value.  This\n                         ** is the value of the token  */\n};\ntypedef struct fts5yyStackEntry fts5yyStackEntry;\n\n/* The state of the parser is completely contained in an instance of\n** the following structure */\nstruct fts5yyParser {\n  fts5yyStackEntry *fts5yytos;          /* Pointer to top element of the stack */\n#ifdef fts5YYTRACKMAXSTACKDEPTH\n  int fts5yyhwm;                    /* High-water mark of the stack */\n#endif\n#ifndef fts5YYNOERRORRECOVERY\n  int fts5yyerrcnt;                 /* Shifts left before out of the error */\n#endif\n  sqlite3Fts5ParserARG_SDECL                /* A place to hold %extra_argument */\n  sqlite3Fts5ParserCTX_SDECL                /* A place to hold %extra_context */\n#if fts5YYSTACKDEPTH<=0\n  int fts5yystksz;                  /* Current side of the stack */\n  fts5yyStackEntry *fts5yystack;        /* The parser's stack */\n  fts5yyStackEntry fts5yystk0;          /* First stack entry */\n#else\n  fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH];  /* The parser's stack */\n  fts5yyStackEntry *fts5yystackEnd;            /* Last entry in the stack */\n#endif\n};\ntypedef struct fts5yyParser fts5yyParser;\n\n#ifndef NDEBUG\n/* #include <stdio.h> */\nstatic FILE *fts5yyTraceFILE = 0;\nstatic char *fts5yyTracePrompt = 0;\n#endif /* NDEBUG */\n\n#ifndef NDEBUG\n/* \n** Turn parser tracing on by giving a stream to which to write the trace\n** and a prompt to preface each trace message.  Tracing is turned off\n** by making either argument NULL \n**\n** Inputs:\n** <ul>\n** <li> A FILE* to which trace output should be written.\n**      If NULL, then tracing is turned off.\n** <li> A prefix string written at the beginning of every\n**      line of trace output.  If NULL, then tracing is\n**      turned off.\n** </ul>\n**\n** Outputs:\n** None.\n*/\nstatic void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){\n  fts5yyTraceFILE = TraceFILE;\n  fts5yyTracePrompt = zTracePrompt;\n  if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;\n  else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;\n}\n#endif /* NDEBUG */\n\n#if defined(fts5YYCOVERAGE) || !defined(NDEBUG)\n/* For tracing shifts, the names of all terminals and nonterminals\n** are required.  The following table supplies these names */\nstatic const char *const fts5yyTokenName[] = { \n  /*    0 */ \"$\",\n  /*    1 */ \"OR\",\n  /*    2 */ \"AND\",\n  /*    3 */ \"NOT\",\n  /*    4 */ \"TERM\",\n  /*    5 */ \"COLON\",\n  /*    6 */ \"MINUS\",\n  /*    7 */ \"LCP\",\n  /*    8 */ \"RCP\",\n  /*    9 */ \"STRING\",\n  /*   10 */ \"LP\",\n  /*   11 */ \"RP\",\n  /*   12 */ \"CARET\",\n  /*   13 */ \"COMMA\",\n  /*   14 */ \"PLUS\",\n  /*   15 */ \"STAR\",\n  /*   16 */ \"input\",\n  /*   17 */ \"expr\",\n  /*   18 */ \"cnearset\",\n  /*   19 */ \"exprlist\",\n  /*   20 */ \"colset\",\n  /*   21 */ \"colsetlist\",\n  /*   22 */ \"nearset\",\n  /*   23 */ \"nearphrases\",\n  /*   24 */ \"phrase\",\n  /*   25 */ \"neardist_opt\",\n  /*   26 */ \"star_opt\",\n};\n#endif /* defined(fts5YYCOVERAGE) || !defined(NDEBUG) */\n\n#ifndef NDEBUG\n/* For tracing reduce actions, the names of all rules are required.\n*/\nstatic const char *const fts5yyRuleName[] = {\n /*   0 */ \"input ::= expr\",\n /*   1 */ \"colset ::= MINUS LCP colsetlist RCP\",\n /*   2 */ \"colset ::= LCP colsetlist RCP\",\n /*   3 */ \"colset ::= STRING\",\n /*   4 */ \"colset ::= MINUS STRING\",\n /*   5 */ \"colsetlist ::= colsetlist STRING\",\n /*   6 */ \"colsetlist ::= STRING\",\n /*   7 */ \"expr ::= expr AND expr\",\n /*   8 */ \"expr ::= expr OR expr\",\n /*   9 */ \"expr ::= expr NOT expr\",\n /*  10 */ \"expr ::= colset COLON LP expr RP\",\n /*  11 */ \"expr ::= LP expr RP\",\n /*  12 */ \"expr ::= exprlist\",\n /*  13 */ \"exprlist ::= cnearset\",\n /*  14 */ \"exprlist ::= exprlist cnearset\",\n /*  15 */ \"cnearset ::= nearset\",\n /*  16 */ \"cnearset ::= colset COLON nearset\",\n /*  17 */ \"nearset ::= phrase\",\n /*  18 */ \"nearset ::= CARET phrase\",\n /*  19 */ \"nearset ::= STRING LP nearphrases neardist_opt RP\",\n /*  20 */ \"nearphrases ::= phrase\",\n /*  21 */ \"nearphrases ::= nearphrases phrase\",\n /*  22 */ \"neardist_opt ::=\",\n /*  23 */ \"neardist_opt ::= COMMA STRING\",\n /*  24 */ \"phrase ::= phrase PLUS STRING star_opt\",\n /*  25 */ \"phrase ::= STRING star_opt\",\n /*  26 */ \"star_opt ::= STAR\",\n /*  27 */ \"star_opt ::=\",\n};\n#endif /* NDEBUG */\n\n\n#if fts5YYSTACKDEPTH<=0\n/*\n** Try to increase the size of the parser stack.  Return the number\n** of errors.  Return 0 on success.\n*/\nstatic int fts5yyGrowStack(fts5yyParser *p){\n  int newSize;\n  int idx;\n  fts5yyStackEntry *pNew;\n\n  newSize = p->fts5yystksz*2 + 100;\n  idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;\n  if( p->fts5yystack==&p->fts5yystk0 ){\n    pNew = malloc(newSize*sizeof(pNew[0]));\n    if( pNew ) pNew[0] = p->fts5yystk0;\n  }else{\n    pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));\n  }\n  if( pNew ){\n    p->fts5yystack = pNew;\n    p->fts5yytos = &p->fts5yystack[idx];\n#ifndef NDEBUG\n    if( fts5yyTraceFILE ){\n      fprintf(fts5yyTraceFILE,\"%sStack grows from %d to %d entries.\\n\",\n              fts5yyTracePrompt, p->fts5yystksz, newSize);\n    }\n#endif\n    p->fts5yystksz = newSize;\n  }\n  return pNew==0; \n}\n#endif\n\n/* Datatype of the argument to the memory allocated passed as the\n** second argument to sqlite3Fts5ParserAlloc() below.  This can be changed by\n** putting an appropriate #define in the %include section of the input\n** grammar.\n*/\n#ifndef fts5YYMALLOCARGTYPE\n# define fts5YYMALLOCARGTYPE size_t\n#endif\n\n/* Initialize a new parser that has already been allocated.\n*/\nstatic void sqlite3Fts5ParserInit(void *fts5yypRawParser sqlite3Fts5ParserCTX_PDECL){\n  fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yypRawParser;\n  sqlite3Fts5ParserCTX_STORE\n#ifdef fts5YYTRACKMAXSTACKDEPTH\n  fts5yypParser->fts5yyhwm = 0;\n#endif\n#if fts5YYSTACKDEPTH<=0\n  fts5yypParser->fts5yytos = NULL;\n  fts5yypParser->fts5yystack = NULL;\n  fts5yypParser->fts5yystksz = 0;\n  if( fts5yyGrowStack(fts5yypParser) ){\n    fts5yypParser->fts5yystack = &fts5yypParser->fts5yystk0;\n    fts5yypParser->fts5yystksz = 1;\n  }\n#endif\n#ifndef fts5YYNOERRORRECOVERY\n  fts5yypParser->fts5yyerrcnt = -1;\n#endif\n  fts5yypParser->fts5yytos = fts5yypParser->fts5yystack;\n  fts5yypParser->fts5yystack[0].stateno = 0;\n  fts5yypParser->fts5yystack[0].major = 0;\n#if fts5YYSTACKDEPTH>0\n  fts5yypParser->fts5yystackEnd = &fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1];\n#endif\n}\n\n#ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK\n/* \n** This function allocates a new parser.\n** The only argument is a pointer to a function which works like\n** malloc.\n**\n** Inputs:\n** A pointer to the function used to allocate memory.\n**\n** Outputs:\n** A pointer to a parser.  This pointer is used in subsequent calls\n** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.\n*/\nstatic void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE) sqlite3Fts5ParserCTX_PDECL){\n  fts5yyParser *fts5yypParser;\n  fts5yypParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );\n  if( fts5yypParser ){\n    sqlite3Fts5ParserCTX_STORE\n    sqlite3Fts5ParserInit(fts5yypParser sqlite3Fts5ParserCTX_PARAM);\n  }\n  return (void*)fts5yypParser;\n}\n#endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */\n\n\n/* The following function deletes the \"minor type\" or semantic value\n** associated with a symbol.  The symbol can be either a terminal\n** or nonterminal. \"fts5yymajor\" is the symbol code, and \"fts5yypminor\" is\n** a pointer to the value to be deleted.  The code used to do the \n** deletions is derived from the %destructor and/or %token_destructor\n** directives of the input grammar.\n*/\nstatic void fts5yy_destructor(\n  fts5yyParser *fts5yypParser,    /* The parser */\n  fts5YYCODETYPE fts5yymajor,     /* Type code for object to destroy */\n  fts5YYMINORTYPE *fts5yypminor   /* The object to be destroyed */\n){\n  sqlite3Fts5ParserARG_FETCH\n  sqlite3Fts5ParserCTX_FETCH\n  switch( fts5yymajor ){\n    /* Here is inserted the actions which take place when a\n    ** terminal or non-terminal is destroyed.  This can happen\n    ** when the symbol is popped from the stack during a\n    ** reduce or during error processing or when a parser is \n    ** being destroyed before it is finished parsing.\n    **\n    ** Note: during a reduce, the only symbols destroyed are those\n    ** which appear on the RHS of the rule, but which are *not* used\n    ** inside the C code.\n    */\n/********* Begin destructor definitions ***************************************/\n    case 16: /* input */\n{\n (void)pParse; \n}\n      break;\n    case 17: /* expr */\n    case 18: /* cnearset */\n    case 19: /* exprlist */\n{\n sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24)); \n}\n      break;\n    case 20: /* colset */\n    case 21: /* colsetlist */\n{\n sqlite3_free((fts5yypminor->fts5yy11)); \n}\n      break;\n    case 22: /* nearset */\n    case 23: /* nearphrases */\n{\n sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46)); \n}\n      break;\n    case 24: /* phrase */\n{\n sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53)); \n}\n      break;\n/********* End destructor definitions *****************************************/\n    default:  break;   /* If no destructor action specified: do nothing */\n  }\n}\n\n/*\n** Pop the parser's stack once.\n**\n** If there is a destructor routine associated with the token which\n** is popped from the stack, then call it.\n*/\nstatic void fts5yy_pop_parser_stack(fts5yyParser *pParser){\n  fts5yyStackEntry *fts5yytos;\n  assert( pParser->fts5yytos!=0 );\n  assert( pParser->fts5yytos > pParser->fts5yystack );\n  fts5yytos = pParser->fts5yytos--;\n#ifndef NDEBUG\n  if( fts5yyTraceFILE ){\n    fprintf(fts5yyTraceFILE,\"%sPopping %s\\n\",\n      fts5yyTracePrompt,\n      fts5yyTokenName[fts5yytos->major]);\n  }\n#endif\n  fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);\n}\n\n/*\n** Clear all secondary memory allocations from the parser\n*/\nstatic void sqlite3Fts5ParserFinalize(void *p){\n  fts5yyParser *pParser = (fts5yyParser*)p;\n  while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);\n#if fts5YYSTACKDEPTH<=0\n  if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);\n#endif\n}\n\n#ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK\n/* \n** Deallocate and destroy a parser.  Destructors are called for\n** all stack elements before shutting the parser down.\n**\n** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it\n** is defined in a %include section of the input grammar) then it is\n** assumed that the input pointer is never NULL.\n*/\nstatic void sqlite3Fts5ParserFree(\n  void *p,                    /* The parser to be deleted */\n  void (*freeProc)(void*)     /* Function used to reclaim memory */\n){\n#ifndef fts5YYPARSEFREENEVERNULL\n  if( p==0 ) return;\n#endif\n  sqlite3Fts5ParserFinalize(p);\n  (*freeProc)(p);\n}\n#endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */\n\n/*\n** Return the peak depth of the stack for a parser.\n*/\n#ifdef fts5YYTRACKMAXSTACKDEPTH\nstatic int sqlite3Fts5ParserStackPeak(void *p){\n  fts5yyParser *pParser = (fts5yyParser*)p;\n  return pParser->fts5yyhwm;\n}\n#endif\n\n/* This array of booleans keeps track of the parser statement\n** coverage.  The element fts5yycoverage[X][Y] is set when the parser\n** is in state X and has a lookahead token Y.  In a well-tested\n** systems, every element of this matrix should end up being set.\n*/\n#if defined(fts5YYCOVERAGE)\nstatic unsigned char fts5yycoverage[fts5YYNSTATE][fts5YYNFTS5TOKEN];\n#endif\n\n/*\n** Write into out a description of every state/lookahead combination that\n**\n**   (1)  has not been used by the parser, and\n**   (2)  is not a syntax error.\n**\n** Return the number of missed state/lookahead combinations.\n*/\n#if defined(fts5YYCOVERAGE)\nstatic int sqlite3Fts5ParserCoverage(FILE *out){\n  int stateno, iLookAhead, i;\n  int nMissed = 0;\n  for(stateno=0; stateno<fts5YYNSTATE; stateno++){\n    i = fts5yy_shift_ofst[stateno];\n    for(iLookAhead=0; iLookAhead<fts5YYNFTS5TOKEN; iLookAhead++){\n      if( fts5yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;\n      if( fts5yycoverage[stateno][iLookAhead]==0 ) nMissed++;\n      if( out ){\n        fprintf(out,\"State %d lookahead %s %s\\n\", stateno,\n                fts5yyTokenName[iLookAhead],\n                fts5yycoverage[stateno][iLookAhead] ? \"ok\" : \"missed\");\n      }\n    }\n  }\n  return nMissed;\n}\n#endif\n\n/*\n** Find the appropriate action for a parser given the terminal\n** look-ahead token iLookAhead.\n*/\nstatic fts5YYACTIONTYPE fts5yy_find_shift_action(\n  fts5YYCODETYPE iLookAhead,    /* The look-ahead token */\n  fts5YYACTIONTYPE stateno      /* Current state number */\n){\n  int i;\n\n  if( stateno>fts5YY_MAX_SHIFT ) return stateno;\n  assert( stateno <= fts5YY_SHIFT_COUNT );\n#if defined(fts5YYCOVERAGE)\n  fts5yycoverage[stateno][iLookAhead] = 1;\n#endif\n  do{\n    i = fts5yy_shift_ofst[stateno];\n    assert( i>=0 );\n    assert( i<=fts5YY_ACTTAB_COUNT );\n    assert( i+fts5YYNFTS5TOKEN<=(int)fts5YY_NLOOKAHEAD );\n    assert( iLookAhead!=fts5YYNOCODE );\n    assert( iLookAhead < fts5YYNFTS5TOKEN );\n    i += iLookAhead;\n    assert( i<(int)fts5YY_NLOOKAHEAD );\n    if( fts5yy_lookahead[i]!=iLookAhead ){\n#ifdef fts5YYFALLBACK\n      fts5YYCODETYPE iFallback;            /* Fallback token */\n      assert( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0]) );\n      iFallback = fts5yyFallback[iLookAhead];\n      if( iFallback!=0 ){\n#ifndef NDEBUG\n        if( fts5yyTraceFILE ){\n          fprintf(fts5yyTraceFILE, \"%sFALLBACK %s => %s\\n\",\n             fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);\n        }\n#endif\n        assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */\n        iLookAhead = iFallback;\n        continue;\n      }\n#endif\n#ifdef fts5YYWILDCARD\n      {\n        int j = i - iLookAhead + fts5YYWILDCARD;\n        assert( j<(int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])) );\n        if( fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0 ){\n#ifndef NDEBUG\n          if( fts5yyTraceFILE ){\n            fprintf(fts5yyTraceFILE, \"%sWILDCARD %s => %s\\n\",\n               fts5yyTracePrompt, fts5yyTokenName[iLookAhead],\n               fts5yyTokenName[fts5YYWILDCARD]);\n          }\n#endif /* NDEBUG */\n          return fts5yy_action[j];\n        }\n      }\n#endif /* fts5YYWILDCARD */\n      return fts5yy_default[stateno];\n    }else{\n      assert( i>=0 && i<sizeof(fts5yy_action)/sizeof(fts5yy_action[0]) );\n      return fts5yy_action[i];\n    }\n  }while(1);\n}\n\n/*\n** Find the appropriate action for a parser given the non-terminal\n** look-ahead token iLookAhead.\n*/\nstatic fts5YYACTIONTYPE fts5yy_find_reduce_action(\n  fts5YYACTIONTYPE stateno,     /* Current state number */\n  fts5YYCODETYPE iLookAhead     /* The look-ahead token */\n){\n  int i;\n#ifdef fts5YYERRORSYMBOL\n  if( stateno>fts5YY_REDUCE_COUNT ){\n    return fts5yy_default[stateno];\n  }\n#else\n  assert( stateno<=fts5YY_REDUCE_COUNT );\n#endif\n  i = fts5yy_reduce_ofst[stateno];\n  assert( iLookAhead!=fts5YYNOCODE );\n  i += iLookAhead;\n#ifdef fts5YYERRORSYMBOL\n  if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){\n    return fts5yy_default[stateno];\n  }\n#else\n  assert( i>=0 && i<fts5YY_ACTTAB_COUNT );\n  assert( fts5yy_lookahead[i]==iLookAhead );\n#endif\n  return fts5yy_action[i];\n}\n\n/*\n** The following routine is called if the stack overflows.\n*/\nstatic void fts5yyStackOverflow(fts5yyParser *fts5yypParser){\n   sqlite3Fts5ParserARG_FETCH\n   sqlite3Fts5ParserCTX_FETCH\n#ifndef NDEBUG\n   if( fts5yyTraceFILE ){\n     fprintf(fts5yyTraceFILE,\"%sStack Overflow!\\n\",fts5yyTracePrompt);\n   }\n#endif\n   while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);\n   /* Here code is inserted which will execute if the parser\n   ** stack every overflows */\n/******** Begin %stack_overflow code ******************************************/\n\n  sqlite3Fts5ParseError(pParse, \"fts5: parser stack overflow\");\n/******** End %stack_overflow code ********************************************/\n   sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument var */\n   sqlite3Fts5ParserCTX_STORE\n}\n\n/*\n** Print tracing information for a SHIFT action\n*/\n#ifndef NDEBUG\nstatic void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState, const char *zTag){\n  if( fts5yyTraceFILE ){\n    if( fts5yyNewState<fts5YYNSTATE ){\n      fprintf(fts5yyTraceFILE,\"%s%s '%s', go to state %d\\n\",\n         fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],\n         fts5yyNewState);\n    }else{\n      fprintf(fts5yyTraceFILE,\"%s%s '%s', pending reduce %d\\n\",\n         fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],\n         fts5yyNewState - fts5YY_MIN_REDUCE);\n    }\n  }\n}\n#else\n# define fts5yyTraceShift(X,Y,Z)\n#endif\n\n/*\n** Perform a shift action.\n*/\nstatic void fts5yy_shift(\n  fts5yyParser *fts5yypParser,          /* The parser to be shifted */\n  fts5YYACTIONTYPE fts5yyNewState,      /* The new state to shift in */\n  fts5YYCODETYPE fts5yyMajor,           /* The major token to shift in */\n  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor        /* The minor token to shift in */\n){\n  fts5yyStackEntry *fts5yytos;\n  fts5yypParser->fts5yytos++;\n#ifdef fts5YYTRACKMAXSTACKDEPTH\n  if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){\n    fts5yypParser->fts5yyhwm++;\n    assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );\n  }\n#endif\n#if fts5YYSTACKDEPTH>0 \n  if( fts5yypParser->fts5yytos>fts5yypParser->fts5yystackEnd ){\n    fts5yypParser->fts5yytos--;\n    fts5yyStackOverflow(fts5yypParser);\n    return;\n  }\n#else\n  if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){\n    if( fts5yyGrowStack(fts5yypParser) ){\n      fts5yypParser->fts5yytos--;\n      fts5yyStackOverflow(fts5yypParser);\n      return;\n    }\n  }\n#endif\n  if( fts5yyNewState > fts5YY_MAX_SHIFT ){\n    fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;\n  }\n  fts5yytos = fts5yypParser->fts5yytos;\n  fts5yytos->stateno = fts5yyNewState;\n  fts5yytos->major = fts5yyMajor;\n  fts5yytos->minor.fts5yy0 = fts5yyMinor;\n  fts5yyTraceShift(fts5yypParser, fts5yyNewState, \"Shift\");\n}\n\n/* For rule J, fts5yyRuleInfoLhs[J] contains the symbol on the left-hand side\n** of that rule */\nstatic const fts5YYCODETYPE fts5yyRuleInfoLhs[] = {\n    16,  /* (0) input ::= expr */\n    20,  /* (1) colset ::= MINUS LCP colsetlist RCP */\n    20,  /* (2) colset ::= LCP colsetlist RCP */\n    20,  /* (3) colset ::= STRING */\n    20,  /* (4) colset ::= MINUS STRING */\n    21,  /* (5) colsetlist ::= colsetlist STRING */\n    21,  /* (6) colsetlist ::= STRING */\n    17,  /* (7) expr ::= expr AND expr */\n    17,  /* (8) expr ::= expr OR expr */\n    17,  /* (9) expr ::= expr NOT expr */\n    17,  /* (10) expr ::= colset COLON LP expr RP */\n    17,  /* (11) expr ::= LP expr RP */\n    17,  /* (12) expr ::= exprlist */\n    19,  /* (13) exprlist ::= cnearset */\n    19,  /* (14) exprlist ::= exprlist cnearset */\n    18,  /* (15) cnearset ::= nearset */\n    18,  /* (16) cnearset ::= colset COLON nearset */\n    22,  /* (17) nearset ::= phrase */\n    22,  /* (18) nearset ::= CARET phrase */\n    22,  /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */\n    23,  /* (20) nearphrases ::= phrase */\n    23,  /* (21) nearphrases ::= nearphrases phrase */\n    25,  /* (22) neardist_opt ::= */\n    25,  /* (23) neardist_opt ::= COMMA STRING */\n    24,  /* (24) phrase ::= phrase PLUS STRING star_opt */\n    24,  /* (25) phrase ::= STRING star_opt */\n    26,  /* (26) star_opt ::= STAR */\n    26,  /* (27) star_opt ::= */\n};\n\n/* For rule J, fts5yyRuleInfoNRhs[J] contains the negative of the number\n** of symbols on the right-hand side of that rule. */\nstatic const signed char fts5yyRuleInfoNRhs[] = {\n   -1,  /* (0) input ::= expr */\n   -4,  /* (1) colset ::= MINUS LCP colsetlist RCP */\n   -3,  /* (2) colset ::= LCP colsetlist RCP */\n   -1,  /* (3) colset ::= STRING */\n   -2,  /* (4) colset ::= MINUS STRING */\n   -2,  /* (5) colsetlist ::= colsetlist STRING */\n   -1,  /* (6) colsetlist ::= STRING */\n   -3,  /* (7) expr ::= expr AND expr */\n   -3,  /* (8) expr ::= expr OR expr */\n   -3,  /* (9) expr ::= expr NOT expr */\n   -5,  /* (10) expr ::= colset COLON LP expr RP */\n   -3,  /* (11) expr ::= LP expr RP */\n   -1,  /* (12) expr ::= exprlist */\n   -1,  /* (13) exprlist ::= cnearset */\n   -2,  /* (14) exprlist ::= exprlist cnearset */\n   -1,  /* (15) cnearset ::= nearset */\n   -3,  /* (16) cnearset ::= colset COLON nearset */\n   -1,  /* (17) nearset ::= phrase */\n   -2,  /* (18) nearset ::= CARET phrase */\n   -5,  /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */\n   -1,  /* (20) nearphrases ::= phrase */\n   -2,  /* (21) nearphrases ::= nearphrases phrase */\n    0,  /* (22) neardist_opt ::= */\n   -2,  /* (23) neardist_opt ::= COMMA STRING */\n   -4,  /* (24) phrase ::= phrase PLUS STRING star_opt */\n   -2,  /* (25) phrase ::= STRING star_opt */\n   -1,  /* (26) star_opt ::= STAR */\n    0,  /* (27) star_opt ::= */\n};\n\nstatic void fts5yy_accept(fts5yyParser*);  /* Forward Declaration */\n\n/*\n** Perform a reduce action and the shift that must immediately\n** follow the reduce.\n**\n** The fts5yyLookahead and fts5yyLookaheadToken parameters provide reduce actions\n** access to the lookahead token (if any).  The fts5yyLookahead will be fts5YYNOCODE\n** if the lookahead token has already been consumed.  As this procedure is\n** only called from one place, optimizing compilers will in-line it, which\n** means that the extra parameters have no performance impact.\n*/\nstatic fts5YYACTIONTYPE fts5yy_reduce(\n  fts5yyParser *fts5yypParser,         /* The parser */\n  unsigned int fts5yyruleno,       /* Number of the rule by which to reduce */\n  int fts5yyLookahead,             /* Lookahead token, or fts5YYNOCODE if none */\n  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyLookaheadToken  /* Value of the lookahead token */\n  sqlite3Fts5ParserCTX_PDECL                   /* %extra_context */\n){\n  int fts5yygoto;                     /* The next state */\n  fts5YYACTIONTYPE fts5yyact;             /* The next action */\n  fts5yyStackEntry *fts5yymsp;            /* The top of the parser's stack */\n  int fts5yysize;                     /* Amount to pop the stack */\n  sqlite3Fts5ParserARG_FETCH\n  (void)fts5yyLookahead;\n  (void)fts5yyLookaheadToken;\n  fts5yymsp = fts5yypParser->fts5yytos;\n#ifndef NDEBUG\n  if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){\n    fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno];\n    if( fts5yysize ){\n      fprintf(fts5yyTraceFILE, \"%sReduce %d [%s]%s, pop back to state %d.\\n\",\n        fts5yyTracePrompt,\n        fts5yyruleno, fts5yyRuleName[fts5yyruleno],\n        fts5yyruleno<fts5YYNRULE_WITH_ACTION ? \"\" : \" without external action\",\n        fts5yymsp[fts5yysize].stateno);\n    }else{\n      fprintf(fts5yyTraceFILE, \"%sReduce %d [%s]%s.\\n\",\n        fts5yyTracePrompt, fts5yyruleno, fts5yyRuleName[fts5yyruleno],\n        fts5yyruleno<fts5YYNRULE_WITH_ACTION ? \"\" : \" without external action\");\n    }\n  }\n#endif /* NDEBUG */\n\n  /* Check that the stack is large enough to grow by a single entry\n  ** if the RHS of the rule is empty.  This ensures that there is room\n  ** enough on the stack to push the LHS value */\n  if( fts5yyRuleInfoNRhs[fts5yyruleno]==0 ){\n#ifdef fts5YYTRACKMAXSTACKDEPTH\n    if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){\n      fts5yypParser->fts5yyhwm++;\n      assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));\n    }\n#endif\n#if fts5YYSTACKDEPTH>0 \n    if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){\n      fts5yyStackOverflow(fts5yypParser);\n      /* The call to fts5yyStackOverflow() above pops the stack until it is\n      ** empty, causing the main parser loop to exit.  So the return value\n      ** is never used and does not matter. */\n      return 0;\n    }\n#else\n    if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){\n      if( fts5yyGrowStack(fts5yypParser) ){\n        fts5yyStackOverflow(fts5yypParser);\n        /* The call to fts5yyStackOverflow() above pops the stack until it is\n        ** empty, causing the main parser loop to exit.  So the return value\n        ** is never used and does not matter. */\n        return 0;\n      }\n      fts5yymsp = fts5yypParser->fts5yytos;\n    }\n#endif\n  }\n\n  switch( fts5yyruleno ){\n  /* Beginning here are the reduction cases.  A typical example\n  ** follows:\n  **   case 0:\n  **  #line <lineno> <grammarfile>\n  **     { ... }           // User supplied code\n  **  #line <lineno> <thisfile>\n  **     break;\n  */\n/********** Begin reduce actions **********************************************/\n        fts5YYMINORTYPE fts5yylhsminor;\n      case 0: /* input ::= expr */\n{ sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }\n        break;\n      case 1: /* colset ::= MINUS LCP colsetlist RCP */\n{ \n    fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);\n}\n        break;\n      case 2: /* colset ::= LCP colsetlist RCP */\n{ fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }\n        break;\n      case 3: /* colset ::= STRING */\n{\n  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);\n}\n  fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;\n        break;\n      case 4: /* colset ::= MINUS STRING */\n{\n  fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);\n  fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);\n}\n        break;\n      case 5: /* colsetlist ::= colsetlist STRING */\n{ \n  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }\n  fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;\n        break;\n      case 6: /* colsetlist ::= STRING */\n{ \n  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0); \n}\n  fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;\n        break;\n      case 7: /* expr ::= expr AND expr */\n{\n  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);\n}\n  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;\n        break;\n      case 8: /* expr ::= expr OR expr */\n{\n  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);\n}\n  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;\n        break;\n      case 9: /* expr ::= expr NOT expr */\n{\n  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);\n}\n  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;\n        break;\n      case 10: /* expr ::= colset COLON LP expr RP */\n{\n  sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[-4].minor.fts5yy11);\n  fts5yylhsminor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;\n}\n  fts5yymsp[-4].minor.fts5yy24 = fts5yylhsminor.fts5yy24;\n        break;\n      case 11: /* expr ::= LP expr RP */\n{fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}\n        break;\n      case 12: /* expr ::= exprlist */\n      case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);\n{fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}\n  fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;\n        break;\n      case 14: /* exprlist ::= exprlist cnearset */\n{\n  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);\n}\n  fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;\n        break;\n      case 15: /* cnearset ::= nearset */\n{ \n  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46); \n}\n  fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;\n        break;\n      case 16: /* cnearset ::= colset COLON nearset */\n{ \n  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46); \n  sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11);\n}\n  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;\n        break;\n      case 17: /* nearset ::= phrase */\n{ fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }\n  fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;\n        break;\n      case 18: /* nearset ::= CARET phrase */\n{ \n  sqlite3Fts5ParseSetCaret(fts5yymsp[0].minor.fts5yy53);\n  fts5yymsp[-1].minor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); \n}\n        break;\n      case 19: /* nearset ::= STRING LP nearphrases neardist_opt RP */\n{\n  sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);\n  sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);\n  fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;\n}\n  fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;\n        break;\n      case 20: /* nearphrases ::= phrase */\n{ \n  fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); \n}\n  fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;\n        break;\n      case 21: /* nearphrases ::= nearphrases phrase */\n{\n  fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);\n}\n  fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;\n        break;\n      case 22: /* neardist_opt ::= */\n{ fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }\n        break;\n      case 23: /* neardist_opt ::= COMMA STRING */\n{ fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }\n        break;\n      case 24: /* phrase ::= phrase PLUS STRING star_opt */\n{ \n  fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);\n}\n  fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;\n        break;\n      case 25: /* phrase ::= STRING star_opt */\n{ \n  fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);\n}\n  fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;\n        break;\n      case 26: /* star_opt ::= STAR */\n{ fts5yymsp[0].minor.fts5yy4 = 1; }\n        break;\n      case 27: /* star_opt ::= */\n{ fts5yymsp[1].minor.fts5yy4 = 0; }\n        break;\n      default:\n        break;\n/********** End reduce actions ************************************************/\n  };\n  assert( fts5yyruleno<sizeof(fts5yyRuleInfoLhs)/sizeof(fts5yyRuleInfoLhs[0]) );\n  fts5yygoto = fts5yyRuleInfoLhs[fts5yyruleno];\n  fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno];\n  fts5yyact = fts5yy_find_reduce_action(fts5yymsp[fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);\n\n  /* There are no SHIFTREDUCE actions on nonterminals because the table\n  ** generator has simplified them to pure REDUCE actions. */\n  assert( !(fts5yyact>fts5YY_MAX_SHIFT && fts5yyact<=fts5YY_MAX_SHIFTREDUCE) );\n\n  /* It is not possible for a REDUCE to be followed by an error */\n  assert( fts5yyact!=fts5YY_ERROR_ACTION );\n\n  fts5yymsp += fts5yysize+1;\n  fts5yypParser->fts5yytos = fts5yymsp;\n  fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;\n  fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;\n  fts5yyTraceShift(fts5yypParser, fts5yyact, \"... then shift\");\n  return fts5yyact;\n}\n\n/*\n** The following code executes when the parse fails\n*/\n#ifndef fts5YYNOERRORRECOVERY\nstatic void fts5yy_parse_failed(\n  fts5yyParser *fts5yypParser           /* The parser */\n){\n  sqlite3Fts5ParserARG_FETCH\n  sqlite3Fts5ParserCTX_FETCH\n#ifndef NDEBUG\n  if( fts5yyTraceFILE ){\n    fprintf(fts5yyTraceFILE,\"%sFail!\\n\",fts5yyTracePrompt);\n  }\n#endif\n  while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);\n  /* Here code is inserted which will be executed whenever the\n  ** parser fails */\n/************ Begin %parse_failure code ***************************************/\n/************ End %parse_failure code *****************************************/\n  sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */\n  sqlite3Fts5ParserCTX_STORE\n}\n#endif /* fts5YYNOERRORRECOVERY */\n\n/*\n** The following code executes when a syntax error first occurs.\n*/\nstatic void fts5yy_syntax_error(\n  fts5yyParser *fts5yypParser,           /* The parser */\n  int fts5yymajor,                   /* The major type of the error token */\n  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor         /* The minor type of the error token */\n){\n  sqlite3Fts5ParserARG_FETCH\n  sqlite3Fts5ParserCTX_FETCH\n#define FTS5TOKEN fts5yyminor\n/************ Begin %syntax_error code ****************************************/\n\n  UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */\n  sqlite3Fts5ParseError(\n    pParse, \"fts5: syntax error near \\\"%.*s\\\"\",FTS5TOKEN.n,FTS5TOKEN.p\n  );\n/************ End %syntax_error code ******************************************/\n  sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */\n  sqlite3Fts5ParserCTX_STORE\n}\n\n/*\n** The following is executed when the parser accepts\n*/\nstatic void fts5yy_accept(\n  fts5yyParser *fts5yypParser           /* The parser */\n){\n  sqlite3Fts5ParserARG_FETCH\n  sqlite3Fts5ParserCTX_FETCH\n#ifndef NDEBUG\n  if( fts5yyTraceFILE ){\n    fprintf(fts5yyTraceFILE,\"%sAccept!\\n\",fts5yyTracePrompt);\n  }\n#endif\n#ifndef fts5YYNOERRORRECOVERY\n  fts5yypParser->fts5yyerrcnt = -1;\n#endif\n  assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );\n  /* Here code is inserted which will be executed whenever the\n  ** parser accepts */\n/*********** Begin %parse_accept code *****************************************/\n/*********** End %parse_accept code *******************************************/\n  sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */\n  sqlite3Fts5ParserCTX_STORE\n}\n\n/* The main parser program.\n** The first argument is a pointer to a structure obtained from\n** \"sqlite3Fts5ParserAlloc\" which describes the current state of the parser.\n** The second argument is the major token number.  The third is\n** the minor token.  The fourth optional argument is whatever the\n** user wants (and specified in the grammar) and is available for\n** use by the action routines.\n**\n** Inputs:\n** <ul>\n** <li> A pointer to the parser (an opaque structure.)\n** <li> The major token number.\n** <li> The minor token number.\n** <li> An option argument of a grammar-specified type.\n** </ul>\n**\n** Outputs:\n** None.\n*/\nstatic void sqlite3Fts5Parser(\n  void *fts5yyp,                   /* The parser */\n  int fts5yymajor,                 /* The major token code number */\n  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor       /* The value for the token */\n  sqlite3Fts5ParserARG_PDECL               /* Optional %extra_argument parameter */\n){\n  fts5YYMINORTYPE fts5yyminorunion;\n  fts5YYACTIONTYPE fts5yyact;   /* The parser action. */\n#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)\n  int fts5yyendofinput;     /* True if we are at the end of input */\n#endif\n#ifdef fts5YYERRORSYMBOL\n  int fts5yyerrorhit = 0;   /* True if fts5yymajor has invoked an error */\n#endif\n  fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yyp;  /* The parser */\n  sqlite3Fts5ParserCTX_FETCH\n  sqlite3Fts5ParserARG_STORE\n\n  assert( fts5yypParser->fts5yytos!=0 );\n#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)\n  fts5yyendofinput = (fts5yymajor==0);\n#endif\n\n  fts5yyact = fts5yypParser->fts5yytos->stateno;\n#ifndef NDEBUG\n  if( fts5yyTraceFILE ){\n    if( fts5yyact < fts5YY_MIN_REDUCE ){\n      fprintf(fts5yyTraceFILE,\"%sInput '%s' in state %d\\n\",\n              fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact);\n    }else{\n      fprintf(fts5yyTraceFILE,\"%sInput '%s' with pending reduce %d\\n\",\n              fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact-fts5YY_MIN_REDUCE);\n    }\n  }\n#endif\n\n  do{\n    assert( fts5yyact==fts5yypParser->fts5yytos->stateno );\n    fts5yyact = fts5yy_find_shift_action((fts5YYCODETYPE)fts5yymajor,fts5yyact);\n    if( fts5yyact >= fts5YY_MIN_REDUCE ){\n      fts5yyact = fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE,fts5yymajor,\n                        fts5yyminor sqlite3Fts5ParserCTX_PARAM);\n    }else if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){\n      fts5yy_shift(fts5yypParser,fts5yyact,(fts5YYCODETYPE)fts5yymajor,fts5yyminor);\n#ifndef fts5YYNOERRORRECOVERY\n      fts5yypParser->fts5yyerrcnt--;\n#endif\n      break;\n    }else if( fts5yyact==fts5YY_ACCEPT_ACTION ){\n      fts5yypParser->fts5yytos--;\n      fts5yy_accept(fts5yypParser);\n      return;\n    }else{\n      assert( fts5yyact == fts5YY_ERROR_ACTION );\n      fts5yyminorunion.fts5yy0 = fts5yyminor;\n#ifdef fts5YYERRORSYMBOL\n      int fts5yymx;\n#endif\n#ifndef NDEBUG\n      if( fts5yyTraceFILE ){\n        fprintf(fts5yyTraceFILE,\"%sSyntax Error!\\n\",fts5yyTracePrompt);\n      }\n#endif\n#ifdef fts5YYERRORSYMBOL\n      /* A syntax error has occurred.\n      ** The response to an error depends upon whether or not the\n      ** grammar defines an error token \"ERROR\".  \n      **\n      ** This is what we do if the grammar does define ERROR:\n      **\n      **  * Call the %syntax_error function.\n      **\n      **  * Begin popping the stack until we enter a state where\n      **    it is legal to shift the error symbol, then shift\n      **    the error symbol.\n      **\n      **  * Set the error count to three.\n      **\n      **  * Begin accepting and shifting new tokens.  No new error\n      **    processing will occur until three tokens have been\n      **    shifted successfully.\n      **\n      */\n      if( fts5yypParser->fts5yyerrcnt<0 ){\n        fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);\n      }\n      fts5yymx = fts5yypParser->fts5yytos->major;\n      if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){\n#ifndef NDEBUG\n        if( fts5yyTraceFILE ){\n          fprintf(fts5yyTraceFILE,\"%sDiscard input token %s\\n\",\n             fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);\n        }\n#endif\n        fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);\n        fts5yymajor = fts5YYNOCODE;\n      }else{\n        while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack\n            && (fts5yyact = fts5yy_find_reduce_action(\n                        fts5yypParser->fts5yytos->stateno,\n                        fts5YYERRORSYMBOL)) > fts5YY_MAX_SHIFTREDUCE\n        ){\n          fts5yy_pop_parser_stack(fts5yypParser);\n        }\n        if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){\n          fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);\n          fts5yy_parse_failed(fts5yypParser);\n#ifndef fts5YYNOERRORRECOVERY\n          fts5yypParser->fts5yyerrcnt = -1;\n#endif\n          fts5yymajor = fts5YYNOCODE;\n        }else if( fts5yymx!=fts5YYERRORSYMBOL ){\n          fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);\n        }\n      }\n      fts5yypParser->fts5yyerrcnt = 3;\n      fts5yyerrorhit = 1;\n      if( fts5yymajor==fts5YYNOCODE ) break;\n      fts5yyact = fts5yypParser->fts5yytos->stateno;\n#elif defined(fts5YYNOERRORRECOVERY)\n      /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to\n      ** do any kind of error recovery.  Instead, simply invoke the syntax\n      ** error routine and continue going as if nothing had happened.\n      **\n      ** Applications can set this macro (for example inside %include) if\n      ** they intend to abandon the parse upon the first syntax error seen.\n      */\n      fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);\n      fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);\n      break;\n#else  /* fts5YYERRORSYMBOL is not defined */\n      /* This is what we do if the grammar does not define ERROR:\n      **\n      **  * Report an error message, and throw away the input token.\n      **\n      **  * If the input token is $, then fail the parse.\n      **\n      ** As before, subsequent error messages are suppressed until\n      ** three input tokens have been successfully shifted.\n      */\n      if( fts5yypParser->fts5yyerrcnt<=0 ){\n        fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);\n      }\n      fts5yypParser->fts5yyerrcnt = 3;\n      fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);\n      if( fts5yyendofinput ){\n        fts5yy_parse_failed(fts5yypParser);\n#ifndef fts5YYNOERRORRECOVERY\n        fts5yypParser->fts5yyerrcnt = -1;\n#endif\n      }\n      break;\n#endif\n    }\n  }while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );\n#ifndef NDEBUG\n  if( fts5yyTraceFILE ){\n    fts5yyStackEntry *i;\n    char cDiv = '[';\n    fprintf(fts5yyTraceFILE,\"%sReturn. Stack=\",fts5yyTracePrompt);\n    for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){\n      fprintf(fts5yyTraceFILE,\"%c%s\", cDiv, fts5yyTokenName[i->major]);\n      cDiv = ' ';\n    }\n    fprintf(fts5yyTraceFILE,\"]\\n\");\n  }\n#endif\n  return;\n}\n\n/*\n** Return the fallback token corresponding to canonical token iToken, or\n** 0 if iToken has no fallback.\n*/\nstatic int sqlite3Fts5ParserFallback(int iToken){\n#ifdef fts5YYFALLBACK\n  assert( iToken<(int)(sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])) );\n  return fts5yyFallback[iToken];\n#else\n  (void)iToken;\n  return 0;\n#endif\n}\n\n/*\n** 2014 May 31\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n*/\n\n\n/* #include \"fts5Int.h\" */\n#include <math.h>                 /* amalgamator: keep */\n\n/*\n** Object used to iterate through all \"coalesced phrase instances\" in \n** a single column of the current row. If the phrase instances in the\n** column being considered do not overlap, this object simply iterates\n** through them. Or, if they do overlap (share one or more tokens in\n** common), each set of overlapping instances is treated as a single\n** match. See documentation for the highlight() auxiliary function for\n** details.\n**\n** Usage is:\n**\n**   for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);\n**      (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);\n**      rc = fts5CInstIterNext(&iter)\n**   ){\n**     printf(\"instance starts at %d, ends at %d\\n\", iter.iStart, iter.iEnd);\n**   }\n**\n*/\ntypedef struct CInstIter CInstIter;\nstruct CInstIter {\n  const Fts5ExtensionApi *pApi;   /* API offered by current FTS version */\n  Fts5Context *pFts;              /* First arg to pass to pApi functions */\n  int iCol;                       /* Column to search */\n  int iInst;                      /* Next phrase instance index */\n  int nInst;                      /* Total number of phrase instances */\n\n  /* Output variables */\n  int iStart;                     /* First token in coalesced phrase instance */\n  int iEnd;                       /* Last token in coalesced phrase instance */\n};\n\n/*\n** Advance the iterator to the next coalesced phrase instance. Return\n** an SQLite error code if an error occurs, or SQLITE_OK otherwise.\n*/\nstatic int fts5CInstIterNext(CInstIter *pIter){\n  int rc = SQLITE_OK;\n  pIter->iStart = -1;\n  pIter->iEnd = -1;\n\n  while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){\n    int ip; int ic; int io;\n    rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);\n    if( rc==SQLITE_OK ){\n      if( ic==pIter->iCol ){\n        int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);\n        if( pIter->iStart<0 ){\n          pIter->iStart = io;\n          pIter->iEnd = iEnd;\n        }else if( io<=pIter->iEnd ){\n          if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;\n        }else{\n          break;\n        }\n      }\n      pIter->iInst++;\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Initialize the iterator object indicated by the final parameter to \n** iterate through coalesced phrase instances in column iCol.\n*/\nstatic int fts5CInstIterInit(\n  const Fts5ExtensionApi *pApi,\n  Fts5Context *pFts,\n  int iCol,\n  CInstIter *pIter\n){\n  int rc;\n\n  memset(pIter, 0, sizeof(CInstIter));\n  pIter->pApi = pApi;\n  pIter->pFts = pFts;\n  pIter->iCol = iCol;\n  rc = pApi->xInstCount(pFts, &pIter->nInst);\n\n  if( rc==SQLITE_OK ){\n    rc = fts5CInstIterNext(pIter);\n  }\n\n  return rc;\n}\n\n\n\n/*************************************************************************\n** Start of highlight() implementation.\n*/\ntypedef struct HighlightContext HighlightContext;\nstruct HighlightContext {\n  CInstIter iter;                 /* Coalesced Instance Iterator */\n  int iPos;                       /* Current token offset in zIn[] */\n  int iRangeStart;                /* First token to include */\n  int iRangeEnd;                  /* If non-zero, last token to include */\n  const char *zOpen;              /* Opening highlight */\n  const char *zClose;             /* Closing highlight */\n  const char *zIn;                /* Input text */\n  int nIn;                        /* Size of input text in bytes */\n  int iOff;                       /* Current offset within zIn[] */\n  char *zOut;                     /* Output value */\n};\n\n/*\n** Append text to the HighlightContext output string - p->zOut. Argument\n** z points to a buffer containing n bytes of text to append. If n is \n** negative, everything up until the first '\\0' is appended to the output.\n**\n** If *pRc is set to any value other than SQLITE_OK when this function is \n** called, it is a no-op. If an error (i.e. an OOM condition) is encountered, \n** *pRc is set to an error code before returning. \n*/\nstatic void fts5HighlightAppend(\n  int *pRc, \n  HighlightContext *p, \n  const char *z, int n\n){\n  if( *pRc==SQLITE_OK && z ){\n    if( n<0 ) n = (int)strlen(z);\n    p->zOut = sqlite3_mprintf(\"%z%.*s\", p->zOut, n, z);\n    if( p->zOut==0 ) *pRc = SQLITE_NOMEM;\n  }\n}\n\n/*\n** Tokenizer callback used by implementation of highlight() function.\n*/\nstatic int fts5HighlightCb(\n  void *pContext,                 /* Pointer to HighlightContext object */\n  int tflags,                     /* Mask of FTS5_TOKEN_* flags */\n  const char *pToken,             /* Buffer containing token */\n  int nToken,                     /* Size of token in bytes */\n  int iStartOff,                  /* Start offset of token */\n  int iEndOff                     /* End offset of token */\n){\n  HighlightContext *p = (HighlightContext*)pContext;\n  int rc = SQLITE_OK;\n  int iPos;\n\n  UNUSED_PARAM2(pToken, nToken);\n\n  if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;\n  iPos = p->iPos++;\n\n  if( p->iRangeEnd>0 ){\n    if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;\n    if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;\n  }\n\n  if( iPos==p->iter.iStart ){\n    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);\n    fts5HighlightAppend(&rc, p, p->zOpen, -1);\n    p->iOff = iStartOff;\n  }\n\n  if( iPos==p->iter.iEnd ){\n    if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){\n      fts5HighlightAppend(&rc, p, p->zOpen, -1);\n    }\n    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);\n    fts5HighlightAppend(&rc, p, p->zClose, -1);\n    p->iOff = iEndOff;\n    if( rc==SQLITE_OK ){\n      rc = fts5CInstIterNext(&p->iter);\n    }\n  }\n\n  if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){\n    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);\n    p->iOff = iEndOff;\n    if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){\n      fts5HighlightAppend(&rc, p, p->zClose, -1);\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Implementation of highlight() function.\n*/\nstatic void fts5HighlightFunction(\n  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */\n  Fts5Context *pFts,              /* First arg to pass to pApi functions */\n  sqlite3_context *pCtx,          /* Context for returning result/error */\n  int nVal,                       /* Number of values in apVal[] array */\n  sqlite3_value **apVal           /* Array of trailing arguments */\n){\n  HighlightContext ctx;\n  int rc;\n  int iCol;\n\n  if( nVal!=3 ){\n    const char *zErr = \"wrong number of arguments to function highlight()\";\n    sqlite3_result_error(pCtx, zErr, -1);\n    return;\n  }\n\n  iCol = sqlite3_value_int(apVal[0]);\n  memset(&ctx, 0, sizeof(HighlightContext));\n  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);\n  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);\n  rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);\n\n  if( ctx.zIn ){\n    if( rc==SQLITE_OK ){\n      rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);\n    }\n\n    if( rc==SQLITE_OK ){\n      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);\n    }\n    fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);\n\n    if( rc==SQLITE_OK ){\n      sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);\n    }\n    sqlite3_free(ctx.zOut);\n  }\n  if( rc!=SQLITE_OK ){\n    sqlite3_result_error_code(pCtx, rc);\n  }\n}\n/*\n** End of highlight() implementation.\n**************************************************************************/\n\n/*\n** Context object passed to the fts5SentenceFinderCb() function.\n*/\ntypedef struct Fts5SFinder Fts5SFinder;\nstruct Fts5SFinder {\n  int iPos;                       /* Current token position */\n  int nFirstAlloc;                /* Allocated size of aFirst[] */\n  int nFirst;                     /* Number of entries in aFirst[] */\n  int *aFirst;                    /* Array of first token in each sentence */\n  const char *zDoc;               /* Document being tokenized */\n};\n\n/*\n** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if\n** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an\n** error occurs.\n*/\nstatic int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){\n  if( p->nFirstAlloc==p->nFirst ){\n    int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;\n    int *aNew;\n\n    aNew = (int*)sqlite3_realloc64(p->aFirst, nNew*sizeof(int));\n    if( aNew==0 ) return SQLITE_NOMEM;\n    p->aFirst = aNew;\n    p->nFirstAlloc = nNew;\n  }\n  p->aFirst[p->nFirst++] = iAdd;\n  return SQLITE_OK;\n}\n\n/*\n** This function is an xTokenize() callback used by the auxiliary snippet()\n** function. Its job is to identify tokens that are the first in a sentence.\n** For each such token, an entry is added to the SFinder.aFirst[] array.\n*/\nstatic int fts5SentenceFinderCb(\n  void *pContext,                 /* Pointer to HighlightContext object */\n  int tflags,                     /* Mask of FTS5_TOKEN_* flags */\n  const char *pToken,             /* Buffer containing token */\n  int nToken,                     /* Size of token in bytes */\n  int iStartOff,                  /* Start offset of token */\n  int iEndOff                     /* End offset of token */\n){\n  int rc = SQLITE_OK;\n\n  UNUSED_PARAM2(pToken, nToken);\n  UNUSED_PARAM(iEndOff);\n\n  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){\n    Fts5SFinder *p = (Fts5SFinder*)pContext;\n    if( p->iPos>0 ){\n      int i;\n      char c = 0;\n      for(i=iStartOff-1; i>=0; i--){\n        c = p->zDoc[i];\n        if( c!=' ' && c!='\\t' && c!='\\n' && c!='\\r' ) break;\n      }\n      if( i!=iStartOff-1 && (c=='.' || c==':') ){\n        rc = fts5SentenceFinderAdd(p, p->iPos);\n      }\n    }else{\n      rc = fts5SentenceFinderAdd(p, 0);\n    }\n    p->iPos++;\n  }\n  return rc;\n}\n\nstatic int fts5SnippetScore(\n  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */\n  Fts5Context *pFts,              /* First arg to pass to pApi functions */\n  int nDocsize,                   /* Size of column in tokens */\n  unsigned char *aSeen,           /* Array with one element per query phrase */\n  int iCol,                       /* Column to score */\n  int iPos,                       /* Starting offset to score */\n  int nToken,                     /* Max tokens per snippet */\n  int *pnScore,                   /* OUT: Score */\n  int *piPos                      /* OUT: Adjusted offset */\n){\n  int rc;\n  int i;\n  int ip = 0;\n  int ic = 0;\n  int iOff = 0;\n  int iFirst = -1;\n  int nInst;\n  int nScore = 0;\n  int iLast = 0;\n  sqlite3_int64 iEnd = (sqlite3_int64)iPos + nToken;\n\n  rc = pApi->xInstCount(pFts, &nInst);\n  for(i=0; i<nInst && rc==SQLITE_OK; i++){\n    rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);\n    if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<iEnd ){\n      nScore += (aSeen[ip] ? 1 : 1000);\n      aSeen[ip] = 1;\n      if( iFirst<0 ) iFirst = iOff;\n      iLast = iOff + pApi->xPhraseSize(pFts, ip);\n    }\n  }\n\n  *pnScore = nScore;\n  if( piPos ){\n    sqlite3_int64 iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;\n    if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;\n    if( iAdj<0 ) iAdj = 0;\n    *piPos = (int)iAdj;\n  }\n\n  return rc;\n}\n\n/*\n** Return the value in pVal interpreted as utf-8 text. Except, if pVal \n** contains a NULL value, return a pointer to a static string zero\n** bytes in length instead of a NULL pointer.\n*/\nstatic const char *fts5ValueToText(sqlite3_value *pVal){\n  const char *zRet = (const char*)sqlite3_value_text(pVal);\n  return zRet ? zRet : \"\";\n}\n\n/*\n** Implementation of snippet() function.\n*/\nstatic void fts5SnippetFunction(\n  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */\n  Fts5Context *pFts,              /* First arg to pass to pApi functions */\n  sqlite3_context *pCtx,          /* Context for returning result/error */\n  int nVal,                       /* Number of values in apVal[] array */\n  sqlite3_value **apVal           /* Array of trailing arguments */\n){\n  HighlightContext ctx;\n  int rc = SQLITE_OK;             /* Return code */\n  int iCol;                       /* 1st argument to snippet() */\n  const char *zEllips;            /* 4th argument to snippet() */\n  int nToken;                     /* 5th argument to snippet() */\n  int nInst = 0;                  /* Number of instance matches this row */\n  int i;                          /* Used to iterate through instances */\n  int nPhrase;                    /* Number of phrases in query */\n  unsigned char *aSeen;           /* Array of \"seen instance\" flags */\n  int iBestCol;                   /* Column containing best snippet */\n  int iBestStart = 0;             /* First token of best snippet */\n  int nBestScore = 0;             /* Score of best snippet */\n  int nColSize = 0;               /* Total size of iBestCol in tokens */\n  Fts5SFinder sFinder;            /* Used to find the beginnings of sentences */\n  int nCol;\n\n  if( nVal!=5 ){\n    const char *zErr = \"wrong number of arguments to function snippet()\";\n    sqlite3_result_error(pCtx, zErr, -1);\n    return;\n  }\n\n  nCol = pApi->xColumnCount(pFts);\n  memset(&ctx, 0, sizeof(HighlightContext));\n  iCol = sqlite3_value_int(apVal[0]);\n  ctx.zOpen = fts5ValueToText(apVal[1]);\n  ctx.zClose = fts5ValueToText(apVal[2]);\n  zEllips = fts5ValueToText(apVal[3]);\n  nToken = sqlite3_value_int(apVal[4]);\n\n  iBestCol = (iCol>=0 ? iCol : 0);\n  nPhrase = pApi->xPhraseCount(pFts);\n  aSeen = sqlite3_malloc(nPhrase);\n  if( aSeen==0 ){\n    rc = SQLITE_NOMEM;\n  }\n  if( rc==SQLITE_OK ){\n    rc = pApi->xInstCount(pFts, &nInst);\n  }\n\n  memset(&sFinder, 0, sizeof(Fts5SFinder));\n  for(i=0; i<nCol; i++){\n    if( iCol<0 || iCol==i ){\n      int nDoc;\n      int nDocsize;\n      int ii;\n      sFinder.iPos = 0;\n      sFinder.nFirst = 0;\n      rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);\n      if( rc!=SQLITE_OK ) break;\n      rc = pApi->xTokenize(pFts, \n          sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb\n      );\n      if( rc!=SQLITE_OK ) break;\n      rc = pApi->xColumnSize(pFts, i, &nDocsize);\n      if( rc!=SQLITE_OK ) break;\n\n      for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){\n        int ip, ic, io;\n        int iAdj;\n        int nScore;\n        int jj;\n\n        rc = pApi->xInst(pFts, ii, &ip, &ic, &io);\n        if( ic!=i ) continue;\n        if( io>nDocsize ) rc = FTS5_CORRUPT;\n        if( rc!=SQLITE_OK ) continue;\n        memset(aSeen, 0, nPhrase);\n        rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,\n            io, nToken, &nScore, &iAdj\n        );\n        if( rc==SQLITE_OK && nScore>nBestScore ){\n          nBestScore = nScore;\n          iBestCol = i;\n          iBestStart = iAdj;\n          nColSize = nDocsize;\n        }\n\n        if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){\n          for(jj=0; jj<(sFinder.nFirst-1); jj++){\n            if( sFinder.aFirst[jj+1]>io ) break;\n          }\n\n          if( sFinder.aFirst[jj]<io ){\n            memset(aSeen, 0, nPhrase);\n            rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i, \n              sFinder.aFirst[jj], nToken, &nScore, 0\n            );\n\n            nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);\n            if( rc==SQLITE_OK && nScore>nBestScore ){\n              nBestScore = nScore;\n              iBestCol = i;\n              iBestStart = sFinder.aFirst[jj];\n              nColSize = nDocsize;\n            }\n          }\n        }\n      }\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);\n  }\n  if( rc==SQLITE_OK && nColSize==0 ){\n    rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);\n  }\n  if( ctx.zIn ){\n    if( rc==SQLITE_OK ){\n      rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);\n    }\n\n    ctx.iRangeStart = iBestStart;\n    ctx.iRangeEnd = iBestStart + nToken - 1;\n\n    if( iBestStart>0 ){\n      fts5HighlightAppend(&rc, &ctx, zEllips, -1);\n    }\n\n    /* Advance iterator ctx.iter so that it points to the first coalesced\n    ** phrase instance at or following position iBestStart. */\n    while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){\n      rc = fts5CInstIterNext(&ctx.iter);\n    }\n\n    if( rc==SQLITE_OK ){\n      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);\n    }\n    if( ctx.iRangeEnd>=(nColSize-1) ){\n      fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);\n    }else{\n      fts5HighlightAppend(&rc, &ctx, zEllips, -1);\n    }\n  }\n  if( rc==SQLITE_OK ){\n    sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);\n  }else{\n    sqlite3_result_error_code(pCtx, rc);\n  }\n  sqlite3_free(ctx.zOut);\n  sqlite3_free(aSeen);\n  sqlite3_free(sFinder.aFirst);\n}\n\n/************************************************************************/\n\n/*\n** The first time the bm25() function is called for a query, an instance\n** of the following structure is allocated and populated.\n*/\ntypedef struct Fts5Bm25Data Fts5Bm25Data;\nstruct Fts5Bm25Data {\n  int nPhrase;                    /* Number of phrases in query */\n  double avgdl;                   /* Average number of tokens in each row */\n  double *aIDF;                   /* IDF for each phrase */\n  double *aFreq;                  /* Array used to calculate phrase freq. */\n};\n\n/*\n** Callback used by fts5Bm25GetData() to count the number of rows in the\n** table matched by each individual phrase within the query.\n*/\nstatic int fts5CountCb(\n  const Fts5ExtensionApi *pApi, \n  Fts5Context *pFts,\n  void *pUserData                 /* Pointer to sqlite3_int64 variable */\n){\n  sqlite3_int64 *pn = (sqlite3_int64*)pUserData;\n  UNUSED_PARAM2(pApi, pFts);\n  (*pn)++;\n  return SQLITE_OK;\n}\n\n/*\n** Set *ppData to point to the Fts5Bm25Data object for the current query. \n** If the object has not already been allocated, allocate and populate it\n** now.\n*/\nstatic int fts5Bm25GetData(\n  const Fts5ExtensionApi *pApi, \n  Fts5Context *pFts,\n  Fts5Bm25Data **ppData           /* OUT: bm25-data object for this query */\n){\n  int rc = SQLITE_OK;             /* Return code */\n  Fts5Bm25Data *p;                /* Object to return */\n\n  p = pApi->xGetAuxdata(pFts, 0);\n  if( p==0 ){\n    int nPhrase;                  /* Number of phrases in query */\n    sqlite3_int64 nRow = 0;       /* Number of rows in table */\n    sqlite3_int64 nToken = 0;     /* Number of tokens in table */\n    sqlite3_int64 nByte;          /* Bytes of space to allocate */\n    int i;\n\n    /* Allocate the Fts5Bm25Data object */\n    nPhrase = pApi->xPhraseCount(pFts);\n    nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);\n    p = (Fts5Bm25Data*)sqlite3_malloc64(nByte);\n    if( p==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      memset(p, 0, (size_t)nByte);\n      p->nPhrase = nPhrase;\n      p->aIDF = (double*)&p[1];\n      p->aFreq = &p->aIDF[nPhrase];\n    }\n\n    /* Calculate the average document length for this FTS5 table */\n    if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);\n    assert( rc!=SQLITE_OK || nRow>0 );\n    if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);\n    if( rc==SQLITE_OK ) p->avgdl = (double)nToken  / (double)nRow;\n\n    /* Calculate an IDF for each phrase in the query */\n    for(i=0; rc==SQLITE_OK && i<nPhrase; i++){\n      sqlite3_int64 nHit = 0;\n      rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);\n      if( rc==SQLITE_OK ){\n        /* Calculate the IDF (Inverse Document Frequency) for phrase i.\n        ** This is done using the standard BM25 formula as found on wikipedia:\n        **\n        **   IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )\n        **\n        ** where \"N\" is the total number of documents in the set and nHit\n        ** is the number that contain at least one instance of the phrase\n        ** under consideration.\n        **\n        ** The problem with this is that if (N < 2*nHit), the IDF is \n        ** negative. Which is undesirable. So the mimimum allowable IDF is\n        ** (1e-6) - roughly the same as a term that appears in just over\n        ** half of set of 5,000,000 documents.  */\n        double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );\n        if( idf<=0.0 ) idf = 1e-6;\n        p->aIDF[i] = idf;\n      }\n    }\n\n    if( rc!=SQLITE_OK ){\n      sqlite3_free(p);\n    }else{\n      rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);\n    }\n    if( rc!=SQLITE_OK ) p = 0;\n  }\n  *ppData = p;\n  return rc;\n}\n\n/*\n** Implementation of bm25() function.\n*/\nstatic void fts5Bm25Function(\n  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */\n  Fts5Context *pFts,              /* First arg to pass to pApi functions */\n  sqlite3_context *pCtx,          /* Context for returning result/error */\n  int nVal,                       /* Number of values in apVal[] array */\n  sqlite3_value **apVal           /* Array of trailing arguments */\n){\n  const double k1 = 1.2;          /* Constant \"k1\" from BM25 formula */\n  const double b = 0.75;          /* Constant \"b\" from BM25 formula */\n  int rc = SQLITE_OK;             /* Error code */\n  double score = 0.0;             /* SQL function return value */\n  Fts5Bm25Data *pData;            /* Values allocated/calculated once only */\n  int i;                          /* Iterator variable */\n  int nInst = 0;                  /* Value returned by xInstCount() */\n  double D = 0.0;                 /* Total number of tokens in row */\n  double *aFreq = 0;              /* Array of phrase freq. for current row */\n\n  /* Calculate the phrase frequency (symbol \"f(qi,D)\" in the documentation)\n  ** for each phrase in the query for the current row. */\n  rc = fts5Bm25GetData(pApi, pFts, &pData);\n  if( rc==SQLITE_OK ){\n    aFreq = pData->aFreq;\n    memset(aFreq, 0, sizeof(double) * pData->nPhrase);\n    rc = pApi->xInstCount(pFts, &nInst);\n  }\n  for(i=0; rc==SQLITE_OK && i<nInst; i++){\n    int ip; int ic; int io;\n    rc = pApi->xInst(pFts, i, &ip, &ic, &io);\n    if( rc==SQLITE_OK ){\n      double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;\n      aFreq[ip] += w;\n    }\n  }\n\n  /* Figure out the total size of the current row in tokens. */\n  if( rc==SQLITE_OK ){\n    int nTok;\n    rc = pApi->xColumnSize(pFts, -1, &nTok);\n    D = (double)nTok;\n  }\n\n  /* Determine the BM25 score for the current row. */\n  for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){\n    score += pData->aIDF[i] * (\n      ( aFreq[i] * (k1 + 1.0) ) / \n      ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )\n    );\n  }\n  \n  /* If no error has occurred, return the calculated score. Otherwise,\n  ** throw an SQL exception.  */\n  if( rc==SQLITE_OK ){\n    sqlite3_result_double(pCtx, -1.0 * score);\n  }else{\n    sqlite3_result_error_code(pCtx, rc);\n  }\n}\n\nstatic int sqlite3Fts5AuxInit(fts5_api *pApi){\n  struct Builtin {\n    const char *zFunc;            /* Function name (nul-terminated) */\n    void *pUserData;              /* User-data pointer */\n    fts5_extension_function xFunc;/* Callback function */\n    void (*xDestroy)(void*);      /* Destructor function */\n  } aBuiltin [] = {\n    { \"snippet\",   0, fts5SnippetFunction, 0 },\n    { \"highlight\", 0, fts5HighlightFunction, 0 },\n    { \"bm25\",      0, fts5Bm25Function,    0 },\n  };\n  int rc = SQLITE_OK;             /* Return code */\n  int i;                          /* To iterate through builtin functions */\n\n  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){\n    rc = pApi->xCreateFunction(pApi,\n        aBuiltin[i].zFunc,\n        aBuiltin[i].pUserData,\n        aBuiltin[i].xFunc,\n        aBuiltin[i].xDestroy\n    );\n  }\n\n  return rc;\n}\n\n/*\n** 2014 May 31\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n*/\n\n\n\n/* #include \"fts5Int.h\" */\n\nstatic int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){\n  if( (u32)pBuf->nSpace<nByte ){\n    u64 nNew = pBuf->nSpace ? pBuf->nSpace : 64;\n    u8 *pNew;\n    while( nNew<nByte ){\n      nNew = nNew * 2;\n    }\n    pNew = sqlite3_realloc64(pBuf->p, nNew);\n    if( pNew==0 ){\n      *pRc = SQLITE_NOMEM;\n      return 1;\n    }else{\n      pBuf->nSpace = (int)nNew;\n      pBuf->p = pNew;\n    }\n  }\n  return 0;\n}\n\n\n/*\n** Encode value iVal as an SQLite varint and append it to the buffer object\n** pBuf. If an OOM error occurs, set the error code in p.\n*/\nstatic void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){\n  if( fts5BufferGrow(pRc, pBuf, 9) ) return;\n  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);\n}\n\nstatic void sqlite3Fts5Put32(u8 *aBuf, int iVal){\n  aBuf[0] = (iVal>>24) & 0x00FF;\n  aBuf[1] = (iVal>>16) & 0x00FF;\n  aBuf[2] = (iVal>> 8) & 0x00FF;\n  aBuf[3] = (iVal>> 0) & 0x00FF;\n}\n\nstatic int sqlite3Fts5Get32(const u8 *aBuf){\n  return (int)((((u32)aBuf[0])<<24) + (aBuf[1]<<16) + (aBuf[2]<<8) + aBuf[3]);\n}\n\n/*\n** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set \n** the error code in p. If an error has already occurred when this function\n** is called, it is a no-op.\n*/\nstatic void sqlite3Fts5BufferAppendBlob(\n  int *pRc,\n  Fts5Buffer *pBuf, \n  u32 nData, \n  const u8 *pData\n){\n  assert_nc( *pRc || nData>=0 );\n  if( nData ){\n    if( fts5BufferGrow(pRc, pBuf, nData) ) return;\n    memcpy(&pBuf->p[pBuf->n], pData, nData);\n    pBuf->n += nData;\n  }\n}\n\n/*\n** Append the nul-terminated string zStr to the buffer pBuf. This function\n** ensures that the byte following the buffer data is set to 0x00, even \n** though this byte is not included in the pBuf->n count.\n*/\nstatic void sqlite3Fts5BufferAppendString(\n  int *pRc,\n  Fts5Buffer *pBuf, \n  const char *zStr\n){\n  int nStr = (int)strlen(zStr);\n  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);\n  pBuf->n--;\n}\n\n/*\n** Argument zFmt is a printf() style format string. This function performs\n** the printf() style processing, then appends the results to buffer pBuf.\n**\n** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte \n** following the buffer data is set to 0x00, even though this byte is not\n** included in the pBuf->n count.\n*/ \nstatic void sqlite3Fts5BufferAppendPrintf(\n  int *pRc,\n  Fts5Buffer *pBuf, \n  char *zFmt, ...\n){\n  if( *pRc==SQLITE_OK ){\n    char *zTmp;\n    va_list ap;\n    va_start(ap, zFmt);\n    zTmp = sqlite3_vmprintf(zFmt, ap);\n    va_end(ap);\n\n    if( zTmp==0 ){\n      *pRc = SQLITE_NOMEM;\n    }else{\n      sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);\n      sqlite3_free(zTmp);\n    }\n  }\n}\n\nstatic char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){\n  char *zRet = 0;\n  if( *pRc==SQLITE_OK ){\n    va_list ap;\n    va_start(ap, zFmt);\n    zRet = sqlite3_vmprintf(zFmt, ap);\n    va_end(ap);\n    if( zRet==0 ){\n      *pRc = SQLITE_NOMEM; \n    }\n  }\n  return zRet;\n}\n \n\n/*\n** Free any buffer allocated by pBuf. Zero the structure before returning.\n*/\nstatic void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){\n  sqlite3_free(pBuf->p);\n  memset(pBuf, 0, sizeof(Fts5Buffer));\n}\n\n/*\n** Zero the contents of the buffer object. But do not free the associated \n** memory allocation.\n*/\nstatic void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){\n  pBuf->n = 0;\n}\n\n/*\n** Set the buffer to contain nData/pData. If an OOM error occurs, leave an\n** the error code in p. If an error has already occurred when this function\n** is called, it is a no-op.\n*/\nstatic void sqlite3Fts5BufferSet(\n  int *pRc,\n  Fts5Buffer *pBuf, \n  int nData, \n  const u8 *pData\n){\n  pBuf->n = 0;\n  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);\n}\n\nstatic int sqlite3Fts5PoslistNext64(\n  const u8 *a, int n,             /* Buffer containing poslist */\n  int *pi,                        /* IN/OUT: Offset within a[] */\n  i64 *piOff                      /* IN/OUT: Current offset */\n){\n  int i = *pi;\n  if( i>=n ){\n    /* EOF */\n    *piOff = -1;\n    return 1;  \n  }else{\n    i64 iOff = *piOff;\n    int iVal;\n    fts5FastGetVarint32(a, i, iVal);\n    if( iVal<=1 ){\n      if( iVal==0 ){\n        *pi = i;\n        return 0;\n      }\n      fts5FastGetVarint32(a, i, iVal);\n      iOff = ((i64)iVal) << 32;\n      fts5FastGetVarint32(a, i, iVal);\n      if( iVal<2 ){\n        /* This is a corrupt record. So stop parsing it here. */\n        *piOff = -1;\n        return 1;\n      }\n    }\n    *piOff = iOff + ((iVal-2) & 0x7FFFFFFF);\n    *pi = i;\n    return 0;\n  }\n}\n\n\n/*\n** Advance the iterator object passed as the only argument. Return true\n** if the iterator reaches EOF, or false otherwise.\n*/\nstatic int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){\n  if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){\n    pIter->bEof = 1;\n  }\n  return pIter->bEof;\n}\n\nstatic int sqlite3Fts5PoslistReaderInit(\n  const u8 *a, int n,             /* Poslist buffer to iterate through */\n  Fts5PoslistReader *pIter        /* Iterator object to initialize */\n){\n  memset(pIter, 0, sizeof(*pIter));\n  pIter->a = a;\n  pIter->n = n;\n  sqlite3Fts5PoslistReaderNext(pIter);\n  return pIter->bEof;\n}\n\n/*\n** Append position iPos to the position list being accumulated in buffer\n** pBuf, which must be already be large enough to hold the new data.\n** The previous position written to this list is *piPrev. *piPrev is set\n** to iPos before returning.\n*/\nstatic void sqlite3Fts5PoslistSafeAppend(\n  Fts5Buffer *pBuf, \n  i64 *piPrev, \n  i64 iPos\n){\n  static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;\n  if( (iPos & colmask) != (*piPrev & colmask) ){\n    pBuf->p[pBuf->n++] = 1;\n    pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));\n    *piPrev = (iPos & colmask);\n  }\n  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);\n  *piPrev = iPos;\n}\n\nstatic int sqlite3Fts5PoslistWriterAppend(\n  Fts5Buffer *pBuf, \n  Fts5PoslistWriter *pWriter,\n  i64 iPos\n){\n  int rc = 0;   /* Initialized only to suppress erroneous warning from Clang */\n  if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;\n  sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);\n  return SQLITE_OK;\n}\n\nstatic void *sqlite3Fts5MallocZero(int *pRc, sqlite3_int64 nByte){\n  void *pRet = 0;\n  if( *pRc==SQLITE_OK ){\n    pRet = sqlite3_malloc64(nByte);\n    if( pRet==0 ){\n      if( nByte>0 ) *pRc = SQLITE_NOMEM;\n    }else{\n      memset(pRet, 0, (size_t)nByte);\n    }\n  }\n  return pRet;\n}\n\n/*\n** Return a nul-terminated copy of the string indicated by pIn. If nIn\n** is non-negative, then it is the length of the string in bytes. Otherwise,\n** the length of the string is determined using strlen().\n**\n** It is the responsibility of the caller to eventually free the returned\n** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned. \n*/\nstatic char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){\n  char *zRet = 0;\n  if( *pRc==SQLITE_OK ){\n    if( nIn<0 ){\n      nIn = (int)strlen(pIn);\n    }\n    zRet = (char*)sqlite3_malloc(nIn+1);\n    if( zRet ){\n      memcpy(zRet, pIn, nIn);\n      zRet[nIn] = '\\0';\n    }else{\n      *pRc = SQLITE_NOMEM;\n    }\n  }\n  return zRet;\n}\n\n\n/*\n** Return true if character 't' may be part of an FTS5 bareword, or false\n** otherwise. Characters that may be part of barewords:\n**\n**   * All non-ASCII characters,\n**   * The 52 upper and lower case ASCII characters, and\n**   * The 10 integer ASCII characters.\n**   * The underscore character \"_\" (0x5F).\n**   * The unicode \"subsitute\" character (0x1A).\n*/\nstatic int sqlite3Fts5IsBareword(char t){\n  u8 aBareword[128] = {\n    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00 .. 0x0F */\n    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 1, 0, 0, 0, 0, 0,   /* 0x10 .. 0x1F */\n    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20 .. 0x2F */\n    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30 .. 0x3F */\n    0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40 .. 0x4F */\n    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 1,   /* 0x50 .. 0x5F */\n    0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60 .. 0x6F */\n    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 0    /* 0x70 .. 0x7F */\n  };\n\n  return (t & 0x80) || aBareword[(int)t];\n}\n\n\n/*************************************************************************\n*/\ntypedef struct Fts5TermsetEntry Fts5TermsetEntry;\nstruct Fts5TermsetEntry {\n  char *pTerm;\n  int nTerm;\n  int iIdx;                       /* Index (main or aPrefix[] entry) */\n  Fts5TermsetEntry *pNext;\n};\n\nstruct Fts5Termset {\n  Fts5TermsetEntry *apHash[512];\n};\n\nstatic int sqlite3Fts5TermsetNew(Fts5Termset **pp){\n  int rc = SQLITE_OK;\n  *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));\n  return rc;\n}\n\nstatic int sqlite3Fts5TermsetAdd(\n  Fts5Termset *p, \n  int iIdx,\n  const char *pTerm, int nTerm, \n  int *pbPresent\n){\n  int rc = SQLITE_OK;\n  *pbPresent = 0;\n  if( p ){\n    int i;\n    u32 hash = 13;\n    Fts5TermsetEntry *pEntry;\n\n    /* Calculate a hash value for this term. This is the same hash checksum\n    ** used by the fts5_hash.c module. This is not important for correct\n    ** operation of the module, but is necessary to ensure that some tests\n    ** designed to produce hash table collisions really do work.  */\n    for(i=nTerm-1; i>=0; i--){\n      hash = (hash << 3) ^ hash ^ pTerm[i];\n    }\n    hash = (hash << 3) ^ hash ^ iIdx;\n    hash = hash % ArraySize(p->apHash);\n\n    for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){\n      if( pEntry->iIdx==iIdx \n          && pEntry->nTerm==nTerm \n          && memcmp(pEntry->pTerm, pTerm, nTerm)==0 \n      ){\n        *pbPresent = 1;\n        break;\n      }\n    }\n\n    if( pEntry==0 ){\n      pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);\n      if( pEntry ){\n        pEntry->pTerm = (char*)&pEntry[1];\n        pEntry->nTerm = nTerm;\n        pEntry->iIdx = iIdx;\n        memcpy(pEntry->pTerm, pTerm, nTerm);\n        pEntry->pNext = p->apHash[hash];\n        p->apHash[hash] = pEntry;\n      }\n    }\n  }\n\n  return rc;\n}\n\nstatic void sqlite3Fts5TermsetFree(Fts5Termset *p){\n  if( p ){\n    u32 i;\n    for(i=0; i<ArraySize(p->apHash); i++){\n      Fts5TermsetEntry *pEntry = p->apHash[i];\n      while( pEntry ){\n        Fts5TermsetEntry *pDel = pEntry;\n        pEntry = pEntry->pNext;\n        sqlite3_free(pDel);\n      }\n    }\n    sqlite3_free(p);\n  }\n}\n\n/*\n** 2014 Jun 09\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This is an SQLite module implementing full-text search.\n*/\n\n\n/* #include \"fts5Int.h\" */\n\n#define FTS5_DEFAULT_PAGE_SIZE   4050\n#define FTS5_DEFAULT_AUTOMERGE      4\n#define FTS5_DEFAULT_USERMERGE      4\n#define FTS5_DEFAULT_CRISISMERGE   16\n#define FTS5_DEFAULT_HASHSIZE    (1024*1024)\n\n/* Maximum allowed page size */\n#define FTS5_MAX_PAGE_SIZE (64*1024)\n\nstatic int fts5_iswhitespace(char x){\n  return (x==' ');\n}\n\nstatic int fts5_isopenquote(char x){\n  return (x=='\"' || x=='\\'' || x=='[' || x=='`');\n}\n\n/*\n** Argument pIn points to a character that is part of a nul-terminated \n** string. Return a pointer to the first character following *pIn in \n** the string that is not a white-space character.\n*/\nstatic const char *fts5ConfigSkipWhitespace(const char *pIn){\n  const char *p = pIn;\n  if( p ){\n    while( fts5_iswhitespace(*p) ){ p++; }\n  }\n  return p;\n}\n\n/*\n** Argument pIn points to a character that is part of a nul-terminated \n** string. Return a pointer to the first character following *pIn in \n** the string that is not a \"bareword\" character.\n*/\nstatic const char *fts5ConfigSkipBareword(const char *pIn){\n  const char *p = pIn;\n  while ( sqlite3Fts5IsBareword(*p) ) p++;\n  if( p==pIn ) p = 0;\n  return p;\n}\n\nstatic int fts5_isdigit(char a){\n  return (a>='0' && a<='9');\n}\n\n\n\nstatic const char *fts5ConfigSkipLiteral(const char *pIn){\n  const char *p = pIn;\n  switch( *p ){\n    case 'n': case 'N':\n      if( sqlite3_strnicmp(\"null\", p, 4)==0 ){\n        p = &p[4];\n      }else{\n        p = 0;\n      }\n      break;\n\n    case 'x': case 'X':\n      p++;\n      if( *p=='\\'' ){\n        p++;\n        while( (*p>='a' && *p<='f') \n            || (*p>='A' && *p<='F') \n            || (*p>='0' && *p<='9') \n            ){\n          p++;\n        }\n        if( *p=='\\'' && 0==((p-pIn)%2) ){\n          p++;\n        }else{\n          p = 0;\n        }\n      }else{\n        p = 0;\n      }\n      break;\n\n    case '\\'':\n      p++;\n      while( p ){\n        if( *p=='\\'' ){\n          p++;\n          if( *p!='\\'' ) break;\n        }\n        p++;\n        if( *p==0 ) p = 0;\n      }\n      break;\n\n    default:\n      /* maybe a number */\n      if( *p=='+' || *p=='-' ) p++;\n      while( fts5_isdigit(*p) ) p++;\n\n      /* At this point, if the literal was an integer, the parse is \n      ** finished. Or, if it is a floating point value, it may continue\n      ** with either a decimal point or an 'E' character. */\n      if( *p=='.' && fts5_isdigit(p[1]) ){\n        p += 2;\n        while( fts5_isdigit(*p) ) p++;\n      }\n      if( p==pIn ) p = 0;\n\n      break;\n  }\n\n  return p;\n}\n\n/*\n** The first character of the string pointed to by argument z is guaranteed\n** to be an open-quote character (see function fts5_isopenquote()).\n**\n** This function searches for the corresponding close-quote character within\n** the string and, if found, dequotes the string in place and adds a new\n** nul-terminator byte.\n**\n** If the close-quote is found, the value returned is the byte offset of\n** the character immediately following it. Or, if the close-quote is not \n** found, -1 is returned. If -1 is returned, the buffer is left in an \n** undefined state.\n*/\nstatic int fts5Dequote(char *z){\n  char q;\n  int iIn = 1;\n  int iOut = 0;\n  q = z[0];\n\n  /* Set stack variable q to the close-quote character */\n  assert( q=='[' || q=='\\'' || q=='\"' || q=='`' );\n  if( q=='[' ) q = ']';  \n\n  while( z[iIn] ){\n    if( z[iIn]==q ){\n      if( z[iIn+1]!=q ){\n        /* Character iIn was the close quote. */\n        iIn++;\n        break;\n      }else{\n        /* Character iIn and iIn+1 form an escaped quote character. Skip\n        ** the input cursor past both and copy a single quote character \n        ** to the output buffer. */\n        iIn += 2;\n        z[iOut++] = q;\n      }\n    }else{\n      z[iOut++] = z[iIn++];\n    }\n  }\n\n  z[iOut] = '\\0';\n  return iIn;\n}\n\n/*\n** Convert an SQL-style quoted string into a normal string by removing\n** the quote characters.  The conversion is done in-place.  If the\n** input does not begin with a quote character, then this routine\n** is a no-op.\n**\n** Examples:\n**\n**     \"abc\"   becomes   abc\n**     'xyz'   becomes   xyz\n**     [pqr]   becomes   pqr\n**     `mno`   becomes   mno\n*/\nstatic void sqlite3Fts5Dequote(char *z){\n  char quote;                     /* Quote character (if any ) */\n\n  assert( 0==fts5_iswhitespace(z[0]) );\n  quote = z[0];\n  if( quote=='[' || quote=='\\'' || quote=='\"' || quote=='`' ){\n    fts5Dequote(z);\n  }\n}\n\n\nstruct Fts5Enum {\n  const char *zName;\n  int eVal;\n};\ntypedef struct Fts5Enum Fts5Enum;\n\nstatic int fts5ConfigSetEnum(\n  const Fts5Enum *aEnum, \n  const char *zEnum, \n  int *peVal\n){\n  int nEnum = (int)strlen(zEnum);\n  int i;\n  int iVal = -1;\n\n  for(i=0; aEnum[i].zName; i++){\n    if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){\n      if( iVal>=0 ) return SQLITE_ERROR;\n      iVal = aEnum[i].eVal;\n    }\n  }\n\n  *peVal = iVal;\n  return iVal<0 ? SQLITE_ERROR : SQLITE_OK;\n}\n\n/*\n** Parse a \"special\" CREATE VIRTUAL TABLE directive and update\n** configuration object pConfig as appropriate.\n**\n** If successful, object pConfig is updated and SQLITE_OK returned. If\n** an error occurs, an SQLite error code is returned and an error message\n** may be left in *pzErr. It is the responsibility of the caller to\n** eventually free any such error message using sqlite3_free().\n*/\nstatic int fts5ConfigParseSpecial(\n  Fts5Global *pGlobal,\n  Fts5Config *pConfig,            /* Configuration object to update */\n  const char *zCmd,               /* Special command to parse */\n  const char *zArg,               /* Argument to parse */\n  char **pzErr                    /* OUT: Error message */\n){\n  int rc = SQLITE_OK;\n  int nCmd = (int)strlen(zCmd);\n  if( sqlite3_strnicmp(\"prefix\", zCmd, nCmd)==0 ){\n    const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;\n    const char *p;\n    int bFirst = 1;\n    if( pConfig->aPrefix==0 ){\n      pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);\n      if( rc ) return rc;\n    }\n\n    p = zArg;\n    while( 1 ){\n      int nPre = 0;\n\n      while( p[0]==' ' ) p++;\n      if( bFirst==0 && p[0]==',' ){\n        p++;\n        while( p[0]==' ' ) p++;\n      }else if( p[0]=='\\0' ){\n        break;\n      }\n      if( p[0]<'0' || p[0]>'9' ){\n        *pzErr = sqlite3_mprintf(\"malformed prefix=... directive\");\n        rc = SQLITE_ERROR;\n        break;\n      }\n\n      if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){\n        *pzErr = sqlite3_mprintf(\n            \"too many prefix indexes (max %d)\", FTS5_MAX_PREFIX_INDEXES\n        );\n        rc = SQLITE_ERROR;\n        break;\n      }\n\n      while( p[0]>='0' && p[0]<='9' && nPre<1000 ){\n        nPre = nPre*10 + (p[0] - '0');\n        p++;\n      }\n\n      if( nPre<=0 || nPre>=1000 ){\n        *pzErr = sqlite3_mprintf(\"prefix length out of range (max 999)\");\n        rc = SQLITE_ERROR;\n        break;\n      }\n\n      pConfig->aPrefix[pConfig->nPrefix] = nPre;\n      pConfig->nPrefix++;\n      bFirst = 0;\n    }\n    assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );\n    return rc;\n  }\n\n  if( sqlite3_strnicmp(\"tokenize\", zCmd, nCmd)==0 ){\n    const char *p = (const char*)zArg;\n    sqlite3_int64 nArg = strlen(zArg) + 1;\n    char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);\n    char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);\n    char *pSpace = pDel;\n\n    if( azArg && pSpace ){\n      if( pConfig->pTok ){\n        *pzErr = sqlite3_mprintf(\"multiple tokenize=... directives\");\n        rc = SQLITE_ERROR;\n      }else{\n        for(nArg=0; p && *p; nArg++){\n          const char *p2 = fts5ConfigSkipWhitespace(p);\n          if( *p2=='\\'' ){\n            p = fts5ConfigSkipLiteral(p2);\n          }else{\n            p = fts5ConfigSkipBareword(p2);\n          }\n          if( p ){\n            memcpy(pSpace, p2, p-p2);\n            azArg[nArg] = pSpace;\n            sqlite3Fts5Dequote(pSpace);\n            pSpace += (p - p2) + 1;\n            p = fts5ConfigSkipWhitespace(p);\n          }\n        }\n        if( p==0 ){\n          *pzErr = sqlite3_mprintf(\"parse error in tokenize directive\");\n          rc = SQLITE_ERROR;\n        }else{\n          rc = sqlite3Fts5GetTokenizer(pGlobal, \n              (const char**)azArg, (int)nArg, &pConfig->pTok, &pConfig->pTokApi,\n              pzErr\n          );\n        }\n      }\n    }\n\n    sqlite3_free(azArg);\n    sqlite3_free(pDel);\n    return rc;\n  }\n\n  if( sqlite3_strnicmp(\"content\", zCmd, nCmd)==0 ){\n    if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){\n      *pzErr = sqlite3_mprintf(\"multiple content=... directives\");\n      rc = SQLITE_ERROR;\n    }else{\n      if( zArg[0] ){\n        pConfig->eContent = FTS5_CONTENT_EXTERNAL;\n        pConfig->zContent = sqlite3Fts5Mprintf(&rc, \"%Q.%Q\", pConfig->zDb,zArg);\n      }else{\n        pConfig->eContent = FTS5_CONTENT_NONE;\n      }\n    }\n    return rc;\n  }\n\n  if( sqlite3_strnicmp(\"content_rowid\", zCmd, nCmd)==0 ){\n    if( pConfig->zContentRowid ){\n      *pzErr = sqlite3_mprintf(\"multiple content_rowid=... directives\");\n      rc = SQLITE_ERROR;\n    }else{\n      pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);\n    }\n    return rc;\n  }\n\n  if( sqlite3_strnicmp(\"columnsize\", zCmd, nCmd)==0 ){\n    if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\\0' ){\n      *pzErr = sqlite3_mprintf(\"malformed columnsize=... directive\");\n      rc = SQLITE_ERROR;\n    }else{\n      pConfig->bColumnsize = (zArg[0]=='1');\n    }\n    return rc;\n  }\n\n  if( sqlite3_strnicmp(\"detail\", zCmd, nCmd)==0 ){\n    const Fts5Enum aDetail[] = {\n      { \"none\", FTS5_DETAIL_NONE },\n      { \"full\", FTS5_DETAIL_FULL },\n      { \"columns\", FTS5_DETAIL_COLUMNS },\n      { 0, 0 }\n    };\n\n    if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){\n      *pzErr = sqlite3_mprintf(\"malformed detail=... directive\");\n    }\n    return rc;\n  }\n\n  *pzErr = sqlite3_mprintf(\"unrecognized option: \\\"%.*s\\\"\", nCmd, zCmd);\n  return SQLITE_ERROR;\n}\n\n/*\n** Allocate an instance of the default tokenizer (\"simple\") at \n** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error\n** code if an error occurs.\n*/\nstatic int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){\n  assert( pConfig->pTok==0 && pConfig->pTokApi==0 );\n  return sqlite3Fts5GetTokenizer(\n      pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0\n  );\n}\n\n/*\n** Gobble up the first bareword or quoted word from the input buffer zIn.\n** Return a pointer to the character immediately following the last in\n** the gobbled word if successful, or a NULL pointer otherwise (failed\n** to find close-quote character).\n**\n** Before returning, set pzOut to point to a new buffer containing a\n** nul-terminated, dequoted copy of the gobbled word. If the word was\n** quoted, *pbQuoted is also set to 1 before returning.\n**\n** If *pRc is other than SQLITE_OK when this function is called, it is\n** a no-op (NULL is returned). Otherwise, if an OOM occurs within this\n** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*\n** set if a parse error (failed to find close quote) occurs.\n*/\nstatic const char *fts5ConfigGobbleWord(\n  int *pRc,                       /* IN/OUT: Error code */\n  const char *zIn,                /* Buffer to gobble string/bareword from */\n  char **pzOut,                   /* OUT: malloc'd buffer containing str/bw */\n  int *pbQuoted                   /* OUT: Set to true if dequoting required */\n){\n  const char *zRet = 0;\n\n  sqlite3_int64 nIn = strlen(zIn);\n  char *zOut = sqlite3_malloc64(nIn+1);\n\n  assert( *pRc==SQLITE_OK );\n  *pbQuoted = 0;\n  *pzOut = 0;\n\n  if( zOut==0 ){\n    *pRc = SQLITE_NOMEM;\n  }else{\n    memcpy(zOut, zIn, (size_t)(nIn+1));\n    if( fts5_isopenquote(zOut[0]) ){\n      int ii = fts5Dequote(zOut);\n      zRet = &zIn[ii];\n      *pbQuoted = 1;\n    }else{\n      zRet = fts5ConfigSkipBareword(zIn);\n      if( zRet ){\n        zOut[zRet-zIn] = '\\0';\n      }\n    }\n  }\n\n  if( zRet==0 ){\n    sqlite3_free(zOut);\n  }else{\n    *pzOut = zOut;\n  }\n\n  return zRet;\n}\n\nstatic int fts5ConfigParseColumn(\n  Fts5Config *p, \n  char *zCol, \n  char *zArg, \n  char **pzErr\n){\n  int rc = SQLITE_OK;\n  if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME) \n   || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME) \n  ){\n    *pzErr = sqlite3_mprintf(\"reserved fts5 column name: %s\", zCol);\n    rc = SQLITE_ERROR;\n  }else if( zArg ){\n    if( 0==sqlite3_stricmp(zArg, \"unindexed\") ){\n      p->abUnindexed[p->nCol] = 1;\n    }else{\n      *pzErr = sqlite3_mprintf(\"unrecognized column option: %s\", zArg);\n      rc = SQLITE_ERROR;\n    }\n  }\n\n  p->azCol[p->nCol++] = zCol;\n  return rc;\n}\n\n/*\n** Populate the Fts5Config.zContentExprlist string.\n*/\nstatic int fts5ConfigMakeExprlist(Fts5Config *p){\n  int i;\n  int rc = SQLITE_OK;\n  Fts5Buffer buf = {0, 0, 0};\n\n  sqlite3Fts5BufferAppendPrintf(&rc, &buf, \"T.%Q\", p->zContentRowid);\n  if( p->eContent!=FTS5_CONTENT_NONE ){\n    for(i=0; i<p->nCol; i++){\n      if( p->eContent==FTS5_CONTENT_EXTERNAL ){\n        sqlite3Fts5BufferAppendPrintf(&rc, &buf, \", T.%Q\", p->azCol[i]);\n      }else{\n        sqlite3Fts5BufferAppendPrintf(&rc, &buf, \", T.c%d\", i);\n      }\n    }\n  }\n\n  assert( p->zContentExprlist==0 );\n  p->zContentExprlist = (char*)buf.p;\n  return rc;\n}\n\n/*\n** Arguments nArg/azArg contain the string arguments passed to the xCreate\n** or xConnect method of the virtual table. This function attempts to \n** allocate an instance of Fts5Config containing the results of parsing\n** those arguments.\n**\n** If successful, SQLITE_OK is returned and *ppOut is set to point to the\n** new Fts5Config object. If an error occurs, an SQLite error code is \n** returned, *ppOut is set to NULL and an error message may be left in\n** *pzErr. It is the responsibility of the caller to eventually free any \n** such error message using sqlite3_free().\n*/\nstatic int sqlite3Fts5ConfigParse(\n  Fts5Global *pGlobal,\n  sqlite3 *db,\n  int nArg,                       /* Number of arguments */\n  const char **azArg,             /* Array of nArg CREATE VIRTUAL TABLE args */\n  Fts5Config **ppOut,             /* OUT: Results of parse */\n  char **pzErr                    /* OUT: Error message */\n){\n  int rc = SQLITE_OK;             /* Return code */\n  Fts5Config *pRet;               /* New object to return */\n  int i;\n  sqlite3_int64 nByte;\n\n  *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));\n  if( pRet==0 ) return SQLITE_NOMEM;\n  memset(pRet, 0, sizeof(Fts5Config));\n  pRet->db = db;\n  pRet->iCookie = -1;\n\n  nByte = nArg * (sizeof(char*) + sizeof(u8));\n  pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);\n  pRet->abUnindexed = (u8*)&pRet->azCol[nArg];\n  pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);\n  pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);\n  pRet->bColumnsize = 1;\n  pRet->eDetail = FTS5_DETAIL_FULL;\n#ifdef SQLITE_DEBUG\n  pRet->bPrefixIndex = 1;\n#endif\n  if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){\n    *pzErr = sqlite3_mprintf(\"reserved fts5 table name: %s\", pRet->zName);\n    rc = SQLITE_ERROR;\n  }\n\n  for(i=3; rc==SQLITE_OK && i<nArg; i++){\n    const char *zOrig = azArg[i];\n    const char *z;\n    char *zOne = 0;\n    char *zTwo = 0;\n    int bOption = 0;\n    int bMustBeCol = 0;\n\n    z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);\n    z = fts5ConfigSkipWhitespace(z);\n    if( z && *z=='=' ){\n      bOption = 1;\n      z++;\n      if( bMustBeCol ) z = 0;\n    }\n    z = fts5ConfigSkipWhitespace(z);\n    if( z && z[0] ){\n      int bDummy;\n      z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);\n      if( z && z[0] ) z = 0;\n    }\n\n    if( rc==SQLITE_OK ){\n      if( z==0 ){\n        *pzErr = sqlite3_mprintf(\"parse error in \\\"%s\\\"\", zOrig);\n        rc = SQLITE_ERROR;\n      }else{\n        if( bOption ){\n          rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:\"\", pzErr);\n        }else{\n          rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);\n          zOne = 0;\n        }\n      }\n    }\n\n    sqlite3_free(zOne);\n    sqlite3_free(zTwo);\n  }\n\n  /* If a tokenizer= option was successfully parsed, the tokenizer has\n  ** already been allocated. Otherwise, allocate an instance of the default\n  ** tokenizer (unicode61) now.  */\n  if( rc==SQLITE_OK && pRet->pTok==0 ){\n    rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);\n  }\n\n  /* If no zContent option was specified, fill in the default values. */\n  if( rc==SQLITE_OK && pRet->zContent==0 ){\n    const char *zTail = 0;\n    assert( pRet->eContent==FTS5_CONTENT_NORMAL \n         || pRet->eContent==FTS5_CONTENT_NONE \n    );\n    if( pRet->eContent==FTS5_CONTENT_NORMAL ){\n      zTail = \"content\";\n    }else if( pRet->bColumnsize ){\n      zTail = \"docsize\";\n    }\n\n    if( zTail ){\n      pRet->zContent = sqlite3Fts5Mprintf(\n          &rc, \"%Q.'%q_%s'\", pRet->zDb, pRet->zName, zTail\n      );\n    }\n  }\n\n  if( rc==SQLITE_OK && pRet->zContentRowid==0 ){\n    pRet->zContentRowid = sqlite3Fts5Strndup(&rc, \"rowid\", -1);\n  }\n\n  /* Formulate the zContentExprlist text */\n  if( rc==SQLITE_OK ){\n    rc = fts5ConfigMakeExprlist(pRet);\n  }\n\n  if( rc!=SQLITE_OK ){\n    sqlite3Fts5ConfigFree(pRet);\n    *ppOut = 0;\n  }\n  return rc;\n}\n\n/*\n** Free the configuration object passed as the only argument.\n*/\nstatic void sqlite3Fts5ConfigFree(Fts5Config *pConfig){\n  if( pConfig ){\n    int i;\n    if( pConfig->pTok ){\n      pConfig->pTokApi->xDelete(pConfig->pTok);\n    }\n    sqlite3_free(pConfig->zDb);\n    sqlite3_free(pConfig->zName);\n    for(i=0; i<pConfig->nCol; i++){\n      sqlite3_free(pConfig->azCol[i]);\n    }\n    sqlite3_free(pConfig->azCol);\n    sqlite3_free(pConfig->aPrefix);\n    sqlite3_free(pConfig->zRank);\n    sqlite3_free(pConfig->zRankArgs);\n    sqlite3_free(pConfig->zContent);\n    sqlite3_free(pConfig->zContentRowid);\n    sqlite3_free(pConfig->zContentExprlist);\n    sqlite3_free(pConfig);\n  }\n}\n\n/*\n** Call sqlite3_declare_vtab() based on the contents of the configuration\n** object passed as the only argument. Return SQLITE_OK if successful, or\n** an SQLite error code if an error occurs.\n*/\nstatic int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){\n  int i;\n  int rc = SQLITE_OK;\n  char *zSql;\n\n  zSql = sqlite3Fts5Mprintf(&rc, \"CREATE TABLE x(\");\n  for(i=0; zSql && i<pConfig->nCol; i++){\n    const char *zSep = (i==0?\"\":\", \");\n    zSql = sqlite3Fts5Mprintf(&rc, \"%z%s%Q\", zSql, zSep, pConfig->azCol[i]);\n  }\n  zSql = sqlite3Fts5Mprintf(&rc, \"%z, %Q HIDDEN, %s HIDDEN)\", \n      zSql, pConfig->zName, FTS5_RANK_NAME\n  );\n\n  assert( zSql || rc==SQLITE_NOMEM );\n  if( zSql ){\n    rc = sqlite3_declare_vtab(pConfig->db, zSql);\n    sqlite3_free(zSql);\n  }\n \n  return rc;\n}\n\n/*\n** Tokenize the text passed via the second and third arguments.\n**\n** The callback is invoked once for each token in the input text. The\n** arguments passed to it are, in order:\n**\n**     void *pCtx          // Copy of 4th argument to sqlite3Fts5Tokenize()\n**     const char *pToken  // Pointer to buffer containing token\n**     int nToken          // Size of token in bytes\n**     int iStart          // Byte offset of start of token within input text\n**     int iEnd            // Byte offset of end of token within input text\n**     int iPos            // Position of token in input (first token is 0)\n**\n** If the callback returns a non-zero value the tokenization is abandoned\n** and no further callbacks are issued. \n**\n** This function returns SQLITE_OK if successful or an SQLite error code\n** if an error occurs. If the tokenization was abandoned early because\n** the callback returned SQLITE_DONE, this is not an error and this function\n** still returns SQLITE_OK. Or, if the tokenization was abandoned early\n** because the callback returned another non-zero value, it is assumed\n** to be an SQLite error code and returned to the caller.\n*/\nstatic int sqlite3Fts5Tokenize(\n  Fts5Config *pConfig,            /* FTS5 Configuration object */\n  int flags,                      /* FTS5_TOKENIZE_* flags */\n  const char *pText, int nText,   /* Text to tokenize */\n  void *pCtx,                     /* Context passed to xToken() */\n  int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */\n){\n  if( pText==0 ) return SQLITE_OK;\n  return pConfig->pTokApi->xTokenize(\n      pConfig->pTok, pCtx, flags, pText, nText, xToken\n  );\n}\n\n/*\n** Argument pIn points to the first character in what is expected to be\n** a comma-separated list of SQL literals followed by a ')' character.\n** If it actually is this, return a pointer to the ')'. Otherwise, return\n** NULL to indicate a parse error.\n*/\nstatic const char *fts5ConfigSkipArgs(const char *pIn){\n  const char *p = pIn;\n  \n  while( 1 ){\n    p = fts5ConfigSkipWhitespace(p);\n    p = fts5ConfigSkipLiteral(p);\n    p = fts5ConfigSkipWhitespace(p);\n    if( p==0 || *p==')' ) break;\n    if( *p!=',' ){\n      p = 0;\n      break;\n    }\n    p++;\n  }\n\n  return p;\n}\n\n/*\n** Parameter zIn contains a rank() function specification. The format of \n** this is:\n**\n**   + Bareword (function name)\n**   + Open parenthesis - \"(\"\n**   + Zero or more SQL literals in a comma separated list\n**   + Close parenthesis - \")\"\n*/\nstatic int sqlite3Fts5ConfigParseRank(\n  const char *zIn,                /* Input string */\n  char **pzRank,                  /* OUT: Rank function name */\n  char **pzRankArgs               /* OUT: Rank function arguments */\n){\n  const char *p = zIn;\n  const char *pRank;\n  char *zRank = 0;\n  char *zRankArgs = 0;\n  int rc = SQLITE_OK;\n\n  *pzRank = 0;\n  *pzRankArgs = 0;\n\n  if( p==0 ){\n    rc = SQLITE_ERROR;\n  }else{\n    p = fts5ConfigSkipWhitespace(p);\n    pRank = p;\n    p = fts5ConfigSkipBareword(p);\n\n    if( p ){\n      zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);\n      if( zRank ) memcpy(zRank, pRank, p-pRank);\n    }else{\n      rc = SQLITE_ERROR;\n    }\n\n    if( rc==SQLITE_OK ){\n      p = fts5ConfigSkipWhitespace(p);\n      if( *p!='(' ) rc = SQLITE_ERROR;\n      p++;\n    }\n    if( rc==SQLITE_OK ){\n      const char *pArgs; \n      p = fts5ConfigSkipWhitespace(p);\n      pArgs = p;\n      if( *p!=')' ){\n        p = fts5ConfigSkipArgs(p);\n        if( p==0 ){\n          rc = SQLITE_ERROR;\n        }else{\n          zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);\n          if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);\n        }\n      }\n    }\n  }\n\n  if( rc!=SQLITE_OK ){\n    sqlite3_free(zRank);\n    assert( zRankArgs==0 );\n  }else{\n    *pzRank = zRank;\n    *pzRankArgs = zRankArgs;\n  }\n  return rc;\n}\n\nstatic int sqlite3Fts5ConfigSetValue(\n  Fts5Config *pConfig, \n  const char *zKey, \n  sqlite3_value *pVal,\n  int *pbBadkey\n){\n  int rc = SQLITE_OK;\n\n  if( 0==sqlite3_stricmp(zKey, \"pgsz\") ){\n    int pgsz = 0;\n    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){\n      pgsz = sqlite3_value_int(pVal);\n    }\n    if( pgsz<32 || pgsz>FTS5_MAX_PAGE_SIZE ){\n      *pbBadkey = 1;\n    }else{\n      pConfig->pgsz = pgsz;\n    }\n  }\n\n  else if( 0==sqlite3_stricmp(zKey, \"hashsize\") ){\n    int nHashSize = -1;\n    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){\n      nHashSize = sqlite3_value_int(pVal);\n    }\n    if( nHashSize<=0 ){\n      *pbBadkey = 1;\n    }else{\n      pConfig->nHashSize = nHashSize;\n    }\n  }\n\n  else if( 0==sqlite3_stricmp(zKey, \"automerge\") ){\n    int nAutomerge = -1;\n    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){\n      nAutomerge = sqlite3_value_int(pVal);\n    }\n    if( nAutomerge<0 || nAutomerge>64 ){\n      *pbBadkey = 1;\n    }else{\n      if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;\n      pConfig->nAutomerge = nAutomerge;\n    }\n  }\n\n  else if( 0==sqlite3_stricmp(zKey, \"usermerge\") ){\n    int nUsermerge = -1;\n    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){\n      nUsermerge = sqlite3_value_int(pVal);\n    }\n    if( nUsermerge<2 || nUsermerge>16 ){\n      *pbBadkey = 1;\n    }else{\n      pConfig->nUsermerge = nUsermerge;\n    }\n  }\n\n  else if( 0==sqlite3_stricmp(zKey, \"crisismerge\") ){\n    int nCrisisMerge = -1;\n    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){\n      nCrisisMerge = sqlite3_value_int(pVal);\n    }\n    if( nCrisisMerge<0 ){\n      *pbBadkey = 1;\n    }else{\n      if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;\n      if( nCrisisMerge>=FTS5_MAX_SEGMENT ) nCrisisMerge = FTS5_MAX_SEGMENT-1;\n      pConfig->nCrisisMerge = nCrisisMerge;\n    }\n  }\n\n  else if( 0==sqlite3_stricmp(zKey, \"rank\") ){\n    const char *zIn = (const char*)sqlite3_value_text(pVal);\n    char *zRank;\n    char *zRankArgs;\n    rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);\n    if( rc==SQLITE_OK ){\n      sqlite3_free(pConfig->zRank);\n      sqlite3_free(pConfig->zRankArgs);\n      pConfig->zRank = zRank;\n      pConfig->zRankArgs = zRankArgs;\n    }else if( rc==SQLITE_ERROR ){\n      rc = SQLITE_OK;\n      *pbBadkey = 1;\n    }\n  }else{\n    *pbBadkey = 1;\n  }\n  return rc;\n}\n\n/*\n** Load the contents of the %_config table into memory.\n*/\nstatic int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){\n  const char *zSelect = \"SELECT k, v FROM %Q.'%q_config'\";\n  char *zSql;\n  sqlite3_stmt *p = 0;\n  int rc = SQLITE_OK;\n  int iVersion = 0;\n\n  /* Set default values */\n  pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;\n  pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;\n  pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;\n  pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;\n  pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;\n\n  zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);\n  if( zSql ){\n    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);\n    sqlite3_free(zSql);\n  }\n\n  assert( rc==SQLITE_OK || p==0 );\n  if( rc==SQLITE_OK ){\n    while( SQLITE_ROW==sqlite3_step(p) ){\n      const char *zK = (const char*)sqlite3_column_text(p, 0);\n      sqlite3_value *pVal = sqlite3_column_value(p, 1);\n      if( 0==sqlite3_stricmp(zK, \"version\") ){\n        iVersion = sqlite3_value_int(pVal);\n      }else{\n        int bDummy = 0;\n        sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);\n      }\n    }\n    rc = sqlite3_finalize(p);\n  }\n  \n  if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){\n    rc = SQLITE_ERROR;\n    if( pConfig->pzErrmsg ){\n      assert( 0==*pConfig->pzErrmsg );\n      *pConfig->pzErrmsg = sqlite3_mprintf(\n          \"invalid fts5 file format (found %d, expected %d) - run 'rebuild'\",\n          iVersion, FTS5_CURRENT_VERSION\n      );\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    pConfig->iCookie = iCookie;\n  }\n  return rc;\n}\n\n/*\n** 2014 May 31\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n*/\n\n\n\n/* #include \"fts5Int.h\" */\n/* #include \"fts5parse.h\" */\n\n/*\n** All token types in the generated fts5parse.h file are greater than 0.\n*/\n#define FTS5_EOF 0\n\n#define FTS5_LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))\n\ntypedef struct Fts5ExprTerm Fts5ExprTerm;\n\n/*\n** Functions generated by lemon from fts5parse.y.\n*/\nstatic void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));\nstatic void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));\nstatic void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);\n#ifndef NDEBUG\n/* #include <stdio.h> */\nstatic void sqlite3Fts5ParserTrace(FILE*, char*);\n#endif\nstatic int sqlite3Fts5ParserFallback(int);\n\n\nstruct Fts5Expr {\n  Fts5Index *pIndex;\n  Fts5Config *pConfig;\n  Fts5ExprNode *pRoot;\n  int bDesc;                      /* Iterate in descending rowid order */\n  int nPhrase;                    /* Number of phrases in expression */\n  Fts5ExprPhrase **apExprPhrase;  /* Pointers to phrase objects */\n};\n\n/*\n** eType:\n**   Expression node type. Always one of:\n**\n**       FTS5_AND                 (nChild, apChild valid)\n**       FTS5_OR                  (nChild, apChild valid)\n**       FTS5_NOT                 (nChild, apChild valid)\n**       FTS5_STRING              (pNear valid)\n**       FTS5_TERM                (pNear valid)\n*/\nstruct Fts5ExprNode {\n  int eType;                      /* Node type */\n  int bEof;                       /* True at EOF */\n  int bNomatch;                   /* True if entry is not a match */\n\n  /* Next method for this node. */\n  int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);\n\n  i64 iRowid;                     /* Current rowid */\n  Fts5ExprNearset *pNear;         /* For FTS5_STRING - cluster of phrases */\n\n  /* Child nodes. For a NOT node, this array always contains 2 entries. For \n  ** AND or OR nodes, it contains 2 or more entries.  */\n  int nChild;                     /* Number of child nodes */\n  Fts5ExprNode *apChild[1];       /* Array of child nodes */\n};\n\n#define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)\n\n/*\n** Invoke the xNext method of an Fts5ExprNode object. This macro should be\n** used as if it has the same signature as the xNext() methods themselves.\n*/\n#define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))\n\n/*\n** An instance of the following structure represents a single search term\n** or term prefix.\n*/\nstruct Fts5ExprTerm {\n  u8 bPrefix;                     /* True for a prefix term */\n  u8 bFirst;                      /* True if token must be first in column */\n  char *zTerm;                    /* nul-terminated term */\n  Fts5IndexIter *pIter;           /* Iterator for this term */\n  Fts5ExprTerm *pSynonym;         /* Pointer to first in list of synonyms */\n};\n\n/*\n** A phrase. One or more terms that must appear in a contiguous sequence\n** within a document for it to match.\n*/\nstruct Fts5ExprPhrase {\n  Fts5ExprNode *pNode;            /* FTS5_STRING node this phrase is part of */\n  Fts5Buffer poslist;             /* Current position list */\n  int nTerm;                      /* Number of entries in aTerm[] */\n  Fts5ExprTerm aTerm[1];          /* Terms that make up this phrase */\n};\n\n/*\n** One or more phrases that must appear within a certain token distance of\n** each other within each matching document.\n*/\nstruct Fts5ExprNearset {\n  int nNear;                      /* NEAR parameter */\n  Fts5Colset *pColset;            /* Columns to search (NULL -> all columns) */\n  int nPhrase;                    /* Number of entries in aPhrase[] array */\n  Fts5ExprPhrase *apPhrase[1];    /* Array of phrase pointers */\n};\n\n\n/*\n** Parse context.\n*/\nstruct Fts5Parse {\n  Fts5Config *pConfig;\n  char *zErr;\n  int rc;\n  int nPhrase;                    /* Size of apPhrase array */\n  Fts5ExprPhrase **apPhrase;      /* Array of all phrases */\n  Fts5ExprNode *pExpr;            /* Result of a successful parse */\n};\n\nstatic void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){\n  va_list ap;\n  va_start(ap, zFmt);\n  if( pParse->rc==SQLITE_OK ){\n    pParse->zErr = sqlite3_vmprintf(zFmt, ap);\n    pParse->rc = SQLITE_ERROR;\n  }\n  va_end(ap);\n}\n\nstatic int fts5ExprIsspace(char t){\n  return t==' ' || t=='\\t' || t=='\\n' || t=='\\r';\n}\n\n/*\n** Read the first token from the nul-terminated string at *pz.\n*/\nstatic int fts5ExprGetToken(\n  Fts5Parse *pParse, \n  const char **pz,                /* IN/OUT: Pointer into buffer */\n  Fts5Token *pToken\n){\n  const char *z = *pz;\n  int tok;\n\n  /* Skip past any whitespace */\n  while( fts5ExprIsspace(*z) ) z++;\n\n  pToken->p = z;\n  pToken->n = 1;\n  switch( *z ){\n    case '(':  tok = FTS5_LP;    break;\n    case ')':  tok = FTS5_RP;    break;\n    case '{':  tok = FTS5_LCP;   break;\n    case '}':  tok = FTS5_RCP;   break;\n    case ':':  tok = FTS5_COLON; break;\n    case ',':  tok = FTS5_COMMA; break;\n    case '+':  tok = FTS5_PLUS;  break;\n    case '*':  tok = FTS5_STAR;  break;\n    case '-':  tok = FTS5_MINUS; break;\n    case '^':  tok = FTS5_CARET; break;\n    case '\\0': tok = FTS5_EOF;   break;\n\n    case '\"': {\n      const char *z2;\n      tok = FTS5_STRING;\n\n      for(z2=&z[1]; 1; z2++){\n        if( z2[0]=='\"' ){\n          z2++;\n          if( z2[0]!='\"' ) break;\n        }\n        if( z2[0]=='\\0' ){\n          sqlite3Fts5ParseError(pParse, \"unterminated string\");\n          return FTS5_EOF;\n        }\n      }\n      pToken->n = (z2 - z);\n      break;\n    }\n\n    default: {\n      const char *z2;\n      if( sqlite3Fts5IsBareword(z[0])==0 ){\n        sqlite3Fts5ParseError(pParse, \"fts5: syntax error near \\\"%.1s\\\"\", z);\n        return FTS5_EOF;\n      }\n      tok = FTS5_STRING;\n      for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);\n      pToken->n = (z2 - z);\n      if( pToken->n==2 && memcmp(pToken->p, \"OR\", 2)==0 )  tok = FTS5_OR;\n      if( pToken->n==3 && memcmp(pToken->p, \"NOT\", 3)==0 ) tok = FTS5_NOT;\n      if( pToken->n==3 && memcmp(pToken->p, \"AND\", 3)==0 ) tok = FTS5_AND;\n      break;\n    }\n  }\n\n  *pz = &pToken->p[pToken->n];\n  return tok;\n}\n\nstatic void *fts5ParseAlloc(u64 t){ return sqlite3_malloc64((sqlite3_int64)t);}\nstatic void fts5ParseFree(void *p){ sqlite3_free(p); }\n\nstatic int sqlite3Fts5ExprNew(\n  Fts5Config *pConfig,            /* FTS5 Configuration */\n  int iCol,\n  const char *zExpr,              /* Expression text */\n  Fts5Expr **ppNew, \n  char **pzErr\n){\n  Fts5Parse sParse;\n  Fts5Token token;\n  const char *z = zExpr;\n  int t;                          /* Next token type */\n  void *pEngine;\n  Fts5Expr *pNew;\n\n  *ppNew = 0;\n  *pzErr = 0;\n  memset(&sParse, 0, sizeof(sParse));\n  pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);\n  if( pEngine==0 ){ return SQLITE_NOMEM; }\n  sParse.pConfig = pConfig;\n\n  do {\n    t = fts5ExprGetToken(&sParse, &z, &token);\n    sqlite3Fts5Parser(pEngine, t, token, &sParse);\n  }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );\n  sqlite3Fts5ParserFree(pEngine, fts5ParseFree);\n\n  /* If the LHS of the MATCH expression was a user column, apply the\n  ** implicit column-filter.  */\n  if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){\n    int n = sizeof(Fts5Colset);\n    Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);\n    if( pColset ){\n      pColset->nCol = 1;\n      pColset->aiCol[0] = iCol;\n      sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);\n    }\n  }\n\n  assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );\n  if( sParse.rc==SQLITE_OK ){\n    *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));\n    if( pNew==0 ){\n      sParse.rc = SQLITE_NOMEM;\n      sqlite3Fts5ParseNodeFree(sParse.pExpr);\n    }else{\n      if( !sParse.pExpr ){\n        const int nByte = sizeof(Fts5ExprNode);\n        pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);\n        if( pNew->pRoot ){\n          pNew->pRoot->bEof = 1;\n        }\n      }else{\n        pNew->pRoot = sParse.pExpr;\n      }\n      pNew->pIndex = 0;\n      pNew->pConfig = pConfig;\n      pNew->apExprPhrase = sParse.apPhrase;\n      pNew->nPhrase = sParse.nPhrase;\n      sParse.apPhrase = 0;\n    }\n  }else{\n    sqlite3Fts5ParseNodeFree(sParse.pExpr);\n  }\n\n  sqlite3_free(sParse.apPhrase);\n  *pzErr = sParse.zErr;\n  return sParse.rc;\n}\n\n/*\n** Free the expression node object passed as the only argument.\n*/\nstatic void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){\n  if( p ){\n    int i;\n    for(i=0; i<p->nChild; i++){\n      sqlite3Fts5ParseNodeFree(p->apChild[i]);\n    }\n    sqlite3Fts5ParseNearsetFree(p->pNear);\n    sqlite3_free(p);\n  }\n}\n\n/*\n** Free the expression object passed as the only argument.\n*/\nstatic void sqlite3Fts5ExprFree(Fts5Expr *p){\n  if( p ){\n    sqlite3Fts5ParseNodeFree(p->pRoot);\n    sqlite3_free(p->apExprPhrase);\n    sqlite3_free(p);\n  }\n}\n\nstatic int sqlite3Fts5ExprAnd(Fts5Expr **pp1, Fts5Expr *p2){\n  Fts5Parse sParse;\n  memset(&sParse, 0, sizeof(sParse));\n\n  if( *pp1 ){\n    Fts5Expr *p1 = *pp1;\n    int nPhrase = p1->nPhrase + p2->nPhrase;\n\n    p1->pRoot = sqlite3Fts5ParseNode(&sParse, FTS5_AND, p1->pRoot, p2->pRoot,0);\n    p2->pRoot = 0;\n\n    if( sParse.rc==SQLITE_OK ){\n      Fts5ExprPhrase **ap = (Fts5ExprPhrase**)sqlite3_realloc(\n          p1->apExprPhrase, nPhrase * sizeof(Fts5ExprPhrase*)\n      );\n      if( ap==0 ){\n        sParse.rc = SQLITE_NOMEM;\n      }else{\n        int i;\n        memmove(&ap[p2->nPhrase], ap, p1->nPhrase*sizeof(Fts5ExprPhrase*));\n        for(i=0; i<p2->nPhrase; i++){\n          ap[i] = p2->apExprPhrase[i];\n        }\n        p1->nPhrase = nPhrase;\n        p1->apExprPhrase = ap;\n      }\n    }\n    sqlite3_free(p2->apExprPhrase);\n    sqlite3_free(p2);\n  }else{\n    *pp1 = p2;\n  }\n\n  return sParse.rc;\n}\n\n/*\n** Argument pTerm must be a synonym iterator. Return the current rowid\n** that it points to.\n*/\nstatic i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){\n  i64 iRet = 0;\n  int bRetValid = 0;\n  Fts5ExprTerm *p;\n\n  assert( pTerm->pSynonym );\n  assert( bDesc==0 || bDesc==1 );\n  for(p=pTerm; p; p=p->pSynonym){\n    if( 0==sqlite3Fts5IterEof(p->pIter) ){\n      i64 iRowid = p->pIter->iRowid;\n      if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){\n        iRet = iRowid;\n        bRetValid = 1;\n      }\n    }\n  }\n\n  if( pbEof && bRetValid==0 ) *pbEof = 1;\n  return iRet;\n}\n\n/*\n** Argument pTerm must be a synonym iterator.\n*/\nstatic int fts5ExprSynonymList(\n  Fts5ExprTerm *pTerm, \n  i64 iRowid,\n  Fts5Buffer *pBuf,               /* Use this buffer for space if required */\n  u8 **pa, int *pn\n){\n  Fts5PoslistReader aStatic[4];\n  Fts5PoslistReader *aIter = aStatic;\n  int nIter = 0;\n  int nAlloc = 4;\n  int rc = SQLITE_OK;\n  Fts5ExprTerm *p;\n\n  assert( pTerm->pSynonym );\n  for(p=pTerm; p; p=p->pSynonym){\n    Fts5IndexIter *pIter = p->pIter;\n    if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){\n      if( pIter->nData==0 ) continue;\n      if( nIter==nAlloc ){\n        sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;\n        Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc64(nByte);\n        if( aNew==0 ){\n          rc = SQLITE_NOMEM;\n          goto synonym_poslist_out;\n        }\n        memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);\n        nAlloc = nAlloc*2;\n        if( aIter!=aStatic ) sqlite3_free(aIter);\n        aIter = aNew;\n      }\n      sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);\n      assert( aIter[nIter].bEof==0 );\n      nIter++;\n    }\n  }\n\n  if( nIter==1 ){\n    *pa = (u8*)aIter[0].a;\n    *pn = aIter[0].n;\n  }else{\n    Fts5PoslistWriter writer = {0};\n    i64 iPrev = -1;\n    fts5BufferZero(pBuf);\n    while( 1 ){\n      int i;\n      i64 iMin = FTS5_LARGEST_INT64;\n      for(i=0; i<nIter; i++){\n        if( aIter[i].bEof==0 ){\n          if( aIter[i].iPos==iPrev ){\n            if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;\n          }\n          if( aIter[i].iPos<iMin ){\n            iMin = aIter[i].iPos;\n          }\n        }\n      }\n      if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;\n      rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);\n      iPrev = iMin;\n    }\n    if( rc==SQLITE_OK ){\n      *pa = pBuf->p;\n      *pn = pBuf->n;\n    }\n  }\n\n synonym_poslist_out:\n  if( aIter!=aStatic ) sqlite3_free(aIter);\n  return rc;\n}\n\n\n/*\n** All individual term iterators in pPhrase are guaranteed to be valid and\n** pointing to the same rowid when this function is called. This function \n** checks if the current rowid really is a match, and if so populates\n** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch\n** is set to true if this is really a match, or false otherwise.\n**\n** SQLITE_OK is returned if an error occurs, or an SQLite error code \n** otherwise. It is not considered an error code if the current rowid is \n** not a match.\n*/\nstatic int fts5ExprPhraseIsMatch(\n  Fts5ExprNode *pNode,            /* Node pPhrase belongs to */\n  Fts5ExprPhrase *pPhrase,        /* Phrase object to initialize */\n  int *pbMatch                    /* OUT: Set to true if really a match */\n){\n  Fts5PoslistWriter writer = {0};\n  Fts5PoslistReader aStatic[4];\n  Fts5PoslistReader *aIter = aStatic;\n  int i;\n  int rc = SQLITE_OK;\n  int bFirst = pPhrase->aTerm[0].bFirst;\n  \n  fts5BufferZero(&pPhrase->poslist);\n\n  /* If the aStatic[] array is not large enough, allocate a large array\n  ** using sqlite3_malloc(). This approach could be improved upon. */\n  if( pPhrase->nTerm>ArraySize(aStatic) ){\n    sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;\n    aIter = (Fts5PoslistReader*)sqlite3_malloc64(nByte);\n    if( !aIter ) return SQLITE_NOMEM;\n  }\n  memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);\n\n  /* Initialize a term iterator for each term in the phrase */\n  for(i=0; i<pPhrase->nTerm; i++){\n    Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];\n    int n = 0;\n    int bFlag = 0;\n    u8 *a = 0;\n    if( pTerm->pSynonym ){\n      Fts5Buffer buf = {0, 0, 0};\n      rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);\n      if( rc ){\n        sqlite3_free(a);\n        goto ismatch_out;\n      }\n      if( a==buf.p ) bFlag = 1;\n    }else{\n      a = (u8*)pTerm->pIter->pData;\n      n = pTerm->pIter->nData;\n    }\n    sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);\n    aIter[i].bFlag = (u8)bFlag;\n    if( aIter[i].bEof ) goto ismatch_out;\n  }\n\n  while( 1 ){\n    int bMatch;\n    i64 iPos = aIter[0].iPos;\n    do {\n      bMatch = 1;\n      for(i=0; i<pPhrase->nTerm; i++){\n        Fts5PoslistReader *pPos = &aIter[i];\n        i64 iAdj = iPos + i;\n        if( pPos->iPos!=iAdj ){\n          bMatch = 0;\n          while( pPos->iPos<iAdj ){\n            if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;\n          }\n          if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;\n        }\n      }\n    }while( bMatch==0 );\n\n    /* Append position iPos to the output */\n    if( bFirst==0 || FTS5_POS2OFFSET(iPos)==0 ){\n      rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);\n      if( rc!=SQLITE_OK ) goto ismatch_out;\n    }\n\n    for(i=0; i<pPhrase->nTerm; i++){\n      if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;\n    }\n  }\n\n ismatch_out:\n  *pbMatch = (pPhrase->poslist.n>0);\n  for(i=0; i<pPhrase->nTerm; i++){\n    if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);\n  }\n  if( aIter!=aStatic ) sqlite3_free(aIter);\n  return rc;\n}\n\ntypedef struct Fts5LookaheadReader Fts5LookaheadReader;\nstruct Fts5LookaheadReader {\n  const u8 *a;                    /* Buffer containing position list */\n  int n;                          /* Size of buffer a[] in bytes */\n  int i;                          /* Current offset in position list */\n  i64 iPos;                       /* Current position */\n  i64 iLookahead;                 /* Next position */\n};\n\n#define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)\n\nstatic int fts5LookaheadReaderNext(Fts5LookaheadReader *p){\n  p->iPos = p->iLookahead;\n  if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){\n    p->iLookahead = FTS5_LOOKAHEAD_EOF;\n  }\n  return (p->iPos==FTS5_LOOKAHEAD_EOF);\n}\n\nstatic int fts5LookaheadReaderInit(\n  const u8 *a, int n,             /* Buffer to read position list from */\n  Fts5LookaheadReader *p          /* Iterator object to initialize */\n){\n  memset(p, 0, sizeof(Fts5LookaheadReader));\n  p->a = a;\n  p->n = n;\n  fts5LookaheadReaderNext(p);\n  return fts5LookaheadReaderNext(p);\n}\n\ntypedef struct Fts5NearTrimmer Fts5NearTrimmer;\nstruct Fts5NearTrimmer {\n  Fts5LookaheadReader reader;     /* Input iterator */\n  Fts5PoslistWriter writer;       /* Writer context */\n  Fts5Buffer *pOut;               /* Output poslist */\n};\n\n/*\n** The near-set object passed as the first argument contains more than\n** one phrase. All phrases currently point to the same row. The\n** Fts5ExprPhrase.poslist buffers are populated accordingly. This function\n** tests if the current row contains instances of each phrase sufficiently\n** close together to meet the NEAR constraint. Non-zero is returned if it\n** does, or zero otherwise.\n**\n** If in/out parameter (*pRc) is set to other than SQLITE_OK when this\n** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)\n** occurs within this function (*pRc) is set accordingly before returning.\n** The return value is undefined in both these cases.\n** \n** If no error occurs and non-zero (a match) is returned, the position-list\n** of each phrase object is edited to contain only those entries that\n** meet the constraint before returning.\n*/\nstatic int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){\n  Fts5NearTrimmer aStatic[4];\n  Fts5NearTrimmer *a = aStatic;\n  Fts5ExprPhrase **apPhrase = pNear->apPhrase;\n\n  int i;\n  int rc = *pRc;\n  int bMatch;\n\n  assert( pNear->nPhrase>1 );\n\n  /* If the aStatic[] array is not large enough, allocate a large array\n  ** using sqlite3_malloc(). This approach could be improved upon. */\n  if( pNear->nPhrase>ArraySize(aStatic) ){\n    sqlite3_int64 nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;\n    a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);\n  }else{\n    memset(aStatic, 0, sizeof(aStatic));\n  }\n  if( rc!=SQLITE_OK ){\n    *pRc = rc;\n    return 0;\n  }\n\n  /* Initialize a lookahead iterator for each phrase. After passing the\n  ** buffer and buffer size to the lookaside-reader init function, zero\n  ** the phrase poslist buffer. The new poslist for the phrase (containing\n  ** the same entries as the original with some entries removed on account \n  ** of the NEAR constraint) is written over the original even as it is\n  ** being read. This is safe as the entries for the new poslist are a\n  ** subset of the old, so it is not possible for data yet to be read to\n  ** be overwritten.  */\n  for(i=0; i<pNear->nPhrase; i++){\n    Fts5Buffer *pPoslist = &apPhrase[i]->poslist;\n    fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);\n    pPoslist->n = 0;\n    a[i].pOut = pPoslist;\n  }\n\n  while( 1 ){\n    int iAdv;\n    i64 iMin;\n    i64 iMax;\n\n    /* This block advances the phrase iterators until they point to a set of\n    ** entries that together comprise a match.  */\n    iMax = a[0].reader.iPos;\n    do {\n      bMatch = 1;\n      for(i=0; i<pNear->nPhrase; i++){\n        Fts5LookaheadReader *pPos = &a[i].reader;\n        iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;\n        if( pPos->iPos<iMin || pPos->iPos>iMax ){\n          bMatch = 0;\n          while( pPos->iPos<iMin ){\n            if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;\n          }\n          if( pPos->iPos>iMax ) iMax = pPos->iPos;\n        }\n      }\n    }while( bMatch==0 );\n\n    /* Add an entry to each output position list */\n    for(i=0; i<pNear->nPhrase; i++){\n      i64 iPos = a[i].reader.iPos;\n      Fts5PoslistWriter *pWriter = &a[i].writer;\n      if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){\n        sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);\n      }\n    }\n\n    iAdv = 0;\n    iMin = a[0].reader.iLookahead;\n    for(i=0; i<pNear->nPhrase; i++){\n      if( a[i].reader.iLookahead < iMin ){\n        iMin = a[i].reader.iLookahead;\n        iAdv = i;\n      }\n    }\n    if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;\n  }\n\n  ismatch_out: {\n    int bRet = a[0].pOut->n>0;\n    *pRc = rc;\n    if( a!=aStatic ) sqlite3_free(a);\n    return bRet;\n  }\n}\n\n/*\n** Advance iterator pIter until it points to a value equal to or laster\n** than the initial value of *piLast. If this means the iterator points\n** to a value laster than *piLast, update *piLast to the new lastest value.\n**\n** If the iterator reaches EOF, set *pbEof to true before returning. If\n** an error occurs, set *pRc to an error code. If either *pbEof or *pRc\n** are set, return a non-zero value. Otherwise, return zero.\n*/\nstatic int fts5ExprAdvanceto(\n  Fts5IndexIter *pIter,           /* Iterator to advance */\n  int bDesc,                      /* True if iterator is \"rowid DESC\" */\n  i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */\n  int *pRc,                       /* OUT: Error code */\n  int *pbEof                      /* OUT: Set to true if EOF */\n){\n  i64 iLast = *piLast;\n  i64 iRowid;\n\n  iRowid = pIter->iRowid;\n  if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){\n    int rc = sqlite3Fts5IterNextFrom(pIter, iLast);\n    if( rc || sqlite3Fts5IterEof(pIter) ){\n      *pRc = rc;\n      *pbEof = 1;\n      return 1;\n    }\n    iRowid = pIter->iRowid;\n    assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );\n  }\n  *piLast = iRowid;\n\n  return 0;\n}\n\nstatic int fts5ExprSynonymAdvanceto(\n  Fts5ExprTerm *pTerm,            /* Term iterator to advance */\n  int bDesc,                      /* True if iterator is \"rowid DESC\" */\n  i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */\n  int *pRc                        /* OUT: Error code */\n){\n  int rc = SQLITE_OK;\n  i64 iLast = *piLast;\n  Fts5ExprTerm *p;\n  int bEof = 0;\n\n  for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){\n    if( sqlite3Fts5IterEof(p->pIter)==0 ){\n      i64 iRowid = p->pIter->iRowid;\n      if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){\n        rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);\n      }\n    }\n  }\n\n  if( rc!=SQLITE_OK ){\n    *pRc = rc;\n    bEof = 1;\n  }else{\n    *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);\n  }\n  return bEof;\n}\n\n\nstatic int fts5ExprNearTest(\n  int *pRc,\n  Fts5Expr *pExpr,                /* Expression that pNear is a part of */\n  Fts5ExprNode *pNode             /* The \"NEAR\" node (FTS5_STRING) */\n){\n  Fts5ExprNearset *pNear = pNode->pNear;\n  int rc = *pRc;\n\n  if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){\n    Fts5ExprTerm *pTerm;\n    Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];\n    pPhrase->poslist.n = 0;\n    for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){\n      Fts5IndexIter *pIter = pTerm->pIter;\n      if( sqlite3Fts5IterEof(pIter)==0 ){\n        if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){\n          pPhrase->poslist.n = 1;\n        }\n      }\n    }\n    return pPhrase->poslist.n;\n  }else{\n    int i;\n\n    /* Check that each phrase in the nearset matches the current row.\n    ** Populate the pPhrase->poslist buffers at the same time. If any\n    ** phrase is not a match, break out of the loop early.  */\n    for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){\n      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];\n      if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym \n       || pNear->pColset || pPhrase->aTerm[0].bFirst\n      ){\n        int bMatch = 0;\n        rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);\n        if( bMatch==0 ) break;\n      }else{\n        Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;\n        fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);\n      }\n    }\n\n    *pRc = rc;\n    if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){\n      return 1;\n    }\n    return 0;\n  }\n}\n\n\n/*\n** Initialize all term iterators in the pNear object. If any term is found\n** to match no documents at all, return immediately without initializing any\n** further iterators.\n**\n** If an error occurs, return an SQLite error code. Otherwise, return\n** SQLITE_OK. It is not considered an error if some term matches zero\n** documents.\n*/\nstatic int fts5ExprNearInitAll(\n  Fts5Expr *pExpr,\n  Fts5ExprNode *pNode\n){\n  Fts5ExprNearset *pNear = pNode->pNear;\n  int i;\n\n  assert( pNode->bNomatch==0 );\n  for(i=0; i<pNear->nPhrase; i++){\n    Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];\n    if( pPhrase->nTerm==0 ){\n      pNode->bEof = 1;\n      return SQLITE_OK;\n    }else{\n      int j;\n      for(j=0; j<pPhrase->nTerm; j++){\n        Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];\n        Fts5ExprTerm *p;\n        int bHit = 0;\n\n        for(p=pTerm; p; p=p->pSynonym){\n          int rc;\n          if( p->pIter ){\n            sqlite3Fts5IterClose(p->pIter);\n            p->pIter = 0;\n          }\n          rc = sqlite3Fts5IndexQuery(\n              pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),\n              (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |\n              (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),\n              pNear->pColset,\n              &p->pIter\n          );\n          assert( (rc==SQLITE_OK)==(p->pIter!=0) );\n          if( rc!=SQLITE_OK ) return rc;\n          if( 0==sqlite3Fts5IterEof(p->pIter) ){\n            bHit = 1;\n          }\n        }\n\n        if( bHit==0 ){\n          pNode->bEof = 1;\n          return SQLITE_OK;\n        }\n      }\n    }\n  }\n\n  pNode->bEof = 0;\n  return SQLITE_OK;\n}\n\n/*\n** If pExpr is an ASC iterator, this function returns a value with the\n** same sign as:\n**\n**   (iLhs - iRhs)\n**\n** Otherwise, if this is a DESC iterator, the opposite is returned:\n**\n**   (iRhs - iLhs)\n*/\nstatic int fts5RowidCmp(\n  Fts5Expr *pExpr,\n  i64 iLhs,\n  i64 iRhs\n){\n  assert( pExpr->bDesc==0 || pExpr->bDesc==1 );\n  if( pExpr->bDesc==0 ){\n    if( iLhs<iRhs ) return -1;\n    return (iLhs > iRhs);\n  }else{\n    if( iLhs>iRhs ) return -1;\n    return (iLhs < iRhs);\n  }\n}\n\nstatic void fts5ExprSetEof(Fts5ExprNode *pNode){\n  int i;\n  pNode->bEof = 1;\n  pNode->bNomatch = 0;\n  for(i=0; i<pNode->nChild; i++){\n    fts5ExprSetEof(pNode->apChild[i]);\n  }\n}\n\nstatic void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){\n  if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){\n    Fts5ExprNearset *pNear = pNode->pNear;\n    int i;\n    for(i=0; i<pNear->nPhrase; i++){\n      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];\n      pPhrase->poslist.n = 0;\n    }\n  }else{\n    int i;\n    for(i=0; i<pNode->nChild; i++){\n      fts5ExprNodeZeroPoslist(pNode->apChild[i]);\n    }\n  }\n}\n\n\n\n/*\n** Compare the values currently indicated by the two nodes as follows:\n**\n**    res = (*p1) - (*p2)\n**\n** Nodes that point to values that come later in the iteration order are\n** considered to be larger. Nodes at EOF are the largest of all.\n**\n** This means that if the iteration order is ASC, then numerically larger\n** rowids are considered larger. Or if it is the default DESC, numerically\n** smaller rowids are larger.\n*/\nstatic int fts5NodeCompare(\n  Fts5Expr *pExpr,\n  Fts5ExprNode *p1, \n  Fts5ExprNode *p2\n){\n  if( p2->bEof ) return -1;\n  if( p1->bEof ) return +1;\n  return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);\n}\n\n/*\n** All individual term iterators in pNear are guaranteed to be valid when\n** this function is called. This function checks if all term iterators\n** point to the same rowid, and if not, advances them until they do.\n** If an EOF is reached before this happens, *pbEof is set to true before\n** returning.\n**\n** SQLITE_OK is returned if an error occurs, or an SQLite error code \n** otherwise. It is not considered an error code if an iterator reaches\n** EOF.\n*/\nstatic int fts5ExprNodeTest_STRING(\n  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */\n  Fts5ExprNode *pNode\n){\n  Fts5ExprNearset *pNear = pNode->pNear;\n  Fts5ExprPhrase *pLeft = pNear->apPhrase[0];\n  int rc = SQLITE_OK;\n  i64 iLast;                      /* Lastest rowid any iterator points to */\n  int i, j;                       /* Phrase and token index, respectively */\n  int bMatch;                     /* True if all terms are at the same rowid */\n  const int bDesc = pExpr->bDesc;\n\n  /* Check that this node should not be FTS5_TERM */\n  assert( pNear->nPhrase>1 \n       || pNear->apPhrase[0]->nTerm>1 \n       || pNear->apPhrase[0]->aTerm[0].pSynonym\n       || pNear->apPhrase[0]->aTerm[0].bFirst\n  );\n\n  /* Initialize iLast, the \"lastest\" rowid any iterator points to. If the\n  ** iterator skips through rowids in the default ascending order, this means\n  ** the maximum rowid. Or, if the iterator is \"ORDER BY rowid DESC\", then it\n  ** means the minimum rowid.  */\n  if( pLeft->aTerm[0].pSynonym ){\n    iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);\n  }else{\n    iLast = pLeft->aTerm[0].pIter->iRowid;\n  }\n\n  do {\n    bMatch = 1;\n    for(i=0; i<pNear->nPhrase; i++){\n      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];\n      for(j=0; j<pPhrase->nTerm; j++){\n        Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];\n        if( pTerm->pSynonym ){\n          i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);\n          if( iRowid==iLast ) continue;\n          bMatch = 0;\n          if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){\n            pNode->bNomatch = 0;\n            pNode->bEof = 1;\n            return rc;\n          }\n        }else{\n          Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;\n          if( pIter->iRowid==iLast || pIter->bEof ) continue;\n          bMatch = 0;\n          if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){\n            return rc;\n          }\n        }\n      }\n    }\n  }while( bMatch==0 );\n\n  pNode->iRowid = iLast;\n  pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);\n  assert( pNode->bEof==0 || pNode->bNomatch==0 );\n\n  return rc;\n}\n\n/*\n** Advance the first term iterator in the first phrase of pNear. Set output\n** variable *pbEof to true if it reaches EOF or if an error occurs.\n**\n** Return SQLITE_OK if successful, or an SQLite error code if an error\n** occurs.\n*/\nstatic int fts5ExprNodeNext_STRING(\n  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */\n  Fts5ExprNode *pNode,            /* FTS5_STRING or FTS5_TERM node */\n  int bFromValid,\n  i64 iFrom \n){\n  Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];\n  int rc = SQLITE_OK;\n\n  pNode->bNomatch = 0;\n  if( pTerm->pSynonym ){\n    int bEof = 1;\n    Fts5ExprTerm *p;\n\n    /* Find the firstest rowid any synonym points to. */\n    i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);\n\n    /* Advance each iterator that currently points to iRowid. Or, if iFrom\n    ** is valid - each iterator that points to a rowid before iFrom.  */\n    for(p=pTerm; p; p=p->pSynonym){\n      if( sqlite3Fts5IterEof(p->pIter)==0 ){\n        i64 ii = p->pIter->iRowid;\n        if( ii==iRowid \n         || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc) \n        ){\n          if( bFromValid ){\n            rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);\n          }else{\n            rc = sqlite3Fts5IterNext(p->pIter);\n          }\n          if( rc!=SQLITE_OK ) break;\n          if( sqlite3Fts5IterEof(p->pIter)==0 ){\n            bEof = 0;\n          }\n        }else{\n          bEof = 0;\n        }\n      }\n    }\n\n    /* Set the EOF flag if either all synonym iterators are at EOF or an\n    ** error has occurred.  */\n    pNode->bEof = (rc || bEof);\n  }else{\n    Fts5IndexIter *pIter = pTerm->pIter;\n\n    assert( Fts5NodeIsString(pNode) );\n    if( bFromValid ){\n      rc = sqlite3Fts5IterNextFrom(pIter, iFrom);\n    }else{\n      rc = sqlite3Fts5IterNext(pIter);\n    }\n\n    pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));\n  }\n\n  if( pNode->bEof==0 ){\n    assert( rc==SQLITE_OK );\n    rc = fts5ExprNodeTest_STRING(pExpr, pNode);\n  }\n\n  return rc;\n}\n\n\nstatic int fts5ExprNodeTest_TERM(\n  Fts5Expr *pExpr,                /* Expression that pNear is a part of */\n  Fts5ExprNode *pNode             /* The \"NEAR\" node (FTS5_TERM) */\n){\n  /* As this \"NEAR\" object is actually a single phrase that consists \n  ** of a single term only, grab pointers into the poslist managed by the\n  ** fts5_index.c iterator object. This is much faster than synthesizing \n  ** a new poslist the way we have to for more complicated phrase or NEAR\n  ** expressions.  */\n  Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];\n  Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;\n\n  assert( pNode->eType==FTS5_TERM );\n  assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );\n  assert( pPhrase->aTerm[0].pSynonym==0 );\n\n  pPhrase->poslist.n = pIter->nData;\n  if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){\n    pPhrase->poslist.p = (u8*)pIter->pData;\n  }\n  pNode->iRowid = pIter->iRowid;\n  pNode->bNomatch = (pPhrase->poslist.n==0);\n  return SQLITE_OK;\n}\n\n/*\n** xNext() method for a node of type FTS5_TERM.\n*/\nstatic int fts5ExprNodeNext_TERM(\n  Fts5Expr *pExpr, \n  Fts5ExprNode *pNode,\n  int bFromValid,\n  i64 iFrom\n){\n  int rc;\n  Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;\n\n  assert( pNode->bEof==0 );\n  if( bFromValid ){\n    rc = sqlite3Fts5IterNextFrom(pIter, iFrom);\n  }else{\n    rc = sqlite3Fts5IterNext(pIter);\n  }\n  if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){\n    rc = fts5ExprNodeTest_TERM(pExpr, pNode);\n  }else{\n    pNode->bEof = 1;\n    pNode->bNomatch = 0;\n  }\n  return rc;\n}\n\nstatic void fts5ExprNodeTest_OR(\n  Fts5Expr *pExpr,                /* Expression of which pNode is a part */\n  Fts5ExprNode *pNode             /* Expression node to test */\n){\n  Fts5ExprNode *pNext = pNode->apChild[0];\n  int i;\n\n  for(i=1; i<pNode->nChild; i++){\n    Fts5ExprNode *pChild = pNode->apChild[i];\n    int cmp = fts5NodeCompare(pExpr, pNext, pChild);\n    if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){\n      pNext = pChild;\n    }\n  }\n  pNode->iRowid = pNext->iRowid;\n  pNode->bEof = pNext->bEof;\n  pNode->bNomatch = pNext->bNomatch;\n}\n\nstatic int fts5ExprNodeNext_OR(\n  Fts5Expr *pExpr, \n  Fts5ExprNode *pNode,\n  int bFromValid,\n  i64 iFrom\n){\n  int i;\n  i64 iLast = pNode->iRowid;\n\n  for(i=0; i<pNode->nChild; i++){\n    Fts5ExprNode *p1 = pNode->apChild[i];\n    assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );\n    if( p1->bEof==0 ){\n      if( (p1->iRowid==iLast) \n       || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)\n      ){\n        int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);\n        if( rc!=SQLITE_OK ){\n          pNode->bNomatch = 0;\n          return rc;\n        }\n      }\n    }\n  }\n\n  fts5ExprNodeTest_OR(pExpr, pNode);\n  return SQLITE_OK;\n}\n\n/*\n** Argument pNode is an FTS5_AND node.\n*/\nstatic int fts5ExprNodeTest_AND(\n  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */\n  Fts5ExprNode *pAnd              /* FTS5_AND node to advance */\n){\n  int iChild;\n  i64 iLast = pAnd->iRowid;\n  int rc = SQLITE_OK;\n  int bMatch;\n\n  assert( pAnd->bEof==0 );\n  do {\n    pAnd->bNomatch = 0;\n    bMatch = 1;\n    for(iChild=0; iChild<pAnd->nChild; iChild++){\n      Fts5ExprNode *pChild = pAnd->apChild[iChild];\n      int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);\n      if( cmp>0 ){\n        /* Advance pChild until it points to iLast or laster */\n        rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);\n        if( rc!=SQLITE_OK ){\n          pAnd->bNomatch = 0;\n          return rc;\n        }\n      }\n\n      /* If the child node is now at EOF, so is the parent AND node. Otherwise,\n      ** the child node is guaranteed to have advanced at least as far as\n      ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the\n      ** new lastest rowid seen so far.  */\n      assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );\n      if( pChild->bEof ){\n        fts5ExprSetEof(pAnd);\n        bMatch = 1;\n        break;\n      }else if( iLast!=pChild->iRowid ){\n        bMatch = 0;\n        iLast = pChild->iRowid;\n      }\n\n      if( pChild->bNomatch ){\n        pAnd->bNomatch = 1;\n      }\n    }\n  }while( bMatch==0 );\n\n  if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){\n    fts5ExprNodeZeroPoslist(pAnd);\n  }\n  pAnd->iRowid = iLast;\n  return SQLITE_OK;\n}\n\nstatic int fts5ExprNodeNext_AND(\n  Fts5Expr *pExpr, \n  Fts5ExprNode *pNode,\n  int bFromValid,\n  i64 iFrom\n){\n  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);\n  if( rc==SQLITE_OK ){\n    rc = fts5ExprNodeTest_AND(pExpr, pNode);\n  }else{\n    pNode->bNomatch = 0;\n  }\n  return rc;\n}\n\nstatic int fts5ExprNodeTest_NOT(\n  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */\n  Fts5ExprNode *pNode             /* FTS5_NOT node to advance */\n){\n  int rc = SQLITE_OK;\n  Fts5ExprNode *p1 = pNode->apChild[0];\n  Fts5ExprNode *p2 = pNode->apChild[1];\n  assert( pNode->nChild==2 );\n\n  while( rc==SQLITE_OK && p1->bEof==0 ){\n    int cmp = fts5NodeCompare(pExpr, p1, p2);\n    if( cmp>0 ){\n      rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);\n      cmp = fts5NodeCompare(pExpr, p1, p2);\n    }\n    assert( rc!=SQLITE_OK || cmp<=0 );\n    if( cmp || p2->bNomatch ) break;\n    rc = fts5ExprNodeNext(pExpr, p1, 0, 0);\n  }\n  pNode->bEof = p1->bEof;\n  pNode->bNomatch = p1->bNomatch;\n  pNode->iRowid = p1->iRowid;\n  if( p1->bEof ){\n    fts5ExprNodeZeroPoslist(p2);\n  }\n  return rc;\n}\n\nstatic int fts5ExprNodeNext_NOT(\n  Fts5Expr *pExpr, \n  Fts5ExprNode *pNode,\n  int bFromValid,\n  i64 iFrom\n){\n  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);\n  if( rc==SQLITE_OK ){\n    rc = fts5ExprNodeTest_NOT(pExpr, pNode);\n  }\n  if( rc!=SQLITE_OK ){\n    pNode->bNomatch = 0;\n  }\n  return rc;\n}\n\n/*\n** If pNode currently points to a match, this function returns SQLITE_OK\n** without modifying it. Otherwise, pNode is advanced until it does point\n** to a match or EOF is reached.\n*/\nstatic int fts5ExprNodeTest(\n  Fts5Expr *pExpr,                /* Expression of which pNode is a part */\n  Fts5ExprNode *pNode             /* Expression node to test */\n){\n  int rc = SQLITE_OK;\n  if( pNode->bEof==0 ){\n    switch( pNode->eType ){\n\n      case FTS5_STRING: {\n        rc = fts5ExprNodeTest_STRING(pExpr, pNode);\n        break;\n      }\n\n      case FTS5_TERM: {\n        rc = fts5ExprNodeTest_TERM(pExpr, pNode);\n        break;\n      }\n\n      case FTS5_AND: {\n        rc = fts5ExprNodeTest_AND(pExpr, pNode);\n        break;\n      }\n\n      case FTS5_OR: {\n        fts5ExprNodeTest_OR(pExpr, pNode);\n        break;\n      }\n\n      default: assert( pNode->eType==FTS5_NOT ); {\n        rc = fts5ExprNodeTest_NOT(pExpr, pNode);\n        break;\n      }\n    }\n  }\n  return rc;\n}\n\n \n/*\n** Set node pNode, which is part of expression pExpr, to point to the first\n** match. If there are no matches, set the Node.bEof flag to indicate EOF.\n**\n** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.\n** It is not an error if there are no matches.\n*/\nstatic int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){\n  int rc = SQLITE_OK;\n  pNode->bEof = 0;\n  pNode->bNomatch = 0;\n\n  if( Fts5NodeIsString(pNode) ){\n    /* Initialize all term iterators in the NEAR object. */\n    rc = fts5ExprNearInitAll(pExpr, pNode);\n  }else if( pNode->xNext==0 ){\n    pNode->bEof = 1;\n  }else{\n    int i;\n    int nEof = 0;\n    for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){\n      Fts5ExprNode *pChild = pNode->apChild[i];\n      rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);\n      assert( pChild->bEof==0 || pChild->bEof==1 );\n      nEof += pChild->bEof;\n    }\n    pNode->iRowid = pNode->apChild[0]->iRowid;\n\n    switch( pNode->eType ){\n      case FTS5_AND:\n        if( nEof>0 ) fts5ExprSetEof(pNode);\n        break;\n\n      case FTS5_OR:\n        if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);\n        break;\n\n      default:\n        assert( pNode->eType==FTS5_NOT );\n        pNode->bEof = pNode->apChild[0]->bEof;\n        break;\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = fts5ExprNodeTest(pExpr, pNode);\n  }\n  return rc;\n}\n\n\n/*\n** Begin iterating through the set of documents in index pIdx matched by\n** the MATCH expression passed as the first argument. If the \"bDesc\" \n** parameter is passed a non-zero value, iteration is in descending rowid \n** order. Or, if it is zero, in ascending order.\n**\n** If iterating in ascending rowid order (bDesc==0), the first document\n** visited is that with the smallest rowid that is larger than or equal\n** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),\n** then the first document visited must have a rowid smaller than or\n** equal to iFirst.\n**\n** Return SQLITE_OK if successful, or an SQLite error code otherwise. It\n** is not considered an error if the query does not match any documents.\n*/\nstatic int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){\n  Fts5ExprNode *pRoot = p->pRoot;\n  int rc;                         /* Return code */\n\n  p->pIndex = pIdx;\n  p->bDesc = bDesc;\n  rc = fts5ExprNodeFirst(p, pRoot);\n\n  /* If not at EOF but the current rowid occurs earlier than iFirst in\n  ** the iteration order, move to document iFirst or later. */\n  if( rc==SQLITE_OK \n   && 0==pRoot->bEof \n   && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 \n  ){\n    rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);\n  }\n\n  /* If the iterator is not at a real match, skip forward until it is. */\n  while( pRoot->bNomatch ){\n    assert( pRoot->bEof==0 && rc==SQLITE_OK );\n    rc = fts5ExprNodeNext(p, pRoot, 0, 0);\n  }\n  return rc;\n}\n\n/*\n** Move to the next document \n**\n** Return SQLITE_OK if successful, or an SQLite error code otherwise. It\n** is not considered an error if the query does not match any documents.\n*/\nstatic int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){\n  int rc;\n  Fts5ExprNode *pRoot = p->pRoot;\n  assert( pRoot->bEof==0 && pRoot->bNomatch==0 );\n  do {\n    rc = fts5ExprNodeNext(p, pRoot, 0, 0);\n    assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );\n  }while( pRoot->bNomatch );\n  if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){\n    pRoot->bEof = 1;\n  }\n  return rc;\n}\n\nstatic int sqlite3Fts5ExprEof(Fts5Expr *p){\n  return p->pRoot->bEof;\n}\n\nstatic i64 sqlite3Fts5ExprRowid(Fts5Expr *p){\n  return p->pRoot->iRowid;\n}\n\nstatic int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){\n  int rc = SQLITE_OK;\n  *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);\n  return rc;\n}\n\n/*\n** Free the phrase object passed as the only argument.\n*/\nstatic void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){\n  if( pPhrase ){\n    int i;\n    for(i=0; i<pPhrase->nTerm; i++){\n      Fts5ExprTerm *pSyn;\n      Fts5ExprTerm *pNext;\n      Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];\n      sqlite3_free(pTerm->zTerm);\n      sqlite3Fts5IterClose(pTerm->pIter);\n      for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){\n        pNext = pSyn->pSynonym;\n        sqlite3Fts5IterClose(pSyn->pIter);\n        fts5BufferFree((Fts5Buffer*)&pSyn[1]);\n        sqlite3_free(pSyn);\n      }\n    }\n    if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);\n    sqlite3_free(pPhrase);\n  }\n}\n\n/*\n** Set the \"bFirst\" flag on the first token of the phrase passed as the\n** only argument.\n*/\nstatic void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase *pPhrase){\n  if( pPhrase && pPhrase->nTerm ){\n    pPhrase->aTerm[0].bFirst = 1;\n  }\n}\n\n/*\n** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated\n** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is\n** appended to it and the results returned.\n**\n** If an OOM error occurs, both the pNear and pPhrase objects are freed and\n** NULL returned.\n*/\nstatic Fts5ExprNearset *sqlite3Fts5ParseNearset(\n  Fts5Parse *pParse,              /* Parse context */\n  Fts5ExprNearset *pNear,         /* Existing nearset, or NULL */\n  Fts5ExprPhrase *pPhrase         /* Recently parsed phrase */\n){\n  const int SZALLOC = 8;\n  Fts5ExprNearset *pRet = 0;\n\n  if( pParse->rc==SQLITE_OK ){\n    if( pPhrase==0 ){\n      return pNear;\n    }\n    if( pNear==0 ){\n      sqlite3_int64 nByte;\n      nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);\n      pRet = sqlite3_malloc64(nByte);\n      if( pRet==0 ){\n        pParse->rc = SQLITE_NOMEM;\n      }else{\n        memset(pRet, 0, (size_t)nByte);\n      }\n    }else if( (pNear->nPhrase % SZALLOC)==0 ){\n      int nNew = pNear->nPhrase + SZALLOC;\n      sqlite3_int64 nByte;\n\n      nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);\n      pRet = (Fts5ExprNearset*)sqlite3_realloc64(pNear, nByte);\n      if( pRet==0 ){\n        pParse->rc = SQLITE_NOMEM;\n      }\n    }else{\n      pRet = pNear;\n    }\n  }\n\n  if( pRet==0 ){\n    assert( pParse->rc!=SQLITE_OK );\n    sqlite3Fts5ParseNearsetFree(pNear);\n    sqlite3Fts5ParsePhraseFree(pPhrase);\n  }else{\n    if( pRet->nPhrase>0 ){\n      Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];\n      assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );\n      if( pPhrase->nTerm==0 ){\n        fts5ExprPhraseFree(pPhrase);\n        pRet->nPhrase--;\n        pParse->nPhrase--;\n        pPhrase = pLast;\n      }else if( pLast->nTerm==0 ){\n        fts5ExprPhraseFree(pLast);\n        pParse->apPhrase[pParse->nPhrase-2] = pPhrase;\n        pParse->nPhrase--;\n        pRet->nPhrase--;\n      }\n    }\n    pRet->apPhrase[pRet->nPhrase++] = pPhrase;\n  }\n  return pRet;\n}\n\ntypedef struct TokenCtx TokenCtx;\nstruct TokenCtx {\n  Fts5ExprPhrase *pPhrase;\n  int rc;\n};\n\n/*\n** Callback for tokenizing terms used by ParseTerm().\n*/\nstatic int fts5ParseTokenize(\n  void *pContext,                 /* Pointer to Fts5InsertCtx object */\n  int tflags,                     /* Mask of FTS5_TOKEN_* flags */\n  const char *pToken,             /* Buffer containing token */\n  int nToken,                     /* Size of token in bytes */\n  int iUnused1,                   /* Start offset of token */\n  int iUnused2                    /* End offset of token */\n){\n  int rc = SQLITE_OK;\n  const int SZALLOC = 8;\n  TokenCtx *pCtx = (TokenCtx*)pContext;\n  Fts5ExprPhrase *pPhrase = pCtx->pPhrase;\n\n  UNUSED_PARAM2(iUnused1, iUnused2);\n\n  /* If an error has already occurred, this is a no-op */\n  if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;\n  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;\n\n  if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){\n    Fts5ExprTerm *pSyn;\n    sqlite3_int64 nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;\n    pSyn = (Fts5ExprTerm*)sqlite3_malloc64(nByte);\n    if( pSyn==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      memset(pSyn, 0, (size_t)nByte);\n      pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);\n      memcpy(pSyn->zTerm, pToken, nToken);\n      pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;\n      pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;\n    }\n  }else{\n    Fts5ExprTerm *pTerm;\n    if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){\n      Fts5ExprPhrase *pNew;\n      int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);\n\n      pNew = (Fts5ExprPhrase*)sqlite3_realloc64(pPhrase, \n          sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew\n      );\n      if( pNew==0 ){\n        rc = SQLITE_NOMEM;\n      }else{\n        if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));\n        pCtx->pPhrase = pPhrase = pNew;\n        pNew->nTerm = nNew - SZALLOC;\n      }\n    }\n\n    if( rc==SQLITE_OK ){\n      pTerm = &pPhrase->aTerm[pPhrase->nTerm++];\n      memset(pTerm, 0, sizeof(Fts5ExprTerm));\n      pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);\n    }\n  }\n\n  pCtx->rc = rc;\n  return rc;\n}\n\n\n/*\n** Free the phrase object passed as the only argument.\n*/\nstatic void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){\n  fts5ExprPhraseFree(pPhrase);\n}\n\n/*\n** Free the phrase object passed as the second argument.\n*/\nstatic void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){\n  if( pNear ){\n    int i;\n    for(i=0; i<pNear->nPhrase; i++){\n      fts5ExprPhraseFree(pNear->apPhrase[i]);\n    }\n    sqlite3_free(pNear->pColset);\n    sqlite3_free(pNear);\n  }\n}\n\nstatic void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){\n  assert( pParse->pExpr==0 );\n  pParse->pExpr = p;\n}\n\n/*\n** This function is called by the parser to process a string token. The\n** string may or may not be quoted. In any case it is tokenized and a\n** phrase object consisting of all tokens returned.\n*/\nstatic Fts5ExprPhrase *sqlite3Fts5ParseTerm(\n  Fts5Parse *pParse,              /* Parse context */\n  Fts5ExprPhrase *pAppend,        /* Phrase to append to */\n  Fts5Token *pToken,              /* String to tokenize */\n  int bPrefix                     /* True if there is a trailing \"*\" */\n){\n  Fts5Config *pConfig = pParse->pConfig;\n  TokenCtx sCtx;                  /* Context object passed to callback */\n  int rc;                         /* Tokenize return code */\n  char *z = 0;\n\n  memset(&sCtx, 0, sizeof(TokenCtx));\n  sCtx.pPhrase = pAppend;\n\n  rc = fts5ParseStringFromToken(pToken, &z);\n  if( rc==SQLITE_OK ){\n    int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);\n    int n;\n    sqlite3Fts5Dequote(z);\n    n = (int)strlen(z);\n    rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);\n  }\n  sqlite3_free(z);\n  if( rc || (rc = sCtx.rc) ){\n    pParse->rc = rc;\n    fts5ExprPhraseFree(sCtx.pPhrase);\n    sCtx.pPhrase = 0;\n  }else{\n\n    if( pAppend==0 ){\n      if( (pParse->nPhrase % 8)==0 ){\n        sqlite3_int64 nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);\n        Fts5ExprPhrase **apNew;\n        apNew = (Fts5ExprPhrase**)sqlite3_realloc64(pParse->apPhrase, nByte);\n        if( apNew==0 ){\n          pParse->rc = SQLITE_NOMEM;\n          fts5ExprPhraseFree(sCtx.pPhrase);\n          return 0;\n        }\n        pParse->apPhrase = apNew;\n      }\n      pParse->nPhrase++;\n    }\n\n    if( sCtx.pPhrase==0 ){\n      /* This happens when parsing a token or quoted phrase that contains\n      ** no token characters at all. (e.g ... MATCH '\"\"'). */\n      sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));\n    }else if( sCtx.pPhrase->nTerm ){\n      sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = (u8)bPrefix;\n    }\n    pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;\n  }\n\n  return sCtx.pPhrase;\n}\n\n/*\n** Create a new FTS5 expression by cloning phrase iPhrase of the\n** expression passed as the second argument.\n*/\nstatic int sqlite3Fts5ExprClonePhrase(\n  Fts5Expr *pExpr, \n  int iPhrase, \n  Fts5Expr **ppNew\n){\n  int rc = SQLITE_OK;             /* Return code */\n  Fts5ExprPhrase *pOrig;          /* The phrase extracted from pExpr */\n  Fts5Expr *pNew = 0;             /* Expression to return via *ppNew */\n  TokenCtx sCtx = {0,0};          /* Context object for fts5ParseTokenize */\n\n  pOrig = pExpr->apExprPhrase[iPhrase];\n  pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));\n  if( rc==SQLITE_OK ){\n    pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc, \n        sizeof(Fts5ExprPhrase*));\n  }\n  if( rc==SQLITE_OK ){\n    pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc, \n        sizeof(Fts5ExprNode));\n  }\n  if( rc==SQLITE_OK ){\n    pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc, \n        sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));\n  }\n  if( rc==SQLITE_OK ){\n    Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;\n    if( pColsetOrig ){\n      sqlite3_int64 nByte;\n      Fts5Colset *pColset;\n      nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);\n      pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);\n      if( pColset ){ \n        memcpy(pColset, pColsetOrig, (size_t)nByte);\n      }\n      pNew->pRoot->pNear->pColset = pColset;\n    }\n  }\n\n  if( pOrig->nTerm ){\n    int i;                          /* Used to iterate through phrase terms */\n    for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){\n      int tflags = 0;\n      Fts5ExprTerm *p;\n      for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){\n        const char *zTerm = p->zTerm;\n        rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),\n            0, 0);\n        tflags = FTS5_TOKEN_COLOCATED;\n      }\n      if( rc==SQLITE_OK ){\n        sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;\n        sCtx.pPhrase->aTerm[i].bFirst = pOrig->aTerm[i].bFirst;\n      }\n    }\n  }else{\n    /* This happens when parsing a token or quoted phrase that contains\n    ** no token characters at all. (e.g ... MATCH '\"\"'). */\n    sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));\n  }\n\n  if( rc==SQLITE_OK ){\n    /* All the allocations succeeded. Put the expression object together. */\n    pNew->pIndex = pExpr->pIndex;\n    pNew->pConfig = pExpr->pConfig;\n    pNew->nPhrase = 1;\n    pNew->apExprPhrase[0] = sCtx.pPhrase;\n    pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;\n    pNew->pRoot->pNear->nPhrase = 1;\n    sCtx.pPhrase->pNode = pNew->pRoot;\n\n    if( pOrig->nTerm==1 \n     && pOrig->aTerm[0].pSynonym==0 \n     && pOrig->aTerm[0].bFirst==0 \n    ){\n      pNew->pRoot->eType = FTS5_TERM;\n      pNew->pRoot->xNext = fts5ExprNodeNext_TERM;\n    }else{\n      pNew->pRoot->eType = FTS5_STRING;\n      pNew->pRoot->xNext = fts5ExprNodeNext_STRING;\n    }\n  }else{\n    sqlite3Fts5ExprFree(pNew);\n    fts5ExprPhraseFree(sCtx.pPhrase);\n    pNew = 0;\n  }\n\n  *ppNew = pNew;\n  return rc;\n}\n\n\n/*\n** Token pTok has appeared in a MATCH expression where the NEAR operator\n** is expected. If token pTok does not contain \"NEAR\", store an error\n** in the pParse object.\n*/\nstatic void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){\n  if( pTok->n!=4 || memcmp(\"NEAR\", pTok->p, 4) ){\n    sqlite3Fts5ParseError(\n        pParse, \"fts5: syntax error near \\\"%.*s\\\"\", pTok->n, pTok->p\n    );\n  }\n}\n\nstatic void sqlite3Fts5ParseSetDistance(\n  Fts5Parse *pParse, \n  Fts5ExprNearset *pNear,\n  Fts5Token *p\n){\n  if( pNear ){\n    int nNear = 0;\n    int i;\n    if( p->n ){\n      for(i=0; i<p->n; i++){\n        char c = (char)p->p[i];\n        if( c<'0' || c>'9' ){\n          sqlite3Fts5ParseError(\n              pParse, \"expected integer, got \\\"%.*s\\\"\", p->n, p->p\n              );\n          return;\n        }\n        nNear = nNear * 10 + (p->p[i] - '0');\n      }\n    }else{\n      nNear = FTS5_DEFAULT_NEARDIST;\n    }\n    pNear->nNear = nNear;\n  }\n}\n\n/*\n** The second argument passed to this function may be NULL, or it may be\n** an existing Fts5Colset object. This function returns a pointer to\n** a new colset object containing the contents of (p) with new value column\n** number iCol appended. \n**\n** If an OOM error occurs, store an error code in pParse and return NULL.\n** The old colset object (if any) is not freed in this case.\n*/\nstatic Fts5Colset *fts5ParseColset(\n  Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */\n  Fts5Colset *p,                  /* Existing colset object */\n  int iCol                        /* New column to add to colset object */\n){\n  int nCol = p ? p->nCol : 0;     /* Num. columns already in colset object */\n  Fts5Colset *pNew;               /* New colset object to return */\n\n  assert( pParse->rc==SQLITE_OK );\n  assert( iCol>=0 && iCol<pParse->pConfig->nCol );\n\n  pNew = sqlite3_realloc64(p, sizeof(Fts5Colset) + sizeof(int)*nCol);\n  if( pNew==0 ){\n    pParse->rc = SQLITE_NOMEM;\n  }else{\n    int *aiCol = pNew->aiCol;\n    int i, j;\n    for(i=0; i<nCol; i++){\n      if( aiCol[i]==iCol ) return pNew;\n      if( aiCol[i]>iCol ) break;\n    }\n    for(j=nCol; j>i; j--){\n      aiCol[j] = aiCol[j-1];\n    }\n    aiCol[i] = iCol;\n    pNew->nCol = nCol+1;\n\n#ifndef NDEBUG\n    /* Check that the array is in order and contains no duplicate entries. */\n    for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );\n#endif\n  }\n\n  return pNew;\n}\n\n/*\n** Allocate and return an Fts5Colset object specifying the inverse of\n** the colset passed as the second argument. Free the colset passed\n** as the second argument before returning.\n*/\nstatic Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){\n  Fts5Colset *pRet;\n  int nCol = pParse->pConfig->nCol;\n\n  pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc, \n      sizeof(Fts5Colset) + sizeof(int)*nCol\n  );\n  if( pRet ){\n    int i;\n    int iOld = 0;\n    for(i=0; i<nCol; i++){\n      if( iOld>=p->nCol || p->aiCol[iOld]!=i ){\n        pRet->aiCol[pRet->nCol++] = i;\n      }else{\n        iOld++;\n      }\n    }\n  }\n\n  sqlite3_free(p);\n  return pRet;\n}\n\nstatic Fts5Colset *sqlite3Fts5ParseColset(\n  Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */\n  Fts5Colset *pColset,            /* Existing colset object */\n  Fts5Token *p\n){\n  Fts5Colset *pRet = 0;\n  int iCol;\n  char *z;                        /* Dequoted copy of token p */\n\n  z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);\n  if( pParse->rc==SQLITE_OK ){\n    Fts5Config *pConfig = pParse->pConfig;\n    sqlite3Fts5Dequote(z);\n    for(iCol=0; iCol<pConfig->nCol; iCol++){\n      if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;\n    }\n    if( iCol==pConfig->nCol ){\n      sqlite3Fts5ParseError(pParse, \"no such column: %s\", z);\n    }else{\n      pRet = fts5ParseColset(pParse, pColset, iCol);\n    }\n    sqlite3_free(z);\n  }\n\n  if( pRet==0 ){\n    assert( pParse->rc!=SQLITE_OK );\n    sqlite3_free(pColset);\n  }\n\n  return pRet;\n}\n\n/*\n** If argument pOrig is NULL, or if (*pRc) is set to anything other than\n** SQLITE_OK when this function is called, NULL is returned. \n**\n** Otherwise, a copy of (*pOrig) is made into memory obtained from\n** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation\n** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.\n*/\nstatic Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){\n  Fts5Colset *pRet;\n  if( pOrig ){\n    sqlite3_int64 nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);\n    pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);\n    if( pRet ){ \n      memcpy(pRet, pOrig, (size_t)nByte);\n    }\n  }else{\n    pRet = 0;\n  }\n  return pRet;\n}\n\n/*\n** Remove from colset pColset any columns that are not also in colset pMerge.\n*/\nstatic void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){\n  int iIn = 0;          /* Next input in pColset */\n  int iMerge = 0;       /* Next input in pMerge */\n  int iOut = 0;         /* Next output slot in pColset */\n\n  while( iIn<pColset->nCol && iMerge<pMerge->nCol ){\n    int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];\n    if( iDiff==0 ){\n      pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];\n      iMerge++;\n      iIn++;\n    }else if( iDiff>0 ){\n      iMerge++;\n    }else{\n      iIn++;\n    }\n  }\n  pColset->nCol = iOut;\n}\n\n/*\n** Recursively apply colset pColset to expression node pNode and all of\n** its decendents. If (*ppFree) is not NULL, it contains a spare copy\n** of pColset. This function may use the spare copy and set (*ppFree) to\n** zero, or it may create copies of pColset using fts5CloneColset().\n*/\nstatic void fts5ParseSetColset(\n  Fts5Parse *pParse, \n  Fts5ExprNode *pNode, \n  Fts5Colset *pColset,\n  Fts5Colset **ppFree\n){\n  if( pParse->rc==SQLITE_OK ){\n    assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING \n         || pNode->eType==FTS5_AND  || pNode->eType==FTS5_OR\n         || pNode->eType==FTS5_NOT  || pNode->eType==FTS5_EOF\n    );\n    if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){\n      Fts5ExprNearset *pNear = pNode->pNear;\n      if( pNear->pColset ){\n        fts5MergeColset(pNear->pColset, pColset);\n        if( pNear->pColset->nCol==0 ){\n          pNode->eType = FTS5_EOF;\n          pNode->xNext = 0;\n        }\n      }else if( *ppFree ){\n        pNear->pColset = pColset;\n        *ppFree = 0;\n      }else{\n        pNear->pColset = fts5CloneColset(&pParse->rc, pColset);\n      }\n    }else{\n      int i;\n      assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );\n      for(i=0; i<pNode->nChild; i++){\n        fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);\n      }\n    }\n  }\n}\n\n/*\n** Apply colset pColset to expression node pExpr and all of its descendents.\n*/\nstatic void sqlite3Fts5ParseSetColset(\n  Fts5Parse *pParse, \n  Fts5ExprNode *pExpr, \n  Fts5Colset *pColset \n){\n  Fts5Colset *pFree = pColset;\n  if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){\n    pParse->rc = SQLITE_ERROR;\n    pParse->zErr = sqlite3_mprintf(\n      \"fts5: column queries are not supported (detail=none)\"\n    );\n  }else{\n    fts5ParseSetColset(pParse, pExpr, pColset, &pFree);\n  }\n  sqlite3_free(pFree);\n}\n\nstatic void fts5ExprAssignXNext(Fts5ExprNode *pNode){\n  switch( pNode->eType ){\n    case FTS5_STRING: {\n      Fts5ExprNearset *pNear = pNode->pNear;\n      if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1 \n       && pNear->apPhrase[0]->aTerm[0].pSynonym==0\n       && pNear->apPhrase[0]->aTerm[0].bFirst==0\n      ){\n        pNode->eType = FTS5_TERM;\n        pNode->xNext = fts5ExprNodeNext_TERM;\n      }else{\n        pNode->xNext = fts5ExprNodeNext_STRING;\n      }\n      break;\n    };\n\n    case FTS5_OR: {\n      pNode->xNext = fts5ExprNodeNext_OR;\n      break;\n    };\n\n    case FTS5_AND: {\n      pNode->xNext = fts5ExprNodeNext_AND;\n      break;\n    };\n\n    default: assert( pNode->eType==FTS5_NOT ); {\n      pNode->xNext = fts5ExprNodeNext_NOT;\n      break;\n    };\n  }\n}\n\nstatic void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){\n  if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){\n    int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;\n    memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);\n    p->nChild += pSub->nChild;\n    sqlite3_free(pSub);\n  }else{\n    p->apChild[p->nChild++] = pSub;\n  }\n}\n\n/*\n** Allocate and return a new expression object. If anything goes wrong (i.e.\n** OOM error), leave an error code in pParse and return NULL.\n*/\nstatic Fts5ExprNode *sqlite3Fts5ParseNode(\n  Fts5Parse *pParse,              /* Parse context */\n  int eType,                      /* FTS5_STRING, AND, OR or NOT */\n  Fts5ExprNode *pLeft,            /* Left hand child expression */\n  Fts5ExprNode *pRight,           /* Right hand child expression */\n  Fts5ExprNearset *pNear          /* For STRING expressions, the near cluster */\n){\n  Fts5ExprNode *pRet = 0;\n\n  if( pParse->rc==SQLITE_OK ){\n    int nChild = 0;               /* Number of children of returned node */\n    sqlite3_int64 nByte;          /* Bytes of space to allocate for this node */\n \n    assert( (eType!=FTS5_STRING && !pNear)\n         || (eType==FTS5_STRING && !pLeft && !pRight)\n    );\n    if( eType==FTS5_STRING && pNear==0 ) return 0;\n    if( eType!=FTS5_STRING && pLeft==0 ) return pRight;\n    if( eType!=FTS5_STRING && pRight==0 ) return pLeft;\n\n    if( eType==FTS5_NOT ){\n      nChild = 2;\n    }else if( eType==FTS5_AND || eType==FTS5_OR ){\n      nChild = 2;\n      if( pLeft->eType==eType ) nChild += pLeft->nChild-1;\n      if( pRight->eType==eType ) nChild += pRight->nChild-1;\n    }\n\n    nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);\n    pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);\n\n    if( pRet ){\n      pRet->eType = eType;\n      pRet->pNear = pNear;\n      fts5ExprAssignXNext(pRet);\n      if( eType==FTS5_STRING ){\n        int iPhrase;\n        for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){\n          pNear->apPhrase[iPhrase]->pNode = pRet;\n          if( pNear->apPhrase[iPhrase]->nTerm==0 ){\n            pRet->xNext = 0;\n            pRet->eType = FTS5_EOF;\n          }\n        }\n\n        if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL ){\n          Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];\n          if( pNear->nPhrase!=1 \n           || pPhrase->nTerm>1\n           || (pPhrase->nTerm>0 && pPhrase->aTerm[0].bFirst)\n          ){\n            assert( pParse->rc==SQLITE_OK );\n            pParse->rc = SQLITE_ERROR;\n            assert( pParse->zErr==0 );\n            pParse->zErr = sqlite3_mprintf(\n                \"fts5: %s queries are not supported (detail!=full)\", \n                pNear->nPhrase==1 ? \"phrase\": \"NEAR\"\n                );\n            sqlite3_free(pRet);\n            pRet = 0;\n          }\n        }\n      }else{\n        fts5ExprAddChildren(pRet, pLeft);\n        fts5ExprAddChildren(pRet, pRight);\n      }\n    }\n  }\n\n  if( pRet==0 ){\n    assert( pParse->rc!=SQLITE_OK );\n    sqlite3Fts5ParseNodeFree(pLeft);\n    sqlite3Fts5ParseNodeFree(pRight);\n    sqlite3Fts5ParseNearsetFree(pNear);\n  }\n  return pRet;\n}\n\nstatic Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(\n  Fts5Parse *pParse,              /* Parse context */\n  Fts5ExprNode *pLeft,            /* Left hand child expression */\n  Fts5ExprNode *pRight            /* Right hand child expression */\n){\n  Fts5ExprNode *pRet = 0;\n  Fts5ExprNode *pPrev;\n\n  if( pParse->rc ){\n    sqlite3Fts5ParseNodeFree(pLeft);\n    sqlite3Fts5ParseNodeFree(pRight);\n  }else{\n\n    assert( pLeft->eType==FTS5_STRING \n        || pLeft->eType==FTS5_TERM\n        || pLeft->eType==FTS5_EOF\n        || pLeft->eType==FTS5_AND\n    );\n    assert( pRight->eType==FTS5_STRING \n        || pRight->eType==FTS5_TERM \n        || pRight->eType==FTS5_EOF \n    );\n\n    if( pLeft->eType==FTS5_AND ){\n      pPrev = pLeft->apChild[pLeft->nChild-1];\n    }else{\n      pPrev = pLeft;\n    }\n    assert( pPrev->eType==FTS5_STRING \n        || pPrev->eType==FTS5_TERM \n        || pPrev->eType==FTS5_EOF \n        );\n\n    if( pRight->eType==FTS5_EOF ){\n      assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );\n      sqlite3Fts5ParseNodeFree(pRight);\n      pRet = pLeft;\n      pParse->nPhrase--;\n    }\n    else if( pPrev->eType==FTS5_EOF ){\n      Fts5ExprPhrase **ap;\n\n      if( pPrev==pLeft ){\n        pRet = pRight;\n      }else{\n        pLeft->apChild[pLeft->nChild-1] = pRight;\n        pRet = pLeft;\n      }\n\n      ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];\n      assert( ap[0]==pPrev->pNear->apPhrase[0] );\n      memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);\n      pParse->nPhrase--;\n\n      sqlite3Fts5ParseNodeFree(pPrev);\n    }\n    else{\n      pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);\n    }\n  }\n\n  return pRet;\n}\n\nstatic char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){\n  sqlite3_int64 nByte = 0;\n  Fts5ExprTerm *p;\n  char *zQuoted;\n\n  /* Determine the maximum amount of space required. */\n  for(p=pTerm; p; p=p->pSynonym){\n    nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;\n  }\n  zQuoted = sqlite3_malloc64(nByte);\n\n  if( zQuoted ){\n    int i = 0;\n    for(p=pTerm; p; p=p->pSynonym){\n      char *zIn = p->zTerm;\n      zQuoted[i++] = '\"';\n      while( *zIn ){\n        if( *zIn=='\"' ) zQuoted[i++] = '\"';\n        zQuoted[i++] = *zIn++;\n      }\n      zQuoted[i++] = '\"';\n      if( p->pSynonym ) zQuoted[i++] = '|';\n    }\n    if( pTerm->bPrefix ){\n      zQuoted[i++] = ' ';\n      zQuoted[i++] = '*';\n    }\n    zQuoted[i++] = '\\0';\n  }\n  return zQuoted;\n}\n\nstatic char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){\n  char *zNew;\n  va_list ap;\n  va_start(ap, zFmt);\n  zNew = sqlite3_vmprintf(zFmt, ap);\n  va_end(ap);\n  if( zApp && zNew ){\n    char *zNew2 = sqlite3_mprintf(\"%s%s\", zApp, zNew);\n    sqlite3_free(zNew);\n    zNew = zNew2;\n  }\n  sqlite3_free(zApp);\n  return zNew;\n}\n\n/*\n** Compose a tcl-readable representation of expression pExpr. Return a \n** pointer to a buffer containing that representation. It is the \n** responsibility of the caller to at some point free the buffer using \n** sqlite3_free().\n*/\nstatic char *fts5ExprPrintTcl(\n  Fts5Config *pConfig, \n  const char *zNearsetCmd,\n  Fts5ExprNode *pExpr\n){\n  char *zRet = 0;\n  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){\n    Fts5ExprNearset *pNear = pExpr->pNear;\n    int i; \n    int iTerm;\n\n    zRet = fts5PrintfAppend(zRet, \"%s \", zNearsetCmd);\n    if( zRet==0 ) return 0;\n    if( pNear->pColset ){\n      int *aiCol = pNear->pColset->aiCol;\n      int nCol = pNear->pColset->nCol;\n      if( nCol==1 ){\n        zRet = fts5PrintfAppend(zRet, \"-col %d \", aiCol[0]);\n      }else{\n        zRet = fts5PrintfAppend(zRet, \"-col {%d\", aiCol[0]);\n        for(i=1; i<pNear->pColset->nCol; i++){\n          zRet = fts5PrintfAppend(zRet, \" %d\", aiCol[i]);\n        }\n        zRet = fts5PrintfAppend(zRet, \"} \");\n      }\n      if( zRet==0 ) return 0;\n    }\n\n    if( pNear->nPhrase>1 ){\n      zRet = fts5PrintfAppend(zRet, \"-near %d \", pNear->nNear);\n      if( zRet==0 ) return 0;\n    }\n\n    zRet = fts5PrintfAppend(zRet, \"--\");\n    if( zRet==0 ) return 0;\n\n    for(i=0; i<pNear->nPhrase; i++){\n      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];\n\n      zRet = fts5PrintfAppend(zRet, \" {\");\n      for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){\n        char *zTerm = pPhrase->aTerm[iTerm].zTerm;\n        zRet = fts5PrintfAppend(zRet, \"%s%s\", iTerm==0?\"\":\" \", zTerm);\n        if( pPhrase->aTerm[iTerm].bPrefix ){\n          zRet = fts5PrintfAppend(zRet, \"*\");\n        }\n      }\n\n      if( zRet ) zRet = fts5PrintfAppend(zRet, \"}\");\n      if( zRet==0 ) return 0;\n    }\n\n  }else{\n    char const *zOp = 0;\n    int i;\n    switch( pExpr->eType ){\n      case FTS5_AND: zOp = \"AND\"; break;\n      case FTS5_NOT: zOp = \"NOT\"; break;\n      default: \n        assert( pExpr->eType==FTS5_OR );\n        zOp = \"OR\"; \n        break;\n    }\n\n    zRet = sqlite3_mprintf(\"%s\", zOp);\n    for(i=0; zRet && i<pExpr->nChild; i++){\n      char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);\n      if( !z ){\n        sqlite3_free(zRet);\n        zRet = 0;\n      }else{\n        zRet = fts5PrintfAppend(zRet, \" [%z]\", z);\n      }\n    }\n  }\n\n  return zRet;\n}\n\nstatic char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){\n  char *zRet = 0;\n  if( pExpr->eType==0 ){\n    return sqlite3_mprintf(\"\\\"\\\"\");\n  }else\n  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){\n    Fts5ExprNearset *pNear = pExpr->pNear;\n    int i; \n    int iTerm;\n\n    if( pNear->pColset ){\n      int iCol = pNear->pColset->aiCol[0];\n      zRet = fts5PrintfAppend(zRet, \"%s : \", pConfig->azCol[iCol]);\n      if( zRet==0 ) return 0;\n    }\n\n    if( pNear->nPhrase>1 ){\n      zRet = fts5PrintfAppend(zRet, \"NEAR(\");\n      if( zRet==0 ) return 0;\n    }\n\n    for(i=0; i<pNear->nPhrase; i++){\n      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];\n      if( i!=0 ){\n        zRet = fts5PrintfAppend(zRet, \" \");\n        if( zRet==0 ) return 0;\n      }\n      for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){\n        char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);\n        if( zTerm ){\n          zRet = fts5PrintfAppend(zRet, \"%s%s\", iTerm==0?\"\":\" + \", zTerm);\n          sqlite3_free(zTerm);\n        }\n        if( zTerm==0 || zRet==0 ){\n          sqlite3_free(zRet);\n          return 0;\n        }\n      }\n    }\n\n    if( pNear->nPhrase>1 ){\n      zRet = fts5PrintfAppend(zRet, \", %d)\", pNear->nNear);\n      if( zRet==0 ) return 0;\n    }\n\n  }else{\n    char const *zOp = 0;\n    int i;\n\n    switch( pExpr->eType ){\n      case FTS5_AND: zOp = \" AND \"; break;\n      case FTS5_NOT: zOp = \" NOT \"; break;\n      default:  \n        assert( pExpr->eType==FTS5_OR );\n        zOp = \" OR \"; \n        break;\n    }\n\n    for(i=0; i<pExpr->nChild; i++){\n      char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);\n      if( z==0 ){\n        sqlite3_free(zRet);\n        zRet = 0;\n      }else{\n        int e = pExpr->apChild[i]->eType;\n        int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);\n        zRet = fts5PrintfAppend(zRet, \"%s%s%z%s\", \n            (i==0 ? \"\" : zOp),\n            (b?\"(\":\"\"), z, (b?\")\":\"\")\n        );\n      }\n      if( zRet==0 ) break;\n    }\n  }\n\n  return zRet;\n}\n\n/*\n** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)\n** and fts5_expr_tcl() (bTcl!=0).\n*/\nstatic void fts5ExprFunction(\n  sqlite3_context *pCtx,          /* Function call context */\n  int nArg,                       /* Number of args */\n  sqlite3_value **apVal,          /* Function arguments */\n  int bTcl\n){\n  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);\n  sqlite3 *db = sqlite3_context_db_handle(pCtx);\n  const char *zExpr = 0;\n  char *zErr = 0;\n  Fts5Expr *pExpr = 0;\n  int rc;\n  int i;\n\n  const char **azConfig;          /* Array of arguments for Fts5Config */\n  const char *zNearsetCmd = \"nearset\";\n  int nConfig;                    /* Size of azConfig[] */\n  Fts5Config *pConfig = 0;\n  int iArg = 1;\n\n  if( nArg<1 ){\n    zErr = sqlite3_mprintf(\"wrong number of arguments to function %s\",\n        bTcl ? \"fts5_expr_tcl\" : \"fts5_expr\"\n    );\n    sqlite3_result_error(pCtx, zErr, -1);\n    sqlite3_free(zErr);\n    return;\n  }\n\n  if( bTcl && nArg>1 ){\n    zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);\n    iArg = 2;\n  }\n\n  nConfig = 3 + (nArg-iArg);\n  azConfig = (const char**)sqlite3_malloc64(sizeof(char*) * nConfig);\n  if( azConfig==0 ){\n    sqlite3_result_error_nomem(pCtx);\n    return;\n  }\n  azConfig[0] = 0;\n  azConfig[1] = \"main\";\n  azConfig[2] = \"tbl\";\n  for(i=3; iArg<nArg; iArg++){\n    const char *z = (const char*)sqlite3_value_text(apVal[iArg]);\n    azConfig[i++] = (z ? z : \"\");\n  }\n\n  zExpr = (const char*)sqlite3_value_text(apVal[0]);\n  if( zExpr==0 ) zExpr = \"\";\n\n  rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);\n  }\n  if( rc==SQLITE_OK ){\n    char *zText;\n    if( pExpr->pRoot->xNext==0 ){\n      zText = sqlite3_mprintf(\"\");\n    }else if( bTcl ){\n      zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);\n    }else{\n      zText = fts5ExprPrint(pConfig, pExpr->pRoot);\n    }\n    if( zText==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);\n      sqlite3_free(zText);\n    }\n  }\n\n  if( rc!=SQLITE_OK ){\n    if( zErr ){\n      sqlite3_result_error(pCtx, zErr, -1);\n      sqlite3_free(zErr);\n    }else{\n      sqlite3_result_error_code(pCtx, rc);\n    }\n  }\n  sqlite3_free((void *)azConfig);\n  sqlite3Fts5ConfigFree(pConfig);\n  sqlite3Fts5ExprFree(pExpr);\n}\n\nstatic void fts5ExprFunctionHr(\n  sqlite3_context *pCtx,          /* Function call context */\n  int nArg,                       /* Number of args */\n  sqlite3_value **apVal           /* Function arguments */\n){\n  fts5ExprFunction(pCtx, nArg, apVal, 0);\n}\nstatic void fts5ExprFunctionTcl(\n  sqlite3_context *pCtx,          /* Function call context */\n  int nArg,                       /* Number of args */\n  sqlite3_value **apVal           /* Function arguments */\n){\n  fts5ExprFunction(pCtx, nArg, apVal, 1);\n}\n\n/*\n** The implementation of an SQLite user-defined-function that accepts a\n** single integer as an argument. If the integer is an alpha-numeric \n** unicode code point, 1 is returned. Otherwise 0.\n*/\nstatic void fts5ExprIsAlnum(\n  sqlite3_context *pCtx,          /* Function call context */\n  int nArg,                       /* Number of args */\n  sqlite3_value **apVal           /* Function arguments */\n){\n  int iCode;\n  u8 aArr[32];\n  if( nArg!=1 ){\n    sqlite3_result_error(pCtx, \n        \"wrong number of arguments to function fts5_isalnum\", -1\n    );\n    return;\n  }\n  memset(aArr, 0, sizeof(aArr));\n  sqlite3Fts5UnicodeCatParse(\"L*\", aArr);\n  sqlite3Fts5UnicodeCatParse(\"N*\", aArr);\n  sqlite3Fts5UnicodeCatParse(\"Co\", aArr);\n  iCode = sqlite3_value_int(apVal[0]);\n  sqlite3_result_int(pCtx, aArr[sqlite3Fts5UnicodeCategory((u32)iCode)]);\n}\n\nstatic void fts5ExprFold(\n  sqlite3_context *pCtx,          /* Function call context */\n  int nArg,                       /* Number of args */\n  sqlite3_value **apVal           /* Function arguments */\n){\n  if( nArg!=1 && nArg!=2 ){\n    sqlite3_result_error(pCtx, \n        \"wrong number of arguments to function fts5_fold\", -1\n    );\n  }else{\n    int iCode;\n    int bRemoveDiacritics = 0;\n    iCode = sqlite3_value_int(apVal[0]);\n    if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);\n    sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));\n  }\n}\n\n/*\n** This is called during initialization to register the fts5_expr() scalar\n** UDF with the SQLite handle passed as the only argument.\n*/\nstatic int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){\n  struct Fts5ExprFunc {\n    const char *z;\n    void (*x)(sqlite3_context*,int,sqlite3_value**);\n  } aFunc[] = {\n    { \"fts5_expr\",     fts5ExprFunctionHr },\n    { \"fts5_expr_tcl\", fts5ExprFunctionTcl },\n    { \"fts5_isalnum\",  fts5ExprIsAlnum },\n    { \"fts5_fold\",     fts5ExprFold },\n  };\n  int i;\n  int rc = SQLITE_OK;\n  void *pCtx = (void*)pGlobal;\n\n  for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){\n    struct Fts5ExprFunc *p = &aFunc[i];\n    rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);\n  }\n\n  /* Avoid warnings indicating that sqlite3Fts5ParserTrace() and\n  ** sqlite3Fts5ParserFallback() are unused */\n#ifndef NDEBUG\n  (void)sqlite3Fts5ParserTrace;\n#endif\n  (void)sqlite3Fts5ParserFallback;\n\n  return rc;\n}\n\n/*\n** Return the number of phrases in expression pExpr.\n*/\nstatic int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){\n  return (pExpr ? pExpr->nPhrase : 0);\n}\n\n/*\n** Return the number of terms in the iPhrase'th phrase in pExpr.\n*/\nstatic int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){\n  if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;\n  return pExpr->apExprPhrase[iPhrase]->nTerm;\n}\n\n/*\n** This function is used to access the current position list for phrase\n** iPhrase.\n*/\nstatic int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){\n  int nRet;\n  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];\n  Fts5ExprNode *pNode = pPhrase->pNode;\n  if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){\n    *pa = pPhrase->poslist.p;\n    nRet = pPhrase->poslist.n;\n  }else{\n    *pa = 0;\n    nRet = 0;\n  }\n  return nRet;\n}\n\nstruct Fts5PoslistPopulator {\n  Fts5PoslistWriter writer;\n  int bOk;                        /* True if ok to populate */\n  int bMiss;\n};\n\nstatic Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){\n  Fts5PoslistPopulator *pRet;\n  pRet = sqlite3_malloc64(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);\n  if( pRet ){\n    int i;\n    memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);\n    for(i=0; i<pExpr->nPhrase; i++){\n      Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;\n      Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;\n      assert( pExpr->apExprPhrase[i]->nTerm==1 );\n      if( bLive && \n          (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)\n      ){\n        pRet[i].bMiss = 1;\n      }else{\n        pBuf->n = 0;\n      }\n    }\n  }\n  return pRet;\n}\n\nstruct Fts5ExprCtx {\n  Fts5Expr *pExpr;\n  Fts5PoslistPopulator *aPopulator;\n  i64 iOff;\n};\ntypedef struct Fts5ExprCtx Fts5ExprCtx;\n\n/*\n** TODO: Make this more efficient!\n*/\nstatic int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){\n  int i;\n  for(i=0; i<pColset->nCol; i++){\n    if( pColset->aiCol[i]==iCol ) return 1;\n  }\n  return 0;\n}\n\nstatic int fts5ExprPopulatePoslistsCb(\n  void *pCtx,                /* Copy of 2nd argument to xTokenize() */\n  int tflags,                /* Mask of FTS5_TOKEN_* flags */\n  const char *pToken,        /* Pointer to buffer containing token */\n  int nToken,                /* Size of token in bytes */\n  int iUnused1,              /* Byte offset of token within input text */\n  int iUnused2               /* Byte offset of end of token within input text */\n){\n  Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;\n  Fts5Expr *pExpr = p->pExpr;\n  int i;\n\n  UNUSED_PARAM2(iUnused1, iUnused2);\n\n  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;\n  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;\n  for(i=0; i<pExpr->nPhrase; i++){\n    Fts5ExprTerm *pTerm;\n    if( p->aPopulator[i].bOk==0 ) continue;\n    for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){\n      int nTerm = (int)strlen(pTerm->zTerm);\n      if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))\n       && memcmp(pTerm->zTerm, pToken, nTerm)==0\n      ){\n        int rc = sqlite3Fts5PoslistWriterAppend(\n            &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff\n        );\n        if( rc ) return rc;\n        break;\n      }\n    }\n  }\n  return SQLITE_OK;\n}\n\nstatic int sqlite3Fts5ExprPopulatePoslists(\n  Fts5Config *pConfig,\n  Fts5Expr *pExpr, \n  Fts5PoslistPopulator *aPopulator,\n  int iCol, \n  const char *z, int n\n){\n  int i;\n  Fts5ExprCtx sCtx;\n  sCtx.pExpr = pExpr;\n  sCtx.aPopulator = aPopulator;\n  sCtx.iOff = (((i64)iCol) << 32) - 1;\n\n  for(i=0; i<pExpr->nPhrase; i++){\n    Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;\n    Fts5Colset *pColset = pNode->pNear->pColset;\n    if( (pColset && 0==fts5ExprColsetTest(pColset, iCol)) \n     || aPopulator[i].bMiss\n    ){\n      aPopulator[i].bOk = 0;\n    }else{\n      aPopulator[i].bOk = 1;\n    }\n  }\n\n  return sqlite3Fts5Tokenize(pConfig, \n      FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb\n  );\n}\n\nstatic void fts5ExprClearPoslists(Fts5ExprNode *pNode){\n  if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){\n    pNode->pNear->apPhrase[0]->poslist.n = 0;\n  }else{\n    int i;\n    for(i=0; i<pNode->nChild; i++){\n      fts5ExprClearPoslists(pNode->apChild[i]);\n    }\n  }\n}\n\nstatic int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){\n  pNode->iRowid = iRowid;\n  pNode->bEof = 0;\n  switch( pNode->eType ){\n    case FTS5_TERM:\n    case FTS5_STRING:\n      return (pNode->pNear->apPhrase[0]->poslist.n>0);\n\n    case FTS5_AND: {\n      int i;\n      for(i=0; i<pNode->nChild; i++){\n        if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){\n          fts5ExprClearPoslists(pNode);\n          return 0;\n        }\n      }\n      break;\n    }\n\n    case FTS5_OR: {\n      int i;\n      int bRet = 0;\n      for(i=0; i<pNode->nChild; i++){\n        if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){\n          bRet = 1;\n        }\n      }\n      return bRet;\n    }\n\n    default: {\n      assert( pNode->eType==FTS5_NOT );\n      if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)\n          || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)\n        ){\n        fts5ExprClearPoslists(pNode);\n        return 0;\n      }\n      break;\n    }\n  }\n  return 1;\n}\n\nstatic void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){\n  fts5ExprCheckPoslists(pExpr->pRoot, iRowid);\n}\n\n/*\n** This function is only called for detail=columns tables. \n*/\nstatic int sqlite3Fts5ExprPhraseCollist(\n  Fts5Expr *pExpr, \n  int iPhrase, \n  const u8 **ppCollist, \n  int *pnCollist\n){\n  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];\n  Fts5ExprNode *pNode = pPhrase->pNode;\n  int rc = SQLITE_OK;\n\n  assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );\n  assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );\n\n  if( pNode->bEof==0 \n   && pNode->iRowid==pExpr->pRoot->iRowid \n   && pPhrase->poslist.n>0\n  ){\n    Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];\n    if( pTerm->pSynonym ){\n      Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];\n      rc = fts5ExprSynonymList(\n          pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist\n      );\n    }else{\n      *ppCollist = pPhrase->aTerm[0].pIter->pData;\n      *pnCollist = pPhrase->aTerm[0].pIter->nData;\n    }\n  }else{\n    *ppCollist = 0;\n    *pnCollist = 0;\n  }\n\n  return rc;\n}\n\n/*\n** 2014 August 11\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n*/\n\n\n\n/* #include \"fts5Int.h\" */\n\ntypedef struct Fts5HashEntry Fts5HashEntry;\n\n/*\n** This file contains the implementation of an in-memory hash table used\n** to accumuluate \"term -> doclist\" content before it is flused to a level-0\n** segment.\n*/\n\n\nstruct Fts5Hash {\n  int eDetail;                    /* Copy of Fts5Config.eDetail */\n  int *pnByte;                    /* Pointer to bytes counter */\n  int nEntry;                     /* Number of entries currently in hash */\n  int nSlot;                      /* Size of aSlot[] array */\n  Fts5HashEntry *pScan;           /* Current ordered scan item */\n  Fts5HashEntry **aSlot;          /* Array of hash slots */\n};\n\n/*\n** Each entry in the hash table is represented by an object of the \n** following type. Each object, its key (a nul-terminated string) and \n** its current data are stored in a single memory allocation. The \n** key immediately follows the object in memory. The position list\n** data immediately follows the key data in memory.\n**\n** The data that follows the key is in a similar, but not identical format\n** to the doclist data stored in the database. It is:\n**\n**   * Rowid, as a varint\n**   * Position list, without 0x00 terminator.\n**   * Size of previous position list and rowid, as a 4 byte\n**     big-endian integer.\n**\n** iRowidOff:\n**   Offset of last rowid written to data area. Relative to first byte of\n**   structure.\n**\n** nData:\n**   Bytes of data written since iRowidOff.\n*/\nstruct Fts5HashEntry {\n  Fts5HashEntry *pHashNext;       /* Next hash entry with same hash-key */\n  Fts5HashEntry *pScanNext;       /* Next entry in sorted order */\n  \n  int nAlloc;                     /* Total size of allocation */\n  int iSzPoslist;                 /* Offset of space for 4-byte poslist size */\n  int nData;                      /* Total bytes of data (incl. structure) */\n  int nKey;                       /* Length of key in bytes */\n  u8 bDel;                        /* Set delete-flag @ iSzPoslist */\n  u8 bContent;                    /* Set content-flag (detail=none mode) */\n  i16 iCol;                       /* Column of last value written */\n  int iPos;                       /* Position of last value written */\n  i64 iRowid;                     /* Rowid of last value written */\n};\n\n/*\n** Eqivalent to:\n**\n**   char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }\n*/\n#define fts5EntryKey(p) ( ((char *)(&(p)[1])) )\n\n\n/*\n** Allocate a new hash table.\n*/\nstatic int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){\n  int rc = SQLITE_OK;\n  Fts5Hash *pNew;\n\n  *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));\n  if( pNew==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    sqlite3_int64 nByte;\n    memset(pNew, 0, sizeof(Fts5Hash));\n    pNew->pnByte = pnByte;\n    pNew->eDetail = pConfig->eDetail;\n\n    pNew->nSlot = 1024;\n    nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;\n    pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc64(nByte);\n    if( pNew->aSlot==0 ){\n      sqlite3_free(pNew);\n      *ppNew = 0;\n      rc = SQLITE_NOMEM;\n    }else{\n      memset(pNew->aSlot, 0, (size_t)nByte);\n    }\n  }\n  return rc;\n}\n\n/*\n** Free a hash table object.\n*/\nstatic void sqlite3Fts5HashFree(Fts5Hash *pHash){\n  if( pHash ){\n    sqlite3Fts5HashClear(pHash);\n    sqlite3_free(pHash->aSlot);\n    sqlite3_free(pHash);\n  }\n}\n\n/*\n** Empty (but do not delete) a hash table.\n*/\nstatic void sqlite3Fts5HashClear(Fts5Hash *pHash){\n  int i;\n  for(i=0; i<pHash->nSlot; i++){\n    Fts5HashEntry *pNext;\n    Fts5HashEntry *pSlot;\n    for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){\n      pNext = pSlot->pHashNext;\n      sqlite3_free(pSlot);\n    }\n  }\n  memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));\n  pHash->nEntry = 0;\n}\n\nstatic unsigned int fts5HashKey(int nSlot, const u8 *p, int n){\n  int i;\n  unsigned int h = 13;\n  for(i=n-1; i>=0; i--){\n    h = (h << 3) ^ h ^ p[i];\n  }\n  return (h % nSlot);\n}\n\nstatic unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){\n  int i;\n  unsigned int h = 13;\n  for(i=n-1; i>=0; i--){\n    h = (h << 3) ^ h ^ p[i];\n  }\n  h = (h << 3) ^ h ^ b;\n  return (h % nSlot);\n}\n\n/*\n** Resize the hash table by doubling the number of slots.\n*/\nstatic int fts5HashResize(Fts5Hash *pHash){\n  int nNew = pHash->nSlot*2;\n  int i;\n  Fts5HashEntry **apNew;\n  Fts5HashEntry **apOld = pHash->aSlot;\n\n  apNew = (Fts5HashEntry**)sqlite3_malloc64(nNew*sizeof(Fts5HashEntry*));\n  if( !apNew ) return SQLITE_NOMEM;\n  memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));\n\n  for(i=0; i<pHash->nSlot; i++){\n    while( apOld[i] ){\n      unsigned int iHash;\n      Fts5HashEntry *p = apOld[i];\n      apOld[i] = p->pHashNext;\n      iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p),\n                          (int)strlen(fts5EntryKey(p)));\n      p->pHashNext = apNew[iHash];\n      apNew[iHash] = p;\n    }\n  }\n\n  sqlite3_free(apOld);\n  pHash->nSlot = nNew;\n  pHash->aSlot = apNew;\n  return SQLITE_OK;\n}\n\nstatic int fts5HashAddPoslistSize(\n  Fts5Hash *pHash, \n  Fts5HashEntry *p,\n  Fts5HashEntry *p2\n){\n  int nRet = 0;\n  if( p->iSzPoslist ){\n    u8 *pPtr = p2 ? (u8*)p2 : (u8*)p;\n    int nData = p->nData;\n    if( pHash->eDetail==FTS5_DETAIL_NONE ){\n      assert( nData==p->iSzPoslist );\n      if( p->bDel ){\n        pPtr[nData++] = 0x00;\n        if( p->bContent ){\n          pPtr[nData++] = 0x00;\n        }\n      }\n    }else{\n      int nSz = (nData - p->iSzPoslist - 1);       /* Size in bytes */\n      int nPos = nSz*2 + p->bDel;                     /* Value of nPos field */\n\n      assert( p->bDel==0 || p->bDel==1 );\n      if( nPos<=127 ){\n        pPtr[p->iSzPoslist] = (u8)nPos;\n      }else{\n        int nByte = sqlite3Fts5GetVarintLen((u32)nPos);\n        memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);\n        sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);\n        nData += (nByte-1);\n      }\n    }\n\n    nRet = nData - p->nData;\n    if( p2==0 ){\n      p->iSzPoslist = 0;\n      p->bDel = 0;\n      p->bContent = 0;\n      p->nData = nData;\n    }\n  }\n  return nRet;\n}\n\n/*\n** Add an entry to the in-memory hash table. The key is the concatenation\n** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).\n**\n**     (bByte || pToken) -> (iRowid,iCol,iPos)\n**\n** Or, if iCol is negative, then the value is a delete marker.\n*/\nstatic int sqlite3Fts5HashWrite(\n  Fts5Hash *pHash,\n  i64 iRowid,                     /* Rowid for this entry */\n  int iCol,                       /* Column token appears in (-ve -> delete) */\n  int iPos,                       /* Position of token within column */\n  char bByte,                     /* First byte of token */\n  const char *pToken, int nToken  /* Token to add or remove to or from index */\n){\n  unsigned int iHash;\n  Fts5HashEntry *p;\n  u8 *pPtr;\n  int nIncr = 0;                  /* Amount to increment (*pHash->pnByte) by */\n  int bNew;                       /* If non-delete entry should be written */\n  \n  bNew = (pHash->eDetail==FTS5_DETAIL_FULL);\n\n  /* Attempt to locate an existing hash entry */\n  iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);\n  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){\n    char *zKey = fts5EntryKey(p);\n    if( zKey[0]==bByte \n     && p->nKey==nToken\n     && memcmp(&zKey[1], pToken, nToken)==0 \n    ){\n      break;\n    }\n  }\n\n  /* If an existing hash entry cannot be found, create a new one. */\n  if( p==0 ){\n    /* Figure out how much space to allocate */\n    char *zKey;\n    sqlite3_int64 nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;\n    if( nByte<128 ) nByte = 128;\n\n    /* Grow the Fts5Hash.aSlot[] array if necessary. */\n    if( (pHash->nEntry*2)>=pHash->nSlot ){\n      int rc = fts5HashResize(pHash);\n      if( rc!=SQLITE_OK ) return rc;\n      iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);\n    }\n\n    /* Allocate new Fts5HashEntry and add it to the hash table. */\n    p = (Fts5HashEntry*)sqlite3_malloc64(nByte);\n    if( !p ) return SQLITE_NOMEM;\n    memset(p, 0, sizeof(Fts5HashEntry));\n    p->nAlloc = (int)nByte;\n    zKey = fts5EntryKey(p);\n    zKey[0] = bByte;\n    memcpy(&zKey[1], pToken, nToken);\n    assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );\n    p->nKey = nToken;\n    zKey[nToken+1] = '\\0';\n    p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry);\n    p->pHashNext = pHash->aSlot[iHash];\n    pHash->aSlot[iHash] = p;\n    pHash->nEntry++;\n\n    /* Add the first rowid field to the hash-entry */\n    p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);\n    p->iRowid = iRowid;\n\n    p->iSzPoslist = p->nData;\n    if( pHash->eDetail!=FTS5_DETAIL_NONE ){\n      p->nData += 1;\n      p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);\n    }\n\n    nIncr += p->nData;\n  }else{\n\n    /* Appending to an existing hash-entry. Check that there is enough \n    ** space to append the largest possible new entry. Worst case scenario \n    ** is:\n    **\n    **     + 9 bytes for a new rowid,\n    **     + 4 byte reserved for the \"poslist size\" varint.\n    **     + 1 byte for a \"new column\" byte,\n    **     + 3 bytes for a new column number (16-bit max) as a varint,\n    **     + 5 bytes for the new position offset (32-bit max).\n    */\n    if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){\n      sqlite3_int64 nNew = p->nAlloc * 2;\n      Fts5HashEntry *pNew;\n      Fts5HashEntry **pp;\n      pNew = (Fts5HashEntry*)sqlite3_realloc64(p, nNew);\n      if( pNew==0 ) return SQLITE_NOMEM;\n      pNew->nAlloc = (int)nNew;\n      for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);\n      *pp = pNew;\n      p = pNew;\n    }\n    nIncr -= p->nData;\n  }\n  assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );\n\n  pPtr = (u8*)p;\n\n  /* If this is a new rowid, append the 4-byte size field for the previous\n  ** entry, and the new rowid for this entry.  */\n  if( iRowid!=p->iRowid ){\n    fts5HashAddPoslistSize(pHash, p, 0);\n    p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);\n    p->iRowid = iRowid;\n    bNew = 1;\n    p->iSzPoslist = p->nData;\n    if( pHash->eDetail!=FTS5_DETAIL_NONE ){\n      p->nData += 1;\n      p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);\n      p->iPos = 0;\n    }\n  }\n\n  if( iCol>=0 ){\n    if( pHash->eDetail==FTS5_DETAIL_NONE ){\n      p->bContent = 1;\n    }else{\n      /* Append a new column value, if necessary */\n      assert( iCol>=p->iCol );\n      if( iCol!=p->iCol ){\n        if( pHash->eDetail==FTS5_DETAIL_FULL ){\n          pPtr[p->nData++] = 0x01;\n          p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);\n          p->iCol = (i16)iCol;\n          p->iPos = 0;\n        }else{\n          bNew = 1;\n          p->iCol = (i16)(iPos = iCol);\n        }\n      }\n\n      /* Append the new position offset, if necessary */\n      if( bNew ){\n        p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);\n        p->iPos = iPos;\n      }\n    }\n  }else{\n    /* This is a delete. Set the delete flag. */\n    p->bDel = 1;\n  }\n\n  nIncr += p->nData;\n  *pHash->pnByte += nIncr;\n  return SQLITE_OK;\n}\n\n\n/*\n** Arguments pLeft and pRight point to linked-lists of hash-entry objects,\n** each sorted in key order. This function merges the two lists into a\n** single list and returns a pointer to its first element.\n*/\nstatic Fts5HashEntry *fts5HashEntryMerge(\n  Fts5HashEntry *pLeft,\n  Fts5HashEntry *pRight\n){\n  Fts5HashEntry *p1 = pLeft;\n  Fts5HashEntry *p2 = pRight;\n  Fts5HashEntry *pRet = 0;\n  Fts5HashEntry **ppOut = &pRet;\n\n  while( p1 || p2 ){\n    if( p1==0 ){\n      *ppOut = p2;\n      p2 = 0;\n    }else if( p2==0 ){\n      *ppOut = p1;\n      p1 = 0;\n    }else{\n      int i = 0;\n      char *zKey1 = fts5EntryKey(p1);\n      char *zKey2 = fts5EntryKey(p2);\n      while( zKey1[i]==zKey2[i] ) i++;\n\n      if( ((u8)zKey1[i])>((u8)zKey2[i]) ){\n        /* p2 is smaller */\n        *ppOut = p2;\n        ppOut = &p2->pScanNext;\n        p2 = p2->pScanNext;\n      }else{\n        /* p1 is smaller */\n        *ppOut = p1;\n        ppOut = &p1->pScanNext;\n        p1 = p1->pScanNext;\n      }\n      *ppOut = 0;\n    }\n  }\n\n  return pRet;\n}\n\n/*\n** Extract all tokens from hash table iHash and link them into a list\n** in sorted order. The hash table is cleared before returning. It is\n** the responsibility of the caller to free the elements of the returned\n** list.\n*/\nstatic int fts5HashEntrySort(\n  Fts5Hash *pHash, \n  const char *pTerm, int nTerm,   /* Query prefix, if any */\n  Fts5HashEntry **ppSorted\n){\n  const int nMergeSlot = 32;\n  Fts5HashEntry **ap;\n  Fts5HashEntry *pList;\n  int iSlot;\n  int i;\n\n  *ppSorted = 0;\n  ap = sqlite3_malloc64(sizeof(Fts5HashEntry*) * nMergeSlot);\n  if( !ap ) return SQLITE_NOMEM;\n  memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);\n\n  for(iSlot=0; iSlot<pHash->nSlot; iSlot++){\n    Fts5HashEntry *pIter;\n    for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){\n      if( pTerm==0 \n       || (pIter->nKey+1>=nTerm && 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm))\n      ){\n        Fts5HashEntry *pEntry = pIter;\n        pEntry->pScanNext = 0;\n        for(i=0; ap[i]; i++){\n          pEntry = fts5HashEntryMerge(pEntry, ap[i]);\n          ap[i] = 0;\n        }\n        ap[i] = pEntry;\n      }\n    }\n  }\n\n  pList = 0;\n  for(i=0; i<nMergeSlot; i++){\n    pList = fts5HashEntryMerge(pList, ap[i]);\n  }\n\n  pHash->nEntry = 0;\n  sqlite3_free(ap);\n  *ppSorted = pList;\n  return SQLITE_OK;\n}\n\n/*\n** Query the hash table for a doclist associated with term pTerm/nTerm.\n*/\nstatic int sqlite3Fts5HashQuery(\n  Fts5Hash *pHash,                /* Hash table to query */\n  int nPre,\n  const char *pTerm, int nTerm,   /* Query term */\n  void **ppOut,                   /* OUT: Pointer to new object */\n  int *pnDoclist                  /* OUT: Size of doclist in bytes */\n){\n  unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);\n  char *zKey = 0;\n  Fts5HashEntry *p;\n\n  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){\n    zKey = fts5EntryKey(p);\n    assert( p->nKey+1==(int)strlen(zKey) );\n    if( nTerm==p->nKey+1 && memcmp(zKey, pTerm, nTerm)==0 ) break;\n  }\n\n  if( p ){\n    int nHashPre = sizeof(Fts5HashEntry) + nTerm + 1;\n    int nList = p->nData - nHashPre;\n    u8 *pRet = (u8*)(*ppOut = sqlite3_malloc64(nPre + nList + 10));\n    if( pRet ){\n      Fts5HashEntry *pFaux = (Fts5HashEntry*)&pRet[nPre-nHashPre];\n      memcpy(&pRet[nPre], &((u8*)p)[nHashPre], nList);\n      nList += fts5HashAddPoslistSize(pHash, p, pFaux);\n      *pnDoclist = nList;\n    }else{\n      *pnDoclist = 0;\n      return SQLITE_NOMEM;\n    }\n  }else{\n    *ppOut = 0;\n    *pnDoclist = 0;\n  }\n\n  return SQLITE_OK;\n}\n\nstatic int sqlite3Fts5HashScanInit(\n  Fts5Hash *p,                    /* Hash table to query */\n  const char *pTerm, int nTerm    /* Query prefix */\n){\n  return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);\n}\n\nstatic void sqlite3Fts5HashScanNext(Fts5Hash *p){\n  assert( !sqlite3Fts5HashScanEof(p) );\n  p->pScan = p->pScan->pScanNext;\n}\n\nstatic int sqlite3Fts5HashScanEof(Fts5Hash *p){\n  return (p->pScan==0);\n}\n\nstatic void sqlite3Fts5HashScanEntry(\n  Fts5Hash *pHash,\n  const char **pzTerm,            /* OUT: term (nul-terminated) */\n  const u8 **ppDoclist,           /* OUT: pointer to doclist */\n  int *pnDoclist                  /* OUT: size of doclist in bytes */\n){\n  Fts5HashEntry *p;\n  if( (p = pHash->pScan) ){\n    char *zKey = fts5EntryKey(p);\n    int nTerm = (int)strlen(zKey);\n    fts5HashAddPoslistSize(pHash, p, 0);\n    *pzTerm = zKey;\n    *ppDoclist = (const u8*)&zKey[nTerm+1];\n    *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);\n  }else{\n    *pzTerm = 0;\n    *ppDoclist = 0;\n    *pnDoclist = 0;\n  }\n}\n\n/*\n** 2014 May 31\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** Low level access to the FTS index stored in the database file. The \n** routines in this file file implement all read and write access to the\n** %_data table. Other parts of the system access this functionality via\n** the interface defined in fts5Int.h.\n*/\n\n\n/* #include \"fts5Int.h\" */\n\n/*\n** Overview:\n**\n** The %_data table contains all the FTS indexes for an FTS5 virtual table.\n** As well as the main term index, there may be up to 31 prefix indexes.\n** The format is similar to FTS3/4, except that:\n**\n**   * all segment b-tree leaf data is stored in fixed size page records \n**     (e.g. 1000 bytes). A single doclist may span multiple pages. Care is \n**     taken to ensure it is possible to iterate in either direction through \n**     the entries in a doclist, or to seek to a specific entry within a \n**     doclist, without loading it into memory.\n**\n**   * large doclists that span many pages have associated \"doclist index\"\n**     records that contain a copy of the first rowid on each page spanned by\n**     the doclist. This is used to speed up seek operations, and merges of\n**     large doclists with very small doclists.\n**\n**   * extra fields in the \"structure record\" record the state of ongoing\n**     incremental merge operations.\n**\n*/\n\n\n#define FTS5_OPT_WORK_UNIT  1000  /* Number of leaf pages per optimize step */\n#define FTS5_WORK_UNIT      64    /* Number of leaf pages in unit of work */\n\n#define FTS5_MIN_DLIDX_SIZE 4     /* Add dlidx if this many empty pages */\n\n#define FTS5_MAIN_PREFIX '0'\n\n#if FTS5_MAX_PREFIX_INDEXES > 31\n# error \"FTS5_MAX_PREFIX_INDEXES is too large\"\n#endif\n\n/*\n** Details:\n**\n** The %_data table managed by this module,\n**\n**     CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);\n**\n** , contains the following 5 types of records. See the comments surrounding\n** the FTS5_*_ROWID macros below for a description of how %_data rowids are \n** assigned to each fo them.\n**\n** 1. Structure Records:\n**\n**   The set of segments that make up an index - the index structure - are\n**   recorded in a single record within the %_data table. The record consists\n**   of a single 32-bit configuration cookie value followed by a list of \n**   SQLite varints. If the FTS table features more than one index (because\n**   there are one or more prefix indexes), it is guaranteed that all share\n**   the same cookie value.\n**\n**   Immediately following the configuration cookie, the record begins with\n**   three varints:\n**\n**     + number of levels,\n**     + total number of segments on all levels,\n**     + value of write counter.\n**\n**   Then, for each level from 0 to nMax:\n**\n**     + number of input segments in ongoing merge.\n**     + total number of segments in level.\n**     + for each segment from oldest to newest:\n**         + segment id (always > 0)\n**         + first leaf page number (often 1, always greater than 0)\n**         + final leaf page number\n**\n** 2. The Averages Record:\n**\n**   A single record within the %_data table. The data is a list of varints.\n**   The first value is the number of rows in the index. Then, for each column\n**   from left to right, the total number of tokens in the column for all\n**   rows of the table.\n**\n** 3. Segment leaves:\n**\n**   TERM/DOCLIST FORMAT:\n**\n**     Most of each segment leaf is taken up by term/doclist data. The \n**     general format of term/doclist, starting with the first term\n**     on the leaf page, is:\n**\n**         varint : size of first term\n**         blob:    first term data\n**         doclist: first doclist\n**         zero-or-more {\n**           varint:  number of bytes in common with previous term\n**           varint:  number of bytes of new term data (nNew)\n**           blob:    nNew bytes of new term data\n**           doclist: next doclist\n**         }\n**\n**     doclist format:\n**\n**         varint:  first rowid\n**         poslist: first poslist\n**         zero-or-more {\n**           varint:  rowid delta (always > 0)\n**           poslist: next poslist\n**         }\n**\n**     poslist format:\n**\n**         varint: size of poslist in bytes multiplied by 2, not including\n**                 this field. Plus 1 if this entry carries the \"delete\" flag.\n**         collist: collist for column 0\n**         zero-or-more {\n**           0x01 byte\n**           varint: column number (I)\n**           collist: collist for column I\n**         }\n**\n**     collist format:\n**\n**         varint: first offset + 2\n**         zero-or-more {\n**           varint: offset delta + 2\n**         }\n**\n**   PAGE FORMAT\n**\n**     Each leaf page begins with a 4-byte header containing 2 16-bit \n**     unsigned integer fields in big-endian format. They are:\n**\n**       * The byte offset of the first rowid on the page, if it exists\n**         and occurs before the first term (otherwise 0).\n**\n**       * The byte offset of the start of the page footer. If the page\n**         footer is 0 bytes in size, then this field is the same as the\n**         size of the leaf page in bytes.\n**\n**     The page footer consists of a single varint for each term located\n**     on the page. Each varint is the byte offset of the current term\n**     within the page, delta-compressed against the previous value. In\n**     other words, the first varint in the footer is the byte offset of\n**     the first term, the second is the byte offset of the second less that\n**     of the first, and so on.\n**\n**     The term/doclist format described above is accurate if the entire\n**     term/doclist data fits on a single leaf page. If this is not the case,\n**     the format is changed in two ways:\n**\n**       + if the first rowid on a page occurs before the first term, it\n**         is stored as a literal value:\n**\n**             varint:  first rowid\n**\n**       + the first term on each page is stored in the same way as the\n**         very first term of the segment:\n**\n**             varint : size of first term\n**             blob:    first term data\n**\n** 5. Segment doclist indexes:\n**\n**   Doclist indexes are themselves b-trees, however they usually consist of\n**   a single leaf record only. The format of each doclist index leaf page \n**   is:\n**\n**     * Flags byte. Bits are:\n**         0x01: Clear if leaf is also the root page, otherwise set.\n**\n**     * Page number of fts index leaf page. As a varint.\n**\n**     * First rowid on page indicated by previous field. As a varint.\n**\n**     * A list of varints, one for each subsequent termless page. A \n**       positive delta if the termless page contains at least one rowid, \n**       or an 0x00 byte otherwise.\n**\n**   Internal doclist index nodes are:\n**\n**     * Flags byte. Bits are:\n**         0x01: Clear for root page, otherwise set.\n**\n**     * Page number of first child page. As a varint.\n**\n**     * Copy of first rowid on page indicated by previous field. As a varint.\n**\n**     * A list of delta-encoded varints - the first rowid on each subsequent\n**       child page. \n**\n*/\n\n/*\n** Rowids for the averages and structure records in the %_data table.\n*/\n#define FTS5_AVERAGES_ROWID     1    /* Rowid used for the averages record */\n#define FTS5_STRUCTURE_ROWID   10    /* The structure record */\n\n/*\n** Macros determining the rowids used by segment leaves and dlidx leaves\n** and nodes. All nodes and leaves are stored in the %_data table with large\n** positive rowids.\n**\n** Each segment has a unique non-zero 16-bit id.\n**\n** The rowid for each segment leaf is found by passing the segment id and \n** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered\n** sequentially starting from 1.\n*/\n#define FTS5_DATA_ID_B     16     /* Max seg id number 65535 */\n#define FTS5_DATA_DLI_B     1     /* Doclist-index flag (1 bit) */\n#define FTS5_DATA_HEIGHT_B  5     /* Max dlidx tree height of 32 */\n#define FTS5_DATA_PAGE_B   31     /* Max page number of 2147483648 */\n\n#define fts5_dri(segid, dlidx, height, pgno) (                                 \\\n ((i64)(segid)  << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) +    \\\n ((i64)(dlidx)  << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) +                  \\\n ((i64)(height) << (FTS5_DATA_PAGE_B)) +                                       \\\n ((i64)(pgno))                                                                 \\\n)\n\n#define FTS5_SEGMENT_ROWID(segid, pgno)       fts5_dri(segid, 0, 0, pgno)\n#define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)\n\n#ifdef SQLITE_DEBUG\nstatic int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }\n#endif\n\n\n/*\n** Each time a blob is read from the %_data table, it is padded with this\n** many zero bytes. This makes it easier to decode the various record formats\n** without overreading if the records are corrupt.\n*/\n#define FTS5_DATA_ZERO_PADDING 8\n#define FTS5_DATA_PADDING 20\n\ntypedef struct Fts5Data Fts5Data;\ntypedef struct Fts5DlidxIter Fts5DlidxIter;\ntypedef struct Fts5DlidxLvl Fts5DlidxLvl;\ntypedef struct Fts5DlidxWriter Fts5DlidxWriter;\ntypedef struct Fts5Iter Fts5Iter;\ntypedef struct Fts5PageWriter Fts5PageWriter;\ntypedef struct Fts5SegIter Fts5SegIter;\ntypedef struct Fts5DoclistIter Fts5DoclistIter;\ntypedef struct Fts5SegWriter Fts5SegWriter;\ntypedef struct Fts5Structure Fts5Structure;\ntypedef struct Fts5StructureLevel Fts5StructureLevel;\ntypedef struct Fts5StructureSegment Fts5StructureSegment;\n\nstruct Fts5Data {\n  u8 *p;                          /* Pointer to buffer containing record */\n  int nn;                         /* Size of record in bytes */\n  int szLeaf;                     /* Size of leaf without page-index */\n};\n\n/*\n** One object per %_data table.\n*/\nstruct Fts5Index {\n  Fts5Config *pConfig;            /* Virtual table configuration */\n  char *zDataTbl;                 /* Name of %_data table */\n  int nWorkUnit;                  /* Leaf pages in a \"unit\" of work */\n\n  /*\n  ** Variables related to the accumulation of tokens and doclists within the\n  ** in-memory hash tables before they are flushed to disk.\n  */\n  Fts5Hash *pHash;                /* Hash table for in-memory data */\n  int nPendingData;               /* Current bytes of pending data */\n  i64 iWriteRowid;                /* Rowid for current doc being written */\n  int bDelete;                    /* Current write is a delete */\n\n  /* Error state. */\n  int rc;                         /* Current error code */\n\n  /* State used by the fts5DataXXX() functions. */\n  sqlite3_blob *pReader;          /* RO incr-blob open on %_data table */\n  sqlite3_stmt *pWriter;          /* \"INSERT ... %_data VALUES(?,?)\" */\n  sqlite3_stmt *pDeleter;         /* \"DELETE FROM %_data ... id>=? AND id<=?\" */\n  sqlite3_stmt *pIdxWriter;       /* \"INSERT ... %_idx VALUES(?,?,?,?)\" */\n  sqlite3_stmt *pIdxDeleter;      /* \"DELETE FROM %_idx WHERE segid=? */\n  sqlite3_stmt *pIdxSelect;\n  int nRead;                      /* Total number of blocks read */\n\n  sqlite3_stmt *pDataVersion;\n  i64 iStructVersion;             /* data_version when pStruct read */\n  Fts5Structure *pStruct;         /* Current db structure (or NULL) */\n};\n\nstruct Fts5DoclistIter {\n  u8 *aEof;                       /* Pointer to 1 byte past end of doclist */\n\n  /* Output variables. aPoslist==0 at EOF */\n  i64 iRowid;\n  u8 *aPoslist;\n  int nPoslist;\n  int nSize;\n};\n\n/*\n** The contents of the \"structure\" record for each index are represented\n** using an Fts5Structure record in memory. Which uses instances of the \n** other Fts5StructureXXX types as components.\n*/\nstruct Fts5StructureSegment {\n  int iSegid;                     /* Segment id */\n  int pgnoFirst;                  /* First leaf page number in segment */\n  int pgnoLast;                   /* Last leaf page number in segment */\n};\nstruct Fts5StructureLevel {\n  int nMerge;                     /* Number of segments in incr-merge */\n  int nSeg;                       /* Total number of segments on level */\n  Fts5StructureSegment *aSeg;     /* Array of segments. aSeg[0] is oldest. */\n};\nstruct Fts5Structure {\n  int nRef;                       /* Object reference count */\n  u64 nWriteCounter;              /* Total leaves written to level 0 */\n  int nSegment;                   /* Total segments in this structure */\n  int nLevel;                     /* Number of levels in this index */\n  Fts5StructureLevel aLevel[1];   /* Array of nLevel level objects */\n};\n\n/*\n** An object of type Fts5SegWriter is used to write to segments.\n*/\nstruct Fts5PageWriter {\n  int pgno;                       /* Page number for this page */\n  int iPrevPgidx;                 /* Previous value written into pgidx */\n  Fts5Buffer buf;                 /* Buffer containing leaf data */\n  Fts5Buffer pgidx;               /* Buffer containing page-index */\n  Fts5Buffer term;                /* Buffer containing previous term on page */\n};\nstruct Fts5DlidxWriter {\n  int pgno;                       /* Page number for this page */\n  int bPrevValid;                 /* True if iPrev is valid */\n  i64 iPrev;                      /* Previous rowid value written to page */\n  Fts5Buffer buf;                 /* Buffer containing page data */\n};\nstruct Fts5SegWriter {\n  int iSegid;                     /* Segid to write to */\n  Fts5PageWriter writer;          /* PageWriter object */\n  i64 iPrevRowid;                 /* Previous rowid written to current leaf */\n  u8 bFirstRowidInDoclist;        /* True if next rowid is first in doclist */\n  u8 bFirstRowidInPage;           /* True if next rowid is first in page */\n  /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */\n  u8 bFirstTermInPage;            /* True if next term will be first in leaf */\n  int nLeafWritten;               /* Number of leaf pages written */\n  int nEmpty;                     /* Number of contiguous term-less nodes */\n\n  int nDlidx;                     /* Allocated size of aDlidx[] array */\n  Fts5DlidxWriter *aDlidx;        /* Array of Fts5DlidxWriter objects */\n\n  /* Values to insert into the %_idx table */\n  Fts5Buffer btterm;              /* Next term to insert into %_idx table */\n  int iBtPage;                    /* Page number corresponding to btterm */\n};\n\ntypedef struct Fts5CResult Fts5CResult;\nstruct Fts5CResult {\n  u16 iFirst;                     /* aSeg[] index of firstest iterator */\n  u8 bTermEq;                     /* True if the terms are equal */\n};\n\n/*\n** Object for iterating through a single segment, visiting each term/rowid\n** pair in the segment.\n**\n** pSeg:\n**   The segment to iterate through.\n**\n** iLeafPgno:\n**   Current leaf page number within segment.\n**\n** iLeafOffset:\n**   Byte offset within the current leaf that is the first byte of the \n**   position list data (one byte passed the position-list size field).\n**   rowid field of the current entry. Usually this is the size field of the\n**   position list data. The exception is if the rowid for the current entry \n**   is the last thing on the leaf page.\n**\n** pLeaf:\n**   Buffer containing current leaf page data. Set to NULL at EOF.\n**\n** iTermLeafPgno, iTermLeafOffset:\n**   Leaf page number containing the last term read from the segment. And\n**   the offset immediately following the term data.\n**\n** flags:\n**   Mask of FTS5_SEGITER_XXX values. Interpreted as follows:\n**\n**   FTS5_SEGITER_ONETERM:\n**     If set, set the iterator to point to EOF after the current doclist \n**     has been exhausted. Do not proceed to the next term in the segment.\n**\n**   FTS5_SEGITER_REVERSE:\n**     This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If\n**     it is set, iterate through rowid in descending order instead of the\n**     default ascending order.\n**\n** iRowidOffset/nRowidOffset/aRowidOffset:\n**     These are used if the FTS5_SEGITER_REVERSE flag is set.\n**\n**     For each rowid on the page corresponding to the current term, the\n**     corresponding aRowidOffset[] entry is set to the byte offset of the\n**     start of the \"position-list-size\" field within the page.\n**\n** iTermIdx:\n**     Index of current term on iTermLeafPgno.\n*/\nstruct Fts5SegIter {\n  Fts5StructureSegment *pSeg;     /* Segment to iterate through */\n  int flags;                      /* Mask of configuration flags */\n  int iLeafPgno;                  /* Current leaf page number */\n  Fts5Data *pLeaf;                /* Current leaf data */\n  Fts5Data *pNextLeaf;            /* Leaf page (iLeafPgno+1) */\n  int iLeafOffset;                /* Byte offset within current leaf */\n\n  /* Next method */\n  void (*xNext)(Fts5Index*, Fts5SegIter*, int*);\n\n  /* The page and offset from which the current term was read. The offset \n  ** is the offset of the first rowid in the current doclist.  */\n  int iTermLeafPgno;\n  int iTermLeafOffset;\n\n  int iPgidxOff;                  /* Next offset in pgidx */\n  int iEndofDoclist;\n\n  /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */\n  int iRowidOffset;               /* Current entry in aRowidOffset[] */\n  int nRowidOffset;               /* Allocated size of aRowidOffset[] array */\n  int *aRowidOffset;              /* Array of offset to rowid fields */\n\n  Fts5DlidxIter *pDlidx;          /* If there is a doclist-index */\n\n  /* Variables populated based on current entry. */\n  Fts5Buffer term;                /* Current term */\n  i64 iRowid;                     /* Current rowid */\n  int nPos;                       /* Number of bytes in current position list */\n  u8 bDel;                        /* True if the delete flag is set */\n};\n\n/*\n** Argument is a pointer to an Fts5Data structure that contains a \n** leaf page.\n*/\n#define ASSERT_SZLEAF_OK(x) assert( \\\n    (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \\\n)\n\n#define FTS5_SEGITER_ONETERM 0x01\n#define FTS5_SEGITER_REVERSE 0x02\n\n/* \n** Argument is a pointer to an Fts5Data structure that contains a leaf\n** page. This macro evaluates to true if the leaf contains no terms, or\n** false if it contains at least one term.\n*/\n#define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)\n\n#define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))\n\n#define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))\n\n/*\n** Object for iterating through the merged results of one or more segments,\n** visiting each term/rowid pair in the merged data.\n**\n** nSeg is always a power of two greater than or equal to the number of\n** segments that this object is merging data from. Both the aSeg[] and\n** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded\n** with zeroed objects - these are handled as if they were iterators opened\n** on empty segments.\n**\n** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an\n** even number, is stored in aFirst[(nSeg+N)/2]. The \"result\" of the \n** comparison in this context is the index of the iterator that currently\n** points to the smaller term/rowid combination. Iterators at EOF are\n** considered to be greater than all other iterators.\n**\n** aFirst[1] contains the index in aSeg[] of the iterator that points to\n** the smallest key overall. aFirst[0] is unused. \n**\n** poslist:\n**   Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.\n**   There is no way to tell if this is populated or not.\n*/\nstruct Fts5Iter {\n  Fts5IndexIter base;             /* Base class containing output vars */\n\n  Fts5Index *pIndex;              /* Index that owns this iterator */\n  Fts5Buffer poslist;             /* Buffer containing current poslist */\n  Fts5Colset *pColset;            /* Restrict matches to these columns */\n\n  /* Invoked to set output variables. */\n  void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);\n\n  int nSeg;                       /* Size of aSeg[] array */\n  int bRev;                       /* True to iterate in reverse order */\n  u8 bSkipEmpty;                  /* True to skip deleted entries */\n\n  i64 iSwitchRowid;               /* Firstest rowid of other than aFirst[1] */\n  Fts5CResult *aFirst;            /* Current merge state (see above) */\n  Fts5SegIter aSeg[1];            /* Array of segment iterators */\n};\n\n\n/*\n** An instance of the following type is used to iterate through the contents\n** of a doclist-index record.\n**\n** pData:\n**   Record containing the doclist-index data.\n**\n** bEof:\n**   Set to true once iterator has reached EOF.\n**\n** iOff:\n**   Set to the current offset within record pData.\n*/\nstruct Fts5DlidxLvl {\n  Fts5Data *pData;              /* Data for current page of this level */\n  int iOff;                     /* Current offset into pData */\n  int bEof;                     /* At EOF already */\n  int iFirstOff;                /* Used by reverse iterators */\n\n  /* Output variables */\n  int iLeafPgno;                /* Page number of current leaf page */\n  i64 iRowid;                   /* First rowid on leaf iLeafPgno */\n};\nstruct Fts5DlidxIter {\n  int nLvl;\n  int iSegid;\n  Fts5DlidxLvl aLvl[1];\n};\n\nstatic void fts5PutU16(u8 *aOut, u16 iVal){\n  aOut[0] = (iVal>>8);\n  aOut[1] = (iVal&0xFF);\n}\n\nstatic u16 fts5GetU16(const u8 *aIn){\n  return ((u16)aIn[0] << 8) + aIn[1];\n} \n\n/*\n** Allocate and return a buffer at least nByte bytes in size.\n**\n** If an OOM error is encountered, return NULL and set the error code in\n** the Fts5Index handle passed as the first argument.\n*/\nstatic void *fts5IdxMalloc(Fts5Index *p, sqlite3_int64 nByte){\n  return sqlite3Fts5MallocZero(&p->rc, nByte);\n}\n\n/*\n** Compare the contents of the pLeft buffer with the pRight/nRight blob.\n**\n** Return -ve if pLeft is smaller than pRight, 0 if they are equal or\n** +ve if pRight is smaller than pLeft. In other words:\n**\n**     res = *pLeft - *pRight\n*/\n#ifdef SQLITE_DEBUG\nstatic int fts5BufferCompareBlob(\n  Fts5Buffer *pLeft,              /* Left hand side of comparison */\n  const u8 *pRight, int nRight    /* Right hand side of comparison */\n){\n  int nCmp = MIN(pLeft->n, nRight);\n  int res = memcmp(pLeft->p, pRight, nCmp);\n  return (res==0 ? (pLeft->n - nRight) : res);\n}\n#endif\n\n/*\n** Compare the contents of the two buffers using memcmp(). If one buffer\n** is a prefix of the other, it is considered the lesser.\n**\n** Return -ve if pLeft is smaller than pRight, 0 if they are equal or\n** +ve if pRight is smaller than pLeft. In other words:\n**\n**     res = *pLeft - *pRight\n*/\nstatic int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){\n  int nCmp = MIN(pLeft->n, pRight->n);\n  int res = fts5Memcmp(pLeft->p, pRight->p, nCmp);\n  return (res==0 ? (pLeft->n - pRight->n) : res);\n}\n\nstatic int fts5LeafFirstTermOff(Fts5Data *pLeaf){\n  int ret;\n  fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);\n  return ret;\n}\n\n/*\n** Close the read-only blob handle, if it is open.\n*/\nstatic void sqlite3Fts5IndexCloseReader(Fts5Index *p){\n  if( p->pReader ){\n    sqlite3_blob *pReader = p->pReader;\n    p->pReader = 0;\n    sqlite3_blob_close(pReader);\n  }\n}\n\n/*\n** Retrieve a record from the %_data table.\n**\n** If an error occurs, NULL is returned and an error left in the \n** Fts5Index object.\n*/\nstatic Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){\n  Fts5Data *pRet = 0;\n  if( p->rc==SQLITE_OK ){\n    int rc = SQLITE_OK;\n\n    if( p->pReader ){\n      /* This call may return SQLITE_ABORT if there has been a savepoint\n      ** rollback since it was last used. In this case a new blob handle\n      ** is required.  */\n      sqlite3_blob *pBlob = p->pReader;\n      p->pReader = 0;\n      rc = sqlite3_blob_reopen(pBlob, iRowid);\n      assert( p->pReader==0 );\n      p->pReader = pBlob;\n      if( rc!=SQLITE_OK ){\n        sqlite3Fts5IndexCloseReader(p);\n      }\n      if( rc==SQLITE_ABORT ) rc = SQLITE_OK;\n    }\n\n    /* If the blob handle is not open at this point, open it and seek \n    ** to the requested entry.  */\n    if( p->pReader==0 && rc==SQLITE_OK ){\n      Fts5Config *pConfig = p->pConfig;\n      rc = sqlite3_blob_open(pConfig->db, \n          pConfig->zDb, p->zDataTbl, \"block\", iRowid, 0, &p->pReader\n      );\n    }\n\n    /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls\n    ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.\n    ** All the reasons those functions might return SQLITE_ERROR - missing\n    ** table, missing row, non-blob/text in block column - indicate \n    ** backing store corruption.  */\n    if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;\n\n    if( rc==SQLITE_OK ){\n      u8 *aOut = 0;               /* Read blob data into this buffer */\n      int nByte = sqlite3_blob_bytes(p->pReader);\n      sqlite3_int64 nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;\n      pRet = (Fts5Data*)sqlite3_malloc64(nAlloc);\n      if( pRet ){\n        pRet->nn = nByte;\n        aOut = pRet->p = (u8*)&pRet[1];\n      }else{\n        rc = SQLITE_NOMEM;\n      }\n\n      if( rc==SQLITE_OK ){\n        rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);\n      }\n      if( rc!=SQLITE_OK ){\n        sqlite3_free(pRet);\n        pRet = 0;\n      }else{\n        /* TODO1: Fix this */\n        pRet->p[nByte] = 0x00;\n        pRet->p[nByte+1] = 0x00;\n        pRet->szLeaf = fts5GetU16(&pRet->p[2]);\n      }\n    }\n    p->rc = rc;\n    p->nRead++;\n  }\n\n  assert( (pRet==0)==(p->rc!=SQLITE_OK) );\n  return pRet;\n}\n\n/*\n** Release a reference to data record returned by an earlier call to\n** fts5DataRead().\n*/\nstatic void fts5DataRelease(Fts5Data *pData){\n  sqlite3_free(pData);\n}\n\nstatic Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){\n  Fts5Data *pRet = fts5DataRead(p, iRowid);\n  if( pRet ){\n    if( pRet->nn<4 || pRet->szLeaf>pRet->nn ){\n      p->rc = FTS5_CORRUPT;\n      fts5DataRelease(pRet);\n      pRet = 0;\n    }\n  }\n  return pRet;\n}\n\nstatic int fts5IndexPrepareStmt(\n  Fts5Index *p,\n  sqlite3_stmt **ppStmt,\n  char *zSql\n){\n  if( p->rc==SQLITE_OK ){\n    if( zSql ){\n      p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,\n          SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB,\n          ppStmt, 0);\n    }else{\n      p->rc = SQLITE_NOMEM;\n    }\n  }\n  sqlite3_free(zSql);\n  return p->rc;\n}\n\n\n/*\n** INSERT OR REPLACE a record into the %_data table.\n*/\nstatic void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){\n  if( p->rc!=SQLITE_OK ) return;\n\n  if( p->pWriter==0 ){\n    Fts5Config *pConfig = p->pConfig;\n    fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(\n          \"REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)\", \n          pConfig->zDb, pConfig->zName\n    ));\n    if( p->rc ) return;\n  }\n\n  sqlite3_bind_int64(p->pWriter, 1, iRowid);\n  sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);\n  sqlite3_step(p->pWriter);\n  p->rc = sqlite3_reset(p->pWriter);\n  sqlite3_bind_null(p->pWriter, 2);\n}\n\n/*\n** Execute the following SQL:\n**\n**     DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast\n*/\nstatic void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){\n  if( p->rc!=SQLITE_OK ) return;\n\n  if( p->pDeleter==0 ){\n    Fts5Config *pConfig = p->pConfig;\n    char *zSql = sqlite3_mprintf(\n        \"DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?\", \n          pConfig->zDb, pConfig->zName\n    );\n    if( fts5IndexPrepareStmt(p, &p->pDeleter, zSql) ) return;\n  }\n\n  sqlite3_bind_int64(p->pDeleter, 1, iFirst);\n  sqlite3_bind_int64(p->pDeleter, 2, iLast);\n  sqlite3_step(p->pDeleter);\n  p->rc = sqlite3_reset(p->pDeleter);\n}\n\n/*\n** Remove all records associated with segment iSegid.\n*/\nstatic void fts5DataRemoveSegment(Fts5Index *p, int iSegid){\n  i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);\n  i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;\n  fts5DataDelete(p, iFirst, iLast);\n  if( p->pIdxDeleter==0 ){\n    Fts5Config *pConfig = p->pConfig;\n    fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(\n          \"DELETE FROM '%q'.'%q_idx' WHERE segid=?\",\n          pConfig->zDb, pConfig->zName\n    ));\n  }\n  if( p->rc==SQLITE_OK ){\n    sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);\n    sqlite3_step(p->pIdxDeleter);\n    p->rc = sqlite3_reset(p->pIdxDeleter);\n  }\n}\n\n/*\n** Release a reference to an Fts5Structure object returned by an earlier \n** call to fts5StructureRead() or fts5StructureDecode().\n*/\nstatic void fts5StructureRelease(Fts5Structure *pStruct){\n  if( pStruct && 0>=(--pStruct->nRef) ){\n    int i;\n    assert( pStruct->nRef==0 );\n    for(i=0; i<pStruct->nLevel; i++){\n      sqlite3_free(pStruct->aLevel[i].aSeg);\n    }\n    sqlite3_free(pStruct);\n  }\n}\n\nstatic void fts5StructureRef(Fts5Structure *pStruct){\n  pStruct->nRef++;\n}\n\n/*\n** Deserialize and return the structure record currently stored in serialized\n** form within buffer pData/nData.\n**\n** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array\n** are over-allocated by one slot. This allows the structure contents\n** to be more easily edited.\n**\n** If an error occurs, *ppOut is set to NULL and an SQLite error code\n** returned. Otherwise, *ppOut is set to point to the new object and\n** SQLITE_OK returned.\n*/\nstatic int fts5StructureDecode(\n  const u8 *pData,                /* Buffer containing serialized structure */\n  int nData,                      /* Size of buffer pData in bytes */\n  int *piCookie,                  /* Configuration cookie value */\n  Fts5Structure **ppOut           /* OUT: Deserialized object */\n){\n  int rc = SQLITE_OK;\n  int i = 0;\n  int iLvl;\n  int nLevel = 0;\n  int nSegment = 0;\n  sqlite3_int64 nByte;            /* Bytes of space to allocate at pRet */\n  Fts5Structure *pRet = 0;        /* Structure object to return */\n\n  /* Grab the cookie value */\n  if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);\n  i = 4;\n\n  /* Read the total number of levels and segments from the start of the\n  ** structure record.  */\n  i += fts5GetVarint32(&pData[i], nLevel);\n  i += fts5GetVarint32(&pData[i], nSegment);\n  if( nLevel>FTS5_MAX_SEGMENT   || nLevel<0\n   || nSegment>FTS5_MAX_SEGMENT || nSegment<0\n  ){\n    return FTS5_CORRUPT;\n  }\n  nByte = (\n      sizeof(Fts5Structure) +                    /* Main structure */\n      sizeof(Fts5StructureLevel) * (nLevel-1)    /* aLevel[] array */\n  );\n  pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);\n\n  if( pRet ){\n    pRet->nRef = 1;\n    pRet->nLevel = nLevel;\n    pRet->nSegment = nSegment;\n    i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);\n\n    for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){\n      Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];\n      int nTotal = 0;\n      int iSeg;\n\n      if( i>=nData ){\n        rc = FTS5_CORRUPT;\n      }else{\n        i += fts5GetVarint32(&pData[i], pLvl->nMerge);\n        i += fts5GetVarint32(&pData[i], nTotal);\n        if( nTotal<pLvl->nMerge ) rc = FTS5_CORRUPT;\n        pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc, \n            nTotal * sizeof(Fts5StructureSegment)\n        );\n        nSegment -= nTotal;\n      }\n\n      if( rc==SQLITE_OK ){\n        pLvl->nSeg = nTotal;\n        for(iSeg=0; iSeg<nTotal; iSeg++){\n          Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];\n          if( i>=nData ){\n            rc = FTS5_CORRUPT;\n            break;\n          }\n          i += fts5GetVarint32(&pData[i], pSeg->iSegid);\n          i += fts5GetVarint32(&pData[i], pSeg->pgnoFirst);\n          i += fts5GetVarint32(&pData[i], pSeg->pgnoLast);\n          if( pSeg->pgnoLast<pSeg->pgnoFirst ){\n            rc = FTS5_CORRUPT;\n            break;\n          }\n        }\n        if( iLvl>0 && pLvl[-1].nMerge && nTotal==0 ) rc = FTS5_CORRUPT;\n        if( iLvl==nLevel-1 && pLvl->nMerge ) rc = FTS5_CORRUPT;\n      }\n    }\n    if( nSegment!=0 && rc==SQLITE_OK ) rc = FTS5_CORRUPT;\n\n    if( rc!=SQLITE_OK ){\n      fts5StructureRelease(pRet);\n      pRet = 0;\n    }\n  }\n\n  *ppOut = pRet;\n  return rc;\n}\n\n/*\n**\n*/\nstatic void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){\n  if( *pRc==SQLITE_OK ){\n    Fts5Structure *pStruct = *ppStruct;\n    int nLevel = pStruct->nLevel;\n    sqlite3_int64 nByte = (\n        sizeof(Fts5Structure) +                  /* Main structure */\n        sizeof(Fts5StructureLevel) * (nLevel+1)  /* aLevel[] array */\n    );\n\n    pStruct = sqlite3_realloc64(pStruct, nByte);\n    if( pStruct ){\n      memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));\n      pStruct->nLevel++;\n      *ppStruct = pStruct;\n    }else{\n      *pRc = SQLITE_NOMEM;\n    }\n  }\n}\n\n/*\n** Extend level iLvl so that there is room for at least nExtra more\n** segments.\n*/\nstatic void fts5StructureExtendLevel(\n  int *pRc, \n  Fts5Structure *pStruct, \n  int iLvl, \n  int nExtra, \n  int bInsert\n){\n  if( *pRc==SQLITE_OK ){\n    Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];\n    Fts5StructureSegment *aNew;\n    sqlite3_int64 nByte;\n\n    nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);\n    aNew = sqlite3_realloc64(pLvl->aSeg, nByte);\n    if( aNew ){\n      if( bInsert==0 ){\n        memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);\n      }else{\n        int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);\n        memmove(&aNew[nExtra], aNew, nMove);\n        memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);\n      }\n      pLvl->aSeg = aNew;\n    }else{\n      *pRc = SQLITE_NOMEM;\n    }\n  }\n}\n\nstatic Fts5Structure *fts5StructureReadUncached(Fts5Index *p){\n  Fts5Structure *pRet = 0;\n  Fts5Config *pConfig = p->pConfig;\n  int iCookie;                    /* Configuration cookie */\n  Fts5Data *pData;\n\n  pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);\n  if( p->rc==SQLITE_OK ){\n    /* TODO: Do we need this if the leaf-index is appended? Probably... */\n    memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);\n    p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);\n    if( p->rc==SQLITE_OK && (pConfig->pgsz==0 || pConfig->iCookie!=iCookie) ){\n      p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);\n    }\n    fts5DataRelease(pData);\n    if( p->rc!=SQLITE_OK ){\n      fts5StructureRelease(pRet);\n      pRet = 0;\n    }\n  }\n\n  return pRet;\n}\n\nstatic i64 fts5IndexDataVersion(Fts5Index *p){\n  i64 iVersion = 0;\n\n  if( p->rc==SQLITE_OK ){\n    if( p->pDataVersion==0 ){\n      p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion, \n          sqlite3_mprintf(\"PRAGMA %Q.data_version\", p->pConfig->zDb)\n          );\n      if( p->rc ) return 0;\n    }\n\n    if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){\n      iVersion = sqlite3_column_int64(p->pDataVersion, 0);\n    }\n    p->rc = sqlite3_reset(p->pDataVersion);\n  }\n\n  return iVersion;\n}\n\n/*\n** Read, deserialize and return the structure record.\n**\n** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array\n** are over-allocated as described for function fts5StructureDecode() \n** above.\n**\n** If an error occurs, NULL is returned and an error code left in the\n** Fts5Index handle. If an error has already occurred when this function\n** is called, it is a no-op.\n*/\nstatic Fts5Structure *fts5StructureRead(Fts5Index *p){\n\n  if( p->pStruct==0 ){\n    p->iStructVersion = fts5IndexDataVersion(p);\n    if( p->rc==SQLITE_OK ){\n      p->pStruct = fts5StructureReadUncached(p);\n    }\n  }\n\n#if 0\n  else{\n    Fts5Structure *pTest = fts5StructureReadUncached(p);\n    if( pTest ){\n      int i, j;\n      assert_nc( p->pStruct->nSegment==pTest->nSegment );\n      assert_nc( p->pStruct->nLevel==pTest->nLevel );\n      for(i=0; i<pTest->nLevel; i++){\n        assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );\n        assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );\n        for(j=0; j<pTest->aLevel[i].nSeg; j++){\n          Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];\n          Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];\n          assert_nc( p1->iSegid==p2->iSegid );\n          assert_nc( p1->pgnoFirst==p2->pgnoFirst );\n          assert_nc( p1->pgnoLast==p2->pgnoLast );\n        }\n      }\n      fts5StructureRelease(pTest);\n    }\n  }\n#endif\n\n  if( p->rc!=SQLITE_OK ) return 0;\n  assert( p->iStructVersion!=0 );\n  assert( p->pStruct!=0 );\n  fts5StructureRef(p->pStruct);\n  return p->pStruct;\n}\n\nstatic void fts5StructureInvalidate(Fts5Index *p){\n  if( p->pStruct ){\n    fts5StructureRelease(p->pStruct);\n    p->pStruct = 0;\n  }\n}\n\n/*\n** Return the total number of segments in index structure pStruct. This\n** function is only ever used as part of assert() conditions.\n*/\n#ifdef SQLITE_DEBUG\nstatic int fts5StructureCountSegments(Fts5Structure *pStruct){\n  int nSegment = 0;               /* Total number of segments */\n  if( pStruct ){\n    int iLvl;                     /* Used to iterate through levels */\n    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){\n      nSegment += pStruct->aLevel[iLvl].nSeg;\n    }\n  }\n\n  return nSegment;\n}\n#endif\n\n#define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) {     \\\n  assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) );             \\\n  memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob);             \\\n  (pBuf)->n += nBlob;                                      \\\n}\n\n#define fts5BufferSafeAppendVarint(pBuf, iVal) {                \\\n  (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal));  \\\n  assert( (pBuf)->nSpace>=(pBuf)->n );                          \\\n}\n\n\n/*\n** Serialize and store the \"structure\" record.\n**\n** If an error occurs, leave an error code in the Fts5Index object. If an\n** error has already occurred, this function is a no-op.\n*/\nstatic void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){\n  if( p->rc==SQLITE_OK ){\n    Fts5Buffer buf;               /* Buffer to serialize record into */\n    int iLvl;                     /* Used to iterate through levels */\n    int iCookie;                  /* Cookie value to store */\n\n    assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );\n    memset(&buf, 0, sizeof(Fts5Buffer));\n\n    /* Append the current configuration cookie */\n    iCookie = p->pConfig->iCookie;\n    if( iCookie<0 ) iCookie = 0;\n\n    if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){\n      sqlite3Fts5Put32(buf.p, iCookie);\n      buf.n = 4;\n      fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);\n      fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);\n      fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);\n    }\n\n    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){\n      int iSeg;                     /* Used to iterate through segments */\n      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];\n      fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);\n      fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);\n      assert( pLvl->nMerge<=pLvl->nSeg );\n\n      for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){\n        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);\n        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);\n        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);\n      }\n    }\n\n    fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);\n    fts5BufferFree(&buf);\n  }\n}\n\n#if 0\nstatic void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);\nstatic void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){\n  int rc = SQLITE_OK;\n  Fts5Buffer buf;\n  memset(&buf, 0, sizeof(buf));\n  fts5DebugStructure(&rc, &buf, pStruct);\n  fprintf(stdout, \"%s: %s\\n\", zCaption, buf.p);\n  fflush(stdout);\n  fts5BufferFree(&buf);\n}\n#else\n# define fts5PrintStructure(x,y)\n#endif\n\nstatic int fts5SegmentSize(Fts5StructureSegment *pSeg){\n  return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;\n}\n\n/*\n** Return a copy of index structure pStruct. Except, promote as many \n** segments as possible to level iPromote. If an OOM occurs, NULL is \n** returned.\n*/\nstatic void fts5StructurePromoteTo(\n  Fts5Index *p,\n  int iPromote,\n  int szPromote,\n  Fts5Structure *pStruct\n){\n  int il, is;\n  Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];\n\n  if( pOut->nMerge==0 ){\n    for(il=iPromote+1; il<pStruct->nLevel; il++){\n      Fts5StructureLevel *pLvl = &pStruct->aLevel[il];\n      if( pLvl->nMerge ) return;\n      for(is=pLvl->nSeg-1; is>=0; is--){\n        int sz = fts5SegmentSize(&pLvl->aSeg[is]);\n        if( sz>szPromote ) return;\n        fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);\n        if( p->rc ) return;\n        memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));\n        pOut->nSeg++;\n        pLvl->nSeg--;\n      }\n    }\n  }\n}\n\n/*\n** A new segment has just been written to level iLvl of index structure\n** pStruct. This function determines if any segments should be promoted\n** as a result. Segments are promoted in two scenarios:\n**\n**   a) If the segment just written is smaller than one or more segments\n**      within the previous populated level, it is promoted to the previous\n**      populated level.\n**\n**   b) If the segment just written is larger than the newest segment on\n**      the next populated level, then that segment, and any other adjacent\n**      segments that are also smaller than the one just written, are \n**      promoted. \n**\n** If one or more segments are promoted, the structure object is updated\n** to reflect this.\n*/\nstatic void fts5StructurePromote(\n  Fts5Index *p,                   /* FTS5 backend object */\n  int iLvl,                       /* Index level just updated */\n  Fts5Structure *pStruct          /* Index structure */\n){\n  if( p->rc==SQLITE_OK ){\n    int iTst;\n    int iPromote = -1;\n    int szPromote = 0;            /* Promote anything this size or smaller */\n    Fts5StructureSegment *pSeg;   /* Segment just written */\n    int szSeg;                    /* Size of segment just written */\n    int nSeg = pStruct->aLevel[iLvl].nSeg;\n\n    if( nSeg==0 ) return;\n    pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];\n    szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);\n\n    /* Check for condition (a) */\n    for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);\n    if( iTst>=0 ){\n      int i;\n      int szMax = 0;\n      Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];\n      assert( pTst->nMerge==0 );\n      for(i=0; i<pTst->nSeg; i++){\n        int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;\n        if( sz>szMax ) szMax = sz;\n      }\n      if( szMax>=szSeg ){\n        /* Condition (a) is true. Promote the newest segment on level \n        ** iLvl to level iTst.  */\n        iPromote = iTst;\n        szPromote = szMax;\n      }\n    }\n\n    /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()\n    ** is a no-op if it is not.  */\n    if( iPromote<0 ){\n      iPromote = iLvl;\n      szPromote = szSeg;\n    }\n    fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);\n  }\n}\n\n\n/*\n** Advance the iterator passed as the only argument. If the end of the \n** doclist-index page is reached, return non-zero.\n*/\nstatic int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){\n  Fts5Data *pData = pLvl->pData;\n\n  if( pLvl->iOff==0 ){\n    assert( pLvl->bEof==0 );\n    pLvl->iOff = 1;\n    pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);\n    pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);\n    pLvl->iFirstOff = pLvl->iOff;\n  }else{\n    int iOff;\n    for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){\n      if( pData->p[iOff] ) break; \n    }\n\n    if( iOff<pData->nn ){\n      i64 iVal;\n      pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;\n      iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);\n      pLvl->iRowid += iVal;\n      pLvl->iOff = iOff;\n    }else{\n      pLvl->bEof = 1;\n    }\n  }\n\n  return pLvl->bEof;\n}\n\n/*\n** Advance the iterator passed as the only argument.\n*/\nstatic int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){\n  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];\n\n  assert( iLvl<pIter->nLvl );\n  if( fts5DlidxLvlNext(pLvl) ){\n    if( (iLvl+1) < pIter->nLvl ){\n      fts5DlidxIterNextR(p, pIter, iLvl+1);\n      if( pLvl[1].bEof==0 ){\n        fts5DataRelease(pLvl->pData);\n        memset(pLvl, 0, sizeof(Fts5DlidxLvl));\n        pLvl->pData = fts5DataRead(p, \n            FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)\n        );\n        if( pLvl->pData ) fts5DlidxLvlNext(pLvl);\n      }\n    }\n  }\n\n  return pIter->aLvl[0].bEof;\n}\nstatic int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){\n  return fts5DlidxIterNextR(p, pIter, 0);\n}\n\n/*\n** The iterator passed as the first argument has the following fields set\n** as follows. This function sets up the rest of the iterator so that it\n** points to the first rowid in the doclist-index.\n**\n**   pData:\n**     pointer to doclist-index record, \n**\n** When this function is called pIter->iLeafPgno is the page number the\n** doclist is associated with (the one featuring the term).\n*/\nstatic int fts5DlidxIterFirst(Fts5DlidxIter *pIter){\n  int i;\n  for(i=0; i<pIter->nLvl; i++){\n    fts5DlidxLvlNext(&pIter->aLvl[i]);\n  }\n  return pIter->aLvl[0].bEof;\n}\n\n\nstatic int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){\n  return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;\n}\n\nstatic void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){\n  int i;\n\n  /* Advance each level to the last entry on the last page */\n  for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){\n    Fts5DlidxLvl *pLvl = &pIter->aLvl[i];\n    while( fts5DlidxLvlNext(pLvl)==0 );\n    pLvl->bEof = 0;\n\n    if( i>0 ){\n      Fts5DlidxLvl *pChild = &pLvl[-1];\n      fts5DataRelease(pChild->pData);\n      memset(pChild, 0, sizeof(Fts5DlidxLvl));\n      pChild->pData = fts5DataRead(p, \n          FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)\n      );\n    }\n  }\n}\n\n/*\n** Move the iterator passed as the only argument to the previous entry.\n*/\nstatic int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){\n  int iOff = pLvl->iOff;\n\n  assert( pLvl->bEof==0 );\n  if( iOff<=pLvl->iFirstOff ){\n    pLvl->bEof = 1;\n  }else{\n    u8 *a = pLvl->pData->p;\n    i64 iVal;\n    int iLimit;\n    int ii;\n    int nZero = 0;\n\n    /* Currently iOff points to the first byte of a varint. This block \n    ** decrements iOff until it points to the first byte of the previous \n    ** varint. Taking care not to read any memory locations that occur\n    ** before the buffer in memory.  */\n    iLimit = (iOff>9 ? iOff-9 : 0);\n    for(iOff--; iOff>iLimit; iOff--){\n      if( (a[iOff-1] & 0x80)==0 ) break;\n    }\n\n    fts5GetVarint(&a[iOff], (u64*)&iVal);\n    pLvl->iRowid -= iVal;\n    pLvl->iLeafPgno--;\n\n    /* Skip backwards past any 0x00 varints. */\n    for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){\n      nZero++;\n    }\n    if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){\n      /* The byte immediately before the last 0x00 byte has the 0x80 bit\n      ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80\n      ** bytes before a[ii]. */\n      int bZero = 0;              /* True if last 0x00 counts */\n      if( (ii-8)>=pLvl->iFirstOff ){\n        int j;\n        for(j=1; j<=8 && (a[ii-j] & 0x80); j++);\n        bZero = (j>8);\n      }\n      if( bZero==0 ) nZero--;\n    }\n    pLvl->iLeafPgno -= nZero;\n    pLvl->iOff = iOff - nZero;\n  }\n\n  return pLvl->bEof;\n}\n\nstatic int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){\n  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];\n\n  assert( iLvl<pIter->nLvl );\n  if( fts5DlidxLvlPrev(pLvl) ){\n    if( (iLvl+1) < pIter->nLvl ){\n      fts5DlidxIterPrevR(p, pIter, iLvl+1);\n      if( pLvl[1].bEof==0 ){\n        fts5DataRelease(pLvl->pData);\n        memset(pLvl, 0, sizeof(Fts5DlidxLvl));\n        pLvl->pData = fts5DataRead(p, \n            FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)\n        );\n        if( pLvl->pData ){\n          while( fts5DlidxLvlNext(pLvl)==0 );\n          pLvl->bEof = 0;\n        }\n      }\n    }\n  }\n\n  return pIter->aLvl[0].bEof;\n}\nstatic int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){\n  return fts5DlidxIterPrevR(p, pIter, 0);\n}\n\n/*\n** Free a doclist-index iterator object allocated by fts5DlidxIterInit().\n*/\nstatic void fts5DlidxIterFree(Fts5DlidxIter *pIter){\n  if( pIter ){\n    int i;\n    for(i=0; i<pIter->nLvl; i++){\n      fts5DataRelease(pIter->aLvl[i].pData);\n    }\n    sqlite3_free(pIter);\n  }\n}\n\nstatic Fts5DlidxIter *fts5DlidxIterInit(\n  Fts5Index *p,                   /* Fts5 Backend to iterate within */\n  int bRev,                       /* True for ORDER BY ASC */\n  int iSegid,                     /* Segment id */\n  int iLeafPg                     /* Leaf page number to load dlidx for */\n){\n  Fts5DlidxIter *pIter = 0;\n  int i;\n  int bDone = 0;\n\n  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){\n    sqlite3_int64 nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);\n    Fts5DlidxIter *pNew;\n\n    pNew = (Fts5DlidxIter*)sqlite3_realloc64(pIter, nByte);\n    if( pNew==0 ){\n      p->rc = SQLITE_NOMEM;\n    }else{\n      i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);\n      Fts5DlidxLvl *pLvl = &pNew->aLvl[i];\n      pIter = pNew;\n      memset(pLvl, 0, sizeof(Fts5DlidxLvl));\n      pLvl->pData = fts5DataRead(p, iRowid);\n      if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){\n        bDone = 1;\n      }\n      pIter->nLvl = i+1;\n    }\n  }\n\n  if( p->rc==SQLITE_OK ){\n    pIter->iSegid = iSegid;\n    if( bRev==0 ){\n      fts5DlidxIterFirst(pIter);\n    }else{\n      fts5DlidxIterLast(p, pIter);\n    }\n  }\n\n  if( p->rc!=SQLITE_OK ){\n    fts5DlidxIterFree(pIter);\n    pIter = 0;\n  }\n\n  return pIter;\n}\n\nstatic i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){\n  return pIter->aLvl[0].iRowid;\n}\nstatic int fts5DlidxIterPgno(Fts5DlidxIter *pIter){\n  return pIter->aLvl[0].iLeafPgno;\n}\n\n/*\n** Load the next leaf page into the segment iterator.\n*/\nstatic void fts5SegIterNextPage(\n  Fts5Index *p,                   /* FTS5 backend object */\n  Fts5SegIter *pIter              /* Iterator to advance to next page */\n){\n  Fts5Data *pLeaf;\n  Fts5StructureSegment *pSeg = pIter->pSeg;\n  fts5DataRelease(pIter->pLeaf);\n  pIter->iLeafPgno++;\n  if( pIter->pNextLeaf ){\n    pIter->pLeaf = pIter->pNextLeaf;\n    pIter->pNextLeaf = 0;\n  }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){\n    pIter->pLeaf = fts5LeafRead(p, \n        FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)\n    );\n  }else{\n    pIter->pLeaf = 0;\n  }\n  pLeaf = pIter->pLeaf;\n\n  if( pLeaf ){\n    pIter->iPgidxOff = pLeaf->szLeaf;\n    if( fts5LeafIsTermless(pLeaf) ){\n      pIter->iEndofDoclist = pLeaf->nn+1;\n    }else{\n      pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],\n          pIter->iEndofDoclist\n      );\n    }\n  }\n}\n\n/*\n** Argument p points to a buffer containing a varint to be interpreted as a\n** position list size field. Read the varint and return the number of bytes\n** read. Before returning, set *pnSz to the number of bytes in the position\n** list, and *pbDel to true if the delete flag is set, or false otherwise.\n*/\nstatic int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){\n  int nSz;\n  int n = 0;\n  fts5FastGetVarint32(p, n, nSz);\n  assert_nc( nSz>=0 );\n  *pnSz = nSz/2;\n  *pbDel = nSz & 0x0001;\n  return n;\n}\n\n/*\n** Fts5SegIter.iLeafOffset currently points to the first byte of a\n** position-list size field. Read the value of the field and store it\n** in the following variables:\n**\n**   Fts5SegIter.nPos\n**   Fts5SegIter.bDel\n**\n** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the \n** position list content (if any).\n*/\nstatic void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){\n  if( p->rc==SQLITE_OK ){\n    int iOff = pIter->iLeafOffset;  /* Offset to read at */\n    ASSERT_SZLEAF_OK(pIter->pLeaf);\n    if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){\n      int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);\n      pIter->bDel = 0;\n      pIter->nPos = 1;\n      if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){\n        pIter->bDel = 1;\n        iOff++;\n        if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){\n          pIter->nPos = 1;\n          iOff++;\n        }else{\n          pIter->nPos = 0;\n        }\n      }\n    }else{\n      int nSz;\n      fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);\n      pIter->bDel = (nSz & 0x0001);\n      pIter->nPos = nSz>>1;\n      assert_nc( pIter->nPos>=0 );\n    }\n    pIter->iLeafOffset = iOff;\n  }\n}\n\nstatic void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){\n  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */\n  int iOff = pIter->iLeafOffset;\n\n  ASSERT_SZLEAF_OK(pIter->pLeaf);\n  if( iOff>=pIter->pLeaf->szLeaf ){\n    fts5SegIterNextPage(p, pIter);\n    if( pIter->pLeaf==0 ){\n      if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;\n      return;\n    }\n    iOff = 4;\n    a = pIter->pLeaf->p;\n  }\n  iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);\n  pIter->iLeafOffset = iOff;\n}\n\n/*\n** Fts5SegIter.iLeafOffset currently points to the first byte of the \n** \"nSuffix\" field of a term. Function parameter nKeep contains the value\n** of the \"nPrefix\" field (if there was one - it is passed 0 if this is\n** the first term in the segment).\n**\n** This function populates:\n**\n**   Fts5SegIter.term\n**   Fts5SegIter.rowid\n**\n** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of\n** the first position list. The position list belonging to document \n** (Fts5SegIter.iRowid).\n*/\nstatic void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){\n  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */\n  int iOff = pIter->iLeafOffset;  /* Offset to read at */\n  int nNew;                       /* Bytes of new data */\n\n  iOff += fts5GetVarint32(&a[iOff], nNew);\n  if( iOff+nNew>pIter->pLeaf->szLeaf || nKeep>pIter->term.n || nNew==0 ){\n    p->rc = FTS5_CORRUPT;\n    return;\n  }\n  pIter->term.n = nKeep;\n  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);\n  assert( pIter->term.n<=pIter->term.nSpace );\n  iOff += nNew;\n  pIter->iTermLeafOffset = iOff;\n  pIter->iTermLeafPgno = pIter->iLeafPgno;\n  pIter->iLeafOffset = iOff;\n\n  if( pIter->iPgidxOff>=pIter->pLeaf->nn ){\n    pIter->iEndofDoclist = pIter->pLeaf->nn+1;\n  }else{\n    int nExtra;\n    pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);\n    pIter->iEndofDoclist += nExtra;\n  }\n\n  fts5SegIterLoadRowid(p, pIter);\n}\n\nstatic void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);\nstatic void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);\nstatic void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);\n\nstatic void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){\n  if( pIter->flags & FTS5_SEGITER_REVERSE ){\n    pIter->xNext = fts5SegIterNext_Reverse;\n  }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){\n    pIter->xNext = fts5SegIterNext_None;\n  }else{\n    pIter->xNext = fts5SegIterNext;\n  }\n}\n\n/*\n** Initialize the iterator object pIter to iterate through the entries in\n** segment pSeg. The iterator is left pointing to the first entry when \n** this function returns.\n**\n** If an error occurs, Fts5Index.rc is set to an appropriate error code. If \n** an error has already occurred when this function is called, it is a no-op.\n*/\nstatic void fts5SegIterInit(\n  Fts5Index *p,                   /* FTS index object */\n  Fts5StructureSegment *pSeg,     /* Description of segment */\n  Fts5SegIter *pIter              /* Object to populate */\n){\n  if( pSeg->pgnoFirst==0 ){\n    /* This happens if the segment is being used as an input to an incremental\n    ** merge and all data has already been \"trimmed\". See function\n    ** fts5TrimSegments() for details. In this case leave the iterator empty.\n    ** The caller will see the (pIter->pLeaf==0) and assume the iterator is\n    ** at EOF already. */\n    assert( pIter->pLeaf==0 );\n    return;\n  }\n\n  if( p->rc==SQLITE_OK ){\n    memset(pIter, 0, sizeof(*pIter));\n    fts5SegIterSetNext(p, pIter);\n    pIter->pSeg = pSeg;\n    pIter->iLeafPgno = pSeg->pgnoFirst-1;\n    fts5SegIterNextPage(p, pIter);\n  }\n\n  if( p->rc==SQLITE_OK ){\n    pIter->iLeafOffset = 4;\n    assert_nc( pIter->pLeaf->nn>4 );\n    assert_nc( fts5LeafFirstTermOff(pIter->pLeaf)==4 );\n    pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;\n    fts5SegIterLoadTerm(p, pIter, 0);\n    fts5SegIterLoadNPos(p, pIter);\n  }\n}\n\n/*\n** This function is only ever called on iterators created by calls to\n** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.\n**\n** The iterator is in an unusual state when this function is called: the\n** Fts5SegIter.iLeafOffset variable is set to the offset of the start of\n** the position-list size field for the first relevant rowid on the page.\n** Fts5SegIter.rowid is set, but nPos and bDel are not.\n**\n** This function advances the iterator so that it points to the last \n** relevant rowid on the page and, if necessary, initializes the \n** aRowidOffset[] and iRowidOffset variables. At this point the iterator\n** is in its regular state - Fts5SegIter.iLeafOffset points to the first\n** byte of the position list content associated with said rowid.\n*/\nstatic void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){\n  int eDetail = p->pConfig->eDetail;\n  int n = pIter->pLeaf->szLeaf;\n  int i = pIter->iLeafOffset;\n  u8 *a = pIter->pLeaf->p;\n  int iRowidOffset = 0;\n\n  if( n>pIter->iEndofDoclist ){\n    n = pIter->iEndofDoclist;\n  }\n\n  ASSERT_SZLEAF_OK(pIter->pLeaf);\n  while( 1 ){\n    i64 iDelta = 0;\n\n    if( eDetail==FTS5_DETAIL_NONE ){\n      /* todo */\n      if( i<n && a[i]==0 ){\n        i++;\n        if( i<n && a[i]==0 ) i++;\n      }\n    }else{\n      int nPos;\n      int bDummy;\n      i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);\n      i += nPos;\n    }\n    if( i>=n ) break;\n    i += fts5GetVarint(&a[i], (u64*)&iDelta);\n    pIter->iRowid += iDelta;\n\n    /* If necessary, grow the pIter->aRowidOffset[] array. */\n    if( iRowidOffset>=pIter->nRowidOffset ){\n      int nNew = pIter->nRowidOffset + 8;\n      int *aNew = (int*)sqlite3_realloc64(pIter->aRowidOffset,nNew*sizeof(int));\n      if( aNew==0 ){\n        p->rc = SQLITE_NOMEM;\n        break;\n      }\n      pIter->aRowidOffset = aNew;\n      pIter->nRowidOffset = nNew;\n    }\n\n    pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;\n    pIter->iLeafOffset = i;\n  }\n  pIter->iRowidOffset = iRowidOffset;\n  fts5SegIterLoadNPos(p, pIter);\n}\n\n/*\n**\n*/\nstatic void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){\n  assert( pIter->flags & FTS5_SEGITER_REVERSE );\n  assert( pIter->flags & FTS5_SEGITER_ONETERM );\n\n  fts5DataRelease(pIter->pLeaf);\n  pIter->pLeaf = 0;\n  while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){\n    Fts5Data *pNew;\n    pIter->iLeafPgno--;\n    pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(\n          pIter->pSeg->iSegid, pIter->iLeafPgno\n    ));\n    if( pNew ){\n      /* iTermLeafOffset may be equal to szLeaf if the term is the last\n      ** thing on the page - i.e. the first rowid is on the following page.\n      ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */\n      if( pIter->iLeafPgno==pIter->iTermLeafPgno ){\n        assert( pIter->pLeaf==0 );\n        if( pIter->iTermLeafOffset<pNew->szLeaf ){\n          pIter->pLeaf = pNew;\n          pIter->iLeafOffset = pIter->iTermLeafOffset;\n        }\n      }else{\n        int iRowidOff;\n        iRowidOff = fts5LeafFirstRowidOff(pNew);\n        if( iRowidOff ){\n          pIter->pLeaf = pNew;\n          pIter->iLeafOffset = iRowidOff;\n        }\n      }\n\n      if( pIter->pLeaf ){\n        u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];\n        pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);\n        break;\n      }else{\n        fts5DataRelease(pNew);\n      }\n    }\n  }\n\n  if( pIter->pLeaf ){\n    pIter->iEndofDoclist = pIter->pLeaf->nn+1;\n    fts5SegIterReverseInitPage(p, pIter);\n  }\n}\n\n/*\n** Return true if the iterator passed as the second argument currently\n** points to a delete marker. A delete marker is an entry with a 0 byte\n** position-list.\n*/\nstatic int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){\n  Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];\n  return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);\n}\n\n/*\n** Advance iterator pIter to the next entry.\n**\n** This version of fts5SegIterNext() is only used by reverse iterators.\n*/\nstatic void fts5SegIterNext_Reverse(\n  Fts5Index *p,                   /* FTS5 backend object */\n  Fts5SegIter *pIter,             /* Iterator to advance */\n  int *pbUnused                   /* Unused */\n){\n  assert( pIter->flags & FTS5_SEGITER_REVERSE );\n  assert( pIter->pNextLeaf==0 );\n  UNUSED_PARAM(pbUnused);\n\n  if( pIter->iRowidOffset>0 ){\n    u8 *a = pIter->pLeaf->p;\n    int iOff;\n    i64 iDelta;\n\n    pIter->iRowidOffset--;\n    pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];\n    fts5SegIterLoadNPos(p, pIter);\n    iOff = pIter->iLeafOffset;\n    if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){\n      iOff += pIter->nPos;\n    }\n    fts5GetVarint(&a[iOff], (u64*)&iDelta);\n    pIter->iRowid -= iDelta;\n  }else{\n    fts5SegIterReverseNewPage(p, pIter);\n  }\n}\n\n/*\n** Advance iterator pIter to the next entry.\n**\n** This version of fts5SegIterNext() is only used if detail=none and the\n** iterator is not a reverse direction iterator.\n*/\nstatic void fts5SegIterNext_None(\n  Fts5Index *p,                   /* FTS5 backend object */\n  Fts5SegIter *pIter,             /* Iterator to advance */\n  int *pbNewTerm                  /* OUT: Set for new term */\n){\n  int iOff;\n\n  assert( p->rc==SQLITE_OK );\n  assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );\n  assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );\n\n  ASSERT_SZLEAF_OK(pIter->pLeaf);\n  iOff = pIter->iLeafOffset;\n\n  /* Next entry is on the next page */\n  if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){\n    fts5SegIterNextPage(p, pIter);\n    if( p->rc || pIter->pLeaf==0 ) return;\n    pIter->iRowid = 0;\n    iOff = 4;\n  }\n\n  if( iOff<pIter->iEndofDoclist ){\n    /* Next entry is on the current page */\n    i64 iDelta;\n    iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);\n    pIter->iLeafOffset = iOff;\n    pIter->iRowid += iDelta;\n  }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){\n    if( pIter->pSeg ){\n      int nKeep = 0;\n      if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){\n        iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);\n      }\n      pIter->iLeafOffset = iOff;\n      fts5SegIterLoadTerm(p, pIter, nKeep);\n    }else{\n      const u8 *pList = 0;\n      const char *zTerm = 0;\n      int nList;\n      sqlite3Fts5HashScanNext(p->pHash);\n      sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);\n      if( pList==0 ) goto next_none_eof;\n      pIter->pLeaf->p = (u8*)pList;\n      pIter->pLeaf->nn = nList;\n      pIter->pLeaf->szLeaf = nList;\n      pIter->iEndofDoclist = nList;\n      sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);\n      pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);\n    }\n\n    if( pbNewTerm ) *pbNewTerm = 1;\n  }else{\n    goto next_none_eof;\n  }\n\n  fts5SegIterLoadNPos(p, pIter);\n\n  return;\n next_none_eof:\n  fts5DataRelease(pIter->pLeaf);\n  pIter->pLeaf = 0;\n}\n\n\n/*\n** Advance iterator pIter to the next entry. \n**\n** If an error occurs, Fts5Index.rc is set to an appropriate error code. It \n** is not considered an error if the iterator reaches EOF. If an error has \n** already occurred when this function is called, it is a no-op.\n*/\nstatic void fts5SegIterNext(\n  Fts5Index *p,                   /* FTS5 backend object */\n  Fts5SegIter *pIter,             /* Iterator to advance */\n  int *pbNewTerm                  /* OUT: Set for new term */\n){\n  Fts5Data *pLeaf = pIter->pLeaf;\n  int iOff;\n  int bNewTerm = 0;\n  int nKeep = 0;\n  u8 *a;\n  int n;\n\n  assert( pbNewTerm==0 || *pbNewTerm==0 );\n  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );\n\n  /* Search for the end of the position list within the current page. */\n  a = pLeaf->p;\n  n = pLeaf->szLeaf;\n\n  ASSERT_SZLEAF_OK(pLeaf);\n  iOff = pIter->iLeafOffset + pIter->nPos;\n\n  if( iOff<n ){\n    /* The next entry is on the current page. */\n    assert_nc( iOff<=pIter->iEndofDoclist );\n    if( iOff>=pIter->iEndofDoclist ){\n      bNewTerm = 1;\n      if( iOff!=fts5LeafFirstTermOff(pLeaf) ){\n        iOff += fts5GetVarint32(&a[iOff], nKeep);\n      }\n    }else{\n      u64 iDelta;\n      iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);\n      pIter->iRowid += iDelta;\n      assert_nc( iDelta>0 );\n    }\n    pIter->iLeafOffset = iOff;\n\n  }else if( pIter->pSeg==0 ){\n    const u8 *pList = 0;\n    const char *zTerm = 0;\n    int nList = 0;\n    assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );\n    if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){\n      sqlite3Fts5HashScanNext(p->pHash);\n      sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);\n    }\n    if( pList==0 ){\n      fts5DataRelease(pIter->pLeaf);\n      pIter->pLeaf = 0;\n    }else{\n      pIter->pLeaf->p = (u8*)pList;\n      pIter->pLeaf->nn = nList;\n      pIter->pLeaf->szLeaf = nList;\n      pIter->iEndofDoclist = nList+1;\n      sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),\n          (u8*)zTerm);\n      pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);\n      *pbNewTerm = 1;\n    }\n  }else{\n    iOff = 0;\n    /* Next entry is not on the current page */\n    while( iOff==0 ){\n      fts5SegIterNextPage(p, pIter);\n      pLeaf = pIter->pLeaf;\n      if( pLeaf==0 ) break;\n      ASSERT_SZLEAF_OK(pLeaf);\n      if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){\n        iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);\n        pIter->iLeafOffset = iOff;\n\n        if( pLeaf->nn>pLeaf->szLeaf ){\n          pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(\n              &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist\n          );\n        }\n      }\n      else if( pLeaf->nn>pLeaf->szLeaf ){\n        pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(\n            &pLeaf->p[pLeaf->szLeaf], iOff\n        );\n        pIter->iLeafOffset = iOff;\n        pIter->iEndofDoclist = iOff;\n        bNewTerm = 1;\n      }\n      assert_nc( iOff<pLeaf->szLeaf );\n      if( iOff>pLeaf->szLeaf ){\n        p->rc = FTS5_CORRUPT;\n        return;\n      }\n    }\n  }\n\n  /* Check if the iterator is now at EOF. If so, return early. */\n  if( pIter->pLeaf ){\n    if( bNewTerm ){\n      if( pIter->flags & FTS5_SEGITER_ONETERM ){\n        fts5DataRelease(pIter->pLeaf);\n        pIter->pLeaf = 0;\n      }else{\n        fts5SegIterLoadTerm(p, pIter, nKeep);\n        fts5SegIterLoadNPos(p, pIter);\n        if( pbNewTerm ) *pbNewTerm = 1;\n      }\n    }else{\n      /* The following could be done by calling fts5SegIterLoadNPos(). But\n      ** this block is particularly performance critical, so equivalent\n      ** code is inlined. \n      **\n      ** Later: Switched back to fts5SegIterLoadNPos() because it supports\n      ** detail=none mode. Not ideal.\n      */\n      int nSz;\n      assert( p->rc==SQLITE_OK );\n      assert( pIter->iLeafOffset<=pIter->pLeaf->nn );\n      fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);\n      pIter->bDel = (nSz & 0x0001);\n      pIter->nPos = nSz>>1;\n      assert_nc( pIter->nPos>=0 );\n    }\n  }\n}\n\n#define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }\n\n#define fts5IndexSkipVarint(a, iOff) {            \\\n  int iEnd = iOff+9;                              \\\n  while( (a[iOff++] & 0x80) && iOff<iEnd );       \\\n}\n\n/*\n** Iterator pIter currently points to the first rowid in a doclist. This\n** function sets the iterator up so that iterates in reverse order through\n** the doclist.\n*/\nstatic void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){\n  Fts5DlidxIter *pDlidx = pIter->pDlidx;\n  Fts5Data *pLast = 0;\n  int pgnoLast = 0;\n\n  if( pDlidx ){\n    int iSegid = pIter->pSeg->iSegid;\n    pgnoLast = fts5DlidxIterPgno(pDlidx);\n    pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));\n  }else{\n    Fts5Data *pLeaf = pIter->pLeaf;         /* Current leaf data */\n\n    /* Currently, Fts5SegIter.iLeafOffset points to the first byte of\n    ** position-list content for the current rowid. Back it up so that it\n    ** points to the start of the position-list size field. */\n    int iPoslist;\n    if( pIter->iTermLeafPgno==pIter->iLeafPgno ){\n      iPoslist = pIter->iTermLeafOffset;\n    }else{\n      iPoslist = 4;\n    }\n    fts5IndexSkipVarint(pLeaf->p, iPoslist);\n    pIter->iLeafOffset = iPoslist;\n\n    /* If this condition is true then the largest rowid for the current\n    ** term may not be stored on the current page. So search forward to\n    ** see where said rowid really is.  */\n    if( pIter->iEndofDoclist>=pLeaf->szLeaf ){\n      int pgno;\n      Fts5StructureSegment *pSeg = pIter->pSeg;\n\n      /* The last rowid in the doclist may not be on the current page. Search\n      ** forward to find the page containing the last rowid.  */\n      for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){\n        i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);\n        Fts5Data *pNew = fts5DataRead(p, iAbs);\n        if( pNew ){\n          int iRowid, bTermless;\n          iRowid = fts5LeafFirstRowidOff(pNew);\n          bTermless = fts5LeafIsTermless(pNew);\n          if( iRowid ){\n            SWAPVAL(Fts5Data*, pNew, pLast);\n            pgnoLast = pgno;\n          }\n          fts5DataRelease(pNew);\n          if( bTermless==0 ) break;\n        }\n      }\n    }\n  }\n\n  /* If pLast is NULL at this point, then the last rowid for this doclist\n  ** lies on the page currently indicated by the iterator. In this case \n  ** pIter->iLeafOffset is already set to point to the position-list size\n  ** field associated with the first relevant rowid on the page.\n  **\n  ** Or, if pLast is non-NULL, then it is the page that contains the last\n  ** rowid. In this case configure the iterator so that it points to the\n  ** first rowid on this page.\n  */\n  if( pLast ){\n    int iOff;\n    fts5DataRelease(pIter->pLeaf);\n    pIter->pLeaf = pLast;\n    pIter->iLeafPgno = pgnoLast;\n    iOff = fts5LeafFirstRowidOff(pLast);\n    iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);\n    pIter->iLeafOffset = iOff;\n\n    if( fts5LeafIsTermless(pLast) ){\n      pIter->iEndofDoclist = pLast->nn+1;\n    }else{\n      pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);\n    }\n\n  }\n\n  fts5SegIterReverseInitPage(p, pIter);\n}\n\n/*\n** Iterator pIter currently points to the first rowid of a doclist.\n** There is a doclist-index associated with the final term on the current \n** page. If the current term is the last term on the page, load the \n** doclist-index from disk and initialize an iterator at (pIter->pDlidx).\n*/\nstatic void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){\n  int iSeg = pIter->pSeg->iSegid;\n  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);\n  Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */\n\n  assert( pIter->flags & FTS5_SEGITER_ONETERM );\n  assert( pIter->pDlidx==0 );\n\n  /* Check if the current doclist ends on this page. If it does, return\n  ** early without loading the doclist-index (as it belongs to a different\n  ** term. */\n  if( pIter->iTermLeafPgno==pIter->iLeafPgno \n   && pIter->iEndofDoclist<pLeaf->szLeaf \n  ){\n    return;\n  }\n\n  pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);\n}\n\n/*\n** The iterator object passed as the second argument currently contains\n** no valid values except for the Fts5SegIter.pLeaf member variable. This\n** function searches the leaf page for a term matching (pTerm/nTerm).\n**\n** If the specified term is found on the page, then the iterator is left\n** pointing to it. If argument bGe is zero and the term is not found,\n** the iterator is left pointing at EOF.\n**\n** If bGe is non-zero and the specified term is not found, then the\n** iterator is left pointing to the smallest term in the segment that\n** is larger than the specified term, even if this term is not on the\n** current page.\n*/\nstatic void fts5LeafSeek(\n  Fts5Index *p,                   /* Leave any error code here */\n  int bGe,                        /* True for a >= search */\n  Fts5SegIter *pIter,             /* Iterator to seek */\n  const u8 *pTerm, int nTerm      /* Term to search for */\n){\n  int iOff;\n  const u8 *a = pIter->pLeaf->p;\n  int szLeaf = pIter->pLeaf->szLeaf;\n  int n = pIter->pLeaf->nn;\n\n  u32 nMatch = 0;\n  u32 nKeep = 0;\n  u32 nNew = 0;\n  u32 iTermOff;\n  int iPgidx;                     /* Current offset in pgidx */\n  int bEndOfPage = 0;\n\n  assert( p->rc==SQLITE_OK );\n\n  iPgidx = szLeaf;\n  iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);\n  iOff = iTermOff;\n  if( iOff>n ){\n    p->rc = FTS5_CORRUPT;\n    return;\n  }\n\n  while( 1 ){\n\n    /* Figure out how many new bytes are in this term */\n    fts5FastGetVarint32(a, iOff, nNew);\n    if( nKeep<nMatch ){\n      goto search_failed;\n    }\n\n    assert( nKeep>=nMatch );\n    if( nKeep==nMatch ){\n      u32 nCmp;\n      u32 i;\n      nCmp = (u32)MIN(nNew, nTerm-nMatch);\n      for(i=0; i<nCmp; i++){\n        if( a[iOff+i]!=pTerm[nMatch+i] ) break;\n      }\n      nMatch += i;\n\n      if( (u32)nTerm==nMatch ){\n        if( i==nNew ){\n          goto search_success;\n        }else{\n          goto search_failed;\n        }\n      }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){\n        goto search_failed;\n      }\n    }\n\n    if( iPgidx>=n ){\n      bEndOfPage = 1;\n      break;\n    }\n\n    iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);\n    iTermOff += nKeep;\n    iOff = iTermOff;\n\n    if( iOff>=n ){\n      p->rc = FTS5_CORRUPT;\n      return;\n    }\n\n    /* Read the nKeep field of the next term. */\n    fts5FastGetVarint32(a, iOff, nKeep);\n  }\n\n search_failed:\n  if( bGe==0 ){\n    fts5DataRelease(pIter->pLeaf);\n    pIter->pLeaf = 0;\n    return;\n  }else if( bEndOfPage ){\n    do {\n      fts5SegIterNextPage(p, pIter);\n      if( pIter->pLeaf==0 ) return;\n      a = pIter->pLeaf->p;\n      if( fts5LeafIsTermless(pIter->pLeaf)==0 ){\n        iPgidx = pIter->pLeaf->szLeaf;\n        iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);\n        if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){\n          p->rc = FTS5_CORRUPT;\n          return;\n        }else{\n          nKeep = 0;\n          iTermOff = iOff;\n          n = pIter->pLeaf->nn;\n          iOff += fts5GetVarint32(&a[iOff], nNew);\n          break;\n        }\n      }\n    }while( 1 );\n  }\n\n search_success:\n  pIter->iLeafOffset = iOff + nNew;\n  if( pIter->iLeafOffset>n || nNew<1 ){\n    p->rc = FTS5_CORRUPT;\n    return;\n  }\n  pIter->iTermLeafOffset = pIter->iLeafOffset;\n  pIter->iTermLeafPgno = pIter->iLeafPgno;\n\n  fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);\n  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);\n\n  if( iPgidx>=n ){\n    pIter->iEndofDoclist = pIter->pLeaf->nn+1;\n  }else{\n    int nExtra;\n    iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);\n    pIter->iEndofDoclist = iTermOff + nExtra;\n  }\n  pIter->iPgidxOff = iPgidx;\n\n  fts5SegIterLoadRowid(p, pIter);\n  fts5SegIterLoadNPos(p, pIter);\n}\n\nstatic sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){\n  if( p->pIdxSelect==0 ){\n    Fts5Config *pConfig = p->pConfig;\n    fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(\n          \"SELECT pgno FROM '%q'.'%q_idx' WHERE \"\n          \"segid=? AND term<=? ORDER BY term DESC LIMIT 1\",\n          pConfig->zDb, pConfig->zName\n    ));\n  }\n  return p->pIdxSelect;\n}\n\n/*\n** Initialize the object pIter to point to term pTerm/nTerm within segment\n** pSeg. If there is no such term in the index, the iterator is set to EOF.\n**\n** If an error occurs, Fts5Index.rc is set to an appropriate error code. If \n** an error has already occurred when this function is called, it is a no-op.\n*/\nstatic void fts5SegIterSeekInit(\n  Fts5Index *p,                   /* FTS5 backend */\n  const u8 *pTerm, int nTerm,     /* Term to seek to */\n  int flags,                      /* Mask of FTS5INDEX_XXX flags */\n  Fts5StructureSegment *pSeg,     /* Description of segment */\n  Fts5SegIter *pIter              /* Object to populate */\n){\n  int iPg = 1;\n  int bGe = (flags & FTS5INDEX_QUERY_SCAN);\n  int bDlidx = 0;                 /* True if there is a doclist-index */\n  sqlite3_stmt *pIdxSelect = 0;\n\n  assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );\n  assert( pTerm && nTerm );\n  memset(pIter, 0, sizeof(*pIter));\n  pIter->pSeg = pSeg;\n\n  /* This block sets stack variable iPg to the leaf page number that may\n  ** contain term (pTerm/nTerm), if it is present in the segment. */\n  pIdxSelect = fts5IdxSelectStmt(p);\n  if( p->rc ) return;\n  sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);\n  sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);\n  if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){\n    i64 val = sqlite3_column_int(pIdxSelect, 0);\n    iPg = (int)(val>>1);\n    bDlidx = (val & 0x0001);\n  }\n  p->rc = sqlite3_reset(pIdxSelect);\n  sqlite3_bind_null(pIdxSelect, 2);\n\n  if( iPg<pSeg->pgnoFirst ){\n    iPg = pSeg->pgnoFirst;\n    bDlidx = 0;\n  }\n\n  pIter->iLeafPgno = iPg - 1;\n  fts5SegIterNextPage(p, pIter);\n\n  if( pIter->pLeaf ){\n    fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);\n  }\n\n  if( p->rc==SQLITE_OK && bGe==0 ){\n    pIter->flags |= FTS5_SEGITER_ONETERM;\n    if( pIter->pLeaf ){\n      if( flags & FTS5INDEX_QUERY_DESC ){\n        pIter->flags |= FTS5_SEGITER_REVERSE;\n      }\n      if( bDlidx ){\n        fts5SegIterLoadDlidx(p, pIter);\n      }\n      if( flags & FTS5INDEX_QUERY_DESC ){\n        fts5SegIterReverse(p, pIter);\n      }\n    }\n  }\n\n  fts5SegIterSetNext(p, pIter);\n\n  /* Either:\n  **\n  **   1) an error has occurred, or\n  **   2) the iterator points to EOF, or\n  **   3) the iterator points to an entry with term (pTerm/nTerm), or\n  **   4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points\n  **      to an entry with a term greater than or equal to (pTerm/nTerm).\n  */\n  assert_nc( p->rc!=SQLITE_OK                                       /* 1 */\n   || pIter->pLeaf==0                                               /* 2 */\n   || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0          /* 3 */\n   || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0)  /* 4 */\n  );\n}\n\n/*\n** Initialize the object pIter to point to term pTerm/nTerm within the\n** in-memory hash table. If there is no such term in the hash-table, the \n** iterator is set to EOF.\n**\n** If an error occurs, Fts5Index.rc is set to an appropriate error code. If \n** an error has already occurred when this function is called, it is a no-op.\n*/\nstatic void fts5SegIterHashInit(\n  Fts5Index *p,                   /* FTS5 backend */\n  const u8 *pTerm, int nTerm,     /* Term to seek to */\n  int flags,                      /* Mask of FTS5INDEX_XXX flags */\n  Fts5SegIter *pIter              /* Object to populate */\n){\n  int nList = 0;\n  const u8 *z = 0;\n  int n = 0;\n  Fts5Data *pLeaf = 0;\n\n  assert( p->pHash );\n  assert( p->rc==SQLITE_OK );\n\n  if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){\n    const u8 *pList = 0;\n\n    p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);\n    sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);\n    n = (z ? (int)strlen((const char*)z) : 0);\n    if( pList ){\n      pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));\n      if( pLeaf ){\n        pLeaf->p = (u8*)pList;\n      }\n    }\n  }else{\n    p->rc = sqlite3Fts5HashQuery(p->pHash, sizeof(Fts5Data), \n        (const char*)pTerm, nTerm, (void**)&pLeaf, &nList\n    );\n    if( pLeaf ){\n      pLeaf->p = (u8*)&pLeaf[1];\n    }\n    z = pTerm;\n    n = nTerm;\n    pIter->flags |= FTS5_SEGITER_ONETERM;\n  }\n\n  if( pLeaf ){\n    sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);\n    pLeaf->nn = pLeaf->szLeaf = nList;\n    pIter->pLeaf = pLeaf;\n    pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);\n    pIter->iEndofDoclist = pLeaf->nn;\n\n    if( flags & FTS5INDEX_QUERY_DESC ){\n      pIter->flags |= FTS5_SEGITER_REVERSE;\n      fts5SegIterReverseInitPage(p, pIter);\n    }else{\n      fts5SegIterLoadNPos(p, pIter);\n    }\n  }\n\n  fts5SegIterSetNext(p, pIter);\n}\n\n/*\n** Zero the iterator passed as the only argument.\n*/\nstatic void fts5SegIterClear(Fts5SegIter *pIter){\n  fts5BufferFree(&pIter->term);\n  fts5DataRelease(pIter->pLeaf);\n  fts5DataRelease(pIter->pNextLeaf);\n  fts5DlidxIterFree(pIter->pDlidx);\n  sqlite3_free(pIter->aRowidOffset);\n  memset(pIter, 0, sizeof(Fts5SegIter));\n}\n\n#ifdef SQLITE_DEBUG\n\n/*\n** This function is used as part of the big assert() procedure implemented by\n** fts5AssertMultiIterSetup(). It ensures that the result currently stored\n** in *pRes is the correct result of comparing the current positions of the\n** two iterators.\n*/\nstatic void fts5AssertComparisonResult(\n  Fts5Iter *pIter, \n  Fts5SegIter *p1,\n  Fts5SegIter *p2,\n  Fts5CResult *pRes\n){\n  int i1 = p1 - pIter->aSeg;\n  int i2 = p2 - pIter->aSeg;\n\n  if( p1->pLeaf || p2->pLeaf ){\n    if( p1->pLeaf==0 ){\n      assert( pRes->iFirst==i2 );\n    }else if( p2->pLeaf==0 ){\n      assert( pRes->iFirst==i1 );\n    }else{\n      int nMin = MIN(p1->term.n, p2->term.n);\n      int res = fts5Memcmp(p1->term.p, p2->term.p, nMin);\n      if( res==0 ) res = p1->term.n - p2->term.n;\n\n      if( res==0 ){\n        assert( pRes->bTermEq==1 );\n        assert( p1->iRowid!=p2->iRowid );\n        res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;\n      }else{\n        assert( pRes->bTermEq==0 );\n      }\n\n      if( res<0 ){\n        assert( pRes->iFirst==i1 );\n      }else{\n        assert( pRes->iFirst==i2 );\n      }\n    }\n  }\n}\n\n/*\n** This function is a no-op unless SQLITE_DEBUG is defined when this module\n** is compiled. In that case, this function is essentially an assert() \n** statement used to verify that the contents of the pIter->aFirst[] array\n** are correct.\n*/\nstatic void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){\n  if( p->rc==SQLITE_OK ){\n    Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];\n    int i;\n\n    assert( (pFirst->pLeaf==0)==pIter->base.bEof );\n\n    /* Check that pIter->iSwitchRowid is set correctly. */\n    for(i=0; i<pIter->nSeg; i++){\n      Fts5SegIter *p1 = &pIter->aSeg[i];\n      assert( p1==pFirst \n           || p1->pLeaf==0 \n           || fts5BufferCompare(&pFirst->term, &p1->term) \n           || p1->iRowid==pIter->iSwitchRowid\n           || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev\n      );\n    }\n\n    for(i=0; i<pIter->nSeg; i+=2){\n      Fts5SegIter *p1 = &pIter->aSeg[i];\n      Fts5SegIter *p2 = &pIter->aSeg[i+1];\n      Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];\n      fts5AssertComparisonResult(pIter, p1, p2, pRes);\n    }\n\n    for(i=1; i<(pIter->nSeg / 2); i+=2){\n      Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];\n      Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];\n      Fts5CResult *pRes = &pIter->aFirst[i];\n      fts5AssertComparisonResult(pIter, p1, p2, pRes);\n    }\n  }\n}\n#else\n# define fts5AssertMultiIterSetup(x,y)\n#endif\n\n/*\n** Do the comparison necessary to populate pIter->aFirst[iOut].\n**\n** If the returned value is non-zero, then it is the index of an entry\n** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing\n** to a key that is a duplicate of another, higher priority, \n** segment-iterator in the pSeg->aSeg[] array.\n*/\nstatic int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){\n  int i1;                         /* Index of left-hand Fts5SegIter */\n  int i2;                         /* Index of right-hand Fts5SegIter */\n  int iRes;\n  Fts5SegIter *p1;                /* Left-hand Fts5SegIter */\n  Fts5SegIter *p2;                /* Right-hand Fts5SegIter */\n  Fts5CResult *pRes = &pIter->aFirst[iOut];\n\n  assert( iOut<pIter->nSeg && iOut>0 );\n  assert( pIter->bRev==0 || pIter->bRev==1 );\n\n  if( iOut>=(pIter->nSeg/2) ){\n    i1 = (iOut - pIter->nSeg/2) * 2;\n    i2 = i1 + 1;\n  }else{\n    i1 = pIter->aFirst[iOut*2].iFirst;\n    i2 = pIter->aFirst[iOut*2+1].iFirst;\n  }\n  p1 = &pIter->aSeg[i1];\n  p2 = &pIter->aSeg[i2];\n\n  pRes->bTermEq = 0;\n  if( p1->pLeaf==0 ){           /* If p1 is at EOF */\n    iRes = i2;\n  }else if( p2->pLeaf==0 ){     /* If p2 is at EOF */\n    iRes = i1;\n  }else{\n    int res = fts5BufferCompare(&p1->term, &p2->term);\n    if( res==0 ){\n      assert_nc( i2>i1 );\n      assert_nc( i2!=0 );\n      pRes->bTermEq = 1;\n      if( p1->iRowid==p2->iRowid ){\n        p1->bDel = p2->bDel;\n        return i2;\n      }\n      res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;\n    }\n    assert( res!=0 );\n    if( res<0 ){\n      iRes = i1;\n    }else{\n      iRes = i2;\n    }\n  }\n\n  pRes->iFirst = (u16)iRes;\n  return 0;\n}\n\n/*\n** Move the seg-iter so that it points to the first rowid on page iLeafPgno.\n** It is an error if leaf iLeafPgno does not exist or contains no rowids.\n*/\nstatic void fts5SegIterGotoPage(\n  Fts5Index *p,                   /* FTS5 backend object */\n  Fts5SegIter *pIter,             /* Iterator to advance */\n  int iLeafPgno\n){\n  assert( iLeafPgno>pIter->iLeafPgno );\n\n  if( iLeafPgno>pIter->pSeg->pgnoLast ){\n    p->rc = FTS5_CORRUPT;\n  }else{\n    fts5DataRelease(pIter->pNextLeaf);\n    pIter->pNextLeaf = 0;\n    pIter->iLeafPgno = iLeafPgno-1;\n    fts5SegIterNextPage(p, pIter);\n    assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );\n\n    if( p->rc==SQLITE_OK ){\n      int iOff;\n      u8 *a = pIter->pLeaf->p;\n      int n = pIter->pLeaf->szLeaf;\n\n      iOff = fts5LeafFirstRowidOff(pIter->pLeaf);\n      if( iOff<4 || iOff>=n ){\n        p->rc = FTS5_CORRUPT;\n      }else{\n        iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);\n        pIter->iLeafOffset = iOff;\n        fts5SegIterLoadNPos(p, pIter);\n      }\n    }\n  }\n}\n\n/*\n** Advance the iterator passed as the second argument until it is at or \n** past rowid iFrom. Regardless of the value of iFrom, the iterator is\n** always advanced at least once.\n*/\nstatic void fts5SegIterNextFrom(\n  Fts5Index *p,                   /* FTS5 backend object */\n  Fts5SegIter *pIter,             /* Iterator to advance */\n  i64 iMatch                      /* Advance iterator at least this far */\n){\n  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);\n  Fts5DlidxIter *pDlidx = pIter->pDlidx;\n  int iLeafPgno = pIter->iLeafPgno;\n  int bMove = 1;\n\n  assert( pIter->flags & FTS5_SEGITER_ONETERM );\n  assert( pIter->pDlidx );\n  assert( pIter->pLeaf );\n\n  if( bRev==0 ){\n    while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){\n      iLeafPgno = fts5DlidxIterPgno(pDlidx);\n      fts5DlidxIterNext(p, pDlidx);\n    }\n    assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );\n    if( iLeafPgno>pIter->iLeafPgno ){\n      fts5SegIterGotoPage(p, pIter, iLeafPgno);\n      bMove = 0;\n    }\n  }else{\n    assert( pIter->pNextLeaf==0 );\n    assert( iMatch<pIter->iRowid );\n    while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){\n      fts5DlidxIterPrev(p, pDlidx);\n    }\n    iLeafPgno = fts5DlidxIterPgno(pDlidx);\n\n    assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );\n\n    if( iLeafPgno<pIter->iLeafPgno ){\n      pIter->iLeafPgno = iLeafPgno+1;\n      fts5SegIterReverseNewPage(p, pIter);\n      bMove = 0;\n    }\n  }\n\n  do{\n    if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);\n    if( pIter->pLeaf==0 ) break;\n    if( bRev==0 && pIter->iRowid>=iMatch ) break;\n    if( bRev!=0 && pIter->iRowid<=iMatch ) break;\n    bMove = 1;\n  }while( p->rc==SQLITE_OK );\n}\n\n\n/*\n** Free the iterator object passed as the second argument.\n*/\nstatic void fts5MultiIterFree(Fts5Iter *pIter){\n  if( pIter ){\n    int i;\n    for(i=0; i<pIter->nSeg; i++){\n      fts5SegIterClear(&pIter->aSeg[i]);\n    }\n    fts5BufferFree(&pIter->poslist);\n    sqlite3_free(pIter);\n  }\n}\n\nstatic void fts5MultiIterAdvanced(\n  Fts5Index *p,                   /* FTS5 backend to iterate within */\n  Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */\n  int iChanged,                   /* Index of sub-iterator just advanced */\n  int iMinset                     /* Minimum entry in aFirst[] to set */\n){\n  int i;\n  for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){\n    int iEq;\n    if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){\n      Fts5SegIter *pSeg = &pIter->aSeg[iEq];\n      assert( p->rc==SQLITE_OK );\n      pSeg->xNext(p, pSeg, 0);\n      i = pIter->nSeg + iEq;\n    }\n  }\n}\n\n/*\n** Sub-iterator iChanged of iterator pIter has just been advanced. It still\n** points to the same term though - just a different rowid. This function\n** attempts to update the contents of the pIter->aFirst[] accordingly.\n** If it does so successfully, 0 is returned. Otherwise 1.\n**\n** If non-zero is returned, the caller should call fts5MultiIterAdvanced()\n** on the iterator instead. That function does the same as this one, except\n** that it deals with more complicated cases as well.\n*/ \nstatic int fts5MultiIterAdvanceRowid(\n  Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */\n  int iChanged,                   /* Index of sub-iterator just advanced */\n  Fts5SegIter **ppFirst\n){\n  Fts5SegIter *pNew = &pIter->aSeg[iChanged];\n\n  if( pNew->iRowid==pIter->iSwitchRowid\n   || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev\n  ){\n    int i;\n    Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];\n    pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;\n    for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){\n      Fts5CResult *pRes = &pIter->aFirst[i];\n\n      assert( pNew->pLeaf );\n      assert( pRes->bTermEq==0 || pOther->pLeaf );\n\n      if( pRes->bTermEq ){\n        if( pNew->iRowid==pOther->iRowid ){\n          return 1;\n        }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){\n          pIter->iSwitchRowid = pOther->iRowid;\n          pNew = pOther;\n        }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){\n          pIter->iSwitchRowid = pOther->iRowid;\n        }\n      }\n      pRes->iFirst = (u16)(pNew - pIter->aSeg);\n      if( i==1 ) break;\n\n      pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];\n    }\n  }\n\n  *ppFirst = pNew;\n  return 0;\n}\n\n/*\n** Set the pIter->bEof variable based on the state of the sub-iterators.\n*/\nstatic void fts5MultiIterSetEof(Fts5Iter *pIter){\n  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];\n  pIter->base.bEof = pSeg->pLeaf==0;\n  pIter->iSwitchRowid = pSeg->iRowid;\n}\n\n/*\n** Move the iterator to the next entry. \n**\n** If an error occurs, an error code is left in Fts5Index.rc. It is not \n** considered an error if the iterator reaches EOF, or if it is already at \n** EOF when this function is called.\n*/\nstatic void fts5MultiIterNext(\n  Fts5Index *p, \n  Fts5Iter *pIter,\n  int bFrom,                      /* True if argument iFrom is valid */\n  i64 iFrom                       /* Advance at least as far as this */\n){\n  int bUseFrom = bFrom;\n  assert( pIter->base.bEof==0 );\n  while( p->rc==SQLITE_OK ){\n    int iFirst = pIter->aFirst[1].iFirst;\n    int bNewTerm = 0;\n    Fts5SegIter *pSeg = &pIter->aSeg[iFirst];\n    assert( p->rc==SQLITE_OK );\n    if( bUseFrom && pSeg->pDlidx ){\n      fts5SegIterNextFrom(p, pSeg, iFrom);\n    }else{\n      pSeg->xNext(p, pSeg, &bNewTerm);\n    }\n\n    if( pSeg->pLeaf==0 || bNewTerm \n     || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)\n    ){\n      fts5MultiIterAdvanced(p, pIter, iFirst, 1);\n      fts5MultiIterSetEof(pIter);\n      pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];\n      if( pSeg->pLeaf==0 ) return;\n    }\n\n    fts5AssertMultiIterSetup(p, pIter);\n    assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );\n    if( pIter->bSkipEmpty==0 || pSeg->nPos ){\n      pIter->xSetOutputs(pIter, pSeg);\n      return;\n    }\n    bUseFrom = 0;\n  }\n}\n\nstatic void fts5MultiIterNext2(\n  Fts5Index *p, \n  Fts5Iter *pIter,\n  int *pbNewTerm                  /* OUT: True if *might* be new term */\n){\n  assert( pIter->bSkipEmpty );\n  if( p->rc==SQLITE_OK ){\n    *pbNewTerm = 0;\n    do{\n      int iFirst = pIter->aFirst[1].iFirst;\n      Fts5SegIter *pSeg = &pIter->aSeg[iFirst];\n      int bNewTerm = 0;\n\n      assert( p->rc==SQLITE_OK );\n      pSeg->xNext(p, pSeg, &bNewTerm);\n      if( pSeg->pLeaf==0 || bNewTerm \n       || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)\n      ){\n        fts5MultiIterAdvanced(p, pIter, iFirst, 1);\n        fts5MultiIterSetEof(pIter);\n        *pbNewTerm = 1;\n      }\n      fts5AssertMultiIterSetup(p, pIter);\n\n    }while( fts5MultiIterIsEmpty(p, pIter) );\n  }\n}\n\nstatic void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){\n  UNUSED_PARAM2(pUnused1, pUnused2);\n}\n\nstatic Fts5Iter *fts5MultiIterAlloc(\n  Fts5Index *p,                   /* FTS5 backend to iterate within */\n  int nSeg\n){\n  Fts5Iter *pNew;\n  int nSlot;                      /* Power of two >= nSeg */\n\n  for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);\n  pNew = fts5IdxMalloc(p, \n      sizeof(Fts5Iter) +                  /* pNew */\n      sizeof(Fts5SegIter) * (nSlot-1) +   /* pNew->aSeg[] */\n      sizeof(Fts5CResult) * nSlot         /* pNew->aFirst[] */\n  );\n  if( pNew ){\n    pNew->nSeg = nSlot;\n    pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];\n    pNew->pIndex = p;\n    pNew->xSetOutputs = fts5IterSetOutputs_Noop;\n  }\n  return pNew;\n}\n\nstatic void fts5PoslistCallback(\n  Fts5Index *pUnused, \n  void *pContext, \n  const u8 *pChunk, int nChunk\n){\n  UNUSED_PARAM(pUnused);\n  assert_nc( nChunk>=0 );\n  if( nChunk>0 ){\n    fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);\n  }\n}\n\ntypedef struct PoslistCallbackCtx PoslistCallbackCtx;\nstruct PoslistCallbackCtx {\n  Fts5Buffer *pBuf;               /* Append to this buffer */\n  Fts5Colset *pColset;            /* Restrict matches to this column */\n  int eState;                     /* See above */\n};\n\ntypedef struct PoslistOffsetsCtx PoslistOffsetsCtx;\nstruct PoslistOffsetsCtx {\n  Fts5Buffer *pBuf;               /* Append to this buffer */\n  Fts5Colset *pColset;            /* Restrict matches to this column */\n  int iRead;\n  int iWrite;\n};\n\n/*\n** TODO: Make this more efficient!\n*/\nstatic int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){\n  int i;\n  for(i=0; i<pColset->nCol; i++){\n    if( pColset->aiCol[i]==iCol ) return 1;\n  }\n  return 0;\n}\n\nstatic void fts5PoslistOffsetsCallback(\n  Fts5Index *pUnused, \n  void *pContext, \n  const u8 *pChunk, int nChunk\n){\n  PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;\n  UNUSED_PARAM(pUnused);\n  assert_nc( nChunk>=0 );\n  if( nChunk>0 ){\n    int i = 0;\n    while( i<nChunk ){\n      int iVal;\n      i += fts5GetVarint32(&pChunk[i], iVal);\n      iVal += pCtx->iRead - 2;\n      pCtx->iRead = iVal;\n      if( fts5IndexColsetTest(pCtx->pColset, iVal) ){\n        fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);\n        pCtx->iWrite = iVal;\n      }\n    }\n  }\n}\n\nstatic void fts5PoslistFilterCallback(\n  Fts5Index *pUnused,\n  void *pContext, \n  const u8 *pChunk, int nChunk\n){\n  PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;\n  UNUSED_PARAM(pUnused);\n  assert_nc( nChunk>=0 );\n  if( nChunk>0 ){\n    /* Search through to find the first varint with value 1. This is the\n    ** start of the next columns hits. */\n    int i = 0;\n    int iStart = 0;\n\n    if( pCtx->eState==2 ){\n      int iCol;\n      fts5FastGetVarint32(pChunk, i, iCol);\n      if( fts5IndexColsetTest(pCtx->pColset, iCol) ){\n        pCtx->eState = 1;\n        fts5BufferSafeAppendVarint(pCtx->pBuf, 1);\n      }else{\n        pCtx->eState = 0;\n      }\n    }\n\n    do {\n      while( i<nChunk && pChunk[i]!=0x01 ){\n        while( pChunk[i] & 0x80 ) i++;\n        i++;\n      }\n      if( pCtx->eState ){\n        fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);\n      }\n      if( i<nChunk ){\n        int iCol;\n        iStart = i;\n        i++;\n        if( i>=nChunk ){\n          pCtx->eState = 2;\n        }else{\n          fts5FastGetVarint32(pChunk, i, iCol);\n          pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);\n          if( pCtx->eState ){\n            fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);\n            iStart = i;\n          }\n        }\n      }\n    }while( i<nChunk );\n  }\n}\n\nstatic void fts5ChunkIterate(\n  Fts5Index *p,                   /* Index object */\n  Fts5SegIter *pSeg,              /* Poslist of this iterator */\n  void *pCtx,                     /* Context pointer for xChunk callback */\n  void (*xChunk)(Fts5Index*, void*, const u8*, int)\n){\n  int nRem = pSeg->nPos;          /* Number of bytes still to come */\n  Fts5Data *pData = 0;\n  u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];\n  int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);\n  int pgno = pSeg->iLeafPgno;\n  int pgnoSave = 0;\n\n  /* This function does notmwork with detail=none databases. */\n  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );\n\n  if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){\n    pgnoSave = pgno+1;\n  }\n\n  while( 1 ){\n    xChunk(p, pCtx, pChunk, nChunk);\n    nRem -= nChunk;\n    fts5DataRelease(pData);\n    if( nRem<=0 ){\n      break;\n    }else{\n      pgno++;\n      pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));\n      if( pData==0 ) break;\n      pChunk = &pData->p[4];\n      nChunk = MIN(nRem, pData->szLeaf - 4);\n      if( pgno==pgnoSave ){\n        assert( pSeg->pNextLeaf==0 );\n        pSeg->pNextLeaf = pData;\n        pData = 0;\n      }\n    }\n  }\n}\n\n/*\n** Iterator pIter currently points to a valid entry (not EOF). This\n** function appends the position list data for the current entry to\n** buffer pBuf. It does not make a copy of the position-list size\n** field.\n*/\nstatic void fts5SegiterPoslist(\n  Fts5Index *p,\n  Fts5SegIter *pSeg,\n  Fts5Colset *pColset,\n  Fts5Buffer *pBuf\n){\n  if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos+FTS5_DATA_ZERO_PADDING) ){\n    memset(&pBuf->p[pBuf->n+pSeg->nPos], 0, FTS5_DATA_ZERO_PADDING);\n    if( pColset==0 ){\n      fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);\n    }else{\n      if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){\n        PoslistCallbackCtx sCtx;\n        sCtx.pBuf = pBuf;\n        sCtx.pColset = pColset;\n        sCtx.eState = fts5IndexColsetTest(pColset, 0);\n        assert( sCtx.eState==0 || sCtx.eState==1 );\n        fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);\n      }else{\n        PoslistOffsetsCtx sCtx;\n        memset(&sCtx, 0, sizeof(sCtx));\n        sCtx.pBuf = pBuf;\n        sCtx.pColset = pColset;\n        fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);\n      }\n    }\n  }\n}\n\n/*\n** IN/OUT parameter (*pa) points to a position list n bytes in size. If\n** the position list contains entries for column iCol, then (*pa) is set\n** to point to the sub-position-list for that column and the number of\n** bytes in it returned. Or, if the argument position list does not\n** contain any entries for column iCol, return 0.\n*/\nstatic int fts5IndexExtractCol(\n  const u8 **pa,                  /* IN/OUT: Pointer to poslist */\n  int n,                          /* IN: Size of poslist in bytes */\n  int iCol                        /* Column to extract from poslist */\n){\n  int iCurrent = 0;               /* Anything before the first 0x01 is col 0 */\n  const u8 *p = *pa;\n  const u8 *pEnd = &p[n];         /* One byte past end of position list */\n\n  while( iCol>iCurrent ){\n    /* Advance pointer p until it points to pEnd or an 0x01 byte that is\n    ** not part of a varint. Note that it is not possible for a negative\n    ** or extremely large varint to occur within an uncorrupted position \n    ** list. So the last byte of each varint may be assumed to have a clear\n    ** 0x80 bit.  */\n    while( *p!=0x01 ){\n      while( *p++ & 0x80 );\n      if( p>=pEnd ) return 0;\n    }\n    *pa = p++;\n    iCurrent = *p++;\n    if( iCurrent & 0x80 ){\n      p--;\n      p += fts5GetVarint32(p, iCurrent);\n    }\n  }\n  if( iCol!=iCurrent ) return 0;\n\n  /* Advance pointer p until it points to pEnd or an 0x01 byte that is\n  ** not part of a varint */\n  while( p<pEnd && *p!=0x01 ){\n    while( *p++ & 0x80 );\n  }\n\n  return p - (*pa);\n}\n\nstatic void fts5IndexExtractColset(\n  int *pRc,\n  Fts5Colset *pColset,            /* Colset to filter on */\n  const u8 *pPos, int nPos,       /* Position list */\n  Fts5Buffer *pBuf                /* Output buffer */\n){\n  if( *pRc==SQLITE_OK ){\n    int i;\n    fts5BufferZero(pBuf);\n    for(i=0; i<pColset->nCol; i++){\n      const u8 *pSub = pPos;\n      int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);\n      if( nSub ){\n        fts5BufferAppendBlob(pRc, pBuf, nSub, pSub);\n      }\n    }\n  }\n}\n\n/*\n** xSetOutputs callback used by detail=none tables.\n*/\nstatic void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){\n  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );\n  pIter->base.iRowid = pSeg->iRowid;\n  pIter->base.nData = pSeg->nPos;\n}\n\n/*\n** xSetOutputs callback used by detail=full and detail=col tables when no\n** column filters are specified.\n*/\nstatic void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){\n  pIter->base.iRowid = pSeg->iRowid;\n  pIter->base.nData = pSeg->nPos;\n\n  assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );\n  assert( pIter->pColset==0 );\n\n  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){\n    /* All data is stored on the current page. Populate the output \n    ** variables to point into the body of the page object. */\n    pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];\n  }else{\n    /* The data is distributed over two or more pages. Copy it into the\n    ** Fts5Iter.poslist buffer and then set the output pointer to point\n    ** to this buffer.  */\n    fts5BufferZero(&pIter->poslist);\n    fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);\n    pIter->base.pData = pIter->poslist.p;\n  }\n}\n\n/*\n** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match\n** against no columns at all).\n*/\nstatic void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){\n  UNUSED_PARAM(pSeg);\n  pIter->base.nData = 0;\n}\n\n/*\n** xSetOutputs callback used by detail=col when there is a column filter\n** and there are 100 or more columns. Also called as a fallback from\n** fts5IterSetOutputs_Col100 if the column-list spans more than one page.\n*/\nstatic void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){\n  fts5BufferZero(&pIter->poslist);\n  fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);\n  pIter->base.iRowid = pSeg->iRowid;\n  pIter->base.pData = pIter->poslist.p;\n  pIter->base.nData = pIter->poslist.n;\n}\n\n/*\n** xSetOutputs callback used when: \n**\n**   * detail=col,\n**   * there is a column filter, and\n**   * the table contains 100 or fewer columns. \n**\n** The last point is to ensure all column numbers are stored as \n** single-byte varints.\n*/\nstatic void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){\n\n  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );\n  assert( pIter->pColset );\n\n  if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){\n    fts5IterSetOutputs_Col(pIter, pSeg);\n  }else{\n    u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];\n    u8 *pEnd = (u8*)&a[pSeg->nPos]; \n    int iPrev = 0;\n    int *aiCol = pIter->pColset->aiCol;\n    int *aiColEnd = &aiCol[pIter->pColset->nCol];\n\n    u8 *aOut = pIter->poslist.p;\n    int iPrevOut = 0;\n\n    pIter->base.iRowid = pSeg->iRowid;\n\n    while( a<pEnd ){\n      iPrev += (int)a++[0] - 2;\n      while( *aiCol<iPrev ){\n        aiCol++;\n        if( aiCol==aiColEnd ) goto setoutputs_col_out;\n      }\n      if( *aiCol==iPrev ){\n        *aOut++ = (u8)((iPrev - iPrevOut) + 2);\n        iPrevOut = iPrev;\n      }\n    }\n\nsetoutputs_col_out:\n    pIter->base.pData = pIter->poslist.p;\n    pIter->base.nData = aOut - pIter->poslist.p;\n  }\n}\n\n/*\n** xSetOutputs callback used by detail=full when there is a column filter.\n*/\nstatic void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){\n  Fts5Colset *pColset = pIter->pColset;\n  pIter->base.iRowid = pSeg->iRowid;\n\n  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );\n  assert( pColset );\n\n  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){\n    /* All data is stored on the current page. Populate the output \n    ** variables to point into the body of the page object. */\n    const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];\n    if( pColset->nCol==1 ){\n      pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);\n      pIter->base.pData = a;\n    }else{\n      int *pRc = &pIter->pIndex->rc;\n      fts5BufferZero(&pIter->poslist);\n      fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist);\n      pIter->base.pData = pIter->poslist.p;\n      pIter->base.nData = pIter->poslist.n;\n    }\n  }else{\n    /* The data is distributed over two or more pages. Copy it into the\n    ** Fts5Iter.poslist buffer and then set the output pointer to point\n    ** to this buffer.  */\n    fts5BufferZero(&pIter->poslist);\n    fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);\n    pIter->base.pData = pIter->poslist.p;\n    pIter->base.nData = pIter->poslist.n;\n  }\n}\n\nstatic void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){\n  if( *pRc==SQLITE_OK ){\n    Fts5Config *pConfig = pIter->pIndex->pConfig;\n    if( pConfig->eDetail==FTS5_DETAIL_NONE ){\n      pIter->xSetOutputs = fts5IterSetOutputs_None;\n    }\n\n    else if( pIter->pColset==0 ){\n      pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;\n    }\n\n    else if( pIter->pColset->nCol==0 ){\n      pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;\n    }\n\n    else if( pConfig->eDetail==FTS5_DETAIL_FULL ){\n      pIter->xSetOutputs = fts5IterSetOutputs_Full;\n    }\n\n    else{\n      assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );\n      if( pConfig->nCol<=100 ){\n        pIter->xSetOutputs = fts5IterSetOutputs_Col100;\n        sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);\n      }else{\n        pIter->xSetOutputs = fts5IterSetOutputs_Col;\n      }\n    }\n  }\n}\n\n\n/*\n** Allocate a new Fts5Iter object.\n**\n** The new object will be used to iterate through data in structure pStruct.\n** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel\n** is zero or greater, data from the first nSegment segments on level iLevel\n** is merged.\n**\n** The iterator initially points to the first term/rowid entry in the \n** iterated data.\n*/\nstatic void fts5MultiIterNew(\n  Fts5Index *p,                   /* FTS5 backend to iterate within */\n  Fts5Structure *pStruct,         /* Structure of specific index */\n  int flags,                      /* FTS5INDEX_QUERY_XXX flags */\n  Fts5Colset *pColset,            /* Colset to filter on (or NULL) */\n  const u8 *pTerm, int nTerm,     /* Term to seek to (or NULL/0) */\n  int iLevel,                     /* Level to iterate (-1 for all) */\n  int nSegment,                   /* Number of segments to merge (iLevel>=0) */\n  Fts5Iter **ppOut                /* New object */\n){\n  int nSeg = 0;                   /* Number of segment-iters in use */\n  int iIter = 0;                  /* */\n  int iSeg;                       /* Used to iterate through segments */\n  Fts5StructureLevel *pLvl;\n  Fts5Iter *pNew;\n\n  assert( (pTerm==0 && nTerm==0) || iLevel<0 );\n\n  /* Allocate space for the new multi-seg-iterator. */\n  if( p->rc==SQLITE_OK ){\n    if( iLevel<0 ){\n      assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );\n      nSeg = pStruct->nSegment;\n      nSeg += (p->pHash ? 1 : 0);\n    }else{\n      nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);\n    }\n  }\n  *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);\n  if( pNew==0 ) return;\n  pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));\n  pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));\n  pNew->pColset = pColset;\n  if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){\n    fts5IterSetOutputCb(&p->rc, pNew);\n  }\n\n  /* Initialize each of the component segment iterators. */\n  if( p->rc==SQLITE_OK ){\n    if( iLevel<0 ){\n      Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];\n      if( p->pHash ){\n        /* Add a segment iterator for the current contents of the hash table. */\n        Fts5SegIter *pIter = &pNew->aSeg[iIter++];\n        fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);\n      }\n      for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){\n        for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){\n          Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];\n          Fts5SegIter *pIter = &pNew->aSeg[iIter++];\n          if( pTerm==0 ){\n            fts5SegIterInit(p, pSeg, pIter);\n          }else{\n            fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);\n          }\n        }\n      }\n    }else{\n      pLvl = &pStruct->aLevel[iLevel];\n      for(iSeg=nSeg-1; iSeg>=0; iSeg--){\n        fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);\n      }\n    }\n    assert( iIter==nSeg );\n  }\n\n  /* If the above was successful, each component iterators now points \n  ** to the first entry in its segment. In this case initialize the \n  ** aFirst[] array. Or, if an error has occurred, free the iterator\n  ** object and set the output variable to NULL.  */\n  if( p->rc==SQLITE_OK ){\n    for(iIter=pNew->nSeg-1; iIter>0; iIter--){\n      int iEq;\n      if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){\n        Fts5SegIter *pSeg = &pNew->aSeg[iEq];\n        if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);\n        fts5MultiIterAdvanced(p, pNew, iEq, iIter);\n      }\n    }\n    fts5MultiIterSetEof(pNew);\n    fts5AssertMultiIterSetup(p, pNew);\n\n    if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){\n      fts5MultiIterNext(p, pNew, 0, 0);\n    }else if( pNew->base.bEof==0 ){\n      Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];\n      pNew->xSetOutputs(pNew, pSeg);\n    }\n\n  }else{\n    fts5MultiIterFree(pNew);\n    *ppOut = 0;\n  }\n}\n\n/*\n** Create an Fts5Iter that iterates through the doclist provided\n** as the second argument.\n*/\nstatic void fts5MultiIterNew2(\n  Fts5Index *p,                   /* FTS5 backend to iterate within */\n  Fts5Data *pData,                /* Doclist to iterate through */\n  int bDesc,                      /* True for descending rowid order */\n  Fts5Iter **ppOut                /* New object */\n){\n  Fts5Iter *pNew;\n  pNew = fts5MultiIterAlloc(p, 2);\n  if( pNew ){\n    Fts5SegIter *pIter = &pNew->aSeg[1];\n\n    pIter->flags = FTS5_SEGITER_ONETERM;\n    if( pData->szLeaf>0 ){\n      pIter->pLeaf = pData;\n      pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);\n      pIter->iEndofDoclist = pData->nn;\n      pNew->aFirst[1].iFirst = 1;\n      if( bDesc ){\n        pNew->bRev = 1;\n        pIter->flags |= FTS5_SEGITER_REVERSE;\n        fts5SegIterReverseInitPage(p, pIter);\n      }else{\n        fts5SegIterLoadNPos(p, pIter);\n      }\n      pData = 0;\n    }else{\n      pNew->base.bEof = 1;\n    }\n    fts5SegIterSetNext(p, pIter);\n\n    *ppOut = pNew;\n  }\n\n  fts5DataRelease(pData);\n}\n\n/*\n** Return true if the iterator is at EOF or if an error has occurred. \n** False otherwise.\n*/\nstatic int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){\n  assert( p->rc \n      || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof \n  );\n  return (p->rc || pIter->base.bEof);\n}\n\n/*\n** Return the rowid of the entry that the iterator currently points\n** to. If the iterator points to EOF when this function is called the\n** results are undefined.\n*/\nstatic i64 fts5MultiIterRowid(Fts5Iter *pIter){\n  assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );\n  return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;\n}\n\n/*\n** Move the iterator to the next entry at or following iMatch.\n*/\nstatic void fts5MultiIterNextFrom(\n  Fts5Index *p, \n  Fts5Iter *pIter, \n  i64 iMatch\n){\n  while( 1 ){\n    i64 iRowid;\n    fts5MultiIterNext(p, pIter, 1, iMatch);\n    if( fts5MultiIterEof(p, pIter) ) break;\n    iRowid = fts5MultiIterRowid(pIter);\n    if( pIter->bRev==0 && iRowid>=iMatch ) break;\n    if( pIter->bRev!=0 && iRowid<=iMatch ) break;\n  }\n}\n\n/*\n** Return a pointer to a buffer containing the term associated with the \n** entry that the iterator currently points to.\n*/\nstatic const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){\n  Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];\n  *pn = p->term.n;\n  return p->term.p;\n}\n\n/*\n** Allocate a new segment-id for the structure pStruct. The new segment\n** id must be between 1 and 65335 inclusive, and must not be used by \n** any currently existing segment. If a free segment id cannot be found,\n** SQLITE_FULL is returned.\n**\n** If an error has already occurred, this function is a no-op. 0 is \n** returned in this case.\n*/\nstatic int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){\n  int iSegid = 0;\n\n  if( p->rc==SQLITE_OK ){\n    if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){\n      p->rc = SQLITE_FULL;\n    }else{\n      /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following\n      ** array is 63 elements, or 252 bytes, in size.  */\n      u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];\n      int iLvl, iSeg;\n      int i;\n      u32 mask;\n      memset(aUsed, 0, sizeof(aUsed));\n      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){\n        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){\n          int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;\n          if( iId<=FTS5_MAX_SEGMENT && iId>0 ){\n            aUsed[(iId-1) / 32] |= (u32)1 << ((iId-1) % 32);\n          }\n        }\n      }\n\n      for(i=0; aUsed[i]==0xFFFFFFFF; i++);\n      mask = aUsed[i];\n      for(iSegid=0; mask & ((u32)1 << iSegid); iSegid++);\n      iSegid += 1 + i*32;\n\n#ifdef SQLITE_DEBUG\n      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){\n        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){\n          assert_nc( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );\n        }\n      }\n      assert_nc( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );\n\n      {\n        sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);\n        if( p->rc==SQLITE_OK ){\n          u8 aBlob[2] = {0xff, 0xff};\n          sqlite3_bind_int(pIdxSelect, 1, iSegid);\n          sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);\n          assert_nc( sqlite3_step(pIdxSelect)!=SQLITE_ROW );\n          p->rc = sqlite3_reset(pIdxSelect);\n          sqlite3_bind_null(pIdxSelect, 2);\n        }\n      }\n#endif\n    }\n  }\n\n  return iSegid;\n}\n\n/*\n** Discard all data currently cached in the hash-tables.\n*/\nstatic void fts5IndexDiscardData(Fts5Index *p){\n  assert( p->pHash || p->nPendingData==0 );\n  if( p->pHash ){\n    sqlite3Fts5HashClear(p->pHash);\n    p->nPendingData = 0;\n  }\n}\n\n/*\n** Return the size of the prefix, in bytes, that buffer \n** (pNew/<length-unknown>) shares with buffer (pOld/nOld).\n**\n** Buffer (pNew/<length-unknown>) is guaranteed to be greater \n** than buffer (pOld/nOld).\n*/\nstatic int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){\n  int i;\n  for(i=0; i<nOld; i++){\n    if( pOld[i]!=pNew[i] ) break;\n  }\n  return i;\n}\n\nstatic void fts5WriteDlidxClear(\n  Fts5Index *p, \n  Fts5SegWriter *pWriter,\n  int bFlush                      /* If true, write dlidx to disk */\n){\n  int i;\n  assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );\n  for(i=0; i<pWriter->nDlidx; i++){\n    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];\n    if( pDlidx->buf.n==0 ) break;\n    if( bFlush ){\n      assert( pDlidx->pgno!=0 );\n      fts5DataWrite(p, \n          FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),\n          pDlidx->buf.p, pDlidx->buf.n\n      );\n    }\n    sqlite3Fts5BufferZero(&pDlidx->buf);\n    pDlidx->bPrevValid = 0;\n  }\n}\n\n/*\n** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.\n** Any new array elements are zeroed before returning.\n*/\nstatic int fts5WriteDlidxGrow(\n  Fts5Index *p,\n  Fts5SegWriter *pWriter,\n  int nLvl\n){\n  if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){\n    Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc64(\n        pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl\n    );\n    if( aDlidx==0 ){\n      p->rc = SQLITE_NOMEM;\n    }else{\n      size_t nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);\n      memset(&aDlidx[pWriter->nDlidx], 0, nByte);\n      pWriter->aDlidx = aDlidx;\n      pWriter->nDlidx = nLvl;\n    }\n  }\n  return p->rc;\n}\n\n/*\n** If the current doclist-index accumulating in pWriter->aDlidx[] is large\n** enough, flush it to disk and return 1. Otherwise discard it and return\n** zero.\n*/\nstatic int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){\n  int bFlag = 0;\n\n  /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written\n  ** to the database, also write the doclist-index to disk.  */\n  if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){\n    bFlag = 1;\n  }\n  fts5WriteDlidxClear(p, pWriter, bFlag);\n  pWriter->nEmpty = 0;\n  return bFlag;\n}\n\n/*\n** This function is called whenever processing of the doclist for the \n** last term on leaf page (pWriter->iBtPage) is completed. \n**\n** The doclist-index for that term is currently stored in-memory within the\n** Fts5SegWriter.aDlidx[] array. If it is large enough, this function\n** writes it out to disk. Or, if it is too small to bother with, discards\n** it.\n**\n** Fts5SegWriter.btterm currently contains the first term on page iBtPage.\n*/\nstatic void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){\n  int bFlag;\n\n  assert( pWriter->iBtPage || pWriter->nEmpty==0 );\n  if( pWriter->iBtPage==0 ) return;\n  bFlag = fts5WriteFlushDlidx(p, pWriter);\n\n  if( p->rc==SQLITE_OK ){\n    const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:\"\");\n    /* The following was already done in fts5WriteInit(): */\n    /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */\n    sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);\n    sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));\n    sqlite3_step(p->pIdxWriter);\n    p->rc = sqlite3_reset(p->pIdxWriter);\n    sqlite3_bind_null(p->pIdxWriter, 2);\n  }\n  pWriter->iBtPage = 0;\n}\n\n/*\n** This is called once for each leaf page except the first that contains\n** at least one term. Argument (nTerm/pTerm) is the split-key - a term that\n** is larger than all terms written to earlier leaves, and equal to or\n** smaller than the first term on the new leaf.\n**\n** If an error occurs, an error code is left in Fts5Index.rc. If an error\n** has already occurred when this function is called, it is a no-op.\n*/\nstatic void fts5WriteBtreeTerm(\n  Fts5Index *p,                   /* FTS5 backend object */\n  Fts5SegWriter *pWriter,         /* Writer object */\n  int nTerm, const u8 *pTerm      /* First term on new page */\n){\n  fts5WriteFlushBtree(p, pWriter);\n  if( p->rc==SQLITE_OK ){\n    fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);\n    pWriter->iBtPage = pWriter->writer.pgno;\n  }\n}\n\n/*\n** This function is called when flushing a leaf page that contains no\n** terms at all to disk.\n*/\nstatic void fts5WriteBtreeNoTerm(\n  Fts5Index *p,                   /* FTS5 backend object */\n  Fts5SegWriter *pWriter          /* Writer object */\n){\n  /* If there were no rowids on the leaf page either and the doclist-index\n  ** has already been started, append an 0x00 byte to it.  */\n  if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){\n    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];\n    assert( pDlidx->bPrevValid );\n    sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);\n  }\n\n  /* Increment the \"number of sequential leaves without a term\" counter. */\n  pWriter->nEmpty++;\n}\n\nstatic i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){\n  i64 iRowid;\n  int iOff;\n\n  iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);\n  fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);\n  return iRowid;\n}\n\n/*\n** Rowid iRowid has just been appended to the current leaf page. It is the\n** first on the page. This function appends an appropriate entry to the current\n** doclist-index.\n*/\nstatic void fts5WriteDlidxAppend(\n  Fts5Index *p, \n  Fts5SegWriter *pWriter, \n  i64 iRowid\n){\n  int i;\n  int bDone = 0;\n\n  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){\n    i64 iVal;\n    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];\n\n    if( pDlidx->buf.n>=p->pConfig->pgsz ){\n      /* The current doclist-index page is full. Write it to disk and push\n      ** a copy of iRowid (which will become the first rowid on the next\n      ** doclist-index leaf page) up into the next level of the b-tree \n      ** hierarchy. If the node being flushed is currently the root node,\n      ** also push its first rowid upwards. */\n      pDlidx->buf.p[0] = 0x01;    /* Not the root node */\n      fts5DataWrite(p, \n          FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),\n          pDlidx->buf.p, pDlidx->buf.n\n      );\n      fts5WriteDlidxGrow(p, pWriter, i+2);\n      pDlidx = &pWriter->aDlidx[i];\n      if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){\n        i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);\n\n        /* This was the root node. Push its first rowid up to the new root. */\n        pDlidx[1].pgno = pDlidx->pgno;\n        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);\n        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);\n        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);\n        pDlidx[1].bPrevValid = 1;\n        pDlidx[1].iPrev = iFirst;\n      }\n\n      sqlite3Fts5BufferZero(&pDlidx->buf);\n      pDlidx->bPrevValid = 0;\n      pDlidx->pgno++;\n    }else{\n      bDone = 1;\n    }\n\n    if( pDlidx->bPrevValid ){\n      iVal = iRowid - pDlidx->iPrev;\n    }else{\n      i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);\n      assert( pDlidx->buf.n==0 );\n      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);\n      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);\n      iVal = iRowid;\n    }\n\n    sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);\n    pDlidx->bPrevValid = 1;\n    pDlidx->iPrev = iRowid;\n  }\n}\n\nstatic void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){\n  static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };\n  Fts5PageWriter *pPage = &pWriter->writer;\n  i64 iRowid;\n\n  assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );\n\n  /* Set the szLeaf header field. */\n  assert( 0==fts5GetU16(&pPage->buf.p[2]) );\n  fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);\n\n  if( pWriter->bFirstTermInPage ){\n    /* No term was written to this page. */\n    assert( pPage->pgidx.n==0 );\n    fts5WriteBtreeNoTerm(p, pWriter);\n  }else{\n    /* Append the pgidx to the page buffer. Set the szLeaf header field. */\n    fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);\n  }\n\n  /* Write the page out to disk */\n  iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);\n  fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);\n\n  /* Initialize the next page. */\n  fts5BufferZero(&pPage->buf);\n  fts5BufferZero(&pPage->pgidx);\n  fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);\n  pPage->iPrevPgidx = 0;\n  pPage->pgno++;\n\n  /* Increase the leaves written counter */\n  pWriter->nLeafWritten++;\n\n  /* The new leaf holds no terms or rowids */\n  pWriter->bFirstTermInPage = 1;\n  pWriter->bFirstRowidInPage = 1;\n}\n\n/*\n** Append term pTerm/nTerm to the segment being written by the writer passed\n** as the second argument.\n**\n** If an error occurs, set the Fts5Index.rc error code. If an error has \n** already occurred, this function is a no-op.\n*/\nstatic void fts5WriteAppendTerm(\n  Fts5Index *p, \n  Fts5SegWriter *pWriter,\n  int nTerm, const u8 *pTerm \n){\n  int nPrefix;                    /* Bytes of prefix compression for term */\n  Fts5PageWriter *pPage = &pWriter->writer;\n  Fts5Buffer *pPgidx = &pWriter->writer.pgidx;\n  int nMin = MIN(pPage->term.n, nTerm);\n\n  assert( p->rc==SQLITE_OK );\n  assert( pPage->buf.n>=4 );\n  assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );\n\n  /* If the current leaf page is full, flush it to disk. */\n  if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){\n    if( pPage->buf.n>4 ){\n      fts5WriteFlushLeaf(p, pWriter);\n      if( p->rc!=SQLITE_OK ) return;\n    }\n    fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);\n  }\n  \n  /* TODO1: Updating pgidx here. */\n  pPgidx->n += sqlite3Fts5PutVarint(\n      &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx\n  );\n  pPage->iPrevPgidx = pPage->buf.n;\n#if 0\n  fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);\n  pPgidx->n += 2;\n#endif\n\n  if( pWriter->bFirstTermInPage ){\n    nPrefix = 0;\n    if( pPage->pgno!=1 ){\n      /* This is the first term on a leaf that is not the leftmost leaf in\n      ** the segment b-tree. In this case it is necessary to add a term to\n      ** the b-tree hierarchy that is (a) larger than the largest term \n      ** already written to the segment and (b) smaller than or equal to\n      ** this term. In other words, a prefix of (pTerm/nTerm) that is one\n      ** byte longer than the longest prefix (pTerm/nTerm) shares with the\n      ** previous term. \n      **\n      ** Usually, the previous term is available in pPage->term. The exception\n      ** is if this is the first term written in an incremental-merge step.\n      ** In this case the previous term is not available, so just write a\n      ** copy of (pTerm/nTerm) into the parent node. This is slightly\n      ** inefficient, but still correct.  */\n      int n = nTerm;\n      if( pPage->term.n ){\n        n = 1 + fts5PrefixCompress(nMin, pPage->term.p, pTerm);\n      }\n      fts5WriteBtreeTerm(p, pWriter, n, pTerm);\n      if( p->rc!=SQLITE_OK ) return;\n      pPage = &pWriter->writer;\n    }\n  }else{\n    nPrefix = fts5PrefixCompress(nMin, pPage->term.p, pTerm);\n    fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);\n  }\n\n  /* Append the number of bytes of new data, then the term data itself\n  ** to the page. */\n  fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);\n  fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);\n\n  /* Update the Fts5PageWriter.term field. */\n  fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);\n  pWriter->bFirstTermInPage = 0;\n\n  pWriter->bFirstRowidInPage = 0;\n  pWriter->bFirstRowidInDoclist = 1;\n\n  assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );\n  pWriter->aDlidx[0].pgno = pPage->pgno;\n}\n\n/*\n** Append a rowid and position-list size field to the writers output. \n*/\nstatic void fts5WriteAppendRowid(\n  Fts5Index *p, \n  Fts5SegWriter *pWriter,\n  i64 iRowid\n){\n  if( p->rc==SQLITE_OK ){\n    Fts5PageWriter *pPage = &pWriter->writer;\n\n    if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){\n      fts5WriteFlushLeaf(p, pWriter);\n    }\n\n    /* If this is to be the first rowid written to the page, set the \n    ** rowid-pointer in the page-header. Also append a value to the dlidx\n    ** buffer, in case a doclist-index is required.  */\n    if( pWriter->bFirstRowidInPage ){\n      fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);\n      fts5WriteDlidxAppend(p, pWriter, iRowid);\n    }\n\n    /* Write the rowid. */\n    if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){\n      fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);\n    }else{\n      assert_nc( p->rc || iRowid>pWriter->iPrevRowid );\n      fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);\n    }\n    pWriter->iPrevRowid = iRowid;\n    pWriter->bFirstRowidInDoclist = 0;\n    pWriter->bFirstRowidInPage = 0;\n  }\n}\n\nstatic void fts5WriteAppendPoslistData(\n  Fts5Index *p, \n  Fts5SegWriter *pWriter, \n  const u8 *aData, \n  int nData\n){\n  Fts5PageWriter *pPage = &pWriter->writer;\n  const u8 *a = aData;\n  int n = nData;\n  \n  assert( p->pConfig->pgsz>0 );\n  while( p->rc==SQLITE_OK \n     && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz \n  ){\n    int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;\n    int nCopy = 0;\n    while( nCopy<nReq ){\n      i64 dummy;\n      nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);\n    }\n    fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);\n    a += nCopy;\n    n -= nCopy;\n    fts5WriteFlushLeaf(p, pWriter);\n  }\n  if( n>0 ){\n    fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);\n  }\n}\n\n/*\n** Flush any data cached by the writer object to the database. Free any\n** allocations associated with the writer.\n*/\nstatic void fts5WriteFinish(\n  Fts5Index *p, \n  Fts5SegWriter *pWriter,         /* Writer object */\n  int *pnLeaf                     /* OUT: Number of leaf pages in b-tree */\n){\n  int i;\n  Fts5PageWriter *pLeaf = &pWriter->writer;\n  if( p->rc==SQLITE_OK ){\n    assert( pLeaf->pgno>=1 );\n    if( pLeaf->buf.n>4 ){\n      fts5WriteFlushLeaf(p, pWriter);\n    }\n    *pnLeaf = pLeaf->pgno-1;\n    if( pLeaf->pgno>1 ){\n      fts5WriteFlushBtree(p, pWriter);\n    }\n  }\n  fts5BufferFree(&pLeaf->term);\n  fts5BufferFree(&pLeaf->buf);\n  fts5BufferFree(&pLeaf->pgidx);\n  fts5BufferFree(&pWriter->btterm);\n\n  for(i=0; i<pWriter->nDlidx; i++){\n    sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);\n  }\n  sqlite3_free(pWriter->aDlidx);\n}\n\nstatic void fts5WriteInit(\n  Fts5Index *p, \n  Fts5SegWriter *pWriter, \n  int iSegid\n){\n  const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;\n\n  memset(pWriter, 0, sizeof(Fts5SegWriter));\n  pWriter->iSegid = iSegid;\n\n  fts5WriteDlidxGrow(p, pWriter, 1);\n  pWriter->writer.pgno = 1;\n  pWriter->bFirstTermInPage = 1;\n  pWriter->iBtPage = 1;\n\n  assert( pWriter->writer.buf.n==0 );\n  assert( pWriter->writer.pgidx.n==0 );\n\n  /* Grow the two buffers to pgsz + padding bytes in size. */\n  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);\n  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);\n\n  if( p->pIdxWriter==0 ){\n    Fts5Config *pConfig = p->pConfig;\n    fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(\n          \"INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)\", \n          pConfig->zDb, pConfig->zName\n    ));\n  }\n\n  if( p->rc==SQLITE_OK ){\n    /* Initialize the 4-byte leaf-page header to 0x00. */\n    memset(pWriter->writer.buf.p, 0, 4);\n    pWriter->writer.buf.n = 4;\n\n    /* Bind the current output segment id to the index-writer. This is an\n    ** optimization over binding the same value over and over as rows are\n    ** inserted into %_idx by the current writer.  */\n    sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);\n  }\n}\n\n/*\n** Iterator pIter was used to iterate through the input segments of on an\n** incremental merge operation. This function is called if the incremental\n** merge step has finished but the input has not been completely exhausted.\n*/\nstatic void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){\n  int i;\n  Fts5Buffer buf;\n  memset(&buf, 0, sizeof(Fts5Buffer));\n  for(i=0; i<pIter->nSeg && p->rc==SQLITE_OK; i++){\n    Fts5SegIter *pSeg = &pIter->aSeg[i];\n    if( pSeg->pSeg==0 ){\n      /* no-op */\n    }else if( pSeg->pLeaf==0 ){\n      /* All keys from this input segment have been transfered to the output.\n      ** Set both the first and last page-numbers to 0 to indicate that the\n      ** segment is now empty. */\n      pSeg->pSeg->pgnoLast = 0;\n      pSeg->pSeg->pgnoFirst = 0;\n    }else{\n      int iOff = pSeg->iTermLeafOffset;     /* Offset on new first leaf page */\n      i64 iLeafRowid;\n      Fts5Data *pData;\n      int iId = pSeg->pSeg->iSegid;\n      u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};\n\n      iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);\n      pData = fts5LeafRead(p, iLeafRowid);\n      if( pData ){\n        if( iOff>pData->szLeaf ){\n          /* This can occur if the pages that the segments occupy overlap - if\n          ** a single page has been assigned to more than one segment. In\n          ** this case a prior iteration of this loop may have corrupted the\n          ** segment currently being trimmed.  */\n          p->rc = FTS5_CORRUPT;\n        }else{\n          fts5BufferZero(&buf);\n          fts5BufferGrow(&p->rc, &buf, pData->nn);\n          fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);\n          fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);\n          fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);\n          fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff,&pData->p[iOff]);\n          if( p->rc==SQLITE_OK ){\n            /* Set the szLeaf field */\n            fts5PutU16(&buf.p[2], (u16)buf.n);\n          }\n\n          /* Set up the new page-index array */\n          fts5BufferAppendVarint(&p->rc, &buf, 4);\n          if( pSeg->iLeafPgno==pSeg->iTermLeafPgno \n           && pSeg->iEndofDoclist<pData->szLeaf\n           && pSeg->iPgidxOff<=pData->nn\n          ){\n            int nDiff = pData->szLeaf - pSeg->iEndofDoclist;\n            fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);\n            fts5BufferAppendBlob(&p->rc, &buf, \n                pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]\n            );\n          }\n\n          pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;\n          fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);\n          fts5DataWrite(p, iLeafRowid, buf.p, buf.n);\n        }\n        fts5DataRelease(pData);\n      }\n    }\n  }\n  fts5BufferFree(&buf);\n}\n\nstatic void fts5MergeChunkCallback(\n  Fts5Index *p, \n  void *pCtx, \n  const u8 *pChunk, int nChunk\n){\n  Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;\n  fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);\n}\n\n/*\n**\n*/\nstatic void fts5IndexMergeLevel(\n  Fts5Index *p,                   /* FTS5 backend object */\n  Fts5Structure **ppStruct,       /* IN/OUT: Stucture of index */\n  int iLvl,                       /* Level to read input from */\n  int *pnRem                      /* Write up to this many output leaves */\n){\n  Fts5Structure *pStruct = *ppStruct;\n  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];\n  Fts5StructureLevel *pLvlOut;\n  Fts5Iter *pIter = 0;       /* Iterator to read input data */\n  int nRem = pnRem ? *pnRem : 0;  /* Output leaf pages left to write */\n  int nInput;                     /* Number of input segments */\n  Fts5SegWriter writer;           /* Writer object */\n  Fts5StructureSegment *pSeg;     /* Output segment */\n  Fts5Buffer term;\n  int bOldest;                    /* True if the output segment is the oldest */\n  int eDetail = p->pConfig->eDetail;\n  const int flags = FTS5INDEX_QUERY_NOOUTPUT;\n  int bTermWritten = 0;           /* True if current term already output */\n\n  assert( iLvl<pStruct->nLevel );\n  assert( pLvl->nMerge<=pLvl->nSeg );\n\n  memset(&writer, 0, sizeof(Fts5SegWriter));\n  memset(&term, 0, sizeof(Fts5Buffer));\n  if( pLvl->nMerge ){\n    pLvlOut = &pStruct->aLevel[iLvl+1];\n    assert( pLvlOut->nSeg>0 );\n    nInput = pLvl->nMerge;\n    pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];\n\n    fts5WriteInit(p, &writer, pSeg->iSegid);\n    writer.writer.pgno = pSeg->pgnoLast+1;\n    writer.iBtPage = 0;\n  }else{\n    int iSegid = fts5AllocateSegid(p, pStruct);\n\n    /* Extend the Fts5Structure object as required to ensure the output\n    ** segment exists. */\n    if( iLvl==pStruct->nLevel-1 ){\n      fts5StructureAddLevel(&p->rc, ppStruct);\n      pStruct = *ppStruct;\n    }\n    fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);\n    if( p->rc ) return;\n    pLvl = &pStruct->aLevel[iLvl];\n    pLvlOut = &pStruct->aLevel[iLvl+1];\n\n    fts5WriteInit(p, &writer, iSegid);\n\n    /* Add the new segment to the output level */\n    pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];\n    pLvlOut->nSeg++;\n    pSeg->pgnoFirst = 1;\n    pSeg->iSegid = iSegid;\n    pStruct->nSegment++;\n\n    /* Read input from all segments in the input level */\n    nInput = pLvl->nSeg;\n  }\n  bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);\n\n  assert( iLvl>=0 );\n  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);\n      fts5MultiIterEof(p, pIter)==0;\n      fts5MultiIterNext(p, pIter, 0, 0)\n  ){\n    Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];\n    int nPos;                     /* position-list size field value */\n    int nTerm;\n    const u8 *pTerm;\n\n    pTerm = fts5MultiIterTerm(pIter, &nTerm);\n    if( nTerm!=term.n || fts5Memcmp(pTerm, term.p, nTerm) ){\n      if( pnRem && writer.nLeafWritten>nRem ){\n        break;\n      }\n      fts5BufferSet(&p->rc, &term, nTerm, pTerm);\n      bTermWritten =0;\n    }\n\n    /* Check for key annihilation. */\n    if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;\n\n    if( p->rc==SQLITE_OK && bTermWritten==0 ){\n      /* This is a new term. Append a term to the output segment. */\n      fts5WriteAppendTerm(p, &writer, nTerm, pTerm);\n      bTermWritten = 1;\n    }\n\n    /* Append the rowid to the output */\n    /* WRITEPOSLISTSIZE */\n    fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));\n\n    if( eDetail==FTS5_DETAIL_NONE ){\n      if( pSegIter->bDel ){\n        fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);\n        if( pSegIter->nPos>0 ){\n          fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);\n        }\n      }\n    }else{\n      /* Append the position-list data to the output */\n      nPos = pSegIter->nPos*2 + pSegIter->bDel;\n      fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);\n      fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);\n    }\n  }\n\n  /* Flush the last leaf page to disk. Set the output segment b-tree height\n  ** and last leaf page number at the same time.  */\n  fts5WriteFinish(p, &writer, &pSeg->pgnoLast);\n\n  if( fts5MultiIterEof(p, pIter) ){\n    int i;\n\n    /* Remove the redundant segments from the %_data table */\n    for(i=0; i<nInput; i++){\n      fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);\n    }\n\n    /* Remove the redundant segments from the input level */\n    if( pLvl->nSeg!=nInput ){\n      int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);\n      memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);\n    }\n    pStruct->nSegment -= nInput;\n    pLvl->nSeg -= nInput;\n    pLvl->nMerge = 0;\n    if( pSeg->pgnoLast==0 ){\n      pLvlOut->nSeg--;\n      pStruct->nSegment--;\n    }\n  }else{\n    assert( pSeg->pgnoLast>0 );\n    fts5TrimSegments(p, pIter);\n    pLvl->nMerge = nInput;\n  }\n\n  fts5MultiIterFree(pIter);\n  fts5BufferFree(&term);\n  if( pnRem ) *pnRem -= writer.nLeafWritten;\n}\n\n/*\n** Do up to nPg pages of automerge work on the index.\n**\n** Return true if any changes were actually made, or false otherwise.\n*/\nstatic int fts5IndexMerge(\n  Fts5Index *p,                   /* FTS5 backend object */\n  Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */\n  int nPg,                        /* Pages of work to do */\n  int nMin                        /* Minimum number of segments to merge */\n){\n  int nRem = nPg;\n  int bRet = 0;\n  Fts5Structure *pStruct = *ppStruct;\n  while( nRem>0 && p->rc==SQLITE_OK ){\n    int iLvl;                   /* To iterate through levels */\n    int iBestLvl = 0;           /* Level offering the most input segments */\n    int nBest = 0;              /* Number of input segments on best level */\n\n    /* Set iBestLvl to the level to read input segments from. */\n    assert( pStruct->nLevel>0 );\n    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){\n      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];\n      if( pLvl->nMerge ){\n        if( pLvl->nMerge>nBest ){\n          iBestLvl = iLvl;\n          nBest = pLvl->nMerge;\n        }\n        break;\n      }\n      if( pLvl->nSeg>nBest ){\n        nBest = pLvl->nSeg;\n        iBestLvl = iLvl;\n      }\n    }\n\n    /* If nBest is still 0, then the index must be empty. */\n#ifdef SQLITE_DEBUG\n    for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){\n      assert( pStruct->aLevel[iLvl].nSeg==0 );\n    }\n#endif\n\n    if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){\n      break;\n    }\n    bRet = 1;\n    fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);\n    if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){\n      fts5StructurePromote(p, iBestLvl+1, pStruct);\n    }\n  }\n  *ppStruct = pStruct;\n  return bRet;\n}\n\n/*\n** A total of nLeaf leaf pages of data has just been flushed to a level-0\n** segment. This function updates the write-counter accordingly and, if\n** necessary, performs incremental merge work.\n**\n** If an error occurs, set the Fts5Index.rc error code. If an error has \n** already occurred, this function is a no-op.\n*/\nstatic void fts5IndexAutomerge(\n  Fts5Index *p,                   /* FTS5 backend object */\n  Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */\n  int nLeaf                       /* Number of output leaves just written */\n){\n  if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){\n    Fts5Structure *pStruct = *ppStruct;\n    u64 nWrite;                   /* Initial value of write-counter */\n    int nWork;                    /* Number of work-quanta to perform */\n    int nRem;                     /* Number of leaf pages left to write */\n\n    /* Update the write-counter. While doing so, set nWork. */\n    nWrite = pStruct->nWriteCounter;\n    nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));\n    pStruct->nWriteCounter += nLeaf;\n    nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);\n\n    fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);\n  }\n}\n\nstatic void fts5IndexCrisismerge(\n  Fts5Index *p,                   /* FTS5 backend object */\n  Fts5Structure **ppStruct        /* IN/OUT: Current structure of index */\n){\n  const int nCrisis = p->pConfig->nCrisisMerge;\n  Fts5Structure *pStruct = *ppStruct;\n  int iLvl = 0;\n\n  assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );\n  while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){\n    fts5IndexMergeLevel(p, &pStruct, iLvl, 0);\n    assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );\n    fts5StructurePromote(p, iLvl+1, pStruct);\n    iLvl++;\n  }\n  *ppStruct = pStruct;\n}\n\nstatic int fts5IndexReturn(Fts5Index *p){\n  int rc = p->rc;\n  p->rc = SQLITE_OK;\n  return rc;\n}\n\ntypedef struct Fts5FlushCtx Fts5FlushCtx;\nstruct Fts5FlushCtx {\n  Fts5Index *pIdx;\n  Fts5SegWriter writer; \n};\n\n/*\n** Buffer aBuf[] contains a list of varints, all small enough to fit\n** in a 32-bit integer. Return the size of the largest prefix of this \n** list nMax bytes or less in size.\n*/\nstatic int fts5PoslistPrefix(const u8 *aBuf, int nMax){\n  int ret;\n  u32 dummy;\n  ret = fts5GetVarint32(aBuf, dummy);\n  if( ret<nMax ){\n    while( 1 ){\n      int i = fts5GetVarint32(&aBuf[ret], dummy);\n      if( (ret + i) > nMax ) break;\n      ret += i;\n    }\n  }\n  return ret;\n}\n\n/*\n** Flush the contents of in-memory hash table iHash to a new level-0 \n** segment on disk. Also update the corresponding structure record.\n**\n** If an error occurs, set the Fts5Index.rc error code. If an error has \n** already occurred, this function is a no-op.\n*/\nstatic void fts5FlushOneHash(Fts5Index *p){\n  Fts5Hash *pHash = p->pHash;\n  Fts5Structure *pStruct;\n  int iSegid;\n  int pgnoLast = 0;                 /* Last leaf page number in segment */\n\n  /* Obtain a reference to the index structure and allocate a new segment-id\n  ** for the new level-0 segment.  */\n  pStruct = fts5StructureRead(p);\n  iSegid = fts5AllocateSegid(p, pStruct);\n  fts5StructureInvalidate(p);\n\n  if( iSegid ){\n    const int pgsz = p->pConfig->pgsz;\n    int eDetail = p->pConfig->eDetail;\n    Fts5StructureSegment *pSeg;   /* New segment within pStruct */\n    Fts5Buffer *pBuf;             /* Buffer in which to assemble leaf page */\n    Fts5Buffer *pPgidx;           /* Buffer in which to assemble pgidx */\n\n    Fts5SegWriter writer;\n    fts5WriteInit(p, &writer, iSegid);\n\n    pBuf = &writer.writer.buf;\n    pPgidx = &writer.writer.pgidx;\n\n    /* fts5WriteInit() should have initialized the buffers to (most likely)\n    ** the maximum space required. */\n    assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );\n    assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );\n\n    /* Begin scanning through hash table entries. This loop runs once for each\n    ** term/doclist currently stored within the hash table. */\n    if( p->rc==SQLITE_OK ){\n      p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);\n    }\n    while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){\n      const char *zTerm;          /* Buffer containing term */\n      const u8 *pDoclist;         /* Pointer to doclist for this term */\n      int nDoclist;               /* Size of doclist in bytes */\n\n      /* Write the term for this entry to disk. */\n      sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);\n      fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);\n      if( p->rc!=SQLITE_OK ) break;\n\n      assert( writer.bFirstRowidInPage==0 );\n      if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){\n        /* The entire doclist will fit on the current leaf. */\n        fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);\n      }else{\n        i64 iRowid = 0;\n        i64 iDelta = 0;\n        int iOff = 0;\n\n        /* The entire doclist will not fit on this leaf. The following \n        ** loop iterates through the poslists that make up the current \n        ** doclist.  */\n        while( p->rc==SQLITE_OK && iOff<nDoclist ){\n          iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);\n          iRowid += iDelta;\n          \n          if( writer.bFirstRowidInPage ){\n            fts5PutU16(&pBuf->p[0], (u16)pBuf->n);   /* first rowid on page */\n            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);\n            writer.bFirstRowidInPage = 0;\n            fts5WriteDlidxAppend(p, &writer, iRowid);\n            if( p->rc!=SQLITE_OK ) break;\n          }else{\n            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);\n          }\n          assert( pBuf->n<=pBuf->nSpace );\n\n          if( eDetail==FTS5_DETAIL_NONE ){\n            if( iOff<nDoclist && pDoclist[iOff]==0 ){\n              pBuf->p[pBuf->n++] = 0;\n              iOff++;\n              if( iOff<nDoclist && pDoclist[iOff]==0 ){\n                pBuf->p[pBuf->n++] = 0;\n                iOff++;\n              }\n            }\n            if( (pBuf->n + pPgidx->n)>=pgsz ){\n              fts5WriteFlushLeaf(p, &writer);\n            }\n          }else{\n            int bDummy;\n            int nPos;\n            int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);\n            nCopy += nPos;\n            if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){\n              /* The entire poslist will fit on the current leaf. So copy\n              ** it in one go. */\n              fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);\n            }else{\n              /* The entire poslist will not fit on this leaf. So it needs\n              ** to be broken into sections. The only qualification being\n              ** that each varint must be stored contiguously.  */\n              const u8 *pPoslist = &pDoclist[iOff];\n              int iPos = 0;\n              while( p->rc==SQLITE_OK ){\n                int nSpace = pgsz - pBuf->n - pPgidx->n;\n                int n = 0;\n                if( (nCopy - iPos)<=nSpace ){\n                  n = nCopy - iPos;\n                }else{\n                  n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);\n                }\n                assert( n>0 );\n                fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);\n                iPos += n;\n                if( (pBuf->n + pPgidx->n)>=pgsz ){\n                  fts5WriteFlushLeaf(p, &writer);\n                }\n                if( iPos>=nCopy ) break;\n              }\n            }\n            iOff += nCopy;\n          }\n        }\n      }\n\n      /* TODO2: Doclist terminator written here. */\n      /* pBuf->p[pBuf->n++] = '\\0'; */\n      assert( pBuf->n<=pBuf->nSpace );\n      if( p->rc==SQLITE_OK ) sqlite3Fts5HashScanNext(pHash);\n    }\n    sqlite3Fts5HashClear(pHash);\n    fts5WriteFinish(p, &writer, &pgnoLast);\n\n    /* Update the Fts5Structure. It is written back to the database by the\n    ** fts5StructureRelease() call below.  */\n    if( pStruct->nLevel==0 ){\n      fts5StructureAddLevel(&p->rc, &pStruct);\n    }\n    fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);\n    if( p->rc==SQLITE_OK ){\n      pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];\n      pSeg->iSegid = iSegid;\n      pSeg->pgnoFirst = 1;\n      pSeg->pgnoLast = pgnoLast;\n      pStruct->nSegment++;\n    }\n    fts5StructurePromote(p, 0, pStruct);\n  }\n\n  fts5IndexAutomerge(p, &pStruct, pgnoLast);\n  fts5IndexCrisismerge(p, &pStruct);\n  fts5StructureWrite(p, pStruct);\n  fts5StructureRelease(pStruct);\n}\n\n/*\n** Flush any data stored in the in-memory hash tables to the database.\n*/\nstatic void fts5IndexFlush(Fts5Index *p){\n  /* Unless it is empty, flush the hash table to disk */\n  if( p->nPendingData ){\n    assert( p->pHash );\n    p->nPendingData = 0;\n    fts5FlushOneHash(p);\n  }\n}\n\nstatic Fts5Structure *fts5IndexOptimizeStruct(\n  Fts5Index *p, \n  Fts5Structure *pStruct\n){\n  Fts5Structure *pNew = 0;\n  sqlite3_int64 nByte = sizeof(Fts5Structure);\n  int nSeg = pStruct->nSegment;\n  int i;\n\n  /* Figure out if this structure requires optimization. A structure does\n  ** not require optimization if either:\n  **\n  **  + it consists of fewer than two segments, or \n  **  + all segments are on the same level, or\n  **  + all segments except one are currently inputs to a merge operation.\n  **\n  ** In the first case, return NULL. In the second, increment the ref-count\n  ** on *pStruct and return a copy of the pointer to it.\n  */\n  if( nSeg<2 ) return 0;\n  for(i=0; i<pStruct->nLevel; i++){\n    int nThis = pStruct->aLevel[i].nSeg;\n    if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){\n      fts5StructureRef(pStruct);\n      return pStruct;\n    }\n    assert( pStruct->aLevel[i].nMerge<=nThis );\n  }\n\n  nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);\n  pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);\n\n  if( pNew ){\n    Fts5StructureLevel *pLvl;\n    nByte = nSeg * sizeof(Fts5StructureSegment);\n    pNew->nLevel = pStruct->nLevel+1;\n    pNew->nRef = 1;\n    pNew->nWriteCounter = pStruct->nWriteCounter;\n    pLvl = &pNew->aLevel[pStruct->nLevel];\n    pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);\n    if( pLvl->aSeg ){\n      int iLvl, iSeg;\n      int iSegOut = 0;\n      /* Iterate through all segments, from oldest to newest. Add them to\n      ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest\n      ** segment in the data structure.  */\n      for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){\n        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){\n          pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];\n          iSegOut++;\n        }\n      }\n      pNew->nSegment = pLvl->nSeg = nSeg;\n    }else{\n      sqlite3_free(pNew);\n      pNew = 0;\n    }\n  }\n\n  return pNew;\n}\n\nstatic int sqlite3Fts5IndexOptimize(Fts5Index *p){\n  Fts5Structure *pStruct;\n  Fts5Structure *pNew = 0;\n\n  assert( p->rc==SQLITE_OK );\n  fts5IndexFlush(p);\n  pStruct = fts5StructureRead(p);\n  fts5StructureInvalidate(p);\n\n  if( pStruct ){\n    pNew = fts5IndexOptimizeStruct(p, pStruct);\n  }\n  fts5StructureRelease(pStruct);\n\n  assert( pNew==0 || pNew->nSegment>0 );\n  if( pNew ){\n    int iLvl;\n    for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}\n    while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){\n      int nRem = FTS5_OPT_WORK_UNIT;\n      fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);\n    }\n\n    fts5StructureWrite(p, pNew);\n    fts5StructureRelease(pNew);\n  }\n\n  return fts5IndexReturn(p); \n}\n\n/*\n** This is called to implement the special \"VALUES('merge', $nMerge)\"\n** INSERT command.\n*/\nstatic int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){\n  Fts5Structure *pStruct = fts5StructureRead(p);\n  if( pStruct ){\n    int nMin = p->pConfig->nUsermerge;\n    fts5StructureInvalidate(p);\n    if( nMerge<0 ){\n      Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);\n      fts5StructureRelease(pStruct);\n      pStruct = pNew;\n      nMin = 2;\n      nMerge = nMerge*-1;\n    }\n    if( pStruct && pStruct->nLevel ){\n      if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){\n        fts5StructureWrite(p, pStruct);\n      }\n    }\n    fts5StructureRelease(pStruct);\n  }\n  return fts5IndexReturn(p);\n}\n\nstatic void fts5AppendRowid(\n  Fts5Index *p,\n  i64 iDelta,\n  Fts5Iter *pUnused,\n  Fts5Buffer *pBuf\n){\n  UNUSED_PARAM(pUnused);\n  fts5BufferAppendVarint(&p->rc, pBuf, iDelta);\n}\n\nstatic void fts5AppendPoslist(\n  Fts5Index *p,\n  i64 iDelta,\n  Fts5Iter *pMulti,\n  Fts5Buffer *pBuf\n){\n  int nData = pMulti->base.nData;\n  int nByte = nData + 9 + 9 + FTS5_DATA_ZERO_PADDING;\n  assert( nData>0 );\n  if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nByte) ){\n    fts5BufferSafeAppendVarint(pBuf, iDelta);\n    fts5BufferSafeAppendVarint(pBuf, nData*2);\n    fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);\n    memset(&pBuf->p[pBuf->n], 0, FTS5_DATA_ZERO_PADDING);\n  }\n}\n\n\nstatic void fts5DoclistIterNext(Fts5DoclistIter *pIter){\n  u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;\n\n  assert( pIter->aPoslist );\n  if( p>=pIter->aEof ){\n    pIter->aPoslist = 0;\n  }else{\n    i64 iDelta;\n\n    p += fts5GetVarint(p, (u64*)&iDelta);\n    pIter->iRowid += iDelta;\n\n    /* Read position list size */\n    if( p[0] & 0x80 ){\n      int nPos;\n      pIter->nSize = fts5GetVarint32(p, nPos);\n      pIter->nPoslist = (nPos>>1);\n    }else{\n      pIter->nPoslist = ((int)(p[0])) >> 1;\n      pIter->nSize = 1;\n    }\n\n    pIter->aPoslist = p;\n  }\n}\n\nstatic void fts5DoclistIterInit(\n  Fts5Buffer *pBuf, \n  Fts5DoclistIter *pIter\n){\n  memset(pIter, 0, sizeof(*pIter));\n  pIter->aPoslist = pBuf->p;\n  pIter->aEof = &pBuf->p[pBuf->n];\n  fts5DoclistIterNext(pIter);\n}\n\n#if 0\n/*\n** Append a doclist to buffer pBuf.\n**\n** This function assumes that space within the buffer has already been\n** allocated.\n*/\nstatic void fts5MergeAppendDocid(\n  Fts5Buffer *pBuf,               /* Buffer to write to */\n  i64 *piLastRowid,               /* IN/OUT: Previous rowid written (if any) */\n  i64 iRowid                      /* Rowid to append */\n){\n  assert( pBuf->n!=0 || (*piLastRowid)==0 );\n  fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);\n  *piLastRowid = iRowid;\n}\n#endif\n\n#define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) {       \\\n  assert( (pBuf)->n!=0 || (iLastRowid)==0 );                   \\\n  fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \\\n  (iLastRowid) = (iRowid);                                     \\\n}\n\n/*\n** Swap the contents of buffer *p1 with that of *p2.\n*/\nstatic void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){\n  Fts5Buffer tmp = *p1;\n  *p1 = *p2;\n  *p2 = tmp;\n}\n\nstatic void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){\n  int i = *piOff;\n  if( i>=pBuf->n ){\n    *piOff = -1;\n  }else{\n    u64 iVal;\n    *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);\n    *piRowid += iVal;\n  }\n}\n\n/*\n** This is the equivalent of fts5MergePrefixLists() for detail=none mode.\n** In this case the buffers consist of a delta-encoded list of rowids only.\n*/\nstatic void fts5MergeRowidLists(\n  Fts5Index *p,                   /* FTS5 backend object */\n  Fts5Buffer *p1,                 /* First list to merge */\n  Fts5Buffer *p2                  /* Second list to merge */\n){\n  int i1 = 0;\n  int i2 = 0;\n  i64 iRowid1 = 0;\n  i64 iRowid2 = 0;\n  i64 iOut = 0;\n\n  Fts5Buffer out;\n  memset(&out, 0, sizeof(out));\n  sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);\n  if( p->rc ) return;\n\n  fts5NextRowid(p1, &i1, &iRowid1);\n  fts5NextRowid(p2, &i2, &iRowid2);\n  while( i1>=0 || i2>=0 ){\n    if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){\n      assert( iOut==0 || iRowid1>iOut );\n      fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);\n      iOut = iRowid1;\n      fts5NextRowid(p1, &i1, &iRowid1);\n    }else{\n      assert( iOut==0 || iRowid2>iOut );\n      fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);\n      iOut = iRowid2;\n      if( i1>=0 && iRowid1==iRowid2 ){\n        fts5NextRowid(p1, &i1, &iRowid1);\n      }\n      fts5NextRowid(p2, &i2, &iRowid2);\n    }\n  }\n\n  fts5BufferSwap(&out, p1);\n  fts5BufferFree(&out);\n}\n\n/*\n** Buffers p1 and p2 contain doclists. This function merges the content\n** of the two doclists together and sets buffer p1 to the result before\n** returning.\n**\n** If an error occurs, an error code is left in p->rc. If an error has\n** already occurred, this function is a no-op.\n*/\nstatic void fts5MergePrefixLists(\n  Fts5Index *p,                   /* FTS5 backend object */\n  Fts5Buffer *p1,                 /* First list to merge */\n  Fts5Buffer *p2                  /* Second list to merge */\n){\n  if( p2->n ){\n    i64 iLastRowid = 0;\n    Fts5DoclistIter i1;\n    Fts5DoclistIter i2;\n    Fts5Buffer out = {0, 0, 0};\n    Fts5Buffer tmp = {0, 0, 0};\n\n    /* The maximum size of the output is equal to the sum of the two \n    ** input sizes + 1 varint (9 bytes). The extra varint is because if the\n    ** first rowid in one input is a large negative number, and the first in\n    ** the other a non-negative number, the delta for the non-negative\n    ** number will be larger on disk than the literal integer value\n    ** was.  \n    **\n    ** Or, if the input position-lists are corrupt, then the output might\n    ** include up to 2 extra 10-byte positions created by interpreting -1\n    ** (the value PoslistNext64() uses for EOF) as a position and appending\n    ** it to the output. This can happen at most once for each input \n    ** position-list, hence two 10 byte paddings.  */\n    if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n + 9+10+10) ) return;\n    fts5DoclistIterInit(p1, &i1);\n    fts5DoclistIterInit(p2, &i2);\n\n    while( 1 ){\n      if( i1.iRowid<i2.iRowid ){\n        /* Copy entry from i1 */\n        fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);\n        fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);\n        fts5DoclistIterNext(&i1);\n        if( i1.aPoslist==0 ) break;\n        assert( out.n<=((i1.aPoslist-p1->p) + (i2.aPoslist-p2->p)+9+10+10) );\n      }\n      else if( i2.iRowid!=i1.iRowid ){\n        /* Copy entry from i2 */\n        fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);\n        fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);\n        fts5DoclistIterNext(&i2);\n        if( i2.aPoslist==0 ) break;\n        assert( out.n<=((i1.aPoslist-p1->p) + (i2.aPoslist-p2->p)+9+10+10) );\n      }\n      else{\n        /* Merge the two position lists. */ \n        i64 iPos1 = 0;\n        i64 iPos2 = 0;\n        int iOff1 = 0;\n        int iOff2 = 0;\n        u8 *a1 = &i1.aPoslist[i1.nSize];\n        u8 *a2 = &i2.aPoslist[i2.nSize];\n        int nCopy;\n        u8 *aCopy;\n\n        i64 iPrev = 0;\n        Fts5PoslistWriter writer;\n        memset(&writer, 0, sizeof(writer));\n\n        /* See the earlier comment in this function for an explanation of why\n        ** corrupt input position lists might cause the output to consume\n        ** at most 20 bytes of unexpected space. */\n        fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);\n        fts5BufferZero(&tmp);\n        sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist + 10 + 10);\n        if( p->rc ) break;\n\n        sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);\n        sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);\n        assert_nc( iPos1>=0 && iPos2>=0 );\n\n        if( iPos1<iPos2 ){\n          sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);\n          sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);\n        }else{\n          sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);\n          sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);\n        }\n        if( iPos1>=0 && iPos2>=0 ){\n          while( 1 ){\n            if( iPos1<iPos2 ){\n              if( iPos1!=iPrev ){\n                sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);\n              }\n              sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);\n              if( iPos1<0 ) break;\n            }else{\n              assert_nc( iPos2!=iPrev );\n              sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);\n              sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);\n              if( iPos2<0 ) break;\n            }\n          }\n        }\n\n        if( iPos1>=0 ){\n          if( iPos1!=iPrev ){\n            sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);\n          }\n          aCopy = &a1[iOff1];\n          nCopy = i1.nPoslist - iOff1;\n        }else{\n          assert_nc( iPos2>=0 && iPos2!=iPrev );\n          sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);\n          aCopy = &a2[iOff2];\n          nCopy = i2.nPoslist - iOff2;\n        }\n        if( nCopy>0 ){\n          fts5BufferSafeAppendBlob(&tmp, aCopy, nCopy);\n        }\n\n        /* WRITEPOSLISTSIZE */\n        assert_nc( tmp.n<=i1.nPoslist+i2.nPoslist );\n        assert( tmp.n<=i1.nPoslist+i2.nPoslist+10+10 );\n        if( tmp.n>i1.nPoslist+i2.nPoslist ){\n          if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;\n          break;\n        }\n        fts5BufferSafeAppendVarint(&out, tmp.n * 2);\n        fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);\n        fts5DoclistIterNext(&i1);\n        fts5DoclistIterNext(&i2);\n        assert_nc( out.n<=(p1->n+p2->n+9) );\n        if( i1.aPoslist==0 || i2.aPoslist==0 ) break;\n        assert( out.n<=((i1.aPoslist-p1->p) + (i2.aPoslist-p2->p)+9+10+10) );\n      }\n    }\n\n    if( i1.aPoslist ){\n      fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);\n      fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);\n    }\n    else if( i2.aPoslist ){\n      fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);\n      fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);\n    }\n    assert_nc( out.n<=(p1->n+p2->n+9) );\n\n    fts5BufferSet(&p->rc, p1, out.n, out.p);\n    fts5BufferFree(&tmp);\n    fts5BufferFree(&out);\n  }\n}\n\nstatic void fts5SetupPrefixIter(\n  Fts5Index *p,                   /* Index to read from */\n  int bDesc,                      /* True for \"ORDER BY rowid DESC\" */\n  const u8 *pToken,               /* Buffer containing prefix to match */\n  int nToken,                     /* Size of buffer pToken in bytes */\n  Fts5Colset *pColset,            /* Restrict matches to these columns */\n  Fts5Iter **ppIter          /* OUT: New iterator */\n){\n  Fts5Structure *pStruct;\n  Fts5Buffer *aBuf;\n  const int nBuf = 32;\n\n  void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);\n  void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);\n  if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){\n    xMerge = fts5MergeRowidLists;\n    xAppend = fts5AppendRowid;\n  }else{\n    xMerge = fts5MergePrefixLists;\n    xAppend = fts5AppendPoslist;\n  }\n\n  aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);\n  pStruct = fts5StructureRead(p);\n\n  if( aBuf && pStruct ){\n    const int flags = FTS5INDEX_QUERY_SCAN \n                    | FTS5INDEX_QUERY_SKIPEMPTY \n                    | FTS5INDEX_QUERY_NOOUTPUT;\n    int i;\n    i64 iLastRowid = 0;\n    Fts5Iter *p1 = 0;     /* Iterator used to gather data from index */\n    Fts5Data *pData;\n    Fts5Buffer doclist;\n    int bNewTerm = 1;\n\n    memset(&doclist, 0, sizeof(doclist));\n    fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);\n    fts5IterSetOutputCb(&p->rc, p1);\n    for( /* no-op */ ;\n        fts5MultiIterEof(p, p1)==0;\n        fts5MultiIterNext2(p, p1, &bNewTerm)\n    ){\n      Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];\n      int nTerm = pSeg->term.n;\n      const u8 *pTerm = pSeg->term.p;\n      p1->xSetOutputs(p1, pSeg);\n\n      assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );\n      if( bNewTerm ){\n        if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;\n      }\n\n      if( p1->base.nData==0 ) continue;\n\n      if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){\n        for(i=0; p->rc==SQLITE_OK && doclist.n; i++){\n          assert( i<nBuf );\n          if( aBuf[i].n==0 ){\n            fts5BufferSwap(&doclist, &aBuf[i]);\n            fts5BufferZero(&doclist);\n          }else{\n            xMerge(p, &doclist, &aBuf[i]);\n            fts5BufferZero(&aBuf[i]);\n          }\n        }\n        iLastRowid = 0;\n      }\n\n      xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);\n      iLastRowid = p1->base.iRowid;\n    }\n\n    for(i=0; i<nBuf; i++){\n      if( p->rc==SQLITE_OK ){\n        xMerge(p, &doclist, &aBuf[i]);\n      }\n      fts5BufferFree(&aBuf[i]);\n    }\n    fts5MultiIterFree(p1);\n\n    pData = fts5IdxMalloc(p, sizeof(Fts5Data)+doclist.n+FTS5_DATA_ZERO_PADDING);\n    if( pData ){\n      pData->p = (u8*)&pData[1];\n      pData->nn = pData->szLeaf = doclist.n;\n      if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);\n      fts5MultiIterNew2(p, pData, bDesc, ppIter);\n    }\n    fts5BufferFree(&doclist);\n  }\n\n  fts5StructureRelease(pStruct);\n  sqlite3_free(aBuf);\n}\n\n\n/*\n** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain\n** to the document with rowid iRowid.\n*/\nstatic int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){\n  assert( p->rc==SQLITE_OK );\n\n  /* Allocate the hash table if it has not already been allocated */\n  if( p->pHash==0 ){\n    p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);\n  }\n\n  /* Flush the hash table to disk if required */\n  if( iRowid<p->iWriteRowid \n   || (iRowid==p->iWriteRowid && p->bDelete==0)\n   || (p->nPendingData > p->pConfig->nHashSize) \n  ){\n    fts5IndexFlush(p);\n  }\n\n  p->iWriteRowid = iRowid;\n  p->bDelete = bDelete;\n  return fts5IndexReturn(p);\n}\n\n/*\n** Commit data to disk.\n*/\nstatic int sqlite3Fts5IndexSync(Fts5Index *p){\n  assert( p->rc==SQLITE_OK );\n  fts5IndexFlush(p);\n  sqlite3Fts5IndexCloseReader(p);\n  return fts5IndexReturn(p);\n}\n\n/*\n** Discard any data stored in the in-memory hash tables. Do not write it\n** to the database. Additionally, assume that the contents of the %_data\n** table may have changed on disk. So any in-memory caches of %_data \n** records must be invalidated.\n*/\nstatic int sqlite3Fts5IndexRollback(Fts5Index *p){\n  sqlite3Fts5IndexCloseReader(p);\n  fts5IndexDiscardData(p);\n  fts5StructureInvalidate(p);\n  /* assert( p->rc==SQLITE_OK ); */\n  return SQLITE_OK;\n}\n\n/*\n** The %_data table is completely empty when this function is called. This\n** function populates it with the initial structure objects for each index,\n** and the initial version of the \"averages\" record (a zero-byte blob).\n*/\nstatic int sqlite3Fts5IndexReinit(Fts5Index *p){\n  Fts5Structure s;\n  fts5StructureInvalidate(p);\n  fts5IndexDiscardData(p);\n  memset(&s, 0, sizeof(Fts5Structure));\n  fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)\"\", 0);\n  fts5StructureWrite(p, &s);\n  return fts5IndexReturn(p);\n}\n\n/*\n** Open a new Fts5Index handle. If the bCreate argument is true, create\n** and initialize the underlying %_data table.\n**\n** If successful, set *pp to point to the new object and return SQLITE_OK.\n** Otherwise, set *pp to NULL and return an SQLite error code.\n*/\nstatic int sqlite3Fts5IndexOpen(\n  Fts5Config *pConfig, \n  int bCreate, \n  Fts5Index **pp,\n  char **pzErr\n){\n  int rc = SQLITE_OK;\n  Fts5Index *p;                   /* New object */\n\n  *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));\n  if( rc==SQLITE_OK ){\n    p->pConfig = pConfig;\n    p->nWorkUnit = FTS5_WORK_UNIT;\n    p->zDataTbl = sqlite3Fts5Mprintf(&rc, \"%s_data\", pConfig->zName);\n    if( p->zDataTbl && bCreate ){\n      rc = sqlite3Fts5CreateTable(\n          pConfig, \"data\", \"id INTEGER PRIMARY KEY, block BLOB\", 0, pzErr\n      );\n      if( rc==SQLITE_OK ){\n        rc = sqlite3Fts5CreateTable(pConfig, \"idx\", \n            \"segid, term, pgno, PRIMARY KEY(segid, term)\", \n            1, pzErr\n        );\n      }\n      if( rc==SQLITE_OK ){\n        rc = sqlite3Fts5IndexReinit(p);\n      }\n    }\n  }\n\n  assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );\n  if( rc ){\n    sqlite3Fts5IndexClose(p);\n    *pp = 0;\n  }\n  return rc;\n}\n\n/*\n** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().\n*/\nstatic int sqlite3Fts5IndexClose(Fts5Index *p){\n  int rc = SQLITE_OK;\n  if( p ){\n    assert( p->pReader==0 );\n    fts5StructureInvalidate(p);\n    sqlite3_finalize(p->pWriter);\n    sqlite3_finalize(p->pDeleter);\n    sqlite3_finalize(p->pIdxWriter);\n    sqlite3_finalize(p->pIdxDeleter);\n    sqlite3_finalize(p->pIdxSelect);\n    sqlite3_finalize(p->pDataVersion);\n    sqlite3Fts5HashFree(p->pHash);\n    sqlite3_free(p->zDataTbl);\n    sqlite3_free(p);\n  }\n  return rc;\n}\n\n/*\n** Argument p points to a buffer containing utf-8 text that is n bytes in \n** size. Return the number of bytes in the nChar character prefix of the\n** buffer, or 0 if there are less than nChar characters in total.\n*/\nstatic int sqlite3Fts5IndexCharlenToBytelen(\n  const char *p, \n  int nByte, \n  int nChar\n){\n  int n = 0;\n  int i;\n  for(i=0; i<nChar; i++){\n    if( n>=nByte ) return 0;      /* Input contains fewer than nChar chars */\n    if( (unsigned char)p[n++]>=0xc0 ){\n      if( n>=nByte ) return 0;\n      while( (p[n] & 0xc0)==0x80 ){\n        n++;\n        if( n>=nByte ){\n          if( i+1==nChar ) break;\n          return 0;\n        }\n      }\n    }\n  }\n  return n;\n}\n\n/*\n** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of\n** unicode characters in the string.\n*/\nstatic int fts5IndexCharlen(const char *pIn, int nIn){\n  int nChar = 0;            \n  int i = 0;\n  while( i<nIn ){\n    if( (unsigned char)pIn[i++]>=0xc0 ){\n      while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;\n    }\n    nChar++;\n  }\n  return nChar;\n}\n\n/*\n** Insert or remove data to or from the index. Each time a document is \n** added to or removed from the index, this function is called one or more\n** times.\n**\n** For an insert, it must be called once for each token in the new document.\n** If the operation is a delete, it must be called (at least) once for each\n** unique token in the document with an iCol value less than zero. The iPos\n** argument is ignored for a delete.\n*/\nstatic int sqlite3Fts5IndexWrite(\n  Fts5Index *p,                   /* Index to write to */\n  int iCol,                       /* Column token appears in (-ve -> delete) */\n  int iPos,                       /* Position of token within column */\n  const char *pToken, int nToken  /* Token to add or remove to or from index */\n){\n  int i;                          /* Used to iterate through indexes */\n  int rc = SQLITE_OK;             /* Return code */\n  Fts5Config *pConfig = p->pConfig;\n\n  assert( p->rc==SQLITE_OK );\n  assert( (iCol<0)==p->bDelete );\n\n  /* Add the entry to the main terms index. */\n  rc = sqlite3Fts5HashWrite(\n      p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken\n  );\n\n  for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){\n    const int nChar = pConfig->aPrefix[i];\n    int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);\n    if( nByte ){\n      rc = sqlite3Fts5HashWrite(p->pHash, \n          p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,\n          nByte\n      );\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Open a new iterator to iterate though all rowid that match the \n** specified token or token prefix.\n*/\nstatic int sqlite3Fts5IndexQuery(\n  Fts5Index *p,                   /* FTS index to query */\n  const char *pToken, int nToken, /* Token (or prefix) to query for */\n  int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */\n  Fts5Colset *pColset,            /* Match these columns only */\n  Fts5IndexIter **ppIter          /* OUT: New iterator object */\n){\n  Fts5Config *pConfig = p->pConfig;\n  Fts5Iter *pRet = 0;\n  Fts5Buffer buf = {0, 0, 0};\n\n  /* If the QUERY_SCAN flag is set, all other flags must be clear. */\n  assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );\n\n  if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){\n    int iIdx = 0;                 /* Index to search */\n    if( nToken ) memcpy(&buf.p[1], pToken, nToken);\n\n    /* Figure out which index to search and set iIdx accordingly. If this\n    ** is a prefix query for which there is no prefix index, set iIdx to\n    ** greater than pConfig->nPrefix to indicate that the query will be\n    ** satisfied by scanning multiple terms in the main index.\n    **\n    ** If the QUERY_TEST_NOIDX flag was specified, then this must be a\n    ** prefix-query. Instead of using a prefix-index (if one exists), \n    ** evaluate the prefix query using the main FTS index. This is used\n    ** for internal sanity checking by the integrity-check in debug \n    ** mode only.  */\n#ifdef SQLITE_DEBUG\n    if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){\n      assert( flags & FTS5INDEX_QUERY_PREFIX );\n      iIdx = 1+pConfig->nPrefix;\n    }else\n#endif\n    if( flags & FTS5INDEX_QUERY_PREFIX ){\n      int nChar = fts5IndexCharlen(pToken, nToken);\n      for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){\n        if( pConfig->aPrefix[iIdx-1]==nChar ) break;\n      }\n    }\n\n    if( iIdx<=pConfig->nPrefix ){\n      /* Straight index lookup */\n      Fts5Structure *pStruct = fts5StructureRead(p);\n      buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);\n      if( pStruct ){\n        fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY, \n            pColset, buf.p, nToken+1, -1, 0, &pRet\n        );\n        fts5StructureRelease(pStruct);\n      }\n    }else{\n      /* Scan multiple terms in the main index */\n      int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;\n      buf.p[0] = FTS5_MAIN_PREFIX;\n      fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);\n      assert( p->rc!=SQLITE_OK || pRet->pColset==0 );\n      fts5IterSetOutputCb(&p->rc, pRet);\n      if( p->rc==SQLITE_OK ){\n        Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];\n        if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);\n      }\n    }\n\n    if( p->rc ){\n      sqlite3Fts5IterClose((Fts5IndexIter*)pRet);\n      pRet = 0;\n      sqlite3Fts5IndexCloseReader(p);\n    }\n\n    *ppIter = (Fts5IndexIter*)pRet;\n    sqlite3Fts5BufferFree(&buf);\n  }\n  return fts5IndexReturn(p);\n}\n\n/*\n** Return true if the iterator passed as the only argument is at EOF.\n*/\n/*\n** Move to the next matching rowid. \n*/\nstatic int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){\n  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;\n  assert( pIter->pIndex->rc==SQLITE_OK );\n  fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);\n  return fts5IndexReturn(pIter->pIndex);\n}\n\n/*\n** Move to the next matching term/rowid. Used by the fts5vocab module.\n*/\nstatic int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){\n  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;\n  Fts5Index *p = pIter->pIndex;\n\n  assert( pIter->pIndex->rc==SQLITE_OK );\n\n  fts5MultiIterNext(p, pIter, 0, 0);\n  if( p->rc==SQLITE_OK ){\n    Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];\n    if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){\n      fts5DataRelease(pSeg->pLeaf);\n      pSeg->pLeaf = 0;\n      pIter->base.bEof = 1;\n    }\n  }\n\n  return fts5IndexReturn(pIter->pIndex);\n}\n\n/*\n** Move to the next matching rowid that occurs at or after iMatch. The\n** definition of \"at or after\" depends on whether this iterator iterates\n** in ascending or descending rowid order.\n*/\nstatic int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){\n  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;\n  fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);\n  return fts5IndexReturn(pIter->pIndex);\n}\n\n/*\n** Return the current term.\n*/\nstatic const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){\n  int n;\n  const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);\n  *pn = n-1;\n  return &z[1];\n}\n\n/*\n** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().\n*/\nstatic void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){\n  if( pIndexIter ){\n    Fts5Iter *pIter = (Fts5Iter*)pIndexIter;\n    Fts5Index *pIndex = pIter->pIndex;\n    fts5MultiIterFree(pIter);\n    sqlite3Fts5IndexCloseReader(pIndex);\n  }\n}\n\n/*\n** Read and decode the \"averages\" record from the database. \n**\n** Parameter anSize must point to an array of size nCol, where nCol is\n** the number of user defined columns in the FTS table.\n*/\nstatic int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){\n  int nCol = p->pConfig->nCol;\n  Fts5Data *pData;\n\n  *pnRow = 0;\n  memset(anSize, 0, sizeof(i64) * nCol);\n  pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);\n  if( p->rc==SQLITE_OK && pData->nn ){\n    int i = 0;\n    int iCol;\n    i += fts5GetVarint(&pData->p[i], (u64*)pnRow);\n    for(iCol=0; i<pData->nn && iCol<nCol; iCol++){\n      i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);\n    }\n  }\n\n  fts5DataRelease(pData);\n  return fts5IndexReturn(p);\n}\n\n/*\n** Replace the current \"averages\" record with the contents of the buffer \n** supplied as the second argument.\n*/\nstatic int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){\n  assert( p->rc==SQLITE_OK );\n  fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);\n  return fts5IndexReturn(p);\n}\n\n/*\n** Return the total number of blocks this module has read from the %_data\n** table since it was created.\n*/\nstatic int sqlite3Fts5IndexReads(Fts5Index *p){\n  return p->nRead;\n}\n\n/*\n** Set the 32-bit cookie value stored at the start of all structure \n** records to the value passed as the second argument.\n**\n** Return SQLITE_OK if successful, or an SQLite error code if an error\n** occurs.\n*/\nstatic int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){\n  int rc;                              /* Return code */\n  Fts5Config *pConfig = p->pConfig;    /* Configuration object */\n  u8 aCookie[4];                       /* Binary representation of iNew */\n  sqlite3_blob *pBlob = 0;\n\n  assert( p->rc==SQLITE_OK );\n  sqlite3Fts5Put32(aCookie, iNew);\n\n  rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl, \n      \"block\", FTS5_STRUCTURE_ROWID, 1, &pBlob\n  );\n  if( rc==SQLITE_OK ){\n    sqlite3_blob_write(pBlob, aCookie, 4, 0);\n    rc = sqlite3_blob_close(pBlob);\n  }\n\n  return rc;\n}\n\nstatic int sqlite3Fts5IndexLoadConfig(Fts5Index *p){\n  Fts5Structure *pStruct;\n  pStruct = fts5StructureRead(p);\n  fts5StructureRelease(pStruct);\n  return fts5IndexReturn(p);\n}\n\n\n/*************************************************************************\n**************************************************************************\n** Below this point is the implementation of the integrity-check \n** functionality.\n*/\n\n/*\n** Return a simple checksum value based on the arguments.\n*/\nstatic u64 sqlite3Fts5IndexEntryCksum(\n  i64 iRowid, \n  int iCol, \n  int iPos, \n  int iIdx,\n  const char *pTerm,\n  int nTerm\n){\n  int i;\n  u64 ret = iRowid;\n  ret += (ret<<3) + iCol;\n  ret += (ret<<3) + iPos;\n  if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);\n  for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];\n  return ret;\n}\n\n#ifdef SQLITE_DEBUG\n/*\n** This function is purely an internal test. It does not contribute to \n** FTS functionality, or even the integrity-check, in any way.\n**\n** Instead, it tests that the same set of pgno/rowid combinations are \n** visited regardless of whether the doclist-index identified by parameters\n** iSegid/iLeaf is iterated in forwards or reverse order.\n*/\nstatic void fts5TestDlidxReverse(\n  Fts5Index *p, \n  int iSegid,                     /* Segment id to load from */\n  int iLeaf                       /* Load doclist-index for this leaf */\n){\n  Fts5DlidxIter *pDlidx = 0;\n  u64 cksum1 = 13;\n  u64 cksum2 = 13;\n\n  for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);\n      fts5DlidxIterEof(p, pDlidx)==0;\n      fts5DlidxIterNext(p, pDlidx)\n  ){\n    i64 iRowid = fts5DlidxIterRowid(pDlidx);\n    int pgno = fts5DlidxIterPgno(pDlidx);\n    assert( pgno>iLeaf );\n    cksum1 += iRowid + ((i64)pgno<<32);\n  }\n  fts5DlidxIterFree(pDlidx);\n  pDlidx = 0;\n\n  for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);\n      fts5DlidxIterEof(p, pDlidx)==0;\n      fts5DlidxIterPrev(p, pDlidx)\n  ){\n    i64 iRowid = fts5DlidxIterRowid(pDlidx);\n    int pgno = fts5DlidxIterPgno(pDlidx);\n    assert( fts5DlidxIterPgno(pDlidx)>iLeaf );\n    cksum2 += iRowid + ((i64)pgno<<32);\n  }\n  fts5DlidxIterFree(pDlidx);\n  pDlidx = 0;\n\n  if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;\n}\n\nstatic int fts5QueryCksum(\n  Fts5Index *p,                   /* Fts5 index object */\n  int iIdx,\n  const char *z,                  /* Index key to query for */\n  int n,                          /* Size of index key in bytes */\n  int flags,                      /* Flags for Fts5IndexQuery */\n  u64 *pCksum                     /* IN/OUT: Checksum value */\n){\n  int eDetail = p->pConfig->eDetail;\n  u64 cksum = *pCksum;\n  Fts5IndexIter *pIter = 0;\n  int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);\n\n  while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){\n    i64 rowid = pIter->iRowid;\n\n    if( eDetail==FTS5_DETAIL_NONE ){\n      cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);\n    }else{\n      Fts5PoslistReader sReader;\n      for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);\n          sReader.bEof==0;\n          sqlite3Fts5PoslistReaderNext(&sReader)\n      ){\n        int iCol = FTS5_POS2COLUMN(sReader.iPos);\n        int iOff = FTS5_POS2OFFSET(sReader.iPos);\n        cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);\n      }\n    }\n    if( rc==SQLITE_OK ){\n      rc = sqlite3Fts5IterNext(pIter);\n    }\n  }\n  sqlite3Fts5IterClose(pIter);\n\n  *pCksum = cksum;\n  return rc;\n}\n\n/*\n** Check if buffer z[], size n bytes, contains as series of valid utf-8\n** encoded codepoints. If so, return 0. Otherwise, if the buffer does not\n** contain valid utf-8, return non-zero.\n*/\nstatic int fts5TestUtf8(const char *z, int n){\n  int i = 0;\n  assert_nc( n>0 );\n  while( i<n ){\n    if( (z[i] & 0x80)==0x00 ){\n      i++;\n    }else\n    if( (z[i] & 0xE0)==0xC0 ){\n      if( i+1>=n || (z[i+1] & 0xC0)!=0x80 ) return 1;\n      i += 2;\n    }else\n    if( (z[i] & 0xF0)==0xE0 ){\n      if( i+2>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1;\n      i += 3;\n    }else\n    if( (z[i] & 0xF8)==0xF0 ){\n      if( i+3>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1;\n      if( (z[i+2] & 0xC0)!=0x80 ) return 1;\n      i += 3;\n    }else{\n      return 1;\n    }\n  }\n\n  return 0;\n}\n\n/*\n** This function is also purely an internal test. It does not contribute to \n** FTS functionality, or even the integrity-check, in any way.\n*/\nstatic void fts5TestTerm(\n  Fts5Index *p, \n  Fts5Buffer *pPrev,              /* Previous term */\n  const char *z, int n,           /* Possibly new term to test */\n  u64 expected,\n  u64 *pCksum\n){\n  int rc = p->rc;\n  if( pPrev->n==0 ){\n    fts5BufferSet(&rc, pPrev, n, (const u8*)z);\n  }else\n  if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){\n    u64 cksum3 = *pCksum;\n    const char *zTerm = (const char*)&pPrev->p[1];  /* term sans prefix-byte */\n    int nTerm = pPrev->n-1;            /* Size of zTerm in bytes */\n    int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);\n    int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);\n    u64 ck1 = 0;\n    u64 ck2 = 0;\n\n    /* Check that the results returned for ASC and DESC queries are\n    ** the same. If not, call this corruption.  */\n    rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);\n    if( rc==SQLITE_OK ){\n      int f = flags|FTS5INDEX_QUERY_DESC;\n      rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);\n    }\n    if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;\n\n    /* If this is a prefix query, check that the results returned if the\n    ** the index is disabled are the same. In both ASC and DESC order. \n    **\n    ** This check may only be performed if the hash table is empty. This\n    ** is because the hash table only supports a single scan query at\n    ** a time, and the multi-iter loop from which this function is called\n    ** is already performing such a scan. \n    **\n    ** Also only do this if buffer zTerm contains nTerm bytes of valid\n    ** utf-8. Otherwise, the last part of the buffer contents might contain\n    ** a non-utf-8 sequence that happens to be a prefix of a valid utf-8\n    ** character stored in the main fts index, which will cause the\n    ** test to fail.  */\n    if( p->nPendingData==0 && 0==fts5TestUtf8(zTerm, nTerm) ){\n      if( iIdx>0 && rc==SQLITE_OK ){\n        int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;\n        ck2 = 0;\n        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);\n        if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;\n      }\n      if( iIdx>0 && rc==SQLITE_OK ){\n        int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;\n        ck2 = 0;\n        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);\n        if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;\n      }\n    }\n\n    cksum3 ^= ck1;\n    fts5BufferSet(&rc, pPrev, n, (const u8*)z);\n\n    if( rc==SQLITE_OK && cksum3!=expected ){\n      rc = FTS5_CORRUPT;\n    }\n    *pCksum = cksum3;\n  }\n  p->rc = rc;\n}\n \n#else\n# define fts5TestDlidxReverse(x,y,z)\n# define fts5TestTerm(u,v,w,x,y,z)\n#endif\n\n/*\n** Check that:\n**\n**   1) All leaves of pSeg between iFirst and iLast (inclusive) exist and\n**      contain zero terms.\n**   2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and\n**      contain zero rowids.\n*/\nstatic void fts5IndexIntegrityCheckEmpty(\n  Fts5Index *p,\n  Fts5StructureSegment *pSeg,     /* Segment to check internal consistency */\n  int iFirst,\n  int iNoRowid,\n  int iLast\n){\n  int i;\n\n  /* Now check that the iter.nEmpty leaves following the current leaf\n  ** (a) exist and (b) contain no terms. */\n  for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){\n    Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));\n    if( pLeaf ){\n      if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;\n      if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;\n    }\n    fts5DataRelease(pLeaf);\n  }\n}\n\nstatic void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){\n  int iTermOff = 0;\n  int ii;\n\n  Fts5Buffer buf1 = {0,0,0};\n  Fts5Buffer buf2 = {0,0,0};\n\n  ii = pLeaf->szLeaf;\n  while( ii<pLeaf->nn && p->rc==SQLITE_OK ){\n    int res;\n    int iOff;\n    int nIncr;\n\n    ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);\n    iTermOff += nIncr;\n    iOff = iTermOff;\n\n    if( iOff>=pLeaf->szLeaf ){\n      p->rc = FTS5_CORRUPT;\n    }else if( iTermOff==nIncr ){\n      int nByte;\n      iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);\n      if( (iOff+nByte)>pLeaf->szLeaf ){\n        p->rc = FTS5_CORRUPT;\n      }else{\n        fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);\n      }\n    }else{\n      int nKeep, nByte;\n      iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);\n      iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);\n      if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){\n        p->rc = FTS5_CORRUPT;\n      }else{\n        buf1.n = nKeep;\n        fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);\n      }\n\n      if( p->rc==SQLITE_OK ){\n        res = fts5BufferCompare(&buf1, &buf2);\n        if( res<=0 ) p->rc = FTS5_CORRUPT;\n      }\n    }\n    fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);\n  }\n\n  fts5BufferFree(&buf1);\n  fts5BufferFree(&buf2);\n}\n\nstatic void fts5IndexIntegrityCheckSegment(\n  Fts5Index *p,                   /* FTS5 backend object */\n  Fts5StructureSegment *pSeg      /* Segment to check internal consistency */\n){\n  Fts5Config *pConfig = p->pConfig;\n  sqlite3_stmt *pStmt = 0;\n  int rc2;\n  int iIdxPrevLeaf = pSeg->pgnoFirst-1;\n  int iDlidxPrevLeaf = pSeg->pgnoLast;\n\n  if( pSeg->pgnoFirst==0 ) return;\n\n  fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(\n      \"SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d \"\n      \"ORDER BY 1, 2\",\n      pConfig->zDb, pConfig->zName, pSeg->iSegid\n  ));\n\n  /* Iterate through the b-tree hierarchy.  */\n  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){\n    i64 iRow;                     /* Rowid for this leaf */\n    Fts5Data *pLeaf;              /* Data for this leaf */\n\n    const char *zIdxTerm = (const char*)sqlite3_column_blob(pStmt, 1);\n    int nIdxTerm = sqlite3_column_bytes(pStmt, 1);\n    int iIdxLeaf = sqlite3_column_int(pStmt, 2);\n    int bIdxDlidx = sqlite3_column_int(pStmt, 3);\n\n    /* If the leaf in question has already been trimmed from the segment, \n    ** ignore this b-tree entry. Otherwise, load it into memory. */\n    if( iIdxLeaf<pSeg->pgnoFirst ) continue;\n    iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);\n    pLeaf = fts5LeafRead(p, iRow);\n    if( pLeaf==0 ) break;\n\n    /* Check that the leaf contains at least one term, and that it is equal\n    ** to or larger than the split-key in zIdxTerm.  Also check that if there\n    ** is also a rowid pointer within the leaf page header, it points to a\n    ** location before the term.  */\n    if( pLeaf->nn<=pLeaf->szLeaf ){\n      p->rc = FTS5_CORRUPT;\n    }else{\n      int iOff;                   /* Offset of first term on leaf */\n      int iRowidOff;              /* Offset of first rowid on leaf */\n      int nTerm;                  /* Size of term on leaf in bytes */\n      int res;                    /* Comparison of term and split-key */\n\n      iOff = fts5LeafFirstTermOff(pLeaf);\n      iRowidOff = fts5LeafFirstRowidOff(pLeaf);\n      if( iRowidOff>=iOff || iOff>=pLeaf->szLeaf ){\n        p->rc = FTS5_CORRUPT;\n      }else{\n        iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);\n        res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));\n        if( res==0 ) res = nTerm - nIdxTerm;\n        if( res<0 ) p->rc = FTS5_CORRUPT;\n      }\n\n      fts5IntegrityCheckPgidx(p, pLeaf);\n    }\n    fts5DataRelease(pLeaf);\n    if( p->rc ) break;\n\n    /* Now check that the iter.nEmpty leaves following the current leaf\n    ** (a) exist and (b) contain no terms. */\n    fts5IndexIntegrityCheckEmpty(\n        p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1\n    );\n    if( p->rc ) break;\n\n    /* If there is a doclist-index, check that it looks right. */\n    if( bIdxDlidx ){\n      Fts5DlidxIter *pDlidx = 0;  /* For iterating through doclist index */\n      int iPrevLeaf = iIdxLeaf;\n      int iSegid = pSeg->iSegid;\n      int iPg = 0;\n      i64 iKey;\n\n      for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);\n          fts5DlidxIterEof(p, pDlidx)==0;\n          fts5DlidxIterNext(p, pDlidx)\n      ){\n\n        /* Check any rowid-less pages that occur before the current leaf. */\n        for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){\n          iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);\n          pLeaf = fts5DataRead(p, iKey);\n          if( pLeaf ){\n            if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;\n            fts5DataRelease(pLeaf);\n          }\n        }\n        iPrevLeaf = fts5DlidxIterPgno(pDlidx);\n\n        /* Check that the leaf page indicated by the iterator really does\n        ** contain the rowid suggested by the same. */\n        iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);\n        pLeaf = fts5DataRead(p, iKey);\n        if( pLeaf ){\n          i64 iRowid;\n          int iRowidOff = fts5LeafFirstRowidOff(pLeaf);\n          ASSERT_SZLEAF_OK(pLeaf);\n          if( iRowidOff>=pLeaf->szLeaf ){\n            p->rc = FTS5_CORRUPT;\n          }else{\n            fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);\n            if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;\n          }\n          fts5DataRelease(pLeaf);\n        }\n      }\n\n      iDlidxPrevLeaf = iPg;\n      fts5DlidxIterFree(pDlidx);\n      fts5TestDlidxReverse(p, iSegid, iIdxLeaf);\n    }else{\n      iDlidxPrevLeaf = pSeg->pgnoLast;\n      /* TODO: Check there is no doclist index */\n    }\n\n    iIdxPrevLeaf = iIdxLeaf;\n  }\n\n  rc2 = sqlite3_finalize(pStmt);\n  if( p->rc==SQLITE_OK ) p->rc = rc2;\n\n  /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */\n#if 0\n  if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){\n    p->rc = FTS5_CORRUPT;\n  }\n#endif\n}\n\n\n/*\n** Run internal checks to ensure that the FTS index (a) is internally \n** consistent and (b) contains entries for which the XOR of the checksums\n** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.\n**\n** Return SQLITE_CORRUPT if any of the internal checks fail, or if the\n** checksum does not match. Return SQLITE_OK if all checks pass without\n** error, or some other SQLite error code if another error (e.g. OOM)\n** occurs.\n*/\nstatic int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){\n  int eDetail = p->pConfig->eDetail;\n  u64 cksum2 = 0;                 /* Checksum based on contents of indexes */\n  Fts5Buffer poslist = {0,0,0};   /* Buffer used to hold a poslist */\n  Fts5Iter *pIter;                /* Used to iterate through entire index */\n  Fts5Structure *pStruct;         /* Index structure */\n\n#ifdef SQLITE_DEBUG\n  /* Used by extra internal tests only run if NDEBUG is not defined */\n  u64 cksum3 = 0;                 /* Checksum based on contents of indexes */\n  Fts5Buffer term = {0,0,0};      /* Buffer used to hold most recent term */\n#endif\n  const int flags = FTS5INDEX_QUERY_NOOUTPUT;\n  \n  /* Load the FTS index structure */\n  pStruct = fts5StructureRead(p);\n\n  /* Check that the internal nodes of each segment match the leaves */\n  if( pStruct ){\n    int iLvl, iSeg;\n    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){\n      for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){\n        Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];\n        fts5IndexIntegrityCheckSegment(p, pSeg);\n      }\n    }\n  }\n\n  /* The cksum argument passed to this function is a checksum calculated\n  ** based on all expected entries in the FTS index (including prefix index\n  ** entries). This block checks that a checksum calculated based on the\n  ** actual contents of FTS index is identical.\n  **\n  ** Two versions of the same checksum are calculated. The first (stack\n  ** variable cksum2) based on entries extracted from the full-text index\n  ** while doing a linear scan of each individual index in turn. \n  **\n  ** As each term visited by the linear scans, a separate query for the\n  ** same term is performed. cksum3 is calculated based on the entries\n  ** extracted by these queries.\n  */\n  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);\n      fts5MultiIterEof(p, pIter)==0;\n      fts5MultiIterNext(p, pIter, 0, 0)\n  ){\n    int n;                      /* Size of term in bytes */\n    i64 iPos = 0;               /* Position read from poslist */\n    int iOff = 0;               /* Offset within poslist */\n    i64 iRowid = fts5MultiIterRowid(pIter);\n    char *z = (char*)fts5MultiIterTerm(pIter, &n);\n\n    /* If this is a new term, query for it. Update cksum3 with the results. */\n    fts5TestTerm(p, &term, z, n, cksum2, &cksum3);\n\n    if( eDetail==FTS5_DETAIL_NONE ){\n      if( 0==fts5MultiIterIsEmpty(p, pIter) ){\n        cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);\n      }\n    }else{\n      poslist.n = 0;\n      fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);\n      while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){\n        int iCol = FTS5_POS2COLUMN(iPos);\n        int iTokOff = FTS5_POS2OFFSET(iPos);\n        cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);\n      }\n    }\n  }\n  fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);\n\n  fts5MultiIterFree(pIter);\n  if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;\n\n  fts5StructureRelease(pStruct);\n#ifdef SQLITE_DEBUG\n  fts5BufferFree(&term);\n#endif\n  fts5BufferFree(&poslist);\n  return fts5IndexReturn(p);\n}\n\n/*************************************************************************\n**************************************************************************\n** Below this point is the implementation of the fts5_decode() scalar\n** function only.\n*/\n\n/*\n** Decode a segment-data rowid from the %_data table. This function is\n** the opposite of macro FTS5_SEGMENT_ROWID().\n*/\nstatic void fts5DecodeRowid(\n  i64 iRowid,                     /* Rowid from %_data table */\n  int *piSegid,                   /* OUT: Segment id */\n  int *pbDlidx,                   /* OUT: Dlidx flag */\n  int *piHeight,                  /* OUT: Height */\n  int *piPgno                     /* OUT: Page number */\n){\n  *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));\n  iRowid >>= FTS5_DATA_PAGE_B;\n\n  *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));\n  iRowid >>= FTS5_DATA_HEIGHT_B;\n\n  *pbDlidx = (int)(iRowid & 0x0001);\n  iRowid >>= FTS5_DATA_DLI_B;\n\n  *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));\n}\n\nstatic void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){\n  int iSegid, iHeight, iPgno, bDlidx;       /* Rowid compenents */\n  fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);\n\n  if( iSegid==0 ){\n    if( iKey==FTS5_AVERAGES_ROWID ){\n      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, \"{averages} \");\n    }else{\n      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, \"{structure}\");\n    }\n  }\n  else{\n    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, \"{%ssegid=%d h=%d pgno=%d}\",\n        bDlidx ? \"dlidx \" : \"\", iSegid, iHeight, iPgno\n    );\n  }\n}\n\nstatic void fts5DebugStructure(\n  int *pRc,                       /* IN/OUT: error code */\n  Fts5Buffer *pBuf,\n  Fts5Structure *p\n){\n  int iLvl, iSeg;                 /* Iterate through levels, segments */\n\n  for(iLvl=0; iLvl<p->nLevel; iLvl++){\n    Fts5StructureLevel *pLvl = &p->aLevel[iLvl];\n    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, \n        \" {lvl=%d nMerge=%d nSeg=%d\", iLvl, pLvl->nMerge, pLvl->nSeg\n    );\n    for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){\n      Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];\n      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, \" {id=%d leaves=%d..%d}\", \n          pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast\n      );\n    }\n    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, \"}\");\n  }\n}\n\n/*\n** This is part of the fts5_decode() debugging aid.\n**\n** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This\n** function appends a human-readable representation of the same object\n** to the buffer passed as the second argument. \n*/\nstatic void fts5DecodeStructure(\n  int *pRc,                       /* IN/OUT: error code */\n  Fts5Buffer *pBuf,\n  const u8 *pBlob, int nBlob\n){\n  int rc;                         /* Return code */\n  Fts5Structure *p = 0;           /* Decoded structure object */\n\n  rc = fts5StructureDecode(pBlob, nBlob, 0, &p);\n  if( rc!=SQLITE_OK ){\n    *pRc = rc;\n    return;\n  }\n\n  fts5DebugStructure(pRc, pBuf, p);\n  fts5StructureRelease(p);\n}\n\n/*\n** This is part of the fts5_decode() debugging aid.\n**\n** Arguments pBlob/nBlob contain an \"averages\" record. This function \n** appends a human-readable representation of record to the buffer passed \n** as the second argument. \n*/\nstatic void fts5DecodeAverages(\n  int *pRc,                       /* IN/OUT: error code */\n  Fts5Buffer *pBuf,\n  const u8 *pBlob, int nBlob\n){\n  int i = 0;\n  const char *zSpace = \"\";\n\n  while( i<nBlob ){\n    u64 iVal;\n    i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);\n    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, \"%s%d\", zSpace, (int)iVal);\n    zSpace = \" \";\n  }\n}\n\n/*\n** Buffer (a/n) is assumed to contain a list of serialized varints. Read\n** each varint and append its string representation to buffer pBuf. Return\n** after either the input buffer is exhausted or a 0 value is read.\n**\n** The return value is the number of bytes read from the input buffer.\n*/\nstatic int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){\n  int iOff = 0;\n  while( iOff<n ){\n    int iVal;\n    iOff += fts5GetVarint32(&a[iOff], iVal);\n    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, \" %d\", iVal);\n  }\n  return iOff;\n}\n\n/*\n** The start of buffer (a/n) contains the start of a doclist. The doclist\n** may or may not finish within the buffer. This function appends a text\n** representation of the part of the doclist that is present to buffer\n** pBuf. \n**\n** The return value is the number of bytes read from the input buffer.\n*/\nstatic int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){\n  i64 iDocid = 0;\n  int iOff = 0;\n\n  if( n>0 ){\n    iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);\n    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, \" id=%lld\", iDocid);\n  }\n  while( iOff<n ){\n    int nPos;\n    int bDel;\n    iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);\n    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, \" nPos=%d%s\", nPos, bDel?\"*\":\"\");\n    iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));\n    if( iOff<n ){\n      i64 iDelta;\n      iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);\n      iDocid += iDelta;\n      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, \" id=%lld\", iDocid);\n    }\n  }\n\n  return iOff;\n}\n\n/*\n** This function is part of the fts5_decode() debugging function. It is \n** only ever used with detail=none tables.\n**\n** Buffer (pData/nData) contains a doclist in the format used by detail=none\n** tables. This function appends a human-readable version of that list to\n** buffer pBuf.\n**\n** If *pRc is other than SQLITE_OK when this function is called, it is a\n** no-op. If an OOM or other error occurs within this function, *pRc is\n** set to an SQLite error code before returning. The final state of buffer\n** pBuf is undefined in this case.\n*/\nstatic void fts5DecodeRowidList(\n  int *pRc,                       /* IN/OUT: Error code */\n  Fts5Buffer *pBuf,               /* Buffer to append text to */\n  const u8 *pData, int nData      /* Data to decode list-of-rowids from */\n){\n  int i = 0;\n  i64 iRowid = 0;\n\n  while( i<nData ){\n    const char *zApp = \"\";\n    u64 iVal;\n    i += sqlite3Fts5GetVarint(&pData[i], &iVal);\n    iRowid += iVal;\n\n    if( i<nData && pData[i]==0x00 ){\n      i++;\n      if( i<nData && pData[i]==0x00 ){\n        i++;\n        zApp = \"+\";\n      }else{\n        zApp = \"*\";\n      }\n    }\n\n    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, \" %lld%s\", iRowid, zApp);\n  }\n}\n\n/*\n** The implementation of user-defined scalar function fts5_decode().\n*/\nstatic void fts5DecodeFunction(\n  sqlite3_context *pCtx,          /* Function call context */\n  int nArg,                       /* Number of args (always 2) */\n  sqlite3_value **apVal           /* Function arguments */\n){\n  i64 iRowid;                     /* Rowid for record being decoded */\n  int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */\n  const u8 *aBlob; int n;         /* Record to decode */\n  u8 *a = 0;\n  Fts5Buffer s;                   /* Build up text to return here */\n  int rc = SQLITE_OK;             /* Return code */\n  sqlite3_int64 nSpace = 0;\n  int eDetailNone = (sqlite3_user_data(pCtx)!=0);\n\n  assert( nArg==2 );\n  UNUSED_PARAM(nArg);\n  memset(&s, 0, sizeof(Fts5Buffer));\n  iRowid = sqlite3_value_int64(apVal[0]);\n\n  /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]\n  ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents\n  ** buffer overreads even if the record is corrupt.  */\n  n = sqlite3_value_bytes(apVal[1]);\n  aBlob = sqlite3_value_blob(apVal[1]);\n  nSpace = n + FTS5_DATA_ZERO_PADDING;\n  a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);\n  if( a==0 ) goto decode_out;\n  if( n>0 ) memcpy(a, aBlob, n);\n\n  fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);\n\n  fts5DebugRowid(&rc, &s, iRowid);\n  if( bDlidx ){\n    Fts5Data dlidx;\n    Fts5DlidxLvl lvl;\n\n    dlidx.p = a;\n    dlidx.nn = n;\n\n    memset(&lvl, 0, sizeof(Fts5DlidxLvl));\n    lvl.pData = &dlidx;\n    lvl.iLeafPgno = iPgno;\n\n    for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){\n      sqlite3Fts5BufferAppendPrintf(&rc, &s, \n          \" %d(%lld)\", lvl.iLeafPgno, lvl.iRowid\n      );\n    }\n  }else if( iSegid==0 ){\n    if( iRowid==FTS5_AVERAGES_ROWID ){\n      fts5DecodeAverages(&rc, &s, a, n);\n    }else{\n      fts5DecodeStructure(&rc, &s, a, n);\n    }\n  }else if( eDetailNone ){\n    Fts5Buffer term;              /* Current term read from page */\n    int szLeaf;\n    int iPgidxOff = szLeaf = fts5GetU16(&a[2]);\n    int iTermOff;\n    int nKeep = 0;\n    int iOff;\n\n    memset(&term, 0, sizeof(Fts5Buffer));\n\n    /* Decode any entries that occur before the first term. */\n    if( szLeaf<n ){\n      iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);\n    }else{\n      iTermOff = szLeaf;\n    }\n    fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);\n\n    iOff = iTermOff;\n    while( iOff<szLeaf ){\n      int nAppend;\n\n      /* Read the term data for the next term*/\n      iOff += fts5GetVarint32(&a[iOff], nAppend);\n      term.n = nKeep;\n      fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);\n      sqlite3Fts5BufferAppendPrintf(\n          &rc, &s, \" term=%.*s\", term.n, (const char*)term.p\n      );\n      iOff += nAppend;\n\n      /* Figure out where the doclist for this term ends */\n      if( iPgidxOff<n ){\n        int nIncr;\n        iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);\n        iTermOff += nIncr;\n      }else{\n        iTermOff = szLeaf;\n      }\n\n      fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);\n      iOff = iTermOff;\n      if( iOff<szLeaf ){\n        iOff += fts5GetVarint32(&a[iOff], nKeep);\n      }\n    }\n\n    fts5BufferFree(&term);\n  }else{\n    Fts5Buffer term;              /* Current term read from page */\n    int szLeaf;                   /* Offset of pgidx in a[] */\n    int iPgidxOff;\n    int iPgidxPrev = 0;           /* Previous value read from pgidx */\n    int iTermOff = 0;\n    int iRowidOff = 0;\n    int iOff;\n    int nDoclist;\n\n    memset(&term, 0, sizeof(Fts5Buffer));\n\n    if( n<4 ){\n      sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)\"corrupt\");\n      goto decode_out;\n    }else{\n      iRowidOff = fts5GetU16(&a[0]);\n      iPgidxOff = szLeaf = fts5GetU16(&a[2]);\n      if( iPgidxOff<n ){\n        fts5GetVarint32(&a[iPgidxOff], iTermOff);\n      }else if( iPgidxOff>n ){\n        rc = FTS5_CORRUPT;\n        goto decode_out;\n      }\n    }\n\n    /* Decode the position list tail at the start of the page */\n    if( iRowidOff!=0 ){\n      iOff = iRowidOff;\n    }else if( iTermOff!=0 ){\n      iOff = iTermOff;\n    }else{\n      iOff = szLeaf;\n    }\n    if( iOff>n ){\n      rc = FTS5_CORRUPT;\n      goto decode_out;\n    }\n    fts5DecodePoslist(&rc, &s, &a[4], iOff-4);\n\n    /* Decode any more doclist data that appears on the page before the\n    ** first term. */\n    nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;\n    if( nDoclist+iOff>n ){\n      rc = FTS5_CORRUPT;\n      goto decode_out;\n    }\n    fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);\n\n    while( iPgidxOff<n && rc==SQLITE_OK ){\n      int bFirst = (iPgidxOff==szLeaf);     /* True for first term on page */\n      int nByte;                            /* Bytes of data */\n      int iEnd;\n      \n      iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);\n      iPgidxPrev += nByte;\n      iOff = iPgidxPrev;\n\n      if( iPgidxOff<n ){\n        fts5GetVarint32(&a[iPgidxOff], nByte);\n        iEnd = iPgidxPrev + nByte;\n      }else{\n        iEnd = szLeaf;\n      }\n      if( iEnd>szLeaf ){\n        rc = FTS5_CORRUPT;\n        break;\n      }\n\n      if( bFirst==0 ){\n        iOff += fts5GetVarint32(&a[iOff], nByte);\n        if( nByte>term.n ){\n          rc = FTS5_CORRUPT;\n          break;\n        }\n        term.n = nByte;\n      }\n      iOff += fts5GetVarint32(&a[iOff], nByte);\n      if( iOff+nByte>n ){\n        rc = FTS5_CORRUPT;\n        break;\n      }\n      fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);\n      iOff += nByte;\n\n      sqlite3Fts5BufferAppendPrintf(\n          &rc, &s, \" term=%.*s\", term.n, (const char*)term.p\n      );\n      iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);\n    }\n\n    fts5BufferFree(&term);\n  }\n  \n decode_out:\n  sqlite3_free(a);\n  if( rc==SQLITE_OK ){\n    sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);\n  }else{\n    sqlite3_result_error_code(pCtx, rc);\n  }\n  fts5BufferFree(&s);\n}\n\n/*\n** The implementation of user-defined scalar function fts5_rowid().\n*/\nstatic void fts5RowidFunction(\n  sqlite3_context *pCtx,          /* Function call context */\n  int nArg,                       /* Number of args (always 2) */\n  sqlite3_value **apVal           /* Function arguments */\n){\n  const char *zArg;\n  if( nArg==0 ){\n    sqlite3_result_error(pCtx, \"should be: fts5_rowid(subject, ....)\", -1);\n  }else{\n    zArg = (const char*)sqlite3_value_text(apVal[0]);\n    if( 0==sqlite3_stricmp(zArg, \"segment\") ){\n      i64 iRowid;\n      int segid, pgno;\n      if( nArg!=3 ){\n        sqlite3_result_error(pCtx, \n            \"should be: fts5_rowid('segment', segid, pgno))\", -1\n        );\n      }else{\n        segid = sqlite3_value_int(apVal[1]);\n        pgno = sqlite3_value_int(apVal[2]);\n        iRowid = FTS5_SEGMENT_ROWID(segid, pgno);\n        sqlite3_result_int64(pCtx, iRowid);\n      }\n    }else{\n      sqlite3_result_error(pCtx, \n        \"first arg to fts5_rowid() must be 'segment'\" , -1\n      );\n    }\n  }\n}\n\n/*\n** This is called as part of registering the FTS5 module with database\n** connection db. It registers several user-defined scalar functions useful\n** with FTS5.\n**\n** If successful, SQLITE_OK is returned. If an error occurs, some other\n** SQLite error code is returned instead.\n*/\nstatic int sqlite3Fts5IndexInit(sqlite3 *db){\n  int rc = sqlite3_create_function(\n      db, \"fts5_decode\", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0\n  );\n\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_function(\n        db, \"fts5_decode_none\", 2, \n        SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0\n    );\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_function(\n        db, \"fts5_rowid\", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0\n    );\n  }\n  return rc;\n}\n\n\nstatic int sqlite3Fts5IndexReset(Fts5Index *p){\n  assert( p->pStruct==0 || p->iStructVersion!=0 );\n  if( fts5IndexDataVersion(p)!=p->iStructVersion ){\n    fts5StructureInvalidate(p);\n  }\n  return fts5IndexReturn(p);\n}\n\n/*\n** 2014 Jun 09\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This is an SQLite module implementing full-text search.\n*/\n\n\n/* #include \"fts5Int.h\" */\n\n/*\n** This variable is set to false when running tests for which the on disk\n** structures should not be corrupt. Otherwise, true. If it is false, extra\n** assert() conditions in the fts5 code are activated - conditions that are\n** only true if it is guaranteed that the fts5 database is not corrupt.\n*/\nSQLITE_API int sqlite3_fts5_may_be_corrupt = 1;\n\n\ntypedef struct Fts5Auxdata Fts5Auxdata;\ntypedef struct Fts5Auxiliary Fts5Auxiliary;\ntypedef struct Fts5Cursor Fts5Cursor;\ntypedef struct Fts5FullTable Fts5FullTable;\ntypedef struct Fts5Sorter Fts5Sorter;\ntypedef struct Fts5TokenizerModule Fts5TokenizerModule;\n\n/*\n** NOTES ON TRANSACTIONS: \n**\n** SQLite invokes the following virtual table methods as transactions are \n** opened and closed by the user:\n**\n**     xBegin():    Start of a new transaction.\n**     xSync():     Initial part of two-phase commit.\n**     xCommit():   Final part of two-phase commit.\n**     xRollback(): Rollback the transaction.\n**\n** Anything that is required as part of a commit that may fail is performed\n** in the xSync() callback. Current versions of SQLite ignore any errors \n** returned by xCommit().\n**\n** And as sub-transactions are opened/closed:\n**\n**     xSavepoint(int S):  Open savepoint S.\n**     xRelease(int S):    Commit and close savepoint S.\n**     xRollbackTo(int S): Rollback to start of savepoint S.\n**\n** During a write-transaction the fts5_index.c module may cache some data \n** in-memory. It is flushed to disk whenever xSync(), xRelease() or\n** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo() \n** is called.\n**\n** Additionally, if SQLITE_DEBUG is defined, an instance of the following\n** structure is used to record the current transaction state. This information\n** is not required, but it is used in the assert() statements executed by\n** function fts5CheckTransactionState() (see below).\n*/\nstruct Fts5TransactionState {\n  int eState;                     /* 0==closed, 1==open, 2==synced */\n  int iSavepoint;                 /* Number of open savepoints (0 -> none) */\n};\n\n/*\n** A single object of this type is allocated when the FTS5 module is \n** registered with a database handle. It is used to store pointers to\n** all registered FTS5 extensions - tokenizers and auxiliary functions.\n*/\nstruct Fts5Global {\n  fts5_api api;                   /* User visible part of object (see fts5.h) */\n  sqlite3 *db;                    /* Associated database connection */ \n  i64 iNextId;                    /* Used to allocate unique cursor ids */\n  Fts5Auxiliary *pAux;            /* First in list of all aux. functions */\n  Fts5TokenizerModule *pTok;      /* First in list of all tokenizer modules */\n  Fts5TokenizerModule *pDfltTok;  /* Default tokenizer module */\n  Fts5Cursor *pCsr;               /* First in list of all open cursors */\n};\n\n/*\n** Each auxiliary function registered with the FTS5 module is represented\n** by an object of the following type. All such objects are stored as part\n** of the Fts5Global.pAux list.\n*/\nstruct Fts5Auxiliary {\n  Fts5Global *pGlobal;            /* Global context for this function */\n  char *zFunc;                    /* Function name (nul-terminated) */\n  void *pUserData;                /* User-data pointer */\n  fts5_extension_function xFunc;  /* Callback function */\n  void (*xDestroy)(void*);        /* Destructor function */\n  Fts5Auxiliary *pNext;           /* Next registered auxiliary function */\n};\n\n/*\n** Each tokenizer module registered with the FTS5 module is represented\n** by an object of the following type. All such objects are stored as part\n** of the Fts5Global.pTok list.\n*/\nstruct Fts5TokenizerModule {\n  char *zName;                    /* Name of tokenizer */\n  void *pUserData;                /* User pointer passed to xCreate() */\n  fts5_tokenizer x;               /* Tokenizer functions */\n  void (*xDestroy)(void*);        /* Destructor function */\n  Fts5TokenizerModule *pNext;     /* Next registered tokenizer module */\n};\n\nstruct Fts5FullTable {\n  Fts5Table p;                    /* Public class members from fts5Int.h */\n  Fts5Storage *pStorage;          /* Document store */\n  Fts5Global *pGlobal;            /* Global (connection wide) data */\n  Fts5Cursor *pSortCsr;           /* Sort data from this cursor */\n#ifdef SQLITE_DEBUG\n  struct Fts5TransactionState ts;\n#endif\n};\n\nstruct Fts5MatchPhrase {\n  Fts5Buffer *pPoslist;           /* Pointer to current poslist */\n  int nTerm;                      /* Size of phrase in terms */\n};\n\n/*\n** pStmt:\n**   SELECT rowid, <fts> FROM <fts> ORDER BY +rank;\n**\n** aIdx[]:\n**   There is one entry in the aIdx[] array for each phrase in the query,\n**   the value of which is the offset within aPoslist[] following the last \n**   byte of the position list for the corresponding phrase.\n*/\nstruct Fts5Sorter {\n  sqlite3_stmt *pStmt;\n  i64 iRowid;                     /* Current rowid */\n  const u8 *aPoslist;             /* Position lists for current row */\n  int nIdx;                       /* Number of entries in aIdx[] */\n  int aIdx[1];                    /* Offsets into aPoslist for current row */\n};\n\n\n/*\n** Virtual-table cursor object.\n**\n** iSpecial:\n**   If this is a 'special' query (refer to function fts5SpecialMatch()), \n**   then this variable contains the result of the query. \n**\n** iFirstRowid, iLastRowid:\n**   These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the\n**   cursor iterates in ascending order of rowids, iFirstRowid is the lower\n**   limit of rowids to return, and iLastRowid the upper. In other words, the\n**   WHERE clause in the user's query might have been:\n**\n**       <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid\n**\n**   If the cursor iterates in descending order of rowid, iFirstRowid\n**   is the upper limit (i.e. the \"first\" rowid visited) and iLastRowid\n**   the lower.\n*/\nstruct Fts5Cursor {\n  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */\n  Fts5Cursor *pNext;              /* Next cursor in Fts5Cursor.pCsr list */\n  int *aColumnSize;               /* Values for xColumnSize() */\n  i64 iCsrId;                     /* Cursor id */\n\n  /* Zero from this point onwards on cursor reset */\n  int ePlan;                      /* FTS5_PLAN_XXX value */\n  int bDesc;                      /* True for \"ORDER BY rowid DESC\" queries */\n  i64 iFirstRowid;                /* Return no rowids earlier than this */\n  i64 iLastRowid;                 /* Return no rowids later than this */\n  sqlite3_stmt *pStmt;            /* Statement used to read %_content */\n  Fts5Expr *pExpr;                /* Expression for MATCH queries */\n  Fts5Sorter *pSorter;            /* Sorter for \"ORDER BY rank\" queries */\n  int csrflags;                   /* Mask of cursor flags (see below) */\n  i64 iSpecial;                   /* Result of special query */\n\n  /* \"rank\" function. Populated on demand from vtab.xColumn(). */\n  char *zRank;                    /* Custom rank function */\n  char *zRankArgs;                /* Custom rank function args */\n  Fts5Auxiliary *pRank;           /* Rank callback (or NULL) */\n  int nRankArg;                   /* Number of trailing arguments for rank() */\n  sqlite3_value **apRankArg;      /* Array of trailing arguments */\n  sqlite3_stmt *pRankArgStmt;     /* Origin of objects in apRankArg[] */\n\n  /* Auxiliary data storage */\n  Fts5Auxiliary *pAux;            /* Currently executing extension function */\n  Fts5Auxdata *pAuxdata;          /* First in linked list of saved aux-data */\n\n  /* Cache used by auxiliary functions xInst() and xInstCount() */\n  Fts5PoslistReader *aInstIter;   /* One for each phrase */\n  int nInstAlloc;                 /* Size of aInst[] array (entries / 3) */\n  int nInstCount;                 /* Number of phrase instances */\n  int *aInst;                     /* 3 integers per phrase instance */\n};\n\n/*\n** Bits that make up the \"idxNum\" parameter passed indirectly by \n** xBestIndex() to xFilter().\n*/\n#define FTS5_BI_MATCH        0x0001         /* <tbl> MATCH ? */\n#define FTS5_BI_RANK         0x0002         /* rank MATCH ? */\n#define FTS5_BI_ROWID_EQ     0x0004         /* rowid == ? */\n#define FTS5_BI_ROWID_LE     0x0008         /* rowid <= ? */\n#define FTS5_BI_ROWID_GE     0x0010         /* rowid >= ? */\n\n#define FTS5_BI_ORDER_RANK   0x0020\n#define FTS5_BI_ORDER_ROWID  0x0040\n#define FTS5_BI_ORDER_DESC   0x0080\n\n/*\n** Values for Fts5Cursor.csrflags\n*/\n#define FTS5CSR_EOF               0x01\n#define FTS5CSR_REQUIRE_CONTENT   0x02\n#define FTS5CSR_REQUIRE_DOCSIZE   0x04\n#define FTS5CSR_REQUIRE_INST      0x08\n#define FTS5CSR_FREE_ZRANK        0x10\n#define FTS5CSR_REQUIRE_RESEEK    0x20\n#define FTS5CSR_REQUIRE_POSLIST   0x40\n\n#define BitFlagAllTest(x,y) (((x) & (y))==(y))\n#define BitFlagTest(x,y)    (((x) & (y))!=0)\n\n\n/*\n** Macros to Set(), Clear() and Test() cursor flags.\n*/\n#define CsrFlagSet(pCsr, flag)   ((pCsr)->csrflags |= (flag))\n#define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))\n#define CsrFlagTest(pCsr, flag)  ((pCsr)->csrflags & (flag))\n\nstruct Fts5Auxdata {\n  Fts5Auxiliary *pAux;            /* Extension to which this belongs */\n  void *pPtr;                     /* Pointer value */\n  void(*xDelete)(void*);          /* Destructor */\n  Fts5Auxdata *pNext;             /* Next object in linked list */\n};\n\n#ifdef SQLITE_DEBUG\n#define FTS5_BEGIN      1\n#define FTS5_SYNC       2\n#define FTS5_COMMIT     3\n#define FTS5_ROLLBACK   4\n#define FTS5_SAVEPOINT  5\n#define FTS5_RELEASE    6\n#define FTS5_ROLLBACKTO 7\nstatic void fts5CheckTransactionState(Fts5FullTable *p, int op, int iSavepoint){\n  switch( op ){\n    case FTS5_BEGIN:\n      assert( p->ts.eState==0 );\n      p->ts.eState = 1;\n      p->ts.iSavepoint = -1;\n      break;\n\n    case FTS5_SYNC:\n      assert( p->ts.eState==1 );\n      p->ts.eState = 2;\n      break;\n\n    case FTS5_COMMIT:\n      assert( p->ts.eState==2 );\n      p->ts.eState = 0;\n      break;\n\n    case FTS5_ROLLBACK:\n      assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );\n      p->ts.eState = 0;\n      break;\n\n    case FTS5_SAVEPOINT:\n      assert( p->ts.eState==1 );\n      assert( iSavepoint>=0 );\n      assert( iSavepoint>=p->ts.iSavepoint );\n      p->ts.iSavepoint = iSavepoint;\n      break;\n      \n    case FTS5_RELEASE:\n      assert( p->ts.eState==1 );\n      assert( iSavepoint>=0 );\n      assert( iSavepoint<=p->ts.iSavepoint );\n      p->ts.iSavepoint = iSavepoint-1;\n      break;\n\n    case FTS5_ROLLBACKTO:\n      assert( p->ts.eState==1 );\n      assert( iSavepoint>=-1 );\n      /* The following assert() can fail if another vtab strikes an error\n      ** within an xSavepoint() call then SQLite calls xRollbackTo() - without\n      ** having called xSavepoint() on this vtab.  */\n      /* assert( iSavepoint<=p->ts.iSavepoint ); */\n      p->ts.iSavepoint = iSavepoint;\n      break;\n  }\n}\n#else\n# define fts5CheckTransactionState(x,y,z)\n#endif\n\n/*\n** Return true if pTab is a contentless table.\n*/\nstatic int fts5IsContentless(Fts5FullTable *pTab){\n  return pTab->p.pConfig->eContent==FTS5_CONTENT_NONE;\n}\n\n/*\n** Delete a virtual table handle allocated by fts5InitVtab(). \n*/\nstatic void fts5FreeVtab(Fts5FullTable *pTab){\n  if( pTab ){\n    sqlite3Fts5IndexClose(pTab->p.pIndex);\n    sqlite3Fts5StorageClose(pTab->pStorage);\n    sqlite3Fts5ConfigFree(pTab->p.pConfig);\n    sqlite3_free(pTab);\n  }\n}\n\n/*\n** The xDisconnect() virtual table method.\n*/\nstatic int fts5DisconnectMethod(sqlite3_vtab *pVtab){\n  fts5FreeVtab((Fts5FullTable*)pVtab);\n  return SQLITE_OK;\n}\n\n/*\n** The xDestroy() virtual table method.\n*/\nstatic int fts5DestroyMethod(sqlite3_vtab *pVtab){\n  Fts5Table *pTab = (Fts5Table*)pVtab;\n  int rc = sqlite3Fts5DropAll(pTab->pConfig);\n  if( rc==SQLITE_OK ){\n    fts5FreeVtab((Fts5FullTable*)pVtab);\n  }\n  return rc;\n}\n\n/*\n** This function is the implementation of both the xConnect and xCreate\n** methods of the FTS3 virtual table.\n**\n** The argv[] array contains the following:\n**\n**   argv[0]   -> module name  (\"fts5\")\n**   argv[1]   -> database name\n**   argv[2]   -> table name\n**   argv[...] -> \"column name\" and other module argument fields.\n*/\nstatic int fts5InitVtab(\n  int bCreate,                    /* True for xCreate, false for xConnect */\n  sqlite3 *db,                    /* The SQLite database connection */\n  void *pAux,                     /* Hash table containing tokenizers */\n  int argc,                       /* Number of elements in argv array */\n  const char * const *argv,       /* xCreate/xConnect argument array */\n  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */\n  char **pzErr                    /* Write any error message here */\n){\n  Fts5Global *pGlobal = (Fts5Global*)pAux;\n  const char **azConfig = (const char**)argv;\n  int rc = SQLITE_OK;             /* Return code */\n  Fts5Config *pConfig = 0;        /* Results of parsing argc/argv */\n  Fts5FullTable *pTab = 0;        /* New virtual table object */\n\n  /* Allocate the new vtab object and parse the configuration */\n  pTab = (Fts5FullTable*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5FullTable));\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);\n    assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );\n  }\n  if( rc==SQLITE_OK ){\n    pTab->p.pConfig = pConfig;\n    pTab->pGlobal = pGlobal;\n  }\n\n  /* Open the index sub-system */\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->p.pIndex, pzErr);\n  }\n\n  /* Open the storage sub-system */\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts5StorageOpen(\n        pConfig, pTab->p.pIndex, bCreate, &pTab->pStorage, pzErr\n    );\n  }\n\n  /* Call sqlite3_declare_vtab() */\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts5ConfigDeclareVtab(pConfig);\n  }\n\n  /* Load the initial configuration */\n  if( rc==SQLITE_OK ){\n    assert( pConfig->pzErrmsg==0 );\n    pConfig->pzErrmsg = pzErr;\n    rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);\n    sqlite3Fts5IndexRollback(pTab->p.pIndex);\n    pConfig->pzErrmsg = 0;\n  }\n\n  if( rc!=SQLITE_OK ){\n    fts5FreeVtab(pTab);\n    pTab = 0;\n  }else if( bCreate ){\n    fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);\n  }\n  *ppVTab = (sqlite3_vtab*)pTab;\n  return rc;\n}\n\n/*\n** The xConnect() and xCreate() methods for the virtual table. All the\n** work is done in function fts5InitVtab().\n*/\nstatic int fts5ConnectMethod(\n  sqlite3 *db,                    /* Database connection */\n  void *pAux,                     /* Pointer to tokenizer hash table */\n  int argc,                       /* Number of elements in argv array */\n  const char * const *argv,       /* xCreate/xConnect argument array */\n  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */\n  char **pzErr                    /* OUT: sqlite3_malloc'd error message */\n){\n  return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);\n}\nstatic int fts5CreateMethod(\n  sqlite3 *db,                    /* Database connection */\n  void *pAux,                     /* Pointer to tokenizer hash table */\n  int argc,                       /* Number of elements in argv array */\n  const char * const *argv,       /* xCreate/xConnect argument array */\n  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */\n  char **pzErr                    /* OUT: sqlite3_malloc'd error message */\n){\n  return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);\n}\n\n/*\n** The different query plans.\n*/\n#define FTS5_PLAN_MATCH          1       /* (<tbl> MATCH ?) */\n#define FTS5_PLAN_SOURCE         2       /* A source cursor for SORTED_MATCH */\n#define FTS5_PLAN_SPECIAL        3       /* An internal query */\n#define FTS5_PLAN_SORTED_MATCH   4       /* (<tbl> MATCH ? ORDER BY rank) */\n#define FTS5_PLAN_SCAN           5       /* No usable constraint */\n#define FTS5_PLAN_ROWID          6       /* (rowid = ?) */\n\n/*\n** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this\n** extension is currently being used by a version of SQLite too old to\n** support index-info flags. In that case this function is a no-op.\n*/\nstatic void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){\n#if SQLITE_VERSION_NUMBER>=3008012\n#ifndef SQLITE_CORE\n  if( sqlite3_libversion_number()>=3008012 )\n#endif\n  {\n    pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;\n  }\n#endif\n}\n\n/*\n** Implementation of the xBestIndex method for FTS5 tables. Within the \n** WHERE constraint, it searches for the following:\n**\n**   1. A MATCH constraint against the table column.\n**   2. A MATCH constraint against the \"rank\" column.\n**   3. A MATCH constraint against some other column.\n**   4. An == constraint against the rowid column.\n**   5. A < or <= constraint against the rowid column.\n**   6. A > or >= constraint against the rowid column.\n**\n** Within the ORDER BY, the following are supported:\n**\n**   5. ORDER BY rank [ASC|DESC]\n**   6. ORDER BY rowid [ASC|DESC]\n**\n** Information for the xFilter call is passed via both the idxNum and \n** idxStr variables. Specifically, idxNum is a bitmask of the following\n** flags used to encode the ORDER BY clause:\n**\n**     FTS5_BI_ORDER_RANK\n**     FTS5_BI_ORDER_ROWID\n**     FTS5_BI_ORDER_DESC\n**\n** idxStr is used to encode data from the WHERE clause. For each argument\n** passed to the xFilter method, the following is appended to idxStr:\n**\n**   Match against table column:            \"m\"\n**   Match against rank column:             \"r\"\n**   Match against other column:            \"<column-number>\"\n**   Equality constraint against the rowid: \"=\"\n**   A < or <= against the rowid:           \"<\"\n**   A > or >= against the rowid:           \">\"\n**\n** This function ensures that there is at most one \"r\" or \"=\". And that if\n** there exists an \"=\" then there is no \"<\" or \">\".\n**\n** Costs are assigned as follows:\n**\n**  a) If an unusable MATCH operator is present in the WHERE clause, the\n**     cost is unconditionally set to 1e50 (a really big number).\n**\n**  a) If a MATCH operator is present, the cost depends on the other\n**     constraints also present. As follows:\n**\n**       * No other constraints:         cost=1000.0\n**       * One rowid range constraint:   cost=750.0\n**       * Both rowid range constraints: cost=500.0\n**       * An == rowid constraint:       cost=100.0\n**\n**  b) Otherwise, if there is no MATCH:\n**\n**       * No other constraints:         cost=1000000.0\n**       * One rowid range constraint:   cost=750000.0\n**       * Both rowid range constraints: cost=250000.0\n**       * An == rowid constraint:       cost=10.0\n**\n** Costs are not modified by the ORDER BY clause.\n*/\nstatic int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){\n  Fts5Table *pTab = (Fts5Table*)pVTab;\n  Fts5Config *pConfig = pTab->pConfig;\n  const int nCol = pConfig->nCol;\n  int idxFlags = 0;               /* Parameter passed through to xFilter() */\n  int i;\n\n  char *idxStr;\n  int iIdxStr = 0;\n  int iCons = 0;\n\n  int bSeenEq = 0;\n  int bSeenGt = 0;\n  int bSeenLt = 0;\n  int bSeenMatch = 0;\n  int bSeenRank = 0;\n\n\n  assert( SQLITE_INDEX_CONSTRAINT_EQ<SQLITE_INDEX_CONSTRAINT_MATCH );\n  assert( SQLITE_INDEX_CONSTRAINT_GT<SQLITE_INDEX_CONSTRAINT_MATCH );\n  assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );\n  assert( SQLITE_INDEX_CONSTRAINT_GE<SQLITE_INDEX_CONSTRAINT_MATCH );\n  assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );\n\n  if( pConfig->bLock ){\n    pTab->base.zErrMsg = sqlite3_mprintf(\n        \"recursively defined fts5 content table\"\n    );\n    return SQLITE_ERROR;\n  }\n\n  idxStr = (char*)sqlite3_malloc(pInfo->nConstraint * 6 + 1);\n  if( idxStr==0 ) return SQLITE_NOMEM;\n  pInfo->idxStr = idxStr;\n  pInfo->needToFreeIdxStr = 1;\n\n  for(i=0; i<pInfo->nConstraint; i++){\n    struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];\n    int iCol = p->iColumn;\n    if( p->op==SQLITE_INDEX_CONSTRAINT_MATCH\n     || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol>=nCol)\n    ){\n      /* A MATCH operator or equivalent */\n      if( p->usable==0 || iCol<0 ){\n        /* As there exists an unusable MATCH constraint this is an \n        ** unusable plan. Set a prohibitively high cost. */\n        pInfo->estimatedCost = 1e50;\n        assert( iIdxStr < pInfo->nConstraint*6 + 1 );\n        idxStr[iIdxStr] = 0;\n        return SQLITE_OK;\n      }else{\n        if( iCol==nCol+1 ){\n          if( bSeenRank ) continue;\n          idxStr[iIdxStr++] = 'r';\n          bSeenRank = 1;\n        }else{\n          bSeenMatch = 1;\n          idxStr[iIdxStr++] = 'm';\n          if( iCol<nCol ){\n            sqlite3_snprintf(6, &idxStr[iIdxStr], \"%d\", iCol);\n            idxStr += strlen(&idxStr[iIdxStr]);\n            assert( idxStr[iIdxStr]=='\\0' );\n          }\n        }\n        pInfo->aConstraintUsage[i].argvIndex = ++iCons;\n        pInfo->aConstraintUsage[i].omit = 1;\n      }\n    }\n    else if( p->usable && bSeenEq==0 \n      && p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol<0 \n    ){\n      idxStr[iIdxStr++] = '=';\n      bSeenEq = 1;\n      pInfo->aConstraintUsage[i].argvIndex = ++iCons;\n    }\n  }\n\n  if( bSeenEq==0 ){\n    for(i=0; i<pInfo->nConstraint; i++){\n      struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];\n      if( p->iColumn<0 && p->usable ){\n        int op = p->op;\n        if( op==SQLITE_INDEX_CONSTRAINT_LT || op==SQLITE_INDEX_CONSTRAINT_LE ){\n          if( bSeenLt ) continue;\n          idxStr[iIdxStr++] = '<';\n          pInfo->aConstraintUsage[i].argvIndex = ++iCons;\n          bSeenLt = 1;\n        }else\n        if( op==SQLITE_INDEX_CONSTRAINT_GT || op==SQLITE_INDEX_CONSTRAINT_GE ){\n          if( bSeenGt ) continue;\n          idxStr[iIdxStr++] = '>';\n          pInfo->aConstraintUsage[i].argvIndex = ++iCons;\n          bSeenGt = 1;\n        }\n      }\n    }\n  }\n  idxStr[iIdxStr] = '\\0';\n\n  /* Set idxFlags flags for the ORDER BY clause */\n  if( pInfo->nOrderBy==1 ){\n    int iSort = pInfo->aOrderBy[0].iColumn;\n    if( iSort==(pConfig->nCol+1) && bSeenMatch ){\n      idxFlags |= FTS5_BI_ORDER_RANK;\n    }else if( iSort==-1 ){\n      idxFlags |= FTS5_BI_ORDER_ROWID;\n    }\n    if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){\n      pInfo->orderByConsumed = 1;\n      if( pInfo->aOrderBy[0].desc ){\n        idxFlags |= FTS5_BI_ORDER_DESC;\n      }\n    }\n  }\n\n  /* Calculate the estimated cost based on the flags set in idxFlags. */\n  if( bSeenEq ){\n    pInfo->estimatedCost = bSeenMatch ? 100.0 : 10.0;\n    if( bSeenMatch==0 ) fts5SetUniqueFlag(pInfo);\n  }else if( bSeenLt && bSeenGt ){\n    pInfo->estimatedCost = bSeenMatch ? 500.0 : 250000.0;\n  }else if( bSeenLt || bSeenGt ){\n    pInfo->estimatedCost = bSeenMatch ? 750.0 : 750000.0;\n  }else{\n    pInfo->estimatedCost = bSeenMatch ? 1000.0 : 1000000.0;\n  }\n\n  pInfo->idxNum = idxFlags;\n  return SQLITE_OK;\n}\n\nstatic int fts5NewTransaction(Fts5FullTable *pTab){\n  Fts5Cursor *pCsr;\n  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){\n    if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;\n  }\n  return sqlite3Fts5StorageReset(pTab->pStorage);\n}\n\n/*\n** Implementation of xOpen method.\n*/\nstatic int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){\n  Fts5FullTable *pTab = (Fts5FullTable*)pVTab;\n  Fts5Config *pConfig = pTab->p.pConfig;\n  Fts5Cursor *pCsr = 0;           /* New cursor object */\n  sqlite3_int64 nByte;            /* Bytes of space to allocate */\n  int rc;                         /* Return code */\n\n  rc = fts5NewTransaction(pTab);\n  if( rc==SQLITE_OK ){\n    nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);\n    pCsr = (Fts5Cursor*)sqlite3_malloc64(nByte);\n    if( pCsr ){\n      Fts5Global *pGlobal = pTab->pGlobal;\n      memset(pCsr, 0, (size_t)nByte);\n      pCsr->aColumnSize = (int*)&pCsr[1];\n      pCsr->pNext = pGlobal->pCsr;\n      pGlobal->pCsr = pCsr;\n      pCsr->iCsrId = ++pGlobal->iNextId;\n    }else{\n      rc = SQLITE_NOMEM;\n    }\n  }\n  *ppCsr = (sqlite3_vtab_cursor*)pCsr;\n  return rc;\n}\n\nstatic int fts5StmtType(Fts5Cursor *pCsr){\n  if( pCsr->ePlan==FTS5_PLAN_SCAN ){\n    return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;\n  }\n  return FTS5_STMT_LOOKUP;\n}\n\n/*\n** This function is called after the cursor passed as the only argument\n** is moved to point at a different row. It clears all cached data \n** specific to the previous row stored by the cursor object.\n*/\nstatic void fts5CsrNewrow(Fts5Cursor *pCsr){\n  CsrFlagSet(pCsr, \n      FTS5CSR_REQUIRE_CONTENT \n    | FTS5CSR_REQUIRE_DOCSIZE \n    | FTS5CSR_REQUIRE_INST \n    | FTS5CSR_REQUIRE_POSLIST \n  );\n}\n\nstatic void fts5FreeCursorComponents(Fts5Cursor *pCsr){\n  Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);\n  Fts5Auxdata *pData;\n  Fts5Auxdata *pNext;\n\n  sqlite3_free(pCsr->aInstIter);\n  sqlite3_free(pCsr->aInst);\n  if( pCsr->pStmt ){\n    int eStmt = fts5StmtType(pCsr);\n    sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);\n  }\n  if( pCsr->pSorter ){\n    Fts5Sorter *pSorter = pCsr->pSorter;\n    sqlite3_finalize(pSorter->pStmt);\n    sqlite3_free(pSorter);\n  }\n\n  if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){\n    sqlite3Fts5ExprFree(pCsr->pExpr);\n  }\n\n  for(pData=pCsr->pAuxdata; pData; pData=pNext){\n    pNext = pData->pNext;\n    if( pData->xDelete ) pData->xDelete(pData->pPtr);\n    sqlite3_free(pData);\n  }\n\n  sqlite3_finalize(pCsr->pRankArgStmt);\n  sqlite3_free(pCsr->apRankArg);\n\n  if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){\n    sqlite3_free(pCsr->zRank);\n    sqlite3_free(pCsr->zRankArgs);\n  }\n\n  sqlite3Fts5IndexCloseReader(pTab->p.pIndex);\n  memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));\n}\n\n\n/*\n** Close the cursor.  For additional information see the documentation\n** on the xClose method of the virtual table interface.\n*/\nstatic int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){\n  if( pCursor ){\n    Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);\n    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;\n    Fts5Cursor **pp;\n\n    fts5FreeCursorComponents(pCsr);\n    /* Remove the cursor from the Fts5Global.pCsr list */\n    for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);\n    *pp = pCsr->pNext;\n\n    sqlite3_free(pCsr);\n  }\n  return SQLITE_OK;\n}\n\nstatic int fts5SorterNext(Fts5Cursor *pCsr){\n  Fts5Sorter *pSorter = pCsr->pSorter;\n  int rc;\n\n  rc = sqlite3_step(pSorter->pStmt);\n  if( rc==SQLITE_DONE ){\n    rc = SQLITE_OK;\n    CsrFlagSet(pCsr, FTS5CSR_EOF);\n  }else if( rc==SQLITE_ROW ){\n    const u8 *a;\n    const u8 *aBlob;\n    int nBlob;\n    int i;\n    int iOff = 0;\n    rc = SQLITE_OK;\n\n    pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);\n    nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);\n    aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);\n\n    /* nBlob==0 in detail=none mode. */\n    if( nBlob>0 ){\n      for(i=0; i<(pSorter->nIdx-1); i++){\n        int iVal;\n        a += fts5GetVarint32(a, iVal);\n        iOff += iVal;\n        pSorter->aIdx[i] = iOff;\n      }\n      pSorter->aIdx[i] = &aBlob[nBlob] - a;\n      pSorter->aPoslist = a;\n    }\n\n    fts5CsrNewrow(pCsr);\n  }\n\n  return rc;\n}\n\n\n/*\n** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors \n** open on table pTab.\n*/\nstatic void fts5TripCursors(Fts5FullTable *pTab){\n  Fts5Cursor *pCsr;\n  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){\n    if( pCsr->ePlan==FTS5_PLAN_MATCH\n     && pCsr->base.pVtab==(sqlite3_vtab*)pTab \n    ){\n      CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);\n    }\n  }\n}\n\n/*\n** If the REQUIRE_RESEEK flag is set on the cursor passed as the first\n** argument, close and reopen all Fts5IndexIter iterators that the cursor \n** is using. Then attempt to move the cursor to a rowid equal to or laster\n** (in the cursors sort order - ASC or DESC) than the current rowid. \n**\n** If the new rowid is not equal to the old, set output parameter *pbSkip\n** to 1 before returning. Otherwise, leave it unchanged.\n**\n** Return SQLITE_OK if successful or if no reseek was required, or an \n** error code if an error occurred.\n*/\nstatic int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){\n  int rc = SQLITE_OK;\n  assert( *pbSkip==0 );\n  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){\n    Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);\n    int bDesc = pCsr->bDesc;\n    i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);\n\n    rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->p.pIndex, iRowid, bDesc);\n    if( rc==SQLITE_OK &&  iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){\n      *pbSkip = 1;\n    }\n\n    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);\n    fts5CsrNewrow(pCsr);\n    if( sqlite3Fts5ExprEof(pCsr->pExpr) ){\n      CsrFlagSet(pCsr, FTS5CSR_EOF);\n      *pbSkip = 1;\n    }\n  }\n  return rc;\n}\n\n\n/*\n** Advance the cursor to the next row in the table that matches the \n** search criteria.\n**\n** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned\n** even if we reach end-of-file.  The fts5EofMethod() will be called\n** subsequently to determine whether or not an EOF was hit.\n*/\nstatic int fts5NextMethod(sqlite3_vtab_cursor *pCursor){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;\n  int rc;\n\n  assert( (pCsr->ePlan<3)==\n          (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE) \n  );\n  assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );\n\n  if( pCsr->ePlan<3 ){\n    int bSkip = 0;\n    if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;\n    rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);\n    CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));\n    fts5CsrNewrow(pCsr);\n  }else{\n    switch( pCsr->ePlan ){\n      case FTS5_PLAN_SPECIAL: {\n        CsrFlagSet(pCsr, FTS5CSR_EOF);\n        rc = SQLITE_OK;\n        break;\n      }\n  \n      case FTS5_PLAN_SORTED_MATCH: {\n        rc = fts5SorterNext(pCsr);\n        break;\n      }\n  \n      default: {\n        Fts5Config *pConfig = ((Fts5Table*)pCursor->pVtab)->pConfig;\n        pConfig->bLock++;\n        rc = sqlite3_step(pCsr->pStmt);\n        pConfig->bLock--;\n        if( rc!=SQLITE_ROW ){\n          CsrFlagSet(pCsr, FTS5CSR_EOF);\n          rc = sqlite3_reset(pCsr->pStmt);\n          if( rc!=SQLITE_OK ){\n            pCursor->pVtab->zErrMsg = sqlite3_mprintf(\n                \"%s\", sqlite3_errmsg(pConfig->db)\n            );\n          }\n        }else{\n          rc = SQLITE_OK;\n        }\n        break;\n      }\n    }\n  }\n  \n  return rc;\n}\n\n\nstatic int fts5PrepareStatement(\n  sqlite3_stmt **ppStmt,\n  Fts5Config *pConfig, \n  const char *zFmt,\n  ...\n){\n  sqlite3_stmt *pRet = 0;\n  int rc;\n  char *zSql;\n  va_list ap;\n\n  va_start(ap, zFmt);\n  zSql = sqlite3_vmprintf(zFmt, ap);\n  if( zSql==0 ){\n    rc = SQLITE_NOMEM; \n  }else{\n    rc = sqlite3_prepare_v3(pConfig->db, zSql, -1, \n                            SQLITE_PREPARE_PERSISTENT, &pRet, 0);\n    if( rc!=SQLITE_OK ){\n      *pConfig->pzErrmsg = sqlite3_mprintf(\"%s\", sqlite3_errmsg(pConfig->db));\n    }\n    sqlite3_free(zSql);\n  }\n\n  va_end(ap);\n  *ppStmt = pRet;\n  return rc;\n} \n\nstatic int fts5CursorFirstSorted(\n  Fts5FullTable *pTab, \n  Fts5Cursor *pCsr, \n  int bDesc\n){\n  Fts5Config *pConfig = pTab->p.pConfig;\n  Fts5Sorter *pSorter;\n  int nPhrase;\n  sqlite3_int64 nByte;\n  int rc;\n  const char *zRank = pCsr->zRank;\n  const char *zRankArgs = pCsr->zRankArgs;\n  \n  nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);\n  nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);\n  pSorter = (Fts5Sorter*)sqlite3_malloc64(nByte);\n  if( pSorter==0 ) return SQLITE_NOMEM;\n  memset(pSorter, 0, (size_t)nByte);\n  pSorter->nIdx = nPhrase;\n\n  /* TODO: It would be better to have some system for reusing statement\n  ** handles here, rather than preparing a new one for each query. But that\n  ** is not possible as SQLite reference counts the virtual table objects.\n  ** And since the statement required here reads from this very virtual \n  ** table, saving it creates a circular reference.\n  **\n  ** If SQLite a built-in statement cache, this wouldn't be a problem. */\n  rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,\n      \"SELECT rowid, rank FROM %Q.%Q ORDER BY %s(\\\"%w\\\"%s%s) %s\",\n      pConfig->zDb, pConfig->zName, zRank, pConfig->zName,\n      (zRankArgs ? \", \" : \"\"),\n      (zRankArgs ? zRankArgs : \"\"),\n      bDesc ? \"DESC\" : \"ASC\"\n  );\n\n  pCsr->pSorter = pSorter;\n  if( rc==SQLITE_OK ){\n    assert( pTab->pSortCsr==0 );\n    pTab->pSortCsr = pCsr;\n    rc = fts5SorterNext(pCsr);\n    pTab->pSortCsr = 0;\n  }\n\n  if( rc!=SQLITE_OK ){\n    sqlite3_finalize(pSorter->pStmt);\n    sqlite3_free(pSorter);\n    pCsr->pSorter = 0;\n  }\n\n  return rc;\n}\n\nstatic int fts5CursorFirst(Fts5FullTable *pTab, Fts5Cursor *pCsr, int bDesc){\n  int rc;\n  Fts5Expr *pExpr = pCsr->pExpr;\n  rc = sqlite3Fts5ExprFirst(pExpr, pTab->p.pIndex, pCsr->iFirstRowid, bDesc);\n  if( sqlite3Fts5ExprEof(pExpr) ){\n    CsrFlagSet(pCsr, FTS5CSR_EOF);\n  }\n  fts5CsrNewrow(pCsr);\n  return rc;\n}\n\n/*\n** Process a \"special\" query. A special query is identified as one with a\n** MATCH expression that begins with a '*' character. The remainder of\n** the text passed to the MATCH operator are used as  the special query\n** parameters.\n*/\nstatic int fts5SpecialMatch(\n  Fts5FullTable *pTab, \n  Fts5Cursor *pCsr, \n  const char *zQuery\n){\n  int rc = SQLITE_OK;             /* Return code */\n  const char *z = zQuery;         /* Special query text */\n  int n;                          /* Number of bytes in text at z */\n\n  while( z[0]==' ' ) z++;\n  for(n=0; z[n] && z[n]!=' '; n++);\n\n  assert( pTab->p.base.zErrMsg==0 );\n  pCsr->ePlan = FTS5_PLAN_SPECIAL;\n\n  if( n==5 && 0==sqlite3_strnicmp(\"reads\", z, n) ){\n    pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->p.pIndex);\n  }\n  else if( n==2 && 0==sqlite3_strnicmp(\"id\", z, n) ){\n    pCsr->iSpecial = pCsr->iCsrId;\n  }\n  else{\n    /* An unrecognized directive. Return an error message. */\n    pTab->p.base.zErrMsg = sqlite3_mprintf(\"unknown special query: %.*s\", n, z);\n    rc = SQLITE_ERROR;\n  }\n\n  return rc;\n}\n\n/*\n** Search for an auxiliary function named zName that can be used with table\n** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary\n** structure. Otherwise, if no such function exists, return NULL.\n*/\nstatic Fts5Auxiliary *fts5FindAuxiliary(Fts5FullTable *pTab, const char *zName){\n  Fts5Auxiliary *pAux;\n\n  for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){\n    if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;\n  }\n\n  /* No function of the specified name was found. Return 0. */\n  return 0;\n}\n\n\nstatic int fts5FindRankFunction(Fts5Cursor *pCsr){\n  Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);\n  Fts5Config *pConfig = pTab->p.pConfig;\n  int rc = SQLITE_OK;\n  Fts5Auxiliary *pAux = 0;\n  const char *zRank = pCsr->zRank;\n  const char *zRankArgs = pCsr->zRankArgs;\n\n  if( zRankArgs ){\n    char *zSql = sqlite3Fts5Mprintf(&rc, \"SELECT %s\", zRankArgs);\n    if( zSql ){\n      sqlite3_stmt *pStmt = 0;\n      rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,\n                              SQLITE_PREPARE_PERSISTENT, &pStmt, 0);\n      sqlite3_free(zSql);\n      assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );\n      if( rc==SQLITE_OK ){\n        if( SQLITE_ROW==sqlite3_step(pStmt) ){\n          sqlite3_int64 nByte;\n          pCsr->nRankArg = sqlite3_column_count(pStmt);\n          nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;\n          pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);\n          if( rc==SQLITE_OK ){\n            int i;\n            for(i=0; i<pCsr->nRankArg; i++){\n              pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);\n            }\n          }\n          pCsr->pRankArgStmt = pStmt;\n        }else{\n          rc = sqlite3_finalize(pStmt);\n          assert( rc!=SQLITE_OK );\n        }\n      }\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    pAux = fts5FindAuxiliary(pTab, zRank);\n    if( pAux==0 ){\n      assert( pTab->p.base.zErrMsg==0 );\n      pTab->p.base.zErrMsg = sqlite3_mprintf(\"no such function: %s\", zRank);\n      rc = SQLITE_ERROR;\n    }\n  }\n\n  pCsr->pRank = pAux;\n  return rc;\n}\n\n\nstatic int fts5CursorParseRank(\n  Fts5Config *pConfig,\n  Fts5Cursor *pCsr, \n  sqlite3_value *pRank\n){\n  int rc = SQLITE_OK;\n  if( pRank ){\n    const char *z = (const char*)sqlite3_value_text(pRank);\n    char *zRank = 0;\n    char *zRankArgs = 0;\n\n    if( z==0 ){\n      if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;\n    }else{\n      rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);\n    }\n    if( rc==SQLITE_OK ){\n      pCsr->zRank = zRank;\n      pCsr->zRankArgs = zRankArgs;\n      CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);\n    }else if( rc==SQLITE_ERROR ){\n      pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(\n          \"parse error in rank function: %s\", z\n      );\n    }\n  }else{\n    if( pConfig->zRank ){\n      pCsr->zRank = (char*)pConfig->zRank;\n      pCsr->zRankArgs = (char*)pConfig->zRankArgs;\n    }else{\n      pCsr->zRank = (char*)FTS5_DEFAULT_RANK;\n      pCsr->zRankArgs = 0;\n    }\n  }\n  return rc;\n}\n\nstatic i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){\n  if( pVal ){\n    int eType = sqlite3_value_numeric_type(pVal);\n    if( eType==SQLITE_INTEGER ){\n      return sqlite3_value_int64(pVal);\n    }\n  }\n  return iDefault;\n}\n\n/*\n** This is the xFilter interface for the virtual table.  See\n** the virtual table xFilter method documentation for additional\n** information.\n** \n** There are three possible query strategies:\n**\n**   1. Full-text search using a MATCH operator.\n**   2. A by-rowid lookup.\n**   3. A full-table scan.\n*/\nstatic int fts5FilterMethod(\n  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */\n  int idxNum,                     /* Strategy index */\n  const char *idxStr,             /* Unused */\n  int nVal,                       /* Number of elements in apVal */\n  sqlite3_value **apVal           /* Arguments for the indexing scheme */\n){\n  Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);\n  Fts5Config *pConfig = pTab->p.pConfig;\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;\n  int rc = SQLITE_OK;             /* Error code */\n  int bDesc;                      /* True if ORDER BY [rank|rowid] DESC */\n  int bOrderByRank;               /* True if ORDER BY rank */\n  sqlite3_value *pRank = 0;       /* rank MATCH ? expression (or NULL) */\n  sqlite3_value *pRowidEq = 0;    /* rowid = ? expression (or NULL) */\n  sqlite3_value *pRowidLe = 0;    /* rowid <= ? expression (or NULL) */\n  sqlite3_value *pRowidGe = 0;    /* rowid >= ? expression (or NULL) */\n  int iCol;                       /* Column on LHS of MATCH operator */\n  char **pzErrmsg = pConfig->pzErrmsg;\n  int i;\n  int iIdxStr = 0;\n  Fts5Expr *pExpr = 0;\n\n  if( pConfig->bLock ){\n    pTab->p.base.zErrMsg = sqlite3_mprintf(\n        \"recursively defined fts5 content table\"\n    );\n    return SQLITE_ERROR;\n  }\n\n  if( pCsr->ePlan ){\n    fts5FreeCursorComponents(pCsr);\n    memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));\n  }\n\n  assert( pCsr->pStmt==0 );\n  assert( pCsr->pExpr==0 );\n  assert( pCsr->csrflags==0 );\n  assert( pCsr->pRank==0 );\n  assert( pCsr->zRank==0 );\n  assert( pCsr->zRankArgs==0 );\n  assert( pTab->pSortCsr==0 || nVal==0 );\n\n  assert( pzErrmsg==0 || pzErrmsg==&pTab->p.base.zErrMsg );\n  pConfig->pzErrmsg = &pTab->p.base.zErrMsg;\n\n  /* Decode the arguments passed through to this function. */\n  for(i=0; i<nVal; i++){\n    switch( idxStr[iIdxStr++] ){\n      case 'r':\n        pRank = apVal[i];\n        break;\n      case 'm': {\n        const char *zText = (const char*)sqlite3_value_text(apVal[i]);\n        if( zText==0 ) zText = \"\";\n\n        if( idxStr[iIdxStr]>='0' && idxStr[iIdxStr]<='9' ){\n          iCol = 0;\n          do{\n            iCol = iCol*10 + (idxStr[iIdxStr]-'0');\n            iIdxStr++;\n          }while( idxStr[iIdxStr]>='0' && idxStr[iIdxStr]<='9' );\n        }else{\n          iCol = pConfig->nCol;\n        }\n\n        if( zText[0]=='*' ){\n          /* The user has issued a query of the form \"MATCH '*...'\". This\n          ** indicates that the MATCH expression is not a full text query,\n          ** but a request for an internal parameter.  */\n          rc = fts5SpecialMatch(pTab, pCsr, &zText[1]);\n          goto filter_out;\n        }else{\n          char **pzErr = &pTab->p.base.zErrMsg;\n          rc = sqlite3Fts5ExprNew(pConfig, iCol, zText, &pExpr, pzErr);\n          if( rc==SQLITE_OK ){\n            rc = sqlite3Fts5ExprAnd(&pCsr->pExpr, pExpr);\n            pExpr = 0;\n          }\n          if( rc!=SQLITE_OK ) goto filter_out;\n        }\n\n        break;\n      }\n      case '=':\n        pRowidEq = apVal[i];\n        break;\n      case '<':\n        pRowidLe = apVal[i];\n        break;\n      default: assert( idxStr[iIdxStr-1]=='>' );\n        pRowidGe = apVal[i];\n        break;\n    }\n  }\n  bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);\n  pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);\n\n  /* Set the cursor upper and lower rowid limits. Only some strategies \n  ** actually use them. This is ok, as the xBestIndex() method leaves the\n  ** sqlite3_index_constraint.omit flag clear for range constraints\n  ** on the rowid field.  */\n  if( pRowidEq ){\n    pRowidLe = pRowidGe = pRowidEq;\n  }\n  if( bDesc ){\n    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);\n    pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);\n  }else{\n    pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);\n    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);\n  }\n\n  if( pTab->pSortCsr ){\n    /* If pSortCsr is non-NULL, then this call is being made as part of \n    ** processing for a \"... MATCH <expr> ORDER BY rank\" query (ePlan is\n    ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will\n    ** return results to the user for this query. The current cursor \n    ** (pCursor) is used to execute the query issued by function \n    ** fts5CursorFirstSorted() above.  */\n    assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );\n    assert( nVal==0 && bOrderByRank==0 && bDesc==0 );\n    assert( pCsr->iLastRowid==LARGEST_INT64 );\n    assert( pCsr->iFirstRowid==SMALLEST_INT64 );\n    if( pTab->pSortCsr->bDesc ){\n      pCsr->iLastRowid = pTab->pSortCsr->iFirstRowid;\n      pCsr->iFirstRowid = pTab->pSortCsr->iLastRowid;\n    }else{\n      pCsr->iLastRowid = pTab->pSortCsr->iLastRowid;\n      pCsr->iFirstRowid = pTab->pSortCsr->iFirstRowid;\n    }\n    pCsr->ePlan = FTS5_PLAN_SOURCE;\n    pCsr->pExpr = pTab->pSortCsr->pExpr;\n    rc = fts5CursorFirst(pTab, pCsr, bDesc);\n  }else if( pCsr->pExpr ){\n    rc = fts5CursorParseRank(pConfig, pCsr, pRank);\n    if( rc==SQLITE_OK ){\n      if( bOrderByRank ){\n        pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;\n        rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);\n      }else{\n        pCsr->ePlan = FTS5_PLAN_MATCH;\n        rc = fts5CursorFirst(pTab, pCsr, bDesc);\n      }\n    }\n  }else if( pConfig->zContent==0 ){\n    *pConfig->pzErrmsg = sqlite3_mprintf(\n        \"%s: table does not support scanning\", pConfig->zName\n    );\n    rc = SQLITE_ERROR;\n  }else{\n    /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup\n    ** by rowid (ePlan==FTS5_PLAN_ROWID).  */\n    pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);\n    rc = sqlite3Fts5StorageStmt(\n        pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->p.base.zErrMsg\n    );\n    if( rc==SQLITE_OK ){\n      if( pCsr->ePlan==FTS5_PLAN_ROWID ){\n        sqlite3_bind_value(pCsr->pStmt, 1, pRowidEq);\n      }else{\n        sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);\n        sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);\n      }\n      rc = fts5NextMethod(pCursor);\n    }\n  }\n\n filter_out:\n  sqlite3Fts5ExprFree(pExpr);\n  pConfig->pzErrmsg = pzErrmsg;\n  return rc;\n}\n\n/* \n** This is the xEof method of the virtual table. SQLite calls this \n** routine to find out if it has reached the end of a result set.\n*/\nstatic int fts5EofMethod(sqlite3_vtab_cursor *pCursor){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;\n  return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);\n}\n\n/*\n** Return the rowid that the cursor currently points to.\n*/\nstatic i64 fts5CursorRowid(Fts5Cursor *pCsr){\n  assert( pCsr->ePlan==FTS5_PLAN_MATCH \n       || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH \n       || pCsr->ePlan==FTS5_PLAN_SOURCE \n  );\n  if( pCsr->pSorter ){\n    return pCsr->pSorter->iRowid;\n  }else{\n    return sqlite3Fts5ExprRowid(pCsr->pExpr);\n  }\n}\n\n/* \n** This is the xRowid method. The SQLite core calls this routine to\n** retrieve the rowid for the current row of the result set. fts5\n** exposes %_content.rowid as the rowid for the virtual table. The\n** rowid should be written to *pRowid.\n*/\nstatic int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;\n  int ePlan = pCsr->ePlan;\n  \n  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );\n  switch( ePlan ){\n    case FTS5_PLAN_SPECIAL:\n      *pRowid = 0;\n      break;\n\n    case FTS5_PLAN_SOURCE:\n    case FTS5_PLAN_MATCH:\n    case FTS5_PLAN_SORTED_MATCH:\n      *pRowid = fts5CursorRowid(pCsr);\n      break;\n\n    default:\n      *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);\n      break;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** If the cursor requires seeking (bSeekRequired flag is set), seek it.\n** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.\n**\n** If argument bErrormsg is true and an error occurs, an error message may\n** be left in sqlite3_vtab.zErrMsg.\n*/\nstatic int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){\n  int rc = SQLITE_OK;\n\n  /* If the cursor does not yet have a statement handle, obtain one now. */ \n  if( pCsr->pStmt==0 ){\n    Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);\n    int eStmt = fts5StmtType(pCsr);\n    rc = sqlite3Fts5StorageStmt(\n        pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->p.base.zErrMsg:0)\n    );\n    assert( rc!=SQLITE_OK || pTab->p.base.zErrMsg==0 );\n    assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );\n  }\n\n  if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){\n    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);\n    assert( pCsr->pExpr );\n    sqlite3_reset(pCsr->pStmt);\n    sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));\n    pTab->pConfig->bLock++;\n    rc = sqlite3_step(pCsr->pStmt);\n    pTab->pConfig->bLock--;\n    if( rc==SQLITE_ROW ){\n      rc = SQLITE_OK;\n      CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);\n    }else{\n      rc = sqlite3_reset(pCsr->pStmt);\n      if( rc==SQLITE_OK ){\n        rc = FTS5_CORRUPT;\n      }else if( pTab->pConfig->pzErrmsg ){\n        *pTab->pConfig->pzErrmsg = sqlite3_mprintf(\n            \"%s\", sqlite3_errmsg(pTab->pConfig->db)\n        );\n      }\n    }\n  }\n  return rc;\n}\n\nstatic void fts5SetVtabError(Fts5FullTable *p, const char *zFormat, ...){\n  va_list ap;                     /* ... printf arguments */\n  va_start(ap, zFormat);\n  assert( p->p.base.zErrMsg==0 );\n  p->p.base.zErrMsg = sqlite3_vmprintf(zFormat, ap);\n  va_end(ap);\n}\n\n/*\n** This function is called to handle an FTS INSERT command. In other words,\n** an INSERT statement of the form:\n**\n**     INSERT INTO fts(fts) VALUES($pCmd)\n**     INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)\n**\n** Argument pVal is the value assigned to column \"fts\" by the INSERT \n** statement. This function returns SQLITE_OK if successful, or an SQLite\n** error code if an error occurs.\n**\n** The commands implemented by this function are documented in the \"Special\n** INSERT Directives\" section of the documentation. It should be updated if\n** more commands are added to this function.\n*/\nstatic int fts5SpecialInsert(\n  Fts5FullTable *pTab,            /* Fts5 table object */\n  const char *zCmd,               /* Text inserted into table-name column */\n  sqlite3_value *pVal             /* Value inserted into rank column */\n){\n  Fts5Config *pConfig = pTab->p.pConfig;\n  int rc = SQLITE_OK;\n  int bError = 0;\n\n  if( 0==sqlite3_stricmp(\"delete-all\", zCmd) ){\n    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){\n      fts5SetVtabError(pTab, \n          \"'delete-all' may only be used with a \"\n          \"contentless or external content fts5 table\"\n      );\n      rc = SQLITE_ERROR;\n    }else{\n      rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);\n    }\n  }else if( 0==sqlite3_stricmp(\"rebuild\", zCmd) ){\n    if( pConfig->eContent==FTS5_CONTENT_NONE ){\n      fts5SetVtabError(pTab, \n          \"'rebuild' may not be used with a contentless fts5 table\"\n      );\n      rc = SQLITE_ERROR;\n    }else{\n      rc = sqlite3Fts5StorageRebuild(pTab->pStorage);\n    }\n  }else if( 0==sqlite3_stricmp(\"optimize\", zCmd) ){\n    rc = sqlite3Fts5StorageOptimize(pTab->pStorage);\n  }else if( 0==sqlite3_stricmp(\"merge\", zCmd) ){\n    int nMerge = sqlite3_value_int(pVal);\n    rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);\n  }else if( 0==sqlite3_stricmp(\"integrity-check\", zCmd) ){\n    rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);\n#ifdef SQLITE_DEBUG\n  }else if( 0==sqlite3_stricmp(\"prefix-index\", zCmd) ){\n    pConfig->bPrefixIndex = sqlite3_value_int(pVal);\n#endif\n  }else{\n    rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);\n    if( rc==SQLITE_OK ){\n      rc = sqlite3Fts5ConfigSetValue(pTab->p.pConfig, zCmd, pVal, &bError);\n    }\n    if( rc==SQLITE_OK ){\n      if( bError ){\n        rc = SQLITE_ERROR;\n      }else{\n        rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);\n      }\n    }\n  }\n  return rc;\n}\n\nstatic int fts5SpecialDelete(\n  Fts5FullTable *pTab, \n  sqlite3_value **apVal\n){\n  int rc = SQLITE_OK;\n  int eType1 = sqlite3_value_type(apVal[1]);\n  if( eType1==SQLITE_INTEGER ){\n    sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);\n    rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);\n  }\n  return rc;\n}\n\nstatic void fts5StorageInsert(\n  int *pRc, \n  Fts5FullTable *pTab, \n  sqlite3_value **apVal, \n  i64 *piRowid\n){\n  int rc = *pRc;\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);\n  }\n  *pRc = rc;\n}\n\n/* \n** This function is the implementation of the xUpdate callback used by \n** FTS3 virtual tables. It is invoked by SQLite each time a row is to be\n** inserted, updated or deleted.\n**\n** A delete specifies a single argument - the rowid of the row to remove.\n** \n** Update and insert operations pass:\n**\n**   1. The \"old\" rowid, or NULL.\n**   2. The \"new\" rowid.\n**   3. Values for each of the nCol matchable columns.\n**   4. Values for the two hidden columns (<tablename> and \"rank\").\n*/\nstatic int fts5UpdateMethod(\n  sqlite3_vtab *pVtab,            /* Virtual table handle */\n  int nArg,                       /* Size of argument array */\n  sqlite3_value **apVal,          /* Array of arguments */\n  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */\n){\n  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;\n  Fts5Config *pConfig = pTab->p.pConfig;\n  int eType0;                     /* value_type() of apVal[0] */\n  int rc = SQLITE_OK;             /* Return code */\n\n  /* A transaction must be open when this is called. */\n  assert( pTab->ts.eState==1 );\n\n  assert( pVtab->zErrMsg==0 );\n  assert( nArg==1 || nArg==(2+pConfig->nCol+2) );\n  assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER \n       || sqlite3_value_type(apVal[0])==SQLITE_NULL \n  );\n  assert( pTab->p.pConfig->pzErrmsg==0 );\n  pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;\n\n  /* Put any active cursors into REQUIRE_SEEK state. */\n  fts5TripCursors(pTab);\n\n  eType0 = sqlite3_value_type(apVal[0]);\n  if( eType0==SQLITE_NULL \n   && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL \n  ){\n    /* A \"special\" INSERT op. These are handled separately. */\n    const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);\n    if( pConfig->eContent!=FTS5_CONTENT_NORMAL \n      && 0==sqlite3_stricmp(\"delete\", z) \n    ){\n      rc = fts5SpecialDelete(pTab, apVal);\n    }else{\n      rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);\n    }\n  }else{\n    /* A regular INSERT, UPDATE or DELETE statement. The trick here is that\n    ** any conflict on the rowid value must be detected before any \n    ** modifications are made to the database file. There are 4 cases:\n    **\n    **   1) DELETE\n    **   2) UPDATE (rowid not modified)\n    **   3) UPDATE (rowid modified)\n    **   4) INSERT\n    **\n    ** Cases 3 and 4 may violate the rowid constraint.\n    */\n    int eConflict = SQLITE_ABORT;\n    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){\n      eConflict = sqlite3_vtab_on_conflict(pConfig->db);\n    }\n\n    assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );\n    assert( nArg!=1 || eType0==SQLITE_INTEGER );\n\n    /* Filter out attempts to run UPDATE or DELETE on contentless tables.\n    ** This is not suported.  */\n    if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){\n      pTab->p.base.zErrMsg = sqlite3_mprintf(\n          \"cannot %s contentless fts5 table: %s\", \n          (nArg>1 ? \"UPDATE\" : \"DELETE from\"), pConfig->zName\n      );\n      rc = SQLITE_ERROR;\n    }\n\n    /* DELETE */\n    else if( nArg==1 ){\n      i64 iDel = sqlite3_value_int64(apVal[0]);  /* Rowid to delete */\n      rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);\n    }\n\n    /* INSERT or UPDATE */\n    else{\n      int eType1 = sqlite3_value_numeric_type(apVal[1]);\n\n      if( eType1!=SQLITE_INTEGER && eType1!=SQLITE_NULL ){\n        rc = SQLITE_MISMATCH;\n      }\n\n      else if( eType0!=SQLITE_INTEGER ){     \n        /* If this is a REPLACE, first remove the current entry (if any) */\n        if( eConflict==SQLITE_REPLACE && eType1==SQLITE_INTEGER ){\n          i64 iNew = sqlite3_value_int64(apVal[1]);  /* Rowid to delete */\n          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);\n        }\n        fts5StorageInsert(&rc, pTab, apVal, pRowid);\n      }\n\n      /* UPDATE */\n      else{\n        i64 iOld = sqlite3_value_int64(apVal[0]);  /* Old rowid */\n        i64 iNew = sqlite3_value_int64(apVal[1]);  /* New rowid */\n        if( eType1==SQLITE_INTEGER && iOld!=iNew ){\n          if( eConflict==SQLITE_REPLACE ){\n            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);\n            if( rc==SQLITE_OK ){\n              rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);\n            }\n            fts5StorageInsert(&rc, pTab, apVal, pRowid);\n          }else{\n            rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);\n            if( rc==SQLITE_OK ){\n              rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);\n            }\n            if( rc==SQLITE_OK ){\n              rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal,*pRowid);\n            }\n          }\n        }else{\n          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);\n          fts5StorageInsert(&rc, pTab, apVal, pRowid);\n        }\n      }\n    }\n  }\n\n  pTab->p.pConfig->pzErrmsg = 0;\n  return rc;\n}\n\n/*\n** Implementation of xSync() method. \n*/\nstatic int fts5SyncMethod(sqlite3_vtab *pVtab){\n  int rc;\n  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;\n  fts5CheckTransactionState(pTab, FTS5_SYNC, 0);\n  pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;\n  fts5TripCursors(pTab);\n  rc = sqlite3Fts5StorageSync(pTab->pStorage);\n  pTab->p.pConfig->pzErrmsg = 0;\n  return rc;\n}\n\n/*\n** Implementation of xBegin() method. \n*/\nstatic int fts5BeginMethod(sqlite3_vtab *pVtab){\n  fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_BEGIN, 0);\n  fts5NewTransaction((Fts5FullTable*)pVtab);\n  return SQLITE_OK;\n}\n\n/*\n** Implementation of xCommit() method. This is a no-op. The contents of\n** the pending-terms hash-table have already been flushed into the database\n** by fts5SyncMethod().\n*/\nstatic int fts5CommitMethod(sqlite3_vtab *pVtab){\n  UNUSED_PARAM(pVtab);  /* Call below is a no-op for NDEBUG builds */\n  fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_COMMIT, 0);\n  return SQLITE_OK;\n}\n\n/*\n** Implementation of xRollback(). Discard the contents of the pending-terms\n** hash-table. Any changes made to the database are reverted by SQLite.\n*/\nstatic int fts5RollbackMethod(sqlite3_vtab *pVtab){\n  int rc;\n  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;\n  fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);\n  rc = sqlite3Fts5StorageRollback(pTab->pStorage);\n  return rc;\n}\n\nstatic int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);\n\nstatic void *fts5ApiUserData(Fts5Context *pCtx){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  return pCsr->pAux->pUserData;\n}\n\nstatic int fts5ApiColumnCount(Fts5Context *pCtx){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;\n}\n\nstatic int fts5ApiColumnTotalSize(\n  Fts5Context *pCtx, \n  int iCol, \n  sqlite3_int64 *pnToken\n){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);\n  return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);\n}\n\nstatic int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);\n  return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);\n}\n\nstatic int fts5ApiTokenize(\n  Fts5Context *pCtx, \n  const char *pText, int nText, \n  void *pUserData,\n  int (*xToken)(void*, int, const char*, int, int, int)\n){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);\n  return sqlite3Fts5Tokenize(\n      pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken\n  );\n}\n\nstatic int fts5ApiPhraseCount(Fts5Context *pCtx){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);\n}\n\nstatic int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);\n}\n\nstatic int fts5ApiColumnText(\n  Fts5Context *pCtx, \n  int iCol, \n  const char **pz, \n  int *pn\n){\n  int rc = SQLITE_OK;\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  if( fts5IsContentless((Fts5FullTable*)(pCsr->base.pVtab)) \n   || pCsr->ePlan==FTS5_PLAN_SPECIAL \n  ){\n    *pz = 0;\n    *pn = 0;\n  }else{\n    rc = fts5SeekCursor(pCsr, 0);\n    if( rc==SQLITE_OK ){\n      *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);\n      *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);\n    }\n  }\n  return rc;\n}\n\nstatic int fts5CsrPoslist(\n  Fts5Cursor *pCsr, \n  int iPhrase, \n  const u8 **pa,\n  int *pn\n){\n  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;\n  int rc = SQLITE_OK;\n  int bLive = (pCsr->pSorter==0);\n\n  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){\n\n    if( pConfig->eDetail!=FTS5_DETAIL_FULL ){\n      Fts5PoslistPopulator *aPopulator;\n      int i;\n      aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);\n      if( aPopulator==0 ) rc = SQLITE_NOMEM;\n      for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){\n        int n; const char *z;\n        rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);\n        if( rc==SQLITE_OK ){\n          rc = sqlite3Fts5ExprPopulatePoslists(\n              pConfig, pCsr->pExpr, aPopulator, i, z, n\n          );\n        }\n      }\n      sqlite3_free(aPopulator);\n\n      if( pCsr->pSorter ){\n        sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);\n      }\n    }\n    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);\n  }\n\n  if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){\n    Fts5Sorter *pSorter = pCsr->pSorter;\n    int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);\n    *pn = pSorter->aIdx[iPhrase] - i1;\n    *pa = &pSorter->aPoslist[i1];\n  }else{\n    *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);\n  }\n\n  return rc;\n}\n\n/*\n** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated\n** correctly for the current view. Return SQLITE_OK if successful, or an\n** SQLite error code otherwise.\n*/\nstatic int fts5CacheInstArray(Fts5Cursor *pCsr){\n  int rc = SQLITE_OK;\n  Fts5PoslistReader *aIter;       /* One iterator for each phrase */\n  int nIter;                      /* Number of iterators/phrases */\n  int nCol = ((Fts5Table*)pCsr->base.pVtab)->pConfig->nCol;\n  \n  nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);\n  if( pCsr->aInstIter==0 ){\n    sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nIter;\n    pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);\n  }\n  aIter = pCsr->aInstIter;\n\n  if( aIter ){\n    int nInst = 0;                /* Number instances seen so far */\n    int i;\n\n    /* Initialize all iterators */\n    for(i=0; i<nIter && rc==SQLITE_OK; i++){\n      const u8 *a;\n      int n; \n      rc = fts5CsrPoslist(pCsr, i, &a, &n);\n      if( rc==SQLITE_OK ){\n        sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);\n      }\n    }\n\n    if( rc==SQLITE_OK ){\n      while( 1 ){\n        int *aInst;\n        int iBest = -1;\n        for(i=0; i<nIter; i++){\n          if( (aIter[i].bEof==0) \n              && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos) \n            ){\n            iBest = i;\n          }\n        }\n        if( iBest<0 ) break;\n\n        nInst++;\n        if( nInst>=pCsr->nInstAlloc ){\n          pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;\n          aInst = (int*)sqlite3_realloc64(\n              pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3\n              );\n          if( aInst ){\n            pCsr->aInst = aInst;\n          }else{\n            rc = SQLITE_NOMEM;\n            break;\n          }\n        }\n\n        aInst = &pCsr->aInst[3 * (nInst-1)];\n        aInst[0] = iBest;\n        aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);\n        aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);\n        if( aInst[1]<0 || aInst[1]>=nCol ){\n          rc = FTS5_CORRUPT;\n          break;\n        }\n        sqlite3Fts5PoslistReaderNext(&aIter[iBest]);\n      }\n    }\n\n    pCsr->nInstCount = nInst;\n    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);\n  }\n  return rc;\n}\n\nstatic int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  int rc = SQLITE_OK;\n  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0 \n   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){\n    *pnInst = pCsr->nInstCount;\n  }\n  return rc;\n}\n\nstatic int fts5ApiInst(\n  Fts5Context *pCtx, \n  int iIdx, \n  int *piPhrase, \n  int *piCol, \n  int *piOff\n){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  int rc = SQLITE_OK;\n  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0 \n   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) \n  ){\n    if( iIdx<0 || iIdx>=pCsr->nInstCount ){\n      rc = SQLITE_RANGE;\n#if 0\n    }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){\n      *piPhrase = pCsr->aInst[iIdx*3];\n      *piCol = pCsr->aInst[iIdx*3 + 2];\n      *piOff = -1;\n#endif\n    }else{\n      *piPhrase = pCsr->aInst[iIdx*3];\n      *piCol = pCsr->aInst[iIdx*3 + 1];\n      *piOff = pCsr->aInst[iIdx*3 + 2];\n    }\n  }\n  return rc;\n}\n\nstatic sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){\n  return fts5CursorRowid((Fts5Cursor*)pCtx);\n}\n\nstatic int fts5ColumnSizeCb(\n  void *pContext,                 /* Pointer to int */\n  int tflags,\n  const char *pUnused,            /* Buffer containing token */\n  int nUnused,                    /* Size of token in bytes */\n  int iUnused1,                   /* Start offset of token */\n  int iUnused2                    /* End offset of token */\n){\n  int *pCnt = (int*)pContext;\n  UNUSED_PARAM2(pUnused, nUnused);\n  UNUSED_PARAM2(iUnused1, iUnused2);\n  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){\n    (*pCnt)++;\n  }\n  return SQLITE_OK;\n}\n\nstatic int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);\n  Fts5Config *pConfig = pTab->p.pConfig;\n  int rc = SQLITE_OK;\n\n  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){\n    if( pConfig->bColumnsize ){\n      i64 iRowid = fts5CursorRowid(pCsr);\n      rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);\n    }else if( pConfig->zContent==0 ){\n      int i;\n      for(i=0; i<pConfig->nCol; i++){\n        if( pConfig->abUnindexed[i]==0 ){\n          pCsr->aColumnSize[i] = -1;\n        }\n      }\n    }else{\n      int i;\n      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){\n        if( pConfig->abUnindexed[i]==0 ){\n          const char *z; int n;\n          void *p = (void*)(&pCsr->aColumnSize[i]);\n          pCsr->aColumnSize[i] = 0;\n          rc = fts5ApiColumnText(pCtx, i, &z, &n);\n          if( rc==SQLITE_OK ){\n            rc = sqlite3Fts5Tokenize(\n                pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb\n            );\n          }\n        }\n      }\n    }\n    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);\n  }\n  if( iCol<0 ){\n    int i;\n    *pnToken = 0;\n    for(i=0; i<pConfig->nCol; i++){\n      *pnToken += pCsr->aColumnSize[i];\n    }\n  }else if( iCol<pConfig->nCol ){\n    *pnToken = pCsr->aColumnSize[iCol];\n  }else{\n    *pnToken = 0;\n    rc = SQLITE_RANGE;\n  }\n  return rc;\n}\n\n/*\n** Implementation of the xSetAuxdata() method.\n*/\nstatic int fts5ApiSetAuxdata(\n  Fts5Context *pCtx,              /* Fts5 context */\n  void *pPtr,                     /* Pointer to save as auxdata */\n  void(*xDelete)(void*)           /* Destructor for pPtr (or NULL) */\n){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  Fts5Auxdata *pData;\n\n  /* Search through the cursors list of Fts5Auxdata objects for one that\n  ** corresponds to the currently executing auxiliary function.  */\n  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){\n    if( pData->pAux==pCsr->pAux ) break;\n  }\n\n  if( pData ){\n    if( pData->xDelete ){\n      pData->xDelete(pData->pPtr);\n    }\n  }else{\n    int rc = SQLITE_OK;\n    pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));\n    if( pData==0 ){\n      if( xDelete ) xDelete(pPtr);\n      return rc;\n    }\n    pData->pAux = pCsr->pAux;\n    pData->pNext = pCsr->pAuxdata;\n    pCsr->pAuxdata = pData;\n  }\n\n  pData->xDelete = xDelete;\n  pData->pPtr = pPtr;\n  return SQLITE_OK;\n}\n\nstatic void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  Fts5Auxdata *pData;\n  void *pRet = 0;\n\n  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){\n    if( pData->pAux==pCsr->pAux ) break;\n  }\n\n  if( pData ){\n    pRet = pData->pPtr;\n    if( bClear ){\n      pData->pPtr = 0;\n      pData->xDelete = 0;\n    }\n  }\n\n  return pRet;\n}\n\nstatic void fts5ApiPhraseNext(\n  Fts5Context *pUnused, \n  Fts5PhraseIter *pIter, \n  int *piCol, int *piOff\n){\n  UNUSED_PARAM(pUnused);\n  if( pIter->a>=pIter->b ){\n    *piCol = -1;\n    *piOff = -1;\n  }else{\n    int iVal;\n    pIter->a += fts5GetVarint32(pIter->a, iVal);\n    if( iVal==1 ){\n      pIter->a += fts5GetVarint32(pIter->a, iVal);\n      *piCol = iVal;\n      *piOff = 0;\n      pIter->a += fts5GetVarint32(pIter->a, iVal);\n    }\n    *piOff += (iVal-2);\n  }\n}\n\nstatic int fts5ApiPhraseFirst(\n  Fts5Context *pCtx, \n  int iPhrase, \n  Fts5PhraseIter *pIter, \n  int *piCol, int *piOff\n){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  int n;\n  int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);\n  if( rc==SQLITE_OK ){\n    pIter->b = &pIter->a[n];\n    *piCol = 0;\n    *piOff = 0;\n    fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);\n  }\n  return rc;\n}\n\nstatic void fts5ApiPhraseNextColumn(\n  Fts5Context *pCtx, \n  Fts5PhraseIter *pIter, \n  int *piCol\n){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;\n\n  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){\n    if( pIter->a>=pIter->b ){\n      *piCol = -1;\n    }else{\n      int iIncr;\n      pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);\n      *piCol += (iIncr-2);\n    }\n  }else{\n    while( 1 ){\n      int dummy;\n      if( pIter->a>=pIter->b ){\n        *piCol = -1;\n        return;\n      }\n      if( pIter->a[0]==0x01 ) break;\n      pIter->a += fts5GetVarint32(pIter->a, dummy);\n    }\n    pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);\n  }\n}\n\nstatic int fts5ApiPhraseFirstColumn(\n  Fts5Context *pCtx, \n  int iPhrase, \n  Fts5PhraseIter *pIter, \n  int *piCol\n){\n  int rc = SQLITE_OK;\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;\n\n  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){\n    Fts5Sorter *pSorter = pCsr->pSorter;\n    int n;\n    if( pSorter ){\n      int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);\n      n = pSorter->aIdx[iPhrase] - i1;\n      pIter->a = &pSorter->aPoslist[i1];\n    }else{\n      rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);\n    }\n    if( rc==SQLITE_OK ){\n      pIter->b = &pIter->a[n];\n      *piCol = 0;\n      fts5ApiPhraseNextColumn(pCtx, pIter, piCol);\n    }\n  }else{\n    int n;\n    rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);\n    if( rc==SQLITE_OK ){\n      pIter->b = &pIter->a[n];\n      if( n<=0 ){\n        *piCol = -1;\n      }else if( pIter->a[0]==0x01 ){\n        pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);\n      }else{\n        *piCol = 0;\n      }\n    }\n  }\n\n  return rc;\n}\n\n\nstatic int fts5ApiQueryPhrase(Fts5Context*, int, void*, \n    int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)\n);\n\nstatic const Fts5ExtensionApi sFts5Api = {\n  2,                            /* iVersion */\n  fts5ApiUserData,\n  fts5ApiColumnCount,\n  fts5ApiRowCount,\n  fts5ApiColumnTotalSize,\n  fts5ApiTokenize,\n  fts5ApiPhraseCount,\n  fts5ApiPhraseSize,\n  fts5ApiInstCount,\n  fts5ApiInst,\n  fts5ApiRowid,\n  fts5ApiColumnText,\n  fts5ApiColumnSize,\n  fts5ApiQueryPhrase,\n  fts5ApiSetAuxdata,\n  fts5ApiGetAuxdata,\n  fts5ApiPhraseFirst,\n  fts5ApiPhraseNext,\n  fts5ApiPhraseFirstColumn,\n  fts5ApiPhraseNextColumn,\n};\n\n/*\n** Implementation of API function xQueryPhrase().\n*/\nstatic int fts5ApiQueryPhrase(\n  Fts5Context *pCtx, \n  int iPhrase, \n  void *pUserData,\n  int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)\n){\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;\n  Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);\n  int rc;\n  Fts5Cursor *pNew = 0;\n\n  rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);\n  if( rc==SQLITE_OK ){\n    pNew->ePlan = FTS5_PLAN_MATCH;\n    pNew->iFirstRowid = SMALLEST_INT64;\n    pNew->iLastRowid = LARGEST_INT64;\n    pNew->base.pVtab = (sqlite3_vtab*)pTab;\n    rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);\n  }\n\n  if( rc==SQLITE_OK ){\n    for(rc = fts5CursorFirst(pTab, pNew, 0);\n        rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;\n        rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)\n    ){\n      rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);\n      if( rc!=SQLITE_OK ){\n        if( rc==SQLITE_DONE ) rc = SQLITE_OK;\n        break;\n      }\n    }\n  }\n\n  fts5CloseMethod((sqlite3_vtab_cursor*)pNew);\n  return rc;\n}\n\nstatic void fts5ApiInvoke(\n  Fts5Auxiliary *pAux,\n  Fts5Cursor *pCsr,\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  assert( pCsr->pAux==0 );\n  pCsr->pAux = pAux;\n  pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);\n  pCsr->pAux = 0;\n}\n\nstatic Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){\n  Fts5Cursor *pCsr;\n  for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){\n    if( pCsr->iCsrId==iCsrId ) break;\n  }\n  return pCsr;\n}\n\nstatic void fts5ApiCallback(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n\n  Fts5Auxiliary *pAux;\n  Fts5Cursor *pCsr;\n  i64 iCsrId;\n\n  assert( argc>=1 );\n  pAux = (Fts5Auxiliary*)sqlite3_user_data(context);\n  iCsrId = sqlite3_value_int64(argv[0]);\n\n  pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);\n  if( pCsr==0 || pCsr->ePlan==0 ){\n    char *zErr = sqlite3_mprintf(\"no such cursor: %lld\", iCsrId);\n    sqlite3_result_error(context, zErr, -1);\n    sqlite3_free(zErr);\n  }else{\n    fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);\n  }\n}\n\n\n/*\n** Given cursor id iId, return a pointer to the corresponding Fts5Table \n** object. Or NULL If the cursor id does not exist.\n*/\nstatic Fts5Table *sqlite3Fts5TableFromCsrid(\n  Fts5Global *pGlobal,            /* FTS5 global context for db handle */\n  i64 iCsrId                      /* Id of cursor to find */\n){\n  Fts5Cursor *pCsr;\n  pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);\n  if( pCsr ){\n    return (Fts5Table*)pCsr->base.pVtab;\n  }\n  return 0;\n}\n\n/*\n** Return a \"position-list blob\" corresponding to the current position of\n** cursor pCsr via sqlite3_result_blob(). A position-list blob contains\n** the current position-list for each phrase in the query associated with\n** cursor pCsr.\n**\n** A position-list blob begins with (nPhrase-1) varints, where nPhrase is\n** the number of phrases in the query. Following the varints are the\n** concatenated position lists for each phrase, in order.\n**\n** The first varint (if it exists) contains the size of the position list\n** for phrase 0. The second (same disclaimer) contains the size of position\n** list 1. And so on. There is no size field for the final position list,\n** as it can be derived from the total size of the blob.\n*/\nstatic int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){\n  int i;\n  int rc = SQLITE_OK;\n  int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);\n  Fts5Buffer val;\n\n  memset(&val, 0, sizeof(Fts5Buffer));\n  switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){\n    case FTS5_DETAIL_FULL:\n\n      /* Append the varints */\n      for(i=0; i<(nPhrase-1); i++){\n        const u8 *dummy;\n        int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);\n        sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);\n      }\n\n      /* Append the position lists */\n      for(i=0; i<nPhrase; i++){\n        const u8 *pPoslist;\n        int nPoslist;\n        nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);\n        sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);\n      }\n      break;\n\n    case FTS5_DETAIL_COLUMNS:\n\n      /* Append the varints */\n      for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){\n        const u8 *dummy;\n        int nByte;\n        rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);\n        sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);\n      }\n\n      /* Append the position lists */\n      for(i=0; rc==SQLITE_OK && i<nPhrase; i++){\n        const u8 *pPoslist;\n        int nPoslist;\n        rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);\n        sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);\n      }\n      break;\n\n    default:\n      break;\n  }\n\n  sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);\n  return rc;\n}\n\n/* \n** This is the xColumn method, called by SQLite to request a value from\n** the row that the supplied cursor currently points to.\n*/\nstatic int fts5ColumnMethod(\n  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */\n  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */\n  int iCol                        /* Index of column to read value from */\n){\n  Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);\n  Fts5Config *pConfig = pTab->p.pConfig;\n  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;\n  int rc = SQLITE_OK;\n  \n  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );\n\n  if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){\n    if( iCol==pConfig->nCol ){\n      sqlite3_result_int64(pCtx, pCsr->iSpecial);\n    }\n  }else\n\n  if( iCol==pConfig->nCol ){\n    /* User is requesting the value of the special column with the same name\n    ** as the table. Return the cursor integer id number. This value is only\n    ** useful in that it may be passed as the first argument to an FTS5\n    ** auxiliary function.  */\n    sqlite3_result_int64(pCtx, pCsr->iCsrId);\n  }else if( iCol==pConfig->nCol+1 ){\n\n    /* The value of the \"rank\" column. */\n    if( pCsr->ePlan==FTS5_PLAN_SOURCE ){\n      fts5PoslistBlob(pCtx, pCsr);\n    }else if( \n        pCsr->ePlan==FTS5_PLAN_MATCH\n     || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH\n    ){\n      if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){\n        fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);\n      }\n    }\n  }else if( !fts5IsContentless(pTab) ){\n    pConfig->pzErrmsg = &pTab->p.base.zErrMsg;\n    rc = fts5SeekCursor(pCsr, 1);\n    if( rc==SQLITE_OK ){\n      sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));\n    }\n    pConfig->pzErrmsg = 0;\n  }\n  return rc;\n}\n\n\n/*\n** This routine implements the xFindFunction method for the FTS3\n** virtual table.\n*/\nstatic int fts5FindFunctionMethod(\n  sqlite3_vtab *pVtab,            /* Virtual table handle */\n  int nUnused,                    /* Number of SQL function arguments */\n  const char *zName,              /* Name of SQL function */\n  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */\n  void **ppArg                    /* OUT: User data for *pxFunc */\n){\n  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;\n  Fts5Auxiliary *pAux;\n\n  UNUSED_PARAM(nUnused);\n  pAux = fts5FindAuxiliary(pTab, zName);\n  if( pAux ){\n    *pxFunc = fts5ApiCallback;\n    *ppArg = (void*)pAux;\n    return 1;\n  }\n\n  /* No function of the specified name was found. Return 0. */\n  return 0;\n}\n\n/*\n** Implementation of FTS5 xRename method. Rename an fts5 table.\n*/\nstatic int fts5RenameMethod(\n  sqlite3_vtab *pVtab,            /* Virtual table handle */\n  const char *zName               /* New name of table */\n){\n  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;\n  return sqlite3Fts5StorageRename(pTab->pStorage, zName);\n}\n\nstatic int sqlite3Fts5FlushToDisk(Fts5Table *pTab){\n  fts5TripCursors((Fts5FullTable*)pTab);\n  return sqlite3Fts5StorageSync(((Fts5FullTable*)pTab)->pStorage);\n}\n\n/*\n** The xSavepoint() method.\n**\n** Flush the contents of the pending-terms table to disk.\n*/\nstatic int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){\n  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */\n  fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_SAVEPOINT, iSavepoint);\n  return sqlite3Fts5FlushToDisk((Fts5Table*)pVtab);\n}\n\n/*\n** The xRelease() method.\n**\n** This is a no-op.\n*/\nstatic int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){\n  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */\n  fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_RELEASE, iSavepoint);\n  return sqlite3Fts5FlushToDisk((Fts5Table*)pVtab);\n}\n\n/*\n** The xRollbackTo() method.\n**\n** Discard the contents of the pending terms table.\n*/\nstatic int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){\n  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;\n  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */\n  fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);\n  fts5TripCursors(pTab);\n  return sqlite3Fts5StorageRollback(pTab->pStorage);\n}\n\n/*\n** Register a new auxiliary function with global context pGlobal.\n*/\nstatic int fts5CreateAux(\n  fts5_api *pApi,                 /* Global context (one per db handle) */\n  const char *zName,              /* Name of new function */\n  void *pUserData,                /* User data for aux. function */\n  fts5_extension_function xFunc,  /* Aux. function implementation */\n  void(*xDestroy)(void*)          /* Destructor for pUserData */\n){\n  Fts5Global *pGlobal = (Fts5Global*)pApi;\n  int rc = sqlite3_overload_function(pGlobal->db, zName, -1);\n  if( rc==SQLITE_OK ){\n    Fts5Auxiliary *pAux;\n    sqlite3_int64 nName;            /* Size of zName in bytes, including \\0 */\n    sqlite3_int64 nByte;            /* Bytes of space to allocate */\n\n    nName = strlen(zName) + 1;\n    nByte = sizeof(Fts5Auxiliary) + nName;\n    pAux = (Fts5Auxiliary*)sqlite3_malloc64(nByte);\n    if( pAux ){\n      memset(pAux, 0, (size_t)nByte);\n      pAux->zFunc = (char*)&pAux[1];\n      memcpy(pAux->zFunc, zName, nName);\n      pAux->pGlobal = pGlobal;\n      pAux->pUserData = pUserData;\n      pAux->xFunc = xFunc;\n      pAux->xDestroy = xDestroy;\n      pAux->pNext = pGlobal->pAux;\n      pGlobal->pAux = pAux;\n    }else{\n      rc = SQLITE_NOMEM;\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Register a new tokenizer. This is the implementation of the \n** fts5_api.xCreateTokenizer() method.\n*/\nstatic int fts5CreateTokenizer(\n  fts5_api *pApi,                 /* Global context (one per db handle) */\n  const char *zName,              /* Name of new function */\n  void *pUserData,                /* User data for aux. function */\n  fts5_tokenizer *pTokenizer,     /* Tokenizer implementation */\n  void(*xDestroy)(void*)          /* Destructor for pUserData */\n){\n  Fts5Global *pGlobal = (Fts5Global*)pApi;\n  Fts5TokenizerModule *pNew;\n  sqlite3_int64 nName;            /* Size of zName and its \\0 terminator */\n  sqlite3_int64 nByte;            /* Bytes of space to allocate */\n  int rc = SQLITE_OK;\n\n  nName = strlen(zName) + 1;\n  nByte = sizeof(Fts5TokenizerModule) + nName;\n  pNew = (Fts5TokenizerModule*)sqlite3_malloc64(nByte);\n  if( pNew ){\n    memset(pNew, 0, (size_t)nByte);\n    pNew->zName = (char*)&pNew[1];\n    memcpy(pNew->zName, zName, nName);\n    pNew->pUserData = pUserData;\n    pNew->x = *pTokenizer;\n    pNew->xDestroy = xDestroy;\n    pNew->pNext = pGlobal->pTok;\n    pGlobal->pTok = pNew;\n    if( pNew->pNext==0 ){\n      pGlobal->pDfltTok = pNew;\n    }\n  }else{\n    rc = SQLITE_NOMEM;\n  }\n\n  return rc;\n}\n\nstatic Fts5TokenizerModule *fts5LocateTokenizer(\n  Fts5Global *pGlobal, \n  const char *zName\n){\n  Fts5TokenizerModule *pMod = 0;\n\n  if( zName==0 ){\n    pMod = pGlobal->pDfltTok;\n  }else{\n    for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){\n      if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;\n    }\n  }\n\n  return pMod;\n}\n\n/*\n** Find a tokenizer. This is the implementation of the \n** fts5_api.xFindTokenizer() method.\n*/\nstatic int fts5FindTokenizer(\n  fts5_api *pApi,                 /* Global context (one per db handle) */\n  const char *zName,              /* Name of new function */\n  void **ppUserData,\n  fts5_tokenizer *pTokenizer      /* Populate this object */\n){\n  int rc = SQLITE_OK;\n  Fts5TokenizerModule *pMod;\n\n  pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);\n  if( pMod ){\n    *pTokenizer = pMod->x;\n    *ppUserData = pMod->pUserData;\n  }else{\n    memset(pTokenizer, 0, sizeof(fts5_tokenizer));\n    rc = SQLITE_ERROR;\n  }\n\n  return rc;\n}\n\nstatic int sqlite3Fts5GetTokenizer(\n  Fts5Global *pGlobal, \n  const char **azArg,\n  int nArg,\n  Fts5Tokenizer **ppTok,\n  fts5_tokenizer **ppTokApi,\n  char **pzErr\n){\n  Fts5TokenizerModule *pMod;\n  int rc = SQLITE_OK;\n\n  pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);\n  if( pMod==0 ){\n    assert( nArg>0 );\n    rc = SQLITE_ERROR;\n    *pzErr = sqlite3_mprintf(\"no such tokenizer: %s\", azArg[0]);\n  }else{\n    rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);\n    *ppTokApi = &pMod->x;\n    if( rc!=SQLITE_OK && pzErr ){\n      *pzErr = sqlite3_mprintf(\"error in tokenizer constructor\");\n    }\n  }\n\n  if( rc!=SQLITE_OK ){\n    *ppTokApi = 0;\n    *ppTok = 0;\n  }\n\n  return rc;\n}\n\nstatic void fts5ModuleDestroy(void *pCtx){\n  Fts5TokenizerModule *pTok, *pNextTok;\n  Fts5Auxiliary *pAux, *pNextAux;\n  Fts5Global *pGlobal = (Fts5Global*)pCtx;\n\n  for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){\n    pNextAux = pAux->pNext;\n    if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);\n    sqlite3_free(pAux);\n  }\n\n  for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){\n    pNextTok = pTok->pNext;\n    if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);\n    sqlite3_free(pTok);\n  }\n\n  sqlite3_free(pGlobal);\n}\n\nstatic void fts5Fts5Func(\n  sqlite3_context *pCtx,          /* Function call context */\n  int nArg,                       /* Number of args */\n  sqlite3_value **apArg           /* Function arguments */\n){\n  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);\n  fts5_api **ppApi;\n  UNUSED_PARAM(nArg);\n  assert( nArg==1 );\n  ppApi = (fts5_api**)sqlite3_value_pointer(apArg[0], \"fts5_api_ptr\");\n  if( ppApi ) *ppApi = &pGlobal->api;\n}\n\n/*\n** Implementation of fts5_source_id() function.\n*/\nstatic void fts5SourceIdFunc(\n  sqlite3_context *pCtx,          /* Function call context */\n  int nArg,                       /* Number of args */\n  sqlite3_value **apUnused        /* Function arguments */\n){\n  assert( nArg==0 );\n  UNUSED_PARAM2(nArg, apUnused);\n  sqlite3_result_text(pCtx, \"fts5: 2020-06-18 14:00:33 7ebdfa80be8e8e73324b8d66b3460222eb74c7e9dfd655b48d6ca7e1933cc8fd\", -1, SQLITE_TRANSIENT);\n}\n\n/*\n** Return true if zName is the extension on one of the shadow tables used\n** by this module.\n*/\nstatic int fts5ShadowName(const char *zName){\n  static const char *azName[] = {\n    \"config\", \"content\", \"data\", \"docsize\", \"idx\"\n  };\n  unsigned int i;\n  for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){\n    if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;\n  }\n  return 0;\n}\n\nstatic int fts5Init(sqlite3 *db){\n  static const sqlite3_module fts5Mod = {\n    /* iVersion      */ 3,\n    /* xCreate       */ fts5CreateMethod,\n    /* xConnect      */ fts5ConnectMethod,\n    /* xBestIndex    */ fts5BestIndexMethod,\n    /* xDisconnect   */ fts5DisconnectMethod,\n    /* xDestroy      */ fts5DestroyMethod,\n    /* xOpen         */ fts5OpenMethod,\n    /* xClose        */ fts5CloseMethod,\n    /* xFilter       */ fts5FilterMethod,\n    /* xNext         */ fts5NextMethod,\n    /* xEof          */ fts5EofMethod,\n    /* xColumn       */ fts5ColumnMethod,\n    /* xRowid        */ fts5RowidMethod,\n    /* xUpdate       */ fts5UpdateMethod,\n    /* xBegin        */ fts5BeginMethod,\n    /* xSync         */ fts5SyncMethod,\n    /* xCommit       */ fts5CommitMethod,\n    /* xRollback     */ fts5RollbackMethod,\n    /* xFindFunction */ fts5FindFunctionMethod,\n    /* xRename       */ fts5RenameMethod,\n    /* xSavepoint    */ fts5SavepointMethod,\n    /* xRelease      */ fts5ReleaseMethod,\n    /* xRollbackTo   */ fts5RollbackToMethod,\n    /* xShadowName   */ fts5ShadowName\n  };\n\n  int rc;\n  Fts5Global *pGlobal = 0;\n\n  pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));\n  if( pGlobal==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    void *p = (void*)pGlobal;\n    memset(pGlobal, 0, sizeof(Fts5Global));\n    pGlobal->db = db;\n    pGlobal->api.iVersion = 2;\n    pGlobal->api.xCreateFunction = fts5CreateAux;\n    pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;\n    pGlobal->api.xFindTokenizer = fts5FindTokenizer;\n    rc = sqlite3_create_module_v2(db, \"fts5\", &fts5Mod, p, fts5ModuleDestroy);\n    if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);\n    if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);\n    if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);\n    if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);\n    if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);\n    if( rc==SQLITE_OK ){\n      rc = sqlite3_create_function(\n          db, \"fts5\", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0\n      );\n    }\n    if( rc==SQLITE_OK ){\n      rc = sqlite3_create_function(\n          db, \"fts5_source_id\", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0\n      );\n    }\n  }\n\n  /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file\n  ** fts5_test_mi.c is compiled and linked into the executable. And call\n  ** its entry point to enable the matchinfo() demo.  */\n#ifdef SQLITE_FTS5_ENABLE_TEST_MI\n  if( rc==SQLITE_OK ){\n    extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);\n    rc = sqlite3Fts5TestRegisterMatchinfo(db);\n  }\n#endif\n\n  return rc;\n}\n\n/*\n** The following functions are used to register the module with SQLite. If\n** this module is being built as part of the SQLite core (SQLITE_CORE is\n** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.\n**\n** Or, if this module is being built as a loadable extension, \n** sqlite3Fts5Init() is omitted and the two standard entry points\n** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.\n*/\n#ifndef SQLITE_CORE\n#ifdef _WIN32\n__declspec(dllexport)\n#endif\nSQLITE_API int sqlite3_fts_init(\n  sqlite3 *db,\n  char **pzErrMsg,\n  const sqlite3_api_routines *pApi\n){\n  SQLITE_EXTENSION_INIT2(pApi);\n  (void)pzErrMsg;  /* Unused parameter */\n  return fts5Init(db);\n}\n\n#ifdef _WIN32\n__declspec(dllexport)\n#endif\nSQLITE_API int sqlite3_fts5_init(\n  sqlite3 *db,\n  char **pzErrMsg,\n  const sqlite3_api_routines *pApi\n){\n  SQLITE_EXTENSION_INIT2(pApi);\n  (void)pzErrMsg;  /* Unused parameter */\n  return fts5Init(db);\n}\n#else\nSQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){\n  return fts5Init(db);\n}\n#endif\n\n/*\n** 2014 May 31\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n*/\n\n\n\n/* #include \"fts5Int.h\" */\n\nstruct Fts5Storage {\n  Fts5Config *pConfig;\n  Fts5Index *pIndex;\n  int bTotalsValid;               /* True if nTotalRow/aTotalSize[] are valid */\n  i64 nTotalRow;                  /* Total number of rows in FTS table */\n  i64 *aTotalSize;                /* Total sizes of each column */ \n  sqlite3_stmt *aStmt[11];\n};\n\n\n#if FTS5_STMT_SCAN_ASC!=0 \n# error \"FTS5_STMT_SCAN_ASC mismatch\" \n#endif\n#if FTS5_STMT_SCAN_DESC!=1 \n# error \"FTS5_STMT_SCAN_DESC mismatch\" \n#endif\n#if FTS5_STMT_LOOKUP!=2\n# error \"FTS5_STMT_LOOKUP mismatch\" \n#endif\n\n#define FTS5_STMT_INSERT_CONTENT  3\n#define FTS5_STMT_REPLACE_CONTENT 4\n#define FTS5_STMT_DELETE_CONTENT  5\n#define FTS5_STMT_REPLACE_DOCSIZE  6\n#define FTS5_STMT_DELETE_DOCSIZE  7\n#define FTS5_STMT_LOOKUP_DOCSIZE  8\n#define FTS5_STMT_REPLACE_CONFIG 9\n#define FTS5_STMT_SCAN 10\n\n/*\n** Prepare the two insert statements - Fts5Storage.pInsertContent and\n** Fts5Storage.pInsertDocsize - if they have not already been prepared.\n** Return SQLITE_OK if successful, or an SQLite error code if an error\n** occurs.\n*/\nstatic int fts5StorageGetStmt(\n  Fts5Storage *p,                 /* Storage handle */\n  int eStmt,                      /* FTS5_STMT_XXX constant */\n  sqlite3_stmt **ppStmt,          /* OUT: Prepared statement handle */\n  char **pzErrMsg                 /* OUT: Error message (if any) */\n){\n  int rc = SQLITE_OK;\n\n  /* If there is no %_docsize table, there should be no requests for \n  ** statements to operate on it.  */\n  assert( p->pConfig->bColumnsize || (\n        eStmt!=FTS5_STMT_REPLACE_DOCSIZE \n     && eStmt!=FTS5_STMT_DELETE_DOCSIZE \n     && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE \n  ));\n\n  assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );\n  if( p->aStmt[eStmt]==0 ){\n    const char *azStmt[] = {\n      \"SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC\",\n      \"SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC\",\n      \"SELECT %s FROM %s T WHERE T.%Q=?\",               /* LOOKUP  */\n\n      \"INSERT INTO %Q.'%q_content' VALUES(%s)\",         /* INSERT_CONTENT  */\n      \"REPLACE INTO %Q.'%q_content' VALUES(%s)\",        /* REPLACE_CONTENT */\n      \"DELETE FROM %Q.'%q_content' WHERE id=?\",         /* DELETE_CONTENT  */\n      \"REPLACE INTO %Q.'%q_docsize' VALUES(?,?)\",       /* REPLACE_DOCSIZE  */\n      \"DELETE FROM %Q.'%q_docsize' WHERE id=?\",         /* DELETE_DOCSIZE  */\n\n      \"SELECT sz FROM %Q.'%q_docsize' WHERE id=?\",      /* LOOKUP_DOCSIZE  */\n\n      \"REPLACE INTO %Q.'%q_config' VALUES(?,?)\",        /* REPLACE_CONFIG */\n      \"SELECT %s FROM %s AS T\",                         /* SCAN */\n    };\n    Fts5Config *pC = p->pConfig;\n    char *zSql = 0;\n\n    switch( eStmt ){\n      case FTS5_STMT_SCAN:\n        zSql = sqlite3_mprintf(azStmt[eStmt], \n            pC->zContentExprlist, pC->zContent\n        );\n        break;\n\n      case FTS5_STMT_SCAN_ASC:\n      case FTS5_STMT_SCAN_DESC:\n        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist, \n            pC->zContent, pC->zContentRowid, pC->zContentRowid,\n            pC->zContentRowid\n        );\n        break;\n\n      case FTS5_STMT_LOOKUP:\n        zSql = sqlite3_mprintf(azStmt[eStmt], \n            pC->zContentExprlist, pC->zContent, pC->zContentRowid\n        );\n        break;\n\n      case FTS5_STMT_INSERT_CONTENT: \n      case FTS5_STMT_REPLACE_CONTENT: {\n        int nCol = pC->nCol + 1;\n        char *zBind;\n        int i;\n\n        zBind = sqlite3_malloc64(1 + nCol*2);\n        if( zBind ){\n          for(i=0; i<nCol; i++){\n            zBind[i*2] = '?';\n            zBind[i*2 + 1] = ',';\n          }\n          zBind[i*2-1] = '\\0';\n          zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);\n          sqlite3_free(zBind);\n        }\n        break;\n      }\n\n      default:\n        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);\n        break;\n    }\n\n    if( zSql==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      int f = SQLITE_PREPARE_PERSISTENT;\n      if( eStmt>FTS5_STMT_LOOKUP ) f |= SQLITE_PREPARE_NO_VTAB;\n      p->pConfig->bLock++;\n      rc = sqlite3_prepare_v3(pC->db, zSql, -1, f, &p->aStmt[eStmt], 0);\n      p->pConfig->bLock--;\n      sqlite3_free(zSql);\n      if( rc!=SQLITE_OK && pzErrMsg ){\n        *pzErrMsg = sqlite3_mprintf(\"%s\", sqlite3_errmsg(pC->db));\n      }\n    }\n  }\n\n  *ppStmt = p->aStmt[eStmt];\n  sqlite3_reset(*ppStmt);\n  return rc;\n}\n\n\nstatic int fts5ExecPrintf(\n  sqlite3 *db,\n  char **pzErr,\n  const char *zFormat,\n  ...\n){\n  int rc;\n  va_list ap;                     /* ... printf arguments */\n  char *zSql;\n\n  va_start(ap, zFormat);\n  zSql = sqlite3_vmprintf(zFormat, ap);\n\n  if( zSql==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    rc = sqlite3_exec(db, zSql, 0, 0, pzErr);\n    sqlite3_free(zSql);\n  }\n\n  va_end(ap);\n  return rc;\n}\n\n/*\n** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error\n** code otherwise.\n*/\nstatic int sqlite3Fts5DropAll(Fts5Config *pConfig){\n  int rc = fts5ExecPrintf(pConfig->db, 0, \n      \"DROP TABLE IF EXISTS %Q.'%q_data';\"\n      \"DROP TABLE IF EXISTS %Q.'%q_idx';\"\n      \"DROP TABLE IF EXISTS %Q.'%q_config';\",\n      pConfig->zDb, pConfig->zName,\n      pConfig->zDb, pConfig->zName,\n      pConfig->zDb, pConfig->zName\n  );\n  if( rc==SQLITE_OK && pConfig->bColumnsize ){\n    rc = fts5ExecPrintf(pConfig->db, 0, \n        \"DROP TABLE IF EXISTS %Q.'%q_docsize';\",\n        pConfig->zDb, pConfig->zName\n    );\n  }\n  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){\n    rc = fts5ExecPrintf(pConfig->db, 0, \n        \"DROP TABLE IF EXISTS %Q.'%q_content';\",\n        pConfig->zDb, pConfig->zName\n    );\n  }\n  return rc;\n}\n\nstatic void fts5StorageRenameOne(\n  Fts5Config *pConfig,            /* Current FTS5 configuration */\n  int *pRc,                       /* IN/OUT: Error code */\n  const char *zTail,              /* Tail of table name e.g. \"data\", \"config\" */\n  const char *zName               /* New name of FTS5 table */\n){\n  if( *pRc==SQLITE_OK ){\n    *pRc = fts5ExecPrintf(pConfig->db, 0, \n        \"ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';\",\n        pConfig->zDb, pConfig->zName, zTail, zName, zTail\n    );\n  }\n}\n\nstatic int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){\n  Fts5Config *pConfig = pStorage->pConfig;\n  int rc = sqlite3Fts5StorageSync(pStorage);\n\n  fts5StorageRenameOne(pConfig, &rc, \"data\", zName);\n  fts5StorageRenameOne(pConfig, &rc, \"idx\", zName);\n  fts5StorageRenameOne(pConfig, &rc, \"config\", zName);\n  if( pConfig->bColumnsize ){\n    fts5StorageRenameOne(pConfig, &rc, \"docsize\", zName);\n  }\n  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){\n    fts5StorageRenameOne(pConfig, &rc, \"content\", zName);\n  }\n  return rc;\n}\n\n/*\n** Create the shadow table named zPost, with definition zDefn. Return\n** SQLITE_OK if successful, or an SQLite error code otherwise.\n*/\nstatic int sqlite3Fts5CreateTable(\n  Fts5Config *pConfig,            /* FTS5 configuration */\n  const char *zPost,              /* Shadow table to create (e.g. \"content\") */\n  const char *zDefn,              /* Columns etc. for shadow table */\n  int bWithout,                   /* True for without rowid */\n  char **pzErr                    /* OUT: Error message */\n){\n  int rc;\n  char *zErr = 0;\n\n  rc = fts5ExecPrintf(pConfig->db, &zErr, \"CREATE TABLE %Q.'%q_%q'(%s)%s\",\n      pConfig->zDb, pConfig->zName, zPost, zDefn, \n#ifndef SQLITE_FTS5_NO_WITHOUT_ROWID\n      bWithout?\" WITHOUT ROWID\":\n#endif\n      \"\"\n  );\n  if( zErr ){\n    *pzErr = sqlite3_mprintf(\n        \"fts5: error creating shadow table %q_%s: %s\", \n        pConfig->zName, zPost, zErr\n    );\n    sqlite3_free(zErr);\n  }\n\n  return rc;\n}\n\n/*\n** Open a new Fts5Index handle. If the bCreate argument is true, create\n** and initialize the underlying tables \n**\n** If successful, set *pp to point to the new object and return SQLITE_OK.\n** Otherwise, set *pp to NULL and return an SQLite error code.\n*/\nstatic int sqlite3Fts5StorageOpen(\n  Fts5Config *pConfig, \n  Fts5Index *pIndex, \n  int bCreate, \n  Fts5Storage **pp,\n  char **pzErr                    /* OUT: Error message */\n){\n  int rc = SQLITE_OK;\n  Fts5Storage *p;                 /* New object */\n  sqlite3_int64 nByte;            /* Bytes of space to allocate */\n\n  nByte = sizeof(Fts5Storage)               /* Fts5Storage object */\n        + pConfig->nCol * sizeof(i64);      /* Fts5Storage.aTotalSize[] */\n  *pp = p = (Fts5Storage*)sqlite3_malloc64(nByte);\n  if( !p ) return SQLITE_NOMEM;\n\n  memset(p, 0, (size_t)nByte);\n  p->aTotalSize = (i64*)&p[1];\n  p->pConfig = pConfig;\n  p->pIndex = pIndex;\n\n  if( bCreate ){\n    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){\n      int nDefn = 32 + pConfig->nCol*10;\n      char *zDefn = sqlite3_malloc64(32 + (sqlite3_int64)pConfig->nCol * 10);\n      if( zDefn==0 ){\n        rc = SQLITE_NOMEM;\n      }else{\n        int i;\n        int iOff;\n        sqlite3_snprintf(nDefn, zDefn, \"id INTEGER PRIMARY KEY\");\n        iOff = (int)strlen(zDefn);\n        for(i=0; i<pConfig->nCol; i++){\n          sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], \", c%d\", i);\n          iOff += (int)strlen(&zDefn[iOff]);\n        }\n        rc = sqlite3Fts5CreateTable(pConfig, \"content\", zDefn, 0, pzErr);\n      }\n      sqlite3_free(zDefn);\n    }\n\n    if( rc==SQLITE_OK && pConfig->bColumnsize ){\n      rc = sqlite3Fts5CreateTable(\n          pConfig, \"docsize\", \"id INTEGER PRIMARY KEY, sz BLOB\", 0, pzErr\n      );\n    }\n    if( rc==SQLITE_OK ){\n      rc = sqlite3Fts5CreateTable(\n          pConfig, \"config\", \"k PRIMARY KEY, v\", 1, pzErr\n      );\n    }\n    if( rc==SQLITE_OK ){\n      rc = sqlite3Fts5StorageConfigValue(p, \"version\", 0, FTS5_CURRENT_VERSION);\n    }\n  }\n\n  if( rc ){\n    sqlite3Fts5StorageClose(p);\n    *pp = 0;\n  }\n  return rc;\n}\n\n/*\n** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().\n*/\nstatic int sqlite3Fts5StorageClose(Fts5Storage *p){\n  int rc = SQLITE_OK;\n  if( p ){\n    int i;\n\n    /* Finalize all SQL statements */\n    for(i=0; i<ArraySize(p->aStmt); i++){\n      sqlite3_finalize(p->aStmt[i]);\n    }\n\n    sqlite3_free(p);\n  }\n  return rc;\n}\n\ntypedef struct Fts5InsertCtx Fts5InsertCtx;\nstruct Fts5InsertCtx {\n  Fts5Storage *pStorage;\n  int iCol;\n  int szCol;                      /* Size of column value in tokens */\n};\n\n/*\n** Tokenization callback used when inserting tokens into the FTS index.\n*/\nstatic int fts5StorageInsertCallback(\n  void *pContext,                 /* Pointer to Fts5InsertCtx object */\n  int tflags,\n  const char *pToken,             /* Buffer containing token */\n  int nToken,                     /* Size of token in bytes */\n  int iUnused1,                   /* Start offset of token */\n  int iUnused2                    /* End offset of token */\n){\n  Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;\n  Fts5Index *pIdx = pCtx->pStorage->pIndex;\n  UNUSED_PARAM2(iUnused1, iUnused2);\n  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;\n  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){\n    pCtx->szCol++;\n  }\n  return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);\n}\n\n/*\n** If a row with rowid iDel is present in the %_content table, add the\n** delete-markers to the FTS index necessary to delete it. Do not actually\n** remove the %_content row at this time though.\n*/\nstatic int fts5StorageDeleteFromIndex(\n  Fts5Storage *p, \n  i64 iDel, \n  sqlite3_value **apVal\n){\n  Fts5Config *pConfig = p->pConfig;\n  sqlite3_stmt *pSeek = 0;        /* SELECT to read row iDel from %_data */\n  int rc;                         /* Return code */\n  int rc2;                        /* sqlite3_reset() return code */\n  int iCol;\n  Fts5InsertCtx ctx;\n\n  if( apVal==0 ){\n    rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);\n    if( rc!=SQLITE_OK ) return rc;\n    sqlite3_bind_int64(pSeek, 1, iDel);\n    if( sqlite3_step(pSeek)!=SQLITE_ROW ){\n      return sqlite3_reset(pSeek);\n    }\n  }\n\n  ctx.pStorage = p;\n  ctx.iCol = -1;\n  rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);\n  for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){\n    if( pConfig->abUnindexed[iCol-1]==0 ){\n      const char *zText;\n      int nText;\n      if( pSeek ){\n        zText = (const char*)sqlite3_column_text(pSeek, iCol);\n        nText = sqlite3_column_bytes(pSeek, iCol);\n      }else{\n        zText = (const char*)sqlite3_value_text(apVal[iCol-1]);\n        nText = sqlite3_value_bytes(apVal[iCol-1]);\n      }\n      ctx.szCol = 0;\n      rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, \n          zText, nText, (void*)&ctx, fts5StorageInsertCallback\n      );\n      p->aTotalSize[iCol-1] -= (i64)ctx.szCol;\n    }\n  }\n  p->nTotalRow--;\n\n  rc2 = sqlite3_reset(pSeek);\n  if( rc==SQLITE_OK ) rc = rc2;\n  return rc;\n}\n\n\n/*\n** Insert a record into the %_docsize table. Specifically, do:\n**\n**   INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);\n**\n** If there is no %_docsize table (as happens if the columnsize=0 option\n** is specified when the FTS5 table is created), this function is a no-op.\n*/\nstatic int fts5StorageInsertDocsize(\n  Fts5Storage *p,                 /* Storage module to write to */\n  i64 iRowid,                     /* id value */\n  Fts5Buffer *pBuf                /* sz value */\n){\n  int rc = SQLITE_OK;\n  if( p->pConfig->bColumnsize ){\n    sqlite3_stmt *pReplace = 0;\n    rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int64(pReplace, 1, iRowid);\n      sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);\n      sqlite3_step(pReplace);\n      rc = sqlite3_reset(pReplace);\n      sqlite3_bind_null(pReplace, 2);\n    }\n  }\n  return rc;\n}\n\n/*\n** Load the contents of the \"averages\" record from disk into the \n** p->nTotalRow and p->aTotalSize[] variables. If successful, and if\n** argument bCache is true, set the p->bTotalsValid flag to indicate\n** that the contents of aTotalSize[] and nTotalRow are valid until\n** further notice.\n**\n** Return SQLITE_OK if successful, or an SQLite error code if an error\n** occurs.\n*/\nstatic int fts5StorageLoadTotals(Fts5Storage *p, int bCache){\n  int rc = SQLITE_OK;\n  if( p->bTotalsValid==0 ){\n    rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);\n    p->bTotalsValid = bCache;\n  }\n  return rc;\n}\n\n/*\n** Store the current contents of the p->nTotalRow and p->aTotalSize[] \n** variables in the \"averages\" record on disk.\n**\n** Return SQLITE_OK if successful, or an SQLite error code if an error\n** occurs.\n*/\nstatic int fts5StorageSaveTotals(Fts5Storage *p){\n  int nCol = p->pConfig->nCol;\n  int i;\n  Fts5Buffer buf;\n  int rc = SQLITE_OK;\n  memset(&buf, 0, sizeof(buf));\n\n  sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);\n  for(i=0; i<nCol; i++){\n    sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);\n  }\n  sqlite3_free(buf.p);\n\n  return rc;\n}\n\n/*\n** Remove a row from the FTS table.\n*/\nstatic int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){\n  Fts5Config *pConfig = p->pConfig;\n  int rc;\n  sqlite3_stmt *pDel = 0;\n\n  assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );\n  rc = fts5StorageLoadTotals(p, 1);\n\n  /* Delete the index records */\n  if( rc==SQLITE_OK ){\n    rc = fts5StorageDeleteFromIndex(p, iDel, apVal);\n  }\n\n  /* Delete the %_docsize record */\n  if( rc==SQLITE_OK && pConfig->bColumnsize ){\n    rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int64(pDel, 1, iDel);\n      sqlite3_step(pDel);\n      rc = sqlite3_reset(pDel);\n    }\n  }\n\n  /* Delete the %_content record */\n  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){\n    if( rc==SQLITE_OK ){\n      rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);\n    }\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int64(pDel, 1, iDel);\n      sqlite3_step(pDel);\n      rc = sqlite3_reset(pDel);\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Delete all entries in the FTS5 index.\n*/\nstatic int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){\n  Fts5Config *pConfig = p->pConfig;\n  int rc;\n\n  p->bTotalsValid = 0;\n\n  /* Delete the contents of the %_data and %_docsize tables. */\n  rc = fts5ExecPrintf(pConfig->db, 0,\n      \"DELETE FROM %Q.'%q_data';\" \n      \"DELETE FROM %Q.'%q_idx';\",\n      pConfig->zDb, pConfig->zName,\n      pConfig->zDb, pConfig->zName\n  );\n  if( rc==SQLITE_OK && pConfig->bColumnsize ){\n    rc = fts5ExecPrintf(pConfig->db, 0,\n        \"DELETE FROM %Q.'%q_docsize';\",\n        pConfig->zDb, pConfig->zName\n    );\n  }\n\n  /* Reinitialize the %_data table. This call creates the initial structure\n  ** and averages records.  */\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts5IndexReinit(p->pIndex);\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts5StorageConfigValue(p, \"version\", 0, FTS5_CURRENT_VERSION);\n  }\n  return rc;\n}\n\nstatic int sqlite3Fts5StorageRebuild(Fts5Storage *p){\n  Fts5Buffer buf = {0,0,0};\n  Fts5Config *pConfig = p->pConfig;\n  sqlite3_stmt *pScan = 0;\n  Fts5InsertCtx ctx;\n  int rc, rc2;\n\n  memset(&ctx, 0, sizeof(Fts5InsertCtx));\n  ctx.pStorage = p;\n  rc = sqlite3Fts5StorageDeleteAll(p);\n  if( rc==SQLITE_OK ){\n    rc = fts5StorageLoadTotals(p, 1);\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);\n  }\n\n  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){\n    i64 iRowid = sqlite3_column_int64(pScan, 0);\n\n    sqlite3Fts5BufferZero(&buf);\n    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);\n    for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){\n      ctx.szCol = 0;\n      if( pConfig->abUnindexed[ctx.iCol]==0 ){\n        const char *zText = (const char*)sqlite3_column_text(pScan, ctx.iCol+1);\n        int nText = sqlite3_column_bytes(pScan, ctx.iCol+1);\n        rc = sqlite3Fts5Tokenize(pConfig, \n            FTS5_TOKENIZE_DOCUMENT,\n            zText, nText,\n            (void*)&ctx,\n            fts5StorageInsertCallback\n        );\n      }\n      sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);\n      p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;\n    }\n    p->nTotalRow++;\n\n    if( rc==SQLITE_OK ){\n      rc = fts5StorageInsertDocsize(p, iRowid, &buf);\n    }\n  }\n  sqlite3_free(buf.p);\n  rc2 = sqlite3_reset(pScan);\n  if( rc==SQLITE_OK ) rc = rc2;\n\n  /* Write the averages record */\n  if( rc==SQLITE_OK ){\n    rc = fts5StorageSaveTotals(p);\n  }\n  return rc;\n}\n\nstatic int sqlite3Fts5StorageOptimize(Fts5Storage *p){\n  return sqlite3Fts5IndexOptimize(p->pIndex);\n}\n\nstatic int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){\n  return sqlite3Fts5IndexMerge(p->pIndex, nMerge);\n}\n\nstatic int sqlite3Fts5StorageReset(Fts5Storage *p){\n  return sqlite3Fts5IndexReset(p->pIndex);\n}\n\n/*\n** Allocate a new rowid. This is used for \"external content\" tables when\n** a NULL value is inserted into the rowid column. The new rowid is allocated\n** by inserting a dummy row into the %_docsize table. The dummy will be\n** overwritten later.\n**\n** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In\n** this case the user is required to provide a rowid explicitly.\n*/\nstatic int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){\n  int rc = SQLITE_MISMATCH;\n  if( p->pConfig->bColumnsize ){\n    sqlite3_stmt *pReplace = 0;\n    rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_null(pReplace, 1);\n      sqlite3_bind_null(pReplace, 2);\n      sqlite3_step(pReplace);\n      rc = sqlite3_reset(pReplace);\n    }\n    if( rc==SQLITE_OK ){\n      *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);\n    }\n  }\n  return rc;\n}\n\n/*\n** Insert a new row into the FTS content table.\n*/\nstatic int sqlite3Fts5StorageContentInsert(\n  Fts5Storage *p, \n  sqlite3_value **apVal, \n  i64 *piRowid\n){\n  Fts5Config *pConfig = p->pConfig;\n  int rc = SQLITE_OK;\n\n  /* Insert the new row into the %_content table. */\n  if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){\n    if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){\n      *piRowid = sqlite3_value_int64(apVal[1]);\n    }else{\n      rc = fts5StorageNewRowid(p, piRowid);\n    }\n  }else{\n    sqlite3_stmt *pInsert = 0;    /* Statement to write %_content table */\n    int i;                        /* Counter variable */\n    rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);\n    for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){\n      rc = sqlite3_bind_value(pInsert, i, apVal[i]);\n    }\n    if( rc==SQLITE_OK ){\n      sqlite3_step(pInsert);\n      rc = sqlite3_reset(pInsert);\n    }\n    *piRowid = sqlite3_last_insert_rowid(pConfig->db);\n  }\n\n  return rc;\n}\n\n/*\n** Insert new entries into the FTS index and %_docsize table.\n*/\nstatic int sqlite3Fts5StorageIndexInsert(\n  Fts5Storage *p, \n  sqlite3_value **apVal, \n  i64 iRowid\n){\n  Fts5Config *pConfig = p->pConfig;\n  int rc = SQLITE_OK;             /* Return code */\n  Fts5InsertCtx ctx;              /* Tokenization callback context object */\n  Fts5Buffer buf;                 /* Buffer used to build up %_docsize blob */\n\n  memset(&buf, 0, sizeof(Fts5Buffer));\n  ctx.pStorage = p;\n  rc = fts5StorageLoadTotals(p, 1);\n\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);\n  }\n  for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){\n    ctx.szCol = 0;\n    if( pConfig->abUnindexed[ctx.iCol]==0 ){\n      const char *zText = (const char*)sqlite3_value_text(apVal[ctx.iCol+2]);\n      int nText = sqlite3_value_bytes(apVal[ctx.iCol+2]);\n      rc = sqlite3Fts5Tokenize(pConfig, \n          FTS5_TOKENIZE_DOCUMENT,\n          zText, nText,\n          (void*)&ctx,\n          fts5StorageInsertCallback\n      );\n    }\n    sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);\n    p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;\n  }\n  p->nTotalRow++;\n\n  /* Write the %_docsize record */\n  if( rc==SQLITE_OK ){\n    rc = fts5StorageInsertDocsize(p, iRowid, &buf);\n  }\n  sqlite3_free(buf.p);\n\n  return rc;\n}\n\nstatic int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){\n  Fts5Config *pConfig = p->pConfig;\n  char *zSql;\n  int rc;\n\n  zSql = sqlite3_mprintf(\"SELECT count(*) FROM %Q.'%q_%s'\", \n      pConfig->zDb, pConfig->zName, zSuffix\n  );\n  if( zSql==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    sqlite3_stmt *pCnt = 0;\n    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);\n    if( rc==SQLITE_OK ){\n      if( SQLITE_ROW==sqlite3_step(pCnt) ){\n        *pnRow = sqlite3_column_int64(pCnt, 0);\n      }\n      rc = sqlite3_finalize(pCnt);\n    }\n  }\n\n  sqlite3_free(zSql);\n  return rc;\n}\n\n/*\n** Context object used by sqlite3Fts5StorageIntegrity().\n*/\ntypedef struct Fts5IntegrityCtx Fts5IntegrityCtx;\nstruct Fts5IntegrityCtx {\n  i64 iRowid;\n  int iCol;\n  int szCol;\n  u64 cksum;\n  Fts5Termset *pTermset;\n  Fts5Config *pConfig;\n};\n\n\n/*\n** Tokenization callback used by integrity check.\n*/\nstatic int fts5StorageIntegrityCallback(\n  void *pContext,                 /* Pointer to Fts5IntegrityCtx object */\n  int tflags,\n  const char *pToken,             /* Buffer containing token */\n  int nToken,                     /* Size of token in bytes */\n  int iUnused1,                   /* Start offset of token */\n  int iUnused2                    /* End offset of token */\n){\n  Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;\n  Fts5Termset *pTermset = pCtx->pTermset;\n  int bPresent;\n  int ii;\n  int rc = SQLITE_OK;\n  int iPos;\n  int iCol;\n\n  UNUSED_PARAM2(iUnused1, iUnused2);\n  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;\n\n  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){\n    pCtx->szCol++;\n  }\n\n  switch( pCtx->pConfig->eDetail ){\n    case FTS5_DETAIL_FULL:\n      iPos = pCtx->szCol-1;\n      iCol = pCtx->iCol;\n      break;\n\n    case FTS5_DETAIL_COLUMNS:\n      iPos = pCtx->iCol;\n      iCol = 0;\n      break;\n\n    default:\n      assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );\n      iPos = 0;\n      iCol = 0;\n      break;\n  }\n\n  rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);\n  if( rc==SQLITE_OK && bPresent==0 ){\n    pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(\n        pCtx->iRowid, iCol, iPos, 0, pToken, nToken\n    );\n  }\n\n  for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){\n    const int nChar = pCtx->pConfig->aPrefix[ii];\n    int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);\n    if( nByte ){\n      rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);\n      if( bPresent==0 ){\n        pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(\n            pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte\n        );\n      }\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Check that the contents of the FTS index match that of the %_content\n** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return\n** some other SQLite error code if an error occurs while attempting to\n** determine this.\n*/\nstatic int sqlite3Fts5StorageIntegrity(Fts5Storage *p){\n  Fts5Config *pConfig = p->pConfig;\n  int rc;                         /* Return code */\n  int *aColSize;                  /* Array of size pConfig->nCol */\n  i64 *aTotalSize;                /* Array of size pConfig->nCol */\n  Fts5IntegrityCtx ctx;\n  sqlite3_stmt *pScan;\n\n  memset(&ctx, 0, sizeof(Fts5IntegrityCtx));\n  ctx.pConfig = p->pConfig;\n  aTotalSize = (i64*)sqlite3_malloc64(pConfig->nCol*(sizeof(int)+sizeof(i64)));\n  if( !aTotalSize ) return SQLITE_NOMEM;\n  aColSize = (int*)&aTotalSize[pConfig->nCol];\n  memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);\n\n  /* Generate the expected index checksum based on the contents of the\n  ** %_content table. This block stores the checksum in ctx.cksum. */\n  rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);\n  if( rc==SQLITE_OK ){\n    int rc2;\n    while( SQLITE_ROW==sqlite3_step(pScan) ){\n      int i;\n      ctx.iRowid = sqlite3_column_int64(pScan, 0);\n      ctx.szCol = 0;\n      if( pConfig->bColumnsize ){\n        rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);\n      }\n      if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){\n        rc = sqlite3Fts5TermsetNew(&ctx.pTermset);\n      }\n      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){\n        if( pConfig->abUnindexed[i] ) continue;\n        ctx.iCol = i;\n        ctx.szCol = 0;\n        if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){\n          rc = sqlite3Fts5TermsetNew(&ctx.pTermset);\n        }\n        if( rc==SQLITE_OK ){\n          const char *zText = (const char*)sqlite3_column_text(pScan, i+1);\n          int nText = sqlite3_column_bytes(pScan, i+1);\n          rc = sqlite3Fts5Tokenize(pConfig, \n              FTS5_TOKENIZE_DOCUMENT,\n              zText, nText,\n              (void*)&ctx,\n              fts5StorageIntegrityCallback\n          );\n        }\n        if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){\n          rc = FTS5_CORRUPT;\n        }\n        aTotalSize[i] += ctx.szCol;\n        if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){\n          sqlite3Fts5TermsetFree(ctx.pTermset);\n          ctx.pTermset = 0;\n        }\n      }\n      sqlite3Fts5TermsetFree(ctx.pTermset);\n      ctx.pTermset = 0;\n\n      if( rc!=SQLITE_OK ) break;\n    }\n    rc2 = sqlite3_reset(pScan);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n\n  /* Test that the \"totals\" (sometimes called \"averages\") record looks Ok */\n  if( rc==SQLITE_OK ){\n    int i;\n    rc = fts5StorageLoadTotals(p, 0);\n    for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){\n      if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;\n    }\n  }\n\n  /* Check that the %_docsize and %_content tables contain the expected\n  ** number of rows.  */\n  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){\n    i64 nRow = 0;\n    rc = fts5StorageCount(p, \"content\", &nRow);\n    if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;\n  }\n  if( rc==SQLITE_OK && pConfig->bColumnsize ){\n    i64 nRow = 0;\n    rc = fts5StorageCount(p, \"docsize\", &nRow);\n    if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;\n  }\n\n  /* Pass the expected checksum down to the FTS index module. It will\n  ** verify, amongst other things, that it matches the checksum generated by\n  ** inspecting the index itself.  */\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);\n  }\n\n  sqlite3_free(aTotalSize);\n  return rc;\n}\n\n/*\n** Obtain an SQLite statement handle that may be used to read data from the\n** %_content table.\n*/\nstatic int sqlite3Fts5StorageStmt(\n  Fts5Storage *p, \n  int eStmt, \n  sqlite3_stmt **pp, \n  char **pzErrMsg\n){\n  int rc;\n  assert( eStmt==FTS5_STMT_SCAN_ASC \n       || eStmt==FTS5_STMT_SCAN_DESC\n       || eStmt==FTS5_STMT_LOOKUP\n  );\n  rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);\n  if( rc==SQLITE_OK ){\n    assert( p->aStmt[eStmt]==*pp );\n    p->aStmt[eStmt] = 0;\n  }\n  return rc;\n}\n\n/*\n** Release an SQLite statement handle obtained via an earlier call to\n** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function\n** must match that passed to the sqlite3Fts5StorageStmt() call.\n*/\nstatic void sqlite3Fts5StorageStmtRelease(\n  Fts5Storage *p, \n  int eStmt, \n  sqlite3_stmt *pStmt\n){\n  assert( eStmt==FTS5_STMT_SCAN_ASC\n       || eStmt==FTS5_STMT_SCAN_DESC\n       || eStmt==FTS5_STMT_LOOKUP\n  );\n  if( p->aStmt[eStmt]==0 ){\n    sqlite3_reset(pStmt);\n    p->aStmt[eStmt] = pStmt;\n  }else{\n    sqlite3_finalize(pStmt);\n  }\n}\n\nstatic int fts5StorageDecodeSizeArray(\n  int *aCol, int nCol,            /* Array to populate */\n  const u8 *aBlob, int nBlob      /* Record to read varints from */\n){\n  int i;\n  int iOff = 0;\n  for(i=0; i<nCol; i++){\n    if( iOff>=nBlob ) return 1;\n    iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);\n  }\n  return (iOff!=nBlob);\n}\n\n/*\n** Argument aCol points to an array of integers containing one entry for\n** each table column. This function reads the %_docsize record for the\n** specified rowid and populates aCol[] with the results.\n**\n** An SQLite error code is returned if an error occurs, or SQLITE_OK\n** otherwise.\n*/\nstatic int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){\n  int nCol = p->pConfig->nCol;    /* Number of user columns in table */\n  sqlite3_stmt *pLookup = 0;      /* Statement to query %_docsize */\n  int rc;                         /* Return Code */\n\n  assert( p->pConfig->bColumnsize );\n  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);\n  if( rc==SQLITE_OK ){\n    int bCorrupt = 1;\n    sqlite3_bind_int64(pLookup, 1, iRowid);\n    if( SQLITE_ROW==sqlite3_step(pLookup) ){\n      const u8 *aBlob = sqlite3_column_blob(pLookup, 0);\n      int nBlob = sqlite3_column_bytes(pLookup, 0);\n      if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){\n        bCorrupt = 0;\n      }\n    }\n    rc = sqlite3_reset(pLookup);\n    if( bCorrupt && rc==SQLITE_OK ){\n      rc = FTS5_CORRUPT;\n    }\n  }\n\n  return rc;\n}\n\nstatic int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){\n  int rc = fts5StorageLoadTotals(p, 0);\n  if( rc==SQLITE_OK ){\n    *pnToken = 0;\n    if( iCol<0 ){\n      int i;\n      for(i=0; i<p->pConfig->nCol; i++){\n        *pnToken += p->aTotalSize[i];\n      }\n    }else if( iCol<p->pConfig->nCol ){\n      *pnToken = p->aTotalSize[iCol];\n    }else{\n      rc = SQLITE_RANGE;\n    }\n  }\n  return rc;\n}\n\nstatic int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){\n  int rc = fts5StorageLoadTotals(p, 0);\n  if( rc==SQLITE_OK ){\n    /* nTotalRow being zero does not necessarily indicate a corrupt \n    ** database - it might be that the FTS5 table really does contain zero\n    ** rows. However this function is only called from the xRowCount() API,\n    ** and there is no way for that API to be invoked if the table contains\n    ** no rows. Hence the FTS5_CORRUPT return.  */\n    *pnRow = p->nTotalRow;\n    if( p->nTotalRow<=0 ) rc = FTS5_CORRUPT;\n  }\n  return rc;\n}\n\n/*\n** Flush any data currently held in-memory to disk.\n*/\nstatic int sqlite3Fts5StorageSync(Fts5Storage *p){\n  int rc = SQLITE_OK;\n  i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);\n  if( p->bTotalsValid ){\n    rc = fts5StorageSaveTotals(p);\n    p->bTotalsValid = 0;\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts5IndexSync(p->pIndex);\n  }\n  sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);\n  return rc;\n}\n\nstatic int sqlite3Fts5StorageRollback(Fts5Storage *p){\n  p->bTotalsValid = 0;\n  return sqlite3Fts5IndexRollback(p->pIndex);\n}\n\nstatic int sqlite3Fts5StorageConfigValue(\n  Fts5Storage *p, \n  const char *z,\n  sqlite3_value *pVal,\n  int iVal\n){\n  sqlite3_stmt *pReplace = 0;\n  int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);\n    if( pVal ){\n      sqlite3_bind_value(pReplace, 2, pVal);\n    }else{\n      sqlite3_bind_int(pReplace, 2, iVal);\n    }\n    sqlite3_step(pReplace);\n    rc = sqlite3_reset(pReplace);\n    sqlite3_bind_null(pReplace, 1);\n  }\n  if( rc==SQLITE_OK && pVal ){\n    int iNew = p->pConfig->iCookie + 1;\n    rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);\n    if( rc==SQLITE_OK ){\n      p->pConfig->iCookie = iNew;\n    }\n  }\n  return rc;\n}\n\n/*\n** 2014 May 31\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n*/\n\n\n/* #include \"fts5Int.h\" */\n\n/**************************************************************************\n** Start of ascii tokenizer implementation.\n*/\n\n/*\n** For tokenizers with no \"unicode\" modifier, the set of token characters\n** is the same as the set of ASCII range alphanumeric characters. \n*/\nstatic unsigned char aAsciiTokenChar[128] = {\n  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00..0x0F */\n  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x10..0x1F */\n  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20..0x2F */\n  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30..0x3F */\n  0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40..0x4F */\n  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x50..0x5F */\n  0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60..0x6F */\n  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x70..0x7F */\n};\n\ntypedef struct AsciiTokenizer AsciiTokenizer;\nstruct AsciiTokenizer {\n  unsigned char aTokenChar[128];\n};\n\nstatic void fts5AsciiAddExceptions(\n  AsciiTokenizer *p, \n  const char *zArg, \n  int bTokenChars\n){\n  int i;\n  for(i=0; zArg[i]; i++){\n    if( (zArg[i] & 0x80)==0 ){\n      p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;\n    }\n  }\n}\n\n/*\n** Delete a \"ascii\" tokenizer.\n*/\nstatic void fts5AsciiDelete(Fts5Tokenizer *p){\n  sqlite3_free(p);\n}\n\n/*\n** Create an \"ascii\" tokenizer.\n*/\nstatic int fts5AsciiCreate(\n  void *pUnused, \n  const char **azArg, int nArg,\n  Fts5Tokenizer **ppOut\n){\n  int rc = SQLITE_OK;\n  AsciiTokenizer *p = 0;\n  UNUSED_PARAM(pUnused);\n  if( nArg%2 ){\n    rc = SQLITE_ERROR;\n  }else{\n    p = sqlite3_malloc(sizeof(AsciiTokenizer));\n    if( p==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      int i;\n      memset(p, 0, sizeof(AsciiTokenizer));\n      memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));\n      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){\n        const char *zArg = azArg[i+1];\n        if( 0==sqlite3_stricmp(azArg[i], \"tokenchars\") ){\n          fts5AsciiAddExceptions(p, zArg, 1);\n        }else\n        if( 0==sqlite3_stricmp(azArg[i], \"separators\") ){\n          fts5AsciiAddExceptions(p, zArg, 0);\n        }else{\n          rc = SQLITE_ERROR;\n        }\n      }\n      if( rc!=SQLITE_OK ){\n        fts5AsciiDelete((Fts5Tokenizer*)p);\n        p = 0;\n      }\n    }\n  }\n\n  *ppOut = (Fts5Tokenizer*)p;\n  return rc;\n}\n\n\nstatic void asciiFold(char *aOut, const char *aIn, int nByte){\n  int i;\n  for(i=0; i<nByte; i++){\n    char c = aIn[i];\n    if( c>='A' && c<='Z' ) c += 32;\n    aOut[i] = c;\n  }\n}\n\n/*\n** Tokenize some text using the ascii tokenizer.\n*/\nstatic int fts5AsciiTokenize(\n  Fts5Tokenizer *pTokenizer,\n  void *pCtx,\n  int iUnused,\n  const char *pText, int nText,\n  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)\n){\n  AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;\n  int rc = SQLITE_OK;\n  int ie;\n  int is = 0;\n\n  char aFold[64];\n  int nFold = sizeof(aFold);\n  char *pFold = aFold;\n  unsigned char *a = p->aTokenChar;\n\n  UNUSED_PARAM(iUnused);\n\n  while( is<nText && rc==SQLITE_OK ){\n    int nByte;\n\n    /* Skip any leading divider characters. */\n    while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){\n      is++;\n    }\n    if( is==nText ) break;\n\n    /* Count the token characters */\n    ie = is+1;\n    while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){\n      ie++;\n    }\n\n    /* Fold to lower case */\n    nByte = ie-is;\n    if( nByte>nFold ){\n      if( pFold!=aFold ) sqlite3_free(pFold);\n      pFold = sqlite3_malloc64((sqlite3_int64)nByte*2);\n      if( pFold==0 ){\n        rc = SQLITE_NOMEM;\n        break;\n      }\n      nFold = nByte*2;\n    }\n    asciiFold(pFold, &pText[is], nByte);\n\n    /* Invoke the token callback */\n    rc = xToken(pCtx, 0, pFold, nByte, is, ie);\n    is = ie+1;\n  }\n  \n  if( pFold!=aFold ) sqlite3_free(pFold);\n  if( rc==SQLITE_DONE ) rc = SQLITE_OK;\n  return rc;\n}\n\n/**************************************************************************\n** Start of unicode61 tokenizer implementation.\n*/\n\n\n/*\n** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied\n** from the sqlite3 source file utf.c. If this file is compiled as part\n** of the amalgamation, they are not required.\n*/\n#ifndef SQLITE_AMALGAMATION\n\nstatic const unsigned char sqlite3Utf8Trans1[] = {\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,\n  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,\n  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,\n};\n\n#define READ_UTF8(zIn, zTerm, c)                           \\\n  c = *(zIn++);                                            \\\n  if( c>=0xc0 ){                                           \\\n    c = sqlite3Utf8Trans1[c-0xc0];                         \\\n    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \\\n      c = (c<<6) + (0x3f & *(zIn++));                      \\\n    }                                                      \\\n    if( c<0x80                                             \\\n        || (c&0xFFFFF800)==0xD800                          \\\n        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \\\n  }\n\n\n#define WRITE_UTF8(zOut, c) {                          \\\n  if( c<0x00080 ){                                     \\\n    *zOut++ = (unsigned char)(c&0xFF);                 \\\n  }                                                    \\\n  else if( c<0x00800 ){                                \\\n    *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F);     \\\n    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \\\n  }                                                    \\\n  else if( c<0x10000 ){                                \\\n    *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F);    \\\n    *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \\\n    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \\\n  }else{                                               \\\n    *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07);  \\\n    *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F);  \\\n    *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \\\n    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \\\n  }                                                    \\\n}\n\n#endif /* ifndef SQLITE_AMALGAMATION */\n\ntypedef struct Unicode61Tokenizer Unicode61Tokenizer;\nstruct Unicode61Tokenizer {\n  unsigned char aTokenChar[128];  /* ASCII range token characters */\n  char *aFold;                    /* Buffer to fold text into */\n  int nFold;                      /* Size of aFold[] in bytes */\n  int eRemoveDiacritic;           /* True if remove_diacritics=1 is set */\n  int nException;\n  int *aiException;\n\n  unsigned char aCategory[32];    /* True for token char categories */\n};\n\n/* Values for eRemoveDiacritic (must match internals of fts5_unicode2.c) */\n#define FTS5_REMOVE_DIACRITICS_NONE    0\n#define FTS5_REMOVE_DIACRITICS_SIMPLE  1\n#define FTS5_REMOVE_DIACRITICS_COMPLEX 2\n\nstatic int fts5UnicodeAddExceptions(\n  Unicode61Tokenizer *p,          /* Tokenizer object */\n  const char *z,                  /* Characters to treat as exceptions */\n  int bTokenChars                 /* 1 for 'tokenchars', 0 for 'separators' */\n){\n  int rc = SQLITE_OK;\n  int n = (int)strlen(z);\n  int *aNew;\n\n  if( n>0 ){\n    aNew = (int*)sqlite3_realloc64(p->aiException,\n                                   (n+p->nException)*sizeof(int));\n    if( aNew ){\n      int nNew = p->nException;\n      const unsigned char *zCsr = (const unsigned char*)z;\n      const unsigned char *zTerm = (const unsigned char*)&z[n];\n      while( zCsr<zTerm ){\n        u32 iCode;\n        int bToken;\n        READ_UTF8(zCsr, zTerm, iCode);\n        if( iCode<128 ){\n          p->aTokenChar[iCode] = (unsigned char)bTokenChars;\n        }else{\n          bToken = p->aCategory[sqlite3Fts5UnicodeCategory(iCode)];\n          assert( (bToken==0 || bToken==1) ); \n          assert( (bTokenChars==0 || bTokenChars==1) );\n          if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){\n            int i;\n            for(i=0; i<nNew; i++){\n              if( (u32)aNew[i]>iCode ) break;\n            }\n            memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));\n            aNew[i] = iCode;\n            nNew++;\n          }\n        }\n      }\n      p->aiException = aNew;\n      p->nException = nNew;\n    }else{\n      rc = SQLITE_NOMEM;\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Return true if the p->aiException[] array contains the value iCode.\n*/\nstatic int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){\n  if( p->nException>0 ){\n    int *a = p->aiException;\n    int iLo = 0;\n    int iHi = p->nException-1;\n\n    while( iHi>=iLo ){\n      int iTest = (iHi + iLo) / 2;\n      if( iCode==a[iTest] ){\n        return 1;\n      }else if( iCode>a[iTest] ){\n        iLo = iTest+1;\n      }else{\n        iHi = iTest-1;\n      }\n    }\n  }\n\n  return 0;\n}\n\n/*\n** Delete a \"unicode61\" tokenizer.\n*/\nstatic void fts5UnicodeDelete(Fts5Tokenizer *pTok){\n  if( pTok ){\n    Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;\n    sqlite3_free(p->aiException);\n    sqlite3_free(p->aFold);\n    sqlite3_free(p);\n  }\n  return;\n}\n\nstatic int unicodeSetCategories(Unicode61Tokenizer *p, const char *zCat){\n  const char *z = zCat;\n\n  while( *z ){\n    while( *z==' ' || *z=='\\t' ) z++;\n    if( *z && sqlite3Fts5UnicodeCatParse(z, p->aCategory) ){\n      return SQLITE_ERROR;\n    }\n    while( *z!=' ' && *z!='\\t' && *z!='\\0' ) z++;\n  }\n\n  sqlite3Fts5UnicodeAscii(p->aCategory, p->aTokenChar);\n  return SQLITE_OK;\n}\n\n/*\n** Create a \"unicode61\" tokenizer.\n*/\nstatic int fts5UnicodeCreate(\n  void *pUnused, \n  const char **azArg, int nArg,\n  Fts5Tokenizer **ppOut\n){\n  int rc = SQLITE_OK;             /* Return code */\n  Unicode61Tokenizer *p = 0;      /* New tokenizer object */ \n\n  UNUSED_PARAM(pUnused);\n\n  if( nArg%2 ){\n    rc = SQLITE_ERROR;\n  }else{\n    p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));\n    if( p ){\n      const char *zCat = \"L* N* Co\";\n      int i;\n      memset(p, 0, sizeof(Unicode61Tokenizer));\n\n      p->eRemoveDiacritic = FTS5_REMOVE_DIACRITICS_SIMPLE;\n      p->nFold = 64;\n      p->aFold = sqlite3_malloc64(p->nFold * sizeof(char));\n      if( p->aFold==0 ){\n        rc = SQLITE_NOMEM;\n      }\n\n      /* Search for a \"categories\" argument */\n      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){\n        if( 0==sqlite3_stricmp(azArg[i], \"categories\") ){\n          zCat = azArg[i+1];\n        }\n      }\n\n      if( rc==SQLITE_OK ){\n        rc = unicodeSetCategories(p, zCat);\n      }\n\n      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){\n        const char *zArg = azArg[i+1];\n        if( 0==sqlite3_stricmp(azArg[i], \"remove_diacritics\") ){\n          if( (zArg[0]!='0' && zArg[0]!='1' && zArg[0]!='2') || zArg[1] ){\n            rc = SQLITE_ERROR;\n          }else{\n            p->eRemoveDiacritic = (zArg[0] - '0');\n            assert( p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_NONE\n                 || p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_SIMPLE\n                 || p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_COMPLEX\n            );\n          }\n        }else\n        if( 0==sqlite3_stricmp(azArg[i], \"tokenchars\") ){\n          rc = fts5UnicodeAddExceptions(p, zArg, 1);\n        }else\n        if( 0==sqlite3_stricmp(azArg[i], \"separators\") ){\n          rc = fts5UnicodeAddExceptions(p, zArg, 0);\n        }else\n        if( 0==sqlite3_stricmp(azArg[i], \"categories\") ){\n          /* no-op */\n        }else{\n          rc = SQLITE_ERROR;\n        }\n      }\n\n    }else{\n      rc = SQLITE_NOMEM;\n    }\n    if( rc!=SQLITE_OK ){\n      fts5UnicodeDelete((Fts5Tokenizer*)p);\n      p = 0;\n    }\n    *ppOut = (Fts5Tokenizer*)p;\n  }\n  return rc;\n}\n\n/*\n** Return true if, for the purposes of tokenizing with the tokenizer\n** passed as the first argument, codepoint iCode is considered a token \n** character (not a separator).\n*/\nstatic int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){\n  return (\n    p->aCategory[sqlite3Fts5UnicodeCategory((u32)iCode)]\n    ^ fts5UnicodeIsException(p, iCode)\n  );\n}\n\nstatic int fts5UnicodeTokenize(\n  Fts5Tokenizer *pTokenizer,\n  void *pCtx,\n  int iUnused,\n  const char *pText, int nText,\n  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)\n){\n  Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;\n  int rc = SQLITE_OK;\n  unsigned char *a = p->aTokenChar;\n\n  unsigned char *zTerm = (unsigned char*)&pText[nText];\n  unsigned char *zCsr = (unsigned char *)pText;\n\n  /* Output buffer */\n  char *aFold = p->aFold;\n  int nFold = p->nFold;\n  const char *pEnd = &aFold[nFold-6];\n\n  UNUSED_PARAM(iUnused);\n\n  /* Each iteration of this loop gobbles up a contiguous run of separators,\n  ** then the next token.  */\n  while( rc==SQLITE_OK ){\n    u32 iCode;                    /* non-ASCII codepoint read from input */\n    char *zOut = aFold;\n    int is;\n    int ie;\n\n    /* Skip any separator characters. */\n    while( 1 ){\n      if( zCsr>=zTerm ) goto tokenize_done;\n      if( *zCsr & 0x80 ) {\n        /* A character outside of the ascii range. Skip past it if it is\n        ** a separator character. Or break out of the loop if it is not. */\n        is = zCsr - (unsigned char*)pText;\n        READ_UTF8(zCsr, zTerm, iCode);\n        if( fts5UnicodeIsAlnum(p, iCode) ){\n          goto non_ascii_tokenchar;\n        }\n      }else{\n        if( a[*zCsr] ){\n          is = zCsr - (unsigned char*)pText;\n          goto ascii_tokenchar;\n        }\n        zCsr++;\n      }\n    }\n\n    /* Run through the tokenchars. Fold them into the output buffer along\n    ** the way.  */\n    while( zCsr<zTerm ){\n\n      /* Grow the output buffer so that there is sufficient space to fit the\n      ** largest possible utf-8 character.  */\n      if( zOut>pEnd ){\n        aFold = sqlite3_malloc64((sqlite3_int64)nFold*2);\n        if( aFold==0 ){\n          rc = SQLITE_NOMEM;\n          goto tokenize_done;\n        }\n        zOut = &aFold[zOut - p->aFold];\n        memcpy(aFold, p->aFold, nFold);\n        sqlite3_free(p->aFold);\n        p->aFold = aFold;\n        p->nFold = nFold = nFold*2;\n        pEnd = &aFold[nFold-6];\n      }\n\n      if( *zCsr & 0x80 ){\n        /* An non-ascii-range character. Fold it into the output buffer if\n        ** it is a token character, or break out of the loop if it is not. */\n        READ_UTF8(zCsr, zTerm, iCode);\n        if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){\n non_ascii_tokenchar:\n          iCode = sqlite3Fts5UnicodeFold(iCode, p->eRemoveDiacritic);\n          if( iCode ) WRITE_UTF8(zOut, iCode);\n        }else{\n          break;\n        }\n      }else if( a[*zCsr]==0 ){\n        /* An ascii-range separator character. End of token. */\n        break; \n      }else{\n ascii_tokenchar:\n        if( *zCsr>='A' && *zCsr<='Z' ){\n          *zOut++ = *zCsr + 32;\n        }else{\n          *zOut++ = *zCsr;\n        }\n        zCsr++;\n      }\n      ie = zCsr - (unsigned char*)pText;\n    }\n\n    /* Invoke the token callback */\n    rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie); \n  }\n  \n tokenize_done:\n  if( rc==SQLITE_DONE ) rc = SQLITE_OK;\n  return rc;\n}\n\n/**************************************************************************\n** Start of porter stemmer implementation.\n*/\n\n/* Any tokens larger than this (in bytes) are passed through without\n** stemming. */\n#define FTS5_PORTER_MAX_TOKEN 64\n\ntypedef struct PorterTokenizer PorterTokenizer;\nstruct PorterTokenizer {\n  fts5_tokenizer tokenizer;       /* Parent tokenizer module */\n  Fts5Tokenizer *pTokenizer;      /* Parent tokenizer instance */\n  char aBuf[FTS5_PORTER_MAX_TOKEN + 64];\n};\n\n/*\n** Delete a \"porter\" tokenizer.\n*/\nstatic void fts5PorterDelete(Fts5Tokenizer *pTok){\n  if( pTok ){\n    PorterTokenizer *p = (PorterTokenizer*)pTok;\n    if( p->pTokenizer ){\n      p->tokenizer.xDelete(p->pTokenizer);\n    }\n    sqlite3_free(p);\n  }\n}\n\n/*\n** Create a \"porter\" tokenizer.\n*/\nstatic int fts5PorterCreate(\n  void *pCtx, \n  const char **azArg, int nArg,\n  Fts5Tokenizer **ppOut\n){\n  fts5_api *pApi = (fts5_api*)pCtx;\n  int rc = SQLITE_OK;\n  PorterTokenizer *pRet;\n  void *pUserdata = 0;\n  const char *zBase = \"unicode61\";\n\n  if( nArg>0 ){\n    zBase = azArg[0];\n  }\n\n  pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));\n  if( pRet ){\n    memset(pRet, 0, sizeof(PorterTokenizer));\n    rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);\n  }else{\n    rc = SQLITE_NOMEM;\n  }\n  if( rc==SQLITE_OK ){\n    int nArg2 = (nArg>0 ? nArg-1 : 0);\n    const char **azArg2 = (nArg2 ? &azArg[1] : 0);\n    rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);\n  }\n\n  if( rc!=SQLITE_OK ){\n    fts5PorterDelete((Fts5Tokenizer*)pRet);\n    pRet = 0;\n  }\n  *ppOut = (Fts5Tokenizer*)pRet;\n  return rc;\n}\n\ntypedef struct PorterContext PorterContext;\nstruct PorterContext {\n  void *pCtx;\n  int (*xToken)(void*, int, const char*, int, int, int);\n  char *aBuf;\n};\n\ntypedef struct PorterRule PorterRule;\nstruct PorterRule {\n  const char *zSuffix;\n  int nSuffix;\n  int (*xCond)(char *zStem, int nStem);\n  const char *zOutput;\n  int nOutput;\n};\n\n#if 0\nstatic int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){\n  int ret = -1;\n  int nBuf = *pnBuf;\n  PorterRule *p;\n\n  for(p=aRule; p->zSuffix; p++){\n    assert( strlen(p->zSuffix)==p->nSuffix );\n    assert( strlen(p->zOutput)==p->nOutput );\n    if( nBuf<p->nSuffix ) continue;\n    if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;\n  }\n\n  if( p->zSuffix ){\n    int nStem = nBuf - p->nSuffix;\n    if( p->xCond==0 || p->xCond(aBuf, nStem) ){\n      memcpy(&aBuf[nStem], p->zOutput, p->nOutput);\n      *pnBuf = nStem + p->nOutput;\n      ret = p - aRule;\n    }\n  }\n\n  return ret;\n}\n#endif\n\nstatic int fts5PorterIsVowel(char c, int bYIsVowel){\n  return (\n      c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')\n  );\n}\n\nstatic int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){\n  int i;\n  int bCons = bPrevCons;\n\n  /* Scan for a vowel */\n  for(i=0; i<nStem; i++){\n    if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;\n  }\n\n  /* Scan for a consonent */\n  for(i++; i<nStem; i++){\n    if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;\n  }\n  return 0;\n}\n\n/* porter rule condition: (m > 0) */\nstatic int fts5Porter_MGt0(char *zStem, int nStem){\n  return !!fts5PorterGobbleVC(zStem, nStem, 0);\n}\n\n/* porter rule condition: (m > 1) */\nstatic int fts5Porter_MGt1(char *zStem, int nStem){\n  int n;\n  n = fts5PorterGobbleVC(zStem, nStem, 0);\n  if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){\n    return 1;\n  }\n  return 0;\n}\n\n/* porter rule condition: (m = 1) */\nstatic int fts5Porter_MEq1(char *zStem, int nStem){\n  int n;\n  n = fts5PorterGobbleVC(zStem, nStem, 0);\n  if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){\n    return 1;\n  }\n  return 0;\n}\n\n/* porter rule condition: (*o) */\nstatic int fts5Porter_Ostar(char *zStem, int nStem){\n  if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){\n    return 0;\n  }else{\n    int i;\n    int mask = 0;\n    int bCons = 0;\n    for(i=0; i<nStem; i++){\n      bCons = !fts5PorterIsVowel(zStem[i], bCons);\n      assert( bCons==0 || bCons==1 );\n      mask = (mask << 1) + bCons;\n    }\n    return ((mask & 0x0007)==0x0005);\n  }\n}\n\n/* porter rule condition: (m > 1 and (*S or *T)) */\nstatic int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){\n  assert( nStem>0 );\n  return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t') \n      && fts5Porter_MGt1(zStem, nStem);\n}\n\n/* porter rule condition: (*v*) */\nstatic int fts5Porter_Vowel(char *zStem, int nStem){\n  int i;\n  for(i=0; i<nStem; i++){\n    if( fts5PorterIsVowel(zStem[i], i>0) ){\n      return 1;\n    }\n  }\n  return 0;\n}\n\n\n/**************************************************************************\n***************************************************************************\n** GENERATED CODE STARTS HERE (mkportersteps.tcl)\n*/\n\nstatic int fts5PorterStep4(char *aBuf, int *pnBuf){\n  int ret = 0;\n  int nBuf = *pnBuf;\n  switch( aBuf[nBuf-2] ){\n    \n    case 'a': \n      if( nBuf>2 && 0==memcmp(\"al\", &aBuf[nBuf-2], 2) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-2) ){\n          *pnBuf = nBuf - 2;\n        }\n      }\n      break;\n  \n    case 'c': \n      if( nBuf>4 && 0==memcmp(\"ance\", &aBuf[nBuf-4], 4) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-4) ){\n          *pnBuf = nBuf - 4;\n        }\n      }else if( nBuf>4 && 0==memcmp(\"ence\", &aBuf[nBuf-4], 4) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-4) ){\n          *pnBuf = nBuf - 4;\n        }\n      }\n      break;\n  \n    case 'e': \n      if( nBuf>2 && 0==memcmp(\"er\", &aBuf[nBuf-2], 2) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-2) ){\n          *pnBuf = nBuf - 2;\n        }\n      }\n      break;\n  \n    case 'i': \n      if( nBuf>2 && 0==memcmp(\"ic\", &aBuf[nBuf-2], 2) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-2) ){\n          *pnBuf = nBuf - 2;\n        }\n      }\n      break;\n  \n    case 'l': \n      if( nBuf>4 && 0==memcmp(\"able\", &aBuf[nBuf-4], 4) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-4) ){\n          *pnBuf = nBuf - 4;\n        }\n      }else if( nBuf>4 && 0==memcmp(\"ible\", &aBuf[nBuf-4], 4) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-4) ){\n          *pnBuf = nBuf - 4;\n        }\n      }\n      break;\n  \n    case 'n': \n      if( nBuf>3 && 0==memcmp(\"ant\", &aBuf[nBuf-3], 3) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-3) ){\n          *pnBuf = nBuf - 3;\n        }\n      }else if( nBuf>5 && 0==memcmp(\"ement\", &aBuf[nBuf-5], 5) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-5) ){\n          *pnBuf = nBuf - 5;\n        }\n      }else if( nBuf>4 && 0==memcmp(\"ment\", &aBuf[nBuf-4], 4) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-4) ){\n          *pnBuf = nBuf - 4;\n        }\n      }else if( nBuf>3 && 0==memcmp(\"ent\", &aBuf[nBuf-3], 3) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-3) ){\n          *pnBuf = nBuf - 3;\n        }\n      }\n      break;\n  \n    case 'o': \n      if( nBuf>3 && 0==memcmp(\"ion\", &aBuf[nBuf-3], 3) ){\n        if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){\n          *pnBuf = nBuf - 3;\n        }\n      }else if( nBuf>2 && 0==memcmp(\"ou\", &aBuf[nBuf-2], 2) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-2) ){\n          *pnBuf = nBuf - 2;\n        }\n      }\n      break;\n  \n    case 's': \n      if( nBuf>3 && 0==memcmp(\"ism\", &aBuf[nBuf-3], 3) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-3) ){\n          *pnBuf = nBuf - 3;\n        }\n      }\n      break;\n  \n    case 't': \n      if( nBuf>3 && 0==memcmp(\"ate\", &aBuf[nBuf-3], 3) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-3) ){\n          *pnBuf = nBuf - 3;\n        }\n      }else if( nBuf>3 && 0==memcmp(\"iti\", &aBuf[nBuf-3], 3) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-3) ){\n          *pnBuf = nBuf - 3;\n        }\n      }\n      break;\n  \n    case 'u': \n      if( nBuf>3 && 0==memcmp(\"ous\", &aBuf[nBuf-3], 3) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-3) ){\n          *pnBuf = nBuf - 3;\n        }\n      }\n      break;\n  \n    case 'v': \n      if( nBuf>3 && 0==memcmp(\"ive\", &aBuf[nBuf-3], 3) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-3) ){\n          *pnBuf = nBuf - 3;\n        }\n      }\n      break;\n  \n    case 'z': \n      if( nBuf>3 && 0==memcmp(\"ize\", &aBuf[nBuf-3], 3) ){\n        if( fts5Porter_MGt1(aBuf, nBuf-3) ){\n          *pnBuf = nBuf - 3;\n        }\n      }\n      break;\n  \n  }\n  return ret;\n}\n  \n\nstatic int fts5PorterStep1B2(char *aBuf, int *pnBuf){\n  int ret = 0;\n  int nBuf = *pnBuf;\n  switch( aBuf[nBuf-2] ){\n    \n    case 'a': \n      if( nBuf>2 && 0==memcmp(\"at\", &aBuf[nBuf-2], 2) ){\n        memcpy(&aBuf[nBuf-2], \"ate\", 3);\n        *pnBuf = nBuf - 2 + 3;\n        ret = 1;\n      }\n      break;\n  \n    case 'b': \n      if( nBuf>2 && 0==memcmp(\"bl\", &aBuf[nBuf-2], 2) ){\n        memcpy(&aBuf[nBuf-2], \"ble\", 3);\n        *pnBuf = nBuf - 2 + 3;\n        ret = 1;\n      }\n      break;\n  \n    case 'i': \n      if( nBuf>2 && 0==memcmp(\"iz\", &aBuf[nBuf-2], 2) ){\n        memcpy(&aBuf[nBuf-2], \"ize\", 3);\n        *pnBuf = nBuf - 2 + 3;\n        ret = 1;\n      }\n      break;\n  \n  }\n  return ret;\n}\n  \n\nstatic int fts5PorterStep2(char *aBuf, int *pnBuf){\n  int ret = 0;\n  int nBuf = *pnBuf;\n  switch( aBuf[nBuf-2] ){\n    \n    case 'a': \n      if( nBuf>7 && 0==memcmp(\"ational\", &aBuf[nBuf-7], 7) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-7) ){\n          memcpy(&aBuf[nBuf-7], \"ate\", 3);\n          *pnBuf = nBuf - 7 + 3;\n        }\n      }else if( nBuf>6 && 0==memcmp(\"tional\", &aBuf[nBuf-6], 6) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-6) ){\n          memcpy(&aBuf[nBuf-6], \"tion\", 4);\n          *pnBuf = nBuf - 6 + 4;\n        }\n      }\n      break;\n  \n    case 'c': \n      if( nBuf>4 && 0==memcmp(\"enci\", &aBuf[nBuf-4], 4) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-4) ){\n          memcpy(&aBuf[nBuf-4], \"ence\", 4);\n          *pnBuf = nBuf - 4 + 4;\n        }\n      }else if( nBuf>4 && 0==memcmp(\"anci\", &aBuf[nBuf-4], 4) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-4) ){\n          memcpy(&aBuf[nBuf-4], \"ance\", 4);\n          *pnBuf = nBuf - 4 + 4;\n        }\n      }\n      break;\n  \n    case 'e': \n      if( nBuf>4 && 0==memcmp(\"izer\", &aBuf[nBuf-4], 4) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-4) ){\n          memcpy(&aBuf[nBuf-4], \"ize\", 3);\n          *pnBuf = nBuf - 4 + 3;\n        }\n      }\n      break;\n  \n    case 'g': \n      if( nBuf>4 && 0==memcmp(\"logi\", &aBuf[nBuf-4], 4) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-4) ){\n          memcpy(&aBuf[nBuf-4], \"log\", 3);\n          *pnBuf = nBuf - 4 + 3;\n        }\n      }\n      break;\n  \n    case 'l': \n      if( nBuf>3 && 0==memcmp(\"bli\", &aBuf[nBuf-3], 3) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-3) ){\n          memcpy(&aBuf[nBuf-3], \"ble\", 3);\n          *pnBuf = nBuf - 3 + 3;\n        }\n      }else if( nBuf>4 && 0==memcmp(\"alli\", &aBuf[nBuf-4], 4) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-4) ){\n          memcpy(&aBuf[nBuf-4], \"al\", 2);\n          *pnBuf = nBuf - 4 + 2;\n        }\n      }else if( nBuf>5 && 0==memcmp(\"entli\", &aBuf[nBuf-5], 5) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-5) ){\n          memcpy(&aBuf[nBuf-5], \"ent\", 3);\n          *pnBuf = nBuf - 5 + 3;\n        }\n      }else if( nBuf>3 && 0==memcmp(\"eli\", &aBuf[nBuf-3], 3) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-3) ){\n          memcpy(&aBuf[nBuf-3], \"e\", 1);\n          *pnBuf = nBuf - 3 + 1;\n        }\n      }else if( nBuf>5 && 0==memcmp(\"ousli\", &aBuf[nBuf-5], 5) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-5) ){\n          memcpy(&aBuf[nBuf-5], \"ous\", 3);\n          *pnBuf = nBuf - 5 + 3;\n        }\n      }\n      break;\n  \n    case 'o': \n      if( nBuf>7 && 0==memcmp(\"ization\", &aBuf[nBuf-7], 7) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-7) ){\n          memcpy(&aBuf[nBuf-7], \"ize\", 3);\n          *pnBuf = nBuf - 7 + 3;\n        }\n      }else if( nBuf>5 && 0==memcmp(\"ation\", &aBuf[nBuf-5], 5) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-5) ){\n          memcpy(&aBuf[nBuf-5], \"ate\", 3);\n          *pnBuf = nBuf - 5 + 3;\n        }\n      }else if( nBuf>4 && 0==memcmp(\"ator\", &aBuf[nBuf-4], 4) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-4) ){\n          memcpy(&aBuf[nBuf-4], \"ate\", 3);\n          *pnBuf = nBuf - 4 + 3;\n        }\n      }\n      break;\n  \n    case 's': \n      if( nBuf>5 && 0==memcmp(\"alism\", &aBuf[nBuf-5], 5) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-5) ){\n          memcpy(&aBuf[nBuf-5], \"al\", 2);\n          *pnBuf = nBuf - 5 + 2;\n        }\n      }else if( nBuf>7 && 0==memcmp(\"iveness\", &aBuf[nBuf-7], 7) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-7) ){\n          memcpy(&aBuf[nBuf-7], \"ive\", 3);\n          *pnBuf = nBuf - 7 + 3;\n        }\n      }else if( nBuf>7 && 0==memcmp(\"fulness\", &aBuf[nBuf-7], 7) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-7) ){\n          memcpy(&aBuf[nBuf-7], \"ful\", 3);\n          *pnBuf = nBuf - 7 + 3;\n        }\n      }else if( nBuf>7 && 0==memcmp(\"ousness\", &aBuf[nBuf-7], 7) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-7) ){\n          memcpy(&aBuf[nBuf-7], \"ous\", 3);\n          *pnBuf = nBuf - 7 + 3;\n        }\n      }\n      break;\n  \n    case 't': \n      if( nBuf>5 && 0==memcmp(\"aliti\", &aBuf[nBuf-5], 5) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-5) ){\n          memcpy(&aBuf[nBuf-5], \"al\", 2);\n          *pnBuf = nBuf - 5 + 2;\n        }\n      }else if( nBuf>5 && 0==memcmp(\"iviti\", &aBuf[nBuf-5], 5) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-5) ){\n          memcpy(&aBuf[nBuf-5], \"ive\", 3);\n          *pnBuf = nBuf - 5 + 3;\n        }\n      }else if( nBuf>6 && 0==memcmp(\"biliti\", &aBuf[nBuf-6], 6) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-6) ){\n          memcpy(&aBuf[nBuf-6], \"ble\", 3);\n          *pnBuf = nBuf - 6 + 3;\n        }\n      }\n      break;\n  \n  }\n  return ret;\n}\n  \n\nstatic int fts5PorterStep3(char *aBuf, int *pnBuf){\n  int ret = 0;\n  int nBuf = *pnBuf;\n  switch( aBuf[nBuf-2] ){\n    \n    case 'a': \n      if( nBuf>4 && 0==memcmp(\"ical\", &aBuf[nBuf-4], 4) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-4) ){\n          memcpy(&aBuf[nBuf-4], \"ic\", 2);\n          *pnBuf = nBuf - 4 + 2;\n        }\n      }\n      break;\n  \n    case 's': \n      if( nBuf>4 && 0==memcmp(\"ness\", &aBuf[nBuf-4], 4) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-4) ){\n          *pnBuf = nBuf - 4;\n        }\n      }\n      break;\n  \n    case 't': \n      if( nBuf>5 && 0==memcmp(\"icate\", &aBuf[nBuf-5], 5) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-5) ){\n          memcpy(&aBuf[nBuf-5], \"ic\", 2);\n          *pnBuf = nBuf - 5 + 2;\n        }\n      }else if( nBuf>5 && 0==memcmp(\"iciti\", &aBuf[nBuf-5], 5) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-5) ){\n          memcpy(&aBuf[nBuf-5], \"ic\", 2);\n          *pnBuf = nBuf - 5 + 2;\n        }\n      }\n      break;\n  \n    case 'u': \n      if( nBuf>3 && 0==memcmp(\"ful\", &aBuf[nBuf-3], 3) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-3) ){\n          *pnBuf = nBuf - 3;\n        }\n      }\n      break;\n  \n    case 'v': \n      if( nBuf>5 && 0==memcmp(\"ative\", &aBuf[nBuf-5], 5) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-5) ){\n          *pnBuf = nBuf - 5;\n        }\n      }\n      break;\n  \n    case 'z': \n      if( nBuf>5 && 0==memcmp(\"alize\", &aBuf[nBuf-5], 5) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-5) ){\n          memcpy(&aBuf[nBuf-5], \"al\", 2);\n          *pnBuf = nBuf - 5 + 2;\n        }\n      }\n      break;\n  \n  }\n  return ret;\n}\n  \n\nstatic int fts5PorterStep1B(char *aBuf, int *pnBuf){\n  int ret = 0;\n  int nBuf = *pnBuf;\n  switch( aBuf[nBuf-2] ){\n    \n    case 'e': \n      if( nBuf>3 && 0==memcmp(\"eed\", &aBuf[nBuf-3], 3) ){\n        if( fts5Porter_MGt0(aBuf, nBuf-3) ){\n          memcpy(&aBuf[nBuf-3], \"ee\", 2);\n          *pnBuf = nBuf - 3 + 2;\n        }\n      }else if( nBuf>2 && 0==memcmp(\"ed\", &aBuf[nBuf-2], 2) ){\n        if( fts5Porter_Vowel(aBuf, nBuf-2) ){\n          *pnBuf = nBuf - 2;\n          ret = 1;\n        }\n      }\n      break;\n  \n    case 'n': \n      if( nBuf>3 && 0==memcmp(\"ing\", &aBuf[nBuf-3], 3) ){\n        if( fts5Porter_Vowel(aBuf, nBuf-3) ){\n          *pnBuf = nBuf - 3;\n          ret = 1;\n        }\n      }\n      break;\n  \n  }\n  return ret;\n}\n  \n/* \n** GENERATED CODE ENDS HERE (mkportersteps.tcl)\n***************************************************************************\n**************************************************************************/\n\nstatic void fts5PorterStep1A(char *aBuf, int *pnBuf){\n  int nBuf = *pnBuf;\n  if( aBuf[nBuf-1]=='s' ){\n    if( aBuf[nBuf-2]=='e' ){\n      if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s') \n       || (nBuf>3 && aBuf[nBuf-3]=='i' )\n      ){\n        *pnBuf = nBuf-2;\n      }else{\n        *pnBuf = nBuf-1;\n      }\n    }\n    else if( aBuf[nBuf-2]!='s' ){\n      *pnBuf = nBuf-1;\n    }\n  }\n}\n\nstatic int fts5PorterCb(\n  void *pCtx, \n  int tflags,\n  const char *pToken, \n  int nToken, \n  int iStart, \n  int iEnd\n){\n  PorterContext *p = (PorterContext*)pCtx;\n\n  char *aBuf;\n  int nBuf;\n\n  if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;\n  aBuf = p->aBuf;\n  nBuf = nToken;\n  memcpy(aBuf, pToken, nBuf);\n\n  /* Step 1. */\n  fts5PorterStep1A(aBuf, &nBuf);\n  if( fts5PorterStep1B(aBuf, &nBuf) ){\n    if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){\n      char c = aBuf[nBuf-1];\n      if( fts5PorterIsVowel(c, 0)==0 \n       && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2] \n      ){\n        nBuf--;\n      }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){\n        aBuf[nBuf++] = 'e';\n      }\n    }\n  }\n\n  /* Step 1C. */\n  if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){\n    aBuf[nBuf-1] = 'i';\n  }\n\n  /* Steps 2 through 4. */\n  fts5PorterStep2(aBuf, &nBuf);\n  fts5PorterStep3(aBuf, &nBuf);\n  fts5PorterStep4(aBuf, &nBuf);\n\n  /* Step 5a. */\n  assert( nBuf>0 );\n  if( aBuf[nBuf-1]=='e' ){\n    if( fts5Porter_MGt1(aBuf, nBuf-1) \n     || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))\n    ){\n      nBuf--;\n    }\n  }\n\n  /* Step 5b. */\n  if( nBuf>1 && aBuf[nBuf-1]=='l' \n   && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1) \n  ){\n    nBuf--;\n  }\n\n  return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);\n\n pass_through:\n  return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);\n}\n\n/*\n** Tokenize using the porter tokenizer.\n*/\nstatic int fts5PorterTokenize(\n  Fts5Tokenizer *pTokenizer,\n  void *pCtx,\n  int flags,\n  const char *pText, int nText,\n  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)\n){\n  PorterTokenizer *p = (PorterTokenizer*)pTokenizer;\n  PorterContext sCtx;\n  sCtx.xToken = xToken;\n  sCtx.pCtx = pCtx;\n  sCtx.aBuf = p->aBuf;\n  return p->tokenizer.xTokenize(\n      p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb\n  );\n}\n\n/*\n** Register all built-in tokenizers with FTS5.\n*/\nstatic int sqlite3Fts5TokenizerInit(fts5_api *pApi){\n  struct BuiltinTokenizer {\n    const char *zName;\n    fts5_tokenizer x;\n  } aBuiltin[] = {\n    { \"unicode61\", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},\n    { \"ascii\",     {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},\n    { \"porter\",    {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},\n  };\n  \n  int rc = SQLITE_OK;             /* Return code */\n  int i;                          /* To iterate through builtin functions */\n\n  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){\n    rc = pApi->xCreateTokenizer(pApi,\n        aBuiltin[i].zName,\n        (void*)pApi,\n        &aBuiltin[i].x,\n        0\n    );\n  }\n\n  return rc;\n}\n\n/*\n** 2012-05-25\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n*/\n\n/*\n** DO NOT EDIT THIS MACHINE GENERATED FILE.\n*/\n\n\n/* #include <assert.h> */\n\n\n\n/*\n** If the argument is a codepoint corresponding to a lowercase letter\n** in the ASCII range with a diacritic added, return the codepoint\n** of the ASCII letter only. For example, if passed 235 - \"LATIN\n** SMALL LETTER E WITH DIAERESIS\" - return 65 (\"LATIN SMALL LETTER\n** E\"). The resuls of passing a codepoint that corresponds to an\n** uppercase letter are undefined.\n*/\nstatic int fts5_remove_diacritic(int c, int bComplex){\n  unsigned short aDia[] = {\n        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, \n     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, \n     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, \n     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, \n     3456,  3696,  3712,  3728,  3744,  3766,  3832,  3896, \n     3912,  3928,  3944,  3968,  4008,  4040,  4056,  4106, \n     4138,  4170,  4202,  4234,  4266,  4296,  4312,  4344, \n     4408,  4424,  4442,  4472,  4488,  4504,  6148,  6198, \n     6264,  6280,  6360,  6429,  6505,  6529, 61448, 61468, \n    61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704, \n    61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914, \n    61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218, \n    62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554, \n    62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766, \n    62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118, \n    63182, 63242, 63274, 63310, 63368, 63390, \n  };\n#define HIBIT ((unsigned char)0x80)\n  unsigned char aChar[] = {\n    '\\0',      'a',       'c',       'e',       'i',       'n',       \n    'o',       'u',       'y',       'y',       'a',       'c',       \n    'd',       'e',       'e',       'g',       'h',       'i',       \n    'j',       'k',       'l',       'n',       'o',       'r',       \n    's',       't',       'u',       'u',       'w',       'y',       \n    'z',       'o',       'u',       'a',       'i',       'o',       \n    'u',       'u'|HIBIT, 'a'|HIBIT, 'g',       'k',       'o',       \n    'o'|HIBIT, 'j',       'g',       'n',       'a'|HIBIT, 'a',       \n    'e',       'i',       'o',       'r',       'u',       's',       \n    't',       'h',       'a',       'e',       'o'|HIBIT, 'o',       \n    'o'|HIBIT, 'y',       '\\0',      '\\0',      '\\0',      '\\0',      \n    '\\0',      '\\0',      '\\0',      '\\0',      'a',       'b',       \n    'c'|HIBIT, 'd',       'd',       'e'|HIBIT, 'e',       'e'|HIBIT, \n    'f',       'g',       'h',       'h',       'i',       'i'|HIBIT, \n    'k',       'l',       'l'|HIBIT, 'l',       'm',       'n',       \n    'o'|HIBIT, 'p',       'r',       'r'|HIBIT, 'r',       's',       \n    's'|HIBIT, 't',       'u',       'u'|HIBIT, 'v',       'w',       \n    'w',       'x',       'y',       'z',       'h',       't',       \n    'w',       'y',       'a',       'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT, \n    'e',       'e'|HIBIT, 'e'|HIBIT, 'i',       'o',       'o'|HIBIT, \n    'o'|HIBIT, 'o'|HIBIT, 'u',       'u'|HIBIT, 'u'|HIBIT, 'y',       \n  };\n\n  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;\n  int iRes = 0;\n  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;\n  int iLo = 0;\n  while( iHi>=iLo ){\n    int iTest = (iHi + iLo) / 2;\n    if( key >= aDia[iTest] ){\n      iRes = iTest;\n      iLo = iTest+1;\n    }else{\n      iHi = iTest-1;\n    }\n  }\n  assert( key>=aDia[iRes] );\n  if( bComplex==0 && (aChar[iRes] & 0x80) ) return c;\n  return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F);\n}\n\n\n/*\n** Return true if the argument interpreted as a unicode codepoint\n** is a diacritical modifier character.\n*/\nstatic int sqlite3Fts5UnicodeIsdiacritic(int c){\n  unsigned int mask0 = 0x08029FDF;\n  unsigned int mask1 = 0x000361F8;\n  if( c<768 || c>817 ) return 0;\n  return (c < 768+32) ?\n      (mask0 & ((unsigned int)1 << (c-768))) :\n      (mask1 & ((unsigned int)1 << (c-768-32)));\n}\n\n\n/*\n** Interpret the argument as a unicode codepoint. If the codepoint\n** is an upper case character that has a lower case equivalent,\n** return the codepoint corresponding to the lower case version.\n** Otherwise, return a copy of the argument.\n**\n** The results are undefined if the value passed to this function\n** is less than zero.\n*/\nstatic int sqlite3Fts5UnicodeFold(int c, int eRemoveDiacritic){\n  /* Each entry in the following array defines a rule for folding a range\n  ** of codepoints to lower case. The rule applies to a range of nRange\n  ** codepoints starting at codepoint iCode.\n  **\n  ** If the least significant bit in flags is clear, then the rule applies\n  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and\n  ** need to be folded). Or, if it is set, then the rule only applies to\n  ** every second codepoint in the range, starting with codepoint C.\n  **\n  ** The 7 most significant bits in flags are an index into the aiOff[]\n  ** array. If a specific codepoint C does require folding, then its lower\n  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).\n  **\n  ** The contents of this array are generated by parsing the CaseFolding.txt\n  ** file distributed as part of the \"Unicode Character Database\". See\n  ** http://www.unicode.org for details.\n  */\n  static const struct TableEntry {\n    unsigned short iCode;\n    unsigned char flags;\n    unsigned char nRange;\n  } aEntry[] = {\n    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},\n    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},\n    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},\n    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},\n    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},\n    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},\n    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},\n    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},\n    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},\n    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},\n    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},\n    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},\n    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},\n    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},\n    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},\n    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},\n    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},\n    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},\n    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},\n    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},\n    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},\n    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},\n    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},\n    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},\n    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},\n    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},\n    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},\n    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},\n    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},\n    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},\n    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},\n    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},\n    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},\n    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},\n    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},\n    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},\n    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},\n    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},\n    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},\n    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},\n    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},\n    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},\n    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},\n    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},\n    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},\n    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},\n    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},\n    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},\n    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},\n    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},\n    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},\n    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},\n    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},\n    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},\n    {65313, 14, 26},       \n  };\n  static const unsigned short aiOff[] = {\n   1,     2,     8,     15,    16,    26,    28,    32,    \n   37,    38,    40,    48,    63,    64,    69,    71,    \n   79,    80,    116,   202,   203,   205,   206,   207,   \n   209,   210,   211,   213,   214,   217,   218,   219,   \n   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721, \n   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, \n   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, \n   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, \n   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, \n   65514, 65521, 65527, 65528, 65529, \n  };\n\n  int ret = c;\n\n  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );\n\n  if( c<128 ){\n    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');\n  }else if( c<65536 ){\n    const struct TableEntry *p;\n    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;\n    int iLo = 0;\n    int iRes = -1;\n\n    assert( c>aEntry[0].iCode );\n    while( iHi>=iLo ){\n      int iTest = (iHi + iLo) / 2;\n      int cmp = (c - aEntry[iTest].iCode);\n      if( cmp>=0 ){\n        iRes = iTest;\n        iLo = iTest+1;\n      }else{\n        iHi = iTest-1;\n      }\n    }\n\n    assert( iRes>=0 && c>=aEntry[iRes].iCode );\n    p = &aEntry[iRes];\n    if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){\n      ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;\n      assert( ret>0 );\n    }\n\n    if( eRemoveDiacritic ){\n      ret = fts5_remove_diacritic(ret, eRemoveDiacritic==2);\n    }\n  }\n  \n  else if( c>=66560 && c<66600 ){\n    ret = c + 40;\n  }\n\n  return ret;\n}\n\n\nstatic int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){ \n  aArray[0] = 1;\n  switch( zCat[0] ){\n    case 'C':\n          switch( zCat[1] ){\n            case 'c': aArray[1] = 1; break;\n            case 'f': aArray[2] = 1; break;\n            case 'n': aArray[3] = 1; break;\n            case 's': aArray[4] = 1; break;\n            case 'o': aArray[31] = 1; break;\n            case '*': \n              aArray[1] = 1;\n              aArray[2] = 1;\n              aArray[3] = 1;\n              aArray[4] = 1;\n              aArray[31] = 1;\n              break;\n            default: return 1;          }\n          break;\n\n    case 'L':\n          switch( zCat[1] ){\n            case 'l': aArray[5] = 1; break;\n            case 'm': aArray[6] = 1; break;\n            case 'o': aArray[7] = 1; break;\n            case 't': aArray[8] = 1; break;\n            case 'u': aArray[9] = 1; break;\n            case 'C': aArray[30] = 1; break;\n            case '*': \n              aArray[5] = 1;\n              aArray[6] = 1;\n              aArray[7] = 1;\n              aArray[8] = 1;\n              aArray[9] = 1;\n              aArray[30] = 1;\n              break;\n            default: return 1;          }\n          break;\n\n    case 'M':\n          switch( zCat[1] ){\n            case 'c': aArray[10] = 1; break;\n            case 'e': aArray[11] = 1; break;\n            case 'n': aArray[12] = 1; break;\n            case '*': \n              aArray[10] = 1;\n              aArray[11] = 1;\n              aArray[12] = 1;\n              break;\n            default: return 1;          }\n          break;\n\n    case 'N':\n          switch( zCat[1] ){\n            case 'd': aArray[13] = 1; break;\n            case 'l': aArray[14] = 1; break;\n            case 'o': aArray[15] = 1; break;\n            case '*': \n              aArray[13] = 1;\n              aArray[14] = 1;\n              aArray[15] = 1;\n              break;\n            default: return 1;          }\n          break;\n\n    case 'P':\n          switch( zCat[1] ){\n            case 'c': aArray[16] = 1; break;\n            case 'd': aArray[17] = 1; break;\n            case 'e': aArray[18] = 1; break;\n            case 'f': aArray[19] = 1; break;\n            case 'i': aArray[20] = 1; break;\n            case 'o': aArray[21] = 1; break;\n            case 's': aArray[22] = 1; break;\n            case '*': \n              aArray[16] = 1;\n              aArray[17] = 1;\n              aArray[18] = 1;\n              aArray[19] = 1;\n              aArray[20] = 1;\n              aArray[21] = 1;\n              aArray[22] = 1;\n              break;\n            default: return 1;          }\n          break;\n\n    case 'S':\n          switch( zCat[1] ){\n            case 'c': aArray[23] = 1; break;\n            case 'k': aArray[24] = 1; break;\n            case 'm': aArray[25] = 1; break;\n            case 'o': aArray[26] = 1; break;\n            case '*': \n              aArray[23] = 1;\n              aArray[24] = 1;\n              aArray[25] = 1;\n              aArray[26] = 1;\n              break;\n            default: return 1;          }\n          break;\n\n    case 'Z':\n          switch( zCat[1] ){\n            case 'l': aArray[27] = 1; break;\n            case 'p': aArray[28] = 1; break;\n            case 's': aArray[29] = 1; break;\n            case '*': \n              aArray[27] = 1;\n              aArray[28] = 1;\n              aArray[29] = 1;\n              break;\n            default: return 1;          }\n          break;\n\n  }\n  return 0;\n}\n\nstatic u16 aFts5UnicodeBlock[] = {\n    0,     1471,  1753,  1760,  1760,  1760,  1760,  1760,  1760,  1760,  \n    1760,  1760,  1760,  1760,  1760,  1763,  1765,  \n  };\nstatic u16 aFts5UnicodeMap[] = {\n    0,     32,    33,    36,    37,    40,    41,    42,    43,    44,    \n    45,    46,    48,    58,    60,    63,    65,    91,    92,    93,    \n    94,    95,    96,    97,    123,   124,   125,   126,   127,   160,   \n    161,   162,   166,   167,   168,   169,   170,   171,   172,   173,   \n    174,   175,   176,   177,   178,   180,   181,   182,   184,   185,   \n    186,   187,   188,   191,   192,   215,   216,   223,   247,   248,   \n    256,   312,   313,   329,   330,   377,   383,   385,   387,   388,   \n    391,   394,   396,   398,   402,   403,   405,   406,   409,   412,   \n    414,   415,   417,   418,   423,   427,   428,   431,   434,   436,   \n    437,   440,   442,   443,   444,   446,   448,   452,   453,   454,   \n    455,   456,   457,   458,   459,   460,   461,   477,   478,   496,   \n    497,   498,   499,   500,   503,   505,   506,   564,   570,   572,   \n    573,   575,   577,   580,   583,   584,   592,   660,   661,   688,   \n    706,   710,   722,   736,   741,   748,   749,   750,   751,   768,   \n    880,   884,   885,   886,   890,   891,   894,   900,   902,   903,   \n    904,   908,   910,   912,   913,   931,   940,   975,   977,   978,   \n    981,   984,   1008,  1012,  1014,  1015,  1018,  1020,  1021,  1072,  \n    1120,  1154,  1155,  1160,  1162,  1217,  1231,  1232,  1329,  1369,  \n    1370,  1377,  1417,  1418,  1423,  1425,  1470,  1471,  1472,  1473,  \n    1475,  1476,  1478,  1479,  1488,  1520,  1523,  1536,  1542,  1545,  \n    1547,  1548,  1550,  1552,  1563,  1566,  1568,  1600,  1601,  1611,  \n    1632,  1642,  1646,  1648,  1649,  1748,  1749,  1750,  1757,  1758,  \n    1759,  1765,  1767,  1769,  1770,  1774,  1776,  1786,  1789,  1791,  \n    1792,  1807,  1808,  1809,  1810,  1840,  1869,  1958,  1969,  1984,  \n    1994,  2027,  2036,  2038,  2039,  2042,  2048,  2070,  2074,  2075,  \n    2084,  2085,  2088,  2089,  2096,  2112,  2137,  2142,  2208,  2210,  \n    2276,  2304,  2307,  2308,  2362,  2363,  2364,  2365,  2366,  2369,  \n    2377,  2381,  2382,  2384,  2385,  2392,  2402,  2404,  2406,  2416,  \n    2417,  2418,  2425,  2433,  2434,  2437,  2447,  2451,  2474,  2482,  \n    2486,  2492,  2493,  2494,  2497,  2503,  2507,  2509,  2510,  2519,  \n    2524,  2527,  2530,  2534,  2544,  2546,  2548,  2554,  2555,  2561,  \n    2563,  2565,  2575,  2579,  2602,  2610,  2613,  2616,  2620,  2622,  \n    2625,  2631,  2635,  2641,  2649,  2654,  2662,  2672,  2674,  2677,  \n    2689,  2691,  2693,  2703,  2707,  2730,  2738,  2741,  2748,  2749,  \n    2750,  2753,  2759,  2761,  2763,  2765,  2768,  2784,  2786,  2790,  \n    2800,  2801,  2817,  2818,  2821,  2831,  2835,  2858,  2866,  2869,  \n    2876,  2877,  2878,  2879,  2880,  2881,  2887,  2891,  2893,  2902,  \n    2903,  2908,  2911,  2914,  2918,  2928,  2929,  2930,  2946,  2947,  \n    2949,  2958,  2962,  2969,  2972,  2974,  2979,  2984,  2990,  3006,  \n    3008,  3009,  3014,  3018,  3021,  3024,  3031,  3046,  3056,  3059,  \n    3065,  3066,  3073,  3077,  3086,  3090,  3114,  3125,  3133,  3134,  \n    3137,  3142,  3146,  3157,  3160,  3168,  3170,  3174,  3192,  3199,  \n    3202,  3205,  3214,  3218,  3242,  3253,  3260,  3261,  3262,  3263,  \n    3264,  3270,  3271,  3274,  3276,  3285,  3294,  3296,  3298,  3302,  \n    3313,  3330,  3333,  3342,  3346,  3389,  3390,  3393,  3398,  3402,  \n    3405,  3406,  3415,  3424,  3426,  3430,  3440,  3449,  3450,  3458,  \n    3461,  3482,  3507,  3517,  3520,  3530,  3535,  3538,  3542,  3544,  \n    3570,  3572,  3585,  3633,  3634,  3636,  3647,  3648,  3654,  3655,  \n    3663,  3664,  3674,  3713,  3716,  3719,  3722,  3725,  3732,  3737,  \n    3745,  3749,  3751,  3754,  3757,  3761,  3762,  3764,  3771,  3773,  \n    3776,  3782,  3784,  3792,  3804,  3840,  3841,  3844,  3859,  3860,  \n    3861,  3864,  3866,  3872,  3882,  3892,  3893,  3894,  3895,  3896,  \n    3897,  3898,  3899,  3900,  3901,  3902,  3904,  3913,  3953,  3967,  \n    3968,  3973,  3974,  3976,  3981,  3993,  4030,  4038,  4039,  4046,  \n    4048,  4053,  4057,  4096,  4139,  4141,  4145,  4146,  4152,  4153,  \n    4155,  4157,  4159,  4160,  4170,  4176,  4182,  4184,  4186,  4190,  \n    4193,  4194,  4197,  4199,  4206,  4209,  4213,  4226,  4227,  4229,  \n    4231,  4237,  4238,  4239,  4240,  4250,  4253,  4254,  4256,  4295,  \n    4301,  4304,  4347,  4348,  4349,  4682,  4688,  4696,  4698,  4704,  \n    4746,  4752,  4786,  4792,  4800,  4802,  4808,  4824,  4882,  4888,  \n    4957,  4960,  4969,  4992,  5008,  5024,  5120,  5121,  5741,  5743,  \n    5760,  5761,  5787,  5788,  5792,  5867,  5870,  5888,  5902,  5906,  \n    5920,  5938,  5941,  5952,  5970,  5984,  5998,  6002,  6016,  6068,  \n    6070,  6071,  6078,  6086,  6087,  6089,  6100,  6103,  6104,  6107,  \n    6108,  6109,  6112,  6128,  6144,  6150,  6151,  6155,  6158,  6160,  \n    6176,  6211,  6212,  6272,  6313,  6314,  6320,  6400,  6432,  6435,  \n    6439,  6441,  6448,  6450,  6451,  6457,  6464,  6468,  6470,  6480,  \n    6512,  6528,  6576,  6593,  6600,  6608,  6618,  6622,  6656,  6679,  \n    6681,  6686,  6688,  6741,  6742,  6743,  6744,  6752,  6753,  6754,  \n    6755,  6757,  6765,  6771,  6783,  6784,  6800,  6816,  6823,  6824,  \n    6912,  6916,  6917,  6964,  6965,  6966,  6971,  6972,  6973,  6978,  \n    6979,  6981,  6992,  7002,  7009,  7019,  7028,  7040,  7042,  7043,  \n    7073,  7074,  7078,  7080,  7082,  7083,  7084,  7086,  7088,  7098,  \n    7142,  7143,  7144,  7146,  7149,  7150,  7151,  7154,  7164,  7168,  \n    7204,  7212,  7220,  7222,  7227,  7232,  7245,  7248,  7258,  7288,  \n    7294,  7360,  7376,  7379,  7380,  7393,  7394,  7401,  7405,  7406,  \n    7410,  7412,  7413,  7424,  7468,  7531,  7544,  7545,  7579,  7616,  \n    7676,  7680,  7830,  7838,  7936,  7944,  7952,  7960,  7968,  7976,  \n    7984,  7992,  8000,  8008,  8016,  8025,  8027,  8029,  8031,  8033,  \n    8040,  8048,  8064,  8072,  8080,  8088,  8096,  8104,  8112,  8118,  \n    8120,  8124,  8125,  8126,  8127,  8130,  8134,  8136,  8140,  8141,  \n    8144,  8150,  8152,  8157,  8160,  8168,  8173,  8178,  8182,  8184,  \n    8188,  8189,  8192,  8203,  8208,  8214,  8216,  8217,  8218,  8219,  \n    8221,  8222,  8223,  8224,  8232,  8233,  8234,  8239,  8240,  8249,  \n    8250,  8251,  8255,  8257,  8260,  8261,  8262,  8263,  8274,  8275,  \n    8276,  8277,  8287,  8288,  8298,  8304,  8305,  8308,  8314,  8317,  \n    8318,  8319,  8320,  8330,  8333,  8334,  8336,  8352,  8400,  8413,  \n    8417,  8418,  8421,  8448,  8450,  8451,  8455,  8456,  8458,  8459,  \n    8462,  8464,  8467,  8468,  8469,  8470,  8472,  8473,  8478,  8484,  \n    8485,  8486,  8487,  8488,  8489,  8490,  8494,  8495,  8496,  8500,  \n    8501,  8505,  8506,  8508,  8510,  8512,  8517,  8519,  8522,  8523,  \n    8524,  8526,  8527,  8528,  8544,  8579,  8581,  8585,  8592,  8597,  \n    8602,  8604,  8608,  8609,  8611,  8612,  8614,  8615,  8622,  8623,  \n    8654,  8656,  8658,  8659,  8660,  8661,  8692,  8960,  8968,  8972,  \n    8992,  8994,  9001,  9002,  9003,  9084,  9085,  9115,  9140,  9180,  \n    9186,  9216,  9280,  9312,  9372,  9450,  9472,  9655,  9656,  9665,  \n    9666,  9720,  9728,  9839,  9840,  9985,  10088, 10089, 10090, 10091, \n    10092, 10093, 10094, 10095, 10096, 10097, 10098, 10099, 10100, 10101, \n    10102, 10132, 10176, 10181, 10182, 10183, 10214, 10215, 10216, 10217, \n    10218, 10219, 10220, 10221, 10222, 10223, 10224, 10240, 10496, 10627, \n    10628, 10629, 10630, 10631, 10632, 10633, 10634, 10635, 10636, 10637, \n    10638, 10639, 10640, 10641, 10642, 10643, 10644, 10645, 10646, 10647, \n    10648, 10649, 10712, 10713, 10714, 10715, 10716, 10748, 10749, 10750, \n    11008, 11056, 11077, 11079, 11088, 11264, 11312, 11360, 11363, 11365, \n    11367, 11374, 11377, 11378, 11380, 11381, 11383, 11388, 11390, 11393, \n    11394, 11492, 11493, 11499, 11503, 11506, 11513, 11517, 11518, 11520, \n    11559, 11565, 11568, 11631, 11632, 11647, 11648, 11680, 11688, 11696, \n    11704, 11712, 11720, 11728, 11736, 11744, 11776, 11778, 11779, 11780, \n    11781, 11782, 11785, 11786, 11787, 11788, 11789, 11790, 11799, 11800, \n    11802, 11803, 11804, 11805, 11806, 11808, 11809, 11810, 11811, 11812, \n    11813, 11814, 11815, 11816, 11817, 11818, 11823, 11824, 11834, 11904, \n    11931, 12032, 12272, 12288, 12289, 12292, 12293, 12294, 12295, 12296, \n    12297, 12298, 12299, 12300, 12301, 12302, 12303, 12304, 12305, 12306, \n    12308, 12309, 12310, 12311, 12312, 12313, 12314, 12315, 12316, 12317, \n    12318, 12320, 12321, 12330, 12334, 12336, 12337, 12342, 12344, 12347, \n    12348, 12349, 12350, 12353, 12441, 12443, 12445, 12447, 12448, 12449, \n    12539, 12540, 12543, 12549, 12593, 12688, 12690, 12694, 12704, 12736, \n    12784, 12800, 12832, 12842, 12872, 12880, 12881, 12896, 12928, 12938, \n    12977, 12992, 13056, 13312, 19893, 19904, 19968, 40908, 40960, 40981, \n    40982, 42128, 42192, 42232, 42238, 42240, 42508, 42509, 42512, 42528, \n    42538, 42560, 42606, 42607, 42608, 42611, 42612, 42622, 42623, 42624, \n    42655, 42656, 42726, 42736, 42738, 42752, 42775, 42784, 42786, 42800, \n    42802, 42864, 42865, 42873, 42878, 42888, 42889, 42891, 42896, 42912, \n    43000, 43002, 43003, 43010, 43011, 43014, 43015, 43019, 43020, 43043, \n    43045, 43047, 43048, 43056, 43062, 43064, 43065, 43072, 43124, 43136, \n    43138, 43188, 43204, 43214, 43216, 43232, 43250, 43256, 43259, 43264, \n    43274, 43302, 43310, 43312, 43335, 43346, 43359, 43360, 43392, 43395, \n    43396, 43443, 43444, 43446, 43450, 43452, 43453, 43457, 43471, 43472, \n    43486, 43520, 43561, 43567, 43569, 43571, 43573, 43584, 43587, 43588, \n    43596, 43597, 43600, 43612, 43616, 43632, 43633, 43639, 43642, 43643, \n    43648, 43696, 43697, 43698, 43701, 43703, 43705, 43710, 43712, 43713, \n    43714, 43739, 43741, 43742, 43744, 43755, 43756, 43758, 43760, 43762, \n    43763, 43765, 43766, 43777, 43785, 43793, 43808, 43816, 43968, 44003, \n    44005, 44006, 44008, 44009, 44011, 44012, 44013, 44016, 44032, 55203, \n    55216, 55243, 55296, 56191, 56319, 57343, 57344, 63743, 63744, 64112, \n    64256, 64275, 64285, 64286, 64287, 64297, 64298, 64312, 64318, 64320, \n    64323, 64326, 64434, 64467, 64830, 64831, 64848, 64914, 65008, 65020, \n    65021, 65024, 65040, 65047, 65048, 65049, 65056, 65072, 65073, 65075, \n    65077, 65078, 65079, 65080, 65081, 65082, 65083, 65084, 65085, 65086, \n    65087, 65088, 65089, 65090, 65091, 65092, 65093, 65095, 65096, 65097, \n    65101, 65104, 65108, 65112, 65113, 65114, 65115, 65116, 65117, 65118, \n    65119, 65122, 65123, 65124, 65128, 65129, 65130, 65136, 65142, 65279, \n    65281, 65284, 65285, 65288, 65289, 65290, 65291, 65292, 65293, 65294, \n    65296, 65306, 65308, 65311, 65313, 65339, 65340, 65341, 65342, 65343, \n    65344, 65345, 65371, 65372, 65373, 65374, 65375, 65376, 65377, 65378, \n    65379, 65380, 65382, 65392, 65393, 65438, 65440, 65474, 65482, 65490, \n    65498, 65504, 65506, 65507, 65508, 65509, 65512, 65513, 65517, 65529, \n    65532, 0,     13,    40,    60,    63,    80,    128,   256,   263,   \n    311,   320,   373,   377,   394,   400,   464,   509,   640,   672,   \n    768,   800,   816,   833,   834,   842,   896,   927,   928,   968,   \n    976,   977,   1024,  1064,  1104,  1184,  2048,  2056,  2058,  2103,  \n    2108,  2111,  2135,  2136,  2304,  2326,  2335,  2336,  2367,  2432,  \n    2494,  2560,  2561,  2565,  2572,  2576,  2581,  2585,  2616,  2623,  \n    2624,  2640,  2656,  2685,  2687,  2816,  2873,  2880,  2904,  2912,  \n    2936,  3072,  3680,  4096,  4097,  4098,  4099,  4152,  4167,  4178,  \n    4198,  4224,  4226,  4227,  4272,  4275,  4279,  4281,  4283,  4285,  \n    4286,  4304,  4336,  4352,  4355,  4391,  4396,  4397,  4406,  4416,  \n    4480,  4482,  4483,  4531,  4534,  4543,  4545,  4549,  4560,  5760,  \n    5803,  5804,  5805,  5806,  5808,  5814,  5815,  5824,  8192,  9216,  \n    9328,  12288, 26624, 28416, 28496, 28497, 28559, 28563, 45056, 53248, \n    53504, 53545, 53605, 53607, 53610, 53613, 53619, 53627, 53635, 53637, \n    53644, 53674, 53678, 53760, 53826, 53829, 54016, 54112, 54272, 54298, \n    54324, 54350, 54358, 54376, 54402, 54428, 54430, 54434, 54437, 54441, \n    54446, 54454, 54459, 54461, 54469, 54480, 54506, 54532, 54535, 54541, \n    54550, 54558, 54584, 54587, 54592, 54598, 54602, 54610, 54636, 54662, \n    54688, 54714, 54740, 54766, 54792, 54818, 54844, 54870, 54896, 54922, \n    54952, 54977, 54978, 55003, 55004, 55010, 55035, 55036, 55061, 55062, \n    55068, 55093, 55094, 55119, 55120, 55126, 55151, 55152, 55177, 55178, \n    55184, 55209, 55210, 55235, 55236, 55242, 55246, 60928, 60933, 60961, \n    60964, 60967, 60969, 60980, 60985, 60987, 60994, 60999, 61001, 61003, \n    61005, 61009, 61012, 61015, 61017, 61019, 61021, 61023, 61025, 61028, \n    61031, 61036, 61044, 61049, 61054, 61056, 61067, 61089, 61093, 61099, \n    61168, 61440, 61488, 61600, 61617, 61633, 61649, 61696, 61712, 61744, \n    61808, 61926, 61968, 62016, 62032, 62208, 62256, 62263, 62336, 62368, \n    62406, 62432, 62464, 62528, 62530, 62713, 62720, 62784, 62800, 62971, \n    63045, 63104, 63232, 0,     42710, 42752, 46900, 46912, 47133, 63488, \n    1,     32,    256,   0,     65533, \n  };\nstatic u16 aFts5UnicodeData[] = {\n    1025,  61,    117,   55,    117,   54,    50,    53,    57,    53,    \n    49,    85,    333,   85,    121,   85,    841,   54,    53,    50,    \n    56,    48,    56,    837,   54,    57,    50,    57,    1057,  61,    \n    53,    151,   58,    53,    56,    58,    39,    52,    57,    34,    \n    58,    56,    58,    57,    79,    56,    37,    85,    56,    47,    \n    39,    51,    111,   53,    745,   57,    233,   773,   57,    261,   \n    1822,  37,    542,   37,    1534,  222,   69,    73,    37,    126,   \n    126,   73,    69,    137,   37,    73,    37,    105,   101,   73,    \n    37,    73,    37,    190,   158,   37,    126,   126,   73,    37,    \n    126,   94,    37,    39,    94,    69,    135,   41,    40,    37,    \n    41,    40,    37,    41,    40,    37,    542,   37,    606,   37,    \n    41,    40,    37,    126,   73,    37,    1886,  197,   73,    37,    \n    73,    69,    126,   105,   37,    286,   2181,  39,    869,   582,   \n    152,   390,   472,   166,   248,   38,    56,    38,    568,   3596,  \n    158,   38,    56,    94,    38,    101,   53,    88,    41,    53,    \n    105,   41,    73,    37,    553,   297,   1125,  94,    37,    105,   \n    101,   798,   133,   94,    57,    126,   94,    37,    1641,  1541,  \n    1118,  58,    172,   75,    1790,  478,   37,    2846,  1225,  38,    \n    213,   1253,  53,    49,    55,    1452,  49,    44,    53,    76,    \n    53,    76,    53,    44,    871,   103,   85,    162,   121,   85,    \n    55,    85,    90,    364,   53,    85,    1031,  38,    327,   684,   \n    333,   149,   71,    44,    3175,  53,    39,    236,   34,    58,    \n    204,   70,    76,    58,    140,   71,    333,   103,   90,    39,    \n    469,   34,    39,    44,    967,   876,   2855,  364,   39,    333,   \n    1063,  300,   70,    58,    117,   38,    711,   140,   38,    300,   \n    38,    108,   38,    172,   501,   807,   108,   53,    39,    359,   \n    876,   108,   42,    1735,  44,    42,    44,    39,    106,   268,   \n    138,   44,    74,    39,    236,   327,   76,    85,    333,   53,    \n    38,    199,   231,   44,    74,    263,   71,    711,   231,   39,    \n    135,   44,    39,    106,   140,   74,    74,    44,    39,    42,    \n    71,    103,   76,    333,   71,    87,    207,   58,    55,    76,    \n    42,    199,   71,    711,   231,   71,    71,    71,    44,    106,   \n    76,    76,    108,   44,    135,   39,    333,   76,    103,   44,    \n    76,    42,    295,   103,   711,   231,   71,    167,   44,    39,    \n    106,   172,   76,    42,    74,    44,    39,    71,    76,    333,   \n    53,    55,    44,    74,    263,   71,    711,   231,   71,    167,   \n    44,    39,    42,    44,    42,    140,   74,    74,    44,    44,    \n    42,    71,    103,   76,    333,   58,    39,    207,   44,    39,    \n    199,   103,   135,   71,    39,    71,    71,    103,   391,   74,    \n    44,    74,    106,   106,   44,    39,    42,    333,   111,   218,   \n    55,    58,    106,   263,   103,   743,   327,   167,   39,    108,   \n    138,   108,   140,   76,    71,    71,    76,    333,   239,   58,    \n    74,    263,   103,   743,   327,   167,   44,    39,    42,    44,    \n    170,   44,    74,    74,    76,    74,    39,    71,    76,    333,   \n    71,    74,    263,   103,   1319,  39,    106,   140,   106,   106,   \n    44,    39,    42,    71,    76,    333,   207,   58,    199,   74,    \n    583,   775,   295,   39,    231,   44,    106,   108,   44,    266,   \n    74,    53,    1543,  44,    71,    236,   55,    199,   38,    268,   \n    53,    333,   85,    71,    39,    71,    39,    39,    135,   231,   \n    103,   39,    39,    71,    135,   44,    71,    204,   76,    39,    \n    167,   38,    204,   333,   135,   39,    122,   501,   58,    53,    \n    122,   76,    218,   333,   335,   58,    44,    58,    44,    58,    \n    44,    54,    50,    54,    50,    74,    263,   1159,  460,   42,    \n    172,   53,    76,    167,   364,   1164,  282,   44,    218,   90,    \n    181,   154,   85,    1383,  74,    140,   42,    204,   42,    76,    \n    74,    76,    39,    333,   213,   199,   74,    76,    135,   108,   \n    39,    106,   71,    234,   103,   140,   423,   44,    74,    76,    \n    202,   44,    39,    42,    333,   106,   44,    90,    1225,  41,    \n    41,    1383,  53,    38,    10631, 135,   231,   39,    135,   1319,  \n    135,   1063,  135,   231,   39,    135,   487,   1831,  135,   2151,  \n    108,   309,   655,   519,   346,   2727,  49,    19847, 85,    551,   \n    61,    839,   54,    50,    2407,  117,   110,   423,   135,   108,   \n    583,   108,   85,    583,   76,    423,   103,   76,    1671,  76,    \n    42,    236,   266,   44,    74,    364,   117,   38,    117,   55,    \n    39,    44,    333,   335,   213,   49,    149,   108,   61,    333,   \n    1127,  38,    1671,  1319,  44,    39,    2247,  935,   108,   138,   \n    76,    106,   74,    44,    202,   108,   58,    85,    333,   967,   \n    167,   1415,  554,   231,   74,    333,   47,    1114,  743,   76,    \n    106,   85,    1703,  42,    44,    42,    236,   44,    42,    44,    \n    74,    268,   202,   332,   44,    333,   333,   245,   38,    213,   \n    140,   42,    1511,  44,    42,    172,   42,    44,    170,   44,    \n    74,    231,   333,   245,   346,   300,   314,   76,    42,    967,   \n    42,    140,   74,    76,    42,    44,    74,    71,    333,   1415,  \n    44,    42,    76,    106,   44,    42,    108,   74,    149,   1159,  \n    266,   268,   74,    76,    181,   333,   103,   333,   967,   198,   \n    85,    277,   108,   53,    428,   42,    236,   135,   44,    135,   \n    74,    44,    71,    1413,  2022,  421,   38,    1093,  1190,  1260,  \n    140,   4830,  261,   3166,  261,   265,   197,   201,   261,   265,   \n    261,   265,   197,   201,   261,   41,    41,    41,    94,    229,   \n    265,   453,   261,   264,   261,   264,   261,   264,   165,   69,    \n    137,   40,    56,    37,    120,   101,   69,    137,   40,    120,   \n    133,   69,    137,   120,   261,   169,   120,   101,   69,    137,   \n    40,    88,    381,   162,   209,   85,    52,    51,    54,    84,    \n    51,    54,    52,    277,   59,    60,    162,   61,    309,   52,    \n    51,    149,   80,    117,   57,    54,    50,    373,   57,    53,    \n    48,    341,   61,    162,   194,   47,    38,    207,   121,   54,    \n    50,    38,    335,   121,   54,    50,    422,   855,   428,   139,   \n    44,    107,   396,   90,    41,    154,   41,    90,    37,    105,   \n    69,    105,   37,    58,    41,    90,    57,    169,   218,   41,    \n    58,    41,    58,    41,    58,    137,   58,    37,    137,   37,    \n    135,   37,    90,    69,    73,    185,   94,    101,   58,    57,    \n    90,    37,    58,    527,   1134,  94,    142,   47,    185,   186,   \n    89,    154,   57,    90,    57,    90,    57,    250,   57,    1018,  \n    89,    90,    57,    58,    57,    1018,  8601,  282,   153,   666,   \n    89,    250,   54,    50,    2618,  57,    986,   825,   1306,  217,   \n    602,   1274,  378,   1935,  2522,  719,   5882,  57,    314,   57,    \n    1754,  281,   3578,  57,    4634,  3322,  54,    50,    54,    50,    \n    54,    50,    54,    50,    54,    50,    54,    50,    54,    50,    \n    975,   1434,  185,   54,    50,    1017,  54,    50,    54,    50,    \n    54,    50,    54,    50,    54,    50,    537,   8218,  4217,  54,    \n    50,    54,    50,    54,    50,    54,    50,    54,    50,    54,    \n    50,    54,    50,    54,    50,    54,    50,    54,    50,    54,    \n    50,    2041,  54,    50,    54,    50,    1049,  54,    50,    8281,  \n    1562,  697,   90,    217,   346,   1513,  1509,  126,   73,    69,    \n    254,   105,   37,    94,    37,    94,    165,   70,    105,   37,    \n    3166,  37,    218,   158,   108,   94,    149,   47,    85,    1221,  \n    37,    37,    1799,  38,    53,    44,    743,   231,   231,   231,   \n    231,   231,   231,   231,   231,   1036,  85,    52,    51,    52,    \n    51,    117,   52,    51,    53,    52,    51,    309,   49,    85,    \n    49,    53,    52,    51,    85,    52,    51,    54,    50,    54,    \n    50,    54,    50,    54,    50,    181,   38,    341,   81,    858,   \n    2874,  6874,  410,   61,    117,   58,    38,    39,    46,    54,    \n    50,    54,    50,    54,    50,    54,    50,    54,    50,    90,    \n    54,    50,    54,    50,    54,    50,    54,    50,    49,    54,    \n    82,    58,    302,   140,   74,    49,    166,   90,    110,   38,    \n    39,    53,    90,    2759,  76,    88,    70,    39,    49,    2887,  \n    53,    102,   39,    1319,  3015,  90,    143,   346,   871,   1178,  \n    519,   1018,  335,   986,   271,   58,    495,   1050,  335,   1274,  \n    495,   2042,  8218,  39,    39,    2074,  39,    39,    679,   38,    \n    36583, 1786,  1287,  198,   85,    8583,  38,    117,   519,   333,   \n    71,    1502,  39,    44,    107,   53,    332,   53,    38,    798,   \n    44,    2247,  334,   76,    213,   760,   294,   88,    478,   69,    \n    2014,  38,    261,   190,   350,   38,    88,    158,   158,   382,   \n    70,    37,    231,   44,    103,   44,    135,   44,    743,   74,    \n    76,    42,    154,   207,   90,    55,    58,    1671,  149,   74,    \n    1607,  522,   44,    85,    333,   588,   199,   117,   39,    333,   \n    903,   268,   85,    743,   364,   74,    53,    935,   108,   42,    \n    1511,  44,    74,    140,   74,    44,    138,   437,   38,    333,   \n    85,    1319,  204,   74,    76,    74,    76,    103,   44,    263,   \n    44,    42,    333,   149,   519,   38,    199,   122,   39,    42,    \n    1543,  44,    39,    108,   71,    76,    167,   76,    39,    44,    \n    39,    71,    38,    85,    359,   42,    76,    74,    85,    39,    \n    70,    42,    44,    199,   199,   199,   231,   231,   1127,  74,    \n    44,    74,    44,    74,    53,    42,    44,    333,   39,    39,    \n    743,   1575,  36,    68,    68,    36,    63,    63,    11719, 3399,  \n    229,   165,   39,    44,    327,   57,    423,   167,   39,    71,    \n    71,    3463,  536,   11623, 54,    50,    2055,  1735,  391,   55,    \n    58,    524,   245,   54,    50,    53,    236,   53,    81,    80,    \n    54,    50,    54,    50,    54,    50,    54,    50,    54,    50,    \n    54,    50,    54,    50,    54,    50,    85,    54,    50,    149,   \n    112,   117,   149,   49,    54,    50,    54,    50,    54,    50,    \n    117,   57,    49,    121,   53,    55,    85,    167,   4327,  34,    \n    117,   55,    117,   54,    50,    53,    57,    53,    49,    85,    \n    333,   85,    121,   85,    841,   54,    53,    50,    56,    48,    \n    56,    837,   54,    57,    50,    57,    54,    50,    53,    54,    \n    50,    85,    327,   38,    1447,  70,    999,   199,   199,   199,   \n    103,   87,    57,    56,    58,    87,    58,    153,   90,    98,    \n    90,    391,   839,   615,   71,    487,   455,   3943,  117,   1455,  \n    314,   1710,  143,   570,   47,    410,   1466,  44,    935,   1575,  \n    999,   143,   551,   46,    263,   46,    967,   53,    1159,  263,   \n    53,    174,   1289,  1285,  2503,  333,   199,   39,    1415,  71,    \n    39,    743,   53,    271,   711,   207,   53,    839,   53,    1799,  \n    71,    39,    108,   76,    140,   135,   103,   871,   108,   44,    \n    271,   309,   935,   79,    53,    1735,  245,   711,   271,   615,   \n    271,   2343,  1007,  42,    44,    42,    1703,  492,   245,   655,   \n    333,   76,    42,    1447,  106,   140,   74,    76,    85,    34,    \n    149,   807,   333,   108,   1159,  172,   42,    268,   333,   149,   \n    76,    42,    1543,  106,   300,   74,    135,   149,   333,   1383,  \n    44,    42,    44,    74,    204,   42,    44,    333,   28135, 3182,  \n    149,   34279, 18215, 2215,  39,    1482,  140,   422,   71,    7898,  \n    1274,  1946,  74,    108,   122,   202,   258,   268,   90,    236,   \n    986,   140,   1562,  2138,  108,   58,    2810,  591,   841,   837,   \n    841,   229,   581,   841,   837,   41,    73,    41,    73,    137,   \n    265,   133,   37,    229,   357,   841,   837,   73,    137,   265,   \n    233,   837,   73,    137,   169,   41,    233,   837,   841,   837,   \n    841,   837,   841,   837,   841,   837,   841,   837,   841,   901,   \n    809,   57,    805,   57,    197,   809,   57,    805,   57,    197,   \n    809,   57,    805,   57,    197,   809,   57,    805,   57,    197,   \n    809,   57,    805,   57,    197,   94,    1613,  135,   871,   71,    \n    39,    39,    327,   135,   39,    39,    39,    39,    39,    39,    \n    103,   71,    39,    39,    39,    39,    39,    39,    71,    39,    \n    135,   231,   135,   135,   39,    327,   551,   103,   167,   551,   \n    89,    1434,  3226,  506,   474,   506,   506,   367,   1018,  1946,  \n    1402,  954,   1402,  314,   90,    1082,  218,   2266,  666,   1210,  \n    186,   570,   2042,  58,    5850,  154,   2010,  154,   794,   2266,  \n    378,   2266,  3738,  39,    39,    39,    39,    39,    39,    17351, \n    34,    3074,  7692,  63,    63,    \n  };\n\nstatic int sqlite3Fts5UnicodeCategory(u32 iCode) { \n  int iRes = -1;\n  int iHi;\n  int iLo;\n  int ret;\n  u16 iKey;\n\n  if( iCode>=(1<<20) ){\n    return 0;\n  }\n  iLo = aFts5UnicodeBlock[(iCode>>16)];\n  iHi = aFts5UnicodeBlock[1+(iCode>>16)];\n  iKey = (iCode & 0xFFFF);\n  while( iHi>iLo ){\n    int iTest = (iHi + iLo) / 2;\n    assert( iTest>=iLo && iTest<iHi );\n    if( iKey>=aFts5UnicodeMap[iTest] ){\n      iRes = iTest;\n      iLo = iTest+1;\n    }else{\n      iHi = iTest;\n    }\n  }\n\n  if( iRes<0 ) return 0;\n  if( iKey>=(aFts5UnicodeMap[iRes]+(aFts5UnicodeData[iRes]>>5)) ) return 0;\n  ret = aFts5UnicodeData[iRes] & 0x1F;\n  if( ret!=30 ) return ret;\n  return ((iKey - aFts5UnicodeMap[iRes]) & 0x01) ? 5 : 9;\n}\n\nstatic void sqlite3Fts5UnicodeAscii(u8 *aArray, u8 *aAscii){\n  int i = 0;\n  int iTbl = 0;\n  while( i<128 ){\n    int bToken = aArray[ aFts5UnicodeData[iTbl] & 0x1F ];\n    int n = (aFts5UnicodeData[iTbl] >> 5) + i;\n    for(; i<128 && i<n; i++){\n      aAscii[i] = (u8)bToken;\n    }\n    iTbl++;\n  }\n}\n\n/*\n** 2015 May 30\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** Routines for varint serialization and deserialization.\n*/\n\n\n/* #include \"fts5Int.h\" */\n\n/*\n** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.\n** Except, this version does handle the single byte case that the core\n** version depends on being handled before its function is called.\n*/\nstatic int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){\n  u32 a,b;\n\n  /* The 1-byte case. Overwhelmingly the most common. */\n  a = *p;\n  /* a: p0 (unmasked) */\n  if (!(a&0x80))\n  {\n    /* Values between 0 and 127 */\n    *v = a;\n    return 1;\n  }\n\n  /* The 2-byte case */\n  p++;\n  b = *p;\n  /* b: p1 (unmasked) */\n  if (!(b&0x80))\n  {\n    /* Values between 128 and 16383 */\n    a &= 0x7f;\n    a = a<<7;\n    *v = a | b;\n    return 2;\n  }\n\n  /* The 3-byte case */\n  p++;\n  a = a<<14;\n  a |= *p;\n  /* a: p0<<14 | p2 (unmasked) */\n  if (!(a&0x80))\n  {\n    /* Values between 16384 and 2097151 */\n    a &= (0x7f<<14)|(0x7f);\n    b &= 0x7f;\n    b = b<<7;\n    *v = a | b;\n    return 3;\n  }\n\n  /* A 32-bit varint is used to store size information in btrees.\n  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.\n  ** A 3-byte varint is sufficient, for example, to record the size\n  ** of a 1048569-byte BLOB or string.\n  **\n  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very\n  ** rare larger cases can be handled by the slower 64-bit varint\n  ** routine.\n  */\n  {\n    u64 v64;\n    u8 n;\n    p -= 2;\n    n = sqlite3Fts5GetVarint(p, &v64);\n    *v = ((u32)v64) & 0x7FFFFFFF;\n    assert( n>3 && n<=9 );\n    return n;\n  }\n}\n\n\n/*\n** Bitmasks used by sqlite3GetVarint().  These precomputed constants\n** are defined here rather than simply putting the constant expressions\n** inline in order to work around bugs in the RVT compiler.\n**\n** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f\n**\n** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0\n*/\n#define SLOT_2_0     0x001fc07f\n#define SLOT_4_2_0   0xf01fc07f\n\n/*\n** Read a 64-bit variable-length integer from memory starting at p[0].\n** Return the number of bytes read.  The value is stored in *v.\n*/\nstatic u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){\n  u32 a,b,s;\n\n  a = *p;\n  /* a: p0 (unmasked) */\n  if (!(a&0x80))\n  {\n    *v = a;\n    return 1;\n  }\n\n  p++;\n  b = *p;\n  /* b: p1 (unmasked) */\n  if (!(b&0x80))\n  {\n    a &= 0x7f;\n    a = a<<7;\n    a |= b;\n    *v = a;\n    return 2;\n  }\n\n  /* Verify that constants are precomputed correctly */\n  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );\n  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );\n\n  p++;\n  a = a<<14;\n  a |= *p;\n  /* a: p0<<14 | p2 (unmasked) */\n  if (!(a&0x80))\n  {\n    a &= SLOT_2_0;\n    b &= 0x7f;\n    b = b<<7;\n    a |= b;\n    *v = a;\n    return 3;\n  }\n\n  /* CSE1 from below */\n  a &= SLOT_2_0;\n  p++;\n  b = b<<14;\n  b |= *p;\n  /* b: p1<<14 | p3 (unmasked) */\n  if (!(b&0x80))\n  {\n    b &= SLOT_2_0;\n    /* moved CSE1 up */\n    /* a &= (0x7f<<14)|(0x7f); */\n    a = a<<7;\n    a |= b;\n    *v = a;\n    return 4;\n  }\n\n  /* a: p0<<14 | p2 (masked) */\n  /* b: p1<<14 | p3 (unmasked) */\n  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */\n  /* moved CSE1 up */\n  /* a &= (0x7f<<14)|(0x7f); */\n  b &= SLOT_2_0;\n  s = a;\n  /* s: p0<<14 | p2 (masked) */\n\n  p++;\n  a = a<<14;\n  a |= *p;\n  /* a: p0<<28 | p2<<14 | p4 (unmasked) */\n  if (!(a&0x80))\n  {\n    /* we can skip these cause they were (effectively) done above in calc'ing s */\n    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */\n    /* b &= (0x7f<<14)|(0x7f); */\n    b = b<<7;\n    a |= b;\n    s = s>>18;\n    *v = ((u64)s)<<32 | a;\n    return 5;\n  }\n\n  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */\n  s = s<<7;\n  s |= b;\n  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */\n\n  p++;\n  b = b<<14;\n  b |= *p;\n  /* b: p1<<28 | p3<<14 | p5 (unmasked) */\n  if (!(b&0x80))\n  {\n    /* we can skip this cause it was (effectively) done above in calc'ing s */\n    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */\n    a &= SLOT_2_0;\n    a = a<<7;\n    a |= b;\n    s = s>>18;\n    *v = ((u64)s)<<32 | a;\n    return 6;\n  }\n\n  p++;\n  a = a<<14;\n  a |= *p;\n  /* a: p2<<28 | p4<<14 | p6 (unmasked) */\n  if (!(a&0x80))\n  {\n    a &= SLOT_4_2_0;\n    b &= SLOT_2_0;\n    b = b<<7;\n    a |= b;\n    s = s>>11;\n    *v = ((u64)s)<<32 | a;\n    return 7;\n  }\n\n  /* CSE2 from below */\n  a &= SLOT_2_0;\n  p++;\n  b = b<<14;\n  b |= *p;\n  /* b: p3<<28 | p5<<14 | p7 (unmasked) */\n  if (!(b&0x80))\n  {\n    b &= SLOT_4_2_0;\n    /* moved CSE2 up */\n    /* a &= (0x7f<<14)|(0x7f); */\n    a = a<<7;\n    a |= b;\n    s = s>>4;\n    *v = ((u64)s)<<32 | a;\n    return 8;\n  }\n\n  p++;\n  a = a<<15;\n  a |= *p;\n  /* a: p4<<29 | p6<<15 | p8 (unmasked) */\n\n  /* moved CSE2 up */\n  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */\n  b &= SLOT_2_0;\n  b = b<<8;\n  a |= b;\n\n  s = s<<4;\n  b = p[-4];\n  b &= 0x7f;\n  b = b>>3;\n  s |= b;\n\n  *v = ((u64)s)<<32 | a;\n\n  return 9;\n}\n\n/*\n** The variable-length integer encoding is as follows:\n**\n** KEY:\n**         A = 0xxxxxxx    7 bits of data and one flag bit\n**         B = 1xxxxxxx    7 bits of data and one flag bit\n**         C = xxxxxxxx    8 bits of data\n**\n**  7 bits - A\n** 14 bits - BA\n** 21 bits - BBA\n** 28 bits - BBBA\n** 35 bits - BBBBA\n** 42 bits - BBBBBA\n** 49 bits - BBBBBBA\n** 56 bits - BBBBBBBA\n** 64 bits - BBBBBBBBC\n*/\n\n#ifdef SQLITE_NOINLINE\n# define FTS5_NOINLINE SQLITE_NOINLINE\n#else\n# define FTS5_NOINLINE\n#endif\n\n/*\n** Write a 64-bit variable-length integer to memory starting at p[0].\n** The length of data write will be between 1 and 9 bytes.  The number\n** of bytes written is returned.\n**\n** A variable-length integer consists of the lower 7 bits of each byte\n** for all bytes that have the 8th bit set and one byte with the 8th\n** bit clear.  Except, if we get to the 9th byte, it stores the full\n** 8 bits and is the last byte.\n*/\nstatic int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){\n  int i, j, n;\n  u8 buf[10];\n  if( v & (((u64)0xff000000)<<32) ){\n    p[8] = (u8)v;\n    v >>= 8;\n    for(i=7; i>=0; i--){\n      p[i] = (u8)((v & 0x7f) | 0x80);\n      v >>= 7;\n    }\n    return 9;\n  }    \n  n = 0;\n  do{\n    buf[n++] = (u8)((v & 0x7f) | 0x80);\n    v >>= 7;\n  }while( v!=0 );\n  buf[0] &= 0x7f;\n  assert( n<=9 );\n  for(i=0, j=n-1; j>=0; j--, i++){\n    p[i] = buf[j];\n  }\n  return n;\n}\n\nstatic int sqlite3Fts5PutVarint(unsigned char *p, u64 v){\n  if( v<=0x7f ){\n    p[0] = v&0x7f;\n    return 1;\n  }\n  if( v<=0x3fff ){\n    p[0] = ((v>>7)&0x7f)|0x80;\n    p[1] = v&0x7f;\n    return 2;\n  }\n  return fts5PutVarint64(p,v);\n}\n\n\nstatic int sqlite3Fts5GetVarintLen(u32 iVal){\n#if 0\n  if( iVal<(1 << 7 ) ) return 1;\n#endif\n  assert( iVal>=(1 << 7) );\n  if( iVal<(1 << 14) ) return 2;\n  if( iVal<(1 << 21) ) return 3;\n  if( iVal<(1 << 28) ) return 4;\n  return 5;\n}\n\n/*\n** 2015 May 08\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This is an SQLite virtual table module implementing direct access to an\n** existing FTS5 index. The module may create several different types of \n** tables:\n**\n** col:\n**     CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));\n**\n**   One row for each term/column combination. The value of $doc is set to\n**   the number of fts5 rows that contain at least one instance of term\n**   $term within column $col. Field $cnt is set to the total number of \n**   instances of term $term in column $col (in any row of the fts5 table). \n**\n** row:\n**     CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));\n**\n**   One row for each term in the database. The value of $doc is set to\n**   the number of fts5 rows that contain at least one instance of term\n**   $term. Field $cnt is set to the total number of instances of term \n**   $term in the database.\n**\n** instance:\n**     CREATE TABLE vocab(term, doc, col, offset, PRIMARY KEY(<all-fields>));\n**\n**   One row for each term instance in the database. \n*/\n\n\n/* #include \"fts5Int.h\" */\n\n\ntypedef struct Fts5VocabTable Fts5VocabTable;\ntypedef struct Fts5VocabCursor Fts5VocabCursor;\n\nstruct Fts5VocabTable {\n  sqlite3_vtab base;\n  char *zFts5Tbl;                 /* Name of fts5 table */\n  char *zFts5Db;                  /* Db containing fts5 table */\n  sqlite3 *db;                    /* Database handle */\n  Fts5Global *pGlobal;            /* FTS5 global object for this database */\n  int eType;                      /* FTS5_VOCAB_COL, ROW or INSTANCE */\n  unsigned bBusy;                 /* True if busy */\n};\n\nstruct Fts5VocabCursor {\n  sqlite3_vtab_cursor base;\n  sqlite3_stmt *pStmt;            /* Statement holding lock on pIndex */\n  Fts5Table *pFts5;               /* Associated FTS5 table */\n\n  int bEof;                       /* True if this cursor is at EOF */\n  Fts5IndexIter *pIter;           /* Term/rowid iterator object */\n\n  int nLeTerm;                    /* Size of zLeTerm in bytes */\n  char *zLeTerm;                  /* (term <= $zLeTerm) paramater, or NULL */\n\n  /* These are used by 'col' tables only */\n  int iCol;\n  i64 *aCnt;\n  i64 *aDoc;\n\n  /* Output values used by all tables. */\n  i64 rowid;                      /* This table's current rowid value */\n  Fts5Buffer term;                /* Current value of 'term' column */\n\n  /* Output values Used by 'instance' tables only */\n  i64 iInstPos;\n  int iInstOff;\n};\n\n#define FTS5_VOCAB_COL      0\n#define FTS5_VOCAB_ROW      1\n#define FTS5_VOCAB_INSTANCE 2\n\n#define FTS5_VOCAB_COL_SCHEMA  \"term, col, doc, cnt\"\n#define FTS5_VOCAB_ROW_SCHEMA  \"term, doc, cnt\"\n#define FTS5_VOCAB_INST_SCHEMA \"term, doc, col, offset\"\n\n/*\n** Bits for the mask used as the idxNum value by xBestIndex/xFilter.\n*/\n#define FTS5_VOCAB_TERM_EQ 0x01\n#define FTS5_VOCAB_TERM_GE 0x02\n#define FTS5_VOCAB_TERM_LE 0x04\n\n\n/*\n** Translate a string containing an fts5vocab table type to an \n** FTS5_VOCAB_XXX constant. If successful, set *peType to the output\n** value and return SQLITE_OK. Otherwise, set *pzErr to an error message\n** and return SQLITE_ERROR.\n*/\nstatic int fts5VocabTableType(const char *zType, char **pzErr, int *peType){\n  int rc = SQLITE_OK;\n  char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);\n  if( rc==SQLITE_OK ){\n    sqlite3Fts5Dequote(zCopy);\n    if( sqlite3_stricmp(zCopy, \"col\")==0 ){\n      *peType = FTS5_VOCAB_COL;\n    }else\n\n    if( sqlite3_stricmp(zCopy, \"row\")==0 ){\n      *peType = FTS5_VOCAB_ROW;\n    }else\n    if( sqlite3_stricmp(zCopy, \"instance\")==0 ){\n      *peType = FTS5_VOCAB_INSTANCE;\n    }else\n    {\n      *pzErr = sqlite3_mprintf(\"fts5vocab: unknown table type: %Q\", zCopy);\n      rc = SQLITE_ERROR;\n    }\n    sqlite3_free(zCopy);\n  }\n\n  return rc;\n}\n\n\n/*\n** The xDisconnect() virtual table method.\n*/\nstatic int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){\n  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;\n  sqlite3_free(pTab);\n  return SQLITE_OK;\n}\n\n/*\n** The xDestroy() virtual table method.\n*/\nstatic int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){\n  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;\n  sqlite3_free(pTab);\n  return SQLITE_OK;\n}\n\n/*\n** This function is the implementation of both the xConnect and xCreate\n** methods of the FTS3 virtual table.\n**\n** The argv[] array contains the following:\n**\n**   argv[0]   -> module name  (\"fts5vocab\")\n**   argv[1]   -> database name\n**   argv[2]   -> table name\n**\n** then:\n**\n**   argv[3]   -> name of fts5 table\n**   argv[4]   -> type of fts5vocab table\n**\n** or, for tables in the TEMP schema only.\n**\n**   argv[3]   -> name of fts5 tables database\n**   argv[4]   -> name of fts5 table\n**   argv[5]   -> type of fts5vocab table\n*/\nstatic int fts5VocabInitVtab(\n  sqlite3 *db,                    /* The SQLite database connection */\n  void *pAux,                     /* Pointer to Fts5Global object */\n  int argc,                       /* Number of elements in argv array */\n  const char * const *argv,       /* xCreate/xConnect argument array */\n  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */\n  char **pzErr                    /* Write any error message here */\n){\n  const char *azSchema[] = { \n    \"CREATE TABlE vocab(\" FTS5_VOCAB_COL_SCHEMA  \")\", \n    \"CREATE TABlE vocab(\" FTS5_VOCAB_ROW_SCHEMA  \")\",\n    \"CREATE TABlE vocab(\" FTS5_VOCAB_INST_SCHEMA \")\"\n  };\n\n  Fts5VocabTable *pRet = 0;\n  int rc = SQLITE_OK;             /* Return code */\n  int bDb;\n\n  bDb = (argc==6 && strlen(argv[1])==4 && memcmp(\"temp\", argv[1], 4)==0);\n\n  if( argc!=5 && bDb==0 ){\n    *pzErr = sqlite3_mprintf(\"wrong number of vtable arguments\");\n    rc = SQLITE_ERROR;\n  }else{\n    int nByte;                      /* Bytes of space to allocate */\n    const char *zDb = bDb ? argv[3] : argv[1];\n    const char *zTab = bDb ? argv[4] : argv[3];\n    const char *zType = bDb ? argv[5] : argv[4];\n    int nDb = (int)strlen(zDb)+1; \n    int nTab = (int)strlen(zTab)+1;\n    int eType = 0;\n    \n    rc = fts5VocabTableType(zType, pzErr, &eType);\n    if( rc==SQLITE_OK ){\n      assert( eType>=0 && eType<ArraySize(azSchema) );\n      rc = sqlite3_declare_vtab(db, azSchema[eType]);\n    }\n\n    nByte = sizeof(Fts5VocabTable) + nDb + nTab;\n    pRet = sqlite3Fts5MallocZero(&rc, nByte);\n    if( pRet ){\n      pRet->pGlobal = (Fts5Global*)pAux;\n      pRet->eType = eType;\n      pRet->db = db;\n      pRet->zFts5Tbl = (char*)&pRet[1];\n      pRet->zFts5Db = &pRet->zFts5Tbl[nTab];\n      memcpy(pRet->zFts5Tbl, zTab, nTab);\n      memcpy(pRet->zFts5Db, zDb, nDb);\n      sqlite3Fts5Dequote(pRet->zFts5Tbl);\n      sqlite3Fts5Dequote(pRet->zFts5Db);\n    }\n  }\n\n  *ppVTab = (sqlite3_vtab*)pRet;\n  return rc;\n}\n\n\n/*\n** The xConnect() and xCreate() methods for the virtual table. All the\n** work is done in function fts5VocabInitVtab().\n*/\nstatic int fts5VocabConnectMethod(\n  sqlite3 *db,                    /* Database connection */\n  void *pAux,                     /* Pointer to tokenizer hash table */\n  int argc,                       /* Number of elements in argv array */\n  const char * const *argv,       /* xCreate/xConnect argument array */\n  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */\n  char **pzErr                    /* OUT: sqlite3_malloc'd error message */\n){\n  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);\n}\nstatic int fts5VocabCreateMethod(\n  sqlite3 *db,                    /* Database connection */\n  void *pAux,                     /* Pointer to tokenizer hash table */\n  int argc,                       /* Number of elements in argv array */\n  const char * const *argv,       /* xCreate/xConnect argument array */\n  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */\n  char **pzErr                    /* OUT: sqlite3_malloc'd error message */\n){\n  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);\n}\n\n/* \n** Implementation of the xBestIndex method.\n**\n** Only constraints of the form:\n**\n**     term <= ?\n**     term == ?\n**     term >= ?\n**\n** are interpreted. Less-than and less-than-or-equal are treated \n** identically, as are greater-than and greater-than-or-equal.\n*/\nstatic int fts5VocabBestIndexMethod(\n  sqlite3_vtab *pUnused,\n  sqlite3_index_info *pInfo\n){\n  int i;\n  int iTermEq = -1;\n  int iTermGe = -1;\n  int iTermLe = -1;\n  int idxNum = 0;\n  int nArg = 0;\n\n  UNUSED_PARAM(pUnused);\n\n  for(i=0; i<pInfo->nConstraint; i++){\n    struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];\n    if( p->usable==0 ) continue;\n    if( p->iColumn==0 ){          /* term column */\n      if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;\n      if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;\n      if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;\n      if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;\n      if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;\n    }\n  }\n\n  if( iTermEq>=0 ){\n    idxNum |= FTS5_VOCAB_TERM_EQ;\n    pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;\n    pInfo->estimatedCost = 100;\n  }else{\n    pInfo->estimatedCost = 1000000;\n    if( iTermGe>=0 ){\n      idxNum |= FTS5_VOCAB_TERM_GE;\n      pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;\n      pInfo->estimatedCost = pInfo->estimatedCost / 2;\n    }\n    if( iTermLe>=0 ){\n      idxNum |= FTS5_VOCAB_TERM_LE;\n      pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;\n      pInfo->estimatedCost = pInfo->estimatedCost / 2;\n    }\n  }\n\n  /* This virtual table always delivers results in ascending order of\n  ** the \"term\" column (column 0). So if the user has requested this\n  ** specifically - \"ORDER BY term\" or \"ORDER BY term ASC\" - set the\n  ** sqlite3_index_info.orderByConsumed flag to tell the core the results\n  ** are already in sorted order.  */\n  if( pInfo->nOrderBy==1 \n   && pInfo->aOrderBy[0].iColumn==0 \n   && pInfo->aOrderBy[0].desc==0\n  ){\n    pInfo->orderByConsumed = 1;\n  }\n\n  pInfo->idxNum = idxNum;\n  return SQLITE_OK;\n}\n\n/*\n** Implementation of xOpen method.\n*/\nstatic int fts5VocabOpenMethod(\n  sqlite3_vtab *pVTab, \n  sqlite3_vtab_cursor **ppCsr\n){\n  Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;\n  Fts5Table *pFts5 = 0;\n  Fts5VocabCursor *pCsr = 0;\n  int rc = SQLITE_OK;\n  sqlite3_stmt *pStmt = 0;\n  char *zSql = 0;\n\n  if( pTab->bBusy ){\n    pVTab->zErrMsg = sqlite3_mprintf(\n       \"recursive definition for %s.%s\", pTab->zFts5Db, pTab->zFts5Tbl\n    );\n    return SQLITE_ERROR;\n  }\n  zSql = sqlite3Fts5Mprintf(&rc,\n      \"SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'\",\n      pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl\n  );\n  if( zSql ){\n    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);\n  }\n  sqlite3_free(zSql);\n  assert( rc==SQLITE_OK || pStmt==0 );\n  if( rc==SQLITE_ERROR ) rc = SQLITE_OK;\n\n  pTab->bBusy = 1;\n  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){\n    i64 iId = sqlite3_column_int64(pStmt, 0);\n    pFts5 = sqlite3Fts5TableFromCsrid(pTab->pGlobal, iId);\n  }\n  pTab->bBusy = 0;\n\n  if( rc==SQLITE_OK ){\n    if( pFts5==0 ){\n      rc = sqlite3_finalize(pStmt);\n      pStmt = 0;\n      if( rc==SQLITE_OK ){\n        pVTab->zErrMsg = sqlite3_mprintf(\n            \"no such fts5 table: %s.%s\", pTab->zFts5Db, pTab->zFts5Tbl\n            );\n        rc = SQLITE_ERROR;\n      }\n    }else{\n      rc = sqlite3Fts5FlushToDisk(pFts5);\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    int nByte = pFts5->pConfig->nCol * sizeof(i64)*2 + sizeof(Fts5VocabCursor);\n    pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);\n  }\n\n  if( pCsr ){\n    pCsr->pFts5 = pFts5;\n    pCsr->pStmt = pStmt;\n    pCsr->aCnt = (i64*)&pCsr[1];\n    pCsr->aDoc = &pCsr->aCnt[pFts5->pConfig->nCol];\n  }else{\n    sqlite3_finalize(pStmt);\n  }\n\n  *ppCsr = (sqlite3_vtab_cursor*)pCsr;\n  return rc;\n}\n\nstatic void fts5VocabResetCursor(Fts5VocabCursor *pCsr){\n  pCsr->rowid = 0;\n  sqlite3Fts5IterClose(pCsr->pIter);\n  pCsr->pIter = 0;\n  sqlite3_free(pCsr->zLeTerm);\n  pCsr->nLeTerm = -1;\n  pCsr->zLeTerm = 0;\n  pCsr->bEof = 0;\n}\n\n/*\n** Close the cursor.  For additional information see the documentation\n** on the xClose method of the virtual table interface.\n*/\nstatic int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){\n  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;\n  fts5VocabResetCursor(pCsr);\n  sqlite3Fts5BufferFree(&pCsr->term);\n  sqlite3_finalize(pCsr->pStmt);\n  sqlite3_free(pCsr);\n  return SQLITE_OK;\n}\n\nstatic int fts5VocabInstanceNewTerm(Fts5VocabCursor *pCsr){\n  int rc = SQLITE_OK;\n  \n  if( sqlite3Fts5IterEof(pCsr->pIter) ){\n    pCsr->bEof = 1;\n  }else{\n    const char *zTerm;\n    int nTerm;\n    zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);\n    if( pCsr->nLeTerm>=0 ){\n      int nCmp = MIN(nTerm, pCsr->nLeTerm);\n      int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);\n      if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){\n        pCsr->bEof = 1;\n      }\n    }\n\n    sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);\n  }\n  return rc;\n}\n\nstatic int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){\n  int eDetail = pCsr->pFts5->pConfig->eDetail;\n  int rc = SQLITE_OK;\n  Fts5IndexIter *pIter = pCsr->pIter;\n  i64 *pp = &pCsr->iInstPos;\n  int *po = &pCsr->iInstOff;\n  \n  assert( sqlite3Fts5IterEof(pIter)==0 );\n  assert( pCsr->bEof==0 );\n  while( eDetail==FTS5_DETAIL_NONE\n      || sqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp) \n  ){\n    pCsr->iInstPos = 0;\n    pCsr->iInstOff = 0;\n\n    rc = sqlite3Fts5IterNextScan(pCsr->pIter);\n    if( rc==SQLITE_OK ){\n      rc = fts5VocabInstanceNewTerm(pCsr);\n      if( pCsr->bEof || eDetail==FTS5_DETAIL_NONE ) break;\n    }\n    if( rc ){\n      pCsr->bEof = 1;\n      break;\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Advance the cursor to the next row in the table.\n*/\nstatic int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){\n  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;\n  Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;\n  int rc = SQLITE_OK;\n  int nCol = pCsr->pFts5->pConfig->nCol;\n\n  pCsr->rowid++;\n\n  if( pTab->eType==FTS5_VOCAB_INSTANCE ){\n    return fts5VocabInstanceNext(pCsr);\n  }\n\n  if( pTab->eType==FTS5_VOCAB_COL ){\n    for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){\n      if( pCsr->aDoc[pCsr->iCol] ) break;\n    }\n  }\n\n  if( pTab->eType!=FTS5_VOCAB_COL || pCsr->iCol>=nCol ){\n    if( sqlite3Fts5IterEof(pCsr->pIter) ){\n      pCsr->bEof = 1;\n    }else{\n      const char *zTerm;\n      int nTerm;\n\n      zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);\n      assert( nTerm>=0 );\n      if( pCsr->nLeTerm>=0 ){\n        int nCmp = MIN(nTerm, pCsr->nLeTerm);\n        int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);\n        if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){\n          pCsr->bEof = 1;\n          return SQLITE_OK;\n        }\n      }\n\n      sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);\n      memset(pCsr->aCnt, 0, nCol * sizeof(i64));\n      memset(pCsr->aDoc, 0, nCol * sizeof(i64));\n      pCsr->iCol = 0;\n\n      assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );\n      while( rc==SQLITE_OK ){\n        int eDetail = pCsr->pFts5->pConfig->eDetail;\n        const u8 *pPos; int nPos;   /* Position list */\n        i64 iPos = 0;               /* 64-bit position read from poslist */\n        int iOff = 0;               /* Current offset within position list */\n\n        pPos = pCsr->pIter->pData;\n        nPos = pCsr->pIter->nData;\n\n        switch( pTab->eType ){\n          case FTS5_VOCAB_ROW:\n            if( eDetail==FTS5_DETAIL_FULL ){\n              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){\n                pCsr->aCnt[0]++;\n              }\n            }\n            pCsr->aDoc[0]++;\n            break;\n\n          case FTS5_VOCAB_COL:\n            if( eDetail==FTS5_DETAIL_FULL ){\n              int iCol = -1;\n              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){\n                int ii = FTS5_POS2COLUMN(iPos);\n                if( iCol!=ii ){\n                  if( ii>=nCol ){\n                    rc = FTS5_CORRUPT;\n                    break;\n                  }\n                  pCsr->aDoc[ii]++;\n                  iCol = ii;\n                }\n                pCsr->aCnt[ii]++;\n              }\n            }else if( eDetail==FTS5_DETAIL_COLUMNS ){\n              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){\n                assert_nc( iPos>=0 && iPos<nCol );\n                if( iPos>=nCol ){\n                  rc = FTS5_CORRUPT;\n                  break;\n                }\n                pCsr->aDoc[iPos]++;\n              }\n            }else{\n              assert( eDetail==FTS5_DETAIL_NONE );\n              pCsr->aDoc[0]++;\n            }\n            break;\n\n          default:\n            assert( pTab->eType==FTS5_VOCAB_INSTANCE );\n            break;\n        }\n\n        if( rc==SQLITE_OK ){\n          rc = sqlite3Fts5IterNextScan(pCsr->pIter);\n        }\n        if( pTab->eType==FTS5_VOCAB_INSTANCE ) break;\n\n        if( rc==SQLITE_OK ){\n          zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);\n          if( nTerm!=pCsr->term.n \n          || (nTerm>0 && memcmp(zTerm, pCsr->term.p, nTerm)) \n          ){\n            break;\n          }\n          if( sqlite3Fts5IterEof(pCsr->pIter) ) break;\n        }\n      }\n    }\n  }\n\n  if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){\n    for(/* noop */; pCsr->iCol<nCol && pCsr->aDoc[pCsr->iCol]==0; pCsr->iCol++);\n    if( pCsr->iCol==nCol ){\n      rc = FTS5_CORRUPT;\n    }\n  }\n  return rc;\n}\n\n/*\n** This is the xFilter implementation for the virtual table.\n*/\nstatic int fts5VocabFilterMethod(\n  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */\n  int idxNum,                     /* Strategy index */\n  const char *zUnused,            /* Unused */\n  int nUnused,                    /* Number of elements in apVal */\n  sqlite3_value **apVal           /* Arguments for the indexing scheme */\n){\n  Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;\n  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;\n  int eType = pTab->eType;\n  int rc = SQLITE_OK;\n\n  int iVal = 0;\n  int f = FTS5INDEX_QUERY_SCAN;\n  const char *zTerm = 0;\n  int nTerm = 0;\n\n  sqlite3_value *pEq = 0;\n  sqlite3_value *pGe = 0;\n  sqlite3_value *pLe = 0;\n\n  UNUSED_PARAM2(zUnused, nUnused);\n\n  fts5VocabResetCursor(pCsr);\n  if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];\n  if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];\n  if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];\n\n  if( pEq ){\n    zTerm = (const char *)sqlite3_value_text(pEq);\n    nTerm = sqlite3_value_bytes(pEq);\n    f = 0;\n  }else{\n    if( pGe ){\n      zTerm = (const char *)sqlite3_value_text(pGe);\n      nTerm = sqlite3_value_bytes(pGe);\n    }\n    if( pLe ){\n      const char *zCopy = (const char *)sqlite3_value_text(pLe);\n      if( zCopy==0 ) zCopy = \"\";\n      pCsr->nLeTerm = sqlite3_value_bytes(pLe);\n      pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);\n      if( pCsr->zLeTerm==0 ){\n        rc = SQLITE_NOMEM;\n      }else{\n        memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);\n      }\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    Fts5Index *pIndex = pCsr->pFts5->pIndex;\n    rc = sqlite3Fts5IndexQuery(pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);\n  }\n  if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){\n    rc = fts5VocabInstanceNewTerm(pCsr);\n  }\n  if( rc==SQLITE_OK && !pCsr->bEof \n   && (eType!=FTS5_VOCAB_INSTANCE \n    || pCsr->pFts5->pConfig->eDetail!=FTS5_DETAIL_NONE)\n  ){\n    rc = fts5VocabNextMethod(pCursor);\n  }\n\n  return rc;\n}\n\n/* \n** This is the xEof method of the virtual table. SQLite calls this \n** routine to find out if it has reached the end of a result set.\n*/\nstatic int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){\n  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;\n  return pCsr->bEof;\n}\n\nstatic int fts5VocabColumnMethod(\n  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */\n  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */\n  int iCol                        /* Index of column to read value from */\n){\n  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;\n  int eDetail = pCsr->pFts5->pConfig->eDetail;\n  int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;\n  i64 iVal = 0;\n\n  if( iCol==0 ){\n    sqlite3_result_text(\n        pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT\n    );\n  }else if( eType==FTS5_VOCAB_COL ){\n    assert( iCol==1 || iCol==2 || iCol==3 );\n    if( iCol==1 ){\n      if( eDetail!=FTS5_DETAIL_NONE ){\n        const char *z = pCsr->pFts5->pConfig->azCol[pCsr->iCol];\n        sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);\n      }\n    }else if( iCol==2 ){\n      iVal = pCsr->aDoc[pCsr->iCol];\n    }else{\n      iVal = pCsr->aCnt[pCsr->iCol];\n    }\n  }else if( eType==FTS5_VOCAB_ROW ){\n    assert( iCol==1 || iCol==2 );\n    if( iCol==1 ){\n      iVal = pCsr->aDoc[0];\n    }else{\n      iVal = pCsr->aCnt[0];\n    }\n  }else{\n    assert( eType==FTS5_VOCAB_INSTANCE );\n    switch( iCol ){\n      case 1:\n        sqlite3_result_int64(pCtx, pCsr->pIter->iRowid);\n        break;\n      case 2: {\n        int ii = -1;\n        if( eDetail==FTS5_DETAIL_FULL ){\n          ii = FTS5_POS2COLUMN(pCsr->iInstPos);\n        }else if( eDetail==FTS5_DETAIL_COLUMNS ){\n          ii = (int)pCsr->iInstPos;\n        }\n        if( ii>=0 && ii<pCsr->pFts5->pConfig->nCol ){\n          const char *z = pCsr->pFts5->pConfig->azCol[ii];\n          sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);\n        }\n        break;\n      }\n      default: {\n        assert( iCol==3 );\n        if( eDetail==FTS5_DETAIL_FULL ){\n          int ii = FTS5_POS2OFFSET(pCsr->iInstPos);\n          sqlite3_result_int(pCtx, ii);\n        }\n        break;\n      }\n    }\n  }\n\n  if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);\n  return SQLITE_OK;\n}\n\n/* \n** This is the xRowid method. The SQLite core calls this routine to\n** retrieve the rowid for the current row of the result set. The\n** rowid should be written to *pRowid.\n*/\nstatic int fts5VocabRowidMethod(\n  sqlite3_vtab_cursor *pCursor, \n  sqlite_int64 *pRowid\n){\n  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;\n  *pRowid = pCsr->rowid;\n  return SQLITE_OK;\n}\n\nstatic int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){\n  static const sqlite3_module fts5Vocab = {\n    /* iVersion      */ 2,\n    /* xCreate       */ fts5VocabCreateMethod,\n    /* xConnect      */ fts5VocabConnectMethod,\n    /* xBestIndex    */ fts5VocabBestIndexMethod,\n    /* xDisconnect   */ fts5VocabDisconnectMethod,\n    /* xDestroy      */ fts5VocabDestroyMethod,\n    /* xOpen         */ fts5VocabOpenMethod,\n    /* xClose        */ fts5VocabCloseMethod,\n    /* xFilter       */ fts5VocabFilterMethod,\n    /* xNext         */ fts5VocabNextMethod,\n    /* xEof          */ fts5VocabEofMethod,\n    /* xColumn       */ fts5VocabColumnMethod,\n    /* xRowid        */ fts5VocabRowidMethod,\n    /* xUpdate       */ 0,\n    /* xBegin        */ 0,\n    /* xSync         */ 0,\n    /* xCommit       */ 0,\n    /* xRollback     */ 0,\n    /* xFindFunction */ 0,\n    /* xRename       */ 0,\n    /* xSavepoint    */ 0,\n    /* xRelease      */ 0,\n    /* xRollbackTo   */ 0,\n    /* xShadowName   */ 0\n  };\n  void *p = (void*)pGlobal;\n\n  return sqlite3_create_module_v2(db, \"fts5vocab\", &fts5Vocab, p, 0);\n}\n\n\n    \n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */\n\n/************** End of fts5.c ************************************************/\n/************** Begin file stmt.c ********************************************/\n/*\n** 2017-05-31\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file demonstrates an eponymous virtual table that returns information\n** about all prepared statements for the database connection.\n**\n** Usage example:\n**\n**     .load ./stmt\n**     .mode line\n**     .header on\n**     SELECT * FROM stmt;\n*/\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB)\n#if !defined(SQLITEINT_H)\n/* #include \"sqlite3ext.h\" */\n#endif\nSQLITE_EXTENSION_INIT1\n/* #include <assert.h> */\n/* #include <string.h> */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n\n/* stmt_vtab is a subclass of sqlite3_vtab which will\n** serve as the underlying representation of a stmt virtual table\n*/\ntypedef struct stmt_vtab stmt_vtab;\nstruct stmt_vtab {\n  sqlite3_vtab base;  /* Base class - must be first */\n  sqlite3 *db;        /* Database connection for this stmt vtab */\n};\n\n/* stmt_cursor is a subclass of sqlite3_vtab_cursor which will\n** serve as the underlying representation of a cursor that scans\n** over rows of the result\n*/\ntypedef struct stmt_cursor stmt_cursor;\nstruct stmt_cursor {\n  sqlite3_vtab_cursor base;  /* Base class - must be first */\n  sqlite3 *db;               /* Database connection for this cursor */\n  sqlite3_stmt *pStmt;       /* Statement cursor is currently pointing at */\n  sqlite3_int64 iRowid;      /* The rowid */\n};\n\n/*\n** The stmtConnect() method is invoked to create a new\n** stmt_vtab that describes the stmt virtual table.\n**\n** Think of this routine as the constructor for stmt_vtab objects.\n**\n** All this routine needs to do is:\n**\n**    (1) Allocate the stmt_vtab object and initialize all fields.\n**\n**    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the\n**        result set of queries against stmt will look like.\n*/\nstatic int stmtConnect(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  stmt_vtab *pNew;\n  int rc;\n\n/* Column numbers */\n#define STMT_COLUMN_SQL     0   /* SQL for the statement */\n#define STMT_COLUMN_NCOL    1   /* Number of result columns */\n#define STMT_COLUMN_RO      2   /* True if read-only */\n#define STMT_COLUMN_BUSY    3   /* True if currently busy */\n#define STMT_COLUMN_NSCAN   4   /* SQLITE_STMTSTATUS_FULLSCAN_STEP */\n#define STMT_COLUMN_NSORT   5   /* SQLITE_STMTSTATUS_SORT */\n#define STMT_COLUMN_NAIDX   6   /* SQLITE_STMTSTATUS_AUTOINDEX */\n#define STMT_COLUMN_NSTEP   7   /* SQLITE_STMTSTATUS_VM_STEP */\n#define STMT_COLUMN_REPREP  8   /* SQLITE_STMTSTATUS_REPREPARE */\n#define STMT_COLUMN_RUN     9   /* SQLITE_STMTSTATUS_RUN */\n#define STMT_COLUMN_MEM    10   /* SQLITE_STMTSTATUS_MEMUSED */\n\n\n  rc = sqlite3_declare_vtab(db,\n     \"CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep,\"\n                    \"reprep,run,mem)\");\n  if( rc==SQLITE_OK ){\n    pNew = sqlite3_malloc( sizeof(*pNew) );\n    *ppVtab = (sqlite3_vtab*)pNew;\n    if( pNew==0 ) return SQLITE_NOMEM;\n    memset(pNew, 0, sizeof(*pNew));\n    pNew->db = db;\n  }\n  return rc;\n}\n\n/*\n** This method is the destructor for stmt_cursor objects.\n*/\nstatic int stmtDisconnect(sqlite3_vtab *pVtab){\n  sqlite3_free(pVtab);\n  return SQLITE_OK;\n}\n\n/*\n** Constructor for a new stmt_cursor object.\n*/\nstatic int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){\n  stmt_cursor *pCur;\n  pCur = sqlite3_malloc( sizeof(*pCur) );\n  if( pCur==0 ) return SQLITE_NOMEM;\n  memset(pCur, 0, sizeof(*pCur));\n  pCur->db = ((stmt_vtab*)p)->db;\n  *ppCursor = &pCur->base;\n  return SQLITE_OK;\n}\n\n/*\n** Destructor for a stmt_cursor.\n*/\nstatic int stmtClose(sqlite3_vtab_cursor *cur){\n  sqlite3_free(cur);\n  return SQLITE_OK;\n}\n\n\n/*\n** Advance a stmt_cursor to its next row of output.\n*/\nstatic int stmtNext(sqlite3_vtab_cursor *cur){\n  stmt_cursor *pCur = (stmt_cursor*)cur;\n  pCur->iRowid++;\n  pCur->pStmt = sqlite3_next_stmt(pCur->db, pCur->pStmt);\n  return SQLITE_OK;\n}\n\n/*\n** Return values of columns for the row at which the stmt_cursor\n** is currently pointing.\n*/\nstatic int stmtColumn(\n  sqlite3_vtab_cursor *cur,   /* The cursor */\n  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */\n  int i                       /* Which column to return */\n){\n  stmt_cursor *pCur = (stmt_cursor*)cur;\n  switch( i ){\n    case STMT_COLUMN_SQL: {\n      sqlite3_result_text(ctx, sqlite3_sql(pCur->pStmt), -1, SQLITE_TRANSIENT);\n      break;\n    }\n    case STMT_COLUMN_NCOL: {\n      sqlite3_result_int(ctx, sqlite3_column_count(pCur->pStmt));\n      break;\n    }\n    case STMT_COLUMN_RO: {\n      sqlite3_result_int(ctx, sqlite3_stmt_readonly(pCur->pStmt));\n      break;\n    }\n    case STMT_COLUMN_BUSY: {\n      sqlite3_result_int(ctx, sqlite3_stmt_busy(pCur->pStmt));\n      break;\n    }\n    default: {\n      assert( i==STMT_COLUMN_MEM );\n      i = SQLITE_STMTSTATUS_MEMUSED + \n            STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP;\n      /* Fall thru */\n    }\n    case STMT_COLUMN_NSCAN:\n    case STMT_COLUMN_NSORT:\n    case STMT_COLUMN_NAIDX:\n    case STMT_COLUMN_NSTEP:\n    case STMT_COLUMN_REPREP:\n    case STMT_COLUMN_RUN: {\n      sqlite3_result_int(ctx, sqlite3_stmt_status(pCur->pStmt,\n                      i-STMT_COLUMN_NSCAN+SQLITE_STMTSTATUS_FULLSCAN_STEP, 0));\n      break;\n    }\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Return the rowid for the current row.  In this implementation, the\n** rowid is the same as the output value.\n*/\nstatic int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){\n  stmt_cursor *pCur = (stmt_cursor*)cur;\n  *pRowid = pCur->iRowid;\n  return SQLITE_OK;\n}\n\n/*\n** Return TRUE if the cursor has been moved off of the last\n** row of output.\n*/\nstatic int stmtEof(sqlite3_vtab_cursor *cur){\n  stmt_cursor *pCur = (stmt_cursor*)cur;\n  return pCur->pStmt==0;\n}\n\n/*\n** This method is called to \"rewind\" the stmt_cursor object back\n** to the first row of output.  This method is always called at least\n** once prior to any call to stmtColumn() or stmtRowid() or \n** stmtEof().\n*/\nstatic int stmtFilter(\n  sqlite3_vtab_cursor *pVtabCursor, \n  int idxNum, const char *idxStr,\n  int argc, sqlite3_value **argv\n){\n  stmt_cursor *pCur = (stmt_cursor *)pVtabCursor;\n  pCur->pStmt = 0;\n  pCur->iRowid = 0;\n  return stmtNext(pVtabCursor);\n}\n\n/*\n** SQLite will invoke this method one or more times while planning a query\n** that uses the stmt virtual table.  This routine needs to create\n** a query plan for each invocation and compute an estimated cost for that\n** plan.\n*/\nstatic int stmtBestIndex(\n  sqlite3_vtab *tab,\n  sqlite3_index_info *pIdxInfo\n){\n  pIdxInfo->estimatedCost = (double)500;\n  pIdxInfo->estimatedRows = 500;\n  return SQLITE_OK;\n}\n\n/*\n** This following structure defines all the methods for the \n** stmt virtual table.\n*/\nstatic sqlite3_module stmtModule = {\n  0,                         /* iVersion */\n  0,                         /* xCreate */\n  stmtConnect,               /* xConnect */\n  stmtBestIndex,             /* xBestIndex */\n  stmtDisconnect,            /* xDisconnect */\n  0,                         /* xDestroy */\n  stmtOpen,                  /* xOpen - open a cursor */\n  stmtClose,                 /* xClose - close a cursor */\n  stmtFilter,                /* xFilter - configure scan constraints */\n  stmtNext,                  /* xNext - advance a cursor */\n  stmtEof,                   /* xEof - check for end of scan */\n  stmtColumn,                /* xColumn - read data */\n  stmtRowid,                 /* xRowid - read data */\n  0,                         /* xUpdate */\n  0,                         /* xBegin */\n  0,                         /* xSync */\n  0,                         /* xCommit */\n  0,                         /* xRollback */\n  0,                         /* xFindMethod */\n  0,                         /* xRename */\n  0,                         /* xSavepoint */\n  0,                         /* xRelease */\n  0,                         /* xRollbackTo */\n  0,                         /* xShadowName */\n};\n\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\nSQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3 *db){\n  int rc = SQLITE_OK;\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  rc = sqlite3_create_module(db, \"sqlite_stmt\", &stmtModule, 0);\n#endif\n  return rc;\n}\n\n#ifndef SQLITE_CORE\n#ifdef _WIN32\n__declspec(dllexport)\n#endif\nSQLITE_API int sqlite3_stmt_init(\n  sqlite3 *db, \n  char **pzErrMsg, \n  const sqlite3_api_routines *pApi\n){\n  int rc = SQLITE_OK;\n  SQLITE_EXTENSION_INIT2(pApi);\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  rc = sqlite3StmtVtabInit(db);\n#endif\n  return rc;\n}\n#endif /* SQLITE_CORE */\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */\n\n/************** End of stmt.c ************************************************/\n#if __LINE__!=229781\n#undef SQLITE_SOURCE_ID\n#define SQLITE_SOURCE_ID      \"2020-06-18 14:00:33 7ebdfa80be8e8e73324b8d66b3460222eb74c7e9dfd655b48d6ca7e1933calt2\"\n#endif\n/* Return the source-id for this library */\nSQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }\n/************************** End of sqlite3.c ******************************/\n"
  },
  {
    "path": "jsb_build/sqlite3/sqlite-amalgamation-3320300/sqlite3.h",
    "content": "/*\n** 2001-09-15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This header file defines the interface that the SQLite library\n** presents to client programs.  If a C-function, structure, datatype,\n** or constant definition does not appear in this file, then it is\n** not a published API of SQLite, is subject to change without\n** notice, and should not be referenced by programs that use SQLite.\n**\n** Some of the definitions that are in this file are marked as\n** \"experimental\".  Experimental interfaces are normally new\n** features recently added to SQLite.  We do not anticipate changes\n** to experimental interfaces but reserve the right to make minor changes\n** if experience from use \"in the wild\" suggest such changes are prudent.\n**\n** The official C-language API documentation for SQLite is derived\n** from comments in this file.  This file is the authoritative source\n** on how SQLite interfaces are supposed to operate.\n**\n** The name of this file under configuration management is \"sqlite.h.in\".\n** The makefile makes some minor changes to this file (such as inserting\n** the version number) and changes its name to \"sqlite3.h\" as\n** part of the build process.\n*/\n#ifndef SQLITE3_H\n#define SQLITE3_H\n#include <stdarg.h>     /* Needed for the definition of va_list */\n\n/*\n** Make sure we can call this stuff from C++.\n*/\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\n/*\n** Provide the ability to override linkage features of the interface.\n*/\n#ifndef SQLITE_EXTERN\n# define SQLITE_EXTERN extern\n#endif\n#ifndef SQLITE_API\n# define SQLITE_API\n#endif\n#ifndef SQLITE_CDECL\n# define SQLITE_CDECL\n#endif\n#ifndef SQLITE_APICALL\n# define SQLITE_APICALL\n#endif\n#ifndef SQLITE_STDCALL\n# define SQLITE_STDCALL SQLITE_APICALL\n#endif\n#ifndef SQLITE_CALLBACK\n# define SQLITE_CALLBACK\n#endif\n#ifndef SQLITE_SYSAPI\n# define SQLITE_SYSAPI\n#endif\n\n/*\n** These no-op macros are used in front of interfaces to mark those\n** interfaces as either deprecated or experimental.  New applications\n** should not use deprecated interfaces - they are supported for backwards\n** compatibility only.  Application writers should be aware that\n** experimental interfaces are subject to change in point releases.\n**\n** These macros used to resolve to various kinds of compiler magic that\n** would generate warning messages when they were used.  But that\n** compiler magic ended up generating such a flurry of bug reports\n** that we have taken it all out and gone back to using simple\n** noop macros.\n*/\n#define SQLITE_DEPRECATED\n#define SQLITE_EXPERIMENTAL\n\n/*\n** Ensure these symbols were not defined by some previous header file.\n*/\n#ifdef SQLITE_VERSION\n# undef SQLITE_VERSION\n#endif\n#ifdef SQLITE_VERSION_NUMBER\n# undef SQLITE_VERSION_NUMBER\n#endif\n\n/*\n** CAPI3REF: Compile-Time Library Version Numbers\n**\n** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header\n** evaluates to a string literal that is the SQLite version in the\n** format \"X.Y.Z\" where X is the major version number (always 3 for\n** SQLite3) and Y is the minor version number and Z is the release number.)^\n** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer\n** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same\n** numbers used in [SQLITE_VERSION].)^\n** The SQLITE_VERSION_NUMBER for any given release of SQLite will also\n** be larger than the release from which it is derived.  Either Y will\n** be held constant and Z will be incremented or else Y will be incremented\n** and Z will be reset to zero.\n**\n** Since [version 3.6.18] ([dateof:3.6.18]), \n** SQLite source code has been stored in the\n** <a href=\"http://www.fossil-scm.org/\">Fossil configuration management\n** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to\n** a string which identifies a particular check-in of SQLite\n** within its configuration management system.  ^The SQLITE_SOURCE_ID\n** string contains the date and time of the check-in (UTC) and a SHA1\n** or SHA3-256 hash of the entire source tree.  If the source code has\n** been edited in any way since it was last checked in, then the last\n** four hexadecimal digits of the hash may be modified.\n**\n** See also: [sqlite3_libversion()],\n** [sqlite3_libversion_number()], [sqlite3_sourceid()],\n** [sqlite_version()] and [sqlite_source_id()].\n*/\n#define SQLITE_VERSION        \"3.32.3\"\n#define SQLITE_VERSION_NUMBER 3032003\n#define SQLITE_SOURCE_ID      \"2020-06-18 14:00:33 7ebdfa80be8e8e73324b8d66b3460222eb74c7e9dfd655b48d6ca7e1933cc8fd\"\n\n/*\n** CAPI3REF: Run-Time Library Version Numbers\n** KEYWORDS: sqlite3_version sqlite3_sourceid\n**\n** These interfaces provide the same information as the [SQLITE_VERSION],\n** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros\n** but are associated with the library instead of the header file.  ^(Cautious\n** programmers might include assert() statements in their application to\n** verify that values returned by these interfaces match the macros in\n** the header, and thus ensure that the application is\n** compiled with matching library and header files.\n**\n** <blockquote><pre>\n** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );\n** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );\n** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );\n** </pre></blockquote>)^\n**\n** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]\n** macro.  ^The sqlite3_libversion() function returns a pointer to the\n** to the sqlite3_version[] string constant.  The sqlite3_libversion()\n** function is provided for use in DLLs since DLL users usually do not have\n** direct access to string constants within the DLL.  ^The\n** sqlite3_libversion_number() function returns an integer equal to\n** [SQLITE_VERSION_NUMBER].  ^(The sqlite3_sourceid() function returns \n** a pointer to a string constant whose value is the same as the \n** [SQLITE_SOURCE_ID] C preprocessor macro.  Except if SQLite is built\n** using an edited copy of [the amalgamation], then the last four characters\n** of the hash might be different from [SQLITE_SOURCE_ID].)^\n**\n** See also: [sqlite_version()] and [sqlite_source_id()].\n*/\nSQLITE_API SQLITE_EXTERN const char sqlite3_version[];\nSQLITE_API const char *sqlite3_libversion(void);\nSQLITE_API const char *sqlite3_sourceid(void);\nSQLITE_API int sqlite3_libversion_number(void);\n\n/*\n** CAPI3REF: Run-Time Library Compilation Options Diagnostics\n**\n** ^The sqlite3_compileoption_used() function returns 0 or 1 \n** indicating whether the specified option was defined at \n** compile time.  ^The SQLITE_ prefix may be omitted from the \n** option name passed to sqlite3_compileoption_used().  \n**\n** ^The sqlite3_compileoption_get() function allows iterating\n** over the list of options that were defined at compile time by\n** returning the N-th compile time option string.  ^If N is out of range,\n** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ \n** prefix is omitted from any strings returned by \n** sqlite3_compileoption_get().\n**\n** ^Support for the diagnostic functions sqlite3_compileoption_used()\n** and sqlite3_compileoption_get() may be omitted by specifying the \n** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.\n**\n** See also: SQL functions [sqlite_compileoption_used()] and\n** [sqlite_compileoption_get()] and the [compile_options pragma].\n*/\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\nSQLITE_API int sqlite3_compileoption_used(const char *zOptName);\nSQLITE_API const char *sqlite3_compileoption_get(int N);\n#else\n# define sqlite3_compileoption_used(X) 0\n# define sqlite3_compileoption_get(X)  ((void*)0)\n#endif\n\n/*\n** CAPI3REF: Test To See If The Library Is Threadsafe\n**\n** ^The sqlite3_threadsafe() function returns zero if and only if\n** SQLite was compiled with mutexing code omitted due to the\n** [SQLITE_THREADSAFE] compile-time option being set to 0.\n**\n** SQLite can be compiled with or without mutexes.  When\n** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes\n** are enabled and SQLite is threadsafe.  When the\n** [SQLITE_THREADSAFE] macro is 0, \n** the mutexes are omitted.  Without the mutexes, it is not safe\n** to use SQLite concurrently from more than one thread.\n**\n** Enabling mutexes incurs a measurable performance penalty.\n** So if speed is of utmost importance, it makes sense to disable\n** the mutexes.  But for maximum safety, mutexes should be enabled.\n** ^The default behavior is for mutexes to be enabled.\n**\n** This interface can be used by an application to make sure that the\n** version of SQLite that it is linking against was compiled with\n** the desired setting of the [SQLITE_THREADSAFE] macro.\n**\n** This interface only reports on the compile-time mutex setting\n** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with\n** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but\n** can be fully or partially disabled using a call to [sqlite3_config()]\n** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],\n** or [SQLITE_CONFIG_SERIALIZED].  ^(The return value of the\n** sqlite3_threadsafe() function shows only the compile-time setting of\n** thread safety, not any run-time changes to that setting made by\n** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()\n** is unchanged by calls to sqlite3_config().)^\n**\n** See the [threading mode] documentation for additional information.\n*/\nSQLITE_API int sqlite3_threadsafe(void);\n\n/*\n** CAPI3REF: Database Connection Handle\n** KEYWORDS: {database connection} {database connections}\n**\n** Each open SQLite database is represented by a pointer to an instance of\n** the opaque structure named \"sqlite3\".  It is useful to think of an sqlite3\n** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and\n** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]\n** and [sqlite3_close_v2()] are its destructors.  There are many other\n** interfaces (such as\n** [sqlite3_prepare_v2()], [sqlite3_create_function()], and\n** [sqlite3_busy_timeout()] to name but three) that are methods on an\n** sqlite3 object.\n*/\ntypedef struct sqlite3 sqlite3;\n\n/*\n** CAPI3REF: 64-Bit Integer Types\n** KEYWORDS: sqlite_int64 sqlite_uint64\n**\n** Because there is no cross-platform way to specify 64-bit integer types\n** SQLite includes typedefs for 64-bit signed and unsigned integers.\n**\n** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.\n** The sqlite_int64 and sqlite_uint64 types are supported for backwards\n** compatibility only.\n**\n** ^The sqlite3_int64 and sqlite_int64 types can store integer values\n** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The\n** sqlite3_uint64 and sqlite_uint64 types can store integer values \n** between 0 and +18446744073709551615 inclusive.\n*/\n#ifdef SQLITE_INT64_TYPE\n  typedef SQLITE_INT64_TYPE sqlite_int64;\n# ifdef SQLITE_UINT64_TYPE\n    typedef SQLITE_UINT64_TYPE sqlite_uint64;\n# else  \n    typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;\n# endif\n#elif defined(_MSC_VER) || defined(__BORLANDC__)\n  typedef __int64 sqlite_int64;\n  typedef unsigned __int64 sqlite_uint64;\n#else\n  typedef long long int sqlite_int64;\n  typedef unsigned long long int sqlite_uint64;\n#endif\ntypedef sqlite_int64 sqlite3_int64;\ntypedef sqlite_uint64 sqlite3_uint64;\n\n/*\n** If compiling for a processor that lacks floating point support,\n** substitute integer for floating-point.\n*/\n#ifdef SQLITE_OMIT_FLOATING_POINT\n# define double sqlite3_int64\n#endif\n\n/*\n** CAPI3REF: Closing A Database Connection\n** DESTRUCTOR: sqlite3\n**\n** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors\n** for the [sqlite3] object.\n** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if\n** the [sqlite3] object is successfully destroyed and all associated\n** resources are deallocated.\n**\n** Ideally, applications should [sqlite3_finalize | finalize] all\n** [prepared statements], [sqlite3_blob_close | close] all [BLOB handles], and \n** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated\n** with the [sqlite3] object prior to attempting to close the object.\n** ^If the database connection is associated with unfinalized prepared\n** statements, BLOB handlers, and/or unfinished sqlite3_backup objects then\n** sqlite3_close() will leave the database connection open and return\n** [SQLITE_BUSY]. ^If sqlite3_close_v2() is called with unfinalized prepared\n** statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups,\n** it returns [SQLITE_OK] regardless, but instead of deallocating the database\n** connection immediately, it marks the database connection as an unusable\n** \"zombie\" and makes arrangements to automatically deallocate the database\n** connection after all prepared statements are finalized, all BLOB handles\n** are closed, and all backups have finished. The sqlite3_close_v2() interface\n** is intended for use with host languages that are garbage collected, and\n** where the order in which destructors are called is arbitrary.\n**\n** ^If an [sqlite3] object is destroyed while a transaction is open,\n** the transaction is automatically rolled back.\n**\n** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]\n** must be either a NULL\n** pointer or an [sqlite3] object pointer obtained\n** from [sqlite3_open()], [sqlite3_open16()], or\n** [sqlite3_open_v2()], and not previously closed.\n** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer\n** argument is a harmless no-op.\n*/\nSQLITE_API int sqlite3_close(sqlite3*);\nSQLITE_API int sqlite3_close_v2(sqlite3*);\n\n/*\n** The type for a callback function.\n** This is legacy and deprecated.  It is included for historical\n** compatibility and is not documented.\n*/\ntypedef int (*sqlite3_callback)(void*,int,char**, char**);\n\n/*\n** CAPI3REF: One-Step Query Execution Interface\n** METHOD: sqlite3\n**\n** The sqlite3_exec() interface is a convenience wrapper around\n** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],\n** that allows an application to run multiple statements of SQL\n** without having to use a lot of C code. \n**\n** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,\n** semicolon-separate SQL statements passed into its 2nd argument,\n** in the context of the [database connection] passed in as its 1st\n** argument.  ^If the callback function of the 3rd argument to\n** sqlite3_exec() is not NULL, then it is invoked for each result row\n** coming out of the evaluated SQL statements.  ^The 4th argument to\n** sqlite3_exec() is relayed through to the 1st argument of each\n** callback invocation.  ^If the callback pointer to sqlite3_exec()\n** is NULL, then no callback is ever invoked and result rows are\n** ignored.\n**\n** ^If an error occurs while evaluating the SQL statements passed into\n** sqlite3_exec(), then execution of the current statement stops and\n** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()\n** is not NULL then any error message is written into memory obtained\n** from [sqlite3_malloc()] and passed back through the 5th parameter.\n** To avoid memory leaks, the application should invoke [sqlite3_free()]\n** on error message strings returned through the 5th parameter of\n** sqlite3_exec() after the error message string is no longer needed.\n** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors\n** occur, then sqlite3_exec() sets the pointer in its 5th parameter to\n** NULL before returning.\n**\n** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()\n** routine returns SQLITE_ABORT without invoking the callback again and\n** without running any subsequent SQL statements.\n**\n** ^The 2nd argument to the sqlite3_exec() callback function is the\n** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()\n** callback is an array of pointers to strings obtained as if from\n** [sqlite3_column_text()], one for each column.  ^If an element of a\n** result row is NULL then the corresponding string pointer for the\n** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the\n** sqlite3_exec() callback is an array of pointers to strings where each\n** entry represents the name of corresponding result column as obtained\n** from [sqlite3_column_name()].\n**\n** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer\n** to an empty string, or a pointer that contains only whitespace and/or \n** SQL comments, then no SQL statements are evaluated and the database\n** is not changed.\n**\n** Restrictions:\n**\n** <ul>\n** <li> The application must ensure that the 1st parameter to sqlite3_exec()\n**      is a valid and open [database connection].\n** <li> The application must not close the [database connection] specified by\n**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.\n** <li> The application must not modify the SQL statement text passed into\n**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.\n** </ul>\n*/\nSQLITE_API int sqlite3_exec(\n  sqlite3*,                                  /* An open database */\n  const char *sql,                           /* SQL to be evaluated */\n  int (*callback)(void*,int,char**,char**),  /* Callback function */\n  void *,                                    /* 1st argument to callback */\n  char **errmsg                              /* Error msg written here */\n);\n\n/*\n** CAPI3REF: Result Codes\n** KEYWORDS: {result code definitions}\n**\n** Many SQLite functions return an integer result code from the set shown\n** here in order to indicate success or failure.\n**\n** New error codes may be added in future versions of SQLite.\n**\n** See also: [extended result code definitions]\n*/\n#define SQLITE_OK           0   /* Successful result */\n/* beginning-of-error-codes */\n#define SQLITE_ERROR        1   /* Generic error */\n#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */\n#define SQLITE_PERM         3   /* Access permission denied */\n#define SQLITE_ABORT        4   /* Callback routine requested an abort */\n#define SQLITE_BUSY         5   /* The database file is locked */\n#define SQLITE_LOCKED       6   /* A table in the database is locked */\n#define SQLITE_NOMEM        7   /* A malloc() failed */\n#define SQLITE_READONLY     8   /* Attempt to write a readonly database */\n#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/\n#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */\n#define SQLITE_CORRUPT     11   /* The database disk image is malformed */\n#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */\n#define SQLITE_FULL        13   /* Insertion failed because database is full */\n#define SQLITE_CANTOPEN    14   /* Unable to open the database file */\n#define SQLITE_PROTOCOL    15   /* Database lock protocol error */\n#define SQLITE_EMPTY       16   /* Internal use only */\n#define SQLITE_SCHEMA      17   /* The database schema changed */\n#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */\n#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */\n#define SQLITE_MISMATCH    20   /* Data type mismatch */\n#define SQLITE_MISUSE      21   /* Library used incorrectly */\n#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */\n#define SQLITE_AUTH        23   /* Authorization denied */\n#define SQLITE_FORMAT      24   /* Not used */\n#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */\n#define SQLITE_NOTADB      26   /* File opened that is not a database file */\n#define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */\n#define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */\n#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */\n#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */\n/* end-of-error-codes */\n\n/*\n** CAPI3REF: Extended Result Codes\n** KEYWORDS: {extended result code definitions}\n**\n** In its default configuration, SQLite API routines return one of 30 integer\n** [result codes].  However, experience has shown that many of\n** these result codes are too coarse-grained.  They do not provide as\n** much information about problems as programmers might like.  In an effort to\n** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]\n** and later) include\n** support for additional result codes that provide more detailed information\n** about errors. These [extended result codes] are enabled or disabled\n** on a per database connection basis using the\n** [sqlite3_extended_result_codes()] API.  Or, the extended code for\n** the most recent error can be obtained using\n** [sqlite3_extended_errcode()].\n*/\n#define SQLITE_ERROR_MISSING_COLLSEQ   (SQLITE_ERROR | (1<<8))\n#define SQLITE_ERROR_RETRY             (SQLITE_ERROR | (2<<8))\n#define SQLITE_ERROR_SNAPSHOT          (SQLITE_ERROR | (3<<8))\n#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))\n#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))\n#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))\n#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))\n#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))\n#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))\n#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))\n#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))\n#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))\n#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))\n#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))\n#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))\n#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))\n#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))\n#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))\n#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))\n#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))\n#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))\n#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))\n#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))\n#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))\n#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))\n#define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))\n#define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))\n#define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))\n#define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))\n#define SQLITE_IOERR_VNODE             (SQLITE_IOERR | (27<<8))\n#define SQLITE_IOERR_AUTH              (SQLITE_IOERR | (28<<8))\n#define SQLITE_IOERR_BEGIN_ATOMIC      (SQLITE_IOERR | (29<<8))\n#define SQLITE_IOERR_COMMIT_ATOMIC     (SQLITE_IOERR | (30<<8))\n#define SQLITE_IOERR_ROLLBACK_ATOMIC   (SQLITE_IOERR | (31<<8))\n#define SQLITE_IOERR_DATA              (SQLITE_IOERR | (32<<8))\n#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))\n#define SQLITE_LOCKED_VTAB             (SQLITE_LOCKED |  (2<<8))\n#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))\n#define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))\n#define SQLITE_BUSY_TIMEOUT            (SQLITE_BUSY   |  (3<<8))\n#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))\n#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))\n#define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))\n#define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))\n#define SQLITE_CANTOPEN_DIRTYWAL       (SQLITE_CANTOPEN | (5<<8)) /* Not Used */\n#define SQLITE_CANTOPEN_SYMLINK        (SQLITE_CANTOPEN | (6<<8))\n#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))\n#define SQLITE_CORRUPT_SEQUENCE        (SQLITE_CORRUPT | (2<<8))\n#define SQLITE_CORRUPT_INDEX           (SQLITE_CORRUPT | (3<<8))\n#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))\n#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))\n#define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))\n#define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))\n#define SQLITE_READONLY_CANTINIT       (SQLITE_READONLY | (5<<8))\n#define SQLITE_READONLY_DIRECTORY      (SQLITE_READONLY | (6<<8))\n#define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))\n#define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))\n#define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))\n#define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))\n#define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))\n#define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))\n#define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))\n#define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))\n#define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))\n#define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))\n#define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))\n#define SQLITE_CONSTRAINT_PINNED       (SQLITE_CONSTRAINT |(11<<8))\n#define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))\n#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))\n#define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))\n#define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))\n#define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))\n#define SQLITE_OK_SYMLINK              (SQLITE_OK | (2<<8))\n\n/*\n** CAPI3REF: Flags For File Open Operations\n**\n** These bit values are intended for use in the\n** 3rd parameter to the [sqlite3_open_v2()] interface and\n** in the 4th parameter to the [sqlite3_vfs.xOpen] method.\n*/\n#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */\n#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */\n#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */\n#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */\n#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */\n#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */\n#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */\n#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */\n#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */\n#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */\n#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */\n#define SQLITE_OPEN_NOFOLLOW         0x01000000  /* Ok for sqlite3_open_v2() */\n\n/* Reserved:                         0x00F00000 */\n\n/*\n** CAPI3REF: Device Characteristics\n**\n** The xDeviceCharacteristics method of the [sqlite3_io_methods]\n** object returns an integer which is a vector of these\n** bit values expressing I/O characteristics of the mass storage\n** device that holds the file that the [sqlite3_io_methods]\n** refers to.\n**\n** The SQLITE_IOCAP_ATOMIC property means that all writes of\n** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values\n** mean that writes of blocks that are nnn bytes in size and\n** are aligned to an address which is an integer multiple of\n** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means\n** that when data is appended to a file, the data is appended\n** first then the size of the file is extended, never the other\n** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that\n** information is written to disk in the same order as calls\n** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that\n** after reboot following a crash or power loss, the only bytes in a\n** file that were written at the application level might have changed\n** and that adjacent bytes, even bytes within the same sector are\n** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN\n** flag indicates that a file cannot be deleted when open.  The\n** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on\n** read-only media and cannot be changed even by processes with\n** elevated privileges.\n**\n** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying\n** filesystem supports doing multiple write operations atomically when those\n** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and\n** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].\n*/\n#define SQLITE_IOCAP_ATOMIC                 0x00000001\n#define SQLITE_IOCAP_ATOMIC512              0x00000002\n#define SQLITE_IOCAP_ATOMIC1K               0x00000004\n#define SQLITE_IOCAP_ATOMIC2K               0x00000008\n#define SQLITE_IOCAP_ATOMIC4K               0x00000010\n#define SQLITE_IOCAP_ATOMIC8K               0x00000020\n#define SQLITE_IOCAP_ATOMIC16K              0x00000040\n#define SQLITE_IOCAP_ATOMIC32K              0x00000080\n#define SQLITE_IOCAP_ATOMIC64K              0x00000100\n#define SQLITE_IOCAP_SAFE_APPEND            0x00000200\n#define SQLITE_IOCAP_SEQUENTIAL             0x00000400\n#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800\n#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000\n#define SQLITE_IOCAP_IMMUTABLE              0x00002000\n#define SQLITE_IOCAP_BATCH_ATOMIC           0x00004000\n\n/*\n** CAPI3REF: File Locking Levels\n**\n** SQLite uses one of these integer values as the second\n** argument to calls it makes to the xLock() and xUnlock() methods\n** of an [sqlite3_io_methods] object.\n*/\n#define SQLITE_LOCK_NONE          0\n#define SQLITE_LOCK_SHARED        1\n#define SQLITE_LOCK_RESERVED      2\n#define SQLITE_LOCK_PENDING       3\n#define SQLITE_LOCK_EXCLUSIVE     4\n\n/*\n** CAPI3REF: Synchronization Type Flags\n**\n** When SQLite invokes the xSync() method of an\n** [sqlite3_io_methods] object it uses a combination of\n** these integer values as the second argument.\n**\n** When the SQLITE_SYNC_DATAONLY flag is used, it means that the\n** sync operation only needs to flush data to mass storage.  Inode\n** information need not be flushed. If the lower four bits of the flag\n** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.\n** If the lower four bits equal SQLITE_SYNC_FULL, that means\n** to use Mac OS X style fullsync instead of fsync().\n**\n** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags\n** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL\n** settings.  The [synchronous pragma] determines when calls to the\n** xSync VFS method occur and applies uniformly across all platforms.\n** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how\n** energetic or rigorous or forceful the sync operations are and\n** only make a difference on Mac OSX for the default SQLite code.\n** (Third-party VFS implementations might also make the distinction\n** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the\n** operating systems natively supported by SQLite, only Mac OSX\n** cares about the difference.)\n*/\n#define SQLITE_SYNC_NORMAL        0x00002\n#define SQLITE_SYNC_FULL          0x00003\n#define SQLITE_SYNC_DATAONLY      0x00010\n\n/*\n** CAPI3REF: OS Interface Open File Handle\n**\n** An [sqlite3_file] object represents an open file in the \n** [sqlite3_vfs | OS interface layer].  Individual OS interface\n** implementations will\n** want to subclass this object by appending additional fields\n** for their own use.  The pMethods entry is a pointer to an\n** [sqlite3_io_methods] object that defines methods for performing\n** I/O operations on the open file.\n*/\ntypedef struct sqlite3_file sqlite3_file;\nstruct sqlite3_file {\n  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */\n};\n\n/*\n** CAPI3REF: OS Interface File Virtual Methods Object\n**\n** Every file opened by the [sqlite3_vfs.xOpen] method populates an\n** [sqlite3_file] object (or, more commonly, a subclass of the\n** [sqlite3_file] object) with a pointer to an instance of this object.\n** This object defines the methods used to perform various operations\n** against the open file represented by the [sqlite3_file] object.\n**\n** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element \n** to a non-NULL pointer, then the sqlite3_io_methods.xClose method\n** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The\n** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]\n** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element\n** to NULL.\n**\n** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or\n** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().\n** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]\n** flag may be ORed in to indicate that only the data of the file\n** and not its inode needs to be synced.\n**\n** The integer values to xLock() and xUnlock() are one of\n** <ul>\n** <li> [SQLITE_LOCK_NONE],\n** <li> [SQLITE_LOCK_SHARED],\n** <li> [SQLITE_LOCK_RESERVED],\n** <li> [SQLITE_LOCK_PENDING], or\n** <li> [SQLITE_LOCK_EXCLUSIVE].\n** </ul>\n** xLock() increases the lock. xUnlock() decreases the lock.\n** The xCheckReservedLock() method checks whether any database connection,\n** either in this process or in some other process, is holding a RESERVED,\n** PENDING, or EXCLUSIVE lock on the file.  It returns true\n** if such a lock exists and false otherwise.\n**\n** The xFileControl() method is a generic interface that allows custom\n** VFS implementations to directly control an open file using the\n** [sqlite3_file_control()] interface.  The second \"op\" argument is an\n** integer opcode.  The third argument is a generic pointer intended to\n** point to a structure that may contain arguments or space in which to\n** write return values.  Potential uses for xFileControl() might be\n** functions to enable blocking locks with timeouts, to change the\n** locking strategy (for example to use dot-file locks), to inquire\n** about the status of a lock, or to break stale locks.  The SQLite\n** core reserves all opcodes less than 100 for its own use.\n** A [file control opcodes | list of opcodes] less than 100 is available.\n** Applications that define a custom xFileControl method should use opcodes\n** greater than 100 to avoid conflicts.  VFS implementations should\n** return [SQLITE_NOTFOUND] for file control opcodes that they do not\n** recognize.\n**\n** The xSectorSize() method returns the sector size of the\n** device that underlies the file.  The sector size is the\n** minimum write that can be performed without disturbing\n** other bytes in the file.  The xDeviceCharacteristics()\n** method returns a bit vector describing behaviors of the\n** underlying device:\n**\n** <ul>\n** <li> [SQLITE_IOCAP_ATOMIC]\n** <li> [SQLITE_IOCAP_ATOMIC512]\n** <li> [SQLITE_IOCAP_ATOMIC1K]\n** <li> [SQLITE_IOCAP_ATOMIC2K]\n** <li> [SQLITE_IOCAP_ATOMIC4K]\n** <li> [SQLITE_IOCAP_ATOMIC8K]\n** <li> [SQLITE_IOCAP_ATOMIC16K]\n** <li> [SQLITE_IOCAP_ATOMIC32K]\n** <li> [SQLITE_IOCAP_ATOMIC64K]\n** <li> [SQLITE_IOCAP_SAFE_APPEND]\n** <li> [SQLITE_IOCAP_SEQUENTIAL]\n** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]\n** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]\n** <li> [SQLITE_IOCAP_IMMUTABLE]\n** <li> [SQLITE_IOCAP_BATCH_ATOMIC]\n** </ul>\n**\n** The SQLITE_IOCAP_ATOMIC property means that all writes of\n** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values\n** mean that writes of blocks that are nnn bytes in size and\n** are aligned to an address which is an integer multiple of\n** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means\n** that when data is appended to a file, the data is appended\n** first then the size of the file is extended, never the other\n** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that\n** information is written to disk in the same order as calls\n** to xWrite().\n**\n** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill\n** in the unread portions of the buffer with zeros.  A VFS that\n** fails to zero-fill short reads might seem to work.  However,\n** failure to zero-fill short reads will eventually lead to\n** database corruption.\n*/\ntypedef struct sqlite3_io_methods sqlite3_io_methods;\nstruct sqlite3_io_methods {\n  int iVersion;\n  int (*xClose)(sqlite3_file*);\n  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);\n  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);\n  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);\n  int (*xSync)(sqlite3_file*, int flags);\n  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);\n  int (*xLock)(sqlite3_file*, int);\n  int (*xUnlock)(sqlite3_file*, int);\n  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);\n  int (*xFileControl)(sqlite3_file*, int op, void *pArg);\n  int (*xSectorSize)(sqlite3_file*);\n  int (*xDeviceCharacteristics)(sqlite3_file*);\n  /* Methods above are valid for version 1 */\n  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);\n  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);\n  void (*xShmBarrier)(sqlite3_file*);\n  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);\n  /* Methods above are valid for version 2 */\n  int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);\n  int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);\n  /* Methods above are valid for version 3 */\n  /* Additional methods may be added in future releases */\n};\n\n/*\n** CAPI3REF: Standard File Control Opcodes\n** KEYWORDS: {file control opcodes} {file control opcode}\n**\n** These integer constants are opcodes for the xFileControl method\n** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]\n** interface.\n**\n** <ul>\n** <li>[[SQLITE_FCNTL_LOCKSTATE]]\n** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This\n** opcode causes the xFileControl method to write the current state of\n** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],\n** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])\n** into an integer that the pArg argument points to. This capability\n** is used during testing and is only available when the SQLITE_TEST\n** compile-time option is used.\n**\n** <li>[[SQLITE_FCNTL_SIZE_HINT]]\n** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS\n** layer a hint of how large the database file will grow to be during the\n** current transaction.  This hint is not guaranteed to be accurate but it\n** is often close.  The underlying VFS might choose to preallocate database\n** file space based on this hint in order to help writes to the database\n** file run faster.\n**\n** <li>[[SQLITE_FCNTL_SIZE_LIMIT]]\n** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that\n** implements [sqlite3_deserialize()] to set an upper bound on the size\n** of the in-memory database.  The argument is a pointer to a [sqlite3_int64].\n** If the integer pointed to is negative, then it is filled in with the\n** current limit.  Otherwise the limit is set to the larger of the value\n** of the integer pointed to and the current database size.  The integer\n** pointed to is set to the new limit.\n**\n** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]\n** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS\n** extends and truncates the database file in chunks of a size specified\n** by the user. The fourth argument to [sqlite3_file_control()] should \n** point to an integer (type int) containing the new chunk-size to use\n** for the nominated database. Allocating database file space in large\n** chunks (say 1MB at a time), may reduce file-system fragmentation and\n** improve performance on some systems.\n**\n** <li>[[SQLITE_FCNTL_FILE_POINTER]]\n** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer\n** to the [sqlite3_file] object associated with a particular database\n** connection.  See also [SQLITE_FCNTL_JOURNAL_POINTER].\n**\n** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]\n** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer\n** to the [sqlite3_file] object associated with the journal file (either\n** the [rollback journal] or the [write-ahead log]) for a particular database\n** connection.  See also [SQLITE_FCNTL_FILE_POINTER].\n**\n** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]\n** No longer in use.\n**\n** <li>[[SQLITE_FCNTL_SYNC]]\n** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and\n** sent to the VFS immediately before the xSync method is invoked on a\n** database file descriptor. Or, if the xSync method is not invoked \n** because the user has configured SQLite with \n** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place \n** of the xSync method. In most cases, the pointer argument passed with\n** this file-control is NULL. However, if the database file is being synced\n** as part of a multi-database commit, the argument points to a nul-terminated\n** string containing the transactions master-journal file name. VFSes that \n** do not need this signal should silently ignore this opcode. Applications \n** should not call [sqlite3_file_control()] with this opcode as doing so may \n** disrupt the operation of the specialized VFSes that do require it.  \n**\n** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]\n** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite\n** and sent to the VFS after a transaction has been committed immediately\n** but before the database is unlocked. VFSes that do not need this signal\n** should silently ignore this opcode. Applications should not call\n** [sqlite3_file_control()] with this opcode as doing so may disrupt the \n** operation of the specialized VFSes that do require it.  \n**\n** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]\n** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic\n** retry counts and intervals for certain disk I/O operations for the\n** windows [VFS] in order to provide robustness in the presence of\n** anti-virus programs.  By default, the windows VFS will retry file read,\n** file write, and file delete operations up to 10 times, with a delay\n** of 25 milliseconds before the first retry and with the delay increasing\n** by an additional 25 milliseconds with each subsequent retry.  This\n** opcode allows these two values (10 retries and 25 milliseconds of delay)\n** to be adjusted.  The values are changed for all database connections\n** within the same process.  The argument is a pointer to an array of two\n** integers where the first integer is the new retry count and the second\n** integer is the delay.  If either integer is negative, then the setting\n** is not changed but instead the prior value of that setting is written\n** into the array entry, allowing the current retry settings to be\n** interrogated.  The zDbName parameter is ignored.\n**\n** <li>[[SQLITE_FCNTL_PERSIST_WAL]]\n** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the\n** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary\n** write ahead log ([WAL file]) and shared memory\n** files used for transaction control\n** are automatically deleted when the latest connection to the database\n** closes.  Setting persistent WAL mode causes those files to persist after\n** close.  Persisting the files is useful when other processes that do not\n** have write permission on the directory containing the database file want\n** to read the database file, as the WAL and shared memory files must exist\n** in order for the database to be readable.  The fourth parameter to\n** [sqlite3_file_control()] for this opcode should be a pointer to an integer.\n** That integer is 0 to disable persistent WAL mode or 1 to enable persistent\n** WAL mode.  If the integer is -1, then it is overwritten with the current\n** WAL persistence setting.\n**\n** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]\n** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the\n** persistent \"powersafe-overwrite\" or \"PSOW\" setting.  The PSOW setting\n** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the\n** xDeviceCharacteristics methods. The fourth parameter to\n** [sqlite3_file_control()] for this opcode should be a pointer to an integer.\n** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage\n** mode.  If the integer is -1, then it is overwritten with the current\n** zero-damage mode setting.\n**\n** <li>[[SQLITE_FCNTL_OVERWRITE]]\n** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening\n** a write transaction to indicate that, unless it is rolled back for some\n** reason, the entire database file will be overwritten by the current \n** transaction. This is used by VACUUM operations.\n**\n** <li>[[SQLITE_FCNTL_VFSNAME]]\n** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of\n** all [VFSes] in the VFS stack.  The names are of all VFS shims and the\n** final bottom-level VFS are written into memory obtained from \n** [sqlite3_malloc()] and the result is stored in the char* variable\n** that the fourth parameter of [sqlite3_file_control()] points to.\n** The caller is responsible for freeing the memory when done.  As with\n** all file-control actions, there is no guarantee that this will actually\n** do anything.  Callers should initialize the char* variable to a NULL\n** pointer in case this file-control is not implemented.  This file-control\n** is intended for diagnostic use only.\n**\n** <li>[[SQLITE_FCNTL_VFS_POINTER]]\n** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level\n** [VFSes] currently in use.  ^(The argument X in\n** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be\n** of type \"[sqlite3_vfs] **\".  This opcodes will set *X\n** to a pointer to the top-level VFS.)^\n** ^When there are multiple VFS shims in the stack, this opcode finds the\n** upper-most shim only.\n**\n** <li>[[SQLITE_FCNTL_PRAGMA]]\n** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] \n** file control is sent to the open [sqlite3_file] object corresponding\n** to the database file to which the pragma statement refers. ^The argument\n** to the [SQLITE_FCNTL_PRAGMA] file control is an array of\n** pointers to strings (char**) in which the second element of the array\n** is the name of the pragma and the third element is the argument to the\n** pragma or NULL if the pragma has no argument.  ^The handler for an\n** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element\n** of the char** argument point to a string obtained from [sqlite3_mprintf()]\n** or the equivalent and that string will become the result of the pragma or\n** the error message if the pragma fails. ^If the\n** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal \n** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]\n** file control returns [SQLITE_OK], then the parser assumes that the\n** VFS has handled the PRAGMA itself and the parser generates a no-op\n** prepared statement if result string is NULL, or that returns a copy\n** of the result string if the string is non-NULL.\n** ^If the [SQLITE_FCNTL_PRAGMA] file control returns\n** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means\n** that the VFS encountered an error while handling the [PRAGMA] and the\n** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]\n** file control occurs at the beginning of pragma statement analysis and so\n** it is able to override built-in [PRAGMA] statements.\n**\n** <li>[[SQLITE_FCNTL_BUSYHANDLER]]\n** ^The [SQLITE_FCNTL_BUSYHANDLER]\n** file-control may be invoked by SQLite on the database file handle\n** shortly after it is opened in order to provide a custom VFS with access\n** to the connection's busy-handler callback. The argument is of type (void**)\n** - an array of two (void *) values. The first (void *) actually points\n** to a function of type (int (*)(void *)). In order to invoke the connection's\n** busy-handler, this function should be invoked with the second (void *) in\n** the array as the only argument. If it returns non-zero, then the operation\n** should be retried. If it returns zero, the custom VFS should abandon the\n** current operation.\n**\n** <li>[[SQLITE_FCNTL_TEMPFILENAME]]\n** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control\n** to have SQLite generate a\n** temporary filename using the same algorithm that is followed to generate\n** temporary filenames for TEMP tables and other internal uses.  The\n** argument should be a char** which will be filled with the filename\n** written into memory obtained from [sqlite3_malloc()].  The caller should\n** invoke [sqlite3_free()] on the result to avoid a memory leak.\n**\n** <li>[[SQLITE_FCNTL_MMAP_SIZE]]\n** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the\n** maximum number of bytes that will be used for memory-mapped I/O.\n** The argument is a pointer to a value of type sqlite3_int64 that\n** is an advisory maximum number of bytes in the file to memory map.  The\n** pointer is overwritten with the old value.  The limit is not changed if\n** the value originally pointed to is negative, and so the current limit \n** can be queried by passing in a pointer to a negative number.  This\n** file-control is used internally to implement [PRAGMA mmap_size].\n**\n** <li>[[SQLITE_FCNTL_TRACE]]\n** The [SQLITE_FCNTL_TRACE] file control provides advisory information\n** to the VFS about what the higher layers of the SQLite stack are doing.\n** This file control is used by some VFS activity tracing [shims].\n** The argument is a zero-terminated string.  Higher layers in the\n** SQLite stack may generate instances of this file control if\n** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.\n**\n** <li>[[SQLITE_FCNTL_HAS_MOVED]]\n** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a\n** pointer to an integer and it writes a boolean into that integer depending\n** on whether or not the file has been renamed, moved, or deleted since it\n** was first opened.\n**\n** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]\n** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the\n** underlying native file handle associated with a file handle.  This file\n** control interprets its argument as a pointer to a native file handle and\n** writes the resulting value there.\n**\n** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]\n** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging.  This\n** opcode causes the xFileControl method to swap the file handle with the one\n** pointed to by the pArg argument.  This capability is used during testing\n** and only needs to be supported when SQLITE_TEST is defined.\n**\n** <li>[[SQLITE_FCNTL_WAL_BLOCK]]\n** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might\n** be advantageous to block on the next WAL lock if the lock is not immediately\n** available.  The WAL subsystem issues this signal during rare\n** circumstances in order to fix a problem with priority inversion.\n** Applications should <em>not</em> use this file-control.\n**\n** <li>[[SQLITE_FCNTL_ZIPVFS]]\n** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other\n** VFS should return SQLITE_NOTFOUND for this opcode.\n**\n** <li>[[SQLITE_FCNTL_RBU]]\n** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by\n** the RBU extension only.  All other VFS should return SQLITE_NOTFOUND for\n** this opcode.  \n**\n** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]\n** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then\n** the file descriptor is placed in \"batch write mode\", which\n** means all subsequent write operations will be deferred and done\n** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].  Systems\n** that do not support batch atomic writes will return SQLITE_NOTFOUND.\n** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to\n** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or\n** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make\n** no VFS interface calls on the same [sqlite3_file] file descriptor\n** except for calls to the xWrite method and the xFileControl method\n** with [SQLITE_FCNTL_SIZE_HINT].\n**\n** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]\n** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write\n** operations since the previous successful call to \n** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.\n** This file control returns [SQLITE_OK] if and only if the writes were\n** all performed successfully and have been committed to persistent storage.\n** ^Regardless of whether or not it is successful, this file control takes\n** the file descriptor out of batch write mode so that all subsequent\n** write operations are independent.\n** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without\n** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].\n**\n** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]\n** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write\n** operations since the previous successful call to \n** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.\n** ^This file control takes the file descriptor out of batch write mode\n** so that all subsequent write operations are independent.\n** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without\n** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].\n**\n** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]\n** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode is used to configure a VFS\n** to block for up to M milliseconds before failing when attempting to \n** obtain a file lock using the xLock or xShmLock methods of the VFS. \n** The parameter is a pointer to a 32-bit signed integer that contains\n** the value that M is to be set to. Before returning, the 32-bit signed\n** integer is overwritten with the previous value of M.\n**\n** <li>[[SQLITE_FCNTL_DATA_VERSION]]\n** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to\n** a database file.  The argument is a pointer to a 32-bit unsigned integer.\n** The \"data version\" for the pager is written into the pointer.  The\n** \"data version\" changes whenever any change occurs to the corresponding\n** database file, either through SQL statements on the same database\n** connection or through transactions committed by separate database\n** connections possibly in other processes. The [sqlite3_total_changes()]\n** interface can be used to find if any database on the connection has changed,\n** but that interface responds to changes on TEMP as well as MAIN and does\n** not provide a mechanism to detect changes to MAIN only.  Also, the\n** [sqlite3_total_changes()] interface responds to internal changes only and\n** omits changes made by other database connections.  The\n** [PRAGMA data_version] command provides a mechanism to detect changes to\n** a single attached database that occur due to other database connections,\n** but omits changes implemented by the database connection on which it is\n** called.  This file control is the only mechanism to detect changes that\n** happen either internally or externally and that are associated with\n** a particular attached database.\n**\n** <li>[[SQLITE_FCNTL_CKPT_START]]\n** The [SQLITE_FCNTL_CKPT_START] opcode is invoked from within a checkpoint\n** in wal mode before the client starts to copy pages from the wal\n** file to the database file.\n**\n** <li>[[SQLITE_FCNTL_CKPT_DONE]]\n** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint\n** in wal mode after the client has finished copying pages from the wal\n** file to the database file, but before the *-shm file is updated to\n** record the fact that the pages have been checkpointed.\n** </ul>\n*/\n#define SQLITE_FCNTL_LOCKSTATE               1\n#define SQLITE_FCNTL_GET_LOCKPROXYFILE       2\n#define SQLITE_FCNTL_SET_LOCKPROXYFILE       3\n#define SQLITE_FCNTL_LAST_ERRNO              4\n#define SQLITE_FCNTL_SIZE_HINT               5\n#define SQLITE_FCNTL_CHUNK_SIZE              6\n#define SQLITE_FCNTL_FILE_POINTER            7\n#define SQLITE_FCNTL_SYNC_OMITTED            8\n#define SQLITE_FCNTL_WIN32_AV_RETRY          9\n#define SQLITE_FCNTL_PERSIST_WAL            10\n#define SQLITE_FCNTL_OVERWRITE              11\n#define SQLITE_FCNTL_VFSNAME                12\n#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13\n#define SQLITE_FCNTL_PRAGMA                 14\n#define SQLITE_FCNTL_BUSYHANDLER            15\n#define SQLITE_FCNTL_TEMPFILENAME           16\n#define SQLITE_FCNTL_MMAP_SIZE              18\n#define SQLITE_FCNTL_TRACE                  19\n#define SQLITE_FCNTL_HAS_MOVED              20\n#define SQLITE_FCNTL_SYNC                   21\n#define SQLITE_FCNTL_COMMIT_PHASETWO        22\n#define SQLITE_FCNTL_WIN32_SET_HANDLE       23\n#define SQLITE_FCNTL_WAL_BLOCK              24\n#define SQLITE_FCNTL_ZIPVFS                 25\n#define SQLITE_FCNTL_RBU                    26\n#define SQLITE_FCNTL_VFS_POINTER            27\n#define SQLITE_FCNTL_JOURNAL_POINTER        28\n#define SQLITE_FCNTL_WIN32_GET_HANDLE       29\n#define SQLITE_FCNTL_PDB                    30\n#define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE     31\n#define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE    32\n#define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE  33\n#define SQLITE_FCNTL_LOCK_TIMEOUT           34\n#define SQLITE_FCNTL_DATA_VERSION           35\n#define SQLITE_FCNTL_SIZE_LIMIT             36\n#define SQLITE_FCNTL_CKPT_DONE              37\n#define SQLITE_FCNTL_RESERVE_BYTES          38\n#define SQLITE_FCNTL_CKPT_START             39\n\n/* deprecated names */\n#define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE\n#define SQLITE_SET_LOCKPROXYFILE      SQLITE_FCNTL_SET_LOCKPROXYFILE\n#define SQLITE_LAST_ERRNO             SQLITE_FCNTL_LAST_ERRNO\n\n\n/*\n** CAPI3REF: Mutex Handle\n**\n** The mutex module within SQLite defines [sqlite3_mutex] to be an\n** abstract type for a mutex object.  The SQLite core never looks\n** at the internal representation of an [sqlite3_mutex].  It only\n** deals with pointers to the [sqlite3_mutex] object.\n**\n** Mutexes are created using [sqlite3_mutex_alloc()].\n*/\ntypedef struct sqlite3_mutex sqlite3_mutex;\n\n/*\n** CAPI3REF: Loadable Extension Thunk\n**\n** A pointer to the opaque sqlite3_api_routines structure is passed as\n** the third parameter to entry points of [loadable extensions].  This\n** structure must be typedefed in order to work around compiler warnings\n** on some platforms.\n*/\ntypedef struct sqlite3_api_routines sqlite3_api_routines;\n\n/*\n** CAPI3REF: OS Interface Object\n**\n** An instance of the sqlite3_vfs object defines the interface between\n** the SQLite core and the underlying operating system.  The \"vfs\"\n** in the name of the object stands for \"virtual file system\".  See\n** the [VFS | VFS documentation] for further information.\n**\n** The VFS interface is sometimes extended by adding new methods onto\n** the end.  Each time such an extension occurs, the iVersion field\n** is incremented.  The iVersion value started out as 1 in\n** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2\n** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased\n** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6].  Additional fields\n** may be appended to the sqlite3_vfs object and the iVersion value\n** may increase again in future versions of SQLite.\n** Note that due to an oversight, the structure\n** of the sqlite3_vfs object changed in the transition from\n** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]\n** and yet the iVersion field was not increased.\n**\n** The szOsFile field is the size of the subclassed [sqlite3_file]\n** structure used by this VFS.  mxPathname is the maximum length of\n** a pathname in this VFS.\n**\n** Registered sqlite3_vfs objects are kept on a linked list formed by\n** the pNext pointer.  The [sqlite3_vfs_register()]\n** and [sqlite3_vfs_unregister()] interfaces manage this list\n** in a thread-safe way.  The [sqlite3_vfs_find()] interface\n** searches the list.  Neither the application code nor the VFS\n** implementation should use the pNext pointer.\n**\n** The pNext field is the only field in the sqlite3_vfs\n** structure that SQLite will ever modify.  SQLite will only access\n** or modify this field while holding a particular static mutex.\n** The application should never modify anything within the sqlite3_vfs\n** object once the object has been registered.\n**\n** The zName field holds the name of the VFS module.  The name must\n** be unique across all VFS modules.\n**\n** [[sqlite3_vfs.xOpen]]\n** ^SQLite guarantees that the zFilename parameter to xOpen\n** is either a NULL pointer or string obtained\n** from xFullPathname() with an optional suffix added.\n** ^If a suffix is added to the zFilename parameter, it will\n** consist of a single \"-\" character followed by no more than\n** 11 alphanumeric and/or \"-\" characters.\n** ^SQLite further guarantees that\n** the string will be valid and unchanged until xClose() is\n** called. Because of the previous sentence,\n** the [sqlite3_file] can safely store a pointer to the\n** filename if it needs to remember the filename for some reason.\n** If the zFilename parameter to xOpen is a NULL pointer then xOpen\n** must invent its own temporary name for the file.  ^Whenever the \n** xFilename parameter is NULL it will also be the case that the\n** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].\n**\n** The flags argument to xOpen() includes all bits set in\n** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]\n** or [sqlite3_open16()] is used, then flags includes at least\n** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. \n** If xOpen() opens a file read-only then it sets *pOutFlags to\n** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.\n**\n** ^(SQLite will also add one of the following flags to the xOpen()\n** call, depending on the object being opened:\n**\n** <ul>\n** <li>  [SQLITE_OPEN_MAIN_DB]\n** <li>  [SQLITE_OPEN_MAIN_JOURNAL]\n** <li>  [SQLITE_OPEN_TEMP_DB]\n** <li>  [SQLITE_OPEN_TEMP_JOURNAL]\n** <li>  [SQLITE_OPEN_TRANSIENT_DB]\n** <li>  [SQLITE_OPEN_SUBJOURNAL]\n** <li>  [SQLITE_OPEN_MASTER_JOURNAL]\n** <li>  [SQLITE_OPEN_WAL]\n** </ul>)^\n**\n** The file I/O implementation can use the object type flags to\n** change the way it deals with files.  For example, an application\n** that does not care about crash recovery or rollback might make\n** the open of a journal file a no-op.  Writes to this journal would\n** also be no-ops, and any attempt to read the journal would return\n** SQLITE_IOERR.  Or the implementation might recognize that a database\n** file will be doing page-aligned sector reads and writes in a random\n** order and set up its I/O subsystem accordingly.\n**\n** SQLite might also add one of the following flags to the xOpen method:\n**\n** <ul>\n** <li> [SQLITE_OPEN_DELETEONCLOSE]\n** <li> [SQLITE_OPEN_EXCLUSIVE]\n** </ul>\n**\n** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be\n** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]\n** will be set for TEMP databases and their journals, transient\n** databases, and subjournals.\n**\n** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction\n** with the [SQLITE_OPEN_CREATE] flag, which are both directly\n** analogous to the O_EXCL and O_CREAT flags of the POSIX open()\n** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the \n** SQLITE_OPEN_CREATE, is used to indicate that file should always\n** be created, and that it is an error if it already exists.\n** It is <i>not</i> used to indicate the file should be opened \n** for exclusive access.\n**\n** ^At least szOsFile bytes of memory are allocated by SQLite\n** to hold the [sqlite3_file] structure passed as the third\n** argument to xOpen.  The xOpen method does not have to\n** allocate the structure; it should just fill it in.  Note that\n** the xOpen method must set the sqlite3_file.pMethods to either\n** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do\n** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods\n** element will be valid after xOpen returns regardless of the success\n** or failure of the xOpen call.\n**\n** [[sqlite3_vfs.xAccess]]\n** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]\n** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to\n** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]\n** to test whether a file is at least readable.  The SQLITE_ACCESS_READ\n** flag is never actually used and is not implemented in the built-in\n** VFSes of SQLite.  The file is named by the second argument and can be a\n** directory. The xAccess method returns [SQLITE_OK] on success or some\n** non-zero error code if there is an I/O error or if the name of\n** the file given in the second argument is illegal.  If SQLITE_OK\n** is returned, then non-zero or zero is written into *pResOut to indicate\n** whether or not the file is accessible.  \n**\n** ^SQLite will always allocate at least mxPathname+1 bytes for the\n** output buffer xFullPathname.  The exact size of the output buffer\n** is also passed as a parameter to both  methods. If the output buffer\n** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is\n** handled as a fatal error by SQLite, vfs implementations should endeavor\n** to prevent this by setting mxPathname to a sufficiently large value.\n**\n** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()\n** interfaces are not strictly a part of the filesystem, but they are\n** included in the VFS structure for completeness.\n** The xRandomness() function attempts to return nBytes bytes\n** of good-quality randomness into zOut.  The return value is\n** the actual number of bytes of randomness obtained.\n** The xSleep() method causes the calling thread to sleep for at\n** least the number of microseconds given.  ^The xCurrentTime()\n** method returns a Julian Day Number for the current date and time as\n** a floating point value.\n** ^The xCurrentTimeInt64() method returns, as an integer, the Julian\n** Day Number multiplied by 86400000 (the number of milliseconds in \n** a 24-hour day).  \n** ^SQLite will use the xCurrentTimeInt64() method to get the current\n** date and time if that method is available (if iVersion is 2 or \n** greater and the function pointer is not NULL) and will fall back\n** to xCurrentTime() if xCurrentTimeInt64() is unavailable.\n**\n** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces\n** are not used by the SQLite core.  These optional interfaces are provided\n** by some VFSes to facilitate testing of the VFS code. By overriding \n** system calls with functions under its control, a test program can\n** simulate faults and error conditions that would otherwise be difficult\n** or impossible to induce.  The set of system calls that can be overridden\n** varies from one VFS to another, and from one version of the same VFS to the\n** next.  Applications that use these interfaces must be prepared for any\n** or all of these interfaces to be NULL or for their behavior to change\n** from one release to the next.  Applications must not attempt to access\n** any of these methods if the iVersion of the VFS is less than 3.\n*/\ntypedef struct sqlite3_vfs sqlite3_vfs;\ntypedef void (*sqlite3_syscall_ptr)(void);\nstruct sqlite3_vfs {\n  int iVersion;            /* Structure version number (currently 3) */\n  int szOsFile;            /* Size of subclassed sqlite3_file */\n  int mxPathname;          /* Maximum file pathname length */\n  sqlite3_vfs *pNext;      /* Next registered VFS */\n  const char *zName;       /* Name of this virtual file system */\n  void *pAppData;          /* Pointer to application-specific data */\n  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,\n               int flags, int *pOutFlags);\n  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);\n  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);\n  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);\n  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);\n  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);\n  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);\n  void (*xDlClose)(sqlite3_vfs*, void*);\n  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);\n  int (*xSleep)(sqlite3_vfs*, int microseconds);\n  int (*xCurrentTime)(sqlite3_vfs*, double*);\n  int (*xGetLastError)(sqlite3_vfs*, int, char *);\n  /*\n  ** The methods above are in version 1 of the sqlite_vfs object\n  ** definition.  Those that follow are added in version 2 or later\n  */\n  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);\n  /*\n  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.\n  ** Those below are for version 3 and greater.\n  */\n  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);\n  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);\n  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);\n  /*\n  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.\n  ** New fields may be appended in future versions.  The iVersion\n  ** value will increment whenever this happens. \n  */\n};\n\n/*\n** CAPI3REF: Flags for the xAccess VFS method\n**\n** These integer constants can be used as the third parameter to\n** the xAccess method of an [sqlite3_vfs] object.  They determine\n** what kind of permissions the xAccess method is looking for.\n** With SQLITE_ACCESS_EXISTS, the xAccess method\n** simply checks whether the file exists.\n** With SQLITE_ACCESS_READWRITE, the xAccess method\n** checks whether the named directory is both readable and writable\n** (in other words, if files can be added, removed, and renamed within\n** the directory).\n** The SQLITE_ACCESS_READWRITE constant is currently used only by the\n** [temp_store_directory pragma], though this could change in a future\n** release of SQLite.\n** With SQLITE_ACCESS_READ, the xAccess method\n** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is\n** currently unused, though it might be used in a future release of\n** SQLite.\n*/\n#define SQLITE_ACCESS_EXISTS    0\n#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */\n#define SQLITE_ACCESS_READ      2   /* Unused */\n\n/*\n** CAPI3REF: Flags for the xShmLock VFS method\n**\n** These integer constants define the various locking operations\n** allowed by the xShmLock method of [sqlite3_io_methods].  The\n** following are the only legal combinations of flags to the\n** xShmLock method:\n**\n** <ul>\n** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED\n** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE\n** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED\n** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE\n** </ul>\n**\n** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as\n** was given on the corresponding lock.  \n**\n** The xShmLock method can transition between unlocked and SHARED or\n** between unlocked and EXCLUSIVE.  It cannot transition between SHARED\n** and EXCLUSIVE.\n*/\n#define SQLITE_SHM_UNLOCK       1\n#define SQLITE_SHM_LOCK         2\n#define SQLITE_SHM_SHARED       4\n#define SQLITE_SHM_EXCLUSIVE    8\n\n/*\n** CAPI3REF: Maximum xShmLock index\n**\n** The xShmLock method on [sqlite3_io_methods] may use values\n** between 0 and this upper bound as its \"offset\" argument.\n** The SQLite core will never attempt to acquire or release a\n** lock outside of this range\n*/\n#define SQLITE_SHM_NLOCK        8\n\n\n/*\n** CAPI3REF: Initialize The SQLite Library\n**\n** ^The sqlite3_initialize() routine initializes the\n** SQLite library.  ^The sqlite3_shutdown() routine\n** deallocates any resources that were allocated by sqlite3_initialize().\n** These routines are designed to aid in process initialization and\n** shutdown on embedded systems.  Workstation applications using\n** SQLite normally do not need to invoke either of these routines.\n**\n** A call to sqlite3_initialize() is an \"effective\" call if it is\n** the first time sqlite3_initialize() is invoked during the lifetime of\n** the process, or if it is the first time sqlite3_initialize() is invoked\n** following a call to sqlite3_shutdown().  ^(Only an effective call\n** of sqlite3_initialize() does any initialization.  All other calls\n** are harmless no-ops.)^\n**\n** A call to sqlite3_shutdown() is an \"effective\" call if it is the first\n** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only\n** an effective call to sqlite3_shutdown() does any deinitialization.\n** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^\n**\n** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()\n** is not.  The sqlite3_shutdown() interface must only be called from a\n** single thread.  All open [database connections] must be closed and all\n** other SQLite resources must be deallocated prior to invoking\n** sqlite3_shutdown().\n**\n** Among other things, ^sqlite3_initialize() will invoke\n** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()\n** will invoke sqlite3_os_end().\n**\n** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.\n** ^If for some reason, sqlite3_initialize() is unable to initialize\n** the library (perhaps it is unable to allocate a needed resource such\n** as a mutex) it returns an [error code] other than [SQLITE_OK].\n**\n** ^The sqlite3_initialize() routine is called internally by many other\n** SQLite interfaces so that an application usually does not need to\n** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]\n** calls sqlite3_initialize() so the SQLite library will be automatically\n** initialized when [sqlite3_open()] is called if it has not be initialized\n** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]\n** compile-time option, then the automatic calls to sqlite3_initialize()\n** are omitted and the application must call sqlite3_initialize() directly\n** prior to using any other SQLite interface.  For maximum portability,\n** it is recommended that applications always invoke sqlite3_initialize()\n** directly prior to using any other SQLite interface.  Future releases\n** of SQLite may require this.  In other words, the behavior exhibited\n** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the\n** default behavior in some future release of SQLite.\n**\n** The sqlite3_os_init() routine does operating-system specific\n** initialization of the SQLite library.  The sqlite3_os_end()\n** routine undoes the effect of sqlite3_os_init().  Typical tasks\n** performed by these routines include allocation or deallocation\n** of static resources, initialization of global variables,\n** setting up a default [sqlite3_vfs] module, or setting up\n** a default configuration using [sqlite3_config()].\n**\n** The application should never invoke either sqlite3_os_init()\n** or sqlite3_os_end() directly.  The application should only invoke\n** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()\n** interface is called automatically by sqlite3_initialize() and\n** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate\n** implementations for sqlite3_os_init() and sqlite3_os_end()\n** are built into SQLite when it is compiled for Unix, Windows, or OS/2.\n** When [custom builds | built for other platforms]\n** (using the [SQLITE_OS_OTHER=1] compile-time\n** option) the application must supply a suitable implementation for\n** sqlite3_os_init() and sqlite3_os_end().  An application-supplied\n** implementation of sqlite3_os_init() or sqlite3_os_end()\n** must return [SQLITE_OK] on success and some other [error code] upon\n** failure.\n*/\nSQLITE_API int sqlite3_initialize(void);\nSQLITE_API int sqlite3_shutdown(void);\nSQLITE_API int sqlite3_os_init(void);\nSQLITE_API int sqlite3_os_end(void);\n\n/*\n** CAPI3REF: Configuring The SQLite Library\n**\n** The sqlite3_config() interface is used to make global configuration\n** changes to SQLite in order to tune SQLite to the specific needs of\n** the application.  The default configuration is recommended for most\n** applications and so this routine is usually not necessary.  It is\n** provided to support rare applications with unusual needs.\n**\n** <b>The sqlite3_config() interface is not threadsafe. The application\n** must ensure that no other SQLite interfaces are invoked by other\n** threads while sqlite3_config() is running.</b>\n**\n** The sqlite3_config() interface\n** may only be invoked prior to library initialization using\n** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].\n** ^If sqlite3_config() is called after [sqlite3_initialize()] and before\n** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.\n** Note, however, that ^sqlite3_config() can be called as part of the\n** implementation of an application-defined [sqlite3_os_init()].\n**\n** The first argument to sqlite3_config() is an integer\n** [configuration option] that determines\n** what property of SQLite is to be configured.  Subsequent arguments\n** vary depending on the [configuration option]\n** in the first argument.\n**\n** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].\n** ^If the option is unknown or SQLite is unable to set the option\n** then this routine returns a non-zero [error code].\n*/\nSQLITE_API int sqlite3_config(int, ...);\n\n/*\n** CAPI3REF: Configure database connections\n** METHOD: sqlite3\n**\n** The sqlite3_db_config() interface is used to make configuration\n** changes to a [database connection].  The interface is similar to\n** [sqlite3_config()] except that the changes apply to a single\n** [database connection] (specified in the first argument).\n**\n** The second argument to sqlite3_db_config(D,V,...)  is the\n** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code \n** that indicates what aspect of the [database connection] is being configured.\n** Subsequent arguments vary depending on the configuration verb.\n**\n** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if\n** the call is considered successful.\n*/\nSQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);\n\n/*\n** CAPI3REF: Memory Allocation Routines\n**\n** An instance of this object defines the interface between SQLite\n** and low-level memory allocation routines.\n**\n** This object is used in only one place in the SQLite interface.\n** A pointer to an instance of this object is the argument to\n** [sqlite3_config()] when the configuration option is\n** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  \n** By creating an instance of this object\n** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])\n** during configuration, an application can specify an alternative\n** memory allocation subsystem for SQLite to use for all of its\n** dynamic memory needs.\n**\n** Note that SQLite comes with several [built-in memory allocators]\n** that are perfectly adequate for the overwhelming majority of applications\n** and that this object is only useful to a tiny minority of applications\n** with specialized memory allocation requirements.  This object is\n** also used during testing of SQLite in order to specify an alternative\n** memory allocator that simulates memory out-of-memory conditions in\n** order to verify that SQLite recovers gracefully from such\n** conditions.\n**\n** The xMalloc, xRealloc, and xFree methods must work like the\n** malloc(), realloc() and free() functions from the standard C library.\n** ^SQLite guarantees that the second argument to\n** xRealloc is always a value returned by a prior call to xRoundup.\n**\n** xSize should return the allocated size of a memory allocation\n** previously obtained from xMalloc or xRealloc.  The allocated size\n** is always at least as big as the requested size but may be larger.\n**\n** The xRoundup method returns what would be the allocated size of\n** a memory allocation given a particular requested size.  Most memory\n** allocators round up memory allocations at least to the next multiple\n** of 8.  Some allocators round up to a larger multiple or to a power of 2.\n** Every memory allocation request coming in through [sqlite3_malloc()]\n** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, \n** that causes the corresponding memory allocation to fail.\n**\n** The xInit method initializes the memory allocator.  For example,\n** it might allocate any required mutexes or initialize internal data\n** structures.  The xShutdown method is invoked (indirectly) by\n** [sqlite3_shutdown()] and should deallocate any resources acquired\n** by xInit.  The pAppData pointer is used as the only parameter to\n** xInit and xShutdown.\n**\n** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes\n** the xInit method, so the xInit method need not be threadsafe.  The\n** xShutdown method is only called from [sqlite3_shutdown()] so it does\n** not need to be threadsafe either.  For all other methods, SQLite\n** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the\n** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which\n** it is by default) and so the methods are automatically serialized.\n** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other\n** methods must be threadsafe or else make their own arrangements for\n** serialization.\n**\n** SQLite will never invoke xInit() more than once without an intervening\n** call to xShutdown().\n*/\ntypedef struct sqlite3_mem_methods sqlite3_mem_methods;\nstruct sqlite3_mem_methods {\n  void *(*xMalloc)(int);         /* Memory allocation function */\n  void (*xFree)(void*);          /* Free a prior allocation */\n  void *(*xRealloc)(void*,int);  /* Resize an allocation */\n  int (*xSize)(void*);           /* Return the size of an allocation */\n  int (*xRoundup)(int);          /* Round up request size to allocation size */\n  int (*xInit)(void*);           /* Initialize the memory allocator */\n  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */\n  void *pAppData;                /* Argument to xInit() and xShutdown() */\n};\n\n/*\n** CAPI3REF: Configuration Options\n** KEYWORDS: {configuration option}\n**\n** These constants are the available integer configuration options that\n** can be passed as the first argument to the [sqlite3_config()] interface.\n**\n** New configuration options may be added in future releases of SQLite.\n** Existing configuration options might be discontinued.  Applications\n** should check the return code from [sqlite3_config()] to make sure that\n** the call worked.  The [sqlite3_config()] interface will return a\n** non-zero [error code] if a discontinued or unsupported configuration option\n** is invoked.\n**\n** <dl>\n** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>\n** <dd>There are no arguments to this option.  ^This option sets the\n** [threading mode] to Single-thread.  In other words, it disables\n** all mutexing and puts SQLite into a mode where it can only be used\n** by a single thread.   ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** it is not possible to change the [threading mode] from its default\n** value of Single-thread and so [sqlite3_config()] will return \n** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD\n** configuration option.</dd>\n**\n** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>\n** <dd>There are no arguments to this option.  ^This option sets the\n** [threading mode] to Multi-thread.  In other words, it disables\n** mutexing on [database connection] and [prepared statement] objects.\n** The application is responsible for serializing access to\n** [database connections] and [prepared statements].  But other mutexes\n** are enabled so that SQLite will be safe to use in a multi-threaded\n** environment as long as no two threads attempt to use the same\n** [database connection] at the same time.  ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** it is not possible to set the Multi-thread [threading mode] and\n** [sqlite3_config()] will return [SQLITE_ERROR] if called with the\n** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>\n**\n** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>\n** <dd>There are no arguments to this option.  ^This option sets the\n** [threading mode] to Serialized. In other words, this option enables\n** all mutexes including the recursive\n** mutexes on [database connection] and [prepared statement] objects.\n** In this mode (which is the default when SQLite is compiled with\n** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access\n** to [database connections] and [prepared statements] so that the\n** application is free to use the same [database connection] or the\n** same [prepared statement] in different threads at the same time.\n** ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** it is not possible to set the Serialized [threading mode] and\n** [sqlite3_config()] will return [SQLITE_ERROR] if called with the\n** SQLITE_CONFIG_SERIALIZED configuration option.</dd>\n**\n** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>\n** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is \n** a pointer to an instance of the [sqlite3_mem_methods] structure.\n** The argument specifies\n** alternative low-level memory allocation routines to be used in place of\n** the memory allocation routines built into SQLite.)^ ^SQLite makes\n** its own private copy of the content of the [sqlite3_mem_methods] structure\n** before the [sqlite3_config()] call returns.</dd>\n**\n** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>\n** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which\n** is a pointer to an instance of the [sqlite3_mem_methods] structure.\n** The [sqlite3_mem_methods]\n** structure is filled with the currently defined memory allocation routines.)^\n** This option can be used to overload the default memory allocation\n** routines with a wrapper that simulations memory allocation failure or\n** tracks memory usage, for example. </dd>\n**\n** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>\n** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of\n** type int, interpreted as a boolean, which if true provides a hint to\n** SQLite that it should avoid large memory allocations if possible.\n** SQLite will run faster if it is free to make large memory allocations,\n** but some application might prefer to run slower in exchange for\n** guarantees about memory fragmentation that are possible if large\n** allocations are avoided.  This hint is normally off.\n** </dd>\n**\n** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>\n** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,\n** interpreted as a boolean, which enables or disables the collection of\n** memory allocation statistics. ^(When memory allocation statistics are\n** disabled, the following SQLite interfaces become non-operational:\n**   <ul>\n**   <li> [sqlite3_hard_heap_limit64()]\n**   <li> [sqlite3_memory_used()]\n**   <li> [sqlite3_memory_highwater()]\n**   <li> [sqlite3_soft_heap_limit64()]\n**   <li> [sqlite3_status64()]\n**   </ul>)^\n** ^Memory allocation statistics are enabled by default unless SQLite is\n** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory\n** allocation statistics are disabled by default.\n** </dd>\n**\n** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>\n** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.\n** </dd>\n**\n** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>\n** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool\n** that SQLite can use for the database page cache with the default page\n** cache implementation.  \n** This configuration option is a no-op if an application-defined page\n** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].\n** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to\n** 8-byte aligned memory (pMem), the size of each page cache line (sz),\n** and the number of cache lines (N).\n** The sz argument should be the size of the largest database page\n** (a power of two between 512 and 65536) plus some extra bytes for each\n** page header.  ^The number of extra bytes needed by the page header\n** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].\n** ^It is harmless, apart from the wasted memory,\n** for the sz parameter to be larger than necessary.  The pMem\n** argument must be either a NULL pointer or a pointer to an 8-byte\n** aligned block of memory of at least sz*N bytes, otherwise\n** subsequent behavior is undefined.\n** ^When pMem is not NULL, SQLite will strive to use the memory provided\n** to satisfy page cache needs, falling back to [sqlite3_malloc()] if\n** a page cache line is larger than sz bytes or if all of the pMem buffer\n** is exhausted.\n** ^If pMem is NULL and N is non-zero, then each database connection\n** does an initial bulk allocation for page cache memory\n** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or\n** of -1024*N bytes if N is negative, . ^If additional\n** page cache memory is needed beyond what is provided by the initial\n** allocation, then SQLite goes to [sqlite3_malloc()] separately for each\n** additional cache line. </dd>\n**\n** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>\n** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer \n** that SQLite will use for all of its dynamic memory allocation needs\n** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].\n** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled\n** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns\n** [SQLITE_ERROR] if invoked otherwise.\n** ^There are three arguments to SQLITE_CONFIG_HEAP:\n** An 8-byte aligned pointer to the memory,\n** the number of bytes in the memory buffer, and the minimum allocation size.\n** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts\n** to using its default memory allocator (the system malloc() implementation),\n** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the\n** memory pointer is not NULL then the alternative memory\n** allocator is engaged to handle all of SQLites memory allocation needs.\n** The first pointer (the memory pointer) must be aligned to an 8-byte\n** boundary or subsequent behavior of SQLite will be undefined.\n** The minimum allocation size is capped at 2**12. Reasonable values\n** for the minimum allocation size are 2**5 through 2**8.</dd>\n**\n** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>\n** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a\n** pointer to an instance of the [sqlite3_mutex_methods] structure.\n** The argument specifies alternative low-level mutex routines to be used\n** in place the mutex routines built into SQLite.)^  ^SQLite makes a copy of\n** the content of the [sqlite3_mutex_methods] structure before the call to\n** [sqlite3_config()] returns. ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** the entire mutexing subsystem is omitted from the build and hence calls to\n** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will\n** return [SQLITE_ERROR].</dd>\n**\n** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>\n** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which\n** is a pointer to an instance of the [sqlite3_mutex_methods] structure.  The\n** [sqlite3_mutex_methods]\n** structure is filled with the currently defined mutex routines.)^\n** This option can be used to overload the default mutex allocation\n** routines with a wrapper used to track mutex usage for performance\n** profiling or testing, for example.   ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** the entire mutexing subsystem is omitted from the build and hence calls to\n** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will\n** return [SQLITE_ERROR].</dd>\n**\n** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>\n** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine\n** the default size of lookaside memory on each [database connection].\n** The first argument is the\n** size of each lookaside buffer slot and the second is the number of\n** slots allocated to each database connection.)^  ^(SQLITE_CONFIG_LOOKASIDE\n** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]\n** option to [sqlite3_db_config()] can be used to change the lookaside\n** configuration on individual connections.)^ </dd>\n**\n** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>\n** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is \n** a pointer to an [sqlite3_pcache_methods2] object.  This object specifies\n** the interface to a custom page cache implementation.)^\n** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>\n**\n** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>\n** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which\n** is a pointer to an [sqlite3_pcache_methods2] object.  SQLite copies of\n** the current page cache implementation into that object.)^ </dd>\n**\n** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>\n** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite\n** global [error log].\n** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a\n** function with a call signature of void(*)(void*,int,const char*), \n** and a pointer to void. ^If the function pointer is not NULL, it is\n** invoked by [sqlite3_log()] to process each logging event.  ^If the\n** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.\n** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is\n** passed through as the first parameter to the application-defined logger\n** function whenever that function is invoked.  ^The second parameter to\n** the logger function is a copy of the first parameter to the corresponding\n** [sqlite3_log()] call and is intended to be a [result code] or an\n** [extended result code].  ^The third parameter passed to the logger is\n** log message after formatting via [sqlite3_snprintf()].\n** The SQLite logging interface is not reentrant; the logger function\n** supplied by the application must not invoke any SQLite interface.\n** In a multi-threaded application, the application-defined logger\n** function must be threadsafe. </dd>\n**\n** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI\n** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.\n** If non-zero, then URI handling is globally enabled. If the parameter is zero,\n** then URI handling is globally disabled.)^ ^If URI handling is globally\n** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],\n** [sqlite3_open16()] or\n** specified as part of [ATTACH] commands are interpreted as URIs, regardless\n** of whether or not the [SQLITE_OPEN_URI] flag is set when the database\n** connection is opened. ^If it is globally disabled, filenames are\n** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the\n** database connection is opened. ^(By default, URI handling is globally\n** disabled. The default value may be changed by compiling with the\n** [SQLITE_USE_URI] symbol defined.)^\n**\n** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN\n** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer\n** argument which is interpreted as a boolean in order to enable or disable\n** the use of covering indices for full table scans in the query optimizer.\n** ^The default setting is determined\n** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is \"on\"\n** if that compile-time option is omitted.\n** The ability to disable the use of covering indices for full table scans\n** is because some incorrectly coded legacy applications might malfunction\n** when the optimization is enabled.  Providing the ability to\n** disable the optimization allows the older, buggy application code to work\n** without change even with newer versions of SQLite.\n**\n** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]\n** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE\n** <dd> These options are obsolete and should not be used by new code.\n** They are retained for backwards compatibility but are now no-ops.\n** </dd>\n**\n** [[SQLITE_CONFIG_SQLLOG]]\n** <dt>SQLITE_CONFIG_SQLLOG\n** <dd>This option is only available if sqlite is compiled with the\n** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should\n** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).\n** The second should be of type (void*). The callback is invoked by the library\n** in three separate circumstances, identified by the value passed as the\n** fourth parameter. If the fourth parameter is 0, then the database connection\n** passed as the second argument has just been opened. The third argument\n** points to a buffer containing the name of the main database file. If the\n** fourth parameter is 1, then the SQL statement that the third parameter\n** points to has just been executed. Or, if the fourth parameter is 2, then\n** the connection being passed as the second parameter is being closed. The\n** third parameter is passed NULL In this case.  An example of using this\n** configuration option can be seen in the \"test_sqllog.c\" source file in\n** the canonical SQLite source tree.</dd>\n**\n** [[SQLITE_CONFIG_MMAP_SIZE]]\n** <dt>SQLITE_CONFIG_MMAP_SIZE\n** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values\n** that are the default mmap size limit (the default setting for\n** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.\n** ^The default setting can be overridden by each database connection using\n** either the [PRAGMA mmap_size] command, or by using the\n** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size\n** will be silently truncated if necessary so that it does not exceed the\n** compile-time maximum mmap size set by the\n** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^\n** ^If either argument to this option is negative, then that argument is\n** changed to its compile-time default.\n**\n** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]\n** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE\n** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is\n** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro\n** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value\n** that specifies the maximum size of the created heap.\n**\n** [[SQLITE_CONFIG_PCACHE_HDRSZ]]\n** <dt>SQLITE_CONFIG_PCACHE_HDRSZ\n** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which\n** is a pointer to an integer and writes into that integer the number of extra\n** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].\n** The amount of extra space required can change depending on the compiler,\n** target platform, and SQLite version.\n**\n** [[SQLITE_CONFIG_PMASZ]]\n** <dt>SQLITE_CONFIG_PMASZ\n** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which\n** is an unsigned integer and sets the \"Minimum PMA Size\" for the multithreaded\n** sorter to that integer.  The default minimum PMA Size is set by the\n** [SQLITE_SORTER_PMASZ] compile-time option.  New threads are launched\n** to help with sort operations when multithreaded sorting\n** is enabled (using the [PRAGMA threads] command) and the amount of content\n** to be sorted exceeds the page size times the minimum of the\n** [PRAGMA cache_size] setting and this value.\n**\n** [[SQLITE_CONFIG_STMTJRNL_SPILL]]\n** <dt>SQLITE_CONFIG_STMTJRNL_SPILL\n** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which\n** becomes the [statement journal] spill-to-disk threshold.  \n** [Statement journals] are held in memory until their size (in bytes)\n** exceeds this threshold, at which point they are written to disk.\n** Or if the threshold is -1, statement journals are always held\n** exclusively in memory.\n** Since many statement journals never become large, setting the spill\n** threshold to a value such as 64KiB can greatly reduce the amount of\n** I/O required to support statement rollback.\n** The default value for this setting is controlled by the\n** [SQLITE_STMTJRNL_SPILL] compile-time option.\n**\n** [[SQLITE_CONFIG_SORTERREF_SIZE]]\n** <dt>SQLITE_CONFIG_SORTERREF_SIZE\n** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter\n** of type (int) - the new value of the sorter-reference size threshold.\n** Usually, when SQLite uses an external sort to order records according\n** to an ORDER BY clause, all fields required by the caller are present in the\n** sorted records. However, if SQLite determines based on the declared type\n** of a table column that its values are likely to be very large - larger\n** than the configured sorter-reference size threshold - then a reference\n** is stored in each sorted record and the required column values loaded\n** from the database as records are returned in sorted order. The default\n** value for this option is to never use this optimization. Specifying a \n** negative value for this option restores the default behaviour.\n** This option is only available if SQLite is compiled with the\n** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.\n**\n** [[SQLITE_CONFIG_MEMDB_MAXSIZE]]\n** <dt>SQLITE_CONFIG_MEMDB_MAXSIZE\n** <dd>The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter\n** [sqlite3_int64] parameter which is the default maximum size for an in-memory\n** database created using [sqlite3_deserialize()].  This default maximum\n** size can be adjusted up or down for individual databases using the\n** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control].  If this\n** configuration setting is never used, then the default maximum is determined\n** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option.  If that\n** compile-time option is not set, then the default maximum is 1073741824.\n** </dl>\n*/\n#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */\n#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */\n#define SQLITE_CONFIG_SERIALIZED    3  /* nil */\n#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */\n#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */\n#define SQLITE_CONFIG_SCRATCH       6  /* No longer used */\n#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */\n#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */\n#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */\n#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */\n#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */\n/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ \n#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */\n#define SQLITE_CONFIG_PCACHE       14  /* no-op */\n#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */\n#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */\n#define SQLITE_CONFIG_URI          17  /* int */\n#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */\n#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */\n#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */\n#define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */\n#define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */\n#define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */\n#define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */\n#define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */\n#define SQLITE_CONFIG_STMTJRNL_SPILL      26  /* int nByte */\n#define SQLITE_CONFIG_SMALL_MALLOC        27  /* boolean */\n#define SQLITE_CONFIG_SORTERREF_SIZE      28  /* int nByte */\n#define SQLITE_CONFIG_MEMDB_MAXSIZE       29  /* sqlite3_int64 */\n\n/*\n** CAPI3REF: Database Connection Configuration Options\n**\n** These constants are the available integer configuration options that\n** can be passed as the second argument to the [sqlite3_db_config()] interface.\n**\n** New configuration options may be added in future releases of SQLite.\n** Existing configuration options might be discontinued.  Applications\n** should check the return code from [sqlite3_db_config()] to make sure that\n** the call worked.  ^The [sqlite3_db_config()] interface will return a\n** non-zero [error code] if a discontinued or unsupported configuration option\n** is invoked.\n**\n** <dl>\n** [[SQLITE_DBCONFIG_LOOKASIDE]]\n** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>\n** <dd> ^This option takes three additional arguments that determine the \n** [lookaside memory allocator] configuration for the [database connection].\n** ^The first argument (the third parameter to [sqlite3_db_config()] is a\n** pointer to a memory buffer to use for lookaside memory.\n** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb\n** may be NULL in which case SQLite will allocate the\n** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the\n** size of each lookaside buffer slot.  ^The third argument is the number of\n** slots.  The size of the buffer in the first argument must be greater than\n** or equal to the product of the second and third arguments.  The buffer\n** must be aligned to an 8-byte boundary.  ^If the second argument to\n** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally\n** rounded down to the next smaller multiple of 8.  ^(The lookaside memory\n** configuration for a database connection can only be changed when that\n** connection is not currently using lookaside memory, or in other words\n** when the \"current value\" returned by\n** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.\n** Any attempt to change the lookaside memory configuration when lookaside\n** memory is in use leaves the configuration unchanged and returns \n** [SQLITE_BUSY].)^</dd>\n**\n** [[SQLITE_DBCONFIG_ENABLE_FKEY]]\n** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>\n** <dd> ^This option is used to enable or disable the enforcement of\n** [foreign key constraints].  There should be two additional arguments.\n** The first argument is an integer which is 0 to disable FK enforcement,\n** positive to enable FK enforcement or negative to leave FK enforcement\n** unchanged.  The second parameter is a pointer to an integer into which\n** is written 0 or 1 to indicate whether FK enforcement is off or on\n** following this call.  The second parameter may be a NULL pointer, in\n** which case the FK enforcement setting is not reported back. </dd>\n**\n** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]]\n** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>\n** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].\n** There should be two additional arguments.\n** The first argument is an integer which is 0 to disable triggers,\n** positive to enable triggers or negative to leave the setting unchanged.\n** The second parameter is a pointer to an integer into which\n** is written 0 or 1 to indicate whether triggers are disabled or enabled\n** following this call.  The second parameter may be a NULL pointer, in\n** which case the trigger setting is not reported back. </dd>\n**\n** [[SQLITE_DBCONFIG_ENABLE_VIEW]]\n** <dt>SQLITE_DBCONFIG_ENABLE_VIEW</dt>\n** <dd> ^This option is used to enable or disable [CREATE VIEW | views].\n** There should be two additional arguments.\n** The first argument is an integer which is 0 to disable views,\n** positive to enable views or negative to leave the setting unchanged.\n** The second parameter is a pointer to an integer into which\n** is written 0 or 1 to indicate whether views are disabled or enabled\n** following this call.  The second parameter may be a NULL pointer, in\n** which case the view setting is not reported back. </dd>\n**\n** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]\n** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>\n** <dd> ^This option is used to enable or disable the\n** [fts3_tokenizer()] function which is part of the\n** [FTS3] full-text search engine extension.\n** There should be two additional arguments.\n** The first argument is an integer which is 0 to disable fts3_tokenizer() or\n** positive to enable fts3_tokenizer() or negative to leave the setting\n** unchanged.\n** The second parameter is a pointer to an integer into which\n** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled\n** following this call.  The second parameter may be a NULL pointer, in\n** which case the new setting is not reported back. </dd>\n**\n** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]\n** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>\n** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]\n** interface independently of the [load_extension()] SQL function.\n** The [sqlite3_enable_load_extension()] API enables or disables both the\n** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].\n** There should be two additional arguments.\n** When the first argument to this interface is 1, then only the C-API is\n** enabled and the SQL function remains disabled.  If the first argument to\n** this interface is 0, then both the C-API and the SQL function are disabled.\n** If the first argument is -1, then no changes are made to state of either the\n** C-API or the SQL function.\n** The second parameter is a pointer to an integer into which\n** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface\n** is disabled or enabled following this call.  The second parameter may\n** be a NULL pointer, in which case the new setting is not reported back.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>\n** <dd> ^This option is used to change the name of the \"main\" database\n** schema.  ^The sole argument is a pointer to a constant UTF8 string\n** which will become the new schema name in place of \"main\".  ^SQLite\n** does not make a copy of the new main schema name string, so the application\n** must ensure that the argument passed into this DBCONFIG option is unchanged\n** until after the database connection closes.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]] \n** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>\n** <dd> Usually, when a database in wal mode is closed or detached from a \n** database handle, SQLite checks if this will mean that there are now no \n** connections at all to the database. If so, it performs a checkpoint \n** operation before closing the connection. This option may be used to\n** override this behaviour. The first parameter passed to this operation\n** is an integer - positive to disable checkpoints-on-close, or zero (the\n** default) to enable them, and negative to leave the setting unchanged.\n** The second parameter is a pointer to an integer\n** into which is written 0 or 1 to indicate whether checkpoints-on-close\n** have been disabled - 0 if they are not disabled, 1 if they are.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>\n** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates\n** the [query planner stability guarantee] (QPSG).  When the QPSG is active,\n** a single SQL query statement will always use the same algorithm regardless\n** of values of [bound parameters].)^ The QPSG disables some query optimizations\n** that look at the values of bound parameters, which can make some queries\n** slower.  But the QPSG has the advantage of more predictable behavior.  With\n** the QPSG active, SQLite will always use the same query plan in the field as\n** was used during testing in the lab.\n** The first argument to this setting is an integer which is 0 to disable \n** the QPSG, positive to enable QPSG, or negative to leave the setting\n** unchanged. The second parameter is a pointer to an integer into which\n** is written 0 or 1 to indicate whether the QPSG is disabled or enabled\n** following this call.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>\n** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not \n** include output for any operations performed by trigger programs. This\n** option is used to set or clear (the default) a flag that governs this\n** behavior. The first parameter passed to this operation is an integer -\n** positive to enable output for trigger programs, or zero to disable it,\n** or negative to leave the setting unchanged.\n** The second parameter is a pointer to an integer into which is written \n** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if \n** it is not disabled, 1 if it is.  \n** </dd>\n**\n** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>\n** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run\n** [VACUUM] in order to reset a database back to an empty database\n** with no schema and no content. The following process works even for\n** a badly corrupted database file:\n** <ol>\n** <li> If the database connection is newly opened, make sure it has read the\n**      database schema by preparing then discarding some query against the\n**      database, or calling sqlite3_table_column_metadata(), ignoring any\n**      errors.  This step is only necessary if the application desires to keep\n**      the database in WAL mode after the reset if it was in WAL mode before\n**      the reset.  \n** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);\n** <li> [sqlite3_exec](db, \"[VACUUM]\", 0, 0, 0);\n** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);\n** </ol>\n** Because resetting a database is destructive and irreversible, the\n** process requires the use of this obscure API and multiple steps to help\n** ensure that it does not happen by accident.\n**\n** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt>\n** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the\n** \"defensive\" flag for a database connection.  When the defensive\n** flag is enabled, language features that allow ordinary SQL to \n** deliberately corrupt the database file are disabled.  The disabled\n** features include but are not limited to the following:\n** <ul>\n** <li> The [PRAGMA writable_schema=ON] statement.\n** <li> The [PRAGMA journal_mode=OFF] statement.\n** <li> Writes to the [sqlite_dbpage] virtual table.\n** <li> Direct writes to [shadow tables].\n** </ul>\n** </dd>\n**\n** [[SQLITE_DBCONFIG_WRITABLE_SCHEMA]] <dt>SQLITE_DBCONFIG_WRITABLE_SCHEMA</dt>\n** <dd>The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the\n** \"writable_schema\" flag. This has the same effect and is logically equivalent\n** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF].\n** The first argument to this setting is an integer which is 0 to disable \n** the writable_schema, positive to enable writable_schema, or negative to\n** leave the setting unchanged. The second parameter is a pointer to an\n** integer into which is written 0 or 1 to indicate whether the writable_schema\n** is enabled or disabled following this call.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]]\n** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt>\n** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates\n** the legacy behavior of the [ALTER TABLE RENAME] command such it\n** behaves as it did prior to [version 3.24.0] (2018-06-04).  See the\n** \"Compatibility Notice\" on the [ALTER TABLE RENAME documentation] for\n** additional information. This feature can also be turned on and off\n** using the [PRAGMA legacy_alter_table] statement.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_DQS_DML]]\n** <dt>SQLITE_DBCONFIG_DQS_DML</td>\n** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates\n** the legacy [double-quoted string literal] misfeature for DML statements\n** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The\n** default value of this setting is determined by the [-DSQLITE_DQS]\n** compile-time option.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_DQS_DDL]]\n** <dt>SQLITE_DBCONFIG_DQS_DDL</td>\n** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates\n** the legacy [double-quoted string literal] misfeature for DDL statements,\n** such as CREATE TABLE and CREATE INDEX. The\n** default value of this setting is determined by the [-DSQLITE_DQS]\n** compile-time option.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]]\n** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</td>\n** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to\n** assume that database schemas (the contents of the [sqlite_master] tables)\n** are untainted by malicious content.\n** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite\n** takes additional defensive steps to protect the application from harm\n** including:\n** <ul>\n** <li> Prohibit the use of SQL functions inside triggers, views,\n** CHECK constraints, DEFAULT clauses, expression indexes, \n** partial indexes, or generated columns\n** unless those functions are tagged with [SQLITE_INNOCUOUS].\n** <li> Prohibit the use of virtual tables inside of triggers or views\n** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS].\n** </ul>\n** This setting defaults to \"on\" for legacy compatibility, however\n** all applications are advised to turn it off if possible. This setting\n** can also be controlled using the [PRAGMA trusted_schema] statement.\n** </dd>\n**\n** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]]\n** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</td>\n** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates\n** the legacy file format flag.  When activated, this flag causes all newly\n** created database file to have a schema format version number (the 4-byte\n** integer found at offset 44 into the database header) of 1.  This in turn\n** means that the resulting database file will be readable and writable by\n** any SQLite version back to 3.0.0 ([dateof:3.0.0]).  Without this setting,\n** newly created databases are generally not understandable by SQLite versions\n** prior to 3.3.0 ([dateof:3.3.0]).  As these words are written, there\n** is now scarcely any need to generated database files that are compatible \n** all the way back to version 3.0.0, and so this setting is of little\n** practical use, but is provided so that SQLite can continue to claim the\n** ability to generate new database files that are compatible with  version\n** 3.0.0.\n** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on,\n** the [VACUUM] command will fail with an obscure error when attempting to\n** process a table with generated columns and a descending index.  This is\n** not considered a bug since SQLite versions 3.3.0 and earlier do not support\n** either generated columns or decending indexes.\n** </dd>\n** </dl>\n*/\n#define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */\n#define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */\n#define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */\n#define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */\n#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */\n#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */\n#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      1006 /* int int* */\n#define SQLITE_DBCONFIG_ENABLE_QPSG           1007 /* int int* */\n#define SQLITE_DBCONFIG_TRIGGER_EQP           1008 /* int int* */\n#define SQLITE_DBCONFIG_RESET_DATABASE        1009 /* int int* */\n#define SQLITE_DBCONFIG_DEFENSIVE             1010 /* int int* */\n#define SQLITE_DBCONFIG_WRITABLE_SCHEMA       1011 /* int int* */\n#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    1012 /* int int* */\n#define SQLITE_DBCONFIG_DQS_DML               1013 /* int int* */\n#define SQLITE_DBCONFIG_DQS_DDL               1014 /* int int* */\n#define SQLITE_DBCONFIG_ENABLE_VIEW           1015 /* int int* */\n#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    1016 /* int int* */\n#define SQLITE_DBCONFIG_TRUSTED_SCHEMA        1017 /* int int* */\n#define SQLITE_DBCONFIG_MAX                   1017 /* Largest DBCONFIG */\n\n/*\n** CAPI3REF: Enable Or Disable Extended Result Codes\n** METHOD: sqlite3\n**\n** ^The sqlite3_extended_result_codes() routine enables or disables the\n** [extended result codes] feature of SQLite. ^The extended result\n** codes are disabled by default for historical compatibility.\n*/\nSQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);\n\n/*\n** CAPI3REF: Last Insert Rowid\n** METHOD: sqlite3\n**\n** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)\n** has a unique 64-bit signed\n** integer key called the [ROWID | \"rowid\"]. ^The rowid is always available\n** as an undeclared column named ROWID, OID, or _ROWID_ as long as those\n** names are not also used by explicitly declared columns. ^If\n** the table has a column of type [INTEGER PRIMARY KEY] then that column\n** is another alias for the rowid.\n**\n** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of\n** the most recent successful [INSERT] into a rowid table or [virtual table]\n** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not\n** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred \n** on the database connection D, then sqlite3_last_insert_rowid(D) returns \n** zero.\n**\n** As well as being set automatically as rows are inserted into database\n** tables, the value returned by this function may be set explicitly by\n** [sqlite3_set_last_insert_rowid()]\n**\n** Some virtual table implementations may INSERT rows into rowid tables as\n** part of committing a transaction (e.g. to flush data accumulated in memory\n** to disk). In this case subsequent calls to this function return the rowid\n** associated with these internal INSERT operations, which leads to \n** unintuitive results. Virtual table implementations that do write to rowid\n** tables in this way can avoid this problem by restoring the original \n** rowid value using [sqlite3_set_last_insert_rowid()] before returning \n** control to the user.\n**\n** ^(If an [INSERT] occurs within a trigger then this routine will \n** return the [rowid] of the inserted row as long as the trigger is \n** running. Once the trigger program ends, the value returned \n** by this routine reverts to what it was before the trigger was fired.)^\n**\n** ^An [INSERT] that fails due to a constraint violation is not a\n** successful [INSERT] and does not change the value returned by this\n** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,\n** and INSERT OR ABORT make no changes to the return value of this\n** routine when their insertion fails.  ^(When INSERT OR REPLACE\n** encounters a constraint violation, it does not fail.  The\n** INSERT continues to completion after deleting rows that caused\n** the constraint problem so INSERT OR REPLACE will always change\n** the return value of this interface.)^\n**\n** ^For the purposes of this routine, an [INSERT] is considered to\n** be successful even if it is subsequently rolled back.\n**\n** This function is accessible to SQL statements via the\n** [last_insert_rowid() SQL function].\n**\n** If a separate thread performs a new [INSERT] on the same\n** database connection while the [sqlite3_last_insert_rowid()]\n** function is running and thus changes the last insert [rowid],\n** then the value returned by [sqlite3_last_insert_rowid()] is\n** unpredictable and might not equal either the old or the new\n** last insert [rowid].\n*/\nSQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);\n\n/*\n** CAPI3REF: Set the Last Insert Rowid value.\n** METHOD: sqlite3\n**\n** The sqlite3_set_last_insert_rowid(D, R) method allows the application to\n** set the value returned by calling sqlite3_last_insert_rowid(D) to R \n** without inserting a row into the database.\n*/\nSQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);\n\n/*\n** CAPI3REF: Count The Number Of Rows Modified\n** METHOD: sqlite3\n**\n** ^This function returns the number of rows modified, inserted or\n** deleted by the most recently completed INSERT, UPDATE or DELETE\n** statement on the database connection specified by the only parameter.\n** ^Executing any other type of SQL statement does not modify the value\n** returned by this function.\n**\n** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are\n** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], \n** [foreign key actions] or [REPLACE] constraint resolution are not counted.\n** \n** Changes to a view that are intercepted by \n** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value \n** returned by sqlite3_changes() immediately after an INSERT, UPDATE or \n** DELETE statement run on a view is always zero. Only changes made to real \n** tables are counted.\n**\n** Things are more complicated if the sqlite3_changes() function is\n** executed while a trigger program is running. This may happen if the\n** program uses the [changes() SQL function], or if some other callback\n** function invokes sqlite3_changes() directly. Essentially:\n** \n** <ul>\n**   <li> ^(Before entering a trigger program the value returned by\n**        sqlite3_changes() function is saved. After the trigger program \n**        has finished, the original value is restored.)^\n** \n**   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE \n**        statement sets the value returned by sqlite3_changes() \n**        upon completion as normal. Of course, this value will not include \n**        any changes performed by sub-triggers, as the sqlite3_changes() \n**        value will be saved and restored after each sub-trigger has run.)^\n** </ul>\n** \n** ^This means that if the changes() SQL function (or similar) is used\n** by the first INSERT, UPDATE or DELETE statement within a trigger, it \n** returns the value as set when the calling statement began executing.\n** ^If it is used by the second or subsequent such statement within a trigger \n** program, the value returned reflects the number of rows modified by the \n** previous INSERT, UPDATE or DELETE statement within the same trigger.\n**\n** If a separate thread makes changes on the same database connection\n** while [sqlite3_changes()] is running then the value returned\n** is unpredictable and not meaningful.\n**\n** See also:\n** <ul>\n** <li> the [sqlite3_total_changes()] interface\n** <li> the [count_changes pragma]\n** <li> the [changes() SQL function]\n** <li> the [data_version pragma]\n** </ul>\n*/\nSQLITE_API int sqlite3_changes(sqlite3*);\n\n/*\n** CAPI3REF: Total Number Of Rows Modified\n** METHOD: sqlite3\n**\n** ^This function returns the total number of rows inserted, modified or\n** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed\n** since the database connection was opened, including those executed as\n** part of trigger programs. ^Executing any other type of SQL statement\n** does not affect the value returned by sqlite3_total_changes().\n** \n** ^Changes made as part of [foreign key actions] are included in the\n** count, but those made as part of REPLACE constraint resolution are\n** not. ^Changes to a view that are intercepted by INSTEAD OF triggers \n** are not counted.\n**\n** The [sqlite3_total_changes(D)] interface only reports the number\n** of rows that changed due to SQL statement run against database\n** connection D.  Any changes by other database connections are ignored.\n** To detect changes against a database file from other database\n** connections use the [PRAGMA data_version] command or the\n** [SQLITE_FCNTL_DATA_VERSION] [file control].\n** \n** If a separate thread makes changes on the same database connection\n** while [sqlite3_total_changes()] is running then the value\n** returned is unpredictable and not meaningful.\n**\n** See also:\n** <ul>\n** <li> the [sqlite3_changes()] interface\n** <li> the [count_changes pragma]\n** <li> the [changes() SQL function]\n** <li> the [data_version pragma]\n** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control]\n** </ul>\n*/\nSQLITE_API int sqlite3_total_changes(sqlite3*);\n\n/*\n** CAPI3REF: Interrupt A Long-Running Query\n** METHOD: sqlite3\n**\n** ^This function causes any pending database operation to abort and\n** return at its earliest opportunity. This routine is typically\n** called in response to a user action such as pressing \"Cancel\"\n** or Ctrl-C where the user wants a long query operation to halt\n** immediately.\n**\n** ^It is safe to call this routine from a thread different from the\n** thread that is currently running the database operation.  But it\n** is not safe to call this routine with a [database connection] that\n** is closed or might close before sqlite3_interrupt() returns.\n**\n** ^If an SQL operation is very nearly finished at the time when\n** sqlite3_interrupt() is called, then it might not have an opportunity\n** to be interrupted and might continue to completion.\n**\n** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].\n** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE\n** that is inside an explicit transaction, then the entire transaction\n** will be rolled back automatically.\n**\n** ^The sqlite3_interrupt(D) call is in effect until all currently running\n** SQL statements on [database connection] D complete.  ^Any new SQL statements\n** that are started after the sqlite3_interrupt() call and before the \n** running statement count reaches zero are interrupted as if they had been\n** running prior to the sqlite3_interrupt() call.  ^New SQL statements\n** that are started after the running statement count reaches zero are\n** not effected by the sqlite3_interrupt().\n** ^A call to sqlite3_interrupt(D) that occurs when there are no running\n** SQL statements is a no-op and has no effect on SQL statements\n** that are started after the sqlite3_interrupt() call returns.\n*/\nSQLITE_API void sqlite3_interrupt(sqlite3*);\n\n/*\n** CAPI3REF: Determine If An SQL Statement Is Complete\n**\n** These routines are useful during command-line input to determine if the\n** currently entered text seems to form a complete SQL statement or\n** if additional input is needed before sending the text into\n** SQLite for parsing.  ^These routines return 1 if the input string\n** appears to be a complete SQL statement.  ^A statement is judged to be\n** complete if it ends with a semicolon token and is not a prefix of a\n** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within\n** string literals or quoted identifier names or comments are not\n** independent tokens (they are part of the token in which they are\n** embedded) and thus do not count as a statement terminator.  ^Whitespace\n** and comments that follow the final semicolon are ignored.\n**\n** ^These routines return 0 if the statement is incomplete.  ^If a\n** memory allocation fails, then SQLITE_NOMEM is returned.\n**\n** ^These routines do not parse the SQL statements thus\n** will not detect syntactically incorrect SQL.\n**\n** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior \n** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked\n** automatically by sqlite3_complete16().  If that initialization fails,\n** then the return value from sqlite3_complete16() will be non-zero\n** regardless of whether or not the input SQL is complete.)^\n**\n** The input to [sqlite3_complete()] must be a zero-terminated\n** UTF-8 string.\n**\n** The input to [sqlite3_complete16()] must be a zero-terminated\n** UTF-16 string in native byte order.\n*/\nSQLITE_API int sqlite3_complete(const char *sql);\nSQLITE_API int sqlite3_complete16(const void *sql);\n\n/*\n** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors\n** KEYWORDS: {busy-handler callback} {busy handler}\n** METHOD: sqlite3\n**\n** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X\n** that might be invoked with argument P whenever\n** an attempt is made to access a database table associated with\n** [database connection] D when another thread\n** or process has the table locked.\n** The sqlite3_busy_handler() interface is used to implement\n** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].\n**\n** ^If the busy callback is NULL, then [SQLITE_BUSY]\n** is returned immediately upon encountering the lock.  ^If the busy callback\n** is not NULL, then the callback might be invoked with two arguments.\n**\n** ^The first argument to the busy handler is a copy of the void* pointer which\n** is the third argument to sqlite3_busy_handler().  ^The second argument to\n** the busy handler callback is the number of times that the busy handler has\n** been invoked previously for the same locking event.  ^If the\n** busy callback returns 0, then no additional attempts are made to\n** access the database and [SQLITE_BUSY] is returned\n** to the application.\n** ^If the callback returns non-zero, then another attempt\n** is made to access the database and the cycle repeats.\n**\n** The presence of a busy handler does not guarantee that it will be invoked\n** when there is lock contention. ^If SQLite determines that invoking the busy\n** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]\n** to the application instead of invoking the \n** busy handler.\n** Consider a scenario where one process is holding a read lock that\n** it is trying to promote to a reserved lock and\n** a second process is holding a reserved lock that it is trying\n** to promote to an exclusive lock.  The first process cannot proceed\n** because it is blocked by the second and the second process cannot\n** proceed because it is blocked by the first.  If both processes\n** invoke the busy handlers, neither will make any progress.  Therefore,\n** SQLite returns [SQLITE_BUSY] for the first process, hoping that this\n** will induce the first process to release its read lock and allow\n** the second process to proceed.\n**\n** ^The default busy callback is NULL.\n**\n** ^(There can only be a single busy handler defined for each\n** [database connection].  Setting a new busy handler clears any\n** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]\n** or evaluating [PRAGMA busy_timeout=N] will change the\n** busy handler and thus clear any previously set busy handler.\n**\n** The busy callback should not take any actions which modify the\n** database connection that invoked the busy handler.  In other words,\n** the busy handler is not reentrant.  Any such actions\n** result in undefined behavior.\n** \n** A busy handler must not close the database connection\n** or [prepared statement] that invoked the busy handler.\n*/\nSQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);\n\n/*\n** CAPI3REF: Set A Busy Timeout\n** METHOD: sqlite3\n**\n** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps\n** for a specified amount of time when a table is locked.  ^The handler\n** will sleep multiple times until at least \"ms\" milliseconds of sleeping\n** have accumulated.  ^After at least \"ms\" milliseconds of sleeping,\n** the handler returns 0 which causes [sqlite3_step()] to return\n** [SQLITE_BUSY].\n**\n** ^Calling this routine with an argument less than or equal to zero\n** turns off all busy handlers.\n**\n** ^(There can only be a single busy handler for a particular\n** [database connection] at any given moment.  If another busy handler\n** was defined  (using [sqlite3_busy_handler()]) prior to calling\n** this routine, that other busy handler is cleared.)^\n**\n** See also:  [PRAGMA busy_timeout]\n*/\nSQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);\n\n/*\n** CAPI3REF: Convenience Routines For Running Queries\n** METHOD: sqlite3\n**\n** This is a legacy interface that is preserved for backwards compatibility.\n** Use of this interface is not recommended.\n**\n** Definition: A <b>result table</b> is memory data structure created by the\n** [sqlite3_get_table()] interface.  A result table records the\n** complete query results from one or more queries.\n**\n** The table conceptually has a number of rows and columns.  But\n** these numbers are not part of the result table itself.  These\n** numbers are obtained separately.  Let N be the number of rows\n** and M be the number of columns.\n**\n** A result table is an array of pointers to zero-terminated UTF-8 strings.\n** There are (N+1)*M elements in the array.  The first M pointers point\n** to zero-terminated strings that  contain the names of the columns.\n** The remaining entries all point to query results.  NULL values result\n** in NULL pointers.  All other values are in their UTF-8 zero-terminated\n** string representation as returned by [sqlite3_column_text()].\n**\n** A result table might consist of one or more memory allocations.\n** It is not safe to pass a result table directly to [sqlite3_free()].\n** A result table should be deallocated using [sqlite3_free_table()].\n**\n** ^(As an example of the result table format, suppose a query result\n** is as follows:\n**\n** <blockquote><pre>\n**        Name        | Age\n**        -----------------------\n**        Alice       | 43\n**        Bob         | 28\n**        Cindy       | 21\n** </pre></blockquote>\n**\n** There are two columns (M==2) and three rows (N==3).  Thus the\n** result table has 8 entries.  Suppose the result table is stored\n** in an array named azResult.  Then azResult holds this content:\n**\n** <blockquote><pre>\n**        azResult&#91;0] = \"Name\";\n**        azResult&#91;1] = \"Age\";\n**        azResult&#91;2] = \"Alice\";\n**        azResult&#91;3] = \"43\";\n**        azResult&#91;4] = \"Bob\";\n**        azResult&#91;5] = \"28\";\n**        azResult&#91;6] = \"Cindy\";\n**        azResult&#91;7] = \"21\";\n** </pre></blockquote>)^\n**\n** ^The sqlite3_get_table() function evaluates one or more\n** semicolon-separated SQL statements in the zero-terminated UTF-8\n** string of its 2nd parameter and returns a result table to the\n** pointer given in its 3rd parameter.\n**\n** After the application has finished with the result from sqlite3_get_table(),\n** it must pass the result table pointer to sqlite3_free_table() in order to\n** release the memory that was malloced.  Because of the way the\n** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling\n** function must not try to call [sqlite3_free()] directly.  Only\n** [sqlite3_free_table()] is able to release the memory properly and safely.\n**\n** The sqlite3_get_table() interface is implemented as a wrapper around\n** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access\n** to any internal data structures of SQLite.  It uses only the public\n** interface defined here.  As a consequence, errors that occur in the\n** wrapper layer outside of the internal [sqlite3_exec()] call are not\n** reflected in subsequent calls to [sqlite3_errcode()] or\n** [sqlite3_errmsg()].\n*/\nSQLITE_API int sqlite3_get_table(\n  sqlite3 *db,          /* An open database */\n  const char *zSql,     /* SQL to be evaluated */\n  char ***pazResult,    /* Results of the query */\n  int *pnRow,           /* Number of result rows written here */\n  int *pnColumn,        /* Number of result columns written here */\n  char **pzErrmsg       /* Error msg written here */\n);\nSQLITE_API void sqlite3_free_table(char **result);\n\n/*\n** CAPI3REF: Formatted String Printing Functions\n**\n** These routines are work-alikes of the \"printf()\" family of functions\n** from the standard C library.\n** These routines understand most of the common formatting options from\n** the standard library printf() \n** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).\n** See the [built-in printf()] documentation for details.\n**\n** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their\n** results into memory obtained from [sqlite3_malloc64()].\n** The strings returned by these two routines should be\n** released by [sqlite3_free()].  ^Both routines return a\n** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough\n** memory to hold the resulting string.\n**\n** ^(The sqlite3_snprintf() routine is similar to \"snprintf()\" from\n** the standard C library.  The result is written into the\n** buffer supplied as the second parameter whose size is given by\n** the first parameter. Note that the order of the\n** first two parameters is reversed from snprintf().)^  This is an\n** historical accident that cannot be fixed without breaking\n** backwards compatibility.  ^(Note also that sqlite3_snprintf()\n** returns a pointer to its buffer instead of the number of\n** characters actually written into the buffer.)^  We admit that\n** the number of characters written would be a more useful return\n** value but we cannot change the implementation of sqlite3_snprintf()\n** now without breaking compatibility.\n**\n** ^As long as the buffer size is greater than zero, sqlite3_snprintf()\n** guarantees that the buffer is always zero-terminated.  ^The first\n** parameter \"n\" is the total size of the buffer, including space for\n** the zero terminator.  So the longest string that can be completely\n** written will be n-1 characters.\n**\n** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().\n**\n** See also:  [built-in printf()], [printf() SQL function]\n*/\nSQLITE_API char *sqlite3_mprintf(const char*,...);\nSQLITE_API char *sqlite3_vmprintf(const char*, va_list);\nSQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);\nSQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);\n\n/*\n** CAPI3REF: Memory Allocation Subsystem\n**\n** The SQLite core uses these three routines for all of its own\n** internal memory allocation needs. \"Core\" in the previous sentence\n** does not include operating-system specific [VFS] implementation.  The\n** Windows VFS uses native malloc() and free() for some operations.\n**\n** ^The sqlite3_malloc() routine returns a pointer to a block\n** of memory at least N bytes in length, where N is the parameter.\n** ^If sqlite3_malloc() is unable to obtain sufficient free\n** memory, it returns a NULL pointer.  ^If the parameter N to\n** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns\n** a NULL pointer.\n**\n** ^The sqlite3_malloc64(N) routine works just like\n** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead\n** of a signed 32-bit integer.\n**\n** ^Calling sqlite3_free() with a pointer previously returned\n** by sqlite3_malloc() or sqlite3_realloc() releases that memory so\n** that it might be reused.  ^The sqlite3_free() routine is\n** a no-op if is called with a NULL pointer.  Passing a NULL pointer\n** to sqlite3_free() is harmless.  After being freed, memory\n** should neither be read nor written.  Even reading previously freed\n** memory might result in a segmentation fault or other severe error.\n** Memory corruption, a segmentation fault, or other severe error\n** might result if sqlite3_free() is called with a non-NULL pointer that\n** was not obtained from sqlite3_malloc() or sqlite3_realloc().\n**\n** ^The sqlite3_realloc(X,N) interface attempts to resize a\n** prior memory allocation X to be at least N bytes.\n** ^If the X parameter to sqlite3_realloc(X,N)\n** is a NULL pointer then its behavior is identical to calling\n** sqlite3_malloc(N).\n** ^If the N parameter to sqlite3_realloc(X,N) is zero or\n** negative then the behavior is exactly the same as calling\n** sqlite3_free(X).\n** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation\n** of at least N bytes in size or NULL if insufficient memory is available.\n** ^If M is the size of the prior allocation, then min(N,M) bytes\n** of the prior allocation are copied into the beginning of buffer returned\n** by sqlite3_realloc(X,N) and the prior allocation is freed.\n** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the\n** prior allocation is not freed.\n**\n** ^The sqlite3_realloc64(X,N) interfaces works the same as\n** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead\n** of a 32-bit signed integer.\n**\n** ^If X is a memory allocation previously obtained from sqlite3_malloc(),\n** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then\n** sqlite3_msize(X) returns the size of that memory allocation in bytes.\n** ^The value returned by sqlite3_msize(X) might be larger than the number\n** of bytes requested when X was allocated.  ^If X is a NULL pointer then\n** sqlite3_msize(X) returns zero.  If X points to something that is not\n** the beginning of memory allocation, or if it points to a formerly\n** valid memory allocation that has now been freed, then the behavior\n** of sqlite3_msize(X) is undefined and possibly harmful.\n**\n** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),\n** sqlite3_malloc64(), and sqlite3_realloc64()\n** is always aligned to at least an 8 byte boundary, or to a\n** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time\n** option is used.\n**\n** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]\n** must be either NULL or else pointers obtained from a prior\n** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have\n** not yet been released.\n**\n** The application must not read or write any part of\n** a block of memory after it has been released using\n** [sqlite3_free()] or [sqlite3_realloc()].\n*/\nSQLITE_API void *sqlite3_malloc(int);\nSQLITE_API void *sqlite3_malloc64(sqlite3_uint64);\nSQLITE_API void *sqlite3_realloc(void*, int);\nSQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);\nSQLITE_API void sqlite3_free(void*);\nSQLITE_API sqlite3_uint64 sqlite3_msize(void*);\n\n/*\n** CAPI3REF: Memory Allocator Statistics\n**\n** SQLite provides these two interfaces for reporting on the status\n** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]\n** routines, which form the built-in memory allocation subsystem.\n**\n** ^The [sqlite3_memory_used()] routine returns the number of bytes\n** of memory currently outstanding (malloced but not freed).\n** ^The [sqlite3_memory_highwater()] routine returns the maximum\n** value of [sqlite3_memory_used()] since the high-water mark\n** was last reset.  ^The values returned by [sqlite3_memory_used()] and\n** [sqlite3_memory_highwater()] include any overhead\n** added by SQLite in its implementation of [sqlite3_malloc()],\n** but not overhead added by the any underlying system library\n** routines that [sqlite3_malloc()] may call.\n**\n** ^The memory high-water mark is reset to the current value of\n** [sqlite3_memory_used()] if and only if the parameter to\n** [sqlite3_memory_highwater()] is true.  ^The value returned\n** by [sqlite3_memory_highwater(1)] is the high-water mark\n** prior to the reset.\n*/\nSQLITE_API sqlite3_int64 sqlite3_memory_used(void);\nSQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);\n\n/*\n** CAPI3REF: Pseudo-Random Number Generator\n**\n** SQLite contains a high-quality pseudo-random number generator (PRNG) used to\n** select random [ROWID | ROWIDs] when inserting new records into a table that\n** already uses the largest possible [ROWID].  The PRNG is also used for\n** the built-in random() and randomblob() SQL functions.  This interface allows\n** applications to access the same PRNG for other purposes.\n**\n** ^A call to this routine stores N bytes of randomness into buffer P.\n** ^The P parameter can be a NULL pointer.\n**\n** ^If this routine has not been previously called or if the previous\n** call had N less than one or a NULL pointer for P, then the PRNG is\n** seeded using randomness obtained from the xRandomness method of\n** the default [sqlite3_vfs] object.\n** ^If the previous call to this routine had an N of 1 or more and a\n** non-NULL P then the pseudo-randomness is generated\n** internally and without recourse to the [sqlite3_vfs] xRandomness\n** method.\n*/\nSQLITE_API void sqlite3_randomness(int N, void *P);\n\n/*\n** CAPI3REF: Compile-Time Authorization Callbacks\n** METHOD: sqlite3\n** KEYWORDS: {authorizer callback}\n**\n** ^This routine registers an authorizer callback with a particular\n** [database connection], supplied in the first argument.\n** ^The authorizer callback is invoked as SQL statements are being compiled\n** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],\n** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],\n** and [sqlite3_prepare16_v3()].  ^At various\n** points during the compilation process, as logic is being created\n** to perform various actions, the authorizer callback is invoked to\n** see if those actions are allowed.  ^The authorizer callback should\n** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the\n** specific action but allow the SQL statement to continue to be\n** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be\n** rejected with an error.  ^If the authorizer callback returns\n** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]\n** then the [sqlite3_prepare_v2()] or equivalent call that triggered\n** the authorizer will fail with an error message.\n**\n** When the callback returns [SQLITE_OK], that means the operation\n** requested is ok.  ^When the callback returns [SQLITE_DENY], the\n** [sqlite3_prepare_v2()] or equivalent call that triggered the\n** authorizer will fail with an error message explaining that\n** access is denied. \n**\n** ^The first parameter to the authorizer callback is a copy of the third\n** parameter to the sqlite3_set_authorizer() interface. ^The second parameter\n** to the callback is an integer [SQLITE_COPY | action code] that specifies\n** the particular action to be authorized. ^The third through sixth parameters\n** to the callback are either NULL pointers or zero-terminated strings\n** that contain additional details about the action to be authorized.\n** Applications must always be prepared to encounter a NULL pointer in any\n** of the third through the sixth parameters of the authorization callback.\n**\n** ^If the action code is [SQLITE_READ]\n** and the callback returns [SQLITE_IGNORE] then the\n** [prepared statement] statement is constructed to substitute\n** a NULL value in place of the table column that would have\n** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]\n** return can be used to deny an untrusted user access to individual\n** columns of a table.\n** ^When a table is referenced by a [SELECT] but no column values are\n** extracted from that table (for example in a query like\n** \"SELECT count(*) FROM tab\") then the [SQLITE_READ] authorizer callback\n** is invoked once for that table with a column name that is an empty string.\n** ^If the action code is [SQLITE_DELETE] and the callback returns\n** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the\n** [truncate optimization] is disabled and all rows are deleted individually.\n**\n** An authorizer is used when [sqlite3_prepare | preparing]\n** SQL statements from an untrusted source, to ensure that the SQL statements\n** do not try to access data they are not allowed to see, or that they do not\n** try to execute malicious statements that damage the database.  For\n** example, an application may allow a user to enter arbitrary\n** SQL queries for evaluation by a database.  But the application does\n** not want the user to be able to make arbitrary changes to the\n** database.  An authorizer could then be put in place while the\n** user-entered SQL is being [sqlite3_prepare | prepared] that\n** disallows everything except [SELECT] statements.\n**\n** Applications that need to process SQL from untrusted sources\n** might also consider lowering resource limits using [sqlite3_limit()]\n** and limiting database size using the [max_page_count] [PRAGMA]\n** in addition to using an authorizer.\n**\n** ^(Only a single authorizer can be in place on a database connection\n** at a time.  Each call to sqlite3_set_authorizer overrides the\n** previous call.)^  ^Disable the authorizer by installing a NULL callback.\n** The authorizer is disabled by default.\n**\n** The authorizer callback must not do anything that will modify\n** the database connection that invoked the authorizer callback.\n** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their\n** database connections for the meaning of \"modify\" in this paragraph.\n**\n** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the\n** statement might be re-prepared during [sqlite3_step()] due to a \n** schema change.  Hence, the application should ensure that the\n** correct authorizer callback remains in place during the [sqlite3_step()].\n**\n** ^Note that the authorizer callback is invoked only during\n** [sqlite3_prepare()] or its variants.  Authorization is not\n** performed during statement evaluation in [sqlite3_step()], unless\n** as stated in the previous paragraph, sqlite3_step() invokes\n** sqlite3_prepare_v2() to reprepare a statement after a schema change.\n*/\nSQLITE_API int sqlite3_set_authorizer(\n  sqlite3*,\n  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),\n  void *pUserData\n);\n\n/*\n** CAPI3REF: Authorizer Return Codes\n**\n** The [sqlite3_set_authorizer | authorizer callback function] must\n** return either [SQLITE_OK] or one of these two constants in order\n** to signal SQLite whether or not the action is permitted.  See the\n** [sqlite3_set_authorizer | authorizer documentation] for additional\n** information.\n**\n** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]\n** returned from the [sqlite3_vtab_on_conflict()] interface.\n*/\n#define SQLITE_DENY   1   /* Abort the SQL statement with an error */\n#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */\n\n/*\n** CAPI3REF: Authorizer Action Codes\n**\n** The [sqlite3_set_authorizer()] interface registers a callback function\n** that is invoked to authorize certain SQL statement actions.  The\n** second parameter to the callback is an integer code that specifies\n** what action is being authorized.  These are the integer action codes that\n** the authorizer callback may be passed.\n**\n** These action code values signify what kind of operation is to be\n** authorized.  The 3rd and 4th parameters to the authorization\n** callback function will be parameters or NULL depending on which of these\n** codes is used as the second parameter.  ^(The 5th parameter to the\n** authorizer callback is the name of the database (\"main\", \"temp\",\n** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback\n** is the name of the inner-most trigger or view that is responsible for\n** the access attempt or NULL if this access attempt is directly from\n** top-level SQL code.\n*/\n/******************************************* 3rd ************ 4th ***********/\n#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */\n#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */\n#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */\n#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */\n#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */\n#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */\n#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */\n#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */\n#define SQLITE_DELETE                9   /* Table Name      NULL            */\n#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */\n#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */\n#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */\n#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */\n#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */\n#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */\n#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */\n#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */\n#define SQLITE_INSERT               18   /* Table Name      NULL            */\n#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */\n#define SQLITE_READ                 20   /* Table Name      Column Name     */\n#define SQLITE_SELECT               21   /* NULL            NULL            */\n#define SQLITE_TRANSACTION          22   /* Operation       NULL            */\n#define SQLITE_UPDATE               23   /* Table Name      Column Name     */\n#define SQLITE_ATTACH               24   /* Filename        NULL            */\n#define SQLITE_DETACH               25   /* Database Name   NULL            */\n#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */\n#define SQLITE_REINDEX              27   /* Index Name      NULL            */\n#define SQLITE_ANALYZE              28   /* Table Name      NULL            */\n#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */\n#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */\n#define SQLITE_FUNCTION             31   /* NULL            Function Name   */\n#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */\n#define SQLITE_COPY                  0   /* No longer used */\n#define SQLITE_RECURSIVE            33   /* NULL            NULL            */\n\n/*\n** CAPI3REF: Tracing And Profiling Functions\n** METHOD: sqlite3\n**\n** These routines are deprecated. Use the [sqlite3_trace_v2()] interface\n** instead of the routines described here.\n**\n** These routines register callback functions that can be used for\n** tracing and profiling the execution of SQL statements.\n**\n** ^The callback function registered by sqlite3_trace() is invoked at\n** various times when an SQL statement is being run by [sqlite3_step()].\n** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the\n** SQL statement text as the statement first begins executing.\n** ^(Additional sqlite3_trace() callbacks might occur\n** as each triggered subprogram is entered.  The callbacks for triggers\n** contain a UTF-8 SQL comment that identifies the trigger.)^\n**\n** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit\n** the length of [bound parameter] expansion in the output of sqlite3_trace().\n**\n** ^The callback function registered by sqlite3_profile() is invoked\n** as each SQL statement finishes.  ^The profile callback contains\n** the original statement text and an estimate of wall-clock time\n** of how long that statement took to run.  ^The profile callback\n** time is in units of nanoseconds, however the current implementation\n** is only capable of millisecond resolution so the six least significant\n** digits in the time are meaningless.  Future versions of SQLite\n** might provide greater resolution on the profiler callback.  Invoking\n** either [sqlite3_trace()] or [sqlite3_trace_v2()] will cancel the\n** profile callback.\n*/\nSQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,\n   void(*xTrace)(void*,const char*), void*);\nSQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,\n   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);\n\n/*\n** CAPI3REF: SQL Trace Event Codes\n** KEYWORDS: SQLITE_TRACE\n**\n** These constants identify classes of events that can be monitored\n** using the [sqlite3_trace_v2()] tracing logic.  The M argument\n** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of\n** the following constants.  ^The first argument to the trace callback\n** is one of the following constants.\n**\n** New tracing constants may be added in future releases.\n**\n** ^A trace callback has four arguments: xCallback(T,C,P,X).\n** ^The T argument is one of the integer type codes above.\n** ^The C argument is a copy of the context pointer passed in as the\n** fourth argument to [sqlite3_trace_v2()].\n** The P and X arguments are pointers whose meanings depend on T.\n**\n** <dl>\n** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>\n** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement\n** first begins running and possibly at other times during the\n** execution of the prepared statement, such as at the start of each\n** trigger subprogram. ^The P argument is a pointer to the\n** [prepared statement]. ^The X argument is a pointer to a string which\n** is the unexpanded SQL text of the prepared statement or an SQL comment \n** that indicates the invocation of a trigger.  ^The callback can compute\n** the same text that would have been returned by the legacy [sqlite3_trace()]\n** interface by using the X argument when X begins with \"--\" and invoking\n** [sqlite3_expanded_sql(P)] otherwise.\n**\n** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>\n** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same\n** information as is provided by the [sqlite3_profile()] callback.\n** ^The P argument is a pointer to the [prepared statement] and the\n** X argument points to a 64-bit integer which is the estimated of\n** the number of nanosecond that the prepared statement took to run.\n** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.\n**\n** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>\n** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared\n** statement generates a single row of result.  \n** ^The P argument is a pointer to the [prepared statement] and the\n** X argument is unused.\n**\n** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>\n** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database\n** connection closes.\n** ^The P argument is a pointer to the [database connection] object\n** and the X argument is unused.\n** </dl>\n*/\n#define SQLITE_TRACE_STMT       0x01\n#define SQLITE_TRACE_PROFILE    0x02\n#define SQLITE_TRACE_ROW        0x04\n#define SQLITE_TRACE_CLOSE      0x08\n\n/*\n** CAPI3REF: SQL Trace Hook\n** METHOD: sqlite3\n**\n** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback\n** function X against [database connection] D, using property mask M\n** and context pointer P.  ^If the X callback is\n** NULL or if the M mask is zero, then tracing is disabled.  The\n** M argument should be the bitwise OR-ed combination of\n** zero or more [SQLITE_TRACE] constants.\n**\n** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides \n** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().\n**\n** ^The X callback is invoked whenever any of the events identified by \n** mask M occur.  ^The integer return value from the callback is currently\n** ignored, though this may change in future releases.  Callback\n** implementations should return zero to ensure future compatibility.\n**\n** ^A trace callback is invoked with four arguments: callback(T,C,P,X).\n** ^The T argument is one of the [SQLITE_TRACE]\n** constants to indicate why the callback was invoked.\n** ^The C argument is a copy of the context pointer.\n** The P and X arguments are pointers whose meanings depend on T.\n**\n** The sqlite3_trace_v2() interface is intended to replace the legacy\n** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which\n** are deprecated.\n*/\nSQLITE_API int sqlite3_trace_v2(\n  sqlite3*,\n  unsigned uMask,\n  int(*xCallback)(unsigned,void*,void*,void*),\n  void *pCtx\n);\n\n/*\n** CAPI3REF: Query Progress Callbacks\n** METHOD: sqlite3\n**\n** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback\n** function X to be invoked periodically during long running calls to\n** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for\n** database connection D.  An example use for this\n** interface is to keep a GUI updated during a large query.\n**\n** ^The parameter P is passed through as the only parameter to the \n** callback function X.  ^The parameter N is the approximate number of \n** [virtual machine instructions] that are evaluated between successive\n** invocations of the callback X.  ^If N is less than one then the progress\n** handler is disabled.\n**\n** ^Only a single progress handler may be defined at one time per\n** [database connection]; setting a new progress handler cancels the\n** old one.  ^Setting parameter X to NULL disables the progress handler.\n** ^The progress handler is also disabled by setting N to a value less\n** than 1.\n**\n** ^If the progress callback returns non-zero, the operation is\n** interrupted.  This feature can be used to implement a\n** \"Cancel\" button on a GUI progress dialog box.\n**\n** The progress handler callback must not do anything that will modify\n** the database connection that invoked the progress handler.\n** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their\n** database connections for the meaning of \"modify\" in this paragraph.\n**\n*/\nSQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);\n\n/*\n** CAPI3REF: Opening A New Database Connection\n** CONSTRUCTOR: sqlite3\n**\n** ^These routines open an SQLite database file as specified by the \n** filename argument. ^The filename argument is interpreted as UTF-8 for\n** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte\n** order for sqlite3_open16(). ^(A [database connection] handle is usually\n** returned in *ppDb, even if an error occurs.  The only exception is that\n** if SQLite is unable to allocate memory to hold the [sqlite3] object,\n** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]\n** object.)^ ^(If the database is opened (and/or created) successfully, then\n** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The\n** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain\n** an English language description of the error following a failure of any\n** of the sqlite3_open() routines.\n**\n** ^The default encoding will be UTF-8 for databases created using\n** sqlite3_open() or sqlite3_open_v2().  ^The default encoding for databases\n** created using sqlite3_open16() will be UTF-16 in the native byte order.\n**\n** Whether or not an error occurs when it is opened, resources\n** associated with the [database connection] handle should be released by\n** passing it to [sqlite3_close()] when it is no longer required.\n**\n** The sqlite3_open_v2() interface works like sqlite3_open()\n** except that it accepts two additional parameters for additional control\n** over the new database connection.  ^(The flags parameter to\n** sqlite3_open_v2() must include, at a minimum, one of the following\n** three flag combinations:)^\n**\n** <dl>\n** ^(<dt>[SQLITE_OPEN_READONLY]</dt>\n** <dd>The database is opened in read-only mode.  If the database does not\n** already exist, an error is returned.</dd>)^\n**\n** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>\n** <dd>The database is opened for reading and writing if possible, or reading\n** only if the file is write protected by the operating system.  In either\n** case the database must already exist, otherwise an error is returned.</dd>)^\n**\n** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>\n** <dd>The database is opened for reading and writing, and is created if\n** it does not already exist. This is the behavior that is always used for\n** sqlite3_open() and sqlite3_open16().</dd>)^\n** </dl>\n**\n** In addition to the required flags, the following optional flags are\n** also supported:\n**\n** <dl>\n** ^(<dt>[SQLITE_OPEN_URI]</dt>\n** <dd>The filename can be interpreted as a URI if this flag is set.</dd>)^\n**\n** ^(<dt>[SQLITE_OPEN_MEMORY]</dt>\n** <dd>The database will be opened as an in-memory database.  The database\n** is named by the \"filename\" argument for the purposes of cache-sharing,\n** if shared cache mode is enabled, but the \"filename\" is otherwise ignored.\n** </dd>)^\n**\n** ^(<dt>[SQLITE_OPEN_NOMUTEX]</dt>\n** <dd>The new database connection will use the \"multi-thread\"\n** [threading mode].)^  This means that separate threads are allowed\n** to use SQLite at the same time, as long as each thread is using\n** a different [database connection].\n**\n** ^(<dt>[SQLITE_OPEN_FULLMUTEX]</dt>\n** <dd>The new database connection will use the \"serialized\"\n** [threading mode].)^  This means the multiple threads can safely\n** attempt to use the same database connection at the same time.\n** (Mutexes will block any actual concurrency, but in this mode\n** there is no harm in trying.)\n**\n** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt>\n** <dd>The database is opened [shared cache] enabled, overriding\n** the default shared cache setting provided by\n** [sqlite3_enable_shared_cache()].)^\n**\n** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>\n** <dd>The database is opened [shared cache] disabled, overriding\n** the default shared cache setting provided by\n** [sqlite3_enable_shared_cache()].)^\n**\n** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>\n** <dd>The database filename is not allowed to be a symbolic link</dd>\n** </dl>)^\n**\n** If the 3rd parameter to sqlite3_open_v2() is not one of the\n** required combinations shown above optionally combined with other\n** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]\n** then the behavior is undefined.\n**\n** ^The fourth parameter to sqlite3_open_v2() is the name of the\n** [sqlite3_vfs] object that defines the operating system interface that\n** the new database connection should use.  ^If the fourth parameter is\n** a NULL pointer then the default [sqlite3_vfs] object is used.\n**\n** ^If the filename is \":memory:\", then a private, temporary in-memory database\n** is created for the connection.  ^This in-memory database will vanish when\n** the database connection is closed.  Future versions of SQLite might\n** make use of additional special filenames that begin with the \":\" character.\n** It is recommended that when a database filename actually does begin with\n** a \":\" character you should prefix the filename with a pathname such as\n** \"./\" to avoid ambiguity.\n**\n** ^If the filename is an empty string, then a private, temporary\n** on-disk database will be created.  ^This private database will be\n** automatically deleted as soon as the database connection is closed.\n**\n** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>\n**\n** ^If [URI filename] interpretation is enabled, and the filename argument\n** begins with \"file:\", then the filename is interpreted as a URI. ^URI\n** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is\n** set in the third argument to sqlite3_open_v2(), or if it has\n** been enabled globally using the [SQLITE_CONFIG_URI] option with the\n** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.\n** URI filename interpretation is turned off\n** by default, but future releases of SQLite might enable URI filename\n** interpretation by default.  See \"[URI filenames]\" for additional\n** information.\n**\n** URI filenames are parsed according to RFC 3986. ^If the URI contains an\n** authority, then it must be either an empty string or the string \n** \"localhost\". ^If the authority is not an empty string or \"localhost\", an \n** error is returned to the caller. ^The fragment component of a URI, if \n** present, is ignored.\n**\n** ^SQLite uses the path component of the URI as the name of the disk file\n** which contains the database. ^If the path begins with a '/' character, \n** then it is interpreted as an absolute path. ^If the path does not begin \n** with a '/' (meaning that the authority section is omitted from the URI)\n** then the path is interpreted as a relative path. \n** ^(On windows, the first component of an absolute path \n** is a drive specification (e.g. \"C:\").)^\n**\n** [[core URI query parameters]]\n** The query component of a URI may contain parameters that are interpreted\n** either by SQLite itself, or by a [VFS | custom VFS implementation].\n** SQLite and its built-in [VFSes] interpret the\n** following query parameters:\n**\n** <ul>\n**   <li> <b>vfs</b>: ^The \"vfs\" parameter may be used to specify the name of\n**     a VFS object that provides the operating system interface that should\n**     be used to access the database file on disk. ^If this option is set to\n**     an empty string the default VFS object is used. ^Specifying an unknown\n**     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is\n**     present, then the VFS specified by the option takes precedence over\n**     the value passed as the fourth parameter to sqlite3_open_v2().\n**\n**   <li> <b>mode</b>: ^(The mode parameter may be set to either \"ro\", \"rw\",\n**     \"rwc\", or \"memory\". Attempting to set it to any other value is\n**     an error)^. \n**     ^If \"ro\" is specified, then the database is opened for read-only \n**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the \n**     third argument to sqlite3_open_v2(). ^If the mode option is set to \n**     \"rw\", then the database is opened for read-write (but not create) \n**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had \n**     been set. ^Value \"rwc\" is equivalent to setting both \n**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is\n**     set to \"memory\" then a pure [in-memory database] that never reads\n**     or writes from disk is used. ^It is an error to specify a value for\n**     the mode parameter that is less restrictive than that specified by\n**     the flags passed in the third parameter to sqlite3_open_v2().\n**\n**   <li> <b>cache</b>: ^The cache parameter may be set to either \"shared\" or\n**     \"private\". ^Setting it to \"shared\" is equivalent to setting the\n**     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to\n**     sqlite3_open_v2(). ^Setting the cache parameter to \"private\" is \n**     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.\n**     ^If sqlite3_open_v2() is used and the \"cache\" parameter is present in\n**     a URI filename, its value overrides any behavior requested by setting\n**     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.\n**\n**  <li> <b>psow</b>: ^The psow parameter indicates whether or not the\n**     [powersafe overwrite] property does or does not apply to the\n**     storage media on which the database file resides.\n**\n**  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter\n**     which if set disables file locking in rollback journal modes.  This\n**     is useful for accessing a database on a filesystem that does not\n**     support locking.  Caution:  Database corruption might result if two\n**     or more processes write to the same database and any one of those\n**     processes uses nolock=1.\n**\n**  <li> <b>immutable</b>: ^The immutable parameter is a boolean query\n**     parameter that indicates that the database file is stored on\n**     read-only media.  ^When immutable is set, SQLite assumes that the\n**     database file cannot be changed, even by a process with higher\n**     privilege, and so the database is opened read-only and all locking\n**     and change detection is disabled.  Caution: Setting the immutable\n**     property on a database file that does in fact change can result\n**     in incorrect query results and/or [SQLITE_CORRUPT] errors.\n**     See also: [SQLITE_IOCAP_IMMUTABLE].\n**       \n** </ul>\n**\n** ^Specifying an unknown parameter in the query component of a URI is not an\n** error.  Future versions of SQLite might understand additional query\n** parameters.  See \"[query parameters with special meaning to SQLite]\" for\n** additional information.\n**\n** [[URI filename examples]] <h3>URI filename examples</h3>\n**\n** <table border=\"1\" align=center cellpadding=5>\n** <tr><th> URI filenames <th> Results\n** <tr><td> file:data.db <td> \n**          Open the file \"data.db\" in the current directory.\n** <tr><td> file:/home/fred/data.db<br>\n**          file:///home/fred/data.db <br> \n**          file://localhost/home/fred/data.db <br> <td> \n**          Open the database file \"/home/fred/data.db\".\n** <tr><td> file://darkstar/home/fred/data.db <td> \n**          An error. \"darkstar\" is not a recognized authority.\n** <tr><td style=\"white-space:nowrap\"> \n**          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db\n**     <td> Windows only: Open the file \"data.db\" on fred's desktop on drive\n**          C:. Note that the %20 escaping in this example is not strictly \n**          necessary - space characters can be used literally\n**          in URI filenames.\n** <tr><td> file:data.db?mode=ro&cache=private <td> \n**          Open file \"data.db\" in the current directory for read-only access.\n**          Regardless of whether or not shared-cache mode is enabled by\n**          default, use a private cache.\n** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>\n**          Open file \"/home/fred/data.db\". Use the special VFS \"unix-dotfile\"\n**          that uses dot-files in place of posix advisory locking.\n** <tr><td> file:data.db?mode=readonly <td> \n**          An error. \"readonly\" is not a valid option for the \"mode\" parameter.\n** </table>\n**\n** ^URI hexadecimal escape sequences (%HH) are supported within the path and\n** query components of a URI. A hexadecimal escape sequence consists of a\n** percent sign - \"%\" - followed by exactly two hexadecimal digits \n** specifying an octet value. ^Before the path or query components of a\n** URI filename are interpreted, they are encoded using UTF-8 and all \n** hexadecimal escape sequences replaced by a single byte containing the\n** corresponding octet. If this process generates an invalid UTF-8 encoding,\n** the results are undefined.\n**\n** <b>Note to Windows users:</b>  The encoding used for the filename argument\n** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever\n** codepage is currently defined.  Filenames containing international\n** characters must be converted to UTF-8 prior to passing them into\n** sqlite3_open() or sqlite3_open_v2().\n**\n** <b>Note to Windows Runtime users:</b>  The temporary directory must be set\n** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various\n** features that require the use of temporary files may fail.\n**\n** See also: [sqlite3_temp_directory]\n*/\nSQLITE_API int sqlite3_open(\n  const char *filename,   /* Database filename (UTF-8) */\n  sqlite3 **ppDb          /* OUT: SQLite db handle */\n);\nSQLITE_API int sqlite3_open16(\n  const void *filename,   /* Database filename (UTF-16) */\n  sqlite3 **ppDb          /* OUT: SQLite db handle */\n);\nSQLITE_API int sqlite3_open_v2(\n  const char *filename,   /* Database filename (UTF-8) */\n  sqlite3 **ppDb,         /* OUT: SQLite db handle */\n  int flags,              /* Flags */\n  const char *zVfs        /* Name of VFS module to use */\n);\n\n/*\n** CAPI3REF: Obtain Values For URI Parameters\n**\n** These are utility routines, useful to [VFS|custom VFS implementations],\n** that check if a database file was a URI that contained a specific query \n** parameter, and if so obtains the value of that query parameter.\n**\n** The first parameter to these interfaces (hereafter referred to\n** as F) must be one of:\n** <ul>\n** <li> A database filename pointer created by the SQLite core and\n** passed into the xOpen() method of a VFS implemention, or\n** <li> A filename obtained from [sqlite3_db_filename()], or\n** <li> A new filename constructed using [sqlite3_create_filename()].\n** </ul>\n** If the F parameter is not one of the above, then the behavior is\n** undefined and probably undesirable.  Older versions of SQLite were\n** more tolerant of invalid F parameters than newer versions.\n**\n** If F is a suitable filename (as described in the previous paragraph)\n** and if P is the name of the query parameter, then\n** sqlite3_uri_parameter(F,P) returns the value of the P\n** parameter if it exists or a NULL pointer if P does not appear as a \n** query parameter on F.  If P is a query parameter of F and it\n** has no explicit value, then sqlite3_uri_parameter(F,P) returns\n** a pointer to an empty string.\n**\n** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean\n** parameter and returns true (1) or false (0) according to the value\n** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the\n** value of query parameter P is one of \"yes\", \"true\", or \"on\" in any\n** case or if the value begins with a non-zero number.  The \n** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of\n** query parameter P is one of \"no\", \"false\", or \"off\" in any case or\n** if the value begins with a numeric zero.  If P is not a query\n** parameter on F or if the value of P does not match any of the\n** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).\n**\n** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a\n** 64-bit signed integer and returns that integer, or D if P does not\n** exist.  If the value of P is something other than an integer, then\n** zero is returned.\n**\n** The sqlite3_uri_key(F,N) returns a pointer to the name (not\n** the value) of the N-th query parameter for filename F, or a NULL\n** pointer if N is less than zero or greater than the number of query\n** parameters minus 1.  The N value is zero-based so N should be 0 to obtain\n** the name of the first query parameter, 1 for the second parameter, and\n** so forth.\n** \n** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and\n** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and\n** is not a database file pathname pointer that the SQLite core passed\n** into the xOpen VFS method, then the behavior of this routine is undefined\n** and probably undesirable.\n**\n** Beginning with SQLite [version 3.31.0] ([dateof:3.31.0]) the input F\n** parameter can also be the name of a rollback journal file or WAL file\n** in addition to the main database file.  Prior to version 3.31.0, these\n** routines would only work if F was the name of the main database file.\n** When the F parameter is the name of the rollback journal or WAL file,\n** it has access to all the same query parameters as were found on the\n** main database file.\n**\n** See the [URI filename] documentation for additional information.\n*/\nSQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);\nSQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);\nSQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);\nSQLITE_API const char *sqlite3_uri_key(const char *zFilename, int N);\n\n/*\n** CAPI3REF:  Translate filenames\n**\n** These routines are available to [VFS|custom VFS implementations] for\n** translating filenames between the main database file, the journal file,\n** and the WAL file.\n**\n** If F is the name of an sqlite database file, journal file, or WAL file\n** passed by the SQLite core into the VFS, then sqlite3_filename_database(F)\n** returns the name of the corresponding database file.\n**\n** If F is the name of an sqlite database file, journal file, or WAL file\n** passed by the SQLite core into the VFS, or if F is a database filename\n** obtained from [sqlite3_db_filename()], then sqlite3_filename_journal(F)\n** returns the name of the corresponding rollback journal file.\n**\n** If F is the name of an sqlite database file, journal file, or WAL file\n** that was passed by the SQLite core into the VFS, or if F is a database\n** filename obtained from [sqlite3_db_filename()], then\n** sqlite3_filename_wal(F) returns the name of the corresponding\n** WAL file.\n**\n** In all of the above, if F is not the name of a database, journal or WAL\n** filename passed into the VFS from the SQLite core and F is not the\n** return value from [sqlite3_db_filename()], then the result is\n** undefined and is likely a memory access violation.\n*/\nSQLITE_API const char *sqlite3_filename_database(const char*);\nSQLITE_API const char *sqlite3_filename_journal(const char*);\nSQLITE_API const char *sqlite3_filename_wal(const char*);\n\n/*\n** CAPI3REF:  Database File Corresponding To A Journal\n**\n** ^If X is the name of a rollback or WAL-mode journal file that is\n** passed into the xOpen method of [sqlite3_vfs], then \n** sqlite3_database_file_object(X) returns a pointer to the [sqlite3_file]\n** object that represents the main database file.\n**\n** This routine is intended for use in custom [VFS] implementations\n** only.  It is not a general-purpose interface.\n** The argument sqlite3_file_object(X) must be a filename pointer that\n** has been passed into [sqlite3_vfs].xOpen method where the \n** flags parameter to xOpen contains one of the bits\n** [SQLITE_OPEN_MAIN_JOURNAL] or [SQLITE_OPEN_WAL].  Any other use\n** of this routine results in undefined and probably undesirable\n** behavior.\n*/\nSQLITE_API sqlite3_file *sqlite3_database_file_object(const char*);\n\n/*\n** CAPI3REF: Create and Destroy VFS Filenames\n**\n** These interfces are provided for use by [VFS shim] implementations and\n** are not useful outside of that context.\n**\n** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of\n** database filename D with corresponding journal file J and WAL file W and\n** with N URI parameters key/values pairs in the array P.  The result from\n** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that\n** is safe to pass to routines like:\n** <ul>\n** <li> [sqlite3_uri_parameter()],\n** <li> [sqlite3_uri_boolean()],\n** <li> [sqlite3_uri_int64()],\n** <li> [sqlite3_uri_key()], \n** <li> [sqlite3_filename_database()],\n** <li> [sqlite3_filename_journal()], or\n** <li> [sqlite3_filename_wal()].\n** </ul>\n** If a memory allocation error occurs, sqlite3_create_filename() might\n** return a NULL pointer.  The memory obtained from sqlite3_create_filename(X)\n** must be released by a corresponding call to sqlite3_free_filename(Y).\n**\n** The P parameter in sqlite3_create_filename(D,J,W,N,P) should be an array\n** of 2*N pointers to strings.  Each pair of pointers in this array corresponds\n** to a key and value for a query parameter.  The P parameter may be a NULL\n** pointer if N is zero.  None of the 2*N pointers in the P array may be\n** NULL pointers and key pointers should not be empty strings.\n** None of the D, J, or W parameters to sqlite3_create_filename(D,J,W,N,P) may\n** be NULL pointers, though they can be empty strings.\n**\n** The sqlite3_free_filename(Y) routine releases a memory allocation\n** previously obtained from sqlite3_create_filename().  Invoking\n** sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op.\n**\n** If the Y parameter to sqlite3_free_filename(Y) is anything other\n** than a NULL pointer or a pointer previously acquired from\n** sqlite3_create_filename(), then bad things such as heap\n** corruption or segfaults may occur. The value Y should be \n** used again after sqlite3_free_filename(Y) has been called.  This means\n** that if the [sqlite3_vfs.xOpen()] method of a VFS has been called using Y,\n** then the corresponding [sqlite3_module.xClose() method should also be\n** invoked prior to calling sqlite3_free_filename(Y).\n*/\nSQLITE_API char *sqlite3_create_filename(\n  const char *zDatabase,\n  const char *zJournal,\n  const char *zWal,\n  int nParam,\n  const char **azParam\n);\nSQLITE_API void sqlite3_free_filename(char*);\n\n/*\n** CAPI3REF: Error Codes And Messages\n** METHOD: sqlite3\n**\n** ^If the most recent sqlite3_* API call associated with \n** [database connection] D failed, then the sqlite3_errcode(D) interface\n** returns the numeric [result code] or [extended result code] for that\n** API call.\n** ^The sqlite3_extended_errcode()\n** interface is the same except that it always returns the \n** [extended result code] even when extended result codes are\n** disabled.\n**\n** The values returned by sqlite3_errcode() and/or\n** sqlite3_extended_errcode() might change with each API call.\n** Except, there are some interfaces that are guaranteed to never\n** change the value of the error code.  The error-code preserving\n** interfaces are:\n**\n** <ul>\n** <li> sqlite3_errcode()\n** <li> sqlite3_extended_errcode()\n** <li> sqlite3_errmsg()\n** <li> sqlite3_errmsg16()\n** </ul>\n**\n** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language\n** text that describes the error, as either UTF-8 or UTF-16 respectively.\n** ^(Memory to hold the error message string is managed internally.\n** The application does not need to worry about freeing the result.\n** However, the error string might be overwritten or deallocated by\n** subsequent calls to other SQLite interface functions.)^\n**\n** ^The sqlite3_errstr() interface returns the English-language text\n** that describes the [result code], as UTF-8.\n** ^(Memory to hold the error message string is managed internally\n** and must not be freed by the application)^.\n**\n** When the serialized [threading mode] is in use, it might be the\n** case that a second error occurs on a separate thread in between\n** the time of the first error and the call to these interfaces.\n** When that happens, the second error will be reported since these\n** interfaces always report the most recent result.  To avoid\n** this, each thread can obtain exclusive use of the [database connection] D\n** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning\n** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after\n** all calls to the interfaces listed here are completed.\n**\n** If an interface fails with SQLITE_MISUSE, that means the interface\n** was invoked incorrectly by the application.  In that case, the\n** error code and message may or may not be set.\n*/\nSQLITE_API int sqlite3_errcode(sqlite3 *db);\nSQLITE_API int sqlite3_extended_errcode(sqlite3 *db);\nSQLITE_API const char *sqlite3_errmsg(sqlite3*);\nSQLITE_API const void *sqlite3_errmsg16(sqlite3*);\nSQLITE_API const char *sqlite3_errstr(int);\n\n/*\n** CAPI3REF: Prepared Statement Object\n** KEYWORDS: {prepared statement} {prepared statements}\n**\n** An instance of this object represents a single SQL statement that\n** has been compiled into binary form and is ready to be evaluated.\n**\n** Think of each SQL statement as a separate computer program.  The\n** original SQL text is source code.  A prepared statement object \n** is the compiled object code.  All SQL must be converted into a\n** prepared statement before it can be run.\n**\n** The life-cycle of a prepared statement object usually goes like this:\n**\n** <ol>\n** <li> Create the prepared statement object using [sqlite3_prepare_v2()].\n** <li> Bind values to [parameters] using the sqlite3_bind_*()\n**      interfaces.\n** <li> Run the SQL by calling [sqlite3_step()] one or more times.\n** <li> Reset the prepared statement using [sqlite3_reset()] then go back\n**      to step 2.  Do this zero or more times.\n** <li> Destroy the object using [sqlite3_finalize()].\n** </ol>\n*/\ntypedef struct sqlite3_stmt sqlite3_stmt;\n\n/*\n** CAPI3REF: Run-time Limits\n** METHOD: sqlite3\n**\n** ^(This interface allows the size of various constructs to be limited\n** on a connection by connection basis.  The first parameter is the\n** [database connection] whose limit is to be set or queried.  The\n** second parameter is one of the [limit categories] that define a\n** class of constructs to be size limited.  The third parameter is the\n** new limit for that construct.)^\n**\n** ^If the new limit is a negative number, the limit is unchanged.\n** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a \n** [limits | hard upper bound]\n** set at compile-time by a C preprocessor macro called\n** [limits | SQLITE_MAX_<i>NAME</i>].\n** (The \"_LIMIT_\" in the name is changed to \"_MAX_\".))^\n** ^Attempts to increase a limit above its hard upper bound are\n** silently truncated to the hard upper bound.\n**\n** ^Regardless of whether or not the limit was changed, the \n** [sqlite3_limit()] interface returns the prior value of the limit.\n** ^Hence, to find the current value of a limit without changing it,\n** simply invoke this interface with the third parameter set to -1.\n**\n** Run-time limits are intended for use in applications that manage\n** both their own internal database and also databases that are controlled\n** by untrusted external sources.  An example application might be a\n** web browser that has its own databases for storing history and\n** separate databases controlled by JavaScript applications downloaded\n** off the Internet.  The internal databases can be given the\n** large, default limits.  Databases managed by external sources can\n** be given much smaller limits designed to prevent a denial of service\n** attack.  Developers might also want to use the [sqlite3_set_authorizer()]\n** interface to further control untrusted SQL.  The size of the database\n** created by an untrusted script can be contained using the\n** [max_page_count] [PRAGMA].\n**\n** New run-time limit categories may be added in future releases.\n*/\nSQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);\n\n/*\n** CAPI3REF: Run-Time Limit Categories\n** KEYWORDS: {limit category} {*limit categories}\n**\n** These constants define various performance limits\n** that can be lowered at run-time using [sqlite3_limit()].\n** The synopsis of the meanings of the various limits is shown below.\n** Additional information is available at [limits | Limits in SQLite].\n**\n** <dl>\n** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>\n** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^\n**\n** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>\n** <dd>The maximum length of an SQL statement, in bytes.</dd>)^\n**\n** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>\n** <dd>The maximum number of columns in a table definition or in the\n** result set of a [SELECT] or the maximum number of columns in an index\n** or in an ORDER BY or GROUP BY clause.</dd>)^\n**\n** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>\n** <dd>The maximum depth of the parse tree on any expression.</dd>)^\n**\n** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>\n** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^\n**\n** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>\n** <dd>The maximum number of instructions in a virtual machine program\n** used to implement an SQL statement.  If [sqlite3_prepare_v2()] or\n** the equivalent tries to allocate space for more than this many opcodes\n** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^\n**\n** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>\n** <dd>The maximum number of arguments on a function.</dd>)^\n**\n** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>\n** <dd>The maximum number of [ATTACH | attached databases].)^</dd>\n**\n** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]\n** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>\n** <dd>The maximum length of the pattern argument to the [LIKE] or\n** [GLOB] operators.</dd>)^\n**\n** [[SQLITE_LIMIT_VARIABLE_NUMBER]]\n** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>\n** <dd>The maximum index number of any [parameter] in an SQL statement.)^\n**\n** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>\n** <dd>The maximum depth of recursion for triggers.</dd>)^\n**\n** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>\n** <dd>The maximum number of auxiliary worker threads that a single\n** [prepared statement] may start.</dd>)^\n** </dl>\n*/\n#define SQLITE_LIMIT_LENGTH                    0\n#define SQLITE_LIMIT_SQL_LENGTH                1\n#define SQLITE_LIMIT_COLUMN                    2\n#define SQLITE_LIMIT_EXPR_DEPTH                3\n#define SQLITE_LIMIT_COMPOUND_SELECT           4\n#define SQLITE_LIMIT_VDBE_OP                   5\n#define SQLITE_LIMIT_FUNCTION_ARG              6\n#define SQLITE_LIMIT_ATTACHED                  7\n#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8\n#define SQLITE_LIMIT_VARIABLE_NUMBER           9\n#define SQLITE_LIMIT_TRIGGER_DEPTH            10\n#define SQLITE_LIMIT_WORKER_THREADS           11\n\n/*\n** CAPI3REF: Prepare Flags\n**\n** These constants define various flags that can be passed into\n** \"prepFlags\" parameter of the [sqlite3_prepare_v3()] and\n** [sqlite3_prepare16_v3()] interfaces.\n**\n** New flags may be added in future releases of SQLite.\n**\n** <dl>\n** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>\n** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner\n** that the prepared statement will be retained for a long time and\n** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]\n** and [sqlite3_prepare16_v3()] assume that the prepared statement will \n** be used just once or at most a few times and then destroyed using\n** [sqlite3_finalize()] relatively soon. The current implementation acts\n** on this hint by avoiding the use of [lookaside memory] so as not to\n** deplete the limited store of lookaside memory. Future versions of\n** SQLite may act on this hint differently.\n**\n** [[SQLITE_PREPARE_NORMALIZE]] <dt>SQLITE_PREPARE_NORMALIZE</dt>\n** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used\n** to be required for any prepared statement that wanted to use the\n** [sqlite3_normalized_sql()] interface.  However, the\n** [sqlite3_normalized_sql()] interface is now available to all\n** prepared statements, regardless of whether or not they use this\n** flag.\n**\n** [[SQLITE_PREPARE_NO_VTAB]] <dt>SQLITE_PREPARE_NO_VTAB</dt>\n** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler\n** to return an error (error code SQLITE_ERROR) if the statement uses\n** any virtual tables.\n** </dl>\n*/\n#define SQLITE_PREPARE_PERSISTENT              0x01\n#define SQLITE_PREPARE_NORMALIZE               0x02\n#define SQLITE_PREPARE_NO_VTAB                 0x04\n\n/*\n** CAPI3REF: Compiling An SQL Statement\n** KEYWORDS: {SQL statement compiler}\n** METHOD: sqlite3\n** CONSTRUCTOR: sqlite3_stmt\n**\n** To execute an SQL statement, it must first be compiled into a byte-code\n** program using one of these routines.  Or, in other words, these routines\n** are constructors for the [prepared statement] object.\n**\n** The preferred routine to use is [sqlite3_prepare_v2()].  The\n** [sqlite3_prepare()] interface is legacy and should be avoided.\n** [sqlite3_prepare_v3()] has an extra \"prepFlags\" option that is used\n** for special purposes.\n**\n** The use of the UTF-8 interfaces is preferred, as SQLite currently\n** does all parsing using UTF-8.  The UTF-16 interfaces are provided\n** as a convenience.  The UTF-16 interfaces work by converting the\n** input text into UTF-8, then invoking the corresponding UTF-8 interface.\n**\n** The first argument, \"db\", is a [database connection] obtained from a\n** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or\n** [sqlite3_open16()].  The database connection must not have been closed.\n**\n** The second argument, \"zSql\", is the statement to be compiled, encoded\n** as either UTF-8 or UTF-16.  The sqlite3_prepare(), sqlite3_prepare_v2(),\n** and sqlite3_prepare_v3()\n** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),\n** and sqlite3_prepare16_v3() use UTF-16.\n**\n** ^If the nByte argument is negative, then zSql is read up to the\n** first zero terminator. ^If nByte is positive, then it is the\n** number of bytes read from zSql.  ^If nByte is zero, then no prepared\n** statement is generated.\n** If the caller knows that the supplied string is nul-terminated, then\n** there is a small performance advantage to passing an nByte parameter that\n** is the number of bytes in the input string <i>including</i>\n** the nul-terminator.\n**\n** ^If pzTail is not NULL then *pzTail is made to point to the first byte\n** past the end of the first SQL statement in zSql.  These routines only\n** compile the first statement in zSql, so *pzTail is left pointing to\n** what remains uncompiled.\n**\n** ^*ppStmt is left pointing to a compiled [prepared statement] that can be\n** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set\n** to NULL.  ^If the input text contains no SQL (if the input is an empty\n** string or a comment) then *ppStmt is set to NULL.\n** The calling procedure is responsible for deleting the compiled\n** SQL statement using [sqlite3_finalize()] after it has finished with it.\n** ppStmt may not be NULL.\n**\n** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];\n** otherwise an [error code] is returned.\n**\n** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),\n** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.\n** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())\n** are retained for backwards compatibility, but their use is discouraged.\n** ^In the \"vX\" interfaces, the prepared statement\n** that is returned (the [sqlite3_stmt] object) contains a copy of the\n** original SQL text. This causes the [sqlite3_step()] interface to\n** behave differently in three ways:\n**\n** <ol>\n** <li>\n** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it\n** always used to do, [sqlite3_step()] will automatically recompile the SQL\n** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]\n** retries will occur before sqlite3_step() gives up and returns an error.\n** </li>\n**\n** <li>\n** ^When an error occurs, [sqlite3_step()] will return one of the detailed\n** [error codes] or [extended error codes].  ^The legacy behavior was that\n** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code\n** and the application would have to make a second call to [sqlite3_reset()]\n** in order to find the underlying cause of the problem. With the \"v2\" prepare\n** interfaces, the underlying reason for the error is returned immediately.\n** </li>\n**\n** <li>\n** ^If the specific value bound to a [parameter | host parameter] in the \n** WHERE clause might influence the choice of query plan for a statement,\n** then the statement will be automatically recompiled, as if there had been \n** a schema change, on the first [sqlite3_step()] call following any change\n** to the [sqlite3_bind_text | bindings] of that [parameter]. \n** ^The specific value of a WHERE-clause [parameter] might influence the \n** choice of query plan if the parameter is the left-hand side of a [LIKE]\n** or [GLOB] operator or if the parameter is compared to an indexed column\n** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled.\n** </li>\n** </ol>\n**\n** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having\n** the extra prepFlags parameter, which is a bit array consisting of zero or\n** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags.  ^The\n** sqlite3_prepare_v2() interface works exactly the same as\n** sqlite3_prepare_v3() with a zero prepFlags parameter.\n*/\nSQLITE_API int sqlite3_prepare(\n  sqlite3 *db,            /* Database handle */\n  const char *zSql,       /* SQL statement, UTF-8 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const char **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\nSQLITE_API int sqlite3_prepare_v2(\n  sqlite3 *db,            /* Database handle */\n  const char *zSql,       /* SQL statement, UTF-8 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const char **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\nSQLITE_API int sqlite3_prepare_v3(\n  sqlite3 *db,            /* Database handle */\n  const char *zSql,       /* SQL statement, UTF-8 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const char **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\nSQLITE_API int sqlite3_prepare16(\n  sqlite3 *db,            /* Database handle */\n  const void *zSql,       /* SQL statement, UTF-16 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const void **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\nSQLITE_API int sqlite3_prepare16_v2(\n  sqlite3 *db,            /* Database handle */\n  const void *zSql,       /* SQL statement, UTF-16 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const void **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\nSQLITE_API int sqlite3_prepare16_v3(\n  sqlite3 *db,            /* Database handle */\n  const void *zSql,       /* SQL statement, UTF-16 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const void **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\n\n/*\n** CAPI3REF: Retrieving Statement SQL\n** METHOD: sqlite3_stmt\n**\n** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8\n** SQL text used to create [prepared statement] P if P was\n** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],\n** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].\n** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8\n** string containing the SQL text of prepared statement P with\n** [bound parameters] expanded.\n** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8\n** string containing the normalized SQL text of prepared statement P.  The\n** semantics used to normalize a SQL statement are unspecified and subject\n** to change.  At a minimum, literal values will be replaced with suitable\n** placeholders.\n**\n** ^(For example, if a prepared statement is created using the SQL\n** text \"SELECT $abc,:xyz\" and if parameter $abc is bound to integer 2345\n** and parameter :xyz is unbound, then sqlite3_sql() will return\n** the original string, \"SELECT $abc,:xyz\" but sqlite3_expanded_sql()\n** will return \"SELECT 2345,NULL\".)^\n**\n** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory\n** is available to hold the result, or if the result would exceed the\n** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].\n**\n** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of\n** bound parameter expansions.  ^The [SQLITE_OMIT_TRACE] compile-time\n** option causes sqlite3_expanded_sql() to always return NULL.\n**\n** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P)\n** are managed by SQLite and are automatically freed when the prepared\n** statement is finalized.\n** ^The string returned by sqlite3_expanded_sql(P), on the other hand,\n** is obtained from [sqlite3_malloc()] and must be free by the application\n** by passing it to [sqlite3_free()].\n*/\nSQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);\nSQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);\nSQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Determine If An SQL Statement Writes The Database\n** METHOD: sqlite3_stmt\n**\n** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if\n** and only if the [prepared statement] X makes no direct changes to\n** the content of the database file.\n**\n** Note that [application-defined SQL functions] or\n** [virtual tables] might change the database indirectly as a side effect.  \n** ^(For example, if an application defines a function \"eval()\" that \n** calls [sqlite3_exec()], then the following SQL statement would\n** change the database file through side-effects:\n**\n** <blockquote><pre>\n**    SELECT eval('DELETE FROM t1') FROM t2;\n** </pre></blockquote>\n**\n** But because the [SELECT] statement does not change the database file\n** directly, sqlite3_stmt_readonly() would still return true.)^\n**\n** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],\n** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,\n** since the statements themselves do not actually modify the database but\n** rather they control the timing of when other statements modify the \n** database.  ^The [ATTACH] and [DETACH] statements also cause\n** sqlite3_stmt_readonly() to return true since, while those statements\n** change the configuration of a database connection, they do not make \n** changes to the content of the database files on disk.\n** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since\n** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and\n** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so\n** sqlite3_stmt_readonly() returns false for those commands.\n*/\nSQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement\n** METHOD: sqlite3_stmt\n**\n** ^The sqlite3_stmt_isexplain(S) interface returns 1 if the\n** prepared statement S is an EXPLAIN statement, or 2 if the\n** statement S is an EXPLAIN QUERY PLAN.\n** ^The sqlite3_stmt_isexplain(S) interface returns 0 if S is\n** an ordinary statement or a NULL pointer.\n*/\nSQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Determine If A Prepared Statement Has Been Reset\n** METHOD: sqlite3_stmt\n**\n** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the\n** [prepared statement] S has been stepped at least once using \n** [sqlite3_step(S)] but has neither run to completion (returned\n** [SQLITE_DONE] from [sqlite3_step(S)]) nor\n** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)\n** interface returns false if S is a NULL pointer.  If S is not a \n** NULL pointer and is not a pointer to a valid [prepared statement]\n** object, then the behavior is undefined and probably undesirable.\n**\n** This interface can be used in combination [sqlite3_next_stmt()]\n** to locate all prepared statements associated with a database \n** connection that are in need of being reset.  This can be used,\n** for example, in diagnostic routines to search for prepared \n** statements that are holding a transaction open.\n*/\nSQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Dynamically Typed Value Object\n** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}\n**\n** SQLite uses the sqlite3_value object to represent all values\n** that can be stored in a database table. SQLite uses dynamic typing\n** for the values it stores.  ^Values stored in sqlite3_value objects\n** can be integers, floating point values, strings, BLOBs, or NULL.\n**\n** An sqlite3_value object may be either \"protected\" or \"unprotected\".\n** Some interfaces require a protected sqlite3_value.  Other interfaces\n** will accept either a protected or an unprotected sqlite3_value.\n** Every interface that accepts sqlite3_value arguments specifies\n** whether or not it requires a protected sqlite3_value.  The\n** [sqlite3_value_dup()] interface can be used to construct a new \n** protected sqlite3_value from an unprotected sqlite3_value.\n**\n** The terms \"protected\" and \"unprotected\" refer to whether or not\n** a mutex is held.  An internal mutex is held for a protected\n** sqlite3_value object but no mutex is held for an unprotected\n** sqlite3_value object.  If SQLite is compiled to be single-threaded\n** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)\n** or if SQLite is run in one of reduced mutex modes \n** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]\n** then there is no distinction between protected and unprotected\n** sqlite3_value objects and they can be used interchangeably.  However,\n** for maximum code portability it is recommended that applications\n** still make the distinction between protected and unprotected\n** sqlite3_value objects even when not strictly required.\n**\n** ^The sqlite3_value objects that are passed as parameters into the\n** implementation of [application-defined SQL functions] are protected.\n** ^The sqlite3_value object returned by\n** [sqlite3_column_value()] is unprotected.\n** Unprotected sqlite3_value objects may only be used as arguments\n** to [sqlite3_result_value()], [sqlite3_bind_value()], and\n** [sqlite3_value_dup()].\n** The [sqlite3_value_blob | sqlite3_value_type()] family of\n** interfaces require protected sqlite3_value objects.\n*/\ntypedef struct sqlite3_value sqlite3_value;\n\n/*\n** CAPI3REF: SQL Function Context Object\n**\n** The context in which an SQL function executes is stored in an\n** sqlite3_context object.  ^A pointer to an sqlite3_context object\n** is always first parameter to [application-defined SQL functions].\n** The application-defined SQL function implementation will pass this\n** pointer through into calls to [sqlite3_result_int | sqlite3_result()],\n** [sqlite3_aggregate_context()], [sqlite3_user_data()],\n** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],\n** and/or [sqlite3_set_auxdata()].\n*/\ntypedef struct sqlite3_context sqlite3_context;\n\n/*\n** CAPI3REF: Binding Values To Prepared Statements\n** KEYWORDS: {host parameter} {host parameters} {host parameter name}\n** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}\n** METHOD: sqlite3_stmt\n**\n** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,\n** literals may be replaced by a [parameter] that matches one of following\n** templates:\n**\n** <ul>\n** <li>  ?\n** <li>  ?NNN\n** <li>  :VVV\n** <li>  @VVV\n** <li>  $VVV\n** </ul>\n**\n** In the templates above, NNN represents an integer literal,\n** and VVV represents an alphanumeric identifier.)^  ^The values of these\n** parameters (also called \"host parameter names\" or \"SQL parameters\")\n** can be set using the sqlite3_bind_*() routines defined here.\n**\n** ^The first argument to the sqlite3_bind_*() routines is always\n** a pointer to the [sqlite3_stmt] object returned from\n** [sqlite3_prepare_v2()] or its variants.\n**\n** ^The second argument is the index of the SQL parameter to be set.\n** ^The leftmost SQL parameter has an index of 1.  ^When the same named\n** SQL parameter is used more than once, second and subsequent\n** occurrences have the same index as the first occurrence.\n** ^The index for named parameters can be looked up using the\n** [sqlite3_bind_parameter_index()] API if desired.  ^The index\n** for \"?NNN\" parameters is the value of NNN.\n** ^The NNN value must be between 1 and the [sqlite3_limit()]\n** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 32766).\n**\n** ^The third argument is the value to bind to the parameter.\n** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()\n** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter\n** is ignored and the end result is the same as sqlite3_bind_null().\n** ^If the third parameter to sqlite3_bind_text() is not NULL, then\n** it should be a pointer to well-formed UTF8 text.\n** ^If the third parameter to sqlite3_bind_text16() is not NULL, then\n** it should be a pointer to well-formed UTF16 text.\n** ^If the third parameter to sqlite3_bind_text64() is not NULL, then\n** it should be a pointer to a well-formed unicode string that is\n** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF16\n** otherwise.\n**\n** [[byte-order determination rules]] ^The byte-order of\n** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF)\n** found in first character, which is removed, or in the absence of a BOM\n** the byte order is the native byte order of the host\n** machine for sqlite3_bind_text16() or the byte order specified in\n** the 6th parameter for sqlite3_bind_text64().)^ \n** ^If UTF16 input text contains invalid unicode\n** characters, then SQLite might change those invalid characters\n** into the unicode replacement character: U+FFFD.\n**\n** ^(In those routines that have a fourth argument, its value is the\n** number of bytes in the parameter.  To be clear: the value is the\n** number of <u>bytes</u> in the value, not the number of characters.)^\n** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()\n** is negative, then the length of the string is\n** the number of bytes up to the first zero terminator.\n** If the fourth parameter to sqlite3_bind_blob() is negative, then\n** the behavior is undefined.\n** If a non-negative fourth parameter is provided to sqlite3_bind_text()\n** or sqlite3_bind_text16() or sqlite3_bind_text64() then\n** that parameter must be the byte offset\n** where the NUL terminator would occur assuming the string were NUL\n** terminated.  If any NUL characters occurs at byte offsets less than \n** the value of the fourth parameter then the resulting string value will\n** contain embedded NULs.  The result of expressions involving strings\n** with embedded NULs is undefined.\n**\n** ^The fifth argument to the BLOB and string binding interfaces\n** is a destructor used to dispose of the BLOB or\n** string after SQLite has finished with it.  ^The destructor is called\n** to dispose of the BLOB or string even if the call to the bind API fails,\n** except the destructor is not called if the third parameter is a NULL\n** pointer or the fourth parameter is negative.\n** ^If the fifth argument is\n** the special value [SQLITE_STATIC], then SQLite assumes that the\n** information is in static, unmanaged space and does not need to be freed.\n** ^If the fifth argument has the value [SQLITE_TRANSIENT], then\n** SQLite makes its own private copy of the data immediately, before\n** the sqlite3_bind_*() routine returns.\n**\n** ^The sixth argument to sqlite3_bind_text64() must be one of\n** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]\n** to specify the encoding of the text in the third parameter.  If\n** the sixth argument to sqlite3_bind_text64() is not one of the\n** allowed values shown above, or if the text encoding is different\n** from the encoding specified by the sixth parameter, then the behavior\n** is undefined.\n**\n** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that\n** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory\n** (just an integer to hold its size) while it is being processed.\n** Zeroblobs are intended to serve as placeholders for BLOBs whose\n** content is later written using\n** [sqlite3_blob_open | incremental BLOB I/O] routines.\n** ^A negative value for the zeroblob results in a zero-length BLOB.\n**\n** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in\n** [prepared statement] S to have an SQL value of NULL, but to also be\n** associated with the pointer P of type T.  ^D is either a NULL pointer or\n** a pointer to a destructor function for P. ^SQLite will invoke the\n** destructor D with a single argument of P when it is finished using\n** P.  The T parameter should be a static string, preferably a string\n** literal. The sqlite3_bind_pointer() routine is part of the\n** [pointer passing interface] added for SQLite 3.20.0.\n**\n** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer\n** for the [prepared statement] or with a prepared statement for which\n** [sqlite3_step()] has been called more recently than [sqlite3_reset()],\n** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()\n** routine is passed a [prepared statement] that has been finalized, the\n** result is undefined and probably harmful.\n**\n** ^Bindings are not cleared by the [sqlite3_reset()] routine.\n** ^Unbound parameters are interpreted as NULL.\n**\n** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an\n** [error code] if anything goes wrong.\n** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB\n** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or\n** [SQLITE_MAX_LENGTH].\n** ^[SQLITE_RANGE] is returned if the parameter\n** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.\n**\n** See also: [sqlite3_bind_parameter_count()],\n** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].\n*/\nSQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));\nSQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,\n                        void(*)(void*));\nSQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);\nSQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);\nSQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);\nSQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);\nSQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));\nSQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));\nSQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,\n                         void(*)(void*), unsigned char encoding);\nSQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);\nSQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));\nSQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);\nSQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);\n\n/*\n** CAPI3REF: Number Of SQL Parameters\n** METHOD: sqlite3_stmt\n**\n** ^This routine can be used to find the number of [SQL parameters]\n** in a [prepared statement].  SQL parameters are tokens of the\n** form \"?\", \"?NNN\", \":AAA\", \"$AAA\", or \"@AAA\" that serve as\n** placeholders for values that are [sqlite3_bind_blob | bound]\n** to the parameters at a later time.\n**\n** ^(This routine actually returns the index of the largest (rightmost)\n** parameter. For all forms except ?NNN, this will correspond to the\n** number of unique parameters.  If parameters of the ?NNN form are used,\n** there may be gaps in the list.)^\n**\n** See also: [sqlite3_bind_blob|sqlite3_bind()],\n** [sqlite3_bind_parameter_name()], and\n** [sqlite3_bind_parameter_index()].\n*/\nSQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Name Of A Host Parameter\n** METHOD: sqlite3_stmt\n**\n** ^The sqlite3_bind_parameter_name(P,N) interface returns\n** the name of the N-th [SQL parameter] in the [prepared statement] P.\n** ^(SQL parameters of the form \"?NNN\" or \":AAA\" or \"@AAA\" or \"$AAA\"\n** have a name which is the string \"?NNN\" or \":AAA\" or \"@AAA\" or \"$AAA\"\n** respectively.\n** In other words, the initial \":\" or \"$\" or \"@\" or \"?\"\n** is included as part of the name.)^\n** ^Parameters of the form \"?\" without a following integer have no name\n** and are referred to as \"nameless\" or \"anonymous parameters\".\n**\n** ^The first host parameter has an index of 1, not 0.\n**\n** ^If the value N is out of range or if the N-th parameter is\n** nameless, then NULL is returned.  ^The returned string is\n** always in UTF-8 encoding even if the named parameter was\n** originally specified as UTF-16 in [sqlite3_prepare16()],\n** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].\n**\n** See also: [sqlite3_bind_blob|sqlite3_bind()],\n** [sqlite3_bind_parameter_count()], and\n** [sqlite3_bind_parameter_index()].\n*/\nSQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);\n\n/*\n** CAPI3REF: Index Of A Parameter With A Given Name\n** METHOD: sqlite3_stmt\n**\n** ^Return the index of an SQL parameter given its name.  ^The\n** index value returned is suitable for use as the second\n** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero\n** is returned if no matching parameter is found.  ^The parameter\n** name must be given in UTF-8 even if the original statement\n** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or\n** [sqlite3_prepare16_v3()].\n**\n** See also: [sqlite3_bind_blob|sqlite3_bind()],\n** [sqlite3_bind_parameter_count()], and\n** [sqlite3_bind_parameter_name()].\n*/\nSQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);\n\n/*\n** CAPI3REF: Reset All Bindings On A Prepared Statement\n** METHOD: sqlite3_stmt\n**\n** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset\n** the [sqlite3_bind_blob | bindings] on a [prepared statement].\n** ^Use this routine to reset all host parameters to NULL.\n*/\nSQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Number Of Columns In A Result Set\n** METHOD: sqlite3_stmt\n**\n** ^Return the number of columns in the result set returned by the\n** [prepared statement]. ^If this routine returns 0, that means the \n** [prepared statement] returns no data (for example an [UPDATE]).\n** ^However, just because this routine returns a positive number does not\n** mean that one or more rows of data will be returned.  ^A SELECT statement\n** will always have a positive sqlite3_column_count() but depending on the\n** WHERE clause constraints and the table content, it might return no rows.\n**\n** See also: [sqlite3_data_count()]\n*/\nSQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Column Names In A Result Set\n** METHOD: sqlite3_stmt\n**\n** ^These routines return the name assigned to a particular column\n** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()\n** interface returns a pointer to a zero-terminated UTF-8 string\n** and sqlite3_column_name16() returns a pointer to a zero-terminated\n** UTF-16 string.  ^The first parameter is the [prepared statement]\n** that implements the [SELECT] statement. ^The second parameter is the\n** column number.  ^The leftmost column is number 0.\n**\n** ^The returned string pointer is valid until either the [prepared statement]\n** is destroyed by [sqlite3_finalize()] or until the statement is automatically\n** reprepared by the first call to [sqlite3_step()] for a particular run\n** or until the next call to\n** sqlite3_column_name() or sqlite3_column_name16() on the same column.\n**\n** ^If sqlite3_malloc() fails during the processing of either routine\n** (for example during a conversion from UTF-8 to UTF-16) then a\n** NULL pointer is returned.\n**\n** ^The name of a result column is the value of the \"AS\" clause for\n** that column, if there is an AS clause.  If there is no AS clause\n** then the name of the column is unspecified and may change from\n** one release of SQLite to the next.\n*/\nSQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);\nSQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);\n\n/*\n** CAPI3REF: Source Of Data In A Query Result\n** METHOD: sqlite3_stmt\n**\n** ^These routines provide a means to determine the database, table, and\n** table column that is the origin of a particular result column in\n** [SELECT] statement.\n** ^The name of the database or table or column can be returned as\n** either a UTF-8 or UTF-16 string.  ^The _database_ routines return\n** the database name, the _table_ routines return the table name, and\n** the origin_ routines return the column name.\n** ^The returned string is valid until the [prepared statement] is destroyed\n** using [sqlite3_finalize()] or until the statement is automatically\n** reprepared by the first call to [sqlite3_step()] for a particular run\n** or until the same information is requested\n** again in a different encoding.\n**\n** ^The names returned are the original un-aliased names of the\n** database, table, and column.\n**\n** ^The first argument to these interfaces is a [prepared statement].\n** ^These functions return information about the Nth result column returned by\n** the statement, where N is the second function argument.\n** ^The left-most column is column 0 for these routines.\n**\n** ^If the Nth column returned by the statement is an expression or\n** subquery and is not a column value, then all of these functions return\n** NULL.  ^These routines might also return NULL if a memory allocation error\n** occurs.  ^Otherwise, they return the name of the attached database, table,\n** or column that query result column was extracted from.\n**\n** ^As with all other SQLite APIs, those whose names end with \"16\" return\n** UTF-16 encoded strings and the other functions return UTF-8.\n**\n** ^These APIs are only available if the library was compiled with the\n** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.\n**\n** If two or more threads call one or more\n** [sqlite3_column_database_name | column metadata interfaces]\n** for the same [prepared statement] and result column\n** at the same time then the results are undefined.\n*/\nSQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);\nSQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);\nSQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);\nSQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);\nSQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);\nSQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);\n\n/*\n** CAPI3REF: Declared Datatype Of A Query Result\n** METHOD: sqlite3_stmt\n**\n** ^(The first parameter is a [prepared statement].\n** If this statement is a [SELECT] statement and the Nth column of the\n** returned result set of that [SELECT] is a table column (not an\n** expression or subquery) then the declared type of the table\n** column is returned.)^  ^If the Nth column of the result set is an\n** expression or subquery, then a NULL pointer is returned.\n** ^The returned string is always UTF-8 encoded.\n**\n** ^(For example, given the database schema:\n**\n** CREATE TABLE t1(c1 VARIANT);\n**\n** and the following statement to be compiled:\n**\n** SELECT c1 + 1, c1 FROM t1;\n**\n** this routine would return the string \"VARIANT\" for the second result\n** column (i==1), and a NULL pointer for the first result column (i==0).)^\n**\n** ^SQLite uses dynamic run-time typing.  ^So just because a column\n** is declared to contain a particular type does not mean that the\n** data stored in that column is of the declared type.  SQLite is\n** strongly typed, but the typing is dynamic not static.  ^Type\n** is associated with individual values, not with the containers\n** used to hold those values.\n*/\nSQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);\nSQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);\n\n/*\n** CAPI3REF: Evaluate An SQL Statement\n** METHOD: sqlite3_stmt\n**\n** After a [prepared statement] has been prepared using any of\n** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],\n** or [sqlite3_prepare16_v3()] or one of the legacy\n** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function\n** must be called one or more times to evaluate the statement.\n**\n** The details of the behavior of the sqlite3_step() interface depend\n** on whether the statement was prepared using the newer \"vX\" interfaces\n** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],\n** [sqlite3_prepare16_v2()] or the older legacy\n** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the\n** new \"vX\" interface is recommended for new applications but the legacy\n** interface will continue to be supported.\n**\n** ^In the legacy interface, the return value will be either [SQLITE_BUSY],\n** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].\n** ^With the \"v2\" interface, any of the other [result codes] or\n** [extended result codes] might be returned as well.\n**\n** ^[SQLITE_BUSY] means that the database engine was unable to acquire the\n** database locks it needs to do its job.  ^If the statement is a [COMMIT]\n** or occurs outside of an explicit transaction, then you can retry the\n** statement.  If the statement is not a [COMMIT] and occurs within an\n** explicit transaction then you should rollback the transaction before\n** continuing.\n**\n** ^[SQLITE_DONE] means that the statement has finished executing\n** successfully.  sqlite3_step() should not be called again on this virtual\n** machine without first calling [sqlite3_reset()] to reset the virtual\n** machine back to its initial state.\n**\n** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]\n** is returned each time a new row of data is ready for processing by the\n** caller. The values may be accessed using the [column access functions].\n** sqlite3_step() is called again to retrieve the next row of data.\n**\n** ^[SQLITE_ERROR] means that a run-time error (such as a constraint\n** violation) has occurred.  sqlite3_step() should not be called again on\n** the VM. More information may be found by calling [sqlite3_errmsg()].\n** ^With the legacy interface, a more specific error code (for example,\n** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)\n** can be obtained by calling [sqlite3_reset()] on the\n** [prepared statement].  ^In the \"v2\" interface,\n** the more specific error code is returned directly by sqlite3_step().\n**\n** [SQLITE_MISUSE] means that the this routine was called inappropriately.\n** Perhaps it was called on a [prepared statement] that has\n** already been [sqlite3_finalize | finalized] or on one that had\n** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could\n** be the case that the same database connection is being used by two or\n** more threads at the same moment in time.\n**\n** For all versions of SQLite up to and including 3.6.23.1, a call to\n** [sqlite3_reset()] was required after sqlite3_step() returned anything\n** other than [SQLITE_ROW] before any subsequent invocation of\n** sqlite3_step().  Failure to reset the prepared statement using \n** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from\n** sqlite3_step().  But after [version 3.6.23.1] ([dateof:3.6.23.1],\n** sqlite3_step() began\n** calling [sqlite3_reset()] automatically in this circumstance rather\n** than returning [SQLITE_MISUSE].  This is not considered a compatibility\n** break because any application that ever receives an SQLITE_MISUSE error\n** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option\n** can be used to restore the legacy behavior.\n**\n** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()\n** API always returns a generic error code, [SQLITE_ERROR], following any\n** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call\n** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the\n** specific [error codes] that better describes the error.\n** We admit that this is a goofy design.  The problem has been fixed\n** with the \"v2\" interface.  If you prepare all of your SQL statements\n** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]\n** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead\n** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,\n** then the more specific [error codes] are returned directly\n** by sqlite3_step().  The use of the \"vX\" interfaces is recommended.\n*/\nSQLITE_API int sqlite3_step(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Number of columns in a result set\n** METHOD: sqlite3_stmt\n**\n** ^The sqlite3_data_count(P) interface returns the number of columns in the\n** current row of the result set of [prepared statement] P.\n** ^If prepared statement P does not have results ready to return\n** (via calls to the [sqlite3_column_int | sqlite3_column()] family of\n** interfaces) then sqlite3_data_count(P) returns 0.\n** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.\n** ^The sqlite3_data_count(P) routine returns 0 if the previous call to\n** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)\n** will return non-zero if previous call to [sqlite3_step](P) returned\n** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]\n** where it always returns zero since each step of that multi-step\n** pragma returns 0 columns of data.\n**\n** See also: [sqlite3_column_count()]\n*/\nSQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Fundamental Datatypes\n** KEYWORDS: SQLITE_TEXT\n**\n** ^(Every value in SQLite has one of five fundamental datatypes:\n**\n** <ul>\n** <li> 64-bit signed integer\n** <li> 64-bit IEEE floating point number\n** <li> string\n** <li> BLOB\n** <li> NULL\n** </ul>)^\n**\n** These constants are codes for each of those types.\n**\n** Note that the SQLITE_TEXT constant was also used in SQLite version 2\n** for a completely different meaning.  Software that links against both\n** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not\n** SQLITE_TEXT.\n*/\n#define SQLITE_INTEGER  1\n#define SQLITE_FLOAT    2\n#define SQLITE_BLOB     4\n#define SQLITE_NULL     5\n#ifdef SQLITE_TEXT\n# undef SQLITE_TEXT\n#else\n# define SQLITE_TEXT     3\n#endif\n#define SQLITE3_TEXT     3\n\n/*\n** CAPI3REF: Result Values From A Query\n** KEYWORDS: {column access functions}\n** METHOD: sqlite3_stmt\n**\n** <b>Summary:</b>\n** <blockquote><table border=0 cellpadding=0 cellspacing=0>\n** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result\n** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result\n** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result\n** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result\n** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result\n** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result\n** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an \n** [sqlite3_value|unprotected sqlite3_value] object.\n** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;\n** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB\n** or a UTF-8 TEXT result in bytes\n** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>\n** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16\n** TEXT in bytes\n** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default\n** datatype of the result\n** </table></blockquote>\n**\n** <b>Details:</b>\n**\n** ^These routines return information about a single column of the current\n** result row of a query.  ^In every case the first argument is a pointer\n** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]\n** that was returned from [sqlite3_prepare_v2()] or one of its variants)\n** and the second argument is the index of the column for which information\n** should be returned. ^The leftmost column of the result set has the index 0.\n** ^The number of columns in the result can be determined using\n** [sqlite3_column_count()].\n**\n** If the SQL statement does not currently point to a valid row, or if the\n** column index is out of range, the result is undefined.\n** These routines may only be called when the most recent call to\n** [sqlite3_step()] has returned [SQLITE_ROW] and neither\n** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.\n** If any of these routines are called after [sqlite3_reset()] or\n** [sqlite3_finalize()] or after [sqlite3_step()] has returned\n** something other than [SQLITE_ROW], the results are undefined.\n** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]\n** are called from a different thread while any of these routines\n** are pending, then the results are undefined.\n**\n** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)\n** each return the value of a result column in a specific data format.  If\n** the result column is not initially in the requested format (for example,\n** if the query returns an integer but the sqlite3_column_text() interface\n** is used to extract the value) then an automatic type conversion is performed.\n**\n** ^The sqlite3_column_type() routine returns the\n** [SQLITE_INTEGER | datatype code] for the initial data type\n** of the result column.  ^The returned value is one of [SQLITE_INTEGER],\n** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].\n** The return value of sqlite3_column_type() can be used to decide which\n** of the first six interface should be used to extract the column value.\n** The value returned by sqlite3_column_type() is only meaningful if no\n** automatic type conversions have occurred for the value in question.  \n** After a type conversion, the result of calling sqlite3_column_type()\n** is undefined, though harmless.  Future\n** versions of SQLite may change the behavior of sqlite3_column_type()\n** following a type conversion.\n**\n** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()\n** or sqlite3_column_bytes16() interfaces can be used to determine the size\n** of that BLOB or string.\n**\n** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()\n** routine returns the number of bytes in that BLOB or string.\n** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts\n** the string to UTF-8 and then returns the number of bytes.\n** ^If the result is a numeric value then sqlite3_column_bytes() uses\n** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns\n** the number of bytes in that string.\n** ^If the result is NULL, then sqlite3_column_bytes() returns zero.\n**\n** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()\n** routine returns the number of bytes in that BLOB or string.\n** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts\n** the string to UTF-16 and then returns the number of bytes.\n** ^If the result is a numeric value then sqlite3_column_bytes16() uses\n** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns\n** the number of bytes in that string.\n** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.\n**\n** ^The values returned by [sqlite3_column_bytes()] and \n** [sqlite3_column_bytes16()] do not include the zero terminators at the end\n** of the string.  ^For clarity: the values returned by\n** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of\n** bytes in the string, not the number of characters.\n**\n** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),\n** even empty strings, are always zero-terminated.  ^The return\n** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.\n**\n** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an\n** [unprotected sqlite3_value] object.  In a multithreaded environment,\n** an unprotected sqlite3_value object may only be used safely with\n** [sqlite3_bind_value()] and [sqlite3_result_value()].\n** If the [unprotected sqlite3_value] object returned by\n** [sqlite3_column_value()] is used in any other way, including calls\n** to routines like [sqlite3_value_int()], [sqlite3_value_text()],\n** or [sqlite3_value_bytes()], the behavior is not threadsafe.\n** Hence, the sqlite3_column_value() interface\n** is normally only useful within the implementation of \n** [application-defined SQL functions] or [virtual tables], not within\n** top-level application code.\n**\n** The these routines may attempt to convert the datatype of the result.\n** ^For example, if the internal representation is FLOAT and a text result\n** is requested, [sqlite3_snprintf()] is used internally to perform the\n** conversion automatically.  ^(The following table details the conversions\n** that are applied:\n**\n** <blockquote>\n** <table border=\"1\">\n** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion\n**\n** <tr><td>  NULL    <td> INTEGER   <td> Result is 0\n** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0\n** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer\n** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer\n** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float\n** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer\n** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT\n** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER\n** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float\n** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB\n** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER\n** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL\n** <tr><td>  TEXT    <td>   BLOB    <td> No change\n** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER\n** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL\n** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed\n** </table>\n** </blockquote>)^\n**\n** Note that when type conversions occur, pointers returned by prior\n** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or\n** sqlite3_column_text16() may be invalidated.\n** Type conversions and pointer invalidations might occur\n** in the following cases:\n**\n** <ul>\n** <li> The initial content is a BLOB and sqlite3_column_text() or\n**      sqlite3_column_text16() is called.  A zero-terminator might\n**      need to be added to the string.</li>\n** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or\n**      sqlite3_column_text16() is called.  The content must be converted\n**      to UTF-16.</li>\n** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or\n**      sqlite3_column_text() is called.  The content must be converted\n**      to UTF-8.</li>\n** </ul>\n**\n** ^Conversions between UTF-16be and UTF-16le are always done in place and do\n** not invalidate a prior pointer, though of course the content of the buffer\n** that the prior pointer references will have been modified.  Other kinds\n** of conversion are done in place when it is possible, but sometimes they\n** are not possible and in those cases prior pointers are invalidated.\n**\n** The safest policy is to invoke these routines\n** in one of the following ways:\n**\n** <ul>\n**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>\n**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>\n**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>\n** </ul>\n**\n** In other words, you should call sqlite3_column_text(),\n** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result\n** into the desired format, then invoke sqlite3_column_bytes() or\n** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls\n** to sqlite3_column_text() or sqlite3_column_blob() with calls to\n** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()\n** with calls to sqlite3_column_bytes().\n**\n** ^The pointers returned are valid until a type conversion occurs as\n** described above, or until [sqlite3_step()] or [sqlite3_reset()] or\n** [sqlite3_finalize()] is called.  ^The memory space used to hold strings\n** and BLOBs is freed automatically.  Do not pass the pointers returned\n** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into\n** [sqlite3_free()].\n**\n** As long as the input parameters are correct, these routines will only\n** fail if an out-of-memory error occurs during a format conversion.\n** Only the following subset of interfaces are subject to out-of-memory\n** errors:\n**\n** <ul>\n** <li> sqlite3_column_blob()\n** <li> sqlite3_column_text()\n** <li> sqlite3_column_text16()\n** <li> sqlite3_column_bytes()\n** <li> sqlite3_column_bytes16()\n** </ul>\n**\n** If an out-of-memory error occurs, then the return value from these\n** routines is the same as if the column had contained an SQL NULL value.\n** Valid SQL NULL returns can be distinguished from out-of-memory errors\n** by invoking the [sqlite3_errcode()] immediately after the suspect\n** return value is obtained and before any\n** other SQLite interface is called on the same [database connection].\n*/\nSQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);\nSQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);\nSQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);\nSQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);\nSQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);\nSQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);\nSQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);\nSQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);\nSQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);\nSQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);\n\n/*\n** CAPI3REF: Destroy A Prepared Statement Object\n** DESTRUCTOR: sqlite3_stmt\n**\n** ^The sqlite3_finalize() function is called to delete a [prepared statement].\n** ^If the most recent evaluation of the statement encountered no errors\n** or if the statement is never been evaluated, then sqlite3_finalize() returns\n** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then\n** sqlite3_finalize(S) returns the appropriate [error code] or\n** [extended error code].\n**\n** ^The sqlite3_finalize(S) routine can be called at any point during\n** the life cycle of [prepared statement] S:\n** before statement S is ever evaluated, after\n** one or more calls to [sqlite3_reset()], or after any call\n** to [sqlite3_step()] regardless of whether or not the statement has\n** completed execution.\n**\n** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.\n**\n** The application must finalize every [prepared statement] in order to avoid\n** resource leaks.  It is a grievous error for the application to try to use\n** a prepared statement after it has been finalized.  Any use of a prepared\n** statement after it has been finalized can result in undefined and\n** undesirable behavior such as segfaults and heap corruption.\n*/\nSQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Reset A Prepared Statement Object\n** METHOD: sqlite3_stmt\n**\n** The sqlite3_reset() function is called to reset a [prepared statement]\n** object back to its initial state, ready to be re-executed.\n** ^Any SQL statement variables that had values bound to them using\n** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.\n** Use [sqlite3_clear_bindings()] to reset the bindings.\n**\n** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S\n** back to the beginning of its program.\n**\n** ^If the most recent call to [sqlite3_step(S)] for the\n** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],\n** or if [sqlite3_step(S)] has never before been called on S,\n** then [sqlite3_reset(S)] returns [SQLITE_OK].\n**\n** ^If the most recent call to [sqlite3_step(S)] for the\n** [prepared statement] S indicated an error, then\n** [sqlite3_reset(S)] returns an appropriate [error code].\n**\n** ^The [sqlite3_reset(S)] interface does not change the values\n** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.\n*/\nSQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Create Or Redefine SQL Functions\n** KEYWORDS: {function creation routines}\n** METHOD: sqlite3\n**\n** ^These functions (collectively known as \"function creation routines\")\n** are used to add SQL functions or aggregates or to redefine the behavior\n** of existing SQL functions or aggregates. The only differences between\n** the three \"sqlite3_create_function*\" routines are the text encoding \n** expected for the second parameter (the name of the function being \n** created) and the presence or absence of a destructor callback for\n** the application data pointer. Function sqlite3_create_window_function()\n** is similar, but allows the user to supply the extra callback functions\n** needed by [aggregate window functions].\n**\n** ^The first parameter is the [database connection] to which the SQL\n** function is to be added.  ^If an application uses more than one database\n** connection then application-defined SQL functions must be added\n** to each database connection separately.\n**\n** ^The second parameter is the name of the SQL function to be created or\n** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8\n** representation, exclusive of the zero-terminator.  ^Note that the name\n** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  \n** ^Any attempt to create a function with a longer name\n** will result in [SQLITE_MISUSE] being returned.\n**\n** ^The third parameter (nArg)\n** is the number of arguments that the SQL function or\n** aggregate takes. ^If this parameter is -1, then the SQL function or\n** aggregate may take any number of arguments between 0 and the limit\n** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third\n** parameter is less than -1 or greater than 127 then the behavior is\n** undefined.\n**\n** ^The fourth parameter, eTextRep, specifies what\n** [SQLITE_UTF8 | text encoding] this SQL function prefers for\n** its parameters.  The application should set this parameter to\n** [SQLITE_UTF16LE] if the function implementation invokes \n** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the\n** implementation invokes [sqlite3_value_text16be()] on an input, or\n** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]\n** otherwise.  ^The same SQL function may be registered multiple times using\n** different preferred text encodings, with different implementations for\n** each encoding.\n** ^When multiple implementations of the same function are available, SQLite\n** will pick the one that involves the least amount of data conversion.\n**\n** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]\n** to signal that the function will always return the same result given\n** the same inputs within a single SQL statement.  Most SQL functions are\n** deterministic.  The built-in [random()] SQL function is an example of a\n** function that is not deterministic.  The SQLite query planner is able to\n** perform additional optimizations on deterministic functions, so use\n** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.\n**\n** ^The fourth parameter may also optionally include the [SQLITE_DIRECTONLY]\n** flag, which if present prevents the function from being invoked from\n** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions,\n** index expressions, or the WHERE clause of partial indexes.\n**\n** <span style=\"background-color:#ffff90;\">\n** For best security, the [SQLITE_DIRECTONLY] flag is recommended for\n** all application-defined SQL functions that do not need to be\n** used inside of triggers, view, CHECK constraints, or other elements of\n** the database schema.  This flags is especially recommended for SQL \n** functions that have side effects or reveal internal application state.\n** Without this flag, an attacker might be able to modify the schema of\n** a database file to include invocations of the function with parameters\n** chosen by the attacker, which the application will then execute when\n** the database file is opened and read.\n** </span>\n**\n** ^(The fifth parameter is an arbitrary pointer.  The implementation of the\n** function can gain access to this pointer using [sqlite3_user_data()].)^\n**\n** ^The sixth, seventh and eighth parameters passed to the three\n** \"sqlite3_create_function*\" functions, xFunc, xStep and xFinal, are\n** pointers to C-language functions that implement the SQL function or\n** aggregate. ^A scalar SQL function requires an implementation of the xFunc\n** callback only; NULL pointers must be passed as the xStep and xFinal\n** parameters. ^An aggregate SQL function requires an implementation of xStep\n** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing\n** SQL function or aggregate, pass NULL pointers for all three function\n** callbacks.\n**\n** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue \n** and xInverse) passed to sqlite3_create_window_function are pointers to\n** C-language callbacks that implement the new function. xStep and xFinal\n** must both be non-NULL. xValue and xInverse may either both be NULL, in\n** which case a regular aggregate function is created, or must both be \n** non-NULL, in which case the new function may be used as either an aggregate\n** or aggregate window function. More details regarding the implementation\n** of aggregate window functions are \n** [user-defined window functions|available here].\n**\n** ^(If the final parameter to sqlite3_create_function_v2() or\n** sqlite3_create_window_function() is not NULL, then it is destructor for\n** the application data pointer. The destructor is invoked when the function \n** is deleted, either by being overloaded or when the database connection \n** closes.)^ ^The destructor is also invoked if the call to \n** sqlite3_create_function_v2() fails.  ^When the destructor callback is\n** invoked, it is passed a single argument which is a copy of the application\n** data pointer which was the fifth parameter to sqlite3_create_function_v2().\n**\n** ^It is permitted to register multiple implementations of the same\n** functions with the same name but with either differing numbers of\n** arguments or differing preferred text encodings.  ^SQLite will use\n** the implementation that most closely matches the way in which the\n** SQL function is used.  ^A function implementation with a non-negative\n** nArg parameter is a better match than a function implementation with\n** a negative nArg.  ^A function where the preferred text encoding\n** matches the database encoding is a better\n** match than a function where the encoding is different.  \n** ^A function where the encoding difference is between UTF16le and UTF16be\n** is a closer match than a function where the encoding difference is\n** between UTF8 and UTF16.\n**\n** ^Built-in functions may be overloaded by new application-defined functions.\n**\n** ^An application-defined function is permitted to call other\n** SQLite interfaces.  However, such calls must not\n** close the database connection nor finalize or reset the prepared\n** statement in which the function is running.\n*/\nSQLITE_API int sqlite3_create_function(\n  sqlite3 *db,\n  const char *zFunctionName,\n  int nArg,\n  int eTextRep,\n  void *pApp,\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*)\n);\nSQLITE_API int sqlite3_create_function16(\n  sqlite3 *db,\n  const void *zFunctionName,\n  int nArg,\n  int eTextRep,\n  void *pApp,\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*)\n);\nSQLITE_API int sqlite3_create_function_v2(\n  sqlite3 *db,\n  const char *zFunctionName,\n  int nArg,\n  int eTextRep,\n  void *pApp,\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*),\n  void(*xDestroy)(void*)\n);\nSQLITE_API int sqlite3_create_window_function(\n  sqlite3 *db,\n  const char *zFunctionName,\n  int nArg,\n  int eTextRep,\n  void *pApp,\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*),\n  void (*xValue)(sqlite3_context*),\n  void (*xInverse)(sqlite3_context*,int,sqlite3_value**),\n  void(*xDestroy)(void*)\n);\n\n/*\n** CAPI3REF: Text Encodings\n**\n** These constant define integer codes that represent the various\n** text encodings supported by SQLite.\n*/\n#define SQLITE_UTF8           1    /* IMP: R-37514-35566 */\n#define SQLITE_UTF16LE        2    /* IMP: R-03371-37637 */\n#define SQLITE_UTF16BE        3    /* IMP: R-51971-34154 */\n#define SQLITE_UTF16          4    /* Use native byte order */\n#define SQLITE_ANY            5    /* Deprecated */\n#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */\n\n/*\n** CAPI3REF: Function Flags\n**\n** These constants may be ORed together with the \n** [SQLITE_UTF8 | preferred text encoding] as the fourth argument\n** to [sqlite3_create_function()], [sqlite3_create_function16()], or\n** [sqlite3_create_function_v2()].\n**\n** <dl>\n** [[SQLITE_DETERMINISTIC]] <dt>SQLITE_DETERMINISTIC</dt><dd>\n** The SQLITE_DETERMINISTIC flag means that the new function always gives\n** the same output when the input parameters are the same.\n** The [abs|abs() function] is deterministic, for example, but\n** [randomblob|randomblob()] is not.  Functions must\n** be deterministic in order to be used in certain contexts such as\n** with the WHERE clause of [partial indexes] or in [generated columns].\n** SQLite might also optimize deterministic functions by factoring them\n** out of inner loops.\n** </dd>\n** \n** [[SQLITE_DIRECTONLY]] <dt>SQLITE_DIRECTONLY</dt><dd>\n** The SQLITE_DIRECTONLY flag means that the function may only be invoked\n** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in \n** schema structures such as [CHECK constraints], [DEFAULT clauses],\n** [expression indexes], [partial indexes], or [generated columns].\n** The SQLITE_DIRECTONLY flags is a security feature which is recommended\n** for all [application-defined SQL functions], and especially for functions\n** that have side-effects or that could potentially leak sensitive\n** information.\n** </dd>\n**\n** [[SQLITE_INNOCUOUS]] <dt>SQLITE_INNOCUOUS</dt><dd>\n** The SQLITE_INNOCUOUS flag means that the function is unlikely\n** to cause problems even if misused.  An innocuous function should have\n** no side effects and should not depend on any values other than its\n** input parameters. The [abs|abs() function] is an example of an\n** innocuous function.\n** The [load_extension() SQL function] is not innocuous because of its\n** side effects.\n** <p> SQLITE_INNOCUOUS is similar to SQLITE_DETERMINISTIC, but is not\n** exactly the same.  The [random|random() function] is an example of a\n** function that is innocuous but not deterministic.\n** <p>Some heightened security settings\n** ([SQLITE_DBCONFIG_TRUSTED_SCHEMA] and [PRAGMA trusted_schema=OFF])\n** disable the use of SQL functions inside views and triggers and in\n** schema structures such as [CHECK constraints], [DEFAULT clauses],\n** [expression indexes], [partial indexes], and [generated columns] unless\n** the function is tagged with SQLITE_INNOCUOUS.  Most built-in functions\n** are innocuous.  Developers are advised to avoid using the\n** SQLITE_INNOCUOUS flag for application-defined functions unless the\n** function has been carefully audited and found to be free of potentially\n** security-adverse side-effects and information-leaks.\n** </dd>\n**\n** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd>\n** The SQLITE_SUBTYPE flag indicates to SQLite that a function may call\n** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.\n** Specifying this flag makes no difference for scalar or aggregate user\n** functions. However, if it is not specified for a user-defined window\n** function, then any sub-types belonging to arguments passed to the window\n** function may be discarded before the window function is called (i.e.\n** sqlite3_value_subtype() will always return 0).\n** </dd>\n** </dl>\n*/\n#define SQLITE_DETERMINISTIC    0x000000800\n#define SQLITE_DIRECTONLY       0x000080000\n#define SQLITE_SUBTYPE          0x000100000\n#define SQLITE_INNOCUOUS        0x000200000\n\n/*\n** CAPI3REF: Deprecated Functions\n** DEPRECATED\n**\n** These functions are [deprecated].  In order to maintain\n** backwards compatibility with older code, these functions continue \n** to be supported.  However, new applications should avoid\n** the use of these functions.  To encourage programmers to avoid\n** these functions, we will not explain what they do.\n*/\n#ifndef SQLITE_OMIT_DEPRECATED\nSQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);\nSQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);\nSQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);\nSQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);\nSQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);\nSQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),\n                      void*,sqlite3_int64);\n#endif\n\n/*\n** CAPI3REF: Obtaining SQL Values\n** METHOD: sqlite3_value\n**\n** <b>Summary:</b>\n** <blockquote><table border=0 cellpadding=0 cellspacing=0>\n** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value\n** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value\n** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value\n** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value\n** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value\n** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value\n** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in\n** the native byteorder\n** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value\n** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value\n** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;\n** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB\n** or a UTF-8 TEXT in bytes\n** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>\n** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16\n** TEXT in bytes\n** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default\n** datatype of the value\n** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>\n** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value\n** <tr><td><b>sqlite3_value_nochange&nbsp;&nbsp;</b>\n** <td>&rarr;&nbsp;&nbsp;<td>True if the column is unchanged in an UPDATE\n** against a virtual table.\n** <tr><td><b>sqlite3_value_frombind&nbsp;&nbsp;</b>\n** <td>&rarr;&nbsp;&nbsp;<td>True if value originated from a [bound parameter]\n** </table></blockquote>\n**\n** <b>Details:</b>\n**\n** These routines extract type, size, and content information from\n** [protected sqlite3_value] objects.  Protected sqlite3_value objects\n** are used to pass parameter information into the functions that\n** implement [application-defined SQL functions] and [virtual tables].\n**\n** These routines work only with [protected sqlite3_value] objects.\n** Any attempt to use these routines on an [unprotected sqlite3_value]\n** is not threadsafe.\n**\n** ^These routines work just like the corresponding [column access functions]\n** except that these routines take a single [protected sqlite3_value] object\n** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.\n**\n** ^The sqlite3_value_text16() interface extracts a UTF-16 string\n** in the native byte-order of the host machine.  ^The\n** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces\n** extract UTF-16 strings as big-endian and little-endian respectively.\n**\n** ^If [sqlite3_value] object V was initialized \n** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]\n** and if X and Y are strings that compare equal according to strcmp(X,Y),\n** then sqlite3_value_pointer(V,Y) will return the pointer P.  ^Otherwise,\n** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer() \n** routine is part of the [pointer passing interface] added for SQLite 3.20.0.\n**\n** ^(The sqlite3_value_type(V) interface returns the\n** [SQLITE_INTEGER | datatype code] for the initial datatype of the\n** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],\n** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^\n** Other interfaces might change the datatype for an sqlite3_value object.\n** For example, if the datatype is initially SQLITE_INTEGER and\n** sqlite3_value_text(V) is called to extract a text value for that\n** integer, then subsequent calls to sqlite3_value_type(V) might return\n** SQLITE_TEXT.  Whether or not a persistent internal datatype conversion\n** occurs is undefined and may change from one release of SQLite to the next.\n**\n** ^(The sqlite3_value_numeric_type() interface attempts to apply\n** numeric affinity to the value.  This means that an attempt is\n** made to convert the value to an integer or floating point.  If\n** such a conversion is possible without loss of information (in other\n** words, if the value is a string that looks like a number)\n** then the conversion is performed.  Otherwise no conversion occurs.\n** The [SQLITE_INTEGER | datatype] after conversion is returned.)^\n**\n** ^Within the [xUpdate] method of a [virtual table], the\n** sqlite3_value_nochange(X) interface returns true if and only if\n** the column corresponding to X is unchanged by the UPDATE operation\n** that the xUpdate method call was invoked to implement and if\n** and the prior [xColumn] method call that was invoked to extracted\n** the value for that column returned without setting a result (probably\n** because it queried [sqlite3_vtab_nochange()] and found that the column\n** was unchanging).  ^Within an [xUpdate] method, any value for which\n** sqlite3_value_nochange(X) is true will in all other respects appear\n** to be a NULL value.  If sqlite3_value_nochange(X) is invoked anywhere other\n** than within an [xUpdate] method call for an UPDATE statement, then\n** the return value is arbitrary and meaningless.\n**\n** ^The sqlite3_value_frombind(X) interface returns non-zero if the\n** value X originated from one of the [sqlite3_bind_int|sqlite3_bind()]\n** interfaces.  ^If X comes from an SQL literal value, or a table column,\n** or an expression, then sqlite3_value_frombind(X) returns zero.\n**\n** Please pay particular attention to the fact that the pointer returned\n** from [sqlite3_value_blob()], [sqlite3_value_text()], or\n** [sqlite3_value_text16()] can be invalidated by a subsequent call to\n** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],\n** or [sqlite3_value_text16()].\n**\n** These routines must be called from the same thread as\n** the SQL function that supplied the [sqlite3_value*] parameters.\n**\n** As long as the input parameter is correct, these routines can only\n** fail if an out-of-memory error occurs during a format conversion.\n** Only the following subset of interfaces are subject to out-of-memory\n** errors:\n**\n** <ul>\n** <li> sqlite3_value_blob()\n** <li> sqlite3_value_text()\n** <li> sqlite3_value_text16()\n** <li> sqlite3_value_text16le()\n** <li> sqlite3_value_text16be()\n** <li> sqlite3_value_bytes()\n** <li> sqlite3_value_bytes16()\n** </ul>\n**\n** If an out-of-memory error occurs, then the return value from these\n** routines is the same as if the column had contained an SQL NULL value.\n** Valid SQL NULL returns can be distinguished from out-of-memory errors\n** by invoking the [sqlite3_errcode()] immediately after the suspect\n** return value is obtained and before any\n** other SQLite interface is called on the same [database connection].\n*/\nSQLITE_API const void *sqlite3_value_blob(sqlite3_value*);\nSQLITE_API double sqlite3_value_double(sqlite3_value*);\nSQLITE_API int sqlite3_value_int(sqlite3_value*);\nSQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);\nSQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);\nSQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);\nSQLITE_API const void *sqlite3_value_text16(sqlite3_value*);\nSQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);\nSQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);\nSQLITE_API int sqlite3_value_bytes(sqlite3_value*);\nSQLITE_API int sqlite3_value_bytes16(sqlite3_value*);\nSQLITE_API int sqlite3_value_type(sqlite3_value*);\nSQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);\nSQLITE_API int sqlite3_value_nochange(sqlite3_value*);\nSQLITE_API int sqlite3_value_frombind(sqlite3_value*);\n\n/*\n** CAPI3REF: Finding The Subtype Of SQL Values\n** METHOD: sqlite3_value\n**\n** The sqlite3_value_subtype(V) function returns the subtype for\n** an [application-defined SQL function] argument V.  The subtype\n** information can be used to pass a limited amount of context from\n** one SQL function to another.  Use the [sqlite3_result_subtype()]\n** routine to set the subtype for the return value of an SQL function.\n*/\nSQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);\n\n/*\n** CAPI3REF: Copy And Free SQL Values\n** METHOD: sqlite3_value\n**\n** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]\n** object D and returns a pointer to that copy.  ^The [sqlite3_value] returned\n** is a [protected sqlite3_value] object even if the input is not.\n** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a\n** memory allocation fails.\n**\n** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object\n** previously obtained from [sqlite3_value_dup()].  ^If V is a NULL pointer\n** then sqlite3_value_free(V) is a harmless no-op.\n*/\nSQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);\nSQLITE_API void sqlite3_value_free(sqlite3_value*);\n\n/*\n** CAPI3REF: Obtain Aggregate Function Context\n** METHOD: sqlite3_context\n**\n** Implementations of aggregate SQL functions use this\n** routine to allocate memory for storing their state.\n**\n** ^The first time the sqlite3_aggregate_context(C,N) routine is called \n** for a particular aggregate function, SQLite allocates\n** N bytes of memory, zeroes out that memory, and returns a pointer\n** to the new memory. ^On second and subsequent calls to\n** sqlite3_aggregate_context() for the same aggregate function instance,\n** the same buffer is returned.  Sqlite3_aggregate_context() is normally\n** called once for each invocation of the xStep callback and then one\n** last time when the xFinal callback is invoked.  ^(When no rows match\n** an aggregate query, the xStep() callback of the aggregate function\n** implementation is never called and xFinal() is called exactly once.\n** In those cases, sqlite3_aggregate_context() might be called for the\n** first time from within xFinal().)^\n**\n** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer \n** when first called if N is less than or equal to zero or if a memory\n** allocate error occurs.\n**\n** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is\n** determined by the N parameter on first successful call.  Changing the\n** value of N in any subsequent call to sqlite3_aggregate_context() within\n** the same aggregate function instance will not resize the memory\n** allocation.)^  Within the xFinal callback, it is customary to set\n** N=0 in calls to sqlite3_aggregate_context(C,N) so that no \n** pointless memory allocations occur.\n**\n** ^SQLite automatically frees the memory allocated by \n** sqlite3_aggregate_context() when the aggregate query concludes.\n**\n** The first parameter must be a copy of the\n** [sqlite3_context | SQL function context] that is the first parameter\n** to the xStep or xFinal callback routine that implements the aggregate\n** function.\n**\n** This routine must be called from the same thread in which\n** the aggregate SQL function is running.\n*/\nSQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);\n\n/*\n** CAPI3REF: User Data For Functions\n** METHOD: sqlite3_context\n**\n** ^The sqlite3_user_data() interface returns a copy of\n** the pointer that was the pUserData parameter (the 5th parameter)\n** of the [sqlite3_create_function()]\n** and [sqlite3_create_function16()] routines that originally\n** registered the application defined function.\n**\n** This routine must be called from the same thread in which\n** the application-defined function is running.\n*/\nSQLITE_API void *sqlite3_user_data(sqlite3_context*);\n\n/*\n** CAPI3REF: Database Connection For Functions\n** METHOD: sqlite3_context\n**\n** ^The sqlite3_context_db_handle() interface returns a copy of\n** the pointer to the [database connection] (the 1st parameter)\n** of the [sqlite3_create_function()]\n** and [sqlite3_create_function16()] routines that originally\n** registered the application defined function.\n*/\nSQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);\n\n/*\n** CAPI3REF: Function Auxiliary Data\n** METHOD: sqlite3_context\n**\n** These functions may be used by (non-aggregate) SQL functions to\n** associate metadata with argument values. If the same value is passed to\n** multiple invocations of the same SQL function during query execution, under\n** some circumstances the associated metadata may be preserved.  An example\n** of where this might be useful is in a regular-expression matching\n** function. The compiled version of the regular expression can be stored as\n** metadata associated with the pattern string.  \n** Then as long as the pattern string remains the same,\n** the compiled regular expression can be reused on multiple\n** invocations of the same function.\n**\n** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata\n** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument\n** value to the application-defined function.  ^N is zero for the left-most\n** function argument.  ^If there is no metadata\n** associated with the function argument, the sqlite3_get_auxdata(C,N) interface\n** returns a NULL pointer.\n**\n** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th\n** argument of the application-defined function.  ^Subsequent\n** calls to sqlite3_get_auxdata(C,N) return P from the most recent\n** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or\n** NULL if the metadata has been discarded.\n** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,\n** SQLite will invoke the destructor function X with parameter P exactly\n** once, when the metadata is discarded.\n** SQLite is free to discard the metadata at any time, including: <ul>\n** <li> ^(when the corresponding function parameter changes)^, or\n** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the\n**      SQL statement)^, or\n** <li> ^(when sqlite3_set_auxdata() is invoked again on the same\n**       parameter)^, or\n** <li> ^(during the original sqlite3_set_auxdata() call when a memory \n**      allocation error occurs.)^ </ul>\n**\n** Note the last bullet in particular.  The destructor X in \n** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the\n** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()\n** should be called near the end of the function implementation and the\n** function implementation should not make any use of P after\n** sqlite3_set_auxdata() has been called.\n**\n** ^(In practice, metadata is preserved between function calls for\n** function parameters that are compile-time constants, including literal\n** values and [parameters] and expressions composed from the same.)^\n**\n** The value of the N parameter to these interfaces should be non-negative.\n** Future enhancements may make use of negative N values to define new\n** kinds of function caching behavior.\n**\n** These routines must be called from the same thread in which\n** the SQL function is running.\n*/\nSQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);\nSQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));\n\n\n/*\n** CAPI3REF: Constants Defining Special Destructor Behavior\n**\n** These are special values for the destructor that is passed in as the\n** final argument to routines like [sqlite3_result_blob()].  ^If the destructor\n** argument is SQLITE_STATIC, it means that the content pointer is constant\n** and will never change.  It does not need to be destroyed.  ^The\n** SQLITE_TRANSIENT value means that the content will likely change in\n** the near future and that SQLite should make its own private copy of\n** the content before returning.\n**\n** The typedef is necessary to work around problems in certain\n** C++ compilers.\n*/\ntypedef void (*sqlite3_destructor_type)(void*);\n#define SQLITE_STATIC      ((sqlite3_destructor_type)0)\n#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)\n\n/*\n** CAPI3REF: Setting The Result Of An SQL Function\n** METHOD: sqlite3_context\n**\n** These routines are used by the xFunc or xFinal callbacks that\n** implement SQL functions and aggregates.  See\n** [sqlite3_create_function()] and [sqlite3_create_function16()]\n** for additional information.\n**\n** These functions work very much like the [parameter binding] family of\n** functions used to bind values to host parameters in prepared statements.\n** Refer to the [SQL parameter] documentation for additional information.\n**\n** ^The sqlite3_result_blob() interface sets the result from\n** an application-defined function to be the BLOB whose content is pointed\n** to by the second parameter and which is N bytes long where N is the\n** third parameter.\n**\n** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)\n** interfaces set the result of the application-defined function to be\n** a BLOB containing all zero bytes and N bytes in size.\n**\n** ^The sqlite3_result_double() interface sets the result from\n** an application-defined function to be a floating point value specified\n** by its 2nd argument.\n**\n** ^The sqlite3_result_error() and sqlite3_result_error16() functions\n** cause the implemented SQL function to throw an exception.\n** ^SQLite uses the string pointed to by the\n** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()\n** as the text of an error message.  ^SQLite interprets the error\n** message string from sqlite3_result_error() as UTF-8. ^SQLite\n** interprets the string from sqlite3_result_error16() as UTF-16 using\n** the same [byte-order determination rules] as [sqlite3_bind_text16()].\n** ^If the third parameter to sqlite3_result_error()\n** or sqlite3_result_error16() is negative then SQLite takes as the error\n** message all text up through the first zero character.\n** ^If the third parameter to sqlite3_result_error() or\n** sqlite3_result_error16() is non-negative then SQLite takes that many\n** bytes (not characters) from the 2nd parameter as the error message.\n** ^The sqlite3_result_error() and sqlite3_result_error16()\n** routines make a private copy of the error message text before\n** they return.  Hence, the calling function can deallocate or\n** modify the text after they return without harm.\n** ^The sqlite3_result_error_code() function changes the error code\n** returned by SQLite as a result of an error in a function.  ^By default,\n** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()\n** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.\n**\n** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an\n** error indicating that a string or BLOB is too long to represent.\n**\n** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an\n** error indicating that a memory allocation failed.\n**\n** ^The sqlite3_result_int() interface sets the return value\n** of the application-defined function to be the 32-bit signed integer\n** value given in the 2nd argument.\n** ^The sqlite3_result_int64() interface sets the return value\n** of the application-defined function to be the 64-bit signed integer\n** value given in the 2nd argument.\n**\n** ^The sqlite3_result_null() interface sets the return value\n** of the application-defined function to be NULL.\n**\n** ^The sqlite3_result_text(), sqlite3_result_text16(),\n** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces\n** set the return value of the application-defined function to be\n** a text string which is represented as UTF-8, UTF-16 native byte order,\n** UTF-16 little endian, or UTF-16 big endian, respectively.\n** ^The sqlite3_result_text64() interface sets the return value of an\n** application-defined function to be a text string in an encoding\n** specified by the fifth (and last) parameter, which must be one\n** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].\n** ^SQLite takes the text result from the application from\n** the 2nd parameter of the sqlite3_result_text* interfaces.\n** ^If the 3rd parameter to the sqlite3_result_text* interfaces\n** is negative, then SQLite takes result text from the 2nd parameter\n** through the first zero character.\n** ^If the 3rd parameter to the sqlite3_result_text* interfaces\n** is non-negative, then as many bytes (not characters) of the text\n** pointed to by the 2nd parameter are taken as the application-defined\n** function result.  If the 3rd parameter is non-negative, then it\n** must be the byte offset into the string where the NUL terminator would\n** appear if the string where NUL terminated.  If any NUL characters occur\n** in the string at a byte offset that is less than the value of the 3rd\n** parameter, then the resulting string will contain embedded NULs and the\n** result of expressions operating on strings with embedded NULs is undefined.\n** ^If the 4th parameter to the sqlite3_result_text* interfaces\n** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that\n** function as the destructor on the text or BLOB result when it has\n** finished using that result.\n** ^If the 4th parameter to the sqlite3_result_text* interfaces or to\n** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite\n** assumes that the text or BLOB result is in constant space and does not\n** copy the content of the parameter nor call a destructor on the content\n** when it has finished using that result.\n** ^If the 4th parameter to the sqlite3_result_text* interfaces\n** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT\n** then SQLite makes a copy of the result into space obtained\n** from [sqlite3_malloc()] before it returns.\n**\n** ^For the sqlite3_result_text16(), sqlite3_result_text16le(), and\n** sqlite3_result_text16be() routines, and for sqlite3_result_text64()\n** when the encoding is not UTF8, if the input UTF16 begins with a\n** byte-order mark (BOM, U+FEFF) then the BOM is removed from the\n** string and the rest of the string is interpreted according to the\n** byte-order specified by the BOM.  ^The byte-order specified by\n** the BOM at the beginning of the text overrides the byte-order\n** specified by the interface procedure.  ^So, for example, if\n** sqlite3_result_text16le() is invoked with text that begins\n** with bytes 0xfe, 0xff (a big-endian byte-order mark) then the\n** first two bytes of input are skipped and the remaining input\n** is interpreted as UTF16BE text.\n**\n** ^For UTF16 input text to the sqlite3_result_text16(),\n** sqlite3_result_text16be(), sqlite3_result_text16le(), and\n** sqlite3_result_text64() routines, if the text contains invalid\n** UTF16 characters, the invalid characters might be converted\n** into the unicode replacement character, U+FFFD.\n**\n** ^The sqlite3_result_value() interface sets the result of\n** the application-defined function to be a copy of the\n** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The\n** sqlite3_result_value() interface makes a copy of the [sqlite3_value]\n** so that the [sqlite3_value] specified in the parameter may change or\n** be deallocated after sqlite3_result_value() returns without harm.\n** ^A [protected sqlite3_value] object may always be used where an\n** [unprotected sqlite3_value] object is required, so either\n** kind of [sqlite3_value] object can be used with this interface.\n**\n** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an\n** SQL NULL value, just like [sqlite3_result_null(C)], except that it\n** also associates the host-language pointer P or type T with that \n** NULL value such that the pointer can be retrieved within an\n** [application-defined SQL function] using [sqlite3_value_pointer()].\n** ^If the D parameter is not NULL, then it is a pointer to a destructor\n** for the P parameter.  ^SQLite invokes D with P as its only argument\n** when SQLite is finished with P.  The T parameter should be a static\n** string and preferably a string literal. The sqlite3_result_pointer()\n** routine is part of the [pointer passing interface] added for SQLite 3.20.0.\n**\n** If these routines are called from within the different thread\n** than the one containing the application-defined function that received\n** the [sqlite3_context] pointer, the results are undefined.\n*/\nSQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));\nSQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,\n                           sqlite3_uint64,void(*)(void*));\nSQLITE_API void sqlite3_result_double(sqlite3_context*, double);\nSQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);\nSQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);\nSQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);\nSQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);\nSQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);\nSQLITE_API void sqlite3_result_int(sqlite3_context*, int);\nSQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);\nSQLITE_API void sqlite3_result_null(sqlite3_context*);\nSQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));\nSQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,\n                           void(*)(void*), unsigned char encoding);\nSQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));\nSQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));\nSQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));\nSQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);\nSQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));\nSQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);\nSQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);\n\n\n/*\n** CAPI3REF: Setting The Subtype Of An SQL Function\n** METHOD: sqlite3_context\n**\n** The sqlite3_result_subtype(C,T) function causes the subtype of\n** the result from the [application-defined SQL function] with \n** [sqlite3_context] C to be the value T.  Only the lower 8 bits \n** of the subtype T are preserved in current versions of SQLite;\n** higher order bits are discarded.\n** The number of subtype bytes preserved by SQLite might increase\n** in future releases of SQLite.\n*/\nSQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);\n\n/*\n** CAPI3REF: Define New Collating Sequences\n** METHOD: sqlite3\n**\n** ^These functions add, remove, or modify a [collation] associated\n** with the [database connection] specified as the first argument.\n**\n** ^The name of the collation is a UTF-8 string\n** for sqlite3_create_collation() and sqlite3_create_collation_v2()\n** and a UTF-16 string in native byte order for sqlite3_create_collation16().\n** ^Collation names that compare equal according to [sqlite3_strnicmp()] are\n** considered to be the same name.\n**\n** ^(The third argument (eTextRep) must be one of the constants:\n** <ul>\n** <li> [SQLITE_UTF8],\n** <li> [SQLITE_UTF16LE],\n** <li> [SQLITE_UTF16BE],\n** <li> [SQLITE_UTF16], or\n** <li> [SQLITE_UTF16_ALIGNED].\n** </ul>)^\n** ^The eTextRep argument determines the encoding of strings passed\n** to the collating function callback, xCompare.\n** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep\n** force strings to be UTF16 with native byte order.\n** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin\n** on an even byte address.\n**\n** ^The fourth argument, pArg, is an application data pointer that is passed\n** through as the first argument to the collating function callback.\n**\n** ^The fifth argument, xCompare, is a pointer to the collating function.\n** ^Multiple collating functions can be registered using the same name but\n** with different eTextRep parameters and SQLite will use whichever\n** function requires the least amount of data transformation.\n** ^If the xCompare argument is NULL then the collating function is\n** deleted.  ^When all collating functions having the same name are deleted,\n** that collation is no longer usable.\n**\n** ^The collating function callback is invoked with a copy of the pArg \n** application data pointer and with two strings in the encoding specified\n** by the eTextRep argument.  The two integer parameters to the collating\n** function callback are the length of the two strings, in bytes. The collating\n** function must return an integer that is negative, zero, or positive\n** if the first string is less than, equal to, or greater than the second,\n** respectively.  A collating function must always return the same answer\n** given the same inputs.  If two or more collating functions are registered\n** to the same collation name (using different eTextRep values) then all\n** must give an equivalent answer when invoked with equivalent strings.\n** The collating function must obey the following properties for all\n** strings A, B, and C:\n**\n** <ol>\n** <li> If A==B then B==A.\n** <li> If A==B and B==C then A==C.\n** <li> If A&lt;B THEN B&gt;A.\n** <li> If A&lt;B and B&lt;C then A&lt;C.\n** </ol>\n**\n** If a collating function fails any of the above constraints and that\n** collating function is registered and used, then the behavior of SQLite\n** is undefined.\n**\n** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()\n** with the addition that the xDestroy callback is invoked on pArg when\n** the collating function is deleted.\n** ^Collating functions are deleted when they are overridden by later\n** calls to the collation creation functions or when the\n** [database connection] is closed using [sqlite3_close()].\n**\n** ^The xDestroy callback is <u>not</u> called if the \n** sqlite3_create_collation_v2() function fails.  Applications that invoke\n** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should \n** check the return code and dispose of the application data pointer\n** themselves rather than expecting SQLite to deal with it for them.\n** This is different from every other SQLite interface.  The inconsistency \n** is unfortunate but cannot be changed without breaking backwards \n** compatibility.\n**\n** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].\n*/\nSQLITE_API int sqlite3_create_collation(\n  sqlite3*, \n  const char *zName, \n  int eTextRep, \n  void *pArg,\n  int(*xCompare)(void*,int,const void*,int,const void*)\n);\nSQLITE_API int sqlite3_create_collation_v2(\n  sqlite3*, \n  const char *zName, \n  int eTextRep, \n  void *pArg,\n  int(*xCompare)(void*,int,const void*,int,const void*),\n  void(*xDestroy)(void*)\n);\nSQLITE_API int sqlite3_create_collation16(\n  sqlite3*, \n  const void *zName,\n  int eTextRep, \n  void *pArg,\n  int(*xCompare)(void*,int,const void*,int,const void*)\n);\n\n/*\n** CAPI3REF: Collation Needed Callbacks\n** METHOD: sqlite3\n**\n** ^To avoid having to register all collation sequences before a database\n** can be used, a single callback function may be registered with the\n** [database connection] to be invoked whenever an undefined collation\n** sequence is required.\n**\n** ^If the function is registered using the sqlite3_collation_needed() API,\n** then it is passed the names of undefined collation sequences as strings\n** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,\n** the names are passed as UTF-16 in machine native byte order.\n** ^A call to either function replaces the existing collation-needed callback.\n**\n** ^(When the callback is invoked, the first argument passed is a copy\n** of the second argument to sqlite3_collation_needed() or\n** sqlite3_collation_needed16().  The second argument is the database\n** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],\n** or [SQLITE_UTF16LE], indicating the most desirable form of the collation\n** sequence function required.  The fourth parameter is the name of the\n** required collation sequence.)^\n**\n** The callback function should register the desired collation using\n** [sqlite3_create_collation()], [sqlite3_create_collation16()], or\n** [sqlite3_create_collation_v2()].\n*/\nSQLITE_API int sqlite3_collation_needed(\n  sqlite3*, \n  void*, \n  void(*)(void*,sqlite3*,int eTextRep,const char*)\n);\nSQLITE_API int sqlite3_collation_needed16(\n  sqlite3*, \n  void*,\n  void(*)(void*,sqlite3*,int eTextRep,const void*)\n);\n\n#ifdef SQLITE_ENABLE_CEROD\n/*\n** Specify the activation key for a CEROD database.  Unless \n** activated, none of the CEROD routines will work.\n*/\nSQLITE_API void sqlite3_activate_cerod(\n  const char *zPassPhrase        /* Activation phrase */\n);\n#endif\n\n/*\n** CAPI3REF: Suspend Execution For A Short Time\n**\n** The sqlite3_sleep() function causes the current thread to suspend execution\n** for at least a number of milliseconds specified in its parameter.\n**\n** If the operating system does not support sleep requests with\n** millisecond time resolution, then the time will be rounded up to\n** the nearest second. The number of milliseconds of sleep actually\n** requested from the operating system is returned.\n**\n** ^SQLite implements this interface by calling the xSleep()\n** method of the default [sqlite3_vfs] object.  If the xSleep() method\n** of the default VFS is not implemented correctly, or not implemented at\n** all, then the behavior of sqlite3_sleep() may deviate from the description\n** in the previous paragraphs.\n*/\nSQLITE_API int sqlite3_sleep(int);\n\n/*\n** CAPI3REF: Name Of The Folder Holding Temporary Files\n**\n** ^(If this global variable is made to point to a string which is\n** the name of a folder (a.k.a. directory), then all temporary files\n** created by SQLite when using a built-in [sqlite3_vfs | VFS]\n** will be placed in that directory.)^  ^If this variable\n** is a NULL pointer, then SQLite performs a search for an appropriate\n** temporary file directory.\n**\n** Applications are strongly discouraged from using this global variable.\n** It is required to set a temporary folder on Windows Runtime (WinRT).\n** But for all other platforms, it is highly recommended that applications\n** neither read nor write this variable.  This global variable is a relic\n** that exists for backwards compatibility of legacy applications and should\n** be avoided in new projects.\n**\n** It is not safe to read or modify this variable in more than one\n** thread at a time.  It is not safe to read or modify this variable\n** if a [database connection] is being used at the same time in a separate\n** thread.\n** It is intended that this variable be set once\n** as part of process initialization and before any SQLite interface\n** routines have been called and that this variable remain unchanged\n** thereafter.\n**\n** ^The [temp_store_directory pragma] may modify this variable and cause\n** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,\n** the [temp_store_directory pragma] always assumes that any string\n** that this variable points to is held in memory obtained from \n** [sqlite3_malloc] and the pragma may attempt to free that memory\n** using [sqlite3_free].\n** Hence, if this variable is modified directly, either it should be\n** made NULL or made to point to memory obtained from [sqlite3_malloc]\n** or else the use of the [temp_store_directory pragma] should be avoided.\n** Except when requested by the [temp_store_directory pragma], SQLite\n** does not free the memory that sqlite3_temp_directory points to.  If\n** the application wants that memory to be freed, it must do\n** so itself, taking care to only do so after all [database connection]\n** objects have been destroyed.\n**\n** <b>Note to Windows Runtime users:</b>  The temporary directory must be set\n** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various\n** features that require the use of temporary files may fail.  Here is an\n** example of how to do this using C++ with the Windows Runtime:\n**\n** <blockquote><pre>\n** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->\n** &nbsp;     TemporaryFolder->Path->Data();\n** char zPathBuf&#91;MAX_PATH + 1&#93;;\n** memset(zPathBuf, 0, sizeof(zPathBuf));\n** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),\n** &nbsp;     NULL, NULL);\n** sqlite3_temp_directory = sqlite3_mprintf(\"%s\", zPathBuf);\n** </pre></blockquote>\n*/\nSQLITE_API SQLITE_EXTERN char *sqlite3_temp_directory;\n\n/*\n** CAPI3REF: Name Of The Folder Holding Database Files\n**\n** ^(If this global variable is made to point to a string which is\n** the name of a folder (a.k.a. directory), then all database files\n** specified with a relative pathname and created or accessed by\n** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed\n** to be relative to that directory.)^ ^If this variable is a NULL\n** pointer, then SQLite assumes that all database files specified\n** with a relative pathname are relative to the current directory\n** for the process.  Only the windows VFS makes use of this global\n** variable; it is ignored by the unix VFS.\n**\n** Changing the value of this variable while a database connection is\n** open can result in a corrupt database.\n**\n** It is not safe to read or modify this variable in more than one\n** thread at a time.  It is not safe to read or modify this variable\n** if a [database connection] is being used at the same time in a separate\n** thread.\n** It is intended that this variable be set once\n** as part of process initialization and before any SQLite interface\n** routines have been called and that this variable remain unchanged\n** thereafter.\n**\n** ^The [data_store_directory pragma] may modify this variable and cause\n** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,\n** the [data_store_directory pragma] always assumes that any string\n** that this variable points to is held in memory obtained from \n** [sqlite3_malloc] and the pragma may attempt to free that memory\n** using [sqlite3_free].\n** Hence, if this variable is modified directly, either it should be\n** made NULL or made to point to memory obtained from [sqlite3_malloc]\n** or else the use of the [data_store_directory pragma] should be avoided.\n*/\nSQLITE_API SQLITE_EXTERN char *sqlite3_data_directory;\n\n/*\n** CAPI3REF: Win32 Specific Interface\n**\n** These interfaces are available only on Windows.  The\n** [sqlite3_win32_set_directory] interface is used to set the value associated\n** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to\n** zValue, depending on the value of the type parameter.  The zValue parameter\n** should be NULL to cause the previous value to be freed via [sqlite3_free];\n** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]\n** prior to being used.  The [sqlite3_win32_set_directory] interface returns\n** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,\n** or [SQLITE_NOMEM] if memory could not be allocated.  The value of the\n** [sqlite3_data_directory] variable is intended to act as a replacement for\n** the current directory on the sub-platforms of Win32 where that concept is\n** not present, e.g. WinRT and UWP.  The [sqlite3_win32_set_directory8] and\n** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the\n** sqlite3_win32_set_directory interface except the string parameter must be\n** UTF-8 or UTF-16, respectively.\n*/\nSQLITE_API int sqlite3_win32_set_directory(\n  unsigned long type, /* Identifier for directory being set or reset */\n  void *zValue        /* New value for directory being set or reset */\n);\nSQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);\nSQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);\n\n/*\n** CAPI3REF: Win32 Directory Types\n**\n** These macros are only available on Windows.  They define the allowed values\n** for the type argument to the [sqlite3_win32_set_directory] interface.\n*/\n#define SQLITE_WIN32_DATA_DIRECTORY_TYPE  1\n#define SQLITE_WIN32_TEMP_DIRECTORY_TYPE  2\n\n/*\n** CAPI3REF: Test For Auto-Commit Mode\n** KEYWORDS: {autocommit mode}\n** METHOD: sqlite3\n**\n** ^The sqlite3_get_autocommit() interface returns non-zero or\n** zero if the given database connection is or is not in autocommit mode,\n** respectively.  ^Autocommit mode is on by default.\n** ^Autocommit mode is disabled by a [BEGIN] statement.\n** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].\n**\n** If certain kinds of errors occur on a statement within a multi-statement\n** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],\n** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the\n** transaction might be rolled back automatically.  The only way to\n** find out whether SQLite automatically rolled back the transaction after\n** an error is to use this function.\n**\n** If another thread changes the autocommit status of the database\n** connection while this routine is running, then the return value\n** is undefined.\n*/\nSQLITE_API int sqlite3_get_autocommit(sqlite3*);\n\n/*\n** CAPI3REF: Find The Database Handle Of A Prepared Statement\n** METHOD: sqlite3_stmt\n**\n** ^The sqlite3_db_handle interface returns the [database connection] handle\n** to which a [prepared statement] belongs.  ^The [database connection]\n** returned by sqlite3_db_handle is the same [database connection]\n** that was the first argument\n** to the [sqlite3_prepare_v2()] call (or its variants) that was used to\n** create the statement in the first place.\n*/\nSQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Return The Filename For A Database Connection\n** METHOD: sqlite3\n**\n** ^The sqlite3_db_filename(D,N) interface returns a pointer to the filename\n** associated with database N of connection D.\n** ^If there is no attached database N on the database\n** connection D, or if database N is a temporary or in-memory database, then\n** this function will return either a NULL pointer or an empty string.\n**\n** ^The string value returned by this routine is owned and managed by\n** the database connection.  ^The value will be valid until the database N\n** is [DETACH]-ed or until the database connection closes.\n**\n** ^The filename returned by this function is the output of the\n** xFullPathname method of the [VFS].  ^In other words, the filename\n** will be an absolute pathname, even if the filename used\n** to open the database originally was a URI or relative pathname.\n**\n** If the filename pointer returned by this routine is not NULL, then it\n** can be used as the filename input parameter to these routines:\n** <ul>\n** <li> [sqlite3_uri_parameter()]\n** <li> [sqlite3_uri_boolean()]\n** <li> [sqlite3_uri_int64()]\n** <li> [sqlite3_filename_database()]\n** <li> [sqlite3_filename_journal()]\n** <li> [sqlite3_filename_wal()]\n** </ul>\n*/\nSQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);\n\n/*\n** CAPI3REF: Determine if a database is read-only\n** METHOD: sqlite3\n**\n** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N\n** of connection D is read-only, 0 if it is read/write, or -1 if N is not\n** the name of a database on connection D.\n*/\nSQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);\n\n/*\n** CAPI3REF: Find the next prepared statement\n** METHOD: sqlite3\n**\n** ^This interface returns a pointer to the next [prepared statement] after\n** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL\n** then this interface returns a pointer to the first prepared statement\n** associated with the database connection pDb.  ^If no prepared statement\n** satisfies the conditions of this routine, it returns NULL.\n**\n** The [database connection] pointer D in a call to\n** [sqlite3_next_stmt(D,S)] must refer to an open database\n** connection and in particular must not be a NULL pointer.\n*/\nSQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Commit And Rollback Notification Callbacks\n** METHOD: sqlite3\n**\n** ^The sqlite3_commit_hook() interface registers a callback\n** function to be invoked whenever a transaction is [COMMIT | committed].\n** ^Any callback set by a previous call to sqlite3_commit_hook()\n** for the same database connection is overridden.\n** ^The sqlite3_rollback_hook() interface registers a callback\n** function to be invoked whenever a transaction is [ROLLBACK | rolled back].\n** ^Any callback set by a previous call to sqlite3_rollback_hook()\n** for the same database connection is overridden.\n** ^The pArg argument is passed through to the callback.\n** ^If the callback on a commit hook function returns non-zero,\n** then the commit is converted into a rollback.\n**\n** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions\n** return the P argument from the previous call of the same function\n** on the same [database connection] D, or NULL for\n** the first call for each function on D.\n**\n** The commit and rollback hook callbacks are not reentrant.\n** The callback implementation must not do anything that will modify\n** the database connection that invoked the callback.  Any actions\n** to modify the database connection must be deferred until after the\n** completion of the [sqlite3_step()] call that triggered the commit\n** or rollback hook in the first place.\n** Note that running any other SQL statements, including SELECT statements,\n** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify\n** the database connections for the meaning of \"modify\" in this paragraph.\n**\n** ^Registering a NULL function disables the callback.\n**\n** ^When the commit hook callback routine returns zero, the [COMMIT]\n** operation is allowed to continue normally.  ^If the commit hook\n** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].\n** ^The rollback hook is invoked on a rollback that results from a commit\n** hook returning non-zero, just as it would be with any other rollback.\n**\n** ^For the purposes of this API, a transaction is said to have been\n** rolled back if an explicit \"ROLLBACK\" statement is executed, or\n** an error or constraint causes an implicit rollback to occur.\n** ^The rollback callback is not invoked if a transaction is\n** automatically rolled back because the database connection is closed.\n**\n** See also the [sqlite3_update_hook()] interface.\n*/\nSQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);\nSQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);\n\n/*\n** CAPI3REF: Data Change Notification Callbacks\n** METHOD: sqlite3\n**\n** ^The sqlite3_update_hook() interface registers a callback function\n** with the [database connection] identified by the first argument\n** to be invoked whenever a row is updated, inserted or deleted in\n** a [rowid table].\n** ^Any callback set by a previous call to this function\n** for the same database connection is overridden.\n**\n** ^The second argument is a pointer to the function to invoke when a\n** row is updated, inserted or deleted in a rowid table.\n** ^The first argument to the callback is a copy of the third argument\n** to sqlite3_update_hook().\n** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],\n** or [SQLITE_UPDATE], depending on the operation that caused the callback\n** to be invoked.\n** ^The third and fourth arguments to the callback contain pointers to the\n** database and table name containing the affected row.\n** ^The final callback parameter is the [rowid] of the row.\n** ^In the case of an update, this is the [rowid] after the update takes place.\n**\n** ^(The update hook is not invoked when internal system tables are\n** modified (i.e. sqlite_master and sqlite_sequence).)^\n** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.\n**\n** ^In the current implementation, the update hook\n** is not invoked when conflicting rows are deleted because of an\n** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook\n** invoked when rows are deleted using the [truncate optimization].\n** The exceptions defined in this paragraph might change in a future\n** release of SQLite.\n**\n** The update hook implementation must not do anything that will modify\n** the database connection that invoked the update hook.  Any actions\n** to modify the database connection must be deferred until after the\n** completion of the [sqlite3_step()] call that triggered the update hook.\n** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their\n** database connections for the meaning of \"modify\" in this paragraph.\n**\n** ^The sqlite3_update_hook(D,C,P) function\n** returns the P argument from the previous call\n** on the same [database connection] D, or NULL for\n** the first call on D.\n**\n** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],\n** and [sqlite3_preupdate_hook()] interfaces.\n*/\nSQLITE_API void *sqlite3_update_hook(\n  sqlite3*, \n  void(*)(void *,int ,char const *,char const *,sqlite3_int64),\n  void*\n);\n\n/*\n** CAPI3REF: Enable Or Disable Shared Pager Cache\n**\n** ^(This routine enables or disables the sharing of the database cache\n** and schema data structures between [database connection | connections]\n** to the same database. Sharing is enabled if the argument is true\n** and disabled if the argument is false.)^\n**\n** ^Cache sharing is enabled and disabled for an entire process.\n** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]). \n** In prior versions of SQLite,\n** sharing was enabled or disabled for each thread separately.\n**\n** ^(The cache sharing mode set by this interface effects all subsequent\n** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].\n** Existing database connections continue to use the sharing mode\n** that was in effect at the time they were opened.)^\n**\n** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled\n** successfully.  An [error code] is returned otherwise.)^\n**\n** ^Shared cache is disabled by default. It is recommended that it stay\n** that way.  In other words, do not use this routine.  This interface\n** continues to be provided for historical compatibility, but its use is\n** discouraged.  Any use of shared cache is discouraged.  If shared cache\n** must be used, it is recommended that shared cache only be enabled for\n** individual database connections using the [sqlite3_open_v2()] interface\n** with the [SQLITE_OPEN_SHAREDCACHE] flag.\n**\n** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0\n** and will always return SQLITE_MISUSE. On those systems, \n** shared cache mode should be enabled per-database connection via \n** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].\n**\n** This interface is threadsafe on processors where writing a\n** 32-bit integer is atomic.\n**\n** See Also:  [SQLite Shared-Cache Mode]\n*/\nSQLITE_API int sqlite3_enable_shared_cache(int);\n\n/*\n** CAPI3REF: Attempt To Free Heap Memory\n**\n** ^The sqlite3_release_memory() interface attempts to free N bytes\n** of heap memory by deallocating non-essential memory allocations\n** held by the database library.   Memory used to cache database\n** pages to improve performance is an example of non-essential memory.\n** ^sqlite3_release_memory() returns the number of bytes actually freed,\n** which might be more or less than the amount requested.\n** ^The sqlite3_release_memory() routine is a no-op returning zero\n** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].\n**\n** See also: [sqlite3_db_release_memory()]\n*/\nSQLITE_API int sqlite3_release_memory(int);\n\n/*\n** CAPI3REF: Free Memory Used By A Database Connection\n** METHOD: sqlite3\n**\n** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap\n** memory as possible from database connection D. Unlike the\n** [sqlite3_release_memory()] interface, this interface is in effect even\n** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is\n** omitted.\n**\n** See also: [sqlite3_release_memory()]\n*/\nSQLITE_API int sqlite3_db_release_memory(sqlite3*);\n\n/*\n** CAPI3REF: Impose A Limit On Heap Size\n**\n** These interfaces impose limits on the amount of heap memory that will be\n** by all database connections within a single process.\n**\n** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the\n** soft limit on the amount of heap memory that may be allocated by SQLite.\n** ^SQLite strives to keep heap memory utilization below the soft heap\n** limit by reducing the number of pages held in the page cache\n** as heap memory usages approaches the limit.\n** ^The soft heap limit is \"soft\" because even though SQLite strives to stay\n** below the limit, it will exceed the limit rather than generate\n** an [SQLITE_NOMEM] error.  In other words, the soft heap limit \n** is advisory only.\n**\n** ^The sqlite3_hard_heap_limit64(N) interface sets a hard upper bound of\n** N bytes on the amount of memory that will be allocated.  ^The\n** sqlite3_hard_heap_limit64(N) interface is similar to\n** sqlite3_soft_heap_limit64(N) except that memory allocations will fail\n** when the hard heap limit is reached.\n**\n** ^The return value from both sqlite3_soft_heap_limit64() and\n** sqlite3_hard_heap_limit64() is the size of\n** the heap limit prior to the call, or negative in the case of an\n** error.  ^If the argument N is negative\n** then no change is made to the heap limit.  Hence, the current\n** size of heap limits can be determined by invoking\n** sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1).\n**\n** ^Setting the heap limits to zero disables the heap limiter mechanism.\n**\n** ^The soft heap limit may not be greater than the hard heap limit.\n** ^If the hard heap limit is enabled and if sqlite3_soft_heap_limit(N)\n** is invoked with a value of N that is greater than the hard heap limit,\n** the the soft heap limit is set to the value of the hard heap limit.\n** ^The soft heap limit is automatically enabled whenever the hard heap\n** limit is enabled. ^When sqlite3_hard_heap_limit64(N) is invoked and\n** the soft heap limit is outside the range of 1..N, then the soft heap\n** limit is set to N.  ^Invoking sqlite3_soft_heap_limit64(0) when the\n** hard heap limit is enabled makes the soft heap limit equal to the\n** hard heap limit.\n**\n** The memory allocation limits can also be adjusted using\n** [PRAGMA soft_heap_limit] and [PRAGMA hard_heap_limit].\n**\n** ^(The heap limits are not enforced in the current implementation\n** if one or more of following conditions are true:\n**\n** <ul>\n** <li> The limit value is set to zero.\n** <li> Memory accounting is disabled using a combination of the\n**      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and\n**      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.\n** <li> An alternative page cache implementation is specified using\n**      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).\n** <li> The page cache allocates from its own memory pool supplied\n**      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than\n**      from the heap.\n** </ul>)^\n**\n** The circumstances under which SQLite will enforce the heap limits may\n** changes in future releases of SQLite.\n*/\nSQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);\nSQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N);\n\n/*\n** CAPI3REF: Deprecated Soft Heap Limit Interface\n** DEPRECATED\n**\n** This is a deprecated version of the [sqlite3_soft_heap_limit64()]\n** interface.  This routine is provided for historical compatibility\n** only.  All new applications should use the\n** [sqlite3_soft_heap_limit64()] interface rather than this one.\n*/\nSQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);\n\n\n/*\n** CAPI3REF: Extract Metadata About A Column Of A Table\n** METHOD: sqlite3\n**\n** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns\n** information about column C of table T in database D\n** on [database connection] X.)^  ^The sqlite3_table_column_metadata()\n** interface returns SQLITE_OK and fills in the non-NULL pointers in\n** the final five arguments with appropriate values if the specified\n** column exists.  ^The sqlite3_table_column_metadata() interface returns\n** SQLITE_ERROR if the specified column does not exist.\n** ^If the column-name parameter to sqlite3_table_column_metadata() is a\n** NULL pointer, then this routine simply checks for the existence of the\n** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it\n** does not.  If the table name parameter T in a call to\n** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is\n** undefined behavior.\n**\n** ^The column is identified by the second, third and fourth parameters to\n** this function. ^(The second parameter is either the name of the database\n** (i.e. \"main\", \"temp\", or an attached database) containing the specified\n** table or NULL.)^ ^If it is NULL, then all attached databases are searched\n** for the table using the same algorithm used by the database engine to\n** resolve unqualified table references.\n**\n** ^The third and fourth parameters to this function are the table and column\n** name of the desired column, respectively.\n**\n** ^Metadata is returned by writing to the memory locations passed as the 5th\n** and subsequent parameters to this function. ^Any of these arguments may be\n** NULL, in which case the corresponding element of metadata is omitted.\n**\n** ^(<blockquote>\n** <table border=\"1\">\n** <tr><th> Parameter <th> Output<br>Type <th>  Description\n**\n** <tr><td> 5th <td> const char* <td> Data type\n** <tr><td> 6th <td> const char* <td> Name of default collation sequence\n** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint\n** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY\n** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]\n** </table>\n** </blockquote>)^\n**\n** ^The memory pointed to by the character pointers returned for the\n** declaration type and collation sequence is valid until the next\n** call to any SQLite API function.\n**\n** ^If the specified table is actually a view, an [error code] is returned.\n**\n** ^If the specified column is \"rowid\", \"oid\" or \"_rowid_\" and the table \n** is not a [WITHOUT ROWID] table and an\n** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output\n** parameters are set for the explicitly declared column. ^(If there is no\n** [INTEGER PRIMARY KEY] column, then the outputs\n** for the [rowid] are set as follows:\n**\n** <pre>\n**     data type: \"INTEGER\"\n**     collation sequence: \"BINARY\"\n**     not null: 0\n**     primary key: 1\n**     auto increment: 0\n** </pre>)^\n**\n** ^This function causes all database schemas to be read from disk and\n** parsed, if that has not already been done, and returns an error if\n** any errors are encountered while loading the schema.\n*/\nSQLITE_API int sqlite3_table_column_metadata(\n  sqlite3 *db,                /* Connection handle */\n  const char *zDbName,        /* Database name or NULL */\n  const char *zTableName,     /* Table name */\n  const char *zColumnName,    /* Column name */\n  char const **pzDataType,    /* OUTPUT: Declared data type */\n  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */\n  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */\n  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */\n  int *pAutoinc               /* OUTPUT: True if column is auto-increment */\n);\n\n/*\n** CAPI3REF: Load An Extension\n** METHOD: sqlite3\n**\n** ^This interface loads an SQLite extension library from the named file.\n**\n** ^The sqlite3_load_extension() interface attempts to load an\n** [SQLite extension] library contained in the file zFile.  If\n** the file cannot be loaded directly, attempts are made to load\n** with various operating-system specific extensions added.\n** So for example, if \"samplelib\" cannot be loaded, then names like\n** \"samplelib.so\" or \"samplelib.dylib\" or \"samplelib.dll\" might\n** be tried also.\n**\n** ^The entry point is zProc.\n** ^(zProc may be 0, in which case SQLite will try to come up with an\n** entry point name on its own.  It first tries \"sqlite3_extension_init\".\n** If that does not work, it constructs a name \"sqlite3_X_init\" where the\n** X is consists of the lower-case equivalent of all ASCII alphabetic\n** characters in the filename from the last \"/\" to the first following\n** \".\" and omitting any initial \"lib\".)^\n** ^The sqlite3_load_extension() interface returns\n** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.\n** ^If an error occurs and pzErrMsg is not 0, then the\n** [sqlite3_load_extension()] interface shall attempt to\n** fill *pzErrMsg with error message text stored in memory\n** obtained from [sqlite3_malloc()]. The calling function\n** should free this memory by calling [sqlite3_free()].\n**\n** ^Extension loading must be enabled using\n** [sqlite3_enable_load_extension()] or\n** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)\n** prior to calling this API,\n** otherwise an error will be returned.\n**\n** <b>Security warning:</b> It is recommended that the \n** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this\n** interface.  The use of the [sqlite3_enable_load_extension()] interface\n** should be avoided.  This will keep the SQL function [load_extension()]\n** disabled and prevent SQL injections from giving attackers\n** access to extension loading capabilities.\n**\n** See also the [load_extension() SQL function].\n*/\nSQLITE_API int sqlite3_load_extension(\n  sqlite3 *db,          /* Load the extension into this database connection */\n  const char *zFile,    /* Name of the shared library containing extension */\n  const char *zProc,    /* Entry point.  Derived from zFile if 0 */\n  char **pzErrMsg       /* Put error message here if not 0 */\n);\n\n/*\n** CAPI3REF: Enable Or Disable Extension Loading\n** METHOD: sqlite3\n**\n** ^So as not to open security holes in older applications that are\n** unprepared to deal with [extension loading], and as a means of disabling\n** [extension loading] while evaluating user-entered SQL, the following API\n** is provided to turn the [sqlite3_load_extension()] mechanism on and off.\n**\n** ^Extension loading is off by default.\n** ^Call the sqlite3_enable_load_extension() routine with onoff==1\n** to turn extension loading on and call it with onoff==0 to turn\n** it back off again.\n**\n** ^This interface enables or disables both the C-API\n** [sqlite3_load_extension()] and the SQL function [load_extension()].\n** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)\n** to enable or disable only the C-API.)^\n**\n** <b>Security warning:</b> It is recommended that extension loading\n** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method\n** rather than this interface, so the [load_extension()] SQL function\n** remains disabled. This will prevent SQL injections from giving attackers\n** access to extension loading capabilities.\n*/\nSQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);\n\n/*\n** CAPI3REF: Automatically Load Statically Linked Extensions\n**\n** ^This interface causes the xEntryPoint() function to be invoked for\n** each new [database connection] that is created.  The idea here is that\n** xEntryPoint() is the entry point for a statically linked [SQLite extension]\n** that is to be automatically loaded into all new database connections.\n**\n** ^(Even though the function prototype shows that xEntryPoint() takes\n** no arguments and returns void, SQLite invokes xEntryPoint() with three\n** arguments and expects an integer result as if the signature of the\n** entry point where as follows:\n**\n** <blockquote><pre>\n** &nbsp;  int xEntryPoint(\n** &nbsp;    sqlite3 *db,\n** &nbsp;    const char **pzErrMsg,\n** &nbsp;    const struct sqlite3_api_routines *pThunk\n** &nbsp;  );\n** </pre></blockquote>)^\n**\n** If the xEntryPoint routine encounters an error, it should make *pzErrMsg\n** point to an appropriate error message (obtained from [sqlite3_mprintf()])\n** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg\n** is NULL before calling the xEntryPoint().  ^SQLite will invoke\n** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any\n** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],\n** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.\n**\n** ^Calling sqlite3_auto_extension(X) with an entry point X that is already\n** on the list of automatic extensions is a harmless no-op. ^No entry point\n** will be called more than once for each database connection that is opened.\n**\n** See also: [sqlite3_reset_auto_extension()]\n** and [sqlite3_cancel_auto_extension()]\n*/\nSQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));\n\n/*\n** CAPI3REF: Cancel Automatic Extension Loading\n**\n** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the\n** initialization routine X that was registered using a prior call to\n** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]\n** routine returns 1 if initialization routine X was successfully \n** unregistered and it returns 0 if X was not on the list of initialization\n** routines.\n*/\nSQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));\n\n/*\n** CAPI3REF: Reset Automatic Extension Loading\n**\n** ^This interface disables all automatic extensions previously\n** registered using [sqlite3_auto_extension()].\n*/\nSQLITE_API void sqlite3_reset_auto_extension(void);\n\n/*\n** The interface to the virtual-table mechanism is currently considered\n** to be experimental.  The interface might change in incompatible ways.\n** If this is a problem for you, do not use the interface at this time.\n**\n** When the virtual-table mechanism stabilizes, we will declare the\n** interface fixed, support it indefinitely, and remove this comment.\n*/\n\n/*\n** Structures used by the virtual table interface\n*/\ntypedef struct sqlite3_vtab sqlite3_vtab;\ntypedef struct sqlite3_index_info sqlite3_index_info;\ntypedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;\ntypedef struct sqlite3_module sqlite3_module;\n\n/*\n** CAPI3REF: Virtual Table Object\n** KEYWORDS: sqlite3_module {virtual table module}\n**\n** This structure, sometimes called a \"virtual table module\", \n** defines the implementation of a [virtual table].  \n** This structure consists mostly of methods for the module.\n**\n** ^A virtual table module is created by filling in a persistent\n** instance of this structure and passing a pointer to that instance\n** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].\n** ^The registration remains valid until it is replaced by a different\n** module or until the [database connection] closes.  The content\n** of this structure must not change while it is registered with\n** any database connection.\n*/\nstruct sqlite3_module {\n  int iVersion;\n  int (*xCreate)(sqlite3*, void *pAux,\n               int argc, const char *const*argv,\n               sqlite3_vtab **ppVTab, char**);\n  int (*xConnect)(sqlite3*, void *pAux,\n               int argc, const char *const*argv,\n               sqlite3_vtab **ppVTab, char**);\n  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);\n  int (*xDisconnect)(sqlite3_vtab *pVTab);\n  int (*xDestroy)(sqlite3_vtab *pVTab);\n  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);\n  int (*xClose)(sqlite3_vtab_cursor*);\n  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,\n                int argc, sqlite3_value **argv);\n  int (*xNext)(sqlite3_vtab_cursor*);\n  int (*xEof)(sqlite3_vtab_cursor*);\n  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);\n  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);\n  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);\n  int (*xBegin)(sqlite3_vtab *pVTab);\n  int (*xSync)(sqlite3_vtab *pVTab);\n  int (*xCommit)(sqlite3_vtab *pVTab);\n  int (*xRollback)(sqlite3_vtab *pVTab);\n  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,\n                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),\n                       void **ppArg);\n  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);\n  /* The methods above are in version 1 of the sqlite_module object. Those \n  ** below are for version 2 and greater. */\n  int (*xSavepoint)(sqlite3_vtab *pVTab, int);\n  int (*xRelease)(sqlite3_vtab *pVTab, int);\n  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);\n  /* The methods above are in versions 1 and 2 of the sqlite_module object.\n  ** Those below are for version 3 and greater. */\n  int (*xShadowName)(const char*);\n};\n\n/*\n** CAPI3REF: Virtual Table Indexing Information\n** KEYWORDS: sqlite3_index_info\n**\n** The sqlite3_index_info structure and its substructures is used as part\n** of the [virtual table] interface to\n** pass information into and receive the reply from the [xBestIndex]\n** method of a [virtual table module].  The fields under **Inputs** are the\n** inputs to xBestIndex and are read-only.  xBestIndex inserts its\n** results into the **Outputs** fields.\n**\n** ^(The aConstraint[] array records WHERE clause constraints of the form:\n**\n** <blockquote>column OP expr</blockquote>\n**\n** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is\n** stored in aConstraint[].op using one of the\n** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^\n** ^(The index of the column is stored in\n** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the\n** expr on the right-hand side can be evaluated (and thus the constraint\n** is usable) and false if it cannot.)^\n**\n** ^The optimizer automatically inverts terms of the form \"expr OP column\"\n** and makes other simplifications to the WHERE clause in an attempt to\n** get as many WHERE clause terms into the form shown above as possible.\n** ^The aConstraint[] array only reports WHERE clause terms that are\n** relevant to the particular virtual table being queried.\n**\n** ^Information about the ORDER BY clause is stored in aOrderBy[].\n** ^Each term of aOrderBy records a column of the ORDER BY clause.\n**\n** The colUsed field indicates which columns of the virtual table may be\n** required by the current scan. Virtual table columns are numbered from\n** zero in the order in which they appear within the CREATE TABLE statement\n** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),\n** the corresponding bit is set within the colUsed mask if the column may be\n** required by SQLite. If the table has at least 64 columns and any column\n** to the right of the first 63 is required, then bit 63 of colUsed is also\n** set. In other words, column iCol may be required if the expression\n** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to \n** non-zero.\n**\n** The [xBestIndex] method must fill aConstraintUsage[] with information\n** about what parameters to pass to xFilter.  ^If argvIndex>0 then\n** the right-hand side of the corresponding aConstraint[] is evaluated\n** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit\n** is true, then the constraint is assumed to be fully handled by the\n** virtual table and might not be checked again by the byte code.)^ ^(The\n** aConstraintUsage[].omit flag is an optimization hint. When the omit flag\n** is left in its default setting of false, the constraint will always be\n** checked separately in byte code.  If the omit flag is change to true, then\n** the constraint may or may not be checked in byte code.  In other words,\n** when the omit flag is true there is no guarantee that the constraint will\n** not be checked again using byte code.)^\n**\n** ^The idxNum and idxPtr values are recorded and passed into the\n** [xFilter] method.\n** ^[sqlite3_free()] is used to free idxPtr if and only if\n** needToFreeIdxPtr is true.\n**\n** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in\n** the correct order to satisfy the ORDER BY clause so that no separate\n** sorting step is required.\n**\n** ^The estimatedCost value is an estimate of the cost of a particular\n** strategy. A cost of N indicates that the cost of the strategy is similar\n** to a linear scan of an SQLite table with N rows. A cost of log(N) \n** indicates that the expense of the operation is similar to that of a\n** binary search on a unique indexed field of an SQLite table with N rows.\n**\n** ^The estimatedRows value is an estimate of the number of rows that\n** will be returned by the strategy.\n**\n** The xBestIndex method may optionally populate the idxFlags field with a \n** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -\n** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite\n** assumes that the strategy may visit at most one row. \n**\n** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then\n** SQLite also assumes that if a call to the xUpdate() method is made as\n** part of the same statement to delete or update a virtual table row and the\n** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback\n** any database changes. In other words, if the xUpdate() returns\n** SQLITE_CONSTRAINT, the database contents must be exactly as they were\n** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not\n** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by\n** the xUpdate method are automatically rolled back by SQLite.\n**\n** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info\n** structure for SQLite [version 3.8.2] ([dateof:3.8.2]). \n** If a virtual table extension is\n** used with an SQLite version earlier than 3.8.2, the results of attempting \n** to read or write the estimatedRows field are undefined (but are likely \n** to include crashing the application). The estimatedRows field should\n** therefore only be used if [sqlite3_libversion_number()] returns a\n** value greater than or equal to 3008002. Similarly, the idxFlags field\n** was added for [version 3.9.0] ([dateof:3.9.0]). \n** It may therefore only be used if\n** sqlite3_libversion_number() returns a value greater than or equal to\n** 3009000.\n*/\nstruct sqlite3_index_info {\n  /* Inputs */\n  int nConstraint;           /* Number of entries in aConstraint */\n  struct sqlite3_index_constraint {\n     int iColumn;              /* Column constrained.  -1 for ROWID */\n     unsigned char op;         /* Constraint operator */\n     unsigned char usable;     /* True if this constraint is usable */\n     int iTermOffset;          /* Used internally - xBestIndex should ignore */\n  } *aConstraint;            /* Table of WHERE clause constraints */\n  int nOrderBy;              /* Number of terms in the ORDER BY clause */\n  struct sqlite3_index_orderby {\n     int iColumn;              /* Column number */\n     unsigned char desc;       /* True for DESC.  False for ASC. */\n  } *aOrderBy;               /* The ORDER BY clause */\n  /* Outputs */\n  struct sqlite3_index_constraint_usage {\n    int argvIndex;           /* if >0, constraint is part of argv to xFilter */\n    unsigned char omit;      /* Do not code a test for this constraint */\n  } *aConstraintUsage;\n  int idxNum;                /* Number used to identify the index */\n  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */\n  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */\n  int orderByConsumed;       /* True if output is already ordered */\n  double estimatedCost;           /* Estimated cost of using this index */\n  /* Fields below are only available in SQLite 3.8.2 and later */\n  sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */\n  /* Fields below are only available in SQLite 3.9.0 and later */\n  int idxFlags;              /* Mask of SQLITE_INDEX_SCAN_* flags */\n  /* Fields below are only available in SQLite 3.10.0 and later */\n  sqlite3_uint64 colUsed;    /* Input: Mask of columns used by statement */\n};\n\n/*\n** CAPI3REF: Virtual Table Scan Flags\n**\n** Virtual table implementations are allowed to set the \n** [sqlite3_index_info].idxFlags field to some combination of\n** these bits.\n*/\n#define SQLITE_INDEX_SCAN_UNIQUE      1     /* Scan visits at most 1 row */\n\n/*\n** CAPI3REF: Virtual Table Constraint Operator Codes\n**\n** These macros define the allowed values for the\n** [sqlite3_index_info].aConstraint[].op field.  Each value represents\n** an operator that is part of a constraint term in the wHERE clause of\n** a query that uses a [virtual table].\n*/\n#define SQLITE_INDEX_CONSTRAINT_EQ         2\n#define SQLITE_INDEX_CONSTRAINT_GT         4\n#define SQLITE_INDEX_CONSTRAINT_LE         8\n#define SQLITE_INDEX_CONSTRAINT_LT        16\n#define SQLITE_INDEX_CONSTRAINT_GE        32\n#define SQLITE_INDEX_CONSTRAINT_MATCH     64\n#define SQLITE_INDEX_CONSTRAINT_LIKE      65\n#define SQLITE_INDEX_CONSTRAINT_GLOB      66\n#define SQLITE_INDEX_CONSTRAINT_REGEXP    67\n#define SQLITE_INDEX_CONSTRAINT_NE        68\n#define SQLITE_INDEX_CONSTRAINT_ISNOT     69\n#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70\n#define SQLITE_INDEX_CONSTRAINT_ISNULL    71\n#define SQLITE_INDEX_CONSTRAINT_IS        72\n#define SQLITE_INDEX_CONSTRAINT_FUNCTION 150\n\n/*\n** CAPI3REF: Register A Virtual Table Implementation\n** METHOD: sqlite3\n**\n** ^These routines are used to register a new [virtual table module] name.\n** ^Module names must be registered before\n** creating a new [virtual table] using the module and before using a\n** preexisting [virtual table] for the module.\n**\n** ^The module name is registered on the [database connection] specified\n** by the first parameter.  ^The name of the module is given by the \n** second parameter.  ^The third parameter is a pointer to\n** the implementation of the [virtual table module].   ^The fourth\n** parameter is an arbitrary client data pointer that is passed through\n** into the [xCreate] and [xConnect] methods of the virtual table module\n** when a new virtual table is be being created or reinitialized.\n**\n** ^The sqlite3_create_module_v2() interface has a fifth parameter which\n** is a pointer to a destructor for the pClientData.  ^SQLite will\n** invoke the destructor function (if it is not NULL) when SQLite\n** no longer needs the pClientData pointer.  ^The destructor will also\n** be invoked if the call to sqlite3_create_module_v2() fails.\n** ^The sqlite3_create_module()\n** interface is equivalent to sqlite3_create_module_v2() with a NULL\n** destructor.\n**\n** ^If the third parameter (the pointer to the sqlite3_module object) is\n** NULL then no new module is create and any existing modules with the\n** same name are dropped.\n**\n** See also: [sqlite3_drop_modules()]\n*/\nSQLITE_API int sqlite3_create_module(\n  sqlite3 *db,               /* SQLite connection to register module with */\n  const char *zName,         /* Name of the module */\n  const sqlite3_module *p,   /* Methods for the module */\n  void *pClientData          /* Client data for xCreate/xConnect */\n);\nSQLITE_API int sqlite3_create_module_v2(\n  sqlite3 *db,               /* SQLite connection to register module with */\n  const char *zName,         /* Name of the module */\n  const sqlite3_module *p,   /* Methods for the module */\n  void *pClientData,         /* Client data for xCreate/xConnect */\n  void(*xDestroy)(void*)     /* Module destructor function */\n);\n\n/*\n** CAPI3REF: Remove Unnecessary Virtual Table Implementations\n** METHOD: sqlite3\n**\n** ^The sqlite3_drop_modules(D,L) interface removes all virtual\n** table modules from database connection D except those named on list L.\n** The L parameter must be either NULL or a pointer to an array of pointers\n** to strings where the array is terminated by a single NULL pointer.\n** ^If the L parameter is NULL, then all virtual table modules are removed.\n**\n** See also: [sqlite3_create_module()]\n*/\nSQLITE_API int sqlite3_drop_modules(\n  sqlite3 *db,                /* Remove modules from this connection */\n  const char **azKeep         /* Except, do not remove the ones named here */\n);\n\n/*\n** CAPI3REF: Virtual Table Instance Object\n** KEYWORDS: sqlite3_vtab\n**\n** Every [virtual table module] implementation uses a subclass\n** of this object to describe a particular instance\n** of the [virtual table].  Each subclass will\n** be tailored to the specific needs of the module implementation.\n** The purpose of this superclass is to define certain fields that are\n** common to all module implementations.\n**\n** ^Virtual tables methods can set an error message by assigning a\n** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should\n** take care that any prior string is freed by a call to [sqlite3_free()]\n** prior to assigning a new string to zErrMsg.  ^After the error message\n** is delivered up to the client application, the string will be automatically\n** freed by sqlite3_free() and the zErrMsg field will be zeroed.\n*/\nstruct sqlite3_vtab {\n  const sqlite3_module *pModule;  /* The module for this virtual table */\n  int nRef;                       /* Number of open cursors */\n  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */\n  /* Virtual table implementations will typically add additional fields */\n};\n\n/*\n** CAPI3REF: Virtual Table Cursor Object\n** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}\n**\n** Every [virtual table module] implementation uses a subclass of the\n** following structure to describe cursors that point into the\n** [virtual table] and are used\n** to loop through the virtual table.  Cursors are created using the\n** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed\n** by the [sqlite3_module.xClose | xClose] method.  Cursors are used\n** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods\n** of the module.  Each module implementation will define\n** the content of a cursor structure to suit its own needs.\n**\n** This superclass exists in order to define fields of the cursor that\n** are common to all implementations.\n*/\nstruct sqlite3_vtab_cursor {\n  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */\n  /* Virtual table implementations will typically add additional fields */\n};\n\n/*\n** CAPI3REF: Declare The Schema Of A Virtual Table\n**\n** ^The [xCreate] and [xConnect] methods of a\n** [virtual table module] call this interface\n** to declare the format (the names and datatypes of the columns) of\n** the virtual tables they implement.\n*/\nSQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);\n\n/*\n** CAPI3REF: Overload A Function For A Virtual Table\n** METHOD: sqlite3\n**\n** ^(Virtual tables can provide alternative implementations of functions\n** using the [xFindFunction] method of the [virtual table module].  \n** But global versions of those functions\n** must exist in order to be overloaded.)^\n**\n** ^(This API makes sure a global version of a function with a particular\n** name and number of parameters exists.  If no such function exists\n** before this API is called, a new function is created.)^  ^The implementation\n** of the new function always causes an exception to be thrown.  So\n** the new function is not good for anything by itself.  Its only\n** purpose is to be a placeholder function that can be overloaded\n** by a [virtual table].\n*/\nSQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);\n\n/*\n** The interface to the virtual-table mechanism defined above (back up\n** to a comment remarkably similar to this one) is currently considered\n** to be experimental.  The interface might change in incompatible ways.\n** If this is a problem for you, do not use the interface at this time.\n**\n** When the virtual-table mechanism stabilizes, we will declare the\n** interface fixed, support it indefinitely, and remove this comment.\n*/\n\n/*\n** CAPI3REF: A Handle To An Open BLOB\n** KEYWORDS: {BLOB handle} {BLOB handles}\n**\n** An instance of this object represents an open BLOB on which\n** [sqlite3_blob_open | incremental BLOB I/O] can be performed.\n** ^Objects of this type are created by [sqlite3_blob_open()]\n** and destroyed by [sqlite3_blob_close()].\n** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces\n** can be used to read or write small subsections of the BLOB.\n** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.\n*/\ntypedef struct sqlite3_blob sqlite3_blob;\n\n/*\n** CAPI3REF: Open A BLOB For Incremental I/O\n** METHOD: sqlite3\n** CONSTRUCTOR: sqlite3_blob\n**\n** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located\n** in row iRow, column zColumn, table zTable in database zDb;\n** in other words, the same BLOB that would be selected by:\n**\n** <pre>\n**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;\n** </pre>)^\n**\n** ^(Parameter zDb is not the filename that contains the database, but \n** rather the symbolic name of the database. For attached databases, this is\n** the name that appears after the AS keyword in the [ATTACH] statement.\n** For the main database file, the database name is \"main\". For TEMP\n** tables, the database name is \"temp\".)^\n**\n** ^If the flags parameter is non-zero, then the BLOB is opened for read\n** and write access. ^If the flags parameter is zero, the BLOB is opened for\n** read-only access.\n**\n** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored\n** in *ppBlob. Otherwise an [error code] is returned and, unless the error\n** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided\n** the API is not misused, it is always safe to call [sqlite3_blob_close()] \n** on *ppBlob after this function it returns.\n**\n** This function fails with SQLITE_ERROR if any of the following are true:\n** <ul>\n**   <li> ^(Database zDb does not exist)^, \n**   <li> ^(Table zTable does not exist within database zDb)^, \n**   <li> ^(Table zTable is a WITHOUT ROWID table)^, \n**   <li> ^(Column zColumn does not exist)^,\n**   <li> ^(Row iRow is not present in the table)^,\n**   <li> ^(The specified column of row iRow contains a value that is not\n**         a TEXT or BLOB value)^,\n**   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE \n**         constraint and the blob is being opened for read/write access)^,\n**   <li> ^([foreign key constraints | Foreign key constraints] are enabled, \n**         column zColumn is part of a [child key] definition and the blob is\n**         being opened for read/write access)^.\n** </ul>\n**\n** ^Unless it returns SQLITE_MISUSE, this function sets the \n** [database connection] error code and message accessible via \n** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. \n**\n** A BLOB referenced by sqlite3_blob_open() may be read using the\n** [sqlite3_blob_read()] interface and modified by using\n** [sqlite3_blob_write()].  The [BLOB handle] can be moved to a\n** different row of the same table using the [sqlite3_blob_reopen()]\n** interface.  However, the column, table, or database of a [BLOB handle]\n** cannot be changed after the [BLOB handle] is opened.\n**\n** ^(If the row that a BLOB handle points to is modified by an\n** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects\n** then the BLOB handle is marked as \"expired\".\n** This is true if any column of the row is changed, even a column\n** other than the one the BLOB handle is open on.)^\n** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for\n** an expired BLOB handle fail with a return code of [SQLITE_ABORT].\n** ^(Changes written into a BLOB prior to the BLOB expiring are not\n** rolled back by the expiration of the BLOB.  Such changes will eventually\n** commit if the transaction continues to completion.)^\n**\n** ^Use the [sqlite3_blob_bytes()] interface to determine the size of\n** the opened blob.  ^The size of a blob may not be changed by this\n** interface.  Use the [UPDATE] SQL command to change the size of a\n** blob.\n**\n** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces\n** and the built-in [zeroblob] SQL function may be used to create a \n** zero-filled blob to read or write using the incremental-blob interface.\n**\n** To avoid a resource leak, every open [BLOB handle] should eventually\n** be released by a call to [sqlite3_blob_close()].\n**\n** See also: [sqlite3_blob_close()],\n** [sqlite3_blob_reopen()], [sqlite3_blob_read()],\n** [sqlite3_blob_bytes()], [sqlite3_blob_write()].\n*/\nSQLITE_API int sqlite3_blob_open(\n  sqlite3*,\n  const char *zDb,\n  const char *zTable,\n  const char *zColumn,\n  sqlite3_int64 iRow,\n  int flags,\n  sqlite3_blob **ppBlob\n);\n\n/*\n** CAPI3REF: Move a BLOB Handle to a New Row\n** METHOD: sqlite3_blob\n**\n** ^This function is used to move an existing [BLOB handle] so that it points\n** to a different row of the same database table. ^The new row is identified\n** by the rowid value passed as the second argument. Only the row can be\n** changed. ^The database, table and column on which the blob handle is open\n** remain the same. Moving an existing [BLOB handle] to a new row is\n** faster than closing the existing handle and opening a new one.\n**\n** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -\n** it must exist and there must be either a blob or text value stored in\n** the nominated column.)^ ^If the new row is not present in the table, or if\n** it does not contain a blob or text value, or if another error occurs, an\n** SQLite error code is returned and the blob handle is considered aborted.\n** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or\n** [sqlite3_blob_reopen()] on an aborted blob handle immediately return\n** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle\n** always returns zero.\n**\n** ^This function sets the database handle error code and message.\n*/\nSQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);\n\n/*\n** CAPI3REF: Close A BLOB Handle\n** DESTRUCTOR: sqlite3_blob\n**\n** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed\n** unconditionally.  Even if this routine returns an error code, the \n** handle is still closed.)^\n**\n** ^If the blob handle being closed was opened for read-write access, and if\n** the database is in auto-commit mode and there are no other open read-write\n** blob handles or active write statements, the current transaction is\n** committed. ^If an error occurs while committing the transaction, an error\n** code is returned and the transaction rolled back.\n**\n** Calling this function with an argument that is not a NULL pointer or an\n** open blob handle results in undefined behaviour. ^Calling this routine \n** with a null pointer (such as would be returned by a failed call to \n** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function\n** is passed a valid open blob handle, the values returned by the \n** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.\n*/\nSQLITE_API int sqlite3_blob_close(sqlite3_blob *);\n\n/*\n** CAPI3REF: Return The Size Of An Open BLOB\n** METHOD: sqlite3_blob\n**\n** ^Returns the size in bytes of the BLOB accessible via the \n** successfully opened [BLOB handle] in its only argument.  ^The\n** incremental blob I/O routines can only read or overwriting existing\n** blob content; they cannot change the size of a blob.\n**\n** This routine only works on a [BLOB handle] which has been created\n** by a prior successful call to [sqlite3_blob_open()] and which has not\n** been closed by [sqlite3_blob_close()].  Passing any other pointer in\n** to this routine results in undefined and probably undesirable behavior.\n*/\nSQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);\n\n/*\n** CAPI3REF: Read Data From A BLOB Incrementally\n** METHOD: sqlite3_blob\n**\n** ^(This function is used to read data from an open [BLOB handle] into a\n** caller-supplied buffer. N bytes of data are copied into buffer Z\n** from the open BLOB, starting at offset iOffset.)^\n**\n** ^If offset iOffset is less than N bytes from the end of the BLOB,\n** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is\n** less than zero, [SQLITE_ERROR] is returned and no data is read.\n** ^The size of the blob (and hence the maximum value of N+iOffset)\n** can be determined using the [sqlite3_blob_bytes()] interface.\n**\n** ^An attempt to read from an expired [BLOB handle] fails with an\n** error code of [SQLITE_ABORT].\n**\n** ^(On success, sqlite3_blob_read() returns SQLITE_OK.\n** Otherwise, an [error code] or an [extended error code] is returned.)^\n**\n** This routine only works on a [BLOB handle] which has been created\n** by a prior successful call to [sqlite3_blob_open()] and which has not\n** been closed by [sqlite3_blob_close()].  Passing any other pointer in\n** to this routine results in undefined and probably undesirable behavior.\n**\n** See also: [sqlite3_blob_write()].\n*/\nSQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);\n\n/*\n** CAPI3REF: Write Data Into A BLOB Incrementally\n** METHOD: sqlite3_blob\n**\n** ^(This function is used to write data into an open [BLOB handle] from a\n** caller-supplied buffer. N bytes of data are copied from the buffer Z\n** into the open BLOB, starting at offset iOffset.)^\n**\n** ^(On success, sqlite3_blob_write() returns SQLITE_OK.\n** Otherwise, an  [error code] or an [extended error code] is returned.)^\n** ^Unless SQLITE_MISUSE is returned, this function sets the \n** [database connection] error code and message accessible via \n** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. \n**\n** ^If the [BLOB handle] passed as the first argument was not opened for\n** writing (the flags parameter to [sqlite3_blob_open()] was zero),\n** this function returns [SQLITE_READONLY].\n**\n** This function may only modify the contents of the BLOB; it is\n** not possible to increase the size of a BLOB using this API.\n** ^If offset iOffset is less than N bytes from the end of the BLOB,\n** [SQLITE_ERROR] is returned and no data is written. The size of the \n** BLOB (and hence the maximum value of N+iOffset) can be determined \n** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less \n** than zero [SQLITE_ERROR] is returned and no data is written.\n**\n** ^An attempt to write to an expired [BLOB handle] fails with an\n** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred\n** before the [BLOB handle] expired are not rolled back by the\n** expiration of the handle, though of course those changes might\n** have been overwritten by the statement that expired the BLOB handle\n** or by other independent statements.\n**\n** This routine only works on a [BLOB handle] which has been created\n** by a prior successful call to [sqlite3_blob_open()] and which has not\n** been closed by [sqlite3_blob_close()].  Passing any other pointer in\n** to this routine results in undefined and probably undesirable behavior.\n**\n** See also: [sqlite3_blob_read()].\n*/\nSQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);\n\n/*\n** CAPI3REF: Virtual File System Objects\n**\n** A virtual filesystem (VFS) is an [sqlite3_vfs] object\n** that SQLite uses to interact\n** with the underlying operating system.  Most SQLite builds come with a\n** single default VFS that is appropriate for the host computer.\n** New VFSes can be registered and existing VFSes can be unregistered.\n** The following interfaces are provided.\n**\n** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.\n** ^Names are case sensitive.\n** ^Names are zero-terminated UTF-8 strings.\n** ^If there is no match, a NULL pointer is returned.\n** ^If zVfsName is NULL then the default VFS is returned.\n**\n** ^New VFSes are registered with sqlite3_vfs_register().\n** ^Each new VFS becomes the default VFS if the makeDflt flag is set.\n** ^The same VFS can be registered multiple times without injury.\n** ^To make an existing VFS into the default VFS, register it again\n** with the makeDflt flag set.  If two different VFSes with the\n** same name are registered, the behavior is undefined.  If a\n** VFS is registered with a name that is NULL or an empty string,\n** then the behavior is undefined.\n**\n** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.\n** ^(If the default VFS is unregistered, another VFS is chosen as\n** the default.  The choice for the new VFS is arbitrary.)^\n*/\nSQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);\nSQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);\nSQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);\n\n/*\n** CAPI3REF: Mutexes\n**\n** The SQLite core uses these routines for thread\n** synchronization. Though they are intended for internal\n** use by SQLite, code that links against SQLite is\n** permitted to use any of these routines.\n**\n** The SQLite source code contains multiple implementations\n** of these mutex routines.  An appropriate implementation\n** is selected automatically at compile-time.  The following\n** implementations are available in the SQLite core:\n**\n** <ul>\n** <li>   SQLITE_MUTEX_PTHREADS\n** <li>   SQLITE_MUTEX_W32\n** <li>   SQLITE_MUTEX_NOOP\n** </ul>\n**\n** The SQLITE_MUTEX_NOOP implementation is a set of routines\n** that does no real locking and is appropriate for use in\n** a single-threaded application.  The SQLITE_MUTEX_PTHREADS and\n** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix\n** and Windows.\n**\n** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor\n** macro defined (with \"-DSQLITE_MUTEX_APPDEF=1\"), then no mutex\n** implementation is included with the library. In this case the\n** application must supply a custom mutex implementation using the\n** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function\n** before calling sqlite3_initialize() or any other public sqlite3_\n** function that calls sqlite3_initialize().\n**\n** ^The sqlite3_mutex_alloc() routine allocates a new\n** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()\n** routine returns NULL if it is unable to allocate the requested\n** mutex.  The argument to sqlite3_mutex_alloc() must one of these\n** integer constants:\n**\n** <ul>\n** <li>  SQLITE_MUTEX_FAST\n** <li>  SQLITE_MUTEX_RECURSIVE\n** <li>  SQLITE_MUTEX_STATIC_MASTER\n** <li>  SQLITE_MUTEX_STATIC_MEM\n** <li>  SQLITE_MUTEX_STATIC_OPEN\n** <li>  SQLITE_MUTEX_STATIC_PRNG\n** <li>  SQLITE_MUTEX_STATIC_LRU\n** <li>  SQLITE_MUTEX_STATIC_PMEM\n** <li>  SQLITE_MUTEX_STATIC_APP1\n** <li>  SQLITE_MUTEX_STATIC_APP2\n** <li>  SQLITE_MUTEX_STATIC_APP3\n** <li>  SQLITE_MUTEX_STATIC_VFS1\n** <li>  SQLITE_MUTEX_STATIC_VFS2\n** <li>  SQLITE_MUTEX_STATIC_VFS3\n** </ul>\n**\n** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)\n** cause sqlite3_mutex_alloc() to create\n** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE\n** is used but not necessarily so when SQLITE_MUTEX_FAST is used.\n** The mutex implementation does not need to make a distinction\n** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does\n** not want to.  SQLite will only request a recursive mutex in\n** cases where it really needs one.  If a faster non-recursive mutex\n** implementation is available on the host platform, the mutex subsystem\n** might return such a mutex in response to SQLITE_MUTEX_FAST.\n**\n** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other\n** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return\n** a pointer to a static preexisting mutex.  ^Nine static mutexes are\n** used by the current version of SQLite.  Future versions of SQLite\n** may add additional static mutexes.  Static mutexes are for internal\n** use by SQLite only.  Applications that use SQLite mutexes should\n** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or\n** SQLITE_MUTEX_RECURSIVE.\n**\n** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST\n** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()\n** returns a different mutex on every call.  ^For the static\n** mutex types, the same mutex is returned on every call that has\n** the same type number.\n**\n** ^The sqlite3_mutex_free() routine deallocates a previously\n** allocated dynamic mutex.  Attempting to deallocate a static\n** mutex results in undefined behavior.\n**\n** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt\n** to enter a mutex.  ^If another thread is already within the mutex,\n** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return\n** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]\n** upon successful entry.  ^(Mutexes created using\n** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.\n** In such cases, the\n** mutex must be exited an equal number of times before another thread\n** can enter.)^  If the same thread tries to enter any mutex other\n** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.\n**\n** ^(Some systems (for example, Windows 95) do not support the operation\n** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()\n** will always return SQLITE_BUSY. The SQLite core only ever uses\n** sqlite3_mutex_try() as an optimization so this is acceptable \n** behavior.)^\n**\n** ^The sqlite3_mutex_leave() routine exits a mutex that was\n** previously entered by the same thread.   The behavior\n** is undefined if the mutex is not currently entered by the\n** calling thread or is not currently allocated.\n**\n** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or\n** sqlite3_mutex_leave() is a NULL pointer, then all three routines\n** behave as no-ops.\n**\n** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].\n*/\nSQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);\nSQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);\nSQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);\nSQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);\nSQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);\n\n/*\n** CAPI3REF: Mutex Methods Object\n**\n** An instance of this structure defines the low-level routines\n** used to allocate and use mutexes.\n**\n** Usually, the default mutex implementations provided by SQLite are\n** sufficient, however the application has the option of substituting a custom\n** implementation for specialized deployments or systems for which SQLite\n** does not provide a suitable implementation. In this case, the application\n** creates and populates an instance of this structure to pass\n** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.\n** Additionally, an instance of this structure can be used as an\n** output variable when querying the system for the current mutex\n** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.\n**\n** ^The xMutexInit method defined by this structure is invoked as\n** part of system initialization by the sqlite3_initialize() function.\n** ^The xMutexInit routine is called by SQLite exactly once for each\n** effective call to [sqlite3_initialize()].\n**\n** ^The xMutexEnd method defined by this structure is invoked as\n** part of system shutdown by the sqlite3_shutdown() function. The\n** implementation of this method is expected to release all outstanding\n** resources obtained by the mutex methods implementation, especially\n** those obtained by the xMutexInit method.  ^The xMutexEnd()\n** interface is invoked exactly once for each call to [sqlite3_shutdown()].\n**\n** ^(The remaining seven methods defined by this structure (xMutexAlloc,\n** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and\n** xMutexNotheld) implement the following interfaces (respectively):\n**\n** <ul>\n**   <li>  [sqlite3_mutex_alloc()] </li>\n**   <li>  [sqlite3_mutex_free()] </li>\n**   <li>  [sqlite3_mutex_enter()] </li>\n**   <li>  [sqlite3_mutex_try()] </li>\n**   <li>  [sqlite3_mutex_leave()] </li>\n**   <li>  [sqlite3_mutex_held()] </li>\n**   <li>  [sqlite3_mutex_notheld()] </li>\n** </ul>)^\n**\n** The only difference is that the public sqlite3_XXX functions enumerated\n** above silently ignore any invocations that pass a NULL pointer instead\n** of a valid mutex handle. The implementations of the methods defined\n** by this structure are not required to handle this case. The results\n** of passing a NULL pointer instead of a valid mutex handle are undefined\n** (i.e. it is acceptable to provide an implementation that segfaults if\n** it is passed a NULL pointer).\n**\n** The xMutexInit() method must be threadsafe.  It must be harmless to\n** invoke xMutexInit() multiple times within the same process and without\n** intervening calls to xMutexEnd().  Second and subsequent calls to\n** xMutexInit() must be no-ops.\n**\n** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]\n** and its associates).  Similarly, xMutexAlloc() must not use SQLite memory\n** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite\n** memory allocation for a fast or recursive mutex.\n**\n** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is\n** called, but only if the prior call to xMutexInit returned SQLITE_OK.\n** If xMutexInit fails in any way, it is expected to clean up after itself\n** prior to returning.\n*/\ntypedef struct sqlite3_mutex_methods sqlite3_mutex_methods;\nstruct sqlite3_mutex_methods {\n  int (*xMutexInit)(void);\n  int (*xMutexEnd)(void);\n  sqlite3_mutex *(*xMutexAlloc)(int);\n  void (*xMutexFree)(sqlite3_mutex *);\n  void (*xMutexEnter)(sqlite3_mutex *);\n  int (*xMutexTry)(sqlite3_mutex *);\n  void (*xMutexLeave)(sqlite3_mutex *);\n  int (*xMutexHeld)(sqlite3_mutex *);\n  int (*xMutexNotheld)(sqlite3_mutex *);\n};\n\n/*\n** CAPI3REF: Mutex Verification Routines\n**\n** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines\n** are intended for use inside assert() statements.  The SQLite core\n** never uses these routines except inside an assert() and applications\n** are advised to follow the lead of the core.  The SQLite core only\n** provides implementations for these routines when it is compiled\n** with the SQLITE_DEBUG flag.  External mutex implementations\n** are only required to provide these routines if SQLITE_DEBUG is\n** defined and if NDEBUG is not defined.\n**\n** These routines should return true if the mutex in their argument\n** is held or not held, respectively, by the calling thread.\n**\n** The implementation is not required to provide versions of these\n** routines that actually work. If the implementation does not provide working\n** versions of these routines, it should at least provide stubs that always\n** return true so that one does not get spurious assertion failures.\n**\n** If the argument to sqlite3_mutex_held() is a NULL pointer then\n** the routine should return 1.   This seems counter-intuitive since\n** clearly the mutex cannot be held if it does not exist.  But\n** the reason the mutex does not exist is because the build is not\n** using mutexes.  And we do not want the assert() containing the\n** call to sqlite3_mutex_held() to fail, so a non-zero return is\n** the appropriate thing to do.  The sqlite3_mutex_notheld()\n** interface should also return 1 when given a NULL pointer.\n*/\n#ifndef NDEBUG\nSQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);\nSQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);\n#endif\n\n/*\n** CAPI3REF: Mutex Types\n**\n** The [sqlite3_mutex_alloc()] interface takes a single argument\n** which is one of these integer constants.\n**\n** The set of static mutexes may change from one SQLite release to the\n** next.  Applications that override the built-in mutex logic must be\n** prepared to accommodate additional static mutexes.\n*/\n#define SQLITE_MUTEX_FAST             0\n#define SQLITE_MUTEX_RECURSIVE        1\n#define SQLITE_MUTEX_STATIC_MASTER    2\n#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */\n#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */\n#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */\n#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_randomness() */\n#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */\n#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */\n#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */\n#define SQLITE_MUTEX_STATIC_APP1      8  /* For use by application */\n#define SQLITE_MUTEX_STATIC_APP2      9  /* For use by application */\n#define SQLITE_MUTEX_STATIC_APP3     10  /* For use by application */\n#define SQLITE_MUTEX_STATIC_VFS1     11  /* For use by built-in VFS */\n#define SQLITE_MUTEX_STATIC_VFS2     12  /* For use by extension VFS */\n#define SQLITE_MUTEX_STATIC_VFS3     13  /* For use by application VFS */\n\n/*\n** CAPI3REF: Retrieve the mutex for a database connection\n** METHOD: sqlite3\n**\n** ^This interface returns a pointer the [sqlite3_mutex] object that \n** serializes access to the [database connection] given in the argument\n** when the [threading mode] is Serialized.\n** ^If the [threading mode] is Single-thread or Multi-thread then this\n** routine returns a NULL pointer.\n*/\nSQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);\n\n/*\n** CAPI3REF: Low-Level Control Of Database Files\n** METHOD: sqlite3\n** KEYWORDS: {file control}\n**\n** ^The [sqlite3_file_control()] interface makes a direct call to the\n** xFileControl method for the [sqlite3_io_methods] object associated\n** with a particular database identified by the second argument. ^The\n** name of the database is \"main\" for the main database or \"temp\" for the\n** TEMP database, or the name that appears after the AS keyword for\n** databases that are added using the [ATTACH] SQL command.\n** ^A NULL pointer can be used in place of \"main\" to refer to the\n** main database file.\n** ^The third and fourth parameters to this routine\n** are passed directly through to the second and third parameters of\n** the xFileControl method.  ^The return value of the xFileControl\n** method becomes the return value of this routine.\n**\n** A few opcodes for [sqlite3_file_control()] are handled directly\n** by the SQLite core and never invoke the \n** sqlite3_io_methods.xFileControl method.\n** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes\n** a pointer to the underlying [sqlite3_file] object to be written into\n** the space pointed to by the 4th parameter.  The\n** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns\n** the [sqlite3_file] object associated with the journal file instead of\n** the main database.  The [SQLITE_FCNTL_VFS_POINTER] opcode returns\n** a pointer to the underlying [sqlite3_vfs] object for the file.\n** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter\n** from the pager.\n**\n** ^If the second parameter (zDbName) does not match the name of any\n** open database file, then SQLITE_ERROR is returned.  ^This error\n** code is not remembered and will not be recalled by [sqlite3_errcode()]\n** or [sqlite3_errmsg()].  The underlying xFileControl method might\n** also return SQLITE_ERROR.  There is no way to distinguish between\n** an incorrect zDbName and an SQLITE_ERROR return from the underlying\n** xFileControl method.\n**\n** See also: [file control opcodes]\n*/\nSQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);\n\n/*\n** CAPI3REF: Testing Interface\n**\n** ^The sqlite3_test_control() interface is used to read out internal\n** state of SQLite and to inject faults into SQLite for testing\n** purposes.  ^The first parameter is an operation code that determines\n** the number, meaning, and operation of all subsequent parameters.\n**\n** This interface is not for use by applications.  It exists solely\n** for verifying the correct operation of the SQLite library.  Depending\n** on how the SQLite library is compiled, this interface might not exist.\n**\n** The details of the operation codes, their meanings, the parameters\n** they take, and what they do are all subject to change without notice.\n** Unlike most of the SQLite API, this function is not guaranteed to\n** operate consistently from one release to the next.\n*/\nSQLITE_API int sqlite3_test_control(int op, ...);\n\n/*\n** CAPI3REF: Testing Interface Operation Codes\n**\n** These constants are the valid operation code parameters used\n** as the first argument to [sqlite3_test_control()].\n**\n** These parameters and their meanings are subject to change\n** without notice.  These values are for testing purposes only.\n** Applications should not use any of these parameters or the\n** [sqlite3_test_control()] interface.\n*/\n#define SQLITE_TESTCTRL_FIRST                    5\n#define SQLITE_TESTCTRL_PRNG_SAVE                5\n#define SQLITE_TESTCTRL_PRNG_RESTORE             6\n#define SQLITE_TESTCTRL_PRNG_RESET               7  /* NOT USED */\n#define SQLITE_TESTCTRL_BITVEC_TEST              8\n#define SQLITE_TESTCTRL_FAULT_INSTALL            9\n#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10\n#define SQLITE_TESTCTRL_PENDING_BYTE            11\n#define SQLITE_TESTCTRL_ASSERT                  12\n#define SQLITE_TESTCTRL_ALWAYS                  13\n#define SQLITE_TESTCTRL_RESERVE                 14  /* NOT USED */\n#define SQLITE_TESTCTRL_OPTIMIZATIONS           15\n#define SQLITE_TESTCTRL_ISKEYWORD               16  /* NOT USED */\n#define SQLITE_TESTCTRL_SCRATCHMALLOC           17  /* NOT USED */\n#define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS      17\n#define SQLITE_TESTCTRL_LOCALTIME_FAULT         18\n#define SQLITE_TESTCTRL_EXPLAIN_STMT            19  /* NOT USED */\n#define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD    19\n#define SQLITE_TESTCTRL_NEVER_CORRUPT           20\n#define SQLITE_TESTCTRL_VDBE_COVERAGE           21\n#define SQLITE_TESTCTRL_BYTEORDER               22\n#define SQLITE_TESTCTRL_ISINIT                  23\n#define SQLITE_TESTCTRL_SORTER_MMAP             24\n#define SQLITE_TESTCTRL_IMPOSTER                25\n#define SQLITE_TESTCTRL_PARSER_COVERAGE         26\n#define SQLITE_TESTCTRL_RESULT_INTREAL          27\n#define SQLITE_TESTCTRL_PRNG_SEED               28\n#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS     29\n#define SQLITE_TESTCTRL_LAST                    29  /* Largest TESTCTRL */\n\n/*\n** CAPI3REF: SQL Keyword Checking\n**\n** These routines provide access to the set of SQL language keywords \n** recognized by SQLite.  Applications can uses these routines to determine\n** whether or not a specific identifier needs to be escaped (for example,\n** by enclosing in double-quotes) so as not to confuse the parser.\n**\n** The sqlite3_keyword_count() interface returns the number of distinct\n** keywords understood by SQLite.\n**\n** The sqlite3_keyword_name(N,Z,L) interface finds the N-th keyword and\n** makes *Z point to that keyword expressed as UTF8 and writes the number\n** of bytes in the keyword into *L.  The string that *Z points to is not\n** zero-terminated.  The sqlite3_keyword_name(N,Z,L) routine returns\n** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z\n** or L are NULL or invalid pointers then calls to\n** sqlite3_keyword_name(N,Z,L) result in undefined behavior.\n**\n** The sqlite3_keyword_check(Z,L) interface checks to see whether or not\n** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero\n** if it is and zero if not.\n**\n** The parser used by SQLite is forgiving.  It is often possible to use\n** a keyword as an identifier as long as such use does not result in a\n** parsing ambiguity.  For example, the statement\n** \"CREATE TABLE BEGIN(REPLACE,PRAGMA,END);\" is accepted by SQLite, and\n** creates a new table named \"BEGIN\" with three columns named\n** \"REPLACE\", \"PRAGMA\", and \"END\".  Nevertheless, best practice is to avoid\n** using keywords as identifiers.  Common techniques used to avoid keyword\n** name collisions include:\n** <ul>\n** <li> Put all identifier names inside double-quotes.  This is the official\n**      SQL way to escape identifier names.\n** <li> Put identifier names inside &#91;...&#93;.  This is not standard SQL,\n**      but it is what SQL Server does and so lots of programmers use this\n**      technique.\n** <li> Begin every identifier with the letter \"Z\" as no SQL keywords start\n**      with \"Z\".\n** <li> Include a digit somewhere in every identifier name.\n** </ul>\n**\n** Note that the number of keywords understood by SQLite can depend on\n** compile-time options.  For example, \"VACUUM\" is not a keyword if\n** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option.  Also,\n** new keywords may be added to future releases of SQLite.\n*/\nSQLITE_API int sqlite3_keyword_count(void);\nSQLITE_API int sqlite3_keyword_name(int,const char**,int*);\nSQLITE_API int sqlite3_keyword_check(const char*,int);\n\n/*\n** CAPI3REF: Dynamic String Object\n** KEYWORDS: {dynamic string}\n**\n** An instance of the sqlite3_str object contains a dynamically-sized\n** string under construction.\n**\n** The lifecycle of an sqlite3_str object is as follows:\n** <ol>\n** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].\n** <li> ^Text is appended to the sqlite3_str object using various\n** methods, such as [sqlite3_str_appendf()].\n** <li> ^The sqlite3_str object is destroyed and the string it created\n** is returned using the [sqlite3_str_finish()] interface.\n** </ol>\n*/\ntypedef struct sqlite3_str sqlite3_str;\n\n/*\n** CAPI3REF: Create A New Dynamic String Object\n** CONSTRUCTOR: sqlite3_str\n**\n** ^The [sqlite3_str_new(D)] interface allocates and initializes\n** a new [sqlite3_str] object.  To avoid memory leaks, the object returned by\n** [sqlite3_str_new()] must be freed by a subsequent call to \n** [sqlite3_str_finish(X)].\n**\n** ^The [sqlite3_str_new(D)] interface always returns a pointer to a\n** valid [sqlite3_str] object, though in the event of an out-of-memory\n** error the returned object might be a special singleton that will\n** silently reject new text, always return SQLITE_NOMEM from \n** [sqlite3_str_errcode()], always return 0 for \n** [sqlite3_str_length()], and always return NULL from\n** [sqlite3_str_finish(X)].  It is always safe to use the value\n** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter\n** to any of the other [sqlite3_str] methods.\n**\n** The D parameter to [sqlite3_str_new(D)] may be NULL.  If the\n** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum\n** length of the string contained in the [sqlite3_str] object will be\n** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead\n** of [SQLITE_MAX_LENGTH].\n*/\nSQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);\n\n/*\n** CAPI3REF: Finalize A Dynamic String\n** DESTRUCTOR: sqlite3_str\n**\n** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X\n** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]\n** that contains the constructed string.  The calling application should\n** pass the returned value to [sqlite3_free()] to avoid a memory leak.\n** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any\n** errors were encountered during construction of the string.  ^The\n** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the\n** string in [sqlite3_str] object X is zero bytes long.\n*/\nSQLITE_API char *sqlite3_str_finish(sqlite3_str*);\n\n/*\n** CAPI3REF: Add Content To A Dynamic String\n** METHOD: sqlite3_str\n**\n** These interfaces add content to an sqlite3_str object previously obtained\n** from [sqlite3_str_new()].\n**\n** ^The [sqlite3_str_appendf(X,F,...)] and \n** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]\n** functionality of SQLite to append formatted text onto the end of \n** [sqlite3_str] object X.\n**\n** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S\n** onto the end of the [sqlite3_str] object X.  N must be non-negative.\n** S must contain at least N non-zero bytes of content.  To append a\n** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]\n** method instead.\n**\n** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of\n** zero-terminated string S onto the end of [sqlite3_str] object X.\n**\n** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the\n** single-byte character C onto the end of [sqlite3_str] object X.\n** ^This method can be used, for example, to add whitespace indentation.\n**\n** ^The [sqlite3_str_reset(X)] method resets the string under construction\n** inside [sqlite3_str] object X back to zero bytes in length.  \n**\n** These methods do not return a result code.  ^If an error occurs, that fact\n** is recorded in the [sqlite3_str] object and can be recovered by a\n** subsequent call to [sqlite3_str_errcode(X)].\n*/\nSQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);\nSQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);\nSQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);\nSQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);\nSQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);\nSQLITE_API void sqlite3_str_reset(sqlite3_str*);\n\n/*\n** CAPI3REF: Status Of A Dynamic String\n** METHOD: sqlite3_str\n**\n** These interfaces return the current status of an [sqlite3_str] object.\n**\n** ^If any prior errors have occurred while constructing the dynamic string\n** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return\n** an appropriate error code.  ^The [sqlite3_str_errcode(X)] method returns\n** [SQLITE_NOMEM] following any out-of-memory error, or\n** [SQLITE_TOOBIG] if the size of the dynamic string exceeds\n** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.\n**\n** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,\n** of the dynamic string under construction in [sqlite3_str] object X.\n** ^The length returned by [sqlite3_str_length(X)] does not include the\n** zero-termination byte.\n**\n** ^The [sqlite3_str_value(X)] method returns a pointer to the current\n** content of the dynamic string under construction in X.  The value\n** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X\n** and might be freed or altered by any subsequent method on the same\n** [sqlite3_str] object.  Applications must not used the pointer returned\n** [sqlite3_str_value(X)] after any subsequent method call on the same\n** object.  ^Applications may change the content of the string returned\n** by [sqlite3_str_value(X)] as long as they do not write into any bytes\n** outside the range of 0 to [sqlite3_str_length(X)] and do not read or\n** write any byte after any subsequent sqlite3_str method call.\n*/\nSQLITE_API int sqlite3_str_errcode(sqlite3_str*);\nSQLITE_API int sqlite3_str_length(sqlite3_str*);\nSQLITE_API char *sqlite3_str_value(sqlite3_str*);\n\n/*\n** CAPI3REF: SQLite Runtime Status\n**\n** ^These interfaces are used to retrieve runtime status information\n** about the performance of SQLite, and optionally to reset various\n** highwater marks.  ^The first argument is an integer code for\n** the specific parameter to measure.  ^(Recognized integer codes\n** are of the form [status parameters | SQLITE_STATUS_...].)^\n** ^The current value of the parameter is returned into *pCurrent.\n** ^The highest recorded value is returned in *pHighwater.  ^If the\n** resetFlag is true, then the highest record value is reset after\n** *pHighwater is written.  ^(Some parameters do not record the highest\n** value.  For those parameters\n** nothing is written into *pHighwater and the resetFlag is ignored.)^\n** ^(Other parameters record only the highwater mark and not the current\n** value.  For these latter parameters nothing is written into *pCurrent.)^\n**\n** ^The sqlite3_status() and sqlite3_status64() routines return\n** SQLITE_OK on success and a non-zero [error code] on failure.\n**\n** If either the current value or the highwater mark is too large to\n** be represented by a 32-bit integer, then the values returned by\n** sqlite3_status() are undefined.\n**\n** See also: [sqlite3_db_status()]\n*/\nSQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);\nSQLITE_API int sqlite3_status64(\n  int op,\n  sqlite3_int64 *pCurrent,\n  sqlite3_int64 *pHighwater,\n  int resetFlag\n);\n\n\n/*\n** CAPI3REF: Status Parameters\n** KEYWORDS: {status parameters}\n**\n** These integer constants designate various run-time status parameters\n** that can be returned by [sqlite3_status()].\n**\n** <dl>\n** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>\n** <dd>This parameter is the current amount of memory checked out\n** using [sqlite3_malloc()], either directly or indirectly.  The\n** figure includes calls made to [sqlite3_malloc()] by the application\n** and internal memory usage by the SQLite library.  Auxiliary page-cache\n** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in\n** this parameter.  The amount returned is the sum of the allocation\n** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^\n**\n** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>\n** <dd>This parameter records the largest memory allocation request\n** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their\n** internal equivalents).  Only the value returned in the\n** *pHighwater parameter to [sqlite3_status()] is of interest.  \n** The value written into the *pCurrent parameter is undefined.</dd>)^\n**\n** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>\n** <dd>This parameter records the number of separate memory allocations\n** currently checked out.</dd>)^\n**\n** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>\n** <dd>This parameter returns the number of pages used out of the\n** [pagecache memory allocator] that was configured using \n** [SQLITE_CONFIG_PAGECACHE].  The\n** value returned is in pages, not in bytes.</dd>)^\n**\n** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] \n** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>\n** <dd>This parameter returns the number of bytes of page cache\n** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]\n** buffer and where forced to overflow to [sqlite3_malloc()].  The\n** returned value includes allocations that overflowed because they\n** where too large (they were larger than the \"sz\" parameter to\n** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because\n** no space was left in the page cache.</dd>)^\n**\n** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>\n** <dd>This parameter records the largest memory allocation request\n** handed to the [pagecache memory allocator].  Only the value returned in the\n** *pHighwater parameter to [sqlite3_status()] is of interest.  \n** The value written into the *pCurrent parameter is undefined.</dd>)^\n**\n** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>\n** <dd>No longer used.</dd>\n**\n** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>\n** <dd>No longer used.</dd>\n**\n** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>\n** <dd>No longer used.</dd>\n**\n** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>\n** <dd>The *pHighwater parameter records the deepest parser stack. \n** The *pCurrent value is undefined.  The *pHighwater value is only\n** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^\n** </dl>\n**\n** New status parameters may be added from time to time.\n*/\n#define SQLITE_STATUS_MEMORY_USED          0\n#define SQLITE_STATUS_PAGECACHE_USED       1\n#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2\n#define SQLITE_STATUS_SCRATCH_USED         3  /* NOT USED */\n#define SQLITE_STATUS_SCRATCH_OVERFLOW     4  /* NOT USED */\n#define SQLITE_STATUS_MALLOC_SIZE          5\n#define SQLITE_STATUS_PARSER_STACK         6\n#define SQLITE_STATUS_PAGECACHE_SIZE       7\n#define SQLITE_STATUS_SCRATCH_SIZE         8  /* NOT USED */\n#define SQLITE_STATUS_MALLOC_COUNT         9\n\n/*\n** CAPI3REF: Database Connection Status\n** METHOD: sqlite3\n**\n** ^This interface is used to retrieve runtime status information \n** about a single [database connection].  ^The first argument is the\n** database connection object to be interrogated.  ^The second argument\n** is an integer constant, taken from the set of\n** [SQLITE_DBSTATUS options], that\n** determines the parameter to interrogate.  The set of \n** [SQLITE_DBSTATUS options] is likely\n** to grow in future releases of SQLite.\n**\n** ^The current value of the requested parameter is written into *pCur\n** and the highest instantaneous value is written into *pHiwtr.  ^If\n** the resetFlg is true, then the highest instantaneous value is\n** reset back down to the current value.\n**\n** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a\n** non-zero [error code] on failure.\n**\n** See also: [sqlite3_status()] and [sqlite3_stmt_status()].\n*/\nSQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);\n\n/*\n** CAPI3REF: Status Parameters for database connections\n** KEYWORDS: {SQLITE_DBSTATUS options}\n**\n** These constants are the available integer \"verbs\" that can be passed as\n** the second argument to the [sqlite3_db_status()] interface.\n**\n** New verbs may be added in future releases of SQLite. Existing verbs\n** might be discontinued. Applications should check the return code from\n** [sqlite3_db_status()] to make sure that the call worked.\n** The [sqlite3_db_status()] interface will return a non-zero error code\n** if a discontinued or unsupported verb is invoked.\n**\n** <dl>\n** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>\n** <dd>This parameter returns the number of lookaside memory slots currently\n** checked out.</dd>)^\n**\n** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>\n** <dd>This parameter returns the number of malloc attempts that were \n** satisfied using lookaside memory. Only the high-water value is meaningful;\n** the current value is always zero.)^\n**\n** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]\n** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>\n** <dd>This parameter returns the number malloc attempts that might have\n** been satisfied using lookaside memory but failed due to the amount of\n** memory requested being larger than the lookaside slot size.\n** Only the high-water value is meaningful;\n** the current value is always zero.)^\n**\n** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]\n** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>\n** <dd>This parameter returns the number malloc attempts that might have\n** been satisfied using lookaside memory but failed due to all lookaside\n** memory already being in use.\n** Only the high-water value is meaningful;\n** the current value is always zero.)^\n**\n** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>\n** <dd>This parameter returns the approximate number of bytes of heap\n** memory used by all pager caches associated with the database connection.)^\n** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.\n**\n** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]] \n** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>\n** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a\n** pager cache is shared between two or more connections the bytes of heap\n** memory used by that pager cache is divided evenly between the attached\n** connections.)^  In other words, if none of the pager caches associated\n** with the database connection are shared, this request returns the same\n** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are\n** shared, the value returned by this call will be smaller than that returned\n** by DBSTATUS_CACHE_USED. ^The highwater mark associated with\n** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.\n**\n** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>\n** <dd>This parameter returns the approximate number of bytes of heap\n** memory used to store the schema for all databases associated\n** with the connection - main, temp, and any [ATTACH]-ed databases.)^ \n** ^The full amount of memory used by the schemas is reported, even if the\n** schema memory is shared with other database connections due to\n** [shared cache mode] being enabled.\n** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.\n**\n** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>\n** <dd>This parameter returns the approximate number of bytes of heap\n** and lookaside memory used by all prepared statements associated with\n** the database connection.)^\n** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.\n** </dd>\n**\n** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>\n** <dd>This parameter returns the number of pager cache hits that have\n** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT \n** is always 0.\n** </dd>\n**\n** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>\n** <dd>This parameter returns the number of pager cache misses that have\n** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS \n** is always 0.\n** </dd>\n**\n** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>\n** <dd>This parameter returns the number of dirty cache entries that have\n** been written to disk. Specifically, the number of pages written to the\n** wal file in wal mode databases, or the number of pages written to the\n** database file in rollback mode databases. Any pages written as part of\n** transaction rollback or database recovery operations are not included.\n** If an IO or other error occurs while writing a page to disk, the effect\n** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The\n** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.\n** </dd>\n**\n** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>\n** <dd>This parameter returns the number of dirty cache entries that have\n** been written to disk in the middle of a transaction due to the page\n** cache overflowing. Transactions are more efficient if they are written\n** to disk all at once. When pages spill mid-transaction, that introduces\n** additional overhead. This parameter can be used help identify\n** inefficiencies that can be resolved by increasing the cache size.\n** </dd>\n**\n** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>\n** <dd>This parameter returns zero for the current value if and only if\n** all foreign key constraints (deferred or immediate) have been\n** resolved.)^  ^The highwater mark is always 0.\n** </dd>\n** </dl>\n*/\n#define SQLITE_DBSTATUS_LOOKASIDE_USED       0\n#define SQLITE_DBSTATUS_CACHE_USED           1\n#define SQLITE_DBSTATUS_SCHEMA_USED          2\n#define SQLITE_DBSTATUS_STMT_USED            3\n#define SQLITE_DBSTATUS_LOOKASIDE_HIT        4\n#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5\n#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6\n#define SQLITE_DBSTATUS_CACHE_HIT            7\n#define SQLITE_DBSTATUS_CACHE_MISS           8\n#define SQLITE_DBSTATUS_CACHE_WRITE          9\n#define SQLITE_DBSTATUS_DEFERRED_FKS        10\n#define SQLITE_DBSTATUS_CACHE_USED_SHARED   11\n#define SQLITE_DBSTATUS_CACHE_SPILL         12\n#define SQLITE_DBSTATUS_MAX                 12   /* Largest defined DBSTATUS */\n\n\n/*\n** CAPI3REF: Prepared Statement Status\n** METHOD: sqlite3_stmt\n**\n** ^(Each prepared statement maintains various\n** [SQLITE_STMTSTATUS counters] that measure the number\n** of times it has performed specific operations.)^  These counters can\n** be used to monitor the performance characteristics of the prepared\n** statements.  For example, if the number of table steps greatly exceeds\n** the number of table searches or result rows, that would tend to indicate\n** that the prepared statement is using a full table scan rather than\n** an index.  \n**\n** ^(This interface is used to retrieve and reset counter values from\n** a [prepared statement].  The first argument is the prepared statement\n** object to be interrogated.  The second argument\n** is an integer code for a specific [SQLITE_STMTSTATUS counter]\n** to be interrogated.)^\n** ^The current value of the requested counter is returned.\n** ^If the resetFlg is true, then the counter is reset to zero after this\n** interface call returns.\n**\n** See also: [sqlite3_status()] and [sqlite3_db_status()].\n*/\nSQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);\n\n/*\n** CAPI3REF: Status Parameters for prepared statements\n** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}\n**\n** These preprocessor macros define integer codes that name counter\n** values associated with the [sqlite3_stmt_status()] interface.\n** The meanings of the various counters are as follows:\n**\n** <dl>\n** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>\n** <dd>^This is the number of times that SQLite has stepped forward in\n** a table as part of a full table scan.  Large numbers for this counter\n** may indicate opportunities for performance improvement through \n** careful use of indices.</dd>\n**\n** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>\n** <dd>^This is the number of sort operations that have occurred.\n** A non-zero value in this counter may indicate an opportunity to\n** improvement performance through careful use of indices.</dd>\n**\n** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>\n** <dd>^This is the number of rows inserted into transient indices that\n** were created automatically in order to help joins run faster.\n** A non-zero value in this counter may indicate an opportunity to\n** improvement performance by adding permanent indices that do not\n** need to be reinitialized each time the statement is run.</dd>\n**\n** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>\n** <dd>^This is the number of virtual machine operations executed\n** by the prepared statement if that number is less than or equal\n** to 2147483647.  The number of virtual machine operations can be \n** used as a proxy for the total work done by the prepared statement.\n** If the number of virtual machine operations exceeds 2147483647\n** then the value returned by this statement status code is undefined.\n**\n** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>\n** <dd>^This is the number of times that the prepare statement has been\n** automatically regenerated due to schema changes or changes to \n** [bound parameters] that might affect the query plan.\n**\n** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>\n** <dd>^This is the number of times that the prepared statement has\n** been run.  A single \"run\" for the purposes of this counter is one\n** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].\n** The counter is incremented on the first [sqlite3_step()] call of each\n** cycle.\n**\n** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>\n** <dd>^This is the approximate number of bytes of heap memory\n** used to store the prepared statement.  ^This value is not actually\n** a counter, and so the resetFlg parameter to sqlite3_stmt_status()\n** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.\n** </dd>\n** </dl>\n*/\n#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1\n#define SQLITE_STMTSTATUS_SORT              2\n#define SQLITE_STMTSTATUS_AUTOINDEX         3\n#define SQLITE_STMTSTATUS_VM_STEP           4\n#define SQLITE_STMTSTATUS_REPREPARE         5\n#define SQLITE_STMTSTATUS_RUN               6\n#define SQLITE_STMTSTATUS_MEMUSED           99\n\n/*\n** CAPI3REF: Custom Page Cache Object\n**\n** The sqlite3_pcache type is opaque.  It is implemented by\n** the pluggable module.  The SQLite core has no knowledge of\n** its size or internal structure and never deals with the\n** sqlite3_pcache object except by holding and passing pointers\n** to the object.\n**\n** See [sqlite3_pcache_methods2] for additional information.\n*/\ntypedef struct sqlite3_pcache sqlite3_pcache;\n\n/*\n** CAPI3REF: Custom Page Cache Object\n**\n** The sqlite3_pcache_page object represents a single page in the\n** page cache.  The page cache will allocate instances of this\n** object.  Various methods of the page cache use pointers to instances\n** of this object as parameters or as their return value.\n**\n** See [sqlite3_pcache_methods2] for additional information.\n*/\ntypedef struct sqlite3_pcache_page sqlite3_pcache_page;\nstruct sqlite3_pcache_page {\n  void *pBuf;        /* The content of the page */\n  void *pExtra;      /* Extra information associated with the page */\n};\n\n/*\n** CAPI3REF: Application Defined Page Cache.\n** KEYWORDS: {page cache}\n**\n** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can\n** register an alternative page cache implementation by passing in an \n** instance of the sqlite3_pcache_methods2 structure.)^\n** In many applications, most of the heap memory allocated by \n** SQLite is used for the page cache.\n** By implementing a \n** custom page cache using this API, an application can better control\n** the amount of memory consumed by SQLite, the way in which \n** that memory is allocated and released, and the policies used to \n** determine exactly which parts of a database file are cached and for \n** how long.\n**\n** The alternative page cache mechanism is an\n** extreme measure that is only needed by the most demanding applications.\n** The built-in page cache is recommended for most uses.\n**\n** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an\n** internal buffer by SQLite within the call to [sqlite3_config].  Hence\n** the application may discard the parameter after the call to\n** [sqlite3_config()] returns.)^\n**\n** [[the xInit() page cache method]]\n** ^(The xInit() method is called once for each effective \n** call to [sqlite3_initialize()])^\n** (usually only once during the lifetime of the process). ^(The xInit()\n** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^\n** The intent of the xInit() method is to set up global data structures \n** required by the custom page cache implementation. \n** ^(If the xInit() method is NULL, then the \n** built-in default page cache is used instead of the application defined\n** page cache.)^\n**\n** [[the xShutdown() page cache method]]\n** ^The xShutdown() method is called by [sqlite3_shutdown()].\n** It can be used to clean up \n** any outstanding resources before process shutdown, if required.\n** ^The xShutdown() method may be NULL.\n**\n** ^SQLite automatically serializes calls to the xInit method,\n** so the xInit method need not be threadsafe.  ^The\n** xShutdown method is only called from [sqlite3_shutdown()] so it does\n** not need to be threadsafe either.  All other methods must be threadsafe\n** in multithreaded applications.\n**\n** ^SQLite will never invoke xInit() more than once without an intervening\n** call to xShutdown().\n**\n** [[the xCreate() page cache methods]]\n** ^SQLite invokes the xCreate() method to construct a new cache instance.\n** SQLite will typically create one cache instance for each open database file,\n** though this is not guaranteed. ^The\n** first parameter, szPage, is the size in bytes of the pages that must\n** be allocated by the cache.  ^szPage will always a power of two.  ^The\n** second parameter szExtra is a number of bytes of extra storage \n** associated with each page cache entry.  ^The szExtra parameter will\n** a number less than 250.  SQLite will use the\n** extra szExtra bytes on each page to store metadata about the underlying\n** database page on disk.  The value passed into szExtra depends\n** on the SQLite version, the target platform, and how SQLite was compiled.\n** ^The third argument to xCreate(), bPurgeable, is true if the cache being\n** created will be used to cache database pages of a file stored on disk, or\n** false if it is used for an in-memory database. The cache implementation\n** does not have to do anything special based with the value of bPurgeable;\n** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will\n** never invoke xUnpin() except to deliberately delete a page.\n** ^In other words, calls to xUnpin() on a cache with bPurgeable set to\n** false will always have the \"discard\" flag set to true.  \n** ^Hence, a cache created with bPurgeable false will\n** never contain any unpinned pages.\n**\n** [[the xCachesize() page cache method]]\n** ^(The xCachesize() method may be called at any time by SQLite to set the\n** suggested maximum cache-size (number of pages stored by) the cache\n** instance passed as the first argument. This is the value configured using\n** the SQLite \"[PRAGMA cache_size]\" command.)^  As with the bPurgeable\n** parameter, the implementation is not required to do anything with this\n** value; it is advisory only.\n**\n** [[the xPagecount() page cache methods]]\n** The xPagecount() method must return the number of pages currently\n** stored in the cache, both pinned and unpinned.\n** \n** [[the xFetch() page cache methods]]\n** The xFetch() method locates a page in the cache and returns a pointer to \n** an sqlite3_pcache_page object associated with that page, or a NULL pointer.\n** The pBuf element of the returned sqlite3_pcache_page object will be a\n** pointer to a buffer of szPage bytes used to store the content of a \n** single database page.  The pExtra element of sqlite3_pcache_page will be\n** a pointer to the szExtra bytes of extra storage that SQLite has requested\n** for each entry in the page cache.\n**\n** The page to be fetched is determined by the key. ^The minimum key value\n** is 1.  After it has been retrieved using xFetch, the page is considered\n** to be \"pinned\".\n**\n** If the requested page is already in the page cache, then the page cache\n** implementation must return a pointer to the page buffer with its content\n** intact.  If the requested page is not already in the cache, then the\n** cache implementation should use the value of the createFlag\n** parameter to help it determined what action to take:\n**\n** <table border=1 width=85% align=center>\n** <tr><th> createFlag <th> Behavior when page is not already in cache\n** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.\n** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.\n**                 Otherwise return NULL.\n** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return\n**                 NULL if allocating a new page is effectively impossible.\n** </table>\n**\n** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite\n** will only use a createFlag of 2 after a prior call with a createFlag of 1\n** failed.)^  In between the xFetch() calls, SQLite may\n** attempt to unpin one or more cache pages by spilling the content of\n** pinned pages to disk and synching the operating system disk cache.\n**\n** [[the xUnpin() page cache method]]\n** ^xUnpin() is called by SQLite with a pointer to a currently pinned page\n** as its second argument.  If the third parameter, discard, is non-zero,\n** then the page must be evicted from the cache.\n** ^If the discard parameter is\n** zero, then the page may be discarded or retained at the discretion of\n** page cache implementation. ^The page cache implementation\n** may choose to evict unpinned pages at any time.\n**\n** The cache must not perform any reference counting. A single \n** call to xUnpin() unpins the page regardless of the number of prior calls \n** to xFetch().\n**\n** [[the xRekey() page cache methods]]\n** The xRekey() method is used to change the key value associated with the\n** page passed as the second argument. If the cache\n** previously contains an entry associated with newKey, it must be\n** discarded. ^Any prior cache entry associated with newKey is guaranteed not\n** to be pinned.\n**\n** When SQLite calls the xTruncate() method, the cache must discard all\n** existing cache entries with page numbers (keys) greater than or equal\n** to the value of the iLimit parameter passed to xTruncate(). If any\n** of these pages are pinned, they are implicitly unpinned, meaning that\n** they can be safely discarded.\n**\n** [[the xDestroy() page cache method]]\n** ^The xDestroy() method is used to delete a cache allocated by xCreate().\n** All resources associated with the specified cache should be freed. ^After\n** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]\n** handle invalid, and will not use it with any other sqlite3_pcache_methods2\n** functions.\n**\n** [[the xShrink() page cache method]]\n** ^SQLite invokes the xShrink() method when it wants the page cache to\n** free up as much of heap memory as possible.  The page cache implementation\n** is not obligated to free any memory, but well-behaved implementations should\n** do their best.\n*/\ntypedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;\nstruct sqlite3_pcache_methods2 {\n  int iVersion;\n  void *pArg;\n  int (*xInit)(void*);\n  void (*xShutdown)(void*);\n  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);\n  void (*xCachesize)(sqlite3_pcache*, int nCachesize);\n  int (*xPagecount)(sqlite3_pcache*);\n  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);\n  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);\n  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, \n      unsigned oldKey, unsigned newKey);\n  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);\n  void (*xDestroy)(sqlite3_pcache*);\n  void (*xShrink)(sqlite3_pcache*);\n};\n\n/*\n** This is the obsolete pcache_methods object that has now been replaced\n** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is\n** retained in the header file for backwards compatibility only.\n*/\ntypedef struct sqlite3_pcache_methods sqlite3_pcache_methods;\nstruct sqlite3_pcache_methods {\n  void *pArg;\n  int (*xInit)(void*);\n  void (*xShutdown)(void*);\n  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);\n  void (*xCachesize)(sqlite3_pcache*, int nCachesize);\n  int (*xPagecount)(sqlite3_pcache*);\n  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);\n  void (*xUnpin)(sqlite3_pcache*, void*, int discard);\n  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);\n  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);\n  void (*xDestroy)(sqlite3_pcache*);\n};\n\n\n/*\n** CAPI3REF: Online Backup Object\n**\n** The sqlite3_backup object records state information about an ongoing\n** online backup operation.  ^The sqlite3_backup object is created by\n** a call to [sqlite3_backup_init()] and is destroyed by a call to\n** [sqlite3_backup_finish()].\n**\n** See Also: [Using the SQLite Online Backup API]\n*/\ntypedef struct sqlite3_backup sqlite3_backup;\n\n/*\n** CAPI3REF: Online Backup API.\n**\n** The backup API copies the content of one database into another.\n** It is useful either for creating backups of databases or\n** for copying in-memory databases to or from persistent files. \n**\n** See Also: [Using the SQLite Online Backup API]\n**\n** ^SQLite holds a write transaction open on the destination database file\n** for the duration of the backup operation.\n** ^The source database is read-locked only while it is being read;\n** it is not locked continuously for the entire backup operation.\n** ^Thus, the backup may be performed on a live source database without\n** preventing other database connections from\n** reading or writing to the source database while the backup is underway.\n** \n** ^(To perform a backup operation: \n**   <ol>\n**     <li><b>sqlite3_backup_init()</b> is called once to initialize the\n**         backup, \n**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer \n**         the data between the two databases, and finally\n**     <li><b>sqlite3_backup_finish()</b> is called to release all resources \n**         associated with the backup operation. \n**   </ol>)^\n** There should be exactly one call to sqlite3_backup_finish() for each\n** successful call to sqlite3_backup_init().\n**\n** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>\n**\n** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the \n** [database connection] associated with the destination database \n** and the database name, respectively.\n** ^The database name is \"main\" for the main database, \"temp\" for the\n** temporary database, or the name specified after the AS keyword in\n** an [ATTACH] statement for an attached database.\n** ^The S and M arguments passed to \n** sqlite3_backup_init(D,N,S,M) identify the [database connection]\n** and database name of the source database, respectively.\n** ^The source and destination [database connections] (parameters S and D)\n** must be different or else sqlite3_backup_init(D,N,S,M) will fail with\n** an error.\n**\n** ^A call to sqlite3_backup_init() will fail, returning NULL, if \n** there is already a read or read-write transaction open on the \n** destination database.\n**\n** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is\n** returned and an error code and error message are stored in the\n** destination [database connection] D.\n** ^The error code and message for the failed call to sqlite3_backup_init()\n** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or\n** [sqlite3_errmsg16()] functions.\n** ^A successful call to sqlite3_backup_init() returns a pointer to an\n** [sqlite3_backup] object.\n** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and\n** sqlite3_backup_finish() functions to perform the specified backup \n** operation.\n**\n** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>\n**\n** ^Function sqlite3_backup_step(B,N) will copy up to N pages between \n** the source and destination databases specified by [sqlite3_backup] object B.\n** ^If N is negative, all remaining source pages are copied. \n** ^If sqlite3_backup_step(B,N) successfully copies N pages and there\n** are still more pages to be copied, then the function returns [SQLITE_OK].\n** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages\n** from source to destination, then it returns [SQLITE_DONE].\n** ^If an error occurs while running sqlite3_backup_step(B,N),\n** then an [error code] is returned. ^As well as [SQLITE_OK] and\n** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],\n** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an\n** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.\n**\n** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if\n** <ol>\n** <li> the destination database was opened read-only, or\n** <li> the destination database is using write-ahead-log journaling\n** and the destination and source page sizes differ, or\n** <li> the destination database is an in-memory database and the\n** destination and source page sizes differ.\n** </ol>)^\n**\n** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then\n** the [sqlite3_busy_handler | busy-handler function]\n** is invoked (if one is specified). ^If the \n** busy-handler returns non-zero before the lock is available, then \n** [SQLITE_BUSY] is returned to the caller. ^In this case the call to\n** sqlite3_backup_step() can be retried later. ^If the source\n** [database connection]\n** is being used to write to the source database when sqlite3_backup_step()\n** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this\n** case the call to sqlite3_backup_step() can be retried later on. ^(If\n** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or\n** [SQLITE_READONLY] is returned, then \n** there is no point in retrying the call to sqlite3_backup_step(). These \n** errors are considered fatal.)^  The application must accept \n** that the backup operation has failed and pass the backup operation handle \n** to the sqlite3_backup_finish() to release associated resources.\n**\n** ^The first call to sqlite3_backup_step() obtains an exclusive lock\n** on the destination file. ^The exclusive lock is not released until either \n** sqlite3_backup_finish() is called or the backup operation is complete \n** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to\n** sqlite3_backup_step() obtains a [shared lock] on the source database that\n** lasts for the duration of the sqlite3_backup_step() call.\n** ^Because the source database is not locked between calls to\n** sqlite3_backup_step(), the source database may be modified mid-way\n** through the backup process.  ^If the source database is modified by an\n** external process or via a database connection other than the one being\n** used by the backup operation, then the backup will be automatically\n** restarted by the next call to sqlite3_backup_step(). ^If the source \n** database is modified by the using the same database connection as is used\n** by the backup operation, then the backup database is automatically\n** updated at the same time.\n**\n** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>\n**\n** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the \n** application wishes to abandon the backup operation, the application\n** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().\n** ^The sqlite3_backup_finish() interfaces releases all\n** resources associated with the [sqlite3_backup] object. \n** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any\n** active write-transaction on the destination database is rolled back.\n** The [sqlite3_backup] object is invalid\n** and may not be used following a call to sqlite3_backup_finish().\n**\n** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no\n** sqlite3_backup_step() errors occurred, regardless or whether or not\n** sqlite3_backup_step() completed.\n** ^If an out-of-memory condition or IO error occurred during any prior\n** sqlite3_backup_step() call on the same [sqlite3_backup] object, then\n** sqlite3_backup_finish() returns the corresponding [error code].\n**\n** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()\n** is not a permanent error and does not affect the return value of\n** sqlite3_backup_finish().\n**\n** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]\n** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>\n**\n** ^The sqlite3_backup_remaining() routine returns the number of pages still\n** to be backed up at the conclusion of the most recent sqlite3_backup_step().\n** ^The sqlite3_backup_pagecount() routine returns the total number of pages\n** in the source database at the conclusion of the most recent\n** sqlite3_backup_step().\n** ^(The values returned by these functions are only updated by\n** sqlite3_backup_step(). If the source database is modified in a way that\n** changes the size of the source database or the number of pages remaining,\n** those changes are not reflected in the output of sqlite3_backup_pagecount()\n** and sqlite3_backup_remaining() until after the next\n** sqlite3_backup_step().)^\n**\n** <b>Concurrent Usage of Database Handles</b>\n**\n** ^The source [database connection] may be used by the application for other\n** purposes while a backup operation is underway or being initialized.\n** ^If SQLite is compiled and configured to support threadsafe database\n** connections, then the source database connection may be used concurrently\n** from within other threads.\n**\n** However, the application must guarantee that the destination \n** [database connection] is not passed to any other API (by any thread) after \n** sqlite3_backup_init() is called and before the corresponding call to\n** sqlite3_backup_finish().  SQLite does not currently check to see\n** if the application incorrectly accesses the destination [database connection]\n** and so no error code is reported, but the operations may malfunction\n** nevertheless.  Use of the destination database connection while a\n** backup is in progress might also also cause a mutex deadlock.\n**\n** If running in [shared cache mode], the application must\n** guarantee that the shared cache used by the destination database\n** is not accessed while the backup is running. In practice this means\n** that the application must guarantee that the disk file being \n** backed up to is not accessed by any connection within the process,\n** not just the specific connection that was passed to sqlite3_backup_init().\n**\n** The [sqlite3_backup] object itself is partially threadsafe. Multiple \n** threads may safely make multiple concurrent calls to sqlite3_backup_step().\n** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()\n** APIs are not strictly speaking threadsafe. If they are invoked at the\n** same time as another thread is invoking sqlite3_backup_step() it is\n** possible that they return invalid values.\n*/\nSQLITE_API sqlite3_backup *sqlite3_backup_init(\n  sqlite3 *pDest,                        /* Destination database handle */\n  const char *zDestName,                 /* Destination database name */\n  sqlite3 *pSource,                      /* Source database handle */\n  const char *zSourceName                /* Source database name */\n);\nSQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);\nSQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);\nSQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);\nSQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);\n\n/*\n** CAPI3REF: Unlock Notification\n** METHOD: sqlite3\n**\n** ^When running in shared-cache mode, a database operation may fail with\n** an [SQLITE_LOCKED] error if the required locks on the shared-cache or\n** individual tables within the shared-cache cannot be obtained. See\n** [SQLite Shared-Cache Mode] for a description of shared-cache locking. \n** ^This API may be used to register a callback that SQLite will invoke \n** when the connection currently holding the required lock relinquishes it.\n** ^This API is only available if the library was compiled with the\n** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.\n**\n** See Also: [Using the SQLite Unlock Notification Feature].\n**\n** ^Shared-cache locks are released when a database connection concludes\n** its current transaction, either by committing it or rolling it back. \n**\n** ^When a connection (known as the blocked connection) fails to obtain a\n** shared-cache lock and SQLITE_LOCKED is returned to the caller, the\n** identity of the database connection (the blocking connection) that\n** has locked the required resource is stored internally. ^After an \n** application receives an SQLITE_LOCKED error, it may call the\n** sqlite3_unlock_notify() method with the blocked connection handle as \n** the first argument to register for a callback that will be invoked\n** when the blocking connections current transaction is concluded. ^The\n** callback is invoked from within the [sqlite3_step] or [sqlite3_close]\n** call that concludes the blocking connection's transaction.\n**\n** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,\n** there is a chance that the blocking connection will have already\n** concluded its transaction by the time sqlite3_unlock_notify() is invoked.\n** If this happens, then the specified callback is invoked immediately,\n** from within the call to sqlite3_unlock_notify().)^\n**\n** ^If the blocked connection is attempting to obtain a write-lock on a\n** shared-cache table, and more than one other connection currently holds\n** a read-lock on the same table, then SQLite arbitrarily selects one of \n** the other connections to use as the blocking connection.\n**\n** ^(There may be at most one unlock-notify callback registered by a \n** blocked connection. If sqlite3_unlock_notify() is called when the\n** blocked connection already has a registered unlock-notify callback,\n** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is\n** called with a NULL pointer as its second argument, then any existing\n** unlock-notify callback is canceled. ^The blocked connections \n** unlock-notify callback may also be canceled by closing the blocked\n** connection using [sqlite3_close()].\n**\n** The unlock-notify callback is not reentrant. If an application invokes\n** any sqlite3_xxx API functions from within an unlock-notify callback, a\n** crash or deadlock may be the result.\n**\n** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always\n** returns SQLITE_OK.\n**\n** <b>Callback Invocation Details</b>\n**\n** When an unlock-notify callback is registered, the application provides a \n** single void* pointer that is passed to the callback when it is invoked.\n** However, the signature of the callback function allows SQLite to pass\n** it an array of void* context pointers. The first argument passed to\n** an unlock-notify callback is a pointer to an array of void* pointers,\n** and the second is the number of entries in the array.\n**\n** When a blocking connection's transaction is concluded, there may be\n** more than one blocked connection that has registered for an unlock-notify\n** callback. ^If two or more such blocked connections have specified the\n** same callback function, then instead of invoking the callback function\n** multiple times, it is invoked once with the set of void* context pointers\n** specified by the blocked connections bundled together into an array.\n** This gives the application an opportunity to prioritize any actions \n** related to the set of unblocked database connections.\n**\n** <b>Deadlock Detection</b>\n**\n** Assuming that after registering for an unlock-notify callback a \n** database waits for the callback to be issued before taking any further\n** action (a reasonable assumption), then using this API may cause the\n** application to deadlock. For example, if connection X is waiting for\n** connection Y's transaction to be concluded, and similarly connection\n** Y is waiting on connection X's transaction, then neither connection\n** will proceed and the system may remain deadlocked indefinitely.\n**\n** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock\n** detection. ^If a given call to sqlite3_unlock_notify() would put the\n** system in a deadlocked state, then SQLITE_LOCKED is returned and no\n** unlock-notify callback is registered. The system is said to be in\n** a deadlocked state if connection A has registered for an unlock-notify\n** callback on the conclusion of connection B's transaction, and connection\n** B has itself registered for an unlock-notify callback when connection\n** A's transaction is concluded. ^Indirect deadlock is also detected, so\n** the system is also considered to be deadlocked if connection B has\n** registered for an unlock-notify callback on the conclusion of connection\n** C's transaction, where connection C is waiting on connection A. ^Any\n** number of levels of indirection are allowed.\n**\n** <b>The \"DROP TABLE\" Exception</b>\n**\n** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost \n** always appropriate to call sqlite3_unlock_notify(). There is however,\n** one exception. When executing a \"DROP TABLE\" or \"DROP INDEX\" statement,\n** SQLite checks if there are any currently executing SELECT statements\n** that belong to the same connection. If there are, SQLITE_LOCKED is\n** returned. In this case there is no \"blocking connection\", so invoking\n** sqlite3_unlock_notify() results in the unlock-notify callback being\n** invoked immediately. If the application then re-attempts the \"DROP TABLE\"\n** or \"DROP INDEX\" query, an infinite loop might be the result.\n**\n** One way around this problem is to check the extended error code returned\n** by an sqlite3_step() call. ^(If there is a blocking connection, then the\n** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in\n** the special \"DROP TABLE/INDEX\" case, the extended error code is just \n** SQLITE_LOCKED.)^\n*/\nSQLITE_API int sqlite3_unlock_notify(\n  sqlite3 *pBlocked,                          /* Waiting connection */\n  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */\n  void *pNotifyArg                            /* Argument to pass to xNotify */\n);\n\n\n/*\n** CAPI3REF: String Comparison\n**\n** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications\n** and extensions to compare the contents of two buffers containing UTF-8\n** strings in a case-independent fashion, using the same definition of \"case\n** independence\" that SQLite uses internally when comparing identifiers.\n*/\nSQLITE_API int sqlite3_stricmp(const char *, const char *);\nSQLITE_API int sqlite3_strnicmp(const char *, const char *, int);\n\n/*\n** CAPI3REF: String Globbing\n*\n** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if\n** string X matches the [GLOB] pattern P.\n** ^The definition of [GLOB] pattern matching used in\n** [sqlite3_strglob(P,X)] is the same as for the \"X GLOB P\" operator in the\n** SQL dialect understood by SQLite.  ^The [sqlite3_strglob(P,X)] function\n** is case sensitive.\n**\n** Note that this routine returns zero on a match and non-zero if the strings\n** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].\n**\n** See also: [sqlite3_strlike()].\n*/\nSQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);\n\n/*\n** CAPI3REF: String LIKE Matching\n*\n** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if\n** string X matches the [LIKE] pattern P with escape character E.\n** ^The definition of [LIKE] pattern matching used in\n** [sqlite3_strlike(P,X,E)] is the same as for the \"X LIKE P ESCAPE E\"\n** operator in the SQL dialect understood by SQLite.  ^For \"X LIKE P\" without\n** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.\n** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case\n** insensitive - equivalent upper and lower case ASCII characters match\n** one another.\n**\n** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though\n** only ASCII characters are case folded.\n**\n** Note that this routine returns zero on a match and non-zero if the strings\n** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].\n**\n** See also: [sqlite3_strglob()].\n*/\nSQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);\n\n/*\n** CAPI3REF: Error Logging Interface\n**\n** ^The [sqlite3_log()] interface writes a message into the [error log]\n** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].\n** ^If logging is enabled, the zFormat string and subsequent arguments are\n** used with [sqlite3_snprintf()] to generate the final output string.\n**\n** The sqlite3_log() interface is intended for use by extensions such as\n** virtual tables, collating functions, and SQL functions.  While there is\n** nothing to prevent an application from calling sqlite3_log(), doing so\n** is considered bad form.\n**\n** The zFormat string must not be NULL.\n**\n** To avoid deadlocks and other threading problems, the sqlite3_log() routine\n** will not use dynamically allocated memory.  The log message is stored in\n** a fixed-length buffer on the stack.  If the log message is longer than\n** a few hundred characters, it will be truncated to the length of the\n** buffer.\n*/\nSQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);\n\n/*\n** CAPI3REF: Write-Ahead Log Commit Hook\n** METHOD: sqlite3\n**\n** ^The [sqlite3_wal_hook()] function is used to register a callback that\n** is invoked each time data is committed to a database in wal mode.\n**\n** ^(The callback is invoked by SQLite after the commit has taken place and \n** the associated write-lock on the database released)^, so the implementation \n** may read, write or [checkpoint] the database as required.\n**\n** ^The first parameter passed to the callback function when it is invoked\n** is a copy of the third parameter passed to sqlite3_wal_hook() when\n** registering the callback. ^The second is a copy of the database handle.\n** ^The third parameter is the name of the database that was written to -\n** either \"main\" or the name of an [ATTACH]-ed database. ^The fourth parameter\n** is the number of pages currently in the write-ahead log file,\n** including those that were just committed.\n**\n** The callback function should normally return [SQLITE_OK].  ^If an error\n** code is returned, that error will propagate back up through the\n** SQLite code base to cause the statement that provoked the callback\n** to report an error, though the commit will have still occurred. If the\n** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value\n** that does not correspond to any valid SQLite error code, the results\n** are undefined.\n**\n** A single database handle may have at most a single write-ahead log callback \n** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any\n** previously registered write-ahead log callback. ^Note that the\n** [sqlite3_wal_autocheckpoint()] interface and the\n** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will\n** overwrite any prior [sqlite3_wal_hook()] settings.\n*/\nSQLITE_API void *sqlite3_wal_hook(\n  sqlite3*, \n  int(*)(void *,sqlite3*,const char*,int),\n  void*\n);\n\n/*\n** CAPI3REF: Configure an auto-checkpoint\n** METHOD: sqlite3\n**\n** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around\n** [sqlite3_wal_hook()] that causes any database on [database connection] D\n** to automatically [checkpoint]\n** after committing a transaction if there are N or\n** more frames in the [write-ahead log] file.  ^Passing zero or \n** a negative value as the nFrame parameter disables automatic\n** checkpoints entirely.\n**\n** ^The callback registered by this function replaces any existing callback\n** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback\n** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism\n** configured by this function.\n**\n** ^The [wal_autocheckpoint pragma] can be used to invoke this interface\n** from SQL.\n**\n** ^Checkpoints initiated by this mechanism are\n** [sqlite3_wal_checkpoint_v2|PASSIVE].\n**\n** ^Every new [database connection] defaults to having the auto-checkpoint\n** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]\n** pages.  The use of this interface\n** is only necessary if the default setting is found to be suboptimal\n** for a particular application.\n*/\nSQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);\n\n/*\n** CAPI3REF: Checkpoint a database\n** METHOD: sqlite3\n**\n** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to\n** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^\n**\n** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the \n** [write-ahead log] for database X on [database connection] D to be\n** transferred into the database file and for the write-ahead log to\n** be reset.  See the [checkpointing] documentation for addition\n** information.\n**\n** This interface used to be the only way to cause a checkpoint to\n** occur.  But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]\n** interface was added.  This interface is retained for backwards\n** compatibility and as a convenience for applications that need to manually\n** start a callback but which do not need the full power (and corresponding\n** complication) of [sqlite3_wal_checkpoint_v2()].\n*/\nSQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);\n\n/*\n** CAPI3REF: Checkpoint a database\n** METHOD: sqlite3\n**\n** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint\n** operation on database X of [database connection] D in mode M.  Status\n** information is written back into integers pointed to by L and C.)^\n** ^(The M parameter must be a valid [checkpoint mode]:)^\n**\n** <dl>\n** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>\n**   ^Checkpoint as many frames as possible without waiting for any database \n**   readers or writers to finish, then sync the database file if all frames \n**   in the log were checkpointed. ^The [busy-handler callback]\n**   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.  \n**   ^On the other hand, passive mode might leave the checkpoint unfinished\n**   if there are concurrent readers or writers.\n**\n** <dt>SQLITE_CHECKPOINT_FULL<dd>\n**   ^This mode blocks (it invokes the\n**   [sqlite3_busy_handler|busy-handler callback]) until there is no\n**   database writer and all readers are reading from the most recent database\n**   snapshot. ^It then checkpoints all frames in the log file and syncs the\n**   database file. ^This mode blocks new database writers while it is pending,\n**   but new database readers are allowed to continue unimpeded.\n**\n** <dt>SQLITE_CHECKPOINT_RESTART<dd>\n**   ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition\n**   that after checkpointing the log file it blocks (calls the \n**   [busy-handler callback])\n**   until all readers are reading from the database file only. ^This ensures \n**   that the next writer will restart the log file from the beginning.\n**   ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new\n**   database writer attempts while it is pending, but does not impede readers.\n**\n** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>\n**   ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the\n**   addition that it also truncates the log file to zero bytes just prior\n**   to a successful return.\n** </dl>\n**\n** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in\n** the log file or to -1 if the checkpoint could not run because\n** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not\n** NULL,then *pnCkpt is set to the total number of checkpointed frames in the\n** log file (including any that were already checkpointed before the function\n** was called) or to -1 if the checkpoint could not run due to an error or\n** because the database is not in WAL mode. ^Note that upon successful\n** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been\n** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.\n**\n** ^All calls obtain an exclusive \"checkpoint\" lock on the database file. ^If\n** any other process is running a checkpoint operation at the same time, the \n** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a \n** busy-handler configured, it will not be invoked in this case.\n**\n** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the \n** exclusive \"writer\" lock on the database file. ^If the writer lock cannot be\n** obtained immediately, and a busy-handler is configured, it is invoked and\n** the writer lock retried until either the busy-handler returns 0 or the lock\n** is successfully obtained. ^The busy-handler is also invoked while waiting for\n** database readers as described above. ^If the busy-handler returns 0 before\n** the writer lock is obtained or while waiting for database readers, the\n** checkpoint operation proceeds from that point in the same way as \n** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible \n** without blocking any further. ^SQLITE_BUSY is returned in this case.\n**\n** ^If parameter zDb is NULL or points to a zero length string, then the\n** specified operation is attempted on all WAL databases [attached] to \n** [database connection] db.  In this case the\n** values written to output parameters *pnLog and *pnCkpt are undefined. ^If \n** an SQLITE_BUSY error is encountered when processing one or more of the \n** attached WAL databases, the operation is still attempted on any remaining \n** attached databases and SQLITE_BUSY is returned at the end. ^If any other \n** error occurs while processing an attached database, processing is abandoned \n** and the error code is returned to the caller immediately. ^If no error \n** (SQLITE_BUSY or otherwise) is encountered while processing the attached \n** databases, SQLITE_OK is returned.\n**\n** ^If database zDb is the name of an attached database that is not in WAL\n** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If\n** zDb is not NULL (or a zero length string) and is not the name of any\n** attached database, SQLITE_ERROR is returned to the caller.\n**\n** ^Unless it returns SQLITE_MISUSE,\n** the sqlite3_wal_checkpoint_v2() interface\n** sets the error information that is queried by\n** [sqlite3_errcode()] and [sqlite3_errmsg()].\n**\n** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface\n** from SQL.\n*/\nSQLITE_API int sqlite3_wal_checkpoint_v2(\n  sqlite3 *db,                    /* Database handle */\n  const char *zDb,                /* Name of attached database (or NULL) */\n  int eMode,                      /* SQLITE_CHECKPOINT_* value */\n  int *pnLog,                     /* OUT: Size of WAL log in frames */\n  int *pnCkpt                     /* OUT: Total number of frames checkpointed */\n);\n\n/*\n** CAPI3REF: Checkpoint Mode Values\n** KEYWORDS: {checkpoint mode}\n**\n** These constants define all valid values for the \"checkpoint mode\" passed\n** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.\n** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the\n** meaning of each of these checkpoint modes.\n*/\n#define SQLITE_CHECKPOINT_PASSIVE  0  /* Do as much as possible w/o blocking */\n#define SQLITE_CHECKPOINT_FULL     1  /* Wait for writers, then checkpoint */\n#define SQLITE_CHECKPOINT_RESTART  2  /* Like FULL but wait for for readers */\n#define SQLITE_CHECKPOINT_TRUNCATE 3  /* Like RESTART but also truncate WAL */\n\n/*\n** CAPI3REF: Virtual Table Interface Configuration\n**\n** This function may be called by either the [xConnect] or [xCreate] method\n** of a [virtual table] implementation to configure\n** various facets of the virtual table interface.\n**\n** If this interface is invoked outside the context of an xConnect or\n** xCreate virtual table method then the behavior is undefined.\n**\n** In the call sqlite3_vtab_config(D,C,...) the D parameter is the\n** [database connection] in which the virtual table is being created and\n** which is passed in as the first argument to the [xConnect] or [xCreate]\n** method that is invoking sqlite3_vtab_config().  The C parameter is one\n** of the [virtual table configuration options].  The presence and meaning\n** of parameters after C depend on which [virtual table configuration option]\n** is used.\n*/\nSQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);\n\n/*\n** CAPI3REF: Virtual Table Configuration Options\n** KEYWORDS: {virtual table configuration options} \n** KEYWORDS: {virtual table configuration option}\n**\n** These macros define the various options to the\n** [sqlite3_vtab_config()] interface that [virtual table] implementations\n** can use to customize and optimize their behavior.\n**\n** <dl>\n** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]]\n** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT</dt>\n** <dd>Calls of the form\n** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,\n** where X is an integer.  If X is zero, then the [virtual table] whose\n** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not\n** support constraints.  In this configuration (which is the default) if\n** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire\n** statement is rolled back as if [ON CONFLICT | OR ABORT] had been\n** specified as part of the users SQL statement, regardless of the actual\n** ON CONFLICT mode specified.\n**\n** If X is non-zero, then the virtual table implementation guarantees\n** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before\n** any modifications to internal or persistent data structures have been made.\n** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite \n** is able to roll back a statement or database transaction, and abandon\n** or continue processing the current SQL statement as appropriate. \n** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns\n** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode\n** had been ABORT.\n**\n** Virtual table implementations that are required to handle OR REPLACE\n** must do so within the [xUpdate] method. If a call to the \n** [sqlite3_vtab_on_conflict()] function indicates that the current ON \n** CONFLICT policy is REPLACE, the virtual table implementation should \n** silently replace the appropriate rows within the xUpdate callback and\n** return SQLITE_OK. Or, if this is not possible, it may return\n** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT \n** constraint handling.\n** </dd>\n**\n** [[SQLITE_VTAB_DIRECTONLY]]<dt>SQLITE_VTAB_DIRECTONLY</dt>\n** <dd>Calls of the form\n** [sqlite3_vtab_config](db,SQLITE_VTAB_DIRECTONLY) from within the\n** the [xConnect] or [xCreate] methods of a [virtual table] implmentation\n** prohibits that virtual table from being used from within triggers and\n** views.\n** </dd>\n**\n** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>\n** <dd>Calls of the form\n** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the\n** the [xConnect] or [xCreate] methods of a [virtual table] implmentation\n** identify that virtual table as being safe to use from within triggers\n** and views.  Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the\n** virtual table can do no serious harm even if it is controlled by a\n** malicious hacker.  Developers should avoid setting the SQLITE_VTAB_INNOCUOUS\n** flag unless absolutely necessary.\n** </dd>\n** </dl>\n*/\n#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1\n#define SQLITE_VTAB_INNOCUOUS          2\n#define SQLITE_VTAB_DIRECTONLY         3\n\n/*\n** CAPI3REF: Determine The Virtual Table Conflict Policy\n**\n** This function may only be called from within a call to the [xUpdate] method\n** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The\n** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],\n** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode\n** of the SQL statement that triggered the call to the [xUpdate] method of the\n** [virtual table].\n*/\nSQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);\n\n/*\n** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE\n**\n** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]\n** method of a [virtual table], then it returns true if and only if the\n** column is being fetched as part of an UPDATE operation during which the\n** column value will not change.  Applications might use this to substitute\n** a return value that is less expensive to compute and that the corresponding\n** [xUpdate] method understands as a \"no-change\" value.\n**\n** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that\n** the column is not changed by the UPDATE statement, then the xColumn\n** method can optionally return without setting a result, without calling\n** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].\n** In that case, [sqlite3_value_nochange(X)] will return true for the\n** same column in the [xUpdate] method.\n*/\nSQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);\n\n/*\n** CAPI3REF: Determine The Collation For a Virtual Table Constraint\n**\n** This function may only be called from within a call to the [xBestIndex]\n** method of a [virtual table]. \n**\n** The first argument must be the sqlite3_index_info object that is the\n** first parameter to the xBestIndex() method. The second argument must be\n** an index into the aConstraint[] array belonging to the sqlite3_index_info\n** structure passed to xBestIndex. This function returns a pointer to a buffer \n** containing the name of the collation sequence for the corresponding\n** constraint.\n*/\nSQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);\n\n/*\n** CAPI3REF: Conflict resolution modes\n** KEYWORDS: {conflict resolution mode}\n**\n** These constants are returned by [sqlite3_vtab_on_conflict()] to\n** inform a [virtual table] implementation what the [ON CONFLICT] mode\n** is for the SQL statement being evaluated.\n**\n** Note that the [SQLITE_IGNORE] constant is also used as a potential\n** return value from the [sqlite3_set_authorizer()] callback and that\n** [SQLITE_ABORT] is also a [result code].\n*/\n#define SQLITE_ROLLBACK 1\n/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */\n#define SQLITE_FAIL     3\n/* #define SQLITE_ABORT 4  // Also an error code */\n#define SQLITE_REPLACE  5\n\n/*\n** CAPI3REF: Prepared Statement Scan Status Opcodes\n** KEYWORDS: {scanstatus options}\n**\n** The following constants can be used for the T parameter to the\n** [sqlite3_stmt_scanstatus(S,X,T,V)] interface.  Each constant designates a\n** different metric for sqlite3_stmt_scanstatus() to return.\n**\n** When the value returned to V is a string, space to hold that string is\n** managed by the prepared statement S and will be automatically freed when\n** S is finalized.\n**\n** <dl>\n** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>\n** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be\n** set to the total number of times that the X-th loop has run.</dd>\n**\n** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>\n** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be set\n** to the total number of rows examined by all iterations of the X-th loop.</dd>\n**\n** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>\n** <dd>^The \"double\" variable pointed to by the V parameter will be set to the\n** query planner's estimate for the average number of rows output from each\n** iteration of the X-th loop.  If the query planner's estimates was accurate,\n** then this value will approximate the quotient NVISIT/NLOOP and the\n** product of this value for all prior loops with the same SELECTID will\n** be the NLOOP value for the current loop.\n**\n** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>\n** <dd>^The \"const char *\" variable pointed to by the V parameter will be set\n** to a zero-terminated UTF-8 string containing the name of the index or table\n** used for the X-th loop.\n**\n** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>\n** <dd>^The \"const char *\" variable pointed to by the V parameter will be set\n** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]\n** description for the X-th loop.\n**\n** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>\n** <dd>^The \"int\" variable pointed to by the V parameter will be set to the\n** \"select-id\" for the X-th loop.  The select-id identifies which query or\n** subquery the loop is part of.  The main query has a select-id of zero.\n** The select-id is the same value as is output in the first column\n** of an [EXPLAIN QUERY PLAN] query.\n** </dl>\n*/\n#define SQLITE_SCANSTAT_NLOOP    0\n#define SQLITE_SCANSTAT_NVISIT   1\n#define SQLITE_SCANSTAT_EST      2\n#define SQLITE_SCANSTAT_NAME     3\n#define SQLITE_SCANSTAT_EXPLAIN  4\n#define SQLITE_SCANSTAT_SELECTID 5\n\n/*\n** CAPI3REF: Prepared Statement Scan Status\n** METHOD: sqlite3_stmt\n**\n** This interface returns information about the predicted and measured\n** performance for pStmt.  Advanced applications can use this\n** interface to compare the predicted and the measured performance and\n** issue warnings and/or rerun [ANALYZE] if discrepancies are found.\n**\n** Since this interface is expected to be rarely used, it is only\n** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]\n** compile-time option.\n**\n** The \"iScanStatusOp\" parameter determines which status information to return.\n** The \"iScanStatusOp\" must be one of the [scanstatus options] or the behavior\n** of this interface is undefined.\n** ^The requested measurement is written into a variable pointed to by\n** the \"pOut\" parameter.\n** Parameter \"idx\" identifies the specific loop to retrieve statistics for.\n** Loops are numbered starting from zero. ^If idx is out of range - less than\n** zero or greater than or equal to the total number of loops used to implement\n** the statement - a non-zero value is returned and the variable that pOut\n** points to is unchanged.\n**\n** ^Statistics might not be available for all loops in all statements. ^In cases\n** where there exist loops with no available statistics, this function behaves\n** as if the loop did not exist - it returns non-zero and leave the variable\n** that pOut points to unchanged.\n**\n** See also: [sqlite3_stmt_scanstatus_reset()]\n*/\nSQLITE_API int sqlite3_stmt_scanstatus(\n  sqlite3_stmt *pStmt,      /* Prepared statement for which info desired */\n  int idx,                  /* Index of loop to report on */\n  int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */\n  void *pOut                /* Result written here */\n);     \n\n/*\n** CAPI3REF: Zero Scan-Status Counters\n** METHOD: sqlite3_stmt\n**\n** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.\n**\n** This API is only available if the library is built with pre-processor\n** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.\n*/\nSQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Flush caches to disk mid-transaction\n**\n** ^If a write-transaction is open on [database connection] D when the\n** [sqlite3_db_cacheflush(D)] interface invoked, any dirty\n** pages in the pager-cache that are not currently in use are written out \n** to disk. A dirty page may be in use if a database cursor created by an\n** active SQL statement is reading from it, or if it is page 1 of a database\n** file (page 1 is always \"in use\").  ^The [sqlite3_db_cacheflush(D)]\n** interface flushes caches for all schemas - \"main\", \"temp\", and\n** any [attached] databases.\n**\n** ^If this function needs to obtain extra database locks before dirty pages \n** can be flushed to disk, it does so. ^If those locks cannot be obtained \n** immediately and there is a busy-handler callback configured, it is invoked\n** in the usual manner. ^If the required lock still cannot be obtained, then\n** the database is skipped and an attempt made to flush any dirty pages\n** belonging to the next (if any) database. ^If any databases are skipped\n** because locks cannot be obtained, but no other error occurs, this\n** function returns SQLITE_BUSY.\n**\n** ^If any other error occurs while flushing dirty pages to disk (for\n** example an IO error or out-of-memory condition), then processing is\n** abandoned and an SQLite [error code] is returned to the caller immediately.\n**\n** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.\n**\n** ^This function does not set the database handle error code or message\n** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.\n*/\nSQLITE_API int sqlite3_db_cacheflush(sqlite3*);\n\n/*\n** CAPI3REF: The pre-update hook.\n**\n** ^These interfaces are only available if SQLite is compiled using the\n** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.\n**\n** ^The [sqlite3_preupdate_hook()] interface registers a callback function\n** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation\n** on a database table.\n** ^At most one preupdate hook may be registered at a time on a single\n** [database connection]; each call to [sqlite3_preupdate_hook()] overrides\n** the previous setting.\n** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]\n** with a NULL pointer as the second parameter.\n** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as\n** the first parameter to callbacks.\n**\n** ^The preupdate hook only fires for changes to real database tables; the\n** preupdate hook is not invoked for changes to [virtual tables] or to\n** system tables like sqlite_master or sqlite_stat1.\n**\n** ^The second parameter to the preupdate callback is a pointer to\n** the [database connection] that registered the preupdate hook.\n** ^The third parameter to the preupdate callback is one of the constants\n** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the\n** kind of update operation that is about to occur.\n** ^(The fourth parameter to the preupdate callback is the name of the\n** database within the database connection that is being modified.  This\n** will be \"main\" for the main database or \"temp\" for TEMP tables or \n** the name given after the AS keyword in the [ATTACH] statement for attached\n** databases.)^\n** ^The fifth parameter to the preupdate callback is the name of the\n** table that is being modified.\n**\n** For an UPDATE or DELETE operation on a [rowid table], the sixth\n** parameter passed to the preupdate callback is the initial [rowid] of the \n** row being modified or deleted. For an INSERT operation on a rowid table,\n** or any operation on a WITHOUT ROWID table, the value of the sixth \n** parameter is undefined. For an INSERT or UPDATE on a rowid table the\n** seventh parameter is the final rowid value of the row being inserted\n** or updated. The value of the seventh parameter passed to the callback\n** function is not defined for operations on WITHOUT ROWID tables, or for\n** INSERT operations on rowid tables.\n**\n** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],\n** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces\n** provide additional information about a preupdate event. These routines\n** may only be called from within a preupdate callback.  Invoking any of\n** these routines from outside of a preupdate callback or with a\n** [database connection] pointer that is different from the one supplied\n** to the preupdate callback results in undefined and probably undesirable\n** behavior.\n**\n** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns\n** in the row that is being inserted, updated, or deleted.\n**\n** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to\n** a [protected sqlite3_value] that contains the value of the Nth column of\n** the table row before it is updated.  The N parameter must be between 0\n** and one less than the number of columns or the behavior will be\n** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE\n** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the\n** behavior is undefined.  The [sqlite3_value] that P points to\n** will be destroyed when the preupdate callback returns.\n**\n** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to\n** a [protected sqlite3_value] that contains the value of the Nth column of\n** the table row after it is updated.  The N parameter must be between 0\n** and one less than the number of columns or the behavior will be\n** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE\n** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the\n** behavior is undefined.  The [sqlite3_value] that P points to\n** will be destroyed when the preupdate callback returns.\n**\n** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate\n** callback was invoked as a result of a direct insert, update, or delete\n** operation; or 1 for inserts, updates, or deletes invoked by top-level \n** triggers; or 2 for changes resulting from triggers called by top-level\n** triggers; and so forth.\n**\n** See also:  [sqlite3_update_hook()]\n*/\n#if defined(SQLITE_ENABLE_PREUPDATE_HOOK)\nSQLITE_API void *sqlite3_preupdate_hook(\n  sqlite3 *db,\n  void(*xPreUpdate)(\n    void *pCtx,                   /* Copy of third arg to preupdate_hook() */\n    sqlite3 *db,                  /* Database handle */\n    int op,                       /* SQLITE_UPDATE, DELETE or INSERT */\n    char const *zDb,              /* Database name */\n    char const *zName,            /* Table name */\n    sqlite3_int64 iKey1,          /* Rowid of row about to be deleted/updated */\n    sqlite3_int64 iKey2           /* New rowid value (for a rowid UPDATE) */\n  ),\n  void*\n);\nSQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);\nSQLITE_API int sqlite3_preupdate_count(sqlite3 *);\nSQLITE_API int sqlite3_preupdate_depth(sqlite3 *);\nSQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);\n#endif\n\n/*\n** CAPI3REF: Low-level system error code\n**\n** ^Attempt to return the underlying operating system error code or error\n** number that caused the most recent I/O error or failure to open a file.\n** The return value is OS-dependent.  For example, on unix systems, after\n** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be\n** called to get back the underlying \"errno\" that caused the problem, such\n** as ENOSPC, EAUTH, EISDIR, and so forth.  \n*/\nSQLITE_API int sqlite3_system_errno(sqlite3*);\n\n/*\n** CAPI3REF: Database Snapshot\n** KEYWORDS: {snapshot} {sqlite3_snapshot}\n**\n** An instance of the snapshot object records the state of a [WAL mode]\n** database for some specific point in history.\n**\n** In [WAL mode], multiple [database connections] that are open on the\n** same database file can each be reading a different historical version\n** of the database file.  When a [database connection] begins a read\n** transaction, that connection sees an unchanging copy of the database\n** as it existed for the point in time when the transaction first started.\n** Subsequent changes to the database from other connections are not seen\n** by the reader until a new read transaction is started.\n**\n** The sqlite3_snapshot object records state information about an historical\n** version of the database file so that it is possible to later open a new read\n** transaction that sees that historical version of the database rather than\n** the most recent version.\n*/\ntypedef struct sqlite3_snapshot {\n  unsigned char hidden[48];\n} sqlite3_snapshot;\n\n/*\n** CAPI3REF: Record A Database Snapshot\n** CONSTRUCTOR: sqlite3_snapshot\n**\n** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a\n** new [sqlite3_snapshot] object that records the current state of\n** schema S in database connection D.  ^On success, the\n** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly\n** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.\n** If there is not already a read-transaction open on schema S when\n** this function is called, one is opened automatically. \n**\n** The following must be true for this function to succeed. If any of\n** the following statements are false when sqlite3_snapshot_get() is\n** called, SQLITE_ERROR is returned. The final value of *P is undefined\n** in this case. \n**\n** <ul>\n**   <li> The database handle must not be in [autocommit mode].\n**\n**   <li> Schema S of [database connection] D must be a [WAL mode] database.\n**\n**   <li> There must not be a write transaction open on schema S of database\n**        connection D.\n**\n**   <li> One or more transactions must have been written to the current wal\n**        file since it was created on disk (by any connection). This means\n**        that a snapshot cannot be taken on a wal mode database with no wal \n**        file immediately after it is first opened. At least one transaction\n**        must be written to it first.\n** </ul>\n**\n** This function may also return SQLITE_NOMEM.  If it is called with the\n** database handle in autocommit mode but fails for some other reason, \n** whether or not a read transaction is opened on schema S is undefined.\n**\n** The [sqlite3_snapshot] object returned from a successful call to\n** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]\n** to avoid a memory leak.\n**\n** The [sqlite3_snapshot_get()] interface is only available when the\n** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.\n*/\nSQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(\n  sqlite3 *db,\n  const char *zSchema,\n  sqlite3_snapshot **ppSnapshot\n);\n\n/*\n** CAPI3REF: Start a read transaction on an historical snapshot\n** METHOD: sqlite3_snapshot\n**\n** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read \n** transaction or upgrades an existing one for schema S of \n** [database connection] D such that the read transaction refers to \n** historical [snapshot] P, rather than the most recent change to the \n** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK \n** on success or an appropriate [error code] if it fails.\n**\n** ^In order to succeed, the database connection must not be in \n** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there\n** is already a read transaction open on schema S, then the database handle\n** must have no active statements (SELECT statements that have been passed\n** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()). \n** SQLITE_ERROR is returned if either of these conditions is violated, or\n** if schema S does not exist, or if the snapshot object is invalid.\n**\n** ^A call to sqlite3_snapshot_open() will fail to open if the specified\n** snapshot has been overwritten by a [checkpoint]. In this case \n** SQLITE_ERROR_SNAPSHOT is returned.\n**\n** If there is already a read transaction open when this function is \n** invoked, then the same read transaction remains open (on the same\n** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT\n** is returned. If another error code - for example SQLITE_PROTOCOL or an\n** SQLITE_IOERR error code - is returned, then the final state of the\n** read transaction is undefined. If SQLITE_OK is returned, then the \n** read transaction is now open on database snapshot P.\n**\n** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the\n** database connection D does not know that the database file for\n** schema S is in [WAL mode].  A database connection might not know\n** that the database file is in [WAL mode] if there has been no prior\n** I/O on that database connection, or if the database entered [WAL mode] \n** after the most recent I/O on the database connection.)^\n** (Hint: Run \"[PRAGMA application_id]\" against a newly opened\n** database connection in order to make it ready to use snapshots.)\n**\n** The [sqlite3_snapshot_open()] interface is only available when the\n** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.\n*/\nSQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(\n  sqlite3 *db,\n  const char *zSchema,\n  sqlite3_snapshot *pSnapshot\n);\n\n/*\n** CAPI3REF: Destroy a snapshot\n** DESTRUCTOR: sqlite3_snapshot\n**\n** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.\n** The application must eventually free every [sqlite3_snapshot] object\n** using this routine to avoid a memory leak.\n**\n** The [sqlite3_snapshot_free()] interface is only available when the\n** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.\n*/\nSQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);\n\n/*\n** CAPI3REF: Compare the ages of two snapshot handles.\n** METHOD: sqlite3_snapshot\n**\n** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages\n** of two valid snapshot handles. \n**\n** If the two snapshot handles are not associated with the same database \n** file, the result of the comparison is undefined. \n**\n** Additionally, the result of the comparison is only valid if both of the\n** snapshot handles were obtained by calling sqlite3_snapshot_get() since the\n** last time the wal file was deleted. The wal file is deleted when the\n** database is changed back to rollback mode or when the number of database\n** clients drops to zero. If either snapshot handle was obtained before the \n** wal file was last deleted, the value returned by this function \n** is undefined.\n**\n** Otherwise, this API returns a negative value if P1 refers to an older\n** snapshot than P2, zero if the two handles refer to the same database\n** snapshot, and a positive value if P1 is a newer snapshot than P2.\n**\n** This interface is only available if SQLite is compiled with the\n** [SQLITE_ENABLE_SNAPSHOT] option.\n*/\nSQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(\n  sqlite3_snapshot *p1,\n  sqlite3_snapshot *p2\n);\n\n/*\n** CAPI3REF: Recover snapshots from a wal file\n** METHOD: sqlite3_snapshot\n**\n** If a [WAL file] remains on disk after all database connections close\n** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control]\n** or because the last process to have the database opened exited without\n** calling [sqlite3_close()]) and a new connection is subsequently opened\n** on that database and [WAL file], the [sqlite3_snapshot_open()] interface\n** will only be able to open the last transaction added to the WAL file\n** even though the WAL file contains other valid transactions.\n**\n** This function attempts to scan the WAL file associated with database zDb\n** of database handle db and make all valid snapshots available to\n** sqlite3_snapshot_open(). It is an error if there is already a read\n** transaction open on the database, or if the database is not a WAL mode\n** database.\n**\n** SQLITE_OK is returned if successful, or an SQLite error code otherwise.\n**\n** This interface is only available if SQLite is compiled with the\n** [SQLITE_ENABLE_SNAPSHOT] option.\n*/\nSQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);\n\n/*\n** CAPI3REF: Serialize a database\n**\n** The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory\n** that is a serialization of the S database on [database connection] D.\n** If P is not a NULL pointer, then the size of the database in bytes\n** is written into *P.\n**\n** For an ordinary on-disk database file, the serialization is just a\n** copy of the disk file.  For an in-memory database or a \"TEMP\" database,\n** the serialization is the same sequence of bytes which would be written\n** to disk if that database where backed up to disk.\n**\n** The usual case is that sqlite3_serialize() copies the serialization of\n** the database into memory obtained from [sqlite3_malloc64()] and returns\n** a pointer to that memory.  The caller is responsible for freeing the\n** returned value to avoid a memory leak.  However, if the F argument\n** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations\n** are made, and the sqlite3_serialize() function will return a pointer\n** to the contiguous memory representation of the database that SQLite\n** is currently using for that database, or NULL if the no such contiguous\n** memory representation of the database exists.  A contiguous memory\n** representation of the database will usually only exist if there has\n** been a prior call to [sqlite3_deserialize(D,S,...)] with the same\n** values of D and S.\n** The size of the database is written into *P even if the \n** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy\n** of the database exists.\n**\n** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the\n** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory\n** allocation error occurs.\n**\n** This interface is only available if SQLite is compiled with the\n** [SQLITE_ENABLE_DESERIALIZE] option.\n*/\nSQLITE_API unsigned char *sqlite3_serialize(\n  sqlite3 *db,           /* The database connection */\n  const char *zSchema,   /* Which DB to serialize. ex: \"main\", \"temp\", ... */\n  sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */\n  unsigned int mFlags    /* Zero or more SQLITE_SERIALIZE_* flags */\n);\n\n/*\n** CAPI3REF: Flags for sqlite3_serialize\n**\n** Zero or more of the following constants can be OR-ed together for\n** the F argument to [sqlite3_serialize(D,S,P,F)].\n**\n** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return\n** a pointer to contiguous in-memory database that it is currently using,\n** without making a copy of the database.  If SQLite is not currently using\n** a contiguous in-memory database, then this option causes\n** [sqlite3_serialize()] to return a NULL pointer.  SQLite will only be\n** using a contiguous in-memory database if it has been initialized by a\n** prior call to [sqlite3_deserialize()].\n*/\n#define SQLITE_SERIALIZE_NOCOPY 0x001   /* Do no memory allocations */\n\n/*\n** CAPI3REF: Deserialize a database\n**\n** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the \n** [database connection] D to disconnect from database S and then\n** reopen S as an in-memory database based on the serialization contained\n** in P.  The serialized database P is N bytes in size.  M is the size of\n** the buffer P, which might be larger than N.  If M is larger than N, and\n** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is\n** permitted to add content to the in-memory database as long as the total\n** size does not exceed M bytes.\n**\n** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will\n** invoke sqlite3_free() on the serialization buffer when the database\n** connection closes.  If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then\n** SQLite will try to increase the buffer size using sqlite3_realloc64()\n** if writes on the database cause it to grow larger than M bytes.\n**\n** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the\n** database is currently in a read transaction or is involved in a backup\n** operation.\n**\n** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the \n** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then\n** [sqlite3_free()] is invoked on argument P prior to returning.\n**\n** This interface is only available if SQLite is compiled with the\n** [SQLITE_ENABLE_DESERIALIZE] option.\n*/\nSQLITE_API int sqlite3_deserialize(\n  sqlite3 *db,            /* The database connection */\n  const char *zSchema,    /* Which DB to reopen with the deserialization */\n  unsigned char *pData,   /* The serialized database content */\n  sqlite3_int64 szDb,     /* Number bytes in the deserialization */\n  sqlite3_int64 szBuf,    /* Total size of buffer pData[] */\n  unsigned mFlags         /* Zero or more SQLITE_DESERIALIZE_* flags */\n);\n\n/*\n** CAPI3REF: Flags for sqlite3_deserialize()\n**\n** The following are allowed values for 6th argument (the F argument) to\n** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.\n**\n** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization\n** in the P argument is held in memory obtained from [sqlite3_malloc64()]\n** and that SQLite should take ownership of this memory and automatically\n** free it when it has finished using it.  Without this flag, the caller\n** is responsible for freeing any dynamically allocated memory.\n**\n** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to\n** grow the size of the database using calls to [sqlite3_realloc64()].  This\n** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.\n** Without this flag, the deserialized database cannot increase in size beyond\n** the number of bytes specified by the M parameter.\n**\n** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database\n** should be treated as read-only.\n*/\n#define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */\n#define SQLITE_DESERIALIZE_RESIZEABLE  2 /* Resize using sqlite3_realloc64() */\n#define SQLITE_DESERIALIZE_READONLY    4 /* Database is read-only */\n\n/*\n** Undo the hack that converts floating point types to integer for\n** builds on processors without floating point support.\n*/\n#ifdef SQLITE_OMIT_FLOATING_POINT\n# undef double\n#endif\n\n#ifdef __cplusplus\n}  /* End of the 'extern \"C\"' block */\n#endif\n#endif /* SQLITE3_H */\n\n/******** Begin file sqlite3rtree.h *********/\n/*\n** 2010 August 30\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n*/\n\n#ifndef _SQLITE3RTREE_H_\n#define _SQLITE3RTREE_H_\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;\ntypedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;\n\n/* The double-precision datatype used by RTree depends on the\n** SQLITE_RTREE_INT_ONLY compile-time option.\n*/\n#ifdef SQLITE_RTREE_INT_ONLY\n  typedef sqlite3_int64 sqlite3_rtree_dbl;\n#else\n  typedef double sqlite3_rtree_dbl;\n#endif\n\n/*\n** Register a geometry callback named zGeom that can be used as part of an\n** R-Tree geometry query as follows:\n**\n**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)\n*/\nSQLITE_API int sqlite3_rtree_geometry_callback(\n  sqlite3 *db,\n  const char *zGeom,\n  int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),\n  void *pContext\n);\n\n\n/*\n** A pointer to a structure of the following type is passed as the first\n** argument to callbacks registered using rtree_geometry_callback().\n*/\nstruct sqlite3_rtree_geometry {\n  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */\n  int nParam;                     /* Size of array aParam[] */\n  sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */\n  void *pUser;                    /* Callback implementation user data */\n  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */\n};\n\n/*\n** Register a 2nd-generation geometry callback named zScore that can be \n** used as part of an R-Tree geometry query as follows:\n**\n**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)\n*/\nSQLITE_API int sqlite3_rtree_query_callback(\n  sqlite3 *db,\n  const char *zQueryFunc,\n  int (*xQueryFunc)(sqlite3_rtree_query_info*),\n  void *pContext,\n  void (*xDestructor)(void*)\n);\n\n\n/*\n** A pointer to a structure of the following type is passed as the \n** argument to scored geometry callback registered using\n** sqlite3_rtree_query_callback().\n**\n** Note that the first 5 fields of this structure are identical to\n** sqlite3_rtree_geometry.  This structure is a subclass of\n** sqlite3_rtree_geometry.\n*/\nstruct sqlite3_rtree_query_info {\n  void *pContext;                   /* pContext from when function registered */\n  int nParam;                       /* Number of function parameters */\n  sqlite3_rtree_dbl *aParam;        /* value of function parameters */\n  void *pUser;                      /* callback can use this, if desired */\n  void (*xDelUser)(void*);          /* function to free pUser */\n  sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */\n  unsigned int *anQueue;            /* Number of pending entries in the queue */\n  int nCoord;                       /* Number of coordinates */\n  int iLevel;                       /* Level of current node or entry */\n  int mxLevel;                      /* The largest iLevel value in the tree */\n  sqlite3_int64 iRowid;             /* Rowid for current entry */\n  sqlite3_rtree_dbl rParentScore;   /* Score of parent node */\n  int eParentWithin;                /* Visibility of parent node */\n  int eWithin;                      /* OUT: Visibility */\n  sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */\n  /* The following fields are only available in 3.8.11 and later */\n  sqlite3_value **apSqlParam;       /* Original SQL values of parameters */\n};\n\n/*\n** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.\n*/\n#define NOT_WITHIN       0   /* Object completely outside of query region */\n#define PARTLY_WITHIN    1   /* Object partially overlaps query region */\n#define FULLY_WITHIN     2   /* Object fully contained within query region */\n\n\n#ifdef __cplusplus\n}  /* end of the 'extern \"C\"' block */\n#endif\n\n#endif  /* ifndef _SQLITE3RTREE_H_ */\n\n/******** End of sqlite3rtree.h *********/\n/******** Begin file sqlite3session.h *********/\n\n#if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)\n#define __SQLITESESSION_H_ 1\n\n/*\n** Make sure we can call this stuff from C++.\n*/\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\n/*\n** CAPI3REF: Session Object Handle\n**\n** An instance of this object is a [session] that can be used to\n** record changes to a database.\n*/\ntypedef struct sqlite3_session sqlite3_session;\n\n/*\n** CAPI3REF: Changeset Iterator Handle\n**\n** An instance of this object acts as a cursor for iterating\n** over the elements of a [changeset] or [patchset].\n*/\ntypedef struct sqlite3_changeset_iter sqlite3_changeset_iter;\n\n/*\n** CAPI3REF: Create A New Session Object\n** CONSTRUCTOR: sqlite3_session\n**\n** Create a new session object attached to database handle db. If successful,\n** a pointer to the new object is written to *ppSession and SQLITE_OK is\n** returned. If an error occurs, *ppSession is set to NULL and an SQLite\n** error code (e.g. SQLITE_NOMEM) is returned.\n**\n** It is possible to create multiple session objects attached to a single\n** database handle.\n**\n** Session objects created using this function should be deleted using the\n** [sqlite3session_delete()] function before the database handle that they\n** are attached to is itself closed. If the database handle is closed before\n** the session object is deleted, then the results of calling any session\n** module function, including [sqlite3session_delete()] on the session object\n** are undefined.\n**\n** Because the session module uses the [sqlite3_preupdate_hook()] API, it\n** is not possible for an application to register a pre-update hook on a\n** database handle that has one or more session objects attached. Nor is\n** it possible to create a session object attached to a database handle for\n** which a pre-update hook is already defined. The results of attempting \n** either of these things are undefined.\n**\n** The session object will be used to create changesets for tables in\n** database zDb, where zDb is either \"main\", or \"temp\", or the name of an\n** attached database. It is not an error if database zDb is not attached\n** to the database when the session object is created.\n*/\nSQLITE_API int sqlite3session_create(\n  sqlite3 *db,                    /* Database handle */\n  const char *zDb,                /* Name of db (e.g. \"main\") */\n  sqlite3_session **ppSession     /* OUT: New session object */\n);\n\n/*\n** CAPI3REF: Delete A Session Object\n** DESTRUCTOR: sqlite3_session\n**\n** Delete a session object previously allocated using \n** [sqlite3session_create()]. Once a session object has been deleted, the\n** results of attempting to use pSession with any other session module\n** function are undefined.\n**\n** Session objects must be deleted before the database handle to which they\n** are attached is closed. Refer to the documentation for \n** [sqlite3session_create()] for details.\n*/\nSQLITE_API void sqlite3session_delete(sqlite3_session *pSession);\n\n\n/*\n** CAPI3REF: Enable Or Disable A Session Object\n** METHOD: sqlite3_session\n**\n** Enable or disable the recording of changes by a session object. When\n** enabled, a session object records changes made to the database. When\n** disabled - it does not. A newly created session object is enabled.\n** Refer to the documentation for [sqlite3session_changeset()] for further\n** details regarding how enabling and disabling a session object affects\n** the eventual changesets.\n**\n** Passing zero to this function disables the session. Passing a value\n** greater than zero enables it. Passing a value less than zero is a \n** no-op, and may be used to query the current state of the session.\n**\n** The return value indicates the final state of the session object: 0 if \n** the session is disabled, or 1 if it is enabled.\n*/\nSQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);\n\n/*\n** CAPI3REF: Set Or Clear the Indirect Change Flag\n** METHOD: sqlite3_session\n**\n** Each change recorded by a session object is marked as either direct or\n** indirect. A change is marked as indirect if either:\n**\n** <ul>\n**   <li> The session object \"indirect\" flag is set when the change is\n**        made, or\n**   <li> The change is made by an SQL trigger or foreign key action \n**        instead of directly as a result of a users SQL statement.\n** </ul>\n**\n** If a single row is affected by more than one operation within a session,\n** then the change is considered indirect if all operations meet the criteria\n** for an indirect change above, or direct otherwise.\n**\n** This function is used to set, clear or query the session object indirect\n** flag.  If the second argument passed to this function is zero, then the\n** indirect flag is cleared. If it is greater than zero, the indirect flag\n** is set. Passing a value less than zero does not modify the current value\n** of the indirect flag, and may be used to query the current state of the \n** indirect flag for the specified session object.\n**\n** The return value indicates the final state of the indirect flag: 0 if \n** it is clear, or 1 if it is set.\n*/\nSQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);\n\n/*\n** CAPI3REF: Attach A Table To A Session Object\n** METHOD: sqlite3_session\n**\n** If argument zTab is not NULL, then it is the name of a table to attach\n** to the session object passed as the first argument. All subsequent changes \n** made to the table while the session object is enabled will be recorded. See \n** documentation for [sqlite3session_changeset()] for further details.\n**\n** Or, if argument zTab is NULL, then changes are recorded for all tables\n** in the database. If additional tables are added to the database (by \n** executing \"CREATE TABLE\" statements) after this call is made, changes for \n** the new tables are also recorded.\n**\n** Changes can only be recorded for tables that have a PRIMARY KEY explicitly\n** defined as part of their CREATE TABLE statement. It does not matter if the \n** PRIMARY KEY is an \"INTEGER PRIMARY KEY\" (rowid alias) or not. The PRIMARY\n** KEY may consist of a single column, or may be a composite key.\n** \n** It is not an error if the named table does not exist in the database. Nor\n** is it an error if the named table does not have a PRIMARY KEY. However,\n** no changes will be recorded in either of these scenarios.\n**\n** Changes are not recorded for individual rows that have NULL values stored\n** in one or more of their PRIMARY KEY columns.\n**\n** SQLITE_OK is returned if the call completes without error. Or, if an error \n** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.\n**\n** <h3>Special sqlite_stat1 Handling</h3>\n**\n** As of SQLite version 3.22.0, the \"sqlite_stat1\" table is an exception to \n** some of the rules above. In SQLite, the schema of sqlite_stat1 is:\n**  <pre>\n**  &nbsp;     CREATE TABLE sqlite_stat1(tbl,idx,stat)  \n**  </pre>\n**\n** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are \n** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes \n** are recorded for rows for which (idx IS NULL) is true. However, for such\n** rows a zero-length blob (SQL value X'') is stored in the changeset or\n** patchset instead of a NULL value. This allows such changesets to be\n** manipulated by legacy implementations of sqlite3changeset_invert(),\n** concat() and similar.\n**\n** The sqlite3changeset_apply() function automatically converts the \n** zero-length blob back to a NULL value when updating the sqlite_stat1\n** table. However, if the application calls sqlite3changeset_new(),\n** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset \n** iterator directly (including on a changeset iterator passed to a\n** conflict-handler callback) then the X'' value is returned. The application\n** must translate X'' to NULL itself if required.\n**\n** Legacy (older than 3.22.0) versions of the sessions module cannot capture\n** changes made to the sqlite_stat1 table. Legacy versions of the\n** sqlite3changeset_apply() function silently ignore any modifications to the\n** sqlite_stat1 table that are part of a changeset or patchset.\n*/\nSQLITE_API int sqlite3session_attach(\n  sqlite3_session *pSession,      /* Session object */\n  const char *zTab                /* Table name */\n);\n\n/*\n** CAPI3REF: Set a table filter on a Session Object.\n** METHOD: sqlite3_session\n**\n** The second argument (xFilter) is the \"filter callback\". For changes to rows \n** in tables that are not attached to the Session object, the filter is called\n** to determine whether changes to the table's rows should be tracked or not. \n** If xFilter returns 0, changes are not tracked. Note that once a table is \n** attached, xFilter will not be called again.\n*/\nSQLITE_API void sqlite3session_table_filter(\n  sqlite3_session *pSession,      /* Session object */\n  int(*xFilter)(\n    void *pCtx,                   /* Copy of third arg to _filter_table() */\n    const char *zTab              /* Table name */\n  ),\n  void *pCtx                      /* First argument passed to xFilter */\n);\n\n/*\n** CAPI3REF: Generate A Changeset From A Session Object\n** METHOD: sqlite3_session\n**\n** Obtain a changeset containing changes to the tables attached to the \n** session object passed as the first argument. If successful, \n** set *ppChangeset to point to a buffer containing the changeset \n** and *pnChangeset to the size of the changeset in bytes before returning\n** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to\n** zero and return an SQLite error code.\n**\n** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,\n** each representing a change to a single row of an attached table. An INSERT\n** change contains the values of each field of a new database row. A DELETE\n** contains the original values of each field of a deleted database row. An\n** UPDATE change contains the original values of each field of an updated\n** database row along with the updated values for each updated non-primary-key\n** column. It is not possible for an UPDATE change to represent a change that\n** modifies the values of primary key columns. If such a change is made, it\n** is represented in a changeset as a DELETE followed by an INSERT.\n**\n** Changes are not recorded for rows that have NULL values stored in one or \n** more of their PRIMARY KEY columns. If such a row is inserted or deleted,\n** no corresponding change is present in the changesets returned by this\n** function. If an existing row with one or more NULL values stored in\n** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,\n** only an INSERT is appears in the changeset. Similarly, if an existing row\n** with non-NULL PRIMARY KEY values is updated so that one or more of its\n** PRIMARY KEY columns are set to NULL, the resulting changeset contains a\n** DELETE change only.\n**\n** The contents of a changeset may be traversed using an iterator created\n** using the [sqlite3changeset_start()] API. A changeset may be applied to\n** a database with a compatible schema using the [sqlite3changeset_apply()]\n** API.\n**\n** Within a changeset generated by this function, all changes related to a\n** single table are grouped together. In other words, when iterating through\n** a changeset or when applying a changeset to a database, all changes related\n** to a single table are processed before moving on to the next table. Tables\n** are sorted in the same order in which they were attached (or auto-attached)\n** to the sqlite3_session object. The order in which the changes related to\n** a single table are stored is undefined.\n**\n** Following a successful call to this function, it is the responsibility of\n** the caller to eventually free the buffer that *ppChangeset points to using\n** [sqlite3_free()].\n**\n** <h3>Changeset Generation</h3>\n**\n** Once a table has been attached to a session object, the session object\n** records the primary key values of all new rows inserted into the table.\n** It also records the original primary key and other column values of any\n** deleted or updated rows. For each unique primary key value, data is only\n** recorded once - the first time a row with said primary key is inserted,\n** updated or deleted in the lifetime of the session.\n**\n** There is one exception to the previous paragraph: when a row is inserted,\n** updated or deleted, if one or more of its primary key columns contain a\n** NULL value, no record of the change is made.\n**\n** The session object therefore accumulates two types of records - those\n** that consist of primary key values only (created when the user inserts\n** a new record) and those that consist of the primary key values and the\n** original values of other table columns (created when the users deletes\n** or updates a record).\n**\n** When this function is called, the requested changeset is created using\n** both the accumulated records and the current contents of the database\n** file. Specifically:\n**\n** <ul>\n**   <li> For each record generated by an insert, the database is queried\n**        for a row with a matching primary key. If one is found, an INSERT\n**        change is added to the changeset. If no such row is found, no change \n**        is added to the changeset.\n**\n**   <li> For each record generated by an update or delete, the database is \n**        queried for a row with a matching primary key. If such a row is\n**        found and one or more of the non-primary key fields have been\n**        modified from their original values, an UPDATE change is added to \n**        the changeset. Or, if no such row is found in the table, a DELETE \n**        change is added to the changeset. If there is a row with a matching\n**        primary key in the database, but all fields contain their original\n**        values, no change is added to the changeset.\n** </ul>\n**\n** This means, amongst other things, that if a row is inserted and then later\n** deleted while a session object is active, neither the insert nor the delete\n** will be present in the changeset. Or if a row is deleted and then later a \n** row with the same primary key values inserted while a session object is\n** active, the resulting changeset will contain an UPDATE change instead of\n** a DELETE and an INSERT.\n**\n** When a session object is disabled (see the [sqlite3session_enable()] API),\n** it does not accumulate records when rows are inserted, updated or deleted.\n** This may appear to have some counter-intuitive effects if a single row\n** is written to more than once during a session. For example, if a row\n** is inserted while a session object is enabled, then later deleted while \n** the same session object is disabled, no INSERT record will appear in the\n** changeset, even though the delete took place while the session was disabled.\n** Or, if one field of a row is updated while a session is disabled, and \n** another field of the same row is updated while the session is enabled, the\n** resulting changeset will contain an UPDATE change that updates both fields.\n*/\nSQLITE_API int sqlite3session_changeset(\n  sqlite3_session *pSession,      /* Session object */\n  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */\n  void **ppChangeset              /* OUT: Buffer containing changeset */\n);\n\n/*\n** CAPI3REF: Load The Difference Between Tables Into A Session\n** METHOD: sqlite3_session\n**\n** If it is not already attached to the session object passed as the first\n** argument, this function attaches table zTbl in the same manner as the\n** [sqlite3session_attach()] function. If zTbl does not exist, or if it\n** does not have a primary key, this function is a no-op (but does not return\n** an error).\n**\n** Argument zFromDb must be the name of a database (\"main\", \"temp\" etc.)\n** attached to the same database handle as the session object that contains \n** a table compatible with the table attached to the session by this function.\n** A table is considered compatible if it:\n**\n** <ul>\n**   <li> Has the same name,\n**   <li> Has the same set of columns declared in the same order, and\n**   <li> Has the same PRIMARY KEY definition.\n** </ul>\n**\n** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables\n** are compatible but do not have any PRIMARY KEY columns, it is not an error\n** but no changes are added to the session object. As with other session\n** APIs, tables without PRIMARY KEYs are simply ignored.\n**\n** This function adds a set of changes to the session object that could be\n** used to update the table in database zFrom (call this the \"from-table\") \n** so that its content is the same as the table attached to the session \n** object (call this the \"to-table\"). Specifically:\n**\n** <ul>\n**   <li> For each row (primary key) that exists in the to-table but not in \n**     the from-table, an INSERT record is added to the session object.\n**\n**   <li> For each row (primary key) that exists in the to-table but not in \n**     the from-table, a DELETE record is added to the session object.\n**\n**   <li> For each row (primary key) that exists in both tables, but features \n**     different non-PK values in each, an UPDATE record is added to the\n**     session.  \n** </ul>\n**\n** To clarify, if this function is called and then a changeset constructed\n** using [sqlite3session_changeset()], then after applying that changeset to \n** database zFrom the contents of the two compatible tables would be \n** identical.\n**\n** It an error if database zFrom does not exist or does not contain the\n** required compatible table.\n**\n** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite\n** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg\n** may be set to point to a buffer containing an English language error \n** message. It is the responsibility of the caller to free this buffer using\n** sqlite3_free().\n*/\nSQLITE_API int sqlite3session_diff(\n  sqlite3_session *pSession,\n  const char *zFromDb,\n  const char *zTbl,\n  char **pzErrMsg\n);\n\n\n/*\n** CAPI3REF: Generate A Patchset From A Session Object\n** METHOD: sqlite3_session\n**\n** The differences between a patchset and a changeset are that:\n**\n** <ul>\n**   <li> DELETE records consist of the primary key fields only. The \n**        original values of other fields are omitted.\n**   <li> The original values of any modified fields are omitted from \n**        UPDATE records.\n** </ul>\n**\n** A patchset blob may be used with up to date versions of all \n** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(), \n** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,\n** attempting to use a patchset blob with old versions of the\n** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. \n**\n** Because the non-primary key \"old.*\" fields are omitted, no \n** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset\n** is passed to the sqlite3changeset_apply() API. Other conflict types work\n** in the same way as for changesets.\n**\n** Changes within a patchset are ordered in the same way as for changesets\n** generated by the sqlite3session_changeset() function (i.e. all changes for\n** a single table are grouped together, tables appear in the order in which\n** they were attached to the session object).\n*/\nSQLITE_API int sqlite3session_patchset(\n  sqlite3_session *pSession,      /* Session object */\n  int *pnPatchset,                /* OUT: Size of buffer at *ppPatchset */\n  void **ppPatchset               /* OUT: Buffer containing patchset */\n);\n\n/*\n** CAPI3REF: Test if a changeset has recorded any changes.\n**\n** Return non-zero if no changes to attached tables have been recorded by \n** the session object passed as the first argument. Otherwise, if one or \n** more changes have been recorded, return zero.\n**\n** Even if this function returns zero, it is possible that calling\n** [sqlite3session_changeset()] on the session handle may still return a\n** changeset that contains no changes. This can happen when a row in \n** an attached table is modified and then later on the original values \n** are restored. However, if this function returns non-zero, then it is\n** guaranteed that a call to sqlite3session_changeset() will return a \n** changeset containing zero changes.\n*/\nSQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);\n\n/*\n** CAPI3REF: Create An Iterator To Traverse A Changeset \n** CONSTRUCTOR: sqlite3_changeset_iter\n**\n** Create an iterator used to iterate through the contents of a changeset.\n** If successful, *pp is set to point to the iterator handle and SQLITE_OK\n** is returned. Otherwise, if an error occurs, *pp is set to zero and an\n** SQLite error code is returned.\n**\n** The following functions can be used to advance and query a changeset \n** iterator created by this function:\n**\n** <ul>\n**   <li> [sqlite3changeset_next()]\n**   <li> [sqlite3changeset_op()]\n**   <li> [sqlite3changeset_new()]\n**   <li> [sqlite3changeset_old()]\n** </ul>\n**\n** It is the responsibility of the caller to eventually destroy the iterator\n** by passing it to [sqlite3changeset_finalize()]. The buffer containing the\n** changeset (pChangeset) must remain valid until after the iterator is\n** destroyed.\n**\n** Assuming the changeset blob was created by one of the\n** [sqlite3session_changeset()], [sqlite3changeset_concat()] or\n** [sqlite3changeset_invert()] functions, all changes within the changeset \n** that apply to a single table are grouped together. This means that when \n** an application iterates through a changeset using an iterator created by \n** this function, all changes that relate to a single table are visited \n** consecutively. There is no chance that the iterator will visit a change \n** the applies to table X, then one for table Y, and then later on visit \n** another change for table X.\n**\n** The behavior of sqlite3changeset_start_v2() and its streaming equivalent\n** may be modified by passing a combination of\n** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter.\n**\n** Note that the sqlite3changeset_start_v2() API is still <b>experimental</b>\n** and therefore subject to change.\n*/\nSQLITE_API int sqlite3changeset_start(\n  sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */\n  int nChangeset,                 /* Size of changeset blob in bytes */\n  void *pChangeset                /* Pointer to blob containing changeset */\n);\nSQLITE_API int sqlite3changeset_start_v2(\n  sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */\n  int nChangeset,                 /* Size of changeset blob in bytes */\n  void *pChangeset,               /* Pointer to blob containing changeset */\n  int flags                       /* SESSION_CHANGESETSTART_* flags */\n);\n\n/*\n** CAPI3REF: Flags for sqlite3changeset_start_v2\n**\n** The following flags may passed via the 4th parameter to\n** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:\n**\n** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>\n**   Invert the changeset while iterating through it. This is equivalent to\n**   inverting a changeset using sqlite3changeset_invert() before applying it.\n**   It is an error to specify this flag with a patchset.\n*/\n#define SQLITE_CHANGESETSTART_INVERT        0x0002\n\n\n/*\n** CAPI3REF: Advance A Changeset Iterator\n** METHOD: sqlite3_changeset_iter\n**\n** This function may only be used with iterators created by the function\n** [sqlite3changeset_start()]. If it is called on an iterator passed to\n** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE\n** is returned and the call has no effect.\n**\n** Immediately after an iterator is created by sqlite3changeset_start(), it\n** does not point to any change in the changeset. Assuming the changeset\n** is not empty, the first call to this function advances the iterator to\n** point to the first change in the changeset. Each subsequent call advances\n** the iterator to point to the next change in the changeset (if any). If\n** no error occurs and the iterator points to a valid change after a call\n** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. \n** Otherwise, if all changes in the changeset have already been visited,\n** SQLITE_DONE is returned.\n**\n** If an error occurs, an SQLite error code is returned. Possible error \n** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or \n** SQLITE_NOMEM.\n*/\nSQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);\n\n/*\n** CAPI3REF: Obtain The Current Operation From A Changeset Iterator\n** METHOD: sqlite3_changeset_iter\n**\n** The pIter argument passed to this function may either be an iterator\n** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator\n** created by [sqlite3changeset_start()]. In the latter case, the most recent\n** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this\n** is not the case, this function returns [SQLITE_MISUSE].\n**\n** If argument pzTab is not NULL, then *pzTab is set to point to a\n** nul-terminated utf-8 encoded string containing the name of the table\n** affected by the current change. The buffer remains valid until either\n** sqlite3changeset_next() is called on the iterator or until the \n** conflict-handler function returns. If pnCol is not NULL, then *pnCol is \n** set to the number of columns in the table affected by the change. If\n** pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change\n** is an indirect change, or false (0) otherwise. See the documentation for\n** [sqlite3session_indirect()] for a description of direct and indirect\n** changes. Finally, if pOp is not NULL, then *pOp is set to one of \n** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the \n** type of change that the iterator currently points to.\n**\n** If no error occurs, SQLITE_OK is returned. If an error does occur, an\n** SQLite error code is returned. The values of the output variables may not\n** be trusted in this case.\n*/\nSQLITE_API int sqlite3changeset_op(\n  sqlite3_changeset_iter *pIter,  /* Iterator object */\n  const char **pzTab,             /* OUT: Pointer to table name */\n  int *pnCol,                     /* OUT: Number of columns in table */\n  int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */\n  int *pbIndirect                 /* OUT: True for an 'indirect' change */\n);\n\n/*\n** CAPI3REF: Obtain The Primary Key Definition Of A Table\n** METHOD: sqlite3_changeset_iter\n**\n** For each modified table, a changeset includes the following:\n**\n** <ul>\n**   <li> The number of columns in the table, and\n**   <li> Which of those columns make up the tables PRIMARY KEY.\n** </ul>\n**\n** This function is used to find which columns comprise the PRIMARY KEY of\n** the table modified by the change that iterator pIter currently points to.\n** If successful, *pabPK is set to point to an array of nCol entries, where\n** nCol is the number of columns in the table. Elements of *pabPK are set to\n** 0x01 if the corresponding column is part of the tables primary key, or\n** 0x00 if it is not.\n**\n** If argument pnCol is not NULL, then *pnCol is set to the number of columns\n** in the table.\n**\n** If this function is called when the iterator does not point to a valid\n** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,\n** SQLITE_OK is returned and the output variables populated as described\n** above.\n*/\nSQLITE_API int sqlite3changeset_pk(\n  sqlite3_changeset_iter *pIter,  /* Iterator object */\n  unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */\n  int *pnCol                      /* OUT: Number of entries in output array */\n);\n\n/*\n** CAPI3REF: Obtain old.* Values From A Changeset Iterator\n** METHOD: sqlite3_changeset_iter\n**\n** The pIter argument passed to this function may either be an iterator\n** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator\n** created by [sqlite3changeset_start()]. In the latter case, the most recent\n** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. \n** Furthermore, it may only be called if the type of change that the iterator\n** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,\n** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.\n**\n** Argument iVal must be greater than or equal to 0, and less than the number\n** of columns in the table affected by the current change. Otherwise,\n** [SQLITE_RANGE] is returned and *ppValue is set to NULL.\n**\n** If successful, this function sets *ppValue to point to a protected\n** sqlite3_value object containing the iVal'th value from the vector of \n** original row values stored as part of the UPDATE or DELETE change and\n** returns SQLITE_OK. The name of the function comes from the fact that this \n** is similar to the \"old.*\" columns available to update or delete triggers.\n**\n** If some other error occurs (e.g. an OOM condition), an SQLite error code\n** is returned and *ppValue is set to NULL.\n*/\nSQLITE_API int sqlite3changeset_old(\n  sqlite3_changeset_iter *pIter,  /* Changeset iterator */\n  int iVal,                       /* Column number */\n  sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */\n);\n\n/*\n** CAPI3REF: Obtain new.* Values From A Changeset Iterator\n** METHOD: sqlite3_changeset_iter\n**\n** The pIter argument passed to this function may either be an iterator\n** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator\n** created by [sqlite3changeset_start()]. In the latter case, the most recent\n** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. \n** Furthermore, it may only be called if the type of change that the iterator\n** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,\n** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.\n**\n** Argument iVal must be greater than or equal to 0, and less than the number\n** of columns in the table affected by the current change. Otherwise,\n** [SQLITE_RANGE] is returned and *ppValue is set to NULL.\n**\n** If successful, this function sets *ppValue to point to a protected\n** sqlite3_value object containing the iVal'th value from the vector of \n** new row values stored as part of the UPDATE or INSERT change and\n** returns SQLITE_OK. If the change is an UPDATE and does not include\n** a new value for the requested column, *ppValue is set to NULL and \n** SQLITE_OK returned. The name of the function comes from the fact that \n** this is similar to the \"new.*\" columns available to update or delete \n** triggers.\n**\n** If some other error occurs (e.g. an OOM condition), an SQLite error code\n** is returned and *ppValue is set to NULL.\n*/\nSQLITE_API int sqlite3changeset_new(\n  sqlite3_changeset_iter *pIter,  /* Changeset iterator */\n  int iVal,                       /* Column number */\n  sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */\n);\n\n/*\n** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator\n** METHOD: sqlite3_changeset_iter\n**\n** This function should only be used with iterator objects passed to a\n** conflict-handler callback by [sqlite3changeset_apply()] with either\n** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function\n** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue\n** is set to NULL.\n**\n** Argument iVal must be greater than or equal to 0, and less than the number\n** of columns in the table affected by the current change. Otherwise,\n** [SQLITE_RANGE] is returned and *ppValue is set to NULL.\n**\n** If successful, this function sets *ppValue to point to a protected\n** sqlite3_value object containing the iVal'th value from the \n** \"conflicting row\" associated with the current conflict-handler callback\n** and returns SQLITE_OK.\n**\n** If some other error occurs (e.g. an OOM condition), an SQLite error code\n** is returned and *ppValue is set to NULL.\n*/\nSQLITE_API int sqlite3changeset_conflict(\n  sqlite3_changeset_iter *pIter,  /* Changeset iterator */\n  int iVal,                       /* Column number */\n  sqlite3_value **ppValue         /* OUT: Value from conflicting row */\n);\n\n/*\n** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations\n** METHOD: sqlite3_changeset_iter\n**\n** This function may only be called with an iterator passed to an\n** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case\n** it sets the output variable to the total number of known foreign key\n** violations in the destination database and returns SQLITE_OK.\n**\n** In all other cases this function returns SQLITE_MISUSE.\n*/\nSQLITE_API int sqlite3changeset_fk_conflicts(\n  sqlite3_changeset_iter *pIter,  /* Changeset iterator */\n  int *pnOut                      /* OUT: Number of FK violations */\n);\n\n\n/*\n** CAPI3REF: Finalize A Changeset Iterator\n** METHOD: sqlite3_changeset_iter\n**\n** This function is used to finalize an iterator allocated with\n** [sqlite3changeset_start()].\n**\n** This function should only be called on iterators created using the\n** [sqlite3changeset_start()] function. If an application calls this\n** function with an iterator passed to a conflict-handler by\n** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the\n** call has no effect.\n**\n** If an error was encountered within a call to an sqlite3changeset_xxx()\n** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an \n** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding\n** to that error is returned by this function. Otherwise, SQLITE_OK is\n** returned. This is to allow the following pattern (pseudo-code):\n**\n** <pre>\n**   sqlite3changeset_start();\n**   while( SQLITE_ROW==sqlite3changeset_next() ){\n**     // Do something with change.\n**   }\n**   rc = sqlite3changeset_finalize();\n**   if( rc!=SQLITE_OK ){\n**     // An error has occurred \n**   }\n** </pre>\n*/\nSQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);\n\n/*\n** CAPI3REF: Invert A Changeset\n**\n** This function is used to \"invert\" a changeset object. Applying an inverted\n** changeset to a database reverses the effects of applying the uninverted\n** changeset. Specifically:\n**\n** <ul>\n**   <li> Each DELETE change is changed to an INSERT, and\n**   <li> Each INSERT change is changed to a DELETE, and\n**   <li> For each UPDATE change, the old.* and new.* values are exchanged.\n** </ul>\n**\n** This function does not change the order in which changes appear within\n** the changeset. It merely reverses the sense of each individual change.\n**\n** If successful, a pointer to a buffer containing the inverted changeset\n** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and\n** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are\n** zeroed and an SQLite error code returned.\n**\n** It is the responsibility of the caller to eventually call sqlite3_free()\n** on the *ppOut pointer to free the buffer allocation following a successful \n** call to this function.\n**\n** WARNING/TODO: This function currently assumes that the input is a valid\n** changeset. If it is not, the results are undefined.\n*/\nSQLITE_API int sqlite3changeset_invert(\n  int nIn, const void *pIn,       /* Input changeset */\n  int *pnOut, void **ppOut        /* OUT: Inverse of input */\n);\n\n/*\n** CAPI3REF: Concatenate Two Changeset Objects\n**\n** This function is used to concatenate two changesets, A and B, into a \n** single changeset. The result is a changeset equivalent to applying\n** changeset A followed by changeset B. \n**\n** This function combines the two input changesets using an \n** sqlite3_changegroup object. Calling it produces similar results as the\n** following code fragment:\n**\n** <pre>\n**   sqlite3_changegroup *pGrp;\n**   rc = sqlite3_changegroup_new(&pGrp);\n**   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);\n**   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);\n**   if( rc==SQLITE_OK ){\n**     rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);\n**   }else{\n**     *ppOut = 0;\n**     *pnOut = 0;\n**   }\n** </pre>\n**\n** Refer to the sqlite3_changegroup documentation below for details.\n*/\nSQLITE_API int sqlite3changeset_concat(\n  int nA,                         /* Number of bytes in buffer pA */\n  void *pA,                       /* Pointer to buffer containing changeset A */\n  int nB,                         /* Number of bytes in buffer pB */\n  void *pB,                       /* Pointer to buffer containing changeset B */\n  int *pnOut,                     /* OUT: Number of bytes in output changeset */\n  void **ppOut                    /* OUT: Buffer containing output changeset */\n);\n\n\n/*\n** CAPI3REF: Changegroup Handle\n**\n** A changegroup is an object used to combine two or more \n** [changesets] or [patchsets]\n*/\ntypedef struct sqlite3_changegroup sqlite3_changegroup;\n\n/*\n** CAPI3REF: Create A New Changegroup Object\n** CONSTRUCTOR: sqlite3_changegroup\n**\n** An sqlite3_changegroup object is used to combine two or more changesets\n** (or patchsets) into a single changeset (or patchset). A single changegroup\n** object may combine changesets or patchsets, but not both. The output is\n** always in the same format as the input.\n**\n** If successful, this function returns SQLITE_OK and populates (*pp) with\n** a pointer to a new sqlite3_changegroup object before returning. The caller\n** should eventually free the returned object using a call to \n** sqlite3changegroup_delete(). If an error occurs, an SQLite error code\n** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.\n**\n** The usual usage pattern for an sqlite3_changegroup object is as follows:\n**\n** <ul>\n**   <li> It is created using a call to sqlite3changegroup_new().\n**\n**   <li> Zero or more changesets (or patchsets) are added to the object\n**        by calling sqlite3changegroup_add().\n**\n**   <li> The result of combining all input changesets together is obtained \n**        by the application via a call to sqlite3changegroup_output().\n**\n**   <li> The object is deleted using a call to sqlite3changegroup_delete().\n** </ul>\n**\n** Any number of calls to add() and output() may be made between the calls to\n** new() and delete(), and in any order.\n**\n** As well as the regular sqlite3changegroup_add() and \n** sqlite3changegroup_output() functions, also available are the streaming\n** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().\n*/\nSQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);\n\n/*\n** CAPI3REF: Add A Changeset To A Changegroup\n** METHOD: sqlite3_changegroup\n**\n** Add all changes within the changeset (or patchset) in buffer pData (size\n** nData bytes) to the changegroup. \n**\n** If the buffer contains a patchset, then all prior calls to this function\n** on the same changegroup object must also have specified patchsets. Or, if\n** the buffer contains a changeset, so must have the earlier calls to this\n** function. Otherwise, SQLITE_ERROR is returned and no changes are added\n** to the changegroup.\n**\n** Rows within the changeset and changegroup are identified by the values in\n** their PRIMARY KEY columns. A change in the changeset is considered to\n** apply to the same row as a change already present in the changegroup if\n** the two rows have the same primary key.\n**\n** Changes to rows that do not already appear in the changegroup are\n** simply copied into it. Or, if both the new changeset and the changegroup\n** contain changes that apply to a single row, the final contents of the\n** changegroup depends on the type of each change, as follows:\n**\n** <table border=1 style=\"margin-left:8ex;margin-right:8ex\">\n**   <tr><th style=\"white-space:pre\">Existing Change  </th>\n**       <th style=\"white-space:pre\">New Change       </th>\n**       <th>Output Change\n**   <tr><td>INSERT <td>INSERT <td>\n**       The new change is ignored. This case does not occur if the new\n**       changeset was recorded immediately after the changesets already\n**       added to the changegroup.\n**   <tr><td>INSERT <td>UPDATE <td>\n**       The INSERT change remains in the changegroup. The values in the \n**       INSERT change are modified as if the row was inserted by the\n**       existing change and then updated according to the new change.\n**   <tr><td>INSERT <td>DELETE <td>\n**       The existing INSERT is removed from the changegroup. The DELETE is\n**       not added.\n**   <tr><td>UPDATE <td>INSERT <td>\n**       The new change is ignored. This case does not occur if the new\n**       changeset was recorded immediately after the changesets already\n**       added to the changegroup.\n**   <tr><td>UPDATE <td>UPDATE <td>\n**       The existing UPDATE remains within the changegroup. It is amended \n**       so that the accompanying values are as if the row was updated once \n**       by the existing change and then again by the new change.\n**   <tr><td>UPDATE <td>DELETE <td>\n**       The existing UPDATE is replaced by the new DELETE within the\n**       changegroup.\n**   <tr><td>DELETE <td>INSERT <td>\n**       If one or more of the column values in the row inserted by the\n**       new change differ from those in the row deleted by the existing \n**       change, the existing DELETE is replaced by an UPDATE within the\n**       changegroup. Otherwise, if the inserted row is exactly the same \n**       as the deleted row, the existing DELETE is simply discarded.\n**   <tr><td>DELETE <td>UPDATE <td>\n**       The new change is ignored. This case does not occur if the new\n**       changeset was recorded immediately after the changesets already\n**       added to the changegroup.\n**   <tr><td>DELETE <td>DELETE <td>\n**       The new change is ignored. This case does not occur if the new\n**       changeset was recorded immediately after the changesets already\n**       added to the changegroup.\n** </table>\n**\n** If the new changeset contains changes to a table that is already present\n** in the changegroup, then the number of columns and the position of the\n** primary key columns for the table must be consistent. If this is not the\n** case, this function fails with SQLITE_SCHEMA. If the input changeset\n** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is\n** returned. Or, if an out-of-memory condition occurs during processing, this\n** function returns SQLITE_NOMEM. In all cases, if an error occurs the state\n** of the final contents of the changegroup is undefined.\n**\n** If no error occurs, SQLITE_OK is returned.\n*/\nSQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);\n\n/*\n** CAPI3REF: Obtain A Composite Changeset From A Changegroup\n** METHOD: sqlite3_changegroup\n**\n** Obtain a buffer containing a changeset (or patchset) representing the\n** current contents of the changegroup. If the inputs to the changegroup\n** were themselves changesets, the output is a changeset. Or, if the\n** inputs were patchsets, the output is also a patchset.\n**\n** As with the output of the sqlite3session_changeset() and\n** sqlite3session_patchset() functions, all changes related to a single\n** table are grouped together in the output of this function. Tables appear\n** in the same order as for the very first changeset added to the changegroup.\n** If the second or subsequent changesets added to the changegroup contain\n** changes for tables that do not appear in the first changeset, they are\n** appended onto the end of the output changeset, again in the order in\n** which they are first encountered.\n**\n** If an error occurs, an SQLite error code is returned and the output\n** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK\n** is returned and the output variables are set to the size of and a \n** pointer to the output buffer, respectively. In this case it is the\n** responsibility of the caller to eventually free the buffer using a\n** call to sqlite3_free().\n*/\nSQLITE_API int sqlite3changegroup_output(\n  sqlite3_changegroup*,\n  int *pnData,                    /* OUT: Size of output buffer in bytes */\n  void **ppData                   /* OUT: Pointer to output buffer */\n);\n\n/*\n** CAPI3REF: Delete A Changegroup Object\n** DESTRUCTOR: sqlite3_changegroup\n*/\nSQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);\n\n/*\n** CAPI3REF: Apply A Changeset To A Database\n**\n** Apply a changeset or patchset to a database. These functions attempt to\n** update the \"main\" database attached to handle db with the changes found in\n** the changeset passed via the second and third arguments. \n**\n** The fourth argument (xFilter) passed to these functions is the \"filter\n** callback\". If it is not NULL, then for each table affected by at least one\n** change in the changeset, the filter callback is invoked with\n** the table name as the second argument, and a copy of the context pointer\n** passed as the sixth argument as the first. If the \"filter callback\"\n** returns zero, then no attempt is made to apply any changes to the table.\n** Otherwise, if the return value is non-zero or the xFilter argument to\n** is NULL, all changes related to the table are attempted.\n**\n** For each table that is not excluded by the filter callback, this function \n** tests that the target database contains a compatible table. A table is \n** considered compatible if all of the following are true:\n**\n** <ul>\n**   <li> The table has the same name as the name recorded in the \n**        changeset, and\n**   <li> The table has at least as many columns as recorded in the \n**        changeset, and\n**   <li> The table has primary key columns in the same position as \n**        recorded in the changeset.\n** </ul>\n**\n** If there is no compatible table, it is not an error, but none of the\n** changes associated with the table are applied. A warning message is issued\n** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most\n** one such warning is issued for each table in the changeset.\n**\n** For each change for which there is a compatible table, an attempt is made \n** to modify the table contents according to the UPDATE, INSERT or DELETE \n** change. If a change cannot be applied cleanly, the conflict handler \n** function passed as the fifth argument to sqlite3changeset_apply() may be \n** invoked. A description of exactly when the conflict handler is invoked for \n** each type of change is below.\n**\n** Unlike the xFilter argument, xConflict may not be passed NULL. The results\n** of passing anything other than a valid function pointer as the xConflict\n** argument are undefined.\n**\n** Each time the conflict handler function is invoked, it must return one\n** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or \n** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned\n** if the second argument passed to the conflict handler is either\n** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler\n** returns an illegal value, any changes already made are rolled back and\n** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different \n** actions are taken by sqlite3changeset_apply() depending on the value\n** returned by each invocation of the conflict-handler function. Refer to\n** the documentation for the three \n** [SQLITE_CHANGESET_OMIT|available return values] for details.\n**\n** <dl>\n** <dt>DELETE Changes<dd>\n**   For each DELETE change, the function checks if the target database \n**   contains a row with the same primary key value (or values) as the \n**   original row values stored in the changeset. If it does, and the values \n**   stored in all non-primary key columns also match the values stored in \n**   the changeset the row is deleted from the target database.\n**\n**   If a row with matching primary key values is found, but one or more of\n**   the non-primary key fields contains a value different from the original\n**   row value stored in the changeset, the conflict-handler function is\n**   invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the\n**   database table has more columns than are recorded in the changeset,\n**   only the values of those non-primary key fields are compared against\n**   the current database contents - any trailing database table columns\n**   are ignored.\n**\n**   If no row with matching primary key values is found in the database,\n**   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]\n**   passed as the second argument.\n**\n**   If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT\n**   (which can only happen if a foreign key constraint is violated), the\n**   conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]\n**   passed as the second argument. This includes the case where the DELETE\n**   operation is attempted because an earlier call to the conflict handler\n**   function returned [SQLITE_CHANGESET_REPLACE].\n**\n** <dt>INSERT Changes<dd>\n**   For each INSERT change, an attempt is made to insert the new row into\n**   the database. If the changeset row contains fewer fields than the\n**   database table, the trailing fields are populated with their default\n**   values.\n**\n**   If the attempt to insert the row fails because the database already \n**   contains a row with the same primary key values, the conflict handler\n**   function is invoked with the second argument set to \n**   [SQLITE_CHANGESET_CONFLICT].\n**\n**   If the attempt to insert the row fails because of some other constraint\n**   violation (e.g. NOT NULL or UNIQUE), the conflict handler function is \n**   invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].\n**   This includes the case where the INSERT operation is re-attempted because \n**   an earlier call to the conflict handler function returned \n**   [SQLITE_CHANGESET_REPLACE].\n**\n** <dt>UPDATE Changes<dd>\n**   For each UPDATE change, the function checks if the target database \n**   contains a row with the same primary key value (or values) as the \n**   original row values stored in the changeset. If it does, and the values \n**   stored in all modified non-primary key columns also match the values\n**   stored in the changeset the row is updated within the target database.\n**\n**   If a row with matching primary key values is found, but one or more of\n**   the modified non-primary key fields contains a value different from an\n**   original row value stored in the changeset, the conflict-handler function\n**   is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since\n**   UPDATE changes only contain values for non-primary key fields that are\n**   to be modified, only those fields need to match the original values to\n**   avoid the SQLITE_CHANGESET_DATA conflict-handler callback.\n**\n**   If no row with matching primary key values is found in the database,\n**   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]\n**   passed as the second argument.\n**\n**   If the UPDATE operation is attempted, but SQLite returns \n**   SQLITE_CONSTRAINT, the conflict-handler function is invoked with \n**   [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.\n**   This includes the case where the UPDATE operation is attempted after \n**   an earlier call to the conflict handler function returned\n**   [SQLITE_CHANGESET_REPLACE].  \n** </dl>\n**\n** It is safe to execute SQL statements, including those that write to the\n** table that the callback related to, from within the xConflict callback.\n** This can be used to further customize the application's conflict\n** resolution strategy.\n**\n** All changes made by these functions are enclosed in a savepoint transaction.\n** If any other error (aside from a constraint failure when attempting to\n** write to the target database) occurs, then the savepoint transaction is\n** rolled back, restoring the target database to its original state, and an \n** SQLite error code returned.\n**\n** If the output parameters (ppRebase) and (pnRebase) are non-NULL and\n** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()\n** may set (*ppRebase) to point to a \"rebase\" that may be used with the \n** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)\n** is set to the size of the buffer in bytes. It is the responsibility of the\n** caller to eventually free any such buffer using sqlite3_free(). The buffer\n** is only allocated and populated if one or more conflicts were encountered\n** while applying the patchset. See comments surrounding the sqlite3_rebaser\n** APIs for further details.\n**\n** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent\n** may be modified by passing a combination of\n** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter.\n**\n** Note that the sqlite3changeset_apply_v2() API is still <b>experimental</b>\n** and therefore subject to change.\n*/\nSQLITE_API int sqlite3changeset_apply(\n  sqlite3 *db,                    /* Apply change to \"main\" db of this handle */\n  int nChangeset,                 /* Size of changeset in bytes */\n  void *pChangeset,               /* Changeset blob */\n  int(*xFilter)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    const char *zTab              /* Table name */\n  ),\n  int(*xConflict)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */\n    sqlite3_changeset_iter *p     /* Handle describing change and conflict */\n  ),\n  void *pCtx                      /* First argument passed to xConflict */\n);\nSQLITE_API int sqlite3changeset_apply_v2(\n  sqlite3 *db,                    /* Apply change to \"main\" db of this handle */\n  int nChangeset,                 /* Size of changeset in bytes */\n  void *pChangeset,               /* Changeset blob */\n  int(*xFilter)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    const char *zTab              /* Table name */\n  ),\n  int(*xConflict)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */\n    sqlite3_changeset_iter *p     /* Handle describing change and conflict */\n  ),\n  void *pCtx,                     /* First argument passed to xConflict */\n  void **ppRebase, int *pnRebase, /* OUT: Rebase data */\n  int flags                       /* SESSION_CHANGESETAPPLY_* flags */\n);\n\n/*\n** CAPI3REF: Flags for sqlite3changeset_apply_v2\n**\n** The following flags may passed via the 9th parameter to\n** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:\n**\n** <dl>\n** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd>\n**   Usually, the sessions module encloses all operations performed by\n**   a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The\n**   SAVEPOINT is committed if the changeset or patchset is successfully\n**   applied, or rolled back if an error occurs. Specifying this flag\n**   causes the sessions module to omit this savepoint. In this case, if the\n**   caller has an open transaction or savepoint when apply_v2() is called, \n**   it may revert the partially applied changeset by rolling it back.\n**\n** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>\n**   Invert the changeset before applying it. This is equivalent to inverting\n**   a changeset using sqlite3changeset_invert() before applying it. It is\n**   an error to specify this flag with a patchset.\n*/\n#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT   0x0001\n#define SQLITE_CHANGESETAPPLY_INVERT        0x0002\n\n/* \n** CAPI3REF: Constants Passed To The Conflict Handler\n**\n** Values that may be passed as the second argument to a conflict-handler.\n**\n** <dl>\n** <dt>SQLITE_CHANGESET_DATA<dd>\n**   The conflict handler is invoked with CHANGESET_DATA as the second argument\n**   when processing a DELETE or UPDATE change if a row with the required\n**   PRIMARY KEY fields is present in the database, but one or more other \n**   (non primary-key) fields modified by the update do not contain the \n**   expected \"before\" values.\n** \n**   The conflicting row, in this case, is the database row with the matching\n**   primary key.\n** \n** <dt>SQLITE_CHANGESET_NOTFOUND<dd>\n**   The conflict handler is invoked with CHANGESET_NOTFOUND as the second\n**   argument when processing a DELETE or UPDATE change if a row with the\n**   required PRIMARY KEY fields is not present in the database.\n** \n**   There is no conflicting row in this case. The results of invoking the\n**   sqlite3changeset_conflict() API are undefined.\n** \n** <dt>SQLITE_CHANGESET_CONFLICT<dd>\n**   CHANGESET_CONFLICT is passed as the second argument to the conflict\n**   handler while processing an INSERT change if the operation would result \n**   in duplicate primary key values.\n** \n**   The conflicting row in this case is the database row with the matching\n**   primary key.\n**\n** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>\n**   If foreign key handling is enabled, and applying a changeset leaves the\n**   database in a state containing foreign key violations, the conflict \n**   handler is invoked with CHANGESET_FOREIGN_KEY as the second argument\n**   exactly once before the changeset is committed. If the conflict handler\n**   returns CHANGESET_OMIT, the changes, including those that caused the\n**   foreign key constraint violation, are committed. Or, if it returns\n**   CHANGESET_ABORT, the changeset is rolled back.\n**\n**   No current or conflicting row information is provided. The only function\n**   it is possible to call on the supplied sqlite3_changeset_iter handle\n**   is sqlite3changeset_fk_conflicts().\n** \n** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>\n**   If any other constraint violation occurs while applying a change (i.e. \n**   a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is \n**   invoked with CHANGESET_CONSTRAINT as the second argument.\n** \n**   There is no conflicting row in this case. The results of invoking the\n**   sqlite3changeset_conflict() API are undefined.\n**\n** </dl>\n*/\n#define SQLITE_CHANGESET_DATA        1\n#define SQLITE_CHANGESET_NOTFOUND    2\n#define SQLITE_CHANGESET_CONFLICT    3\n#define SQLITE_CHANGESET_CONSTRAINT  4\n#define SQLITE_CHANGESET_FOREIGN_KEY 5\n\n/* \n** CAPI3REF: Constants Returned By The Conflict Handler\n**\n** A conflict handler callback must return one of the following three values.\n**\n** <dl>\n** <dt>SQLITE_CHANGESET_OMIT<dd>\n**   If a conflict handler returns this value no special action is taken. The\n**   change that caused the conflict is not applied. The session module \n**   continues to the next change in the changeset.\n**\n** <dt>SQLITE_CHANGESET_REPLACE<dd>\n**   This value may only be returned if the second argument to the conflict\n**   handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this\n**   is not the case, any changes applied so far are rolled back and the \n**   call to sqlite3changeset_apply() returns SQLITE_MISUSE.\n**\n**   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict\n**   handler, then the conflicting row is either updated or deleted, depending\n**   on the type of change.\n**\n**   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict\n**   handler, then the conflicting row is removed from the database and a\n**   second attempt to apply the change is made. If this second attempt fails,\n**   the original row is restored to the database before continuing.\n**\n** <dt>SQLITE_CHANGESET_ABORT<dd>\n**   If this value is returned, any changes applied so far are rolled back \n**   and the call to sqlite3changeset_apply() returns SQLITE_ABORT.\n** </dl>\n*/\n#define SQLITE_CHANGESET_OMIT       0\n#define SQLITE_CHANGESET_REPLACE    1\n#define SQLITE_CHANGESET_ABORT      2\n\n/* \n** CAPI3REF: Rebasing changesets\n** EXPERIMENTAL\n**\n** Suppose there is a site hosting a database in state S0. And that\n** modifications are made that move that database to state S1 and a\n** changeset recorded (the \"local\" changeset). Then, a changeset based\n** on S0 is received from another site (the \"remote\" changeset) and \n** applied to the database. The database is then in state \n** (S1+\"remote\"), where the exact state depends on any conflict\n** resolution decisions (OMIT or REPLACE) made while applying \"remote\".\n** Rebasing a changeset is to update it to take those conflict \n** resolution decisions into account, so that the same conflicts\n** do not have to be resolved elsewhere in the network. \n**\n** For example, if both the local and remote changesets contain an\n** INSERT of the same key on \"CREATE TABLE t1(a PRIMARY KEY, b)\":\n**\n**   local:  INSERT INTO t1 VALUES(1, 'v1');\n**   remote: INSERT INTO t1 VALUES(1, 'v2');\n**\n** and the conflict resolution is REPLACE, then the INSERT change is\n** removed from the local changeset (it was overridden). Or, if the\n** conflict resolution was \"OMIT\", then the local changeset is modified\n** to instead contain:\n**\n**           UPDATE t1 SET b = 'v2' WHERE a=1;\n**\n** Changes within the local changeset are rebased as follows:\n**\n** <dl>\n** <dt>Local INSERT<dd>\n**   This may only conflict with a remote INSERT. If the conflict \n**   resolution was OMIT, then add an UPDATE change to the rebased\n**   changeset. Or, if the conflict resolution was REPLACE, add\n**   nothing to the rebased changeset.\n**\n** <dt>Local DELETE<dd>\n**   This may conflict with a remote UPDATE or DELETE. In both cases the\n**   only possible resolution is OMIT. If the remote operation was a\n**   DELETE, then add no change to the rebased changeset. If the remote\n**   operation was an UPDATE, then the old.* fields of change are updated\n**   to reflect the new.* values in the UPDATE.\n**\n** <dt>Local UPDATE<dd>\n**   This may conflict with a remote UPDATE or DELETE. If it conflicts\n**   with a DELETE, and the conflict resolution was OMIT, then the update\n**   is changed into an INSERT. Any undefined values in the new.* record\n**   from the update change are filled in using the old.* values from\n**   the conflicting DELETE. Or, if the conflict resolution was REPLACE,\n**   the UPDATE change is simply omitted from the rebased changeset.\n**\n**   If conflict is with a remote UPDATE and the resolution is OMIT, then\n**   the old.* values are rebased using the new.* values in the remote\n**   change. Or, if the resolution is REPLACE, then the change is copied\n**   into the rebased changeset with updates to columns also updated by\n**   the conflicting remote UPDATE removed. If this means no columns would \n**   be updated, the change is omitted.\n** </dl>\n**\n** A local change may be rebased against multiple remote changes \n** simultaneously. If a single key is modified by multiple remote \n** changesets, they are combined as follows before the local changeset\n** is rebased:\n**\n** <ul>\n**    <li> If there has been one or more REPLACE resolutions on a\n**         key, it is rebased according to a REPLACE.\n**\n**    <li> If there have been no REPLACE resolutions on a key, then\n**         the local changeset is rebased according to the most recent\n**         of the OMIT resolutions.\n** </ul>\n**\n** Note that conflict resolutions from multiple remote changesets are \n** combined on a per-field basis, not per-row. This means that in the \n** case of multiple remote UPDATE operations, some fields of a single \n** local change may be rebased for REPLACE while others are rebased for \n** OMIT.\n**\n** In order to rebase a local changeset, the remote changeset must first\n** be applied to the local database using sqlite3changeset_apply_v2() and\n** the buffer of rebase information captured. Then:\n**\n** <ol>\n**   <li> An sqlite3_rebaser object is created by calling \n**        sqlite3rebaser_create().\n**   <li> The new object is configured with the rebase buffer obtained from\n**        sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().\n**        If the local changeset is to be rebased against multiple remote\n**        changesets, then sqlite3rebaser_configure() should be called\n**        multiple times, in the same order that the multiple\n**        sqlite3changeset_apply_v2() calls were made.\n**   <li> Each local changeset is rebased by calling sqlite3rebaser_rebase().\n**   <li> The sqlite3_rebaser object is deleted by calling\n**        sqlite3rebaser_delete().\n** </ol>\n*/\ntypedef struct sqlite3_rebaser sqlite3_rebaser;\n\n/*\n** CAPI3REF: Create a changeset rebaser object.\n** EXPERIMENTAL\n**\n** Allocate a new changeset rebaser object. If successful, set (*ppNew) to\n** point to the new object and return SQLITE_OK. Otherwise, if an error\n** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew) \n** to NULL. \n*/\nSQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);\n\n/*\n** CAPI3REF: Configure a changeset rebaser object.\n** EXPERIMENTAL\n**\n** Configure the changeset rebaser object to rebase changesets according\n** to the conflict resolutions described by buffer pRebase (size nRebase\n** bytes), which must have been obtained from a previous call to\n** sqlite3changeset_apply_v2().\n*/\nSQLITE_API int sqlite3rebaser_configure(\n  sqlite3_rebaser*, \n  int nRebase, const void *pRebase\n); \n\n/*\n** CAPI3REF: Rebase a changeset\n** EXPERIMENTAL\n**\n** Argument pIn must point to a buffer containing a changeset nIn bytes\n** in size. This function allocates and populates a buffer with a copy\n** of the changeset rebased according to the configuration of the\n** rebaser object passed as the first argument. If successful, (*ppOut)\n** is set to point to the new buffer containing the rebased changeset and \n** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the\n** responsibility of the caller to eventually free the new buffer using\n** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)\n** are set to zero and an SQLite error code returned.\n*/\nSQLITE_API int sqlite3rebaser_rebase(\n  sqlite3_rebaser*,\n  int nIn, const void *pIn, \n  int *pnOut, void **ppOut \n);\n\n/*\n** CAPI3REF: Delete a changeset rebaser object.\n** EXPERIMENTAL\n**\n** Delete the changeset rebaser object and all associated resources. There\n** should be one call to this function for each successful invocation\n** of sqlite3rebaser_create().\n*/\nSQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p); \n\n/*\n** CAPI3REF: Streaming Versions of API functions.\n**\n** The six streaming API xxx_strm() functions serve similar purposes to the \n** corresponding non-streaming API functions:\n**\n** <table border=1 style=\"margin-left:8ex;margin-right:8ex\">\n**   <tr><th>Streaming function<th>Non-streaming equivalent</th>\n**   <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply] \n**   <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2] \n**   <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat] \n**   <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert] \n**   <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start] \n**   <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset] \n**   <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset] \n** </table>\n**\n** Non-streaming functions that accept changesets (or patchsets) as input\n** require that the entire changeset be stored in a single buffer in memory. \n** Similarly, those that return a changeset or patchset do so by returning \n** a pointer to a single large buffer allocated using sqlite3_malloc(). \n** Normally this is convenient. However, if an application running in a \n** low-memory environment is required to handle very large changesets, the\n** large contiguous memory allocations required can become onerous.\n**\n** In order to avoid this problem, instead of a single large buffer, input\n** is passed to a streaming API functions by way of a callback function that\n** the sessions module invokes to incrementally request input data as it is\n** required. In all cases, a pair of API function parameters such as\n**\n**  <pre>\n**  &nbsp;     int nChangeset,\n**  &nbsp;     void *pChangeset,\n**  </pre>\n**\n** Is replaced by:\n**\n**  <pre>\n**  &nbsp;     int (*xInput)(void *pIn, void *pData, int *pnData),\n**  &nbsp;     void *pIn,\n**  </pre>\n**\n** Each time the xInput callback is invoked by the sessions module, the first\n** argument passed is a copy of the supplied pIn context pointer. The second \n** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no \n** error occurs the xInput method should copy up to (*pnData) bytes of data \n** into the buffer and set (*pnData) to the actual number of bytes copied \n** before returning SQLITE_OK. If the input is completely exhausted, (*pnData) \n** should be set to zero to indicate this. Or, if an error occurs, an SQLite \n** error code should be returned. In all cases, if an xInput callback returns\n** an error, all processing is abandoned and the streaming API function\n** returns a copy of the error code to the caller.\n**\n** In the case of sqlite3changeset_start_strm(), the xInput callback may be\n** invoked by the sessions module at any point during the lifetime of the\n** iterator. If such an xInput callback returns an error, the iterator enters\n** an error state, whereby all subsequent calls to iterator functions \n** immediately fail with the same error code as returned by xInput.\n**\n** Similarly, streaming API functions that return changesets (or patchsets)\n** return them in chunks by way of a callback function instead of via a\n** pointer to a single large buffer. In this case, a pair of parameters such\n** as:\n**\n**  <pre>\n**  &nbsp;     int *pnChangeset,\n**  &nbsp;     void **ppChangeset,\n**  </pre>\n**\n** Is replaced by:\n**\n**  <pre>\n**  &nbsp;     int (*xOutput)(void *pOut, const void *pData, int nData),\n**  &nbsp;     void *pOut\n**  </pre>\n**\n** The xOutput callback is invoked zero or more times to return data to\n** the application. The first parameter passed to each call is a copy of the\n** pOut pointer supplied by the application. The second parameter, pData,\n** points to a buffer nData bytes in size containing the chunk of output\n** data being returned. If the xOutput callback successfully processes the\n** supplied data, it should return SQLITE_OK to indicate success. Otherwise,\n** it should return some other SQLite error code. In this case processing\n** is immediately abandoned and the streaming API function returns a copy\n** of the xOutput error code to the application.\n**\n** The sessions module never invokes an xOutput callback with the third \n** parameter set to a value less than or equal to zero. Other than this,\n** no guarantees are made as to the size of the chunks of data returned.\n*/\nSQLITE_API int sqlite3changeset_apply_strm(\n  sqlite3 *db,                    /* Apply change to \"main\" db of this handle */\n  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */\n  void *pIn,                                          /* First arg for xInput */\n  int(*xFilter)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    const char *zTab              /* Table name */\n  ),\n  int(*xConflict)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */\n    sqlite3_changeset_iter *p     /* Handle describing change and conflict */\n  ),\n  void *pCtx                      /* First argument passed to xConflict */\n);\nSQLITE_API int sqlite3changeset_apply_v2_strm(\n  sqlite3 *db,                    /* Apply change to \"main\" db of this handle */\n  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */\n  void *pIn,                                          /* First arg for xInput */\n  int(*xFilter)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    const char *zTab              /* Table name */\n  ),\n  int(*xConflict)(\n    void *pCtx,                   /* Copy of sixth arg to _apply() */\n    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */\n    sqlite3_changeset_iter *p     /* Handle describing change and conflict */\n  ),\n  void *pCtx,                     /* First argument passed to xConflict */\n  void **ppRebase, int *pnRebase,\n  int flags\n);\nSQLITE_API int sqlite3changeset_concat_strm(\n  int (*xInputA)(void *pIn, void *pData, int *pnData),\n  void *pInA,\n  int (*xInputB)(void *pIn, void *pData, int *pnData),\n  void *pInB,\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut\n);\nSQLITE_API int sqlite3changeset_invert_strm(\n  int (*xInput)(void *pIn, void *pData, int *pnData),\n  void *pIn,\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut\n);\nSQLITE_API int sqlite3changeset_start_strm(\n  sqlite3_changeset_iter **pp,\n  int (*xInput)(void *pIn, void *pData, int *pnData),\n  void *pIn\n);\nSQLITE_API int sqlite3changeset_start_v2_strm(\n  sqlite3_changeset_iter **pp,\n  int (*xInput)(void *pIn, void *pData, int *pnData),\n  void *pIn,\n  int flags\n);\nSQLITE_API int sqlite3session_changeset_strm(\n  sqlite3_session *pSession,\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut\n);\nSQLITE_API int sqlite3session_patchset_strm(\n  sqlite3_session *pSession,\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut\n);\nSQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*, \n    int (*xInput)(void *pIn, void *pData, int *pnData),\n    void *pIn\n);\nSQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,\n    int (*xOutput)(void *pOut, const void *pData, int nData), \n    void *pOut\n);\nSQLITE_API int sqlite3rebaser_rebase_strm(\n  sqlite3_rebaser *pRebaser,\n  int (*xInput)(void *pIn, void *pData, int *pnData),\n  void *pIn,\n  int (*xOutput)(void *pOut, const void *pData, int nData),\n  void *pOut\n);\n\n/*\n** CAPI3REF: Configure global parameters\n**\n** The sqlite3session_config() interface is used to make global configuration\n** changes to the sessions module in order to tune it to the specific needs \n** of the application.\n**\n** The sqlite3session_config() interface is not threadsafe. If it is invoked\n** while any other thread is inside any other sessions method then the\n** results are undefined. Furthermore, if it is invoked after any sessions\n** related objects have been created, the results are also undefined. \n**\n** The first argument to the sqlite3session_config() function must be one\n** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The \n** interpretation of the (void*) value passed as the second parameter and\n** the effect of calling this function depends on the value of the first\n** parameter.\n**\n** <dl>\n** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd>\n**    By default, the sessions module streaming interfaces attempt to input\n**    and output data in approximately 1 KiB chunks. This operand may be used\n**    to set and query the value of this configuration setting. The pointer\n**    passed as the second argument must point to a value of type (int).\n**    If this value is greater than 0, it is used as the new streaming data\n**    chunk size for both input and output. Before returning, the (int) value\n**    pointed to by pArg is set to the final value of the streaming interface\n**    chunk size.\n** </dl>\n**\n** This function returns SQLITE_OK if successful, or an SQLite error code\n** otherwise.\n*/\nSQLITE_API int sqlite3session_config(int op, void *pArg);\n\n/*\n** CAPI3REF: Values for sqlite3session_config().\n*/\n#define SQLITE_SESSION_CONFIG_STRMSIZE 1\n\n/*\n** Make sure we can call this stuff from C++.\n*/\n#ifdef __cplusplus\n}\n#endif\n\n#endif  /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */\n\n/******** End of sqlite3session.h *********/\n/******** Begin file fts5.h *********/\n/*\n** 2014 May 31\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** Interfaces to extend FTS5. Using the interfaces defined in this file, \n** FTS5 may be extended with:\n**\n**     * custom tokenizers, and\n**     * custom auxiliary functions.\n*/\n\n\n#ifndef _FTS5_H\n#define _FTS5_H\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*************************************************************************\n** CUSTOM AUXILIARY FUNCTIONS\n**\n** Virtual table implementations may overload SQL functions by implementing\n** the sqlite3_module.xFindFunction() method.\n*/\n\ntypedef struct Fts5ExtensionApi Fts5ExtensionApi;\ntypedef struct Fts5Context Fts5Context;\ntypedef struct Fts5PhraseIter Fts5PhraseIter;\n\ntypedef void (*fts5_extension_function)(\n  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */\n  Fts5Context *pFts,              /* First arg to pass to pApi functions */\n  sqlite3_context *pCtx,          /* Context for returning result/error */\n  int nVal,                       /* Number of values in apVal[] array */\n  sqlite3_value **apVal           /* Array of trailing arguments */\n);\n\nstruct Fts5PhraseIter {\n  const unsigned char *a;\n  const unsigned char *b;\n};\n\n/*\n** EXTENSION API FUNCTIONS\n**\n** xUserData(pFts):\n**   Return a copy of the context pointer the extension function was \n**   registered with.\n**\n** xColumnTotalSize(pFts, iCol, pnToken):\n**   If parameter iCol is less than zero, set output variable *pnToken\n**   to the total number of tokens in the FTS5 table. Or, if iCol is\n**   non-negative but less than the number of columns in the table, return\n**   the total number of tokens in column iCol, considering all rows in \n**   the FTS5 table.\n**\n**   If parameter iCol is greater than or equal to the number of columns\n**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.\n**   an OOM condition or IO error), an appropriate SQLite error code is \n**   returned.\n**\n** xColumnCount(pFts):\n**   Return the number of columns in the table.\n**\n** xColumnSize(pFts, iCol, pnToken):\n**   If parameter iCol is less than zero, set output variable *pnToken\n**   to the total number of tokens in the current row. Or, if iCol is\n**   non-negative but less than the number of columns in the table, set\n**   *pnToken to the number of tokens in column iCol of the current row.\n**\n**   If parameter iCol is greater than or equal to the number of columns\n**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.\n**   an OOM condition or IO error), an appropriate SQLite error code is \n**   returned.\n**\n**   This function may be quite inefficient if used with an FTS5 table\n**   created with the \"columnsize=0\" option.\n**\n** xColumnText:\n**   This function attempts to retrieve the text of column iCol of the\n**   current document. If successful, (*pz) is set to point to a buffer\n**   containing the text in utf-8 encoding, (*pn) is set to the size in bytes\n**   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,\n**   if an error occurs, an SQLite error code is returned and the final values\n**   of (*pz) and (*pn) are undefined.\n**\n** xPhraseCount:\n**   Returns the number of phrases in the current query expression.\n**\n** xPhraseSize:\n**   Returns the number of tokens in phrase iPhrase of the query. Phrases\n**   are numbered starting from zero.\n**\n** xInstCount:\n**   Set *pnInst to the total number of occurrences of all phrases within\n**   the query within the current row. Return SQLITE_OK if successful, or\n**   an error code (i.e. SQLITE_NOMEM) if an error occurs.\n**\n**   This API can be quite slow if used with an FTS5 table created with the\n**   \"detail=none\" or \"detail=column\" option. If the FTS5 table is created \n**   with either \"detail=none\" or \"detail=column\" and \"content=\" option \n**   (i.e. if it is a contentless table), then this API always returns 0.\n**\n** xInst:\n**   Query for the details of phrase match iIdx within the current row.\n**   Phrase matches are numbered starting from zero, so the iIdx argument\n**   should be greater than or equal to zero and smaller than the value\n**   output by xInstCount().\n**\n**   Usually, output parameter *piPhrase is set to the phrase number, *piCol\n**   to the column in which it occurs and *piOff the token offset of the\n**   first token of the phrase. Returns SQLITE_OK if successful, or an error\n**   code (i.e. SQLITE_NOMEM) if an error occurs.\n**\n**   This API can be quite slow if used with an FTS5 table created with the\n**   \"detail=none\" or \"detail=column\" option. \n**\n** xRowid:\n**   Returns the rowid of the current row.\n**\n** xTokenize:\n**   Tokenize text using the tokenizer belonging to the FTS5 table.\n**\n** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):\n**   This API function is used to query the FTS table for phrase iPhrase\n**   of the current query. Specifically, a query equivalent to:\n**\n**       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid\n**\n**   with $p set to a phrase equivalent to the phrase iPhrase of the\n**   current query is executed. Any column filter that applies to\n**   phrase iPhrase of the current query is included in $p. For each \n**   row visited, the callback function passed as the fourth argument \n**   is invoked. The context and API objects passed to the callback \n**   function may be used to access the properties of each matched row.\n**   Invoking Api.xUserData() returns a copy of the pointer passed as \n**   the third argument to pUserData.\n**\n**   If the callback function returns any value other than SQLITE_OK, the\n**   query is abandoned and the xQueryPhrase function returns immediately.\n**   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.\n**   Otherwise, the error code is propagated upwards.\n**\n**   If the query runs to completion without incident, SQLITE_OK is returned.\n**   Or, if some error occurs before the query completes or is aborted by\n**   the callback, an SQLite error code is returned.\n**\n**\n** xSetAuxdata(pFts5, pAux, xDelete)\n**\n**   Save the pointer passed as the second argument as the extension function's \n**   \"auxiliary data\". The pointer may then be retrieved by the current or any\n**   future invocation of the same fts5 extension function made as part of\n**   the same MATCH query using the xGetAuxdata() API.\n**\n**   Each extension function is allocated a single auxiliary data slot for\n**   each FTS query (MATCH expression). If the extension function is invoked \n**   more than once for a single FTS query, then all invocations share a \n**   single auxiliary data context.\n**\n**   If there is already an auxiliary data pointer when this function is\n**   invoked, then it is replaced by the new pointer. If an xDelete callback\n**   was specified along with the original pointer, it is invoked at this\n**   point.\n**\n**   The xDelete callback, if one is specified, is also invoked on the\n**   auxiliary data pointer after the FTS5 query has finished.\n**\n**   If an error (e.g. an OOM condition) occurs within this function,\n**   the auxiliary data is set to NULL and an error code returned. If the\n**   xDelete parameter was not NULL, it is invoked on the auxiliary data\n**   pointer before returning.\n**\n**\n** xGetAuxdata(pFts5, bClear)\n**\n**   Returns the current auxiliary data pointer for the fts5 extension \n**   function. See the xSetAuxdata() method for details.\n**\n**   If the bClear argument is non-zero, then the auxiliary data is cleared\n**   (set to NULL) before this function returns. In this case the xDelete,\n**   if any, is not invoked.\n**\n**\n** xRowCount(pFts5, pnRow)\n**\n**   This function is used to retrieve the total number of rows in the table.\n**   In other words, the same value that would be returned by:\n**\n**        SELECT count(*) FROM ftstable;\n**\n** xPhraseFirst()\n**   This function is used, along with type Fts5PhraseIter and the xPhraseNext\n**   method, to iterate through all instances of a single query phrase within\n**   the current row. This is the same information as is accessible via the\n**   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient\n**   to use, this API may be faster under some circumstances. To iterate \n**   through instances of phrase iPhrase, use the following code:\n**\n**       Fts5PhraseIter iter;\n**       int iCol, iOff;\n**       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);\n**           iCol>=0;\n**           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)\n**       ){\n**         // An instance of phrase iPhrase at offset iOff of column iCol\n**       }\n**\n**   The Fts5PhraseIter structure is defined above. Applications should not\n**   modify this structure directly - it should only be used as shown above\n**   with the xPhraseFirst() and xPhraseNext() API methods (and by\n**   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).\n**\n**   This API can be quite slow if used with an FTS5 table created with the\n**   \"detail=none\" or \"detail=column\" option. If the FTS5 table is created \n**   with either \"detail=none\" or \"detail=column\" and \"content=\" option \n**   (i.e. if it is a contentless table), then this API always iterates\n**   through an empty set (all calls to xPhraseFirst() set iCol to -1).\n**\n** xPhraseNext()\n**   See xPhraseFirst above.\n**\n** xPhraseFirstColumn()\n**   This function and xPhraseNextColumn() are similar to the xPhraseFirst()\n**   and xPhraseNext() APIs described above. The difference is that instead\n**   of iterating through all instances of a phrase in the current row, these\n**   APIs are used to iterate through the set of columns in the current row\n**   that contain one or more instances of a specified phrase. For example:\n**\n**       Fts5PhraseIter iter;\n**       int iCol;\n**       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);\n**           iCol>=0;\n**           pApi->xPhraseNextColumn(pFts, &iter, &iCol)\n**       ){\n**         // Column iCol contains at least one instance of phrase iPhrase\n**       }\n**\n**   This API can be quite slow if used with an FTS5 table created with the\n**   \"detail=none\" option. If the FTS5 table is created with either \n**   \"detail=none\" \"content=\" option (i.e. if it is a contentless table), \n**   then this API always iterates through an empty set (all calls to \n**   xPhraseFirstColumn() set iCol to -1).\n**\n**   The information accessed using this API and its companion\n**   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext\n**   (or xInst/xInstCount). The chief advantage of this API is that it is\n**   significantly more efficient than those alternatives when used with\n**   \"detail=column\" tables.  \n**\n** xPhraseNextColumn()\n**   See xPhraseFirstColumn above.\n*/\nstruct Fts5ExtensionApi {\n  int iVersion;                   /* Currently always set to 3 */\n\n  void *(*xUserData)(Fts5Context*);\n\n  int (*xColumnCount)(Fts5Context*);\n  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);\n  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);\n\n  int (*xTokenize)(Fts5Context*, \n    const char *pText, int nText, /* Text to tokenize */\n    void *pCtx,                   /* Context passed to xToken() */\n    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */\n  );\n\n  int (*xPhraseCount)(Fts5Context*);\n  int (*xPhraseSize)(Fts5Context*, int iPhrase);\n\n  int (*xInstCount)(Fts5Context*, int *pnInst);\n  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);\n\n  sqlite3_int64 (*xRowid)(Fts5Context*);\n  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);\n  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);\n\n  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,\n    int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)\n  );\n  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));\n  void *(*xGetAuxdata)(Fts5Context*, int bClear);\n\n  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);\n  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);\n\n  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);\n  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);\n};\n\n/* \n** CUSTOM AUXILIARY FUNCTIONS\n*************************************************************************/\n\n/*************************************************************************\n** CUSTOM TOKENIZERS\n**\n** Applications may also register custom tokenizer types. A tokenizer \n** is registered by providing fts5 with a populated instance of the \n** following structure. All structure methods must be defined, setting\n** any member of the fts5_tokenizer struct to NULL leads to undefined\n** behaviour. The structure methods are expected to function as follows:\n**\n** xCreate:\n**   This function is used to allocate and initialize a tokenizer instance.\n**   A tokenizer instance is required to actually tokenize text.\n**\n**   The first argument passed to this function is a copy of the (void*)\n**   pointer provided by the application when the fts5_tokenizer object\n**   was registered with FTS5 (the third argument to xCreateTokenizer()). \n**   The second and third arguments are an array of nul-terminated strings\n**   containing the tokenizer arguments, if any, specified following the\n**   tokenizer name as part of the CREATE VIRTUAL TABLE statement used\n**   to create the FTS5 table.\n**\n**   The final argument is an output variable. If successful, (*ppOut) \n**   should be set to point to the new tokenizer handle and SQLITE_OK\n**   returned. If an error occurs, some value other than SQLITE_OK should\n**   be returned. In this case, fts5 assumes that the final value of *ppOut \n**   is undefined.\n**\n** xDelete:\n**   This function is invoked to delete a tokenizer handle previously\n**   allocated using xCreate(). Fts5 guarantees that this function will\n**   be invoked exactly once for each successful call to xCreate().\n**\n** xTokenize:\n**   This function is expected to tokenize the nText byte string indicated \n**   by argument pText. pText may or may not be nul-terminated. The first\n**   argument passed to this function is a pointer to an Fts5Tokenizer object\n**   returned by an earlier call to xCreate().\n**\n**   The second argument indicates the reason that FTS5 is requesting\n**   tokenization of the supplied text. This is always one of the following\n**   four values:\n**\n**   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into\n**            or removed from the FTS table. The tokenizer is being invoked to\n**            determine the set of tokens to add to (or delete from) the\n**            FTS index.\n**\n**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed \n**            against the FTS index. The tokenizer is being called to tokenize \n**            a bareword or quoted string specified as part of the query.\n**\n**       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as\n**            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is\n**            followed by a \"*\" character, indicating that the last token\n**            returned by the tokenizer will be treated as a token prefix.\n**\n**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to \n**            satisfy an fts5_api.xTokenize() request made by an auxiliary\n**            function. Or an fts5_api.xColumnSize() request made by the same\n**            on a columnsize=0 database.  \n**   </ul>\n**\n**   For each token in the input string, the supplied callback xToken() must\n**   be invoked. The first argument to it should be a copy of the pointer\n**   passed as the second argument to xTokenize(). The third and fourth\n**   arguments are a pointer to a buffer containing the token text, and the\n**   size of the token in bytes. The 4th and 5th arguments are the byte offsets\n**   of the first byte of and first byte immediately following the text from\n**   which the token is derived within the input.\n**\n**   The second argument passed to the xToken() callback (\"tflags\") should\n**   normally be set to 0. The exception is if the tokenizer supports \n**   synonyms. In this case see the discussion below for details.\n**\n**   FTS5 assumes the xToken() callback is invoked for each token in the \n**   order that they occur within the input text.\n**\n**   If an xToken() callback returns any value other than SQLITE_OK, then\n**   the tokenization should be abandoned and the xTokenize() method should\n**   immediately return a copy of the xToken() return value. Or, if the\n**   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,\n**   if an error occurs with the xTokenize() implementation itself, it\n**   may abandon the tokenization and return any error code other than\n**   SQLITE_OK or SQLITE_DONE.\n**\n** SYNONYM SUPPORT\n**\n**   Custom tokenizers may also support synonyms. Consider a case in which a\n**   user wishes to query for a phrase such as \"first place\". Using the \n**   built-in tokenizers, the FTS5 query 'first + place' will match instances\n**   of \"first place\" within the document set, but not alternative forms\n**   such as \"1st place\". In some applications, it would be better to match\n**   all instances of \"first place\" or \"1st place\" regardless of which form\n**   the user specified in the MATCH query text.\n**\n**   There are several ways to approach this in FTS5:\n**\n**   <ol><li> By mapping all synonyms to a single token. In this case, using\n**            the above example, this means that the tokenizer returns the\n**            same token for inputs \"first\" and \"1st\". Say that token is in\n**            fact \"first\", so that when the user inserts the document \"I won\n**            1st place\" entries are added to the index for tokens \"i\", \"won\",\n**            \"first\" and \"place\". If the user then queries for '1st + place',\n**            the tokenizer substitutes \"first\" for \"1st\" and the query works\n**            as expected.\n**\n**       <li> By querying the index for all synonyms of each query term\n**            separately. In this case, when tokenizing query text, the\n**            tokenizer may provide multiple synonyms for a single term \n**            within the document. FTS5 then queries the index for each \n**            synonym individually. For example, faced with the query:\n**\n**   <codeblock>\n**     ... MATCH 'first place'</codeblock>\n**\n**            the tokenizer offers both \"1st\" and \"first\" as synonyms for the\n**            first token in the MATCH query and FTS5 effectively runs a query \n**            similar to:\n**\n**   <codeblock>\n**     ... MATCH '(first OR 1st) place'</codeblock>\n**\n**            except that, for the purposes of auxiliary functions, the query\n**            still appears to contain just two phrases - \"(first OR 1st)\" \n**            being treated as a single phrase.\n**\n**       <li> By adding multiple synonyms for a single term to the FTS index.\n**            Using this method, when tokenizing document text, the tokenizer\n**            provides multiple synonyms for each token. So that when a \n**            document such as \"I won first place\" is tokenized, entries are\n**            added to the FTS index for \"i\", \"won\", \"first\", \"1st\" and\n**            \"place\".\n**\n**            This way, even if the tokenizer does not provide synonyms\n**            when tokenizing query text (it should not - to do so would be\n**            inefficient), it doesn't matter if the user queries for \n**            'first + place' or '1st + place', as there are entries in the\n**            FTS index corresponding to both forms of the first token.\n**   </ol>\n**\n**   Whether it is parsing document or query text, any call to xToken that\n**   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit\n**   is considered to supply a synonym for the previous token. For example,\n**   when parsing the document \"I won first place\", a tokenizer that supports\n**   synonyms would call xToken() 5 times, as follows:\n**\n**   <codeblock>\n**       xToken(pCtx, 0, \"i\",                      1,  0,  1);\n**       xToken(pCtx, 0, \"won\",                    3,  2,  5);\n**       xToken(pCtx, 0, \"first\",                  5,  6, 11);\n**       xToken(pCtx, FTS5_TOKEN_COLOCATED, \"1st\", 3,  6, 11);\n**       xToken(pCtx, 0, \"place\",                  5, 12, 17);\n**</codeblock>\n**\n**   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time\n**   xToken() is called. Multiple synonyms may be specified for a single token\n**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. \n**   There is no limit to the number of synonyms that may be provided for a\n**   single token.\n**\n**   In many cases, method (1) above is the best approach. It does not add \n**   extra data to the FTS index or require FTS5 to query for multiple terms,\n**   so it is efficient in terms of disk space and query speed. However, it\n**   does not support prefix queries very well. If, as suggested above, the\n**   token \"first\" is substituted for \"1st\" by the tokenizer, then the query:\n**\n**   <codeblock>\n**     ... MATCH '1s*'</codeblock>\n**\n**   will not match documents that contain the token \"1st\" (as the tokenizer\n**   will probably not map \"1s\" to any prefix of \"first\").\n**\n**   For full prefix support, method (3) may be preferred. In this case, \n**   because the index contains entries for both \"first\" and \"1st\", prefix\n**   queries such as 'fi*' or '1s*' will match correctly. However, because\n**   extra entries are added to the FTS index, this method uses more space\n**   within the database.\n**\n**   Method (2) offers a midpoint between (1) and (3). Using this method,\n**   a query such as '1s*' will match documents that contain the literal \n**   token \"1st\", but not \"first\" (assuming the tokenizer is not able to\n**   provide synonyms for prefixes). However, a non-prefix query like '1st'\n**   will match against \"1st\" and \"first\". This method does not require\n**   extra disk space, as no extra entries are added to the FTS index. \n**   On the other hand, it may require more CPU cycles to run MATCH queries,\n**   as separate queries of the FTS index are required for each synonym.\n**\n**   When using methods (2) or (3), it is important that the tokenizer only\n**   provide synonyms when tokenizing document text (method (2)) or query\n**   text (method (3)), not both. Doing so will not cause any errors, but is\n**   inefficient.\n*/\ntypedef struct Fts5Tokenizer Fts5Tokenizer;\ntypedef struct fts5_tokenizer fts5_tokenizer;\nstruct fts5_tokenizer {\n  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);\n  void (*xDelete)(Fts5Tokenizer*);\n  int (*xTokenize)(Fts5Tokenizer*, \n      void *pCtx,\n      int flags,            /* Mask of FTS5_TOKENIZE_* flags */\n      const char *pText, int nText, \n      int (*xToken)(\n        void *pCtx,         /* Copy of 2nd argument to xTokenize() */\n        int tflags,         /* Mask of FTS5_TOKEN_* flags */\n        const char *pToken, /* Pointer to buffer containing token */\n        int nToken,         /* Size of token in bytes */\n        int iStart,         /* Byte offset of token within input text */\n        int iEnd            /* Byte offset of end of token within input text */\n      )\n  );\n};\n\n/* Flags that may be passed as the third argument to xTokenize() */\n#define FTS5_TOKENIZE_QUERY     0x0001\n#define FTS5_TOKENIZE_PREFIX    0x0002\n#define FTS5_TOKENIZE_DOCUMENT  0x0004\n#define FTS5_TOKENIZE_AUX       0x0008\n\n/* Flags that may be passed by the tokenizer implementation back to FTS5\n** as the third argument to the supplied xToken callback. */\n#define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */\n\n/*\n** END OF CUSTOM TOKENIZERS\n*************************************************************************/\n\n/*************************************************************************\n** FTS5 EXTENSION REGISTRATION API\n*/\ntypedef struct fts5_api fts5_api;\nstruct fts5_api {\n  int iVersion;                   /* Currently always set to 2 */\n\n  /* Create a new tokenizer */\n  int (*xCreateTokenizer)(\n    fts5_api *pApi,\n    const char *zName,\n    void *pContext,\n    fts5_tokenizer *pTokenizer,\n    void (*xDestroy)(void*)\n  );\n\n  /* Find an existing tokenizer */\n  int (*xFindTokenizer)(\n    fts5_api *pApi,\n    const char *zName,\n    void **ppContext,\n    fts5_tokenizer *pTokenizer\n  );\n\n  /* Create a new auxiliary function */\n  int (*xCreateFunction)(\n    fts5_api *pApi,\n    const char *zName,\n    void *pContext,\n    fts5_extension_function xFunction,\n    void (*xDestroy)(void*)\n  );\n};\n\n/*\n** END OF REGISTRATION API\n*************************************************************************/\n\n#ifdef __cplusplus\n}  /* end of the 'extern \"C\"' block */\n#endif\n\n#endif /* _FTS5_H */\n\n/******** End of fts5.h *********/\n"
  },
  {
    "path": "jsb_build/sqlite3/sqlite-amalgamation-3320300/sqlite3ext.h",
    "content": "/*\n** 2006 June 7\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This header file defines the SQLite interface for use by\n** shared libraries that want to be imported as extensions into\n** an SQLite instance.  Shared libraries that intend to be loaded\n** as extensions by SQLite should #include this file instead of \n** sqlite3.h.\n*/\n#ifndef SQLITE3EXT_H\n#define SQLITE3EXT_H\n#include \"sqlite3.h\"\n\n/*\n** The following structure holds pointers to all of the SQLite API\n** routines.\n**\n** WARNING:  In order to maintain backwards compatibility, add new\n** interfaces to the end of this structure only.  If you insert new\n** interfaces in the middle of this structure, then older different\n** versions of SQLite will not be able to load each other's shared\n** libraries!\n*/\nstruct sqlite3_api_routines {\n  void * (*aggregate_context)(sqlite3_context*,int nBytes);\n  int  (*aggregate_count)(sqlite3_context*);\n  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));\n  int  (*bind_double)(sqlite3_stmt*,int,double);\n  int  (*bind_int)(sqlite3_stmt*,int,int);\n  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);\n  int  (*bind_null)(sqlite3_stmt*,int);\n  int  (*bind_parameter_count)(sqlite3_stmt*);\n  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);\n  const char * (*bind_parameter_name)(sqlite3_stmt*,int);\n  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));\n  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));\n  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);\n  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);\n  int  (*busy_timeout)(sqlite3*,int ms);\n  int  (*changes)(sqlite3*);\n  int  (*close)(sqlite3*);\n  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,\n                           int eTextRep,const char*));\n  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,\n                             int eTextRep,const void*));\n  const void * (*column_blob)(sqlite3_stmt*,int iCol);\n  int  (*column_bytes)(sqlite3_stmt*,int iCol);\n  int  (*column_bytes16)(sqlite3_stmt*,int iCol);\n  int  (*column_count)(sqlite3_stmt*pStmt);\n  const char * (*column_database_name)(sqlite3_stmt*,int);\n  const void * (*column_database_name16)(sqlite3_stmt*,int);\n  const char * (*column_decltype)(sqlite3_stmt*,int i);\n  const void * (*column_decltype16)(sqlite3_stmt*,int);\n  double  (*column_double)(sqlite3_stmt*,int iCol);\n  int  (*column_int)(sqlite3_stmt*,int iCol);\n  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);\n  const char * (*column_name)(sqlite3_stmt*,int);\n  const void * (*column_name16)(sqlite3_stmt*,int);\n  const char * (*column_origin_name)(sqlite3_stmt*,int);\n  const void * (*column_origin_name16)(sqlite3_stmt*,int);\n  const char * (*column_table_name)(sqlite3_stmt*,int);\n  const void * (*column_table_name16)(sqlite3_stmt*,int);\n  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);\n  const void * (*column_text16)(sqlite3_stmt*,int iCol);\n  int  (*column_type)(sqlite3_stmt*,int iCol);\n  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);\n  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);\n  int  (*complete)(const char*sql);\n  int  (*complete16)(const void*sql);\n  int  (*create_collation)(sqlite3*,const char*,int,void*,\n                           int(*)(void*,int,const void*,int,const void*));\n  int  (*create_collation16)(sqlite3*,const void*,int,void*,\n                             int(*)(void*,int,const void*,int,const void*));\n  int  (*create_function)(sqlite3*,const char*,int,int,void*,\n                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n                          void (*xFinal)(sqlite3_context*));\n  int  (*create_function16)(sqlite3*,const void*,int,int,void*,\n                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n                            void (*xFinal)(sqlite3_context*));\n  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);\n  int  (*data_count)(sqlite3_stmt*pStmt);\n  sqlite3 * (*db_handle)(sqlite3_stmt*);\n  int (*declare_vtab)(sqlite3*,const char*);\n  int  (*enable_shared_cache)(int);\n  int  (*errcode)(sqlite3*db);\n  const char * (*errmsg)(sqlite3*);\n  const void * (*errmsg16)(sqlite3*);\n  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);\n  int  (*expired)(sqlite3_stmt*);\n  int  (*finalize)(sqlite3_stmt*pStmt);\n  void  (*free)(void*);\n  void  (*free_table)(char**result);\n  int  (*get_autocommit)(sqlite3*);\n  void * (*get_auxdata)(sqlite3_context*,int);\n  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);\n  int  (*global_recover)(void);\n  void  (*interruptx)(sqlite3*);\n  sqlite_int64  (*last_insert_rowid)(sqlite3*);\n  const char * (*libversion)(void);\n  int  (*libversion_number)(void);\n  void *(*malloc)(int);\n  char * (*mprintf)(const char*,...);\n  int  (*open)(const char*,sqlite3**);\n  int  (*open16)(const void*,sqlite3**);\n  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);\n  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);\n  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);\n  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);\n  void *(*realloc)(void*,int);\n  int  (*reset)(sqlite3_stmt*pStmt);\n  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));\n  void  (*result_double)(sqlite3_context*,double);\n  void  (*result_error)(sqlite3_context*,const char*,int);\n  void  (*result_error16)(sqlite3_context*,const void*,int);\n  void  (*result_int)(sqlite3_context*,int);\n  void  (*result_int64)(sqlite3_context*,sqlite_int64);\n  void  (*result_null)(sqlite3_context*);\n  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));\n  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));\n  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));\n  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));\n  void  (*result_value)(sqlite3_context*,sqlite3_value*);\n  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);\n  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,\n                         const char*,const char*),void*);\n  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));\n  char * (*xsnprintf)(int,char*,const char*,...);\n  int  (*step)(sqlite3_stmt*);\n  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,\n                                char const**,char const**,int*,int*,int*);\n  void  (*thread_cleanup)(void);\n  int  (*total_changes)(sqlite3*);\n  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);\n  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);\n  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,\n                                         sqlite_int64),void*);\n  void * (*user_data)(sqlite3_context*);\n  const void * (*value_blob)(sqlite3_value*);\n  int  (*value_bytes)(sqlite3_value*);\n  int  (*value_bytes16)(sqlite3_value*);\n  double  (*value_double)(sqlite3_value*);\n  int  (*value_int)(sqlite3_value*);\n  sqlite_int64  (*value_int64)(sqlite3_value*);\n  int  (*value_numeric_type)(sqlite3_value*);\n  const unsigned char * (*value_text)(sqlite3_value*);\n  const void * (*value_text16)(sqlite3_value*);\n  const void * (*value_text16be)(sqlite3_value*);\n  const void * (*value_text16le)(sqlite3_value*);\n  int  (*value_type)(sqlite3_value*);\n  char *(*vmprintf)(const char*,va_list);\n  /* Added ??? */\n  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);\n  /* Added by 3.3.13 */\n  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);\n  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);\n  int (*clear_bindings)(sqlite3_stmt*);\n  /* Added by 3.4.1 */\n  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,\n                          void (*xDestroy)(void *));\n  /* Added by 3.5.0 */\n  int (*bind_zeroblob)(sqlite3_stmt*,int,int);\n  int (*blob_bytes)(sqlite3_blob*);\n  int (*blob_close)(sqlite3_blob*);\n  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,\n                   int,sqlite3_blob**);\n  int (*blob_read)(sqlite3_blob*,void*,int,int);\n  int (*blob_write)(sqlite3_blob*,const void*,int,int);\n  int (*create_collation_v2)(sqlite3*,const char*,int,void*,\n                             int(*)(void*,int,const void*,int,const void*),\n                             void(*)(void*));\n  int (*file_control)(sqlite3*,const char*,int,void*);\n  sqlite3_int64 (*memory_highwater)(int);\n  sqlite3_int64 (*memory_used)(void);\n  sqlite3_mutex *(*mutex_alloc)(int);\n  void (*mutex_enter)(sqlite3_mutex*);\n  void (*mutex_free)(sqlite3_mutex*);\n  void (*mutex_leave)(sqlite3_mutex*);\n  int (*mutex_try)(sqlite3_mutex*);\n  int (*open_v2)(const char*,sqlite3**,int,const char*);\n  int (*release_memory)(int);\n  void (*result_error_nomem)(sqlite3_context*);\n  void (*result_error_toobig)(sqlite3_context*);\n  int (*sleep)(int);\n  void (*soft_heap_limit)(int);\n  sqlite3_vfs *(*vfs_find)(const char*);\n  int (*vfs_register)(sqlite3_vfs*,int);\n  int (*vfs_unregister)(sqlite3_vfs*);\n  int (*xthreadsafe)(void);\n  void (*result_zeroblob)(sqlite3_context*,int);\n  void (*result_error_code)(sqlite3_context*,int);\n  int (*test_control)(int, ...);\n  void (*randomness)(int,void*);\n  sqlite3 *(*context_db_handle)(sqlite3_context*);\n  int (*extended_result_codes)(sqlite3*,int);\n  int (*limit)(sqlite3*,int,int);\n  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);\n  const char *(*sql)(sqlite3_stmt*);\n  int (*status)(int,int*,int*,int);\n  int (*backup_finish)(sqlite3_backup*);\n  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);\n  int (*backup_pagecount)(sqlite3_backup*);\n  int (*backup_remaining)(sqlite3_backup*);\n  int (*backup_step)(sqlite3_backup*,int);\n  const char *(*compileoption_get)(int);\n  int (*compileoption_used)(const char*);\n  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,\n                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n                            void (*xFinal)(sqlite3_context*),\n                            void(*xDestroy)(void*));\n  int (*db_config)(sqlite3*,int,...);\n  sqlite3_mutex *(*db_mutex)(sqlite3*);\n  int (*db_status)(sqlite3*,int,int*,int*,int);\n  int (*extended_errcode)(sqlite3*);\n  void (*log)(int,const char*,...);\n  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);\n  const char *(*sourceid)(void);\n  int (*stmt_status)(sqlite3_stmt*,int,int);\n  int (*strnicmp)(const char*,const char*,int);\n  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);\n  int (*wal_autocheckpoint)(sqlite3*,int);\n  int (*wal_checkpoint)(sqlite3*,const char*);\n  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);\n  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);\n  int (*vtab_config)(sqlite3*,int op,...);\n  int (*vtab_on_conflict)(sqlite3*);\n  /* Version 3.7.16 and later */\n  int (*close_v2)(sqlite3*);\n  const char *(*db_filename)(sqlite3*,const char*);\n  int (*db_readonly)(sqlite3*,const char*);\n  int (*db_release_memory)(sqlite3*);\n  const char *(*errstr)(int);\n  int (*stmt_busy)(sqlite3_stmt*);\n  int (*stmt_readonly)(sqlite3_stmt*);\n  int (*stricmp)(const char*,const char*);\n  int (*uri_boolean)(const char*,const char*,int);\n  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);\n  const char *(*uri_parameter)(const char*,const char*);\n  char *(*xvsnprintf)(int,char*,const char*,va_list);\n  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);\n  /* Version 3.8.7 and later */\n  int (*auto_extension)(void(*)(void));\n  int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,\n                     void(*)(void*));\n  int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,\n                      void(*)(void*),unsigned char);\n  int (*cancel_auto_extension)(void(*)(void));\n  int (*load_extension)(sqlite3*,const char*,const char*,char**);\n  void *(*malloc64)(sqlite3_uint64);\n  sqlite3_uint64 (*msize)(void*);\n  void *(*realloc64)(void*,sqlite3_uint64);\n  void (*reset_auto_extension)(void);\n  void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,\n                        void(*)(void*));\n  void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,\n                         void(*)(void*), unsigned char);\n  int (*strglob)(const char*,const char*);\n  /* Version 3.8.11 and later */\n  sqlite3_value *(*value_dup)(const sqlite3_value*);\n  void (*value_free)(sqlite3_value*);\n  int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);\n  int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);\n  /* Version 3.9.0 and later */\n  unsigned int (*value_subtype)(sqlite3_value*);\n  void (*result_subtype)(sqlite3_context*,unsigned int);\n  /* Version 3.10.0 and later */\n  int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);\n  int (*strlike)(const char*,const char*,unsigned int);\n  int (*db_cacheflush)(sqlite3*);\n  /* Version 3.12.0 and later */\n  int (*system_errno)(sqlite3*);\n  /* Version 3.14.0 and later */\n  int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);\n  char *(*expanded_sql)(sqlite3_stmt*);\n  /* Version 3.18.0 and later */\n  void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);\n  /* Version 3.20.0 and later */\n  int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,\n                    sqlite3_stmt**,const char**);\n  int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,\n                      sqlite3_stmt**,const void**);\n  int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));\n  void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));\n  void *(*value_pointer)(sqlite3_value*,const char*);\n  int (*vtab_nochange)(sqlite3_context*);\n  int (*value_nochange)(sqlite3_value*);\n  const char *(*vtab_collation)(sqlite3_index_info*,int);\n  /* Version 3.24.0 and later */\n  int (*keyword_count)(void);\n  int (*keyword_name)(int,const char**,int*);\n  int (*keyword_check)(const char*,int);\n  sqlite3_str *(*str_new)(sqlite3*);\n  char *(*str_finish)(sqlite3_str*);\n  void (*str_appendf)(sqlite3_str*, const char *zFormat, ...);\n  void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list);\n  void (*str_append)(sqlite3_str*, const char *zIn, int N);\n  void (*str_appendall)(sqlite3_str*, const char *zIn);\n  void (*str_appendchar)(sqlite3_str*, int N, char C);\n  void (*str_reset)(sqlite3_str*);\n  int (*str_errcode)(sqlite3_str*);\n  int (*str_length)(sqlite3_str*);\n  char *(*str_value)(sqlite3_str*);\n  /* Version 3.25.0 and later */\n  int (*create_window_function)(sqlite3*,const char*,int,int,void*,\n                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n                            void (*xFinal)(sqlite3_context*),\n                            void (*xValue)(sqlite3_context*),\n                            void (*xInv)(sqlite3_context*,int,sqlite3_value**),\n                            void(*xDestroy)(void*));\n  /* Version 3.26.0 and later */\n  const char *(*normalized_sql)(sqlite3_stmt*);\n  /* Version 3.28.0 and later */\n  int (*stmt_isexplain)(sqlite3_stmt*);\n  int (*value_frombind)(sqlite3_value*);\n  /* Version 3.30.0 and later */\n  int (*drop_modules)(sqlite3*,const char**);\n  /* Version 3.31.0 and later */\n  sqlite3_int64 (*hard_heap_limit64)(sqlite3_int64);\n  const char *(*uri_key)(const char*,int);\n  const char *(*filename_database)(const char*);\n  const char *(*filename_journal)(const char*);\n  const char *(*filename_wal)(const char*);\n  /* Version 3.32.0 and later */\n  char *(*create_filename)(const char*,const char*,const char*,\n                           int,const char**);\n  void (*free_filename)(char*);\n  sqlite3_file *(*database_file_object)(const char*);\n};\n\n/*\n** This is the function signature used for all extension entry points.  It\n** is also defined in the file \"loadext.c\".\n*/\ntypedef int (*sqlite3_loadext_entry)(\n  sqlite3 *db,                       /* Handle to the database. */\n  char **pzErrMsg,                   /* Used to set error string on failure. */\n  const sqlite3_api_routines *pThunk /* Extension API function pointers. */\n);\n\n/*\n** The following macros redefine the API routines so that they are\n** redirected through the global sqlite3_api structure.\n**\n** This header file is also used by the loadext.c source file\n** (part of the main SQLite library - not an extension) so that\n** it can get access to the sqlite3_api_routines structure\n** definition.  But the main library does not want to redefine\n** the API.  So the redefinition macros are only valid if the\n** SQLITE_CORE macros is undefined.\n*/\n#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)\n#define sqlite3_aggregate_context      sqlite3_api->aggregate_context\n#ifndef SQLITE_OMIT_DEPRECATED\n#define sqlite3_aggregate_count        sqlite3_api->aggregate_count\n#endif\n#define sqlite3_bind_blob              sqlite3_api->bind_blob\n#define sqlite3_bind_double            sqlite3_api->bind_double\n#define sqlite3_bind_int               sqlite3_api->bind_int\n#define sqlite3_bind_int64             sqlite3_api->bind_int64\n#define sqlite3_bind_null              sqlite3_api->bind_null\n#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count\n#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index\n#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name\n#define sqlite3_bind_text              sqlite3_api->bind_text\n#define sqlite3_bind_text16            sqlite3_api->bind_text16\n#define sqlite3_bind_value             sqlite3_api->bind_value\n#define sqlite3_busy_handler           sqlite3_api->busy_handler\n#define sqlite3_busy_timeout           sqlite3_api->busy_timeout\n#define sqlite3_changes                sqlite3_api->changes\n#define sqlite3_close                  sqlite3_api->close\n#define sqlite3_collation_needed       sqlite3_api->collation_needed\n#define sqlite3_collation_needed16     sqlite3_api->collation_needed16\n#define sqlite3_column_blob            sqlite3_api->column_blob\n#define sqlite3_column_bytes           sqlite3_api->column_bytes\n#define sqlite3_column_bytes16         sqlite3_api->column_bytes16\n#define sqlite3_column_count           sqlite3_api->column_count\n#define sqlite3_column_database_name   sqlite3_api->column_database_name\n#define sqlite3_column_database_name16 sqlite3_api->column_database_name16\n#define sqlite3_column_decltype        sqlite3_api->column_decltype\n#define sqlite3_column_decltype16      sqlite3_api->column_decltype16\n#define sqlite3_column_double          sqlite3_api->column_double\n#define sqlite3_column_int             sqlite3_api->column_int\n#define sqlite3_column_int64           sqlite3_api->column_int64\n#define sqlite3_column_name            sqlite3_api->column_name\n#define sqlite3_column_name16          sqlite3_api->column_name16\n#define sqlite3_column_origin_name     sqlite3_api->column_origin_name\n#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16\n#define sqlite3_column_table_name      sqlite3_api->column_table_name\n#define sqlite3_column_table_name16    sqlite3_api->column_table_name16\n#define sqlite3_column_text            sqlite3_api->column_text\n#define sqlite3_column_text16          sqlite3_api->column_text16\n#define sqlite3_column_type            sqlite3_api->column_type\n#define sqlite3_column_value           sqlite3_api->column_value\n#define sqlite3_commit_hook            sqlite3_api->commit_hook\n#define sqlite3_complete               sqlite3_api->complete\n#define sqlite3_complete16             sqlite3_api->complete16\n#define sqlite3_create_collation       sqlite3_api->create_collation\n#define sqlite3_create_collation16     sqlite3_api->create_collation16\n#define sqlite3_create_function        sqlite3_api->create_function\n#define sqlite3_create_function16      sqlite3_api->create_function16\n#define sqlite3_create_module          sqlite3_api->create_module\n#define sqlite3_create_module_v2       sqlite3_api->create_module_v2\n#define sqlite3_data_count             sqlite3_api->data_count\n#define sqlite3_db_handle              sqlite3_api->db_handle\n#define sqlite3_declare_vtab           sqlite3_api->declare_vtab\n#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache\n#define sqlite3_errcode                sqlite3_api->errcode\n#define sqlite3_errmsg                 sqlite3_api->errmsg\n#define sqlite3_errmsg16               sqlite3_api->errmsg16\n#define sqlite3_exec                   sqlite3_api->exec\n#ifndef SQLITE_OMIT_DEPRECATED\n#define sqlite3_expired                sqlite3_api->expired\n#endif\n#define sqlite3_finalize               sqlite3_api->finalize\n#define sqlite3_free                   sqlite3_api->free\n#define sqlite3_free_table             sqlite3_api->free_table\n#define sqlite3_get_autocommit         sqlite3_api->get_autocommit\n#define sqlite3_get_auxdata            sqlite3_api->get_auxdata\n#define sqlite3_get_table              sqlite3_api->get_table\n#ifndef SQLITE_OMIT_DEPRECATED\n#define sqlite3_global_recover         sqlite3_api->global_recover\n#endif\n#define sqlite3_interrupt              sqlite3_api->interruptx\n#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid\n#define sqlite3_libversion             sqlite3_api->libversion\n#define sqlite3_libversion_number      sqlite3_api->libversion_number\n#define sqlite3_malloc                 sqlite3_api->malloc\n#define sqlite3_mprintf                sqlite3_api->mprintf\n#define sqlite3_open                   sqlite3_api->open\n#define sqlite3_open16                 sqlite3_api->open16\n#define sqlite3_prepare                sqlite3_api->prepare\n#define sqlite3_prepare16              sqlite3_api->prepare16\n#define sqlite3_prepare_v2             sqlite3_api->prepare_v2\n#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2\n#define sqlite3_profile                sqlite3_api->profile\n#define sqlite3_progress_handler       sqlite3_api->progress_handler\n#define sqlite3_realloc                sqlite3_api->realloc\n#define sqlite3_reset                  sqlite3_api->reset\n#define sqlite3_result_blob            sqlite3_api->result_blob\n#define sqlite3_result_double          sqlite3_api->result_double\n#define sqlite3_result_error           sqlite3_api->result_error\n#define sqlite3_result_error16         sqlite3_api->result_error16\n#define sqlite3_result_int             sqlite3_api->result_int\n#define sqlite3_result_int64           sqlite3_api->result_int64\n#define sqlite3_result_null            sqlite3_api->result_null\n#define sqlite3_result_text            sqlite3_api->result_text\n#define sqlite3_result_text16          sqlite3_api->result_text16\n#define sqlite3_result_text16be        sqlite3_api->result_text16be\n#define sqlite3_result_text16le        sqlite3_api->result_text16le\n#define sqlite3_result_value           sqlite3_api->result_value\n#define sqlite3_rollback_hook          sqlite3_api->rollback_hook\n#define sqlite3_set_authorizer         sqlite3_api->set_authorizer\n#define sqlite3_set_auxdata            sqlite3_api->set_auxdata\n#define sqlite3_snprintf               sqlite3_api->xsnprintf\n#define sqlite3_step                   sqlite3_api->step\n#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata\n#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup\n#define sqlite3_total_changes          sqlite3_api->total_changes\n#define sqlite3_trace                  sqlite3_api->trace\n#ifndef SQLITE_OMIT_DEPRECATED\n#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings\n#endif\n#define sqlite3_update_hook            sqlite3_api->update_hook\n#define sqlite3_user_data              sqlite3_api->user_data\n#define sqlite3_value_blob             sqlite3_api->value_blob\n#define sqlite3_value_bytes            sqlite3_api->value_bytes\n#define sqlite3_value_bytes16          sqlite3_api->value_bytes16\n#define sqlite3_value_double           sqlite3_api->value_double\n#define sqlite3_value_int              sqlite3_api->value_int\n#define sqlite3_value_int64            sqlite3_api->value_int64\n#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type\n#define sqlite3_value_text             sqlite3_api->value_text\n#define sqlite3_value_text16           sqlite3_api->value_text16\n#define sqlite3_value_text16be         sqlite3_api->value_text16be\n#define sqlite3_value_text16le         sqlite3_api->value_text16le\n#define sqlite3_value_type             sqlite3_api->value_type\n#define sqlite3_vmprintf               sqlite3_api->vmprintf\n#define sqlite3_vsnprintf              sqlite3_api->xvsnprintf\n#define sqlite3_overload_function      sqlite3_api->overload_function\n#define sqlite3_prepare_v2             sqlite3_api->prepare_v2\n#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2\n#define sqlite3_clear_bindings         sqlite3_api->clear_bindings\n#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob\n#define sqlite3_blob_bytes             sqlite3_api->blob_bytes\n#define sqlite3_blob_close             sqlite3_api->blob_close\n#define sqlite3_blob_open              sqlite3_api->blob_open\n#define sqlite3_blob_read              sqlite3_api->blob_read\n#define sqlite3_blob_write             sqlite3_api->blob_write\n#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2\n#define sqlite3_file_control           sqlite3_api->file_control\n#define sqlite3_memory_highwater       sqlite3_api->memory_highwater\n#define sqlite3_memory_used            sqlite3_api->memory_used\n#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc\n#define sqlite3_mutex_enter            sqlite3_api->mutex_enter\n#define sqlite3_mutex_free             sqlite3_api->mutex_free\n#define sqlite3_mutex_leave            sqlite3_api->mutex_leave\n#define sqlite3_mutex_try              sqlite3_api->mutex_try\n#define sqlite3_open_v2                sqlite3_api->open_v2\n#define sqlite3_release_memory         sqlite3_api->release_memory\n#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem\n#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig\n#define sqlite3_sleep                  sqlite3_api->sleep\n#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit\n#define sqlite3_vfs_find               sqlite3_api->vfs_find\n#define sqlite3_vfs_register           sqlite3_api->vfs_register\n#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister\n#define sqlite3_threadsafe             sqlite3_api->xthreadsafe\n#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob\n#define sqlite3_result_error_code      sqlite3_api->result_error_code\n#define sqlite3_test_control           sqlite3_api->test_control\n#define sqlite3_randomness             sqlite3_api->randomness\n#define sqlite3_context_db_handle      sqlite3_api->context_db_handle\n#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes\n#define sqlite3_limit                  sqlite3_api->limit\n#define sqlite3_next_stmt              sqlite3_api->next_stmt\n#define sqlite3_sql                    sqlite3_api->sql\n#define sqlite3_status                 sqlite3_api->status\n#define sqlite3_backup_finish          sqlite3_api->backup_finish\n#define sqlite3_backup_init            sqlite3_api->backup_init\n#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount\n#define sqlite3_backup_remaining       sqlite3_api->backup_remaining\n#define sqlite3_backup_step            sqlite3_api->backup_step\n#define sqlite3_compileoption_get      sqlite3_api->compileoption_get\n#define sqlite3_compileoption_used     sqlite3_api->compileoption_used\n#define sqlite3_create_function_v2     sqlite3_api->create_function_v2\n#define sqlite3_db_config              sqlite3_api->db_config\n#define sqlite3_db_mutex               sqlite3_api->db_mutex\n#define sqlite3_db_status              sqlite3_api->db_status\n#define sqlite3_extended_errcode       sqlite3_api->extended_errcode\n#define sqlite3_log                    sqlite3_api->log\n#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64\n#define sqlite3_sourceid               sqlite3_api->sourceid\n#define sqlite3_stmt_status            sqlite3_api->stmt_status\n#define sqlite3_strnicmp               sqlite3_api->strnicmp\n#define sqlite3_unlock_notify          sqlite3_api->unlock_notify\n#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint\n#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint\n#define sqlite3_wal_hook               sqlite3_api->wal_hook\n#define sqlite3_blob_reopen            sqlite3_api->blob_reopen\n#define sqlite3_vtab_config            sqlite3_api->vtab_config\n#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict\n/* Version 3.7.16 and later */\n#define sqlite3_close_v2               sqlite3_api->close_v2\n#define sqlite3_db_filename            sqlite3_api->db_filename\n#define sqlite3_db_readonly            sqlite3_api->db_readonly\n#define sqlite3_db_release_memory      sqlite3_api->db_release_memory\n#define sqlite3_errstr                 sqlite3_api->errstr\n#define sqlite3_stmt_busy              sqlite3_api->stmt_busy\n#define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly\n#define sqlite3_stricmp                sqlite3_api->stricmp\n#define sqlite3_uri_boolean            sqlite3_api->uri_boolean\n#define sqlite3_uri_int64              sqlite3_api->uri_int64\n#define sqlite3_uri_parameter          sqlite3_api->uri_parameter\n#define sqlite3_uri_vsnprintf          sqlite3_api->xvsnprintf\n#define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2\n/* Version 3.8.7 and later */\n#define sqlite3_auto_extension         sqlite3_api->auto_extension\n#define sqlite3_bind_blob64            sqlite3_api->bind_blob64\n#define sqlite3_bind_text64            sqlite3_api->bind_text64\n#define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension\n#define sqlite3_load_extension         sqlite3_api->load_extension\n#define sqlite3_malloc64               sqlite3_api->malloc64\n#define sqlite3_msize                  sqlite3_api->msize\n#define sqlite3_realloc64              sqlite3_api->realloc64\n#define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension\n#define sqlite3_result_blob64          sqlite3_api->result_blob64\n#define sqlite3_result_text64          sqlite3_api->result_text64\n#define sqlite3_strglob                sqlite3_api->strglob\n/* Version 3.8.11 and later */\n#define sqlite3_value_dup              sqlite3_api->value_dup\n#define sqlite3_value_free             sqlite3_api->value_free\n#define sqlite3_result_zeroblob64      sqlite3_api->result_zeroblob64\n#define sqlite3_bind_zeroblob64        sqlite3_api->bind_zeroblob64\n/* Version 3.9.0 and later */\n#define sqlite3_value_subtype          sqlite3_api->value_subtype\n#define sqlite3_result_subtype         sqlite3_api->result_subtype\n/* Version 3.10.0 and later */\n#define sqlite3_status64               sqlite3_api->status64\n#define sqlite3_strlike                sqlite3_api->strlike\n#define sqlite3_db_cacheflush          sqlite3_api->db_cacheflush\n/* Version 3.12.0 and later */\n#define sqlite3_system_errno           sqlite3_api->system_errno\n/* Version 3.14.0 and later */\n#define sqlite3_trace_v2               sqlite3_api->trace_v2\n#define sqlite3_expanded_sql           sqlite3_api->expanded_sql\n/* Version 3.18.0 and later */\n#define sqlite3_set_last_insert_rowid  sqlite3_api->set_last_insert_rowid\n/* Version 3.20.0 and later */\n#define sqlite3_prepare_v3             sqlite3_api->prepare_v3\n#define sqlite3_prepare16_v3           sqlite3_api->prepare16_v3\n#define sqlite3_bind_pointer           sqlite3_api->bind_pointer\n#define sqlite3_result_pointer         sqlite3_api->result_pointer\n#define sqlite3_value_pointer          sqlite3_api->value_pointer\n/* Version 3.22.0 and later */\n#define sqlite3_vtab_nochange          sqlite3_api->vtab_nochange\n#define sqlite3_value_nochange         sqlite3_api->value_nochange\n#define sqlite3_vtab_collation         sqlite3_api->vtab_collation\n/* Version 3.24.0 and later */\n#define sqlite3_keyword_count          sqlite3_api->keyword_count\n#define sqlite3_keyword_name           sqlite3_api->keyword_name\n#define sqlite3_keyword_check          sqlite3_api->keyword_check\n#define sqlite3_str_new                sqlite3_api->str_new\n#define sqlite3_str_finish             sqlite3_api->str_finish\n#define sqlite3_str_appendf            sqlite3_api->str_appendf\n#define sqlite3_str_vappendf           sqlite3_api->str_vappendf\n#define sqlite3_str_append             sqlite3_api->str_append\n#define sqlite3_str_appendall          sqlite3_api->str_appendall\n#define sqlite3_str_appendchar         sqlite3_api->str_appendchar\n#define sqlite3_str_reset              sqlite3_api->str_reset\n#define sqlite3_str_errcode            sqlite3_api->str_errcode\n#define sqlite3_str_length             sqlite3_api->str_length\n#define sqlite3_str_value              sqlite3_api->str_value\n/* Version 3.25.0 and later */\n#define sqlite3_create_window_function sqlite3_api->create_window_function\n/* Version 3.26.0 and later */\n#define sqlite3_normalized_sql         sqlite3_api->normalized_sql\n/* Version 3.28.0 and later */\n#define sqlite3_stmt_isexplain         sqlite3_api->stmt_isexplain\n#define sqlite3_value_frombind         sqlite3_api->value_frombind\n/* Version 3.30.0 and later */\n#define sqlite3_drop_modules           sqlite3_api->drop_modules\n/* Version 3.31.0 and later */\n#define sqlite3_hard_heap_limit64      sqlite3_api->hard_heap_limit64\n#define sqlite3_uri_key                sqlite3_api->uri_key\n#define sqlite3_filename_database      sqlite3_api->filename_database\n#define sqlite3_filename_journal       sqlite3_api->filename_journal\n#define sqlite3_filename_wal           sqlite3_api->filename_wal\n/* Version 3.32.0 and later */\n#define sqlite3_create_filename        sqlite3_api->create_filename\n#define sqlite3_free_filename          sqlite3_api->free_filename\n#define sqlite3_database_file_object   sqlite3_api->database_file_object\n#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */\n\n#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)\n  /* This case when the file really is being compiled as a loadable \n  ** extension */\n# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;\n# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;\n# define SQLITE_EXTENSION_INIT3     \\\n    extern const sqlite3_api_routines *sqlite3_api;\n#else\n  /* This case when the file is being statically linked into the \n  ** application */\n# define SQLITE_EXTENSION_INIT1     /*no-op*/\n# define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */\n# define SQLITE_EXTENSION_INIT3     /*no-op*/\n#endif\n\n#endif /* SQLITE3EXT_H */\n"
  },
  {
    "path": "jsb_build/sqlite3/test_demo_vfs.c",
    "content": "\r\n**             ++++++++++++SYNC+++++++++++\r\n**                        0             12\r\n**             ++++++++++++SYNC+++++++++++\r\n**\r\n**   On many operating systems, this is an efficient way to write to a file.\r\n**   However, on some embedded systems that do not cache writes in OS \r\n**   buffers it is much more efficient to write data in blocks that are\r\n**   an integer multiple of the sector-size in size and aligned at the\r\n**   start of a sector.\r\n**\r\n**   To work around this, the code in this file allocates a fixed size\r\n**   buffer of SQLITE_DEMOVFS_BUFFERSZ using sqlite3_malloc() whenever a \r\n**   journal file is opened. It uses the buffer to coalesce sequential\r\n**   writes into aligned SQLITE_DEMOVFS_BUFFERSZ blocks. When SQLite\r\n**   invokes the xSync() method to sync the contents of the file to disk,\r\n**   all accumulated data is written out, even if it does not constitute\r\n**   a complete block. This means the actual IO to create the rollback \r\n**   journal for the example transaction above is this:\r\n**\r\n**             Write offset | Bytes written\r\n**             ----------------------------\r\n**                        0           8192\r\n**                     8192           4632\r\n**             ++++++++++++SYNC+++++++++++\r\n**                        0             12\r\n**             ++++++++++++SYNC+++++++++++\r\n**\r\n**   Much more efficient if the underlying OS is not caching write \r\n**   operations.\r\n*/\r\n\r\n#if !defined(SQLITE_TEST) || SQLITE_OS_UNIX\r\n\r\n#include \"sqlite3.h\"\r\n\r\n#include <assert.h>\r\n#include <string.h>\r\n#include <sys/types.h>\r\n#include <sys/stat.h>\r\n#include <sys/file.h>\r\n#include <sys/param.h>\r\n#include <unistd.h>\r\n#include <time.h>\r\n#include <errno.h>\r\n#include <fcntl.h>\r\n\r\n/*\r\n** Size of the write buffer used by journal files in bytes.\r\n*/\r\n#ifndef SQLITE_DEMOVFS_BUFFERSZ\r\n# define SQLITE_DEMOVFS_BUFFERSZ 8192\r\n#endif\r\n\r\n/*\r\n** The maximum pathname length supported by this VFS.\r\n*/\r\n#define MAXPATHNAME 512\r\n\r\n/*\r\n** When using this VFS, the sqlite3_file* handles that SQLite uses are\r\n** actually pointers to instances of type DemoFile.\r\n*/\r\ntypedef struct DemoFile DemoFile;\r\nstruct DemoFile {\r\n  sqlite3_file base;              /* Base class. Must be first. */\r\n  int fd;                         /* File descriptor */\r\n\r\n  char *aBuffer;                  /* Pointer to malloc'd buffer */\r\n  int nBuffer;                    /* Valid bytes of data in zBuffer */\r\n  sqlite3_int64 iBufferOfst;      /* Offset in file of zBuffer[0] */\r\n};\r\n\r\n/*\r\n** Write directly to the file passed as the first argument. Even if the\r\n** file has a write-buffer (DemoFile.aBuffer), ignore it.\r\n*/\r\nstatic int demoDirectWrite(\r\n  DemoFile *p,                    /* File handle */\r\n  const void *zBuf,               /* Buffer containing data to write */\r\n  int iAmt,                       /* Size of data to write in bytes */\r\n  sqlite_int64 iOfst              /* File offset to write to */\r\n){\r\n  off_t ofst;                     /* Return value from lseek() */\r\n  size_t nWrite;                  /* Return value from write() */\r\n\r\n  ofst = lseek(p->fd, iOfst, SEEK_SET);\r\n  if( ofst!=iOfst ){\r\n    return SQLITE_IOERR_WRITE;\r\n  }\r\n\r\n  nWrite = write(p->fd, zBuf, iAmt);\r\n  if( nWrite!=iAmt ){\r\n    return SQLITE_IOERR_WRITE;\r\n  }\r\n\r\n  return SQLITE_OK;\r\n}\r\n\r\n/*\r\n** Flush the contents of the DemoFile.aBuffer buffer to disk. This is a\r\n** no-op if this particular file does not have a buffer (i.e. it is not\r\n** a journal file) or if the buffer is currently empty.\r\n*/\r\nstatic int demoFlushBuffer(DemoFile *p){\r\n  int rc = SQLITE_OK;\r\n  if( p->nBuffer ){\r\n    rc = demoDirectWrite(p, p->aBuffer, p->nBuffer, p->iBufferOfst);\r\n    p->nBuffer = 0;\r\n  }\r\n  return rc;\r\n}\r\n\r\n/*\r\n** Close a file.\r\n*/\r\nstatic int demoClose(sqlite3_file *pFile){\r\n  int rc;\r\n  DemoFile *p = (DemoFile*)pFile;\r\n  rc = demoFlushBuffer(p);\r\n  sqlite3_free(p->aBuffer);\r\n  close(p->fd);\r\n  return rc;\r\n}\r\n\r\n/*\r\n** Read data from a file.\r\n*/\r\nstatic int demoRead(\r\n  sqlite3_file *pFile, \r\n  void *zBuf, \r\n  int iAmt, \r\n  sqlite_int64 iOfst\r\n){\r\n  DemoFile *p = (DemoFile*)pFile;\r\n  off_t ofst;                     /* Return value from lseek() */\r\n  int nRead;                      /* Return value from read() */\r\n  int rc;                         /* Return code from demoFlushBuffer() */\r\n\r\n  /* Flush any data in the write buffer to disk in case this operation\r\n  ** is trying to read data the file-region currently cached in the buffer.\r\n  ** It would be possible to detect this case and possibly save an \r\n  ** unnecessary write here, but in practice SQLite will rarely read from\r\n  ** a journal file when there is data cached in the write-buffer.\r\n  */\r\n  rc = demoFlushBuffer(p);\r\n  if( rc!=SQLITE_OK ){\r\n    return rc;\r\n  }\r\n\r\n  ofst = lseek(p->fd, iOfst, SEEK_SET);\r\n  if( ofst!=iOfst ){\r\n    return SQLITE_IOERR_READ;\r\n  }\r\n  nRead = read(p->fd, zBuf, iAmt);\r\n\r\n  if( nRead==iAmt ){\r\n    return SQLITE_OK;\r\n  }else if( nRead>=0 ){\r\n    if( nRead<iAmt ){\r\n      memset(&((char*)zBuf)[nRead], 0, iAmt-nRead);\r\n    }\r\n    return SQLITE_IOERR_SHORT_READ;\r\n  }\r\n\r\n  return SQLITE_IOERR_READ;\r\n}\r\n\r\n/*\r\n** Write data to a crash-file.\r\n*/\r\nstatic int demoWrite(\r\n  sqlite3_file *pFile, \r\n  const void *zBuf, \r\n  int iAmt, \r\n  sqlite_int64 iOfst\r\n){\r\n  DemoFile *p = (DemoFile*)pFile;\r\n  \r\n  if( p->aBuffer ){\r\n    char *z = (char *)zBuf;       /* Pointer to remaining data to write */\r\n    int n = iAmt;                 /* Number of bytes at z */\r\n    sqlite3_int64 i = iOfst;      /* File offset to write to */\r\n\r\n    while( n>0 ){\r\n      int nCopy;                  /* Number of bytes to copy into buffer */\r\n\r\n      /* If the buffer is full, or if this data is not being written directly\r\n      ** following the data already buffered, flush the buffer. Flushing\r\n      ** the buffer is a no-op if it is empty.  \r\n      */\r\n      if( p->nBuffer==SQLITE_DEMOVFS_BUFFERSZ || p->iBufferOfst+p->nBuffer!=i ){\r\n        int rc = demoFlushBuffer(p);\r\n        if( rc!=SQLITE_OK ){\r\n          return rc;\r\n        }\r\n      }\r\n      assert( p->nBuffer==0 || p->iBufferOfst+p->nBuffer==i );\r\n      p->iBufferOfst = i - p->nBuffer;\r\n\r\n      /* Copy as much data as possible into the buffer. */\r\n      nCopy = SQLITE_DEMOVFS_BUFFERSZ - p->nBuffer;\r\n      if( nCopy>n ){\r\n        nCopy = n;\r\n      }\r\n      memcpy(&p->aBuffer[p->nBuffer], z, nCopy);\r\n      p->nBuffer += nCopy;\r\n\r\n      n -= nCopy;\r\n      i += nCopy;\r\n      z += nCopy;\r\n    }\r\n  }else{\r\n    return demoDirectWrite(p, zBuf, iAmt, iOfst);\r\n  }\r\n\r\n  return SQLITE_OK;\r\n}\r\n\r\n/*\r\n** Truncate a file. This is a no-op for this VFS (see header comments at\r\n** the top of the file).\r\n*/\r\nstatic int demoTruncate(sqlite3_file *pFile, sqlite_int64 size){\r\n#if 0\r\n  if( ftruncate(((DemoFile *)pFile)->fd, size) ) return SQLITE_IOERR_TRUNCATE;\r\n#endif\r\n  return SQLITE_OK;\r\n}\r\n\r\n/*\r\n** Sync the contents of the file to the persistent media.\r\n*/\r\nstatic int demoSync(sqlite3_file *pFile, int flags){\r\n  DemoFile *p = (DemoFile*)pFile;\r\n  int rc;\r\n\r\n  rc = demoFlushBuffer(p);\r\n  if( rc!=SQLITE_OK ){\r\n    return rc;\r\n  }\r\n\r\n  rc = fsync(p->fd);\r\n  return (rc==0 ? SQLITE_OK : SQLITE_IOERR_FSYNC);\r\n}\r\n\r\n/*\r\n** Write the size of the file in bytes to *pSize.\r\n*/\r\nstatic int demoFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){\r\n  DemoFile *p = (DemoFile*)pFile;\r\n  int rc;                         /* Return code from fstat() call */\r\n  struct stat sStat;              /* Output of fstat() call */\r\n\r\n  /* Flush the contents of the buffer to disk. As with the flush in the\r\n  ** demoRead() method, it would be possible to avoid this and save a write\r\n  ** here and there. But in practice this comes up so infrequently it is\r\n  ** not worth the trouble.\r\n  */\r\n  rc = demoFlushBuffer(p);\r\n  if( rc!=SQLITE_OK ){\r\n    return rc;\r\n  }\r\n\r\n  rc = fstat(p->fd, &sStat);\r\n  if( rc!=0 ) return SQLITE_IOERR_FSTAT;\r\n  *pSize = sStat.st_size;\r\n  return SQLITE_OK;\r\n}\r\n\r\n/*\r\n** Locking functions. The xLock() and xUnlock() methods are both no-ops.\r\n** The xCheckReservedLock() always indicates that no other process holds\r\n** a reserved lock on the database file. This ensures that if a hot-journal\r\n** file is found in the file-system it is rolled back.\r\n*/\r\nstatic int demoLock(sqlite3_file *pFile, int eLock){\r\n  return SQLITE_OK;\r\n}\r\nstatic int demoUnlock(sqlite3_file *pFile, int eLock){\r\n  return SQLITE_OK;\r\n}\r\nstatic int demoCheckReservedLock(sqlite3_file *pFile, int *pResOut){\r\n  *pResOut = 0;\r\n  return SQLITE_OK;\r\n}\r\n\r\n/*\r\n** No xFileControl() verbs are implemented by this VFS.\r\n*/\r\nstatic int demoFileControl(sqlite3_file *pFile, int op, void *pArg){\r\n  return SQLITE_NOTFOUND;\r\n}\r\n\r\n/*\r\n** The xSectorSize() and xDeviceCharacteristics() methods. These two\r\n** may return special values allowing SQLite to optimize file-system \r\n** access to some extent. But it is also safe to simply return 0.\r\n*/\r\nstatic int demoSectorSize(sqlite3_file *pFile){\r\n  return 0;\r\n}\r\nstatic int demoDeviceCharacteristics(sqlite3_file *pFile){\r\n  return 0;\r\n}\r\n\r\n/*\r\n** Open a file handle.\r\n*/\r\nstatic int demoOpen(\r\n  sqlite3_vfs *pVfs,              /* VFS */\r\n  const char *zName,              /* File to open, or 0 for a temp file */\r\n  sqlite3_file *pFile,            /* Pointer to DemoFile struct to populate */\r\n  int flags,                      /* Input SQLITE_OPEN_XXX flags */\r\n  int *pOutFlags                  /* Output SQLITE_OPEN_XXX flags (or NULL) */\r\n){\r\n  static const sqlite3_io_methods demoio = {\r\n    1,                            /* iVersion */\r\n    demoClose,                    /* xClose */\r\n    demoRead,                     /* xRead */\r\n    demoWrite,                    /* xWrite */\r\n    demoTruncate,                 /* xTruncate */\r\n    demoSync,                     /* xSync */\r\n    demoFileSize,                 /* xFileSize */\r\n    demoLock,                     /* xLock */\r\n    demoUnlock,                   /* xUnlock */\r\n    demoCheckReservedLock,        /* xCheckReservedLock */\r\n    demoFileControl,              /* xFileControl */\r\n    demoSectorSize,               /* xSectorSize */\r\n    demoDeviceCharacteristics     /* xDeviceCharacteristics */\r\n  };\r\n\r\n  DemoFile *p = (DemoFile*)pFile; /* Populate this structure */\r\n  int oflags = 0;                 /* flags to pass to open() call */\r\n  char *aBuf = 0;\r\n\r\n  if( zName==0 ){\r\n    return SQLITE_IOERR;\r\n  }\r\n\r\n  if( flags&SQLITE_OPEN_MAIN_JOURNAL ){\r\n    aBuf = (char *)sqlite3_malloc(SQLITE_DEMOVFS_BUFFERSZ);\r\n    if( !aBuf ){\r\n      return SQLITE_NOMEM;\r\n    }\r\n  }\r\n\r\n  if( flags&SQLITE_OPEN_EXCLUSIVE ) oflags |= O_EXCL;\r\n  if( flags&SQLITE_OPEN_CREATE )    oflags |= O_CREAT;\r\n  if( flags&SQLITE_OPEN_READONLY )  oflags |= O_RDONLY;\r\n  if( flags&SQLITE_OPEN_READWRITE ) oflags |= O_RDWR;\r\n\r\n  memset(p, 0, sizeof(DemoFile));\r\n  p->fd = open(zName, oflags, 0600);\r\n  if( p->fd<0 ){\r\n    sqlite3_free(aBuf);\r\n    return SQLITE_CANTOPEN;\r\n  }\r\n  p->aBuffer = aBuf;\r\n\r\n  if( pOutFlags ){\r\n    *pOutFlags = flags;\r\n  }\r\n  p->base.pMethods = &demoio;\r\n  return SQLITE_OK;\r\n}\r\n\r\n/*\r\n** Delete the file identified by argument zPath. If the dirSync parameter\r\n** is non-zero, then ensure the file-system modification to delete the\r\n** file has been synced to disk before returning.\r\n*/\r\nstatic int demoDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){\r\n  int rc;                         /* Return code */\r\n\r\n  rc = unlink(zPath);\r\n  if( rc!=0 && errno==ENOENT ) return SQLITE_OK;\r\n\r\n  if( rc==0 && dirSync ){\r\n    int dfd;                      /* File descriptor open on directory */\r\n    int i;                        /* Iterator variable */\r\n    char zDir[MAXPATHNAME+1];     /* Name of directory containing file zPath */\r\n\r\n    /* Figure out the directory name from the path of the file deleted. */\r\n    sqlite3_snprintf(MAXPATHNAME, zDir, \"%s\", zPath);\r\n    zDir[MAXPATHNAME] = '\\0';\r\n    for(i=strlen(zDir); i>1 && zDir[i]!='/'; i++);\r\n    zDir[i] = '\\0';\r\n\r\n    /* Open a file-descriptor on the directory. Sync. Close. */\r\n    dfd = open(zDir, O_RDONLY, 0);\r\n    if( dfd<0 ){\r\n      rc = -1;\r\n    }else{\r\n      rc = fsync(dfd);\r\n      close(dfd);\r\n    }\r\n  }\r\n  return (rc==0 ? SQLITE_OK : SQLITE_IOERR_DELETE);\r\n}\r\n\r\n#ifndef F_OK\r\n# define F_OK 0\r\n#endif\r\n#ifndef R_OK\r\n# define R_OK 4\r\n#endif\r\n#ifndef W_OK\r\n# define W_OK 2\r\n#endif\r\n\r\n/*\r\n** Query the file-system to see if the named file exists, is readable or\r\n** is both readable and writable.\r\n*/\r\nstatic int demoAccess(\r\n  sqlite3_vfs *pVfs, \r\n  const char *zPath, \r\n  int flags, \r\n  int *pResOut\r\n){\r\n  int rc;                         /* access() return code */\r\n  int eAccess = F_OK;             /* Second argument to access() */\r\n\r\n  assert( flags==SQLITE_ACCESS_EXISTS       /* access(zPath, F_OK) */\r\n       || flags==SQLITE_ACCESS_READ         /* access(zPath, R_OK) */\r\n       || flags==SQLITE_ACCESS_READWRITE    /* access(zPath, R_OK|W_OK) */\r\n  );\r\n\r\n  if( flags==SQLITE_ACCESS_READWRITE ) eAccess = R_OK|W_OK;\r\n  if( flags==SQLITE_ACCESS_READ )      eAccess = R_OK;\r\n\r\n  rc = access(zPath, eAccess);\r\n  *pResOut = (rc==0);\r\n  return SQLITE_OK;\r\n}\r\n\r\n/*\r\n** Argument zPath points to a nul-terminated string containing a file path.\r\n** If zPath is an absolute path, then it is copied as is into the output \r\n** buffer. Otherwise, if it is a relative path, then the equivalent full\r\n** path is written to the output buffer.\r\n**\r\n** This function assumes that paths are UNIX style. Specifically, that:\r\n**\r\n**   1. Path components are separated by a '/'. and \r\n**   2. Full paths begin with a '/' character.\r\n*/\r\nstatic int demoFullPathname(\r\n  sqlite3_vfs *pVfs,              /* VFS */\r\n  const char *zPath,              /* Input path (possibly a relative path) */\r\n  int nPathOut,                   /* Size of output buffer in bytes */\r\n  char *zPathOut                  /* Pointer to output buffer */\r\n){\r\n  char zDir[MAXPATHNAME+1];\r\n  if( zPath[0]=='/' ){\r\n    zDir[0] = '\\0';\r\n  }else{\r\n    if( getcwd(zDir, sizeof(zDir))==0 ) return SQLITE_IOERR;\r\n  }\r\n  zDir[MAXPATHNAME] = '\\0';\r\n\r\n  sqlite3_snprintf(nPathOut, zPathOut, \"%s/%s\", zDir, zPath);\r\n  zPathOut[nPathOut-1] = '\\0';\r\n\r\n  return SQLITE_OK;\r\n}\r\n\r\n/*\r\n** The following four VFS methods:\r\n**\r\n**   xDlOpen\r\n**   xDlError\r\n**   xDlSym\r\n**   xDlClose\r\n**\r\n** are supposed to implement the functionality needed by SQLite to load\r\n** extensions compiled as shared objects. This simple VFS does not support\r\n** this functionality, so the following functions are no-ops.\r\n*/\r\nstatic void *demoDlOpen(sqlite3_vfs *pVfs, const char *zPath){\r\n  return 0;\r\n}\r\nstatic void demoDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){\r\n  sqlite3_snprintf(nByte, zErrMsg, \"Loadable extensions are not supported\");\r\n  zErrMsg[nByte-1] = '\\0';\r\n}\r\nstatic void (*demoDlSym(sqlite3_vfs *pVfs, void *pH, const char *z))(void){\r\n  return 0;\r\n}\r\nstatic void demoDlClose(sqlite3_vfs *pVfs, void *pHandle){\r\n  return;\r\n}\r\n\r\n/*\r\n** Parameter zByte points to a buffer nByte bytes in size. Populate this\r\n** buffer with pseudo-random data.\r\n*/\r\nstatic int demoRandomness(sqlite3_vfs *pVfs, int nByte, char *zByte){\r\n  return SQLITE_OK;\r\n}\r\n\r\n/*\r\n** Sleep for at least nMicro microseconds. Return the (approximate) number \r\n** of microseconds slept for.\r\n*/\r\nstatic int demoSleep(sqlite3_vfs *pVfs, int nMicro){\r\n  sleep(nMicro / 1000000);\r\n  usleep(nMicro % 1000000);\r\n  return nMicro;\r\n}\r\n\r\n/*\r\n** Set *pTime to the current UTC time expressed as a Julian day. Return\r\n** SQLITE_OK if successful, or an error code otherwise.\r\n**\r\n**   http://en.wikipedia.org/wiki/Julian_day\r\n**\r\n** This implementation is not very good. The current time is rounded to\r\n** an integer number of seconds. Also, assuming time_t is a signed 32-bit \r\n** value, it will stop working some time in the year 2038 AD (the so-called\r\n** \"year 2038\" problem that afflicts systems that store time this way). \r\n*/\r\nstatic int demoCurrentTime(sqlite3_vfs *pVfs, double *pTime){\r\n  time_t t = time(0);\r\n  *pTime = t/86400.0 + 2440587.5; \r\n  return SQLITE_OK;\r\n}\r\n\r\n/*\r\n** This function returns a pointer to the VFS implemented in this file.\r\n** To make the VFS available to SQLite:\r\n**\r\n**   sqlite3_vfs_register(sqlite3_demovfs(), 0);\r\n*/\r\nsqlite3_vfs *sqlite3_demovfs(void){\r\n  static sqlite3_vfs demovfs = {\r\n    1,                            /* iVersion */\r\n    sizeof(DemoFile),             /* szOsFile */\r\n    MAXPATHNAME,                  /* mxPathname */\r\n    0,                            /* pNext */\r\n    \"demo\",                       /* zName */\r\n    0,                            /* pAppData */\r\n    demoOpen,                     /* xOpen */\r\n    demoDelete,                   /* xDelete */\r\n    demoAccess,                   /* xAccess */\r\n    demoFullPathname,             /* xFullPathname */\r\n    demoDlOpen,                   /* xDlOpen */\r\n    demoDlError,                  /* xDlError */\r\n    demoDlSym,                    /* xDlSym */\r\n    demoDlClose,                  /* xDlClose */\r\n    demoRandomness,               /* xRandomness */\r\n    demoSleep,                    /* xSleep */\r\n    demoCurrentTime,              /* xCurrentTime */\r\n  };\r\n  return &demovfs;\r\n}\r\n\r\n#endif /* !defined(SQLITE_TEST) || SQLITE_OS_UNIX */\r\n\r\n\r\n#ifdef SQLITE_TEST\r\n\r\n#if defined(INCLUDE_SQLITE_TCL_H)\r\n#  include \"sqlite_tcl.h\"\r\n#else\r\n#  include \"tcl.h\"\r\n#  ifndef SQLITE_TCLAPI\r\n#    define SQLITE_TCLAPI\r\n#  endif\r\n#endif\r\n\r\n#if SQLITE_OS_UNIX\r\nstatic int SQLITE_TCLAPI register_demovfs(\r\n  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */\r\n  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */\r\n  int objc,              /* Number of arguments */\r\n  Tcl_Obj *CONST objv[]  /* Command arguments */\r\n){\r\n  sqlite3_vfs_register(sqlite3_demovfs(), 1);\r\n  return TCL_OK;\r\n}\r\nstatic int SQLITE_TCLAPI unregister_demovfs(\r\n  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */\r\n  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */\r\n  int objc,              /* Number of arguments */\r\n  Tcl_Obj *CONST objv[]  /* Command arguments */\r\n){\r\n  sqlite3_vfs_unregister(sqlite3_demovfs());\r\n  return TCL_OK;\r\n}\r\n\r\n/*\r\n** Register commands with the TCL interpreter.\r\n*/\r\nint Sqlitetest_demovfs_Init(Tcl_Interp *interp){\r\n  Tcl_CreateObjCommand(interp, \"register_demovfs\", register_demovfs, 0, 0);\r\n  Tcl_CreateObjCommand(interp, \"unregister_demovfs\", unregister_demovfs, 0, 0);\r\n  return TCL_OK;\r\n}\r\n\r\n#else\r\nint Sqlitetest_demovfs_Init(Tcl_Interp *interp){ return TCL_OK; }\r\n#endif\r\n\r\n#endif /* SQLITE_TEST */"
  },
  {
    "path": "jsb_build/sqlite3/unity_sqlite.c",
    "content": "\r\n#define SQLITE_EXTERN\r\n\r\n#if defined(WIN32) || defined(_WIN32)\r\n    #define SQLITE_API extern __declspec(dllexport)\r\n#else\r\n    #define SQLITE_API extern\r\n#endif\r\n\r\n#include \"sqlite3.c\"\r\n"
  },
  {
    "path": "jsb_build/v8-bridge/include/JSApi.h",
    "content": "#pragma once\r\n\r\n/*\r\n * λ ./Packages/cc.starlessnight.unity-jsb/Source/Native\r\n *  extern\r\n * ڱ༭ JS_HasProperty\r\n */\r\n\r\n#include \"QuickJSCompatible.h\"\r\n\r\n#ifdef __cplusplus\r\nextern \"C\" {\r\n#endif\r\n\r\nstruct JSContext;\r\nstruct JSRuntime;\r\n\r\n#define DEF(name, str) \\\r\nJS_EXPORT JSAtom JSB_ATOM_##name();\r\n#include \"quickjs-atom.h\"\r\n#undef DEF\r\n\r\nJS_EXPORT void* js_malloc(JSContext* ctx, size_t size);\r\nJS_EXPORT void* js_mallocz(JSContext* ctx, size_t size);\r\nJS_EXPORT void js_free(JSContext* ctx, void* ptr);\r\nJS_EXPORT IntPtr js_strndup(JSContext* ctx, const char* s, size_t n);\r\n\r\n//JS_EXPORT JSValue JS_GetImportMeta(JSContext ctx, JSModuleDef m);\r\n\r\nJS_EXPORT void JS_AddIntrinsicOperators(JSContext* ctx);\r\nJS_EXPORT void JS_RunGC(JSRuntime* rt);\r\n\r\nJS_EXPORT int JSB_Init();\r\nJS_EXPORT JSClassID JSB_GetBridgeClassID();\r\n\r\nJS_EXPORT JSRuntime* JSB_NewRuntime(JSGCObjectFinalizer* finalizer);\r\nJS_EXPORT int JSB_FreeRuntime(JSRuntime* rt);\r\nJS_EXPORT void* JSB_GetRuntimeOpaque(JSRuntime* rt);\r\nJS_EXPORT void JSB_SetRuntimeOpaque(JSRuntime* rt, void* opaque);\r\nJS_EXPORT void* JS_GetContextOpaque(JSContext* ctx);\r\nJS_EXPORT void JS_SetContextOpaque(JSContext* ctx, void* opaque);\r\nJS_EXPORT JSContext* JS_NewContext(JSRuntime* rt);\r\nJS_EXPORT void JS_FreeContext(JSContext* ctx);\r\nJS_EXPORT JSRuntime* JS_GetRuntime(JSContext* ctx);\r\nJS_EXPORT JSPayloadHeader JSB_FreePayload(JSContext* ctx, JSValue val);\r\n\r\nJS_EXPORT JSValue JSB_DupValue(JSContext* ctx, JSValue val);\r\nJS_EXPORT void JSB_FreeValue(JSContext* ctx, JSValue val);\r\nJS_EXPORT void JSB_FreeValueRT(JSRuntime* rt, JSValue val);\r\n\r\nJS_EXPORT JSAtom JS_NewAtomLen(JSContext* ctx, const char* str, size_t len);\r\nJS_EXPORT JSAtom JS_DupAtom(JSContext* ctx, JSAtom v);\r\nJS_EXPORT void JS_FreeAtom(JSContext* ctx, JSAtom v);\r\nJS_EXPORT JSValue JS_AtomToString(JSContext* ctx, JSAtom atom);\r\n\r\nJS_EXPORT int JS_ToBool(JSContext* ctx, JSValueConst val);\r\nJS_EXPORT int JS_ToInt32(JSContext* ctx, int* pres, JSValue val);\r\nJS_EXPORT int JS_ToInt64(JSContext* ctx, int64_t* pres, JSValue val);\r\nJS_EXPORT int JS_ToFloat64(JSContext* ctx, double* pres, JSValueConst val);\r\nJS_EXPORT int JS_ToBigInt64(JSContext* ctx, int64_t* pres, JSValue val);\r\nJS_EXPORT int JS_ToIndex(JSContext* ctx, uint64_t* plen, JSValueConst val);\r\n//WIP: JS_ToFloat64\r\nJS_EXPORT const char* JS_ToCStringLen(JSContext* ctx, size_t* plen, JSValueConst val1);\r\nJS_EXPORT const char* JS_ToCStringLen2(JSContext* ctx, size_t* plen, JSValueConst val1, JS_BOOL cesu8);\r\nJS_EXPORT void JS_FreeCString(JSContext* ctx, const char* ptr);\r\n\r\nJS_EXPORT int JS_IsInstanceOf(JSContext* ctx, JSValueConst val, JSValueConst obj);\r\nJS_EXPORT JS_BOOL JS_IsException(JSValueConst val);\r\nJS_EXPORT JSValue JS_GetException(JSContext* ctx);\r\nJS_EXPORT JS_BOOL JS_IsError(JSContext* ctx, JSValueConst val);\r\nJS_EXPORT JSValue JSB_ThrowError(JSContext* ctx, const char* buf, size_t buf_len);\r\nJS_EXPORT JSValue JSB_ThrowTypeError(JSContext* ctx, const char* buf);\r\nJS_EXPORT JSValue JSB_ThrowInternalError(JSContext* ctx, const char* buf);\r\nJS_EXPORT JSValue JSB_ThrowRangeError(JSContext* ctx, const char* buf);\r\nJS_EXPORT JSValue JSB_ThrowReferenceError(JSContext* ctx, const char* buf);\r\n\r\n//JS_EXPORT JSClassID JSB_NewClass(JSRuntime* rt, JSClassID class_id, const char* class_name, JSGCObjectFinalizer* finalizer);\r\n\r\nJS_EXPORT JSValue JS_NewObjectProtoClass(JSContext* ctx, JSValueConst proto, JSClassID class_id);\r\n\r\nJS_EXPORT JSValue JSB_NewCFunction(JSContext* ctx, JSCFunction* func, JSAtom atom, int length, JSCFunctionEnum cproto, int magic);\r\nJS_EXPORT JSValue JSB_NewCFunctionMagic(JSContext* ctx, JSCFunctionMagic* func, JSAtom atom, int length, JSCFunctionEnum cproto, int magic);\r\nJS_EXPORT JSValue JS_GetGlobalObject(JSContext* ctx);\r\nJS_EXPORT JSValue JS_NewObject(JSContext* ctx);\r\nJS_EXPORT JSValue JSB_NewEmptyString(JSContext* ctx);\r\nJS_EXPORT JSValue JS_NewString(JSContext* ctx, const char* str);\r\nJS_EXPORT JSValue JS_NewStringLen(JSContext* ctx, const char* buf, size_t buf_len);\r\nJS_EXPORT JSValue JSB_NewInt64(JSContext* ctx, int64_t val);\r\nJS_EXPORT JSValue JSB_NewFloat64(JSContext* ctx, double d);\r\nJS_EXPORT IntPtr JS_GetArrayBuffer(JSContext* ctx, size_t* psize, JSValueConst obj);\r\nJS_EXPORT JSValue JS_NewArrayBufferCopy(JSContext* ctx, const char* buf, size_t len);\r\n\r\nJS_EXPORT void* JSB_GetOpaque(JSContext* ctx, JSValue val, JSClassID class_id);\r\nJS_EXPORT void JSB_SetOpaque(JSContext* ctx, JSValue val, void* data);\r\n\r\nJS_EXPORT JSValue JS_NewArray(JSContext* ctx);\r\nJS_EXPORT int JS_IsArray(JSContext* ctx, JSValueConst val);\r\n\r\nJS_EXPORT JS_BOOL JS_IsFunction(JSContext* ctx, JSValueConst val);\r\nJS_EXPORT JS_BOOL JS_IsConstructor(JSContext* ctx, JSValueConst val);\r\n\r\nJS_EXPORT JSValue JS_GetPropertyStr(JSContext* ctx, JSValueConst this_obj, const char* prop);\r\nJS_EXPORT JSValue JS_GetProperty(JSContext* ctx, JSValueConst this_obj, JSAtom prop);\r\nJS_EXPORT JSValue JS_GetPropertyUint32(JSContext* ctx, JSValueConst this_obj, uint32_t idx);\r\nJS_EXPORT JSValue JS_GetPropertyInternal(JSContext* ctx, JSValueConst this_obj, JSAtom prop, JSValueConst receiver, JS_BOOL throw_ref_error);\r\nJS_EXPORT int JS_HasProperty(JSContext* ctx, JSValueConst this_obj, JSAtom prop);\r\nJS_EXPORT int JS_SetPropertyUint32(JSContext* ctx, JSValueConst this_obj, uint32_t idx, JSValue val);\r\nJS_EXPORT int JS_SetPropertyInternal(JSContext* ctx, JSValueConst this_obj, JSAtom prop, JSValue val, int flags);\r\n\r\nJS_EXPORT int JS_DefineProperty(JSContext* ctx, JSValueConst this_obj, JSAtom prop, JSValueConst val, JSValueConst getter, JSValueConst setter, int flags); // val is unused\r\nJS_EXPORT int JS_DefinePropertyValue(JSContext* ctx, JSValueConst this_obj, JSAtom prop, JSValue val, int flags);\r\n\r\nJS_EXPORT int JS_SetPrototype(JSContext* ctx, JSValueConst obj, JSValueConst proto_val);\r\nJS_EXPORT void JS_SetConstructor(JSContext* ctx, JSValueConst func_obj, JSValueConst proto);\r\n\r\nJS_EXPORT JSValue JS_Eval(JSContext* ctx, const char* input, size_t input_len, const char* filename, int eval_flags);\r\nJS_EXPORT JSValue JS_CallConstructor(JSContext* ctx, JSValueConst func_obj, int argc, JSValueConst* argv);\r\nJS_EXPORT JSValue JS_Call(JSContext* ctx, JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst* argv);\r\nJS_EXPORT JSValue JS_Invoke(JSContext* ctx, JSValueConst this_val, JSAtom atom, int argc, JSValueConst* argv);\r\n\r\nJS_EXPORT JSValue JSB_GetGlobalObject(JSContext* ctx);\r\n\r\nJS_EXPORT JSValue JS_ParseJSON(JSContext* ctx, const char* buf, size_t buf_len, const char* filename);\r\nJS_EXPORT JSValue JS_JSONStringify(JSContext* ctx, JSValueConst obj, JSValueConst replacer, JSValueConst space0);\r\n\r\nJS_EXPORT JSValue JS_NewPromiseCapability(JSContext* ctx, JSValue* resolving_funcs);\r\nJS_EXPORT void JS_SetHostPromiseRejectionTracker(JSRuntime* rt, JSHostPromiseRejectionTracker* cb, void* opaque);\r\n\r\nJS_EXPORT int JS_ExecutePendingJob(JSRuntime* rt, JSContext** pctx);\r\nJS_EXPORT void JS_SetInterruptHandler(JSRuntime* rt, JSInterruptHandler* cb, IntPtr opaque);\r\nJS_EXPORT void JS_ComputeMemoryUsage(JSRuntime* rt, JSMemoryUsage* s);\r\n\r\nJS_EXPORT void JS_OpenDebugger(JSContext* ctx, int port);\r\nJS_EXPORT JS_BOOL JS_IsDebuggerOpen(JSContext* ctx);\r\nJS_EXPORT JS_BOOL JS_IsDebuggerConnected(JSContext* ctx);\r\nJS_EXPORT void JS_CloseDebugger(JSContext* ctx);\r\nJS_EXPORT void JS_SetWaitingForDebuggerFunc(JSContext* ctx, JSWaitingForDebuggerCFunction func);\r\nJS_EXPORT void JS_SetLogFunc(JSContext* ctx, JSLogCFunction func);\r\n\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n"
  },
  {
    "path": "jsb_build/v8-bridge/include/JSContext.h",
    "content": "#pragma once\r\n\r\n#include <v8.h>\r\n#include <string>\r\n#include \"JSRuntime.h\"\r\n#include \"JSInspectorClient.h\"\r\n#include \"QuickJSCompatible.h\"\r\n\r\nclass WSServer;\r\n\r\nstruct JSContext\r\n{\r\n\tstruct JSCFunctionMagicWrapper\r\n\t{\r\n\t\tJSContext* _context;\r\n\t\tunion {\r\n\t\t\tJSCFunctionMagic* _funcMagic;\r\n\t\t\tJSCFunction* _func;\r\n\r\n\t\t\tJSCFunctionSetterMagic* _setterMagic;\r\n\t\t\tJSCFunctionSetter* _setter;\r\n\r\n\t\t\tJSCFunctionGetterMagic* _getterMagic;\r\n\t\t\tJSCFunctionGetter* _getter;\r\n\t\t};\r\n\t\tint _magic;\r\n\t};\r\n\r\n\tJSLogCFunction _logCallback;\r\n\tJSWaitingForDebuggerCFunction _waingForDebuggerCallback;\r\n\tstd::unique_ptr<WSServer> _debugServer = nullptr;\r\n\tvoid OpenDebugger(int port);\r\n\tvoid CloseDebugger();\r\n\tbool IsDebuggerOpen();\r\n\tbool IsDebuggerConnected();\r\n\r\n\tvoid* _opaque = nullptr;\r\n\tJSRuntime* _runtime = nullptr;\r\n\tv8::UniquePersistent<v8::Context> _context;\r\n\t\r\n\tJSValue _global;\r\n\tJSValue _emptyString;\r\n\r\n\tJSContext(JSRuntime* runtime);\r\n\t~JSContext();\r\n\r\n\tstd::string GetAtomString(JSAtom atom);\r\n\tJSValue AtomToValue(JSAtom atom);\r\n\r\n\tv8::Local<v8::Context> Get();\r\n\tv8::Isolate* GetIsolate();\r\n\tJSValue GetGlobal();\r\n\tJSValue GetEmptyString();\r\n\r\n\tJSValue NewObject();\r\n\tJSValue NewArray();\r\n\r\n\tJSValue NewObjectProtoClass(v8::Local<v8::Object> new_target, JSClassDef* classDef);\r\n\r\n\tJSValue NewCFunctionMagic(JSCFunctionMagic* func, JSAtom atom, int length, JSCFunctionEnum cproto, int magic);\r\n\tJSValue NewCFunction(JSCFunction* func, JSAtom atom, int length, JSCFunctionEnum cproto);\r\n\r\n\tJSValue GetPropertyStr(JSValueConst this_obj, const char* prop);\r\n\tJSValue GetProperty(JSValueConst this_obj, JSAtom prop);\r\n\tJSValue GetPropertyUint32(JSValueConst this_obj, uint32_t idx);\r\n\tJSValue GetPropertyInternal(JSValueConst this_obj, JSAtom prop, JSValueConst receiver, JS_BOOL throw_ref_error);\r\n\tint HasProperty(JSValueConst this_obj, JSAtom prop);\r\n\t// will decrease the reference count of val \r\n\t// return TRUE/FALSE or -1 if exception\r\n\tint SetPropertyUint32(JSValueConst this_obj, uint32_t idx, JSValue val);\r\n\t// will decrease the reference count of val \r\n\t// return TRUE/FALSE or -1 if exception\r\n\tint SetPropertyInternal(JSValueConst this_obj, JSAtom prop, JSValue val, int flags);\r\n\tint DefineProperty(JSValueConst this_obj, JSAtom prop, JSValueConst getter, JSValueConst setter, int flags);\r\n\tint DefinePropertyValue(JSValueConst this_obj, JSAtom prop, JSValue val, int flags);\r\n\r\n\tJSValue Eval(const char* input, size_t input_len, const char* filename, int eval_flags);\r\n\tJSValue CallConstructor(JSValueConst func_obj, int argc, JSValueConst* argv);\r\n\tJSValue Call(JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst* argv);\r\n\r\n\tJSValue NewPromiseCapability(JSValue* resolving_funcs);\r\n\r\nprivate:\r\n\tstd::vector<JSCFunctionMagicWrapper*> _functionMagicWrappers;\r\n};\r\n"
  },
  {
    "path": "jsb_build/v8-bridge/include/JSInspectorClient.h",
    "content": "#pragma once\r\n\r\n#include \"QuickJSCompatible.h\"\r\n\r\nstruct JSContext;\r\nclass JSInspectorChannel;\r\n\r\nclass JSDebugger\r\n{\r\npublic:\r\n\tvirtual void Open() = 0;\r\n\tvirtual void Close() = 0;\r\n\tvirtual void Update() = 0;\r\n\tvirtual bool IsConnected() = 0;\r\n\r\n\tvirtual void OnConnectionClosed() = 0;\r\n\tvirtual void OnMessageReceived(const unsigned char* buf, size_t len) = 0;\r\n\r\n\tstatic JSDebugger* CreateDefaultDebugger(JSContext* ctx, JSDebuggerCallbacks callbacks);\r\n};\r\n"
  },
  {
    "path": "jsb_build/v8-bridge/include/JSRuntime.h",
    "content": "#pragma once\r\n#include <v8.h>\r\n#include <map>\r\n#include <string>\r\n#include \"v8impl.h\"\r\n#include \"QuickJSCompatible.h\"\r\n\r\n//struct JSValueRef\r\n//{\r\n//\tsize_t _next = 0;\r\n//\tuint32_t _references = 1;\r\n//\tv8::Isolate* _isolate = nullptr;\r\n//\tv8impl::Persistent<v8::Value> _value;\r\n//\r\n//\tJSValueRef() = default;\r\n//\tJSValueRef(v8::Isolate* isolate, v8::Local<v8::Value> value) : _isolate(isolate), _value(isolate, value) {}\r\n//\tJSValueRef(const JSValueRef& o) : _next(o._next), _references(o._references), _isolate(o._isolate), _value(o._isolate, o._value) {}\r\n//};\r\n\r\nstruct JSValueRef\r\n{\r\n\tsize_t _next;\r\n\r\n\t// when references == 0 and gc_handle == 0, this slot will be recycled\r\n\t// if references == 0 and gc_handle != 0, it's still alive until the object is actually garbage collected by v8.\r\n\t//     * before gc, it's possible to resurrect this JSValue without changing it slot index\r\n\tuint32_t _references;\r\n\tsize_t _gc_handle;\r\n\tv8impl::CopyPersistent<v8::Value> _value;\r\n\r\n\tJSValueRef() = default;\r\n\tJSValueRef(v8::Isolate* isolate, v8::Local<v8::Value> value) : _value(isolate, value), _references(1), _next(0), _gc_handle(0) {}\r\n};\r\n\r\nstruct JSAtomRef\r\n{\r\n\tuint32_t _next;\r\n\tuint32_t _references;\r\n\tv8impl::CopyPersistent<v8::String> _value;\r\n\r\n\tJSAtomRef() = default;\r\n\tJSAtomRef(v8::Isolate * isolate, v8::Local<v8::String> value) : _value(isolate, value), _references(1), _next(0) {}\r\n};\r\n\r\nstruct JSClassDef\r\n{\r\n\tJSClassID _classID = 0;\r\n\tJSGCObjectFinalizer* _finalizer = nullptr;\r\n\tv8::Global<v8::FunctionTemplate> _class;\r\n};\r\n\r\nstruct GCObject\r\n{\r\n\tsize_t _next = 0;\r\n\tsize_t _index = 0; // self index\r\n\tJSClassDef* _classDef = nullptr;\r\n\tJSRuntime* _runtime = nullptr;\r\n\tv8::Global<v8::Object> _obj; // weak \r\n\r\n\t// reference to JSValue\r\n\t// (keep it alive without strong reference before GC)\r\n\tsize_t _value_handle;\r\n};\r\n\r\nstruct JSRuntime\r\n{\r\n\tenum EInternalFieldName\r\n\t{\r\n\t\tEIFN_Payload,\r\n\t\tEIFN_FieldCount,\r\n\t};\r\n\r\n\tvoid* _opaque = nullptr;\r\n\tv8::Isolate* _isolate = nullptr;\r\n\tv8::ArrayBuffer::Allocator* _arrayBufferAllocator = nullptr;\r\nprivate:\r\n\tJSMallocFunctions malloc_functions;\r\n\tv8::UniquePersistent<v8::Private> _PrivateCacheIndexKey;\r\n\r\npublic:\r\n\tJSRuntime(JSGCObjectFinalizer* finalizer);\r\n\t~JSRuntime();\r\n\r\n\tJS_BOOL Release();\r\n\tvoid ComputeMemoryUsage(JSMemoryUsage* memoryUsage);\r\n\r\n\tJSContext* _context;\r\n\tvoid SetContext(JSContext* context);\r\n#pragma region JSValue\r\nprivate:\r\n\tsize_t _freeObjectSlot = 0;\r\n\tsize_t _aliveObjectNum = 0;\r\n\tstd::vector<JSValueRef> _objectRefs;\r\n\r\npublic:\r\n\tJSValue DupValue(JSValue value);\r\n\tvoid FreeValue(JSValue value);\r\n\tJSPayloadHeader FreePayload(JSValue value);\r\n\r\n\tv8::MaybeLocal<v8::Value> GetReferencedValue(size_t id);\r\n\tv8::MaybeLocal<v8::Value> GetValue(JSValue val);\r\n\r\n\tJSValue AddValue(v8::Local<v8::Context> context, v8::Local<v8::Value> val);\r\n\tJSValue AddString(v8::Local<v8::Context> context, v8::Local<v8::String> val);\r\n\tJSValue AddSymbol(v8::Local<v8::Context> context, v8::Local<v8::Symbol> val);\r\n\tJSValue AddObject(v8::Local<v8::Context> context, v8::Local<v8::Object> val);\r\n\r\n\t// register a finalization callback and AddObject at the same time\r\n\tJSValue AddGCObject(v8::Local<v8::Context> context, v8::Local<v8::Object> obj, JSClassDef* def);\r\nprivate:\r\n\tsize_t _AddValueInternal(v8::Local<v8::Context> context, v8::Local<v8::Value> val, size_t gc_handle = 0);\r\n#pragma endregion\r\n\t\r\n#pragma region Low Level Memory Management\r\npublic:\r\n\tvoid* mem_alloc(JSMallocState* s, size_t size);\r\n\tvoid mem_free(JSMallocState* s, void* ptr);\r\n\tvoid* mem_realloc(JSMallocState* s, void* ptr, size_t size);\r\n\tsize_t mem_malloc_usable_size(const void* ptr);\r\n#pragma endregion \r\n\r\n#pragma region JSAtom Management\r\nprivate:\r\n\tuint32_t _freeAtomSlot = 0;\r\n\tuint32_t _aliveAtomNum = 0;\r\n\tstd::vector<JSAtomRef> _atomRefs;\r\n\tstd::map<std::string, JSAtom> _atoms;\r\n\r\npublic:\r\n\tJSAtom GetAtom(std::string& val);\r\n\tJSAtom GetAtom(const char* val, size_t len);\r\n\r\n\tv8::MaybeLocal<v8::String> GetAtomValue(JSAtom atom);\r\n\tJSAtom DupAtom(JSAtom atom);\r\n\tvoid FreeAtom(JSAtom atom);\r\n#pragma endregion\r\n\r\n#pragma region Class Management\r\n\tstd::map<JSClassID, JSClassDef*> _classes;\r\n\tJSClassID NewClass(JSClassID class_id, const char* class_name, JSGCObjectFinalizer* finalizer);\r\n\tJSClassDef* GetClassDef(JSClassID class_id);\r\n#pragma endregion\r\n\r\n#pragma region Promise\r\n\tJSHostPromiseRejectionTracker* _promiseRejectionTracker;\r\n\tvoid* _promiseRejectionOpaque;\r\n\r\n\tvoid SetHostPromiseRejectionTracker(JSHostPromiseRejectionTracker* cb, void* opaque);\r\n\tint ExecutePendingJob(JSContext** pctx);\r\n#pragma endregion\r\n\r\n#pragma region GC \r\n\tvoid RunGC();\r\n#pragma endregion\r\n\r\n#pragma region GCObject Management\r\nprivate:\r\n\tsize_t _freeGCObjectSlot = 0;\r\n\tsize_t _aliveGCObjectNum = 0;\r\n\tstd::vector<GCObject*> _gcObjects;\r\n\tstatic void OnGarbadgeCollectCallback(const v8::WeakCallbackInfo<GCObject>& info);\r\npublic:\r\n#pragma endregion\r\n\r\n#pragma region JSException\r\n\tJSValue ThrowException(v8::Local<v8::Context> context, v8::Local<v8::Value> exception);\r\n\tJSValue ThrowError(v8::Local<v8::Context> context, const char* exception, int len = -1);\r\n\tJSValue ThrowTypeError(v8::Local<v8::Context> context, const char* exception, int len = -1);\r\n\r\n\tv8::Global<v8::Value> _exception;\r\n#pragma endregion\r\n\r\n\tfriend struct JSContext;\r\n};\r\n"
  },
  {
    "path": "jsb_build/v8-bridge/include/PlatformTypes.h",
    "content": "#pragma once\r\n"
  },
  {
    "path": "jsb_build/v8-bridge/include/QuickJSCompatible.h",
    "content": "#pragma once\r\n\r\n#include <stdint.h>\r\n\r\n#ifdef __cplusplus\r\nextern \"C\" {\r\n#endif\r\n\r\n#define CONFIG_BIGNUM\r\n#define JS_EXPORT __declspec(dllexport)\r\n\r\n/* flags for object properties */\r\n#define JS_PROP_CONFIGURABLE  (1 << 0)\r\n#define JS_PROP_WRITABLE      (1 << 1)\r\n#define JS_PROP_ENUMERABLE    (1 << 2)\r\n#define JS_PROP_C_W_E         (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE | JS_PROP_ENUMERABLE)\r\n#define JS_PROP_LENGTH        (1 << 3) /* used internally in Arrays */\r\n#define JS_PROP_TMASK         (3 << 4) /* mask for NORMAL, GETSET, VARREF, AUTOINIT */\r\n#define JS_PROP_NORMAL         (0 << 4)\r\n#define JS_PROP_GETSET         (1 << 4)\r\n#define JS_PROP_VARREF         (2 << 4) /* used internally */\r\n#define JS_PROP_AUTOINIT       (3 << 4) /* used internally */\r\n\r\n/* flags for JS_DefineProperty */\r\n#define JS_PROP_HAS_SHIFT        8\r\n#define JS_PROP_HAS_CONFIGURABLE (1 << 8)\r\n#define JS_PROP_HAS_WRITABLE     (1 << 9)\r\n#define JS_PROP_HAS_ENUMERABLE   (1 << 10)\r\n#define JS_PROP_HAS_GET          (1 << 11)\r\n#define JS_PROP_HAS_SET          (1 << 12)\r\n#define JS_PROP_HAS_VALUE        (1 << 13)\r\n\r\n/* throw an exception if false would be returned\r\n   (JS_DefineProperty/JS_SetProperty) */\r\n#define JS_PROP_THROW            (1 << 14)\r\n   /* throw an exception if false would be returned in strict mode\r\n\t  (JS_SetProperty) */\r\n#define JS_PROP_THROW_STRICT     (1 << 15)\r\n\r\n#define JS_PROP_NO_ADD           (1 << 16) /* internal use */\r\n#define JS_PROP_NO_EXOTIC        (1 << 17) /* internal use */\r\n\r\n/* JS_Eval() flags */\r\n#define JS_EVAL_TYPE_GLOBAL   (0 << 0) /* global code (default) */\r\n#define JS_EVAL_TYPE_MODULE   (1 << 0) /* module code */\r\n#define JS_EVAL_TYPE_DIRECT   (2 << 0) /* direct call (internal use) */\r\n#define JS_EVAL_TYPE_INDIRECT (3 << 0) /* indirect call (internal use) */\r\n#define JS_EVAL_TYPE_MASK     (3 << 0)\r\n\r\n#define JS_EVAL_FLAG_STRICT   (1 << 3) /* force 'strict' mode */\r\n#define JS_EVAL_FLAG_STRIP    (1 << 4) /* force 'strip' mode */\r\n/* compile but do not run. The result is an object with a\r\n   JS_TAG_FUNCTION_BYTECODE or JS_TAG_MODULE tag. It can be executed\r\n   with JS_EvalFunction(). */\r\n#define JS_EVAL_FLAG_COMPILE_ONLY (1 << 5)\r\n/* don't include the stack frames before this eval in the Error() backtraces */\r\n#define JS_EVAL_FLAG_BACKTRACE_BARRIER (1 << 6)\r\n\r\nenum {\r\n\t/* all tags with a reference count are negative */\r\n\tJS_TAG_FIRST = -11, /* first negative tag */\r\n\tJS_TAG_BIG_DECIMAL = -11,\r\n\tJS_TAG_BIG_INT = -10,\r\n\tJS_TAG_BIG_FLOAT = -9,\r\n\tJS_TAG_SYMBOL = -8,\r\n\tJS_TAG_STRING = -7,\r\n\tJS_TAG_MODULE = -3, /* used internally */\r\n\tJS_TAG_FUNCTION_BYTECODE = -2, /* used internally */\r\n\tJS_TAG_OBJECT = -1,\r\n\r\n\tJS_TAG_INT = 0,\r\n\tJS_TAG_BOOL = 1,\r\n\tJS_TAG_NULL = 2,\r\n\tJS_TAG_UNDEFINED = 3,\r\n\tJS_TAG_UNINITIALIZED = 4,\r\n\tJS_TAG_CATCH_OFFSET = 5,\r\n\tJS_TAG_EXCEPTION = 6,\r\n\tJS_TAG_FLOAT64 = 7,\r\n\t/* any larger tag is FLOAT64 if JS_NAN_BOXING */\r\n};\r\n\r\nenum JSCFunctionEnum {  /* XXX: should rename for namespace isolation */\r\n\tJS_CFUNC_generic,\r\n\tJS_CFUNC_generic_magic,\r\n\tJS_CFUNC_constructor,\r\n\tJS_CFUNC_constructor_magic,\r\n\tJS_CFUNC_constructor_or_func,\r\n\tJS_CFUNC_constructor_or_func_magic,\r\n\tJS_CFUNC_f_f,\r\n\tJS_CFUNC_f_f_f,\r\n\tJS_CFUNC_getter,\r\n\tJS_CFUNC_setter,\r\n\tJS_CFUNC_getter_magic,\r\n\tJS_CFUNC_setter_magic,\r\n\tJS_CFUNC_iterator_next,\r\n};\r\n\r\ntypedef struct JSMemoryUsage {\r\n\tint64_t malloc_size, malloc_limit, memory_used_size;\r\n\tint64_t malloc_count;\r\n\tint64_t memory_used_count;\r\n\tint64_t atom_count, atom_size;\r\n\tint64_t str_count, str_size;\r\n\tint64_t obj_count, obj_size;\r\n\tint64_t prop_count, prop_size;\r\n\tint64_t shape_count, shape_size;\r\n\tint64_t js_func_count, js_func_size, js_func_code_size;\r\n\tint64_t js_func_pc2line_count, js_func_pc2line_size;\r\n\tint64_t c_func_count, array_count;\r\n\tint64_t fast_array_count, fast_array_elements;\r\n\tint64_t binary_object_count, binary_object_size;\r\n} JSMemoryUsage;\r\n\r\ntypedef union JSValueUnion\r\n{\r\n\tint32_t int32;\r\n\tdouble float64;\r\n\tsize_t ptr;\r\n} JSValueUnion;\r\n\r\ntypedef struct JSValue\r\n{\r\n\tJSValueUnion u = { 0 };\r\n\tint64_t tag = 0;\r\n} JSValue;\r\n\r\ntypedef uint32_t JSAtom;\r\n\r\ntypedef struct JSMallocState {\r\n\tsize_t malloc_count;\r\n\tsize_t malloc_size;\r\n\tsize_t malloc_limit;\r\n\tvoid* opaque; /* user opaque */\r\n} JSMallocState;\r\n\r\ntypedef struct JSMallocFunctions {\r\n\tvoid* (*js_malloc)(JSMallocState* s, size_t size);\r\n\tvoid (*js_free)(JSMallocState* s, void* ptr);\r\n\tvoid* (*js_realloc)(JSMallocState* s, void* ptr, size_t size);\r\n\tsize_t(*js_malloc_usable_size)(const void* ptr);\r\n} JSMallocFunctions;\r\n\r\nstruct JSContext;\r\nstruct JSRuntime;\r\n\r\ntypedef void* IntPtr;\r\ntypedef int JS_BOOL;\r\n\r\ntypedef uint32_t JSClassID;\r\n\r\ntypedef JSValue JSValueConst;\r\n\r\ntypedef JSValue JSCFunction(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv);\r\ntypedef JSValue JSCFunctionMagic(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv, int magic);\r\n\r\ntypedef JSValue JSCFunctionSetter(JSContext* ctx, JSValueConst this_val, JSValueConst val);\r\ntypedef JSValue JSCFunctionSetterMagic(JSContext* ctx, JSValueConst this_val, JSValueConst val, int magic);\r\n\r\ntypedef JSValue JSCFunctionGetter(JSContext* ctx, JSValueConst this_val);\r\ntypedef JSValue JSCFunctionGetterMagic(JSContext* ctx, JSValueConst this_val, int magic);\r\n\r\ntypedef void JSClassFinalizer(JSRuntime* rt, JSValue val);\r\ntypedef int JSInterruptHandler(JSRuntime* rt, IntPtr opaque);\r\n\r\n#define JS_BO_TYPE 1\r\n#define JS_BO_OBJECT 2\r\n#define JS_BO_VALUE 3\r\n\r\ntypedef struct JSPayloadHeader\r\n{\r\n\tint32_t type_id; // JS_BO_*\r\n\tint32_t value;\r\n} JSPayloadHeader;\r\n\r\nstatic JSPayloadHeader EmptyPayload = { .type_id = 0, .value = 0 };\r\n\r\ntypedef struct JSPayload\r\n{\r\n\tJSPayloadHeader header;\r\n\tchar data[1];\r\n} JSPayload;\r\n\r\ntypedef void JSGCObjectFinalizer(JSRuntime* rt, JSPayloadHeader val);\r\ntypedef void JSHostPromiseRejectionTracker(JSContext* ctx, JSValueConst promise, JSValueConst reason, JS_BOOL is_handled, void* opaque);\r\n\r\n#ifndef TRUE\r\n#define TRUE 1\r\n#define FALSE 0\r\n#endif\r\n\r\ntypedef enum JSToNumberHintEnum {\r\n\tTON_FLAG_NUMBER,\r\n\tTON_FLAG_NUMERIC,\r\n} JSToNumberHintEnum;\r\n\r\ntypedef void (*JSDebuggerCFunction)(JSContext* ctx);\r\ntypedef void (*JSDebuggerSendCFunction)(JSContext* ctx, unsigned char type, const unsigned char* buf, size_t size);\r\n\r\ntypedef struct JSDebuggerCallbacks\r\n{\r\n\tJSDebuggerCFunction update;\r\n\tJSDebuggerSendCFunction send;\r\n} JSDebuggerCallbacks;\r\n\r\ntypedef void (*JSLogCFunction)(int level, const char* line);\r\ntypedef void (*JSWaitingForDebuggerCFunction)(JSContext* ctx);\r\n\r\n#define JS_FLOAT64_NAN NAN\r\n\r\n#define JS_TAG_IS_BYREF(tag) (tag) < 0\r\n\r\n//#define JS_MKVAL() JSValue{}\r\n#define JS_MKINT32(tag, v) JSValue{{.int32=(v)},(tag)}\r\n#define JS_MKFLOAT64(tag, v) JSValue{{.float64=(v)},(tag)}\r\n#define JS_MKPTR(tag, v) JSValue{{.ptr=(v)},(tag)}\r\n\r\n#define JS_VALUE_GET_TAG(v) ((int32_t)(v).tag)\r\n/* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */\r\n#define JS_VALUE_GET_NORM_TAG(v) JS_VALUE_GET_TAG(v)\r\n#define JS_VALUE_GET_INT(v) ((v).u.int32)\r\n#define JS_VALUE_GET_BOOL(v) ((v).u.int32)\r\n#define JS_VALUE_GET_FLOAT64(v) ((v).u.float64)\r\n#define JS_VALUE_GET_PTR(v) ((v).u.ptr)\r\n\r\n#define JS_TAG_IS_FLOAT64(tag) ((unsigned)(tag) == JS_TAG_FLOAT64)\r\n\r\n#define JS_UNDEFINED JSValue{ {0}, JS_TAG_UNDEFINED }\r\n#define JS_NULL JSValue{ {0}, JS_TAG_NULL }\r\n#define JS_EXCEPTION JSValue { {0}, JS_TAG_EXCEPTION }\r\n#define JS_NAN JSValue{{.float64=JS_FLOAT64_NAN},JS_TAG_FLOAT64}\r\n\r\n#define ATOD_ACCEPT_BIN_OCT  (1 << 2)\r\n\r\n#if !defined(FORCEINLINE)\r\n#define FORCEINLINE __forceinline\r\n#endif\r\n\r\n#if !defined(JSB_DEBUG)\r\n#define JSB_DEBUG 1\r\n#endif\r\n\r\n#define JS_ATOM_NULL 0\r\n\r\n#define JS_CONTEXT_DATA_SELF 1\r\n\r\n#define JS_ISOLATE_DATA_SELF 0\r\n\r\nenum\r\n{\r\n\t__JS_ATOM_NULL = JS_ATOM_NULL,\r\n#define DEF(name, str) JS_ATOM_##name,\r\n#define SSR\r\n#include \"quickjs-atom.h\"\r\n#undef DEF\r\n\tJS_ATOM_END,\r\n};\r\n\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n"
  },
  {
    "path": "jsb_build/v8-bridge/include/WSServer.h",
    "content": "#pragma once\r\n\r\n#include \"QuickJSCompatible.h\"\r\n\r\nclass WSServer\r\n{\r\npublic:\r\n\tvirtual bool IsConnected() = 0;\r\n\tvirtual void Update(bool bDebugging) = 0;\r\n\tvirtual ~WSServer() {}\r\n\r\n\tstatic WSServer* CreateDebugServer(JSContext* ctx, int port);\r\n};"
  },
  {
    "path": "jsb_build/v8-bridge/include/quickjs-atom.h",
    "content": "\r\n#ifdef DEF\r\n\r\nDEF(Proxy, \"Proxy\")\r\nDEF(constructor, \"constructor\")\r\nDEF(Number, \"Number\")\r\nDEF(Object, \"Object\")\r\nDEF(String, \"String\")\r\nDEF(Function, \"Function\")\r\nDEF(Error, \"Error\")\r\nDEF(Operators, \"Operators\")\r\nDEF(Symbol_operatorSet, \"Symbol.operatorSet\")\r\nDEF(name, \"name\")\r\nDEF(message, \"message\")\r\nDEF(fileName, \"fileName\")\r\nDEF(lineNumber, \"lineNumber\")\r\nDEF(length, \"length\")\r\nDEF(stack, \"stack\")\r\nDEF(prototype, \"prototype\")\r\nDEF(global, \"global\")\r\n\r\n#endif\r\n"
  },
  {
    "path": "jsb_build/v8-bridge/include/v8impl.h",
    "content": "#pragma once\r\n\r\n#include <v8.h>\r\n\r\nnamespace v8impl\r\n{\r\n\ttemplate<typename T>\r\n\tusing Persistent = v8::Global<T>;\r\n\r\n\ttemplate<typename T>\r\n\tusing CopyPersistent = typename v8::CopyablePersistentTraits<T>::CopyablePersistent;\r\n}\r\n\r\n"
  },
  {
    "path": "jsb_build/v8-bridge/src/JSApi.cpp",
    "content": "\r\n#include \"JSApi.h\"\r\n#include \"JSRuntime.h\"\r\n#include \"JSContext.h\"\r\n\r\n#include <v8.h>\r\n#include <cassert>\r\n\r\n#define SO_JSB_VERSION 0xa\r\n\r\n#ifdef __cplusplus\r\nextern \"C\" {\r\n#endif\r\n\r\n#define DEF(name, str) \\\r\nJSAtom JSB_ATOM_##name() { return (uint32_t)JS_ATOM_##name; }\r\n#include \"quickjs-atom.h\"\r\n#undef DEF\r\n\r\n#define byte unsigned char\r\n#define JS_FreeValue JSB_FreeValue\r\n\r\nstatic JSClassID js_bridge_class_id = 0;\r\n\r\n#define UNITY_EXT_COMPILING\r\n#include \"unity_ext.c\"\r\n#include \"cutils.c\"\r\n#include \"libregexp.c\"\r\n#undef UNITY_EXT_COMPILING\r\n\r\nvoid* js_malloc(JSContext* ctx, size_t size)\r\n{\r\n\treturn ctx->_runtime->mem_alloc(nullptr, size);\r\n}\r\n\r\nvoid* js_mallocz(JSContext* ctx, size_t size)\r\n{\r\n\tvoid* ptr = ctx->_runtime->mem_alloc(nullptr, size);\r\n\treturn memset(ptr, 0, size);\r\n}\r\n\r\nvoid js_free(JSContext* ctx, void* ptr)\r\n{\r\n\tctx->_runtime->mem_free(nullptr, ptr);\r\n}\r\n\r\nIntPtr js_strndup(JSContext* ctx, const char* s, size_t n)\r\n{\r\n\tif (s && n > 0)\r\n\t{\r\n\t\treturn memcpy(ctx->_runtime->mem_alloc(0, n), s, n);\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nvoid JS_AddIntrinsicOperators(JSContext* ctx)\r\n{\r\n}\r\n\r\nvoid JS_RunGC(JSRuntime* rt)\r\n{\r\n\trt->RunGC();\r\n}\r\n\r\nint JSB_Init()\r\n{\r\n\tif (js_bridge_class_id == 0)\r\n\t{\r\n\t\tjs_bridge_class_id = 1;\r\n\t}\r\n\treturn SO_JSB_VERSION;\r\n}\r\n\r\nJSClassID JSB_GetBridgeClassID()\r\n{\r\n\treturn js_bridge_class_id;\r\n}\r\n\r\nstatic JSValue JS_ThrowError(JSContext* ctx, const char* msg)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->_runtime->ThrowError(ctx->Get(), msg);\r\n}\r\n\r\nJSRuntime* JSB_NewRuntime(JSGCObjectFinalizer* finalizer)\r\n{\r\n\tJSRuntime* rt = new JSRuntime(finalizer);\r\n\treturn rt;\r\n}\r\n\r\nint JSB_FreeRuntime(JSRuntime* rt)\r\n{\r\n\tJS_BOOL res = rt->Release();\r\n\tdelete rt;\r\n\treturn res;\r\n}\r\n\r\nvoid* JSB_GetRuntimeOpaque(JSRuntime* rt)\r\n{\r\n\treturn rt->_opaque;\r\n}\r\n\r\nvoid JSB_SetRuntimeOpaque(JSRuntime* rt, void* opaque)\r\n{\r\n\trt->_opaque = opaque;\r\n}\r\n\r\nvoid* JS_GetContextOpaque(JSContext* ctx)\r\n{\r\n\treturn ctx->_opaque;\r\n}\r\n\r\nvoid JS_SetContextOpaque(JSContext* ctx, void* opaque)\r\n{\r\n\tctx->_opaque = opaque;\r\n}\r\n\r\nJSContext* JS_NewContext(JSRuntime* rt)\r\n{\r\n\tv8::Isolate::Scope isolateScope(rt->_isolate);\r\n\tv8::HandleScope handleScope(rt->_isolate);\r\n\r\n\tJSContext* ctx = new JSContext(rt);\r\n\tJSValue globalObject = JS_GetGlobalObject(ctx);\r\n\tJS_SetPropertyInternal(ctx, globalObject, JSB_ATOM_global(), globalObject, 0);\r\n\treturn ctx;\r\n}\r\n\r\nvoid JS_FreeContext(JSContext* ctx)\r\n{\r\n\tdelete ctx;\r\n}\r\n\r\nJSRuntime* JS_GetRuntime(JSContext* ctx)\r\n{\r\n\treturn ctx->_runtime;\r\n}\r\n\r\nJSPayloadHeader JSB_FreePayload(JSContext* ctx, JSValue val)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->_runtime->_isolate);\r\n\tv8::HandleScope handleScope(ctx->_runtime->_isolate);\r\n\r\n\treturn ctx->_runtime->FreePayload(val);\r\n}\r\n\r\nJSValue JSB_DupValue(JSContext* ctx, JSValue val)\r\n{\r\n\treturn ctx->_runtime->DupValue(val);\r\n}\r\n\r\nvoid JSB_FreeValue(JSContext* ctx, JSValue val)\r\n{\r\n\tctx->_runtime->FreeValue(val);\r\n}\r\n\r\nvoid JSB_FreeValueRT(JSRuntime* rt, JSValue val)\r\n{\r\n\trt->FreeValue(val);\r\n}\r\n\r\nJSAtom JS_NewAtomLen(JSContext* ctx, const char* str, size_t len)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->_runtime->GetAtom(str, len);\r\n}\r\n\r\nJSAtom JS_DupAtom(JSContext* ctx, JSAtom v)\r\n{\r\n\treturn ctx->_runtime->DupAtom(v);\r\n}\r\n\r\nvoid JS_FreeAtom(JSContext* ctx, JSAtom v)\r\n{\r\n\tctx->_runtime->FreeAtom(v);\r\n}\r\n\r\nJSValue JS_AtomToString(JSContext* ctx, JSAtom atom)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->AtomToValue(atom);\r\n}\r\n\r\nint JS_ToBool(JSContext* ctx, JSValueConst val)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\tv8::MaybeLocal<v8::Value> maybe = ctx->_runtime->GetValue(val);\r\n\tv8::Local<v8::Value> value;\r\n\tif (maybe.ToLocal(&value))\r\n\t{\r\n\t\treturn value->ToBoolean(ctx->GetIsolate())->Value() ? TRUE : FALSE;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nint JS_ToInt32(JSContext* ctx, int* pres, JSValue val)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\tv8::MaybeLocal<v8::Value> maybe = ctx->_runtime->GetValue(val);\r\n\tv8::Local<v8::Value> value;\r\n\tif (maybe.ToLocal(&value))\r\n\t{\r\n\t\tv8::MaybeLocal<v8::Int32> maybe_int32 = value->ToInt32(ctx->Get());\r\n\t\tv8::Local<v8::Int32> int32;\r\n\t\tif (maybe_int32.ToLocal(&int32))\r\n\t\t{\r\n\t\t\t*pres = int32->Value();\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\t*pres = 0;\r\n\treturn -1;\r\n}\r\n\r\nint JS_ToInt64(JSContext* ctx, int64_t* pres, JSValue val)\r\n{\r\n\treturn JS_ToBigInt64(ctx, pres, val);\r\n}\r\n\r\nstatic int skip_spaces(const char* pc)\r\n{\r\n\tconst uint8_t* p, * p_next, * p_start;\r\n\tuint32_t c;\r\n\r\n\tp = p_start = (const uint8_t*)pc;\r\n\tfor (;;) {\r\n\t\tc = *p;\r\n\t\tif (c < 128) {\r\n\t\t\tif (!((c >= 0x09 && c <= 0x0d) || (c == 0x20)))\r\n\t\t\t\tbreak;\r\n\t\t\tp++;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tc = unicode_from_utf8(p, UTF8_CHAR_LEN_MAX, &p_next);\r\n\t\t\tif (!lre_is_space(c))\r\n\t\t\t\tbreak;\r\n\t\t\tp = p_next;\r\n\t\t}\r\n\t}\r\n\treturn p - p_start;\r\n}\r\n\r\nstatic JSValue JS_ToNumberHintFree(JSContext* ctx, JSValue val,\r\n\tJSToNumberHintEnum flag)\r\n{\r\n\tuint32_t tag;\r\n\tJSValue ret;\r\n\r\nredo:\r\n\ttag = JS_VALUE_GET_NORM_TAG(val);\r\n\tswitch (tag) {\r\n#ifdef CONFIG_BIGNUM\r\n\tcase JS_TAG_BIG_DECIMAL:\r\n\t\tif (flag != TON_FLAG_NUMERIC) {\r\n\t\t\tJS_FreeValue(ctx, val);\r\n\t\t\treturn JSB_ThrowTypeError(ctx, \"cannot convert bigdecimal to number\");\r\n\t\t}\r\n\t\tret = val;\r\n\t\tbreak;\r\n\tcase JS_TAG_BIG_INT:\r\n\t\tif (flag != TON_FLAG_NUMERIC) {\r\n\t\t\tJS_FreeValue(ctx, val);\r\n\t\t\treturn JSB_ThrowTypeError(ctx, \"cannot convert bigint to number\");\r\n\t\t}\r\n\t\tret = val;\r\n\t\tbreak;\r\n\tcase JS_TAG_BIG_FLOAT:\r\n\t\tif (flag != TON_FLAG_NUMERIC) {\r\n\t\t\tJS_FreeValue(ctx, val);\r\n\t\t\treturn JSB_ThrowTypeError(ctx, \"cannot convert bigfloat to number\");\r\n\t\t}\r\n\t\tret = val;\r\n\t\tbreak;\r\n#endif\r\n\tcase JS_TAG_FLOAT64:\r\n\tcase JS_TAG_INT:\r\n\tcase JS_TAG_EXCEPTION:\r\n\t\tret = val;\r\n\t\tbreak;\r\n\tcase JS_TAG_BOOL:\r\n\tcase JS_TAG_NULL:\r\n\t\tret = JS_MKINT32(JS_TAG_INT, JS_VALUE_GET_INT(val));\r\n\t\tbreak;\r\n\tcase JS_TAG_UNDEFINED:\r\n\t\tret = JS_NAN;\r\n\t\tbreak;\r\n\tcase JS_TAG_OBJECT:\r\n\t\tJS_FreeValue(ctx, val);\r\n\t\treturn JSB_ThrowTypeError(ctx, \"cannot convert object to number\");\r\n\t\t//val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER);\r\n\t\t//if (JS_IsException(val))\r\n\t\t//\treturn JS_EXCEPTION;\r\n\t\t//goto redo;\r\n\tcase JS_TAG_STRING:\r\n\t{\r\n\t\tconst char* str;\r\n\t\tconst char* p;\r\n\t\tsize_t len;\r\n\r\n\t\tstr = JS_ToCStringLen(ctx, &len, val);\r\n\t\tJS_FreeValue(ctx, val);\r\n\t\tif (!str)\r\n\t\t\treturn JS_EXCEPTION;\r\n\t\tp = str;\r\n\t\tp += skip_spaces(p);\r\n\t\tif ((p - str) == len) {\r\n\t\t\tret = JS_MKINT32(JS_TAG_INT, 0);\r\n\t\t}\r\n\t\telse {\r\n\t\t\t//TODO: js_atof\r\n\t\t\tret = JS_MKFLOAT64(JS_TAG_FLOAT64, atof(p));\r\n\t\t\t//int flags = ATOD_ACCEPT_BIN_OCT;\r\n\t\t\t//ret = js_atof(ctx, p, &p, 0, flags);\r\n\t\t\t//if (!JS_IsException(ret)) {\r\n\t\t\t//\tp += skip_spaces(p);\r\n\t\t\t//\tif ((p - str) != len) {\r\n\t\t\t//\t\tJS_FreeValue(ctx, ret);\r\n\t\t\t//\t\tret = JS_NAN;\r\n\t\t\t//\t}\r\n\t\t\t//}\r\n\t\t}\r\n\t\tJS_FreeCString(ctx, str);\r\n\t}\r\n\tbreak;\r\n\tcase JS_TAG_SYMBOL:\r\n\t\tJS_FreeValue(ctx, val);\r\n\t\treturn JSB_ThrowTypeError(ctx, \"cannot convert symbol to number\");\r\n\tdefault:\r\n\t\tJS_FreeValue(ctx, val);\r\n\t\tret = JS_NAN;\r\n\t\tbreak;\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nstatic JSValue JS_ToNumberFree(JSContext* ctx, JSValue val)\r\n{\r\n\treturn JS_ToNumberHintFree(ctx, val, TON_FLAG_NUMBER);\r\n}\r\n\r\nstatic int __JS_ToFloat64Free(JSContext* ctx, double* pres,\r\n\tJSValue val)\r\n{\r\n\tdouble d;\r\n\tuint32_t tag;\r\n\r\n\tval = JS_ToNumberFree(ctx, val);\r\n\tif (JS_IsException(val)) {\r\n\t\t*pres = JS_FLOAT64_NAN;\r\n\t\treturn -1;\r\n\t}\r\n\ttag = JS_VALUE_GET_NORM_TAG(val);\r\n\tswitch (tag) {\r\n\tcase JS_TAG_INT:\r\n\t\td = JS_VALUE_GET_INT(val);\r\n\t\tbreak;\r\n\tcase JS_TAG_FLOAT64:\r\n\t\td = JS_VALUE_GET_FLOAT64(val);\r\n\t\tbreak;\r\n#ifdef CONFIG_BIGNUM\r\n\tcase JS_TAG_BIG_INT:\r\n\tcase JS_TAG_BIG_FLOAT:\r\n\t{\r\n\t\t//TODO bigint & bigfloat\r\n\t\t//ctx->_runtime->GetReferencedValue(JS_VALUE_GET_PTR(val));\r\n\t\td = 0;\r\n\t\t//JSBigFloat* p = JS_VALUE_GET_PTR(val);\r\n\t\t///* XXX: there can be a double rounding issue with some\r\n\t\t//   primitives (such as JS_ToUint8ClampFree()), but it is\r\n\t\t//   not critical to fix it. */\r\n\t\t//bf_get_float64(&p->num, &d, BF_RNDN);\r\n\t\tJS_FreeValue(ctx, val);\r\n\t}\r\n\tbreak;\r\n#endif\r\n\tdefault:\r\n\t\tabort();\r\n\t}\r\n\t*pres = d;\r\n\treturn 0;\r\n}\r\n\r\nstatic inline int JS_ToFloat64Free(JSContext* ctx, double* pres, JSValue val)\r\n{\r\n\tuint32_t tag;\r\n\r\n\ttag = JS_VALUE_GET_TAG(val);\r\n\tif (tag <= JS_TAG_NULL) {\r\n\t\t*pres = JS_VALUE_GET_INT(val);\r\n\t\treturn 0;\r\n\t}\r\n\telse if (JS_TAG_IS_FLOAT64(tag)) {\r\n\t\t*pres = JS_VALUE_GET_FLOAT64(val);\r\n\t\treturn 0;\r\n\t}\r\n\telse {\r\n\t\treturn __JS_ToFloat64Free(ctx, pres, val);\r\n\t}\r\n}\r\n\r\nint JS_ToFloat64(JSContext* ctx, double* pres, JSValueConst val)\r\n{\r\n\treturn JS_ToFloat64Free(ctx, pres, JSB_DupValue(ctx, val));\r\n}\r\n\r\nint JS_ToBigInt64(JSContext* ctx, int64_t* pres, JSValue val)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\tv8::MaybeLocal<v8::Value> maybe = ctx->_runtime->GetValue(val);\r\n\tv8::Local<v8::Value> value;\r\n\tif (maybe.ToLocal(&value))\r\n\t{\r\n\t\tv8::MaybeLocal<v8::BigInt> maybe_bigint = value->ToBigInt(ctx->Get());\r\n\t\tv8::Local<v8::BigInt> bigint;\r\n\t\tif (maybe_bigint.ToLocal(&bigint))\r\n\t\t{\r\n\t\t\t*pres = bigint->Int64Value();\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\t*pres = 0;\r\n\treturn -1;\r\n}\r\n\r\nint JS_ToIndex(JSContext* ctx, uint64_t* plen, JSValueConst val)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\tv8::MaybeLocal<v8::Value> maybe = ctx->_runtime->GetValue(val);\r\n\tv8::Local<v8::Value> value;\r\n\tif (maybe.ToLocal(&value))\r\n\t{\r\n\t\tv8::MaybeLocal<v8::BigInt> maybe_bigint = value->ToBigInt(ctx->Get());\r\n\t\tv8::Local<v8::BigInt> bigint;\r\n\t\tif (maybe_bigint.ToLocal(&bigint))\r\n\t\t{\r\n\t\t\t*plen = bigint->Uint64Value();\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\t*plen = 0;\r\n\treturn -1;\r\n}\r\n\r\nconst char* JS_ToCStringLen(JSContext* ctx, size_t* plen, JSValueConst val1)\r\n{\r\n\treturn JS_ToCStringLen2(ctx, plen, val1, 0);\r\n}\r\n\r\nconst char* JS_ToCStringLen2(JSContext* ctx, size_t* plen, JSValueConst val1, JS_BOOL cesu8)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\tv8::MaybeLocal<v8::Value> maybe_value = ctx->_runtime->GetValue(val1);\r\n\tv8::Local<v8::Value> value;\r\n\tif (maybe_value.ToLocal(&value))\r\n\t{\r\n\t\tif (value->IsSymbol())\r\n\t\t{\r\n\t\t\tv8::Local<v8::Symbol> symbol = v8::Local<v8::Symbol>::Cast(value);\r\n\t\t\tv8::Local<v8::Value> description = symbol->Description(ctx->GetIsolate());\r\n\t\t\tv8::String::Utf8Value str(ctx->GetIsolate(), description);\r\n\t\t\tsize_t len = str.length();\r\n\t\t\tchar* pmem = (char*)ctx->_runtime->mem_alloc(nullptr, len + 1);\r\n\t\t\tif (pmem)\r\n\t\t\t{\r\n\t\t\t\tmemcpy(pmem, *str, len);\r\n\t\t\t\tpmem[len] = 0;\r\n\t\t\t\tif (plen)\r\n\t\t\t\t{\r\n\t\t\t\t\t*plen = len;\r\n\t\t\t\t}\r\n\t\t\t\treturn pmem;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse \r\n\t\t{\r\n\t\t\tv8::MaybeLocal<v8::String> maybe_string = value->ToString(ctx->Get());\r\n\t\t\tv8::Local<v8::String> _string;\r\n\t\t\tif (maybe_string.ToLocal(&_string) && _string->Length() > 0)\r\n\t\t\t{\r\n\t\t\t\tv8::String::Utf8Value str(ctx->GetIsolate(), _string);\r\n\t\t\t\tsize_t len = str.length();\r\n\t\t\t\tchar* pmem = (char*)ctx->_runtime->mem_alloc(nullptr, len + 1);\r\n\t\t\t\tif (pmem)\r\n\t\t\t\t{\r\n\t\t\t\t\tmemcpy(pmem, *str, len);\r\n\t\t\t\t\tpmem[len] = 0;\r\n\t\t\t\t\tif (plen)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t*plen = len;\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn pmem;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif (plen) \r\n\t{\r\n\t\t*plen = 0;\r\n\t}\r\n\treturn nullptr;\r\n}\r\n\r\nvoid JS_FreeCString(JSContext* ctx, const char* ptr)\r\n{\r\n\tctx->_runtime->mem_free(nullptr, (void*)ptr);\r\n}\r\n\r\nint JS_IsInstanceOf(JSContext* ctx, JSValueConst val, JSValueConst obj)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\tv8::MaybeLocal<v8::Value> v = ctx->_runtime->GetValue(val);\r\n\tv8::MaybeLocal<v8::Value> t = ctx->_runtime->GetValue(obj);\r\n\tif (!v.IsEmpty() && !t.IsEmpty())\r\n\t{\r\n\t\tv8::Local<v8::Object> t_o = v8::Local<v8::Object>::Cast(t.ToLocalChecked());\r\n\t\tv8::Maybe<bool> res = v.ToLocalChecked()->InstanceOf(ctx->Get(), t_o);\r\n\t\tif (res.IsJust())\r\n\t\t{\r\n\t\t\treturn res.FromJust() ? 1 : 0;\r\n\t\t}\r\n\t}\r\n\t//TODO throw exception and return -1\r\n\treturn 0;\r\n}\r\n\r\nJS_BOOL JS_IsException(JSValueConst val)\r\n{\r\n\treturn val.tag == JS_TAG_EXCEPTION ? 1 : 0;\r\n}\r\n\r\nJSValue JS_GetException(JSContext* ctx)\r\n{\r\n\tif (ctx->_runtime->_exception.IsEmpty())\r\n\t{\r\n\t\treturn JS_UNDEFINED;\r\n\t}\r\n\treturn JS_EXCEPTION;\r\n}\r\n\r\nJS_BOOL JS_IsError(JSContext* ctx, JSValueConst val)\r\n{\r\n\tif (val.tag == JS_TAG_EXCEPTION)\r\n\t{\r\n\t\treturn TRUE;\r\n\t}\r\n\tif (val.tag == JS_TAG_OBJECT)\r\n\t{\r\n\t\t//TODO check Error object\r\n\t\t//v8::MaybeLocal<v8::Value> maybe = ctx->_runtime->GetReferencedValue(val.u.ptr);\r\n\t\t//v8::Local<v8::Value> value;\r\n\t\t//if (maybe.ToLocal(&value))\r\n\t\t//{\r\n\t\t//}\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nJSValue JSB_ThrowError(JSContext* ctx, const char* buf, size_t buf_len)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->_runtime->ThrowError(ctx->Get(), buf, (int)buf_len);\r\n}\r\n\r\nJSValue JSB_ThrowTypeError(JSContext* ctx, const char* buf)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->_runtime->ThrowTypeError(ctx->Get(), buf);\r\n}\r\n\r\nJSValue JSB_ThrowInternalError(JSContext* ctx, const char* buf)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->_runtime->ThrowError(ctx->Get(), buf);\r\n}\r\n\r\nJSValue JSB_ThrowRangeError(JSContext* ctx, const char* buf)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->_runtime->ThrowError(ctx->Get(), buf);\r\n}\r\n\r\nJSValue JSB_ThrowReferenceError(JSContext* ctx, const char* buf)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->_runtime->ThrowError(ctx->Get(), buf);\r\n}\r\n\r\nJSClassID JSB_NewClass(JSRuntime* rt, JSClassID class_id, const char* class_name, JSGCObjectFinalizer* finalizer)\r\n{\r\n\tv8::Isolate::Scope isolateScope(rt->_isolate);\r\n\tv8::HandleScope handleScope(rt->_isolate);\r\n\r\n\treturn rt->NewClass(class_id, class_name, finalizer);\r\n}\r\n\r\nJSValue JS_NewObjectProtoClass(JSContext* ctx, JSValueConst proto, JSClassID class_id)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\tif (proto.tag == JS_TAG_OBJECT)\r\n\t{\r\n\t\tJSClassDef* def = ctx->_runtime->GetClassDef(class_id);\r\n\t\tif (def)\r\n\t\t{\r\n\t\t\tv8::MaybeLocal<v8::Value> maybe_value = ctx->_runtime->GetReferencedValue(proto.u.ptr);\r\n\t\t\tv8::Local<v8::Value> value;\r\n\t\t\tif (maybe_value.ToLocal(&value) && value->IsObject())\r\n\t\t\t{\r\n\t\t\t\treturn ctx->NewObjectProtoClass(v8::Local<v8::Object>::Cast(value), def);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn ctx->_runtime->ThrowError(ctx->Get(), \"proto is not an object\");\r\n}\r\n\r\n// DO NOT USE 'magic'\r\nJSValue JSB_NewCFunction(JSContext* ctx, JSCFunction* func, JSAtom atom, int length, JSCFunctionEnum cproto, int magic)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->NewCFunction(func, atom, length, cproto);\r\n}\r\n\r\nJSValue JSB_NewCFunctionMagic(JSContext* ctx, JSCFunctionMagic* func, JSAtom atom, int length, JSCFunctionEnum cproto, int magic)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->NewCFunctionMagic(func, atom, length, cproto, magic);\r\n}\r\n\r\nJSValue JS_GetGlobalObject(JSContext* ctx)\r\n{\r\n\treturn ctx->GetGlobal();\r\n}\r\n\r\nJSValue JS_NewObject(JSContext* ctx)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->NewObject();\r\n}\r\n\r\nJSValue JSB_NewEmptyString(JSContext* ctx)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->GetEmptyString();\r\n}\r\n\r\nJSValue JS_NewString(JSContext* ctx, const char* str)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\tv8::MaybeLocal<v8::String> maybe = v8::String::NewFromUtf8(ctx->GetIsolate(), str);\r\n\tif (maybe.IsEmpty())\r\n\t{\r\n\t\treturn ctx->_runtime->ThrowError(ctx->Get(), \"failed to new string\");\r\n\t}\r\n\treturn ctx->_runtime->AddString(ctx->Get(), maybe.ToLocalChecked());\r\n}\r\n\r\nJSValue JS_NewStringLen(JSContext* ctx, const char* buf, size_t buf_len)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\tv8::MaybeLocal<v8::String> maybe = v8::String::NewFromUtf8(ctx->GetIsolate(), buf, v8::NewStringType::kNormal, (int)buf_len);\r\n\tif (maybe.IsEmpty())\r\n\t{\r\n\t\treturn ctx->_runtime->ThrowError(ctx->Get(), \"failed to new string\");\r\n\t}\r\n\treturn ctx->_runtime->AddString(ctx->Get(), maybe.ToLocalChecked());\r\n}\r\n\r\nJSValue JSB_NewInt64(JSContext* ctx, int64_t val)\r\n{\r\n\tJSValue v;\r\n\tif (val == (int32_t)val) {\r\n\t\tv = JS_MKINT32(JS_TAG_INT, (int32_t)val);\r\n\t}\r\n\telse {\r\n\t\tv = JS_MKFLOAT64(JS_TAG_FLOAT64, (double)val);\r\n\t}\r\n\treturn v;\r\n}\r\n\r\nJSValue JSB_NewFloat64(JSContext* ctx, double d)\r\n{\r\n\tJSValue v;\r\n\tint32_t val;\r\n\tunion {\r\n\t\tdouble d;\r\n\t\tuint64_t u;\r\n\t} u, t;\r\n\tu.d = d;\r\n\tval = (int32_t)d;\r\n\tt.d = val;\r\n\t/* -0 cannot be represented as integer, so we compare the bit\r\n\t\trepresentation */\r\n\tif (u.u == t.u) {\r\n\t\tv = JS_MKINT32(JS_TAG_INT, val);\r\n\t}\r\n\telse {\r\n\t\tv = JS_MKFLOAT64(JS_TAG_FLOAT64, d);\r\n\t}\r\n\treturn v;\r\n}\r\n\r\nIntPtr JS_GetArrayBuffer(JSContext* ctx, size_t* psize, JSValueConst obj)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\tv8::MaybeLocal<v8::Value> maybe_value = ctx->_runtime->GetValue(obj);\r\n\tv8::Local<v8::Value> value;\r\n\tif (maybe_value.ToLocal(&value) && value->IsArrayBuffer()) \r\n\t{\r\n\t\tv8::Local<v8::ArrayBuffer> array_buffer = v8::Local<v8::ArrayBuffer>::Cast(value);\r\n\t\tstd::shared_ptr<v8::BackingStore> backing_store = array_buffer->GetBackingStore();\r\n\t\tvoid* buf = backing_store->Data();\r\n\t\tif (buf)\r\n\t\t{\r\n\t\t\t*psize = backing_store->ByteLength();\r\n\t\t}\r\n\t\treturn buf;\r\n\t}\r\n\t*psize = 0;\r\n\treturn 0;\r\n}\r\n\r\nJSValue JS_NewArrayBufferCopy(JSContext* ctx, const char* buf, size_t len)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::Context::Scope contextScope(ctx->Get());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\tv8::Local<v8::ArrayBuffer> array_buffer = v8::ArrayBuffer::New(ctx->GetIsolate(), len);\r\n\tstd::shared_ptr<v8::BackingStore> backing_store = array_buffer->GetBackingStore();\r\n\tmemcpy(backing_store->Data(), buf, len);\r\n\treturn ctx->_runtime->AddObject(ctx->Get(), array_buffer);\r\n}\r\n\r\nvoid* JSB_GetOpaque(JSContext* ctx, JSValue val, JSClassID class_id)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\tv8::MaybeLocal<v8::Value> maybe_value = ctx->_runtime->GetValue(val);\r\n\tv8::Local<v8::Value> value;\r\n\tif (maybe_value.ToLocal(&value) && value->IsObject())\r\n\t{\r\n\t\tv8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(value);\r\n\t\tif (obj->InternalFieldCount() == JSRuntime::EIFN_FieldCount)\r\n\t\t{\r\n\t\t\t//return v8::Local<v8::External>::Cast(obj->GetInternalField(JSRuntime::EIFN_Payload))->Value();\r\n\t\t\treturn obj->GetAlignedPointerFromInternalField(JSRuntime::EIFN_Payload);\r\n\t\t}\r\n\t}\r\n\treturn nullptr;\r\n}\r\n\r\nvoid JSB_SetOpaque(JSContext* ctx, JSValue val, void* data)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\tv8::MaybeLocal<v8::Value> maybe_value = ctx->_runtime->GetValue(val);\r\n\tv8::Local<v8::Value> value;\r\n\tif (maybe_value.ToLocal(&value) && value->IsObject())\r\n\t{\r\n\t\tv8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(value);\r\n\t\tif (obj->InternalFieldCount() == JSRuntime::EIFN_FieldCount) \r\n\t\t{\r\n\t\t\t//obj->SetInternalField(JSRuntime::EIFN_Payload, v8::External::New(ctx->GetIsolate(), data));\r\n\t\t\tobj->SetAlignedPointerInInternalField(JSRuntime::EIFN_Payload, data);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nJSValue JS_NewArray(JSContext* ctx)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->NewArray();\r\n}\r\n\r\nint JS_IsArray(JSContext* ctx, JSValueConst val)\r\n{\r\n\tif (val.tag == JS_TAG_OBJECT)\r\n\t{\r\n\t\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\t\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\t\tv8::MaybeLocal<v8::Value> maybe_value = ctx->_runtime->GetReferencedValue(val.u.ptr);\r\n\t\tv8::Local<v8::Value> value;\r\n\t\tif (maybe_value.ToLocal(&value) && value->IsArray())\r\n\t\t{\r\n\t\t\treturn TRUE;\r\n\t\t}\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nJS_BOOL JS_IsFunction(JSContext* ctx, JSValueConst val)\r\n{\r\n\tif (val.tag == JS_TAG_OBJECT)\r\n\t{\r\n\t\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\t\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\t\tv8::MaybeLocal<v8::Value> maybe_value = ctx->_runtime->GetReferencedValue(val.u.ptr);\r\n\t\tv8::Local<v8::Value> value;\r\n\t\tif (maybe_value.ToLocal(&value) && value->IsFunction())\r\n\t\t{\r\n\t\t\treturn TRUE;\r\n\t\t}\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nJS_BOOL JS_IsConstructor(JSContext* ctx, JSValueConst val)\r\n{\r\n\tif (val.tag == JS_TAG_OBJECT)\r\n\t{\r\n\t\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\t\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\t\tv8::MaybeLocal<v8::Value> maybe_value = ctx->_runtime->GetReferencedValue(val.u.ptr);\r\n\t\tv8::Local<v8::Value> value;\r\n\t\tif (maybe_value.ToLocal(&value) && value->IsFunction())\r\n\t\t{\r\n\t\t\tv8::Local<v8::Function> func_value = v8::Local<v8::Function>::Cast(value);\r\n\t\t\treturn func_value->IsConstructor() ? TRUE : FALSE;\r\n\t\t}\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nJSValue JS_GetPropertyStr(JSContext* ctx, JSValueConst this_obj, const char* prop)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->GetPropertyStr(this_obj, prop);\r\n}\r\n\r\nJSValue JS_GetProperty(JSContext* ctx, JSValueConst this_obj, JSAtom prop)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->GetProperty(this_obj, prop);\r\n}\r\n\r\nJSValue JS_GetPropertyUint32(JSContext* ctx, JSValueConst this_obj, uint32_t idx)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->GetPropertyUint32(this_obj, idx);\r\n}\r\n\r\nJSValue JS_GetPropertyInternal(JSContext* ctx, JSValueConst this_obj, JSAtom prop, JSValueConst receiver, JS_BOOL throw_ref_error)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->GetPropertyInternal(this_obj, prop, receiver, throw_ref_error);\r\n}\r\n\r\nint JS_HasProperty(JSContext* ctx, JSValueConst this_obj, JSAtom prop)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->HasProperty(this_obj, prop);\r\n}\r\n\r\n// return TRUE/FALSE or -1 if exception\r\nint JS_SetPropertyUint32(JSContext* ctx, JSValueConst this_obj, uint32_t idx, JSValue val)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->SetPropertyUint32(this_obj, idx, val);\r\n}\r\n\r\n// return TRUE/FALSE or -1 if exception\r\nint JS_SetPropertyInternal(JSContext* ctx, JSValueConst this_obj, JSAtom prop, JSValue val, int flags)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->SetPropertyInternal(this_obj, prop, val, flags);\r\n}\r\n\r\nint JS_DefineProperty(JSContext* ctx, JSValueConst this_obj, JSAtom prop, JSValueConst val, JSValueConst getter, JSValueConst setter, int flags)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->DefineProperty(this_obj, prop, getter, setter, flags);\r\n}\r\n\r\nint JS_DefinePropertyValue(JSContext* ctx, JSValueConst this_obj, JSAtom prop, JSValue val, int flags)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->DefinePropertyValue(this_obj, prop, val, flags);\r\n}\r\n\r\nint JS_SetPrototype(JSContext* ctx, JSValueConst obj, JSValueConst proto_val)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\tv8::MaybeLocal<v8::Value> obj_v = ctx->_runtime->GetValue(obj);\r\n\tv8::MaybeLocal<v8::Value> proto_val_v = ctx->_runtime->GetValue(proto_val);\r\n\tif (!obj_v.IsEmpty() && !proto_val_v.IsEmpty())\r\n\t{\r\n\t\tv8::Local<v8::Object> obj_o = v8::Local<v8::Object>::Cast(obj_v.ToLocalChecked());\r\n\t\tv8::Maybe<bool> res = obj_o->SetPrototype(ctx->Get(), proto_val_v.ToLocalChecked());\r\n\t\tif (res.IsJust())\r\n\t\t{\r\n\t\t\treturn res.FromJust() ? 1 : 0;\r\n\t\t}\r\n\t}\r\n\t//TODO throw exception and return -1\r\n\treturn 0;\r\n}\r\n\r\nvoid JS_SetConstructor(JSContext* ctx, JSValueConst func_obj, JSValueConst proto)\r\n{\r\n\tJS_DefinePropertyValue(ctx, func_obj, JS_ATOM_prototype, JSB_DupValue(ctx, proto), 0);\r\n\tJS_DefinePropertyValue(ctx, proto, JS_ATOM_constructor, JSB_DupValue(ctx, func_obj), 0);\r\n}\r\n\r\nJSValue JS_Eval(JSContext* ctx, const char* input, size_t input_len, const char* filename, int eval_flags)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->Eval(input, input_len, filename, eval_flags);\r\n}\r\n\r\nJSValue JS_CallConstructor(JSContext* ctx, JSValueConst func_obj, int argc, JSValueConst* argv)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->CallConstructor(func_obj, argc, argv);\r\n}\r\n\r\nJSValue JS_Call(JSContext* ctx, JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst* argv)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->Call(func_obj, this_obj, argc, argv);\r\n}\r\n\r\nJSValue JS_Invoke(JSContext* ctx, JSValueConst this_val, JSAtom atom, int argc, JSValueConst* argv)\r\n{\r\n\tJSValue v = JS_GetProperty(ctx, this_val, atom);\r\n\tif (JS_IsFunction(ctx, v))\r\n\t{\r\n\t\tJSValue ret = JS_Call(ctx, v, this_val, argc, argv);\r\n\t\tJS_FreeValue(ctx, v);\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tJS_FreeValue(ctx, v);\r\n\treturn JS_ThrowError(ctx, \"not a function\");\r\n}\r\n\r\nJSValue JSB_GetGlobalObject(JSContext* ctx)\r\n{\r\n\treturn ctx->GetGlobal();\r\n}\r\n\r\nJSValue JS_ParseJSON(JSContext* ctx, const char* buf, size_t buf_len, const char* filename)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\tv8::MaybeLocal<v8::String> json_string = v8::String::NewFromUtf8(ctx->_runtime->_isolate, buf, v8::NewStringType::kNormal, (int)buf_len);\r\n\tif (!json_string.IsEmpty())\r\n\t{\r\n\t\tv8::Local<v8::Context> context = ctx->Get();\r\n\t\tv8::Context::Scope contextScope(context);\r\n\t\tv8::MaybeLocal<v8::Value> maybe_json_object = v8::JSON::Parse(context, json_string.ToLocalChecked());\r\n\t\tv8::Local<v8::Value> json_object;\r\n\t\tif (maybe_json_object.ToLocal(&json_object))\r\n\t\t{\r\n\t\t\treturn ctx->_runtime->AddValue(ctx->Get(), json_object);\r\n\t\t}\r\n\t}\r\n\treturn JS_ThrowError(ctx, \"can not parse\");\r\n}\r\n\r\nJSValue JS_JSONStringify(JSContext* ctx, JSValueConst obj, JSValueConst replacer, JSValueConst space0)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\tv8::MaybeLocal<v8::Value> json_object = ctx->_runtime->GetValue(obj);\r\n\tif (!json_object.IsEmpty())\r\n\t{\r\n\t\tv8::MaybeLocal<v8::String> maybe_json_string = v8::JSON::Stringify(ctx->Get(), json_object.ToLocalChecked());\r\n\t\tv8::Local<v8::String> json_string;\r\n\t\tif (maybe_json_string.ToLocal(&json_string))\r\n\t\t{\r\n\t\t\treturn ctx->_runtime->AddString(ctx->Get(), json_string);\r\n\t\t}\r\n\t}\r\n\treturn JS_UNDEFINED;\r\n}\r\n\r\nJSValue JS_NewPromiseCapability(JSContext* ctx, JSValue* resolving_funcs)\r\n{\r\n\tv8::Isolate::Scope isolateScope(ctx->GetIsolate());\r\n\tv8::HandleScope handleScope(ctx->GetIsolate());\r\n\r\n\treturn ctx->NewPromiseCapability(resolving_funcs);\r\n}\r\n\r\nvoid JS_SetHostPromiseRejectionTracker(JSRuntime* rt, JSHostPromiseRejectionTracker* cb, void* opaque)\r\n{\r\n\treturn rt->SetHostPromiseRejectionTracker(cb, opaque);\r\n}\r\n\r\nint JS_ExecutePendingJob(JSRuntime* rt, JSContext** pctx)\r\n{\r\n\treturn rt->ExecutePendingJob(pctx);\r\n}\r\n\r\nvoid JS_SetInterruptHandler(JSRuntime* rt, JSInterruptHandler* cb, IntPtr opaque)\r\n{\r\n\t//TODO not implemented\r\n}\r\n\r\nvoid JS_ComputeMemoryUsage(JSRuntime* rt, JSMemoryUsage* s)\r\n{\r\n\trt->ComputeMemoryUsage(s);\r\n}\r\n\r\nvoid JS_OpenDebugger(JSContext* ctx, int port)\r\n{\r\n\tctx->OpenDebugger(port);\r\n}\r\n\r\nJS_BOOL JS_IsDebuggerOpen(JSContext* ctx)\r\n{\r\n\treturn ctx->IsDebuggerOpen() ? TRUE : FALSE;\r\n}\r\n\r\nJS_BOOL JS_IsDebuggerConnected(JSContext* ctx)\r\n{\r\n\treturn ctx->IsDebuggerConnected() ? TRUE : FALSE;\r\n}\r\n\r\nvoid JS_CloseDebugger(JSContext* ctx)\r\n{\r\n\tctx->CloseDebugger();\r\n}\r\n\r\nvoid JS_SetWaitingForDebuggerFunc(JSContext* ctx, JSWaitingForDebuggerCFunction func)\r\n{\r\n\tctx->_waingForDebuggerCallback = func;\r\n}\r\n\r\nvoid JS_SetLogFunc(JSContext* ctx, JSLogCFunction func)\r\n{\r\n\tctx->_logCallback = func;\r\n}\r\n\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n"
  },
  {
    "path": "jsb_build/v8-bridge/src/JSContext.cpp",
    "content": "#include \"JSContext.h\"\r\n#include <cassert>\r\n#include \"WSServer.h\"\r\n\r\n#define JSB_PRINT_CONTENT\r\n\r\n#if defined(JSB_EXEC_TEST)\r\nstatic void _print(const v8::FunctionCallbackInfo<v8::Value>& args)\r\n{\r\n#if defined(JSB_PRINT_CONTENT)\r\n\tbool first = true;\r\n\tfor (int i = 0; i < args.Length(); i++)\r\n\t{\r\n\t\tv8::HandleScope handle_scope(args.GetIsolate());\r\n\t\tv8::String::Utf8Value str(args.GetIsolate(), args[i]);\r\n\t\tif (str.length() > 0)\r\n\t\t{\r\n\t\t\tif (first)\r\n\t\t\t{\r\n\t\t\t\tfirst = false;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tprintf(\" \");\r\n\t\t\t}\r\n\t\t\tprintf(\"%s\", *str);\r\n\t\t}\r\n\t}\r\n\tprintf(\"\\n\");\r\n\tfflush(stdout);\r\n#endif\r\n}\r\n#endif\r\n\r\nstatic void _SetReturnValue(v8::Local<v8::Context> context, JSRuntime* runtime, const v8::FunctionCallbackInfo<v8::Value>& info, JSValue rval)\r\n{\r\n\tswitch (rval.tag)\r\n\t{\r\n\tcase JS_TAG_UNDEFINED:\r\n\t\tbreak;\r\n\tcase JS_TAG_EXCEPTION:\r\n\t{\r\n\t\t//v8::Local<v8::Value> e = runtime->_exception.Get(runtime->_isolate);\r\n\t\t//if (!e.IsEmpty())\r\n\t\t//{\r\n\t\t//\truntime->_exception.Reset();\r\n\t\t//\truntime->_isolate->ThrowException(e);\r\n\t\t//}\r\n\t\t//else\r\n\t\t//{\r\n\t\t//\truntime->_isolate->ThrowError(\"unexpected exception\");\r\n\t\t//}\r\n\t\tbreak;\r\n\t}\r\n\tdefault:\r\n\t{\r\n\t\tv8::MaybeLocal<v8::Value> maybe_returnValue = runtime->GetValue(rval);\r\n\t\tv8::Local<v8::Value> returnValue;\r\n\t\truntime->FreeValue(rval);\r\n\t\tif (maybe_returnValue.ToLocal(&returnValue))\r\n\t\t{\r\n\t\t\tinfo.GetReturnValue().Set(returnValue);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tstatic char errmsg[256];\r\n\t\t\tint errmsg_len = sprintf_s(errmsg, \"failed to translate return value from JSValue %lld:%zd\", rval.tag, rval.u.ptr);\r\n\t\t\truntime->ThrowError(context, errmsg, errmsg_len);\r\n\t\t}\r\n\t\tbreak;\r\n\t}\r\n\t}\r\n}\r\n\r\nstatic void JSCFunctionConstructorMagicCallback(const v8::FunctionCallbackInfo<v8::Value>& info)\r\n{\r\n\tv8::Isolate* _isolate = info.GetIsolate();\r\n\tv8::Isolate::Scope isolateScope(_isolate);\r\n\tv8::HandleScope handleScope(_isolate);\r\n\r\n\tJSContext::JSCFunctionMagicWrapper* wrapper = reinterpret_cast<JSContext::JSCFunctionMagicWrapper*>(v8::Local<v8::External>::Cast(info.Data())->Value());\r\n\r\n\tv8::Local<v8::Context> context = wrapper->_context->Get();\r\n\tJSRuntime* runtime = wrapper->_context->_runtime;\r\n\tJSValue this_obj = runtime->AddObject(context, info.This());\r\n\tint argc = info.Length();\r\n\tJSValue* argv = argc > 0 ? (JSValue*)alloca(sizeof(JSValue) * argc) : nullptr;\r\n\r\n\tfor (int i = 0; i < argc; i++)\r\n\t{\r\n\t\targv[i] = runtime->AddValue(context, info[i]);\r\n\t}\r\n\r\n\tJSValue rval = wrapper->_funcMagic(wrapper->_context, this_obj, argc, argv, wrapper->_magic);\r\n\t_SetReturnValue(context, runtime, info, rval);\r\n\tfor (int i = 0; i < argc; i++)\r\n\t{\r\n\t\truntime->FreeValue(argv[i]);\r\n\t}\r\n\truntime->FreeValue(this_obj);\r\n}\r\n\r\nstatic void JSCFunctionMagicCallback(const v8::FunctionCallbackInfo<v8::Value>& info)\r\n{\r\n\tv8::Isolate* _isolate = info.GetIsolate();\r\n\tv8::Isolate::Scope isolateScope(_isolate);\r\n\tv8::HandleScope handleScope(_isolate);\r\n\r\n\tJSContext::JSCFunctionMagicWrapper* wrapper = reinterpret_cast<JSContext::JSCFunctionMagicWrapper*>(v8::Local<v8::External>::Cast(info.Data())->Value());\r\n\r\n\tv8::Local<v8::Context> context = wrapper->_context->Get();\r\n\tJSRuntime* runtime = wrapper->_context->_runtime;\r\n\tJSValue this_obj = runtime->AddObject(context, info.This());\r\n\tint argc = info.Length();\r\n\tJSValue* argv = argc > 0 ? (JSValue*)alloca(sizeof(JSValue) * argc) : nullptr;\r\n\r\n\tfor (int i = 0; i < argc; i++)\r\n\t{\r\n\t\targv[i] = runtime->AddValue(context, info[i]);\r\n\t}\r\n\r\n\tJSValue rval = wrapper->_funcMagic(wrapper->_context, this_obj, argc, argv, wrapper->_magic);\r\n\t_SetReturnValue(context, runtime, info, rval);\r\n\tfor (int i = 0; i < argc; i++)\r\n\t{\r\n\t\truntime->FreeValue(argv[i]);\r\n\t}\r\n\truntime->FreeValue(this_obj);\r\n}\r\n\r\nstatic void JSCFunctionCallback(const v8::FunctionCallbackInfo<v8::Value>& info)\r\n{\r\n\tv8::Isolate* _isolate = info.GetIsolate();\r\n\tv8::Isolate::Scope isolateScope(_isolate);\r\n\tv8::HandleScope handleScope(_isolate);\r\n\r\n\tJSContext::JSCFunctionMagicWrapper* wrapper = reinterpret_cast<JSContext::JSCFunctionMagicWrapper*>(v8::Local<v8::External>::Cast(info.Data())->Value());\r\n\r\n\tv8::Local<v8::Context> context = wrapper->_context->Get();\r\n\tJSRuntime* runtime = wrapper->_context->_runtime;\r\n\tJSValue this_obj = runtime->AddObject(context, info.This());\r\n\tint argc = info.Length();\r\n\tJSValue* argv = argc > 0 ? (JSValue*)alloca(sizeof(JSValue) * argc) : nullptr;\r\n\r\n\tfor (int i = 0; i < argc; i++)\r\n\t{\r\n\t\targv[i] = runtime->AddValue(context, info[i]);\r\n\t}\r\n\r\n\tJSValue rval = wrapper->_func(wrapper->_context, this_obj, argc, argv);\r\n\t_SetReturnValue(context, runtime, info, rval);\r\n\tfor (int i = 0; i < argc; i++)\r\n\t{\r\n\t\truntime->FreeValue(argv[i]);\r\n\t}\r\n\truntime->FreeValue(this_obj);\r\n}\r\n\r\nstatic void JSCFunctionGetterMagicCallback(const v8::FunctionCallbackInfo<v8::Value>& info)\r\n{\r\n\tv8::Isolate* _isolate = info.GetIsolate();\r\n\tv8::Isolate::Scope isolateScope(_isolate);\r\n\tv8::HandleScope handleScope(_isolate);\r\n\r\n\tJSContext::JSCFunctionMagicWrapper* wrapper = reinterpret_cast<JSContext::JSCFunctionMagicWrapper*>(v8::Local<v8::External>::Cast(info.Data())->Value());\r\n\r\n\tv8::Local<v8::Context> context = wrapper->_context->Get();\r\n\tJSRuntime* runtime = wrapper->_context->_runtime;\r\n\tJSValue this_obj = runtime->AddObject(context, info.This());\r\n\r\n\tJSValue rval = wrapper->_getterMagic(wrapper->_context, this_obj, wrapper->_magic);\r\n\t_SetReturnValue(context, runtime, info, rval);\r\n\truntime->FreeValue(this_obj);\r\n}\r\n\r\nstatic void JSCFunctionGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)\r\n{\r\n\tv8::Isolate* _isolate = info.GetIsolate();\r\n\tv8::Isolate::Scope isolateScope(_isolate);\r\n\tv8::HandleScope handleScope(_isolate);\r\n\r\n\tJSContext::JSCFunctionMagicWrapper* wrapper = reinterpret_cast<JSContext::JSCFunctionMagicWrapper*>(v8::Local<v8::External>::Cast(info.Data())->Value());\r\n\r\n\tv8::Local<v8::Context> context = wrapper->_context->Get();\r\n\tJSRuntime* runtime = wrapper->_context->_runtime;\r\n\tJSValue this_obj = runtime->AddObject(context, info.This());\r\n\r\n\tJSValue rval = wrapper->_getter(wrapper->_context, this_obj);\r\n\t_SetReturnValue(context, runtime, info, rval);\r\n\truntime->FreeValue(this_obj);\r\n}\r\n\r\nstatic void JSCFunctionSetterMagicCallback(const v8::FunctionCallbackInfo<v8::Value>& info)\r\n{\r\n\tv8::Isolate* _isolate = info.GetIsolate();\r\n\tv8::Isolate::Scope isolateScope(_isolate);\r\n\tv8::HandleScope handleScope(_isolate);\r\n\r\n\tJSContext::JSCFunctionMagicWrapper* wrapper = reinterpret_cast<JSContext::JSCFunctionMagicWrapper*>(v8::Local<v8::External>::Cast(info.Data())->Value());\r\n\r\n\tv8::Local<v8::Context> context = wrapper->_context->Get();\r\n\tJSRuntime* runtime = wrapper->_context->_runtime;\r\n\tJSValue this_obj = runtime->AddObject(context, info.This());\r\n\tJSValue val = info.Length() == 1 ? runtime->AddValue(context, info[0]) : JS_UNDEFINED;\r\n\r\n\tJSValue rval = wrapper->_setterMagic(wrapper->_context, this_obj, val, wrapper->_magic);\r\n\t_SetReturnValue(context, runtime, info, rval);\r\n\truntime->FreeValue(this_obj);\r\n\truntime->FreeValue(val);\r\n}\r\n\r\nstatic void JSCFunctionSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)\r\n{\r\n\tv8::Isolate* _isolate = info.GetIsolate();\r\n\tv8::Isolate::Scope isolateScope(_isolate);\r\n\tv8::HandleScope handleScope(_isolate);\r\n\r\n\tJSContext::JSCFunctionMagicWrapper* wrapper = reinterpret_cast<JSContext::JSCFunctionMagicWrapper*>(v8::Local<v8::External>::Cast(info.Data())->Value());\r\n\r\n\tv8::Local<v8::Context> context = wrapper->_context->Get();\r\n\tJSRuntime* runtime = wrapper->_context->_runtime;\r\n\tJSValue this_obj = runtime->AddObject(context, info.This());\r\n\tJSValue val = info.Length() == 1 ? runtime->AddValue(context, info[0]) : JS_UNDEFINED;\r\n\r\n\tJSValue rval = wrapper->_setter(wrapper->_context, this_obj, val);\r\n\t_SetReturnValue(context, runtime, info, rval);\r\n\truntime->FreeValue(this_obj);\r\n\truntime->FreeValue(val);\r\n}\r\n\r\nJSContext::JSContext(JSRuntime* runtime)\r\n\t:_debugServer(), _runtime(runtime), _logCallback(nullptr), _waingForDebuggerCallback(nullptr)\r\n{\r\n\tv8::Local<v8::Context> context = v8::Context::New(_runtime->_isolate);\r\n\tv8::Context::Scope contextScope(context);\r\n\tcontext->SetAlignedPointerInEmbedderData(JS_CONTEXT_DATA_SELF, this);\r\n\t_context.Reset(_runtime->_isolate, context); // = v8::UniquePersistent<v8::Context>(_runtime->_isolate, context);\r\n\r\n\tv8::Local<v8::Object> global = context->Global();\r\n\r\n#if defined(JSB_EXEC_TEST)\r\n\tglobal->Set(context, v8::String::NewFromUtf8Literal(_runtime->_isolate, \"print\"), v8::Function::New(context, _print).ToLocalChecked()).Check();\r\n#endif\r\n\t_global = _runtime->AddObject(context, global);\r\n\t_emptyString = _runtime->AddString(context, v8::String::NewFromUtf8Literal(_runtime->_isolate, \"\"));\r\n\t_runtime->SetContext(this);\r\n}\r\n\r\nJSContext::~JSContext()\r\n{\r\n\tCloseDebugger();\r\n\tsize_t size = _functionMagicWrappers.size();\r\n\tfor (size_t i = 0; i < size; ++i)\r\n\t{\r\n\t\t_runtime->mem_free(nullptr, _functionMagicWrappers[i]);\r\n\t}\r\n\t_runtime->FreeValue(_emptyString);\r\n\t_runtime->FreeValue(_global);\r\n\t_runtime->SetContext(nullptr);\r\n\t_context.Reset();\r\n}\r\n\r\nvoid JSContext::OpenDebugger(int port)\r\n{\r\n\t_debugServer.reset(WSServer::CreateDebugServer(this, port));\r\n}\r\n\r\nbool JSContext::IsDebuggerOpen()\r\n{\r\n\treturn !!_debugServer;\r\n}\r\n\r\nbool JSContext::IsDebuggerConnected()\r\n{\r\n\treturn _debugServer && _debugServer->IsConnected();\r\n}\r\n\r\nvoid JSContext::CloseDebugger()\r\n{\r\n\t_debugServer.reset();\r\n}\r\n\r\nstd::string JSContext::GetAtomString(JSAtom atom)\r\n{\r\n\tv8::MaybeLocal<v8::String> maybe_value = _runtime->GetAtomValue(atom);\r\n\tv8::Local<v8::String> value;\r\n\tif (maybe_value.ToLocal(&value))\r\n\t{\r\n\t\tv8::String::Utf8Value utf8_value(_runtime->_isolate, value);\r\n\t\treturn *utf8_value;\r\n\t}\r\n\treturn {};\r\n}\r\n\r\nJSValue JSContext::AtomToValue(JSAtom atom)\r\n{\r\n\tv8::MaybeLocal<v8::String> maybe_value = _runtime->GetAtomValue(atom);\r\n\tv8::Local<v8::String> value;\r\n\tif (maybe_value.ToLocal(&value))\r\n\t{\r\n\t\treturn _runtime->AddString(Get(), value);\r\n\t\t//return JS_MKPTR(JS_TAG_STRING, (size_t)atom);\r\n\t}\r\n\treturn JS_UNDEFINED;\r\n}\r\n\r\nv8::Local<v8::Context> JSContext::Get()\r\n{\r\n\treturn _context.Get(_runtime->_isolate);\r\n}\r\n\r\nv8::Isolate* JSContext::GetIsolate()\r\n{\r\n\treturn _runtime->_isolate;\r\n}\r\n\r\nJSValue JSContext::GetGlobal()\r\n{\r\n\treturn _runtime->DupValue(_global);\r\n}\r\n\r\nJSValue JSContext::GetEmptyString()\r\n{\r\n\treturn _runtime->DupValue(_emptyString);\r\n}\r\n\r\nJSValue JSContext::NewArray()\r\n{\r\n\tv8::Context::Scope contextScope(Get());\r\n\tv8::Local<v8::Array> array_value = v8::Array::New(GetIsolate());\r\n\treturn _runtime->AddObject(Get(), array_value);\r\n}\r\n\r\nJSValue JSContext::NewObject()\r\n{\r\n\tv8::Context::Scope contextScope(Get());\r\n\tv8::Local<v8::Object> object_value = v8::Object::New(GetIsolate());\r\n\treturn _runtime->AddObject(Get(), object_value);\r\n}\r\n\r\nJSValue JSContext::NewObjectProtoClass(v8::Local<v8::Object> new_target, JSClassDef* classDef)\r\n{\r\n\tv8::Isolate* isolate = GetIsolate();\r\n\tv8::Local<v8::Context> context = Get();\r\n\tv8::Context::Scope contextScope(context);\r\n\tv8::Local<v8::FunctionTemplate> _class = classDef->_class.Get(isolate);\r\n\r\n\tv8::Local<v8::Object> prototype = new_target;\r\n\tv8::Local<v8::Object> instance = _class->GetFunction(context).ToLocalChecked()->NewInstance(context).ToLocalChecked();\r\n\tinstance->SetPrototype(context, prototype).Check();\r\n\treturn _runtime->AddGCObject(context, instance, classDef);\r\n}\r\n\r\nJSValue JSContext::NewCFunctionMagic(JSCFunctionMagic* func, JSAtom atom, int length, JSCFunctionEnum cproto, int magic)\r\n{\r\n\tJSCFunctionMagicWrapper* wrapper = (JSCFunctionMagicWrapper*)_runtime->mem_alloc(nullptr, sizeof(JSCFunctionMagicWrapper));\r\n\twrapper->_context = this;\r\n\twrapper->_magic = magic;\r\n\twrapper->_funcMagic = func;\r\n\t_functionMagicWrappers.push_back(wrapper);\r\n\tv8::Local<v8::Context> context = Get();\r\n\tv8::Context::Scope contextScope(context);\r\n\tv8::Local<v8::External> data = v8::External::New(_runtime->_isolate, wrapper);\r\n\t\r\n\tswitch (cproto)\r\n\t{\r\n\t\tcase JS_CFUNC_constructor_magic:\r\n\t\t{\r\n\t\t\tv8::Local<v8::FunctionTemplate> function_template = v8::FunctionTemplate::New(GetIsolate(), JSCFunctionConstructorMagicCallback, data, {}, length);\r\n\t\t\tv8::MaybeLocal<v8::Function> func_o = function_template->GetFunction(context);\r\n\t\t\t// v8::MaybeLocal<v8::Function> func_o = v8::Function::New(context, JSCFunctionConstructorMagicCallback, data, length);\r\n\t\t\tv8::Local<v8::Function> func_v;\r\n\t\t\tif (func_o.ToLocal(&func_v))\r\n\t\t\t{\r\n\t\t\t\treturn _runtime->AddObject(context, func_v);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase JS_CFUNC_generic_magic:\r\n\t\t{\r\n\t\t\tv8::MaybeLocal<v8::Function> func_o = v8::Function::New(context, JSCFunctionMagicCallback, data, length);\r\n\t\t\tv8::Local<v8::Function> func_v;\r\n\t\t\tif (func_o.ToLocal(&func_v))\r\n\t\t\t{\r\n\t\t\t\treturn _runtime->AddObject(context, func_v);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase JS_CFUNC_getter_magic:\r\n\t\t{\r\n\t\t\tv8::MaybeLocal<v8::Function> func_o = v8::Function::New(context, JSCFunctionGetterMagicCallback, data, length);\r\n\t\t\tv8::Local<v8::Function> func_v;\r\n\t\t\tif (func_o.ToLocal(&func_v))\r\n\t\t\t{\r\n\t\t\t\treturn _runtime->AddObject(context, func_v);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase JS_CFUNC_setter_magic:\r\n\t\t{\r\n\t\t\tv8::MaybeLocal<v8::Function> func_o = v8::Function::New(context, JSCFunctionSetterMagicCallback, data, length);\r\n\t\t\tv8::Local<v8::Function> func_v;\r\n\t\t\tif (func_o.ToLocal(&func_v))\r\n\t\t\t{\r\n\t\t\t\treturn _runtime->AddObject(context, func_v);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tdefault: \r\n\t\t{\r\n\t\t\treturn _runtime->ThrowError(context, \"unsupported function enum\");\r\n\t\t}\r\n\t}\r\n\r\n\treturn _runtime->ThrowError(context, \"failed to make function\");\r\n\t\r\n}\r\n\r\nJSValue JSContext::NewCFunction(JSCFunction* func, JSAtom atom, int length, JSCFunctionEnum cproto)\r\n{\r\n\tv8::Context::Scope contextScope(Get());\r\n\tJSCFunctionMagicWrapper* wrapper = (JSCFunctionMagicWrapper*)_runtime->mem_alloc(nullptr, sizeof(JSCFunctionMagicWrapper));\r\n\twrapper->_context = this;\r\n\twrapper->_func = func;\r\n\twrapper->_magic = 0;\r\n\t_functionMagicWrappers.push_back(wrapper);\r\n\tv8::Local<v8::External> data = v8::External::New(_runtime->_isolate, wrapper);\r\n\tv8::Local<v8::Context> context = Get();\r\n\r\n\tswitch (cproto)\r\n\t{\r\n\tcase JS_CFUNC_generic:\r\n\t{\r\n\t\tv8::MaybeLocal<v8::Function> func_o = v8::Function::New(Get(), JSCFunctionCallback, data, length);\r\n\t\tv8::Local<v8::Function> func_v;\r\n\t\tif (func_o.ToLocal(&func_v))\r\n\t\t{\r\n\t\t\treturn _runtime->AddObject(context, func_v);\r\n\t\t}\r\n\t\tbreak;\r\n\t}\r\n\tcase JS_CFUNC_getter:\r\n\t{\r\n\t\tv8::MaybeLocal<v8::Function> func_o = v8::Function::New(Get(), JSCFunctionGetterCallback, data, length);\r\n\t\tv8::Local<v8::Function> func_v;\r\n\t\tif (func_o.ToLocal(&func_v))\r\n\t\t{\r\n\t\t\treturn _runtime->AddObject(context, func_v);\r\n\t\t}\r\n\t\tbreak;\r\n\t}\r\n\tcase JS_CFUNC_setter:\r\n\t{\r\n\t\tv8::MaybeLocal<v8::Function> func_o = v8::Function::New(Get(), JSCFunctionSetterCallback, data, length);\r\n\t\tv8::Local<v8::Function> func_v;\r\n\t\tif (func_o.ToLocal(&func_v))\r\n\t\t{\r\n\t\t\treturn _runtime->AddObject(context, func_v);\r\n\t\t}\r\n\t\tbreak;\r\n\t}\r\n\tdefault:\r\n\t{\r\n\t\treturn _runtime->ThrowError(context, \"unsupported function enum\");\r\n\t}\r\n\t}\r\n\r\n\treturn _runtime->ThrowError(context, \"failed to make function\");\r\n}\r\n\r\nJSValue JSContext::GetPropertyStr(JSValueConst this_obj, const char* prop)\r\n{\r\n\tv8::MaybeLocal<v8::Value> maybe_value = _runtime->GetValue(this_obj);\r\n\tv8::Local<v8::Value> value;\r\n\tv8::Local<v8::Context> context = Get();\r\n\r\n\tif (maybe_value.ToLocal(&value) && value->IsObject())\r\n\t{\r\n\t\tv8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(value);\r\n\t\tv8::MaybeLocal<v8::String> pkey = v8::String::NewFromUtf8(GetIsolate(), prop);\r\n\t\tif (!pkey.IsEmpty())\r\n\t\t{\r\n\t\t\tv8::MaybeLocal<v8::Value> maybe_res = obj->Get(context, pkey.ToLocalChecked());\r\n\t\t\tv8::Local<v8::Value> res;\r\n\t\t\tif (maybe_res.ToLocal(&res))\r\n\t\t\t{\r\n\t\t\t\treturn _runtime->AddValue(context, res);\r\n\t\t\t}\r\n\t\t\treturn _runtime->ThrowError(context, \"failed to call Object::Has()\");\r\n\t\t}\r\n\t\treturn _runtime->ThrowError(context, \"GetPropertyStr: no such JSAtom\");\r\n\t}\r\n\treturn _runtime->ThrowError(context, \"not an object\");\r\n}\r\n\r\nJSValue JSContext::GetProperty(JSValueConst this_obj, JSAtom prop)\r\n{\r\n\treturn GetPropertyInternal(this_obj, prop, this_obj, FALSE);\r\n}\r\n\r\nJSValue JSContext::GetPropertyUint32(JSValueConst this_obj, uint32_t idx)\r\n{\r\n\tv8::MaybeLocal<v8::Value> maybe_value = _runtime->GetValue(this_obj);\r\n\tv8::Local<v8::Value> value;\r\n\tv8::Local<v8::Context> context = Get();\r\n\r\n\tif (maybe_value.ToLocal(&value) && value->IsObject())\r\n\t{\r\n\t\tv8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(value);\r\n\t\tv8::MaybeLocal<v8::Value> maybe_res = obj->Get(context, idx);\r\n\t\tv8::Local<v8::Value> res;\r\n\t\tif (maybe_res.ToLocal(&res))\r\n\t\t{\r\n\t\t\treturn _runtime->AddValue(context, res);\r\n\t\t}\r\n\t\treturn _runtime->ThrowError(context, \"failed to call Object::Has()\");\r\n\t}\r\n\treturn _runtime->ThrowError(context, \"not an object\");\r\n}\r\n\r\nJSValue JSContext::GetPropertyInternal(JSValueConst this_obj, JSAtom prop, JSValueConst receiver, JS_BOOL throw_ref_error)\r\n{\r\n\tv8::MaybeLocal<v8::Value> maybe_value = _runtime->GetValue(this_obj);\r\n\tv8::Local<v8::Value> value;\r\n\tv8::Local<v8::Context> context = Get();\r\n\r\n\tif (maybe_value.ToLocal(&value) && value->IsObject())\r\n\t{\r\n\t\tv8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(value);\r\n\t\tv8::MaybeLocal<v8::String> pkey = _runtime->GetAtomValue(prop);\r\n\t\tif (!pkey.IsEmpty())\r\n\t\t{\r\n\t\t\tv8::MaybeLocal<v8::Value> maybe_res = obj->Get(context, pkey.ToLocalChecked());\r\n\t\t\tv8::Local<v8::Value> res;\r\n\t\t\tif (maybe_res.ToLocal(&res))\r\n\t\t\t{\r\n\t\t\t\treturn _runtime->AddValue(context, res);\r\n\t\t\t}\r\n\t\t\tif (throw_ref_error)\r\n\t\t\t{\r\n\t\t\t\treturn _runtime->ThrowError(context, \"failed to call Object::Has()\");\r\n\t\t\t}\r\n\t\t\treturn JS_UNDEFINED;\r\n\t\t}\r\n\t\treturn _runtime->ThrowError(context, \"GetPropertyInternal: no such JSAtom\");\r\n\t}\r\n\treturn _runtime->ThrowError(context, \"not an object\");\r\n}\r\n\r\nint JSContext::HasProperty(JSValueConst this_obj, JSAtom prop)\r\n{\r\n\tv8::MaybeLocal<v8::Value> maybe_value = _runtime->GetValue(this_obj);\r\n\tv8::Local<v8::Value> value;\r\n\tv8::Local<v8::Context> context = Get();\r\n\r\n\tif (maybe_value.ToLocal(&value) && value->IsObject())\r\n\t{\r\n\t\tv8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(value);\r\n\t\tv8::MaybeLocal<v8::String> pkey = _runtime->GetAtomValue(prop);\r\n\t\tif (!pkey.IsEmpty())\r\n\t\t{\r\n\t\t\tv8::Maybe<bool> maybe_res = obj->Has(context, pkey.ToLocalChecked());\r\n\t\t\treturn maybe_res.FromMaybe(false) ? 1 : 0;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t_runtime->ThrowError(context, \"HasProperty: no such JSAtom\");\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\t_runtime->ThrowError(context, \"not an object\");\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\nint JSContext::SetPropertyUint32(JSValueConst this_obj, uint32_t idx, JSValue val)\r\n{\r\n\tv8::MaybeLocal<v8::Value> maybe_value = _runtime->GetValue(this_obj);\r\n\tv8::Local<v8::Value> value;\r\n\tv8::Local<v8::Context> context = Get();\r\n\r\n\tif (maybe_value.ToLocal(&value) && value->IsObject())\r\n\t{\r\n\t\tv8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(value);\r\n\t\tv8::MaybeLocal<v8::Value> maybe_pvalue = _runtime->GetValue(val);\r\n\t\tv8::Local<v8::Value> pvalue;\r\n\t\tif (maybe_pvalue.ToLocal(&pvalue))\r\n\t\t{\r\n\t\t\tv8::Maybe<bool> maybe_res = obj->Set(context, idx, pvalue);\r\n\r\n\t\t\t_runtime->FreeValue(val);\r\n\t\t\treturn maybe_res.FromMaybe(false) ? 1 : 0;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t_runtime->ThrowError(context, \"SetPropertyUint32: no such JSAtom\");\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\t_runtime->ThrowError(context, \"not an object\");\r\n\t}\r\n\t_runtime->FreeValue(val);\r\n\treturn -1;\r\n}\r\n\r\nint JSContext::SetPropertyInternal(JSValueConst this_obj, JSAtom prop, JSValue val, int flags)\r\n{\r\n\tv8::MaybeLocal<v8::Value> maybe_this = _runtime->GetValue(this_obj);\r\n\tv8::Local<v8::Context> context = Get();\r\n\tv8::Context::Scope contextScope(context);\r\n\r\n\tv8::Local<v8::Value> thiz;\r\n\tif (maybe_this.ToLocal(&thiz) && thiz->IsObject())\r\n\t{\r\n\t\tv8::MaybeLocal<v8::String> maybe_key = _runtime->GetAtomValue(prop);\r\n\t\tv8::Local<v8::String> key;\r\n\t\tif (maybe_key.ToLocal(&key))\r\n\t\t{\r\n\t\t\tv8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(thiz);\r\n\t\t\tv8::MaybeLocal<v8::Value> maybe_pvalue = _runtime->GetValue(val);\r\n\t\t\tv8::Local<v8::Value> pvalue;\r\n\t\t\tif (maybe_pvalue.ToLocal(&pvalue))\r\n\t\t\t{\r\n\t\t\t\tv8::Maybe<bool> maybe_res = obj->Set(context, key, pvalue);\r\n\t\t\t\t_runtime->FreeValue(val);\r\n\t\t\t\treturn maybe_res.FromMaybe(false) ? 1 : 0;\r\n\t\t}\r\n\t\t\telse \r\n\t\t\t{\r\n\t\t\t\t_runtime->ThrowError(context, \"failed to get value\");\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t_runtime->ThrowError(context, \"SetPropertyInternal: no such JSAtom\");\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\t_runtime->ThrowError(context, \"not an object\");\r\n\t}\r\n\t_runtime->FreeValue(val);\r\n\treturn -1;\r\n}\r\n\r\nstatic v8::Local<v8::Function> GetFunction(v8::MaybeLocal<v8::Value> value)\r\n{\r\n\tv8::Local<v8::Value> t;\r\n\tif (value.ToLocal(&t) && t->IsFunction())\r\n\t{\r\n\t\treturn v8::Local<v8::Function>::Cast(t);\r\n\t}\r\n\treturn {};\r\n}\r\n\r\nint JSContext::DefineProperty(JSValueConst this_obj, JSAtom prop, JSValueConst getter, JSValueConst setter, int flags)\r\n{\r\n\tv8::MaybeLocal<v8::Value> maybe_value = _runtime->GetValue(this_obj);\r\n\tv8::Local<v8::Value> value;\r\n\tv8::Local<v8::Context> context = Get();\r\n\r\n\tif (maybe_value.ToLocal(&value) && value->IsObject())\r\n\t{\r\n\t\tv8::MaybeLocal<v8::String> pkey = _runtime->GetAtomValue(prop);\r\n\t\tif (!pkey.IsEmpty())\r\n\t\t{\r\n\t\t\tv8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(value);\r\n\t\t\tv8::MaybeLocal<v8::Value> maybe_getter = _runtime->GetValue(getter);\r\n\t\t\tv8::MaybeLocal<v8::Value> maybe_setter = _runtime->GetValue(setter);\r\n\r\n\t\t\tint attr = v8::None;\r\n\t\t\tif (!(flags & JS_PROP_CONFIGURABLE))\r\n\t\t\t{\r\n\t\t\t\tattr |= v8::DontDelete;\r\n\t\t\t}\r\n\t\t\tif (!(flags & JS_PROP_ENUMERABLE))\r\n\t\t\t{\r\n\t\t\t\tattr |= v8::DontEnum;\r\n\t\t\t}\r\n\t\t\tobj->SetAccessorProperty(pkey.ToLocalChecked(), GetFunction(maybe_getter), GetFunction(maybe_setter), \t(v8::PropertyAttribute)attr);\r\n\t\t\treturn 1;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t_runtime->ThrowError(context, \"DefineProperty: no such JSAtom\");\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\t_runtime->ThrowError(context, \"not an object\");\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\nint JSContext::DefinePropertyValue(JSValueConst this_obj, JSAtom prop, JSValue val, int flags)\r\n{\r\n\treturn SetPropertyInternal(this_obj, prop, val, flags);\r\n}\r\n\r\nJSValue JSContext::Eval(const char* input, size_t input_len, const char* filename, int eval_flags)\r\n{\r\n\tv8::Isolate* isolate = _runtime->_isolate;\r\n\tv8::Local<v8::Context> context = _context.Get(isolate);\r\n\tv8::Context::Scope contextScope(context);\r\n\r\n\tv8::TryCatch try_catch(isolate);\r\n\tv8::ScriptOrigin origin(isolate, v8::String::NewFromUtf8(isolate, filename).ToLocalChecked());\r\n\tv8::MaybeLocal<v8::String> source = v8::String::NewFromUtf8(isolate, input, v8::NewStringType::kNormal, (int)input_len);\r\n\tv8::MaybeLocal<v8::Script> script = v8::Script::Compile(context, source.ToLocalChecked(), &origin);\r\n\tif (try_catch.HasCaught())\r\n\t{\r\n\t\treturn _runtime->ThrowException(context, try_catch.Exception());\r\n\t}\r\n\tif (!script.IsEmpty())\r\n\t{\r\n\t\tv8::TryCatch try_catch(isolate);\r\n\t\tv8::MaybeLocal<v8::Value> maybe_value = script.ToLocalChecked()->Run(context);\r\n\t\tif (try_catch.HasCaught())\r\n\t\t{\r\n\t\t\treturn _runtime->ThrowException(context, try_catch.Exception());\r\n\t\t}\r\n\t\tv8::Local<v8::Value> value;\r\n\t\tif (maybe_value.ToLocal(&value))\r\n\t\t{\r\n\t\t\treturn _runtime->AddValue(context, value);\r\n\t\t}\r\n\t\treturn JS_UNDEFINED;\r\n\t}\r\n\r\n\treturn _runtime->ThrowError(context, \"failed to compile\");\r\n}\r\n\r\nJSValue JSContext::CallConstructor(JSValueConst func_obj, int argc, JSValueConst* argv)\r\n{\r\n\tv8::Local<v8::Context> context = Get();\r\n\tv8::MaybeLocal<v8::Value> maybe_value = _runtime->GetValue(func_obj);\r\n\tv8::Local<v8::Value> value;\r\n\tif (maybe_value.ToLocal(&value) && value->IsFunction())\r\n\t{\r\n\t\tv8::TryCatch try_catch(_runtime->_isolate);\r\n\t\tv8::Local<v8::Function> func_value = v8::Local<v8::Function>::Cast(value);\r\n\r\n\t\tstd::vector<v8::Local<v8::Value>> _args_;\r\n\t\tfor (int i = 0; i < argc; ++i)\r\n\t\t{\r\n\t\t\tv8::MaybeLocal<v8::Value> maybe_arg_value = _runtime->GetValue(argv[i]);\r\n\t\t\tv8::Local<v8::Value> arg_value;\r\n\t\t\tif (!maybe_arg_value.ToLocal(&arg_value))\r\n\t\t\t{\r\n\t\t\t\tstatic char errmsg[256];\r\n\t\t\t\tint errmsg_len = sprintf_s(errmsg, \"CallConstructor: translate failed %d:%lld:%zd\", i, argv[i].tag, argv[i].u.ptr);\r\n\t\t\t\treturn _runtime->ThrowError(context, errmsg, errmsg_len);\r\n\t\t\t}\r\n\t\t\t_args_.push_back(arg_value);\r\n\t\t}\r\n\t\tv8::MaybeLocal<v8::Value> func_retValues = func_value->CallAsConstructor(context, argc, _args_.data());\r\n\t\tif (try_catch.HasCaught())\r\n\t\t{\r\n\t\t\treturn _runtime->ThrowException(context, try_catch.Exception());\r\n\t\t}\r\n\t\tif (!func_retValues.IsEmpty())\r\n\t\t{\r\n\t\t\treturn _runtime->AddValue(context, func_retValues.ToLocalChecked());\r\n\t\t}\r\n\t\treturn _runtime->ThrowError(context, \"CallConstructor: failed to call\");\r\n\t}\r\n\r\n\treturn _runtime->ThrowError(context, \"CallConstructor: not a constructor function\");\r\n}\r\n\r\nJSValue JSContext::Call(JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst* argv)\r\n{\r\n\tv8::Local<v8::Context> context = Get();\r\n\tv8::Context::Scope contextScope(context);\r\n\tv8::MaybeLocal<v8::Value> maybe_value = _runtime->GetValue(func_obj);\r\n\tv8::Local<v8::Value> value;\r\n\tif (maybe_value.ToLocal(&value) && value->IsFunction())\r\n\t{\r\n\t\tv8::TryCatch try_catch(_runtime->_isolate);\r\n\t\tv8::Local<v8::Function> func_value = v8::Local<v8::Function>::Cast(value);\r\n\t\tstd::vector<v8::Local<v8::Value>> _args_;\r\n\t\tfor (int i = 0; i < argc; ++i)\r\n\t\t{\r\n\t\t\tv8::MaybeLocal<v8::Value> maybe_arg_value = _runtime->GetValue(argv[i]);\r\n\t\t\tv8::Local<v8::Value> arg_value;\r\n\t\t\tif (!maybe_arg_value.ToLocal(&arg_value))\r\n\t\t\t{\r\n\t\t\t\tstatic char errmsg[256];\r\n\t\t\t\tint errmsg_len = sprintf_s(errmsg, \"Call: translate failed %d:%lld:%zd\", i, argv[i].tag, argv[i].u.ptr);\r\n\t\t\t\treturn _runtime->ThrowError(context, errmsg, errmsg_len);\r\n\t\t\t}\r\n\t\t\t_args_.push_back(arg_value);\r\n\t\t}\r\n\t\tv8::Local<v8::Value> this_val = _runtime->GetValue(this_obj).ToLocalChecked();\r\n\t\tv8::MaybeLocal<v8::Value> func_retValues = func_value->Call(context, this_val, argc, _args_.data());\r\n\t\tif (try_catch.HasCaught())\r\n\t\t{\r\n\t\t\treturn _runtime->ThrowException(context, try_catch.Exception());\r\n\t\t}\r\n\t\tif (!func_retValues.IsEmpty())\r\n\t\t{\r\n\t\t\treturn _runtime->AddValue(context, func_retValues.ToLocalChecked());\r\n\t\t}\r\n\t\treturn JS_UNDEFINED;\r\n\t}\r\n\treturn _runtime->ThrowError(context, \"Call: not a function\");\r\n}\r\n\r\nstatic void _JSPromiseResolveCallback(const v8::FunctionCallbackInfo<v8::Value>& info)\r\n{\r\n\tv8::Isolate* _isolate = info.GetIsolate();\r\n\tv8::Isolate::Scope isolateScope(_isolate);\r\n\tv8::HandleScope handleScope(_isolate);\r\n\r\n\tv8::Local<v8::Context> context = info.GetIsolate()->GetCurrentContext();\r\n\tv8::Local<v8::Value> value = info.Data();\r\n\tv8::Local<v8::Promise::Resolver> resolver = v8::Local<v8::Promise::Resolver>::Cast(value);\r\n\tif (info.Length() > 0)\r\n\t{\r\n\t\tv8::Maybe<bool> res = resolver->Resolve(context, info[0]);\r\n\t\tif (res.IsJust())\r\n\t\t{\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\tv8::Maybe<bool> res = resolver->Resolve(context, v8::Undefined(_isolate));\r\n\t\tif (res.IsJust())\r\n\t\t{\r\n\t\t}\r\n\t}\r\n}\r\n\r\nstatic void _JSPromiseRejectCallback(const v8::FunctionCallbackInfo<v8::Value>& info)\r\n{\r\n\tv8::Isolate* _isolate = info.GetIsolate();\r\n\tv8::Isolate::Scope isolateScope(_isolate);\r\n\tv8::HandleScope handleScope(_isolate);\r\n\r\n\tv8::Local<v8::Context> context = info.GetIsolate()->GetCurrentContext();\r\n\tv8::Local<v8::Value> value = info.Data();\r\n\tv8::Local<v8::Promise::Resolver> resolver = v8::Local<v8::Promise::Resolver>::Cast(value);\r\n\t\r\n\tif (info.Length() > 0)\r\n\t{\r\n\t\tv8::Maybe<bool> res = resolver->Reject(context, info[0]);\r\n\t\tif (res.IsJust())\r\n\t\t{\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\tv8::Maybe<bool> res = resolver->Reject(context, v8::Undefined(_isolate));\r\n\t\tif (res.IsJust())\r\n\t\t{\r\n\t\t}\r\n\t}\r\n}\r\n\r\nJSValue JSContext::NewPromiseCapability(JSValue* resolving_funcs)\r\n{\r\n\tv8::Local<v8::Context> context = Get();\r\n\tv8::Context::Scope contextScope(context);\r\n\tv8::MaybeLocal<v8::Promise::Resolver> maybe_resolver = v8::Promise::Resolver::New(context);\r\n\tif (maybe_resolver.IsEmpty())\r\n\t{\r\n\t\treturn _runtime->ThrowError(context, \"failed to create promise\");\r\n\t}\r\n\tv8::Local<v8::Promise::Resolver> resolver = maybe_resolver.ToLocalChecked();\r\n\tv8::Local<v8::Promise> promise = resolver->GetPromise();\r\n\r\n\tresolving_funcs[0] = _runtime->AddObject(context, v8::Function::New(context, _JSPromiseResolveCallback, resolver, 1).ToLocalChecked());\r\n\tresolving_funcs[1] = _runtime->AddObject(context, v8::Function::New(context, _JSPromiseRejectCallback, resolver, 1).ToLocalChecked());\r\n\treturn _runtime->AddObject(context, promise);\r\n}\r\n"
  },
  {
    "path": "jsb_build/v8-bridge/src/JSInspectorClient.cpp",
    "content": "#include <v8-inspector.h>\r\n#include <v8.h>\r\n\r\n#include \"JSContext.h\"\r\n#include \"JSInspectorClient.h\"\r\n\r\n#include <codecvt>\r\n#include <cuchar>\r\n#include <locale>\r\n#define WIN32_LEAN_AND_MEAN\r\n#include <Windows.h>\r\n\r\nclass JSInspectorClient : public JSDebugger, public v8_inspector::V8InspectorClient\r\n{\r\n\tclass JSInspectorChannel : public v8_inspector::V8Inspector::Channel\r\n\t{\r\n\tpublic:\r\n\t\tJSInspectorChannel(JSInspectorClient* client, int groupId);\r\n\t\tvirtual ~JSInspectorChannel();\r\n\r\n\t\tvoid Initialize();\r\n\t\tvoid OnMessageReceived(const unsigned char* buf, size_t len);\r\n\t\tvoid OnConnectionClosed();\r\n\r\n\t\tvirtual void sendResponse(int callId, std::unique_ptr<v8_inspector::StringBuffer> message) override;\r\n\t\tvirtual void sendNotification(std::unique_ptr<v8_inspector::StringBuffer> message) override;\r\n\t\tvirtual void flushProtocolNotifications() override;\r\n\tprivate:\r\n\t\tvoid SendString(v8_inspector::StringView view);\r\n\r\n\t\tint _groupId;\r\n\t\tJSInspectorClient* _client;\r\n\t\tstd::unique_ptr<v8_inspector::V8InspectorSession> _session;\r\n\t};\r\n\r\n\tenum EClientState\r\n\t{\r\n\t\tECS_NONE,\r\n\t\tECS_READY,\r\n\t\tECS_PAUSED,\r\n\t};\r\npublic:\r\n\tJSInspectorClient(JSContext* ctx, JSDebuggerCallbacks callbacks);\r\n\tvirtual ~JSInspectorClient();\r\n\r\n\tvirtual void runMessageLoopOnPause(int contextGroupId) override;\r\n\tvirtual void quitMessageLoopOnPause() override;\r\n\tvirtual void runIfWaitingForDebugger(int contextGroupId) override;\r\n\r\n\tvirtual void Open() override;\r\n\tvirtual void Close() override;\r\n\tvirtual void Update() override;\r\n\tvirtual bool IsConnected() override;\r\n\tvirtual void OnConnectionClosed() override;\r\n\tvirtual void OnMessageReceived(const unsigned char* buf, size_t len) override;\r\nprivate:\r\n\tstd::unique_ptr<v8_inspector::V8Inspector> _inspector;\r\n\tJSDebuggerCallbacks _callbacks;\r\n\tJSContext* _ctx;\r\n\tstd::unique_ptr<JSInspectorChannel> _channel;\r\n\tEClientState _state;\r\n\tbool _isConnected;\r\n\tbool _isWaiting;\r\n};\r\n\r\nJSDebugger* JSDebugger::CreateDefaultDebugger(JSContext* ctx, JSDebuggerCallbacks callbacks)\r\n{\r\n\treturn new JSInspectorClient(ctx, callbacks);\r\n}\r\n\r\nJSInspectorClient::JSInspectorChannel::JSInspectorChannel(JSInspectorClient* client, int groupId)\r\n\t:_client(client), _groupId(groupId)\r\n{\r\n\tv8_inspector::StringView state;\r\n\t_session = client->_inspector->connect(groupId, this, state);\r\n}\r\n\r\nJSInspectorClient::JSInspectorChannel::~JSInspectorChannel()\r\n{\r\n\t_session.reset();\r\n}\r\n\r\nvoid JSInspectorClient::JSInspectorChannel::Initialize()\r\n{\r\n\t\r\n}\r\n\r\nvoid JSInspectorClient::JSInspectorChannel::OnConnectionClosed()\r\n{\r\n\tif (_session)\r\n\t{\r\n\t\t_session->setSkipAllPauses(true);\r\n\t\t_session->resume();\r\n\t}\r\n}\r\n\r\nvoid JSInspectorClient::JSInspectorChannel::OnMessageReceived(const unsigned char* buf, size_t len)\r\n{\r\n\tif (_session)\r\n\t{\r\n\t\tv8::Isolate* isolate = _client->_ctx->GetIsolate();\r\n\t\tv8::Isolate::Scope isolateScope(isolate);\r\n\t\tv8::HandleScope handleScope(isolate);\r\n\t\tv8::TryCatch try_catch(isolate);\r\n\r\n\t\tv8_inspector::StringView message(buf, len);\r\n\t\t_session->dispatchProtocolMessage(message);\r\n\t\tif (try_catch.HasCaught())\r\n\t\t{\r\n\t\t\t//printf(\"inspector exception: %s\\n\", buf);\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t//printf(\"inspector dispatch: %d\\n\", (int)len);\r\n\t}\r\n\telse\r\n\t{\r\n\t\t//printf(\"invalid session\\n\");\r\n\t}\r\n}\r\n\r\nvoid JSInspectorClient::JSInspectorChannel::SendString(v8_inspector::StringView view)\r\n{\r\n\tif (view.is8Bit())\r\n\t{\r\n\t\t_client->_callbacks.send(_client->_ctx, 0, view.characters8(), view.length());\r\n\t}\r\n\telse\r\n\t{\r\n\t\tint cap = WideCharToMultiByte(CP_UTF8, 0, (LPCWCH)view.characters16(), view.length(), NULL, 0, NULL, NULL);\r\n\t\tif (cap > 0)\r\n\t\t{\r\n\t\t\tstd::string str(cap, 0);\r\n\t\t\tWideCharToMultiByte(CP_UTF8, 0, (LPCWCH)view.characters16(), view.length(), (LPSTR)str.c_str(), cap, NULL, NULL);\r\n\t\t\t_client->_callbacks.send(_client->_ctx, 0, reinterpret_cast<const unsigned char*>(str.c_str()), str.length());\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid JSInspectorClient::JSInspectorChannel::sendResponse(int callId, std::unique_ptr<v8_inspector::StringBuffer> message)\r\n{\r\n\tSendString(message->string());\r\n}\r\n\r\nvoid JSInspectorClient::JSInspectorChannel::sendNotification(std::unique_ptr<v8_inspector::StringBuffer> message)\r\n{\r\n\tSendString(message->string());\r\n}\r\n\r\nvoid JSInspectorClient::JSInspectorChannel::flushProtocolNotifications()\r\n{\r\n}\r\n\r\nJSInspectorClient::JSInspectorClient(JSContext* ctx, JSDebuggerCallbacks callbacks)\r\n\t:_ctx(ctx), _callbacks(callbacks), _state(ECS_NONE), _channel(nullptr), _isConnected(false), _isWaiting(true)\r\n{\r\n}\r\n\r\nJSInspectorClient::~JSInspectorClient()\r\n{\r\n\tClose();\r\n}\r\n\r\nvoid JSInspectorClient::runMessageLoopOnPause(int contextGroupId)\r\n{\r\n\tif (_state == ECS_READY)\r\n\t{\r\n\t\t_state = ECS_PAUSED;\r\n\t\twhile (_state == ECS_PAUSED)\r\n\t\t{\r\n\t\t\tUpdate();\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid JSInspectorClient::quitMessageLoopOnPause()\r\n{\r\n\tif (_state == ECS_PAUSED)\r\n\t{\r\n\t\t_state = ECS_READY;\r\n\t}\r\n}\r\n\r\nvoid JSInspectorClient::runIfWaitingForDebugger(int contextGroupId)\r\n{\r\n\t//printf(\"runIfWaitingForDebugger %d\\n\", _state);\r\n\t_isWaiting = false;\r\n\tif (_ctx && _ctx->_waingForDebuggerCallback)\r\n\t{\r\n\t\t_ctx->_waingForDebuggerCallback(_ctx);\r\n\t}\r\n}\r\n\r\nvoid JSInspectorClient::Open()\r\n{\r\n\tif (_state == ECS_NONE)\r\n\t{\r\n\t\tv8::Isolate* isolate = _ctx->GetIsolate();\r\n\t\tv8::Isolate::Scope isolateScope(isolate);\r\n\t\tv8::HandleScope handleScope(isolate);\r\n\r\n\t\tint contextGroupId = 1;\r\n\t\t_isConnected = true;\r\n\t\t_isWaiting = true;\r\n\t\t_inspector = v8_inspector::V8Inspector::create(isolate, this);\r\n\t\tconst uint8_t p_name[] = \"DefaultInsepctorContext\";\r\n\t\tv8_inspector::StringView name(p_name, sizeof(p_name) - 1);\r\n\t\t_channel.reset(new JSInspectorChannel(this, contextGroupId));\r\n\t\t_inspector->contextCreated(v8_inspector::V8ContextInfo(_ctx->Get(), contextGroupId, name));\r\n\t\t_state = ECS_READY;\r\n\t\t//printf(\"open inspector\\n\");\r\n\t}\r\n}\r\n\r\nvoid JSInspectorClient::Close()\r\n{\r\n\tif (_state != ECS_NONE)\r\n\t{\r\n\t\t_state = ECS_NONE;\r\n\t\t_isConnected = false;\r\n\t\t_isWaiting = false;\r\n\t\tv8::Isolate* isolate = _ctx->GetIsolate();\r\n\t\tv8::Isolate::Scope isolateScope(isolate);\r\n\t\tv8::HandleScope handleScope(isolate);\r\n\r\n\t\t_channel.reset();\r\n\t\t_inspector->contextDestroyed(_ctx->Get());\r\n\t\t_inspector.reset();\r\n\t\t//printf(\"close inspector\\n\");\r\n\t}\r\n}\r\n\r\nvoid JSInspectorClient::OnMessageReceived(const unsigned char* buf, size_t len)\r\n{\r\n\tif (_channel)\r\n\t{\r\n\t\t_channel->OnMessageReceived(buf, len);\r\n\t}\r\n}\r\n\r\nvoid JSInspectorClient::OnConnectionClosed()\r\n{\r\n\t_isConnected = false;\r\n\tif (_channel)\r\n\t{\r\n\t\t_channel->OnConnectionClosed();\r\n\t}\r\n\t//_channel.reset();\r\n}\r\n\r\nbool JSInspectorClient::IsConnected()\r\n{\r\n\treturn _isConnected && !_isWaiting;\r\n}\r\n\r\nvoid JSInspectorClient::Update()\r\n{\r\n\t_callbacks.update(_ctx);\r\n}\r\n"
  },
  {
    "path": "jsb_build/v8-bridge/src/JSRuntime.cpp",
    "content": "#include \"JSRuntime.h\"\r\n#include \"JSApi.h\"\r\n#include <cassert>\r\n#include <string>\r\n#include <libplatform/libplatform.h>\r\n\r\n#include \"JSContext.h\"\r\n#include \"WSServer.h\"\r\n\r\nstruct GlobalInitializer\r\n{\r\n\tstd::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();\r\n\r\n\tGlobalInitializer()\r\n\t{\r\n#if defined(JSB_DEBUG) && JSB_DEBUG\r\n\t\t\tstd::string args = \"--expose-gc\";\r\n\t\t\tv8::V8::SetFlagsFromString(args.c_str(), static_cast<int>(args.size()));\r\n#endif\r\n\t\tv8::V8::InitializePlatform(platform.get());\r\n\t\tv8::V8::Initialize();\r\n\t}\r\n};\r\n\r\nstatic GlobalInitializer _gInit;\r\n\r\nstatic void* default_malloc(JSMallocState* state, size_t size)\r\n{\r\n\treturn malloc(size);\r\n}\r\n\r\nstatic void* default_realloc(JSMallocState* state, void* buf, size_t size)\r\n{\r\n\treturn realloc(buf, size);\r\n}\r\n\r\nstatic void default_free(JSMallocState* state, void* buf)\r\n{\r\n\tfree(buf);\r\n}\r\n\r\nstatic size_t default_malloc_usable_size(const void* buf)\r\n{\r\n\treturn 0;\r\n}\r\n\r\nstatic void _PromiseRejectCallback(v8::PromiseRejectMessage message)\r\n{\r\n\tv8::Local<v8::Promise> promise = message.GetPromise();\r\n\tv8::Isolate* isolate = promise->GetIsolate();\r\n\tJSRuntime* rt = (JSRuntime*)isolate->GetData(JS_ISOLATE_DATA_SELF);\r\n\r\n\tif (rt->_promiseRejectionTracker)\r\n\t{\r\n\t\tv8::Isolate::Scope isolateScope(isolate);\r\n\t\tv8::HandleScope handleScope(isolate);\r\n\r\n\t\tv8::Local<v8::Value> value = message.GetValue();\r\n\t\tv8::PromiseRejectEvent rejectEvent = message.GetEvent();\r\n\t\tv8::Local<v8::Context> context = isolate->GetCurrentContext();\r\n\t\tJSContext* ctx = (JSContext*)context->GetAlignedPointerFromEmbedderData(JS_CONTEXT_DATA_SELF);\r\n\t\tJS_BOOL is_handled = rejectEvent == v8::kPromiseRejectWithNoHandler ? 0 : 1;\r\n\r\n\t\tJSValue promise_jsval = rt->AddObject(context, promise);\r\n\t\tJSValue reason_jsval = rt->AddValue(context, value);\r\n\t\trt->_promiseRejectionTracker(ctx, promise_jsval, reason_jsval, is_handled, rt->_promiseRejectionOpaque);\r\n\t\trt->FreeValue(promise_jsval);\r\n\t\trt->FreeValue(reason_jsval);\r\n\t}\r\n}\r\n\r\nJSRuntime::JSRuntime(JSGCObjectFinalizer* finalizer)\r\n: _arrayBufferAllocator(v8::ArrayBuffer::Allocator::NewDefaultAllocator())\r\n{\r\n\tmalloc_functions.js_malloc = default_malloc;\r\n\tmalloc_functions.js_free = default_free;\r\n\tmalloc_functions.js_realloc = default_realloc;\r\n\tmalloc_functions.js_malloc_usable_size = default_malloc_usable_size;\r\n\r\n\tv8::Isolate::CreateParams create_params;\r\n\tcreate_params.array_buffer_allocator = _arrayBufferAllocator;\r\n\t_isolate = v8::Isolate::New(create_params);\r\n\t_isolate->SetData(JS_ISOLATE_DATA_SELF, this);\r\n\t_isolate->SetPromiseRejectCallback(_PromiseRejectCallback);\r\n\t_objectRefs.emplace_back(JSValueRef());\r\n\t_atomRefs.emplace_back(JSAtomRef());\r\n\t_gcObjects.emplace_back(nullptr);\r\n\r\n\t{\r\n\t\tv8::Isolate::Scope isolateScope(_isolate);\r\n\t\tv8::HandleScope handleScope(_isolate);\r\n\r\n\t\t_PrivateCacheIndexKey.Reset(_isolate, v8::Private::New(_isolate, v8::String::NewFromUtf8Literal(_isolate, \"PrivateCacheIndex\")));\r\n\t\t_isolate->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit);\r\n#define DEF(name, str) \\\r\n\t\t{ JSAtom atom = GetAtom(str, sizeof(str) - 1); assert(atom._value == (uint32_t)JS_ATOM_##name); }\r\n\t\t#include \"quickjs-atom.h\"\r\n#undef DEF\r\n\r\n\t\tNewClass(JSB_GetBridgeClassID(), \"CSharpClass\", finalizer);\r\n\t}\r\n}\r\n\r\nJSRuntime::~JSRuntime() = default;\r\n\r\nJS_BOOL JSRuntime::Release()\r\n{\r\n\t_PrivateCacheIndexKey.Reset();\r\n#define DEF(name, str) \\\r\n\tFreeAtom((uint32_t)JS_ATOM_##name);\r\n#include \"quickjs-atom.h\"\r\n#undef DEF\r\n\r\n\t// cleanup gc objects\r\n\t{\r\n\t\tv8::Isolate::Scope isolateScope(_isolate);\r\n\t\tv8::HandleScope handleScope(_isolate);\r\n\t\tfor (GCObject* gcObject : _gcObjects)\r\n\t\t{\r\n\t\t\tif (gcObject && !gcObject->_obj.IsEmpty())\r\n\t\t\t{\r\n\t\t\t\tv8::Local<v8::Object> obj = gcObject->_obj.Get(_isolate);\r\n\t\t\t\tif (obj->InternalFieldCount() == EIFN_FieldCount)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (void* sv = obj->GetAlignedPointerFromInternalField(EIFN_Payload))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tobj->SetAlignedPointerInInternalField(EIFN_Payload, nullptr);\r\n\t\t\t\t\t\tif (JSGCObjectFinalizer* finalizer = gcObject->_classDef->_finalizer)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tJSPayloadHeader header = *static_cast<JSPayloadHeader*>(sv);\r\n\t\t\t\t\t\t\tfinalizer(this, header);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tmem_free(nullptr, sv);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (gcObject->_value_handle != 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tJSValueRef& valueRef = _objectRefs[gcObject->_value_handle];\r\n\t\t\t\t\tvalueRef._gc_handle = 0;\r\n\t\t\t\t\tif (valueRef._references == 0)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t--_aliveObjectNum;\r\n\t\t\t\t\t\tvalueRef._next = _freeObjectSlot;\r\n\t\t\t\t\t\t_freeObjectSlot = gcObject->_value_handle;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tgcObject->_obj.Reset();\r\n\t\t\t\tmem_free(nullptr, gcObject);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tJS_BOOL res = _aliveAtomNum == 0 && _aliveObjectNum == 0 ? TRUE : FALSE;\r\n\t_atomRefs.clear();\r\n\t_objectRefs.clear();\r\n\t_atoms.clear();\r\n\t_gcObjects.clear();\r\n\r\n\tfor (auto pair : _classes)\r\n\t{\r\n\t\tJSClassDef* def = pair.second;\r\n\t\tdef->_class.Reset();\r\n\t\tmem_free(nullptr, def);\r\n\t}\r\n\t_classes.clear();\r\n\t_exception.Reset();\r\n\t_isolate->Dispose();\r\n\tdelete _arrayBufferAllocator;\r\n\t//assert(res);\r\n\treturn res;\r\n}\r\n\r\nvoid JSRuntime::ComputeMemoryUsage(JSMemoryUsage* memoryUsage)\r\n{\r\n\tmemoryUsage->obj_count = _aliveObjectNum;\r\n\tmemoryUsage->atom_count = _aliveAtomNum;\r\n}\r\n\r\nvoid JSRuntime::SetContext(JSContext* context)\r\n{\r\n\t_context = context;\r\n}\r\n\r\nsize_t JSRuntime::_AddValueInternal(v8::Local<v8::Context> context, v8::Local<v8::Value> val, size_t gc_handle)\r\n{\r\n\tv8::Local<v8::Object> obj;\r\n\r\n\tif (val->IsObject())\r\n\t{\r\n\t\tobj = v8::Local<v8::Object>::Cast(val);\r\n\t\tv8::MaybeLocal<v8::Value> maybe_cacheIndex = obj->GetPrivate(context, _PrivateCacheIndexKey.Get(_isolate));\r\n\t\tv8::Local<v8::Value> cacheIndex;\r\n\t\tif (maybe_cacheIndex.ToLocal(&cacheIndex) && cacheIndex->IsInt32())\r\n\t\t{\r\n\t\t\tsize_t last_id = static_cast<size_t>(cacheIndex->ToInt32(context).ToLocalChecked()->Value());\r\n\t\t\tJSValueRef& valueRef = _objectRefs[last_id];\r\n\t\t\tif (valueRef._next == 0 && valueRef._references > 0 && valueRef._value == val)\r\n\t\t\t{\r\n\t\t\t\t++valueRef._references;\r\n\t\t\t\treturn last_id;\r\n\t\t\t}\r\n\r\n\t\t\t// resurrect\r\n\t\t\tif (gc_handle != 0 && valueRef._gc_handle == gc_handle && _gcObjects[valueRef._gc_handle]->_obj == val)\r\n\t\t\t{\r\n\t\t\t\t++valueRef._references;\r\n\t\t\t\t//printf(\"resurrect: JSValue is alive again %zd: %d (should be 1)\", last_id, valueRef._references);\r\n\t\t\t\treturn last_id;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tsize_t id;\r\n\t++_aliveObjectNum;\r\n\tif (_freeObjectSlot == 0)\r\n\t{\r\n\t\tJSValueRef valueRef(_isolate, val);\r\n\t\tid = _objectRefs.size();\r\n\t\tvalueRef._gc_handle = gc_handle;\r\n\t\t_objectRefs.emplace_back(valueRef);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tid = _freeObjectSlot;\r\n\t\tJSValueRef& valueRef = _objectRefs[id];\r\n\t\t_freeObjectSlot = valueRef._next;\r\n\t\tvalueRef._next = 0;\r\n\t\tvalueRef._value.Reset(_isolate, val);\r\n\t\tvalueRef._references = 1;\r\n\t\tvalueRef._gc_handle = gc_handle;\r\n\t}\r\n\r\n\tif (val->IsObject())\r\n\t{\r\n\t\tobj->SetPrivate(context, _PrivateCacheIndexKey.Get(_isolate), v8::Int32::New(_isolate, static_cast<int32_t>(id)));\r\n\t}\r\n\treturn id;\r\n}\r\n\r\nvoid* JSRuntime::mem_alloc(JSMallocState* s, size_t size)\r\n{\r\n\treturn malloc_functions.js_malloc(s, size);\r\n}\r\n\r\nvoid JSRuntime::mem_free(JSMallocState* s, void* ptr)\r\n{\r\n\tmalloc_functions.js_free(s, ptr);\r\n}\r\n\r\nvoid* JSRuntime::mem_realloc(JSMallocState* s, void* ptr, size_t size)\r\n{\r\n\treturn malloc_functions.js_realloc(s, ptr, size);\r\n}\r\n\r\nsize_t JSRuntime::mem_malloc_usable_size(const void* ptr)\r\n{\r\n\treturn malloc_functions.js_malloc_usable_size(ptr);\r\n}\r\n\r\nvoid JSRuntime::OnGarbadgeCollectCallback(const v8::WeakCallbackInfo<GCObject>& info)\r\n{\r\n\tGCObject* gcObject = info.GetParameter();\r\n\tJSRuntime* rt = gcObject->_runtime;\r\n\tJSGCObjectFinalizer* finalizer = gcObject->_classDef->_finalizer;\r\n\tgcObject->_classDef = nullptr;\r\n\tgcObject->_next = rt->_freeGCObjectSlot;\r\n\tgcObject->_obj.Reset();\r\n\r\n\tsize_t value_handle = gcObject->_value_handle;\r\n\tif (value_handle != 0)\r\n\t{\r\n\t\tJSValueRef& valueRef = rt->_objectRefs[value_handle];\r\n\t\tvalueRef._gc_handle = 0;\r\n\t\t--rt->_aliveObjectNum;\r\n\t\tvalueRef._next = rt->_freeObjectSlot;\r\n\t\trt->_freeObjectSlot = value_handle;\r\n\t\tgcObject->_value_handle = 0;\r\n\t\t//printf(\"resurrect: gc value removed %zd\\n\", value_handle);\r\n\t}\r\n\trt->_freeGCObjectSlot = gcObject->_index;\r\n\t--rt->_aliveGCObjectNum;\r\n\r\n\tif (void* payload = info.GetInternalField(EIFN_Payload))\r\n\t{\r\n\t\tif (finalizer)\r\n\t\t{\r\n\t\t\tJSPayloadHeader header = *static_cast<JSPayloadHeader*>(payload);\r\n\t\t\tfinalizer(rt, header);\r\n\t\t}\r\n\t\trt->mem_free(nullptr, payload);\r\n\t}\r\n}\r\n\r\nJSValue JSRuntime::AddGCObject(v8::Local<v8::Context> context, v8::Local<v8::Object> obj, JSClassDef* def)\r\n{\r\n\tGCObject* gcObject = nullptr;\r\n\tif (_freeGCObjectSlot == 0)\r\n\t{\r\n\t\tsize_t index = _gcObjects.size();\r\n\t\tgcObject = static_cast<GCObject*>(mem_alloc(nullptr, sizeof(GCObject)));\r\n\t\tmemset(gcObject, 0, sizeof(GCObject));\r\n\t\tgcObject->_index = index;\r\n\t\tgcObject->_runtime = this;\r\n\r\n\t\t_gcObjects.push_back(gcObject);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tgcObject = _gcObjects[_freeGCObjectSlot];\r\n\t\t_freeGCObjectSlot = gcObject->_next;\r\n\t\tgcObject->_next = 0;\r\n\t}\r\n\r\n\t++_aliveGCObjectNum;\r\n\tgcObject->_classDef = def;\r\n\tgcObject->_next = 0;\r\n\tgcObject->_obj.Reset(_isolate, obj);\r\n\tgcObject->_obj.SetWeak<GCObject>(gcObject, OnGarbadgeCollectCallback, v8::WeakCallbackType::kInternalFields);\r\n\tJSValue js_value = JS_MKPTR(JS_TAG_OBJECT, _AddValueInternal(context, obj, gcObject->_index));\r\n\tgcObject->_value_handle = js_value.u.ptr;\r\n\treturn js_value;\r\n}\r\n\r\nJSValue JSRuntime::AddValue(v8::Local<v8::Context> context, v8::Local<v8::Value> val)\r\n{\r\n\tif (val->IsInt32())\r\n\t{\r\n\t\treturn JS_MKINT32(JS_TAG_INT, v8::Local<v8::Int32>::Cast(val)->Value());\r\n\t}\r\n\tif (val->IsNumber())\r\n\t{\r\n\t\treturn JS_MKFLOAT64(JS_TAG_FLOAT64, v8::Local<v8::Number>::Cast(val)->Value());\r\n\t}\r\n\tif (val->IsBoolean())\r\n\t{\r\n\t\treturn JS_MKINT32(JS_TAG_BOOL, v8::Local<v8::Boolean>::Cast(val)->Value());\r\n\t}\r\n\tif (val->IsNull())\r\n\t{\r\n\t\treturn JS_NULL;\r\n\t}\r\n\tif (val->IsUndefined())\r\n\t{\r\n\t\treturn JS_UNDEFINED;\r\n\t}\r\n\tif (val->IsString())\r\n\t{\r\n\t\treturn AddString(context, v8::Local<v8::String>::Cast(val));\r\n\t}\r\n\tif (val->IsSymbol())\r\n\t{\r\n\t\treturn AddSymbol(context, v8::Local<v8::Symbol>::Cast(val));\r\n\t}\r\n\tif (val->IsBigInt())\r\n\t{\r\n\t\treturn JS_MKPTR(JS_TAG_BIG_INT, _AddValueInternal(context, val));\r\n\t}\r\n\treturn JS_MKPTR(JS_TAG_OBJECT, _AddValueInternal(context, val));\r\n}\r\n\r\nJSValue JSRuntime::AddString(v8::Local<v8::Context> context, v8::Local<v8::String> val)\r\n{\r\n\treturn JS_MKPTR(JS_TAG_STRING, _AddValueInternal(context, val));\r\n}\r\n\r\nJSValue JSRuntime::AddObject(v8::Local<v8::Context> context, v8::Local<v8::Object> val)\r\n{\r\n\treturn JS_MKPTR(JS_TAG_OBJECT, _AddValueInternal(context, val));\r\n}\r\n\r\nJSValue JSRuntime::AddSymbol(v8::Local<v8::Context> context, v8::Local<v8::Symbol> val)\r\n{\r\n\treturn JS_MKPTR(JS_TAG_SYMBOL, _AddValueInternal(context, val));\r\n}\r\n\r\nJSValue JSRuntime::ThrowException(v8::Local<v8::Context> context, v8::Local<v8::Value> exception)\r\n{\r\n\t//v8::String::Utf8Value str(_isolate, exception);\r\n\t//printf(\"error: %s\\n\", *str);\r\n\t//if (stack.IsEmpty())\r\n\t//{\r\n\t//\tv8::String::Utf8Value stack_str(_isolate, stack.ToLocalChecked());\r\n\t//\tprintf(\"stack: %s\\n\", *stack_str);\r\n\t//}\r\n\t_exception.Reset(_isolate, exception);\r\n\treturn JS_EXCEPTION;\r\n}\r\n\r\nJSValue JSRuntime::ThrowError(v8::Local<v8::Context> context, const char* exception, int len)\r\n{\r\n\tv8::MaybeLocal<v8::String> maybe_string = v8::String::NewFromUtf8(_isolate, exception, v8::NewStringType::kNormal, len);\r\n\tv8::Local<v8::String> string_;\r\n\tif (maybe_string.ToLocal(&string_))\r\n\t{\r\n\t\t_exception.Reset(_isolate, _isolate->ThrowError(string_));\r\n\t}\r\n\telse\r\n\t{\r\n\t\t_exception.Reset(_isolate, _isolate->ThrowError(\"failed to new error string\"));\r\n\t}\r\n\treturn JS_EXCEPTION;\r\n}\r\n\r\nJSValue JSRuntime::ThrowTypeError(v8::Local<v8::Context> context, const char* exception, int len)\r\n{\r\n\tv8::MaybeLocal<v8::String> maybe_string = v8::String::NewFromUtf8(_isolate, exception, v8::NewStringType::kNormal, len);\r\n\tv8::Local<v8::String> string_;\r\n\tif (maybe_string.ToLocal(&string_))\r\n\t{\r\n\t\t_exception.Reset(_isolate, _isolate->ThrowException(v8::Exception::TypeError(string_)));\r\n\t}\r\n\telse\r\n\t{\r\n\t\t_exception.Reset(_isolate, _isolate->ThrowError(\"failed to new error string\"));\r\n\t}\r\n\treturn JS_EXCEPTION;\r\n}\r\n\r\nJSValue JSRuntime::DupValue(JSValue value)\r\n{\r\n\tif (JS_TAG_IS_BYREF(value.tag))\r\n\t{\r\n\t\tsize_t id = value.u.ptr;\r\n\t\tif (id > 0 && id < _objectRefs.size())\r\n\t\t{\r\n\t\t\tJSValueRef& valueRef = _objectRefs[id];\r\n\t\t\tif (valueRef._gc_handle != 0 && valueRef._references == 0)\r\n\t\t\t{\r\n\t\t\t\tv8::Isolate::Scope isolateScope(_isolate);\r\n\t\t\t\tv8::HandleScope handleScope(_isolate);\r\n\r\n\t\t\t\tGCObject* gcObject = _gcObjects[valueRef._gc_handle];\r\n\t\t\t\tvalueRef._value.Reset(_isolate, gcObject->_obj.Get(_isolate));\r\n\t\t\t\t//printf(\"resurrect: JSValue is alive again %zd\\n\", id);\r\n\t\t\t}\r\n\t\t\t++valueRef._references;\r\n\t\t}\r\n\t}\r\n\treturn value;\r\n}\r\n\r\nvoid JSRuntime::FreeValue(JSValue value)\r\n{\r\n\tif (JS_TAG_IS_BYREF(value.tag))\r\n\t{\r\n\t\tsize_t id = value.u.ptr;\r\n\t\tif (id > 0 && id < _objectRefs.size())\r\n\t\t{\r\n\t\t\tJSValueRef& valueRef = _objectRefs[id];\r\n\t\t\tassert(valueRef._references > 0);\r\n\t\t\tif (--valueRef._references == 0)\r\n\t\t\t{\r\n\t\t\t\tvalueRef._value.Reset();\r\n\t\t\t\tif (valueRef._gc_handle == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\t--_aliveObjectNum;\r\n\t\t\t\t\tvalueRef._next = _freeObjectSlot;\r\n\t\t\t\t\t_freeObjectSlot = id;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nJSPayloadHeader JSRuntime::FreePayload(JSValue value)\r\n{\r\n\tif (value.tag == JS_TAG_OBJECT)\r\n\t{\r\n\t\tv8::MaybeLocal<v8::Value> maybe_local = GetReferencedValue(value.u.ptr);\r\n\t\tv8::Local<v8::Value> local;\r\n\t\tif (maybe_local.ToLocal(&local) && local->IsObject())\r\n\t\t{\r\n\t\t\tv8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(local);\r\n\t\t\tif (obj->InternalFieldCount() == EIFN_FieldCount)\r\n\t\t\t{\r\n\t\t\t\tif (void* sv = obj->GetAlignedPointerFromInternalField(EIFN_Payload))\r\n\t\t\t\t{\r\n\t\t\t\t\tobj->SetAlignedPointerInInternalField(EIFN_Payload, nullptr);\r\n\t\t\t\t\tJSPayloadHeader header = *static_cast<JSPayloadHeader*>(sv);\r\n\t\t\t\t\tmem_free(nullptr, sv);\r\n\t\t\t\t\treturn header;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn EmptyPayload;\r\n}\r\n\r\n\r\nv8::MaybeLocal<v8::Value> JSRuntime::GetValue(JSValue val)\r\n{\r\n\tswitch (val.tag)\r\n\t{\r\n\tcase JS_TAG_OBJECT:\r\n\tcase JS_TAG_STRING:\r\n\tcase JS_TAG_SYMBOL:\treturn GetReferencedValue(val.u.ptr);\r\n\tcase JS_TAG_INT: return v8::Int32::New(_isolate, val.u.int32);\r\n\tcase JS_TAG_BOOL: return v8::Boolean::New(_isolate, val.u.int32 == 1);\r\n\tcase JS_TAG_NULL: return v8::Null(_isolate);\r\n\tcase JS_TAG_UNDEFINED: return v8::Undefined(_isolate);\r\n\tcase JS_TAG_EXCEPTION: return _exception.Get(_isolate);\r\n\tcase JS_TAG_FLOAT64: return v8::Number::New(_isolate, val.u.float64);\r\n\tdefault: return {};\r\n\t}\r\n}\r\n\r\nv8::MaybeLocal<v8::Value> JSRuntime::GetReferencedValue(size_t id)\r\n{\r\n\tif (id > 0 && id < _objectRefs.size())\r\n\t{\r\n\t\tJSValueRef& valueRef = _objectRefs[id];\r\n\t\tif (valueRef._references != 0)\r\n\t\t{\r\n\t\t\treturn valueRef._value.Get(_isolate);\r\n\t\t}\r\n\t\tif (valueRef._gc_handle != 0)\r\n\t\t{\r\n\t\t\tGCObject* gcObject = _gcObjects[valueRef._gc_handle];\r\n\t\t\treturn gcObject->_obj.Get(_isolate);\r\n\t\t}\r\n\t}\r\n\treturn {};\r\n}\r\n\r\nJSAtom JSRuntime::GetAtom(const char* val, size_t len)\r\n{\r\n\tstd::string str(val, len);\r\n\treturn GetAtom(str);\r\n}\r\n\r\nJSAtom JSRuntime::GetAtom(std::string& val)\r\n{\r\n\tstd::map<std::string, JSAtom>::iterator it = _atoms.find(val);\r\n\tif (it != _atoms.end())\r\n\t{\r\n\t\tuint32_t id = it->second;\r\n\t\tJSAtomRef& valueRef =_atomRefs[id];\r\n\t\t++valueRef._references;\r\n\t\treturn id;\r\n\t}\r\n\tint len = (int)val.length();\r\n\tv8::MaybeLocal<v8::String> str = v8::String::NewFromUtf8(_isolate, val.c_str(), v8::NewStringType::kInternalized, len);\r\n\tif (str.IsEmpty())\r\n\t{\r\n\t\treturn {};\r\n\t}\r\n\r\n\tJSAtom atom;\r\n\t_aliveAtomNum++;\r\n\tif (_freeAtomSlot == 0)\r\n\t{\r\n\t\tJSAtomRef atomRef(_isolate, str.ToLocalChecked());\r\n\t\tatomRef._references = 1;\r\n\t\tatom = static_cast<uint32_t>(_atomRefs.size());\r\n\t\t_atomRefs.emplace_back(atomRef);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tatom = _freeAtomSlot;\r\n\t\tJSAtomRef& valueRef = _atomRefs[atom];\r\n\t\t_freeAtomSlot = valueRef._next;\r\n\t\tvalueRef._next = 0;\r\n\t\tvalueRef._value.Reset(_isolate, str.ToLocalChecked());\r\n\t\tvalueRef._references = 1;\r\n\t}\r\n\t_atoms[val] = atom;\r\n\treturn atom;\r\n}\r\n\r\nv8::MaybeLocal<v8::String> JSRuntime::GetAtomValue(JSAtom atom)\r\n{\r\n\tif (atom > 0 && atom < _atomRefs.size())\r\n\t{\r\n\t\tJSAtomRef& valueRef = _atomRefs[atom];\r\n\t\treturn valueRef._value.Get(_isolate);\r\n\t}\r\n\treturn {};\r\n}\r\n\r\nJSAtom JSRuntime::DupAtom(JSAtom atom)\r\n{\r\n\tuint32_t id = atom;\r\n\tif (id > 0 && id < _atomRefs.size())\r\n\t{\r\n\t\tJSAtomRef& valueRef = _atomRefs[id];\r\n\t\t++valueRef._references;\r\n\t}\r\n\treturn atom;\r\n}\r\n\r\nvoid JSRuntime::FreeAtom(JSAtom atom)\r\n{\r\n\tuint32_t id = atom;\r\n\tif (id > 0 && id < _atomRefs.size())\r\n\t{\r\n\t\tJSAtomRef& atomRef = _atomRefs[id];\r\n\t\tassert(valueRef._references > 0);\r\n\t\tif (--atomRef._references == 0)\r\n\t\t{\r\n\t\t\tv8::Isolate::Scope isolateScope(_isolate);\r\n\t\t\tv8::HandleScope handleScope(_isolate);\r\n\r\n\t\t\tatomRef._next = _freeAtomSlot;\r\n\t\t\t_freeAtomSlot = id;\r\n\t\t\tv8::Local<v8::String> str = atomRef._value.Get(_isolate);\r\n\t\t\tatomRef._value.Reset();\r\n\t\t\t--_aliveAtomNum;\r\n\t\t\tv8::String::Utf8Value str_str(_isolate, str);\r\n\t\t\tstd::string c_str(*str_str, str_str.length());\r\n\t\t\t_atoms.erase(c_str);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n//static void _FunctionCallback(const v8::FunctionCallbackInfo<v8::Value>& info)\r\n//{\r\n//\tprintf(\"!!!!!!!!! _FunctionCallback\\n\");\r\n//}\r\n\r\nJSClassID JSRuntime::NewClass(JSClassID class_id, const char* class_name, JSGCObjectFinalizer* finalizer)\r\n{\r\n\tif (_classes.contains(class_id))\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tv8::MaybeLocal<v8::String> className = v8::String::NewFromUtf8(_isolate, class_name, v8::NewStringType::kInternalized);\r\n\tif (className.IsEmpty())\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\tJSClassDef* def = static_cast<JSClassDef*>(mem_alloc(nullptr, sizeof(JSClassDef)));\r\n\r\n\tdef->_classID = class_id;\r\n\tdef->_finalizer = finalizer;\r\n\tmemset(&(def->_class), 0, sizeof(v8::Global<v8::FunctionTemplate>));\r\n\tv8::Local<v8::FunctionTemplate> func_template = v8::FunctionTemplate::New(_isolate/*, _FunctionCallback*/);\r\n\tfunc_template->InstanceTemplate()->SetInternalFieldCount(EIFN_FieldCount);\r\n\tfunc_template->SetClassName(className.ToLocalChecked());\r\n\tdef->_class.Reset(_isolate, func_template);\r\n\t_classes[class_id] = def;\r\n\treturn class_id;\r\n}\r\n\r\nJSClassDef* JSRuntime::GetClassDef(JSClassID class_id)\r\n{\r\n\tstd::map<JSClassID, JSClassDef*>::iterator it = _classes.find(class_id);\r\n\tif (it != _classes.end())\r\n\t{\r\n\t\treturn it->second;\r\n\t}\r\n\treturn nullptr;\r\n}\r\n\r\nvoid JSRuntime::SetHostPromiseRejectionTracker(JSHostPromiseRejectionTracker* cb, void* opaque)\r\n{\r\n\t_promiseRejectionTracker = cb;\r\n\t_promiseRejectionOpaque = opaque;\r\n}\r\n\r\nint JSRuntime::ExecutePendingJob(JSContext** pctx)\r\n{\r\n\tif (_context && _context->_debugServer)\r\n\t{\r\n\t\t_context->_debugServer->Update(false);\r\n\t}\r\n\t_isolate->PerformMicrotaskCheckpoint();\r\n\t*pctx = nullptr;\r\n\treturn 0;\r\n}\r\n\r\nvoid JSRuntime::RunGC()\r\n{\r\n#if defined(JSB_DEBUG) && JSB_DEBUG\r\n\t_isolate->RequestGarbageCollectionForTesting(v8::Isolate::kFullGarbageCollection);\r\n#else\r\n\t_isolate->LowMemoryNotification();\r\n#endif\r\n}\r\n"
  },
  {
    "path": "jsb_build/v8-bridge/src/WSServer.cpp",
    "content": "#include \"WSServer.h\"\r\n#include \"JSApi.h\"\r\n#include \"JSInspectorClient.h\"\r\n#include <libwebsockets.h>\r\n#include <string>\r\n#include <cstdio>\r\n#include <memory>\r\n#include <queue>\r\n#include <v8-version-string.h>\r\n\r\n#include \"JSContext.h\"\r\n\r\n//#define JSB_ENABLE_WSS_LOG\r\n\r\n#if defined(JSB_EXEC_TEST) || defined(JSB_ENABLE_WSS_LOG)\r\n#define wss_debug(...) _lws_log(LLL_NOTICE, __VA_ARGS__)\r\n#else\r\n#define wss_debug(...) do {} while(0)\r\n#endif\r\n\r\nstatic void custom_log(int level, const char* msg)\r\n{\r\n#if defined(JSB_EXEC_TEST)\r\n\tprintf(\"%s\", msg);\r\n#endif\r\n}\r\n\r\ntemplate<int N>\r\nstatic bool _is_request(lws* wsi, lws_token_indexes token, const char (&expected)[N])\r\n{\r\n\tstatic char buf[1024];\r\n\tint hlen = lws_hdr_total_length(wsi, token);\r\n\tif (!hlen || hlen != N - 1 || hlen > (int)sizeof(buf) - 1) {\r\n\t\treturn false;\r\n\t}\r\n\r\n\tif (lws_hdr_copy(wsi, buf, sizeof(buf), token) < 0)\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\treturn memcmp(buf, expected, N - 1) == 0;\r\n}\r\n\r\nint _response_json(lws* wsi, http_status code, const char* content, int content_len)\r\n{\r\n\tstatic unsigned char buf[4096];\r\n\tunsigned char* p = buf;\r\n\tunsigned char* end = p + sizeof(buf);\r\n\tif (lws_add_http_common_headers(wsi, HTTP_STATUS_OK, \"application/json\", content_len, &p, end))\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\tif (end - p - 1 - 2 < content_len)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\tp[0] = '\\r';\r\n\tp[1] = '\\n';\r\n\tp += 2;\r\n\tmemcpy(p, content, content_len);\r\n\tp[content_len] = '\\0';\r\n\tif (lws_write_http(wsi, buf, (p - buf) + content_len))\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\r\n\tif (lws_http_transaction_completed(wsi))\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nstruct WSBuffer\r\n{\r\n\tsize_t size;\r\n\tsize_t capacity;\r\n\tunsigned char* buffer;\r\n};\r\n\r\nclass WSServerImpl : public WSServer\r\n{\r\npublic:\r\n\tvoid Open(int port);\r\n\tvirtual void Update(bool bDebugging) override;\r\n\tvirtual bool IsConnected() override;\r\n\r\n\tWSServerImpl(JSContext* ctx);\r\n\tvirtual ~WSServerImpl();\r\nprivate:\r\n\tvoid OnReceiveBegin();\r\n\tvoid OnReceive(unsigned char* buf, size_t len);\r\n\tvoid OnReceiveEnd(bool is_binary);\r\n\tvoid Start(lws* wsi, bool isDebugger = true);\r\n\tvoid Stop();\r\n\tvoid Send(unsigned char const* buf, size_t len);\r\n\r\n\tstatic void _JSDebuggerUpdate(JSContext* ctx);\r\n\tstatic void _JSDebuggerSend(JSContext* ctx, unsigned char type, const unsigned char* buf, size_t size);\r\n\tstatic int _v8_protocol_callback(struct lws* wsi, enum lws_callback_reasons reason, void* user, void* in, size_t len);\r\n\tstatic int _echo_callback(struct lws* wsi, enum lws_callback_reasons reason, void* user, void* in, size_t len);\r\n\tstd::string _json_list;\r\n\tstd::string _json_version;\r\n\tlws_protocols _protocols[3];\r\n\tlws_context* _ws_ctx;\r\n\tJSContext* _js_context;\r\n\tstd::unique_ptr<JSDebugger> _debugger;\r\n\r\n\tlws* _wsi; // active wsi\r\n\tbool _is_polling;\r\n\tbool _is_servicing;\r\n\tbool _is_closing;\r\n\r\n\tsize_t _recv_len;\r\n\tsize_t _recv_cap;\r\n\tunsigned char* _recv_buffer;\r\n\tstd::queue<WSBuffer*> _send_queue;\r\n\tstd::vector<WSBuffer*> _free_queue;\r\n};\r\n\r\nWSServerImpl::WSServerImpl(JSContext* ctx)\r\n\t: _ws_ctx(nullptr), _js_context(ctx), _wsi(nullptr),\r\n\t_is_polling(false), _is_servicing(false), _is_closing(false),\r\n\t_recv_len(0), _recv_cap(0), _recv_buffer(nullptr)\r\n{\r\n}\r\n\r\nvoid WSServerImpl::OnReceiveBegin()\r\n{\r\n\t_recv_len = 0;\r\n}\r\n\r\nvoid WSServerImpl::OnReceive(unsigned char* buf, size_t len)\r\n{\r\n\tsize_t new_len = _recv_len + len;\r\n\tif (new_len > _recv_cap)\r\n\t{\r\n\t\t_recv_cap = max(_recv_cap + 4096, new_len);\r\n\t\tunsigned char* new_buffer = new unsigned char[_recv_cap];\r\n\t\tmemcpy(new_buffer, _recv_buffer, _recv_len);\r\n\t\tdelete[] _recv_buffer;\r\n\t\t_recv_buffer = new_buffer;\r\n\t}\r\n\tmemcpy(&_recv_buffer[_recv_len], buf, len);\r\n\t_recv_len = new_len;\r\n}\r\n\r\nvoid WSServerImpl::OnReceiveEnd(bool is_binary)\r\n{\r\n\tif (_debugger)\r\n\t{\r\n\t\t_debugger->OnMessageReceived(_recv_buffer, _recv_len);\r\n\t\twss_debug(\"receive message: %s %d %s\", is_binary ? \"binary\" : \"text\", (int)_recv_len, _recv_buffer);\r\n\t}\r\n}\r\n\r\nvoid WSServerImpl::Send(unsigned char const* buf, size_t len)\r\n{\r\n\tif (!_wsi)\r\n\t{\r\n\t\twss_debug(\"no connection to send\");\r\n\t\treturn;\r\n\t}\r\n\r\n\tWSBuffer* c = nullptr;\r\n\tsize_t rlen = len + LWS_PRE;\r\n\tfor (std::vector<WSBuffer*>::iterator i = _free_queue.begin(); i != _free_queue.end(); ++i)\r\n\t{\r\n\t\tif ((*i)->capacity >= rlen)\r\n\t\t{\r\n\t\t\tc = (*i);\r\n\t\t\t_free_queue.erase(i);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tif (!c)\r\n\t{\r\n\t\tc = new WSBuffer();\r\n\t\tc->capacity += max(rlen + 1, 512);\r\n\t\tc->buffer = new unsigned char[c->capacity];\r\n\t}\r\n\r\n\t//memset(c->buffer, 0, LWS_PRE);\r\n\tmemcpy(&c->buffer[LWS_PRE], buf, len);\r\n\tc->size = len;\r\n\tc->buffer[LWS_PRE + len] = '\\0';\r\n\t_send_queue.push(c);\r\n\tlws_callback_on_writable(_wsi);\r\n\t//printf(\"sending message %d (queue: %d): %s\", (int)len, (int)_send_queue.size(), buf);\r\n}\r\n\r\nvoid WSServerImpl::Start(lws* wsi, bool isDebugger)\r\n{\r\n\t_wsi = wsi;\r\n\tif (isDebugger)\r\n\t{\r\n\t\t_debugger.reset(JSDebugger::CreateDefaultDebugger(_js_context, { _JSDebuggerUpdate, _JSDebuggerSend }));\r\n\t\t_debugger->Open();\r\n\t}\r\n}\r\n\r\nvoid WSServerImpl::Stop()\r\n{\r\n\twhile (!_send_queue.empty()) \r\n\t{\r\n\t\tWSBuffer* buffer = _send_queue.front();\r\n\t\t_send_queue.pop();\r\n\t\t_free_queue.push_back(buffer);\r\n\t}\r\n\tif (_debugger)\r\n\t{\r\n\t\t_debugger->OnConnectionClosed();\r\n\t\t_is_closing = true;\r\n\t}\r\n\t_wsi = nullptr;\r\n}\r\n\r\nWSServerImpl::~WSServerImpl()\r\n{\r\n\twhile (!_send_queue.empty()) \r\n\t{\r\n\t\tWSBuffer* f = _send_queue.front();\r\n\t\t_send_queue.pop();\r\n\t\tdelete[] f->buffer;\r\n\t\tdelete f;\r\n\t}\r\n\tfor (WSBuffer* c : _free_queue)\r\n\t{\r\n\t\tdelete[] c->buffer;\r\n\t\tdelete c;\r\n\t}\r\n\tdelete[] _recv_buffer;\r\n\t_debugger.reset();\r\n\tlws_context_destroy(_ws_ctx);\r\n}\r\n\r\nWSServer* WSServer::CreateDebugServer(JSContext* ctx, int port)\r\n{\r\n\tWSServerImpl* s = new WSServerImpl(ctx);\r\n\ts->Open(port);\r\n\treturn s;\r\n}\r\n\r\nvoid WSServerImpl::_JSDebuggerUpdate(JSContext* ctx)\r\n{\r\n\tWSServerImpl* impl = (WSServerImpl*)ctx->_debugServer.get();\r\n\tif (impl)\r\n\t{\r\n\t\timpl->Update(true);\r\n\t}\r\n}\r\n\r\nvoid WSServerImpl::_JSDebuggerSend(JSContext* ctx, unsigned char type, const unsigned char* buf, size_t size)\r\n{\r\n\tWSServerImpl* impl = (WSServerImpl*)ctx->_debugServer.get();\r\n\tif (impl)\r\n\t{\r\n\t\timpl->Send(buf, size);\r\n\t}\r\n}\r\n\r\nint WSServerImpl::_echo_callback(struct lws* wsi, enum lws_callback_reasons reason, void* user, void* in, size_t len)\r\n{\r\n\tlws_context* ctx = lws_get_context(wsi);\r\n\tWSServerImpl* wss = (WSServerImpl*)lws_context_user(ctx);\r\n\r\n\tstatic int tick = 0;\r\n\tswitch (reason)\r\n\t{\r\n\tcase LWS_CALLBACK_ESTABLISHED:\r\n\t\twss_debug(\"LWS_CALLBACK_CLIENT_ESTABLISHED\");\r\n\t\twss->Stop();\r\n\t\twss->Start(wsi, false);\r\n\t\tbreak;\r\n\tcase LWS_CALLBACK_CLOSED:\r\n\t\twss->Stop();\r\n\t\twss_debug(\"LWS_CALLBACK_CLIENT_CLOSED\");\r\n\t\treturn -1;\r\n\tcase LWS_CALLBACK_RECEIVE:\r\n\t\tif (wss->_wsi != wsi)\r\n\t\t{\r\n\t\t\twss_debug(\"wrong connection\");\r\n\t\t\twss->Stop();\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t\tif (lws_is_first_fragment(wsi))\r\n\t\t{\r\n\t\t\twss->OnReceiveBegin();\r\n\t\t}\r\n\t\twss->OnReceive((unsigned char*)in, len);\r\n\t\tif (lws_is_final_fragment(wsi))\r\n\t\t{\r\n\t\t\twss_debug(\"%p receive message\", wsi);\r\n\t\t\twss->OnReceiveEnd(lws_frame_is_binary(wsi) == 1);\r\n\t\t\twss->Send((unsigned char const*)\"hello1\", 6);\r\n\t\t\twss->Send((unsigned char const*)\"hello2\", 6);\r\n\t\t\twss->Send((unsigned char const*)\"hello3\", 6);\r\n\t\t\tif (!wss->_send_queue.empty())\r\n\t\t\t{\r\n\t\t\t\twss->_is_servicing = true;\r\n\t\t\t\tlws_callback_on_writable(wsi);\r\n\t\t\t}\r\n\t\t}\r\n\t\tbreak;\r\n\tcase LWS_CALLBACK_CLIENT_WRITEABLE:\r\n\t\twss_debug(\"LWS_CALLBACK_CLIENT_WRITEABLE\");\r\n\t\tbreak;\r\n\tcase LWS_CALLBACK_SERVER_WRITEABLE:\r\n\t\tif (!wss->_send_queue.empty())\r\n\t\t{\r\n\t\t\tif (wss->_wsi != wsi)\r\n\t\t\t{\r\n\t\t\t\twss_debug(\"wrong connection\");\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\t\t\tWSBuffer* buffer = wss->_send_queue.front();\r\n\t\t\tif (lws_write(wsi, &(buffer->buffer[LWS_PRE]), buffer->size, LWS_WRITE_TEXT) != (int)buffer->size)\r\n\t\t\t{\r\n\t\t\t\twss_debug(\"connection write error\");\r\n\t\t\t\twss->Stop();\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\twss->_send_queue.pop();\r\n\t\t\t\twss->_free_queue.push_back(buffer);\r\n\t\t\t\twss_debug(\"LWS_CALLBACK_SERVER_WRITEABLE %p send message: [queue:%d] %d %s\\n\", wsi, (int)wss->_send_queue.size(), (int)buffer->size, &buffer->buffer[LWS_PRE]);\r\n\t\t\t\tif (!wss->_send_queue.empty())\r\n\t\t\t\t{\r\n\t\t\t\t\tlws_callback_on_writable(wsi);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nint WSServerImpl::_v8_protocol_callback(struct lws* wsi, enum lws_callback_reasons reason, void* user, void* in, size_t len)\r\n{\r\n\tlws_context* ctx = lws_get_context(wsi);\r\n\tWSServerImpl* wss = (WSServerImpl*)lws_context_user(ctx);\r\n\r\n\t//printf(\"servicing begin %d\\n\", reason);\r\n\tswitch (reason)\r\n\t{\r\n\tcase LWS_CALLBACK_ESTABLISHED:\r\n\t\tif (wss->_wsi || wss->_is_closing)\r\n\t\t{\r\n\t\t\twss_debug(\"supports only one connection\");\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t\twss->Start(wsi);\r\n\t\twss_debug(\"%p accept new incoming connection\", wsi);\r\n\t\tbreak;\r\n\tcase LWS_CALLBACK_RECEIVE:\r\n\t\tif (wss->_wsi != wsi)\r\n\t\t{\r\n\t\t\twss_debug(\"wrong connection\");\r\n\t\t\twss->Stop();\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t\tif (lws_is_first_fragment(wsi))\r\n\t\t{\r\n\t\t\twss->OnReceiveBegin();\r\n\t\t}\r\n\t\twss->OnReceive((unsigned char*)in, len);\r\n\t\tif (lws_is_final_fragment(wsi))\r\n\t\t{\r\n\t\t\t//wss_debug(\"%p receive message\", wsi);\r\n\t\t\twss->OnReceiveEnd(lws_frame_is_binary(wsi) == 1);\r\n\t\t\tif (!wss->_send_queue.empty())\r\n\t\t\t{\r\n\t\t\t\twss->_is_servicing = true;\r\n\t\t\t\tlws_callback_on_writable(wsi);\r\n\t\t\t}\r\n\t\t}\r\n\t\tbreak;\r\n\tcase LWS_CALLBACK_CLIENT_WRITEABLE:\r\n\tcase LWS_CALLBACK_SERVER_WRITEABLE:\r\n\t\tif (wss->_is_closing)\r\n\t\t{\r\n\t\t\twss_debug(\"_WRITEABLE, but inspector is closing\");\r\n\t\t\tlws_close_reason(wsi, LWS_CLOSE_STATUS_NORMAL, (unsigned char*)\"\", 0);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tif (!wss->_send_queue.empty())\r\n\t\t{\r\n\t\t\tif (wss->_wsi != wsi)\r\n\t\t\t{\r\n\t\t\t\twss_debug(\"wrong connection\");\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\t\t\tWSBuffer* buffer = wss->_send_queue.front();\r\n\t\t\tif (lws_write(wsi, &(buffer->buffer[LWS_PRE]), buffer->size, LWS_WRITE_TEXT) != (int)buffer->size)\r\n\t\t\t{\r\n\t\t\t\twss_debug(\"connection write error\");\r\n\t\t\t\twss->Stop();\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\t\t\telse \r\n\t\t\t{\r\n\t\t\t\twss->_send_queue.pop();\r\n\t\t\t\twss->_free_queue.push_back(buffer);\r\n\t\t\t\twss_debug(\"%p send message: [queue:%d] %d %s\\n\", wsi, (int)wss->_send_queue.size(), (int)buffer->size, &buffer->buffer[LWS_PRE]);\r\n\t\t\t\tif (!wss->_send_queue.empty())\r\n\t\t\t\t{\r\n\t\t\t\t\twss->_is_servicing = true;\r\n\t\t\t\t\tlws_callback_on_writable(wsi);\r\n\t\t\t\t\t//lws_rx_flow_control(wsi, 0);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t//lws_rx_flow_control(wsi, 1);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tbreak;\r\n\tcase LWS_CALLBACK_CLOSED:\r\n\t\tif (wss->_wsi != wsi)\r\n\t\t{\r\n\t\t\twss_debug(\"LWS_CALLBACK_CLOSED, and mismatched wsi\");\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t\twss->Stop();\r\n\t\twss_debug(\"connection closed\");\r\n\t\tbreak;\r\n\tcase LWS_CALLBACK_CLIENT_CONNECTION_ERROR:\r\n\t\tif (wss->_wsi != wsi)\r\n\t\t{\r\n\t\t\twss_debug(\"LWS_CALLBACK_CLIENT_CONNECTION_ERROR, and mismatched wsi\");\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t\twss->Stop();\r\n\t\twss_debug(\"connection error\");\r\n\t\tbreak;\r\n\tcase LWS_CALLBACK_HTTP:\r\n\t\tif (_is_request(wsi, WSI_TOKEN_GET_URI, \"/json\") || _is_request(wsi, WSI_TOKEN_GET_URI, \"/json/list\"))\r\n\t\t{\r\n\t\t\tconst char* content = wss->_json_list.c_str();\r\n\t\t\tint content_len = wss->_json_list.length();\r\n\t\t\tif (_response_json(wsi, HTTP_STATUS_OK, content, content_len))\r\n\t\t\t{\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (_is_request(wsi, WSI_TOKEN_GET_URI, \"/json/version\"))\r\n\t\t{\r\n\t\t\tconst char* content = wss->_json_version.c_str();\r\n\t\t\tint content_len = wss->_json_version.length();\r\n\t\t\tif (_response_json(wsi, HTTP_STATUS_OK, content, content_len))\r\n\t\t\t{\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse \r\n\t\t{\r\n\t\t\tif (lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, nullptr))\r\n\t\t\t{\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tbreak;\r\n\tcase LWS_CALLBACK_HTTP_BODY_COMPLETION:\r\n\t\t//wss_debug(\"LWS_CALLBACK_HTTP_BODY_COMPLETION\");\r\n\t\tif (lws_return_http_status(wsi, 200, nullptr))\r\n\t\t{\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t\tbreak;\r\n\tcase LWS_CALLBACK_CLIENT_ESTABLISHED:\r\n\tcase LWS_CALLBACK_CLIENT_CLOSED:\r\n\tcase LWS_CALLBACK_CLIENT_RECEIVE:\r\n\t\twss_debug(\"unexpected %d\", reason);\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n\t//printf(\"servicing end\\n\");\r\n\treturn 0;\r\n}\r\n\r\n// devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9229/backend\r\nvoid WSServerImpl::Open(int port)\r\n{\r\n\t_json_version = \\\r\n\t\t\"{\"\r\n\t\t\"    \\\"Browser\\\": \\\"unity-jsb/1.7.1.0\\\",\"\r\n\t\t\"    \\\"Protocol-Version\\\" : \\\"1.1\\\",\"\r\n\t\t\"    \\\"User-Agent\\\" : \\\"unity-jsb/1.7\\\",\"\r\n\t\t\"    \\\"V8-Version\\\" : \\\"\" V8_VERSION_STRING \"\\\",\";\r\n\t_json_version += \"\t\\\"webSocketDebuggerUrl\\\" : \\\"ws://localhost:\";\r\n\t_json_version += std::to_string(port);\r\n\t_json_version += \"\\\"\";\r\n\t_json_version += \"}\";\r\n\r\n\t_json_list = \"[{\";\r\n\t_json_list += \"\\\"description\\\": \\\"unity-jsb (v8-bridge)\\\",\";\r\n\t_json_list += \"\\\"id\\\": \\\"0\\\",\";\r\n\t_json_list += \"\\\"title\\\": \\\"unity-jsb (v8-bridge)\\\",\";\r\n\t_json_list += \"\\\"type\\\": \\\"node\\\",\";\r\n\t_json_list += \"\\\"webSocketDebuggerUrl\\\" : \\\"ws://localhost:\";\r\n\t_json_list += std::to_string(port);\r\n\t_json_list += \"\\\"\";\r\n\t_json_list += \"}]\";\r\n\r\n#if defined(JSB_EXEC_TEST)\r\n\tlws_set_log_level(LLL_USER | LLL_DEBUG | LLL_NOTICE | LLL_ERR | LLL_WARN | LLL_INFO | LLL_CLIENT | LLL_THREAD, custom_log);\r\n\twss_debug(\"ws server starting\");\r\n#else\r\n\t//lws_set_log_level(LLL_USER | LLL_DEBUG | LLL_NOTICE | LLL_ERR | LLL_WARN | LLL_INFO | LLL_CLIENT | LLL_THREAD, _js_context->_logCallback ? _js_context->_logCallback : custom_log);\r\n\tlws_set_log_level(LLL_USER | LLL_ERR | LLL_WARN, _js_context->_logCallback ? _js_context->_logCallback : custom_log);\r\n#endif\r\n\r\n\tmemset(_protocols, 0, sizeof(lws_protocols) * 3);\r\n\t_protocols[0].name = \"binary\";\r\n\t_protocols[0].callback = _v8_protocol_callback;\r\n\t_protocols[0].per_session_data_size = 0;\r\n\t_protocols[0].rx_buffer_size = (size_t)4 * 1024 * 1024;\r\n\r\n\t//_protocols[1].name = \"echo\";\r\n\t//_protocols[1].callback = _echo_callback;\r\n\t//_protocols[1].per_session_data_size = 0;\r\n\t//_protocols[1].rx_buffer_size = (size_t)4 * 1024 * 1024;\r\n\r\n\tlws_context_creation_info context_creation_info;\r\n\tmemset(&context_creation_info, 0, sizeof(lws_context_creation_info));\r\n\tcontext_creation_info.port = port;\r\n\tcontext_creation_info.iface = nullptr;\r\n\tcontext_creation_info.protocols = _protocols;\r\n\tcontext_creation_info.extensions = nullptr;\r\n\tcontext_creation_info.gid = -1;\r\n\tcontext_creation_info.uid = -1;\r\n\tcontext_creation_info.options = 0;\r\n\tcontext_creation_info.user = this;\r\n\t//context_creation_info.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;\r\n\tcontext_creation_info.options |= LWS_SERVER_OPTION_DISABLE_IPV6;\r\n\r\n\t_ws_ctx = lws_create_context(&context_creation_info);\r\n\t_debugger.reset(JSDebugger::CreateDefaultDebugger(_js_context, { _JSDebuggerUpdate, _JSDebuggerSend }));\r\n\t_debugger->Open();\r\n}\r\n\r\nbool WSServerImpl::IsConnected()\r\n{\r\n\treturn _debugger && _debugger->IsConnected();\r\n}\r\n\r\nvoid WSServerImpl::Update(bool bDebugging)\r\n{\r\n\tif (!bDebugging && _is_closing)\r\n\t{\r\n\t\tif (_debugger)\r\n\t\t{\r\n\t\t\t_debugger->Close();\r\n\t\t\t_debugger.reset();\r\n\t\t}\r\n\t\t_is_closing = false;\r\n\t}\r\n\t_is_polling = true;\r\n\t//printf(\"loop begin\\n\");\r\n\tlws_service(_ws_ctx, 0);\r\n\tlws_callback_on_writable_all_protocol(_ws_ctx, _protocols);\r\n\t//printf(\"loop end\\n\");\r\n\t_is_polling = false;\r\n}\r\n"
  },
  {
    "path": "jsb_build/v8-bridge/src/cutils.c",
    "content": "\r\n#ifdef UNITY_EXT_COMPILING\r\n\r\n#define UTF8_CHAR_LEN_MAX 6\r\n\r\nstatic const unsigned int utf8_min_code[5] = {\r\n    0x80, 0x800, 0x10000, 0x00200000, 0x04000000,\r\n};\r\n\r\nstatic const unsigned char utf8_first_code_mask[5] = {\r\n    0x1f, 0xf, 0x7, 0x3, 0x1,\r\n};\r\n\r\n/* return -1 if error. *pp is not updated in this case. max_len must\r\n   be >= 1. The maximum length for a UTF8 byte sequence is 6 bytes. */\r\nint unicode_from_utf8(const uint8_t* p, int max_len, const uint8_t** pp)\r\n{\r\n    int l, c, b, i;\r\n\r\n    c = *p++;\r\n    if (c < 0x80) {\r\n        *pp = p;\r\n        return c;\r\n    }\r\n    switch (c) {\r\n    case 0xc0: case 0xc1: case 0xc2: case 0xc3:\r\n    case 0xc4: case 0xc5: case 0xc6: case 0xc7:\r\n    case 0xc8: case 0xc9: case 0xca: case 0xcb:\r\n    case 0xcc: case 0xcd: case 0xce: case 0xcf:\r\n    case 0xd0: case 0xd1: case 0xd2: case 0xd3:\r\n    case 0xd4: case 0xd5: case 0xd6: case 0xd7:\r\n    case 0xd8: case 0xd9: case 0xda: case 0xdb:\r\n    case 0xdc: case 0xdd: case 0xde: case 0xdf:\r\n        l = 1;\r\n        break;\r\n    case 0xe0: case 0xe1: case 0xe2: case 0xe3:\r\n    case 0xe4: case 0xe5: case 0xe6: case 0xe7:\r\n    case 0xe8: case 0xe9: case 0xea: case 0xeb:\r\n    case 0xec: case 0xed: case 0xee: case 0xef:\r\n        l = 2;\r\n        break;\r\n    case 0xf0: case 0xf1: case 0xf2: case 0xf3:\r\n    case 0xf4: case 0xf5: case 0xf6: case 0xf7:\r\n        l = 3;\r\n        break;\r\n    case 0xf8: case 0xf9: case 0xfa: case 0xfb:\r\n        l = 4;\r\n        break;\r\n    case 0xfc: case 0xfd:\r\n        l = 5;\r\n        break;\r\n    default:\r\n        return -1;\r\n    }\r\n    /* check that we have enough characters */\r\n    if (l > (max_len - 1))\r\n        return -1;\r\n    c &= utf8_first_code_mask[l - 1];\r\n    for (i = 0; i < l; i++) {\r\n        b = *p++;\r\n        if (b < 0x80 || b >= 0xc0)\r\n            return -1;\r\n        c = (c << 6) | (b & 0x3f);\r\n    }\r\n    if (c < utf8_min_code[l - 1])\r\n        return -1;\r\n    *pp = p;\r\n    return c;\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "jsb_build/v8-bridge/src/libregexp.c",
    "content": "\r\n#ifdef UNITY_EXT_COMPILING\r\n\r\n#ifndef countof\r\n#define countof(x) (sizeof(x) / sizeof((x)[0]))\r\n#endif\r\n\r\n/* code point ranges for Zs,Zl or Zp property */\r\nstatic const uint16_t char_range_s[] = {\r\n    10,\r\n    0x0009, 0x000D + 1,\r\n    0x0020, 0x0020 + 1,\r\n    0x00A0, 0x00A0 + 1,\r\n    0x1680, 0x1680 + 1,\r\n    0x2000, 0x200A + 1,\r\n    /* 2028;LINE SEPARATOR;Zl;0;WS;;;;;N;;;;; */\r\n    /* 2029;PARAGRAPH SEPARATOR;Zp;0;B;;;;;N;;;;; */\r\n    0x2028, 0x2029 + 1,\r\n    0x202F, 0x202F + 1,\r\n    0x205F, 0x205F + 1,\r\n    0x3000, 0x3000 + 1,\r\n    /* FEFF;ZERO WIDTH NO-BREAK SPACE;Cf;0;BN;;;;;N;BYTE ORDER MARK;;;; */\r\n    0xFEFF, 0xFEFF + 1,\r\n};\r\n\r\nJS_BOOL lre_is_space(int c)\r\n{\r\n    int i, n, low, high;\r\n    n = (countof(char_range_s) - 1) / 2;\r\n    for (i = 0; i < n; i++) {\r\n        low = char_range_s[2 * i + 1];\r\n        if (c < low)\r\n            return FALSE;\r\n        high = char_range_s[2 * i + 2];\r\n        if (c < high)\r\n            return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "jsb_build/v8-bridge/src/unity_ext.c",
    "content": "\r\n#ifdef UNITY_EXT_COMPILING\r\n\r\nJS_EXPORT JSValue jsb_crossbind_constructor(JSContext* ctx, JSValue new_target)\r\n{\r\n    //JSValue proto = JS_GetProperty(ctx, new_target, JS_ATOM_prototype);\r\n    JSValue proto = JSB_DupValue(ctx, new_target);\r\n    if (!JS_IsException(proto))\r\n    {\r\n        JSValue val = JS_NewObjectProtoClass(ctx, proto, js_bridge_class_id);\r\n        JS_FreeValue(ctx, proto);\r\n        return val;\r\n    }\r\n\r\n    return proto;\r\n}\r\n\r\nJS_EXPORT JSValue jsb_construct_bridge_object(JSContext* ctx, JSValue proto, int32_t object_id)\r\n{\r\n    JSValue obj = JS_CallConstructor(ctx, proto, 0, NULL);\r\n    if (!JS_IsException(obj))\r\n    {\r\n        JSPayload* sv = (JSPayload*)js_malloc(ctx, sizeof(JSPayloadHeader));\r\n        sv->header.type_id = JS_BO_OBJECT;\r\n        sv->header.value = object_id;\r\n        JSB_SetOpaque(ctx, obj, sv);\r\n    }\r\n\r\n    return obj;\r\n}\r\n\r\nJS_EXPORT JSValue jsb_new_bridge_object(JSContext* ctx, JSValue proto, int32_t object_id/*, int32_t type_id = JS_BO_OBJECT */)\r\n{\r\n    JSValue obj = JS_NewObjectProtoClass(ctx, proto, js_bridge_class_id);\r\n    if (!JS_IsException(obj))\r\n    {\r\n        JSPayload* sv = (JSPayload*)js_malloc(ctx, sizeof(JSPayloadHeader));\r\n        sv->header.type_id = JS_BO_OBJECT;\r\n        sv->header.value = object_id;\r\n        JSB_SetOpaque(ctx, obj, sv);\r\n    }\r\n\r\n    return obj;\r\n}\r\n\r\n// for constructor new_target\r\nJS_EXPORT JSValue JSB_NewBridgeClassObject(JSContext* ctx, JSValue new_target, int32_t object_id/*, int32_t type_id = JS_BO_OBJECT */)\r\n{\r\n    //JSValue proto = JS_GetProperty(ctx, new_target, JS_ATOM_prototype);\r\n    JSValue proto = JSB_DupValue(ctx, new_target);\r\n    if (!JS_IsException(proto))\r\n    {\r\n        JSValue obj = jsb_new_bridge_object(ctx, proto, object_id/*, type_id*/);\r\n        JS_FreeValue(ctx, proto);\r\n        return obj;\r\n    }\r\n\r\n    return proto;\r\n}\r\n\r\nJS_EXPORT JSValue jsb_new_bridge_value(JSContext* ctx, JSValue proto, int32_t size)\r\n{\r\n    JSValue obj = JS_NewObjectProtoClass(ctx, proto, js_bridge_class_id);\r\n    if (!JS_IsException(obj))\r\n    {\r\n        JSPayload* sv = (JSPayload*)js_mallocz(ctx, sizeof(JSPayloadHeader) + size);\r\n        sv->header.type_id = JS_BO_VALUE;\r\n        sv->header.value = size;\r\n        JSB_SetOpaque(ctx, obj, sv);\r\n    }\r\n\r\n    return obj;\r\n}\r\n\r\nJS_EXPORT JSValue JSB_NewBridgeClassValue(JSContext* ctx, JSValue new_target, int32_t size)\r\n{\r\n    //JSValue proto = JS_GetProperty(ctx, new_target, JS_ATOM_prototype);\r\n    JSValue proto = JSB_DupValue(ctx, new_target);\r\n    if (!JS_IsException(proto))\r\n    {\r\n        JSValue obj = jsb_new_bridge_value(ctx, proto, size);\r\n        JS_FreeValue(ctx, proto);\r\n        return obj;\r\n    }\r\n\r\n    return proto;\r\n}\r\n\r\nJS_EXPORT JSPayloadHeader jsb_get_payload_header(JSContext* ctx, JSValue val)\r\n{\r\n    JSPayloadHeader* sv = (JSPayloadHeader*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv)\r\n    {\r\n        return *sv;\r\n    }\r\n    return EmptyPayload;\r\n}\r\n\r\nJS_EXPORT JSPayload* jsb_get_payload(JSContext* ctx, JSValue val)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv)\r\n    {\r\n        return sv;\r\n    }\r\n    return 0;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_floats(JSContext* ctx, JSValue val, int n, float* v0)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(float) * n)\r\n    {\r\n        float* ptr = (float*)&(sv->data[0]);\r\n        for (int i = 0; i < n; ++i)\r\n        {\r\n            *(v0 + i) = ptr[i];\r\n        }\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_floats(JSContext* ctx, JSValue val, int n, float* v0)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(float) * n)\r\n    {\r\n        float* ptr = (float*)&(sv->data[0]);\r\n        for (int i = 0; i < n; ++i)\r\n        {\r\n            ptr[i] = *(v0 + i);\r\n        }\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_float_2(JSContext* ctx, JSValue val, float* v0, float* v1)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(float) * 2)\r\n    {\r\n        float* ptr = (float*)&(sv->data[0]);\r\n        *v0 = ptr[0];\r\n        *v1 = ptr[1];\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_float_2(JSContext* ctx, JSValue val, float v0, float v1)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(float) * 2)\r\n    {\r\n        float* ptr = (float*)&(sv->data[0]);\r\n        ptr[0] = v0;\r\n        ptr[1] = v1;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_float_3(JSContext* ctx, JSValue val, float* v0, float* v1, float* v2)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(float) * 3)\r\n    {\r\n        float* ptr = (float*)&(sv->data[0]);\r\n        *v0 = ptr[0];\r\n        *v1 = ptr[1];\r\n        *v2 = ptr[2];\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_float_3(JSContext* ctx, JSValue val, float v0, float v1, float v2)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(float) * 3)\r\n    {\r\n        float* ptr = (float*)&(sv->data[0]);\r\n        ptr[0] = v0;\r\n        ptr[1] = v1;\r\n        ptr[2] = v2;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_float_4(JSContext* ctx, JSValue val, float* v0, float* v1, float* v2, float* v3)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(float) * 4)\r\n    {\r\n        float* ptr = (float*)&(sv->data[0]);\r\n        *v0 = ptr[0];\r\n        *v1 = ptr[1];\r\n        *v2 = ptr[2];\r\n        *v3 = ptr[3];\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_float_4(JSContext* ctx, JSValue val, float v0, float v1, float v2, float v3)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(float) * 4)\r\n    {\r\n        float* ptr = (float*)&(sv->data[0]);\r\n        ptr[0] = v0;\r\n        ptr[1] = v1;\r\n        ptr[2] = v2;\r\n        ptr[3] = v3;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_ints(JSContext* ctx, JSValue val, int n, int* v0)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int) * n)\r\n    {\r\n        int* ptr = (int*)&(sv->data[0]);\r\n        for (int i = 0; i < n; ++i)\r\n        {\r\n            *(v0 + i) = ptr[i];\r\n        }\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_ints(JSContext* ctx, JSValue val, int n, int* v0)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int) * n)\r\n    {\r\n        int* ptr = (int*)&(sv->data[0]);\r\n        for (int i = 0; i < n; ++i)\r\n        {\r\n            ptr[i] = *(v0 + i);\r\n        }\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_int_1(JSContext* ctx, JSValue val, int* v0)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int))\r\n    {\r\n        int* ptr = (int*)&(sv->data[0]);\r\n        *v0 = ptr[0];\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_int_1(JSContext* ctx, JSValue val, int v0)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int))\r\n    {\r\n        int* ptr = (int*)&(sv->data[0]);\r\n        ptr[0] = v0;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_int_2(JSContext* ctx, JSValue val, int* v0, int* v1)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int) * 2)\r\n    {\r\n        int* ptr = (int*)&(sv->data[0]);\r\n        *v0 = ptr[0];\r\n        *v1 = ptr[1];\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_int_2(JSContext* ctx, JSValue val, int v0, int v1)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int) * 2)\r\n    {\r\n        int* ptr = (int*)&(sv->data[0]);\r\n        ptr[0] = v0;\r\n        ptr[1] = v1;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_int_3(JSContext* ctx, JSValue val, int* v0, int* v1, int* v2)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int) * 3)\r\n    {\r\n        int* ptr = (int*)&(sv->data[0]);\r\n        *v0 = ptr[0];\r\n        *v1 = ptr[1];\r\n        *v2 = ptr[2];\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_int_3(JSContext* ctx, JSValue val, int v0, int v1, int v2)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int) * 3)\r\n    {\r\n        int* ptr = (int*)&(sv->data[0]);\r\n        ptr[0] = v0;\r\n        ptr[1] = v1;\r\n        ptr[2] = v2;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_int_4(JSContext* ctx, JSValue val, int* v0, int* v1, int* v2, int* v3)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int) * 4)\r\n    {\r\n        int* ptr = (int*)&(sv->data[0]);\r\n        *v0 = ptr[0];\r\n        *v1 = ptr[1];\r\n        *v2 = ptr[2];\r\n        *v3 = ptr[3];\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_int_4(JSContext* ctx, JSValue val, int v0, int v1, int v2, int v3)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(int) * 4)\r\n    {\r\n        int* ptr = (int*)&(sv->data[0]);\r\n        ptr[0] = v0;\r\n        ptr[1] = v1;\r\n        ptr[2] = v2;\r\n        ptr[3] = v3;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_bytes(JSContext* ctx, JSValue val, int n, byte* v0)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(byte) * n)\r\n    {\r\n        byte* ptr = (byte*)&(sv->data[0]);\r\n        for (int i = 0; i < n; ++i)\r\n        {\r\n            *(v0 + i) = ptr[i];\r\n        }\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_bytes(JSContext* ctx, JSValue val, int n, byte* v0)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(byte) * n)\r\n    {\r\n        byte* ptr = (byte*)&(sv->data[0]);\r\n        for (int i = 0; i < n; ++i)\r\n        {\r\n            ptr[i] = *(v0 + i);\r\n        }\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_get_byte_4(JSContext* ctx, JSValue val, byte* v0, byte* v1, byte* v2, byte* v3)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(byte) * 4)\r\n    {\r\n        byte* ptr = (byte*)&(sv->data[0]);\r\n        *v0 = ptr[0];\r\n        *v1 = ptr[1];\r\n        *v2 = ptr[2];\r\n        *v3 = ptr[3];\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\nJS_EXPORT JS_BOOL jsb_set_byte_4(JSContext* ctx, JSValue val, byte v0, byte v1, byte v2, byte v3)\r\n{\r\n    JSPayload* sv = (JSPayload*)JSB_GetOpaque(ctx, val, js_bridge_class_id);\r\n    if (sv && sv->header.type_id == JS_BO_VALUE && sv->header.value == sizeof(byte) * 4)\r\n    {\r\n        byte* ptr = (byte*)&(sv->data[0]);\r\n        ptr[0] = v0;\r\n        ptr[1] = v1;\r\n        ptr[2] = v2;\r\n        ptr[3] = v3;\r\n        return TRUE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "jsb_build/websockets/CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.7.2)\r\nproject(websockets)\r\n\r\nif (WIN32)\r\n    add_definitions(-D_WINSOCKAPI_)\r\nendif ()\r\n\r\nadd_definitions(-DLWS_DLL -DLWS_INTERNAL)\r\n\r\nset(TOP_DIR ${CMAKE_CURRENT_SOURCE_DIR})\r\nset(OUT_DIR ${TOP_DIR}/build)\r\n\r\nset(LIBWEBSOCKETS_DIR ${TOP_DIR}/libwebsockets)\r\nset(MBEDTLS_DIR ${TOP_DIR}/mbedtls)\r\nset(ZLIB_DIR ${TOP_DIR}/zlib)\r\n\r\ninclude_directories(${MBEDTLS_DIR}/include)\r\naux_source_directory(${MBEDTLS_DIR}/library MBEDTLS_SRCS)\r\n\r\ninclude_directories(${ZLIB_DIR})\r\nset(ZLIB_SRCS\r\n    ${ZLIB_DIR}/adler32.c\r\n    ${ZLIB_DIR}/compress.c\r\n    ${ZLIB_DIR}/crc32.c\r\n    ${ZLIB_DIR}/deflate.c\r\n    ${ZLIB_DIR}/infback.c\r\n    ${ZLIB_DIR}/inffast.c\r\n    ${ZLIB_DIR}/inflate.c\r\n    ${ZLIB_DIR}/inftrees.c\r\n    ${ZLIB_DIR}/trees.c\r\n    ${ZLIB_DIR}/uncompr.c\r\n    ${ZLIB_DIR}/zutil.c\r\n)\r\n\r\ninclude_directories(${TOP_DIR})\r\ninclude_directories(${LIBWEBSOCKETS_DIR})\r\ninclude_directories(${LIBWEBSOCKETS_DIR}/win32helpers)\r\ninclude_directories(${LIBWEBSOCKETS_DIR}/tls/mbedtls/wrapper/include)\r\ninclude_directories(${LIBWEBSOCKETS_DIR}/tls/mbedtls/wrapper/include/internal)\r\ninclude_directories(${LIBWEBSOCKETS_DIR}/tls/mbedtls/wrapper/include/openssl)\r\ninclude_directories(${LIBWEBSOCKETS_DIR}/tls/mbedtls/wrapper/include/platform)\r\n\r\nif (MSVC)\r\n\t# Turn off security warnings.\r\n\tadd_definitions(-D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE)\r\nendif(MSVC)\r\n\r\nset(LIBWEBSOCKETS_SRCS\r\n    ${LIBWEBSOCKETS_DIR}/core/alloc.c\r\n    ${LIBWEBSOCKETS_DIR}/core/context.c\r\n    ${LIBWEBSOCKETS_DIR}/core/libwebsockets.c\r\n    ${LIBWEBSOCKETS_DIR}/core/output.c\r\n    ${LIBWEBSOCKETS_DIR}/core/pollfd.c\r\n    ${LIBWEBSOCKETS_DIR}/core/service.c\r\n\r\n    ${LIBWEBSOCKETS_DIR}/event-libs/poll/poll.c\r\n\r\n    ${LIBWEBSOCKETS_DIR}/misc/base64-decode.c\r\n    ${LIBWEBSOCKETS_DIR}/misc/lejp.c\r\n    ${LIBWEBSOCKETS_DIR}/misc/sha-1.c\r\n\r\n    ${LIBWEBSOCKETS_DIR}/roles/h1/ops-h1.c\r\n    ${LIBWEBSOCKETS_DIR}/roles/http/header.c\r\n    ${LIBWEBSOCKETS_DIR}/roles/http/client/client.c\r\n    ${LIBWEBSOCKETS_DIR}/roles/http/client/client-handshake.c\r\n    ${LIBWEBSOCKETS_DIR}/roles/http/server/fops-zip.c\r\n    ${LIBWEBSOCKETS_DIR}/roles/http/server/lejp-conf.c\r\n    ${LIBWEBSOCKETS_DIR}/roles/http/server/parsers.c\r\n    ${LIBWEBSOCKETS_DIR}/roles/http/server/server.c\r\n    ${LIBWEBSOCKETS_DIR}/roles/listen/ops-listen.c\r\n    ${LIBWEBSOCKETS_DIR}/roles/pipe/ops-pipe.c\r\n    ${LIBWEBSOCKETS_DIR}/roles/raw/ops-raw.c\r\n\r\n    ${LIBWEBSOCKETS_DIR}/roles/ws/client-ws.c\r\n    ${LIBWEBSOCKETS_DIR}/roles/ws/client-parser-ws.c\r\n    ${LIBWEBSOCKETS_DIR}/roles/ws/ops-ws.c\r\n    ${LIBWEBSOCKETS_DIR}/roles/ws/server-ws.c\r\n\r\n    ${LIBWEBSOCKETS_DIR}/tls/tls.c\r\n    ${LIBWEBSOCKETS_DIR}/tls/tls-client.c\r\n    ${LIBWEBSOCKETS_DIR}/tls/tls-server.c\r\n\r\n    ${LIBWEBSOCKETS_DIR}/tls/mbedtls/wrapper/library/ssl_cert.c\r\n    ${LIBWEBSOCKETS_DIR}/tls/mbedtls/wrapper/library/ssl_pkey.c\r\n    ${LIBWEBSOCKETS_DIR}/tls/mbedtls/wrapper/library/ssl_stack.c\r\n    ${LIBWEBSOCKETS_DIR}/tls/mbedtls/wrapper/library/ssl_methods.c\r\n    ${LIBWEBSOCKETS_DIR}/tls/mbedtls/wrapper/library/ssl_lib.c\r\n    ${LIBWEBSOCKETS_DIR}/tls/mbedtls/wrapper/library/ssl_x509.c\r\n    ${LIBWEBSOCKETS_DIR}/tls/mbedtls/wrapper/platform/ssl_port.c\r\n    ${LIBWEBSOCKETS_DIR}/tls/mbedtls/wrapper/platform/ssl_pm.c\r\n    ${LIBWEBSOCKETS_DIR}/tls/mbedtls/lws-genhash.c\r\n    ${LIBWEBSOCKETS_DIR}/tls/mbedtls/mbedtls-client.c\r\n    ${LIBWEBSOCKETS_DIR}/tls/mbedtls/lws-genrsa.c\r\n    ${LIBWEBSOCKETS_DIR}/tls/mbedtls/ssl.c\r\n    ${LIBWEBSOCKETS_DIR}/tls/mbedtls/mbedtls-server.c\r\n)\r\n\r\nif (WIN32)\r\n    add_definitions(-DWINVER=0x0601 -D_WIN32_WINNT=0x0601)\r\n    add_definitions(-DWINDOWS_ENABLED)\r\n    add_definitions(-DLWS_MINGW_SUPPORT)\r\n    list(APPEND LIBWEBSOCKETS_SRCS\r\n        ${LIBWEBSOCKETS_DIR}/plat/lws-plat-win.c\r\n        ${LIBWEBSOCKETS_DIR}/win32helpers/getopt.c\r\n        ${LIBWEBSOCKETS_DIR}/win32helpers/getopt_long.c\r\n        ${LIBWEBSOCKETS_DIR}/win32helpers/gettimeofday.c\r\n    )\r\nelse ()\r\n    list(APPEND LIBWEBSOCKETS_SRCS ${LIBWEBSOCKETS_DIR}/plat/lws-plat-unix.c)\r\nendif ()\r\n\r\nif (ANDROID)\r\n    set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -fstrict-aliasing -fomit-frame-pointer\")\r\n    set(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -fstrict-aliasing -fomit-frame-pointer\")\r\n    list(APPEND LIBWEBSOCKETS_SRCS\r\n        ${LIBWEBSOCKETS_DIR}/misc/getifaddrs.c\r\n    )\r\nendif ()\r\n\r\nlist(APPEND LIBWEBSOCKETS_SRCS\r\n    ${TOP_DIR}/unity_ws.c\r\n)\r\n\r\nif (APPLE) \r\n    if (IOS)\r\n        add_library(websockets STATIC ${MBEDTLS_SRCS} ${LIBWEBSOCKETS_SRCS} ${ZLIB_SRCS})\r\n        set(CMAKE_OSX_ARCHITECTURES \"$(ARCHS_STANDARD)\")\r\n        set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -fembed-bitcode\")\r\n        set(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -fembed-bitcode\")\r\n        set_xcode_property (websockets IPHONEOS_DEPLOYMENT_TARGET \"7.0\" \"all\")\r\n    else ()\r\n        add_library(websockets MODULE ${MBEDTLS_SRCS} ${LIBWEBSOCKETS_SRCS} ${ZLIB_SRCS})\r\n        set(CMAKE_OSX_ARCHITECTURES \"$(ARCHS_STANDARD_64_BIT)\")\r\n        set_target_properties(websockets PROPERTIES MACOSX_BUNDLE TRUE)\r\n        set_target_properties(websockets PROPERTIES BUNDLE TRUE)\r\n    endif ()\r\nelse ()\r\n    if (WIN32)\r\n        add_library(websockets SHARED ${MBEDTLS_SRCS} ${LIBWEBSOCKETS_SRCS} ${ZLIB_SRCS})\r\n        target_link_libraries(websockets bcrypt)\r\n    else ()\r\n        add_library(websockets SHARED ${MBEDTLS_SRCS} ${LIBWEBSOCKETS_SRCS} ${ZLIB_SRCS})\r\n    endif ()\r\nendif ()\r\n\r\n#target_link_libraries(websockets librws_static.lib)\r\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/LICENSE",
    "content": "Libwebsockets and included programs are provided under the terms of the GNU\nLibrary General Public License (LGPL) 2.1, with the following exceptions:\n\n1) Any reference, whether in these modifications or in the GNU\nLibrary General Public License 2.1, to this License, these terms, the\nGNU Lesser Public License,  GNU Library General Public License, LGPL, or\nany similar reference shall refer to the GNU Library General Public\nLicense 2.1 as modified by these paragraphs 1) through 4).\n\n2) Static linking of programs with the libwebsockets library does not\nconstitute a derivative work and does not require the author to provide \nsource code for the program, use the shared libwebsockets libraries, or\nlink their program against a user-supplied version of libwebsockets.\n\nIf you link the program to a modified version of libwebsockets, then the\nchanges to libwebsockets must be provided under the terms of the LGPL in\nsections 1, 2, and 4.\n\n3) You do not have to provide a copy of the libwebsockets license with\nprograms that are linked to the libwebsockets library, nor do you have to\nidentify the libwebsockets license in your program or documentation as\nrequired by section 6 of the LGPL.\n\nHowever, programs must still identify their use of libwebsockets. The\nfollowing example statement can be included in user documentation to\nsatisfy this requirement:\n\n\"[program] is based in part on the work of the libwebsockets  project\n(https://libwebsockets.org)\"\n\n4) Some sources included have their own, more liberal licenses, or options\nto get original sources with the liberal terms.\n\nOriginal liberal license retained\n\n  - lib/misc/sha-1.c    - 3-clause BSD license retained, link to original\n  - win32port/zlib      - ZLIB license (see zlib.h)\n  - lib/tls/mbedtls/wrapper - Apache 2.0 (only built if linked against mbedtls)\n\nRelicensed to libwebsocket license\n\n  - lib/misc/base64-decode.c - relicensed to LGPL2.1+SLE, link to original\n  - lib/misc/daemonize.c     - relicensed from Public Domain to LGPL2.1+SLE,\n                               link to original Public Domain version\n\nPublic Domain (CC-zero) to simplify reuse\n\n  - test-apps/*.c\n  - test-apps/*.h\n  - minimal-examples/*\n  - lwsws/*\n\n------ end of exceptions\n \n                  GNU LESSER GENERAL PUBLIC LICENSE\n                       Version 2.1, February 1999\n\n Copyright (C) 1991, 1999 Free Software Foundation, Inc.\n 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n[This is the first released version of the Lesser GPL.  It also counts\n as the successor of the GNU Library Public License, version 2, hence\n the version number 2.1.]\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicenses are intended to guarantee your freedom to share and change\nfree software--to make sure the software is free for all its users.\n\n  This license, the Lesser General Public License, applies to some\nspecially designated software packages--typically libraries--of the\nFree Software Foundation and other authors who decide to use it.  You\ncan use it too, but we suggest you first think carefully about whether\nthis license or the ordinary General Public License is the better\nstrategy to use in any particular case, based on the explanations below.\n\n  When we speak of free software, we are referring to freedom of use,\nnot price.  Our General Public Licenses are designed to make sure that\nyou have the freedom to distribute copies of free software (and charge\nfor this service if you wish); that you receive source code or can get\nit if you want it; that you can change the software and use pieces of\nit in new free programs; and that you are informed that you can do\nthese things.\n\n  To protect your rights, we need to make restrictions that forbid\ndistributors to deny you these rights or to ask you to surrender these\nrights.  These restrictions translate to certain responsibilities for\nyou if you distribute copies of the library or if you modify it.\n\n  For example, if you distribute copies of the library, whether gratis\nor for a fee, you must give the recipients all the rights that we gave\nyou.  You must make sure that they, too, receive or can get the source\ncode.  If you link other code with the library, you must provide\ncomplete object files to the recipients, so that they can relink them\nwith the library after making changes to the library and recompiling\nit.  And you must show them these terms so they know their rights.\n\n  We protect your rights with a two-step method: (1) we copyright the\nlibrary, and (2) we offer you this license, which gives you legal\npermission to copy, distribute and/or modify the library.\n\n  To protect each distributor, we want to make it very clear that\nthere is no warranty for the free library.  Also, if the library is\nmodified by someone else and passed on, the recipients should know\nthat what they have is not the original version, so that the original\nauthor's reputation will not be affected by problems that might be\nintroduced by others.\n\f\n  Finally, software patents pose a constant threat to the existence of\nany free program.  We wish to make sure that a company cannot\neffectively restrict the users of a free program by obtaining a\nrestrictive license from a patent holder.  Therefore, we insist that\nany patent license obtained for a version of the library must be\nconsistent with the full freedom of use specified in this license.\n\n  Most GNU software, including some libraries, is covered by the\nordinary GNU General Public License.  This license, the GNU Lesser\nGeneral Public License, applies to certain designated libraries, and\nis quite different from the ordinary General Public License.  We use\nthis license for certain libraries in order to permit linking those\nlibraries into non-free programs.\n\n  When a program is linked with a library, whether statically or using\na shared library, the combination of the two is legally speaking a\ncombined work, a derivative of the original library.  The ordinary\nGeneral Public License therefore permits such linking only if the\nentire combination fits its criteria of freedom.  The Lesser General\nPublic License permits more lax criteria for linking other code with\nthe library.\n\n  We call this license the \"Lesser\" General Public License because it\ndoes Less to protect the user's freedom than the ordinary General\nPublic License.  It also provides other free software developers Less\nof an advantage over competing non-free programs.  These disadvantages\nare the reason we use the ordinary General Public License for many\nlibraries.  However, the Lesser license provides advantages in certain\nspecial circumstances.\n\n  For example, on rare occasions, there may be a special need to\nencourage the widest possible use of a certain library, so that it becomes\na de-facto standard.  To achieve this, non-free programs must be\nallowed to use the library.  A more frequent case is that a free\nlibrary does the same job as widely used non-free libraries.  In this\ncase, there is little to gain by limiting the free library to free\nsoftware only, so we use the Lesser General Public License.\n\n  In other cases, permission to use a particular library in non-free\nprograms enables a greater number of people to use a large body of\nfree software.  For example, permission to use the GNU C Library in\nnon-free programs enables many more people to use the whole GNU\noperating system, as well as its variant, the GNU/Linux operating\nsystem.\n\n  Although the Lesser General Public License is Less protective of the\nusers' freedom, it does ensure that the user of a program that is\nlinked with the Library has the freedom and the wherewithal to run\nthat program using a modified version of the Library.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.  Pay close attention to the difference between a\n\"work based on the library\" and a \"work that uses the library\".  The\nformer contains code derived from the library, whereas the latter must\nbe combined with the library in order to run.\n\f\n                  GNU LESSER GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License Agreement applies to any software library or other\nprogram which contains a notice placed by the copyright holder or\nother authorized party saying it may be distributed under the terms of\nthis Lesser General Public License (also called \"this License\").\nEach licensee is addressed as \"you\".\n\n  A \"library\" means a collection of software functions and/or data\nprepared so as to be conveniently linked with application programs\n(which use some of those functions and data) to form executables.\n\n  The \"Library\", below, refers to any such software library or work\nwhich has been distributed under these terms.  A \"work based on the\nLibrary\" means either the Library or any derivative work under\ncopyright law: that is to say, a work containing the Library or a\nportion of it, either verbatim or with modifications and/or translated\nstraightforwardly into another language.  (Hereinafter, translation is\nincluded without limitation in the term \"modification\".)\n\n  \"Source code\" for a work means the preferred form of the work for\nmaking modifications to it.  For a library, complete source code means\nall the source code for all modules it contains, plus any associated\ninterface definition files, plus the scripts used to control compilation\nand installation of the library.\n\n  Activities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning a program using the Library is not restricted, and output from\nsuch a program is covered only if its contents constitute a work based\non the Library (independent of the use of the Library in a tool for\nwriting it).  Whether that is true depends on what the Library does\nand what the program that uses the Library does.\n\n  1. You may copy and distribute verbatim copies of the Library's\ncomplete source code as you receive it, in any medium, provided that\nyou conspicuously and appropriately publish on each copy an\nappropriate copyright notice and disclaimer of warranty; keep intact\nall the notices that refer to this License and to the absence of any\nwarranty; and distribute a copy of this License along with the\nLibrary.\n\n  You may charge a fee for the physical act of transferring a copy,\nand you may at your option offer warranty protection in exchange for a\nfee.\n\f\n  2. You may modify your copy or copies of the Library or any portion\nof it, thus forming a work based on the Library, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) The modified work must itself be a software library.\n\n    b) You must cause the files modified to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    c) You must cause the whole of the work to be licensed at no\n    charge to all third parties under the terms of this License.\n\n    d) If a facility in the modified Library refers to a function or a\n    table of data to be supplied by an application program that uses\n    the facility, other than as an argument passed when the facility\n    is invoked, then you must make a good faith effort to ensure that,\n    in the event an application does not supply such function or\n    table, the facility still operates, and performs whatever part of\n    its purpose remains meaningful.\n\n    (For example, a function in a library to compute square roots has\n    a purpose that is entirely well-defined independent of the\n    application.  Therefore, Subsection 2d requires that any\n    application-supplied function or table used by this function must\n    be optional: if the application does not supply it, the square\n    root function must still compute square roots.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Library,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Library, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote\nit.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Library.\n\nIn addition, mere aggregation of another work not based on the Library\nwith the Library (or with a work based on the Library) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may opt to apply the terms of the ordinary GNU General Public\nLicense instead of this License to a given copy of the Library.  To do\nthis, you must alter all the notices that refer to this License, so\nthat they refer to the ordinary GNU General Public License, version 2,\ninstead of to this License.  (If a newer version than version 2 of the\nordinary GNU General Public License has appeared, then you can specify\nthat version instead if you wish.)  Do not make any other change in\nthese notices.\n\f\n  Once this change is made in a given copy, it is irreversible for\nthat copy, so the ordinary GNU General Public License applies to all\nsubsequent copies and derivative works made from that copy.\n\n  This option is useful when you wish to copy part of the code of\nthe Library into a program that is not a library.\n\n  4. You may copy and distribute the Library (or a portion or\nderivative of it, under Section 2) in object code or executable form\nunder the terms of Sections 1 and 2 above provided that you accompany\nit with the complete corresponding machine-readable source code, which\nmust be distributed under the terms of Sections 1 and 2 above on a\nmedium customarily used for software interchange.\n\n  If distribution of object code is made by offering access to copy\nfrom a designated place, then offering equivalent access to copy the\nsource code from the same place satisfies the requirement to\ndistribute the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  5. A program that contains no derivative of any portion of the\nLibrary, but is designed to work with the Library by being compiled or\nlinked with it, is called a \"work that uses the Library\".  Such a\nwork, in isolation, is not a derivative work of the Library, and\ntherefore falls outside the scope of this License.\n\n  However, linking a \"work that uses the Library\" with the Library\ncreates an executable that is a derivative of the Library (because it\ncontains portions of the Library), rather than a \"work that uses the\nlibrary\".  The executable is therefore covered by this License.\nSection 6 states terms for distribution of such executables.\n\n  When a \"work that uses the Library\" uses material from a header file\nthat is part of the Library, the object code for the work may be a\nderivative work of the Library even though the source code is not.\nWhether this is true is especially significant if the work can be\nlinked without the Library, or if the work is itself a library.  The\nthreshold for this to be true is not precisely defined by law.\n\n  If such an object file uses only numerical parameters, data\nstructure layouts and accessors, and small macros and small inline\nfunctions (ten lines or less in length), then the use of the object\nfile is unrestricted, regardless of whether it is legally a derivative\nwork.  (Executables containing this object code plus portions of the\nLibrary will still fall under Section 6.)\n\n  Otherwise, if the work is a derivative of the Library, you may\ndistribute the object code for the work under the terms of Section 6.\nAny executables containing that work also fall under Section 6,\nwhether or not they are linked directly with the Library itself.\n\f\n  6. As an exception to the Sections above, you may also combine or\nlink a \"work that uses the Library\" with the Library to produce a\nwork containing portions of the Library, and distribute that work\nunder terms of your choice, provided that the terms permit\nmodification of the work for the customer's own use and reverse\nengineering for debugging such modifications.\n\n  You must give prominent notice with each copy of the work that the\nLibrary is used in it and that the Library and its use are covered by\nthis License.  You must supply a copy of this License.  If the work\nduring execution displays copyright notices, you must include the\ncopyright notice for the Library among them, as well as a reference\ndirecting the user to the copy of this License.  Also, you must do one\nof these things:\n\n    a) Accompany the work with the complete corresponding\n    machine-readable source code for the Library including whatever\n    changes were used in the work (which must be distributed under\n    Sections 1 and 2 above); and, if the work is an executable linked\n    with the Library, with the complete machine-readable \"work that\n    uses the Library\", as object code and/or source code, so that the\n    user can modify the Library and then relink to produce a modified\n    executable containing the modified Library.  (It is understood\n    that the user who changes the contents of definitions files in the\n    Library will not necessarily be able to recompile the application\n    to use the modified definitions.)\n\n    b) Use a suitable shared library mechanism for linking with the\n    Library.  A suitable mechanism is one that (1) uses at run time a\n    copy of the library already present on the user's computer system,\n    rather than copying library functions into the executable, and (2)\n    will operate properly with a modified version of the library, if\n    the user installs one, as long as the modified version is\n    interface-compatible with the version that the work was made with.\n\n    c) Accompany the work with a written offer, valid for at\n    least three years, to give the same user the materials\n    specified in Subsection 6a, above, for a charge no more\n    than the cost of performing this distribution.\n\n    d) If distribution of the work is made by offering access to copy\n    from a designated place, offer equivalent access to copy the above\n    specified materials from the same place.\n\n    e) Verify that the user has already received a copy of these\n    materials or that you have already sent this user a copy.\n\n  For an executable, the required form of the \"work that uses the\nLibrary\" must include any data and utility programs needed for\nreproducing the executable from it.  However, as a special exception,\nthe materials to be distributed need not include anything that is\nnormally distributed (in either source or binary form) with the major\ncomponents (compiler, kernel, and so on) of the operating system on\nwhich the executable runs, unless that component itself accompanies\nthe executable.\n\n  It may happen that this requirement contradicts the license\nrestrictions of other proprietary libraries that do not normally\naccompany the operating system.  Such a contradiction means you cannot\nuse both them and the Library together in an executable that you\ndistribute.\n\f\n  7. You may place library facilities that are a work based on the\nLibrary side-by-side in a single library together with other library\nfacilities not covered by this License, and distribute such a combined\nlibrary, provided that the separate distribution of the work based on\nthe Library and of the other library facilities is otherwise\npermitted, and provided that you do these two things:\n\n    a) Accompany the combined library with a copy of the same work\n    based on the Library, uncombined with any other library\n    facilities.  This must be distributed under the terms of the\n    Sections above.\n\n    b) Give prominent notice with the combined library of the fact\n    that part of it is a work based on the Library, and explaining\n    where to find the accompanying uncombined form of the same work.\n\n  8. You may not copy, modify, sublicense, link with, or distribute\nthe Library except as expressly provided under this License.  Any\nattempt otherwise to copy, modify, sublicense, link with, or\ndistribute the Library is void, and will automatically terminate your\nrights under this License.  However, parties who have received copies,\nor rights, from you under this License will not have their licenses\nterminated so long as such parties remain in full compliance.\n\n  9. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Library or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Library (or any work based on the\nLibrary), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Library or works based on it.\n\n  10. Each time you redistribute the Library (or any work based on the\nLibrary), the recipient automatically receives a license from the\noriginal licensor to copy, distribute, link with or modify the Library\nsubject to these terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties with\nthis License.\n\f\n  11. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Library at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Library by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Library.\n\nIf any portion of this section is held invalid or unenforceable under any\nparticular circumstance, the balance of the section is intended to apply,\nand the section as a whole is intended to apply in other circumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  12. If the distribution and/or use of the Library is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Library under this License may add\nan explicit geographical distribution limitation excluding those countries,\nso that distribution is permitted only in or among countries not thus\nexcluded.  In such case, this License incorporates the limitation as if\nwritten in the body of this License.\n\n  13. The Free Software Foundation may publish revised and/or new\nversions of the Lesser General Public License from time to time.\nSuch new versions will be similar in spirit to the present version,\nbut may differ in detail to address new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Library\nspecifies a version number of this License which applies to it and\n\"any later version\", you have the option of following the terms and\nconditions either of that version or of any later version published by\nthe Free Software Foundation.  If the Library does not specify a\nlicense version number, you may choose any version ever published by\nthe Free Software Foundation.\n\f\n  14. If you wish to incorporate parts of the Library into other free\nprograms whose distribution conditions are incompatible with these,\nwrite to the author to ask for permission.  For software which is\ncopyrighted by the Free Software Foundation, write to the Free\nSoftware Foundation; we sometimes make exceptions for this.  Our\ndecision will be guided by the two goals of preserving the free status\nof all derivatives of our free software and of promoting the sharing\nand reuse of software generally.\n\n                            NO WARRANTY\n\n  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO\nWARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.\nEXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR\nOTHER PARTIES PROVIDE THE LIBRARY \"AS IS\" WITHOUT WARRANTY OF ANY\nKIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE\nLIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME\nTHE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN\nWRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY\nAND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU\nFOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR\nCONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE\nLIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING\nRENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A\nFAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF\nSUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\nDAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\f\n           How to Apply These Terms to Your New Libraries\n\n  If you develop a new library, and you want it to be of the greatest\npossible use to the public, we recommend making it free software that\neveryone can redistribute and change.  You can do so by permitting\nredistribution under these terms (or, alternatively, under the terms of the\nordinary General Public License).\n\n  To apply these terms, attach the following notices to the library.  It is\nsafest to attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least the\n\"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the library's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n\nAlso add information on how to contact you by electronic and paper mail.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the library, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the\n  library `Frob' (a library for tweaking knobs) written by James Random Hacker.\n\n  <signature of Ty Coon>, 1 April 1990\n  Ty Coon, President of Vice\n\nThat's all there is to it!\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/core/alloc.c",
    "content": "#include \"core/private.h\"\n\n#if defined(LWS_PLAT_OPTEE)\n\n#define TEE_USER_MEM_HINT_NO_FILL_ZERO       0x80000000\n\nvoid *__attribute__((weak))\n\tTEE_Malloc(uint32_t size, uint32_t hint)\n{\n\treturn NULL;\n}\nvoid *__attribute__((weak))\n\tTEE_Realloc(void *buffer, uint32_t newSize)\n{\n\treturn NULL;\n}\nvoid __attribute__((weak))\n\tTEE_Free(void *buffer)\n{\n}\n\nvoid *lws_realloc(void *ptr, size_t size, const char *reason)\n{\n\treturn TEE_Realloc(ptr, size);\n}\n\nvoid *lws_malloc(size_t size, const char *reason)\n{\n\treturn TEE_Malloc(size, TEE_USER_MEM_HINT_NO_FILL_ZERO);\n}\n\nvoid lws_free(void *p)\n{\n\tTEE_Free(p);\n}\n\nvoid *lws_zalloc(size_t size, const char *reason)\n{\n\tvoid *ptr = TEE_Malloc(size, TEE_USER_MEM_HINT_NO_FILL_ZERO);\n\tif (ptr)\n\t\tmemset(ptr, 0, size);\n\treturn ptr;\n}\n\nvoid lws_set_allocator(void *(*cb)(void *ptr, size_t size, const char *reason))\n{\n\t(void)cb;\n}\n#else\n\nstatic void *_realloc(void *ptr, size_t size, const char *reason)\n{\n\tif (size) {\n#if defined(LWS_WITH_ESP32)\n\t\tlwsl_notice(\"%s: size %lu: %s (free heap %d)\\n\", __func__,\n\t\t\t    (unsigned long)size, reason, (unsigned int)esp_get_free_heap_size() - (int)size);\n#else\n\t\tlwsl_debug(\"%s: size %lu: %s\\n\", __func__,\n\t\t\t   (unsigned long)size, reason);\n#endif\n#if defined(LWS_PLAT_OPTEE)\n\t\treturn (void *)TEE_Realloc(ptr, size);\n#else\n\t\treturn (void *)realloc(ptr, size);\n#endif\n\t}\n\tif (ptr)\n\t\tfree(ptr);\n\n\treturn NULL;\n}\n\nvoid *(*_lws_realloc)(void *ptr, size_t size, const char *reason) = _realloc;\n\nvoid *lws_realloc(void *ptr, size_t size, const char *reason)\n{\n\treturn _lws_realloc(ptr, size, reason);\n}\n\nvoid *lws_zalloc(size_t size, const char *reason)\n{\n\tvoid *ptr = _lws_realloc(NULL, size, reason);\n\tif (ptr)\n\t\tmemset(ptr, 0, size);\n\treturn ptr;\n}\n\nvoid lws_set_allocator(void *(*cb)(void *ptr, size_t size, const char *reason))\n{\n\t_lws_realloc = cb;\n}\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/core/context.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n\n#ifndef LWS_BUILD_HASH\n#define LWS_BUILD_HASH \"unknown-build-hash\"\n#endif\n\nconst struct lws_role_ops *available_roles[] = {\n#if defined(LWS_ROLE_H2)\n\t&role_ops_h2,\n#endif\n#if defined(LWS_ROLE_H1)\n\t&role_ops_h1,\n#endif\n#if defined(LWS_ROLE_WS)\n\t&role_ops_ws,\n#endif\n\tNULL\n};\n\nconst struct lws_event_loop_ops *available_event_libs[] = {\n#if defined(LWS_WITH_POLL)\n\t&event_loop_ops_poll,\n#endif\n#if defined(LWS_WITH_LIBUV)\n\t&event_loop_ops_uv,\n#endif\n#if defined(LWS_WITH_LIBEVENT)\n\t&event_loop_ops_event,\n#endif\n#if defined(LWS_WITH_LIBEV)\n\t&event_loop_ops_ev,\n#endif\n\tNULL\n};\n\nstatic const char *library_version = LWS_LIBRARY_VERSION \" \" LWS_BUILD_HASH;\n\n/**\n * lws_get_library_version: get version and git hash library built from\n *\n *\treturns a const char * to a string like \"1.1 178d78c\"\n *\trepresenting the library version followed by the git head hash it\n *\twas built from\n */\nLWS_VISIBLE const char *\nlws_get_library_version(void)\n{\n\treturn library_version;\n}\n\nint\nlws_role_call_alpn_negotiated(struct lws *wsi, const char *alpn)\n{\n#if defined(LWS_WITH_TLS)\n\tif (!alpn)\n\t\treturn 0;\n\n\tlwsl_info(\"%s: '%s'\\n\", __func__, alpn);\n\n\tLWS_FOR_EVERY_AVAILABLE_ROLE_START(ar)\n\t\tif (ar->alpn && !strcmp(ar->alpn, alpn) && ar->alpn_negotiated)\n\t\t\treturn ar->alpn_negotiated(wsi, alpn);\n\tLWS_FOR_EVERY_AVAILABLE_ROLE_END;\n#endif\n\treturn 0;\n}\n\nstatic const char * const mount_protocols[] = {\n\t\"http://\",\n\t\"https://\",\n\t\"file://\",\n\t\"cgi://\",\n\t\">http://\",\n\t\">https://\",\n\t\"callback://\"\n};\n\nLWS_VISIBLE void *\nlws_protocol_vh_priv_zalloc(struct lws_vhost *vhost,\n\t\t\t    const struct lws_protocols *prot, int size)\n{\n\tint n = 0;\n\n\t/* allocate the vh priv array only on demand */\n\tif (!vhost->protocol_vh_privs) {\n\t\tvhost->protocol_vh_privs = (void **)lws_zalloc(\n\t\t\t\tvhost->count_protocols * sizeof(void *),\n\t\t\t\t\"protocol_vh_privs\");\n\t\tif (!vhost->protocol_vh_privs)\n\t\t\treturn NULL;\n\t}\n\n\twhile (n < vhost->count_protocols && &vhost->protocols[n] != prot)\n\t\tn++;\n\n\tif (n == vhost->count_protocols) {\n\t\tn = 0;\n\t\twhile (n < vhost->count_protocols &&\n\t\t       strcmp(vhost->protocols[n].name, prot->name))\n\t\t\tn++;\n\n\t\tif (n == vhost->count_protocols)\n\t\t\treturn NULL;\n\t}\n\n\tvhost->protocol_vh_privs[n] = lws_zalloc(size, \"vh priv\");\n\treturn vhost->protocol_vh_privs[n];\n}\n\nLWS_VISIBLE void *\nlws_protocol_vh_priv_get(struct lws_vhost *vhost,\n\t\t\t const struct lws_protocols *prot)\n{\n\tint n = 0;\n\n\tif (!vhost || !vhost->protocol_vh_privs || !prot)\n\t\treturn NULL;\n\n\twhile (n < vhost->count_protocols && &vhost->protocols[n] != prot)\n\t\tn++;\n\n\tif (n == vhost->count_protocols) {\n\t\tn = 0;\n\t\twhile (n < vhost->count_protocols &&\n\t\t       strcmp(vhost->protocols[n].name, prot->name))\n\t\t\tn++;\n\n\t\tif (n == vhost->count_protocols) {\n\t\t\tlwsl_err(\"%s: unknown protocol %p\\n\", __func__, prot);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\treturn vhost->protocol_vh_privs[n];\n}\n\nstatic const struct lws_protocol_vhost_options *\nlws_vhost_protocol_options(struct lws_vhost *vh, const char *name)\n{\n\tconst struct lws_protocol_vhost_options *pvo = vh->pvo;\n\n\tif (!name)\n\t\treturn NULL;\n\n\twhile (pvo) {\n\t\tif (!strcmp(pvo->name, name))\n\t\t\treturn pvo;\n\t\tpvo = pvo->next;\n\t}\n\n\treturn NULL;\n}\n\n/*\n * inform every vhost that hasn't already done it, that\n * his protocols are initializing\n */\nLWS_VISIBLE int\nlws_protocol_init(struct lws_context *context)\n{\n\tstruct lws_vhost *vh = context->vhost_list;\n\tconst struct lws_protocol_vhost_options *pvo, *pvo1;\n\tstruct lws wsi;\n\tint n, any = 0;\n\n\tif (context->doing_protocol_init)\n\t\treturn 0;\n\n\tcontext->doing_protocol_init = 1;\n\n\tmemset(&wsi, 0, sizeof(wsi));\n\twsi.context = context;\n\n\tlwsl_info(\"%s\\n\", __func__);\n\n\twhile (vh) {\n\t\twsi.vhost = vh;\n\n\t\t/* only do the protocol init once for a given vhost */\n\t\tif (vh->created_vhost_protocols ||\n\t\t    (vh->options & LWS_SERVER_OPTION_SKIP_PROTOCOL_INIT))\n\t\t\tgoto next;\n\n\t\t/* initialize supported protocols on this vhost */\n\n\t\tfor (n = 0; n < vh->count_protocols; n++) {\n\t\t\twsi.protocol = &vh->protocols[n];\n\t\t\tif (!vh->protocols[n].name)\n\t\t\t\tcontinue;\n\t\t\tpvo = lws_vhost_protocol_options(vh,\n\t\t\t\t\t\t\t vh->protocols[n].name);\n\t\t\tif (pvo) {\n\t\t\t\t/*\n\t\t\t\t * linked list of options specific to\n\t\t\t\t * vh + protocol\n\t\t\t\t */\n\t\t\t\tpvo1 = pvo;\n\t\t\t\tpvo = pvo1->options;\n\n\t\t\t\twhile (pvo) {\n\t\t\t\t\tlwsl_debug(\n\t\t\t\t\t\t\"    vhost \\\"%s\\\", \"\n\t\t\t\t\t\t\"protocol \\\"%s\\\", \"\n\t\t\t\t\t\t\"option \\\"%s\\\"\\n\",\n\t\t\t\t\t\t\tvh->name,\n\t\t\t\t\t\t\tvh->protocols[n].name,\n\t\t\t\t\t\t\tpvo->name);\n\n\t\t\t\t\tif (!strcmp(pvo->name, \"default\")) {\n\t\t\t\t\t\tlwsl_info(\"Setting default \"\n\t\t\t\t\t\t   \"protocol for vh %s to %s\\n\",\n\t\t\t\t\t\t   vh->name,\n\t\t\t\t\t\t   vh->protocols[n].name);\n\t\t\t\t\t\tvh->default_protocol_index = n;\n\t\t\t\t\t}\n\t\t\t\t\tif (!strcmp(pvo->name, \"raw\")) {\n\t\t\t\t\t\tlwsl_info(\"Setting raw \"\n\t\t\t\t\t\t   \"protocol for vh %s to %s\\n\",\n\t\t\t\t\t\t   vh->name,\n\t\t\t\t\t\t   vh->protocols[n].name);\n\t\t\t\t\t\tvh->raw_protocol_index = n;\n\t\t\t\t\t}\n\t\t\t\t\tpvo = pvo->next;\n\t\t\t\t}\n\n\t\t\t\tpvo = pvo1->options;\n\t\t\t}\n\n#if defined(LWS_WITH_TLS)\n\t\t\tany |= !!vh->tls.ssl_ctx;\n#endif\n\n\t\t\t/*\n\t\t\t * inform all the protocols that they are doing their\n\t\t\t * one-time initialization if they want to.\n\t\t\t *\n\t\t\t * NOTE the wsi is all zeros except for the context, vh\n\t\t\t * + protocol ptrs so lws_get_context(wsi) etc can work\n\t\t\t */\n\t\t\tif (vh->protocols[n].callback(&wsi,\n\t\t\t\t\tLWS_CALLBACK_PROTOCOL_INIT, NULL,\n\t\t\t\t\t(void *)pvo, 0)) {\n\t\t\t\tif (vh->protocol_vh_privs) {\n\t\t\t\t\tlws_free(vh->protocol_vh_privs[n]);\n\t\t\t\t\tvh->protocol_vh_privs[n] = NULL;\n\t\t\t\t}\n\t\t\t\tlwsl_err(\"%s: protocol %s failed init\\n\", __func__,\n\t\t\t\t\t vh->protocols[n].name);\n\t\t\t}\n\t\t}\n\n\t\tvh->created_vhost_protocols = 1;\nnext:\n\t\tvh = vh->vhost_next;\n\t}\n\n\tcontext->doing_protocol_init = 0;\n\n\tif (!context->protocol_init_done)\n\t\tlws_finalize_startup(context);\n\n\tcontext->protocol_init_done = 1;\n\n\tif (any)\n\t\tlws_tls_check_all_cert_lifetimes(context);\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\nlws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,\n\t\t    void *user, void *in, size_t len)\n{\n\tstruct lws_ssl_info *si;\n#ifdef LWS_WITH_CGI\n\tstruct lws_cgi_args *args;\n#endif\n#if defined(LWS_WITH_CGI) || defined(LWS_WITH_HTTP_PROXY)\n\tchar buf[512];\n\tint n;\n#endif\n\n\tswitch (reason) {\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tcase LWS_CALLBACK_HTTP:\n#ifndef LWS_NO_SERVER\n\t\tif (lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL))\n\t\t\treturn -1;\n\n\t\tif (lws_http_transaction_completed(wsi))\n#endif\n\t\t\treturn -1;\n\t\tbreak;\n#if !defined(LWS_NO_SERVER)\n\tcase LWS_CALLBACK_HTTP_FILE_COMPLETION:\n\t\tif (lws_http_transaction_completed(wsi))\n\t\t\treturn -1;\n\t\tbreak;\n#endif\n\n\tcase LWS_CALLBACK_HTTP_WRITEABLE:\n#ifdef LWS_WITH_CGI\n\t\tif (wsi->reason_bf & (LWS_CB_REASON_AUX_BF__CGI_HEADERS |\n\t\t\t\t      LWS_CB_REASON_AUX_BF__CGI)) {\n\t\t\tn = lws_cgi_write_split_stdout_headers(wsi);\n\t\t\tif (n < 0) {\n\t\t\t\tlwsl_debug(\"AUX_BF__CGI forcing close\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (!n)\n\t\t\t\tlws_rx_flow_control(\n\t\t\t\t\twsi->http.cgi->stdwsi[LWS_STDOUT], 1);\n\n\t\t\tif (wsi->reason_bf & LWS_CB_REASON_AUX_BF__CGI_HEADERS)\n\t\t\t\twsi->reason_bf &=\n\t\t\t\t\t~LWS_CB_REASON_AUX_BF__CGI_HEADERS;\n\t\t\telse\n\t\t\t\twsi->reason_bf &= ~LWS_CB_REASON_AUX_BF__CGI;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (wsi->reason_bf & LWS_CB_REASON_AUX_BF__CGI_CHUNK_END) {\n\t\t\tif (!wsi->http2_substream) {\n\t\t\t\tmemcpy(buf + LWS_PRE, \"0\\x0d\\x0a\\x0d\\x0a\", 5);\n\t\t\t\tlwsl_debug(\"writing chunk term and exiting\\n\");\n\t\t\t\tn = lws_write(wsi, (unsigned char *)buf +\n\t\t\t\t\t\t   LWS_PRE, 5, LWS_WRITE_HTTP);\n\t\t\t} else\n\t\t\t\tn = lws_write(wsi, (unsigned char *)buf +\n\t\t\t\t\t\t   LWS_PRE, 0,\n\t\t\t\t\t\t   LWS_WRITE_HTTP_FINAL);\n\n\t\t\t/* always close after sending it */\n\t\t\treturn -1;\n\t\t}\n#endif\n#if defined(LWS_WITH_HTTP_PROXY)\n\t\tif (wsi->reason_bf & LWS_CB_REASON_AUX_BF__PROXY) {\n\t\t\tchar *px = buf + LWS_PRE;\n\t\t\tint lenx = sizeof(buf) - LWS_PRE;\n\n\t\t\t/*\n\t\t\t * our sink is writeable and our source has something\n\t\t\t * to read.  So read a lump of source material of\n\t\t\t * suitable size to send or what's available, whichever\n\t\t\t * is the smaller.\n\t\t\t */\n\t\t\twsi->reason_bf &= ~LWS_CB_REASON_AUX_BF__PROXY;\n\t\t\tif (!lws_get_child(wsi))\n\t\t\t\tbreak;\n\t\t\tif (lws_http_client_read(lws_get_child(wsi), &px,\n\t\t\t\t\t\t &lenx) < 0)\n\t\t\t\treturn -1;\n\t\t\tbreak;\n\t\t}\n#endif\n\t\tbreak;\n\n#if defined(LWS_WITH_HTTP_PROXY)\n\tcase LWS_CALLBACK_RECEIVE_CLIENT_HTTP:\n\t\tassert(lws_get_parent(wsi));\n\t\tif (!lws_get_parent(wsi))\n\t\t\tbreak;\n\t\tlws_get_parent(wsi)->reason_bf |= LWS_CB_REASON_AUX_BF__PROXY;\n\t\tlws_callback_on_writable(lws_get_parent(wsi));\n\t\tbreak;\n\n\tcase LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:\n\t\tassert(lws_get_parent(wsi));\n\t\tn = lws_write(lws_get_parent(wsi), (unsigned char *)in,\n\t\t\t\tlen, LWS_WRITE_HTTP);\n\t\tif (n < 0)\n\t\t\treturn -1;\n\t\tbreak;\n\n\tcase LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: {\n\t\tunsigned char *p, *end;\n\t\tchar ctype[64], ctlen = 0;\n\t\n\t\tp = (unsigned char *)buf + LWS_PRE;\n\t\tend = p + sizeof(buf) - LWS_PRE;\n\n\t\tif (lws_add_http_header_status(lws_get_parent(wsi),\n\t\t\t\t\t       HTTP_STATUS_OK, &p, end))\n\t\t\treturn 1;\n\t\tif (lws_add_http_header_by_token(lws_get_parent(wsi),\n\t\t\t\tWSI_TOKEN_HTTP_SERVER,\n\t\t\t    \t(unsigned char *)\"libwebsockets\",\n\t\t\t\t13, &p, end))\n\t\t\treturn 1;\n\n\t\tctlen = lws_hdr_copy(wsi, ctype, sizeof(ctype),\n\t\t\t\t     WSI_TOKEN_HTTP_CONTENT_TYPE);\n\t\tif (ctlen > 0) {\n\t\t\tif (lws_add_http_header_by_token(lws_get_parent(wsi),\n\t\t\t\tWSI_TOKEN_HTTP_CONTENT_TYPE,\n\t\t\t\t(unsigned char *)ctype, ctlen, &p, end))\n\t\t\t\treturn 1;\n\t\t}\n\n\t\tif (lws_finalize_http_header(lws_get_parent(wsi), &p, end))\n\t\t\treturn 1;\n\n\t\t*p = '\\0';\n\t\tn = lws_write(lws_get_parent(wsi),\n\t\t\t      (unsigned char *)buf + LWS_PRE,\n\t\t\t      p - ((unsigned char *)buf + LWS_PRE),\n\t\t\t      LWS_WRITE_HTTP_HEADERS);\n\t\tif (n < 0)\n\t\t\treturn -1;\n\n\t\tbreak; }\n\n#endif\n\n#ifdef LWS_WITH_CGI\n\t/* CGI IO events (POLLIN/OUT) appear here, our default policy is:\n\t *\n\t *  - POST data goes on subprocess stdin\n\t *  - subprocess stdout goes on http via writeable callback\n\t *  - subprocess stderr goes to the logs\n\t */\n\tcase LWS_CALLBACK_CGI:\n\t\targs = (struct lws_cgi_args *)in;\n\t\tswitch (args->ch) { /* which of stdin/out/err ? */\n\t\tcase LWS_STDIN:\n\t\t\t/* TBD stdin rx flow control */\n\t\t\tbreak;\n\t\tcase LWS_STDOUT:\n\t\t\t/* quench POLLIN on STDOUT until MASTER got writeable */\n\t\t\tlws_rx_flow_control(args->stdwsi[LWS_STDOUT], 0);\n\t\t\twsi->reason_bf |= LWS_CB_REASON_AUX_BF__CGI;\n\t\t\t/* when writing to MASTER would not block */\n\t\t\tlws_callback_on_writable(wsi);\n\t\t\tbreak;\n\t\tcase LWS_STDERR:\n\t\t\tn = lws_get_socket_fd(args->stdwsi[LWS_STDERR]);\n\t\t\tif (n < 0)\n\t\t\t\tbreak;\n\t\t\tn = read(n, buf, sizeof(buf) - 2);\n\t\t\tif (n > 0) {\n\t\t\t\tif (buf[n - 1] != '\\n')\n\t\t\t\t\tbuf[n++] = '\\n';\n\t\t\t\tbuf[n] = '\\0';\n\t\t\t\tlwsl_notice(\"CGI-stderr: %s\\n\", buf);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n\tcase LWS_CALLBACK_CGI_TERMINATED:\n\t\tlwsl_debug(\"LWS_CALLBACK_CGI_TERMINATED: %d %\" PRIu64 \"\\n\",\n\t\t\t\twsi->http.cgi->explicitly_chunked,\n\t\t\t\t(uint64_t)wsi->http.cgi->content_length);\n\t\tif (!wsi->http.cgi->explicitly_chunked &&\n\t\t    !wsi->http.cgi->content_length) {\n\t\t\t/* send terminating chunk */\n\t\t\tlwsl_debug(\"LWS_CALLBACK_CGI_TERMINATED: ending\\n\");\n\t\t\twsi->reason_bf |= LWS_CB_REASON_AUX_BF__CGI_CHUNK_END;\n\t\t\tlws_callback_on_writable(wsi);\n\t\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_CGI, 3);\n\t\t\tbreak;\n\t\t}\n\t\treturn -1;\n\n\tcase LWS_CALLBACK_CGI_STDIN_DATA:  /* POST body for stdin */\n\t\targs = (struct lws_cgi_args *)in;\n\t\targs->data[args->len] = '\\0';\n\t\tn = lws_get_socket_fd(args->stdwsi[LWS_STDIN]);\n\t\tif (n < 0)\n\t\t\treturn -1;\n\t\tn = write(n, args->data, args->len);\n\t\tif (n < args->len)\n\t\t\tlwsl_notice(\"LWS_CALLBACK_CGI_STDIN_DATA: \"\n\t\t\t\t    \"sent %d only %d went\", n, args->len);\n\t\treturn n;\n#endif\n#endif\n\tcase LWS_CALLBACK_SSL_INFO:\n\t\tsi = in;\n\n\t\t(void)si;\n\t\tlwsl_notice(\"LWS_CALLBACK_SSL_INFO: where: 0x%x, ret: 0x%x\\n\",\n\t\t\t    si->where, si->ret);\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\n/* list of supported protocols and callbacks */\n\nstatic const struct lws_protocols protocols_dummy[] = {\n\t/* first protocol must always be HTTP handler */\n\n\t{\n\t\t\"http-only\",\t\t\t/* name */\n\t\tlws_callback_http_dummy,\t/* callback */\n\t\t0,\t\t\t\t/* per_session_data_size */\n\t\t0,\t\t\t\t/* rx_buffer_size */\n\t\t0,\t\t\t\t/* id */\n\t\tNULL,\t\t\t\t/* user */\n\t\t0\t\t\t\t/* tx_packet_size */\n\t},\n\t/*\n\t * the other protocols are provided by lws plugins\n\t */\n\t{ NULL, NULL, 0, 0, 0, NULL, 0} /* terminator */\n};\n\n#ifdef LWS_PLAT_OPTEE\n#undef LWS_HAVE_GETENV\n#endif\n\nstatic void\nlws_vhost_destroy2(struct lws_vhost *vh);\n\nLWS_VISIBLE struct lws_vhost *\nlws_create_vhost(struct lws_context *context,\n\t\t const struct lws_context_creation_info *info)\n{\n\tstruct lws_vhost *vh = lws_zalloc(sizeof(*vh), \"create vhost\"),\n\t\t\t **vh1 = &context->vhost_list;\n\tconst struct lws_http_mount *mounts;\n\tconst struct lws_protocols *pcols = info->protocols;\n\tconst struct lws_protocol_vhost_options *pvo;\n#ifdef LWS_WITH_PLUGINS\n\tstruct lws_plugin *plugin = context->plugin_list;\n#endif\n\tstruct lws_protocols *lwsp;\n\tint m, f = !info->pvo;\n\tchar buf[20];\n#if !defined(LWS_WITHOUT_CLIENT) && defined(LWS_HAVE_GETENV)\n\tchar *p;\n#endif\n\tint n;\n\n\tif (!vh)\n\t\treturn NULL;\n\n#if LWS_MAX_SMP > 1\n\tpthread_mutex_init(&vh->lock, NULL);\n#endif\n\n\tif (!pcols)\n\t\tpcols = &protocols_dummy[0];\n\n\tvh->context = context;\n\tif (!info->vhost_name)\n\t\tvh->name = \"default\";\n\telse\n\t\tvh->name = info->vhost_name;\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tvh->http.error_document_404 = info->error_document_404;\n#endif\n\n\tif (info->options & LWS_SERVER_OPTION_ONLY_RAW)\n\t\tlwsl_info(\"%s set to only support RAW\\n\", vh->name);\n\n\tvh->iface = info->iface;\n#if !defined(LWS_WITH_ESP32) && \\\n    !defined(OPTEE_TA) && !defined(WIN32)\n\tvh->bind_iface = info->bind_iface;\n#endif\n\n\tfor (vh->count_protocols = 0;\n\t     pcols[vh->count_protocols].callback;\n\t     vh->count_protocols++)\n\t\t;\n\n\tvh->options = info->options;\n\tvh->pvo = info->pvo;\n\tvh->headers = info->headers;\n\tvh->user = info->user;\n\n\tLWS_FOR_EVERY_AVAILABLE_ROLE_START(ar)\n\t\tif (ar->init_vhost)\n\t\t\tif (ar->init_vhost(vh, info))\n\t\t\t\treturn NULL;\n\tLWS_FOR_EVERY_AVAILABLE_ROLE_END;\n\n\n\tif (info->keepalive_timeout)\n\t\tvh->keepalive_timeout = info->keepalive_timeout;\n\telse\n\t\tvh->keepalive_timeout = 5;\n\n\tif (info->timeout_secs_ah_idle)\n\t\tvh->timeout_secs_ah_idle = info->timeout_secs_ah_idle;\n\telse\n\t\tvh->timeout_secs_ah_idle = 10;\n\n#if defined(LWS_WITH_TLS)\n\n\tvh->tls.alpn = info->alpn;\n\tvh->tls.ssl_info_event_mask = info->ssl_info_event_mask;\n\n\tif (info->ecdh_curve)\n\t\tlws_strncpy(vh->tls.ecdh_curve, info->ecdh_curve,\n\t\t\t    sizeof(vh->tls.ecdh_curve));\n\n\t/* carefully allocate and take a copy of cert + key paths if present */\n\tn = 0;\n\tif (info->ssl_cert_filepath)\n\t\tn += (int)strlen(info->ssl_cert_filepath) + 1;\n\tif (info->ssl_private_key_filepath)\n\t\tn += (int)strlen(info->ssl_private_key_filepath) + 1;\n\n\tif (n) {\n\t\tvh->tls.key_path = vh->tls.alloc_cert_path = lws_malloc(n, \"vh paths\");\n\t\tif (info->ssl_cert_filepath) {\n\t\t\tn = (int)strlen(info->ssl_cert_filepath) + 1;\n\t\t\tmemcpy(vh->tls.alloc_cert_path, info->ssl_cert_filepath, n);\n\t\t\tvh->tls.key_path += n;\n\t\t}\n\t\tif (info->ssl_private_key_filepath)\n\t\t\tmemcpy(vh->tls.key_path, info->ssl_private_key_filepath,\n\t\t\t       strlen(info->ssl_private_key_filepath) + 1);\n\t}\n#endif\n\n\t/*\n\t * give the vhost a unified list of protocols including the\n\t * ones that came from plugins\n\t */\n\tlwsp = lws_zalloc(sizeof(struct lws_protocols) * (vh->count_protocols +\n\t\t\t\t   context->plugin_protocol_count + 1),\n\t\t\t\t   \"vhost-specific plugin table\");\n\tif (!lwsp) {\n\t\tlwsl_err(\"OOM\\n\");\n\t\treturn NULL;\n\t}\n\n\tm = vh->count_protocols;\n\tmemcpy(lwsp, pcols, sizeof(struct lws_protocols) * m);\n\n\t/* for compatibility, all protocols enabled on vhost if only\n\t * the default vhost exists.  Otherwise only vhosts who ask\n\t * for a protocol get it enabled.\n\t */\n\n\tif (context->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)\n\t\tf = 0;\n\t(void)f;\n#ifdef LWS_WITH_PLUGINS\n\tif (plugin) {\n\n\t\twhile (plugin) {\n\t\t\tfor (n = 0; n < plugin->caps.count_protocols; n++) {\n\t\t\t\t/*\n\t\t\t\t * for compatibility's sake, no pvo implies\n\t\t\t\t * allow all protocols\n\t\t\t\t */\n\t\t\t\tif (f || lws_vhost_protocol_options(vh,\n\t\t\t\t    plugin->caps.protocols[n].name)) {\n\t\t\t\t\tmemcpy(&lwsp[m],\n\t\t\t\t\t       &plugin->caps.protocols[n],\n\t\t\t\t\t       sizeof(struct lws_protocols));\n\t\t\t\t\tm++;\n\t\t\t\t\tvh->count_protocols++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tplugin = plugin->list;\n\t\t}\n\t}\n#endif\n\n\tif (\n#ifdef LWS_WITH_PLUGINS\n\t    (context->plugin_list) ||\n#endif\n\t    context->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)\n\t\tvh->protocols = lwsp;\n\telse {\n\t\tvh->protocols = pcols;\n\t\tlws_free(lwsp);\n\t}\n\n\tvh->same_vh_protocol_list = (struct lws **)\n\t\t\tlws_zalloc(sizeof(struct lws *) * vh->count_protocols,\n\t\t\t\t   \"same vh list\");\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tvh->http.mount_list = info->mounts;\n#endif\n\n#ifdef LWS_WITH_UNIX_SOCK\n\tif (LWS_UNIX_SOCK_ENABLED(context)) {\n\t\tlwsl_notice(\"Creating Vhost '%s' path \\\"%s\\\", %d protocols\\n\",\n\t\t\t\tvh->name, vh->iface, vh->count_protocols);\n\t} else\n#endif\n\t{\n\t\tswitch(info->port) {\n\t\tcase CONTEXT_PORT_NO_LISTEN:\n\t\t\tstrcpy(buf, \"(serving disabled)\");\n\t\t\tbreak;\n\t\tcase CONTEXT_PORT_NO_LISTEN_SERVER:\n\t\t\tstrcpy(buf, \"(no listener)\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tlws_snprintf(buf, sizeof(buf), \"port %u\", info->port);\n\t\t\tbreak;\n\t\t}\n\t\tlwsl_notice(\"Creating Vhost '%s' %s, %d protocols, IPv6 %s\\n\",\n\t\t\t\tvh->name, buf, vh->count_protocols,\n\t\t\t\tLWS_IPV6_ENABLED(vh) ? \"on\" : \"off\");\n\t}\n\tmounts = info->mounts;\n\twhile (mounts) {\n\t\t(void)mount_protocols[0];\n\t\tlwsl_info(\"   mounting %s%s to %s\\n\",\n\t\t\t  mount_protocols[mounts->origin_protocol],\n\t\t\t  mounts->origin, mounts->mountpoint);\n\n\t\t/* convert interpreter protocol names to pointers */\n\t\tpvo = mounts->interpret;\n\t\twhile (pvo) {\n\t\t\tfor (n = 0; n < vh->count_protocols; n++) {\n\t\t\t\tif (strcmp(pvo->value, vh->protocols[n].name))\n\t\t\t\t\tcontinue;\n\t\t\t\t((struct lws_protocol_vhost_options *)pvo)->\n\t\t\t\t\tvalue = (const char *)(lws_intptr_t)n;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (n == vh->count_protocols)\n\t\t\t\tlwsl_err(\"ignoring unknown interp pr %s\\n\",\n\t\t\t\t\t pvo->value);\n\t\t\tpvo = pvo->next;\n\t\t}\n\n\t\tmounts = mounts->mount_next;\n\t}\n\n\tvh->listen_port = info->port;\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tvh->http.http_proxy_port = 0;\n\tvh->http.http_proxy_address[0] = '\\0';\n#endif\n#if defined(LWS_WITH_SOCKS5)\n\tvh->socks_proxy_port = 0;\n\tvh->socks_proxy_address[0] = '\\0';\n#endif\n\n#if !defined(LWS_WITHOUT_CLIENT)\n\t/* either use proxy from info, or try get it from env var */\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\t/* http proxy */\n\tif (info->http_proxy_address) {\n\t\t/* override for backwards compatibility */\n\t\tif (info->http_proxy_port)\n\t\t\tvh->http.http_proxy_port = info->http_proxy_port;\n\t\tlws_set_proxy(vh, info->http_proxy_address);\n\t} else\n#endif\n\t{\n#ifdef LWS_HAVE_GETENV\n\t\tp = getenv(\"http_proxy\");\n\t\tif (p)\n\t\t\tlws_set_proxy(vh, p);\n#endif\n\t}\n#endif\n#if defined(LWS_WITH_SOCKS5)\n\t/* socks proxy */\n\tif (info->socks_proxy_address) {\n\t\t/* override for backwards compatibility */\n\t\tif (info->socks_proxy_port)\n\t\t\tvh->socks_proxy_port = info->socks_proxy_port;\n\t\tlws_set_socks(vh, info->socks_proxy_address);\n\t} else {\n#ifdef LWS_HAVE_GETENV\n\t\tp = getenv(\"socks_proxy\");\n\t\tif (p)\n\t\t\tlws_set_socks(vh, p);\n#endif\n\t}\n#endif\n\n\tvh->ka_time = info->ka_time;\n\tvh->ka_interval = info->ka_interval;\n\tvh->ka_probes = info->ka_probes;\n\n\tif (vh->options & LWS_SERVER_OPTION_STS)\n\t\tlwsl_notice(\"   STS enabled\\n\");\n\n#ifdef LWS_WITH_ACCESS_LOG\n\tif (info->log_filepath) {\n\t\tvh->log_fd = lws_open(info->log_filepath,\n\t\t\t\t  O_CREAT | O_APPEND | O_RDWR, 0600);\n\t\tif (vh->log_fd == (int)LWS_INVALID_FILE) {\n\t\t\tlwsl_err(\"unable to open log filepath %s\\n\",\n\t\t\t\t info->log_filepath);\n\t\t\tgoto bail;\n\t\t}\n#ifndef WIN32\n\t\tif (context->uid != -1)\n\t\t\tif (chown(info->log_filepath, context->uid,\n\t\t\t\t  context->gid) == -1)\n\t\t\t\tlwsl_err(\"unable to chown log file %s\\n\",\n\t\t\t\t\t\tinfo->log_filepath);\n#endif\n\t} else\n\t\tvh->log_fd = (int)LWS_INVALID_FILE;\n#endif\n\tif (lws_context_init_server_ssl(info, vh)) {\n\t\tlwsl_err(\"%s: lws_context_init_server_ssl failed\\n\", __func__);\n\t\tgoto bail1;\n\t}\n\tif (lws_context_init_client_ssl(info, vh)) {\n\t\tlwsl_err(\"%s: lws_context_init_client_ssl failed\\n\", __func__);\n\t\tgoto bail1;\n\t}\n\tlws_context_lock(context);\n\tn = _lws_vhost_init_server(info, vh);\n\tlws_context_unlock(context);\n\tif (n < 0) {\n\t\tlwsl_err(\"init server failed\\n\");\n\t\tgoto bail1;\n\t}\n\n\n\twhile (1) {\n\t\tif (!(*vh1)) {\n\t\t\t*vh1 = vh;\n\t\t\tbreak;\n\t\t}\n\t\tvh1 = &(*vh1)->vhost_next;\n\t};\n\n\t/* for the case we are adding a vhost much later, after server init */\n\n\tif (context->protocol_init_done)\n\t\tif (lws_protocol_init(context)) {\n\t\t\tlwsl_err(\"%s: lws_protocol_init failed\\n\", __func__);\n\t\t\tgoto bail1;\n\t\t}\n\n\treturn vh;\n\nbail1:\n\tlws_vhost_destroy(vh);\n\tlws_vhost_destroy2(vh);\n\n\treturn NULL;\n\n#ifdef LWS_WITH_ACCESS_LOG\nbail:\n\tlws_free(vh);\n#endif\n\n\treturn NULL;\n}\n\nLWS_VISIBLE int\nlws_init_vhost_client_ssl(const struct lws_context_creation_info *info,\n\t\t\t  struct lws_vhost *vhost)\n{\n\tstruct lws_context_creation_info i;\n\n\tmemcpy(&i, info, sizeof(i));\n\ti.port = CONTEXT_PORT_NO_LISTEN;\n\n\treturn lws_context_init_client_ssl(&i, vhost);\n}\n\nLWS_VISIBLE void\nlws_cancel_service_pt(struct lws *wsi)\n{\n\tlws_plat_pipe_signal(wsi);\n}\n\nLWS_VISIBLE void\nlws_cancel_service(struct lws_context *context)\n{\n\tstruct lws_context_per_thread *pt = &context->pt[0];\n\tshort m = context->count_threads;\n\n\tif (context->being_destroyed1)\n\t\treturn;\n\n\tlwsl_info(\"%s\\n\", __func__);\n\n\twhile (m--) {\n\t\tif (pt->pipe_wsi)\n\t\t\tlws_plat_pipe_signal(pt->pipe_wsi);\n\t\tpt++;\n\t}\n}\n\nint\nlws_create_event_pipes(struct lws_context *context)\n{\n\tstruct lws *wsi;\n\tint n;\n\n\t/*\n\t * Create the pt event pipes... these are unique in that they are\n\t * not bound to a vhost or protocol (both are NULL)\n\t */\n\n\tfor (n = 0; n < context->count_threads; n++) {\n\t\tif (context->pt[n].pipe_wsi)\n\t\t\tcontinue;\n\n\t\twsi = lws_zalloc(sizeof(*wsi), \"event pipe wsi\");\n\t\tif (!wsi) {\n\t\t\tlwsl_err(\"Out of mem\\n\");\n\t\t\treturn 1;\n\t\t}\n\t\twsi->context = context;\n\t\tlws_role_transition(wsi, 0, LRS_UNCONNECTED, &role_ops_pipe);\n\t\twsi->protocol = NULL;\n\t\twsi->tsi = n;\n\t\twsi->vhost = NULL;\n\t\twsi->event_pipe = 1;\n\t\twsi->desc.sockfd = LWS_SOCK_INVALID;\n\t\tcontext->pt[n].pipe_wsi = wsi;\n\t\tcontext->count_wsi_allocated++;\n\n\t\tif (lws_plat_pipe_create(wsi))\n\t\t\t/*\n\t\t\t * platform code returns 0 if it actually created pipes\n\t\t\t * and initialized pt->dummy_pipe_fds[].  If it used\n\t\t\t * some other mechanism outside of signaling in the\n\t\t\t * normal event loop, we skip treating the pipe as\n\t\t\t * related to dummy_pipe_fds[], adding it to the fds,\n\t\t\t * etc.\n\t\t\t */\n\t\t\tcontinue;\n\n\t\twsi->desc.sockfd = context->pt[n].dummy_pipe_fds[0];\n\t\tlwsl_debug(\"event pipe fd %d\\n\", wsi->desc.sockfd);\n\n\t\tif (context->event_loop_ops->accept)\n\t\t\tcontext->event_loop_ops->accept(wsi);\n\n\t\tif (__insert_wsi_socket_into_fds(context, wsi))\n\t\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\nvoid\nlws_destroy_event_pipe(struct lws *wsi)\n{\n\tlwsl_info(\"%s\\n\", __func__);\n\t__remove_wsi_socket_from_fds(wsi);\n\n\tif (wsi->context->event_loop_ops->wsi_logical_close) {\n\t\twsi->context->event_loop_ops->wsi_logical_close(wsi);\n\t\tlws_plat_pipe_close(wsi);\n\t\treturn;\n\t}\n\n\tif (wsi->context->event_loop_ops->destroy_wsi)\n\t\twsi->context->event_loop_ops->destroy_wsi(wsi);\n\tlws_plat_pipe_close(wsi);\n\twsi->context->count_wsi_allocated--;\n\tlws_free(wsi);\n}\n\nLWS_VISIBLE struct lws_context *\nlws_create_context(const struct lws_context_creation_info *info)\n{\n\tstruct lws_context *context = NULL;\n\tstruct lws_plat_file_ops *prev;\n#ifndef LWS_NO_DAEMONIZE\n\tint pid_daemon = get_daemonize_pid();\n#endif\n\tint n;\n#if defined(__ANDROID__)\n\tstruct rlimit rt;\n#endif\n\n\n\n\tlwsl_info(\"Initial logging level %d\\n\", log_level);\n\tlwsl_info(\"Libwebsockets version: %s\\n\", library_version);\n#if defined(GCC_VER)\n\tlwsl_info(\"Compiled with  %s\\n\", GCC_VER);\n#endif\n\n#ifdef LWS_WITH_IPV6\n\tif (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6))\n\t\tlwsl_info(\"IPV6 compiled in and enabled\\n\");\n\telse\n\t\tlwsl_info(\"IPV6 compiled in but disabled\\n\");\n#else\n\tlwsl_info(\"IPV6 not compiled in\\n\");\n#endif\n\n\tlwsl_info(\" LWS_DEF_HEADER_LEN    : %u\\n\", LWS_DEF_HEADER_LEN);\n\tlwsl_info(\" LWS_MAX_PROTOCOLS     : %u\\n\", LWS_MAX_PROTOCOLS);\n\tlwsl_info(\" LWS_MAX_SMP           : %u\\n\", LWS_MAX_SMP);\n\tlwsl_info(\" sizeof (*info)        : %ld\\n\", (long)sizeof(*info));\n#if defined(LWS_WITH_STATS)\n\tlwsl_info(\" LWS_WITH_STATS        : on\\n\");\n#endif\n\tlwsl_info(\" SYSTEM_RANDOM_FILEPATH: '%s'\\n\", SYSTEM_RANDOM_FILEPATH);\n#if defined(LWS_WITH_HTTP2)\n\tlwsl_info(\" HTTP2 support         : available\\n\");\n#else\n\tlwsl_info(\" HTTP2 support         : not configured\\n\");\n#endif\n\tif (lws_plat_context_early_init())\n\t\treturn NULL;\n\n\tcontext = lws_zalloc(sizeof(struct lws_context), \"context\");\n\tif (!context) {\n\t\tlwsl_err(\"No memory for websocket context\\n\");\n\t\treturn NULL;\n\t}\n\n#if defined(LWS_WITH_TLS)\n#if defined(LWS_WITH_MBEDTLS)\n\tcontext->tls_ops = &tls_ops_mbedtls;\n#else\n\tcontext->tls_ops = &tls_ops_openssl;\n#endif\n#endif\n\n\tif (info->pt_serv_buf_size)\n\t\tcontext->pt_serv_buf_size = info->pt_serv_buf_size;\n\telse\n\t\tcontext->pt_serv_buf_size = 4096;\n\n#if defined(LWS_ROLE_H2)\n\trole_ops_h2.init_context(context, info);\n#endif\n\n#if LWS_MAX_SMP > 1\n\tpthread_mutex_init(&context->lock, NULL);\n#endif\n\n#if defined(LWS_WITH_ESP32)\n\tcontext->last_free_heap = esp_get_free_heap_size();\n#endif\n\n\t/* default to just the platform fops implementation */\n\n\tcontext->fops_platform.LWS_FOP_OPEN\t= _lws_plat_file_open;\n\tcontext->fops_platform.LWS_FOP_CLOSE\t= _lws_plat_file_close;\n\tcontext->fops_platform.LWS_FOP_SEEK_CUR\t= _lws_plat_file_seek_cur;\n\tcontext->fops_platform.LWS_FOP_READ\t= _lws_plat_file_read;\n\tcontext->fops_platform.LWS_FOP_WRITE\t= _lws_plat_file_write;\n\tcontext->fops_platform.fi[0].sig\t= NULL;\n\n\t/*\n\t *  arrange a linear linked-list of fops starting from context->fops\n\t *\n\t * platform fops\n\t * [ -> fops_zip (copied into context so .next settable) ]\n\t * [ -> info->fops ]\n\t */\n\n\tcontext->fops = &context->fops_platform;\n\tprev = (struct lws_plat_file_ops *)context->fops;\n\n#if defined(LWS_WITH_ZIP_FOPS)\n\t/* make a soft copy so we can set .next */\n\tcontext->fops_zip = fops_zip;\n\tprev->next = &context->fops_zip;\n\tprev = (struct lws_plat_file_ops *)prev->next;\n#endif\n\n\t/* if user provided fops, tack them on the end of the list */\n\tif (info->fops)\n\t\tprev->next = info->fops;\n\n\tcontext->reject_service_keywords = info->reject_service_keywords;\n\tif (info->external_baggage_free_on_destroy)\n\t\tcontext->external_baggage_free_on_destroy =\n\t\t\tinfo->external_baggage_free_on_destroy;\n\n\tcontext->time_up = time(NULL);\n\tcontext->pcontext_finalize = info->pcontext;\n\n\tcontext->simultaneous_ssl_restriction =\n\t\t\tinfo->simultaneous_ssl_restriction;\n\n#ifndef LWS_NO_DAEMONIZE\n\tif (pid_daemon) {\n\t\tcontext->started_with_parent = pid_daemon;\n\t\tlwsl_info(\" Started with daemon pid %d\\n\", pid_daemon);\n\t}\n#endif\n#if defined(__ANDROID__)\n\t\tn = getrlimit ( RLIMIT_NOFILE,&rt);\n\t\tif (-1 == n) {\n\t\t\tlwsl_err(\"Get RLIMIT_NOFILE failed!\\n\");\n\t\t\treturn NULL;\n\t\t}\n\t\tcontext->max_fds = rt.rlim_cur;\n#else\n\t\tcontext->max_fds = getdtablesize();\n#endif\n\n\tif (info->count_threads)\n\t\tcontext->count_threads = info->count_threads;\n\telse\n\t\tcontext->count_threads = 1;\n\n\tif (context->count_threads > LWS_MAX_SMP)\n\t\tcontext->count_threads = LWS_MAX_SMP;\n\n\tcontext->token_limits = info->token_limits;\n\n\tcontext->options = info->options;\n\n\t/*\n\t * set the context event loops ops struct\n\t *\n\t * after this, all event_loop actions use the generic ops\n\t */\n\n#if defined(LWS_WITH_POLL)\n\tcontext->event_loop_ops = &event_loop_ops_poll;\n#endif\n\n\tif (lws_check_opt(context->options, LWS_SERVER_OPTION_LIBUV))\n#if defined(LWS_WITH_LIBUV)\n\t\tcontext->event_loop_ops = &event_loop_ops_uv;\n#else\n\t\tgoto fail_event_libs;\n#endif\n\n\tif (lws_check_opt(context->options, LWS_SERVER_OPTION_LIBEV))\n#if defined(LWS_WITH_LIBEV)\n\t\tcontext->event_loop_ops = &event_loop_ops_ev;\n#else\n\t\tgoto fail_event_libs;\n#endif\n\n\tif (lws_check_opt(context->options, LWS_SERVER_OPTION_LIBEVENT))\n#if defined(LWS_WITH_LIBEVENT)\n\t\tcontext->event_loop_ops = &event_loop_ops_event;\n#else\n\t\tgoto fail_event_libs;\n#endif\n\n\tif (!context->event_loop_ops)\n\t\tgoto fail_event_libs;\n\n\tlwsl_info(\"Using event loop: %s\\n\", context->event_loop_ops->name);\n\n#if defined(LWS_WITH_TLS)\n\ttime(&context->tls.last_cert_check_s);\n\tif (info->alpn)\n\t\tcontext->tls.alpn_default = info->alpn;\n\telse {\n\t\tchar *p = context->tls.alpn_discovered, first = 1;\n\n\t\tLWS_FOR_EVERY_AVAILABLE_ROLE_START(ar) {\n\t\t\tif (ar->alpn) {\n\t\t\t\tif (!first)\n\t\t\t\t\t*p++ = ',';\n\t\t\t\tp += lws_snprintf(p,\n\t\t\t\t\tcontext->tls.alpn_discovered +\n\t\t\t\t\tsizeof(context->tls.alpn_discovered) -\n\t\t\t\t\t2 - p, \"%s\", ar->alpn);\n\t\t\t\tfirst = 0;\n\t\t\t}\n\t\t} LWS_FOR_EVERY_AVAILABLE_ROLE_END;\n\n\t\tcontext->tls.alpn_default = context->tls.alpn_discovered;\n\t}\n\n\tlwsl_info(\"Default ALPN advertisment: %s\\n\", context->tls.alpn_default);\n#endif\n\n\tif (info->timeout_secs)\n\t\tcontext->timeout_secs = info->timeout_secs;\n\telse\n\t\tcontext->timeout_secs = AWAITING_TIMEOUT;\n\n\tcontext->ws_ping_pong_interval = info->ws_ping_pong_interval;\n\n\tlwsl_info(\" default timeout (secs): %u\\n\", context->timeout_secs);\n\n\tif (info->max_http_header_data)\n\t\tcontext->max_http_header_data = info->max_http_header_data;\n\telse\n\t\tif (info->max_http_header_data2)\n\t\t\tcontext->max_http_header_data =\n\t\t\t\t\tinfo->max_http_header_data2;\n\t\telse\n\t\t\tcontext->max_http_header_data = LWS_DEF_HEADER_LEN;\n\n\tif (info->max_http_header_pool)\n\t\tcontext->max_http_header_pool = info->max_http_header_pool;\n\telse\n\t\tcontext->max_http_header_pool = context->max_fds;\n\n\tif (info->fd_limit_per_thread)\n\t\tcontext->fd_limit_per_thread = info->fd_limit_per_thread;\n\telse\n\t\tcontext->fd_limit_per_thread = context->max_fds /\n\t\t\t\t\t       context->count_threads;\n\n\t/*\n\t * Allocate the per-thread storage for scratchpad buffers,\n\t * and header data pool\n\t */\n\tfor (n = 0; n < context->count_threads; n++) {\n\t\tcontext->pt[n].serv_buf = lws_malloc(context->pt_serv_buf_size,\n\t\t\t\t\t\t     \"pt_serv_buf\");\n\t\tif (!context->pt[n].serv_buf) {\n\t\t\tlwsl_err(\"OOM\\n\");\n\t\t\treturn NULL;\n\t\t}\n\n\t\tcontext->pt[n].context = context;\n\t\tcontext->pt[n].tid = n;\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\t\tcontext->pt[n].http.ah_list = NULL;\n\t\tcontext->pt[n].http.ah_pool_length = 0;\n#endif\n\t\tlws_pt_mutex_init(&context->pt[n]);\n\t}\n\n\tlwsl_info(\" Threads: %d each %d fds\\n\", context->count_threads,\n\t\t    context->fd_limit_per_thread);\n\n\tif (!info->ka_interval && info->ka_time > 0) {\n\t\tlwsl_err(\"info->ka_interval can't be 0 if ka_time used\\n\");\n\t\treturn NULL;\n\t}\n\n\n#if defined(LWS_WITH_PEER_LIMITS)\n\t/* scale the peer hash table according to the max fds for the process,\n\t * so that the max list depth averages 16.  Eg, 1024 fd -> 64,\n\t * 102400 fd -> 6400\n\t */\n\tcontext->pl_hash_elements =\n\t\t(context->count_threads * context->fd_limit_per_thread) / 16;\n\tcontext->pl_hash_table = lws_zalloc(sizeof(struct lws_peer *) *\n\t\t\tcontext->pl_hash_elements, \"peer limits hash table\");\n\tcontext->ip_limit_ah = info->ip_limit_ah;\n\tcontext->ip_limit_wsi = info->ip_limit_wsi;\n#endif\n\n\tlwsl_info(\" mem: context:         %5lu B (%ld ctx + (%ld thr x %d))\\n\",\n\t\t  (long)sizeof(struct lws_context) +\n\t\t  (context->count_threads * context->pt_serv_buf_size),\n\t\t  (long)sizeof(struct lws_context),\n\t\t  (long)context->count_threads,\n\t\t  context->pt_serv_buf_size);\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tlwsl_info(\" mem: http hdr rsvd:   %5lu B (%u thr x (%u + %lu) x %u))\\n\",\n\t\t    (long)(context->max_http_header_data +\n\t\t     sizeof(struct allocated_headers)) *\n\t\t    context->max_http_header_pool * context->count_threads,\n\t\t    context->count_threads,\n\t\t    context->max_http_header_data,\n\t\t    (long)sizeof(struct allocated_headers),\n\t\t    context->max_http_header_pool);\n#endif\n\tn = sizeof(struct lws_pollfd) * context->count_threads *\n\t    context->fd_limit_per_thread;\n\tcontext->pt[0].fds = lws_zalloc(n, \"fds table\");\n\tif (context->pt[0].fds == NULL) {\n\t\tlwsl_err(\"OOM allocating %d fds\\n\", context->max_fds);\n\t\tgoto bail;\n\t}\n\tlwsl_info(\" mem: pollfd map:      %5u\\n\", n);\n\n\tif (info->server_string) {\n\t\tcontext->server_string = info->server_string;\n\t\tcontext->server_string_len = (short)\n\t\t\t\tstrlen(context->server_string);\n\t}\n\n#if LWS_MAX_SMP > 1\n\t/* each thread serves his own chunk of fds */\n\tfor (n = 1; n < (int)info->count_threads; n++)\n\t\tcontext->pt[n].fds = context->pt[n - 1].fds +\n\t\t\t\t     context->fd_limit_per_thread;\n#endif\n\n\tif (lws_plat_init(context, info))\n\t\tgoto bail;\n\n\tif (context->event_loop_ops->init_context)\n\t\tif (context->event_loop_ops->init_context(context, info))\n\t\t\tgoto bail;\n\n\n\tif (context->event_loop_ops->init_pt)\n\t\tfor (n = 0; n < context->count_threads; n++) {\n\t\t\tvoid *lp = NULL;\n\n\t\t\tif (info->foreign_loops)\n\t\t\t\tlp = info->foreign_loops[n];\n\n\t\t\tif (context->event_loop_ops->init_pt(context, lp, n))\n\t\t\t\tgoto bail;\n\t\t}\n\n\tif (lws_create_event_pipes(context))\n\t\tgoto bail;\n\n\tlws_context_init_ssl_library(info);\n\n\tcontext->user_space = info->user;\n\n\t/*\n\t * if he's not saying he'll make his own vhosts later then act\n\t * compatibly and make a default vhost using the data in the info\n\t */\n\tif (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))\n\t\tif (!lws_create_vhost(context, info)) {\n\t\t\tlwsl_err(\"Failed to create default vhost\\n\");\n\t\t\tfor (n = 0; n < context->count_threads; n++)\n\t\t\t\tlws_free_set_NULL(context->pt[n].serv_buf);\n#if defined(LWS_WITH_PEER_LIMITS)\n\t\t\tlws_free_set_NULL(context->pl_hash_table);\n#endif\n\t\t\tlws_free_set_NULL(context->pt[0].fds);\n\t\t\tlws_plat_context_late_destroy(context);\n\t\t\tlws_free_set_NULL(context);\n\t\t\treturn NULL;\n\t\t}\n\n\tlws_context_init_extensions(info, context);\n\n\tlwsl_info(\" mem: per-conn:        %5lu bytes + protocol rx buf\\n\",\n\t\t    (unsigned long)sizeof(struct lws));\n\n\tstrcpy(context->canonical_hostname, \"unknown\");\n\tlws_server_get_canonical_hostname(context, info);\n\n\tcontext->uid = info->uid;\n\tcontext->gid = info->gid;\n\n#if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)\n\tmemcpy(context->caps, info->caps, sizeof(context->caps));\n\tcontext->count_caps = info->count_caps;\n#endif\n\n\t/*\n\t * drop any root privs for this process\n\t * to listen on port < 1023 we would have needed root, but now we are\n\t * listening, we don't want the power for anything else\n\t */\n\tif (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))\n\t\tlws_plat_drop_app_privileges(info);\n\n\t/* expedite post-context init (eg, protocols) */\n\tlws_cancel_service(context);\n\n#if defined(LWS_WITH_SELFTESTS)\n\tlws_jws_selftest();\n#endif\n\n\treturn context;\n\nbail:\n\tlws_context_destroy(context);\n\n\treturn NULL;\n\nfail_event_libs:\n\tlwsl_err(\"Requested event library support not configured, available:\\n\");\n\t{\n\t\tconst struct lws_event_loop_ops **elops = available_event_libs;\n\n\t\twhile (*elops) {\n\t\t\tlwsl_err(\"  - %s\\n\", (*elops)->name);\n\t\t\telops++;\n\t\t}\n\t}\n\tlws_free(context);\n\n\treturn NULL;\n}\n\nLWS_VISIBLE LWS_EXTERN void\nlws_context_deprecate(struct lws_context *context, lws_reload_func cb)\n{\n\tstruct lws_vhost *vh = context->vhost_list, *vh1;\n\tstruct lws *wsi;\n\n\t/*\n\t * \"deprecation\" means disable the context from accepting any new\n\t * connections and free up listen sockets to be used by a replacement\n\t * context.\n\t *\n\t * Otherwise the deprecated context remains operational, until its\n\t * number of connected sockets falls to zero, when it is deleted.\n\t */\n\n\t/* for each vhost, close his listen socket */\n\n\twhile (vh) {\n\t\twsi = vh->lserv_wsi;\n\t\tif (wsi) {\n\t\t\twsi->socket_is_permanently_unusable = 1;\n\t\t\tlws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, \"ctx deprecate\");\n\t\t\twsi->context->deprecation_pending_listen_close_count++;\n\t\t\t/*\n\t\t\t * other vhosts can share the listen port, they\n\t\t\t * point to the same wsi.  So zap those too.\n\t\t\t */\n\t\t\tvh1 = context->vhost_list;\n\t\t\twhile (vh1) {\n\t\t\t\tif (vh1->lserv_wsi == wsi)\n\t\t\t\t\tvh1->lserv_wsi = NULL;\n\t\t\t\tvh1 = vh1->vhost_next;\n\t\t\t}\n\t\t}\n\t\tvh = vh->vhost_next;\n\t}\n\n\tcontext->deprecated = 1;\n\tcontext->deprecation_cb = cb;\n}\n\nLWS_VISIBLE LWS_EXTERN int\nlws_context_is_deprecated(struct lws_context *context)\n{\n\treturn context->deprecated;\n}\n\nvoid\nlws_vhost_destroy1(struct lws_vhost *vh)\n{\n\tconst struct lws_protocols *protocol = NULL;\n\tstruct lws_context_per_thread *pt;\n\tint n, m = vh->context->count_threads;\n\tstruct lws_context *context = vh->context;\n\tstruct lws wsi;\n\n\tlwsl_info(\"%s\\n\", __func__);\n\n\tif (vh->being_destroyed)\n\t\treturn;\n\n\tvh->being_destroyed = 1;\n\n\t/*\n\t * Are there other vhosts that are piggybacking on our listen socket?\n\t * If so we need to hand the listen socket off to one of the others\n\t * so it will remain open.  If not, leave it attached to the closing\n\t * vhost and it will get closed.\n\t */\n\n\tif (vh->lserv_wsi)\n\t\tlws_start_foreach_ll(struct lws_vhost *, v,\n\t\t\t\t     context->vhost_list) {\n\t\t\tif (v != vh &&\n\t\t\t    !v->being_destroyed &&\n\t\t\t    v->listen_port == vh->listen_port &&\n\t\t\t    ((!v->iface && !vh->iface) ||\n\t\t\t    (v->iface && vh->iface &&\n\t\t\t    !strcmp(v->iface, vh->iface)))) {\n\t\t\t\t/*\n\t\t\t\t * this can only be a listen wsi, which is\n\t\t\t\t * restricted... it has no protocol or other\n\t\t\t\t * bindings or states.  So we can simply\n\t\t\t\t * swap it to a vhost that has the same\n\t\t\t\t * iface + port, but is not closing.\n\t\t\t\t */\n\t\t\t\tassert(v->lserv_wsi == NULL);\n\t\t\t\tv->lserv_wsi = vh->lserv_wsi;\n\t\t\t\tvh->lserv_wsi = NULL;\n\t\t\t\tif (v->lserv_wsi)\n\t\t\t\t\tv->lserv_wsi->vhost = v;\n\n\t\t\t\tlwsl_notice(\"%s: listen skt from %s to %s\\n\",\n\t\t\t\t\t    __func__, vh->name, v->name);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} lws_end_foreach_ll(v, vhost_next);\n\n\t/*\n\t * Forcibly close every wsi assoicated with this vhost.  That will\n\t * include the listen socket if it is still associated with the closing\n\t * vhost.\n\t */\n\n\twhile (m--) {\n\t\tpt = &context->pt[m];\n\n\t\tfor (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {\n\t\t\tstruct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);\n\t\t\tif (!wsi)\n\t\t\t\tcontinue;\n\t\t\tif (wsi->vhost != vh)\n\t\t\t\tcontinue;\n\n\t\t\tlws_close_free_wsi(wsi,\n\t\t\t\tLWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY,\n\t\t\t\t\"vh destroy\"\n\t\t\t\t/* no protocol close */);\n\t\t\tn--;\n\t\t}\n\t}\n\n\t/*\n\t * destroy any pending timed events\n\t */\n\n\twhile (vh->timed_vh_protocol_list)\n\t\tlws_timed_callback_remove(vh, vh->timed_vh_protocol_list);\n\n\t/*\n\t * let the protocols destroy the per-vhost protocol objects\n\t */\n\n\tmemset(&wsi, 0, sizeof(wsi));\n\twsi.context = vh->context;\n\twsi.vhost = vh;\n\tprotocol = vh->protocols;\n\tif (protocol && vh->created_vhost_protocols) {\n\t\tn = 0;\n\t\twhile (n < vh->count_protocols) {\n\t\t\twsi.protocol = protocol;\n\t\t\tprotocol->callback(&wsi, LWS_CALLBACK_PROTOCOL_DESTROY,\n\t\t\t\t\t   NULL, NULL, 0);\n\t\t\tprotocol++;\n\t\t\tn++;\n\t\t}\n\t}\n\n\t/*\n\t * remove vhost from context list of vhosts\n\t */\n\n\tlws_start_foreach_llp(struct lws_vhost **, pv, context->vhost_list) {\n\t\tif (*pv == vh) {\n\t\t\t*pv = vh->vhost_next;\n\t\t\tbreak;\n\t\t}\n\t} lws_end_foreach_llp(pv, vhost_next);\n\n\t/* add ourselves to the pending destruction list */\n\n\tvh->vhost_next = vh->context->vhost_pending_destruction_list;\n\tvh->context->vhost_pending_destruction_list = vh;\n}\n\nstatic void\nlws_vhost_destroy2(struct lws_vhost *vh)\n{\n\tconst struct lws_protocols *protocol = NULL;\n\tstruct lws_context *context = vh->context;\n\tstruct lws_deferred_free *df;\n\tint n;\n\n\tlwsl_info(\"%s: %p\\n\", __func__, vh);\n\n\t/* if we are still on deferred free list, remove ourselves */\n\n\tlws_start_foreach_llp(struct lws_deferred_free **, pdf,\n\t\t\t      context->deferred_free_list) {\n\t\tif ((*pdf)->payload == vh) {\n\t\t\tdf = *pdf;\n\t\t\t*pdf = df->next;\n\t\t\tlws_free(df);\n\t\t\tbreak;\n\t\t}\n\t} lws_end_foreach_llp(pdf, next);\n\n\t/* remove ourselves from the pending destruction list */\n\n\tlws_start_foreach_llp(struct lws_vhost **, pv,\n\t\t\t      context->vhost_pending_destruction_list) {\n\t\tif ((*pv) == vh) {\n\t\t\t*pv = (*pv)->vhost_next;\n\t\t\tbreak;\n\t\t}\n\t} lws_end_foreach_llp(pv, vhost_next);\n\n\t/*\n\t * Free all the allocations associated with the vhost\n\t */\n\n\tprotocol = vh->protocols;\n\tif (protocol) {\n\t\tn = 0;\n\t\twhile (n < vh->count_protocols) {\n\t\t\tif (vh->protocol_vh_privs &&\n\t\t\t    vh->protocol_vh_privs[n]) {\n\t\t\t\tlws_free(vh->protocol_vh_privs[n]);\n\t\t\t\tvh->protocol_vh_privs[n] = NULL;\n\t\t\t}\n\t\t\tprotocol++;\n\t\t\tn++;\n\t\t}\n\t}\n\tif (vh->protocol_vh_privs)\n\t\tlws_free(vh->protocol_vh_privs);\n\tlws_ssl_SSL_CTX_destroy(vh);\n\tlws_free(vh->same_vh_protocol_list);\n\n\tif (context->plugin_list ||\n\t    (context->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS))\n\t\tlws_free((void *)vh->protocols);\n\n\tLWS_FOR_EVERY_AVAILABLE_ROLE_START(ar)\n\t\tif (ar->destroy_vhost)\n\t\t\tar->destroy_vhost(vh);\n\tLWS_FOR_EVERY_AVAILABLE_ROLE_END;\n\n#ifdef LWS_WITH_ACCESS_LOG\n\tif (vh->log_fd != (int)LWS_INVALID_FILE)\n\t\tclose(vh->log_fd);\n#endif\n\n#if defined (LWS_WITH_TLS)\n\tlws_free_set_NULL(vh->tls.alloc_cert_path);\n#endif\n\n#if LWS_MAX_SMP > 1\n       pthread_mutex_destroy(&vh->lock);\n#endif\n\n#if defined(LWS_WITH_UNIX_SOCK)\n\tif (LWS_UNIX_SOCK_ENABLED(context)) {\n\t\tn = unlink(vh->iface);\n\t\tif (n)\n\t\t\tlwsl_info(\"Closing unix socket %s: errno %d\\n\",\n\t\t\t\t  vh->iface, errno);\n\t}\n#endif\n\t/*\n\t * although async event callbacks may still come for wsi handles with\n\t * pending close in the case of asycn event library like libuv,\n\t * they do not refer to the vhost.  So it's safe to free.\n\t */\n\n\tlwsl_info(\"  %s: Freeing vhost %p\\n\", __func__, vh);\n\n\tmemset(vh, 0, sizeof(*vh));\n\tlws_free(vh);\n}\n\nint\nlws_check_deferred_free(struct lws_context *context, int force)\n{\n\tstruct lws_deferred_free *df;\n\ttime_t now = lws_now_secs();\n\n\tlws_start_foreach_llp(struct lws_deferred_free **, pdf,\n\t\t\t      context->deferred_free_list) {\n\t\tif (force ||\n\t\t    lws_compare_time_t(context, now, (*pdf)->deadline) > 5) {\n\t\t\tdf = *pdf;\n\t\t\t*pdf = df->next;\n\t\t\t/* finalize vh destruction */\n\t\t\tlwsl_notice(\"deferred vh %p destroy\\n\", df->payload);\n\t\t\tlws_vhost_destroy2(df->payload);\n\t\t\tlws_free(df);\n\t\t\tcontinue; /* after deletion we already point to next */\n\t\t}\n\t} lws_end_foreach_llp(pdf, next);\n\n\treturn 0;\n}\n\nLWS_VISIBLE void\nlws_vhost_destroy(struct lws_vhost *vh)\n{\n\tstruct lws_deferred_free *df = lws_malloc(sizeof(*df), \"deferred free\");\n\n\tif (!df)\n\t\treturn;\n\n\tlws_vhost_destroy1(vh);\n\n\t/* part 2 is deferred to allow all the handle closes to complete */\n\n\tdf->next = vh->context->deferred_free_list;\n\tdf->deadline = lws_now_secs();\n\tdf->payload = vh;\n\tvh->context->deferred_free_list = df;\n}\n\n/*\n * When using an event loop, the context destruction is in three separate\n * parts.  This is to cover both internal and foreign event loops cleanly.\n *\n *  - lws_context_destroy() simply starts a soft close of all wsi and\n *     related allocations.  The event loop continues.\n *\n *     As the closes complete in the event loop, reference counting is used\n *     to determine when everything is closed.  It then calls\n *     lws_context_destroy2().\n *\n *  - lws_context_destroy2() cleans up the rest of the higher-level logical\n *     lws pieces like vhosts.  If the loop was foreign, it then proceeds to\n *     lws_context_destroy3().  If it the loop is internal, it stops the\n *     internal loops and waits for lws_context_destroy() to be called again\n *     outside the event loop (since we cannot destroy the loop from\n *     within the loop).  That will cause lws_context_destroy3() to run\n *     directly.\n *\n *  - lws_context_destroy3() destroys any internal event loops and then\n *     destroys the context itself, setting what was info.pcontext to NULL.\n */\n\n/*\n * destroy the actual context itself\n */\n\nstatic void\nlws_context_destroy3(struct lws_context *context)\n{\n\tstruct lws_context **pcontext_finalize = context->pcontext_finalize;\n\tstruct lws_context_per_thread *pt;\n\tint n;\n\n\tfor (n = 0; n < context->count_threads; n++) {\n\t\tpt = &context->pt[n];\n\n\t\tif (context->event_loop_ops->destroy_pt)\n\t\t\tcontext->event_loop_ops->destroy_pt(context, n);\n\n\t\tlws_free_set_NULL(context->pt[n].serv_buf);\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\t\twhile (pt->http.ah_list)\n\t\t\t_lws_destroy_ah(pt, pt->http.ah_list);\n#endif\n\t}\n\n\tlws_free(context);\n\tlwsl_info(\"%s: ctx %p freed\\n\", __func__, context);\n\n\tif (pcontext_finalize)\n\t\t*pcontext_finalize = NULL;\n}\n\n/*\n * really start destroying things\n */\n\nvoid\nlws_context_destroy2(struct lws_context *context)\n{\n\tstruct lws_vhost *vh = NULL, *vh1;\n#if defined(LWS_WITH_PEER_LIMITS)\n\tuint32_t nu;\n#endif\n\tint n;\n\n\tlwsl_info(\"%s: ctx %p\\n\", __func__, context);\n\n\tcontext->being_destroyed2 = 1;\n\n\tif (context->pt[0].fds)\n\t\tlws_free_set_NULL(context->pt[0].fds);\n\n\t/*\n\t * free all the per-vhost allocations\n\t */\n\n\tvh = context->vhost_list;\n\twhile (vh) {\n\t\tvh1 = vh->vhost_next;\n\t\tlws_vhost_destroy2(vh);\n\t\tvh = vh1;\n\t}\n\n\t/* remove ourselves from the pending destruction list */\n\n\twhile (context->vhost_pending_destruction_list)\n\t\t/* removes itself from list */\n\t\tlws_vhost_destroy2(context->vhost_pending_destruction_list);\n\n\n\tlws_stats_log_dump(context);\n\n\tlws_ssl_context_destroy(context);\n\tlws_plat_context_late_destroy(context);\n\n#if defined(LWS_WITH_PEER_LIMITS)\n\tfor (nu = 0; nu < context->pl_hash_elements; nu++)\t{\n\t\tlws_start_foreach_llp(struct lws_peer **, peer,\n\t\t\t\t      context->pl_hash_table[nu]) {\n\t\t\tstruct lws_peer *df = *peer;\n\t\t\t*peer = df->next;\n\t\t\tlws_free(df);\n\t\t\tcontinue;\n\t\t} lws_end_foreach_llp(peer, next);\n\t}\n\tlws_free(context->pl_hash_table);\n#endif\n\n\tif (context->external_baggage_free_on_destroy)\n\t\tfree(context->external_baggage_free_on_destroy);\n\n\tlws_check_deferred_free(context, 1);\n\n#if LWS_MAX_SMP > 1\n\tpthread_mutex_destroy(&context->lock);\n#endif\n\n\tif (context->event_loop_ops->destroy_context2)\n\t\tif (context->event_loop_ops->destroy_context2(context)) {\n\t\t\tcontext->finalize_destroy_after_internal_loops_stopped = 1;\n\t\t\treturn;\n\t\t}\n\n\tif (!context->pt[0].event_loop_foreign)\n\t\tfor (n = 0; n < context->count_threads; n++)\n\t\t\tif (context->pt[n].inside_service)\n\t\t\t\treturn;\n\n\tlws_context_destroy3(context);\n}\n\n/*\n * Begin the context takedown\n */\n\nLWS_VISIBLE void\nlws_context_destroy(struct lws_context *context)\n{\n\tvolatile struct lws_foreign_thread_pollfd *ftp, *next;\n\tvolatile struct lws_context_per_thread *vpt;\n\tstruct lws_context_per_thread *pt;\n\tstruct lws_vhost *vh = NULL;\n\tstruct lws wsi;\n\tint n, m;\n\n\tif (!context)\n\t\treturn;\n\n\tif (context->finalize_destroy_after_internal_loops_stopped) {\n\t\tif (context->event_loop_ops->destroy_context2)\n\t\t\tcontext->event_loop_ops->destroy_context2(context);\n\n\t\tlws_context_destroy3(context);\n\n\t\treturn;\n\t}\n\n\tif (context->being_destroyed1) {\n\t\tif (!context->being_destroyed2) {\n\t\t\tlws_context_destroy2(context);\n\n\t\t\treturn;\n\t\t}\n\t\tlwsl_info(\"%s: ctx %p: already being destroyed\\n\",\n\t\t\t    __func__, context);\n\n\t\tlws_context_destroy3(context);\n\t\treturn;\n\t}\n\n\tlwsl_info(\"%s: ctx %p\\n\", __func__, context);\n\n\tm = context->count_threads;\n\tcontext->being_destroyed = 1;\n\tcontext->being_destroyed1 = 1;\n\tcontext->requested_kill = 1;\n\n\tmemset(&wsi, 0, sizeof(wsi));\n\twsi.context = context;\n\n#ifdef LWS_LATENCY\n\tif (context->worst_latency_info[0])\n\t\tlwsl_notice(\"Worst latency: %s\\n\", context->worst_latency_info);\n#endif\n\n\twhile (m--) {\n\t\tpt = &context->pt[m];\n\t\tvpt = (volatile struct lws_context_per_thread *)pt;\n\n\t\tftp = vpt->foreign_pfd_list;\n\t\twhile (ftp) {\n\t\t\tnext = ftp->next;\n\t\t\tlws_free((void *)ftp);\n\t\t\tftp = next;\n\t\t}\n\t\tvpt->foreign_pfd_list = NULL;\n\n\t\tfor (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) {\n\t\t\tstruct lws *wsi = wsi_from_fd(context, pt->fds[n].fd);\n\t\t\tif (!wsi)\n\t\t\t\tcontinue;\n\n\t\t\tif (wsi->event_pipe)\n\t\t\t\tlws_destroy_event_pipe(wsi);\n\t\t\telse\n\t\t\t\tlws_close_free_wsi(wsi,\n\t\t\t\t\tLWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY,\n\t\t\t\t\t\"ctx destroy\"\n\t\t\t\t\t/* no protocol close */);\n\t\t\tn--;\n\t\t}\n\t\tlws_pt_mutex_destroy(pt);\n\t}\n\n\t/*\n\t * inform all the protocols that they are done and will have no more\n\t * callbacks.\n\t *\n\t * We can't free things until after the event loop shuts down.\n\t */\n\tif (context->protocol_init_done)\n\t\tvh = context->vhost_list;\n\twhile (vh) {\n\t\tstruct lws_vhost *vhn = vh->vhost_next;\n\t\tlws_vhost_destroy1(vh);\n\t\tvh = vhn;\n\t}\n\n\tlws_plat_context_early_destroy(context);\n\n\t/*\n\t * We face two different needs depending if foreign loop or not.\n\t *\n\t * 1) If foreign loop, we really want to advance the destroy_context()\n\t *    past here, and block only for libuv-style async close completion.\n\t *\n\t * 2a) If poll, and we exited by ourselves and are calling a final\n\t *     destroy_context() outside of any service already, we want to\n\t *     advance all the way in one step.\n\t *\n\t * 2b) If poll, and we are reacting to a SIGINT, service thread(s) may\n\t *     be in poll wait or servicing.  We can't advance the\n\t *     destroy_context() to the point it's freeing things; we have to\n\t *     leave that for the final destroy_context() after the service\n\t *     thread(s) are finished calling for service.\n\t */\n\n\tif (context->event_loop_ops->destroy_context1) {\n\t\tcontext->event_loop_ops->destroy_context1(context);\n\n\t\treturn;\n\t}\n\n\tlws_context_destroy2(context);\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/core/libwebsockets.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n\n#ifdef LWS_HAVE_SYS_TYPES_H\n#include <sys/types.h>\n#endif\n\n#ifdef LWS_WITH_IPV6\n#if defined(WIN32) || defined(_WIN32)\n#include <wincrypt.h>\n#include <iphlpapi.h>\n#else\n#include <net/if.h>\n#endif\n#endif\n\nint log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;\nstatic void (*lwsl_emit)(int level, const char *line)\n#ifndef LWS_PLAT_OPTEE\n\t= lwsl_emit_stderr\n#endif\n\t;\n#ifndef LWS_PLAT_OPTEE\nstatic const char * const log_level_names[] = {\n\t\"ERR\",\n\t\"WARN\",\n\t\"NOTICE\",\n\t\"INFO\",\n\t\"DEBUG\",\n\t\"PARSER\",\n\t\"HEADER\",\n\t\"EXTENSION\",\n\t\"CLIENT\",\n\t\"LATENCY\",\n\t\"USER\",\n\t\"?\",\n\t\"?\"\n};\n#endif\n\nint lws_open(const char *__file, int __oflag, ...)\n{\n\tva_list ap;\n\tint n;\n\n\tva_start(ap, __oflag);\n\tif (((__oflag & O_CREAT) == O_CREAT)\n#if defined(O_TMPFILE)\n\t\t|| ((__oflag & O_TMPFILE) == O_TMPFILE)\n#endif\n\t)\n\t\t/* last arg is really a mode_t.  But windows... */\n\t\tn = open(__file, __oflag, va_arg(ap, uint32_t));\n\telse\n\t\tn = open(__file, __oflag);\n\tva_end(ap);\n\n\tlws_plat_apply_FD_CLOEXEC(n);\n\n\treturn n;\n}\n\n#if defined (_DEBUG)\nvoid lwsi_set_role(struct lws *wsi, lws_wsi_state_t role)\n{\n\twsi->wsistate = (wsi->wsistate & (~LWSI_ROLE_MASK)) | role;\n\n\tlwsl_debug(\"lwsi_set_role(%p, 0x%x)\\n\", wsi, wsi->wsistate);\n}\n\nvoid lwsi_set_state(struct lws *wsi, lws_wsi_state_t lrs)\n{\n\twsi->wsistate = (wsi->wsistate & (~LRS_MASK)) | lrs;\n\n\tlwsl_debug(\"lwsi_set_state(%p, 0x%x)\\n\", wsi, wsi->wsistate);\n}\n#endif\n\nsigned char char_to_hex(const char c)\n{\n\tif (c >= '0' && c <= '9')\n\t\treturn c - '0';\n\n\tif (c >= 'a' && c <= 'f')\n\t\treturn c - 'a' + 10;\n\n\tif (c >= 'A' && c <= 'F')\n\t\treturn c - 'A' + 10;\n\n\treturn -1;\n}\n\nvoid\n__lws_free_wsi(struct lws *wsi)\n{\n\tif (!wsi)\n\t\treturn;\n\n\t/*\n\t * Protocol user data may be allocated either internally by lws\n\t * or by specified the user. We should only free what we allocated.\n\t */\n\tif (wsi->protocol && wsi->protocol->per_session_data_size &&\n\t    wsi->user_space && !wsi->user_space_externally_allocated)\n\t\tlws_free(wsi->user_space);\n\n\tlws_buflist_destroy_all_segments(&wsi->buflist);\n\tlws_free_set_NULL(wsi->trunc_alloc);\n\tlws_free_set_NULL(wsi->udp);\n\n\tif (wsi->vhost && wsi->vhost->lserv_wsi == wsi)\n\t\twsi->vhost->lserv_wsi = NULL;\n\n\t// lws_peer_dump_from_wsi(wsi);\n\n\tif (wsi->role_ops->destroy_role)\n\t\twsi->role_ops->destroy_role(wsi);\n\n#if defined(LWS_WITH_PEER_LIMITS)\n\tlws_peer_track_wsi_close(wsi->context, wsi->peer);\n\twsi->peer = NULL;\n#endif\n\n\t/* since we will destroy the wsi, make absolutely sure now */\n\n#if defined(LWS_WITH_OPENSSL)\n\t__lws_ssl_remove_wsi_from_buffered_list(wsi);\n#endif\n\t__lws_remove_from_timeout_list(wsi);\n\n\tif (wsi->context->event_loop_ops->destroy_wsi)\n\t\twsi->context->event_loop_ops->destroy_wsi(wsi);\n\n\twsi->context->count_wsi_allocated--;\n\tlwsl_debug(\"%s: %p, remaining wsi %d\\n\", __func__, wsi,\n\t\t\twsi->context->count_wsi_allocated);\n\n\tlws_free(wsi);\n}\n\nvoid\nlws_dll_add_front(struct lws_dll *d, struct lws_dll *phead)\n{\n\tif (d->prev)\n\t\treturn;\n\n\t/* our next guy is current first guy */\n\td->next = phead->next;\n\t/* if there is a next guy, set his prev ptr to our next ptr */\n\tif (d->next)\n\t\td->next->prev = d;\n\t/* our prev ptr is first ptr */\n\td->prev = phead;\n\t/* set the first guy to be us */\n\tphead->next = d;\n}\n\n/* situation is:\n *\n *  HEAD: struct lws_dll * = &entry1\n *\n *  Entry 1: struct lws_dll  .pprev = &HEAD , .next = Entry 2\n *  Entry 2: struct lws_dll  .pprev = &entry1 , .next = &entry2\n *  Entry 3: struct lws_dll  .pprev = &entry2 , .next = NULL\n *\n *  Delete Entry1:\n *\n *   - HEAD = &entry2\n *   - Entry2: .pprev = &HEAD, .next = &entry3\n *   - Entry3: .pprev = &entry2, .next = NULL\n *\n *  Delete Entry2:\n *\n *   - HEAD = &entry1\n *   - Entry1: .pprev = &HEAD, .next = &entry3\n *   - Entry3: .pprev = &entry1, .next = NULL\n *\n *  Delete Entry3:\n *\n *   - HEAD = &entry1\n *   - Entry1: .pprev = &HEAD, .next = &entry2\n *   - Entry2: .pprev = &entry1, .next = NULL\n *\n */\n\nvoid\nlws_dll_remove(struct lws_dll *d)\n{\n\tif (!d->prev) /* ie, not part of the list */\n\t\treturn;\n\n\t/*\n\t *  remove us\n\t *\n\t *  USp <-> us <-> USn  -->  USp <-> USn\n\t */\n\n\t/* if we have a next guy, set his prev to our prev */\n\tif (d->next)\n\t\td->next->prev = d->prev;\n\n\t/* set our prev guy to our next guy instead of us */\n\tif (d->prev)\n\t\td->prev->next = d->next;\n\n\t/* we're out of the list, we should not point anywhere any more */\n\td->prev = NULL;\n\td->next = NULL;\n}\n\nvoid\n__lws_remove_from_timeout_list(struct lws *wsi)\n{\n\tlws_dll_lws_remove(&wsi->dll_timeout);\n}\n\nvoid\nlws_remove_from_timeout_list(struct lws *wsi)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\n\tlws_pt_lock(pt, __func__);\n\t__lws_remove_from_timeout_list(wsi);\n\tlws_pt_unlock(pt);\n}\n\nvoid\nlws_dll_dump(struct lws_dll_lws *head, const char *title)\n{\n\tint n = 0;\n\n\t(void)n;\n\tlwsl_notice(\"%s: %s (head.next %p)\\n\", __func__, title, head->next);\n\n\tlws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1, head->next) {\n\t\tstruct lws *wsi = lws_container_of(d, struct lws, dll_hrtimer);\n\n\t\t(void)wsi;\n\n\t\tlwsl_notice(\"  %d: wsi %p: %llu\\n\", n++, wsi,\n\t\t\t\t(unsigned long long)wsi->pending_timer);\n\t} lws_end_foreach_dll_safe(d, d1);\n}\n\nvoid\n__lws_set_timer_usecs(struct lws *wsi, lws_usec_t usecs)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tstruct lws_dll_lws *dd = &pt->dll_head_hrtimer;\n\tstruct timeval now;\n\tstruct lws *wsi1;\n\tint bef = 0;\n\n\tlws_dll_lws_remove(&wsi->dll_hrtimer);\n\n\tif (usecs == LWS_SET_TIMER_USEC_CANCEL)\n\t\treturn;\n\n\tgettimeofday(&now, NULL);\n\twsi->pending_timer = ((now.tv_sec * 1000000ll) + now.tv_usec) + usecs;\n\n\t/*\n\t * we sort the hrtimer list with the earliest timeout first\n\t */\n\n\tlws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1,\n\t\t\t\t   pt->dll_head_hrtimer.next) {\n\t\tdd = d;\n\t\twsi1 = lws_container_of(d, struct lws, dll_hrtimer);\n\n\t\tif (wsi1->pending_timer >= wsi->pending_timer) {\n\t\t\t/* d, dprev's next, is >= our time */\n\t\t\tbef = 1;\n\t\t\tbreak;\n\t\t}\n\t} lws_end_foreach_dll_safe(d, d1);\n\n\tif (bef) {\n\t\t/*\n\t\t *  we go before dd\n\t\t *  DDp <-> DD <-> DDn --> DDp <-> us <-> DD <-> DDn\n\t\t */\n\t\t/* we point forward to dd */\n\t\twsi->dll_hrtimer.next = dd;\n\t\t/* we point back to what dd used to point back to */\n\t\twsi->dll_hrtimer.prev = dd->prev;\n\t\t/* DDp points forward to us now */\n\t\tdd->prev->next = &wsi->dll_hrtimer;\n\t\t/* DD points back to us now */\n\t\tdd->prev = &wsi->dll_hrtimer;\n\t} else {\n\t\t/*\n\t\t *  we go after dd\n\t\t *  DDp <-> DD <-> DDn --> DDp <-> DD <-> us <-> DDn\n\t\t */\n\t\t/* we point forward to what dd used to point forward to */\n\t\twsi->dll_hrtimer.next = dd->next;\n\t\t/* we point back to dd */\n\t\twsi->dll_hrtimer.prev = dd;\n\t\t/* DDn points back to us */\n\t\tif (dd->next)\n\t\t\tdd->next->prev = &wsi->dll_hrtimer;\n\t\t/* DD points forward to us */\n\t\tdd->next = &wsi->dll_hrtimer;\n\t}\n\n//\tlws_dll_dump(&pt->dll_head_hrtimer, \"after set_timer_usec\");\n}\n\nLWS_VISIBLE void\nlws_set_timer_usecs(struct lws *wsi, lws_usec_t usecs)\n{\n\t__lws_set_timer_usecs(wsi, usecs);\n}\n\nlws_usec_t\n__lws_hrtimer_service(struct lws_context_per_thread *pt)\n{\n\tstruct timeval now;\n\tstruct lws *wsi;\n\tlws_usec_t t;\n\n\tgettimeofday(&now, NULL);\n\tt = (now.tv_sec * 1000000ll) + now.tv_usec;\n\n\tlws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1,\n\t\t\t\t   pt->dll_head_hrtimer.next) {\n\t\twsi = lws_container_of(d, struct lws, dll_hrtimer);\n\n\t\t/*\n\t\t * if we met one in the future, we are done, because the list\n\t\t * is sorted by time in the future.\n\t\t */\n\t\tif (wsi->pending_timer > t)\n\t\t\tbreak;\n\n\t\tlws_set_timer_usecs(wsi, LWS_SET_TIMER_USEC_CANCEL);\n\n\t\t/* it's time for the timer to be serviced */\n\n\t\tif (wsi->protocol &&\n\t\t    wsi->protocol->callback(wsi, LWS_CALLBACK_TIMER,\n\t\t\t\t\t    wsi->user_space, NULL, 0))\n\t\t\t__lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS,\n\t\t\t\t\t     \"timer cb errored\");\n\t} lws_end_foreach_dll_safe(d, d1);\n\n\t/* return an estimate how many us until next timer hit */\n\n\tif (!pt->dll_head_hrtimer.next)\n\t\treturn LWS_HRTIMER_NOWAIT;\n\n\twsi = lws_container_of(pt->dll_head_hrtimer.next, struct lws, dll_hrtimer);\n\n\tgettimeofday(&now, NULL);\n\tt = (now.tv_sec * 1000000ll) + now.tv_usec;\n\n\tif (wsi->pending_timer < t)\n\t\treturn 0;\n\n\treturn wsi->pending_timer - t;\n}\n\nvoid\n__lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\ttime_t now;\n\n\ttime(&now);\n\n\tlwsl_debug(\"%s: %p: %d secs\\n\", __func__, wsi, secs);\n\twsi->pending_timeout_limit = secs;\n\twsi->pending_timeout_set = now;\n\twsi->pending_timeout = reason;\n\n\tif (!reason)\n\t\tlws_dll_lws_remove(&wsi->dll_timeout);\n\telse\n\t\tlws_dll_lws_add_front(&wsi->dll_timeout, &pt->dll_head_timeout);\n}\n\nLWS_VISIBLE void\nlws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\n\tif (secs == LWS_TO_KILL_SYNC) {\n\t\tlws_remove_from_timeout_list(wsi);\n\t\tlwsl_debug(\"synchronously killing %p\\n\", wsi);\n\t\tlws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, \"to sync kill\");\n\t\treturn;\n\t}\n\n\tif (secs == LWS_TO_KILL_ASYNC)\n\t\tsecs = 0;\n\n\tlws_pt_lock(pt, __func__);\n\t__lws_set_timeout(wsi, reason, secs);\n\tlws_pt_unlock(pt);\n}\n\nint\nlws_timed_callback_remove(struct lws_vhost *vh, struct lws_timed_vh_protocol *p)\n{\n\tlws_start_foreach_llp(struct lws_timed_vh_protocol **, pt,\n\t\t\t      vh->timed_vh_protocol_list) {\n\t\tif (*pt == p) {\n\t\t\t*pt = p->next;\n\t\t\tlws_free(p);\n\n\t\t\treturn 0;\n\t\t}\n\t} lws_end_foreach_llp(pt, next);\n\n\treturn 1;\n}\n\nLWS_VISIBLE LWS_EXTERN int\nlws_timed_callback_vh_protocol(struct lws_vhost *vh, const struct lws_protocols *prot,\n\t\t\t       int reason, int secs)\n{\n\tstruct lws_timed_vh_protocol *p = (struct lws_timed_vh_protocol *)\n\t\t\tlws_malloc(sizeof(*p), \"timed_vh\");\n\n\tif (!p)\n\t\treturn 1;\n\n\tp->protocol = prot;\n\tp->reason = reason;\n\tp->time = lws_now_secs() + secs;\n\tp->next = vh->timed_vh_protocol_list;\n\n\tvh->timed_vh_protocol_list = p;\n\n\treturn 0;\n}\n\nstatic void\nlws_remove_child_from_any_parent(struct lws *wsi)\n{\n\tstruct lws **pwsi;\n\tint seen = 0;\n\n\tif (!wsi->parent)\n\t\treturn;\n\n\t/* detach ourselves from parent's child list */\n\tpwsi = &wsi->parent->child_list;\n\twhile (*pwsi) {\n\t\tif (*pwsi == wsi) {\n\t\t\tlwsl_info(\"%s: detach %p from parent %p\\n\", __func__,\n\t\t\t\t  wsi, wsi->parent);\n\n\t\t\tif (wsi->parent->protocol)\n\t\t\t\twsi->parent->protocol->callback(wsi,\n\t\t\t\t\t\tLWS_CALLBACK_CHILD_CLOSING,\n\t\t\t\t\t       wsi->parent->user_space, wsi, 0);\n\n\t\t\t*pwsi = wsi->sibling_list;\n\t\t\tseen = 1;\n\t\t\tbreak;\n\t\t}\n\t\tpwsi = &(*pwsi)->sibling_list;\n\t}\n\tif (!seen)\n\t\tlwsl_err(\"%s: failed to detach from parent\\n\", __func__);\n\n\twsi->parent = NULL;\n}\n\nint\nlws_bind_protocol(struct lws *wsi, const struct lws_protocols *p)\n{\n//\tif (wsi->protocol == p)\n//\t\treturn 0;\n\tconst struct lws_protocols *vp = wsi->vhost->protocols, *vpo;\n\n\tif (wsi->protocol && wsi->protocol_bind_balance) {\n\t\twsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_DROP_PROTOCOL,\n\t\t\t\t\twsi->user_space, NULL, 0);\n\t\twsi->protocol_bind_balance = 0;\n\t}\n\tif (!wsi->user_space_externally_allocated)\n\t\tlws_free_set_NULL(wsi->user_space);\n\n\tlws_same_vh_protocol_remove(wsi);\n\n\twsi->protocol = p;\n\tif (!p)\n\t\treturn 0;\n\n\tif (lws_ensure_user_space(wsi))\n\t\treturn 1;\n\n\tif (p > vp && p < &vp[wsi->vhost->count_protocols])\n\t\tlws_same_vh_protocol_insert(wsi, (int)(p - vp));\n\telse {\n\t\tint n = wsi->vhost->count_protocols;\n\t\tint hit = 0;\n\n\t\tvpo = vp;\n\n\t\twhile (n--) {\n\t\t\tif (p->name && vp->name && !strcmp(p->name, vp->name)) {\n\t\t\t\thit = 1;\n\t\t\t\tlws_same_vh_protocol_insert(wsi, (int)(vp - vpo));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tvp++;\n\t\t}\n\t\tif (!hit)\n\t\t\tlwsl_err(\"%s: %p is not in vhost '%s' protocols list\\n\",\n\t\t\t\t __func__, p, wsi->vhost->name);\n\t}\n\n\tif (wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_BIND_PROTOCOL,\n\t\t\t\t    wsi->user_space, NULL, 0))\n\t\treturn 1;\n\n\twsi->protocol_bind_balance = 1;\n\n\treturn 0;\n}\n\nvoid\n__lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason, const char *caller)\n{\n\tstruct lws_context_per_thread *pt;\n\tstruct lws *wsi1, *wsi2;\n\tstruct lws_context *context;\n\tint n;\n\n\tlwsl_info(\"%s: %p: caller: %s\\n\", __func__, wsi, caller);\n\n\tif (!wsi)\n\t\treturn;\n\n\tlws_access_log(wsi);\n\n\tcontext = wsi->context;\n\tpt = &context->pt[(int)wsi->tsi];\n\tlws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_API_CLOSE, 1);\n\n#if !defined(LWS_NO_CLIENT)\n\n\tlws_free_set_NULL(wsi->client_hostname_copy);\n\t/* we are no longer an active client connection that can piggyback */\n\tlws_dll_lws_remove(&wsi->dll_active_client_conns);\n\n\t/*\n\t * if we have wsi in our transaction queue, if we are closing we\n\t * must go through and close all those first\n\t */\n\tif (wsi->vhost) {\n\t\tif ((int)reason != -1)\n\t\t\tlws_vhost_lock(wsi->vhost);\n\t\tlws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1,\n\t\t\t\t\twsi->dll_client_transaction_queue_head.next) {\n\t\t\tstruct lws *w = lws_container_of(d, struct lws,\n\t\t\t\t\t\t\t dll_client_transaction_queue);\n\n\t\t\t__lws_close_free_wsi(w, -1, \"trans q leader closing\");\n\t\t} lws_end_foreach_dll_safe(d, d1);\n\n\t\t/*\n\t\t * !!! If we are closing, but we have pending pipelined transaction\n\t\t * results we already sent headers for, that's going to destroy sync\n\t\t * for HTTP/1 and leave H2 stream with no live swsi.\n\t\t *\n\t\t * However this is normal if we are being closed because the transaction\n\t\t * queue leader is closing.\n\t\t */\n\t\tlws_dll_lws_remove(&wsi->dll_client_transaction_queue);\n\t\tif ((int)reason !=-1)\n\t\t\tlws_vhost_unlock(wsi->vhost);\n\t}\n#endif\n\n\t/* if we have children, close them first */\n\tif (wsi->child_list) {\n\t\twsi2 = wsi->child_list;\n\t\twhile (wsi2) {\n\t\t\twsi1 = wsi2->sibling_list;\n\t\t\twsi2->parent = NULL;\n\t\t\t/* stop it doing shutdown processing */\n\t\t\twsi2->socket_is_permanently_unusable = 1;\n\t\t\t__lws_close_free_wsi(wsi2, reason, \"general child recurse\");\n\t\t\twsi2 = wsi1;\n\t\t}\n\t\twsi->child_list = NULL;\n\t}\n\n\tif (wsi->role_ops == &role_ops_raw_file) {\n\t\tlws_remove_child_from_any_parent(wsi);\n\t\t__remove_wsi_socket_from_fds(wsi);\n\t\twsi->protocol->callback(wsi, wsi->role_ops->close_cb[0],\n\t\t\t\t\twsi->user_space, NULL, 0);\n\t\tgoto async_close;\n\t}\n\n\twsi->wsistate_pre_close = wsi->wsistate;\n\n#ifdef LWS_WITH_CGI\n\tif (wsi->role_ops == &role_ops_cgi) {\n\t\t/* we are not a network connection, but a handler for CGI io */\n\t\tif (wsi->parent && wsi->parent->http.cgi) {\n\n\t\t\tif (wsi->cgi_channel == LWS_STDOUT)\n\t\t\t\tlws_cgi_remove_and_kill(wsi->parent);\n\n\t\t\t/* end the binding between us and master */\n\t\t\twsi->parent->http.cgi->stdwsi[(int)wsi->cgi_channel] = NULL;\n\t\t}\n\t\twsi->socket_is_permanently_unusable = 1;\n\n\t\tgoto just_kill_connection;\n\t}\n\n\tif (wsi->http.cgi)\n\t\tlws_cgi_remove_and_kill(wsi);\n#endif\n\n#if !defined(LWS_NO_CLIENT)\n\tlws_client_stash_destroy(wsi);\n#endif\n\n\tif (wsi->role_ops == &role_ops_raw_skt) {\n\t\twsi->socket_is_permanently_unusable = 1;\n\t\tgoto just_kill_connection;\n\t}\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tif (lwsi_role_http(wsi) && lwsi_role_server(wsi) &&\n\t    wsi->http.fop_fd != NULL)\n\t\tlws_vfs_file_close(&wsi->http.fop_fd);\n#endif\n\n\tif (lwsi_state(wsi) == LRS_DEAD_SOCKET)\n\t\treturn;\n\n\tif (wsi->socket_is_permanently_unusable ||\n\t    reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY ||\n\t    lwsi_state(wsi) == LRS_SHUTDOWN)\n\t\tgoto just_kill_connection;\n\n\tswitch (lwsi_state_PRE_CLOSE(wsi)) {\n\tcase LRS_DEAD_SOCKET:\n\t\treturn;\n\n\t/* we tried the polite way... */\n\tcase LRS_WAITING_TO_SEND_CLOSE:\n\tcase LRS_AWAITING_CLOSE_ACK:\n\tcase LRS_RETURNED_CLOSE:\n\t\tgoto just_kill_connection;\n\n\tcase LRS_FLUSHING_BEFORE_CLOSE:\n\t\tif (wsi->trunc_len) {\n\t\t\tlws_callback_on_writable(wsi);\n\t\t\treturn;\n\t\t}\n\t\tlwsl_info(\"%p: end LRS_FLUSHING_BEFORE_CLOSE\\n\", wsi);\n\t\tgoto just_kill_connection;\n\tdefault:\n\t\tif (wsi->trunc_len) {\n\t\t\tlwsl_info(\"%p: LRS_FLUSHING_BEFORE_CLOSE\\n\", wsi);\n\t\t\tlwsi_set_state(wsi, LRS_FLUSHING_BEFORE_CLOSE);\n\t\t\t__lws_set_timeout(wsi,\n\t\t\t\tPENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5);\n\t\t\treturn;\n\t\t}\n\t\tbreak;\n\t}\n\n\tif (lwsi_state(wsi) == LRS_WAITING_CONNECT ||\n\t    lwsi_state(wsi) == LRS_H1C_ISSUE_HANDSHAKE)\n\t\tgoto just_kill_connection;\n\n\tif (!wsi->told_user_closed && lwsi_role_http(wsi) &&\n\t    lwsi_role_server(wsi)) {\n\t\tif (wsi->user_space && wsi->protocol &&\n\t\t    wsi->protocol_bind_balance) {\n\t\t\twsi->protocol->callback(wsi,\n\t\t\t\t\t\tLWS_CALLBACK_HTTP_DROP_PROTOCOL,\n\t\t\t\t\t       wsi->user_space, NULL, 0);\n\t\t\twsi->protocol_bind_balance = 0;\n\t\t}\n\t}\n\n\t/*\n\t * signal we are closing, lws_write will\n\t * add any necessary version-specific stuff.  If the write fails,\n\t * no worries we are closing anyway.  If we didn't initiate this\n\t * close, then our state has been changed to\n\t * LRS_RETURNED_CLOSE and we will skip this.\n\t *\n\t * Likewise if it's a second call to close this connection after we\n\t * sent the close indication to the peer already, we are in state\n\t * LRS_AWAITING_CLOSE_ACK and will skip doing this a second time.\n\t */\n\n\tif (wsi->role_ops->close_via_role_protocol &&\n\t    wsi->role_ops->close_via_role_protocol(wsi, reason))\n\t\treturn;\n\njust_kill_connection:\n\n\tif (wsi->role_ops->close_kill_connection)\n\t\twsi->role_ops->close_kill_connection(wsi, reason);\n\n\tlws_remove_child_from_any_parent(wsi);\n\tn = 0;\n\n\tif (!wsi->told_user_closed && wsi->user_space &&\n\t    wsi->protocol_bind_balance) {\n\t\tlwsl_debug(\"%s: %p: DROP_PROTOCOL %s\\n\", __func__, wsi,\n\t\t       wsi->protocol->name);\n\t\twsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_DROP_PROTOCOL,\n\t\t\t\t        wsi->user_space, NULL, 0);\n\t\twsi->protocol_bind_balance = 0;\n\t}\n\n\tif ((lwsi_state(wsi) == LRS_WAITING_SERVER_REPLY ||\n\t     lwsi_state(wsi) == LRS_WAITING_CONNECT) && !wsi->already_did_cce)\n\t\twsi->protocol->callback(wsi,\n\t\t\t\t        LWS_CALLBACK_CLIENT_CONNECTION_ERROR,\n\t\t\t\t\t\twsi->user_space, NULL, 0);\n\n\t/*\n\t * Testing with ab shows that we have to stage the socket close when\n\t * the system is under stress... shutdown any further TX, change the\n\t * state to one that won't emit anything more, and wait with a timeout\n\t * for the POLLIN to show a zero-size rx before coming back and doing\n\t * the actual close.\n\t */\n\tif (wsi->role_ops != &role_ops_raw_skt && !lwsi_role_client(wsi) &&\n\t    lwsi_state(wsi) != LRS_SHUTDOWN &&\n\t    lwsi_state(wsi) != LRS_UNCONNECTED &&\n\t    reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY &&\n\t    !wsi->socket_is_permanently_unusable) {\n\n#if defined(LWS_WITH_TLS)\n\tif (lws_is_ssl(wsi) && wsi->tls.ssl) {\n\t\tn = 0;\n\t\tswitch (__lws_tls_shutdown(wsi)) {\n\t\tcase LWS_SSL_CAPABLE_DONE:\n\t\tcase LWS_SSL_CAPABLE_ERROR:\n\t\tcase LWS_SSL_CAPABLE_MORE_SERVICE_READ:\n\t\tcase LWS_SSL_CAPABLE_MORE_SERVICE_WRITE:\n\t\tcase LWS_SSL_CAPABLE_MORE_SERVICE:\n\t\t\tbreak;\n\t\t}\n\t} else\n#endif\n\t\t{\n\t\t\tlwsl_info(\"%s: shutdown conn: %p (sock %d, state 0x%x)\\n\",\n\t\t\t\t  __func__, wsi, (int)(long)wsi->desc.sockfd,\n\t\t\t\t  lwsi_state(wsi));\n\t\t\tif (!wsi->socket_is_permanently_unusable &&\n\t\t\t    lws_socket_is_valid(wsi->desc.sockfd)) {\n\t\t\t\twsi->socket_is_permanently_unusable = 1;\n\t\t\t\tn = shutdown(wsi->desc.sockfd, SHUT_WR);\n\t\t\t}\n\t\t}\n\t\tif (n)\n\t\t\tlwsl_debug(\"closing: shutdown (state 0x%x) ret %d\\n\",\n\t\t\t\t   lwsi_state(wsi), LWS_ERRNO);\n\n\t\t/*\n\t\t * This causes problems on WINCE / ESP32 with disconnection\n\t\t * when the events are half closing connection\n\t\t */\n#if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP32)\n\t\t/* libuv: no event available to guarantee completion */\n\t\tif (!wsi->socket_is_permanently_unusable &&\n\t\t    lws_socket_is_valid(wsi->desc.sockfd) &&\n\t\t    lwsi_state(wsi) != LRS_SHUTDOWN &&\n\t\t    context->event_loop_ops->periodic_events_available) {\n\t\t\t__lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN);\n\t\t\tlwsi_set_state(wsi, LRS_SHUTDOWN);\n\t\t\t__lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH,\n\t\t\t\t\t  context->timeout_secs);\n\n\t\t\treturn;\n\t\t}\n#endif\n\t}\n\n\tlwsl_debug(\"%s: real just_kill_connection: %p (sockfd %d)\\n\", __func__,\n\t\t   wsi, wsi->desc.sockfd);\n\t\n#ifdef LWS_WITH_HTTP_PROXY\n\tif (wsi->http.rw) {\n\t\tlws_rewrite_destroy(wsi->http.rw);\n\t\twsi->http.rw = NULL;\n\t}\n#endif\n\t/*\n\t * we won't be servicing or receiving anything further from this guy\n\t * delete socket from the internal poll list if still present\n\t */\n\t__lws_ssl_remove_wsi_from_buffered_list(wsi);\n\t__lws_remove_from_timeout_list(wsi);\n\tlws_dll_lws_remove(&wsi->dll_hrtimer);\n\n\t/* don't repeat event loop stuff */\n\tif (wsi->told_event_loop_closed)\n\t\treturn;\n\n\t/* checking return redundant since we anyway close */\n\tif (wsi->desc.sockfd != LWS_SOCK_INVALID)\n\t\t__remove_wsi_socket_from_fds(wsi);\n\telse\n\t\tlws_same_vh_protocol_remove(wsi);\n\n\tlwsi_set_state(wsi, LRS_DEAD_SOCKET);\n\tlws_buflist_destroy_all_segments(&wsi->buflist);\n\tlws_dll_lws_remove(&wsi->dll_buflist);\n\n\tif (wsi->role_ops->close_role)\n\t    wsi->role_ops->close_role(pt, wsi);\n\n\t/* tell the user it's all over for this guy */\n\n\tif (lwsi_state_est_PRE_CLOSE(wsi) && !wsi->told_user_closed &&\n\t    wsi->role_ops->close_cb[lwsi_role_server(wsi)]) {\n\t\tconst struct lws_protocols *pro = wsi->protocol;\n\n\t\tif (!wsi->protocol)\n\t\t\tpro = &wsi->vhost->protocols[0];\n\n\t\tif (!wsi->upgraded_to_http2 || !lwsi_role_client(wsi))\n\t\t\t/*\n\t\t\t * The network wsi for a client h2 connection shouldn't\n\t\t\t * call back for its role: the child stream connections\n\t\t\t * own the role.  Otherwise h2 will call back closed\n\t\t\t * one too many times as the children do it and then\n\t\t\t * the closing network stream.\n\t\t\t */\n\t\t\tpro->callback(wsi,\n\t\t\t      wsi->role_ops->close_cb[lwsi_role_server(wsi)],\n\t\t\t      wsi->user_space, NULL, 0);\n\t\twsi->told_user_closed = 1;\n\t}\n\nasync_close:\n\twsi->socket_is_permanently_unusable = 1;\n\n\tif (wsi->context->event_loop_ops->wsi_logical_close)\n\t\tif (wsi->context->event_loop_ops->wsi_logical_close(wsi))\n\t\t\treturn;\n\n\t__lws_close_free_wsi_final(wsi);\n}\n\nvoid\n__lws_close_free_wsi_final(struct lws *wsi)\n{\n\tint n;\n\n\tif (lws_socket_is_valid(wsi->desc.sockfd) && !lws_ssl_close(wsi)) {\n\t\tn = compatible_close(wsi->desc.sockfd);\n\t\tif (n)\n\t\t\tlwsl_debug(\"closing: close ret %d\\n\", LWS_ERRNO);\n\n\t\twsi->desc.sockfd = LWS_SOCK_INVALID;\n\t}\n\n\t/* outermost destroy notification for wsi (user_space still intact) */\n\tif (wsi->vhost)\n\t\twsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY,\n\t\t\t\t\t\t  wsi->user_space, NULL, 0);\n\n#ifdef LWS_WITH_CGI\n\tif (wsi->http.cgi) {\n\n\t\tfor (n = 0; n < 3; n++) {\n\t\t\tif (wsi->http.cgi->pipe_fds[n][!!(n == 0)] == 0)\n\t\t\t\tlwsl_err(\"ZERO FD IN CGI CLOSE\");\n\n\t\t\tif (wsi->http.cgi->pipe_fds[n][!!(n == 0)] >= 0)\n\t\t\t\tclose(wsi->http.cgi->pipe_fds[n][!!(n == 0)]);\n\t\t}\n\n\t\tlws_free(wsi->http.cgi);\n\t}\n#endif\n\n\t__lws_free_wsi(wsi);\n}\n\n\nvoid\nlws_close_free_wsi(struct lws *wsi, enum lws_close_status reason, const char *caller)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\n\tlws_pt_lock(pt, __func__);\n\t__lws_close_free_wsi(wsi, reason, caller);\n\tlws_pt_unlock(pt);\n}\n\n/* lws_buflist */\n\nint\nlws_buflist_append_segment(struct lws_buflist **head, const uint8_t *buf,\n\t\t\t   size_t len)\n{\n\tstruct lws_buflist *nbuf;\n\tint first = !*head;\n\tvoid *p = *head;\n\tint sanity = 1024;\n\n\tassert(buf);\n\tassert(len);\n\n\t/* append at the tail */\n\twhile (*head) {\n\t\tif (!--sanity || head == &((*head)->next)) {\n\t\t\tlwsl_err(\"%s: corrupt list points to self\\n\", __func__);\n\t\t\treturn -1;\n\t\t}\n\t\thead = &((*head)->next);\n\t}\n\n\tlwsl_info(\"%s: len %u first %d %p\\n\", __func__, (uint32_t)len, first, p);\n\n\tnbuf = (struct lws_buflist *)\n\t\t\tlws_malloc(sizeof(**head) + len, __func__);\n\tif (!nbuf) {\n\t\tlwsl_err(\"%s: OOM\\n\", __func__);\n\t\treturn -1;\n\t}\n\n\tnbuf->len = len;\n\tnbuf->pos = 0;\n\tnbuf->next = NULL;\n\n\tp = (void *)nbuf->buf;\n\tmemcpy(p, buf, len);\n\n\t*head = nbuf;\n\n\treturn first; /* returns 1 if first segment just created */\n}\n\nstatic int\nlws_buflist_destroy_segment(struct lws_buflist **head)\n{\n\tstruct lws_buflist *old = *head;\n\n\tassert(*head);\n\t*head = (*head)->next;\n\told->next = NULL;\n\tlws_free(old);\n\n\treturn !*head; /* returns 1 if last segment just destroyed */\n}\n\nvoid\nlws_buflist_destroy_all_segments(struct lws_buflist **head)\n{\n\tstruct lws_buflist *p = *head, *p1;\n\n\twhile (p) {\n\t\tp1 = p->next;\n\t\tp->next = NULL;\n\t\tlws_free(p);\n\t\tp = p1;\n\t}\n\n\t*head = NULL;\n}\n\nsize_t\nlws_buflist_next_segment_len(struct lws_buflist **head, uint8_t **buf)\n{\n\tif (!*head) {\n\t\tif (buf)\n\t\t\t*buf = NULL;\n\n\t\treturn 0;\n\t}\n\n\tif (!(*head)->len && (*head)->next)\n\t\tlws_buflist_destroy_segment(head);\n\n\tif (!*head) {\n\t\tif (buf)\n\t\t\t*buf = NULL;\n\n\t\treturn 0;\n\t}\n\n\tassert((*head)->pos < (*head)->len);\n\n\tif (buf)\n\t\t*buf = (*head)->buf + (*head)->pos;\n\n\treturn (*head)->len - (*head)->pos;\n}\n\nint\nlws_buflist_use_segment(struct lws_buflist **head, size_t len)\n{\n\tassert(*head);\n\tassert(len);\n\tassert((*head)->pos + len <= (*head)->len);\n\n\t(*head)->pos += len;\n\tif ((*head)->pos == (*head)->len)\n\t\tlws_buflist_destroy_segment(head);\n\n\tif (!*head)\n\t\treturn 0;\n\n\treturn (int)((*head)->len - (*head)->pos);\n}\n\nvoid\nlws_buflist_describe(struct lws_buflist **head, void *id)\n{\n\tstruct lws_buflist *old;\n\tint n = 0;\n\n\tif (*head == NULL)\n\t\tlwsl_notice(\"%p: buflist empty\\n\", id);\n\n\twhile (*head) {\n\t\tlwsl_notice(\"%p: %d: %llu / %llu (%llu left)\\n\", id, n,\n\t\t\t    (unsigned long long)(*head)->pos,\n\t\t\t    (unsigned long long)(*head)->len,\n\t\t\t    (unsigned long long)(*head)->len - (*head)->pos);\n\t\told = *head;\n\t\thead = &((*head)->next);\n\t\tif (*head == old) {\n\t\t\tlwsl_err(\"%s: next points to self\\n\", __func__);\n\t\t\tbreak;\n\t\t}\n\t\tn++;\n\t}\n}\n\n/* ... */\n\nLWS_VISIBLE LWS_EXTERN const char *\nlws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len)\n{\n\tint n = 0, sl = (int)strlen(name);\n\n\twhile (lws_hdr_copy_fragment(wsi, buf, len,\n\t\t\t  WSI_TOKEN_HTTP_URI_ARGS, n) >= 0) {\n\n\t\tif (!strncmp(buf, name, sl))\n\t\t\treturn buf + sl;\n\n\t\tn++;\n\t}\n\n\treturn NULL;\n}\n\n#if !defined(LWS_WITH_ESP32)\nLWS_VISIBLE int\ninterface_to_sa(struct lws_vhost *vh, const char *ifname,\n\t\tstruct sockaddr_in *addr, size_t addrlen)\n{\n\tint ipv6 = 0;\n#ifdef LWS_WITH_IPV6\n\tipv6 = LWS_IPV6_ENABLED(vh);\n#endif\n\t(void)vh;\n\n\treturn lws_interface_to_sa(ipv6, ifname, addr, addrlen);\n}\n#endif\n\n#ifndef LWS_PLAT_OPTEE\nstatic int\nlws_get_addresses(struct lws_vhost *vh, void *ads, char *name,\n\t\t  int name_len, char *rip, int rip_len)\n{\n\tstruct addrinfo ai, *res;\n\tstruct sockaddr_in addr4;\n\n\trip[0] = '\\0';\n\tname[0] = '\\0';\n\taddr4.sin_family = AF_UNSPEC;\n\n#ifdef LWS_WITH_IPV6\n\tif (LWS_IPV6_ENABLED(vh)) {\n\t\tif (!lws_plat_inet_ntop(AF_INET6,\n\t\t\t\t\t&((struct sockaddr_in6 *)ads)->sin6_addr,\n\t\t\t\t\trip, rip_len)) {\n\t\t\tlwsl_err(\"inet_ntop: %s\", strerror(LWS_ERRNO));\n\t\t\treturn -1;\n\t\t}\n\n\t\t// Strip off the IPv4 to IPv6 header if one exists\n\t\tif (strncmp(rip, \"::ffff:\", 7) == 0)\n\t\t\tmemmove(rip, rip + 7, strlen(rip) - 6);\n\n\t\tgetnameinfo((struct sockaddr *)ads, sizeof(struct sockaddr_in6),\n\t\t\t    name, name_len, NULL, 0, 0);\n\n\t\treturn 0;\n\t} else\n#endif\n\t{\n\t\tstruct addrinfo *result;\n\n\t\tmemset(&ai, 0, sizeof ai);\n\t\tai.ai_family = PF_UNSPEC;\n\t\tai.ai_socktype = SOCK_STREAM;\n#if !defined(LWS_WITH_ESP32)\n\t\tif (getnameinfo((struct sockaddr *)ads,\n\t\t\t\tsizeof(struct sockaddr_in),\n\t\t\t\tname, name_len, NULL, 0, 0))\n\t\t\treturn -1;\n#endif\n\n\t\tif (getaddrinfo(name, NULL, &ai, &result))\n\t\t\treturn -1;\n\n\t\tres = result;\n\t\twhile (addr4.sin_family == AF_UNSPEC && res) {\n\t\t\tswitch (res->ai_family) {\n\t\t\tcase AF_INET:\n\t\t\t\taddr4.sin_addr =\n\t\t\t\t ((struct sockaddr_in *)res->ai_addr)->sin_addr;\n\t\t\t\taddr4.sin_family = AF_INET;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tres = res->ai_next;\n\t\t}\n\t\tfreeaddrinfo(result);\n\t}\n\n\tif (addr4.sin_family == AF_UNSPEC)\n\t\treturn -1;\n\n\tif (lws_plat_inet_ntop(AF_INET, &addr4.sin_addr, rip, rip_len) == NULL)\n\t\treturn -1;\n\n\treturn 0;\n}\n\n\nLWS_VISIBLE const char *\nlws_get_peer_simple(struct lws *wsi, char *name, int namelen)\n{\n\tsocklen_t len, olen;\n#ifdef LWS_WITH_IPV6\n\tstruct sockaddr_in6 sin6;\n#endif\n\tstruct sockaddr_in sin4;\n\tint af = AF_INET;\n\tvoid *p, *q;\n\n\twsi = lws_get_network_wsi(wsi);\n\n\tif (wsi->parent_carries_io)\n\t\twsi = wsi->parent;\n\n#ifdef LWS_WITH_IPV6\n\tif (LWS_IPV6_ENABLED(wsi->vhost)) {\n\t\tlen = sizeof(sin6);\n\t\tp = &sin6;\n\t\taf = AF_INET6;\n\t\tq = &sin6.sin6_addr;\n\t} else\n#endif\n\t{\n\t\tlen = sizeof(sin4);\n\t\tp = &sin4;\n\t\tq = &sin4.sin_addr;\n\t}\n\n\tolen = len;\n\tif (getpeername(wsi->desc.sockfd, p, &len) < 0 || len > olen) {\n\t\tlwsl_warn(\"getpeername: %s\\n\", strerror(LWS_ERRNO));\n\t\treturn NULL;\n\t}\n\n\treturn lws_plat_inet_ntop(af, q, name, namelen);\n}\n#endif\n\nLWS_VISIBLE void\nlws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,\n\t\t       int name_len, char *rip, int rip_len)\n{\n#ifndef LWS_PLAT_OPTEE\n\tsocklen_t len;\n#ifdef LWS_WITH_IPV6\n\tstruct sockaddr_in6 sin6;\n#endif\n\tstruct sockaddr_in sin4;\n\tstruct lws_context *context = wsi->context;\n\tint ret = -1;\n\tvoid *p;\n\n\trip[0] = '\\0';\n\tname[0] = '\\0';\n\n\tlws_latency_pre(context, wsi);\n\n#ifdef LWS_WITH_IPV6\n\tif (LWS_IPV6_ENABLED(wsi->vhost)) {\n\t\tlen = sizeof(sin6);\n\t\tp = &sin6;\n\t} else\n#endif\n\t{\n\t\tlen = sizeof(sin4);\n\t\tp = &sin4;\n\t}\n\n\tif (getpeername(fd, p, &len) < 0) {\n\t\tlwsl_warn(\"getpeername: %s\\n\", strerror(LWS_ERRNO));\n\t\tgoto bail;\n\t}\n\n\tret = lws_get_addresses(wsi->vhost, p, name, name_len, rip, rip_len);\n\nbail:\n\tlws_latency(context, wsi, \"lws_get_peer_addresses\", ret, 1);\n#endif\n\t(void)wsi;\n\t(void)fd;\n\t(void)name;\n\t(void)name_len;\n\t(void)rip;\n\t(void)rip_len;\n\n}\n\nLWS_EXTERN void *\nlws_vhost_user(struct lws_vhost *vhost)\n{\n\treturn vhost->user;\n}\n\nLWS_EXTERN void *\nlws_context_user(struct lws_context *context)\n{\n\treturn context->user_space;\n}\n\nLWS_VISIBLE struct lws_vhost *\nlws_vhost_get(struct lws *wsi)\n{\n\treturn wsi->vhost;\n}\n\nLWS_VISIBLE struct lws_vhost *\nlws_get_vhost(struct lws *wsi)\n{\n\treturn wsi->vhost;\n}\n\nLWS_VISIBLE const struct lws_protocols *\nlws_protocol_get(struct lws *wsi)\n{\n\treturn wsi->protocol;\n}\n\nLWS_VISIBLE const struct lws_udp *\nlws_get_udp(const struct lws *wsi)\n{\n\treturn wsi->udp;\n}\n\nLWS_VISIBLE struct lws *\nlws_get_network_wsi(struct lws *wsi)\n{\n\tif (!wsi)\n\t\treturn NULL;\n\n#if defined(LWS_WITH_HTTP2)\n\tif (!wsi->http2_substream && !wsi->client_h2_substream)\n\t\treturn wsi;\n\n\twhile (wsi->h2.parent_wsi)\n\t\twsi = wsi->h2.parent_wsi;\n#endif\n\n\treturn wsi;\n}\n\nLWS_VISIBLE LWS_EXTERN const struct lws_protocols *\nlws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name)\n{\n\tint n;\n\n\tfor (n = 0; n < vh->count_protocols; n++)\n\t\tif (!strcmp(name, vh->protocols[n].name))\n\t\t\treturn &vh->protocols[n];\n\n\treturn NULL;\n}\n\nLWS_VISIBLE int\nlws_callback_all_protocol(struct lws_context *context,\n\t\t\t  const struct lws_protocols *protocol, int reason)\n{\n\tstruct lws_context_per_thread *pt = &context->pt[0];\n\tunsigned int n, m = context->count_threads;\n\tstruct lws *wsi;\n\n\twhile (m--) {\n\t\tfor (n = 0; n < pt->fds_count; n++) {\n\t\t\twsi = wsi_from_fd(context, pt->fds[n].fd);\n\t\t\tif (!wsi)\n\t\t\t\tcontinue;\n\t\t\tif (wsi->protocol == protocol)\n\t\t\t\tprotocol->callback(wsi, reason, wsi->user_space,\n\t\t\t\t\t\t   NULL, 0);\n\t\t}\n\t\tpt++;\n\t}\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\nlws_callback_all_protocol_vhost_args(struct lws_vhost *vh,\n\t\t\t  const struct lws_protocols *protocol, int reason,\n\t\t\t  void *argp, size_t len)\n{\n\tstruct lws_context *context = vh->context;\n\tstruct lws_context_per_thread *pt = &context->pt[0];\n\tunsigned int n, m = context->count_threads;\n\tstruct lws *wsi;\n\n\twhile (m--) {\n\t\tfor (n = 0; n < pt->fds_count; n++) {\n\t\t\twsi = wsi_from_fd(context, pt->fds[n].fd);\n\t\t\tif (!wsi)\n\t\t\t\tcontinue;\n\t\t\tif (wsi->vhost == vh && (wsi->protocol == protocol ||\n\t\t\t\t\t\t !protocol))\n\t\t\t\twsi->protocol->callback(wsi, reason,\n\t\t\t\t\t\twsi->user_space, argp, len);\n\t\t}\n\t\tpt++;\n\t}\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\nlws_callback_all_protocol_vhost(struct lws_vhost *vh,\n\t\t\t  const struct lws_protocols *protocol, int reason)\n{\n\treturn lws_callback_all_protocol_vhost_args(vh, protocol, reason, NULL, 0);\n}\n\nLWS_VISIBLE LWS_EXTERN int\nlws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len)\n{\n\tint n;\n\n\tfor (n = 0; n < wsi->vhost->count_protocols; n++)\n\t\tif (wsi->vhost->protocols[n].callback(wsi, reason, NULL, in, len))\n\t\t\treturn 1;\n\n\treturn 0;\n}\n\nLWS_VISIBLE LWS_EXTERN int\nlws_callback_vhost_protocols_vhost(struct lws_vhost *vh, int reason, void *in,\n\t\t\t\t   size_t len)\n{\n\tint n;\n\tstruct lws *wsi = lws_zalloc(sizeof(*wsi), \"fake wsi\");\n\n\twsi->context = vh->context;\n\twsi->vhost = vh;\n\n\tfor (n = 0; n < wsi->vhost->count_protocols; n++) {\n\t\twsi->protocol = &vh->protocols[n];\n\t\tif (wsi->protocol->callback(wsi, reason, NULL, in, len)) {\n\t\t\tlws_free(wsi);\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tlws_free(wsi);\n\n\treturn 0;\n}\n\nLWS_VISIBLE LWS_EXTERN void\nlws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops)\n{\n\tcontext->fops = fops;\n}\n\nLWS_VISIBLE LWS_EXTERN lws_filepos_t\nlws_vfs_tell(lws_fop_fd_t fop_fd)\n{\n\treturn fop_fd->pos;\n}\n\nLWS_VISIBLE LWS_EXTERN lws_filepos_t\nlws_vfs_get_length(lws_fop_fd_t fop_fd)\n{\n\treturn fop_fd->len;\n}\n\nLWS_VISIBLE LWS_EXTERN uint32_t\nlws_vfs_get_mod_time(lws_fop_fd_t fop_fd)\n{\n\treturn fop_fd->mod_time;\n}\n\nLWS_VISIBLE lws_fileofs_t\nlws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset)\n{\n\tlws_fileofs_t ofs;\n\n\tofs = fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, offset - fop_fd->pos);\n\n\treturn ofs;\n}\n\n\nLWS_VISIBLE lws_fileofs_t\nlws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset)\n{\n\treturn fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, fop_fd->len +\n\t\t\t\t\t      fop_fd->pos + offset);\n}\n\n\nconst struct lws_plat_file_ops *\nlws_vfs_select_fops(const struct lws_plat_file_ops *fops, const char *vfs_path,\n\t\t    const char **vpath)\n{\n\tconst struct lws_plat_file_ops *pf;\n\tconst char *p = vfs_path;\n\tint n;\n\n\t*vpath = NULL;\n\n\t/* no non-platform fops, just use that */\n\n\tif (!fops->next)\n\t\treturn fops;\n\n\t/*\n\t *  scan the vfs path looking for indications we are to be\n\t * handled by a specific fops\n\t */\n\n\twhile (p && *p) {\n\t\tif (*p != '/') {\n\t\t\tp++;\n\t\t\tcontinue;\n\t\t}\n\t\t/* the first one is always platform fops, so skip */\n\t\tpf = fops->next;\n\t\twhile (pf) {\n\t\t\tn = 0;\n\t\t\twhile (n < (int)LWS_ARRAY_SIZE(pf->fi) && pf->fi[n].sig) {\n\t\t\t\tif (p >= vfs_path + pf->fi[n].len)\n\t\t\t\t\tif (!strncmp(p - (pf->fi[n].len - 1),\n\t\t\t\t\t\t    pf->fi[n].sig,\n\t\t\t\t\t\t    pf->fi[n].len - 1)) {\n\t\t\t\t\t\t*vpath = p + 1;\n\t\t\t\t\t\treturn pf;\n\t\t\t\t\t}\n\n\t\t\t\tn++;\n\t\t\t}\n\t\t\tpf = pf->next;\n\t\t}\n\t\tp++;\n\t}\n\n\treturn fops;\n}\n\nLWS_VISIBLE LWS_EXTERN lws_fop_fd_t LWS_WARN_UNUSED_RESULT\nlws_vfs_file_open(const struct lws_plat_file_ops *fops, const char *vfs_path,\n\t\t  lws_fop_flags_t *flags)\n{\n\tconst char *vpath = \"\";\n\tconst struct lws_plat_file_ops *selected;\n\n\tselected = lws_vfs_select_fops(fops, vfs_path, &vpath);\n\n\treturn selected->LWS_FOP_OPEN(fops, vfs_path, vpath, flags);\n}\n\n\n/**\n * lws_now_secs() - seconds since 1970-1-1\n *\n */\nLWS_VISIBLE LWS_EXTERN unsigned long\nlws_now_secs(void)\n{\n\tstruct timeval tv;\n\n\tgettimeofday(&tv, NULL);\n\n\treturn tv.tv_sec;\n}\n\nLWS_VISIBLE LWS_EXTERN int\nlws_compare_time_t(struct lws_context *context, time_t t1, time_t t2)\n{\n\tif (t1 < context->time_discontiguity)\n\t\tt1 += context->time_fixup;\n\n\tif (t2 < context->time_discontiguity)\n\t\tt2 += context->time_fixup;\n\n\treturn (int)(t1 - t2);\n}\n\nLWS_VISIBLE lws_sockfd_type\nlws_get_socket_fd(struct lws *wsi)\n{\n\tif (!wsi)\n\t\treturn -1;\n\treturn wsi->desc.sockfd;\n}\n\n#ifdef LWS_LATENCY\nvoid\nlws_latency(struct lws_context *context, struct lws *wsi, const char *action,\n\t    int ret, int completed)\n{\n\tunsigned long long u;\n\tchar buf[256];\n\n\tu = time_in_microseconds();\n\n\tif (!action) {\n\t\twsi->latency_start = u;\n\t\tif (!wsi->action_start)\n\t\t\twsi->action_start = u;\n\t\treturn;\n\t}\n\tif (completed) {\n\t\tif (wsi->action_start == wsi->latency_start)\n\t\t\tsprintf(buf,\n\t\t\t  \"Completion first try lat %lluus: %p: ret %d: %s\\n\",\n\t\t\t\t\tu - wsi->latency_start,\n\t\t\t\t\t\t      (void *)wsi, ret, action);\n\t\telse\n\t\t\tsprintf(buf,\n\t\t\t  \"Completion %lluus: lat %lluus: %p: ret %d: %s\\n\",\n\t\t\t\tu - wsi->action_start,\n\t\t\t\t\tu - wsi->latency_start,\n\t\t\t\t\t\t      (void *)wsi, ret, action);\n\t\twsi->action_start = 0;\n\t} else\n\t\tsprintf(buf, \"lat %lluus: %p: ret %d: %s\\n\",\n\t\t\t      u - wsi->latency_start, (void *)wsi, ret, action);\n\n\tif (u - wsi->latency_start > context->worst_latency) {\n\t\tcontext->worst_latency = u - wsi->latency_start;\n\t\tstrcpy(context->worst_latency_info, buf);\n\t}\n\tlwsl_latency(\"%s\", buf);\n}\n#endif\n\nLWS_VISIBLE int\nlws_rx_flow_control(struct lws *wsi, int _enable)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tint en = _enable;\n\n\t// h2 ignores rx flow control atm\n\tif (lwsi_role_h2(wsi) || wsi->http2_substream ||\n\t    lwsi_role_h2_ENCAPSULATION(wsi))\n\t\treturn 0; // !!!\n\n\tlwsl_info(\"%s: %p 0x%x\\n\", __func__, wsi, _enable);\n\n\tif (!(_enable & LWS_RXFLOW_REASON_APPLIES)) {\n\t\t/*\n\t\t * convert user bool style to bitmap style... in user simple\n\t\t * bool style _enable = 0 = flow control it, = 1 = allow rx\n\t\t */\n\t\ten = LWS_RXFLOW_REASON_APPLIES | LWS_RXFLOW_REASON_USER_BOOL;\n\t\tif (_enable & 1)\n\t\t\ten |= LWS_RXFLOW_REASON_APPLIES_ENABLE_BIT;\n\t}\n\n\tlws_pt_lock(pt, __func__);\n\n\t/* any bit set in rxflow_bitmap DISABLEs rxflow control */\n\tif (en & LWS_RXFLOW_REASON_APPLIES_ENABLE_BIT)\n\t\twsi->rxflow_bitmap &= ~(en & 0xff);\n\telse\n\t\twsi->rxflow_bitmap |= en & 0xff;\n\n\tif ((LWS_RXFLOW_PENDING_CHANGE | (!wsi->rxflow_bitmap)) ==\n\t    wsi->rxflow_change_to)\n\t\tgoto skip;\n\n\twsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !wsi->rxflow_bitmap;\n\n\tlwsl_info(\"%s: %p: bitmap 0x%x: en 0x%x, ch 0x%x\\n\", __func__, wsi,\n\t\t  wsi->rxflow_bitmap, en, wsi->rxflow_change_to);\n\n\tif (_enable & LWS_RXFLOW_REASON_FLAG_PROCESS_NOW ||\n\t    !wsi->rxflow_will_be_applied) {\n\t\ten = __lws_rx_flow_control(wsi);\n\t\tlws_pt_unlock(pt);\n\n\t\treturn en;\n\t}\n\nskip:\n\tlws_pt_unlock(pt);\n\n\treturn 0;\n}\n\nLWS_VISIBLE void\nlws_rx_flow_allow_all_protocol(const struct lws_context *context,\n\t\t\t       const struct lws_protocols *protocol)\n{\n\tconst struct lws_context_per_thread *pt = &context->pt[0];\n\tstruct lws *wsi;\n\tunsigned int n, m = context->count_threads;\n\n\twhile (m--) {\n\t\tfor (n = 0; n < pt->fds_count; n++) {\n\t\t\twsi = wsi_from_fd(context, pt->fds[n].fd);\n\t\t\tif (!wsi)\n\t\t\t\tcontinue;\n\t\t\tif (wsi->protocol == protocol)\n\t\t\t\tlws_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);\n\t\t}\n\t\tpt++;\n\t}\n}\n\nint\nlws_broadcast(struct lws_context *context, int reason, void *in, size_t len)\n{\n\tstruct lws_vhost *v = context->vhost_list;\n\tstruct lws wsi;\n\tint n, ret = 0;\n\n\tmemset(&wsi, 0, sizeof(wsi));\n\twsi.context = context;\n\n\twhile (v) {\n\t\tconst struct lws_protocols *p = v->protocols;\n\t\twsi.vhost = v;\n\n\t\tfor (n = 0; n < v->count_protocols; n++) {\n\t\t\twsi.protocol = p;\n\t\t\tif (p->callback &&\n\t\t\t    p->callback(&wsi, reason, NULL, in, len))\n\t\t\t\tret |= 1;\n\t\t\tp++;\n\t\t}\n\t\tv = v->vhost_next;\n\t}\n\n\treturn ret;\n}\n\nLWS_VISIBLE extern const char *\nlws_canonical_hostname(struct lws_context *context)\n{\n\treturn (const char *)context->canonical_hostname;\n}\n\nLWS_VISIBLE LWS_EXTERN const char *\nlws_get_vhost_name(struct lws_vhost *vhost)\n{\n\treturn vhost->name;\n}\n\nLWS_VISIBLE LWS_EXTERN int\nlws_get_vhost_port(struct lws_vhost *vhost)\n{\n\treturn vhost->listen_port;\n}\n\nLWS_VISIBLE LWS_EXTERN void *\nlws_get_vhost_user(struct lws_vhost *vhost)\n{\n\treturn vhost->user;\n}\n\nLWS_VISIBLE LWS_EXTERN const char *\nlws_get_vhost_iface(struct lws_vhost *vhost)\n{\n\treturn vhost->iface;\n}\n\nint user_callback_handle_rxflow(lws_callback_function callback_function,\n\t\t\t\tstruct lws *wsi,\n\t\t\t\tenum lws_callback_reasons reason, void *user,\n\t\t\t\tvoid *in, size_t len)\n{\n\tint n;\n\n\twsi->rxflow_will_be_applied = 1;\n\tn = callback_function(wsi, reason, user, in, len);\n\twsi->rxflow_will_be_applied = 0;\n\tif (!n)\n\t\tn = __lws_rx_flow_control(wsi);\n\n\treturn n;\n}\n\n#if !defined(LWS_WITHOUT_CLIENT)\nLWS_VISIBLE int\nlws_set_proxy(struct lws_vhost *vhost, const char *proxy)\n{\n\tchar *p;\n\tchar authstring[96];\n\n\tif (!proxy)\n\t\treturn -1;\n\n\t/* we have to deal with a possible redundant leading http:// */\n\tif (!strncmp(proxy, \"http://\", 7))\n\t\tproxy += 7;\n\n\tp = strrchr(proxy, '@');\n\tif (p) { /* auth is around */\n\n\t\tif ((unsigned int)(p - proxy) > sizeof(authstring) - 1)\n\t\t\tgoto auth_too_long;\n\n\t\tlws_strncpy(authstring, proxy, p - proxy + 1);\n\t\t// null termination not needed on input\n\t\tif (lws_b64_encode_string(authstring, lws_ptr_diff(p, proxy),\n\t\t\t\tvhost->proxy_basic_auth_token,\n\t\t    sizeof vhost->proxy_basic_auth_token) < 0)\n\t\t\tgoto auth_too_long;\n\n\t\tlwsl_info(\" Proxy auth in use\\n\");\n\n\t\tproxy = p + 1;\n\t} else\n\t\tvhost->proxy_basic_auth_token[0] = '\\0';\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tlws_strncpy(vhost->http.http_proxy_address, proxy,\n\t\t    sizeof(vhost->http.http_proxy_address));\n\n\tp = strchr(vhost->http.http_proxy_address, ':');\n\tif (!p && !vhost->http.http_proxy_port) {\n\t\tlwsl_err(\"http_proxy needs to be ads:port\\n\");\n\n\t\treturn -1;\n\t} else {\n\t\tif (p) {\n\t\t\t*p = '\\0';\n\t\t\tvhost->http.http_proxy_port = atoi(p + 1);\n\t\t}\n\t}\n\n\tlwsl_info(\" Proxy %s:%u\\n\", vhost->http.http_proxy_address,\n\t\t\tvhost->http.http_proxy_port);\n#endif\n\treturn 0;\n\nauth_too_long:\n\tlwsl_err(\"proxy auth too long\\n\");\n\n\treturn -1;\n}\n#endif\n\n#if defined(LWS_WITH_SOCKS5)\nLWS_VISIBLE int\nlws_set_socks(struct lws_vhost *vhost, const char *socks)\n{\n\tchar *p_at, *p_colon;\n\tchar user[96];\n\tchar password[96];\n\n\tif (!socks)\n\t\treturn -1;\n\n\tvhost->socks_user[0] = '\\0';\n\tvhost->socks_password[0] = '\\0';\n\n\tp_at = strrchr(socks, '@');\n\tif (p_at) { /* auth is around */\n\t\tif ((unsigned int)(p_at - socks) > (sizeof(user)\n\t\t\t+ sizeof(password) - 2)) {\n\t\t\tlwsl_err(\"Socks auth too long\\n\");\n\t\t\tgoto bail;\n\t\t}\n\n\t\tp_colon = strchr(socks, ':');\n\t\tif (p_colon) {\n\t\t\tif ((unsigned int)(p_colon - socks) > (sizeof(user)\n\t\t\t\t- 1) ) {\n\t\t\t\tlwsl_err(\"Socks user too long\\n\");\n\t\t\t\tgoto bail;\n\t\t\t}\n\t\t\tif ((unsigned int)(p_at - p_colon) > (sizeof(password)\n\t\t\t\t- 1) ) {\n\t\t\t\tlwsl_err(\"Socks password too long\\n\");\n\t\t\t\tgoto bail;\n\t\t\t}\n\n\t\t\tlws_strncpy(vhost->socks_user, socks, p_colon - socks + 1);\n\t\t\tlws_strncpy(vhost->socks_password, p_colon + 1,\n\t\t\t\tp_at - (p_colon + 1) + 1);\n\t\t}\n\n\t\tlwsl_info(\" Socks auth, user: %s, password: %s\\n\",\n\t\t\tvhost->socks_user, vhost->socks_password );\n\n\t\tsocks = p_at + 1;\n\t}\n\n\tlws_strncpy(vhost->socks_proxy_address, socks,\n\t\t    sizeof(vhost->socks_proxy_address));\n\n\tp_colon = strchr(vhost->socks_proxy_address, ':');\n\tif (!p_colon && !vhost->socks_proxy_port) {\n\t\tlwsl_err(\"socks_proxy needs to be address:port\\n\");\n\t\treturn -1;\n\t} else {\n\t\tif (p_colon) {\n\t\t\t*p_colon = '\\0';\n\t\t\tvhost->socks_proxy_port = atoi(p_colon + 1);\n\t\t}\n\t}\n\n\tlwsl_info(\" Socks %s:%u\\n\", vhost->socks_proxy_address,\n\t\t\tvhost->socks_proxy_port);\n\n\treturn 0;\n\nbail:\n\treturn -1;\n}\n#endif\n\nLWS_VISIBLE const struct lws_protocols *\nlws_get_protocol(struct lws *wsi)\n{\n\treturn wsi->protocol;\n}\n\n\nint\nlws_ensure_user_space(struct lws *wsi)\n{\n\tif (!wsi->protocol)\n\t\treturn 0;\n\n\t/* allocate the per-connection user memory (if any) */\n\n\tif (wsi->protocol->per_session_data_size && !wsi->user_space) {\n\t\twsi->user_space = lws_zalloc(\n\t\t\t    wsi->protocol->per_session_data_size, \"user space\");\n\t\tif (wsi->user_space == NULL) {\n\t\t\tlwsl_err(\"%s: OOM\\n\", __func__);\n\t\t\treturn 1;\n\t\t}\n\t} else\n\t\tlwsl_debug(\"%s: %p protocol pss %lu, user_space=%p\\n\", __func__,\n\t\t\t   wsi, (long)wsi->protocol->per_session_data_size,\n\t\t\t   wsi->user_space);\n\treturn 0;\n}\n\nLWS_VISIBLE void *\nlws_adjust_protocol_psds(struct lws *wsi, size_t new_size)\n{\n\t((struct lws_protocols *)lws_get_protocol(wsi))->per_session_data_size =\n\t\tnew_size;\n\n\tif (lws_ensure_user_space(wsi))\n\t\t\treturn NULL;\n\n\treturn wsi->user_space;\n}\n\nLWS_VISIBLE int\nlwsl_timestamp(int level, char *p, int len)\n{\n#ifndef LWS_PLAT_OPTEE\n\ttime_t o_now = time(NULL);\n\tunsigned long long now;\n\tstruct tm *ptm = NULL;\n#ifndef WIN32\n\tstruct tm tm;\n#endif\n\tint n;\n\n#ifndef _WIN32_WCE\n#ifdef WIN32\n\tptm = localtime(&o_now);\n#else\n\tif (localtime_r(&o_now, &tm))\n\t\tptm = &tm;\n#endif\n#endif\n\tp[0] = '\\0';\n\tfor (n = 0; n < LLL_COUNT; n++) {\n\t\tif (level != (1 << n))\n\t\t\tcontinue;\n\t\tnow = time_in_microseconds() / 100;\n\t\tif (ptm)\n\t\t\tn = lws_snprintf(p, len,\n\t\t\t\t\"[%04d/%02d/%02d %02d:%02d:%02d:%04d] %s: \",\n\t\t\t\tptm->tm_year + 1900,\n\t\t\t\tptm->tm_mon + 1,\n\t\t\t\tptm->tm_mday,\n\t\t\t\tptm->tm_hour,\n\t\t\t\tptm->tm_min,\n\t\t\t\tptm->tm_sec,\n\t\t\t\t(int)(now % 10000), log_level_names[n]);\n\t\telse\n\t\t\tn = lws_snprintf(p, len, \"[%llu:%04d] %s: \",\n\t\t\t\t\t(unsigned long long) now / 10000,\n\t\t\t\t\t(int)(now % 10000), log_level_names[n]);\n\t\treturn n;\n\t}\n#else\n\tp[0] = '\\0';\n#endif\n\n\treturn 0;\n}\n\n#ifndef LWS_PLAT_OPTEE\nstatic const char * const colours[] = {\n\t\"[31;1m\", /* LLL_ERR */\n\t\"[36;1m\", /* LLL_WARN */\n\t\"[35;1m\", /* LLL_NOTICE */\n\t\"[32;1m\", /* LLL_INFO */\n\t\"[34;1m\", /* LLL_DEBUG */\n\t\"[33;1m\", /* LLL_PARSER */\n\t\"[33m\", /* LLL_HEADER */\n\t\"[33m\", /* LLL_EXT */\n\t\"[33m\", /* LLL_CLIENT */\n\t\"[33;1m\", /* LLL_LATENCY */\n\t\"[30;1m\", /* LLL_USER */\n};\n\nLWS_VISIBLE void lwsl_emit_stderr(int level, const char *line)\n{\n\tchar buf[50];\n\tstatic char tty = 3;\n\tint n, m = LWS_ARRAY_SIZE(colours) - 1;\n\n\tif (!tty)\n\t\ttty = isatty(2) | 2;\n\tlwsl_timestamp(level, buf, sizeof(buf));\n\n\tif (tty == 3) {\n\t\tn = 1 << (LWS_ARRAY_SIZE(colours) - 1);\n\t\twhile (n) {\n\t\t\tif (level & n)\n\t\t\t\tbreak;\n\t\t\tm--;\n\t\t\tn >>= 1;\n\t\t}\n\t\tfprintf(stderr, \"%c%s%s%s%c[0m\", 27, colours[m], buf, line, 27);\n\t} else\n\t\tfprintf(stderr, \"%s%s\", buf, line);\n}\n#endif\n\nLWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl)\n{\n\tchar buf[256];\n\tint n;\n\n\tif (!(log_level & filter))\n\t\treturn;\n\n\tn = vsnprintf(buf, sizeof(buf) - 1, format, vl);\n\t(void)n;\n\t/* vnsprintf returns what it would have written, even if truncated */\n\tif (n > (int)sizeof(buf) - 1)\n\t\tn = sizeof(buf) - 1;\n\tif (n > 0)\n\t\tbuf[n] = '\\0';\n\n\tlwsl_emit(filter, buf);\n}\n\nLWS_VISIBLE void _lws_log(int filter, const char *format, ...)\n{\n\tva_list ap;\n\n\tva_start(ap, format);\n\t_lws_logv(filter, format, ap);\n\tva_end(ap);\n}\n\nLWS_VISIBLE void lws_set_log_level(int level,\n\t\t\t\t   void (*func)(int level, const char *line))\n{\n\tlog_level = level;\n\tif (func)\n\t\tlwsl_emit = func;\n}\n\nLWS_VISIBLE int lwsl_visible(int level)\n{\n\treturn log_level & level;\n}\n\nLWS_VISIBLE void\nlwsl_hexdump_level(int hexdump_level, const void *vbuf, size_t len)\n{\n\tunsigned char *buf = (unsigned char *)vbuf;\n\tunsigned int n, m, start;\n\tchar line[80];\n\tchar *p;\n\n\tif (!lwsl_visible(hexdump_level))\n\t\treturn;\n\n\tif (!len)\n\t\treturn;\n\n\tif (!vbuf)\n\t\treturn;\n\n\t_lws_log(hexdump_level, \"\\n\");\n\n\tfor (n = 0; n < len;) {\n\t\tstart = n;\n\t\tp = line;\n\n\t\tp += sprintf(p, \"%04X: \", start);\n\n\t\tfor (m = 0; m < 16 && n < len; m++)\n\t\t\tp += sprintf(p, \"%02X \", buf[n++]);\n\t\twhile (m++ < 16)\n\t\t\tp += sprintf(p, \"   \");\n\n\t\tp += sprintf(p, \"   \");\n\n\t\tfor (m = 0; m < 16 && (start + m) < len; m++) {\n\t\t\tif (buf[start + m] >= ' ' && buf[start + m] < 127)\n\t\t\t\t*p++ = buf[start + m];\n\t\t\telse\n\t\t\t\t*p++ = '.';\n\t\t}\n\t\twhile (m++ < 16)\n\t\t\t*p++ = ' ';\n\n\t\t*p++ = '\\n';\n\t\t*p = '\\0';\n\t\t_lws_log(hexdump_level, \"%s\", line);\n\t\t(void)line;\n\t}\n\n\t_lws_log(hexdump_level, \"\\n\");\n}\n\nLWS_VISIBLE void\nlwsl_hexdump(const void *vbuf, size_t len)\n{\n#if defined(_DEBUG)\n\tlwsl_hexdump_level(LLL_DEBUG, vbuf, len);\n#endif\n}\n\nLWS_VISIBLE int\nlws_is_ssl(struct lws *wsi)\n{\n#if defined(LWS_WITH_TLS)\n\treturn wsi->tls.use_ssl & LCCSCF_USE_SSL;\n#else\n\t(void)wsi;\n\treturn 0;\n#endif\n}\n\n#if defined(LWS_WITH_TLS) && !defined(LWS_WITH_MBEDTLS)\nLWS_VISIBLE lws_tls_conn*\nlws_get_ssl(struct lws *wsi)\n{\n\treturn wsi->tls.ssl;\n}\n#endif\n\nLWS_VISIBLE int\nlws_partial_buffered(struct lws *wsi)\n{\n\treturn !!wsi->trunc_len;\n}\n\nLWS_VISIBLE lws_fileofs_t\nlws_get_peer_write_allowance(struct lws *wsi)\n{\n\tif (!wsi->role_ops->tx_credit)\n\t\treturn -1;\n\treturn wsi->role_ops->tx_credit(wsi);\n}\n\nLWS_VISIBLE void\nlws_role_transition(struct lws *wsi, enum lwsi_role role, enum lwsi_state state,\n\t\tstruct lws_role_ops *ops)\n{\n#if defined(_DEBUG)\n\tconst char *name = \"(unset)\";\n#endif\n\twsi->wsistate = role | state;\n\tif (ops)\n\t\twsi->role_ops = ops;\n#if defined(_DEBUG)\n\tif (wsi->role_ops)\n\t\tname = wsi->role_ops->name;\n\tlwsl_debug(\"%s: %p: wsistate 0x%x, ops %s\\n\", __func__, wsi,\n\t\t   wsi->wsistate, name);\n#endif\n}\n\nLWS_VISIBLE struct lws_plat_file_ops *\nlws_get_fops(struct lws_context *context)\n{\n\treturn (struct lws_plat_file_ops *)context->fops;\n}\n\nLWS_VISIBLE LWS_EXTERN struct lws_context *\nlws_get_context(const struct lws *wsi)\n{\n\treturn wsi->context;\n}\n\nLWS_VISIBLE LWS_EXTERN int\nlws_get_count_threads(struct lws_context *context)\n{\n\treturn context->count_threads;\n}\n\nLWS_VISIBLE LWS_EXTERN void *\nlws_wsi_user(struct lws *wsi)\n{\n\treturn wsi->user_space;\n}\n\nLWS_VISIBLE LWS_EXTERN void\nlws_set_wsi_user(struct lws *wsi, void *data)\n{\n\tif (wsi->user_space_externally_allocated)\n\t\twsi->user_space = data;\n\telse\n\t\tlwsl_err(\"%s: Cannot set internally-allocated user_space\\n\",\n\t\t\t __func__);\n}\n\nLWS_VISIBLE LWS_EXTERN struct lws *\nlws_get_parent(const struct lws *wsi)\n{\n\treturn wsi->parent;\n}\n\nLWS_VISIBLE LWS_EXTERN struct lws *\nlws_get_child(const struct lws *wsi)\n{\n\treturn wsi->child_list;\n}\n\nLWS_VISIBLE LWS_EXTERN void\nlws_set_parent_carries_io(struct lws *wsi)\n{\n\twsi->parent_carries_io = 1;\n}\n\nLWS_VISIBLE LWS_EXTERN void *\nlws_get_opaque_parent_data(const struct lws *wsi)\n{\n\treturn wsi->opaque_parent_data;\n}\n\nLWS_VISIBLE LWS_EXTERN void\nlws_set_opaque_parent_data(struct lws *wsi, void *data)\n{\n\twsi->opaque_parent_data = data;\n}\n\nLWS_VISIBLE LWS_EXTERN int\nlws_get_child_pending_on_writable(const struct lws *wsi)\n{\n\treturn wsi->parent_pending_cb_on_writable;\n}\n\nLWS_VISIBLE LWS_EXTERN void\nlws_clear_child_pending_on_writable(struct lws *wsi)\n{\n\twsi->parent_pending_cb_on_writable = 0;\n}\n\n\nLWS_EXTERN int\n__lws_rx_flow_control(struct lws *wsi)\n{\n\tstruct lws *wsic = wsi->child_list;\n\n\t// h2 ignores rx flow control atm\n\tif (lwsi_role_h2(wsi) || wsi->http2_substream ||\n\t    lwsi_role_h2_ENCAPSULATION(wsi))\n\t\treturn 0; // !!!\n\n\t/* if he has children, do those if they were changed */\n\twhile (wsic) {\n\t\tif (wsic->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)\n\t\t\t__lws_rx_flow_control(wsic);\n\n\t\twsic = wsic->sibling_list;\n\t}\n\n\t/* there is no pending change */\n\tif (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE))\n\t\treturn 0;\n\n\t/* stuff is still buffered, not ready to really accept new input */\n\tif (lws_buflist_next_segment_len(&wsi->buflist, NULL)) {\n\t\t/* get ourselves called back to deal with stashed buffer */\n\t\tlws_callback_on_writable(wsi);\n\t\treturn 0;\n\t}\n\n\t/* now the pending is cleared, we can change rxflow state */\n\n\twsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;\n\n\tlwsl_info(\"rxflow: wsi %p change_to %d\\n\", wsi,\n\t\t\t      wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);\n\n\t/* adjust the pollfd for this wsi */\n\n\tif (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {\n\t\tif (__lws_change_pollfd(wsi, 0, LWS_POLLIN)) {\n\t\t\tlwsl_info(\"%s: fail\\n\", __func__);\n\t\t\treturn -1;\n\t\t}\n\t} else\n\t\tif (__lws_change_pollfd(wsi, LWS_POLLIN, 0))\n\t\t\treturn -1;\n\n\treturn 0;\n}\n\nLWS_EXTERN int\nlws_check_utf8(unsigned char *state, unsigned char *buf, size_t len)\n{\n\tstatic const unsigned char e0f4[] = {\n\t\t0xa0 | ((2 - 1) << 2) | 1, /* e0 */\n\t\t0x80 | ((4 - 1) << 2) | 1, /* e1 */\n\t\t0x80 | ((4 - 1) << 2) | 1, /* e2 */\n\t\t0x80 | ((4 - 1) << 2) | 1, /* e3 */\n\t\t0x80 | ((4 - 1) << 2) | 1, /* e4 */\n\t\t0x80 | ((4 - 1) << 2) | 1, /* e5 */\n\t\t0x80 | ((4 - 1) << 2) | 1, /* e6 */\n\t\t0x80 | ((4 - 1) << 2) | 1, /* e7 */\n\t\t0x80 | ((4 - 1) << 2) | 1, /* e8 */\n\t\t0x80 | ((4 - 1) << 2) | 1, /* e9 */\n\t\t0x80 | ((4 - 1) << 2) | 1, /* ea */\n\t\t0x80 | ((4 - 1) << 2) | 1, /* eb */\n\t\t0x80 | ((4 - 1) << 2) | 1, /* ec */\n\t\t0x80 | ((2 - 1) << 2) | 1, /* ed */\n\t\t0x80 | ((4 - 1) << 2) | 1, /* ee */\n\t\t0x80 | ((4 - 1) << 2) | 1, /* ef */\n\t\t0x90 | ((3 - 1) << 2) | 2, /* f0 */\n\t\t0x80 | ((4 - 1) << 2) | 2, /* f1 */\n\t\t0x80 | ((4 - 1) << 2) | 2, /* f2 */\n\t\t0x80 | ((4 - 1) << 2) | 2, /* f3 */\n\t\t0x80 | ((1 - 1) << 2) | 2, /* f4 */\n\n\t\t0,\t\t\t   /* s0 */\n\t\t0x80 | ((4 - 1) << 2) | 0, /* s2 */\n\t\t0x80 | ((4 - 1) << 2) | 1, /* s3 */\n\t};\n\tunsigned char s = *state;\n\n\twhile (len--) {\n\t\tunsigned char c = *buf++;\n\n\t\tif (!s) {\n\t\t\tif (c >= 0x80) {\n\t\t\t\tif (c < 0xc2 || c > 0xf4)\n\t\t\t\t\treturn 1;\n\t\t\t\tif (c < 0xe0)\n\t\t\t\t\ts = 0x80 | ((4 - 1) << 2);\n\t\t\t\telse\n\t\t\t\t\ts = e0f4[c - 0xe0];\n\t\t\t}\n\t\t} else {\n\t\t\tif (c < (s & 0xf0) ||\n\t\t\t    c >= (s & 0xf0) + 0x10 + ((s << 2) & 0x30))\n\t\t\t\treturn 1;\n\t\t\ts = e0f4[21 + (s & 3)];\n\t\t}\n\t}\n\n\t*state = s;\n\n\treturn 0;\n}\n\nLWS_VISIBLE LWS_EXTERN int\nlws_parse_uri(char *p, const char **prot, const char **ads, int *port,\n\t      const char **path)\n{\n\tconst char *end;\n\tstatic const char *slash = \"/\";\n\n\t/* cut up the location into address, port and path */\n\t*prot = p;\n\twhile (*p && (*p != ':' || p[1] != '/' || p[2] != '/'))\n\t\tp++;\n\tif (!*p) {\n\t\tend = p;\n\t\tp = (char *)*prot;\n\t\t*prot = end;\n\t} else {\n\t\t*p = '\\0';\n\t\tp += 3;\n\t}\n\t*ads = p;\n\tif (!strcmp(*prot, \"http\") || !strcmp(*prot, \"ws\"))\n\t\t*port = 80;\n\telse if (!strcmp(*prot, \"https\") || !strcmp(*prot, \"wss\"))\n\t\t*port = 443;\n\n       if (*p == '[')\n       {\n               ++(*ads);\n               while (*p && *p != ']')\n                       p++;\n               if (*p)\n                       *p++ = '\\0';\n       }\n       else\n       {\n               while (*p && *p != ':' && *p != '/')\n                       p++;\n       }\n\tif (*p == ':') {\n\t\t*p++ = '\\0';\n\t\t*port = atoi(p);\n\t\twhile (*p && *p != '/')\n\t\t\tp++;\n\t}\n\t*path = slash;\n\tif (*p) {\n\t\t*p++ = '\\0';\n\t\tif (*p)\n\t\t\t*path = p;\n\t}\n\n\treturn 0;\n}\n\n#if defined(LWS_WITHOUT_EXTENSIONS)\n\n/* we need to provide dummy callbacks for internal exts\n * so user code runs when faced with a lib compiled with\n * extensions disabled.\n */\n\nLWS_VISIBLE int\nlws_extension_callback_pm_deflate(struct lws_context *context,\n                                  const struct lws_extension *ext,\n                                  struct lws *wsi,\n                                  enum lws_extension_callback_reasons reason,\n                                  void *user, void *in, size_t len)\n{\n\t(void)context;\n\t(void)ext;\n\t(void)wsi;\n\t(void)reason;\n\t(void)user;\n\t(void)in;\n\t(void)len;\n\n\treturn 0;\n}\n\nLWS_EXTERN int\nlws_set_extension_option(struct lws *wsi, const char *ext_name,\n\t\t\t const char *opt_name, const char *opt_val)\n{\n\treturn -1;\n}\n#endif\n\nLWS_EXTERN int\nlws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port,\n\t\tconst char *iface)\n{\n#ifdef LWS_WITH_UNIX_SOCK\n\tstruct sockaddr_un serv_unix;\n#endif\n#ifdef LWS_WITH_IPV6\n\tstruct sockaddr_in6 serv_addr6;\n#endif\n\tstruct sockaddr_in serv_addr4;\n#ifndef LWS_PLAT_OPTEE\n\tsocklen_t len = sizeof(struct sockaddr_storage);\n#endif\n\tint n;\n#if !defined(LWS_WITH_ESP32)\n\tint m;\n#endif\n\tstruct sockaddr_storage sin;\n\tstruct sockaddr *v;\n\n#ifdef LWS_WITH_UNIX_SOCK\n\tif (LWS_UNIX_SOCK_ENABLED(vhost)) {\n\t\tv = (struct sockaddr *)&serv_unix;\n\t\tn = sizeof(struct sockaddr_un);\n\t\tbzero((char *) &serv_unix, sizeof(serv_unix));\n\t\tserv_unix.sun_family = AF_UNIX;\n\t\tif (!iface)\n\t\t\treturn -1;\n\t\tif (sizeof(serv_unix.sun_path) <= strlen(iface)) {\n\t\t\tlwsl_err(\"\\\"%s\\\" too long for UNIX domain socket\\n\",\n\t\t\t         iface);\n\t\t\treturn -1;\n\t\t}\n\t\tstrcpy(serv_unix.sun_path, iface);\n\t\tif (serv_unix.sun_path[0] == '@')\n\t\t\tserv_unix.sun_path[0] = '\\0';\n\n\t} else\n#endif\n#if defined(LWS_WITH_IPV6) && !defined(LWS_WITH_ESP32)\n\tif (LWS_IPV6_ENABLED(vhost)) {\n\t\tv = (struct sockaddr *)&serv_addr6;\n\t\tn = sizeof(struct sockaddr_in6);\n\t\tbzero((char *) &serv_addr6, sizeof(serv_addr6));\n\t\tif (iface) {\n\t\t\tm = interface_to_sa(vhost, iface,\n\t\t\t\t    (struct sockaddr_in *)v, n);\n\t\t\tif (m == LWS_ITOSA_NOT_USABLE) {\n\t\t\t\tlwsl_info(\"%s: netif %s: Not usable\\n\",\n\t\t\t\t\t __func__, iface);\n\t\t\t\treturn m;\n\t\t\t}\n\t\t\tif (m == LWS_ITOSA_NOT_EXIST) {\n\t\t\t\tlwsl_info(\"%s: netif %s: Does not exist\\n\",\n\t\t\t\t\t __func__, iface);\n\t\t\t\treturn m;\n\t\t\t}\n\t\t\tserv_addr6.sin6_scope_id = lws_get_addr_scope(iface);\n\t\t}\n\n\t\tserv_addr6.sin6_family = AF_INET6;\n\t\tserv_addr6.sin6_port = htons(port);\n\t} else\n#endif\n\t{\n\t\tv = (struct sockaddr *)&serv_addr4;\n\t\tn = sizeof(serv_addr4);\n\t\tbzero((char *) &serv_addr4, sizeof(serv_addr4));\n\t\tserv_addr4.sin_addr.s_addr = INADDR_ANY;\n\t\tserv_addr4.sin_family = AF_INET;\n#if !defined(LWS_WITH_ESP32)\n\n\t\tif (iface) {\n\t\t    m = interface_to_sa(vhost, iface,\n\t\t\t\t    (struct sockaddr_in *)v, n);\n\t\t\tif (m == LWS_ITOSA_NOT_USABLE) {\n\t\t\t\tlwsl_info(\"%s: netif %s: Not usable\\n\",\n\t\t\t\t\t __func__, iface);\n\t\t\t\treturn m;\n\t\t\t}\n\t\t\tif (m == LWS_ITOSA_NOT_EXIST) {\n\t\t\t\tlwsl_info(\"%s: netif %s: Does not exist\\n\",\n\t\t\t\t\t __func__, iface);\n\t\t\t\treturn m;\n\t\t\t}\n\t\t}\n#endif\n\t\tserv_addr4.sin_port = htons(port);\n\t} /* ipv4 */\n\n\t/* just checking for the interface extant */\n\tif (sockfd == LWS_SOCK_INVALID)\n\t\treturn 0;\n\n\tn = bind(sockfd, v, n);\n#ifdef LWS_WITH_UNIX_SOCK\n\tif (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) {\n\t\tlwsl_err(\"ERROR on binding fd %d to \\\"%s\\\" (%d %d)\\n\",\n\t\t\t\tsockfd, iface, n, LWS_ERRNO);\n\t\treturn -1;\n\t} else\n#endif\n\tif (n < 0) {\n\t\tlwsl_err(\"ERROR on binding fd %d to port %d (%d %d)\\n\",\n\t\t\t\tsockfd, port, n, LWS_ERRNO);\n\t\treturn -1;\n\t}\n\n#ifndef LWS_PLAT_OPTEE\n\tif (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)\n\t\tlwsl_warn(\"getsockname: %s\\n\", strerror(LWS_ERRNO));\n\telse\n#endif\n#if defined(LWS_WITH_IPV6)\n\t\tport = (sin.ss_family == AF_INET6) ?\n\t\t\tntohs(((struct sockaddr_in6 *) &sin)->sin6_port) :\n\t\t\tntohs(((struct sockaddr_in *) &sin)->sin_port);\n#else\n\t\t{\n\t\t\tstruct sockaddr_in sain;\n\t\t\tmemcpy(&sain, &sin, sizeof(sain));\n\t\t\tport = ntohs(sain.sin_port);\n\t\t}\n#endif\n\n\treturn port;\n}\n\nLWS_VISIBLE LWS_EXTERN int\nlws_get_vhost_listen_port(struct lws_vhost *vhost)\n{\n\treturn vhost->listen_port;\n}\n\n#if defined(LWS_WITH_IPV6)\nLWS_EXTERN unsigned long\nlws_get_addr_scope(const char *ipaddr)\n{\n\tunsigned long scope = 0;\n\n#ifndef WIN32\n\tstruct ifaddrs *addrs, *addr;\n\tchar ip[NI_MAXHOST];\n\tunsigned int i;\n\n\tgetifaddrs(&addrs);\n\tfor (addr = addrs; addr; addr = addr->ifa_next) {\n\t\tif (!addr->ifa_addr ||\n\t\t\taddr->ifa_addr->sa_family != AF_INET6)\n\t\t\tcontinue;\n\n\t\tgetnameinfo(addr->ifa_addr,\n\t\t\t\tsizeof(struct sockaddr_in6),\n\t\t\t\tip, sizeof(ip),\n\t\t\t\tNULL, 0, NI_NUMERICHOST);\n\n\t\ti = 0;\n\t\twhile (ip[i])\n\t\t\tif (ip[i++] == '%') {\n\t\t\t\tip[i - 1] = '\\0';\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tif (!strcmp(ip, ipaddr)) {\n\t\t\tscope = if_nametoindex(addr->ifa_name);\n\t\t\tbreak;\n\t\t}\n\t}\n\tfreeifaddrs(addrs);\n#else\n\tPIP_ADAPTER_ADDRESSES adapter, addrs = NULL;\n\tPIP_ADAPTER_UNICAST_ADDRESS addr;\n\tULONG size = 0;\n\tDWORD ret;\n\tstruct sockaddr_in6 *sockaddr;\n\tchar ip[NI_MAXHOST];\n\tunsigned int i;\n\tint found = 0;\n\n\tfor (i = 0; i < 5; i++)\n\t{\n\t\tret = GetAdaptersAddresses(AF_INET6, GAA_FLAG_INCLUDE_PREFIX,\n\t\t\t\tNULL, addrs, &size);\n\t\tif ((ret == NO_ERROR) || (ret == ERROR_NO_DATA)) {\n\t\t\tbreak;\n\t\t} else if (ret == ERROR_BUFFER_OVERFLOW)\n\t\t{\n\t\t\tif (addrs)\n\t\t\t\tfree(addrs);\n\t\t\taddrs = (IP_ADAPTER_ADDRESSES *)malloc(size);\n\t\t} else\n\t\t{\n\t\t\tif (addrs)\n\t\t\t{\n\t\t\t\tfree(addrs);\n\t\t\t\taddrs = NULL;\n\t\t\t}\n\t\t\tlwsl_err(\"Failed to get IPv6 address table (%d)\", ret);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif ((ret == NO_ERROR) && (addrs)) {\n\t\tadapter = addrs;\n\t\twhile (adapter && !found) {\n\t\t\taddr = adapter->FirstUnicastAddress;\n\t\t\twhile (addr && !found) {\n\t\t\t\tif (addr->Address.lpSockaddr->sa_family ==\n\t\t\t\t    AF_INET6) {\n\t\t\t\t\tsockaddr = (struct sockaddr_in6 *)\n\t\t\t\t\t\t(addr->Address.lpSockaddr);\n\n\t\t\t\t\tlws_plat_inet_ntop(sockaddr->sin6_family,\n\t\t\t\t\t\t\t&sockaddr->sin6_addr,\n\t\t\t\t\t\t\tip, sizeof(ip));\n\n\t\t\t\t\tif (!strcmp(ip, ipaddr)) {\n\t\t\t\t\t\tscope = sockaddr->sin6_scope_id;\n\t\t\t\t\t\tfound = 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\taddr = addr->Next;\n\t\t\t}\n\t\t\tadapter = adapter->Next;\n\t\t}\n\t}\n\tif (addrs)\n\t\tfree(addrs);\n#endif\n\n\treturn scope;\n}\n#endif\n\n#if !defined(LWS_NO_SERVER)\n\nLWS_EXTERN struct lws *\nlws_create_adopt_udp(struct lws_vhost *vhost, int port, int flags,\n\t\t     const char *protocol_name, struct lws *parent_wsi)\n{\n\tlws_sock_file_fd_type sock;\n\tstruct addrinfo h, *r, *rp;\n\tstruct lws *wsi = NULL;\n\tchar buf[16];\n\tint n;\n\n\tmemset(&h, 0, sizeof(h));\n\th.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */\n\th.ai_socktype = SOCK_DGRAM;\n\th.ai_protocol = IPPROTO_UDP;\n\th.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;\n\n\tlws_snprintf(buf, sizeof(buf), \"%u\", port);\n\tn = getaddrinfo(NULL, buf, &h, &r);\n\tif (n) {\n\t\tlwsl_info(\"%s: getaddrinfo error: %s\\n\", __func__,\n\t\t\t  gai_strerror(n));\n\t\tgoto bail;\n\t}\n\n\tfor (rp = r; rp; rp = rp->ai_next) {\n\t\tsock.sockfd = socket(rp->ai_family, rp->ai_socktype,\n\t\t\t\t     rp->ai_protocol);\n\t\tif (sock.sockfd >= 0)\n\t\t\tbreak;\n\t}\n\tif (!rp) {\n\t\tlwsl_err(\"%s: unable to create INET socket\\n\", __func__);\n\t\tgoto bail1;\n\t}\n\n\tif ((flags & LWS_CAUDP_BIND) && bind(sock.sockfd, rp->ai_addr,\n#if defined(_WIN32)\n\t\t\t    (int)rp->ai_addrlen\n#else\n\t\t\t    rp->ai_addrlen\n#endif\n\t   ) == -1) {\n\t\tlwsl_err(\"%s: bind failed\\n\", __func__);\n\t\tgoto bail2;\n\t}\n\n\twsi = lws_adopt_descriptor_vhost(vhost, LWS_ADOPT_RAW_SOCKET_UDP, sock,\n\t\t\t\t        protocol_name, parent_wsi);\n\tif (!wsi)\n\t\tlwsl_err(\"%s: udp adoption failed\\n\", __func__);\n\nbail2:\n\tif (!wsi)\n\t\tclose((int)sock.sockfd);\nbail1:\n\tfreeaddrinfo(r);\n\nbail:\n\treturn wsi;\n}\n\n#endif\n\n\n\nstatic const char *hex = \"0123456789ABCDEF\";\n\nLWS_VISIBLE LWS_EXTERN const char *\nlws_sql_purify(char *escaped, const char *string, int len)\n{\n\tconst char *p = string;\n\tchar *q = escaped;\n\n\twhile (*p && len-- > 2) {\n\t\tif (*p == '\\'') {\n\t\t\t*q++ = '\\'';\n\t\t\t*q++ = '\\'';\n\t\t\tlen --;\n\t\t\tp++;\n\t\t} else\n\t\t\t*q++ = *p++;\n\t}\n\t*q = '\\0';\n\n\treturn escaped;\n}\n\nLWS_VISIBLE LWS_EXTERN const char *\nlws_json_purify(char *escaped, const char *string, int len)\n{\n\tconst char *p = string;\n\tchar *q = escaped;\n\n\tif (!p) {\n\t\tescaped[0] = '\\0';\n\t\treturn escaped;\n\t}\n\n\twhile (*p && len-- > 6) {\n\t\tif (*p == '\\\"' || *p == '\\\\' || *p < 0x20) {\n\t\t\t*q++ = '\\\\';\n\t\t\t*q++ = 'u';\n\t\t\t*q++ = '0';\n\t\t\t*q++ = '0';\n\t\t\t*q++ = hex[((*p) >> 4) & 15];\n\t\t\t*q++ = hex[(*p) & 15];\n\t\t\tlen -= 5;\n\t\t\tp++;\n\t\t} else\n\t\t\t*q++ = *p++;\n\t}\n\t*q = '\\0';\n\n\treturn escaped;\n}\n\nLWS_VISIBLE LWS_EXTERN void\nlws_filename_purify_inplace(char *filename)\n{\n\twhile (*filename) {\n\n\t\tif (*filename == '.' && filename[1] == '.') {\n\t\t\t*filename = '_';\n\t\t\tfilename[1] = '_';\n\t\t}\n\n\t\tif (*filename == ':' ||\n\t\t    *filename == '/' ||\n\t\t    *filename == '\\\\' ||\n\t\t    *filename == '$' ||\n\t\t    *filename == '%')\n\t\t\t*filename = '_';\n\n\t\tfilename++;\n\t}\n}\n\nLWS_VISIBLE LWS_EXTERN const char *\nlws_urlencode(char *escaped, const char *string, int len)\n{\n\tconst char *p = string;\n\tchar *q = escaped;\n\n\twhile (*p && len-- > 3) {\n\t\tif (*p == ' ') {\n\t\t\t*q++ = '+';\n\t\t\tp++;\n\t\t\tcontinue;\n\t\t}\n\t\tif ((*p >= '0' && *p <= '9') ||\n\t\t    (*p >= 'A' && *p <= 'Z') ||\n\t\t    (*p >= 'a' && *p <= 'z')) {\n\t\t\t*q++ = *p++;\n\t\t\tcontinue;\n\t\t}\n\t\t*q++ = '%';\n\t\t*q++ = hex[(*p >> 4) & 0xf];\n\t\t*q++ = hex[*p & 0xf];\n\n\t\tlen -= 2;\n\t\tp++;\n\t}\n\t*q = '\\0';\n\n\treturn escaped;\n}\n\nLWS_VISIBLE LWS_EXTERN int\nlws_urldecode(char *string, const char *escaped, int len)\n{\n\tint state = 0, n;\n\tchar sum = 0;\n\n\twhile (*escaped && len) {\n\t\tswitch (state) {\n\t\tcase 0:\n\t\t\tif (*escaped == '%') {\n\t\t\t\tstate++;\n\t\t\t\tescaped++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (*escaped == '+') {\n\t\t\t\tescaped++;\n\t\t\t\t*string++ = ' ';\n\t\t\t\tlen--;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t*string++ = *escaped++;\n\t\t\tlen--;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tn = char_to_hex(*escaped);\n\t\t\tif (n < 0)\n\t\t\t\treturn -1;\n\t\t\tescaped++;\n\t\t\tsum = n << 4;\n\t\t\tstate++;\n\t\t\tbreak;\n\n\t\tcase 2:\n\t\t\tn = char_to_hex(*escaped);\n\t\t\tif (n < 0)\n\t\t\t\treturn -1;\n\t\t\tescaped++;\n\t\t\t*string++ = sum | n;\n\t\t\tlen--;\n\t\t\tstate = 0;\n\t\t\tbreak;\n\t\t}\n\n\t}\n\t*string = '\\0';\n\n\treturn 0;\n}\n\nLWS_VISIBLE LWS_EXTERN int\nlws_finalize_startup(struct lws_context *context)\n{\n\tstruct lws_context_creation_info info;\n\n\tinfo.uid = context->uid;\n\tinfo.gid = context->gid;\n\n#if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)\n\tmemcpy(info.caps, context->caps, sizeof(info.caps));\n\tinfo.count_caps = context->count_caps;\n#endif\n\n\tif (lws_check_opt(context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS))\n\t\tlws_plat_drop_app_privileges(&info);\n\n\treturn 0;\n}\n\nint\nlws_snprintf(char *str, size_t size, const char *format, ...)\n{\n\tva_list ap;\n\tint n;\n\n\tif (!size)\n\t\treturn 0;\n\n\tva_start(ap, format);\n\tn = vsnprintf(str, size, format, ap);\n\tva_end(ap);\n\n\tif (n >= (int)size)\n\t\treturn (int)size;\n\n\treturn n;\n}\n\nchar *\nlws_strncpy(char *dest, const char *src, size_t size)\n{\n\tstrncpy(dest, src, size - 1);\n\tdest[size - 1] = '\\0';\n\n\treturn dest;\n}\n\n\nLWS_VISIBLE LWS_EXTERN int\nlws_is_cgi(struct lws *wsi) {\n#ifdef LWS_WITH_CGI\n\treturn !!wsi->http.cgi;\n#else\n\treturn 0;\n#endif\n}\n\nconst struct lws_protocol_vhost_options *\nlws_pvo_search(const struct lws_protocol_vhost_options *pvo, const char *name)\n{\n\twhile (pvo) {\n\t\tif (!strcmp(pvo->name, name))\n\t\t\tbreak;\n\n\t\tpvo = pvo->next;\n\t}\n\n\treturn pvo;\n}\n\nvoid\nlws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs)\n{\n\tconst struct lws_vhost *vh = ctx->vhost_list;\n\n\twhile (vh) {\n\n\t\tcs->rx += vh->conn_stats.rx;\n\t\tcs->tx += vh->conn_stats.tx;\n\t\tcs->h1_conn += vh->conn_stats.h1_conn;\n\t\tcs->h1_trans += vh->conn_stats.h1_trans;\n\t\tcs->h2_trans += vh->conn_stats.h2_trans;\n\t\tcs->ws_upg += vh->conn_stats.ws_upg;\n\t\tcs->h2_upg += vh->conn_stats.h2_upg;\n\t\tcs->h2_alpn += vh->conn_stats.h2_alpn;\n\t\tcs->h2_subs += vh->conn_stats.h2_subs;\n\t\tcs->rejected += vh->conn_stats.rejected;\n\n\t\tvh = vh->vhost_next;\n\t}\n}\n\nconst char *\nlws_cmdline_option(int argc, const char **argv, const char *val)\n{\n\tint n = (int)strlen(val), c = argc;\n\n\twhile (--c > 0) {\n\n\t\tif (!strncmp(argv[c], val, n)) {\n\t\t\tif (!*(argv[c] + n) && c < argc - 1) {\n\t\t\t\t/* coverity treats unchecked argv as \"tainted\" */\n\t\t\t\tif (!argv[c + 1] || strlen(argv[c + 1]) > 1024)\n\t\t\t\t\treturn NULL;\n\t\t\t\treturn argv[c + 1];\n\t\t\t}\n\n\t\t\treturn argv[c] + n;\n\t\t}\n\t}\n\n\treturn NULL;\n}\n\n#ifdef LWS_WITH_SERVER_STATUS\n\nLWS_EXTERN int\nlws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len)\n{\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tstatic const char * const prots[] = {\n\t\t\"http://\",\n\t\t\"https://\",\n\t\t\"file://\",\n\t\t\"cgi://\",\n\t\t\">http://\",\n\t\t\">https://\",\n\t\t\"callback://\"\n\t};\n#endif\n\tchar *orig = buf, *end = buf + len - 1, first = 1;\n\tint n = 0;\n\n\tif (len < 100)\n\t\treturn 0;\n\n\tbuf += lws_snprintf(buf, end - buf,\n\t\t\t\"{\\n \\\"name\\\":\\\"%s\\\",\\n\"\n\t\t\t\" \\\"port\\\":\\\"%d\\\",\\n\"\n\t\t\t\" \\\"use_ssl\\\":\\\"%d\\\",\\n\"\n\t\t\t\" \\\"sts\\\":\\\"%d\\\",\\n\"\n\t\t\t\" \\\"rx\\\":\\\"%llu\\\",\\n\"\n\t\t\t\" \\\"tx\\\":\\\"%llu\\\",\\n\"\n\t\t\t\" \\\"h1_conn\\\":\\\"%lu\\\",\\n\"\n\t\t\t\" \\\"h1_trans\\\":\\\"%lu\\\",\\n\"\n\t\t\t\" \\\"h2_trans\\\":\\\"%lu\\\",\\n\"\n\t\t\t\" \\\"ws_upg\\\":\\\"%lu\\\",\\n\"\n\t\t\t\" \\\"rejected\\\":\\\"%lu\\\",\\n\"\n\t\t\t\" \\\"h2_upg\\\":\\\"%lu\\\",\\n\"\n\t\t\t\" \\\"h2_alpn\\\":\\\"%lu\\\",\\n\"\n\t\t\t\" \\\"h2_subs\\\":\\\"%lu\\\"\"\n\t\t\t,\n\t\t\tvh->name, vh->listen_port,\n#if defined(LWS_WITH_TLS)\n\t\t\tvh->tls.use_ssl & LCCSCF_USE_SSL,\n#else\n\t\t\t0,\n#endif\n\t\t\t!!(vh->options & LWS_SERVER_OPTION_STS),\n\t\t\tvh->conn_stats.rx, vh->conn_stats.tx,\n\t\t\tvh->conn_stats.h1_conn,\n\t\t\tvh->conn_stats.h1_trans,\n\t\t\tvh->conn_stats.h2_trans,\n\t\t\tvh->conn_stats.ws_upg,\n\t\t\tvh->conn_stats.rejected,\n\t\t\tvh->conn_stats.h2_upg,\n\t\t\tvh->conn_stats.h2_alpn,\n\t\t\tvh->conn_stats.h2_subs\n\t);\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tif (vh->http.mount_list) {\n\t\tconst struct lws_http_mount *m = vh->http.mount_list;\n\n\t\tbuf += lws_snprintf(buf, end - buf, \",\\n \\\"mounts\\\":[\");\n\t\twhile (m) {\n\t\t\tif (!first)\n\t\t\t\tbuf += lws_snprintf(buf, end - buf, \",\");\n\t\t\tbuf += lws_snprintf(buf, end - buf,\n\t\t\t\t\t\"\\n  {\\n   \\\"mountpoint\\\":\\\"%s\\\",\\n\"\n\t\t\t\t\t\"  \\\"origin\\\":\\\"%s%s\\\",\\n\"\n\t\t\t\t\t\"  \\\"cache_max_age\\\":\\\"%d\\\",\\n\"\n\t\t\t\t\t\"  \\\"cache_reuse\\\":\\\"%d\\\",\\n\"\n\t\t\t\t\t\"  \\\"cache_revalidate\\\":\\\"%d\\\",\\n\"\n\t\t\t\t\t\"  \\\"cache_intermediaries\\\":\\\"%d\\\"\\n\"\n\t\t\t\t\t,\n\t\t\t\t\tm->mountpoint,\n\t\t\t\t\tprots[m->origin_protocol],\n\t\t\t\t\tm->origin,\n\t\t\t\t\tm->cache_max_age,\n\t\t\t\t\tm->cache_reusable,\n\t\t\t\t\tm->cache_revalidate,\n\t\t\t\t\tm->cache_intermediaries);\n\t\t\tif (m->def)\n\t\t\t\tbuf += lws_snprintf(buf, end - buf,\n\t\t\t\t\t\t\",\\n  \\\"default\\\":\\\"%s\\\"\",\n\t\t\t\t\t\tm->def);\n\t\t\tbuf += lws_snprintf(buf, end - buf, \"\\n  }\");\n\t\t\tfirst = 0;\n\t\t\tm = m->mount_next;\n\t\t}\n\t\tbuf += lws_snprintf(buf, end - buf, \"\\n ]\");\n\t}\n#endif\n\tif (vh->protocols) {\n\t\tn = 0;\n\t\tfirst = 1;\n\n\t\tbuf += lws_snprintf(buf, end - buf, \",\\n \\\"ws-protocols\\\":[\");\n\t\twhile (n < vh->count_protocols) {\n\t\t\tif (!first)\n\t\t\t\tbuf += lws_snprintf(buf, end - buf, \",\");\n\t\t\tbuf += lws_snprintf(buf, end - buf,\n\t\t\t\t\t\"\\n  {\\n   \\\"%s\\\":{\\n\"\n\t\t\t\t\t\"    \\\"status\\\":\\\"ok\\\"\\n   }\\n  }\"\n\t\t\t\t\t,\n\t\t\t\t\tvh->protocols[n].name);\n\t\t\tfirst = 0;\n\t\t\tn++;\n\t\t}\n\t\tbuf += lws_snprintf(buf, end - buf, \"\\n ]\");\n\t}\n\n\tbuf += lws_snprintf(buf, end - buf, \"\\n}\");\n\n\treturn buf - orig;\n}\n\n\nLWS_EXTERN LWS_VISIBLE int\nlws_json_dump_context(const struct lws_context *context, char *buf, int len,\n\t\tint hide_vhosts)\n{\n\tchar *orig = buf, *end = buf + len - 1, first = 1;\n\tconst struct lws_vhost *vh = context->vhost_list;\n\tconst struct lws_context_per_thread *pt;\n\ttime_t t = time(NULL);\n\tint n, listening = 0, cgi_count = 0;\n\tstruct lws_conn_stats cs;\n\tdouble d = 0;\n#ifdef LWS_WITH_CGI\n\tstruct lws_cgi * const *pcgi;\n#endif\n\n#ifdef LWS_WITH_LIBUV\n\tuv_uptime(&d);\n#endif\n\n\tbuf += lws_snprintf(buf, end - buf, \"{ \"\n\t\t\t    \"\\\"version\\\":\\\"%s\\\",\\n\"\n\t\t\t    \"\\\"uptime\\\":\\\"%ld\\\",\\n\",\n\t\t\t    lws_get_library_version(),\n\t\t\t    (long)d);\n\n#ifdef LWS_HAVE_GETLOADAVG\n\t{\n\t\tdouble d[3];\n\t\tint m;\n\n\t\tm = getloadavg(d, 3);\n\t\tfor (n = 0; n < m; n++) {\n\t\t\tbuf += lws_snprintf(buf, end - buf,\n\t\t\t\t\"\\\"l%d\\\":\\\"%.2f\\\",\\n\",\n\t\t\t\tn + 1, d[n]);\n\t\t}\n\t}\n#endif\n\n\tbuf += lws_snprintf(buf, end - buf, \"\\\"contexts\\\":[\\n\");\n\n\tbuf += lws_snprintf(buf, end - buf, \"{ \"\n\t\t\t\t\"\\\"context_uptime\\\":\\\"%ld\\\",\\n\"\n\t\t\t\t\"\\\"cgi_spawned\\\":\\\"%d\\\",\\n\"\n\t\t\t\t\"\\\"pt_fd_max\\\":\\\"%d\\\",\\n\"\n\t\t\t\t\"\\\"ah_pool_max\\\":\\\"%d\\\",\\n\"\n\t\t\t\t\"\\\"deprecated\\\":\\\"%d\\\",\\n\"\n\t\t\t\t\"\\\"wsi_alive\\\":\\\"%d\\\",\\n\",\n\t\t\t\t(unsigned long)(t - context->time_up),\n\t\t\t\tcontext->count_cgi_spawned,\n\t\t\t\tcontext->fd_limit_per_thread,\n\t\t\t\tcontext->max_http_header_pool,\n\t\t\t\tcontext->deprecated,\n\t\t\t\tcontext->count_wsi_allocated);\n\n\tbuf += lws_snprintf(buf, end - buf, \"\\\"pt\\\":[\\n \");\n\tfor (n = 0; n < context->count_threads; n++) {\n\t\tpt = &context->pt[n];\n\t\tif (n)\n\t\t\tbuf += lws_snprintf(buf, end - buf, \",\");\n\t\tbuf += lws_snprintf(buf, end - buf,\n\t\t\t\t\"\\n  {\\n\"\n\t\t\t\t\"    \\\"fds_count\\\":\\\"%d\\\",\\n\"\n\t\t\t\t\"    \\\"ah_pool_inuse\\\":\\\"%d\\\",\\n\"\n\t\t\t\t\"    \\\"ah_wait_list\\\":\\\"%d\\\"\\n\"\n\t\t\t\t\"    }\",\n\t\t\t\tpt->fds_count,\n\t\t\t\tpt->http.ah_count_in_use,\n\t\t\t\tpt->http.ah_wait_list_length);\n\t}\n\n\tbuf += lws_snprintf(buf, end - buf, \"]\");\n\n\tbuf += lws_snprintf(buf, end - buf, \", \\\"vhosts\\\":[\\n \");\n\n\tfirst = 1;\n\tvh = context->vhost_list;\n\tlistening = 0;\n\tcs = context->conn_stats;\n\tlws_sum_stats(context, &cs);\n\twhile (vh) {\n\n\t\tif (!hide_vhosts) {\n\t\t\tif (!first)\n\t\t\t\tif(buf != end)\n\t\t\t\t\t*buf++ = ',';\n\t\t\tbuf += lws_json_dump_vhost(vh, buf, end - buf);\n\t\t\tfirst = 0;\n\t\t}\n\t\tif (vh->lserv_wsi)\n\t\t\tlistening++;\n\t\tvh = vh->vhost_next;\n\t}\n\n\tbuf += lws_snprintf(buf, end - buf,\n\t\t\t\"],\\n\\\"listen_wsi\\\":\\\"%d\\\",\\n\"\n\t\t\t\" \\\"rx\\\":\\\"%llu\\\",\\n\"\n\t\t\t\" \\\"tx\\\":\\\"%llu\\\",\\n\"\n\t\t\t\" \\\"h1_conn\\\":\\\"%lu\\\",\\n\"\n\t\t\t\" \\\"h1_trans\\\":\\\"%lu\\\",\\n\"\n\t\t\t\" \\\"h2_trans\\\":\\\"%lu\\\",\\n\"\n\t\t\t\" \\\"ws_upg\\\":\\\"%lu\\\",\\n\"\n\t\t\t\" \\\"rejected\\\":\\\"%lu\\\",\\n\"\n\t\t\t\" \\\"h2_alpn\\\":\\\"%lu\\\",\\n\"\n\t\t\t\" \\\"h2_subs\\\":\\\"%lu\\\",\\n\"\n\t\t\t\" \\\"h2_upg\\\":\\\"%lu\\\"\",\n\t\t\tlistening, cs.rx, cs.tx,\n\t\t\tcs.h1_conn,\n\t\t\tcs.h1_trans,\n\t\t\tcs.h2_trans,\n\t\t\tcs.ws_upg,\n\t\t\tcs.rejected,\n\t\t\tcs.h2_alpn,\n\t\t\tcs.h2_subs,\n\t\t\tcs.h2_upg);\n\n#ifdef LWS_WITH_CGI\n\tfor (n = 0; n < context->count_threads; n++) {\n\t\tpt = &context->pt[n];\n\t\tpcgi = &pt->http.cgi_list;\n\n\t\twhile (*pcgi) {\n\t\t\tpcgi = &(*pcgi)->cgi_list;\n\n\t\t\tcgi_count++;\n\t\t}\n\t}\n#endif\n\tbuf += lws_snprintf(buf, end - buf, \",\\n \\\"cgi_alive\\\":\\\"%d\\\"\\n \",\n\t\t\tcgi_count);\n\n\tbuf += lws_snprintf(buf, end - buf, \"}\");\n\n\n\tbuf += lws_snprintf(buf, end - buf, \"]}\\n \");\n\n\treturn buf - orig;\n}\n\n#endif\n\n#if defined(LWS_WITH_STATS)\n\nLWS_VISIBLE LWS_EXTERN uint64_t\nlws_stats_get(struct lws_context *context, int index)\n{\n\tif (index >= LWSSTATS_SIZE)\n\t\treturn 0;\n\n\treturn context->lws_stats[index];\n}\n\nLWS_VISIBLE LWS_EXTERN void\nlws_stats_log_dump(struct lws_context *context)\n{\n\tstruct lws_vhost *v = context->vhost_list;\n\tint n, m;\n\n\t(void)m;\n\n\tif (!context->updated)\n\t\treturn;\n\n\tcontext->updated = 0;\n\n\tlwsl_notice(\"\\n\");\n\tlwsl_notice(\"LWS internal statistics dump ----->\\n\");\n\tlwsl_notice(\"LWSSTATS_C_CONNECTIONS:                     %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_CONNECTIONS));\n\tlwsl_notice(\"LWSSTATS_C_API_CLOSE:                       %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_API_CLOSE));\n\tlwsl_notice(\"LWSSTATS_C_API_READ:                        %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_API_READ));\n\tlwsl_notice(\"LWSSTATS_C_API_LWS_WRITE:                   %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_API_LWS_WRITE));\n\tlwsl_notice(\"LWSSTATS_C_API_WRITE:                       %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_API_WRITE));\n\tlwsl_notice(\"LWSSTATS_C_WRITE_PARTIALS:                  %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_WRITE_PARTIALS));\n\tlwsl_notice(\"LWSSTATS_C_WRITEABLE_CB_REQ:                %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_WRITEABLE_CB_REQ));\n\tlwsl_notice(\"LWSSTATS_C_WRITEABLE_CB_EFF_REQ:            %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_WRITEABLE_CB_EFF_REQ));\n\tlwsl_notice(\"LWSSTATS_C_WRITEABLE_CB:                    %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_WRITEABLE_CB));\n\tlwsl_notice(\"LWSSTATS_C_SSL_CONNECTIONS_ACCEPT_SPIN:     %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_SSL_CONNECTIONS_ACCEPT_SPIN));\n\tlwsl_notice(\"LWSSTATS_C_SSL_CONNECTIONS_FAILED:          %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_SSL_CONNECTIONS_FAILED));\n\tlwsl_notice(\"LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED:        %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_SSL_CONNECTIONS_ACCEPTED));\n\tlwsl_notice(\"LWSSTATS_C_SSL_CONNS_HAD_RX:                %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_SSL_CONNS_HAD_RX));\n\tlwsl_notice(\"LWSSTATS_C_PEER_LIMIT_AH_DENIED:            %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_PEER_LIMIT_AH_DENIED));\n\tlwsl_notice(\"LWSSTATS_C_PEER_LIMIT_WSI_DENIED:           %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_PEER_LIMIT_WSI_DENIED));\n\n\tlwsl_notice(\"LWSSTATS_C_TIMEOUTS:                        %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_TIMEOUTS));\n\tlwsl_notice(\"LWSSTATS_C_SERVICE_ENTRY:                   %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_SERVICE_ENTRY));\n\tlwsl_notice(\"LWSSTATS_B_READ:                            %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context, LWSSTATS_B_READ));\n\tlwsl_notice(\"LWSSTATS_B_WRITE:                           %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context, LWSSTATS_B_WRITE));\n\tlwsl_notice(\"LWSSTATS_B_PARTIALS_ACCEPTED_PARTS:         %8llu\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_B_PARTIALS_ACCEPTED_PARTS));\n\tlwsl_notice(\"LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY: %8llums\\n\",\n\t\t(unsigned long long)lws_stats_get(context,\n\t\t\tLWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) / 1000);\n\tif (lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED))\n\t\tlwsl_notice(\"  Avg accept delay:                         %8llums\\n\",\n\t\t\t(unsigned long long)(lws_stats_get(context,\n\t\t\t\tLWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) /\n\t\t\t\t\tlws_stats_get(context,\n\t\t\t\tLWSSTATS_C_SSL_CONNECTIONS_ACCEPTED)) / 1000);\n\tlwsl_notice(\"LWSSTATS_MS_SSL_RX_DELAY:                   %8llums\\n\",\n\t\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_MS_SSL_RX_DELAY) / 1000);\n\tif (lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX))\n\t\tlwsl_notice(\"  Avg accept-rx delay:                      %8llums\\n\",\n\t\t\t(unsigned long long)(lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_MS_SSL_RX_DELAY) /\n\t\t\tlws_stats_get(context,\n\t\t\t\t\tLWSSTATS_C_SSL_CONNS_HAD_RX)) / 1000);\n\n\tlwsl_notice(\"LWSSTATS_MS_WRITABLE_DELAY:                 %8lluus\\n\",\n\t\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_MS_WRITABLE_DELAY));\n\tlwsl_notice(\"LWSSTATS_MS_WORST_WRITABLE_DELAY:           %8lluus\\n\",\n\t\t\t\t(unsigned long long)lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_MS_WORST_WRITABLE_DELAY));\n\tif (lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB))\n\t\tlwsl_notice(\"  Avg writable delay:                       %8lluus\\n\",\n\t\t\t(unsigned long long)(lws_stats_get(context,\n\t\t\t\t\tLWSSTATS_MS_WRITABLE_DELAY) /\n\t\t\tlws_stats_get(context, LWSSTATS_C_WRITEABLE_CB)));\n\tlwsl_notice(\"Simultaneous SSL restriction:               %8d/%d\\n\",\n\t\t\tcontext->simultaneous_ssl,\n\t\t\tcontext->simultaneous_ssl_restriction);\n\n\tlwsl_notice(\"Live wsi:                                   %8d\\n\",\n\t\t\tcontext->count_wsi_allocated);\n\n\tcontext->updated = 1;\n\n\twhile (v) {\n\t\tif (v->lserv_wsi &&\n\t\t    v->lserv_wsi->position_in_fds_table != LWS_NO_FDS_POS) {\n\n\t\t\tstruct lws_context_per_thread *pt =\n\t\t\t\t\t&context->pt[(int)v->lserv_wsi->tsi];\n\t\t\tstruct lws_pollfd *pfd;\n\n\t\t\tpfd = &pt->fds[v->lserv_wsi->position_in_fds_table];\n\n\t\t\tlwsl_notice(\"  Listen port %d actual POLLIN:   %d\\n\",\n\t\t\t\t    v->listen_port,\n\t\t\t\t    (int)pfd->events & LWS_POLLIN);\n\t\t}\n\n\t\tv = v->vhost_next;\n\t}\n\n\tfor (n = 0; n < context->count_threads; n++) {\n\t\tstruct lws_context_per_thread *pt = &context->pt[n];\n\t\tstruct lws *wl;\n\t\tint m = 0;\n\n\t\tlwsl_notice(\"PT %d\\n\", n + 1);\n\n\t\tlws_pt_lock(pt, __func__);\n\n\t\tlwsl_notice(\"  AH in use / max:                  %d / %d\\n\",\n\t\t\t\tpt->http.ah_count_in_use,\n\t\t\t\tcontext->max_http_header_pool);\n\n\t\twl = pt->http.ah_wait_list;\n\t\twhile (wl) {\n\t\t\tm++;\n\t\t\twl = wl->http.ah_wait_list;\n\t\t}\n\n\t\tlwsl_notice(\"  AH wait list count / actual:      %d / %d\\n\",\n\t\t\t\tpt->http.ah_wait_list_length, m);\n\n\t\tlws_pt_unlock(pt);\n\t}\n\n#if defined(LWS_WITH_PEER_LIMITS)\n\tm = 0;\n\tfor (n = 0; n < (int)context->pl_hash_elements; n++) {\n\t\tlws_start_foreach_llp(struct lws_peer **, peer,\n\t\t\t\t      context->pl_hash_table[n]) {\n\t\t\tm++;\n\t\t} lws_end_foreach_llp(peer, next);\n\t}\n\n\tlwsl_notice(\" Peers: total active %d\\n\", m);\n\tif (m > 10) {\n\t\tm = 10;\n\t\tlwsl_notice(\"  (showing 10 peers only)\\n\");\n\t}\n\n\tif (m) {\n\t\tfor (n = 0; n < (int)context->pl_hash_elements; n++) {\n\t\t\tchar buf[72];\n\n\t\t\tlws_start_foreach_llp(struct lws_peer **, peer,\n\t\t\t\t\t      context->pl_hash_table[n]) {\n\t\t\t\tstruct lws_peer *df = *peer;\n\n\t\t\t\tif (!lws_plat_inet_ntop(df->af, df->addr, buf,\n\t\t\t\t\t\t\tsizeof(buf) - 1))\n\t\t\t\t\tstrcpy(buf, \"unknown\");\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\t\t\t\tlwsl_notice(\"  peer %s: count wsi: %d, count ah: %d\\n\",\n\t\t\t\t\t    buf, df->count_wsi,\n\t\t\t\t\t    df->http.count_ah);\n#else\n\t\t\t\tlwsl_notice(\"  peer %s: count wsi: %d\\n\",\n\t\t\t\t\t    buf, df->count_wsi);\n#endif\n\n\t\t\t\tif (!--m)\n\t\t\t\t\tbreak;\n\t\t\t} lws_end_foreach_llp(peer, next);\n\t\t}\n\t}\n#endif\n\n\tlwsl_notice(\"\\n\");\n}\n\nvoid\nlws_stats_atomic_bump(struct lws_context * context,\n\t\tstruct lws_context_per_thread *pt, int index, uint64_t bump)\n{\n\tlws_pt_stats_lock(pt);\n\tcontext->lws_stats[index] += bump;\n\tif (index != LWSSTATS_C_SERVICE_ENTRY)\n\t\tcontext->updated = 1;\n\tlws_pt_stats_unlock(pt);\n}\n\nvoid\nlws_stats_atomic_max(struct lws_context * context,\n\t\tstruct lws_context_per_thread *pt, int index, uint64_t val)\n{\n\tlws_pt_stats_lock(pt);\n\tif (val > context->lws_stats[index]) {\n\t\tcontext->lws_stats[index] = val;\n\t\tcontext->updated = 1;\n\t}\n\tlws_pt_stats_unlock(pt);\n}\n\n#endif\n\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/core/output.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n\n/*\n * notice this returns number of bytes consumed, or -1\n */\nint lws_issue_raw(struct lws *wsi, unsigned char *buf, size_t len)\n{\n\tstruct lws_context *context = lws_get_context(wsi);\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tsize_t real_len = len;\n\tunsigned int n;\n\n\t// lwsl_hexdump_err(buf, len);\n\n\t/*\n\t * Detect if we got called twice without going through the\n\t * event loop to handle pending.  This would be caused by either\n\t * back-to-back writes in one WRITABLE (illegal) or calling lws_write()\n\t * from outside the WRITABLE callback (illegal).\n\t */\n\tif (wsi->could_have_pending) {\n\t\tlwsl_hexdump_level(LLL_ERR, buf, len);\n\t\tlwsl_err(\"** %p: vh: %s, prot: %s, role %s: \"\n\t\t\t \"Illegal back-to-back write of %lu detected...\\n\",\n\t\t\t wsi, wsi->vhost->name, wsi->protocol->name,\n\t\t\t wsi->role_ops->name,\n\t\t\t (unsigned long)len);\n\t\t// assert(0);\n\n\t\treturn -1;\n\t}\n\n\tlws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_API_WRITE, 1);\n\n\tif (!len)\n\t\treturn 0;\n\t/* just ignore sends after we cleared the truncation buffer */\n\tif (lwsi_state(wsi) == LRS_FLUSHING_BEFORE_CLOSE && !wsi->trunc_len)\n\t\treturn (int)len;\n\n\tif (wsi->trunc_len && (buf < wsi->trunc_alloc ||\n\t    buf > (wsi->trunc_alloc + wsi->trunc_len + wsi->trunc_offset))) {\n\t\tlwsl_hexdump_level(LLL_ERR, buf, len);\n\t\tlwsl_err(\"** %p: vh: %s, prot: %s, Sending new %lu, pending truncated ...\\n\"\n\t\t\t \"   It's illegal to do an lws_write outside of\\n\"\n\t\t\t \"   the writable callback: fix your code\\n\",\n\t\t\t wsi, wsi->vhost->name, wsi->protocol->name,\n\t\t\t (unsigned long)len);\n\t\tassert(0);\n\n\t\treturn -1;\n\t}\n\n\tif (!wsi->http2_substream && !lws_socket_is_valid(wsi->desc.sockfd))\n\t\tlwsl_warn(\"** error invalid sock but expected to send\\n\");\n\n\t/* limit sending */\n\tif (wsi->protocol->tx_packet_size)\n\t\tn = (int)wsi->protocol->tx_packet_size;\n\telse {\n\t\tn = (int)wsi->protocol->rx_buffer_size;\n\t\tif (!n)\n\t\t\tn = context->pt_serv_buf_size;\n\t}\n\tn += LWS_PRE + 4;\n\tif (n > len)\n\t\tn = (int)len;\n\n\t/* nope, send it on the socket directly */\n\tlws_latency_pre(context, wsi);\n\tn = lws_ssl_capable_write(wsi, buf, n);\n\tlws_latency(context, wsi, \"send lws_issue_raw\", n, n == len);\n\n\t/* something got written, it can have been truncated now */\n\twsi->could_have_pending = 1;\n\n\tswitch (n) {\n\tcase LWS_SSL_CAPABLE_ERROR:\n\t\t/* we're going to close, let close know sends aren't possible */\n\t\twsi->socket_is_permanently_unusable = 1;\n\t\treturn -1;\n\tcase LWS_SSL_CAPABLE_MORE_SERVICE:\n\t\t/*\n\t\t * nothing got sent, not fatal.  Retry the whole thing later,\n\t\t * ie, implying treat it was a truncated send so it gets\n\t\t * retried\n\t\t */\n\t\tn = 0;\n\t\tbreak;\n\t}\n\n\t/*\n\t * we were already handling a truncated send?\n\t */\n\tif (wsi->trunc_len) {\n\t\tlwsl_info(\"%p partial adv %d (vs %ld)\\n\", wsi, n, (long)real_len);\n\t\twsi->trunc_offset += n;\n\t\twsi->trunc_len -= n;\n\n\t\tif (!wsi->trunc_len) {\n\t\t\tlwsl_info(\"** %p partial send completed\\n\", wsi);\n\t\t\t/* done with it, but don't free it */\n\t\t\tn = (int)real_len;\n\t\t\tif (lwsi_state(wsi) == LRS_FLUSHING_BEFORE_CLOSE) {\n\t\t\t\tlwsl_info(\"** %p signalling to close now\\n\", wsi);\n\t\t\t\treturn -1; /* retry closing now */\n\t\t\t}\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n#if !defined(LWS_WITHOUT_SERVER)\n\t\t\tif (wsi->http.deferred_transaction_completed) {\n\t\t\t\tlwsl_notice(\"%s: partial completed, doing \"\n\t\t\t\t\t    \"deferred transaction completed\\n\",\n\t\t\t\t\t    __func__);\n\t\t\t\twsi->http.deferred_transaction_completed = 0;\n\t\t\t\treturn lws_http_transaction_completed(wsi);\n\t\t\t}\n#endif\n#endif\n\t\t}\n\t\t/* always callback on writeable */\n\t\tlws_callback_on_writable(wsi);\n\n\t\treturn n;\n\t}\n\n\tif ((unsigned int)n == real_len)\n\t\t/* what we just sent went out cleanly */\n\t\treturn n;\n\n\t/*\n\t * Newly truncated send.  Buffer the remainder (it will get\n\t * first priority next time the socket is writable).\n\t */\n\tlwsl_debug(\"%p new partial sent %d from %lu total\\n\", wsi, n,\n\t\t    (unsigned long)real_len);\n\n\tlws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITE_PARTIALS, 1);\n\tlws_stats_atomic_bump(wsi->context, pt, LWSSTATS_B_PARTIALS_ACCEPTED_PARTS, n);\n\n\t/*\n\t *  - if we still have a suitable malloc lying around, use it\n\t *  - or, if too small, reallocate it\n\t *  - or, if no buffer, create it\n\t */\n\tif (!wsi->trunc_alloc || real_len - n > wsi->trunc_alloc_len) {\n\t\tlws_free(wsi->trunc_alloc);\n\n\t\twsi->trunc_alloc_len = (unsigned int)(real_len - n);\n\t\twsi->trunc_alloc = lws_malloc(real_len - n,\n\t\t\t\t\t      \"truncated send alloc\");\n\t\tif (!wsi->trunc_alloc) {\n\t\t\tlwsl_err(\"truncated send: unable to malloc %lu\\n\",\n\t\t\t\t (unsigned long)(real_len - n));\n\t\t\treturn -1;\n\t\t}\n\t}\n\twsi->trunc_offset = 0;\n\twsi->trunc_len = (unsigned int)(real_len - n);\n\tmemcpy(wsi->trunc_alloc, buf + n, real_len - n);\n\n#if !defined(LWS_WITH_ESP32)\n\tif (lws_wsi_is_udp(wsi)) {\n\t\t/* stash original destination for fulfilling UDP partials */\n\t\twsi->udp->sa_pending = wsi->udp->sa;\n\t\twsi->udp->salen_pending = wsi->udp->salen;\n\t}\n#endif\n\n\t/* since something buffered, force it to get another chance to send */\n\tlws_callback_on_writable(wsi);\n\n\treturn (int)real_len;\n}\n\nLWS_VISIBLE int lws_write(struct lws *wsi, unsigned char *buf, size_t len,\n\t\t\t  enum lws_write_protocol wp)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\n\tif (wsi->parent_carries_io) {\n\t\tstruct lws_write_passthru pas;\n\n\t\tpas.buf = buf;\n\t\tpas.len = len;\n\t\tpas.wp = wp;\n\t\tpas.wsi = wsi;\n\n\t\tif (wsi->parent->protocol->callback(wsi->parent,\n\t\t\t\tLWS_CALLBACK_CHILD_WRITE_VIA_PARENT,\n\t\t\t\twsi->parent->user_space,\n\t\t\t\t(void *)&pas, 0))\n\t\t\treturn 1;\n\n\t\treturn (int)len;\n\t}\n\n\tlws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_API_LWS_WRITE, 1);\n\n\tif ((int)len < 0) {\n\t\tlwsl_err(\"%s: suspicious len int %d, ulong %lu\\n\", __func__,\n\t\t\t\t(int)len, (unsigned long)len);\n\t\treturn -1;\n\t}\n\n\tlws_stats_atomic_bump(wsi->context, pt, LWSSTATS_B_WRITE, len);\n\n#ifdef LWS_WITH_ACCESS_LOG\n\twsi->http.access_log.sent += len;\n#endif\n\tif (wsi->vhost)\n\t\twsi->vhost->conn_stats.tx += len;\n\n\tassert(wsi->role_ops);\n\tif (!wsi->role_ops->write_role_protocol)\n\t\treturn lws_issue_raw(wsi, buf, len);\n\n\treturn wsi->role_ops->write_role_protocol(wsi, buf, len, &wp);\n}\n\nLWS_VISIBLE int\nlws_ssl_capable_read_no_ssl(struct lws *wsi, unsigned char *buf, int len)\n{\n\tstruct lws_context *context = wsi->context;\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tint n = 0;\n\n\tlws_stats_atomic_bump(context, pt, LWSSTATS_C_API_READ, 1);\n\n\tif (lws_wsi_is_udp(wsi)) {\n#if !defined(LWS_WITH_ESP32)\n\t\twsi->udp->salen = sizeof(wsi->udp->sa);\n\t\tn = recvfrom(wsi->desc.sockfd, (char *)buf, len, 0,\n\t\t\t     &wsi->udp->sa, &wsi->udp->salen);\n#endif\n\t} else\n\t\tn = recv(wsi->desc.sockfd, (char *)buf, len, 0);\n\n\tif (n >= 0) {\n\t\tif (wsi->vhost)\n\t\t\twsi->vhost->conn_stats.rx += n;\n\t\tlws_stats_atomic_bump(context, pt, LWSSTATS_B_READ, n);\n\n\t\treturn n;\n\t}\n\n\tif (LWS_ERRNO == LWS_EAGAIN ||\n\t    LWS_ERRNO == LWS_EWOULDBLOCK ||\n\t    LWS_ERRNO == LWS_EINTR)\n\t\treturn LWS_SSL_CAPABLE_MORE_SERVICE;\n\n\tlwsl_notice(\"error on reading from skt : %d\\n\", LWS_ERRNO);\n\treturn LWS_SSL_CAPABLE_ERROR;\n}\n\nLWS_VISIBLE int\nlws_ssl_capable_write_no_ssl(struct lws *wsi, unsigned char *buf, int len)\n{\n\tint n = 0;\n\n\tif (lws_wsi_is_udp(wsi)) {\n#if !defined(LWS_WITH_ESP32)\n\t\tif (wsi->trunc_len)\n\t\t\tn = sendto(wsi->desc.sockfd, buf, len, 0, &wsi->udp->sa_pending, wsi->udp->salen_pending);\n\t\telse\n\t\t\tn = sendto(wsi->desc.sockfd, buf, len, 0, &wsi->udp->sa, wsi->udp->salen);\n#endif\n\t} else\n\t\tn = send(wsi->desc.sockfd, (char *)buf, len, MSG_NOSIGNAL);\n//\tlwsl_info(\"%s: sent len %d result %d\", __func__, len, n);\n\tif (n >= 0)\n\t\treturn n;\n\n\tif (LWS_ERRNO == LWS_EAGAIN ||\n\t    LWS_ERRNO == LWS_EWOULDBLOCK ||\n\t    LWS_ERRNO == LWS_EINTR) {\n\t\tif (LWS_ERRNO == LWS_EWOULDBLOCK) {\n\t\t\tlws_set_blocking_send(wsi);\n\t\t}\n\n\t\treturn LWS_SSL_CAPABLE_MORE_SERVICE;\n\t}\n\n\tlwsl_debug(\"ERROR writing len %d to skt fd %d err %d / errno %d\\n\",\n\t\t\tlen, wsi->desc.sockfd, n, LWS_ERRNO);\n\n\treturn LWS_SSL_CAPABLE_ERROR;\n}\n\nLWS_VISIBLE int\nlws_ssl_pending_no_ssl(struct lws *wsi)\n{\n\t(void)wsi;\n#if defined(LWS_WITH_ESP32)\n\treturn 100;\n#else\n\treturn 0;\n#endif\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/core/pollfd.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n\nint\n_lws_change_pollfd(struct lws *wsi, int _and, int _or, struct lws_pollargs *pa)\n{\n#if !defined(LWS_WITH_LIBUV) && !defined(LWS_WITH_LIBEV) && !defined(LWS_WITH_LIBEVENT)\n\tvolatile struct lws_context_per_thread *vpt;\n#endif\n\tstruct lws_context_per_thread *pt;\n\tstruct lws_context *context;\n\tint ret = 0, pa_events = 1;\n\tstruct lws_pollfd *pfd;\n\tint sampled_tid, tid;\n\n\tif (!wsi)\n\t\treturn 0;\n\n\tassert(wsi->position_in_fds_table == LWS_NO_FDS_POS ||\n\t       wsi->position_in_fds_table >= 0);\n\n\tif (wsi->position_in_fds_table == LWS_NO_FDS_POS)\n\t\treturn 0;\n\n\tif (((volatile struct lws *)wsi)->handling_pollout &&\n\t    !_and && _or == LWS_POLLOUT) {\n\t\t/*\n\t\t * Happening alongside service thread handling POLLOUT.\n\t\t * The danger is when he is finished, he will disable POLLOUT,\n\t\t * countermanding what we changed here.\n\t\t *\n\t\t * Instead of changing the fds, inform the service thread\n\t\t * what happened, and ask it to leave POLLOUT active on exit\n\t\t */\n\t\t((volatile struct lws *)wsi)->leave_pollout_active = 1;\n\t\t/*\n\t\t * by definition service thread is not in poll wait, so no need\n\t\t * to cancel service\n\t\t */\n\n\t\tlwsl_debug(\"%s: using leave_pollout_active\\n\", __func__);\n\n\t\treturn 0;\n\t}\n\n\tcontext = wsi->context;\n\tpt = &context->pt[(int)wsi->tsi];\n\n\tassert(wsi->position_in_fds_table < (int)pt->fds_count);\n\n#if !defined(LWS_WITH_LIBUV) && \\\n    !defined(LWS_WITH_LIBEV) && \\\n    !defined(LWS_WITH_LIBEVENT)\n\t/*\n\t * This only applies when we use the default poll() event loop.\n\t *\n\t * BSD can revert pa->events at any time, when the kernel decides to\n\t * exit from poll().  We can't protect against it using locking.\n\t *\n\t * Therefore we must check first if the service thread is in poll()\n\t * wait; if so, we know we must be being called from a foreign thread,\n\t * and we must keep a strictly ordered list of changes we made instead\n\t * of trying to apply them, since when poll() exits, which may happen\n\t * at any time it would revert our changes.\n\t *\n\t * The plat code will apply them when it leaves the poll() wait\n\t * before doing anything else.\n\t */\n\n\tvpt = (volatile struct lws_context_per_thread *)pt;\n\n\tvpt->foreign_spinlock = 1;\n\tlws_memory_barrier();\n\n\tif (vpt->inside_poll) {\n\t\tstruct lws_foreign_thread_pollfd *ftp, **ftp1;\n\t\t/*\n\t\t * We are certainly a foreign thread trying to change events\n\t\t * while the service thread is in the poll() wait.\n\t\t *\n\t\t * Create a list of changes to be applied after poll() exit,\n\t\t * instead of trying to apply them now.\n\t\t */\n\t\tftp = lws_malloc(sizeof(*ftp), \"ftp\");\n\t\tif (!ftp) {\n\t\t\tvpt->foreign_spinlock = 0;\n\t\t\tlws_memory_barrier();\n\t\t\tret = -1;\n\t\t\tgoto bail;\n\t\t}\n\n\t\tftp->_and = _and;\n\t\tftp->_or = _or;\n\t\tftp->fd_index = wsi->position_in_fds_table;\n\t\tftp->next = NULL;\n\n\t\t/* place at END of list to maintain order */\n\t\tftp1 = (struct lws_foreign_thread_pollfd **)\n\t\t\t\t\t\t&vpt->foreign_pfd_list;\n\t\twhile (*ftp1)\n\t\t\tftp1 = &((*ftp1)->next);\n\n\t\t*ftp1 = ftp;\n\t\tvpt->foreign_spinlock = 0;\n\t\tlws_memory_barrier();\n\t\tlws_cancel_service_pt(wsi);\n\n\t\treturn 0;\n\t}\n\n\tvpt->foreign_spinlock = 0;\n\tlws_memory_barrier();\n#endif\n\n\tpfd = &pt->fds[wsi->position_in_fds_table];\n\tpa->fd = wsi->desc.sockfd;\n\tlwsl_debug(\"%s: wsi %p: fd %d events %d -> %d\\n\", __func__, wsi, pa->fd, pfd->events, (pfd->events & ~_and) | _or);\n\tpa->prev_events = pfd->events;\n\tpa->events = pfd->events = (pfd->events & ~_and) | _or;\n\n\tif (wsi->http2_substream)\n\t\treturn 0;\n\n\tif (wsi->vhost &&\n\t    wsi->vhost->protocols[0].callback(wsi,\n\t\t\t    \t    \t      LWS_CALLBACK_CHANGE_MODE_POLL_FD,\n\t\t\t\t\t      wsi->user_space, (void *)pa, 0)) {\n\t\tret = -1;\n\t\tgoto bail;\n\t}\n\n\tif (context->event_loop_ops->io) {\n\t\tif (_and & LWS_POLLIN)\n\t\t\tcontext->event_loop_ops->io(wsi,\n\t\t\t\t\tLWS_EV_STOP | LWS_EV_READ);\n\n\t\tif (_or & LWS_POLLIN)\n\t\t\tcontext->event_loop_ops->io(wsi,\n\t\t\t\t\tLWS_EV_START | LWS_EV_READ);\n\n\t\tif (_and & LWS_POLLOUT)\n\t\t\tcontext->event_loop_ops->io(wsi,\n\t\t\t\t\tLWS_EV_STOP | LWS_EV_WRITE);\n\n\t\tif (_or & LWS_POLLOUT)\n\t\t\tcontext->event_loop_ops->io(wsi,\n\t\t\t\t\tLWS_EV_START | LWS_EV_WRITE);\n\t}\n\n\t/*\n\t * if we changed something in this pollfd...\n\t *   ... and we're running in a different thread context\n\t *     than the service thread...\n\t *       ... and the service thread is waiting ...\n\t *         then cancel it to force a restart with our changed events\n\t */\n\tpa_events = pa->prev_events != pa->events;\n\n\tif (pa_events) {\n\t\tif (lws_plat_change_pollfd(context, wsi, pfd)) {\n\t\t\tlwsl_info(\"%s failed\\n\", __func__);\n\t\t\tret = -1;\n\t\t\tgoto bail;\n\t\t}\n\t\tsampled_tid = context->service_tid;\n\t\tif (sampled_tid && wsi->vhost) {\n\t\t\ttid = wsi->vhost->protocols[0].callback(wsi,\n\t\t\t\t     LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0);\n\t\t\tif (tid == -1) {\n\t\t\t\tret = -1;\n\t\t\t\tgoto bail;\n\t\t\t}\n\t\t\tif (tid != sampled_tid)\n\t\t\t\tlws_cancel_service_pt(wsi);\n\t\t}\n\t}\n\nbail:\n\treturn ret;\n}\n\n#ifndef LWS_NO_SERVER\n/*\n * Enable or disable listen sockets on this pt globally...\n * it's modulated according to the pt having space for a new accept.\n */\nstatic void\nlws_accept_modulation(struct lws_context *context,\n\t\t      struct lws_context_per_thread *pt, int allow)\n{\n\tstruct lws_vhost *vh = context->vhost_list;\n\tstruct lws_pollargs pa1;\n\n\twhile (vh) {\n\t\tif (vh->lserv_wsi) {\n\t\t\tif (allow)\n\t\t\t\t_lws_change_pollfd(vh->lserv_wsi,\n\t\t\t\t\t   0, LWS_POLLIN, &pa1);\n\t\t\telse\n\t\t\t\t_lws_change_pollfd(vh->lserv_wsi,\n\t\t\t\t\t   LWS_POLLIN, 0, &pa1);\n\t\t}\n\t\tvh = vh->vhost_next;\n\t}\n}\n#endif\n\nint\n__insert_wsi_socket_into_fds(struct lws_context *context, struct lws *wsi)\n{\n\tstruct lws_pollargs pa = { wsi->desc.sockfd, LWS_POLLIN, 0 };\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tint ret = 0;\n\n\n\tlwsl_debug(\"%s: %p: tsi=%d, sock=%d, pos-in-fds=%d\\n\",\n\t\t  __func__, wsi, wsi->tsi, wsi->desc.sockfd, pt->fds_count);\n\n\tif ((unsigned int)pt->fds_count >= context->fd_limit_per_thread) {\n\t\tlwsl_err(\"Too many fds (%d vs %d)\\n\", context->max_fds,\n\t\t\t\tcontext->fd_limit_per_thread\t);\n\t\treturn 1;\n\t}\n\n#if !defined(_WIN32)\n\tif (wsi->desc.sockfd - lws_plat_socket_offset() >= context->max_fds) {\n\t\tlwsl_err(\"Socket fd %d is too high (%d) offset %d\\n\",\n\t\t\t wsi->desc.sockfd, context->max_fds, lws_plat_socket_offset());\n\t\treturn 1;\n\t}\n#endif\n\n\tassert(wsi);\n\tassert(wsi->event_pipe || wsi->vhost);\n\tassert(lws_socket_is_valid(wsi->desc.sockfd));\n\n\tif (wsi->vhost &&\n\t    wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_LOCK_POLL,\n\t\t\t\t\t   wsi->user_space, (void *) &pa, 1))\n\t\treturn -1;\n\n\tpt->count_conns++;\n\tinsert_wsi(context, wsi);\n\twsi->position_in_fds_table = pt->fds_count;\n\n\tpt->fds[wsi->position_in_fds_table].fd = wsi->desc.sockfd;\n\tpt->fds[wsi->position_in_fds_table].events = LWS_POLLIN;\n\tpa.events = pt->fds[pt->fds_count].events;\n\n\tlws_plat_insert_socket_into_fds(context, wsi);\n\n\t/* external POLL support via protocol 0 */\n\tif (wsi->vhost &&\n\t    wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_ADD_POLL_FD,\n\t\t\t\t\t   wsi->user_space, (void *) &pa, 0))\n\t\tret =  -1;\n#ifndef LWS_NO_SERVER\n\t/* if no more room, defeat accepts on this thread */\n\tif ((unsigned int)pt->fds_count == context->fd_limit_per_thread - 1)\n\t\tlws_accept_modulation(context, pt, 0);\n#endif\n\n\tif (wsi->vhost &&\n\t    wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_UNLOCK_POLL,\n\t\t\t\t\t   wsi->user_space, (void *)&pa, 1))\n\t\tret = -1;\n\n\treturn ret;\n}\n\nint\n__remove_wsi_socket_from_fds(struct lws *wsi)\n{\n\tstruct lws_context *context = wsi->context;\n\tstruct lws_pollargs pa = { wsi->desc.sockfd, 0, 0 };\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tstruct lws *end_wsi;\n\tint v;\n\tint m, ret = 0;\n\n\tif (wsi->parent_carries_io) {\n\t\tlws_same_vh_protocol_remove(wsi);\n\t\treturn 0;\n\t}\n\n#if !defined(_WIN32)\n\tif (wsi->desc.sockfd - lws_plat_socket_offset() > context->max_fds) {\n\t\tlwsl_err(\"fd %d too high (%d)\\n\", wsi->desc.sockfd,\n\t\t\t context->max_fds);\n\t\treturn 1;\n\t}\n#endif\n\n\tif (wsi->vhost &&\n\t    wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_LOCK_POLL,\n\t\t\t\t\t   wsi->user_space, (void *)&pa, 1))\n\t\treturn -1;\n\n\tlws_same_vh_protocol_remove(wsi);\n\n\t/* the guy who is to be deleted's slot index in pt->fds */\n\tm = wsi->position_in_fds_table;\n\t\n\t/* these are the only valid possibilities for position_in_fds_table */\n\tassert(m == LWS_NO_FDS_POS || (m >= 0 &&\n\t\t\t\t       (unsigned int)m < pt->fds_count));\n\n\tif (context->event_loop_ops->io)\n\t\tcontext->event_loop_ops->io(wsi,\n\t\t\t\t  LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE |\n\t\t\t\t  LWS_EV_PREPARE_DELETION);\n\n\tlwsl_debug(\"%s: wsi=%p, sock=%d, fds pos=%d, end guy pos=%d, endfd=%d\\n\",\n\t\t  __func__, wsi, wsi->desc.sockfd, wsi->position_in_fds_table,\n\t\t  pt->fds_count, pt->fds[pt->fds_count].fd);\n\n\tif (m != LWS_NO_FDS_POS) {\n\n\t\t/* have the last guy take up the now vacant slot */\n\t\tpt->fds[m] = pt->fds[pt->fds_count - 1];\n\t\t/* this decrements pt->fds_count */\n\t\tlws_plat_delete_socket_from_fds(context, wsi, m);\n\t\tv = (int) pt->fds[m].fd;\n\t\t/* end guy's \"position in fds table\" is now the deletion guy's old one */\n\t\tend_wsi = wsi_from_fd(context, v);\n\t\tif (!end_wsi) {\n\t\t\tlwsl_err(\"no wsi for fd %d at pos %d, pt->fds_count=%d\\n\",\n\t\t\t\t (int)pt->fds[m].fd, m, pt->fds_count);\n\t\t\tassert(0);\n\t\t} else\n\t\t\tend_wsi->position_in_fds_table = m;\n\n\t\t/* deletion guy's lws_lookup entry needs nuking */\n\t\tdelete_from_fd(context, wsi->desc.sockfd);\n\n\t\t/* removed wsi has no position any more */\n\t\twsi->position_in_fds_table = LWS_NO_FDS_POS;\n\t}\n\n\t/* remove also from external POLL support via protocol 0 */\n\tif (lws_socket_is_valid(wsi->desc.sockfd) && wsi->vhost &&\n\t    wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_DEL_POLL_FD,\n\t\t\t\t\t      wsi->user_space, (void *) &pa, 0))\n\t\tret = -1;\n\n#ifndef LWS_NO_SERVER\n\tif (!context->being_destroyed &&\n\t    /* if this made some room, accept connects on this thread */\n\t    (unsigned int)pt->fds_count < context->fd_limit_per_thread - 1)\n\t\tlws_accept_modulation(context, pt, 1);\n#endif\n\n\tif (wsi->vhost &&\n\t    wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_UNLOCK_POLL,\n\t\t\t\t\t      wsi->user_space, (void *) &pa, 1))\n\t\tret = -1;\n\n\treturn ret;\n}\n\nint\n__lws_change_pollfd(struct lws *wsi, int _and, int _or)\n{\n\tstruct lws_context *context;\n\tstruct lws_pollargs pa;\n\tint ret = 0;\n\n\tif (!wsi || (!wsi->protocol && !wsi->event_pipe) ||\n\t    wsi->position_in_fds_table == LWS_NO_FDS_POS)\n\t\treturn 0;\n\n\tcontext = lws_get_context(wsi);\n\tif (!context)\n\t\treturn 1;\n\n\tif (wsi->vhost &&\n\t    wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_LOCK_POLL,\n\t\t\t\t\t      wsi->user_space, (void *) &pa, 0))\n\t\treturn -1;\n\n\tret = _lws_change_pollfd(wsi, _and, _or, &pa);\n\tif (wsi->vhost &&\n\t    wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_UNLOCK_POLL,\n\t\t\t\t\t   wsi->user_space, (void *) &pa, 0))\n\t\tret = -1;\n\n\treturn ret;\n}\n\nint\nlws_change_pollfd(struct lws *wsi, int _and, int _or)\n{\n\tstruct lws_context_per_thread *pt;\n\tint ret = 0;\n\n\tpt = &wsi->context->pt[(int)wsi->tsi];\n\n\tlws_pt_lock(pt, __func__);\n\tret = __lws_change_pollfd(wsi, _and, _or);\n\tlws_pt_unlock(pt);\n\n\treturn ret;\n}\n\nLWS_VISIBLE int\nlws_callback_on_writable(struct lws *wsi)\n{\n\tstruct lws_context_per_thread *pt;\n\tint n;\n\n\tif (lwsi_state(wsi) == LRS_SHUTDOWN)\n\t\treturn 0;\n\n\tif (wsi->socket_is_permanently_unusable)\n\t\treturn 0;\n\n\tpt = &wsi->context->pt[(int)wsi->tsi];\n\n\tif (wsi->parent_carries_io) {\n#if defined(LWS_WITH_STATS)\n\t\tif (!wsi->active_writable_req_us) {\n\t\t\twsi->active_writable_req_us = time_in_microseconds();\n\t\t\tlws_stats_atomic_bump(wsi->context, pt,\n\t\t\t\t\t      LWSSTATS_C_WRITEABLE_CB_EFF_REQ, 1);\n\t\t}\n#endif\n\t\tn = lws_callback_on_writable(wsi->parent);\n\t\tif (n < 0)\n\t\t\treturn n;\n\n\t\twsi->parent_pending_cb_on_writable = 1;\n\t\treturn 1;\n\t}\n\n\tlws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITEABLE_CB_REQ, 1);\n#if defined(LWS_WITH_STATS)\n\tif (!wsi->active_writable_req_us) {\n\t\twsi->active_writable_req_us = time_in_microseconds();\n\t\tlws_stats_atomic_bump(wsi->context, pt,\n\t\t\t\t      LWSSTATS_C_WRITEABLE_CB_EFF_REQ, 1);\n\t}\n#endif\n\n\n\tif (wsi->role_ops->callback_on_writable) {\n\t\tif (wsi->role_ops->callback_on_writable(wsi))\n\t\t\treturn 1;\n\t\twsi = lws_get_network_wsi(wsi);\n\t}\n\n\tif (wsi->position_in_fds_table == LWS_NO_FDS_POS) {\n\t\tlwsl_debug(\"%s: failed to find socket %d\\n\", __func__,\n\t\t\t   wsi->desc.sockfd);\n\t\treturn -1;\n\t}\n\n\tif (__lws_change_pollfd(wsi, 0, LWS_POLLOUT))\n\t\treturn -1;\n\n\treturn 1;\n}\n\n\n/*\n * stitch protocol choice into the vh protocol linked list\n * We always insert ourselves at the start of the list\n *\n * X <-> B\n * X <-> pAn <-> pB\n *\n * Illegal to attach more than once without detach inbetween\n */\nvoid\nlws_same_vh_protocol_insert(struct lws *wsi, int n)\n{\n\tif (wsi->same_vh_protocol_prev || wsi->same_vh_protocol_next) {\n\t\tlws_same_vh_protocol_remove(wsi);\n\t\tlwsl_notice(\"Attempted to attach wsi twice to same vh prot\\n\");\n\t}\n\n\tlws_vhost_lock(wsi->vhost);\n\n\twsi->same_vh_protocol_prev = &wsi->vhost->same_vh_protocol_list[n];\n\t/* old first guy is our next */\n\twsi->same_vh_protocol_next =  wsi->vhost->same_vh_protocol_list[n];\n\t/* we become the new first guy */\n\twsi->vhost->same_vh_protocol_list[n] = wsi;\n\n\tif (wsi->same_vh_protocol_next)\n\t\t/* old first guy points back to us now */\n\t\twsi->same_vh_protocol_next->same_vh_protocol_prev =\n\t\t\t\t&wsi->same_vh_protocol_next;\n\n\twsi->on_same_vh_list = 1;\n\n\tlws_vhost_unlock(wsi->vhost);\n}\n\nvoid\nlws_same_vh_protocol_remove(struct lws *wsi)\n{\n\t/*\n\t * detach ourselves from vh protocol list if we're on one\n\t * A -> B -> C\n\t * A -> C , or, B -> C, or A -> B\n\t *\n\t * OK to call on already-detached wsi\n\t */\n\tlwsl_info(\"%s: removing same prot wsi %p\\n\", __func__, wsi);\n\n\tif (!wsi->vhost || !wsi->on_same_vh_list)\n\t\treturn;\n\n\tlws_vhost_lock(wsi->vhost);\n\n\tif (wsi->same_vh_protocol_prev) {\n\t\tassert (*(wsi->same_vh_protocol_prev) == wsi);\n\t\tlwsl_info(\"have prev %p, setting him to our next %p\\n\",\n\t\t\t wsi->same_vh_protocol_prev,\n\t\t\t wsi->same_vh_protocol_next);\n\n\t\t/* guy who pointed to us should point to our next */\n\t\t*(wsi->same_vh_protocol_prev) = wsi->same_vh_protocol_next;\n\t}\n\n\t/* our next should point back to our prev */\n\tif (wsi->same_vh_protocol_next)\n\t\twsi->same_vh_protocol_next->same_vh_protocol_prev =\n\t\t\t\twsi->same_vh_protocol_prev;\n\n\twsi->same_vh_protocol_prev = NULL;\n\twsi->same_vh_protocol_next = NULL;\n\twsi->on_same_vh_list = 0;\n\n\tlws_vhost_unlock(wsi->vhost);\n}\n\n\nLWS_VISIBLE int\nlws_callback_on_writable_all_protocol_vhost(const struct lws_vhost *vhost,\n\t\t\t\t      const struct lws_protocols *protocol)\n{\n\tstruct lws *wsi;\n\n\tif (protocol < vhost->protocols ||\n\t    protocol >= (vhost->protocols + vhost->count_protocols)) {\n\t\tlwsl_err(\"%s: protocol %p is not from vhost %p (%p - %p)\\n\",\n\t\t\t__func__, protocol, vhost->protocols, vhost,\n\t\t\t(vhost->protocols + vhost->count_protocols));\n\n\t\treturn -1;\n\t}\n\n\twsi = vhost->same_vh_protocol_list[protocol - vhost->protocols];\n\twhile (wsi) {\n\t\tassert(wsi->protocol == protocol);\n\t\tassert(*wsi->same_vh_protocol_prev == wsi);\n\t\tif (wsi->same_vh_protocol_next)\n\t\t\tassert(wsi->same_vh_protocol_next->\n\t\t\t\t\tsame_vh_protocol_prev ==\n\t\t\t\t\t&wsi->same_vh_protocol_next);\n\n\t\tlws_callback_on_writable(wsi);\n\t\twsi = wsi->same_vh_protocol_next;\n\t}\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\nlws_callback_on_writable_all_protocol(const struct lws_context *context,\n\t\t\t\t      const struct lws_protocols *protocol)\n{\n\tstruct lws_vhost *vhost;\n\tint n;\n\n\tif (!context)\n\t\treturn 0;\n\n\tvhost = context->vhost_list;\n\n\twhile (vhost) {\n\t\tfor (n = 0; n < vhost->count_protocols; n++)\n\t\t\tif (protocol->callback ==\n\t\t\t    vhost->protocols[n].callback &&\n\t\t\t    !strcmp(protocol->name, vhost->protocols[n].name))\n\t\t\t\tbreak;\n\t\tif (n != vhost->count_protocols)\n\t\t\tlws_callback_on_writable_all_protocol_vhost(\n\t\t\t\tvhost, &vhost->protocols[n]);\n\n\t\tvhost = vhost->vhost_next;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/core/private.h",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"lws_config.h\"\n#include \"lws_config_private.h\"\n\n#if defined(LWS_WITH_CGI) && defined(LWS_HAVE_VFORK)\n #define  _GNU_SOURCE\n#endif\n\n#if defined(__COVERITY__) && !defined(LWS_COVERITY_WORKAROUND)\n #define LWS_COVERITY_WORKAROUND\n typedef float _Float32;\n typedef float _Float64;\n typedef float _Float128;\n typedef float _Float32x;\n typedef float _Float64x;\n typedef float _Float128x;\n#endif\n\n#ifdef LWS_HAVE_SYS_TYPES_H\n #include <sys/types.h>\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <ctype.h>\n#include <limits.h>\n#include <stdarg.h>\n#include <inttypes.h>\n\n#if defined(LWS_WITH_ESP32)\n #define MSG_NOSIGNAL 0\n #define SOMAXCONN 3\n#endif\n\n#define STORE_IN_ROM\n#include <assert.h>\n#if LWS_MAX_SMP > 1\n #include <pthread.h>\n#endif\n\n#ifdef LWS_HAVE_SYS_STAT_H\n #include <sys/stat.h>\n#endif\n\n#if defined(WIN32) || defined(_WIN32)\n\n #ifndef WIN32_LEAN_AND_MEAN\n  #define WIN32_LEAN_AND_MEAN\n #endif\n\n #if (WINVER < 0x0501)\n  #undef WINVER\n  #undef _WIN32_WINNT\n  #define WINVER 0x0501\n  #define _WIN32_WINNT WINVER\n #endif\n\n #define LWS_NO_DAEMONIZE\n #define LWS_ERRNO WSAGetLastError()\n #define LWS_EAGAIN WSAEWOULDBLOCK\n #define LWS_EALREADY WSAEALREADY\n #define LWS_EINPROGRESS WSAEINPROGRESS\n #define LWS_EINTR WSAEINTR\n #define LWS_EISCONN WSAEISCONN\n #define LWS_EWOULDBLOCK WSAEWOULDBLOCK\n #define MSG_NOSIGNAL 0\n #define SHUT_RDWR SD_BOTH\n #define SOL_TCP IPPROTO_TCP\n #define SHUT_WR SD_SEND\n\n #define compatible_close(fd) closesocket(fd)\n #define lws_set_blocking_send(wsi) wsi->sock_send_blocking = 1\n #define LWS_SOCK_INVALID (INVALID_SOCKET)\n\n #include <winsock2.h>\n #include <ws2tcpip.h>\n #include <windows.h>\n #include <tchar.h>\n #ifdef LWS_HAVE_IN6ADDR_H\n  #include <in6addr.h>\n #endif\n #include <mstcpip.h>\n #include <io.h>\n\n #if !defined(LWS_HAVE_ATOLL)\n  #if defined(LWS_HAVE__ATOI64)\n   #define atoll _atoi64\n  #else\n   #warning No atoll or _atoi64 available, using atoi\n   #define atoll atoi\n  #endif\n #endif\n\n #ifndef __func__\n  #define __func__ __FUNCTION__\n #endif\n\n #ifdef LWS_HAVE__VSNPRINTF\n  #define vsnprintf _vsnprintf\n #endif\n\n /* we don't have an implementation for this on windows... */\n int kill(int pid, int sig);\n int fork(void);\n #ifndef SIGINT\n  #define SIGINT 2\n #endif\n\n#else /* not windows --> */\n\n #include <fcntl.h>\n #include <strings.h>\n #include <unistd.h>\n #include <sys/types.h>\n\n #ifndef __cplusplus\n  #include <errno.h>\n #endif\n #include <netdb.h>\n #include <signal.h>\n #include <sys/socket.h>\n\n #if defined(LWS_BUILTIN_GETIFADDRS)\n  #include \"./misc/getifaddrs.h\"\n #else\n  #if !defined(LWS_WITH_ESP32)\n   #if defined(__HAIKU__)\n    #define _BSD_SOURCE\n   #endif\n   #include <ifaddrs.h>\n  #endif\n #endif\n #if defined (__ANDROID__)\n  #include <syslog.h>\n  #include <sys/resource.h>\n #elif defined (__sun) || defined(__HAIKU__) || defined(__QNX__)\n  #include <syslog.h>\n #else\n  #if !defined(LWS_WITH_ESP32)\n   #include <sys/syslog.h>\n  #endif\n #endif\n #include <netdb.h>\n #if !defined(LWS_WITH_ESP32)\n  #include <sys/mman.h>\n  #include <sys/un.h>\n  #include <netinet/in.h>\n  #include <netinet/tcp.h>\n  #include <arpa/inet.h>\n  #include <poll.h>\n #endif\n #ifndef LWS_NO_FORK\n  #ifdef LWS_HAVE_SYS_PRCTL_H\n   #include <sys/prctl.h>\n  #endif\n #endif\n\n #include <sys/time.h>\n\n #define LWS_ERRNO errno\n #define LWS_EAGAIN EAGAIN\n #define LWS_EALREADY EALREADY\n #define LWS_EINPROGRESS EINPROGRESS\n #define LWS_EINTR EINTR\n #define LWS_EISCONN EISCONN\n #define LWS_EWOULDBLOCK EWOULDBLOCK\n\n #define lws_set_blocking_send(wsi)\n\n #define LWS_SOCK_INVALID (-1)\n#endif /* not windows */\n\n#ifndef LWS_HAVE_BZERO\n #ifndef bzero\n  #define bzero(b, len) (memset((b), '\\0', (len)), (void) 0)\n #endif\n#endif\n\n#ifndef LWS_HAVE_STRERROR\n #define strerror(x) \"\"\n#endif\n\n\n#define lws_socket_is_valid(x) (x != LWS_SOCK_INVALID)\n\n#include \"libwebsockets.h\"\n\n#include \"tls/private.h\"\n\n#if defined(WIN32) || defined(_WIN32)\n #include <gettimeofday.h>\n\n #ifndef BIG_ENDIAN\n  #define BIG_ENDIAN    4321  /* to show byte order (taken from gcc) */\n #endif\n #ifndef LITTLE_ENDIAN\n  #define LITTLE_ENDIAN 1234\n #endif\n #ifndef BYTE_ORDER\n  #define BYTE_ORDER LITTLE_ENDIAN\n #endif\n\n #undef __P\n #ifndef __P\n  #if __STDC__\n   #define __P(protos) protos\n  #else\n   #define __P(protos) ()\n  #endif\n #endif\n\n#else /* not windows */\n static LWS_INLINE int compatible_close(int fd) { return close(fd); }\n\n #include <sys/stat.h>\n #include <sys/time.h>\n\n #if defined(__APPLE__)\n  #include <machine/endian.h>\n #elif defined(__FreeBSD__)\n  #include <sys/endian.h>\n #elif defined(__linux__)\n  #include <endian.h>\n #endif\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if defined(__QNX__)\n\t#include <gulliver.h>\n\t#if defined(__LITTLEENDIAN__)\n\t\t#define BYTE_ORDER __LITTLEENDIAN__\n\t\t#define LITTLE_ENDIAN __LITTLEENDIAN__\n\t\t#define BIG_ENDIAN 4321  /* to show byte order (taken from gcc); for suppres warning that BIG_ENDIAN is not defined. */\n\t#endif\n\t#if defined(__BIGENDIAN__)\n\t\t#define BYTE_ORDER __BIGENDIAN__\n\t\t#define LITTLE_ENDIAN 1234  /* to show byte order (taken from gcc); for suppres warning that LITTLE_ENDIAN is not defined. */\n\t\t#define BIG_ENDIAN __BIGENDIAN__\n\t#endif\n#endif\n\n#if defined(__sun) && defined(__GNUC__)\n\n #include <arpa/nameser_compat.h>\n\n #if !defined (BYTE_ORDER)\n  #define BYTE_ORDER __BYTE_ORDER__\n #endif\n\n #if !defined(LITTLE_ENDIAN)\n  #define LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__\n #endif\n\n #if !defined(BIG_ENDIAN)\n  #define BIG_ENDIAN __ORDER_BIG_ENDIAN__\n #endif\n\n#endif /* sun + GNUC */\n\n#if !defined(BYTE_ORDER)\n #define BYTE_ORDER __BYTE_ORDER\n#endif\n#if !defined(LITTLE_ENDIAN)\n #define LITTLE_ENDIAN __LITTLE_ENDIAN\n#endif\n#if !defined(BIG_ENDIAN)\n #define BIG_ENDIAN __BIG_ENDIAN\n#endif\n\n\n/*\n * Mac OSX as well as iOS do not define the MSG_NOSIGNAL flag,\n * but happily have something equivalent in the SO_NOSIGPIPE flag.\n */\n#ifdef __APPLE__\n#define MSG_NOSIGNAL SO_NOSIGPIPE\n#endif\n\n/*\n * Solaris 11.X only supports POSIX 2001, MSG_NOSIGNAL appears in\n * POSIX 2008.\n */\n#ifdef __sun\n #define MSG_NOSIGNAL 0\n#endif\n\n#ifdef _WIN32\n #ifndef FD_HASHTABLE_MODULUS\n  #define FD_HASHTABLE_MODULUS 32\n #endif\n#endif\n\n#ifndef LWS_DEF_HEADER_LEN\n#define LWS_DEF_HEADER_LEN 4096\n#endif\n#ifndef LWS_DEF_HEADER_POOL\n#define LWS_DEF_HEADER_POOL 4\n#endif\n#ifndef LWS_MAX_PROTOCOLS\n#define LWS_MAX_PROTOCOLS 5\n#endif\n#ifndef LWS_MAX_EXTENSIONS_ACTIVE\n#define LWS_MAX_EXTENSIONS_ACTIVE 1\n#endif\n#ifndef LWS_MAX_EXT_OFFERS\n#define LWS_MAX_EXT_OFFERS 8\n#endif\n#ifndef SPEC_LATEST_SUPPORTED\n#define SPEC_LATEST_SUPPORTED 13\n#endif\n#ifndef AWAITING_TIMEOUT\n#define AWAITING_TIMEOUT 20\n#endif\n#ifndef CIPHERS_LIST_STRING\n#define CIPHERS_LIST_STRING \"DEFAULT\"\n#endif\n#ifndef LWS_SOMAXCONN\n#define LWS_SOMAXCONN SOMAXCONN\n#endif\n\n#define MAX_WEBSOCKET_04_KEY_LEN 128\n\n#ifndef SYSTEM_RANDOM_FILEPATH\n#define SYSTEM_RANDOM_FILEPATH \"/dev/urandom\"\n#endif\n\n#define LWS_H2_RX_SCRATCH_SIZE 512\n\n#if defined(WIN32) || defined(_WIN32)\n\t // Visual studio older than 2015 and WIN_CE has only _stricmp\n\t#if (defined(_MSC_VER) && _MSC_VER < 1900) || defined(_WIN32_WCE)\n\t#define strcasecmp _stricmp\n\t#elif !defined(__MINGW32__)\n\t#define strcasecmp stricmp\n\t#endif\n\t#define getdtablesize() 30000\n#endif\n\n/*\n * All lws_tls...() functions must return this type, converting the\n * native backend result and doing the extra work to determine which one\n * as needed.\n *\n * Native TLS backend return codes are NOT ALLOWED outside the backend.\n *\n * Non-SSL mode also uses these types.\n */\nenum lws_ssl_capable_status {\n\tLWS_SSL_CAPABLE_ERROR = -1,\t\t /* it failed */\n\tLWS_SSL_CAPABLE_DONE = 0,\t\t /* it succeeded */\n\tLWS_SSL_CAPABLE_MORE_SERVICE_READ = -2,\t /* retry WANT_READ */\n\tLWS_SSL_CAPABLE_MORE_SERVICE_WRITE = -3,  /* retry WANT_WRITE */\n\tLWS_SSL_CAPABLE_MORE_SERVICE = -4,\t /* general retry */\n};\n\n#if defined(__clang__)\n#define lws_memory_barrier() __sync_synchronize()\n#elif defined(__GNUC__)\n#define lws_memory_barrier() __sync_synchronize()\n#else\n#define lws_memory_barrier()\n#endif\n\n/*\n *\n *  ------ roles ------\n *\n */\n\n#include \"roles/private.h\"\n\n/* null-terminated array of pointers to roles lws built with */\nextern const struct lws_role_ops *available_roles[];\n\n#define LWS_FOR_EVERY_AVAILABLE_ROLE_START(xx) { \\\n\t\tconst struct lws_role_ops **ppxx = available_roles; \\\n\t\twhile (*ppxx) { \\\n\t\t\tconst struct lws_role_ops *xx = *ppxx++;\n\n#define LWS_FOR_EVERY_AVAILABLE_ROLE_END }}\n\n/*\n *\n *  ------ event_loop ops ------\n *\n */\n\n#include \"event-libs/private.h\"\n\n/* enums of socks version */\nenum socks_version {\n\tSOCKS_VERSION_4 = 4,\n\tSOCKS_VERSION_5 = 5\n};\n\n/* enums of subnegotiation version */\nenum socks_subnegotiation_version {\n\tSOCKS_SUBNEGOTIATION_VERSION_1 = 1,\n};\n\n/* enums of socks commands */\nenum socks_command {\n\tSOCKS_COMMAND_CONNECT = 1,\n\tSOCKS_COMMAND_BIND = 2,\n\tSOCKS_COMMAND_UDP_ASSOCIATE = 3\n};\n\n/* enums of socks address type */\nenum socks_atyp {\n\tSOCKS_ATYP_IPV4 = 1,\n\tSOCKS_ATYP_DOMAINNAME = 3,\n\tSOCKS_ATYP_IPV6 = 4\n};\n\n/* enums of socks authentication methods */\nenum socks_auth_method {\n\tSOCKS_AUTH_NO_AUTH = 0,\n\tSOCKS_AUTH_GSSAPI = 1,\n\tSOCKS_AUTH_USERNAME_PASSWORD = 2\n};\n\n/* enums of subnegotiation status */\nenum socks_subnegotiation_status {\n\tSOCKS_SUBNEGOTIATION_STATUS_SUCCESS = 0,\n};\n\n/* enums of socks request reply */\nenum socks_request_reply {\n\tSOCKS_REQUEST_REPLY_SUCCESS = 0,\n\tSOCKS_REQUEST_REPLY_FAILURE_GENERAL = 1,\n\tSOCKS_REQUEST_REPLY_CONNECTION_NOT_ALLOWED = 2,\n\tSOCKS_REQUEST_REPLY_NETWORK_UNREACHABLE = 3,\n\tSOCKS_REQUEST_REPLY_HOST_UNREACHABLE = 4,\n\tSOCKS_REQUEST_REPLY_CONNECTION_REFUSED = 5,\n\tSOCKS_REQUEST_REPLY_TTL_EXPIRED = 6,\n\tSOCKS_REQUEST_REPLY_COMMAND_NOT_SUPPORTED = 7,\n\tSOCKS_REQUEST_REPLY_ATYP_NOT_SUPPORTED = 8\n};\n\n/* enums used to generate socks messages */\nenum socks_msg_type {\n\t/* greeting */\n\tSOCKS_MSG_GREETING,\n\t/* credential, user name and password */\n\tSOCKS_MSG_USERNAME_PASSWORD,\n\t/* connect command */\n\tSOCKS_MSG_CONNECT\n};\n\nenum {\n\tLWS_RXFLOW_ALLOW = (1 << 0),\n\tLWS_RXFLOW_PENDING_CHANGE = (1 << 1),\n};\n\nstruct lws_ring {\n\tvoid *buf;\n\tvoid (*destroy_element)(void *element);\n\tuint32_t buflen;\n\tuint32_t element_len;\n\tuint32_t head;\n\tuint32_t oldest_tail;\n};\n\nstruct lws_protocols;\nstruct lws;\n\nstruct lws_io_watcher {\n#ifdef LWS_WITH_LIBEV\n\tstruct lws_io_watcher_libev ev;\n#endif\n#ifdef LWS_WITH_LIBUV\n\tstruct lws_io_watcher_libuv uv;\n#endif\n#ifdef LWS_WITH_LIBEVENT\n\tstruct lws_io_watcher_libevent event;\n#endif\n\tstruct lws_context *context;\n\n\tuint8_t actual_events;\n};\n\nstruct lws_signal_watcher {\n#ifdef LWS_WITH_LIBEV\n\tstruct lws_signal_watcher_libev ev;\n#endif\n#ifdef LWS_WITH_LIBUV\n\tstruct lws_signal_watcher_libuv uv;\n#endif\n#ifdef LWS_WITH_LIBEVENT\n\tstruct lws_signal_watcher_libevent event;\n#endif\n\tstruct lws_context *context;\n};\n\n#ifdef _WIN32\n#define LWS_FD_HASH(fd) ((fd ^ (fd >> 8) ^ (fd >> 16)) % FD_HASHTABLE_MODULUS)\nstruct lws_fd_hashtable {\n\tstruct lws **wsi;\n\tint length;\n};\n#endif\n\nstruct lws_foreign_thread_pollfd {\n\tstruct lws_foreign_thread_pollfd *next;\n\tint fd_index;\n\tint _and;\n\tint _or;\n};\n\n\n#define LWS_HRTIMER_NOWAIT (0x7fffffffffffffffll)\n\n/*\n * so we can have n connections being serviced simultaneously,\n * these things need to be isolated per-thread.\n */\n\nstruct lws_context_per_thread {\n#if LWS_MAX_SMP > 1\n\tpthread_mutex_t lock;\n\tpthread_mutex_t lock_stats;\n\tpthread_t lock_owner;\n\tconst char *last_lock_reason;\n#endif\n\n\tstruct lws_context *context;\n\n\t/*\n\t * usable by anything in the service code, but only if the scope\n\t * does not last longer than the service action (since next service\n\t * of any socket can likewise use it and overwrite)\n\t */\n\tunsigned char *serv_buf;\n\n\tstruct lws_dll_lws dll_head_timeout;\n\tstruct lws_dll_lws dll_head_hrtimer;\n\tstruct lws_dll_lws dll_head_buflist; /* guys with pending rxflow */\n\n#if defined(LWS_WITH_TLS)\n\tstruct lws_pt_tls tls;\n#endif\n\n\tstruct lws_pollfd *fds;\n\tvolatile struct lws_foreign_thread_pollfd * volatile foreign_pfd_list;\n#ifdef _WIN32\n\tWSAEVENT *events;\n#endif\n\tlws_sockfd_type dummy_pipe_fds[2];\n\tstruct lws *pipe_wsi;\n\n\t/* --- role based members --- */\n\n#if defined(LWS_ROLE_WS) && !defined(LWS_WITHOUT_EXTENSIONS)\n\tstruct lws_pt_role_ws ws;\n#endif\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tstruct lws_pt_role_http http;\n#endif\n\n\t/* --- event library based members --- */\n\n#if defined(LWS_WITH_LIBEV)\n\tstruct lws_pt_eventlibs_libev ev;\n#endif\n#if defined(LWS_WITH_LIBUV)\n\tstruct lws_pt_eventlibs_libuv uv;\n#endif\n#if defined(LWS_WITH_LIBEVENT)\n\tstruct lws_pt_eventlibs_libevent event;\n#endif\n\n#if defined(LWS_WITH_LIBEV) || defined(LWS_WITH_LIBUV) || defined(LWS_WITH_LIBEVENT)\n\tstruct lws_signal_watcher w_sigint;\n#endif\n\n\t/* --- */\n\n\tunsigned long count_conns;\n\tunsigned int fds_count;\n\n\tvolatile unsigned char inside_poll;\n\tvolatile unsigned char foreign_spinlock;\n\n\tunsigned char tid;\n\n\tunsigned char lock_depth;\n\tunsigned char inside_service:1;\n\tunsigned char event_loop_foreign:1;\n\tunsigned char event_loop_destroy_processing_done:1;\n};\n\nstruct lws_conn_stats {\n\tunsigned long long rx, tx;\n\tunsigned long h1_conn, h1_trans, h2_trans, ws_upg, h2_alpn, h2_subs,\n\t\t      h2_upg, rejected;\n};\n\nvoid\nlws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs);\n\nstruct lws_timed_vh_protocol {\n\tstruct lws_timed_vh_protocol *next;\n\tconst struct lws_protocols *protocol;\n\ttime_t time;\n\tint reason;\n};\n\n/*\n * virtual host -related context information\n *   vhostwide SSL context\n *   vhostwide proxy\n *\n * hierarchy:\n *\n * context -> vhost -> wsi\n *\n * incoming connection non-SSL vhost binding:\n *\n *    listen socket -> wsi -> select vhost after first headers\n *\n * incoming connection SSL vhost binding:\n *\n *    SSL SNI -> wsi -> bind after SSL negotiation\n */\n\n\nstruct lws_vhost {\n#if !defined(LWS_WITHOUT_CLIENT)\n\tchar proxy_basic_auth_token[128];\n#endif\n#if LWS_MAX_SMP > 1\n\tpthread_mutex_t lock;\n#endif\n\n#if defined(LWS_ROLE_H2)\n\tstruct lws_vhost_role_h2 h2;\n#endif\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tstruct lws_vhost_role_http http;\n#endif\n#if defined(LWS_ROLE_WS) && !defined(LWS_WITHOUT_EXTENSIONS)\n\tstruct lws_vhost_role_ws ws;\n#endif\n\n#if defined(LWS_WITH_SOCKS5)\n\tchar socks_proxy_address[128];\n\tchar socks_user[96];\n\tchar socks_password[96];\n#endif\n#if defined(LWS_WITH_LIBEV)\n\tstruct lws_io_watcher w_accept;\n#endif\n\tstruct lws_conn_stats conn_stats;\n\tstruct lws_context *context;\n\tstruct lws_vhost *vhost_next;\n\n\tstruct lws *lserv_wsi;\n\tconst char *name;\n\tconst char *iface;\n\n#if !defined(LWS_WITH_ESP32) && !defined(OPTEE_TA) && !defined(WIN32)\n\tint bind_iface;\n#endif\n\tconst struct lws_protocols *protocols;\n\tvoid **protocol_vh_privs;\n\tconst struct lws_protocol_vhost_options *pvo;\n\tconst struct lws_protocol_vhost_options *headers;\n\tstruct lws **same_vh_protocol_list;\n\tstruct lws_vhost *no_listener_vhost_list;\n#if !defined(LWS_NO_CLIENT)\n\tstruct lws_dll_lws dll_active_client_conns;\n#endif\n\n#if defined(LWS_WITH_TLS)\n\tstruct lws_vhost_tls tls;\n#endif\n\n\tstruct lws_timed_vh_protocol *timed_vh_protocol_list;\n\tvoid *user;\n\n\tint listen_port;\n\n#if defined(LWS_WITH_SOCKS5)\n\tunsigned int socks_proxy_port;\n#endif\n\tunsigned int options;\n\tint count_protocols;\n\tint ka_time;\n\tint ka_probes;\n\tint ka_interval;\n\tint keepalive_timeout;\n\tint timeout_secs_ah_idle;\n\n#ifdef LWS_WITH_ACCESS_LOG\n\tint log_fd;\n#endif\n\n\tunsigned int created_vhost_protocols:1;\n\tunsigned int being_destroyed:1;\n\n\tunsigned char default_protocol_index;\n\tunsigned char raw_protocol_index;\n};\n\nstruct lws_deferred_free\n{\n\tstruct lws_deferred_free *next;\n\ttime_t deadline;\n\tvoid *payload;\n};\n\ntypedef union {\n#ifdef LWS_WITH_IPV6\n\tstruct sockaddr_in6 sa6;\n#endif\n\tstruct sockaddr_in sa4;\n} sockaddr46;\n\n\n#if defined(LWS_WITH_PEER_LIMITS)\nstruct lws_peer {\n\tstruct lws_peer *next;\n\tstruct lws_peer *peer_wait_list;\n\n\ttime_t time_created;\n\ttime_t time_closed_all;\n\n\tuint8_t addr[32];\n\tuint32_t hash;\n\tuint32_t count_wsi;\n\tuint32_t total_wsi;\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tstruct lws_peer_role_http http;\n#endif\n\n\tuint8_t af;\n};\n#endif\n\n/*\n * the rest is managed per-context, that includes\n *\n *  - processwide single fd -> wsi lookup\n *  - contextwide headers pool\n */\n\nstruct lws_context {\n\ttime_t last_timeout_check_s;\n\ttime_t last_ws_ping_pong_check_s;\n\ttime_t time_up;\n\ttime_t time_discontiguity;\n\ttime_t time_fixup;\n\tconst struct lws_plat_file_ops *fops;\n\tstruct lws_plat_file_ops fops_platform;\n\tstruct lws_context **pcontext_finalize;\n\n\tconst struct lws_tls_ops *tls_ops;\n\n#if defined(LWS_WITH_HTTP2)\n\tstruct http2_settings set;\n#endif\n#if defined(LWS_WITH_ZIP_FOPS)\n\tstruct lws_plat_file_ops fops_zip;\n#endif\n\tstruct lws_context_per_thread pt[LWS_MAX_SMP];\n\tstruct lws_conn_stats conn_stats;\n#if LWS_MAX_SMP > 1\n\tpthread_mutex_t lock;\n\tint lock_depth;\n#endif\n#ifdef _WIN32\n/* different implementation between unix and windows */\n\tstruct lws_fd_hashtable fd_hashtable[FD_HASHTABLE_MODULUS];\n#else\n\tstruct lws **lws_lookup;  /* fd to wsi */\n#endif\n\tstruct lws_vhost *vhost_list;\n\tstruct lws_vhost *no_listener_vhost_list;\n\tstruct lws_vhost *vhost_pending_destruction_list;\n\tstruct lws_plugin *plugin_list;\n\tstruct lws_deferred_free *deferred_free_list;\n#if defined(LWS_WITH_PEER_LIMITS)\n\tstruct lws_peer **pl_hash_table;\n\tstruct lws_peer *peer_wait_list;\n\ttime_t next_cull;\n#endif\n\n\tvoid *external_baggage_free_on_destroy;\n\tconst struct lws_token_limits *token_limits;\n\tvoid *user_space;\n\tconst struct lws_protocol_vhost_options *reject_service_keywords;\n\tlws_reload_func deprecation_cb;\n\tvoid (*eventlib_signal_cb)(void *event_lib_handle, int signum);\n\n#if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)\n\tcap_value_t caps[4];\n\tchar count_caps;\n#endif\n\n#if defined(LWS_WITH_LIBEV)\n\tstruct lws_context_eventlibs_libev ev;\n#endif\n#if defined(LWS_WITH_LIBUV)\n\tstruct lws_context_eventlibs_libuv uv;\n#endif\n#if defined(LWS_WITH_LIBEVENT)\n\tstruct lws_context_eventlibs_libevent event;\n#endif\n\tstruct lws_event_loop_ops *event_loop_ops;\n\n\n#if defined(LWS_WITH_TLS)\n\tstruct lws_context_tls tls;\n#endif\n\n\tchar canonical_hostname[128];\n\tconst char *server_string;\n\n#ifdef LWS_LATENCY\n\tunsigned long worst_latency;\n\tchar worst_latency_info[256];\n#endif\n\n#if defined(LWS_WITH_STATS)\n\tuint64_t lws_stats[LWSSTATS_SIZE];\n\tuint64_t last_dump;\n\tint updated;\n#endif\n#if defined(LWS_WITH_ESP32)\n\tunsigned long time_last_state_dump;\n\tuint32_t last_free_heap;\n#endif\n\n\tint max_fds;\n\tint count_event_loop_static_asset_handles;\n\tint started_with_parent;\n\tint uid, gid;\n\n\tint fd_random;\n\n\tint count_wsi_allocated;\n\tint count_cgi_spawned;\n\tunsigned int options;\n\tunsigned int fd_limit_per_thread;\n\tunsigned int timeout_secs;\n\tunsigned int pt_serv_buf_size;\n\tint max_http_header_data;\n\tint max_http_header_pool;\n\tint simultaneous_ssl_restriction;\n\tint simultaneous_ssl;\n#if defined(LWS_WITH_PEER_LIMITS)\n\tuint32_t pl_hash_elements;\t/* protected by context->lock */\n\tuint32_t count_peers;\t\t/* protected by context->lock */\n\tunsigned short ip_limit_ah;\n\tunsigned short ip_limit_wsi;\n#endif\n\tunsigned int deprecated:1;\n\tunsigned int being_destroyed:1;\n\tunsigned int being_destroyed1:1;\n\tunsigned int being_destroyed2:1;\n\tunsigned int requested_kill:1;\n\tunsigned int protocol_init_done:1;\n\tunsigned int doing_protocol_init:1;\n\tunsigned int done_protocol_destroy_cb:1;\n\tunsigned int finalize_destroy_after_internal_loops_stopped:1;\n\t/*\n\t * set to the Thread ID that's doing the service loop just before entry\n\t * to poll indicates service thread likely idling in poll()\n\t * volatile because other threads may check it as part of processing\n\t * for pollfd event change.\n\t */\n\tvolatile int service_tid;\n\tint service_tid_detected;\n\n\tshort count_threads;\n\tshort plugin_protocol_count;\n\tshort plugin_extension_count;\n\tshort server_string_len;\n\tunsigned short ws_ping_pong_interval;\n\tunsigned short deprecation_pending_listen_close_count;\n\n\tuint8_t max_fi;\n};\n\nint\nlws_check_deferred_free(struct lws_context *context, int force);\n\n#define lws_get_context_protocol(ctx, x) ctx->vhost_list->protocols[x]\n#define lws_get_vh_protocol(vh, x) vh->protocols[x]\n\nLWS_EXTERN void\n__lws_close_free_wsi_final(struct lws *wsi);\nLWS_EXTERN void\nlws_libuv_closehandle(struct lws *wsi);\nLWS_EXTERN int\nlws_libuv_check_watcher_active(struct lws *wsi);\n\nLWS_VISIBLE LWS_EXTERN int\nlws_plat_plugins_init(struct lws_context * context, const char * const *d);\n\nLWS_VISIBLE LWS_EXTERN int\nlws_plat_plugins_destroy(struct lws_context * context);\n\nLWS_EXTERN void\nlws_restart_ws_ping_pong_timer(struct lws *wsi);\n\nstruct lws *\nlws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd);\n\nint\nlws_jws_base64_enc(const char *in, size_t in_len, char *out, size_t out_max);\n\nvoid\nlws_vhost_destroy1(struct lws_vhost *vh);\n\nenum {\n\tLWS_EV_READ = (1 << 0),\n\tLWS_EV_WRITE = (1 << 1),\n\tLWS_EV_START = (1 << 2),\n\tLWS_EV_STOP = (1 << 3),\n\n\tLWS_EV_PREPARE_DELETION = (1 << 31),\n};\n\n\n#if defined(LWS_WITH_ESP32)\nLWS_EXTERN int\nlws_find_string_in_file(const char *filename, const char *string, int stringlen);\n#endif\n\n#ifdef LWS_WITH_IPV6\n#define LWS_IPV6_ENABLED(vh) \\\n\t(!lws_check_opt(vh->context->options, LWS_SERVER_OPTION_DISABLE_IPV6) && \\\n\t !lws_check_opt(vh->options, LWS_SERVER_OPTION_DISABLE_IPV6))\n#else\n#define LWS_IPV6_ENABLED(context) (0)\n#endif\n\n#ifdef LWS_WITH_UNIX_SOCK\n#define LWS_UNIX_SOCK_ENABLED(vhost) \\\n\t(vhost->options & LWS_SERVER_OPTION_UNIX_SOCK)\n#else\n#define LWS_UNIX_SOCK_ENABLED(vhost) (0)\n#endif\n\nenum uri_path_states {\n\tURIPS_IDLE,\n\tURIPS_SEEN_SLASH,\n\tURIPS_SEEN_SLASH_DOT,\n\tURIPS_SEEN_SLASH_DOT_DOT,\n};\n\nenum uri_esc_states {\n\tURIES_IDLE,\n\tURIES_SEEN_PERCENT,\n\tURIES_SEEN_PERCENT_H1,\n};\n\n\n#ifndef LWS_NO_CLIENT\nstruct client_info_stash {\n\tchar *address;\n\tchar *path;\n\tchar *host;\n\tchar *origin;\n\tchar *protocol;\n\tchar *method;\n\tchar *iface;\n\tchar *alpn;\n};\n#endif\n\n\nsigned char char_to_hex(const char c);\n\n\nstruct lws_buflist {\n\tstruct lws_buflist *next;\n\n\tsize_t len;\n\tsize_t pos;\n\n\tuint8_t buf[1]; /* true length of this is set by the oversize malloc */\n};\n\n#define lws_wsi_is_udp(___wsi) (!!___wsi->udp)\n\n#define LWS_H2_FRAME_HEADER_LENGTH 9\n\n\nstruct lws {\n\t/* structs */\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tstruct _lws_http_mode_related http;\n#endif\n#if defined(LWS_ROLE_H2)\n\tstruct _lws_h2_related h2;\n#endif\n#if defined(LWS_ROLE_WS)\n\tstruct _lws_websocket_related *ws; /* allocated if we upgrade to ws */\n#endif\n\n\tconst struct lws_role_ops *role_ops;\n\tlws_wsi_state_t\twsistate;\n\tlws_wsi_state_t wsistate_pre_close;\n\n\t/* lifetime members */\n\n#if defined(LWS_WITH_LIBEV) || defined(LWS_WITH_LIBUV) || defined(LWS_WITH_LIBEVENT)\n\tstruct lws_io_watcher w_read;\n#endif\n#if defined(LWS_WITH_LIBEV) || defined(LWS_WITH_LIBEVENT)\n\tstruct lws_io_watcher w_write;\n#endif\n\n\t/* pointers */\n\n\tstruct lws_context *context;\n\tstruct lws_vhost *vhost;\n\tstruct lws *parent; /* points to parent, if any */\n\tstruct lws *child_list; /* points to first child */\n\tstruct lws *sibling_list; /* subsequent children at same level */\n\n\tconst struct lws_protocols *protocol;\n\tstruct lws **same_vh_protocol_prev, *same_vh_protocol_next;\n\n\tstruct lws_dll_lws dll_timeout;\n\tstruct lws_dll_lws dll_hrtimer;\n\tstruct lws_dll_lws dll_buflist; /* guys with pending rxflow */\n\n#if defined(LWS_WITH_PEER_LIMITS)\n\tstruct lws_peer *peer;\n#endif\n\n\tstruct lws_udp *udp;\n#ifndef LWS_NO_CLIENT\n\tstruct client_info_stash *stash;\n\tchar *client_hostname_copy;\n\tstruct lws_dll_lws dll_active_client_conns;\n\tstruct lws_dll_lws dll_client_transaction_queue_head;\n\tstruct lws_dll_lws dll_client_transaction_queue;\n#endif\n\tvoid *user_space;\n\tvoid *opaque_parent_data;\n\n\tstruct lws_buflist *buflist;\n\n\t/* truncated send handling */\n\tunsigned char *trunc_alloc; /* non-NULL means buffering in progress */\n\n#if defined(LWS_WITH_TLS)\n\tstruct lws_lws_tls tls;\n#endif\n\n\tlws_sock_file_fd_type desc; /* .filefd / .sockfd */\n#if defined(LWS_WITH_STATS)\n\tuint64_t active_writable_req_us;\n#if defined(LWS_WITH_TLS)\n\tuint64_t accept_start_us;\n#endif\n#endif\n\n\tlws_usec_t pending_timer; /* hrtimer fires */\n\ttime_t pending_timeout_set; /* second-resolution timeout start */\n\n#ifdef LWS_LATENCY\n\tunsigned long action_start;\n\tunsigned long latency_start;\n#endif\n\n\t/* ints */\n#define LWS_NO_FDS_POS (-1)\n\tint position_in_fds_table;\n\tunsigned int trunc_alloc_len; /* size of malloc */\n\tunsigned int trunc_offset; /* where we are in terms of spilling */\n\tunsigned int trunc_len; /* how much is buffered */\n#ifndef LWS_NO_CLIENT\n\tint chunk_remaining;\n#endif\n\tunsigned int cache_secs;\n\n\tunsigned int hdr_parsing_completed:1;\n\tunsigned int http2_substream:1;\n\tunsigned int upgraded_to_http2:1;\n\tunsigned int h2_stream_carries_ws:1;\n\tunsigned int seen_nonpseudoheader:1;\n\tunsigned int listener:1;\n\tunsigned int user_space_externally_allocated:1;\n\tunsigned int socket_is_permanently_unusable:1;\n\tunsigned int rxflow_change_to:2;\n\tunsigned int conn_stat_done:1;\n\tunsigned int cache_reuse:1;\n\tunsigned int cache_revalidate:1;\n\tunsigned int cache_intermediaries:1;\n\tunsigned int favoured_pollin:1;\n\tunsigned int sending_chunked:1;\n\tunsigned int interpreting:1;\n\tunsigned int already_did_cce:1;\n\tunsigned int told_user_closed:1;\n\tunsigned int told_event_loop_closed:1;\n\tunsigned int waiting_to_send_close_frame:1;\n\tunsigned int close_needs_ack:1;\n\tunsigned int ipv6:1;\n\tunsigned int parent_carries_io:1;\n\tunsigned int parent_pending_cb_on_writable:1;\n\tunsigned int cgi_stdout_zero_length:1;\n\tunsigned int seen_zero_length_recv:1;\n\tunsigned int rxflow_will_be_applied:1;\n\tunsigned int event_pipe:1;\n\tunsigned int on_same_vh_list:1;\n\tunsigned int handling_404:1;\n\tunsigned int protocol_bind_balance:1;\n\n\tunsigned int could_have_pending:1; /* detect back-to-back writes */\n\tunsigned int outer_will_close:1;\n\n#ifdef LWS_WITH_ACCESS_LOG\n\tunsigned int access_log_pending:1;\n#endif\n#ifndef LWS_NO_CLIENT\n\tunsigned int do_ws:1; /* whether we are doing http or ws flow */\n\tunsigned int chunked:1; /* if the clientside connection is chunked */\n\tunsigned int client_rx_avail:1;\n\tunsigned int client_http_body_pending:1;\n\tunsigned int transaction_from_pipeline_queue:1;\n\tunsigned int keepalive_active:1;\n\tunsigned int keepalive_rejected:1;\n\tunsigned int client_pipeline:1;\n\tunsigned int client_h2_alpn:1;\n\tunsigned int client_h2_substream:1;\n#endif\n\n#ifdef _WIN32\n\tunsigned int sock_send_blocking:1;\n#endif\n\n#ifndef LWS_NO_CLIENT\n\tunsigned short c_port;\n#endif\n\tunsigned short pending_timeout_limit;\n\n\t/* chars */\n\n\tchar lws_rx_parse_state; /* enum lws_rx_parse_state */\n\tchar rx_frame_type; /* enum lws_write_protocol */\n\tchar pending_timeout; /* enum pending_timeout */\n\tchar tsi; /* thread service index we belong to */\n\tchar protocol_interpret_idx;\n\tchar redirects;\n\tuint8_t rxflow_bitmap;\n#ifdef LWS_WITH_CGI\n\tchar cgi_channel; /* which of stdin/out/err */\n\tchar hdr_state;\n#endif\n#ifndef LWS_NO_CLIENT\n\tchar chunk_parser; /* enum lws_chunk_parser */\n#endif\n#if defined(LWS_WITH_CGI) || !defined(LWS_NO_CLIENT)\n\tchar reason_bf; /* internal writeable callback reason bitfield */\n#endif\n#if defined(LWS_WITH_STATS) && defined(LWS_WITH_TLS)\n\tchar seen_rx;\n#endif\n\tuint8_t ws_over_h2_count;\n\t/* volatile to make sure code is aware other thread can change */\n\tvolatile char handling_pollout;\n\tvolatile char leave_pollout_active;\n};\n\n#define lws_is_flowcontrolled(w) (!!(wsi->rxflow_bitmap))\n\nvoid\nlws_service_do_ripe_rxflow(struct lws_context_per_thread *pt);\n\nLWS_EXTERN int log_level;\n\nLWS_EXTERN int\nlws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port,\n\t\tconst char *iface);\n\n#if defined(LWS_WITH_IPV6)\nLWS_EXTERN unsigned long\nlws_get_addr_scope(const char *ipaddr);\n#endif\n\nLWS_EXTERN void\nlws_close_free_wsi(struct lws *wsi, enum lws_close_status, const char *caller);\nLWS_EXTERN void\n__lws_close_free_wsi(struct lws *wsi, enum lws_close_status, const char *caller);\n\nLWS_EXTERN void\n__lws_free_wsi(struct lws *wsi);\n\nLWS_EXTERN int\n__remove_wsi_socket_from_fds(struct lws *wsi);\nLWS_EXTERN int\nlws_rxflow_cache(struct lws *wsi, unsigned char *buf, int n, int len);\n\n#ifndef LWS_LATENCY\nstatic LWS_INLINE void\nlws_latency(struct lws_context *context, struct lws *wsi, const char *action,\n\t    int ret, int completion) {\n\tdo {\n\t\t(void)context; (void)wsi; (void)action; (void)ret;\n\t\t(void)completion;\n\t} while (0);\n}\nstatic LWS_INLINE void\nlws_latency_pre(struct lws_context *context, struct lws *wsi) {\n\tdo { (void)context; (void)wsi; } while (0);\n}\n#else\n#define lws_latency_pre(_context, _wsi) lws_latency(_context, _wsi, NULL, 0, 0)\nextern void\nlws_latency(struct lws_context *context, struct lws *wsi, const char *action,\n\t    int ret, int completion);\n#endif\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_ws_client_rx_sm(struct lws *wsi, unsigned char c);\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_parse(struct lws *wsi, unsigned char *buf, int *len);\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_parse_urldecode(struct lws *wsi, uint8_t *_c);\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_http_action(struct lws *wsi);\n\nLWS_EXTERN int\nlws_b64_selftest(void);\n\nLWS_EXTERN int\nlws_service_flag_pending(struct lws_context *context, int tsi);\n\nLWS_EXTERN int\nlws_timed_callback_remove(struct lws_vhost *vh, struct lws_timed_vh_protocol *p);\n\n#if defined(_WIN32)\nLWS_EXTERN struct lws *\nwsi_from_fd(const struct lws_context *context, lws_sockfd_type fd);\n\nLWS_EXTERN int\ninsert_wsi(struct lws_context *context, struct lws *wsi);\n\nLWS_EXTERN int\ndelete_from_fd(struct lws_context *context, lws_sockfd_type fd);\n#else\n#define wsi_from_fd(A,B)  A->lws_lookup[B - lws_plat_socket_offset()]\n#define insert_wsi(A,B)   assert(A->lws_lookup[B->desc.sockfd - lws_plat_socket_offset()] == 0); A->lws_lookup[B->desc.sockfd - lws_plat_socket_offset()]=B\n#define delete_from_fd(A,B) A->lws_lookup[B - lws_plat_socket_offset()]=0\n#endif\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\n__insert_wsi_socket_into_fds(struct lws_context *context, struct lws *wsi);\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_issue_raw(struct lws *wsi, unsigned char *buf, size_t len);\n\nLWS_EXTERN void\nlws_remove_from_timeout_list(struct lws *wsi);\n\nLWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT\nlws_client_connect_2(struct lws *wsi);\n\nLWS_VISIBLE struct lws * LWS_WARN_UNUSED_RESULT\nlws_client_reset(struct lws **wsi, int ssl, const char *address, int port,\n\t\t const char *path, const char *host);\n\nLWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT\nlws_create_new_server_wsi(struct lws_vhost *vhost, int fixed_tsi);\n\nLWS_EXTERN char * LWS_WARN_UNUSED_RESULT\nlws_generate_client_handshake(struct lws *wsi, char *pkt);\n\nLWS_EXTERN int\nlws_handle_POLLOUT_event(struct lws *wsi, struct lws_pollfd *pollfd);\n\nLWS_EXTERN struct lws *\nlws_client_connect_via_info2(struct lws *wsi);\n\n\n\nLWS_EXTERN void\nlws_client_stash_destroy(struct lws *wsi);\n\n/*\n * EXTENSIONS\n */\n\n#if defined(LWS_WITHOUT_EXTENSIONS)\n#define lws_any_extension_handled(_a, _b, _c, _d) (0)\n#define lws_ext_cb_active(_a, _b, _c, _d) (0)\n#define lws_ext_cb_all_exts(_a, _b, _c, _d, _e) (0)\n#define lws_issue_raw_ext_access lws_issue_raw\n#define lws_context_init_extensions(_a, _b)\n#endif\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_client_interpret_server_handshake(struct lws *wsi);\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_ws_rx_sm(struct lws *wsi, char already_processed, unsigned char c);\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_issue_raw_ext_access(struct lws *wsi, unsigned char *buf, size_t len);\n\nLWS_EXTERN void\nlws_role_transition(struct lws *wsi, enum lwsi_role role, enum lwsi_state state,\n\t\t\tstruct lws_role_ops *ops);\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nuser_callback_handle_rxflow(lws_callback_function, struct lws *wsi,\n\t\t\t    enum lws_callback_reasons reason, void *user,\n\t\t\t    void *in, size_t len);\n\nLWS_EXTERN int\nlws_plat_socket_offset(void);\n\nLWS_EXTERN int\nlws_plat_set_socket_options(struct lws_vhost *vhost, lws_sockfd_type fd);\n\nLWS_EXTERN int\nlws_plat_check_connection_error(struct lws *wsi);\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_header_table_attach(struct lws *wsi, int autoservice);\n\nLWS_EXTERN int\nlws_header_table_detach(struct lws *wsi, int autoservice);\nLWS_EXTERN int\n__lws_header_table_detach(struct lws *wsi, int autoservice);\n\nLWS_EXTERN void\nlws_header_table_reset(struct lws *wsi, int autoservice);\n\nvoid\n__lws_header_table_reset(struct lws *wsi, int autoservice);\n\nLWS_EXTERN char * LWS_WARN_UNUSED_RESULT\nlws_hdr_simple_ptr(struct lws *wsi, enum lws_token_indexes h);\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_hdr_simple_create(struct lws *wsi, enum lws_token_indexes h, const char *s);\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_ensure_user_space(struct lws *wsi);\n\nLWS_EXTERN int\nlws_change_pollfd(struct lws *wsi, int _and, int _or);\n\n#ifndef LWS_NO_SERVER\n int _lws_vhost_init_server(const struct lws_context_creation_info *info,\n\t\t\t      struct lws_vhost *vhost);\n LWS_EXTERN struct lws_vhost *\n lws_select_vhost(struct lws_context *context, int port, const char *servername);\n LWS_EXTERN int LWS_WARN_UNUSED_RESULT\n lws_parse_ws(struct lws *wsi, unsigned char **buf, size_t len);\n LWS_EXTERN void\n lws_server_get_canonical_hostname(struct lws_context *context,\n\t\t\t\t   const struct lws_context_creation_info *info);\n#else\n #define _lws_vhost_init_server(_a, _b) (0)\n #define lws_parse_ws(_a, _b, _c) (0)\n #define lws_server_get_canonical_hostname(_a, _b)\n#endif\n\n#ifndef LWS_NO_DAEMONIZE\n LWS_EXTERN int get_daemonize_pid();\n#else\n #define get_daemonize_pid() (0)\n#endif\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\ninterface_to_sa(struct lws_vhost *vh, const char *ifname,\n\t\tstruct sockaddr_in *addr, size_t addrlen);\nLWS_EXTERN void lwsl_emit_stderr(int level, const char *line);\n\n#if !defined(LWS_WITH_TLS)\n #define LWS_SSL_ENABLED(context) (0)\n #define lws_context_init_server_ssl(_a, _b) (0)\n #define lws_ssl_destroy(_a)\n #define lws_context_init_alpn(_a)\n #define lws_ssl_capable_read lws_ssl_capable_read_no_ssl\n #define lws_ssl_capable_write lws_ssl_capable_write_no_ssl\n #define lws_ssl_pending lws_ssl_pending_no_ssl\n #define lws_server_socket_service_ssl(_b, _c) (0)\n #define lws_ssl_close(_a) (0)\n #define lws_ssl_context_destroy(_a)\n #define lws_ssl_SSL_CTX_destroy(_a)\n #define lws_ssl_remove_wsi_from_buffered_list(_a)\n #define __lws_ssl_remove_wsi_from_buffered_list(_a)\n #define lws_context_init_ssl_library(_a)\n #define lws_tls_check_all_cert_lifetimes(_a)\n #define lws_tls_acme_sni_cert_destroy(_a)\n#endif\n\n\n#if LWS_MAX_SMP > 1\n\nstatic LWS_INLINE void\nlws_pt_mutex_init(struct lws_context_per_thread *pt)\n{\n\tpthread_mutex_init(&pt->lock, NULL);\n\tpthread_mutex_init(&pt->lock_stats, NULL);\n}\n\nstatic LWS_INLINE void\nlws_pt_mutex_destroy(struct lws_context_per_thread *pt)\n{\n\tpthread_mutex_destroy(&pt->lock_stats);\n\tpthread_mutex_destroy(&pt->lock);\n}\n\nstatic LWS_INLINE void\nlws_pt_lock(struct lws_context_per_thread *pt, const char *reason)\n{\n\tif (pt->lock_owner == pthread_self()) {\n\t\tpt->lock_depth++;\n\t\treturn;\n\t}\n\tpthread_mutex_lock(&pt->lock);\n\tpt->last_lock_reason = reason;\n\tpt->lock_owner = pthread_self();\n\t//lwsl_notice(\"tid %d: lock %s\\n\", pt->tid, reason);\n}\n\nstatic LWS_INLINE void\nlws_pt_unlock(struct lws_context_per_thread *pt)\n{\n\tif (pt->lock_depth) {\n\t\tpt->lock_depth--;\n\t\treturn;\n\t}\n\tpt->last_lock_reason = \"free\";\n\tpt->lock_owner = 0;\n\t//lwsl_notice(\"tid %d: unlock %s\\n\", pt->tid, pt->last_lock_reason);\n\tpthread_mutex_unlock(&pt->lock);\n}\n\nstatic LWS_INLINE void\nlws_pt_stats_lock(struct lws_context_per_thread *pt)\n{\n\tpthread_mutex_lock(&pt->lock_stats);\n}\n\nstatic LWS_INLINE void\nlws_pt_stats_unlock(struct lws_context_per_thread *pt)\n{\n\tpthread_mutex_unlock(&pt->lock_stats);\n}\n\nstatic LWS_INLINE void\nlws_context_lock(struct lws_context *context)\n{\n\tpthread_mutex_lock(&context->lock);\n}\n\nstatic LWS_INLINE void\nlws_context_unlock(struct lws_context *context)\n{\n\tpthread_mutex_unlock(&context->lock);\n}\n\nstatic LWS_INLINE void\nlws_vhost_lock(struct lws_vhost *vhost)\n{\n\tpthread_mutex_lock(&vhost->lock);\n}\n\nstatic LWS_INLINE void\nlws_vhost_unlock(struct lws_vhost *vhost)\n{\n\tpthread_mutex_unlock(&vhost->lock);\n}\n\n\n#else\n#define lws_pt_mutex_init(_a) (void)(_a)\n#define lws_pt_mutex_destroy(_a) (void)(_a)\n#define lws_pt_lock(_a, b) (void)(_a)\n#define lws_pt_unlock(_a) (void)(_a)\n#define lws_context_lock(_a) (void)(_a)\n#define lws_context_unlock(_a) (void)(_a)\n#define lws_vhost_lock(_a) (void)(_a)\n#define lws_vhost_unlock(_a) (void)(_a)\n#define lws_pt_stats_lock(_a) (void)(_a)\n#define lws_pt_stats_unlock(_a) (void)(_a)\n#endif\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_ssl_capable_read_no_ssl(struct lws *wsi, unsigned char *buf, int len);\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_ssl_capable_write_no_ssl(struct lws *wsi, unsigned char *buf, int len);\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_ssl_pending_no_ssl(struct lws *wsi);\n\nint\nlws_tls_check_cert_lifetime(struct lws_vhost *vhost);\n\nint lws_jws_selftest(void);\n\n\n#ifndef LWS_NO_CLIENT\nLWS_EXTERN int lws_client_socket_service(struct lws *wsi,\n\t\t\t\t\t struct lws_pollfd *pollfd,\n\t\t\t\t\t struct lws *wsi_conn);\nLWS_EXTERN struct lws *\nlws_client_wsi_effective(struct lws *wsi);\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_http_transaction_completed_client(struct lws *wsi);\n#if !defined(LWS_WITH_TLS)\n\t#define lws_context_init_client_ssl(_a, _b) (0)\n#endif\nLWS_EXTERN void\nlws_decode_ssl_error(void);\n#else\n#define lws_context_init_client_ssl(_a, _b) (0)\n#endif\n\nLWS_EXTERN int\n__lws_rx_flow_control(struct lws *wsi);\n\nLWS_EXTERN int\n_lws_change_pollfd(struct lws *wsi, int _and, int _or, struct lws_pollargs *pa);\n\n#ifndef LWS_NO_SERVER\nLWS_EXTERN int\nlws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len);\n#else\n#define lws_server_socket_service(_b, _c) (0)\n#define lws_handshake_server(_a, _b, _c) (0)\n#endif\n\n#ifdef LWS_WITH_ACCESS_LOG\nLWS_EXTERN int\nlws_access_log(struct lws *wsi);\nLWS_EXTERN void\nlws_prepare_access_log_info(struct lws *wsi, char *uri_ptr, int meth);\n#else\n#define lws_access_log(_a)\n#endif\n\nLWS_EXTERN int\nlws_cgi_kill_terminated(struct lws_context_per_thread *pt);\n\nLWS_EXTERN void\nlws_cgi_remove_and_kill(struct lws *wsi);\n\nint\nlws_protocol_init(struct lws_context *context);\n\nint\nlws_bind_protocol(struct lws *wsi, const struct lws_protocols *p);\n\nconst struct lws_http_mount *\nlws_find_mount(struct lws *wsi, const char *uri_ptr, int uri_len);\n\n/*\n * custom allocator\n */\nLWS_EXTERN void *\nlws_realloc(void *ptr, size_t size, const char *reason);\n\nLWS_EXTERN void * LWS_WARN_UNUSED_RESULT\nlws_zalloc(size_t size, const char *reason);\n\n#ifdef LWS_PLAT_OPTEE\nvoid *lws_malloc(size_t size, const char *reason);\nvoid lws_free(void *p);\n#define lws_free_set_NULL(P)    do { lws_free(P); (P) = NULL; } while(0)\n#else\n#define lws_malloc(S, R)\tlws_realloc(NULL, S, R)\n#define lws_free(P)\tlws_realloc(P, 0, \"lws_free\")\n#define lws_free_set_NULL(P)\tdo { lws_realloc(P, 0, \"free\"); (P) = NULL; } while(0)\n#endif\n\nchar *\nlws_strdup(const char *s);\n\nint\nlws_plat_pipe_create(struct lws *wsi);\nint\nlws_plat_pipe_signal(struct lws *wsi);\nvoid\nlws_plat_pipe_close(struct lws *wsi);\nint\nlws_create_event_pipes(struct lws_context *context);\n\nint lws_open(const char *__file, int __oflag, ...);\nvoid lws_plat_apply_FD_CLOEXEC(int n);\n\nconst struct lws_plat_file_ops *\nlws_vfs_select_fops(const struct lws_plat_file_ops *fops, const char *vfs_path,\n\t\t    const char **vpath);\n\n/* lws_plat_ */\nLWS_EXTERN void\nlws_plat_delete_socket_from_fds(struct lws_context *context,\n\t\t\t\tstruct lws *wsi, int m);\nLWS_EXTERN void\nlws_plat_insert_socket_into_fds(struct lws_context *context,\n\t\t\t\tstruct lws *wsi);\nLWS_EXTERN void\nlws_plat_service_periodic(struct lws_context *context);\n\nLWS_EXTERN int\nlws_plat_change_pollfd(struct lws_context *context, struct lws *wsi,\n\t\t       struct lws_pollfd *pfd);\nLWS_EXTERN void\nlws_add_wsi_to_draining_ext_list(struct lws *wsi);\nLWS_EXTERN void\nlws_remove_wsi_from_draining_ext_list(struct lws *wsi);\nLWS_EXTERN int\nlws_plat_context_early_init(void);\nLWS_EXTERN void\nlws_plat_context_early_destroy(struct lws_context *context);\nLWS_EXTERN void\nlws_plat_context_late_destroy(struct lws_context *context);\nLWS_EXTERN int\nlws_poll_listen_fd(struct lws_pollfd *fd);\nLWS_EXTERN int\nlws_plat_service(struct lws_context *context, int timeout_ms);\nLWS_EXTERN LWS_VISIBLE int\n_lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi);\nLWS_EXTERN int\nlws_plat_init(struct lws_context *context,\n\t      const struct lws_context_creation_info *info);\nLWS_EXTERN void\nlws_plat_drop_app_privileges(const struct lws_context_creation_info *info);\nLWS_EXTERN unsigned long long\ntime_in_microseconds(void);\nLWS_EXTERN const char * LWS_WARN_UNUSED_RESULT\nlws_plat_inet_ntop(int af, const void *src, char *dst, int cnt);\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_plat_inet_pton(int af, const char *src, void *dst);\n\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_check_utf8(unsigned char *state, unsigned char *buf, size_t len);\nLWS_EXTERN int alloc_file(struct lws_context *context, const char *filename, uint8_t **buf,\n\t\t                lws_filepos_t *amount);\n\n\nLWS_EXTERN void\nlws_same_vh_protocol_remove(struct lws *wsi);\nLWS_EXTERN void\nlws_same_vh_protocol_insert(struct lws *wsi, int n);\n\nLWS_EXTERN int\nlws_broadcast(struct lws_context *context, int reason, void *in, size_t len);\n\n#if defined(LWS_WITH_STATS)\n void\n lws_stats_atomic_bump(struct lws_context * context,\n\t\tstruct lws_context_per_thread *pt, int index, uint64_t bump);\n void\n lws_stats_atomic_max(struct lws_context * context,\n\t\tstruct lws_context_per_thread *pt, int index, uint64_t val);\n#else\n static LWS_INLINE uint64_t lws_stats_atomic_bump(struct lws_context * context,\n\t\tstruct lws_context_per_thread *pt, int index, uint64_t bump) {\n\t(void)context; (void)pt; (void)index; (void)bump; return 0; }\n static LWS_INLINE uint64_t lws_stats_atomic_max(struct lws_context * context,\n\t\tstruct lws_context_per_thread *pt, int index, uint64_t val) {\n\t(void)context; (void)pt; (void)index; (void)val; return 0; }\n#endif\n\n/* socks */\nvoid socks_generate_msg(struct lws *wsi, enum socks_msg_type type,\n\t\t\tssize_t *msg_len);\n\n#if defined(LWS_WITH_PEER_LIMITS)\nvoid\nlws_peer_track_wsi_close(struct lws_context *context, struct lws_peer *peer);\nint\nlws_peer_confirm_ah_attach_ok(struct lws_context *context, struct lws_peer *peer);\nvoid\nlws_peer_track_ah_detach(struct lws_context *context, struct lws_peer *peer);\nvoid\nlws_peer_cull_peer_wait_list(struct lws_context *context);\nstruct lws_peer *\nlws_get_or_create_peer(struct lws_vhost *vhost, lws_sockfd_type sockfd);\nvoid\nlws_peer_add_wsi(struct lws_context *context, struct lws_peer *peer,\n\t\t struct lws *wsi);\nvoid\nlws_peer_dump_from_wsi(struct lws *wsi);\n#endif\n\n#ifdef LWS_WITH_HTTP_PROXY\nhubbub_error\nhtml_parser_cb(const hubbub_token *token, void *pw);\n#endif\n\n\nvoid\n__lws_remove_from_timeout_list(struct lws *wsi);\n\nlws_usec_t\n__lws_hrtimer_service(struct lws_context_per_thread *pt);\n\nvoid\n__lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs);\nint\n__lws_change_pollfd(struct lws *wsi, int _and, int _or);\n\n\nint\nlws_callback_as_writeable(struct lws *wsi);\nint\nlws_buflist_aware_read(struct lws_context_per_thread *pt, struct lws *wsi,\n\t\t       struct lws_tokens *ebuf);\nint\nlws_buflist_aware_consume(struct lws *wsi, struct lws_tokens *ebuf, int used,\n\t\t\t  int buffered);\n\n\nchar *\nlws_generate_client_ws_handshake(struct lws *wsi, char *p);\nint\nlws_client_ws_upgrade(struct lws *wsi, const char **cce);\nint\nlws_create_client_ws_object(struct lws_client_connect_info *i, struct lws *wsi);\nint\nlws_alpn_comma_to_openssl(const char *comma, uint8_t *os, int len);\nint\nlws_role_call_alpn_negotiated(struct lws *wsi, const char *alpn);\nint\nlws_tls_server_conn_alpn(struct lws *wsi);\n\nint\nlws_ws_client_rx_sm_block(struct lws *wsi, unsigned char **buf, size_t len);\nvoid\nlws_destroy_event_pipe(struct lws *wsi);\nvoid\nlws_context_destroy2(struct lws_context *context);\n\n#ifdef __cplusplus\n};\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/core/service.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n\nint\nlws_callback_as_writeable(struct lws *wsi)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tint n, m;\n\n\tlws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITEABLE_CB, 1);\n#if defined(LWS_WITH_STATS)\n\tif (wsi->active_writable_req_us) {\n\t\tuint64_t ul = time_in_microseconds() -\n\t\t\t      wsi->active_writable_req_us;\n\n\t\tlws_stats_atomic_bump(wsi->context, pt,\n\t\t\t\t      LWSSTATS_MS_WRITABLE_DELAY, ul);\n\t\tlws_stats_atomic_max(wsi->context, pt,\n\t\t\t\t     LWSSTATS_MS_WORST_WRITABLE_DELAY, ul);\n\t\twsi->active_writable_req_us = 0;\n\t}\n#endif\n\n\tn = wsi->role_ops->writeable_cb[lwsi_role_server(wsi)];\n\n\tm = user_callback_handle_rxflow(wsi->protocol->callback,\n\t\t\t\t\twsi, (enum lws_callback_reasons) n,\n\t\t\t\t\twsi->user_space, NULL, 0);\n\n\treturn m;\n}\n\nLWS_VISIBLE int\nlws_handle_POLLOUT_event(struct lws *wsi, struct lws_pollfd *pollfd)\n{\n\tvolatile struct lws *vwsi = (volatile struct lws *)wsi;\n\tint n;\n\n\t//lwsl_notice(\"%s: %p\\n\", __func__, wsi);\n\n\tvwsi->leave_pollout_active = 0;\n\tvwsi->handling_pollout = 1;\n\t/*\n\t * if another thread wants POLLOUT on us, from here on while\n\t * handling_pollout is set, he will only set leave_pollout_active.\n\t * If we are going to disable POLLOUT, we will check that first.\n\t */\n\twsi->could_have_pending = 0; /* clear back-to-back write detection */\n\n\t/*\n\t * user callback is lowest priority to get these notifications\n\t * actually, since other pending things cannot be disordered\n\t *\n\t * Priority 1: pending truncated sends are incomplete ws fragments\n\t *\t       If anything else sent first the protocol would be\n\t *\t       corrupted.\n\t */\n\n\tif (wsi->trunc_len) {\n\t\t//lwsl_notice(\"%s: completing partial\\n\", __func__);\n\t\tif (lws_issue_raw(wsi, wsi->trunc_alloc + wsi->trunc_offset,\n\t\t\t\t  wsi->trunc_len) < 0) {\n\t\t\tlwsl_info(\"%s signalling to close\\n\", __func__);\n\t\t\tgoto bail_die;\n\t\t}\n\t\t/* leave POLLOUT active either way */\n\t\tgoto bail_ok;\n\t} else\n\t\tif (lwsi_state(wsi) == LRS_FLUSHING_BEFORE_CLOSE) {\n\t\t\twsi->socket_is_permanently_unusable = 1;\n\t\t\tgoto bail_die; /* retry closing now */\n\t\t}\n\n#ifdef LWS_WITH_CGI\n\t/*\n\t * A cgi master's wire protocol remains h1 or h2.  He is just getting\n\t * his data from his child cgis.\n\t */\n\tif (wsi->http.cgi) {\n\t\t/* also one shot */\n\t\tif (pollfd)\n\t\t\tif (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {\n\t\t\t\tlwsl_info(\"failed at set pollfd\\n\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\tgoto user_service_go_again;\n\t}\n#endif\n\n\t/* if we got here, we should have wire protocol ops set on the wsi */\n\tassert(wsi->role_ops);\n\n\tif (!wsi->role_ops->handle_POLLOUT)\n\t\tgoto bail_ok;\n\n\tswitch ((wsi->role_ops->handle_POLLOUT)(wsi)) {\n\tcase LWS_HP_RET_BAIL_OK:\n\t\tgoto bail_ok;\n\tcase LWS_HP_RET_BAIL_DIE:\n\t\tgoto bail_die;\n\tcase LWS_HP_RET_USER_SERVICE:\n\t\tbreak;\n\tdefault:\n\t\tassert(0);\n\t}\n\n\t/* one shot */\n\n\tif (wsi->parent_carries_io) {\n\t\tvwsi->handling_pollout = 0;\n\t\tvwsi->leave_pollout_active = 0;\n\n\t\treturn lws_callback_as_writeable(wsi);\n\t}\n\n\tif (pollfd) {\n\t\tint eff = vwsi->leave_pollout_active;\n\n\t\tif (!eff) {\n\t\t\tif (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {\n\t\t\t\tlwsl_info(\"failed at set pollfd\\n\");\n\t\t\t\tgoto bail_die;\n\t\t\t}\n\t\t}\n\n\t\tvwsi->handling_pollout = 0;\n\n\t\t/* cannot get leave_pollout_active set after the above */\n\t\tif (!eff && wsi->leave_pollout_active) {\n\t\t\t/*\n\t\t\t * got set inbetween sampling eff and clearing\n\t\t\t * handling_pollout, force POLLOUT on\n\t\t\t */\n\t\t\tlwsl_debug(\"leave_pollout_active\\n\");\n\t\t\tif (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) {\n\t\t\t\tlwsl_info(\"failed at set pollfd\\n\");\n\t\t\t\tgoto bail_die;\n\t\t\t}\n\t\t}\n\n\t\tvwsi->leave_pollout_active = 0;\n\t}\n\n\tif (lwsi_role_client(wsi) &&\n\t    !wsi->hdr_parsing_completed &&\n\t     lwsi_state(wsi) != LRS_H2_WAITING_TO_SEND_HEADERS &&\n\t     lwsi_state(wsi) != LRS_ISSUE_HTTP_BODY\n\t     )\n\t\tgoto bail_ok;\n\n\n#ifdef LWS_WITH_CGI\nuser_service_go_again:\n#endif\n\n\tif (wsi->role_ops->perform_user_POLLOUT) {\n\t\tif (wsi->role_ops->perform_user_POLLOUT(wsi) == -1)\n\t\t\tgoto bail_die;\n\t\telse\n\t\t\tgoto bail_ok;\n\t}\n\t\n\tlwsl_debug(\"%s: %p: non mux: wsistate 0x%x, ops %s\\n\", __func__, wsi,\n\t\t   wsi->wsistate, wsi->role_ops->name);\n\n\tvwsi = (volatile struct lws *)wsi;\n\tvwsi->leave_pollout_active = 0;\n\n\tn = lws_callback_as_writeable(wsi);\n\tvwsi->handling_pollout = 0;\n\n\tif (vwsi->leave_pollout_active)\n\t\tlws_change_pollfd(wsi, 0, LWS_POLLOUT);\n\n\treturn n;\n\n\t/*\n\t * since these don't disable the POLLOUT, they are always doing the\n\t * right thing for leave_pollout_active whether it was set or not.\n\t */\n\nbail_ok:\n\tvwsi->handling_pollout = 0;\n\tvwsi->leave_pollout_active = 0;\n\n\treturn 0;\n\nbail_die:\n\tvwsi->handling_pollout = 0;\n\tvwsi->leave_pollout_active = 0;\n\n\treturn -1;\n}\n\nstatic int\n__lws_service_timeout_check(struct lws *wsi, time_t sec)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tint n = 0;\n\n\t(void)n;\n\n\t/*\n\t * if we went beyond the allowed time, kill the\n\t * connection\n\t */\n\tif (wsi->dll_timeout.prev &&\n\t    lws_compare_time_t(wsi->context, sec, wsi->pending_timeout_set) >\n\t\t\t       wsi->pending_timeout_limit) {\n\n\t\tif (wsi->desc.sockfd != LWS_SOCK_INVALID &&\n\t\t    wsi->position_in_fds_table >= 0)\n\t\t\tn = pt->fds[wsi->position_in_fds_table].events;\n\n\t\tlws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_TIMEOUTS, 1);\n\n\t\t/* no need to log normal idle keepalive timeout */\n\t\tif (wsi->pending_timeout != PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE)\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\t\t\tlwsl_info(\"wsi %p: TIMEDOUT WAITING on %d \"\n\t\t\t\t  \"(did hdr %d, ah %p, wl %d, pfd \"\n\t\t\t\t  \"events %d) %llu vs %llu\\n\",\n\t\t\t\t  (void *)wsi, wsi->pending_timeout,\n\t\t\t\t  wsi->hdr_parsing_completed, wsi->http.ah,\n\t\t\t\t  pt->http.ah_wait_list_length, n,\n\t\t\t\t  (unsigned long long)sec,\n\t\t\t\t  (unsigned long long)wsi->pending_timeout_limit);\n#if defined(LWS_WITH_CGI)\n\t\tif (wsi->http.cgi)\n\t\t\tlwsl_notice(\"CGI timeout: %s\\n\", wsi->http.cgi->summary);\n#endif\n#else\n\t\tlwsl_info(\"wsi %p: TIMEDOUT WAITING on %d \", (void *)wsi,\n\t\t\t  wsi->pending_timeout);\n#endif\n\n\t\t/*\n\t\t * Since he failed a timeout, he already had a chance to do\n\t\t * something and was unable to... that includes situations like\n\t\t * half closed connections.  So process this \"failed timeout\"\n\t\t * close as a violent death and don't try to do protocol\n\t\t * cleanup like flush partials.\n\t\t */\n\t\twsi->socket_is_permanently_unusable = 1;\n\t\tif (lwsi_state(wsi) == LRS_WAITING_SSL && wsi->protocol)\n\t\t\twsi->protocol->callback(wsi,\n\t\t\t\tLWS_CALLBACK_CLIENT_CONNECTION_ERROR,\n\t\t\t\twsi->user_space,\n\t\t\t\t(void *)\"Timed out waiting SSL\", 21);\n\n\t\t__lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, \"timeout\");\n\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\nint lws_rxflow_cache(struct lws *wsi, unsigned char *buf, int n, int len)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tuint8_t *buffered;\n\tsize_t blen;\n\tint ret = 0, m;\n\n\t/* his RX is flowcontrolled, don't send remaining now */\n\tblen = lws_buflist_next_segment_len(&wsi->buflist, &buffered);\n\tif (blen) {\n\t\tif (buf >= buffered && buf + len <= buffered + blen) {\n\t\t\t/* rxflow while we were spilling prev rxflow */\n\t\t\tlwsl_info(\"%s: staying in rxflow buf\\n\", __func__);\n\n\t\t\treturn 1;\n\t\t}\n\t\tret = 1;\n\t}\n\n\t/* a new rxflow, buffer it and warn caller */\n\n\tm = lws_buflist_append_segment(&wsi->buflist, buf + n, len - n);\n\n\tif (m < 0)\n\t\treturn -1;\n\tif (m) {\n\t\tlwsl_debug(\"%s: added %p to rxflow list\\n\", __func__, wsi);\n\t\tlws_dll_lws_add_front(&wsi->dll_buflist, &pt->dll_head_buflist);\n\t}\n\n\treturn ret;\n}\n\n/* this is used by the platform service code to stop us waiting for network\n * activity in poll() when we have something that already needs service\n */\n\nLWS_VISIBLE LWS_EXTERN int\nlws_service_adjust_timeout(struct lws_context *context, int timeout_ms, int tsi)\n{\n\tstruct lws_context_per_thread *pt = &context->pt[tsi];\n\n\t/* Figure out if we really want to wait in poll()\n\t * We only need to wait if really nothing already to do and we have\n\t * to wait for something from network\n\t */\n#if defined(LWS_ROLE_WS) && !defined(LWS_WITHOUT_EXTENSIONS)\n\t/* 1) if we know we are draining rx ext, do not wait in poll */\n\tif (pt->ws.rx_draining_ext_list)\n\t\treturn 0;\n#endif\n\n\t/* 2) if we know we have non-network pending data, do not wait in poll */\n\n\tif (pt->context->tls_ops &&\n\t    pt->context->tls_ops->fake_POLLIN_for_buffered)\n\t\tif (pt->context->tls_ops->fake_POLLIN_for_buffered(pt))\n\t\t\treturn 0;\n\n\t/* 3) If there is any wsi with rxflow buffered and in a state to process\n\t *    it, we should not wait in poll\n\t */\n\n\tlws_start_foreach_dll(struct lws_dll_lws *, d, pt->dll_head_buflist.next) {\n\t\tstruct lws *wsi = lws_container_of(d, struct lws, dll_buflist);\n\n\t\tif (lwsi_state(wsi) != LRS_DEFERRING_ACTION)\n\t\t\treturn 0;\n\n\t} lws_end_foreach_dll(d);\n\n\treturn timeout_ms;\n}\n\n/*\n * POLLIN said there is something... we must read it, and either use it; or\n * if other material already in the buflist append it and return the buflist\n * head material.\n */\nint\nlws_buflist_aware_read(struct lws_context_per_thread *pt, struct lws *wsi,\n\t\t       struct lws_tokens *ebuf)\n{\n\tint n, prior = (int)lws_buflist_next_segment_len(&wsi->buflist, NULL);\n\n\tebuf->token = (char *)pt->serv_buf;\n\tebuf->len = lws_ssl_capable_read(wsi, pt->serv_buf,\n\t\t\t\t\t wsi->context->pt_serv_buf_size);\n\n\tif (ebuf->len == LWS_SSL_CAPABLE_MORE_SERVICE && prior)\n\t\tgoto get_from_buflist;\n\n\tif (ebuf->len <= 0)\n\t\treturn 0;\n\n\t/* nothing in buflist already?  Then just use what we read */\n\n\tif (!prior)\n\t\treturn 0;\n\n\t/* stash what we read */\n\n\tn = lws_buflist_append_segment(&wsi->buflist, (uint8_t *)ebuf->token,\n\t\t\t\t       ebuf->len);\n\tif (n < 0)\n\t\treturn -1;\n\tif (n) {\n\t\tlwsl_debug(\"%s: added %p to rxflow list\\n\", __func__, wsi);\n\t\tlws_dll_lws_add_front(&wsi->dll_buflist, &pt->dll_head_buflist);\n\t}\n\n\t/* get the first buflist guy in line */\n\nget_from_buflist:\n\n\tebuf->len = (int)lws_buflist_next_segment_len(&wsi->buflist,\n\t\t\t\t\t\t      (uint8_t **)&ebuf->token);\n\n\treturn 1; /* came from buflist */\n}\n\nint\nlws_buflist_aware_consume(struct lws *wsi, struct lws_tokens *ebuf, int used,\n\t\t\t  int buffered)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tint m;\n\n\t/* it's in the buflist; we didn't use any */\n\n\tif (!used && buffered)\n\t\treturn 0;\n\n\tif (used && buffered) {\n\t\tm = lws_buflist_use_segment(&wsi->buflist, used);\n\t\tlwsl_info(\"%s: draining rxflow: used %d, next %d\\n\",\n\t\t\t    __func__, used, m);\n\t\tif (m)\n\t\t\treturn 0;\n\n\t\tlwsl_info(\"%s: removed %p from dll_buflist\\n\", __func__, wsi);\n\t\tlws_dll_lws_remove(&wsi->dll_buflist);\n\n\t\treturn 0;\n\t}\n\n\t/* any remainder goes on the buflist */\n\n\tif (used != ebuf->len) {\n\t\tm = lws_buflist_append_segment(&wsi->buflist,\n\t\t\t\t\t       (uint8_t *)ebuf->token + used,\n\t\t\t\t\t       ebuf->len - used);\n\t\tif (m < 0)\n\t\t\treturn 1; /* OOM */\n\t\tif (m) {\n\t\t\tlwsl_debug(\"%s: added %p to rxflow list\\n\", __func__, wsi);\n\t\t\tlws_dll_lws_add_front(&wsi->dll_buflist, &pt->dll_head_buflist);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nvoid\nlws_service_do_ripe_rxflow(struct lws_context_per_thread *pt)\n{\n\tstruct lws_pollfd pfd;\n\n\tif (!pt->dll_head_buflist.next)\n\t\treturn;\n\n\t/*\n\t * service all guys with pending rxflow that reached a state they can\n\t * accept the pending data\n\t */\n\n\tlws_pt_lock(pt, __func__);\n\n\tlws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1,\n\t\t\t\t   pt->dll_head_buflist.next) {\n\t\tstruct lws *wsi = lws_container_of(d, struct lws, dll_buflist);\n\n\t\tpfd.events = LWS_POLLIN;\n\t\tpfd.revents = LWS_POLLIN;\n\t\tpfd.fd = -1;\n\n\t\tlwsl_debug(\"%s: rxflow processing: %p 0x%x\\n\", __func__, wsi,\n\t\t\t    wsi->wsistate);\n\n\t\tif (!lws_is_flowcontrolled(wsi) &&\n\t\t    lwsi_state(wsi) != LRS_DEFERRING_ACTION &&\n\t\t    (wsi->role_ops->handle_POLLIN)(pt, wsi, &pfd) ==\n\t\t\t\t\t\t   LWS_HPI_RET_PLEASE_CLOSE_ME)\n\t\t\tlws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS,\n\t\t\t\t\t   \"close_and_handled\");\n\n\t} lws_end_foreach_dll_safe(d, d1);\n\n\tlws_pt_unlock(pt);\n}\n\n/*\n * guys that need POLLIN service again without waiting for network action\n * can force POLLIN here if not flowcontrolled, so they will get service.\n *\n * Return nonzero if anybody got their POLLIN faked\n */\nint\nlws_service_flag_pending(struct lws_context *context, int tsi)\n{\n\tstruct lws_context_per_thread *pt = &context->pt[tsi];\n\n#if defined(LWS_WITH_TLS)\n\tstruct lws *wsi, *wsi_next;\n#endif\n\tint forced = 0;\n\n\tlws_pt_lock(pt, __func__);\n\n\t/*\n\t * 1) If there is any wsi with a buflist and in a state to process\n\t *    it, we should not wait in poll\n\t */\n\n\tlws_start_foreach_dll(struct lws_dll_lws *, d, pt->dll_head_buflist.next) {\n\t\tstruct lws *wsi = lws_container_of(d, struct lws, dll_buflist);\n\n\t\tif (lwsi_state(wsi) != LRS_DEFERRING_ACTION) {\n\t\t\tforced = 1;\n\t\t\tbreak;\n\t\t}\n\t} lws_end_foreach_dll(d);\n\n#if defined(LWS_ROLE_WS)\n\tforced |= role_ops_ws.service_flag_pending(context, tsi);\n#endif\n\n#if defined(LWS_WITH_TLS)\n\t/*\n\t * 2) For all guys with buffered SSL read data already saved up, if they\n\t * are not flowcontrolled, fake their POLLIN status so they'll get\n\t * service to use up the buffered incoming data, even though their\n\t * network socket may have nothing\n\t */\n\twsi = pt->tls.pending_read_list;\n\twhile (wsi) {\n\t\twsi_next = wsi->tls.pending_read_list_next;\n\t\tpt->fds[wsi->position_in_fds_table].revents |=\n\t\t\tpt->fds[wsi->position_in_fds_table].events & LWS_POLLIN;\n\t\tif (pt->fds[wsi->position_in_fds_table].revents & LWS_POLLIN) {\n\t\t\tforced = 1;\n\t\t\t/*\n\t\t\t * he's going to get serviced now, take him off the\n\t\t\t * list of guys with buffered SSL.  If he still has some\n\t\t\t * at the end of the service, he'll get put back on the\n\t\t\t * list then.\n\t\t\t */\n\t\t\t__lws_ssl_remove_wsi_from_buffered_list(wsi);\n\t\t}\n\n\t\twsi = wsi_next;\n\t}\n#endif\n\n\tlws_pt_unlock(pt);\n\n\treturn forced;\n}\n\nstatic int\nlws_service_periodic_checks(struct lws_context *context,\n\t\t\t    struct lws_pollfd *pollfd, int tsi)\n{\n\tstruct lws_context_per_thread *pt = &context->pt[tsi];\n\tlws_sockfd_type our_fd = 0, tmp_fd;\n\tstruct lws *wsi;\n\tint timed_out = 0;\n\ttime_t now;\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tstruct allocated_headers *ah;\n\tint m;\n#endif\n\n\tif (!context->protocol_init_done)\n\t\tif (lws_protocol_init(context))\n\t\t\treturn -1;\n\n\ttime(&now);\n\n\t/*\n\t * handle case that system time was uninitialized when lws started\n\t * at boot, and got initialized a little later\n\t */\n\tif (context->time_up < 1464083026 && now > 1464083026)\n\t\tcontext->time_up = now;\n\n\tif (context->last_timeout_check_s &&\n\t    now - context->last_timeout_check_s > 100) {\n\t\t/*\n\t\t * There has been a discontiguity.  Any stored time that is\n\t\t * less than context->time_discontiguity should have context->\n\t\t * time_fixup added to it.\n\t\t *\n\t\t * Some platforms with no RTC will experience this as a normal\n\t\t * event when ntp sets their clock, but we can have started\n\t\t * long before that with a 0-based unix time.\n\t\t */\n\n\t\tcontext->time_discontiguity = now;\n\t\tcontext->time_fixup = now - context->last_timeout_check_s;\n\n\t\tlwsl_notice(\"time discontiguity: at old time %llus, \"\n\t\t\t    \"new time %llus: +%llus\\n\",\n\t\t\t    (unsigned long long)context->last_timeout_check_s,\n\t\t\t    (unsigned long long)context->time_discontiguity,\n\t\t\t    (unsigned long long)context->time_fixup);\n\n\t\tcontext->last_timeout_check_s = now - 1;\n\t}\n\n\tif (!lws_compare_time_t(context, context->last_timeout_check_s, now))\n\t\treturn 0;\n\n\tcontext->last_timeout_check_s = now;\n\n#if defined(LWS_WITH_STATS)\n\tif (!tsi && now - context->last_dump > 10) {\n\t\tlws_stats_log_dump(context);\n\t\tcontext->last_dump = now;\n\t}\n#endif\n\n\tlws_plat_service_periodic(context);\n\tlws_check_deferred_free(context, 0);\n\n#if defined(LWS_WITH_PEER_LIMITS)\n\tlws_peer_cull_peer_wait_list(context);\n#endif\n\n\t/* retire unused deprecated context */\n#if !defined(LWS_PLAT_OPTEE) && !defined(LWS_WITH_ESP32)\n#if !defined(_WIN32)\n\tif (context->deprecated && !context->count_wsi_allocated) {\n\t\tlwsl_notice(\"%s: ending deprecated context\\n\", __func__);\n\t\tkill(getpid(), SIGINT);\n\t\treturn 0;\n\t}\n#endif\n#endif\n\t/* global timeout check once per second */\n\n\tif (pollfd)\n\t\tour_fd = pollfd->fd;\n\n\t/*\n\t * Phase 1: check every wsi on the timeout check list\n\t */\n\n\tlws_pt_lock(pt, __func__);\n\n\tlws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1,\n\t\t\t\t   context->pt[tsi].dll_head_timeout.next) {\n\t\twsi = lws_container_of(d, struct lws, dll_timeout);\n\t\ttmp_fd = wsi->desc.sockfd;\n\t\tif (__lws_service_timeout_check(wsi, now)) {\n\t\t\t/* he did time out... */\n\t\t\tif (tmp_fd == our_fd)\n\t\t\t\t/* it was the guy we came to service! */\n\t\t\t\ttimed_out = 1;\n\t\t\t/* he's gone, no need to mark as handled */\n\t\t}\n\t} lws_end_foreach_dll_safe(d, d1);\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\t/*\n\t * Phase 2: double-check active ah timeouts independent of wsi\n\t *\t    timeout status\n\t */\n\n\tah = pt->http.ah_list;\n\twhile (ah) {\n\t\tint len;\n\t\tchar buf[256];\n\t\tconst unsigned char *c;\n\n\t\tif (!ah->in_use || !ah->wsi || !ah->assigned ||\n\t\t    (ah->wsi->vhost &&\n\t\t     lws_compare_time_t(context, now, ah->assigned) <\n\t\t     ah->wsi->vhost->timeout_secs_ah_idle + 360)) {\n\t\t\tah = ah->next;\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*\n\t\t * a single ah session somehow got held for\n\t\t * an unreasonable amount of time.\n\t\t *\n\t\t * Dump info on the connection...\n\t\t */\n\t\twsi = ah->wsi;\n\t\tbuf[0] = '\\0';\n#if !defined(LWS_PLAT_OPTEE)\n\t\tlws_get_peer_simple(wsi, buf, sizeof(buf));\n#else\n\t\tbuf[0] = '\\0';\n#endif\n\t\tlwsl_notice(\"ah excessive hold: wsi %p\\n\"\n\t\t\t    \"  peer address: %s\\n\"\n\t\t\t    \"  ah pos %u\\n\",\n\t\t\t    wsi, buf, ah->pos);\n\t\tbuf[0] = '\\0';\n\t\tm = 0;\n\t\tdo {\n\t\t\tc = lws_token_to_string(m);\n\t\t\tif (!c)\n\t\t\t\tbreak;\n\t\t\tif (!(*c))\n\t\t\t\tbreak;\n\n\t\t\tlen = lws_hdr_total_length(wsi, m);\n\t\t\tif (!len || len > (int)sizeof(buf) - 1) {\n\t\t\t\tm++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (lws_hdr_copy(wsi, buf,\n\t\t\t\t\t sizeof buf, m) > 0) {\n\t\t\t\tbuf[sizeof(buf) - 1] = '\\0';\n\n\t\t\t\tlwsl_notice(\"   %s = %s\\n\",\n\t\t\t\t\t    (const char *)c, buf);\n\t\t\t}\n\t\t\tm++;\n\t\t} while (1);\n\n\t\t/* explicitly detach the ah */\n\t\tlws_header_table_detach(wsi, 0);\n\n\t\t/* ... and then drop the connection */\n\n\t\tm = 0;\n\t\tif (wsi->desc.sockfd == our_fd) {\n\t\t\tm = timed_out;\n\n\t\t\t/* it was the guy we came to service! */\n\t\t\ttimed_out = 1;\n\t\t}\n\n\t\tif (!m) /* if he didn't already timeout */\n\t\t\t__lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS,\n\t\t\t\t\t     \"excessive ah\");\n\n\t\tah = pt->http.ah_list;\n\t}\n#endif\n\tlws_pt_unlock(pt);\n\n#if 0\n\t{\n\t\tchar s[300], *p = s;\n\n\t\tfor (n = 0; n < context->count_threads; n++)\n\t\t\tp += sprintf(p, \" %7lu (%5d), \",\n\t\t\t\t     context->pt[n].count_conns,\n\t\t\t\t     context->pt[n].fds_count);\n\n\t\tlwsl_notice(\"load: %s\\n\", s);\n\t}\n#endif\n\t/*\n\t * Phase 3: vhost / protocol timer callbacks\n\t */\n\n\twsi = NULL;\n\tlws_start_foreach_ll(struct lws_vhost *, v, context->vhost_list) {\n\t\tstruct lws_timed_vh_protocol *nx;\n\t\tif (v->timed_vh_protocol_list) {\n\t\t\tlws_start_foreach_ll(struct lws_timed_vh_protocol *,\n\t\t\t\t\tq, v->timed_vh_protocol_list) {\n\t\t\t\tif (now >= q->time) {\n\t\t\t\t\tif (!wsi)\n\t\t\t\t\t\twsi = lws_zalloc(sizeof(*wsi), \"cbwsi\");\n\t\t\t\t\twsi->context = context;\n\t\t\t\t\twsi->vhost = v;\n\t\t\t\t\twsi->protocol = q->protocol;\n\t\t\t\t\tlwsl_debug(\"timed cb: vh %s, protocol %s, reason %d\\n\", v->name, q->protocol->name, q->reason);\n\t\t\t\t\tq->protocol->callback(wsi, q->reason, NULL, NULL, 0);\n\t\t\t\t\tnx = q->next;\n\t\t\t\t\tlws_timed_callback_remove(v, q);\n\t\t\t\t\tq = nx;\n\t\t\t\t\tcontinue; /* we pointed ourselves to the next from the now-deleted guy */\n\t\t\t\t}\n\t\t\t} lws_end_foreach_ll(q, next);\n\t\t}\n\t} lws_end_foreach_ll(v, vhost_next);\n\tif (wsi)\n\t\tlws_free(wsi);\n\n\t/*\n\t * Phase 4: check for unconfigured vhosts due to required\n\t *\t    interface missing before\n\t */\n\n\tlws_context_lock(context);\n\tlws_start_foreach_llp(struct lws_vhost **, pv,\n\t\t\t      context->no_listener_vhost_list) {\n\t\tstruct lws_vhost *v = *pv;\n\t\tlwsl_debug(\"deferred iface: checking if on vh %s\\n\", (*pv)->name);\n\t\tif (_lws_vhost_init_server(NULL, *pv) == 0) {\n\t\t\t/* became happy */\n\t\t\tlwsl_notice(\"vh %s: became connected\\n\", v->name);\n\t\t\t*pv = v->no_listener_vhost_list;\n\t\t\tv->no_listener_vhost_list = NULL;\n\t\t\tbreak;\n\t\t}\n\t} lws_end_foreach_llp(pv, no_listener_vhost_list);\n\tlws_context_unlock(context);\n\n\t/*\n\t * Phase 5: role periodic checks\n\t */\n#if defined(LWS_ROLE_WS)\n\trole_ops_ws.periodic_checks(context, tsi, now);\n#endif\n#if defined(LWS_ROLE_CGI)\n\trole_ops_cgi.periodic_checks(context, tsi, now);\n#endif\n\n\t/*\n\t * Phase 6: check the remaining cert lifetime daily\n\t */\n\n\tif (context->tls_ops &&\n\t    context->tls_ops->periodic_housekeeping)\n\t\tcontext->tls_ops->periodic_housekeeping(context, now);\n\n\treturn timed_out;\n}\n\nLWS_VISIBLE int\nlws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd,\n\t\t   int tsi)\n{\n\tstruct lws_context_per_thread *pt = &context->pt[tsi];\n\tstruct lws *wsi;\n\n\tif (!context || context->being_destroyed1)\n\t\treturn -1;\n\n\t/* the socket we came to service timed out, nothing to do */\n\tif (lws_service_periodic_checks(context, pollfd, tsi) || !pollfd)\n\t\treturn 0;\n\n\t/* no, here to service a socket descriptor */\n\twsi = wsi_from_fd(context, pollfd->fd);\n\tif (!wsi)\n\t\t/* not lws connection ... leave revents alone and return */\n\t\treturn 0;\n\n\t/*\n\t * so that caller can tell we handled, past here we need to\n\t * zero down pollfd->revents after handling\n\t */\n\n\t/* handle session socket closed */\n\n\tif ((!(pollfd->revents & pollfd->events & LWS_POLLIN)) &&\n\t    (pollfd->revents & LWS_POLLHUP)) {\n\t\twsi->socket_is_permanently_unusable = 1;\n\t\tlwsl_debug(\"Session Socket %p (fd=%d) dead\\n\",\n\t\t\t   (void *)wsi, pollfd->fd);\n\n\t\tgoto close_and_handled;\n\t}\n\n#ifdef _WIN32\n\tif (pollfd->revents & LWS_POLLOUT)\n\t\twsi->sock_send_blocking = FALSE;\n#endif\n\n\tif ((!(pollfd->revents & pollfd->events & LWS_POLLIN)) &&\n\t    (pollfd->revents & LWS_POLLHUP)) {\n\t\tlwsl_debug(\"pollhup\\n\");\n\t\twsi->socket_is_permanently_unusable = 1;\n\t\tgoto close_and_handled;\n\t}\n\n#if defined(LWS_WITH_TLS)\n\tif (lwsi_state(wsi) == LRS_SHUTDOWN &&\n\t    lws_is_ssl(wsi) && wsi->tls.ssl) {\n\t\tswitch (__lws_tls_shutdown(wsi)) {\n\t\tcase LWS_SSL_CAPABLE_DONE:\n\t\tcase LWS_SSL_CAPABLE_ERROR:\n\t\t\tgoto close_and_handled;\n\n\t\tcase LWS_SSL_CAPABLE_MORE_SERVICE_READ:\n\t\tcase LWS_SSL_CAPABLE_MORE_SERVICE_WRITE:\n\t\tcase LWS_SSL_CAPABLE_MORE_SERVICE:\n\t\t\tgoto handled;\n\t\t}\n\t}\n#endif\n\twsi->could_have_pending = 0; /* clear back-to-back write detection */\n\n\t/* okay, what we came here to do... */\n\n\t/* if we got here, we should have wire protocol ops set on the wsi */\n\tassert(wsi->role_ops);\n\n\t// lwsl_notice(\"%s: %s: wsistate 0x%x\\n\", __func__, wsi->role_ops->name,\n\t//\t    wsi->wsistate);\n\n\tswitch ((wsi->role_ops->handle_POLLIN)(pt, wsi, pollfd)) {\n\tcase LWS_HPI_RET_WSI_ALREADY_DIED:\n\t\treturn 1;\n\tcase LWS_HPI_RET_HANDLED:\n\t\tbreak;\n\tcase LWS_HPI_RET_PLEASE_CLOSE_ME:\nclose_and_handled:\n\t\tlwsl_debug(\"%p: Close and handled\\n\", wsi);\n\t\tlws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS,\n\t\t\t\t   \"close_and_handled\");\n#if defined(_DEBUG) && defined(LWS_WITH_LIBUV)\n\t\t/*\n\t\t * confirm close has no problem being called again while\n\t\t * it waits for libuv service to complete the first async\n\t\t * close\n\t\t */\n\t\tif (context->event_loop_ops == &event_loop_ops_uv)\n\t\t\tlws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS,\n\t\t\t\t\t   \"close_and_handled uv repeat test\");\n#endif\n\t\t/*\n\t\t * pollfd may point to something else after the close\n\t\t * due to pollfd swapping scheme on delete on some platforms\n\t\t * we can't clear revents now because it'd be the wrong guy's\n\t\t * revents\n\t\t */\n\t\treturn 1;\n\tdefault:\n\t\tassert(0);\n\t}\n#if defined(LWS_WITH_TLS)\nhandled:\n#endif\n\tpollfd->revents = 0;\n\n\tlws_pt_lock(pt, __func__);\n\t__lws_hrtimer_service(pt);\n\tlws_pt_unlock(pt);\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\nlws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd)\n{\n\treturn lws_service_fd_tsi(context, pollfd, 0);\n}\n\nLWS_VISIBLE int\nlws_service(struct lws_context *context, int timeout_ms)\n{\n\tstruct lws_context_per_thread *pt = &context->pt[0];\n\tint n;\n\n\tif (!context)\n\t\treturn 1;\n\n\tpt->inside_service = 1;\n\n\tif (context->event_loop_ops->run_pt) {\n\t\t/* we are configured for an event loop */\n\t\tcontext->event_loop_ops->run_pt(context, 0);\n\n\t\tpt->inside_service = 0;\n\n\t\treturn 1;\n\t}\n\tn = lws_plat_service(context, timeout_ms);\n\n\tpt->inside_service = 0;\n\n\treturn n;\n}\n\nLWS_VISIBLE int\nlws_service_tsi(struct lws_context *context, int timeout_ms, int tsi)\n{\n\tstruct lws_context_per_thread *pt = &context->pt[tsi];\n\tint n;\n\n\tpt->inside_service = 1;\n\n\tif (context->event_loop_ops->run_pt) {\n\t\t/* we are configured for an event loop */\n\t\tcontext->event_loop_ops->run_pt(context, tsi);\n\n\t\tpt->inside_service = 0;\n\n\t\treturn 1;\n\t}\n\n\tn = _lws_plat_service_tsi(context, timeout_ms, tsi);\n\n\tpt->inside_service = 0;\n\n\treturn n;\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/event-libs/poll/poll.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n *\n *  This is included from core/private.h if LWS_ROLE_WS\n */\n\n#include <core/private.h>\n\nstruct lws_event_loop_ops event_loop_ops_poll = {\n\t/* name */\t\t\t\"poll\",\n\t/* init_context */\t\tNULL,\n\t/* destroy_context1 */\t\tNULL,\n\t/* destroy_context2 */\t\tNULL,\n\t/* init_vhost_listen_wsi */\tNULL,\n\t/* init_pt */\t\t\tNULL,\n\t/* wsi_logical_close */\t\tNULL,\n\t/* check_client_connect_ok */\tNULL,\n\t/* close_handle_manually */\tNULL,\n\t/* accept */\t\t\tNULL,\n\t/* io */\t\t\tNULL,\n\t/* run */\t\t\tNULL,\n\t/* destroy_pt */\t\tNULL,\n\t/* destroy wsi */\t\tNULL,\n\n\t/* periodic_events_available */\t1,\n};"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/event-libs/poll/private.h",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n *\n */\n\nextern struct lws_event_loop_ops event_loop_ops_poll;\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/event-libs/private.h",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n *\n *  This is included from core/private.h\n */\n\nstruct lws_event_loop_ops {\n\tconst char *name;\n\t/* event loop-specific context init during context creation */\n\tint (*init_context)(struct lws_context *context,\n\t\t\t    const struct lws_context_creation_info *info);\n\t/* called during lws_destroy_context */\n\tint (*destroy_context1)(struct lws_context *context);\n\t/* called during lws_destroy_context2 */\n\tint (*destroy_context2)(struct lws_context *context);\n\t/* init vhost listening wsi */\n\tint (*init_vhost_listen_wsi)(struct lws *wsi);\n\t/* init the event loop for a pt */\n\tint (*init_pt)(struct lws_context *context, void *_loop, int tsi);\n\t/* called at end of first phase of close_free_wsi()  */\n\tint (*wsi_logical_close)(struct lws *wsi);\n\t/* return nonzero if client connect not allowed  */\n\tint (*check_client_connect_ok)(struct lws *wsi);\n\t/* close handle manually  */\n\tvoid (*close_handle_manually)(struct lws *wsi);\n\t/* event loop accept processing  */\n\tvoid (*accept)(struct lws *wsi);\n\t/* control wsi active events  */\n\tvoid (*io)(struct lws *wsi, int flags);\n\t/* run the event loop for a pt */\n\tvoid (*run_pt)(struct lws_context *context, int tsi);\n\t/* called before pt is destroyed */\n\tvoid (*destroy_pt)(struct lws_context *context, int tsi);\n\t/* called just before wsi is freed  */\n\tvoid (*destroy_wsi)(struct lws *wsi);\n\n\tunsigned int periodic_events_available:1;\n};\n\n/* bring in event libs private declarations */\n\n#if defined(LWS_WITH_POLL)\n#include \"event-libs/poll/private.h\"\n#endif\n\n#if defined(LWS_WITH_LIBUV)\n#include \"event-libs/libuv/private.h\"\n#endif\n\n#if defined(LWS_WITH_LIBEVENT)\n#include \"event-libs/libevent/private.h\"\n#endif\n\n#if defined(LWS_WITH_LIBEV)\n#include \"event-libs/libev/private.h\"\n#endif\n\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/libwebsockets.h",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n/** @file */\n\n#ifndef LIBWEBSOCKET_H_3060898B846849FF9F88F5DB59B5950C\n#define LIBWEBSOCKET_H_3060898B846849FF9F88F5DB59B5950C\n\n#ifdef __cplusplus\n#include <cstddef>\n#include <cstdarg>\n\nextern \"C\" {\n#else\n#include <stdarg.h>\n#endif\n\n#include <string.h>\n#include <stdlib.h>\n\n#include \"lws_config.h\"\n\n/*\n * CARE: everything using cmake defines needs to be below here\n */\n\n#if defined(LWS_HAS_INTPTR_T)\n#include <stdint.h>\n#define lws_intptr_t intptr_t\n#else\ntypedef unsigned long long lws_intptr_t;\n#endif\n\n#if defined(WIN32) || defined(_WIN32)\n#ifndef WIN32_LEAN_AND_MEAN\n#define WIN32_LEAN_AND_MEAN\n#endif\n\n#include <winsock2.h>\n#include <ws2tcpip.h>\n#include <stddef.h>\n#include <basetsd.h>\n#include <io.h>\n#ifndef _WIN32_WCE\n#include <fcntl.h>\n#else\n#define _O_RDONLY\t0x0000\n#define O_RDONLY\t_O_RDONLY\n#endif\n\n#define LWS_INLINE __inline\n#define LWS_VISIBLE\n#define LWS_WARN_UNUSED_RESULT\n#define LWS_WARN_DEPRECATED\n#define LWS_FORMAT(string_index)\n\n#ifdef LWS_DLL\n#ifdef LWS_INTERNAL\n#define LWS_EXTERN extern __declspec(dllexport)\n#else\n#define LWS_EXTERN extern __declspec(dllimport)\n#endif\n#else\n#define LWS_EXTERN\n#endif\n\n#define LWS_INVALID_FILE INVALID_HANDLE_VALUE\n#define LWS_O_RDONLY _O_RDONLY\n#define LWS_O_WRONLY _O_WRONLY\n#define LWS_O_CREAT _O_CREAT\n#define LWS_O_TRUNC _O_TRUNC\n\n#ifndef __func__\n#define __func__ __FUNCTION__\n#endif\n\n#else /* NOT WIN32 */\n#include <unistd.h>\n#if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)\n#include <sys/capability.h>\n#endif\n\n#if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__QNX__) || defined(__OpenBSD__)\n#include <sys/socket.h>\n#include <netinet/in.h>\n#endif\n\n#define LWS_INLINE inline\n#define LWS_O_RDONLY O_RDONLY\n#define LWS_O_WRONLY O_WRONLY\n#define LWS_O_CREAT O_CREAT\n#define LWS_O_TRUNC O_TRUNC\n\n#if !defined(LWS_PLAT_OPTEE) && !defined(OPTEE_TA) && !defined(LWS_WITH_ESP32)\n#include <poll.h>\n#include <netdb.h>\n#define LWS_INVALID_FILE -1\n#else\n#define getdtablesize() (30)\n#if defined(LWS_WITH_ESP32)\n#define LWS_INVALID_FILE NULL\n#else\n#define LWS_INVALID_FILE NULL\n#endif\n#endif\n\n#if defined(__GNUC__)\n\n/* warn_unused_result attribute only supported by GCC 3.4 or later */\n#if __GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)\n#define LWS_WARN_UNUSED_RESULT __attribute__((warn_unused_result))\n#else\n#define LWS_WARN_UNUSED_RESULT\n#endif\n\n#define LWS_VISIBLE __attribute__((visibility(\"default\")))\n#define LWS_WARN_DEPRECATED __attribute__ ((deprecated))\n#define LWS_FORMAT(string_index) __attribute__ ((format(printf, string_index, string_index+1)))\n#else\n#define LWS_VISIBLE\n#define LWS_WARN_UNUSED_RESULT\n#define LWS_WARN_DEPRECATED\n#define LWS_FORMAT(string_index)\n#endif\n\n#if defined(__ANDROID__)\n#include <netinet/in.h>\n#include <unistd.h>\n#define getdtablesize() sysconf(_SC_OPEN_MAX)\n#endif\n\n#endif\n\n#if defined(LWS_WITH_LIBEV)\n#include <ev.h>\n#endif /* LWS_WITH_LIBEV */\n#ifdef LWS_WITH_LIBUV\n#include <uv.h>\n#ifdef LWS_HAVE_UV_VERSION_H\n#include <uv-version.h>\n#endif\n#ifdef LWS_HAVE_NEW_UV_VERSION_H\n#include <uv/version.h>\n#endif\n#endif /* LWS_WITH_LIBUV */\n#if defined(LWS_WITH_LIBEVENT)\n#include <event2/event.h>\n#endif /* LWS_WITH_LIBEVENT */\n\n#ifndef LWS_EXTERN\n#define LWS_EXTERN extern\n#endif\n\n#ifdef _WIN32\n#define random rand\n#else\n#if !defined(OPTEE_TA)\n#include <sys/time.h>\n#include <unistd.h>\n#endif\n#endif\n\n#if defined(LWS_WITH_TLS)\n\n#ifdef USE_WOLFSSL\n#ifdef USE_OLD_CYASSL\n#ifdef _WIN32\n/*\n * Include user-controlled settings for windows from\n * <wolfssl-root>/IDE/WIN/user_settings.h\n */\n#include <IDE/WIN/user_settings.h>\n#include <cyassl/ctaocrypt/settings.h>\n#else\n#include <cyassl/options.h>\n#endif\n#include <cyassl/openssl/ssl.h>\n#include <cyassl/error-ssl.h>\n\n#else\n#ifdef _WIN32\n/*\n * Include user-controlled settings for windows from\n * <wolfssl-root>/IDE/WIN/user_settings.h\n */\n#include <IDE/WIN/user_settings.h>\n#include <wolfssl/wolfcrypt/settings.h>\n#else\n#include <wolfssl/options.h>\n#endif\n#include <wolfssl/openssl/ssl.h>\n#include <wolfssl/error-ssl.h>\n#endif /* not USE_OLD_CYASSL */\n#else\n#if defined(LWS_WITH_MBEDTLS)\n#if defined(LWS_WITH_ESP32)\n/* this filepath is passed to us but without quotes or <> */\n#undef MBEDTLS_CONFIG_FILE\n#define MBEDTLS_CONFIG_FILE <mbedtls/esp_config.h>\n#endif\n#include <mbedtls/ssl.h>\n#else\n#include <openssl/ssl.h>\n#if !defined(LWS_WITH_MBEDTLS)\n#include <openssl/err.h>\n#endif\n#endif\n#endif /* not USE_WOLFSSL */\n#endif\n\n/*\n * Helpers for pthread mutex in user code... if lws is built for\n * multiple service threads, these resolve to pthread mutex\n * operations.  In the case LWS_MAX_SMP is 1 (the default), they\n * are all NOPs and no pthread type or api is referenced.\n */\n\n#if LWS_MAX_SMP > 1\n\n#include <pthread.h>\n\n#define lws_pthread_mutex(name) pthread_mutex_t name;\n\nstatic LWS_INLINE void\nlws_pthread_mutex_init(pthread_mutex_t *lock)\n{\n\tpthread_mutex_init(lock, NULL);\n}\n\nstatic LWS_INLINE void\nlws_pthread_mutex_destroy(pthread_mutex_t *lock)\n{\n\tpthread_mutex_destroy(lock);\n}\n\nstatic LWS_INLINE void\nlws_pthread_mutex_lock(pthread_mutex_t *lock)\n{\n\tpthread_mutex_lock(lock);\n}\n\nstatic LWS_INLINE void\nlws_pthread_mutex_unlock(pthread_mutex_t *lock)\n{\n\tpthread_mutex_unlock(lock);\n}\n\n#else\n#define lws_pthread_mutex(name)\n#define lws_pthread_mutex_init(_a)\n#define lws_pthread_mutex_destroy(_a)\n#define lws_pthread_mutex_lock(_a)\n#define lws_pthread_mutex_unlock(_a)\n#endif\n\n\n#define CONTEXT_PORT_NO_LISTEN -1\n#define CONTEXT_PORT_NO_LISTEN_SERVER -2\n\n/** \\defgroup log Logging\n *\n * ##Logging\n *\n * Lws provides flexible and filterable logging facilities, which can be\n * used inside lws and in user code.\n *\n * Log categories may be individually filtered bitwise, and directed to built-in\n * sinks for syslog-compatible logging, or a user-defined function.\n */\n///@{\n\nenum lws_log_levels {\n\tLLL_ERR = 1 << 0,\n\tLLL_WARN = 1 << 1,\n\tLLL_NOTICE = 1 << 2,\n\tLLL_INFO = 1 << 3,\n\tLLL_DEBUG = 1 << 4,\n\tLLL_PARSER = 1 << 5,\n\tLLL_HEADER = 1 << 6,\n\tLLL_EXT = 1 << 7,\n\tLLL_CLIENT = 1 << 8,\n\tLLL_LATENCY = 1 << 9,\n\tLLL_USER = 1 << 10,\n\n\tLLL_COUNT = 11 /* set to count of valid flags */\n};\n\nLWS_VISIBLE LWS_EXTERN void _lws_log(int filter, const char *format, ...) LWS_FORMAT(2);\nLWS_VISIBLE LWS_EXTERN void _lws_logv(int filter, const char *format, va_list vl);\n/**\n * lwsl_timestamp: generate logging timestamp string\n *\n * \\param level:\tlogging level\n * \\param p:\t\tchar * buffer to take timestamp\n * \\param len:\tlength of p\n *\n * returns length written in p\n */\nLWS_VISIBLE LWS_EXTERN int\nlwsl_timestamp(int level, char *p, int len);\n\n/* these guys are unconditionally included */\n\n#define lwsl_err(...) _lws_log(LLL_ERR, __VA_ARGS__)\n#define lwsl_user(...) _lws_log(LLL_USER, __VA_ARGS__)\n\n#if !defined(LWS_WITH_NO_LOGS)\n/* notice and warn are usually included by being compiled in */\n#define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)\n#define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)\n#endif\n/*\n *  weaker logging can be deselected by telling CMake to build in RELEASE mode\n *  that gets rid of the overhead of checking while keeping _warn and _err\n *  active\n */\n\n#ifdef _DEBUG\n#if defined(LWS_WITH_NO_LOGS)\n/* notice, warn and log are always compiled in */\n#define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)\n#define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)\n#endif\n#define lwsl_info(...) _lws_log(LLL_INFO, __VA_ARGS__)\n#define lwsl_debug(...) _lws_log(LLL_DEBUG, __VA_ARGS__)\n#define lwsl_parser(...) _lws_log(LLL_PARSER, __VA_ARGS__)\n#define lwsl_header(...)  _lws_log(LLL_HEADER, __VA_ARGS__)\n#define lwsl_ext(...)  _lws_log(LLL_EXT, __VA_ARGS__)\n#define lwsl_client(...) _lws_log(LLL_CLIENT, __VA_ARGS__)\n#define lwsl_latency(...) _lws_log(LLL_LATENCY, __VA_ARGS__)\n\n#else /* no debug */\n#if defined(LWS_WITH_NO_LOGS)\n#define lwsl_warn(...) do {} while(0)\n#define lwsl_notice(...) do {} while(0)\n#endif\n#define lwsl_info(...) do {} while(0)\n#define lwsl_debug(...) do {} while(0)\n#define lwsl_parser(...) do {} while(0)\n#define lwsl_header(...) do {} while(0)\n#define lwsl_ext(...) do {} while(0)\n#define lwsl_client(...) do {} while(0)\n#define lwsl_latency(...) do {} while(0)\n\n#endif\n\n#define lwsl_hexdump_err(...) lwsl_hexdump_level(LLL_ERR, __VA_ARGS__)\n#define lwsl_hexdump_warn(...) lwsl_hexdump_level(LLL_WARN, __VA_ARGS__)\n#define lwsl_hexdump_notice(...) lwsl_hexdump_level(LLL_NOTICE, __VA_ARGS__)\n#define lwsl_hexdump_info(...) lwsl_hexdump_level(LLL_INFO, __VA_ARGS__)\n#define lwsl_hexdump_debug(...) lwsl_hexdump_level(LLL_DEBUG, __VA_ARGS__)\n\n/**\n * lwsl_hexdump_level() - helper to hexdump a buffer at a selected debug level\n *\n * \\param level: one of LLL_ constants\n * \\param vbuf: buffer start to dump\n * \\param len: length of buffer to dump\n *\n * If \\p level is visible, does a nice hexdump -C style dump of \\p vbuf for\n * \\p len bytes.  This can be extremely convenient while debugging.\n */\nLWS_VISIBLE LWS_EXTERN void\nlwsl_hexdump_level(int level, const void *vbuf, size_t len);\n\n/**\n * lwsl_hexdump() - helper to hexdump a buffer (DEBUG builds only)\n *\n * \\param buf: buffer start to dump\n * \\param len: length of buffer to dump\n *\n * Calls through to lwsl_hexdump_level(LLL_DEBUG, ... for compatability.\n * It's better to use lwsl_hexdump_level(level, ... directly so you can control\n * the visibility.\n */\nLWS_VISIBLE LWS_EXTERN void\nlwsl_hexdump(const void *buf, size_t len);\n\n/**\n * lws_is_be() - returns nonzero if the platform is Big Endian\n */\nstatic LWS_INLINE int lws_is_be(void) {\n\tconst int probe = ~0xff;\n\n\treturn *(const char *)&probe;\n}\n\n/**\n * lws_set_log_level() - Set the logging bitfield\n * \\param level:\tOR together the LLL_ debug contexts you want output from\n * \\param log_emit_function:\tNULL to leave it as it is, or a user-supplied\n *\t\t\tfunction to perform log string emission instead of\n *\t\t\tthe default stderr one.\n *\n *\tlog level defaults to \"err\", \"warn\" and \"notice\" contexts enabled and\n *\temission on stderr.  If stderr is a tty (according to isatty()) then\n *\tthe output is coloured according to the log level using ANSI escapes.\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_set_log_level(int level,\n\t\t  void (*log_emit_function)(int level, const char *line));\n\n/**\n * lwsl_emit_syslog() - helper log emit function writes to system log\n *\n * \\param level: one of LLL_ log level indexes\n * \\param line: log string\n *\n * You use this by passing the function pointer to lws_set_log_level(), to set\n * it as the log emit function, it is not called directly.\n */\nLWS_VISIBLE LWS_EXTERN void\nlwsl_emit_syslog(int level, const char *line);\n\n/**\n * lwsl_visible() - returns true if the log level should be printed\n *\n * \\param level: one of LLL_ log level indexes\n *\n * This is useful if you have to do work to generate the log content, you\n * can skip the work if the log level used to print it is not actually\n * enabled at runtime.\n */\nLWS_VISIBLE LWS_EXTERN int\nlwsl_visible(int level);\n\n///@}\n\n\n#include <stddef.h>\n\n#ifndef lws_container_of\n#define lws_container_of(P,T,M)\t((T *)((char *)(P) - offsetof(T, M)))\n#endif\n\nstruct lws;\n\ntypedef int64_t lws_usec_t;\n\n/* api change list for user code to test against */\n\n#define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_ARG\n\n/* the struct lws_protocols has the id field present */\n#define LWS_FEATURE_PROTOCOLS_HAS_ID_FIELD\n\n/* you can call lws_get_peer_write_allowance */\n#define LWS_FEATURE_PROTOCOLS_HAS_PEER_WRITE_ALLOWANCE\n\n/* extra parameter introduced in 917f43ab821 */\n#define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_LEN\n\n/* File operations stuff exists */\n#define LWS_FEATURE_FOPS\n\n\n#if defined(_WIN32)\ntypedef SOCKET lws_sockfd_type;\ntypedef HANDLE lws_filefd_type;\n\nstruct lws_pollfd {\n\tlws_sockfd_type fd; /**< file descriptor */\n\tSHORT events; /**< which events to respond to */\n\tSHORT revents; /**< which events happened */\n};\n#define LWS_POLLHUP (FD_CLOSE)\n#define LWS_POLLIN (FD_READ | FD_ACCEPT)\n#define LWS_POLLOUT (FD_WRITE)\n#else\n\n\n#if defined(LWS_WITH_ESP32)\n\ntypedef int lws_sockfd_type;\ntypedef int lws_filefd_type;\n\nstruct pollfd {\n\tlws_sockfd_type fd; /**< fd related to */\n\tshort events; /**< which POLL... events to respond to */\n\tshort revents; /**< which POLL... events occurred */\n};\n#define POLLIN\t\t0x0001\n#define POLLPRI\t\t0x0002\n#define POLLOUT\t\t0x0004\n#define POLLERR\t\t0x0008\n#define POLLHUP\t\t0x0010\n#define POLLNVAL\t0x0020\n\n#include <freertos/FreeRTOS.h>\n#include <freertos/event_groups.h>\n#include <string.h>\n#include \"esp_wifi.h\"\n#include \"esp_system.h\"\n#include \"esp_event.h\"\n#include \"esp_event_loop.h\"\n#include \"nvs.h\"\n#include \"driver/gpio.h\"\n#include \"esp_spi_flash.h\"\n#include \"freertos/timers.h\"\n\n#if !defined(CONFIG_FREERTOS_HZ)\n#define CONFIG_FREERTOS_HZ 100\n#endif\n\ntypedef TimerHandle_t uv_timer_t;\ntypedef void uv_cb_t(uv_timer_t *);\ntypedef void * uv_handle_t;\n\nstruct timer_mapping {\n\tuv_cb_t *cb;\n\tuv_timer_t *t;\n};\n\n#define UV_VERSION_MAJOR 1\n\n#define lws_uv_getloop(a, b) (NULL)\n\nstatic LWS_INLINE void uv_timer_init(void *l, uv_timer_t *t)\n{\n\t(void)l;\n\t*t = NULL;\n}\n\nextern void esp32_uvtimer_cb(TimerHandle_t t);\n\nstatic LWS_INLINE void uv_timer_start(uv_timer_t *t, uv_cb_t *cb, int first, int rep)\n{\n\tstruct timer_mapping *tm = (struct timer_mapping *)malloc(sizeof(*tm));\n\n\tif (!tm)\n\t\treturn;\n\n\ttm->t = t;\n\ttm->cb = cb;\n\n\t*t = xTimerCreate(\"x\", pdMS_TO_TICKS(first), !!rep, tm,\n\t\t\t  (TimerCallbackFunction_t)esp32_uvtimer_cb);\n\txTimerStart(*t, 0);\n}\n\nstatic LWS_INLINE void uv_timer_stop(uv_timer_t *t)\n{\n\txTimerStop(*t, 0);\n}\n\nstatic LWS_INLINE void uv_close(uv_handle_t *h, void *v)\n{\n\tfree(pvTimerGetTimerID((uv_timer_t)h));\n\txTimerDelete(*(uv_timer_t *)h, 0);\n}\n\n/* ESP32 helper declarations */\n\n#include <mdns.h>\n#include <esp_partition.h>\n\n#define LWS_PLUGIN_STATIC\n#define LWS_MAGIC_REBOOT_TYPE_ADS 0x50001ffc\n#define LWS_MAGIC_REBOOT_TYPE_REQ_FACTORY 0xb00bcafe\n#define LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY 0xfaceb00b\n#define LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY_BUTTON 0xf0cedfac\n\n\n/* user code provides these */\n\nextern void\nlws_esp32_identify_physical_device(void);\n\n/* lws-plat-esp32 provides these */\n\ntypedef void (*lws_cb_scan_done)(uint16_t count, wifi_ap_record_t *recs, void *arg);\n\nenum genled_state {\n\tLWSESP32_GENLED__INIT,\n\tLWSESP32_GENLED__LOST_NETWORK,\n\tLWSESP32_GENLED__NO_NETWORK,\n\tLWSESP32_GENLED__CONN_AP,\n\tLWSESP32_GENLED__GOT_IP,\n\tLWSESP32_GENLED__OK,\n};\n\nstruct lws_group_member {\n\tstruct lws_group_member *next;\n\tuint64_t last_seen;\n\tchar model[16];\n\tchar role[16];\n\tchar host[32];\n\tchar mac[20];\n\tint width, height;\n\tstruct ip4_addr addr;\n\tstruct ip6_addr addrv6;\n\tuint8_t\tflags;\n};\n\n#define LWS_SYSTEM_GROUP_MEMBER_ADD\t\t1\n#define LWS_SYSTEM_GROUP_MEMBER_CHANGE\t\t2\n#define LWS_SYSTEM_GROUP_MEMBER_REMOVE\t\t3\n\n#define LWS_GROUP_FLAG_SELF 1\n\nstruct lws_esp32 {\n\tchar sta_ip[16];\n\tchar sta_mask[16];\n\tchar sta_gw[16];\n\tchar serial[16];\n\tchar opts[16];\n\tchar model[16];\n\tchar group[16];\n\tchar role[16];\n\tchar ssid[4][64];\n\tchar password[4][64];\n\tchar active_ssid[64];\n\tchar access_pw[16];\n\tchar hostname[32];\n\tchar mac[20];\n\tchar le_dns[64];\n\tchar le_email[64];\n       \tchar region;\n       \tchar inet;\n\tchar conn_ap;\n\n\tenum genled_state genled;\n\tuint64_t genled_t;\n\n\tlws_cb_scan_done scan_consumer;\n\tvoid *scan_consumer_arg;\n\tstruct lws_group_member *first;\n\tint extant_group_members;\n\n\tchar acme;\n\tchar upload;\n\n\tvolatile char button_is_down;\n};\n\nstruct lws_esp32_image {\n\tuint32_t romfs;\n\tuint32_t romfs_len;\n\tuint32_t json;\n\tuint32_t json_len;\n};\n\nextern struct lws_esp32 lws_esp32;\nstruct lws_vhost;\n\nextern esp_err_t\nlws_esp32_event_passthru(void *ctx, system_event_t *event);\nextern void\nlws_esp32_wlan_config(void);\nextern void\nlws_esp32_wlan_start_ap(void);\nextern void\nlws_esp32_wlan_start_station(void);\nstruct lws_context_creation_info;\nextern void\nlws_esp32_set_creation_defaults(struct lws_context_creation_info *info);\nextern struct lws_context *\nlws_esp32_init(struct lws_context_creation_info *, struct lws_vhost **pvh);\nextern int\nlws_esp32_wlan_nvs_get(int retry);\nextern esp_err_t\nlws_nvs_set_str(nvs_handle handle, const char* key, const char* value);\nextern void\nlws_esp32_restart_guided(uint32_t type);\nextern const esp_partition_t *\nlws_esp_ota_get_boot_partition(void);\nextern int\nlws_esp32_get_image_info(const esp_partition_t *part, struct lws_esp32_image *i, char *json, int json_len);\nextern int\nlws_esp32_leds_network_indication(void);\n\nextern uint32_t lws_esp32_get_reboot_type(void);\nextern uint16_t lws_esp32_sine_interp(int n);\n\n/* required in external code by esp32 plat (may just return if no leds) */\nextern void lws_esp32_leds_timer_cb(TimerHandle_t th);\n#else\ntypedef int lws_sockfd_type;\ntypedef int lws_filefd_type;\n#endif\n\n#define lws_pollfd pollfd\n#define LWS_POLLHUP (POLLHUP|POLLERR)\n#define LWS_POLLIN (POLLIN)\n#define LWS_POLLOUT (POLLOUT)\n#endif\n\n\n#if (defined(WIN32) || defined(_WIN32)) && !defined(__MINGW32__)\n/* ... */\n#define ssize_t SSIZE_T\n#endif\n\n#if defined(WIN32) && defined(LWS_HAVE__STAT32I64)\n#include <sys/types.h>\n#include <sys/stat.h>\n#endif\n\n#if defined(LWS_HAVE_STDINT_H)\n#include <stdint.h>\n#else\n#if defined(WIN32) || defined(_WIN32)\n/* !!! >:-[  */\ntypedef unsigned __int32 uint32_t;\ntypedef unsigned __int16 uint16_t;\ntypedef unsigned __int8 uint8_t;\n#else\ntypedef unsigned int uint32_t;\ntypedef unsigned short uint16_t;\ntypedef unsigned char uint8_t;\n#endif\n#endif\n\ntypedef unsigned long long lws_filepos_t;\ntypedef long long lws_fileofs_t;\ntypedef uint32_t lws_fop_flags_t;\n\n/** struct lws_pollargs - argument structure for all external poll related calls\n * passed in via 'in' */\nstruct lws_pollargs {\n\tlws_sockfd_type fd;\t/**< applicable socket descriptor */\n\tint events;\t\t/**< the new event mask */\n\tint prev_events;\t/**< the previous event mask */\n};\n\nstruct lws_tokens;\nstruct lws_token_limits;\n\n/*! \\defgroup wsclose Websocket Close\n *\n * ##Websocket close frame control\n *\n * When we close a ws connection, we can send a reason code and a short\n * UTF-8 description back with the close packet.\n */\n///@{\n\n/*\n * NOTE: These public enums are part of the abi.  If you want to add one,\n * add it at where specified so existing users are unaffected.\n */\n/** enum lws_close_status - RFC6455 close status codes */\nenum lws_close_status {\n\tLWS_CLOSE_STATUS_NOSTATUS\t\t\t\t=    0,\n\tLWS_CLOSE_STATUS_NORMAL\t\t\t\t\t= 1000,\n\t/**< 1000 indicates a normal closure, meaning that the purpose for\n      which the connection was established has been fulfilled. */\n\tLWS_CLOSE_STATUS_GOINGAWAY\t\t\t\t= 1001,\n\t/**< 1001 indicates that an endpoint is \"going away\", such as a server\n      going down or a browser having navigated away from a page. */\n\tLWS_CLOSE_STATUS_PROTOCOL_ERR\t\t\t\t= 1002,\n\t/**< 1002 indicates that an endpoint is terminating the connection due\n      to a protocol error. */\n\tLWS_CLOSE_STATUS_UNACCEPTABLE_OPCODE\t\t\t= 1003,\n\t/**< 1003 indicates that an endpoint is terminating the connection\n      because it has received a type of data it cannot accept (e.g., an\n      endpoint that understands only text data MAY send this if it\n      receives a binary message). */\n\tLWS_CLOSE_STATUS_RESERVED\t\t\t\t= 1004,\n\t/**< Reserved.  The specific meaning might be defined in the future. */\n\tLWS_CLOSE_STATUS_NO_STATUS\t\t\t\t= 1005,\n\t/**< 1005 is a reserved value and MUST NOT be set as a status code in a\n      Close control frame by an endpoint.  It is designated for use in\n      applications expecting a status code to indicate that no status\n      code was actually present. */\n\tLWS_CLOSE_STATUS_ABNORMAL_CLOSE\t\t\t\t= 1006,\n\t/**< 1006 is a reserved value and MUST NOT be set as a status code in a\n      Close control frame by an endpoint.  It is designated for use in\n      applications expecting a status code to indicate that the\n      connection was closed abnormally, e.g., without sending or\n      receiving a Close control frame. */\n\tLWS_CLOSE_STATUS_INVALID_PAYLOAD\t\t\t= 1007,\n\t/**< 1007 indicates that an endpoint is terminating the connection\n      because it has received data within a message that was not\n      consistent with the type of the message (e.g., non-UTF-8 [RFC3629]\n      data within a text message). */\n\tLWS_CLOSE_STATUS_POLICY_VIOLATION\t\t\t= 1008,\n\t/**< 1008 indicates that an endpoint is terminating the connection\n      because it has received a message that violates its policy.  This\n      is a generic status code that can be returned when there is no\n      other more suitable status code (e.g., 1003 or 1009) or if there\n      is a need to hide specific details about the policy. */\n\tLWS_CLOSE_STATUS_MESSAGE_TOO_LARGE\t\t\t= 1009,\n\t/**< 1009 indicates that an endpoint is terminating the connection\n      because it has received a message that is too big for it to\n      process. */\n\tLWS_CLOSE_STATUS_EXTENSION_REQUIRED\t\t\t= 1010,\n\t/**< 1010 indicates that an endpoint (client) is terminating the\n      connection because it has expected the server to negotiate one or\n      more extension, but the server didn't return them in the response\n      message of the WebSocket handshake.  The list of extensions that\n      are needed SHOULD appear in the /reason/ part of the Close frame.\n      Note that this status code is not used by the server, because it\n      can fail the WebSocket handshake instead */\n\tLWS_CLOSE_STATUS_UNEXPECTED_CONDITION\t\t\t= 1011,\n\t/**< 1011 indicates that a server is terminating the connection because\n      it encountered an unexpected condition that prevented it from\n      fulfilling the request. */\n\tLWS_CLOSE_STATUS_TLS_FAILURE\t\t\t\t= 1015,\n\t/**< 1015 is a reserved value and MUST NOT be set as a status code in a\n      Close control frame by an endpoint.  It is designated for use in\n      applications expecting a status code to indicate that the\n      connection was closed due to a failure to perform a TLS handshake\n      (e.g., the server certificate can't be verified). */\n\n\tLWS_CLOSE_STATUS_CLIENT_TRANSACTION_DONE\t\t= 2000,\n\n\t/****** add new things just above ---^ ******/\n\n\tLWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY\t\t= 9999,\n};\n\n/**\n * lws_close_reason - Set reason and aux data to send with Close packet\n *\t\tIf you are going to return nonzero from the callback\n *\t\trequesting the connection to close, you can optionally\n *\t\tcall this to set the reason the peer will be told if\n *\t\tpossible.\n *\n * \\param wsi:\tThe websocket connection to set the close reason on\n * \\param status:\tA valid close status from websocket standard\n * \\param buf:\tNULL or buffer containing up to 124 bytes of auxiliary data\n * \\param len:\tLength of data in \\param buf to send\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_close_reason(struct lws *wsi, enum lws_close_status status,\n\t\t unsigned char *buf, size_t len);\n\n///@}\n\nstruct lws;\nstruct lws_context;\n/* needed even with extensions disabled for create context */\nstruct lws_extension;\n\n\n/*! \\defgroup usercb User Callback\n *\n * ##User protocol callback\n *\n * The protocol callback is the primary way lws interacts with\n * user code.  For one of a list of a few dozen reasons the callback gets\n * called at some event to be handled.\n *\n * All of the events can be ignored, returning 0 is taken as \"OK\" and returning\n * nonzero in most cases indicates that the connection should be closed.\n */\n///@{\n\nstruct lws_ssl_info {\n\tint where;\n\tint ret;\n};\n\nenum lws_cert_update_state {\n\tLWS_CUS_IDLE,\n\tLWS_CUS_STARTING,\n\tLWS_CUS_SUCCESS,\n\tLWS_CUS_FAILED,\n\n\tLWS_CUS_CREATE_KEYS,\n\tLWS_CUS_REG,\n\tLWS_CUS_AUTH,\n\tLWS_CUS_CHALLENGE,\n\tLWS_CUS_CREATE_REQ,\n\tLWS_CUS_REQ,\n\tLWS_CUS_CONFIRM,\n\tLWS_CUS_ISSUE,\n};\n\nenum {\n\tLWS_TLS_REQ_ELEMENT_COUNTRY,\n\tLWS_TLS_REQ_ELEMENT_STATE,\n\tLWS_TLS_REQ_ELEMENT_LOCALITY,\n\tLWS_TLS_REQ_ELEMENT_ORGANIZATION,\n\tLWS_TLS_REQ_ELEMENT_COMMON_NAME,\n\tLWS_TLS_REQ_ELEMENT_EMAIL,\n\n\tLWS_TLS_REQ_ELEMENT_COUNT,\n\n\tLWS_TLS_SET_DIR_URL = LWS_TLS_REQ_ELEMENT_COUNT,\n\tLWS_TLS_SET_AUTH_PATH,\n\tLWS_TLS_SET_CERT_PATH,\n\tLWS_TLS_SET_KEY_PATH,\n\n\tLWS_TLS_TOTAL_COUNT\n};\n\nstruct lws_acme_cert_aging_args {\n\tstruct lws_vhost *vh;\n\tconst char *element_overrides[LWS_TLS_TOTAL_COUNT]; /* NULL = use pvo */\n};\n\n/*\n * NOTE: These public enums are part of the abi.  If you want to add one,\n * add it at where specified so existing users are unaffected.\n */\n/** enum lws_callback_reasons - reason you're getting a protocol callback */\nenum lws_callback_reasons {\n\n\t/* ---------------------------------------------------------------------\n\t * ----- Callbacks related to wsi and protocol binding lifecycle -----\n\t */\n\n\tLWS_CALLBACK_PROTOCOL_INIT\t\t\t\t= 27,\n\t/**< One-time call per protocol, per-vhost using it, so it can\n\t * do initial setup / allocations etc */\n\n\tLWS_CALLBACK_PROTOCOL_DESTROY\t\t\t\t= 28,\n\t/**< One-time call per protocol, per-vhost using it, indicating\n\t * this protocol won't get used at all after this callback, the\n\t * vhost is getting destroyed.  Take the opportunity to\n\t * deallocate everything that was allocated by the protocol. */\n\n\tLWS_CALLBACK_WSI_CREATE\t\t\t\t\t= 29,\n\t/**< outermost (earliest) wsi create notification to protocols[0] */\n\n\tLWS_CALLBACK_WSI_DESTROY\t\t\t\t= 30,\n\t/**< outermost (latest) wsi destroy notification to protocols[0] */\n\n\tLWS_CALLBACK_HTTP_BIND_PROTOCOL\t\t\t\t= 49,\n\t/**< By default, all HTTP handling is done in protocols[0].\n\t * However you can bind different protocols (by name) to\n\t * different parts of the URL space using callback mounts.  This\n\t * callback occurs in the new protocol when a wsi is bound\n\t * to that protocol.  Any protocol allocation related to the\n\t * http transaction processing should be created then.\n\t * These specific callbacks are necessary because with HTTP/1.1,\n\t * a single connection may perform at series of different\n\t * transactions at different URLs, thus the lifetime of the\n\t * protocol bind is just for one transaction, not connection. */\n\n\tLWS_CALLBACK_HTTP_DROP_PROTOCOL\t\t\t\t= 50,\n\t/**< This is called when a transaction is unbound from a protocol.\n\t * It indicates the connection completed its transaction and may\n\t * do something different now.  Any protocol allocation related\n\t * to the http transaction processing should be destroyed. */\n\n\t/* ---------------------------------------------------------------------\n\t * ----- Callbacks related to Server TLS -----\n\t */\n\n\tLWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS\t= 21,\n\t/**< if configured for\n\t * including OpenSSL support, this callback allows your user code\n\t * to perform extra SSL_CTX_load_verify_locations() or similar\n\t * calls to direct OpenSSL where to find certificates the client\n\t * can use to confirm the remote server identity.  user is the\n\t * OpenSSL SSL_CTX* */\n\n\tLWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS\t= 22,\n\t/**< if configured for\n\t * including OpenSSL support, this callback allows your user code\n\t * to load extra certificates into the server which allow it to\n\t * verify the validity of certificates returned by clients.  user\n\t * is the server's OpenSSL SSL_CTX* and in is the lws_vhost */\n\n\tLWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION\t= 23,\n\t/**< if the libwebsockets vhost was created with the option\n\t * LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this\n\t * callback is generated during OpenSSL verification of the cert\n\t * sent from the client.  It is sent to protocol[0] callback as\n\t * no protocol has been negotiated on the connection yet.\n\t * Notice that the libwebsockets context and wsi are both NULL\n\t * during this callback.  See\n\t *  http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html\n\t * to understand more detail about the OpenSSL callback that\n\t * generates this libwebsockets callback and the meanings of the\n\t * arguments passed.  In this callback, user is the x509_ctx,\n\t * in is the ssl pointer and len is preverify_ok\n\t * Notice that this callback maintains libwebsocket return\n\t * conventions, return 0 to mean the cert is OK or 1 to fail it.\n\t * This also means that if you don't handle this callback then\n\t * the default callback action of returning 0 allows the client\n\t * certificates. */\n\n\tLWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY\t= 37,\n\t/**< if configured for including OpenSSL support but no private key\n\t * file has been specified (ssl_private_key_filepath is NULL), this is\n\t * called to allow the user to set the private key directly via\n\t * libopenssl and perform further operations if required; this might be\n\t * useful in situations where the private key is not directly accessible\n\t * by the OS, for example if it is stored on a smartcard.\n\t * user is the server's OpenSSL SSL_CTX* */\n\n\tLWS_CALLBACK_SSL_INFO\t\t\t\t\t= 67,\n\t/**< SSL connections only.  An event you registered an\n\t * interest in at the vhost has occurred on a connection\n\t * using the vhost.  in is a pointer to a\n\t * struct lws_ssl_info containing information about the\n\t * event*/\n\n\t/* ---------------------------------------------------------------------\n\t * ----- Callbacks related to Client TLS -----\n\t */\n\n\tLWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION = 58,\n\t/**< Similar to LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION\n\t * this callback is called during OpenSSL verification of the cert\n\t * sent from the server to the client. It is sent to protocol[0]\n\t * callback as no protocol has been negotiated on the connection yet.\n\t * Notice that the wsi is set because lws_client_connect_via_info was\n\t * successful.\n\t *\n\t * See http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html\n\t * to understand more detail about the OpenSSL callback that\n\t * generates this libwebsockets callback and the meanings of the\n\t * arguments passed. In this callback, user is the x509_ctx,\n\t * in is the ssl pointer and len is preverify_ok.\n\t *\n\t * THIS IS NOT RECOMMENDED BUT if a cert validation error shall be\n\t * overruled and cert shall be accepted as ok,\n\t * X509_STORE_CTX_set_error((X509_STORE_CTX*)user, X509_V_OK); must be\n\t * called and return value must be 0 to mean the cert is OK;\n\t * returning 1 will fail the cert in any case.\n\t *\n\t * This also means that if you don't handle this callback then\n\t * the default callback action of returning 0 will not accept the\n\t * certificate in case of a validation error decided by the SSL lib.\n\t *\n\t * This is expected and secure behaviour when validating certificates.\n\t *\n\t * Note: LCCSCF_ALLOW_SELFSIGNED and\n\t * LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK still work without this\n\t * callback being implemented.\n\t */\n\n\t/* ---------------------------------------------------------------------\n\t * ----- Callbacks related to HTTP Server  -----\n\t */\n\n\tLWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED\t\t= 19,\n\t/**< A new client has been accepted by the ws server.  This\n\t * callback allows setting any relevant property to it. Because this\n\t * happens immediately after the instantiation of a new client,\n\t * there's no websocket protocol selected yet so this callback is\n\t * issued only to protocol 0. Only wsi is defined, pointing to the\n\t * new client, and the return value is ignored. */\n\n\tLWS_CALLBACK_HTTP\t\t\t\t\t= 12,\n\t/**< an http request has come from a client that is not\n\t * asking to upgrade the connection to a websocket\n\t * one.  This is a chance to serve http content,\n\t * for example, to send a script to the client\n\t * which will then open the websockets connection.\n\t * in points to the URI path requested and\n\t * lws_serve_http_file() makes it very\n\t * simple to send back a file to the client.\n\t * Normally after sending the file you are done\n\t * with the http connection, since the rest of the\n\t * activity will come by websockets from the script\n\t * that was delivered by http, so you will want to\n\t * return 1; to close and free up the connection. */\n\n\tLWS_CALLBACK_HTTP_BODY\t\t\t\t\t= 13,\n\t/**< the next len bytes data from the http\n\t * request body HTTP connection is now available in in. */\n\n\tLWS_CALLBACK_HTTP_BODY_COMPLETION\t\t\t= 14,\n\t/**< the expected amount of http request body has been delivered */\n\n\tLWS_CALLBACK_HTTP_FILE_COMPLETION\t\t\t= 15,\n\t/**< a file requested to be sent down http link has completed. */\n\n\tLWS_CALLBACK_HTTP_WRITEABLE\t\t\t\t= 16,\n\t/**< you can write more down the http protocol link now. */\n\n\tLWS_CALLBACK_CLOSED_HTTP\t\t\t\t=  5,\n\t/**< when a HTTP (non-websocket) session ends */\n\n\tLWS_CALLBACK_FILTER_HTTP_CONNECTION\t\t\t= 18,\n\t/**< called when the request has\n\t * been received and parsed from the client, but the response is\n\t * not sent yet.  Return non-zero to disallow the connection.\n\t * user is a pointer to the connection user space allocation,\n\t * in is the URI, eg, \"/\"\n\t * In your handler you can use the public APIs\n\t * lws_hdr_total_length() / lws_hdr_copy() to access all of the\n\t * headers using the header enums lws_token_indexes from\n\t * libwebsockets.h to check for and read the supported header\n\t * presence and content before deciding to allow the http\n\t * connection to proceed or to kill the connection. */\n\n\tLWS_CALLBACK_ADD_HEADERS\t\t\t\t= 53,\n\t/**< This gives your user code a chance to add headers to a server\n\t * transaction bound to your protocol.  `in` points to a\n\t * `struct lws_process_html_args` describing a buffer and length\n\t * you can add headers into using the normal lws apis.\n\t *\n\t * (see LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER to add headers to\n\t * a client transaction)\n\t *\n\t * Only `args->p` and `args->len` are valid, and `args->p` should\n\t * be moved on by the amount of bytes written, if any.  Eg\n\t *\n\t * \tcase LWS_CALLBACK_ADD_HEADERS:\n\t *\n\t *          struct lws_process_html_args *args =\n\t *          \t\t(struct lws_process_html_args *)in;\n\t *\n\t *\t    if (lws_add_http_header_by_name(wsi,\n\t *\t\t\t(unsigned char *)\"set-cookie:\",\n\t *\t\t\t(unsigned char *)cookie, cookie_len,\n\t *\t\t\t(unsigned char **)&args->p,\n\t *\t\t\t(unsigned char *)args->p + args->max_len))\n\t *\t\treturn 1;\n\t *\n\t *          break;\n\t */\n\n\tLWS_CALLBACK_CHECK_ACCESS_RIGHTS\t\t\t= 51,\n\t/**< This gives the user code a chance to forbid an http access.\n\t * `in` points to a `struct lws_process_html_args`, which\n\t * describes the URL, and a bit mask describing the type of\n\t * authentication required.  If the callback returns nonzero,\n\t * the transaction ends with HTTP_STATUS_UNAUTHORIZED. */\n\n\tLWS_CALLBACK_PROCESS_HTML\t\t\t\t= 52,\n\t/**< This gives your user code a chance to mangle outgoing\n\t * HTML.  `in` points to a `struct lws_process_html_args`\n\t * which describes the buffer containing outgoing HTML.\n\t * The buffer may grow up to `.max_len` (currently +128\n\t * bytes per buffer).\n\t */\n\n\t/* ---------------------------------------------------------------------\n\t * ----- Callbacks related to HTTP Client  -----\n\t */\n\n\tLWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\t\t\t= 44,\n\t/**< The HTTP client connection has succeeded, and is now\n\t * connected to the server */\n\n\tLWS_CALLBACK_CLOSED_CLIENT_HTTP\t\t\t\t= 45,\n\t/**< The HTTP client connection is closing */\n\n\tLWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ\t\t\t= 48,\n\t/**< This is generated by lws_http_client_read() used to drain\n\t * incoming data.  In the case the incoming data was chunked, it will\n\t * be split into multiple smaller callbacks for each chunk block,\n\t * removing the chunk headers. If not chunked, it will appear all in\n\t * one callback. */\n\n\tLWS_CALLBACK_RECEIVE_CLIENT_HTTP\t\t\t= 46,\n\t/**< This simply indicates data was received on the HTTP client\n\t * connection.  It does NOT drain or provide the data.\n\t * This exists to neatly allow a proxying type situation,\n\t * where this incoming data will go out on another connection.\n\t * If the outgoing connection stalls, we should stall processing\n\t * the incoming data.  So a handler for this in that case should\n\t * simply set a flag to indicate there is incoming data ready\n\t * and ask for a writeable callback on the outgoing connection.\n\t * In the writable callback he can check the flag and then get\n\t * and drain the waiting incoming data using lws_http_client_read().\n\t * This will use callbacks to LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ\n\t * to get and drain the incoming data, where it should be sent\n\t * back out on the outgoing connection. */\n\tLWS_CALLBACK_COMPLETED_CLIENT_HTTP\t\t\t= 47,\n\t/**< The client transaction completed... at the moment this\n\t * is the same as closing since transaction pipelining on\n\t * client side is not yet supported.  */\n\n\tLWS_CALLBACK_CLIENT_HTTP_WRITEABLE\t\t\t= 57,\n\t/**< when doing an HTTP type client connection, you can call\n\t * lws_client_http_body_pending(wsi, 1) from\n\t * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER to get these callbacks\n\t * sending the HTTP headers.\n\t *\n\t * From this callback, when you have sent everything, you should let\n\t * lws know by calling lws_client_http_body_pending(wsi, 0)\n\t */\n\n\t/* ---------------------------------------------------------------------\n\t * ----- Callbacks related to Websocket Server -----\n\t */\n\n\tLWS_CALLBACK_ESTABLISHED\t\t\t\t=  0,\n\t/**< (VH) after the server completes a handshake with an incoming\n\t * client.  If you built the library with ssl support, in is a\n\t * pointer to the ssl struct associated with the connection or NULL.\n\t *\n\t * b0 of len is set if the connection was made using ws-over-h2\n\t */\n\n\tLWS_CALLBACK_CLOSED\t\t\t\t\t=  4,\n\t/**< when the websocket session ends */\n\n\tLWS_CALLBACK_SERVER_WRITEABLE\t\t\t\t= 11,\n\t/**< See LWS_CALLBACK_CLIENT_WRITEABLE */\n\n\tLWS_CALLBACK_RECEIVE\t\t\t\t\t=  6,\n\t/**< data has appeared for this server endpoint from a\n\t * remote client, it can be found at *in and is\n\t * len bytes long */\n\n\tLWS_CALLBACK_RECEIVE_PONG\t\t\t\t=  7,\n\t/**< servers receive PONG packets with this callback reason */\n\n\tLWS_CALLBACK_WS_PEER_INITIATED_CLOSE\t\t\t= 38,\n\t/**< The peer has sent an unsolicited Close WS packet.  in and\n\t * len are the optional close code (first 2 bytes, network\n\t * order) and the optional additional information which is not\n\t * defined in the standard, and may be a string or non human-readable\n\t * data.\n\t * If you return 0 lws will echo the close and then close the\n\t * connection.  If you return nonzero lws will just close the\n\t * connection. */\n\n\tLWS_CALLBACK_FILTER_PROTOCOL_CONNECTION\t\t\t= 20,\n\t/**< called when the handshake has\n\t * been received and parsed from the client, but the response is\n\t * not sent yet.  Return non-zero to disallow the connection.\n\t * user is a pointer to the connection user space allocation,\n\t * in is the requested protocol name\n\t * In your handler you can use the public APIs\n\t * lws_hdr_total_length() / lws_hdr_copy() to access all of the\n\t * headers using the header enums lws_token_indexes from\n\t * libwebsockets.h to check for and read the supported header\n\t * presence and content before deciding to allow the handshake\n\t * to proceed or to kill the connection. */\n\n\tLWS_CALLBACK_CONFIRM_EXTENSION_OKAY\t\t\t= 25,\n\t/**< When the server handshake code\n\t * sees that it does support a requested extension, before\n\t * accepting the extension by additing to the list sent back to\n\t * the client it gives this callback just to check that it's okay\n\t * to use that extension.  It calls back to the requested protocol\n\t * and with in being the extension name, len is 0 and user is\n\t * valid.  Note though at this time the ESTABLISHED callback hasn't\n\t * happened yet so if you initialize user content there, user\n\t * content during this callback might not be useful for anything. */\n\n\t/* ---------------------------------------------------------------------\n\t * ----- Callbacks related to Websocket Client -----\n\t */\n\n\tLWS_CALLBACK_CLIENT_CONNECTION_ERROR\t\t\t=  1,\n\t/**< the request client connection has been unable to complete a\n\t * handshake with the remote server.  If in is non-NULL, you can\n\t * find an error string of length len where it points to\n\t *\n\t * Diagnostic strings that may be returned include\n\t *\n\t *     \t\"getaddrinfo (ipv6) failed\"\n\t *     \t\"unknown address family\"\n\t *     \t\"getaddrinfo (ipv4) failed\"\n\t *     \t\"set socket opts failed\"\n\t *     \t\"insert wsi failed\"\n\t *     \t\"lws_ssl_client_connect1 failed\"\n\t *     \t\"lws_ssl_client_connect2 failed\"\n\t *     \t\"Peer hung up\"\n\t *     \t\"read failed\"\n\t *     \t\"HS: URI missing\"\n\t *     \t\"HS: Redirect code but no Location\"\n\t *     \t\"HS: URI did not parse\"\n\t *     \t\"HS: Redirect failed\"\n\t *     \t\"HS: Server did not return 200\"\n\t *     \t\"HS: OOM\"\n\t *     \t\"HS: disallowed by client filter\"\n\t *     \t\"HS: disallowed at ESTABLISHED\"\n\t *     \t\"HS: ACCEPT missing\"\n\t *     \t\"HS: ws upgrade response not 101\"\n\t *     \t\"HS: UPGRADE missing\"\n\t *     \t\"HS: Upgrade to something other than websocket\"\n\t *     \t\"HS: CONNECTION missing\"\n\t *     \t\"HS: UPGRADE malformed\"\n\t *     \t\"HS: PROTOCOL malformed\"\n\t *     \t\"HS: Cannot match protocol\"\n\t *     \t\"HS: EXT: list too big\"\n\t *     \t\"HS: EXT: failed setting defaults\"\n\t *     \t\"HS: EXT: failed parsing defaults\"\n\t *     \t\"HS: EXT: failed parsing options\"\n\t *     \t\"HS: EXT: Rejects server options\"\n\t *     \t\"HS: EXT: unknown ext\"\n\t *     \t\"HS: Accept hash wrong\"\n\t *     \t\"HS: Rejected by filter cb\"\n\t *     \t\"HS: OOM\"\n\t *     \t\"HS: SO_SNDBUF failed\"\n\t *     \t\"HS: Rejected at CLIENT_ESTABLISHED\"\n\t */\n\n\tLWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH\t\t=  2,\n\t/**< this is the last chance for the client user code to examine the\n\t * http headers and decide to reject the connection.  If the\n\t * content in the headers is interesting to the\n\t * client (url, etc) it needs to copy it out at\n\t * this point since it will be destroyed before\n\t * the CLIENT_ESTABLISHED call */\n\n\tLWS_CALLBACK_CLIENT_ESTABLISHED\t\t\t\t=  3,\n\t/**< after your client connection completed the websocket upgrade\n\t * handshake with the remote server */\n\n\tLWS_CALLBACK_CLIENT_CLOSED\t\t\t\t=  75,\n\t/**< when a client websocket session ends */\n\n\tLWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER\t\t= 24,\n\t/**< this callback happens\n\t * when a client handshake is being compiled.  user is NULL,\n\t * in is a char **, it's pointing to a char * which holds the\n\t * next location in the header buffer where you can add\n\t * headers, and len is the remaining space in the header buffer,\n\t * which is typically some hundreds of bytes.  So, to add a canned\n\t * cookie, your handler code might look similar to:\n\t *\n\t *\tchar **p = (char **)in;\n\t *\n\t *\tif (len < 100)\n\t *\t\treturn 1;\n\t *\n\t *\t*p += sprintf(*p, \"Cookie: a=b\\x0d\\x0a\");\n\t *\n\t *\treturn 0;\n\t *\n\t * Notice if you add anything, you just have to take care about\n\t * the CRLF on the line you added.  Obviously this callback is\n\t * optional, if you don't handle it everything is fine.\n\t *\n\t * Notice the callback is coming to protocols[0] all the time,\n\t * because there is no specific protocol negotiated yet.\n\t *\n\t * See LWS_CALLBACK_ADD_HEADERS for adding headers to server\n\t * transactions.\n\t */\n\n\tLWS_CALLBACK_CLIENT_RECEIVE\t\t\t\t=  8,\n\t/**< data has appeared from the server for the client connection, it\n\t * can be found at *in and is len bytes long */\n\n\tLWS_CALLBACK_CLIENT_RECEIVE_PONG\t\t\t=  9,\n\t/**< clients receive PONG packets with this callback reason */\n\n\tLWS_CALLBACK_CLIENT_WRITEABLE\t\t\t\t= 10,\n\t/**<  If you call lws_callback_on_writable() on a connection, you will\n\t * get one of these callbacks coming when the connection socket\n\t * is able to accept another write packet without blocking.\n\t * If it already was able to take another packet without blocking,\n\t * you'll get this callback at the next call to the service loop\n\t * function.  Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE\n\t * and servers get LWS_CALLBACK_SERVER_WRITEABLE. */\n\n\tLWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED\t\t= 26,\n\t/**< When a ws client\n\t * connection is being prepared to start a handshake to a server,\n\t * each supported extension is checked with protocols[0] callback\n\t * with this reason, giving the user code a chance to suppress the\n\t * claim to support that extension by returning non-zero.  If\n\t * unhandled, by default 0 will be returned and the extension\n\t * support included in the header to the server.  Notice this\n\t * callback comes to protocols[0]. */\n\n\tLWS_CALLBACK_WS_EXT_DEFAULTS\t\t\t\t= 39,\n\t/**< Gives client connections an opportunity to adjust negotiated\n\t * extension defaults.  `user` is the extension name that was\n\t * negotiated (eg, \"permessage-deflate\").  `in` points to a\n\t * buffer and `len` is the buffer size.  The user callback can\n\t * set the buffer to a string describing options the extension\n\t * should parse.  Or just ignore for defaults. */\n\n\n\tLWS_CALLBACK_FILTER_NETWORK_CONNECTION\t\t\t= 17,\n\t/**< called when a client connects to\n\t * the server at network level; the connection is accepted but then\n\t * passed to this callback to decide whether to hang up immediately\n\t * or not, based on the client IP.  in contains the connection\n\t * socket's descriptor. Since the client connection information is\n\t * not available yet, wsi still pointing to the main server socket.\n\t * Return non-zero to terminate the connection before sending or\n\t * receiving anything. Because this happens immediately after the\n\t * network connection from the client, there's no websocket protocol\n\t * selected yet so this callback is issued only to protocol 0. */\n\n\t/* ---------------------------------------------------------------------\n\t * ----- Callbacks related to external poll loop integration  -----\n\t */\n\n\tLWS_CALLBACK_GET_THREAD_ID\t\t\t\t= 31,\n\t/**< lws can accept callback when writable requests from other\n\t * threads, if you implement this callback and return an opaque\n\t * current thread ID integer. */\n\n\t/* external poll() management support */\n\tLWS_CALLBACK_ADD_POLL_FD\t\t\t\t= 32,\n\t/**< lws normally deals with its poll() or other event loop\n\t * internally, but in the case you are integrating with another\n\t * server you will need to have lws sockets share a\n\t * polling array with the other server.  This and the other\n\t * POLL_FD related callbacks let you put your specialized\n\t * poll array interface code in the callback for protocol 0, the\n\t * first protocol you support, usually the HTTP protocol in the\n\t * serving case.\n\t * This callback happens when a socket needs to be\n\t * added to the polling loop: in points to a struct\n\t * lws_pollargs; the fd member of the struct is the file\n\t * descriptor, and events contains the active events\n\t *\n\t * If you are using the internal lws polling / event loop\n\t * you can just ignore these callbacks. */\n\n\tLWS_CALLBACK_DEL_POLL_FD\t\t\t\t= 33,\n\t/**< This callback happens when a socket descriptor\n\t * needs to be removed from an external polling array.  in is\n\t * again the struct lws_pollargs containing the fd member\n\t * to be removed.  If you are using the internal polling\n\t * loop, you can just ignore it. */\n\n\tLWS_CALLBACK_CHANGE_MODE_POLL_FD\t\t\t= 34,\n\t/**< This callback happens when lws wants to modify the events for\n\t * a connection.\n\t * in is the struct lws_pollargs with the fd to change.\n\t * The new event mask is in events member and the old mask is in\n\t * the prev_events member.\n\t * If you are using the internal polling loop, you can just ignore\n\t * it. */\n\n\tLWS_CALLBACK_LOCK_POLL\t\t\t\t\t= 35,\n\t/**< These allow the external poll changes driven\n\t * by lws to participate in an external thread locking\n\t * scheme around the changes, so the whole thing is threadsafe.\n\t * These are called around three activities in the library,\n\t *\t- inserting a new wsi in the wsi / fd table (len=1)\n\t *\t- deleting a wsi from the wsi / fd table (len=1)\n\t *\t- changing a wsi's POLLIN/OUT state (len=0)\n\t * Locking and unlocking external synchronization objects when\n\t * len == 1 allows external threads to be synchronized against\n\t * wsi lifecycle changes if it acquires the same lock for the\n\t * duration of wsi dereference from the other thread context. */\n\n\tLWS_CALLBACK_UNLOCK_POLL\t\t\t\t= 36,\n\t/**< See LWS_CALLBACK_LOCK_POLL, ignore if using lws internal poll */\n\n\t/* ---------------------------------------------------------------------\n\t * ----- Callbacks related to CGI serving -----\n\t */\n\n\tLWS_CALLBACK_CGI\t\t\t\t\t= 40,\n\t/**< CGI: CGI IO events on stdin / out / err are sent here on\n\t * protocols[0].  The provided `lws_callback_http_dummy()`\n\t * handles this and the callback should be directed there if\n\t * you use CGI. */\n\n\tLWS_CALLBACK_CGI_TERMINATED\t\t\t\t= 41,\n\t/**< CGI: The related CGI process ended, this is called before\n\t * the wsi is closed.  Used to, eg, terminate chunking.\n\t * The provided `lws_callback_http_dummy()`\n\t * handles this and the callback should be directed there if\n\t * you use CGI.  The child PID that terminated is in len. */\n\n\tLWS_CALLBACK_CGI_STDIN_DATA\t\t\t\t= 42,\n\t/**< CGI: Data is, to be sent to the CGI process stdin, eg from\n\t * a POST body.  The provided `lws_callback_http_dummy()`\n\t * handles this and the callback should be directed there if\n\t * you use CGI. */\n\n\tLWS_CALLBACK_CGI_STDIN_COMPLETED\t\t\t= 43,\n\t/**< CGI: no more stdin is coming.  The provided\n\t * `lws_callback_http_dummy()` handles this and the callback\n\t * should be directed there if you use CGI. */\n\n\tLWS_CALLBACK_CGI_PROCESS_ATTACH\t\t\t\t= 70,\n\t/**< CGI: Sent when the CGI process is spawned for the wsi.  The\n\t * len parameter is the PID of the child process */\n\n\t/* ---------------------------------------------------------------------\n\t * ----- Callbacks related to Generic Sessions -----\n\t */\n\n\tLWS_CALLBACK_SESSION_INFO\t\t\t\t= 54,\n\t/**< This is only generated by user code using generic sessions.\n\t * It's used to get a `struct lws_session_info` filled in by\n\t * generic sessions with information about the logged-in user.\n\t * See the messageboard sample for an example of how to use. */\n\n\tLWS_CALLBACK_GS_EVENT\t\t\t\t\t= 55,\n\t/**< Indicates an event happened to the Generic Sessions session.\n\t * `in` contains a `struct lws_gs_event_args` describing the event. */\n\n\tLWS_CALLBACK_HTTP_PMO\t\t\t\t\t= 56,\n\t/**< per-mount options for this connection, called before\n\t * the normal LWS_CALLBACK_HTTP when the mount has per-mount\n\t * options.\n\t */\n\n\t/* ---------------------------------------------------------------------\n\t * ----- Callbacks related to RAW sockets -----\n\t */\n\n\tLWS_CALLBACK_RAW_RX\t\t\t\t\t= 59,\n\t/**< RAW mode connection RX */\n\n\tLWS_CALLBACK_RAW_CLOSE\t\t\t\t\t= 60,\n\t/**< RAW mode connection is closing */\n\n\tLWS_CALLBACK_RAW_WRITEABLE\t\t\t\t= 61,\n\t/**< RAW mode connection may be written */\n\n\tLWS_CALLBACK_RAW_ADOPT\t\t\t\t\t= 62,\n\t/**< RAW mode connection was adopted (equivalent to 'wsi created') */\n\n\t/* ---------------------------------------------------------------------\n\t * ----- Callbacks related to RAW file handles -----\n\t */\n\n\tLWS_CALLBACK_RAW_ADOPT_FILE\t\t\t\t= 63,\n\t/**< RAW mode file was adopted (equivalent to 'wsi created') */\n\n\tLWS_CALLBACK_RAW_RX_FILE\t\t\t\t= 64,\n\t/**< This is the indication the RAW mode file has something to read.\n\t *   This doesn't actually do the read of the file and len is always\n\t *   0... your code should do the read having been informed there is\n\t *   something to read now. */\n\n\tLWS_CALLBACK_RAW_WRITEABLE_FILE\t\t\t\t= 65,\n\t/**< RAW mode file is writeable */\n\n\tLWS_CALLBACK_RAW_CLOSE_FILE\t\t\t\t= 66,\n\t/**< RAW mode wsi that adopted a file is closing */\n\n\t/* ---------------------------------------------------------------------\n\t * ----- Callbacks related to generic wsi events -----\n\t */\n\n\tLWS_CALLBACK_TIMER\t\t\t\t\t= 73,\n\t/**< When the time elapsed after a call to\n\t * lws_set_timer_usecs(wsi, usecs) is up, the wsi will get one of\n\t * these callbacks.  The deadline can be continuously extended into the\n\t * future by later calls to lws_set_timer_usecs() before the deadline\n\t * expires, or cancelled by lws_set_timer_usecs(wsi, -1);\n\t * See the note on lws_set_timer_usecs() about which event loops are\n\t * supported. */\n\n\tLWS_CALLBACK_EVENT_WAIT_CANCELLED\t\t\t= 71,\n\t/**< This is sent to every protocol of every vhost in response\n\t * to lws_cancel_service() or lws_cancel_service_pt().  This\n\t * callback is serialized in the lws event loop normally, even\n\t * if the lws_cancel_service[_pt]() call was from a different\n\t * thread. */\n\n\tLWS_CALLBACK_CHILD_CLOSING\t\t\t\t= 69,\n\t/**< Sent to parent to notify them a child is closing / being\n\t * destroyed.  in is the child wsi.\n\t */\n\n\tLWS_CALLBACK_CHILD_WRITE_VIA_PARENT\t\t\t= 68,\n\t/**< Child has been marked with parent_carries_io attribute, so\n\t * lws_write directs the to this callback at the parent,\n\t * in is a struct lws_write_passthru containing the args\n\t * the lws_write() was called with.\n\t */\n\n\t/* ---------------------------------------------------------------------\n\t * ----- Callbacks related to TLS certificate management -----\n\t */\n\n\tLWS_CALLBACK_VHOST_CERT_AGING\t\t\t\t= 72,\n\t/**< When a vhost TLS cert has its expiry checked, this callback\n\t * is broadcast to every protocol of every vhost in case the\n\t * protocol wants to take some action with this information.\n\t * \\p in is a pointer to a struct lws_acme_cert_aging_args,\n\t * and \\p len is the number of days left before it expires, as\n\t * a (ssize_t).  In the struct lws_acme_cert_aging_args, vh\n\t * points to the vhost the cert aging information applies to,\n\t * and element_overrides[] is an optional way to update information\n\t * from the pvos... NULL in an index means use the information from\n\t * from the pvo for the cert renewal, non-NULL in the array index\n\t * means use that pointer instead for the index. */\n\n\tLWS_CALLBACK_VHOST_CERT_UPDATE\t\t\t\t= 74,\n\t/**< When a vhost TLS cert is being updated, progress is\n\t * reported to the vhost in question here, including completion\n\t * and failure.  in points to optional JSON, and len represents the\n\t * connection state using enum lws_cert_update_state */\n\n\n\t/****** add new things just above ---^ ******/\n\n\tLWS_CALLBACK_USER = 1000,\n\t/**<  user code can use any including above without fear of clashes */\n};\n\n\n\n/**\n * typedef lws_callback_function() - User server actions\n * \\param wsi:\tOpaque websocket instance pointer\n * \\param reason:\tThe reason for the call\n * \\param user:\tPointer to per-session user data allocated by library\n * \\param in:\t\tPointer used for some callback reasons\n * \\param len:\tLength set for some callback reasons\n *\n *\tThis callback is the way the user controls what is served.  All the\n *\tprotocol detail is hidden and handled by the library.\n *\n *\tFor each connection / session there is user data allocated that is\n *\tpointed to by \"user\".  You set the size of this user data area when\n *\tthe library is initialized with lws_create_server.\n */\ntypedef int\nlws_callback_function(struct lws *wsi, enum lws_callback_reasons reason,\n\t\t    void *user, void *in, size_t len);\n\n#define LWS_CB_REASON_AUX_BF__CGI\t\t1\n#define LWS_CB_REASON_AUX_BF__PROXY\t\t2\n#define LWS_CB_REASON_AUX_BF__CGI_CHUNK_END\t4\n#define LWS_CB_REASON_AUX_BF__CGI_HEADERS\t8\n///@}\n\nstruct lws_vhost;\n\n/*! \\defgroup generic hash\n * ## Generic Hash related functions\n *\n * Lws provides generic hash / digest accessors that abstract the ones\n * provided by whatever OpenSSL library you are linking against.\n *\n * It lets you use the same code if you build against mbedtls or OpenSSL\n * for example.\n */\n///@{\n\n#if defined(LWS_WITH_TLS)\n\n#if defined(LWS_WITH_MBEDTLS)\n#include <mbedtls/sha1.h>\n#include <mbedtls/sha256.h>\n#include <mbedtls/sha512.h>\n#endif\n\nenum lws_genhash_types {\n\tLWS_GENHASH_TYPE_SHA1,\n\tLWS_GENHASH_TYPE_SHA256,\n\tLWS_GENHASH_TYPE_SHA384,\n\tLWS_GENHASH_TYPE_SHA512,\n};\n\nenum lws_genhmac_types {\n\tLWS_GENHMAC_TYPE_SHA256,\n\tLWS_GENHMAC_TYPE_SHA384,\n\tLWS_GENHMAC_TYPE_SHA512,\n};\n\n#define LWS_GENHASH_LARGEST 64\n\nstruct lws_genhash_ctx {\n        uint8_t type;\n#if defined(LWS_WITH_MBEDTLS)\n        union {\n\t\tmbedtls_sha1_context sha1;\n\t\tmbedtls_sha256_context sha256;\n\t\tmbedtls_sha512_context sha512; /* 384 also uses this */\n\t\tconst mbedtls_md_info_t *hmac;\n        } u;\n#else\n        const EVP_MD *evp_type;\n        EVP_MD_CTX *mdctx;\n#endif\n};\n\nstruct lws_genhmac_ctx {\n        uint8_t type;\n#if defined(LWS_WITH_MBEDTLS)\n\tconst mbedtls_md_info_t *hmac;\n\tmbedtls_md_context_t ctx;\n#else\n        const EVP_MD *evp_type;\n        EVP_MD_CTX *ctx;\n#endif\n};\n\n/** lws_genhash_size() - get hash size in bytes\n *\n * \\param type:\tone of LWS_GENHASH_TYPE_...\n *\n * Returns number of bytes in this type of hash\n */\nLWS_VISIBLE LWS_EXTERN size_t LWS_WARN_UNUSED_RESULT\nlws_genhash_size(enum lws_genhash_types type);\n\n/** lws_genhmac_size() - get hash size in bytes\n *\n * \\param type:\tone of LWS_GENHASH_TYPE_...\n *\n * Returns number of bytes in this type of hmac\n */\nLWS_VISIBLE LWS_EXTERN size_t LWS_WARN_UNUSED_RESULT\nlws_genhmac_size(enum lws_genhmac_types type);\n\n/** lws_genhash_init() - prepare your struct lws_genhash_ctx for use\n *\n * \\param ctx: your struct lws_genhash_ctx\n * \\param type:\tone of LWS_GENHASH_TYPE_...\n *\n * Initializes the hash context for the type you requested\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_genhash_init(struct lws_genhash_ctx *ctx, enum lws_genhash_types type);\n\n/** lws_genhash_update() - digest len bytes of the buffer starting at in\n *\n * \\param ctx: your struct lws_genhash_ctx\n * \\param in: start of the bytes to digest\n * \\param len: count of bytes to digest\n *\n * Updates the state of your hash context to reflect digesting len bytes from in\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_genhash_update(struct lws_genhash_ctx *ctx, const void *in, size_t len);\n\n/** lws_genhash_destroy() - copy out the result digest and destroy the ctx\n *\n * \\param ctx: your struct lws_genhash_ctx\n * \\param result: NULL, or where to copy the result hash\n *\n * Finalizes the hash and copies out the digest.  Destroys any allocations such\n * that ctx can safely go out of scope after calling this.\n *\n * NULL result is supported so that you can destroy the ctx cleanly on error\n * conditions, where there is no valid result.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_genhash_destroy(struct lws_genhash_ctx *ctx, void *result);\n\n/** lws_genhmac_init() - prepare your struct lws_genhmac_ctx for use\n *\n * \\param ctx: your struct lws_genhmac_ctx\n * \\param type:\tone of LWS_GENHMAC_TYPE_...\n * \\param key: pointer to the start of the HMAC key\n * \\param key_len: length of the HMAC key\n *\n * Initializes the hash context for the type you requested\n *\n * If the return is nonzero, it failed and there is nothing needing to be\n * destroyed.\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_genhmac_init(struct lws_genhmac_ctx *ctx, enum lws_genhmac_types type,\n\t\tconst uint8_t *key, size_t key_len);\n\n/** lws_genhmac_update() - digest len bytes of the buffer starting at in\n *\n * \\param ctx: your struct lws_genhmac_ctx\n * \\param in: start of the bytes to digest\n * \\param len: count of bytes to digest\n *\n * Updates the state of your hash context to reflect digesting len bytes from in\n *\n * If the return is nonzero, it failed and needs destroying.\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_genhmac_update(struct lws_genhmac_ctx *ctx, const void *in, size_t len);\n\n/** lws_genhmac_destroy() - copy out the result digest and destroy the ctx\n *\n * \\param ctx: your struct lws_genhmac_ctx\n * \\param result: NULL, or where to copy the result hash\n *\n * Finalizes the hash and copies out the digest.  Destroys any allocations such\n * that ctx can safely go out of scope after calling this.\n *\n * NULL result is supported so that you can destroy the ctx cleanly on error\n * conditions, where there is no valid result.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_genhmac_destroy(struct lws_genhmac_ctx *ctx, void *result);\n///@}\n\n/*! \\defgroup generic RSA\n * ## Generic RSA related functions\n *\n * Lws provides generic RSA functions that abstract the ones\n * provided by whatever OpenSSL library you are linking against.\n *\n * It lets you use the same code if you build against mbedtls or OpenSSL\n * for example.\n */\n///@{\n\nenum enum_jwk_tok {\n\tJWK_KEY_E,\n\tJWK_KEY_N,\n\tJWK_KEY_D,\n\tJWK_KEY_P,\n\tJWK_KEY_Q,\n\tJWK_KEY_DP,\n\tJWK_KEY_DQ,\n\tJWK_KEY_QI,\n\tJWK_KTY, /* also serves as count of real elements */\n\tJWK_KEY,\n};\n\n#define LWS_COUNT_RSA_ELEMENTS JWK_KTY\n\nstruct lws_genrsa_ctx {\n#if defined(LWS_WITH_MBEDTLS)\n\tmbedtls_rsa_context *ctx;\n#else\n\tBIGNUM *bn[LWS_COUNT_RSA_ELEMENTS];\n\tRSA *rsa;\n#endif\n};\n\nstruct lws_genrsa_element {\n\tuint8_t *buf;\n\tuint16_t len;\n};\n\nstruct lws_genrsa_elements {\n\tstruct lws_genrsa_element e[LWS_COUNT_RSA_ELEMENTS];\n};\n\n/** lws_jwk_destroy_genrsa_elements() - Free allocations in genrsa_elements\n *\n * \\param el: your struct lws_genrsa_elements\n *\n * This is a helper for user code making use of struct lws_genrsa_elements\n * where the elements are allocated on the heap, it frees any non-NULL\n * buf element and sets the buf to NULL.\n *\n * NB: lws_genrsa_public_... apis do not need this as they take care of the key\n * creation and destruction themselves.\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_jwk_destroy_genrsa_elements(struct lws_genrsa_elements *el);\n\n/** lws_genrsa_public_decrypt_create() - Create RSA public decrypt context\n *\n * \\param ctx: your struct lws_genrsa_ctx\n * \\param el: struct prepared with key element data\n *\n * Creates an RSA context with a public key associated with it, formed from\n * the key elements in \\p el.\n *\n * Returns 0 for OK or nonzero for error.\n *\n * This and related APIs operate identically with OpenSSL or mbedTLS backends.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_genrsa_create(struct lws_genrsa_ctx *ctx, struct lws_genrsa_elements *el);\n\n/** lws_genrsa_new_keypair() - Create new RSA keypair\n *\n * \\param context: your struct lws_context (may be used for RNG)\n * \\param ctx: your struct lws_genrsa_ctx\n * \\param el: struct to get the new key element data allocated into it\n * \\param bits: key size, eg, 4096\n *\n * Creates a new RSA context and generates a new keypair into it, with \\p bits\n * bits.\n *\n * Returns 0 for OK or nonzero for error.\n *\n * This and related APIs operate identically with OpenSSL or mbedTLS backends.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_genrsa_new_keypair(struct lws_context *context, struct lws_genrsa_ctx *ctx,\n\t\t       struct lws_genrsa_elements *el, int bits);\n\n/** lws_genrsa_public_decrypt() - Perform RSA public decryption\n *\n * \\param ctx: your struct lws_genrsa_ctx\n * \\param in: encrypted input\n * \\param in_len: length of encrypted input\n * \\param out: decrypted output\n * \\param out_max: size of output buffer\n *\n * Performs the decryption.\n *\n * Returns <0 for error, or length of decrypted data.\n *\n * This and related APIs operate identically with OpenSSL or mbedTLS backends.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_genrsa_public_decrypt(struct lws_genrsa_ctx *ctx, const uint8_t *in,\n\t\t\t  size_t in_len, uint8_t *out, size_t out_max);\n\n/** lws_genrsa_public_verify() - Perform RSA public verification\n *\n * \\param ctx: your struct lws_genrsa_ctx\n * \\param in: unencrypted payload (usually a recomputed hash)\n * \\param hash_type: one of LWS_GENHASH_TYPE_\n * \\param sig: pointer to the signature we received with the payload\n * \\param sig_len: length of the signature we are checking in bytes\n *\n * Returns <0 for error, or 0 if signature matches the payload + key.\n *\n * This and related APIs operate identically with OpenSSL or mbedTLS backends.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_genrsa_public_verify(struct lws_genrsa_ctx *ctx, const uint8_t *in,\n\t\t\t enum lws_genhash_types hash_type,\n\t\t\t const uint8_t *sig, size_t sig_len);\n\n/** lws_genrsa_public_sign() - Create RSA signature\n *\n * \\param ctx: your struct lws_genrsa_ctx\n * \\param in: precomputed hash\n * \\param hash_type: one of LWS_GENHASH_TYPE_\n * \\param sig: pointer to buffer to take signature\n * \\param sig_len: length of the buffer (must be >= length of key N)\n *\n * Returns <0 for error, or 0 for success.\n *\n * This and related APIs operate identically with OpenSSL or mbedTLS backends.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_genrsa_public_sign(struct lws_genrsa_ctx *ctx, const uint8_t *in,\n\t\t\t enum lws_genhash_types hash_type, uint8_t *sig,\n\t\t\t size_t sig_len);\n\n/** lws_genrsa_public_decrypt_destroy() - Destroy RSA public decrypt context\n *\n * \\param ctx: your struct lws_genrsa_ctx\n *\n * Destroys any allocations related to \\p ctx.\n *\n * This and related APIs operate identically with OpenSSL or mbedTLS backends.\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_genrsa_destroy(struct lws_genrsa_ctx *ctx);\n\n/** lws_genrsa_render_pkey_asn1() - Exports public or private key to ASN1/DER\n *\n * \\param ctx: your struct lws_genrsa_ctx\n * \\param _private: 0 = public part only, 1 = all parts of the key\n * \\param pkey_asn1: pointer to buffer to take the ASN1\n * \\param pkey_asn1_len: max size of the pkey_asn1_len\n *\n * Returns length of pkey_asn1 written, or -1 for error.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_genrsa_render_pkey_asn1(struct lws_genrsa_ctx *ctx, int _private,\n\t\t\t    uint8_t *pkey_asn1, size_t pkey_asn1_len);\n///@}\n\n/*! \\defgroup jwk JSON Web Keys\n * ## JSON Web Keys API\n *\n * Lws provides an API to parse JSON Web Keys into a struct lws_genrsa_elements.\n *\n * \"oct\" and \"RSA\" type keys are supported.  For \"oct\" keys, they are held in\n * the \"e\" member of the struct lws_genrsa_elements.\n *\n * Keys elements are allocated on the heap.  You must destroy the allocations\n * in the struct lws_genrsa_elements by calling\n * lws_jwk_destroy_genrsa_elements() when you are finished with it.\n */\n///@{\n\nstruct lws_jwk {\n\tchar keytype[5];\t\t/**< \"oct\" or \"RSA\" */\n\tstruct lws_genrsa_elements el;\t/**< OCTet key is in el.e */\n};\n\n/** lws_jwk_import() - Create a JSON Web key from the textual representation\n *\n * \\param s: the JWK object to create\n * \\param in: a single JWK JSON stanza in utf-8\n * \\param len: the length of the JWK JSON stanza in bytes\n *\n * Creates an lws_jwk struct filled with data from the JSON representation.\n * \"oct\" and \"rsa\" key types are supported.\n *\n * For \"oct\" type keys, it is loaded into el.e.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_jwk_import(struct lws_jwk *s, const char *in, size_t len);\n\n/** lws_jwk_destroy() - Destroy a JSON Web key\n *\n * \\param s: the JWK object to destroy\n *\n * All allocations in the lws_jwk are destroyed\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_jwk_destroy(struct lws_jwk *s);\n\n/** lws_jwk_export() - Export a JSON Web key to a textual representation\n *\n * \\param s: the JWK object to export\n * \\param _private: 0 = just export public parts, 1 = export everything\n * \\param p: the buffer to write the exported JWK to\n * \\param len: the length of the buffer \\p p in bytes\n *\n * Returns length of the used part of the buffer if OK, or -1 for error.\n *\n * Serializes the content of the JWK into a char buffer.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_jwk_export(struct lws_jwk *s, int _private, char *p, size_t len);\n\n/** lws_jwk_load() - Import a JSON Web key from a file\n *\n * \\param s: the JWK object to load into\n * \\param filename: filename to load from\n *\n * Returns 0 for OK or -1 for failure\n */\nLWS_VISIBLE int\nlws_jwk_load(struct lws_jwk *s, const char *filename);\n\n/** lws_jwk_save() - Export a JSON Web key to a file\n *\n * \\param s: the JWK object to save from\n * \\param filename: filename to save to\n *\n * Returns 0 for OK or -1 for failure\n */\nLWS_VISIBLE int\nlws_jwk_save(struct lws_jwk *s, const char *filename);\n\n/** lws_jwk_rfc7638_fingerprint() - jwk to RFC7638 compliant fingerprint\n *\n * \\param s: the JWK object to fingerprint\n * \\param digest32: buffer to take 32-byte digest\n *\n * Returns 0 for OK or -1 for failure\n */\nLWS_VISIBLE int\nlws_jwk_rfc7638_fingerprint(struct lws_jwk *s, char *digest32);\n///@}\n\n\n/*! \\defgroup jws JSON Web Signature\n * ## JSON Web Signature API\n *\n * Lws provides an API to check and create RFC7515 JSON Web Signatures\n *\n * SHA256/384/512 HMAC, and RSA 256/384/512 are supported.\n *\n * The API uses your TLS library crypto, but works exactly the same no matter\n * what you TLS backend is.\n */\n///@{\n\nLWS_VISIBLE LWS_EXTERN int\nlws_jws_confirm_sig(const char *in, size_t len, struct lws_jwk *jwk);\n\n/**\n * lws_jws_sign_from_b64() - add b64 sig to b64 hdr + payload\n *\n * \\param b64_hdr: protected header encoded in b64, may be NULL\n * \\param hdr_len: bytes in b64 coding of protected header\n * \\param b64_pay: payload encoded in b64\n * \\param pay_len: bytes in b64 coding of payload\n * \\param b64_sig: buffer to write the b64 encoded signature into\n * \\param sig_len: max bytes we can write at b64_sig\n * \\param hash_type: one of LWS_GENHASH_TYPE_SHA[256|384|512]\n * \\param jwk: the struct lws_jwk containing the signing key\n *\n * This adds a b64-coded JWS signature of the b64-encoded protected header\n * and b64-encoded payload, at \\p b64_sig.  The signature will be as large\n * as the N element of the RSA key when the RSA key is used, eg, 512 bytes for\n * a 4096-bit key, and then b64-encoding on top.\n *\n * In some special cases, there is only payload to sign and no header, in that\n * case \\p b64_hdr may be NULL, and only the payload will be hashed before\n * signing.\n *\n * Returns the length of the encoded signature written to \\p b64_sig, or -1.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_jws_sign_from_b64(const char *b64_hdr, size_t hdr_len, const char *b64_pay,\n\t\t      size_t pay_len, char *b64_sig, size_t sig_len,\n\t\t      enum lws_genhash_types hash_type, struct lws_jwk *jwk);\n\n/**\n * lws_jws_create_packet() - add b64 sig to b64 hdr + payload\n *\n * \\param jwk: the struct lws_jwk containing the signing key\n * \\param payload: unencoded payload JSON\n * \\param len: length of unencoded payload JSON\n * \\param nonce: Nonse string to include in protected header\n * \\param out: buffer to take signed packet\n * \\param out_len: size of \\p out buffer\n *\n * This creates a \"flattened\" JWS packet from the jwk and the plaintext\n * payload, and signs it.  The packet is written into \\p out.\n *\n * This does the whole packet assembly and signing, calling through to\n * lws_jws_sign_from_b64() as part of the process.\n *\n * Returns the length written to \\p out, or -1.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_jws_create_packet(struct lws_jwk *jwk, const char *payload, size_t len,\n\t\t      const char *nonce, char *out, size_t out_len);\n\n/**\n * lws_jws_base64_enc() - encode input data into b64url data\n *\n * \\param in: the incoming plaintext\n * \\param in_len: the length of the incoming plaintext in bytes\n * \\param out: the buffer to store the b64url encoded data to\n * \\param out_max: the length of \\p out in bytes\n *\n * Returns either -1 if problems, or the number of bytes written to \\p out.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_jws_base64_enc(const char *in, size_t in_len, char *out, size_t out_max);\n///@}\n#endif\n\n/*! \\defgroup extensions Extension related functions\n * ##Extension releated functions\n *\n *  Ws defines optional extensions, lws provides the ability to implement these\n *  in user code if so desired.\n *\n *  We provide one extensions permessage-deflate.\n */\n///@{\n\n/*\n * NOTE: These public enums are part of the abi.  If you want to add one,\n * add it at where specified so existing users are unaffected.\n */\nenum lws_extension_callback_reasons {\n\tLWS_EXT_CB_CONSTRUCT\t\t\t\t=  4,\n\tLWS_EXT_CB_CLIENT_CONSTRUCT\t\t\t=  5,\n\tLWS_EXT_CB_DESTROY\t\t\t\t=  8,\n\tLWS_EXT_CB_PACKET_TX_PRESEND\t\t\t= 12,\n\tLWS_EXT_CB_PAYLOAD_TX\t\t\t\t= 21,\n\tLWS_EXT_CB_PAYLOAD_RX\t\t\t\t= 22,\n\tLWS_EXT_CB_OPTION_DEFAULT\t\t\t= 23,\n\tLWS_EXT_CB_OPTION_SET\t\t\t\t= 24,\n\tLWS_EXT_CB_OPTION_CONFIRM\t\t\t= 25,\n\tLWS_EXT_CB_NAMED_OPTION_SET\t\t\t= 26,\n\n\t/****** add new things just above ---^ ******/\n};\n\n/** enum lws_ext_options_types */\nenum lws_ext_options_types {\n\tEXTARG_NONE, /**< does not take an argument */\n\tEXTARG_DEC,  /**< requires a decimal argument */\n\tEXTARG_OPT_DEC /**< may have an optional decimal argument */\n\n\t/* Add new things just above here ---^\n\t * This is part of the ABI, don't needlessly break compatibility */\n};\n\n/** struct lws_ext_options -\tOption arguments to the extension.  These are\n *\t\t\t\tused in the negotiation at ws upgrade time.\n *\t\t\t\tThe helper function lws_ext_parse_options()\n *\t\t\t\tuses these to generate callbacks */\nstruct lws_ext_options {\n\tconst char *name; /**< Option name, eg, \"server_no_context_takeover\" */\n\tenum lws_ext_options_types type; /**< What kind of args the option can take */\n\n\t/* Add new things just above here ---^\n\t * This is part of the ABI, don't needlessly break compatibility */\n};\n\n/** struct lws_ext_option_arg */\nstruct lws_ext_option_arg {\n\tconst char *option_name; /**< may be NULL, option_index used then */\n\tint option_index; /**< argument ordinal to use if option_name missing */\n\tconst char *start; /**< value */\n\tint len; /**< length of value */\n};\n\n/**\n * typedef lws_extension_callback_function() - Hooks to allow extensions to operate\n * \\param context:\tWebsockets context\n * \\param ext:\tThis extension\n * \\param wsi:\tOpaque websocket instance pointer\n * \\param reason:\tThe reason for the call\n * \\param user:\tPointer to ptr to per-session user data allocated by library\n * \\param in:\t\tPointer used for some callback reasons\n * \\param len:\tLength set for some callback reasons\n *\n *\tEach extension that is active on a particular connection receives\n *\tcallbacks during the connection lifetime to allow the extension to\n *\toperate on websocket data and manage itself.\n *\n *\tLibwebsockets takes care of allocating and freeing \"user\" memory for\n *\teach active extension on each connection.  That is what is pointed to\n *\tby the user parameter.\n *\n *\tLWS_EXT_CB_CONSTRUCT:  called when the server has decided to\n *\t\tselect this extension from the list provided by the client,\n *\t\tjust before the server will send back the handshake accepting\n *\t\tthe connection with this extension active.  This gives the\n *\t\textension a chance to initialize its connection context found\n *\t\tin user.\n *\n *\tLWS_EXT_CB_CLIENT_CONSTRUCT: same as LWS_EXT_CB_CONSTRUCT\n *\t\tbut called when client is instantiating this extension.  Some\n *\t\textensions will work the same on client and server side and then\n *\t\tyou can just merge handlers for both CONSTRUCTS.\n *\n *\tLWS_EXT_CB_DESTROY:  called when the connection the extension was\n *\t\tbeing used on is about to be closed and deallocated.  It's the\n *\t\tlast chance for the extension to deallocate anything it has\n *\t\tallocated in the user data (pointed to by user) before the\n *\t\tuser data is deleted.  This same callback is used whether you\n *\t\tare in client or server instantiation context.\n *\n *\tLWS_EXT_CB_PACKET_TX_PRESEND: this works the same way as\n *\t\tLWS_EXT_CB_PACKET_RX_PREPARSE above, except it gives the\n *\t\textension a chance to change websocket data just before it will\n *\t\tbe sent out.  Using the same lws_token pointer scheme in in,\n *\t\tthe extension can change the buffer and the length to be\n *\t\ttransmitted how it likes.  Again if it wants to grow the\n *\t\tbuffer safely, it should copy the data into its own buffer and\n *\t\tset the lws_tokens token pointer to it.\n *\n *\tLWS_EXT_CB_ARGS_VALIDATE:\n */\ntypedef int\nlws_extension_callback_function(struct lws_context *context,\n\t\t\t      const struct lws_extension *ext, struct lws *wsi,\n\t\t\t      enum lws_extension_callback_reasons reason,\n\t\t\t      void *user, void *in, size_t len);\n\n/** struct lws_extension -\tAn extension we support */\nstruct lws_extension {\n\tconst char *name; /**< Formal extension name, eg, \"permessage-deflate\" */\n\tlws_extension_callback_function *callback; /**< Service callback */\n\tconst char *client_offer; /**< String containing exts and options client offers */\n\n\t/* Add new things just above here ---^\n\t * This is part of the ABI, don't needlessly break compatibility */\n};\n\n/**\n * lws_set_extension_option(): set extension option if possible\n *\n * \\param wsi:\twebsocket connection\n * \\param ext_name:\tname of ext, like \"permessage-deflate\"\n * \\param opt_name:\tname of option, like \"rx_buf_size\"\n * \\param opt_val:\tvalue to set option to\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_set_extension_option(struct lws *wsi, const char *ext_name,\n\t\t\t const char *opt_name, const char *opt_val);\n\n/**\n * lws_ext_parse_options() - deal with parsing negotiated extension options\n *\n * \\param ext: related extension struct\n * \\param wsi:\twebsocket connection\n * \\param ext_user: per-connection extension private data\n * \\param opts: list of supported options\n * \\param o: option string to parse\n * \\param len: length\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_ext_parse_options(const struct lws_extension *ext, struct lws *wsi,\n\t\t       void *ext_user, const struct lws_ext_options *opts,\n\t\t       const char *o, int len);\n\n/** lws_extension_callback_pm_deflate() - extension for RFC7692\n *\n * \\param context:\tlws context\n * \\param ext:\trelated lws_extension struct\n * \\param wsi:\twebsocket connection\n * \\param reason:\tincoming callback reason\n * \\param user:\tper-connection extension private data\n * \\param in:\tpointer parameter\n * \\param len:\tlength parameter\n *\n * Built-in callback implementing RFC7692 permessage-deflate\n */\nLWS_EXTERN\nint lws_extension_callback_pm_deflate(\n\tstruct lws_context *context, const struct lws_extension *ext,\n\tstruct lws *wsi, enum lws_extension_callback_reasons reason,\n\tvoid *user, void *in, size_t len);\n\n/*\n * The internal exts are part of the public abi\n * If we add more extensions, publish the callback here  ------v\n */\n///@}\n\n/*! \\defgroup Protocols-and-Plugins Protocols and Plugins\n * \\ingroup lwsapi\n *\n * ##Protocol and protocol plugin -related apis\n *\n * Protocols bind ws protocol names to a custom callback specific to that\n * protocol implementaion.\n *\n * A list of protocols can be passed in at context creation time, but it is\n * also legal to leave that NULL and add the protocols and their callback code\n * using plugins.\n *\n * Plugins are much preferable compared to cut and pasting code into an\n * application each time, since they can be used standalone.\n */\n///@{\n/** struct lws_protocols -\tList of protocols and handlers client or server\n *\t\t\t\t\tsupports. */\n\nstruct lws_protocols {\n\tconst char *name;\n\t/**< Protocol name that must match the one given in the client\n\t * Javascript new WebSocket(url, 'protocol') name. */\n\tlws_callback_function *callback;\n\t/**< The service callback used for this protocol.  It allows the\n\t * service action for an entire protocol to be encapsulated in\n\t * the protocol-specific callback */\n\tsize_t per_session_data_size;\n\t/**< Each new connection using this protocol gets\n\t * this much memory allocated on connection establishment and\n\t * freed on connection takedown.  A pointer to this per-connection\n\t * allocation is passed into the callback in the 'user' parameter */\n\tsize_t rx_buffer_size;\n\t/**< lws allocates this much space for rx data and informs callback\n\t * when something came.  Due to rx flow control, the callback may not\n\t * be able to consume it all without having to return to the event\n\t * loop.  That is supported in lws.\n\t *\n\t * If .tx_packet_size is 0, this also controls how much may be sent at\n\t * once for backwards compatibility.\n\t */\n\tunsigned int id;\n\t/**< ignored by lws, but useful to contain user information bound\n\t * to the selected protocol.  For example if this protocol was\n\t * called \"myprotocol-v2\", you might set id to 2, and the user\n\t * code that acts differently according to the version can do so by\n\t * switch (wsi->protocol->id), user code might use some bits as\n\t * capability flags based on selected protocol version, etc. */\n\tvoid *user; /**< ignored by lws, but user code can pass a pointer\n\t\t\there it can later access from the protocol callback */\n\tsize_t tx_packet_size;\n\t/**< 0 indicates restrict send() size to .rx_buffer_size for backwards-\n\t * compatibility.\n\t * If greater than zero, a single send() is restricted to this amount\n\t * and any remainder is buffered by lws and sent afterwards also in\n\t * these size chunks.  Since that is expensive, it's preferable\n\t * to restrict one fragment you are trying to send to match this\n\t * size.\n\t */\n\n\t/* Add new things just above here ---^\n\t * This is part of the ABI, don't needlessly break compatibility */\n};\n\n/**\n * lws_vhost_name_to_protocol() - get vhost's protocol object from its name\n *\n * \\param vh: vhost to search\n * \\param name: protocol name\n *\n * Returns NULL or a pointer to the vhost's protocol of the requested name\n */\nLWS_VISIBLE LWS_EXTERN const struct lws_protocols *\nlws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name);\n\n/**\n * lws_get_protocol() - Returns a protocol pointer from a websocket\n *\t\t\t\t  connection.\n * \\param wsi:\tpointer to struct websocket you want to know the protocol of\n *\n *\n *\tSome apis can act on all live connections of a given protocol,\n *\tthis is how you can get a pointer to the active protocol if needed.\n */\nLWS_VISIBLE LWS_EXTERN const struct lws_protocols *\nlws_get_protocol(struct lws *wsi);\n\n/** lws_protocol_get() -  deprecated: use lws_get_protocol */\nLWS_VISIBLE LWS_EXTERN const struct lws_protocols *\nlws_protocol_get(struct lws *wsi) LWS_WARN_DEPRECATED;\n\n/**\n * lws_protocol_vh_priv_zalloc() - Allocate and zero down a protocol's per-vhost\n *\t\t\t\t   storage\n * \\param vhost:\tvhost the instance is related to\n * \\param prot:\t\tprotocol the instance is related to\n * \\param size:\t\tbytes to allocate\n *\n * Protocols often find it useful to allocate a per-vhost struct, this is a\n * helper to be called in the per-vhost init LWS_CALLBACK_PROTOCOL_INIT\n */\nLWS_VISIBLE LWS_EXTERN void *\nlws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot,\n\t\t\t    int size);\n\n/**\n * lws_protocol_vh_priv_get() - retreive a protocol's per-vhost storage\n *\n * \\param vhost:\tvhost the instance is related to\n * \\param prot:\t\tprotocol the instance is related to\n *\n * Recover a pointer to the allocated per-vhost storage for the protocol created\n * by lws_protocol_vh_priv_zalloc() earlier\n */\nLWS_VISIBLE LWS_EXTERN void *\nlws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot);\n\n/**\n * lws_adjust_protocol_psds - change a vhost protocol's per session data size\n *\n * \\param wsi: a connection with the protocol to change\n * \\param new_size: the new size of the per session data size for the protocol\n *\n * Returns user_space for the wsi, after allocating\n *\n * This should not be used except to initalize a vhost protocol's per session\n * data size one time, before any connections are accepted.\n *\n * Sometimes the protocol wraps another protocol and needs to discover and set\n * its per session data size at runtime.\n */\nLWS_VISIBLE LWS_EXTERN void *\nlws_adjust_protocol_psds(struct lws *wsi, size_t new_size);\n\n/**\n * lws_finalize_startup() - drop initial process privileges\n *\n * \\param context:\tlws context\n *\n * This is called after the end of the vhost protocol initializations, but\n * you may choose to call it earlier\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_finalize_startup(struct lws_context *context);\n\n/**\n * lws_pvo_search() - helper to find a named pvo in a linked-list\n *\n * \\param pvo:\tthe first pvo in the linked-list\n * \\param name: the name of the pvo to return if found\n *\n * Returns NULL, or a pointer to the name pvo in the linked-list\n */\nLWS_VISIBLE LWS_EXTERN const struct lws_protocol_vhost_options *\nlws_pvo_search(const struct lws_protocol_vhost_options *pvo, const char *name);\n\nLWS_VISIBLE LWS_EXTERN int\nlws_protocol_init(struct lws_context *context);\n\n#ifdef LWS_WITH_PLUGINS\n\n/* PLUGINS implies LIBUV */\n\n#define LWS_PLUGIN_API_MAGIC 180\n\n/** struct lws_plugin_capability - how a plugin introduces itself to lws */\nstruct lws_plugin_capability {\n\tunsigned int api_magic;\t/**< caller fills this in, plugin fills rest */\n\tconst struct lws_protocols *protocols; /**< array of supported protocols provided by plugin */\n\tint count_protocols; /**< how many protocols */\n\tconst struct lws_extension *extensions; /**< array of extensions provided by plugin */\n\tint count_extensions; /**< how many extensions */\n};\n\ntypedef int (*lws_plugin_init_func)(struct lws_context *,\n\t\t\t\t    struct lws_plugin_capability *);\ntypedef int (*lws_plugin_destroy_func)(struct lws_context *);\n\n/** struct lws_plugin */\nstruct lws_plugin {\n\tstruct lws_plugin *list; /**< linked list */\n#if (UV_VERSION_MAJOR > 0)\n\tuv_lib_t lib; /**< shared library pointer */\n#else\n\tvoid *l; /**< so we can compile on ancient libuv */\n#endif\n\tchar name[64]; /**< name of the plugin */\n\tstruct lws_plugin_capability caps; /**< plugin capabilities */\n};\n\n#endif\n\n///@}\n\n\n/*! \\defgroup generic-sessions plugin: generic-sessions\n * \\ingroup Protocols-and-Plugins\n *\n * ##Plugin Generic-sessions related\n *\n * generic-sessions plugin provides a reusable, generic session and login /\n * register / forgot password framework including email verification.\n */\n///@{\n\n#define LWSGS_EMAIL_CONTENT_SIZE 16384\n/**< Maximum size of email we might send */\n\n/* SHA-1 binary and hexified versions */\n/** typedef struct lwsgw_hash_bin */\ntypedef struct { unsigned char bin[20]; /**< binary representation of hash */} lwsgw_hash_bin;\n/** typedef struct lwsgw_hash */\ntypedef struct { char id[41]; /**< ascii hex representation of hash */ } lwsgw_hash;\n\n/** enum lwsgs_auth_bits */\nenum lwsgs_auth_bits {\n\tLWSGS_AUTH_LOGGED_IN = 1, /**< user is logged in as somebody */\n\tLWSGS_AUTH_ADMIN = 2,\t/**< logged in as the admin user */\n\tLWSGS_AUTH_VERIFIED = 4,  /**< user has verified his email */\n\tLWSGS_AUTH_FORGOT_FLOW = 8,\t/**< he just completed \"forgot password\" flow */\n};\n\n/** struct lws_session_info - information about user session status */\nstruct lws_session_info {\n\tchar username[32]; /**< username logged in as, or empty string */\n\tchar email[100]; /**< email address associated with login, or empty string */\n\tchar ip[72]; /**< ip address session was started from */\n\tunsigned int mask; /**< access rights mask associated with session\n\t \t \t    * see enum lwsgs_auth_bits */\n\tchar session[42]; /**< session id string, usable as opaque uid when not logged in */\n};\n\n/** enum lws_gs_event */\nenum lws_gs_event {\n\tLWSGSE_CREATED, /**< a new user was created */\n\tLWSGSE_DELETED  /**< an existing user was deleted */\n};\n\n/** struct lws_gs_event_args */\nstruct lws_gs_event_args {\n\tenum lws_gs_event event; /**< which event happened */\n\tconst char *username; /**< which username the event happened to */\n\tconst char *email; /**< the email address of that user */\n};\n\n///@}\n\n\n/*! \\defgroup context-and-vhost context and vhost related functions\n * ##Context and Vhost releated functions\n * \\ingroup lwsapi\n *\n *\n *  LWS requires that there is one context, in which you may define multiple\n *  vhosts.  Each vhost is a virtual host, with either its own listen port\n *  or sharing an existing one.  Each vhost has its own SSL context that can\n *  be set up individually or left disabled.\n *\n *  If you don't care about multiple \"site\" support, you can ignore it and\n *  lws will create a single default vhost at context creation time.\n */\n///@{\n\n/*\n * NOTE: These public enums are part of the abi.  If you want to add one,\n * add it at where specified so existing users are unaffected.\n */\n\n/** enum lws_context_options - context and vhost options */\nenum lws_context_options {\n\tLWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT\t= (1 << 1) |\n\t\t\t\t\t\t\t\t  (1 << 12),\n\t/**< (VH) Don't allow the connection unless the client has a\n\t * client cert that we recognize; provides\n\t * LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT */\n\tLWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME\t\t= (1 << 2),\n\t/**< (CTX) Don't try to get the server's hostname */\n\tLWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT\t\t= (1 << 3) |\n\t\t\t\t\t\t\t\t  (1 << 12),\n\t/**< (VH) Allow non-SSL (plaintext) connections on the same\n\t * port as SSL is listening... undermines the security of SSL;\n\t * provides  LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT */\n\tLWS_SERVER_OPTION_LIBEV\t\t\t\t\t= (1 << 4),\n\t/**< (CTX) Use libev event loop */\n\tLWS_SERVER_OPTION_DISABLE_IPV6\t\t\t\t= (1 << 5),\n\t/**< (VH) Disable IPV6 support */\n\tLWS_SERVER_OPTION_DISABLE_OS_CA_CERTS\t\t\t= (1 << 6),\n\t/**< (VH) Don't load OS CA certs, you will need to load your\n\t * own CA cert(s) */\n\tLWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED\t\t= (1 << 7),\n\t/**< (VH) Accept connections with no valid Cert (eg, selfsigned) */\n\tLWS_SERVER_OPTION_VALIDATE_UTF8\t\t\t\t= (1 << 8),\n\t/**< (VH) Check UT-8 correctness */\n\tLWS_SERVER_OPTION_SSL_ECDH\t\t\t\t= (1 << 9) |\n\t\t\t\t\t\t\t\t  (1 << 12),\n\t/**< (VH)  initialize ECDH ciphers */\n\tLWS_SERVER_OPTION_LIBUV\t\t\t\t\t= (1 << 10),\n\t/**< (CTX)  Use libuv event loop */\n\tLWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS\t\t= (1 << 11) |\n\t\t\t\t\t\t\t\t  (1 << 12),\n\t/**< (VH) Use http redirect to force http to https\n\t * (deprecated: use mount redirection) */\n\tLWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT\t\t\t= (1 << 12),\n\t/**< (CTX) Initialize the SSL library at all */\n\tLWS_SERVER_OPTION_EXPLICIT_VHOSTS\t\t\t= (1 << 13),\n\t/**< (CTX) Only create the context when calling context\n\t * create api, implies user code will create its own vhosts */\n\tLWS_SERVER_OPTION_UNIX_SOCK\t\t\t\t= (1 << 14),\n\t/**< (VH) Use Unix socket */\n\tLWS_SERVER_OPTION_STS\t\t\t\t\t= (1 << 15),\n\t/**< (VH) Send Strict Transport Security header, making\n\t * clients subsequently go to https even if user asked for http */\n\tLWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY\t\t\t= (1 << 16),\n\t/**< (VH) Enable LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE to take effect */\n\tLWS_SERVER_OPTION_IPV6_V6ONLY_VALUE\t\t\t= (1 << 17),\n\t/**< (VH) if set, only ipv6 allowed on the vhost */\n\tLWS_SERVER_OPTION_UV_NO_SIGSEGV_SIGFPE_SPIN\t\t= (1 << 18),\n\t/**< (CTX) Libuv only: Do not spin on SIGSEGV / SIGFPE.  A segfault\n\t * normally makes the lib spin so you can attach a debugger to it\n\t * even if it happened without a debugger in place.  You can disable\n\t * that by giving this option.\n\t */\n\tLWS_SERVER_OPTION_JUST_USE_RAW_ORIGIN\t\t\t= (1 << 19),\n\t/**< For backwards-compatibility reasons, by default\n\t * lws prepends \"http://\" to the origin you give in the client\n\t * connection info struct.  If you give this flag when you create\n\t * the context, only the string you give in the client connect\n\t * info for .origin (if any) will be used directly.\n\t */\n\tLWS_SERVER_OPTION_FALLBACK_TO_RAW\t\t\t= (1 << 20),\n\t/**< (VH) if invalid http is coming in the first line,  */\n\tLWS_SERVER_OPTION_LIBEVENT\t\t\t\t= (1 << 21),\n\t/**< (CTX) Use libevent event loop */\n\tLWS_SERVER_OPTION_ONLY_RAW\t\t\t\t= (1 << 22),\n\t/**< (VH) All connections to this vhost / port are RAW as soon as\n\t * the connection is accepted, no HTTP is going to be coming.\n\t */\n\tLWS_SERVER_OPTION_ALLOW_LISTEN_SHARE\t\t\t= (1 << 23),\n\t/**< (VH) Set to allow multiple listen sockets on one interface +\n\t * address + port.  The default is to strictly allow only one\n\t * listen socket at a time.  This is automatically selected if you\n\t * have multiple service threads.\n\t */\n\tLWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX\t\t\t= (1 << 24),\n\t/**< (VH) Force setting up the vhost SSL_CTX, even though the user\n\t * code doesn't explicitly provide a cert in the info struct.  It\n\t * implies the user code is going to provide a cert at the\n\t * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS callback, which\n\t * provides the vhost SSL_CTX * in the user parameter.\n\t */\n\tLWS_SERVER_OPTION_SKIP_PROTOCOL_INIT\t\t\t= (1 << 25),\n\t/**< (VH) You probably don't want this.  It forces this vhost to not\n\t * call LWS_CALLBACK_PROTOCOL_INIT on its protocols.  It's used in the\n\t * special case of a temporary vhost bound to a single protocol.\n\t */\n\tLWS_SERVER_OPTION_IGNORE_MISSING_CERT\t\t\t= (1 << 26),\n\t/**< (VH) Don't fail if the vhost TLS cert or key are missing, just\n\t * continue.  The vhost won't be able to serve anything, but if for\n\t * example the ACME plugin was configured to fetch a cert, this lets\n\t * you bootstrap your vhost from having no cert to start with.\n\t */\n\n\t/****** add new things just above ---^ ******/\n};\n\n#define lws_check_opt(c, f) (((c) & (f)) == (f))\n\nstruct lws_plat_file_ops;\n\n/** struct lws_context_creation_info - parameters to create context and /or vhost with\n *\n * This is also used to create vhosts.... if LWS_SERVER_OPTION_EXPLICIT_VHOSTS\n * is not given, then for backwards compatibility one vhost is created at\n * context-creation time using the info from this struct.\n *\n * If LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, then no vhosts are created\n * at the same time as the context, they are expected to be created afterwards.\n */\nstruct lws_context_creation_info {\n\tint port;\n\t/**< VHOST: Port to listen on. Use CONTEXT_PORT_NO_LISTEN to suppress\n\t * listening for a client. Use CONTEXT_PORT_NO_LISTEN_SERVER if you are\n\t * writing a server but you are using \\ref sock-adopt instead of the\n\t * built-in listener.\n\t *\n\t * You can also set port to 0, in which case the kernel will pick\n\t * a random port that is not already in use.  You can find out what\n\t * port the vhost is listening on using lws_get_vhost_listen_port() */\n\tconst char *iface;\n\t/**< VHOST: NULL to bind the listen socket to all interfaces, or the\n\t * interface name, eg, \"eth2\"\n\t * If options specifies LWS_SERVER_OPTION_UNIX_SOCK, this member is\n\t * the pathname of a UNIX domain socket. you can use the UNIX domain\n\t * sockets in abstract namespace, by prepending an at symbol to the\n\t * socket name. */\n\tconst struct lws_protocols *protocols;\n\t/**< VHOST: Array of structures listing supported protocols and a protocol-\n\t * specific callback for each one.  The list is ended with an\n\t * entry that has a NULL callback pointer. */\n\tconst struct lws_extension *extensions;\n\t/**< VHOST: NULL or array of lws_extension structs listing the\n\t * extensions this context supports. */\n\tconst struct lws_token_limits *token_limits;\n\t/**< CONTEXT: NULL or struct lws_token_limits pointer which is initialized\n\t * with a token length limit for each possible WSI_TOKEN_ */\n\tconst char *ssl_private_key_password;\n\t/**< VHOST: NULL or the passphrase needed for the private key. (For\n\t * backwards compatibility, this can also be used to pass the client\n\t * cert passphrase when setting up a vhost client SSL context, but it is\n\t * preferred to use .client_ssl_private_key_password for that.) */\n\tconst char *ssl_cert_filepath;\n\t/**< VHOST: If libwebsockets was compiled to use ssl, and you want\n\t * to listen using SSL, set to the filepath to fetch the\n\t * server cert from, otherwise NULL for unencrypted.  (For backwards\n\t * compatibility, this can also be used to pass the client certificate\n\t * when setting up a vhost client SSL context, but it is preferred to\n\t * use .client_ssl_cert_filepath for that.) */\n\tconst char *ssl_private_key_filepath;\n\t/**<  VHOST: filepath to private key if wanting SSL mode;\n\t * if this is set to NULL but ssl_cert_filepath is set, the\n\t * OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY callback is called\n\t * to allow setting of the private key directly via openSSL\n\t * library calls.   (For backwards compatibility, this can also be used\n\t * to pass the client cert private key filepath when setting up a\n\t * vhost client SSL context, but it is preferred to use\n\t * .client_ssl_private_key_filepath for that.) */\n\tconst char *ssl_ca_filepath;\n\t/**< VHOST: CA certificate filepath or NULL.  (For backwards\n\t * compatibility, this can also be used to pass the client CA\n\t * filepath when setting up a vhost client SSL context,\n\t * but it is preferred to use .client_ssl_ca_filepath for that.) */\n\tconst char *ssl_cipher_list;\n\t/**< VHOST: List of valid ciphers to use (eg,\n\t * \"RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL\"\n\t * or you can leave it as NULL to get \"DEFAULT\" (For backwards\n\t * compatibility, this can also be used to pass the client cipher\n\t * list when setting up a vhost client SSL context,\n\t * but it is preferred to use .client_ssl_cipher_list for that.)*/\n\tconst char *http_proxy_address;\n\t/**< VHOST: If non-NULL, attempts to proxy via the given address.\n\t * If proxy auth is required, use format \"username:password\\@server:port\" */\n\tunsigned int http_proxy_port;\n\t/**< VHOST: If http_proxy_address was non-NULL, uses this port */\n\tint gid;\n\t/**< CONTEXT: group id to change to after setting listen socket, or -1. */\n\tint uid;\n\t/**< CONTEXT: user id to change to after setting listen socket, or -1. */\n\tunsigned int options;\n\t/**< VHOST + CONTEXT: 0, or LWS_SERVER_OPTION_... bitfields */\n\tvoid *user;\n\t/**< VHOST + CONTEXT: optional user pointer that will be associated\n\t * with the context when creating the context (and can be retrieved by\n\t * lws_context_user(context), or with the vhost when creating the vhost\n\t * (and can be retrieved by lws_vhost_user(vhost)).  You will need to\n\t * use LWS_SERVER_OPTION_EXPLICIT_VHOSTS and create the vhost separately\n\t * if you care about giving the context and vhost different user pointer\n\t * values.\n\t */\n\tint ka_time;\n\t/**< CONTEXT: 0 for no TCP keepalive, otherwise apply this keepalive\n\t * timeout to all libwebsocket sockets, client or server */\n\tint ka_probes;\n\t/**< CONTEXT: if ka_time was nonzero, after the timeout expires how many\n\t * times to try to get a response from the peer before giving up\n\t * and killing the connection */\n\tint ka_interval;\n\t/**< CONTEXT: if ka_time was nonzero, how long to wait before each ka_probes\n\t * attempt */\n#if defined(LWS_WITH_TLS) && !defined(LWS_WITH_MBEDTLS)\n\tSSL_CTX *provided_client_ssl_ctx;\n\t/**< CONTEXT: If non-null, swap out libwebsockets ssl\n\t  * implementation for the one provided by provided_ssl_ctx.\n\t  * Libwebsockets no longer is responsible for freeing the context\n\t  * if this option is selected. */\n#else /* maintain structure layout either way */\n\tvoid *provided_client_ssl_ctx; /**< dummy if ssl disabled */\n#endif\n\n\tshort max_http_header_data;\n\t/**< CONTEXT: The max amount of header payload that can be handled\n\t * in an http request (unrecognized header payload is dropped) */\n\tshort max_http_header_pool;\n\t/**< CONTEXT: The max number of connections with http headers that\n\t * can be processed simultaneously (the corresponding memory is\n\t * allocated and deallocated dynamically as needed).  If the pool is\n\t * fully busy new incoming connections must wait for accept until one\n\t * becomes free. 0 = allow as many ah as number of availble fds for\n\t * the process */\n\n\tunsigned int count_threads;\n\t/**< CONTEXT: how many contexts to create in an array, 0 = 1 */\n\tunsigned int fd_limit_per_thread;\n\t/**< CONTEXT: nonzero means restrict each service thread to this\n\t * many fds, 0 means the default which is divide the process fd\n\t * limit by the number of threads. */\n\tunsigned int timeout_secs;\n\t/**< VHOST: various processes involving network roundtrips in the\n\t * library are protected from hanging forever by timeouts.  If\n\t * nonzero, this member lets you set the timeout used in seconds.\n\t * Otherwise a default timeout is used. */\n\tconst char *ecdh_curve;\n\t/**< VHOST: if NULL, defaults to initializing server with \"prime256v1\" */\n\tconst char *vhost_name;\n\t/**< VHOST: name of vhost, must match external DNS name used to\n\t * access the site, like \"warmcat.com\" as it's used to match\n\t * Host: header and / or SNI name for SSL. */\n\tconst char * const *plugin_dirs;\n\t/**< CONTEXT: NULL, or NULL-terminated array of directories to\n\t * scan for lws protocol plugins at context creation time */\n\tconst struct lws_protocol_vhost_options *pvo;\n\t/**< VHOST: pointer to optional linked list of per-vhost\n\t * options made accessible to protocols */\n\tint keepalive_timeout;\n\t/**< VHOST: (default = 0 = 5s) seconds to allow remote\n\t * client to hold on to an idle HTTP/1.1 connection */\n\tconst char *log_filepath;\n\t/**< VHOST: filepath to append logs to... this is opened before\n\t *\t\tany dropping of initial privileges */\n\tconst struct lws_http_mount *mounts;\n\t/**< VHOST: optional linked list of mounts for this vhost */\n\tconst char *server_string;\n\t/**< CONTEXT: string used in HTTP headers to identify server\n *\t\tsoftware, if NULL, \"libwebsockets\". */\n\tunsigned int pt_serv_buf_size;\n\t/**< CONTEXT: 0 = default of 4096.  This buffer is used by\n\t * various service related features including file serving, it\n\t * defines the max chunk of file that can be sent at once.\n\t * At the risk of lws having to buffer failed large sends, it\n\t * can be increased to, eg, 128KiB to improve throughput. */\n\tunsigned int max_http_header_data2;\n\t/**< CONTEXT: if max_http_header_data is 0 and this\n\t * is nonzero, this will be used in place of the default.  It's\n\t * like this for compatibility with the original short version,\n\t * this is unsigned int length. */\n\tlong ssl_options_set;\n\t/**< VHOST: Any bits set here will be set as SSL options */\n\tlong ssl_options_clear;\n\t/**< VHOST: Any bits set here will be cleared as SSL options */\n\tunsigned short ws_ping_pong_interval;\n\t/**< CONTEXT: 0 for none, else interval in seconds between sending\n\t * PINGs on idle websocket connections.  When the PING is sent,\n\t * the PONG must come within the normal timeout_secs timeout period\n\t * or the connection will be dropped.\n\t * Any RX or TX traffic on the connection restarts the interval timer,\n\t * so a connection which always sends or receives something at intervals\n\t * less than the interval given here will never send PINGs / expect\n\t * PONGs.  Conversely as soon as the ws connection is established, an\n\t * idle connection will do the PING / PONG roundtrip as soon as\n\t * ws_ping_pong_interval seconds has passed without traffic\n\t */\n\tconst struct lws_protocol_vhost_options *headers;\n\t\t/**< VHOST: pointer to optional linked list of per-vhost\n\t\t * canned headers that are added to server responses */\n\n\tconst struct lws_protocol_vhost_options *reject_service_keywords;\n\t/**< CONTEXT: Optional list of keywords and rejection codes + text.\n\t *\n\t * The keywords are checked for existing in the user agent string.\n\t *\n\t * Eg, \"badrobot\" \"404 Not Found\"\n\t */\n\tvoid *external_baggage_free_on_destroy;\n\t/**< CONTEXT: NULL, or pointer to something externally malloc'd, that\n\t * should be freed when the context is destroyed.  This allows you to\n\t * automatically sync the freeing action to the context destruction\n\t * action, so there is no need for an external free() if the context\n\t * succeeded to create.\n\t */\n\n\tconst char *client_ssl_private_key_password;\n\t/**< VHOST: Client SSL context init: NULL or the passphrase needed\n\t * for the private key */\n\tconst char *client_ssl_cert_filepath;\n\t/**< VHOST: Client SSL context init:T he certificate the client\n\t * should present to the peer on connection */\n\tconst char *client_ssl_private_key_filepath;\n\t/**<  VHOST: Client SSL context init: filepath to client private key\n\t * if this is set to NULL but client_ssl_cert_filepath is set, you\n\t * can handle the LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS\n\t * callback of protocols[0] to allow setting of the private key directly\n\t * via openSSL library calls */\n\tconst char *client_ssl_ca_filepath;\n\t/**< VHOST: Client SSL context init: CA certificate filepath or NULL */\n\tconst char *client_ssl_cipher_list;\n\t/**< VHOST: Client SSL context init: List of valid ciphers to use (eg,\n\t* \"RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL\"\n\t* or you can leave it as NULL to get \"DEFAULT\" */\n\n\tconst struct lws_plat_file_ops *fops;\n\t/**< CONTEXT: NULL, or pointer to an array of fops structs, terminated\n\t * by a sentinel with NULL .open.\n\t *\n\t * If NULL, lws provides just the platform file operations struct for\n\t * backwards compatibility.\n\t */\n\tint simultaneous_ssl_restriction;\n\t/**< CONTEXT: 0 (no limit) or limit of simultaneous SSL sessions possible.*/\n\tconst char *socks_proxy_address;\n\t/**< VHOST: If non-NULL, attempts to proxy via the given address.\n\t * If proxy auth is required, use format \"username:password\\@server:port\" */\n\tunsigned int socks_proxy_port;\n\t/**< VHOST: If socks_proxy_address was non-NULL, uses this port */\n#if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)\n\tcap_value_t caps[4];\n\t/**< CONTEXT: array holding Linux capabilities you want to\n\t * continue to be available to the server after it transitions\n\t * to a noprivileged user.  Usually none are needed but for, eg,\n\t * .bind_iface, CAP_NET_RAW is required.  This gives you a way\n\t * to still have the capability but drop root.\n\t */\n\tchar count_caps;\n\t/**< CONTEXT: count of Linux capabilities in .caps[].  0 means\n\t * no capabilities will be inherited from root (the default) */\n#endif\n\tint bind_iface;\n\t/**< VHOST: nonzero to strictly bind sockets to the interface name in\n\t * .iface (eg, \"eth2\"), using SO_BIND_TO_DEVICE.\n\t *\n\t * Requires SO_BINDTODEVICE support from your OS and CAP_NET_RAW\n\t * capability.\n\t *\n\t * Notice that common things like access network interface IP from\n\t * your local machine use your lo / loopback interface and will be\n\t * disallowed by this.\n\t */\n\tint ssl_info_event_mask;\n\t/**< VHOST: mask of ssl events to be reported on LWS_CALLBACK_SSL_INFO\n\t * callback for connections on this vhost.  The mask values are of\n\t * the form SSL_CB_ALERT, defined in openssl/ssl.h.  The default of\n\t * 0 means no info events will be reported.\n\t */\n\tunsigned int timeout_secs_ah_idle;\n\t/**< VHOST: seconds to allow a client to hold an ah without using it.\n\t * 0 defaults to 10s. */\n\tunsigned short ip_limit_ah;\n\t/**< CONTEXT: max number of ah a single IP may use simultaneously\n\t *\t      0 is no limit. This is a soft limit: if the limit is\n\t *\t      reached, connections from that IP will wait in the ah\n\t *\t      waiting list and not be able to acquire an ah until\n\t *\t      a connection belonging to the IP relinquishes one it\n\t *\t      already has.\n\t */\n\tunsigned short ip_limit_wsi;\n\t/**< CONTEXT: max number of wsi a single IP may use simultaneously.\n\t *\t      0 is no limit.  This is a hard limit, connections from\n\t *\t      the same IP will simply be dropped once it acquires the\n\t *\t      amount of simultaneous wsi / accepted connections\n\t *\t      given here.\n\t */\n\tuint32_t\thttp2_settings[7];\n\t/**< VHOST:  if http2_settings[0] is nonzero, the values given in\n\t *\t      http2_settings[1]..[6] are used instead of the lws\n\t *\t      platform default values.\n\t *\t      Just leave all at 0 if you don't care.\n\t */\n\tconst char *error_document_404;\n\t/**< VHOST: If non-NULL, when asked to serve a non-existent file,\n\t *          lws attempts to server this url path instead.  Eg,\n\t *          \"/404.html\" */\n\tconst char *alpn;\n\t/**< CONTEXT: If non-NULL, default list of advertised alpn, comma-\n\t *\t      separated\n\t *\n\t *     VHOST: If non-NULL, per-vhost list of advertised alpn, comma-\n\t *\t      separated\n\t */\n\tvoid **foreign_loops;\n\t/**< CONTEXT: This is ignored if the context is not being started with\n\t *\t\tan event loop, ie, .options has a flag like\n\t *\t\tLWS_SERVER_OPTION_LIBUV.\n\t *\n\t *\t\tNULL indicates lws should start its own even loop for\n\t *\t\teach service thread, and deal with closing the loops\n\t *\t\twhen the context is destroyed.\n\t *\n\t *\t\tNon-NULL means it points to an array of external\n\t *\t\t(\"foreign\") event loops that are to be used in turn for\n\t *\t\teach service thread.  In the default case of 1 service\n\t *\t\tthread, it can just point to one foreign event loop.\n\t */\n\tvoid (*signal_cb)(void *event_lib_handle, int signum);\n\t/**< CONTEXT: NULL: default signal handling.  Otherwise this receives\n\t *\t\tthe signal handler callback.  event_lib_handle is the\n\t *\t\tnative event library signal handle, eg uv_signal_t *\n\t *\t\tfor libuv.\n\t */\n\n\t/* Add new things just above here ---^\n\t * This is part of the ABI, don't needlessly break compatibility\n\t *\n\t * The below is to ensure later library versions with new\n\t * members added above will see 0 (default) even if the app\n\t * was not built against the newer headers.\n\t */\n\tstruct lws_context **pcontext;\n\t/**< CONTEXT: if non-NULL, at the end of context destroy processing,\n\t * the pointer pointed to by pcontext is written with NULL.  You can\n\t * use this to let foreign event loops know that lws context destruction\n\t * is fully completed.\n\t */\n\n\tvoid *_unused[4]; /**< dummy */\n};\n\n/**\n * lws_create_context() - Create the websocket handler\n * \\param info:\tpointer to struct with parameters\n *\n *\tThis function creates the listening socket (if serving) and takes care\n *\tof all initialization in one step.\n *\n *\tIf option LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, no vhost is\n *\tcreated; you're expected to create your own vhosts afterwards using\n *\tlws_create_vhost().  Otherwise a vhost named \"default\" is also created\n *\tusing the information in the vhost-related members, for compatibility.\n *\n *\tAfter initialization, it returns a struct lws_context * that\n *\trepresents this server.  After calling, user code needs to take care\n *\tof calling lws_service() with the context pointer to get the\n *\tserver's sockets serviced.  This must be done in the same process\n *\tcontext as the initialization call.\n *\n *\tThe protocol callback functions are called for a handful of events\n *\tincluding http requests coming in, websocket connections becoming\n *\testablished, and data arriving; it's also called periodically to allow\n *\tasync transmission.\n *\n *\tHTTP requests are sent always to the FIRST protocol in protocol, since\n *\tat that time websocket protocol has not been negotiated.  Other\n *\tprotocols after the first one never see any HTTP callback activity.\n *\n *\tThe server created is a simple http server by default; part of the\n *\twebsocket standard is upgrading this http connection to a websocket one.\n *\n *\tThis allows the same server to provide files like scripts and favicon /\n *\timages or whatever over http and dynamic data over websockets all in\n *\tone place; they're all handled in the user callback.\n */\nLWS_VISIBLE LWS_EXTERN struct lws_context *\nlws_create_context(const struct lws_context_creation_info *info);\n\n\n/**\n * lws_context_destroy() - Destroy the websocket context\n * \\param context:\tWebsocket context\n *\n *\tThis function closes any active connections and then frees the\n *\tcontext.  After calling this, any further use of the context is\n *\tundefined.\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_context_destroy(struct lws_context *context);\n\ntypedef int (*lws_reload_func)(void);\n\n/**\n * lws_context_deprecate() - Deprecate the websocket context\n *\n * \\param context:\tWebsocket context\n * \\param cb: Callback notified when old context listen sockets are closed\n *\n *\tThis function is used on an existing context before superceding it\n *\twith a new context.\n *\n *\tIt closes any listen sockets in the context, so new connections are\n *\tnot possible.\n *\n *\tAnd it marks the context to be deleted when the number of active\n *\tconnections into it falls to zero.\n *\n *\tOtherwise if you attach the deprecated context to the replacement\n *\tcontext when it has been created using lws_context_attach_deprecated()\n *\tboth any deprecated and the new context will service their connections.\n *\n *\tThis is aimed at allowing seamless configuration reloads.\n *\n *\tThe callback cb will be called after the listen sockets are actually\n *\tclosed and may be reopened.  In the callback the new context should be\n *\tconfigured and created.  (With libuv, socket close happens async after\n *\tmore loop events).\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_context_deprecate(struct lws_context *context, lws_reload_func cb);\n\nLWS_VISIBLE LWS_EXTERN int\nlws_context_is_deprecated(struct lws_context *context);\n\n/**\n * lws_set_proxy() - Setups proxy to lws_context.\n * \\param vhost:\tpointer to struct lws_vhost you want set proxy for\n * \\param proxy: pointer to c string containing proxy in format address:port\n *\n * Returns 0 if proxy string was parsed and proxy was setup.\n * Returns -1 if proxy is NULL or has incorrect format.\n *\n * This is only required if your OS does not provide the http_proxy\n * environment variable (eg, OSX)\n *\n *   IMPORTANT! You should call this function right after creation of the\n *   lws_context and before call to connect. If you call this\n *   function after connect behavior is undefined.\n *   This function will override proxy settings made on lws_context\n *   creation with genenv() call.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_set_proxy(struct lws_vhost *vhost, const char *proxy);\n\n/**\n * lws_set_socks() - Setup socks to lws_context.\n * \\param vhost:\tpointer to struct lws_vhost you want set socks for\n * \\param socks: pointer to c string containing socks in format address:port\n *\n * Returns 0 if socks string was parsed and socks was setup.\n * Returns -1 if socks is NULL or has incorrect format.\n *\n * This is only required if your OS does not provide the socks_proxy\n * environment variable (eg, OSX)\n *\n *   IMPORTANT! You should call this function right after creation of the\n *   lws_context and before call to connect. If you call this\n *   function after connect behavior is undefined.\n *   This function will override proxy settings made on lws_context\n *   creation with genenv() call.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_set_socks(struct lws_vhost *vhost, const char *socks);\n\nstruct lws_vhost;\n\n/**\n * lws_create_vhost() - Create a vhost (virtual server context)\n * \\param context:\tpointer to result of lws_create_context()\n * \\param info:\t\tpointer to struct with parameters\n *\n * This function creates a virtual server (vhost) using the vhost-related\n * members of the info struct.  You can create many vhosts inside one context\n * if you created the context with the option LWS_SERVER_OPTION_EXPLICIT_VHOSTS\n */\nLWS_VISIBLE LWS_EXTERN struct lws_vhost *\nlws_create_vhost(struct lws_context *context,\n\t\t const struct lws_context_creation_info *info);\n\n/**\n * lws_vhost_destroy() - Destroy a vhost (virtual server context)\n *\n * \\param vh:\tpointer to result of lws_create_vhost()\n *\n * This function destroys a vhost.  Normally, if you just want to exit,\n * then lws_destroy_context() will take care of everything.  If you want\n * to destroy an individual vhost and all connections and allocations, you\n * can do it with this.\n *\n * If the vhost has a listen sockets shared by other vhosts, it will be given\n * to one of the vhosts sharing it rather than closed.\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_vhost_destroy(struct lws_vhost *vh);\n\n/**\n * lwsws_get_config_globals() - Parse a JSON server config file\n * \\param info:\t\tpointer to struct with parameters\n * \\param d:\t\tfilepath of the config file\n * \\param config_strings: storage for the config strings extracted from JSON,\n * \t\t\t  the pointer is incremented as strings are stored\n * \\param len:\t\tpointer to the remaining length left in config_strings\n *\t\t\t  the value is decremented as strings are stored\n *\n * This function prepares a n lws_context_creation_info struct with global\n * settings from a file d.\n *\n * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled\n */\nLWS_VISIBLE LWS_EXTERN int\nlwsws_get_config_globals(struct lws_context_creation_info *info, const char *d,\n\t\t\t char **config_strings, int *len);\n\n/**\n * lwsws_get_config_vhosts() - Create vhosts from a JSON server config file\n * \\param context:\tpointer to result of lws_create_context()\n * \\param info:\t\tpointer to struct with parameters\n * \\param d:\t\tfilepath of the config file\n * \\param config_strings: storage for the config strings extracted from JSON,\n * \t\t\t  the pointer is incremented as strings are stored\n * \\param len:\t\tpointer to the remaining length left in config_strings\n *\t\t\t  the value is decremented as strings are stored\n *\n * This function creates vhosts into a context according to the settings in\n *JSON files found in directory d.\n *\n * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled\n */\nLWS_VISIBLE LWS_EXTERN int\nlwsws_get_config_vhosts(struct lws_context *context,\n\t\t\tstruct lws_context_creation_info *info, const char *d,\n\t\t\tchar **config_strings, int *len);\n\n/** lws_vhost_get() - \\deprecated deprecated: use lws_get_vhost() */\nLWS_VISIBLE LWS_EXTERN struct lws_vhost *\nlws_vhost_get(struct lws *wsi) LWS_WARN_DEPRECATED;\n\n/**\n * lws_get_vhost() - return the vhost a wsi belongs to\n *\n * \\param wsi: which connection\n */\nLWS_VISIBLE LWS_EXTERN struct lws_vhost *\nlws_get_vhost(struct lws *wsi);\n\n/**\n * lws_get_vhost_name() - returns the name of a vhost\n *\n * \\param vhost: which vhost\n */\nLWS_VISIBLE LWS_EXTERN const char *\nlws_get_vhost_name(struct lws_vhost *vhost);\n\n/**\n * lws_get_vhost_port() - returns the port a vhost listens on, or -1\n *\n * \\param vhost: which vhost\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_get_vhost_port(struct lws_vhost *vhost);\n\n/**\n * lws_get_vhost_user() - returns the user pointer for the vhost\n *\n * \\param vhost: which vhost\n */\nLWS_VISIBLE LWS_EXTERN void *\nlws_get_vhost_user(struct lws_vhost *vhost);\n\n/**\n * lws_get_vhost_iface() - returns the binding for the vhost listen socket\n *\n * \\param vhost: which vhost\n */\nLWS_VISIBLE LWS_EXTERN const char *\nlws_get_vhost_iface(struct lws_vhost *vhost);\n\n/**\n * lws_json_dump_vhost() - describe vhost state and stats in JSON\n *\n * \\param vh: the vhost\n * \\param buf: buffer to fill with JSON\n * \\param len: max length of buf\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len);\n\n/**\n * lws_json_dump_context() - describe context state and stats in JSON\n *\n * \\param context: the context\n * \\param buf: buffer to fill with JSON\n * \\param len: max length of buf\n * \\param hide_vhosts: nonzero to not provide per-vhost mount etc information\n *\n * Generates a JSON description of vhost state into buf\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_json_dump_context(const struct lws_context *context, char *buf, int len,\n\t\t      int hide_vhosts);\n\n/**\n * lws_vhost_user() - get the user data associated with the vhost\n * \\param vhost: Websocket vhost\n *\n * This returns the optional user pointer that can be attached to\n * a vhost when it was created.  Lws never dereferences this pointer, it only\n * sets it when the vhost is created, and returns it using this api.\n */\nLWS_VISIBLE LWS_EXTERN void *\nlws_vhost_user(struct lws_vhost *vhost);\n\n/**\n * lws_context_user() - get the user data associated with the context\n * \\param context: Websocket context\n *\n * This returns the optional user allocation that can be attached to\n * the context the sockets live in at context_create time.  It's a way\n * to let all sockets serviced in the same context share data without\n * using globals statics in the user code.\n */\nLWS_VISIBLE LWS_EXTERN void *\nlws_context_user(struct lws_context *context);\n\n/*! \\defgroup vhost-mounts Vhost mounts and options\n * \\ingroup context-and-vhost-creation\n *\n * ##Vhost mounts and options\n */\n///@{\n/** struct lws_protocol_vhost_options - linked list of per-vhost protocol\n * \t\t\t\t\tname=value options\n *\n * This provides a general way to attach a linked-list of name=value pairs,\n * which can also have an optional child link-list using the options member.\n */\nstruct lws_protocol_vhost_options {\n\tconst struct lws_protocol_vhost_options *next; /**< linked list */\n\tconst struct lws_protocol_vhost_options *options; /**< child linked-list of more options for this node */\n\tconst char *name; /**< name of name=value pair */\n\tconst char *value; /**< value of name=value pair */\n};\n\n/** enum lws_mount_protocols\n * This specifies the mount protocol for a mountpoint, whether it is to be\n * served from a filesystem, or it is a cgi etc.\n */\nenum lws_mount_protocols {\n\tLWSMPRO_HTTP\t\t= 0, /**< http reverse proxy */\n\tLWSMPRO_HTTPS\t\t= 1, /**< https reverse proxy */\n\tLWSMPRO_FILE\t\t= 2, /**< serve from filesystem directory */\n\tLWSMPRO_CGI\t\t= 3, /**< pass to CGI to handle */\n\tLWSMPRO_REDIR_HTTP\t= 4, /**< redirect to http:// url */\n\tLWSMPRO_REDIR_HTTPS\t= 5, /**< redirect to https:// url */\n\tLWSMPRO_CALLBACK\t= 6, /**< hand by named protocol's callback */\n};\n\n/** struct lws_http_mount\n *\n * arguments for mounting something in a vhost's url namespace\n */\nstruct lws_http_mount {\n\tconst struct lws_http_mount *mount_next;\n\t/**< pointer to next struct lws_http_mount */\n\tconst char *mountpoint;\n\t/**< mountpoint in http pathspace, eg, \"/\" */\n\tconst char *origin;\n\t/**< path to be mounted, eg, \"/var/www/warmcat.com\" */\n\tconst char *def;\n\t/**< default target, eg, \"index.html\" */\n\tconst char *protocol;\n\t/**<\"protocol-name\" to handle mount */\n\n\tconst struct lws_protocol_vhost_options *cgienv;\n\t/**< optional linked-list of cgi options.  These are created\n\t * as environment variables for the cgi process\n\t */\n\tconst struct lws_protocol_vhost_options *extra_mimetypes;\n\t/**< optional linked-list of mimetype mappings */\n\tconst struct lws_protocol_vhost_options *interpret;\n\t/**< optional linked-list of files to be interpreted */\n\n\tint cgi_timeout;\n\t/**< seconds cgi is allowed to live, if cgi://mount type */\n\tint cache_max_age;\n\t/**< max-age for reuse of client cache of files, seconds */\n\tunsigned int auth_mask;\n\t/**< bits set here must be set for authorized client session */\n\n\tunsigned int cache_reusable:1; /**< set if client cache may reuse this */\n\tunsigned int cache_revalidate:1; /**< set if client cache should revalidate on use */\n\tunsigned int cache_intermediaries:1; /**< set if intermediaries are allowed to cache */\n\n\tunsigned char origin_protocol; /**< one of enum lws_mount_protocols */\n\tunsigned char mountpoint_len; /**< length of mountpoint string */\n\n\tconst char *basic_auth_login_file;\n\t/**<NULL, or filepath to use to check basic auth logins against */\n\n\t/* Add new things just above here ---^\n\t * This is part of the ABI, don't needlessly break compatibility\n\t *\n\t * The below is to ensure later library versions with new\n\t * members added above will see 0 (default) even if the app\n\t * was not built against the newer headers.\n\t */\n\n\tvoid *_unused[2]; /**< dummy */\n};\n///@}\n///@}\n\n/*! \\defgroup client Client related functions\n * ##Client releated functions\n * \\ingroup lwsapi\n *\n * */\n///@{\n\n/** enum lws_client_connect_ssl_connection_flags - flags that may be used\n * with struct lws_client_connect_info ssl_connection member to control if\n * and how SSL checks apply to the client connection being created\n */\n\nenum lws_client_connect_ssl_connection_flags {\n\tLCCSCF_USE_SSL \t\t\t\t= (1 << 0),\n\tLCCSCF_ALLOW_SELFSIGNED\t\t\t= (1 << 1),\n\tLCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK\t= (1 << 2),\n\tLCCSCF_ALLOW_EXPIRED\t\t\t= (1 << 3),\n\n\tLCCSCF_PIPELINE\t\t\t\t= (1 << 16),\n\t\t/**< Serialize / pipeline multiple client connections\n\t\t * on a single connection where possible.\n\t\t *\n\t\t * HTTP/1.0: possible if Keep-Alive: yes sent by server\n\t\t * HTTP/1.1: always possible... uses pipelining\n\t\t * HTTP/2:   always possible... uses parallel streams\n\t\t * */\n};\n\n/** struct lws_client_connect_info - parameters to connect with when using\n *\t\t\t\t    lws_client_connect_via_info() */\n\nstruct lws_client_connect_info {\n\tstruct lws_context *context;\n\t/**< lws context to create connection in */\n\tconst char *address;\n\t/**< remote address to connect to */\n\tint port;\n\t/**< remote port to connect to */\n\tint ssl_connection;\n\t/**< 0, or a combination of LCCSCF_ flags */\n\tconst char *path;\n\t/**< uri path */\n\tconst char *host;\n\t/**< content of host header */\n\tconst char *origin;\n\t/**< content of origin header */\n\tconst char *protocol;\n\t/**< list of ws protocols we could accept */\n\tint ietf_version_or_minus_one;\n\t/**< deprecated: currently leave at 0 or -1 */\n\tvoid *userdata;\n\t/**< if non-NULL, use this as wsi user_data instead of malloc it */\n\tconst void *client_exts;\n\t/**< UNUSED... provide in info.extensions at context creation time */\n\tconst char *method;\n\t/**< if non-NULL, do this http method instead of ws[s] upgrade.\n\t * use \"GET\" to be a simple http client connection.  \"RAW\" gets\n\t * you a connected socket that lws itself will leave alone once\n\t * connected. */\n\tstruct lws *parent_wsi;\n\t/**< if another wsi is responsible for this connection, give it here.\n\t * this is used to make sure if the parent closes so do any\n\t * child connections first. */\n\tconst char *uri_replace_from;\n\t/**< if non-NULL, when this string is found in URIs in\n\t * text/html content-encoding, it's replaced with uri_replace_to */\n\tconst char *uri_replace_to;\n\t/**< see uri_replace_from */\n\tstruct lws_vhost *vhost;\n\t/**< vhost to bind to (used to determine related SSL_CTX) */\n\tstruct lws **pwsi;\n\t/**< if not NULL, store the new wsi here early in the connection\n\t * process.  Although we return the new wsi, the call to create the\n\t * client connection does progress the connection somewhat and may\n\t * meet an error that will result in the connection being scrubbed and\n\t * NULL returned.  While the wsi exists though, he may process a\n\t * callback like CLIENT_CONNECTION_ERROR with his wsi: this gives the\n\t * user callback a way to identify which wsi it is that faced the error\n\t * even before the new wsi is returned and even if ultimately no wsi\n\t * is returned.\n\t */\n\tconst char *iface;\n\t/**< NULL to allow routing on any interface, or interface name or IP\n\t * to bind the socket to */\n\tconst char *local_protocol_name;\n\t/**< NULL: .protocol is used both to select the local protocol handler\n\t *         to bind to and as the list of remote ws protocols we could\n\t *         accept.\n\t *   non-NULL: this protocol name is used to bind the connection to\n\t *             the local protocol handler.  .protocol is used for the\n\t *             list of remote ws protocols we could accept */\n\n\t/* Add new things just above here ---^\n\t * This is part of the ABI, don't needlessly break compatibility\n\t *\n\t * The below is to ensure later library versions with new\n\t * members added above will see 0 (default) even if the app\n\t * was not built against the newer headers.\n\t */\n\tconst char *alpn;\n\t/* NULL: allow lws default ALPN list, from vhost if present or from\n\t *       list of roles built into lws\n\t * non-NULL: require one from provided comma-separated list of alpn\n\t *           tokens\n\t */\n\n\tvoid *_unused[4]; /**< dummy */\n};\n\n/**\n * lws_client_connect_via_info() - Connect to another websocket server\n * \\param ccinfo: pointer to lws_client_connect_info struct\n *\n *\tThis function creates a connection to a remote server using the\n *\tinformation provided in ccinfo.\n */\nLWS_VISIBLE LWS_EXTERN struct lws *\nlws_client_connect_via_info(struct lws_client_connect_info * ccinfo);\n\n/**\n * lws_client_connect() - Connect to another websocket server\n * \t\t\\deprecated DEPRECATED use lws_client_connect_via_info\n * \\param clients:\tWebsocket context\n * \\param address:\tRemote server address, eg, \"myserver.com\"\n * \\param port:\tPort to connect to on the remote server, eg, 80\n * \\param ssl_connection:\t0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self\n *\t\t\tsigned certs\n * \\param path:\tWebsocket path on server\n * \\param host:\tHostname on server\n * \\param origin:\tSocket origin name\n * \\param protocol:\tComma-separated list of protocols being asked for from\n *\t\tthe server, or just one.  The server will pick the one it\n *\t\tlikes best.  If you don't want to specify a protocol, which is\n *\t\tlegal, use NULL here.\n * \\param ietf_version_or_minus_one: -1 to ask to connect using the default, latest\n *\t\tprotocol supported, or the specific protocol ordinal\n *\n *\tThis function creates a connection to a remote server\n */\n/* deprecated, use lws_client_connect_via_info() */\nLWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT\nlws_client_connect(struct lws_context *clients, const char *address,\n\t\t   int port, int ssl_connection, const char *path,\n\t\t   const char *host, const char *origin, const char *protocol,\n\t\t   int ietf_version_or_minus_one) LWS_WARN_DEPRECATED;\n/* deprecated, use lws_client_connect_via_info() */\n/**\n * lws_client_connect_extended() - Connect to another websocket server\n * \t\t\t\\deprecated DEPRECATED use lws_client_connect_via_info\n * \\param clients:\tWebsocket context\n * \\param address:\tRemote server address, eg, \"myserver.com\"\n * \\param port:\tPort to connect to on the remote server, eg, 80\n * \\param ssl_connection:\t0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self\n *\t\t\tsigned certs\n * \\param path:\tWebsocket path on server\n * \\param host:\tHostname on server\n * \\param origin:\tSocket origin name\n * \\param protocol:\tComma-separated list of protocols being asked for from\n *\t\tthe server, or just one.  The server will pick the one it\n *\t\tlikes best.\n * \\param ietf_version_or_minus_one: -1 to ask to connect using the default, latest\n *\t\tprotocol supported, or the specific protocol ordinal\n * \\param userdata: Pre-allocated user data\n *\n *\tThis function creates a connection to a remote server\n */\nLWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT\nlws_client_connect_extended(struct lws_context *clients, const char *address,\n\t\t\t    int port, int ssl_connection, const char *path,\n\t\t\t    const char *host, const char *origin,\n\t\t\t    const char *protocol, int ietf_version_or_minus_one,\n\t\t\t    void *userdata) LWS_WARN_DEPRECATED;\n\n/**\n * lws_init_vhost_client_ssl() - also enable client SSL on an existing vhost\n *\n * \\param info: client ssl related info\n * \\param vhost: which vhost to initialize client ssl operations on\n *\n * You only need to call this if you plan on using SSL client connections on\n * the vhost.  For non-SSL client connections, it's not necessary to call this.\n *\n * The following members of info are used during the call\n *\n *\t - options must have LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT set,\n *\t     otherwise the call does nothing\n *\t - provided_client_ssl_ctx must be NULL to get a generated client\n *\t     ssl context, otherwise you can pass a prepared one in by setting it\n *\t - ssl_cipher_list may be NULL or set to the client valid cipher list\n *\t - ssl_ca_filepath may be NULL or client cert filepath\n *\t - ssl_cert_filepath may be NULL or client cert filepath\n *\t - ssl_private_key_filepath may be NULL or client cert private key\n *\n * You must create your vhost explicitly if you want to use this, so you have\n * a pointer to the vhost.  Create the context first with the option flag\n * LWS_SERVER_OPTION_EXPLICIT_VHOSTS and then call lws_create_vhost() with\n * the same info struct.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_init_vhost_client_ssl(const struct lws_context_creation_info *info,\n\t\t\t  struct lws_vhost *vhost);\n/**\n * lws_http_client_read() - consume waiting received http client data\n *\n * \\param wsi: client connection\n * \\param buf: pointer to buffer pointer - fill with pointer to your buffer\n * \\param len: pointer to chunk length - fill with max length of buffer\n *\n * This is called when the user code is notified client http data has arrived.\n * The user code may choose to delay calling it to consume the data, for example\n * waiting until an onward connection is writeable.\n *\n * For non-chunked connections, up to len bytes of buf are filled with the\n * received content.  len is set to the actual amount filled before return.\n *\n * For chunked connections, the linear buffer content contains the chunking\n * headers and it cannot be passed in one lump.  Instead, this function will\n * call back LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ with in pointing to the\n * chunk start and len set to the chunk length.  There will be as many calls\n * as there are chunks or partial chunks in the buffer.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_http_client_read(struct lws *wsi, char **buf, int *len);\n\n/**\n * lws_http_client_http_response() - get last HTTP response code\n *\n * \\param wsi: client connection\n *\n * Returns the last server response code, eg, 200 for client http connections.\n *\n * You should capture this during the LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\n * callback, because after that the memory reserved for storing the related\n * headers is freed and this value is lost.\n */\nLWS_VISIBLE LWS_EXTERN unsigned int\nlws_http_client_http_response(struct lws *wsi);\n\nLWS_VISIBLE LWS_EXTERN void\nlws_client_http_body_pending(struct lws *wsi, int something_left_to_send);\n\n/**\n * lws_client_http_body_pending() - control if client connection neeeds to send body\n *\n * \\param wsi: client connection\n * \\param something_left_to_send: nonzero if need to send more body, 0 (default)\n * \t\t\t\tif nothing more to send\n *\n * If you will send payload data with your HTTP client connection, eg, for POST,\n * when you set the related http headers in\n * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER callback you should also call\n * this API with something_left_to_send nonzero, and call\n * lws_callback_on_writable(wsi);\n *\n * After sending the headers, lws will call your callback with\n * LWS_CALLBACK_CLIENT_HTTP_WRITEABLE reason when writable.  You can send the\n * next part of the http body payload, calling lws_callback_on_writable(wsi);\n * if there is more to come, or lws_client_http_body_pending(wsi, 0); to\n * let lws know the last part is sent and the connection can move on.\n */\n\n///@}\n\n/** \\defgroup service Built-in service loop entry\n *\n * ##Built-in service loop entry\n *\n * If you're not using libev / libuv, these apis are needed to enter the poll()\n * wait in lws and service any connections with pending events.\n */\n///@{\n\n/**\n * lws_service() - Service any pending websocket activity\n * \\param context:\tWebsocket context\n * \\param timeout_ms:\tTimeout for poll; 0 means return immediately if nothing needed\n *\t\tservice otherwise block and service immediately, returning\n *\t\tafter the timeout if nothing needed service.\n *\n *\tThis function deals with any pending websocket traffic, for three\n *\tkinds of event.  It handles these events on both server and client\n *\ttypes of connection the same.\n *\n *\t1) Accept new connections to our context's server\n *\n *\t2) Call the receive callback for incoming frame data received by\n *\t    server or client connections.\n *\n *\tYou need to call this service function periodically to all the above\n *\tfunctions to happen; if your application is single-threaded you can\n *\tjust call it in your main event loop.\n *\n *\tAlternatively you can fork a new process that asynchronously handles\n *\tcalling this service in a loop.  In that case you are happy if this\n *\tcall blocks your thread until it needs to take care of something and\n *\twould call it with a large nonzero timeout.  Your loop then takes no\n *\tCPU while there is nothing happening.\n *\n *\tIf you are calling it in a single-threaded app, you don't want it to\n *\twait around blocking other things in your loop from happening, so you\n *\twould call it with a timeout_ms of 0, so it returns immediately if\n *\tnothing is pending, or as soon as it services whatever was pending.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_service(struct lws_context *context, int timeout_ms);\n\n/**\n * lws_service_tsi() - Service any pending websocket activity\n *\n * \\param context:\tWebsocket context\n * \\param timeout_ms:\tTimeout for poll; 0 means return immediately if nothing needed\n *\t\tservice otherwise block and service immediately, returning\n *\t\tafter the timeout if nothing needed service.\n * \\param tsi:\t\tThread service index, starting at 0\n *\n * Same as lws_service(), but for a specific thread service index.  Only needed\n * if you are spawning multiple service threads.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_service_tsi(struct lws_context *context, int timeout_ms, int tsi);\n\n/**\n * lws_cancel_service_pt() - Cancel servicing of pending socket activity\n *\t\t\t\ton one thread\n * \\param wsi:\tCancel service on the thread this wsi is serviced by\n *\n * Same as lws_cancel_service(), but targets a single service thread, the one\n * the wsi belongs to.  You probably want to use lws_cancel_service() instead.\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_cancel_service_pt(struct lws *wsi);\n\n/**\n * lws_cancel_service() - Cancel wait for new pending socket activity\n * \\param context:\tWebsocket context\n *\n * This function creates an immediate \"synchronous interrupt\" to the lws poll()\n * wait or event loop.  As soon as possible in the serialzed service sequencing,\n * a LWS_CALLBACK_EVENT_WAIT_CANCELLED callback is sent to every protocol on\n * every vhost.\n *\n * lws_cancel_service() may be called from another thread while the context\n * exists, and its effect will be immediately serialized.\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_cancel_service(struct lws_context *context);\n\n/**\n * lws_service_fd() - Service polled socket with something waiting\n * \\param context:\tWebsocket context\n * \\param pollfd:\tThe pollfd entry describing the socket fd and which events\n *\t\thappened, or NULL to tell lws to do only timeout servicing.\n *\n * This function takes a pollfd that has POLLIN or POLLOUT activity and\n * services it according to the state of the associated\n * struct lws.\n *\n * The one call deals with all \"service\" that might happen on a socket\n * including listen accepts, http files as well as websocket protocol.\n *\n * If a pollfd says it has something, you can just pass it to\n * lws_service_fd() whether it is a socket handled by lws or not.\n * If it sees it is a lws socket, the traffic will be handled and\n * pollfd->revents will be zeroed now.\n *\n * If the socket is foreign to lws, it leaves revents alone.  So you can\n * see if you should service yourself by checking the pollfd revents\n * after letting lws try to service it.\n *\n * You should also call this with pollfd = NULL to just allow the\n * once-per-second global timeout checks; if less than a second since the last\n * check it returns immediately then.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd);\n\n/**\n * lws_service_fd_tsi() - Service polled socket in specific service thread\n * \\param context:\tWebsocket context\n * \\param pollfd:\tThe pollfd entry describing the socket fd and which events\n *\t\thappened.\n * \\param tsi: thread service index\n *\n * Same as lws_service_fd() but used with multiple service threads\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd,\n\t\t   int tsi);\n\n/**\n * lws_service_adjust_timeout() - Check for any connection needing forced service\n * \\param context:\tWebsocket context\n * \\param timeout_ms:\tThe original poll timeout value.  You can just set this\n *\t\t\tto 1 if you don't really have a poll timeout.\n * \\param tsi: thread service index\n *\n * Under some conditions connections may need service even though there is no\n * pending network action on them, this is \"forced service\".  For default\n * poll() and libuv / libev, the library takes care of calling this and\n * dealing with it for you.  But for external poll() integration, you need\n * access to the apis.\n *\n * If anybody needs \"forced service\", returned timeout is zero.  In that case,\n * you can call lws_service_tsi() with a timeout of -1 to only service\n * guys who need forced service.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_service_adjust_timeout(struct lws_context *context, int timeout_ms, int tsi);\n\n/* Backwards compatibility */\n#define lws_plat_service_tsi lws_service_tsi\n\nLWS_VISIBLE LWS_EXTERN int\nlws_handle_POLLOUT_event(struct lws *wsi, struct lws_pollfd *pollfd);\n\n///@}\n\n/*! \\defgroup http HTTP\n\n    Modules related to handling HTTP\n*/\n//@{\n\n/*! \\defgroup httpft HTTP File transfer\n * \\ingroup http\n\n    APIs for sending local files in response to HTTP requests\n*/\n//@{\n\n/**\n * lws_get_mimetype() - Determine mimetype to use from filename\n *\n * \\param file:\t\tfilename\n * \\param m:\t\tNULL, or mount context\n *\n * This uses a canned list of known filetypes first, if no match and m is\n * non-NULL, then tries a list of per-mount file suffix to mimtype mappings.\n *\n * Returns either NULL or a pointer to the mimetype matching the file.\n */\nLWS_VISIBLE LWS_EXTERN const char *\nlws_get_mimetype(const char *file, const struct lws_http_mount *m);\n\n/**\n * lws_serve_http_file() - Send a file back to the client using http\n * \\param wsi:\t\tWebsocket instance (available from user callback)\n * \\param file:\t\tThe file to issue over http\n * \\param content_type:\tThe http content type, eg, text/html\n * \\param other_headers:\tNULL or pointer to header string\n * \\param other_headers_len:\tlength of the other headers if non-NULL\n *\n *\tThis function is intended to be called from the callback in response\n *\tto http requests from the client.  It allows the callback to issue\n *\tlocal files down the http link in a single step.\n *\n *\tReturning <0 indicates error and the wsi should be closed.  Returning\n *\t>0 indicates the file was completely sent and\n *\tlws_http_transaction_completed() called on the wsi (and close if != 0)\n *\t==0 indicates the file transfer is started and needs more service later,\n *\tthe wsi should be left alone.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,\n\t\t    const char *other_headers, int other_headers_len);\n\nLWS_VISIBLE LWS_EXTERN int\nlws_serve_http_file_fragment(struct lws *wsi);\n//@}\n\n\nenum http_status {\n\tHTTP_STATUS_CONTINUE\t\t\t\t\t= 100,\n\n\tHTTP_STATUS_OK\t\t\t\t\t\t= 200,\n\tHTTP_STATUS_NO_CONTENT\t\t\t\t\t= 204,\n\tHTTP_STATUS_PARTIAL_CONTENT\t\t\t\t= 206,\n\n\tHTTP_STATUS_MOVED_PERMANENTLY\t\t\t\t= 301,\n\tHTTP_STATUS_FOUND\t\t\t\t\t= 302,\n\tHTTP_STATUS_SEE_OTHER\t\t\t\t\t= 303,\n\tHTTP_STATUS_NOT_MODIFIED\t\t\t\t= 304,\n\n\tHTTP_STATUS_BAD_REQUEST\t\t\t\t\t= 400,\n\tHTTP_STATUS_UNAUTHORIZED,\n\tHTTP_STATUS_PAYMENT_REQUIRED,\n\tHTTP_STATUS_FORBIDDEN,\n\tHTTP_STATUS_NOT_FOUND,\n\tHTTP_STATUS_METHOD_NOT_ALLOWED,\n\tHTTP_STATUS_NOT_ACCEPTABLE,\n\tHTTP_STATUS_PROXY_AUTH_REQUIRED,\n\tHTTP_STATUS_REQUEST_TIMEOUT,\n\tHTTP_STATUS_CONFLICT,\n\tHTTP_STATUS_GONE,\n\tHTTP_STATUS_LENGTH_REQUIRED,\n\tHTTP_STATUS_PRECONDITION_FAILED,\n\tHTTP_STATUS_REQ_ENTITY_TOO_LARGE,\n\tHTTP_STATUS_REQ_URI_TOO_LONG,\n\tHTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,\n\tHTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE,\n\tHTTP_STATUS_EXPECTATION_FAILED,\n\n\tHTTP_STATUS_INTERNAL_SERVER_ERROR\t\t\t= 500,\n\tHTTP_STATUS_NOT_IMPLEMENTED,\n\tHTTP_STATUS_BAD_GATEWAY,\n\tHTTP_STATUS_SERVICE_UNAVAILABLE,\n\tHTTP_STATUS_GATEWAY_TIMEOUT,\n\tHTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED,\n};\n/*! \\defgroup html-chunked-substitution HTML Chunked Substitution\n * \\ingroup http\n *\n * ##HTML chunked Substitution\n *\n * APIs for receiving chunks of text, replacing a set of variable names via\n * a callback, and then prepending and appending HTML chunked encoding\n * headers.\n */\n//@{\n\nstruct lws_process_html_args {\n\tchar *p; /**< pointer to the buffer containing the data */\n\tint len; /**< length of the original data at p */\n\tint max_len; /**< maximum length we can grow the data to */\n\tint final; /**< set if this is the last chunk of the file */\n\tint chunked; /**< 0 == unchunked, 1 == produce chunk headers (incompatible with HTTP/2) */\n};\n\ntypedef const char *(*lws_process_html_state_cb)(void *data, int index);\n\nstruct lws_process_html_state {\n\tchar *start; /**< pointer to start of match */\n\tchar swallow[16]; /**< matched character buffer */\n\tint pos; /**< position in match */\n\tvoid *data; /**< opaque pointer */\n\tconst char * const *vars; /**< list of variable names */\n\tint count_vars; /**< count of variable names */\n\n\tlws_process_html_state_cb replace; /**< called on match to perform substitution */\n};\n\n/*! lws_chunked_html_process() - generic chunked substitution\n * \\param args: buffer to process using chunked encoding\n * \\param s: current processing state\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_chunked_html_process(struct lws_process_html_args *args,\n\t\t\t struct lws_process_html_state *s);\n//@}\n\n/** \\defgroup HTTP-headers-read HTTP headers: read\n * \\ingroup http\n *\n * ##HTTP header releated functions\n *\n *  In lws the client http headers are temporarily stored in a pool, only for the\n *  duration of the http part of the handshake.  It's because in most cases,\n *  the header content is ignored for the whole rest of the connection lifetime\n *  and would then just be taking up space needlessly.\n *\n *  During LWS_CALLBACK_HTTP when the URI path is delivered is the last time\n *  the http headers are still allocated, you can use these apis then to\n *  look at and copy out interesting header content (cookies, etc)\n *\n *  Notice that the header total length reported does not include a terminating\n *  '\\0', however you must allocate for it when using the _copy apis.  So the\n *  length reported for a header containing \"123\" is 3, but you must provide\n *  a buffer of length 4 so that \"123\\0\" may be copied into it, or the copy\n *  will fail with a nonzero return code.\n *\n *  In the special case of URL arguments, like ?x=1&y=2, the arguments are\n *  stored in a token named for the method, eg,  WSI_TOKEN_GET_URI if it\n *  was a GET or WSI_TOKEN_POST_URI if POST.  You can check the total\n *  length to confirm the method.\n *\n *  For URL arguments, each argument is stored urldecoded in a \"fragment\", so\n *  you can use the fragment-aware api lws_hdr_copy_fragment() to access each\n *  argument in turn: the fragments contain urldecoded strings like x=1 or y=2.\n *\n *  As a convenience, lws has an api that will find the fragment with a\n *  given name= part, lws_get_urlarg_by_name().\n */\n///@{\n\n/** struct lws_tokens\n * you need these to look at headers that have been parsed if using the\n * LWS_CALLBACK_FILTER_CONNECTION callback.  If a header from the enum\n * list below is absent, .token = NULL and len = 0.  Otherwise .token\n * points to .len chars containing that header content.\n */\nstruct lws_tokens {\n\tchar *token; /**< pointer to start of the token */\n\tint len; /**< length of the token's value */\n};\n\n/* enum lws_token_indexes\n * these have to be kept in sync with lextable.h / minilex.c\n *\n * NOTE: These public enums are part of the abi.  If you want to add one,\n * add it at where specified so existing users are unaffected.\n */\nenum lws_token_indexes {\n\tWSI_TOKEN_GET_URI\t\t\t\t\t=  0,\n\tWSI_TOKEN_POST_URI\t\t\t\t\t=  1,\n\tWSI_TOKEN_OPTIONS_URI\t\t\t\t\t=  2,\n\tWSI_TOKEN_HOST\t\t\t\t\t\t=  3,\n\tWSI_TOKEN_CONNECTION\t\t\t\t\t=  4,\n\tWSI_TOKEN_UPGRADE\t\t\t\t\t=  5,\n\tWSI_TOKEN_ORIGIN\t\t\t\t\t=  6,\n\tWSI_TOKEN_DRAFT\t\t\t\t\t\t=  7,\n\tWSI_TOKEN_CHALLENGE\t\t\t\t\t=  8,\n\tWSI_TOKEN_EXTENSIONS\t\t\t\t\t=  9,\n\tWSI_TOKEN_KEY1\t\t\t\t\t\t= 10,\n\tWSI_TOKEN_KEY2\t\t\t\t\t\t= 11,\n\tWSI_TOKEN_PROTOCOL\t\t\t\t\t= 12,\n\tWSI_TOKEN_ACCEPT\t\t\t\t\t= 13,\n\tWSI_TOKEN_NONCE\t\t\t\t\t\t= 14,\n\tWSI_TOKEN_HTTP\t\t\t\t\t\t= 15,\n\tWSI_TOKEN_HTTP2_SETTINGS\t\t\t\t= 16,\n\tWSI_TOKEN_HTTP_ACCEPT\t\t\t\t\t= 17,\n\tWSI_TOKEN_HTTP_AC_REQUEST_HEADERS\t\t\t= 18,\n\tWSI_TOKEN_HTTP_IF_MODIFIED_SINCE\t\t\t= 19,\n\tWSI_TOKEN_HTTP_IF_NONE_MATCH\t\t\t\t= 20,\n\tWSI_TOKEN_HTTP_ACCEPT_ENCODING\t\t\t\t= 21,\n\tWSI_TOKEN_HTTP_ACCEPT_LANGUAGE\t\t\t\t= 22,\n\tWSI_TOKEN_HTTP_PRAGMA\t\t\t\t\t= 23,\n\tWSI_TOKEN_HTTP_CACHE_CONTROL\t\t\t\t= 24,\n\tWSI_TOKEN_HTTP_AUTHORIZATION\t\t\t\t= 25,\n\tWSI_TOKEN_HTTP_COOKIE\t\t\t\t\t= 26,\n\tWSI_TOKEN_HTTP_CONTENT_LENGTH\t\t\t\t= 27,\n\tWSI_TOKEN_HTTP_CONTENT_TYPE\t\t\t\t= 28,\n\tWSI_TOKEN_HTTP_DATE\t\t\t\t\t= 29,\n\tWSI_TOKEN_HTTP_RANGE\t\t\t\t\t= 30,\n\tWSI_TOKEN_HTTP_REFERER\t\t\t\t\t= 31,\n\tWSI_TOKEN_KEY\t\t\t\t\t\t= 32,\n\tWSI_TOKEN_VERSION\t\t\t\t\t= 33,\n\tWSI_TOKEN_SWORIGIN\t\t\t\t\t= 34,\n\n\tWSI_TOKEN_HTTP_COLON_AUTHORITY\t\t\t\t= 35,\n\tWSI_TOKEN_HTTP_COLON_METHOD\t\t\t\t= 36,\n\tWSI_TOKEN_HTTP_COLON_PATH\t\t\t\t= 37,\n\tWSI_TOKEN_HTTP_COLON_SCHEME\t\t\t\t= 38,\n\tWSI_TOKEN_HTTP_COLON_STATUS\t\t\t\t= 39,\n\n\tWSI_TOKEN_HTTP_ACCEPT_CHARSET\t\t\t\t= 40,\n\tWSI_TOKEN_HTTP_ACCEPT_RANGES\t\t\t\t= 41,\n\tWSI_TOKEN_HTTP_ACCESS_CONTROL_ALLOW_ORIGIN\t\t= 42,\n\tWSI_TOKEN_HTTP_AGE\t\t\t\t\t= 43,\n\tWSI_TOKEN_HTTP_ALLOW\t\t\t\t\t= 44,\n\tWSI_TOKEN_HTTP_CONTENT_DISPOSITION\t\t\t= 45,\n\tWSI_TOKEN_HTTP_CONTENT_ENCODING\t\t\t\t= 46,\n\tWSI_TOKEN_HTTP_CONTENT_LANGUAGE\t\t\t\t= 47,\n\tWSI_TOKEN_HTTP_CONTENT_LOCATION\t\t\t\t= 48,\n\tWSI_TOKEN_HTTP_CONTENT_RANGE\t\t\t\t= 49,\n\tWSI_TOKEN_HTTP_ETAG\t\t\t\t\t= 50,\n\tWSI_TOKEN_HTTP_EXPECT\t\t\t\t\t= 51,\n\tWSI_TOKEN_HTTP_EXPIRES\t\t\t\t\t= 52,\n\tWSI_TOKEN_HTTP_FROM\t\t\t\t\t= 53,\n\tWSI_TOKEN_HTTP_IF_MATCH\t\t\t\t\t= 54,\n\tWSI_TOKEN_HTTP_IF_RANGE\t\t\t\t\t= 55,\n\tWSI_TOKEN_HTTP_IF_UNMODIFIED_SINCE\t\t\t= 56,\n\tWSI_TOKEN_HTTP_LAST_MODIFIED\t\t\t\t= 57,\n\tWSI_TOKEN_HTTP_LINK\t\t\t\t\t= 58,\n\tWSI_TOKEN_HTTP_LOCATION\t\t\t\t\t= 59,\n\tWSI_TOKEN_HTTP_MAX_FORWARDS\t\t\t\t= 60,\n\tWSI_TOKEN_HTTP_PROXY_AUTHENTICATE\t\t\t= 61,\n\tWSI_TOKEN_HTTP_PROXY_AUTHORIZATION\t\t\t= 62,\n\tWSI_TOKEN_HTTP_REFRESH\t\t\t\t\t= 63,\n\tWSI_TOKEN_HTTP_RETRY_AFTER\t\t\t\t= 64,\n\tWSI_TOKEN_HTTP_SERVER\t\t\t\t\t= 65,\n\tWSI_TOKEN_HTTP_SET_COOKIE\t\t\t\t= 66,\n\tWSI_TOKEN_HTTP_STRICT_TRANSPORT_SECURITY\t\t= 67,\n\tWSI_TOKEN_HTTP_TRANSFER_ENCODING\t\t\t= 68,\n\tWSI_TOKEN_HTTP_USER_AGENT\t\t\t\t= 69,\n\tWSI_TOKEN_HTTP_VARY\t\t\t\t\t= 70,\n\tWSI_TOKEN_HTTP_VIA\t\t\t\t\t= 71,\n\tWSI_TOKEN_HTTP_WWW_AUTHENTICATE\t\t\t\t= 72,\n\n\tWSI_TOKEN_PATCH_URI\t\t\t\t\t= 73,\n\tWSI_TOKEN_PUT_URI\t\t\t\t\t= 74,\n\tWSI_TOKEN_DELETE_URI\t\t\t\t\t= 75,\n\n\tWSI_TOKEN_HTTP_URI_ARGS\t\t\t\t\t= 76,\n\tWSI_TOKEN_PROXY\t\t\t\t\t\t= 77,\n\tWSI_TOKEN_HTTP_X_REAL_IP\t\t\t\t= 78,\n\tWSI_TOKEN_HTTP1_0\t\t\t\t\t= 79,\n\tWSI_TOKEN_X_FORWARDED_FOR\t\t\t\t= 80,\n\tWSI_TOKEN_CONNECT\t\t\t\t\t= 81,\n\tWSI_TOKEN_HEAD_URI\t\t\t\t\t= 82,\n\tWSI_TOKEN_TE\t\t\t\t\t\t= 83,\n\tWSI_TOKEN_REPLAY_NONCE\t\t\t\t\t= 84,\n\tWSI_TOKEN_COLON_PROTOCOL\t\t\t\t= 85,\n\tWSI_TOKEN_X_AUTH_TOKEN\t\t\t\t\t= 86,\n\n\t/****** add new things just above ---^ ******/\n\n\t/* use token storage to stash these internally, not for\n\t * user use */\n\n\t_WSI_TOKEN_CLIENT_SENT_PROTOCOLS,\n\t_WSI_TOKEN_CLIENT_PEER_ADDRESS,\n\t_WSI_TOKEN_CLIENT_URI,\n\t_WSI_TOKEN_CLIENT_HOST,\n\t_WSI_TOKEN_CLIENT_ORIGIN,\n\t_WSI_TOKEN_CLIENT_METHOD,\n\t_WSI_TOKEN_CLIENT_IFACE,\n\t_WSI_TOKEN_CLIENT_ALPN,\n\n\t/* always last real token index*/\n\tWSI_TOKEN_COUNT,\n\n\t/* parser state additions, no storage associated */\n\tWSI_TOKEN_NAME_PART,\n\tWSI_TOKEN_SKIPPING,\n\tWSI_TOKEN_SKIPPING_SAW_CR,\n\tWSI_PARSING_COMPLETE,\n\tWSI_INIT_TOKEN_MUXURL,\n};\n\nstruct lws_token_limits {\n\tunsigned short token_limit[WSI_TOKEN_COUNT]; /**< max chars for this token */\n};\n\n/**\n * lws_token_to_string() - returns a textual representation of a hdr token index\n *\n * \\param token: token index\n */\nLWS_VISIBLE LWS_EXTERN const unsigned char *\nlws_token_to_string(enum lws_token_indexes token);\n\n/**\n * lws_hdr_total_length: report length of all fragments of a header totalled up\n *\t\tThe returned length does not include the space for a\n *\t\tterminating '\\0'\n *\n * \\param wsi: websocket connection\n * \\param h: which header index we are interested in\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h);\n\n/**\n * lws_hdr_fragment_length: report length of a single fragment of a header\n *\t\tThe returned length does not include the space for a\n *\t\tterminating '\\0'\n *\n * \\param wsi: websocket connection\n * \\param h: which header index we are interested in\n * \\param frag_idx: which fragment of h we want to get the length of\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx);\n\n/**\n * lws_hdr_copy() - copy a single fragment of the given header to a buffer\n *\t\tThe buffer length len must include space for an additional\n *\t\tterminating '\\0', or it will fail returning -1.\n *\n * \\param wsi: websocket connection\n * \\param dest: destination buffer\n * \\param len: length of destination buffer\n * \\param h: which header index we are interested in\n *\n * copies the whole, aggregated header, even if it was delivered in\n * several actual headers piece by piece\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_hdr_copy(struct lws *wsi, char *dest, int len, enum lws_token_indexes h);\n\n/**\n * lws_hdr_copy_fragment() - copy a single fragment of the given header to a buffer\n *\t\tThe buffer length len must include space for an additional\n *\t\tterminating '\\0', or it will fail returning -1.\n *\t\tIf the requested fragment index is not present, it fails\n *\t\treturning -1.\n *\n * \\param wsi: websocket connection\n * \\param dest: destination buffer\n * \\param len: length of destination buffer\n * \\param h: which header index we are interested in\n * \\param frag_idx: which fragment of h we want to copy\n *\n * Normally this is only useful\n * to parse URI arguments like ?x=1&y=2, token index WSI_TOKEN_HTTP_URI_ARGS\n * fragment 0 will contain \"x=1\" and fragment 1 \"y=2\"\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_hdr_copy_fragment(struct lws *wsi, char *dest, int len,\n\t\t      enum lws_token_indexes h, int frag_idx);\n\n/**\n * lws_get_urlarg_by_name() - return pointer to arg value if present\n * \\param wsi: the connection to check\n * \\param name: the arg name, like \"token=\"\n * \\param buf: the buffer to receive the urlarg (including the name= part)\n * \\param len: the length of the buffer to receive the urlarg\n *\n *     Returns NULL if not found or a pointer inside buf to just after the\n *     name= part.\n */\nLWS_VISIBLE LWS_EXTERN const char *\nlws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len);\n///@}\n\n/*! \\defgroup HTTP-headers-create HTTP headers: create\n *\n * ## HTTP headers: Create\n *\n * These apis allow you to create HTTP response headers in a way compatible with\n * both HTTP/1.x and HTTP/2.\n *\n * They each append to a buffer taking care about the buffer end, which is\n * passed in as a pointer.  When data is written to the buffer, the current\n * position p is updated accordingly.\n *\n * All of these apis are LWS_WARN_UNUSED_RESULT as they can run out of space\n * and fail with nonzero return.\n */\n///@{\n\n#define LWSAHH_CODE_MASK\t\t\t((1 << 16) - 1)\n#define LWSAHH_FLAG_NO_SERVER_NAME\t\t(1 << 30)\n\n/**\n * lws_add_http_header_status() - add the HTTP response status code\n *\n * \\param wsi: the connection to check\n * \\param code: an HTTP code like 200, 404 etc (see enum http_status)\n * \\param p: pointer to current position in buffer pointer\n * \\param end: pointer to end of buffer\n *\n * Adds the initial response code, so should be called first.\n *\n * Code may additionally take OR'd flags:\n *\n *    LWSAHH_FLAG_NO_SERVER_NAME:  don't apply server name header this time\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_add_http_header_status(struct lws *wsi,\n\t\t\t   unsigned int code, unsigned char **p,\n\t\t\t   unsigned char *end);\n/**\n * lws_add_http_header_by_name() - append named header and value\n *\n * \\param wsi: the connection to check\n * \\param name: the hdr name, like \"my-header\"\n * \\param value: the value after the = for this header\n * \\param length: the length of the value\n * \\param p: pointer to current position in buffer pointer\n * \\param end: pointer to end of buffer\n *\n * Appends name: value to the headers\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_add_http_header_by_name(struct lws *wsi, const unsigned char *name,\n\t\t\t    const unsigned char *value, int length,\n\t\t\t    unsigned char **p, unsigned char *end);\n/**\n * lws_add_http_header_by_token() - append given header and value\n *\n * \\param wsi: the connection to check\n * \\param token: the token index for the hdr\n * \\param value: the value after the = for this header\n * \\param length: the length of the value\n * \\param p: pointer to current position in buffer pointer\n * \\param end: pointer to end of buffer\n *\n * Appends name=value to the headers, but is able to take advantage of better\n * HTTP/2 coding mechanisms where possible.\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_add_http_header_by_token(struct lws *wsi, enum lws_token_indexes token,\n\t\t\t     const unsigned char *value, int length,\n\t\t\t     unsigned char **p, unsigned char *end);\n/**\n * lws_add_http_header_content_length() - append content-length helper\n *\n * \\param wsi: the connection to check\n * \\param content_length: the content length to use\n * \\param p: pointer to current position in buffer pointer\n * \\param end: pointer to end of buffer\n *\n * Appends content-length: content_length to the headers\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_add_http_header_content_length(struct lws *wsi,\n\t\t\t\t   lws_filepos_t content_length,\n\t\t\t\t   unsigned char **p, unsigned char *end);\n/**\n * lws_finalize_http_header() - terminate header block\n *\n * \\param wsi: the connection to check\n * \\param p: pointer to current position in buffer pointer\n * \\param end: pointer to end of buffer\n *\n * Indicates no more headers will be added\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_finalize_http_header(struct lws *wsi, unsigned char **p,\n\t\t\t unsigned char *end);\n\n/**\n * lws_finalize_write_http_header() - Helper finializing and writing http headers\n *\n * \\param wsi: the connection to check\n * \\param start: pointer to the start of headers in the buffer, eg &buf[LWS_PRE]\n * \\param p: pointer to current position in buffer pointer\n * \\param end: pointer to end of buffer\n *\n * Terminates the headers correctly accoring to the protocol in use (h1 / h2)\n * and writes the headers.  Returns nonzero for error.\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_finalize_write_http_header(struct lws *wsi, unsigned char *start,\n\t\t\t       unsigned char **p, unsigned char *end);\n\n#define LWS_ILLEGAL_HTTP_CONTENT_LEN ((lws_filepos_t)-1ll)\n\n/**\n * lws_add_http_common_headers() - Helper preparing common http headers\n *\n * \\param wsi: the connection to check\n * \\param code: an HTTP code like 200, 404 etc (see enum http_status)\n * \\param content_type: the content type, like \"text/html\"\n * \\param content_len: the content length, in bytes\n * \\param p: pointer to current position in buffer pointer\n * \\param end: pointer to end of buffer\n *\n * Adds the initial response code, so should be called first.\n *\n * Code may additionally take OR'd flags:\n *\n *    LWSAHH_FLAG_NO_SERVER_NAME:  don't apply server name header this time\n *\n * This helper just calls public apis to simplify adding headers that are\n * commonly needed.  If it doesn't fit your case, or you want to add additional\n * headers just call the public apis directly yourself for what you want.\n *\n * You can miss out the content length header by providing the constant\n * LWS_ILLEGAL_HTTP_CONTENT_LEN for the content_len.\n *\n * It does not call lws_finalize_http_header(), to allow you to add further\n * headers after calling this.  You will need to call that yourself at the end.\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_add_http_common_headers(struct lws *wsi, unsigned int code,\n\t\t\t    const char *content_type, lws_filepos_t content_len,\n\t\t\t    unsigned char **p, unsigned char *end);\n///@}\n\n/** \\defgroup form-parsing  Form Parsing\n * \\ingroup http\n * ##POSTed form parsing functions\n *\n * These lws_spa (stateful post arguments) apis let you parse and urldecode\n * POSTed form arguments, both using simple urlencoded and multipart transfer\n * encoding.\n *\n * It's capable of handling file uploads as well a named input parsing,\n * and the apis are the same for both form upload styles.\n *\n * You feed it a list of parameter names and it creates pointers to the\n * urldecoded arguments: file upload parameters pass the file data in chunks to\n * a user-supplied callback as they come.\n *\n * Since it's stateful, it handles the incoming data needing more than one\n * POST_BODY callback and has no limit on uploaded file size.\n */\n///@{\n\n/** enum lws_spa_fileupload_states */\nenum lws_spa_fileupload_states {\n\tLWS_UFS_CONTENT,\n\t/**< a chunk of file content has arrived */\n\tLWS_UFS_FINAL_CONTENT,\n\t/**< the last chunk (possibly zero length) of file content has arrived */\n\tLWS_UFS_OPEN\n\t/**< a new file is starting to arrive */\n};\n\n/**\n * lws_spa_fileupload_cb() - callback to receive file upload data\n *\n * \\param data: opt_data pointer set in lws_spa_create\n * \\param name: name of the form field being uploaded\n * \\param filename: original filename from client\n * \\param buf: start of data to receive\n * \\param len: length of data to receive\n * \\param state: information about how this call relates to file\n *\n * Notice name and filename shouldn't be trusted, as they are passed from\n * HTTP provided by the client.\n */\ntypedef int (*lws_spa_fileupload_cb)(void *data, const char *name,\n\t\t\tconst char *filename, char *buf, int len,\n\t\t\tenum lws_spa_fileupload_states state);\n\n/** struct lws_spa - opaque urldecode parser capable of handling multipart\n *\t\t\tand file uploads */\nstruct lws_spa;\n\n/**\n * lws_spa_create() - create urldecode parser\n *\n * \\param wsi: lws connection (used to find Content Type)\n * \\param param_names: array of form parameter names, like \"username\"\n * \\param count_params: count of param_names\n * \\param max_storage: total amount of form parameter values we can store\n * \\param opt_cb: NULL, or callback to receive file upload data.\n * \\param opt_data: NULL, or user pointer provided to opt_cb.\n *\n * Creates a urldecode parser and initializes it.\n *\n * opt_cb can be NULL if you just want normal name=value parsing, however\n * if one or more entries in your form are bulk data (file transfer), you\n * can provide this callback and filter on the name callback parameter to\n * treat that urldecoded data separately.  The callback should return -1\n * in case of fatal error, and 0 if OK.\n */\nLWS_VISIBLE LWS_EXTERN struct lws_spa *\nlws_spa_create(struct lws *wsi, const char * const *param_names,\n\t       int count_params, int max_storage, lws_spa_fileupload_cb opt_cb,\n\t       void *opt_data);\n\n/**\n * lws_spa_process() - parses a chunk of input data\n *\n * \\param spa: the parser object previously created\n * \\param in: incoming, urlencoded data\n * \\param len: count of bytes valid at \\param in\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_spa_process(struct lws_spa *spa, const char *in, int len);\n\n/**\n * lws_spa_finalize() - indicate incoming data completed\n *\n * \\param spa: the parser object previously created\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_spa_finalize(struct lws_spa *spa);\n\n/**\n * lws_spa_get_length() - return length of parameter value\n *\n * \\param spa: the parser object previously created\n * \\param n: parameter ordinal to return length of value for\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_spa_get_length(struct lws_spa *spa, int n);\n\n/**\n * lws_spa_get_string() - return pointer to parameter value\n * \\param spa: the parser object previously created\n * \\param n: parameter ordinal to return pointer to value for\n */\nLWS_VISIBLE LWS_EXTERN const char *\nlws_spa_get_string(struct lws_spa *spa, int n);\n\n/**\n * lws_spa_destroy() - destroy parser object\n *\n * \\param spa: the parser object previously created\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_spa_destroy(struct lws_spa *spa);\n///@}\n\n/*! \\defgroup urlendec Urlencode and Urldecode\n * \\ingroup http\n *\n * ##HTML chunked Substitution\n *\n * APIs for receiving chunks of text, replacing a set of variable names via\n * a callback, and then prepending and appending HTML chunked encoding\n * headers.\n */\n//@{\n\n/**\n * lws_urlencode() - like strncpy but with urlencoding\n *\n * \\param escaped: output buffer\n * \\param string: input buffer ('/0' terminated)\n * \\param len: output buffer max length\n *\n * Because urlencoding expands the output string, it's not\n * possible to do it in-place, ie, with escaped == string\n */\nLWS_VISIBLE LWS_EXTERN const char *\nlws_urlencode(char *escaped, const char *string, int len);\n\n/*\n * URLDECODE 1 / 2\n *\n * This simple urldecode only operates until the first '\\0' and requires the\n * data to exist all at once\n */\n/**\n * lws_urldecode() - like strncpy but with urldecoding\n *\n * \\param string: output buffer\n * \\param escaped: input buffer ('\\0' terminated)\n * \\param len: output buffer max length\n *\n * This is only useful for '\\0' terminated strings\n *\n * Since urldecoding only shrinks the output string, it is possible to\n * do it in-place, ie, string == escaped\n *\n * Returns 0 if completed OK or nonzero for urldecode violation (non-hex chars\n * where hex required, etc)\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_urldecode(char *string, const char *escaped, int len);\n///@}\n/**\n * lws_return_http_status() - Return simple http status\n * \\param wsi:\t\tWebsocket instance (available from user callback)\n * \\param code:\t\tStatus index, eg, 404\n * \\param html_body:\t\tUser-readable HTML description < 1KB, or NULL\n *\n *\tHelper to report HTTP errors back to the client cleanly and\n *\tconsistently\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_return_http_status(struct lws *wsi, unsigned int code,\n\t\t       const char *html_body);\n\n/**\n * lws_http_redirect() - write http redirect out on wsi\n *\n * \\param wsi:\twebsocket connection\n * \\param code:\tHTTP response code (eg, 301)\n * \\param loc:\twhere to redirect to\n * \\param len:\tlength of loc\n * \\param p:\tpointer current position in buffer (updated as we write)\n * \\param end:\tpointer to end of buffer\n *\n * Returns amount written, or < 0 indicating fatal write failure.\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_http_redirect(struct lws *wsi, int code, const unsigned char *loc, int len,\n\t\t  unsigned char **p, unsigned char *end);\n\n/**\n * lws_http_transaction_completed() - wait for new http transaction or close\n * \\param wsi:\twebsocket connection\n *\n *\tReturns 1 if the HTTP connection must close now\n *\tReturns 0 and resets connection to wait for new HTTP header /\n *\t  transaction if possible\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_http_transaction_completed(struct lws *wsi);\n///@}\n\n/*! \\defgroup pur Sanitize / purify SQL and JSON helpers\n *\n * ##Sanitize / purify SQL and JSON helpers\n *\n * APIs for escaping untrusted JSON and SQL safely before use\n */\n//@{\n\n/**\n * lws_sql_purify() - like strncpy but with escaping for sql quotes\n *\n * \\param escaped: output buffer\n * \\param string: input buffer ('/0' terminated)\n * \\param len: output buffer max length\n *\n * Because escaping expands the output string, it's not\n * possible to do it in-place, ie, with escaped == string\n */\nLWS_VISIBLE LWS_EXTERN const char *\nlws_sql_purify(char *escaped, const char *string, int len);\n\n/**\n * lws_json_purify() - like strncpy but with escaping for json chars\n *\n * \\param escaped: output buffer\n * \\param string: input buffer ('/0' terminated)\n * \\param len: output buffer max length\n *\n * Because escaping expands the output string, it's not\n * possible to do it in-place, ie, with escaped == string\n */\nLWS_VISIBLE LWS_EXTERN const char *\nlws_json_purify(char *escaped, const char *string, int len);\n\n/**\n * lws_filename_purify_inplace() - replace scary filename chars with underscore\n *\n * \\param filename: filename to be purified\n *\n * Replace scary characters in the filename (it should not be a path)\n * with underscore, so it's safe to use.\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_filename_purify_inplace(char *filename);\n\nLWS_VISIBLE LWS_EXTERN int\nlws_plat_write_cert(struct lws_vhost *vhost, int is_key, int fd, void *buf,\n\t\t\tint len);\nLWS_VISIBLE LWS_EXTERN int\nlws_plat_write_file(const char *filename, void *buf, int len);\n\nLWS_VISIBLE LWS_EXTERN int\nlws_plat_read_file(const char *filename, void *buf, int len);\n\nLWS_VISIBLE LWS_EXTERN int\nlws_plat_recommended_rsa_bits(void);\n///@}\n\n/*! \\defgroup uv libuv helpers\n *\n * ##libuv helpers\n *\n * APIs specific to libuv event loop itegration\n */\n///@{\n#ifdef LWS_WITH_LIBUV\n/*\n * Any direct libuv allocations in lws protocol handlers must participate in the\n * lws reference counting scheme.  Two apis are provided:\n *\n * - lws_libuv_static_refcount_add(handle, context) to mark the handle with\n *  a pointer to the context and increment the global uv object counter\n *\n * - lws_libuv_static_refcount_del() which should be used as the close callback\n *   for your own libuv objects declared in the protocol scope.\n *\n * Using the apis allows lws to detach itself from a libuv loop completely\n * cleanly and at the moment all of its libuv objects have completed close.\n */\n\nLWS_VISIBLE LWS_EXTERN uv_loop_t *\nlws_uv_getloop(struct lws_context *context, int tsi);\n\nLWS_VISIBLE LWS_EXTERN void\nlws_libuv_static_refcount_add(uv_handle_t *, struct lws_context *context);\n\nLWS_VISIBLE LWS_EXTERN void\nlws_libuv_static_refcount_del(uv_handle_t *);\n\n#endif /* LWS_WITH_LIBUV */\n\n#if defined(LWS_WITH_ESP32)\n#define lws_libuv_static_refcount_add(_a, _b)\n#define lws_libuv_static_refcount_del NULL\n#endif\n///@}\n\n\n/*! \\defgroup timeout Connection timeouts\n\n    APIs related to setting connection timeouts\n*/\n//@{\n\n/*\n * NOTE: These public enums are part of the abi.  If you want to add one,\n * add it at where specified so existing users are unaffected.\n */\nenum pending_timeout {\n\tNO_PENDING_TIMEOUT\t\t\t\t\t=  0,\n\tPENDING_TIMEOUT_AWAITING_PROXY_RESPONSE\t\t\t=  1,\n\tPENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE\t\t=  2,\n\tPENDING_TIMEOUT_ESTABLISH_WITH_SERVER\t\t\t=  3,\n\tPENDING_TIMEOUT_AWAITING_SERVER_RESPONSE\t\t=  4,\n\tPENDING_TIMEOUT_AWAITING_PING\t\t\t\t=  5,\n\tPENDING_TIMEOUT_CLOSE_ACK\t\t\t\t=  6,\n\tPENDING_TIMEOUT_UNUSED1\t\t\t\t\t=  7,\n\tPENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE\t\t\t=  8,\n\tPENDING_TIMEOUT_SSL_ACCEPT\t\t\t\t=  9,\n\tPENDING_TIMEOUT_HTTP_CONTENT\t\t\t\t= 10,\n\tPENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND\t\t\t= 11,\n\tPENDING_FLUSH_STORED_SEND_BEFORE_CLOSE\t\t\t= 12,\n\tPENDING_TIMEOUT_SHUTDOWN_FLUSH\t\t\t\t= 13,\n\tPENDING_TIMEOUT_CGI\t\t\t\t\t= 14,\n\tPENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE\t\t\t= 15,\n\tPENDING_TIMEOUT_WS_PONG_CHECK_SEND_PING\t\t\t= 16,\n\tPENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG\t\t\t= 17,\n\tPENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD\t\t\t= 18,\n\tPENDING_TIMEOUT_AWAITING_SOCKS_GREETING_REPLY\t        = 19,\n\tPENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY\t\t= 20,\n\tPENDING_TIMEOUT_AWAITING_SOCKS_AUTH_REPLY\t\t= 21,\n\tPENDING_TIMEOUT_KILLED_BY_SSL_INFO\t\t\t= 22,\n\tPENDING_TIMEOUT_KILLED_BY_PARENT\t\t\t= 23,\n\tPENDING_TIMEOUT_CLOSE_SEND\t\t\t\t= 24,\n\tPENDING_TIMEOUT_HOLDING_AH\t\t\t\t= 25,\n\tPENDING_TIMEOUT_UDP_IDLE\t\t\t\t= 26,\n\tPENDING_TIMEOUT_CLIENT_CONN_IDLE\t\t\t= 27,\n\tPENDING_TIMEOUT_LAGGING\t\t\t\t\t= 28,\n\n\t/****** add new things just above ---^ ******/\n\n\tPENDING_TIMEOUT_USER_REASON_BASE\t\t\t= 1000\n};\n\n#define LWS_TO_KILL_ASYNC -1\n/**< If LWS_TO_KILL_ASYNC is given as the timeout sec in a lws_set_timeout()\n * call, then the connection is marked to be killed at the next timeout\n * check.  This is how you should force-close the wsi being serviced if\n * you are doing it outside the callback (where you should close by nonzero\n * return).\n */\n#define LWS_TO_KILL_SYNC -2\n/**< If LWS_TO_KILL_SYNC is given as the timeout sec in a lws_set_timeout()\n * call, then the connection is closed before returning (which may delete\n * the wsi).  This should only be used where the wsi being closed is not the\n * wsi currently being serviced.\n */\n/**\n * lws_set_timeout() - marks the wsi as subject to a timeout\n *\n * You will not need this unless you are doing something special\n *\n * \\param wsi:\tWebsocket connection instance\n * \\param reason:\ttimeout reason\n * \\param secs:\thow many seconds.  You may set to LWS_TO_KILL_ASYNC to\n *\t\tforce the connection to timeout at the next opportunity, or\n *\t\tLWS_TO_KILL_SYNC to close it synchronously if you know the\n *\t\twsi is not the one currently being serviced.\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs);\n\n#define LWS_SET_TIMER_USEC_CANCEL ((lws_usec_t)-1ll)\n#define LWS_USEC_PER_SEC (1000000ll)\n\n/**\n * lws_set_timer_usecs() - schedules a callback on the wsi in the future\n *\n * \\param wsi:\tWebsocket connection instance\n * \\param usecs:  LWS_SET_TIMER_USEC_CANCEL removes any existing scheduled\n *\t\t  callback, otherwise number of microseconds in the future\n *\t\t  the callback will occur at.\n *\n * NOTE: event loop support for this:\n *\n *  default poll() loop:   yes\n *  libuv event loop:      yes\n *  libev:    not implemented (patch welcome)\n *  libevent: not implemented (patch welcome)\n *\n * After the deadline expires, the wsi will get a callback of type\n * LWS_CALLBACK_TIMER and the timer is exhausted.  The deadline may be\n * continuously deferred by further calls to lws_set_timer_usecs() with a later\n * deadline, or cancelled by lws_set_timer_usecs(wsi, -1).\n *\n * If the timer should repeat, lws_set_timer_usecs() must be called again from\n * LWS_CALLBACK_TIMER.\n *\n * Accuracy depends on the platform and the load on the event loop or system...\n * all that's guaranteed is the callback will come after the requested wait\n * period.\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_set_timer_usecs(struct lws *wsi, lws_usec_t usecs);\n\n/*\n * lws_timed_callback_vh_protocol() - calls back a protocol on a vhost after\n * \t\t\t\t\tthe specified delay\n *\n * \\param vh:\t the vhost to call back\n * \\param protocol: the protocol to call back\n * \\param reason: callback reason\n * \\param secs:\thow many seconds in the future to do the callback.  Set to\n *\t\t-1 to cancel the timer callback.\n *\n * Callback the specified protocol with a fake wsi pointing to the specified\n * vhost and protocol, with the specified reason, at the specified time in the\n * future.\n *\n * Returns 0 if OK.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_timed_callback_vh_protocol(struct lws_vhost *vh,\n\t\t\t       const struct lws_protocols *prot,\n\t\t\t       int reason, int secs);\n///@}\n\n/*! \\defgroup sending-data Sending data\n\n    APIs related to writing data on a connection\n*/\n//@{\n#if !defined(LWS_SIZEOFPTR)\n#define LWS_SIZEOFPTR ((int)sizeof (void *))\n#endif\n\n#if defined(__x86_64__)\n#define _LWS_PAD_SIZE 16\t/* Intel recommended for best performance */\n#else\n#define _LWS_PAD_SIZE LWS_SIZEOFPTR   /* Size of a pointer on the target arch */\n#endif\n#define _LWS_PAD(n) (((n) % _LWS_PAD_SIZE) ? \\\n\t\t((n) + (_LWS_PAD_SIZE - ((n) % _LWS_PAD_SIZE))) : (n))\n/* last 2 is for lws-meta */\n#define LWS_PRE _LWS_PAD(4 + 10 + 2)\n/* used prior to 1.7 and retained for backward compatibility */\n#define LWS_SEND_BUFFER_PRE_PADDING LWS_PRE\n#define LWS_SEND_BUFFER_POST_PADDING 0\n\n#define LWS_WRITE_RAW LWS_WRITE_HTTP\n\n/*\n * NOTE: These public enums are part of the abi.  If you want to add one,\n * add it at where specified so existing users are unaffected.\n */\nenum lws_write_protocol {\n\tLWS_WRITE_TEXT\t\t\t\t\t\t= 0,\n\t/**< Send a ws TEXT message,the pointer must have LWS_PRE valid\n\t * memory behind it.  The receiver expects only valid utf-8 in the\n\t * payload */\n\tLWS_WRITE_BINARY\t\t\t\t\t= 1,\n\t/**< Send a ws BINARY message, the pointer must have LWS_PRE valid\n\t * memory behind it.  Any sequence of bytes is valid */\n\tLWS_WRITE_CONTINUATION\t\t\t\t\t= 2,\n\t/**< Continue a previous ws message, the pointer must have LWS_PRE valid\n\t * memory behind it */\n\tLWS_WRITE_HTTP\t\t\t\t\t\t= 3,\n\t/**< Send HTTP content */\n\n\t/* LWS_WRITE_CLOSE is handled by lws_close_reason() */\n\tLWS_WRITE_PING\t\t\t\t\t\t= 5,\n\tLWS_WRITE_PONG\t\t\t\t\t\t= 6,\n\n\t/* Same as write_http but we know this write ends the transaction */\n\tLWS_WRITE_HTTP_FINAL\t\t\t\t\t= 7,\n\n\t/* HTTP2 */\n\n\tLWS_WRITE_HTTP_HEADERS\t\t\t\t\t= 8,\n\t/**< Send http headers (http2 encodes this payload and LWS_WRITE_HTTP\n\t * payload differently, http 1.x links also handle this correctly. so\n\t * to be compatible with both in the future,header response part should\n\t * be sent using this regardless of http version expected)\n\t */\n\tLWS_WRITE_HTTP_HEADERS_CONTINUATION\t\t\t= 9,\n\t/**< Continuation of http/2 headers\n\t */\n\n\t/****** add new things just above ---^ ******/\n\n\t/* flags */\n\n\tLWS_WRITE_NO_FIN = 0x40,\n\t/**< This part of the message is not the end of the message */\n\n\tLWS_WRITE_H2_STREAM_END = 0x80,\n\t/**< Flag indicates this packet should go out with STREAM_END if h2\n\t * STREAM_END is allowed on DATA or HEADERS.\n\t */\n\n\tLWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80\n\t/**< client packet payload goes out on wire unmunged\n\t * only useful for security tests since normal servers cannot\n\t * decode the content if used */\n};\n\n/* used with LWS_CALLBACK_CHILD_WRITE_VIA_PARENT */\n\nstruct lws_write_passthru {\n\tstruct lws *wsi;\n\tunsigned char *buf;\n\tsize_t len;\n\tenum lws_write_protocol wp;\n};\n\n\n/**\n * lws_write() - Apply protocol then write data to client\n * \\param wsi:\tWebsocket instance (available from user callback)\n * \\param buf:\tThe data to send.  For data being sent on a websocket\n *\t\tconnection (ie, not default http), this buffer MUST have\n *\t\tLWS_PRE bytes valid BEFORE the pointer.\n *\t\tThis is so the protocol header data can be added in-situ.\n * \\param len:\tCount of the data bytes in the payload starting from buf\n * \\param protocol:\tUse LWS_WRITE_HTTP to reply to an http connection, and one\n *\t\tof LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate\n *\t\tdata on a websockets connection.  Remember to allow the extra\n *\t\tbytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT\n *\t\tare used.\n *\n *\tThis function provides the way to issue data back to the client\n *\tfor both http and websocket protocols.\n *\n * IMPORTANT NOTICE!\n *\n * When sending with websocket protocol\n *\n * LWS_WRITE_TEXT,\n * LWS_WRITE_BINARY,\n * LWS_WRITE_CONTINUATION,\n * LWS_WRITE_PING,\n * LWS_WRITE_PONG\n *\n * the send buffer has to have LWS_PRE bytes valid BEFORE\n * the buffer pointer you pass to lws_write().\n *\n * This allows us to add protocol info before and after the data, and send as\n * one packet on the network without payload copying, for maximum efficiency.\n *\n * So for example you need this kind of code to use lws_write with a\n * 128-byte payload\n *\n *   char buf[LWS_PRE + 128];\n *\n *   // fill your part of the buffer... for example here it's all zeros\n *   memset(&buf[LWS_PRE], 0, 128);\n *\n *   lws_write(wsi, &buf[LWS_PRE], 128, LWS_WRITE_TEXT);\n *\n * When sending HTTP, with\n *\n * LWS_WRITE_HTTP,\n * LWS_WRITE_HTTP_HEADERS\n * LWS_WRITE_HTTP_FINAL\n *\n * there is no protocol data prepended, and don't need to take care about the\n * LWS_PRE bytes valid before the buffer pointer.\n *\n * LWS_PRE is at least the frame nonce + 2 header + 8 length\n * LWS_SEND_BUFFER_POST_PADDING is deprecated, it's now 0 and can be left off.\n * The example apps no longer use it.\n *\n * Pad LWS_PRE to the CPU word size, so that word references\n * to the address immediately after the padding won't cause an unaligned access\n * error. Sometimes for performance reasons the recommended padding is even\n * larger than sizeof(void *).\n *\n *\tIn the case of sending using websocket protocol, be sure to allocate\n *\tvalid storage before and after buf as explained above.  This scheme\n *\tallows maximum efficiency of sending data and protocol in a single\n *\tpacket while not burdening the user code with any protocol knowledge.\n *\n *\tReturn may be -1 for a fatal error needing connection close, or the\n *\tnumber of bytes sent.\n *\n * Truncated Writes\n * ================\n *\n * The OS may not accept everything you asked to write on the connection.\n *\n * Posix defines POLLOUT indication from poll() to show that the connection\n * will accept more write data, but it doesn't specifiy how much.  It may just\n * accept one byte of whatever you wanted to send.\n *\n * LWS will buffer the remainder automatically, and send it out autonomously.\n *\n * During that time, WRITABLE callbacks will be suppressed.\n *\n * This is to handle corner cases where unexpectedly the OS refuses what we\n * usually expect it to accept.  You should try to send in chunks that are\n * almost always accepted in order to avoid the inefficiency of the buffering.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_write(struct lws *wsi, unsigned char *buf, size_t len,\n\t  enum lws_write_protocol protocol);\n\n/* helper for case where buffer may be const */\n#define lws_write_http(wsi, buf, len) \\\n\tlws_write(wsi, (unsigned char *)(buf), len, LWS_WRITE_HTTP)\n\n/* helper for multi-frame ws message flags */\nstatic LWS_INLINE int\nlws_write_ws_flags(int initial, int is_start, int is_end)\n{\n\tint r;\n\n\tif (is_start)\n\t\tr = initial;\n\telse\n\t\tr = LWS_WRITE_CONTINUATION;\n\n\tif (!is_end)\n\t\tr |= LWS_WRITE_NO_FIN;\n\n\treturn r;\n}\n///@}\n\n/** \\defgroup callback-when-writeable Callback when writeable\n *\n * ##Callback When Writeable\n *\n * lws can only write data on a connection when it is able to accept more\n * data without blocking.\n *\n * So a basic requirement is we should only use the lws_write() apis when the\n * connection we want to write on says that he can accept more data.\n *\n * When lws cannot complete your send at the time, it will buffer the data\n * and send it in the background, suppressing any further WRITEABLE callbacks\n * on that connection until it completes.  So it is important to write new\n * things in a new writeable callback.\n *\n * These apis reflect the various ways we can indicate we would like to be\n * called back when one or more connections is writeable.\n */\n///@{\n\n/**\n * lws_callback_on_writable() - Request a callback when this socket\n *\t\t\t\t\t becomes able to be written to without\n *\t\t\t\t\t blocking\n *\n * \\param wsi:\tWebsocket connection instance to get callback for\n *\n * - Which:  only this wsi\n * - When:   when the individual connection becomes writeable\n * - What: LWS_CALLBACK_*_WRITEABLE\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_callback_on_writable(struct lws *wsi);\n\n/**\n * lws_callback_on_writable_all_protocol() - Request a callback for all\n *\t\t\tconnections using the given protocol when it\n *\t\t\tbecomes possible to write to each socket without\n *\t\t\tblocking in turn.\n *\n * \\param context:\tlws_context\n * \\param protocol:\tProtocol whose connections will get callbacks\n *\n * - Which:  connections using this protocol on ANY VHOST\n * - When:   when the individual connection becomes writeable\n * - What: LWS_CALLBACK_*_WRITEABLE\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_callback_on_writable_all_protocol(const struct lws_context *context,\n\t\t\t\t      const struct lws_protocols *protocol);\n\n/**\n * lws_callback_on_writable_all_protocol_vhost() - Request a callback for\n *\t\t\tall connections on same vhost using the given protocol\n *\t\t\twhen it becomes possible to write to each socket without\n *\t\t\tblocking in turn.\n *\n * \\param vhost:\tOnly consider connections on this lws_vhost\n * \\param protocol:\tProtocol whose connections will get callbacks\n *\n * - Which:  connections using this protocol on GIVEN VHOST ONLY\n * - When:   when the individual connection becomes writeable\n * - What: LWS_CALLBACK_*_WRITEABLE\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_callback_on_writable_all_protocol_vhost(const struct lws_vhost *vhost,\n\t\t\t\t      const struct lws_protocols *protocol);\n\n/**\n * lws_callback_all_protocol() - Callback all connections using\n *\t\t\t\tthe given protocol with the given reason\n *\n * \\param context:\tlws_context\n * \\param protocol:\tProtocol whose connections will get callbacks\n * \\param reason:\tCallback reason index\n *\n * - Which:  connections using this protocol on ALL VHOSTS\n * - When:   before returning\n * - What:   reason\n *\n * This isn't normally what you want... normally any update of connection-\n * specific information can wait until a network-related callback like rx,\n * writable, or close.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_callback_all_protocol(struct lws_context *context,\n\t\t\t  const struct lws_protocols *protocol, int reason);\n\n/**\n * lws_callback_all_protocol_vhost() - Callback all connections using\n *\t\t\tthe given protocol with the given reason.  This is\n *\t\t\tdeprecated since v2.4: use lws_callback_all_protocol_vhost_args\n *\n * \\param vh:\t\tVhost whose connections will get callbacks\n * \\param protocol:\tWhich protocol to match.  NULL means all.\n * \\param reason:\tCallback reason index\n *\n * - Which:  connections using this protocol on GIVEN VHOST ONLY\n * - When:   now\n * - What:   reason\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_callback_all_protocol_vhost(struct lws_vhost *vh,\n\t\t\t  const struct lws_protocols *protocol, int reason)\nLWS_WARN_DEPRECATED;\n\n/**\n * lws_callback_all_protocol_vhost_args() - Callback all connections using\n *\t\t\tthe given protocol with the given reason and args\n *\n * \\param vh:\t\tVhost whose connections will get callbacks\n * \\param protocol:\tWhich protocol to match.  NULL means all.\n * \\param reason:\tCallback reason index\n * \\param argp:\t\tCallback \"in\" parameter\n * \\param len:\t\tCallback \"len\" parameter\n *\n * - Which:  connections using this protocol on GIVEN VHOST ONLY\n * - When:   now\n * - What:   reason\n */\nLWS_VISIBLE int\nlws_callback_all_protocol_vhost_args(struct lws_vhost *vh,\n\t\t\t  const struct lws_protocols *protocol, int reason,\n\t\t\t  void *argp, size_t len);\n\n/**\n * lws_callback_vhost_protocols() - Callback all protocols enabled on a vhost\n *\t\t\t\t\twith the given reason\n *\n * \\param wsi:\twsi whose vhost will get callbacks\n * \\param reason:\tCallback reason index\n * \\param in:\t\tin argument to callback\n * \\param len:\tlen argument to callback\n *\n * - Which:  connections using this protocol on same VHOST as wsi ONLY\n * - When:   now\n * - What:   reason\n *\n * This is deprecated since v2.5, use lws_callback_vhost_protocols_vhost()\n * which takes the pointer to the vhost directly without using or needing the\n * wsi.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len)\nLWS_WARN_DEPRECATED;\n\n/**\n * lws_callback_vhost_protocols_vhost() - Callback all protocols enabled on a vhost\n *\t\t\t\t\twith the given reason\n *\n * \\param vh:\t\tvhost that will get callbacks\n * \\param reason:\tCallback reason index\n * \\param in:\t\tin argument to callback\n * \\param len:\t\tlen argument to callback\n *\n * - Which:  connections using this protocol on same VHOST as wsi ONLY\n * - When:   now\n * - What:   reason\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_callback_vhost_protocols_vhost(struct lws_vhost *vh, int reason, void *in,\n\t\t\t\t   size_t len);\n\nLWS_VISIBLE LWS_EXTERN int\nlws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,\n\t\t    void *user, void *in, size_t len);\n\n/**\n * lws_get_socket_fd() - returns the socket file descriptor\n *\n * This is needed to use sendto() on UDP raw sockets\n *\n * \\param wsi:\tWebsocket connection instance\n */\nLWS_VISIBLE LWS_EXTERN lws_sockfd_type\nlws_get_socket_fd(struct lws *wsi);\n\n/**\n * lws_get_peer_write_allowance() - get the amount of data writeable to peer\n * \t\t\t\t\tif known\n *\n * \\param wsi:\tWebsocket connection instance\n *\n * if the protocol does not have any guidance, returns -1.  Currently only\n * http2 connections get send window information from this API.  But your code\n * should use it so it can work properly with any protocol.\n *\n * If nonzero return is the amount of payload data the peer or intermediary has\n * reported it has buffer space for.  That has NO relationship with the amount\n * of buffer space your OS can accept on this connection for a write action.\n *\n * This number represents the maximum you could send to the peer or intermediary\n * on this connection right now without the protocol complaining.\n *\n * lws manages accounting for send window updates and payload writes\n * automatically, so this number reflects the situation at the peer or\n * intermediary dynamically.\n */\nLWS_VISIBLE LWS_EXTERN lws_fileofs_t\nlws_get_peer_write_allowance(struct lws *wsi);\n///@}\n\nenum {\n\t/*\n\t * Flags for enable and disable rxflow with reason bitmap and with\n\t * backwards-compatible single bool\n\t */\n\tLWS_RXFLOW_REASON_USER_BOOL\t\t= (1 << 0),\n\tLWS_RXFLOW_REASON_HTTP_RXBUFFER\t\t= (1 << 6),\n\tLWS_RXFLOW_REASON_H2_PPS_PENDING\t= (1 << 7),\n\n\tLWS_RXFLOW_REASON_APPLIES\t\t= (1 << 14),\n\tLWS_RXFLOW_REASON_APPLIES_ENABLE_BIT\t= (1 << 13),\n\tLWS_RXFLOW_REASON_APPLIES_ENABLE\t= LWS_RXFLOW_REASON_APPLIES |\n\t\t\t\t\t\t  LWS_RXFLOW_REASON_APPLIES_ENABLE_BIT,\n\tLWS_RXFLOW_REASON_APPLIES_DISABLE\t= LWS_RXFLOW_REASON_APPLIES,\n\tLWS_RXFLOW_REASON_FLAG_PROCESS_NOW\t= (1 << 12),\n\n};\n\n/**\n * lws_rx_flow_control() - Enable and disable socket servicing for\n *\t\t\t\treceived packets.\n *\n * If the output side of a server process becomes choked, this allows flow\n * control for the input side.\n *\n * \\param wsi:\tWebsocket connection instance to get callback for\n * \\param enable:\t0 = disable read servicing for this connection, 1 = enable\n *\n * If you need more than one additive reason for rxflow control, you can give\n * iLWS_RXFLOW_REASON_APPLIES_ENABLE or _DISABLE together with one or more of\n * b5..b0 set to idicate which bits to enable or disable.  If any bits are\n * enabled, rx on the connection is suppressed.\n *\n * LWS_RXFLOW_REASON_FLAG_PROCESS_NOW  flag may also be given to force any change\n * in rxflowbstatus to benapplied immediately, this should be used when you are\n * changing a wsi flow control state from outside a callback on that wsi.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_rx_flow_control(struct lws *wsi, int enable);\n\n/**\n * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive\n *\n * When the user server code realizes it can accept more input, it can\n * call this to have the RX flow restriction removed from all connections using\n * the given protocol.\n * \\param context:\tlws_context\n * \\param protocol:\tall connections using this protocol will be allowed to receive\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_rx_flow_allow_all_protocol(const struct lws_context *context,\n\t\t\t       const struct lws_protocols *protocol);\n\n/**\n * lws_remaining_packet_payload() - Bytes to come before \"overall\"\n *\t\t\t\t\t      rx fragment is complete\n * \\param wsi:\t\tWebsocket instance (available from user callback)\n *\n * This tracks how many bytes are left in the current ws fragment, according\n * to the ws length given in the fragment header.\n *\n * If the message was in a single fragment, and there is no compression, this\n * is the same as \"how much data is left to read for this message\".\n *\n * However, if the message is being sent in multiple fragments, this will\n * reflect the unread amount of the current **fragment**, not the message.  With\n * ws, it is legal to not know the length of the message before it completes.\n *\n * Additionally if the message is sent via the negotiated permessage-deflate\n * extension, this number only tells the amount of **compressed** data left to\n * be read, since that is the only information available at the ws layer.\n */\nLWS_VISIBLE LWS_EXTERN size_t\nlws_remaining_packet_payload(struct lws *wsi);\n\n\n/** \\defgroup sock-adopt Socket adoption helpers\n * ##Socket adoption helpers\n *\n * When integrating with an external app with its own event loop, these can\n * be used to accept connections from someone else's listening socket.\n *\n * When using lws own event loop, these are not needed.\n */\n///@{\n\n/**\n * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it\n * for the default vhost of context.\n *\n * \\param context: lws context\n * \\param accept_fd: fd of already-accepted socket to adopt\n *\n * Either returns new wsi bound to accept_fd, or closes accept_fd and\n * returns NULL, having cleaned up any new wsi pieces.\n *\n * LWS adopts the socket in http serving mode, it's ready to accept an upgrade\n * to ws or just serve http.\n */\nLWS_VISIBLE LWS_EXTERN struct lws *\nlws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd);\n/**\n * lws_adopt_socket_vhost() - adopt foreign socket as if listen socket accepted it\n * for vhost\n *\n * \\param vh: lws vhost\n * \\param accept_fd: fd of already-accepted socket to adopt\n *\n * Either returns new wsi bound to accept_fd, or closes accept_fd and\n * returns NULL, having cleaned up any new wsi pieces.\n *\n * LWS adopts the socket in http serving mode, it's ready to accept an upgrade\n * to ws or just serve http.\n */\nLWS_VISIBLE LWS_EXTERN struct lws *\nlws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd);\n\ntypedef enum {\n\tLWS_ADOPT_RAW_FILE_DESC = 0,\t/* convenience constant */\n\tLWS_ADOPT_HTTP = 1,\t\t/* flag: absent implies RAW */\n\tLWS_ADOPT_SOCKET = 2,\t\t/* flag: absent implies file descr */\n\tLWS_ADOPT_ALLOW_SSL = 4,\t/* flag: if set requires LWS_ADOPT_SOCKET */\n\tLWS_ADOPT_WS_PARENTIO = 8,\t/* flag: ws mode parent handles IO\n\t\t\t\t\t *   if given must be only flag\n\t\t\t\t\t *   wsi put directly into ws mode */\n\tLWS_ADOPT_FLAG_UDP = 16,\t/* flag: socket is UDP */\n\n\tLWS_ADOPT_RAW_SOCKET_UDP = LWS_ADOPT_SOCKET | LWS_ADOPT_FLAG_UDP,\n} lws_adoption_type;\n\ntypedef union {\n\tlws_sockfd_type sockfd;\n\tlws_filefd_type filefd;\n} lws_sock_file_fd_type;\n\n#if !defined(LWS_WITH_ESP32)\nstruct lws_udp {\n\tstruct sockaddr sa;\n\tsocklen_t salen;\n\n\tstruct sockaddr sa_pending;\n\tsocklen_t salen_pending;\n};\n#endif\n\n/*\n* lws_adopt_descriptor_vhost() - adopt foreign socket or file descriptor\n* if socket descriptor, should already have been accepted from listen socket\n*\n* \\param vhost: lws vhost\n* \\param type: OR-ed combinations of lws_adoption_type flags\n* \\param fd: union with either .sockfd or .filefd set\n* \\param vh_prot_name: NULL or vh protocol name to bind raw connection to\n* \\param parent: NULL or struct lws to attach new_wsi to as a child\n*\n* Either returns new wsi bound to accept_fd, or closes accept_fd and\n* returns NULL, having cleaned up any new wsi pieces.\n*\n* If LWS_ADOPT_SOCKET is set, LWS adopts the socket in http serving mode, it's\n* ready to accept an upgrade to ws or just serve http.\n*\n* parent may be NULL, if given it should be an existing wsi that will become the\n* parent of the new wsi created by this call.\n*/\nLWS_VISIBLE LWS_EXTERN struct lws *\nlws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type,\n\t\t\t   lws_sock_file_fd_type fd, const char *vh_prot_name,\n\t\t\t   struct lws *parent);\n\n/**\n * lws_adopt_socket_readbuf() - adopt foreign socket and first rx as if listen socket accepted it\n * for the default vhost of context.\n * \\param context:\tlws context\n * \\param accept_fd:\tfd of already-accepted socket to adopt\n * \\param readbuf:\tNULL or pointer to data that must be drained before reading from\n *\t\taccept_fd\n * \\param len:\tThe length of the data held at \\param readbuf\n *\n * Either returns new wsi bound to accept_fd, or closes accept_fd and\n * returns NULL, having cleaned up any new wsi pieces.\n *\n * LWS adopts the socket in http serving mode, it's ready to accept an upgrade\n * to ws or just serve http.\n *\n * If your external code did not already read from the socket, you can use\n * lws_adopt_socket() instead.\n *\n * This api is guaranteed to use the data at \\param readbuf first, before reading from\n * the socket.\n *\n * readbuf is limited to the size of the ah rx buf, currently 2048 bytes.\n */\nLWS_VISIBLE LWS_EXTERN struct lws *\nlws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,\n                         const char *readbuf, size_t len);\n/**\n * lws_adopt_socket_vhost_readbuf() - adopt foreign socket and first rx as if listen socket\n * accepted it for vhost.\n * \\param vhost:\tlws vhost\n * \\param accept_fd:\tfd of already-accepted socket to adopt\n * \\param readbuf:\tNULL or pointer to data that must be drained before reading from\n *\t\t\taccept_fd\n * \\param len:\t\tThe length of the data held at \\param readbuf\n *\n * Either returns new wsi bound to accept_fd, or closes accept_fd and\n * returns NULL, having cleaned up any new wsi pieces.\n *\n * LWS adopts the socket in http serving mode, it's ready to accept an upgrade\n * to ws or just serve http.\n *\n * If your external code did not already read from the socket, you can use\n * lws_adopt_socket() instead.\n *\n * This api is guaranteed to use the data at \\param readbuf first, before reading from\n * the socket.\n *\n * readbuf is limited to the size of the ah rx buf, currently 2048 bytes.\n */\nLWS_VISIBLE LWS_EXTERN struct lws *\nlws_adopt_socket_vhost_readbuf(struct lws_vhost *vhost, lws_sockfd_type accept_fd,\n                               const char *readbuf, size_t len);\n\n#define LWS_CAUDP_BIND 1\n\n/**\n * lws_create_adopt_udp() - create, bind and adopt a UDP socket\n *\n * \\param vhost:\t lws vhost\n * \\param port:\t\t UDP port to bind to, -1 means unbound\n * \\param flags:\t 0 or LWS_CAUDP_NO_BIND\n * \\param protocol_name: Name of protocol on vhost to bind wsi to\n * \\param parent_wsi:\t NULL or parent wsi new wsi will be a child of\n *\n * Either returns new wsi bound to accept_fd, or closes accept_fd and\n * returns NULL, having cleaned up any new wsi pieces.\n * */\nLWS_VISIBLE LWS_EXTERN struct lws *\nlws_create_adopt_udp(struct lws_vhost *vhost, int port, int flags,\n\t\t     const char *protocol_name, struct lws *parent_wsi);\n///@}\n\n/** \\defgroup net Network related helper APIs\n * ##Network related helper APIs\n *\n * These wrap miscellaneous useful network-related functions\n */\n///@{\n\n/**\n * lws_canonical_hostname() - returns this host's hostname\n *\n * This is typically used by client code to fill in the host parameter\n * when making a client connection.  You can only call it after the context\n * has been created.\n *\n * \\param context:\tWebsocket context\n */\nLWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT\nlws_canonical_hostname(struct lws_context *context);\n\n/**\n * lws_get_peer_addresses() - Get client address information\n * \\param wsi:\tLocal struct lws associated with\n * \\param fd:\t\tConnection socket descriptor\n * \\param name:\tBuffer to take client address name\n * \\param name_len:\tLength of client address name buffer\n * \\param rip:\tBuffer to take client address IP dotted quad\n * \\param rip_len:\tLength of client address IP buffer\n *\n *\tThis function fills in name and rip with the name and IP of\n *\tthe client connected with socket descriptor fd.  Names may be\n *\ttruncated if there is not enough room.  If either cannot be\n *\tdetermined, they will be returned as valid zero-length strings.\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,\n\t\t       int name_len, char *rip, int rip_len);\n\n/**\n * lws_get_peer_simple() - Get client address information without RDNS\n *\n * \\param wsi:\tLocal struct lws associated with\n * \\param name:\tBuffer to take client address name\n * \\param namelen:\tLength of client address name buffer\n *\n * This provides a 123.123.123.123 type IP address in name from the\n * peer that has connected to wsi\n */\nLWS_VISIBLE LWS_EXTERN const char *\nlws_get_peer_simple(struct lws *wsi, char *name, int namelen);\n\n\n#define LWS_ITOSA_NOT_EXIST -1\n#define LWS_ITOSA_NOT_USABLE -2\n#define LWS_ITOSA_USABLE 0\n#if !defined(LWS_WITH_ESP32)\n/**\n * lws_interface_to_sa() - Convert interface name or IP to sockaddr struct\n *\n * \\param ipv6:\t\tAllow IPV6 addresses\n * \\param ifname:\tInterface name or IP\n * \\param addr:\t\tstruct sockaddr_in * to be written\n * \\param addrlen:\tLength of addr\n *\n * This converts a textual network interface name to a sockaddr usable by\n * other network functions.\n *\n * If the network interface doesn't exist, it will return LWS_ITOSA_NOT_EXIST.\n *\n * If the network interface is not usable, eg ethernet cable is removed, it\n * may logically exist but not have any IP address.  As such it will return\n * LWS_ITOSA_NOT_USABLE.\n *\n * If the network interface exists and is usable, it will return\n * LWS_ITOSA_USABLE.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,\n\t\t    size_t addrlen);\n///@}\n#endif\n\n/** \\defgroup misc Miscellaneous APIs\n* ##Miscellaneous APIs\n*\n* Various APIs outside of other categories\n*/\n///@{\n\n/**\n * lws_start_foreach_ll(): linkedlist iterator helper start\n *\n * \\param type: type of iteration, eg, struct xyz *\n * \\param it: iterator var name to create\n * \\param start: start of list\n *\n * This helper creates an iterator and starts a while (it) {\n * loop.  The iterator runs through the linked list starting at start and\n * ends when it gets a NULL.\n * The while loop should be terminated using lws_start_foreach_ll().\n */\n#define lws_start_foreach_ll(type, it, start)\\\n{ \\\n\ttype it = start; \\\n\twhile (it) {\n\n/**\n * lws_end_foreach_ll(): linkedlist iterator helper end\n *\n * \\param it: same iterator var name given when starting\n * \\param nxt: member name in the iterator pointing to next list element\n *\n * This helper is the partner for lws_start_foreach_ll() that ends the\n * while loop.\n */\n\n#define lws_end_foreach_ll(it, nxt) \\\n\t\tit = it->nxt; \\\n\t} \\\n}\n\n/**\n * lws_start_foreach_llp(): linkedlist pointer iterator helper start\n *\n * \\param type: type of iteration, eg, struct xyz **\n * \\param it: iterator var name to create\n * \\param start: start of list\n *\n * This helper creates an iterator and starts a while (it) {\n * loop.  The iterator runs through the linked list starting at the\n * address of start and ends when it gets a NULL.\n * The while loop should be terminated using lws_start_foreach_llp().\n *\n * This helper variant iterates using a pointer to the previous linked-list\n * element.  That allows you to easily delete list members by rewriting the\n * previous pointer to the element's next pointer.\n */\n#define lws_start_foreach_llp(type, it, start)\\\n{ \\\n\ttype it = &(start); \\\n\twhile (*(it)) {\n\n#define lws_start_foreach_llp_safe(type, it, start, nxt)\\\n{ \\\n\ttype it = &(start); \\\n\ttype next; \\\n\twhile (*(it)) { \\\n\t\tnext = &((*(it))->nxt); \\\n\n/**\n * lws_end_foreach_llp(): linkedlist pointer iterator helper end\n *\n * \\param it: same iterator var name given when starting\n * \\param nxt: member name in the iterator pointing to next list element\n *\n * This helper is the partner for lws_start_foreach_llp() that ends the\n * while loop.\n */\n\n#define lws_end_foreach_llp(it, nxt) \\\n\t\tit = &(*(it))->nxt; \\\n\t} \\\n}\n\n#define lws_end_foreach_llp_safe(it) \\\n\t\tit = next; \\\n\t} \\\n}\n\n#define lws_ll_fwd_insert(\\\n\t___new_object,\t/* pointer to new object */ \\\n\t___m_list,\t/* member for next list object ptr */ \\\n\t___list_head\t/* list head */ \\\n\t\t) {\\\n\t\t___new_object->___m_list = ___list_head; \\\n\t\t___list_head = ___new_object; \\\n\t}\n\n#define lws_ll_fwd_remove(\\\n\t___type,\t/* type of listed object */ \\\n\t___m_list,\t/* member for next list object ptr */ \\\n\t___target,\t/* object to remove from list */ \\\n\t___list_head\t/* list head */ \\\n\t) { \\\n                lws_start_foreach_llp(___type **, ___ppss, ___list_head) { \\\n                        if (*___ppss == ___target) { \\\n                                *___ppss = ___target->___m_list; \\\n                                break; \\\n                        } \\\n                } lws_end_foreach_llp(___ppss, ___m_list); \\\n\t}\n\n/*\n * doubly linked-list\n */\n\nstruct lws_dll { /* abstract */\n\tstruct lws_dll *prev;\n\tstruct lws_dll *next;\n};\n\n/*\n * these all point to the composed list objects... you have to use the\n * lws_container_of() helper to recover the start of the containing struct\n */\n\nLWS_VISIBLE LWS_EXTERN void\nlws_dll_add_front(struct lws_dll *d, struct lws_dll *phead);\n\nLWS_VISIBLE LWS_EXTERN void\nlws_dll_remove(struct lws_dll *d);\n\nstruct lws_dll_lws { /* typed as struct lws * */\n\tstruct lws_dll_lws *prev;\n\tstruct lws_dll_lws *next;\n};\n\n#define lws_dll_is_null(___dll) (!(___dll)->prev && !(___dll)->next)\n\nstatic LWS_INLINE void\nlws_dll_lws_add_front(struct lws_dll_lws *_a, struct lws_dll_lws *_head)\n{\n\tlws_dll_add_front((struct lws_dll *)_a, (struct lws_dll *)_head);\n}\n\nstatic LWS_INLINE void\nlws_dll_lws_remove(struct lws_dll_lws *_a)\n{\n\tlws_dll_remove((struct lws_dll *)_a);\n}\n\n/*\n * these are safe against the current container object getting deleted,\n * since the hold his next in a temp and go to that next.  ___tmp is\n * the temp.\n */\n\n#define lws_start_foreach_dll_safe(___type, ___it, ___tmp, ___start) \\\n{ \\\n\t___type ___it = ___start; \\\n\twhile (___it) { \\\n\t\t___type ___tmp = (___it)->next;\n\n#define lws_end_foreach_dll_safe(___it, ___tmp) \\\n\t\t___it = ___tmp; \\\n\t} \\\n}\n\n#define lws_start_foreach_dll(___type, ___it, ___start) \\\n{ \\\n\t___type ___it = ___start; \\\n\twhile (___it) {\n\n#define lws_end_foreach_dll(___it) \\\n\t\t___it = (___it)->next; \\\n\t} \\\n}\n\nstruct lws_buflist;\n\n/**\n * lws_buflist_append_segment(): add buffer to buflist at head\n *\n * \\param head: list head\n * \\param buf: buffer to stash\n * \\param len: length of buffer to stash\n *\n * Returns -1 on OOM, 1 if this was the first segment on the list, and 0 if\n * it was a subsequent segment.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_buflist_append_segment(struct lws_buflist **head, const uint8_t *buf,\n\t\t\t   size_t len);\n/**\n * lws_buflist_next_segment_len(): number of bytes left in current segment\n *\n * \\param head: list head\n * \\param buf: if non-NULL, *buf is written with the address of the start of\n *\t\tthe remaining data in the segment\n *\n * Returns the number of bytes left in the current segment.  0 indicates\n * that the buflist is empty (there are no segments on the buflist).\n */\nLWS_VISIBLE LWS_EXTERN size_t\nlws_buflist_next_segment_len(struct lws_buflist **head, uint8_t **buf);\n/**\n * lws_buflist_use_segment(): remove len bytes from the current segment\n *\n * \\param head: list head\n * \\param len: number of bytes to mark as used\n *\n * If len is less than the remaining length of the current segment, the position\n * in the current segment is simply advanced and it returns.\n *\n * If len uses up the remaining length of the current segment, then the segment\n * is deleted and the list head moves to the next segment if any.\n *\n * Returns the number of bytes left in the current segment.  0 indicates\n * that the buflist is empty (there are no segments on the buflist).\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_buflist_use_segment(struct lws_buflist **head, size_t len);\n/**\n * lws_buflist_destroy_all_segments(): free all segments on the list\n *\n * \\param head: list head\n *\n * This frees everything on the list unconditionally.  *head is always\n * NULL after this.\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_buflist_destroy_all_segments(struct lws_buflist **head);\n\nvoid\nlws_buflist_describe(struct lws_buflist **head, void *id);\n\n/**\n * lws_ptr_diff(): helper to report distance between pointers as an int\n *\n * \\param head: the pointer with the larger address\n * \\param tail: the pointer with the smaller address\n *\n * This helper gives you an int representing the number of bytes further\n * forward the first pointer is compared to the second pointer.\n */\n#define lws_ptr_diff(head, tail) \\\n\t\t\t((int)((char *)(head) - (char *)(tail)))\n\n/**\n * lws_snprintf(): snprintf that truncates the returned length too\n *\n * \\param str: destination buffer\n * \\param size: bytes left in destination buffer\n * \\param format: format string\n * \\param ...: args for format\n *\n * This lets you correctly truncate buffers by concatenating lengths, if you\n * reach the limit the reported length doesn't exceed the limit.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_snprintf(char *str, size_t size, const char *format, ...) LWS_FORMAT(3);\n\n/**\n * lws_strncpy(): strncpy that guarantees NUL on truncated copy\n *\n * \\param dest: destination buffer\n * \\param src: source buffer\n * \\param size: bytes left in destination buffer\n *\n * This lets you correctly truncate buffers by concatenating lengths, if you\n * reach the limit the reported length doesn't exceed the limit.\n */\nLWS_VISIBLE LWS_EXTERN char *\nlws_strncpy(char *dest, const char *src, size_t size);\n\n/**\n * lws_get_random(): fill a buffer with platform random data\n *\n * \\param context: the lws context\n * \\param buf: buffer to fill\n * \\param len: how much to fill\n *\n * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if\n * it's interested to see if the frame it's dealing with was sent in binary\n * mode.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_get_random(struct lws_context *context, void *buf, int len);\n/**\n * lws_daemonize(): make current process run in the background\n *\n * \\param _lock_path: the filepath to write the lock file\n *\n * Spawn lws as a background process, taking care of various things\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_daemonize(const char *_lock_path);\n/**\n * lws_get_library_version(): return string describing the version of lws\n *\n * On unix, also includes the git describe\n */\nLWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT\nlws_get_library_version(void);\n\n/**\n * lws_wsi_user() - get the user data associated with the connection\n * \\param wsi: lws connection\n *\n * Not normally needed since it's passed into the callback\n */\nLWS_VISIBLE LWS_EXTERN void *\nlws_wsi_user(struct lws *wsi);\n\n/**\n * lws_wsi_set_user() - set the user data associated with the client connection\n * \\param wsi: lws connection\n * \\param user: user data\n *\n * By default lws allocates this and it's not legal to externally set it\n * yourself.  However client connections may have it set externally when the\n * connection is created... if so, this api can be used to modify it at\n * runtime additionally.\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_set_wsi_user(struct lws *wsi, void *user);\n\n/**\n * lws_parse_uri:\tcut up prot:/ads:port/path into pieces\n *\t\t\tNotice it does so by dropping '\\0' into input string\n *\t\t\tand the leading / on the path is consequently lost\n *\n * \\param p:\t\t\tincoming uri string.. will get written to\n * \\param prot:\t\tresult pointer for protocol part (https://)\n * \\param ads:\t\tresult pointer for address part\n * \\param port:\t\tresult pointer for port part\n * \\param path:\t\tresult pointer for path part\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_parse_uri(char *p, const char **prot, const char **ads, int *port,\n\t      const char **path);\n/**\n * lws_cmdline_option():\tsimple commandline parser\n *\n * \\param argc:\t\tcount of argument strings\n * \\param argv:\t\targument strings\n * \\param val:\t\tstring to find\n *\n * Returns NULL if the string \\p val is not found in the arguments.\n *\n * If it is found, then it returns a pointer to the next character after \\p val.\n * So if \\p val is \"-d\", then for the commandlines \"myapp -d15\" and\n * \"myapp -d 15\", in both cases the return will point to the \"15\".\n *\n * In the case there is no argument, like \"myapp -d\", the return will\n * either point to the '\\\\0' at the end of -d, or to the start of the\n * next argument, ie, will be non-NULL.\n */\nLWS_VISIBLE LWS_EXTERN const char *\nlws_cmdline_option(int argc, const char **argv, const char *val);\n\n/**\n * lws_now_secs(): return seconds since 1970-1-1\n */\nLWS_VISIBLE LWS_EXTERN unsigned long\nlws_now_secs(void);\n\n/**\n * lws_compare_time_t(): return relationship between two time_t\n *\n * \\param context: struct lws_context\n * \\param t1: time_t 1\n * \\param t2: time_t 2\n *\n * returns <0 if t2 > t1; >0 if t1 > t2; or == 0 if t1 == t2.\n *\n * This is aware of clock discontiguities that may have affected either t1 or\n * t2 and adapts the comparison for them.\n *\n * For the discontiguity detection to work, you must avoid any arithmetic on\n * the times being compared.  For example to have a timeout that triggers\n * 15s from when it was set, store the time it was set and compare like\n * `if (lws_compare_time_t(context, now, set_time) > 15)`\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_compare_time_t(struct lws_context *context, time_t t1, time_t t2);\n\n/**\n * lws_get_context - Allow getting lws_context from a Websocket connection\n * instance\n *\n * With this function, users can access context in the callback function.\n * Otherwise users may have to declare context as a global variable.\n *\n * \\param wsi:\tWebsocket connection instance\n */\nLWS_VISIBLE LWS_EXTERN struct lws_context * LWS_WARN_UNUSED_RESULT\nlws_get_context(const struct lws *wsi);\n\n/**\n * lws_get_vhost_listen_port - Find out the port number a vhost is listening on\n *\n * In the case you passed 0 for the port number at context creation time, you\n * can discover the port number that was actually chosen for the vhost using\n * this api.\n *\n * \\param vhost:\tVhost to get listen port from\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_get_vhost_listen_port(struct lws_vhost *vhost);\n\n/**\n * lws_get_count_threads(): how many service threads the context uses\n *\n * \\param context: the lws context\n *\n * By default this is always 1, if you asked for more than lws can handle it\n * will clip the number of threads.  So you can use this to find out how many\n * threads are actually in use.\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_get_count_threads(struct lws_context *context);\n\n/**\n * lws_get_parent() - get parent wsi or NULL\n * \\param wsi: lws connection\n *\n * Specialized wsi like cgi stdin/out/err are associated to a parent wsi,\n * this allows you to get their parent.\n */\nLWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT\nlws_get_parent(const struct lws *wsi);\n\n/**\n * lws_get_child() - get child wsi or NULL\n * \\param wsi: lws connection\n *\n * Allows you to find a related wsi from the parent wsi.\n */\nLWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT\nlws_get_child(const struct lws *wsi);\n\n/**\n * lws_get_udp() - get wsi's udp struct\n *\n * \\param wsi: lws connection\n *\n * Returns NULL or pointer to the wsi's UDP-specific information\n */\nLWS_VISIBLE LWS_EXTERN const struct lws_udp * LWS_WARN_UNUSED_RESULT\nlws_get_udp(const struct lws *wsi);\n\n/**\n * lws_parent_carries_io() - mark wsi as needing to send messages via parent\n *\n * \\param wsi: child lws connection\n */\n\nLWS_VISIBLE LWS_EXTERN void\nlws_set_parent_carries_io(struct lws *wsi);\n\nLWS_VISIBLE LWS_EXTERN void *\nlws_get_opaque_parent_data(const struct lws *wsi);\n\nLWS_VISIBLE LWS_EXTERN void\nlws_set_opaque_parent_data(struct lws *wsi, void *data);\n\nLWS_VISIBLE LWS_EXTERN int\nlws_get_child_pending_on_writable(const struct lws *wsi);\n\nLWS_VISIBLE LWS_EXTERN void\nlws_clear_child_pending_on_writable(struct lws *wsi);\n\nLWS_VISIBLE LWS_EXTERN int\nlws_get_close_length(struct lws *wsi);\n\nLWS_VISIBLE LWS_EXTERN unsigned char *\nlws_get_close_payload(struct lws *wsi);\n\n/**\n * lws_get_network_wsi() - Returns wsi that has the tcp connection for this wsi\n *\n * \\param wsi: wsi you have\n *\n * Returns wsi that has the tcp connection (which may be the incoming wsi)\n *\n * HTTP/1 connections will always return the incoming wsi\n * HTTP/2 connections may return a different wsi that has the tcp connection\n */\nLWS_VISIBLE LWS_EXTERN\nstruct lws *lws_get_network_wsi(struct lws *wsi);\n\n/**\n * lws_set_allocator() - custom allocator support\n *\n * \\param realloc\n *\n * Allows you to replace the allocator (and deallocator) used by lws\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_set_allocator(void *(*realloc)(void *ptr, size_t size, const char *reason));\n///@}\n\n/** \\defgroup wsstatus Websocket status APIs\n * ##Websocket connection status APIs\n *\n * These provide information about ws connection or message status\n */\n///@{\n/**\n * lws_send_pipe_choked() - tests if socket is writable or not\n * \\param wsi: lws connection\n *\n * Allows you to check if you can write more on the socket\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_send_pipe_choked(struct lws *wsi);\n\n/**\n * lws_is_final_fragment() - tests if last part of ws message\n *\n * \\param wsi: lws connection\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_is_final_fragment(struct lws *wsi);\n\n/**\n * lws_is_first_fragment() - tests if first part of ws message\n *\n * \\param wsi: lws connection\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_is_first_fragment(struct lws *wsi);\n\n/**\n * lws_get_reserved_bits() - access reserved bits of ws frame\n * \\param wsi: lws connection\n */\nLWS_VISIBLE LWS_EXTERN unsigned char\nlws_get_reserved_bits(struct lws *wsi);\n\n/**\n * lws_partial_buffered() - find out if lws buffered the last write\n * \\param wsi:\twebsocket connection to check\n *\n * Returns 1 if you cannot use lws_write because the last\n * write on this connection is still buffered, and can't be cleared without\n * returning to the service loop and waiting for the connection to be\n * writeable again.\n *\n * If you will try to do >1 lws_write call inside a single\n * WRITEABLE callback, you must check this after every write and bail if\n * set, ask for a new writeable callback and continue writing from there.\n *\n * This is never set at the start of a writeable callback, but any write\n * may set it.\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_partial_buffered(struct lws *wsi);\n\n/**\n * lws_frame_is_binary(): true if the current frame was sent in binary mode\n *\n * \\param wsi: the connection we are inquiring about\n *\n * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if\n * it's interested to see if the frame it's dealing with was sent in binary\n * mode.\n */\nLWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_frame_is_binary(struct lws *wsi);\n\n/**\n * lws_is_ssl() - Find out if connection is using SSL\n * \\param wsi:\twebsocket connection to check\n *\n *\tReturns 0 if the connection is not using SSL, 1 if using SSL and\n *\tusing verified cert, and 2 if using SSL but the cert was not\n *\tchecked (appears for client wsi told to skip check on connection)\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_is_ssl(struct lws *wsi);\n/**\n * lws_is_cgi() - find out if this wsi is running a cgi process\n * \\param wsi: lws connection\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_is_cgi(struct lws *wsi);\n\n\nstruct lws_wifi_scan { /* generic wlan scan item */\n\tstruct lws_wifi_scan *next;\n\tchar ssid[32];\n\tint32_t rssi; /* divide by .count to get db */\n\tuint8_t bssid[6];\n\tuint8_t count;\n\tuint8_t channel;\n\tuint8_t authmode;\n};\n\n#if defined(LWS_WITH_TLS) && !defined(LWS_WITH_MBEDTLS)\n/**\n * lws_get_ssl() - Return wsi's SSL context structure\n * \\param wsi:\twebsocket connection\n *\n * Returns pointer to the SSL library's context structure\n */\nLWS_VISIBLE LWS_EXTERN SSL*\nlws_get_ssl(struct lws *wsi);\n#endif\n\nenum lws_tls_cert_info {\n\tLWS_TLS_CERT_INFO_VALIDITY_FROM,\n\t/**< fills .time with the time_t the cert validity started from */\n\tLWS_TLS_CERT_INFO_VALIDITY_TO,\n\t/**< fills .time with the time_t the cert validity ends at */\n\tLWS_TLS_CERT_INFO_COMMON_NAME,\n\t/**< fills up to len bytes of .ns.name with the cert common name */\n\tLWS_TLS_CERT_INFO_ISSUER_NAME,\n\t/**< fills up to len bytes of .ns.name with the cert issuer name */\n\tLWS_TLS_CERT_INFO_USAGE,\n\t/**< fills verified with a bitfield asserting the valid uses */\n\tLWS_TLS_CERT_INFO_VERIFIED,\n\t/**< fills .verified with a bool representing peer cert validity,\n\t *   call returns -1 if no cert */\n\tLWS_TLS_CERT_INFO_OPAQUE_PUBLIC_KEY,\n\t/**< the certificate's public key, as an opaque bytestream.  These\n\t * opaque bytestreams can only be compared with each other using the\n\t * same tls backend, ie, OpenSSL or mbedTLS.  The different backends\n\t * produce different, incompatible representations for the same cert.\n\t */\n};\n\nunion lws_tls_cert_info_results {\n\tunsigned int verified;\n\ttime_t time;\n\tunsigned int usage;\n\tstruct {\n\t\tint len;\n\t\t/* KEEP LAST... notice the [64] is only there because\n\t\t * name[] is not allowed in a union.  The actual length of\n\t\t * name[] is arbitrary and is passed into the api using the\n\t\t * len parameter.  Eg\n\t\t *\n\t\t * char big[1024];\n\t\t * union lws_tls_cert_info_results *buf =\n\t\t * \t(union lws_tls_cert_info_results *)big;\n\t\t *\n\t\t * lws_tls_peer_cert_info(wsi, type, buf, sizeof(big) -\n\t\t *\t\t\t  sizeof(*buf) + sizeof(buf->ns.name));\n\t\t */\n\t\tchar name[64];\n\t} ns;\n};\n\n/**\n * lws_tls_peer_cert_info() - get information from the peer's TLS cert\n *\n * \\param wsi: the connection to query\n * \\param type: one of LWS_TLS_CERT_INFO_\n * \\param buf: pointer to union to take result\n * \\param len: when result is a string, the true length of buf->ns.name[]\n *\n * lws_tls_peer_cert_info() lets you get hold of information from the peer\n * certificate.\n *\n * Return 0 if there is a result in \\p buf, or -1 indicating there was no cert\n * or another problem.\n *\n * This function works the same no matter if the TLS backend is OpenSSL or\n * mbedTLS.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_tls_peer_cert_info(struct lws *wsi, enum lws_tls_cert_info type,\n\t\t       union lws_tls_cert_info_results *buf, size_t len);\n\n/**\n * lws_tls_vhost_cert_info() - get information from the vhost's own TLS cert\n *\n * \\param vhost: the vhost to query\n * \\param type: one of LWS_TLS_CERT_INFO_\n * \\param buf: pointer to union to take result\n * \\param len: when result is a string, the true length of buf->ns.name[]\n *\n * lws_tls_vhost_cert_info() lets you get hold of information from the vhost\n * certificate.\n *\n * Return 0 if there is a result in \\p buf, or -1 indicating there was no cert\n * or another problem.\n *\n * This function works the same no matter if the TLS backend is OpenSSL or\n * mbedTLS.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_tls_vhost_cert_info(struct lws_vhost *vhost, enum lws_tls_cert_info type,\n\t\t        union lws_tls_cert_info_results *buf, size_t len);\n\n/**\n * lws_tls_acme_sni_cert_create() - creates a temp selfsigned cert\n *\t\t\t\t    and attaches to a vhost\n *\n * \\param vhost: the vhost to acquire the selfsigned cert\n * \\param san_a: SAN written into the certificate\n * \\param san_b: second SAN written into the certificate\n *\n *\n * Returns 0 if created and attached to the vhost.  Returns -1 if problems and\n * frees all allocations before returning.\n *\n * On success, any allocations are destroyed at vhost destruction automatically.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_tls_acme_sni_cert_create(struct lws_vhost *vhost, const char *san_a,\n\t\t\t     const char *san_b);\n\n/**\n * lws_tls_acme_sni_csr_create() - creates a CSR and related private key PEM\n *\n * \\param context: lws_context used for random\n * \\param elements: array of LWS_TLS_REQ_ELEMENT_COUNT const char *\n * \\param csr: buffer that will get the b64URL(ASN-1 CSR)\n * \\param csr_len: max length of the csr buffer\n * \\param privkey_pem: pointer to pointer allocated to hold the privkey_pem\n * \\param privkey_len: pointer to size_t set to the length of the privkey_pem\n *\n * Creates a CSR according to the information in \\p elements, and a private\n * RSA key used to sign the CSR.\n *\n * The outputs are the b64URL(ASN-1 CSR) into csr, and the PEM private key into\n * privkey_pem.\n *\n * Notice that \\p elements points to an array of const char *s pointing to the\n * information listed in the enum above.  If an entry is NULL or an empty\n * string, the element is set to \"none\" in the CSR.\n *\n * Returns 0 on success or nonzero for failure.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_tls_acme_sni_csr_create(struct lws_context *context, const char *elements[],\n\t\t\t    uint8_t *csr, size_t csr_len, char **privkey_pem,\n\t\t\t    size_t *privkey_len);\n\n/**\n * lws_tls_cert_updated() - update every vhost using the given cert path\n *\n * \\param context: our lws_context\n * \\param certpath: the filepath to the certificate\n * \\param keypath: the filepath to the private key of the certificate\n * \\param mem_cert: copy of the cert in memory\n * \\param len_mem_cert: length of the copy of the cert in memory\n * \\param mem_privkey: copy of the private key in memory\n * \\param len_mem_privkey: length of the copy of the private key in memory\n *\n * Checks every vhost to see if it is the using certificate described by the\n * the given filepaths.  If so, it attempts to update the vhost ssl_ctx to use\n * the new certificate.\n *\n * Returns 0 on success or nonzero for failure.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_tls_cert_updated(struct lws_context *context, const char *certpath,\n\t\t     const char *keypath,\n\t\t     const char *mem_cert, size_t len_mem_cert,\n\t\t     const char *mem_privkey, size_t len_mem_privkey);\n///@}\n\n/** \\defgroup lws_ring LWS Ringbuffer APIs\n * ##lws_ring: generic ringbuffer struct\n *\n * Provides an abstract ringbuffer api supporting one head and one or an\n * unlimited number of tails.\n *\n * All of the members are opaque and manipulated by lws_ring_...() apis.\n *\n * The lws_ring and its buffer is allocated at runtime on the heap, using\n *\n *  - lws_ring_create()\n *  - lws_ring_destroy()\n *\n * It may contain any type, the size of the \"element\" stored in the ring\n * buffer and the number of elements is given at creation time.\n *\n * When you create the ringbuffer, you can optionally provide an element\n * destroy callback that frees any allocations inside the element.  This is then\n * automatically called for elements with no tail behind them, ie, elements\n * which don't have any pending consumer are auto-freed.\n *\n * Whole elements may be inserted into the ringbuffer and removed from it, using\n *\n *  - lws_ring_insert()\n *  - lws_ring_consume()\n *\n * You can find out how many whole elements are free or waiting using\n *\n *  - lws_ring_get_count_free_elements()\n *  - lws_ring_get_count_waiting_elements()\n *\n * In addition there are special purpose optional byte-centric apis\n *\n *  - lws_ring_next_linear_insert_range()\n *  - lws_ring_bump_head()\n *\n *  which let you, eg, read() directly into the ringbuffer without needing\n *  an intermediate bounce buffer.\n *\n *  The accessors understand that the ring wraps, and optimizes insertion and\n *  consumption into one or two memcpy()s depending on if the head or tail\n *  wraps.\n *\n *  lws_ring only supports a single head, but optionally multiple tails with\n *  an API to inform it when the \"oldest\" tail has moved on.  You can give\n *  NULL where-ever an api asks for a tail pointer, and it will use an internal\n *  single tail pointer for convenience.\n *\n *  The \"oldest tail\", which is the only tail if you give it NULL instead of\n *  some other tail, is used to track which elements in the ringbuffer are\n *  still unread by anyone.\n *\n *   - lws_ring_update_oldest_tail()\n */\n///@{\nstruct lws_ring;\n\n/**\n * lws_ring_create(): create a new ringbuffer\n *\n * \\param element_len: the size in bytes of one element in the ringbuffer\n * \\param count: the number of elements the ringbuffer can contain\n * \\param destroy_element: NULL, or callback to be called for each element\n *\t\t\t   that is removed from the ringbuffer due to the\n *\t\t\t   oldest tail moving beyond it\n *\n * Creates the ringbuffer and allocates the storage.  Returns the new\n * lws_ring *, or NULL if the allocation failed.\n *\n * If non-NULL, destroy_element will get called back for every element that is\n * retired from the ringbuffer after the oldest tail has gone past it, and for\n * any element still left in the ringbuffer when it is destroyed.  It replaces\n * all other element destruction code in your user code.\n */\nLWS_VISIBLE LWS_EXTERN struct lws_ring *\nlws_ring_create(size_t element_len, size_t count,\n\t\tvoid (*destroy_element)(void *element));\n\n/**\n * lws_ring_destroy():  destroy a previously created ringbuffer\n *\n * \\param ring: the struct lws_ring to destroy\n *\n * Destroys the ringbuffer allocation and the struct lws_ring itself.\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_ring_destroy(struct lws_ring *ring);\n\n/**\n * lws_ring_get_count_free_elements():  return how many elements can fit\n *\t\t\t\t      in the free space\n *\n * \\param ring: the struct lws_ring to report on\n *\n * Returns how much room is left in the ringbuffer for whole element insertion.\n */\nLWS_VISIBLE LWS_EXTERN size_t\nlws_ring_get_count_free_elements(struct lws_ring *ring);\n\n/**\n * lws_ring_get_count_waiting_elements():  return how many elements can be consumed\n *\n * \\param ring: the struct lws_ring to report on\n * \\param tail: a pointer to the tail struct to use, or NULL for single tail\n *\n * Returns how many elements are waiting to be consumed from the perspective\n * of the tail pointer given.\n */\nLWS_VISIBLE LWS_EXTERN size_t\nlws_ring_get_count_waiting_elements(struct lws_ring *ring, uint32_t *tail);\n\n/**\n * lws_ring_insert():  attempt to insert up to max_count elements from src\n *\n * \\param ring: the struct lws_ring to report on\n * \\param src: the array of elements to be inserted\n * \\param max_count: the number of available elements at src\n *\n * Attempts to insert as many of the elements at src as possible, up to the\n * maximum max_count.  Returns the number of elements actually inserted.\n */\nLWS_VISIBLE LWS_EXTERN size_t\nlws_ring_insert(struct lws_ring *ring, const void *src, size_t max_count);\n\n/**\n * lws_ring_consume():  attempt to copy out and remove up to max_count elements\n *\t\t        to src\n *\n * \\param ring: the struct lws_ring to report on\n * \\param tail: a pointer to the tail struct to use, or NULL for single tail\n * \\param dest: the array of elements to be inserted. or NULL for no copy\n * \\param max_count: the number of available elements at src\n *\n * Attempts to copy out as many waiting elements as possible into dest, from\n * the perspective of the given tail, up to max_count.  If dest is NULL, the\n * copying out is not done but the elements are logically consumed as usual.\n * NULL dest is useful in combination with lws_ring_get_element(), where you\n * can use the element direct from the ringbuffer and then call this with NULL\n * dest to logically consume it.\n *\n * Increments the tail position according to how many elements could be\n * consumed.\n *\n * Returns the number of elements consumed.\n */\nLWS_VISIBLE LWS_EXTERN size_t\nlws_ring_consume(struct lws_ring *ring, uint32_t *tail, void *dest,\n\t\t size_t max_count);\n\n/**\n * lws_ring_get_element():  get a pointer to the next waiting element for tail\n *\n * \\param ring: the struct lws_ring to report on\n * \\param tail: a pointer to the tail struct to use, or NULL for single tail\n *\n * Points to the next element that tail would consume, directly in the\n * ringbuffer.  This lets you write() or otherwise use the element without\n * having to copy it out somewhere first.\n *\n * After calling this, you must call lws_ring_consume(ring, &tail, NULL, 1)\n * which will logically consume the element you used up and increment your\n * tail (tail may also be NULL there if you use a single tail).\n *\n * Returns NULL if no waiting element, or a const void * pointing to it.\n */\nLWS_VISIBLE LWS_EXTERN const void *\nlws_ring_get_element(struct lws_ring *ring, uint32_t *tail);\n\n/**\n * lws_ring_update_oldest_tail():  free up elements older than tail for reuse\n *\n * \\param ring: the struct lws_ring to report on\n * \\param tail: a pointer to the tail struct to use, or NULL for single tail\n *\n * If you are using multiple tails, you must use this API to inform the\n * lws_ring when none of the tails still need elements in the fifo any more,\n * by updating it when the \"oldest\" tail has moved on.\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_ring_update_oldest_tail(struct lws_ring *ring, uint32_t tail);\n\n/**\n * lws_ring_get_oldest_tail():  get current oldest available data index\n *\n * \\param ring: the struct lws_ring to report on\n *\n * If you are initializing a new ringbuffer consumer, you can set its tail to\n * this to start it from the oldest ringbuffer entry still available.\n */\nLWS_VISIBLE LWS_EXTERN uint32_t\nlws_ring_get_oldest_tail(struct lws_ring *ring);\n\n/**\n * lws_ring_next_linear_insert_range():  used to write directly into the ring\n *\n * \\param ring: the struct lws_ring to report on\n * \\param start: pointer to a void * set to the start of the next ringbuffer area\n * \\param bytes: pointer to a size_t set to the max length you may use from *start\n *\n * This provides a low-level, bytewise access directly into the ringbuffer\n * allowing direct insertion of data without having to use a bounce buffer.\n *\n * The api reports the position and length of the next linear range that can\n * be written in the ringbuffer, ie, up to the point it would wrap, and sets\n * *start and *bytes accordingly.  You can then, eg, directly read() into\n * *start for up to *bytes, and use lws_ring_bump_head() to update the lws_ring\n * with what you have done.\n *\n * Returns nonzero if no insertion is currently possible.\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_ring_next_linear_insert_range(struct lws_ring *ring, void **start,\n\t\t\t\t  size_t *bytes);\n\n/**\n * lws_ring_bump_head():  used to write directly into the ring\n *\n * \\param ring: the struct lws_ring to operate on\n * \\param bytes: the number of bytes you inserted at the current head\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_ring_bump_head(struct lws_ring *ring, size_t bytes);\n\nLWS_VISIBLE LWS_EXTERN void\nlws_ring_dump(struct lws_ring *ring, uint32_t *tail);\n\n/*\n * This is a helper that combines the common pattern of needing to consume\n * some ringbuffer elements, move the consumer tail on, and check if that\n * has moved any ringbuffer elements out of scope, because it was the last\n * consumer that had not already consumed them.\n *\n * Elements that go out of scope because the oldest tail is now after them\n * get garbage-collected by calling the destroy_element callback on them\n * defined when the ringbuffer was created.\n */\n\n#define lws_ring_consume_and_update_oldest_tail(\\\n\t\t___ring,    /* the lws_ring object */ \\\n\t\t___type,    /* type of objects with tails */ \\\n\t\t___ptail,   /* ptr to tail of obj with tail doing consuming */ \\\n\t\t___count,   /* count of payload objects being consumed */ \\\n\t\t___list_head,\t/* head of list of objects with tails */ \\\n\t\t___mtail,   /* member name of tail in ___type */ \\\n\t\t___mlist  /* member name of next list member ptr in ___type */ \\\n\t) { \\\n\t\tint ___n, ___m; \\\n\t\\\n\t___n = lws_ring_get_oldest_tail(___ring) == *(___ptail); \\\n\tlws_ring_consume(___ring, ___ptail, NULL, ___count); \\\n\tif (___n) { \\\n\t\tuint32_t ___oldest; \\\n\t\t___n = 0; \\\n\t\t___oldest = *(___ptail); \\\n\t\tlws_start_foreach_llp(___type **, ___ppss, ___list_head) { \\\n\t\t\t___m = lws_ring_get_count_waiting_elements( \\\n\t\t\t\t\t___ring, &(*___ppss)->tail); \\\n\t\t\tif (___m >= ___n) { \\\n\t\t\t\t___n = ___m; \\\n\t\t\t\t___oldest = (*___ppss)->tail; \\\n\t\t\t} \\\n\t\t} lws_end_foreach_llp(___ppss, ___mlist); \\\n\t\\\n\t\tlws_ring_update_oldest_tail(___ring, ___oldest); \\\n\t} \\\n}\n\n/*\n * This does the same as the lws_ring_consume_and_update_oldest_tail()\n * helper, but for the simpler case there is only one consumer, so one\n * tail, and that tail is always the oldest tail.\n */\n\n#define lws_ring_consume_single_tail(\\\n\t\t___ring,  /* the lws_ring object */ \\\n\t\t___ptail, /* ptr to tail of obj with tail doing consuming */ \\\n\t\t___count  /* count of payload objects being consumed */ \\\n\t) { \\\n\tlws_ring_consume(___ring, ___ptail, NULL, ___count); \\\n\tlws_ring_update_oldest_tail(___ring, *(___ptail)); \\\n}\n///@}\n\n/** \\defgroup sha SHA and B64 helpers\n * ##SHA and B64 helpers\n *\n * These provide SHA-1 and B64 helper apis\n */\n///@{\n#ifdef LWS_SHA1_USE_OPENSSL_NAME\n#define lws_SHA1 SHA1\n#else\n/**\n * lws_SHA1(): make a SHA-1 digest of a buffer\n *\n * \\param d: incoming buffer\n * \\param n: length of incoming buffer\n * \\param md: buffer for message digest (must be >= 20 bytes)\n *\n * Reduces any size buffer into a 20-byte SHA-1 hash.\n */\nLWS_VISIBLE LWS_EXTERN unsigned char *\nlws_SHA1(const unsigned char *d, size_t n, unsigned char *md);\n#endif\n/**\n * lws_b64_encode_string(): encode a string into base 64\n *\n * \\param in: incoming buffer\n * \\param in_len: length of incoming buffer\n * \\param out: result buffer\n * \\param out_size: length of result buffer\n *\n * Encodes a string using b64\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_b64_encode_string(const char *in, int in_len, char *out, int out_size);\n/**\n * lws_b64_encode_string_url(): encode a string into base 64\n *\n * \\param in: incoming buffer\n * \\param in_len: length of incoming buffer\n * \\param out: result buffer\n * \\param out_size: length of result buffer\n *\n * Encodes a string using b64 with the \"URL\" variant (+ -> -, and / -> _)\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_b64_encode_string_url(const char *in, int in_len, char *out, int out_size);\n/**\n * lws_b64_decode_string(): decode a string from base 64\n *\n * \\param in: incoming buffer\n * \\param out: result buffer\n * \\param out_size: length of result buffer\n *\n * Decodes a NUL-terminated string using b64\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_b64_decode_string(const char *in, char *out, int out_size);\n/**\n * lws_b64_decode_string_len(): decode a string from base 64\n *\n * \\param in: incoming buffer\n * \\param in_len: length of incoming buffer\n * \\param out: result buffer\n * \\param out_size: length of result buffer\n *\n * Decodes a range of chars using b64\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_b64_decode_string_len(const char *in, int in_len, char *out, int out_size);\n///@}\n\n\n/*! \\defgroup cgi cgi handling\n *\n * ##CGI handling\n *\n * These functions allow low-level control over stdin/out/err of the cgi.\n *\n * However for most cases, binding the cgi to http in and out, the default\n * lws implementation already does the right thing.\n */\n\nenum lws_enum_stdinouterr {\n\tLWS_STDIN = 0,\n\tLWS_STDOUT = 1,\n\tLWS_STDERR = 2,\n};\n\nenum lws_cgi_hdr_state {\n\tLCHS_HEADER,\n\tLCHS_CR1,\n\tLCHS_LF1,\n\tLCHS_CR2,\n\tLCHS_LF2,\n\tLHCS_RESPONSE,\n\tLHCS_DUMP_HEADERS,\n\tLHCS_PAYLOAD,\n\tLCHS_SINGLE_0A,\n};\n\nstruct lws_cgi_args {\n\tstruct lws **stdwsi; /**< get fd with lws_get_socket_fd() */\n\tenum lws_enum_stdinouterr ch; /**< channel index */\n\tunsigned char *data; /**< for messages with payload */\n\tenum lws_cgi_hdr_state hdr_state; /**< track where we are in cgi headers */\n\tint len; /**< length */\n};\n\n#ifdef LWS_WITH_CGI\n/**\n * lws_cgi: spawn network-connected cgi process\n *\n * \\param wsi: connection to own the process\n * \\param exec_array: array of \"exec-name\" \"arg1\" ... \"argn\" NULL\n * \\param script_uri_path_len: how many chars on the left of the uri are the\n *        path to the cgi, or -1 to spawn without URL-related env vars\n * \\param timeout_secs: seconds script should be allowed to run\n * \\param mp_cgienv: pvo list with per-vhost cgi options to put in env\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_cgi(struct lws *wsi, const char * const *exec_array,\n\tint script_uri_path_len, int timeout_secs,\n\tconst struct lws_protocol_vhost_options *mp_cgienv);\n\n/**\n * lws_cgi_write_split_stdout_headers: write cgi output accounting for header part\n *\n * \\param wsi: connection to own the process\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_cgi_write_split_stdout_headers(struct lws *wsi);\n\n/**\n * lws_cgi_kill: terminate cgi process associated with wsi\n *\n * \\param wsi: connection to own the process\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_cgi_kill(struct lws *wsi);\n\n/**\n * lws_cgi_get_stdwsi: get wsi for stdin, stdout, or stderr\n *\n * \\param wsi: parent wsi that has cgi\n * \\param ch: which of LWS_STDIN, LWS_STDOUT or LWS_STDERR\n */\nLWS_VISIBLE LWS_EXTERN struct lws *\nlws_cgi_get_stdwsi(struct lws *wsi, enum lws_enum_stdinouterr ch);\n\n#endif\n///@}\n\n\n/*! \\defgroup fops file operation wrapping\n *\n * ##File operation wrapping\n *\n * Use these helper functions if you want to access a file from the perspective\n * of a specific wsi, which is usually the case.  If you just want contextless\n * file access, use the fops callbacks directly with NULL wsi instead of these\n * helpers.\n *\n * If so, then it calls the platform handler or user overrides where present\n * (as defined in info->fops)\n *\n * The advantage from all this is user code can be portable for file operations\n * without having to deal with differences between platforms.\n */\n//@{\n\n/** struct lws_plat_file_ops - Platform-specific file operations\n *\n * These provide platform-agnostic ways to deal with filesystem access in the\n * library and in the user code.\n */\n\n#if defined(LWS_WITH_ESP32)\n/* sdk preprocessor defs? compiler issue? gets confused with member names */\n#define LWS_FOP_OPEN\t\t_open\n#define LWS_FOP_CLOSE\t\t_close\n#define LWS_FOP_SEEK_CUR\t_seek_cur\n#define LWS_FOP_READ\t\t_read\n#define LWS_FOP_WRITE\t\t_write\n#else\n#define LWS_FOP_OPEN\t\topen\n#define LWS_FOP_CLOSE\t\tclose\n#define LWS_FOP_SEEK_CUR\tseek_cur\n#define LWS_FOP_READ\t\tread\n#define LWS_FOP_WRITE\t\twrite\n#endif\n\n#define LWS_FOP_FLAGS_MASK\t\t   ((1 << 23) - 1)\n#define LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP (1 << 24)\n#define LWS_FOP_FLAG_COMPR_IS_GZIP\t   (1 << 25)\n#define LWS_FOP_FLAG_MOD_TIME_VALID\t   (1 << 26)\n#define LWS_FOP_FLAG_VIRTUAL\t\t   (1 << 27)\n\nstruct lws_plat_file_ops;\n\nstruct lws_fop_fd {\n\tlws_filefd_type\t\t\tfd;\n\t/**< real file descriptor related to the file... */\n\tconst struct lws_plat_file_ops\t*fops;\n\t/**< fops that apply to this fop_fd */\n\tvoid\t\t\t\t*filesystem_priv;\n\t/**< ignored by lws; owned by the fops handlers */\n\tlws_filepos_t\t\t\tpos;\n\t/**< generic \"position in file\" */\n\tlws_filepos_t\t\t\tlen;\n\t/**< generic \"length of file\" */\n\tlws_fop_flags_t\t\t\tflags;\n\t/**< copy of the returned flags */\n\tuint32_t\t\t\tmod_time;\n\t/**< optional \"modification time of file\", only valid if .open()\n\t * set the LWS_FOP_FLAG_MOD_TIME_VALID flag */\n};\ntypedef struct lws_fop_fd *lws_fop_fd_t;\n\nstruct lws_fops_index {\n\tconst char *sig;\t/* NULL or vfs signature, eg, \".zip/\" */\n\tuint8_t len;\t\t/* length of above string */\n};\n\nstruct lws_plat_file_ops {\n\tlws_fop_fd_t (*LWS_FOP_OPEN)(const struct lws_plat_file_ops *fops,\n\t\t\t\t     const char *filename, const char *vpath,\n\t\t\t\t     lws_fop_flags_t *flags);\n\t/**< Open file (always binary access if plat supports it)\n\t * vpath may be NULL, or if the fops understands it, the point at which\n\t * the filename's virtual part starts.\n\t * *flags & LWS_FOP_FLAGS_MASK should be set to O_RDONLY or O_RDWR.\n\t * If the file may be gzip-compressed,\n\t * LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP is set.  If it actually is\n\t * gzip-compressed, then the open handler should OR\n\t * LWS_FOP_FLAG_COMPR_IS_GZIP on to *flags before returning.\n\t */\n\tint (*LWS_FOP_CLOSE)(lws_fop_fd_t *fop_fd);\n\t/**< close file AND set the pointer to NULL */\n\tlws_fileofs_t (*LWS_FOP_SEEK_CUR)(lws_fop_fd_t fop_fd,\n\t\t\t\t\t  lws_fileofs_t offset_from_cur_pos);\n\t/**< seek from current position */\n\tint (*LWS_FOP_READ)(lws_fop_fd_t fop_fd, lws_filepos_t *amount,\n\t\t\t    uint8_t *buf, lws_filepos_t len);\n\t/**< Read from file, on exit *amount is set to amount actually read */\n\tint (*LWS_FOP_WRITE)(lws_fop_fd_t fop_fd, lws_filepos_t *amount,\n\t\t\t     uint8_t *buf, lws_filepos_t len);\n\t/**< Write to file, on exit *amount is set to amount actually written */\n\n\tstruct lws_fops_index fi[3];\n\t/**< vfs path signatures implying use of this fops */\n\n\tconst struct lws_plat_file_ops *next;\n\t/**< NULL or next fops in list */\n\n\t/* Add new things just above here ---^\n\t * This is part of the ABI, don't needlessly break compatibility */\n};\n\n/**\n * lws_get_fops() - get current file ops\n *\n * \\param context: context\n */\nLWS_VISIBLE LWS_EXTERN struct lws_plat_file_ops * LWS_WARN_UNUSED_RESULT\nlws_get_fops(struct lws_context *context);\nLWS_VISIBLE LWS_EXTERN void\nlws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops);\n/**\n * lws_vfs_tell() - get current file position\n *\n * \\param fop_fd: fop_fd we are asking about\n */\nLWS_VISIBLE LWS_EXTERN lws_filepos_t LWS_WARN_UNUSED_RESULT\nlws_vfs_tell(lws_fop_fd_t fop_fd);\n/**\n * lws_vfs_get_length() - get current file total length in bytes\n *\n * \\param fop_fd: fop_fd we are asking about\n */\nLWS_VISIBLE LWS_EXTERN lws_filepos_t LWS_WARN_UNUSED_RESULT\nlws_vfs_get_length(lws_fop_fd_t fop_fd);\n/**\n * lws_vfs_get_mod_time() - get time file last modified\n *\n * \\param fop_fd: fop_fd we are asking about\n */\nLWS_VISIBLE LWS_EXTERN uint32_t LWS_WARN_UNUSED_RESULT\nlws_vfs_get_mod_time(lws_fop_fd_t fop_fd);\n/**\n * lws_vfs_file_seek_set() - seek relative to start of file\n *\n * \\param fop_fd: fop_fd we are seeking in\n * \\param offset: offset from start of file\n */\nLWS_VISIBLE LWS_EXTERN lws_fileofs_t\nlws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset);\n/**\n * lws_vfs_file_seek_end() - seek relative to end of file\n *\n * \\param fop_fd: fop_fd we are seeking in\n * \\param offset: offset from start of file\n */\nLWS_VISIBLE LWS_EXTERN lws_fileofs_t\nlws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset);\n\nextern struct lws_plat_file_ops fops_zip;\n\n/**\n * lws_plat_file_open() - open vfs filepath\n *\n * \\param fops: file ops struct that applies to this descriptor\n * \\param vfs_path: filename to open\n * \\param flags: pointer to open flags\n *\n * The vfs_path is scanned for known fops signatures, and the open directed\n * to any matching fops open.\n *\n * User code should use this api to perform vfs opens.\n *\n * returns semi-opaque handle\n */\nLWS_VISIBLE LWS_EXTERN lws_fop_fd_t LWS_WARN_UNUSED_RESULT\nlws_vfs_file_open(const struct lws_plat_file_ops *fops, const char *vfs_path,\n\t\t  lws_fop_flags_t *flags);\n\n/**\n * lws_plat_file_close() - close file\n *\n * \\param fop_fd: file handle to close\n */\nstatic LWS_INLINE int\nlws_vfs_file_close(lws_fop_fd_t *fop_fd)\n{\n\treturn (*fop_fd)->fops->LWS_FOP_CLOSE(fop_fd);\n}\n\n/**\n * lws_plat_file_seek_cur() - close file\n *\n *\n * \\param fop_fd: file handle\n * \\param offset: position to seek to\n */\nstatic LWS_INLINE lws_fileofs_t\nlws_vfs_file_seek_cur(lws_fop_fd_t fop_fd, lws_fileofs_t offset)\n{\n\treturn fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, offset);\n}\n/**\n * lws_plat_file_read() - read from file\n *\n * \\param fop_fd: file handle\n * \\param amount: how much to read (rewritten by call)\n * \\param buf: buffer to write to\n * \\param len: max length\n */\nstatic LWS_INLINE int LWS_WARN_UNUSED_RESULT\nlws_vfs_file_read(lws_fop_fd_t fop_fd, lws_filepos_t *amount,\n\t\t   uint8_t *buf, lws_filepos_t len)\n{\n\treturn fop_fd->fops->LWS_FOP_READ(fop_fd, amount, buf, len);\n}\n/**\n * lws_plat_file_write() - write from file\n *\n * \\param fop_fd: file handle\n * \\param amount: how much to write (rewritten by call)\n * \\param buf: buffer to read from\n * \\param len: max length\n */\nstatic LWS_INLINE int LWS_WARN_UNUSED_RESULT\nlws_vfs_file_write(lws_fop_fd_t fop_fd, lws_filepos_t *amount,\n\t\t    uint8_t *buf, lws_filepos_t len)\n{\n\treturn fop_fd->fops->LWS_FOP_WRITE(fop_fd, amount, buf, len);\n}\n\n/* these are the platform file operations implementations... they can\n * be called directly and used in fops arrays\n */\n\nLWS_VISIBLE LWS_EXTERN lws_fop_fd_t\n_lws_plat_file_open(const struct lws_plat_file_ops *fops, const char *filename,\n\t\t    const char *vpath, lws_fop_flags_t *flags);\nLWS_VISIBLE LWS_EXTERN int\n_lws_plat_file_close(lws_fop_fd_t *fop_fd);\nLWS_VISIBLE LWS_EXTERN lws_fileofs_t\n_lws_plat_file_seek_cur(lws_fop_fd_t fop_fd, lws_fileofs_t offset);\nLWS_VISIBLE LWS_EXTERN int\n_lws_plat_file_read(lws_fop_fd_t fop_fd, lws_filepos_t *amount,\n\t\t    uint8_t *buf, lws_filepos_t len);\nLWS_VISIBLE LWS_EXTERN int\n_lws_plat_file_write(lws_fop_fd_t fop_fd, lws_filepos_t *amount,\n\t\t     uint8_t *buf, lws_filepos_t len);\n\nLWS_VISIBLE LWS_EXTERN int\nlws_alloc_vfs_file(struct lws_context *context, const char *filename,\n\t\t   uint8_t **buf, lws_filepos_t *amount);\n//@}\n\n/** \\defgroup smtp SMTP related functions\n * ##SMTP related functions\n * \\ingroup lwsapi\n *\n * These apis let you communicate with a local SMTP server to send email from\n * lws.  It handles all the SMTP sequencing and protocol actions.\n *\n * Your system should have postfix, sendmail or another MTA listening on port\n * 25 and able to send email using the \"mail\" commandline app.  Usually distro\n * MTAs are configured for this by default.\n *\n * It runs via its own libuv events if initialized (which requires giving it\n * a libuv loop to attach to).\n *\n * It operates using three callbacks, on_next() queries if there is a new email\n * to send, on_get_body() asks for the body of the email, and on_sent() is\n * called after the email is successfully sent.\n *\n * To use it\n *\n *  - create an lws_email struct\n *\n *  - initialize data, loop, the email_* strings, max_content_size and\n *    the callbacks\n *\n *  - call lws_email_init()\n *\n *  When you have at least one email to send, call lws_email_check() to\n *  schedule starting to send it.\n */\n//@{\n#ifdef LWS_WITH_SMTP\n\n/** enum lwsgs_smtp_states - where we are in SMTP protocol sequence */\nenum lwsgs_smtp_states {\n\tLGSSMTP_IDLE, /**< awaiting new email */\n\tLGSSMTP_CONNECTING, /**< opening tcp connection to MTA */\n\tLGSSMTP_CONNECTED, /**< tcp connection to MTA is connected */\n\tLGSSMTP_SENT_HELO, /**< sent the HELO */\n\tLGSSMTP_SENT_FROM, /**< sent FROM */\n\tLGSSMTP_SENT_TO, /**< sent TO */\n\tLGSSMTP_SENT_DATA, /**< sent DATA request */\n\tLGSSMTP_SENT_BODY, /**< sent the email body */\n\tLGSSMTP_SENT_QUIT, /**< sent the session quit */\n};\n\n/** struct lws_email - abstract context for performing SMTP operations */\nstruct lws_email {\n\tvoid *data;\n\t/**< opaque pointer set by user code and available to the callbacks */\n\tuv_loop_t *loop;\n\t/**< the libuv loop we will work on */\n\n\tchar email_smtp_ip[32]; /**< Fill before init, eg, \"127.0.0.1\" */\n\tchar email_helo[32];\t/**< Fill before init, eg, \"myserver.com\" */\n\tchar email_from[100];\t/**< Fill before init or on_next */\n\tchar email_to[100];\t/**< Fill before init or on_next */\n\n\tunsigned int max_content_size;\n\t/**< largest possible email body size */\n\n\t/* Fill all the callbacks before init */\n\n\tint (*on_next)(struct lws_email *email);\n\t/**< (Fill in before calling lws_email_init)\n\t * called when idle, 0 = another email to send, nonzero is idle.\n\t * If you return 0, all of the email_* char arrays must be set\n\t * to something useful. */\n\tint (*on_sent)(struct lws_email *email);\n\t/**< (Fill in before calling lws_email_init)\n\t * called when transfer of the email to the SMTP server was\n\t * successful, your callback would remove the current email\n\t * from its queue */\n\tint (*on_get_body)(struct lws_email *email, char *buf, int len);\n\t/**< (Fill in before calling lws_email_init)\n\t * called when the body part of the queued email is about to be\n\t * sent to the SMTP server. */\n\n\n\t/* private things */\n\tuv_timer_t timeout_email; /**< private */\n\tenum lwsgs_smtp_states estate; /**< private */\n\tuv_connect_t email_connect_req; /**< private */\n\tuv_tcp_t email_client; /**< private */\n\ttime_t email_connect_started; /**< private */\n\tchar email_buf[256]; /**< private */\n\tchar *content; /**< private */\n};\n\n/**\n * lws_email_init() - Initialize a struct lws_email\n *\n * \\param email: struct lws_email to init\n * \\param loop: libuv loop to use\n * \\param max_content: max email content size\n *\n * Prepares a struct lws_email for use ending SMTP\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_email_init(struct lws_email *email, uv_loop_t *loop, int max_content);\n\n/**\n * lws_email_check() - Request check for new email\n *\n * \\param email: struct lws_email context to check\n *\n * Schedules a check for new emails in 1s... call this when you have queued an\n * email for send.\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_email_check(struct lws_email *email);\n/**\n * lws_email_destroy() - stop using the struct lws_email\n *\n * \\param email: the struct lws_email context\n *\n * Stop sending email using email and free allocations\n */\nLWS_VISIBLE LWS_EXTERN void\nlws_email_destroy(struct lws_email *email);\n\n#endif\n//@}\n\n\n/** \\defgroup lejp JSON parser\n * ##JSON parsing related functions\n * \\ingroup lwsapi\n *\n * LEJP is an extremely lightweight JSON stream parser included in lws.\n */\n//@{\nstruct lejp_ctx;\n\n#define LWS_ARRAY_SIZE(_x) (sizeof(_x) / sizeof(_x[0]))\n#define LEJP_FLAG_WS_KEEP 64\n#define LEJP_FLAG_WS_COMMENTLINE 32\n\nenum lejp_states {\n\tLEJP_IDLE = 0,\n\tLEJP_MEMBERS = 1,\n\tLEJP_M_P = 2,\n\tLEJP_MP_STRING = LEJP_FLAG_WS_KEEP | 3,\n\tLEJP_MP_STRING_ESC = LEJP_FLAG_WS_KEEP | 4,\n\tLEJP_MP_STRING_ESC_U1 = LEJP_FLAG_WS_KEEP | 5,\n\tLEJP_MP_STRING_ESC_U2 = LEJP_FLAG_WS_KEEP | 6,\n\tLEJP_MP_STRING_ESC_U3 = LEJP_FLAG_WS_KEEP | 7,\n\tLEJP_MP_STRING_ESC_U4 = LEJP_FLAG_WS_KEEP | 8,\n\tLEJP_MP_DELIM = 9,\n\tLEJP_MP_VALUE = 10,\n\tLEJP_MP_VALUE_NUM_INT = LEJP_FLAG_WS_KEEP | 11,\n\tLEJP_MP_VALUE_NUM_EXP = LEJP_FLAG_WS_KEEP | 12,\n\tLEJP_MP_VALUE_TOK = LEJP_FLAG_WS_KEEP | 13,\n\tLEJP_MP_COMMA_OR_END = 14,\n\tLEJP_MP_ARRAY_END = 15,\n};\n\nenum lejp_reasons {\n\tLEJP_CONTINUE = -1,\n\tLEJP_REJECT_IDLE_NO_BRACE = -2,\n\tLEJP_REJECT_MEMBERS_NO_CLOSE = -3,\n\tLEJP_REJECT_MP_NO_OPEN_QUOTE = -4,\n\tLEJP_REJECT_MP_STRING_UNDERRUN = -5,\n\tLEJP_REJECT_MP_ILLEGAL_CTRL = -6,\n\tLEJP_REJECT_MP_STRING_ESC_ILLEGAL_ESC = -7,\n\tLEJP_REJECT_ILLEGAL_HEX = -8,\n\tLEJP_REJECT_MP_DELIM_MISSING_COLON = -9,\n\tLEJP_REJECT_MP_DELIM_BAD_VALUE_START = -10,\n\tLEJP_REJECT_MP_VAL_NUM_INT_NO_FRAC = -11,\n\tLEJP_REJECT_MP_VAL_NUM_FORMAT = -12,\n\tLEJP_REJECT_MP_VAL_NUM_EXP_BAD_EXP = -13,\n\tLEJP_REJECT_MP_VAL_TOK_UNKNOWN = -14,\n\tLEJP_REJECT_MP_C_OR_E_UNDERF = -15,\n\tLEJP_REJECT_MP_C_OR_E_NOTARRAY = -16,\n\tLEJP_REJECT_MP_ARRAY_END_MISSING = -17,\n\tLEJP_REJECT_STACK_OVERFLOW = -18,\n\tLEJP_REJECT_MP_DELIM_ISTACK = -19,\n\tLEJP_REJECT_NUM_TOO_LONG = -20,\n\tLEJP_REJECT_MP_C_OR_E_NEITHER = -21,\n\tLEJP_REJECT_UNKNOWN = -22,\n\tLEJP_REJECT_CALLBACK = -23\n};\n\n#define LEJP_FLAG_CB_IS_VALUE 64\n\nenum lejp_callbacks {\n\tLEJPCB_CONSTRUCTED\t= 0,\n\tLEJPCB_DESTRUCTED\t= 1,\n\n\tLEJPCB_START\t\t= 2,\n\tLEJPCB_COMPLETE\t\t= 3,\n\tLEJPCB_FAILED\t\t= 4,\n\n\tLEJPCB_PAIR_NAME\t= 5,\n\n\tLEJPCB_VAL_TRUE\t\t= LEJP_FLAG_CB_IS_VALUE | 6,\n\tLEJPCB_VAL_FALSE\t= LEJP_FLAG_CB_IS_VALUE | 7,\n\tLEJPCB_VAL_NULL\t\t= LEJP_FLAG_CB_IS_VALUE | 8,\n\tLEJPCB_VAL_NUM_INT\t= LEJP_FLAG_CB_IS_VALUE | 9,\n\tLEJPCB_VAL_NUM_FLOAT\t= LEJP_FLAG_CB_IS_VALUE | 10,\n\tLEJPCB_VAL_STR_START\t= 11, /* notice handle separately */\n\tLEJPCB_VAL_STR_CHUNK\t= LEJP_FLAG_CB_IS_VALUE | 12,\n\tLEJPCB_VAL_STR_END\t= LEJP_FLAG_CB_IS_VALUE | 13,\n\n\tLEJPCB_ARRAY_START\t= 14,\n\tLEJPCB_ARRAY_END\t= 15,\n\n\tLEJPCB_OBJECT_START\t= 16,\n\tLEJPCB_OBJECT_END\t= 17\n};\n\n/**\n * _lejp_callback() - User parser actions\n * \\param ctx:\tLEJP context\n * \\param reason:\tCallback reason\n *\n *\tYour user callback is associated with the context at construction time,\n *\tand receives calls as the parsing progresses.\n *\n *\tAll of the callbacks may be ignored and just return 0.\n *\n *\tThe reasons it might get called, found in @reason, are:\n *\n *  LEJPCB_CONSTRUCTED:  The context was just constructed... you might want to\n *\t\tperform one-time allocation for the life of the context.\n *\n *  LEJPCB_DESTRUCTED:\tThe context is being destructed... if you made any\n *\t\tallocations at construction-time, you can free them now\n *\n *  LEJPCB_START:\tParsing is beginning at the first byte of input\n *\n *  LEJPCB_COMPLETE:\tParsing has completed successfully.  You'll get a 0 or\n *\t\t\tpositive return code from lejp_parse indicating the\n *\t\t\tamount of unused bytes left in the input buffer\n *\n *  LEJPCB_FAILED:\tParsing failed.  You'll get a negative error code\n *  \t\t\treturned from lejp_parse\n *\n *  LEJPCB_PAIR_NAME:\tWhen a \"name\":\"value\" pair has had the name parsed,\n *\t\t\tthis callback occurs.  You can find the new name at\n *\t\t\tthe end of ctx->path[]\n *\n *  LEJPCB_VAL_TRUE:\tThe \"true\" value appeared\n *\n *  LEJPCB_VAL_FALSE:\tThe \"false\" value appeared\n *\n *  LEJPCB_VAL_NULL:\tThe \"null\" value appeared\n *\n *  LEJPCB_VAL_NUM_INT:\tA string representing an integer is in ctx->buf\n *\n *  LEJPCB_VAL_NUM_FLOAT: A string representing a float is in ctx->buf\n *\n *  LEJPCB_VAL_STR_START: We are starting to parse a string, no data yet\n *\n *  LEJPCB_VAL_STR_CHUNK: We parsed LEJP_STRING_CHUNK -1 bytes of string data in\n *\t\t\tctx->buf, which is as much as we can buffer, so we are\n *\t\t\tspilling it.  If all your strings are less than\n *\t\t\tLEJP_STRING_CHUNK - 1 bytes, you will never see this\n *\t\t\tcallback.\n *\n *  LEJPCB_VAL_STR_END:\tString parsing has completed, the last chunk of the\n *\t\t\tstring is in ctx->buf.\n *\n *  LEJPCB_ARRAY_START:\tAn array started\n *\n *  LEJPCB_ARRAY_END:\tAn array ended\n *\n *  LEJPCB_OBJECT_START: An object started\n *\n *  LEJPCB_OBJECT_END:\tAn object ended\n */\nLWS_EXTERN signed char _lejp_callback(struct lejp_ctx *ctx, char reason);\n\ntypedef signed char (*lejp_callback)(struct lejp_ctx *ctx, char reason);\n\n#ifndef LEJP_MAX_DEPTH\n#define LEJP_MAX_DEPTH 12\n#endif\n#ifndef LEJP_MAX_INDEX_DEPTH\n#define LEJP_MAX_INDEX_DEPTH 5\n#endif\n#ifndef LEJP_MAX_PATH\n#define LEJP_MAX_PATH 128\n#endif\n#ifndef LEJP_STRING_CHUNK\n/* must be >= 30 to assemble floats */\n#define LEJP_STRING_CHUNK 254\n#endif\n\nenum num_flags {\n\tLEJP_SEEN_MINUS = (1 << 0),\n\tLEJP_SEEN_POINT = (1 << 1),\n\tLEJP_SEEN_POST_POINT = (1 << 2),\n\tLEJP_SEEN_EXP = (1 << 3)\n};\n\nstruct _lejp_stack {\n\tchar s; /* lejp_state stack*/\n\tchar p;\t/* path length */\n\tchar i; /* index array length */\n\tchar b; /* user bitfield */\n};\n\nstruct lejp_ctx {\n\n\t/* sorted by type for most compact alignment\n\t *\n\t * pointers\n\t */\n\n\tsigned char (*callback)(struct lejp_ctx *ctx, char reason);\n\tvoid *user;\n\tconst char * const *paths;\n\n\t/* arrays */\n\n\tstruct _lejp_stack st[LEJP_MAX_DEPTH];\n\tuint16_t i[LEJP_MAX_INDEX_DEPTH]; /* index array */\n\tuint16_t wild[LEJP_MAX_INDEX_DEPTH]; /* index array */\n\tchar path[LEJP_MAX_PATH];\n\tchar buf[LEJP_STRING_CHUNK + 1];\n\n\t/* int */\n\n\tuint32_t line;\n\n\t/* short */\n\n\tuint16_t uni;\n\n\t/* char */\n\n\tuint8_t npos;\n\tuint8_t dcount;\n\tuint8_t f;\n\tuint8_t sp; /* stack head */\n\tuint8_t ipos; /* index stack depth */\n\tuint8_t ppos;\n\tuint8_t count_paths;\n\tuint8_t path_match;\n\tuint8_t path_match_len;\n\tuint8_t wildcount;\n};\n\nLWS_VISIBLE LWS_EXTERN void\nlejp_construct(struct lejp_ctx *ctx,\n\t       signed char (*callback)(struct lejp_ctx *ctx, char reason),\n\t       void *user, const char * const *paths, unsigned char paths_count);\n\nLWS_VISIBLE LWS_EXTERN void\nlejp_destruct(struct lejp_ctx *ctx);\n\nLWS_VISIBLE LWS_EXTERN int\nlejp_parse(struct lejp_ctx *ctx, const unsigned char *json, int len);\n\nLWS_VISIBLE LWS_EXTERN void\nlejp_change_callback(struct lejp_ctx *ctx,\n\t\t     signed char (*callback)(struct lejp_ctx *ctx, char reason));\n\nLWS_VISIBLE LWS_EXTERN int\nlejp_get_wildcard(struct lejp_ctx *ctx, int wildcard, char *dest, int len);\n//@}\n\n/*\n * Stats are all uint64_t numbers that start at 0.\n * Index names here have the convention\n *\n *  _C_ counter\n *  _B_ byte count\n *  _MS_ millisecond count\n */\n\nenum {\n\tLWSSTATS_C_CONNECTIONS, /**< count incoming connections */\n\tLWSSTATS_C_API_CLOSE, /**< count calls to close api */\n\tLWSSTATS_C_API_READ, /**< count calls to read from socket api */\n\tLWSSTATS_C_API_LWS_WRITE, /**< count calls to lws_write API */\n\tLWSSTATS_C_API_WRITE, /**< count calls to write API */\n\tLWSSTATS_C_WRITE_PARTIALS, /**< count of partial writes */\n\tLWSSTATS_C_WRITEABLE_CB_REQ, /**< count of writable callback requests */\n\tLWSSTATS_C_WRITEABLE_CB_EFF_REQ, /**< count of effective writable callback requests */\n\tLWSSTATS_C_WRITEABLE_CB, /**< count of writable callbacks */\n\tLWSSTATS_C_SSL_CONNECTIONS_FAILED, /**< count of failed SSL connections */\n\tLWSSTATS_C_SSL_CONNECTIONS_ACCEPTED, /**< count of accepted SSL connections */\n\tLWSSTATS_C_SSL_CONNECTIONS_ACCEPT_SPIN, /**< count of SSL_accept() attempts */\n\tLWSSTATS_C_SSL_CONNS_HAD_RX, /**< count of accepted SSL conns that have had some RX */\n\tLWSSTATS_C_TIMEOUTS, /**< count of timed-out connections */\n\tLWSSTATS_C_SERVICE_ENTRY, /**< count of entries to lws service loop */\n\tLWSSTATS_B_READ, /**< aggregate bytes read */\n\tLWSSTATS_B_WRITE, /**< aggregate bytes written */\n\tLWSSTATS_B_PARTIALS_ACCEPTED_PARTS, /**< aggreate of size of accepted write data from new partials */\n\tLWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY, /**< aggregate delay in accepting connection */\n\tLWSSTATS_MS_WRITABLE_DELAY, /**< aggregate delay between asking for writable and getting cb */\n\tLWSSTATS_MS_WORST_WRITABLE_DELAY, /**< single worst delay between asking for writable and getting cb */\n\tLWSSTATS_MS_SSL_RX_DELAY, /**< aggregate delay between ssl accept complete and first RX */\n\tLWSSTATS_C_PEER_LIMIT_AH_DENIED, /**< number of times we would have given an ah but for the peer limit */\n\tLWSSTATS_C_PEER_LIMIT_WSI_DENIED, /**< number of times we would have given a wsi but for the peer limit */\n\n\t/* Add new things just above here ---^\n\t * This is part of the ABI, don't needlessly break compatibility */\n\tLWSSTATS_SIZE\n};\n\n#if defined(LWS_WITH_STATS)\n\nLWS_VISIBLE LWS_EXTERN uint64_t\nlws_stats_get(struct lws_context *context, int index);\nLWS_VISIBLE LWS_EXTERN void\nlws_stats_log_dump(struct lws_context *context);\n#else\nstatic LWS_INLINE uint64_t\nlws_stats_get(struct lws_context *context, int index) { (void)context; (void)index;  return 0; }\nstatic LWS_INLINE void\nlws_stats_log_dump(struct lws_context *context) { (void)context; }\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/lws_config.h",
    "content": "/* lws_config.h  Generated from lws_config.h.in  */\n\n/* GODOT ADDITION */\n#ifndef DEBUG_ENABLED\n#define LWS_WITH_NO_LOGS\n#endif\n/* END GODOT ADDITION */\n\n#ifndef NDEBUG\n\t#ifndef _DEBUG\n\t\t#define _DEBUG\n\t#endif\n#endif\n\n#define LWS_INSTALL_DATADIR \"/usr/local/share\"\n\n#define LWS_ROLE_H1\n#define LWS_ROLE_WS\n#define LWS_ROLE_RAW\n/* #undef LWS_ROLE_H2 */\n/* #undef LWS_ROLE_CGI */\n\n/* Define to 1 to use wolfSSL/CyaSSL as a replacement for OpenSSL.\n * LWS_OPENSSL_SUPPORT needs to be set also for this to work. */\n/* #undef USE_WOLFSSL */\n\n/* Also define to 1 (in addition to USE_WOLFSSL) when using the\n  (older) CyaSSL library */\n/* #undef USE_OLD_CYASSL */\n/* #undef LWS_WITH_BORINGSSL */\n\n#define LWS_WITH_MBEDTLS\n/* #undef LWS_WITH_POLARSSL */\n/* #undef LWS_WITH_ESP32 */\n\n/* #undef LWS_WITH_PLUGINS */\n/* #undef LWS_WITH_NO_LOGS */\n\n/* The Libwebsocket version */\n#define LWS_LIBRARY_VERSION \"3.0.0\"\n\n#define LWS_LIBRARY_VERSION_MAJOR 3\n#define LWS_LIBRARY_VERSION_MINOR 0\n#define LWS_LIBRARY_VERSION_PATCH 0\n/* LWS_LIBRARY_VERSION_NUMBER looks like 1005001 for e.g. version 1.5.1 */\n#define LWS_LIBRARY_VERSION_NUMBER (LWS_LIBRARY_VERSION_MAJOR*1000000)+(LWS_LIBRARY_VERSION_MINOR*1000)+LWS_LIBRARY_VERSION_PATCH\n\n/* The current git commit hash that we're building from */\n#define LWS_BUILD_HASH \"v2.0.0-948-geaa935a8\"\n\n/* Build with OpenSSL support ... alias of LWS_WITH_TLS for compatibility*/\n#define LWS_OPENSSL_SUPPORT\n#define LWS_WITH_TLS\n\n/* The client should load and trust CA root certs it finds in the OS */\n/* #undef LWS_SSL_CLIENT_USE_OS_CA_CERTS */\n\n/* Sets the path where the client certs should be installed. */\n/* #undef LWS_OPENSSL_CLIENT_CERTS \"../share\" */\n\n/* Turn off websocket extensions */\n#define LWS_WITHOUT_EXTENSIONS\n\n/* notice if client or server gone */\n/* #undef LWS_WITHOUT_SERVER */\n/* #undef LWS_WITHOUT_CLIENT */\n\n#define LWS_WITH_POLL\n\n/* Enable libev io loop */\n/* #undef LWS_WITH_LIBEV */\n\n/* Enable libuv io loop */\n/* #undef LWS_WITH_LIBUV */\n\n/* Enable libevent io loop */\n/* #undef LWS_WITH_LIBEVENT */\n\n/* Build with support for ipv6 */\n/* #undef LWS_WITH_IPV6 */\n\n/* Build with support for UNIX domain socket */\n/* #undef LWS_WITH_UNIX_SOCK */\n\n/* Build with support for HTTP2 */\n/* #undef LWS_WITH_HTTP2 */\n\n/* Turn on latency measuring code */\n/* #undef LWS_LATENCY */\n\n/* Don't build the daemonizeation api */\n#define LWS_NO_DAEMONIZE\n\n/* Build without server support */\n/* #undef LWS_NO_SERVER */\n\n/* Build without client support */\n/* #undef LWS_NO_CLIENT */\n\n/* If we should compile with MinGW support */\n/* #undef LWS_MINGW_SUPPORT */\n\n/* Use the BSD getifaddrs that comes with libwebsocket, for uclibc support */\n/* #undef LWS_BUILTIN_GETIFADDRS */\n\n/* use SHA1() not internal libwebsockets_SHA1 */\n/* #undef LWS_SHA1_USE_OPENSSL_NAME */\n\n/* SSL server using ECDH certificate */\n/* #undef LWS_SSL_SERVER_WITH_ECDH_CERT */\n/* #undef LWS_HAVE_SSL_CTX_set1_param */\n#define LWS_HAVE_X509_VERIFY_PARAM_set1_host\n/* #undef LWS_HAVE_RSA_SET0_KEY */\n/* #undef LWS_HAVE_X509_get_key_usage */\n/* #undef LWS_HAVE_SSL_CTX_get0_certificate */\n\n/* #undef LWS_HAVE_UV_VERSION_H */\n/* #undef LWS_HAVE_PTHREAD_H */\n\n/* CGI apis */\n/* #undef LWS_WITH_CGI */\n\n/* whether the Openssl is recent enough, and / or built with, ecdh */\n/* #undef LWS_HAVE_OPENSSL_ECDH_H */\n\n/* HTTP Proxy support */\n/* #undef LWS_WITH_HTTP_PROXY */\n\n/* HTTP Ranges support */\n/* #undef LWS_WITH_RANGES */\n\n/* Http access log support */\n/* #undef LWS_WITH_ACCESS_LOG */\n/* #undef LWS_WITH_SERVER_STATUS */\n\n/* #undef LWS_WITH_STATEFUL_URLDECODE */\n/* #undef LWS_WITH_PEER_LIMITS */\n\n/* Maximum supported service threads */\n#define LWS_MAX_SMP 1\n\n/* Lightweight JSON Parser */\n/* #undef LWS_WITH_LEJP */\n\n/* SMTP */\n/* #undef LWS_WITH_SMTP */\n\n/* OPTEE */\n/* #undef LWS_PLAT_OPTEE */\n\n/* ZIP FOPS */\n/* #undef LWS_WITH_ZIP_FOPS */\n#define LWS_HAVE_STDINT_H\n\n/* #undef LWS_AVOID_SIGPIPE_IGN */\n\n/* #undef LWS_FALLBACK_GETHOSTBYNAME */\n\n/* #undef LWS_WITH_STATS */\n/* #undef LWS_WITH_SOCKS5 */\n\n/* #undef LWS_HAVE_SYS_CAPABILITY_H */\n/* #undef LWS_HAVE_LIBCAP */\n\n#define LWS_HAVE_ATOLL\n/* #undef LWS_HAVE__ATOI64 */\n/* #undef LWS_HAVE__STAT32I64 */\n\n/* #undef LWS_WITH_JWS */\n/* #undef LWS_WITH_ACME */\n/* #undef LWS_WITH_SELFTESTS */\n\n#if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__OpenBSD__)\n#define LWS_HAVE_MALLOC_H\n#endif\n\n#if !defined(__APPLE__) && !defined(__HAIKU__)\n#define LWS_HAVE_PIPE2\n#endif\n\n/* OpenSSL various APIs */\n\n#define LWS_HAVE_TLS_CLIENT_METHOD\n/* #undef LWS_HAVE_TLSV1_2_CLIENT_METHOD */\n/* #undef LWS_HAVE_SSL_SET_INFO_CALLBACK */\n/* #undef LWS_HAVE_SSL_EXTRA_CHAIN_CERTS */\n/* #undef LWS_HAVE_SSL_get0_alpn_selected */\n/* #undef LWS_HAVE_SSL_set_alpn_protos */\n\n#define LWS_HAS_INTPTR_T\n\n\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/lws_config_private.h",
    "content": "/* lws_config_private.h.in. Private compilation options. */\n#ifndef DEBUG_ENABLED\n#ifndef NDEBUG\n#define NDEBUG\n#endif\n#endif\n\n#ifndef NDEBUG\n\t#ifndef _DEBUG\n\t\t#define _DEBUG\n\t#endif\n#endif\n\n/* Define to 1 to use CyaSSL as a replacement for OpenSSL. \n * LWS_OPENSSL_SUPPORT needs to be set also for this to work. */\n/* #undef USE_CYASSL */\n\n/* Define to 1 if you have the `bzero' function. */\n#define LWS_HAVE_BZERO\n/*  Windows has no bzero function */\n#ifdef WINDOWS_ENABLED\n#undef LWS_HAVE_BZERO\n#endif\n\n/* Define to 1 if you have the <dlfcn.h> header file. */\n#define LWS_HAVE_DLFCN_H\n\n/* Define to 1 if you have the <fcntl.h> header file. */\n#define LWS_HAVE_FCNTL_H\n#ifdef NO_FCNTL\n#undef LWS_HAVE_FCNTL_H\n#endif\n\n/* Define to 1 if you have the `fork' function. */\n#define LWS_HAVE_FORK\n\n/* Define to 1 if you have the `getenv’ function. */\n#define LWS_HAVE_GETENV\n\n/* Define to 1 if you have the <in6addr.h> header file. */\n/* #undef LWS_HAVE_IN6ADDR_H */\n\n/* Define to 1 if you have the <inttypes.h> header file. */\n#define LWS_HAVE_INTTYPES_H\n\n/* Define to 1 if you have the `ssl' library (-lssl). */\n/* #undef LWS_HAVE_LIBSSL */\n\n/* Define to 1 if your system has a GNU libc compatible `malloc' function, and\n   to 0 otherwise. */\n#define LWS_HAVE_MALLOC\n\n/* Define to 1 if you have the <memory.h> header file. */\n#define LWS_HAVE_MEMORY_H\n\n/* Define to 1 if you have the `memset' function. */\n#define LWS_HAVE_MEMSET\n\n/* Define to 1 if you have the <netinet/in.h> header file. */\n#define LWS_HAVE_NETINET_IN_H\n\n/* Define to 1 if your system has a GNU libc compatible `realloc' function,\n   and to 0 otherwise. */\n#define LWS_HAVE_REALLOC\n\n/* Define to 1 if you have the `socket' function. */\n#define LWS_HAVE_SOCKET\n\n/* Define to 1 if you have the <stdint.h> header file. */\n#define LWS_HAVE_STDINT_H\n\n/* Define to 1 if you have the <stdlib.h> header file. */\n#define LWS_HAVE_STDLIB_H\n\n/* Define to 1 if you have the `strerror' function. */\n#define LWS_HAVE_STRERROR\n\n/* Define to 1 if you have the <strings.h> header file. */\n#define LWS_HAVE_STRINGS_H\n\n/* Define to 1 if you have the <string.h> header file. */\n#define LWS_HAVE_STRING_H\n\n/* Define to 1 if you have the <sys/prctl.h> header file. */\n#define LWS_HAVE_SYS_PRCTL_H\n#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__HAIKU__)\n#undef LWS_HAVE_SYS_PRCTL_H\n#endif\n\n/* Define to 1 if you have the <sys/socket.h> header file. */\n#define LWS_HAVE_SYS_SOCKET_H\n\n/* Define to 1 if you have the <sys/sockio.h> header file. */\n/* #undef LWS_HAVE_SYS_SOCKIO_H */\n\n/* Define to 1 if you have the <sys/stat.h> header file. */\n#define LWS_HAVE_SYS_STAT_H\n\n/* Define to 1 if you have the <sys/types.h> header file. */\n#define LWS_HAVE_SYS_TYPES_H\n\n/* Define to 1 if you have the <unistd.h> header file. */\n#define LWS_HAVE_UNISTD_H\n\n#define LWS_HAVE_TCP_USER_TIMEOUT\n\n/* Define to 1 if you have the `vfork' function. */\n#define LWS_HAVE_VFORK\n\n/* Define to 1 if you have the <vfork.h> header file. */\n/* #undef LWS_HAVE_VFORK_H */\n\n/* Define to 1 if `fork' works. */\n#define LWS_HAVE_WORKING_FORK\n\n/* Define to 1 if `vfork' works. */\n#define LWS_HAVE_WORKING_VFORK\n\n/* Define to 1 if execvpe() exists */\n#define LWS_HAVE_EXECVPE\n\n/* Define to 1 if you have the <zlib.h> header file. */\n#define LWS_HAVE_ZLIB_H\n\n#define LWS_HAVE_GETLOADAVG\n\n/* Define to the sub-directory in which libtool stores uninstalled libraries.\n   */\n#undef LT_OBJDIR // We're not using libtool\n\n/* Define to rpl_malloc if the replacement function should be used. */\n/* #undef malloc */\n\n/* Define to rpl_realloc if the replacement function should be used. */\n/* #undef realloc */\n\n/* Define to 1 if we have getifaddrs */\n#define LWS_HAVE_GETIFADDRS\n#if defined(ANDROID_ENABLED)\n#undef LWS_HAVE_GETIFADDRS\n#define LWS_BUILTIN_GETIFADDRS\n#endif\n\n/* Define if the inline keyword doesn't exist. */\n/* #undef inline */\n\n\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/misc/base64-decode.c",
    "content": "/*\n * This code originally came from here\n *\n * http://base64.sourceforge.net/b64.c\n *\n * with the following license:\n *\n * LICENCE:        Copyright (c) 2001 Bob Trower, Trantor Standard Systems Inc.\n *\n *                Permission is hereby granted, free of charge, to any person\n *                obtaining a copy of this software and associated\n *                documentation files (the \"Software\"), to deal in the\n *                Software without restriction, including without limitation\n *                the rights to use, copy, modify, merge, publish, distribute,\n *                sublicense, and/or sell copies of the Software, and to\n *                permit persons to whom the Software is furnished to do so,\n *                subject to the following conditions:\n *\n *                The above copyright notice and this permission notice shall\n *                be included in all copies or substantial portions of the\n *                Software.\n *\n *                THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n *                KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n *                WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n *                PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n *                OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n *                OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n *                OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n *                SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n * VERSION HISTORY:\n *               Bob Trower 08/04/01 -- Create Version 0.00.00B\n *\n * I cleaned it up quite a bit to match the (linux kernel) style of the rest\n * of libwebsockets; this version is under LGPL2.1 + SLE like the rest of lws\n * since he explicitly allows sublicensing, but I give the URL above so you can\n * get the original with Bob's super-liberal terms directly if you prefer.\n */\n\n#include <stdio.h>\n#include <string.h>\n#include \"core/private.h\"\n\nstatic const char encode_orig[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\t\t\t     \"abcdefghijklmnopqrstuvwxyz0123456789+/\";\nstatic const char encode_url[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\t\t\t     \"abcdefghijklmnopqrstuvwxyz0123456789-_\";\nstatic const char decode[] = \"|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW\"\n\t\t\t     \"$$$$$$XYZ[\\\\]^_`abcdefghijklmnopq\";\n\nstatic int\n_lws_b64_encode_string(const char *encode, const char *in, int in_len,\n\t\t       char *out, int out_size)\n{\n\tunsigned char triple[3];\n\tint i;\n\tint len;\n\tint line = 0;\n\tint done = 0;\n\n\twhile (in_len) {\n\t\tlen = 0;\n\t\tfor (i = 0; i < 3; i++) {\n\t\t\tif (in_len) {\n\t\t\t\ttriple[i] = *in++;\n\t\t\t\tlen++;\n\t\t\t\tin_len--;\n\t\t\t} else\n\t\t\t\ttriple[i] = 0;\n\t\t}\n\n\t\tif (done + 4 >= out_size)\n\t\t\treturn -1;\n\n\t\t*out++ = encode[triple[0] >> 2];\n\t\t*out++ = encode[((triple[0] & 0x03) << 4) |\n\t\t\t\t\t     ((triple[1] & 0xf0) >> 4)];\n\t\t*out++ = (len > 1 ? encode[((triple[1] & 0x0f) << 2) |\n\t\t\t\t\t     ((triple[2] & 0xc0) >> 6)] : '=');\n\t\t*out++ = (len > 2 ? encode[triple[2] & 0x3f] : '=');\n\n\t\tdone += 4;\n\t\tline += 4;\n\t}\n\n\tif (done + 1 >= out_size)\n\t\treturn -1;\n\n\t*out++ = '\\0';\n\n\treturn done;\n}\n\nLWS_VISIBLE int\nlws_b64_encode_string(const char *in, int in_len, char *out, int out_size)\n{\n\treturn _lws_b64_encode_string(encode_orig, in, in_len, out, out_size);\n}\n\nLWS_VISIBLE int\nlws_b64_encode_string_url(const char *in, int in_len, char *out, int out_size)\n{\n\treturn _lws_b64_encode_string(encode_url, in, in_len, out, out_size);\n}\n\n/*\n * returns length of decoded string in out, or -1 if out was too small\n * according to out_size\n *\n * Only reads up to in_len chars, otherwise if in_len is -1 on entry reads until\n * the first NUL in the input.\n */\n\nstatic int\n_lws_b64_decode_string(const char *in, int in_len, char *out, int out_size)\n{\n\tint len, i, c = 0, done = 0;\n\tunsigned char v, quad[4];\n\n\twhile (in_len && *in) {\n\n\t\tlen = 0;\n\t\tfor (i = 0; i < 4 && in_len && *in; i++) {\n\n\t\t\tv = 0;\n\t\t\tc = 0;\n\t\t\twhile (in_len && *in  && !v) {\n\t\t\t\tc = v = *in++;\n\t\t\t\tin_len--;\n\t\t\t\t/* support the url base64 variant too */\n\t\t\t\tif (v == '-')\n\t\t\t\t\tc = v = '+';\n\t\t\t\tif (v == '_')\n\t\t\t\t\tc = v = '/';\n\t\t\t\tv = (v < 43 || v > 122) ? 0 : decode[v - 43];\n\t\t\t\tif (v)\n\t\t\t\t\tv = (v == '$') ? 0 : v - 61;\n\t\t\t}\n\t\t\tif (c) {\n\t\t\t\tlen++;\n\t\t\t\tif (v)\n\t\t\t\t\tquad[i] = v - 1;\n\t\t\t} else\n\t\t\t\tquad[i] = 0;\n\t\t}\n\n\t\tif (out_size < (done + len - 1))\n\t\t\t/* out buffer is too small */\n\t\t\treturn -1;\n\n\t\t/*\n\t\t * \"The '==' sequence indicates that the last group contained\n\t\t * only one byte, and '=' indicates that it contained two\n\t\t * bytes.\" (wikipedia)\n\t\t */\n\n\t\tif ((!in_len || !*in) && c == '=')\n\t\t\tlen--;\n\n\t\tif (len >= 2)\n\t\t\t*out++ = quad[0] << 2 | quad[1] >> 4;\n\t\tif (len >= 3)\n\t\t\t*out++ = quad[1] << 4 | quad[2] >> 2;\n\t\tif (len >= 4)\n\t\t\t*out++ = ((quad[2] << 6) & 0xc0) | quad[3];\n\n\t\tdone += len - 1;\n\t}\n\n\tif (done + 1 >= out_size)\n\t\treturn -1;\n\n\t*out = '\\0';\n\n\treturn done;\n}\n\nLWS_VISIBLE int\nlws_b64_decode_string(const char *in, char *out, int out_size)\n{\n\treturn _lws_b64_decode_string(in, -1, out, out_size);\n}\n\nLWS_VISIBLE int\nlws_b64_decode_string_len(const char *in, int in_len, char *out, int out_size)\n{\n\treturn _lws_b64_decode_string(in, in_len, out, out_size);\n}\n\n#if 0\nint\nlws_b64_selftest(void)\n{\n\tchar buf[64];\n\tunsigned int n,  r = 0;\n\tunsigned int test;\n\t/* examples from https://en.wikipedia.org/wiki/Base64 */\n\tstatic const char * const plaintext[] = {\n\t\t\"any carnal pleasure.\",\n\t\t\"any carnal pleasure\",\n\t\t\"any carnal pleasur\",\n\t\t\"any carnal pleasu\",\n\t\t\"any carnal pleas\",\n\t\t\"Admin:kloikloi\"\n\t};\n\tstatic const char * const coded[] = {\n\t\t\"YW55IGNhcm5hbCBwbGVhc3VyZS4=\",\n\t\t\"YW55IGNhcm5hbCBwbGVhc3VyZQ==\",\n\t\t\"YW55IGNhcm5hbCBwbGVhc3Vy\",\n\t\t\"YW55IGNhcm5hbCBwbGVhc3U=\",\n\t\t\"YW55IGNhcm5hbCBwbGVhcw==\",\n\t\t\"QWRtaW46a2xvaWtsb2k=\"\n\t};\n\n\tfor (test = 0; test < sizeof plaintext / sizeof(plaintext[0]); test++) {\n\n\t\tbuf[sizeof(buf) - 1] = '\\0';\n\t\tn = lws_b64_encode_string(plaintext[test],\n\t\t\t\t      strlen(plaintext[test]), buf, sizeof buf);\n\t\tif (n != strlen(coded[test]) || strcmp(buf, coded[test])) {\n\t\t\tlwsl_err(\"Failed lws_b64 encode selftest \"\n\t\t\t\t\t   \"%d result '%s' %d\\n\", test, buf, n);\n\t\t\tr = -1;\n\t\t}\n\n\t\tbuf[sizeof(buf) - 1] = '\\0';\n\t\tn = lws_b64_decode_string(coded[test], buf, sizeof buf);\n\t\tif (n != strlen(plaintext[test]) ||\n\t\t\t\t\t\t strcmp(buf, plaintext[test])) {\n\t\t\tlwsl_err(\"Failed lws_b64 decode selftest \"\n\t\t\t\t \"%d result '%s' / '%s', %d / %d\\n\",\n\t\t\t\t test, buf, plaintext[test], n, strlen(plaintext[test]));\n\t\t\tr = -1;\n\t\t}\n\t}\n\n\tlwsl_notice(\"Base 64 selftests passed\\n\");\n\n\treturn r;\n}\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/misc/getifaddrs.c",
    "content": "/*\n * Copyright (c) 2000 - 2001 Kungliga Tekniska H�gskolan\n * (Royal Institute of Technology, Stockholm, Sweden).\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * 3. Neither the name of the Institute nor the names of its contributors\n *    may be used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * originally downloaded from\n *\n * http://ftp.uninett.no/pub/OpenBSD/src/kerberosV/src/lib/roken/getifaddrs.c\n */\n\n#include <errno.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <net/if.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/ioctl.h>\n#include <unistd.h>\n#include \"core/private.h\"\n\n#ifdef LWS_HAVE_SYS_SOCKIO_H\n#include <sys/sockio.h>\n#endif\n\n#ifdef LWS_HAVE_NETINET_IN6_VAR_H\n#include <netinet/in6_var.h>\n#endif\n\n#ifndef max\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#endif\n\n#include \"getifaddrs.h\"\n\nstatic int\ngetifaddrs2(struct ifaddrs **ifap, int af, int siocgifconf, int siocgifflags,\n\t    size_t ifreq_sz)\n{\n\tint ret;\n\tint fd;\n\tsize_t buf_size;\n\tchar *buf;\n\tstruct ifconf ifconf;\n\tchar *p;\n\tsize_t sz;\n\tstruct sockaddr sa_zero;\n\tstruct ifreq *ifr;\n\tstruct ifaddrs *start,  **end = &start;\n\n\tbuf = NULL;\n\n\tmemset(&sa_zero, 0, sizeof(sa_zero));\n\tfd = socket(af, SOCK_DGRAM, 0);\n\tif (fd < 0)\n\t\treturn -1;\n\n\tbuf_size = 8192;\n\tfor (;;) {\n\t\tbuf = lws_zalloc(buf_size, \"getifaddrs2\");\n\t\tif (buf == NULL) {\n\t\t\tret = ENOMEM;\n\t\t\tgoto error_out;\n\t\t}\n\t\tifconf.ifc_len = buf_size;\n\t\tifconf.ifc_buf = buf;\n\n\t\t/*\n\t\t * Solaris returns EINVAL when the buffer is too small.\n\t\t */\n\t\tif (ioctl(fd, siocgifconf, &ifconf) < 0 && errno != EINVAL) {\n\t\t\tret = errno;\n\t\t\tgoto error_out;\n\t\t}\n\t\t/*\n\t\t * Can the difference between a full and a overfull buf\n\t\t * be determined?\n\t\t */\n\n\t\tif (ifconf.ifc_len < (int)buf_size)\n\t\t\tbreak;\n\t\tlws_free(buf);\n\t\tbuf_size *= 2;\n\t}\n\n\tfor (p = ifconf.ifc_buf; p < ifconf.ifc_buf + ifconf.ifc_len; p += sz) {\n\t\tstruct ifreq ifreq;\n\t\tstruct sockaddr *sa;\n\t\tsize_t salen;\n\n\t\tifr = (struct ifreq *)p;\n\t\tsa  = &ifr->ifr_addr;\n\n\t\tsz = ifreq_sz;\n\t\tsalen = sizeof(struct sockaddr);\n#ifdef LWS_HAVE_STRUCT_SOCKADDR_SA_LEN\n\t\tsalen = sa->sa_len;\n\t\tsz = max(sz, sizeof(ifr->ifr_name) + sa->sa_len);\n#endif\n#ifdef SA_LEN\n\t\tsalen = SA_LEN(sa);\n\t\tsz = max(sz, sizeof(ifr->ifr_name) + SA_LEN(sa));\n#endif\n\t\tmemset(&ifreq, 0, sizeof(ifreq));\n\t\tmemcpy(ifreq.ifr_name, ifr->ifr_name, sizeof(ifr->ifr_name));\n\n\t\tif (ioctl(fd, siocgifflags, &ifreq) < 0) {\n\t\t\tret = errno;\n\t\t\tgoto error_out;\n\t\t}\n\n\t\t*end = lws_malloc(sizeof(**end), \"getifaddrs\");\n\n\t\t(*end)->ifa_next = NULL;\n\t\t(*end)->ifa_name = strdup(ifr->ifr_name);\n\t\t(*end)->ifa_flags = ifreq.ifr_flags;\n\t\t(*end)->ifa_addr = lws_malloc(salen, \"getifaddrs\");\n\t\tmemcpy((*end)->ifa_addr, sa, salen);\n\t\t(*end)->ifa_netmask = NULL;\n\n#if 0\n\t\t/* fix these when we actually need them */\n\t\tif (ifreq.ifr_flags & IFF_BROADCAST) {\n\t\t\t(*end)->ifa_broadaddr =\n\t\t\t\tlws_malloc(sizeof(ifr->ifr_broadaddr), \"getifaddrs\");\n\t\t\tmemcpy((*end)->ifa_broadaddr, &ifr->ifr_broadaddr,\n\t\t\t\t\t\t    sizeof(ifr->ifr_broadaddr));\n\t\t} else if (ifreq.ifr_flags & IFF_POINTOPOINT) {\n\t\t\t(*end)->ifa_dstaddr =\n\t\t\t\tlws_malloc(sizeof(ifr->ifr_dstaddr), \"getifaddrs\");\n\t\t\tmemcpy((*end)->ifa_dstaddr, &ifr->ifr_dstaddr,\n\t\t\t\t\t\t      sizeof(ifr->ifr_dstaddr));\n\t\t} else\n\t\t\t(*end)->ifa_dstaddr = NULL;\n#else\n\t\t(*end)->ifa_dstaddr = NULL;\n#endif\n\t\t(*end)->ifa_data = NULL;\n\n\t\tend = &(*end)->ifa_next;\n\n\t}\n\t*ifap = start;\n\tclose(fd);\n\tlws_free(buf);\n\treturn 0;\n\nerror_out:\n\tclose(fd);\n\tlws_free(buf);\n\terrno = ret;\n\n\treturn -1;\n}\n\nint\ngetifaddrs(struct ifaddrs **ifap)\n{\n\tint ret = -1;\n\terrno = ENXIO;\n#if defined(AF_INET6) && defined(SIOCGIF6CONF) && defined(SIOCGIF6FLAGS)\n\tif (ret)\n\t\tret = getifaddrs2(ifap, AF_INET6, SIOCGIF6CONF, SIOCGIF6FLAGS,\n\t\t\t   sizeof(struct in6_ifreq));\n#endif\n#if defined(LWS_HAVE_IPV6) && defined(SIOCGIFCONF)\n\tif (ret)\n\t\tret = getifaddrs2(ifap, AF_INET6, SIOCGIFCONF, SIOCGIFFLAGS,\n\t\t\t   sizeof(struct ifreq));\n#endif\n#if defined(AF_INET) && defined(SIOCGIFCONF) && defined(SIOCGIFFLAGS)\n\tif (ret)\n\t\tret = getifaddrs2(ifap, AF_INET, SIOCGIFCONF, SIOCGIFFLAGS,\n\t\t\t   sizeof(struct ifreq));\n#endif\n\treturn ret;\n}\n\nvoid\nfreeifaddrs(struct ifaddrs *ifp)\n{\n\tstruct ifaddrs *p, *q;\n\n\tfor (p = ifp; p; ) {\n\t\tlws_free(p->ifa_name);\n\t\tlws_free(p->ifa_addr);\n\t\tlws_free(p->ifa_dstaddr);\n\t\tlws_free(p->ifa_netmask);\n\t\tlws_free(p->ifa_data);\n\t\tq = p;\n\t\tp = p->ifa_next;\n\t\tlws_free(q);\n\t}\n}\n\n#ifdef TEST\n\nvoid\nprint_addr(const char *s, struct sockaddr *sa)\n{\n\tint i;\n\tprintf(\"  %s=%d/\", s, sa->sa_family);\n#ifdef LWS_HAVE_STRUCT_SOCKADDR_SA_LEN\n\tfor (i = 0;\n\t       i < sa->sa_len - ((lws_intptr_t)sa->sa_data - (lws_intptr_t)&sa->sa_family); i++)\n\t\tprintf(\"%02x\", ((unsigned char *)sa->sa_data)[i]);\n#else\n\tfor (i = 0; i < sizeof(sa->sa_data); i++)\n\t\tprintf(\"%02x\", ((unsigned char *)sa->sa_data)[i]);\n#endif\n\tprintf(\"\\n\");\n}\n\nvoid\nprint_ifaddrs(struct ifaddrs *x)\n{\n\tstruct ifaddrs *p;\n\n\tfor (p = x; p; p = p->ifa_next) {\n\t\tprintf(\"%s\\n\", p->ifa_name);\n\t\tprintf(\"  flags=%x\\n\", p->ifa_flags);\n\t\tif (p->ifa_addr)\n\t\t\tprint_addr(\"addr\", p->ifa_addr);\n\t\tif (p->ifa_dstaddr)\n\t\t\tprint_addr(\"dstaddr\", p->ifa_dstaddr);\n\t\tif (p->ifa_netmask)\n\t\t\tprint_addr(\"netmask\", p->ifa_netmask);\n\t\tprintf(\"  %p\\n\", p->ifa_data);\n\t}\n}\n\nint\nmain()\n{\n\tstruct ifaddrs *a = NULL, *b;\n\tgetifaddrs2(&a, AF_INET, SIOCGIFCONF, SIOCGIFFLAGS,\n\t\t    sizeof(struct ifreq));\n\tprint_ifaddrs(a);\n\tprintf(\"---\\n\");\n\tgetifaddrs(&b);\n\tprint_ifaddrs(b);\n\treturn 0;\n}\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/misc/getifaddrs.h",
    "content": "#ifndef LWS_HAVE_GETIFADDRS\n#define LWS_HAVE_GETIFADDRS 0\n#endif\n\n#ifdef LWS_HAVE_GETIFADDRS\n#include <sys/types.h>\n#include <ifaddrs.h>\n#else\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n/*\n * Copyright (c) 2000 Kungliga Tekniska H�gskolan\n * (Royal Institute of Technology, Stockholm, Sweden).\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * 3. Neither the name of the Institute nor the names of its contributors\n *    may be used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n */\n\n/* $KTH: ifaddrs.hin,v 1.3 2000/12/11 00:01:13 assar Exp $ */\n\n#ifndef ifaddrs_h_7467027A95AD4B5C8DDD40FE7D973791\n#define ifaddrs_h_7467027A95AD4B5C8DDD40FE7D973791\n\n/*\n * the interface is defined in terms of the fields below, and this is\n * sometimes #define'd, so there seems to be no simple way of solving\n * this and this seemed the best. */\n\n#undef ifa_dstaddr\n\nstruct ifaddrs {\n\tstruct ifaddrs *ifa_next;\n\tchar *ifa_name;\n\tunsigned int ifa_flags;\n\tstruct sockaddr *ifa_addr;\n\tstruct sockaddr *ifa_netmask;\n\tstruct sockaddr *ifa_dstaddr;\n\tvoid *ifa_data;\n};\n\n#ifndef ifa_broadaddr\n#define ifa_broadaddr ifa_dstaddr\n#endif\n\nint getifaddrs(struct ifaddrs **);\n\nvoid freeifaddrs(struct ifaddrs *);\n\n#endif /* __ifaddrs_h__ */\n\n#ifdef __cplusplus\n}\n#endif\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/misc/lejp.c",
    "content": "/*\n * Lightweight Embedded JSON Parser\n *\n * Copyright (C) 2013-2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include <libwebsockets.h>\n#include \"core/private.h\"\n#include <string.h>\n#include <stdio.h>\n\n/**\n * lejp_construct - prepare a struct lejp_ctx for use\n *\n * \\param ctx:\tpointer to your struct lejp_ctx\n * \\param callback:\tyour user callback which will received parsed tokens\n * \\param user:\toptional user data pointer untouched by lejp\n * \\param paths:\tyour array of name elements you are interested in\n * \\param count_paths:\tLWS_ARRAY_SIZE() of @paths\n *\n * Prepares your context struct for use with lejp\n */\n\nvoid\nlejp_construct(struct lejp_ctx *ctx,\n\tsigned char (*callback)(struct lejp_ctx *ctx, char reason), void *user,\n\t\t\tconst char * const *paths, unsigned char count_paths)\n{\n\tctx->st[0].s = 0;\n\tctx->st[0].p = 0;\n\tctx->st[0].i = 0;\n\tctx->st[0].b = 0;\n\tctx->sp = 0;\n\tctx->ipos = 0;\n\tctx->ppos = 0;\n\tctx->path_match = 0;\n\tctx->path[0] = '\\0';\n\tctx->callback = callback;\n\tctx->user = user;\n\tctx->paths = paths;\n\tctx->count_paths = count_paths;\n\tctx->line = 1;\n\tctx->callback(ctx, LEJPCB_CONSTRUCTED);\n}\n\n/**\n * lejp_destruct - retire a previously constructed struct lejp_ctx\n *\n * \\param ctx:\tpointer to your struct lejp_ctx\n *\n * lejp does not perform any allocations, but since your user code might, this\n * provides a one-time LEJPCB_DESTRUCTED callback at destruction time where\n * you can clean up in your callback.\n */\n\nvoid\nlejp_destruct(struct lejp_ctx *ctx)\n{\n\t/* no allocations... just let callback know what it happening */\n\tctx->callback(ctx, LEJPCB_DESTRUCTED);\n}\n\n/**\n * lejp_change_callback - switch to a different callback from now on\n *\n * \\param ctx:\tpointer to your struct lejp_ctx\n * \\param callback:\tyour user callback which will received parsed tokens\n *\n * This tells the old callback it was destroyed, in case you want to take any\n * action because that callback \"lost focus\", then changes to the new\n * callback and tells it first that it was constructed, and then started.\n *\n * Changing callback is a cheap and powerful trick to split out handlers\n * according to information earlier in the parse.  For example you may have\n * a JSON pair \"schema\" whose value defines what can be expected for the rest\n * of the JSON.  Rather than having one huge callback for all cases, you can\n * have an initial one looking for \"schema\" which then calls\n * lejp_change_callback() to a handler specific for the schema.\n *\n * Notice that afterwards, you need to construct the context again anyway to\n * parse another JSON object, and the callback is reset then to the main,\n * schema-interpreting one.  The construction action is very lightweight.\n */\n\nvoid\nlejp_change_callback(struct lejp_ctx *ctx,\n\t\t     signed char (*callback)(struct lejp_ctx *ctx, char reason))\n{\n\tctx->callback(ctx, LEJPCB_DESTRUCTED);\n\tctx->callback = callback;\n\tctx->callback(ctx, LEJPCB_CONSTRUCTED);\n\tctx->callback(ctx, LEJPCB_START);\n}\n\nstatic void\nlejp_check_path_match(struct lejp_ctx *ctx)\n{\n\tconst char *p, *q;\n\tint n;\n\n\t/* we only need to check if a match is not active */\n\tfor (n = 0; !ctx->path_match && n < ctx->count_paths; n++) {\n\t\tctx->wildcount = 0;\n\t\tp = ctx->path;\n\t\tq = ctx->paths[n];\n\t\twhile (*p && *q) {\n\t\t\tif (*q != '*') {\n\t\t\t\tif (*p != *q)\n\t\t\t\t\tbreak;\n\t\t\t\tp++;\n\t\t\t\tq++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tctx->wild[ctx->wildcount++] = p - ctx->path;\n\t\t\tq++;\n\t\t\t/*\n\t\t\t * if * has something after it, match to .\n\t\t\t * if ends with *, eat everything.\n\t\t\t * This implies match sequences must be ordered like\n\t\t\t *  x.*.*\n\t\t\t *  x.*\n\t\t\t * if both options are possible\n\t\t\t */\n\t\t\twhile (*p && (*p != '.' || !*q))\n\t\t\t\tp++;\n\t\t}\n\t\tif (*p || *q)\n\t\t\tcontinue;\n\n\t\tctx->path_match = n + 1;\n\t\tctx->path_match_len = ctx->ppos;\n\t\treturn;\n\t}\n\n\tif (!ctx->path_match)\n\t\tctx->wildcount = 0;\n}\n\nint\nlejp_get_wildcard(struct lejp_ctx *ctx, int wildcard, char *dest, int len)\n{\n\tint n;\n\n\tif (wildcard >= ctx->wildcount || !len)\n\t\treturn 0;\n\n\tn = ctx->wild[wildcard];\n\n\twhile (--len && n < ctx->ppos &&\n\t       (n == ctx->wild[wildcard] || ctx->path[n] != '.'))\n\t\t*dest++ = ctx->path[n++];\n\n\t*dest = '\\0';\n\tn++;\n\n\treturn n - ctx->wild[wildcard];\n}\n\n/**\n * lejp_parse - interpret some more incoming data incrementally\n *\n * \\param ctx:\tpreviously constructed parsing context\n * \\param json:\tchar buffer with the new data to interpret\n * \\param len:\tamount of data in the buffer\n *\n * Because lejp is a stream parser, it incrementally parses as new data\n * becomes available, maintaining all state in the context struct.  So an\n * incomplete JSON is a normal situation, getting you a LEJP_CONTINUE\n * return, signalling there's no error but to call again with more data when\n * it comes to complete the parsing.  Successful parsing completes with a\n * 0 or positive integer indicating how much of the last input buffer was\n * unused.\n */\n\nint\nlejp_parse(struct lejp_ctx *ctx, const unsigned char *json, int len)\n{\n\tunsigned char c, n, s, ret = LEJP_REJECT_UNKNOWN;\n\tstatic const char esc_char[] = \"\\\"\\\\/bfnrt\";\n\tstatic const char esc_tran[] = \"\\\"\\\\/\\b\\f\\n\\r\\t\";\n\tstatic const char tokens[] = \"rue alse ull \";\n\n\tif (!ctx->sp && !ctx->ppos)\n\t\tctx->callback(ctx, LEJPCB_START);\n\n\twhile (len--) {\n\t\tc = *json++;\n\t\ts = ctx->st[ctx->sp].s;\n\n\t\t/* skip whitespace unless we should care */\n\t\tif (c == ' ' || c == '\\t' || c == '\\n' || c == '\\r' || c == '#') {\n\t\t\tif (c == '\\n') {\n\t\t\t\tctx->line++;\n\t\t\t\tctx->st[ctx->sp].s &= ~LEJP_FLAG_WS_COMMENTLINE;\n\t\t\t}\n\t\t\tif (!(s & LEJP_FLAG_WS_KEEP)) {\n\t\t\t\tif (c == '#')\n\t\t\t\t\tctx->st[ctx->sp].s |=\n\t\t\t\t\t\tLEJP_FLAG_WS_COMMENTLINE;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (ctx->st[ctx->sp].s & LEJP_FLAG_WS_COMMENTLINE)\n\t\t\tcontinue;\n\n\t\tswitch (s) {\n\t\tcase LEJP_IDLE:\n\t\t\tif (c != '{') {\n\t\t\t\tret = LEJP_REJECT_IDLE_NO_BRACE;\n\t\t\t\tgoto reject;\n\t\t\t}\n\t\t\tif (ctx->callback(ctx, LEJPCB_OBJECT_START)) {\n\t\t\t\tret = LEJP_REJECT_CALLBACK;\n\t\t\t\tgoto reject;\n\t\t\t}\n\t\t\tctx->st[ctx->sp].s = LEJP_MEMBERS;\n\t\t\tbreak;\n\t\tcase LEJP_MEMBERS:\n\t\t\tif (c == '}') {\n\t\t\t\tctx->st[ctx->sp].s = LEJP_IDLE;\n\t\t\t\tret = LEJP_REJECT_MEMBERS_NO_CLOSE;\n\t\t\t\tgoto reject;\n\t\t\t}\n\t\t\tctx->st[ctx->sp].s = LEJP_M_P;\n\t\t\tgoto redo_character;\n\t\tcase LEJP_M_P:\n\t\t\tif (c != '\\\"') {\n\t\t\t\tret = LEJP_REJECT_MP_NO_OPEN_QUOTE;\n\t\t\t\tgoto reject;\n\t\t\t}\n\t\t\t/* push */\n\t\t\tctx->st[ctx->sp].s = LEJP_MP_DELIM;\n\t\t\tc = LEJP_MP_STRING;\n\t\t\tgoto add_stack_level;\n\n\t\tcase LEJP_MP_STRING:\n\t\t\tif (c == '\\\"') {\n\t\t\t\tif (!ctx->sp) { /* JSON can't end on quote */\n\t\t\t\t\tret = LEJP_REJECT_MP_STRING_UNDERRUN;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t\tif (ctx->st[ctx->sp - 1].s != LEJP_MP_DELIM) {\n\t\t\t\t\tctx->buf[ctx->npos] = '\\0';\n\t\t\t\t\tif (ctx->callback(ctx,\n\t\t\t\t\t\t      LEJPCB_VAL_STR_END) < 0) {\n\t\t\t\t\t\tret = LEJP_REJECT_CALLBACK;\n\t\t\t\t\t\tgoto reject;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/* pop */\n\t\t\t\tctx->sp--;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (c == '\\\\') {\n\t\t\t\tctx->st[ctx->sp].s = LEJP_MP_STRING_ESC;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (c < ' ') {/* \"control characters\" not allowed */\n\t\t\t\tret = LEJP_REJECT_MP_ILLEGAL_CTRL;\n\t\t\t\tgoto reject;\n\t\t\t}\n\t\t\tgoto emit_string_char;\n\n\t\tcase LEJP_MP_STRING_ESC:\n\t\t\tif (c == 'u') {\n\t\t\t\tctx->st[ctx->sp].s = LEJP_MP_STRING_ESC_U1;\n\t\t\t\tctx->uni = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfor (n = 0; n < sizeof(esc_char); n++) {\n\t\t\t\tif (c != esc_char[n])\n\t\t\t\t\tcontinue;\n\t\t\t\t/* found it */\n\t\t\t\tc = esc_tran[n];\n\t\t\t\tctx->st[ctx->sp].s = LEJP_MP_STRING;\n\t\t\t\tgoto emit_string_char;\n\t\t\t}\n\t\t\tret = LEJP_REJECT_MP_STRING_ESC_ILLEGAL_ESC;\n\t\t\t/* illegal escape char */\n\t\t\tgoto reject;\n\n\t\tcase LEJP_MP_STRING_ESC_U1:\n\t\tcase LEJP_MP_STRING_ESC_U2:\n\t\tcase LEJP_MP_STRING_ESC_U3:\n\t\tcase LEJP_MP_STRING_ESC_U4:\n\t\t\tctx->uni <<= 4;\n\t\t\tif (c >= '0' && c <= '9')\n\t\t\t\tctx->uni |= c - '0';\n\t\t\telse\n\t\t\t\tif (c >= 'a' && c <= 'f')\n\t\t\t\t\tctx->uni = c - 'a' + 10;\n\t\t\t\telse\n\t\t\t\t\tif (c >= 'A' && c <= 'F')\n\t\t\t\t\t\tctx->uni = c - 'A' + 10;\n\t\t\t\t\telse {\n\t\t\t\t\t\tret = LEJP_REJECT_ILLEGAL_HEX;\n\t\t\t\t\t\tgoto reject;\n\t\t\t\t\t}\n\t\t\tctx->st[ctx->sp].s++;\n\t\t\tswitch (s) {\n\t\t\tcase LEJP_MP_STRING_ESC_U2:\n\t\t\t\tif (ctx->uni < 0x08)\n\t\t\t\t\tbreak;\n\t\t\t\t/*\n\t\t\t\t * 0x08-0xff (0x0800 - 0xffff)\n\t\t\t\t * emit 3-byte UTF-8\n\t\t\t\t */\n\t\t\t\tc = 0xe0 | ((ctx->uni >> 4) & 0xf);\n\t\t\t\tgoto emit_string_char;\n\n\t\t\tcase LEJP_MP_STRING_ESC_U3:\n\t\t\t\tif (ctx->uni >= 0x080) {\n\t\t\t\t\t/*\n\t\t\t\t\t * 0x080 - 0xfff (0x0800 - 0xffff)\n\t\t\t\t\t * middle 3-byte seq\n\t\t\t\t\t * send ....XXXXXX..\n\t\t\t\t\t */\n\t\t\t\t\tc = 0x80 | ((ctx->uni >> 2) & 0x3f);\n\t\t\t\t\tgoto emit_string_char;\n\t\t\t\t}\n\t\t\t\tif (ctx->uni < 0x008)\n\t\t\t\t\tbreak;\n\t\t\t\t/*\n\t\t\t\t * 0x008 - 0x7f (0x0080 - 0x07ff)\n\t\t\t\t * start 2-byte seq\n\t\t\t\t */\n\t\t\t\tc = 0xc0 | (ctx->uni >> 2);\n\t\t\t\tgoto emit_string_char;\n\n\t\t\tcase LEJP_MP_STRING_ESC_U4:\n\t\t\t\tif (ctx->uni >= 0x0080)\n\t\t\t\t\t/* end of 2 or 3-byte seq */\n\t\t\t\t\tc = 0x80 | (ctx->uni & 0x3f);\n\t\t\t\telse\n\t\t\t\t\t/* literal */\n\t\t\t\t\tc = (unsigned char)ctx->uni;\n\n\t\t\t\tctx->st[ctx->sp].s = LEJP_MP_STRING;\n\t\t\t\tgoto emit_string_char;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase LEJP_MP_DELIM:\n\t\t\tif (c != ':') {\n\t\t\t\tret = LEJP_REJECT_MP_DELIM_MISSING_COLON;\n\t\t\t\tgoto reject;\n\t\t\t}\n\t\t\tctx->st[ctx->sp].s = LEJP_MP_VALUE;\n\t\t\tctx->path[ctx->ppos] = '\\0';\n\n\t\t\tlejp_check_path_match(ctx);\n\t\t\tif (ctx->callback(ctx, LEJPCB_PAIR_NAME)) {\n\t\t\t\tret = LEJP_REJECT_CALLBACK;\n\t\t\t\tgoto reject;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase LEJP_MP_VALUE:\n\t\t\tif (c >= '0' && c <= '9') {\n\t\t\t\tctx->npos = 0;\n\t\t\t\tctx->dcount = 0;\n\t\t\t\tctx->f = 0;\n\t\t\t\tctx->st[ctx->sp].s = LEJP_MP_VALUE_NUM_INT;\n\t\t\t\tgoto redo_character;\n\t\t\t}\n\t\t\tswitch (c) {\n\t\t\tcase'\\\"':\n\t\t\t\t/* push */\n\t\t\t\tctx->st[ctx->sp].s = LEJP_MP_COMMA_OR_END;\n\t\t\t\tc = LEJP_MP_STRING;\n\t\t\t\tctx->npos = 0;\n\t\t\t\tctx->buf[0] = '\\0';\n\t\t\t\tif (ctx->callback(ctx, LEJPCB_VAL_STR_START)) {\n\t\t\t\t\tret = LEJP_REJECT_CALLBACK;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t\tgoto add_stack_level;\n\n\t\t\tcase '{':\n\t\t\t\t/* push */\n\t\t\t\tctx->st[ctx->sp].s = LEJP_MP_COMMA_OR_END;\n\t\t\t\tc = LEJP_MEMBERS;\n\t\t\t\tlejp_check_path_match(ctx);\n\t\t\t\tif (ctx->callback(ctx, LEJPCB_OBJECT_START)) {\n\t\t\t\t\tret = LEJP_REJECT_CALLBACK;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t\tctx->path_match = 0;\n\t\t\t\tgoto add_stack_level;\n\n\t\t\tcase '[':\n\t\t\t\t/* push */\n\t\t\t\tctx->st[ctx->sp].s = LEJP_MP_ARRAY_END;\n\t\t\t\tc = LEJP_MP_VALUE;\n\t\t\t\tctx->path[ctx->ppos++] = '[';\n\t\t\t\tctx->path[ctx->ppos++] = ']';\n\t\t\t\tctx->path[ctx->ppos] = '\\0';\n\t\t\t\tif (ctx->callback(ctx, LEJPCB_ARRAY_START)) {\n\t\t\t\t\tret = LEJP_REJECT_CALLBACK;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t\tctx->i[ctx->ipos++] = 0;\n\t\t\t\tif (ctx->ipos > LWS_ARRAY_SIZE(ctx->i)) {\n\t\t\t\t\tret = LEJP_REJECT_MP_DELIM_ISTACK;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t\tgoto add_stack_level;\n\n\t\t\tcase ']':\n\t\t\t\t/* pop */\n\t\t\t\tif (!ctx->sp) { /* JSON can't end on ] */\n\t\t\t\t\tret = LEJP_REJECT_MP_C_OR_E_UNDERF;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t\tctx->sp--;\n\t\t\t\tif (ctx->st[ctx->sp].s != LEJP_MP_ARRAY_END) {\n\t\t\t\t\tret = LEJP_REJECT_MP_C_OR_E_NOTARRAY;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t\t/* drop the path [n] bit */\n\t\t\t\tif (ctx->sp) {\n\t\t\t\t\tctx->ppos = ctx->st[ctx->sp - 1].p;\n\t\t\t\t\tctx->ipos = ctx->st[ctx->sp - 1].i;\n\t\t\t\t}\n\t\t\t\tctx->path[ctx->ppos] = '\\0';\n\t\t\t\tif (ctx->path_match &&\n\t\t\t\t    ctx->ppos <= ctx->path_match_len)\n\t\t\t\t\t/*\n\t\t\t\t\t * we shrank the path to be\n\t\t\t\t\t * smaller than the matching point\n\t\t\t\t\t */\n\t\t\t\t\tctx->path_match = 0;\n\t\t\t\tgoto array_end;\n\n\t\t\tcase 't': /* true */\n\t\t\t\tctx->uni = 0;\n\t\t\t\tctx->st[ctx->sp].s = LEJP_MP_VALUE_TOK;\n\t\t\t\tbreak;\n\n\t\t\tcase 'f':\n\t\t\t\tctx->uni = 4;\n\t\t\t\tctx->st[ctx->sp].s = LEJP_MP_VALUE_TOK;\n\t\t\t\tbreak;\n\n\t\t\tcase 'n':\n\t\t\t\tctx->uni = 4 + 5;\n\t\t\t\tctx->st[ctx->sp].s = LEJP_MP_VALUE_TOK;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tret = LEJP_REJECT_MP_DELIM_BAD_VALUE_START;\n\t\t\t\tgoto reject;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase LEJP_MP_VALUE_NUM_INT:\n\t\t\tif (!ctx->npos && c == '-') {\n\t\t\t\tctx->f |= LEJP_SEEN_MINUS;\n\t\t\t\tgoto append_npos;\n\t\t\t}\n\n\t\t\tif (ctx->dcount < 10 && c >= '0' && c <= '9') {\n\t\t\t\tif (ctx->f & LEJP_SEEN_POINT)\n\t\t\t\t\tctx->f |= LEJP_SEEN_POST_POINT;\n\t\t\t\tctx->dcount++;\n\t\t\t\tgoto append_npos;\n\t\t\t}\n\t\t\tif (c == '.') {\n\t\t\t\tif (!ctx->dcount || (ctx->f & LEJP_SEEN_POINT)) {\n\t\t\t\t\tret = LEJP_REJECT_MP_VAL_NUM_FORMAT;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t\tctx->f |= LEJP_SEEN_POINT;\n\t\t\t\tgoto append_npos;\n\t\t\t}\n\t\t\t/*\n\t\t\t * before exponent, if we had . we must have had at\n\t\t\t * least one more digit\n\t\t\t */\n\t\t\tif ((ctx->f &\n\t\t\t\t(LEJP_SEEN_POINT | LEJP_SEEN_POST_POINT)) ==\n\t\t\t\t\t\t\t      LEJP_SEEN_POINT) {\n\t\t\t\tret = LEJP_REJECT_MP_VAL_NUM_INT_NO_FRAC;\n\t\t\t\tgoto reject;\n\t\t\t}\n\t\t\tif (c == 'e' || c == 'E') {\n\t\t\t\tif (ctx->f & LEJP_SEEN_EXP) {\n\t\t\t\t\tret = LEJP_REJECT_MP_VAL_NUM_FORMAT;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t\tctx->f |= LEJP_SEEN_EXP;\n\t\t\t\tctx->st[ctx->sp].s = LEJP_MP_VALUE_NUM_EXP;\n\t\t\t\tgoto append_npos;\n\t\t\t}\n\t\t\t/* if none of the above, did we even have a number? */\n\t\t\tif (!ctx->dcount) {\n\t\t\t\tret = LEJP_REJECT_MP_VAL_NUM_FORMAT;\n\t\t\t\tgoto reject;\n\t\t\t}\n\n\t\t\tctx->buf[ctx->npos] = '\\0';\n\t\t\tif (ctx->f & LEJP_SEEN_POINT) {\n\t\t\t\tif (ctx->callback(ctx, LEJPCB_VAL_NUM_FLOAT)) {\n\t\t\t\t\tret = LEJP_REJECT_CALLBACK;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (ctx->callback(ctx, LEJPCB_VAL_NUM_INT)) {\n\t\t\t\t\tret = LEJP_REJECT_CALLBACK;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* then this is the post-number character, loop */\n\t\t\tctx->st[ctx->sp].s = LEJP_MP_COMMA_OR_END;\n\t\t\tgoto redo_character;\n\n\t\tcase LEJP_MP_VALUE_NUM_EXP:\n\t\t\tctx->st[ctx->sp].s = LEJP_MP_VALUE_NUM_INT;\n\t\t\tif (c >= '0' && c <= '9')\n\t\t\t\tgoto redo_character;\n\t\t\tif (c == '+' || c == '-')\n\t\t\t\tgoto append_npos;\n\t\t\tret = LEJP_REJECT_MP_VAL_NUM_EXP_BAD_EXP;\n\t\t\tgoto reject;\n\n\t\tcase LEJP_MP_VALUE_TOK: /* true, false, null */\n\t\t\tif (c != tokens[ctx->uni]) {\n\t\t\t\tret = LEJP_REJECT_MP_VAL_TOK_UNKNOWN;\n\t\t\t\tgoto reject;\n\t\t\t}\n\t\t\tctx->uni++;\n\t\t\tif (tokens[ctx->uni] != ' ')\n\t\t\t\tbreak;\n\t\t\tswitch (ctx->uni) {\n\t\t\tcase 3:\n\t\t\t\tctx->buf[0] = '1';\n\t\t\t\tctx->buf[1] = '\\0';\n\t\t\t\tif (ctx->callback(ctx, LEJPCB_VAL_TRUE)) {\n\t\t\t\t\tret = LEJP_REJECT_CALLBACK;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\tctx->buf[0] = '0';\n\t\t\t\tctx->buf[1] = '\\0';\n\t\t\t\tif (ctx->callback(ctx, LEJPCB_VAL_FALSE)) {\n\t\t\t\t\tret = LEJP_REJECT_CALLBACK;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 12:\n\t\t\t\tctx->buf[0] = '\\0';\n\t\t\t\tif (ctx->callback(ctx, LEJPCB_VAL_NULL)) {\n\t\t\t\t\tret = LEJP_REJECT_CALLBACK;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tctx->st[ctx->sp].s = LEJP_MP_COMMA_OR_END;\n\t\t\tbreak;\n\n\t\tcase LEJP_MP_COMMA_OR_END:\n\t\t\tctx->path[ctx->ppos] = '\\0';\n\t\t\tif (c == ',') {\n\t\t\t\t/* increment this stack level's index */\n\t\t\t\tctx->st[ctx->sp].s = LEJP_M_P;\n\t\t\t\tif (!ctx->sp) {\n\t\t\t\t\tctx->ppos = 0;\n\t\t\t\t\t/*\n\t\t\t\t\t * since we came back to root level,\n\t\t\t\t\t * no path can still match\n\t\t\t\t\t */\n\t\t\t\t\tctx->path_match = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tctx->ppos = ctx->st[ctx->sp - 1].p;\n\t\t\t\tctx->path[ctx->ppos] = '\\0';\n\t\t\t\tif (ctx->path_match &&\n\t\t\t\t\t       ctx->ppos <= ctx->path_match_len)\n\t\t\t\t\t/*\n\t\t\t\t\t * we shrank the path to be\n\t\t\t\t\t * smaller than the matching point\n\t\t\t\t\t */\n\t\t\t\t\tctx->path_match = 0;\n\n\t\t\t\tif (ctx->st[ctx->sp - 1].s != LEJP_MP_ARRAY_END)\n\t\t\t\t\tbreak;\n\t\t\t\t/* top level is definitely an array... */\n\t\t\t\tif (ctx->ipos)\n\t\t\t\t\tctx->i[ctx->ipos - 1]++;\n\t\t\t\tctx->st[ctx->sp].s = LEJP_MP_VALUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (c == ']') {\n\t\t\t\tif (!ctx->sp) {  /* JSON can't end on ] */\n\t\t\t\t\tret = LEJP_REJECT_MP_C_OR_E_UNDERF;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t\t/* pop */\n\t\t\t\tctx->sp--;\n\t\t\t\tif (ctx->st[ctx->sp].s != LEJP_MP_ARRAY_END) {\n\t\t\t\t\tret = LEJP_REJECT_MP_C_OR_E_NOTARRAY;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t\t/* drop the path [n] bit */\n\t\t\t\tif (ctx->sp) {\n\t\t\t\t\tctx->ppos = ctx->st[ctx->sp - 1].p;\n\t\t\t\t\tctx->ipos = ctx->st[ctx->sp - 1].i;\n\t\t\t\t}\n\t\t\t\tctx->path[ctx->ppos] = '\\0';\n\t\t\t\tif (ctx->path_match &&\n\t\t\t\t\t       ctx->ppos <= ctx->path_match_len)\n\t\t\t\t\t/*\n\t\t\t\t\t * we shrank the path to be\n\t\t\t\t\t * smaller than the matching point\n\t\t\t\t\t */\n\t\t\t\t\tctx->path_match = 0;\n\n\t\t\t\t/* do LEJP_MP_ARRAY_END processing */\n\t\t\t\tgoto redo_character;\n\t\t\t}\n\t\t\tif (c == '}') {\n\t\t\t\tif (!ctx->sp) {\n\t\t\t\t\tlejp_check_path_match(ctx);\n\t\t\t\t\tif (ctx->callback(ctx, LEJPCB_OBJECT_END)) {\n\t\t\t\t\t\tret = LEJP_REJECT_CALLBACK;\n\t\t\t\t\t\tgoto reject;\n\t\t\t\t\t}\n\t\t\t\t\tctx->callback(ctx, LEJPCB_COMPLETE);\n\t\t\t\t\t/* done, return unused amount */\n\t\t\t\t\treturn len;\n\t\t\t\t}\n\t\t\t\t/* pop */\n\t\t\t\tctx->sp--;\n\t\t\t\tif (ctx->sp) {\n\t\t\t\t\tctx->ppos = ctx->st[ctx->sp - 1].p;\n\t\t\t\t\tctx->ipos = ctx->st[ctx->sp - 1].i;\n\t\t\t\t}\n\t\t\t\tctx->path[ctx->ppos] = '\\0';\n\t\t\t\tif (ctx->path_match &&\n\t\t\t\t\t       ctx->ppos <= ctx->path_match_len)\n\t\t\t\t\t/*\n\t\t\t\t\t * we shrank the path to be\n\t\t\t\t\t * smaller than the matching point\n\t\t\t\t\t */\n\t\t\t\t\tctx->path_match = 0;\n\t\t\t\tlejp_check_path_match(ctx);\n\t\t\t\tif (ctx->callback(ctx, LEJPCB_OBJECT_END)) {\n\t\t\t\t\tret = LEJP_REJECT_CALLBACK;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tret = LEJP_REJECT_MP_C_OR_E_NEITHER;\n\t\t\tgoto reject;\n\n\t\tcase LEJP_MP_ARRAY_END:\narray_end:\n\t\t\tctx->path[ctx->ppos] = '\\0';\n\t\t\tif (c == ',') {\n\t\t\t\t/* increment this stack level's index */\n\t\t\t\tif (ctx->ipos)\n\t\t\t\t\tctx->i[ctx->ipos - 1]++;\n\t\t\t\tctx->st[ctx->sp].s = LEJP_MP_VALUE;\n\t\t\t\tif (ctx->sp)\n\t\t\t\t\tctx->ppos = ctx->st[ctx->sp - 1].p;\n\t\t\t\tctx->path[ctx->ppos] = '\\0';\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (c != ']') {\n\t\t\t\tret = LEJP_REJECT_MP_ARRAY_END_MISSING;\n\t\t\t\tgoto reject;\n\t\t\t}\n\n\t\t\tctx->st[ctx->sp].s = LEJP_MP_COMMA_OR_END;\n\t\t\tctx->callback(ctx, LEJPCB_ARRAY_END);\n\t\t\tbreak;\n\t\t}\n\n\t\tcontinue;\n\nemit_string_char:\n\t\tif (!ctx->sp || ctx->st[ctx->sp - 1].s != LEJP_MP_DELIM) {\n\t\t\t/* assemble the string value into chunks */\n\t\t\tctx->buf[ctx->npos++] = c;\n\t\t\tif (ctx->npos == sizeof(ctx->buf) - 1) {\n\t\t\t\tif (ctx->callback(ctx, LEJPCB_VAL_STR_CHUNK)) {\n\t\t\t\t\tret = LEJP_REJECT_CALLBACK;\n\t\t\t\t\tgoto reject;\n\t\t\t\t}\n\t\t\t\tctx->npos = 0;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\t/* name part of name:value pair */\n\t\tctx->path[ctx->ppos++] = c;\n\t\tcontinue;\n\nadd_stack_level:\n\t\t/* push on to the object stack */\n\t\tif (ctx->ppos && ctx->st[ctx->sp].s != LEJP_MP_COMMA_OR_END &&\n\t\t\t\tctx->st[ctx->sp].s != LEJP_MP_ARRAY_END)\n\t\t\tctx->path[ctx->ppos++] = '.';\n\n\t\tctx->st[ctx->sp].p = ctx->ppos;\n\t\tctx->st[ctx->sp].i = ctx->ipos;\n\t\tif (++ctx->sp == LWS_ARRAY_SIZE(ctx->st)) {\n\t\t\tret = LEJP_REJECT_STACK_OVERFLOW;\n\t\t\tgoto reject;\n\t\t}\n\t\tctx->path[ctx->ppos] = '\\0';\n\t\tctx->st[ctx->sp].s = c;\n\t\tctx->st[ctx->sp].b = 0;\n\t\tcontinue;\n\nappend_npos:\n\t\tif (ctx->npos >= sizeof(ctx->buf)) {\n\t\t\tret = LEJP_REJECT_NUM_TOO_LONG;\n\t\t\tgoto reject;\n\t\t}\n\t\tctx->buf[ctx->npos++] = c;\n\t\tcontinue;\n\nredo_character:\n\t\tjson--;\n\t\tlen++;\n\t}\n\n\treturn LEJP_CONTINUE;\n\nreject:\n\tctx->callback(ctx, LEJPCB_FAILED);\n\treturn ret;\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/misc/sha-1.c",
    "content": "/*\n * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the project nor the names of its contributors\n *    may be used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n */\n/*\n * FIPS pub 180-1: Secure Hash Algorithm (SHA-1)\n * based on: http://csrc.nist.gov/fips/fip180-1.txt\n * implemented by Jun-ichiro itojun Itoh <itojun@itojun.org>\n */\n\n#include \"core/private.h\"\n\n#ifdef LWS_HAVE_SYS_TYPES_H\n#include <sys/types.h>\n#endif\n\nstruct sha1_ctxt {\n\tunion {\n\t\tunsigned char\t\tb8[20];\n\t\tunsigned int\t\tb32[5];\n\t} h;\n\tunion {\n\t\tunsigned char\t\tb8[8];\n\t\tuint64_t\t\tb64[1];\n\t} c;\n\tunion {\n\t\tunsigned char\t\tb8[64];\n\t\tunsigned int\t\tb32[16];\n\t} m;\n\tunsigned char\t\t\tcount;\n};\n\n/* sanity check */\n#if !defined(BYTE_ORDER) || !defined(LITTLE_ENDIAN) || !defined(BIG_ENDIAN)\n# define unsupported 1\n#elif BYTE_ORDER != BIG_ENDIAN\n# if BYTE_ORDER != LITTLE_ENDIAN\n#  define unsupported 1\n# endif\n#endif\n\n#ifndef unsupported\n\n/* constant table */\nstatic const unsigned int _K[] =\n\t\t\t{ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6 };\n#define\tK(t)\t_K[(t) / 20]\n\n#define\tF0(b, c, d)\t(((b) & (c)) | ((~(b)) & (d)))\n#define\tF1(b, c, d)\t(((b) ^ (c)) ^ (d))\n#define\tF2(b, c, d)\t(((b) & (c)) | ((b) & (d)) | ((c) & (d)))\n#define\tF3(b, c, d)\t(((b) ^ (c)) ^ (d))\n\n#define\tS(n, x)\t\t(((x) << (n)) | ((x) >> (32 - n)))\n\n#define\tH(n)\t(ctxt->h.b32[(n)])\n#define\tCOUNT\t(ctxt->count)\n#define\tBCOUNT\t(ctxt->c.b64[0] / 8)\n#define\tW(n)\t(ctxt->m.b32[(n)])\n\n#define\tPUTBYTE(x)\t{ \\\n\tctxt->m.b8[(COUNT % 64)] = (x);\t\t\\\n\tCOUNT++;\t\t\t\t\\\n\tCOUNT %= 64;\t\t\t\t\\\n\tctxt->c.b64[0] += 8;\t\t\t\\\n\tif (COUNT % 64 == 0)\t\t\t\\\n\t\tsha1_step(ctxt);\t\t\\\n\t}\n\n#define\tPUTPAD(x)\t{ \\\n\tctxt->m.b8[(COUNT % 64)] = (x);\t\t\\\n\tCOUNT++;\t\t\t\t\\\n\tCOUNT %= 64;\t\t\t\t\\\n\tif (COUNT % 64 == 0)\t\t\t\\\n\t\tsha1_step(ctxt);\t\t\\\n\t}\n\n\nstatic void\nsha1_step(struct sha1_ctxt *ctxt)\n{\n\tunsigned int\ta, b, c, d, e, tmp;\n\tsize_t t, s;\n\n#if BYTE_ORDER == LITTLE_ENDIAN\n\tstruct sha1_ctxt tctxt;\n\n\tmemcpy(&tctxt.m.b8[0], &ctxt->m.b8[0], 64);\n\tctxt->m.b8[0] = tctxt.m.b8[3]; ctxt->m.b8[1] = tctxt.m.b8[2];\n\tctxt->m.b8[2] = tctxt.m.b8[1]; ctxt->m.b8[3] = tctxt.m.b8[0];\n\tctxt->m.b8[4] = tctxt.m.b8[7]; ctxt->m.b8[5] = tctxt.m.b8[6];\n\tctxt->m.b8[6] = tctxt.m.b8[5]; ctxt->m.b8[7] = tctxt.m.b8[4];\n\tctxt->m.b8[8] = tctxt.m.b8[11]; ctxt->m.b8[9] = tctxt.m.b8[10];\n\tctxt->m.b8[10] = tctxt.m.b8[9]; ctxt->m.b8[11] = tctxt.m.b8[8];\n\tctxt->m.b8[12] = tctxt.m.b8[15]; ctxt->m.b8[13] = tctxt.m.b8[14];\n\tctxt->m.b8[14] = tctxt.m.b8[13]; ctxt->m.b8[15] = tctxt.m.b8[12];\n\tctxt->m.b8[16] = tctxt.m.b8[19]; ctxt->m.b8[17] = tctxt.m.b8[18];\n\tctxt->m.b8[18] = tctxt.m.b8[17]; ctxt->m.b8[19] = tctxt.m.b8[16];\n\tctxt->m.b8[20] = tctxt.m.b8[23]; ctxt->m.b8[21] = tctxt.m.b8[22];\n\tctxt->m.b8[22] = tctxt.m.b8[21]; ctxt->m.b8[23] = tctxt.m.b8[20];\n\tctxt->m.b8[24] = tctxt.m.b8[27]; ctxt->m.b8[25] = tctxt.m.b8[26];\n\tctxt->m.b8[26] = tctxt.m.b8[25]; ctxt->m.b8[27] = tctxt.m.b8[24];\n\tctxt->m.b8[28] = tctxt.m.b8[31]; ctxt->m.b8[29] = tctxt.m.b8[30];\n\tctxt->m.b8[30] = tctxt.m.b8[29]; ctxt->m.b8[31] = tctxt.m.b8[28];\n\tctxt->m.b8[32] = tctxt.m.b8[35]; ctxt->m.b8[33] = tctxt.m.b8[34];\n\tctxt->m.b8[34] = tctxt.m.b8[33]; ctxt->m.b8[35] = tctxt.m.b8[32];\n\tctxt->m.b8[36] = tctxt.m.b8[39]; ctxt->m.b8[37] = tctxt.m.b8[38];\n\tctxt->m.b8[38] = tctxt.m.b8[37]; ctxt->m.b8[39] = tctxt.m.b8[36];\n\tctxt->m.b8[40] = tctxt.m.b8[43]; ctxt->m.b8[41] = tctxt.m.b8[42];\n\tctxt->m.b8[42] = tctxt.m.b8[41]; ctxt->m.b8[43] = tctxt.m.b8[40];\n\tctxt->m.b8[44] = tctxt.m.b8[47]; ctxt->m.b8[45] = tctxt.m.b8[46];\n\tctxt->m.b8[46] = tctxt.m.b8[45]; ctxt->m.b8[47] = tctxt.m.b8[44];\n\tctxt->m.b8[48] = tctxt.m.b8[51]; ctxt->m.b8[49] = tctxt.m.b8[50];\n\tctxt->m.b8[50] = tctxt.m.b8[49]; ctxt->m.b8[51] = tctxt.m.b8[48];\n\tctxt->m.b8[52] = tctxt.m.b8[55]; ctxt->m.b8[53] = tctxt.m.b8[54];\n\tctxt->m.b8[54] = tctxt.m.b8[53]; ctxt->m.b8[55] = tctxt.m.b8[52];\n\tctxt->m.b8[56] = tctxt.m.b8[59]; ctxt->m.b8[57] = tctxt.m.b8[58];\n\tctxt->m.b8[58] = tctxt.m.b8[57]; ctxt->m.b8[59] = tctxt.m.b8[56];\n\tctxt->m.b8[60] = tctxt.m.b8[63]; ctxt->m.b8[61] = tctxt.m.b8[62];\n\tctxt->m.b8[62] = tctxt.m.b8[61]; ctxt->m.b8[63] = tctxt.m.b8[60];\n#endif\n\n\ta = H(0); b = H(1); c = H(2); d = H(3); e = H(4);\n\n\tfor (t = 0; t < 20; t++) {\n\t\ts = t & 0x0f;\n\t\tif (t >= 16)\n\t\t\tW(s) = S(1, W((s+13) & 0x0f) ^ W((s+8) & 0x0f) ^\n\t\t\t\t\t\t\tW((s+2) & 0x0f) ^ W(s));\n\n\t\ttmp = S(5, a) + F0(b, c, d) + e + W(s) + K(t);\n\t\te = d; d = c; c = S(30, b); b = a; a = tmp;\n\t}\n\tfor (t = 20; t < 40; t++) {\n\t\ts = t & 0x0f;\n\t\tW(s) = S(1, W((s+13) & 0x0f) ^ W((s+8) & 0x0f) ^\n\t\t\t\t\t\t\tW((s+2) & 0x0f) ^ W(s));\n\t\ttmp = S(5, a) + F1(b, c, d) + e + W(s) + K(t);\n\t\te = d; d = c; c = S(30, b); b = a; a = tmp;\n\t}\n\tfor (t = 40; t < 60; t++) {\n\t\ts = t & 0x0f;\n\t\tW(s) = S(1, W((s+13) & 0x0f) ^ W((s+8) & 0x0f) ^\n\t\t\t\t\t\t\tW((s+2) & 0x0f) ^ W(s));\n\t\ttmp = S(5, a) + F2(b, c, d) + e + W(s) + K(t);\n\t\te = d; d = c; c = S(30, b); b = a; a = tmp;\n\t}\n\tfor (t = 60; t < 80; t++) {\n\t\ts = t & 0x0f;\n\t\tW(s) = S(1, W((s+13) & 0x0f) ^ W((s+8) & 0x0f) ^\n\t\t\t\t\t\t\tW((s+2) & 0x0f) ^ W(s));\n\t\ttmp = S(5, a) + F3(b, c, d) + e + W(s) + K(t);\n\t\te = d; d = c; c = S(30, b); b = a; a = tmp;\n\t}\n\n\tH(0) = H(0) + a;\n\tH(1) = H(1) + b;\n\tH(2) = H(2) + c;\n\tH(3) = H(3) + d;\n\tH(4) = H(4) + e;\n\n\tbzero(&ctxt->m.b8[0], 64);\n}\n\n/*------------------------------------------------------------*/\n\nstatic void\n_sha1_init(struct sha1_ctxt *ctxt)\n{\n\tbzero(ctxt, sizeof(struct sha1_ctxt));\n\tH(0) = 0x67452301;\n\tH(1) = 0xefcdab89;\n\tH(2) = 0x98badcfe;\n\tH(3) = 0x10325476;\n\tH(4) = 0xc3d2e1f0;\n}\n\nvoid\nsha1_pad(struct sha1_ctxt *ctxt)\n{\n\tsize_t padlen;\t\t/*pad length in bytes*/\n\tsize_t padstart;\n\n\tPUTPAD(0x80);\n\n\tpadstart = COUNT % 64;\n\tpadlen = 64 - padstart;\n\tif (padlen < 8) {\n\t\tbzero(&ctxt->m.b8[padstart], padlen);\n\t\tCOUNT += (unsigned char)padlen;\n\t\tCOUNT %= 64;\n\t\tsha1_step(ctxt);\n\t\tpadstart = COUNT % 64;\t/* should be 0 */\n\t\tpadlen = 64 - padstart;\t/* should be 64 */\n\t}\n\tbzero(&ctxt->m.b8[padstart], padlen - 8);\n\tCOUNT += ((unsigned char)padlen - 8);\n\tCOUNT %= 64;\n#if BYTE_ORDER == BIG_ENDIAN\n\tPUTPAD(ctxt->c.b8[0]); PUTPAD(ctxt->c.b8[1]);\n\tPUTPAD(ctxt->c.b8[2]); PUTPAD(ctxt->c.b8[3]);\n\tPUTPAD(ctxt->c.b8[4]); PUTPAD(ctxt->c.b8[5]);\n\tPUTPAD(ctxt->c.b8[6]); PUTPAD(ctxt->c.b8[7]);\n#else\n\tPUTPAD(ctxt->c.b8[7]); PUTPAD(ctxt->c.b8[6]);\n\tPUTPAD(ctxt->c.b8[5]); PUTPAD(ctxt->c.b8[4]);\n\tPUTPAD(ctxt->c.b8[3]); PUTPAD(ctxt->c.b8[2]);\n\tPUTPAD(ctxt->c.b8[1]); PUTPAD(ctxt->c.b8[0]);\n#endif\n}\n\nvoid\nsha1_loop(struct sha1_ctxt *ctxt, const unsigned char *input, size_t len)\n{\n\tsize_t gaplen;\n\tsize_t gapstart;\n\tsize_t off;\n\tsize_t copysiz;\n\n\toff = 0;\n\n\twhile (off < len) {\n\t\tgapstart = COUNT % 64;\n\t\tgaplen = 64 - gapstart;\n\n\t\tcopysiz = (gaplen < len - off) ? gaplen : len - off;\n\t\tmemcpy(&ctxt->m.b8[gapstart], &input[off], copysiz);\n\t\tCOUNT += (unsigned char)copysiz;\n\t\tCOUNT %= 64;\n\t\tctxt->c.b64[0] += copysiz * 8;\n\t\tif (COUNT % 64 == 0)\n\t\t\tsha1_step(ctxt);\n\t\toff += copysiz;\n\t}\n}\n\nvoid\nsha1_result(struct sha1_ctxt *ctxt, void *digest0)\n{\n\tunsigned char *digest;\n\n\tdigest = (unsigned char *)digest0;\n\tsha1_pad(ctxt);\n#if BYTE_ORDER == BIG_ENDIAN\n\tmemcpy(digest, &ctxt->h.b8[0], 20);\n#else\n\tdigest[0] = ctxt->h.b8[3]; digest[1] = ctxt->h.b8[2];\n\tdigest[2] = ctxt->h.b8[1]; digest[3] = ctxt->h.b8[0];\n\tdigest[4] = ctxt->h.b8[7]; digest[5] = ctxt->h.b8[6];\n\tdigest[6] = ctxt->h.b8[5]; digest[7] = ctxt->h.b8[4];\n\tdigest[8] = ctxt->h.b8[11]; digest[9] = ctxt->h.b8[10];\n\tdigest[10] = ctxt->h.b8[9]; digest[11] = ctxt->h.b8[8];\n\tdigest[12] = ctxt->h.b8[15]; digest[13] = ctxt->h.b8[14];\n\tdigest[14] = ctxt->h.b8[13]; digest[15] = ctxt->h.b8[12];\n\tdigest[16] = ctxt->h.b8[19]; digest[17] = ctxt->h.b8[18];\n\tdigest[18] = ctxt->h.b8[17]; digest[19] = ctxt->h.b8[16];\n#endif\n}\n\n/*\n * This should look and work like the libcrypto implementation\n */\n\nLWS_VISIBLE unsigned char *\nlws_SHA1(const unsigned char *d, size_t n, unsigned char *md)\n{\n\tstruct sha1_ctxt ctx;\n\n\t_sha1_init(&ctx);\n\tsha1_loop(&ctx, d, n);\n\tsha1_result(&ctx, (void *)md);\n\n\treturn md;\n}\n\n#endif /*unsupported*/\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/plat/lws-plat-unix.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#define _GNU_SOURCE\n#include \"core/private.h\"\n\n#include <pwd.h>\n#include <grp.h>\n\n#ifdef LWS_WITH_PLUGINS\n#include <dlfcn.h>\n#endif\n#include <dirent.h>\n\nvoid lws_plat_apply_FD_CLOEXEC(int n)\n{\n\tif (n != -1)\n\t\tfcntl(n, F_SETFD, FD_CLOEXEC );\n}\n\nint\nlws_plat_socket_offset(void)\n{\n\treturn 0;\n}\n\nint\nlws_plat_pipe_create(struct lws *wsi)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\n#if defined(LWS_HAVE_PIPE2)\n\treturn pipe2(pt->dummy_pipe_fds, O_NONBLOCK);\n#else\n\treturn pipe(pt->dummy_pipe_fds);\n#endif\n}\n\nint\nlws_plat_pipe_signal(struct lws *wsi)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tchar buf = 0;\n\tint n;\n\n\tn = write(pt->dummy_pipe_fds[1], &buf, 1);\n\n\treturn n != 1;\n}\n\nvoid\nlws_plat_pipe_close(struct lws *wsi)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\n\tif (pt->dummy_pipe_fds[0] && pt->dummy_pipe_fds[0] != -1)\n\t\tclose(pt->dummy_pipe_fds[0]);\n\tif (pt->dummy_pipe_fds[1] && pt->dummy_pipe_fds[1] != -1)\n\t\tclose(pt->dummy_pipe_fds[1]);\n\n\tpt->dummy_pipe_fds[0] = pt->dummy_pipe_fds[1] = -1;\n}\n\n#ifdef __QNX__\n# include \"netinet/tcp_var.h\"\n# define TCP_KEEPINTVL TCPCTL_KEEPINTVL\n# define TCP_KEEPIDLE  TCPCTL_KEEPIDLE\n# define TCP_KEEPCNT   TCPCTL_KEEPCNT\n#endif\n\nunsigned long long time_in_microseconds(void)\n{\n\tstruct timeval tv;\n\n\tgettimeofday(&tv, NULL);\n\treturn ((unsigned long long)tv.tv_sec * 1000000LL) + tv.tv_usec;\n}\n\nLWS_VISIBLE int\nlws_get_random(struct lws_context *context, void *buf, int len)\n{\n\treturn read(context->fd_random, (char *)buf, len);\n}\n\nLWS_VISIBLE int\nlws_send_pipe_choked(struct lws *wsi)\n{\n\tstruct lws_pollfd fds;\n\tstruct lws *wsi_eff = wsi;\n\n#if defined(LWS_WITH_HTTP2)\n\twsi_eff = lws_get_network_wsi(wsi);\n#endif\n\n\t/* the fact we checked implies we avoided back-to-back writes */\n\twsi_eff->could_have_pending = 0;\n\n\t/* treat the fact we got a truncated send pending as if we're choked */\n\tif (wsi_eff->trunc_len)\n\t\treturn 1;\n\n\tfds.fd = wsi_eff->desc.sockfd;\n\tfds.events = POLLOUT;\n\tfds.revents = 0;\n\n\tif (poll(&fds, 1, 0) != 1)\n\t\treturn 1;\n\n\tif ((fds.revents & POLLOUT) == 0)\n\t\treturn 1;\n\n\t/* okay to send another packet without blocking */\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\nlws_poll_listen_fd(struct lws_pollfd *fd)\n{\n\treturn poll(fd, 1, 0);\n}\n\nLWS_VISIBLE void lwsl_emit_syslog(int level, const char *line)\n{\n\tint syslog_level = LOG_DEBUG;\n\n\tswitch (level) {\n\tcase LLL_ERR:\n\t\tsyslog_level = LOG_ERR;\n\t\tbreak;\n\tcase LLL_WARN:\n\t\tsyslog_level = LOG_WARNING;\n\t\tbreak;\n\tcase LLL_NOTICE:\n\t\tsyslog_level = LOG_NOTICE;\n\t\tbreak;\n\tcase LLL_INFO:\n\t\tsyslog_level = LOG_INFO;\n\t\tbreak;\n\t}\n\tsyslog(syslog_level, \"%s\", line);\n}\n\nLWS_VISIBLE LWS_EXTERN int\n_lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi)\n{\n\tvolatile struct lws_foreign_thread_pollfd *ftp, *next;\n\tvolatile struct lws_context_per_thread *vpt;\n\tstruct lws_context_per_thread *pt;\n\tint n = -1, m, c;\n\n\t/* stay dead once we are dead */\n\n\tif (!context || !context->vhost_list)\n\t\treturn 1;\n\n\tpt = &context->pt[tsi];\n\tvpt = (volatile struct lws_context_per_thread *)pt;\n\n\tlws_stats_atomic_bump(context, pt, LWSSTATS_C_SERVICE_ENTRY, 1);\n\n\tif (timeout_ms < 0)\n\t\tgoto faked_service;\n\n\tif (context->event_loop_ops->run_pt)\n\t\tcontext->event_loop_ops->run_pt(context, tsi);\n\n\tif (!context->service_tid_detected) {\n\t\tstruct lws _lws;\n\n\t\tmemset(&_lws, 0, sizeof(_lws));\n\t\t_lws.context = context;\n\n\t\tcontext->service_tid_detected =\n\t\t\tcontext->vhost_list->protocols[0].callback(\n\t\t\t&_lws, LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0);\n\t\tcontext->service_tid = context->service_tid_detected;\n\t\tcontext->service_tid_detected = 1;\n\t}\n\n\t/*\n\t * is there anybody with pending stuff that needs service forcing?\n\t */\n\tif (!lws_service_adjust_timeout(context, 1, tsi)) {\n\t\t/* -1 timeout means just do forced service */\n\t\t_lws_plat_service_tsi(context, -1, pt->tid);\n\t\t/* still somebody left who wants forced service? */\n\t\tif (!lws_service_adjust_timeout(context, 1, pt->tid))\n\t\t\t/* yes... come back again quickly */\n\t\t\ttimeout_ms = 0;\n\t}\n\n\tif (timeout_ms) {\n\t\tlws_pt_lock(pt, __func__);\n\t\t/* don't stay in poll wait longer than next hr timeout */\n\t\tlws_usec_t t =  __lws_hrtimer_service(pt);\n\t\tif ((lws_usec_t)timeout_ms * 1000 > t)\n\t\t\ttimeout_ms = t / 1000;\n\t\tlws_pt_unlock(pt);\n\t}\n\n\tvpt->inside_poll = 1;\n\tlws_memory_barrier();\n\tn = poll(pt->fds, pt->fds_count, timeout_ms);\n\tvpt->inside_poll = 0;\n\tlws_memory_barrier();\n\n\t/* Collision will be rare and brief.  Just spin until it completes */\n\twhile (vpt->foreign_spinlock)\n\t\t;\n\n\t/*\n\t * At this point we are not inside a foreign thread pollfd change,\n\t * and we have marked ourselves as outside the poll() wait.  So we\n\t * are the only guys that can modify the lws_foreign_thread_pollfd\n\t * list on the pt.  Drain the list and apply the changes to the\n\t * affected pollfds in the correct order.\n\t */\n\n\tlws_pt_lock(pt, __func__);\n\n\tftp = vpt->foreign_pfd_list;\n\t//lwsl_notice(\"cleared list %p\\n\", ftp);\n\twhile (ftp) {\n\t\tstruct lws *wsi;\n\t\tstruct lws_pollfd *pfd;\n\n\t\tnext = ftp->next;\n\t\tpfd = &vpt->fds[ftp->fd_index];\n\t\tif (lws_socket_is_valid(pfd->fd)) {\n\t\t\twsi = wsi_from_fd(context, pfd->fd);\n\t\t\tif (wsi)\n\t\t\t\t__lws_change_pollfd(wsi, ftp->_and, ftp->_or);\n\t\t}\n\t\tlws_free((void *)ftp);\n\t\tftp = next;\n\t}\n\tvpt->foreign_pfd_list = NULL;\n\tlws_memory_barrier();\n\n\t/* we have come out of a poll wait... check the hrtimer list */\n\n\t__lws_hrtimer_service(pt);\n\n\tlws_pt_unlock(pt);\n\n\tm = 0;\n#if defined(LWS_ROLE_WS) && !defined(LWS_WITHOUT_EXTENSIONS)\n\tm |= !!pt->ws.rx_draining_ext_list;\n#endif\n\n\tif (pt->context->tls_ops &&\n\t    pt->context->tls_ops->fake_POLLIN_for_buffered)\n\t\tm |= pt->context->tls_ops->fake_POLLIN_for_buffered(pt);\n\n\tif (!m && !n) { /* nothing to do */\n\t\tlws_service_fd_tsi(context, NULL, tsi);\n\t\tlws_service_do_ripe_rxflow(pt);\n\n\t\treturn 0;\n\t}\n\nfaked_service:\n\tm = lws_service_flag_pending(context, tsi);\n\tif (m)\n\t\tc = -1; /* unknown limit */\n\telse\n\t\tif (n < 0) {\n\t\t\tif (LWS_ERRNO != LWS_EINTR)\n\t\t\t\treturn -1;\n\t\t\treturn 0;\n\t\t} else\n\t\t\tc = n;\n\n\t/* any socket with events to service? */\n\tfor (n = 0; n < (int)pt->fds_count && c; n++) {\n\t\tif (!pt->fds[n].revents)\n\t\t\tcontinue;\n\n\t\tc--;\n\n\t\tm = lws_service_fd_tsi(context, &pt->fds[n], tsi);\n\t\tif (m < 0)\n\t\t\treturn -1;\n\t\t/* if something closed, retry this slot */\n\t\tif (m)\n\t\t\tn--;\n\t}\n\n\tlws_service_do_ripe_rxflow(pt);\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\nlws_plat_check_connection_error(struct lws *wsi)\n{\n\treturn 0;\n}\n\nLWS_VISIBLE int\nlws_plat_service(struct lws_context *context, int timeout_ms)\n{\n\treturn _lws_plat_service_tsi(context, timeout_ms, 0);\n}\n\nLWS_VISIBLE int\nlws_plat_set_socket_options(struct lws_vhost *vhost, int fd)\n{\n\tint optval = 1;\n\tsocklen_t optlen = sizeof(optval);\n\n#if defined(__APPLE__) || \\\n    defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \\\n    defined(__NetBSD__) || \\\n    defined(__OpenBSD__) || \\\n    defined(__HAIKU__)\n\tstruct protoent *tcp_proto;\n#endif\n\n\tfcntl(fd, F_SETFD, FD_CLOEXEC);\n\n\tif (vhost->ka_time) {\n\t\t/* enable keepalive on this socket */\n\t\toptval = 1;\n\t\tif (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,\n\t\t\t       (const void *)&optval, optlen) < 0)\n\t\t\treturn 1;\n\n#if defined(__APPLE__) || \\\n    defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \\\n    defined(__NetBSD__) || \\\n    defined(__CYGWIN__) || defined(__OpenBSD__) || defined (__sun) || \\\n    defined(__HAIKU__)\n\n\t\t/*\n\t\t * didn't find a way to set these per-socket, need to\n\t\t * tune kernel systemwide values\n\t\t */\n#else\n\t\t/* set the keepalive conditions we want on it too */\n\n#if defined(LWS_HAVE_TCP_USER_TIMEOUT)\n\t\toptval = 1000 * (vhost->ka_time +\n\t\t\t\t (vhost->ka_interval * vhost->ka_probes));\n\t\tif (setsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT,\n\t\t\t       (const void *)&optval, optlen) < 0)\n\t\t\treturn 1;\n#endif\n\t\toptval = vhost->ka_time;\n\t\tif (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE,\n\t\t\t       (const void *)&optval, optlen) < 0)\n\t\t\treturn 1;\n\n\t\toptval = vhost->ka_interval;\n\t\tif (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL,\n\t\t\t       (const void *)&optval, optlen) < 0)\n\t\t\treturn 1;\n\n\t\toptval = vhost->ka_probes;\n\t\tif (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT,\n\t\t\t       (const void *)&optval, optlen) < 0)\n\t\t\treturn 1;\n#endif\n\t}\n\n#if defined(SO_BINDTODEVICE)\n\tif (vhost->bind_iface && vhost->iface) {\n\t\tlwsl_info(\"binding listen skt to %s using SO_BINDTODEVICE\\n\", vhost->iface);\n\t\tif (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, vhost->iface,\n\t\t\t\tstrlen(vhost->iface)) < 0) {\n\t\t\tlwsl_warn(\"Failed to bind to device %s\\n\", vhost->iface);\n\t\t\treturn 1;\n\t\t}\n\t}\n#endif\n\n\t/* Disable Nagle */\n\toptval = 1;\n#if defined (__sun) || defined(__QNX__)\n\tif (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&optval, optlen) < 0)\n\t\treturn 1;\n#elif !defined(__APPLE__) && \\\n      !defined(__FreeBSD__) && !defined(__FreeBSD_kernel__) &&        \\\n      !defined(__NetBSD__) && \\\n      !defined(__OpenBSD__) && \\\n      !defined(__HAIKU__)\n\tif (setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen) < 0)\n\t\treturn 1;\n#else\n\ttcp_proto = getprotobyname(\"TCP\");\n\tif (setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen) < 0)\n\t\treturn 1;\n#endif\n\n\t/* We are nonblocking... */\n\tif (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)\n\t\treturn 1;\n\n\treturn 0;\n}\n\n#if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)\nstatic void\n_lws_plat_apply_caps(int mode, const cap_value_t *cv, int count)\n{\n\tcap_t caps;\n\n\tif (!count)\n\t\treturn;\n\n\tcaps = cap_get_proc();\n\n\tcap_set_flag(caps, mode, count, cv, CAP_SET);\n\tcap_set_proc(caps);\n\tprctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);\n\tcap_free(caps);\n}\n#endif\n\nLWS_VISIBLE void\nlws_plat_drop_app_privileges(const struct lws_context_creation_info *info)\n{\n#if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)\n\tint n;\n#endif\n\n\tif (info->gid && info->gid != -1)\n\t\tif (setgid(info->gid))\n\t\t\tlwsl_warn(\"setgid: %s\\n\", strerror(LWS_ERRNO));\n\n\tif (info->uid && info->uid != -1) {\n\t\tstruct passwd *p = getpwuid(info->uid);\n\n\t\tif (p) {\n\n#if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)\n\t\t\t_lws_plat_apply_caps(CAP_PERMITTED, info->caps, info->count_caps);\n#endif\n\n\t\t\tinitgroups(p->pw_name, info->gid);\n\t\t\tif (setuid(info->uid))\n\t\t\t\tlwsl_warn(\"setuid: %s\\n\", strerror(LWS_ERRNO));\n\t\t\telse\n\t\t\t\tlwsl_notice(\"Set privs to user '%s'\\n\", p->pw_name);\n\n#if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)\n\t\t\t_lws_plat_apply_caps(CAP_EFFECTIVE, info->caps, info->count_caps);\n\n\t\t\tif (info->count_caps)\n\t\t\t\tfor (n = 0; n < info->count_caps; n++)\n\t\t\t\t\tlwsl_notice(\"   RETAINING CAPABILITY %d\\n\", (int)info->caps[n]);\n#endif\n\n\t\t} else\n\t\t\tlwsl_warn(\"getpwuid: unable to find uid %d\", info->uid);\n\t}\n}\n\n#ifdef LWS_WITH_PLUGINS\n\n#if defined(LWS_WITH_LIBUV) && UV_VERSION_MAJOR > 0\n\n/* libuv.c implements these in a cross-platform way */\n\n#else\n\nstatic int filter(const struct dirent *ent)\n{\n\tif (!strcmp(ent->d_name, \".\") || !strcmp(ent->d_name, \"..\"))\n\t\treturn 0;\n\n\treturn 1;\n}\n\nLWS_VISIBLE int\nlws_plat_plugins_init(struct lws_context * context, const char * const *d)\n{\n\tstruct lws_plugin_capability lcaps;\n\tstruct lws_plugin *plugin;\n\tlws_plugin_init_func initfunc;\n\tstruct dirent **namelist;\n\tint n, i, m, ret = 0;\n\tchar path[256];\n\tvoid *l;\n\n\tlwsl_notice(\"  Plugins:\\n\");\n\n\twhile (d && *d) {\n\t\tn = scandir(*d, &namelist, filter, alphasort);\n\t\tif (n < 0) {\n\t\t\tlwsl_err(\"Scandir on %s failed\\n\", *d);\n\t\t\treturn 1;\n\t\t}\n\n\t\tfor (i = 0; i < n; i++) {\n\t\t\tif (strlen(namelist[i]->d_name) < 7)\n\t\t\t\tgoto inval;\n\n\t\t\tlwsl_notice(\"   %s\\n\", namelist[i]->d_name);\n\n\t\t\tlws_snprintf(path, sizeof(path) - 1, \"%s/%s\", *d,\n\t\t\t\t namelist[i]->d_name);\n\t\t\tl = dlopen(path, RTLD_NOW);\n\t\t\tif (!l) {\n\t\t\t\tlwsl_err(\"Error loading DSO: %s\\n\", dlerror());\n\t\t\t\twhile (i++ < n)\n\t\t\t\t\tfree(namelist[i]);\n\t\t\t\tgoto bail;\n\t\t\t}\n\t\t\t/* we could open it, can we get his init function? */\n\t\t\tm = lws_snprintf(path, sizeof(path) - 1, \"init_%s\",\n\t\t\t\t     namelist[i]->d_name + 3 /* snip lib... */);\n\t\t\tpath[m - 3] = '\\0'; /* snip the .so */\n\t\t\tinitfunc = dlsym(l, path);\n\t\t\tif (!initfunc) {\n\t\t\t\tlwsl_err(\"Failed to get init on %s: %s\",\n\t\t\t\t\t\tnamelist[i]->d_name, dlerror());\n\t\t\t\tdlclose(l);\n\t\t\t}\n\t\t\tlcaps.api_magic = LWS_PLUGIN_API_MAGIC;\n\t\t\tm = initfunc(context, &lcaps);\n\t\t\tif (m) {\n\t\t\t\tlwsl_err(\"Initializing %s failed %d\\n\",\n\t\t\t\t\tnamelist[i]->d_name, m);\n\t\t\t\tdlclose(l);\n\t\t\t\tgoto skip;\n\t\t\t}\n\n\t\t\tplugin = lws_malloc(sizeof(*plugin), \"plugin\");\n\t\t\tif (!plugin) {\n\t\t\t\tlwsl_err(\"OOM\\n\");\n\t\t\t\tgoto bail;\n\t\t\t}\n\t\t\tplugin->list = context->plugin_list;\n\t\t\tcontext->plugin_list = plugin;\n\t\t\tlws_strncpy(plugin->name, namelist[i]->d_name,\n\t\t\t\t    sizeof(plugin->name));\n\t\t\tplugin->l = l;\n\t\t\tplugin->caps = lcaps;\n\t\t\tcontext->plugin_protocol_count += lcaps.count_protocols;\n\t\t\tcontext->plugin_extension_count += lcaps.count_extensions;\n\n\t\t\tfree(namelist[i]);\n\t\t\tcontinue;\n\n\tskip:\n\t\t\tdlclose(l);\n\tinval:\n\t\t\tfree(namelist[i]);\n\t\t}\n\t\tfree(namelist);\n\t\td++;\n\t}\n\nbail:\n\tfree(namelist);\n\n\treturn ret;\n}\n\nLWS_VISIBLE int\nlws_plat_plugins_destroy(struct lws_context * context)\n{\n\tstruct lws_plugin *plugin = context->plugin_list, *p;\n\tlws_plugin_destroy_func func;\n\tchar path[256];\n\tint m;\n\n\tif (!plugin)\n\t\treturn 0;\n\n\tlwsl_notice(\"%s\\n\", __func__);\n\n\twhile (plugin) {\n\t\tp = plugin;\n\t\tm = lws_snprintf(path, sizeof(path) - 1, \"destroy_%s\", plugin->name + 3);\n\t\tpath[m - 3] = '\\0';\n\t\tfunc = dlsym(plugin->l, path);\n\t\tif (!func) {\n\t\t\tlwsl_err(\"Failed to get destroy on %s: %s\",\n\t\t\t\t\tplugin->name, dlerror());\n\t\t\tgoto next;\n\t\t}\n\t\tm = func(context);\n\t\tif (m)\n\t\t\tlwsl_err(\"Initializing %s failed %d\\n\",\n\t\t\t\tplugin->name, m);\nnext:\n\t\tdlclose(p->l);\n\t\tplugin = p->list;\n\t\tp->list = NULL;\n\t\tfree(p);\n\t}\n\n\tcontext->plugin_list = NULL;\n\n\treturn 0;\n}\n\n#endif\n#endif\n\n\n#if 0\nstatic void\nsigabrt_handler(int x)\n{\n\tprintf(\"%s\\n\", __func__);\n}\n#endif\n\nLWS_VISIBLE int\nlws_plat_context_early_init(void)\n{\n#if !defined(LWS_AVOID_SIGPIPE_IGN)\n\tsignal(SIGPIPE, SIG_IGN);\n#endif\n\n\treturn 0;\n}\n\nLWS_VISIBLE void\nlws_plat_context_early_destroy(struct lws_context *context)\n{\n}\n\nLWS_VISIBLE void\nlws_plat_context_late_destroy(struct lws_context *context)\n{\n#ifdef LWS_WITH_PLUGINS\n\tif (context->plugin_list)\n\t\tlws_plat_plugins_destroy(context);\n#endif\n\n\tif (context->lws_lookup)\n\t\tlws_free(context->lws_lookup);\n\n\tif (!context->fd_random)\n\t\tlwsl_err(\"ZERO RANDOM FD\\n\");\n\tif (context->fd_random != LWS_INVALID_FILE)\n\t\tclose(context->fd_random);\n}\n\n/* cast a struct sockaddr_in6 * into addr for ipv6 */\n\nLWS_VISIBLE int\nlws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,\n\t\t    size_t addrlen)\n{\n\tint rc = LWS_ITOSA_NOT_EXIST;\n\n\tstruct ifaddrs *ifr;\n\tstruct ifaddrs *ifc;\n#ifdef LWS_WITH_IPV6\n\tstruct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;\n#endif\n\n\tgetifaddrs(&ifr);\n\tfor (ifc = ifr; ifc != NULL && rc; ifc = ifc->ifa_next) {\n\t\tif (!ifc->ifa_addr)\n\t\t\tcontinue;\n\n\t\tlwsl_debug(\" interface %s vs %s (fam %d) ipv6 %d\\n\", ifc->ifa_name, ifname, ifc->ifa_addr->sa_family, ipv6);\n\n\t\tif (strcmp(ifc->ifa_name, ifname))\n\t\t\tcontinue;\n\n\t\tswitch (ifc->ifa_addr->sa_family) {\n#if defined(AF_PACKET)\n\t\tcase AF_PACKET:\n\t\t\t/* interface exists but is not usable */\n\t\t\trc = LWS_ITOSA_NOT_USABLE;\n\t\t\tcontinue;\n#endif\n\n\t\tcase AF_INET:\n#ifdef LWS_WITH_IPV6\n\t\t\tif (ipv6) {\n\t\t\t\t/* map IPv4 to IPv6 */\n\t\t\t\tbzero((char *)&addr6->sin6_addr,\n\t\t\t\t\t\tsizeof(struct in6_addr));\n\t\t\t\taddr6->sin6_addr.s6_addr[10] = 0xff;\n\t\t\t\taddr6->sin6_addr.s6_addr[11] = 0xff;\n\t\t\t\tmemcpy(&addr6->sin6_addr.s6_addr[12],\n\t\t\t\t\t&((struct sockaddr_in *)ifc->ifa_addr)->sin_addr,\n\t\t\t\t\t\t\tsizeof(struct in_addr));\n\t\t\t} else\n#endif\n\t\t\t\tmemcpy(addr,\n\t\t\t\t\t(struct sockaddr_in *)ifc->ifa_addr,\n\t\t\t\t\t\t    sizeof(struct sockaddr_in));\n\t\t\tbreak;\n#ifdef LWS_WITH_IPV6\n\t\tcase AF_INET6:\n\t\t\tmemcpy(&addr6->sin6_addr,\n\t\t\t  &((struct sockaddr_in6 *)ifc->ifa_addr)->sin6_addr,\n\t\t\t\t\t\t       sizeof(struct in6_addr));\n\t\t\tbreak;\n#endif\n\t\tdefault:\n\t\t\tcontinue;\n\t\t}\n\t\trc = LWS_ITOSA_USABLE;\n\t}\n\n\tfreeifaddrs(ifr);\n\n\tif (rc) {\n\t\t/* check if bind to IP address */\n#ifdef LWS_WITH_IPV6\n\t\tif (inet_pton(AF_INET6, ifname, &addr6->sin6_addr) == 1)\n\t\t\trc = LWS_ITOSA_USABLE;\n\t\telse\n#endif\n\t\tif (inet_pton(AF_INET, ifname, &addr->sin_addr) == 1)\n\t\t\trc = LWS_ITOSA_USABLE;\n\t}\n\n\treturn rc;\n}\n\nLWS_VISIBLE void\nlws_plat_insert_socket_into_fds(struct lws_context *context, struct lws *wsi)\n{\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\n\tif (context->event_loop_ops->io)\n\t\tcontext->event_loop_ops->io(wsi, LWS_EV_START | LWS_EV_READ);\n\n\tpt->fds[pt->fds_count++].revents = 0;\n}\n\nLWS_VISIBLE void\nlws_plat_delete_socket_from_fds(struct lws_context *context,\n\t\t\t\t\t\tstruct lws *wsi, int m)\n{\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\n\tif (context->event_loop_ops->io)\n\t\tcontext->event_loop_ops->io(wsi,\n\t\t\t\tLWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE);\n\n\tpt->fds_count--;\n}\n\nLWS_VISIBLE void\nlws_plat_service_periodic(struct lws_context *context)\n{\n\t/* if our parent went down, don't linger around */\n\tif (context->started_with_parent &&\n\t    kill(context->started_with_parent, 0) < 0)\n\t\tkill(getpid(), SIGTERM);\n}\n\nLWS_VISIBLE int\nlws_plat_change_pollfd(struct lws_context *context,\n\t\t      struct lws *wsi, struct lws_pollfd *pfd)\n{\n\treturn 0;\n}\n\nLWS_VISIBLE const char *\nlws_plat_inet_ntop(int af, const void *src, char *dst, int cnt)\n{\n\treturn inet_ntop(af, src, dst, cnt);\n}\n\nLWS_VISIBLE int\nlws_plat_inet_pton(int af, const char *src, void *dst)\n{\n\treturn inet_pton(af, src, dst);\n}\n\nLWS_VISIBLE lws_fop_fd_t\n_lws_plat_file_open(const struct lws_plat_file_ops *fops, const char *filename,\n\t\t    const char *vpath, lws_fop_flags_t *flags)\n{\n\tstruct stat stat_buf;\n\tint ret = open(filename, (*flags) & LWS_FOP_FLAGS_MASK, 0664);\n\tlws_fop_fd_t fop_fd;\n\n\tif (ret < 0)\n\t\treturn NULL;\n\n\tif (fstat(ret, &stat_buf) < 0)\n\t\tgoto bail;\n\n\tfop_fd = malloc(sizeof(*fop_fd));\n\tif (!fop_fd)\n\t\tgoto bail;\n\n\tfop_fd->fops = fops;\n\tfop_fd->flags = *flags;\n\tfop_fd->fd = ret;\n\tfop_fd->filesystem_priv = NULL; /* we don't use it */\n\tfop_fd->len = stat_buf.st_size;\n\tfop_fd->pos = 0;\n\n\treturn fop_fd;\n\nbail:\n\tclose(ret);\n\treturn NULL;\n}\n\nLWS_VISIBLE int\n_lws_plat_file_close(lws_fop_fd_t *fop_fd)\n{\n\tint fd = (*fop_fd)->fd;\n\n\tfree(*fop_fd);\n\t*fop_fd = NULL;\n\n\treturn close(fd);\n}\n\nLWS_VISIBLE lws_fileofs_t\n_lws_plat_file_seek_cur(lws_fop_fd_t fop_fd, lws_fileofs_t offset)\n{\n\tlws_fileofs_t r;\n\n\tif (offset > 0 &&\n\t    offset > (lws_fileofs_t)fop_fd->len - (lws_fileofs_t)fop_fd->pos)\n\t\toffset = fop_fd->len - fop_fd->pos;\n\n\tif ((lws_fileofs_t)fop_fd->pos + offset < 0)\n\t\toffset = -fop_fd->pos;\n\n\tr = lseek(fop_fd->fd, offset, SEEK_CUR);\n\n\tif (r >= 0)\n\t\tfop_fd->pos = r;\n\telse\n\t\tlwsl_err(\"error seeking from cur %ld, offset %ld\\n\",\n                        (long)fop_fd->pos, (long)offset);\n\n\treturn r;\n}\n\nLWS_VISIBLE int\n_lws_plat_file_read(lws_fop_fd_t fop_fd, lws_filepos_t *amount,\n\t\t    uint8_t *buf, lws_filepos_t len)\n{\n\tlong n;\n\n\tn = read((int)fop_fd->fd, buf, len);\n\tif (n == -1) {\n\t\t*amount = 0;\n\t\treturn -1;\n\t}\n\tfop_fd->pos += n;\n\tlwsl_debug(\"%s: read %ld of req %ld, pos %ld, len %ld\\n\", __func__, n,\n                  (long)len, (long)fop_fd->pos, (long)fop_fd->len);\n\t*amount = n;\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\n_lws_plat_file_write(lws_fop_fd_t fop_fd, lws_filepos_t *amount,\n\t\t     uint8_t *buf, lws_filepos_t len)\n{\n\tlong n;\n\n\tn = write((int)fop_fd->fd, buf, len);\n\tif (n == -1) {\n\t\t*amount = 0;\n\t\treturn -1;\n\t}\n\n\tfop_fd->pos += n;\n\t*amount = n;\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\nlws_plat_init(struct lws_context *context,\n\t      const struct lws_context_creation_info *info)\n{\n\tint fd;\n\n\t/* master context has the global fd lookup array */\n\tcontext->lws_lookup = lws_zalloc(sizeof(struct lws *) *\n\t\t\t\t\t context->max_fds, \"lws_lookup\");\n\tif (context->lws_lookup == NULL) {\n\t\tlwsl_err(\"OOM on lws_lookup array for %d connections\\n\",\n\t\t\t context->max_fds);\n\t\treturn 1;\n\t}\n\n\tlwsl_info(\" mem: platform fd map: %5lu bytes\\n\",\n\t\t    (unsigned long)(sizeof(struct lws *) * context->max_fds));\n\tfd = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);\n\n\tcontext->fd_random = fd;\n\tif (context->fd_random < 0) {\n\t\tlwsl_err(\"Unable to open random device %s %d\\n\",\n\t\t\t SYSTEM_RANDOM_FILEPATH, context->fd_random);\n\t\treturn 1;\n\t}\n\n#ifdef LWS_WITH_PLUGINS\n\tif (info->plugin_dirs)\n\t\tlws_plat_plugins_init(context, info->plugin_dirs);\n#endif\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\nlws_plat_write_cert(struct lws_vhost *vhost, int is_key, int fd, void *buf,\n\t\t\tint len)\n{\n\tint n;\n\n\tn = write(fd, buf, len);\n\n\tfsync(fd);\n\tlseek(fd, 0, SEEK_SET);\n\n\treturn n != len;\n}\n\nLWS_VISIBLE int\nlws_plat_write_file(const char *filename, void *buf, int len)\n{\n\tint m, fd;\n\n\tfd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);\n\n\tif (fd == -1)\n\t\treturn 1;\n\n\tm = write(fd, buf, len);\n\tclose(fd);\n\n\treturn m != len;\n}\n\nLWS_VISIBLE int\nlws_plat_read_file(const char *filename, void *buf, int len)\n{\n\tint n, fd = lws_open(filename, O_RDONLY);\n\tif (fd == -1)\n\t\treturn -1;\n\n\tn = read(fd, buf, len);\n\tclose(fd);\n\n\treturn n;\n}\n\nLWS_VISIBLE int\nlws_plat_recommended_rsa_bits(void)\n{\n\treturn 4096;\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/plat/lws-plat-win.c",
    "content": "#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS\n#define _WINSOCK_DEPRECATED_NO_WARNINGS\n#endif\n#include \"core/private.h\"\n\nvoid lws_plat_apply_FD_CLOEXEC(int n)\n{\n}\n\nint\nlws_plat_socket_offset(void)\n{\n\treturn 0;\n}\n\nint\nlws_plat_pipe_create(struct lws *wsi)\n{\n\treturn 1;\n}\n\nint\nlws_plat_pipe_signal(struct lws *wsi)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\n\tWSASetEvent(pt->events[0]); /* trigger the cancel event */\n\n\treturn 0;\n}\n\nvoid\nlws_plat_pipe_close(struct lws *wsi)\n{\n}\n\nunsigned long long\ntime_in_microseconds()\n{\n#ifndef DELTA_EPOCH_IN_MICROSECS\n#define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL\n#endif\n\tFILETIME filetime;\n\tULARGE_INTEGER datetime;\n\n#ifdef _WIN32_WCE\n\tGetCurrentFT(&filetime);\n#else\n\tGetSystemTimeAsFileTime(&filetime);\n#endif\n\n\t/*\n\t * As per Windows documentation for FILETIME, copy the resulting\n\t * FILETIME structure to a ULARGE_INTEGER structure using memcpy\n\t * (using memcpy instead of direct assignment can prevent alignment\n\t * faults on 64-bit Windows).\n\t */\n\tmemcpy(&datetime, &filetime, sizeof(datetime));\n\n\t/* Windows file times are in 100s of nanoseconds. */\n\treturn (datetime.QuadPart / 10) - DELTA_EPOCH_IN_MICROSECS;\n}\n\n#ifdef _WIN32_WCE\ntime_t time(time_t *t)\n{\n\ttime_t ret = time_in_microseconds() / 1000000;\n\n\tif(t != NULL)\n\t\t*t = ret;\n\n\treturn ret;\n}\n#endif\n\n/* file descriptor hash management */\n\nstruct lws *\nwsi_from_fd(const struct lws_context *context, lws_sockfd_type fd)\n{\n\tint h = LWS_FD_HASH(fd);\n\tint n = 0;\n\n\tfor (n = 0; n < context->fd_hashtable[h].length; n++)\n\t\tif (context->fd_hashtable[h].wsi[n]->desc.sockfd == fd)\n\t\t\treturn context->fd_hashtable[h].wsi[n];\n\n\treturn NULL;\n}\n\nint\ninsert_wsi(struct lws_context *context, struct lws *wsi)\n{\n\tint h = LWS_FD_HASH(wsi->desc.sockfd);\n\n\tif (context->fd_hashtable[h].length == (getdtablesize() - 1)) {\n\t\tlwsl_err(\"hash table overflow\\n\");\n\t\treturn 1;\n\t}\n\n\tcontext->fd_hashtable[h].wsi[context->fd_hashtable[h].length++] = wsi;\n\n\treturn 0;\n}\n\nint\ndelete_from_fd(struct lws_context *context, lws_sockfd_type fd)\n{\n\tint h = LWS_FD_HASH(fd);\n\tint n = 0;\n\n\tfor (n = 0; n < context->fd_hashtable[h].length; n++)\n\t\tif (context->fd_hashtable[h].wsi[n]->desc.sockfd == fd) {\n\t\t\twhile (n < context->fd_hashtable[h].length) {\n\t\t\t\tcontext->fd_hashtable[h].wsi[n] =\n\t\t\t\t\tcontext->fd_hashtable[h].wsi[n + 1];\n\t\t\t\tn++;\n\t\t\t}\n\t\t\tcontext->fd_hashtable[h].length--;\n\n\t\t\treturn 0;\n\t\t}\n\n\tlwsl_err(\"Failed to find fd %d requested for \"\n\t\t \"delete in hashtable\\n\", fd);\n\treturn 1;\n}\n\nLWS_VISIBLE int\nlws_get_random(struct lws_context *context, void *buf, int len)\n{\n\tint n;\n\tchar *p = (char *)buf;\n\n\tfor (n = 0; n < len; n++)\n\t\tp[n] = (unsigned char)rand();\n\n\treturn n;\n}\n\nLWS_VISIBLE int\nlws_send_pipe_choked(struct lws *wsi)\n{\tstruct lws *wsi_eff = wsi;\n\n#if defined(LWS_WITH_HTTP2)\n\twsi_eff = lws_get_network_wsi(wsi);\n#endif\n\t/* the fact we checked implies we avoided back-to-back writes */\n\twsi_eff->could_have_pending = 0;\n\n\t/* treat the fact we got a truncated send pending as if we're choked */\n\tif (wsi_eff->trunc_len)\n\t\treturn 1;\n\n\treturn (int)wsi_eff->sock_send_blocking;\n}\n\nLWS_VISIBLE int\nlws_poll_listen_fd(struct lws_pollfd *fd)\n{\n\tfd_set readfds;\n\tstruct timeval tv = { 0, 0 };\n\n\tassert((fd->events & LWS_POLLIN) == LWS_POLLIN);\n\n\tFD_ZERO(&readfds);\n\tFD_SET(fd->fd, &readfds);\n\n\treturn select(((int)fd->fd) + 1, &readfds, NULL, NULL, &tv);\n}\n\nLWS_VISIBLE void\nlwsl_emit_syslog(int level, const char *line)\n{\n\tlwsl_emit_stderr(level, line);\n}\n\nLWS_VISIBLE LWS_EXTERN int\n_lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi)\n{\n\tstruct lws_context_per_thread *pt;\n\tWSANETWORKEVENTS networkevents;\n\tstruct lws_pollfd *pfd;\n\tstruct lws *wsi;\n\tunsigned int i;\n\tDWORD ev;\n\tint n, m;\n\n\t/* stay dead once we are dead */\n\tif (context == NULL || !context->vhost_list)\n\t\treturn 1;\n\n\tpt = &context->pt[tsi];\n\n\tif (!context->service_tid_detected) {\n\t\tstruct lws _lws;\n\n\t\tmemset(&_lws, 0, sizeof(_lws));\n\t\t_lws.context = context;\n\n\t\tcontext->service_tid_detected = context->vhost_list->\n\t\t\tprotocols[0].callback(&_lws, LWS_CALLBACK_GET_THREAD_ID,\n\t\t\t\t\t\t  NULL, NULL, 0);\n\t\tcontext->service_tid = context->service_tid_detected;\n\t\tcontext->service_tid_detected = 1;\n\t}\n\n\tif (timeout_ms < 0) {\n\t\tif (lws_service_flag_pending(context, tsi)) {\n\t\t\t/* any socket with events to service? */\n\t\t\tfor (n = 0; n < (int)pt->fds_count; n++) {\n\t\t\t\tif (!pt->fds[n].revents)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tm = lws_service_fd_tsi(context, &pt->fds[n], tsi);\n\t\t\t\tif (m < 0)\n\t\t\t\t\treturn -1;\n\t\t\t\t/* if something closed, retry this slot */\n\t\t\t\tif (m)\n\t\t\t\t\tn--;\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\n\tif (context->event_loop_ops->run_pt)\n\t\tcontext->event_loop_ops->run_pt(context, tsi);\n\n\tfor (i = 0; i < pt->fds_count; ++i) {\n\t\tpfd = &pt->fds[i];\n\n\t\tif (!(pfd->events & LWS_POLLOUT))\n\t\t\tcontinue;\n\n\t\twsi = wsi_from_fd(context, pfd->fd);\n\t\tif (!wsi || wsi->listener)\n\t\t\tcontinue;\n\t\tif (wsi->sock_send_blocking)\n\t\t\tcontinue;\n\t\tpfd->revents = LWS_POLLOUT;\n\t\tn = lws_service_fd(context, pfd);\n\t\tif (n < 0)\n\t\t\treturn -1;\n\n\t\t/* Force WSAWaitForMultipleEvents() to check events and then return immediately. */\n\t\ttimeout_ms = 0;\n\n\t\t/* if something closed, retry this slot */\n\t\tif (n)\n\t\t\ti--;\n\t}\n\n\t/*\n\t * is there anybody with pending stuff that needs service forcing?\n\t */\n\tif (!lws_service_adjust_timeout(context, 1, tsi)) {\n\t\t/* -1 timeout means just do forced service */\n\t\t_lws_plat_service_tsi(context, -1, pt->tid);\n\t\t/* still somebody left who wants forced service? */\n\t\tif (!lws_service_adjust_timeout(context, 1, pt->tid))\n\t\t\t/* yes... come back again quickly */\n\t\t\ttimeout_ms = 0;\n\t}\n\n\tif (timeout_ms) {\n\t\tlws_usec_t t;\n\n\t\tlws_pt_lock(pt, __func__);\n\t\t/* don't stay in poll wait longer than next hr timeout */\n\t\tt =  __lws_hrtimer_service(pt);\n\n\t\tif ((lws_usec_t)timeout_ms * 1000 > t)\n\t\t\ttimeout_ms = (int)(t / 1000);\n\t\tlws_pt_unlock(pt);\n\t}\n\n\tev = WSAWaitForMultipleEvents(1, pt->events, FALSE, timeout_ms, FALSE);\n\tif (ev == WSA_WAIT_EVENT_0) {\n\t\tunsigned int eIdx, err;\n\n\t\tWSAResetEvent(pt->events[0]);\n\n\t\tif (pt->context->tls_ops &&\n\t\t    pt->context->tls_ops->fake_POLLIN_for_buffered)\n\t\t\tpt->context->tls_ops->fake_POLLIN_for_buffered(pt);\n\n\t\tfor (eIdx = 0; eIdx < pt->fds_count; ++eIdx) {\n\t\t\tif (WSAEnumNetworkEvents(pt->fds[eIdx].fd, 0,\n\t\t\t\t\t&networkevents) == SOCKET_ERROR) {\n\t\t\t\tlwsl_err(\"WSAEnumNetworkEvents() failed \"\n\t\t\t\t\t \"with error %d\\n\", LWS_ERRNO);\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tpfd = &pt->fds[eIdx];\n\t\t\tpfd->revents = (short)networkevents.lNetworkEvents;\n\n\t\t\terr = networkevents.iErrorCode[FD_CONNECT_BIT];\n\n\t\t\tif ((networkevents.lNetworkEvents & FD_CONNECT) &&\n\t\t\t     err && err != LWS_EALREADY &&\n\t\t\t     err != LWS_EINPROGRESS && err != LWS_EWOULDBLOCK &&\n\t\t\t     err != WSAEINVAL) {\n\t\t\t\tlwsl_debug(\"Unable to connect errno=%d\\n\", err);\n\t\t\t\tpfd->revents |= LWS_POLLHUP;\n\t\t\t}\n\n\t\t\tif (pfd->revents & LWS_POLLOUT) {\n\t\t\t\twsi = wsi_from_fd(context, pfd->fd);\n\t\t\t\tif (wsi)\n\t\t\t\t\twsi->sock_send_blocking = 0;\n\t\t\t}\n\t\t\t /* if something closed, retry this slot */\n\t\t\tif (pfd->revents & LWS_POLLHUP)\n\t\t\t\t--eIdx;\n\n\t\t\tif (pfd->revents) {\n\t\t\t\trecv(pfd->fd, NULL, 0, 0);\n\t\t\t\tlws_service_fd_tsi(context, pfd, tsi);\n\t\t\t}\n\t\t}\n\t}\n\n\tcontext->service_tid = 0;\n\n\tif (ev == WSA_WAIT_TIMEOUT)\n\t\tlws_service_fd(context, NULL);\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\nlws_plat_service(struct lws_context *context, int timeout_ms)\n{\n\treturn _lws_plat_service_tsi(context, timeout_ms, 0);\n}\n\nLWS_VISIBLE int\nlws_plat_set_socket_options(struct lws_vhost *vhost, lws_sockfd_type fd)\n{\n\tint optval = 1;\n\tint optlen = sizeof(optval);\n\tu_long optl = 1;\n\tDWORD dwBytesRet;\n\tstruct tcp_keepalive alive;\n\tint protonbr;\n#ifndef _WIN32_WCE\n\tstruct protoent *tcp_proto;\n#endif\n\n\tif (vhost->ka_time) {\n\t\t/* enable keepalive on this socket */\n\t\toptval = 1;\n\t\tif (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,\n\t\t\t       (const char *)&optval, optlen) < 0)\n\t\t\treturn 1;\n\n\t\talive.onoff = TRUE;\n\t\talive.keepalivetime = vhost->ka_time;\n\t\talive.keepaliveinterval = vhost->ka_interval;\n\n\t\tif (WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive, sizeof(alive),\n\t\t\t     NULL, 0, &dwBytesRet, NULL, NULL))\n\t\t\treturn 1;\n\t}\n\n\t/* Disable Nagle */\n\toptval = 1;\n#ifndef _WIN32_WCE\n\ttcp_proto = getprotobyname(\"TCP\");\n\tif (!tcp_proto) {\n\t\tlwsl_err(\"getprotobyname() failed with error %d\\n\", LWS_ERRNO);\n\t\treturn 1;\n\t}\n\tprotonbr = tcp_proto->p_proto;\n#else\n\tprotonbr = 6;\n#endif\n\n\tsetsockopt(fd, protonbr, TCP_NODELAY, (const char *)&optval, optlen);\n\n\t/* We are nonblocking... */\n\tioctlsocket(fd, FIONBIO, &optl);\n\n\treturn 0;\n}\n\nLWS_VISIBLE void\nlws_plat_drop_app_privileges(const struct lws_context_creation_info *info)\n{\n}\n\nLWS_VISIBLE int\nlws_plat_context_early_init(void)\n{\n\tWORD wVersionRequested;\n\tWSADATA wsaData;\n\tint err;\n\n\t/* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */\n\twVersionRequested = MAKEWORD(2, 2);\n\n\terr = WSAStartup(wVersionRequested, &wsaData);\n\tif (!err)\n\t\treturn 0;\n\t/*\n\t * Tell the user that we could not find a usable\n\t * Winsock DLL\n\t */\n\tlwsl_err(\"WSAStartup failed with error: %d\\n\", err);\n\n\treturn 1;\n}\n\nLWS_VISIBLE void\nlws_plat_context_early_destroy(struct lws_context *context)\n{\n\tstruct lws_context_per_thread *pt = &context->pt[0];\n\tint n = context->count_threads;\n\n\twhile (n--) {\n\t\tif (pt->events) {\n\t\t\tWSACloseEvent(pt->events[0]);\n\t\t\tlws_free(pt->events);\n\t\t}\n\t\tpt++;\n\t}\n}\n\nLWS_VISIBLE void\nlws_plat_context_late_destroy(struct lws_context *context)\n{\n\tint n;\n\n\tfor (n = 0; n < FD_HASHTABLE_MODULUS; n++) {\n\t\tif (context->fd_hashtable[n].wsi)\n\t\t\tlws_free(context->fd_hashtable[n].wsi);\n\t}\n\n\tWSACleanup();\n}\n\nLWS_VISIBLE LWS_EXTERN int\nlws_interface_to_sa(int ipv6,\n\t\tconst char *ifname, struct sockaddr_in *addr, size_t addrlen)\n{\n#ifdef LWS_WITH_IPV6\n\tstruct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;\n\n\tif (ipv6) {\n\t\tif (lws_plat_inet_pton(AF_INET6, ifname, &addr6->sin6_addr) == 1) {\n\t\t\treturn LWS_ITOSA_USABLE;\n\t\t}\n\t}\n#endif\n\n\tlong long address = inet_addr(ifname);\n\n\tif (address == INADDR_NONE) {\n\t\tstruct hostent *entry = gethostbyname(ifname);\n\t\tif (entry)\n\t\t\taddress = ((struct in_addr *)entry->h_addr_list[0])->s_addr;\n\t}\n\n\tif (address == INADDR_NONE)\n\t\treturn LWS_ITOSA_NOT_EXIST;\n\n\taddr->sin_addr.s_addr = (unsigned long)(lws_intptr_t)address;\n\n\treturn LWS_ITOSA_USABLE;\n}\n\nLWS_VISIBLE void\nlws_plat_insert_socket_into_fds(struct lws_context *context, struct lws *wsi)\n{\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\n\tpt->fds[pt->fds_count++].revents = 0;\n\tpt->events[pt->fds_count] = pt->events[0];\n\tWSAEventSelect(wsi->desc.sockfd, pt->events[0],\n\t\t\t   LWS_POLLIN | LWS_POLLHUP | FD_CONNECT);\n}\n\nLWS_VISIBLE void\nlws_plat_delete_socket_from_fds(struct lws_context *context,\n\t\t\t\t\t\tstruct lws *wsi, int m)\n{\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\n\tpt->events[m + 1] = pt->events[pt->fds_count--];\n}\n\nLWS_VISIBLE void\nlws_plat_service_periodic(struct lws_context *context)\n{\n}\n\nLWS_VISIBLE int\nlws_plat_check_connection_error(struct lws *wsi)\n{\n\tint optVal;\n\tint optLen = sizeof(int);\n\n\tif (getsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_ERROR,\n\t\t\t   (char*)&optVal, &optLen) != SOCKET_ERROR && optVal &&\n\t\toptVal != LWS_EALREADY && optVal != LWS_EINPROGRESS &&\n\t\toptVal != LWS_EWOULDBLOCK && optVal != WSAEINVAL) {\n\t\t   lwsl_debug(\"Connect failed SO_ERROR=%d\\n\", optVal);\n\t\t   return 1;\n\t}\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\nlws_plat_change_pollfd(struct lws_context *context,\n\t\t\t  struct lws *wsi, struct lws_pollfd *pfd)\n{\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tlong networkevents = LWS_POLLHUP | FD_CONNECT;\n\n\tif ((pfd->events & LWS_POLLIN))\n\t\tnetworkevents |= LWS_POLLIN;\n\n\tif ((pfd->events & LWS_POLLOUT))\n\t\tnetworkevents |= LWS_POLLOUT;\n\n\tif (WSAEventSelect(wsi->desc.sockfd,\n\t\t\tpt->events[0],\n\t\t\t\t\t\t   networkevents) != SOCKET_ERROR)\n\t\treturn 0;\n\n\tlwsl_err(\"WSAEventSelect() failed with error %d\\n\", LWS_ERRNO);\n\n\treturn 1;\n}\n\nLWS_VISIBLE const char *\nlws_plat_inet_ntop(int af, const void *src, char *dst, int cnt)\n{\n\tWCHAR *buffer;\n\tDWORD bufferlen = cnt;\n\tBOOL ok = FALSE;\n\n\tbuffer = lws_malloc(bufferlen * 2, \"inet_ntop\");\n\tif (!buffer) {\n\t\tlwsl_err(\"Out of memory\\n\");\n\t\treturn NULL;\n\t}\n\n\tif (af == AF_INET) {\n\t\tstruct sockaddr_in srcaddr;\n\t\tbzero(&srcaddr, sizeof(srcaddr));\n\t\tsrcaddr.sin_family = AF_INET;\n\t\tmemcpy(&(srcaddr.sin_addr), src, sizeof(srcaddr.sin_addr));\n\n\t\tif (!WSAAddressToStringW((struct sockaddr*)&srcaddr, sizeof(srcaddr), 0, buffer, &bufferlen))\n\t\t\tok = TRUE;\n#ifdef LWS_WITH_IPV6\n\t} else if (af == AF_INET6) {\n\t\tstruct sockaddr_in6 srcaddr;\n\t\tbzero(&srcaddr, sizeof(srcaddr));\n\t\tsrcaddr.sin6_family = AF_INET6;\n\t\tmemcpy(&(srcaddr.sin6_addr), src, sizeof(srcaddr.sin6_addr));\n\n\t\tif (!WSAAddressToStringW((struct sockaddr*)&srcaddr, sizeof(srcaddr), 0, buffer, &bufferlen))\n\t\t\tok = TRUE;\n#endif\n\t} else\n\t\tlwsl_err(\"Unsupported type\\n\");\n\n\tif (!ok) {\n\t\tint rv = WSAGetLastError();\n\t\tlwsl_err(\"WSAAddressToString() : %d\\n\", rv);\n\t} else {\n\t\tif (WideCharToMultiByte(CP_ACP, 0, buffer, bufferlen, dst, cnt, 0, NULL) <= 0)\n\t\t\tok = FALSE;\n\t}\n\n\tlws_free(buffer);\n\treturn ok ? dst : NULL;\n}\n\nLWS_VISIBLE int\nlws_plat_inet_pton(int af, const char *src, void *dst)\n{\n\tWCHAR *buffer;\n\tDWORD bufferlen = (int)strlen(src) + 1;\n\tBOOL ok = FALSE;\n\n\tbuffer = lws_malloc(bufferlen * 2, \"inet_pton\");\n\tif (!buffer) {\n\t\tlwsl_err(\"Out of memory\\n\");\n\t\treturn -1;\n\t}\n\n\tif (MultiByteToWideChar(CP_ACP, 0, src, bufferlen, buffer, bufferlen) <= 0) {\n\t\tlwsl_err(\"Failed to convert multi byte to wide char\\n\");\n\t\tlws_free(buffer);\n\t\treturn -1;\n\t}\n\n\tif (af == AF_INET) {\n\t\tstruct sockaddr_in dstaddr;\n\t\tint dstaddrlen = sizeof(dstaddr);\n\t\tbzero(&dstaddr, sizeof(dstaddr));\n\t\tdstaddr.sin_family = AF_INET;\n\n\t\tif (!WSAStringToAddressW(buffer, af, 0, (struct sockaddr *) &dstaddr, &dstaddrlen)) {\n\t\t\tok = TRUE;\n\t\t\tmemcpy(dst, &dstaddr.sin_addr, sizeof(dstaddr.sin_addr));\n\t\t}\n#ifdef LWS_WITH_IPV6\n\t} else if (af == AF_INET6) {\n\t\tstruct sockaddr_in6 dstaddr;\n\t\tint dstaddrlen = sizeof(dstaddr);\n\t\tbzero(&dstaddr, sizeof(dstaddr));\n\t\tdstaddr.sin6_family = AF_INET6;\n\n\t\tif (!WSAStringToAddressW(buffer, af, 0, (struct sockaddr *) &dstaddr, &dstaddrlen)) {\n\t\t\tok = TRUE;\n\t\t\tmemcpy(dst, &dstaddr.sin6_addr, sizeof(dstaddr.sin6_addr));\n\t\t}\n#endif\n\t} else\n\t\tlwsl_err(\"Unsupported type\\n\");\n\n\tif (!ok) {\n\t\tint rv = WSAGetLastError();\n\t\tlwsl_err(\"WSAAddressToString() : %d\\n\", rv);\n\t}\n\n\tlws_free(buffer);\n\treturn ok ? 1 : -1;\n}\n\nLWS_VISIBLE lws_fop_fd_t\n_lws_plat_file_open(const struct lws_plat_file_ops *fops, const char *filename,\n\t\t    const char *vpath, lws_fop_flags_t *flags)\n{\n\tHANDLE ret;\n\tWCHAR buf[MAX_PATH];\n\tlws_fop_fd_t fop_fd;\n\tFILE_STANDARD_INFO fInfo = {0};\n\n\tMultiByteToWideChar(CP_UTF8, 0, filename, -1, buf, LWS_ARRAY_SIZE(buf));\n\n#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0602 // Windows 8 (minimum when UWP_ENABLED, but can be used in Windows builds)\n\tCREATEFILE2_EXTENDED_PARAMETERS extParams = {0};\n\textParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;\n\n\tif (((*flags) & 7) == _O_RDONLY) {\n\t\tret = CreateFile2(buf, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &extParams);\n\t} else {\n\t\tret = CreateFile2(buf, GENERIC_WRITE, 0, CREATE_ALWAYS, &extParams);\n\t}\n#else\n\tif (((*flags) & 7) == _O_RDONLY) {\n\t\tret = CreateFileW(buf, GENERIC_READ, FILE_SHARE_READ,\n\t\t\t  NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n\t} else {\n\t\tret = CreateFileW(buf, GENERIC_WRITE, 0, NULL,\n\t\t\t  CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n\t}\n#endif\n\n\tif (ret == LWS_INVALID_FILE)\n\t\tgoto bail;\n\n\tfop_fd = malloc(sizeof(*fop_fd));\n\tif (!fop_fd)\n\t\tgoto bail;\n\n\tfop_fd->fops = fops;\n\tfop_fd->fd = ret;\n\tfop_fd->filesystem_priv = NULL; /* we don't use it */\n\tfop_fd->flags = *flags;\n\tfop_fd->len = 0;\n\tif(GetFileInformationByHandleEx(ret, FileStandardInfo, &fInfo, sizeof(fInfo)))\n\t\tfop_fd->len = fInfo.EndOfFile.QuadPart;\n\n\tfop_fd->pos = 0;\n\n\treturn fop_fd;\n\nbail:\n\treturn NULL;\n}\n\nLWS_VISIBLE int\n_lws_plat_file_close(lws_fop_fd_t *fop_fd)\n{\n\tHANDLE fd = (*fop_fd)->fd;\n\n\tfree(*fop_fd);\n\t*fop_fd = NULL;\n\n\tCloseHandle((HANDLE)fd);\n\n\treturn 0;\n}\n\nLWS_VISIBLE lws_fileofs_t\n_lws_plat_file_seek_cur(lws_fop_fd_t fop_fd, lws_fileofs_t offset)\n{\n\tLARGE_INTEGER l;\n\n\tl.QuadPart = offset;\n\treturn SetFilePointerEx((HANDLE)fop_fd->fd, l, NULL, FILE_CURRENT);\n}\n\nLWS_VISIBLE int\n_lws_plat_file_read(lws_fop_fd_t fop_fd, lws_filepos_t *amount,\n\t\t    uint8_t *buf, lws_filepos_t len)\n{\n\tDWORD _amount;\n\n\tif (!ReadFile((HANDLE)fop_fd->fd, buf, (DWORD)len, &_amount, NULL)) {\n\t\t*amount = 0;\n\n\t\treturn 1;\n\t}\n\n\tfop_fd->pos += _amount;\n\t*amount = (unsigned long)_amount;\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\n_lws_plat_file_write(lws_fop_fd_t fop_fd, lws_filepos_t *amount,\n\t\t\t uint8_t* buf, lws_filepos_t len)\n{\n\tDWORD _amount;\n\n\tif (!WriteFile((HANDLE)fop_fd->fd, buf, (DWORD)len, &_amount, NULL)) {\n\t\t*amount = 0;\n\n\t\treturn 1;\n\t}\n\n\tfop_fd->pos += _amount;\n\t*amount = (unsigned long)_amount;\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\nlws_plat_init(struct lws_context *context,\n\t      const struct lws_context_creation_info *info)\n{\n\tstruct lws_context_per_thread *pt = &context->pt[0];\n\tint i, n = context->count_threads;\n\n\tfor (i = 0; i < FD_HASHTABLE_MODULUS; i++) {\n\t\tcontext->fd_hashtable[i].wsi =\n\t\t\tlws_zalloc(sizeof(struct lws*) * context->max_fds, \"win hashtable\");\n\n\t\tif (!context->fd_hashtable[i].wsi)\n\t\t\treturn -1;\n\t}\n\n\twhile (n--) {\n\t\tpt->events = lws_malloc(sizeof(WSAEVENT) *\n\t\t\t\t\t(context->fd_limit_per_thread + 1), \"event table\");\n\t\tif (pt->events == NULL) {\n\t\t\tlwsl_err(\"Unable to allocate events array for %d connections\\n\",\n\t\t\t\t\tcontext->fd_limit_per_thread + 1);\n\t\t\treturn 1;\n\t\t}\n\n\t\tpt->fds_count = 0;\n\t\tpt->events[0] = WSACreateEvent(); /* the cancel event */\n\n\t\tpt++;\n\t}\n\n\tcontext->fd_random = 0;\n\n#ifdef LWS_WITH_PLUGINS\n\tif (info->plugin_dirs)\n\t\tlws_plat_plugins_init(context, info->plugin_dirs);\n#endif\n\n\treturn 0;\n}\n\n\nint kill(int pid, int sig)\n{\n\tlwsl_err(\"Sorry Windows doesn't support kill().\");\n\texit(0);\n}\n\nint fork(void)\n{\n\tlwsl_err(\"Sorry Windows doesn't support fork().\");\n\texit(0);\n}\n\nLWS_VISIBLE int\nlws_plat_write_cert(struct lws_vhost *vhost, int is_key, int fd, void *buf,\n\t\t\tint len)\n{\n\tint n;\n\n\tn = write(fd, buf, len);\n\n\tlseek(fd, 0, SEEK_SET);\n\n\treturn n != len;\n}\n\nLWS_VISIBLE int\nlws_plat_write_file(const char *filename, void *buf, int len)\n{\n\tint m, fd;\n\n\tfd = lws_open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);\n\n\tif (fd == -1)\n\t\treturn -1;\n\n\tm = write(fd, buf, len);\n\tclose(fd);\n\n\treturn m != len;\n}\n\nLWS_VISIBLE int\nlws_plat_read_file(const char *filename, void *buf, int len)\n{\n\tint n, fd = lws_open(filename, O_RDONLY);\n\tif (fd == -1)\n\t\treturn -1;\n\n\tn = read(fd, buf, len);\n\tclose(fd);\n\n\treturn n;\n}\n\nLWS_VISIBLE int\nlws_plat_recommended_rsa_bits(void)\n{\n\treturn 4096;\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/h1/ops-h1.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include <core/private.h>\n\n#ifndef min\n#define min(a, b) ((a) < (b) ? (a) : (b))\n#endif\n\n\n/*\n * We have to take care about parsing because the headers may be split\n * into multiple fragments.  They may contain unknown headers with arbitrary\n * argument lengths.  So, we parse using a single-character at a time state\n * machine that is completely independent of packet size.\n *\n * Returns <0 for error or length of chars consumed from buf (up to len)\n */\n\nint\nlws_read_h1(struct lws *wsi, unsigned char *buf, lws_filepos_t len)\n{\n\tunsigned char *last_char, *oldbuf = buf;\n\tlws_filepos_t body_chunk_len;\n\tsize_t n;\n\n\t// lwsl_notice(\"%s: h1 path: wsi state 0x%x\\n\", __func__, lwsi_state(wsi));\n\n\tswitch (lwsi_state(wsi)) {\n\n\tcase LRS_ISSUING_FILE:\n\t\treturn 0;\n\n\tcase LRS_ESTABLISHED:\n\n\t\tif (lwsi_role_ws(wsi))\n\t\t\tgoto ws_mode;\n\n\t\tif (lwsi_role_client(wsi))\n\t\t\tbreak;\n\n\t\twsi->hdr_parsing_completed = 0;\n\n\t\t/* fallthru */\n\n\tcase LRS_HEADERS:\n\t\tif (!wsi->http.ah) {\n\t\t\tlwsl_err(\"%s: LRS_HEADERS: NULL ah\\n\", __func__);\n\t\t\tassert(0);\n\t\t}\n\t\tlwsl_parser(\"issuing %d bytes to parser\\n\", (int)len);\n#if defined(LWS_ROLE_WS) && !defined(LWS_NO_CLIENT)\n\t\tif (lws_ws_handshake_client(wsi, &buf, (size_t)len))\n\t\t\tgoto bail;\n#endif\n\t\tlast_char = buf;\n\t\tif (lws_handshake_server(wsi, &buf, (size_t)len))\n\t\t\t/* Handshake indicates this session is done. */\n\t\t\tgoto bail;\n\n\t\t/* we might have transitioned to RAW */\n\t\tif (wsi->role_ops == &role_ops_raw_skt ||\n\t\t    wsi->role_ops == &role_ops_raw_file)\n\t\t\t /* we gave the read buffer to RAW handler already */\n\t\t\tgoto read_ok;\n\n\t\t/*\n\t\t * It's possible that we've exhausted our data already, or\n\t\t * rx flow control has stopped us dealing with this early,\n\t\t * but lws_handshake_server doesn't update len for us.\n\t\t * Figure out how much was read, so that we can proceed\n\t\t * appropriately:\n\t\t */\n\t\tlen -= (buf - last_char);\n//\t\tlwsl_debug(\"%s: thinks we have used %ld\\n\", __func__, (long)len);\n\n\t\tif (!wsi->hdr_parsing_completed)\n\t\t\t/* More header content on the way */\n\t\t\tgoto read_ok;\n\n\t\tswitch (lwsi_state(wsi)) {\n\t\t\tcase LRS_ESTABLISHED:\n\t\t\tcase LRS_HEADERS:\n\t\t\t\tgoto read_ok;\n\t\t\tcase LRS_ISSUING_FILE:\n\t\t\t\tgoto read_ok;\n\t\t\tcase LRS_BODY:\n\t\t\t\twsi->http.rx_content_remain =\n\t\t\t\t\t\twsi->http.rx_content_length;\n\t\t\t\tif (wsi->http.rx_content_remain)\n\t\t\t\t\tgoto http_postbody;\n\n\t\t\t\t/* there is no POST content */\n\t\t\t\tgoto postbody_completion;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n\tcase LRS_BODY:\nhttp_postbody:\n\t\tlwsl_debug(\"%s: http post body: remain %d\\n\", __func__,\n\t\t\t    (int)wsi->http.rx_content_remain);\n\t\twhile (len && wsi->http.rx_content_remain) {\n\t\t\t/* Copy as much as possible, up to the limit of:\n\t\t\t * what we have in the read buffer (len)\n\t\t\t * remaining portion of the POST body (content_remain)\n\t\t\t */\n\t\t\tbody_chunk_len = min(wsi->http.rx_content_remain, len);\n\t\t\twsi->http.rx_content_remain -= body_chunk_len;\n\t\t\tlen -= body_chunk_len;\n#ifdef LWS_WITH_CGI\n\t\t\tif (wsi->http.cgi) {\n\t\t\t\tstruct lws_cgi_args args;\n\n\t\t\t\targs.ch = LWS_STDIN;\n\t\t\t\targs.stdwsi = &wsi->http.cgi->stdwsi[0];\n\t\t\t\targs.data = buf;\n\t\t\t\targs.len = body_chunk_len;\n\n\t\t\t\t/* returns how much used */\n\t\t\t\tn = user_callback_handle_rxflow(\n\t\t\t\t\twsi->protocol->callback,\n\t\t\t\t\twsi, LWS_CALLBACK_CGI_STDIN_DATA,\n\t\t\t\t\twsi->user_space,\n\t\t\t\t\t(void *)&args, 0);\n\t\t\t\tif ((int)n < 0)\n\t\t\t\t\tgoto bail;\n\t\t\t} else {\n#endif\n\t\t\t\tn = wsi->protocol->callback(wsi,\n\t\t\t\t\tLWS_CALLBACK_HTTP_BODY, wsi->user_space,\n\t\t\t\t\tbuf, (size_t)body_chunk_len);\n\t\t\t\tif (n)\n\t\t\t\t\tgoto bail;\n\t\t\t\tn = (size_t)body_chunk_len;\n#ifdef LWS_WITH_CGI\n\t\t\t}\n#endif\n\t\t\tbuf += n;\n\n\t\t\tif (wsi->http.rx_content_remain)  {\n\t\t\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,\n\t\t\t\t\t\twsi->context->timeout_secs);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* he sent all the content in time */\npostbody_completion:\n#ifdef LWS_WITH_CGI\n\t\t\t/*\n\t\t\t * If we're running a cgi, we can't let him off the\n\t\t\t * hook just because he sent his POST data\n\t\t\t */\n\t\t\tif (wsi->http.cgi)\n\t\t\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_CGI,\n\t\t\t\t\t\twsi->context->timeout_secs);\n\t\t\telse\n#endif\n\t\t\tlws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);\n#ifdef LWS_WITH_CGI\n\t\t\tif (!wsi->http.cgi)\n#endif\n\t\t\t{\n\t\t\t\tlwsl_info(\"HTTP_BODY_COMPLETION: %p (%s)\\n\",\n\t\t\t\t\t  wsi, wsi->protocol->name);\n\t\t\t\tn = wsi->protocol->callback(wsi,\n\t\t\t\t\tLWS_CALLBACK_HTTP_BODY_COMPLETION,\n\t\t\t\t\twsi->user_space, NULL, 0);\n\t\t\t\tif (n)\n\t\t\t\t\tgoto bail;\n\n\t\t\t\tif (wsi->http2_substream)\n\t\t\t\t\tlwsi_set_state(wsi, LRS_ESTABLISHED);\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n\tcase LRS_RETURNED_CLOSE:\n\tcase LRS_AWAITING_CLOSE_ACK:\n\tcase LRS_WAITING_TO_SEND_CLOSE:\n\tcase LRS_SHUTDOWN:\n\nws_mode:\n#if !defined(LWS_NO_CLIENT) && defined(LWS_ROLE_WS)\n\t\t// lwsl_notice(\"%s: ws_mode\\n\", __func__);\n\t\tif (lws_ws_handshake_client(wsi, &buf, (size_t)len))\n\t\t\tgoto bail;\n#endif\n#if defined(LWS_ROLE_WS)\n\t\tif (lwsi_role_ws(wsi) && lwsi_role_server(wsi) &&\n\t\t\t/*\n\t\t\t * for h2 we are on the swsi\n\t\t\t */\n\t\t    lws_parse_ws(wsi, &buf, (size_t)len) < 0) {\n\t\t\tlwsl_info(\"%s: lws_parse_ws bailed\\n\", __func__);\n\t\t\tgoto bail;\n\t\t}\n#endif\n\t\t// lwsl_notice(\"%s: ws_mode: buf moved on by %d\\n\", __func__,\n\t\t//\t       lws_ptr_diff(buf, oldbuf));\n\t\tbreak;\n\n\tcase LRS_DEFERRING_ACTION:\n\t\tlwsl_debug(\"%s: LRS_DEFERRING_ACTION\\n\", __func__);\n\t\tbreak;\n\n\tcase LRS_SSL_ACK_PENDING:\n\t\tbreak;\n\n\tcase LRS_DEAD_SOCKET:\n\t\tlwsl_err(\"%s: Unhandled state LRS_DEAD_SOCKET\\n\", __func__);\n\t\tgoto bail;\n\t\t// assert(0);\n\t\t/* fallthru */\n\n\tdefault:\n\t\tlwsl_err(\"%s: Unhandled state %d\\n\", __func__, lwsi_state(wsi));\n\t\tassert(0);\n\t\tgoto bail;\n\t}\n\nread_ok:\n\t/* Nothing more to do for now */\n//\tlwsl_info(\"%s: %p: read_ok, used %ld (len %d, state %d)\\n\", __func__,\n//\t\t  wsi, (long)(buf - oldbuf), (int)len, wsi->state);\n\n\treturn lws_ptr_diff(buf, oldbuf);\n\nbail:\n\t/*\n\t * h2 / h2-ws calls us recursively in\n\t *\n\t * lws_read_h1()->\n\t *   lws_h2_parser()->\n\t *     lws_read_h1()\n\t *\n\t * pattern, having stripped the h2 framing in the middle.\n\t *\n\t * When taking down the whole connection, make sure that only the\n\t * outer lws_read() does the wsi close.\n\t */\n\tif (!wsi->outer_will_close)\n\t\tlws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS,\n\t\t\t\t   \"lws_read_h1 bail\");\n\n\treturn -1;\n}\n#if !defined(LWS_NO_SERVER)\nstatic int\nlws_h1_server_socket_service(struct lws *wsi, struct lws_pollfd *pollfd)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tstruct lws_tokens ebuf;\n\tint n, buffered;\n\n\tif (lwsi_state(wsi) == LRS_DEFERRING_ACTION)\n\t\tgoto try_pollout;\n\n\t/* any incoming data ready? */\n\n\tif (!(pollfd->revents & pollfd->events & LWS_POLLIN))\n\t\tgoto try_pollout;\n\n\t/*\n\t * If we previously just did POLLIN when IN and OUT were signaled\n\t * (because POLLIN processing may have used up the POLLOUT), don't let\n\t * that happen twice in a row... next time we see the situation favour\n\t * POLLOUT\n\t */\n\n\tif (wsi->favoured_pollin &&\n\t    (pollfd->revents & pollfd->events & LWS_POLLOUT)) {\n\t\t// lwsl_notice(\"favouring pollout\\n\");\n\t\twsi->favoured_pollin = 0;\n\t\tgoto try_pollout;\n\t}\n\n\t/*\n\t * We haven't processed that the tunnel is set up yet, so\n\t * defer reading\n\t */\n\n\tif (lwsi_state(wsi) == LRS_SSL_ACK_PENDING)\n\t\treturn LWS_HPI_RET_HANDLED;\n\n\t/* these states imply we MUST have an ah attached */\n\n\tif ((lwsi_state(wsi) == LRS_ESTABLISHED ||\n\t     lwsi_state(wsi) == LRS_ISSUING_FILE ||\n\t     lwsi_state(wsi) == LRS_HEADERS ||\n\t     lwsi_state(wsi) == LRS_BODY)) {\n\n\t\tif (!wsi->http.ah && lws_header_table_attach(wsi, 0)) {\n\t\t\tlwsl_info(\"%s: wsi %p: ah not available\\n\", __func__, wsi);\n\t\t\tgoto try_pollout;\n\t\t}\n\n\t\t/*\n\t\t * We got here because there was specifically POLLIN...\n\t\t * regardless of our buflist state, we need to get it,\n\t\t * and either use it, or append to the buflist and use\n\t\t * buflist head material.\n\t\t *\n\t\t * We will not notice a connection close until the buflist is\n\t\t * exhausted and we tried to do a read of some kind.\n\t\t */\n\n\t\tbuffered = lws_buflist_aware_read(pt, wsi, &ebuf);\n\t\tswitch (ebuf.len) {\n\t\tcase 0:\n\t\t\tlwsl_info(\"%s: read 0 len a\\n\", __func__);\n\t\t\twsi->seen_zero_length_recv = 1;\n\t\t\tlws_change_pollfd(wsi, LWS_POLLIN, 0);\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\t\t/*\n\t\t\t * autobahn requires us to win the race between close\n\t\t\t * and draining the extensions\n\t\t\t */\n\t\t\tif (wsi->ws &&\n\t\t\t    (wsi->ws->rx_draining_ext || wsi->ws->tx_draining_ext))\n\t\t\t\tgoto try_pollout;\n#endif\n\t\t\t/*\n\t\t\t * normally, we respond to close with logically closing\n\t\t\t * our side immediately\n\t\t\t */\n\t\t\tgoto fail;\n\n\t\tcase LWS_SSL_CAPABLE_ERROR:\n\t\t\tgoto fail;\n\t\tcase LWS_SSL_CAPABLE_MORE_SERVICE:\n\t\t\tgoto try_pollout;\n\t\t}\n\n\t\t/* just ignore incoming if waiting for close */\n\t\tif (lwsi_state(wsi) == LRS_FLUSHING_BEFORE_CLOSE) {\n\t\t\tlwsl_notice(\"%s: just ignoring\\n\", __func__);\n\t\t\tgoto try_pollout;\n\t\t}\n\n\t\tif (lwsi_state(wsi) == LRS_ISSUING_FILE) {\n\t\t\t// lwsl_notice(\"stashing: wsi %p: bd %d\\n\", wsi, buffered);\n\t\t\tif (lws_buflist_aware_consume(wsi, &ebuf, 0, buffered))\n\t\t\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\n\t\t\tgoto try_pollout;\n\t\t}\n\n\t\t/*\n\t\t * Otherwise give it to whoever wants it according to the\n\t\t * connection state\n\t\t */\n#if defined(LWS_ROLE_H2)\n\t\tif (lwsi_role_h2(wsi) && lwsi_state(wsi) != LRS_BODY)\n\t\t\tn = lws_read_h2(wsi, (uint8_t *)ebuf.token, ebuf.len);\n\t\telse\n#endif\n\t\t\tn = lws_read_h1(wsi, (uint8_t *)ebuf.token, ebuf.len);\n\t\tif (n < 0) /* we closed wsi */\n\t\t\treturn LWS_HPI_RET_WSI_ALREADY_DIED;\n\n\t\tlwsl_debug(\"%s: consumed %d\\n\", __func__, n);\n\n\t\tif (lws_buflist_aware_consume(wsi, &ebuf, n, buffered))\n\t\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\n\t\t/*\n\t\t * during the parsing our role changed to something non-http,\n\t\t * so the ah has no further meaning\n\t\t */\n\n\t\tif (wsi->http.ah &&\n\t\t    !lwsi_role_h1(wsi) &&\n\t\t    !lwsi_role_h2(wsi) &&\n\t\t    !lwsi_role_cgi(wsi))\n\t\t\tlws_header_table_detach(wsi, 0);\n\n\t\t/*\n\t\t * He may have used up the writability above, if we will defer\n\t\t * POLLOUT processing in favour of POLLIN, note it\n\t\t */\n\n\t\tif (pollfd->revents & LWS_POLLOUT)\n\t\t\twsi->favoured_pollin = 1;\n\n\t\treturn LWS_HPI_RET_HANDLED;\n\t}\n\n\t/*\n\t * He may have used up the writability above, if we will defer POLLOUT\n\t * processing in favour of POLLIN, note it\n\t */\n\n\tif (pollfd->revents & LWS_POLLOUT)\n\t\twsi->favoured_pollin = 1;\n\ntry_pollout:\n\n\t/* this handles POLLOUT for http serving fragments */\n\n\tif (!(pollfd->revents & LWS_POLLOUT))\n\t\treturn LWS_HPI_RET_HANDLED;\n\n\t/* one shot */\n\tif (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {\n\t\tlwsl_notice(\"%s a\\n\", __func__);\n\t\tgoto fail;\n\t}\n\n\t/* clear back-to-back write detection */\n\twsi->could_have_pending = 0;\n\n\tif (lwsi_state(wsi) == LRS_DEFERRING_ACTION) {\n\t\tlwsl_debug(\"%s: LRS_DEFERRING_ACTION now writable\\n\", __func__);\n\n\t\tlwsi_set_state(wsi, LRS_ESTABLISHED);\n\t\tif (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {\n\t\t\tlwsl_info(\"failed at set pollfd\\n\");\n\t\t\tgoto fail;\n\t\t}\n\t}\n\n\tif (!wsi->hdr_parsing_completed)\n\t\treturn LWS_HPI_RET_HANDLED;\n\n\tif (lwsi_state(wsi) != LRS_ISSUING_FILE) {\n\n\t\tif (wsi->trunc_len) {\n\t\t\t//lwsl_notice(\"%s: completing partial\\n\", __func__);\n\t\t\tif (lws_issue_raw(wsi, wsi->trunc_alloc + wsi->trunc_offset,\n\t\t\t\t\t  wsi->trunc_len) < 0) {\n\t\t\t\tlwsl_info(\"%s signalling to close\\n\", __func__);\n\t\t\t\tgoto fail;\n\t\t\t}\n\t\t\treturn LWS_HPI_RET_HANDLED;\n\t\t}\n\n\t\tlws_stats_atomic_bump(wsi->context, pt,\n\t\t\t\t\tLWSSTATS_C_WRITEABLE_CB, 1);\n#if defined(LWS_WITH_STATS)\n\t\tif (wsi->active_writable_req_us) {\n\t\t\tuint64_t ul = time_in_microseconds() -\n\t\t\t\t\twsi->active_writable_req_us;\n\n\t\t\tlws_stats_atomic_bump(wsi->context, pt,\n\t\t\t\t\tLWSSTATS_MS_WRITABLE_DELAY, ul);\n\t\t\tlws_stats_atomic_max(wsi->context, pt,\n\t\t\t\t  LWSSTATS_MS_WORST_WRITABLE_DELAY, ul);\n\t\t\twsi->active_writable_req_us = 0;\n\t\t}\n#endif\n\n\t\tn = user_callback_handle_rxflow(wsi->protocol->callback, wsi,\n\t\t\t\t\t\tLWS_CALLBACK_HTTP_WRITEABLE,\n\t\t\t\t\t\twsi->user_space, NULL, 0);\n\t\tif (n < 0) {\n\t\t\tlwsl_info(\"writeable_fail\\n\");\n\t\t\tgoto fail;\n\t\t}\n\n\t\treturn LWS_HPI_RET_HANDLED;\n\t}\n\n\t/* >0 == completion, <0 == error\n\t *\n\t * We'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when\n\t * it's done.  That's the case even if we just completed the\n\t * send, so wait for that.\n\t */\n\tn = lws_serve_http_file_fragment(wsi);\n\tif (n < 0)\n\t\tgoto fail;\n\n\treturn LWS_HPI_RET_HANDLED;\n\n\nfail:\n\tlws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS,\n\t\t\t   \"server socket svc fail\");\n\n\treturn LWS_HPI_RET_WSI_ALREADY_DIED;\n}\n#endif\n\nstatic int\nrops_handle_POLLIN_h1(struct lws_context_per_thread *pt, struct lws *wsi,\n\t\t       struct lws_pollfd *pollfd)\n{\n\n//\tlwsl_notice(\"%s: %p: wsistate 0x%x %s, revents 0x%x\\n\", __func__, wsi,\n//\t\t\twsi->wsistate, wsi->role_ops->name, pollfd->revents);\n\n#ifdef LWS_WITH_CGI\n\tif (wsi->http.cgi && (pollfd->revents & LWS_POLLOUT)) {\n\t\tif (lws_handle_POLLOUT_event(wsi, pollfd))\n\t\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\n\t\treturn LWS_HPI_RET_HANDLED;\n\t}\n#endif\n\n        if (lws_is_flowcontrolled(wsi))\n                /* We cannot deal with any kind of new RX because we are\n                 * RX-flowcontrolled.\n                 */\n\t\treturn LWS_HPI_RET_HANDLED;\n\n#if !defined(LWS_NO_SERVER)\n\tif (!lwsi_role_client(wsi)) {\n\t\tint n;\n\n\t\tlwsl_debug(\"%s: %p: wsistate 0x%x\\n\", __func__, wsi, wsi->wsistate);\n\t\tn = lws_h1_server_socket_service(wsi, pollfd);\n\t\tif (n != LWS_HPI_RET_HANDLED)\n\t\t\treturn n;\n\t\tif (lwsi_state(wsi) != LRS_SSL_INIT)\n\t\t\tif (lws_server_socket_service_ssl(wsi, LWS_SOCK_INVALID))\n\t\t\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\n\t\treturn LWS_HPI_RET_HANDLED;\n\t}\n#endif\n\n#ifndef LWS_NO_CLIENT\n\tif ((pollfd->revents & LWS_POLLIN) &&\n\t     wsi->hdr_parsing_completed && !wsi->told_user_closed) {\n\n\t\t/*\n\t\t * In SSL mode we get POLLIN notification about\n\t\t * encrypted data in.\n\t\t *\n\t\t * But that is not necessarily related to decrypted\n\t\t * data out becoming available; in may need to perform\n\t\t * other in or out before that happens.\n\t\t *\n\t\t * simply mark ourselves as having readable data\n\t\t * and turn off our POLLIN\n\t\t */\n\t\twsi->client_rx_avail = 1;\n\t\tlws_change_pollfd(wsi, LWS_POLLIN, 0);\n\n\t\t//lwsl_notice(\"calling back %s\\n\", wsi->protocol->name);\n\n\t\t/* let user code know, he'll usually ask for writeable\n\t\t * callback and drain / re-enable it there\n\t\t */\n\t\tif (user_callback_handle_rxflow(\n\t\t\t\twsi->protocol->callback,\n\t\t\t\twsi, LWS_CALLBACK_RECEIVE_CLIENT_HTTP,\n\t\t\t\twsi->user_space, NULL, 0)) {\n\t\t\tlwsl_info(\"RECEIVE_CLIENT_HTTP closed it\\n\");\n\t\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\t\t}\n\n\t\treturn LWS_HPI_RET_HANDLED;\n\t}\n#endif\n\n//\tif (lwsi_state(wsi) == LRS_ESTABLISHED)\n//\t\treturn LWS_HPI_RET_HANDLED;\n\n#if !defined(LWS_NO_CLIENT)\n\tif ((pollfd->revents & LWS_POLLOUT) &&\n\t    lws_handle_POLLOUT_event(wsi, pollfd)) {\n\t\tlwsl_debug(\"POLLOUT event closed it\\n\");\n\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\t}\n\n\tif (lws_client_socket_service(wsi, pollfd, NULL))\n\t\treturn LWS_HPI_RET_WSI_ALREADY_DIED;\n#endif\n\n\treturn LWS_HPI_RET_HANDLED;\n}\n\nint rops_handle_POLLOUT_h1(struct lws *wsi)\n{\n\tif (lwsi_state(wsi) == LRS_ISSUE_HTTP_BODY)\n\t\treturn LWS_HP_RET_USER_SERVICE;\n\n\tif (lwsi_role_client(wsi))\n\t\treturn LWS_HP_RET_USER_SERVICE;\n\n\treturn LWS_HP_RET_BAIL_OK;\n}\n\nstatic int\nrops_write_role_protocol_h1(struct lws *wsi, unsigned char *buf, size_t len,\n\t\t\t    enum lws_write_protocol *wp)\n{\n#if 0\n\t/* if not in a state to send stuff, then just send nothing */\n\n\tif ((lwsi_state(wsi) != LRS_RETURNED_CLOSE &&\n\t     lwsi_state(wsi) != LRS_WAITING_TO_SEND_CLOSE &&\n\t     lwsi_state(wsi) != LRS_AWAITING_CLOSE_ACK)) {\n\t\t//assert(0);\n\t\tlwsl_debug(\"binning %d %d\\n\", lwsi_state(wsi), *wp);\n\t\treturn 0;\n\t}\n#endif\n\n\treturn lws_issue_raw(wsi, (unsigned char *)buf, len);\n}\n\nstatic int\nrops_alpn_negotiated_h1(struct lws *wsi, const char *alpn)\n{\n\tlwsl_debug(\"%s: client %d\\n\", __func__, lwsi_role_client(wsi));\n#if !defined(LWS_NO_CLIENT)\n\tif (lwsi_role_client(wsi)) {\n\t\t/*\n\t\t * If alpn asserts it is http/1.1, server support for KA is\n\t\t * mandatory.\n\t\t *\n\t\t * Knowing this lets us proceed with sending pipelined headers\n\t\t * before we received the first response headers.\n\t\t */\n\t\twsi->keepalive_active = 1;\n\t}\n#endif\n\n\treturn 0;\n}\n\nstatic int\nrops_destroy_role_h1(struct lws *wsi)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tstruct allocated_headers *ah;\n\n\t/* we may not have an ah, but may be on the waiting list... */\n\tlwsl_info(\"%s: ah det due to close\\n\", __func__);\n\t__lws_header_table_detach(wsi, 0);\n\n\t ah = pt->http.ah_list;\n\n\twhile (ah) {\n\t\tif (ah->in_use && ah->wsi == wsi) {\n\t\t\tlwsl_err(\"%s: ah leak: wsi %p\\n\", __func__, wsi);\n\t\t\tah->in_use = 0;\n\t\t\tah->wsi = NULL;\n\t\t\tpt->http.ah_count_in_use--;\n\t\t\tbreak;\n\t\t}\n\t\tah = ah->next;\n\t}\n\n#ifdef LWS_ROLE_WS\n\tlws_free_set_NULL(wsi->ws);\n#endif\n\treturn 0;\n}\n\nstruct lws_role_ops role_ops_h1 = {\n\t/* role name */\t\t\t\"h1\",\n\t/* alpn id */\t\t\t\"http/1.1\",\n\t/* check_upgrades */\t\tNULL,\n\t/* init_context */\t\tNULL,\n\t/* init_vhost */\t\tNULL,\n\t/* destroy_vhost */\t\tNULL,\n\t/* periodic_checks */\t\tNULL,\n\t/* service_flag_pending */\tNULL,\n\t/* handle_POLLIN */\t\trops_handle_POLLIN_h1,\n\t/* handle_POLLOUT */\t\trops_handle_POLLOUT_h1,\n\t/* perform_user_POLLOUT */\tNULL,\n\t/* callback_on_writable */\tNULL,\n\t/* tx_credit */\t\t\tNULL,\n\t/* write_role_protocol */\trops_write_role_protocol_h1,\n\t/* encapsulation_parent */\tNULL,\n\t/* alpn_negotiated */\t\trops_alpn_negotiated_h1,\n\t/* close_via_role_protocol */\tNULL,\n\t/* close_role */\t\tNULL,\n\t/* close_kill_connection */\tNULL,\n\t/* destroy_role */\t\trops_destroy_role_h1,\n\t/* writeable cb clnt, srv */\t{ LWS_CALLBACK_CLIENT_HTTP_WRITEABLE,\n\t\t\t\t\t  LWS_CALLBACK_HTTP_WRITEABLE },\n\t/* close cb clnt, srv */\t{ LWS_CALLBACK_CLOSED_CLIENT_HTTP,\n\t\t\t\t\t  LWS_CALLBACK_CLOSED_HTTP },\n\t/* file_handle */\t\t0,\n};\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/h1/private.h",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n *\n *  This is included from core/private.h if LWS_ROLE_H1\n *\n *  Most of the h1 business is defined in the h1 / h2 common roles/http dir\n */\n\nextern struct lws_role_ops role_ops_h1;\n#define lwsi_role_h1(wsi) (wsi->role_ops == &role_ops_h1)\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/http/client/client-handshake.c",
    "content": "#include \"core/private.h\"\n\nstatic int\nlws_getaddrinfo46(struct lws *wsi, const char *ads, struct addrinfo **result)\n{\n\tstruct addrinfo hints;\n\n\tmemset(&hints, 0, sizeof(hints));\n\t*result = NULL;\n\n#ifdef LWS_WITH_IPV6\n\tif (wsi->ipv6) {\n\n#if !defined(__ANDROID__)\n\t\thints.ai_family = AF_INET6;\n\t\thints.ai_flags = AI_V4MAPPED;\n#endif\n\t} else\n#endif\n\t{\n\t\thints.ai_family = PF_UNSPEC;\n\t\thints.ai_socktype = SOCK_STREAM;\n\t}\n\n\treturn getaddrinfo(ads, NULL, &hints, result);\n}\n\nstruct lws *\nlws_client_connect_2(struct lws *wsi)\n{\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tstruct lws_context *context = wsi->context;\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tconst char *adsin;\n\tstruct lws *wsi_piggyback = NULL;\n\tstruct lws_pollfd pfd;\n\tssize_t plen = 0;\n#endif\n\tstruct addrinfo *result;\n\tconst char *ads;\n\tsockaddr46 sa46;\n\tint n, port;\n\tconst char *cce = \"\", *iface;\n\tconst char *meth = NULL;\n#ifdef LWS_WITH_IPV6\n\tchar ipv6only = lws_check_opt(wsi->vhost->options,\n\t\t\tLWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY |\n\t\t\tLWS_SERVER_OPTION_IPV6_V6ONLY_VALUE);\n\n#if defined(__ANDROID__)\n\tipv6only = 0;\n#endif\n#endif\n\n\tlwsl_client(\"%s: %p\\n\", __func__, wsi);\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tif (!wsi->http.ah) {\n\t\tcce = \"ah was NULL at cc2\";\n\t\tlwsl_err(\"%s\\n\", cce);\n\t\tgoto oom4;\n\t}\n\n\t/* we can only piggyback GET or POST */\n\n\tmeth = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_METHOD);\n\tif (meth && strcmp(meth, \"GET\") && strcmp(meth, \"POST\"))\n\t\tgoto create_new_conn;\n\n\t/* we only pipeline connections that said it was okay */\n\n\tif (!wsi->client_pipeline)\n\t\tgoto create_new_conn;\n\n\t/*\n\t * let's take a look first and see if there are any already-active\n\t * client connections we can piggy-back on.\n\t */\n\n\tadsin = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS);\n\n\tlws_vhost_lock(wsi->vhost); /* ----------------------------------- { */\n\n\tlws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1,\n\t\t\t\t   wsi->vhost->dll_active_client_conns.next) {\n\t\tstruct lws *w = lws_container_of(d, struct lws,\n\t\t\t\t\t\t dll_active_client_conns);\n\n\t\tlwsl_debug(\"%s: check %s %s %d %d\\n\", __func__, adsin,\n\t\t\t   w->client_hostname_copy, wsi->c_port, w->c_port);\n\n\t\tif (w != wsi && w->client_hostname_copy &&\n\t\t    !strcmp(adsin, w->client_hostname_copy) &&\n#if defined(LWS_WITH_TLS)\n\t\t    (wsi->tls.use_ssl & LCCSCF_USE_SSL) ==\n\t\t     (w->tls.use_ssl & LCCSCF_USE_SSL) &&\n#endif\n\t\t    wsi->c_port == w->c_port) {\n\n\t\t\t/* someone else is already connected to the right guy */\n\n\t\t\t/* do we know for a fact pipelining won't fly? */\n\t\t\tif (w->keepalive_rejected) {\n\t\t\t\tlwsl_info(\"defeating pipelining due to no \"\n\t\t\t\t\t    \"keepalive on server\\n\");\n\t\t\t\tlws_vhost_unlock(wsi->vhost); /* } ---------- */\n\t\t\t\tgoto create_new_conn;\n\t\t\t}\n#if defined (LWS_WITH_HTTP2)\n\t\t\t/*\n\t\t\t * h2: in usable state already: just use it without\n\t\t\t *     going through the queue\n\t\t\t */\n\t\t\tif (w->client_h2_alpn &&\n\t\t\t    (lwsi_state(w) == LRS_H2_WAITING_TO_SEND_HEADERS ||\n\t\t\t     lwsi_state(w) == LRS_ESTABLISHED)) {\n\n\t\t\t\tlwsl_info(\"%s: just join h2 directly\\n\",\n\t\t\t\t\t\t__func__);\n\n\t\t\t\twsi->client_h2_alpn = 1;\n\t\t\t\tlws_wsi_h2_adopt(w, wsi);\n\t\t\t\tlws_vhost_unlock(wsi->vhost); /* } ---------- */\n\n\t\t\t\treturn wsi;\n\t\t\t}\n#endif\n\n\t\t\tlwsl_info(\"applying %p to txn queue on %p (wsistate 0x%x)\\n\",\n\t\t\t\twsi, w, w->wsistate);\n\t\t\t/*\n\t\t\t * ...let's add ourselves to his transaction queue...\n\t\t\t * we are adding ourselves at the HEAD\n\t\t\t */\n\t\t\tlws_dll_lws_add_front(&wsi->dll_client_transaction_queue,\n\t\t\t\t&w->dll_client_transaction_queue_head);\n\n\t\t\t/*\n\t\t\t * h1: pipeline our headers out on him,\n\t\t\t * and wait for our turn at client transaction_complete\n\t\t\t * to take over parsing the rx.\n\t\t\t */\n\n\t\t\twsi_piggyback = w;\n\n\t\t\tlws_vhost_unlock(wsi->vhost); /* } ---------- */\n\t\t\tgoto send_hs;\n\t\t}\n\n\t} lws_end_foreach_dll_safe(d, d1);\n\n\tlws_vhost_unlock(wsi->vhost); /* } ---------------------------------- */\n\ncreate_new_conn:\n#endif\n\n\t/*\n\t * clients who will create their own fresh connection keep a copy of\n\t * the hostname they originally connected to, in case other connections\n\t * want to use it too\n\t */\n\n\tif (!wsi->client_hostname_copy)\n\t\twsi->client_hostname_copy =\n\t\t\tlws_strdup(lws_hdr_simple_ptr(wsi,\n\t\t\t\t\t_WSI_TOKEN_CLIENT_PEER_ADDRESS));\n\n\t/*\n\t * If we made our own connection, and we're doing a method that can take\n\t * a pipeline, we are an \"active client connection\".\n\t *\n\t * Add ourselves to the vhost list of those so that others can\n\t * piggyback on our transaction queue\n\t */\n\n\tif (meth && (!strcmp(meth, \"GET\") || !strcmp(meth, \"POST\")) &&\n\t    lws_dll_is_null(&wsi->dll_client_transaction_queue) &&\n\t    lws_dll_is_null(&wsi->dll_active_client_conns)) {\n\t\tlws_vhost_lock(wsi->vhost);\n\t\tlws_dll_lws_add_front(&wsi->dll_active_client_conns,\n\t\t\t\t      &wsi->vhost->dll_active_client_conns);\n\t\tlws_vhost_unlock(wsi->vhost);\n\t}\n\n\t/*\n\t * start off allowing ipv6 on connection if vhost allows it\n\t */\n\twsi->ipv6 = LWS_IPV6_ENABLED(wsi->vhost);\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\n\t/* Decide what it is we need to connect to:\n\t *\n\t * Priority 1: connect to http proxy */\n\n\tif (wsi->vhost->http.http_proxy_port) {\n\t\tplen = sprintf((char *)pt->serv_buf,\n\t\t\t\"CONNECT %s:%u HTTP/1.0\\x0d\\x0a\"\n\t\t\t\"User-agent: libwebsockets\\x0d\\x0a\",\n\t\t\tlws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS),\n\t\t\twsi->c_port);\n\n\t\tif (wsi->vhost->proxy_basic_auth_token[0])\n\t\t\tplen += sprintf((char *)pt->serv_buf + plen,\n\t\t\t\t\t\"Proxy-authorization: basic %s\\x0d\\x0a\",\n\t\t\t\t\twsi->vhost->proxy_basic_auth_token);\n\n\t\tplen += sprintf((char *)pt->serv_buf + plen, \"\\x0d\\x0a\");\n\t\tads = wsi->vhost->http.http_proxy_address;\n\t\tport = wsi->vhost->http.http_proxy_port;\n#else\n\t\tif (0) {\n#endif\n\n#if defined(LWS_WITH_SOCKS5)\n\n\t/* Priority 2: Connect to SOCK5 Proxy */\n\n\t} else if (wsi->vhost->socks_proxy_port) {\n\t\tsocks_generate_msg(wsi, SOCKS_MSG_GREETING, &plen);\n\t\tlwsl_client(\"Sending SOCKS Greeting\\n\");\n\t\tads = wsi->vhost->socks_proxy_address;\n\t\tport = wsi->vhost->socks_proxy_port;\n#endif\n\t} else {\n\n\t\t/* Priority 3: Connect directly */\n\n\t\tads = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS);\n\t\tport = wsi->c_port;\n\t}\n\n\t/*\n\t * prepare the actual connection\n\t * to whatever we decided to connect to\n\t */\n\n       lwsl_info(\"%s: %p: address %s\\n\", __func__, wsi, ads);\n\n       n = lws_getaddrinfo46(wsi, ads, &result);\n\n#ifdef LWS_WITH_IPV6\n\tif (wsi->ipv6) {\n\t\tstruct sockaddr_in6 *sa6 =\n\t\t\t\t((struct sockaddr_in6 *)result->ai_addr);\n\n\t\tif (n) {\n\t\t\t/* lws_getaddrinfo46 failed, there is no usable result */\n\t\t\tlwsl_notice(\"%s: lws_getaddrinfo46 failed %d\\n\",\n\t\t\t\t\t__func__, n);\n\t\t\tcce = \"ipv6 lws_getaddrinfo46 failed\";\n\t\t\tgoto oom4;\n\t\t}\n\n\t\tmemset(&sa46, 0, sizeof(sa46));\n\n\t\tsa46.sa6.sin6_family = AF_INET6;\n\t\tswitch (result->ai_family) {\n\t\tcase AF_INET:\n\t\t\tif (ipv6only)\n\t\t\t\tbreak;\n\t\t\t/* map IPv4 to IPv6 */\n\t\t\tbzero((char *)&sa46.sa6.sin6_addr,\n\t\t\t\t\t\tsizeof(sa46.sa6.sin6_addr));\n\t\t\tsa46.sa6.sin6_addr.s6_addr[10] = 0xff;\n\t\t\tsa46.sa6.sin6_addr.s6_addr[11] = 0xff;\n\t\t\tmemcpy(&sa46.sa6.sin6_addr.s6_addr[12],\n\t\t\t\t&((struct sockaddr_in *)result->ai_addr)->sin_addr,\n\t\t\t\t\t\t\tsizeof(struct in_addr));\n\t\t\tlwsl_notice(\"uplevelling AF_INET to AF_INET6\\n\");\n\t\t\tbreak;\n\n\t\tcase AF_INET6:\n\t\t\tmemcpy(&sa46.sa6.sin6_addr, &sa6->sin6_addr,\n\t\t\t\t\t\tsizeof(struct in6_addr));\n\t\t\tsa46.sa6.sin6_scope_id = sa6->sin6_scope_id;\n\t\t\tsa46.sa6.sin6_flowinfo = sa6->sin6_flowinfo;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tlwsl_err(\"Unknown address family\\n\");\n\t\t\tfreeaddrinfo(result);\n\t\t\tcce = \"unknown address family\";\n\t\t\tgoto oom4;\n\t\t}\n\t} else\n#endif /* use ipv6 */\n\n\t/* use ipv4 */\n\t{\n\t\tvoid *p = NULL;\n\n\t\tif (!n) {\n\t\t\tstruct addrinfo *res = result;\n\n\t\t\t/* pick the first AF_INET (IPv4) result */\n\n\t\t\twhile (!p && res) {\n\t\t\t\tswitch (res->ai_family) {\n\t\t\t\tcase AF_INET:\n\t\t\t\t\tp = &((struct sockaddr_in *)res->ai_addr)->sin_addr;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tres = res->ai_next;\n\t\t\t}\n#if defined(LWS_FALLBACK_GETHOSTBYNAME)\n\t\t} else if (n == EAI_SYSTEM) {\n\t\t\tstruct hostent *host;\n\n\t\t\tlwsl_info(\"getaddrinfo (ipv4) failed, trying gethostbyname\\n\");\n\t\t\thost = gethostbyname(ads);\n\t\t\tif (host) {\n\t\t\t\tp = host->h_addr;\n\t\t\t} else {\n\t\t\t\tlwsl_err(\"gethostbyname failed\\n\");\n\t\t\t\tcce = \"gethostbyname (ipv4) failed\";\n\t\t\t\tgoto oom4;\n\t\t\t}\n#endif\n\t\t} else {\n\t\t\tlwsl_err(\"getaddrinfo failed\\n\");\n\t\t\tcce = \"getaddrinfo failed\";\n\t\t\tgoto oom4;\n\t\t}\n\n\t\tif (!p) {\n\t\t\tif (result)\n\t\t\t\tfreeaddrinfo(result);\n\t\t\tlwsl_err(\"Couldn't identify address\\n\");\n\t\t\tcce = \"unable to lookup address\";\n\t\t\tgoto oom4;\n\t\t}\n\n\t\tsa46.sa4.sin_family = AF_INET;\n\t\tsa46.sa4.sin_addr = *((struct in_addr *)p);\n\t\tbzero(&sa46.sa4.sin_zero, 8);\n\t}\n\n\tif (result)\n\t\tfreeaddrinfo(result);\n\n\t/* now we decided on ipv4 or ipv6, set the port */\n\n\tif (!lws_socket_is_valid(wsi->desc.sockfd)) {\n\n\t\tif (wsi->context->event_loop_ops->check_client_connect_ok &&\n\t\t    wsi->context->event_loop_ops->check_client_connect_ok(wsi)) {\n\t\t\tcce = \"waiting for event loop watcher to close\";\n\t\t\tgoto oom4;\n\t\t}\n\n#ifdef LWS_WITH_IPV6\n\t\tif (wsi->ipv6)\n\t\t\twsi->desc.sockfd = socket(AF_INET6, SOCK_STREAM, 0);\n\t\telse\n#endif\n\t\t\twsi->desc.sockfd = socket(AF_INET, SOCK_STREAM, 0);\n\n\t\tif (!lws_socket_is_valid(wsi->desc.sockfd)) {\n\t\t\tlwsl_warn(\"Unable to open socket\\n\");\n\t\t\tcce = \"unable to open socket\";\n\t\t\tgoto oom4;\n\t\t}\n\n\t\tif (lws_plat_set_socket_options(wsi->vhost, wsi->desc.sockfd)) {\n\t\t\tlwsl_err(\"Failed to set wsi socket options\\n\");\n\t\t\tcompatible_close(wsi->desc.sockfd);\n\t\t\tcce = \"set socket opts failed\";\n\t\t\tgoto oom4;\n\t\t}\n\n\t\tlwsi_set_state(wsi, LRS_WAITING_CONNECT);\n\n\t\tif (wsi->context->event_loop_ops->accept)\n\t\t\twsi->context->event_loop_ops->accept(wsi);\n\n\t\tif (__insert_wsi_socket_into_fds(wsi->context, wsi)) {\n\t\t\tcompatible_close(wsi->desc.sockfd);\n\t\t\tcce = \"insert wsi failed\";\n\t\t\tgoto oom4;\n\t\t}\n\n\t\tlws_change_pollfd(wsi, 0, LWS_POLLIN);\n\n\t\t/*\n\t\t * past here, we can't simply free the structs as error\n\t\t * handling as oom4 does.  We have to run the whole close flow.\n\t\t */\n\n\t\tif (!wsi->protocol)\n\t\t\twsi->protocol = &wsi->vhost->protocols[0];\n\n\t\twsi->protocol->callback(wsi, LWS_CALLBACK_WSI_CREATE,\n\t\t\t\t\twsi->user_space, NULL, 0);\n\n\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE,\n\t\t\t\tAWAITING_TIMEOUT);\n\n\t\tiface = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_IFACE);\n\n\t\tif (iface) {\n\t\t\tn = lws_socket_bind(wsi->vhost, wsi->desc.sockfd, 0, iface);\n\t\t\tif (n < 0) {\n\t\t\t\tcce = \"unable to bind socket\";\n\t\t\t\tgoto failed;\n\t\t\t}\n\t\t}\n\t}\n\n#ifdef LWS_WITH_IPV6\n\tif (wsi->ipv6) {\n\t\tsa46.sa6.sin6_port = htons(port);\n\t\tn = sizeof(struct sockaddr_in6);\n\t} else\n#endif\n\t{\n\t\tsa46.sa4.sin_port = htons(port);\n\t\tn = sizeof(struct sockaddr);\n\t}\n\n\tif (connect(wsi->desc.sockfd, (const struct sockaddr *)&sa46, n) == -1 ||\n\t    LWS_ERRNO == LWS_EISCONN) {\n\t\tif (LWS_ERRNO == LWS_EALREADY ||\n\t\t    LWS_ERRNO == LWS_EINPROGRESS ||\n\t\t    LWS_ERRNO == LWS_EWOULDBLOCK\n#ifdef _WIN32\n\t\t\t|| LWS_ERRNO == WSAEINVAL\n#endif\n\t\t) {\n\t\t\tlwsl_client(\"nonblocking connect retry (errno = %d)\\n\",\n\t\t\t\t    LWS_ERRNO);\n\n\t\t\tif (lws_plat_check_connection_error(wsi)) {\n\t\t\t\tcce = \"socket connect failed\";\n\t\t\t\tgoto failed;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * must do specifically a POLLOUT poll to hear\n\t\t\t * about the connect completion\n\t\t\t */\n\t\t\tif (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) {\n\t\t\t\tcce = \"POLLOUT set failed\";\n\t\t\t\tgoto failed;\n\t\t\t}\n\n\t\t\treturn wsi;\n\t\t}\n\n\t\tif (LWS_ERRNO != LWS_EISCONN) {\n\t\t\tlwsl_notice(\"Connect failed errno=%d\\n\", LWS_ERRNO);\n\t\t\tcce = \"connect failed\";\n\t\t\tgoto failed;\n\t\t}\n\t}\n\n\tlwsl_client(\"connected\\n\");\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\t/* we are connected to server, or proxy */\n\n\t/* http proxy */\n\tif (wsi->vhost->http.http_proxy_port) {\n\n\t\t/*\n\t\t * OK from now on we talk via the proxy, so connect to that\n\t\t *\n\t\t * (will overwrite existing pointer,\n\t\t * leaving old string/frag there but unreferenced)\n\t\t */\n\t\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS,\n\t\t\t\t\t  wsi->vhost->http.http_proxy_address))\n\t\t\tgoto failed;\n\t\twsi->c_port = wsi->vhost->http.http_proxy_port;\n\n\t\tn = send(wsi->desc.sockfd, (char *)pt->serv_buf, (int)plen,\n\t\t\t MSG_NOSIGNAL);\n\t\tif (n < 0) {\n\t\t\tlwsl_debug(\"ERROR writing to proxy socket\\n\");\n\t\t\tcce = \"proxy write failed\";\n\t\t\tgoto failed;\n\t\t}\n\n\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE,\n\t\t\t\tAWAITING_TIMEOUT);\n\n\t\tlwsi_set_state(wsi, LRS_WAITING_PROXY_REPLY);\n\n\t\treturn wsi;\n\t}\n#endif\n#if defined(LWS_WITH_SOCKS5)\n\t/* socks proxy */\n\telse if (wsi->vhost->socks_proxy_port) {\n\t\tn = send(wsi->desc.sockfd, (char *)pt->serv_buf, plen,\n\t\t\t MSG_NOSIGNAL);\n\t\tif (n < 0) {\n\t\t\tlwsl_debug(\"ERROR writing socks greeting\\n\");\n\t\t\tcce = \"socks write failed\";\n\t\t\tgoto failed;\n\t\t}\n\n\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SOCKS_GREETING_REPLY,\n\t\t\t\tAWAITING_TIMEOUT);\n\n\t\tlwsi_set_state(wsi, LRS_WAITING_SOCKS_GREETING_REPLY);\n\n\t\treturn wsi;\n\t}\n#endif\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\nsend_hs:\n\n\tif (wsi_piggyback &&\n\t    !lws_dll_is_null(&wsi->dll_client_transaction_queue)) {\n\t\t/*\n\t\t * We are pipelining on an already-established connection...\n\t\t * we can skip tls establishment.\n\t\t */\n\n\t\tlwsi_set_state(wsi, LRS_H1C_ISSUE_HANDSHAKE2);\n\n\t\t/*\n\t\t * we can't send our headers directly, because they have to\n\t\t * be sent when the parent is writeable.  The parent will check\n\t\t * for anybody on his client transaction queue that is in\n\t\t * LRS_H1C_ISSUE_HANDSHAKE2, and let them write.\n\t\t *\n\t\t * If we are trying to do this too early, before the master\n\t\t * connection has written his own headers, then it will just\n\t\t * wait in the queue until it's possible to send them.\n\t\t */\n\t\tlws_callback_on_writable(wsi_piggyback);\n\t\tlwsl_info(\"%s: wsi %p: waiting to send headers (parent state %x)\\n\",\n\t\t\t    __func__, wsi, lwsi_state(wsi_piggyback));\n\t} else {\n\t\tlwsl_info(\"%s: wsi %p: client creating own connection\\n\",\n\t\t\t    __func__, wsi);\n\n\t\t/* we are making our own connection */\n\t\tlwsi_set_state(wsi, LRS_H1C_ISSUE_HANDSHAKE);\n\n\t\t/*\n\t\t * provoke service to issue the handshake directly.\n\t\t *\n\t\t * we need to do it this way because in the proxy case, this is\n\t\t * the next state and executed only if and when we get a good\n\t\t * proxy response inside the state machine... but notice in\n\t\t * SSL case this may not have sent anything yet with 0 return,\n\t\t * and won't until many retries from main loop.  To stop that\n\t\t * becoming endless, cover with a timeout.\n\t\t */\n\n\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE,\n\t\t\t\tAWAITING_TIMEOUT);\n\n\t\tpfd.fd = wsi->desc.sockfd;\n\t\tpfd.events = LWS_POLLIN;\n\t\tpfd.revents = LWS_POLLIN;\n\n\t\tn = lws_service_fd(context, &pfd);\n\t\tif (n < 0) {\n\t\t\tcce = \"first service failed\";\n\t\t\tgoto failed;\n\t\t}\n\t\tif (n) /* returns 1 on failure after closing wsi */\n\t\t\treturn NULL;\n\t}\n#endif\n\treturn wsi;\n\noom4:\n\tif (lwsi_role_client(wsi) && lwsi_state_est(wsi)) {\n\t\twsi->protocol->callback(wsi,\n\t\t\tLWS_CALLBACK_CLIENT_CONNECTION_ERROR,\n\t\t\twsi->user_space, (void *)cce, strlen(cce));\n\t\twsi->already_did_cce = 1;\n\t}\n\t/* take care that we might be inserted in fds already */\n\tif (wsi->position_in_fds_table != LWS_NO_FDS_POS)\n\t\tgoto failed1;\n\tlws_remove_from_timeout_list(wsi);\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tlws_header_table_detach(wsi, 0);\n#endif\n\tlws_client_stash_destroy(wsi);\n\tlws_free_set_NULL(wsi->client_hostname_copy);\n\tlws_free(wsi);\n\n\treturn NULL;\n\nfailed:\n\twsi->protocol->callback(wsi,\n\t\tLWS_CALLBACK_CLIENT_CONNECTION_ERROR,\n\t\twsi->user_space, (void *)cce, strlen(cce));\n\twsi->already_did_cce = 1;\nfailed1:\n\tlws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, \"client_connect2\");\n\n\treturn NULL;\n}\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\n/**\n * lws_client_reset() - retarget a connected wsi to start over with a new connection (ie, redirect)\n *\t\t\tthis only works if still in HTTP, ie, not upgraded yet\n * wsi:\t\tconnection to reset\n * address:\tnetwork address of the new server\n * port:\tport to connect to\n * path:\turi path to connect to on the new server\n * host:\thost header to send to the new server\n */\nLWS_VISIBLE struct lws *\nlws_client_reset(struct lws **pwsi, int ssl, const char *address, int port,\n\t\t const char *path, const char *host)\n{\n\tchar origin[300] = \"\", protocol[300] = \"\", method[32] = \"\",\n\t     iface[16] = \"\", alpn[32] = \"\", *p;\n\tstruct lws *wsi = *pwsi;\n\n\tif (wsi->redirects == 3) {\n\t\tlwsl_err(\"%s: Too many redirects\\n\", __func__);\n\t\treturn NULL;\n\t}\n\twsi->redirects++;\n\n\tp = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN);\n\tif (p)\n\t\tlws_strncpy(origin, p, sizeof(origin));\n\n\tp = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);\n\tif (p)\n\t\tlws_strncpy(protocol, p, sizeof(protocol));\n\n\tp = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_METHOD);\n\tif (p)\n\t\tlws_strncpy(method, p, sizeof(method));\n\n\tp = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_IFACE);\n\tif (p)\n\t\tlws_strncpy(iface, p, sizeof(iface));\n\n\tp = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ALPN);\n\tif (p)\n\t\tlws_strncpy(alpn, p, sizeof(alpn));\n\n\tlwsl_info(\"redirect ads='%s', port=%d, path='%s', ssl = %d\\n\",\n\t\t   address, port, path, ssl);\n\n\t/* close the connection by hand */\n\n#if defined(LWS_WITH_TLS)\n\tlws_ssl_close(wsi);\n#endif\n\n\t__remove_wsi_socket_from_fds(wsi);\n\n\tif (wsi->context->event_loop_ops->close_handle_manually)\n\t\twsi->context->event_loop_ops->close_handle_manually(wsi);\n\telse\n\t\tcompatible_close(wsi->desc.sockfd);\n\n#if defined(LWS_WITH_TLS)\n\twsi->tls.use_ssl = ssl;\n#else\n\tif (ssl) {\n\t\tlwsl_err(\"%s: not configured for ssl\\n\", __func__);\n\t\treturn NULL;\n\t}\n#endif\n\n\twsi->desc.sockfd = LWS_SOCK_INVALID;\n\tlwsi_set_state(wsi, LRS_UNCONNECTED);\n\twsi->protocol = NULL;\n\twsi->pending_timeout = NO_PENDING_TIMEOUT;\n\twsi->c_port = port;\n\twsi->hdr_parsing_completed = 0;\n\t_lws_header_table_reset(wsi->http.ah);\n\n\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS, address))\n\t\treturn NULL;\n\n\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_HOST, host))\n\t\treturn NULL;\n\n\tif (origin[0])\n\t\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_ORIGIN,\n\t\t\t\t\t  origin))\n\t\t\treturn NULL;\n\tif (protocol[0])\n\t\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS,\n\t\t\t\t\t  protocol))\n\t\t\treturn NULL;\n\tif (method[0])\n\t\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_METHOD,\n\t\t\t\t\t  method))\n\t\t\treturn NULL;\n\n\tif (iface[0])\n\t\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_IFACE,\n\t\t\t\t\t  iface))\n\t\t\treturn NULL;\n\tif (alpn[0])\n\t\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_ALPN,\n\t\t\t\t\t  alpn))\n\t\t\treturn NULL;\n\n\torigin[0] = '/';\n\tstrncpy(&origin[1], path, sizeof(origin) - 2);\n\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_URI, origin))\n\t\treturn NULL;\n\n\t*pwsi = lws_client_connect_2(wsi);\n\n\treturn *pwsi;\n}\n\n#ifdef LWS_WITH_HTTP_PROXY\nhubbub_error\nhtml_parser_cb(const hubbub_token *token, void *pw)\n{\n\tstruct lws_rewrite *r = (struct lws_rewrite *)pw;\n\tchar buf[1024], *start = buf + LWS_PRE, *p = start,\n\t     *end = &buf[sizeof(buf) - 1];\n\tsize_t i;\n\n\tswitch (token->type) {\n\tcase HUBBUB_TOKEN_DOCTYPE:\n\n\t\tp += lws_snprintf(p, end - p, \"<!DOCTYPE %.*s %s \",\n\t\t\t\t(int) token->data.doctype.name.len,\n\t\t\t\ttoken->data.doctype.name.ptr,\n\t\t\t\ttoken->data.doctype.force_quirks ?\n\t\t\t\t\t\t\"(force-quirks) \" : \"\");\n\n\t\tif (token->data.doctype.public_missing)\n\t\t\tlwsl_debug(\"\\tpublic: missing\\n\");\n\t\telse\n\t\t\tp += lws_snprintf(p, end - p, \"PUBLIC \\\"%.*s\\\"\\n\",\n\t\t\t\t(int) token->data.doctype.public_id.len,\n\t\t\t\ttoken->data.doctype.public_id.ptr);\n\n\t\tif (token->data.doctype.system_missing)\n\t\t\tlwsl_debug(\"\\tsystem: missing\\n\");\n\t\telse\n\t\t\tp += lws_snprintf(p, end - p, \" \\\"%.*s\\\">\\n\",\n\t\t\t\t(int) token->data.doctype.system_id.len,\n\t\t\t\ttoken->data.doctype.system_id.ptr);\n\n\t\tbreak;\n\tcase HUBBUB_TOKEN_START_TAG:\n\t\tp += lws_snprintf(p, end - p, \"<%.*s\", (int)token->data.tag.name.len,\n\t\t\t\ttoken->data.tag.name.ptr);\n\n/*\t\t\t\t(token->data.tag.self_closing) ?\n\t\t\t\t\t\t\"(self-closing) \" : \"\",\n\t\t\t\t(token->data.tag.n_attributes > 0) ?\n\t\t\t\t\t\t\"attributes:\" : \"\");\n*/\n\t\tfor (i = 0; i < token->data.tag.n_attributes; i++) {\n\t\t\tif (!hstrcmp(&token->data.tag.attributes[i].name, \"href\", 4) ||\n\t\t\t    !hstrcmp(&token->data.tag.attributes[i].name, \"action\", 6) ||\n\t\t\t    !hstrcmp(&token->data.tag.attributes[i].name, \"src\", 3)) {\n\t\t\t\tconst char *pp = (const char *)token->data.tag.attributes[i].value.ptr;\n\t\t\t\tint plen = (int) token->data.tag.attributes[i].value.len;\n\n\t\t\t\tif (strncmp(pp, \"http:\", 5) && strncmp(pp, \"https:\", 6)) {\n\n\t\t\t\t\tif (!hstrcmp(&token->data.tag.attributes[i].value,\n\t\t\t\t\t\t     r->from, r->from_len)) {\n\t\t\t\t\t\tpp += r->from_len;\n\t\t\t\t\t\tplen -= r->from_len;\n\t\t\t\t\t}\n\t\t\t\t\tp += lws_snprintf(p, end - p, \" %.*s=\\\"%s/%.*s\\\"\",\n\t\t\t\t\t       (int) token->data.tag.attributes[i].name.len,\n\t\t\t\t\t       token->data.tag.attributes[i].name.ptr,\n\t\t\t\t\t       r->to, plen, pp);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tp += lws_snprintf(p, end - p, \" %.*s=\\\"%.*s\\\"\",\n\t\t\t\t(int) token->data.tag.attributes[i].name.len,\n\t\t\t\ttoken->data.tag.attributes[i].name.ptr,\n\t\t\t\t(int) token->data.tag.attributes[i].value.len,\n\t\t\t\ttoken->data.tag.attributes[i].value.ptr);\n\t\t}\n\t\tp += lws_snprintf(p, end - p, \">\");\n\t\tbreak;\n\tcase HUBBUB_TOKEN_END_TAG:\n\t\tp += lws_snprintf(p, end - p, \"</%.*s\", (int) token->data.tag.name.len,\n\t\t\t\ttoken->data.tag.name.ptr);\n/*\n\t\t\t\t(token->data.tag.self_closing) ?\n\t\t\t\t\t\t\"(self-closing) \" : \"\",\n\t\t\t\t(token->data.tag.n_attributes > 0) ?\n\t\t\t\t\t\t\"attributes:\" : \"\");\n*/\n\t\tfor (i = 0; i < token->data.tag.n_attributes; i++) {\n\t\t\tp += lws_snprintf(p, end - p, \" %.*s='%.*s'\\n\",\n\t\t\t\t(int) token->data.tag.attributes[i].name.len,\n\t\t\t\ttoken->data.tag.attributes[i].name.ptr,\n\t\t\t\t(int) token->data.tag.attributes[i].value.len,\n\t\t\t\ttoken->data.tag.attributes[i].value.ptr);\n\t\t}\n\t\tp += lws_snprintf(p, end - p, \">\");\n\t\tbreak;\n\tcase HUBBUB_TOKEN_COMMENT:\n\t\tp += lws_snprintf(p, end - p, \"<!-- %.*s -->\\n\",\n\t\t\t\t(int) token->data.comment.len,\n\t\t\t\ttoken->data.comment.ptr);\n\t\tbreak;\n\tcase HUBBUB_TOKEN_CHARACTER:\n\t\tif (token->data.character.len == 1) {\n\t\t\tif (*token->data.character.ptr == '<') {\n\t\t\t\tp += lws_snprintf(p, end - p, \"&lt;\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (*token->data.character.ptr == '>') {\n\t\t\t\tp += lws_snprintf(p, end - p, \"&gt;\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (*token->data.character.ptr == '&') {\n\t\t\t\tp += lws_snprintf(p, end - p, \"&amp;\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tp += lws_snprintf(p, end - p, \"%.*s\", (int) token->data.character.len,\n\t\t\t\ttoken->data.character.ptr);\n\t\tbreak;\n\tcase HUBBUB_TOKEN_EOF:\n\t\tp += lws_snprintf(p, end - p, \"\\n\");\n\t\tbreak;\n\t}\n\n\tif (user_callback_handle_rxflow(r->wsi->protocol->callback,\n\t\t\tr->wsi, LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ,\n\t\t\tr->wsi->user_space, start, p - start))\n\t\treturn -1;\n\n\treturn HUBBUB_OK;\n}\n#endif\n\n#endif\n\nchar *\nlws_strdup(const char *s)\n{\n\tchar *d = lws_malloc(strlen(s) + 1, \"strdup\");\n\n\tif (d)\n\t\tstrcpy(d, s);\n\n\treturn d;\n}\n\nvoid\nlws_client_stash_destroy(struct lws *wsi)\n{\n\tif (!wsi || !wsi->stash)\n\t\treturn;\n\n\tlws_free_set_NULL(wsi->stash->address);\n\tlws_free_set_NULL(wsi->stash->path);\n\tlws_free_set_NULL(wsi->stash->host);\n\tlws_free_set_NULL(wsi->stash->origin);\n\tlws_free_set_NULL(wsi->stash->protocol);\n\tlws_free_set_NULL(wsi->stash->method);\n\tlws_free_set_NULL(wsi->stash->iface);\n\tlws_free_set_NULL(wsi->stash->alpn);\n\n\tlws_free_set_NULL(wsi->stash);\n}\n\nLWS_VISIBLE struct lws *\nlws_client_connect_via_info(struct lws_client_connect_info *i)\n{\n\tstruct lws *wsi;\n\tconst struct lws_protocols *p;\n\tconst char *local = i->protocol;\n\n\tif (i->context->requested_kill)\n\t\treturn NULL;\n\n\tif (!i->context->protocol_init_done)\n\t\tlws_protocol_init(i->context);\n\t/*\n\t * If we have .local_protocol_name, use it to select the\n\t * local protocol handler to bind to.  Otherwise use .protocol if\n\t * http[s].\n\t */\n\tif (i->local_protocol_name)\n\t\tlocal = i->local_protocol_name;\n\n\twsi = lws_zalloc(sizeof(struct lws), \"client wsi\");\n\tif (wsi == NULL)\n\t\tgoto bail;\n\n\twsi->context = i->context;\n#if defined(LWS_ROLE_H1)\n\t/* assert the mode and union status (hdr) clearly */\n\tlws_role_transition(wsi, LWSIFR_CLIENT, LRS_UNCONNECTED, &role_ops_h1);\n#else\n\tlws_role_transition(wsi, LWSIFR_CLIENT, LRS_UNCONNECTED, &role_ops_raw_skt);\n#endif\n\twsi->desc.sockfd = LWS_SOCK_INVALID;\n\n\t/* 1) fill up the wsi with stuff from the connect_info as far as it\n\t * can go.  It's because not only is our connection async, we might\n\t * not even be able to get ahold of an ah at this point.\n\t */\n\n\tif (!i->method) /* ie, ws */\n#if defined(LWS_ROLE_WS)\n\t\tif (lws_create_client_ws_object(i, wsi))\n\t\t\treturn NULL;\n#else\n\t\treturn NULL;\n#endif\n\n\twsi->user_space = NULL;\n\twsi->pending_timeout = NO_PENDING_TIMEOUT;\n\twsi->position_in_fds_table = LWS_NO_FDS_POS;\n\twsi->c_port = i->port;\n\twsi->vhost = i->vhost;\n\tif (!wsi->vhost)\n\t\twsi->vhost = i->context->vhost_list;\n\n\tif (!wsi->vhost) {\n\t\tlwsl_err(\"At least one vhost in the context is required\\n\");\n\n\t\tgoto bail;\n\t}\n\n\twsi->protocol = &wsi->vhost->protocols[0];\n\twsi->client_pipeline = !!(i->ssl_connection & LCCSCF_PIPELINE);\n\n\t/* reasonable place to start */\n\tlws_role_transition(wsi, LWSIFR_CLIENT, LRS_UNCONNECTED,\n#if defined(LWS_ROLE_H1)\n\t\t\t&role_ops_h1);\n#else\n\t&role_ops_raw_skt);\n#endif\n\n\t/*\n\t * 1) for http[s] connection, allow protocol selection by name\n\t * 2) for ws[s], if local_protocol_name given also use it for\n\t *    local protocol binding... this defeats the server\n\t *    protocol negotiation if so\n\t *\n\t * Otherwise leave at protocols[0]... the server will tell us\n\t * which protocol we are associated with since we can give it a\n\t * list.\n\t */\n\tif (/*(i->method || i->local_protocol_name) && */local) {\n\t\tlwsl_info(\"binding to %s\\n\", local);\n\t\tp = lws_vhost_name_to_protocol(wsi->vhost, local);\n\t\tif (p)\n\t\t\twsi->protocol = p;\n\t}\n\n\tif (wsi && !wsi->user_space && i->userdata) {\n\t\twsi->user_space_externally_allocated = 1;\n\t\twsi->user_space = i->userdata;\n\t} else\n\t\t/* if we stay in http, we can assign the user space now,\n\t\t * otherwise do it after the protocol negotiated\n\t\t */\n\t\tif (i->method)\n\t\t\tif (lws_ensure_user_space(wsi))\n\t\t\t\tgoto bail;\n\n#if defined(LWS_WITH_TLS)\n\twsi->tls.use_ssl = i->ssl_connection;\n#else\n\tif (i->ssl_connection & LCCSCF_USE_SSL) {\n\t\tlwsl_err(\"libwebsockets not configured for ssl\\n\");\n\t\tgoto bail;\n\t}\n#endif\n\n\t/* 2) stash the things from connect_info that we can't process without\n\t * an ah.  Because if no ah, we will go on the ah waiting list and\n\t * process those things later (after the connect_info and maybe the\n\t * things pointed to have gone out of scope.\n\t */\n\n\twsi->stash = lws_zalloc(sizeof(*wsi->stash), \"client stash\");\n\tif (!wsi->stash) {\n\t\tlwsl_err(\"%s: OOM\\n\", __func__);\n\t\tgoto bail1;\n\t}\n\n\twsi->stash->address = lws_strdup(i->address);\n\twsi->stash->path = lws_strdup(i->path);\n\twsi->stash->host = lws_strdup(i->host);\n\n\tif (!wsi->stash->address || !wsi->stash->path || !wsi->stash->host)\n\t\tgoto bail1;\n\n\tif (i->origin) {\n\t\twsi->stash->origin = lws_strdup(i->origin);\n\t\tif (!wsi->stash->origin)\n\t\t\tgoto bail1;\n\t}\n\tif (i->protocol) {\n\t\twsi->stash->protocol = lws_strdup(i->protocol);\n\t\tif (!wsi->stash->protocol)\n\t\t\tgoto bail1;\n\t}\n\tif (i->method) {\n\t\twsi->stash->method = lws_strdup(i->method);\n\t\tif (!wsi->stash->method)\n\t\t\tgoto bail1;\n\t}\n\tif (i->iface) {\n\t\twsi->stash->iface = lws_strdup(i->iface);\n\t\tif (!wsi->stash->iface)\n\t\t\tgoto bail1;\n\t}\n\t /*\n\t  * For ws, default to http/1.1 only.  If i->alpn is set, defer to\n\t  * whatever he has set in there (eg, \"h2\").\n\t  *\n\t  * The problem is he has to commit to h2 before he can find out if the\n\t  * server has the SETTINGS for ws-over-h2 enabled; if not then ws is\n\t  * not possible on that connection.  So we only try it if he\n\t  * assertively said to use h2 alpn.\n\t  */\n\tif (!i->method && !i->alpn) {\n\t\twsi->stash->alpn = lws_strdup(\"http/1.1\");\n\t\tif (!wsi->stash->alpn)\n\t\t\tgoto bail1;\n\t} else\n\t\tif (i->alpn) {\n\t\t\twsi->stash->alpn = lws_strdup(i->alpn);\n\t\t\tif (!wsi->stash->alpn)\n\t\t\t\tgoto bail1;\n\t\t}\n\n\tif (i->pwsi)\n\t\t*i->pwsi = wsi;\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\t/* if we went on the waiting list, no probs just return the wsi\n\t * when we get the ah, now or later, he will call\n\t * lws_client_connect_via_info2() below.\n\t */\n\tif (lws_header_table_attach(wsi, 0) < 0) {\n\t\t/*\n\t\t * if we failed here, the connection is already closed\n\t\t * and freed.\n\t\t */\n\t\tgoto bail2;\n\t}\n\n#endif\n\n\tif (i->parent_wsi) {\n\t\tlwsl_info(\"%s: created child %p of parent %p\\n\", __func__,\n\t\t\t\twsi, i->parent_wsi);\n\t\twsi->parent = i->parent_wsi;\n\t\twsi->sibling_list = i->parent_wsi->child_list;\n\t\ti->parent_wsi->child_list = wsi;\n\t}\n#ifdef LWS_WITH_HTTP_PROXY\n\tif (i->uri_replace_to)\n\t\twsi->http.rw = lws_rewrite_create(wsi, html_parser_cb,\n\t\t\t\t\t     i->uri_replace_from,\n\t\t\t\t\t     i->uri_replace_to);\n#endif\n\n\treturn wsi;\n\nbail1:\n\tlws_client_stash_destroy(wsi);\n\nbail:\n\tlws_free(wsi);\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\nbail2:\n#endif\n\tif (i->pwsi)\n\t\t*i->pwsi = NULL;\n\n\treturn NULL;\n}\n\nstruct lws *\nlws_client_connect_via_info2(struct lws *wsi)\n{\n\tstruct client_info_stash *stash = wsi->stash;\n\n\tif (!stash)\n\t\treturn wsi;\n\n\t/*\n\t * we're not necessarily in a position to action these right away,\n\t * stash them... we only need during connect phase so into a temp\n\t * allocated stash\n\t */\n\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS,\n\t\t\t\t  stash->address))\n\t\tgoto bail1;\n\n\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_URI, stash->path))\n\t\tgoto bail1;\n\n\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_HOST, stash->host))\n\t\tgoto bail1;\n\n\tif (stash->origin)\n\t\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_ORIGIN,\n\t\t\t\t\t  stash->origin))\n\t\t\tgoto bail1;\n\t/*\n\t * this is a list of protocols we tell the server we're okay with\n\t * stash it for later when we compare server response with it\n\t */\n\tif (stash->protocol)\n\t\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS,\n\t\t\t\t\t  stash->protocol))\n\t\t\tgoto bail1;\n\tif (stash->method)\n\t\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_METHOD,\n\t\t\t\t\t  stash->method))\n\t\t\tgoto bail1;\n\tif (stash->iface)\n\t\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_IFACE,\n\t\t\t\t\t  stash->iface))\n\t\t\tgoto bail1;\n\tif (stash->alpn)\n\t\tif (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_ALPN,\n\t\t\t\t\t  stash->alpn))\n\t\t\tgoto bail1;\n\n#if defined(LWS_WITH_SOCKS5)\n\tif (!wsi->vhost->socks_proxy_port)\n\t\tlws_client_stash_destroy(wsi);\n#endif\n\n\twsi->context->count_wsi_allocated++;\n\n\treturn lws_client_connect_2(wsi);\n\nbail1:\n#if defined(LWS_WITH_SOCKS5)\n\tif (!wsi->vhost->socks_proxy_port)\n\t\tlws_free_set_NULL(wsi->stash);\n#endif\n\n\treturn NULL;\n}\n\nLWS_VISIBLE struct lws *\nlws_client_connect_extended(struct lws_context *context, const char *address,\n\t\t\t    int port, int ssl_connection, const char *path,\n\t\t\t    const char *host, const char *origin,\n\t\t\t    const char *protocol, int ietf_version_or_minus_one,\n\t\t\t    void *userdata)\n{\n\tstruct lws_client_connect_info i;\n\n\tmemset(&i, 0, sizeof(i));\n\n\ti.context = context;\n\ti.address = address;\n\ti.port = port;\n\ti.ssl_connection = ssl_connection;\n\ti.path = path;\n\ti.host = host;\n\ti.origin = origin;\n\ti.protocol = protocol;\n\ti.ietf_version_or_minus_one = ietf_version_or_minus_one;\n\ti.userdata = userdata;\n\n\treturn lws_client_connect_via_info(&i);\n}\n\nLWS_VISIBLE struct lws *\nlws_client_connect(struct lws_context *context, const char *address,\n\t\t\t    int port, int ssl_connection, const char *path,\n\t\t\t    const char *host, const char *origin,\n\t\t\t    const char *protocol, int ietf_version_or_minus_one)\n{\n\tstruct lws_client_connect_info i;\n\n\tmemset(&i, 0, sizeof(i));\n\n\ti.context = context;\n\ti.address = address;\n\ti.port = port;\n\ti.ssl_connection = ssl_connection;\n\ti.path = path;\n\ti.host = host;\n\ti.origin = origin;\n\ti.protocol = protocol;\n\ti.ietf_version_or_minus_one = ietf_version_or_minus_one;\n\ti.userdata = NULL;\n\n\treturn lws_client_connect_via_info(&i);\n}\n\n#if defined(LWS_WITH_SOCKS5)\nvoid socks_generate_msg(struct lws *wsi, enum socks_msg_type type,\n\t\t\tssize_t *msg_len)\n{\n\tstruct lws_context *context = wsi->context;\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tssize_t len = 0, n, passwd_len;\n\tshort net_num;\n\tchar *p;\n\n\tswitch (type) {\n\tcase SOCKS_MSG_GREETING:\n\t\t/* socks version, version 5 only */\n\t\tpt->serv_buf[len++] = SOCKS_VERSION_5;\n\t\t/* number of methods */\n\t\tpt->serv_buf[len++] = 2;\n\t\t/* username password method */\n\t\tpt->serv_buf[len++] = SOCKS_AUTH_USERNAME_PASSWORD;\n\t\t/* no authentication method */\n\t\tpt->serv_buf[len++] = SOCKS_AUTH_NO_AUTH;\n\t\tbreak;\n\n\tcase SOCKS_MSG_USERNAME_PASSWORD:\n\t\tn = strlen(wsi->vhost->socks_user);\n\t\tpasswd_len = strlen(wsi->vhost->socks_password);\n\n\t\t/* the subnegotiation version */\n\t\tpt->serv_buf[len++] = SOCKS_SUBNEGOTIATION_VERSION_1;\n\t\t/* length of the user name */\n\t\tpt->serv_buf[len++] = n;\n\t\t/* user name */\n\t\tlws_strncpy((char *)&pt->serv_buf[len], wsi->vhost->socks_user,\n\t\t\tcontext->pt_serv_buf_size - len + 1);\n\t\tlen += n;\n\t\t/* length of the password */\n\t\tpt->serv_buf[len++] = passwd_len;\n\t\t/* password */\n\t\tlws_strncpy((char *)&pt->serv_buf[len], wsi->vhost->socks_password,\n\t\t\tcontext->pt_serv_buf_size - len + 1);\n\t\tlen += passwd_len;\n\t\tbreak;\n\n\tcase SOCKS_MSG_CONNECT:\n\t\tp = (char*)&net_num;\n\n\t\t/* socks version */\n\t\tpt->serv_buf[len++] = SOCKS_VERSION_5;\n\t\t/* socks command */\n\t\tpt->serv_buf[len++] = SOCKS_COMMAND_CONNECT;\n\t\t/* reserved */\n\t\tpt->serv_buf[len++] = 0;\n\t\t/* address type */\n\t\tpt->serv_buf[len++] = SOCKS_ATYP_DOMAINNAME;\n\t\t/* skip length, we fill it in at the end */\n\t\tn = len++;\n\n\t\t/* the address we tell SOCKS proxy to connect to */\n\t\tlws_strncpy((char *)&(pt->serv_buf[len]), wsi->stash->address,\n\t\t\tcontext->pt_serv_buf_size - len + 1);\n\t\tlen += strlen(wsi->stash->address);\n\t\tnet_num = htons(wsi->c_port);\n\n\t\t/* the port we tell SOCKS proxy to connect to */\n\t\tpt->serv_buf[len++] = p[0];\n\t\tpt->serv_buf[len++] = p[1];\n\n\t\t/* the length of the address, excluding port */\n\t\tpt->serv_buf[n] = strlen(wsi->stash->address);\n\t\tbreak;\n\t\t\n\tdefault:\n\t\treturn;\n\t}\n\n\t*msg_len = len;\n}\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/http/client/client.c",
    "content": "/*\n * libwebsockets - lib/client/client.c\n *\n * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n\nLWS_VISIBLE LWS_EXTERN void\nlws_client_http_body_pending(struct lws *wsi, int something_left_to_send)\n{\n\twsi->client_http_body_pending = !!something_left_to_send;\n}\n\n/*\n * return self, or queued client wsi we are acting on behalf of\n *\n * That is the TAIL of the queue (new queue elements are added at the HEAD)\n */\n\nstruct lws *\nlws_client_wsi_effective(struct lws *wsi)\n{\n\tstruct lws_dll_lws *tail = NULL;\n\n\tif (!wsi->transaction_from_pipeline_queue ||\n\t    !wsi->dll_client_transaction_queue_head.next)\n\t\treturn wsi;\n\n\tlws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1,\n\t\t\t\t   wsi->dll_client_transaction_queue_head.next) {\n\t\ttail = d;\n\t} lws_end_foreach_dll_safe(d, d1);\n\n\treturn lws_container_of(tail, struct lws,\n\t\t\t\t  dll_client_transaction_queue);\n}\n\n/*\n * return self or the guy we are queued under\n *\n * REQUIRES VHOST LOCK HELD\n */\n\nstatic struct lws *\n_lws_client_wsi_master(struct lws *wsi)\n{\n\tstruct lws *wsi_eff = wsi;\n\tstruct lws_dll_lws *d;\n\n\td = wsi->dll_client_transaction_queue.prev;\n\twhile (d) {\n\t\twsi_eff = lws_container_of(d, struct lws,\n\t\t\t\t\tdll_client_transaction_queue_head);\n\n\t\td = d->prev;\n\t}\n\n\treturn wsi_eff;\n}\n\nint\nlws_client_socket_service(struct lws *wsi, struct lws_pollfd *pollfd,\n\t\t\t  struct lws *wsi_conn)\n{\n\tstruct lws_context *context = wsi->context;\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tchar *p = (char *)&pt->serv_buf[0];\n\tstruct lws *w;\n#if defined(LWS_WITH_TLS)\n\tchar ebuf[128];\n#endif\n\tconst char *cce = NULL;\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tssize_t len = 0;\n\tunsigned char c;\n#endif\n\tchar *sb = p;\n\tint n = 0;\n#if defined(LWS_WITH_SOCKS5)\n\tint conn_mode = 0, pending_timeout = 0;\n#endif\n\n\tif ((pollfd->revents & LWS_POLLOUT) &&\n\t     wsi->keepalive_active &&\n\t     wsi->dll_client_transaction_queue_head.next) {\n\t\tstruct lws *wfound = NULL;\n\n\t\tlwsl_debug(\"%s: pollout HANDSHAKE2\\n\", __func__);\n\n\t\t/*\n\t\t * We have a transaction queued that wants to pipeline.\n\t\t *\n\t\t * We have to allow it to send headers strictly in the order\n\t\t * that it was queued, ie, tail-first.\n\t\t */\n\t\tlws_vhost_lock(wsi->vhost);\n\t\tlws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1,\n\t\t\t\t\t   wsi->dll_client_transaction_queue_head.next) {\n\t\t\tstruct lws *w = lws_container_of(d, struct lws,\n\t\t\t\t\t\t  dll_client_transaction_queue);\n\n\t\t\tlwsl_debug(\"%s: %p states 0x%x\\n\", __func__, w, w->wsistate);\n\t\t\tif (lwsi_state(w) == LRS_H1C_ISSUE_HANDSHAKE2)\n\t\t\t\twfound = w;\n\t\t} lws_end_foreach_dll_safe(d, d1);\n\n\t\tif (wfound) {\n\t\t\t/*\n\t\t\t * pollfd has the master sockfd in it... we\n\t\t\t * need to use that in HANDSHAKE2 to understand\n\t\t\t * which wsi to actually write on\n\t\t\t */\n\t\t\tlws_client_socket_service(wfound, pollfd, wsi);\n\t\t\tlws_callback_on_writable(wsi);\n\t\t} else\n\t\t\tlwsl_debug(\"%s: didn't find anything in txn q in HS2\\n\",\n\t\t\t\t\t\t\t   __func__);\n\n\t\tlws_vhost_unlock(wsi->vhost);\n\n\t\treturn 0;\n\t}\n\n\tswitch (lwsi_state(wsi)) {\n\n\tcase LRS_WAITING_CONNECT:\n\n\t\t/*\n\t\t * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE\n\t\t * timeout protection set in client-handshake.c\n\t\t */\n\n\t\tif (!lws_client_connect_2(wsi)) {\n\t\t\t/* closed */\n\t\t\tlwsl_client(\"closed\\n\");\n\t\t\treturn -1;\n\t\t}\n\n\t\t/* either still pending connection, or changed mode */\n\t\treturn 0;\n\n#if defined(LWS_WITH_SOCKS5)\n\t/* SOCKS Greeting Reply */\n\tcase LRS_WAITING_SOCKS_GREETING_REPLY:\n\tcase LRS_WAITING_SOCKS_AUTH_REPLY:\n\tcase LRS_WAITING_SOCKS_CONNECT_REPLY:\n\n\t\t/* handle proxy hung up on us */\n\n\t\tif (pollfd->revents & LWS_POLLHUP) {\n\t\t\tlwsl_warn(\"SOCKS connection %p (fd=%d) dead\\n\",\n\t\t\t\t  (void *)wsi, pollfd->fd);\n\t\t\tgoto bail3;\n\t\t}\n\n\t\tn = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0);\n\t\tif (n < 0) {\n\t\t\tif (LWS_ERRNO == LWS_EAGAIN) {\n\t\t\t\tlwsl_debug(\"SOCKS read EAGAIN, retrying\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tlwsl_err(\"ERROR reading from SOCKS socket\\n\");\n\t\t\tgoto bail3;\n\t\t}\n\n\t\tswitch (lwsi_state(wsi)) {\n\n\t\tcase LRS_WAITING_SOCKS_GREETING_REPLY:\n\t\t\tif (pt->serv_buf[0] != SOCKS_VERSION_5)\n\t\t\t\tgoto socks_reply_fail;\n\n\t\t\tif (pt->serv_buf[1] == SOCKS_AUTH_NO_AUTH) {\n\t\t\t\tlwsl_client(\"SOCKS GR: No Auth Method\\n\");\n\t\t\t\tsocks_generate_msg(wsi, SOCKS_MSG_CONNECT, &len);\n\t\t\t\tconn_mode = LRS_WAITING_SOCKS_CONNECT_REPLY;\n\t\t\t\tpending_timeout =\n\t\t\t\t   PENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY;\n\t\t\t\tgoto socks_send;\n\t\t\t}\n\n\t\t\tif (pt->serv_buf[1] == SOCKS_AUTH_USERNAME_PASSWORD) {\n\t\t\t\tlwsl_client(\"SOCKS GR: User/Pw Method\\n\");\n\t\t\t\tsocks_generate_msg(wsi,\n\t\t\t\t\t\t   SOCKS_MSG_USERNAME_PASSWORD,\n\t\t\t\t\t\t   &len);\n\t\t\t\tconn_mode = LRS_WAITING_SOCKS_AUTH_REPLY;\n\t\t\t\tpending_timeout =\n\t\t\t\t      PENDING_TIMEOUT_AWAITING_SOCKS_AUTH_REPLY;\n\t\t\t\tgoto socks_send;\n\t\t\t}\n\t\t\tgoto socks_reply_fail;\n\n\t\tcase LRS_WAITING_SOCKS_AUTH_REPLY:\n\t\t\tif (pt->serv_buf[0] != SOCKS_SUBNEGOTIATION_VERSION_1 ||\n\t\t\t    pt->serv_buf[1] != SOCKS_SUBNEGOTIATION_STATUS_SUCCESS)\n\t\t\t\tgoto socks_reply_fail;\n\n\t\t\tlwsl_client(\"SOCKS password OK, sending connect\\n\");\n\t\t\tsocks_generate_msg(wsi, SOCKS_MSG_CONNECT, &len);\n\t\t\tconn_mode = LRS_WAITING_SOCKS_CONNECT_REPLY;\n\t\t\tpending_timeout =\n\t\t\t\t   PENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY;\nsocks_send:\n\t\t\tn = send(wsi->desc.sockfd, (char *)pt->serv_buf, len,\n\t\t\t\t MSG_NOSIGNAL);\n\t\t\tif (n < 0) {\n\t\t\t\tlwsl_debug(\"ERROR writing to socks proxy\\n\");\n\t\t\t\tgoto bail3;\n\t\t\t}\n\n\t\t\tlws_set_timeout(wsi, pending_timeout, AWAITING_TIMEOUT);\n\t\t\tlwsi_set_state(wsi, conn_mode);\n\t\t\tbreak;\n\nsocks_reply_fail:\n\t\t\tlwsl_notice(\"socks reply: v%d, err %d\\n\",\n\t\t\t\t    pt->serv_buf[0], pt->serv_buf[1]);\n\t\t\tgoto bail3;\n\n\t\tcase LRS_WAITING_SOCKS_CONNECT_REPLY:\n\t\t\tif (pt->serv_buf[0] != SOCKS_VERSION_5 ||\n\t\t\t    pt->serv_buf[1] != SOCKS_REQUEST_REPLY_SUCCESS)\n\t\t\t\tgoto socks_reply_fail;\n\n\t\t\tlwsl_client(\"socks connect OK\\n\");\n\n\t\t\t/* free stash since we are done with it */\n\t\t\tlws_client_stash_destroy(wsi);\n\t\t\tif (lws_hdr_simple_create(wsi,\n\t\t\t\t\t\t  _WSI_TOKEN_CLIENT_PEER_ADDRESS,\n\t\t\t\t\t\t  wsi->vhost->socks_proxy_address))\n\t\t\t\tgoto bail3;\n\n\t\t\twsi->c_port = wsi->vhost->socks_proxy_port;\n\n\t\t\t/* clear his proxy connection timeout */\n\t\t\tlws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);\n\t\t\tgoto start_ws_handshake;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n#endif\n\n\tcase LRS_WAITING_PROXY_REPLY:\n\n\t\t/* handle proxy hung up on us */\n\n\t\tif (pollfd->revents & LWS_POLLHUP) {\n\n\t\t\tlwsl_warn(\"Proxy connection %p (fd=%d) dead\\n\",\n\t\t\t\t  (void *)wsi, pollfd->fd);\n\n\t\t\tgoto bail3;\n\t\t}\n\n\t\tn = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0);\n\t\tif (n < 0) {\n\t\t\tif (LWS_ERRNO == LWS_EAGAIN) {\n\t\t\t\tlwsl_debug(\"Proxy read EAGAIN... retrying\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tlwsl_err(\"ERROR reading from proxy socket\\n\");\n\t\t\tgoto bail3;\n\t\t}\n\n\t\tpt->serv_buf[13] = '\\0';\n\t\tif (strcmp(sb, \"HTTP/1.0 200 \") &&\n\t\t    strcmp(sb, \"HTTP/1.1 200 \")) {\n\t\t\tlwsl_err(\"ERROR proxy: %s\\n\", sb);\n\t\t\tgoto bail3;\n\t\t}\n\n\t\t/* clear his proxy connection timeout */\n\n\t\tlws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);\n\n\t\t/* fallthru */\n\n\tcase LRS_H1C_ISSUE_HANDSHAKE:\n\n\t\t/*\n\t\t * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE\n\t\t * timeout protection set in client-handshake.c\n\t\t *\n\t\t * take care of our lws_callback_on_writable\n\t\t * happening at a time when there's no real connection yet\n\t\t */\n#if defined(LWS_WITH_SOCKS5)\nstart_ws_handshake:\n#endif\n\t\tif (lws_change_pollfd(wsi, LWS_POLLOUT, 0))\n\t\t\treturn -1;\n\n#if defined(LWS_WITH_TLS)\n\t\t/* we can retry this... just cook the SSL BIO the first time */\n\n\t\tif ((wsi->tls.use_ssl & LCCSCF_USE_SSL) && !wsi->tls.ssl &&\n\t\t    lws_ssl_client_bio_create(wsi) < 0) {\n\t\t\tcce = \"bio_create failed\";\n\t\t\tgoto bail3;\n\t\t}\n\n\t\tif (wsi->tls.use_ssl & LCCSCF_USE_SSL) {\n\t\t\tn = lws_ssl_client_connect1(wsi);\n\t\t\tif (!n)\n\t\t\t\treturn 0;\n\t\t\tif (n < 0) {\n\t\t\t\tcce = \"lws_ssl_client_connect1 failed\";\n\t\t\t\tgoto bail3;\n\t\t\t}\n\t\t} else\n\t\t\twsi->tls.ssl = NULL;\n\n\t\t/* fallthru */\n\n\tcase LRS_WAITING_SSL:\n\n\t\tif (wsi->tls.use_ssl & LCCSCF_USE_SSL) {\n\t\t\tn = lws_ssl_client_connect2(wsi, ebuf, sizeof(ebuf));\n\t\t\tif (!n)\n\t\t\t\treturn 0;\n\t\t\tif (n < 0) {\n\t\t\t\tcce = ebuf;\n\t\t\t\tgoto bail3;\n\t\t\t}\n\t\t} else\n\t\t\twsi->tls.ssl = NULL;\n#endif\n#if defined (LWS_WITH_HTTP2)\n\t\tif (wsi->client_h2_alpn) {\n\t\t\t/*\n\t\t\t * We connected to the server and set up tls, and\n\t\t\t * negotiated \"h2\".\n\t\t\t *\n\t\t\t * So this is it, we are an h2 master client connection\n\t\t\t * now, not an h1 client connection.\n\t\t\t */\n\t\t\tlws_tls_server_conn_alpn(wsi);\n\n\t\t\t/* send the H2 preface to legitimize the connection */\n\t\t\tif (lws_h2_issue_preface(wsi)) {\n\t\t\t\tcce = \"error sending h2 preface\";\n\t\t\t\tgoto bail3;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n#endif\n\t\tlwsi_set_state(wsi, LRS_H1C_ISSUE_HANDSHAKE2);\n\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND,\n\t\t\t\tcontext->timeout_secs);\n\n\t\t/* fallthru */\n\n\tcase LRS_H1C_ISSUE_HANDSHAKE2:\n\t\tp = lws_generate_client_handshake(wsi, p);\n\t\tif (p == NULL) {\n\t\t\tif (wsi->role_ops == &role_ops_raw_skt ||\n\t\t\t    wsi->role_ops == &role_ops_raw_file)\n\t\t\t\treturn 0;\n\n\t\t\tlwsl_err(\"Failed to generate handshake for client\\n\");\n\t\t\tlws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, \"chs\");\n\t\t\treturn 0;\n\t\t}\n\n\t\t/* send our request to the server */\n\t\tlws_latency_pre(context, wsi);\n\n\t\tw = _lws_client_wsi_master(wsi);\n\t\tlwsl_info(\"%s: HANDSHAKE2: %p: sending headers on %p (wsistate 0x%x 0x%x)\\n\",\n\t\t\t\t__func__, wsi, w, wsi->wsistate, w->wsistate);\n\n\t\tn = lws_ssl_capable_write(w, (unsigned char *)sb, (int)(p - sb));\n\t\tlws_latency(context, wsi, \"send lws_issue_raw\", n,\n\t\t\t    n == p - sb);\n\t\tswitch (n) {\n\t\tcase LWS_SSL_CAPABLE_ERROR:\n\t\t\tlwsl_debug(\"ERROR writing to client socket\\n\");\n\t\t\tlws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, \"cws\");\n\t\t\treturn 0;\n\t\tcase LWS_SSL_CAPABLE_MORE_SERVICE:\n\t\t\tlws_callback_on_writable(wsi);\n\t\t\tbreak;\n\t\t}\n\n\t\tif (wsi->client_http_body_pending) {\n\t\t\tlwsi_set_state(wsi, LRS_ISSUE_HTTP_BODY);\n\t\t\tlws_set_timeout(wsi,\n\t\t\t\t\tPENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD,\n\t\t\t\t\tcontext->timeout_secs);\n\t\t\t/* user code must ask for writable callback */\n\t\t\tbreak;\n\t\t}\n\n\t\tlwsi_set_state(wsi, LRS_WAITING_SERVER_REPLY);\n\t\twsi->hdr_parsing_completed = 0;\n\n\t\tif (lwsi_state(w) == LRS_IDLING) {\n\t\t\tlwsi_set_state(w, LRS_WAITING_SERVER_REPLY);\n\t\t\tw->hdr_parsing_completed = 0;\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\t\t\tw->http.ah->parser_state = WSI_TOKEN_NAME_PART;\n\t\t\tw->http.ah->lextable_pos = 0;\n\t\t\t/* If we're (re)starting on headers, need other implied init */\n\t\t\twsi->http.ah->ues = URIES_IDLE;\n#endif\n\t\t}\n\n\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE,\n\t\t\t\twsi->context->timeout_secs);\n\n\t\tlws_callback_on_writable(w);\n\n\t\tgoto client_http_body_sent;\n\n\tcase LRS_ISSUE_HTTP_BODY:\n\t\tif (wsi->client_http_body_pending) {\n\t\t\t//lws_set_timeout(wsi,\n\t\t\t//\t\tPENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD,\n\t\t\t//\t\tcontext->timeout_secs);\n\t\t\t/* user code must ask for writable callback */\n\t\t\tbreak;\n\t\t}\nclient_http_body_sent:\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\t\t/* prepare ourselves to do the parsing */\n\t\twsi->http.ah->parser_state = WSI_TOKEN_NAME_PART;\n\t\twsi->http.ah->lextable_pos = 0;\n#endif\n\t\tlwsi_set_state(wsi, LRS_WAITING_SERVER_REPLY);\n\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE,\n\t\t\t\tcontext->timeout_secs);\n\t\tbreak;\n\n\tcase LRS_WAITING_SERVER_REPLY:\n\t\t/*\n\t\t * handle server hanging up on us...\n\t\t * but if there is POLLIN waiting, handle that first\n\t\t */\n\t\tif ((pollfd->revents & (LWS_POLLIN | LWS_POLLHUP)) ==\n\t\t\t\t\t\t\t\tLWS_POLLHUP) {\n\n\t\t\tlwsl_debug(\"Server connection %p (fd=%d) dead\\n\",\n\t\t\t\t(void *)wsi, pollfd->fd);\n\t\t\tcce = \"Peer hung up\";\n\t\t\tgoto bail3;\n\t\t}\n\n\t\tif (!(pollfd->revents & LWS_POLLIN))\n\t\t\tbreak;\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\t\t/* interpret the server response\n\t\t *\n\t\t *  HTTP/1.1 101 Switching Protocols\n\t\t *  Upgrade: websocket\n\t\t *  Connection: Upgrade\n\t\t *  Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=\n\t\t *  Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==\n\t\t *  Sec-WebSocket-Protocol: chat\n\t\t *\n\t\t * we have to take some care here to only take from the\n\t\t * socket bytewise.  The browser may (and has been seen to\n\t\t * in the case that onopen() performs websocket traffic)\n\t\t * coalesce both handshake response and websocket traffic\n\t\t * in one packet, since at that point the connection is\n\t\t * definitively ready from browser pov.\n\t\t */\n\t\tlen = 1;\n\t\twhile (wsi->http.ah->parser_state != WSI_PARSING_COMPLETE &&\n\t\t       len > 0) {\n\t\t\tint plen = 1;\n\n\t\t\tn = lws_ssl_capable_read(wsi, &c, 1);\n\t\t\tlws_latency(context, wsi, \"send lws_issue_raw\", n,\n\t\t\t\t    n == 1);\n\t\t\tswitch (n) {\n\t\t\tcase 0:\n\t\t\tcase LWS_SSL_CAPABLE_ERROR:\n\t\t\t\tcce = \"read failed\";\n\t\t\t\tgoto bail3;\n\t\t\tcase LWS_SSL_CAPABLE_MORE_SERVICE:\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tif (lws_parse(wsi, &c, &plen)) {\n\t\t\t\tlwsl_warn(\"problems parsing header\\n\");\n\t\t\t\tgoto bail3;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * hs may also be coming in multiple packets, there is a 5-sec\n\t\t * libwebsocket timeout still active here too, so if parsing did\n\t\t * not complete just wait for next packet coming in this state\n\t\t */\n\t\tif (wsi->http.ah->parser_state != WSI_PARSING_COMPLETE)\n\t\t\tbreak;\n\n#endif\n\n\t\t/*\n\t\t * otherwise deal with the handshake.  If there's any\n\t\t * packet traffic already arrived we'll trigger poll() again\n\t\t * right away and deal with it that way\n\t\t */\n\t\treturn lws_client_interpret_server_handshake(wsi);\n\nbail3:\n\t\tlwsl_info(\"closing conn at LWS_CONNMODE...SERVER_REPLY\\n\");\n\t\tif (cce)\n\t\t\tlwsl_info(\"reason: %s\\n\", cce);\n\t\twsi->protocol->callback(wsi,\n\t\t\tLWS_CALLBACK_CLIENT_CONNECTION_ERROR,\n\t\t\twsi->user_space, (void *)cce, cce ? strlen(cce) : 0);\n\t\twsi->already_did_cce = 1;\n\t\tlws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, \"cbail3\");\n\t\treturn -1;\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\nint LWS_WARN_UNUSED_RESULT\nlws_http_transaction_completed_client(struct lws *wsi)\n{\n\tstruct lws *wsi_eff = lws_client_wsi_effective(wsi);\n\n\tlwsl_info(\"%s: wsi: %p, wsi_eff: %p\\n\", __func__, wsi, wsi_eff);\n\n\tif (user_callback_handle_rxflow(wsi_eff->protocol->callback,\n\t\t\twsi_eff, LWS_CALLBACK_COMPLETED_CLIENT_HTTP,\n\t\t\twsi_eff->user_space, NULL, 0)) {\n\t\tlwsl_debug(\"%s: Completed call returned nonzero (role 0x%x)\\n\",\n\t\t\t\t\t\t__func__, lwsi_role(wsi_eff));\n\t\treturn -1;\n\t}\n\n\t/*\n\t * Are we constitutionally capable of having a queue, ie, we are on\n\t * the \"active client connections\" list?\n\t *\n\t * If not, that's it for us.\n\t */\n\n\tif (lws_dll_is_null(&wsi->dll_active_client_conns))\n\t\treturn -1;\n\n\t/* if this was a queued guy, close him and remove from queue */\n\n\tif (wsi->transaction_from_pipeline_queue) {\n\t\tlwsl_debug(\"closing queued wsi %p\\n\", wsi_eff);\n\t\t/* so the close doesn't trigger a CCE */\n\t\twsi_eff->already_did_cce = 1;\n\t\t__lws_close_free_wsi(wsi_eff,\n\t\t\tLWS_CLOSE_STATUS_CLIENT_TRANSACTION_DONE,\n\t\t\t\"queued client done\");\n\t}\n\n\t_lws_header_table_reset(wsi->http.ah);\n\n\t/* after the first one, they can only be coming from the queue */\n\twsi->transaction_from_pipeline_queue = 1;\n\n\twsi->http.rx_content_length = 0;\n\twsi->hdr_parsing_completed = 0;\n\n\t/* is there a new tail after removing that one? */\n\twsi_eff = lws_client_wsi_effective(wsi);\n\n\t/*\n\t * Do we have something pipelined waiting?\n\t * it's OK if he hasn't managed to send his headers yet... he's next\n\t * in line to do that...\n\t */\n\tif (wsi_eff == wsi) {\n\t\t/*\n\t\t * Nothing pipelined... we should hang around a bit\n\t\t * in case something turns up...\n\t\t */\n\t\tlwsl_info(\"%s: nothing pipelined waiting\\n\", __func__);\n\t\tlwsi_set_state(wsi, LRS_IDLING);\n\n\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_CLIENT_CONN_IDLE, 5);\n\n\t\treturn 0;\n\t}\n\n\t/*\n\t * H1: we can serialize the queued guys into the same ah\n\t * H2: everybody needs their own ah until their own STREAM_END\n\t */\n\n\t/* otherwise set ourselves up ready to go again */\n\tlwsi_set_state(wsi, LRS_WAITING_SERVER_REPLY);\n\n\twsi->http.ah->parser_state = WSI_TOKEN_NAME_PART;\n\twsi->http.ah->lextable_pos = 0;\n\n\tlws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE,\n\t\t\twsi->context->timeout_secs);\n\n\t/* If we're (re)starting on headers, need other implied init */\n\twsi->http.ah->ues = URIES_IDLE;\n\n\tlwsl_info(\"%s: %p: new queued transaction as %p\\n\", __func__, wsi, wsi_eff);\n\tlws_callback_on_writable(wsi);\n\n\treturn 0;\n}\n\nLWS_VISIBLE LWS_EXTERN unsigned int\nlws_http_client_http_response(struct lws *_wsi)\n{\n\tstruct lws *wsi;\n\tunsigned int resp;\n\n\tif (_wsi->http.ah && _wsi->http.ah->http_response)\n\t\treturn _wsi->http.ah->http_response;\n\n\tlws_vhost_lock(_wsi->vhost);\n\twsi = _lws_client_wsi_master(_wsi);\n\tresp = wsi->http.ah->http_response;\n\tlws_vhost_unlock(_wsi->vhost);\n\n\treturn resp;\n}\n#endif\n#if defined(LWS_PLAT_OPTEE)\nchar *\nstrrchr(const char *s, int c)\n{\n\tchar *hit = NULL;\n\n\twhile (*s)\n\t\tif (*(s++) == (char)c)\n\t\t       hit = (char *)s - 1;\n\n\treturn hit;\n}\n\n#define atoll atoi\n#endif\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\nint\nlws_client_interpret_server_handshake(struct lws *wsi)\n{\n\tint n, port = 0, ssl = 0;\n\tint close_reason = LWS_CLOSE_STATUS_PROTOCOL_ERR;\n\tconst char *prot, *ads = NULL, *path, *cce = NULL;\n\tstruct allocated_headers *ah = NULL;\n\tstruct lws *w = lws_client_wsi_effective(wsi);\n\tchar *p, *q;\n\tchar new_path[300];\n\n\tlws_client_stash_destroy(wsi);\n\n\tah = wsi->http.ah;\n\tif (!wsi->do_ws) {\n\t\t/* we are being an http client...\n\t\t */\n#if defined(LWS_ROLE_H2)\n\t\tif (wsi->client_h2_alpn || wsi->client_h2_substream) {\n\t\t\tlwsl_debug(\"%s: %p: transitioning to h2 client\\n\", __func__, wsi);\n\t\t\tlws_role_transition(wsi, LWSIFR_CLIENT,\n\t\t\t\t\t    LRS_ESTABLISHED, &role_ops_h2);\n\t\t} else\n#endif\n\t\t{\n#if defined(LWS_ROLE_H1)\n\t\t\t{\n\t\t\tlwsl_debug(\"%s: %p: transitioning to h1 client\\n\", __func__, wsi);\n\t\t\tlws_role_transition(wsi, LWSIFR_CLIENT,\n\t\t\t\t\t    LRS_ESTABLISHED, &role_ops_h1);\n\t\t\t}\n#else\n\t\t\treturn -1;\n#endif\n\t\t}\n\n\t\twsi->http.ah = ah;\n\t\tah->http_response = 0;\n\t}\n\n\t/*\n\t * well, what the server sent looked reasonable for syntax.\n\t * Now let's confirm it sent all the necessary headers\n\t *\n\t * http (non-ws) client will expect something like this\n\t *\n\t * HTTP/1.0.200\n\t * server:.libwebsockets\n\t * content-type:.text/html\n\t * content-length:.17703\n\t * set-cookie:.test=LWS_1456736240_336776_COOKIE;Max-Age=360000\n\t */\n\n\twsi->http.connection_type = HTTP_CONNECTION_KEEP_ALIVE;\n\tif (!wsi->client_h2_substream) {\n\t\tp = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP);\n\t\tif (wsi->do_ws && !p) {\n\t\t\tlwsl_info(\"no URI\\n\");\n\t\t\tcce = \"HS: URI missing\";\n\t\t\tgoto bail3;\n\t\t}\n\t\tif (!p) {\n\t\t\tp = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP1_0);\n\t\t\twsi->http.connection_type = HTTP_CONNECTION_CLOSE;\n\t\t}\n\t\tif (!p) {\n\t\t\tcce = \"HS: URI missing\";\n\t\t\tlwsl_info(\"no URI\\n\");\n\t\t\tgoto bail3;\n\t\t}\n\t} else {\n\t\tp = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COLON_STATUS);\n\t\tif (!p) {\n\t\t\tcce = \"HS: :status missing\";\n\t\t\tlwsl_info(\"no status\\n\");\n\t\t\tgoto bail3;\n\t\t}\n\t}\n\tn = atoi(p);\n\tif (ah)\n\t\tah->http_response = n;\n\n\tif (n == 301 || n == 302 || n == 303 || n == 307 || n == 308) {\n\t\tp = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_LOCATION);\n\t\tif (!p) {\n\t\t\tcce = \"HS: Redirect code but no Location\";\n\t\t\tgoto bail3;\n\t\t}\n\n\t\t/* Relative reference absolute path */\n\t\tif (p[0] == '/') {\n#if defined(LWS_WITH_TLS)\n\t\t\tssl = wsi->tls.use_ssl & LCCSCF_USE_SSL;\n#endif\n\t\t\tads = lws_hdr_simple_ptr(wsi,\n\t\t\t\t\t\t _WSI_TOKEN_CLIENT_PEER_ADDRESS);\n\t\t\tport = wsi->c_port;\n\t\t\t/* +1 as lws_client_reset expects leading / omitted */\n\t\t\tpath = p + 1;\n\t\t}\n\t\t/* Absolute (Full) URI */\n\t\telse if (strchr(p, ':')) {\n\t\t\tif (lws_parse_uri(p, &prot, &ads, &port, &path)) {\n\t\t\t\tcce = \"HS: URI did not parse\";\n\t\t\t\tgoto bail3;\n\t\t\t}\n\n\t\t\tif (!strcmp(prot, \"wss\") || !strcmp(prot, \"https\"))\n\t\t\t\tssl = 1;\n\t\t}\n\t\t/* Relative reference relative path */\n\t\telse {\n\t\t\t/* This doesn't try to calculate an absolute path,\n\t\t\t * that will be left to the server */\n#if defined(LWS_WITH_TLS)\n\t\t\tssl = wsi->tls.use_ssl & LCCSCF_USE_SSL;\n#endif\n\t\t\tads = lws_hdr_simple_ptr(wsi,\n\t\t\t\t\t\t _WSI_TOKEN_CLIENT_PEER_ADDRESS);\n\t\t\tport = wsi->c_port;\n\t\t\t/* +1 as lws_client_reset expects leading / omitted */\n\t\t\tpath = new_path + 1;\n\t\t\tlws_strncpy(new_path, lws_hdr_simple_ptr(wsi,\n\t\t\t\t   _WSI_TOKEN_CLIENT_URI), sizeof(new_path));\n\t\t\tq = strrchr(new_path, '/');\n\t\t\tif (q)\n\t\t\t\tlws_strncpy(q + 1, p, sizeof(new_path) -\n\t\t\t\t\t\t\t(q - new_path) - 1);\n\t\t\telse\n\t\t\t\tpath = p;\n\t\t}\n\n#if defined(LWS_WITH_TLS)\n\t\tif ((wsi->tls.use_ssl & LCCSCF_USE_SSL) && !ssl) {\n\t\t\tcce = \"HS: Redirect attempted SSL downgrade\";\n\t\t\tgoto bail3;\n\t\t}\n#endif\n\n\t\tif (!lws_client_reset(&wsi, ssl, ads, port, path, ads)) {\n\t\t\t/* there are two ways to fail out with NULL return...\n\t\t\t * simple, early problem where the wsi is intact, or\n\t\t\t * we went through with the reconnect attempt and the\n\t\t\t * wsi is already closed.  In the latter case, the wsi\n\t\t\t * has beet set to NULL additionally.\n\t\t\t */\n\t\t\tlwsl_err(\"Redirect failed\\n\");\n\t\t\tcce = \"HS: Redirect failed\";\n\t\t\tif (wsi)\n\t\t\t\tgoto bail3;\n\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tif (!wsi->do_ws) {\n\n\t\t/* if h1 KA is allowed, enable the queued pipeline guys */\n\n\t\tif (!wsi->client_h2_alpn && !wsi->client_h2_substream && w == wsi) { /* ie, coming to this for the first time */\n\t\t\tif (wsi->http.connection_type == HTTP_CONNECTION_KEEP_ALIVE)\n\t\t\t\twsi->keepalive_active = 1;\n\t\t\telse {\n\t\t\t\t/*\n\t\t\t\t * Ugh... now the main http connection has seen\n\t\t\t\t * both sides, we learn the server doesn't\n\t\t\t\t * support keepalive.\n\t\t\t\t *\n\t\t\t\t * That means any guys queued on us are going\n\t\t\t\t * to have to be restarted from connect2 with\n\t\t\t\t * their own connections.\n\t\t\t\t */\n\n\t\t\t\t/*\n\t\t\t\t * stick around telling any new guys they can't\n\t\t\t\t * pipeline to this server\n\t\t\t\t */\n\t\t\t\twsi->keepalive_rejected = 1;\n\n\t\t\t\tlws_vhost_lock(wsi->vhost);\n\t\t\t\tlws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1,\n\t\t\t\t\t\t\t   wsi->dll_client_transaction_queue_head.next) {\n\t\t\t\t\tstruct lws *ww = lws_container_of(d, struct lws,\n\t\t\t\t\t\t\t\t  dll_client_transaction_queue);\n\n\t\t\t\t\t/* remove him from our queue */\n\t\t\t\t\tlws_dll_lws_remove(&ww->dll_client_transaction_queue);\n\t\t\t\t\t/* give up on pipelining */\n\t\t\t\t\tww->client_pipeline = 0;\n\n\t\t\t\t\t/* go back to \"trying to connect\" state */\n\t\t\t\t\tlws_role_transition(ww, LWSIFR_CLIENT,\n\t\t\t\t\t\t\t    LRS_UNCONNECTED,\n#if defined(LWS_ROLE_H1)\n\t\t\t\t\t\t\t    &role_ops_h1);\n#else\n#if defined (LWS_ROLE_H2)\n\t\t\t\t\t\t\t    &role_ops_h2);\n#else\n\t\t\t\t\t\t\t    &role_ops_raw);\n#endif\n#endif\n\t\t\t\t\tww->user_space = NULL;\n\t\t\t\t} lws_end_foreach_dll_safe(d, d1);\n\t\t\t\tlws_vhost_unlock(wsi->vhost);\n\t\t\t}\n\t\t}\n\n#ifdef LWS_WITH_HTTP_PROXY\n\t\twsi->http.perform_rewrite = 0;\n\t\tif (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {\n\t\t\tif (!strncmp(lws_hdr_simple_ptr(wsi,\n\t\t\t\t\t\tWSI_TOKEN_HTTP_CONTENT_TYPE),\n\t\t\t\t\t\t\"text/html\", 9))\n\t\t\t\twsi->http.perform_rewrite = 1;\n\t\t}\n#endif\n\n\t\t/* allocate the per-connection user memory (if any) */\n\t\tif (lws_ensure_user_space(wsi)) {\n\t\t\tlwsl_err(\"Problem allocating wsi user mem\\n\");\n\t\t\tcce = \"HS: OOM\";\n\t\t\tgoto bail2;\n\t\t}\n\n\t\t/* he may choose to send us stuff in chunked transfer-coding */\n\t\twsi->chunked = 0;\n\t\twsi->chunk_remaining = 0; /* ie, next thing is chunk size */\n\t\tif (lws_hdr_total_length(wsi,\n\t\t\t\t\tWSI_TOKEN_HTTP_TRANSFER_ENCODING)) {\n\t\t\twsi->chunked = !strcmp(lws_hdr_simple_ptr(wsi,\n\t\t\t\t\t       WSI_TOKEN_HTTP_TRANSFER_ENCODING),\n\t\t\t\t\t\t\"chunked\");\n\t\t\t/* first thing is hex, after payload there is crlf */\n\t\t\twsi->chunk_parser = ELCP_HEX;\n\t\t}\n\n\t\tif (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {\n\t\t\twsi->http.rx_content_length =\n\t\t\t\t\tatoll(lws_hdr_simple_ptr(wsi,\n\t\t\t\t\t\tWSI_TOKEN_HTTP_CONTENT_LENGTH));\n\t\t\tlwsl_info(\"%s: incoming content length %llu\\n\",\n\t\t\t\t    __func__, (unsigned long long)\n\t\t\t\t\t    wsi->http.rx_content_length);\n\t\t\twsi->http.rx_content_remain =\n\t\t\t\t\twsi->http.rx_content_length;\n\t\t} else /* can't do 1.1 without a content length or chunked */\n\t\t\tif (!wsi->chunked)\n\t\t\t\twsi->http.connection_type =\n\t\t\t\t\t\t\tHTTP_CONNECTION_CLOSE;\n\n\t\t/*\n\t\t * we seem to be good to go, give client last chance to check\n\t\t * headers and OK it\n\t\t */\n\t\tif (w->protocol->callback(w,\n\t\t\t\tLWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,\n\t\t\t\t\t    w->user_space, NULL, 0)) {\n\n\t\t\tcce = \"HS: disallowed by client filter\";\n\t\t\tgoto bail2;\n\t\t}\n\n\t\t/* clear his proxy connection timeout */\n\t\tlws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);\n\n\t\twsi->rxflow_change_to = LWS_RXFLOW_ALLOW;\n\n\t\t/* call him back to inform him he is up */\n\t\tif (w->protocol->callback(w,\n\t\t\t\t\t    LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP,\n\t\t\t\t\t    w->user_space, NULL, 0)) {\n\t\t\tcce = \"HS: disallowed at ESTABLISHED\";\n\t\t\tgoto bail3;\n\t\t}\n\n\t\t/*\n\t\t * for pipelining, master needs to keep his ah... guys who\n\t\t * queued on him can drop it now though.\n\t\t */\n\n\t\tif (w != wsi)\n\t\t\t/* free up parsing allocations for queued guy */\n\t\t\tlws_header_table_detach(w, 0);\n\n\t\tlwsl_info(\"%s: client connection up\\n\", __func__);\n\n\t\treturn 0;\n\t}\n\n#if defined(LWS_ROLE_WS)\n\tswitch (lws_client_ws_upgrade(wsi, &cce)) {\n\tcase 2:\n\t\tgoto bail2;\n\tcase 3:\n\t\tgoto bail3;\n\t}\n\n\treturn 0;\n#endif\n\nbail3:\n\tclose_reason = LWS_CLOSE_STATUS_NOSTATUS;\n\nbail2:\n\tif (wsi->protocol) {\n\t\tn = 0;\n\t\tif (cce)\n\t\t\tn = (int)strlen(cce);\n\t\tw->protocol->callback(w,\n\t\t\t\tLWS_CALLBACK_CLIENT_CONNECTION_ERROR,\n\t\t\t\tw->user_space, (void *)cce,\n\t\t\t\t(unsigned int)n);\n\t}\n\twsi->already_did_cce = 1;\n\n\tlwsl_info(\"closing connection due to bail2 connection error\\n\");\n\n\t/* closing will free up his parsing allocations */\n\tlws_close_free_wsi(wsi, close_reason, \"c hs interp\");\n\n\treturn 1;\n}\n#endif\n\nchar *\nlws_generate_client_handshake(struct lws *wsi, char *pkt)\n{\n\tchar *p = pkt;\n\tconst char *meth;\n\tconst char *pp = lws_hdr_simple_ptr(wsi,\n\t\t\t\t_WSI_TOKEN_CLIENT_SENT_PROTOCOLS);\n\n\tmeth = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_METHOD);\n\tif (!meth) {\n\t\tmeth = \"GET\";\n\t\twsi->do_ws = 1;\n\t} else {\n\t\twsi->do_ws = 0;\n\t}\n\n\tif (!strcmp(meth, \"RAW\")) {\n\t\tlws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);\n\t\tlwsl_notice(\"client transition to raw\\n\");\n\n\t\tif (pp) {\n\t\t\tconst struct lws_protocols *pr;\n\n\t\t\tpr = lws_vhost_name_to_protocol(wsi->vhost, pp);\n\n\t\t\tif (!pr) {\n\t\t\t\tlwsl_err(\"protocol %s not enabled on vhost\\n\",\n\t\t\t\t\t pp);\n\t\t\t\treturn NULL;\n\t\t\t}\n\n\t\t\tlws_bind_protocol(wsi, pr);\n\t\t}\n\n\t\tif ((wsi->protocol->callback)(wsi, LWS_CALLBACK_RAW_ADOPT,\n\t\t\t\t\t      wsi->user_space, NULL, 0))\n\t\t\treturn NULL;\n\n\t\tlws_role_transition(wsi, 0, LRS_ESTABLISHED, &role_ops_raw_skt);\n\t\tlws_header_table_detach(wsi, 1);\n\n\t\treturn NULL;\n\t}\n\n\t/*\n\t * 04 example client handshake\n\t *\n\t * GET /chat HTTP/1.1\n\t * Host: server.example.com\n\t * Upgrade: websocket\n\t * Connection: Upgrade\n\t * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\n\t * Sec-WebSocket-Origin: http://example.com\n\t * Sec-WebSocket-Protocol: chat, superchat\n\t * Sec-WebSocket-Version: 4\n\t */\n\n\tp += sprintf(p, \"%s %s HTTP/1.1\\x0d\\x0a\", meth,\n\t\t     lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI));\n\n\tp += sprintf(p, \"Pragma: no-cache\\x0d\\x0a\"\n\t\t\t\"Cache-Control: no-cache\\x0d\\x0a\");\n\n\tp += sprintf(p, \"Host: %s\\x0d\\x0a\",\n\t\t     lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_HOST));\n\n\tif (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN)) {\n\t\tif (lws_check_opt(wsi->context->options,\n\t\t\t\t  LWS_SERVER_OPTION_JUST_USE_RAW_ORIGIN))\n\t\t\tp += sprintf(p, \"Origin: %s\\x0d\\x0a\",\n\t\t\t\t     lws_hdr_simple_ptr(wsi,\n\t\t\t\t\t\t     _WSI_TOKEN_CLIENT_ORIGIN));\n\t\telse\n\t\t\tp += sprintf(p, \"Origin: http://%s\\x0d\\x0a\",\n\t\t\t\t     lws_hdr_simple_ptr(wsi,\n\t\t\t\t\t\t     _WSI_TOKEN_CLIENT_ORIGIN));\n\t}\n#if defined(LWS_ROLE_WS)\n\tif (wsi->do_ws)\n\t\tp = lws_generate_client_ws_handshake(wsi, p);\n#endif\n\n\t/* give userland a chance to append, eg, cookies */\n\n\tif (wsi->protocol->callback(wsi,\n\t\t\t\tLWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,\n\t\t\t\twsi->user_space, &p,\n\t\t\t\t(pkt + wsi->context->pt_serv_buf_size) - p - 12))\n\t\treturn NULL;\n\n\tp += sprintf(p, \"\\x0d\\x0a\");\n\n\treturn p;\n}\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\nLWS_VISIBLE int\nlws_http_client_read(struct lws *wsi, char **buf, int *len)\n{\n\tint rlen, n;\n\n\trlen = lws_ssl_capable_read(wsi, (unsigned char *)*buf, *len);\n\t*len = 0;\n\n\t// lwsl_notice(\"%s: rlen %d\\n\", __func__, rlen);\n\n\t/* allow the source to signal he has data again next time */\n\tlws_change_pollfd(wsi, 0, LWS_POLLIN);\n\n\tif (rlen == LWS_SSL_CAPABLE_ERROR) {\n\t\tlwsl_notice(\"%s: SSL capable error\\n\", __func__);\n\t\treturn -1;\n\t}\n\n\tif (rlen == 0)\n\t\treturn -1;\n\n\tif (rlen < 0)\n\t\treturn 0;\n\n\t*len = rlen;\n\twsi->client_rx_avail = 0;\n\n\t/*\n\t * server may insist on transfer-encoding: chunked,\n\t * so http client must deal with it\n\t */\nspin_chunks:\n\twhile (wsi->chunked && (wsi->chunk_parser != ELCP_CONTENT) && *len) {\n\t\tswitch (wsi->chunk_parser) {\n\t\tcase ELCP_HEX:\n\t\t\tif ((*buf)[0] == '\\x0d') {\n\t\t\t\twsi->chunk_parser = ELCP_CR;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tn = char_to_hex((*buf)[0]);\n\t\t\tif (n < 0) {\n\t\t\t\tlwsl_debug(\"chunking failure\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\twsi->chunk_remaining <<= 4;\n\t\t\twsi->chunk_remaining |= n;\n\t\t\tbreak;\n\t\tcase ELCP_CR:\n\t\t\tif ((*buf)[0] != '\\x0a') {\n\t\t\t\tlwsl_debug(\"chunking failure\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\twsi->chunk_parser = ELCP_CONTENT;\n\t\t\tlwsl_info(\"chunk %d\\n\", wsi->chunk_remaining);\n\t\t\tif (wsi->chunk_remaining)\n\t\t\t\tbreak;\n\t\t\tlwsl_info(\"final chunk\\n\");\n\t\t\tgoto completed;\n\n\t\tcase ELCP_CONTENT:\n\t\t\tbreak;\n\n\t\tcase ELCP_POST_CR:\n\t\t\tif ((*buf)[0] != '\\x0d') {\n\t\t\t\tlwsl_debug(\"chunking failure\\n\");\n\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\twsi->chunk_parser = ELCP_POST_LF;\n\t\t\tbreak;\n\n\t\tcase ELCP_POST_LF:\n\t\t\tif ((*buf)[0] != '\\x0a')\n\t\t\t\treturn -1;\n\n\t\t\twsi->chunk_parser = ELCP_HEX;\n\t\t\twsi->chunk_remaining = 0;\n\t\t\tbreak;\n\t\t}\n\t\t(*buf)++;\n\t\t(*len)--;\n\t}\n\n\tif (wsi->chunked && !wsi->chunk_remaining)\n\t\treturn 0;\n\n\tif (wsi->http.rx_content_remain &&\n\t    wsi->http.rx_content_remain < (unsigned int)*len)\n\t\tn = (int)wsi->http.rx_content_remain;\n\telse\n\t\tn = *len;\n\n\tif (wsi->chunked && wsi->chunk_remaining &&\n\t    wsi->chunk_remaining < n)\n\t\tn = wsi->chunk_remaining;\n\n#ifdef LWS_WITH_HTTP_PROXY\n\t/* hubbub */\n\tif (wsi->http.perform_rewrite)\n\t\tlws_rewrite_parse(wsi->http.rw, (unsigned char *)*buf, n);\n\telse\n#endif\n\t{\n\t\tstruct lws *wsi_eff = lws_client_wsi_effective(wsi);\n\n\t\tif (user_callback_handle_rxflow(wsi_eff->protocol->callback,\n\t\t\t\twsi_eff, LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ,\n\t\t\t\twsi_eff->user_space, *buf, n)) {\n\t\t\tlwsl_debug(\"%s: RECEIVE_CLIENT_HTTP_READ returned -1\\n\",\n\t\t\t\t   __func__);\n\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tif (wsi->chunked && wsi->chunk_remaining) {\n\t\t(*buf) += n;\n\t\twsi->chunk_remaining -= n;\n\t\t*len -= n;\n\t}\n\n\tif (wsi->chunked && !wsi->chunk_remaining)\n\t\twsi->chunk_parser = ELCP_POST_CR;\n\n\tif (wsi->chunked && *len)\n\t\tgoto spin_chunks;\n\n\tif (wsi->chunked)\n\t\treturn 0;\n\n\t/* if we know the content length, decrement the content remaining */\n\tif (wsi->http.rx_content_length > 0)\n\t\twsi->http.rx_content_remain -= n;\n\n\t// lwsl_notice(\"rx_content_remain %lld, rx_content_length %lld\\n\",\n\t//\twsi->http.rx_content_remain, wsi->http.rx_content_length);\n\n\tif (wsi->http.rx_content_remain || !wsi->http.rx_content_length)\n\t\treturn 0;\n\ncompleted:\n\n\tif (lws_http_transaction_completed_client(wsi)) {\n\t\tlwsl_notice(\"%s: transaction completed says -1\\n\", __func__);\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/http/header.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n#include \"lextable-strings.h\"\n\n\nconst unsigned char *\nlws_token_to_string(enum lws_token_indexes token)\n{\n\tif ((unsigned int)token >= LWS_ARRAY_SIZE(set))\n\t\treturn NULL;\n\n\treturn (unsigned char *)set[token];\n}\n\nint\nlws_add_http_header_by_name(struct lws *wsi, const unsigned char *name,\n\t\t\t    const unsigned char *value, int length,\n\t\t\t    unsigned char **p, unsigned char *end)\n{\n#ifdef LWS_WITH_HTTP2\n\tif (lwsi_role_h2(wsi) || lwsi_role_h2_ENCAPSULATION(wsi))\n\t\treturn lws_add_http2_header_by_name(wsi, name,\n\t\t\t\t\t\t    value, length, p, end);\n#else\n\t(void)wsi;\n#endif\n\tif (name) {\n\t\twhile (*p < end && *name)\n\t\t\t*((*p)++) = *name++;\n\t\tif (*p == end)\n\t\t\treturn 1;\n\t\t*((*p)++) = ' ';\n\t}\n\tif (*p + length + 3 >= end)\n\t\treturn 1;\n\n\tmemcpy(*p, value, length);\n\t*p += length;\n\t*((*p)++) = '\\x0d';\n\t*((*p)++) = '\\x0a';\n\n\treturn 0;\n}\n\nint lws_finalize_http_header(struct lws *wsi, unsigned char **p,\n\t\t\t     unsigned char *end)\n{\n#ifdef LWS_WITH_HTTP2\n\tif (lwsi_role_h2(wsi) || lwsi_role_h2_ENCAPSULATION(wsi))\n\t\treturn 0;\n#else\n\t(void)wsi;\n#endif\n\tif ((lws_intptr_t)(end - *p) < 3)\n\t\treturn 1;\n\t*((*p)++) = '\\x0d';\n\t*((*p)++) = '\\x0a';\n\n\treturn 0;\n}\n\nint\nlws_finalize_write_http_header(struct lws *wsi, unsigned char *start,\n\t\t\t       unsigned char **pp, unsigned char *end)\n{\n\tunsigned char *p;\n\tint len;\n\n\tif (lws_finalize_http_header(wsi, pp, end))\n\t\treturn 1;\n\n\tp = *pp;\n\tlen = lws_ptr_diff(p, start);\n\n\tif (lws_write(wsi, start, len, LWS_WRITE_HTTP_HEADERS) != len)\n\t\treturn 1;\n\n\treturn 0;\n}\n\nint\nlws_add_http_header_by_token(struct lws *wsi, enum lws_token_indexes token,\n\t\t\t     const unsigned char *value, int length,\n\t\t\t     unsigned char **p, unsigned char *end)\n{\n\tconst unsigned char *name;\n#ifdef LWS_WITH_HTTP2\n\tif (lwsi_role_h2(wsi) || lwsi_role_h2_ENCAPSULATION(wsi))\n\t\treturn lws_add_http2_header_by_token(wsi, token, value,\n\t\t\t\t\t\t     length, p, end);\n#endif\n\tname = lws_token_to_string(token);\n\tif (!name)\n\t\treturn 1;\n\n\treturn lws_add_http_header_by_name(wsi, name, value, length, p, end);\n}\n\nint lws_add_http_header_content_length(struct lws *wsi,\n\t\t\t\t       lws_filepos_t content_length,\n\t\t\t\t       unsigned char **p, unsigned char *end)\n{\n\tchar b[24];\n\tint n;\n\n\tn = sprintf(b, \"%llu\", (unsigned long long)content_length);\n\tif (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH,\n\t\t\t\t\t (unsigned char *)b, n, p, end))\n\t\treturn 1;\n\twsi->http.tx_content_length = content_length;\n\twsi->http.tx_content_remain = content_length;\n\n\tlwsl_info(\"%s: wsi %p: tx_content_length/remain %llu\\n\", __func__,\n\t\t\twsi, (unsigned long long)content_length);\n\n\treturn 0;\n}\n\nint\nlws_add_http_common_headers(struct lws *wsi, unsigned int code,\n\t\t\t    const char *content_type, lws_filepos_t content_len,\n\t\t\t    unsigned char **p, unsigned char *end)\n{\n\tif (lws_add_http_header_status(wsi, code, p, end))\n\t\treturn 1;\n\n\tif (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,\n\t\t    \t\t\t(unsigned char *)content_type,\n\t\t    \t\t\t(int)strlen(content_type), p, end))\n\t\treturn 1;\n\n\tif (content_len != LWS_ILLEGAL_HTTP_CONTENT_LEN) {\n\t\tif (lws_add_http_header_content_length(wsi, content_len, p, end))\n\t\t\treturn 1;\n\t} else {\n\t\tif (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,\n\t\t\t\t\t\t (unsigned char *)\"close\", 5,\n\t\t\t\t\t\t p, end))\n\t\t\treturn 1;\n\n\t\twsi->http.connection_type = HTTP_CONNECTION_CLOSE;\n\t}\n\n\treturn 0;\n}\n\nSTORE_IN_ROM static const char * const err400[] = {\n\t\"Bad Request\",\n\t\"Unauthorized\",\n\t\"Payment Required\",\n\t\"Forbidden\",\n\t\"Not Found\",\n\t\"Method Not Allowed\",\n\t\"Not Acceptable\",\n\t\"Proxy Auth Required\",\n\t\"Request Timeout\",\n\t\"Conflict\",\n\t\"Gone\",\n\t\"Length Required\",\n\t\"Precondition Failed\",\n\t\"Request Entity Too Large\",\n\t\"Request URI too Long\",\n\t\"Unsupported Media Type\",\n\t\"Requested Range Not Satisfiable\",\n\t\"Expectation Failed\"\n};\n\nSTORE_IN_ROM static const char * const err500[] = {\n\t\"Internal Server Error\",\n\t\"Not Implemented\",\n\t\"Bad Gateway\",\n\t\"Service Unavailable\",\n\t\"Gateway Timeout\",\n\t\"HTTP Version Not Supported\"\n};\n\nint\nlws_add_http_header_status(struct lws *wsi, unsigned int _code,\n\t\t\t   unsigned char **p, unsigned char *end)\n{\n\tSTORE_IN_ROM static const char * const hver[] = {\n\t\t\"HTTP/1.0\", \"HTTP/1.1\", \"HTTP/2\"\n\t};\n\tconst struct lws_protocol_vhost_options *headers;\n\tunsigned int code = _code & LWSAHH_CODE_MASK;\n\tconst char *description = \"\", *p1;\n\tunsigned char code_and_desc[60];\n\tint n;\n\n#ifdef LWS_WITH_ACCESS_LOG\n\twsi->http.access_log.response = code;\n#endif\n\n#ifdef LWS_WITH_HTTP2\n\tif (lwsi_role_h2(wsi) || lwsi_role_h2_ENCAPSULATION(wsi)) {\n\t\tn = lws_add_http2_header_status(wsi, code, p, end);\n\t\tif (n)\n\t\t\treturn n;\n\t} else\n#endif\n\t{\n\t\tif (code >= 400 && code < (400 + LWS_ARRAY_SIZE(err400)))\n\t\t\tdescription = err400[code - 400];\n\t\tif (code >= 500 && code < (500 + LWS_ARRAY_SIZE(err500)))\n\t\t\tdescription = err500[code - 500];\n\n\t\tif (code == 100)\n\t\t\tdescription = \"Continue\";\n\t\tif (code == 200)\n\t\t\tdescription = \"OK\";\n\t\tif (code == 304)\n\t\t\tdescription = \"Not Modified\";\n\t\telse\n\t\t\tif (code >= 300 && code < 400)\n\t\t\t\tdescription = \"Redirect\";\n\n\t\tif (wsi->http.request_version < LWS_ARRAY_SIZE(hver))\n\t\t\tp1 = hver[wsi->http.request_version];\n\t\telse\n\t\t\tp1 = hver[0];\n\n\t\tn = sprintf((char *)code_and_desc, \"%s %u %s\", p1, code,\n\t\t\t    description);\n\n\t\tif (lws_add_http_header_by_name(wsi, NULL, code_and_desc, n, p,\n\t\t\t\t\t\tend))\n\t\t\treturn 1;\n\t}\n\theaders = wsi->vhost->headers;\n\twhile (headers) {\n\t\tif (lws_add_http_header_by_name(wsi,\n\t\t\t\t(const unsigned char *)headers->name,\n\t\t\t\t(unsigned char *)headers->value,\n\t\t\t\t(int)strlen(headers->value), p, end))\n\t\t\treturn 1;\n\n\t\theaders = headers->next;\n\t}\n\n\tif (wsi->context->server_string &&\n\t    !(_code & LWSAHH_FLAG_NO_SERVER_NAME))\n\t\tif (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,\n\t\t\t\t(unsigned char *)wsi->context->server_string,\n\t\t\t\twsi->context->server_string_len, p, end))\n\t\t\treturn 1;\n\n\tif (wsi->vhost->options & LWS_SERVER_OPTION_STS)\n\t\tif (lws_add_http_header_by_name(wsi, (unsigned char *)\n\t\t\t\t\"Strict-Transport-Security:\",\n\t\t\t\t(unsigned char *)\"max-age=15768000 ; \"\n\t\t\t\t\"includeSubDomains\", 36, p, end))\n\t\t\treturn 1;\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\nlws_return_http_status(struct lws *wsi, unsigned int code,\n\t\t       const char *html_body)\n{\n\tstruct lws_context *context = lws_get_context(wsi);\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tunsigned char *p = pt->serv_buf + LWS_PRE;\n\tunsigned char *start = p;\n\tunsigned char *end = p + context->pt_serv_buf_size - LWS_PRE;\n\tint n = 0, m = 0, len;\n\tchar slen[20];\n\n\tif (!wsi->vhost) {\n\t\tlwsl_err(\"%s: wsi not bound to vhost\\n\", __func__);\n\n\t\treturn 1;\n\t}\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tif (!wsi->handling_404 &&\n\t    wsi->vhost->http.error_document_404 &&\n\t    code == HTTP_STATUS_NOT_FOUND)\n\t\t/* we should do a redirect, and do the 404 there */\n\t\tif (lws_http_redirect(wsi, HTTP_STATUS_FOUND,\n\t\t\t\t       (uint8_t *)wsi->vhost->http.error_document_404,\n\t\t\t\t       (int)strlen(wsi->vhost->http.error_document_404),\n\t\t\t\t       &p, end) > 0)\n\t\t\treturn 0;\n#endif\n\n\t/* if the redirect failed, just do a simple status */\n\tp = start;\n\n\tif (!html_body)\n\t\thtml_body = \"\";\n\n\tif (lws_add_http_header_status(wsi, code, &p, end))\n\t\treturn 1;\n\n\tif (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,\n\t\t\t\t\t (unsigned char *)\"text/html\", 9,\n\t\t\t\t\t &p, end))\n\t\treturn 1;\n\n\tlen = 35 + (int)strlen(html_body) + sprintf(slen, \"%d\", code);\n\tn = sprintf(slen, \"%d\", len);\n\n\tif (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH,\n\t\t\t\t\t (unsigned char *)slen, n, &p, end))\n\t\treturn 1;\n\n\tif (lws_finalize_http_header(wsi, &p, end))\n\t\treturn 1;\n\n#if defined(LWS_WITH_HTTP2)\n\tif (wsi->http2_substream) {\n\t\tunsigned char *body = p + 512;\n\n\t\t/*\n\t\t * for HTTP/2, the headers must be sent separately, since they\n\t\t * go out in their own frame.  That puts us in a bind that\n\t\t * we won't always be able to get away with two lws_write()s in\n\t\t * sequence, since the first may use up the writability due to\n\t\t * the pipe being choked or SSL_WANT_.\n\t\t *\n\t\t * However we do need to send the human-readable body, and the\n\t\t * END_STREAM.\n\t\t *\n\t\t * Solve it by writing the headers now...\n\t\t */\n\t\tm = lws_write(wsi, start, p - start, LWS_WRITE_HTTP_HEADERS);\n\t\tif (m != lws_ptr_diff(p, start))\n\t\t\treturn 1;\n\n\t\t/*\n\t\t * ... but stash the body and send it as a priority next\n\t\t * handle_POLLOUT\n\t\t */\n\n\t\tlen = sprintf((char *)body,\n\t\t\t      \"<html><body><h1>%u</h1>%s</body></html>\",\n\t\t\t      code, html_body);\n\t\twsi->http.tx_content_length = len;\n\t\twsi->http.tx_content_remain = len;\n\n\t\twsi->h2.pending_status_body = lws_malloc(len + LWS_PRE + 1,\n\t\t\t\t\t\t\t\"pending status body\");\n\t\tif (!wsi->h2.pending_status_body)\n\t\t\treturn -1;\n\n\t\tstrcpy(wsi->h2.pending_status_body + LWS_PRE,\n\t\t       (const char *)body);\n\t\tlws_callback_on_writable(wsi);\n\n\t\treturn 0;\n\t} else\n#endif\n\t{\n\t\t/*\n\t\t * for http/1, we can just append the body after the finalized\n\t\t * headers and send it all in one go.\n\t\t */\n\t\tp += lws_snprintf((char *)p, end - p - 1,\n\t\t\t\t  \"<html><body><h1>%u</h1>%s</body></html>\",\n\t\t\t\t  code, html_body);\n\n\t\tn = lws_ptr_diff(p, start);\n\t\tm = lws_write(wsi, start, n, LWS_WRITE_HTTP);\n\t\tif (m != n)\n\t\t\treturn 1;\n\t}\n\n\treturn m != n;\n}\n\nLWS_VISIBLE int\nlws_http_redirect(struct lws *wsi, int code, const unsigned char *loc, int len,\n\t\t  unsigned char **p, unsigned char *end)\n{\n\tunsigned char *start = *p;\n\n\tif (lws_add_http_header_status(wsi, code, p, end))\n\t\treturn -1;\n\n\tif (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_LOCATION, loc, len,\n\t\t\t\t\t p, end))\n\t\treturn -1;\n\t/*\n\t * if we're going with http/1.1 and keepalive, we have to give fake\n\t * content metadata so the client knows we completed the transaction and\n\t * it can do the redirect...\n\t */\n\tif (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,\n\t\t\t\t\t (unsigned char *)\"text/html\", 9, p,\n\t\t\t\t\t end))\n\t\treturn -1;\n\tif (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH,\n\t\t\t\t\t (unsigned char *)\"0\", 1, p, end))\n\t\treturn -1;\n\n\tif (lws_finalize_http_header(wsi, p, end))\n\t\treturn -1;\n\n\treturn lws_write(wsi, start, *p - start, LWS_WRITE_HTTP_HEADERS |\n\t\t\t\t\t\t LWS_WRITE_H2_STREAM_END);\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/http/lextable-strings.h",
    "content": "/* set of parsable strings -- ALL LOWER CASE */\n\n#if !defined(STORE_IN_ROM)\n#define STORE_IN_ROM\n#endif\n\nSTORE_IN_ROM static const char * const set[] = {\n\t\"get \",\n\t\"post \",\n\t\"options \",\n\t\"host:\",\n\t\"connection:\",\n\t\"upgrade:\",\n\t\"origin:\",\n\t\"sec-websocket-draft:\",\n\t\"\\x0d\\x0a\",\n\n\t\"sec-websocket-extensions:\",\n\t\"sec-websocket-key1:\",\n\t\"sec-websocket-key2:\",\n\t\"sec-websocket-protocol:\",\n\n\t\"sec-websocket-accept:\",\n\t\"sec-websocket-nonce:\",\n\t\"http/1.1 \",\n\t\"http2-settings:\",\n\n\t\"accept:\",\n\t\"access-control-request-headers:\",\n\t\"if-modified-since:\",\n\t\"if-none-match:\",\n\t\"accept-encoding:\",\n\t\"accept-language:\",\n\t\"pragma:\",\n\t\"cache-control:\",\n\t\"authorization:\",\n\t\"cookie:\",\n\t\"content-length:\",\n\t\"content-type:\",\n\t\"date:\",\n\t\"range:\",\n\t\"referer:\",\n\t\"sec-websocket-key:\",\n\t\"sec-websocket-version:\",\n\t\"sec-websocket-origin:\",\n\n\t\":authority\",\n\t\":method\",\n\t\":path\",\n\t\":scheme\",\n\t\":status\",\n\n\t\"accept-charset:\",\n\t\"accept-ranges:\",\n\t\"access-control-allow-origin:\",\n\t\"age:\",\n\t\"allow:\",\n\t\"content-disposition:\",\n\t\"content-encoding:\",\n\t\"content-language:\",\n\t\"content-location:\",\n\t\"content-range:\",\n\t\"etag:\",\n\t\"expect:\",\n\t\"expires:\",\n\t\"from:\",\n\t\"if-match:\",\n\t\"if-range:\",\n\t\"if-unmodified-since:\",\n\t\"last-modified:\",\n\t\"link:\",\n\t\"location:\",\n\t\"max-forwards:\",\n\t\"proxy-authenticate:\",\n\t\"proxy-authorization:\",\n\t\"refresh:\",\n\t\"retry-after:\",\n\t\"server:\",\n\t\"set-cookie:\",\n\t\"strict-transport-security:\",\n\t\"transfer-encoding:\",\n\t\"user-agent:\",\n\t\"vary:\",\n\t\"via:\",\n\t\"www-authenticate:\",\n\n\t\"patch\",\n\t\"put\",\n\t\"delete\",\n\n\t\"uri-args\", /* fake header used for uri-only storage */\n\n\t\"proxy \",\n\t\"x-real-ip:\",\n\t\"http/1.0 \",\n\n\t\"x-forwarded-for\",\n\t\"connect \",\n\t\"head \",\n\t\"te:\",\t\t/* http/2 wants it to reject it */\n\t\"replay-nonce:\", /* ACME */\n\t\":protocol\",\t\t/* defined in mcmanus-httpbis-h2-ws-02 */\n\n\t\"x-auth-token:\",\n\n\t\"\", /* not matchable */\n\n};\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/http/lextable.h",
    "content": "/* pos 0000:   0 */    0x67 /* 'g' */, 0x40, 0x00  /* (to 0x0040 state   1) */,\n                       0x70 /* 'p' */, 0x42, 0x00  /* (to 0x0045 state   5) */,\n                       0x6F /* 'o' */, 0x51, 0x00  /* (to 0x0057 state  10) */,\n                       0x68 /* 'h' */, 0x5D, 0x00  /* (to 0x0066 state  18) */,\n                       0x63 /* 'c' */, 0x69, 0x00  /* (to 0x0075 state  23) */,\n                       0x75 /* 'u' */, 0x8A, 0x00  /* (to 0x0099 state  34) */,\n                       0x73 /* 's' */, 0xA0, 0x00  /* (to 0x00B2 state  48) */,\n                       0x0D /* '.' */, 0xD9, 0x00  /* (to 0x00EE state  68) */,\n                       0x61 /* 'a' */, 0x31, 0x01  /* (to 0x0149 state 129) */,\n                       0x69 /* 'i' */, 0x70, 0x01  /* (to 0x018B state 163) */,\n                       0x64 /* 'd' */, 0x19, 0x02  /* (to 0x0237 state 265) */,\n                       0x72 /* 'r' */, 0x22, 0x02  /* (to 0x0243 state 270) */,\n                       0x3A /* ':' */, 0x56, 0x02  /* (to 0x027A state 299) */,\n                       0x65 /* 'e' */, 0xE8, 0x02  /* (to 0x030F state 409) */,\n                       0x66 /* 'f' */, 0x04, 0x03  /* (to 0x032E state 425) */,\n                       0x6C /* 'l' */, 0x26, 0x03  /* (to 0x0353 state 458) */,\n                       0x6D /* 'm' */, 0x49, 0x03  /* (to 0x0379 state 484) */,\n                       0x74 /* 't' */, 0xB8, 0x03  /* (to 0x03EB state 578) */,\n                       0x76 /* 'v' */, 0xD9, 0x03  /* (to 0x040F state 606) */,\n                       0x77 /* 'w' */, 0xE6, 0x03  /* (to 0x041F state 614) */,\n                       0x78 /* 'x' */, 0x0D, 0x04  /* (to 0x0449 state 650) */,\n                       0x08, /* fail */\n/* pos 0040:   1 */    0xE5 /* 'e' -> */,\n/* pos 0041:   2 */    0xF4 /* 't' -> */,\n/* pos 0042:   3 */    0xA0 /* ' ' -> */,\n/* pos 0043:   4 */    0x00, 0x00                  /* - terminal marker  0 - */,\n/* pos 0045:   5 */    0x6F /* 'o' */, 0x0D, 0x00  /* (to 0x0052 state   6) */,\n                       0x72 /* 'r' */, 0x95, 0x01  /* (to 0x01DD state 211) */,\n                       0x61 /* 'a' */, 0xE6, 0x03  /* (to 0x0431 state 631) */,\n                       0x75 /* 'u' */, 0xE8, 0x03  /* (to 0x0436 state 635) */,\n                       0x08, /* fail */\n/* pos 0052:   6 */    0xF3 /* 's' -> */,\n/* pos 0053:   7 */    0xF4 /* 't' -> */,\n/* pos 0054:   8 */    0xA0 /* ' ' -> */,\n/* pos 0055:   9 */    0x00, 0x01                  /* - terminal marker  1 - */,\n/* pos 0057:  10 */    0x70 /* 'p' */, 0x07, 0x00  /* (to 0x005E state  11) */,\n                       0x72 /* 'r' */, 0x51, 0x00  /* (to 0x00AB state  42) */,\n                       0x08, /* fail */\n/* pos 005e:  11 */    0xF4 /* 't' -> */,\n/* pos 005f:  12 */    0xE9 /* 'i' -> */,\n/* pos 0060:  13 */    0xEF /* 'o' -> */,\n/* pos 0061:  14 */    0xEE /* 'n' -> */,\n/* pos 0062:  15 */    0xF3 /* 's' -> */,\n/* pos 0063:  16 */    0xA0 /* ' ' -> */,\n/* pos 0064:  17 */    0x00, 0x02                  /* - terminal marker  2 - */,\n/* pos 0066:  18 */    0x6F /* 'o' */, 0x0A, 0x00  /* (to 0x0070 state  19) */,\n                       0x74 /* 't' */, 0xBF, 0x00  /* (to 0x0128 state 110) */,\n                       0x65 /* 'e' */, 0x04, 0x04  /* (to 0x0470 state 676) */,\n                       0x08, /* fail */\n/* pos 0070:  19 */    0xF3 /* 's' -> */,\n/* pos 0071:  20 */    0xF4 /* 't' -> */,\n/* pos 0072:  21 */    0xBA /* ':' -> */,\n/* pos 0073:  22 */    0x00, 0x03                  /* - terminal marker  3 - */,\n/* pos 0075:  23 */    0x6F /* 'o' */, 0x07, 0x00  /* (to 0x007C state  24) */,\n                       0x61 /* 'a' */, 0x72, 0x01  /* (to 0x01EA state 217) */,\n                       0x08, /* fail */\n/* pos 007c:  24 */    0x6E /* 'n' */, 0x07, 0x00  /* (to 0x0083 state  25) */,\n                       0x6F /* 'o' */, 0x87, 0x01  /* (to 0x0206 state 243) */,\n                       0x08, /* fail */\n/* pos 0083:  25 */    0x6E /* 'n' */, 0x07, 0x00  /* (to 0x008A state  26) */,\n                       0x74 /* 't' */, 0x86, 0x01  /* (to 0x020C state 248) */,\n                       0x08, /* fail */\n/* pos 008a:  26 */    0xE5 /* 'e' -> */,\n/* pos 008b:  27 */    0xE3 /* 'c' -> */,\n/* pos 008c:  28 */    0xF4 /* 't' -> */,\n/* pos 008d:  29 */    0x69 /* 'i' */, 0x07, 0x00  /* (to 0x0094 state  30) */,\n                       0x20 /* ' ' */, 0xDE, 0x03  /* (to 0x046E state 675) */,\n                       0x08, /* fail */\n/* pos 0094:  30 */    0xEF /* 'o' -> */,\n/* pos 0095:  31 */    0xEE /* 'n' -> */,\n/* pos 0096:  32 */    0xBA /* ':' -> */,\n/* pos 0097:  33 */    0x00, 0x04                  /* - terminal marker  4 - */,\n/* pos 0099:  34 */    0x70 /* 'p' */, 0x0A, 0x00  /* (to 0x00A3 state  35) */,\n                       0x73 /* 's' */, 0x68, 0x03  /* (to 0x0404 state 596) */,\n                       0x72 /* 'r' */, 0xA0, 0x03  /* (to 0x043F state 642) */,\n                       0x08, /* fail */\n/* pos 00a3:  35 */    0xE7 /* 'g' -> */,\n/* pos 00a4:  36 */    0xF2 /* 'r' -> */,\n/* pos 00a5:  37 */    0xE1 /* 'a' -> */,\n/* pos 00a6:  38 */    0xE4 /* 'd' -> */,\n/* pos 00a7:  39 */    0xE5 /* 'e' -> */,\n/* pos 00a8:  40 */    0xBA /* ':' -> */,\n/* pos 00a9:  41 */    0x00, 0x05                  /* - terminal marker  5 - */,\n/* pos 00ab:  42 */    0xE9 /* 'i' -> */,\n/* pos 00ac:  43 */    0xE7 /* 'g' -> */,\n/* pos 00ad:  44 */    0xE9 /* 'i' -> */,\n/* pos 00ae:  45 */    0xEE /* 'n' -> */,\n/* pos 00af:  46 */    0xBA /* ':' -> */,\n/* pos 00b0:  47 */    0x00, 0x06                  /* - terminal marker  6 - */,\n/* pos 00b2:  48 */    0x65 /* 'e' */, 0x07, 0x00  /* (to 0x00B9 state  49) */,\n                       0x74 /* 't' */, 0x1C, 0x03  /* (to 0x03D1 state 553) */,\n                       0x08, /* fail */\n/* pos 00b9:  49 */    0x63 /* 'c' */, 0x0A, 0x00  /* (to 0x00C3 state  50) */,\n                       0x72 /* 'r' */, 0x05, 0x03  /* (to 0x03C1 state 539) */,\n                       0x74 /* 't' */, 0x08, 0x03  /* (to 0x03C7 state 544) */,\n                       0x08, /* fail */\n/* pos 00c3:  50 */    0xAD /* '-' -> */,\n/* pos 00c4:  51 */    0xF7 /* 'w' -> */,\n/* pos 00c5:  52 */    0xE5 /* 'e' -> */,\n/* pos 00c6:  53 */    0xE2 /* 'b' -> */,\n/* pos 00c7:  54 */    0xF3 /* 's' -> */,\n/* pos 00c8:  55 */    0xEF /* 'o' -> */,\n/* pos 00c9:  56 */    0xE3 /* 'c' -> */,\n/* pos 00ca:  57 */    0xEB /* 'k' -> */,\n/* pos 00cb:  58 */    0xE5 /* 'e' -> */,\n/* pos 00cc:  59 */    0xF4 /* 't' -> */,\n/* pos 00cd:  60 */    0xAD /* '-' -> */,\n/* pos 00ce:  61 */    0x64 /* 'd' */, 0x19, 0x00  /* (to 0x00E7 state  62) */,\n                       0x65 /* 'e' */, 0x20, 0x00  /* (to 0x00F1 state  70) */,\n                       0x6B /* 'k' */, 0x29, 0x00  /* (to 0x00FD state  81) */,\n                       0x70 /* 'p' */, 0x38, 0x00  /* (to 0x010F state  88) */,\n                       0x61 /* 'a' */, 0x3F, 0x00  /* (to 0x0119 state  97) */,\n                       0x6E /* 'n' */, 0x44, 0x00  /* (to 0x0121 state 104) */,\n                       0x76 /* 'v' */, 0x89, 0x01  /* (to 0x0269 state 284) */,\n                       0x6F /* 'o' */, 0x8F, 0x01  /* (to 0x0272 state 292) */,\n                       0x08, /* fail */\n/* pos 00e7:  62 */    0xF2 /* 'r' -> */,\n/* pos 00e8:  63 */    0xE1 /* 'a' -> */,\n/* pos 00e9:  64 */    0xE6 /* 'f' -> */,\n/* pos 00ea:  65 */    0xF4 /* 't' -> */,\n/* pos 00eb:  66 */    0xBA /* ':' -> */,\n/* pos 00ec:  67 */    0x00, 0x07                  /* - terminal marker  7 - */,\n/* pos 00ee:  68 */    0x8A /* '.' -> */,\n/* pos 00ef:  69 */    0x00, 0x08                  /* - terminal marker  8 - */,\n/* pos 00f1:  70 */    0xF8 /* 'x' -> */,\n/* pos 00f2:  71 */    0xF4 /* 't' -> */,\n/* pos 00f3:  72 */    0xE5 /* 'e' -> */,\n/* pos 00f4:  73 */    0xEE /* 'n' -> */,\n/* pos 00f5:  74 */    0xF3 /* 's' -> */,\n/* pos 00f6:  75 */    0xE9 /* 'i' -> */,\n/* pos 00f7:  76 */    0xEF /* 'o' -> */,\n/* pos 00f8:  77 */    0xEE /* 'n' -> */,\n/* pos 00f9:  78 */    0xF3 /* 's' -> */,\n/* pos 00fa:  79 */    0xBA /* ':' -> */,\n/* pos 00fb:  80 */    0x00, 0x09                  /* - terminal marker  9 - */,\n/* pos 00fd:  81 */    0xE5 /* 'e' -> */,\n/* pos 00fe:  82 */    0xF9 /* 'y' -> */,\n/* pos 00ff:  83 */    0x31 /* '1' */, 0x0A, 0x00  /* (to 0x0109 state  84) */,\n                       0x32 /* '2' */, 0x0A, 0x00  /* (to 0x010C state  86) */,\n                       0x3A /* ':' */, 0x62, 0x01  /* (to 0x0267 state 283) */,\n                       0x08, /* fail */\n/* pos 0109:  84 */    0xBA /* ':' -> */,\n/* pos 010a:  85 */    0x00, 0x0A                  /* - terminal marker 10 - */,\n/* pos 010c:  86 */    0xBA /* ':' -> */,\n/* pos 010d:  87 */    0x00, 0x0B                  /* - terminal marker 11 - */,\n/* pos 010f:  88 */    0xF2 /* 'r' -> */,\n/* pos 0110:  89 */    0xEF /* 'o' -> */,\n/* pos 0111:  90 */    0xF4 /* 't' -> */,\n/* pos 0112:  91 */    0xEF /* 'o' -> */,\n/* pos 0113:  92 */    0xE3 /* 'c' -> */,\n/* pos 0114:  93 */    0xEF /* 'o' -> */,\n/* pos 0115:  94 */    0xEC /* 'l' -> */,\n/* pos 0116:  95 */    0xBA /* ':' -> */,\n/* pos 0117:  96 */    0x00, 0x0C                  /* - terminal marker 12 - */,\n/* pos 0119:  97 */    0xE3 /* 'c' -> */,\n/* pos 011a:  98 */    0xE3 /* 'c' -> */,\n/* pos 011b:  99 */    0xE5 /* 'e' -> */,\n/* pos 011c: 100 */    0xF0 /* 'p' -> */,\n/* pos 011d: 101 */    0xF4 /* 't' -> */,\n/* pos 011e: 102 */    0xBA /* ':' -> */,\n/* pos 011f: 103 */    0x00, 0x0D                  /* - terminal marker 13 - */,\n/* pos 0121: 104 */    0xEF /* 'o' -> */,\n/* pos 0122: 105 */    0xEE /* 'n' -> */,\n/* pos 0123: 106 */    0xE3 /* 'c' -> */,\n/* pos 0124: 107 */    0xE5 /* 'e' -> */,\n/* pos 0125: 108 */    0xBA /* ':' -> */,\n/* pos 0126: 109 */    0x00, 0x0E                  /* - terminal marker 14 - */,\n/* pos 0128: 110 */    0xF4 /* 't' -> */,\n/* pos 0129: 111 */    0xF0 /* 'p' -> */,\n/* pos 012a: 112 */    0x2F /* '/' */, 0x07, 0x00  /* (to 0x0131 state 113) */,\n                       0x32 /* '2' */, 0x10, 0x00  /* (to 0x013D state 118) */,\n                       0x08, /* fail */\n/* pos 0131: 113 */    0xB1 /* '1' -> */,\n/* pos 0132: 114 */    0xAE /* '.' -> */,\n/* pos 0133: 115 */    0x31 /* '1' */, 0x07, 0x00  /* (to 0x013A state 116) */,\n                       0x30 /* '0' */, 0x27, 0x03  /* (to 0x045D state 660) */,\n                       0x08, /* fail */\n/* pos 013a: 116 */    0xA0 /* ' ' -> */,\n/* pos 013b: 117 */    0x00, 0x0F                  /* - terminal marker 15 - */,\n/* pos 013d: 118 */    0xAD /* '-' -> */,\n/* pos 013e: 119 */    0xF3 /* 's' -> */,\n/* pos 013f: 120 */    0xE5 /* 'e' -> */,\n/* pos 0140: 121 */    0xF4 /* 't' -> */,\n/* pos 0141: 122 */    0xF4 /* 't' -> */,\n/* pos 0142: 123 */    0xE9 /* 'i' -> */,\n/* pos 0143: 124 */    0xEE /* 'n' -> */,\n/* pos 0144: 125 */    0xE7 /* 'g' -> */,\n/* pos 0145: 126 */    0xF3 /* 's' -> */,\n/* pos 0146: 127 */    0xBA /* ':' -> */,\n/* pos 0147: 128 */    0x00, 0x10                  /* - terminal marker 16 - */,\n/* pos 0149: 129 */    0x63 /* 'c' */, 0x0D, 0x00  /* (to 0x0156 state 130) */,\n                       0x75 /* 'u' */, 0xAC, 0x00  /* (to 0x01F8 state 230) */,\n                       0x67 /* 'g' */, 0x86, 0x01  /* (to 0x02D5 state 358) */,\n                       0x6C /* 'l' */, 0x87, 0x01  /* (to 0x02D9 state 361) */,\n                       0x08, /* fail */\n/* pos 0156: 130 */    0xE3 /* 'c' -> */,\n/* pos 0157: 131 */    0xE5 /* 'e' -> */,\n/* pos 0158: 132 */    0x70 /* 'p' */, 0x07, 0x00  /* (to 0x015F state 133) */,\n                       0x73 /* 's' */, 0x0E, 0x00  /* (to 0x0169 state 136) */,\n                       0x08, /* fail */\n/* pos 015f: 133 */    0xF4 /* 't' -> */,\n/* pos 0160: 134 */    0x3A /* ':' */, 0x07, 0x00  /* (to 0x0167 state 135) */,\n                       0x2D /* '-' */, 0x59, 0x00  /* (to 0x01BC state 192) */,\n                       0x08, /* fail */\n/* pos 0167: 135 */    0x00, 0x11                  /* - terminal marker 17 - */,\n/* pos 0169: 136 */    0xF3 /* 's' -> */,\n/* pos 016a: 137 */    0xAD /* '-' -> */,\n/* pos 016b: 138 */    0xE3 /* 'c' -> */,\n/* pos 016c: 139 */    0xEF /* 'o' -> */,\n/* pos 016d: 140 */    0xEE /* 'n' -> */,\n/* pos 016e: 141 */    0xF4 /* 't' -> */,\n/* pos 016f: 142 */    0xF2 /* 'r' -> */,\n/* pos 0170: 143 */    0xEF /* 'o' -> */,\n/* pos 0171: 144 */    0xEC /* 'l' -> */,\n/* pos 0172: 145 */    0xAD /* '-' -> */,\n/* pos 0173: 146 */    0x72 /* 'r' */, 0x07, 0x00  /* (to 0x017A state 147) */,\n                       0x61 /* 'a' */, 0x51, 0x01  /* (to 0x02C7 state 345) */,\n                       0x08, /* fail */\n/* pos 017a: 147 */    0xE5 /* 'e' -> */,\n/* pos 017b: 148 */    0xF1 /* 'q' -> */,\n/* pos 017c: 149 */    0xF5 /* 'u' -> */,\n/* pos 017d: 150 */    0xE5 /* 'e' -> */,\n/* pos 017e: 151 */    0xF3 /* 's' -> */,\n/* pos 017f: 152 */    0xF4 /* 't' -> */,\n/* pos 0180: 153 */    0xAD /* '-' -> */,\n/* pos 0181: 154 */    0xE8 /* 'h' -> */,\n/* pos 0182: 155 */    0xE5 /* 'e' -> */,\n/* pos 0183: 156 */    0xE1 /* 'a' -> */,\n/* pos 0184: 157 */    0xE4 /* 'd' -> */,\n/* pos 0185: 158 */    0xE5 /* 'e' -> */,\n/* pos 0186: 159 */    0xF2 /* 'r' -> */,\n/* pos 0187: 160 */    0xF3 /* 's' -> */,\n/* pos 0188: 161 */    0xBA /* ':' -> */,\n/* pos 0189: 162 */    0x00, 0x12                  /* - terminal marker 18 - */,\n/* pos 018b: 163 */    0xE6 /* 'f' -> */,\n/* pos 018c: 164 */    0xAD /* '-' -> */,\n/* pos 018d: 165 */    0x6D /* 'm' */, 0x0D, 0x00  /* (to 0x019A state 166) */,\n                       0x6E /* 'n' */, 0x20, 0x00  /* (to 0x01B0 state 181) */,\n                       0x72 /* 'r' */, 0xA7, 0x01  /* (to 0x033A state 435) */,\n                       0x75 /* 'u' */, 0xAB, 0x01  /* (to 0x0341 state 441) */,\n                       0x08, /* fail */\n/* pos 019a: 166 */    0x6F /* 'o' */, 0x07, 0x00  /* (to 0x01A1 state 167) */,\n                       0x61 /* 'a' */, 0x97, 0x01  /* (to 0x0334 state 430) */,\n                       0x08, /* fail */\n/* pos 01a1: 167 */    0xE4 /* 'd' -> */,\n/* pos 01a2: 168 */    0xE9 /* 'i' -> */,\n/* pos 01a3: 169 */    0xE6 /* 'f' -> */,\n/* pos 01a4: 170 */    0xE9 /* 'i' -> */,\n/* pos 01a5: 171 */    0xE5 /* 'e' -> */,\n/* pos 01a6: 172 */    0xE4 /* 'd' -> */,\n/* pos 01a7: 173 */    0xAD /* '-' -> */,\n/* pos 01a8: 174 */    0xF3 /* 's' -> */,\n/* pos 01a9: 175 */    0xE9 /* 'i' -> */,\n/* pos 01aa: 176 */    0xEE /* 'n' -> */,\n/* pos 01ab: 177 */    0xE3 /* 'c' -> */,\n/* pos 01ac: 178 */    0xE5 /* 'e' -> */,\n/* pos 01ad: 179 */    0xBA /* ':' -> */,\n/* pos 01ae: 180 */    0x00, 0x13                  /* - terminal marker 19 - */,\n/* pos 01b0: 181 */    0xEF /* 'o' -> */,\n/* pos 01b1: 182 */    0xEE /* 'n' -> */,\n/* pos 01b2: 183 */    0xE5 /* 'e' -> */,\n/* pos 01b3: 184 */    0xAD /* '-' -> */,\n/* pos 01b4: 185 */    0xED /* 'm' -> */,\n/* pos 01b5: 186 */    0xE1 /* 'a' -> */,\n/* pos 01b6: 187 */    0xF4 /* 't' -> */,\n/* pos 01b7: 188 */    0xE3 /* 'c' -> */,\n/* pos 01b8: 189 */    0xE8 /* 'h' -> */,\n/* pos 01b9: 190 */    0xBA /* ':' -> */,\n/* pos 01ba: 191 */    0x00, 0x14                  /* - terminal marker 20 - */,\n/* pos 01bc: 192 */    0x65 /* 'e' */, 0x0D, 0x00  /* (to 0x01C9 state 193) */,\n                       0x6C /* 'l' */, 0x14, 0x00  /* (to 0x01D3 state 202) */,\n                       0x63 /* 'c' */, 0xF4, 0x00  /* (to 0x02B6 state 330) */,\n                       0x72 /* 'r' */, 0xFA, 0x00  /* (to 0x02BF state 338) */,\n                       0x08, /* fail */\n/* pos 01c9: 193 */    0xEE /* 'n' -> */,\n/* pos 01ca: 194 */    0xE3 /* 'c' -> */,\n/* pos 01cb: 195 */    0xEF /* 'o' -> */,\n/* pos 01cc: 196 */    0xE4 /* 'd' -> */,\n/* pos 01cd: 197 */    0xE9 /* 'i' -> */,\n/* pos 01ce: 198 */    0xEE /* 'n' -> */,\n/* pos 01cf: 199 */    0xE7 /* 'g' -> */,\n/* pos 01d0: 200 */    0xBA /* ':' -> */,\n/* pos 01d1: 201 */    0x00, 0x15                  /* - terminal marker 21 - */,\n/* pos 01d3: 202 */    0xE1 /* 'a' -> */,\n/* pos 01d4: 203 */    0xEE /* 'n' -> */,\n/* pos 01d5: 204 */    0xE7 /* 'g' -> */,\n/* pos 01d6: 205 */    0xF5 /* 'u' -> */,\n/* pos 01d7: 206 */    0xE1 /* 'a' -> */,\n/* pos 01d8: 207 */    0xE7 /* 'g' -> */,\n/* pos 01d9: 208 */    0xE5 /* 'e' -> */,\n/* pos 01da: 209 */    0xBA /* ':' -> */,\n/* pos 01db: 210 */    0x00, 0x16                  /* - terminal marker 22 - */,\n/* pos 01dd: 211 */    0x61 /* 'a' */, 0x07, 0x00  /* (to 0x01E4 state 212) */,\n                       0x6F /* 'o' */, 0xA7, 0x01  /* (to 0x0387 state 497) */,\n                       0x08, /* fail */\n/* pos 01e4: 212 */    0xE7 /* 'g' -> */,\n/* pos 01e5: 213 */    0xED /* 'm' -> */,\n/* pos 01e6: 214 */    0xE1 /* 'a' -> */,\n/* pos 01e7: 215 */    0xBA /* ':' -> */,\n/* pos 01e8: 216 */    0x00, 0x17                  /* - terminal marker 23 - */,\n/* pos 01ea: 217 */    0xE3 /* 'c' -> */,\n/* pos 01eb: 218 */    0xE8 /* 'h' -> */,\n/* pos 01ec: 219 */    0xE5 /* 'e' -> */,\n/* pos 01ed: 220 */    0xAD /* '-' -> */,\n/* pos 01ee: 221 */    0xE3 /* 'c' -> */,\n/* pos 01ef: 222 */    0xEF /* 'o' -> */,\n/* pos 01f0: 223 */    0xEE /* 'n' -> */,\n/* pos 01f1: 224 */    0xF4 /* 't' -> */,\n/* pos 01f2: 225 */    0xF2 /* 'r' -> */,\n/* pos 01f3: 226 */    0xEF /* 'o' -> */,\n/* pos 01f4: 227 */    0xEC /* 'l' -> */,\n/* pos 01f5: 228 */    0xBA /* ':' -> */,\n/* pos 01f6: 229 */    0x00, 0x18                  /* - terminal marker 24 - */,\n/* pos 01f8: 230 */    0xF4 /* 't' -> */,\n/* pos 01f9: 231 */    0xE8 /* 'h' -> */,\n/* pos 01fa: 232 */    0xEF /* 'o' -> */,\n/* pos 01fb: 233 */    0xF2 /* 'r' -> */,\n/* pos 01fc: 234 */    0xE9 /* 'i' -> */,\n/* pos 01fd: 235 */    0xFA /* 'z' -> */,\n/* pos 01fe: 236 */    0xE1 /* 'a' -> */,\n/* pos 01ff: 237 */    0xF4 /* 't' -> */,\n/* pos 0200: 238 */    0xE9 /* 'i' -> */,\n/* pos 0201: 239 */    0xEF /* 'o' -> */,\n/* pos 0202: 240 */    0xEE /* 'n' -> */,\n/* pos 0203: 241 */    0xBA /* ':' -> */,\n/* pos 0204: 242 */    0x00, 0x19                  /* - terminal marker 25 - */,\n/* pos 0206: 243 */    0xEB /* 'k' -> */,\n/* pos 0207: 244 */    0xE9 /* 'i' -> */,\n/* pos 0208: 245 */    0xE5 /* 'e' -> */,\n/* pos 0209: 246 */    0xBA /* ':' -> */,\n/* pos 020a: 247 */    0x00, 0x1A                  /* - terminal marker 26 - */,\n/* pos 020c: 248 */    0xE5 /* 'e' -> */,\n/* pos 020d: 249 */    0xEE /* 'n' -> */,\n/* pos 020e: 250 */    0xF4 /* 't' -> */,\n/* pos 020f: 251 */    0xAD /* '-' -> */,\n/* pos 0210: 252 */    0x6C /* 'l' */, 0x10, 0x00  /* (to 0x0220 state 253) */,\n                       0x74 /* 't' */, 0x1E, 0x00  /* (to 0x0231 state 260) */,\n                       0x64 /* 'd' */, 0xC9, 0x00  /* (to 0x02DF state 366) */,\n                       0x65 /* 'e' */, 0xD3, 0x00  /* (to 0x02EC state 378) */,\n                       0x72 /* 'r' */, 0xEC, 0x00  /* (to 0x0308 state 403) */,\n                       0x08, /* fail */\n/* pos 0220: 253 */    0x65 /* 'e' */, 0x0A, 0x00  /* (to 0x022A state 254) */,\n                       0x61 /* 'a' */, 0xD3, 0x00  /* (to 0x02F6 state 387) */,\n                       0x6F /* 'o' */, 0xD9, 0x00  /* (to 0x02FF state 395) */,\n                       0x08, /* fail */\n/* pos 022a: 254 */    0xEE /* 'n' -> */,\n/* pos 022b: 255 */    0xE7 /* 'g' -> */,\n/* pos 022c: 256 */    0xF4 /* 't' -> */,\n/* pos 022d: 257 */    0xE8 /* 'h' -> */,\n/* pos 022e: 258 */    0xBA /* ':' -> */,\n/* pos 022f: 259 */    0x00, 0x1B                  /* - terminal marker 27 - */,\n/* pos 0231: 260 */    0xF9 /* 'y' -> */,\n/* pos 0232: 261 */    0xF0 /* 'p' -> */,\n/* pos 0233: 262 */    0xE5 /* 'e' -> */,\n/* pos 0234: 263 */    0xBA /* ':' -> */,\n/* pos 0235: 264 */    0x00, 0x1C                  /* - terminal marker 28 - */,\n/* pos 0237: 265 */    0x61 /* 'a' */, 0x07, 0x00  /* (to 0x023E state 266) */,\n                       0x65 /* 'e' */, 0xFF, 0x01  /* (to 0x0439 state 637) */,\n                       0x08, /* fail */\n/* pos 023e: 266 */    0xF4 /* 't' -> */,\n/* pos 023f: 267 */    0xE5 /* 'e' -> */,\n/* pos 0240: 268 */    0xBA /* ':' -> */,\n/* pos 0241: 269 */    0x00, 0x1D                  /* - terminal marker 29 - */,\n/* pos 0243: 270 */    0x61 /* 'a' */, 0x07, 0x00  /* (to 0x024A state 271) */,\n                       0x65 /* 'e' */, 0x0A, 0x00  /* (to 0x0250 state 276) */,\n                       0x08, /* fail */\n/* pos 024a: 271 */    0xEE /* 'n' -> */,\n/* pos 024b: 272 */    0xE7 /* 'g' -> */,\n/* pos 024c: 273 */    0xE5 /* 'e' -> */,\n/* pos 024d: 274 */    0xBA /* ':' -> */,\n/* pos 024e: 275 */    0x00, 0x1E                  /* - terminal marker 30 - */,\n/* pos 0250: 276 */    0x66 /* 'f' */, 0x0A, 0x00  /* (to 0x025A state 277) */,\n                       0x74 /* 't' */, 0x63, 0x01  /* (to 0x03B6 state 529) */,\n                       0x70 /* 'p' */, 0x22, 0x02  /* (to 0x0478 state 682) */,\n                       0x08, /* fail */\n/* pos 025a: 277 */    0x65 /* 'e' */, 0x07, 0x00  /* (to 0x0261 state 278) */,\n                       0x72 /* 'r' */, 0x53, 0x01  /* (to 0x03B0 state 524) */,\n                       0x08, /* fail */\n/* pos 0261: 278 */    0xF2 /* 'r' -> */,\n/* pos 0262: 279 */    0xE5 /* 'e' -> */,\n/* pos 0263: 280 */    0xF2 /* 'r' -> */,\n/* pos 0264: 281 */    0xBA /* ':' -> */,\n/* pos 0265: 282 */    0x00, 0x1F                  /* - terminal marker 31 - */,\n/* pos 0267: 283 */    0x00, 0x20                  /* - terminal marker 32 - */,\n/* pos 0269: 284 */    0xE5 /* 'e' -> */,\n/* pos 026a: 285 */    0xF2 /* 'r' -> */,\n/* pos 026b: 286 */    0xF3 /* 's' -> */,\n/* pos 026c: 287 */    0xE9 /* 'i' -> */,\n/* pos 026d: 288 */    0xEF /* 'o' -> */,\n/* pos 026e: 289 */    0xEE /* 'n' -> */,\n/* pos 026f: 290 */    0xBA /* ':' -> */,\n/* pos 0270: 291 */    0x00, 0x21                  /* - terminal marker 33 - */,\n/* pos 0272: 292 */    0xF2 /* 'r' -> */,\n/* pos 0273: 293 */    0xE9 /* 'i' -> */,\n/* pos 0274: 294 */    0xE7 /* 'g' -> */,\n/* pos 0275: 295 */    0xE9 /* 'i' -> */,\n/* pos 0276: 296 */    0xEE /* 'n' -> */,\n/* pos 0277: 297 */    0xBA /* ':' -> */,\n/* pos 0278: 298 */    0x00, 0x22                  /* - terminal marker 34 - */,\n/* pos 027a: 299 */    0x61 /* 'a' */, 0x0D, 0x00  /* (to 0x0287 state 300) */,\n                       0x6D /* 'm' */, 0x14, 0x00  /* (to 0x0291 state 309) */,\n                       0x70 /* 'p' */, 0x18, 0x00  /* (to 0x0298 state 315) */,\n                       0x73 /* 's' */, 0x20, 0x00  /* (to 0x02A3 state 319) */,\n                       0x08, /* fail */\n/* pos 0287: 300 */    0xF5 /* 'u' -> */,\n/* pos 0288: 301 */    0xF4 /* 't' -> */,\n/* pos 0289: 302 */    0xE8 /* 'h' -> */,\n/* pos 028a: 303 */    0xEF /* 'o' -> */,\n/* pos 028b: 304 */    0xF2 /* 'r' -> */,\n/* pos 028c: 305 */    0xE9 /* 'i' -> */,\n/* pos 028d: 306 */    0xF4 /* 't' -> */,\n/* pos 028e: 307 */    0xF9 /* 'y' -> */,\n/* pos 028f: 308 */    0x00, 0x23                  /* - terminal marker 35 - */,\n/* pos 0291: 309 */    0xE5 /* 'e' -> */,\n/* pos 0292: 310 */    0xF4 /* 't' -> */,\n/* pos 0293: 311 */    0xE8 /* 'h' -> */,\n/* pos 0294: 312 */    0xEF /* 'o' -> */,\n/* pos 0295: 313 */    0xE4 /* 'd' -> */,\n/* pos 0296: 314 */    0x00, 0x24                  /* - terminal marker 36 - */,\n/* pos 0298: 315 */    0x61 /* 'a' */, 0x07, 0x00  /* (to 0x029F state 316) */,\n                       0x72 /* 'r' */, 0xE9, 0x01  /* (to 0x0484 state 693) */,\n                       0x08, /* fail */\n/* pos 029f: 316 */    0xF4 /* 't' -> */,\n/* pos 02a0: 317 */    0xE8 /* 'h' -> */,\n/* pos 02a1: 318 */    0x00, 0x25                  /* - terminal marker 37 - */,\n/* pos 02a3: 319 */    0x63 /* 'c' */, 0x07, 0x00  /* (to 0x02AA state 320) */,\n                       0x74 /* 't' */, 0x0A, 0x00  /* (to 0x02B0 state 325) */,\n                       0x08, /* fail */\n/* pos 02aa: 320 */    0xE8 /* 'h' -> */,\n/* pos 02ab: 321 */    0xE5 /* 'e' -> */,\n/* pos 02ac: 322 */    0xED /* 'm' -> */,\n/* pos 02ad: 323 */    0xE5 /* 'e' -> */,\n/* pos 02ae: 324 */    0x00, 0x26                  /* - terminal marker 38 - */,\n/* pos 02b0: 325 */    0xE1 /* 'a' -> */,\n/* pos 02b1: 326 */    0xF4 /* 't' -> */,\n/* pos 02b2: 327 */    0xF5 /* 'u' -> */,\n/* pos 02b3: 328 */    0xF3 /* 's' -> */,\n/* pos 02b4: 329 */    0x00, 0x27                  /* - terminal marker 39 - */,\n/* pos 02b6: 330 */    0xE8 /* 'h' -> */,\n/* pos 02b7: 331 */    0xE1 /* 'a' -> */,\n/* pos 02b8: 332 */    0xF2 /* 'r' -> */,\n/* pos 02b9: 333 */    0xF3 /* 's' -> */,\n/* pos 02ba: 334 */    0xE5 /* 'e' -> */,\n/* pos 02bb: 335 */    0xF4 /* 't' -> */,\n/* pos 02bc: 336 */    0xBA /* ':' -> */,\n/* pos 02bd: 337 */    0x00, 0x28                  /* - terminal marker 40 - */,\n/* pos 02bf: 338 */    0xE1 /* 'a' -> */,\n/* pos 02c0: 339 */    0xEE /* 'n' -> */,\n/* pos 02c1: 340 */    0xE7 /* 'g' -> */,\n/* pos 02c2: 341 */    0xE5 /* 'e' -> */,\n/* pos 02c3: 342 */    0xF3 /* 's' -> */,\n/* pos 02c4: 343 */    0xBA /* ':' -> */,\n/* pos 02c5: 344 */    0x00, 0x29                  /* - terminal marker 41 - */,\n/* pos 02c7: 345 */    0xEC /* 'l' -> */,\n/* pos 02c8: 346 */    0xEC /* 'l' -> */,\n/* pos 02c9: 347 */    0xEF /* 'o' -> */,\n/* pos 02ca: 348 */    0xF7 /* 'w' -> */,\n/* pos 02cb: 349 */    0xAD /* '-' -> */,\n/* pos 02cc: 350 */    0xEF /* 'o' -> */,\n/* pos 02cd: 351 */    0xF2 /* 'r' -> */,\n/* pos 02ce: 352 */    0xE9 /* 'i' -> */,\n/* pos 02cf: 353 */    0xE7 /* 'g' -> */,\n/* pos 02d0: 354 */    0xE9 /* 'i' -> */,\n/* pos 02d1: 355 */    0xEE /* 'n' -> */,\n/* pos 02d2: 356 */    0xBA /* ':' -> */,\n/* pos 02d3: 357 */    0x00, 0x2A                  /* - terminal marker 42 - */,\n/* pos 02d5: 358 */    0xE5 /* 'e' -> */,\n/* pos 02d6: 359 */    0xBA /* ':' -> */,\n/* pos 02d7: 360 */    0x00, 0x2B                  /* - terminal marker 43 - */,\n/* pos 02d9: 361 */    0xEC /* 'l' -> */,\n/* pos 02da: 362 */    0xEF /* 'o' -> */,\n/* pos 02db: 363 */    0xF7 /* 'w' -> */,\n/* pos 02dc: 364 */    0xBA /* ':' -> */,\n/* pos 02dd: 365 */    0x00, 0x2C                  /* - terminal marker 44 - */,\n/* pos 02df: 366 */    0xE9 /* 'i' -> */,\n/* pos 02e0: 367 */    0xF3 /* 's' -> */,\n/* pos 02e1: 368 */    0xF0 /* 'p' -> */,\n/* pos 02e2: 369 */    0xEF /* 'o' -> */,\n/* pos 02e3: 370 */    0xF3 /* 's' -> */,\n/* pos 02e4: 371 */    0xE9 /* 'i' -> */,\n/* pos 02e5: 372 */    0xF4 /* 't' -> */,\n/* pos 02e6: 373 */    0xE9 /* 'i' -> */,\n/* pos 02e7: 374 */    0xEF /* 'o' -> */,\n/* pos 02e8: 375 */    0xEE /* 'n' -> */,\n/* pos 02e9: 376 */    0xBA /* ':' -> */,\n/* pos 02ea: 377 */    0x00, 0x2D                  /* - terminal marker 45 - */,\n/* pos 02ec: 378 */    0xEE /* 'n' -> */,\n/* pos 02ed: 379 */    0xE3 /* 'c' -> */,\n/* pos 02ee: 380 */    0xEF /* 'o' -> */,\n/* pos 02ef: 381 */    0xE4 /* 'd' -> */,\n/* pos 02f0: 382 */    0xE9 /* 'i' -> */,\n/* pos 02f1: 383 */    0xEE /* 'n' -> */,\n/* pos 02f2: 384 */    0xE7 /* 'g' -> */,\n/* pos 02f3: 385 */    0xBA /* ':' -> */,\n/* pos 02f4: 386 */    0x00, 0x2E                  /* - terminal marker 46 - */,\n/* pos 02f6: 387 */    0xEE /* 'n' -> */,\n/* pos 02f7: 388 */    0xE7 /* 'g' -> */,\n/* pos 02f8: 389 */    0xF5 /* 'u' -> */,\n/* pos 02f9: 390 */    0xE1 /* 'a' -> */,\n/* pos 02fa: 391 */    0xE7 /* 'g' -> */,\n/* pos 02fb: 392 */    0xE5 /* 'e' -> */,\n/* pos 02fc: 393 */    0xBA /* ':' -> */,\n/* pos 02fd: 394 */    0x00, 0x2F                  /* - terminal marker 47 - */,\n/* pos 02ff: 395 */    0xE3 /* 'c' -> */,\n/* pos 0300: 396 */    0xE1 /* 'a' -> */,\n/* pos 0301: 397 */    0xF4 /* 't' -> */,\n/* pos 0302: 398 */    0xE9 /* 'i' -> */,\n/* pos 0303: 399 */    0xEF /* 'o' -> */,\n/* pos 0304: 400 */    0xEE /* 'n' -> */,\n/* pos 0305: 401 */    0xBA /* ':' -> */,\n/* pos 0306: 402 */    0x00, 0x30                  /* - terminal marker 48 - */,\n/* pos 0308: 403 */    0xE1 /* 'a' -> */,\n/* pos 0309: 404 */    0xEE /* 'n' -> */,\n/* pos 030a: 405 */    0xE7 /* 'g' -> */,\n/* pos 030b: 406 */    0xE5 /* 'e' -> */,\n/* pos 030c: 407 */    0xBA /* ':' -> */,\n/* pos 030d: 408 */    0x00, 0x31                  /* - terminal marker 49 - */,\n/* pos 030f: 409 */    0x74 /* 't' */, 0x07, 0x00  /* (to 0x0316 state 410) */,\n                       0x78 /* 'x' */, 0x09, 0x00  /* (to 0x031B state 414) */,\n                       0x08, /* fail */\n/* pos 0316: 410 */    0xE1 /* 'a' -> */,\n/* pos 0317: 411 */    0xE7 /* 'g' -> */,\n/* pos 0318: 412 */    0xBA /* ':' -> */,\n/* pos 0319: 413 */    0x00, 0x32                  /* - terminal marker 50 - */,\n/* pos 031b: 414 */    0xF0 /* 'p' -> */,\n/* pos 031c: 415 */    0x65 /* 'e' */, 0x07, 0x00  /* (to 0x0323 state 416) */,\n                       0x69 /* 'i' */, 0x09, 0x00  /* (to 0x0328 state 420) */,\n                       0x08, /* fail */\n/* pos 0323: 416 */    0xE3 /* 'c' -> */,\n/* pos 0324: 417 */    0xF4 /* 't' -> */,\n/* pos 0325: 418 */    0xBA /* ':' -> */,\n/* pos 0326: 419 */    0x00, 0x33                  /* - terminal marker 51 - */,\n/* pos 0328: 420 */    0xF2 /* 'r' -> */,\n/* pos 0329: 421 */    0xE5 /* 'e' -> */,\n/* pos 032a: 422 */    0xF3 /* 's' -> */,\n/* pos 032b: 423 */    0xBA /* ':' -> */,\n/* pos 032c: 424 */    0x00, 0x34                  /* - terminal marker 52 - */,\n/* pos 032e: 425 */    0xF2 /* 'r' -> */,\n/* pos 032f: 426 */    0xEF /* 'o' -> */,\n/* pos 0330: 427 */    0xED /* 'm' -> */,\n/* pos 0331: 428 */    0xBA /* ':' -> */,\n/* pos 0332: 429 */    0x00, 0x35                  /* - terminal marker 53 - */,\n/* pos 0334: 430 */    0xF4 /* 't' -> */,\n/* pos 0335: 431 */    0xE3 /* 'c' -> */,\n/* pos 0336: 432 */    0xE8 /* 'h' -> */,\n/* pos 0337: 433 */    0xBA /* ':' -> */,\n/* pos 0338: 434 */    0x00, 0x36                  /* - terminal marker 54 - */,\n/* pos 033a: 435 */    0xE1 /* 'a' -> */,\n/* pos 033b: 436 */    0xEE /* 'n' -> */,\n/* pos 033c: 437 */    0xE7 /* 'g' -> */,\n/* pos 033d: 438 */    0xE5 /* 'e' -> */,\n/* pos 033e: 439 */    0xBA /* ':' -> */,\n/* pos 033f: 440 */    0x00, 0x37                  /* - terminal marker 55 - */,\n/* pos 0341: 441 */    0xEE /* 'n' -> */,\n/* pos 0342: 442 */    0xED /* 'm' -> */,\n/* pos 0343: 443 */    0xEF /* 'o' -> */,\n/* pos 0344: 444 */    0xE4 /* 'd' -> */,\n/* pos 0345: 445 */    0xE9 /* 'i' -> */,\n/* pos 0346: 446 */    0xE6 /* 'f' -> */,\n/* pos 0347: 447 */    0xE9 /* 'i' -> */,\n/* pos 0348: 448 */    0xE5 /* 'e' -> */,\n/* pos 0349: 449 */    0xE4 /* 'd' -> */,\n/* pos 034a: 450 */    0xAD /* '-' -> */,\n/* pos 034b: 451 */    0xF3 /* 's' -> */,\n/* pos 034c: 452 */    0xE9 /* 'i' -> */,\n/* pos 034d: 453 */    0xEE /* 'n' -> */,\n/* pos 034e: 454 */    0xE3 /* 'c' -> */,\n/* pos 034f: 455 */    0xE5 /* 'e' -> */,\n/* pos 0350: 456 */    0xBA /* ':' -> */,\n/* pos 0351: 457 */    0x00, 0x38                  /* - terminal marker 56 - */,\n/* pos 0353: 458 */    0x61 /* 'a' */, 0x0A, 0x00  /* (to 0x035D state 459) */,\n                       0x69 /* 'i' */, 0x15, 0x00  /* (to 0x036B state 472) */,\n                       0x6F /* 'o' */, 0x17, 0x00  /* (to 0x0370 state 476) */,\n                       0x08, /* fail */\n/* pos 035d: 459 */    0xF3 /* 's' -> */,\n/* pos 035e: 460 */    0xF4 /* 't' -> */,\n/* pos 035f: 461 */    0xAD /* '-' -> */,\n/* pos 0360: 462 */    0xED /* 'm' -> */,\n/* pos 0361: 463 */    0xEF /* 'o' -> */,\n/* pos 0362: 464 */    0xE4 /* 'd' -> */,\n/* pos 0363: 465 */    0xE9 /* 'i' -> */,\n/* pos 0364: 466 */    0xE6 /* 'f' -> */,\n/* pos 0365: 467 */    0xE9 /* 'i' -> */,\n/* pos 0366: 468 */    0xE5 /* 'e' -> */,\n/* pos 0367: 469 */    0xE4 /* 'd' -> */,\n/* pos 0368: 470 */    0xBA /* ':' -> */,\n/* pos 0369: 471 */    0x00, 0x39                  /* - terminal marker 57 - */,\n/* pos 036b: 472 */    0xEE /* 'n' -> */,\n/* pos 036c: 473 */    0xEB /* 'k' -> */,\n/* pos 036d: 474 */    0xBA /* ':' -> */,\n/* pos 036e: 475 */    0x00, 0x3A                  /* - terminal marker 58 - */,\n/* pos 0370: 476 */    0xE3 /* 'c' -> */,\n/* pos 0371: 477 */    0xE1 /* 'a' -> */,\n/* pos 0372: 478 */    0xF4 /* 't' -> */,\n/* pos 0373: 479 */    0xE9 /* 'i' -> */,\n/* pos 0374: 480 */    0xEF /* 'o' -> */,\n/* pos 0375: 481 */    0xEE /* 'n' -> */,\n/* pos 0376: 482 */    0xBA /* ':' -> */,\n/* pos 0377: 483 */    0x00, 0x3B                  /* - terminal marker 59 - */,\n/* pos 0379: 484 */    0xE1 /* 'a' -> */,\n/* pos 037a: 485 */    0xF8 /* 'x' -> */,\n/* pos 037b: 486 */    0xAD /* '-' -> */,\n/* pos 037c: 487 */    0xE6 /* 'f' -> */,\n/* pos 037d: 488 */    0xEF /* 'o' -> */,\n/* pos 037e: 489 */    0xF2 /* 'r' -> */,\n/* pos 037f: 490 */    0xF7 /* 'w' -> */,\n/* pos 0380: 491 */    0xE1 /* 'a' -> */,\n/* pos 0381: 492 */    0xF2 /* 'r' -> */,\n/* pos 0382: 493 */    0xE4 /* 'd' -> */,\n/* pos 0383: 494 */    0xF3 /* 's' -> */,\n/* pos 0384: 495 */    0xBA /* ':' -> */,\n/* pos 0385: 496 */    0x00, 0x3C                  /* - terminal marker 60 - */,\n/* pos 0387: 497 */    0xF8 /* 'x' -> */,\n/* pos 0388: 498 */    0xF9 /* 'y' -> */,\n/* pos 0389: 499 */    0x2D /* '-' */, 0x07, 0x00  /* (to 0x0390 state 500) */,\n                       0x20 /* ' ' */, 0xBB, 0x00  /* (to 0x0447 state 649) */,\n                       0x08, /* fail */\n/* pos 0390: 500 */    0xE1 /* 'a' -> */,\n/* pos 0391: 501 */    0xF5 /* 'u' -> */,\n/* pos 0392: 502 */    0xF4 /* 't' -> */,\n/* pos 0393: 503 */    0xE8 /* 'h' -> */,\n/* pos 0394: 504 */    0x65 /* 'e' */, 0x07, 0x00  /* (to 0x039B state 505) */,\n                       0x6F /* 'o' */, 0x0E, 0x00  /* (to 0x03A5 state 514) */,\n                       0x08, /* fail */\n/* pos 039b: 505 */    0xEE /* 'n' -> */,\n/* pos 039c: 506 */    0xF4 /* 't' -> */,\n/* pos 039d: 507 */    0xE9 /* 'i' -> */,\n/* pos 039e: 508 */    0xE3 /* 'c' -> */,\n/* pos 039f: 509 */    0xE1 /* 'a' -> */,\n/* pos 03a0: 510 */    0xF4 /* 't' -> */,\n/* pos 03a1: 511 */    0xE5 /* 'e' -> */,\n/* pos 03a2: 512 */    0xBA /* ':' -> */,\n/* pos 03a3: 513 */    0x00, 0x3D                  /* - terminal marker 61 - */,\n/* pos 03a5: 514 */    0xF2 /* 'r' -> */,\n/* pos 03a6: 515 */    0xE9 /* 'i' -> */,\n/* pos 03a7: 516 */    0xFA /* 'z' -> */,\n/* pos 03a8: 517 */    0xE1 /* 'a' -> */,\n/* pos 03a9: 518 */    0xF4 /* 't' -> */,\n/* pos 03aa: 519 */    0xE9 /* 'i' -> */,\n/* pos 03ab: 520 */    0xEF /* 'o' -> */,\n/* pos 03ac: 521 */    0xEE /* 'n' -> */,\n/* pos 03ad: 522 */    0xBA /* ':' -> */,\n/* pos 03ae: 523 */    0x00, 0x3E                  /* - terminal marker 62 - */,\n/* pos 03b0: 524 */    0xE5 /* 'e' -> */,\n/* pos 03b1: 525 */    0xF3 /* 's' -> */,\n/* pos 03b2: 526 */    0xE8 /* 'h' -> */,\n/* pos 03b3: 527 */    0xBA /* ':' -> */,\n/* pos 03b4: 528 */    0x00, 0x3F                  /* - terminal marker 63 - */,\n/* pos 03b6: 529 */    0xF2 /* 'r' -> */,\n/* pos 03b7: 530 */    0xF9 /* 'y' -> */,\n/* pos 03b8: 531 */    0xAD /* '-' -> */,\n/* pos 03b9: 532 */    0xE1 /* 'a' -> */,\n/* pos 03ba: 533 */    0xE6 /* 'f' -> */,\n/* pos 03bb: 534 */    0xF4 /* 't' -> */,\n/* pos 03bc: 535 */    0xE5 /* 'e' -> */,\n/* pos 03bd: 536 */    0xF2 /* 'r' -> */,\n/* pos 03be: 537 */    0xBA /* ':' -> */,\n/* pos 03bf: 538 */    0x00, 0x40                  /* - terminal marker 64 - */,\n/* pos 03c1: 539 */    0xF6 /* 'v' -> */,\n/* pos 03c2: 540 */    0xE5 /* 'e' -> */,\n/* pos 03c3: 541 */    0xF2 /* 'r' -> */,\n/* pos 03c4: 542 */    0xBA /* ':' -> */,\n/* pos 03c5: 543 */    0x00, 0x41                  /* - terminal marker 65 - */,\n/* pos 03c7: 544 */    0xAD /* '-' -> */,\n/* pos 03c8: 545 */    0xE3 /* 'c' -> */,\n/* pos 03c9: 546 */    0xEF /* 'o' -> */,\n/* pos 03ca: 547 */    0xEF /* 'o' -> */,\n/* pos 03cb: 548 */    0xEB /* 'k' -> */,\n/* pos 03cc: 549 */    0xE9 /* 'i' -> */,\n/* pos 03cd: 550 */    0xE5 /* 'e' -> */,\n/* pos 03ce: 551 */    0xBA /* ':' -> */,\n/* pos 03cf: 552 */    0x00, 0x42                  /* - terminal marker 66 - */,\n/* pos 03d1: 553 */    0xF2 /* 'r' -> */,\n/* pos 03d2: 554 */    0xE9 /* 'i' -> */,\n/* pos 03d3: 555 */    0xE3 /* 'c' -> */,\n/* pos 03d4: 556 */    0xF4 /* 't' -> */,\n/* pos 03d5: 557 */    0xAD /* '-' -> */,\n/* pos 03d6: 558 */    0xF4 /* 't' -> */,\n/* pos 03d7: 559 */    0xF2 /* 'r' -> */,\n/* pos 03d8: 560 */    0xE1 /* 'a' -> */,\n/* pos 03d9: 561 */    0xEE /* 'n' -> */,\n/* pos 03da: 562 */    0xF3 /* 's' -> */,\n/* pos 03db: 563 */    0xF0 /* 'p' -> */,\n/* pos 03dc: 564 */    0xEF /* 'o' -> */,\n/* pos 03dd: 565 */    0xF2 /* 'r' -> */,\n/* pos 03de: 566 */    0xF4 /* 't' -> */,\n/* pos 03df: 567 */    0xAD /* '-' -> */,\n/* pos 03e0: 568 */    0xF3 /* 's' -> */,\n/* pos 03e1: 569 */    0xE5 /* 'e' -> */,\n/* pos 03e2: 570 */    0xE3 /* 'c' -> */,\n/* pos 03e3: 571 */    0xF5 /* 'u' -> */,\n/* pos 03e4: 572 */    0xF2 /* 'r' -> */,\n/* pos 03e5: 573 */    0xE9 /* 'i' -> */,\n/* pos 03e6: 574 */    0xF4 /* 't' -> */,\n/* pos 03e7: 575 */    0xF9 /* 'y' -> */,\n/* pos 03e8: 576 */    0xBA /* ':' -> */,\n/* pos 03e9: 577 */    0x00, 0x43                  /* - terminal marker 67 - */,\n/* pos 03eb: 578 */    0x72 /* 'r' */, 0x07, 0x00  /* (to 0x03F2 state 579) */,\n                       0x65 /* 'e' */, 0x87, 0x00  /* (to 0x0475 state 680) */,\n                       0x08, /* fail */\n/* pos 03f2: 579 */    0xE1 /* 'a' -> */,\n/* pos 03f3: 580 */    0xEE /* 'n' -> */,\n/* pos 03f4: 581 */    0xF3 /* 's' -> */,\n/* pos 03f5: 582 */    0xE6 /* 'f' -> */,\n/* pos 03f6: 583 */    0xE5 /* 'e' -> */,\n/* pos 03f7: 584 */    0xF2 /* 'r' -> */,\n/* pos 03f8: 585 */    0xAD /* '-' -> */,\n/* pos 03f9: 586 */    0xE5 /* 'e' -> */,\n/* pos 03fa: 587 */    0xEE /* 'n' -> */,\n/* pos 03fb: 588 */    0xE3 /* 'c' -> */,\n/* pos 03fc: 589 */    0xEF /* 'o' -> */,\n/* pos 03fd: 590 */    0xE4 /* 'd' -> */,\n/* pos 03fe: 591 */    0xE9 /* 'i' -> */,\n/* pos 03ff: 592 */    0xEE /* 'n' -> */,\n/* pos 0400: 593 */    0xE7 /* 'g' -> */,\n/* pos 0401: 594 */    0xBA /* ':' -> */,\n/* pos 0402: 595 */    0x00, 0x44                  /* - terminal marker 68 - */,\n/* pos 0404: 596 */    0xE5 /* 'e' -> */,\n/* pos 0405: 597 */    0xF2 /* 'r' -> */,\n/* pos 0406: 598 */    0xAD /* '-' -> */,\n/* pos 0407: 599 */    0xE1 /* 'a' -> */,\n/* pos 0408: 600 */    0xE7 /* 'g' -> */,\n/* pos 0409: 601 */    0xE5 /* 'e' -> */,\n/* pos 040a: 602 */    0xEE /* 'n' -> */,\n/* pos 040b: 603 */    0xF4 /* 't' -> */,\n/* pos 040c: 604 */    0xBA /* ':' -> */,\n/* pos 040d: 605 */    0x00, 0x45                  /* - terminal marker 69 - */,\n/* pos 040f: 606 */    0x61 /* 'a' */, 0x07, 0x00  /* (to 0x0416 state 607) */,\n                       0x69 /* 'i' */, 0x09, 0x00  /* (to 0x041B state 611) */,\n                       0x08, /* fail */\n/* pos 0416: 607 */    0xF2 /* 'r' -> */,\n/* pos 0417: 608 */    0xF9 /* 'y' -> */,\n/* pos 0418: 609 */    0xBA /* ':' -> */,\n/* pos 0419: 610 */    0x00, 0x46                  /* - terminal marker 70 - */,\n/* pos 041b: 611 */    0xE1 /* 'a' -> */,\n/* pos 041c: 612 */    0xBA /* ':' -> */,\n/* pos 041d: 613 */    0x00, 0x47                  /* - terminal marker 71 - */,\n/* pos 041f: 614 */    0xF7 /* 'w' -> */,\n/* pos 0420: 615 */    0xF7 /* 'w' -> */,\n/* pos 0421: 616 */    0xAD /* '-' -> */,\n/* pos 0422: 617 */    0xE1 /* 'a' -> */,\n/* pos 0423: 618 */    0xF5 /* 'u' -> */,\n/* pos 0424: 619 */    0xF4 /* 't' -> */,\n/* pos 0425: 620 */    0xE8 /* 'h' -> */,\n/* pos 0426: 621 */    0xE5 /* 'e' -> */,\n/* pos 0427: 622 */    0xEE /* 'n' -> */,\n/* pos 0428: 623 */    0xF4 /* 't' -> */,\n/* pos 0429: 624 */    0xE9 /* 'i' -> */,\n/* pos 042a: 625 */    0xE3 /* 'c' -> */,\n/* pos 042b: 626 */    0xE1 /* 'a' -> */,\n/* pos 042c: 627 */    0xF4 /* 't' -> */,\n/* pos 042d: 628 */    0xE5 /* 'e' -> */,\n/* pos 042e: 629 */    0xBA /* ':' -> */,\n/* pos 042f: 630 */    0x00, 0x48                  /* - terminal marker 72 - */,\n/* pos 0431: 631 */    0xF4 /* 't' -> */,\n/* pos 0432: 632 */    0xE3 /* 'c' -> */,\n/* pos 0433: 633 */    0xE8 /* 'h' -> */,\n/* pos 0434: 634 */    0x00, 0x49                  /* - terminal marker 73 - */,\n/* pos 0436: 635 */    0xF4 /* 't' -> */,\n/* pos 0437: 636 */    0x00, 0x4A                  /* - terminal marker 74 - */,\n/* pos 0439: 637 */    0xEC /* 'l' -> */,\n/* pos 043a: 638 */    0xE5 /* 'e' -> */,\n/* pos 043b: 639 */    0xF4 /* 't' -> */,\n/* pos 043c: 640 */    0xE5 /* 'e' -> */,\n/* pos 043d: 641 */    0x00, 0x4B                  /* - terminal marker 75 - */,\n/* pos 043f: 642 */    0xE9 /* 'i' -> */,\n/* pos 0440: 643 */    0xAD /* '-' -> */,\n/* pos 0441: 644 */    0xE1 /* 'a' -> */,\n/* pos 0442: 645 */    0xF2 /* 'r' -> */,\n/* pos 0443: 646 */    0xE7 /* 'g' -> */,\n/* pos 0444: 647 */    0xF3 /* 's' -> */,\n/* pos 0445: 648 */    0x00, 0x4C                  /* - terminal marker 76 - */,\n/* pos 0447: 649 */    0x00, 0x4D                  /* - terminal marker 77 - */,\n/* pos 0449: 650 */    0xAD /* '-' -> */,\n/* pos 044a: 651 */    0x72 /* 'r' */, 0x0A, 0x00  /* (to 0x0454 state 652) */,\n                       0x66 /* 'f' */, 0x13, 0x00  /* (to 0x0460 state 662) */,\n                       0x61 /* 'a' */, 0x3C, 0x00  /* (to 0x048C state 700) */,\n                       0x08, /* fail */\n/* pos 0454: 652 */    0xE5 /* 'e' -> */,\n/* pos 0455: 653 */    0xE1 /* 'a' -> */,\n/* pos 0456: 654 */    0xEC /* 'l' -> */,\n/* pos 0457: 655 */    0xAD /* '-' -> */,\n/* pos 0458: 656 */    0xE9 /* 'i' -> */,\n/* pos 0459: 657 */    0xF0 /* 'p' -> */,\n/* pos 045a: 658 */    0xBA /* ':' -> */,\n/* pos 045b: 659 */    0x00, 0x4E                  /* - terminal marker 78 - */,\n/* pos 045d: 660 */    0xA0 /* ' ' -> */,\n/* pos 045e: 661 */    0x00, 0x4F                  /* - terminal marker 79 - */,\n/* pos 0460: 662 */    0xEF /* 'o' -> */,\n/* pos 0461: 663 */    0xF2 /* 'r' -> */,\n/* pos 0462: 664 */    0xF7 /* 'w' -> */,\n/* pos 0463: 665 */    0xE1 /* 'a' -> */,\n/* pos 0464: 666 */    0xF2 /* 'r' -> */,\n/* pos 0465: 667 */    0xE4 /* 'd' -> */,\n/* pos 0466: 668 */    0xE5 /* 'e' -> */,\n/* pos 0467: 669 */    0xE4 /* 'd' -> */,\n/* pos 0468: 670 */    0xAD /* '-' -> */,\n/* pos 0469: 671 */    0xE6 /* 'f' -> */,\n/* pos 046a: 672 */    0xEF /* 'o' -> */,\n/* pos 046b: 673 */    0xF2 /* 'r' -> */,\n/* pos 046c: 674 */    0x00, 0x50                  /* - terminal marker 80 - */,\n/* pos 046e: 675 */    0x00, 0x51                  /* - terminal marker 81 - */,\n/* pos 0470: 676 */    0xE1 /* 'a' -> */,\n/* pos 0471: 677 */    0xE4 /* 'd' -> */,\n/* pos 0472: 678 */    0xA0 /* ' ' -> */,\n/* pos 0473: 679 */    0x00, 0x52                  /* - terminal marker 82 - */,\n/* pos 0475: 680 */    0xBA /* ':' -> */,\n/* pos 0476: 681 */    0x00, 0x53                  /* - terminal marker 83 - */,\n/* pos 0478: 682 */    0xEC /* 'l' -> */,\n/* pos 0479: 683 */    0xE1 /* 'a' -> */,\n/* pos 047a: 684 */    0xF9 /* 'y' -> */,\n/* pos 047b: 685 */    0xAD /* '-' -> */,\n/* pos 047c: 686 */    0xEE /* 'n' -> */,\n/* pos 047d: 687 */    0xEF /* 'o' -> */,\n/* pos 047e: 688 */    0xEE /* 'n' -> */,\n/* pos 047f: 689 */    0xE3 /* 'c' -> */,\n/* pos 0480: 690 */    0xE5 /* 'e' -> */,\n/* pos 0481: 691 */    0xBA /* ':' -> */,\n/* pos 0482: 692 */    0x00, 0x54                  /* - terminal marker 84 - */,\n/* pos 0484: 693 */    0xEF /* 'o' -> */,\n/* pos 0485: 694 */    0xF4 /* 't' -> */,\n/* pos 0486: 695 */    0xEF /* 'o' -> */,\n/* pos 0487: 696 */    0xE3 /* 'c' -> */,\n/* pos 0488: 697 */    0xEF /* 'o' -> */,\n/* pos 0489: 698 */    0xEC /* 'l' -> */,\n/* pos 048a: 699 */    0x00, 0x55                  /* - terminal marker 85 - */,\n/* pos 048c: 700 */    0xF5 /* 'u' -> */,\n/* pos 048d: 701 */    0xF4 /* 't' -> */,\n/* pos 048e: 702 */    0xE8 /* 'h' -> */,\n/* pos 048f: 703 */    0xAD /* '-' -> */,\n/* pos 0490: 704 */    0xF4 /* 't' -> */,\n/* pos 0491: 705 */    0xEF /* 'o' -> */,\n/* pos 0492: 706 */    0xEB /* 'k' -> */,\n/* pos 0493: 707 */    0xE5 /* 'e' -> */,\n/* pos 0494: 708 */    0xEE /* 'n' -> */,\n/* pos 0495: 709 */    0xBA /* ':' -> */,\n/* pos 0496: 710 */    0x00, 0x56                  /* - terminal marker 86 - */,\n/* total size 1176 bytes */\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/http/private.h",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n *\n *  This is included from core/private.h if either H1 or H2 roles are\n *  enabled\n */\n\n#if defined(LWS_WITH_HTTP_PROXY)\n  #include <hubbub/hubbub.h>\n  #include <hubbub/parser.h>\n #endif\n\n#define lwsi_role_http(wsi) (lwsi_role_h1(wsi) || lwsi_role_h2(wsi))\n\nenum http_version {\n\tHTTP_VERSION_1_0,\n\tHTTP_VERSION_1_1,\n\tHTTP_VERSION_2\n};\n\nenum http_connection_type {\n\tHTTP_CONNECTION_CLOSE,\n\tHTTP_CONNECTION_KEEP_ALIVE\n};\n\n/*\n * This is totally opaque to code using the library.  It's exported as a\n * forward-reference pointer-only declaration; the user can use the pointer with\n * other APIs to get information out of it.\n */\n\n#if defined(LWS_WITH_ESP32)\ntypedef uint16_t ah_data_idx_t;\n#else\ntypedef uint32_t ah_data_idx_t;\n#endif\n\nstruct lws_fragments {\n\tah_data_idx_t\toffset;\n\tuint16_t\tlen;\n\tuint8_t\t\tnfrag; /* which ah->frag[] continues this content, or 0 */\n\tuint8_t\t\tflags; /* only http2 cares */\n};\n\n#if defined(LWS_WITH_RANGES)\nenum range_states {\n\tLWSRS_NO_ACTIVE_RANGE,\n\tLWSRS_BYTES_EQ,\n\tLWSRS_FIRST,\n\tLWSRS_STARTING,\n\tLWSRS_ENDING,\n\tLWSRS_COMPLETED,\n\tLWSRS_SYNTAX,\n};\n\nstruct lws_range_parsing {\n\tunsigned long long start, end, extent, agg, budget;\n\tconst char buf[128];\n\tint pos;\n\tenum range_states state;\n\tchar start_valid, end_valid, ctr, count_ranges, did_try, inside, send_ctr;\n};\n\nint\nlws_ranges_init(struct lws *wsi, struct lws_range_parsing *rp,\n\t\tunsigned long long extent);\nint\nlws_ranges_next(struct lws_range_parsing *rp);\nvoid\nlws_ranges_reset(struct lws_range_parsing *rp);\n#endif\n\n/*\n * these are assigned from a pool held in the context.\n * Both client and server mode uses them for http header analysis\n */\n\nstruct allocated_headers {\n\tstruct allocated_headers *next; /* linked list */\n\tstruct lws *wsi; /* owner */\n\tchar *data; /* prepared by context init to point to dedicated storage */\n\tah_data_idx_t data_length;\n\t/*\n\t * the randomly ordered fragments, indexed by frag_index and\n\t * lws_fragments->nfrag for continuation.\n\t */\n\tstruct lws_fragments frags[WSI_TOKEN_COUNT];\n\ttime_t assigned;\n\t/*\n\t * for each recognized token, frag_index says which frag[] his data\n\t * starts in (0 means the token did not appear)\n\t * the actual header data gets dumped as it comes in, into data[]\n\t */\n\tuint8_t frag_index[WSI_TOKEN_COUNT];\n\n#ifndef LWS_NO_CLIENT\n\tchar initial_handshake_hash_base64[30];\n#endif\n\n\tuint32_t pos;\n\tuint32_t http_response;\n\tuint32_t current_token_limit;\n\tint hdr_token_idx;\n\n\tint16_t lextable_pos;\n\n\tuint8_t in_use;\n\tuint8_t nfrag;\n\tchar /*enum uri_path_states */ ups;\n\tchar /*enum uri_esc_states */ ues;\n\n\tchar esc_stash;\n\tchar post_literal_equal;\n\tuint8_t /* enum lws_token_indexes */ parser_state;\n};\n\n\n\n#if defined(LWS_WITH_HTTP_PROXY)\nstruct lws_rewrite {\n\thubbub_parser *parser;\n\thubbub_parser_optparams params;\n\tconst char *from, *to;\n\tint from_len, to_len;\n\tunsigned char *p, *end;\n\tstruct lws *wsi;\n};\nstatic LWS_INLINE int hstrcmp(hubbub_string *s, const char *p, int len)\n{\n\tif ((int)s->len != len)\n\t\treturn 1;\n\n\treturn strncmp((const char *)s->ptr, p, len);\n}\ntypedef hubbub_error (*hubbub_callback_t)(const hubbub_token *token, void *pw);\nLWS_EXTERN struct lws_rewrite *\nlws_rewrite_create(struct lws *wsi, hubbub_callback_t cb, const char *from, const char *to);\nLWS_EXTERN void\nlws_rewrite_destroy(struct lws_rewrite *r);\nLWS_EXTERN int\nlws_rewrite_parse(struct lws_rewrite *r, const unsigned char *in, int in_len);\n#endif\n\nstruct lws_pt_role_http {\n\tstruct allocated_headers *ah_list;\n\tstruct lws *ah_wait_list;\n#ifdef LWS_WITH_CGI\n\tstruct lws_cgi *cgi_list;\n#endif\n\tint ah_wait_list_length;\n\tuint32_t ah_pool_length;\n\n\tint ah_count_in_use;\n};\n\nstruct lws_peer_role_http {\n\tuint32_t count_ah;\n\tuint32_t total_ah;\n};\n\nstruct lws_vhost_role_http {\n\tchar http_proxy_address[128];\n\tconst struct lws_http_mount *mount_list;\n\tconst char *error_document_404;\n\tunsigned int http_proxy_port;\n};\n\n#ifdef LWS_WITH_ACCESS_LOG\nstruct lws_access_log {\n\tchar *header_log;\n\tchar *user_agent;\n\tchar *referrer;\n\tunsigned long sent;\n\tint response;\n};\n#endif\n\nstruct _lws_http_mode_related {\n\tstruct lws *new_wsi_list;\n\n#if defined(LWS_WITH_HTTP_PROXY)\n\tstruct lws_rewrite *rw;\n#endif\n\tstruct allocated_headers *ah;\n\tstruct lws *ah_wait_list;\n\n\tlws_filepos_t filepos;\n\tlws_filepos_t filelen;\n\tlws_fop_fd_t fop_fd;\n\n#if defined(LWS_WITH_RANGES)\n\tstruct lws_range_parsing range;\n\tchar multipart_content_type[64];\n#endif\n\n#ifdef LWS_WITH_ACCESS_LOG\n\tstruct lws_access_log access_log;\n#endif\n#ifdef LWS_WITH_CGI\n\tstruct lws_cgi *cgi; /* wsi being cgi master have one of these */\n#endif\n\n\tenum http_version request_version;\n\tenum http_connection_type connection_type;\n\tlws_filepos_t tx_content_length;\n\tlws_filepos_t tx_content_remain;\n\tlws_filepos_t rx_content_length;\n\tlws_filepos_t rx_content_remain;\n\n#if defined(LWS_WITH_HTTP_PROXY)\n\tunsigned int perform_rewrite:1;\n#endif\n\tunsigned int deferred_transaction_completed:1;\n};\n\n\n#ifndef LWS_NO_CLIENT\nenum lws_chunk_parser {\n\tELCP_HEX,\n\tELCP_CR,\n\tELCP_CONTENT,\n\tELCP_POST_CR,\n\tELCP_POST_LF,\n};\n#endif\n\nenum lws_parse_urldecode_results {\n\tLPUR_CONTINUE,\n\tLPUR_SWALLOW,\n\tLPUR_FORBID,\n\tLPUR_EXCESSIVE,\n};\n\nint\nlws_read_h1(struct lws *wsi, unsigned char *buf, lws_filepos_t len);\n\nvoid\n_lws_header_table_reset(struct allocated_headers *ah);\n\nLWS_EXTERN int\n_lws_destroy_ah(struct lws_context_per_thread *pt, struct allocated_headers *ah);\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/http/server/access-log.c",
    "content": "/*\n * libwebsockets - server access log handling\n *\n * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n\n/*\n * Produce Apache-compatible log string for wsi, like this:\n *\n * 2.31.234.19 - - [27/Mar/2016:03:22:44 +0800]\n * \"GET /aep-screen.png HTTP/1.1\"\n * 200 152987 \"https://libwebsockets.org/index.html\"\n * \"Mozilla/5.0 (Macint... Chrome/49.0.2623.87 Safari/537.36\"\n *\n */\n\nextern const char * const method_names[];\n\nstatic const char * const hver[] = {\n\t\"HTTP/1.0\", \"HTTP/1.1\", \"HTTP/2\"\n};\n\nvoid\nlws_prepare_access_log_info(struct lws *wsi, char *uri_ptr, int meth)\n{\n#ifdef LWS_WITH_IPV6\n\tchar ads[INET6_ADDRSTRLEN];\n#else\n\tchar ads[INET_ADDRSTRLEN];\n#endif\n\tchar da[64];\n\tconst char *pa, *me;\n\tstruct tm *tmp;\n\ttime_t t = time(NULL);\n\tint l = 256, m;\n\n\tif (!wsi->vhost)\n\t\treturn;\n\n\t/* only worry about preparing it if we store it */\n\tif (wsi->vhost->log_fd == (int)LWS_INVALID_FILE)\n\t\treturn;\n\n\tif (wsi->access_log_pending)\n\t\tlws_access_log(wsi);\n\n\twsi->http.access_log.header_log = lws_malloc(l, \"access log\");\n\tif (wsi->http.access_log.header_log) {\n\n\t\ttmp = localtime(&t);\n\t\tif (tmp)\n\t\t\tstrftime(da, sizeof(da), \"%d/%b/%Y:%H:%M:%S %z\", tmp);\n\t\telse\n\t\t\tstrcpy(da, \"01/Jan/1970:00:00:00 +0000\");\n\n\t\tpa = lws_get_peer_simple(wsi, ads, sizeof(ads));\n\t\tif (!pa)\n\t\t\tpa = \"(unknown)\";\n\n\t\tif (wsi->http2_substream)\n\t\t\tme = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COLON_METHOD);\n\t\telse\n\t\t\tme = method_names[meth];\n\t\tif (!me)\n\t\t\tme = \"(null)\";\n\n\t\tlws_snprintf(wsi->http.access_log.header_log, l,\n\t\t\t \"%s - - [%s] \\\"%s %s %s\\\"\",\n\t\t\t pa, da, me, uri_ptr,\n\t\t\t hver[wsi->http.request_version]);\n\n\t\tl = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT);\n\t\tif (l) {\n\t\t\twsi->http.access_log.user_agent = lws_malloc(l + 2, \"access log\");\n\t\t\tif (!wsi->http.access_log.user_agent) {\n\t\t\t\tlwsl_err(\"OOM getting user agent\\n\");\n\t\t\t\tlws_free_set_NULL(wsi->http.access_log.header_log);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlws_hdr_copy(wsi, wsi->http.access_log.user_agent,\n\t\t\t\t\tl + 1, WSI_TOKEN_HTTP_USER_AGENT);\n\n\t\t\tfor (m = 0; m < l; m++)\n\t\t\t\tif (wsi->http.access_log.user_agent[m] == '\\\"')\n\t\t\t\t\twsi->http.access_log.user_agent[m] = '\\'';\n\t\t}\n\t\tl = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER);\n\t\tif (l) {\n\t\t\twsi->http.access_log.referrer = lws_malloc(l + 2, \"referrer\");\n\t\t\tif (!wsi->http.access_log.referrer) {\n\t\t\t\tlwsl_err(\"OOM getting user agent\\n\");\n\t\t\t\tlws_free_set_NULL(wsi->http.access_log.user_agent);\n\t\t\t\tlws_free_set_NULL(wsi->http.access_log.header_log);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlws_hdr_copy(wsi, wsi->http.access_log.referrer,\n\t\t\t\t\tl + 1, WSI_TOKEN_HTTP_REFERER);\n\n\t\t\tfor (m = 0; m < l; m++)\n\t\t\t\tif (wsi->http.access_log.referrer[m] == '\\\"')\n\t\t\t\t\twsi->http.access_log.referrer[m] = '\\'';\n\t\t}\n\t\twsi->access_log_pending = 1;\n\t}\n}\n\n\nint\nlws_access_log(struct lws *wsi)\n{\n\tchar *p = wsi->http.access_log.user_agent, ass[512],\n\t     *p1 = wsi->http.access_log.referrer;\n\tint l;\n\n\tif (!wsi->vhost)\n\t\treturn 0;\n\n\tif (wsi->vhost->log_fd == (int)LWS_INVALID_FILE)\n\t\treturn 0;\n\n\tif (!wsi->access_log_pending)\n\t\treturn 0;\n\n\tif (!wsi->http.access_log.header_log)\n\t\treturn 0;\n\n\tif (!p)\n\t\tp = \"\";\n\n\tif (!p1)\n\t\tp1 = \"\";\n\n\t/*\n\t * We do this in two parts to restrict an oversize referrer such that\n\t * we will always have space left to append an empty useragent, while\n\t * maintaining the structure of the log text\n\t */\n\tl = lws_snprintf(ass, sizeof(ass) - 7, \"%s %d %lu \\\"%s\",\n\t\t     wsi->http.access_log.header_log,\n\t\t     wsi->http.access_log.response, wsi->http.access_log.sent, p1);\n\tif (strlen(p) > sizeof(ass) - 6 - l)\n\t\tp[sizeof(ass) - 6 - l] = '\\0';\n\tl += lws_snprintf(ass + l, sizeof(ass) - 1 - l, \"\\\" \\\"%s\\\"\\n\", p);\n\n\tif (write(wsi->vhost->log_fd, ass, l) != l)\n\t\tlwsl_err(\"Failed to write log\\n\");\n\n\tif (wsi->http.access_log.header_log) {\n\t\tlws_free(wsi->http.access_log.header_log);\n\t\twsi->http.access_log.header_log = NULL;\n\t}\n\tif (wsi->http.access_log.user_agent) {\n\t\tlws_free(wsi->http.access_log.user_agent);\n\t\twsi->http.access_log.user_agent = NULL;\n\t}\n\tif (wsi->http.access_log.referrer) {\n\t\tlws_free(wsi->http.access_log.referrer);\n\t\twsi->http.access_log.referrer = NULL;\n\t}\n\twsi->access_log_pending = 0;\n\n\treturn 0;\n}\n\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/http/server/fops-zip.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Original code used in this source file:\n *\n * https://github.com/PerBothner/DomTerm.git @912add15f3d0aec\n *\n * ./lws-term/io.c\n * ./lws-term/junzip.c\n *\n * Copyright (C) 2017  Per Bothner <per@bothner.com>\n *\n * MIT License\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * ( copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\n * lws rewrite:\n *\n * Copyright (C) 2017  Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n\n#include <zlib.h>\n\n/*\n * This code works with zip format containers which may have files compressed\n * with gzip deflate (type 8) or store uncompressed (type 0).\n *\n * Linux zip produces such zipfiles by default, eg\n *\n *  $ zip ../myzip.zip file1 file2 file3\n */\n\n#define ZIP_COMPRESSION_METHOD_STORE 0\n#define ZIP_COMPRESSION_METHOD_DEFLATE 8\n\ntypedef struct {\n\tlws_filepos_t\t\tfilename_start;\n\tuint32_t\t\tcrc32;\n\tuint32_t\t\tcomp_size;\n\tuint32_t\t\tuncomp_size;\n\tuint32_t\t\toffset;\n\tuint32_t\t\tmod_time;\n\tuint16_t\t\tfilename_len;\n\tuint16_t\t\textra;\n\tuint16_t\t\tmethod;\n\tuint16_t\t\tfile_com_len;\n} lws_fops_zip_hdr_t;\n\ntypedef struct {\n\tstruct lws_fop_fd\tfop_fd; /* MUST BE FIRST logical fop_fd into\n\t \t \t \t \t * file inside zip: fops_zip fops */\n\tlws_fop_fd_t\t\tzip_fop_fd; /* logical fop fd on to zip file\n\t \t \t \t \t     * itself: using platform fops */\n\tlws_fops_zip_hdr_t\thdr;\n\tz_stream\t\tinflate;\n\tlws_filepos_t\t\tcontent_start;\n\tlws_filepos_t\t\texp_uncomp_pos;\n\tunion {\n\t\tuint8_t\t\ttrailer8[8];\n\t\tuint32_t\ttrailer32[2];\n\t} u;\n\tuint8_t\t\t\trbuf[128]; /* decompression chunk size */\n\tint\t\t\tentry_count;\n\n\tunsigned int\t\tdecompress:1; /* 0 = direct from file */\n\tunsigned int\t\tadd_gzip_container:1;\n} *lws_fops_zip_t;\n\nstruct lws_plat_file_ops fops_zip;\n#define fop_fd_to_priv(FD) ((lws_fops_zip_t)(FD))\n\nstatic const uint8_t hd[] = { 31, 139, 8, 0, 0, 0, 0, 0, 0, 3 };\n\nenum {\n\tZC_SIGNATURE\t\t\t\t= 0,\n\tZC_VERSION_MADE_BY \t\t\t= 4,\n\tZC_VERSION_NEEDED_TO_EXTRACT \t\t= 6,\n\tZC_GENERAL_PURPOSE_BIT_FLAG \t\t= 8,\n\tZC_COMPRESSION_METHOD \t\t\t= 10,\n\tZC_LAST_MOD_FILE_TIME \t\t\t= 12,\n\tZC_LAST_MOD_FILE_DATE \t\t\t= 14,\n\tZC_CRC32 \t\t\t\t= 16,\n\tZC_COMPRESSED_SIZE \t\t\t= 20,\n\tZC_UNCOMPRESSED_SIZE \t\t\t= 24,\n\tZC_FILE_NAME_LENGTH \t\t\t= 28,\n\tZC_EXTRA_FIELD_LENGTH \t\t\t= 30,\n\n\tZC_FILE_COMMENT_LENGTH \t\t\t= 32,\n\tZC_DISK_NUMBER_START \t\t\t= 34,\n\tZC_INTERNAL_FILE_ATTRIBUTES \t\t= 36,\n\tZC_EXTERNAL_FILE_ATTRIBUTES \t\t= 38,\n\tZC_REL_OFFSET_LOCAL_HEADER \t\t= 42,\n\tZC_DIRECTORY_LENGTH \t\t\t= 46,\n\n\tZE_SIGNATURE_OFFSET \t\t\t= 0,\n\tZE_DESK_NUMBER \t\t\t\t= 4,\n\tZE_CENTRAL_DIRECTORY_DISK_NUMBER \t= 6,\n\tZE_NUM_ENTRIES_THIS_DISK \t\t= 8,\n\tZE_NUM_ENTRIES \t\t\t\t= 10,\n\tZE_CENTRAL_DIRECTORY_SIZE \t\t= 12,\n\tZE_CENTRAL_DIR_OFFSET \t\t\t= 16,\n\tZE_ZIP_COMMENT_LENGTH \t\t\t= 20,\n\tZE_DIRECTORY_LENGTH \t\t\t= 22,\n\n\tZL_REL_OFFSET_CONTENT\t\t\t= 28,\n\tZL_HEADER_LENGTH\t\t\t= 30,\n\n\tLWS_FZ_ERR_SEEK_END_RECORD\t\t= 1,\n\tLWS_FZ_ERR_READ_END_RECORD,\n\tLWS_FZ_ERR_END_RECORD_MAGIC,\n\tLWS_FZ_ERR_END_RECORD_SANITY,\n\tLWS_FZ_ERR_CENTRAL_SEEK,\n\tLWS_FZ_ERR_CENTRAL_READ,\n\tLWS_FZ_ERR_CENTRAL_SANITY,\n\tLWS_FZ_ERR_NAME_TOO_LONG,\n\tLWS_FZ_ERR_NAME_SEEK,\n\tLWS_FZ_ERR_NAME_READ,\n\tLWS_FZ_ERR_CONTENT_SANITY,\n\tLWS_FZ_ERR_CONTENT_SEEK,\n\tLWS_FZ_ERR_SCAN_SEEK,\n\tLWS_FZ_ERR_NOT_FOUND,\n\tLWS_FZ_ERR_ZLIB_INIT,\n\tLWS_FZ_ERR_READ_CONTENT,\n\tLWS_FZ_ERR_SEEK_COMPRESSED,\n};\n\nstatic uint16_t\nget_u16(void *p)\n{\n\tconst uint8_t *c = (const uint8_t *)p;\n\n\treturn (uint16_t)((c[0] | (c[1] << 8)));\n}\n\nstatic uint32_t\nget_u32(void *p)\n{\n\tconst uint8_t *c = (const uint8_t *)p;\n\n\treturn (uint32_t)((c[0] | (c[1] << 8) | (c[2] << 16) | (c[3] << 24)));\n}\n\nint\nlws_fops_zip_scan(lws_fops_zip_t priv, const char *name, int len)\n{\n\tlws_filepos_t amount;\n\tuint8_t buf[96];\n\tint i;\n\n\tif (lws_vfs_file_seek_end(priv->zip_fop_fd, -ZE_DIRECTORY_LENGTH) < 0)\n\t\treturn LWS_FZ_ERR_SEEK_END_RECORD;\n\n\tif (lws_vfs_file_read(priv->zip_fop_fd, &amount, buf,\n\t\t\t      ZE_DIRECTORY_LENGTH))\n\t\treturn LWS_FZ_ERR_READ_END_RECORD;\n\n\tif (amount != ZE_DIRECTORY_LENGTH)\n\t\treturn LWS_FZ_ERR_READ_END_RECORD;\n\n\t/*\n\t * We require the zip to have the last record right at the end\n\t * Linux zip always does this if no zip comment.\n\t */\n\tif (buf[0] != 'P' || buf[1] != 'K' || buf[2] != 5 || buf[3] != 6)\n\t\treturn LWS_FZ_ERR_END_RECORD_MAGIC;\n\n\ti = get_u16(buf + ZE_NUM_ENTRIES);\n\n\tif (get_u16(buf + ZE_DESK_NUMBER) ||\n\t    get_u16(buf + ZE_CENTRAL_DIRECTORY_DISK_NUMBER) ||\n\t    i != get_u16(buf + ZE_NUM_ENTRIES_THIS_DISK))\n\t\treturn LWS_FZ_ERR_END_RECORD_SANITY;\n\n\t/* end record is OK... look for our file in the central dir */\n\n\tif (lws_vfs_file_seek_set(priv->zip_fop_fd,\n\t\t\t\t  get_u32(buf + ZE_CENTRAL_DIR_OFFSET)) < 0)\n\t\treturn LWS_FZ_ERR_CENTRAL_SEEK;\n\n\twhile (i--) {\n\t\tpriv->content_start = lws_vfs_tell(priv->zip_fop_fd);\n\n\t\tif (lws_vfs_file_read(priv->zip_fop_fd, &amount, buf,\n\t\t\t\t      ZC_DIRECTORY_LENGTH))\n\t\t\treturn LWS_FZ_ERR_CENTRAL_READ;\n\n\t\tif (amount != ZC_DIRECTORY_LENGTH)\n\t\t\treturn LWS_FZ_ERR_CENTRAL_READ;\n\n\t\tif (get_u32(buf + ZC_SIGNATURE) != 0x02014B50)\n\t\t\treturn LWS_FZ_ERR_CENTRAL_SANITY;\n\n               lwsl_debug(\"cstart 0x%lx\\n\", (unsigned long)priv->content_start);\n\n\t\tpriv->hdr.filename_len = get_u16(buf + ZC_FILE_NAME_LENGTH);\n\t\tpriv->hdr.extra = get_u16(buf + ZC_EXTRA_FIELD_LENGTH);\n\t\tpriv->hdr.filename_start = lws_vfs_tell(priv->zip_fop_fd);\n\n\t\tpriv->hdr.method = get_u16(buf + ZC_COMPRESSION_METHOD);\n\t\tpriv->hdr.crc32 = get_u32(buf + ZC_CRC32);\n\t\tpriv->hdr.comp_size = get_u32(buf + ZC_COMPRESSED_SIZE);\n\t\tpriv->hdr.uncomp_size = get_u32(buf + ZC_UNCOMPRESSED_SIZE);\n\t\tpriv->hdr.offset = get_u32(buf + ZC_REL_OFFSET_LOCAL_HEADER);\n\t\tpriv->hdr.mod_time = get_u32(buf + ZC_LAST_MOD_FILE_TIME);\n\t\tpriv->hdr.file_com_len = get_u16(buf + ZC_FILE_COMMENT_LENGTH);\n\n\t\tif (priv->hdr.filename_len != len)\n\t\t\tgoto next;\n\n\t\tif (len >= (int)sizeof(buf) - 1)\n\t\t\treturn LWS_FZ_ERR_NAME_TOO_LONG;\n\n\t\tif (priv->zip_fop_fd->fops->LWS_FOP_READ(priv->zip_fop_fd,\n\t\t\t\t\t\t\t&amount, buf, len))\n\t\t\treturn LWS_FZ_ERR_NAME_READ;\n\t\tif ((int)amount != len)\n\t\t\treturn LWS_FZ_ERR_NAME_READ;\n\n\t\tbuf[len] = '\\0';\n\t\tlwsl_debug(\"check %s vs %s\\n\", buf, name);\n\n\t\tif (strcmp((const char *)buf, name))\n\t\t\tgoto next;\n\n\t\t/* we found a match */\n\t\tif (lws_vfs_file_seek_set(priv->zip_fop_fd, priv->hdr.offset) < 0)\n\t\t\treturn LWS_FZ_ERR_NAME_SEEK;\n\t\tif (priv->zip_fop_fd->fops->LWS_FOP_READ(priv->zip_fop_fd,\n\t\t\t\t\t\t\t&amount, buf,\n\t\t\t\t\t\t\tZL_HEADER_LENGTH))\n\t\t\treturn LWS_FZ_ERR_NAME_READ;\n\t\tif (amount != ZL_HEADER_LENGTH)\n\t\t\treturn LWS_FZ_ERR_NAME_READ;\n\n\t\tpriv->content_start = priv->hdr.offset +\n\t\t\t\t      ZL_HEADER_LENGTH +\n\t\t\t\t      priv->hdr.filename_len +\n\t\t\t\t      get_u16(buf + ZL_REL_OFFSET_CONTENT);\n\n\t\tlwsl_debug(\"content supposed to start at 0x%lx\\n\",\n                          (unsigned long)priv->content_start);\n\n\t\tif (priv->content_start > priv->zip_fop_fd->len)\n\t\t\treturn LWS_FZ_ERR_CONTENT_SANITY;\n\n\t\tif (lws_vfs_file_seek_set(priv->zip_fop_fd,\n\t\t\t\t\t  priv->content_start) < 0)\n\t\t\treturn LWS_FZ_ERR_CONTENT_SEEK;\n\n\t\t/* we are aligned at the start of the content */\n\n\t\tpriv->exp_uncomp_pos = 0;\n\n\t\treturn 0;\n\nnext:\n\t\tif (i && lws_vfs_file_seek_set(priv->zip_fop_fd,\n\t\t\t\t\t       priv->content_start +\n\t\t\t\t\t       ZC_DIRECTORY_LENGTH +\n\t\t\t\t\t       priv->hdr.filename_len +\n\t\t\t\t\t       priv->hdr.extra +\n\t\t\t\t\t       priv->hdr.file_com_len) < 0)\n\t\t\treturn LWS_FZ_ERR_SCAN_SEEK;\n\t}\n\n\treturn LWS_FZ_ERR_NOT_FOUND;\n}\n\nstatic int\nlws_fops_zip_reset_inflate(lws_fops_zip_t priv)\n{\n\tif (priv->decompress)\n\t\tinflateEnd(&priv->inflate);\n\n\tpriv->inflate.zalloc = Z_NULL;\n\tpriv->inflate.zfree = Z_NULL;\n\tpriv->inflate.opaque = Z_NULL;\n\tpriv->inflate.avail_in = 0;\n\tpriv->inflate.next_in = Z_NULL;\n\n\tif (inflateInit2(&priv->inflate, -MAX_WBITS) != Z_OK) {\n\t\tlwsl_err(\"inflate init failed\\n\");\n\t\treturn LWS_FZ_ERR_ZLIB_INIT;\n\t}\n\n\tif (lws_vfs_file_seek_set(priv->zip_fop_fd, priv->content_start) < 0)\n\t\treturn LWS_FZ_ERR_CONTENT_SEEK;\n\n\tpriv->exp_uncomp_pos = 0;\n\n\treturn 0;\n}\n\nstatic lws_fop_fd_t\nlws_fops_zip_open(const struct lws_plat_file_ops *fops, const char *vfs_path,\n\t\t  const char *vpath, lws_fop_flags_t *flags)\n{\n\tlws_fop_flags_t local_flags = 0;\n\tlws_fops_zip_t priv;\n\tchar rp[192];\n\tint m;\n\n\t/*\n\t * vpath points at the / after the fops signature in vfs_path, eg\n\t * with a vfs_path \"/var/www/docs/manual.zip/index.html\", vpath\n\t * will come pointing at \"/index.html\"\n\t */\n\n\tpriv = lws_zalloc(sizeof(*priv), \"fops_zip priv\");\n\tif (!priv)\n\t\treturn NULL;\n\n\tpriv->fop_fd.fops = &fops_zip;\n\n\tm = sizeof(rp) - 1;\n\tif ((vpath - vfs_path - 1) < m)\n\t\tm = lws_ptr_diff(vpath, vfs_path) - 1;\n\tlws_strncpy(rp, vfs_path, m + 1);\n\n\t/* open the zip file itself using the incoming fops, not fops_zip */\n\n\tpriv->zip_fop_fd = fops->LWS_FOP_OPEN(fops, rp, NULL, &local_flags);\n\tif (!priv->zip_fop_fd) {\n\t\tlwsl_err(\"unable to open zip %s\\n\", rp);\n\t\tgoto bail1;\n\t}\n\n\tif (*vpath == '/')\n\t\tvpath++;\n\n\tm = lws_fops_zip_scan(priv, vpath, (int)strlen(vpath));\n\tif (m) {\n\t\tlwsl_err(\"unable to find record matching '%s' %d\\n\", vpath, m);\n\t\tgoto bail2;\n\t}\n\n\t/* the directory metadata tells us modification time, so pass it on */\n\tpriv->fop_fd.mod_time = priv->hdr.mod_time;\n\t*flags |= LWS_FOP_FLAG_MOD_TIME_VALID | LWS_FOP_FLAG_VIRTUAL;\n\tpriv->fop_fd.flags = *flags;\n\n\t/* The zip fop_fd is left pointing at the start of the content.\n\t *\n\t * 1) Content could be uncompressed (STORE), and we can always serve\n\t *    that directly\n\t *\n\t * 2) Content could be compressed (GZIP), and the client can handle\n\t *    receiving GZIP... we can wrap it in a GZIP header and trailer\n\t *    and serve the content part directly.  The flag indicating we\n\t *    are providing GZIP directly is set so lws will send the right\n\t *    headers.\n\t *\n\t * 3) Content could be compressed (GZIP) but the client can't handle\n\t *    receiving GZIP... we can decompress it and serve as it is\n\t *    inflated piecemeal.\n\t *\n\t * 4) Content may be compressed some unknown way... fail\n\t *\n\t */\n\tif (priv->hdr.method == ZIP_COMPRESSION_METHOD_STORE) {\n\t\t/*\n\t\t * it is stored uncompressed, leave it indicated as\n\t\t * uncompressed, and just serve it from inside the\n\t\t * zip with no gzip container;\n\t\t */\n\n\t\tlwsl_info(\"direct zip serving (stored)\\n\");\n\n\t\tpriv->fop_fd.len = priv->hdr.uncomp_size;\n\n\t\treturn &priv->fop_fd;\n\t}\n\n\tif ((*flags & LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP) &&\n\t    priv->hdr.method == ZIP_COMPRESSION_METHOD_DEFLATE) {\n\n\t\t/*\n\t\t * We can serve the gzipped file contents directly as gzip\n\t\t * from inside the zip container; client says it is OK.\n\t\t *\n\t\t * To convert to standalone gzip, we have to add a 10-byte\n\t\t * constant header and a variable 8-byte trailer around the\n\t\t * content.\n\t\t *\n\t\t * The 8-byte trailer is prepared now and held in the priv.\n\t\t */\n\n\t\tlwsl_info(\"direct zip serving (gzipped)\\n\");\n\n\t\tpriv->fop_fd.len = sizeof(hd) + priv->hdr.comp_size +\n\t\t\t\t   sizeof(priv->u);\n\n\t\tif (lws_is_be()) {\n\t\t\tuint8_t *p = priv->u.trailer8;\n\n\t\t\t*p++ = (uint8_t)priv->hdr.crc32;\n\t\t\t*p++ = (uint8_t)(priv->hdr.crc32 >> 8);\n\t\t\t*p++ = (uint8_t)(priv->hdr.crc32 >> 16);\n\t\t\t*p++ = (uint8_t)(priv->hdr.crc32 >> 24);\n\t\t\t*p++ = (uint8_t)priv->hdr.uncomp_size;\n\t\t\t*p++ = (uint8_t)(priv->hdr.uncomp_size >> 8);\n\t\t\t*p++ = (uint8_t)(priv->hdr.uncomp_size >> 16);\n\t\t\t*p   = (uint8_t)(priv->hdr.uncomp_size >> 24);\n\t\t} else {\n\t\t\tpriv->u.trailer32[0] = priv->hdr.crc32;\n\t\t\tpriv->u.trailer32[1] = priv->hdr.uncomp_size;\n\t\t}\n\n\t\t*flags |= LWS_FOP_FLAG_COMPR_IS_GZIP;\n\t\tpriv->fop_fd.flags = *flags;\n\t\tpriv->add_gzip_container = 1;\n\n\t\treturn &priv->fop_fd;\n\t}\n\n\tif (priv->hdr.method == ZIP_COMPRESSION_METHOD_DEFLATE) {\n\n\t\t/* we must decompress it to serve it */\n\n\t\tlwsl_info(\"decompressed zip serving\\n\");\n\n\t\tpriv->fop_fd.len = priv->hdr.uncomp_size;\n\n\t\tif (lws_fops_zip_reset_inflate(priv)) {\n\t\t\tlwsl_err(\"inflate init failed\\n\");\n\t\t\tgoto bail2;\n\t\t}\n\n\t\tpriv->decompress = 1;\n\n\t\treturn &priv->fop_fd;\n\t}\n\n\t/* we can't handle it ... */\n\n\tlwsl_err(\"zipped file %s compressed in unknown way (%d)\\n\", vfs_path,\n\t\t priv->hdr.method);\n\nbail2:\n\tlws_vfs_file_close(&priv->zip_fop_fd);\nbail1:\n\tfree(priv);\n\n\treturn NULL;\n}\n\n/* ie, we are closing the fop_fd for the file inside the gzip */\n\nstatic int\nlws_fops_zip_close(lws_fop_fd_t *fd)\n{\n\tlws_fops_zip_t priv = fop_fd_to_priv(*fd);\n\n\tif (priv->decompress)\n\t\tinflateEnd(&priv->inflate);\n\n\tlws_vfs_file_close(&priv->zip_fop_fd); /* close the gzip fop_fd */\n\n\tfree(priv);\n\t*fd = NULL;\n\n\treturn 0;\n}\n\nstatic lws_fileofs_t\nlws_fops_zip_seek_cur(lws_fop_fd_t fd, lws_fileofs_t offset_from_cur_pos)\n{\n\tfd->pos += offset_from_cur_pos;\n\n\treturn fd->pos;\n}\n\nstatic int\nlws_fops_zip_read(lws_fop_fd_t fd, lws_filepos_t *amount, uint8_t *buf,\n\t\t  lws_filepos_t len)\n{\n\tlws_fops_zip_t priv = fop_fd_to_priv(fd);\n\tlws_filepos_t ramount, rlen, cur = lws_vfs_tell(fd);\n\tint ret;\n\n\tif (priv->decompress) {\n\n\t\tif (priv->exp_uncomp_pos != fd->pos) {\n\t\t\t/*\n\t\t\t *  there has been a seek in the uncompressed fop_fd\n\t\t\t * we have to restart the decompression and loop eating\n\t\t\t * the decompressed data up to the seek point\n\t\t\t */\n\t\t\tlwsl_info(\"seek in decompressed\\n\");\n\n\t\t\tlws_fops_zip_reset_inflate(priv);\n\n\t\t\twhile (priv->exp_uncomp_pos != fd->pos) {\n\t\t\t\trlen = len;\n\t\t\t\tif (rlen > fd->pos - priv->exp_uncomp_pos)\n\t\t\t\t\trlen = fd->pos - priv->exp_uncomp_pos;\n\t\t\t\tif (lws_fops_zip_read(fd, amount, buf, rlen))\n\t\t\t\t\treturn LWS_FZ_ERR_SEEK_COMPRESSED;\n\t\t\t}\n\t\t\t*amount = 0;\n\t\t}\n\n\t\tpriv->inflate.avail_out = (unsigned int)len;\n\t\tpriv->inflate.next_out = buf;\n\nspin:\n\t\tif (!priv->inflate.avail_in) {\n\t\t\trlen = sizeof(priv->rbuf);\n\t\t\tif (rlen > priv->hdr.comp_size -\n\t\t\t\t   (cur - priv->content_start))\n\t\t\t\trlen = priv->hdr.comp_size -\n\t\t\t\t       (priv->hdr.comp_size -\n\t\t\t\t\tpriv->content_start);\n\n\t\t\tif (priv->zip_fop_fd->fops->LWS_FOP_READ(\n\t\t\t\t\tpriv->zip_fop_fd, &ramount, priv->rbuf,\n\t\t\t\t\trlen))\n\t\t\t\treturn LWS_FZ_ERR_READ_CONTENT;\n\n\t\t\tcur += ramount;\n\n\t\t\tpriv->inflate.avail_in = (unsigned int)ramount;\n\t\t\tpriv->inflate.next_in = priv->rbuf;\n\t\t}\n\n\t\tret = inflate(&priv->inflate, Z_NO_FLUSH);\n\t\tif (ret == Z_STREAM_ERROR)\n\t\t\treturn ret;\n\n\t\tswitch (ret) {\n\t\tcase Z_NEED_DICT:\n\t\t\tret = Z_DATA_ERROR;\n\t\t\t/* fallthru */\n\t\tcase Z_DATA_ERROR:\n\t\tcase Z_MEM_ERROR:\n\n\t\t\treturn ret;\n\t\t}\n\n\t\tif (!priv->inflate.avail_in && priv->inflate.avail_out &&\n\t\t     cur != priv->content_start + priv->hdr.comp_size)\n\t\t\tgoto spin;\n\n\t\t*amount = len - priv->inflate.avail_out;\n\n\t\tpriv->exp_uncomp_pos += *amount;\n\t\tfd->pos += *amount;\n\n\t\treturn 0;\n\t}\n\n\tif (priv->add_gzip_container) {\n\n\t\tlwsl_info(\"%s: gzip + container\\n\", __func__);\n\t\t*amount = 0;\n\n\t\t/* place the canned header at the start */\n\n\t\tif (len && fd->pos < sizeof(hd)) {\n\t\t\trlen = sizeof(hd) - fd->pos;\n\t\t\tif (rlen > len)\n\t\t\t\trlen = len;\n\t\t\t/* provide stuff from canned header */\n\t\t\tmemcpy(buf, hd + fd->pos, (size_t)rlen);\n\t\t\tfd->pos += rlen;\n\t\t\tbuf += rlen;\n\t\t\tlen -= rlen;\n\t\t\t*amount += rlen;\n\t\t}\n\n\t\t/* serve gzipped data direct from zipfile */\n\n\t\tif (len && fd->pos >= sizeof(hd) &&\n\t\t    fd->pos < priv->hdr.comp_size + sizeof(hd)) {\n\n\t\t\trlen = priv->hdr.comp_size - (priv->zip_fop_fd->pos -\n\t\t\t\t\t\t      priv->content_start);\n\t\t\tif (rlen > len)\n\t\t\t\trlen = len;\n\n\t\t\tif (rlen &&\n\t\t\t    priv->zip_fop_fd->pos < (priv->hdr.comp_size +\n\t\t\t\t\t    \t     priv->content_start)) {\n\t\t\t\tif (lws_vfs_file_read(priv->zip_fop_fd,\n\t\t\t\t\t\t      &ramount, buf, rlen))\n\t\t\t\t\treturn LWS_FZ_ERR_READ_CONTENT;\n\t\t\t\t*amount += ramount;\n\t\t\t\tfd->pos += ramount; // virtual pos\n\t\t\t\tbuf += ramount;\n\t\t\t\tlen -= ramount;\n\t\t\t}\n\t\t}\n\n\t\t/* place the prepared trailer at the end */\n\n\t\tif (len && fd->pos >= priv->hdr.comp_size + sizeof(hd) &&\n\t\t    fd->pos < priv->hdr.comp_size + sizeof(hd) +\n\t\t    \t      sizeof(priv->u)) {\n\t\t\tcur = fd->pos - priv->hdr.comp_size - sizeof(hd);\n\t\t\trlen = sizeof(priv->u) - cur;\n\t\t\tif (rlen > len)\n\t\t\t\trlen = len;\n\n\t\t\tmemcpy(buf, priv->u.trailer8 + cur, (size_t)rlen);\n\n\t\t\t*amount += rlen;\n\t\t\tfd->pos += rlen;\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tlwsl_info(\"%s: store\\n\", __func__);\n\n\tif (len > priv->hdr.uncomp_size - (cur - priv->content_start))\n\t\tlen = priv->hdr.comp_size - (priv->hdr.comp_size -\n\t\t\t\t\t     priv->content_start);\n\n\tif (priv->zip_fop_fd->fops->LWS_FOP_READ(priv->zip_fop_fd,\n\t\t\t\t\t\t amount, buf, len))\n\t\treturn LWS_FZ_ERR_READ_CONTENT;\n\n\treturn 0;\n}\n\nstruct lws_plat_file_ops fops_zip = {\n\tlws_fops_zip_open,\n\tlws_fops_zip_close,\n\tlws_fops_zip_seek_cur,\n\tlws_fops_zip_read,\n\tNULL,\n\t{ { \".zip/\", 5 }, { \".jar/\", 5 }, { \".war/\", 5 } },\n\tNULL,\n};\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/http/server/lejp-conf.c",
    "content": "/*\n * libwebsockets web server application\n *\n * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n\n#ifndef _WIN32\n/* this is needed for Travis CI */\n#include <dirent.h>\n#endif\n\n#define ESC_INSTALL_DATADIR \"_lws_ddir_\"\n\nstatic const char * const paths_global[] = {\n\t\"global.uid\",\n\t\"global.gid\",\n\t\"global.count-threads\",\n\t\"global.init-ssl\",\n\t\"global.server-string\",\n\t\"global.plugin-dir\",\n\t\"global.ws-pingpong-secs\",\n\t\"global.timeout-secs\",\n\t\"global.reject-service-keywords[].*\",\n\t\"global.reject-service-keywords[]\",\n\t\"global.default-alpn\",\n};\n\nenum lejp_global_paths {\n\tLEJPGP_UID,\n\tLEJPGP_GID,\n\tLEJPGP_COUNT_THREADS,\n\tLWJPGP_INIT_SSL,\n\tLEJPGP_SERVER_STRING,\n\tLEJPGP_PLUGIN_DIR,\n\tLWJPGP_PINGPONG_SECS,\n\tLWJPGP_TIMEOUT_SECS,\n\tLWJPGP_REJECT_SERVICE_KEYWORDS_NAME,\n\tLWJPGP_REJECT_SERVICE_KEYWORDS,\n\tLWJPGP_DEFAULT_ALPN,\n};\n\nstatic const char * const paths_vhosts[] = {\n\t\"vhosts[]\",\n\t\"vhosts[].mounts[]\",\n\t\"vhosts[].name\",\n\t\"vhosts[].port\",\n\t\"vhosts[].interface\",\n\t\"vhosts[].unix-socket\",\n\t\"vhosts[].sts\",\n\t\"vhosts[].host-ssl-key\",\n\t\"vhosts[].host-ssl-cert\",\n\t\"vhosts[].host-ssl-ca\",\n\t\"vhosts[].access-log\",\n\t\"vhosts[].mounts[].mountpoint\",\n\t\"vhosts[].mounts[].origin\",\n\t\"vhosts[].mounts[].protocol\",\n\t\"vhosts[].mounts[].default\",\n\t\"vhosts[].mounts[].auth-mask\",\n\t\"vhosts[].mounts[].cgi-timeout\",\n\t\"vhosts[].mounts[].cgi-env[].*\",\n\t\"vhosts[].mounts[].cache-max-age\",\n\t\"vhosts[].mounts[].cache-reuse\",\n\t\"vhosts[].mounts[].cache-revalidate\",\n\t\"vhosts[].mounts[].basic-auth\",\n\t\"vhosts[].mounts[].cache-intermediaries\",\n\t\"vhosts[].mounts[].extra-mimetypes.*\",\n\t\"vhosts[].mounts[].interpret.*\",\n\t\"vhosts[].ws-protocols[].*.*\",\n\t\"vhosts[].ws-protocols[].*\",\n\t\"vhosts[].ws-protocols[]\",\n\t\"vhosts[].keepalive_timeout\",\n\t\"vhosts[].enable-client-ssl\",\n\t\"vhosts[].ciphers\",\n\t\"vhosts[].ecdh-curve\",\n\t\"vhosts[].noipv6\",\n\t\"vhosts[].ipv6only\",\n\t\"vhosts[].ssl-option-set\",\n\t\"vhosts[].ssl-option-clear\",\n\t\"vhosts[].mounts[].pmo[].*\",\n\t\"vhosts[].headers[].*\",\n\t\"vhosts[].headers[]\",\n\t\"vhosts[].client-ssl-key\",\n\t\"vhosts[].client-ssl-cert\",\n\t\"vhosts[].client-ssl-ca\",\n\t\"vhosts[].client-ssl-ciphers\",\n\t\"vhosts[].onlyraw\",\n\t\"vhosts[].client-cert-required\",\n\t\"vhosts[].ignore-missing-cert\",\n\t\"vhosts[].error-document-404\",\n\t\"vhosts[].alpn\",\n};\n\nenum lejp_vhost_paths {\n\tLEJPVP,\n\tLEJPVP_MOUNTS,\n\tLEJPVP_NAME,\n\tLEJPVP_PORT,\n\tLEJPVP_INTERFACE,\n\tLEJPVP_UNIXSKT,\n\tLEJPVP_STS,\n\tLEJPVP_HOST_SSL_KEY,\n\tLEJPVP_HOST_SSL_CERT,\n\tLEJPVP_HOST_SSL_CA,\n\tLEJPVP_ACCESS_LOG,\n\tLEJPVP_MOUNTPOINT,\n\tLEJPVP_ORIGIN,\n\tLEJPVP_MOUNT_PROTOCOL,\n\tLEJPVP_DEFAULT,\n\tLEJPVP_DEFAULT_AUTH_MASK,\n\tLEJPVP_CGI_TIMEOUT,\n\tLEJPVP_CGI_ENV,\n\tLEJPVP_MOUNT_CACHE_MAX_AGE,\n\tLEJPVP_MOUNT_CACHE_REUSE,\n\tLEJPVP_MOUNT_CACHE_REVALIDATE,\n\tLEJPVP_MOUNT_BASIC_AUTH,\n\tLEJPVP_MOUNT_CACHE_INTERMEDIARIES,\n\tLEJPVP_MOUNT_EXTRA_MIMETYPES,\n\tLEJPVP_MOUNT_INTERPRET,\n\tLEJPVP_PROTOCOL_NAME_OPT,\n\tLEJPVP_PROTOCOL_NAME,\n\tLEJPVP_PROTOCOL,\n\tLEJPVP_KEEPALIVE_TIMEOUT,\n\tLEJPVP_ENABLE_CLIENT_SSL,\n\tLEJPVP_CIPHERS,\n\tLEJPVP_ECDH_CURVE,\n\tLEJPVP_NOIPV6,\n\tLEJPVP_IPV6ONLY,\n\tLEJPVP_SSL_OPTION_SET,\n\tLEJPVP_SSL_OPTION_CLEAR,\n\tLEJPVP_PMO,\n\tLEJPVP_HEADERS_NAME,\n\tLEJPVP_HEADERS,\n\tLEJPVP_CLIENT_SSL_KEY,\n\tLEJPVP_CLIENT_SSL_CERT,\n\tLEJPVP_CLIENT_SSL_CA,\n\tLEJPVP_CLIENT_CIPHERS,\n\tLEJPVP_FLAG_ONLYRAW,\n\tLEJPVP_FLAG_CLIENT_CERT_REQUIRED,\n\tLEJPVP_IGNORE_MISSING_CERT,\n\tLEJPVP_ERROR_DOCUMENT_404,\n\tLEJPVP_ALPN,\n};\n\nstatic const char * const parser_errs[] = {\n\t\"\",\n\t\"\",\n\t\"No opening '{'\",\n\t\"Expected closing '}'\",\n\t\"Expected '\\\"'\",\n\t\"String underrun\",\n\t\"Illegal unescaped control char\",\n\t\"Illegal escape format\",\n\t\"Illegal hex number\",\n\t\"Expected ':'\",\n\t\"Illegal value start\",\n\t\"Digit required after decimal point\",\n\t\"Bad number format\",\n\t\"Bad exponent format\",\n\t\"Unknown token\",\n\t\"Too many ']'\",\n\t\"Mismatched ']'\",\n\t\"Expected ']'\",\n\t\"JSON nesting limit exceeded\",\n\t\"Nesting tracking used up\",\n\t\"Number too long\",\n\t\"Comma or block end expected\",\n\t\"Unknown\",\n\t\"Parser callback errored (see earlier error)\",\n};\n\n#define MAX_PLUGIN_DIRS 10\n\nstruct jpargs {\n\tstruct lws_context_creation_info *info;\n\tstruct lws_context *context;\n\tconst struct lws_protocols *protocols;\n\tconst struct lws_extension *extensions;\n\tchar *p, *end, valid;\n\tstruct lws_http_mount *head, *last;\n\n\tstruct lws_protocol_vhost_options *pvo;\n\tstruct lws_protocol_vhost_options *pvo_em;\n\tstruct lws_protocol_vhost_options *pvo_int;\n\tstruct lws_http_mount m;\n\tconst char **plugin_dirs;\n\tint count_plugin_dirs;\n\n\tunsigned int enable_client_ssl:1;\n\tunsigned int fresh_mount:1;\n\tunsigned int any_vhosts:1;\n\tunsigned int chunk:1;\n};\n\nstatic void *\nlwsws_align(struct jpargs *a)\n{\n\tif ((lws_intptr_t)(a->p) & 15)\n\t\ta->p += 16 - ((lws_intptr_t)(a->p) & 15);\n\n\ta->chunk = 0;\n\n\treturn a->p;\n}\n\nstatic int\narg_to_bool(const char *s)\n{\n\tstatic const char * const on[] = { \"on\", \"yes\", \"true\" };\n\tint n = atoi(s);\n\n\tif (n)\n\t\treturn 1;\n\n\tfor (n = 0; n < (int)LWS_ARRAY_SIZE(on); n++)\n\t\tif (!strcasecmp(s, on[n]))\n\t\t\treturn 1;\n\n\treturn 0;\n}\n\nstatic signed char\nlejp_globals_cb(struct lejp_ctx *ctx, char reason)\n{\n\tstruct jpargs *a = (struct jpargs *)ctx->user;\n\tstruct lws_protocol_vhost_options *rej;\n\tint n;\n\n\t/* we only match on the prepared path strings */\n\tif (!(reason & LEJP_FLAG_CB_IS_VALUE) || !ctx->path_match)\n\t\treturn 0;\n\n\t/* this catches, eg, vhosts[].headers[].xxx */\n\tif (reason == LEJPCB_VAL_STR_END &&\n\t    ctx->path_match == LWJPGP_REJECT_SERVICE_KEYWORDS_NAME + 1) {\n\t\trej = lwsws_align(a);\n\t\ta->p += sizeof(*rej);\n\n\t\tn = lejp_get_wildcard(ctx, 0, a->p, a->end - a->p);\n\t\trej->next = a->info->reject_service_keywords;\n\t\ta->info->reject_service_keywords = rej;\n\t\trej->name = a->p;\n\t\t lwsl_notice(\"  adding rej %s=%s\\n\", a->p, ctx->buf);\n\t\ta->p += n - 1;\n\t\t*(a->p++) = '\\0';\n\t\trej->value = a->p;\n\t\trej->options = NULL;\n\t\tgoto dostring;\n\t}\n\n\tswitch (ctx->path_match - 1) {\n\tcase LEJPGP_UID:\n\t\ta->info->uid = atoi(ctx->buf);\n\t\treturn 0;\n\tcase LEJPGP_GID:\n\t\ta->info->gid = atoi(ctx->buf);\n\t\treturn 0;\n\tcase LEJPGP_COUNT_THREADS:\n\t\ta->info->count_threads = atoi(ctx->buf);\n\t\treturn 0;\n\tcase LWJPGP_INIT_SSL:\n\t\tif (arg_to_bool(ctx->buf))\n\t\t\ta->info->options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;\n\t\treturn 0;\n\tcase LEJPGP_SERVER_STRING:\n\t\ta->info->server_string = a->p;\n\t\tbreak;\n\tcase LEJPGP_PLUGIN_DIR:\n\t\tif (a->count_plugin_dirs == MAX_PLUGIN_DIRS - 1) {\n\t\t\tlwsl_err(\"Too many plugin dirs\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\ta->plugin_dirs[a->count_plugin_dirs++] = a->p;\n\t\tbreak;\n\n\tcase LWJPGP_PINGPONG_SECS:\n\t\ta->info->ws_ping_pong_interval = atoi(ctx->buf);\n\t\treturn 0;\n\n\tcase LWJPGP_TIMEOUT_SECS:\n\t\ta->info->timeout_secs = atoi(ctx->buf);\n\t\treturn 0;\n\n\tcase LWJPGP_DEFAULT_ALPN:\n\t\ta->info->alpn = a->p;\n\t\tbreak;\n\n\tdefault:\n\t\treturn 0;\n\t}\n\ndostring:\n\ta->p += lws_snprintf(a->p, a->end - a->p, \"%s\", ctx->buf);\n\t*(a->p)++ = '\\0';\n\n\treturn 0;\n}\n\nstatic signed char\nlejp_vhosts_cb(struct lejp_ctx *ctx, char reason)\n{\n\tstruct jpargs *a = (struct jpargs *)ctx->user;\n\tstruct lws_protocol_vhost_options *pvo, *mp_cgienv, *headers;\n\tstruct lws_http_mount *m;\n\tchar *p, *p1;\n\tint n;\n\n#if 0\n\tlwsl_notice(\" %d: %s (%d)\\n\", reason, ctx->path, ctx->path_match);\n\tfor (n = 0; n < ctx->wildcount; n++)\n\t\tlwsl_notice(\"    %d\\n\", ctx->wild[n]);\n#endif\n\n\tif (reason == LEJPCB_OBJECT_START && ctx->path_match == LEJPVP + 1) {\n\t\tuint32_t i[4];\n\t\tconst char *ss;\n\n\t\t/* set the defaults for this vhost */\n\t\ta->valid = 1;\n\t\ta->head = NULL;\n\t\ta->last = NULL;\n\n\t\ti[0] = a->info->count_threads;\n\t\ti[1] = a->info->options & (\n\t\t\tLWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME |\n\t\t\tLWS_SERVER_OPTION_LIBUV |\n\t\t\tLWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT |\n\t\t\tLWS_SERVER_OPTION_EXPLICIT_VHOSTS |\n\t\t\tLWS_SERVER_OPTION_UV_NO_SIGSEGV_SIGFPE_SPIN |\n\t\t\tLWS_SERVER_OPTION_LIBEVENT |\n\t\t\tLWS_SERVER_OPTION_LIBEV\n\t\t\t\t);\n\t\tss = a->info->server_string;\n\t\ti[2] = a->info->ws_ping_pong_interval;\n\t\ti[3] = a->info->timeout_secs;\n\n\t\tmemset(a->info, 0, sizeof(*a->info));\n\n\t\ta->info->count_threads = i[0];\n\t\ta->info->options = i[1];\n\t\ta->info->server_string = ss;\n\t\ta->info->ws_ping_pong_interval = i[2];\n\t\ta->info->timeout_secs = i[3];\n\n\t\ta->info->protocols = a->protocols;\n\t\ta->info->extensions = a->extensions;\n#if defined(LWS_WITH_TLS)\n\t\ta->info->client_ssl_cipher_list = \"ECDHE-ECDSA-AES256-GCM-SHA384:\"\n\t\t\t\"ECDHE-RSA-AES256-GCM-SHA384:\"\n\t\t\t\"DHE-RSA-AES256-GCM-SHA384:\"\n\t\t\t\"ECDHE-RSA-AES256-SHA384:\"\n\t\t\t\"HIGH:!aNULL:!eNULL:!EXPORT:\"\n\t\t\t\"!DES:!MD5:!PSK:!RC4:!HMAC_SHA1:\"\n\t\t\t\"!SHA1:!DHE-RSA-AES128-GCM-SHA256:\"\n\t\t\t\"!DHE-RSA-AES128-SHA256:\"\n\t\t\t\"!AES128-GCM-SHA256:\"\n\t\t\t\"!AES128-SHA256:\"\n\t\t\t\"!DHE-RSA-AES256-SHA256:\"\n\t\t\t\"!AES256-GCM-SHA384:\"\n\t\t\t\"!AES256-SHA256\";\n#endif\n\t\ta->info->ssl_cipher_list = \"ECDHE-ECDSA-AES256-GCM-SHA384:\"\n\t\t\t\t       \"ECDHE-RSA-AES256-GCM-SHA384:\"\n\t\t\t\t       \"DHE-RSA-AES256-GCM-SHA384:\"\n\t\t\t\t       \"ECDHE-RSA-AES256-SHA384:\"\n\t\t\t\t       \"HIGH:!aNULL:!eNULL:!EXPORT:\"\n\t\t\t\t       \"!DES:!MD5:!PSK:!RC4:!HMAC_SHA1:\"\n\t\t\t\t       \"!SHA1:!DHE-RSA-AES128-GCM-SHA256:\"\n\t\t\t\t       \"!DHE-RSA-AES128-SHA256:\"\n\t\t\t\t       \"!AES128-GCM-SHA256:\"\n\t\t\t\t       \"!AES128-SHA256:\"\n\t\t\t\t       \"!DHE-RSA-AES256-SHA256:\"\n\t\t\t\t       \"!AES256-GCM-SHA384:\"\n\t\t\t\t       \"!AES256-SHA256\";\n\t\ta->info->keepalive_timeout = 5;\n\t}\n\n\tif (reason == LEJPCB_OBJECT_START &&\n\t    ctx->path_match == LEJPVP_MOUNTS + 1) {\n\t\ta->fresh_mount = 1;\n\t\tmemset(&a->m, 0, sizeof(a->m));\n\t}\n\n\t/* this catches, eg, vhosts[].ws-protocols[].xxx-protocol */\n\tif (reason == LEJPCB_OBJECT_START &&\n\t    ctx->path_match == LEJPVP_PROTOCOL_NAME + 1) {\n\t\ta->pvo = lwsws_align(a);\n\t\ta->p += sizeof(*a->pvo);\n\n\t\tn = lejp_get_wildcard(ctx, 0, a->p, a->end - a->p);\n\t\t/* ie, enable this protocol, no options yet */\n\t\ta->pvo->next = a->info->pvo;\n\t\ta->info->pvo = a->pvo;\n\t\ta->pvo->name = a->p;\n\t\tlwsl_info(\"  adding protocol %s\\n\", a->p);\n\t\ta->p += n;\n\t\ta->pvo->value = a->p;\n\t\ta->pvo->options = NULL;\n\t\tgoto dostring;\n\t}\n\n\t/* this catches, eg, vhosts[].headers[].xxx */\n\tif ((reason == LEJPCB_VAL_STR_END || reason == LEJPCB_VAL_STR_CHUNK) &&\n\t    ctx->path_match == LEJPVP_HEADERS_NAME + 1) {\n\t\tif (!a->chunk) {\n\t\t\theaders = lwsws_align(a);\n\t\t\ta->p += sizeof(*headers);\n\n\t\t\tn = lejp_get_wildcard(ctx, 0, a->p,\n\t\t\t\t\tlws_ptr_diff(a->end, a->p));\n\t\t\t/* ie, add this header */\n\t\t\theaders->next = a->info->headers;\n\t\t\ta->info->headers = headers;\n\t\t\theaders->name = a->p;\n\n\t\t\tlwsl_notice(\"  adding header %s=%s\\n\", a->p, ctx->buf);\n\t\t\ta->p += n - 1;\n\t\t\t*(a->p++) = ':';\n\t\t\tif (a->p < a->end)\n\t\t\t\t*(a->p++) = '\\0';\n\t\t\telse\n\t\t\t\t*(a->p - 1) = '\\0';\n\t\t\theaders->value = a->p;\n\t\t\theaders->options = NULL;\n\t\t}\n\t\ta->chunk = reason == LEJPCB_VAL_STR_CHUNK;\n\t\tgoto dostring;\n\t}\n\n\tif (reason == LEJPCB_OBJECT_END &&\n\t    (ctx->path_match == LEJPVP + 1 || !ctx->path[0]) &&\n\t    a->valid) {\n\n\t\tstruct lws_vhost *vhost;\n\n\t\t//lwsl_notice(\"%s\\n\", ctx->path);\n\t\tif (!a->info->port) {\n\t\t\tlwsl_err(\"Port required (eg, 443)\");\n\t\t\treturn 1;\n\t\t}\n\t\ta->valid = 0;\n\t\ta->info->mounts = a->head;\n\n\t\tvhost = lws_create_vhost(a->context, a->info);\n\t\tif (!vhost) {\n\t\t\tlwsl_err(\"Failed to create vhost %s\\n\",\n\t\t\t\t a->info->vhost_name);\n\t\t\treturn 1;\n\t\t}\n\t\ta->any_vhosts = 1;\n\n#if defined(LWS_WITH_TLS)\n\t\tif (a->enable_client_ssl) {\n\t\t\tconst char *cert_filepath = a->info->client_ssl_cert_filepath;\n\t\t\tconst char *private_key_filepath = a->info->client_ssl_private_key_filepath;\n\t\t\tconst char *ca_filepath = a->info->client_ssl_ca_filepath;\n\t\t\tconst char *cipher_list = a->info->client_ssl_cipher_list;\n\t\t\tmemset(a->info, 0, sizeof(*a->info));\n\t\t\ta->info->client_ssl_cert_filepath = cert_filepath;\n\t\t\ta->info->client_ssl_private_key_filepath = private_key_filepath;\n\t\t\ta->info->client_ssl_ca_filepath = ca_filepath;\n\t\t\ta->info->client_ssl_cipher_list = cipher_list;\n\t\t\ta->info->options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;\n\t\t\tlws_init_vhost_client_ssl(a->info, vhost);\n\t\t}\n#endif\n\n\t\treturn 0;\n\t}\n\n\tif (reason == LEJPCB_OBJECT_END &&\n\t    ctx->path_match == LEJPVP_MOUNTS + 1) {\n\t\tstatic const char * const mount_protocols[] = {\n\t\t\t\"http://\",\n\t\t\t\"https://\",\n\t\t\t\"file://\",\n\t\t\t\"cgi://\",\n\t\t\t\">http://\",\n\t\t\t\">https://\",\n\t\t\t\"callback://\",\n\t\t\t\"gzip://\",\n\t\t};\n\n\t\tif (!a->fresh_mount)\n\t\t\treturn 0;\n\n\t\tif (!a->m.mountpoint || !a->m.origin) {\n\t\t\tlwsl_err(\"mountpoint and origin required\\n\");\n\t\t\treturn 1;\n\t\t}\n\t\tlwsl_debug(\"adding mount %s\\n\", a->m.mountpoint);\n\t\tm = lwsws_align(a);\n\t\tmemcpy(m, &a->m, sizeof(*m));\n\t\tif (a->last)\n\t\t\ta->last->mount_next = m;\n\n\t\tfor (n = 0; n < (int)LWS_ARRAY_SIZE(mount_protocols); n++)\n\t\t\tif (!strncmp(a->m.origin, mount_protocols[n],\n\t\t\t     strlen(mount_protocols[n]))) {\n\t\t\t\tlwsl_info(\"----%s\\n\", a->m.origin);\n\t\t\t\tm->origin_protocol = n;\n\t\t\t\tm->origin = a->m.origin +\n\t\t\t\t\t    strlen(mount_protocols[n]);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tif (n == (int)LWS_ARRAY_SIZE(mount_protocols)) {\n\t\t\tlwsl_err(\"unsupported protocol:// %s\\n\", a->m.origin);\n\t\t\treturn 1;\n\t\t}\n\n\t\ta->p += sizeof(*m);\n\t\tif (!a->head)\n\t\t\ta->head = m;\n\n\t\ta->last = m;\n\t\ta->fresh_mount = 0;\n\t}\n\n\t/* we only match on the prepared path strings */\n\tif (!(reason & LEJP_FLAG_CB_IS_VALUE) || !ctx->path_match)\n\t\treturn 0;\n\n\tswitch (ctx->path_match - 1) {\n\tcase LEJPVP_NAME:\n\t\ta->info->vhost_name = a->p;\n\t\tbreak;\n\tcase LEJPVP_PORT:\n\t\ta->info->port = atoi(ctx->buf);\n\t\treturn 0;\n\tcase LEJPVP_INTERFACE:\n\t\ta->info->iface = a->p;\n\t\tbreak;\n\tcase LEJPVP_UNIXSKT:\n\t\tif (arg_to_bool(ctx->buf))\n\t\t\ta->info->options |= LWS_SERVER_OPTION_UNIX_SOCK;\n\t\telse\n\t\t\ta->info->options &= ~(LWS_SERVER_OPTION_UNIX_SOCK);\n\t\treturn 0;\n\tcase LEJPVP_STS:\n\t\tif (arg_to_bool(ctx->buf))\n\t\t\ta->info->options |= LWS_SERVER_OPTION_STS;\n\t\telse\n\t\t\ta->info->options &= ~(LWS_SERVER_OPTION_STS);\n\t\treturn 0;\n\tcase LEJPVP_HOST_SSL_KEY:\n\t\ta->info->ssl_private_key_filepath = a->p;\n\t\tbreak;\n\tcase LEJPVP_HOST_SSL_CERT:\n\t\ta->info->ssl_cert_filepath = a->p;\n\t\tbreak;\n\tcase LEJPVP_HOST_SSL_CA:\n\t\ta->info->ssl_ca_filepath = a->p;\n\t\tbreak;\n\tcase LEJPVP_ACCESS_LOG:\n\t\ta->info->log_filepath = a->p;\n\t\tbreak;\n\tcase LEJPVP_MOUNTPOINT:\n\t\ta->m.mountpoint = a->p;\n\t\ta->m.mountpoint_len = (unsigned char)strlen(ctx->buf);\n\t\tbreak;\n\tcase LEJPVP_ORIGIN:\n\t\tif (!strncmp(ctx->buf, \"callback://\", 11))\n\t\t\ta->m.protocol = a->p + 11;\n\n\t\tif (!a->m.origin)\n\t\t\ta->m.origin = a->p;\n\t\tbreak;\n\tcase LEJPVP_DEFAULT:\n\t\ta->m.def = a->p;\n\t\tbreak;\n\tcase LEJPVP_DEFAULT_AUTH_MASK:\n\t\ta->m.auth_mask = atoi(ctx->buf);\n\t\treturn 0;\n\tcase LEJPVP_MOUNT_CACHE_MAX_AGE:\n\t\ta->m.cache_max_age = atoi(ctx->buf);\n\t\treturn 0;\n\tcase LEJPVP_MOUNT_CACHE_REUSE:\n\t\ta->m.cache_reusable = arg_to_bool(ctx->buf);\n\t\treturn 0;\n\tcase LEJPVP_MOUNT_CACHE_REVALIDATE:\n\t\ta->m.cache_revalidate = arg_to_bool(ctx->buf);\n\t\treturn 0;\n\tcase LEJPVP_MOUNT_CACHE_INTERMEDIARIES:\n\t\ta->m.cache_intermediaries = arg_to_bool(ctx->buf);;\n\t\treturn 0;\n\tcase LEJPVP_MOUNT_BASIC_AUTH:\n\t\ta->m.basic_auth_login_file = a->p;\n\t\tbreak;\n\tcase LEJPVP_CGI_TIMEOUT:\n\t\ta->m.cgi_timeout = atoi(ctx->buf);\n\t\treturn 0;\n\tcase LEJPVP_KEEPALIVE_TIMEOUT:\n\t\ta->info->keepalive_timeout = atoi(ctx->buf);\n\t\treturn 0;\n#if defined(LWS_WITH_TLS)\n\tcase LEJPVP_CLIENT_CIPHERS:\n\t\ta->info->client_ssl_cipher_list = a->p;\n\t\tbreak;\n#endif\n\tcase LEJPVP_CIPHERS:\n\t\ta->info->ssl_cipher_list = a->p;\n\t\tbreak;\n\tcase LEJPVP_ECDH_CURVE:\n\t\ta->info->ecdh_curve = a->p;\n\t\tbreak;\n\tcase LEJPVP_PMO:\n\tcase LEJPVP_CGI_ENV:\n\t\tmp_cgienv = lwsws_align(a);\n\t\ta->p += sizeof(*a->m.cgienv);\n\n\t\tmp_cgienv->next = a->m.cgienv;\n\t\ta->m.cgienv = mp_cgienv;\n\n\t\tn = lejp_get_wildcard(ctx, 0, a->p, a->end - a->p);\n\t\tmp_cgienv->name = a->p;\n\t\ta->p += n;\n\t\tmp_cgienv->value = a->p;\n\t\tmp_cgienv->options = NULL;\n\t\t//lwsl_notice(\"    adding pmo / cgi-env '%s' = '%s'\\n\", mp_cgienv->name,\n\t\t//\t\tmp_cgienv->value);\n\t\tgoto dostring;\n\n\tcase LEJPVP_PROTOCOL_NAME_OPT:\n\t\t/* this catches, eg,\n\t\t * vhosts[].ws-protocols[].xxx-protocol.yyy-option\n\t\t * ie, these are options attached to a protocol with { }\n\t\t */\n\t\tpvo = lwsws_align(a);\n\t\ta->p += sizeof(*a->pvo);\n\n\t\tn = lejp_get_wildcard(ctx, 1, a->p, a->end - a->p);\n\t\t/* ie, enable this protocol, no options yet */\n\t\tpvo->next = a->pvo->options;\n\t\ta->pvo->options = pvo;\n\t\tpvo->name = a->p;\n\t\ta->p += n;\n\t\tpvo->value = a->p;\n\t\tpvo->options = NULL;\n\t\tbreak;\n\n\tcase LEJPVP_MOUNT_EXTRA_MIMETYPES:\n\t\ta->pvo_em = lwsws_align(a);\n\t\ta->p += sizeof(*a->pvo_em);\n\n\t\tn = lejp_get_wildcard(ctx, 0, a->p, a->end - a->p);\n\t\t/* ie, enable this protocol, no options yet */\n\t\ta->pvo_em->next = a->m.extra_mimetypes;\n\t\ta->m.extra_mimetypes = a->pvo_em;\n\t\ta->pvo_em->name = a->p;\n\t\tlwsl_notice(\"  adding extra-mimetypes %s -> %s\\n\", a->p, ctx->buf);\n\t\ta->p += n;\n\t\ta->pvo_em->value = a->p;\n\t\ta->pvo_em->options = NULL;\n\t\tbreak;\n\n\tcase LEJPVP_MOUNT_INTERPRET:\n\t\ta->pvo_int = lwsws_align(a);\n\t\ta->p += sizeof(*a->pvo_int);\n\n\t\tn = lejp_get_wildcard(ctx, 0, a->p, a->end - a->p);\n\t\t/* ie, enable this protocol, no options yet */\n\t\ta->pvo_int->next = a->m.interpret;\n\t\ta->m.interpret = a->pvo_int;\n\t\ta->pvo_int->name = a->p;\n\t\tlwsl_notice(\"  adding interpret %s -> %s\\n\", a->p,\n\t\t\t    ctx->buf);\n\t\ta->p += n;\n\t\ta->pvo_int->value = a->p;\n\t\ta->pvo_int->options = NULL;\n\t\tbreak;\n\n\tcase LEJPVP_ENABLE_CLIENT_SSL:\n\t\ta->enable_client_ssl = arg_to_bool(ctx->buf);\n\t\treturn 0;\n#if defined(LWS_WITH_TLS)\n\tcase LEJPVP_CLIENT_SSL_KEY:\n\t\ta->info->client_ssl_private_key_filepath = a->p;\n\t\tbreak;\n\tcase LEJPVP_CLIENT_SSL_CERT:\n\t\ta->info->client_ssl_cert_filepath = a->p;\n\t\tbreak;\n\tcase LEJPVP_CLIENT_SSL_CA:\n\t\ta->info->client_ssl_ca_filepath = a->p;\n\t\tbreak;\n#endif\n\n\tcase LEJPVP_NOIPV6:\n\t\tif (arg_to_bool(ctx->buf))\n\t\t\ta->info->options |= LWS_SERVER_OPTION_DISABLE_IPV6;\n\t\telse\n\t\t\ta->info->options &= ~(LWS_SERVER_OPTION_DISABLE_IPV6);\n\t\treturn 0;\n\n\tcase LEJPVP_FLAG_ONLYRAW:\n\t\tif (arg_to_bool(ctx->buf))\n\t\t\ta->info->options |= LWS_SERVER_OPTION_ONLY_RAW;\n\t\telse\n\t\t\ta->info->options &= ~(LWS_SERVER_OPTION_ONLY_RAW);\n\t\treturn 0;\n\n\tcase LEJPVP_IPV6ONLY:\n\t\ta->info->options |= LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY;\n\t\tif (arg_to_bool(ctx->buf))\n\t\t\ta->info->options |= LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE;\n\t\telse\n\t\t\ta->info->options &= ~(LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE);\n\t\treturn 0;\n\n\tcase LEJPVP_FLAG_CLIENT_CERT_REQUIRED:\n\t\tif (arg_to_bool(ctx->buf))\n\t\t\ta->info->options |=\n\t\t\t    LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT;\n\t\treturn 0;\n\n\tcase LEJPVP_IGNORE_MISSING_CERT:\n\t\tif (arg_to_bool(ctx->buf))\n\t\t\ta->info->options |= LWS_SERVER_OPTION_IGNORE_MISSING_CERT;\n\t\telse\n\t\t\ta->info->options &= ~(LWS_SERVER_OPTION_IGNORE_MISSING_CERT);\n\n\t\treturn 0;\n\n\tcase LEJPVP_ERROR_DOCUMENT_404:\n\t\ta->info->error_document_404 = a->p;\n\t\tbreak;\n\n\tcase LEJPVP_SSL_OPTION_SET:\n\t\ta->info->ssl_options_set |= atol(ctx->buf);\n\t\treturn 0;\n\tcase LEJPVP_SSL_OPTION_CLEAR:\n\t\ta->info->ssl_options_clear |= atol(ctx->buf);\n\t\treturn 0;\n\n\tcase LEJPVP_ALPN:\n\t\ta->info->alpn = a->p;\n\t\tbreak;\n\n\tdefault:\n\t\treturn 0;\n\t}\n\ndostring:\n\tp = ctx->buf;\n\tp[LEJP_STRING_CHUNK] = '\\0';\n\tp1 = strstr(p, ESC_INSTALL_DATADIR);\n\tif (p1) {\n\t\tn = p1 - p;\n\t\tif (n > a->end - a->p)\n\t\t\tn = a->end - a->p;\n\t\tlws_strncpy(a->p, p, n + 1);\n\t\ta->p += n;\n\t\ta->p += lws_snprintf(a->p, a->end - a->p, \"%s\", LWS_INSTALL_DATADIR);\n\t\tp += n + strlen(ESC_INSTALL_DATADIR);\n\t}\n\n\ta->p += lws_snprintf(a->p, a->end - a->p, \"%s\", p);\n\tif (reason == LEJPCB_VAL_STR_END)\n\t\t*(a->p)++ = '\\0';\n\n\treturn 0;\n}\n\n/*\n * returns 0 = OK, 1 = can't open, 2 = parsing error\n */\n\nstatic int\nlwsws_get_config(void *user, const char *f, const char * const *paths,\n\t\t int count_paths, lejp_callback cb)\n{\n\tunsigned char buf[128];\n\tstruct lejp_ctx ctx;\n\tint n, m, fd;\n\n\tfd = lws_open(f, O_RDONLY);\n\tif (fd < 0) {\n\t\tlwsl_err(\"Cannot open %s\\n\", f);\n\t\treturn 2;\n\t}\n\tlwsl_info(\"%s: %s\\n\", __func__, f);\n\tlejp_construct(&ctx, cb, user, paths, count_paths);\n\n\tdo {\n\t\tn = read(fd, buf, sizeof(buf));\n\t\tif (!n)\n\t\t\tbreak;\n\n\t\tm = (int)(signed char)lejp_parse(&ctx, buf, n);\n\t} while (m == LEJP_CONTINUE);\n\n\tclose(fd);\n\tn = ctx.line;\n\tlejp_destruct(&ctx);\n\n\tif (m < 0) {\n\t\tlwsl_err(\"%s(%u): parsing error %d: %s\\n\", f, n, m,\n\t\t\t parser_errs[-m]);\n\t\treturn 2;\n\t}\n\n\treturn 0;\n}\n\n#if defined(LWS_WITH_LIBUV) && UV_VERSION_MAJOR > 0\n\nstatic int\nlwsws_get_config_d(void *user, const char *d, const char * const *paths,\n\t\t   int count_paths, lejp_callback cb)\n{\n\tuv_dirent_t dent;\n\tuv_fs_t req;\n\tchar path[256];\n\tint ret = 0, ir;\n\tuv_loop_t loop;\n\n\tir = uv_loop_init(&loop);\n\tif (ir) {\n\t\tlwsl_err(\"%s: loop init failed %d\\n\", __func__, ir);\n\t}\n\n\tif (!uv_fs_scandir(&loop, &req, d, 0, NULL)) {\n\t\tlwsl_err(\"Scandir on %s failed\\n\", d);\n\t\treturn 2;\n\t}\n\n\twhile (uv_fs_scandir_next(&req, &dent) != UV_EOF) {\n\t\tlws_snprintf(path, sizeof(path) - 1, \"%s/%s\", d, dent.name);\n\t\tret = lwsws_get_config(user, path, paths, count_paths, cb);\n\t\tif (ret)\n\t\t\tgoto bail;\n\t}\n\nbail:\n\tuv_fs_req_cleanup(&req);\n\twhile (uv_loop_close(&loop))\n\t\t;\n\n\treturn ret;\n}\n\n#else\n\n#ifndef _WIN32\nstatic int filter(const struct dirent *ent)\n{\n\tif (!strcmp(ent->d_name, \".\") || !strcmp(ent->d_name, \"..\"))\n\t\treturn 0;\n\n\treturn 1;\n}\n#endif\n\nstatic int\nlwsws_get_config_d(void *user, const char *d, const char * const *paths,\n\t\t   int count_paths, lejp_callback cb)\n{\n#ifndef _WIN32\n\tstruct dirent **namelist;\n\tchar path[256];\n\tint n, i, ret = 0;\n\n\tn = scandir(d, &namelist, filter, alphasort);\n\tif (n < 0) {\n\t\tlwsl_err(\"Scandir on %s failed\\n\", d);\n\t\treturn 1;\n\t}\n\n\tfor (i = 0; i < n; i++) {\n\t\tif (strchr(namelist[i]->d_name, '~'))\n\t\t\tgoto skip;\n\t\tlws_snprintf(path, sizeof(path) - 1, \"%s/%s\", d,\n\t\t\t namelist[i]->d_name);\n\t\tret = lwsws_get_config(user, path, paths, count_paths, cb);\n\t\tif (ret) {\n\t\t\twhile (i++ < n)\n\t\t\t\tfree(namelist[i]);\n\t\t\tgoto bail;\n\t\t}\nskip:\n\t\tfree(namelist[i]);\n\t}\n\nbail:\n\tfree(namelist);\n\n\treturn ret;\n#else\n\treturn 0;\n#endif\n}\n\n#endif\n\nint\nlwsws_get_config_globals(struct lws_context_creation_info *info, const char *d,\n\t\t\t char **cs, int *len)\n{\n\tstruct jpargs a;\n\tconst char * const *old = info->plugin_dirs;\n\tchar dd[128];\n\n\tmemset(&a, 0, sizeof(a));\n\n\ta.info = info;\n\ta.p = *cs;\n\ta.end = (a.p + *len) - 1;\n\ta.valid = 0;\n\n\tlwsws_align(&a);\n\tinfo->plugin_dirs = (void *)a.p;\n\ta.plugin_dirs = (void *)a.p; /* writeable version */\n\ta.p += MAX_PLUGIN_DIRS * sizeof(void *);\n\n\t/* copy any default paths */\n\n\twhile (old && *old) {\n\t\ta.plugin_dirs[a.count_plugin_dirs++] = *old;\n\t\told++;\n\t}\n\n\tlws_snprintf(dd, sizeof(dd) - 1, \"%s/conf\", d);\n\tif (lwsws_get_config(&a, dd, paths_global,\n\t\t\t     LWS_ARRAY_SIZE(paths_global), lejp_globals_cb) > 1)\n\t\treturn 1;\n\tlws_snprintf(dd, sizeof(dd) - 1, \"%s/conf.d\", d);\n\tif (lwsws_get_config_d(&a, dd, paths_global,\n\t\t\t       LWS_ARRAY_SIZE(paths_global), lejp_globals_cb) > 1)\n\t\treturn 1;\n\n\ta.plugin_dirs[a.count_plugin_dirs] = NULL;\n\n\t*cs = a.p;\n\t*len = a.end - a.p;\n\n\treturn 0;\n}\n\nint\nlwsws_get_config_vhosts(struct lws_context *context,\n\t\t\tstruct lws_context_creation_info *info, const char *d,\n\t\t\tchar **cs, int *len)\n{\n\tstruct jpargs a;\n\tchar dd[128];\n\n\tmemset(&a, 0, sizeof(a));\n\n\ta.info = info;\n\ta.p = *cs;\n\ta.end = a.p + *len;\n\ta.valid = 0;\n\ta.context = context;\n\ta.protocols = info->protocols;\n\ta.extensions = info->extensions;\n\n\tlws_snprintf(dd, sizeof(dd) - 1, \"%s/conf\", d);\n\tif (lwsws_get_config(&a, dd, paths_vhosts,\n\t\t\t     LWS_ARRAY_SIZE(paths_vhosts), lejp_vhosts_cb) > 1)\n\t\treturn 1;\n\tlws_snprintf(dd, sizeof(dd) - 1, \"%s/conf.d\", d);\n\tif (lwsws_get_config_d(&a, dd, paths_vhosts,\n\t\t\t       LWS_ARRAY_SIZE(paths_vhosts), lejp_vhosts_cb) > 1)\n\t\treturn 1;\n\n\t*cs = a.p;\n\t*len = a.end - a.p;\n\n\tif (!a.any_vhosts) {\n\t\tlwsl_err(\"Need at least one vhost\\n\");\n\t\treturn 1;\n\t}\n\n//\tlws_finalize_startup(context);\n\n\treturn 0;\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/http/server/parsers.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n\nstatic const unsigned char lextable[] = {\n\t#include \"../lextable.h\"\n};\n\n#define FAIL_CHAR 0x08\n\nstatic struct allocated_headers *\n_lws_create_ah(struct lws_context_per_thread *pt, ah_data_idx_t data_size)\n{\n\tstruct allocated_headers *ah = lws_zalloc(sizeof(*ah), \"ah struct\");\n\n\tif (!ah)\n\t\treturn NULL;\n\n\tah->data = lws_malloc(data_size, \"ah data\");\n\tif (!ah->data) {\n\t\tlws_free(ah);\n\n\t\treturn NULL;\n\t}\n\tah->next = pt->http.ah_list;\n\tpt->http.ah_list = ah;\n\tah->data_length = data_size;\n\tpt->http.ah_pool_length++;\n\n\tlwsl_info(\"%s: created ah %p (size %d): pool length %d\\n\", __func__,\n\t\t    ah, (int)data_size, pt->http.ah_pool_length);\n\n\treturn ah;\n}\n\nint\n_lws_destroy_ah(struct lws_context_per_thread *pt, struct allocated_headers *ah)\n{\n\tlws_start_foreach_llp(struct allocated_headers **, a, pt->http.ah_list) {\n\t\tif ((*a) == ah) {\n\t\t\t*a = ah->next;\n\t\t\tpt->http.ah_pool_length--;\n\t\t\tlwsl_info(\"%s: freed ah %p : pool length %d\\n\",\n\t\t\t\t    __func__, ah, pt->http.ah_pool_length);\n\t\t\tif (ah->data)\n\t\t\t\tlws_free(ah->data);\n\t\t\tlws_free(ah);\n\n\t\t\treturn 0;\n\t\t}\n\t} lws_end_foreach_llp(a, next);\n\n\treturn 1;\n}\n\nvoid\n_lws_header_table_reset(struct allocated_headers *ah)\n{\n\t/* init the ah to reflect no headers or data have appeared yet */\n\tmemset(ah->frag_index, 0, sizeof(ah->frag_index));\n\tmemset(ah->frags, 0, sizeof(ah->frags));\n\tah->nfrag = 0;\n\tah->pos = 0;\n\tah->http_response = 0;\n\tah->parser_state = WSI_TOKEN_NAME_PART;\n\tah->lextable_pos = 0;\n}\n\n// doesn't scrub the ah rxbuffer by default, parent must do if needed\n\nvoid\n__lws_header_table_reset(struct lws *wsi, int autoservice)\n{\n\tstruct allocated_headers *ah = wsi->http.ah;\n\tstruct lws_context_per_thread *pt;\n\tstruct lws_pollfd *pfd;\n\n\t/* if we have the idea we're resetting 'our' ah, must be bound to one */\n\tassert(ah);\n\t/* ah also concurs with ownership */\n\tassert(ah->wsi == wsi);\n\n\t_lws_header_table_reset(ah);\n\n\t/* since we will restart the ah, our new headers are not completed */\n\twsi->hdr_parsing_completed = 0;\n\n\t/* while we hold the ah, keep a timeout on the wsi */\n\t__lws_set_timeout(wsi, PENDING_TIMEOUT_HOLDING_AH,\n\t\t\twsi->vhost->timeout_secs_ah_idle);\n\n\ttime(&ah->assigned);\n\n\tif (wsi->position_in_fds_table != LWS_NO_FDS_POS &&\n\t    lws_buflist_next_segment_len(&wsi->buflist, NULL) &&\n\t    autoservice) {\n\t\tlwsl_debug(\"%s: service on readbuf ah\\n\", __func__);\n\n\t\tpt = &wsi->context->pt[(int)wsi->tsi];\n\t\t/*\n\t\t * Unlike a normal connect, we have the headers already\n\t\t * (or the first part of them anyway)\n\t\t */\n\t\tpfd = &pt->fds[wsi->position_in_fds_table];\n\t\tpfd->revents |= LWS_POLLIN;\n\t\tlwsl_err(\"%s: calling service\\n\", __func__);\n\t\tlws_service_fd_tsi(wsi->context, pfd, wsi->tsi);\n\t}\n}\n\nvoid\nlws_header_table_reset(struct lws *wsi, int autoservice)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\n\tlws_pt_lock(pt, __func__);\n\n\t__lws_header_table_reset(wsi, autoservice);\n\n\tlws_pt_unlock(pt);\n}\n\nstatic void\n_lws_header_ensure_we_are_on_waiting_list(struct lws *wsi)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tstruct lws_pollargs pa;\n\tstruct lws **pwsi = &pt->http.ah_wait_list;\n\n\twhile (*pwsi) {\n\t\tif (*pwsi == wsi)\n\t\t\treturn;\n\t\tpwsi = &(*pwsi)->http.ah_wait_list;\n\t}\n\n\tlwsl_info(\"%s: wsi: %p\\n\", __func__, wsi);\n\twsi->http.ah_wait_list = pt->http.ah_wait_list;\n\tpt->http.ah_wait_list = wsi;\n\tpt->http.ah_wait_list_length++;\n\n\t/* we cannot accept input then */\n\n\t_lws_change_pollfd(wsi, LWS_POLLIN, 0, &pa);\n}\n\nstatic int\n__lws_remove_from_ah_waiting_list(struct lws *wsi)\n{\n        struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tstruct lws **pwsi =&pt->http.ah_wait_list;\n\n\twhile (*pwsi) {\n\t\tif (*pwsi == wsi) {\n\t\t\tlwsl_info(\"%s: wsi %p\\n\", __func__, wsi);\n\t\t\t/* point prev guy to our next */\n\t\t\t*pwsi = wsi->http.ah_wait_list;\n\t\t\t/* we shouldn't point anywhere now */\n\t\t\twsi->http.ah_wait_list = NULL;\n\t\t\tpt->http.ah_wait_list_length--;\n\n\t\t\treturn 1;\n\t\t}\n\t\tpwsi = &(*pwsi)->http.ah_wait_list;\n\t}\n\n\treturn 0;\n}\n\nint LWS_WARN_UNUSED_RESULT\nlws_header_table_attach(struct lws *wsi, int autoservice)\n{\n\tstruct lws_context *context = wsi->context;\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tstruct lws_pollargs pa;\n\tint n;\n\n\tlwsl_info(\"%s: wsi %p: ah %p (tsi %d, count = %d) in\\n\", __func__,\n\t\t  (void *)wsi, (void *)wsi->http.ah, wsi->tsi,\n\t\t  pt->http.ah_count_in_use);\n\n\tlws_pt_lock(pt, __func__);\n\n\t/* if we are already bound to one, just clear it down */\n\tif (wsi->http.ah) {\n\t\tlwsl_info(\"%s: cleardown\\n\", __func__);\n\t\tgoto reset;\n\t}\n\n\tn = pt->http.ah_count_in_use == context->max_http_header_pool;\n#if defined(LWS_WITH_PEER_LIMITS)\n\tif (!n) {\n\t\tn = lws_peer_confirm_ah_attach_ok(context, wsi->peer);\n\t\tif (n)\n\t\t\tlws_stats_atomic_bump(wsi->context, pt,\n\t\t\t\tLWSSTATS_C_PEER_LIMIT_AH_DENIED, 1);\n\t}\n#endif\n\tif (n) {\n\t\t/*\n\t\t * Pool is either all busy, or we don't want to give this\n\t\t * particular guy an ah right now...\n\t\t *\n\t\t * Make sure we are on the waiting list, and return that we\n\t\t * weren't able to provide the ah\n\t\t */\n\t\t_lws_header_ensure_we_are_on_waiting_list(wsi);\n\n\t\tgoto bail;\n\t}\n\n\t__lws_remove_from_ah_waiting_list(wsi);\n\n\twsi->http.ah = _lws_create_ah(pt, context->max_http_header_data);\n\tif (!wsi->http.ah) { /* we could not create an ah */\n\t\t_lws_header_ensure_we_are_on_waiting_list(wsi);\n\n\t\tgoto bail;\n\t}\n\n\twsi->http.ah->in_use = 1;\n\twsi->http.ah->wsi = wsi; /* mark our owner */\n\tpt->http.ah_count_in_use++;\n\n#if defined(LWS_WITH_PEER_LIMITS) && (defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2))\n\tlws_context_lock(context); /* <====================================== */\n\tif (wsi->peer)\n\t\twsi->peer->http.count_ah++;\n\tlws_context_unlock(context); /* ====================================> */\n#endif\n\n\t_lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa);\n\n\tlwsl_info(\"%s: did attach wsi %p: ah %p: count %d (on exit)\\n\", __func__,\n\t\t  (void *)wsi, (void *)wsi->http.ah, pt->http.ah_count_in_use);\n\nreset:\n\t__lws_header_table_reset(wsi, autoservice);\n\n\tlws_pt_unlock(pt);\n\n#ifndef LWS_NO_CLIENT\n\tif (lwsi_role_client(wsi) && lwsi_state(wsi) == LRS_UNCONNECTED)\n\t\tif (!lws_client_connect_via_info2(wsi))\n\t\t\t/* our client connect has failed, the wsi\n\t\t\t * has been closed\n\t\t\t */\n\t\t\treturn -1;\n#endif\n\n\treturn 0;\n\nbail:\n\tlws_pt_unlock(pt);\n\n\treturn 1;\n}\n\nint __lws_header_table_detach(struct lws *wsi, int autoservice)\n{\n\tstruct lws_context *context = wsi->context;\n\tstruct allocated_headers *ah = wsi->http.ah;\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tstruct lws_pollargs pa;\n\tstruct lws **pwsi, **pwsi_eligible;\n\ttime_t now;\n\n\t__lws_remove_from_ah_waiting_list(wsi);\n\n\tif (!ah)\n\t\treturn 0;\n\n\tlwsl_info(\"%s: wsi %p: ah %p (tsi=%d, count = %d)\\n\", __func__,\n\t\t  (void *)wsi, (void *)ah, wsi->tsi,\n\t\t  pt->http.ah_count_in_use);\n\n\t/* we did have an ah attached */\n\ttime(&now);\n\tif (ah->assigned && now - ah->assigned > 3) {\n\t\t/*\n\t\t * we're detaching the ah, but it was held an\n\t\t * unreasonably long time\n\t\t */\n\t\tlwsl_debug(\"%s: wsi %p: ah held %ds, role/state 0x%x 0x%x,\"\n\t\t\t    \"\\n\", __func__, wsi, (int)(now - ah->assigned),\n\t\t\t    lwsi_role(wsi), lwsi_state(wsi));\n\t}\n\n\tah->assigned = 0;\n\n\t/* if we think we're detaching one, there should be one in use */\n\tassert(pt->http.ah_count_in_use > 0);\n\t/* and this specific one should have been in use */\n\tassert(ah->in_use);\n\tmemset(&wsi->http.ah, 0, sizeof(wsi->http.ah));\n\n#if defined(LWS_WITH_PEER_LIMITS)\n\tif (ah->wsi)\n\t\tlws_peer_track_ah_detach(context, wsi->peer);\n#endif\n\tah->wsi = NULL; /* no owner */\n\n\tpwsi = &pt->http.ah_wait_list;\n\n\t/* oh there is nobody on the waiting list... leave the ah unattached */\n\tif (!*pwsi)\n\t\tgoto nobody_usable_waiting;\n\n\t/*\n\t * at least one wsi on the same tsi is waiting, give it to oldest guy\n\t * who is allowed to take it (if any)\n\t */\n\tlwsl_info(\"pt wait list %p\\n\", *pwsi);\n\twsi = NULL;\n\tpwsi_eligible = NULL;\n\n\twhile (*pwsi) {\n#if defined(LWS_WITH_PEER_LIMITS)\n\t\t/* are we willing to give this guy an ah? */\n\t\tif (!lws_peer_confirm_ah_attach_ok(context, (*pwsi)->peer))\n#endif\n\t\t{\n\t\t\twsi = *pwsi;\n\t\t\tpwsi_eligible = pwsi;\n\t\t}\n#if defined(LWS_WITH_PEER_LIMITS)\n\t\telse\n\t\t\tif (!(*pwsi)->http.ah_wait_list)\n\t\t\t\tlws_stats_atomic_bump(context, pt,\n\t\t\t\t\tLWSSTATS_C_PEER_LIMIT_AH_DENIED, 1);\n#endif\n\t\tpwsi = &(*pwsi)->http.ah_wait_list;\n\t}\n\n\tif (!wsi) /* everybody waiting already has too many ah... */\n\t\tgoto nobody_usable_waiting;\n\n\tlwsl_info(\"%s: transferring ah to last eligible wsi in wait list %p (wsistate 0x%x)\\n\", __func__, wsi, wsi->wsistate);\n\n\twsi->http.ah = ah;\n\tah->wsi = wsi; /* new owner */\n\n\t__lws_header_table_reset(wsi, autoservice);\n#if defined(LWS_WITH_PEER_LIMITS) && (defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2))\n\tlws_context_lock(context); /* <====================================== */\n\tif (wsi->peer)\n\t\twsi->peer->http.count_ah++;\n\tlws_context_unlock(context); /* ====================================> */\n#endif\n\n\t/* clients acquire the ah and then insert themselves in fds table... */\n\tif (wsi->position_in_fds_table != LWS_NO_FDS_POS) {\n\t\tlwsl_info(\"%s: Enabling %p POLLIN\\n\", __func__, wsi);\n\n\t\t/* he has been stuck waiting for an ah, but now his wait is\n\t\t * over, let him progress */\n\n\t\t_lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa);\n\t}\n\n\t/* point prev guy to next guy in list instead */\n\t*pwsi_eligible = wsi->http.ah_wait_list;\n\t/* the guy who got one is out of the list */\n\twsi->http.ah_wait_list = NULL;\n\tpt->http.ah_wait_list_length--;\n\n#ifndef LWS_NO_CLIENT\n\tif (lwsi_role_client(wsi) && lwsi_state(wsi) == LRS_UNCONNECTED) {\n\t\tlws_pt_unlock(pt);\n\n\t\tif (!lws_client_connect_via_info2(wsi)) {\n\t\t\t/* our client connect has failed, the wsi\n\t\t\t * has been closed\n\t\t\t */\n\n\t\t\treturn -1;\n\t\t}\n\t\treturn 0;\n\t}\n#endif\n\n\tassert(!!pt->http.ah_wait_list_length == !!(lws_intptr_t)pt->http.ah_wait_list);\nbail:\n\tlwsl_info(\"%s: wsi %p: ah %p (tsi=%d, count = %d)\\n\", __func__,\n\t\t  (void *)wsi, (void *)ah, pt->tid, pt->http.ah_count_in_use);\n\n\treturn 0;\n\nnobody_usable_waiting:\n\tlwsl_info(\"%s: nobody usable waiting\\n\", __func__);\n\t_lws_destroy_ah(pt, ah);\n\tpt->http.ah_count_in_use--;\n\n\tgoto bail;\n}\n\nint lws_header_table_detach(struct lws *wsi, int autoservice)\n{\n\tstruct lws_context *context = wsi->context;\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tint n;\n\n\tlws_pt_lock(pt, __func__);\n\tn = __lws_header_table_detach(wsi, autoservice);\n\tlws_pt_unlock(pt);\n\n\treturn n;\n}\n\nLWS_VISIBLE int\nlws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx)\n{\n\tint n;\n\n\tif (!wsi->http.ah)\n\t\treturn 0;\n\n\tn = wsi->http.ah->frag_index[h];\n\tif (!n)\n\t\treturn 0;\n\tdo {\n\t\tif (!frag_idx)\n\t\t\treturn wsi->http.ah->frags[n].len;\n\t\tn = wsi->http.ah->frags[n].nfrag;\n\t} while (frag_idx-- && n);\n\n\treturn 0;\n}\n\nLWS_VISIBLE int lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h)\n{\n\tint n;\n\tint len = 0;\n\n\tif (!wsi->http.ah)\n\t\treturn 0;\n\n\tn = wsi->http.ah->frag_index[h];\n\tif (!n)\n\t\treturn 0;\n\tdo {\n\t\tlen += wsi->http.ah->frags[n].len;\n\t\tn = wsi->http.ah->frags[n].nfrag;\n\t} while (n);\n\n\treturn len;\n}\n\nLWS_VISIBLE int lws_hdr_copy_fragment(struct lws *wsi, char *dst, int len,\n\t\t\t\t      enum lws_token_indexes h, int frag_idx)\n{\n\tint n = 0;\n\tint f;\n\n\tif (!wsi->http.ah)\n\t\treturn -1;\n\n\tf = wsi->http.ah->frag_index[h];\n\n\tif (!f)\n\t\treturn -1;\n\n\twhile (n < frag_idx) {\n\t\tf = wsi->http.ah->frags[f].nfrag;\n\t\tif (!f)\n\t\t\treturn -1;\n\t\tn++;\n\t}\n\n\tif (wsi->http.ah->frags[f].len >= len)\n\t\treturn -1;\n\n\tmemcpy(dst, wsi->http.ah->data + wsi->http.ah->frags[f].offset,\n\t       wsi->http.ah->frags[f].len);\n\tdst[wsi->http.ah->frags[f].len] = '\\0';\n\n\treturn wsi->http.ah->frags[f].len;\n}\n\nLWS_VISIBLE int lws_hdr_copy(struct lws *wsi, char *dst, int len,\n\t\t\t     enum lws_token_indexes h)\n{\n\tint toklen = lws_hdr_total_length(wsi, h);\n\tint n;\n\n\tif (toklen >= len)\n\t\treturn -1;\n\n\tif (!wsi->http.ah)\n\t\treturn -1;\n\n\tn = wsi->http.ah->frag_index[h];\n\tif (!n)\n\t\treturn 0;\n\n\tdo {\n\t\tif (wsi->http.ah->frags[n].len >= len)\n\t\t\treturn -1;\n\t\tstrncpy(dst, &wsi->http.ah->data[wsi->http.ah->frags[n].offset],\n\t\t        wsi->http.ah->frags[n].len);\n\t\tdst += wsi->http.ah->frags[n].len;\n\t\tlen -= wsi->http.ah->frags[n].len;\n\t\tn = wsi->http.ah->frags[n].nfrag;\n\t} while (n);\n\t*dst = '\\0';\n\n\treturn toklen;\n}\n\nchar *lws_hdr_simple_ptr(struct lws *wsi, enum lws_token_indexes h)\n{\n\tint n;\n\n\tn = wsi->http.ah->frag_index[h];\n\tif (!n)\n\t\treturn NULL;\n\n\treturn wsi->http.ah->data + wsi->http.ah->frags[n].offset;\n}\n\nstatic int LWS_WARN_UNUSED_RESULT\nlws_pos_in_bounds(struct lws *wsi)\n{\n\tif (wsi->http.ah->pos <\n\t    (unsigned int)wsi->context->max_http_header_data)\n\t\treturn 0;\n\n\tif ((int)wsi->http.ah->pos == wsi->context->max_http_header_data) {\n\t\tlwsl_err(\"Ran out of header data space\\n\");\n\t\treturn 1;\n\t}\n\n\t/*\n\t * with these tests everywhere, it should never be able to exceed\n\t * the limit, only meet it\n\t */\n\tlwsl_err(\"%s: pos %d, limit %d\\n\", __func__, wsi->http.ah->pos,\n\t\t wsi->context->max_http_header_data);\n\tassert(0);\n\n\treturn 1;\n}\n\nint LWS_WARN_UNUSED_RESULT\nlws_hdr_simple_create(struct lws *wsi, enum lws_token_indexes h, const char *s)\n{\n\twsi->http.ah->nfrag++;\n\tif (wsi->http.ah->nfrag == LWS_ARRAY_SIZE(wsi->http.ah->frags)) {\n\t\tlwsl_warn(\"More hdr frags than we can deal with, dropping\\n\");\n\t\treturn -1;\n\t}\n\n\twsi->http.ah->frag_index[h] = wsi->http.ah->nfrag;\n\n\twsi->http.ah->frags[wsi->http.ah->nfrag].offset = wsi->http.ah->pos;\n\twsi->http.ah->frags[wsi->http.ah->nfrag].len = 0;\n\twsi->http.ah->frags[wsi->http.ah->nfrag].nfrag = 0;\n\n\tdo {\n\t\tif (lws_pos_in_bounds(wsi))\n\t\t\treturn -1;\n\n\t\twsi->http.ah->data[wsi->http.ah->pos++] = *s;\n\t\tif (*s)\n\t\t\twsi->http.ah->frags[wsi->http.ah->nfrag].len++;\n\t} while (*s++);\n\n\treturn 0;\n}\n\nstatic int LWS_WARN_UNUSED_RESULT\nissue_char(struct lws *wsi, unsigned char c)\n{\n\tunsigned short frag_len;\n\n\tif (lws_pos_in_bounds(wsi))\n\t\treturn -1;\n\n\tfrag_len = wsi->http.ah->frags[wsi->http.ah->nfrag].len;\n\t/*\n\t * If we haven't hit the token limit, just copy the character into\n\t * the header\n\t */\n\tif (frag_len < wsi->http.ah->current_token_limit) {\n\t\twsi->http.ah->data[wsi->http.ah->pos++] = c;\n\t\tif (c)\n\t\t\twsi->http.ah->frags[wsi->http.ah->nfrag].len++;\n\t\treturn 0;\n\t}\n\n\t/* Insert a null character when we *hit* the limit: */\n\tif (frag_len == wsi->http.ah->current_token_limit) {\n\t\tif (lws_pos_in_bounds(wsi))\n\t\t\treturn -1;\n\n\t\twsi->http.ah->data[wsi->http.ah->pos++] = '\\0';\n\t\tlwsl_warn(\"header %i exceeds limit %d\\n\",\n\t\t\t  wsi->http.ah->parser_state,\n\t\t\t  wsi->http.ah->current_token_limit);\n\t}\n\n\treturn 1;\n}\n\nint\nlws_parse_urldecode(struct lws *wsi, uint8_t *_c)\n{\n\tstruct allocated_headers *ah = wsi->http.ah;\n\tunsigned int enc = 0;\n\tuint8_t c = *_c;\n\n\t// lwsl_notice(\"ah->ups %d\\n\", ah->ups);\n\n\t/*\n\t * PRIORITY 1\n\t * special URI processing... convert %xx\n\t */\n\tswitch (ah->ues) {\n\tcase URIES_IDLE:\n\t\tif (c == '%') {\n\t\t\tah->ues = URIES_SEEN_PERCENT;\n\t\t\tgoto swallow;\n\t\t}\n\t\tbreak;\n\tcase URIES_SEEN_PERCENT:\n\t\tif (char_to_hex(c) < 0)\n\t\t\t/* illegal post-% char */\n\t\t\tgoto forbid;\n\n\t\tah->esc_stash = c;\n\t\tah->ues = URIES_SEEN_PERCENT_H1;\n\t\tgoto swallow;\n\n\tcase URIES_SEEN_PERCENT_H1:\n\t\tif (char_to_hex(c) < 0)\n\t\t\t/* illegal post-% char */\n\t\t\tgoto forbid;\n\n\t\t*_c = (char_to_hex(ah->esc_stash) << 4) |\n\t\t\t\tchar_to_hex(c);\n\t\tc = *_c;\n\t\tenc = 1;\n\t\tah->ues = URIES_IDLE;\n\t\tbreak;\n\t}\n\n\t/*\n\t * PRIORITY 2\n\t * special URI processing...\n\t *  convert /.. or /... or /../ etc to /\n\t *  convert /./ to /\n\t *  convert // or /// etc to /\n\t *  leave /.dir or whatever alone\n\t */\n\n\tswitch (ah->ups) {\n\tcase URIPS_IDLE:\n\t\tif (!c)\n\t\t\treturn -1;\n\t\t/* genuine delimiter */\n\t\tif ((c == '&' || c == ';') && !enc) {\n\t\t\tif (issue_char(wsi, '\\0') < 0)\n\t\t\t\treturn -1;\n\t\t\t/* link to next fragment */\n\t\t\tah->frags[ah->nfrag].nfrag = ah->nfrag + 1;\n\t\t\tah->nfrag++;\n\t\t\tif (ah->nfrag >= LWS_ARRAY_SIZE(ah->frags))\n\t\t\t\tgoto excessive;\n\t\t\t/* start next fragment after the & */\n\t\t\tah->post_literal_equal = 0;\n\t\t\tah->frags[ah->nfrag].offset = ++ah->pos;\n\t\t\tah->frags[ah->nfrag].len = 0;\n\t\t\tah->frags[ah->nfrag].nfrag = 0;\n\t\t\tgoto swallow;\n\t\t}\n\t\t/* uriencoded = in the name part, disallow */\n\t\tif (c == '=' && enc &&\n\t\t    ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] &&\n\t\t    !ah->post_literal_equal) {\n\t\t\tc = '_';\n\t\t\t*_c =c;\n\t\t}\n\n\t\t/* after the real =, we don't care how many = */\n\t\tif (c == '=' && !enc)\n\t\t\tah->post_literal_equal = 1;\n\n\t\t/* + to space */\n\t\tif (c == '+' && !enc) {\n\t\t\tc = ' ';\n\t\t\t*_c = c;\n\t\t}\n\t\t/* issue the first / always */\n\t\tif (c == '/' && !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS])\n\t\t\tah->ups = URIPS_SEEN_SLASH;\n\t\tbreak;\n\tcase URIPS_SEEN_SLASH:\n\t\t/* swallow subsequent slashes */\n\t\tif (c == '/')\n\t\t\tgoto swallow;\n\t\t/* track and swallow the first . after / */\n\t\tif (c == '.') {\n\t\t\tah->ups = URIPS_SEEN_SLASH_DOT;\n\t\t\tgoto swallow;\n\t\t}\n\t\tah->ups = URIPS_IDLE;\n\t\tbreak;\n\tcase URIPS_SEEN_SLASH_DOT:\n\t\t/* swallow second . */\n\t\tif (c == '.') {\n\t\t\tah->ups = URIPS_SEEN_SLASH_DOT_DOT;\n\t\t\tgoto swallow;\n\t\t}\n\t\t/* change /./ to / */\n\t\tif (c == '/') {\n\t\t\tah->ups = URIPS_SEEN_SLASH;\n\t\t\tgoto swallow;\n\t\t}\n\t\t/* it was like /.dir ... regurgitate the . */\n\t\tah->ups = URIPS_IDLE;\n\t\tif (issue_char(wsi, '.') < 0)\n\t\t\treturn -1;\n\t\tbreak;\n\n\tcase URIPS_SEEN_SLASH_DOT_DOT:\n\n\t\t/* /../ or /..[End of URI] --> backup to last / */\n\t\tif (c == '/' || c == '?') {\n\t\t\t/*\n\t\t\t * back up one dir level if possible\n\t\t\t * safe against header fragmentation because\n\t\t\t * the method URI can only be in 1 fragment\n\t\t\t */\n\t\t\tif (ah->frags[ah->nfrag].len > 2) {\n\t\t\t\tah->pos--;\n\t\t\t\tah->frags[ah->nfrag].len--;\n\t\t\t\tdo {\n\t\t\t\t\tah->pos--;\n\t\t\t\t\tah->frags[ah->nfrag].len--;\n\t\t\t\t} while (ah->frags[ah->nfrag].len > 1 &&\n\t\t\t\t\t ah->data[ah->pos] != '/');\n\t\t\t}\n\t\t\tah->ups = URIPS_SEEN_SLASH;\n\t\t\tif (ah->frags[ah->nfrag].len > 1)\n\t\t\t\tbreak;\n\t\t\tgoto swallow;\n\t\t}\n\n\t\t/*  /..[^/] ... regurgitate and allow */\n\n\t\tif (issue_char(wsi, '.') < 0)\n\t\t\treturn -1;\n\t\tif (issue_char(wsi, '.') < 0)\n\t\t\treturn -1;\n\t\tah->ups = URIPS_IDLE;\n\t\tbreak;\n\t}\n\n\tif (c == '?' && !enc &&\n\t    !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS]) { /* start of URI args */\n\t\tif (ah->ues != URIES_IDLE)\n\t\t\tgoto forbid;\n\n\t\t/* seal off uri header */\n\t\tif (issue_char(wsi, '\\0') < 0)\n\t\t\treturn -1;\n\n\t\t/* move to using WSI_TOKEN_HTTP_URI_ARGS */\n\t\tah->nfrag++;\n\t\tif (ah->nfrag >= LWS_ARRAY_SIZE(ah->frags))\n\t\t\tgoto excessive;\n\t\tah->frags[ah->nfrag].offset = ++ah->pos;\n\t\tah->frags[ah->nfrag].len = 0;\n\t\tah->frags[ah->nfrag].nfrag = 0;\n\n\t\tah->post_literal_equal = 0;\n\t\tah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] = ah->nfrag;\n\t\tah->ups = URIPS_IDLE;\n\t\tgoto swallow;\n\t}\n\n\treturn LPUR_CONTINUE;\n\nswallow:\n\treturn LPUR_SWALLOW;\n\nforbid:\n\treturn LPUR_FORBID;\n\nexcessive:\n\treturn LPUR_EXCESSIVE;\n}\n\nstatic const unsigned char methods[] = {\n\tWSI_TOKEN_GET_URI,\n\tWSI_TOKEN_POST_URI,\n\tWSI_TOKEN_OPTIONS_URI,\n\tWSI_TOKEN_PUT_URI,\n\tWSI_TOKEN_PATCH_URI,\n\tWSI_TOKEN_DELETE_URI,\n\tWSI_TOKEN_CONNECT,\n\tWSI_TOKEN_HEAD_URI,\n};\n\n/*\n * possible returns:, -1 fail, 0 ok or 2, transition to raw\n */\n\nint LWS_WARN_UNUSED_RESULT\nlws_parse(struct lws *wsi, unsigned char *buf, int *len)\n{\n\tstruct allocated_headers *ah = wsi->http.ah;\n\tstruct lws_context *context = wsi->context;\n\tunsigned int n, m;\n\tunsigned char c;\n\tint r, pos;\n\n\tassert(wsi->http.ah);\n\n\tdo {\n\t\t(*len)--;\n\t\tc = *buf++;\n\n\t\tswitch (ah->parser_state) {\n\t\tdefault:\n\n\t\t\tlwsl_parser(\"WSI_TOK_(%d) '%c'\\n\", ah->parser_state, c);\n\n\t\t\t/* collect into malloc'd buffers */\n\t\t\t/* optional initial space swallow */\n\t\t\tif (!ah->frags[ah->frag_index[ah->parser_state]].len &&\n\t\t\t    c == ' ')\n\t\t\t\tbreak;\n\n\t\t\tfor (m = 0; m < LWS_ARRAY_SIZE(methods); m++)\n\t\t\t\tif (ah->parser_state == methods[m])\n\t\t\t\t\tbreak;\n\t\t\tif (m == LWS_ARRAY_SIZE(methods))\n\t\t\t\t/* it was not any of the methods */\n\t\t\t\tgoto check_eol;\n\n\t\t\t/* special URI processing... end at space */\n\n\t\t\tif (c == ' ') {\n\t\t\t\t/* enforce starting with / */\n\t\t\t\tif (!ah->frags[ah->nfrag].len)\n\t\t\t\t\tif (issue_char(wsi, '/') < 0)\n\t\t\t\t\t\treturn -1;\n\n\t\t\t\tif (ah->ups == URIPS_SEEN_SLASH_DOT_DOT) {\n\t\t\t\t\t/*\n\t\t\t\t\t * back up one dir level if possible\n\t\t\t\t\t * safe against header fragmentation because\n\t\t\t\t\t * the method URI can only be in 1 fragment\n\t\t\t\t\t */\n\t\t\t\t\tif (ah->frags[ah->nfrag].len > 2) {\n\t\t\t\t\t\tah->pos--;\n\t\t\t\t\t\tah->frags[ah->nfrag].len--;\n\t\t\t\t\t\tdo {\n\t\t\t\t\t\t\tah->pos--;\n\t\t\t\t\t\t\tah->frags[ah->nfrag].len--;\n\t\t\t\t\t\t} while (ah->frags[ah->nfrag].len > 1 &&\n\t\t\t\t\t\t\t ah->data[ah->pos] != '/');\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/* begin parsing HTTP version: */\n\t\t\t\tif (issue_char(wsi, '\\0') < 0)\n\t\t\t\t\treturn -1;\n\t\t\t\tah->parser_state = WSI_TOKEN_HTTP;\n\t\t\t\tgoto start_fragment;\n\t\t\t}\n\n\t\t\tr = lws_parse_urldecode(wsi, &c);\n\t\t\tswitch (r) {\n\t\t\tcase LPUR_CONTINUE:\n\t\t\t\tbreak;\n\t\t\tcase LPUR_SWALLOW:\n\t\t\t\tgoto swallow;\n\t\t\tcase LPUR_FORBID:\n\t\t\t\tgoto forbid;\n\t\t\tcase LPUR_EXCESSIVE:\n\t\t\t\tgoto excessive;\n\t\t\tdefault:\n\t\t\t\treturn -1;\n\t\t\t}\ncheck_eol:\n\t\t\t/* bail at EOL */\n\t\t\tif (ah->parser_state != WSI_TOKEN_CHALLENGE &&\n\t\t\t    c == '\\x0d') {\n\t\t\t\tif (ah->ues != URIES_IDLE)\n\t\t\t\t\tgoto forbid;\n\n\t\t\t\tc = '\\0';\n\t\t\t\tah->parser_state = WSI_TOKEN_SKIPPING_SAW_CR;\n\t\t\t\tlwsl_parser(\"*\\n\");\n\t\t\t}\n\n\t\t\tn = issue_char(wsi, c);\n\t\t\tif ((int)n < 0)\n\t\t\t\treturn -1;\n\t\t\tif (n > 0)\n\t\t\t\tah->parser_state = WSI_TOKEN_SKIPPING;\n\nswallow:\n\t\t\t/* per-protocol end of headers management */\n\n\t\t\tif (ah->parser_state == WSI_TOKEN_CHALLENGE)\n\t\t\t\tgoto set_parsing_complete;\n\t\t\tbreak;\n\n\t\t\t/* collecting and checking a name part */\n\t\tcase WSI_TOKEN_NAME_PART:\n\t\t\tlwsl_parser(\"WSI_TOKEN_NAME_PART '%c' 0x%02X (role=0x%x) \"\n\t\t\t\t    \"wsi->lextable_pos=%d\\n\", c, c, lwsi_role(wsi),\n\t\t\t\t    ah->lextable_pos);\n\n\t\t\tif (c >= 'A' && c <= 'Z')\n\t\t\t\tc += 'a' - 'A';\n\n\t\t\tpos = ah->lextable_pos;\n\n\t\t\twhile (1) {\n\t\t\t\tif (lextable[pos] & (1 << 7)) { /* 1-byte, fail on mismatch */\n\t\t\t\t\tif ((lextable[pos] & 0x7f) != c) {\nnope:\n\t\t\t\t\t\tah->lextable_pos = -1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t/* fall thru */\n\t\t\t\t\tpos++;\n\t\t\t\t\tif (lextable[pos] == FAIL_CHAR)\n\t\t\t\t\t\tgoto nope;\n\n\t\t\t\t\tah->lextable_pos = pos;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (lextable[pos] == FAIL_CHAR)\n\t\t\t\t\tgoto nope;\n\n\t\t\t\t/* b7 = 0, end or 3-byte */\n\t\t\t\tif (lextable[pos] < FAIL_CHAR) { /* terminal marker */\n\t\t\t\t\tah->lextable_pos = pos;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (lextable[pos] == c) { /* goto */\n\t\t\t\t\tah->lextable_pos = pos + (lextable[pos + 1]) +\n\t\t\t\t\t\t\t(lextable[pos + 2] << 8);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t/* fall thru goto */\n\t\t\t\tpos += 3;\n\t\t\t\t/* continue */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * If it's h1, server needs to look out for unknown\n\t\t\t * methods...\n\t\t\t */\n\t\t\tif (ah->lextable_pos < 0 && lwsi_role_h1(wsi) &&\n\t\t\t    lwsi_role_server(wsi)) {\n\t\t\t\t/* this is not a header we know about */\n\t\t\t\tfor (m = 0; m < LWS_ARRAY_SIZE(methods); m++)\n\t\t\t\t\tif (ah->frag_index[methods[m]]) {\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * already had the method, no idea what\n\t\t\t\t\t\t * this crap from the client is, ignore\n\t\t\t\t\t\t */\n\t\t\t\t\t\tah->parser_state = WSI_TOKEN_SKIPPING;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * hm it's an unknown http method from a client in fact,\n\t\t\t\t * it cannot be valid http\n\t\t\t\t */\n\t\t\t\tif (m == LWS_ARRAY_SIZE(methods)) {\n\t\t\t\t\t/*\n\t\t\t\t\t * are we set up to accept raw in these cases?\n\t\t\t\t\t */\n\t\t\t\t\tif (lws_check_opt(wsi->vhost->options,\n\t\t\t\t\t\t   LWS_SERVER_OPTION_FALLBACK_TO_RAW))\n\t\t\t\t\t\treturn 2; /* transition to raw */\n\n\t\t\t\t\tlwsl_info(\"Unknown method - dropping\\n\");\n\t\t\t\t\tgoto forbid;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/*\n\t\t\t * ...otherwise for a client, let him ignore unknown headers\n\t\t\t * coming from the server\n\t\t\t */\n\t\t\tif (ah->lextable_pos < 0) {\n\t\t\t\tah->parser_state = WSI_TOKEN_SKIPPING;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (lextable[ah->lextable_pos] < FAIL_CHAR) {\n\t\t\t\t/* terminal state */\n\n\t\t\t\tn = ((unsigned int)lextable[ah->lextable_pos] << 8) |\n\t\t\t\t\t\tlextable[ah->lextable_pos + 1];\n\n\t\t\t\tlwsl_parser(\"known hdr %d\\n\", n);\n\t\t\t\tfor (m = 0; m < LWS_ARRAY_SIZE(methods); m++)\n\t\t\t\t\tif (n == methods[m] &&\n\t\t\t\t\t    ah->frag_index[methods[m]]) {\n\t\t\t\t\t\tlwsl_warn(\"Duplicated method\\n\");\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * WSORIGIN is protocol equiv to ORIGIN,\n\t\t\t\t * JWebSocket likes to send it, map to ORIGIN\n\t\t\t\t */\n\t\t\t\tif (n == WSI_TOKEN_SWORIGIN)\n\t\t\t\t\tn = WSI_TOKEN_ORIGIN;\n\n\t\t\t\tah->parser_state = (enum lws_token_indexes)\n\t\t\t\t\t\t\t\t(WSI_TOKEN_GET_URI + n);\n\t\t\t\tah->ups = URIPS_IDLE;\n\n\t\t\t\tif (context->token_limits)\n\t\t\t\t\tah->current_token_limit = context->\n\t\t\t\t\t\t\ttoken_limits->token_limit[\n\t\t\t\t\t\t\t\t      ah->parser_state];\n\t\t\t\telse\n\t\t\t\t\tah->current_token_limit =\n\t\t\t\t\t\twsi->context->max_http_header_data;\n\n\t\t\t\tif (ah->parser_state == WSI_TOKEN_CHALLENGE)\n\t\t\t\t\tgoto set_parsing_complete;\n\n\t\t\t\tgoto start_fragment;\n\t\t\t}\n\t\t\tbreak;\n\nstart_fragment:\n\t\t\tah->nfrag++;\nexcessive:\n\t\t\tif (ah->nfrag == LWS_ARRAY_SIZE(ah->frags)) {\n\t\t\t\tlwsl_warn(\"More hdr frags than we can deal with\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tah->frags[ah->nfrag].offset = ah->pos;\n\t\t\tah->frags[ah->nfrag].len = 0;\n\t\t\tah->frags[ah->nfrag].nfrag = 0;\n\t\t\tah->frags[ah->nfrag].flags = 2;\n\n\t\t\tn = ah->frag_index[ah->parser_state];\n\t\t\tif (!n) { /* first fragment */\n\t\t\t\tah->frag_index[ah->parser_state] = ah->nfrag;\n\t\t\t\tah->hdr_token_idx = ah->parser_state;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* continuation */\n\t\t\twhile (ah->frags[n].nfrag)\n\t\t\t\tn = ah->frags[n].nfrag;\n\t\t\tah->frags[n].nfrag = ah->nfrag;\n\n\t\t\tif (issue_char(wsi, ' ') < 0)\n\t\t\t\treturn -1;\n\t\t\tbreak;\n\n\t\t\t/* skipping arg part of a name we didn't recognize */\n\t\tcase WSI_TOKEN_SKIPPING:\n\t\t\tlwsl_parser(\"WSI_TOKEN_SKIPPING '%c'\\n\", c);\n\n\t\t\tif (c == '\\x0d')\n\t\t\t\tah->parser_state = WSI_TOKEN_SKIPPING_SAW_CR;\n\t\t\tbreak;\n\n\t\tcase WSI_TOKEN_SKIPPING_SAW_CR:\n\t\t\tlwsl_parser(\"WSI_TOKEN_SKIPPING_SAW_CR '%c'\\n\", c);\n\t\t\tif (ah->ues != URIES_IDLE)\n\t\t\t\tgoto forbid;\n\t\t\tif (c == '\\x0a') {\n\t\t\t\tah->parser_state = WSI_TOKEN_NAME_PART;\n\t\t\t\tah->lextable_pos = 0;\n\t\t\t} else\n\t\t\t\tah->parser_state = WSI_TOKEN_SKIPPING;\n\t\t\tbreak;\n\t\t\t/* we're done, ignore anything else */\n\n\t\tcase WSI_PARSING_COMPLETE:\n\t\t\tlwsl_parser(\"WSI_PARSING_COMPLETE '%c'\\n\", c);\n\t\t\tbreak;\n\t\t}\n\n\t} while (*len);\n\n\treturn 0;\n\nset_parsing_complete:\n\tif (ah->ues != URIES_IDLE)\n\t\tgoto forbid;\n\tif (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {\n\t\tif (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION))\n\t\t\twsi->rx_frame_type = /* temp for ws version index */\n\t\t\t       atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION));\n\n\t\tlwsl_parser(\"v%02d hdrs done\\n\", wsi->rx_frame_type);\n\t}\n\tah->parser_state = WSI_PARSING_COMPLETE;\n\twsi->hdr_parsing_completed = 1;\n\n\treturn 0;\n\nforbid:\n\tlwsl_notice(\" forbidding on uri sanitation\\n\");\n\tlws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);\n\n\treturn -1;\n}\n\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/http/server/server.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n\nconst char * const method_names[] = {\n\t\"GET\", \"POST\", \"OPTIONS\", \"PUT\", \"PATCH\", \"DELETE\", \"CONNECT\", \"HEAD\",\n#ifdef LWS_WITH_HTTP2\n\t\":path\",\n#endif\n\t};\n\n/*\n * return 0: all done\n *        1: nonfatal error\n *       <0: fatal error\n *\n *       REQUIRES CONTEXT LOCK HELD\n */\n\nint\n_lws_vhost_init_server(const struct lws_context_creation_info *info,\n\t\t\t struct lws_vhost *vhost)\n{\n\tint n, opt = 1, limit = 1;\n\tlws_sockfd_type sockfd;\n\tstruct lws_vhost *vh;\n\tstruct lws *wsi;\n\tint m = 0, is;\n\n\t(void)method_names;\n\t(void)opt;\n\n\tif (info) {\n\t\tvhost->iface = info->iface;\n\t\tvhost->listen_port = info->port;\n\t}\n\n\t/* set up our external listening socket we serve on */\n\n\tif (vhost->listen_port == CONTEXT_PORT_NO_LISTEN ||\n\t    vhost->listen_port == CONTEXT_PORT_NO_LISTEN_SERVER)\n\t\treturn 0;\n\n\tvh = vhost->context->vhost_list;\n\twhile (vh) {\n\t\tif (vh->listen_port == vhost->listen_port) {\n\t\t\tif (((!vhost->iface && !vh->iface) ||\n\t\t\t    (vhost->iface && vh->iface &&\n\t\t\t    !strcmp(vhost->iface, vh->iface))) &&\n\t\t\t   vh->lserv_wsi\n\t\t\t) {\n\t\t\t\tlwsl_notice(\" using listen skt from vhost %s\\n\",\n\t\t\t\t\t    vh->name);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\tvh = vh->vhost_next;\n\t}\n\n\tif (vhost->iface) {\n\t\t/*\n\t\t * let's check before we do anything else about the disposition\n\t\t * of the interface he wants to bind to...\n\t\t */\n\t\tis = lws_socket_bind(vhost, LWS_SOCK_INVALID, vhost->listen_port, vhost->iface);\n\t\tlwsl_debug(\"initial if check says %d\\n\", is);\ndeal:\n\n\t\tlws_start_foreach_llp(struct lws_vhost **, pv,\n\t\t\t\t      vhost->context->no_listener_vhost_list) {\n\t\t\tif (is >= LWS_ITOSA_USABLE && *pv == vhost) {\n\t\t\t\t/* on the list and shouldn't be: remove it */\n\t\t\t\tlwsl_debug(\"deferred iface: removing vh %s\\n\", (*pv)->name);\n\t\t\t\t*pv = vhost->no_listener_vhost_list;\n\t\t\t\tvhost->no_listener_vhost_list = NULL;\n\t\t\t\tgoto done_list;\n\t\t\t}\n\t\t\tif (is < LWS_ITOSA_USABLE && *pv == vhost)\n\t\t\t\tgoto done_list;\n\t\t} lws_end_foreach_llp(pv, no_listener_vhost_list);\n\n\t\t/* not on the list... */\n\n\t\tif (is < LWS_ITOSA_USABLE) {\n\n\t\t\t/* ... but needs to be: so add it */\n\n\t\t\tlwsl_debug(\"deferred iface: adding vh %s\\n\", vhost->name);\n\t\t\tvhost->no_listener_vhost_list = vhost->context->no_listener_vhost_list;\n\t\t\tvhost->context->no_listener_vhost_list = vhost;\n\t\t}\n\ndone_list:\n\n\t\tswitch (is) {\n\t\tdefault:\n\t\t\tbreak;\n\t\tcase LWS_ITOSA_NOT_EXIST:\n\t\t\t/* can't add it */\n\t\t\tif (info) /* first time */\n\t\t\t\tlwsl_err(\"VH %s: iface %s port %d DOESN'T EXIST\\n\",\n\t\t\t\t vhost->name, vhost->iface, vhost->listen_port);\n\t\t\treturn 1;\n\t\tcase LWS_ITOSA_NOT_USABLE:\n\t\t\t/* can't add it */\n\t\t\tif (info) /* first time */\n\t\t\t\tlwsl_err(\"VH %s: iface %s port %d NOT USABLE\\n\",\n\t\t\t\t vhost->name, vhost->iface, vhost->listen_port);\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\t(void)n;\n#if defined(__linux__)\n#ifdef LWS_WITH_UNIX_SOCK\n\t/*\n\t * A Unix domain sockets cannot be bound for several times, even if we set\n\t * the SO_REUSE* options on.\n\t * However, fortunately, each thread is able to independently listen when\n\t * running on a reasonably new Linux kernel. So we can safely assume\n\t * creating just one listening socket for a multi-threaded environment won't\n\t * fail in most cases.\n\t */\n\tif (!LWS_UNIX_SOCK_ENABLED(vhost))\n#endif\n\tlimit = vhost->context->count_threads;\n#endif\n\n\tfor (m = 0; m < limit; m++) {\n#ifdef LWS_WITH_UNIX_SOCK\n\t\tif (LWS_UNIX_SOCK_ENABLED(vhost))\n\t\t\tsockfd = socket(AF_UNIX, SOCK_STREAM, 0);\n\t\telse\n#endif\n#ifdef LWS_WITH_IPV6\n\t\tif (LWS_IPV6_ENABLED(vhost))\n\t\t\tsockfd = socket(AF_INET6, SOCK_STREAM, 0);\n\t\telse\n#endif\n\t\t\tsockfd = socket(AF_INET, SOCK_STREAM, 0);\n\n\t\tif (sockfd == LWS_SOCK_INVALID) {\n\t\t\tlwsl_err(\"ERROR opening socket\\n\");\n\t\t\treturn 1;\n\t\t}\n#if !defined(LWS_WITH_ESP32)\n#if (defined(WIN32) || defined(_WIN32)) && defined(SO_EXCLUSIVEADDRUSE)\n\t\t/*\n\t\t * only accept that we are the only listener on the port\n\t\t * https://msdn.microsoft.com/zh-tw/library/\n\t\t *    windows/desktop/ms740621(v=vs.85).aspx\n\t\t *\n\t\t * for lws, to match Linux, we default to exclusive listen\n\t\t */\n\t\tif (!lws_check_opt(vhost->options,\n\t\t\t\tLWS_SERVER_OPTION_ALLOW_LISTEN_SHARE)) {\n\t\t\tif (setsockopt(sockfd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,\n\t\t\t\t       (const void *)&opt, sizeof(opt)) < 0) {\n\t\t\t\tlwsl_err(\"reuseaddr failed\\n\");\n\t\t\t\tcompatible_close(sockfd);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t} else\n#endif\n\n\t\t/*\n\t\t * allow us to restart even if old sockets in TIME_WAIT\n\t\t */\n\t\tif (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,\n\t\t\t       (const void *)&opt, sizeof(opt)) < 0) {\n\t\t\tlwsl_err(\"reuseaddr failed\\n\");\n\t\t\tcompatible_close(sockfd);\n\t\t\treturn -1;\n\t\t}\n\n#if defined(LWS_WITH_IPV6) && defined(IPV6_V6ONLY)\n\t\tif (LWS_IPV6_ENABLED(vhost) &&\n\t\t    vhost->options & LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY) {\n\t\t\tint value = (vhost->options &\n\t\t\t\tLWS_SERVER_OPTION_IPV6_V6ONLY_VALUE) ? 1 : 0;\n\t\t\tif (setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,\n\t\t\t\t      (const void*)&value, sizeof(value)) < 0) {\n\t\t\t\tcompatible_close(sockfd);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n#endif\n\n#if defined(__linux__) && defined(SO_REUSEPORT)\n\t\t/* keep coverity happy */\n#if LWS_MAX_SMP > 1\n\t\tn = 1;\n#else\n\t\tn = lws_check_opt(vhost->options,\n\t\t\t\t  LWS_SERVER_OPTION_ALLOW_LISTEN_SHARE);\n#endif\n\t\tif (n && vhost->context->count_threads > 1)\n\t\t\tif (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT,\n\t\t\t\t\t(const void *)&opt, sizeof(opt)) < 0) {\n\t\t\t\tcompatible_close(sockfd);\n\t\t\t\treturn -1;\n\t\t\t}\n#endif\n#endif\n\t\tlws_plat_set_socket_options(vhost, sockfd);\n\n\t\tis = lws_socket_bind(vhost, sockfd, vhost->listen_port, vhost->iface);\n\t\t/*\n\t\t * There is a race where the network device may come up and then\n\t\t * go away and fail here.  So correctly handle unexpected failure\n\t\t * here despite we earlier confirmed it.\n\t\t */\n\t\tif (is < 0) {\n\t\t\tlwsl_info(\"%s: lws_socket_bind says %d\\n\", __func__, is);\n\t\t\tcompatible_close(sockfd);\n\t\t\tgoto deal;\n\t\t}\n\t\tvhost->listen_port = is;\n\n\t\tlwsl_debug(\"%s: lws_socket_bind says %d\\n\", __func__, is);\n\n\t\twsi = lws_zalloc(sizeof(struct lws), \"listen wsi\");\n\t\tif (wsi == NULL) {\n\t\t\tlwsl_err(\"Out of mem\\n\");\n\t\t\tgoto bail;\n\t\t}\n\t\twsi->context = vhost->context;\n\t\twsi->desc.sockfd = sockfd;\n\t\tlws_role_transition(wsi, 0, LRS_UNCONNECTED, &role_ops_listen);\n\t\twsi->protocol = vhost->protocols;\n\t\twsi->tsi = m;\n\t\twsi->vhost = vhost;\n\t\twsi->listener = 1;\n\n\t\tif (wsi->context->event_loop_ops->init_vhost_listen_wsi)\n\t\t\twsi->context->event_loop_ops->init_vhost_listen_wsi(wsi);\n\n\t\tif (__insert_wsi_socket_into_fds(vhost->context, wsi)) {\n\t\t\tlwsl_notice(\"inserting wsi socket into fds failed\\n\");\n\t\t\tgoto bail;\n\t\t}\n\n\t\tvhost->context->count_wsi_allocated++;\n\t\tvhost->lserv_wsi = wsi;\n\n\t\tn = listen(wsi->desc.sockfd, LWS_SOMAXCONN);\n\t\tif (n < 0) {\n\t\t\tlwsl_err(\"listen failed with error %d\\n\", LWS_ERRNO);\n\t\t\tvhost->lserv_wsi = NULL;\n\t\t\tvhost->context->count_wsi_allocated--;\n\t\t\t__remove_wsi_socket_from_fds(wsi);\n\t\t\tgoto bail;\n\t\t}\n\t} /* for each thread able to independently listen */\n\n\tif (!lws_check_opt(vhost->context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS)) {\n#ifdef LWS_WITH_UNIX_SOCK\n\t\tif (LWS_UNIX_SOCK_ENABLED(vhost))\n\t\t\tlwsl_info(\" Listening on \\\"%s\\\"\\n\", vhost->iface);\n\t\telse\n#endif\n\t\t\tlwsl_info(\" Listening on port %d\\n\", vhost->listen_port);\n        }\n\n\t// info->port = vhost->listen_port;\n\n\treturn 0;\n\nbail:\n\tcompatible_close(sockfd);\n\n\treturn -1;\n}\n\nstruct lws_vhost *\nlws_select_vhost(struct lws_context *context, int port, const char *servername)\n{\n\tstruct lws_vhost *vhost = context->vhost_list;\n\tconst char *p;\n\tint n, m, colon;\n\n\tn = (int)strlen(servername);\n\tcolon = n;\n\tp = strchr(servername, ':');\n\tif (p)\n\t\tcolon = lws_ptr_diff(p, servername);\n\n\t/* Priotity 1: first try exact matches */\n\n\twhile (vhost) {\n\t\tif (port == vhost->listen_port &&\n\t\t    !strncmp(vhost->name, servername, colon)) {\n\t\t\tlwsl_info(\"SNI: Found: %s\\n\", servername);\n\t\t\treturn vhost;\n\t\t}\n\t\tvhost = vhost->vhost_next;\n\t}\n\n\t/*\n\t * Priority 2: if no exact matches, try matching *.vhost-name\n\t * unintentional matches are possible but resolve to x.com for *.x.com\n\t * which is reasonable.  If exact match exists we already chose it and\n\t * never reach here.  SSL will still fail it if the cert doesn't allow\n\t * *.x.com.\n\t */\n\tvhost = context->vhost_list;\n\twhile (vhost) {\n\t\tm = (int)strlen(vhost->name);\n\t\tif (port == vhost->listen_port &&\n\t\t    m <= (colon - 2) &&\n\t\t    servername[colon - m - 1] == '.' &&\n\t\t    !strncmp(vhost->name, servername + colon - m, m)) {\n\t\t\tlwsl_info(\"SNI: Found %s on wildcard: %s\\n\",\n\t\t\t\t    servername, vhost->name);\n\t\t\treturn vhost;\n\t\t}\n\t\tvhost = vhost->vhost_next;\n\t}\n\n\t/* Priority 3: match the first vhost on our port */\n\n\tvhost = context->vhost_list;\n\twhile (vhost) {\n\t\tif (port == vhost->listen_port) {\n\t\t\tlwsl_info(\"%s: vhost match to %s based on port %d\\n\",\n\t\t\t\t\t__func__, vhost->name, port);\n\t\t\treturn vhost;\n\t\t}\n\t\tvhost = vhost->vhost_next;\n\t}\n\n\t/* no match */\n\n\treturn NULL;\n}\n\nLWS_VISIBLE LWS_EXTERN const char *\nlws_get_mimetype(const char *file, const struct lws_http_mount *m)\n{\n\tint n = (int)strlen(file);\n\tconst struct lws_protocol_vhost_options *pvo = NULL;\n\n\tif (m)\n\t\tpvo = m->extra_mimetypes;\n\n\tif (n < 5)\n\t\treturn NULL;\n\n\tif (!strcmp(&file[n - 4], \".ico\"))\n\t\treturn \"image/x-icon\";\n\n\tif (!strcmp(&file[n - 4], \".gif\"))\n\t\treturn \"image/gif\";\n\n\tif (!strcmp(&file[n - 3], \".js\"))\n\t\treturn \"text/javascript\";\n\n\tif (!strcmp(&file[n - 4], \".png\"))\n\t\treturn \"image/png\";\n\n\tif (!strcmp(&file[n - 4], \".jpg\"))\n\t\treturn \"image/jpeg\";\n\n\tif (!strcmp(&file[n - 3], \".gz\"))\n\t\treturn \"application/gzip\";\n\n\tif (!strcmp(&file[n - 4], \".JPG\"))\n\t\treturn \"image/jpeg\";\n\n\tif (!strcmp(&file[n - 5], \".html\"))\n\t\treturn \"text/html\";\n\n\tif (!strcmp(&file[n - 4], \".css\"))\n\t\treturn \"text/css\";\n\n\tif (!strcmp(&file[n - 4], \".txt\"))\n\t\treturn \"text/plain\";\n\n\tif (!strcmp(&file[n - 4], \".svg\"))\n\t\treturn \"image/svg+xml\";\n\n\tif (!strcmp(&file[n - 4], \".ttf\"))\n\t\treturn \"application/x-font-ttf\";\n\n\tif (!strcmp(&file[n - 4], \".otf\"))\n\t\treturn \"application/font-woff\";\n\n\tif (!strcmp(&file[n - 5], \".woff\"))\n\t\treturn \"application/font-woff\";\n\n\tif (!strcmp(&file[n - 4], \".xml\"))\n\t\treturn \"application/xml\";\n\n\twhile (pvo) {\n\t\tif (pvo->name[0] == '*') /* ie, match anything */\n\t\t\treturn pvo->value;\n\n\t\tif (!strcmp(&file[n - strlen(pvo->name)], pvo->name))\n\t\t\treturn pvo->value;\n\n\t\tpvo = pvo->next;\n\t}\n\n\treturn NULL;\n}\nstatic lws_fop_flags_t\nlws_vfs_prepare_flags(struct lws *wsi)\n{\n\tlws_fop_flags_t f = 0;\n\n\tif (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_ACCEPT_ENCODING))\n\t\treturn f;\n\n\tif (strstr(lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_ACCEPT_ENCODING),\n\t\t   \"gzip\")) {\n\t\tlwsl_info(\"client indicates GZIP is acceptable\\n\");\n\t\tf |= LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP;\n\t}\n\n\treturn f;\n}\n\nstatic int\nlws_http_serve(struct lws *wsi, char *uri, const char *origin,\n\t       const struct lws_http_mount *m)\n{\n\tconst struct lws_protocol_vhost_options *pvo = m->interpret;\n\tstruct lws_process_html_args args;\n\tconst char *mimetype;\n#if !defined(_WIN32_WCE)\n\tconst struct lws_plat_file_ops *fops;\n\tconst char *vpath;\n\tlws_fop_flags_t fflags = LWS_O_RDONLY;\n#if defined(WIN32) && defined(LWS_HAVE__STAT32I64)\n\tstruct _stat32i64 st;\n#else\n\tstruct stat st;\n#endif\n\tint spin = 0;\n#endif\n\tchar path[256], sym[512];\n\tunsigned char *p = (unsigned char *)sym + 32 + LWS_PRE, *start = p;\n\tunsigned char *end = p + sizeof(sym) - 32 - LWS_PRE;\n#if !defined(WIN32) && !defined(LWS_WITH_ESP32)\n\tsize_t len;\n#endif\n\tint n;\n\n\twsi->handling_404 = 0;\n\tif (!wsi->vhost)\n\t\treturn -1;\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n\tif (wsi->vhost->http.error_document_404 &&\n\t    !strcmp(uri, wsi->vhost->http.error_document_404))\n\t\twsi->handling_404 = 1;\n#endif\n\n\tlws_snprintf(path, sizeof(path) - 1, \"%s/%s\", origin, uri);\n\n#if !defined(_WIN32_WCE)\n\n\tfflags |= lws_vfs_prepare_flags(wsi);\n\n\tdo {\n\t\tspin++;\n\t\tfops = lws_vfs_select_fops(wsi->context->fops, path, &vpath);\n\n\t\tif (wsi->http.fop_fd)\n\t\t\tlws_vfs_file_close(&wsi->http.fop_fd);\n\n\t\twsi->http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops,\n\t\t\t\t\t\t\tpath, vpath, &fflags);\n\t\tif (!wsi->http.fop_fd) {\n\t\t\tlwsl_info(\"%s: Unable to open '%s': errno %d\\n\",\n\t\t\t\t  __func__, path, errno);\n\n\t\t\treturn -1;\n\t\t}\n\n\t\t/* if it can't be statted, don't try */\n\t\tif (fflags & LWS_FOP_FLAG_VIRTUAL)\n\t\t\tbreak;\n#if defined(LWS_WITH_ESP32)\n\t\tbreak;\n#endif\n#if !defined(WIN32)\n\t\tif (fstat(wsi->http.fop_fd->fd, &st)) {\n\t\t\tlwsl_info(\"unable to stat %s\\n\", path);\n\t\t\tgoto bail;\n\t\t}\n#else\n#if defined(LWS_HAVE__STAT32I64)\n\t\tif (_stat32i64(path, &st)) {\n\t\t\tlwsl_info(\"unable to stat %s\\n\", path);\n\t\t\tgoto bail;\n\t\t}\n#else\n\t\tif (stat(path, &st)) {\n\t\t\tlwsl_info(\"unable to stat %s\\n\", path);\n\t\t\tgoto bail;\n\t\t}\n#endif\n#endif\n\n\t\twsi->http.fop_fd->mod_time = (uint32_t)st.st_mtime;\n\t\tfflags |= LWS_FOP_FLAG_MOD_TIME_VALID;\n\n#if !defined(WIN32) && !defined(LWS_WITH_ESP32)\n\t\tif ((S_IFMT & st.st_mode) == S_IFLNK) {\n\t\t\tlen = readlink(path, sym, sizeof(sym) - 1);\n\t\t\tif (len) {\n\t\t\t\tlwsl_err(\"Failed to read link %s\\n\", path);\n\t\t\t\tgoto bail;\n\t\t\t}\n\t\t\tsym[len] = '\\0';\n\t\t\tlwsl_debug(\"symlink %s -> %s\\n\", path, sym);\n\t\t\tlws_snprintf(path, sizeof(path) - 1, \"%s\", sym);\n\t\t}\n#endif\n\t\tif ((S_IFMT & st.st_mode) == S_IFDIR) {\n\t\t\tlwsl_debug(\"default filename append to dir\\n\");\n\t\t\tlws_snprintf(path, sizeof(path) - 1, \"%s/%s/index.html\",\n\t\t\t\t origin, uri);\n\t\t}\n\n\t} while ((S_IFMT & st.st_mode) != S_IFREG && spin < 5);\n\n\tif (spin == 5)\n\t\tlwsl_err(\"symlink loop %s \\n\", path);\n\n\tn = sprintf(sym, \"%08llX%08lX\",\n\t\t    (unsigned long long)lws_vfs_get_length(wsi->http.fop_fd),\n\t\t    (unsigned long)lws_vfs_get_mod_time(wsi->http.fop_fd));\n\n\t/* disable ranges if IF_RANGE token invalid */\n\n\tif (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_RANGE))\n\t\tif (strcmp(sym, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_IF_RANGE)))\n\t\t\t/* differs - defeat Range: */\n\t\t\twsi->http.ah->frag_index[WSI_TOKEN_HTTP_RANGE] = 0;\n\n\tif (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH)) {\n\t\t/*\n\t\t * he thinks he has some version of it already,\n\t\t * check if the tag matches\n\t\t */\n\t\tif (!strcmp(sym, lws_hdr_simple_ptr(wsi,\n\t\t\t\t\tWSI_TOKEN_HTTP_IF_NONE_MATCH))) {\n\n\t\t\tlwsl_debug(\"%s: ETAG match %s %s\\n\", __func__,\n\t\t\t\t   uri, origin);\n\n\t\t\t/* we don't need to send the payload */\n\t\t\tif (lws_add_http_header_status(wsi,\n\t\t\t\t\tHTTP_STATUS_NOT_MODIFIED, &p, end))\n\t\t\t\treturn -1;\n\n\t\t\tif (lws_add_http_header_by_token(wsi,\n\t\t\t\t\tWSI_TOKEN_HTTP_ETAG,\n\t\t\t\t\t(unsigned char *)sym, n, &p, end))\n\t\t\t\treturn -1;\n\n\t\t\tif (lws_finalize_http_header(wsi, &p, end))\n\t\t\t\treturn -1;\n\n\t\t\tn = lws_write(wsi, start, p - start,\n\t\t\t\t      LWS_WRITE_HTTP_HEADERS |\n\t\t\t\t      LWS_WRITE_H2_STREAM_END);\n\t\t\tif (n != (p - start)) {\n\t\t\t\tlwsl_err(\"_write returned %d from %ld\\n\", n,\n\t\t\t\t\t (long)(p - start));\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tlws_vfs_file_close(&wsi->http.fop_fd);\n\n\t\t\treturn lws_http_transaction_completed(wsi);\n\t\t}\n\t}\n\n\tif (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ETAG,\n\t\t\t(unsigned char *)sym, n, &p, end))\n\t\treturn -1;\n#endif\n\n\tmimetype = lws_get_mimetype(path, m);\n\tif (!mimetype) {\n\t\tlwsl_err(\"unknown mimetype for %s\\n\", path);\n               goto bail;\n\t}\n\tif (!mimetype[0])\n\t\tlwsl_debug(\"sending no mimetype for %s\\n\", path);\n\n\twsi->sending_chunked = 0;\n\n\t/*\n\t * check if this is in the list of file suffixes to be interpreted by\n\t * a protocol\n\t */\n\twhile (pvo) {\n\t\tn = (int)strlen(path);\n\t\tif (n > (int)strlen(pvo->name) &&\n\t\t    !strcmp(&path[n - strlen(pvo->name)], pvo->name)) {\n\t\t\twsi->interpreting = 1;\n\t\t\tif (!wsi->http2_substream)\n\t\t\t\twsi->sending_chunked = 1;\n\t\t\twsi->protocol_interpret_idx =\n\t\t\t\t\t(char)(lws_intptr_t)pvo->value;\n\t\t\tlwsl_info(\"want %s interpreted by %s\\n\", path,\n\t\t\t\t    wsi->vhost->protocols[\n\t\t\t\t         (int)(lws_intptr_t)(pvo->value)].name);\n\t\t\twsi->protocol = &wsi->vhost->protocols[\n\t\t\t                       (int)(lws_intptr_t)(pvo->value)];\n\t\t\tif (lws_ensure_user_space(wsi))\n\t\t\t\treturn -1;\n\t\t\tbreak;\n\t\t}\n\t\tpvo = pvo->next;\n\t}\n\n\tif (m->protocol) {\n\t\tconst struct lws_protocols *pp = lws_vhost_name_to_protocol(\n\t\t\t\t\t\t       wsi->vhost, m->protocol);\n\n\t\tif (lws_bind_protocol(wsi, pp))\n\t\t\treturn 1;\n\t\targs.p = (char *)p;\n\t\targs.max_len = lws_ptr_diff(end, p);\n\t\tif (pp->callback(wsi, LWS_CALLBACK_ADD_HEADERS,\n\t\t\t\t\t  wsi->user_space, &args, 0))\n\t\t\treturn -1;\n\t\tp = (unsigned char *)args.p;\n\t}\n\n\tn = lws_serve_http_file(wsi, path, mimetype, (char *)start,\n\t\t\t\tlws_ptr_diff(p, start));\n\n\tif (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))\n\t\treturn -1; /* error or can't reuse connection: close the socket */\n\n\treturn 0;\nbail:\n\n\treturn -1;\n}\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\nconst struct lws_http_mount *\nlws_find_mount(struct lws *wsi, const char *uri_ptr, int uri_len)\n{\n\tconst struct lws_http_mount *hm, *hit = NULL;\n\tint best = 0;\n\n\thm = wsi->vhost->http.mount_list;\n\twhile (hm) {\n\t\tif (uri_len >= hm->mountpoint_len &&\n\t\t    !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) &&\n\t\t    (uri_ptr[hm->mountpoint_len] == '\\0' ||\n\t\t     uri_ptr[hm->mountpoint_len] == '/' ||\n\t\t     hm->mountpoint_len == 1)\n\t\t    ) {\n\t\t\tif (hm->origin_protocol == LWSMPRO_CALLBACK ||\n\t\t\t    ((hm->origin_protocol == LWSMPRO_CGI ||\n\t\t\t     lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI) ||\n\t\t\t     (wsi->http2_substream &&\n\t\t\t\tlws_hdr_total_length(wsi,\n\t\t\t\t\t\tWSI_TOKEN_HTTP_COLON_PATH)) ||\n\t\t\t     hm->protocol) &&\n\t\t\t    hm->mountpoint_len > best)) {\n\t\t\t\tbest = hm->mountpoint_len;\n\t\t\t\thit = hm;\n\t\t\t}\n\t\t}\n\t\thm = hm->mount_next;\n\t}\n\n\treturn hit;\n}\n#endif\n\n#if !defined(LWS_WITH_ESP32)\nstatic int\nlws_find_string_in_file(const char *filename, const char *string, int stringlen)\n{\n\tchar buf[128];\n\tint fd, match = 0, pos = 0, n = 0, hit = 0;\n\n\tfd = lws_open(filename, O_RDONLY);\n\tif (fd < 0) {\n\t\tlwsl_err(\"can't open auth file: %s\\n\", filename);\n\t\treturn 0;\n\t}\n\n\twhile (1) {\n\t\tif (pos == n) {\n\t\t\tn = read(fd, buf, sizeof(buf));\n\t\t\tif (n <= 0) {\n\t\t\t\tif (match == stringlen)\n\t\t\t\t\thit = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpos = 0;\n\t\t}\n\n\t\tif (match == stringlen) {\n\t\t\tif (buf[pos] == '\\r' || buf[pos] == '\\n') {\n\t\t\t\thit = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmatch = 0;\n\t\t}\n\n\t\tif (buf[pos] == string[match])\n\t\t\tmatch++;\n\t\telse\n\t\t\tmatch = 0;\n\n\t\tpos++;\n\t}\n\n\tclose(fd);\n\n\treturn hit;\n}\n#endif\n\nstatic int\nlws_unauthorised_basic_auth(struct lws *wsi)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tunsigned char *start = pt->serv_buf + LWS_PRE,\n\t\t      *p = start, *end = p + 512;\n\tchar buf[64];\n\tint n;\n\n\t/* no auth... tell him it is required */\n\n\tif (lws_add_http_header_status(wsi, HTTP_STATUS_UNAUTHORIZED, &p, end))\n\t\treturn -1;\n\n\tn = lws_snprintf(buf, sizeof(buf), \"Basic realm=\\\"lwsws\\\"\");\n\tif (lws_add_http_header_by_token(wsi,\n\t\t\tWSI_TOKEN_HTTP_WWW_AUTHENTICATE,\n\t\t\t(unsigned char *)buf, n, &p, end))\n\t\treturn -1;\n\n\tif (lws_finalize_http_header(wsi, &p, end))\n\t\treturn -1;\n\n\tn = lws_write(wsi, start, p - start, LWS_WRITE_HTTP_HEADERS |\n\t\t\t\t\t     LWS_WRITE_H2_STREAM_END);\n\tif (n < 0)\n\t\treturn -1;\n\n\treturn lws_http_transaction_completed(wsi);\n\n}\n\nint lws_clean_url(char *p)\n{\n\tif (p[0] == 'h' && p[1] == 't' && p[2] == 't' && p[3] == 'p') {\n\t\tp += 4;\n\t\tif (*p == 's')\n\t\tp++;\n\t\tif (*p == ':') {\n\t\t\tp++;\n\t\t\tif (*p == '/')\n\t\t\tp++;\n\t\t}\n\t}\n\n\twhile (*p) {\n\t\tif (p[0] == '/' && p[1] == '/') {\n\t\t\tchar *p1 = p;\n\t\t\twhile (*p1) {\n\t\t\t\t*p1 = p1[1];\n\t\t\t\tp1++;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tp++;\n\t}\n\n\treturn 0;\n}\n\nstatic const unsigned char methods[] = {\n\tWSI_TOKEN_GET_URI,\n\tWSI_TOKEN_POST_URI,\n\tWSI_TOKEN_OPTIONS_URI,\n\tWSI_TOKEN_PUT_URI,\n\tWSI_TOKEN_PATCH_URI,\n\tWSI_TOKEN_DELETE_URI,\n\tWSI_TOKEN_CONNECT,\n\tWSI_TOKEN_HEAD_URI,\n#ifdef LWS_WITH_HTTP2\n\tWSI_TOKEN_HTTP_COLON_PATH,\n#endif\n};\n\nstatic int\nlws_http_get_uri_and_method(struct lws *wsi, char **puri_ptr, int *puri_len)\n{\n\tint n, count = 0;\n\n\tfor (n = 0; n < (int)LWS_ARRAY_SIZE(methods); n++)\n\t\tif (lws_hdr_total_length(wsi, methods[n]))\n\t\t\tcount++;\n\tif (!count) {\n\t\tlwsl_warn(\"Missing URI in HTTP request\\n\");\n\t\treturn -1;\n\t}\n\n\tif (count != 1 &&\n\t    !(wsi->http2_substream &&\n\t      lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COLON_PATH))) {\n\t\tlwsl_warn(\"multiple methods?\\n\");\n\t\treturn -1;\n\t}\n\n\tfor (n = 0; n < (int)LWS_ARRAY_SIZE(methods); n++)\n\t\tif (lws_hdr_total_length(wsi, methods[n])) {\n\t\t\t*puri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);\n\t\t\t*puri_len = lws_hdr_total_length(wsi, methods[n]);\n\t\t\treturn n;\n\t\t}\n\n\treturn -1;\n}\n\nint\nlws_http_action(struct lws *wsi)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tenum http_connection_type connection_type;\n\tenum http_version request_version;\n\tchar content_length_str[32];\n\tstruct lws_process_html_args args;\n\tconst struct lws_http_mount *hit = NULL;\n\tunsigned int n;\n\tchar http_version_str[10];\n\tchar http_conn_str[20];\n\tint http_version_len;\n\tchar *uri_ptr = NULL, *s;\n\tint uri_len = 0, meth;\n\tstatic const char * const oprot[] = {\n\t\t\"http://\", \"https://\"\n\t};\n\n\tmeth = lws_http_get_uri_and_method(wsi, &uri_ptr, &uri_len);\n\tif (meth < 0 || meth >= (int)LWS_ARRAY_SIZE(method_names))\n\t\tgoto bail_nuke_ah;\n\n\t/* we insist on absolute paths */\n\n\tif (!uri_ptr || uri_ptr[0] != '/') {\n\t\tlws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);\n\n\t\tgoto bail_nuke_ah;\n\t}\n\n\tlwsl_info(\"Method: '%s' (%d), request for '%s'\\n\", method_names[meth],\n\t\t  meth, uri_ptr);\n\n\tif (wsi->role_ops && wsi->role_ops->check_upgrades)\n\t\tswitch (wsi->role_ops->check_upgrades(wsi)) {\n\t\tcase LWS_UPG_RET_DONE:\n\t\t\treturn 0;\n\t\tcase LWS_UPG_RET_CONTINUE:\n\t\t\tbreak;\n\t\tcase LWS_UPG_RET_BAIL:\n\t\t\tgoto bail_nuke_ah;\n\t\t}\n\n\tif (lws_ensure_user_space(wsi))\n\t\tgoto bail_nuke_ah;\n\n\t/* HTTP header had a content length? */\n\n\twsi->http.rx_content_length = 0;\n\tif (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||\n\t\tlws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||\n\t\tlws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))\n\t\twsi->http.rx_content_length = 100 * 1024 * 1024;\n\n\tif (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {\n\t\tlws_hdr_copy(wsi, content_length_str,\n\t\t\t     sizeof(content_length_str) - 1,\n\t\t\t     WSI_TOKEN_HTTP_CONTENT_LENGTH);\n\t\twsi->http.rx_content_length = atoll(content_length_str);\n\t}\n\n\tif (wsi->http2_substream) {\n\t\twsi->http.request_version = HTTP_VERSION_2;\n\t} else {\n\t\t/* http_version? Default to 1.0, override with token: */\n\t\trequest_version = HTTP_VERSION_1_0;\n\n\t\t/* Works for single digit HTTP versions. : */\n\t\thttp_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);\n\t\tif (http_version_len > 7) {\n\t\t\tlws_hdr_copy(wsi, http_version_str,\n\t\t\t\t     sizeof(http_version_str) - 1,\n\t\t\t\t     WSI_TOKEN_HTTP);\n\t\t\tif (http_version_str[5] == '1' &&\n\t\t\t    http_version_str[7] == '1')\n\t\t\t\trequest_version = HTTP_VERSION_1_1;\n\t\t}\n\t\twsi->http.request_version = request_version;\n\n\t\t/* HTTP/1.1 defaults to \"keep-alive\", 1.0 to \"close\" */\n\t\tif (request_version == HTTP_VERSION_1_1)\n\t\t\tconnection_type = HTTP_CONNECTION_KEEP_ALIVE;\n\t\telse\n\t\t\tconnection_type = HTTP_CONNECTION_CLOSE;\n\n\t\t/* Override default if http \"Connection:\" header: */\n\t\tif (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {\n\t\t\tlws_hdr_copy(wsi, http_conn_str,\n\t\t\t\t     sizeof(http_conn_str) - 1,\n\t\t\t\t     WSI_TOKEN_CONNECTION);\n\t\t\thttp_conn_str[sizeof(http_conn_str) - 1] = '\\0';\n\t\t\tif (!strcasecmp(http_conn_str, \"keep-alive\"))\n\t\t\t\tconnection_type = HTTP_CONNECTION_KEEP_ALIVE;\n\t\t\telse\n\t\t\t\tif (!strcasecmp(http_conn_str, \"close\"))\n\t\t\t\t\tconnection_type = HTTP_CONNECTION_CLOSE;\n\t\t}\n\t\twsi->http.connection_type = connection_type;\n\t}\n\n\tn = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,\n\t\t\t\t    wsi->user_space, uri_ptr, uri_len);\n\tif (n) {\n\t\tlwsl_info(\"LWS_CALLBACK_HTTP closing\\n\");\n\n\t\treturn 1;\n\t}\n\t/*\n\t * if there is content supposed to be coming,\n\t * put a timeout on it having arrived\n\t */\n\tlws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,\n\t\t\twsi->context->timeout_secs);\n#ifdef LWS_WITH_TLS\n\tif (wsi->tls.redirect_to_https) {\n\t\t/*\n\t\t * we accepted http:// only so we could redirect to\n\t\t * https://, so issue the redirect.  Create the redirection\n\t\t * URI from the host: header and ignore the path part\n\t\t */\n\t\tunsigned char *start = pt->serv_buf + LWS_PRE, *p = start,\n\t\t\t      *end = p + 512;\n\n\t\tif (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))\n\t\t\tgoto bail_nuke_ah;\n\n\t\tn = sprintf((char *)end, \"https://%s/\",\n\t\t\t    lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));\n\n\t\tn = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,\n\t\t\t\t      end, n, &p, end);\n\t\tif ((int)n < 0)\n\t\t\tgoto bail_nuke_ah;\n\n\t\treturn lws_http_transaction_completed(wsi);\n\t}\n#endif\n\n#ifdef LWS_WITH_ACCESS_LOG\n\tlws_prepare_access_log_info(wsi, uri_ptr, meth);\n#endif\n\n\t/* can we serve it from the mount list? */\n\n\thit = lws_find_mount(wsi, uri_ptr, uri_len);\n\tif (!hit) {\n\t\t/* deferred cleanup and reset to protocols[0] */\n\n\t\tlwsl_info(\"no hit\\n\");\n\n\t\tif (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))\n\t\t\treturn 1;\n\n\t\tlwsi_set_state(wsi, LRS_DOING_TRANSACTION);\n\n\t\tn = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,\n\t\t\t\t    wsi->user_space, uri_ptr, uri_len);\n\n\t\tgoto after;\n\t}\n\n\ts = uri_ptr + hit->mountpoint_len;\n\n\t/*\n\t * if we have a mountpoint like https://xxx.com/yyy\n\t * there is an implied / at the end for our purposes since\n\t * we can only mount on a \"directory\".\n\t *\n\t * But if we just go with that, the browser cannot understand\n\t * that he is actually looking down one \"directory level\", so\n\t * even though we give him /yyy/abc.html he acts like the\n\t * current directory level is /.  So relative urls like \"x.png\"\n\t * wrongly look outside the mountpoint.\n\t *\n\t * Therefore if we didn't come in on a url with an explicit\n\t * / at the end, we must redirect to add it so the browser\n\t * understands he is one \"directory level\" down.\n\t */\n\tif ((hit->mountpoint_len > 1 ||\n\t     (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||\n\t      hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&\n\t    (*s != '/' ||\n\t     (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||\n\t      hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&\n\t    (hit->origin_protocol != LWSMPRO_CGI &&\n\t     hit->origin_protocol != LWSMPRO_CALLBACK)) {\n\t\tunsigned char *start = pt->serv_buf + LWS_PRE,\n\t\t\t      *p = start, *end = p + 512;\n\n\t\tlwsl_debug(\"Doing 301 '%s' org %s\\n\", s, hit->origin);\n\n\t\t/* > at start indicates deal with by redirect */\n\t\tif (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||\n\t\t    hit->origin_protocol == LWSMPRO_REDIR_HTTPS)\n\t\t\tn = lws_snprintf((char *)end, 256, \"%s%s\",\n\t\t\t\t    oprot[hit->origin_protocol & 1],\n\t\t\t\t    hit->origin);\n\t\telse {\n\t\t\tif (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {\n\t\t\t\tif (!lws_hdr_total_length(wsi,\n\t\t\t\t\t\tWSI_TOKEN_HTTP_COLON_AUTHORITY))\n\t\t\t\t\tgoto bail_nuke_ah;\n\t\t\t\tn = lws_snprintf((char *)end, 256,\n\t\t\t\t    \"%s%s%s/\", oprot[!!lws_is_ssl(wsi)],\n\t\t\t\t    lws_hdr_simple_ptr(wsi,\n\t\t\t\t\t\tWSI_TOKEN_HTTP_COLON_AUTHORITY),\n\t\t\t\t    uri_ptr);\n\t\t\t} else\n\t\t\t\tn = lws_snprintf((char *)end, 256,\n\t\t\t\t    \"%s%s%s/\", oprot[!!lws_is_ssl(wsi)],\n\t\t\t\t    lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),\n\t\t\t\t    uri_ptr);\n\t\t}\n\n\t\tlws_clean_url((char *)end);\n\t\tn = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,\n\t\t\t\t      end, n, &p, end);\n\t\tif ((int)n < 0)\n\t\t\tgoto bail_nuke_ah;\n\n\t\treturn lws_http_transaction_completed(wsi);\n\t}\n\n\t/* basic auth? */\n\n\tif (hit->basic_auth_login_file) {\n\t\tchar b64[160], plain[(sizeof(b64) * 3) / 4];\n\t\tint m;\n\n\t\t/* Did he send auth? */\n\t\tif (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_AUTHORIZATION))\n\t\t\treturn lws_unauthorised_basic_auth(wsi);\n\n\t\tn = HTTP_STATUS_FORBIDDEN;\n\n\t\tm = lws_hdr_copy(wsi, b64, sizeof(b64),\n\t\t\t\t WSI_TOKEN_HTTP_AUTHORIZATION);\n\t\tif (m < 7) {\n\t\t\tlwsl_err(\"b64 auth too long\\n\");\n\t\t\tgoto transaction_result_n;\n\t\t}\n\n\t\tb64[5] = '\\0';\n\t\tif (strcasecmp(b64, \"Basic\")) {\n\t\t\tlwsl_err(\"auth missing basic: %s\\n\", b64);\n\t\t\tgoto transaction_result_n;\n\t\t}\n\n\t\t/* It'll be like Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l */\n\n\t\tm = lws_b64_decode_string(b64 + 6, plain, sizeof(plain));\n\t\tif (m < 0) {\n\t\t\tlwsl_err(\"plain auth too long\\n\");\n\t\t\tgoto transaction_result_n;\n\t\t}\n\n\t\tif (!lws_find_string_in_file(hit->basic_auth_login_file,\n\t\t\t\t\t     plain, m)) {\n\t\t\tlwsl_err(\"basic auth lookup failed\\n\");\n\t\t\treturn lws_unauthorised_basic_auth(wsi);\n\t\t}\n\n\t\tlwsl_info(\"basic auth accepted\\n\");\n\n\t\t/* accept the auth */\n\t}\n\n#if defined(LWS_WITH_HTTP_PROXY)\n\t/*\n\t * The mount is a reverse proxy?\n\t */\n\n\tif (hit->origin_protocol == LWSMPRO_HTTPS ||\n\t    hit->origin_protocol == LWSMPRO_HTTP)  {\n\t\tstruct lws_client_connect_info i;\n\t\tchar ads[96], rpath[256], *pcolon, *pslash, *p;\n\t\tint n, na;\n\n\t\tmemset(&i, 0, sizeof(i));\n\t\ti.context = lws_get_context(wsi);\n\n\t\tpcolon = strchr(hit->origin, ':');\n\t\tpslash = strchr(hit->origin, '/');\n\t\tif (!pslash) {\n\t\t\tlwsl_err(\"Proxy mount origin '%s' must have /\\n\",\n\t\t\t\t hit->origin);\n\t\t\treturn -1;\n\t\t}\n\t\tif (pcolon > pslash)\n\t\t\tpcolon = NULL;\n\n\t\tif (pcolon)\n\t\t\tn = pcolon - hit->origin;\n\t\telse\n\t\t\tn = pslash - hit->origin;\n\n\t\tif (n >= (int)sizeof(ads) - 2)\n\t\t\tn = sizeof(ads) - 2;\n\n\t\tmemcpy(ads, hit->origin, n);\n\t\tads[n] = '\\0';\n\n\t\ti.address = ads;\n\t\ti.port = 80;\n\t\tif (hit->origin_protocol == LWSMPRO_HTTPS) {\n\t\t\ti.port = 443;\n\t\t\ti.ssl_connection = 1;\n\t\t}\n\t\tif (pcolon)\n\t\t\ti.port = atoi(pcolon + 1);\n\n\t\tlws_snprintf(rpath, sizeof(rpath) - 1, \"/%s/%s\", pslash + 1,\n\t\t\t     uri_ptr + hit->mountpoint_len);\n\t\tlws_clean_url(rpath);\n\t\tna = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_URI_ARGS);\n\t\tif (na) {\n\t\t\tp = rpath + strlen(rpath);\n\t\t\t*p++ = '?';\n\t\t\tlws_hdr_copy(wsi, p, &rpath[sizeof(rpath) - 1] - p,\n\t\t\t\t     WSI_TOKEN_HTTP_URI_ARGS);\n\t\t\twhile (--na) {\n\t\t\t\tif (*p == '\\0')\n\t\t\t\t\t*p = '&';\n\t\t\t\tp++;\n\t\t\t}\n\t\t}\n\n\n\t\ti.path = rpath;\n\t\ti.host = i.address;\n\t\ti.origin = NULL;\n\t\ti.method = \"GET\";\n\t\ti.parent_wsi = wsi;\n\t\ti.uri_replace_from = hit->origin;\n\t\ti.uri_replace_to = hit->mountpoint;\n\n\t\tlwsl_notice(\"proxying to %s port %d url %s, ssl %d, \"\n\t\t\t    \"from %s, to %s\\n\",\n\t\t\t    i.address, i.port, i.path, i.ssl_connection,\n\t\t\t    i.uri_replace_from, i.uri_replace_to);\n\n\t\tif (!lws_client_connect_via_info(&i)) {\n\t\t\tlwsl_err(\"proxy connect fail\\n\");\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn 0;\n\t}\n#endif\n\n\t/*\n\t * A particular protocol callback is mounted here?\n\t *\n\t * For the duration of this http transaction, bind us to the\n\t * associated protocol\n\t */\n\tif (hit->origin_protocol == LWSMPRO_CALLBACK || hit->protocol) {\n\t\tconst struct lws_protocols *pp;\n\t\tconst char *name = hit->origin;\n\t\tif (hit->protocol)\n\t\t\tname = hit->protocol;\n\n\t\tpp = lws_vhost_name_to_protocol(wsi->vhost, name);\n\t\tif (!pp) {\n\t\t\tn = -1;\n\t\t\tlwsl_err(\"Unable to find plugin '%s'\\n\",\n\t\t\t\t hit->origin);\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (lws_bind_protocol(wsi, pp))\n\t\t\treturn 1;\n\n\t\targs.p = uri_ptr;\n\t\targs.len = uri_len;\n\t\targs.max_len = hit->auth_mask;\n\t\targs.final = 0; /* used to signal callback dealt with it */\n\t\targs.chunked = 0;\n\n\t\tn = wsi->protocol->callback(wsi,\n\t\t\t\t\t    LWS_CALLBACK_CHECK_ACCESS_RIGHTS,\n\t\t\t\t\t    wsi->user_space, &args, 0);\n\t\tif (n) {\n\t\t\tlws_return_http_status(wsi, HTTP_STATUS_UNAUTHORIZED,\n\t\t\t\t\t       NULL);\n\t\t\tgoto bail_nuke_ah;\n\t\t}\n\t\tif (args.final) /* callback completely handled it well */\n\t\t\treturn 0;\n\n\t\tif (hit->cgienv && wsi->protocol->callback(wsi,\n\t\t\t\tLWS_CALLBACK_HTTP_PMO,\n\t\t\t\twsi->user_space, (void *)hit->cgienv, 0))\n\t\t\treturn 1;\n\n\t\tif (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) {\n\t\t\tn = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,\n\t\t\t\t\t    wsi->user_space,\n\t\t\t\t\t    uri_ptr + hit->mountpoint_len,\n\t\t\t\t\t    uri_len - hit->mountpoint_len);\n\t\t\tgoto after;\n\t\t}\n\t}\n\n#ifdef LWS_WITH_CGI\n\t/* did we hit something with a cgi:// origin? */\n\tif (hit->origin_protocol == LWSMPRO_CGI) {\n\t\tconst char *cmd[] = {\n\t\t\tNULL, /* replace with cgi path */\n\t\t\tNULL\n\t\t};\n\n\t\tlwsl_debug(\"%s: cgi\\n\", __func__);\n\t\tcmd[0] = hit->origin;\n\n\t\tn = 5;\n\t\tif (hit->cgi_timeout)\n\t\t\tn = hit->cgi_timeout;\n\n\t\tn = lws_cgi(wsi, cmd, hit->mountpoint_len, n,\n\t\t\t    hit->cgienv);\n\t\tif (n) {\n\t\t\tlwsl_err(\"%s: cgi failed\\n\", __func__);\n\t\t\treturn -1;\n\t\t}\n\n\t\tgoto deal_body;\n\t}\n#endif\n\n\tn = (int)strlen(s);\n\tif (s[0] == '\\0' || (n == 1 && s[n - 1] == '/'))\n\t\ts = (char *)hit->def;\n\tif (!s)\n\t\ts = \"index.html\";\n\n\twsi->cache_secs = hit->cache_max_age;\n\twsi->cache_reuse = hit->cache_reusable;\n\twsi->cache_revalidate = hit->cache_revalidate;\n\twsi->cache_intermediaries = hit->cache_intermediaries;\n\n\tn = 1;\n\tif (hit->origin_protocol == LWSMPRO_FILE)\n\t\tn = lws_http_serve(wsi, s, hit->origin, hit);\n\tif (n) {\n\t\t/*\n\t\t * lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);\n\t\t */\n\t\tif (hit->protocol) {\n\t\t\tconst struct lws_protocols *pp =\n\t\t\t\t\tlws_vhost_name_to_protocol(\n\t\t\t\t\t\twsi->vhost, hit->protocol);\n\n\t\t\tif (lws_bind_protocol(wsi, pp))\n\t\t\t\treturn 1;\n\n\t\t\tn = pp->callback(wsi, LWS_CALLBACK_HTTP,\n\t\t\t\t\t wsi->user_space,\n\t\t\t\t\t uri_ptr + hit->mountpoint_len,\n\t\t\t\t\t uri_len - hit->mountpoint_len);\n\t\t} else\n\t\t\tn = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,\n\t\t\t\t    wsi->user_space, uri_ptr, uri_len);\n\t}\n\nafter:\n\tif (n) {\n\t\tlwsl_info(\"LWS_CALLBACK_HTTP closing\\n\");\n\n\t\treturn 1;\n\t}\n\n#ifdef LWS_WITH_CGI\ndeal_body:\n#endif\n\t/*\n\t * If we're not issuing a file, check for content_length or\n\t * HTTP keep-alive. No keep-alive header allocation for\n\t * ISSUING_FILE, as this uses HTTP/1.0.\n\t *\n\t * In any case, return 0 and let lws_read decide how to\n\t * proceed based on state\n\t */\n\tif (lwsi_state(wsi) != LRS_ISSUING_FILE) {\n\t\t/* Prepare to read body if we have a content length: */\n\t\tlwsl_debug(\"wsi->http.rx_content_length %lld %d %d\\n\",\n\t\t\t   (long long)wsi->http.rx_content_length,\n\t\t\t   wsi->upgraded_to_http2, wsi->http2_substream);\n\t\tif (wsi->http.rx_content_length > 0) {\n\t\t\tstruct lws_tokens ebuf;\n\t\t\tint m;\n\n\t\t\tlwsi_set_state(wsi, LRS_BODY);\n\t\t\tlwsl_info(\"%s: %p: LRS_BODY state set (0x%x)\\n\",\n\t\t\t\t    __func__, wsi, wsi->wsistate);\n\t\t\twsi->http.rx_content_remain =\n\t\t\t\t\twsi->http.rx_content_length;\n\n\t\t\t/*\n\t\t\t * At this point we have transitioned from deferred\n\t\t\t * action to expecting BODY on the stream wsi, if it's\n\t\t\t * in a bundle like h2.  So if the stream wsi has its\n\t\t\t * own buflist, we need to deal with that first.\n\t\t\t */\n\n\t\t\twhile (1) {\n\t\t\t\tebuf.len = (int)lws_buflist_next_segment_len(\n\t\t\t\t\t\t&wsi->buflist, (uint8_t **)&ebuf.token);\n\t\t\t\tif (!ebuf.len)\n\t\t\t\t\tbreak;\n\t\t\t\tlwsl_notice(\"%s: consuming %d\\n\", __func__, (int)ebuf.len);\n\t\t\t\tm = lws_read_h1(wsi, (uint8_t *)ebuf.token, ebuf.len);\n\t\t\t\tif (m < 0)\n\t\t\t\t\treturn -1;\n\n\t\t\t\tif (lws_buflist_aware_consume(wsi, &ebuf, m, 1))\n\t\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n\nbail_nuke_ah:\n\tlws_header_table_detach(wsi, 1);\n\n\treturn 1;\n\ntransaction_result_n:\n\tlws_return_http_status(wsi, n, NULL);\n\n\treturn lws_http_transaction_completed(wsi);\n}\n\nint\nlws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)\n{\n\tstruct lws_context *context = lws_get_context(wsi);\n\tunsigned char *obuf = *buf;\n#if defined(LWS_WITH_HTTP2)\n\tchar tbuf[128], *p;\n#endif\n\tsize_t olen = len;\n\tint n = 0, m, i;\n\n\tif (len >= 10000000) {\n\t\tlwsl_err(\"%s: assert: len %ld\\n\", __func__, (long)len);\n\t\tassert(0);\n\t}\n\n\tif (!wsi->http.ah) {\n\t\tlwsl_err(\"%s: assert: NULL ah\\n\", __func__);\n\t\tassert(0);\n\t}\n\n\twhile (len) {\n\t\tif (!lwsi_role_server(wsi) || !lwsi_role_http(wsi)) {\n\t\t\tlwsl_err(\"%s: bad wsi role 0x%x\\n\", __func__,\n\t\t\t\t\tlwsi_role(wsi));\n\t\t\tgoto bail_nuke_ah;\n\t\t}\n\n\t\ti = (int)len;\n\t\tm = lws_parse(wsi, *buf, &i);\n\t\tlwsl_info(\"%s: parsed count %d\\n\", __func__, (int)len - i);\n\t\t(*buf) += (int)len - i;\n\t\tlen = i;\n\t\tif (m) {\n\t\t\tif (m == 2) {\n\t\t\t\t/*\n\t\t\t\t * we are transitioning from http with\n\t\t\t\t * an AH, to raw.  Drop the ah and set\n\t\t\t\t * the mode.\n\t\t\t\t */\nraw_transition:\n\t\t\t\tlws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);\n\t\t\t\tlws_bind_protocol(wsi, &wsi->vhost->protocols[\n\t\t\t\t                        wsi->vhost->\n\t\t\t\t                        raw_protocol_index]);\n\t\t\t\tlwsl_info(\"transition to raw vh %s prot %d\\n\",\n\t\t\t\t\t  wsi->vhost->name,\n\t\t\t\t\t  wsi->vhost->raw_protocol_index);\n\t\t\t\tif ((wsi->protocol->callback)(wsi,\n\t\t\t\t\t\tLWS_CALLBACK_RAW_ADOPT,\n\t\t\t\t\t\twsi->user_space, NULL, 0))\n\t\t\t\t\tgoto bail_nuke_ah;\n\n\t\t\t\tlws_role_transition(wsi, 0, LRS_ESTABLISHED,\n\t\t\t\t\t\t    &role_ops_raw_skt);\n\t\t\t\tlws_header_table_detach(wsi, 1);\n\n\t\t\t\tif (m == 2 && (wsi->protocol->callback)(wsi,\n\t\t\t\t\t\tLWS_CALLBACK_RAW_RX,\n\t\t\t\t\t\twsi->user_space, obuf, olen))\n\t\t\t\t\treturn 1;\n\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tlwsl_info(\"lws_parse failed\\n\");\n\t\t\tgoto bail_nuke_ah;\n\t\t}\n\n\t\tif (wsi->http.ah->parser_state != WSI_PARSING_COMPLETE)\n\t\t\tcontinue;\n\n\t\tlwsl_parser(\"%s: lws_parse sees parsing complete\\n\", __func__);\n\n\t\t/* select vhost */\n\n\t\tif (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {\n\t\t\tstruct lws_vhost *vhost = lws_select_vhost(\n\t\t\t\tcontext, wsi->vhost->listen_port,\n\t\t\t\tlws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));\n\n\t\t\tif (vhost)\n\t\t\t\twsi->vhost = vhost;\n\t\t} else\n\t\t\tlwsl_info(\"no host\\n\");\n\n\t\tif (!lwsi_role_h2(wsi) || !lwsi_role_server(wsi)) {\n\t\t\twsi->vhost->conn_stats.h1_trans++;\n\t\t\tif (!wsi->conn_stat_done) {\n\t\t\t\twsi->vhost->conn_stats.h1_conn++;\n\t\t\t\twsi->conn_stat_done = 1;\n\t\t\t}\n\t\t}\n\n\t\t/* check for unwelcome guests */\n\n\t\tif (wsi->context->reject_service_keywords) {\n\t\t\tconst struct lws_protocol_vhost_options *rej =\n\t\t\t\t\twsi->context->reject_service_keywords;\n\t\t\tchar ua[384], *msg = NULL;\n\n\t\t\tif (lws_hdr_copy(wsi, ua, sizeof(ua) - 1,\n\t\t\t\t\t WSI_TOKEN_HTTP_USER_AGENT) > 0) {\n#ifdef LWS_WITH_ACCESS_LOG\n\t\t\t\tchar *uri_ptr = NULL;\n\t\t\t\tint meth, uri_len;\n#endif\n\t\t\t\tua[sizeof(ua) - 1] = '\\0';\n\t\t\t\twhile (rej) {\n\t\t\t\t\tif (!strstr(ua, rej->name)) {\n\t\t\t\t\t\trej = rej->next;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tmsg = strchr(rej->value, ' ');\n\t\t\t\t\tif (msg)\n\t\t\t\t\t\tmsg++;\n\t\t\t\t\tlws_return_http_status(wsi,\n\t\t\t\t\t\tatoi(rej->value), msg);\n#ifdef LWS_WITH_ACCESS_LOG\n\t\t\t\t\tmeth = lws_http_get_uri_and_method(wsi,\n\t\t\t\t\t\t\t&uri_ptr, &uri_len);\n\t\t\t\t\tif (meth >= 0)\n\t\t\t\t\t\tlws_prepare_access_log_info(wsi,\n\t\t\t\t\t\t\t\turi_ptr, meth);\n\n\t\t\t\t\t/* wsi close will do the log */\n#endif\n\t\t\t\t\twsi->vhost->conn_stats.rejected++;\n\t\t\t\t\t/*\n\t\t\t\t\t * We don't want anything from\n\t\t\t\t\t * this rejected guy.  Follow\n\t\t\t\t\t * the close flow, not the\n\t\t\t\t\t * transaction complete flow.\n\t\t\t\t\t */\n\t\t\t\t\tgoto bail_nuke_ah;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\tif (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECT)) {\n\t\t\tlwsl_info(\"Changing to RAW mode\\n\");\n\t\t\tm = 0;\n\t\t\tgoto raw_transition;\n\t\t}\n\n\t\tlwsi_set_state(wsi, LRS_PRE_WS_SERVING_ACCEPT);\n\t\tlws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);\n\n\t\t/* is this websocket protocol or normal http 1.0? */\n\n\t\tif (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {\n\t\t\tif (!strcasecmp(lws_hdr_simple_ptr(wsi,\n\t\t\t\t\t\t\t   WSI_TOKEN_UPGRADE),\n\t\t\t\t\t\"websocket\")) {\n#if defined(LWS_ROLE_WS)\n\t\t\t\twsi->vhost->conn_stats.ws_upg++;\n\t\t\t\tlwsl_info(\"Upgrade to ws\\n\");\n\t\t\t\tgoto upgrade_ws;\n#endif\n\t\t\t}\n#if defined(LWS_WITH_HTTP2)\n\t\t\tif (!strcasecmp(lws_hdr_simple_ptr(wsi,\n\t\t\t\t\t\t\t   WSI_TOKEN_UPGRADE),\n\t\t\t\t\t\"h2c\")) {\n\t\t\t\twsi->vhost->conn_stats.h2_upg++;\n\t\t\t\tlwsl_info(\"Upgrade to h2c\\n\");\n\t\t\t\tgoto upgrade_h2c;\n\t\t\t}\n#endif\n\t\t\tlwsl_info(\"Unknown upgrade\\n\");\n\t\t\t/* dunno what he wanted to upgrade to */\n\t\t\tgoto bail_nuke_ah;\n\t\t}\n\n\t\t/* no upgrade ack... he remained as HTTP */\n\n\t\tlwsl_info(\"%s: %p: No upgrade\\n\", __func__, wsi);\n\n\t\tlwsi_set_state(wsi, LRS_ESTABLISHED);\n\t\twsi->http.fop_fd = NULL;\n\n\t\tlwsl_debug(\"%s: wsi %p: ah %p\\n\", __func__, (void *)wsi,\n\t\t\t   (void *)wsi->http.ah);\n\n\t\tn = lws_http_action(wsi);\n\n\t\treturn n;\n\n#if defined(LWS_WITH_HTTP2)\nupgrade_h2c:\n\t\tif (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {\n\t\t\tlwsl_info(\"missing http2_settings\\n\");\n\t\t\tgoto bail_nuke_ah;\n\t\t}\n\n\t\tlwsl_info(\"h2c upgrade...\\n\");\n\n\t\tp = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);\n\t\t/* convert the peer's HTTP-Settings */\n\t\tn = lws_b64_decode_string(p, tbuf, sizeof(tbuf));\n\t\tif (n < 0) {\n\t\t\tlwsl_parser(\"HTTP2_SETTINGS too long\\n\");\n\t\t\treturn 1;\n\t\t}\n\n\t\t/* adopt the header info */\n\n\t\tif (!wsi->h2.h2n) {\n\t\t\twsi->h2.h2n = lws_zalloc(sizeof(*wsi->h2.h2n),\n\t\t\t\t\t\t   \"h2n\");\n\t\t\tif (!wsi->h2.h2n)\n\t\t\t\treturn 1;\n\t\t}\n\n\t\tlws_h2_init(wsi);\n\n\t\t/* HTTP2 union */\n\n\t\tlws_h2_settings(wsi, &wsi->h2.h2n->set, (unsigned char *)tbuf, n);\n\n\t\tlws_hpack_dynamic_size(wsi, wsi->h2.h2n->set.s[\n\t\t                                      H2SET_HEADER_TABLE_SIZE]);\n\n\t\tstrcpy(tbuf, \"HTTP/1.1 101 Switching Protocols\\x0d\\x0a\"\n\t\t\t      \"Connection: Upgrade\\x0d\\x0a\"\n\t\t\t      \"Upgrade: h2c\\x0d\\x0a\\x0d\\x0a\");\n\t\tm = (int)strlen(tbuf);\n\t\tn = lws_issue_raw(wsi, (unsigned char *)tbuf, m);\n\t\tif (n != m) {\n\t\t\tlwsl_debug(\"http2 switch: ERROR writing to socket\\n\");\n\t\t\treturn 1;\n\t\t}\n\n\t\tlwsi_set_state(wsi, LRS_H2_AWAIT_PREFACE);\n\t\twsi->upgraded_to_http2 = 1;\n\n\t\treturn 0;\n#endif\n#if defined(LWS_ROLE_WS)\nupgrade_ws:\n\t\tif (lws_process_ws_upgrade(wsi))\n\t\t\tgoto bail_nuke_ah;\n\n\t\treturn 0;\n#endif\n\t} /* while all chars are handled */\n\n\treturn 0;\n\nbail_nuke_ah:\n\t/* drop the header info */\n\tlws_header_table_detach(wsi, 1);\n\n\treturn 1;\n}\n\n\nstatic int\nlws_get_idlest_tsi(struct lws_context *context)\n{\n\tunsigned int lowest = ~0;\n\tint n = 0, hit = -1;\n\n\tfor (; n < context->count_threads; n++) {\n\t\tif ((unsigned int)context->pt[n].fds_count !=\n\t\t    context->fd_limit_per_thread - 1 &&\n\t\t    (unsigned int)context->pt[n].fds_count < lowest) {\n\t\t\tlowest = context->pt[n].fds_count;\n\t\t\thit = n;\n\t\t}\n\t}\n\n\treturn hit;\n}\n\nstruct lws *\nlws_create_new_server_wsi(struct lws_vhost *vhost, int fixed_tsi)\n{\n\tstruct lws *new_wsi;\n\tint n = fixed_tsi;\n\n\tif (n < 0)\n\t\tn = lws_get_idlest_tsi(vhost->context);\n\n\tif (n < 0) {\n\t\tlwsl_err(\"no space for new conn\\n\");\n\t\treturn NULL;\n\t}\n\n\tnew_wsi = lws_zalloc(sizeof(struct lws), \"new server wsi\");\n\tif (new_wsi == NULL) {\n\t\tlwsl_err(\"Out of memory for new connection\\n\");\n\t\treturn NULL;\n\t}\n\n\tnew_wsi->tsi = n;\n\tlwsl_debug(\"new wsi %p joining vhost %s, tsi %d\\n\", new_wsi,\n\t\t   vhost->name, new_wsi->tsi);\n\n\tnew_wsi->vhost = vhost;\n\tnew_wsi->context = vhost->context;\n\tnew_wsi->pending_timeout = NO_PENDING_TIMEOUT;\n\tnew_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;\n\n\t/* initialize the instance struct */\n\n\tlwsi_set_state(new_wsi, LRS_UNCONNECTED);\n\tnew_wsi->hdr_parsing_completed = 0;\n\n#ifdef LWS_WITH_TLS\n\tnew_wsi->tls.use_ssl = LWS_SSL_ENABLED(vhost);\n#endif\n\n\t/*\n\t * these can only be set once the protocol is known\n\t * we set an un-established connection's protocol pointer\n\t * to the start of the supported list, so it can look\n\t * for matching ones during the handshake\n\t */\n\tnew_wsi->protocol = vhost->protocols;\n\tnew_wsi->user_space = NULL;\n\tnew_wsi->desc.sockfd = LWS_SOCK_INVALID;\n\tnew_wsi->position_in_fds_table = LWS_NO_FDS_POS;\n\n\tvhost->context->count_wsi_allocated++;\n\n\t/*\n\t * outermost create notification for wsi\n\t * no user_space because no protocol selection\n\t */\n\tvhost->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,\n\t\t\t\t       NULL, NULL, 0);\n\n\treturn new_wsi;\n}\n\nLWS_VISIBLE int LWS_WARN_UNUSED_RESULT\nlws_http_transaction_completed(struct lws *wsi)\n{\n\tint n = NO_PENDING_TIMEOUT;\n\n\tif (wsi->trunc_len) {\n\t\t/*\n\t\t * ...so he tried to send something large as the http reply,\n\t\t * it went as a partial, but he immediately said the\n\t\t * transaction was completed.\n\t\t *\n\t\t * Defer the transaction completed until the last part of the\n\t\t * partial is sent.\n\t\t */\n\t\tlwsl_notice(\"%s: deferring due to partial\\n\", __func__);\n\t\twsi->http.deferred_transaction_completed = 1;\n\n\t\treturn 0;\n\t}\n\n\tlwsl_info(\"%s: wsi %p\\n\", __func__, wsi);\n\n\tlws_access_log(wsi);\n\n\tif (!wsi->hdr_parsing_completed) {\n\t\tchar peer[64];\n\t\tlws_get_peer_simple(wsi, peer, sizeof(peer) - 1);\n\t\tpeer[sizeof(peer) - 1] = '\\0';\n\t\tlwsl_notice(\"%s: (from %s) ignoring, ah parsing incomplete\\n\",\n\t\t\t\t__func__, peer);\n\t\treturn 0;\n\t}\n\n\t/* if we can't go back to accept new headers, drop the connection */\n\tif (wsi->http2_substream)\n\t\treturn 0;\n\n\tif (wsi->seen_zero_length_recv)\n\t\treturn 1;\n\n\tif (wsi->http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {\n\t\tlwsl_notice(\"%s: %p: close connection\\n\", __func__, wsi);\n\t\treturn 1;\n\t}\n\n\tif (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))\n\t\treturn 1;\n\n\t/*\n\t * otherwise set ourselves up ready to go again, but because we have no\n\t * idea about the wsi writability, we make put it in a holding state\n\t * until we can verify POLLOUT.  The part of this that confirms POLLOUT\n\t * with no partials is in lws_server_socket_service() below.\n\t */\n\tlwsl_debug(\"%s: %p: setting DEF_ACT from 0x%x\\n\", __func__,\n\t\t   wsi, wsi->wsistate);\n\tlwsi_set_state(wsi, LRS_DEFERRING_ACTION);\n\twsi->http.tx_content_length = 0;\n\twsi->http.tx_content_remain = 0;\n\twsi->hdr_parsing_completed = 0;\n#ifdef LWS_WITH_ACCESS_LOG\n\twsi->http.access_log.sent = 0;\n#endif\n\n\tif (wsi->vhost->keepalive_timeout)\n\t\tn = PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE;\n\tlws_set_timeout(wsi, n, wsi->vhost->keepalive_timeout);\n\n\t/*\n\t * We already know we are on http1.1 / keepalive and the next thing\n\t * coming will be another header set.\n\t *\n\t * If there is no pending rx and we still have the ah, drop it and\n\t * reacquire a new ah when the new headers start to arrive.  (Otherwise\n\t * we needlessly hog an ah indefinitely.)\n\t *\n\t * However if there is pending rx and we know from the keepalive state\n\t * that is already at least the start of another header set, simply\n\t * reset the existing header table and keep it.\n\t */\n\tif (wsi->http.ah) {\n\t\t// lws_buflist_describe(&wsi->buflist, wsi);\n\t\tif (!lws_buflist_next_segment_len(&wsi->buflist, NULL)) {\n\t\t\tlwsl_info(\"%s: %p: nothing in buflist so detaching ah\\n\",\n\t\t\t\t  __func__, wsi);\n\t\t\tlws_header_table_detach(wsi, 1);\n#ifdef LWS_WITH_TLS\n\t\t\t/*\n\t\t\t * additionally... if we are hogging an SSL instance\n\t\t\t * with no pending pipelined headers (or ah now), and\n\t\t\t * SSL is scarce, drop this connection without waiting\n\t\t\t */\n\n\t\t\tif (wsi->vhost->tls.use_ssl &&\n\t\t\t    wsi->context->simultaneous_ssl_restriction &&\n\t\t\t    wsi->context->simultaneous_ssl ==\n\t\t\t\t   wsi->context->simultaneous_ssl_restriction) {\n\t\t\t\tlwsl_info(\"%s: simultaneous_ssl_restriction\\n\",\n\t\t\t\t\t  __func__);\n\t\t\t\treturn 1;\n\t\t\t}\n#endif\n\t\t} else {\n\t\t\tlwsl_info(\"%s: %p: resetting and keeping ah as pipeline\\n\",\n\t\t\t\t  __func__, wsi);\n\t\t\tlws_header_table_reset(wsi, 0);\n\t\t\t/*\n\t\t\t * If we kept the ah, we should restrict the amount\n\t\t\t * of time we are willing to keep it.  Otherwise it\n\t\t\t * will be bound the whole time the connection remains\n\t\t\t * open.\n\t\t\t */\n\t\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_HOLDING_AH,\n\t\t\t\t\twsi->vhost->keepalive_timeout);\n\t\t}\n\t\t/* If we're (re)starting on headers, need other implied init */\n\t\tif (wsi->http.ah)\n\t\t\twsi->http.ah->ues = URIES_IDLE;\n\n\t\t//lwsi_set_state(wsi, LRS_ESTABLISHED);\n\t} else\n\t\tif (lws_buflist_next_segment_len(&wsi->buflist, NULL))\n\t\t\tif (lws_header_table_attach(wsi, 0))\n\t\t\t\tlwsl_debug(\"acquired ah\\n\");\n\n\tlwsl_info(\"%s: %p: keep-alive await new transaction\\n\", __func__, wsi);\n\tlws_callback_on_writable(wsi);\n\n\treturn 0;\n}\n\n/* if not a socket, it's a raw, non-ssl file descriptor */\n\nLWS_VISIBLE struct lws *\nlws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type,\n\t\t\t   lws_sock_file_fd_type fd, const char *vh_prot_name,\n\t\t\t   struct lws *parent)\n{\n\tstruct lws_context *context = vh->context;\n\tstruct lws *new_wsi;\n\tstruct lws_context_per_thread *pt;\n\tint n, ssl = 0;\n\n#if defined(LWS_WITH_PEER_LIMITS)\n\tstruct lws_peer *peer = NULL;\n\n\tif (type & LWS_ADOPT_SOCKET && !(type & LWS_ADOPT_WS_PARENTIO)) {\n\t\tpeer = lws_get_or_create_peer(vh, fd.sockfd);\n\n\t\tif (peer && context->ip_limit_wsi &&\n\t\t    peer->count_wsi >= context->ip_limit_wsi) {\n\t\t\tlwsl_notice(\"Peer reached wsi limit %d\\n\",\n\t\t\t\t\tcontext->ip_limit_wsi);\n\t\t\tlws_stats_atomic_bump(context, &context->pt[0],\n\t\t\t\t\t      LWSSTATS_C_PEER_LIMIT_WSI_DENIED, 1);\n\t\t\treturn NULL;\n\t\t}\n\t}\n#endif\n\n\tn = -1;\n\tif (parent)\n\t\tn = parent->tsi;\n\tnew_wsi = lws_create_new_server_wsi(vh, n);\n\tif (!new_wsi) {\n\t\tif (type & LWS_ADOPT_SOCKET && !(type & LWS_ADOPT_WS_PARENTIO))\n\t\t\tcompatible_close(fd.sockfd);\n\t\treturn NULL;\n\t}\n#if defined(LWS_WITH_PEER_LIMITS)\n\tif (peer)\n\t\tlws_peer_add_wsi(context, peer, new_wsi);\n#endif\n\tpt = &context->pt[(int)new_wsi->tsi];\n\tlws_stats_atomic_bump(context, pt, LWSSTATS_C_CONNECTIONS, 1);\n\n\tif (parent) {\n\t\tnew_wsi->parent = parent;\n\t\tnew_wsi->sibling_list = parent->child_list;\n\t\tparent->child_list = new_wsi;\n\n\t\tif (type & LWS_ADOPT_WS_PARENTIO)\n\t\t\tnew_wsi->parent_carries_io = 1;\n\t}\n\n\tnew_wsi->desc = fd;\n\n\tif (vh_prot_name) {\n\t\tnew_wsi->protocol = lws_vhost_name_to_protocol(new_wsi->vhost,\n\t\t\t\t\t\t\t       vh_prot_name);\n\t\tif (!new_wsi->protocol) {\n\t\t\tlwsl_err(\"Protocol %s not enabled on vhost %s\\n\",\n\t\t\t\t vh_prot_name, new_wsi->vhost->name);\n\t\t\tgoto bail;\n\t\t}\n               if (lws_ensure_user_space(new_wsi)) {\n                       lwsl_notice(\"OOM trying to get user_space\\n\");\n\t\t\tgoto bail;\n               }\n#if defined(LWS_ROLE_WS)\n               if (type & LWS_ADOPT_WS_PARENTIO) {\n\t\t\tnew_wsi->desc.sockfd = LWS_SOCK_INVALID;\n\t\t\tlwsl_debug(\"binding to %s\\n\", new_wsi->protocol->name);\n\t\t\tlws_bind_protocol(new_wsi, new_wsi->protocol);\n\t\t\tlws_role_transition(new_wsi, LWSIFR_SERVER,\n\t\t\t\t\t    LRS_ESTABLISHED, &role_ops_ws);\n\t\t\t/* allocate the ws struct for the wsi */\n\t\t\tnew_wsi->ws = lws_zalloc(sizeof(*new_wsi->ws), \"ws struct\");\n\t\t\tif (!new_wsi->ws) {\n\t\t\t\tlwsl_notice(\"OOM\\n\");\n\t\t\t\tgoto bail;\n\t\t\t}\n\t\t\tlws_server_init_wsi_for_ws(new_wsi);\n\n\t\t\treturn new_wsi;\n               }\n#endif\n\t} else\n#if defined(LWS_ROLE_H1)\n\t\tif (type & LWS_ADOPT_HTTP) {/* he will transition later */\n\t\t\tnew_wsi->protocol =\n\t\t\t\t&vh->protocols[vh->default_protocol_index];\n\t\t\tnew_wsi->role_ops = &role_ops_h1;\n\t\t}\n\t\telse\n#endif\n\t\t{ /* this is the only time he will transition */\n\t\t\tlws_bind_protocol(new_wsi,\n\t\t\t\t&vh->protocols[vh->raw_protocol_index]);\n\t\t\tlws_role_transition(new_wsi, 0, LRS_ESTABLISHED,\n\t\t\t\t\t    &role_ops_raw_skt);\n\t\t}\n\n\tif (type & LWS_ADOPT_SOCKET) { /* socket desc */\n\t\tlwsl_debug(\"%s: new wsi %p, sockfd %d\\n\", __func__, new_wsi,\n\t\t\t   (int)(lws_intptr_t)fd.sockfd);\n#if !defined(LWS_WITH_ESP32)\n\t\tif (type & LWS_ADOPT_FLAG_UDP)\n\t\t\t/*\n\t\t\t * these can be >128 bytes, so just alloc for UDP\n\t\t\t */\n\t\t\tnew_wsi->udp = lws_malloc(sizeof(*new_wsi->udp),\n\t\t\t\t\t\t     \"udp struct\");\n#endif\n\n\t\tif (type & LWS_ADOPT_HTTP)\n\t\t\t/* the transport is accepted...\n\t\t\t * give him time to negotiate */\n\t\t\tlws_set_timeout(new_wsi,\n\t\t\t\t\tPENDING_TIMEOUT_ESTABLISH_WITH_SERVER,\n\t\t\t\t\tcontext->timeout_secs);\n\n\t} else /* file desc */\n\t\tlwsl_debug(\"%s: new wsi %p, filefd %d\\n\", __func__, new_wsi,\n\t\t\t   (int)(lws_intptr_t)fd.filefd);\n\n\t/*\n\t * A new connection was accepted. Give the user a chance to\n\t * set properties of the newly created wsi. There's no protocol\n\t * selected yet so we issue this to the vhosts's default protocol,\n\t * itself by default protocols[0]\n\t */\n\tn = LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED;\n\tif (!(type & LWS_ADOPT_HTTP)) {\n\t\tif (!(type & LWS_ADOPT_SOCKET))\n\t\t\tn = LWS_CALLBACK_RAW_ADOPT_FILE;\n\t\telse\n\t\t\tn = LWS_CALLBACK_RAW_ADOPT;\n\t}\n\n\tif (!LWS_SSL_ENABLED(new_wsi->vhost) || !(type & LWS_ADOPT_ALLOW_SSL) ||\n\t    !(type & LWS_ADOPT_SOCKET)) {\n\t\t/* non-SSL */\n\t\tif (!(type & LWS_ADOPT_HTTP)) {\n\t\t\tif (!(type & LWS_ADOPT_SOCKET))\n\t\t\t\tlws_role_transition(new_wsi, 0, LRS_ESTABLISHED,\n\t\t\t\t\t\t    &role_ops_raw_file);\n\t\t\telse\n\t\t\t\tlws_role_transition(new_wsi, 0, LRS_ESTABLISHED,\n\t\t\t\t\t\t    &role_ops_raw_skt);\n\t\t}\n#if defined(LWS_ROLE_H1)\n\t\telse\n\t\t\tlws_role_transition(new_wsi, LWSIFR_SERVER,\n\t\t\t\t\t    LRS_HEADERS, &role_ops_h1);\n#endif\n\t} else {\n\t\t/* SSL */\n\t\tif (!(type & LWS_ADOPT_HTTP))\n\t\t\tlws_role_transition(new_wsi, 0, LRS_SSL_INIT,\n\t\t\t\t\t    &role_ops_raw_skt);\n#if defined(LWS_ROLE_H1)\n\t\telse\n\t\t\tlws_role_transition(new_wsi, LWSIFR_SERVER,\n\t\t\t\t\t    LRS_SSL_INIT, &role_ops_h1);\n#endif\n\t\tssl = 1;\n\t}\n\n\tlwsl_debug(\"new wsi wsistate 0x%x\\n\", new_wsi->wsistate);\n\n\tif (context->event_loop_ops->accept)\n\t\tcontext->event_loop_ops->accept(new_wsi);\n\n\tif (!ssl) {\n\t\tlws_pt_lock(pt, __func__);\n\t\tif (__insert_wsi_socket_into_fds(context, new_wsi)) {\n\t\t\tlws_pt_unlock(pt);\n\t\t\tlwsl_err(\"%s: fail inserting socket\\n\", __func__);\n\t\t\tgoto fail;\n\t\t}\n\t\tlws_pt_unlock(pt);\n\t} else\n\t\tif (lws_server_socket_service_ssl(new_wsi, fd.sockfd)) {\n\t\t\tlwsl_info(\"%s: fail ssl negotiation\\n\", __func__);\n\t\t\tgoto fail;\n\t\t}\n\n\t/*\n\t *  by deferring callback to this point, after insertion to fds,\n\t * lws_callback_on_writable() can work from the callback\n\t */\n\tif ((new_wsi->protocol->callback)(\n\t\t\tnew_wsi, n, new_wsi->user_space, NULL, 0))\n\t\tgoto fail;\n\n\tif (type & LWS_ADOPT_HTTP) {\n\t\tif (!lws_header_table_attach(new_wsi, 0))\n\t\t\tlwsl_debug(\"Attached ah immediately\\n\");\n\t\telse\n\t\t\tlwsl_info(\"%s: waiting for ah\\n\", __func__);\n\t}\n\n\tlws_cancel_service_pt(new_wsi);\n\n\treturn new_wsi;\n\nfail:\n\tif (type & LWS_ADOPT_SOCKET)\n\t\tlws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS, \"adopt skt fail\");\n\n\treturn NULL;\n\nbail:\n       lwsl_notice(\"%s: exiting on bail\\n\", __func__);\n\tif (parent)\n\t\tparent->child_list = new_wsi->sibling_list;\n\tif (new_wsi->user_space)\n\t\tlws_free(new_wsi->user_space);\n\tlws_free(new_wsi);\n       compatible_close(fd.sockfd);\n\n\treturn NULL;\n}\n\nLWS_VISIBLE struct lws *\nlws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd)\n{\n\tlws_sock_file_fd_type fd;\n\n\tfd.sockfd = accept_fd;\n\treturn lws_adopt_descriptor_vhost(vh, LWS_ADOPT_SOCKET |\n\t\t\tLWS_ADOPT_HTTP | LWS_ADOPT_ALLOW_SSL, fd, NULL, NULL);\n}\n\nLWS_VISIBLE struct lws *\nlws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)\n{\n\treturn lws_adopt_socket_vhost(context->vhost_list, accept_fd);\n}\n\n/* Common read-buffer adoption for lws_adopt_*_readbuf */\nstatic struct lws*\nadopt_socket_readbuf(struct lws *wsi, const char *readbuf, size_t len)\n{\n\tstruct lws_context_per_thread *pt;\n\tstruct lws_pollfd *pfd;\n\tint n;\n\n\tif (!wsi)\n\t\treturn NULL;\n\n\tif (!readbuf || len == 0)\n\t\treturn wsi;\n\n\tif (wsi->position_in_fds_table == LWS_NO_FDS_POS)\n\t\treturn wsi;\n\n\tpt = &wsi->context->pt[(int)wsi->tsi];\n\n\tn = lws_buflist_append_segment(&wsi->buflist, (const uint8_t *)readbuf, len);\n\tif (n < 0)\n\t\tgoto bail;\n\tif (n)\n\t\tlws_dll_lws_add_front(&wsi->dll_buflist, &pt->dll_head_buflist);\n\n\t/*\n\t * we can't process the initial read data until we can attach an ah.\n\t *\n\t * if one is available, get it and place the data in his ah rxbuf...\n\t * wsi with ah that have pending rxbuf get auto-POLLIN service.\n\t *\n\t * no autoservice because we didn't get a chance to attach the\n\t * readbuf data to wsi or ah yet, and we will do it next if we get\n\t * the ah.\n\t */\n\tif (wsi->http.ah || !lws_header_table_attach(wsi, 0)) {\n\n\t\tlwsl_notice(\"%s: calling service on readbuf ah\\n\", __func__);\n\n\t\t/* unlike a normal connect, we have the headers already\n\t\t * (or the first part of them anyway).\n\t\t * libuv won't come back and service us without a network\n\t\t * event, so we need to do the header service right here.\n\t\t */\n\t\tpfd = &pt->fds[wsi->position_in_fds_table];\n\t\tpfd->revents |= LWS_POLLIN;\n\t\tlwsl_err(\"%s: calling service\\n\", __func__);\n\t\tif (lws_service_fd_tsi(wsi->context, pfd, wsi->tsi))\n\t\t\t/* service closed us */\n\t\t\treturn NULL;\n\n\t\treturn wsi;\n\t}\n\tlwsl_err(\"%s: deferring handling ah\\n\", __func__);\n\n\treturn wsi;\n\nbail:\n\tlws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, \"adopt skt readbuf fail\");\n\n\treturn NULL;\n}\n\nLWS_VISIBLE struct lws *\nlws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,\n\t\t\t const char *readbuf, size_t len)\n{\n        return adopt_socket_readbuf(lws_adopt_socket(context, accept_fd),\n        \t\t\t    readbuf, len);\n}\n\nLWS_VISIBLE struct lws *\nlws_adopt_socket_vhost_readbuf(struct lws_vhost *vhost,\n\t\t\t       lws_sockfd_type accept_fd,\n\t\t\t       const char *readbuf, size_t len)\n{\n        return adopt_socket_readbuf(lws_adopt_socket_vhost(vhost, accept_fd),\n        \t\t\t    readbuf, len);\n}\n\nLWS_VISIBLE int\nlws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,\n\t\t    const char *other_headers, int other_headers_len)\n{\n\tstatic const char * const intermediates[] = { \"private\", \"public\" };\n\tstruct lws_context *context = lws_get_context(wsi);\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n#if defined(LWS_WITH_RANGES)\n\tstruct lws_range_parsing *rp = &wsi->http.range;\n#endif\n\tchar cache_control[50], *cc = \"no-store\";\n\tunsigned char *response = pt->serv_buf + LWS_PRE;\n\tunsigned char *p = response;\n\tunsigned char *end = p + context->pt_serv_buf_size - LWS_PRE;\n\tlws_filepos_t total_content_length;\n\tint ret = 0, cclen = 8, n = HTTP_STATUS_OK;\n\tlws_fop_flags_t fflags = LWS_O_RDONLY;\n#if defined(LWS_WITH_RANGES)\n\tint ranges;\n#endif\n\tconst struct lws_plat_file_ops *fops;\n\tconst char *vpath;\n\n\tif (wsi->handling_404)\n\t\tn = HTTP_STATUS_NOT_FOUND;\n\n\t/*\n\t * We either call the platform fops .open with first arg platform fops,\n\t * or we call fops_zip .open with first arg platform fops, and fops_zip\n\t * open will decide whether to switch to fops_zip or stay with fops_def.\n\t *\n\t * If wsi->http.fop_fd is already set, the caller already opened it\n\t */\n\tif (!wsi->http.fop_fd) {\n\t\tfops = lws_vfs_select_fops(wsi->context->fops, file, &vpath);\n\t\tfflags |= lws_vfs_prepare_flags(wsi);\n\t\twsi->http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops,\n\t\t\t\t\t\t\tfile, vpath, &fflags);\n\t\tif (!wsi->http.fop_fd) {\n\t\t\tlwsl_info(\"%s: Unable to open: '%s': errno %d\\n\",\n\t\t\t\t  __func__, file, errno);\n\t\t\tif (lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL))\n\t\t\t\t\t\treturn -1;\n\t\t\treturn !wsi->http2_substream;\n\t\t}\n\t}\n\twsi->http.filelen = lws_vfs_get_length(wsi->http.fop_fd);\n\ttotal_content_length = wsi->http.filelen;\n\n#if defined(LWS_WITH_RANGES)\n\tranges = lws_ranges_init(wsi, rp, wsi->http.filelen);\n\n\tlwsl_debug(\"Range count %d\\n\", ranges);\n\t/*\n\t * no ranges -> 200;\n\t *  1 range  -> 206 + Content-Type: normal; Content-Range;\n\t *  more     -> 206 + Content-Type: multipart/byteranges\n\t *  \t\tRepeat the true Content-Type in each multipart header\n\t *  \t\talong with Content-Range\n\t */\n\tif (ranges < 0) {\n\t\t/* it means he expressed a range in Range:, but it was illegal */\n\t\tlws_return_http_status(wsi, HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE,\n\t\t\t\t       NULL);\n\t\tif (lws_http_transaction_completed(wsi))\n\t\t\treturn -1; /* <0 means just hang up */\n\n\t\tlws_vfs_file_close(&wsi->http.fop_fd);\n\n\t\treturn 0; /* == 0 means we dealt with the transaction complete */\n\t}\n\tif (ranges)\n\t\tn = HTTP_STATUS_PARTIAL_CONTENT;\n#endif\n\n\tif (lws_add_http_header_status(wsi, n, &p, end))\n\t\treturn -1;\n\n\tif ((wsi->http.fop_fd->flags & (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP |\n\t\t       LWS_FOP_FLAG_COMPR_IS_GZIP)) ==\n\t    (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP | LWS_FOP_FLAG_COMPR_IS_GZIP)) {\n\t\tif (lws_add_http_header_by_token(wsi,\n\t\t\tWSI_TOKEN_HTTP_CONTENT_ENCODING,\n\t\t\t(unsigned char *)\"gzip\", 4, &p, end))\n\t\t\treturn -1;\n\t\tlwsl_info(\"file is being provided in gzip\\n\");\n\t}\n\n\tif (\n#if defined(LWS_WITH_RANGES)\n\t    ranges < 2 &&\n#endif\n\t    content_type && content_type[0])\n\t\tif (lws_add_http_header_by_token(wsi,\n\t\t\t\t\t\t WSI_TOKEN_HTTP_CONTENT_TYPE,\n\t\t\t\t\t\t (unsigned char *)content_type,\n\t\t\t\t\t\t (int)strlen(content_type),\n\t\t\t\t\t\t &p, end))\n\t\t\treturn -1;\n\n#if defined(LWS_WITH_RANGES)\n\tif (ranges >= 2) { /* multipart byteranges */\n\t\tlws_strncpy(wsi->http.multipart_content_type, content_type,\n\t\t\tsizeof(wsi->http.multipart_content_type));\n\n\t\tif (lws_add_http_header_by_token(wsi,\n\t\t\t\t\t\t WSI_TOKEN_HTTP_CONTENT_TYPE,\n\t\t\t\t\t\t (unsigned char *)\n\t\t\t\t\t\t \"multipart/byteranges; \"\n\t\t\t\t\t\t \"boundary=_lws\",\n\t\t\t \t \t \t 20, &p, end))\n\t\t\treturn -1;\n\n\t\t/*\n\t\t *  our overall content length has to include\n\t\t *\n\t\t *  - (n + 1) x \"_lws\\r\\n\"\n\t\t *  - n x Content-Type: xxx/xxx\\r\\n\n\t\t *  - n x Content-Range: bytes xxx-yyy/zzz\\r\\n\n\t\t *  - n x /r/n\n\t\t *  - the actual payloads (aggregated in rp->agg)\n\t\t *\n\t\t *  Precompute it for the main response header\n\t\t */\n\n\t\ttotal_content_length = (lws_filepos_t)rp->agg +\n\t\t\t\t       6 /* final _lws\\r\\n */;\n\n\t\tlws_ranges_reset(rp);\n\t\twhile (lws_ranges_next(rp)) {\n\t\t\tn = lws_snprintf(cache_control, sizeof(cache_control),\n\t\t\t\t\t\"bytes %llu-%llu/%llu\",\n\t\t\t\t\trp->start, rp->end, rp->extent);\n\n\t\t\ttotal_content_length +=\n\t\t\t\t6 /* header _lws\\r\\n */ +\n\t\t\t\t/* Content-Type: xxx/xxx\\r\\n */\n\t\t\t\t14 + strlen(content_type) + 2 +\n\t\t\t\t/* Content-Range: xxxx\\r\\n */\n\t\t\t\t15 + n + 2 +\n\t\t\t\t2; /* /r/n */\n\t\t}\n\n\t\tlws_ranges_reset(rp);\n\t\tlws_ranges_next(rp);\n\t}\n\n\tif (ranges == 1) {\n\t\ttotal_content_length = (lws_filepos_t)rp->agg;\n\t\tn = lws_snprintf(cache_control, sizeof(cache_control),\n\t\t\t\t \"bytes %llu-%llu/%llu\",\n\t\t\t\t rp->start, rp->end, rp->extent);\n\n\t\tif (lws_add_http_header_by_token(wsi,\n\t\t\t\t\t\t WSI_TOKEN_HTTP_CONTENT_RANGE,\n\t\t\t\t\t\t (unsigned char *)cache_control,\n\t\t\t\t\t\t n, &p, end))\n\t\t\treturn -1;\n\t}\n\n\twsi->http.range.inside = 0;\n\n\tif (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ACCEPT_RANGES,\n\t\t\t\t\t (unsigned char *)\"bytes\", 5, &p, end))\n\t\treturn -1;\n#endif\n\n\tif (!wsi->http2_substream) {\n\t\tif (!wsi->sending_chunked) {\n\t\t\tif (lws_add_http_header_content_length(wsi,\n\t\t\t\t\t\ttotal_content_length,\n\t\t\t\t\t       &p, end))\n\t\t\t\treturn -1;\n\t\t} else {\n\t\t\tif (lws_add_http_header_by_token(wsi,\n\t\t\t\t\t\t WSI_TOKEN_HTTP_TRANSFER_ENCODING,\n\t\t\t\t\t\t (unsigned char *)\"chunked\",\n\t\t\t\t\t\t 7, &p, end))\n\t\t\t\treturn -1;\n\t\t}\n\t}\n\n\tif (wsi->cache_secs && wsi->cache_reuse) {\n\t\tif (wsi->cache_revalidate) {\n\t\t\tcc = cache_control;\n\t\t\tcclen = sprintf(cache_control, \"%s max-age: %u\",\n\t\t\t\t    intermediates[wsi->cache_intermediaries],\n\t\t\t\t    wsi->cache_secs);\n\t\t} else {\n\t\t\tcc = \"no-cache\";\n\t\t\tcclen = 8;\n\t\t}\n\t}\n\n\tif (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CACHE_CONTROL,\n\t\t\t(unsigned char *)cc, cclen, &p, end))\n\t\treturn -1;\n\n\tif (wsi->http.connection_type == HTTP_CONNECTION_KEEP_ALIVE)\n\t\tif (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,\n\t\t\t\t(unsigned char *)\"keep-alive\", 10, &p, end))\n\t\t\treturn -1;\n\n\tif (other_headers) {\n\t\tif ((end - p) < other_headers_len)\n\t\t\treturn -1;\n\t\tmemcpy(p, other_headers, other_headers_len);\n\t\tp += other_headers_len;\n\t}\n\n\tif (lws_finalize_http_header(wsi, &p, end))\n\t\treturn -1;\n\n\tret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);\n\tif (ret != (p - response)) {\n\t\tlwsl_err(\"_write returned %d from %ld\\n\", ret,\n\t\t\t (long)(p - response));\n\t\treturn -1;\n\t}\n\n\twsi->http.filepos = 0;\n\tlwsi_set_state(wsi, LRS_ISSUING_FILE);\n\n\tlws_callback_on_writable(wsi);\n\n\treturn 0;\n}\n\nLWS_VISIBLE int lws_serve_http_file_fragment(struct lws *wsi)\n{\n\tstruct lws_context *context = wsi->context;\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tstruct lws_process_html_args args;\n\tlws_filepos_t amount, poss;\n\tunsigned char *p, *pstart;\n#if defined(LWS_WITH_RANGES)\n\tunsigned char finished = 0;\n#endif\n\tint n, m;\n\n\tlwsl_debug(\"wsi->http2_substream %d\\n\", wsi->http2_substream);\n\n\tdo {\n\n\t\tif (wsi->trunc_len) {\n\t\t\tif (lws_issue_raw(wsi, wsi->trunc_alloc +\n\t\t\t\t\t  wsi->trunc_offset,\n\t\t\t\t\t  wsi->trunc_len) < 0) {\n\t\t\t\tlwsl_info(\"%s: closing\\n\", __func__);\n\t\t\t\tgoto file_had_it;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tif (wsi->http.filepos == wsi->http.filelen)\n\t\t\tgoto all_sent;\n\n\t\tn = 0;\n\n\t\tpstart = pt->serv_buf + LWS_H2_FRAME_HEADER_LENGTH;\n\n\t\tp = pstart;\n\n#if defined(LWS_WITH_RANGES)\n\t\tif (wsi->http.range.count_ranges && !wsi->http.range.inside) {\n\n\t\t\tlwsl_notice(\"%s: doing range start %llu\\n\", __func__,\n\t\t\t\t    wsi->http.range.start);\n\n\t\t\tif ((long long)lws_vfs_file_seek_cur(wsi->http.fop_fd,\n\t\t\t\t\t\t   wsi->http.range.start -\n\t\t\t\t\t\t   wsi->http.filepos) < 0)\n\t\t\t\tgoto file_had_it;\n\n\t\t\twsi->http.filepos = wsi->http.range.start;\n\n\t\t\tif (wsi->http.range.count_ranges > 1) {\n\t\t\t\tn =  lws_snprintf((char *)p,\n\t\t\t\t\t\tcontext->pt_serv_buf_size -\n\t\t\t\t\t\tLWS_H2_FRAME_HEADER_LENGTH,\n\t\t\t\t\t\"_lws\\x0d\\x0a\"\n\t\t\t\t\t\"Content-Type: %s\\x0d\\x0a\"\n\t\t\t\t\t\"Content-Range: bytes %llu-%llu/%llu\\x0d\\x0a\"\n\t\t\t\t\t\"\\x0d\\x0a\",\n\t\t\t\t\twsi->http.multipart_content_type,\n\t\t\t\t\twsi->http.range.start,\n\t\t\t\t\twsi->http.range.end,\n\t\t\t\t\twsi->http.range.extent);\n\t\t\t\tp += n;\n\t\t\t}\n\n\t\t\twsi->http.range.budget = wsi->http.range.end -\n\t\t\t\t\t\t   wsi->http.range.start + 1;\n\t\t\twsi->http.range.inside = 1;\n\t\t}\n#endif\n\n\t\tposs = context->pt_serv_buf_size - n - LWS_H2_FRAME_HEADER_LENGTH;\n\n\t\tif (wsi->http.tx_content_length)\n\t\t\tif (poss > wsi->http.tx_content_remain)\n\t\t\t\tposs = wsi->http.tx_content_remain;\n\n\t\t/*\n\t\t * if there is a hint about how much we will do well to send at\n\t\t * one time, restrict ourselves to only trying to send that.\n\t\t */\n\t\tif (wsi->protocol->tx_packet_size &&\n\t\t    poss > wsi->protocol->tx_packet_size)\n\t\t\tposs = wsi->protocol->tx_packet_size;\n\n\t\tif (wsi->role_ops->tx_credit) {\n\t\t\tlws_filepos_t txc = wsi->role_ops->tx_credit(wsi);\n\n\t\t\tif (!txc) {\n\t\t\t\tlwsl_info(\"%s: came here with no tx credit\\n\",\n\t\t\t\t\t\t__func__);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (txc < poss)\n\t\t\t\tposs = txc;\n\n\t\t\t/*\n\t\t\t * consumption of the actual payload amount sent will be\n\t\t\t * handled when the role data frame is sent\n\t\t\t */\n\t\t}\n\n#if defined(LWS_WITH_RANGES)\n\t\tif (wsi->http.range.count_ranges) {\n\t\t\tif (wsi->http.range.count_ranges > 1)\n\t\t\t\tposs -= 7; /* allow for final boundary */\n\t\t\tif (poss > wsi->http.range.budget)\n\t\t\t\tposs = wsi->http.range.budget;\n\t\t}\n#endif\n\t\tif (wsi->sending_chunked) {\n\t\t\t/* we need to drop the chunk size in here */\n\t\t\tp += 10;\n\t\t\t/* allow for the chunk to grow by 128 in translation */\n\t\t\tposs -= 10 + 128;\n\t\t}\n\n\t\tif (lws_vfs_file_read(wsi->http.fop_fd, &amount, p, poss) < 0)\n\t\t\tgoto file_had_it; /* caller will close */\n\n\t\tif (wsi->sending_chunked)\n\t\t\tn = (int)amount;\n\t\telse\n\t\t\tn = lws_ptr_diff(p, pstart) + (int)amount;\n\n\t\tlwsl_debug(\"%s: sending %d\\n\", __func__, n);\n\n\t\tif (n) {\n\t\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,\n\t\t\t\t\tcontext->timeout_secs);\n\n\t\t\tif (wsi->interpreting) {\n\t\t\t\targs.p = (char *)p;\n\t\t\t\targs.len = n;\n\t\t\t\targs.max_len = (unsigned int)poss + 128;\n\t\t\t\targs.final = wsi->http.filepos + n ==\n\t\t\t\t\t     wsi->http.filelen;\n\t\t\t\targs.chunked = wsi->sending_chunked;\n\t\t\t\tif (user_callback_handle_rxflow(\n\t\t\t\t     wsi->vhost->protocols[\n\t\t\t\t     (int)wsi->protocol_interpret_idx].callback,\n\t\t\t\t     wsi, LWS_CALLBACK_PROCESS_HTML,\n\t\t\t\t     wsi->user_space, &args, 0) < 0)\n\t\t\t\t\tgoto file_had_it;\n\t\t\t\tn = args.len;\n\t\t\t\tp = (unsigned char *)args.p;\n\t\t\t} else\n\t\t\t\tp = pstart;\n\n#if defined(LWS_WITH_RANGES)\n\t\t\tif (wsi->http.range.send_ctr + 1 ==\n\t\t\t\twsi->http.range.count_ranges && // last range\n\t\t\t    wsi->http.range.count_ranges > 1 && // was 2+ ranges (ie, multipart)\n\t\t\t    wsi->http.range.budget - amount == 0) {// final part\n\t\t\t\tn += lws_snprintf((char *)pstart + n, 6,\n\t\t\t\t\t\"_lws\\x0d\\x0a\"); // append trailing boundary\n\t\t\t\tlwsl_debug(\"added trailing boundary\\n\");\n\t\t\t}\n#endif\n\t\t\tm = lws_write(wsi, p, n,\n\t\t\t\t      wsi->http.filepos + amount == wsi->http.filelen ?\n\t\t\t\t\tLWS_WRITE_HTTP_FINAL :\n\t\t\t\t\tLWS_WRITE_HTTP\n\t\t\t\t);\n\t\t\tif (m < 0)\n\t\t\t\tgoto file_had_it;\n\n\t\t\twsi->http.filepos += amount;\n\n#if defined(LWS_WITH_RANGES)\n\t\t\tif (wsi->http.range.count_ranges >= 1) {\n\t\t\t\twsi->http.range.budget -= amount;\n\t\t\t\tif (wsi->http.range.budget == 0) {\n\t\t\t\t\tlwsl_notice(\"range budget exhausted\\n\");\n\t\t\t\t\twsi->http.range.inside = 0;\n\t\t\t\t\twsi->http.range.send_ctr++;\n\n\t\t\t\t\tif (lws_ranges_next(&wsi->http.range) < 1) {\n\t\t\t\t\t\tfinished = 1;\n\t\t\t\t\t\tgoto all_sent;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n#endif\n\n\t\t\tif (m != n) {\n\t\t\t\t/* adjust for what was not sent */\n\t\t\t\tif (lws_vfs_file_seek_cur(wsi->http.fop_fd,\n\t\t\t\t\t\t\t   m - n) ==\n\t\t\t\t\t\t\t     (lws_fileofs_t)-1)\n\t\t\t\t\tgoto file_had_it;\n\t\t\t}\n\t\t}\n\nall_sent:\n\t\tif ((!wsi->trunc_len && wsi->http.filepos >= wsi->http.filelen)\n#if defined(LWS_WITH_RANGES)\n\t\t    || finished)\n#else\n\t\t)\n#endif\n\t\t     {\n\t\t\tlwsi_set_state(wsi, LRS_ESTABLISHED);\n\t\t\t/* we might be in keepalive, so close it off here */\n\t\t\tlws_vfs_file_close(&wsi->http.fop_fd);\n\n\t\t\tlwsl_debug(\"file completed\\n\");\n\n\t\t\tif (wsi->protocol->callback &&\n\t\t\t    user_callback_handle_rxflow(wsi->protocol->callback,\n\t\t\t\t\t\t\twsi, LWS_CALLBACK_HTTP_FILE_COMPLETION,\n\t\t\t\t\t\t\twsi->user_space, NULL,\n\t\t\t\t\t\t\t0) < 0) {\n\t\t\t\t\t/*\n\t\t\t\t\t * For http/1.x, the choices from\n\t\t\t\t\t * transaction_completed are either\n\t\t\t\t\t * 0 to use the connection for pipelined\n\t\t\t\t\t * or nonzero to hang it up.\n\t\t\t\t\t *\n\t\t\t\t\t * However for http/2. while we are\n\t\t\t\t\t * still interested in hanging up the\n\t\t\t\t\t * nwsi if there was a network-level\n\t\t\t\t\t * fatal error, simply completing the\n\t\t\t\t\t * transaction is a matter of the stream\n\t\t\t\t\t * state, not the root connection at the\n\t\t\t\t\t * network level\n\t\t\t\t\t */\n\t\t\t\t\tif (wsi->http2_substream)\n\t\t\t\t\t\treturn 1;\n\t\t\t\t\telse\n\t\t\t\t\t\treturn -1;\n\t\t\t\t}\n\n\t\t\treturn 1;  /* >0 indicates completed */\n\t\t}\n\t} while (0); // while (!lws_send_pipe_choked(wsi))\n\n\tlws_callback_on_writable(wsi);\n\n\treturn 0; /* indicates further processing must be done */\n\nfile_had_it:\n\tlws_vfs_file_close(&wsi->http.fop_fd);\n\n\treturn -1;\n}\n\n\nLWS_VISIBLE void\nlws_server_get_canonical_hostname(struct lws_context *context,\n\t\t\t\t  const struct lws_context_creation_info *info)\n{\n\tif (lws_check_opt(info->options,\n\t\t\tLWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME))\n\t\treturn;\n#if !defined(LWS_WITH_ESP32)\n\t/* find canonical hostname */\n\tgethostname((char *)context->canonical_hostname,\n\t\t    sizeof(context->canonical_hostname) - 1);\n\n\tlwsl_info(\" canonical_hostname = %s\\n\", context->canonical_hostname);\n#else\n\t(void)context;\n#endif\n}\n\n\nLWS_VISIBLE LWS_EXTERN int\nlws_chunked_html_process(struct lws_process_html_args *args,\n\t\t\t struct lws_process_html_state *s)\n{\n\tchar *sp, buffer[32];\n\tconst char *pc;\n\tint old_len, n;\n\n\t/* do replacements */\n\tsp = args->p;\n\told_len = args->len;\n\targs->len = 0;\n\ts->start = sp;\n\twhile (sp < args->p + old_len) {\n\n\t\tif (args->len + 7 >= args->max_len) {\n\t\t\tlwsl_err(\"Used up interpret padding\\n\");\n\t\t\treturn -1;\n\t\t}\n\n\t\tif ((!s->pos && *sp == '$') || s->pos) {\n\t\t\tint hits = 0, hit = 0;\n\n\t\t\tif (!s->pos)\n\t\t\t\ts->start = sp;\n\t\t\ts->swallow[s->pos++] = *sp;\n\t\t\tif (s->pos == sizeof(s->swallow) - 1)\n\t\t\t\tgoto skip;\n\t\t\tfor (n = 0; n < s->count_vars; n++)\n\t\t\t\tif (!strncmp(s->swallow, s->vars[n], s->pos)) {\n\t\t\t\t\thits++;\n\t\t\t\t\thit = n;\n\t\t\t\t}\n\t\t\tif (!hits) {\nskip:\n\t\t\t\ts->swallow[s->pos] = '\\0';\n\t\t\t\tmemcpy(s->start, s->swallow, s->pos);\n\t\t\t\targs->len++;\n\t\t\t\ts->pos = 0;\n\t\t\t\tsp = s->start + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (hits == 1 && s->pos == (int)strlen(s->vars[hit])) {\n\t\t\t\tpc = s->replace(s->data, hit);\n\t\t\t\tif (!pc)\n\t\t\t\t\tpc = \"NULL\";\n\t\t\t\tn = (int)strlen(pc);\n\t\t\t\ts->swallow[s->pos] = '\\0';\n\t\t\t\tif (n != s->pos) {\n\t\t\t\t\tmemmove(s->start + n,\n\t\t\t\t\t\ts->start + s->pos,\n\t\t\t\t\t\told_len - (sp - args->p));\n\t\t\t\t\told_len += (n - s->pos) + 1;\n\t\t\t\t}\n\t\t\t\tmemcpy(s->start, pc, n);\n\t\t\t\targs->len++;\n\t\t\t\tsp = s->start + 1;\n\n\t\t\t\ts->pos = 0;\n\t\t\t}\n\t\t\tsp++;\n\t\t\tcontinue;\n\t\t}\n\n\t\targs->len++;\n\t\tsp++;\n\t}\n\n\tif (args->chunked) {\n\t\t/* no space left for final chunk trailer */\n\t\tif (args->final && args->len + 7 >= args->max_len)\n\t\t\treturn -1;\n\n\t\tn = sprintf(buffer, \"%X\\x0d\\x0a\", args->len);\n\n\t\targs->p -= n;\n\t\tmemcpy(args->p, buffer, n);\n\t\targs->len += n;\n\n\t\tif (args->final) {\n\t\t\tsp = args->p + args->len;\n\t\t\t*sp++ = '\\x0d';\n\t\t\t*sp++ = '\\x0a';\n\t\t\t*sp++ = '0';\n\t\t\t*sp++ = '\\x0d';\n\t\t\t*sp++ = '\\x0a';\n\t\t\t*sp++ = '\\x0d';\n\t\t\t*sp++ = '\\x0a';\n\t\t\targs->len += 7;\n\t\t} else {\n\t\t\tsp = args->p + args->len;\n\t\t\t*sp++ = '\\x0d';\n\t\t\t*sp++ = '\\x0a';\n\t\t\targs->len += 2;\n\t\t}\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/listen/ops-listen.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include <core/private.h>\n\nstatic int\nrops_handle_POLLIN_listen(struct lws_context_per_thread *pt, struct lws *wsi,\n\t\t\t  struct lws_pollfd *pollfd)\n{\n\tstruct lws_context *context = wsi->context;\n\tlws_sockfd_type accept_fd = LWS_SOCK_INVALID;\n\tlws_sock_file_fd_type fd;\n\tint opts = LWS_ADOPT_SOCKET | LWS_ADOPT_ALLOW_SSL;\n\tstruct sockaddr_storage cli_addr;\n\tsocklen_t clilen;\n\n\t/* pollin means a client has connected to us then\n\t *\n\t * pollout is a hack on esp32 for background accepts signalling\n\t * they completed\n\t */\n\n\tdo {\n\t\tstruct lws *cwsi;\n\n\t\tif (!(pollfd->revents & (LWS_POLLIN | LWS_POLLOUT)) ||\n\t\t    !(pollfd->events & LWS_POLLIN))\n\t\t\tbreak;\n\n#if defined(LWS_WITH_TLS)\n\t\t/*\n\t\t * can we really accept it, with regards to SSL limit?\n\t\t * another vhost may also have had POLLIN on his\n\t\t * listener this round and used it up already\n\t\t */\n\t\tif (wsi->vhost->tls.use_ssl &&\n\t\t    context->simultaneous_ssl_restriction &&\n\t\t    context->simultaneous_ssl ==\n\t\t\t\t  context->simultaneous_ssl_restriction)\n\t\t\t/*\n\t\t\t * no... ignore it, he won't come again until\n\t\t\t * we are below the simultaneous_ssl_restriction\n\t\t\t * limit and POLLIN is enabled on him again\n\t\t\t */\n\t\t\tbreak;\n#endif\n\t\t/* listen socket got an unencrypted connection... */\n\n\t\tclilen = sizeof(cli_addr);\n\t\tlws_latency_pre(context, wsi);\n\n\t\t/*\n\t\t * We cannot identify the peer who is in the listen\n\t\t * socket connect queue before we accept it; even if\n\t\t * we could, not accepting it due to PEER_LIMITS would\n\t\t * block the connect queue for other legit peers.\n\t\t */\n\n\t\taccept_fd  = accept((int)pollfd->fd,\n\t\t\t\t    (struct sockaddr *)&cli_addr, &clilen);\n\t\tlws_latency(context, wsi, \"listener accept\",\n\t\t\t    (int)accept_fd, accept_fd != LWS_SOCK_INVALID);\n\t\tif (accept_fd == LWS_SOCK_INVALID) {\n\t\t\tif (LWS_ERRNO == LWS_EAGAIN ||\n\t\t\t    LWS_ERRNO == LWS_EWOULDBLOCK) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tlwsl_err(\"ERROR on accept: %s\\n\",\n\t\t\t\t strerror(LWS_ERRNO));\n\t\t\tbreak;\n\t\t}\n\n\t\tlws_plat_set_socket_options(wsi->vhost, accept_fd);\n\n#if defined(LWS_WITH_IPV6)\n\t\tlwsl_debug(\"accepted new conn port %u on fd=%d\\n\",\n\t\t\t((cli_addr.ss_family == AF_INET6) ?\n\t\t\tntohs(((struct sockaddr_in6 *) &cli_addr)->sin6_port) :\n\t\t\tntohs(((struct sockaddr_in *) &cli_addr)->sin_port)),\n\t\t\taccept_fd);\n#else\n\t\tlwsl_debug(\"accepted new conn port %u on fd=%d\\n\",\n\t\t\t   ntohs(((struct sockaddr_in *) &cli_addr)->sin_port),\n\t\t\t   accept_fd);\n#endif\n\n\t\t/*\n\t\t * look at who we connected to and give user code a\n\t\t * chance to reject based on client IP.  There's no\n\t\t * protocol selected yet so we issue this to\n\t\t * protocols[0]\n\t\t */\n\t\tif ((wsi->vhost->protocols[0].callback)(wsi,\n\t\t\t\tLWS_CALLBACK_FILTER_NETWORK_CONNECTION,\n\t\t\t\tNULL,\n\t\t\t\t(void *)(lws_intptr_t)accept_fd, 0)) {\n\t\t\tlwsl_debug(\"Callback denied net connection\\n\");\n\t\t\tcompatible_close(accept_fd);\n\t\t\tbreak;\n\t\t}\n\n\t\tif (!(wsi->vhost->options & LWS_SERVER_OPTION_ONLY_RAW))\n\t\t\topts |= LWS_ADOPT_HTTP;\n\t\telse\n\t\t\topts = LWS_ADOPT_SOCKET;\n\n\t\tfd.sockfd = accept_fd;\n\t\tcwsi = lws_adopt_descriptor_vhost(wsi->vhost, opts, fd,\n\t\t\t\t\t\t  NULL, NULL);\n\t\tif (!cwsi)\n\t\t\t/* already closed cleanly as necessary */\n\t\t\treturn LWS_HPI_RET_WSI_ALREADY_DIED;\n\n\t\tif (lws_server_socket_service_ssl(cwsi, accept_fd)) {\n\t\t\tlws_close_free_wsi(cwsi, LWS_CLOSE_STATUS_NOSTATUS,\n\t\t\t\t\t   \"listen svc fail\");\n\t\t\treturn LWS_HPI_RET_WSI_ALREADY_DIED;\n\t\t}\n\n\t\tlwsl_info(\"%s: new wsi %p: wsistate 0x%x, role_ops %s\\n\",\n\t\t\t    __func__, cwsi, cwsi->wsistate, cwsi->role_ops->name);\n\n\t} while (pt->fds_count < context->fd_limit_per_thread - 1 &&\n\t\t wsi->position_in_fds_table != LWS_NO_FDS_POS &&\n\t\t lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);\n\n\treturn LWS_HPI_RET_HANDLED;\n}\n\nint rops_handle_POLLOUT_listen(struct lws *wsi)\n{\n\treturn LWS_HP_RET_USER_SERVICE;\n}\n\nstruct lws_role_ops role_ops_listen = {\n\t/* role name */\t\t\t\"listen\",\n\t/* alpn id */\t\t\tNULL,\n\t/* check_upgrades */\t\tNULL,\n\t/* init_context */\t\tNULL,\n\t/* init_vhost */\t\tNULL,\n\t/* destroy_vhost */\t\tNULL,\n\t/* periodic_checks */\t\tNULL,\n\t/* service_flag_pending */\tNULL,\n\t/* handle_POLLIN */\t\trops_handle_POLLIN_listen,\n\t/* handle_POLLOUT */\t\trops_handle_POLLOUT_listen,\n\t/* perform_user_POLLOUT */\tNULL,\n\t/* callback_on_writable */\tNULL,\n\t/* tx_credit */\t\t\tNULL,\n\t/* write_role_protocol */\tNULL,\n\t/* encapsulation_parent */\tNULL,\n\t/* alpn_negotiated */\t\tNULL,\n\t/* close_via_role_protocol */\tNULL,\n\t/* close_role */\t\tNULL,\n\t/* close_kill_connection */\tNULL,\n\t/* destroy_role */\t\tNULL,\n\t/* writeable cb clnt, srv */\t{ 0, 0 },\n\t/* close cb clnt, srv */\t{ 0, 0 },\n\t/* file_handle */\t\t0,\n};\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/pipe/ops-pipe.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include <core/private.h>\n\nstatic int\nrops_handle_POLLIN_pipe(struct lws_context_per_thread *pt, struct lws *wsi,\n\t\t\tstruct lws_pollfd *pollfd)\n{\n#if !defined(WIN32) && !defined(_WIN32)\n\tchar s[100];\n\tint n;\n\n\t/*\n\t * discard the byte(s) that signaled us\n\t * We really don't care about the number of bytes, but coverity\n\t * thinks we should.\n\t */\n\tn = read(wsi->desc.sockfd, s, sizeof(s));\n\t(void)n;\n\tif (n < 0)\n\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n#endif\n\t/*\n\t * the poll() wait, or the event loop for libuv etc is a\n\t * process-wide resource that we interrupted.  So let every\n\t * protocol that may be interested in the pipe event know that\n\t * it happened.\n\t */\n\tif (lws_broadcast(wsi->context, LWS_CALLBACK_EVENT_WAIT_CANCELLED,\n\t\t\t  NULL, 0)) {\n\t\tlwsl_info(\"closed in event cancel\\n\");\n\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\t}\n\n\treturn LWS_HPI_RET_HANDLED;\n}\n\nstruct lws_role_ops role_ops_pipe = {\n\t/* role name */\t\t\t\"pipe\",\n\t/* alpn id */\t\t\tNULL,\n\t/* check_upgrades */\t\tNULL,\n\t/* init_context */\t\tNULL,\n\t/* init_vhost */\t\tNULL,\n\t/* destroy_vhost */\t\tNULL,\n\t/* periodic_checks */\t\tNULL,\n\t/* service_flag_pending */\tNULL,\n\t/* handle_POLLIN */\t\trops_handle_POLLIN_pipe,\n\t/* handle_POLLOUT */\t\tNULL,\n\t/* perform_user_POLLOUT */\tNULL,\n\t/* callback_on_writable */\tNULL,\n\t/* tx_credit */\t\t\tNULL,\n\t/* write_role_protocol */\tNULL,\n\t/* encapsulation_parent */\tNULL,\n\t/* alpn_negotiated */\t\tNULL,\n\t/* close_via_role_protocol */\tNULL,\n\t/* close_role */\t\tNULL,\n\t/* close_kill_connection */\tNULL,\n\t/* destroy_role */\t\tNULL,\n\t/* writeable cb clnt, srv */\t{ 0, 0 },\n\t/* close cb clnt, srv */\t{ 0, 0 },\n\t/* file_handle */\t\t1,\n};\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/private.h",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n *\n *  This is included from core/private.h\n */\n\ntypedef uint32_t lws_wsi_state_t;\n\n/*\n * The wsi->role_ops pointer decides almost everything about what role the wsi\n * will play, h2, raw, ws, etc.\n *\n * However there are a few additional flags needed that vary, such as if the\n * role is a client or server side, if it has that concept.  And the connection\n * fulfilling the role, has a separate dynamic state.\n *\n *   31           16 15      0\n *   [  role flags ] [ state ]\n *\n * The role flags part is generally invariant for the lifetime of the wsi,\n * although it can change if the connection role itself does, eg, if the\n * connection upgrades from H1 -> WS1 the role flags may be changed at that\n * point.\n *\n * The state part reflects the dynamic connection state, and the states are\n * reused between roles.\n *\n * None of the internal role or state representations are made available outside\n * of lws internals.  Even for lws internals, if you add stuff here, please keep\n * the constants inside this header only by adding necessary helpers here and\n * use the helpers in the actual code.  This is to ease any future refactors.\n *\n * Notice LWSIFR_ENCAP means we have a parent wsi that actually carries our\n * data as a stream inside a different protocol.\n */\n\n#define _RS 16\n\n#define LWSIFR_CLIENT\t\t(0x1000 << _RS) /* client side */\n#define LWSIFR_SERVER\t\t(0x2000 << _RS) /* server side */\n\n#define LWSIFR_P_ENCAP_H2\t(0x0100 << _RS) /* we are encapsulated by h2 */\n\nenum lwsi_role {\n\tLWSI_ROLE_MASK\t\t=\t\t\t     (0xffff << _RS),\n\tLWSI_ROLE_ENCAP_MASK\t=\t\t\t     (0x0f00 << _RS),\n};\n\n#define lwsi_role(wsi) (wsi->wsistate & LWSI_ROLE_MASK)\n#if !defined (_DEBUG)\n#define lwsi_set_role(wsi, role) wsi->wsistate = \\\n\t\t\t\t(wsi->wsistate & (~LWSI_ROLE_MASK)) | role\n#else\nvoid lwsi_set_role(struct lws *wsi, lws_wsi_state_t role);\n#endif\n\n#define lwsi_role_client(wsi) (!!(wsi->wsistate & LWSIFR_CLIENT))\n#define lwsi_role_server(wsi) (!!(wsi->wsistate & LWSIFR_SERVER))\n#define lwsi_role_h2_ENCAPSULATION(wsi) \\\n\t\t((wsi->wsistate & LWSI_ROLE_ENCAP_MASK) == LWSIFR_P_ENCAP_H2)\n\n/* Pollout wants a callback in this state */\n#define LWSIFS_POCB\t\t(0x100)\n/* Before any protocol connection was established */\n#define LWSIFS_NOT_EST\t\t(0x200)\n\nenum lwsi_state {\n\n\t/* Phase 1: pre-transport */\n\n\tLRS_UNCONNECTED\t\t\t\t= LWSIFS_NOT_EST | 0,\n\tLRS_WAITING_CONNECT\t\t\t= LWSIFS_NOT_EST | 1,\n\n\t/* Phase 2: establishing intermediaries on top of transport */\n\n\tLRS_WAITING_PROXY_REPLY\t\t\t= LWSIFS_NOT_EST | 2,\n\tLRS_WAITING_SSL\t\t\t\t= LWSIFS_NOT_EST | 3,\n\tLRS_WAITING_SOCKS_GREETING_REPLY\t= LWSIFS_NOT_EST | 4,\n\tLRS_WAITING_SOCKS_CONNECT_REPLY\t\t= LWSIFS_NOT_EST | 5,\n\tLRS_WAITING_SOCKS_AUTH_REPLY\t\t= LWSIFS_NOT_EST | 6,\n\n\t/* Phase 3: establishing tls tunnel */\n\n\tLRS_SSL_INIT\t\t\t\t= LWSIFS_NOT_EST | 7,\n\tLRS_SSL_ACK_PENDING\t\t\t= LWSIFS_NOT_EST | 8,\n\tLRS_PRE_WS_SERVING_ACCEPT\t\t= LWSIFS_NOT_EST | 9,\n\n\t/* Phase 4: connected */\n\n\tLRS_WAITING_SERVER_REPLY\t\t= LWSIFS_NOT_EST | 10,\n\tLRS_H2_AWAIT_PREFACE\t\t\t= LWSIFS_NOT_EST | 11,\n\tLRS_H2_AWAIT_SETTINGS\t\t\t= LWSIFS_NOT_EST |\n\t\t\t\t\t\t  LWSIFS_POCB | 12,\n\n\t/* Phase 5: protocol logically established */\n\n\tLRS_H2_CLIENT_SEND_SETTINGS\t\t= LWSIFS_POCB | 13,\n\tLRS_H2_WAITING_TO_SEND_HEADERS\t\t= LWSIFS_POCB | 14,\n\tLRS_DEFERRING_ACTION\t\t\t= LWSIFS_POCB | 15,\n\tLRS_IDLING\t\t\t\t= 16,\n\tLRS_H1C_ISSUE_HANDSHAKE\t\t\t= 17,\n\tLRS_H1C_ISSUE_HANDSHAKE2\t\t= 18,\n\tLRS_ISSUE_HTTP_BODY\t\t\t= 19,\n\tLRS_ISSUING_FILE\t\t\t= 20,\n\tLRS_HEADERS\t\t\t\t= 21,\n\tLRS_BODY\t\t\t\t= 22,\n\tLRS_ESTABLISHED\t\t\t\t= LWSIFS_POCB | 23,\n\t/* we are established, but we have embarked on serving a single\n\t * transaction.  Other transaction input may be pending, but we will\n\t * not service it while we are busy dealing with the current\n\t * transaction.\n\t *\n\t * When we complete the current transaction, we would reset our state\n\t * back to ESTABLISHED and start to process the next transaction.\n\t */\n\tLRS_DOING_TRANSACTION\t\t\t= LWSIFS_POCB | 24,\n\n\t/* Phase 6: finishing */\n\n\tLRS_WAITING_TO_SEND_CLOSE\t\t= LWSIFS_POCB | 25,\n\tLRS_RETURNED_CLOSE\t\t\t= LWSIFS_POCB | 26,\n\tLRS_AWAITING_CLOSE_ACK\t\t\t= LWSIFS_POCB | 27,\n\tLRS_FLUSHING_BEFORE_CLOSE\t\t= LWSIFS_POCB | 28,\n\tLRS_SHUTDOWN\t\t\t\t= 29,\n\n\t/* Phase 7: dead */\n\n\tLRS_DEAD_SOCKET\t\t\t\t= 30,\n\n\tLRS_MASK\t\t\t\t= 0xffff\n};\n\n#define lwsi_state(wsi) ((enum lwsi_state)(wsi->wsistate & LRS_MASK))\n#define lwsi_state_PRE_CLOSE(wsi) ((enum lwsi_state)(wsi->wsistate_pre_close & LRS_MASK))\n#define lwsi_state_est(wsi) (!(wsi->wsistate & LWSIFS_NOT_EST))\n#define lwsi_state_est_PRE_CLOSE(wsi) (!(wsi->wsistate_pre_close & LWSIFS_NOT_EST))\n#define lwsi_state_can_handle_POLLOUT(wsi) (wsi->wsistate & LWSIFS_POCB)\n#if !defined (_DEBUG)\n#define lwsi_set_state(wsi, lrs) wsi->wsistate = \\\n\t\t\t  (wsi->wsistate & (~LRS_MASK)) | lrs\n#else\nvoid lwsi_set_state(struct lws *wsi, lws_wsi_state_t lrs);\n#endif\n\n/*\n * internal role-specific ops\n */\nstruct lws_context_per_thread;\nstruct lws_role_ops {\n\tconst char *name;\n\tconst char *alpn;\n\t/*\n\t * After http headers have parsed, this is the last chance for a role\n\t * to upgrade the connection to something else using the headers.\n\t * ws-over-h2 is upgraded from h2 like this.\n\t */\n\tint (*check_upgrades)(struct lws *wsi);\n\t/* role-specific context init during context creation */\n\tint (*init_context)(struct lws_context *context,\n\t\t\t    const struct lws_context_creation_info *info);\n\t/* role-specific per-vhost init during vhost creation */\n\tint (*init_vhost)(struct lws_vhost *vh,\n\t\t\t  const struct lws_context_creation_info *info);\n\t/* role-specific per-vhost destructor during vhost destroy */\n\tint (*destroy_vhost)(struct lws_vhost *vh);\n\t/* generic 1Hz callback for the role itself */\n\tint (*periodic_checks)(struct lws_context *context, int tsi,\n\t\t\t       time_t now);\n\t/* chance for the role to force POLLIN without network activity */\n\tint (*service_flag_pending)(struct lws_context *context, int tsi);\n\t/* an fd using this role has POLLIN signalled */\n\tint (*handle_POLLIN)(struct lws_context_per_thread *pt, struct lws *wsi,\n\t\t\t     struct lws_pollfd *pollfd);\n\t/* an fd using the role wanted a POLLOUT callback and now has it */\n\tint (*handle_POLLOUT)(struct lws *wsi);\n\t/* perform user pollout */\n\tint (*perform_user_POLLOUT)(struct lws *wsi);\n\t/* do effective callback on writeable */\n\tint (*callback_on_writable)(struct lws *wsi);\n\t/* connection-specific tx credit in bytes */\n\tlws_fileofs_t (*tx_credit)(struct lws *wsi);\n\t/* role-specific write formatting */\n\tint (*write_role_protocol)(struct lws *wsi, unsigned char *buf,\n\t\t\t\t   size_t len, enum lws_write_protocol *wp);\n\n\t/* get encapsulation parent */\n\tstruct lws * (*encapsulation_parent)(struct lws *wsi);\n\n\t/* role-specific destructor */\n\tint (*alpn_negotiated)(struct lws *wsi, const char *alpn);\n\n\t/* chance for the role to handle close in the protocol */\n\tint (*close_via_role_protocol)(struct lws *wsi,\n\t\t\t\t       enum lws_close_status reason);\n\t/* role-specific close processing */\n\tint (*close_role)(struct lws_context_per_thread *pt, struct lws *wsi);\n\t/* role-specific connection close processing */\n\tint (*close_kill_connection)(struct lws *wsi,\n\t\t\t\t     enum lws_close_status reason);\n\t/* role-specific destructor */\n\tint (*destroy_role)(struct lws *wsi);\n\n\t/*\n\t * the callback reasons for WRITEABLE for client, server\n\t * (just client applies if no concept of client or server)\n\t */\n\tuint16_t writeable_cb[2];\n\t/*\n\t * the callback reasons for CLOSE for client, server\n\t * (just client applies if no concept of client or server)\n\t */\n\tuint16_t close_cb[2];\n\n\tunsigned int file_handle:1; /* role operates on files not sockets */\n};\n\n/* core roles */\nextern struct lws_role_ops role_ops_raw_skt, role_ops_raw_file, role_ops_listen,\n\t\t\t   role_ops_pipe;\n\n/* bring in role private declarations */\n\n#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)\n #include \"roles/http/private.h\"\n#else\n #define lwsi_role_http(wsi) (0)\n#endif\n\n#if defined(LWS_ROLE_H1)\n #include \"roles/h1/private.h\"\n#else\n #define lwsi_role_h1(wsi) (0)\n#endif\n\n#if defined(LWS_ROLE_H2)\n #include \"roles/h2/private.h\"\n#else\n #define lwsi_role_h2(wsi) (0)\n#endif\n\n#if defined(LWS_ROLE_WS)\n #include \"roles/ws/private.h\"\n#else\n #define lwsi_role_ws(wsi) (0)\n#endif\n\n#if defined(LWS_ROLE_CGI)\n #include \"roles/cgi/private.h\"\n#else\n #define lwsi_role_cgi(wsi) (0)\n#endif\n\nenum {\n\tLWS_HP_RET_BAIL_OK,\n\tLWS_HP_RET_BAIL_DIE,\n\tLWS_HP_RET_USER_SERVICE,\n\n\tLWS_HPI_RET_WSI_ALREADY_DIED,\t/* we closed it */\n\tLWS_HPI_RET_HANDLED,\t\t/* no probs */\n\tLWS_HPI_RET_PLEASE_CLOSE_ME,\t/* close it for us */\n\n\tLWS_UPG_RET_DONE,\n\tLWS_UPG_RET_CONTINUE,\n\tLWS_UPG_RET_BAIL\n};\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/raw/ops-raw.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include <core/private.h>\n\nstatic int\nrops_handle_POLLIN_raw_skt(struct lws_context_per_thread *pt, struct lws *wsi,\n\t\t\t   struct lws_pollfd *pollfd)\n{\n\tstruct lws_tokens ebuf;\n\tint n, buffered;\n\n\t/* pending truncated sends have uber priority */\n\n\tif (wsi->trunc_len) {\n\t\tif (!(pollfd->revents & LWS_POLLOUT))\n\t\t\treturn LWS_HPI_RET_HANDLED;\n\n\t\tif (lws_issue_raw(wsi, wsi->trunc_alloc + wsi->trunc_offset,\n\t\t\t\t  wsi->trunc_len) < 0)\n\t\t\tgoto fail;\n\t\t/*\n\t\t * we can't afford to allow input processing to send\n\t\t * something new, so spin around he event loop until\n\t\t * he doesn't have any partials\n\t\t */\n\t\treturn LWS_HPI_RET_HANDLED;\n\t}\n\n\tif ((pollfd->revents & pollfd->events & LWS_POLLIN) &&\n\t    /* any tunnel has to have been established... */\n\t    lwsi_state(wsi) != LRS_SSL_ACK_PENDING &&\n\t    !(wsi->favoured_pollin &&\n\t      (pollfd->revents & pollfd->events & LWS_POLLOUT))) {\n\n\t\tbuffered = lws_buflist_aware_read(pt, wsi, &ebuf);\n\t\tswitch (ebuf.len) {\n\t\tcase 0:\n\t\t\tlwsl_info(\"%s: read 0 len\\n\", __func__);\n\t\t\twsi->seen_zero_length_recv = 1;\n\t\t\tlws_change_pollfd(wsi, LWS_POLLIN, 0);\n\n\t\t\t/*\n\t\t\t * we need to go to fail here, since it's the only\n\t\t\t * chance we get to understand that the socket has\n\t\t\t * closed\n\t\t\t */\n\t\t\t// goto try_pollout;\n\t\t\tgoto fail;\n\n\t\tcase LWS_SSL_CAPABLE_ERROR:\n\t\t\tgoto fail;\n\t\tcase LWS_SSL_CAPABLE_MORE_SERVICE:\n\t\t\tgoto try_pollout;\n\t\t}\n\n\t\tn = user_callback_handle_rxflow(wsi->protocol->callback,\n\t\t\t\t\t\twsi, LWS_CALLBACK_RAW_RX,\n\t\t\t\t\t\twsi->user_space, ebuf.token,\n\t\t\t\t\t\tebuf.len);\n\t\tif (n < 0) {\n\t\t\tlwsl_info(\"LWS_CALLBACK_RAW_RX_fail\\n\");\n\t\t\tgoto fail;\n\t\t}\n\n\t\tif (lws_buflist_aware_consume(wsi, &ebuf, ebuf.len, buffered))\n\t\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\t} else\n\t\tif (wsi->favoured_pollin &&\n\t\t    (pollfd->revents & pollfd->events & LWS_POLLOUT))\n\t\t\t/* we balanced the last favouring of pollin */\n\t\t\twsi->favoured_pollin = 0;\n\ntry_pollout:\n\n\t/* this handles POLLOUT for http serving fragments */\n\n\tif (!(pollfd->revents & LWS_POLLOUT))\n\t\treturn LWS_HPI_RET_HANDLED;\n\n\t/* one shot */\n\tif (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {\n\t\tlwsl_notice(\"%s a\\n\", __func__);\n\t\tgoto fail;\n\t}\n\n\t/* clear back-to-back write detection */\n\twsi->could_have_pending = 0;\n\n\tlws_stats_atomic_bump(wsi->context, pt,\n\t\t\t\tLWSSTATS_C_WRITEABLE_CB, 1);\n#if defined(LWS_WITH_STATS)\n\tif (wsi->active_writable_req_us) {\n\t\tuint64_t ul = time_in_microseconds() -\n\t\t\t\twsi->active_writable_req_us;\n\n\t\tlws_stats_atomic_bump(wsi->context, pt,\n\t\t\t\tLWSSTATS_MS_WRITABLE_DELAY, ul);\n\t\tlws_stats_atomic_max(wsi->context, pt,\n\t\t\t  LWSSTATS_MS_WORST_WRITABLE_DELAY, ul);\n\t\twsi->active_writable_req_us = 0;\n\t}\n#endif\n\tn = user_callback_handle_rxflow(wsi->protocol->callback,\n\t\t\twsi, LWS_CALLBACK_RAW_WRITEABLE,\n\t\t\twsi->user_space, NULL, 0);\n\tif (n < 0) {\n\t\tlwsl_info(\"writeable_fail\\n\");\n\t\tgoto fail;\n\t}\n\n\treturn LWS_HPI_RET_HANDLED;\n\nfail:\n\tlws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, \"raw svc fail\");\n\n\treturn LWS_HPI_RET_WSI_ALREADY_DIED;\n}\n\n\nstatic int\nrops_handle_POLLIN_raw_file(struct lws_context_per_thread *pt, struct lws *wsi,\n\t\t\t    struct lws_pollfd *pollfd)\n{\n\tint n;\n\n\tif (pollfd->revents & LWS_POLLOUT) {\n\t\tn = lws_callback_as_writeable(wsi);\n\t\tif (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {\n\t\t\tlwsl_info(\"failed at set pollfd\\n\");\n\t\t\treturn LWS_HPI_RET_WSI_ALREADY_DIED;\n\t\t}\n\t\tif (n)\n\t\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\t}\n\n\tif (pollfd->revents & LWS_POLLIN) {\n\t\tif (user_callback_handle_rxflow(wsi->protocol->callback,\n\t\t\t\t\t\twsi, LWS_CALLBACK_RAW_RX_FILE,\n\t\t\t\t\t\twsi->user_space, NULL, 0)) {\n\t\t\tlwsl_debug(\"raw rx callback closed it\\n\");\n\t\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\t\t}\n\t}\n\n\tif (pollfd->revents & LWS_POLLHUP)\n\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\n\treturn LWS_HPI_RET_HANDLED;\n}\n\n\nstruct lws_role_ops role_ops_raw_skt = {\n\t/* role name */\t\t\t\"raw-skt\",\n\t/* alpn id */\t\t\tNULL,\n\t/* check_upgrades */\t\tNULL,\n\t/* init_context */\t\tNULL,\n\t/* init_vhost */\t\tNULL,\n\t/* destroy_vhost */\t\tNULL,\n\t/* periodic_checks */\t\tNULL,\n\t/* service_flag_pending */\tNULL,\n\t/* handle_POLLIN */\t\trops_handle_POLLIN_raw_skt,\n\t/* handle_POLLOUT */\t\tNULL,\n\t/* perform_user_POLLOUT */\tNULL,\n\t/* callback_on_writable */\tNULL,\n\t/* tx_credit */\t\t\tNULL,\n\t/* write_role_protocol */\tNULL,\n\t/* encapsulation_parent */\tNULL,\n\t/* alpn_negotiated */\t\tNULL,\n\t/* close_via_role_protocol */\tNULL,\n\t/* close_role */\t\tNULL,\n\t/* close_kill_connection */\tNULL,\n\t/* destroy_role */\t\tNULL,\n\t/* writeable cb clnt, srv */\t{ LWS_CALLBACK_RAW_WRITEABLE, 0 },\n\t/* close cb clnt, srv */\t{ LWS_CALLBACK_RAW_CLOSE, 0 },\n\t/* file_handle */\t\t0,\n};\n\n\n\nstruct lws_role_ops role_ops_raw_file = {\n\t/* role name */\t\t\t\"raw-file\",\n\t/* alpn id */\t\t\tNULL,\n\t/* check_upgrades */\t\tNULL,\n\t/* init_context */\t\tNULL,\n\t/* init_vhost */\t\tNULL,\n\t/* destroy_vhost */\t\tNULL,\n\t/* periodic_checks */\t\tNULL,\n\t/* service_flag_pending */\tNULL,\n\t/* handle_POLLIN */\t\trops_handle_POLLIN_raw_file,\n\t/* handle_POLLOUT */\t\tNULL,\n\t/* perform_user_POLLOUT */\tNULL,\n\t/* callback_on_writable */\tNULL,\n\t/* tx_credit */\t\t\tNULL,\n\t/* write_role_protocol */\tNULL,\n\t/* encapsulation_parent */\tNULL,\n\t/* alpn_negotiated */\t\tNULL,\n\t/* close_via_role_protocol */\tNULL,\n\t/* close_role */\t\tNULL,\n\t/* close_kill_connection */\tNULL,\n\t/* destroy_role */\t\tNULL,\n\t/* writeable cb clnt, srv */\t{ LWS_CALLBACK_RAW_WRITEABLE_FILE, 0 },\n\t/* close cb clnt, srv */\t{ LWS_CALLBACK_RAW_CLOSE_FILE, 0 },\n\t/* file_handle */\t\t1,\n};\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/ws/client-parser-ws.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n\n/*\n * parsers.c: lws_ws_rx_sm() needs to be roughly kept in\n *   sync with changes here, esp related to ext draining\n */\n\nint lws_ws_client_rx_sm(struct lws *wsi, unsigned char c)\n{\n\tint callback_action = LWS_CALLBACK_CLIENT_RECEIVE;\n\tint handled, m;\n\tunsigned short close_code;\n\tstruct lws_tokens ebuf;\n\tunsigned char *pp;\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tint rx_draining_ext = 0, n;\n#endif\n\n\tebuf.token = NULL;\n\tebuf.len = 0;\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tif (wsi->ws->rx_draining_ext) {\n\t\tassert(!c);\n\n\t\tlws_remove_wsi_from_draining_ext_list(wsi);\n\t\trx_draining_ext = 1;\n\t\tlwsl_debug(\"%s: doing draining flow\\n\", __func__);\n\n\t\tgoto drain_extension;\n\t}\n#endif\n\n\tif (wsi->socket_is_permanently_unusable)\n\t\treturn -1;\n\n\tswitch (wsi->lws_rx_parse_state) {\n\tcase LWS_RXPS_NEW:\n\t\t/* control frames (PING) may interrupt checkable sequences */\n\t\twsi->ws->defeat_check_utf8 = 0;\n\n\t\tswitch (wsi->ws->ietf_spec_revision) {\n\t\tcase 13:\n\t\t\twsi->ws->opcode = c & 0xf;\n\t\t\t/* revisit if an extension wants them... */\n\t\t\tswitch (wsi->ws->opcode) {\n\t\t\tcase LWSWSOPC_TEXT_FRAME:\n\t\t\t\twsi->ws->rsv_first_msg = (c & 0x70);\n\t\t\t\twsi->ws->continuation_possible = 1;\n\t\t\t\twsi->ws->check_utf8 = lws_check_opt(\n\t\t\t\t\twsi->context->options,\n\t\t\t\t\tLWS_SERVER_OPTION_VALIDATE_UTF8);\n\t\t\t\twsi->ws->utf8 = 0;\n\t\t\t\twsi->ws->first_fragment = 1;\n\t\t\t\tbreak;\n\t\t\tcase LWSWSOPC_BINARY_FRAME:\n\t\t\t\twsi->ws->rsv_first_msg = (c & 0x70);\n\t\t\t\twsi->ws->check_utf8 = 0;\n\t\t\t\twsi->ws->continuation_possible = 1;\n\t\t\t\twsi->ws->first_fragment = 1;\n\t\t\t\tbreak;\n\t\t\tcase LWSWSOPC_CONTINUATION:\n\t\t\t\tif (!wsi->ws->continuation_possible) {\n\t\t\t\t\tlwsl_info(\"disordered continuation\\n\");\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\twsi->ws->first_fragment = 0;\n\t\t\t\tbreak;\n\t\t\tcase LWSWSOPC_CLOSE:\n\t\t\t\twsi->ws->check_utf8 = 0;\n\t\t\t\twsi->ws->utf8 = 0;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\tcase 4:\n\t\t\tcase 5:\n\t\t\tcase 6:\n\t\t\tcase 7:\n\t\t\tcase 0xb:\n\t\t\tcase 0xc:\n\t\t\tcase 0xd:\n\t\t\tcase 0xe:\n\t\t\tcase 0xf:\n\t\t\t\tlwsl_info(\"illegal opcode\\n\");\n\t\t\t\treturn -1;\n\t\t\tdefault:\n\t\t\t\twsi->ws->defeat_check_utf8 = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\twsi->ws->rsv = (c & 0x70);\n\t\t\t/* revisit if an extension wants them... */\n\t\t\tif (\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\t\t\t!wsi->ws->count_act_ext &&\n#endif\n\t\t\t\twsi->ws->rsv) {\n\t\t\t\tlwsl_info(\"illegal rsv bits set\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\twsi->ws->final = !!((c >> 7) & 1);\n\t\t\tlwsl_ext(\"%s:    This RX frame Final %d\\n\", __func__,\n\t\t\t\t wsi->ws->final);\n\n\t\t\tif (wsi->ws->owed_a_fin &&\n\t\t\t    (wsi->ws->opcode == LWSWSOPC_TEXT_FRAME ||\n\t\t\t     wsi->ws->opcode == LWSWSOPC_BINARY_FRAME)) {\n\t\t\t\tlwsl_info(\"hey you owed us a FIN\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif ((!(wsi->ws->opcode & 8)) && wsi->ws->final) {\n\t\t\t\twsi->ws->continuation_possible = 0;\n\t\t\t\twsi->ws->owed_a_fin = 0;\n\t\t\t}\n\n\t\t\tif ((wsi->ws->opcode & 8) && !wsi->ws->final) {\n\t\t\t\tlwsl_info(\"control msg can't be fragmented\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (!wsi->ws->final)\n\t\t\t\twsi->ws->owed_a_fin = 1;\n\n\t\t\tswitch (wsi->ws->opcode) {\n\t\t\tcase LWSWSOPC_TEXT_FRAME:\n\t\t\tcase LWSWSOPC_BINARY_FRAME:\n\t\t\t\twsi->ws->frame_is_binary = wsi->ws->opcode ==\n\t\t\t\t\t\t LWSWSOPC_BINARY_FRAME;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tlwsl_err(\"unknown spec version %02d\\n\",\n\t\t\t\t wsi->ws->ietf_spec_revision);\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN:\n\n\t\twsi->ws->this_frame_masked = !!(c & 0x80);\n\n\t\tswitch (c & 0x7f) {\n\t\tcase 126:\n\t\t\t/* control frames are not allowed to have big lengths */\n\t\t\tif (wsi->ws->opcode & 8)\n\t\t\t\tgoto illegal_ctl_length;\n\t\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;\n\t\t\tbreak;\n\t\tcase 127:\n\t\t\t/* control frames are not allowed to have big lengths */\n\t\t\tif (wsi->ws->opcode & 8)\n\t\t\t\tgoto illegal_ctl_length;\n\t\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\twsi->ws->rx_packet_length = c & 0x7f;\n\t\t\tif (wsi->ws->this_frame_masked)\n\t\t\t\twsi->lws_rx_parse_state =\n\t\t\t\t\t\tLWS_RXPS_07_COLLECT_FRAME_KEY_1;\n\t\t\telse {\n\t\t\t\tif (wsi->ws->rx_packet_length) {\n\t\t\t\t\twsi->lws_rx_parse_state =\n\t\t\t\t\tLWS_RXPS_WS_FRAME_PAYLOAD;\n\t\t\t\t} else {\n\t\t\t\t\twsi->lws_rx_parse_state = LWS_RXPS_NEW;\n\t\t\t\t\tgoto spill;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN16_2:\n\t\twsi->ws->rx_packet_length = c << 8;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN16_1:\n\t\twsi->ws->rx_packet_length |= c;\n\t\tif (wsi->ws->this_frame_masked)\n\t\t\twsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_1;\n\t\telse {\n\t\t\tif (wsi->ws->rx_packet_length)\n\t\t\t\twsi->lws_rx_parse_state =\n\t\t\t\t\tLWS_RXPS_WS_FRAME_PAYLOAD;\n\t\t\telse {\n\t\t\t\twsi->lws_rx_parse_state = LWS_RXPS_NEW;\n\t\t\t\tgoto spill;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN64_8:\n\t\tif (c & 0x80) {\n\t\t\tlwsl_warn(\"b63 of length must be zero\\n\");\n\t\t\t/* kill the connection */\n\t\t\treturn -1;\n\t\t}\n#if defined __LP64__\n\t\twsi->ws->rx_packet_length = ((size_t)c) << 56;\n#else\n\t\twsi->ws->rx_packet_length = 0;\n#endif\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN64_7:\n#if defined __LP64__\n\t\twsi->ws->rx_packet_length |= ((size_t)c) << 48;\n#endif\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN64_6:\n#if defined __LP64__\n\t\twsi->ws->rx_packet_length |= ((size_t)c) << 40;\n#endif\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN64_5:\n#if defined __LP64__\n\t\twsi->ws->rx_packet_length |= ((size_t)c) << 32;\n#endif\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN64_4:\n\t\twsi->ws->rx_packet_length |= ((size_t)c) << 24;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN64_3:\n\t\twsi->ws->rx_packet_length |= ((size_t)c) << 16;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN64_2:\n\t\twsi->ws->rx_packet_length |= ((size_t)c) << 8;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN64_1:\n\t\twsi->ws->rx_packet_length |= (size_t)c;\n\t\tif (wsi->ws->this_frame_masked)\n\t\t\twsi->lws_rx_parse_state =\n\t\t\t\t\tLWS_RXPS_07_COLLECT_FRAME_KEY_1;\n\t\telse {\n\t\t\tif (wsi->ws->rx_packet_length)\n\t\t\t\twsi->lws_rx_parse_state =\n\t\t\t\t\tLWS_RXPS_WS_FRAME_PAYLOAD;\n\t\t\telse {\n\t\t\t\twsi->lws_rx_parse_state = LWS_RXPS_NEW;\n\t\t\t\tgoto spill;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase LWS_RXPS_07_COLLECT_FRAME_KEY_1:\n\t\twsi->ws->mask[0] = c;\n\t\tif (c)\n\t\t\twsi->ws->all_zero_nonce = 0;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2;\n\t\tbreak;\n\n\tcase LWS_RXPS_07_COLLECT_FRAME_KEY_2:\n\t\twsi->ws->mask[1] = c;\n\t\tif (c)\n\t\t\twsi->ws->all_zero_nonce = 0;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3;\n\t\tbreak;\n\n\tcase LWS_RXPS_07_COLLECT_FRAME_KEY_3:\n\t\twsi->ws->mask[2] = c;\n\t\tif (c)\n\t\t\twsi->ws->all_zero_nonce = 0;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4;\n\t\tbreak;\n\n\tcase LWS_RXPS_07_COLLECT_FRAME_KEY_4:\n\t\twsi->ws->mask[3] = c;\n\t\tif (c)\n\t\t\twsi->ws->all_zero_nonce = 0;\n\n\t\tif (wsi->ws->rx_packet_length)\n\t\t\twsi->lws_rx_parse_state =\n\t\t\t\t\tLWS_RXPS_WS_FRAME_PAYLOAD;\n\t\telse {\n\t\t\twsi->lws_rx_parse_state = LWS_RXPS_NEW;\n\t\t\tgoto spill;\n\t\t}\n\t\tbreak;\n\n\tcase LWS_RXPS_WS_FRAME_PAYLOAD:\n\n\t\tassert(wsi->ws->rx_ubuf);\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\tif (wsi->ws->rx_draining_ext)\n\t\t\tgoto drain_extension;\n#endif\n\t\tif (wsi->ws->this_frame_masked && !wsi->ws->all_zero_nonce)\n\t\t\tc ^= wsi->ws->mask[(wsi->ws->mask_idx++) & 3];\n\n\t\twsi->ws->rx_ubuf[LWS_PRE + (wsi->ws->rx_ubuf_head++)] = c;\n\n\t\tif (--wsi->ws->rx_packet_length == 0) {\n\t\t\t/* spill because we have the whole frame */\n\t\t\twsi->lws_rx_parse_state = LWS_RXPS_NEW;\n\t\t\tgoto spill;\n\t\t}\n\n\t\t/*\n\t\t * if there's no protocol max frame size given, we are\n\t\t * supposed to default to context->pt_serv_buf_size\n\t\t */\n\t\tif (!wsi->protocol->rx_buffer_size &&\n\t\t    wsi->ws->rx_ubuf_head != wsi->context->pt_serv_buf_size)\n\t\t\tbreak;\n\n\t\tif (wsi->protocol->rx_buffer_size &&\n\t\t    wsi->ws->rx_ubuf_head != wsi->protocol->rx_buffer_size)\n\t\t\tbreak;\n\n\t\t/* spill because we filled our rx buffer */\nspill:\n\n\t\thandled = 0;\n\n\t\t/*\n\t\t * is this frame a control packet we should take care of at this\n\t\t * layer?  If so service it and hide it from the user callback\n\t\t */\n\n\t\tswitch (wsi->ws->opcode) {\n\t\tcase LWSWSOPC_CLOSE:\n\t\t\tpp = (unsigned char *)&wsi->ws->rx_ubuf[LWS_PRE];\n\t\t\tif (lws_check_opt(wsi->context->options,\n\t\t\t\t\t  LWS_SERVER_OPTION_VALIDATE_UTF8) &&\n\t\t\t    wsi->ws->rx_ubuf_head > 2 &&\n\t\t\t    lws_check_utf8(&wsi->ws->utf8, pp + 2,\n\t\t\t\t\t   wsi->ws->rx_ubuf_head - 2))\n\t\t\t\tgoto utf8_fail;\n\n\t\t\t/* is this an acknowledgment of our close? */\n\t\t\tif (lwsi_state(wsi) == LRS_AWAITING_CLOSE_ACK) {\n\t\t\t\t/*\n\t\t\t\t * fine he has told us he is closing too, let's\n\t\t\t\t * finish our close\n\t\t\t\t */\n\t\t\t\tlwsl_parser(\"seen server's close ack\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tlwsl_parser(\"client sees server close len = %d\\n\",\n\t\t\t\t\t\t wsi->ws->rx_ubuf_head);\n\t\t\tif (wsi->ws->rx_ubuf_head >= 2) {\n\t\t\t\tclose_code = (pp[0] << 8) | pp[1];\n\t\t\t\tif (close_code < 1000 ||\n\t\t\t\t    close_code == 1004 ||\n\t\t\t\t    close_code == 1005 ||\n\t\t\t\t    close_code == 1006 ||\n\t\t\t\t    close_code == 1012 ||\n\t\t\t\t    close_code == 1013 ||\n\t\t\t\t    close_code == 1014 ||\n\t\t\t\t    close_code == 1015 ||\n\t\t\t\t    (close_code >= 1016 && close_code < 3000)\n\t\t\t\t) {\n\t\t\t\t\tpp[0] = (LWS_CLOSE_STATUS_PROTOCOL_ERR >> 8) & 0xff;\n\t\t\t\t\tpp[1] = LWS_CLOSE_STATUS_PROTOCOL_ERR & 0xff;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (user_callback_handle_rxflow(\n\t\t\t\t\twsi->protocol->callback, wsi,\n\t\t\t\t\tLWS_CALLBACK_WS_PEER_INITIATED_CLOSE,\n\t\t\t\t\twsi->user_space, pp,\n\t\t\t\t\twsi->ws->rx_ubuf_head))\n\t\t\t\treturn -1;\n\n\t\t\tmemcpy(wsi->ws->ping_payload_buf + LWS_PRE, pp,\n\t\t\t       wsi->ws->rx_ubuf_head);\n\t\t\twsi->ws->close_in_ping_buffer_len = wsi->ws->rx_ubuf_head;\n\n\t\t\tlwsl_info(\"%s: scheduling return close as ack\\n\", __func__);\n\t\t\t__lws_change_pollfd(wsi, LWS_POLLIN, 0);\n\t\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_SEND, 3);\n\t\t\twsi->waiting_to_send_close_frame = 1;\n\t\t\twsi->close_needs_ack = 0;\n\t\t\tlwsi_set_state(wsi, LRS_WAITING_TO_SEND_CLOSE);\n\t\t\tlws_callback_on_writable(wsi);\n\t\t\thandled = 1;\n\t\t\tbreak;\n\n\t\tcase LWSWSOPC_PING:\n\t\t\tlwsl_info(\"received %d byte ping, sending pong\\n\",\n\t\t\t\t  wsi->ws->rx_ubuf_head);\n\n\t\t\t/* he set a close reason on this guy, ignore PING */\n\t\t\tif (wsi->ws->close_in_ping_buffer_len)\n\t\t\t\tgoto ping_drop;\n\n\t\t\tif (wsi->ws->ping_pending_flag) {\n\t\t\t\t/*\n\t\t\t\t * there is already a pending ping payload\n\t\t\t\t * we should just log and drop\n\t\t\t\t */\n\t\t\t\tlwsl_parser(\"DROP PING since one pending\\n\");\n\t\t\t\tgoto ping_drop;\n\t\t\t}\n\n\t\t\t/* control packets can only be < 128 bytes long */\n\t\t\tif (wsi->ws->rx_ubuf_head > 128 - 3) {\n\t\t\t\tlwsl_parser(\"DROP PING payload too large\\n\");\n\t\t\t\tgoto ping_drop;\n\t\t\t}\n\n\t\t\t/* stash the pong payload */\n\t\t\tmemcpy(wsi->ws->ping_payload_buf + LWS_PRE,\n\t\t\t       &wsi->ws->rx_ubuf[LWS_PRE],\n\t\t\t\twsi->ws->rx_ubuf_head);\n\n\t\t\twsi->ws->ping_payload_len = wsi->ws->rx_ubuf_head;\n\t\t\twsi->ws->ping_pending_flag = 1;\n\n\t\t\t/* get it sent as soon as possible */\n\t\t\tlws_callback_on_writable(wsi);\nping_drop:\n\t\t\twsi->ws->rx_ubuf_head = 0;\n\t\t\thandled = 1;\n\t\t\tbreak;\n\n\t\tcase LWSWSOPC_PONG:\n\t\t\tlwsl_info(\"client received pong\\n\");\n\t\t\tlwsl_hexdump(&wsi->ws->rx_ubuf[LWS_PRE],\n\t\t\t\t     wsi->ws->rx_ubuf_head);\n\n\t\t\tif (wsi->pending_timeout ==\n\t\t\t\t       PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG) {\n\t\t\t\tlwsl_info(\"%p: received expected PONG\\n\", wsi);\n\t\t\t\tlws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);\n\t\t\t}\n\n\t\t\t/* issue it */\n\t\t\tcallback_action = LWS_CALLBACK_CLIENT_RECEIVE_PONG;\n\t\t\tbreak;\n\n\t\tcase LWSWSOPC_CONTINUATION:\n\t\tcase LWSWSOPC_TEXT_FRAME:\n\t\tcase LWSWSOPC_BINARY_FRAME:\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t/* not handled or failed */\n\t\t\tlwsl_ext(\"Unhandled ext opc 0x%x\\n\", wsi->ws->opcode);\n\t\t\twsi->ws->rx_ubuf_head = 0;\n\n\t\t\treturn -1;\n\t\t}\n\n\t\t/*\n\t\t * No it's real payload, pass it up to the user callback.\n\t\t * It's nicely buffered with the pre-padding taken care of\n\t\t * so it can be sent straight out again using lws_write\n\t\t */\n\t\tif (handled)\n\t\t\tgoto already_done;\n\n\t\tebuf.token = &wsi->ws->rx_ubuf[LWS_PRE];\n\t\tebuf.len = wsi->ws->rx_ubuf_head;\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\ndrain_extension:\n\t\tlwsl_ext(\"%s: passing %d to ext\\n\", __func__, ebuf.len);\n\n\t\tn = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &ebuf, 0);\n\t\tlwsl_ext(\"Ext RX returned %d\\n\", n);\n\t\tif (n < 0) {\n\t\t\twsi->socket_is_permanently_unusable = 1;\n\t\t\treturn -1;\n\t\t}\n#endif\n\t\tlwsl_debug(\"post inflate ebuf len %d\\n\", ebuf.len);\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\tif (rx_draining_ext && !ebuf.len) {\n\t\t\tlwsl_debug(\"   --- ending drain on 0 read result\\n\");\n\t\t\tgoto already_done;\n\t\t}\n#endif\n\n\t\tif (wsi->ws->check_utf8 && !wsi->ws->defeat_check_utf8) {\n\t\t\tif (lws_check_utf8(&wsi->ws->utf8,\n\t\t\t\t\t   (unsigned char *)ebuf.token,\n\t\t\t\t\t   ebuf.len)) {\n\t\t\t\tlws_close_reason(wsi,\n\t\t\t\t\tLWS_CLOSE_STATUS_INVALID_PAYLOAD,\n\t\t\t\t\t(uint8_t *)\"bad utf8\", 8);\n\t\t\t\tgoto utf8_fail;\n\t\t\t}\n\n\t\t\t/* we are ending partway through utf-8 character? */\n\t\t\tif (!wsi->ws->rx_packet_length && wsi->ws->final &&\n\t\t\t    wsi->ws->utf8\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\t\t    && !n\n#endif\n\t\t\t    ) {\n\t\t\t\tlwsl_info(\"FINAL utf8 error\\n\");\n\t\t\t\tlws_close_reason(wsi,\n\t\t\t\t\tLWS_CLOSE_STATUS_INVALID_PAYLOAD,\n\t\t\t\t\t(uint8_t *)\"partial utf8\", 12);\nutf8_fail:\n\t\t\t\tlwsl_info(\"utf8 error\\n\");\n\t\t\t\tlwsl_hexdump_info(ebuf.token, ebuf.len);\n\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\tif (ebuf.len < 0 &&\n\t\t    callback_action != LWS_CALLBACK_CLIENT_RECEIVE_PONG)\n\t\t\tgoto already_done;\n\n\t\tif (!ebuf.token)\n\t\t\tgoto already_done;\n\n\t\tebuf.token[ebuf.len] = '\\0';\n\n\t\tif (!wsi->protocol->callback)\n\t\t\tgoto already_done;\n\n\t\tif (callback_action == LWS_CALLBACK_CLIENT_RECEIVE_PONG)\n\t\t\tlwsl_info(\"Client doing pong callback\\n\");\n\n\t\tif (\n\t\t\t\t/* coverity says dead code otherwise */\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\t\t\tn &&\n#endif\n\t\t\t\tebuf.len)\n\t\t\t/* extension had more... main loop will come back\n\t\t\t * we want callback to be done with this set, if so,\n\t\t\t * because lws_is_final() hides it was final until the\n\t\t\t * last chunk\n\t\t\t */\n\t\t\tlws_add_wsi_to_draining_ext_list(wsi);\n\t\telse\n\t\t\tlws_remove_wsi_from_draining_ext_list(wsi);\n\n\t\tif (lwsi_state(wsi) == LRS_RETURNED_CLOSE ||\n\t\t    lwsi_state(wsi) == LRS_WAITING_TO_SEND_CLOSE ||\n\t\t    lwsi_state(wsi) == LRS_AWAITING_CLOSE_ACK)\n\t\t\tgoto already_done;\n\n\t\tm = wsi->protocol->callback(wsi,\n\t\t\t(enum lws_callback_reasons)callback_action,\n\t\t\twsi->user_space, ebuf.token, ebuf.len);\n\n\t\twsi->ws->first_fragment = 0;\n\n\t\t// lwsl_notice(\"%s: bulk ws rx: input used %d, output %d\\n\",\n\t\t//\t__func__, wsi->ws->rx_ubuf_head, ebuf.len);\n\n\t\t/* if user code wants to close, let caller know */\n\t\tif (m)\n\t\t\treturn 1;\n\nalready_done:\n\t\twsi->ws->rx_ubuf_head = 0;\n\t\tbreak;\n\tdefault:\n\t\tlwsl_err(\"client rx illegal state\\n\");\n\t\treturn 1;\n\t}\n\n\treturn 0;\n\nillegal_ctl_length:\n\tlwsl_warn(\"Control frame asking for extended length is illegal\\n\");\n\n\t/* kill the connection */\n\treturn -1;\n}\n\n\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/ws/client-ws.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include <core/private.h>\n\n/*\n * In-place str to lower case\n */\n\nstatic void\nstrtolower(char *s)\n{\n\twhile (*s) {\n#ifdef LWS_PLAT_OPTEE\n\t\tint tolower_optee(int c);\n\t\t*s = tolower_optee((int)*s);\n#else\n\t\t*s = tolower((int)*s);\n#endif\n\t\ts++;\n\t}\n}\n\nint\nlws_create_client_ws_object(struct lws_client_connect_info *i, struct lws *wsi)\n{\n\tint v = SPEC_LATEST_SUPPORTED;\n\n\t/* allocate the ws struct for the wsi */\n\twsi->ws = lws_zalloc(sizeof(*wsi->ws), \"client ws struct\");\n\tif (!wsi->ws) {\n\t\tlwsl_notice(\"OOM\\n\");\n\t\treturn 1;\n\t}\n\n\t/* -1 means just use latest supported */\n\tif (i->ietf_version_or_minus_one != -1 &&\n\t    i->ietf_version_or_minus_one)\n\t\tv = i->ietf_version_or_minus_one;\n\n\twsi->ws->ietf_spec_revision = v;\n\n\treturn 0;\n}\n\n#if !defined(LWS_NO_CLIENT)\nint\nlws_ws_handshake_client(struct lws *wsi, unsigned char **buf, size_t len)\n{\n\tif ((lwsi_state(wsi) != LRS_WAITING_PROXY_REPLY) &&\n\t    (lwsi_state(wsi) != LRS_H1C_ISSUE_HANDSHAKE) &&\n\t    (lwsi_state(wsi) != LRS_WAITING_SERVER_REPLY) &&\n\t    !lwsi_role_client(wsi))\n\t\treturn 0;\n\n\t// lwsl_notice(\"%s: hs client gets %d in\\n\", __func__, (int)len);\n\n\twhile (len) {\n\t\t/*\n\t\t * we were accepting input but now we stopped doing so\n\t\t */\n\t\tif (lws_is_flowcontrolled(wsi)) {\n\t\t\t//lwsl_notice(\"%s: caching %ld\\n\", __func__, (long)len);\n\t\t\tlws_rxflow_cache(wsi, *buf, 0, (int)len);\n\t\t\t*buf += len;\n\t\t\treturn 0;\n\t\t}\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\tif (wsi->ws->rx_draining_ext) {\n\t\t\tint m;\n\n\t\t\t//lwsl_notice(\"%s: draining ext\\n\", __func__);\n\t\t\tif (lwsi_role_client(wsi))\n\t\t\t\tm = lws_ws_client_rx_sm(wsi, 0);\n\t\t\telse\n\t\t\t\tm = lws_ws_rx_sm(wsi, 0, 0);\n\t\t\tif (m < 0)\n\t\t\t\treturn -1;\n\t\t\tcontinue;\n\t\t}\n#endif\n\t\t/* caller will account for buflist usage */\n\n\t\tif (lws_ws_client_rx_sm(wsi, *(*buf)++)) {\n\t\t\tlwsl_notice(\"%s: client_rx_sm exited, DROPPING %d\\n\",\n\t\t\t\t    __func__, (int)len);\n\t\t\treturn -1;\n\t\t}\n\t\tlen--;\n\t}\n\t// lwsl_notice(\"%s: finished with %ld\\n\", __func__, (long)len);\n\n\treturn 0;\n}\n#endif\n\nchar *\nlws_generate_client_ws_handshake(struct lws *wsi, char *p)\n{\n\tchar buf[128], hash[20], key_b64[40];\n\tint n;\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tconst struct lws_extension *ext;\n\tint ext_count = 0;\n#endif\n\n\t/*\n\t * create the random key\n\t */\n\tn = lws_get_random(wsi->context, hash, 16);\n\tif (n != 16) {\n\t\tlwsl_err(\"Unable to read from random dev %s\\n\",\n\t\t\t SYSTEM_RANDOM_FILEPATH);\n\t\treturn NULL;\n\t}\n\n\tlws_b64_encode_string(hash, 16, key_b64, sizeof(key_b64));\n\n\tp += sprintf(p, \"Upgrade: websocket\\x0d\\x0a\"\n\t\t\t\"Connection: Upgrade\\x0d\\x0a\"\n\t\t\t\"Sec-WebSocket-Key: \");\n\tstrcpy(p, key_b64);\n\tp += strlen(key_b64);\n\tp += sprintf(p, \"\\x0d\\x0a\");\n\tif (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS))\n\t\tp += sprintf(p, \"Sec-WebSocket-Protocol: %s\\x0d\\x0a\",\n\t\t     lws_hdr_simple_ptr(wsi,\n\t\t\t\t     _WSI_TOKEN_CLIENT_SENT_PROTOCOLS));\n\n\t/* tell the server what extensions we could support */\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\text = wsi->vhost->ws.extensions;\n\twhile (ext && ext->callback) {\n\n\t\tn = wsi->vhost->protocols[0].callback(wsi,\n\t\t\tLWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,\n\t\t\t\twsi->user_space, (char *)ext->name, 0);\n\n\t\t/*\n\t\t * zero return from callback means go ahead and allow\n\t\t * the extension, it's what we get if the callback is\n\t\t * unhandled\n\t\t */\n\n\t\tif (n) {\n\t\t\text++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* apply it */\n\n\t\tif (ext_count)\n\t\t\t*p++ = ',';\n\t\telse\n\t\t\tp += sprintf(p, \"Sec-WebSocket-Extensions: \");\n\t\tp += sprintf(p, \"%s\", ext->client_offer);\n\t\text_count++;\n\n\t\text++;\n\t}\n\tif (ext_count)\n\t\tp += sprintf(p, \"\\x0d\\x0a\");\n#endif\n\n\tif (wsi->ws->ietf_spec_revision)\n\t\tp += sprintf(p, \"Sec-WebSocket-Version: %d\\x0d\\x0a\",\n\t\t\t     wsi->ws->ietf_spec_revision);\n\n\t/* prepare the expected server accept response */\n\n\tkey_b64[39] = '\\0'; /* enforce composed length below buf sizeof */\n\tn = sprintf(buf, \"%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11\",\n\t\t\t  key_b64);\n\n\tlws_SHA1((unsigned char *)buf, n, (unsigned char *)hash);\n\n\tlws_b64_encode_string(hash, 20,\n\t\t  wsi->http.ah->initial_handshake_hash_base64,\n\t\t  sizeof(wsi->http.ah->initial_handshake_hash_base64));\n\n\treturn p;\n}\n\nint\nlws_client_ws_upgrade(struct lws *wsi, const char **cce)\n{\n\tint n, len, okay = 0;\n\tstruct lws_context *context = wsi->context;\n\tconst char *pc;\n\tchar *p;\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tchar *sb = (char *)&pt->serv_buf[0];\n\tconst struct lws_ext_options *opts;\n\tconst struct lws_extension *ext;\n\tchar ext_name[128];\n\tconst char *c, *a;\n\tchar ignore;\n\tint more = 1;\n#endif\n\n\tif (wsi->client_h2_substream) {/* !!! client ws-over-h2 not there yet */\n\t\tlwsl_warn(\"%s: client ws-over-h2 upgrade not supported yet\\n\",\n\t\t\t  __func__);\n\t\t*cce = \"HS: h2 / ws upgrade unsupported\";\n\t\tgoto bail3;\n\t}\n\n\tif (wsi->http.ah->http_response == 401) {\n\t\tlwsl_warn(\n\t\t       \"lws_client_handshake: got bad HTTP response '%d'\\n\",\n\t\t       wsi->http.ah->http_response);\n\t\t*cce = \"HS: ws upgrade unauthorized\";\n\t\tgoto bail3;\n\t}\n\n\tif (wsi->http.ah->http_response != 101) {\n\t\tlwsl_warn(\n\t\t       \"lws_client_handshake: got bad HTTP response '%d'\\n\",\n\t\t       wsi->http.ah->http_response);\n\t\t*cce = \"HS: ws upgrade response not 101\";\n\t\tgoto bail3;\n\t}\n\n\tif (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0) {\n\t\tlwsl_info(\"no ACCEPT\\n\");\n\t\t*cce = \"HS: ACCEPT missing\";\n\t\tgoto bail3;\n\t}\n\n\tp = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE);\n\tif (!p) {\n\t\tlwsl_info(\"no UPGRADE\\n\");\n\t\t*cce = \"HS: UPGRADE missing\";\n\t\tgoto bail3;\n\t}\n\tstrtolower(p);\n\tif (strcmp(p, \"websocket\")) {\n\t\tlwsl_warn(\n\t\t      \"lws_client_handshake: got bad Upgrade header '%s'\\n\", p);\n\t\t*cce = \"HS: Upgrade to something other than websocket\";\n\t\tgoto bail3;\n\t}\n\n\tp = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION);\n\tif (!p) {\n\t\tlwsl_info(\"no Connection hdr\\n\");\n\t\t*cce = \"HS: CONNECTION missing\";\n\t\tgoto bail3;\n\t}\n\tstrtolower(p);\n\tif (strcmp(p, \"upgrade\")) {\n\t\tlwsl_warn(\"lws_client_int_s_hs: bad header %s\\n\", p);\n\t\t*cce = \"HS: UPGRADE malformed\";\n\t\tgoto bail3;\n\t}\n\n\tpc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);\n\tif (!pc) {\n\t\tlwsl_parser(\"lws_client_int_s_hs: no protocol list\\n\");\n\t} else\n\t\tlwsl_parser(\"lws_client_int_s_hs: protocol list '%s'\\n\", pc);\n\n\t/*\n\t * confirm the protocol the server wants to talk was in the list\n\t * of protocols we offered\n\t */\n\n\tlen = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);\n\tif (!len) {\n\t\tlwsl_info(\"%s: WSI_TOKEN_PROTOCOL is null\\n\", __func__);\n\t\t/*\n\t\t * no protocol name to work from,\n\t\t * default to first protocol\n\t\t */\n\t\tn = 0;\n\t\twsi->protocol = &wsi->vhost->protocols[0];\n\t\tgoto check_extensions;\n\t}\n\n\tp = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL);\n\tlen = (int)strlen(p);\n\n\twhile (pc && *pc && !okay) {\n\t\tif (!strncmp(pc, p, len) &&\n\t\t    (pc[len] == ',' || pc[len] == '\\0')) {\n\t\t\tokay = 1;\n\t\t\tcontinue;\n\t\t}\n\t\twhile (*pc && *pc++ != ',')\n\t\t\t;\n\t\twhile (*pc && *pc == ' ')\n\t\t\tpc++;\n\t}\n\n\tif (!okay) {\n\t\tlwsl_info(\"%s: got bad protocol %s\\n\", __func__, p);\n\t\t*cce = \"HS: PROTOCOL malformed\";\n\t\tgoto bail2;\n\t}\n\n\t/*\n\t * identify the selected protocol struct and set it\n\t */\n\tn = 0;\n\t/* keep client connection pre-bound protocol */\n\tif (!lwsi_role_client(wsi))\n\t\twsi->protocol = NULL;\n\n\twhile (wsi->vhost->protocols[n].callback) {\n\t\tif (!wsi->protocol &&\n\t\t    strcmp(p, wsi->vhost->protocols[n].name) == 0) {\n\t\t\twsi->protocol = &wsi->vhost->protocols[n];\n\t\t\tbreak;\n\t\t}\n\t\tn++;\n\t}\n\n\tif (!wsi->vhost->protocols[n].callback) { /* no match */\n\t\t/* if server, that's already fatal */\n\t\tif (!lwsi_role_client(wsi)) {\n\t\t\tlwsl_info(\"%s: fail protocol %s\\n\", __func__, p);\n\t\t\t*cce = \"HS: Cannot match protocol\";\n\t\t\tgoto bail2;\n\t\t}\n\n\t\t/* for client, find the index of our pre-bound protocol */\n\n\t\tn = 0;\n\t\twhile (wsi->vhost->protocols[n].callback) {\n\t\t\tif (wsi->protocol && strcmp(wsi->protocol->name,\n\t\t\t\t   wsi->vhost->protocols[n].name) == 0) {\n\t\t\t\twsi->protocol = &wsi->vhost->protocols[n];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tn++;\n\t\t}\n\n\t\tif (!wsi->vhost->protocols[n].callback) {\n\t\t\tif (wsi->protocol)\n\t\t\t\tlwsl_err(\"Failed to match protocol %s\\n\",\n\t\t\t\t\t\twsi->protocol->name);\n\t\t\telse\n\t\t\t\tlwsl_err(\"No protocol on client\\n\");\n\t\t\tgoto bail2;\n\t\t}\n\t}\n\n\tlwsl_debug(\"Selected protocol %s\\n\", wsi->protocol->name);\n\ncheck_extensions:\n\t/*\n\t * stitch protocol choice into the vh protocol linked list\n\t * We always insert ourselves at the start of the list\n\t *\n\t * X <-> B\n\t * X <-> pAn <-> pB\n\t */\n\n\tlws_vhost_lock(wsi->vhost);\n\n\twsi->same_vh_protocol_prev = /* guy who points to us */\n\t\t&wsi->vhost->same_vh_protocol_list[n];\n\twsi->same_vh_protocol_next = /* old first guy is our next */\n\t\t\twsi->vhost->same_vh_protocol_list[n];\n\t/* we become the new first guy */\n\twsi->vhost->same_vh_protocol_list[n] = wsi;\n\n\tif (wsi->same_vh_protocol_next)\n\t\t/* old first guy points back to us now */\n\t\twsi->same_vh_protocol_next->same_vh_protocol_prev =\n\t\t\t\t&wsi->same_vh_protocol_next;\n\twsi->on_same_vh_list = 1;\n\n\tlws_vhost_unlock(wsi->vhost);\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t/* instantiate the accepted extensions */\n\n\tif (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) {\n\t\tlwsl_ext(\"no client extensions allowed by server\\n\");\n\t\tgoto check_accept;\n\t}\n\n\t/*\n\t * break down the list of server accepted extensions\n\t * and go through matching them or identifying bogons\n\t */\n\n\tif (lws_hdr_copy(wsi, sb, context->pt_serv_buf_size,\n\t\t\t WSI_TOKEN_EXTENSIONS) < 0) {\n\t\tlwsl_warn(\"ext list from server failed to copy\\n\");\n\t\t*cce = \"HS: EXT: list too big\";\n\t\tgoto bail2;\n\t}\n\n\tc = sb;\n\tn = 0;\n\tignore = 0;\n\ta = NULL;\n\twhile (more) {\n\n\t\tif (*c && (*c != ',' && *c != '\\t')) {\n\t\t\tif (*c == ';') {\n\t\t\t\tignore = 1;\n\t\t\t\tif (!a)\n\t\t\t\t\ta = c + 1;\n\t\t\t}\n\t\t\tif (ignore || *c == ' ') {\n\t\t\t\tc++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\text_name[n] = *c++;\n\t\t\tif (n < (int)sizeof(ext_name) - 1)\n\t\t\t\tn++;\n\t\t\tcontinue;\n\t\t}\n\t\text_name[n] = '\\0';\n\t\tignore = 0;\n\t\tif (!*c)\n\t\t\tmore = 0;\n\t\telse {\n\t\t\tc++;\n\t\t\tif (!n)\n\t\t\t\tcontinue;\n\t\t}\n\n\t\t/* check we actually support it */\n\n\t\tlwsl_notice(\"checking client ext %s\\n\", ext_name);\n\n\t\tn = 0;\n\t\text = wsi->vhost->ws.extensions;\n\t\twhile (ext && ext->callback) {\n\t\t\tif (strcmp(ext_name, ext->name)) {\n\t\t\t\text++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tn = 1;\n\t\t\tlwsl_notice(\"instantiating client ext %s\\n\", ext_name);\n\n\t\t\t/* instantiate the extension on this conn */\n\n\t\t\twsi->ws->active_extensions[wsi->ws->count_act_ext] = ext;\n\n\t\t\t/* allow him to construct his ext instance */\n\n\t\t\tif (ext->callback(lws_get_context(wsi), ext, wsi,\n\t\t\t\t   LWS_EXT_CB_CLIENT_CONSTRUCT,\n\t\t\t\t   (void *)&wsi->ws->act_ext_user[wsi->ws->count_act_ext],\n\t\t\t\t   (void *)&opts, 0)) {\n\t\t\t\tlwsl_info(\" ext %s failed construction\\n\",\n\t\t\t\t\t  ext_name);\n\t\t\t\text++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * allow the user code to override ext defaults if it\n\t\t\t * wants to\n\t\t\t */\n\t\t\text_name[0] = '\\0';\n\t\t\tif (user_callback_handle_rxflow(wsi->protocol->callback,\n\t\t\t\t\twsi, LWS_CALLBACK_WS_EXT_DEFAULTS,\n\t\t\t\t\t(char *)ext->name, ext_name,\n\t\t\t\t\tsizeof(ext_name))) {\n\t\t\t\t*cce = \"HS: EXT: failed setting defaults\";\n\t\t\t\tgoto bail2;\n\t\t\t}\n\n\t\t\tif (ext_name[0] &&\n\t\t\t    lws_ext_parse_options(ext, wsi, wsi->ws->act_ext_user[\n\t\t\t\t\t\t  wsi->ws->count_act_ext], opts, ext_name,\n\t\t\t\t\t\t  (int)strlen(ext_name))) {\n\t\t\t\tlwsl_err(\"%s: unable to parse user defaults '%s'\",\n\t\t\t\t\t __func__, ext_name);\n\t\t\t\t*cce = \"HS: EXT: failed parsing defaults\";\n\t\t\t\tgoto bail2;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * give the extension the server options\n\t\t\t */\n\t\t\tif (a && lws_ext_parse_options(ext, wsi,\n\t\t\t\t\twsi->ws->act_ext_user[wsi->ws->count_act_ext],\n\t\t\t\t\topts, a, lws_ptr_diff(c, a))) {\n\t\t\t\tlwsl_err(\"%s: unable to parse remote def '%s'\",\n\t\t\t\t\t __func__, a);\n\t\t\t\t*cce = \"HS: EXT: failed parsing options\";\n\t\t\t\tgoto bail2;\n\t\t\t}\n\n\t\t\tif (ext->callback(lws_get_context(wsi), ext, wsi,\n\t\t\t\t\tLWS_EXT_CB_OPTION_CONFIRM,\n\t\t\t\t      wsi->ws->act_ext_user[wsi->ws->count_act_ext],\n\t\t\t\t      NULL, 0)) {\n\t\t\t\tlwsl_err(\"%s: ext %s rejects server options %s\",\n\t\t\t\t\t __func__, ext->name, a);\n\t\t\t\t*cce = \"HS: EXT: Rejects server options\";\n\t\t\t\tgoto bail2;\n\t\t\t}\n\n\t\t\twsi->ws->count_act_ext++;\n\n\t\t\text++;\n\t\t}\n\n\t\tif (n == 0) {\n\t\t\tlwsl_warn(\"Unknown ext '%s'!\\n\", ext_name);\n\t\t\t*cce = \"HS: EXT: unknown ext\";\n\t\t\tgoto bail2;\n\t\t}\n\n\t\ta = NULL;\n\t\tn = 0;\n\t}\n\ncheck_accept:\n#endif\n\n\t/*\n\t * Confirm his accept token is the one we precomputed\n\t */\n\n\tp = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT);\n\tif (strcmp(p, wsi->http.ah->initial_handshake_hash_base64)) {\n\t\tlwsl_warn(\"lws_client_int_s_hs: accept '%s' wrong vs '%s'\\n\", p,\n\t\t\t\t  wsi->http.ah->initial_handshake_hash_base64);\n\t\t*cce = \"HS: Accept hash wrong\";\n\t\tgoto bail2;\n\t}\n\n\t/* allocate the per-connection user memory (if any) */\n\tif (lws_ensure_user_space(wsi)) {\n\t\tlwsl_err(\"Problem allocating wsi user mem\\n\");\n\t\t*cce = \"HS: OOM\";\n\t\tgoto bail2;\n\t}\n\n\t/*\n\t * we seem to be good to go, give client last chance to check\n\t * headers and OK it\n\t */\n\tif (wsi->protocol->callback(wsi,\n\t\t\t\t    LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,\n\t\t\t\t    wsi->user_space, NULL, 0)) {\n\t\t*cce = \"HS: Rejected by filter cb\";\n\t\tgoto bail2;\n\t}\n\n\t/* clear his proxy connection timeout */\n\tlws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);\n\n\t/* free up his parsing allocations */\n\tlws_header_table_detach(wsi, 0);\n\n\tlws_role_transition(wsi, LWSIFR_CLIENT, LRS_ESTABLISHED,\n\t\t\t    &role_ops_ws);\n\tlws_restart_ws_ping_pong_timer(wsi);\n\n\twsi->rxflow_change_to = LWS_RXFLOW_ALLOW;\n\n\t/*\n\t * create the frame buffer for this connection according to the\n\t * size mentioned in the protocol definition.  If 0 there, then\n\t * use a big default for compatibility\n\t */\n\tn = (int)wsi->protocol->rx_buffer_size;\n\tif (!n)\n\t\tn = context->pt_serv_buf_size;\n\tn += LWS_PRE;\n\twsi->ws->rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */,\n\t\t\t\t\"client frame buffer\");\n\tif (!wsi->ws->rx_ubuf) {\n\t\tlwsl_err(\"Out of Mem allocating rx buffer %d\\n\", n);\n\t\t*cce = \"HS: OOM\";\n\t\tgoto bail2;\n\t}\n\twsi->ws->rx_ubuf_alloc = n;\n\tlwsl_info(\"Allocating client RX buffer %d\\n\", n);\n\n#if !defined(LWS_WITH_ESP32)\n\tif (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF,\n\t\t       (const char *)&n, sizeof n)) {\n\t\tlwsl_warn(\"Failed to set SNDBUF to %d\", n);\n\t\t*cce = \"HS: SO_SNDBUF failed\";\n\t\tgoto bail3;\n\t}\n#endif\n\n\tlwsl_debug(\"handshake OK for protocol %s\\n\", wsi->protocol->name);\n\n\t/* call him back to inform him he is up */\n\n\tif (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_ESTABLISHED,\n\t\t\t\t    wsi->user_space, NULL, 0)) {\n\t\t*cce = \"HS: Rejected at CLIENT_ESTABLISHED\";\n\t\tgoto bail3;\n\t}\n\n\treturn 0;\n\nbail3:\n\treturn 3;\n\nbail2:\n\treturn 2;\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/ws/ops-ws.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include <core/private.h>\n\n#define LWS_CPYAPP(ptr, str) { strcpy(ptr, str); ptr += strlen(str); }\n\n/*\n * client-parser.c: lws_ws_client_rx_sm() needs to be roughly kept in\n *   sync with changes here, esp related to ext draining\n */\n\nint\nlws_ws_rx_sm(struct lws *wsi, char already_processed, unsigned char c)\n{\n\tint callback_action = LWS_CALLBACK_RECEIVE;\n\tint ret = 0;\n\tunsigned short close_code;\n\tstruct lws_tokens ebuf;\n\tunsigned char *pp;\n\tint n = 0;\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tint rx_draining_ext = 0;\n\tint lin;\n#endif\n\n\tebuf.token = NULL;\n\tebuf.len = 0;\n\tif (wsi->socket_is_permanently_unusable)\n\t\treturn -1;\n\n\tswitch (wsi->lws_rx_parse_state) {\n\tcase LWS_RXPS_NEW:\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\tif (wsi->ws->rx_draining_ext) {\n\t\t\tebuf.token = NULL;\n\t\t\tebuf.len = 0;\n\t\t\tlws_remove_wsi_from_draining_ext_list(wsi);\n\t\t\trx_draining_ext = 1;\n\t\t\tlwsl_debug(\"%s: doing draining flow\\n\", __func__);\n\n\t\t\tgoto drain_extension;\n\t\t}\n#endif\n\t\tswitch (wsi->ws->ietf_spec_revision) {\n\t\tcase 13:\n\t\t\t/*\n\t\t\t * no prepended frame key any more\n\t\t\t */\n\t\t\twsi->ws->all_zero_nonce = 1;\n\t\t\tgoto handle_first;\n\n\t\tdefault:\n\t\t\tlwsl_warn(\"lws_ws_rx_sm: unknown spec version %d\\n\",\n\t\t\t\t  wsi->ws->ietf_spec_revision);\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase LWS_RXPS_04_mask_1:\n\t\twsi->ws->mask[1] = c;\n\t\tif (c)\n\t\t\twsi->ws->all_zero_nonce = 0;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_mask_2;\n\t\tbreak;\n\tcase LWS_RXPS_04_mask_2:\n\t\twsi->ws->mask[2] = c;\n\t\tif (c)\n\t\t\twsi->ws->all_zero_nonce = 0;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_mask_3;\n\t\tbreak;\n\tcase LWS_RXPS_04_mask_3:\n\t\twsi->ws->mask[3] = c;\n\t\tif (c)\n\t\t\twsi->ws->all_zero_nonce = 0;\n\n\t\t/*\n\t\t * start from the zero'th byte in the XOR key buffer since\n\t\t * this is the start of a frame with a new key\n\t\t */\n\n\t\twsi->ws->mask_idx = 0;\n\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;\n\t\tbreak;\n\n\t/*\n\t *  04 logical framing from the spec (all this is masked when incoming\n\t *  and has to be unmasked)\n\t *\n\t * We ignore the possibility of extension data because we don't\n\t * negotiate any extensions at the moment.\n\t *\n\t *    0                   1                   2                   3\n\t *    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\t *   +-+-+-+-+-------+-+-------------+-------------------------------+\n\t *   |F|R|R|R| opcode|R| Payload len |    Extended payload length    |\n\t *   |I|S|S|S|  (4)  |S|     (7)     |             (16/63)           |\n\t *   |N|V|V|V|       |V|             |   (if payload len==126/127)   |\n\t *   | |1|2|3|       |4|             |                               |\n\t *   +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +\n\t *   |     Extended payload length continued, if payload len == 127  |\n\t *   + - - - - - - - - - - - - - - - +-------------------------------+\n\t *   |                               |         Extension data        |\n\t *   +-------------------------------+ - - - - - - - - - - - - - - - +\n\t *   :                                                               :\n\t *   +---------------------------------------------------------------+\n\t *   :                       Application data                        :\n\t *   +---------------------------------------------------------------+\n\t *\n\t *  We pass payload through to userland as soon as we get it, ignoring\n\t *  FIN.  It's up to userland to buffer it up if it wants to see a\n\t *  whole unfragmented block of the original size (which may be up to\n\t *  2^63 long!)\n\t */\n\n\tcase LWS_RXPS_04_FRAME_HDR_1:\nhandle_first:\n\n\t\twsi->ws->opcode = c & 0xf;\n\t\twsi->ws->rsv = c & 0x70;\n\t\twsi->ws->final = !!((c >> 7) & 1);\n\t\twsi->ws->defeat_check_utf8 = 0;\n\n\t\tif (((wsi->ws->opcode) & 8) && !wsi->ws->final) {\n\t\t\tlws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR,\n\t\t\t\t\t(uint8_t *)\"frag ctl\", 8);\n\t\t\treturn -1;\n\t\t}\n\n\t\tswitch (wsi->ws->opcode) {\n\t\tcase LWSWSOPC_TEXT_FRAME:\n\t\t\twsi->ws->check_utf8 = lws_check_opt(\n\t\t\t\twsi->context->options,\n\t\t\t\tLWS_SERVER_OPTION_VALIDATE_UTF8);\n\t\t\t/* fallthru */\n\t\tcase LWSWSOPC_BINARY_FRAME:\n\t\t\tif (wsi->ws->opcode == LWSWSOPC_BINARY_FRAME)\n\t\t\t\twsi->ws->check_utf8 = 0;\n\t\t\tif (wsi->ws->continuation_possible) {\n\t\t\t\tlws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR, (uint8_t *)\"bad cont\", 8);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\twsi->ws->rsv_first_msg = (c & 0x70);\n\t\t\twsi->ws->frame_is_binary =\n\t\t\t     wsi->ws->opcode == LWSWSOPC_BINARY_FRAME;\n\t\t\twsi->ws->first_fragment = 1;\n\t\t\twsi->ws->continuation_possible = !wsi->ws->final;\n\t\t\tbreak;\n\t\tcase LWSWSOPC_CONTINUATION:\n\t\t\tif (!wsi->ws->continuation_possible) {\n\t\t\t\tlws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR, (uint8_t *)\"bad cont\", 8);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase LWSWSOPC_CLOSE:\n\t\t\twsi->ws->check_utf8 = 0;\n\t\t\twsi->ws->utf8 = 0;\n\t\t\tbreak;\n\t\tcase 3:\n\t\tcase 4:\n\t\tcase 5:\n\t\tcase 6:\n\t\tcase 7:\n\t\tcase 0xb:\n\t\tcase 0xc:\n\t\tcase 0xd:\n\t\tcase 0xe:\n\t\tcase 0xf:\n\t\t\tlws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR, (uint8_t *)\"bad opc\", 7);\n\t\t\tlwsl_info(\"illegal opcode\\n\");\n\t\t\treturn -1;\n\t\t}\n\n\t\tif (wsi->ws->owed_a_fin &&\n\t\t    (wsi->ws->opcode == LWSWSOPC_TEXT_FRAME ||\n\t\t     wsi->ws->opcode == LWSWSOPC_BINARY_FRAME)) {\n\t\t\tlwsl_info(\"hey you owed us a FIN\\n\");\n\t\t\tlws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR, (uint8_t *)\"bad fin\", 7);\n\t\t\treturn -1;\n\t\t}\n\t\tif ((!(wsi->ws->opcode & 8)) && wsi->ws->final) {\n\t\t\twsi->ws->continuation_possible = 0;\n\t\t\twsi->ws->owed_a_fin = 0;\n\t\t}\n\n\t\tif (!wsi->ws->final)\n\t\t\twsi->ws->owed_a_fin = 1;\n\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;\n\t\tif (wsi->ws->rsv &&\n\t\t    (\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\t\t\t    !wsi->ws->count_act_ext ||\n#endif\n\t\t\t\t    (wsi->ws->rsv & ~0x40))) {\n\t\t\tlws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR,\n\t\t\t\t\t (uint8_t *)\"rsv bits\", 8);\n\t\t\treturn -1;\n\t\t}\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN:\n\n\t\twsi->ws->this_frame_masked = !!(c & 0x80);\n\n\t\tswitch (c & 0x7f) {\n\t\tcase 126:\n\t\t\t/* control frames are not allowed to have big lengths */\n\t\t\tif (wsi->ws->opcode & 8)\n\t\t\t\tgoto illegal_ctl_length;\n\n\t\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;\n\t\t\tbreak;\n\t\tcase 127:\n\t\t\t/* control frames are not allowed to have big lengths */\n\t\t\tif (wsi->ws->opcode & 8)\n\t\t\t\tgoto illegal_ctl_length;\n\n\t\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\twsi->ws->rx_packet_length = c & 0x7f;\n\n\n\t\t\tif (wsi->ws->this_frame_masked)\n\t\t\t\twsi->lws_rx_parse_state =\n\t\t\t\t\t\tLWS_RXPS_07_COLLECT_FRAME_KEY_1;\n\t\t\telse\n\t\t\t\tif (wsi->ws->rx_packet_length) {\n\t\t\t\t\twsi->lws_rx_parse_state =\n\t\t\t\t\tLWS_RXPS_WS_FRAME_PAYLOAD;\n\t\t\t\t} else {\n\t\t\t\t\twsi->lws_rx_parse_state = LWS_RXPS_NEW;\n\t\t\t\t\tgoto spill;\n\t\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN16_2:\n\t\twsi->ws->rx_packet_length = c << 8;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN16_1:\n\t\twsi->ws->rx_packet_length |= c;\n\t\tif (wsi->ws->this_frame_masked)\n\t\t\twsi->lws_rx_parse_state =\n\t\t\t\t\tLWS_RXPS_07_COLLECT_FRAME_KEY_1;\n\t\telse {\n\t\t\twsi->lws_rx_parse_state =\n\t\t\t\tLWS_RXPS_WS_FRAME_PAYLOAD;\n\t\t}\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN64_8:\n\t\tif (c & 0x80) {\n\t\t\tlwsl_warn(\"b63 of length must be zero\\n\");\n\t\t\t/* kill the connection */\n\t\t\treturn -1;\n\t\t}\n#if defined __LP64__\n\t\twsi->ws->rx_packet_length = ((size_t)c) << 56;\n#else\n\t\twsi->ws->rx_packet_length = 0;\n#endif\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN64_7:\n#if defined __LP64__\n\t\twsi->ws->rx_packet_length |= ((size_t)c) << 48;\n#endif\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN64_6:\n#if defined __LP64__\n\t\twsi->ws->rx_packet_length |= ((size_t)c) << 40;\n#endif\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN64_5:\n#if defined __LP64__\n\t\twsi->ws->rx_packet_length |= ((size_t)c) << 32;\n#endif\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN64_4:\n\t\twsi->ws->rx_packet_length |= ((size_t)c) << 24;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN64_3:\n\t\twsi->ws->rx_packet_length |= ((size_t)c) << 16;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN64_2:\n\t\twsi->ws->rx_packet_length |= ((size_t)c) << 8;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;\n\t\tbreak;\n\n\tcase LWS_RXPS_04_FRAME_HDR_LEN64_1:\n\t\twsi->ws->rx_packet_length |= ((size_t)c);\n\t\tif (wsi->ws->this_frame_masked)\n\t\t\twsi->lws_rx_parse_state =\n\t\t\t\t\tLWS_RXPS_07_COLLECT_FRAME_KEY_1;\n\t\telse\n\t\t\twsi->lws_rx_parse_state = LWS_RXPS_WS_FRAME_PAYLOAD;\n\t\tbreak;\n\n\tcase LWS_RXPS_07_COLLECT_FRAME_KEY_1:\n\t\twsi->ws->mask[0] = c;\n\t\tif (c)\n\t\t\twsi->ws->all_zero_nonce = 0;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2;\n\t\tbreak;\n\n\tcase LWS_RXPS_07_COLLECT_FRAME_KEY_2:\n\t\twsi->ws->mask[1] = c;\n\t\tif (c)\n\t\t\twsi->ws->all_zero_nonce = 0;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3;\n\t\tbreak;\n\n\tcase LWS_RXPS_07_COLLECT_FRAME_KEY_3:\n\t\twsi->ws->mask[2] = c;\n\t\tif (c)\n\t\t\twsi->ws->all_zero_nonce = 0;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4;\n\t\tbreak;\n\n\tcase LWS_RXPS_07_COLLECT_FRAME_KEY_4:\n\t\twsi->ws->mask[3] = c;\n\t\tif (c)\n\t\t\twsi->ws->all_zero_nonce = 0;\n\t\twsi->lws_rx_parse_state = LWS_RXPS_WS_FRAME_PAYLOAD;\n\t\twsi->ws->mask_idx = 0;\n\t\tif (wsi->ws->rx_packet_length == 0) {\n\t\t\twsi->lws_rx_parse_state = LWS_RXPS_NEW;\n\t\t\tgoto spill;\n\t\t}\n\t\tbreak;\n\n\n\tcase LWS_RXPS_WS_FRAME_PAYLOAD:\n\t\tassert(wsi->ws->rx_ubuf);\n\n\t\tif (wsi->ws->rx_ubuf_head + LWS_PRE >= wsi->ws->rx_ubuf_alloc) {\n\t\t\tlwsl_err(\"Attempted overflow \\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tif (!(already_processed & ALREADY_PROCESSED_IGNORE_CHAR)) {\n\t\t\tif (wsi->ws->all_zero_nonce)\n\t\t\t\twsi->ws->rx_ubuf[LWS_PRE + (wsi->ws->rx_ubuf_head++)] =\n\t\t\t\t   c;\n\t\t\telse\n\t\t\t\twsi->ws->rx_ubuf[LWS_PRE + (wsi->ws->rx_ubuf_head++)] =\n\t\t\t\t   c ^ wsi->ws->mask[(wsi->ws->mask_idx++) & 3];\n\n\t\t\t--wsi->ws->rx_packet_length;\n\t\t}\n\n\t\tif (!wsi->ws->rx_packet_length) {\n\t\t\tlwsl_debug(\"%s: ws fragment length exhausted\\n\", __func__);\n\t\t\t/* spill because we have the whole frame */\n\t\t\twsi->lws_rx_parse_state = LWS_RXPS_NEW;\n\t\t\tgoto spill;\n\t\t}\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\tif (wsi->ws->rx_draining_ext) {\n\t\t\tlwsl_debug(\"%s: UNTIL_EXHAUSTED draining\\n\", __func__);\n\t\t\tgoto drain_extension;\n\t\t}\n#endif\n\t\t/*\n\t\t * if there's no protocol max frame size given, we are\n\t\t * supposed to default to context->pt_serv_buf_size\n\t\t */\n\t\tif (!wsi->protocol->rx_buffer_size &&\n\t\t    wsi->ws->rx_ubuf_head != wsi->context->pt_serv_buf_size)\n\t\t\tbreak;\n\n\t\tif (wsi->protocol->rx_buffer_size &&\n\t\t    wsi->ws->rx_ubuf_head != wsi->protocol->rx_buffer_size)\n\t\t\tbreak;\n\n\t\t/* spill because we filled our rx buffer */\nspill:\n\t\t/*\n\t\t * is this frame a control packet we should take care of at this\n\t\t * layer?  If so service it and hide it from the user callback\n\t\t */\n\n\t\tlwsl_parser(\"spill on %s\\n\", wsi->protocol->name);\n\n\t\tswitch (wsi->ws->opcode) {\n\t\tcase LWSWSOPC_CLOSE:\n\n\t\t\tif (wsi->ws->peer_has_sent_close)\n\t\t\t\tbreak;\n\n\t\t\twsi->ws->peer_has_sent_close = 1;\n\n\t\t\tpp = (unsigned char *)&wsi->ws->rx_ubuf[LWS_PRE];\n\t\t\tif (lws_check_opt(wsi->context->options,\n\t\t\t\t\t  LWS_SERVER_OPTION_VALIDATE_UTF8) &&\n\t\t\t    wsi->ws->rx_ubuf_head > 2 &&\n\t\t\t    lws_check_utf8(&wsi->ws->utf8, pp + 2,\n\t\t\t\t\t   wsi->ws->rx_ubuf_head - 2))\n\t\t\t\tgoto utf8_fail;\n\n\t\t\t/* is this an acknowledgment of our close? */\n\t\t\tif (lwsi_state(wsi) == LRS_AWAITING_CLOSE_ACK) {\n\t\t\t\t/*\n\t\t\t\t * fine he has told us he is closing too, let's\n\t\t\t\t * finish our close\n\t\t\t\t */\n\t\t\t\tlwsl_parser(\"seen client close ack\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (lwsi_state(wsi) == LRS_RETURNED_CLOSE)\n\t\t\t\t/* if he sends us 2 CLOSE, kill him */\n\t\t\t\treturn -1;\n\n\t\t\tif (lws_partial_buffered(wsi)) {\n\t\t\t\t/*\n\t\t\t\t * if we're in the middle of something,\n\t\t\t\t * we can't do a normal close response and\n\t\t\t\t * have to just close our end.\n\t\t\t\t */\n\t\t\t\twsi->socket_is_permanently_unusable = 1;\n\t\t\t\tlwsl_parser(\"Closing on peer close due to Pending tx\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tif (wsi->ws->rx_ubuf_head >= 2) {\n\t\t\t\tclose_code = (pp[0] << 8) | pp[1];\n\t\t\t\tif (close_code < 1000 ||\n\t\t\t\t    close_code == 1004 ||\n\t\t\t\t    close_code == 1005 ||\n\t\t\t\t    close_code == 1006 ||\n\t\t\t\t    close_code == 1012 ||\n\t\t\t\t    close_code == 1013 ||\n\t\t\t\t    close_code == 1014 ||\n\t\t\t\t    close_code == 1015 ||\n\t\t\t\t    (close_code >= 1016 && close_code < 3000)\n\t\t\t\t) {\n\t\t\t\t\tpp[0] = (LWS_CLOSE_STATUS_PROTOCOL_ERR >> 8) & 0xff;\n\t\t\t\t\tpp[1] = LWS_CLOSE_STATUS_PROTOCOL_ERR & 0xff;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (user_callback_handle_rxflow(\n\t\t\t\t\twsi->protocol->callback, wsi,\n\t\t\t\t\tLWS_CALLBACK_WS_PEER_INITIATED_CLOSE,\n\t\t\t\t\twsi->user_space,\n\t\t\t\t\t&wsi->ws->rx_ubuf[LWS_PRE],\n\t\t\t\t\twsi->ws->rx_ubuf_head))\n\t\t\t\treturn -1;\n\n\t\t\tlwsl_parser(\"server sees client close packet\\n\");\n\t\t\tlwsi_set_state(wsi, LRS_RETURNED_CLOSE);\n\t\t\t/* deal with the close packet contents as a PONG */\n\t\t\twsi->ws->payload_is_close = 1;\n\t\t\tgoto process_as_ping;\n\n\t\tcase LWSWSOPC_PING:\n\t\t\tlwsl_info(\"received %d byte ping, sending pong\\n\",\n\t\t\t\t\t\t wsi->ws->rx_ubuf_head);\n\n\t\t\tif (wsi->ws->ping_pending_flag) {\n\t\t\t\t/*\n\t\t\t\t * there is already a pending ping payload\n\t\t\t\t * we should just log and drop\n\t\t\t\t */\n\t\t\t\tlwsl_parser(\"DROP PING since one pending\\n\");\n\t\t\t\tgoto ping_drop;\n\t\t\t}\nprocess_as_ping:\n\t\t\t/* control packets can only be < 128 bytes long */\n\t\t\tif (wsi->ws->rx_ubuf_head > 128 - 3) {\n\t\t\t\tlwsl_parser(\"DROP PING payload too large\\n\");\n\t\t\t\tgoto ping_drop;\n\t\t\t}\n\n\t\t\t/* stash the pong payload */\n\t\t\tmemcpy(wsi->ws->ping_payload_buf + LWS_PRE,\n\t\t\t       &wsi->ws->rx_ubuf[LWS_PRE],\n\t\t\t\twsi->ws->rx_ubuf_head);\n\n\t\t\twsi->ws->ping_payload_len = wsi->ws->rx_ubuf_head;\n\t\t\twsi->ws->ping_pending_flag = 1;\n\n\t\t\t/* get it sent as soon as possible */\n\t\t\tlws_callback_on_writable(wsi);\nping_drop:\n\t\t\twsi->ws->rx_ubuf_head = 0;\n\t\t\treturn 0;\n\n\t\tcase LWSWSOPC_PONG:\n\t\t\tlwsl_info(\"received pong\\n\");\n\t\t\tlwsl_hexdump(&wsi->ws->rx_ubuf[LWS_PRE],\n\t\t\t             wsi->ws->rx_ubuf_head);\n\n\t\t\tif (wsi->pending_timeout ==\n\t\t\t\t       PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG) {\n\t\t\t\tlwsl_info(\"received expected PONG on wsi %p\\n\",\n\t\t\t\t\t\twsi);\n\t\t\t\tlws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);\n\t\t\t}\n\n\t\t\t/* issue it */\n\t\t\tcallback_action = LWS_CALLBACK_RECEIVE_PONG;\n\t\t\tbreak;\n\n\t\tcase LWSWSOPC_TEXT_FRAME:\n\t\tcase LWSWSOPC_BINARY_FRAME:\n\t\tcase LWSWSOPC_CONTINUATION:\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tlwsl_parser(\"unknown opc %x\\n\", wsi->ws->opcode);\n\n\t\t\treturn -1;\n\t\t}\n\n\t\t/*\n\t\t * No it's real payload, pass it up to the user callback.\n\t\t * It's nicely buffered with the pre-padding taken care of\n\t\t * so it can be sent straight out again using lws_write\n\t\t */\n\n\t\tebuf.token = &wsi->ws->rx_ubuf[LWS_PRE];\n\t\tebuf.len = wsi->ws->rx_ubuf_head;\n\n\t\tif (wsi->ws->opcode == LWSWSOPC_PONG && !ebuf.len)\n\t\t\tgoto already_done;\n#if !defined(LWS_WITHOUT_EXTENSIONS)\ndrain_extension:\n#endif\n\t\t// lwsl_notice(\"%s: passing %d to ext\\n\", __func__, ebuf.len);\n\n\t\tif (lwsi_state(wsi) == LRS_RETURNED_CLOSE ||\n\t\t    lwsi_state(wsi) == LRS_AWAITING_CLOSE_ACK)\n\t\t\tgoto already_done;\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\tlin = ebuf.len;\n\t\t//if (lin)\n\t\t//\tlwsl_hexdump_notice(ebuf.token, ebuf.len);\n\t\tn = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &ebuf, 0);\n\t\tlwsl_debug(\"%s: ext says %d / ebuf.len %d\\n\", __func__,  n, ebuf.len);\n\t\tif (wsi->ws->rx_draining_ext)\n\t\t\talready_processed &= ~ALREADY_PROCESSED_NO_CB;\n#endif\n\t\t/*\n\t\t * ebuf may be pointing somewhere completely different now,\n\t\t * it's the output\n\t\t */\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\tif (n < 0) {\n\t\t\t/*\n\t\t\t * we may rely on this to get RX, just drop connection\n\t\t\t */\n\t\t\twsi->socket_is_permanently_unusable = 1;\n\t\t\treturn -1;\n\t\t}\n#endif\n\t\tif (\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\t    rx_draining_ext &&\n#endif\n\t\t    ebuf.len == 0)\n\t\t\tgoto already_done;\n\n\t\tif (\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\t    n &&\n#endif\n\t\t    ebuf.len)\n\t\t\t/* extension had more... main loop will come back */\n\t\t\tlws_add_wsi_to_draining_ext_list(wsi);\n\t\telse\n\t\t\tlws_remove_wsi_from_draining_ext_list(wsi);\n\n\t\tif (wsi->ws->check_utf8 && !wsi->ws->defeat_check_utf8) {\n\t\t\tif (lws_check_utf8(&wsi->ws->utf8,\n\t\t\t\t\t   (unsigned char *)ebuf.token,\n\t\t\t\t\t   ebuf.len)) {\n\t\t\t\tlws_close_reason(wsi,\n\t\t\t\t\tLWS_CLOSE_STATUS_INVALID_PAYLOAD,\n\t\t\t\t\t(uint8_t *)\"bad utf8\", 8);\n\t\t\t\tgoto utf8_fail;\n\t\t\t}\n\n\t\t\t/* we are ending partway through utf-8 character? */\n\t\t\tif (!wsi->ws->rx_packet_length && wsi->ws->final &&\n\t\t\t    wsi->ws->utf8 && !n) {\n\t\t\t\tlwsl_info(\"FINAL utf8 error\\n\");\n\t\t\t\tlws_close_reason(wsi,\n\t\t\t\t\tLWS_CLOSE_STATUS_INVALID_PAYLOAD,\n\t\t\t\t\t(uint8_t *)\"partial utf8\", 12);\nutf8_fail:\n\t\t\t\tlwsl_notice(\"utf8 error\\n\");\n\t\t\t\tlwsl_hexdump_notice(ebuf.token, ebuf.len);\n\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\tif (!wsi->wsistate_pre_close && (ebuf.len >= 0 ||\n\t\t    callback_action == LWS_CALLBACK_RECEIVE_PONG)) {\n\t\t\tif (ebuf.len)\n\t\t\t\tebuf.token[ebuf.len] = '\\0';\n\n\t\t\tif (wsi->protocol->callback &&\n\t\t\t    !(already_processed & ALREADY_PROCESSED_NO_CB)) {\n\t\t\t\tif (callback_action == LWS_CALLBACK_RECEIVE_PONG)\n\t\t\t\t\tlwsl_info(\"Doing pong callback\\n\");\n\n\t\t\t\tret = user_callback_handle_rxflow(\n\t\t\t\t\t\twsi->protocol->callback,\n\t\t\t\t\t\twsi, (enum lws_callback_reasons)\n\t\t\t\t\t\t     callback_action,\n\t\t\t\t\t\twsi->user_space,\n\t\t\t\t\t\tebuf.token,\n\t\t\t\t\t\tebuf.len);\n\t\t\t}\n\t\t\twsi->ws->first_fragment = 0;\n\t\t}\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\tif (!lin)\n\t\t\tbreak;\n#endif\n\nalready_done:\n\t\twsi->ws->rx_ubuf_head = 0;\n\t\tbreak;\n\t}\n\n\treturn ret;\n\nillegal_ctl_length:\n\n\tlwsl_warn(\"Control frame with xtended length is illegal\\n\");\n\t/* kill the connection */\n\treturn -1;\n}\n\n\nLWS_VISIBLE size_t\nlws_remaining_packet_payload(struct lws *wsi)\n{\n\treturn wsi->ws->rx_packet_length;\n}\n\nLWS_VISIBLE int lws_frame_is_binary(struct lws *wsi)\n{\n\treturn wsi->ws->frame_is_binary;\n}\n\nvoid\nlws_add_wsi_to_draining_ext_list(struct lws *wsi)\n{\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\n\tif (wsi->ws->rx_draining_ext)\n\t\treturn;\n\n\tlwsl_debug(\"%s: RX EXT DRAINING: Adding to list\\n\", __func__);\n\n\twsi->ws->rx_draining_ext = 1;\n\twsi->ws->rx_draining_ext_list = pt->ws.rx_draining_ext_list;\n\tpt->ws.rx_draining_ext_list = wsi;\n#endif\n}\n\nvoid\nlws_remove_wsi_from_draining_ext_list(struct lws *wsi)\n{\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tstruct lws **w = &pt->ws.rx_draining_ext_list;\n\n\tif (!wsi->ws->rx_draining_ext)\n\t\treturn;\n\n\tlwsl_debug(\"%s: RX EXT DRAINING: Removing from list\\n\", __func__);\n\n\twsi->ws->rx_draining_ext = 0;\n\n\t/* remove us from context draining ext list */\n\twhile (*w) {\n\t\tif (*w == wsi) {\n\t\t\t/* if us, point it instead to who we were pointing to */\n\t\t\t*w = wsi->ws->rx_draining_ext_list;\n\t\t\tbreak;\n\t\t}\n\t\tw = &((*w)->ws->rx_draining_ext_list);\n\t}\n\twsi->ws->rx_draining_ext_list = NULL;\n#endif\n}\n\nLWS_EXTERN void\nlws_restart_ws_ping_pong_timer(struct lws *wsi)\n{\n\tif (!wsi->context->ws_ping_pong_interval ||\n\t    !lwsi_role_ws(wsi))\n\t\treturn;\n\n\twsi->ws->time_next_ping_check = (time_t)lws_now_secs();\n}\n\nstatic int\nlws_0405_frame_mask_generate(struct lws *wsi)\n{\n\tint n;\n\t/* fetch the per-frame nonce */\n\n\tn = lws_get_random(lws_get_context(wsi), wsi->ws->mask, 4);\n\tif (n != 4) {\n\t\tlwsl_parser(\"Unable to read from random device %s %d\\n\",\n\t\t\t    SYSTEM_RANDOM_FILEPATH, n);\n\t\treturn 1;\n\t}\n\n\t/* start masking from first byte of masking key buffer */\n\twsi->ws->mask_idx = 0;\n\n\treturn 0;\n}\n\nint\nlws_server_init_wsi_for_ws(struct lws *wsi)\n{\n\tint n;\n\n\tlwsi_set_state(wsi, LRS_ESTABLISHED);\n\tlws_restart_ws_ping_pong_timer(wsi);\n\n\t/*\n\t * create the frame buffer for this connection according to the\n\t * size mentioned in the protocol definition.  If 0 there, use\n\t * a big default for compatibility\n\t */\n\n\tn = (int)wsi->protocol->rx_buffer_size;\n\tif (!n)\n\t\tn = wsi->context->pt_serv_buf_size;\n\tn += LWS_PRE;\n\twsi->ws->rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */, \"rx_ubuf\");\n\tif (!wsi->ws->rx_ubuf) {\n\t\tlwsl_err(\"Out of Mem allocating rx buffer %d\\n\", n);\n\t\treturn 1;\n\t}\n\twsi->ws->rx_ubuf_alloc = n;\n\tlwsl_debug(\"Allocating RX buffer %d\\n\", n);\n\n#if !defined(LWS_WITH_ESP32)\n\tif (!wsi->parent_carries_io &&\n\t    !wsi->h2_stream_carries_ws)\n\t\tif (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF,\n\t\t       (const char *)&n, sizeof n)) {\n\t\t\tlwsl_warn(\"Failed to set SNDBUF to %d\", n);\n\t\t\treturn 1;\n\t\t}\n#endif\n\n\t/* notify user code that we're ready to roll */\n\n\tif (wsi->protocol->callback)\n\t\tif (wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,\n\t\t\t\t\t    wsi->user_space,\n#ifdef LWS_WITH_TLS\n\t\t\t\t\t    wsi->tls.ssl,\n#else\n\t\t\t\t\t    NULL,\n#endif\n\t\t\t\t\t    wsi->h2_stream_carries_ws))\n\t\t\treturn 1;\n\n\tlwsl_debug(\"ws established\\n\");\n\n\treturn 0;\n}\n\n\n\nLWS_VISIBLE int\nlws_is_final_fragment(struct lws *wsi)\n{\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n       lwsl_debug(\"%s: final %d, rx pk length %ld, draining %ld\\n\", __func__,\n\t\t\twsi->ws->final, (long)wsi->ws->rx_packet_length,\n\t\t\t(long)wsi->ws->rx_draining_ext);\n\treturn wsi->ws->final && !wsi->ws->rx_packet_length &&\n\t       !wsi->ws->rx_draining_ext;\n#else\n\treturn wsi->ws->final && !wsi->ws->rx_packet_length;\n#endif\n}\n\nLWS_VISIBLE int\nlws_is_first_fragment(struct lws *wsi)\n{\n\treturn wsi->ws->first_fragment;\n}\n\nLWS_VISIBLE unsigned char\nlws_get_reserved_bits(struct lws *wsi)\n{\n\treturn wsi->ws->rsv;\n}\n\nLWS_VISIBLE LWS_EXTERN int\nlws_get_close_length(struct lws *wsi)\n{\n\treturn wsi->ws->close_in_ping_buffer_len;\n}\n\nLWS_VISIBLE LWS_EXTERN unsigned char *\nlws_get_close_payload(struct lws *wsi)\n{\n\treturn &wsi->ws->ping_payload_buf[LWS_PRE];\n}\n\nLWS_VISIBLE LWS_EXTERN void\nlws_close_reason(struct lws *wsi, enum lws_close_status status,\n\t\t unsigned char *buf, size_t len)\n{\n\tunsigned char *p, *start;\n\tint budget = sizeof(wsi->ws->ping_payload_buf) - LWS_PRE;\n\n\tassert(lwsi_role_ws(wsi));\n\n\tstart = p = &wsi->ws->ping_payload_buf[LWS_PRE];\n\n\t*p++ = (((int)status) >> 8) & 0xff;\n\t*p++ = ((int)status) & 0xff;\n\n\tif (buf)\n\t\twhile (len-- && p < start + budget)\n\t\t\t*p++ = *buf++;\n\n\twsi->ws->close_in_ping_buffer_len = lws_ptr_diff(p, start);\n}\n\nstatic int\nlws_is_ws_with_ext(struct lws *wsi)\n{\n#if defined(LWS_WITHOUT_EXTENSIONS)\n\treturn 0;\n#else\n\treturn lwsi_role_ws(wsi) && !!wsi->ws->count_act_ext;\n#endif\n}\n\nstatic int\nrops_handle_POLLIN_ws(struct lws_context_per_thread *pt, struct lws *wsi,\n\t\t       struct lws_pollfd *pollfd)\n{\n\tstruct lws_tokens ebuf;\n\tunsigned int pending = 0;\n\tchar buffered = 0;\n\tint n = 0, m;\n#if defined(LWS_WITH_HTTP2)\n\tstruct lws *wsi1;\n#endif\n\n\tif (!wsi->ws) {\n\t\tlwsl_err(\"ws role wsi with no ws\\n\");\n\t\treturn 1;\n\t}\n\n\t// lwsl_notice(\"%s: %s\\n\", __func__, wsi->protocol->name);\n\n\t//lwsl_info(\"%s: wsistate 0x%x, pollout %d\\n\", __func__,\n\t//\t   wsi->wsistate, pollfd->revents & LWS_POLLOUT);\n\n\t/*\n\t * something went wrong with parsing the handshake, and\n\t * we ended up back in the event loop without completing it\n\t */\n\tif (lwsi_state(wsi) == LRS_PRE_WS_SERVING_ACCEPT) {\n\t\twsi->socket_is_permanently_unusable = 1;\n\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\t}\n\n\tebuf.token = NULL;\n\tebuf.len = 0;\n\n\tif (lwsi_state(wsi) == LRS_WAITING_CONNECT) {\n#if !defined(LWS_NO_CLIENT)\n\t\tif ((pollfd->revents & LWS_POLLOUT) &&\n\t\t    lws_handle_POLLOUT_event(wsi, pollfd)) {\n\t\t\tlwsl_debug(\"POLLOUT event closed it\\n\");\n\t\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\t\t}\n\n\t\tn = lws_client_socket_service(wsi, pollfd, NULL);\n\t\tif (n)\n\t\t\treturn LWS_HPI_RET_WSI_ALREADY_DIED;\n#endif\n\t\treturn LWS_HPI_RET_HANDLED;\n\t}\n\n\t//lwsl_notice(\"%s:  wsi->ws->tx_draining_ext %d revents 0x%x 0x%x %d\\n\", __func__,  wsi->ws->tx_draining_ext, pollfd->revents, wsi->wsistate, lwsi_state_can_handle_POLLOUT(wsi));\n\n\t/* 1: something requested a callback when it was OK to write */\n\n\tif ((pollfd->revents & LWS_POLLOUT) &&\n\t    lwsi_state_can_handle_POLLOUT(wsi) &&\n\t    lws_handle_POLLOUT_event(wsi, pollfd)) {\n\t\tif (lwsi_state(wsi) == LRS_RETURNED_CLOSE)\n\t\t\tlwsi_set_state(wsi, LRS_FLUSHING_BEFORE_CLOSE);\n\n\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\t}\n\n\tif (lwsi_state(wsi) == LRS_RETURNED_CLOSE ||\n\t    lwsi_state(wsi) == LRS_WAITING_TO_SEND_CLOSE) {\n\t\t/*\n\t\t * we stopped caring about anything except control\n\t\t * packets.  Force flow control off, defeat tx\n\t\t * draining.\n\t\t */\n\t\tlws_rx_flow_control(wsi, 1);\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\tif (wsi->ws)\n\t\t\twsi->ws->tx_draining_ext = 0;\n#endif\n\t}\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tif (wsi->ws->tx_draining_ext)\n\t\t/*\n\t\t * We cannot deal with new RX until the TX ext path has\n\t\t * been drained.  It's because new rx will, eg, crap on\n\t\t * the wsi rx buf that may be needed to retain state.\n\t\t *\n\t\t * TX ext drain path MUST go through event loop to avoid\n\t\t * blocking.\n\t\t */\n\t\treturn LWS_HPI_RET_HANDLED;\n#endif\n\tif (lws_is_flowcontrolled(wsi)) {\n\t\t/* We cannot deal with any kind of new RX because we are\n\t\t * RX-flowcontrolled.\n\t\t */\n\t\tlwsl_info(\"flowcontrolled\\n\");\n\t\treturn LWS_HPI_RET_HANDLED;\n\t}\n\n#if defined(LWS_WITH_HTTP2)\n\tif (wsi->http2_substream || wsi->upgraded_to_http2) {\n\t\twsi1 = lws_get_network_wsi(wsi);\n\t\tif (wsi1 && wsi1->trunc_len)\n\t\t\t/* We cannot deal with any kind of new RX\n\t\t\t * because we are dealing with a partial send\n\t\t\t * (new RX may trigger new http_action() that\n\t\t\t * expect to be able to send)\n\t\t\t */\n\t\t\treturn LWS_HPI_RET_HANDLED;\n\t}\n#endif\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t/* 2: RX Extension needs to be drained\n\t */\n\n\tif (wsi->ws->rx_draining_ext) {\n\n\t\tlwsl_debug(\"%s: RX EXT DRAINING: Service\\n\", __func__);\n#ifndef LWS_NO_CLIENT\n\t\tif (lwsi_role_client(wsi)) {\n\t\t\tn = lws_ws_client_rx_sm(wsi, 0);\n\t\t\tif (n < 0)\n\t\t\t\t/* we closed wsi */\n\t\t\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\t\t} else\n#endif\n\t\t\tn = lws_ws_rx_sm(wsi, ALREADY_PROCESSED_IGNORE_CHAR, 0);\n\n\t\treturn LWS_HPI_RET_HANDLED;\n\t}\n\n\tif (wsi->ws->rx_draining_ext)\n\t\t/*\n\t\t * We have RX EXT content to drain, but can't do it\n\t\t * right now.  That means we cannot do anything lower\n\t\t * priority either.\n\t\t */\n\t\treturn LWS_HPI_RET_HANDLED;\n#endif\n\n\t/* 3: buflist needs to be drained\n\t */\nread:\n\t//lws_buflist_describe(&wsi->buflist, wsi);\n\tebuf.len = (int)lws_buflist_next_segment_len(&wsi->buflist,\n\t\t\t\t\t\t     (uint8_t **)&ebuf.token);\n\tif (ebuf.len) {\n\t\tlwsl_info(\"draining buflist (len %d)\\n\", ebuf.len);\n\t\tbuffered = 1;\n\t\tgoto drain;\n\t}\n\n\tif (!(pollfd->revents & pollfd->events & LWS_POLLIN) && !wsi->http.ah)\n\t\treturn LWS_HPI_RET_HANDLED;\n\n\tif (lws_is_flowcontrolled(wsi)) {\n\t\tlwsl_info(\"%s: %p should be rxflow (bm 0x%x)..\\n\",\n\t\t\t    __func__, wsi, wsi->rxflow_bitmap);\n\t\treturn LWS_HPI_RET_HANDLED;\n\t}\n\n\tif (!(lwsi_role_client(wsi) &&\n\t      (lwsi_state(wsi) != LRS_ESTABLISHED &&\n\t       lwsi_state(wsi) != LRS_AWAITING_CLOSE_ACK &&\n\t       lwsi_state(wsi) != LRS_H2_WAITING_TO_SEND_HEADERS))) {\n\t\t/*\n\t\t * In case we are going to react to this rx by scheduling\n\t\t * writes, we need to restrict the amount of rx to the size\n\t\t * the protocol reported for rx buffer.\n\t\t *\n\t\t * Otherwise we get a situation we have to absorb possibly a\n\t\t * lot of reads before we get a chance to drain them by writing\n\t\t * them, eg, with echo type tests in autobahn.\n\t\t */\n\n\t\tbuffered = 0;\n\t\tebuf.token = (char *)pt->serv_buf;\n\t\tif (lwsi_role_ws(wsi))\n\t\t\tebuf.len = wsi->ws->rx_ubuf_alloc;\n\t\telse\n\t\t\tebuf.len = wsi->context->pt_serv_buf_size;\n\n\t\tif ((unsigned int)ebuf.len > wsi->context->pt_serv_buf_size)\n\t\t\tebuf.len = wsi->context->pt_serv_buf_size;\n\n\t\tif ((int)pending > ebuf.len)\n\t\t\tpending = ebuf.len;\n\n\t\tebuf.len = lws_ssl_capable_read(wsi, (uint8_t *)ebuf.token,\n\t\t\t\t\t\tpending ? (int)pending :\n\t\t\t\t\t\tebuf.len);\n\t\tswitch (ebuf.len) {\n\t\tcase 0:\n\t\t\tlwsl_info(\"%s: zero length read\\n\",\n\t\t\t\t  __func__);\n\t\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\t\tcase LWS_SSL_CAPABLE_MORE_SERVICE:\n\t\t\tlwsl_info(\"SSL Capable more service\\n\");\n\t\t\treturn LWS_HPI_RET_HANDLED;\n\t\tcase LWS_SSL_CAPABLE_ERROR:\n\t\t\tlwsl_info(\"%s: LWS_SSL_CAPABLE_ERROR\\n\",\n\t\t\t\t\t__func__);\n\t\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\t\t}\n\t\t// lwsl_notice(\"Actual RX %d\\n\", ebuf.len);\n\n\t\tlws_restart_ws_ping_pong_timer(wsi);\n\n\t\t/*\n\t\t * coverity thinks ssl_capable_read() may read over\n\t\t * 2GB.  Dissuade it...\n\t\t */\n\t\tebuf.len &= 0x7fffffff;\n\t}\n\ndrain:\n\n\t/*\n\t * give any active extensions a chance to munge the buffer\n\t * before parse.  We pass in a pointer to an lws_tokens struct\n\t * prepared with the default buffer and content length that's in\n\t * there.  Rather than rewrite the default buffer, extensions\n\t * that expect to grow the buffer can adapt .token to\n\t * point to their own per-connection buffer in the extension\n\t * user allocation.  By default with no extensions or no\n\t * extension callback handling, just the normal input buffer is\n\t * used then so it is efficient.\n\t */\n\tm = 0;\n\tdo {\n\n\t\t/* service incoming data */\n\t\t//lws_buflist_describe(&wsi->buflist, wsi);\n\t\tif (ebuf.len) {\n#if defined(LWS_ROLE_H2)\n\t\t\tif (lwsi_role_h2(wsi) && lwsi_state(wsi) != LRS_BODY)\n\t\t\t\tn = lws_read_h2(wsi, (unsigned char *)ebuf.token,\n\t\t\t\t\t     ebuf.len);\n\t\t\telse\n#endif\n\t\t\t\tn = lws_read_h1(wsi, (unsigned char *)ebuf.token,\n\t\t\t\t\t     ebuf.len);\n\n\t\t\tif (n < 0) {\n\t\t\t\t/* we closed wsi */\n\t\t\t\tn = 0;\n\t\t\t\treturn LWS_HPI_RET_WSI_ALREADY_DIED;\n\t\t\t}\n\t\t\t//lws_buflist_describe(&wsi->buflist, wsi);\n\t\t\t//lwsl_notice(\"%s: consuming %d / %d\\n\", __func__, n, ebuf.len);\n\t\t\tif (lws_buflist_aware_consume(wsi, &ebuf, n, buffered))\n\t\t\t\treturn LWS_HPI_RET_PLEASE_CLOSE_ME;\n\t\t}\n\n\t\tebuf.token = NULL;\n\t\tebuf.len = 0;\n\t} while (m);\n\n\tif (wsi->http.ah\n#if !defined(LWS_NO_CLIENT)\n\t\t\t&& !wsi->client_h2_alpn\n#endif\n\t\t\t) {\n\t\tlwsl_info(\"%s: %p: detaching ah\\n\", __func__, wsi);\n\t\tlws_header_table_detach(wsi, 0);\n\t}\n\n\tpending = lws_ssl_pending(wsi);\n\tif (pending) {\n\t\tif (lws_is_ws_with_ext(wsi))\n\t\t\tpending = pending > wsi->ws->rx_ubuf_alloc ?\n\t\t\t\twsi->ws->rx_ubuf_alloc : pending;\n\t\telse\n\t\t\tpending = pending > wsi->context->pt_serv_buf_size ?\n\t\t\t\twsi->context->pt_serv_buf_size : pending;\n\t\tgoto read;\n\t}\n\n\tif (buffered && /* were draining, now nothing left */\n\t    !lws_buflist_next_segment_len(&wsi->buflist, NULL)) {\n\t\tlwsl_info(\"%s: %p flow buf: drained\\n\", __func__, wsi);\n\t\t/* having drained the rxflow buffer, can rearm POLLIN */\n#ifdef LWS_NO_SERVER\n\t\tn =\n#endif\n\t\t__lws_rx_flow_control(wsi);\n\t\t/* n ignored, needed for NO_SERVER case */\n\t}\n\n\t/* n = 0 */\n\treturn LWS_HPI_RET_HANDLED;\n}\n\n\nint rops_handle_POLLOUT_ws(struct lws *wsi)\n{\n\tint write_type = LWS_WRITE_PONG;\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tstruct lws_tokens ebuf;\n\tint ret, m;\n#endif\n\tint n;\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tlwsl_debug(\"%s: %s: wsi->ws->tx_draining_ext %d\\n\", __func__,\n\t\t\twsi->protocol->name, wsi->ws->tx_draining_ext);\n#endif\n\n\t/* Priority 3: pending control packets (pong or close)\n\t *\n\t * 3a: close notification packet requested from close api\n\t */\n\n\tif (lwsi_state(wsi) == LRS_WAITING_TO_SEND_CLOSE) {\n\t\tlwsl_debug(\"sending close packet\\n\");\n\t\tlwsl_hexdump_debug(&wsi->ws->ping_payload_buf[LWS_PRE],\n\t\t\t\t   wsi->ws->close_in_ping_buffer_len);\n\t\twsi->waiting_to_send_close_frame = 0;\n\t\tn = lws_write(wsi, &wsi->ws->ping_payload_buf[LWS_PRE],\n\t\t\t      wsi->ws->close_in_ping_buffer_len,\n\t\t\t      LWS_WRITE_CLOSE);\n\t\tif (n >= 0) {\n\t\t\tif (wsi->close_needs_ack) {\n\t\t\t\tlwsi_set_state(wsi, LRS_AWAITING_CLOSE_ACK);\n\t\t\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 5);\n\t\t\t\tlwsl_debug(\"sent close indication, awaiting ack\\n\");\n\n\t\t\t\treturn LWS_HP_RET_BAIL_OK;\n\t\t\t}\n\t\t\twsi->close_needs_ack = 0;\n\t\t\tlwsi_set_state(wsi, LRS_RETURNED_CLOSE);\n\t\t}\n\n\t\treturn LWS_HP_RET_BAIL_DIE;\n\t}\n\n\t/* else, the send failed and we should just hang up */\n\n\tif ((lwsi_role_ws(wsi) && wsi->ws->ping_pending_flag) ||\n\t    (lwsi_state(wsi) == LRS_RETURNED_CLOSE &&\n\t     wsi->ws->payload_is_close)) {\n\n\t\tif (wsi->ws->payload_is_close)\n\t\t\twrite_type = LWS_WRITE_CLOSE;\n\t\telse {\n\t\t\tif (wsi->wsistate_pre_close) {\n\t\t\t\t/* we started close flow, forget pong */\n\t\t\t\twsi->ws->ping_pending_flag = 0;\n\t\t\t\treturn LWS_HP_RET_BAIL_OK;\n\t\t\t}\n\t\t\tlwsl_info(\"issuing pong %d on wsi %p\\n\", wsi->ws->ping_payload_len, wsi);\n\t\t}\n\n\t\tn = lws_write(wsi, &wsi->ws->ping_payload_buf[LWS_PRE],\n\t\t\t      wsi->ws->ping_payload_len, write_type);\n\t\tif (n < 0)\n\t\t\treturn LWS_HP_RET_BAIL_DIE;\n\n\t\t/* well he is sent, mark him done */\n\t\twsi->ws->ping_pending_flag = 0;\n\t\tif (wsi->ws->payload_is_close) {\n\t\t\t// assert(0);\n\t\t\t/* oh... a close frame was it... then we are done */\n\t\t\treturn LWS_HP_RET_BAIL_DIE;\n\t\t}\n\n\t\t/* otherwise for PING, leave POLLOUT active either way */\n\t\treturn LWS_HP_RET_BAIL_OK;\n\t}\n\n\tif (!wsi->socket_is_permanently_unusable && wsi->ws->send_check_ping) {\n\n\t\tlwsl_info(\"issuing ping on wsi %p\\n\", wsi);\n\t\twsi->ws->send_check_ping = 0;\n\t\tn = lws_write(wsi, &wsi->ws->ping_payload_buf[LWS_PRE],\n\t\t\t      0, LWS_WRITE_PING);\n\t\tif (n < 0)\n\t\t\treturn LWS_HP_RET_BAIL_DIE;\n\n\t\t/*\n\t\t * we apparently were able to send the PING in a reasonable time\n\t\t * now reset the clock on our peer to be able to send the\n\t\t * PONG in a reasonable time.\n\t\t */\n\n\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG,\n\t\t\t\twsi->context->timeout_secs);\n\n\t\treturn LWS_HP_RET_BAIL_OK;\n\t}\n\n\t/* Priority 4: if we are closing, not allowed to send more data frags\n\t *\t       which means user callback or tx ext flush banned now\n\t */\n\tif (lwsi_state(wsi) == LRS_RETURNED_CLOSE)\n\t\treturn LWS_HP_RET_USER_SERVICE;\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t/* Priority 5: Tx path extension with more to send\n\t *\n\t *\t       These are handled as new fragments each time around\n\t *\t       So while we must block new writeable callback to enforce\n\t *\t       payload ordering, but since they are always complete\n\t *\t       fragments control packets can interleave OK.\n\t */\n\tif (wsi->ws->tx_draining_ext) {\n\t\tlwsl_ext(\"SERVICING TX EXT DRAINING\\n\");\n\t\tif (lws_write(wsi, NULL, 0, LWS_WRITE_CONTINUATION) < 0)\n\t\t\treturn LWS_HP_RET_BAIL_DIE;\n\t\t/* leave POLLOUT active */\n\t\treturn LWS_HP_RET_BAIL_OK;\n\t}\n\n\t/* Priority 6: extensions\n\t */\n\tif (!wsi->ws->extension_data_pending && !wsi->ws->tx_draining_ext) {\n\t\tlwsl_ext(\"%s: !wsi->ws->extension_data_pending\\n\", __func__);\n\t\treturn LWS_HP_RET_USER_SERVICE;\n\t}\n\n\t/*\n\t * check in on the active extensions, see if they\n\t * had pending stuff to spill... they need to get the\n\t * first look-in otherwise sequence will be disordered\n\t *\n\t * NULL, zero-length ebuf means just spill pending\n\t */\n\n\tret = 1;\n\tif (wsi->role_ops == &role_ops_raw_skt ||\n\t    wsi->role_ops == &role_ops_raw_file)\n\t\tret = 0;\n\n\twhile (ret == 1) {\n\n\t\t/* default to nobody has more to spill */\n\n\t\tret = 0;\n\t\tebuf.token = NULL;\n\t\tebuf.len = 0;\n\n\t\t/* give every extension a chance to spill */\n\n\t\tm = lws_ext_cb_active(wsi, LWS_EXT_CB_PACKET_TX_PRESEND,\n\t\t\t\t      &ebuf, 0);\n\t\tif (m < 0) {\n\t\t\tlwsl_err(\"ext reports fatal error\\n\");\n\t\t\treturn LWS_HP_RET_BAIL_DIE;\n\t\t}\n\t\tif (m)\n\t\t\t/*\n\t\t\t * at least one extension told us he has more\n\t\t\t * to spill, so we will go around again after\n\t\t\t */\n\t\t\tret = 1;\n\n\t\t/* assuming they gave us something to send, send it */\n\n\t\tif (ebuf.len) {\n\t\t\tn = lws_issue_raw(wsi, (unsigned char *)ebuf.token,\n\t\t\t\t\t  ebuf.len);\n\t\t\tif (n < 0) {\n\t\t\t\tlwsl_info(\"closing from POLLOUT spill\\n\");\n\t\t\t\treturn LWS_HP_RET_BAIL_DIE;\n\t\t\t}\n\t\t\t/*\n\t\t\t * Keep amount spilled small to minimize chance of this\n\t\t\t */\n\t\t\tif (n != ebuf.len) {\n\t\t\t\tlwsl_err(\"Unable to spill ext %d vs %d\\n\",\n\t\t\t\t\t\t\t  ebuf.len, n);\n\t\t\t\treturn LWS_HP_RET_BAIL_DIE;\n\t\t\t}\n\t\t} else\n\t\t\tcontinue;\n\n\t\t/* no extension has more to spill */\n\n\t\tif (!ret)\n\t\t\tcontinue;\n\n\t\t/*\n\t\t * There's more to spill from an extension, but we just sent\n\t\t * something... did that leave the pipe choked?\n\t\t */\n\n\t\tif (!lws_send_pipe_choked(wsi))\n\t\t\t/* no we could add more */\n\t\t\tcontinue;\n\n\t\tlwsl_info(\"choked in POLLOUT service\\n\");\n\n\t\t/*\n\t\t * Yes, he's choked.  Leave the POLLOUT masked on so we will\n\t\t * come back here when he is unchoked.  Don't call the user\n\t\t * callback to enforce ordering of spilling, he'll get called\n\t\t * when we come back here and there's nothing more to spill.\n\t\t */\n\n\t\treturn LWS_HP_RET_BAIL_OK;\n\t}\n\n\twsi->ws->extension_data_pending = 0;\n#endif\n\n\treturn LWS_HP_RET_USER_SERVICE;\n}\n\nstatic int\nrops_periodic_checks_ws(struct lws_context *context, int tsi, time_t now)\n{\n\tstruct lws_vhost *vh;\n\n\tif (!context->ws_ping_pong_interval ||\n\t    context->last_ws_ping_pong_check_s >= now + 10)\n\t\treturn 0;\n\n\tvh = context->vhost_list;\n\tcontext->last_ws_ping_pong_check_s = now;\n\n\twhile (vh) {\n\t\tint n;\n\n\t\tlws_vhost_lock(vh);\n\n\t\tfor (n = 0; n < vh->count_protocols; n++) {\n\t\t\tstruct lws *wsi = vh->same_vh_protocol_list[n];\n\n\t\t\twhile (wsi) {\n\t\t\t\tif (lwsi_role_ws(wsi) &&\n\t\t\t\t    !wsi->socket_is_permanently_unusable &&\n\t\t\t\t    !wsi->ws->send_check_ping &&\n\t\t\t\t    wsi->ws->time_next_ping_check &&\n\t\t\t\t    lws_compare_time_t(context, now,\n\t\t\t\t\twsi->ws->time_next_ping_check) >\n\t\t\t\t       context->ws_ping_pong_interval) {\n\n\t\t\t\t\tlwsl_info(\"req pp on wsi %p\\n\", wsi);\n\t\t\t\t\twsi->ws->send_check_ping = 1;\n\t\t\t\t\tlws_set_timeout(wsi,\n\t\t\t\t\tPENDING_TIMEOUT_WS_PONG_CHECK_SEND_PING,\n\t\t\t\t\t\tcontext->timeout_secs);\n\t\t\t\t\tlws_callback_on_writable(wsi);\n\t\t\t\t\twsi->ws->time_next_ping_check = now;\n\t\t\t\t}\n\t\t\t\twsi = wsi->same_vh_protocol_next;\n\t\t\t}\n\t\t}\n\n\t\tlws_vhost_unlock(vh);\n\t\tvh = vh->vhost_next;\n\t}\n\n\treturn 0;\n}\n\nstatic int\nrops_service_flag_pending_ws(struct lws_context *context, int tsi)\n{\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tstruct lws_context_per_thread *pt = &context->pt[tsi];\n\tstruct lws *wsi;\n\tint forced = 0;\n\n\t/* POLLIN faking (the pt lock is taken by the parent) */\n\n\t/*\n\t * 1) For all guys with already-available ext data to drain, if they are\n\t * not flowcontrolled, fake their POLLIN status\n\t */\n\twsi = pt->ws.rx_draining_ext_list;\n\twhile (wsi && wsi->position_in_fds_table != LWS_NO_FDS_POS) {\n\t\tpt->fds[wsi->position_in_fds_table].revents |=\n\t\t\tpt->fds[wsi->position_in_fds_table].events & LWS_POLLIN;\n\t\tif (pt->fds[wsi->position_in_fds_table].revents & LWS_POLLIN)\n\t\t\tforced = 1;\n\n\t\twsi = wsi->ws->rx_draining_ext_list;\n\t}\n\n\treturn forced;\n#else\n\treturn 0;\n#endif\n}\n\nstatic int\nrops_close_via_role_protocol_ws(struct lws *wsi, enum lws_close_status reason)\n{\n\tif (!wsi->ws)\n\t\treturn 0;\n\n\tif (!wsi->ws->close_in_ping_buffer_len && /* already a reason */\n\t     (reason == LWS_CLOSE_STATUS_NOSTATUS ||\n\t      reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY))\n\t\treturn 0;\n\n\tlwsl_debug(\"%s: sending close indication...\\n\", __func__);\n\n\t/* if no prepared close reason, use 1000 and no aux data */\n\n\tif (!wsi->ws->close_in_ping_buffer_len) {\n\t\twsi->ws->close_in_ping_buffer_len = 2;\n\t\twsi->ws->ping_payload_buf[LWS_PRE] = (reason >> 8) & 0xff;\n\t\twsi->ws->ping_payload_buf[LWS_PRE + 1] = reason & 0xff;\n\t}\n\n\twsi->waiting_to_send_close_frame = 1;\n\twsi->close_needs_ack = 1;\n\tlwsi_set_state(wsi, LRS_WAITING_TO_SEND_CLOSE);\n\t__lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_SEND, 5);\n\n\tlws_callback_on_writable(wsi);\n\n\treturn 1;\n}\n\nstatic int\nrops_close_role_ws(struct lws_context_per_thread *pt, struct lws *wsi)\n{\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tif (wsi->ws->rx_draining_ext) {\n\t\tstruct lws **w = &pt->ws.rx_draining_ext_list;\n\n\t\twsi->ws->rx_draining_ext = 0;\n\t\t/* remove us from context draining ext list */\n\t\twhile (*w) {\n\t\t\tif (*w == wsi) {\n\t\t\t\t*w = wsi->ws->rx_draining_ext_list;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tw = &((*w)->ws->rx_draining_ext_list);\n\t\t}\n\t\twsi->ws->rx_draining_ext_list = NULL;\n\t}\n\n\tif (wsi->ws->tx_draining_ext) {\n\t\tstruct lws **w = &pt->ws.tx_draining_ext_list;\n\t\tlwsl_ext(\"%s: CLEARING tx_draining_ext\\n\", __func__);\n\t\twsi->ws->tx_draining_ext = 0;\n\t\t/* remove us from context draining ext list */\n\t\twhile (*w) {\n\t\t\tif (*w == wsi) {\n\t\t\t\t*w = wsi->ws->tx_draining_ext_list;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tw = &((*w)->ws->tx_draining_ext_list);\n\t\t}\n\t\twsi->ws->tx_draining_ext_list = NULL;\n\t}\n#endif\n\tlws_free_set_NULL(wsi->ws->rx_ubuf);\n\n\tif (wsi->trunc_alloc)\n\t\t/* not going to be completed... nuke it */\n\t\tlws_free_set_NULL(wsi->trunc_alloc);\n\n\twsi->ws->ping_payload_len = 0;\n\twsi->ws->ping_pending_flag = 0;\n\n\t/* deallocate any active extension contexts */\n\n\tif (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)\n\t\tlwsl_warn(\"extension destruction failed\\n\");\n\n\treturn 0;\n}\n\nstatic int\nrops_write_role_protocol_ws(struct lws *wsi, unsigned char *buf, size_t len,\n\t\t\t    enum lws_write_protocol *wp)\n{\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tenum lws_write_protocol wpt;\n#endif\n\tint masked7 = lwsi_role_client(wsi);\n\tunsigned char is_masked_bit = 0;\n\tunsigned char *dropmask = NULL;\n\tstruct lws_tokens ebuf;\n\tsize_t orig_len = len;\n\tint pre = 0, n = 0;\n\n\t// lwsl_err(\"%s: wp 0x%x len %d\\n\", __func__, *wp, (int)len);\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tif (wsi->ws->tx_draining_ext) {\n\t\t/* remove us from the list */\n\t\tstruct lws **w = &pt->ws.tx_draining_ext_list;\n\n\t\tlwsl_ext(\"%s: CLEARING tx_draining_ext\\n\", __func__);\n\t\twsi->ws->tx_draining_ext = 0;\n\t\t/* remove us from context draining ext list */\n\t\twhile (*w) {\n\t\t\tif (*w == wsi) {\n\t\t\t\t*w = wsi->ws->tx_draining_ext_list;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tw = &((*w)->ws->tx_draining_ext_list);\n\t\t}\n\t\twsi->ws->tx_draining_ext_list = NULL;\n\n\t\twpt = *wp;\n\t\t*wp = (wsi->ws->tx_draining_stashed_wp & 0xc0)|\n\t\t\t\tLWS_WRITE_CONTINUATION;\n\n\t\t/*\n\t\t * When we are just flushing (len == 0), we can trust the\n\t\t * stashed wp info completely.  Otherwise adjust it to the\n\t\t * FIN status of the incoming packet.\n\t\t */\n\n\t\tif (!(wpt & LWS_WRITE_NO_FIN) && len)\n\t\t\t*wp &= ~LWS_WRITE_NO_FIN;\n\n\t\tlwsl_ext(\"FORCED draining wp to 0x%02X (stashed 0x%02X, incoming 0x%02X)\\n\", *wp,\n\t\t\t\twsi->ws->tx_draining_stashed_wp, wpt);\n\t\t// assert(0);\n\t}\n#endif\n\tlws_restart_ws_ping_pong_timer(wsi);\n\n\tif (((*wp) & 0x1f) == LWS_WRITE_HTTP ||\n\t    ((*wp) & 0x1f) == LWS_WRITE_HTTP_FINAL ||\n\t    ((*wp) & 0x1f) == LWS_WRITE_HTTP_HEADERS_CONTINUATION ||\n\t    ((*wp) & 0x1f) == LWS_WRITE_HTTP_HEADERS)\n\t\tgoto send_raw;\n\n\n\n\t/* if we are continuing a frame that already had its header done */\n\n\tif (wsi->ws->inside_frame) {\n\t\tlwsl_debug(\"INSIDE FRAME\\n\");\n\t\tgoto do_more_inside_frame;\n\t}\n\n\twsi->ws->clean_buffer = 1;\n\n\t/*\n\t * give a chance to the extensions to modify payload\n\t * the extension may decide to produce unlimited payload erratically\n\t * (eg, compression extension), so we require only that if he produces\n\t * something, it will be a complete fragment of the length known at\n\t * the time (just the fragment length known), and if he has\n\t * more we will come back next time he is writeable and allow him to\n\t * produce more fragments until he's drained.\n\t *\n\t * This allows what is sent each time it is writeable to be limited to\n\t * a size that can be sent without partial sends or blocking, allows\n\t * interleaving of control frames and other connection service.\n\t */\n\tebuf.token = (char *)buf;\n\tebuf.len = (int)len;\n\n\tswitch ((int)*wp) {\n\tcase LWS_WRITE_PING:\n\tcase LWS_WRITE_PONG:\n\tcase LWS_WRITE_CLOSE:\n\t\tbreak;\n\tdefault:\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\t// lwsl_notice(\"LWS_EXT_CB_PAYLOAD_TX\\n\");\n\t\t// m = (int)ebuf.len;\n\t\t/* returns 0 if no more tx pending, 1 if more pending */\n\t\tn = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_TX, &ebuf, *wp);\n\t\tif (n < 0)\n\t\t\treturn -1;\n\t\t// lwsl_notice(\"ext processed %d plaintext into %d compressed (wp 0x%x)\\n\", m, (int)ebuf.len, *wp);\n\n\t\tif (n && ebuf.len) {\n\t\t\tlwsl_ext(\"write drain len %d (wp 0x%x) SETTING tx_draining_ext\\n\", (int)ebuf.len, *wp);\n\t\t\t/* extension requires further draining */\n\t\t\twsi->ws->tx_draining_ext = 1;\n\t\t\twsi->ws->tx_draining_ext_list = pt->ws.tx_draining_ext_list;\n\t\t\tpt->ws.tx_draining_ext_list = wsi;\n\t\t\t/* we must come back to do more */\n\t\t\tlws_callback_on_writable(wsi);\n\t\t\t/*\n\t\t\t * keep a copy of the write type for the overall\n\t\t\t * action that has provoked generation of these\n\t\t\t * fragments, so the last guy can use its FIN state.\n\t\t\t */\n\t\t\twsi->ws->tx_draining_stashed_wp = *wp;\n\t\t\t/* this is definitely not actually the last fragment\n\t\t\t * because the extension asserted he has more coming\n\t\t\t * So make sure this intermediate one doesn't go out\n\t\t\t * with a FIN.\n\t\t\t */\n\t\t\t*wp |= LWS_WRITE_NO_FIN;\n\t\t}\n#endif\n\t\tif (ebuf.len && wsi->ws->stashed_write_pending) {\n\t\t\twsi->ws->stashed_write_pending = 0;\n\t\t\t*wp = ((*wp) & 0xc0) | (int)wsi->ws->stashed_write_type;\n\t\t}\n\t}\n\n\t/*\n\t * an extension did something we need to keep... for example, if\n\t * compression extension, it has already updated its state according\n\t * to this being issued\n\t */\n\tif ((char *)buf != ebuf.token) {\n\t\t/*\n\t\t * ext might eat it, but not have anything to issue yet.\n\t\t * In that case we have to follow his lead, but stash and\n\t\t * replace the write type that was lost here the first time.\n\t\t */\n\t\tif (len && !ebuf.len) {\n\t\t\tif (!wsi->ws->stashed_write_pending)\n\t\t\t\twsi->ws->stashed_write_type = (char)(*wp) & 0x3f;\n\t\t\twsi->ws->stashed_write_pending = 1;\n\t\t\treturn (int)len;\n\t\t}\n\t\t/*\n\t\t * extension recreated it:\n\t\t * need to buffer this if not all sent\n\t\t */\n\t\twsi->ws->clean_buffer = 0;\n\t}\n\n\tbuf = (unsigned char *)ebuf.token;\n\tlen = ebuf.len;\n\n\tif (!buf) {\n\t\tlwsl_err(\"null buf (%d)\\n\", (int)len);\n\t\treturn -1;\n\t}\n\n\tswitch (wsi->ws->ietf_spec_revision) {\n\tcase 13:\n\t\tif (masked7) {\n\t\t\tpre += 4;\n\t\t\tdropmask = &buf[0 - pre];\n\t\t\tis_masked_bit = 0x80;\n\t\t}\n\n\t\tswitch ((*wp) & 0xf) {\n\t\tcase LWS_WRITE_TEXT:\n\t\t\tn = LWSWSOPC_TEXT_FRAME;\n\t\t\tbreak;\n\t\tcase LWS_WRITE_BINARY:\n\t\t\tn = LWSWSOPC_BINARY_FRAME;\n\t\t\tbreak;\n\t\tcase LWS_WRITE_CONTINUATION:\n\t\t\tn = LWSWSOPC_CONTINUATION;\n\t\t\tbreak;\n\n\t\tcase LWS_WRITE_CLOSE:\n\t\t\tn = LWSWSOPC_CLOSE;\n\t\t\tbreak;\n\t\tcase LWS_WRITE_PING:\n\t\t\tn = LWSWSOPC_PING;\n\t\t\tbreak;\n\t\tcase LWS_WRITE_PONG:\n\t\t\tn = LWSWSOPC_PONG;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tlwsl_warn(\"lws_write: unknown write opc / wp\\n\");\n\t\t\treturn -1;\n\t\t}\n\n\t\tif (!((*wp) & LWS_WRITE_NO_FIN))\n\t\t\tn |= 1 << 7;\n\n\t\tif (len < 126) {\n\t\t\tpre += 2;\n\t\t\tbuf[-pre] = n;\n\t\t\tbuf[-pre + 1] = (unsigned char)(len | is_masked_bit);\n\t\t} else {\n\t\t\tif (len < 65536) {\n\t\t\t\tpre += 4;\n\t\t\t\tbuf[-pre] = n;\n\t\t\t\tbuf[-pre + 1] = 126 | is_masked_bit;\n\t\t\t\tbuf[-pre + 2] = (unsigned char)(len >> 8);\n\t\t\t\tbuf[-pre + 3] = (unsigned char)len;\n\t\t\t} else {\n\t\t\t\tpre += 10;\n\t\t\t\tbuf[-pre] = n;\n\t\t\t\tbuf[-pre + 1] = 127 | is_masked_bit;\n#if defined __LP64__\n\t\t\t\t\tbuf[-pre + 2] = (len >> 56) & 0x7f;\n\t\t\t\t\tbuf[-pre + 3] = len >> 48;\n\t\t\t\t\tbuf[-pre + 4] = len >> 40;\n\t\t\t\t\tbuf[-pre + 5] = len >> 32;\n#else\n\t\t\t\t\tbuf[-pre + 2] = 0;\n\t\t\t\t\tbuf[-pre + 3] = 0;\n\t\t\t\t\tbuf[-pre + 4] = 0;\n\t\t\t\t\tbuf[-pre + 5] = 0;\n#endif\n\t\t\t\tbuf[-pre + 6] = (unsigned char)(len >> 24);\n\t\t\t\tbuf[-pre + 7] = (unsigned char)(len >> 16);\n\t\t\t\tbuf[-pre + 8] = (unsigned char)(len >> 8);\n\t\t\t\tbuf[-pre + 9] = (unsigned char)len;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\ndo_more_inside_frame:\n\n\t/*\n\t * Deal with masking if we are in client -> server direction and\n\t * the wp demands it\n\t */\n\n\tif (masked7) {\n\t\tif (!wsi->ws->inside_frame)\n\t\t\tif (lws_0405_frame_mask_generate(wsi)) {\n\t\t\t\tlwsl_err(\"frame mask generation failed\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t/*\n\t\t * in v7, just mask the payload\n\t\t */\n\t\tif (dropmask) { /* never set if already inside frame */\n\t\t\tfor (n = 4; n < (int)len + 4; n++)\n\t\t\t\tdropmask[n] = dropmask[n] ^ wsi->ws->mask[\n\t\t\t\t\t(wsi->ws->mask_idx++) & 3];\n\n\t\t\t/* copy the frame nonce into place */\n\t\t\tmemcpy(dropmask, wsi->ws->mask, 4);\n\t\t}\n\t}\n\n\tif (lwsi_role_h2_ENCAPSULATION(wsi)) {\n\t\tstruct lws *encap = lws_get_network_wsi(wsi);\n\n\t\tassert(encap != wsi);\n\t\treturn encap->role_ops->write_role_protocol(wsi, buf - pre,\n\t\t\t\t\t\t\tlen + pre, wp);\n\t}\n\n\tswitch ((*wp) & 0x1f) {\n\tcase LWS_WRITE_TEXT:\n\tcase LWS_WRITE_BINARY:\n\tcase LWS_WRITE_CONTINUATION:\n\t\tif (!wsi->h2_stream_carries_ws) {\n\n\t\t\t/*\n\t\t\t * give any active extensions a chance to munge the\n\t\t\t * buffer before send.  We pass in a pointer to an\n\t\t\t * lws_tokens struct prepared with the default buffer\n\t\t\t * and content length that's in there.  Rather than\n\t\t\t * rewrite the default buffer, extensions that expect\n\t\t\t * to grow the buffer can adapt .token to point to their\n\t\t\t * own per-connection buffer in the extension user\n\t\t\t * allocation.  By default with no extensions or no\n\t\t\t * extension callback handling, just the normal input\n\t\t\t * buffer is used then so it is efficient.\n\t\t\t *\n\t\t\t * callback returns 1 in case it wants to spill more\n\t\t\t * buffers\n\t\t\t *\n\t\t\t * This takes care of holding the buffer if send is\n\t\t\t * incomplete, ie, if wsi->ws->clean_buffer is 0\n\t\t\t * (meaning an extension meddled with the buffer).  If\n\t\t\t * wsi->ws->clean_buffer is 1, it will instead return\n\t\t\t * to the user code how much OF THE USER BUFFER was\n\t\t\t * consumed.\n\t\t\t */\n\n\t\t\tn = lws_issue_raw_ext_access(wsi, buf - pre, len + pre);\n\t\t\twsi->ws->inside_frame = 1;\n\t\t\tif (n <= 0)\n\t\t\t\treturn n;\n\n\t\t\tif (n == (int)len + pre) {\n\t\t\t\t/* everything in the buffer was handled\n\t\t\t\t * (or rebuffered...) */\n\t\t\t\twsi->ws->inside_frame = 0;\n\t\t\t\treturn (int)orig_len;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * it is how many bytes of user buffer got sent... may\n\t\t\t * be < orig_len in which case callback when writable\n\t\t\t * has already been arranged and user code can call\n\t\t\t * lws_write() again with the rest later.\n\t\t\t */\n\n\t\t\treturn n - pre;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\nsend_raw:\n\treturn lws_issue_raw(wsi, (unsigned char *)buf - pre, len + pre);\n}\n\nstatic int\nrops_close_kill_connection_ws(struct lws *wsi, enum lws_close_status reason)\n{\n\t/* deal with ws encapsulation in h2 */\n#if defined(LWS_WITH_HTTP2)\n\tif (wsi->http2_substream && wsi->h2_stream_carries_ws)\n\t\treturn role_ops_h2.close_kill_connection(wsi, reason);\n\n\treturn 0;\n#else\n\treturn 0;\n#endif\n}\n\nstatic int\nrops_callback_on_writable_ws(struct lws *wsi)\n{\n#if defined(LWS_WITH_HTTP2)\n\tif (lwsi_role_h2_ENCAPSULATION(wsi)) {\n\t\t/* we know then that it has an h2 parent */\n\t\tstruct lws *enc = role_ops_h2.encapsulation_parent(wsi);\n\n\t\tassert(enc);\n\t\tif (enc->role_ops->callback_on_writable(wsi))\n\t\t\treturn 1;\n\t}\n#endif\n\treturn 0;\n}\n\nstatic int\nrops_init_vhost_ws(struct lws_vhost *vh,\n\t\t   const struct lws_context_creation_info *info)\n{\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n#ifdef LWS_WITH_PLUGINS\n\tstruct lws_plugin *plugin = vh->context->plugin_list;\n\tint m;\n\n\tif (vh->context->plugin_extension_count) {\n\n\t\tm = 0;\n\t\twhile (info->extensions && info->extensions[m].callback)\n\t\t\tm++;\n\n\t\t/*\n\t\t * give the vhost a unified list of extensions including the\n\t\t * ones that came from plugins\n\t\t */\n\t\tvh->ws.extensions = lws_zalloc(sizeof(struct lws_extension) *\n\t\t\t\t     (m + vh->context->plugin_extension_count + 1),\n\t\t\t\t     \"extensions\");\n\t\tif (!vh->ws.extensions)\n\t\t\treturn 1;\n\n\t\tmemcpy((struct lws_extension *)vh->ws.extensions, info->extensions,\n\t\t       sizeof(struct lws_extension) * m);\n\t\tplugin = vh->context->plugin_list;\n\t\twhile (plugin) {\n\t\t\tmemcpy((struct lws_extension *)&vh->ws.extensions[m],\n\t\t\t\tplugin->caps.extensions,\n\t\t\t       sizeof(struct lws_extension) *\n\t\t\t       plugin->caps.count_extensions);\n\t\t\tm += plugin->caps.count_extensions;\n\t\t\tplugin = plugin->list;\n\t\t}\n\t} else\n#endif\n\t\tvh->ws.extensions = info->extensions;\n#endif\n\n\treturn 0;\n}\n\nstatic int\nrops_destroy_vhost_ws(struct lws_vhost *vh)\n{\n#ifdef LWS_WITH_PLUGINS\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tif (vh->context->plugin_extension_count)\n\t\tlws_free((void *)vh->ws.extensions);\n#endif\n#endif\n\n\treturn 0;\n}\n\nstatic int\nrops_destroy_role_ws(struct lws *wsi)\n{\n\tlws_free_set_NULL(wsi->ws);\n\n\treturn 0;\n}\n\nstruct lws_role_ops role_ops_ws = {\n\t/* role name */\t\t\t\"ws\",\n\t/* alpn id */\t\t\tNULL,\n\t/* check_upgrades */\t\tNULL,\n\t/* init_context */\t\tNULL,\n\t/* init_vhost */\t\trops_init_vhost_ws,\n\t/* destroy_vhost */\t\trops_destroy_vhost_ws,\n\t/* periodic_checks */\t\trops_periodic_checks_ws,\n\t/* service_flag_pending */\trops_service_flag_pending_ws,\n\t/* handle_POLLIN */\t\trops_handle_POLLIN_ws,\n\t/* handle_POLLOUT */\t\trops_handle_POLLOUT_ws,\n\t/* perform_user_POLLOUT */\tNULL,\n\t/* callback_on_writable */\trops_callback_on_writable_ws,\n\t/* tx_credit */\t\t\tNULL,\n\t/* write_role_protocol */\trops_write_role_protocol_ws,\n\t/* encapsulation_parent */\tNULL,\n\t/* alpn_negotiated */\t\tNULL,\n\t/* close_via_role_protocol */\trops_close_via_role_protocol_ws,\n\t/* close_role */\t\trops_close_role_ws,\n\t/* close_kill_connection */\trops_close_kill_connection_ws,\n\t/* destroy_role */\t\trops_destroy_role_ws,\n\t/* writeable cb clnt, srv */\t{ LWS_CALLBACK_CLIENT_WRITEABLE,\n\t\t\t\t\t  LWS_CALLBACK_SERVER_WRITEABLE },\n\t/* close cb clnt, srv */\t{ LWS_CALLBACK_CLIENT_CLOSED,\n\t\t\t\t\t  LWS_CALLBACK_CLOSED },\n\t/* file handles */\t\t0\n};\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/ws/private.h",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n *\n *  This is included from core/private.h if LWS_ROLE_WS\n */\n\nextern struct lws_role_ops role_ops_ws;\n\n#define lwsi_role_ws(wsi) (wsi->role_ops == &role_ops_ws)\n\nenum lws_rx_parse_state {\n\tLWS_RXPS_NEW,\n\n\tLWS_RXPS_04_mask_1,\n\tLWS_RXPS_04_mask_2,\n\tLWS_RXPS_04_mask_3,\n\n\tLWS_RXPS_04_FRAME_HDR_1,\n\tLWS_RXPS_04_FRAME_HDR_LEN,\n\tLWS_RXPS_04_FRAME_HDR_LEN16_2,\n\tLWS_RXPS_04_FRAME_HDR_LEN16_1,\n\tLWS_RXPS_04_FRAME_HDR_LEN64_8,\n\tLWS_RXPS_04_FRAME_HDR_LEN64_7,\n\tLWS_RXPS_04_FRAME_HDR_LEN64_6,\n\tLWS_RXPS_04_FRAME_HDR_LEN64_5,\n\tLWS_RXPS_04_FRAME_HDR_LEN64_4,\n\tLWS_RXPS_04_FRAME_HDR_LEN64_3,\n\tLWS_RXPS_04_FRAME_HDR_LEN64_2,\n\tLWS_RXPS_04_FRAME_HDR_LEN64_1,\n\n\tLWS_RXPS_07_COLLECT_FRAME_KEY_1,\n\tLWS_RXPS_07_COLLECT_FRAME_KEY_2,\n\tLWS_RXPS_07_COLLECT_FRAME_KEY_3,\n\tLWS_RXPS_07_COLLECT_FRAME_KEY_4,\n\n\tLWS_RXPS_WS_FRAME_PAYLOAD\n};\n\nenum lws_websocket_opcodes_07 {\n\tLWSWSOPC_CONTINUATION = 0,\n\tLWSWSOPC_TEXT_FRAME = 1,\n\tLWSWSOPC_BINARY_FRAME = 2,\n\n\tLWSWSOPC_NOSPEC__MUX = 7,\n\n\t/* control extensions 8+ */\n\n\tLWSWSOPC_CLOSE = 8,\n\tLWSWSOPC_PING = 9,\n\tLWSWSOPC_PONG = 0xa,\n};\n\n/* this is not usable directly by user code any more, lws_close_reason() */\n#define LWS_WRITE_CLOSE 4\n\n#define ALREADY_PROCESSED_IGNORE_CHAR 1\n#define ALREADY_PROCESSED_NO_CB 2\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\nstruct lws_vhost_role_ws {\n\tconst struct lws_extension *extensions;\n};\n\nstruct lws_pt_role_ws {\n\tstruct lws *rx_draining_ext_list;\n\tstruct lws *tx_draining_ext_list;\n};\n#endif\n\nstruct _lws_websocket_related {\n\tchar *rx_ubuf;\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tconst struct lws_extension *active_extensions[LWS_MAX_EXTENSIONS_ACTIVE];\n\tvoid *act_ext_user[LWS_MAX_EXTENSIONS_ACTIVE];\n\tstruct lws *rx_draining_ext_list;\n\tstruct lws *tx_draining_ext_list;\n#endif\n\t/* Also used for close content... control opcode == < 128 */\n\tuint8_t ping_payload_buf[128 - 3 + LWS_PRE];\n\tuint8_t mask[4];\n\n\ttime_t time_next_ping_check;\n\tsize_t rx_packet_length;\n\tuint32_t rx_ubuf_head;\n\tuint32_t rx_ubuf_alloc;\n\n\tuint8_t ping_payload_len;\n\tuint8_t mask_idx;\n\tuint8_t opcode;\n\tuint8_t rsv;\n\tuint8_t rsv_first_msg;\n\t/* zero if no info, or length including 2-byte close code */\n\tuint8_t close_in_ping_buffer_len;\n\tuint8_t utf8;\n\tuint8_t stashed_write_type;\n\tuint8_t tx_draining_stashed_wp;\n\tuint8_t ietf_spec_revision;\n\n\tunsigned int final:1;\n\tunsigned int frame_is_binary:1;\n\tunsigned int all_zero_nonce:1;\n\tunsigned int this_frame_masked:1;\n\tunsigned int inside_frame:1; /* next write will be more of frame */\n\tunsigned int clean_buffer:1; /* buffer not rewritten by extension */\n\tunsigned int payload_is_close:1; /* process as PONG, but it is close */\n\tunsigned int ping_pending_flag:1;\n\tunsigned int continuation_possible:1;\n\tunsigned int owed_a_fin:1;\n\tunsigned int check_utf8:1;\n\tunsigned int defeat_check_utf8:1;\n\tunsigned int stashed_write_pending:1;\n\tunsigned int send_check_ping:1;\n\tunsigned int first_fragment:1;\n\tunsigned int peer_has_sent_close:1;\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tunsigned int extension_data_pending:1;\n\tunsigned int rx_draining_ext:1;\n\tunsigned int tx_draining_ext:1;\n\n\tuint8_t count_act_ext;\n#endif\n};\n\nint\nlws_ws_handshake_client(struct lws *wsi, unsigned char **buf, size_t len);\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\nLWS_VISIBLE void\nlws_context_init_extensions(const struct lws_context_creation_info *info,\n\t\t\t    struct lws_context *context);\nLWS_EXTERN int\nlws_any_extension_handled(struct lws *wsi, enum lws_extension_callback_reasons r,\n\t\t\t  void *v, size_t len);\n\nLWS_EXTERN int\nlws_ext_cb_active(struct lws *wsi, int reason, void *buf, int len);\nLWS_EXTERN int\nlws_ext_cb_all_exts(struct lws_context *context, struct lws *wsi, int reason,\n\t\t    void *arg, int len);\n#endif\n\nint\nhandshake_0405(struct lws_context *context, struct lws *wsi);\nint\nlws_process_ws_upgrade(struct lws *wsi);\nint\nlws_server_init_wsi_for_ws(struct lws *wsi);\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/roles/ws/server-ws.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include <core/private.h>\n\n#define LWS_CPYAPP(ptr, str) { strcpy(ptr, str); ptr += strlen(str); }\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\nstatic int\nlws_extension_server_handshake(struct lws *wsi, char **p, int budget)\n{\n\tstruct lws_context *context = wsi->context;\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tchar ext_name[64], *args, *end = (*p) + budget - 1;\n\tconst struct lws_ext_options *opts, *po;\n\tconst struct lws_extension *ext;\n\tstruct lws_ext_option_arg oa;\n\tint n, m, more = 1;\n\tint ext_count = 0;\n\tchar ignore;\n\tchar *c;\n\n\t/*\n\t * Figure out which extensions the client has that we want to\n\t * enable on this connection, and give him back the list\n\t */\n\tif (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS))\n\t\treturn 0;\n\n\t/*\n\t * break down the list of client extensions\n\t * and go through them\n\t */\n\n\tif (lws_hdr_copy(wsi, (char *)pt->serv_buf, context->pt_serv_buf_size,\n\t\t\t WSI_TOKEN_EXTENSIONS) < 0)\n\t\treturn 1;\n\n\tc = (char *)pt->serv_buf;\n\tlwsl_parser(\"WSI_TOKEN_EXTENSIONS = '%s'\\n\", c);\n\twsi->ws->count_act_ext = 0;\n\tignore = 0;\n\tn = 0;\n\targs = NULL;\n\n\t/*\n\t * We may get a simple request\n\t *\n\t * Sec-WebSocket-Extensions: permessage-deflate\n\t *\n\t * or an elaborated one with requested options\n\t *\n\t * Sec-WebSocket-Extensions: permessage-deflate; \\\n\t *\t\t\t     server_no_context_takeover; \\\n\t *\t\t\t     client_no_context_takeover\n\t */\n\n\twhile (more) {\n\n\t\tif (c >= (char *)pt->serv_buf + 255)\n\t\t\treturn -1;\n\n\t\tif (*c && (*c != ',' && *c != '\\t')) {\n\t\t\tif (*c == ';') {\n\t\t\t\tignore = 1;\n\t\t\t\tif (!args)\n\t\t\t\t\targs = c + 1;\n\t\t\t}\n\t\t\tif (ignore || *c == ' ') {\n\t\t\t\tc++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\text_name[n] = *c++;\n\t\t\tif (n < (int)sizeof(ext_name) - 1)\n\t\t\t\tn++;\n\t\t\tcontinue;\n\t\t}\n\t\text_name[n] = '\\0';\n\n\t\tignore = 0;\n\t\tif (!*c)\n\t\t\tmore = 0;\n\t\telse {\n\t\t\tc++;\n\t\t\tif (!n)\n\t\t\t\tcontinue;\n\t\t}\n\n\t\twhile (args && *args && *args == ' ')\n\t\t\targs++;\n\n\t\t/* check a client's extension against our support */\n\n\t\text = wsi->vhost->ws.extensions;\n\n\t\twhile (ext && ext->callback) {\n\n\t\t\tif (strcmp(ext_name, ext->name)) {\n\t\t\t\text++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * oh, we do support this one he asked for... but let's\n\t\t\t * confirm he only gave it once\n\t\t\t */\n\t\t\tfor (m = 0; m < wsi->ws->count_act_ext; m++)\n\t\t\t\tif (wsi->ws->active_extensions[m] == ext) {\n\t\t\t\t\tlwsl_info(\"extension mentioned twice\\n\");\n\t\t\t\t\treturn 1; /* shenanigans */\n\t\t\t\t}\n\n\t\t\t/*\n\t\t\t * ask user code if it's OK to apply it on this\n\t\t\t * particular connection + protocol\n\t\t\t */\n\t\t\tm = (wsi->protocol->callback)(wsi,\n\t\t\t\tLWS_CALLBACK_CONFIRM_EXTENSION_OKAY,\n\t\t\t\twsi->user_space, ext_name, 0);\n\n\t\t\t/*\n\t\t\t * zero return from callback means go ahead and allow\n\t\t\t * the extension, it's what we get if the callback is\n\t\t\t * unhandled\n\t\t\t */\n\t\t\tif (m) {\n\t\t\t\text++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/* apply it */\n\n\t\t\text_count++;\n\n\t\t\t/* instantiate the extension on this conn */\n\n\t\t\twsi->ws->active_extensions[wsi->ws->count_act_ext] = ext;\n\n\t\t\t/* allow him to construct his context */\n\n\t\t\tif (ext->callback(lws_get_context(wsi), ext, wsi,\n\t\t\t\t\t  LWS_EXT_CB_CONSTRUCT,\n\t\t\t\t\t  (void *)&wsi->ws->act_ext_user[\n\t\t\t\t\t                wsi->ws->count_act_ext],\n\t\t\t\t\t  (void *)&opts, 0)) {\n\t\t\t\tlwsl_info(\"ext %s failed construction\\n\",\n\t\t\t\t\t    ext_name);\n\t\t\t\text_count--;\n\t\t\t\text++;\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (ext_count > 1)\n\t\t\t\t*(*p)++ = ',';\n\t\t\telse\n\t\t\t\tLWS_CPYAPP(*p,\n\t\t\t\t\t  \"\\x0d\\x0aSec-WebSocket-Extensions: \");\n\t\t\t*p += lws_snprintf(*p, (end - *p), \"%s\", ext_name);\n\n\t\t\t/*\n\t\t\t * The client may send a bunch of different option\n\t\t\t * sets for the same extension, we are supposed to\n\t\t\t * pick one we like the look of.  The option sets are\n\t\t\t * separated by comma.\n\t\t\t *\n\t\t\t * Actually we just either accept the first one or\n\t\t\t * nothing.\n\t\t\t *\n\t\t\t * Go through the options trying to apply the\n\t\t\t * recognized ones\n\t\t\t */\n\n\t\t\tlwsl_info(\"ext args %s\\n\", args);\n\n\t\t\twhile (args && *args && *args != ',') {\n\t\t\t\twhile (*args == ' ')\n\t\t\t\t\targs++;\n\t\t\t\tpo = opts;\n\t\t\t\twhile (po->name) {\n\t\t\t\t\t/* only support arg-less options... */\n\t\t\t\t\tif (po->type != EXTARG_NONE ||\n\t\t\t\t\t    strncmp(args, po->name,\n\t\t\t\t\t\t    strlen(po->name))) {\n\t\t\t\t\t\tpo++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\toa.option_name = NULL;\n\t\t\t\t\toa.option_index = (int)(po - opts);\n\t\t\t\t\toa.start = NULL;\n\t\t\t\t\toa.len = 0;\n\t\t\t\t\tlwsl_info(\"setting '%s'\\n\", po->name);\n\t\t\t\t\tif (!ext->callback(lws_get_context(wsi),\n\t\t\t\t\t\t\t  ext, wsi,\n\t\t\t\t\t\t\t  LWS_EXT_CB_OPTION_SET,\n\t\t\t\t\t\t\t  wsi->ws->act_ext_user[\n\t\t\t\t\t\t\t\t wsi->ws->count_act_ext],\n\t\t\t\t\t\t\t  &oa, (end - *p))) {\n\n\t\t\t\t\t\t*p += lws_snprintf(*p, (end - *p),\n\t\t\t\t\t\t\t\"; %s\", po->name);\n\t\t\t\t\t\tlwsl_debug(\"adding option %s\\n\",\n\t\t\t\t\t\t\t\tpo->name);\n\t\t\t\t\t}\n\t\t\t\t\tpo++;\n\t\t\t\t}\n\t\t\t\twhile (*args && *args != ',' && *args != ';')\n\t\t\t\t\targs++;\n\n\t\t\t\tif (*args == ';')\n\t\t\t\t\targs++;\n\t\t\t}\n\n\t\t\twsi->ws->count_act_ext++;\n\t\t\tlwsl_parser(\"cnt_act_ext <- %d\\n\", wsi->ws->count_act_ext);\n\n\t\t\tif (args && *args == ',')\n\t\t\t\tmore = 0;\n\n\t\t\text++;\n\t\t}\n\n\t\tn = 0;\n\t\targs = NULL;\n\t}\n\n\treturn 0;\n}\n#endif\n\n\n\nint\nlws_process_ws_upgrade(struct lws *wsi)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tchar protocol_list[128], protocol_name[64], *p;\n\tint protocol_len, hit, n = 0, non_space_char_found = 0;\n\n\tif (!wsi->protocol)\n\t\tlwsl_err(\"NULL protocol at lws_read\\n\");\n\n\t/*\n\t * It's either websocket or h2->websocket\n\t *\n\t * Select the first protocol we support from the list\n\t * the client sent us.\n\t *\n\t * Copy it to remove header fragmentation\n\t */\n\n\tif (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,\n\t\t\t WSI_TOKEN_PROTOCOL) < 0) {\n\t\tlwsl_err(\"protocol list too long\");\n\t\treturn 1;\n\t}\n\n\tprotocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);\n\tprotocol_list[protocol_len] = '\\0';\n\tp = protocol_list;\n\thit = 0;\n\n\twhile (*p && !hit) {\n\t\tn = 0;\n\t\tnon_space_char_found = 0;\n\t\twhile (n < (int)sizeof(protocol_name) - 1 &&\n\t\t       *p && *p != ',') {\n\t\t\t/* ignore leading spaces */\n\t\t\tif (!non_space_char_found && *p == ' ') {\n\t\t\t\tn++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tnon_space_char_found = 1;\n\t\t\tprotocol_name[n++] = *p++;\n\t\t}\n\t\tprotocol_name[n] = '\\0';\n\t\tif (*p)\n\t\t\tp++;\n\n\t\tlwsl_debug(\"checking %s\\n\", protocol_name);\n\n\t\tn = 0;\n\t\twhile (wsi->vhost->protocols[n].callback) {\n\t\t\tlwsl_debug(\"try %s\\n\",\n\t\t\t\t  wsi->vhost->protocols[n].name);\n\n\t\t\tif (wsi->vhost->protocols[n].name &&\n\t\t\t    !strcmp(wsi->vhost->protocols[n].name,\n\t\t\t\t    protocol_name)) {\n\t\t\t\twsi->protocol = &wsi->vhost->protocols[n];\n\t\t\t\thit = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tn++;\n\t\t}\n\t}\n\n\t/* we didn't find a protocol he wanted? */\n\n\tif (!hit) {\n\t\tif (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {\n\t\t\tlwsl_notice(\"No protocol from \\\"%s\\\" supported\\n\",\n\t\t\t\t protocol_list);\n\t\t\treturn 1;\n\t\t}\n\t\t/*\n\t\t * some clients only have one protocol and\n\t\t * do not send the protocol list header...\n\t\t * allow it and match to the vhost's default\n\t\t * protocol (which itself defaults to zero)\n\t\t */\n\t\tlwsl_info(\"defaulting to prot handler %d\\n\",\n\t\t\twsi->vhost->default_protocol_index);\n\t\tn = wsi->vhost->default_protocol_index;\n\t\twsi->protocol = &wsi->vhost->protocols[\n\t\t\t      (int)wsi->vhost->default_protocol_index];\n\t}\n\n\t/* allocate the ws struct for the wsi */\n\twsi->ws = lws_zalloc(sizeof(*wsi->ws), \"ws struct\");\n\tif (!wsi->ws) {\n\t\tlwsl_notice(\"OOM\\n\");\n\t\treturn 1;\n\t}\n\n\tif (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION))\n\t\twsi->ws->ietf_spec_revision =\n\t\t\t       atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION));\n\n\t/* allocate wsi->user storage */\n\tif (lws_ensure_user_space(wsi)) {\n\t\tlwsl_notice(\"problem with user space\\n\");\n\t\treturn 1;\n\t}\n\n\t/*\n\t * Give the user code a chance to study the request and\n\t * have the opportunity to deny it\n\t */\n\tif ((wsi->protocol->callback)(wsi,\n\t\t\tLWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,\n\t\t\twsi->user_space,\n\t\t      lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {\n\t\tlwsl_warn(\"User code denied connection\\n\");\n\t\treturn 1;\n\t}\n\n\t/*\n\t * Perform the handshake according to the protocol version the\n\t * client announced\n\t */\n\n\tswitch (wsi->ws->ietf_spec_revision) {\n\tdefault:\n\t\tlwsl_notice(\"Unknown client spec version %d\\n\",\n\t\t\t  wsi->ws->ietf_spec_revision);\n\t\twsi->ws->ietf_spec_revision = 13;\n\t\t//return 1;\n\t\t/* fallthru */\n\tcase 13:\n#if defined(LWS_WITH_HTTP2)\n\t\tif (wsi->h2_stream_carries_ws) {\n\t\t\tif (lws_h2_ws_handshake(wsi)) {\n\t\t\t\tlwsl_notice(\"h2 ws handshake failed\\n\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t} else\n#endif\n\t\t{\n\t\t\tlwsl_parser(\"lws_parse calling handshake_04\\n\");\n\t\t\tif (handshake_0405(wsi->context, wsi)) {\n\t\t\t\tlwsl_notice(\"hs0405 has failed the connection\\n\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\n\tlws_same_vh_protocol_insert(wsi, n);\n\n\t/*\n\t * We are upgrading to ws, so http/1.1 + h2 and keepalive + pipelined\n\t * header considerations about keeping the ah around no longer apply.\n\t *\n\t * However it's common for the first ws protocol data to have been\n\t * coalesced with the browser upgrade request and to already be in the\n\t * ah rx buffer.\n\t */\n\n\tlws_pt_lock(pt, __func__);\n\n\tif (wsi->h2_stream_carries_ws)\n\t\tlws_role_transition(wsi, LWSIFR_SERVER | LWSIFR_P_ENCAP_H2,\n\t\t\t\t    LRS_ESTABLISHED, &role_ops_ws);\n\telse\n\t\tlws_role_transition(wsi, LWSIFR_SERVER, LRS_ESTABLISHED,\n\t\t\t\t    &role_ops_ws);\n\n\tlws_pt_unlock(pt);\n\n\tlws_server_init_wsi_for_ws(wsi);\n\tlwsl_parser(\"accepted v%02d connection\\n\", wsi->ws->ietf_spec_revision);\n\n\tlwsl_info(\"%s: %p: dropping ah on ws upgrade\\n\", __func__, wsi);\n\tlws_header_table_detach(wsi, 1);\n\n\treturn 0;\n}\n\nint\nhandshake_0405(struct lws_context *context, struct lws *wsi)\n{\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tstruct lws_process_html_args args;\n\tunsigned char hash[20];\n\tint n, accept_len;\n\tchar *response;\n\tchar *p;\n\n\tif (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST) ||\n\t    !lws_hdr_total_length(wsi, WSI_TOKEN_KEY)) {\n\t\tlwsl_info(\"handshake_04 missing pieces\\n\");\n\t\t/* completed header processing, but missing some bits */\n\t\tgoto bail;\n\t}\n\n\tif (lws_hdr_total_length(wsi, WSI_TOKEN_KEY) >= MAX_WEBSOCKET_04_KEY_LEN) {\n\t\tlwsl_warn(\"Client key too long %d\\n\", MAX_WEBSOCKET_04_KEY_LEN);\n\t\tgoto bail;\n\t}\n\n\t/*\n\t * since key length is restricted above (currently 128), cannot\n\t * overflow\n\t */\n\tn = sprintf((char *)pt->serv_buf,\n\t\t    \"%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11\",\n\t\t    lws_hdr_simple_ptr(wsi, WSI_TOKEN_KEY));\n\n\tlws_SHA1(pt->serv_buf, n, hash);\n\n\taccept_len = lws_b64_encode_string((char *)hash, 20,\n\t\t\t(char *)pt->serv_buf, context->pt_serv_buf_size);\n\tif (accept_len < 0) {\n\t\tlwsl_warn(\"Base64 encoded hash too long\\n\");\n\t\tgoto bail;\n\t}\n\n\t/* allocate the per-connection user memory (if any) */\n\tif (lws_ensure_user_space(wsi))\n\t\tgoto bail;\n\n\t/* create the response packet */\n\n\t/* make a buffer big enough for everything */\n\n\tresponse = (char *)pt->serv_buf + MAX_WEBSOCKET_04_KEY_LEN + 256 + LWS_PRE;\n\tp = response;\n\tLWS_CPYAPP(p, \"HTTP/1.1 101 Switching Protocols\\x0d\\x0a\"\n\t\t      \"Upgrade: WebSocket\\x0d\\x0a\"\n\t\t      \"Connection: Upgrade\\x0d\\x0a\"\n\t\t      \"Sec-WebSocket-Accept: \");\n\tstrcpy(p, (char *)pt->serv_buf);\n\tp += accept_len;\n\n\t/* we can only return the protocol header if:\n\t *  - one came in, and ... */\n\tif (lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL) &&\n\t    /*  - it is not an empty string */\n\t    wsi->protocol->name &&\n\t    wsi->protocol->name[0]) {\n\t\tLWS_CPYAPP(p, \"\\x0d\\x0aSec-WebSocket-Protocol: \");\n\t\tp += lws_snprintf(p, 128, \"%s\", wsi->protocol->name);\n\t}\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t/*\n\t * Figure out which extensions the client has that we want to\n\t * enable on this connection, and give him back the list.\n\t *\n\t * Give him a limited write bugdet\n\t */\n\tif (lws_extension_server_handshake(wsi, &p, 192))\n\t\tgoto bail;\n#endif\n\tLWS_CPYAPP(p, \"\\x0d\\x0a\");\n\n\targs.p = p;\n\targs.max_len = lws_ptr_diff((char *)pt->serv_buf +\n\t\t\t\t    context->pt_serv_buf_size, p);\n\tif (user_callback_handle_rxflow(wsi->protocol->callback, wsi,\n\t\t\t\t\tLWS_CALLBACK_ADD_HEADERS,\n\t\t\t\t\twsi->user_space, &args, 0))\n\t\tgoto bail;\n\n\tp = args.p;\n\n\t/* end of response packet */\n\n\tLWS_CPYAPP(p, \"\\x0d\\x0a\");\n\n\t/* okay send the handshake response accepting the connection */\n\n\tlwsl_parser(\"issuing resp pkt %d len\\n\",\n\t\t    lws_ptr_diff(p, response));\n#if defined(DEBUG)\n\tfwrite(response, 1,  p - response, stderr);\n#endif\n\tn = lws_write(wsi, (unsigned char *)response, p - response,\n\t\t      LWS_WRITE_HTTP_HEADERS);\n\tif (n != (p - response)) {\n\t\tlwsl_info(\"%s: ERROR writing to socket %d\\n\", __func__, n);\n\t\tgoto bail;\n\t}\n\n\t/* alright clean up and set ourselves into established state */\n\n\tlwsi_set_state(wsi, LRS_ESTABLISHED);\n\twsi->lws_rx_parse_state = LWS_RXPS_NEW;\n\n\t{\n\t\tconst char * uri_ptr =\n\t\t\tlws_hdr_simple_ptr(wsi, WSI_TOKEN_GET_URI);\n\t\tint uri_len = lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI);\n\t\tconst struct lws_http_mount *hit =\n\t\t\tlws_find_mount(wsi, uri_ptr, uri_len);\n\t\tif (hit && hit->cgienv &&\n\t\t    wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_PMO,\n\t\t\twsi->user_space, (void *)hit->cgienv, 0))\n\t\t\treturn 1;\n\t}\n\n\treturn 0;\n\nbail:\n\t/* caller will free up his parsing allocations */\n\treturn -1;\n}\n\n\n\n/*\n * Once we reach LWS_RXPS_WS_FRAME_PAYLOAD, we know how much\n * to expect in that state and can deal with it in bulk more efficiently.\n */\n\nstatic int\nlws_ws_frame_rest_is_payload(struct lws *wsi, uint8_t **buf, size_t len)\n{\n\tuint8_t *buffer = *buf, mask[4];\n\tstruct lws_tokens ebuf;\n\tunsigned int avail = (unsigned int)len;\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tunsigned int old_packet_length = (int)wsi->ws->rx_packet_length;\n#endif\n\tint n = 0;\n\n\t/*\n\t * With zlib, we can give it as much input as we like.  The pmd\n\t * extension will draw it down in chunks (default 1024).\n\t *\n\t * If we try to restrict how much we give it, because we must go\n\t * back to the event loop each time, we will drop the remainder...\n\t */\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tif (!wsi->ws->count_act_ext)\n#endif\n\t{\n\t\tif (wsi->protocol->rx_buffer_size)\n\t\t\tavail = (int)wsi->protocol->rx_buffer_size;\n\t\telse\n\t\t\tavail = wsi->context->pt_serv_buf_size;\n\t}\n\n\t/* do not consume more than we should */\n\tif (avail > wsi->ws->rx_packet_length)\n\t\tavail = (unsigned int)wsi->ws->rx_packet_length;\n\n\t/* do not consume more than what is in the buffer */\n\tif (avail > len)\n\t\tavail = (unsigned int)len;\n\n\tif (avail <= 0)\n\t\treturn 0;\n\n\tebuf.token = (char *)buffer;\n\tebuf.len = avail;\n\n\t//lwsl_hexdump_notice(ebuf.token, ebuf.len);\n\n\tif (!wsi->ws->all_zero_nonce) {\n\n\t\tfor (n = 0; n < 4; n++)\n\t\t\tmask[n] = wsi->ws->mask[(wsi->ws->mask_idx + n) & 3];\n\n\t\t/* deal with 4-byte chunks using unwrapped loop */\n\t\tn = avail >> 2;\n\t\twhile (n--) {\n\t\t\t*(buffer) = *(buffer) ^ mask[0];\n\t\t\tbuffer++;\n\t\t\t*(buffer) = *(buffer) ^ mask[1];\n\t\t\tbuffer++;\n\t\t\t*(buffer) = *(buffer) ^ mask[2];\n\t\t\tbuffer++;\n\t\t\t*(buffer) = *(buffer) ^ mask[3];\n\t\t\tbuffer++;\n\t\t}\n\t\t/* and the remaining bytes bytewise */\n\t\tfor (n = 0; n < (int)(avail & 3); n++) {\n\t\t\t*(buffer) = *(buffer) ^ mask[n];\n\t\t\tbuffer++;\n\t\t}\n\n\t\twsi->ws->mask_idx = (wsi->ws->mask_idx + avail) & 3;\n\t}\n\n\tlwsl_info(\"%s: using %d of raw input (total %d on offer)\\n\", __func__,\n\t\t    avail, (int)len);\n\n\t(*buf) += avail;\n\tlen -= avail;\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tn = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &ebuf, 0);\n\tlwsl_info(\"%s: ext says %d / ebuf.len %d\\n\", __func__,  n, ebuf.len);\n#endif\n\t/*\n\t * ebuf may be pointing somewhere completely different now,\n\t * it's the output\n\t */\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tif (n < 0) {\n\t\t/*\n\t\t * we may rely on this to get RX, just drop connection\n\t\t */\n\t\tlwsl_notice(\"%s: LWS_EXT_CB_PAYLOAD_RX blew out\\n\", __func__);\n\t\twsi->socket_is_permanently_unusable = 1;\n\t\treturn -1;\n\t}\n#endif\n\n\twsi->ws->rx_packet_length -= avail;\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t/*\n\t * if we had an rx fragment right at the last compressed byte of the\n\t * message, we can get a zero length inflated output, where no prior\n\t * rx inflated output marked themselves with FIN, since there was\n\t * raw ws payload still to drain at that time.\n\t *\n\t * Then we need to generate a zero length ws rx that can be understood\n\t * as the message completion.\n\t */\n\n\tif (!ebuf.len &&\t\t      /* zero-length inflation output */\n\t    !n &&\t\t   /* nothing left to drain from the inflator */\n\t    wsi->ws->count_act_ext &&\t\t\t  /* we are using pmd */\n\t    old_packet_length &&\t    /* we gave the inflator new input */\n\t    !wsi->ws->rx_packet_length &&   /* raw ws packet payload all gone */\n\t    wsi->ws->final &&\t\t    /* the raw ws packet is a FIN guy */\n\t    wsi->protocol->callback &&\n\t    !wsi->wsistate_pre_close) {\n\n\t\tif (user_callback_handle_rxflow(wsi->protocol->callback, wsi,\n\t\t\t\t\t\tLWS_CALLBACK_RECEIVE,\n\t\t\t\t\t\twsi->user_space, NULL, 0))\n\t\t\treturn -1;\n\n\t\treturn avail;\n\t}\n#endif\n\n\tif (!ebuf.len)\n\t\treturn avail;\n\n\tif (\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t    n &&\n#endif\n\t    ebuf.len)\n\t\t/* extension had more... main loop will come back */\n\t\tlws_add_wsi_to_draining_ext_list(wsi);\n\telse\n\t\tlws_remove_wsi_from_draining_ext_list(wsi);\n\n\tif (wsi->ws->check_utf8 && !wsi->ws->defeat_check_utf8) {\n\t\tif (lws_check_utf8(&wsi->ws->utf8,\n\t\t\t\t   (unsigned char *)ebuf.token, ebuf.len)) {\n\t\t\tlws_close_reason(wsi, LWS_CLOSE_STATUS_INVALID_PAYLOAD,\n\t\t\t\t\t (uint8_t *)\"bad utf8\", 8);\n\t\t\tgoto utf8_fail;\n\t\t}\n\n\t\t/* we are ending partway through utf-8 character? */\n\t\tif (!wsi->ws->rx_packet_length && wsi->ws->final &&\n\t\t    wsi->ws->utf8 && !n) {\n\t\t\tlwsl_info(\"FINAL utf8 error\\n\");\n\t\t\tlws_close_reason(wsi, LWS_CLOSE_STATUS_INVALID_PAYLOAD,\n\t\t\t\t\t (uint8_t *)\"partial utf8\", 12);\n\nutf8_fail:\n\t\t\tlwsl_info(\"utf8 error\\n\");\n\t\t\tlwsl_hexdump_info(ebuf.token, ebuf.len);\n\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tif (wsi->protocol->callback && !wsi->wsistate_pre_close)\n\t\tif (user_callback_handle_rxflow(wsi->protocol->callback, wsi,\n\t\t\t\t\t\tLWS_CALLBACK_RECEIVE,\n\t\t\t\t\t\twsi->user_space,\n\t\t\t\t\t\tebuf.token, ebuf.len))\n\t\t\treturn -1;\n\n\twsi->ws->first_fragment = 0;\n\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\tlwsl_info(\"%s: input used %d, output %d, rem len %d, rx_draining_ext %d\\n\",\n\t\t  __func__, avail, ebuf.len, (int)len, wsi->ws->rx_draining_ext);\n#endif\n\n\treturn avail; /* how much we used from the input */\n}\n\n\nint\nlws_parse_ws(struct lws *wsi, unsigned char **buf, size_t len)\n{\n\tint m, bulk = 0;\n\n\tlwsl_debug(\"%s: received %d byte packet\\n\", __func__, (int)len);\n\n\t//lwsl_hexdump_notice(*buf, len);\n\n\t/* let the rx protocol state machine have as much as it needs */\n\n\twhile (len) {\n\t\t/*\n\t\t * we were accepting input but now we stopped doing so\n\t\t */\n\t\tif (wsi->rxflow_bitmap) {\n\t\t\tlwsl_info(\"%s: doing rxflow\\n\", __func__);\n\t\t\tlws_rxflow_cache(wsi, *buf, 0, (int)len);\n\t\t\tlwsl_parser(\"%s: cached %ld\\n\", __func__, (long)len);\n\t\t\t*buf += len; /* stashing it is taking care of it */\n\t\t\treturn 1;\n\t\t}\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\tif (wsi->ws->rx_draining_ext) {\n\t\t\tlwsl_debug(\"%s: draining rx ext\\n\", __func__);\n\t\t\tm = lws_ws_rx_sm(wsi, ALREADY_PROCESSED_IGNORE_CHAR, 0);\n\t\t\tif (m < 0)\n\t\t\t\treturn -1;\n\t\t\tcontinue;\n\t\t}\n#endif\n\n\t\t/* consume payload bytes efficiently */\n\t\twhile (wsi->lws_rx_parse_state == LWS_RXPS_WS_FRAME_PAYLOAD &&\n\t\t\t\t(wsi->ws->opcode == LWSWSOPC_TEXT_FRAME ||\n\t\t\t\t wsi->ws->opcode == LWSWSOPC_BINARY_FRAME ||\n\t\t\t\t wsi->ws->opcode == LWSWSOPC_CONTINUATION) &&\n\t\t       len) {\n\t\t\tuint8_t *bin = *buf;\n\n\t\t\tbulk = 1;\n\t\t\tm = lws_ws_frame_rest_is_payload(wsi, buf, len);\n\t\t\tassert((int)lws_ptr_diff(*buf, bin) <= (int)len);\n\t\t\tlen -= lws_ptr_diff(*buf, bin);\n\n\t\t\tif (!m) {\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (m < 0) {\n\t\t\t\tlwsl_info(\"%s: rest_is_payload bailed\\n\",\n\t\t\t\t\t  __func__);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\tif (!bulk) {\n\t\t\t/* process the byte */\n\t\t\tm = lws_ws_rx_sm(wsi, 0, *(*buf)++);\n\t\t\tlen--;\n\t\t} else {\n\t\t\t/*\n\t\t\t * We already handled this byte in bulk, just deal\n\t\t\t * with the ramifications\n\t\t\t */\n#if !defined(LWS_WITHOUT_EXTENSIONS)\n\t\t\tlwsl_debug(\"%s: coming out of bulk with len %d, \"\n\t\t\t\t   \"wsi->ws->rx_draining_ext %d\\n\",\n\t\t\t\t   __func__, (int)len,\n\t\t\t\t   wsi->ws->rx_draining_ext);\n#endif\n\t\t\tm = lws_ws_rx_sm(wsi, ALREADY_PROCESSED_IGNORE_CHAR |\n\t\t\t\t\t ALREADY_PROCESSED_NO_CB, 0);\n\t\t}\n\n\t\tif (m < 0) {\n\t\t\tlwsl_info(\"%s: lws_ws_rx_sm bailed %d\\n\", __func__,\n\t\t\t\t  bulk);\n\n\t\t\treturn -1;\n\t\t}\n\n\t\tbulk = 0;\n\t}\n\n\tlwsl_debug(\"%s: exit with %d unused\\n\", __func__, (int)len);\n\n\treturn 0;\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/lws-genhash.c",
    "content": "/*\n * libwebsockets - generic hash and HMAC api hiding the backend\n *\n * Copyright (C) 2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n *\n *  lws_genhash provides a hash / hmac abstraction api in lws that works the\n *  same whether you are using openssl or mbedtls hash functions underneath.\n */\n#include \"libwebsockets.h\"\n#include <mbedtls/version.h>\n\n#if (MBEDTLS_VERSION_NUMBER >= 0x02070000)\n#define MBA(fn) fn##_ret\n#else\n#define MBA(fn) fn\n#endif\n\nsize_t\nlws_genhash_size(enum lws_genhash_types type)\n{\n\tswitch(type) {\n\tcase LWS_GENHASH_TYPE_SHA1:\n\t\treturn 20;\n\tcase LWS_GENHASH_TYPE_SHA256:\n\t\treturn 32;\n\tcase LWS_GENHASH_TYPE_SHA384:\n\t\treturn 48;\n\tcase LWS_GENHASH_TYPE_SHA512:\n\t\treturn 64;\n\t}\n\n\treturn 0;\n}\n\nint\nlws_genhash_init(struct lws_genhash_ctx *ctx, enum lws_genhash_types type)\n{\n\tctx->type = type;\n\n\tswitch (ctx->type) {\n\tcase LWS_GENHASH_TYPE_SHA1:\n\t\tmbedtls_sha1_init(&ctx->u.sha1);\n\t\tMBA(mbedtls_sha1_starts)(&ctx->u.sha1);\n\t\tbreak;\n\tcase LWS_GENHASH_TYPE_SHA256:\n\t\tmbedtls_sha256_init(&ctx->u.sha256);\n\t\tMBA(mbedtls_sha256_starts)(&ctx->u.sha256, 0);\n\t\tbreak;\n\tcase LWS_GENHASH_TYPE_SHA384:\n\t\tmbedtls_sha512_init(&ctx->u.sha512);\n\t\tMBA(mbedtls_sha512_starts)(&ctx->u.sha512, 1 /* is384 */);\n\t\tbreak;\n\tcase LWS_GENHASH_TYPE_SHA512:\n\t\tmbedtls_sha512_init(&ctx->u.sha512);\n\t\tMBA(mbedtls_sha512_starts)(&ctx->u.sha512, 0);\n\t\tbreak;\n\tdefault:\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\nint\nlws_genhash_update(struct lws_genhash_ctx *ctx, const void *in, size_t len)\n{\n\tswitch (ctx->type) {\n\tcase LWS_GENHASH_TYPE_SHA1:\n\t\tMBA(mbedtls_sha1_update)(&ctx->u.sha1, in, len);\n\t\tbreak;\n\tcase LWS_GENHASH_TYPE_SHA256:\n\t\tMBA(mbedtls_sha256_update)(&ctx->u.sha256, in, len);\n\t\tbreak;\n\tcase LWS_GENHASH_TYPE_SHA384:\n\t\tMBA(mbedtls_sha512_update)(&ctx->u.sha512, in, len);\n\t\tbreak;\n\tcase LWS_GENHASH_TYPE_SHA512:\n\t\tMBA(mbedtls_sha512_update)(&ctx->u.sha512, in, len);\n\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\nint\nlws_genhash_destroy(struct lws_genhash_ctx *ctx, void *result)\n{\n\tswitch (ctx->type) {\n\tcase LWS_GENHASH_TYPE_SHA1:\n\t\tMBA(mbedtls_sha1_finish)(&ctx->u.sha1, result);\n\t\tmbedtls_sha1_free(&ctx->u.sha1);\n\t\tbreak;\n\tcase LWS_GENHASH_TYPE_SHA256:\n\t\tMBA(mbedtls_sha256_finish)(&ctx->u.sha256, result);\n\t\tmbedtls_sha256_free(&ctx->u.sha256);\n\t\tbreak;\n\tcase LWS_GENHASH_TYPE_SHA384:\n\t\tMBA(mbedtls_sha512_finish)(&ctx->u.sha512, result);\n\t\tmbedtls_sha512_free(&ctx->u.sha512);\n\t\tbreak;\n\tcase LWS_GENHASH_TYPE_SHA512:\n\t\tMBA(mbedtls_sha512_finish)(&ctx->u.sha512, result);\n\t\tmbedtls_sha512_free(&ctx->u.sha512);\n\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\nsize_t\nlws_genhmac_size(enum lws_genhmac_types type)\n{\n\tswitch(type) {\n\tcase LWS_GENHMAC_TYPE_SHA256:\n\t\treturn 32;\n\tcase LWS_GENHMAC_TYPE_SHA384:\n\t\treturn 48;\n\tcase LWS_GENHMAC_TYPE_SHA512:\n\t\treturn 64;\n\t}\n\n\treturn 0;\n}\n\nint\nlws_genhmac_init(struct lws_genhmac_ctx *ctx, enum lws_genhmac_types type,\n\t\t const uint8_t *key, size_t key_len)\n{\n\tint t;\n\n\tctx->type = type;\n\n\tswitch (type) {\n\tcase LWS_GENHMAC_TYPE_SHA256:\n\t\tt = MBEDTLS_MD_SHA256;\n\t\tbreak;\n\tcase LWS_GENHMAC_TYPE_SHA384:\n\t\tt = MBEDTLS_MD_SHA384;\n\t\tbreak;\n\tcase LWS_GENHMAC_TYPE_SHA512:\n\t\tt = MBEDTLS_MD_SHA512;\n\t\tbreak;\n\tdefault:\n\t\treturn -1;\n\t}\n\n\tctx->hmac = mbedtls_md_info_from_type(t);\n\tif (!ctx->hmac)\n\t\treturn -1;\n\n\tif (mbedtls_md_init_ctx(&ctx->ctx, ctx->hmac))\n\t\treturn -1;\n\n\tif (mbedtls_md_hmac_starts(&ctx->ctx, key, key_len)) {\n\t\tmbedtls_md_free(&ctx->ctx);\n\t\tctx->hmac = NULL;\n\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\nint\nlws_genhmac_update(struct lws_genhmac_ctx *ctx, const void *in, size_t len)\n{\n\tif (mbedtls_md_hmac_update(&ctx->ctx, in, len))\n\t\treturn -1;\n\n\treturn 0;\n}\n\nint\nlws_genhmac_destroy(struct lws_genhmac_ctx *ctx, void *result)\n{\n\tint n = 0;\n\n\tif (result)\n\t\tn = mbedtls_md_hmac_finish(&ctx->ctx, result);\n\n\tmbedtls_md_free(&ctx->ctx);\n\tctx->hmac = NULL;\n\tif (n)\n\t\treturn -1;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/lws-genrsa.c",
    "content": "/*\n * libwebsockets - generic RSA api hiding the backend\n *\n * Copyright (C) 2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n *\n *  lws_genhash provides a hash / hmac abstraction api in lws that works the\n *  same whether you are using openssl or mbedtls hash functions underneath.\n */\n#include \"core/private.h\"\n\nLWS_VISIBLE void\nlws_jwk_destroy_genrsa_elements(struct lws_genrsa_elements *el)\n{\n\tint n;\n\n\tfor (n = 0; n < LWS_COUNT_RSA_ELEMENTS; n++)\n\t\tif (el->e[n].buf)\n\t\t\tlws_free_set_NULL(el->e[n].buf);\n}\n\nLWS_VISIBLE int\nlws_genrsa_create(struct lws_genrsa_ctx *ctx, struct lws_genrsa_elements *el)\n{\n\tint n;\n\n\tmemset(ctx, 0, sizeof(*ctx));\n\tctx->ctx = lws_zalloc(sizeof(*ctx->ctx), \"genrsa\");\n\tif (!ctx->ctx)\n\t\treturn 1;\n\n\tmbedtls_rsa_init(ctx->ctx, MBEDTLS_RSA_PKCS_V15, 0);\n\n\t{\n\t\tmbedtls_mpi *mpi[LWS_COUNT_RSA_ELEMENTS] = {\n\t\t\t&ctx->ctx->E, &ctx->ctx->N, &ctx->ctx->D, &ctx->ctx->P,\n\t\t\t&ctx->ctx->Q, &ctx->ctx->DP, &ctx->ctx->DQ,\n\t\t\t&ctx->ctx->QP,\n\t\t};\n\n\t\tfor (n = 0; n < LWS_COUNT_RSA_ELEMENTS; n++)\n\t\t\tif (el->e[n].buf &&\n\t\t\t    mbedtls_mpi_read_binary(mpi[n], el->e[n].buf,\n\t\t\t\t\t    \t    el->e[n].len)) {\n\t\t\t\tlwsl_notice(\"mpi load failed\\n\");\n\t\t\t\tlws_free_set_NULL(ctx->ctx);\n\n\t\t\t\treturn -1;\n\t\t\t}\n\t}\n\n\tctx->ctx->len = el->e[JWK_KEY_N].len;\n\n\treturn 0;\n}\n\nstatic int\n_rngf(void *context, unsigned char *buf, size_t len)\n{\n\tif ((size_t)lws_get_random(context, buf, len) == len)\n\t\treturn 0;\n\n\treturn -1;\n}\n\nLWS_VISIBLE int\nlws_genrsa_new_keypair(struct lws_context *context, struct lws_genrsa_ctx *ctx,\n\t\t       struct lws_genrsa_elements *el, int bits)\n{\n\tint n;\n\n\tmemset(ctx, 0, sizeof(*ctx));\n\tctx->ctx = lws_zalloc(sizeof(*ctx->ctx), \"genrsa\");\n\tif (!ctx->ctx)\n\t\treturn -1;\n\n\tmbedtls_rsa_init(ctx->ctx, MBEDTLS_RSA_PKCS_V15, 0);\n\n\tn = mbedtls_rsa_gen_key(ctx->ctx, _rngf, context, bits, 65537);\n\tif (n) {\n\t\tlwsl_err(\"mbedtls_rsa_gen_key failed 0x%x\\n\", -n);\n\t\tgoto cleanup_1;\n\t}\n\n\t{\n\t\tmbedtls_mpi *mpi[LWS_COUNT_RSA_ELEMENTS] = {\n\t\t\t&ctx->ctx->E, &ctx->ctx->N, &ctx->ctx->D, &ctx->ctx->P,\n\t\t\t&ctx->ctx->Q, &ctx->ctx->DP, &ctx->ctx->DQ,\n\t\t\t&ctx->ctx->QP,\n\t\t};\n\n\t\tfor (n = 0; n < LWS_COUNT_RSA_ELEMENTS; n++)\n\t\t\tif (mbedtls_mpi_size(mpi[n])) {\n\t\t\t\tel->e[n].buf = lws_malloc(\n\t\t\t\t\tmbedtls_mpi_size(mpi[n]), \"genrsakey\");\n\t\t\t\tif (!el->e[n].buf)\n\t\t\t\t\tgoto cleanup;\n\t\t\t\tel->e[n].len = mbedtls_mpi_size(mpi[n]);\n\t\t\t\tmbedtls_mpi_write_binary(mpi[n], el->e[n].buf,\n\t\t\t\t\t\t\t el->e[n].len);\n\t\t\t}\n\t}\n\n\treturn 0;\n\ncleanup:\n\tfor (n = 0; n < LWS_COUNT_RSA_ELEMENTS; n++)\n\t\tif (el->e[n].buf)\n\t\t\tlws_free_set_NULL(el->e[n].buf);\ncleanup_1:\n\tlws_free(ctx->ctx);\n\n\treturn -1;\n}\n\nLWS_VISIBLE int\nlws_genrsa_public_decrypt(struct lws_genrsa_ctx *ctx, const uint8_t *in,\n\t\t\t   size_t in_len, uint8_t *out, size_t out_max)\n{\n\tsize_t olen = 0;\n\tint n;\n\n\tctx->ctx->len = in_len;\n\tn = mbedtls_rsa_rsaes_pkcs1_v15_decrypt(ctx->ctx, NULL, NULL,\n\t\t\t\t\t\tMBEDTLS_RSA_PUBLIC,\n\t\t\t\t\t\t&olen, in, out, out_max);\n\tif (n) {\n\t\tlwsl_notice(\"%s: -0x%x\\n\", __func__, -n);\n\n\t\treturn -1;\n\t}\n\n\treturn olen;\n}\n\nLWS_VISIBLE int\nlws_genrsa_public_encrypt(struct lws_genrsa_ctx *ctx, const uint8_t *in,\n\t\t\t   size_t in_len, uint8_t *out)\n{\n\tint n;\n\n\tctx->ctx->len = in_len;\n\tn = mbedtls_rsa_rsaes_pkcs1_v15_encrypt(ctx->ctx, NULL, NULL,\n\t\t\t\t\t\tMBEDTLS_RSA_PRIVATE,\n\t\t\t\t\t\tin_len, in, out);\n\tif (n) {\n\t\tlwsl_notice(\"%s: -0x%x\\n\", __func__, -n);\n\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\nstatic int\nlws_genrsa_genrsa_hash_to_mbed_hash(enum lws_genhash_types hash_type)\n{\n\tint h = -1;\n\n\tswitch (hash_type) {\n\tcase LWS_GENHASH_TYPE_SHA1:\n\t\th = MBEDTLS_MD_SHA1;\n\t\tbreak;\n\tcase LWS_GENHASH_TYPE_SHA256:\n\t\th = MBEDTLS_MD_SHA256;\n\t\tbreak;\n\tcase LWS_GENHASH_TYPE_SHA384:\n\t\th = MBEDTLS_MD_SHA384;\n\t\tbreak;\n\tcase LWS_GENHASH_TYPE_SHA512:\n\t\th = MBEDTLS_MD_SHA512;\n\t\tbreak;\n\t}\n\n\treturn h;\n}\n\nLWS_VISIBLE int\nlws_genrsa_public_verify(struct lws_genrsa_ctx *ctx, const uint8_t *in,\n\t\t\t enum lws_genhash_types hash_type, const uint8_t *sig,\n\t\t\t size_t sig_len)\n{\n\tint n, h = lws_genrsa_genrsa_hash_to_mbed_hash(hash_type);\n\n\tif (h < 0)\n\t\treturn -1;\n\n\tn = mbedtls_rsa_rsassa_pkcs1_v15_verify(ctx->ctx, NULL, NULL,\n\t\t\t\t\t\tMBEDTLS_RSA_PUBLIC,\n\t\t\t\t\t\th, 0, in, sig);\n\tif (n < 0) {\n\t\tlwsl_notice(\"%s: -0x%x\\n\", __func__, -n);\n\n\t\treturn -1;\n\t}\n\n\treturn n;\n}\n\nLWS_VISIBLE int\nlws_genrsa_public_sign(struct lws_genrsa_ctx *ctx, const uint8_t *in,\n\t\t\t enum lws_genhash_types hash_type, uint8_t *sig,\n\t\t\t size_t sig_len)\n{\n\tint n, h = lws_genrsa_genrsa_hash_to_mbed_hash(hash_type);\n\n\tif (h < 0)\n\t\treturn -1;\n\n\t/*\n\t * The \"sig\" buffer must be as large as the size of ctx->N\n\t * (eg. 128 bytes if RSA-1024 is used).\n\t */\n\tif (sig_len < ctx->ctx->len)\n\t\treturn -1;\n\n\tn = mbedtls_rsa_rsassa_pkcs1_v15_sign(ctx->ctx, NULL, NULL,\n\t\t\t\t\t      MBEDTLS_RSA_PRIVATE, h, 0, in,\n\t\t\t\t\t      sig);\n\tif (n < 0) {\n\t\tlwsl_notice(\"%s: -0x%x\\n\", __func__, -n);\n\n\t\treturn -1;\n\t}\n\n\treturn ctx->ctx->len;\n}\n\nLWS_VISIBLE int\nlws_genrsa_render_pkey_asn1(struct lws_genrsa_ctx *ctx, int _private,\n\t\t\t    uint8_t *pkey_asn1, size_t pkey_asn1_len)\n{\n\tuint8_t *p = pkey_asn1, *totlen, *end = pkey_asn1 + pkey_asn1_len - 1;\n\tmbedtls_mpi *mpi[LWS_COUNT_RSA_ELEMENTS] = {\n\t\t&ctx->ctx->N, &ctx->ctx->E, &ctx->ctx->D, &ctx->ctx->P,\n\t\t&ctx->ctx->Q, &ctx->ctx->DP, &ctx->ctx->DQ,\n\t\t&ctx->ctx->QP,\n\t};\n\tint n;\n\n\t/* 30 82  - sequence\n\t *   09 29  <-- length(0x0929) less 4 bytes\n\t * 02 01 <- length (1)\n\t *  00\n\t * 02 82\n\t *  02 01 <- length (513)  N\n\t *  ...\n\t *\n\t *  02 03 <- length (3) E\n\t *    01 00 01\n\t *\n\t * 02 82\n\t *   02 00 <- length (512) D P Q EXP1 EXP2 COEFF\n\t *\n\t *  */\n\n\t*p++ = 0x30;\n\t*p++ = 0x82;\n\ttotlen = p;\n\tp += 2;\n\n\t*p++ = 0x02;\n\t*p++ = 0x01;\n\t*p++ = 0x00;\n\n\tfor (n = 0; n < LWS_COUNT_RSA_ELEMENTS; n++) {\n\t\tint m = mbedtls_mpi_size(mpi[n]);\n\t\tuint8_t *elen;\n\n\t\t*p++ = 0x02;\n\t\telen = p;\n\t\tif (m < 0x7f)\n\t\t\t*p++ = m;\n\t\telse {\n\t\t\t*p++ = 0x82;\n\t\t\t*p++ = m >> 8;\n\t\t\t*p++ = m & 0xff;\n\t\t}\n\n\t\tif (p + m > end)\n\t\t\treturn -1;\n\n\t\tmbedtls_mpi_write_binary(mpi[n], p, m);\n\t\tif (p[0] & 0x80) {\n\t\t\tp[0] = 0x00;\n\t\t\tmbedtls_mpi_write_binary(mpi[n], &p[1], m);\n\t\t\tm++;\n\t\t}\n\t\tif (m < 0x7f)\n\t\t\t*elen = m;\n\t\telse {\n\t\t\t*elen++ = 0x82;\n\t\t\t*elen++ = m >> 8;\n\t\t\t*elen = m & 0xff;\n\t\t}\n\t\tp += m;\n\t}\n\n\tn = lws_ptr_diff(p, pkey_asn1);\n\n\t*totlen++ = (n - 4) >> 8;\n\t*totlen = (n - 4) & 0xff;\n\n\treturn n;\n}\n\nLWS_VISIBLE void\nlws_genrsa_destroy(struct lws_genrsa_ctx *ctx)\n{\n\tif (!ctx->ctx)\n\t\treturn;\n\tmbedtls_rsa_free(ctx->ctx);\n\tlws_free(ctx->ctx);\n\tctx->ctx = NULL;\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/mbedtls-client.c",
    "content": "/*\n * libwebsockets - mbedtls-specific client TLS code\n *\n * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n\nstatic int\nOpenSSL_client_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)\n{\n\treturn 0;\n}\n\nint\nlws_ssl_client_bio_create(struct lws *wsi)\n{\n\tX509_VERIFY_PARAM *param;\n\tchar hostname[128], *p;\n\tconst char *alpn_comma = wsi->context->tls.alpn_default;\n\tstruct alpn_ctx protos;\n\n\tif (lws_hdr_copy(wsi, hostname, sizeof(hostname),\n\t\t\t _WSI_TOKEN_CLIENT_HOST) <= 0) {\n\t\tlwsl_err(\"%s: Unable to get hostname\\n\", __func__);\n\n\t\treturn -1;\n\t}\n\n\t/*\n\t * remove any :port part on the hostname... necessary for network\n\t * connection but typical certificates do not contain it\n\t */\n\tp = hostname;\n\twhile (*p) {\n\t\tif (*p == ':') {\n\t\t\t*p = '\\0';\n\t\t\tbreak;\n\t\t}\n\t\tp++;\n\t}\n\n\twsi->tls.ssl = SSL_new(wsi->vhost->tls.ssl_client_ctx);\n\tif (!wsi->tls.ssl)\n\t\treturn -1;\n\n\tif (wsi->vhost->tls.ssl_info_event_mask)\n\t\tSSL_set_info_callback(wsi->tls.ssl, lws_ssl_info_callback);\n\n\tif (!(wsi->tls.use_ssl & LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK)) {\n\t\tparam = SSL_get0_param(wsi->tls.ssl);\n\t\t/* Enable automatic hostname checks */\n\t//\tX509_VERIFY_PARAM_set_hostflags(param,\n\t//\t\t\t\tX509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);\n\t\tX509_VERIFY_PARAM_set1_host(param, hostname, 0);\n\t}\n\n\tif (wsi->vhost->tls.alpn)\n\t\talpn_comma = wsi->vhost->tls.alpn;\n\n\tif (lws_hdr_copy(wsi, hostname, sizeof(hostname),\n\t\t\t _WSI_TOKEN_CLIENT_ALPN) > 0)\n\t\talpn_comma = hostname;\n\n\tlwsl_info(\"%s: %p: client conn sending ALPN list '%s'\\n\",\n\t\t  __func__, wsi, alpn_comma);\n\n\tprotos.len = lws_alpn_comma_to_openssl(alpn_comma, protos.data,\n\t\t\t\t\t       sizeof(protos.data) - 1);\n\n\t/* with mbedtls, protos is not pointed to after exit from this call */\n\tSSL_set_alpn_select_cb(wsi->tls.ssl, &protos);\n\n\t/*\n\t * use server name indication (SNI), if supported,\n\t * when establishing connection\n\t */\n\tSSL_set_verify(wsi->tls.ssl, SSL_VERIFY_PEER,\n\t\t       OpenSSL_client_verify_callback);\n\n\tSSL_set_fd(wsi->tls.ssl, wsi->desc.sockfd);\n\n\treturn 0;\n}\n\nint ERR_get_error(void)\n{\n\treturn 0;\n}\n\nenum lws_ssl_capable_status\nlws_tls_client_connect(struct lws *wsi)\n{\n\tint m, n = SSL_connect(wsi->tls.ssl);\n\tconst unsigned char *prot;\n\tunsigned int len;\n\n\tif (n == 1) {\n\t\tSSL_get0_alpn_selected(wsi->tls.ssl, &prot, &len);\n\t\tlws_role_call_alpn_negotiated(wsi, (const char *)prot);\n\t\tlwsl_info(\"client connect OK\\n\");\n\t\treturn LWS_SSL_CAPABLE_DONE;\n\t}\n\n\tm = SSL_get_error(wsi->tls.ssl, n);\n\n\tif (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl))\n\t\treturn LWS_SSL_CAPABLE_MORE_SERVICE_READ;\n\n\tif (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl))\n\t\treturn LWS_SSL_CAPABLE_MORE_SERVICE_WRITE;\n\n\tif (!n) /* we don't know what he wants, but he says to retry */\n\t\treturn LWS_SSL_CAPABLE_MORE_SERVICE;\n\n\treturn LWS_SSL_CAPABLE_ERROR;\n}\n\nint\nlws_tls_client_confirm_peer_cert(struct lws *wsi, char *ebuf, int ebuf_len)\n{\n\tint n;\n\tX509 *peer = SSL_get_peer_certificate(wsi->tls.ssl);\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\tchar *sb = (char *)&pt->serv_buf[0];\n\n\tif (!peer) {\n\t\tlwsl_info(\"peer did not provide cert\\n\");\n\n\t\treturn -1;\n\t}\n\tlwsl_info(\"peer provided cert\\n\");\n\n\tn = SSL_get_verify_result(wsi->tls.ssl);\n\tlws_latency(wsi->context, wsi,\n\t\t\t\"SSL_get_verify_result LWS_CONNMODE..HANDSHAKE\", n, n > 0);\n\n        lwsl_debug(\"get_verify says %d\\n\", n);\n\n\tif (n == X509_V_OK)\n\t\treturn 0;\n\n\tif (n == X509_V_ERR_HOSTNAME_MISMATCH &&\n\t    (wsi->tls.use_ssl & LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK)) {\n\t\tlwsl_info(\"accepting certificate for invalid hostname\\n\");\n\t\treturn 0;\n\t}\n\n\tif (n == X509_V_ERR_INVALID_CA &&\n\t    (wsi->tls.use_ssl & LCCSCF_ALLOW_SELFSIGNED)) {\n\t\tlwsl_info(\"accepting certificate from untrusted CA\\n\");\n\t\treturn 0;\n\t}\n\n\tif ((n == X509_V_ERR_CERT_NOT_YET_VALID ||\n\t     n == X509_V_ERR_CERT_HAS_EXPIRED) &&\n\t     (wsi->tls.use_ssl & LCCSCF_ALLOW_EXPIRED)) {\n\t\tlwsl_info(\"accepting expired or not yet valid certificate\\n\");\n\n\t\treturn 0;\n\t}\n\tlws_snprintf(ebuf, ebuf_len,\n\t\t\"server's cert didn't look good, X509_V_ERR = %d: %s\\n\",\n\t\t n, ERR_error_string(n, sb));\n\tlwsl_info(\"%s\\n\", ebuf);\n\tlws_ssl_elaborate_error();\n\n\treturn -1;\n}\n\nint\nlws_tls_client_create_vhost_context(struct lws_vhost *vh,\n\t\t\t\t    const struct lws_context_creation_info *info,\n\t\t\t\t    const char *cipher_list,\n\t\t\t\t    const char *ca_filepath,\n\t\t\t\t    const char *cert_filepath,\n\t\t\t\t    const char *private_key_filepath)\n{\n\tX509 *d2i_X509(X509 **cert, const unsigned char *buffer, long len);\n\tSSL_METHOD *method = (SSL_METHOD *)TLS_client_method();\n\tunsigned long error;\n\tlws_filepos_t len;\n\tuint8_t *buf;\n\n\tif (!method) {\n\t\terror = ERR_get_error();\n\t\tlwsl_err(\"problem creating ssl method %lu: %s\\n\",\n\t\t\terror, ERR_error_string(error,\n\t\t\t\t      (char *)vh->context->pt[0].serv_buf));\n\t\treturn 1;\n\t}\n\t/* create context */\n\tvh->tls.ssl_client_ctx = SSL_CTX_new(method);\n\tif (!vh->tls.ssl_client_ctx) {\n\t\terror = ERR_get_error();\n\t\tlwsl_err(\"problem creating ssl context %lu: %s\\n\",\n\t\t\terror, ERR_error_string(error,\n\t\t\t\t      (char *)vh->context->pt[0].serv_buf));\n\t\treturn 1;\n\t}\n\n\tif (!ca_filepath)\n\t\treturn 0;\n\n\tif (alloc_file(vh->context, ca_filepath, &buf, &len)) {\n\t\tlwsl_err(\"Load CA cert file %s failed\\n\", ca_filepath);\n\t\treturn 1;\n\t}\n\n\tvh->tls.x509_client_CA = d2i_X509(NULL, buf, len);\n\tfree(buf);\n\tif (!vh->tls.x509_client_CA) {\n\t\tlwsl_err(\"client CA: x509 parse failed\\n\");\n\t\treturn 1;\n\t}\n\n\tif (!vh->tls.ssl_ctx)\n\t\tSSL_CTX_add_client_CA(vh->tls.ssl_client_ctx, vh->tls.x509_client_CA);\n\telse\n\t\tSSL_CTX_add_client_CA(vh->tls.ssl_ctx, vh->tls.x509_client_CA);\n\n\tlwsl_notice(\"client loaded CA for verification %s\\n\", ca_filepath);\n\n\treturn 0;\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/mbedtls-server.c",
    "content": "/*\n * libwebsockets - mbedTLS-specific server functions\n *\n * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n#include <mbedtls/x509_csr.h>\n\nint\nlws_tls_server_client_cert_verify_config(struct lws_vhost *vh)\n{\n\tint verify_options = SSL_VERIFY_PEER;\n\n\t/* as a server, are we requiring clients to identify themselves? */\n\tif (!lws_check_opt(vh->options,\n\t\t\t  LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT)) {\n\t\tlwsl_notice(\"no client cert required\\n\");\n\t\treturn 0;\n\t}\n\n\t/*\n\t * The wrapper has this messed-up mapping:\n\t *\n\t * \t   else if (ctx->verify_mode == SSL_VERIFY_FAIL_IF_NO_PEER_CERT)\n\t *     mode = MBEDTLS_SSL_VERIFY_OPTIONAL;\n\t *\n\t * ie the meaning is inverted.  So where we should test for ! we don't\n\t */\n\tif (lws_check_opt(vh->options, LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED))\n\t\tverify_options = SSL_VERIFY_FAIL_IF_NO_PEER_CERT;\n\n\tlwsl_notice(\"%s: vh %s requires client cert %d\\n\", __func__, vh->name,\n\t\t    verify_options);\n\n\tSSL_CTX_set_verify(vh->tls.ssl_ctx, verify_options, NULL);\n\n\treturn 0;\n}\n\nstatic int\nlws_mbedtls_sni_cb(void *arg, mbedtls_ssl_context *mbedtls_ctx,\n\t\t   const unsigned char *servername, size_t len)\n{\n\tSSL *ssl = SSL_SSL_from_mbedtls_ssl_context(mbedtls_ctx);\n\tstruct lws_context *context = (struct lws_context *)arg;\n\tstruct lws_vhost *vhost, *vh;\n\n\tlwsl_notice(\"%s: %s\\n\", __func__, servername);\n\n\t/*\n\t * We can only get ssl accepted connections by using a vhost's ssl_ctx\n\t * find out which listening one took us and only match vhosts on the\n\t * same port.\n\t */\n\tvh = context->vhost_list;\n\twhile (vh) {\n\t\tif (!vh->being_destroyed &&\n\t\t    vh->tls.ssl_ctx == SSL_get_SSL_CTX(ssl))\n\t\t\tbreak;\n\t\tvh = vh->vhost_next;\n\t}\n\n\tif (!vh) {\n\t\tassert(vh); /* can't match the incoming vh? */\n\t\treturn 0;\n\t}\n\n\tvhost = lws_select_vhost(context, vh->listen_port,\n\t\t\t\t (const char *)servername);\n\tif (!vhost) {\n\t\tlwsl_info(\"SNI: none: %s:%d\\n\", servername, vh->listen_port);\n\n\t\treturn 0;\n\t}\n\n\tlwsl_info(\"SNI: Found: %s:%d at vhost '%s'\\n\", servername,\n\t\t\t\t\tvh->listen_port, vhost->name);\n\n\t/* select the ssl ctx from the selected vhost for this conn */\n\tSSL_set_SSL_CTX(ssl, vhost->tls.ssl_ctx);\n\n\treturn 0;\n}\n\nint\nlws_tls_server_certs_load(struct lws_vhost *vhost, struct lws *wsi,\n\t\t\t  const char *cert, const char *private_key,\n\t\t\t  const char *mem_cert, size_t len_mem_cert,\n\t\t\t  const char *mem_privkey, size_t mem_privkey_len)\n{\n\tint n, f = 0;\n\tconst char *filepath = private_key;\n\tuint8_t *mem = NULL, *p = NULL;\n\tsize_t mem_len = 0;\n\tlws_filepos_t flen;\n\tlong err;\n\n\tif ((!cert || !private_key) && (!mem_cert || !mem_privkey)) {\n\t\tlwsl_notice(\"%s: no usable input\\n\", __func__);\n\t\treturn 0;\n\t}\n\n\tn = lws_tls_generic_cert_checks(vhost, cert, private_key);\n\n\tif (n == LWS_TLS_EXTANT_NO && (!mem_cert || !mem_privkey))\n\t\treturn 0;\n\n\t/*\n\t * we can't read the root-privs files.  But if mem_cert is provided,\n\t * we should use that.\n\t */\n\tif (n == LWS_TLS_EXTANT_NO)\n\t\tn = LWS_TLS_EXTANT_ALTERNATIVE;\n\n\tif (n == LWS_TLS_EXTANT_ALTERNATIVE && (!mem_cert || !mem_privkey))\n\t\treturn 1; /* no alternative */\n\n\tif (n == LWS_TLS_EXTANT_ALTERNATIVE) {\n\t\t/*\n\t\t * Although we have prepared update certs, we no longer have\n\t\t * the rights to read our own cert + key we saved.\n\t\t *\n\t\t * If we were passed copies in memory buffers, use those\n\t\t * instead.\n\t\t *\n\t\t * The passed memory-buffer cert image is in DER, and the\n\t\t * memory-buffer private key image is PEM.\n\t\t */\n\t\t/* mem cert is already DER */\n\t\tp = (uint8_t *)mem_cert;\n\t\tflen = len_mem_cert;\n\t\t/* mem private key is PEM, so go through the motions */\n\t\tmem = (uint8_t *)mem_privkey;\n\t\tmem_len = mem_privkey_len;\n\t\tfilepath = NULL;\n\t} else {\n\t\tif (lws_tls_alloc_pem_to_der_file(vhost->context, cert, NULL,\n\t\t\t\t\t\t  0, &p, &flen)) {\n\t\t\tlwsl_err(\"couldn't find cert file %s\\n\", cert);\n\n\t\t\treturn 1;\n\t\t}\n\t\tf = 1;\n\t}\n\terr = SSL_CTX_use_certificate_ASN1(vhost->tls.ssl_ctx, flen, p);\n\tif (!err) {\n\t\tfree(p);\n\t\tlwsl_err(\"Problem loading cert\\n\");\n\t\treturn 1;\n\t}\n\n\tif (f)\n\t\tfree(p);\n\tp = NULL;\n\n\tif (private_key || n == LWS_TLS_EXTANT_ALTERNATIVE) {\n\t\tif (lws_tls_alloc_pem_to_der_file(vhost->context, filepath,\n\t\t\t\t\t\t  (char *)mem, mem_len, &p,\n\t\t\t\t\t\t  &flen)) {\n\t\t\tlwsl_err(\"couldn't find private key file %s\\n\",\n\t\t\t\t\tprivate_key);\n\n\t\t\treturn 1;\n\t\t}\n\t\terr = SSL_CTX_use_PrivateKey_ASN1(0, vhost->tls.ssl_ctx, p, flen);\n\t\tif (!err) {\n\t\t\tfree(p);\n\t\t\tlwsl_err(\"Problem loading key\\n\");\n\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tif (p && !mem_privkey) {\n\t\tfree(p);\n\t\tp = NULL;\n\t}\n\n\tif (!private_key && !mem_privkey &&\n\t    vhost->protocols[0].callback(wsi,\n\t\t\tLWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY,\n\t\t\tvhost->tls.ssl_ctx, NULL, 0)) {\n\t\tlwsl_err(\"ssl private key not set\\n\");\n\n\t\treturn 1;\n\t}\n\n\tvhost->tls.skipped_certs = 0;\n\n\treturn 0;\n}\n\nint\nlws_tls_server_vhost_backend_init(const struct lws_context_creation_info *info,\n\t\t\t\t  struct lws_vhost *vhost, struct lws *wsi)\n{\n\tconst SSL_METHOD *method = TLS_server_method();\n\tuint8_t *p;\n\tlws_filepos_t flen;\n\tint n;\n\n\tvhost->tls.ssl_ctx = SSL_CTX_new(method);\t/* create context */\n\tif (!vhost->tls.ssl_ctx) {\n\t\tlwsl_err(\"problem creating ssl context\\n\");\n\t\treturn 1;\n\t}\n\n\tif (!vhost->tls.use_ssl || !info->ssl_cert_filepath)\n\t\treturn 0;\n\n\tif (info->ssl_ca_filepath) {\n\t\tlwsl_notice(\"%s: vh %s: loading CA filepath %s\\n\", __func__,\n\t\t\t    vhost->name, info->ssl_ca_filepath);\n\t\tif (lws_tls_alloc_pem_to_der_file(vhost->context,\n\t\t\t\tinfo->ssl_ca_filepath, NULL, 0, &p, &flen)) {\n\t\t\tlwsl_err(\"couldn't find client CA file %s\\n\",\n\t\t\t\t\tinfo->ssl_ca_filepath);\n\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (SSL_CTX_add_client_CA_ASN1(vhost->tls.ssl_ctx, (int)flen, p) != 1) {\n\t\t\tlwsl_err(\"%s: SSL_CTX_add_client_CA_ASN1 unhappy\\n\",\n\t\t\t\t __func__);\n\t\t\tfree(p);\n\t\t\treturn 1;\n\t\t}\n\t\tfree(p);\n\t}\n\n\tn = lws_tls_server_certs_load(vhost, wsi, info->ssl_cert_filepath,\n\t\t\t\t      info->ssl_private_key_filepath, NULL,\n\t\t\t\t      0, NULL, 0);\n\tif (n)\n\t\treturn n;\n\n\treturn 0;\n}\n\nint\nlws_tls_server_new_nonblocking(struct lws *wsi, lws_sockfd_type accept_fd)\n{\n\terrno = 0;\n\twsi->tls.ssl = SSL_new(wsi->vhost->tls.ssl_ctx);\n\tif (wsi->tls.ssl == NULL) {\n\t\tlwsl_err(\"SSL_new failed: errno %d\\n\", errno);\n\n\t\tlws_ssl_elaborate_error();\n\t\treturn 1;\n\t}\n\n\tSSL_set_fd(wsi->tls.ssl, accept_fd);\n\n\tif (wsi->vhost->tls.ssl_info_event_mask)\n\t\tSSL_set_info_callback(wsi->tls.ssl, lws_ssl_info_callback);\n\n\tSSL_set_sni_callback(wsi->tls.ssl, lws_mbedtls_sni_cb, wsi->context);\n\n\treturn 0;\n}\n\nint\nlws_tls_server_abort_connection(struct lws *wsi)\n{\n\t__lws_tls_shutdown(wsi);\n\tSSL_free(wsi->tls.ssl);\n\n\treturn 0;\n}\n\nenum lws_ssl_capable_status\nlws_tls_server_accept(struct lws *wsi)\n{\n\tunion lws_tls_cert_info_results ir;\n\tint m, n;\n\n\tn = SSL_accept(wsi->tls.ssl);\n\tif (n == 1) {\n\n\t\tif (strstr(wsi->vhost->name, \".invalid\")) {\n\t\t\tlwsl_notice(\"%s: vhost has .invalid, rejecting accept\\n\", __func__);\n\n\t\t\treturn LWS_SSL_CAPABLE_ERROR;\n\t\t}\n\n\t\tn = lws_tls_peer_cert_info(wsi, LWS_TLS_CERT_INFO_COMMON_NAME, &ir,\n\t\t\t\t\t   sizeof(ir.ns.name));\n\t\tif (!n)\n\t\t\tlwsl_notice(\"%s: client cert CN '%s'\\n\",\n\t\t\t\t    __func__, ir.ns.name);\n\t\telse\n\t\t\tlwsl_info(\"%s: couldn't get client cert CN\\n\", __func__);\n\t\treturn LWS_SSL_CAPABLE_DONE;\n\t}\n\n\tm = SSL_get_error(wsi->tls.ssl, n);\n\tlwsl_debug(\"%s: %p: accept SSL_get_error %d errno %d\\n\", __func__,\n\t\t   wsi, m, errno);\n\n\t// mbedtls wrapper only\n\tif (m == SSL_ERROR_SYSCALL && errno == 11)\n\t\treturn LWS_SSL_CAPABLE_MORE_SERVICE_READ;\n\n\tif (m == SSL_ERROR_SYSCALL || m == SSL_ERROR_SSL)\n\t\treturn LWS_SSL_CAPABLE_ERROR;\n\n\tif (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl)) {\n\t\tif (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {\n\t\t\tlwsl_info(\"%s: WANT_READ change_pollfd failed\\n\", __func__);\n\t\t\treturn LWS_SSL_CAPABLE_ERROR;\n\t\t}\n\n\t\tlwsl_info(\"SSL_ERROR_WANT_READ\\n\");\n\t\treturn LWS_SSL_CAPABLE_MORE_SERVICE_READ;\n\t}\n\tif (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl)) {\n\t\tlwsl_debug(\"%s: WANT_WRITE\\n\", __func__);\n\n\t\tif (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) {\n\t\t\tlwsl_info(\"%s: WANT_WRITE change_pollfd failed\\n\", __func__);\n\t\t\treturn LWS_SSL_CAPABLE_ERROR;\n\t\t}\n\t\treturn LWS_SSL_CAPABLE_MORE_SERVICE_WRITE;\n\t}\n\n\treturn LWS_SSL_CAPABLE_ERROR;\n}\n\n#if defined(LWS_WITH_ACME)\n/*\n * mbedtls doesn't support SAN for cert creation.  So we use a known-good\n * tls-sni-01 cert from OpenSSL that worked on Let's Encrypt, and just replace\n * the pubkey n part and the signature part.\n *\n * This will need redoing for tls-sni-02...\n */\n\nstatic uint8_t ss_cert_leadin[] = {\n\t0x30, 0x82,\n\t  0x05, 0x56, /* total length: LEN1 (+2 / +3) (correct for 513 + 512)*/\n\n\t0x30, 0x82, /* length: LEN2  (+6 / +7) (correct for 513) */\n\t\t0x03, 0x3e,\n\n\t/* addition: v3 cert (+5 bytes)*/\n\t0xa0, 0x03,\n\t\t0x02, 0x01, 0x02,\n\n\t0x02, 0x01, 0x01,\n\t0x30, 0x0d, 0x06, 0x09, 0x2a,\n\t0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x3f,\n\t0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x47,\n\t0x42, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0b,\n\t0x73, 0x6f, 0x6d, 0x65, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x6e, 0x79, 0x31,\n\t0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x11, 0x74, 0x65,\n\t0x6d, 0x70, 0x2e, 0x61, 0x63, 0x6d, 0x65, 0x2e, 0x69, 0x6e, 0x76, 0x61,\n\t0x6c, 0x69, 0x64, 0x30, 0x1e, 0x17, 0x0d,\n\n\t/* from 2017-10-29 ... */\n\t0x31, 0x37, 0x31, 0x30, 0x32, 0x39, 0x31, 0x31, 0x34, 0x39, 0x34, 0x35,\n\t0x5a, 0x17, 0x0d,\n\n\t/* thru 2049-10-29 we immediately discard the private key, no worries */\n\t0x34, 0x39, 0x31, 0x30, 0x32, 0x39, 0x31, 0x32, 0x34, 0x39, 0x34, 0x35,\n\t0x5a,\n\n\t0x30, 0x3f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,\n\t0x02, 0x47, 0x42, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x0a,\n\t0x0c, 0x0b, 0x73, 0x6f, 0x6d, 0x65, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x6e,\n\t0x79, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x11,\n\t0x74, 0x65, 0x6d, 0x70, 0x2e, 0x61, 0x63, 0x6d, 0x65, 0x2e, 0x69, 0x6e,\n\t0x76, 0x61, 0x6c, 0x69, 0x64, 0x30,\n\n\t0x82,\n\t\t0x02, 0x22, /* LEN3 (+C3 / C4) */\n\t0x30, 0x0d, 0x06,\n\t0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00,\n\t0x03,\n\n\t0x82,\n\t\t0x02, 0x0f, /* LEN4 (+D6 / D7) */\n\n\t0x00, 0x30, 0x82,\n\n\t\t0x02, 0x0a, /* LEN5 (+ DB / DC) */\n\n\t0x02, 0x82,\n\n\t//0x02, 0x01, /* length of n in bytes (including leading 00 if any) */\n\t},\n\n\t/* 1 + (keybits / 8) bytes N */\n\n\tss_cert_san_leadin[] = {\n\t\t/* e - fixed */\n\t\t0x02, 0x03, 0x01, 0x00, 0x01,\n\n\t\t0xa3, 0x5d, 0x30, 0x5b, 0x30, 0x59, 0x06, 0x03, 0x55, 0x1d,\n\t\t0x11, 0x04, 0x52, 0x30, 0x50, /* <-- SAN length + 2 */\n\n\t\t0x82, 0x4e, /* <-- SAN length */\n\t},\n\n\t/* 78 bytes of SAN (tls-sni-01)\n\t0x61, 0x64, 0x34, 0x31, 0x61, 0x66, 0x62, 0x65, 0x30, 0x63, 0x61, 0x34,\n\t0x36, 0x34, 0x32, 0x66, 0x30, 0x61, 0x34, 0x34, 0x39, 0x64, 0x39, 0x63,\n\t0x61, 0x37, 0x36, 0x65, 0x62, 0x61, 0x61, 0x62, 0x2e, 0x32, 0x38, 0x39,\n\t0x34, 0x64, 0x34, 0x31, 0x36, 0x63, 0x39, 0x38, 0x33, 0x66, 0x31, 0x32,\n\t0x65, 0x64, 0x37, 0x33, 0x31, 0x61, 0x33, 0x30, 0x66, 0x35, 0x63, 0x34,\n\t0x34, 0x37, 0x37, 0x66, 0x65, 0x2e, 0x61, 0x63, 0x6d, 0x65, 0x2e, 0x69,\n\t0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, */\n\n\t/* end of LEN2 area */\n\n\tss_cert_sig_leadin[] = {\n\t\t/* it's saying that the signature is SHA256 + RSA */\n\t\t0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,\n\t\t0x01, 0x01, 0x0b, 0x05, 0x00, 0x03,\n\n\t\t0x82,\n\t\t\t0x02, 0x01,\n\t\t0x00,\n\t};\n\n\t/* (keybits / 8) bytes signature to end of LEN1 area */\n\n#define SAN_A_LENGTH 78\n\nLWS_VISIBLE int\nlws_tls_acme_sni_cert_create(struct lws_vhost *vhost, const char *san_a,\n\t\t\t     const char *san_b)\n{\n\tint buflen = 0x560;\n\tuint8_t *buf = lws_malloc(buflen, \"tmp cert buf\"), *p = buf, *pkey_asn1;\n\tstruct lws_genrsa_ctx ctx;\n\tstruct lws_genrsa_elements el;\n\tuint8_t digest[32];\n\tstruct lws_genhash_ctx hash_ctx;\n\tint pkey_asn1_len = 3 * 1024;\n\tint n, m, keybits = lws_plat_recommended_rsa_bits(), adj;\n\n\tif (!buf)\n\t\treturn 1;\n\n\tn = lws_genrsa_new_keypair(vhost->context, &ctx, &el, keybits);\n\tif (n < 0) {\n\t\tlws_jwk_destroy_genrsa_elements(&el);\n\t\tgoto bail1;\n\t}\n\n\tn = sizeof(ss_cert_leadin);\n\tmemcpy(p, ss_cert_leadin, n);\n\tp += n;\n\n\tadj = (0x0556 - 0x401) + (keybits / 4) + 1;\n\tbuf[2] = adj >> 8;\n\tbuf[3] = adj & 0xff;\n\n\tadj = (0x033e - 0x201) + (keybits / 8) + 1;\n\tbuf[6] = adj >> 8;\n\tbuf[7] = adj & 0xff;\n\n\tadj = (0x0222 - 0x201) + (keybits / 8) + 1;\n\tbuf[0xc3] = adj >> 8;\n\tbuf[0xc4] = adj & 0xff;\n\n\tadj = (0x020f - 0x201) + (keybits / 8) + 1;\n\tbuf[0xd6] = adj >> 8;\n\tbuf[0xd7] = adj & 0xff;\n\n\tadj = (0x020a - 0x201) + (keybits / 8) + 1;\n\tbuf[0xdb] = adj >> 8;\n\tbuf[0xdc] = adj & 0xff;\n\n\t*p++ = ((keybits / 8) + 1) >> 8;\n\t*p++ = ((keybits / 8) + 1) & 0xff;\n\n\t/* we need to drop 1 + (keybits / 8) bytes of n in here, 00 + key */\n\n\t*p++ = 0x00;\n\tmemcpy(p, el.e[JWK_KEY_N].buf, el.e[JWK_KEY_N].len);\n\tp += el.e[JWK_KEY_N].len;\n\n\tmemcpy(p, ss_cert_san_leadin, sizeof(ss_cert_san_leadin));\n\tp += sizeof(ss_cert_san_leadin);\n\n\t/* drop in 78 bytes of san_a */\n\n\tmemcpy(p, san_a, SAN_A_LENGTH);\n\tp += SAN_A_LENGTH;\n\tmemcpy(p, ss_cert_sig_leadin, sizeof(ss_cert_sig_leadin));\n\n\tp[17] = ((keybits / 8) + 1) >> 8;\n\tp[18] = ((keybits / 8) + 1) & 0xff;\n\n\tp += sizeof(ss_cert_sig_leadin);\n\n\t/* hash the cert plaintext */\n\n\tif (lws_genhash_init(&hash_ctx, LWS_GENHASH_TYPE_SHA256))\n\t\tgoto bail2;\n\n\tif (lws_genhash_update(&hash_ctx, buf, lws_ptr_diff(p, buf))) {\n\t\tlws_genhash_destroy(&hash_ctx, NULL);\n\n\t\tgoto bail2;\n\t}\n\tif (lws_genhash_destroy(&hash_ctx, digest))\n\t\tgoto bail2;\n\n\t/* sign the hash */\n\n\tn = lws_genrsa_public_sign(&ctx, digest, LWS_GENHASH_TYPE_SHA256, p,\n\t\t\t\t buflen - lws_ptr_diff(p, buf));\n\tif (n < 0)\n\t\tgoto bail2;\n\tp += n;\n\n\tpkey_asn1 = lws_malloc(pkey_asn1_len, \"mbed crt tmp\");\n\tif (!pkey_asn1)\n\t\tgoto bail2;\n\n\tm = lws_genrsa_render_pkey_asn1(&ctx, 1, pkey_asn1, pkey_asn1_len);\n\tif (m < 0) {\n\t\tlws_free(pkey_asn1);\n\t\tgoto bail2;\n\t}\n\n//\tlwsl_hexdump_level(LLL_DEBUG, buf, lws_ptr_diff(p, buf));\n\tn = SSL_CTX_use_certificate_ASN1(vhost->tls.ssl_ctx,\n\t\t\t\t lws_ptr_diff(p, buf), buf);\n\tif (n != 1) {\n\t\tlws_free(pkey_asn1);\n\t\tlwsl_err(\"%s: generated cert failed to load 0x%x\\n\",\n\t\t\t\t__func__, -n);\n\t} else {\n\t\t//lwsl_debug(\"private key\\n\");\n\t\t//lwsl_hexdump_level(LLL_DEBUG, pkey_asn1, n);\n\n\t\t/* and to use our generated private key */\n\t\tn = SSL_CTX_use_PrivateKey_ASN1(0, vhost->tls.ssl_ctx, pkey_asn1, m);\n\t\tlws_free(pkey_asn1);\n\t\tif (n != 1) {\n\t\t\tlwsl_err(\"%s: SSL_CTX_use_PrivateKey_ASN1 failed\\n\",\n\t\t\t\t    __func__);\n\t\t}\n\t}\n\n\tlws_genrsa_destroy(&ctx);\n\tlws_jwk_destroy_genrsa_elements(&el);\n\n\tlws_free(buf);\n\n\treturn n != 1;\n\nbail2:\n\tlws_genrsa_destroy(&ctx);\n\tlws_jwk_destroy_genrsa_elements(&el);\nbail1:\n\tlws_free(buf);\n\n\treturn -1;\n}\n\nvoid\nlws_tls_acme_sni_cert_destroy(struct lws_vhost *vhost)\n{\n}\n\n#if defined(LWS_WITH_JWS)\nstatic int\n_rngf(void *context, unsigned char *buf, size_t len)\n{\n\tif ((size_t)lws_get_random(context, buf, len) == len)\n\t\treturn 0;\n\n\treturn -1;\n}\n\nstatic const char *x5[] = { \"C\", \"ST\", \"L\", \"O\", \"CN\" };\n\n/*\n * CSR is output formatted as b64url(DER)\n * Private key is output as a PEM in memory\n */\nLWS_VISIBLE LWS_EXTERN int\nlws_tls_acme_sni_csr_create(struct lws_context *context, const char *elements[],\n\t\t\t    uint8_t *dcsr, size_t csr_len, char **privkey_pem,\n\t\t\t    size_t *privkey_len)\n{\n\tmbedtls_x509write_csr csr;\n\tmbedtls_pk_context mpk;\n\tint buf_size = 4096, n;\n\tchar subject[200], *p = subject, *end = p + sizeof(subject) - 1;\n\tuint8_t *buf = malloc(buf_size); /* malloc because given to user code */\n\n\tif (!buf)\n\t\treturn -1;\n\n\tmbedtls_x509write_csr_init(&csr);\n\n\tmbedtls_pk_init(&mpk);\n\tif (mbedtls_pk_setup(&mpk, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA))) {\n\t\tlwsl_notice(\"%s: pk_setup failed\\n\", __func__);\n\t\tgoto fail;\n\t}\n\n\tn = mbedtls_rsa_gen_key(mbedtls_pk_rsa(mpk), _rngf, context,\n\t\t\t\tlws_plat_recommended_rsa_bits(), 65537);\n\tif (n) {\n\t\tlwsl_notice(\"%s: failed to generate keys\\n\", __func__);\n\n\t\tgoto fail1;\n\t}\n\n\t/* subject must be formatted like \"C=TW,O=warmcat,CN=myserver\" */\n\n\tfor (n = 0; n < (int)LWS_ARRAY_SIZE(x5); n++) {\n\t\tif (p != subject)\n\t\t\t*p++ = ',';\n\t\tif (elements[n])\n\t\t\tp += lws_snprintf(p, end - p, \"%s=%s\", x5[n],\n\t\t\t\t\t  elements[n]);\n\t}\n\n\tif (mbedtls_x509write_csr_set_subject_name(&csr, subject))\n\t\tgoto fail1;\n\n\tmbedtls_x509write_csr_set_key(&csr, &mpk);\n\tmbedtls_x509write_csr_set_md_alg(&csr, MBEDTLS_MD_SHA256);\n\n\t/*\n\t * data is written at the end of the buffer! Use the\n\t * return value to determine where you should start\n\t * using the buffer\n\t */\n\tn = mbedtls_x509write_csr_der(&csr, buf, buf_size, _rngf, context);\n\tif (n < 0) {\n\t\tlwsl_notice(\"%s: write csr der failed\\n\", __func__);\n\t\tgoto fail1;\n\t}\n\n\t/* we have it in DER, we need it in b64URL */\n\n\tn = lws_jws_base64_enc((char *)(buf + buf_size) - n, n,\n\t\t\t       (char *)dcsr, csr_len);\n\tif (n < 0)\n\t\tgoto fail1;\n\n\t/*\n\t * okay, the CSR is done, last we need the private key in PEM\n\t * re-use the DER CSR buf as the result buffer since we cn do it in\n\t * one step\n\t */\n\n\tif (mbedtls_pk_write_key_pem(&mpk, buf, buf_size)) {\n\t\tlwsl_notice(\"write key pem failed\\n\");\n\t\tgoto fail1;\n\t}\n\n\t*privkey_pem = (char *)buf;\n\t*privkey_len = strlen((const char *)buf);\n\n\tmbedtls_pk_free(&mpk);\n\tmbedtls_x509write_csr_free(&csr);\n\n\treturn n;\n\nfail1:\n\tmbedtls_pk_free(&mpk);\nfail:\n\tmbedtls_x509write_csr_free(&csr);\n\tfree(buf);\n\n\treturn -1;\n}\n#endif\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/ssl.c",
    "content": "/*\n * libwebsockets - mbedTLS-specific lws apis\n *\n * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n#include <mbedtls/oid.h>\n\nvoid\nlws_ssl_elaborate_error(void)\n{\n}\n\nint\nlws_context_init_ssl_library(const struct lws_context_creation_info *info)\n{\n\tlwsl_info(\" Compiled with MbedTLS support\\n\");\n\n\tif (!lws_check_opt(info->options, LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT))\n\t\tlwsl_info(\" SSL disabled: no LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT\\n\");\n\n\treturn 0;\n}\n\nLWS_VISIBLE void\nlws_ssl_destroy(struct lws_vhost *vhost)\n{\n\tif (!lws_check_opt(vhost->context->options,\n\t\t\t   LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT))\n\t\treturn;\n\n\tif (vhost->tls.ssl_ctx)\n\t\tSSL_CTX_free(vhost->tls.ssl_ctx);\n\tif (!vhost->tls.user_supplied_ssl_ctx && vhost->tls.ssl_client_ctx)\n\t\tSSL_CTX_free(vhost->tls.ssl_client_ctx);\n\n\tif (vhost->tls.x509_client_CA)\n\t\tX509_free(vhost->tls.x509_client_CA);\n}\n\nLWS_VISIBLE int\nlws_ssl_capable_read(struct lws *wsi, unsigned char *buf, int len)\n{\n\tstruct lws_context *context = wsi->context;\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tint n = 0, m;\n\n\tif (!wsi->tls.ssl)\n\t\treturn lws_ssl_capable_read_no_ssl(wsi, buf, len);\n\n\tlws_stats_atomic_bump(context, pt, LWSSTATS_C_API_READ, 1);\n\n\terrno = 0;\n\tn = SSL_read(wsi->tls.ssl, buf, len);\n#if defined(LWS_WITH_ESP32)\n\tif (!n && errno == ENOTCONN) {\n\t\tlwsl_debug(\"%p: SSL_read ENOTCONN\\n\", wsi);\n\t\treturn LWS_SSL_CAPABLE_ERROR;\n\t}\n#endif\n#if defined(LWS_WITH_STATS)\n\tif (!wsi->seen_rx) {\n                lws_stats_atomic_bump(wsi->context, pt,\n                \t\t      LWSSTATS_MS_SSL_RX_DELAY,\n\t\t\t\ttime_in_microseconds() - wsi->accept_start_us);\n                lws_stats_atomic_bump(wsi->context, pt,\n                \t\t      LWSSTATS_C_SSL_CONNS_HAD_RX, 1);\n\t\twsi->seen_rx = 1;\n\t}\n#endif\n\n\n\tlwsl_debug(\"%p: SSL_read says %d\\n\", wsi, n);\n\t/* manpage: returning 0 means connection shut down */\n\tif (!n) {\n\t\twsi->socket_is_permanently_unusable = 1;\n\n\t\treturn LWS_SSL_CAPABLE_ERROR;\n\t}\n\n\tif (n < 0) {\n\t\tm = SSL_get_error(wsi->tls.ssl, n);\n\t\tlwsl_debug(\"%p: ssl err %d errno %d\\n\", wsi, m, errno);\n\t\tif (m == SSL_ERROR_ZERO_RETURN ||\n\t\t    m == SSL_ERROR_SYSCALL)\n\t\t\treturn LWS_SSL_CAPABLE_ERROR;\n\n\t\tif (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl)) {\n\t\t\tlwsl_debug(\"%s: WANT_READ\\n\", __func__);\n\t\t\tlwsl_debug(\"%p: LWS_SSL_CAPABLE_MORE_SERVICE\\n\", wsi);\n\t\t\treturn LWS_SSL_CAPABLE_MORE_SERVICE;\n\t\t}\n\t\tif (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl)) {\n\t\t\tlwsl_debug(\"%s: WANT_WRITE\\n\", __func__);\n\t\t\tlwsl_debug(\"%p: LWS_SSL_CAPABLE_MORE_SERVICE\\n\", wsi);\n\t\t\treturn LWS_SSL_CAPABLE_MORE_SERVICE;\n\t\t}\n\t\twsi->socket_is_permanently_unusable = 1;\n\n\t\treturn LWS_SSL_CAPABLE_ERROR;\n\t}\n\n\tlws_stats_atomic_bump(context, pt, LWSSTATS_B_READ, n);\n\n\tif (wsi->vhost)\n\t\twsi->vhost->conn_stats.rx += n;\n\n\t/*\n\t * if it was our buffer that limited what we read,\n\t * check if SSL has additional data pending inside SSL buffers.\n\t *\n\t * Because these won't signal at the network layer with POLLIN\n\t * and if we don't realize, this data will sit there forever\n\t */\n\tif (n != len)\n\t\tgoto bail;\n\tif (!wsi->tls.ssl)\n\t\tgoto bail;\n\n\tif (!SSL_pending(wsi->tls.ssl))\n\t\tgoto bail;\n\n\tif (wsi->tls.pending_read_list_next)\n\t\treturn n;\n\tif (wsi->tls.pending_read_list_prev)\n\t\treturn n;\n\tif (pt->tls.pending_read_list == wsi)\n\t\treturn n;\n\n\t/* add us to the linked list of guys with pending ssl */\n\tif (pt->tls.pending_read_list)\n\t\tpt->tls.pending_read_list->tls.pending_read_list_prev = wsi;\n\n\twsi->tls.pending_read_list_next = pt->tls.pending_read_list;\n\twsi->tls.pending_read_list_prev = NULL;\n\tpt->tls.pending_read_list = wsi;\n\n\treturn n;\nbail:\n\tlws_ssl_remove_wsi_from_buffered_list(wsi);\n\n\treturn n;\n}\n\nLWS_VISIBLE int\nlws_ssl_pending(struct lws *wsi)\n{\n\tif (!wsi->tls.ssl)\n\t\treturn 0;\n\n\treturn SSL_pending(wsi->tls.ssl);\n}\n\nLWS_VISIBLE int\nlws_ssl_capable_write(struct lws *wsi, unsigned char *buf, int len)\n{\n\tint n, m;\n\n\tif (!wsi->tls.ssl)\n\t\treturn lws_ssl_capable_write_no_ssl(wsi, buf, len);\n\n\tn = SSL_write(wsi->tls.ssl, buf, len);\n\tif (n > 0)\n\t\treturn n;\n\n\tm = SSL_get_error(wsi->tls.ssl, n);\n\tif (m != SSL_ERROR_SYSCALL) {\n\t\tif (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl)) {\n\t\t\tlwsl_notice(\"%s: want read\\n\", __func__);\n\n\t\t\treturn LWS_SSL_CAPABLE_MORE_SERVICE;\n\t\t}\n\n\t\tif (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl)) {\n\t\t\tlws_set_blocking_send(wsi);\n\t\t\tlwsl_notice(\"%s: want write\\n\", __func__);\n\n\t\t\treturn LWS_SSL_CAPABLE_MORE_SERVICE;\n\t\t}\n\t}\n\n\tlwsl_debug(\"%s failed: %d\\n\",__func__, m);\n\twsi->socket_is_permanently_unusable = 1;\n\n\treturn LWS_SSL_CAPABLE_ERROR;\n}\n\nint openssl_SSL_CTX_private_data_index;\n\nvoid\nlws_ssl_info_callback(const SSL *ssl, int where, int ret)\n{\n\tstruct lws *wsi;\n\tstruct lws_context *context;\n\tstruct lws_ssl_info si;\n\n\tcontext = (struct lws_context *)SSL_CTX_get_ex_data(\n\t\t\t\t\tSSL_get_SSL_CTX(ssl),\n\t\t\t\t\topenssl_SSL_CTX_private_data_index);\n\tif (!context)\n\t\treturn;\n\twsi = wsi_from_fd(context, SSL_get_fd(ssl));\n\tif (!wsi)\n\t\treturn;\n\n\tif (!(where & wsi->vhost->tls.ssl_info_event_mask))\n\t\treturn;\n\n\tsi.where = where;\n\tsi.ret = ret;\n\n\tif (user_callback_handle_rxflow(wsi->protocol->callback,\n\t\t\t\t\twsi, LWS_CALLBACK_SSL_INFO,\n\t\t\t\t\twsi->user_space, &si, 0))\n\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_KILLED_BY_SSL_INFO, -1);\n}\n\n\nLWS_VISIBLE int\nlws_ssl_close(struct lws *wsi)\n{\n\tlws_sockfd_type n;\n\n\tif (!wsi->tls.ssl)\n\t\treturn 0; /* not handled */\n\n#if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK)\n\t/* kill ssl callbacks, becausse we will remove the fd from the\n\t * table linking it to the wsi\n\t */\n\tif (wsi->vhost->tls.ssl_info_event_mask)\n\t\tSSL_set_info_callback(wsi->tls.ssl, NULL);\n#endif\n\n\tn = SSL_get_fd(wsi->tls.ssl);\n\tif (!wsi->socket_is_permanently_unusable)\n\t\tSSL_shutdown(wsi->tls.ssl);\n\tcompatible_close(n);\n\tSSL_free(wsi->tls.ssl);\n\twsi->tls.ssl = NULL;\n\n\tif (!lwsi_role_client(wsi) &&\n\t    wsi->context->simultaneous_ssl_restriction &&\n\t    wsi->context->simultaneous_ssl-- ==\n\t\t\t    wsi->context->simultaneous_ssl_restriction)\n\t\t/* we made space and can do an accept */\n\t\tlws_gate_accepts(wsi->context, 1);\n\n#if defined(LWS_WITH_STATS)\n\twsi->context->updated = 1;\n#endif\n\n\treturn 1; /* handled */\n}\n\nvoid\nlws_ssl_SSL_CTX_destroy(struct lws_vhost *vhost)\n{\n\tif (vhost->tls.ssl_ctx)\n\t\tSSL_CTX_free(vhost->tls.ssl_ctx);\n\n\tif (!vhost->tls.user_supplied_ssl_ctx && vhost->tls.ssl_client_ctx)\n\t\tSSL_CTX_free(vhost->tls.ssl_client_ctx);\n#if defined(LWS_WITH_ACME)\n\tlws_tls_acme_sni_cert_destroy(vhost);\n#endif\n}\n\nvoid\nlws_ssl_context_destroy(struct lws_context *context)\n{\n}\n\nlws_tls_ctx *\nlws_tls_ctx_from_wsi(struct lws *wsi)\n{\n\tif (!wsi->tls.ssl)\n\t\treturn NULL;\n\n\treturn SSL_get_SSL_CTX(wsi->tls.ssl);\n}\n\nenum lws_ssl_capable_status\n__lws_tls_shutdown(struct lws *wsi)\n{\n\tint n = SSL_shutdown(wsi->tls.ssl);\n\n\tlwsl_debug(\"SSL_shutdown=%d for fd %d\\n\", n, wsi->desc.sockfd);\n\n\tswitch (n) {\n\tcase 1: /* successful completion */\n\t\tn = shutdown(wsi->desc.sockfd, SHUT_WR);\n\t\treturn LWS_SSL_CAPABLE_DONE;\n\n\tcase 0: /* needs a retry */\n\t\t__lws_change_pollfd(wsi, 0, LWS_POLLIN);\n\t\treturn LWS_SSL_CAPABLE_MORE_SERVICE;\n\n\tdefault: /* fatal error, or WANT */\n\t\tn = SSL_get_error(wsi->tls.ssl, n);\n\t\tif (n != SSL_ERROR_SYSCALL && n != SSL_ERROR_SSL) {\n\t\t\tif (SSL_want_read(wsi->tls.ssl)) {\n\t\t\t\tlwsl_debug(\"(wants read)\\n\");\n\t\t\t\t__lws_change_pollfd(wsi, 0, LWS_POLLIN);\n\t\t\t\treturn LWS_SSL_CAPABLE_MORE_SERVICE_READ;\n\t\t\t}\n\t\t\tif (SSL_want_write(wsi->tls.ssl)) {\n\t\t\t\tlwsl_debug(\"(wants write)\\n\");\n\t\t\t\t__lws_change_pollfd(wsi, 0, LWS_POLLOUT);\n\t\t\t\treturn LWS_SSL_CAPABLE_MORE_SERVICE_WRITE;\n\t\t\t}\n\t\t}\n\t\treturn LWS_SSL_CAPABLE_ERROR;\n\t}\n}\n\nstatic time_t\nlws_tls_mbedtls_time_to_unix(mbedtls_x509_time *xtime)\n{\n\tstruct tm t;\n\n\tif (!xtime || !xtime->year || xtime->year < 0)\n\t\treturn (time_t)(long long)-1;\n\n\tmemset(&t, 0, sizeof(t));\n\n\tt.tm_year = xtime->year - 1900;\n\tt.tm_mon = xtime->mon - 1; /* mbedtls months are 1+, tm are 0+ */\n\tt.tm_mday = xtime->day - 1; /* mbedtls days are 1+, tm are 0+ */\n\tt.tm_hour = xtime->hour;\n\tt.tm_min = xtime->min;\n\tt.tm_sec = xtime->sec;\n\tt.tm_isdst = -1;\n\n\treturn mktime(&t);\n}\n\nstatic int\nlws_tls_mbedtls_get_x509_name(mbedtls_x509_name *name,\n\t\t\t      union lws_tls_cert_info_results *buf, size_t len)\n{\n\twhile (name) {\n\t\tif (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid)) {\n\t\t\tname = name->next;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (len - 1 < name->val.len)\n\t\t\treturn -1;\n\n\t\tmemcpy(&buf->ns.name[0], name->val.p, name->val.len);\n\t\tbuf->ns.name[name->val.len] = '\\0';\n\t\tbuf->ns.len = name->val.len;\n\n\t\treturn 0;\n\t}\n\n\treturn -1;\n}\n\nstatic int\nlws_tls_mbedtls_cert_info(mbedtls_x509_crt *x509, enum lws_tls_cert_info type,\n\t\t\t  union lws_tls_cert_info_results *buf, size_t len)\n{\n\tif (!x509)\n\t\treturn -1;\n\n\tswitch (type) {\n\tcase LWS_TLS_CERT_INFO_VALIDITY_FROM:\n\t\tbuf->time = lws_tls_mbedtls_time_to_unix(&x509->valid_from);\n\t\tif (buf->time == (time_t)(long long)-1)\n\t\t\treturn -1;\n\t\tbreak;\n\n\tcase LWS_TLS_CERT_INFO_VALIDITY_TO:\n\t\tbuf->time = lws_tls_mbedtls_time_to_unix(&x509->valid_to);\n\t\tif (buf->time == (time_t)(long long)-1)\n\t\t\treturn -1;\n\t\tbreak;\n\n\tcase LWS_TLS_CERT_INFO_COMMON_NAME:\n\t\treturn lws_tls_mbedtls_get_x509_name(&x509->subject, buf, len);\n\n\tcase LWS_TLS_CERT_INFO_ISSUER_NAME:\n\t\treturn lws_tls_mbedtls_get_x509_name(&x509->issuer, buf, len);\n\n\tcase LWS_TLS_CERT_INFO_USAGE:\n\t\tbuf->usage = x509->key_usage;\n\t\tbreak;\n\n\tcase LWS_TLS_CERT_INFO_OPAQUE_PUBLIC_KEY:\n\t{\n\t\tchar *p = buf->ns.name;\n\t\tsize_t r = len, u;\n\n\t\tswitch (mbedtls_pk_get_type(&x509->pk)) {\n\t\tcase MBEDTLS_PK_RSA:\n\t\t{\n\t\t\tmbedtls_rsa_context *rsa = mbedtls_pk_rsa(x509->pk);\n\n\t\t\tif (mbedtls_mpi_write_string(&rsa->N, 16, p, r, &u))\n\t\t\t\treturn -1;\n\t\t\tr -= u;\n\t\t\tp += u;\n\t\t\tif (mbedtls_mpi_write_string(&rsa->E, 16, p, r, &u))\n\t\t\t\treturn -1;\n\n\t\t\tp += u;\n\t\t\tbuf->ns.len = lws_ptr_diff(p, buf->ns.name);\n\t\t\tbreak;\n\t\t}\n\t\tcase MBEDTLS_PK_ECKEY:\n\t\t{\n\t\t\tmbedtls_ecp_keypair *ecp = mbedtls_pk_ec(x509->pk);\n\n\t\t\tif (mbedtls_mpi_write_string(&ecp->Q.X, 16, p, r, &u))\n\t\t\t\t return -1;\n\t\t\tr -= u;\n\t\t\tp += u;\n\t\t\tif (mbedtls_mpi_write_string(&ecp->Q.Y, 16, p, r, &u))\n\t\t\t\t return -1;\n\t\t\tr -= u;\n\t\t\tp += u;\n\t\t\tif (mbedtls_mpi_write_string(&ecp->Q.Z, 16, p, r, &u))\n\t\t\t\t return -1;\n\t\t\tp += u;\n\t\t\tbuf->ns.len = lws_ptr_diff(p, buf->ns.name);\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tlwsl_notice(\"%s: x509 has unsupported pubkey type %d\\n\",\n\t\t\t\t    __func__,\n\t\t\t\t    mbedtls_pk_get_type(&x509->pk));\n\n\t\t\treturn -1;\n\t\t}\n\t\tbreak;\n\t}\n\n\tdefault:\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\nLWS_VISIBLE LWS_EXTERN int\nlws_tls_vhost_cert_info(struct lws_vhost *vhost, enum lws_tls_cert_info type,\n\t\t        union lws_tls_cert_info_results *buf, size_t len)\n{\n\tmbedtls_x509_crt *x509 = ssl_ctx_get_mbedtls_x509_crt(vhost->tls.ssl_ctx);\n\n\treturn lws_tls_mbedtls_cert_info(x509, type, buf, len);\n}\n\nLWS_VISIBLE int\nlws_tls_peer_cert_info(struct lws *wsi, enum lws_tls_cert_info type,\n\t\t       union lws_tls_cert_info_results *buf, size_t len)\n{\n\tmbedtls_x509_crt *x509;\n\n\twsi = lws_get_network_wsi(wsi);\n\n\tx509 = ssl_get_peer_mbedtls_x509_crt(wsi->tls.ssl);\n\n\tif (!x509)\n\t\treturn -1;\n\n\tswitch (type) {\n\tcase LWS_TLS_CERT_INFO_VERIFIED:\n\t\tbuf->verified = SSL_get_verify_result(wsi->tls.ssl) == X509_V_OK;\n\t\treturn 0;\n\tdefault:\n\t\treturn lws_tls_mbedtls_cert_info(x509, type, buf, len);\n\t}\n\n\treturn -1;\n}\n\nstatic int\ntops_fake_POLLIN_for_buffered_mbedtls(struct lws_context_per_thread *pt)\n{\n\treturn lws_tls_fake_POLLIN_for_buffered(pt);\n}\n\nstatic int\ntops_periodic_housekeeping_mbedtls(struct lws_context *context, time_t now)\n{\n\tint n;\n\n\tn = lws_compare_time_t(context, now, context->tls.last_cert_check_s);\n\tif ((!context->tls.last_cert_check_s || n > (24 * 60 * 60)) &&\n\t    !lws_tls_check_all_cert_lifetimes(context))\n\t\tcontext->tls.last_cert_check_s = now;\n\n\treturn 0;\n}\n\nconst struct lws_tls_ops tls_ops_mbedtls = {\n\t/* fake_POLLIN_for_buffered */\ttops_fake_POLLIN_for_buffered_mbedtls,\n\t/* periodic_housekeeping */\ttops_periodic_housekeeping_mbedtls,\n};\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl3.h",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef _SSL3_H_\n#define _SSL3_H_\n\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n\n# define SSL3_AD_CLOSE_NOTIFY             0\n# define SSL3_AD_UNEXPECTED_MESSAGE      10/* fatal */\n# define SSL3_AD_BAD_RECORD_MAC          20/* fatal */\n# define SSL3_AD_DECOMPRESSION_FAILURE   30/* fatal */\n# define SSL3_AD_HANDSHAKE_FAILURE       40/* fatal */\n# define SSL3_AD_NO_CERTIFICATE          41\n# define SSL3_AD_BAD_CERTIFICATE         42\n# define SSL3_AD_UNSUPPORTED_CERTIFICATE 43\n# define SSL3_AD_CERTIFICATE_REVOKED     44\n# define SSL3_AD_CERTIFICATE_EXPIRED     45\n# define SSL3_AD_CERTIFICATE_UNKNOWN     46\n# define SSL3_AD_ILLEGAL_PARAMETER       47/* fatal */\n\n# define SSL3_AL_WARNING                  1\n# define SSL3_AL_FATAL                    2\n\n#define SSL3_VERSION                 0x0300\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_cert.h",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef _SSL_CERT_H_\n#define _SSL_CERT_H_\n\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n\n#include \"ssl_types.h\"\n\n/**\n * @brief create a certification object include private key object according to input certification\n *\n * @param ic - input certification point\n *\n * @return certification object point\n */\nCERT *__ssl_cert_new(CERT *ic);\n\n/**\n * @brief create a certification object include private key object\n *\n * @param none\n *\n * @return certification object point\n */\nCERT* ssl_cert_new(void);\n\n/**\n * @brief free a certification object\n *\n * @param cert - certification object point\n *\n * @return none\n */\nvoid ssl_cert_free(CERT *cert);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_code.h",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef _SSL_CODE_H_\n#define _SSL_CODE_H_\n\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n\n#include \"ssl3.h\"\n#include \"tls1.h\"\n#include \"x509_vfy.h\"\n\n/* Used in SSL_set_shutdown()/SSL_get_shutdown(); */\n# define SSL_SENT_SHUTDOWN       1\n# define SSL_RECEIVED_SHUTDOWN   2\n\n# define SSL_VERIFY_NONE                 0x00\n# define SSL_VERIFY_PEER                 0x01\n# define SSL_VERIFY_FAIL_IF_NO_PEER_CERT 0x02\n# define SSL_VERIFY_CLIENT_ONCE          0x04\n\n/*\n * The following 3 states are kept in ssl->rlayer.rstate when reads fail, you\n * should not need these\n */\n# define SSL_ST_READ_HEADER                      0xF0\n# define SSL_ST_READ_BODY                        0xF1\n# define SSL_ST_READ_DONE                        0xF2\n\n# define SSL_NOTHING            1\n# define SSL_WRITING            2\n# define SSL_READING            3\n# define SSL_X509_LOOKUP        4\n# define SSL_ASYNC_PAUSED       5\n# define SSL_ASYNC_NO_JOBS      6\n\n\n# define SSL_ERROR_NONE                  0\n# define SSL_ERROR_SSL                   1\n# define SSL_ERROR_WANT_READ             2\n# define SSL_ERROR_WANT_WRITE            3\n# define SSL_ERROR_WANT_X509_LOOKUP      4\n# define SSL_ERROR_SYSCALL               5/* look at error stack/return value/errno */\n# define SSL_ERROR_ZERO_RETURN           6\n# define SSL_ERROR_WANT_CONNECT          7\n# define SSL_ERROR_WANT_ACCEPT           8\n# define SSL_ERROR_WANT_ASYNC            9\n# define SSL_ERROR_WANT_ASYNC_JOB       10\n\n/* Message flow states */\ntypedef enum {\n    /* No handshake in progress */\n    MSG_FLOW_UNINITED,\n    /* A permanent error with this connection */\n    MSG_FLOW_ERROR,\n    /* We are about to renegotiate */\n    MSG_FLOW_RENEGOTIATE,\n    /* We are reading messages */\n    MSG_FLOW_READING,\n    /* We are writing messages */\n    MSG_FLOW_WRITING,\n    /* Handshake has finished */\n    MSG_FLOW_FINISHED\n} MSG_FLOW_STATE;\n\n/* SSL subsystem states */\ntypedef enum {\n    TLS_ST_BEFORE,\n    TLS_ST_OK,\n    DTLS_ST_CR_HELLO_VERIFY_REQUEST,\n    TLS_ST_CR_SRVR_HELLO,\n    TLS_ST_CR_CERT,\n    TLS_ST_CR_CERT_STATUS,\n    TLS_ST_CR_KEY_EXCH,\n    TLS_ST_CR_CERT_REQ,\n    TLS_ST_CR_SRVR_DONE,\n    TLS_ST_CR_SESSION_TICKET,\n    TLS_ST_CR_CHANGE,\n    TLS_ST_CR_FINISHED,\n    TLS_ST_CW_CLNT_HELLO,\n    TLS_ST_CW_CERT,\n    TLS_ST_CW_KEY_EXCH,\n    TLS_ST_CW_CERT_VRFY,\n    TLS_ST_CW_CHANGE,\n    TLS_ST_CW_NEXT_PROTO,\n    TLS_ST_CW_FINISHED,\n    TLS_ST_SW_HELLO_REQ,\n    TLS_ST_SR_CLNT_HELLO,\n    DTLS_ST_SW_HELLO_VERIFY_REQUEST,\n    TLS_ST_SW_SRVR_HELLO,\n    TLS_ST_SW_CERT,\n    TLS_ST_SW_KEY_EXCH,\n    TLS_ST_SW_CERT_REQ,\n    TLS_ST_SW_SRVR_DONE,\n    TLS_ST_SR_CERT,\n    TLS_ST_SR_KEY_EXCH,\n    TLS_ST_SR_CERT_VRFY,\n    TLS_ST_SR_NEXT_PROTO,\n    TLS_ST_SR_CHANGE,\n    TLS_ST_SR_FINISHED,\n    TLS_ST_SW_SESSION_TICKET,\n    TLS_ST_SW_CERT_STATUS,\n    TLS_ST_SW_CHANGE,\n    TLS_ST_SW_FINISHED\n} OSSL_HANDSHAKE_STATE;\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_dbg.h",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef _SSL_DEBUG_H_\n#define _SSL_DEBUG_H_\n\n#include \"platform/ssl_port.h\"\n\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n\n#ifdef CONFIG_OPENSSL_DEBUG_LEVEL\n    #define SSL_DEBUG_LEVEL CONFIG_OPENSSL_DEBUG_LEVEL\n#else\n    #define SSL_DEBUG_LEVEL 0\n#endif\n\n#define SSL_DEBUG_ON  (SSL_DEBUG_LEVEL + 1)\n#define SSL_DEBUG_OFF (SSL_DEBUG_LEVEL - 1)\n\n#ifdef CONFIG_OPENSSL_DEBUG\n    #ifndef SSL_DEBUG_LOG\n        #error \"SSL_DEBUG_LOG is not defined\"\n    #endif\n\n    #ifndef SSL_DEBUG_FL\n        #define SSL_DEBUG_FL \"\\n\"\n    #endif\n\n    #define SSL_SHOW_LOCATION()                         \\\n        SSL_DEBUG_LOG(\"SSL assert : %s %d\\n\",           \\\n            __FILE__, __LINE__)\n\n    #define SSL_DEBUG(level, fmt, ...)                  \\\n    {                                                   \\\n        if (level > SSL_DEBUG_LEVEL) {                  \\\n            SSL_DEBUG_LOG(fmt SSL_DEBUG_FL, ##__VA_ARGS__); \\\n        }                                               \\\n    }\n#else /* CONFIG_OPENSSL_DEBUG */\n    #define SSL_SHOW_LOCATION()\n\n    #define SSL_DEBUG(level, fmt, ...)\n#endif /* CONFIG_OPENSSL_DEBUG */\n\n/**\n * OpenSSL assert function\n *\n * if select \"CONFIG_OPENSSL_ASSERT_DEBUG\", SSL_ASSERT* will show error file name and line\n * if select \"CONFIG_OPENSSL_ASSERT_EXIT\", SSL_ASSERT* will just return error code.\n * if select \"CONFIG_OPENSSL_ASSERT_DEBUG_EXIT\" SSL_ASSERT* will show error file name and line,\n * then return error code.\n * if select \"CONFIG_OPENSSL_ASSERT_DEBUG_BLOCK\", SSL_ASSERT* will show error file name and line,\n * then block here with \"while (1)\"\n *\n * SSL_ASSERT1 may will return \"-1\", so function's return argument is integer.\n * SSL_ASSERT2 may will return \"NULL\", so function's return argument is a point.\n * SSL_ASSERT2 may will return nothing, so function's return argument is \"void\".\n */\n#if defined(CONFIG_OPENSSL_ASSERT_DEBUG)\n    #define SSL_ASSERT1(s)                              \\\n    {                                                   \\\n        if (!(s)) {                                     \\\n            SSL_SHOW_LOCATION();                        \\\n        }                                               \\\n    }\n\n    #define SSL_ASSERT2(s)                              \\\n    {                                                   \\\n        if (!(s)) {                                     \\\n            SSL_SHOW_LOCATION();                        \\\n        }                                               \\\n    }\n\n    #define SSL_ASSERT3(s)                              \\\n    {                                                   \\\n        if (!(s)) {                                     \\\n            SSL_SHOW_LOCATION();                        \\\n        }                                               \\\n    }\n#elif defined(CONFIG_OPENSSL_ASSERT_EXIT)\n    #define SSL_ASSERT1(s)                              \\\n    {                                                   \\\n        if (!(s)) {                                     \\\n            return -1;                                  \\\n        }                                               \\\n    }\n\n    #define SSL_ASSERT2(s)                              \\\n    {                                                   \\\n        if (!(s)) {                                     \\\n            return NULL;                                \\\n        }                                               \\\n    }\n\n    #define SSL_ASSERT3(s)                              \\\n    {                                                   \\\n        if (!(s)) {                                     \\\n            return ;                                    \\\n        }                                               \\\n    }\n#elif defined(CONFIG_OPENSSL_ASSERT_DEBUG_EXIT)\n    #define SSL_ASSERT1(s)                              \\\n    {                                                   \\\n        if (!(s)) {                                     \\\n            SSL_SHOW_LOCATION();                        \\\n            return -1;                                  \\\n        }                                               \\\n    }\n\n    #define SSL_ASSERT2(s)                              \\\n    {                                                   \\\n        if (!(s)) {                                     \\\n            SSL_SHOW_LOCATION();                        \\\n            return NULL;                                \\\n        }                                               \\\n    }\n\n    #define SSL_ASSERT3(s)                              \\\n    {                                                   \\\n        if (!(s)) {                                     \\\n            SSL_SHOW_LOCATION();                        \\\n            return ;                                    \\\n        }                                               \\\n    }\n#elif defined(CONFIG_OPENSSL_ASSERT_DEBUG_BLOCK)\n    #define SSL_ASSERT1(s)                              \\\n    {                                                   \\\n        if (!(s)) {                                     \\\n            SSL_SHOW_LOCATION();                        \\\n            while (1);                                  \\\n        }                                               \\\n    }\n\n    #define SSL_ASSERT2(s)                              \\\n    {                                                   \\\n        if (!(s)) {                                     \\\n            SSL_SHOW_LOCATION();                        \\\n            while (1);                                  \\\n        }                                               \\\n    }\n\n    #define SSL_ASSERT3(s)                              \\\n    {                                                   \\\n        if (!(s)) {                                     \\\n            SSL_SHOW_LOCATION();                        \\\n            while (1);                                  \\\n        }                                               \\\n    }\n#else\n    #define SSL_ASSERT1(s)\n    #define SSL_ASSERT2(s)\n    #define SSL_ASSERT3(s)\n#endif\n\n#define SSL_PLATFORM_DEBUG_LEVEL SSL_DEBUG_OFF\n#define SSL_PLATFORM_ERROR_LEVEL SSL_DEBUG_ON\n\n#define SSL_CERT_DEBUG_LEVEL     SSL_DEBUG_OFF\n#define SSL_CERT_ERROR_LEVEL     SSL_DEBUG_ON\n\n#define SSL_PKEY_DEBUG_LEVEL     SSL_DEBUG_OFF\n#define SSL_PKEY_ERROR_LEVEL     SSL_DEBUG_ON\n\n#define SSL_X509_DEBUG_LEVEL     SSL_DEBUG_OFF\n#define SSL_X509_ERROR_LEVEL     SSL_DEBUG_ON\n\n#define SSL_LIB_DEBUG_LEVEL      SSL_DEBUG_OFF\n#define SSL_LIB_ERROR_LEVEL      SSL_DEBUG_ON\n\n#define SSL_STACK_DEBUG_LEVEL    SSL_DEBUG_OFF\n#define SSL_STACK_ERROR_LEVEL    SSL_DEBUG_ON\n\n#ifdef __cplusplus\n }\n#endif\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_lib.h",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef _SSL_LIB_H_\n#define _SSL_LIB_H_\n\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n\n#include \"ssl_types.h\"\n\n void _ssl_set_alpn_list(const SSL *ssl);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_methods.h",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef _SSL_METHODS_H_\n#define _SSL_METHODS_H_\n\n#include \"ssl_types.h\"\n\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n\n/**\n * TLS method function implement\n */\n#define IMPLEMENT_TLS_METHOD_FUNC(func_name, \\\n                    new, free, \\\n                    handshake, shutdown, clear, \\\n                    read, send, pending, \\\n                    set_fd, get_fd, \\\n                    set_bufflen, \\\n                    get_verify_result, \\\n                    get_state) \\\n        static const SSL_METHOD_FUNC func_name LOCAL_ATRR = { \\\n                new, \\\n                free, \\\n                handshake, \\\n                shutdown, \\\n                clear, \\\n                read, \\\n                send, \\\n                pending, \\\n                set_fd, \\\n                get_fd, \\\n                set_bufflen, \\\n                get_verify_result, \\\n                get_state \\\n        };\n\n#define IMPLEMENT_TLS_METHOD(ver, mode, fun, func_name) \\\n    const SSL_METHOD* func_name(void) { \\\n        static const SSL_METHOD func_name##_data LOCAL_ATRR = { \\\n                ver, \\\n                mode, \\\n                &(fun), \\\n        }; \\\n        return &func_name##_data; \\\n    }\n\n#define IMPLEMENT_SSL_METHOD(ver, mode, fun, func_name) \\\n    const SSL_METHOD* func_name(void) { \\\n        static const SSL_METHOD func_name##_data LOCAL_ATRR = { \\\n                ver, \\\n                mode, \\\n                &(fun), \\\n        }; \\\n        return &func_name##_data; \\\n    }\n\n#define IMPLEMENT_X509_METHOD(func_name, \\\n                new, \\\n                free, \\\n                load, \\\n                show_info) \\\n    const X509_METHOD* func_name(void) { \\\n        static const X509_METHOD func_name##_data LOCAL_ATRR = { \\\n                new, \\\n                free, \\\n                load, \\\n                show_info \\\n        }; \\\n        return &func_name##_data; \\\n    }\n\n#define IMPLEMENT_PKEY_METHOD(func_name, \\\n                new, \\\n                free, \\\n                load) \\\n    const PKEY_METHOD* func_name(void) { \\\n        static const PKEY_METHOD func_name##_data LOCAL_ATRR = { \\\n                new, \\\n                free, \\\n                load \\\n        }; \\\n        return &func_name##_data; \\\n    }\n\n/**\n * @brief get X509 object method\n *\n * @param none\n *\n * @return X509 object method point\n */\nconst X509_METHOD* X509_method(void);\n\n/**\n * @brief get private key object method\n *\n * @param none\n *\n * @return private key object method point\n */\nconst PKEY_METHOD* EVP_PKEY_method(void);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_pkey.h",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef _SSL_PKEY_H_\n#define _SSL_PKEY_H_\n\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n\n#include \"ssl_types.h\"\n\n/**\n * @brief create a private key object according to input private key\n *\n * @param ipk - input private key point\n *\n * @return new private key object point\n */\nEVP_PKEY* __EVP_PKEY_new(EVP_PKEY *ipk);\n\n/**\n * @brief create a private key object\n *\n * @param none\n *\n * @return private key object point\n */\nEVP_PKEY* EVP_PKEY_new(void);\n\n/**\n * @brief load a character key context into system context. If '*a' is pointed to the\n *        private key, then load key into it. Or create a new private key object\n *\n * @param type   - private key type\n * @param a      - a point pointed to a private key point\n * @param pp     - a point pointed to the key context memory point\n * @param length - key bytes\n *\n * @return private key object point\n */\nEVP_PKEY* d2i_PrivateKey(int type,\n                         EVP_PKEY **a,\n                         const unsigned char **pp,\n                         long length);\n\n/**\n * @brief free a private key object\n *\n * @param pkey - private key object point\n *\n * @return none\n */\nvoid EVP_PKEY_free(EVP_PKEY *x);\n\n/**\n * @brief load private key into the SSL\n *\n * @param type - private key type\n * @param ssl  - SSL point\n * @param len  - data bytes\n * @param d    - data point\n *\n * @return result\n *     0 : failed\n *     1 : OK \n */\n int SSL_use_PrivateKey_ASN1(int type, SSL *ssl, const unsigned char *d, long len);\n\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_stack.h",
    "content": "#ifndef _SSL_STACK_H_\n#define _SSL_STACK_H_\n\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n\n#include \"ssl_types.h\"\n\n#define STACK_OF(type)  struct stack_st_##type\n\n#define SKM_DEFINE_STACK_OF(t1, t2, t3) \\\n    STACK_OF(t1); \\\n    static ossl_inline STACK_OF(t1) *sk_##t1##_new_null(void) \\\n    { \\\n        return (STACK_OF(t1) *)OPENSSL_sk_new_null(); \\\n    } \\\n\n#define DEFINE_STACK_OF(t) SKM_DEFINE_STACK_OF(t, t, t)\n\n/**\n * @brief create a openssl stack object\n *\n * @param c - stack function\n *\n * @return openssl stack object point\n */\nOPENSSL_STACK* OPENSSL_sk_new(OPENSSL_sk_compfunc c);\n\n/**\n * @brief create a NULL function openssl stack object\n *\n * @param none\n *\n * @return openssl stack object point\n */\nOPENSSL_STACK *OPENSSL_sk_new_null(void);\n\n/**\n * @brief free openssl stack object\n *\n * @param openssl stack object point\n *\n * @return none\n */\nvoid OPENSSL_sk_free(OPENSSL_STACK *stack);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_types.h",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef _SSL_TYPES_H_\n#define _SSL_TYPES_H_\n\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n\n#include <lws_config.h>\n#if defined(LWS_WITH_ESP32)\n#undef MBEDTLS_CONFIG_FILE\n#define MBEDTLS_CONFIG_FILE <mbedtls/esp_config.h>\n#endif\n\n#include \"ssl_code.h\"\n\ntypedef void SSL_CIPHER;\n\ntypedef void X509_STORE_CTX;\ntypedef void X509_STORE;\n\ntypedef void RSA;\n\ntypedef void STACK;\ntypedef void BIO;\n\n#if defined(WIN32) || defined(_WIN32)\n#define ossl_inline __inline\n#else\n#define ossl_inline inline\n#endif\n\n#define SSL_METHOD_CALL(f, s, ...)        s->method->func->ssl_##f(s, ##__VA_ARGS__)\n#define X509_METHOD_CALL(f, x, ...)       x->method->x509_##f(x, ##__VA_ARGS__)\n#define EVP_PKEY_METHOD_CALL(f, k, ...)   k->method->pkey_##f(k, ##__VA_ARGS__)\n\ntypedef int (*OPENSSL_sk_compfunc)(const void *, const void *);\n\nstruct stack_st;\ntypedef struct stack_st OPENSSL_STACK;\n\nstruct ssl_method_st;\ntypedef struct ssl_method_st SSL_METHOD;\n\nstruct ssl_method_func_st;\ntypedef struct ssl_method_func_st SSL_METHOD_FUNC;\n\nstruct record_layer_st;\ntypedef struct record_layer_st RECORD_LAYER;\n\nstruct ossl_statem_st;\ntypedef struct ossl_statem_st OSSL_STATEM;\n\nstruct ssl_session_st;\ntypedef struct ssl_session_st SSL_SESSION;\n\nstruct ssl_ctx_st;\ntypedef struct ssl_ctx_st SSL_CTX;\n\nstruct ssl_st;\ntypedef struct ssl_st SSL;\n\nstruct cert_st;\ntypedef struct cert_st CERT;\n\nstruct x509_st;\ntypedef struct x509_st X509;\n\nstruct X509_VERIFY_PARAM_st;\ntypedef struct X509_VERIFY_PARAM_st X509_VERIFY_PARAM;\n\nstruct evp_pkey_st;\ntypedef struct evp_pkey_st EVP_PKEY;\n\nstruct x509_method_st;\ntypedef struct x509_method_st X509_METHOD;\n\nstruct pkey_method_st;\ntypedef struct pkey_method_st PKEY_METHOD;\n\nstruct stack_st {\n\n    char **data;\n\n    int num_alloc;\n\n    OPENSSL_sk_compfunc c;\n};\n\nstruct evp_pkey_st {\n\n    void *pkey_pm;\n\n    const PKEY_METHOD *method;\n};\n\nstruct x509_st {\n\n    /* X509 certification platform private point */\n    void *x509_pm;\n\n    const X509_METHOD *method;\n};\n\nstruct cert_st {\n\n    int sec_level;\n\n    X509 *x509;\n\n    EVP_PKEY *pkey;\n\n};\n\nstruct ossl_statem_st {\n\n    MSG_FLOW_STATE state;\n\n    int hand_state;\n};\n\nstruct record_layer_st {\n\n    int rstate;\n\n    int read_ahead;\n};\n\nstruct ssl_session_st {\n\n    long timeout;\n\n    long time;\n\n    X509 *peer;\n};\n\nstruct X509_VERIFY_PARAM_st {\n\n    int depth;\n\n};\n\ntypedef int (*next_proto_cb)(SSL *ssl, unsigned char **out,\n                             unsigned char *outlen, const unsigned char *in,\n                             unsigned int inlen, void *arg);\n\nstruct ssl_ctx_st\n{\n    int version;\n\n    int references;\n\n    unsigned long options;\n\n    const SSL_METHOD *method;\n\n    CERT *cert;\n\n    X509 *client_CA;\n\n    const char **alpn_protos;\n\n    next_proto_cb alpn_cb;\n\n    int verify_mode;\n\n    int (*default_verify_callback) (int ok, X509_STORE_CTX *ctx);\n\n    long session_timeout;\n\n    int read_ahead;\n\n    int read_buffer_len;\n\n    X509_VERIFY_PARAM param;\n};\n\nstruct ssl_st\n{\n    /* protocol version(one of SSL3.0, TLS1.0, etc.) */\n    int version;\n\n    unsigned long options;\n\n    /* shut things down(0x01 : sent, 0x02 : received) */\n    int shutdown;\n\n    CERT *cert;\n\n    X509 *client_CA;\n\n    SSL_CTX  *ctx;\n\n    const SSL_METHOD *method;\n\n    const char **alpn_protos;\n\n    RECORD_LAYER rlayer;\n\n    /* where we are */\n    OSSL_STATEM statem;\n\n    SSL_SESSION *session;\n\n    int verify_mode;\n\n    int (*verify_callback) (int ok, X509_STORE_CTX *ctx);\n\n    int rwstate;\n    int interrupted_remaining_write;\n\n    long verify_result;\n\n    X509_VERIFY_PARAM param;\n\n    int err;\n\n    void (*info_callback) (const SSL *ssl, int type, int val);\n\n    /* SSL low-level system arch point */\n    void *ssl_pm;\n};\n\nstruct ssl_method_st {\n    /* protocol version(one of SSL3.0, TLS1.0, etc.) */\n    int version;\n\n    /* SSL mode(client(0) , server(1), not known(-1)) */\n    int endpoint;\n\n    const SSL_METHOD_FUNC *func;\n};\n\nstruct ssl_method_func_st {\n\n    int (*ssl_new)(SSL *ssl);\n\n    void (*ssl_free)(SSL *ssl);\n\n    int (*ssl_handshake)(SSL *ssl);\n\n    int (*ssl_shutdown)(SSL *ssl);\n\n    int (*ssl_clear)(SSL *ssl);\n\n    int (*ssl_read)(SSL *ssl, void *buffer, int len);\n\n    int (*ssl_send)(SSL *ssl, const void *buffer, int len);\n\n    int (*ssl_pending)(const SSL *ssl);\n\n    void (*ssl_set_fd)(SSL *ssl, int fd, int mode);\n\n    int (*ssl_get_fd)(const SSL *ssl, int mode);\n\n    void (*ssl_set_bufflen)(SSL *ssl, int len);\n\n    long (*ssl_get_verify_result)(const SSL *ssl);\n\n    OSSL_HANDSHAKE_STATE (*ssl_get_state)(const SSL *ssl);\n};\n\nstruct x509_method_st {\n\n    int (*x509_new)(X509 *x, X509 *m_x);\n\n    void (*x509_free)(X509 *x);\n\n    int (*x509_load)(X509 *x, const unsigned char *buf, int len);\n\n    int (*x509_show_info)(X509 *x);\n};\n\nstruct pkey_method_st {\n\n    int (*pkey_new)(EVP_PKEY *pkey, EVP_PKEY *m_pkey);\n\n    void (*pkey_free)(EVP_PKEY *pkey);\n\n    int (*pkey_load)(EVP_PKEY *pkey, const unsigned char *buf, int len);\n};\n\n#define OPENSSL_NPN_NEGOTIATED 1\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_x509.h",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef _SSL_X509_H_\n#define _SSL_X509_H_\n\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n\n#include \"ssl_types.h\"\n#include \"ssl_stack.h\"\n\nDEFINE_STACK_OF(X509_NAME)\n\n/**\n * @brief create a X509 certification object according to input X509 certification\n *\n * @param ix - input X509 certification point\n *\n * @return new X509 certification object point\n */\nX509* __X509_new(X509 *ix);\n\n/**\n * @brief create a X509 certification object\n *\n * @param none\n *\n * @return X509 certification object point\n */\nX509* X509_new(void);\n\n/**\n * @brief load a character certification context into system context. If '*cert' is pointed to the\n *        certification, then load certification into it. Or create a new X509 certification object\n *\n * @param cert   - a point pointed to X509 certification\n * @param buffer - a point pointed to the certification context memory point\n * @param length - certification bytes\n *\n * @return X509 certification object point\n */\nX509* d2i_X509(X509 **cert, const unsigned char *buffer, long len);\n\n/**\n * @brief free a X509 certification object\n *\n * @param x - X509 certification object point\n *\n * @return none\n */\nvoid X509_free(X509 *x);\n\n/**\n * @brief set SSL context client CA certification\n *\n * @param ctx - SSL context point\n * @param x   - X509 certification point\n *\n * @return result\n *     0 : failed\n *     1 : OK\n */\nint SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x);\n\n/**\n * @brief add CA client certification into the SSL\n *\n * @param ssl - SSL point\n * @param x   - X509 certification point\n *\n * @return result\n *     0 : failed\n *     1 : OK\n */\nint SSL_add_client_CA(SSL *ssl, X509 *x);\n\n/**\n * @brief load certification into the SSL\n *\n * @param ssl - SSL point\n * @param len - data bytes\n * @param d   - data point\n *\n * @return result\n *     0 : failed\n *     1 : OK\n *\n */\nint SSL_use_certificate_ASN1(SSL *ssl, int len, const unsigned char *d);\n\nconst char *X509_verify_cert_error_string(long n);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/include/internal/tls1.h",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef _TLS1_H_\n#define _TLS1_H_\n\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n\n# define TLS1_AD_DECRYPTION_FAILED       21\n# define TLS1_AD_RECORD_OVERFLOW         22\n# define TLS1_AD_UNKNOWN_CA              48/* fatal */\n# define TLS1_AD_ACCESS_DENIED           49/* fatal */\n# define TLS1_AD_DECODE_ERROR            50/* fatal */\n# define TLS1_AD_DECRYPT_ERROR           51\n# define TLS1_AD_EXPORT_RESTRICTION      60/* fatal */\n# define TLS1_AD_PROTOCOL_VERSION        70/* fatal */\n# define TLS1_AD_INSUFFICIENT_SECURITY   71/* fatal */\n# define TLS1_AD_INTERNAL_ERROR          80/* fatal */\n# define TLS1_AD_INAPPROPRIATE_FALLBACK  86/* fatal */\n# define TLS1_AD_USER_CANCELLED          90\n# define TLS1_AD_NO_RENEGOTIATION        100\n/* codes 110-114 are from RFC3546 */\n# define TLS1_AD_UNSUPPORTED_EXTENSION   110\n# define TLS1_AD_CERTIFICATE_UNOBTAINABLE 111\n# define TLS1_AD_UNRECOGNIZED_NAME       112\n# define TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE 113\n# define TLS1_AD_BAD_CERTIFICATE_HASH_VALUE 114\n# define TLS1_AD_UNKNOWN_PSK_IDENTITY    115/* fatal */\n# define TLS1_AD_NO_APPLICATION_PROTOCOL 120 /* fatal */\n\n/* Special value for method supporting multiple versions */\n#define TLS_ANY_VERSION                 0x10000\n\n#define TLS1_VERSION                    0x0301\n#define TLS1_1_VERSION                  0x0302\n#define TLS1_2_VERSION                  0x0303\n\n#define SSL_TLSEXT_ERR_OK 0\n#define SSL_TLSEXT_ERR_NOACK 3\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/include/internal/x509_vfy.h",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef _X509_VFY_H_\n#define _X509_VFY_H_\n\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n\n#define         X509_V_OK                                       0\n#define         X509_V_ERR_UNSPECIFIED                          1\n#define         X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT            2\n#define         X509_V_ERR_UNABLE_TO_GET_CRL                    3\n#define         X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE     4\n#define         X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE      5\n#define         X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY   6\n#define         X509_V_ERR_CERT_SIGNATURE_FAILURE               7\n#define         X509_V_ERR_CRL_SIGNATURE_FAILURE                8\n#define         X509_V_ERR_CERT_NOT_YET_VALID                   9\n#define         X509_V_ERR_CERT_HAS_EXPIRED                     10\n#define         X509_V_ERR_CRL_NOT_YET_VALID                    11\n#define         X509_V_ERR_CRL_HAS_EXPIRED                      12\n#define         X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD       13\n#define         X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD        14\n#define         X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD       15\n#define         X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD       16\n#define         X509_V_ERR_OUT_OF_MEM                           17\n#define         X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT          18\n#define         X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN            19\n#define         X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY    20\n#define         X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE      21\n#define         X509_V_ERR_CERT_CHAIN_TOO_LONG                  22\n#define         X509_V_ERR_CERT_REVOKED                         23\n#define         X509_V_ERR_INVALID_CA                           24\n#define         X509_V_ERR_PATH_LENGTH_EXCEEDED                 25\n#define         X509_V_ERR_INVALID_PURPOSE                      26\n#define         X509_V_ERR_CERT_UNTRUSTED                       27\n#define         X509_V_ERR_CERT_REJECTED                        28\n/* These are 'informational' when looking for issuer cert */\n#define         X509_V_ERR_SUBJECT_ISSUER_MISMATCH              29\n#define         X509_V_ERR_AKID_SKID_MISMATCH                   30\n#define         X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH          31\n#define         X509_V_ERR_KEYUSAGE_NO_CERTSIGN                 32\n#define         X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER             33\n#define         X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION         34\n#define         X509_V_ERR_KEYUSAGE_NO_CRL_SIGN                 35\n#define         X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION     36\n#define         X509_V_ERR_INVALID_NON_CA                       37\n#define         X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED           38\n#define         X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE        39\n#define         X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED       40\n#define         X509_V_ERR_INVALID_EXTENSION                    41\n#define         X509_V_ERR_INVALID_POLICY_EXTENSION             42\n#define         X509_V_ERR_NO_EXPLICIT_POLICY                   43\n#define         X509_V_ERR_DIFFERENT_CRL_SCOPE                  44\n#define         X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE        45\n#define         X509_V_ERR_UNNESTED_RESOURCE                    46\n#define         X509_V_ERR_PERMITTED_VIOLATION                  47\n#define         X509_V_ERR_EXCLUDED_VIOLATION                   48\n#define         X509_V_ERR_SUBTREE_MINMAX                       49\n/* The application is not happy */\n#define         X509_V_ERR_APPLICATION_VERIFICATION             50\n#define         X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE          51\n#define         X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX        52\n#define         X509_V_ERR_UNSUPPORTED_NAME_SYNTAX              53\n#define         X509_V_ERR_CRL_PATH_VALIDATION_ERROR            54\n/* Another issuer check debug option */\n#define         X509_V_ERR_PATH_LOOP                            55\n/* Suite B mode algorithm violation */\n#define         X509_V_ERR_SUITE_B_INVALID_VERSION              56\n#define         X509_V_ERR_SUITE_B_INVALID_ALGORITHM            57\n#define         X509_V_ERR_SUITE_B_INVALID_CURVE                58\n#define         X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM  59\n#define         X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED              60\n#define         X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 61\n/* Host, email and IP check errors */\n#define         X509_V_ERR_HOSTNAME_MISMATCH                    62\n#define         X509_V_ERR_EMAIL_MISMATCH                       63\n#define         X509_V_ERR_IP_ADDRESS_MISMATCH                  64\n/* DANE TLSA errors */\n#define         X509_V_ERR_DANE_NO_MATCH                        65\n/* security level errors */\n#define         X509_V_ERR_EE_KEY_TOO_SMALL                     66\n#define         X509_V_ERR_CA_KEY_TOO_SMALL                     67\n#define         X509_V_ERR_CA_MD_TOO_WEAK                       68\n/* Caller error */\n#define         X509_V_ERR_INVALID_CALL                         69\n/* Issuer lookup error */\n#define         X509_V_ERR_STORE_LOOKUP                         70\n/* Certificate transparency */\n#define         X509_V_ERR_NO_VALID_SCTS                        71\n\n#define         X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION         72\n\ntypedef void X509_STORE_CTX;\nint X509_STORE_CTX_get_error(X509_STORE_CTX *ctx);\nint X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx);\n\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/include/openssl/ssl.h",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef _SSL_H_\n#define _SSL_H_\n\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n\n#include <stdlib.h>\n#include \"internal/ssl_x509.h\"\n#include \"internal/ssl_pkey.h\"\n\n/*\n{\n*/\n\n#define SSL_CB_ALERT 0x4000\n\n#define X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT\t\t(1 << 0)\n#define X509_CHECK_FLAG_NO_WILDCARDS\t\t\t(1 << 1)\n#define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS\t\t(1 << 2)\n#define X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS\t\t(1 << 3)\n#define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS\t\t(1 << 4)\n\n mbedtls_x509_crt *\n ssl_ctx_get_mbedtls_x509_crt(SSL_CTX *ssl_ctx);\n\n mbedtls_x509_crt *\n ssl_get_peer_mbedtls_x509_crt(SSL *ssl);\n\n int SSL_set_sni_callback(SSL *ssl, int(*cb)(void *, mbedtls_ssl_context *,\n \t\t\t\tconst unsigned char *, size_t), void *param);\n\n void SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx);\n\n int SSL_CTX_add_client_CA_ASN1(SSL_CTX *ssl, int len,\n                 const unsigned char *d);\n\n SSL *SSL_SSL_from_mbedtls_ssl_context(mbedtls_ssl_context *msc);\n\n/**\n * @brief create a SSL context\n *\n * @param method - the SSL context method point\n *\n * @return the context point\n */\nSSL_CTX* SSL_CTX_new(const SSL_METHOD *method);\n\n/**\n * @brief free a SSL context\n *\n * @param method - the SSL context point\n *\n * @return none\n */\nvoid SSL_CTX_free(SSL_CTX *ctx);\n\n/**\n * @brief create a SSL\n *\n * @param ctx - the SSL context point\n *\n * @return the SSL point\n */\nSSL* SSL_new(SSL_CTX *ctx);\n\n/**\n * @brief free the SSL\n *\n * @param ssl - the SSL point\n *\n * @return none\n */\nvoid SSL_free(SSL *ssl);\n\n/**\n * @brief connect to the remote SSL server\n *\n * @param ssl - the SSL point\n *\n * @return result\n *     1 : OK\n *    -1 : failed\n */\nint SSL_connect(SSL *ssl);\n\n/**\n * @brief accept the remote connection\n *\n * @param ssl - the SSL point\n *\n * @return result\n *     1 : OK\n *    -1 : failed\n */\nint SSL_accept(SSL *ssl);\n\n/**\n * @brief read data from to remote\n *\n * @param ssl    - the SSL point which has been connected\n * @param buffer - the received data buffer point\n * @param len    - the received data length\n *\n * @return result\n *     > 0 : OK, and return received data bytes\n *     = 0 : connection is closed\n *     < 0 : an error catch\n */\nint SSL_read(SSL *ssl, void *buffer, int len);\n\n/**\n * @brief send the data to remote\n *\n * @param ssl    - the SSL point which has been connected\n * @param buffer - the send data buffer point\n * @param len    - the send data length\n *\n * @return result\n *     > 0 : OK, and return sent data bytes\n *     = 0 : connection is closed\n *     < 0 : an error catch\n */\nint SSL_write(SSL *ssl, const void *buffer, int len);\n\n/**\n * @brief get the verifying result of the SSL certification\n *\n * @param ssl - the SSL point\n *\n * @return the result of verifying\n */\nlong SSL_get_verify_result(const SSL *ssl);\n\n/**\n * @brief shutdown the connection\n *\n * @param ssl - the SSL point\n *\n * @return result\n *     1 : OK\n *     0 : shutdown is not finished\n *    -1 : an error catch\n */\nint SSL_shutdown(SSL *ssl);\n\n/**\n * @brief bind the socket file description into the SSL\n *\n * @param ssl - the SSL point\n * @param fd  - socket handle\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_set_fd(SSL *ssl, int fd);\n\n/**\n * @brief These functions load the private key into the SSL_CTX or SSL object\n *\n * @param ctx  - the SSL context point\n * @param pkey - private key object point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey);\n\n/**\n * @brief These functions load the certification into the SSL_CTX or SSL object\n *\n * @param ctx  - the SSL context point\n * @param pkey - certification object point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x);\n\n/**\n * @brief create the target SSL context client method\n *\n * @param none\n *\n * @return the SSLV2.3 version SSL context client method\n */\nconst SSL_METHOD* SSLv23_client_method(void);\n\n/**\n * @brief create the target SSL context client method\n *\n * @param none\n *\n * @return the TLSV1.0 version SSL context client method\n */\nconst SSL_METHOD* TLSv1_client_method(void);\n\n/**\n * @brief create the target SSL context client method\n *\n * @param none\n *\n * @return the SSLV1.0 version SSL context client method\n */\nconst SSL_METHOD* SSLv3_client_method(void);\n\n/**\n * @brief create the target SSL context client method\n *\n * @param none\n *\n * @return the TLSV1.1 version SSL context client method\n */\nconst SSL_METHOD* TLSv1_1_client_method(void);\n\n/**\n * @brief create the target SSL context client method\n *\n * @param none\n *\n * @return the TLSV1.2 version SSL context client method\n */\nconst SSL_METHOD* TLSv1_2_client_method(void);\n\n/**\n * @brief create the target SSL context server method\n *\n * @param none\n *\n * @return the TLS any version SSL context client method\n */\nconst SSL_METHOD* TLS_client_method(void);\n\n/**\n * @brief create the target SSL context server method\n *\n * @param none\n *\n * @return the SSLV2.3 version SSL context server method\n */\nconst SSL_METHOD* SSLv23_server_method(void);\n\n/**\n * @brief create the target SSL context server method\n *\n * @param none\n *\n * @return the TLSV1.1 version SSL context server method\n */\nconst SSL_METHOD* TLSv1_1_server_method(void);\n\n/**\n * @brief create the target SSL context server method\n *\n * @param none\n *\n * @return the TLSV1.2 version SSL context server method\n */\nconst SSL_METHOD* TLSv1_2_server_method(void);\n\n/**\n * @brief create the target SSL context server method\n *\n * @param none\n *\n * @return the TLSV1.0 version SSL context server method\n */\nconst SSL_METHOD* TLSv1_server_method(void);\n\n/**\n * @brief create the target SSL context server method\n *\n * @param none\n *\n * @return the SSLV3.0 version SSL context server method\n */\nconst SSL_METHOD* SSLv3_server_method(void);\n\n/**\n * @brief create the target SSL context server method\n *\n * @param none\n *\n * @return the TLS any version SSL context server method\n */\nconst SSL_METHOD* TLS_server_method(void);\n\n\n/**\n * @brief set the SSL context ALPN select callback function\n *\n * @param ctx - SSL context point\n * @param cb  - ALPN select callback function\n * @param arg - ALPN select callback function entry private data point\n *\n * @return none\n */\nvoid SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,\n                                int (*cb) (SSL *ssl,\n                                           const unsigned char **out,\n                                           unsigned char *outlen,\n                                           const unsigned char *in,\n                                           unsigned int inlen,\n                                           void *arg),\n                                void *arg);\n\nvoid SSL_set_alpn_select_cb(SSL *ssl, void *arg);\n\n/**\n * @brief set the SSL context ALPN select protocol\n *\n * @param ctx        - SSL context point\n * @param protos     - ALPN protocol name\n * @param protos_len - ALPN protocol name bytes\n *\n * @return result\n *     0 : OK\n *     1 : failed\n */\nint SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos, unsigned int protos_len);\n\n/**\n * @brief set the SSL context next ALPN select callback function\n *\n * @param ctx - SSL context point\n * @param cb  - ALPN select callback function\n * @param arg - ALPN select callback function entry private data point\n *\n * @return none\n */\nvoid SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx,\n                                      int (*cb) (SSL *ssl,\n                                                 unsigned char **out,\n                                                 unsigned char *outlen,\n                                                 const unsigned char *in,\n                                                 unsigned int inlen,\n                                                 void *arg),\n                                      void *arg);\n\nvoid SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,\n                             unsigned int *len);\n\nvoid _ssl_set_alpn_list(const SSL *ssl);\n\n/**\n * @brief get SSL error code\n *\n * @param ssl       - SSL point\n * @param ret_code  - SSL return code\n *\n * @return SSL error number\n */\nint SSL_get_error(const SSL *ssl, int ret_code);\n\n/**\n * @brief clear the SSL error code\n *\n * @param none\n *\n * @return none\n */\nvoid ERR_clear_error(void);\n\n/**\n * @brief get the current SSL error code\n *\n * @param none\n *\n * @return current SSL error number\n */\nint ERR_get_error(void);\n\n/**\n * @brief register the SSL error strings\n *\n * @param none\n *\n * @return none\n */\nvoid ERR_load_SSL_strings(void);\n\n/**\n * @brief initialize the SSL library\n *\n * @param none\n *\n * @return none\n */\nvoid SSL_library_init(void);\n\n/**\n * @brief generates a human-readable string representing the error code e\n *        and store it into the \"ret\" point memory\n *\n * @param e   - error code\n * @param ret - memory point to store the string\n *\n * @return the result string point\n */\nchar *ERR_error_string(unsigned long e, char *ret);\n\n/**\n * @brief add the SSL context option\n *\n * @param ctx - SSL context point\n * @param opt - new SSL context option\n *\n * @return the SSL context option\n */\nunsigned long SSL_CTX_set_options(SSL_CTX *ctx, unsigned long opt);\n\n/**\n * @brief add the SSL context mode\n *\n * @param ctx - SSL context point\n * @param mod - new SSL context mod\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_set_mode(SSL_CTX *ctx, int mod);\n\n/*\n}\n*/\n\n/**\n * @brief perform the SSL handshake\n *\n * @param ssl - SSL point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n *    -1 : a error catch\n */\nint SSL_do_handshake(SSL *ssl);\n\n/**\n * @brief get the SSL current version\n *\n * @param ssl - SSL point\n *\n * @return the version string\n */\nconst char *SSL_get_version(const SSL *ssl);\n\n/**\n * @brief set  the SSL context version\n *\n * @param ctx  - SSL context point\n * @param meth - SSL method point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth);\n\n/**\n * @brief get the bytes numbers which are to be read\n *\n * @param ssl  - SSL point\n *\n * @return bytes number\n */\nint SSL_pending(const SSL *ssl);\n\n/**\n * @brief check if SSL want nothing\n *\n * @param ssl - SSL point\n *\n * @return result\n *     0 : false\n *     1 : true\n */\nint SSL_want_nothing(const SSL *ssl);\n\n/**\n * @brief check if SSL want to read\n *\n * @param ssl - SSL point\n *\n * @return result\n *     0 : false\n *     1 : true\n */\nint SSL_want_read(const SSL *ssl);\n\n/**\n * @brief check if SSL want to write\n *\n * @param ssl - SSL point\n *\n * @return result\n *     0 : false\n *     1 : true\n */\nint SSL_want_write(const SSL *ssl);\n\n/**\n * @brief get the SSL context current method\n *\n * @param ctx - SSL context point\n *\n * @return the SSL context current method\n */\nconst SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx);\n\n/**\n * @brief get the SSL current method\n *\n * @param ssl - SSL point\n *\n * @return the SSL current method\n */\nconst SSL_METHOD *SSL_get_ssl_method(SSL *ssl);\n\n/**\n * @brief set the SSL method\n *\n * @param ssl  - SSL point\n * @param meth - SSL method point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_set_ssl_method(SSL *ssl, const SSL_METHOD *method);\n\n/**\n * @brief add CA client certification into the SSL\n *\n * @param ssl - SSL point\n * @param x   - CA certification point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_add_client_CA(SSL *ssl, X509 *x);\n\n/**\n * @brief add CA client certification into the SSL context\n *\n * @param ctx - SSL context point\n * @param x   - CA certification point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x);\n\n/**\n * @brief set the SSL CA certification list\n *\n * @param ssl       - SSL point\n * @param name_list - CA certification list\n *\n * @return none\n */\nvoid SSL_set_client_CA_list(SSL *ssl, STACK_OF(X509_NAME) *name_list);\n\n/**\n * @brief set the SSL context CA certification list\n *\n * @param ctx       - SSL context point\n * @param name_list - CA certification list\n *\n * @return none\n */\nvoid SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list);\n\n/**\n * @briefget the SSL CA certification list\n *\n * @param ssl - SSL point\n *\n * @return CA certification list\n */\nSTACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *ssl);\n\n/**\n * @brief get the SSL context CA certification list\n *\n * @param ctx - SSL context point\n *\n * @return CA certification list\n */\nSTACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *ctx);\n\n/**\n * @brief get the SSL certification point\n *\n * @param ssl - SSL point\n *\n * @return SSL certification point\n */\nX509 *SSL_get_certificate(const SSL *ssl);\n\n/**\n * @brief get the SSL private key point\n *\n * @param ssl - SSL point\n *\n * @return SSL private key point\n */\nEVP_PKEY *SSL_get_privatekey(const SSL *ssl);\n\n/**\n * @brief set the SSL information callback function\n *\n * @param ssl - SSL point\n * @param cb  - information callback function\n *\n * @return none\n */\nvoid SSL_set_info_callback(SSL *ssl, void (*cb) (const SSL *ssl, int type, int val));\n\n/**\n * @brief get the SSL state\n *\n * @param ssl - SSL point\n *\n * @return SSL state\n */\nOSSL_HANDSHAKE_STATE SSL_get_state(const SSL *ssl);\n\n/**\n * @brief set the SSL context read buffer length\n *\n * @param ctx - SSL context point\n * @param len - read buffer length\n *\n * @return none\n */\nvoid SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len);\n\n/**\n * @brief set the SSL read buffer length\n *\n * @param ssl - SSL point\n * @param len - read buffer length\n *\n * @return none\n */\nvoid SSL_set_default_read_buffer_len(SSL *ssl, size_t len);\n\n/**\n * @brief set the SSL security level\n *\n * @param ssl   - SSL point\n * @param level - security level\n *\n * @return none\n */\nvoid SSL_set_security_level(SSL *ssl, int level);\n\n/**\n * @brief get the SSL security level\n *\n * @param ssl - SSL point\n *\n * @return security level\n */\nint SSL_get_security_level(const SSL *ssl);\n\n/**\n * @brief get the SSL verifying mode of the SSL context\n *\n * @param ctx - SSL context point\n *\n * @return verifying mode\n */\nint SSL_CTX_get_verify_mode(const SSL_CTX *ctx);\n\n/**\n * @brief get the SSL verifying depth of the SSL context\n *\n * @param ctx - SSL context point\n *\n * @return verifying depth\n */\nint SSL_CTX_get_verify_depth(const SSL_CTX *ctx);\n\n/**\n * @brief set the SSL context verifying of the SSL context\n *\n * @param ctx             - SSL context point\n * @param mode            - verifying mode\n * @param verify_callback - verifying callback function\n *\n * @return none\n */\nvoid SSL_CTX_set_verify(SSL_CTX *ctx, int mode, int (*verify_callback)(int, X509_STORE_CTX *));\n\n/**\n * @brief set the SSL verifying of the SSL context\n *\n * @param ctx             - SSL point\n * @param mode            - verifying mode\n * @param verify_callback - verifying callback function\n *\n * @return none\n */\nvoid SSL_set_verify(SSL *s, int mode, int (*verify_callback)(int, X509_STORE_CTX *));\n\n/**\n * @brief set the SSL verify depth of the SSL context\n *\n * @param ctx   - SSL context point\n * @param depth - verifying depth\n *\n * @return none\n */\nvoid SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth);\n\n/**\n * @brief certification verifying callback function\n *\n * @param preverify_ok - verifying result\n * @param x509_ctx     - X509 certification point\n *\n * @return verifying result\n */\nint verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx);\n\n/**\n * @brief set the session timeout time\n *\n * @param ctx - SSL context point\n * @param t   - new session timeout time\n *\n * @return old session timeout time\n */\nlong SSL_CTX_set_timeout(SSL_CTX *ctx, long t);\n\n/**\n * @brief get the session timeout time\n *\n * @param ctx - SSL context point\n *\n * @return current session timeout time\n */\nlong SSL_CTX_get_timeout(const SSL_CTX *ctx);\n\n/**\n * @brief set the SSL context cipher through the list string\n *\n * @param ctx - SSL context point\n * @param str - cipher controller list string\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str);\n\n/**\n * @brief set the SSL cipher through the list string\n *\n * @param ssl - SSL point\n * @param str - cipher controller list string\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_set_cipher_list(SSL *ssl, const char *str);\n\n/**\n * @brief get the SSL cipher list string\n *\n * @param ssl - SSL point\n *\n * @return cipher controller list string\n */\nconst char *SSL_get_cipher_list(const SSL *ssl, int n);\n\n/**\n * @brief get the SSL cipher\n *\n * @param ssl - SSL point\n *\n * @return current cipher\n */\nconst SSL_CIPHER *SSL_get_current_cipher(const SSL *ssl);\n\n/**\n * @brief get the SSL cipher string\n *\n * @param ssl - SSL point\n *\n * @return cipher string\n */\nconst char *SSL_get_cipher(const SSL *ssl);\n\n/**\n * @brief get the SSL context object X509 certification storage\n *\n * @param ctx - SSL context point\n *\n * @return x509 certification storage\n */\nX509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx);\n\n/**\n * @brief set the SSL context object X509 certification store\n *\n * @param ctx   - SSL context point\n * @param store - X509 certification store\n *\n * @return none\n */\nvoid SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store);\n\n/**\n * @brief get the SSL specifical statement\n *\n * @param ssl - SSL point\n *\n * @return specifical statement\n */\nint SSL_want(const SSL *ssl);\n\n/**\n * @brief check if the SSL is SSL_X509_LOOKUP state\n *\n * @param ssl - SSL point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_want_x509_lookup(const SSL *ssl);\n\n/**\n * @brief reset the SSL\n *\n * @param ssl - SSL point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_clear(SSL *ssl);\n\n/**\n * @brief get the socket handle of the SSL\n *\n * @param ssl - SSL point\n *\n * @return result\n *     >= 0 : yes, and return socket handle\n *      < 0 : a error catch\n */\nint SSL_get_fd(const SSL *ssl);\n\n/**\n * @brief get the read only socket handle of the SSL\n *\n * @param ssl - SSL point\n *\n * @return result\n *     >= 0 : yes, and return socket handle\n *      < 0 : a error catch\n */\nint SSL_get_rfd(const SSL *ssl);\n\n/**\n * @brief get the write only socket handle of the SSL\n *\n * @param ssl - SSL point\n *\n * @return result\n *     >= 0 : yes, and return socket handle\n *      < 0 : a error catch\n */\nint SSL_get_wfd(const SSL *ssl);\n\n/**\n * @brief set the SSL if we can read as many as data\n *\n * @param ssl - SSL point\n * @param yes - enable the function\n *\n * @return none\n */\nvoid SSL_set_read_ahead(SSL *s, int yes);\n\n/**\n * @brief set the SSL context if we can read as many as data\n *\n * @param ctx - SSL context point\n * @param yes - enbale the function\n *\n * @return none\n */\nvoid SSL_CTX_set_read_ahead(SSL_CTX *ctx, int yes);\n\n/**\n * @brief get the SSL ahead signal if we can read as many as data\n *\n * @param ssl - SSL point\n *\n * @return SSL context ahead signal\n */\nint SSL_get_read_ahead(const SSL *ssl);\n\n/**\n * @brief get the SSL context ahead signal if we can read as many as data\n *\n * @param ctx - SSL context point\n *\n * @return SSL context ahead signal\n */\nlong SSL_CTX_get_read_ahead(SSL_CTX *ctx);\n\n/**\n * @brief check if some data can be read\n *\n * @param ssl - SSL point\n *\n * @return\n *         1 : there are bytes to be read\n *         0 : no data\n */\nint SSL_has_pending(const SSL *ssl);\n\n/**\n * @brief load the X509 certification into SSL context\n *\n * @param ctx - SSL context point\n * @param x   - X509 certification point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x);//loads the certificate x into ctx\n\n/**\n * @brief load the ASN1 certification into SSL context\n *\n * @param ctx - SSL context point\n * @param len - certification length\n * @param d   - data point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len, const unsigned char *d);\n\n/**\n * @brief load the certification file into SSL context\n *\n * @param ctx  - SSL context point\n * @param file - certification file name\n * @param type - certification encoding type\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type);\n\n/**\n * @brief load the certification chain file into SSL context\n *\n * @param ctx  - SSL context point\n * @param file - certification chain file name\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_use_certificate_chain_file(SSL_CTX *ctx, const char *file);\n\n\n/**\n * @brief load the ASN1 private key into SSL context\n *\n * @param ctx - SSL context point\n * @param d   - data point\n * @param len - private key length\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_use_PrivateKey_ASN1(int pk, SSL_CTX *ctx, const unsigned char *d,  long len);//adds the private key of type pk stored at memory location d (length len) to ctx\n\n/**\n * @brief load the private key file into SSL context\n *\n * @param ctx  - SSL context point\n * @param file - private key file name\n * @param type - private key encoding type\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type);\n\n/**\n * @brief load the RSA private key into SSL context\n *\n * @param ctx - SSL context point\n * @param x   - RSA private key point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_use_RSAPrivateKey(SSL_CTX *ctx, RSA *rsa);\n\n/**\n * @brief load the RSA ASN1 private key into SSL context\n *\n * @param ctx - SSL context point\n * @param d   - data point\n * @param len - RSA private key length\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d, long len);\n\n/**\n * @brief load the RSA private key file into SSL context\n *\n * @param ctx  - SSL context point\n * @param file - RSA private key file name\n * @param type - private key encoding type\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_use_RSAPrivateKey_file(SSL_CTX *ctx, const char *file, int type);\n\n\n/**\n * @brief check if the private key and certification is matched\n *\n * @param ctx  - SSL context point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_check_private_key(const SSL_CTX *ctx);\n\n/**\n * @brief set the SSL context server information\n *\n * @param ctx               - SSL context point\n * @param serverinfo        - server information string\n * @param serverinfo_length - server information length\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_use_serverinfo(SSL_CTX *ctx, const unsigned char *serverinfo, size_t serverinfo_length);\n\n/**\n * @brief load  the SSL context server infomation file into SSL context\n *\n * @param ctx  - SSL context point\n * @param file - server information file\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_use_serverinfo_file(SSL_CTX *ctx, const char *file);\n\n/**\n * @brief SSL select next function\n *\n * @param out        - point of output data point\n * @param outlen     - output data length\n * @param in         - input data\n * @param inlen      - input data length\n * @param client     - client data point\n * @param client_len -client data length\n *\n * @return NPN state\n *         OPENSSL_NPN_UNSUPPORTED : not support\n *         OPENSSL_NPN_NEGOTIATED  : negotiated\n *         OPENSSL_NPN_NO_OVERLAP  : no overlap\n */\nint SSL_select_next_proto(unsigned char **out, unsigned char *outlen,\n                          const unsigned char *in, unsigned int inlen,\n                          const unsigned char *client, unsigned int client_len);\n\n/**\n * @brief load the extra certification chain into the SSL context\n *\n * @param ctx  - SSL context point\n * @param x509 - X509 certification\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nlong SSL_CTX_add_extra_chain_cert(SSL_CTX *ctx, X509 *);\n\n/**\n * @brief control the SSL context\n *\n * @param ctx  - SSL context point\n * @param cmd  - command\n * @param larg - parameter length\n * @param parg - parameter point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nlong SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, char *parg);\n\n/**\n * @brief get the SSL context cipher\n *\n * @param ctx - SSL context point\n *\n * @return SSL context cipher\n */\nSTACK *SSL_CTX_get_ciphers(const SSL_CTX *ctx);\n\n/**\n * @brief check if the SSL context can read as many as data\n *\n * @param ctx - SSL context point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nlong SSL_CTX_get_default_read_ahead(SSL_CTX *ctx);\n\n/**\n * @brief get the SSL context extra data\n *\n * @param ctx - SSL context point\n * @param idx - index\n *\n * @return data point\n */\nchar *SSL_CTX_get_ex_data(const SSL_CTX *ctx, int idx);\n\n/**\n * @brief get the SSL context quiet shutdown option\n *\n * @param ctx - SSL context point\n *\n * @return quiet shutdown option\n */\nint SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx);\n\n/**\n * @brief load the SSL context CA file\n *\n * @param ctx    - SSL context point\n * @param CAfile - CA certification file\n * @param CApath - CA certification file path\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile, const char *CApath);\n\n/**\n * @brief add SSL context reference count by '1'\n *\n * @param ctx - SSL context point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_up_ref(SSL_CTX *ctx);\n\n/**\n * @brief set SSL context application private data\n *\n * @param ctx - SSL context point\n * @param arg - private data\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_set_app_data(SSL_CTX *ctx, void *arg);\n\n/**\n * @brief set SSL context client certification callback function\n *\n * @param ctx - SSL context point\n * @param cb  - callback function\n *\n * @return none\n */\nvoid SSL_CTX_set_client_cert_cb(SSL_CTX *ctx, int (*cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey));\n\n/**\n * @brief set the SSL context if we can read as many as data\n *\n * @param ctx - SSL context point\n * @param m   - enable the fuction\n *\n * @return none\n */\nvoid SSL_CTX_set_default_read_ahead(SSL_CTX *ctx, int m);\n\n/**\n * @brief set SSL context default verifying path\n *\n * @param ctx - SSL context point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_set_default_verify_paths(SSL_CTX *ctx);\n\n/**\n * @brief set SSL context default verifying directory\n *\n * @param ctx - SSL context point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_set_default_verify_dir(SSL_CTX *ctx);\n\n/**\n * @brief set SSL context default verifying file\n *\n * @param ctx - SSL context point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_set_default_verify_file(SSL_CTX *ctx);\n\n/**\n * @brief set SSL context extra data\n *\n * @param ctx - SSL context point\n * @param idx - data index\n * @param arg - data point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_set_ex_data(SSL_CTX *s, int idx, char *arg);\n\n/**\n * @brief clear the SSL context option bit of \"op\"\n *\n * @param ctx - SSL context point\n * @param op  - option\n *\n * @return SSL context option\n */\nunsigned long SSL_CTX_clear_options(SSL_CTX *ctx, unsigned long op);\n\n/**\n * @brief get the SSL context option\n *\n * @param ctx - SSL context point\n * @param op  - option\n *\n * @return SSL context option\n */\nunsigned long SSL_CTX_get_options(SSL_CTX *ctx);\n\n/**\n * @brief set the SSL context quiet shutdown mode\n *\n * @param ctx  - SSL context point\n * @param mode - mode\n *\n * @return none\n */\nvoid SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode);\n\n/**\n * @brief get the SSL context X509 certification\n *\n * @param ctx - SSL context point\n *\n * @return X509 certification\n */\nX509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx);\n\n/**\n * @brief get the SSL context private key\n *\n * @param ctx - SSL context point\n *\n * @return private key\n */\nEVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx);\n\n/**\n * @brief set SSL context PSK identity hint\n *\n * @param ctx  - SSL context point\n * @param hint - PSK identity hint\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *hint);\n\n/**\n * @brief set SSL context PSK server callback function\n *\n * @param ctx      - SSL context point\n * @param callback - callback function\n *\n * @return none\n */\nvoid SSL_CTX_set_psk_server_callback(SSL_CTX *ctx,\n                                     unsigned int (*callback)(SSL *ssl,\n                                                              const char *identity,\n                                                              unsigned char *psk,\n                                                              int max_psk_len));\n/**\n * @brief get alert description string\n *\n * @param value - alert value\n *\n * @return alert description string\n */\nconst char *SSL_alert_desc_string(int value);\n\n/**\n * @brief get alert description long string\n *\n * @param value - alert value\n *\n * @return alert description long string\n */\nconst char *SSL_alert_desc_string_long(int value);\n\n/**\n * @brief get alert type string\n *\n * @param value - alert value\n *\n * @return alert type string\n */\nconst char *SSL_alert_type_string(int value);\n\n/**\n * @brief get alert type long string\n *\n * @param value - alert value\n *\n * @return alert type long string\n */\nconst char *SSL_alert_type_string_long(int value);\n\n/**\n * @brief get SSL context of the SSL\n *\n * @param ssl - SSL point\n *\n * @return SSL context\n */\nSSL_CTX *SSL_get_SSL_CTX(const SSL *ssl);\n\n/**\n * @brief get SSL application data\n *\n * @param ssl - SSL point\n *\n * @return application data\n */\nchar *SSL_get_app_data(SSL *ssl);\n\n/**\n * @brief get SSL cipher bits\n *\n * @param ssl - SSL point\n * @param alg_bits - algorithm bits\n *\n * @return strength bits\n */\nint SSL_get_cipher_bits(const SSL *ssl, int *alg_bits);\n\n/**\n * @brief get SSL cipher name\n *\n * @param ssl - SSL point\n *\n * @return SSL cipher name\n */\nchar *SSL_get_cipher_name(const SSL *ssl);\n\n/**\n * @brief get SSL cipher version\n *\n * @param ssl - SSL point\n *\n * @return SSL cipher version\n */\nchar *SSL_get_cipher_version(const SSL *ssl);\n\n/**\n * @brief get SSL extra data\n *\n * @param ssl - SSL point\n * @param idx - data index\n *\n * @return extra data\n */\nchar *SSL_get_ex_data(const SSL *ssl, int idx);\n\n/**\n * @brief get index of the SSL extra data X509 storage context\n *\n * @param none\n *\n * @return data index\n */\nint SSL_get_ex_data_X509_STORE_CTX_idx(void);\n\n/**\n * @brief get peer certification chain\n *\n * @param ssl - SSL point\n *\n * @return certification chain\n */\nSTACK *SSL_get_peer_cert_chain(const SSL *ssl);\n\n/**\n * @brief get peer certification\n *\n * @param ssl - SSL point\n *\n * @return certification\n */\nX509 *SSL_get_peer_certificate(const SSL *ssl);\n\n/**\n * @brief get SSL quiet shutdown mode\n *\n * @param ssl - SSL point\n *\n * @return quiet shutdown mode\n */\nint SSL_get_quiet_shutdown(const SSL *ssl);\n\n/**\n * @brief get SSL read only IO handle\n *\n * @param ssl - SSL point\n *\n * @return IO handle\n */\nBIO *SSL_get_rbio(const SSL *ssl);\n\n/**\n * @brief get SSL shared ciphers\n *\n * @param ssl - SSL point\n * @param buf - buffer to store the ciphers\n * @param len - buffer len\n *\n * @return shared ciphers\n */\nchar *SSL_get_shared_ciphers(const SSL *ssl, char *buf, int len);\n\n/**\n * @brief get SSL shutdown mode\n *\n * @param ssl - SSL point\n *\n * @return shutdown mode\n */\nint SSL_get_shutdown(const SSL *ssl);\n\n/**\n * @brief get SSL session time\n *\n * @param ssl - SSL point\n *\n * @return session time\n */\nlong SSL_get_time(const SSL *ssl);\n\n/**\n * @brief get SSL session timeout time\n *\n * @param ssl - SSL point\n *\n * @return session timeout time\n */\nlong SSL_get_timeout(const SSL *ssl);\n\n/**\n * @brief get SSL verifying mode\n *\n * @param ssl - SSL point\n *\n * @return verifying mode\n */\nint SSL_get_verify_mode(const SSL *ssl);\n\n/**\n * @brief get SSL verify parameters\n *\n * @param ssl - SSL point\n *\n * @return verify parameters\n */\nX509_VERIFY_PARAM *SSL_get0_param(SSL *ssl);\n\n/**\n * @brief set expected hostname the peer cert CN should have\n *\n * @param param - verify parameters from SSL_get0_param()\n *\n * @param name - the expected hostname\n *\n * @param namelen - the length of the hostname, or 0 if NUL terminated\n *\n * @return verify parameters\n */\nint X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param,\n                                const char *name, size_t namelen);\n\n/**\n * @brief set parameters for X509 host verify action\n *\n * @param param -verify parameters from SSL_get0_param()\n *\n * @param flags - bitfield of X509_CHECK_FLAG_... parameters to set\n *\n * @return 1 for success, 0 for failure\n */\nint X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param,\n\t\t\t\t    unsigned long flags);\n\n/**\n * @brief clear parameters for X509 host verify action\n *\n * @param param -verify parameters from SSL_get0_param()\n *\n * @param flags - bitfield of X509_CHECK_FLAG_... parameters to clear\n *\n * @return 1 for success, 0 for failure\n */\nint X509_VERIFY_PARAM_clear_hostflags(X509_VERIFY_PARAM *param,\n\t\t\t\t      unsigned long flags);\n\n/**\n * @brief get SSL write only IO handle\n *\n * @param ssl - SSL point\n *\n * @return IO handle\n */\nBIO *SSL_get_wbio(const SSL *ssl);\n\n/**\n * @brief load SSL client CA certification file\n *\n * @param file - file name\n *\n * @return certification loading object\n */\nSTACK *SSL_load_client_CA_file(const char *file);\n\n/**\n * @brief add SSL reference by '1'\n *\n * @param ssl - SSL point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_up_ref(SSL *ssl);\n\n/**\n * @brief read and put data into buf, but not clear the SSL low-level storage\n *\n * @param ssl - SSL point\n * @param buf - storage buffer point\n * @param num - data bytes\n *\n * @return result\n *     > 0 : OK, and return read bytes\n *     = 0 : connect is closed\n *     < 0 : a error catch\n */\nint SSL_peek(SSL *ssl, void *buf, int num);\n\n/**\n * @brief make SSL renegotiate\n *\n * @param ssl - SSL point\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_renegotiate(SSL *ssl);\n\n/**\n * @brief get the state string where SSL is reading\n *\n * @param ssl - SSL point\n *\n * @return state string\n */\nconst char *SSL_rstate_string(SSL *ssl);\n\n/**\n * @brief get the statement long string where SSL is reading\n *\n * @param ssl - SSL point\n *\n * @return statement long string\n */\nconst char *SSL_rstate_string_long(SSL *ssl);\n\n/**\n * @brief set SSL accept statement\n *\n * @param ssl - SSL point\n *\n * @return none\n */\nvoid SSL_set_accept_state(SSL *ssl);\n\n/**\n * @brief set SSL application data\n *\n * @param ssl - SSL point\n * @param arg - SSL application data point\n *\n * @return none\n */\nvoid SSL_set_app_data(SSL *ssl, char *arg);\n\n/**\n * @brief set SSL BIO\n *\n * @param ssl  - SSL point\n * @param rbio - read only IO\n * @param wbio - write only IO\n *\n * @return none\n */\nvoid SSL_set_bio(SSL *ssl, BIO *rbio, BIO *wbio);\n\n/**\n * @brief clear SSL option\n *\n * @param ssl - SSL point\n * @param op  - clear option\n *\n * @return SSL option\n */\nunsigned long SSL_clear_options(SSL *ssl, unsigned long op);\n\n/**\n * @brief get SSL option\n *\n * @param ssl - SSL point\n *\n * @return SSL option\n */\nunsigned long SSL_get_options(SSL *ssl);\n\n/**\n * @brief clear SSL option\n *\n * @param ssl - SSL point\n * @param op  - setting option\n *\n * @return SSL option\n */\nunsigned long SSL_set_options(SSL *ssl, unsigned long op);\n\n/**\n * @brief set SSL quiet shutdown mode\n *\n * @param ssl  - SSL point\n * @param mode - quiet shutdown mode\n *\n * @return none\n */\nvoid SSL_set_quiet_shutdown(SSL *ssl, int mode);\n\n/**\n * @brief set SSL shutdown mode\n *\n * @param ssl  - SSL point\n * @param mode - shutdown mode\n *\n * @return none\n */\nvoid SSL_set_shutdown(SSL *ssl, int mode);\n\n/**\n * @brief set SSL session time\n *\n * @param ssl - SSL point\n * @param t   - session time\n *\n * @return session time\n */\nvoid SSL_set_time(SSL *ssl, long t);\n\n/**\n * @brief set SSL session timeout time\n *\n * @param ssl - SSL point\n * @param t   - session timeout time\n *\n * @return session timeout time\n */\nvoid SSL_set_timeout(SSL *ssl, long t);\n\n/**\n * @brief get SSL statement string\n *\n * @param ssl - SSL point\n *\n * @return SSL statement string\n */\nchar *SSL_state_string(const SSL *ssl);\n\n/**\n * @brief get SSL statement long string\n *\n * @param ssl - SSL point\n *\n * @return SSL statement long string\n */\nchar *SSL_state_string_long(const SSL *ssl);\n\n/**\n * @brief get SSL renegotiation count\n *\n * @param ssl - SSL point\n *\n * @return renegotiation count\n */\nlong SSL_total_renegotiations(SSL *ssl);\n\n/**\n * @brief get SSL version\n *\n * @param ssl - SSL point\n *\n * @return SSL version\n */\nint SSL_version(const SSL *ssl);\n\n/**\n * @brief set SSL PSK identity hint\n *\n * @param ssl  - SSL point\n * @param hint - identity hint\n *\n * @return result\n *     1 : OK\n *     0 : failed\n */\nint SSL_use_psk_identity_hint(SSL *ssl, const char *hint);\n\n/**\n * @brief get SSL PSK identity hint\n *\n * @param ssl - SSL point\n *\n * @return identity hint\n */\nconst char *SSL_get_psk_identity_hint(SSL *ssl);\n\n/**\n * @brief get SSL PSK identity\n *\n * @param ssl - SSL point\n *\n * @return identity\n */\nconst char *SSL_get_psk_identity(SSL *ssl);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/include/platform/ssl_pm.h",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef _SSL_PM_H_\n#define _SSL_PM_H_\n\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n\n#include <string.h>\n#include \"ssl_types.h\"\n#include \"ssl_port.h\"\n\n#define LOCAL_ATRR\n\nint ssl_pm_new(SSL *ssl);\nvoid ssl_pm_free(SSL *ssl);\n\nint ssl_pm_handshake(SSL *ssl);\nint ssl_pm_shutdown(SSL *ssl);\nint ssl_pm_clear(SSL *ssl);\n\nint ssl_pm_read(SSL *ssl, void *buffer, int len);\nint ssl_pm_send(SSL *ssl, const void *buffer, int len);\nint ssl_pm_pending(const SSL *ssl);\n\nvoid ssl_pm_set_fd(SSL *ssl, int fd, int mode);\nint ssl_pm_get_fd(const SSL *ssl, int mode);\n\nOSSL_HANDSHAKE_STATE ssl_pm_get_state(const SSL *ssl);\n\nvoid ssl_pm_set_bufflen(SSL *ssl, int len);\n\nint x509_pm_show_info(X509 *x);\nint x509_pm_new(X509 *x, X509 *m_x);\nvoid x509_pm_free(X509 *x);\nint x509_pm_load(X509 *x, const unsigned char *buffer, int len);\n\nint pkey_pm_new(EVP_PKEY *pk, EVP_PKEY *m_pk);\nvoid pkey_pm_free(EVP_PKEY *pk);\nint pkey_pm_load(EVP_PKEY *pk, const unsigned char *buffer, int len);\n\nlong ssl_pm_get_verify_result(const SSL *ssl);\n\n#ifdef __cplusplus\n }\n#endif\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/include/platform/ssl_port.h",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef _SSL_PORT_H_\n#define _SSL_PORT_H_\n\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n\n#include \"string.h\"\n#include \"stdlib.h\"\n#if defined(LWS_HAVE_MALLOC_H)\n#include \"malloc.h\"\n#endif\n\nvoid *ssl_mem_zalloc(size_t size);\n\n#define ssl_mem_malloc malloc\n#define ssl_mem_free   free\n\n#define ssl_memcpy     memcpy\n#define ssl_strlen     strlen\n\n#define ssl_speed_up_enter()\n#define ssl_speed_up_exit()\n\n#define SSL_DEBUG_FL\n#define SSL_DEBUG_LOG(fmt, ...) ESP_LOGI(\"openssl\", fmt, ##__VA_ARGS__)\n\n#ifdef __cplusplus\n }\n#endif\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/library/ssl_cert.c",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"ssl_cert.h\"\n#include \"ssl_pkey.h\"\n#include \"ssl_x509.h\"\n#include \"ssl_dbg.h\"\n#include \"ssl_port.h\"\n\n/**\n * @brief create a certification object according to input certification\n */\nCERT *__ssl_cert_new(CERT *ic)\n{\n    CERT *cert;\n\n    X509 *ix;\n    EVP_PKEY *ipk;\n\n    cert = ssl_mem_zalloc(sizeof(CERT));\n    if (!cert) {\n        SSL_DEBUG(SSL_CERT_ERROR_LEVEL, \"no enough memory > (cert)\");\n        goto no_mem;\n    }\n\n    if (ic) {\n        ipk = ic->pkey;\n        ix = ic->x509;\n    } else {\n        ipk = NULL;\n        ix = NULL;\n    }\n\n    cert->pkey = __EVP_PKEY_new(ipk);\n    if (!cert->pkey) {\n        SSL_DEBUG(SSL_CERT_ERROR_LEVEL, \"__EVP_PKEY_new() return NULL\");\n        goto pkey_err;\n    }\n\n    cert->x509 = __X509_new(ix);\n    if (!cert->x509) {\n        SSL_DEBUG(SSL_CERT_ERROR_LEVEL, \"__X509_new() return NULL\");\n        goto x509_err;\n    }\n\n    return cert;\n\nx509_err:\n    EVP_PKEY_free(cert->pkey);\npkey_err:\n    ssl_mem_free(cert);\nno_mem:\n    return NULL;\n}\n\n/**\n * @brief create a certification object include private key object\n */\nCERT *ssl_cert_new(void)\n{\n    return __ssl_cert_new(NULL);\n}\n\n/**\n * @brief free a certification object\n */\nvoid ssl_cert_free(CERT *cert)\n{\n    SSL_ASSERT3(cert);\n\n    X509_free(cert->x509);\n\n    EVP_PKEY_free(cert->pkey);\n\n    ssl_mem_free(cert);\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/library/ssl_lib.c",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"ssl_lib.h\"\n#include \"ssl_pkey.h\"\n#include \"ssl_x509.h\"\n#include \"ssl_cert.h\"\n#include \"ssl_dbg.h\"\n#include \"ssl_port.h\"\n\nchar *\nlws_strncpy(char *dest, const char *src, size_t size);\n\n#define SSL_SEND_DATA_MAX_LENGTH 1460\n\n/**\n * @brief create a new SSL session object\n */\nstatic SSL_SESSION* SSL_SESSION_new(void)\n{\n    SSL_SESSION *session;\n\n    session = ssl_mem_zalloc(sizeof(SSL_SESSION));\n    if (!session) {\n        SSL_DEBUG(SSL_LIB_ERROR_LEVEL, \"no enough memory > (session)\");\n        goto failed1;\n    }\n\n    session->peer = X509_new();\n    if (!session->peer) {\n       SSL_DEBUG(SSL_LIB_ERROR_LEVEL, \"X509_new() return NULL\");\n       goto failed2;\n    }\n\n    return session;\n\nfailed2:\n    ssl_mem_free(session);\nfailed1:\n    return NULL;\n}\n\n/**\n * @brief free a new SSL session object\n */\nstatic void SSL_SESSION_free(SSL_SESSION *session)\n{\n    X509_free(session->peer);\n    ssl_mem_free(session);\n}\n\n/**\n * @brief Discover whether the current connection is in the error state\n */\nint ossl_statem_in_error(const SSL *ssl)\n{\n    SSL_ASSERT1(ssl);\n\n    if (ssl->statem.state == MSG_FLOW_ERROR)\n        return 1;\n\n    return 0;\n}\n\n/**\n * @brief get the SSL specifical statement\n */\nint SSL_want(const SSL *ssl)\n{\n    SSL_ASSERT1(ssl);\n\n    return ssl->rwstate;\n}\n\n/**\n * @brief check if SSL want nothing\n */\nint SSL_want_nothing(const SSL *ssl)\n{\n    SSL_ASSERT1(ssl);\n\n    if (ssl->err)\n\t    return 1;\n\n    return (SSL_want(ssl) == SSL_NOTHING);\n}\n\n/**\n * @brief check if SSL want to read\n */\nint SSL_want_read(const SSL *ssl)\n{\n    SSL_ASSERT1(ssl);\n\n    if (ssl->err)\n\t    return 0;\n\n    return (SSL_want(ssl) == SSL_READING);\n}\n\n/**\n * @brief check if SSL want to write\n */\nint SSL_want_write(const SSL *ssl)\n{\n    SSL_ASSERT1(ssl);\n\n    if (ssl->err)\n\t    return 0;\n\n    return (SSL_want(ssl) == SSL_WRITING);\n}\n\n/**\n * @brief check if SSL want to lookup X509 certification\n */\nint SSL_want_x509_lookup(const SSL *ssl)\n{\n    SSL_ASSERT1(ssl);\n\n    return (SSL_want(ssl) == SSL_WRITING);\n}\n\n/**\n * @brief get SSL error code\n */\nint SSL_get_error(const SSL *ssl, int ret_code)\n{\n    int ret = SSL_ERROR_SYSCALL;\n\n    SSL_ASSERT1(ssl);\n\n    if (ret_code > 0)\n        ret = SSL_ERROR_NONE;\n    else if (ret_code < 0)\n    {\n        if (ssl->err == SSL_ERROR_WANT_READ || SSL_want_read(ssl))\n            ret = SSL_ERROR_WANT_READ;\n        else if (ssl->err == SSL_ERROR_WANT_WRITE || SSL_want_write(ssl))\n            ret = SSL_ERROR_WANT_WRITE;\n        else\n            ret = SSL_ERROR_SYSCALL; //unknown\n    }\n    else // ret_code == 0\n    {\n        if (ssl->shutdown & SSL_RECEIVED_SHUTDOWN)\n            ret = SSL_ERROR_ZERO_RETURN;\n        else\n            ret = SSL_ERROR_SYSCALL;\n    }\n\n    return ret;\n}\n\n/**\n * @brief get the SSL state\n */\nOSSL_HANDSHAKE_STATE SSL_get_state(const SSL *ssl)\n{\n    OSSL_HANDSHAKE_STATE state;\n\n    SSL_ASSERT1(ssl);\n\n    state = SSL_METHOD_CALL(get_state, ssl);\n\n    return state;\n}\n\n/**\n * @brief create a SSL context\n */\nSSL_CTX* SSL_CTX_new(const SSL_METHOD *method)\n{\n    SSL_CTX *ctx;\n    CERT *cert;\n    X509 *client_ca;\n\n    if (!method) {\n        SSL_DEBUG(SSL_LIB_ERROR_LEVEL, \"no no_method\");\n        return NULL;\n    }\n\n    client_ca = X509_new();\n    if (!client_ca) {\n        SSL_DEBUG(SSL_LIB_ERROR_LEVEL, \"X509_new() return NULL\");\n        goto failed1;\n    }\n\n    cert = ssl_cert_new();\n    if (!cert) {\n        SSL_DEBUG(SSL_LIB_ERROR_LEVEL, \"ssl_cert_new() return NULL\");\n        goto failed2;\n    }\n\n    ctx = (SSL_CTX *)ssl_mem_zalloc(sizeof(SSL_CTX));\n    if (!ctx) {\n        SSL_DEBUG(SSL_LIB_ERROR_LEVEL, \"no enough memory > (ctx)\");\n        goto failed3;\n    }\n\n    ctx->method = method;\n    ctx->client_CA = client_ca;\n    ctx->cert = cert;\n\n    ctx->version = method->version;\n\n    return ctx;\n\nfailed3:\n    ssl_cert_free(cert);\nfailed2:\n    X509_free(client_ca);\nfailed1:\n    return NULL;\n}\n\n/**\n * @brief free a SSL context\n */\nvoid SSL_CTX_free(SSL_CTX* ctx)\n{\n    SSL_ASSERT3(ctx);\n\n    ssl_cert_free(ctx->cert);\n\n    X509_free(ctx->client_CA);\n\n    if (ctx->alpn_protos)\n\t    ssl_mem_free(ctx->alpn_protos);\n\n    ssl_mem_free(ctx);\n}\n\n/**\n * @brief set  the SSL context version\n */\nint SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth)\n{\n    SSL_ASSERT1(ctx);\n    SSL_ASSERT1(meth);\n\n    ctx->method = meth;\n\n    ctx->version = meth->version;\n\n    return 1;\n}\n\n/**\n * @brief get the SSL context current method\n */\nconst SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx)\n{\n    SSL_ASSERT2(ctx);\n\n    return ctx->method;\n}\n\n/**\n * @brief create a SSL\n */\nSSL *SSL_new(SSL_CTX *ctx)\n{\n    int ret = 0;\n    SSL *ssl;\n\n    if (!ctx) {\n        SSL_DEBUG(SSL_LIB_ERROR_LEVEL, \"no ctx\");\n        return NULL;\n    }\n\n    ssl = (SSL *)ssl_mem_zalloc(sizeof(SSL));\n    if (!ssl) {\n        SSL_DEBUG(SSL_LIB_ERROR_LEVEL, \"no enough memory > (ssl)\");\n        goto failed1;\n    }\n\n    ssl->session = SSL_SESSION_new();\n    if (!ssl->session) {\n        SSL_DEBUG(SSL_LIB_ERROR_LEVEL, \"SSL_SESSION_new() return NULL\");\n        goto failed2;\n    }\n\n    ssl->cert = __ssl_cert_new(ctx->cert);\n    if (!ssl->cert) {\n        SSL_DEBUG(SSL_LIB_ERROR_LEVEL, \"__ssl_cert_new() return NULL\");\n        goto failed3;\n    }\n\n    ssl->client_CA = __X509_new(ctx->client_CA);\n    if (!ssl->client_CA) {\n        SSL_DEBUG(SSL_LIB_ERROR_LEVEL, \"__X509_new() return NULL\");\n        goto failed4;\n    }\n\n    ssl->ctx = ctx;\n    ssl->method = ctx->method;\n\n    ssl->version = ctx->version;\n    ssl->options = ctx->options;\n\n    ssl->verify_mode = ctx->verify_mode;\n\n    ret = SSL_METHOD_CALL(new, ssl);\n    if (ret) {\n        SSL_DEBUG(SSL_LIB_ERROR_LEVEL, \"SSL_METHOD_CALL(new) return %d\", ret);\n        goto failed5;\n    }\n\n   _ssl_set_alpn_list(ssl);\n\n    ssl->rwstate = SSL_NOTHING;\n\n    return ssl;\n\nfailed5:\n    X509_free(ssl->client_CA);\nfailed4:\n    ssl_cert_free(ssl->cert);\nfailed3:\n    SSL_SESSION_free(ssl->session);\nfailed2:\n    ssl_mem_free(ssl);\nfailed1:\n    return NULL;\n}\n\n/**\n * @brief free the SSL\n */\nvoid SSL_free(SSL *ssl)\n{\n    SSL_ASSERT3(ssl);\n\n    SSL_METHOD_CALL(free, ssl);\n\n    X509_free(ssl->client_CA);\n\n    ssl_cert_free(ssl->cert);\n\n    SSL_SESSION_free(ssl->session);\n\n    if (ssl->alpn_protos)\n\t    ssl_mem_free(ssl->alpn_protos);\n\n    ssl_mem_free(ssl);\n}\n\n/**\n * @brief perform the SSL handshake\n */\nint SSL_do_handshake(SSL *ssl)\n{\n    int ret;\n\n    SSL_ASSERT1(ssl);\n\n    ret = SSL_METHOD_CALL(handshake, ssl);\n\n    return ret;\n}\n\n/**\n * @brief connect to the remote SSL server\n */\nint SSL_connect(SSL *ssl)\n{\n    SSL_ASSERT1(ssl);\n\n    return SSL_do_handshake(ssl);\n}\n\n/**\n * @brief accept the remote connection\n */\nint SSL_accept(SSL *ssl)\n{\n    SSL_ASSERT1(ssl);\n\n    return SSL_do_handshake(ssl);\n}\n\n/**\n * @brief shutdown the connection\n */\nint SSL_shutdown(SSL *ssl)\n{\n    int ret;\n\n    SSL_ASSERT1(ssl);\n\n    if (SSL_get_state(ssl) != TLS_ST_OK) return 1;\n\n    ret = SSL_METHOD_CALL(shutdown, ssl);\n\n    return ret;\n}\n\n/**\n * @brief reset the SSL\n */\nint SSL_clear(SSL *ssl)\n{\n    int ret;\n\n    SSL_ASSERT1(ssl);\n\n    ret = SSL_shutdown(ssl);\n    if (1 != ret) {\n        SSL_DEBUG(SSL_LIB_ERROR_LEVEL, \"SSL_shutdown return %d\", ret);\n        goto failed1;\n    }\n\n    SSL_METHOD_CALL(free, ssl);\n\n    ret = SSL_METHOD_CALL(new, ssl);\n    if (!ret) {\n        SSL_DEBUG(SSL_LIB_ERROR_LEVEL, \"SSL_METHOD_CALL(new) return %d\", ret);\n        goto failed1;\n    }\n\n    return 1;\n\nfailed1:\n    return ret;\n}\n\n/**\n * @brief read data from to remote\n */\nint SSL_read(SSL *ssl, void *buffer, int len)\n{\n    int ret;\n\n    SSL_ASSERT1(ssl);\n    SSL_ASSERT1(buffer);\n    SSL_ASSERT1(len);\n\n    ssl->rwstate = SSL_READING;\n\n    ret = SSL_METHOD_CALL(read, ssl, buffer, len);\n\n    if (ret == len)\n        ssl->rwstate = SSL_NOTHING;\n\n    return ret;\n}\n\n/**\n * @brief send the data to remote\n */\nint SSL_write(SSL *ssl, const void *buffer, int len)\n{\n    int ret;\n    int send_bytes, bytes;\n    const unsigned char *pbuf;\n\n    SSL_ASSERT1(ssl);\n    SSL_ASSERT1(buffer);\n    SSL_ASSERT1(len);\n\n    ssl->rwstate = SSL_WRITING;\n\n    send_bytes = len;\n    pbuf = (const unsigned char *)buffer;\n\n    do {\n        if (send_bytes > SSL_SEND_DATA_MAX_LENGTH)\n            bytes = SSL_SEND_DATA_MAX_LENGTH;\n        else\n            bytes = send_bytes;\n\n\tif (ssl->interrupted_remaining_write) {\n\t\tbytes = ssl->interrupted_remaining_write;\n\t\tssl->interrupted_remaining_write = 0;\n\t}\n\n        ret = SSL_METHOD_CALL(send, ssl, pbuf, bytes);\n\t//printf(\"%s: ssl_pm said %d for %d requested (cum %d)\\n\", __func__, ret, bytes, len -send_bytes);\n        /* the return is a NEGATIVE OpenSSL error code, or the length sent */\n        if (ret > 0) {\n            pbuf += ret;\n            send_bytes -= ret;\n        } else\n\t\tssl->interrupted_remaining_write = bytes;\n    } while (ret > 0 && send_bytes && ret == bytes);\n\n    if (ret >= 0) {\n        ret = len - send_bytes;\n\tif (!ret)\n\t        ssl->rwstate = SSL_NOTHING;\n    } else {\n\t    if (send_bytes == len)\n\t\tret = -1;\n\t    else\n\t\t    ret = len - send_bytes;\n    }\n\n    return ret;\n}\n\n/**\n * @brief get SSL context of the SSL\n */\nSSL_CTX *SSL_get_SSL_CTX(const SSL *ssl)\n{\n    SSL_ASSERT2(ssl);\n\n    return ssl->ctx;\n}\n\n/**\n * @brief get the SSL current method\n */\nconst SSL_METHOD *SSL_get_ssl_method(SSL *ssl)\n{\n    SSL_ASSERT2(ssl);\n\n    return ssl->method;\n}\n\n/**\n * @brief set the SSL method\n */\nint SSL_set_ssl_method(SSL *ssl, const SSL_METHOD *method)\n{\n    int ret;\n\n    SSL_ASSERT1(ssl);\n    SSL_ASSERT1(method);\n\n    if (ssl->version != method->version) {\n\n        ret = SSL_shutdown(ssl);\n        if (1 != ret) {\n            SSL_DEBUG(SSL_LIB_ERROR_LEVEL, \"SSL_shutdown return %d\", ret);\n            goto failed1;\n        }\n\n        SSL_METHOD_CALL(free, ssl);\n\n        ssl->method = method;\n\n        ret = SSL_METHOD_CALL(new, ssl);\n        if (!ret) {\n            SSL_DEBUG(SSL_LIB_ERROR_LEVEL, \"SSL_METHOD_CALL(new) return %d\", ret);\n            goto failed1;\n        }\n    } else {\n        ssl->method = method;\n    }\n\n\n    return 1;\n\nfailed1:\n    return ret;\n}\n\n/**\n * @brief get SSL shutdown mode\n */\nint SSL_get_shutdown(const SSL *ssl)\n{\n    SSL_ASSERT1(ssl);\n\n    return ssl->shutdown;\n}\n\n/**\n * @brief set SSL shutdown mode\n */\nvoid SSL_set_shutdown(SSL *ssl, int mode)\n{\n    SSL_ASSERT3(ssl);\n\n    ssl->shutdown = mode;\n}\n\n\n/**\n * @brief get the number of the bytes to be read\n */\nint SSL_pending(const SSL *ssl)\n{\n    int ret;\n\n    SSL_ASSERT1(ssl);\n\n    ret = SSL_METHOD_CALL(pending, ssl);\n\n    return ret;\n}\n\n/**\n * @brief check if some data can be read\n */\nint SSL_has_pending(const SSL *ssl)\n{\n    int ret;\n\n    SSL_ASSERT1(ssl);\n\n    if (SSL_pending(ssl))\n        ret = 1;\n    else\n        ret = 0;\n\n    return ret;\n}\n\n/**\n * @brief clear the SSL context option bit of \"op\"\n */\nunsigned long SSL_CTX_clear_options(SSL_CTX *ctx, unsigned long op)\n{\n    SSL_ASSERT1(ctx);\n\n    return ctx->options &= ~op;\n}\n\n/**\n * @brief get the SSL context option\n */\nunsigned long SSL_CTX_get_options(SSL_CTX *ctx)\n{\n    SSL_ASSERT1(ctx);\n\n    return ctx->options;\n}\n\n/**\n * @brief set the option of the SSL context\n */\nunsigned long SSL_CTX_set_options(SSL_CTX *ctx, unsigned long opt)\n{\n    SSL_ASSERT1(ctx);\n\n    return ctx->options |= opt;\n}\n\n/**\n * @brief clear SSL option\n */\nunsigned long SSL_clear_options(SSL *ssl, unsigned long op)\n{\n    SSL_ASSERT1(ssl);\n\n    return ssl->options & ~op;\n}\n\n/**\n * @brief get SSL option\n */\nunsigned long SSL_get_options(SSL *ssl)\n{\n    SSL_ASSERT1(ssl);\n\n    return ssl->options;\n}\n\n/**\n * @brief clear SSL option\n */\nunsigned long SSL_set_options(SSL *ssl, unsigned long op)\n{\n    SSL_ASSERT1(ssl);\n\n    return ssl->options |= op;\n}\n\n/**\n * @brief get the socket handle of the SSL\n */\nint SSL_get_fd(const SSL *ssl)\n{\n    int ret;\n\n    SSL_ASSERT1(ssl);\n\n    ret = SSL_METHOD_CALL(get_fd, ssl, 0);\n\n    return ret;\n}\n\n/**\n * @brief get the read only socket handle of the SSL\n */\nint SSL_get_rfd(const SSL *ssl)\n{\n    int ret;\n\n    SSL_ASSERT1(ssl);\n\n    ret = SSL_METHOD_CALL(get_fd, ssl, 0);\n\n    return ret;\n}\n\n/**\n * @brief get the write only socket handle of the SSL\n */\nint SSL_get_wfd(const SSL *ssl)\n{\n    int ret;\n\n    SSL_ASSERT1(ssl);\n\n    ret = SSL_METHOD_CALL(get_fd, ssl, 0);\n\n    return ret;\n}\n\n/**\n * @brief bind the socket file description into the SSL\n */\nint SSL_set_fd(SSL *ssl, int fd)\n{\n    SSL_ASSERT1(ssl);\n    SSL_ASSERT1(fd >= 0);\n\n    SSL_METHOD_CALL(set_fd, ssl, fd, 0);\n\n    return 1;\n}\n\n/**\n * @brief bind the read only socket file description into the SSL\n */\nint SSL_set_rfd(SSL *ssl, int fd)\n{\n    SSL_ASSERT1(ssl);\n    SSL_ASSERT1(fd >= 0);\n\n    SSL_METHOD_CALL(set_fd, ssl, fd, 0);\n\n    return 1;\n}\n\n/**\n * @brief bind the write only socket file description into the SSL\n */\nint SSL_set_wfd(SSL *ssl, int fd)\n{\n    SSL_ASSERT1(ssl);\n    SSL_ASSERT1(fd >= 0);\n\n    SSL_METHOD_CALL(set_fd, ssl, fd, 0);\n\n    return 1;\n}\n\n/**\n * @brief get SSL version\n */\nint SSL_version(const SSL *ssl)\n{\n    SSL_ASSERT1(ssl);\n\n    return ssl->version;\n}\n\n/**\n * @brief get the SSL version string\n */\nstatic const char* ssl_protocol_to_string(int version)\n{\n    const char *str;\n\n    if (version == TLS1_2_VERSION)\n        str = \"TLSv1.2\";\n    else if (version == TLS1_1_VERSION)\n        str = \"TLSv1.1\";\n    else if (version == TLS1_VERSION)\n        str = \"TLSv1\";\n    else if (version == SSL3_VERSION)\n        str = \"SSLv3\";\n    else\n        str = \"unknown\";\n\n    return str;\n}\n\n/**\n * @brief get the SSL current version\n */\nconst char *SSL_get_version(const SSL *ssl)\n{\n    SSL_ASSERT2(ssl);\n\n    return ssl_protocol_to_string(SSL_version(ssl));\n}\n\n/**\n * @brief get alert description string\n */\nconst char* SSL_alert_desc_string(int value)\n{\n    const char *str;\n\n    switch (value & 0xff)\n    {\n        case SSL3_AD_CLOSE_NOTIFY:\n            str = \"CN\";\n            break;\n        case SSL3_AD_UNEXPECTED_MESSAGE:\n            str = \"UM\";\n            break;\n        case SSL3_AD_BAD_RECORD_MAC:\n            str = \"BM\";\n            break;\n        case SSL3_AD_DECOMPRESSION_FAILURE:\n            str = \"DF\";\n            break;\n        case SSL3_AD_HANDSHAKE_FAILURE:\n            str = \"HF\";\n            break;\n        case SSL3_AD_NO_CERTIFICATE:\n            str = \"NC\";\n            break;\n        case SSL3_AD_BAD_CERTIFICATE:\n            str = \"BC\";\n            break;\n        case SSL3_AD_UNSUPPORTED_CERTIFICATE:\n            str = \"UC\";\n            break;\n        case SSL3_AD_CERTIFICATE_REVOKED:\n            str = \"CR\";\n            break;\n        case SSL3_AD_CERTIFICATE_EXPIRED:\n            str = \"CE\";\n            break;\n        case SSL3_AD_CERTIFICATE_UNKNOWN:\n            str = \"CU\";\n            break;\n        case SSL3_AD_ILLEGAL_PARAMETER:\n            str = \"IP\";\n            break;\n        case TLS1_AD_DECRYPTION_FAILED:\n            str = \"DC\";\n            break;\n        case TLS1_AD_RECORD_OVERFLOW:\n            str = \"RO\";\n            break;\n        case TLS1_AD_UNKNOWN_CA:\n            str = \"CA\";\n            break;\n        case TLS1_AD_ACCESS_DENIED:\n            str = \"AD\";\n            break;\n        case TLS1_AD_DECODE_ERROR:\n            str = \"DE\";\n            break;\n        case TLS1_AD_DECRYPT_ERROR:\n            str = \"CY\";\n            break;\n        case TLS1_AD_EXPORT_RESTRICTION:\n            str = \"ER\";\n            break;\n        case TLS1_AD_PROTOCOL_VERSION:\n            str = \"PV\";\n            break;\n        case TLS1_AD_INSUFFICIENT_SECURITY:\n            str = \"IS\";\n            break;\n        case TLS1_AD_INTERNAL_ERROR:\n            str = \"IE\";\n            break;\n        case TLS1_AD_USER_CANCELLED:\n            str = \"US\";\n            break;\n        case TLS1_AD_NO_RENEGOTIATION:\n            str = \"NR\";\n            break;\n        case TLS1_AD_UNSUPPORTED_EXTENSION:\n            str = \"UE\";\n            break;\n        case TLS1_AD_CERTIFICATE_UNOBTAINABLE:\n            str = \"CO\";\n            break;\n        case TLS1_AD_UNRECOGNIZED_NAME:\n            str = \"UN\";\n            break;\n        case TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE:\n            str = \"BR\";\n            break;\n        case TLS1_AD_BAD_CERTIFICATE_HASH_VALUE:\n            str = \"BH\";\n            break;\n        case TLS1_AD_UNKNOWN_PSK_IDENTITY:\n            str = \"UP\";\n            break;\n        default:\n            str = \"UK\";\n            break;\n    }\n\n    return str;\n}\n\n/**\n * @brief get alert description long string\n */\nconst char* SSL_alert_desc_string_long(int value)\n{\n    const char *str;\n\n    switch (value & 0xff)\n    {\n        case SSL3_AD_CLOSE_NOTIFY:\n            str = \"close notify\";\n            break;\n        case SSL3_AD_UNEXPECTED_MESSAGE:\n            str = \"unexpected_message\";\n            break;\n        case SSL3_AD_BAD_RECORD_MAC:\n            str = \"bad record mac\";\n            break;\n        case SSL3_AD_DECOMPRESSION_FAILURE:\n            str = \"decompression failure\";\n            break;\n        case SSL3_AD_HANDSHAKE_FAILURE:\n            str = \"handshake failure\";\n            break;\n        case SSL3_AD_NO_CERTIFICATE:\n            str = \"no certificate\";\n            break;\n        case SSL3_AD_BAD_CERTIFICATE:\n            str = \"bad certificate\";\n            break;\n        case SSL3_AD_UNSUPPORTED_CERTIFICATE:\n            str = \"unsupported certificate\";\n            break;\n        case SSL3_AD_CERTIFICATE_REVOKED:\n            str = \"certificate revoked\";\n            break;\n        case SSL3_AD_CERTIFICATE_EXPIRED:\n            str = \"certificate expired\";\n            break;\n        case SSL3_AD_CERTIFICATE_UNKNOWN:\n            str = \"certificate unknown\";\n            break;\n        case SSL3_AD_ILLEGAL_PARAMETER:\n            str = \"illegal parameter\";\n            break;\n        case TLS1_AD_DECRYPTION_FAILED:\n            str = \"decryption failed\";\n            break;\n        case TLS1_AD_RECORD_OVERFLOW:\n            str = \"record overflow\";\n            break;\n        case TLS1_AD_UNKNOWN_CA:\n            str = \"unknown CA\";\n            break;\n        case TLS1_AD_ACCESS_DENIED:\n            str = \"access denied\";\n            break;\n        case TLS1_AD_DECODE_ERROR:\n            str = \"decode error\";\n            break;\n        case TLS1_AD_DECRYPT_ERROR:\n            str = \"decrypt error\";\n            break;\n        case TLS1_AD_EXPORT_RESTRICTION:\n            str = \"export restriction\";\n            break;\n        case TLS1_AD_PROTOCOL_VERSION:\n            str = \"protocol version\";\n            break;\n        case TLS1_AD_INSUFFICIENT_SECURITY:\n            str = \"insufficient security\";\n            break;\n        case TLS1_AD_INTERNAL_ERROR:\n            str = \"internal error\";\n            break;\n        case TLS1_AD_USER_CANCELLED:\n            str = \"user canceled\";\n            break;\n        case TLS1_AD_NO_RENEGOTIATION:\n            str = \"no renegotiation\";\n            break;\n        case TLS1_AD_UNSUPPORTED_EXTENSION:\n            str = \"unsupported extension\";\n            break;\n        case TLS1_AD_CERTIFICATE_UNOBTAINABLE:\n            str = \"certificate unobtainable\";\n            break;\n        case TLS1_AD_UNRECOGNIZED_NAME:\n            str = \"unrecognized name\";\n            break;\n        case TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE:\n            str = \"bad certificate status response\";\n            break;\n        case TLS1_AD_BAD_CERTIFICATE_HASH_VALUE:\n            str = \"bad certificate hash value\";\n            break;\n        case TLS1_AD_UNKNOWN_PSK_IDENTITY:\n            str = \"unknown PSK identity\";\n            break;\n        default:\n            str = \"unknown\";\n            break;\n    }\n\n    return str;\n}\n\n/**\n * @brief get alert type string\n */\nconst char *SSL_alert_type_string(int value)\n{\n    const char *str;\n\n    switch (value >> 8)\n    {\n    case SSL3_AL_WARNING:\n        str = \"W\";\n        break;\n    case SSL3_AL_FATAL:\n        str = \"F\";\n        break;\n    default:\n        str = \"U\";\n        break;\n    }\n\n    return str;\n}\n\n/**\n * @brief get alert type long string\n */\nconst char *SSL_alert_type_string_long(int value)\n{\n    const char *str;\n\n    switch (value >> 8)\n    {\n        case SSL3_AL_WARNING:\n            str = \"warning\";\n            break;\n        case SSL3_AL_FATAL:\n            str = \"fatal\";\n            break;\n        default:\n            str = \"unknown\";\n            break;\n    }\n\n    return str;\n}\n\n/**\n * @brief get the state string where SSL is reading\n */\nconst char *SSL_rstate_string(SSL *ssl)\n{\n    const char *str;\n\n    SSL_ASSERT2(ssl);\n\n    switch (ssl->rlayer.rstate)\n    {\n        case SSL_ST_READ_HEADER:\n            str = \"RH\";\n            break;\n        case SSL_ST_READ_BODY:\n            str = \"RB\";\n            break;\n        case SSL_ST_READ_DONE:\n            str = \"RD\";\n            break;\n        default:\n            str = \"unknown\";\n            break;\n    }\n\n    return str;\n}\n\n/**\n * @brief get the statement long string where SSL is reading\n */\nconst char *SSL_rstate_string_long(SSL *ssl)\n{\n    const char *str = \"unknown\";\n\n    SSL_ASSERT2(ssl);\n\n    switch (ssl->rlayer.rstate)\n    {\n        case SSL_ST_READ_HEADER:\n            str = \"read header\";\n            break;\n        case SSL_ST_READ_BODY:\n            str = \"read body\";\n            break;\n        case SSL_ST_READ_DONE:\n            str = \"read done\";\n            break;\n        default:\n            break;\n    }\n\n    return str;\n}\n\n/**\n * @brief get SSL statement string\n */\nchar *SSL_state_string(const SSL *ssl)\n{\n    char *str = \"UNKWN \";\n\n    SSL_ASSERT2(ssl);\n\n    if (ossl_statem_in_error(ssl))\n        str = \"SSLERR\";\n    else\n    {\n        switch (SSL_get_state(ssl))\n        {\n            case TLS_ST_BEFORE:\n                str = \"PINIT \";\n                break;\n            case TLS_ST_OK:\n                str =  \"SSLOK \";\n                break;\n            case TLS_ST_CW_CLNT_HELLO:\n                str = \"TWCH\";\n                break;\n            case TLS_ST_CR_SRVR_HELLO:\n                str = \"TRSH\";\n                break;\n            case TLS_ST_CR_CERT:\n                str = \"TRSC\";\n                break;\n            case TLS_ST_CR_KEY_EXCH:\n                str = \"TRSKE\";\n                break;\n            case TLS_ST_CR_CERT_REQ:\n                str = \"TRCR\";\n                break;\n            case TLS_ST_CR_SRVR_DONE:\n                str = \"TRSD\";\n                break;\n            case TLS_ST_CW_CERT:\n                str = \"TWCC\";\n                break;\n            case TLS_ST_CW_KEY_EXCH:\n                str = \"TWCKE\";\n                break;\n            case TLS_ST_CW_CERT_VRFY:\n                str = \"TWCV\";\n                break;\n            case TLS_ST_SW_CHANGE:\n            case TLS_ST_CW_CHANGE:\n                str = \"TWCCS\";\n                break;\n            case TLS_ST_SW_FINISHED:\n            case TLS_ST_CW_FINISHED:\n                str = \"TWFIN\";\n                break;\n            case TLS_ST_SR_CHANGE:\n            case TLS_ST_CR_CHANGE:\n                str = \"TRCCS\";\n                break;\n            case TLS_ST_SR_FINISHED:\n            case TLS_ST_CR_FINISHED:\n                str = \"TRFIN\";\n                break;\n            case TLS_ST_SW_HELLO_REQ:\n                str = \"TWHR\";\n                break;\n            case TLS_ST_SR_CLNT_HELLO:\n                str = \"TRCH\";\n                break;\n            case TLS_ST_SW_SRVR_HELLO:\n                str = \"TWSH\";\n                break;\n            case TLS_ST_SW_CERT:\n                str = \"TWSC\";\n                break;\n            case TLS_ST_SW_KEY_EXCH:\n                str = \"TWSKE\";\n                break;\n            case TLS_ST_SW_CERT_REQ:\n                str = \"TWCR\";\n                break;\n            case TLS_ST_SW_SRVR_DONE:\n                str = \"TWSD\";\n                break;\n            case TLS_ST_SR_CERT:\n                str = \"TRCC\";\n                break;\n            case TLS_ST_SR_KEY_EXCH:\n                str = \"TRCKE\";\n                break;\n            case TLS_ST_SR_CERT_VRFY:\n                str = \"TRCV\";\n                break;\n            case DTLS_ST_CR_HELLO_VERIFY_REQUEST:\n                str = \"DRCHV\";\n                break;\n            case DTLS_ST_SW_HELLO_VERIFY_REQUEST:\n                str = \"DWCHV\";\n                break;\n            default:\n                break;\n        }\n    }\n\n    return str;\n}\n\n/**\n * @brief get SSL statement long string\n */\nchar *SSL_state_string_long(const SSL *ssl)\n{\n    char *str = \"UNKWN \";\n\n    SSL_ASSERT2(ssl);\n\n    if (ossl_statem_in_error(ssl))\n        str = \"SSLERR\";\n    else\n    {\n        switch (SSL_get_state(ssl))\n        {\n            case TLS_ST_BEFORE:\n                str = \"before SSL initialization\";\n                break;\n            case TLS_ST_OK:\n                str = \"SSL negotiation finished successfully\";\n                break;\n            case TLS_ST_CW_CLNT_HELLO:\n                str = \"SSLv3/TLS write client hello\";\n                break;\n            case TLS_ST_CR_SRVR_HELLO:\n                str = \"SSLv3/TLS read server hello\";\n                break;\n            case TLS_ST_CR_CERT:\n                str = \"SSLv3/TLS read server certificate\";\n                break;\n            case TLS_ST_CR_KEY_EXCH:\n                str = \"SSLv3/TLS read server key exchange\";\n                break;\n            case TLS_ST_CR_CERT_REQ:\n                str = \"SSLv3/TLS read server certificate request\";\n                break;\n            case TLS_ST_CR_SESSION_TICKET:\n                str = \"SSLv3/TLS read server session ticket\";\n                break;\n            case TLS_ST_CR_SRVR_DONE:\n                str = \"SSLv3/TLS read server done\";\n                break;\n            case TLS_ST_CW_CERT:\n                str = \"SSLv3/TLS write client certificate\";\n                break;\n            case TLS_ST_CW_KEY_EXCH:\n                str = \"SSLv3/TLS write client key exchange\";\n                break;\n            case TLS_ST_CW_CERT_VRFY:\n                str = \"SSLv3/TLS write certificate verify\";\n                break;\n            case TLS_ST_CW_CHANGE:\n            case TLS_ST_SW_CHANGE:\n                str = \"SSLv3/TLS write change cipher spec\";\n                break;\n            case TLS_ST_CW_FINISHED:\n            case TLS_ST_SW_FINISHED:\n                str = \"SSLv3/TLS write finished\";\n                break;\n            case TLS_ST_CR_CHANGE:\n            case TLS_ST_SR_CHANGE:\n                str = \"SSLv3/TLS read change cipher spec\";\n                break;\n            case TLS_ST_CR_FINISHED:\n            case TLS_ST_SR_FINISHED:\n                str = \"SSLv3/TLS read finished\";\n                break;\n            case TLS_ST_SR_CLNT_HELLO:\n                str = \"SSLv3/TLS read client hello\";\n                break;\n            case TLS_ST_SW_HELLO_REQ:\n                str = \"SSLv3/TLS write hello request\";\n                break;\n            case TLS_ST_SW_SRVR_HELLO:\n                str = \"SSLv3/TLS write server hello\";\n                break;\n            case TLS_ST_SW_CERT:\n                str = \"SSLv3/TLS write certificate\";\n                break;\n            case TLS_ST_SW_KEY_EXCH:\n                str = \"SSLv3/TLS write key exchange\";\n                break;\n            case TLS_ST_SW_CERT_REQ:\n                str = \"SSLv3/TLS write certificate request\";\n                break;\n            case TLS_ST_SW_SESSION_TICKET:\n                str = \"SSLv3/TLS write session ticket\";\n                break;\n            case TLS_ST_SW_SRVR_DONE:\n                str = \"SSLv3/TLS write server done\";\n                break;\n            case TLS_ST_SR_CERT:\n                str = \"SSLv3/TLS read client certificate\";\n                break;\n            case TLS_ST_SR_KEY_EXCH:\n                str = \"SSLv3/TLS read client key exchange\";\n                break;\n            case TLS_ST_SR_CERT_VRFY:\n                str = \"SSLv3/TLS read certificate verify\";\n                break;\n            case DTLS_ST_CR_HELLO_VERIFY_REQUEST:\n                str = \"DTLS1 read hello verify request\";\n                break;\n            case DTLS_ST_SW_HELLO_VERIFY_REQUEST:\n                str = \"DTLS1 write hello verify request\";\n                break;\n            default:\n                break;\n        }\n    }\n\n    return str;\n}\n\n/**\n * @brief set the SSL context read buffer length\n */\nvoid SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)\n{\n    SSL_ASSERT3(ctx);\n\n    ctx->read_buffer_len = len;\n}\n\n/**\n * @brief set the SSL read buffer length\n */\nvoid SSL_set_default_read_buffer_len(SSL *ssl, size_t len)\n{\n    SSL_ASSERT3(ssl);\n    SSL_ASSERT3(len);\n\n    SSL_METHOD_CALL(set_bufflen, ssl, len);\n}\n\n/**\n * @brief set the SSL information callback function\n */\nvoid SSL_set_info_callback(SSL *ssl, void (*cb) (const SSL *ssl, int type, int val))\n{\n    SSL_ASSERT3(ssl);\n\n    ssl->info_callback = cb;\n}\n\n/**\n * @brief add SSL context reference count by '1'\n */\nint SSL_CTX_up_ref(SSL_CTX *ctx)\n{\n    SSL_ASSERT1(ctx);\n\n    /**\n     * no support multi-thread SSL here\n     */\n    ctx->references++;\n\n    return 1;\n}\n\n/**\n * @brief set the SSL security level\n */\nvoid SSL_set_security_level(SSL *ssl, int level)\n{\n    SSL_ASSERT3(ssl);\n\n    ssl->cert->sec_level = level;\n}\n\n/**\n * @brief get the SSL security level\n */\nint SSL_get_security_level(const SSL *ssl)\n{\n    SSL_ASSERT1(ssl);\n\n    return ssl->cert->sec_level;\n}\n\n/**\n * @brief get the SSL verifying mode of the SSL context\n */\nint SSL_CTX_get_verify_mode(const SSL_CTX *ctx)\n{\n    SSL_ASSERT1(ctx);\n\n    return ctx->verify_mode;\n}\n\n/**\n * @brief set the session timeout time\n */\nlong SSL_CTX_set_timeout(SSL_CTX *ctx, long t)\n{\n    long l;\n\n    SSL_ASSERT1(ctx);\n\n    l = ctx->session_timeout;\n    ctx->session_timeout = t;\n\n    return l;\n}\n\n/**\n * @brief get the session timeout time\n */\nlong SSL_CTX_get_timeout(const SSL_CTX *ctx)\n{\n    SSL_ASSERT1(ctx);\n\n    return ctx->session_timeout;\n}\n\n/**\n * @brief set the SSL if we can read as many as data\n */\nvoid SSL_set_read_ahead(SSL *ssl, int yes)\n{\n    SSL_ASSERT3(ssl);\n\n    ssl->rlayer.read_ahead = yes;\n}\n\n/**\n * @brief set the SSL context if we can read as many as data\n */\nvoid SSL_CTX_set_read_ahead(SSL_CTX *ctx, int yes)\n{\n    SSL_ASSERT3(ctx);\n\n    ctx->read_ahead = yes;\n}\n\n/**\n * @brief get the SSL ahead signal if we can read as many as data\n */\nint SSL_get_read_ahead(const SSL *ssl)\n{\n    SSL_ASSERT1(ssl);\n\n    return ssl->rlayer.read_ahead;\n}\n\n/**\n * @brief get the SSL context ahead signal if we can read as many as data\n */\nlong SSL_CTX_get_read_ahead(SSL_CTX *ctx)\n{\n    SSL_ASSERT1(ctx);\n\n    return ctx->read_ahead;\n}\n\n/**\n * @brief check if the SSL context can read as many as data\n */\nlong SSL_CTX_get_default_read_ahead(SSL_CTX *ctx)\n{\n    SSL_ASSERT1(ctx);\n\n    return ctx->read_ahead;\n}\n\n/**\n * @brief set SSL session time\n */\nlong SSL_set_time(SSL *ssl, long t)\n{\n    SSL_ASSERT1(ssl);\n\n    ssl->session->time = t;\n\n    return t;\n}\n\n/**\n * @brief set SSL session timeout time\n */\nlong SSL_set_timeout(SSL *ssl, long t)\n{\n    SSL_ASSERT1(ssl);\n\n    ssl->session->timeout = t;\n\n    return t;\n}\n\n/**\n * @brief get the verifying result of the SSL certification\n */\nlong SSL_get_verify_result(const SSL *ssl)\n{\n    SSL_ASSERT1(ssl);\n\n    return SSL_METHOD_CALL(get_verify_result, ssl);\n}\n\n/**\n * @brief get the SSL verifying depth of the SSL context\n */\nint SSL_CTX_get_verify_depth(const SSL_CTX *ctx)\n{\n    SSL_ASSERT1(ctx);\n\n    return ctx->param.depth;\n}\n\n/**\n * @brief set the SSL verify depth of the SSL context\n */\nvoid SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)\n{\n    SSL_ASSERT3(ctx);\n\n    ctx->param.depth = depth;\n}\n\n/**\n * @brief get the SSL verifying depth of the SSL\n */\nint SSL_get_verify_depth(const SSL *ssl)\n{\n    SSL_ASSERT1(ssl);\n\n    return ssl->param.depth;\n}\n\n/**\n * @brief set the SSL verify depth of the SSL\n */\nvoid SSL_set_verify_depth(SSL *ssl, int depth)\n{\n    SSL_ASSERT3(ssl);\n\n    ssl->param.depth = depth;\n}\n\n/**\n * @brief set the SSL context verifying of the SSL context\n */\nvoid SSL_CTX_set_verify(SSL_CTX *ctx, int mode, int (*verify_callback)(int, X509_STORE_CTX *))\n{\n    SSL_ASSERT3(ctx);\n\n    ctx->verify_mode = mode;\n    ctx->default_verify_callback = verify_callback;\n}\n\n/**\n * @brief set the SSL verifying of the SSL context\n */\nvoid SSL_set_verify(SSL *ssl, int mode, int (*verify_callback)(int, X509_STORE_CTX *))\n{\n    SSL_ASSERT3(ssl);\n\n    ssl->verify_mode = mode;\n    ssl->verify_callback = verify_callback;\n}\n\nvoid ERR_error_string_n(unsigned long e, char *buf, size_t len)\n{\n\tlws_strncpy(buf, \"unknown\", len);\n}\n\nvoid ERR_free_strings(void)\n{\n}\n\nchar *ERR_error_string(unsigned long e, char *buf)\n{\n\tif (!buf)\n\t\treturn \"unknown\";\n\n\tswitch(e) {\n\t\tcase X509_V_ERR_INVALID_CA:\n\t\t\tstrcpy(buf, \"CA is not trusted\");\n\t\t\tbreak;\n\t\tcase X509_V_ERR_HOSTNAME_MISMATCH:\n\t\t\tstrcpy(buf, \"Hostname mismatch\");\n\t\t\tbreak;\n\t\tcase X509_V_ERR_CA_KEY_TOO_SMALL:\n\t\t\tstrcpy(buf, \"CA key too small\");\n\t\t\tbreak;\n\t\tcase X509_V_ERR_CA_MD_TOO_WEAK:\n\t\t\tstrcpy(buf, \"MD key too weak\");\n\t\t\tbreak;\n\t\tcase X509_V_ERR_CERT_NOT_YET_VALID:\n\t\t\tstrcpy(buf, \"Cert from the future\");\n\t\t\tbreak;\n\t\tcase X509_V_ERR_CERT_HAS_EXPIRED:\n\t\t\tstrcpy(buf, \"Cert expired\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tstrcpy(buf, \"unknown\");\n\t\t\tbreak;\n\t}\n\n\treturn buf;\n}\n\nvoid *SSL_CTX_get_ex_data(const SSL_CTX *ctx, int idx)\n{\n\treturn NULL;\n}\n\n/*\n * Openssl wants the valid protocol names supplied like this:\n *\n * (unsigned char *)\"\\x02h2\\x08http/1.1\", 6 + 9\n *\n * Mbedtls wants this:\n *\n * Pointer to a NULL-terminated list of supported protocols, in decreasing\n * preference order. The pointer to the list is recorded by the library for\n * later reference as required, so the lifetime of the table must be at least\n * as long as the lifetime of the SSL configuration structure.\n *\n * So accept the OpenSSL style and convert to mbedtls style\n */\n\nstruct alpn_ctx {\n\tunsigned char data[23];\n\tunsigned char len;\n};\n\nstatic void\n_openssl_alpn_to_mbedtls(struct alpn_ctx *ac, char ***palpn_protos)\n{\n\tunsigned char *p = ac->data, *q;\n\tunsigned char len;\n\tchar **alpn_protos;\n\tint count = 0;\n\n\t/* find out how many entries he gave us */\n\n\tlen = *p++;\n\twhile (p - ac->data < ac->len) {\n\t\tif (len--) {\n\t\t\tp++;\n\t\t\tcontinue;\n\t\t}\n\t\tcount++;\n\t\tlen = *p++;\n\t\tif (!len)\n\t\t\tbreak;\n\t}\n\n\tif (!len)\n\t\tcount++;\n\n\tif (!count)\n\t\treturn;\n\n\t/* allocate space for count + 1 pointers and the data afterwards */\n\n\talpn_protos = ssl_mem_zalloc((count + 1) * sizeof(char *) + ac->len + 1);\n\tif (!alpn_protos)\n\t\treturn;\n\n\t*palpn_protos = alpn_protos;\n\n\t/* convert to mbedtls format */\n\n\tq = (unsigned char *)alpn_protos + (count + 1) * sizeof(char *);\n\tp = ac->data;\n\tcount = 0;\n\n\tlen = *p++;\n\talpn_protos[count] = (char *)q;\n\twhile (p - ac->data < ac->len) {\n\t\tif (len--) {\n\t\t\t*q++ = *p++;\n\t\t\tcontinue;\n\t\t}\n\t\t*q++ = '\\0';\n\t\tcount++;\n\t\tlen = *p++;\n\t\talpn_protos[count] = (char *)q;\n\t\tif (!len)\n\t\t\tbreak;\n\t}\n\tif (!len) {\n\t\t*q++ = '\\0';\n\t\tcount++;\n\t\tlen = *p++;\n\t\talpn_protos[count] = (char *)q;\n\t}\n\talpn_protos[count] = NULL; /* last pointer ends list with NULL */\n}\n\nvoid SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx, next_proto_cb cb, void *arg)\n{\n\tstruct alpn_ctx *ac = arg;\n\n\tctx->alpn_cb = cb;\n\n\t_openssl_alpn_to_mbedtls(ac, (char ***)&ctx->alpn_protos);\n}\n\nvoid SSL_set_alpn_select_cb(SSL *ssl, void *arg)\n{\n\tstruct alpn_ctx *ac = arg;\n\n\t_openssl_alpn_to_mbedtls(ac, (char ***)&ssl->alpn_protos);\n\n\t_ssl_set_alpn_list(ssl);\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/library/ssl_methods.c",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"ssl_methods.h\"\n#include \"ssl_pm.h\"\n\n/**\n * TLS method function collection\n */\nIMPLEMENT_TLS_METHOD_FUNC(TLS_method_func,\n        ssl_pm_new, ssl_pm_free,\n        ssl_pm_handshake, ssl_pm_shutdown, ssl_pm_clear,\n        ssl_pm_read, ssl_pm_send, ssl_pm_pending,\n        ssl_pm_set_fd, ssl_pm_get_fd,\n        ssl_pm_set_bufflen,\n        ssl_pm_get_verify_result,\n        ssl_pm_get_state);\n\n/**\n * TLS or SSL client method collection\n */\nIMPLEMENT_TLS_METHOD(TLS_ANY_VERSION, 0, TLS_method_func, TLS_client_method);\n\nIMPLEMENT_TLS_METHOD(TLS1_2_VERSION, 0, TLS_method_func, TLSv1_2_client_method);\n\nIMPLEMENT_TLS_METHOD(TLS1_1_VERSION, 0, TLS_method_func, TLSv1_1_client_method);\n\nIMPLEMENT_TLS_METHOD(TLS1_VERSION, 0, TLS_method_func, TLSv1_client_method);\n\nIMPLEMENT_SSL_METHOD(SSL3_VERSION, 0, TLS_method_func, SSLv3_client_method);\n\n/**\n * TLS or SSL server method collection\n */\nIMPLEMENT_TLS_METHOD(TLS_ANY_VERSION, 1, TLS_method_func, TLS_server_method);\n\nIMPLEMENT_TLS_METHOD(TLS1_1_VERSION, 1, TLS_method_func, TLSv1_1_server_method);\n\nIMPLEMENT_TLS_METHOD(TLS1_2_VERSION, 1, TLS_method_func, TLSv1_2_server_method);\n\nIMPLEMENT_TLS_METHOD(TLS1_VERSION, 0, TLS_method_func, TLSv1_server_method);\n\nIMPLEMENT_SSL_METHOD(SSL3_VERSION, 1, TLS_method_func, SSLv3_server_method);\n\n/**\n * TLS or SSL method collection\n */\nIMPLEMENT_TLS_METHOD(TLS_ANY_VERSION, -1, TLS_method_func, TLS_method);\n\nIMPLEMENT_SSL_METHOD(TLS1_2_VERSION, -1, TLS_method_func, TLSv1_2_method);\n\nIMPLEMENT_SSL_METHOD(TLS1_1_VERSION, -1, TLS_method_func, TLSv1_1_method);\n\nIMPLEMENT_SSL_METHOD(TLS1_VERSION, -1, TLS_method_func, TLSv1_method);\n\nIMPLEMENT_SSL_METHOD(SSL3_VERSION, -1, TLS_method_func, SSLv3_method);\n\n/**\n * @brief get X509 object method\n */\nIMPLEMENT_X509_METHOD(X509_method,\n            x509_pm_new, x509_pm_free,\n            x509_pm_load, x509_pm_show_info);\n\n/**\n * @brief get private key object method\n */\nIMPLEMENT_PKEY_METHOD(EVP_PKEY_method,\n            pkey_pm_new, pkey_pm_free,\n            pkey_pm_load);\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/library/ssl_pkey.c",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"ssl_pkey.h\"\n#include \"ssl_methods.h\"\n#include \"ssl_dbg.h\"\n#include \"ssl_port.h\"\n\n/**\n * @brief create a private key object according to input private key\n */\nEVP_PKEY* __EVP_PKEY_new(EVP_PKEY *ipk)\n{\n    int ret;\n    EVP_PKEY *pkey;\n\n    pkey = ssl_mem_zalloc(sizeof(EVP_PKEY));\n    if (!pkey) {\n        SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, \"no enough memory > (pkey)\");\n        goto no_mem;\n    }\n\n    if (ipk) {\n        pkey->method = ipk->method;\n    } else {\n        pkey->method = EVP_PKEY_method();\n    }\n\n    ret = EVP_PKEY_METHOD_CALL(new, pkey, ipk);\n    if (ret) {\n        SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, \"EVP_PKEY_METHOD_CALL(new) return %d\", ret);\n        goto failed;\n    }\n\n    return pkey;\n\nfailed:\n    ssl_mem_free(pkey);\nno_mem:\n    return NULL;\n}\n\n/**\n * @brief create a private key object\n */\nEVP_PKEY* EVP_PKEY_new(void)\n{\n    return __EVP_PKEY_new(NULL);\n}\n\n/**\n * @brief free a private key object\n */\nvoid EVP_PKEY_free(EVP_PKEY *pkey)\n{\n    SSL_ASSERT3(pkey);\n\n    EVP_PKEY_METHOD_CALL(free, pkey);\n\n    ssl_mem_free(pkey);\n}\n\n/**\n * @brief load a character key context into system context. If '*a' is pointed to the\n *        private key, then load key into it. Or create a new private key object\n */\nEVP_PKEY *d2i_PrivateKey(int type,\n                         EVP_PKEY **a,\n                         const unsigned char **pp,\n                         long length)\n{\n    int m = 0;\n    int ret;\n    EVP_PKEY *pkey;\n\n    SSL_ASSERT2(pp);\n    SSL_ASSERT2(*pp);\n    SSL_ASSERT2(length);\n\n    if (a && *a) {\n        pkey = *a;\n    } else {\n        pkey = EVP_PKEY_new();;\n        if (!pkey) {\n            SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, \"EVP_PKEY_new() return NULL\");\n            goto failed1;\n        }\n\n        m = 1;\n    }\n\n    ret = EVP_PKEY_METHOD_CALL(load, pkey, *pp, length);\n    if (ret) {\n        SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, \"EVP_PKEY_METHOD_CALL(load) return %d\", ret);\n        goto failed2;\n    }\n\n    if (a)\n        *a = pkey;\n\n    return pkey;\n\nfailed2:\n    if (m)\n        EVP_PKEY_free(pkey);\nfailed1:\n    return NULL;\n}\n\n/**\n * @brief set the SSL context private key\n */\nint SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey)\n{\n    SSL_ASSERT1(ctx);\n    SSL_ASSERT1(pkey);\n\n    if (ctx->cert->pkey == pkey)\n        return 1;\n\n    if (ctx->cert->pkey)\n        EVP_PKEY_free(ctx->cert->pkey);\n\n    ctx->cert->pkey = pkey;\n\n    return 1;\n}\n\n/**\n * @brief set the SSL private key\n */\nint SSL_use_PrivateKey(SSL *ssl, EVP_PKEY *pkey)\n{\n    SSL_ASSERT1(ssl);\n    SSL_ASSERT1(pkey);\n\n    if (ssl->cert->pkey == pkey)\n        return 1;\n\n    if (ssl->cert->pkey)\n        EVP_PKEY_free(ssl->cert->pkey);\n\n    ssl->cert->pkey = pkey;\n\n    return 1;\n}\n\n/**\n * @brief load private key into the SSL context\n */\nint SSL_CTX_use_PrivateKey_ASN1(int type, SSL_CTX *ctx,\n                                const unsigned char *d, long len)\n{\n    int ret;\n    EVP_PKEY *pk;\n\n    pk = d2i_PrivateKey(0, NULL, &d, len);\n    if (!pk) {\n        SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, \"d2i_PrivateKey() return NULL\");\n        goto failed1;\n    }\n\n    ret = SSL_CTX_use_PrivateKey(ctx, pk);\n    if (!ret) {\n        SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, \"SSL_CTX_use_PrivateKey() return %d\", ret);\n        goto failed2;\n    }\n\n    return 1;\n\nfailed2:\n    EVP_PKEY_free(pk);\nfailed1:\n    return 0;\n}\n\n/**\n * @brief load private key into the SSL\n */\nint SSL_use_PrivateKey_ASN1(int type, SSL *ssl,\n                                const unsigned char *d, long len)\n{\n    int ret;\n    EVP_PKEY *pk;\n\n    pk = d2i_PrivateKey(0, NULL, &d, len);\n    if (!pk) {\n        SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, \"d2i_PrivateKey() return NULL\");\n        goto failed1;\n    }\n\n    ret = SSL_use_PrivateKey(ssl, pk);\n    if (!ret) {\n        SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, \"SSL_use_PrivateKey() return %d\", ret);\n        goto failed2;\n    }\n\n    return 1;\n\nfailed2:\n    EVP_PKEY_free(pk);\nfailed1:\n    return 0;\n}\n\n/**\n * @brief load the private key file into SSL context\n */\nint SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type)\n{\n    return 0;\n}\n\n/**\n * @brief load the private key file into SSL\n */\nint SSL_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type)\n{\n    return 0;\n}\n\n/**\n * @brief load the RSA ASN1 private key into SSL context\n */\nint SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d, long len)\n{\n    return SSL_CTX_use_PrivateKey_ASN1(0, ctx, d, len);\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/library/ssl_stack.c",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"ssl_stack.h\"\n#include \"ssl_dbg.h\"\n#include \"ssl_port.h\"\n\n#ifndef CONFIG_MIN_NODES\n    #define MIN_NODES 4\n#else\n    #define MIN_NODES CONFIG_MIN_NODES\n#endif\n\n/**\n * @brief create a openssl stack object\n */\nOPENSSL_STACK* OPENSSL_sk_new(OPENSSL_sk_compfunc c)\n{\n    OPENSSL_STACK *stack;\n    char **data;\n\n    stack = ssl_mem_zalloc(sizeof(OPENSSL_STACK));\n    if (!stack) {\n        SSL_DEBUG(SSL_STACK_ERROR_LEVEL, \"no enough memory > (stack)\");\n        goto no_mem1;\n    }\n\n    data = ssl_mem_zalloc(sizeof(*data) * MIN_NODES);\n    if (!data) {\n        SSL_DEBUG(SSL_STACK_ERROR_LEVEL, \"no enough memory > (data)\");\n        goto no_mem2;\n    }\n\n    stack->data = data;\n    stack->num_alloc = MIN_NODES;\n    stack->c = c;\n\n    return stack;\n\nno_mem2:\n    ssl_mem_free(stack);\nno_mem1:\n    return NULL;\n}\n\n/**\n * @brief create a NULL function openssl stack object\n */\nOPENSSL_STACK *OPENSSL_sk_new_null(void)\n{\n    return OPENSSL_sk_new((OPENSSL_sk_compfunc)NULL);\n}\n\n/**\n * @brief free openssl stack object\n */\nvoid OPENSSL_sk_free(OPENSSL_STACK *stack)\n{\n    SSL_ASSERT3(stack);\n\n    ssl_mem_free(stack->data);\n    ssl_mem_free(stack);\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/library/ssl_x509.c",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"ssl_x509.h\"\n#include \"ssl_methods.h\"\n#include \"ssl_dbg.h\"\n#include \"ssl_port.h\"\n\n#include <assert.h>\n\n/**\n * @brief show X509 certification information\n */\nint __X509_show_info(X509 *x)\n{\n    return X509_METHOD_CALL(show_info, x);\n}\n\n/**\n * @brief create a X509 certification object according to input X509 certification\n */\nX509* __X509_new(X509 *ix)\n{\n    int ret;\n    X509 *x;\n\n    x = ssl_mem_zalloc(sizeof(X509));\n    if (!x) {\n        SSL_DEBUG(SSL_X509_ERROR_LEVEL, \"no enough memory > (x)\");\n        goto no_mem;\n    }\n\n    if (ix)\n        x->method = ix->method;\n    else\n        x->method = X509_method();\n\n    ret = X509_METHOD_CALL(new, x, ix);\n    if (ret) {\n        SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, \"X509_METHOD_CALL(new) return %d\", ret);\n        goto failed;\n    }\n\n    return x;\n\nfailed:\n    ssl_mem_free(x);\nno_mem:\n    return NULL;\n}\n\n/**\n * @brief create a X509 certification object\n */\nX509* X509_new(void)\n{\n    return __X509_new(NULL);\n}\n\n/**\n * @brief free a X509 certification object\n */\nvoid X509_free(X509 *x)\n{\n    SSL_ASSERT3(x);\n\n    X509_METHOD_CALL(free, x);\n\n    ssl_mem_free(x);\n};\n\n/**\n * @brief load a character certification context into system context. If '*cert' is pointed to the\n *        certification, then load certification into it. Or create a new X509 certification object\n */\nX509* d2i_X509(X509 **cert, const unsigned char *buffer, long len)\n{\n    int m = 0;\n    int ret;\n    X509 *x;\n\n    SSL_ASSERT2(buffer);\n    SSL_ASSERT2(len);\n\n    if (cert && *cert) {\n        x = *cert;\n    } else {\n        x = X509_new();\n        if (!x) {\n            SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, \"X509_new() return NULL\");\n            goto failed1;\n        }\n        m = 1;\n    }\n\n    ret = X509_METHOD_CALL(load, x, buffer, len);\n    if (ret) {\n        SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, \"X509_METHOD_CALL(load) return %d\", ret);\n        goto failed2;\n    }\n\n    return x;\n\nfailed2:\n    if (m)\n        X509_free(x);\nfailed1:\n    return NULL;\n}\n\n/**\n * @brief return SSL X509 verify parameters\n */\n\nX509_VERIFY_PARAM *SSL_get0_param(SSL *ssl)\n{\n\treturn &ssl->param;\n}\n\n/**\n * @brief set X509 host verification flags\n */\n\nint X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param,\n\t\t\t\t    unsigned long flags)\n{\n\t/* flags not supported yet */\n\treturn 0;\n}\n\n/**\n * @brief clear X509 host verification flags\n */\n\nint X509_VERIFY_PARAM_clear_hostflags(X509_VERIFY_PARAM *param,\n\t\t\t\t      unsigned long flags)\n{\n\t/* flags not supported yet */\n\treturn 0;\n}\n\n/**\n * @brief set SSL context client CA certification\n */\nint SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x)\n{\n    SSL_ASSERT1(ctx);\n    SSL_ASSERT1(x);\n    assert(ctx);\n    if (ctx->client_CA == x)\n        return 1;\n\n    X509_free(ctx->client_CA);\n\n    ctx->client_CA = x;\n\n    return 1;\n}\n\n/**\n * @brief add CA client certification into the SSL\n */\nint SSL_CTX_add_client_CA_ASN1(SSL_CTX *ctx, int len,\n                const unsigned char *d)\n{\n\tX509 *x;\n\n\tx = d2i_X509(NULL, d, len);\n\tif (!x) {\n\t\tSSL_DEBUG(SSL_PKEY_ERROR_LEVEL, \"d2i_X509() return NULL\");\n\t\treturn 0;\n\t}\n    SSL_ASSERT1(ctx);\n\n    X509_free(ctx->client_CA);\n\n    ctx->client_CA = x;\n\n    return 1;\n}\n\n/**\n * @brief add CA client certification into the SSL\n */\nint SSL_add_client_CA(SSL *ssl, X509 *x)\n{\n    SSL_ASSERT1(ssl);\n    SSL_ASSERT1(x);\n\n    if (ssl->client_CA == x)\n        return 1;\n\n    X509_free(ssl->client_CA);\n\n    ssl->client_CA = x;\n\n    return 1;\n}\n\n/**\n * @brief set the SSL context certification\n */\nint SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x)\n{\n    SSL_ASSERT1(ctx);\n    SSL_ASSERT1(x);\n\n    if (ctx->cert->x509 == x)\n        return 1;\n\n    X509_free(ctx->cert->x509);\n\n    ctx->cert->x509 = x;\n\n    return 1;\n}\n\n/**\n * @brief set the SSL certification\n */\nint SSL_use_certificate(SSL *ssl, X509 *x)\n{\n    SSL_ASSERT1(ssl);\n    SSL_ASSERT1(x);\n\n    if (ssl->cert->x509 == x)\n        return 1;\n\n    X509_free(ssl->cert->x509);\n\n    ssl->cert->x509 = x;\n\n    return 1;\n}\n\n/**\n * @brief get the SSL certification point\n */\nX509 *SSL_get_certificate(const SSL *ssl)\n{\n    SSL_ASSERT2(ssl);\n\n    return ssl->cert->x509;\n}\n\n/**\n * @brief load certification into the SSL context\n */\nint SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len,\n                                 const unsigned char *d)\n{\n    int ret;\n    X509 *x;\n\n    x = d2i_X509(NULL, d, len);\n    if (!x) {\n        SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, \"d2i_X509() return NULL\");\n        goto failed1;\n    }\n\n    ret = SSL_CTX_use_certificate(ctx, x);\n    if (!ret) {\n        SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, \"SSL_CTX_use_certificate() return %d\", ret);\n        goto failed2;\n    }\n\n    return 1;\n\nfailed2:\n    X509_free(x);\nfailed1:\n    return 0;\n}\n\n/**\n * @brief load certification into the SSL\n */\nint SSL_use_certificate_ASN1(SSL *ssl, int len,\n                             const unsigned char *d)\n{\n    int ret;\n    X509 *x;\n\n    x = d2i_X509(NULL, d, len);\n    if (!x) {\n        SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, \"d2i_X509() return NULL\");\n        goto failed1;\n    }\n\n    ret = SSL_use_certificate(ssl, x);\n    if (!ret) {\n        SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, \"SSL_use_certificate() return %d\", ret);\n        goto failed2;\n    }\n\n    return 1;\n\nfailed2:\n    X509_free(x);\nfailed1:\n    return 0;\n}\n\n/**\n * @brief load the certification file into SSL context\n */\nint SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type)\n{\n    return 0;\n}\n\n/**\n * @brief load the certification file into SSL\n */\nint SSL_use_certificate_file(SSL *ssl, const char *file, int type)\n{\n    return 0;\n}\n\n/**\n * @brief get peer certification\n */\nX509 *SSL_get_peer_certificate(const SSL *ssl)\n{\n    SSL_ASSERT2(ssl);\n\n    return ssl->session->peer;\n}\n\nint X509_STORE_CTX_get_error(X509_STORE_CTX *ctx)\n{\n\treturn X509_V_ERR_UNSPECIFIED;\n}\n\nint X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx)\n{\n\treturn 0;\n}\n\nconst char *X509_verify_cert_error_string(long n)\n{\n\treturn \"unknown\";\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/platform/ssl_pm.c",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"ssl_pm.h\"\n#include \"ssl_port.h\"\n#include \"ssl_dbg.h\"\n\n/* mbedtls include */\n#include \"mbedtls/platform.h\"\n#include \"mbedtls/net_sockets.h\"\n#include \"mbedtls/debug.h\"\n#include \"mbedtls/entropy.h\"\n#include \"mbedtls/ctr_drbg.h\"\n#include \"mbedtls/error.h\"\n#include \"mbedtls/certs.h\"\n\n#include <libwebsockets.h>\n\n#define X509_INFO_STRING_LENGTH 8192\n\nstruct ssl_pm\n{\n    /* local socket file description */\n    mbedtls_net_context fd;\n    /* remote client socket file description */\n    mbedtls_net_context cl_fd;\n\n    mbedtls_ssl_config conf;\n\n    mbedtls_ctr_drbg_context ctr_drbg;\n\n    mbedtls_ssl_context ssl;\n\n    mbedtls_entropy_context entropy;\n\n    SSL *owner;\n};\n\nstruct x509_pm\n{\n    mbedtls_x509_crt *x509_crt;\n\n    mbedtls_x509_crt *ex_crt;\n};\n\nstruct pkey_pm\n{\n    mbedtls_pk_context *pkey;\n\n    mbedtls_pk_context *ex_pkey;\n};\n\nunsigned int max_content_len;\n\n/*********************************************************************************************/\n/************************************ SSL arch interface *************************************/\n\n//#ifdef CONFIG_OPENSSL_LOWLEVEL_DEBUG\n\n/* mbedtls debug level */\n#define MBEDTLS_DEBUG_LEVEL 4\n\n/**\n * @brief mbedtls debug function\n */\nstatic void ssl_platform_debug(void *ctx, int level,\n                     const char *file, int line,\n                     const char *str)\n{\n    /* Shorten 'file' from the whole file path to just the filename\n\n       This is a bit wasteful because the macros are compiled in with\n       the full _FILE_ path in each case.\n    */\n//    char *file_sep = rindex(file, '/');\n  //  if(file_sep)\n    //    file = file_sep + 1;\n\n    printf(\"%s:%d %s\", file, line, str);\n}\n//#endif\n\n/**\n * @brief create SSL low-level object\n */\nint ssl_pm_new(SSL *ssl)\n{\n    struct ssl_pm *ssl_pm;\n    int ret;\n\n    const unsigned char pers[] = \"OpenSSL PM\";\n    size_t pers_len = sizeof(pers);\n\n    int endpoint;\n    int version;\n\n    const SSL_METHOD *method = ssl->method;\n\n    ssl_pm = ssl_mem_zalloc(sizeof(struct ssl_pm));\n    if (!ssl_pm) {\n        SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"no enough memory > (ssl_pm)\");\n        goto no_mem;\n    }\n\n    ssl_pm->owner = ssl;\n\n    if (!ssl->ctx->read_buffer_len)\n\t    ssl->ctx->read_buffer_len = 2048;\n\n    max_content_len = ssl->ctx->read_buffer_len;\n    // printf(\"ssl->ctx->read_buffer_len = %d ++++++++++++++++++++\\n\", ssl->ctx->read_buffer_len);\n\n    mbedtls_net_init(&ssl_pm->fd);\n    mbedtls_net_init(&ssl_pm->cl_fd);\n\n    mbedtls_ssl_config_init(&ssl_pm->conf);\n    mbedtls_ctr_drbg_init(&ssl_pm->ctr_drbg);\n    mbedtls_entropy_init(&ssl_pm->entropy);\n    mbedtls_ssl_init(&ssl_pm->ssl);\n\n    ret = mbedtls_ctr_drbg_seed(&ssl_pm->ctr_drbg, mbedtls_entropy_func, &ssl_pm->entropy, pers, pers_len);\n    if (ret) {\n        SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"mbedtls_ctr_drbg_seed() return -0x%x\", -ret);\n        goto mbedtls_err1;\n    }\n\n    if (method->endpoint) {\n        endpoint = MBEDTLS_SSL_IS_SERVER;\n    } else {\n        endpoint = MBEDTLS_SSL_IS_CLIENT;\n    }\n    ret = mbedtls_ssl_config_defaults(&ssl_pm->conf, endpoint, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT);\n    if (ret) {\n        SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"mbedtls_ssl_config_defaults() return -0x%x\", -ret);\n        goto mbedtls_err2;\n    }\n\n    if (TLS_ANY_VERSION != ssl->version) {\n        if (TLS1_2_VERSION == ssl->version)\n            version = MBEDTLS_SSL_MINOR_VERSION_3;\n        else if (TLS1_1_VERSION == ssl->version)\n            version = MBEDTLS_SSL_MINOR_VERSION_2;\n        else if (TLS1_VERSION == ssl->version)\n            version = MBEDTLS_SSL_MINOR_VERSION_1;\n        else\n            version = MBEDTLS_SSL_MINOR_VERSION_0;\n\n        mbedtls_ssl_conf_max_version(&ssl_pm->conf, MBEDTLS_SSL_MAJOR_VERSION_3, version);\n        mbedtls_ssl_conf_min_version(&ssl_pm->conf, MBEDTLS_SSL_MAJOR_VERSION_3, version);\n    } else {\n        mbedtls_ssl_conf_max_version(&ssl_pm->conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);\n        mbedtls_ssl_conf_min_version(&ssl_pm->conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0);\n    }\n\n    mbedtls_ssl_conf_rng(&ssl_pm->conf, mbedtls_ctr_drbg_random, &ssl_pm->ctr_drbg);\n\n//#ifdef CONFIG_OPENSSL_LOWLEVEL_DEBUG\n //   mbedtls_debug_set_threshold(MBEDTLS_DEBUG_LEVEL);\n//    mbedtls_ssl_conf_dbg(&ssl_pm->conf, ssl_platform_debug, NULL);\n//#else\n    mbedtls_ssl_conf_dbg(&ssl_pm->conf, ssl_platform_debug, NULL);\n//#endif\n\n    ret = mbedtls_ssl_setup(&ssl_pm->ssl, &ssl_pm->conf);\n    if (ret) {\n        SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"mbedtls_ssl_setup() return -0x%x\", -ret);\n        goto mbedtls_err2;\n    }\n\n    mbedtls_ssl_set_bio(&ssl_pm->ssl, &ssl_pm->fd, mbedtls_net_send, mbedtls_net_recv, NULL);\n\n    ssl->ssl_pm = ssl_pm;\n\n    return 0;\n\nmbedtls_err2:\n    mbedtls_ssl_config_free(&ssl_pm->conf);\n    mbedtls_ctr_drbg_free(&ssl_pm->ctr_drbg);\nmbedtls_err1:\n    mbedtls_entropy_free(&ssl_pm->entropy);\n    ssl_mem_free(ssl_pm);\nno_mem:\n    return -1;\n}\n\n/**\n * @brief free SSL low-level object\n */\nvoid ssl_pm_free(SSL *ssl)\n{\n    struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;\n\n    mbedtls_ctr_drbg_free(&ssl_pm->ctr_drbg);\n    mbedtls_entropy_free(&ssl_pm->entropy);\n    mbedtls_ssl_config_free(&ssl_pm->conf);\n    mbedtls_ssl_free(&ssl_pm->ssl);\n\n    ssl_mem_free(ssl_pm);\n    ssl->ssl_pm = NULL;\n}\n\n/**\n * @brief reload SSL low-level certification object\n */\nstatic int ssl_pm_reload_crt(SSL *ssl)\n{\n    int ret;\n    int mode;\n    struct ssl_pm *ssl_pm = ssl->ssl_pm;\n    struct x509_pm *ca_pm = (struct x509_pm *)ssl->client_CA->x509_pm;\n\n    struct pkey_pm *pkey_pm = (struct pkey_pm *)ssl->cert->pkey->pkey_pm;\n    struct x509_pm *crt_pm = (struct x509_pm *)ssl->cert->x509->x509_pm;\n\n    if (ssl->verify_mode == SSL_VERIFY_PEER)\n        mode = MBEDTLS_SSL_VERIFY_OPTIONAL;\n    else if (ssl->verify_mode == SSL_VERIFY_FAIL_IF_NO_PEER_CERT)\n        mode = MBEDTLS_SSL_VERIFY_OPTIONAL;\n    else if (ssl->verify_mode == SSL_VERIFY_CLIENT_ONCE)\n        mode = MBEDTLS_SSL_VERIFY_UNSET;\n    else\n        mode = MBEDTLS_SSL_VERIFY_NONE;\n\n    mbedtls_ssl_conf_authmode(&ssl_pm->conf, mode);\n\n    if (ca_pm->x509_crt) {\n        mbedtls_ssl_conf_ca_chain(&ssl_pm->conf, ca_pm->x509_crt, NULL);\n    } else if (ca_pm->ex_crt) {\n        mbedtls_ssl_conf_ca_chain(&ssl_pm->conf, ca_pm->ex_crt, NULL);\n    }\n\n    if (crt_pm->x509_crt && pkey_pm->pkey) {\n        ret = mbedtls_ssl_conf_own_cert(&ssl_pm->conf, crt_pm->x509_crt, pkey_pm->pkey);\n    } else if (crt_pm->ex_crt && pkey_pm->ex_pkey) {\n        ret = mbedtls_ssl_conf_own_cert(&ssl_pm->conf, crt_pm->ex_crt, pkey_pm->ex_pkey);\n    } else {\n        ret = 0;\n    }\n\n    if (ret) {\n        SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"mbedtls_ssl_conf_own_cert() return -0x%x\", -ret);\n        ret = -1;\n    }\n\n    return ret;\n}\n\n/*\n * Perform the mbedtls SSL handshake instead of mbedtls_ssl_handshake.\n * We can add debug here.\n */\nstatic int mbedtls_handshake( mbedtls_ssl_context *ssl )\n{\n    int ret = 0;\n\n    while (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) {\n        ret = mbedtls_ssl_handshake_step(ssl);\n\n        lwsl_info(\"%s: ssl ret -%x state %d\\n\", __func__, -ret, ssl->state);\n\n        if (ret != 0)\n            break;\n    }\n\n    return ret;\n}\n\n#include <errno.h>\n\nint ssl_pm_handshake(SSL *ssl)\n{\n    int ret;\n    struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;\n\n    ssl->err = 0;\n    errno = 0;\n\n    ret = ssl_pm_reload_crt(ssl);\n    if (ret) {\n\t    printf(\"%s: cert reload failed\\n\", __func__);\n        return 0;\n    }\n\n    if (ssl_pm->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER) {\n\t    ssl_speed_up_enter();\n\n\t   /* mbedtls return codes\n\t    * 0 = successful, or MBEDTLS_ERR_SSL_WANT_READ/WRITE\n\t    * anything else = death\n\t    */\n\t    ret = mbedtls_handshake(&ssl_pm->ssl);\n\t    ssl_speed_up_exit();\n    } else\n\t    ret = 0;\n\n    /*\n     * OpenSSL return codes:\n     *   0 = did not complete, but may be retried\n     *   1 = successfully completed\n     *   <0 = death\n     */\n    if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {\n\t    ssl->err = ret;\n        SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"mbedtls_ssl_handshake() return -0x%x\", -ret);\n        return 0; /* OpenSSL: did not complete but may be retried */\n    }\n\n    if (ret == 0) { /* successful */\n        struct x509_pm *x509_pm = (struct x509_pm *)ssl->session->peer->x509_pm;\n\n        x509_pm->ex_crt = (mbedtls_x509_crt *)mbedtls_ssl_get_peer_cert(&ssl_pm->ssl);\n        return 1; /* openssl successful */\n    }\n\n    if (errno == 11) {\n\t    ssl->err = ret == MBEDTLS_ERR_SSL_WANT_READ;\n\n\t    return 0;\n    }\n\n    printf(\"%s: mbedtls_ssl_handshake() returned -0x%x\\n\", __func__, -ret);\n\n    /* it's had it */\n\n    ssl->err = SSL_ERROR_SYSCALL;\n\n    return -1; /* openssl death */\n}\n\nmbedtls_x509_crt *\nssl_ctx_get_mbedtls_x509_crt(SSL_CTX *ssl_ctx)\n{\n\tstruct x509_pm *x509_pm = (struct x509_pm *)ssl_ctx->cert->x509->x509_pm;\n\n\tif (!x509_pm)\n\t\treturn NULL;\n\n\treturn x509_pm->x509_crt;\n}\n\nmbedtls_x509_crt *\nssl_get_peer_mbedtls_x509_crt(SSL *ssl)\n{\n\tstruct x509_pm *x509_pm = (struct x509_pm *)ssl->session->peer->x509_pm;\n\n\tif (!x509_pm)\n\t\treturn NULL;\n\n\treturn x509_pm->ex_crt;\n}\n\nint ssl_pm_shutdown(SSL *ssl)\n{\n    int ret;\n    struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;\n\n    ret = mbedtls_ssl_close_notify(&ssl_pm->ssl);\n    if (ret) {\n        SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"mbedtls_ssl_close_notify() return -0x%x\", -ret);\n        if (ret == MBEDTLS_ERR_NET_CONN_RESET)\n\t\tssl->err = SSL_ERROR_SYSCALL;\n\t ret = -1; /* OpenSSL: \"Call SSL_get_error with the return value to find the reason */\n    } else {\n        struct x509_pm *x509_pm = (struct x509_pm *)ssl->session->peer->x509_pm;\n\n        x509_pm->ex_crt = NULL;\n        ret = 1; /* OpenSSL: \"The shutdown was successfully completed\"\n\t\t     ...0 means retry */\n    }\n\n    return ret;\n}\n\nint ssl_pm_clear(SSL *ssl)\n{\n    return ssl_pm_shutdown(ssl);\n}\n\n\nint ssl_pm_read(SSL *ssl, void *buffer, int len)\n{\n    int ret;\n    struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;\n\n    ret = mbedtls_ssl_read(&ssl_pm->ssl, buffer, len);\n    if (ret < 0) {\n\t //   lwsl_notice(\"%s: mbedtls_ssl_read says -0x%x\\n\", __func__, -ret);\n        SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"mbedtls_ssl_read() return -0x%x\", -ret);\n        if (ret == MBEDTLS_ERR_NET_CONN_RESET ||\n            ret <= MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE) /* fatal errors */\n\t\tssl->err = SSL_ERROR_SYSCALL;\n        ret = -1;\n    }\n\n    return ret;\n}\n\n/*\n * This returns -1, or the length sent.\n * If -1, then you need to find out if the error was\n * fatal or recoverable using SSL_get_error()\n */\nint ssl_pm_send(SSL *ssl, const void *buffer, int len)\n{\n    int ret;\n    struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;\n\n    ret = mbedtls_ssl_write(&ssl_pm->ssl, buffer, len);\n    /*\n     * We can get a positive number, which may be less than len... that\n     * much was sent successfully and you can call again to send more.\n     *\n     * We can get a negative mbedtls error code... if WANT_WRITE or WANT_READ,\n     * it's nonfatal and means it should be retried as-is.  If something else,\n     * it's fatal actually.\n     *\n     * If this function returns something other than a positive value or\n     * MBEDTLS_ERR_SSL_WANT_READ/WRITE, the ssl context becomes unusable, and\n     * you should either free it or call mbedtls_ssl_session_reset() on it\n     * before re-using it for a new connection; the current connection must\n     * be closed.\n     *\n     * When this function returns MBEDTLS_ERR_SSL_WANT_WRITE/READ, it must be\n     * called later with the same arguments, until it returns a positive value.\n     */\n\n    if (ret < 0) {\n\t    SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"mbedtls_ssl_write() return -0x%x\", -ret);\n\tswitch (ret) {\n\tcase MBEDTLS_ERR_NET_SEND_FAILED:\n\tcase MBEDTLS_ERR_NET_CONN_RESET:\n\t\tssl->err = SSL_ERROR_SYSCALL;\n\t\tbreak;\n\tcase MBEDTLS_ERR_SSL_WANT_WRITE:\n\t\tssl->err = SSL_ERROR_WANT_WRITE;\n\t\tbreak;\n\tcase MBEDTLS_ERR_SSL_WANT_READ:\n\t\tssl->err = SSL_ERROR_WANT_READ;\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tret = -1;\n    }\n\n    return ret;\n}\n\nint ssl_pm_pending(const SSL *ssl)\n{\n    struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;\n\n    return mbedtls_ssl_get_bytes_avail(&ssl_pm->ssl);\n}\n\nvoid ssl_pm_set_fd(SSL *ssl, int fd, int mode)\n{\n    struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;\n\n    ssl_pm->fd.fd = fd;\n}\n\nint ssl_pm_get_fd(const SSL *ssl, int mode)\n{\n    struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;\n\n    return ssl_pm->fd.fd;\n}\n\nOSSL_HANDSHAKE_STATE ssl_pm_get_state(const SSL *ssl)\n{\n    OSSL_HANDSHAKE_STATE state;\n\n    struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;\n\n    switch (ssl_pm->ssl.state)\n    {\n        case MBEDTLS_SSL_CLIENT_HELLO:\n            state = TLS_ST_CW_CLNT_HELLO;\n            break;\n        case MBEDTLS_SSL_SERVER_HELLO:\n            state = TLS_ST_SW_SRVR_HELLO;\n            break;\n        case MBEDTLS_SSL_SERVER_CERTIFICATE:\n            state = TLS_ST_SW_CERT;\n            break;\n        case MBEDTLS_SSL_SERVER_HELLO_DONE:\n            state = TLS_ST_SW_SRVR_DONE;\n            break;\n        case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:\n            state = TLS_ST_CW_KEY_EXCH;\n            break;\n        case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:\n            state = TLS_ST_CW_CHANGE;\n            break;\n        case MBEDTLS_SSL_CLIENT_FINISHED:\n            state = TLS_ST_CW_FINISHED;\n            break;\n        case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:\n            state = TLS_ST_SW_CHANGE;\n            break;\n        case MBEDTLS_SSL_SERVER_FINISHED:\n            state = TLS_ST_SW_FINISHED;\n            break;\n        case MBEDTLS_SSL_CLIENT_CERTIFICATE:\n            state = TLS_ST_CW_CERT;\n            break;\n        case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:\n            state = TLS_ST_SR_KEY_EXCH;\n            break;\n        case MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET:\n            state = TLS_ST_SW_SESSION_TICKET;\n            break;\n        case MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT:\n            state = TLS_ST_SW_CERT_REQ;\n            break;\n        case MBEDTLS_SSL_HANDSHAKE_OVER:\n            state = TLS_ST_OK;\n            break;\n        default :\n            state = TLS_ST_BEFORE;\n            break;\n    }\n\n    return state;\n}\n\nint x509_pm_show_info(X509 *x)\n{\n    int ret;\n    char *buf;\n    mbedtls_x509_crt *x509_crt;\n    struct x509_pm *x509_pm = x->x509_pm;\n\n    if (x509_pm->x509_crt)\n        x509_crt = x509_pm->x509_crt;\n    else if (x509_pm->ex_crt)\n        x509_crt = x509_pm->ex_crt;\n    else\n        x509_crt = NULL;\n\n    if (!x509_crt)\n        return -1;\n\n    buf = ssl_mem_malloc(X509_INFO_STRING_LENGTH);\n    if (!buf) {\n        SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"no enough memory > (buf)\");\n        goto no_mem;\n    }\n\n    ret = mbedtls_x509_crt_info(buf, X509_INFO_STRING_LENGTH - 1, \"\", x509_crt);\n    if (ret <= 0) {\n        SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"mbedtls_x509_crt_info() return -0x%x\", -ret);\n        goto mbedtls_err1;\n    }\n\n    buf[ret] = 0;\n\n    ssl_mem_free(buf);\n\n    SSL_DEBUG(SSL_DEBUG_ON, \"%s\", buf);\n\n    return 0;\n\nmbedtls_err1:\n    ssl_mem_free(buf);\nno_mem:\n    return -1;\n}\n\nint x509_pm_new(X509 *x, X509 *m_x)\n{\n    struct x509_pm *x509_pm;\n\n    x509_pm = ssl_mem_zalloc(sizeof(struct x509_pm));\n    if (!x509_pm) {\n        SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"no enough memory > (x509_pm)\");\n        goto failed1;\n    }\n\n    x->x509_pm = x509_pm;\n\n    if (m_x) {\n        struct x509_pm *m_x509_pm = (struct x509_pm *)m_x->x509_pm;\n\n        x509_pm->ex_crt = m_x509_pm->x509_crt;\n    }\n\n    return 0;\n\nfailed1:\n    return -1;\n}\n\nvoid x509_pm_free(X509 *x)\n{\n    struct x509_pm *x509_pm = (struct x509_pm *)x->x509_pm;\n\n    if (x509_pm->x509_crt) {\n        mbedtls_x509_crt_free(x509_pm->x509_crt);\n\n        ssl_mem_free(x509_pm->x509_crt);\n        x509_pm->x509_crt = NULL;\n    }\n\n    ssl_mem_free(x->x509_pm);\n    x->x509_pm = NULL;\n}\n\nint x509_pm_load(X509 *x, const unsigned char *buffer, int len)\n{\n    int ret;\n    unsigned char *load_buf;\n    struct x509_pm *x509_pm = (struct x509_pm *)x->x509_pm;\n\n\tif (x509_pm->x509_crt)\n        mbedtls_x509_crt_free(x509_pm->x509_crt);\n\n    if (!x509_pm->x509_crt) {\n        x509_pm->x509_crt = ssl_mem_malloc(sizeof(mbedtls_x509_crt));\n        if (!x509_pm->x509_crt) {\n            SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"no enough memory > (x509_pm->x509_crt)\");\n            goto no_mem;\n        }\n    }\n\n    mbedtls_x509_crt_init(x509_pm->x509_crt);\n    if (buffer[0] != 0x30) {\n\t    load_buf = ssl_mem_malloc(len + 1);\n\t    if (!load_buf) {\n\t\tSSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"no enough memory > (load_buf)\");\n\t\tgoto failed;\n\t    }\n\n\t    ssl_memcpy(load_buf, buffer, len);\n\t    load_buf[len] = '\\0';\n\n\t    ret = mbedtls_x509_crt_parse(x509_pm->x509_crt, load_buf, len + 1);\n\t    ssl_mem_free(load_buf);\n    } else {\n\t    printf(\"parsing as der\\n\");\n\n\t    ret = mbedtls_x509_crt_parse_der(x509_pm->x509_crt, buffer, len);\n    }\n\n    if (ret) {\n        printf(\"mbedtls_x509_crt_parse return -0x%x\", -ret);\n        goto failed;\n    }\n\n    return 0;\n\nfailed:\n    mbedtls_x509_crt_free(x509_pm->x509_crt);\n    ssl_mem_free(x509_pm->x509_crt);\n    x509_pm->x509_crt = NULL;\nno_mem:\n    return -1;\n}\n\nint pkey_pm_new(EVP_PKEY *pk, EVP_PKEY *m_pkey)\n{\n    struct pkey_pm *pkey_pm;\n\n    pkey_pm = ssl_mem_zalloc(sizeof(struct pkey_pm));\n    if (!pkey_pm)\n        return -1;\n\n    pk->pkey_pm = pkey_pm;\n\n    if (m_pkey) {\n        struct pkey_pm *m_pkey_pm = (struct pkey_pm *)m_pkey->pkey_pm;\n\n        pkey_pm->ex_pkey = m_pkey_pm->pkey;\n    }\n\n    return 0;\n}\n\nvoid pkey_pm_free(EVP_PKEY *pk)\n{\n    struct pkey_pm *pkey_pm = (struct pkey_pm *)pk->pkey_pm;\n\n    if (pkey_pm->pkey) {\n        mbedtls_pk_free(pkey_pm->pkey);\n\n        ssl_mem_free(pkey_pm->pkey);\n        pkey_pm->pkey = NULL;\n    }\n\n    ssl_mem_free(pk->pkey_pm);\n    pk->pkey_pm = NULL;\n}\n\nint pkey_pm_load(EVP_PKEY *pk, const unsigned char *buffer, int len)\n{\n    int ret;\n    unsigned char *load_buf;\n    struct pkey_pm *pkey_pm = (struct pkey_pm *)pk->pkey_pm;\n\n    if (pkey_pm->pkey)\n        mbedtls_pk_free(pkey_pm->pkey);\n\n    if (!pkey_pm->pkey) {\n        pkey_pm->pkey = ssl_mem_malloc(sizeof(mbedtls_pk_context));\n        if (!pkey_pm->pkey) {\n            SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"no enough memory > (pkey_pm->pkey)\");\n            goto no_mem;\n        }\n    }\n\n    load_buf = ssl_mem_malloc(len + 1);\n    if (!load_buf) {\n        SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"no enough memory > (load_buf)\");\n        goto failed;\n    }\n\n    ssl_memcpy(load_buf, buffer, len);\n    load_buf[len] = '\\0';\n\n    mbedtls_pk_init(pkey_pm->pkey);\n\n    ret = mbedtls_pk_parse_key(pkey_pm->pkey, load_buf, len + 1, NULL, 0);\n    ssl_mem_free(load_buf);\n\n    if (ret) {\n        SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, \"mbedtls_pk_parse_key return -0x%x\", -ret);\n        goto failed;\n    }\n\n    return 0;\n\nfailed:\n    mbedtls_pk_free(pkey_pm->pkey);\n    ssl_mem_free(pkey_pm->pkey);\n    pkey_pm->pkey = NULL;\nno_mem:\n    return -1;\n}\n\n\n\nvoid ssl_pm_set_bufflen(SSL *ssl, int len)\n{\n    max_content_len = len;\n}\n\nlong ssl_pm_get_verify_result(const SSL *ssl)\n{\n\tuint32_t ret;\n\tlong verify_result;\n\tstruct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;\n\n\tret = mbedtls_ssl_get_verify_result(&ssl_pm->ssl);\n\tif (!ret)\n\t\treturn X509_V_OK;\n\n\tif (ret & MBEDTLS_X509_BADCERT_NOT_TRUSTED ||\n\t\t(ret & MBEDTLS_X509_BADCRL_NOT_TRUSTED))\n\t\tverify_result = X509_V_ERR_INVALID_CA;\n\n\telse if (ret & MBEDTLS_X509_BADCERT_CN_MISMATCH)\n\t\tverify_result = X509_V_ERR_HOSTNAME_MISMATCH;\n\n\telse if ((ret & MBEDTLS_X509_BADCERT_BAD_KEY) ||\n\t\t(ret & MBEDTLS_X509_BADCRL_BAD_KEY))\n\t\tverify_result = X509_V_ERR_CA_KEY_TOO_SMALL;\n\n\telse if ((ret & MBEDTLS_X509_BADCERT_BAD_MD) ||\n\t\t(ret & MBEDTLS_X509_BADCRL_BAD_MD))\n\t\tverify_result = X509_V_ERR_CA_MD_TOO_WEAK;\n\n\telse if ((ret & MBEDTLS_X509_BADCERT_FUTURE) ||\n\t\t(ret & MBEDTLS_X509_BADCRL_FUTURE))\n\t\tverify_result = X509_V_ERR_CERT_NOT_YET_VALID;\n\n\telse if ((ret & MBEDTLS_X509_BADCERT_EXPIRED) ||\n\t\t(ret & MBEDTLS_X509_BADCRL_EXPIRED))\n\t\tverify_result = X509_V_ERR_CERT_HAS_EXPIRED;\n\n\telse\n\t\tverify_result = X509_V_ERR_UNSPECIFIED;\n\n\tSSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL,\n\t\t  \"mbedtls_ssl_get_verify_result() return 0x%x\", ret);\n\n\treturn verify_result;\n}\n\n/**\n * @brief set expected hostname on peer cert CN\n */\n\nint X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param,\n                                const char *name, size_t namelen)\n{\n\tSSL *ssl = (SSL *)((char *)param - offsetof(SSL, param));\n\tstruct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;\n\tchar *name_cstr = NULL;\n\n\tif (namelen) {\n\t\tname_cstr = malloc(namelen + 1);\n\t\tif (!name_cstr)\n\t\t\treturn 0;\n\t\tmemcpy(name_cstr, name, namelen);\n\t\tname_cstr[namelen] = '\\0';\n\t\tname = name_cstr;\n\t}\n\n\tmbedtls_ssl_set_hostname(&ssl_pm->ssl, name);\n\n\tif (namelen)\n\t\tfree(name_cstr);\n\n\treturn 1;\n}\n\nvoid _ssl_set_alpn_list(const SSL *ssl)\n{\n\tif (ssl->alpn_protos) {\n\t\tif (mbedtls_ssl_conf_alpn_protocols(&((struct ssl_pm *)(ssl->ssl_pm))->conf, ssl->alpn_protos))\n\t\t\tfprintf(stderr, \"mbedtls_ssl_conf_alpn_protocols failed\\n\");\n\n\t\treturn;\n\t}\n\tif (!ssl->ctx->alpn_protos)\n\t\treturn;\n\tif (mbedtls_ssl_conf_alpn_protocols(&((struct ssl_pm *)(ssl->ssl_pm))->conf, ssl->ctx->alpn_protos))\n\t\tfprintf(stderr, \"mbedtls_ssl_conf_alpn_protocols failed\\n\");\n}\n\nvoid SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,\n                            unsigned int *len)\n{\n\tconst char *alp = mbedtls_ssl_get_alpn_protocol(&((struct ssl_pm *)(ssl->ssl_pm))->ssl);\n\n\t*data = (const unsigned char *)alp;\n\tif (alp)\n\t\t*len = strlen(alp);\n\telse\n\t\t*len = 0;\n}\n\nint SSL_set_sni_callback(SSL *ssl, int(*cb)(void *, mbedtls_ssl_context *,\n\t\t\t const unsigned char *, size_t), void *param)\n{\n\tstruct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm;\n\n\tmbedtls_ssl_conf_sni(&ssl_pm->conf, cb, param);\n\n\treturn 0;\n}\n\nSSL *SSL_SSL_from_mbedtls_ssl_context(mbedtls_ssl_context *msc)\n{\n\tstruct ssl_pm *ssl_pm = (struct ssl_pm *)((char *)msc - offsetof(struct ssl_pm, ssl));\n\n\treturn ssl_pm->owner;\n}\n\n#include \"ssl_cert.h\"\n\nvoid SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx)\n{\n\tstruct ssl_pm *ssl_pm = ssl->ssl_pm;\n\tstruct x509_pm *x509_pm = (struct x509_pm *)ctx->cert->x509->x509_pm;\n\tstruct x509_pm *x509_pm_ca = (struct x509_pm *)ctx->client_CA->x509_pm;\n\n\tstruct pkey_pm *pkey_pm = (struct pkey_pm *)ctx->cert->pkey->pkey_pm;\n\tint mode;\n\n\tif (ssl->cert)\n\t\tssl_cert_free(ssl->cert);\n\tssl->ctx = ctx;\n\tssl->cert = __ssl_cert_new(ctx->cert);\n\n\tif (ctx->verify_mode == SSL_VERIFY_PEER)\n\t\tmode = MBEDTLS_SSL_VERIFY_OPTIONAL;\n\telse if (ctx->verify_mode == SSL_VERIFY_FAIL_IF_NO_PEER_CERT)\n\t\tmode = MBEDTLS_SSL_VERIFY_OPTIONAL;\n\telse if (ctx->verify_mode == SSL_VERIFY_CLIENT_ONCE)\n\t\tmode = MBEDTLS_SSL_VERIFY_UNSET;\n\telse\n\t        mode = MBEDTLS_SSL_VERIFY_NONE;\n\n\t    // printf(\"ssl: %p, client ca x509_crt %p, mbedtls mode %d\\n\", ssl, x509_pm_ca->x509_crt, mode);\n\n\t/* apply new ctx cert to ssl */\n\n\tssl->verify_mode = ctx->verify_mode;\n\n\tmbedtls_ssl_set_hs_ca_chain(&ssl_pm->ssl, x509_pm_ca->x509_crt, NULL);\n\tmbedtls_ssl_set_hs_own_cert(&ssl_pm->ssl, x509_pm->x509_crt, pkey_pm->pkey);\n\tmbedtls_ssl_set_hs_authmode(&ssl_pm->ssl, mode);\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/mbedtls/wrapper/platform/ssl_port.c",
    "content": "// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"ssl_port.h\"\n\n/*********************************************************************************************/\n/********************************* SSL general interface *************************************/\n\nvoid *ssl_mem_zalloc(size_t size)\n{\n    void *p = malloc(size);\n\n    if (p)\n        memset(p, 0, size);\n\n    return p;\n}\n\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/private.h",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n *\n *  This is included from core/private.h if LWS_WITH_TLS\n */\n\n#if defined(LWS_WITH_TLS)\n\n#if defined(USE_WOLFSSL)\n #if defined(USE_OLD_CYASSL)\n  #if defined(_WIN32)\n   #include <IDE/WIN/user_settings.h>\n   #include <cyassl/ctaocrypt/settings.h>\n  #else\n   #include <cyassl/options.h>\n  #endif\n  #include <cyassl/openssl/ssl.h>\n  #include <cyassl/error-ssl.h>\n #else\n  #if defined(_WIN32)\n   #include <IDE/WIN/user_settings.h>\n   #include <wolfssl/wolfcrypt/settings.h>\n  #else\n   #include <wolfssl/options.h>\n  #endif\n  #include <wolfssl/openssl/ssl.h>\n  #include <wolfssl/error-ssl.h>\n  #define OPENSSL_NO_TLSEXT\n #endif /* not USE_OLD_CYASSL */\n#else /* WOLFSSL */\n #if defined(LWS_WITH_ESP32)\n  #define OPENSSL_NO_TLSEXT\n  #undef MBEDTLS_CONFIG_FILE\n  #define MBEDTLS_CONFIG_FILE <mbedtls/esp_config.h>\n  #include <mbedtls/ssl.h>\n  #include <mbedtls/x509_crt.h>\n  #include \"tls/mbedtls/wrapper/include/openssl/ssl.h\" /* wrapper !!!! */\n #else /* not esp32 */\n  #if defined(LWS_WITH_MBEDTLS)\n   #include <mbedtls/ssl.h>\n   #include <mbedtls/x509_crt.h>\n   #include <mbedtls/x509_csr.h>\n   #include \"tls/mbedtls/wrapper/include/openssl/ssl.h\" /* wrapper !!!! */\n  #else\n   #include <openssl/ssl.h>\n   #include <openssl/evp.h>\n   #include <openssl/err.h>\n   #include <openssl/md5.h>\n   #include <openssl/sha.h>\n   #ifdef LWS_HAVE_OPENSSL_ECDH_H\n    #include <openssl/ecdh.h>\n   #endif\n   #include <openssl/x509v3.h>\n  #endif /* not mbedtls */\n  #if defined(OPENSSL_VERSION_NUMBER)\n   #if (OPENSSL_VERSION_NUMBER < 0x0009080afL)\n/* later openssl defines this to negate the presence of tlsext... but it was only\n * introduced at 0.9.8j.  Earlier versions don't know it exists so don't\n * define it... making it look like the feature exists...\n */\n    #define OPENSSL_NO_TLSEXT\n   #endif\n  #endif\n #endif /* not ESP32 */\n#endif /* not USE_WOLFSSL */\n\n#endif /* LWS_WITH_TLS */\n\nenum lws_tls_extant {\n\tLWS_TLS_EXTANT_NO,\n\tLWS_TLS_EXTANT_YES,\n\tLWS_TLS_EXTANT_ALTERNATIVE\n};\n\nstruct lws_context_per_thread;\n\nstruct lws_tls_ops {\n\tint (*fake_POLLIN_for_buffered)(struct lws_context_per_thread *pt);\n\tint (*periodic_housekeeping)(struct lws_context *context, time_t now);\n};\n\n#if defined(LWS_WITH_TLS)\n\ntypedef SSL lws_tls_conn;\ntypedef SSL_CTX lws_tls_ctx;\ntypedef BIO lws_tls_bio;\ntypedef X509 lws_tls_x509;\n\n\n#define LWS_SSL_ENABLED(context) (context->tls.use_ssl)\n\nextern const struct lws_tls_ops tls_ops_openssl, tls_ops_mbedtls;\n\nstruct lws_context_tls {\n\tchar alpn_discovered[32];\n\tconst char *alpn_default;\n\ttime_t last_cert_check_s;\n};\n\nstruct lws_pt_tls {\n\tstruct lws *pending_read_list; /* linked list */\n};\n\nstruct lws_tls_ss_pieces;\n\nstruct alpn_ctx {\n\tuint8_t data[23];\n\tuint8_t len;\n};\n\nstruct lws_vhost_tls {\n\tlws_tls_ctx *ssl_ctx;\n\tlws_tls_ctx *ssl_client_ctx;\n\tconst char *alpn;\n\tstruct lws_tls_ss_pieces *ss; /* for acme tls certs */\n\tchar *alloc_cert_path;\n\tchar *key_path;\n#if defined(LWS_WITH_MBEDTLS)\n\tlws_tls_x509 *x509_client_CA;\n#endif\n\tchar ecdh_curve[16];\n\tstruct alpn_ctx alpn_ctx;\n\n\tint use_ssl;\n\tint allow_non_ssl_on_ssl_port;\n\tint ssl_info_event_mask;\n\n\tunsigned int user_supplied_ssl_ctx:1;\n\tunsigned int skipped_certs:1;\n};\n\nstruct lws_lws_tls {\n\tlws_tls_conn *ssl;\n\tlws_tls_bio *client_bio;\n\tstruct lws *pending_read_list_prev, *pending_read_list_next;\n\tunsigned int use_ssl;\n\tunsigned int redirect_to_https:1;\n};\n\nLWS_EXTERN void\nlws_context_init_alpn(struct lws_vhost *vhost);\nLWS_EXTERN enum lws_tls_extant\nlws_tls_use_any_upgrade_check_extant(const char *name);\nLWS_EXTERN int openssl_websocket_private_data_index;\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_ssl_capable_read(struct lws *wsi, unsigned char *buf, int len);\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_ssl_capable_write(struct lws *wsi, unsigned char *buf, int len);\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_ssl_pending(struct lws *wsi);\nLWS_EXTERN int\nlws_context_init_ssl_library(const struct lws_context_creation_info *info);\nLWS_EXTERN int LWS_WARN_UNUSED_RESULT\nlws_server_socket_service_ssl(struct lws *new_wsi, lws_sockfd_type accept_fd);\nLWS_EXTERN int\nlws_ssl_close(struct lws *wsi);\nLWS_EXTERN void\nlws_ssl_SSL_CTX_destroy(struct lws_vhost *vhost);\nLWS_EXTERN void\nlws_ssl_context_destroy(struct lws_context *context);\nvoid\n__lws_ssl_remove_wsi_from_buffered_list(struct lws *wsi);\nLWS_VISIBLE void\nlws_ssl_remove_wsi_from_buffered_list(struct lws *wsi);\nLWS_EXTERN int\nlws_ssl_client_bio_create(struct lws *wsi);\nLWS_EXTERN int\nlws_ssl_client_connect1(struct lws *wsi);\nLWS_EXTERN int\nlws_ssl_client_connect2(struct lws *wsi, char *errbuf, int len);\nLWS_EXTERN void\nlws_ssl_elaborate_error(void);\nLWS_EXTERN int\nlws_tls_fake_POLLIN_for_buffered(struct lws_context_per_thread *pt);\nLWS_EXTERN int\nlws_gate_accepts(struct lws_context *context, int on);\nLWS_EXTERN void\nlws_ssl_bind_passphrase(lws_tls_ctx *ssl_ctx,\n\t\t\tconst struct lws_context_creation_info *info);\nLWS_EXTERN void\nlws_ssl_info_callback(const lws_tls_conn *ssl, int where, int ret);\nLWS_EXTERN int\nlws_tls_openssl_cert_info(X509 *x509, enum lws_tls_cert_info type,\n\t\t\t  union lws_tls_cert_info_results *buf, size_t len);\nLWS_EXTERN int\nlws_tls_check_all_cert_lifetimes(struct lws_context *context);\nLWS_EXTERN int\nlws_tls_server_certs_load(struct lws_vhost *vhost, struct lws *wsi,\n\t\t\t  const char *cert, const char *private_key,\n\t\t\t  const char *mem_cert, size_t len_mem_cert,\n\t\t\t  const char *mem_privkey, size_t mem_privkey_len);\nLWS_EXTERN enum lws_tls_extant\nlws_tls_generic_cert_checks(struct lws_vhost *vhost, const char *cert,\n\t\t\t    const char *private_key);\nLWS_EXTERN int\nlws_tls_alloc_pem_to_der_file(struct lws_context *context, const char *filename,\n\t\t\tconst char *inbuf, lws_filepos_t inlen,\n\t\t      uint8_t **buf, lws_filepos_t *amount);\n\n#if !defined(LWS_NO_SERVER)\n LWS_EXTERN int\n lws_context_init_server_ssl(const struct lws_context_creation_info *info,\n\t\t\t     struct lws_vhost *vhost);\n void\n lws_tls_acme_sni_cert_destroy(struct lws_vhost *vhost);\n#else\n #define lws_context_init_server_ssl(_a, _b) (0)\n #define lws_tls_acme_sni_cert_destroy(_a)\n#endif\n\nLWS_EXTERN void\nlws_ssl_destroy(struct lws_vhost *vhost);\nLWS_EXTERN char *\nlws_ssl_get_error_string(int status, int ret, char *buf, size_t len);\n\n/*\n * lws_tls_ abstract backend implementations\n */\n\nLWS_EXTERN int\nlws_tls_server_client_cert_verify_config(struct lws_vhost *vh);\nLWS_EXTERN int\nlws_tls_server_vhost_backend_init(const struct lws_context_creation_info *info,\n\t\t\t\t  struct lws_vhost *vhost, struct lws *wsi);\nLWS_EXTERN int\nlws_tls_server_new_nonblocking(struct lws *wsi, lws_sockfd_type accept_fd);\n\nLWS_EXTERN enum lws_ssl_capable_status\nlws_tls_server_accept(struct lws *wsi);\n\nLWS_EXTERN enum lws_ssl_capable_status\nlws_tls_server_abort_connection(struct lws *wsi);\n\nLWS_EXTERN enum lws_ssl_capable_status\n__lws_tls_shutdown(struct lws *wsi);\n\nLWS_EXTERN enum lws_ssl_capable_status\nlws_tls_client_connect(struct lws *wsi);\nLWS_EXTERN int\nlws_tls_client_confirm_peer_cert(struct lws *wsi, char *ebuf, int ebuf_len);\nLWS_EXTERN int\nlws_tls_client_create_vhost_context(struct lws_vhost *vh,\n\t\t\t\t    const struct lws_context_creation_info *info,\n\t\t\t\t    const char *cipher_list,\n\t\t\t\t    const char *ca_filepath,\n\t\t\t\t    const char *cert_filepath,\n\t\t\t\t    const char *private_key_filepath);\n\nLWS_EXTERN lws_tls_ctx *\nlws_tls_ctx_from_wsi(struct lws *wsi);\nLWS_EXTERN int\nlws_ssl_get_error(struct lws *wsi, int n);\n\nLWS_EXTERN int\nlws_context_init_client_ssl(const struct lws_context_creation_info *info,\n\t\t\t    struct lws_vhost *vhost);\n\nLWS_EXTERN void\nlws_ssl_info_callback(const lws_tls_conn *ssl, int where, int ret);\n\nint\nlws_tls_fake_POLLIN_for_buffered(struct lws_context_per_thread *pt);\n\n#endif"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/tls-client.c",
    "content": "/*\n * libwebsockets - client-related ssl code independent of backend\n *\n * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n\nint\nlws_ssl_client_connect1(struct lws *wsi)\n{\n\tstruct lws_context *context = wsi->context;\n\tint n = 0;\n\n\tlws_latency_pre(context, wsi);\n\tn = lws_tls_client_connect(wsi);\n\tlws_latency(context, wsi, \"SSL_connect hs\", n, n > 0);\n\n\tswitch (n) {\n\tcase LWS_SSL_CAPABLE_ERROR:\n\t\treturn -1;\n\tcase LWS_SSL_CAPABLE_DONE:\n\t\treturn 1; /* connected */\n\tcase LWS_SSL_CAPABLE_MORE_SERVICE_WRITE:\n\t\tlws_callback_on_writable(wsi);\n\t\t/* fallthru */\n\tcase LWS_SSL_CAPABLE_MORE_SERVICE_READ:\n\t\tlwsi_set_state(wsi, LRS_WAITING_SSL);\n\t\tbreak;\n\tcase LWS_SSL_CAPABLE_MORE_SERVICE:\n\t\tbreak;\n\t}\n\n\treturn 0; /* retry */\n}\n\nint\nlws_ssl_client_connect2(struct lws *wsi, char *errbuf, int len)\n{\n\tint n = 0;\n\n\tif (lwsi_state(wsi) == LRS_WAITING_SSL) {\n\t\tlws_latency_pre(wsi->context, wsi);\n\n\t\tn = lws_tls_client_connect(wsi);\n\t\tlwsl_debug(\"%s: SSL_connect says %d\\n\", __func__, n);\n\t\tlws_latency(wsi->context, wsi,\n\t\t\t    \"SSL_connect LRS_WAITING_SSL\", n, n > 0);\n\n\t\tswitch (n) {\n\t\tcase LWS_SSL_CAPABLE_ERROR:\n\t\t\tlws_snprintf(errbuf, len, \"client connect failed\");\n\t\t\treturn -1;\n\t\tcase LWS_SSL_CAPABLE_DONE:\n\t\t\tbreak; /* connected */\n\t\tcase LWS_SSL_CAPABLE_MORE_SERVICE_WRITE:\n\t\t\tlws_callback_on_writable(wsi);\n\t\t\t/* fallthru */\n\t\tcase LWS_SSL_CAPABLE_MORE_SERVICE_READ:\n\t\t\tlwsi_set_state(wsi, LRS_WAITING_SSL);\n\t\t\t/* fallthru */\n\t\tcase LWS_SSL_CAPABLE_MORE_SERVICE:\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tif (lws_tls_client_confirm_peer_cert(wsi, errbuf, len))\n\t\treturn -1;\n\n\treturn 1;\n}\n\n\nint lws_context_init_client_ssl(const struct lws_context_creation_info *info,\n\t\t\t\tstruct lws_vhost *vhost)\n{\n\tconst char *ca_filepath = info->ssl_ca_filepath;\n\tconst char *cipher_list = info->ssl_cipher_list;\n\tconst char *private_key_filepath = info->ssl_private_key_filepath;\n\tconst char *cert_filepath = info->ssl_cert_filepath;\n\tstruct lws wsi;\n\n\tif (vhost->options & LWS_SERVER_OPTION_ONLY_RAW)\n\t\treturn 0;\n\n\t/*\n\t *  for backwards-compatibility default to using ssl_... members, but\n\t * if the newer client-specific ones are given, use those\n\t */\n\tif (info->client_ssl_cipher_list)\n\t\tcipher_list = info->client_ssl_cipher_list;\n\tif (info->client_ssl_cert_filepath)\n\t\tcert_filepath = info->client_ssl_cert_filepath;\n\tif (info->client_ssl_private_key_filepath)\n\t\tprivate_key_filepath = info->client_ssl_private_key_filepath;\n\n\tif (info->client_ssl_ca_filepath)\n\t\tca_filepath = info->client_ssl_ca_filepath;\n\n\tif (!lws_check_opt(info->options, LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT))\n\t\treturn 0;\n\n\tif (vhost->tls.ssl_client_ctx)\n\t\treturn 0;\n\n\tif (info->provided_client_ssl_ctx) {\n\t\t/* use the provided OpenSSL context if given one */\n\t\tvhost->tls.ssl_client_ctx = info->provided_client_ssl_ctx;\n\t\t/* nothing for lib to delete */\n\t\tvhost->tls.user_supplied_ssl_ctx = 1;\n\n\t\treturn 0;\n\t}\n\n\tif (lws_tls_client_create_vhost_context(vhost, info, cipher_list,\n\t\t\t\t\t\tca_filepath, cert_filepath,\n\t\t\t\t\t\tprivate_key_filepath))\n\t\treturn 1;\n\n\tlwsl_notice(\"created client ssl context for %s\\n\", vhost->name);\n\n\t/*\n\t * give him a fake wsi with context set, so he can use\n\t * lws_get_context() in the callback\n\t */\n\tmemset(&wsi, 0, sizeof(wsi));\n\twsi.vhost = vhost;\n\twsi.context = vhost->context;\n\n\tvhost->protocols[0].callback(&wsi,\n\t\t\tLWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,\n\t\t\t\t       vhost->tls.ssl_client_ctx, NULL, 0);\n\n\treturn 0;\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/tls-server.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n\n#if defined(LWS_WITH_MBEDTLS) || (defined(OPENSSL_VERSION_NUMBER) && \\\n\t\t\t\t  OPENSSL_VERSION_NUMBER >= 0x10002000L)\nstatic int\nalpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen,\n\tconst unsigned char *in, unsigned int inlen, void *arg)\n{\n#if !defined(LWS_WITH_MBEDTLS)\n\tstruct alpn_ctx *alpn_ctx = (struct alpn_ctx *)arg;\n\n\tif (SSL_select_next_proto((unsigned char **)out, outlen, alpn_ctx->data,\n\t\t\t\t  alpn_ctx->len, in, inlen) !=\n\t    OPENSSL_NPN_NEGOTIATED)\n\t\treturn SSL_TLSEXT_ERR_NOACK;\n#endif\n\n\treturn SSL_TLSEXT_ERR_OK;\n}\n#endif\n\nvoid\nlws_context_init_alpn(struct lws_vhost *vhost)\n{\n#if defined(LWS_WITH_MBEDTLS) || (defined(OPENSSL_VERSION_NUMBER) && \\\n\t\t\t\t  OPENSSL_VERSION_NUMBER >= 0x10002000L)\n\tconst char *alpn_comma = vhost->context->tls.alpn_default;\n\n\tif (vhost->tls.alpn)\n\t\talpn_comma = vhost->tls.alpn;\n\n\tlwsl_info(\" Server '%s' advertising ALPN: %s\\n\",\n\t\t    vhost->name, alpn_comma);\n\tvhost->tls.alpn_ctx.len = lws_alpn_comma_to_openssl(alpn_comma,\n\t\t\t\t\tvhost->tls.alpn_ctx.data,\n\t\t\t\t\tsizeof(vhost->tls.alpn_ctx.data) - 1);\n\n\tSSL_CTX_set_alpn_select_cb(vhost->tls.ssl_ctx, alpn_cb, &vhost->tls.alpn_ctx);\n#else\n\tlwsl_err(\n\t\t\" HTTP2 / ALPN configured but not supported by OpenSSL 0x%lx\\n\",\n\t\t    OPENSSL_VERSION_NUMBER);\n#endif // OPENSSL_VERSION_NUMBER >= 0x10002000L\n}\n\nint\nlws_tls_server_conn_alpn(struct lws *wsi)\n{\n#if defined(LWS_WITH_MBEDTLS) || (defined(OPENSSL_VERSION_NUMBER) && \\\n\t\t\t\t  OPENSSL_VERSION_NUMBER >= 0x10002000L)\n\tconst unsigned char *name = NULL;\n\tchar cstr[10];\n\tunsigned len;\n\n\tSSL_get0_alpn_selected(wsi->tls.ssl, &name, &len);\n\tif (!len) {\n\t\tlwsl_info(\"no ALPN upgrade\\n\");\n\t\treturn 0;\n\t}\n\n\tif (len > sizeof(cstr) - 1)\n\t\tlen = sizeof(cstr) - 1;\n\n\tmemcpy(cstr, name, len);\n\tcstr[len] = '\\0';\n\n\tlwsl_info(\"negotiated '%s' using ALPN\\n\", cstr);\n\twsi->tls.use_ssl |= LCCSCF_USE_SSL;\n\n\treturn lws_role_call_alpn_negotiated(wsi, (const char *)cstr);\n#endif // OPENSSL_VERSION_NUMBER >= 0x10002000L\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\nlws_context_init_server_ssl(const struct lws_context_creation_info *info,\n\t\t\t    struct lws_vhost *vhost)\n{\n\tstruct lws_context *context = vhost->context;\n\tstruct lws wsi;\n\n\tif (!lws_check_opt(info->options,\n\t\t\t   LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT)) {\n\t\tvhost->tls.use_ssl = 0;\n\n\t\treturn 0;\n\t}\n\n\t/*\n\t * If he is giving a cert filepath, take it as a sign he wants to use\n\t * it on this vhost.  User code can leave the cert filepath NULL and\n\t * set the LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX option itself, in\n\t * which case he's expected to set up the cert himself at\n\t * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS, which\n\t * provides the vhost SSL_CTX * in the user parameter.\n\t */\n\tif (info->ssl_cert_filepath)\n\t\tvhost->options |= LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX;\n\n\tif (info->port != CONTEXT_PORT_NO_LISTEN) {\n\n\t\tvhost->tls.use_ssl = lws_check_opt(vhost->options,\n\t\t\t\t\tLWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX);\n\n\t\tif (vhost->tls.use_ssl && info->ssl_cipher_list)\n\t\t\tlwsl_notice(\" SSL ciphers: '%s'\\n\",\n\t\t\t\t\t\tinfo->ssl_cipher_list);\n\n\t\tif (vhost->tls.use_ssl)\n\t\t\tlwsl_notice(\" Using SSL mode\\n\");\n\t\telse\n\t\t\tlwsl_notice(\" Using non-SSL mode\\n\");\n\t}\n\n\t/*\n\t * give him a fake wsi with context + vhost set, so he can use\n\t * lws_get_context() in the callback\n\t */\n\tmemset(&wsi, 0, sizeof(wsi));\n\twsi.vhost = vhost;\n\twsi.context = context;\n\n\t/*\n\t * as a server, if we are requiring clients to identify themselves\n\t * then set the backend up for it\n\t */\n\tif (lws_check_opt(info->options,\n\t\t\t  LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT))\n\t\t/* Normally SSL listener rejects non-ssl, optionally allow */\n\t\tvhost->tls.allow_non_ssl_on_ssl_port = 1;\n\n\t/*\n\t * give user code a chance to load certs into the server\n\t * allowing it to verify incoming client certs\n\t */\n\tif (vhost->tls.use_ssl) {\n\t\tif (lws_tls_server_vhost_backend_init(info, vhost, &wsi))\n\t\t\treturn -1;\n\n\t\tlws_tls_server_client_cert_verify_config(vhost);\n\n\t\tif (vhost->protocols[0].callback(&wsi,\n\t\t\t    LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,\n\t\t\t    vhost->tls.ssl_ctx, vhost, 0))\n\t\t\treturn -1;\n\t}\n\n\tif (vhost->tls.use_ssl)\n\t\tlws_context_init_alpn(vhost);\n\n\treturn 0;\n}\n\nLWS_VISIBLE int\nlws_server_socket_service_ssl(struct lws *wsi, lws_sockfd_type accept_fd)\n{\n\tstruct lws_context *context = wsi->context;\n\tstruct lws_vhost *vh;\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\tint n;\n        char buf[256];\n\n        (void)buf;\n\n\tif (!LWS_SSL_ENABLED(wsi->vhost))\n\t\treturn 0;\n\n\tswitch (lwsi_state(wsi)) {\n\tcase LRS_SSL_INIT:\n\n\t\tif (wsi->tls.ssl)\n\t\t\tlwsl_err(\"%s: leaking ssl\\n\", __func__);\n\t\tif (accept_fd == LWS_SOCK_INVALID)\n\t\t\tassert(0);\n\t\tif (context->simultaneous_ssl_restriction &&\n\t\t    context->simultaneous_ssl >=\n\t\t    \t    context->simultaneous_ssl_restriction) {\n\t\t\tlwsl_notice(\"unable to deal with SSL connection\\n\");\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (lws_tls_server_new_nonblocking(wsi, accept_fd)) {\n\t\t\tif (accept_fd != LWS_SOCK_INVALID)\n\t\t\t\tcompatible_close(accept_fd);\n\t\t\tgoto fail;\n\t\t}\n\n\t\tif (context->simultaneous_ssl_restriction &&\n\t\t    ++context->simultaneous_ssl ==\n\t\t\t\t    context->simultaneous_ssl_restriction)\n\t\t\t/* that was the last allowed SSL connection */\n\t\t\tlws_gate_accepts(context, 0);\n\n#if defined(LWS_WITH_STATS)\n\t\tcontext->updated = 1;\n#endif\n\t\t/*\n\t\t * we are not accepted yet, but we need to enter ourselves\n\t\t * as a live connection.  That way we can retry when more\n\t\t * pieces come if we're not sorted yet\n\t\t */\n\t\tlwsi_set_state(wsi, LRS_SSL_ACK_PENDING);\n\n\t\tlws_pt_lock(pt, __func__);\n\t\tif (__insert_wsi_socket_into_fds(context, wsi)) {\n\t\t\tlwsl_err(\"%s: failed to insert into fds\\n\", __func__);\n\t\t\tgoto fail;\n\t\t}\n\t\tlws_pt_unlock(pt);\n\n\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_SSL_ACCEPT,\n\t\t\t\tcontext->timeout_secs);\n\n\t\tlwsl_debug(\"inserted SSL accept into fds, trying SSL_accept\\n\");\n\n\t\t/* fallthru */\n\n\tcase LRS_SSL_ACK_PENDING:\n\n\t\tif (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {\n\t\t\tlwsl_err(\"%s: lws_change_pollfd failed\\n\", __func__);\n\t\t\tgoto fail;\n\t\t}\n\n\t\tlws_latency_pre(context, wsi);\n\n\t\tif (wsi->vhost->tls.allow_non_ssl_on_ssl_port) {\n\n\t\t\tn = recv(wsi->desc.sockfd, (char *)pt->serv_buf,\n\t\t\t\t context->pt_serv_buf_size, MSG_PEEK);\n\n\t\t/*\n\t\t * optionally allow non-SSL connect on SSL listening socket\n\t\t * This is disabled by default, if enabled it goes around any\n\t\t * SSL-level access control (eg, client-side certs) so leave\n\t\t * it disabled unless you know it's not a problem for you\n\t\t */\n\t\t\tif (n >= 1 && pt->serv_buf[0] >= ' ') {\n\t\t\t\t/*\n\t\t\t\t* TLS content-type for Handshake is 0x16, and\n\t\t\t\t* for ChangeCipherSpec Record, it's 0x14\n\t\t\t\t*\n\t\t\t\t* A non-ssl session will start with the HTTP\n\t\t\t\t* method in ASCII.  If we see it's not a legit\n\t\t\t\t* SSL handshake kill the SSL for this\n\t\t\t\t* connection and try to handle as a HTTP\n\t\t\t\t* connection upgrade directly.\n\t\t\t\t*/\n\t\t\t\twsi->tls.use_ssl = 0;\n\n\t\t\t\tlws_tls_server_abort_connection(wsi);\n\t\t\t\t/*\n\t\t\t\t * care... this creates wsi with no ssl\n\t\t\t\t * when ssl is enabled and normally\n\t\t\t\t * mandatory\n\t\t\t\t */\n\t\t\t\twsi->tls.ssl = NULL;\n\t\t\t\tif (lws_check_opt(context->options,\n\t\t\t\t    LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS))\n\t\t\t\t\twsi->tls.redirect_to_https = 1;\n\t\t\t\tlwsl_debug(\"accepted as non-ssl\\n\");\n\t\t\t\tgoto accepted;\n\t\t\t}\n\t\t\tif (!n) {\n\t\t\t\t/*\n\t\t\t\t * connection is gone, fail out\n\t\t\t\t */\n\t\t\t\tlwsl_debug(\"PEEKed 0\\n\");\n\t\t\t\tgoto fail;\n\t\t\t}\n\t\t\tif (n < 0 && (LWS_ERRNO == LWS_EAGAIN ||\n\t\t\t\t      LWS_ERRNO == LWS_EWOULDBLOCK)) {\n\t\t\t\t/*\n\t\t\t\t * well, we get no way to know ssl or not\n\t\t\t\t * so go around again waiting for something\n\t\t\t\t * to come and give us a hint, or timeout the\n\t\t\t\t * connection.\n\t\t\t\t */\n\t\t\t\tif (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {\n\t\t\t\t\tlwsl_info(\"%s: change_pollfd failed\\n\",\n\t\t\t\t\t\t  __func__);\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\n\t\t\t\tlwsl_info(\"SSL_ERROR_WANT_READ\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\n\t\t/* normal SSL connection processing path */\n\n#if defined(LWS_WITH_STATS)\n\t\tif (!wsi->accept_start_us)\n\t\t\twsi->accept_start_us = time_in_microseconds();\n#endif\n\t\terrno = 0;\n\t\tlws_stats_atomic_bump(wsi->context, pt,\n\t\t\t\t      LWSSTATS_C_SSL_CONNECTIONS_ACCEPT_SPIN, 1);\n\t\tn = lws_tls_server_accept(wsi);\n\t\tlws_latency(context, wsi,\n\t\t\t\"SSL_accept LRS_SSL_ACK_PENDING\\n\", n, n == 1);\n\t\tlwsl_info(\"SSL_accept says %d\\n\", n);\n\t\tswitch (n) {\n\t\tcase LWS_SSL_CAPABLE_DONE:\n\t\t\tbreak;\n\t\tcase LWS_SSL_CAPABLE_ERROR:\n\t\t\tlws_stats_atomic_bump(wsi->context, pt,\n\t\t\t\t\t      LWSSTATS_C_SSL_CONNECTIONS_FAILED, 1);\n\t                lwsl_info(\"SSL_accept failed socket %u: %d\\n\",\n\t                \t\twsi->desc.sockfd, n);\n\t\t\twsi->socket_is_permanently_unusable = 1;\n\t\t\tgoto fail;\n\n\t\tdefault: /* MORE_SERVICE */\n\t\t\treturn 0;\n\t\t}\n\n\t\tlws_stats_atomic_bump(wsi->context, pt,\n\t\t\t\t      LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED, 1);\n#if defined(LWS_WITH_STATS)\n\t\tlws_stats_atomic_bump(wsi->context, pt,\n\t\t\t\t      LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY,\n\t\t\t\t      time_in_microseconds() - wsi->accept_start_us);\n\t\twsi->accept_start_us = time_in_microseconds();\n#endif\n\naccepted:\n\n\t\t/* adapt our vhost to match the SNI SSL_CTX that was chosen */\n\t\tvh = context->vhost_list;\n\t\twhile (vh) {\n\t\t\tif (!vh->being_destroyed && wsi->tls.ssl &&\n\t\t\t    vh->tls.ssl_ctx == lws_tls_ctx_from_wsi(wsi)) {\n\t\t\t\tlwsl_info(\"setting wsi to vh %s\\n\", vh->name);\n\t\t\t\twsi->vhost = vh;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tvh = vh->vhost_next;\n\t\t}\n\n\t\t/* OK, we are accepted... give him some time to negotiate */\n\t\tlws_set_timeout(wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,\n\t\t\t\tcontext->timeout_secs);\n\n\t\tlwsi_set_state(wsi, LRS_ESTABLISHED);\n\t\tif (lws_tls_server_conn_alpn(wsi))\n\t\t\tgoto fail;\n\t\tlwsl_debug(\"accepted new SSL conn\\n\");\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn 0;\n\nfail:\n\treturn 1;\n}\n\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/tls/tls.c",
    "content": "/*\n * libwebsockets - small server side websockets and web server implementation\n *\n * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation:\n *  version 2.1 of the License.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n *  MA  02110-1301  USA\n */\n\n#include \"core/private.h\"\n\n/*\n * fakes POLLIN on all tls guys with buffered rx\n *\n * returns nonzero if any tls guys had POLLIN faked\n */\n\nint\nlws_tls_fake_POLLIN_for_buffered(struct lws_context_per_thread *pt)\n{\n\tstruct lws *wsi, *wsi_next;\n\tint ret = 0;\n\n\twsi = pt->tls.pending_read_list;\n\twhile (wsi && wsi->position_in_fds_table != LWS_NO_FDS_POS) {\n\t\twsi_next = wsi->tls.pending_read_list_next;\n\t\tpt->fds[wsi->position_in_fds_table].revents |=\n\t\t\tpt->fds[wsi->position_in_fds_table].events & LWS_POLLIN;\n\t\tret |= pt->fds[wsi->position_in_fds_table].revents & LWS_POLLIN;\n\n\t\twsi = wsi_next;\n\t}\n\n\treturn !!ret;\n}\n\nvoid\n__lws_ssl_remove_wsi_from_buffered_list(struct lws *wsi)\n{\n\tstruct lws_context *context = wsi->context;\n\tstruct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];\n\n\tif (!wsi->tls.pending_read_list_prev &&\n\t    !wsi->tls.pending_read_list_next &&\n\t    pt->tls.pending_read_list != wsi)\n\t\t/* we are not on the list */\n\t\treturn;\n\n\t/* point previous guy's next to our next */\n\tif (!wsi->tls.pending_read_list_prev)\n\t\tpt->tls.pending_read_list = wsi->tls.pending_read_list_next;\n\telse\n\t\twsi->tls.pending_read_list_prev->tls.pending_read_list_next =\n\t\t\twsi->tls.pending_read_list_next;\n\n\t/* point next guy's previous to our previous */\n\tif (wsi->tls.pending_read_list_next)\n\t\twsi->tls.pending_read_list_next->tls.pending_read_list_prev =\n\t\t\twsi->tls.pending_read_list_prev;\n\n\twsi->tls.pending_read_list_prev = NULL;\n\twsi->tls.pending_read_list_next = NULL;\n}\n\nvoid\nlws_ssl_remove_wsi_from_buffered_list(struct lws *wsi)\n{\n\tstruct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];\n\n\tlws_pt_lock(pt, __func__);\n\t__lws_ssl_remove_wsi_from_buffered_list(wsi);\n\tlws_pt_unlock(pt);\n}\n\n#if defined(LWS_WITH_ESP32)\nint alloc_file(struct lws_context *context, const char *filename, uint8_t **buf,\n\t       lws_filepos_t *amount)\n{\n\tnvs_handle nvh;\n\tsize_t s;\n\tint n = 0;\n\n\tESP_ERROR_CHECK(nvs_open(\"lws-station\", NVS_READWRITE, &nvh));\n\tif (nvs_get_blob(nvh, filename, NULL, &s) != ESP_OK) {\n\t\tn = 1;\n\t\tgoto bail;\n\t}\n\t*buf = lws_malloc(s + 1, \"alloc_file\");\n\tif (!*buf) {\n\t\tn = 2;\n\t\tgoto bail;\n\t}\n\tif (nvs_get_blob(nvh, filename, (char *)*buf, &s) != ESP_OK) {\n\t\tlws_free(*buf);\n\t\tn = 1;\n\t\tgoto bail;\n\t}\n\n\t*amount = s;\n\t(*buf)[s] = '\\0';\n\n\tlwsl_notice(\"%s: nvs: read %s, %d bytes\\n\", __func__, filename, (int)s);\n\nbail:\n\tnvs_close(nvh);\n\n\treturn n;\n}\n#else\nint alloc_file(struct lws_context *context, const char *filename, uint8_t **buf,\n\t\tlws_filepos_t *amount)\n{\n\tFILE *f;\n\tsize_t s;\n\tint n = 0;\n\n\tf = fopen(filename, \"rb\");\n\tif (f == NULL) {\n\t\tn = 1;\n\t\tgoto bail;\n\t}\n\n\tif (fseek(f, 0, SEEK_END) != 0) {\n\t\tn = 1;\n\t\tgoto bail;\n\t}\n\n\ts = ftell(f);\n\tif (s == (size_t)-1) {\n\t\tn = 1;\n\t\tgoto bail;\n\t}\n\n\tif (fseek(f, 0, SEEK_SET) != 0) {\n\t\tn = 1;\n\t\tgoto bail;\n\t}\n\n\t*buf = lws_malloc(s, \"alloc_file\");\n\tif (!*buf) {\n\t\tn = 2;\n\t\tgoto bail;\n\t}\n\n\tif (fread(*buf, s, 1, f) != 1) {\n\t\tlws_free(*buf);\n\t\tn = 1;\n\t\tgoto bail;\n\t}\n\n\t*amount = s;\n\nbail:\n\tif (f)\n\t\tfclose(f);\n\n\treturn n;\n\n}\n#endif\n\nint\nlws_tls_alloc_pem_to_der_file(struct lws_context *context, const char *filename,\n\t\t\tconst char *inbuf, lws_filepos_t inlen,\n\t\t      uint8_t **buf, lws_filepos_t *amount)\n{\n\tconst uint8_t *pem, *p, *end;\n\tuint8_t *q;\n\tlws_filepos_t len;\n\tint n;\n\n\tif (filename) {\n\t\tn = alloc_file(context, filename, (uint8_t **)&pem, &len);\n\t\tif (n)\n\t\t\treturn n;\n\t} else {\n\t\tpem = (const uint8_t *)inbuf;\n\t\tlen = inlen;\n\t}\n\n\t/* trim the first line */\n\n\tp = pem;\n\tend = p + len;\n\tif (strncmp((char *)p, \"-----\", 5))\n\t\tgoto bail;\n\tp += 5;\n\twhile (p < end && *p != '\\n' && *p != '-')\n\t\tp++;\n\n\tif (*p != '-')\n\t\tgoto bail;\n\n\twhile (p < end && *p != '\\n')\n\t\tp++;\n\n\tif (p >= end)\n\t\tgoto bail;\n\n\tp++;\n\n\t/* trim the last line */\n\n\tq = (uint8_t *)end - 2;\n\n\twhile (q > pem && *q != '\\n')\n\t\tq--;\n\n\tif (*q != '\\n')\n\t\tgoto bail;\n\n\t*q = '\\0';\n\n\t*amount = lws_b64_decode_string((char *)p, (char *)pem,\n\t\t\t\t\t(int)(long long)len);\n\t*buf = (uint8_t *)pem;\n\n\treturn 0;\n\nbail:\n\tlws_free((uint8_t *)pem);\n\n\treturn 4;\n}\n\nint\nlws_tls_check_cert_lifetime(struct lws_vhost *v)\n{\n\tunion lws_tls_cert_info_results ir;\n\ttime_t now = (time_t)lws_now_secs(), life = 0;\n\tstruct lws_acme_cert_aging_args caa;\n\tint n;\n\n\tif (v->tls.ssl_ctx && !v->tls.skipped_certs) {\n\n\t\tif (now < 1464083026) /* May 2016 */\n\t\t\t/* our clock is wrong and we can't judge the certs */\n\t\t\treturn -1;\n\n\t\tn = lws_tls_vhost_cert_info(v, LWS_TLS_CERT_INFO_VALIDITY_TO, &ir, 0);\n\t\tif (n)\n\t\t\treturn 1;\n\n\t\tlife = (ir.time - now) / (24 * 3600);\n\t\tlwsl_notice(\"   vhost %s: cert expiry: %dd\\n\", v->name, (int)life);\n\t} else\n\t\tlwsl_notice(\"   vhost %s: no cert\\n\", v->name);\n\n\tmemset(&caa, 0, sizeof(caa));\n\tcaa.vh = v;\n\tlws_broadcast(v->context, LWS_CALLBACK_VHOST_CERT_AGING, (void *)&caa,\n\t\t      (size_t)(ssize_t)life);\n\n\treturn 0;\n}\n\nint\nlws_tls_check_all_cert_lifetimes(struct lws_context *context)\n{\n\tstruct lws_vhost *v = context->vhost_list;\n\n\twhile (v) {\n\t\tif (lws_tls_check_cert_lifetime(v) < 0)\n\t\t\treturn -1;\n\t\tv = v->vhost_next;\n\t}\n\n\treturn 0;\n}\n#if !defined(LWS_WITH_ESP32) && !defined(LWS_PLAT_OPTEE)\nstatic int\nlws_tls_extant(const char *name)\n{\n\t/* it exists if we can open it... */\n\tint fd = open(name, O_RDONLY), n;\n\tchar buf[1];\n\n\tif (fd < 0)\n\t\treturn 1;\n\n\t/* and we can read at least one byte out of it */\n\tn = read(fd, buf, 1);\n\tclose(fd);\n\n\treturn n != 1;\n}\n#endif\n/*\n * Returns 0 if the filepath \"name\" exists and can be read from.\n *\n * In addition, if \"name\".upd exists, backup \"name\" to \"name.old.1\"\n * and rename \"name\".upd to \"name\" before reporting its existence.\n *\n * There are four situations and three results possible:\n *\n * 1) LWS_TLS_EXTANT_NO: There are no certs at all (we are waiting for them to\n *    be provisioned).  We also feel like this if we need privs we don't have\n *    any more to look in the directory.\n *\n * 2) There are provisioned certs written (xxx.upd) and we still have root\n *    privs... in this case we rename any existing cert to have a backup name\n *    and move the upd cert into place with the correct name.  This then becomes\n *    situation 4 for the caller.\n *\n * 3) LWS_TLS_EXTANT_ALTERNATIVE: There are provisioned certs written (xxx.upd)\n *    but we no longer have the privs needed to read or rename them.  In this\n *    case, indicate that the caller should use temp copies if any we do have\n *    rights to access.  This is normal after we have updated the cert.\n *\n *    But if we dropped privs, we can't detect the provisioned xxx.upd cert +\n *    key, because we can't see in the dir.  So we have to upgrade NO to\n *    ALTERNATIVE when we actually have the in-memory alternative.\n *\n * 4) LWS_TLS_EXTANT_YES: The certs are present with the correct name and we\n *    have the rights to read them.\n */\nenum lws_tls_extant\nlws_tls_use_any_upgrade_check_extant(const char *name)\n{\n#if !defined(LWS_PLAT_OPTEE)\n\n\tint n;\n\n#if !defined(LWS_WITH_ESP32)\n\tchar buf[256];\n\n\tlws_snprintf(buf, sizeof(buf) - 1, \"%s.upd\", name);\n\tif (!lws_tls_extant(buf)) {\n\t\t/* ah there is an updated file... how about the desired file? */\n\t\tif (!lws_tls_extant(name)) {\n\t\t\t/* rename the desired file */\n\t\t\tfor (n = 0; n < 50; n++) {\n\t\t\t\tlws_snprintf(buf, sizeof(buf) - 1,\n\t\t\t\t\t     \"%s.old.%d\", name, n);\n\t\t\t\tif (!rename(name, buf))\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (n == 50) {\n\t\t\t\tlwsl_notice(\"unable to rename %s\\n\", name);\n\n\t\t\t\treturn LWS_TLS_EXTANT_ALTERNATIVE;\n\t\t\t}\n\t\t\tlws_snprintf(buf, sizeof(buf) - 1, \"%s.upd\", name);\n\t\t}\n\t\t/* desired file is out of the way, rename the updated file */\n\t\tif (rename(buf, name)) {\n\t\t\tlwsl_notice(\"unable to rename %s to %s\\n\", buf, name);\n\n\t\t\treturn LWS_TLS_EXTANT_ALTERNATIVE;\n\t\t}\n\t}\n\n\tif (lws_tls_extant(name))\n\t\treturn LWS_TLS_EXTANT_NO;\n#else\n\tnvs_handle nvh;\n\tsize_t s = 8192;\n\n\tif (nvs_open(\"lws-station\", NVS_READWRITE, &nvh)) {\n\t\tlwsl_notice(\"%s: can't open nvs\\n\", __func__);\n\t\treturn LWS_TLS_EXTANT_NO;\n\t}\n\n\tn = nvs_get_blob(nvh, name, NULL, &s);\n\tnvs_close(nvh);\n\n\tif (n)\n\t\treturn LWS_TLS_EXTANT_NO;\n#endif\n#endif\n\treturn LWS_TLS_EXTANT_YES;\n}\n\n/*\n * LWS_TLS_EXTANT_NO         : skip adding the cert\n * LWS_TLS_EXTANT_YES        : use the cert and private key paths normally\n * LWS_TLS_EXTANT_ALTERNATIVE: normal paths not usable, try alternate if poss\n */\nenum lws_tls_extant\nlws_tls_generic_cert_checks(struct lws_vhost *vhost, const char *cert,\n\t\t\t    const char *private_key)\n{\n\tint n, m;\n\n\t/*\n\t * The user code can choose to either pass the cert and\n\t * key filepaths using the info members like this, or it can\n\t * leave them NULL; force the vhost SSL_CTX init using the info\n\t * options flag LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX; and\n\t * set up the cert himself using the user callback\n\t * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS, which\n\t * happened just above and has the vhost SSL_CTX * in the user\n\t * parameter.\n\t */\n\n\tif (!cert || !private_key)\n\t\treturn LWS_TLS_EXTANT_NO;\n\n\tn = lws_tls_use_any_upgrade_check_extant(cert);\n\tif (n == LWS_TLS_EXTANT_ALTERNATIVE)\n\t\treturn LWS_TLS_EXTANT_ALTERNATIVE;\n\tm = lws_tls_use_any_upgrade_check_extant(private_key);\n\tif (m == LWS_TLS_EXTANT_ALTERNATIVE)\n\t\treturn LWS_TLS_EXTANT_ALTERNATIVE;\n\n\tif ((n == LWS_TLS_EXTANT_NO || m == LWS_TLS_EXTANT_NO) &&\n\t    (vhost->options & LWS_SERVER_OPTION_IGNORE_MISSING_CERT)) {\n\t\tlwsl_notice(\"Ignoring missing %s or %s\\n\", cert, private_key);\n\t\tvhost->tls.skipped_certs = 1;\n\n\t\treturn LWS_TLS_EXTANT_NO;\n\t}\n\n\t/*\n\t * the cert + key exist\n\t */\n\n\treturn LWS_TLS_EXTANT_YES;\n}\n\n#if !defined(LWS_NO_SERVER)\n/*\n * update the cert for every vhost using the given path\n */\n\nLWS_VISIBLE int\nlws_tls_cert_updated(struct lws_context *context, const char *certpath,\n\t\t     const char *keypath,\n\t\t     const char *mem_cert, size_t len_mem_cert,\n\t\t     const char *mem_privkey, size_t len_mem_privkey)\n{\n\tstruct lws wsi;\n\n\twsi.context = context;\n\n\tlws_start_foreach_ll(struct lws_vhost *, v, context->vhost_list) {\n\t\twsi.vhost = v;\n\t\tif (v->tls.alloc_cert_path && v->tls.key_path &&\n\t\t    !strcmp(v->tls.alloc_cert_path, certpath) &&\n\t\t    !strcmp(v->tls.key_path, keypath)) {\n\t\t\tlws_tls_server_certs_load(v, &wsi, certpath, keypath,\n\t\t\t\t\t\t  mem_cert, len_mem_cert,\n\t\t\t\t\t\t  mem_privkey, len_mem_privkey);\n\n\t\t\tif (v->tls.skipped_certs)\n\t\t\t\tlwsl_notice(\"%s: vhost %s: cert unset\\n\",\n\t\t\t\t\t    __func__, v->name);\n\t\t}\n\t} lws_end_foreach_ll(v, vhost_next);\n\n\treturn 0;\n}\n#endif\n\nint\nlws_gate_accepts(struct lws_context *context, int on)\n{\n\tstruct lws_vhost *v = context->vhost_list;\n\n\tlwsl_notice(\"%s: on = %d\\n\", __func__, on);\n\n#if defined(LWS_WITH_STATS)\n\tcontext->updated = 1;\n#endif\n\n\twhile (v) {\n\t\tif (v->tls.use_ssl && v->lserv_wsi &&\n\t\t    lws_change_pollfd(v->lserv_wsi, (LWS_POLLIN) * !on,\n\t\t\t\t      (LWS_POLLIN) * on))\n\t\t\tlwsl_notice(\"Unable to set accept POLLIN %d\\n\", on);\n\n\t\tv = v->vhost_next;\n\t}\n\n\treturn 0;\n}\n\n/* comma-separated alpn list, like \"h2,http/1.1\" to openssl alpn format */\n\nint\nlws_alpn_comma_to_openssl(const char *comma, uint8_t *os, int len)\n{\n\tuint8_t *oos = os, *plen = NULL;\n\n\twhile (*comma && len > 1) {\n\t\tif (!plen && *comma == ' ') {\n\t\t\tcomma++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!plen) {\n\t\t\tplen = os++;\n\t\t\tlen--;\n\t\t}\n\n\t\tif (*comma == ',') {\n\t\t\t*plen = lws_ptr_diff(os, plen + 1);\n\t\t\tplen = NULL;\n\t\t\tcomma++;\n\t\t} else {\n\t\t\t*os++ = *comma++;\n\t\t\tlen--;\n\t\t}\n\t}\n\n\tif (plen)\n\t\t*plen = lws_ptr_diff(os, plen + 1);\n\n\treturn lws_ptr_diff(os, oos);\n}\n\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/uwp_fixes.diff",
    "content": "diff --git a/thirdparty/libwebsockets/plat/lws-plat-win.c b/thirdparty/libwebsockets/plat/lws-plat-win.c\nindex bd513b494..1850b6425 100644\n--- a/thirdparty/libwebsockets/plat/lws-plat-win.c\n+++ b/thirdparty/libwebsockets/plat/lws-plat-win.c\n@@ -641,9 +641,20 @@ _lws_plat_file_open(const struct lws_plat_file_ops *fops, const char *filename,\n \tHANDLE ret;\n \tWCHAR buf[MAX_PATH];\n \tlws_fop_fd_t fop_fd;\n-\tLARGE_INTEGER llFileSize = {0};\n+\tFILE_STANDARD_INFO fInfo = {0};\n \n \tMultiByteToWideChar(CP_UTF8, 0, filename, -1, buf, LWS_ARRAY_SIZE(buf));\n+\n+#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0602 // Windows 8 (minimum when UWP_ENABLED, but can be used in Windows builds)\n+\tCREATEFILE2_EXTENDED_PARAMETERS extParams = {0};\n+\textParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;\n+\n+\tif (((*flags) & 7) == _O_RDONLY) {\n+\t\tret = CreateFile2(buf, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &extParams);\n+\t} else {\n+\t\tret = CreateFile2(buf, GENERIC_WRITE, 0, CREATE_ALWAYS, &extParams);\n+\t}\n+#else\n \tif (((*flags) & 7) == _O_RDONLY) {\n \t\tret = CreateFileW(buf, GENERIC_READ, FILE_SHARE_READ,\n \t\t\t  NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n@@ -651,6 +662,7 @@ _lws_plat_file_open(const struct lws_plat_file_ops *fops, const char *filename,\n \t\tret = CreateFileW(buf, GENERIC_WRITE, 0, NULL,\n \t\t\t  CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n \t}\n+#endif\n \n \tif (ret == LWS_INVALID_FILE)\n \t\tgoto bail;\n@@ -663,9 +675,9 @@ _lws_plat_file_open(const struct lws_plat_file_ops *fops, const char *filename,\n \tfop_fd->fd = ret;\n \tfop_fd->filesystem_priv = NULL; /* we don't use it */\n \tfop_fd->flags = *flags;\n-\tfop_fd->len = GetFileSize(ret, NULL);\n-\tif(GetFileSizeEx(ret, &llFileSize))\n-\t\tfop_fd->len = llFileSize.QuadPart;\n+\tfop_fd->len = 0;\n+\tif(GetFileInformationByHandleEx(ret, FileStandardInfo, &fInfo, sizeof(fInfo)))\n+\t\tfop_fd->len = fInfo.EndOfFile.QuadPart;\n \n \tfop_fd->pos = 0;\n \n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/win32helpers/getopt.c",
    "content": "/*\t$NetBSD: getopt.c,v 1.16 1999/12/02 13:15:56 kleink Exp $\t*/\n\n/*\n * Copyright (c) 1987, 1993, 1994\n *\tThe Regents of the University of California.  All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n * 3. All advertising materials mentioning features or use of this software\n *    must display the following acknowledgement:\n *\tThis product includes software developed by the University of\n *\tCalifornia, Berkeley and its contributors.\n * 4. Neither the name of the University nor the names of its contributors\n *    may be used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n */\n\n#if 0\nstatic char sccsid[] = \"@(#)getopt.c\t8.3 (Berkeley) 4/27/95\";\n#endif\n\n#include <assert.h>\n#include <errno.h>\n#include <stdio.h>\n#include <string.h>\n\n#define __P(x) x\n#define _DIAGASSERT(x) assert(x)\n\n#ifdef __weak_alias\n__weak_alias(getopt,_getopt);\n#endif\n\n\nint\topterr = 1,\t\t/* if error message should be printed */\n\toptind = 1,\t\t/* index into parent argv vector */\n\toptopt,\t\t\t/* character checked for validity */\n\toptreset;\t\t/* reset getopt */\nchar\t*optarg;\t\t/* argument associated with option */\n\nstatic char * _progname __P((char *));\nint getopt_internal __P((int, char * const *, const char *));\n\nstatic char *\n_progname(nargv0)\n\tchar * nargv0;\n{\n\tchar * tmp;\n\n\t_DIAGASSERT(nargv0 != NULL);\n\n\ttmp = strrchr(nargv0, '/');\n\tif (tmp)\n\t\ttmp++;\n\telse\n\t\ttmp = nargv0;\n\treturn(tmp);\n}\n\n#define\tBADCH\t(int)'?'\n#define\tBADARG\t(int)':'\n#define\tEMSG\t\"\"\n\n/*\n * getopt --\n *\tParse argc/argv argument vector.\n */\nint\ngetopt(nargc, nargv, ostr)\n\tint nargc;\n\tchar * const nargv[];\n\tconst char *ostr;\n{\n\tstatic char *__progname = 0;\n\tstatic char *place = EMSG;\t\t/* option letter processing */\n\tchar *oli;\t\t\t\t/* option letter list index */\n        __progname = __progname?__progname:_progname(*nargv);\n\n\t_DIAGASSERT(nargv != NULL);\n\t_DIAGASSERT(ostr != NULL);\n\n\tif (optreset || !*place) {\t\t/* update scanning pointer */\n\t\toptreset = 0;\n\t\tif (optind >= nargc || *(place = nargv[optind]) != '-') {\n\t\t\tplace = EMSG;\n\t\t\treturn (-1);\n\t\t}\n\t\tif (place[1] && *++place == '-'\t/* found \"--\" */\n\t\t    && place[1] == '\\0') {\n\t\t\t++optind;\n\t\t\tplace = EMSG;\n\t\t\treturn (-1);\n\t\t}\n\t}\t\t\t\t\t/* option letter okay? */\n\tif ((optopt = (int)*place++) == (int)':' ||\n\t    !(oli = strchr(ostr, optopt))) {\n\t\t/*\n\t\t * if the user didn't specify '-' as an option,\n\t\t * assume it means -1.\n\t\t */\n\t\tif (optopt == (int)'-')\n\t\t\treturn (-1);\n\t\tif (!*place)\n\t\t\t++optind;\n\t\tif (opterr && *ostr != ':')\n\t\t\t(void)fprintf(stderr,\n\t\t\t    \"%s: illegal option -- %c\\n\", __progname, optopt);\n\t\treturn (BADCH);\n\t}\n\tif (*++oli != ':') {\t\t\t/* don't need argument */\n\t\toptarg = NULL;\n\t\tif (!*place)\n\t\t\t++optind;\n\t}\n\telse {\t\t\t\t\t/* need an argument */\n\t\tif (*place)\t\t\t/* no white space */\n\t\t\toptarg = place;\n\t\telse if (nargc <= ++optind) {\t/* no arg */\n\t\t\tplace = EMSG;\n\t\t\tif (*ostr == ':')\n\t\t\t\treturn (BADARG);\n\t\t\tif (opterr)\n\t\t\t\t(void)fprintf(stderr,\n\t\t\t\t    \"%s: option requires an argument -- %c\\n\",\n\t\t\t\t    __progname, optopt);\n\t\t\treturn (BADCH);\n\t\t}\n\t \telse\t\t\t\t/* white space */\n\t\t\toptarg = nargv[optind];\n\t\tplace = EMSG;\n\t\t++optind;\n\t}\n\treturn (optopt);\t\t\t/* dump back option letter */\n}\n\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/win32helpers/getopt.h",
    "content": "#ifndef __GETOPT_H__\n#define __GETOPT_H__\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nextern int opterr;\t\t/* if error message should be printed */\nextern int optind;\t\t/* index into parent argv vector */\nextern int optopt;\t\t/* character checked for validity */\nextern int optreset;\t\t/* reset getopt */\nextern char *optarg;\t\t/* argument associated with option */\n\nstruct option\n{\n  const char *name;\n  int has_arg;\n  int *flag;\n  int val;\n};\n\n#define no_argument       0\n#define required_argument 1\n#define optional_argument 2\n\nint getopt(int, char**, char*);\nint getopt_long(int, char**, char*, struct option*, int*);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* __GETOPT_H__ */\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/win32helpers/getopt_long.c",
    "content": "\n/*\n * Copyright (c) 1987, 1993, 1994, 1996\n *\tThe Regents of the University of California.  All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n * 3. All advertising materials mentioning features or use of this software\n *    must display the following acknowledgement:\n *\tThis product includes software developed by the University of\n *\tCalifornia, Berkeley and its contributors.\n * 4. Neither the name of the University nor the names of its contributors\n *    may be used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n */\n#include <assert.h>\n#include <errno.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"getopt.h\"\n\n#define lws_ptr_diff(head, tail) \\\n\t\t\t((int)((char *)(head) - (char *)(tail)))\n\nextern int\t  opterr;\t/* if error message should be printed */\nextern int\t  optind;\t/* index into parent argv vector */\nextern int\t  optopt;\t/* character checked for validity */\nextern int\t  optreset;\t/* reset getopt */\nextern char *optarg;\t/* argument associated with option */\n\n#define __P(x) x\n#define _DIAGASSERT(x) assert(x)\n\nstatic char * __progname __P((char *));\nint getopt_internal __P((int, char * const *, const char *));\n\nstatic char *\n__progname(nargv0)\n\tchar * nargv0;\n{\n\tchar * tmp;\n\n\t_DIAGASSERT(nargv0 != NULL);\n\n\ttmp = strrchr(nargv0, '/');\n\tif (tmp)\n\t\ttmp++;\n\telse\n\t\ttmp = nargv0;\n\treturn(tmp);\n}\n\n#define\tBADCH\t(int)'?'\n#define\tBADARG\t(int)':'\n#define\tEMSG\t\"\"\n\n/*\n * getopt --\n *\tParse argc/argv argument vector.\n */\nint\ngetopt_internal(nargc, nargv, ostr)\n\tint nargc;\n\tchar * const *nargv;\n\tconst char *ostr;\n{\n\tstatic char *place = EMSG;\t\t/* option letter processing */\n\tchar *oli;\t\t\t\t/* option letter list index */\n\n\t_DIAGASSERT(nargv != NULL);\n\t_DIAGASSERT(ostr != NULL);\n\n\tif (optreset || !*place) {\t\t/* update scanning pointer */\n\t\toptreset = 0;\n\t\tif (optind >= nargc || *(place = nargv[optind]) != '-') {\n\t\t\tplace = EMSG;\n\t\t\treturn (-1);\n\t\t}\n\t\tif (place[1] && *++place == '-') {\t/* found \"--\" */\n\t\t\t/* ++optind; */\n\t\t\tplace = EMSG;\n\t\t\treturn (-2);\n\t\t}\n\t}\t\t\t\t\t/* option letter okay? */\n\tif ((optopt = (int)*place++) == (int)':' ||\n\t    !(oli = strchr(ostr, optopt))) {\n\t\t/*\n\t\t * if the user didn't specify '-' as an option,\n\t\t * assume it means -1.\n\t\t */\n\t\tif (optopt == (int)'-')\n\t\t\treturn (-1);\n\t\tif (!*place)\n\t\t\t++optind;\n\t\tif (opterr && *ostr != ':')\n\t\t\t(void)fprintf(stderr,\n\t\t\t    \"%s: illegal option -- %c\\n\", __progname(nargv[0]), optopt);\n\t\treturn (BADCH);\n\t}\n\tif (*++oli != ':') {\t\t\t/* don't need argument */\n\t\toptarg = NULL;\n\t\tif (!*place)\n\t\t\t++optind;\n\t} else {\t\t\t\t/* need an argument */\n\t\tif (*place)\t\t\t/* no white space */\n\t\t\toptarg = place;\n\t\telse if (nargc <= ++optind) {\t/* no arg */\n\t\t\tplace = EMSG;\n\t\t\tif ((opterr) && (*ostr != ':'))\n\t\t\t\t(void)fprintf(stderr,\n\t\t\t\t    \"%s: option requires an argument -- %c\\n\",\n\t\t\t\t    __progname(nargv[0]), optopt);\n\t\t\treturn (BADARG);\n\t\t} else\t\t\t\t/* white space */\n\t\t\toptarg = nargv[optind];\n\t\tplace = EMSG;\n\t\t++optind;\n\t}\n\treturn (optopt);\t\t\t/* dump back option letter */\n}\n\n#if 0\n/*\n * getopt --\n *\tParse argc/argv argument vector.\n */\nint\ngetopt2(nargc, nargv, ostr)\n\tint nargc;\n\tchar * const *nargv;\n\tconst char *ostr;\n{\n\tint retval;\n\n\tif ((retval = getopt_internal(nargc, nargv, ostr)) == -2) {\n\t\tretval = -1;\n\t\t++optind; \n\t}\n\treturn(retval);\n}\n#endif\n\n/*\n * getopt_long --\n *\tParse argc/argv argument vector.\n */\nint\ngetopt_long(nargc, nargv, options, long_options, index)\n\tint nargc;\n\tchar ** nargv;\n\tchar * options;\n\tstruct option * long_options;\n\tint * index;\n{\n\tint retval;\n\n\t_DIAGASSERT(nargv != NULL);\n\t_DIAGASSERT(options != NULL);\n\t_DIAGASSERT(long_options != NULL);\n\t/* index may be NULL */\n\n\tif ((retval = getopt_internal(nargc, nargv, options)) == -2) {\n\t\tchar *current_argv = nargv[optind++] + 2, *has_equal;\n\t\tint i, current_argv_len, match = -1;\n\n\t\tif (*current_argv == '\\0') {\n\t\t\treturn(-1);\n\t\t}\n\t\tif ((has_equal = strchr(current_argv, '=')) != NULL) {\n\t\t\tcurrent_argv_len = lws_ptr_diff(has_equal, current_argv);\n\t\t\thas_equal++;\n\t\t} else\n\t\t\tcurrent_argv_len = (int)strlen(current_argv);\n\n\t\tfor (i = 0; long_options[i].name; i++) { \n\t\t\tif (strncmp(current_argv, long_options[i].name, current_argv_len))\n\t\t\t\tcontinue;\n\n\t\t\tif (strlen(long_options[i].name) == (unsigned)current_argv_len) { \n\t\t\t\tmatch = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (match == -1)\n\t\t\t\tmatch = i;\n\t\t}\n\t\tif (match != -1) {\n\t\t\tif (long_options[match].has_arg == required_argument ||\n\t\t\t    long_options[match].has_arg == optional_argument) {\n\t\t\t\tif (has_equal)\n\t\t\t\t\toptarg = has_equal;\n\t\t\t\telse\n\t\t\t\t\toptarg = nargv[optind++];\n\t\t\t}\n\t\t\tif ((long_options[match].has_arg == required_argument)\n\t\t\t    && (optarg == NULL)) {\n\t\t\t\t/*\n\t\t\t\t * Missing argument, leading :\n\t\t\t\t * indicates no error should be generated\n\t\t\t\t */\n\t\t\t\tif ((opterr) && (*options != ':'))\n\t\t\t\t\t(void)fprintf(stderr,\n\t\t\t\t      \"%s: option requires an argument -- %s\\n\",\n\t\t\t\t      __progname(nargv[0]), current_argv);\n\t\t\t\treturn (BADARG);\n\t\t\t}\n\t\t} else { /* No matching argument */\n\t\t\tif ((opterr) && (*options != ':'))\n\t\t\t\t(void)fprintf(stderr,\n\t\t\t\t    \"%s: illegal option -- %s\\n\", __progname(nargv[0]), current_argv);\n\t\t\treturn (BADCH);\n\t\t}\n\t\tif (long_options[match].flag) {\n\t\t\t*long_options[match].flag = long_options[match].val;\n\t\t\tretval = 0;\n\t\t} else \n\t\t\tretval = long_options[match].val;\n\t\tif (index)\n\t\t\t*index = match;\n\t}\n\treturn(retval);\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/win32helpers/gettimeofday.c",
    "content": "#include <time.h>\n#include <windows.h> //I've omitted context line\n\n#include \"gettimeofday.h\"\n\nint gettimeofday(struct timeval *tv, struct timezone *tz)\n{\n\tFILETIME ft;\n\tunsigned __int64 tmpres = 0;\n\tstatic int tzflag;\n\n\tif (NULL != tv) {\n\t\tGetSystemTimeAsFileTime(&ft);\n\n\t\ttmpres |= ft.dwHighDateTime;\n\t\ttmpres <<= 32;\n\t\ttmpres |= ft.dwLowDateTime;\n\n\t\t/*converting file time to unix epoch*/\n\t\ttmpres /= 10;  /*convert into microseconds*/\n\t\ttmpres -= DELTA_EPOCH_IN_MICROSECS;\n\t\ttv->tv_sec = (long)(tmpres / 1000000UL);\n\t\ttv->tv_usec = (long)(tmpres % 1000000UL);\n\t}\n \n\tif (NULL != tz) {\n\t\tif (!tzflag) {\n\t\t\t_tzset();\n\t\t\ttzflag++;\n\t\t}\n\t\ttz->tz_minuteswest = _timezone / 60;\n\t\ttz->tz_dsttime = _daylight;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "jsb_build/websockets/libwebsockets/win32helpers/gettimeofday.h",
    "content": "#ifndef _GET_TIME_OF_DAY_H\n#define _GET_TIME_OF_DAY_H\n\n#include <time.h>\n\n#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)\n  #define DELTA_EPOCH_IN_MICROSECS  11644473600000000Ui64\n#else\n  #define DELTA_EPOCH_IN_MICROSECS  11644473600000000ULL\n#endif\n\n#ifdef LWS_MINGW_SUPPORT\n  #include <winsock2.h>\n#endif\n\n#ifndef _TIMEZONE_DEFINED \nstruct timezone \n{\n  int  tz_minuteswest; /* minutes W of Greenwich */\n  int  tz_dsttime;     /* type of dst correction */\n};\n\n#endif\n\nint gettimeofday(struct timeval *tv, struct timezone *tz);\n\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/make_lws_android.bat",
    "content": "@echo off\r\n\r\nif not defined ANDROID_NDK (\r\n    set ANDROID_NDK=E:/android-ndk-r15c\r\n)\r\nset BASE_PATH=%~dp0\r\nset BUILD_PATH=%~dp0..\\out\\libwebsockets\r\necho %BUILD_PATH%\r\n\r\nmkdir %BUILD_PATH% 2>nul\r\ncd %BUILD_PATH%\r\n\r\nrd /s /q %BUILD_PATH%\\Android_v7a_release 2>nul\r\necho building v7a release\r\nmkdir %BUILD_PATH%\\Android_v7a_release\r\ncd %BUILD_PATH%\\Android_v7a_release\r\ncmake -DCMAKE_BUILD_TYPE=RELEASE -DANDROID_ABI=armeabi-v7a -DCMAKE_TOOLCHAIN_FILE=%ANDROID_NDK%/build/cmake/android.toolchain.cmake -DANDROID_TOOLCHAIN_NAME=arm-linux-androideabi-clang -DANDROID_NATIVE_API_LEVEL=android-9 -G \"NMake Makefiles\" %BASE_PATH%\r\ncd %BUILD_PATH%\r\ncmake --build Android_v7a_release --config Release\r\nmkdir ..\\..\\prebuilt\\Plugins\\Android\\libs\\armeabi-v7a\\\r\nxcopy /Y .\\Android_v7a_release\\libwebsockets.so ..\\..\\prebuilt\\Plugins\\Android\\libs\\armeabi-v7a\\\r\n\r\nrd /s /q %BUILD_PATH%\\Android_v8a_release 2>nul\r\necho building v8a release\r\nmkdir %BUILD_PATH%\\Android_v8a_release\r\ncd %BUILD_PATH%\\Android_v8a_release\r\ncmake -DCMAKE_BUILD_TYPE=RELEASE -DANDROID_ABI=arm64-v8a -DCMAKE_TOOLCHAIN_FILE=%ANDROID_NDK%/build/cmake/android.toolchain.cmake -DANDROID_TOOLCHAIN_NAME=arm-linux-androideabi-clang -DANDROID_NATIVE_API_LEVEL=android-9 -G \"NMake Makefiles\" %BASE_PATH%\r\ncd %BUILD_PATH%\r\ncmake --build Android_v8a_release --config Release\r\nmkdir ..\\..\\prebuilt\\Plugins\\Android\\libs\\arm64-v8a\\\r\nxcopy /Y .\\Android_v8a_release\\libwebsockets.so ..\\..\\prebuilt\\Plugins\\Android\\libs\\arm64-v8a\\\r\n\r\nrd /s /q %BUILD_PATH%\\Android_x86_release 2>nul\r\necho building x86 release\r\nmkdir %BUILD_PATH%\\Android_x86_release\r\ncd %BUILD_PATH%\\Android_x86_release\r\ncmake -DCMAKE_BUILD_TYPE=RELEASE -DANDROID_ABI=x86 -DCMAKE_TOOLCHAIN_FILE=%ANDROID_NDK%/build/cmake/android.toolchain.cmake -DANDROID_TOOLCHAIN_NAME=x86-clang -DANDROID_NATIVE_API_LEVEL=android-9 -G \"NMake Makefiles\" %BASE_PATH%\r\ncd %BUILD_PATH%\r\ncmake --build Android_x86_release --config Release\r\nmkdir ..\\..\\prebuilt\\Plugins\\Android\\libs\\x86\\\r\nxcopy /Y .\\Android_x86_release\\libwebsockets.so ..\\..\\prebuilt\\Plugins\\Android\\libs\\x86\\\r\n\r\ncd %BASE_PATH%\r\n"
  },
  {
    "path": "jsb_build/websockets/make_lws_macos.sh",
    "content": "#!/usr/bin/env sh\n\nrm -rf ../out/websockets/macos_release\nmkdir -p ../out/websockets/macos_release\ncd ../out/websockets/macos_release\ncmake -GXcode ../../../websockets\ncd ..\necho building...\ncmake --build macos_release --config Release\nmkdir -p ../../prebuilt/Plugins/libwebsockets.bundle/Contents/MacOS/\npwd\ncp ./macos_release/Release/websockets.bundle/Contents/MacOS/websockets ../../prebuilt/Plugins/libwebsockets.bundle/Contents/MacOS/libwebsockets\ncd ..\n"
  },
  {
    "path": "jsb_build/websockets/make_lws_windows.bat",
    "content": "@echo off\r\n\r\nSET BASE_PATH=%~dp0\r\nSET BUILD_PATH=%~dp0..\\out\\libwebsockets\r\necho %BUILD_PATH%\r\nREM cmake -G \"Visual Studio 15 2017 Win64\" ..\\..\\..\r\n\r\nmkdir %BUILD_PATH% 2>nul\r\ncd %BUILD_PATH%\r\n\r\nREM rd /s /q x64_Debug 2>nul\r\nREM echo building x64_Debug\r\nREM mkdir x64_Debug\r\nREM cd x64_Debug\r\nREM cmake -G \"Visual Studio 16 2019\" -A x64 ..\\..\\..\\websockets\r\nREM cd %BUILD_PATH%\r\nREM cmake --build x64_Debug --config Debug\r\nREM mkdir ..\\..\\prebuilt\\Plugins\\x64\\\r\nREM xcopy /Y .\\x64_Debug\\Debug\\websockets.dll ..\\..\\prebuilt\\Plugins\\x64\\\r\n\r\nrd /s /q x64_release 2>nul\r\necho building x64_release\r\nmkdir x64_release\r\ncd x64_release\r\ncmake -G \"Visual Studio 16 2019\" -A x64 ..\\..\\..\\websockets\r\ncd %BUILD_PATH%\r\ncmake --build x64_release --config Release\r\nmkdir ..\\..\\prebuilt\\Plugins\\x64\\\r\nxcopy /Y .\\x64_release\\Release\\websockets.dll ..\\..\\prebuilt\\Plugins\\x64\\\r\n\r\nrd /s /q x86_release 2>nul\r\necho building x86_release\r\nmkdir x86_release\r\ncd x86_release\r\ncmake -G \"Visual Studio 16 2019\" -A Win32 ..\\..\\..\\websockets\r\ncd %BUILD_PATH%\r\ncmake --build x86_release --config Release\r\nmkdir ..\\..\\prebuilt\\Plugins\\x86\\\r\nxcopy /Y .\\x86_release\\Release\\websockets.dll ..\\..\\prebuilt\\Plugins\\x86\\\r\n\r\ncd %BASE_PATH%\r\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/1453.diff",
    "content": "diff --git a/library/entropy_poll.c b/library/entropy_poll.c\nindex 67900c46c8..cefe882d2a 100644\n--- a/library/entropy_poll.c\n+++ b/library/entropy_poll.c\n@@ -54,28 +54,43 @@\n #define _WIN32_WINNT 0x0400\n #endif\n #include <windows.h>\n-#include <wincrypt.h>\n+#include <bcrypt.h>\n+#if defined(_MSC_VER) && _MSC_VER <= 1600\n+/* Visual Studio 2010 and earlier issue a warning when both <stdint.h> and\n+ * <intsafe.h> are included, as they redefine a number of <TYPE>_MAX constants.\n+ * These constants are guaranteed to be the same, though, so we suppress the\n+ * warning when including intsafe.h.\n+ */\n+#pragma warning( push )\n+#pragma warning( disable : 4005 )\n+#endif\n+#include <intsafe.h>\n+#if defined(_MSC_VER) && _MSC_VER <= 1600\n+#pragma warning( pop )\n+#endif\n \n int mbedtls_platform_entropy_poll( void *data, unsigned char *output, size_t len,\n                            size_t *olen )\n {\n-    HCRYPTPROV provider;\n+    ULONG len_as_ulong = 0;\n     ((void) data);\n     *olen = 0;\n \n-    if( CryptAcquireContext( &provider, NULL, NULL,\n-                              PROV_RSA_FULL, CRYPT_VERIFYCONTEXT ) == FALSE )\n+    /*\n+     * BCryptGenRandom takes ULONG for size, which is smaller than size_t on\n+     * 64-bit Windows platforms. Ensure len's value can be safely converted into\n+     * a ULONG.\n+     */\n+    if ( FAILED( SizeTToULong( len, &len_as_ulong ) ) )\n     {\n         return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n     }\n \n-    if( CryptGenRandom( provider, (DWORD) len, output ) == FALSE )\n+    if ( !BCRYPT_SUCCESS( BCryptGenRandom( NULL, output, len_as_ulong, BCRYPT_USE_SYSTEM_PREFERRED_RNG ) ) )\n     {\n-        CryptReleaseContext( provider, 0 );\n         return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n     }\n \n-    CryptReleaseContext( provider, 0 );\n     *olen = len;\n \n     return( 0 );\ndiff --git a/library/x509_crt.c b/library/x509_crt.c\nindex 290c1eb3d1..3cf1743821 100644\n--- a/library/x509_crt.c\n+++ b/library/x509_crt.c\n@@ -65,6 +65,19 @@\n \n #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)\n #include <windows.h>\n+#if defined(_MSC_VER) && _MSC_VER <= 1600\n+/* Visual Studio 2010 and earlier issue a warning when both <stdint.h> and\n+ * <intsafe.h> are included, as they redefine a number of <TYPE>_MAX constants.\n+ * These constants are guaranteed to be the same, though, so we suppress the\n+ * warning when including intsafe.h.\n+ */\n+#pragma warning( push )\n+#pragma warning( disable : 4005 )\n+#endif\n+#include <intsafe.h>\n+#if defined(_MSC_VER) && _MSC_VER <= 1600\n+#pragma warning( pop )\n+#endif\n #else\n #include <time.h>\n #endif\n@@ -1126,6 +1139,7 @@ int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path )\n     char filename[MAX_PATH];\n     char *p;\n     size_t len = strlen( path );\n+    int length_as_int = 0;\n \n     WIN32_FIND_DATAW file_data;\n     HANDLE hFind;\n@@ -1140,7 +1154,18 @@ int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path )\n     p = filename + len;\n     filename[len++] = '*';\n \n-    w_ret = MultiByteToWideChar( CP_ACP, 0, filename, (int)len, szDir,\n+    if ( FAILED ( SizeTToInt( len, &length_as_int ) ) )\n+        return( MBEDTLS_ERR_X509_FILE_IO_ERROR );\n+\n+    /*\n+     * Note this function uses the code page CP_ACP, and assumes the incoming\n+     * string is encoded in ANSI, before translating it into Unicode. If the\n+     * incoming string were changed to be UTF-8, then the length check needs to\n+     * change to check the number of characters, not the number of bytes, in the\n+     * incoming string are less than MAX_PATH to avoid a buffer overrun with\n+     * MultiByteToWideChar().\n+     */\n+    w_ret = MultiByteToWideChar( CP_ACP, 0, filename, length_as_int, szDir,\n                                  MAX_PATH - 3 );\n     if( w_ret == 0 )\n         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n@@ -1157,8 +1182,11 @@ int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path )\n         if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )\n             continue;\n \n+        if ( FAILED( SizeTToInt( wcslen( file_data.cFileName ), &length_as_int ) ) )\n+            return( MBEDTLS_ERR_X509_FILE_IO_ERROR );\n+\n         w_ret = WideCharToMultiByte( CP_ACP, 0, file_data.cFileName,\n-                                     lstrlenW( file_data.cFileName ),\n+                                     length_as_int,\n                                      p, (int) len - 1,\n                                      NULL, NULL );\n         if( w_ret == 0 )\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/LICENSE",
    "content": "Unless specifically indicated otherwise in a file, files are licensed\nunder the Apache 2.0 license, as can be found in: apache-2.0.txt\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/apache-2.0.txt",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/aes.h",
    "content": "/**\n * \\file aes.h\n *\n * \\brief   This file contains AES definitions and functions.\n *\n *          The Advanced Encryption Standard (AES) specifies a FIPS-approved\n *          cryptographic algorithm that can be used to protect electronic\n *          data.\n *\n *          The AES algorithm is a symmetric block cipher that can\n *          encrypt and decrypt information. For more information, see\n *          <em>FIPS Publication 197: Advanced Encryption Standard</em> and\n *          <em>ISO/IEC 18033-2:2006: Information technology -- Security\n *          techniques -- Encryption algorithms -- Part 2: Asymmetric\n *          ciphers</em>.\n *\n *          The AES-XTS block mode is standardized by NIST SP 800-38E\n *          <https://nvlpubs.nist.gov/nistpubs/legacy/sp/nistspecialpublication800-38e.pdf>\n *          and described in detail by IEEE P1619\n *          <https://ieeexplore.ieee.org/servlet/opac?punumber=4375278>.\n */\n\n/*  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved.\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_AES_H\n#define MBEDTLS_AES_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n#include <stdint.h>\n\n/* padlock.c and aesni.c rely on these values! */\n#define MBEDTLS_AES_ENCRYPT     1 /**< AES encryption. */\n#define MBEDTLS_AES_DECRYPT     0 /**< AES decryption. */\n\n/* Error codes in range 0x0020-0x0022 */\n#define MBEDTLS_ERR_AES_INVALID_KEY_LENGTH                -0x0020  /**< Invalid key length. */\n#define MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH              -0x0022  /**< Invalid data input length. */\n\n/* Error codes in range 0x0021-0x0025 */\n#define MBEDTLS_ERR_AES_BAD_INPUT_DATA                    -0x0021  /**< Invalid input data. */\n#define MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE               -0x0023  /**< Feature not available. For example, an unsupported AES key size. */\n#define MBEDTLS_ERR_AES_HW_ACCEL_FAILED                   -0x0025  /**< AES hardware accelerator failed. */\n\n#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \\\n    !defined(inline) && !defined(__cplusplus)\n#define inline __inline\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_AES_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief The AES context-type definition.\n */\ntypedef struct\n{\n    int nr;                     /*!< The number of rounds. */\n    uint32_t *rk;               /*!< AES round keys. */\n    uint32_t buf[68];           /*!< Unaligned data buffer. This buffer can\n                                     hold 32 extra Bytes, which can be used for\n                                     one of the following purposes:\n                                     <ul><li>Alignment if VIA padlock is\n                                             used.</li>\n                                     <li>Simplifying key expansion in the 256-bit\n                                         case by generating an extra round key.\n                                         </li></ul> */\n}\nmbedtls_aes_context;\n\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n/**\n * \\brief The AES XTS context-type definition.\n */\ntypedef struct\n{\n    mbedtls_aes_context crypt; /*!< The AES context to use for AES block\n                                        encryption or decryption. */\n    mbedtls_aes_context tweak; /*!< The AES context used for tweak\n                                        computation. */\n} mbedtls_aes_xts_context;\n#endif /* MBEDTLS_CIPHER_MODE_XTS */\n\n#else  /* MBEDTLS_AES_ALT */\n#include \"aes_alt.h\"\n#endif /* MBEDTLS_AES_ALT */\n\n/**\n * \\brief          This function initializes the specified AES context.\n *\n *                 It must be the first API called before using\n *                 the context.\n *\n * \\param ctx      The AES context to initialize.\n */\nvoid mbedtls_aes_init( mbedtls_aes_context *ctx );\n\n/**\n * \\brief          This function releases and clears the specified AES context.\n *\n * \\param ctx      The AES context to clear.\n */\nvoid mbedtls_aes_free( mbedtls_aes_context *ctx );\n\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n/**\n * \\brief          This function initializes the specified AES XTS context.\n *\n *                 It must be the first API called before using\n *                 the context.\n *\n * \\param ctx      The AES XTS context to initialize.\n */\nvoid mbedtls_aes_xts_init( mbedtls_aes_xts_context *ctx );\n\n/**\n * \\brief          This function releases and clears the specified AES XTS context.\n *\n * \\param ctx      The AES XTS context to clear.\n */\nvoid mbedtls_aes_xts_free( mbedtls_aes_xts_context *ctx );\n#endif /* MBEDTLS_CIPHER_MODE_XTS */\n\n/**\n * \\brief          This function sets the encryption key.\n *\n * \\param ctx      The AES context to which the key should be bound.\n * \\param key      The encryption key.\n * \\param keybits  The size of data passed in bits. Valid options are:\n *                 <ul><li>128 bits</li>\n *                 <li>192 bits</li>\n *                 <li>256 bits</li></ul>\n *\n * \\return         \\c 0 on success.\n * \\return         #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.\n */\nint mbedtls_aes_setkey_enc( mbedtls_aes_context *ctx, const unsigned char *key,\n                    unsigned int keybits );\n\n/**\n * \\brief          This function sets the decryption key.\n *\n * \\param ctx      The AES context to which the key should be bound.\n * \\param key      The decryption key.\n * \\param keybits  The size of data passed. Valid options are:\n *                 <ul><li>128 bits</li>\n *                 <li>192 bits</li>\n *                 <li>256 bits</li></ul>\n *\n * \\return         \\c 0 on success.\n * \\return         #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.\n */\nint mbedtls_aes_setkey_dec( mbedtls_aes_context *ctx, const unsigned char *key,\n                    unsigned int keybits );\n\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n/**\n * \\brief          This function prepares an XTS context for encryption and\n *                 sets the encryption key.\n *\n * \\param ctx      The AES XTS context to which the key should be bound.\n * \\param key      The encryption key. This is comprised of the XTS key1\n *                 concatenated with the XTS key2.\n * \\param keybits  The size of \\p key passed in bits. Valid options are:\n *                 <ul><li>256 bits (each of key1 and key2 is a 128-bit key)</li>\n *                 <li>512 bits (each of key1 and key2 is a 256-bit key)</li></ul>\n *\n * \\return         \\c 0 on success.\n * \\return         #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.\n */\nint mbedtls_aes_xts_setkey_enc( mbedtls_aes_xts_context *ctx,\n                                const unsigned char *key,\n                                unsigned int keybits );\n\n/**\n * \\brief          This function prepares an XTS context for decryption and\n *                 sets the decryption key.\n *\n * \\param ctx      The AES XTS context to which the key should be bound.\n * \\param key      The decryption key. This is comprised of the XTS key1\n *                 concatenated with the XTS key2.\n * \\param keybits  The size of \\p key passed in bits. Valid options are:\n *                 <ul><li>256 bits (each of key1 and key2 is a 128-bit key)</li>\n *                 <li>512 bits (each of key1 and key2 is a 256-bit key)</li></ul>\n *\n * \\return         \\c 0 on success.\n * \\return         #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.\n */\nint mbedtls_aes_xts_setkey_dec( mbedtls_aes_xts_context *ctx,\n                                const unsigned char *key,\n                                unsigned int keybits );\n#endif /* MBEDTLS_CIPHER_MODE_XTS */\n\n/**\n * \\brief          This function performs an AES single-block encryption or\n *                 decryption operation.\n *\n *                 It performs the operation defined in the \\p mode parameter\n *                 (encrypt or decrypt), on the input data buffer defined in\n *                 the \\p input parameter.\n *\n *                 mbedtls_aes_init(), and either mbedtls_aes_setkey_enc() or\n *                 mbedtls_aes_setkey_dec() must be called before the first\n *                 call to this API with the same context.\n *\n * \\param ctx      The AES context to use for encryption or decryption.\n * \\param mode     The AES operation: #MBEDTLS_AES_ENCRYPT or\n *                 #MBEDTLS_AES_DECRYPT.\n * \\param input    The 16-Byte buffer holding the input data.\n * \\param output   The 16-Byte buffer holding the output data.\n\n * \\return         \\c 0 on success.\n */\nint mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx,\n                    int mode,\n                    const unsigned char input[16],\n                    unsigned char output[16] );\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n/**\n * \\brief  This function performs an AES-CBC encryption or decryption operation\n *         on full blocks.\n *\n *         It performs the operation defined in the \\p mode\n *         parameter (encrypt/decrypt), on the input data buffer defined in\n *         the \\p input parameter.\n *\n *         It can be called as many times as needed, until all the input\n *         data is processed. mbedtls_aes_init(), and either\n *         mbedtls_aes_setkey_enc() or mbedtls_aes_setkey_dec() must be called\n *         before the first call to this API with the same context.\n *\n * \\note   This function operates on aligned blocks, that is, the input size\n *         must be a multiple of the AES block size of 16 Bytes.\n *\n * \\note   Upon exit, the content of the IV is updated so that you can\n *         call the same function again on the next\n *         block(s) of data and get the same result as if it was\n *         encrypted in one call. This allows a \"streaming\" usage.\n *         If you need to retain the contents of the IV, you should\n *         either save it manually or use the cipher module instead.\n *\n *\n * \\param ctx      The AES context to use for encryption or decryption.\n * \\param mode     The AES operation: #MBEDTLS_AES_ENCRYPT or\n *                 #MBEDTLS_AES_DECRYPT.\n * \\param length   The length of the input data in Bytes. This must be a\n *                 multiple of the block size (16 Bytes).\n * \\param iv       Initialization vector (updated after use).\n * \\param input    The buffer holding the input data.\n * \\param output   The buffer holding the output data.\n *\n * \\return         \\c 0 on success.\n * \\return         #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH\n *                 on failure.\n */\nint mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx,\n                    int mode,\n                    size_t length,\n                    unsigned char iv[16],\n                    const unsigned char *input,\n                    unsigned char *output );\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n/**\n * \\brief      This function performs an AES-XTS encryption or decryption\n *             operation for an entire XTS data unit.\n *\n *             AES-XTS encrypts or decrypts blocks based on their location as\n *             defined by a data unit number. The data unit number must be\n *             provided by \\p data_unit.\n *\n *             NIST SP 800-38E limits the maximum size of a data unit to 2^20\n *             AES blocks. If the data unit is larger than this, this function\n *             returns #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH.\n *\n * \\param ctx          The AES XTS context to use for AES XTS operations.\n * \\param mode         The AES operation: #MBEDTLS_AES_ENCRYPT or\n *                     #MBEDTLS_AES_DECRYPT.\n * \\param length       The length of a data unit in bytes. This can be any\n *                     length between 16 bytes and 2^24 bytes inclusive\n *                     (between 1 and 2^20 block cipher blocks).\n * \\param data_unit    The address of the data unit encoded as an array of 16\n *                     bytes in little-endian format. For disk encryption, this\n *                     is typically the index of the block device sector that\n *                     contains the data.\n * \\param input        The buffer holding the input data (which is an entire\n *                     data unit). This function reads \\p length bytes from \\p\n *                     input.\n * \\param output       The buffer holding the output data (which is an entire\n *                     data unit). This function writes \\p length bytes to \\p\n *                     output.\n *\n * \\return             \\c 0 on success.\n * \\return             #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH if \\p length is\n *                     smaller than an AES block in size (16 bytes) or if \\p\n *                     length is larger than 2^20 blocks (16 MiB).\n */\nint mbedtls_aes_crypt_xts( mbedtls_aes_xts_context *ctx,\n                           int mode,\n                           size_t length,\n                           const unsigned char data_unit[16],\n                           const unsigned char *input,\n                           unsigned char *output );\n#endif /* MBEDTLS_CIPHER_MODE_XTS */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n/**\n * \\brief This function performs an AES-CFB128 encryption or decryption\n *        operation.\n *\n *        It performs the operation defined in the \\p mode\n *        parameter (encrypt or decrypt), on the input data buffer\n *        defined in the \\p input parameter.\n *\n *        For CFB, you must set up the context with mbedtls_aes_setkey_enc(),\n *        regardless of whether you are performing an encryption or decryption\n *        operation, that is, regardless of the \\p mode parameter. This is\n *        because CFB mode uses the same key schedule for encryption and\n *        decryption.\n *\n * \\note  Upon exit, the content of the IV is updated so that you can\n *        call the same function again on the next\n *        block(s) of data and get the same result as if it was\n *        encrypted in one call. This allows a \"streaming\" usage.\n *        If you need to retain the contents of the\n *        IV, you must either save it manually or use the cipher\n *        module instead.\n *\n *\n * \\param ctx      The AES context to use for encryption or decryption.\n * \\param mode     The AES operation: #MBEDTLS_AES_ENCRYPT or\n *                 #MBEDTLS_AES_DECRYPT.\n * \\param length   The length of the input data.\n * \\param iv_off   The offset in IV (updated after use).\n * \\param iv       The initialization vector (updated after use).\n * \\param input    The buffer holding the input data.\n * \\param output   The buffer holding the output data.\n *\n * \\return         \\c 0 on success.\n */\nint mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx,\n                       int mode,\n                       size_t length,\n                       size_t *iv_off,\n                       unsigned char iv[16],\n                       const unsigned char *input,\n                       unsigned char *output );\n\n/**\n * \\brief This function performs an AES-CFB8 encryption or decryption\n *        operation.\n *\n *        It performs the operation defined in the \\p mode\n *        parameter (encrypt/decrypt), on the input data buffer defined\n *        in the \\p input parameter.\n *\n *        Due to the nature of CFB, you must use the same key schedule for\n *        both encryption and decryption operations. Therefore, you must\n *        use the context initialized with mbedtls_aes_setkey_enc() for\n *        both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT.\n *\n * \\note  Upon exit, the content of the IV is updated so that you can\n *        call the same function again on the next\n *        block(s) of data and get the same result as if it was\n *        encrypted in one call. This allows a \"streaming\" usage.\n *        If you need to retain the contents of the\n *        IV, you should either save it manually or use the cipher\n *        module instead.\n *\n *\n * \\param ctx      The AES context to use for encryption or decryption.\n * \\param mode     The AES operation: #MBEDTLS_AES_ENCRYPT or\n *                 #MBEDTLS_AES_DECRYPT\n * \\param length   The length of the input data.\n * \\param iv       The initialization vector (updated after use).\n * \\param input    The buffer holding the input data.\n * \\param output   The buffer holding the output data.\n *\n * \\return         \\c 0 on success.\n */\nint mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx,\n                    int mode,\n                    size_t length,\n                    unsigned char iv[16],\n                    const unsigned char *input,\n                    unsigned char *output );\n#endif /*MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n/**\n * \\brief       This function performs an AES-OFB (Output Feedback Mode)\n *              encryption or decryption operation.\n *\n *              For OFB, you must set up the context with\n *              mbedtls_aes_setkey_enc(), regardless of whether you are\n *              performing an encryption or decryption operation. This is\n *              because OFB mode uses the same key schedule for encryption and\n *              decryption.\n *\n *              The OFB operation is identical for encryption or decryption,\n *              therefore no operation mode needs to be specified.\n *\n * \\note        Upon exit, the content of iv, the Initialisation Vector, is\n *              updated so that you can call the same function again on the next\n *              block(s) of data and get the same result as if it was encrypted\n *              in one call. This allows a \"streaming\" usage, by initialising\n *              iv_off to 0 before the first call, and preserving its value\n *              between calls.\n *\n *              For non-streaming use, the iv should be initialised on each call\n *              to a unique value, and iv_off set to 0 on each call.\n *\n *              If you need to retain the contents of the initialisation vector,\n *              you must either save it manually or use the cipher module\n *              instead.\n *\n * \\warning     For the OFB mode, the initialisation vector must be unique\n *              every encryption operation. Reuse of an initialisation vector\n *              will compromise security.\n *\n * \\param ctx      The AES context to use for encryption or decryption.\n * \\param length   The length of the input data.\n * \\param iv_off   The offset in IV (updated after use).\n * \\param iv       The initialization vector (updated after use).\n * \\param input    The buffer holding the input data.\n * \\param output   The buffer holding the output data.\n *\n * \\return         \\c 0 on success.\n */\nint mbedtls_aes_crypt_ofb( mbedtls_aes_context *ctx,\n                       size_t length,\n                       size_t *iv_off,\n                       unsigned char iv[16],\n                       const unsigned char *input,\n                       unsigned char *output );\n\n#endif /* MBEDTLS_CIPHER_MODE_OFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n/**\n * \\brief      This function performs an AES-CTR encryption or decryption\n *             operation.\n *\n *             This function performs the operation defined in the \\p mode\n *             parameter (encrypt/decrypt), on the input data buffer\n *             defined in the \\p input parameter.\n *\n *             Due to the nature of CTR, you must use the same key schedule\n *             for both encryption and decryption operations. Therefore, you\n *             must use the context initialized with mbedtls_aes_setkey_enc()\n *             for both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT.\n *\n * \\warning    You must never reuse a nonce value with the same key. Doing so\n *             would void the encryption for the two messages encrypted with\n *             the same nonce and key.\n *\n *             There are two common strategies for managing nonces with CTR:\n *\n *             1. You can handle everything as a single message processed over\n *             successive calls to this function. In that case, you want to\n *             set \\p nonce_counter and \\p nc_off to 0 for the first call, and\n *             then preserve the values of \\p nonce_counter, \\p nc_off and \\p\n *             stream_block across calls to this function as they will be\n *             updated by this function.\n *\n *             With this strategy, you must not encrypt more than 2**128\n *             blocks of data with the same key.\n *\n *             2. You can encrypt separate messages by dividing the \\p\n *             nonce_counter buffer in two areas: the first one used for a\n *             per-message nonce, handled by yourself, and the second one\n *             updated by this function internally.\n *\n *             For example, you might reserve the first 12 bytes for the\n *             per-message nonce, and the last 4 bytes for internal use. In that\n *             case, before calling this function on a new message you need to\n *             set the first 12 bytes of \\p nonce_counter to your chosen nonce\n *             value, the last 4 to 0, and \\p nc_off to 0 (which will cause \\p\n *             stream_block to be ignored). That way, you can encrypt at most\n *             2**96 messages of up to 2**32 blocks each with the same key.\n *\n *             The per-message nonce (or information sufficient to reconstruct\n *             it) needs to be communicated with the ciphertext and must be unique.\n *             The recommended way to ensure uniqueness is to use a message\n *             counter. An alternative is to generate random nonces, but this\n *             limits the number of messages that can be securely encrypted:\n *             for example, with 96-bit random nonces, you should not encrypt\n *             more than 2**32 messages with the same key.\n *\n *             Note that for both stategies, sizes are measured in blocks and\n *             that an AES block is 16 bytes.\n *\n * \\warning    Upon return, \\p stream_block contains sensitive data. Its\n *             content must not be written to insecure storage and should be\n *             securely discarded as soon as it's no longer needed.\n *\n * \\param ctx              The AES context to use for encryption or decryption.\n * \\param length           The length of the input data.\n * \\param nc_off           The offset in the current \\p stream_block, for\n *                         resuming within the current cipher stream. The\n *                         offset pointer should be 0 at the start of a stream.\n * \\param nonce_counter    The 128-bit nonce and counter.\n * \\param stream_block     The saved stream block for resuming. This is\n *                         overwritten by the function.\n * \\param input            The buffer holding the input data.\n * \\param output           The buffer holding the output data.\n *\n * \\return                 \\c 0 on success.\n */\nint mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx,\n                       size_t length,\n                       size_t *nc_off,\n                       unsigned char nonce_counter[16],\n                       unsigned char stream_block[16],\n                       const unsigned char *input,\n                       unsigned char *output );\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\n/**\n * \\brief           Internal AES block encryption function. This is only\n *                  exposed to allow overriding it using\n *                  \\c MBEDTLS_AES_ENCRYPT_ALT.\n *\n * \\param ctx       The AES context to use for encryption.\n * \\param input     The plaintext block.\n * \\param output    The output (ciphertext) block.\n *\n * \\return          \\c 0 on success.\n */\nint mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx,\n                                  const unsigned char input[16],\n                                  unsigned char output[16] );\n\n/**\n * \\brief           Internal AES block decryption function. This is only\n *                  exposed to allow overriding it using see\n *                  \\c MBEDTLS_AES_DECRYPT_ALT.\n *\n * \\param ctx       The AES context to use for decryption.\n * \\param input     The ciphertext block.\n * \\param output    The output (plaintext) block.\n *\n * \\return          \\c 0 on success.\n */\nint mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx,\n                                  const unsigned char input[16],\n                                  unsigned char output[16] );\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED      __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n/**\n * \\brief           Deprecated internal AES block encryption function\n *                  without return value.\n *\n * \\deprecated      Superseded by mbedtls_aes_encrypt_ext() in 2.5.0.\n *\n * \\param ctx       The AES context to use for encryption.\n * \\param input     Plaintext block.\n * \\param output    Output (ciphertext) block.\n */\nMBEDTLS_DEPRECATED void mbedtls_aes_encrypt( mbedtls_aes_context *ctx,\n                                             const unsigned char input[16],\n                                             unsigned char output[16] );\n\n/**\n * \\brief           Deprecated internal AES block decryption function\n *                  without return value.\n *\n * \\deprecated      Superseded by mbedtls_aes_decrypt_ext() in 2.5.0.\n *\n * \\param ctx       The AES context to use for decryption.\n * \\param input     Ciphertext block.\n * \\param output    Output (plaintext) block.\n */\nMBEDTLS_DEPRECATED void mbedtls_aes_decrypt( mbedtls_aes_context *ctx,\n                                             const unsigned char input[16],\n                                             unsigned char output[16] );\n\n#undef MBEDTLS_DEPRECATED\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n\n/**\n * \\brief          Checkup routine.\n *\n * \\return         \\c 0 on success.\n * \\return         \\c 1 on failure.\n */\nint mbedtls_aes_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* aes.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/aesni.h",
    "content": "/**\n * \\file aesni.h\n *\n * \\brief AES-NI for hardware AES acceleration on some Intel processors\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_AESNI_H\n#define MBEDTLS_AESNI_H\n\n#include \"aes.h\"\n\n#define MBEDTLS_AESNI_AES      0x02000000u\n#define MBEDTLS_AESNI_CLMUL    0x00000002u\n\n#if defined(MBEDTLS_HAVE_ASM) && defined(__GNUC__) &&  \\\n    ( defined(__amd64__) || defined(__x86_64__) )   &&  \\\n    ! defined(MBEDTLS_HAVE_X86_64)\n#define MBEDTLS_HAVE_X86_64\n#endif\n\n#if defined(MBEDTLS_HAVE_X86_64)\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief          AES-NI features detection routine\n *\n * \\param what     The feature to detect\n *                 (MBEDTLS_AESNI_AES or MBEDTLS_AESNI_CLMUL)\n *\n * \\return         1 if CPU has support for the feature, 0 otherwise\n */\nint mbedtls_aesni_has_support( unsigned int what );\n\n/**\n * \\brief          AES-NI AES-ECB block en(de)cryption\n *\n * \\param ctx      AES context\n * \\param mode     MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT\n * \\param input    16-byte input block\n * \\param output   16-byte output block\n *\n * \\return         0 on success (cannot fail)\n */\nint mbedtls_aesni_crypt_ecb( mbedtls_aes_context *ctx,\n                     int mode,\n                     const unsigned char input[16],\n                     unsigned char output[16] );\n\n/**\n * \\brief          GCM multiplication: c = a * b in GF(2^128)\n *\n * \\param c        Result\n * \\param a        First operand\n * \\param b        Second operand\n *\n * \\note           Both operands and result are bit strings interpreted as\n *                 elements of GF(2^128) as per the GCM spec.\n */\nvoid mbedtls_aesni_gcm_mult( unsigned char c[16],\n                     const unsigned char a[16],\n                     const unsigned char b[16] );\n\n/**\n * \\brief           Compute decryption round keys from encryption round keys\n *\n * \\param invkey    Round keys for the equivalent inverse cipher\n * \\param fwdkey    Original round keys (for encryption)\n * \\param nr        Number of rounds (that is, number of round keys minus one)\n */\nvoid mbedtls_aesni_inverse_key( unsigned char *invkey,\n                        const unsigned char *fwdkey, int nr );\n\n/**\n * \\brief           Perform key expansion (for encryption)\n *\n * \\param rk        Destination buffer where the round keys are written\n * \\param key       Encryption key\n * \\param bits      Key size in bits (must be 128, 192 or 256)\n *\n * \\return          0 if successful, or MBEDTLS_ERR_AES_INVALID_KEY_LENGTH\n */\nint mbedtls_aesni_setkey_enc( unsigned char *rk,\n                      const unsigned char *key,\n                      size_t bits );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* MBEDTLS_HAVE_X86_64 */\n\n#endif /* MBEDTLS_AESNI_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/arc4.h",
    "content": "/**\n * \\file arc4.h\n *\n * \\brief The ARCFOUR stream cipher\n *\n * \\warning   ARC4 is considered a weak cipher and its use constitutes a\n *            security risk. We recommend considering stronger ciphers instead.\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n *\n */\n#ifndef MBEDTLS_ARC4_H\n#define MBEDTLS_ARC4_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n\n#define MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED                  -0x0019  /**< ARC4 hardware accelerator failed. */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_ARC4_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief     ARC4 context structure\n *\n * \\warning   ARC4 is considered a weak cipher and its use constitutes a\n *            security risk. We recommend considering stronger ciphers instead.\n *\n */\ntypedef struct\n{\n    int x;                      /*!< permutation index */\n    int y;                      /*!< permutation index */\n    unsigned char m[256];       /*!< permutation table */\n}\nmbedtls_arc4_context;\n\n#else  /* MBEDTLS_ARC4_ALT */\n#include \"arc4_alt.h\"\n#endif /* MBEDTLS_ARC4_ALT */\n\n/**\n * \\brief          Initialize ARC4 context\n *\n * \\param ctx      ARC4 context to be initialized\n *\n * \\warning        ARC4 is considered a weak cipher and its use constitutes a\n *                 security risk. We recommend considering stronger ciphers\n *                 instead.\n *\n */\nvoid mbedtls_arc4_init( mbedtls_arc4_context *ctx );\n\n/**\n * \\brief          Clear ARC4 context\n *\n * \\param ctx      ARC4 context to be cleared\n *\n * \\warning        ARC4 is considered a weak cipher and its use constitutes a\n *                 security risk. We recommend considering stronger ciphers\n *                 instead.\n *\n */\nvoid mbedtls_arc4_free( mbedtls_arc4_context *ctx );\n\n/**\n * \\brief          ARC4 key schedule\n *\n * \\param ctx      ARC4 context to be setup\n * \\param key      the secret key\n * \\param keylen   length of the key, in bytes\n *\n * \\warning        ARC4 is considered a weak cipher and its use constitutes a\n *                 security risk. We recommend considering stronger ciphers\n *                 instead.\n *\n */\nvoid mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key,\n                 unsigned int keylen );\n\n/**\n * \\brief          ARC4 cipher function\n *\n * \\param ctx      ARC4 context\n * \\param length   length of the input data\n * \\param input    buffer holding the input data\n * \\param output   buffer for the output data\n *\n * \\return         0 if successful\n *\n * \\warning        ARC4 is considered a weak cipher and its use constitutes a\n *                 security risk. We recommend considering stronger ciphers\n *                 instead.\n *\n */\nint mbedtls_arc4_crypt( mbedtls_arc4_context *ctx, size_t length, const unsigned char *input,\n                unsigned char *output );\n\n/**\n * \\brief          Checkup routine\n *\n * \\return         0 if successful, or 1 if the test failed\n *\n * \\warning        ARC4 is considered a weak cipher and its use constitutes a\n *                 security risk. We recommend considering stronger ciphers\n *                 instead.\n *\n */\nint mbedtls_arc4_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* arc4.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/aria.h",
    "content": "/**\n * \\file aria.h\n *\n * \\brief ARIA block cipher\n *\n *        The ARIA algorithm is a symmetric block cipher that can encrypt and\n *        decrypt information. It is defined by the Korean Agency for\n *        Technology and Standards (KATS) in <em>KS X 1213:2004</em> (in\n *        Korean, but see http://210.104.33.10/ARIA/index-e.html in English)\n *        and also described by the IETF in <em>RFC 5794</em>.\n */\n/*  Copyright (C) 2006-2018, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_ARIA_H\n#define MBEDTLS_ARIA_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n#include <stdint.h>\n\n#define MBEDTLS_ARIA_ENCRYPT     1 /**< ARIA encryption. */\n#define MBEDTLS_ARIA_DECRYPT     0 /**< ARIA decryption. */\n\n#define MBEDTLS_ARIA_BLOCKSIZE   16 /**< ARIA block size in bytes. */\n#define MBEDTLS_ARIA_MAX_ROUNDS  16 /**< Maxiumum number of rounds in ARIA. */\n#define MBEDTLS_ARIA_MAX_KEYSIZE 32 /**< Maximum size of an ARIA key in bytes. */\n\n#define MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH   -0x005C  /**< Invalid key length. */\n#define MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH -0x005E  /**< Invalid data input length. */\n#define MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE  -0x005A  /**< Feature not available. For example, an unsupported ARIA key size. */\n#define MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED      -0x0058  /**< ARIA hardware accelerator failed. */\n\n#if !defined(MBEDTLS_ARIA_ALT)\n// Regular implementation\n//\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief The ARIA context-type definition.\n */\ntypedef struct\n{\n    unsigned char nr;           /*!< The number of rounds (12, 14 or 16) */\n    /*! The ARIA round keys. */\n    uint32_t rk[MBEDTLS_ARIA_MAX_ROUNDS + 1][MBEDTLS_ARIA_BLOCKSIZE / 4];\n}\nmbedtls_aria_context;\n\n#else  /* MBEDTLS_ARIA_ALT */\n#include \"aria_alt.h\"\n#endif /* MBEDTLS_ARIA_ALT */\n\n/**\n * \\brief          This function initializes the specified ARIA context.\n *\n *                 It must be the first API called before using\n *                 the context.\n *\n * \\param ctx      The ARIA context to initialize.\n */\nvoid mbedtls_aria_init( mbedtls_aria_context *ctx );\n\n/**\n * \\brief          This function releases and clears the specified ARIA context.\n *\n * \\param ctx      The ARIA context to clear.\n */\nvoid mbedtls_aria_free( mbedtls_aria_context *ctx );\n\n/**\n * \\brief          This function sets the encryption key.\n *\n * \\param ctx      The ARIA context to which the key should be bound.\n * \\param key      The encryption key.\n * \\param keybits  The size of data passed in bits. Valid options are:\n *                 <ul><li>128 bits</li>\n *                 <li>192 bits</li>\n *                 <li>256 bits</li></ul>\n *\n * \\return         \\c 0 on success or #MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH\n *                 on failure.\n */\nint mbedtls_aria_setkey_enc( mbedtls_aria_context *ctx,\n                             const unsigned char *key,\n                             unsigned int keybits );\n\n/**\n * \\brief          This function sets the decryption key.\n *\n * \\param ctx      The ARIA context to which the key should be bound.\n * \\param key      The decryption key.\n * \\param keybits  The size of data passed. Valid options are:\n *                 <ul><li>128 bits</li>\n *                 <li>192 bits</li>\n *                 <li>256 bits</li></ul>\n *\n * \\return         \\c 0 on success, or #MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH on failure.\n */\nint mbedtls_aria_setkey_dec( mbedtls_aria_context *ctx,\n                             const unsigned char *key,\n                             unsigned int keybits );\n\n/**\n * \\brief          This function performs an ARIA single-block encryption or\n *                 decryption operation.\n *\n *                 It performs encryption or decryption (depending on whether\n *                 the key was set for encryption on decryption) on the input\n *                 data buffer defined in the \\p input parameter.\n *\n *                 mbedtls_aria_init(), and either mbedtls_aria_setkey_enc() or\n *                 mbedtls_aria_setkey_dec() must be called before the first\n *                 call to this API with the same context.\n *\n * \\param ctx      The ARIA context to use for encryption or decryption.\n * \\param input    The 16-Byte buffer holding the input data.\n * \\param output   The 16-Byte buffer holding the output data.\n\n * \\return         \\c 0 on success.\n */\nint mbedtls_aria_crypt_ecb( mbedtls_aria_context *ctx,\n                            const unsigned char input[MBEDTLS_ARIA_BLOCKSIZE],\n                            unsigned char output[MBEDTLS_ARIA_BLOCKSIZE] );\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n/**\n * \\brief  This function performs an ARIA-CBC encryption or decryption operation\n *         on full blocks.\n *\n *         It performs the operation defined in the \\p mode\n *         parameter (encrypt/decrypt), on the input data buffer defined in\n *         the \\p input parameter.\n *\n *         It can be called as many times as needed, until all the input\n *         data is processed. mbedtls_aria_init(), and either\n *         mbedtls_aria_setkey_enc() or mbedtls_aria_setkey_dec() must be called\n *         before the first call to this API with the same context.\n *\n * \\note   This function operates on aligned blocks, that is, the input size\n *         must be a multiple of the ARIA block size of 16 Bytes.\n *\n * \\note   Upon exit, the content of the IV is updated so that you can\n *         call the same function again on the next\n *         block(s) of data and get the same result as if it was\n *         encrypted in one call. This allows a \"streaming\" usage.\n *         If you need to retain the contents of the IV, you should\n *         either save it manually or use the cipher module instead.\n *\n *\n * \\param ctx      The ARIA context to use for encryption or decryption.\n * \\param mode     The ARIA operation: #MBEDTLS_ARIA_ENCRYPT or\n *                 #MBEDTLS_ARIA_DECRYPT.\n * \\param length   The length of the input data in Bytes. This must be a\n *                 multiple of the block size (16 Bytes).\n * \\param iv       Initialization vector (updated after use).\n * \\param input    The buffer holding the input data.\n * \\param output   The buffer holding the output data.\n *\n * \\return         \\c 0 on success, or #MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH\n *                 on failure.\n */\nint mbedtls_aria_crypt_cbc( mbedtls_aria_context *ctx,\n                            int mode,\n                            size_t length,\n                            unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE],\n                            const unsigned char *input,\n                            unsigned char *output );\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n/**\n * \\brief This function performs an ARIA-CFB128 encryption or decryption\n *        operation.\n *\n *        It performs the operation defined in the \\p mode\n *        parameter (encrypt or decrypt), on the input data buffer\n *        defined in the \\p input parameter.\n *\n *        For CFB, you must set up the context with mbedtls_aria_setkey_enc(),\n *        regardless of whether you are performing an encryption or decryption\n *        operation, that is, regardless of the \\p mode parameter. This is\n *        because CFB mode uses the same key schedule for encryption and\n *        decryption.\n *\n * \\note  Upon exit, the content of the IV is updated so that you can\n *        call the same function again on the next\n *        block(s) of data and get the same result as if it was\n *        encrypted in one call. This allows a \"streaming\" usage.\n *        If you need to retain the contents of the\n *        IV, you must either save it manually or use the cipher\n *        module instead.\n *\n *\n * \\param ctx      The ARIA context to use for encryption or decryption.\n * \\param mode     The ARIA operation: #MBEDTLS_ARIA_ENCRYPT or\n *                 #MBEDTLS_ARIA_DECRYPT.\n * \\param length   The length of the input data.\n * \\param iv_off   The offset in IV (updated after use).\n * \\param iv       The initialization vector (updated after use).\n * \\param input    The buffer holding the input data.\n * \\param output   The buffer holding the output data.\n *\n * \\return         \\c 0 on success.\n */\nint mbedtls_aria_crypt_cfb128( mbedtls_aria_context *ctx,\n                               int mode,\n                               size_t length,\n                               size_t *iv_off,\n                               unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE],\n                               const unsigned char *input,\n                               unsigned char *output );\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n/**\n * \\brief      This function performs an ARIA-CTR encryption or decryption\n *             operation.\n *\n *             This function performs the operation defined in the \\p mode\n *             parameter (encrypt/decrypt), on the input data buffer\n *             defined in the \\p input parameter.\n *\n *             Due to the nature of CTR, you must use the same key schedule\n *             for both encryption and decryption operations. Therefore, you\n *             must use the context initialized with mbedtls_aria_setkey_enc()\n *             for both #MBEDTLS_ARIA_ENCRYPT and #MBEDTLS_ARIA_DECRYPT.\n *\n * \\warning    You must never reuse a nonce value with the same key. Doing so\n *             would void the encryption for the two messages encrypted with\n *             the same nonce and key.\n *\n *             There are two common strategies for managing nonces with CTR:\n *\n *             1. You can handle everything as a single message processed over\n *             successive calls to this function. In that case, you want to\n *             set \\p nonce_counter and \\p nc_off to 0 for the first call, and\n *             then preserve the values of \\p nonce_counter, \\p nc_off and \\p\n *             stream_block across calls to this function as they will be\n *             updated by this function.\n *\n *             With this strategy, you must not encrypt more than 2**128\n *             blocks of data with the same key.\n *\n *             2. You can encrypt separate messages by dividing the \\p\n *             nonce_counter buffer in two areas: the first one used for a\n *             per-message nonce, handled by yourself, and the second one\n *             updated by this function internally.\n *\n *             For example, you might reserve the first 12 bytes for the\n *             per-message nonce, and the last 4 bytes for internal use. In that\n *             case, before calling this function on a new message you need to\n *             set the first 12 bytes of \\p nonce_counter to your chosen nonce\n *             value, the last 4 to 0, and \\p nc_off to 0 (which will cause \\p\n *             stream_block to be ignored). That way, you can encrypt at most\n *             2**96 messages of up to 2**32 blocks each with the same key.\n *\n *             The per-message nonce (or information sufficient to reconstruct\n *             it) needs to be communicated with the ciphertext and must be unique.\n *             The recommended way to ensure uniqueness is to use a message\n *             counter. An alternative is to generate random nonces, but this\n *             limits the number of messages that can be securely encrypted:\n *             for example, with 96-bit random nonces, you should not encrypt\n *             more than 2**32 messages with the same key.\n *\n *             Note that for both stategies, sizes are measured in blocks and\n *             that an ARIA block is 16 bytes.\n *\n * \\warning    Upon return, \\p stream_block contains sensitive data. Its\n *             content must not be written to insecure storage and should be\n *             securely discarded as soon as it's no longer needed.\n *\n * \\param ctx              The ARIA context to use for encryption or decryption.\n * \\param length           The length of the input data.\n * \\param nc_off           The offset in the current \\p stream_block, for\n *                         resuming within the current cipher stream. The\n *                         offset pointer should be 0 at the start of a stream.\n * \\param nonce_counter    The 128-bit nonce and counter.\n * \\param stream_block     The saved stream block for resuming. This is\n *                         overwritten by the function.\n * \\param input            The buffer holding the input data.\n * \\param output           The buffer holding the output data.\n *\n * \\return     \\c 0 on success.\n */\nint mbedtls_aria_crypt_ctr( mbedtls_aria_context *ctx,\n                            size_t length,\n                            size_t *nc_off,\n                            unsigned char nonce_counter[MBEDTLS_ARIA_BLOCKSIZE],\n                            unsigned char stream_block[MBEDTLS_ARIA_BLOCKSIZE],\n                            const unsigned char *input,\n                            unsigned char *output );\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\n#if defined(MBEDTLS_SELF_TEST)\n/**\n * \\brief          Checkup routine.\n *\n * \\return         \\c 0 on success, or \\c 1 on failure.\n */\nint mbedtls_aria_self_test( int verbose );\n#endif /* MBEDTLS_SELF_TEST */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* aria.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/asn1.h",
    "content": "/**\n * \\file asn1.h\n *\n * \\brief Generic ASN.1 parsing\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_ASN1_H\n#define MBEDTLS_ASN1_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n\n#if defined(MBEDTLS_BIGNUM_C)\n#include \"bignum.h\"\n#endif\n\n/**\n * \\addtogroup asn1_module\n * \\{\n */\n\n/**\n * \\name ASN1 Error codes\n * These error codes are OR'ed to X509 error codes for\n * higher error granularity.\n * ASN1 is a standard to specify data structures.\n * \\{\n */\n#define MBEDTLS_ERR_ASN1_OUT_OF_DATA                      -0x0060  /**< Out of data when parsing an ASN1 data structure. */\n#define MBEDTLS_ERR_ASN1_UNEXPECTED_TAG                   -0x0062  /**< ASN1 tag was of an unexpected value. */\n#define MBEDTLS_ERR_ASN1_INVALID_LENGTH                   -0x0064  /**< Error when trying to determine the length or invalid length. */\n#define MBEDTLS_ERR_ASN1_LENGTH_MISMATCH                  -0x0066  /**< Actual length differs from expected length. */\n#define MBEDTLS_ERR_ASN1_INVALID_DATA                     -0x0068  /**< Data is invalid. (not used) */\n#define MBEDTLS_ERR_ASN1_ALLOC_FAILED                     -0x006A  /**< Memory allocation failed */\n#define MBEDTLS_ERR_ASN1_BUF_TOO_SMALL                    -0x006C  /**< Buffer too small when writing ASN.1 data structure. */\n\n/* \\} name */\n\n/**\n * \\name DER constants\n * These constants comply with the DER encoded ASN.1 type tags.\n * DER encoding uses hexadecimal representation.\n * An example DER sequence is:\\n\n * - 0x02 -- tag indicating INTEGER\n * - 0x01 -- length in octets\n * - 0x05 -- value\n * Such sequences are typically read into \\c ::mbedtls_x509_buf.\n * \\{\n */\n#define MBEDTLS_ASN1_BOOLEAN                 0x01\n#define MBEDTLS_ASN1_INTEGER                 0x02\n#define MBEDTLS_ASN1_BIT_STRING              0x03\n#define MBEDTLS_ASN1_OCTET_STRING            0x04\n#define MBEDTLS_ASN1_NULL                    0x05\n#define MBEDTLS_ASN1_OID                     0x06\n#define MBEDTLS_ASN1_UTF8_STRING             0x0C\n#define MBEDTLS_ASN1_SEQUENCE                0x10\n#define MBEDTLS_ASN1_SET                     0x11\n#define MBEDTLS_ASN1_PRINTABLE_STRING        0x13\n#define MBEDTLS_ASN1_T61_STRING              0x14\n#define MBEDTLS_ASN1_IA5_STRING              0x16\n#define MBEDTLS_ASN1_UTC_TIME                0x17\n#define MBEDTLS_ASN1_GENERALIZED_TIME        0x18\n#define MBEDTLS_ASN1_UNIVERSAL_STRING        0x1C\n#define MBEDTLS_ASN1_BMP_STRING              0x1E\n#define MBEDTLS_ASN1_PRIMITIVE               0x00\n#define MBEDTLS_ASN1_CONSTRUCTED             0x20\n#define MBEDTLS_ASN1_CONTEXT_SPECIFIC        0x80\n\n/*\n * Bit masks for each of the components of an ASN.1 tag as specified in\n * ITU X.690 (08/2015), section 8.1 \"General rules for encoding\",\n * paragraph 8.1.2.2:\n *\n * Bit  8     7   6   5          1\n *     +-------+-----+------------+\n *     | Class | P/C | Tag number |\n *     +-------+-----+------------+\n */\n#define MBEDTLS_ASN1_TAG_CLASS_MASK          0xC0\n#define MBEDTLS_ASN1_TAG_PC_MASK             0x20\n#define MBEDTLS_ASN1_TAG_VALUE_MASK          0x1F\n\n/* \\} name */\n/* \\} addtogroup asn1_module */\n\n/** Returns the size of the binary string, without the trailing \\\\0 */\n#define MBEDTLS_OID_SIZE(x) (sizeof(x) - 1)\n\n/**\n * Compares an mbedtls_asn1_buf structure to a reference OID.\n *\n * Only works for 'defined' oid_str values (MBEDTLS_OID_HMAC_SHA1), you cannot use a\n * 'unsigned char *oid' here!\n */\n#define MBEDTLS_OID_CMP(oid_str, oid_buf)                                   \\\n        ( ( MBEDTLS_OID_SIZE(oid_str) != (oid_buf)->len ) ||                \\\n          memcmp( (oid_str), (oid_buf)->p, (oid_buf)->len) != 0 )\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\name Functions to parse ASN.1 data structures\n * \\{\n */\n\n/**\n * Type-length-value structure that allows for ASN1 using DER.\n */\ntypedef struct mbedtls_asn1_buf\n{\n    int tag;                /**< ASN1 type, e.g. MBEDTLS_ASN1_UTF8_STRING. */\n    size_t len;             /**< ASN1 length, in octets. */\n    unsigned char *p;       /**< ASN1 data, e.g. in ASCII. */\n}\nmbedtls_asn1_buf;\n\n/**\n * Container for ASN1 bit strings.\n */\ntypedef struct mbedtls_asn1_bitstring\n{\n    size_t len;                 /**< ASN1 length, in octets. */\n    unsigned char unused_bits;  /**< Number of unused bits at the end of the string */\n    unsigned char *p;           /**< Raw ASN1 data for the bit string */\n}\nmbedtls_asn1_bitstring;\n\n/**\n * Container for a sequence of ASN.1 items\n */\ntypedef struct mbedtls_asn1_sequence\n{\n    mbedtls_asn1_buf buf;                   /**< Buffer containing the given ASN.1 item. */\n    struct mbedtls_asn1_sequence *next;    /**< The next entry in the sequence. */\n}\nmbedtls_asn1_sequence;\n\n/**\n * Container for a sequence or list of 'named' ASN.1 data items\n */\ntypedef struct mbedtls_asn1_named_data\n{\n    mbedtls_asn1_buf oid;                   /**< The object identifier. */\n    mbedtls_asn1_buf val;                   /**< The named value. */\n    struct mbedtls_asn1_named_data *next;  /**< The next entry in the sequence. */\n    unsigned char next_merged;      /**< Merge next item into the current one? */\n}\nmbedtls_asn1_named_data;\n\n/**\n * \\brief       Get the length of an ASN.1 element.\n *              Updates the pointer to immediately behind the length.\n *\n * \\param p     The position in the ASN.1 data\n * \\param end   End of data\n * \\param len   The variable that will receive the value\n *\n * \\return      0 if successful, MBEDTLS_ERR_ASN1_OUT_OF_DATA on reaching\n *              end of data, MBEDTLS_ERR_ASN1_INVALID_LENGTH if length is\n *              unparseable.\n */\nint mbedtls_asn1_get_len( unsigned char **p,\n                  const unsigned char *end,\n                  size_t *len );\n\n/**\n * \\brief       Get the tag and length of the tag. Check for the requested tag.\n *              Updates the pointer to immediately behind the tag and length.\n *\n * \\param p     The position in the ASN.1 data\n * \\param end   End of data\n * \\param len   The variable that will receive the length\n * \\param tag   The expected tag\n *\n * \\return      0 if successful, MBEDTLS_ERR_ASN1_UNEXPECTED_TAG if tag did\n *              not match requested tag, or another specific ASN.1 error code.\n */\nint mbedtls_asn1_get_tag( unsigned char **p,\n                  const unsigned char *end,\n                  size_t *len, int tag );\n\n/**\n * \\brief       Retrieve a boolean ASN.1 tag and its value.\n *              Updates the pointer to immediately behind the full tag.\n *\n * \\param p     The position in the ASN.1 data\n * \\param end   End of data\n * \\param val   The variable that will receive the value\n *\n * \\return      0 if successful or a specific ASN.1 error code.\n */\nint mbedtls_asn1_get_bool( unsigned char **p,\n                   const unsigned char *end,\n                   int *val );\n\n/**\n * \\brief       Retrieve an integer ASN.1 tag and its value.\n *              Updates the pointer to immediately behind the full tag.\n *\n * \\param p     The position in the ASN.1 data\n * \\param end   End of data\n * \\param val   The variable that will receive the value\n *\n * \\return      0 if successful or a specific ASN.1 error code.\n */\nint mbedtls_asn1_get_int( unsigned char **p,\n                  const unsigned char *end,\n                  int *val );\n\n/**\n * \\brief       Retrieve a bitstring ASN.1 tag and its value.\n *              Updates the pointer to immediately behind the full tag.\n *\n * \\param p     The position in the ASN.1 data\n * \\param end   End of data\n * \\param bs    The variable that will receive the value\n *\n * \\return      0 if successful or a specific ASN.1 error code.\n */\nint mbedtls_asn1_get_bitstring( unsigned char **p, const unsigned char *end,\n                        mbedtls_asn1_bitstring *bs);\n\n/**\n * \\brief       Retrieve a bitstring ASN.1 tag without unused bits and its\n *              value.\n *              Updates the pointer to the beginning of the bit/octet string.\n *\n * \\param p     The position in the ASN.1 data\n * \\param end   End of data\n * \\param len   Length of the actual bit/octect string in bytes\n *\n * \\return      0 if successful or a specific ASN.1 error code.\n */\nint mbedtls_asn1_get_bitstring_null( unsigned char **p, const unsigned char *end,\n                             size_t *len );\n\n/**\n * \\brief       Parses and splits an ASN.1 \"SEQUENCE OF <tag>\"\n *              Updated the pointer to immediately behind the full sequence tag.\n *\n * \\param p     The position in the ASN.1 data\n * \\param end   End of data\n * \\param cur   First variable in the chain to fill\n * \\param tag   Type of sequence\n *\n * \\return      0 if successful or a specific ASN.1 error code.\n */\nint mbedtls_asn1_get_sequence_of( unsigned char **p,\n                          const unsigned char *end,\n                          mbedtls_asn1_sequence *cur,\n                          int tag);\n\n#if defined(MBEDTLS_BIGNUM_C)\n/**\n * \\brief       Retrieve a MPI value from an integer ASN.1 tag.\n *              Updates the pointer to immediately behind the full tag.\n *\n * \\param p     The position in the ASN.1 data\n * \\param end   End of data\n * \\param X     The MPI that will receive the value\n *\n * \\return      0 if successful or a specific ASN.1 or MPI error code.\n */\nint mbedtls_asn1_get_mpi( unsigned char **p,\n                  const unsigned char *end,\n                  mbedtls_mpi *X );\n#endif /* MBEDTLS_BIGNUM_C */\n\n/**\n * \\brief       Retrieve an AlgorithmIdentifier ASN.1 sequence.\n *              Updates the pointer to immediately behind the full\n *              AlgorithmIdentifier.\n *\n * \\param p     The position in the ASN.1 data\n * \\param end   End of data\n * \\param alg   The buffer to receive the OID\n * \\param params The buffer to receive the params (if any)\n *\n * \\return      0 if successful or a specific ASN.1 or MPI error code.\n */\nint mbedtls_asn1_get_alg( unsigned char **p,\n                  const unsigned char *end,\n                  mbedtls_asn1_buf *alg, mbedtls_asn1_buf *params );\n\n/**\n * \\brief       Retrieve an AlgorithmIdentifier ASN.1 sequence with NULL or no\n *              params.\n *              Updates the pointer to immediately behind the full\n *              AlgorithmIdentifier.\n *\n * \\param p     The position in the ASN.1 data\n * \\param end   End of data\n * \\param alg   The buffer to receive the OID\n *\n * \\return      0 if successful or a specific ASN.1 or MPI error code.\n */\nint mbedtls_asn1_get_alg_null( unsigned char **p,\n                       const unsigned char *end,\n                       mbedtls_asn1_buf *alg );\n\n/**\n * \\brief       Find a specific named_data entry in a sequence or list based on\n *              the OID.\n *\n * \\param list  The list to seek through\n * \\param oid   The OID to look for\n * \\param len   Size of the OID\n *\n * \\return      NULL if not found, or a pointer to the existing entry.\n */\nmbedtls_asn1_named_data *mbedtls_asn1_find_named_data( mbedtls_asn1_named_data *list,\n                                       const char *oid, size_t len );\n\n/**\n * \\brief       Free a mbedtls_asn1_named_data entry\n *\n * \\param entry The named data entry to free\n */\nvoid mbedtls_asn1_free_named_data( mbedtls_asn1_named_data *entry );\n\n/**\n * \\brief       Free all entries in a mbedtls_asn1_named_data list\n *              Head will be set to NULL\n *\n * \\param head  Pointer to the head of the list of named data entries to free\n */\nvoid mbedtls_asn1_free_named_data_list( mbedtls_asn1_named_data **head );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* asn1.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/asn1write.h",
    "content": "/**\n * \\file asn1write.h\n *\n * \\brief ASN.1 buffer writing functionality\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_ASN1_WRITE_H\n#define MBEDTLS_ASN1_WRITE_H\n\n#include \"asn1.h\"\n\n#define MBEDTLS_ASN1_CHK_ADD(g, f) do { if( ( ret = f ) < 0 ) return( ret ); else   \\\n                                g += ret; } while( 0 )\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief           Write a length field in ASN.1 format\n *                  Note: function works backwards in data buffer\n *\n * \\param p         reference to current position pointer\n * \\param start     start of the buffer (for bounds-checking)\n * \\param len       the length to write\n *\n * \\return          the length written or a negative error code\n */\nint mbedtls_asn1_write_len( unsigned char **p, unsigned char *start, size_t len );\n\n/**\n * \\brief           Write a ASN.1 tag in ASN.1 format\n *                  Note: function works backwards in data buffer\n *\n * \\param p         reference to current position pointer\n * \\param start     start of the buffer (for bounds-checking)\n * \\param tag       the tag to write\n *\n * \\return          the length written or a negative error code\n */\nint mbedtls_asn1_write_tag( unsigned char **p, unsigned char *start,\n                    unsigned char tag );\n\n/**\n * \\brief           Write raw buffer data\n *                  Note: function works backwards in data buffer\n *\n * \\param p         reference to current position pointer\n * \\param start     start of the buffer (for bounds-checking)\n * \\param buf       data buffer to write\n * \\param size      length of the data buffer\n *\n * \\return          the length written or a negative error code\n */\nint mbedtls_asn1_write_raw_buffer( unsigned char **p, unsigned char *start,\n                           const unsigned char *buf, size_t size );\n\n#if defined(MBEDTLS_BIGNUM_C)\n/**\n * \\brief           Write a big number (MBEDTLS_ASN1_INTEGER) in ASN.1 format\n *                  Note: function works backwards in data buffer\n *\n * \\param p         reference to current position pointer\n * \\param start     start of the buffer (for bounds-checking)\n * \\param X         the MPI to write\n *\n * \\return          the length written or a negative error code\n */\nint mbedtls_asn1_write_mpi( unsigned char **p, unsigned char *start, const mbedtls_mpi *X );\n#endif /* MBEDTLS_BIGNUM_C */\n\n/**\n * \\brief           Write a NULL tag (MBEDTLS_ASN1_NULL) with zero data in ASN.1 format\n *                  Note: function works backwards in data buffer\n *\n * \\param p         reference to current position pointer\n * \\param start     start of the buffer (for bounds-checking)\n *\n * \\return          the length written or a negative error code\n */\nint mbedtls_asn1_write_null( unsigned char **p, unsigned char *start );\n\n/**\n * \\brief           Write an OID tag (MBEDTLS_ASN1_OID) and data in ASN.1 format\n *                  Note: function works backwards in data buffer\n *\n * \\param p         reference to current position pointer\n * \\param start     start of the buffer (for bounds-checking)\n * \\param oid       the OID to write\n * \\param oid_len   length of the OID\n *\n * \\return          the length written or a negative error code\n */\nint mbedtls_asn1_write_oid( unsigned char **p, unsigned char *start,\n                    const char *oid, size_t oid_len );\n\n/**\n * \\brief           Write an AlgorithmIdentifier sequence in ASN.1 format\n *                  Note: function works backwards in data buffer\n *\n * \\param p         reference to current position pointer\n * \\param start     start of the buffer (for bounds-checking)\n * \\param oid       the OID of the algorithm\n * \\param oid_len   length of the OID\n * \\param par_len   length of parameters, which must be already written.\n *                  If 0, NULL parameters are added\n *\n * \\return          the length written or a negative error code\n */\nint mbedtls_asn1_write_algorithm_identifier( unsigned char **p, unsigned char *start,\n                                     const char *oid, size_t oid_len,\n                                     size_t par_len );\n\n/**\n * \\brief           Write a boolean tag (MBEDTLS_ASN1_BOOLEAN) and value in ASN.1 format\n *                  Note: function works backwards in data buffer\n *\n * \\param p         reference to current position pointer\n * \\param start     start of the buffer (for bounds-checking)\n * \\param boolean   0 or 1\n *\n * \\return          the length written or a negative error code\n */\nint mbedtls_asn1_write_bool( unsigned char **p, unsigned char *start, int boolean );\n\n/**\n * \\brief           Write an int tag (MBEDTLS_ASN1_INTEGER) and value in ASN.1 format\n *                  Note: function works backwards in data buffer\n *\n * \\param p         reference to current position pointer\n * \\param start     start of the buffer (for bounds-checking)\n * \\param val       the integer value\n *\n * \\return          the length written or a negative error code\n */\nint mbedtls_asn1_write_int( unsigned char **p, unsigned char *start, int val );\n\n/**\n * \\brief           Write a printable string tag (MBEDTLS_ASN1_PRINTABLE_STRING) and\n *                  value in ASN.1 format\n *                  Note: function works backwards in data buffer\n *\n * \\param p         reference to current position pointer\n * \\param start     start of the buffer (for bounds-checking)\n * \\param text      the text to write\n * \\param text_len  length of the text\n *\n * \\return          the length written or a negative error code\n */\nint mbedtls_asn1_write_printable_string( unsigned char **p, unsigned char *start,\n                                 const char *text, size_t text_len );\n\n/**\n * \\brief           Write an IA5 string tag (MBEDTLS_ASN1_IA5_STRING) and\n *                  value in ASN.1 format\n *                  Note: function works backwards in data buffer\n *\n * \\param p         reference to current position pointer\n * \\param start     start of the buffer (for bounds-checking)\n * \\param text      the text to write\n * \\param text_len  length of the text\n *\n * \\return          the length written or a negative error code\n */\nint mbedtls_asn1_write_ia5_string( unsigned char **p, unsigned char *start,\n                           const char *text, size_t text_len );\n\n/**\n * \\brief           Write a bitstring tag (MBEDTLS_ASN1_BIT_STRING) and\n *                  value in ASN.1 format\n *                  Note: function works backwards in data buffer\n *\n * \\param p         reference to current position pointer\n * \\param start     start of the buffer (for bounds-checking)\n * \\param buf       the bitstring\n * \\param bits      the total number of bits in the bitstring\n *\n * \\return          the length written or a negative error code\n */\nint mbedtls_asn1_write_bitstring( unsigned char **p, unsigned char *start,\n                          const unsigned char *buf, size_t bits );\n\n/**\n * \\brief           Write an octet string tag (MBEDTLS_ASN1_OCTET_STRING) and\n *                  value in ASN.1 format\n *                  Note: function works backwards in data buffer\n *\n * \\param p         reference to current position pointer\n * \\param start     start of the buffer (for bounds-checking)\n * \\param buf       data buffer to write\n * \\param size      length of the data buffer\n *\n * \\return          the length written or a negative error code\n */\nint mbedtls_asn1_write_octet_string( unsigned char **p, unsigned char *start,\n                             const unsigned char *buf, size_t size );\n\n/**\n * \\brief           Create or find a specific named_data entry for writing in a\n *                  sequence or list based on the OID. If not already in there,\n *                  a new entry is added to the head of the list.\n *                  Warning: Destructive behaviour for the val data!\n *\n * \\param list      Pointer to the location of the head of the list to seek\n *                  through (will be updated in case of a new entry)\n * \\param oid       The OID to look for\n * \\param oid_len   Size of the OID\n * \\param val       Data to store (can be NULL if you want to fill it by hand)\n * \\param val_len   Minimum length of the data buffer needed\n *\n * \\return      NULL if if there was a memory allocation error, or a pointer\n *              to the new / existing entry.\n */\nmbedtls_asn1_named_data *mbedtls_asn1_store_named_data( mbedtls_asn1_named_data **list,\n                                        const char *oid, size_t oid_len,\n                                        const unsigned char *val,\n                                        size_t val_len );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* MBEDTLS_ASN1_WRITE_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/base64.h",
    "content": "/**\n * \\file base64.h\n *\n * \\brief RFC 1521 base64 encoding/decoding\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_BASE64_H\n#define MBEDTLS_BASE64_H\n\n#include <stddef.h>\n\n#define MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL               -0x002A  /**< Output buffer too small. */\n#define MBEDTLS_ERR_BASE64_INVALID_CHARACTER              -0x002C  /**< Invalid character in input. */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief          Encode a buffer into base64 format\n *\n * \\param dst      destination buffer\n * \\param dlen     size of the destination buffer\n * \\param olen     number of bytes written\n * \\param src      source buffer\n * \\param slen     amount of data to be encoded\n *\n * \\return         0 if successful, or MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL.\n *                 *olen is always updated to reflect the amount\n *                 of data that has (or would have) been written.\n *                 If that length cannot be represented, then no data is\n *                 written to the buffer and *olen is set to the maximum\n *                 length representable as a size_t.\n *\n * \\note           Call this function with dlen = 0 to obtain the\n *                 required buffer size in *olen\n */\nint mbedtls_base64_encode( unsigned char *dst, size_t dlen, size_t *olen,\n                   const unsigned char *src, size_t slen );\n\n/**\n * \\brief          Decode a base64-formatted buffer\n *\n * \\param dst      destination buffer (can be NULL for checking size)\n * \\param dlen     size of the destination buffer\n * \\param olen     number of bytes written\n * \\param src      source buffer\n * \\param slen     amount of data to be decoded\n *\n * \\return         0 if successful, MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL, or\n *                 MBEDTLS_ERR_BASE64_INVALID_CHARACTER if the input data is\n *                 not correct. *olen is always updated to reflect the amount\n *                 of data that has (or would have) been written.\n *\n * \\note           Call this function with *dst = NULL or dlen = 0 to obtain\n *                 the required buffer size in *olen\n */\nint mbedtls_base64_decode( unsigned char *dst, size_t dlen, size_t *olen,\n                   const unsigned char *src, size_t slen );\n\n/**\n * \\brief          Checkup routine\n *\n * \\return         0 if successful, or 1 if the test failed\n */\nint mbedtls_base64_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* base64.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/bignum.h",
    "content": "/**\n * \\file bignum.h\n *\n * \\brief Multi-precision integer library\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_BIGNUM_H\n#define MBEDTLS_BIGNUM_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n#include <stdint.h>\n\n#if defined(MBEDTLS_FS_IO)\n#include <stdio.h>\n#endif\n\n#define MBEDTLS_ERR_MPI_FILE_IO_ERROR                     -0x0002  /**< An error occurred while reading from or writing to a file. */\n#define MBEDTLS_ERR_MPI_BAD_INPUT_DATA                    -0x0004  /**< Bad input parameters to function. */\n#define MBEDTLS_ERR_MPI_INVALID_CHARACTER                 -0x0006  /**< There is an invalid character in the digit string. */\n#define MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL                  -0x0008  /**< The buffer is too small to write to. */\n#define MBEDTLS_ERR_MPI_NEGATIVE_VALUE                    -0x000A  /**< The input arguments are negative or result in illegal output. */\n#define MBEDTLS_ERR_MPI_DIVISION_BY_ZERO                  -0x000C  /**< The input argument for division is zero, which is not allowed. */\n#define MBEDTLS_ERR_MPI_NOT_ACCEPTABLE                    -0x000E  /**< The input arguments are not acceptable. */\n#define MBEDTLS_ERR_MPI_ALLOC_FAILED                      -0x0010  /**< Memory allocation failed. */\n\n#define MBEDTLS_MPI_CHK(f) do { if( ( ret = f ) != 0 ) goto cleanup; } while( 0 )\n\n/*\n * Maximum size MPIs are allowed to grow to in number of limbs.\n */\n#define MBEDTLS_MPI_MAX_LIMBS                             10000\n\n#if !defined(MBEDTLS_MPI_WINDOW_SIZE)\n/*\n * Maximum window size used for modular exponentiation. Default: 6\n * Minimum value: 1. Maximum value: 6.\n *\n * Result is an array of ( 2 << MBEDTLS_MPI_WINDOW_SIZE ) MPIs used\n * for the sliding window calculation. (So 64 by default)\n *\n * Reduction in size, reduces speed.\n */\n#define MBEDTLS_MPI_WINDOW_SIZE                           6        /**< Maximum windows size used. */\n#endif /* !MBEDTLS_MPI_WINDOW_SIZE */\n\n#if !defined(MBEDTLS_MPI_MAX_SIZE)\n/*\n * Maximum size of MPIs allowed in bits and bytes for user-MPIs.\n * ( Default: 512 bytes => 4096 bits, Maximum tested: 2048 bytes => 16384 bits )\n *\n * Note: Calculations can temporarily result in larger MPIs. So the number\n * of limbs required (MBEDTLS_MPI_MAX_LIMBS) is higher.\n */\n#define MBEDTLS_MPI_MAX_SIZE                              1024     /**< Maximum number of bytes for usable MPIs. */\n#endif /* !MBEDTLS_MPI_MAX_SIZE */\n\n#define MBEDTLS_MPI_MAX_BITS                              ( 8 * MBEDTLS_MPI_MAX_SIZE )    /**< Maximum number of bits for usable MPIs. */\n\n/*\n * When reading from files with mbedtls_mpi_read_file() and writing to files with\n * mbedtls_mpi_write_file() the buffer should have space\n * for a (short) label, the MPI (in the provided radix), the newline\n * characters and the '\\0'.\n *\n * By default we assume at least a 10 char label, a minimum radix of 10\n * (decimal) and a maximum of 4096 bit numbers (1234 decimal chars).\n * Autosized at compile time for at least a 10 char label, a minimum radix\n * of 10 (decimal) for a number of MBEDTLS_MPI_MAX_BITS size.\n *\n * This used to be statically sized to 1250 for a maximum of 4096 bit\n * numbers (1234 decimal chars).\n *\n * Calculate using the formula:\n *  MBEDTLS_MPI_RW_BUFFER_SIZE = ceil(MBEDTLS_MPI_MAX_BITS / ln(10) * ln(2)) +\n *                                LabelSize + 6\n */\n#define MBEDTLS_MPI_MAX_BITS_SCALE100          ( 100 * MBEDTLS_MPI_MAX_BITS )\n#define MBEDTLS_LN_2_DIV_LN_10_SCALE100                 332\n#define MBEDTLS_MPI_RW_BUFFER_SIZE             ( ((MBEDTLS_MPI_MAX_BITS_SCALE100 + MBEDTLS_LN_2_DIV_LN_10_SCALE100 - 1) / MBEDTLS_LN_2_DIV_LN_10_SCALE100) + 10 + 6 )\n\n/*\n * Define the base integer type, architecture-wise.\n *\n * 32 or 64-bit integer types can be forced regardless of the underlying\n * architecture by defining MBEDTLS_HAVE_INT32 or MBEDTLS_HAVE_INT64\n * respectively and undefining MBEDTLS_HAVE_ASM.\n *\n * Double-width integers (e.g. 128-bit in 64-bit architectures) can be\n * disabled by defining MBEDTLS_NO_UDBL_DIVISION.\n */\n#if !defined(MBEDTLS_HAVE_INT32)\n    #if defined(_MSC_VER) && defined(_M_AMD64)\n        /* Always choose 64-bit when using MSC */\n        #if !defined(MBEDTLS_HAVE_INT64)\n            #define MBEDTLS_HAVE_INT64\n        #endif /* !MBEDTLS_HAVE_INT64 */\n        typedef  int64_t mbedtls_mpi_sint;\n        typedef uint64_t mbedtls_mpi_uint;\n    #elif defined(__GNUC__) && (                         \\\n        defined(__amd64__) || defined(__x86_64__)     || \\\n        defined(__ppc64__) || defined(__powerpc64__)  || \\\n        defined(__ia64__)  || defined(__alpha__)      || \\\n        ( defined(__sparc__) && defined(__arch64__) ) || \\\n        defined(__s390x__) || defined(__mips64) )\n        #if !defined(MBEDTLS_HAVE_INT64)\n            #define MBEDTLS_HAVE_INT64\n        #endif /* MBEDTLS_HAVE_INT64 */\n        typedef  int64_t mbedtls_mpi_sint;\n        typedef uint64_t mbedtls_mpi_uint;\n        #if !defined(MBEDTLS_NO_UDBL_DIVISION)\n            /* mbedtls_t_udbl defined as 128-bit unsigned int */\n            typedef unsigned int mbedtls_t_udbl __attribute__((mode(TI)));\n            #define MBEDTLS_HAVE_UDBL\n        #endif /* !MBEDTLS_NO_UDBL_DIVISION */\n    #elif defined(__ARMCC_VERSION) && defined(__aarch64__)\n        /*\n         * __ARMCC_VERSION is defined for both armcc and armclang and\n         * __aarch64__ is only defined by armclang when compiling 64-bit code\n         */\n        #if !defined(MBEDTLS_HAVE_INT64)\n            #define MBEDTLS_HAVE_INT64\n        #endif /* !MBEDTLS_HAVE_INT64 */\n        typedef  int64_t mbedtls_mpi_sint;\n        typedef uint64_t mbedtls_mpi_uint;\n        #if !defined(MBEDTLS_NO_UDBL_DIVISION)\n            /* mbedtls_t_udbl defined as 128-bit unsigned int */\n            typedef __uint128_t mbedtls_t_udbl;\n            #define MBEDTLS_HAVE_UDBL\n        #endif /* !MBEDTLS_NO_UDBL_DIVISION */\n    #elif defined(MBEDTLS_HAVE_INT64)\n        /* Force 64-bit integers with unknown compiler */\n        typedef  int64_t mbedtls_mpi_sint;\n        typedef uint64_t mbedtls_mpi_uint;\n    #endif\n#endif /* !MBEDTLS_HAVE_INT32 */\n\n#if !defined(MBEDTLS_HAVE_INT64)\n    /* Default to 32-bit compilation */\n    #if !defined(MBEDTLS_HAVE_INT32)\n        #define MBEDTLS_HAVE_INT32\n    #endif /* !MBEDTLS_HAVE_INT32 */\n    typedef  int32_t mbedtls_mpi_sint;\n    typedef uint32_t mbedtls_mpi_uint;\n    #if !defined(MBEDTLS_NO_UDBL_DIVISION)\n        typedef uint64_t mbedtls_t_udbl;\n        #define MBEDTLS_HAVE_UDBL\n    #endif /* !MBEDTLS_NO_UDBL_DIVISION */\n#endif /* !MBEDTLS_HAVE_INT64 */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief          MPI structure\n */\ntypedef struct\n{\n    int s;              /*!<  integer sign      */\n    size_t n;           /*!<  total # of limbs  */\n    mbedtls_mpi_uint *p;          /*!<  pointer to limbs  */\n}\nmbedtls_mpi;\n\n/**\n * \\brief           Initialize one MPI (make internal references valid)\n *                  This just makes it ready to be set or freed,\n *                  but does not define a value for the MPI.\n *\n * \\param X         One MPI to initialize.\n */\nvoid mbedtls_mpi_init( mbedtls_mpi *X );\n\n/**\n * \\brief          Unallocate one MPI\n *\n * \\param X        One MPI to unallocate.\n */\nvoid mbedtls_mpi_free( mbedtls_mpi *X );\n\n/**\n * \\brief          Enlarge to the specified number of limbs\n *\n *                 This function does nothing if the MPI is already large enough.\n *\n * \\param X        MPI to grow\n * \\param nblimbs  The target number of limbs\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed\n */\nint mbedtls_mpi_grow( mbedtls_mpi *X, size_t nblimbs );\n\n/**\n * \\brief          Resize down, keeping at least the specified number of limbs\n *\n *                 If \\c X is smaller than \\c nblimbs, it is resized up\n *                 instead.\n *\n * \\param X        MPI to shrink\n * \\param nblimbs  The minimum number of limbs to keep\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed\n *                 (this can only happen when resizing up).\n */\nint mbedtls_mpi_shrink( mbedtls_mpi *X, size_t nblimbs );\n\n/**\n * \\brief          Copy the contents of Y into X\n *\n * \\param X        Destination MPI. It is enlarged if necessary.\n * \\param Y        Source MPI.\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed\n */\nint mbedtls_mpi_copy( mbedtls_mpi *X, const mbedtls_mpi *Y );\n\n/**\n * \\brief          Swap the contents of X and Y\n *\n * \\param X        First MPI value\n * \\param Y        Second MPI value\n */\nvoid mbedtls_mpi_swap( mbedtls_mpi *X, mbedtls_mpi *Y );\n\n/**\n * \\brief          Safe conditional assignement X = Y if assign is 1\n *\n * \\param X        MPI to conditionally assign to\n * \\param Y        Value to be assigned\n * \\param assign   1: perform the assignment, 0: keep X's original value\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed,\n *\n * \\note           This function is equivalent to\n *                      if( assign ) mbedtls_mpi_copy( X, Y );\n *                 except that it avoids leaking any information about whether\n *                 the assignment was done or not (the above code may leak\n *                 information through branch prediction and/or memory access\n *                 patterns analysis).\n */\nint mbedtls_mpi_safe_cond_assign( mbedtls_mpi *X, const mbedtls_mpi *Y, unsigned char assign );\n\n/**\n * \\brief          Safe conditional swap X <-> Y if swap is 1\n *\n * \\param X        First mbedtls_mpi value\n * \\param Y        Second mbedtls_mpi value\n * \\param assign   1: perform the swap, 0: keep X and Y's original values\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed,\n *\n * \\note           This function is equivalent to\n *                      if( assign ) mbedtls_mpi_swap( X, Y );\n *                 except that it avoids leaking any information about whether\n *                 the assignment was done or not (the above code may leak\n *                 information through branch prediction and/or memory access\n *                 patterns analysis).\n */\nint mbedtls_mpi_safe_cond_swap( mbedtls_mpi *X, mbedtls_mpi *Y, unsigned char assign );\n\n/**\n * \\brief          Set value from integer\n *\n * \\param X        MPI to set\n * \\param z        Value to use\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed\n */\nint mbedtls_mpi_lset( mbedtls_mpi *X, mbedtls_mpi_sint z );\n\n/**\n * \\brief          Get a specific bit from X\n *\n * \\param X        MPI to use\n * \\param pos      Zero-based index of the bit in X\n *\n * \\return         Either a 0 or a 1\n */\nint mbedtls_mpi_get_bit( const mbedtls_mpi *X, size_t pos );\n\n/**\n * \\brief          Set a bit of X to a specific value of 0 or 1\n *\n * \\note           Will grow X if necessary to set a bit to 1 in a not yet\n *                 existing limb. Will not grow if bit should be set to 0\n *\n * \\param X        MPI to use\n * \\param pos      Zero-based index of the bit in X\n * \\param val      The value to set the bit to (0 or 1)\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed,\n *                 MBEDTLS_ERR_MPI_BAD_INPUT_DATA if val is not 0 or 1\n */\nint mbedtls_mpi_set_bit( mbedtls_mpi *X, size_t pos, unsigned char val );\n\n/**\n * \\brief          Return the number of zero-bits before the least significant\n *                 '1' bit\n *\n * Note: Thus also the zero-based index of the least significant '1' bit\n *\n * \\param X        MPI to use\n */\nsize_t mbedtls_mpi_lsb( const mbedtls_mpi *X );\n\n/**\n * \\brief          Return the number of bits up to and including the most\n *                 significant '1' bit'\n *\n * Note: Thus also the one-based index of the most significant '1' bit\n *\n * \\param X        MPI to use\n */\nsize_t mbedtls_mpi_bitlen( const mbedtls_mpi *X );\n\n/**\n * \\brief          Return the total size in bytes\n *\n * \\param X        MPI to use\n */\nsize_t mbedtls_mpi_size( const mbedtls_mpi *X );\n\n/**\n * \\brief          Import from an ASCII string\n *\n * \\param X        Destination MPI\n * \\param radix    Input numeric base\n * \\param s        Null-terminated string buffer\n *\n * \\return         0 if successful, or a MBEDTLS_ERR_MPI_XXX error code\n */\nint mbedtls_mpi_read_string( mbedtls_mpi *X, int radix, const char *s );\n\n/**\n * \\brief          Export into an ASCII string\n *\n * \\param X        Source MPI\n * \\param radix    Output numeric base\n * \\param buf      Buffer to write the string to\n * \\param buflen   Length of buf\n * \\param olen     Length of the string written, including final NUL byte\n *\n * \\return         0 if successful, or a MBEDTLS_ERR_MPI_XXX error code.\n *                 *olen is always updated to reflect the amount\n *                 of data that has (or would have) been written.\n *\n * \\note           Call this function with buflen = 0 to obtain the\n *                 minimum required buffer size in *olen.\n */\nint mbedtls_mpi_write_string( const mbedtls_mpi *X, int radix,\n                              char *buf, size_t buflen, size_t *olen );\n\n#if defined(MBEDTLS_FS_IO)\n/**\n * \\brief          Read MPI from a line in an opened file\n *\n * \\param X        Destination MPI\n * \\param radix    Input numeric base\n * \\param fin      Input file handle\n *\n * \\return         0 if successful, MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if\n *                 the file read buffer is too small or a\n *                 MBEDTLS_ERR_MPI_XXX error code\n *\n * \\note           On success, this function advances the file stream\n *                 to the end of the current line or to EOF.\n *\n *                 The function returns 0 on an empty line.\n *\n *                 Leading whitespaces are ignored, as is a\n *                 '0x' prefix for radix 16.\n *\n */\nint mbedtls_mpi_read_file( mbedtls_mpi *X, int radix, FILE *fin );\n\n/**\n * \\brief          Write X into an opened file, or stdout if fout is NULL\n *\n * \\param p        Prefix, can be NULL\n * \\param X        Source MPI\n * \\param radix    Output numeric base\n * \\param fout     Output file handle (can be NULL)\n *\n * \\return         0 if successful, or a MBEDTLS_ERR_MPI_XXX error code\n *\n * \\note           Set fout == NULL to print X on the console.\n */\nint mbedtls_mpi_write_file( const char *p, const mbedtls_mpi *X, int radix, FILE *fout );\n#endif /* MBEDTLS_FS_IO */\n\n/**\n * \\brief          Import X from unsigned binary data, big endian\n *\n * \\param X        Destination MPI\n * \\param buf      Input buffer\n * \\param buflen   Input buffer size\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed\n */\nint mbedtls_mpi_read_binary( mbedtls_mpi *X, const unsigned char *buf, size_t buflen );\n\n/**\n * \\brief          Export X into unsigned binary data, big endian.\n *                 Always fills the whole buffer, which will start with zeros\n *                 if the number is smaller.\n *\n * \\param X        Source MPI\n * \\param buf      Output buffer\n * \\param buflen   Output buffer size\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if buf isn't large enough\n */\nint mbedtls_mpi_write_binary( const mbedtls_mpi *X, unsigned char *buf, size_t buflen );\n\n/**\n * \\brief          Left-shift: X <<= count\n *\n * \\param X        MPI to shift\n * \\param count    Amount to shift\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed\n */\nint mbedtls_mpi_shift_l( mbedtls_mpi *X, size_t count );\n\n/**\n * \\brief          Right-shift: X >>= count\n *\n * \\param X        MPI to shift\n * \\param count    Amount to shift\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed\n */\nint mbedtls_mpi_shift_r( mbedtls_mpi *X, size_t count );\n\n/**\n * \\brief          Compare unsigned values\n *\n * \\param X        Left-hand MPI\n * \\param Y        Right-hand MPI\n *\n * \\return         1 if |X| is greater than |Y|,\n *                -1 if |X| is lesser  than |Y| or\n *                 0 if |X| is equal to |Y|\n */\nint mbedtls_mpi_cmp_abs( const mbedtls_mpi *X, const mbedtls_mpi *Y );\n\n/**\n * \\brief          Compare signed values\n *\n * \\param X        Left-hand MPI\n * \\param Y        Right-hand MPI\n *\n * \\return         1 if X is greater than Y,\n *                -1 if X is lesser  than Y or\n *                 0 if X is equal to Y\n */\nint mbedtls_mpi_cmp_mpi( const mbedtls_mpi *X, const mbedtls_mpi *Y );\n\n/**\n * \\brief          Compare signed values\n *\n * \\param X        Left-hand MPI\n * \\param z        The integer value to compare to\n *\n * \\return         1 if X is greater than z,\n *                -1 if X is lesser  than z or\n *                 0 if X is equal to z\n */\nint mbedtls_mpi_cmp_int( const mbedtls_mpi *X, mbedtls_mpi_sint z );\n\n/**\n * \\brief          Unsigned addition: X = |A| + |B|\n *\n * \\param X        Destination MPI\n * \\param A        Left-hand MPI\n * \\param B        Right-hand MPI\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed\n */\nint mbedtls_mpi_add_abs( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B );\n\n/**\n * \\brief          Unsigned subtraction: X = |A| - |B|\n *\n * \\param X        Destination MPI\n * \\param A        Left-hand MPI\n * \\param B        Right-hand MPI\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_NEGATIVE_VALUE if B is greater than A\n */\nint mbedtls_mpi_sub_abs( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B );\n\n/**\n * \\brief          Signed addition: X = A + B\n *\n * \\param X        Destination MPI\n * \\param A        Left-hand MPI\n * \\param B        Right-hand MPI\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed\n */\nint mbedtls_mpi_add_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B );\n\n/**\n * \\brief          Signed subtraction: X = A - B\n *\n * \\param X        Destination MPI\n * \\param A        Left-hand MPI\n * \\param B        Right-hand MPI\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed\n */\nint mbedtls_mpi_sub_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B );\n\n/**\n * \\brief          Signed addition: X = A + b\n *\n * \\param X        Destination MPI\n * \\param A        Left-hand MPI\n * \\param b        The integer value to add\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed\n */\nint mbedtls_mpi_add_int( mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_sint b );\n\n/**\n * \\brief          Signed subtraction: X = A - b\n *\n * \\param X        Destination MPI\n * \\param A        Left-hand MPI\n * \\param b        The integer value to subtract\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed\n */\nint mbedtls_mpi_sub_int( mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_sint b );\n\n/**\n * \\brief          Baseline multiplication: X = A * B\n *\n * \\param X        Destination MPI\n * \\param A        Left-hand MPI\n * \\param B        Right-hand MPI\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed\n */\nint mbedtls_mpi_mul_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B );\n\n/**\n * \\brief          Baseline multiplication: X = A * b\n *\n * \\param X        Destination MPI\n * \\param A        Left-hand MPI\n * \\param b        The unsigned integer value to multiply with\n *\n * \\note           b is unsigned\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed\n */\nint mbedtls_mpi_mul_int( mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_uint b );\n\n/**\n * \\brief          Division by mbedtls_mpi: A = Q * B + R\n *\n * \\param Q        Destination MPI for the quotient\n * \\param R        Destination MPI for the rest value\n * \\param A        Left-hand MPI\n * \\param B        Right-hand MPI\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed,\n *                 MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if B == 0\n *\n * \\note           Either Q or R can be NULL.\n */\nint mbedtls_mpi_div_mpi( mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A, const mbedtls_mpi *B );\n\n/**\n * \\brief          Division by int: A = Q * b + R\n *\n * \\param Q        Destination MPI for the quotient\n * \\param R        Destination MPI for the rest value\n * \\param A        Left-hand MPI\n * \\param b        Integer to divide by\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed,\n *                 MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if b == 0\n *\n * \\note           Either Q or R can be NULL.\n */\nint mbedtls_mpi_div_int( mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A, mbedtls_mpi_sint b );\n\n/**\n * \\brief          Modulo: R = A mod B\n *\n * \\param R        Destination MPI for the rest value\n * \\param A        Left-hand MPI\n * \\param B        Right-hand MPI\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed,\n *                 MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if B == 0,\n *                 MBEDTLS_ERR_MPI_NEGATIVE_VALUE if B < 0\n */\nint mbedtls_mpi_mod_mpi( mbedtls_mpi *R, const mbedtls_mpi *A, const mbedtls_mpi *B );\n\n/**\n * \\brief          Modulo: r = A mod b\n *\n * \\param r        Destination mbedtls_mpi_uint\n * \\param A        Left-hand MPI\n * \\param b        Integer to divide by\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed,\n *                 MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if b == 0,\n *                 MBEDTLS_ERR_MPI_NEGATIVE_VALUE if b < 0\n */\nint mbedtls_mpi_mod_int( mbedtls_mpi_uint *r, const mbedtls_mpi *A, mbedtls_mpi_sint b );\n\n/**\n * \\brief          Sliding-window exponentiation: X = A^E mod N\n *\n * \\param X        Destination MPI\n * \\param A        Left-hand MPI\n * \\param E        Exponent MPI\n * \\param N        Modular MPI\n * \\param _RR      Speed-up MPI used for recalculations\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed,\n *                 MBEDTLS_ERR_MPI_BAD_INPUT_DATA if N is negative or even or\n *                 if E is negative\n *\n * \\note           _RR is used to avoid re-computing R*R mod N across\n *                 multiple calls, which speeds up things a bit. It can\n *                 be set to NULL if the extra performance is unneeded.\n */\nint mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *E, const mbedtls_mpi *N, mbedtls_mpi *_RR );\n\n/**\n * \\brief          Fill an MPI X with size bytes of random\n *\n * \\param X        Destination MPI\n * \\param size     Size in bytes\n * \\param f_rng    RNG function\n * \\param p_rng    RNG parameter\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed\n *\n * \\note           The bytes obtained from the PRNG are interpreted\n *                 as a big-endian representation of an MPI; this can\n *                 be relevant in applications like deterministic ECDSA.\n */\nint mbedtls_mpi_fill_random( mbedtls_mpi *X, size_t size,\n                     int (*f_rng)(void *, unsigned char *, size_t),\n                     void *p_rng );\n\n/**\n * \\brief          Greatest common divisor: G = gcd(A, B)\n *\n * \\param G        Destination MPI\n * \\param A        Left-hand MPI\n * \\param B        Right-hand MPI\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed\n */\nint mbedtls_mpi_gcd( mbedtls_mpi *G, const mbedtls_mpi *A, const mbedtls_mpi *B );\n\n/**\n * \\brief          Modular inverse: X = A^-1 mod N\n *\n * \\param X        Destination MPI\n * \\param A        Left-hand MPI\n * \\param N        Right-hand MPI\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed,\n *                 MBEDTLS_ERR_MPI_BAD_INPUT_DATA if N is <= 1,\n                   MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if A has no inverse mod N.\n */\nint mbedtls_mpi_inv_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *N );\n\n/**\n * \\brief          Miller-Rabin primality test\n *\n * \\param X        MPI to check\n * \\param f_rng    RNG function\n * \\param p_rng    RNG parameter\n *\n * \\return         0 if successful (probably prime),\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed,\n *                 MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if X is not prime\n */\nint mbedtls_mpi_is_prime( const mbedtls_mpi *X,\n                  int (*f_rng)(void *, unsigned char *, size_t),\n                  void *p_rng );\n\n/**\n * \\brief          Prime number generation\n *\n * \\param X        Destination MPI\n * \\param nbits    Required size of X in bits\n *                 ( 3 <= nbits <= MBEDTLS_MPI_MAX_BITS )\n * \\param dh_flag  If 1, then (X-1)/2 will be prime too\n * \\param f_rng    RNG function\n * \\param p_rng    RNG parameter\n *\n * \\return         0 if successful (probably prime),\n *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed,\n *                 MBEDTLS_ERR_MPI_BAD_INPUT_DATA if nbits is < 3\n */\nint mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int dh_flag,\n                   int (*f_rng)(void *, unsigned char *, size_t),\n                   void *p_rng );\n\n/**\n * \\brief          Checkup routine\n *\n * \\return         0 if successful, or 1 if the test failed\n */\nint mbedtls_mpi_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* bignum.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/blowfish.h",
    "content": "/**\n * \\file blowfish.h\n *\n * \\brief Blowfish block cipher\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_BLOWFISH_H\n#define MBEDTLS_BLOWFISH_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n#include <stdint.h>\n\n#define MBEDTLS_BLOWFISH_ENCRYPT     1\n#define MBEDTLS_BLOWFISH_DECRYPT     0\n#define MBEDTLS_BLOWFISH_MAX_KEY_BITS     448\n#define MBEDTLS_BLOWFISH_MIN_KEY_BITS     32\n#define MBEDTLS_BLOWFISH_ROUNDS      16         /**< Rounds to use. When increasing this value, make sure to extend the initialisation vectors */\n#define MBEDTLS_BLOWFISH_BLOCKSIZE   8          /* Blowfish uses 64 bit blocks */\n\n#define MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH                -0x0016  /**< Invalid key length. */\n#define MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED                   -0x0017  /**< Blowfish hardware accelerator failed. */\n#define MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH              -0x0018  /**< Invalid data input length. */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_BLOWFISH_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief          Blowfish context structure\n */\ntypedef struct\n{\n    uint32_t P[MBEDTLS_BLOWFISH_ROUNDS + 2];    /*!<  Blowfish round keys    */\n    uint32_t S[4][256];                 /*!<  key dependent S-boxes  */\n}\nmbedtls_blowfish_context;\n\n#else  /* MBEDTLS_BLOWFISH_ALT */\n#include \"blowfish_alt.h\"\n#endif /* MBEDTLS_BLOWFISH_ALT */\n\n/**\n * \\brief          Initialize Blowfish context\n *\n * \\param ctx      Blowfish context to be initialized\n */\nvoid mbedtls_blowfish_init( mbedtls_blowfish_context *ctx );\n\n/**\n * \\brief          Clear Blowfish context\n *\n * \\param ctx      Blowfish context to be cleared\n */\nvoid mbedtls_blowfish_free( mbedtls_blowfish_context *ctx );\n\n/**\n * \\brief          Blowfish key schedule\n *\n * \\param ctx      Blowfish context to be initialized\n * \\param key      encryption key\n * \\param keybits  must be between 32 and 448 bits\n *\n * \\return         0 if successful, or MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH\n */\nint mbedtls_blowfish_setkey( mbedtls_blowfish_context *ctx, const unsigned char *key,\n                     unsigned int keybits );\n\n/**\n * \\brief          Blowfish-ECB block encryption/decryption\n *\n * \\param ctx      Blowfish context\n * \\param mode     MBEDTLS_BLOWFISH_ENCRYPT or MBEDTLS_BLOWFISH_DECRYPT\n * \\param input    8-byte input block\n * \\param output   8-byte output block\n *\n * \\return         0 if successful\n */\nint mbedtls_blowfish_crypt_ecb( mbedtls_blowfish_context *ctx,\n                        int mode,\n                        const unsigned char input[MBEDTLS_BLOWFISH_BLOCKSIZE],\n                        unsigned char output[MBEDTLS_BLOWFISH_BLOCKSIZE] );\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n/**\n * \\brief          Blowfish-CBC buffer encryption/decryption\n *                 Length should be a multiple of the block\n *                 size (8 bytes)\n *\n * \\note           Upon exit, the content of the IV is updated so that you can\n *                 call the function same function again on the following\n *                 block(s) of data and get the same result as if it was\n *                 encrypted in one call. This allows a \"streaming\" usage.\n *                 If on the other hand you need to retain the contents of the\n *                 IV, you should either save it manually or use the cipher\n *                 module instead.\n *\n * \\param ctx      Blowfish context\n * \\param mode     MBEDTLS_BLOWFISH_ENCRYPT or MBEDTLS_BLOWFISH_DECRYPT\n * \\param length   length of the input data\n * \\param iv       initialization vector (updated after use)\n * \\param input    buffer holding the input data\n * \\param output   buffer holding the output data\n *\n * \\return         0 if successful, or\n *                 MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH\n */\nint mbedtls_blowfish_crypt_cbc( mbedtls_blowfish_context *ctx,\n                        int mode,\n                        size_t length,\n                        unsigned char iv[MBEDTLS_BLOWFISH_BLOCKSIZE],\n                        const unsigned char *input,\n                        unsigned char *output );\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n/**\n * \\brief          Blowfish CFB buffer encryption/decryption.\n *\n * \\note           Upon exit, the content of the IV is updated so that you can\n *                 call the function same function again on the following\n *                 block(s) of data and get the same result as if it was\n *                 encrypted in one call. This allows a \"streaming\" usage.\n *                 If on the other hand you need to retain the contents of the\n *                 IV, you should either save it manually or use the cipher\n *                 module instead.\n *\n * \\param ctx      Blowfish context\n * \\param mode     MBEDTLS_BLOWFISH_ENCRYPT or MBEDTLS_BLOWFISH_DECRYPT\n * \\param length   length of the input data\n * \\param iv_off   offset in IV (updated after use)\n * \\param iv       initialization vector (updated after use)\n * \\param input    buffer holding the input data\n * \\param output   buffer holding the output data\n *\n * \\return         0 if successful\n */\nint mbedtls_blowfish_crypt_cfb64( mbedtls_blowfish_context *ctx,\n                          int mode,\n                          size_t length,\n                          size_t *iv_off,\n                          unsigned char iv[MBEDTLS_BLOWFISH_BLOCKSIZE],\n                          const unsigned char *input,\n                          unsigned char *output );\n#endif /*MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n/**\n * \\brief               Blowfish-CTR buffer encryption/decryption\n *\n * \\warning    You must never reuse a nonce value with the same key. Doing so\n *             would void the encryption for the two messages encrypted with\n *             the same nonce and key.\n *\n *             There are two common strategies for managing nonces with CTR:\n *\n *             1. You can handle everything as a single message processed over\n *             successive calls to this function. In that case, you want to\n *             set \\p nonce_counter and \\p nc_off to 0 for the first call, and\n *             then preserve the values of \\p nonce_counter, \\p nc_off and \\p\n *             stream_block across calls to this function as they will be\n *             updated by this function.\n *\n *             With this strategy, you must not encrypt more than 2**64\n *             blocks of data with the same key.\n *\n *             2. You can encrypt separate messages by dividing the \\p\n *             nonce_counter buffer in two areas: the first one used for a\n *             per-message nonce, handled by yourself, and the second one\n *             updated by this function internally.\n *\n *             For example, you might reserve the first 4 bytes for the\n *             per-message nonce, and the last 4 bytes for internal use. In that\n *             case, before calling this function on a new message you need to\n *             set the first 4 bytes of \\p nonce_counter to your chosen nonce\n *             value, the last 4 to 0, and \\p nc_off to 0 (which will cause \\p\n *             stream_block to be ignored). That way, you can encrypt at most\n *             2**32 messages of up to 2**32 blocks each with the same key.\n *\n *             The per-message nonce (or information sufficient to reconstruct\n *             it) needs to be communicated with the ciphertext and must be unique.\n *             The recommended way to ensure uniqueness is to use a message\n *             counter.\n *\n *             Note that for both stategies, sizes are measured in blocks and\n *             that a Blowfish block is 8 bytes.\n *\n * \\warning    Upon return, \\p stream_block contains sensitive data. Its\n *             content must not be written to insecure storage and should be\n *             securely discarded as soon as it's no longer needed.\n *\n * \\param ctx           Blowfish context\n * \\param length        The length of the data\n * \\param nc_off        The offset in the current stream_block (for resuming\n *                      within current cipher stream). The offset pointer to\n *                      should be 0 at the start of a stream.\n * \\param nonce_counter The 64-bit nonce and counter.\n * \\param stream_block  The saved stream-block for resuming. Is overwritten\n *                      by the function.\n * \\param input         The input data stream\n * \\param output        The output data stream\n *\n * \\return         0 if successful\n */\nint mbedtls_blowfish_crypt_ctr( mbedtls_blowfish_context *ctx,\n                        size_t length,\n                        size_t *nc_off,\n                        unsigned char nonce_counter[MBEDTLS_BLOWFISH_BLOCKSIZE],\n                        unsigned char stream_block[MBEDTLS_BLOWFISH_BLOCKSIZE],\n                        const unsigned char *input,\n                        unsigned char *output );\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* blowfish.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/bn_mul.h",
    "content": "/**\n * \\file bn_mul.h\n *\n * \\brief Multi-precision integer library\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *      Multiply source vector [s] with b, add result\n *       to destination vector [d] and set carry c.\n *\n *      Currently supports:\n *\n *         . IA-32 (386+)         . AMD64 / EM64T\n *         . IA-32 (SSE2)         . Motorola 68000\n *         . PowerPC, 32-bit      . MicroBlaze\n *         . PowerPC, 64-bit      . TriCore\n *         . SPARC v8             . ARM v3+\n *         . Alpha                . MIPS32\n *         . C, longlong          . C, generic\n */\n#ifndef MBEDTLS_BN_MUL_H\n#define MBEDTLS_BN_MUL_H\n\n#include \"bignum.h\"\n\n#if defined(MBEDTLS_HAVE_ASM)\n\n#ifndef asm\n#define asm __asm\n#endif\n\n/* armcc5 --gnu defines __GNUC__ but doesn't support GNU's extended asm */\n#if defined(__GNUC__) && \\\n    ( !defined(__ARMCC_VERSION) || __ARMCC_VERSION >= 6000000 )\n\n/*\n * Disable use of the i386 assembly code below if option -O0, to disable all\n * compiler optimisations, is passed, detected with __OPTIMIZE__\n * This is done as the number of registers used in the assembly code doesn't\n * work with the -O0 option.\n */\n#if defined(__i386__) && defined(__OPTIMIZE__)\n\n#define MULADDC_INIT                        \\\n    asm(                                    \\\n        \"movl   %%ebx, %0           \\n\\t\"   \\\n        \"movl   %5, %%esi           \\n\\t\"   \\\n        \"movl   %6, %%edi           \\n\\t\"   \\\n        \"movl   %7, %%ecx           \\n\\t\"   \\\n        \"movl   %8, %%ebx           \\n\\t\"\n\n#define MULADDC_CORE                        \\\n        \"lodsl                      \\n\\t\"   \\\n        \"mull   %%ebx               \\n\\t\"   \\\n        \"addl   %%ecx,   %%eax      \\n\\t\"   \\\n        \"adcl   $0,      %%edx      \\n\\t\"   \\\n        \"addl   (%%edi), %%eax      \\n\\t\"   \\\n        \"adcl   $0,      %%edx      \\n\\t\"   \\\n        \"movl   %%edx,   %%ecx      \\n\\t\"   \\\n        \"stosl                      \\n\\t\"\n\n#if defined(MBEDTLS_HAVE_SSE2)\n\n#define MULADDC_HUIT                            \\\n        \"movd     %%ecx,     %%mm1      \\n\\t\"   \\\n        \"movd     %%ebx,     %%mm0      \\n\\t\"   \\\n        \"movd     (%%edi),   %%mm3      \\n\\t\"   \\\n        \"paddq    %%mm3,     %%mm1      \\n\\t\"   \\\n        \"movd     (%%esi),   %%mm2      \\n\\t\"   \\\n        \"pmuludq  %%mm0,     %%mm2      \\n\\t\"   \\\n        \"movd     4(%%esi),  %%mm4      \\n\\t\"   \\\n        \"pmuludq  %%mm0,     %%mm4      \\n\\t\"   \\\n        \"movd     8(%%esi),  %%mm6      \\n\\t\"   \\\n        \"pmuludq  %%mm0,     %%mm6      \\n\\t\"   \\\n        \"movd     12(%%esi), %%mm7      \\n\\t\"   \\\n        \"pmuludq  %%mm0,     %%mm7      \\n\\t\"   \\\n        \"paddq    %%mm2,     %%mm1      \\n\\t\"   \\\n        \"movd     4(%%edi),  %%mm3      \\n\\t\"   \\\n        \"paddq    %%mm4,     %%mm3      \\n\\t\"   \\\n        \"movd     8(%%edi),  %%mm5      \\n\\t\"   \\\n        \"paddq    %%mm6,     %%mm5      \\n\\t\"   \\\n        \"movd     12(%%edi), %%mm4      \\n\\t\"   \\\n        \"paddq    %%mm4,     %%mm7      \\n\\t\"   \\\n        \"movd     %%mm1,     (%%edi)    \\n\\t\"   \\\n        \"movd     16(%%esi), %%mm2      \\n\\t\"   \\\n        \"pmuludq  %%mm0,     %%mm2      \\n\\t\"   \\\n        \"psrlq    $32,       %%mm1      \\n\\t\"   \\\n        \"movd     20(%%esi), %%mm4      \\n\\t\"   \\\n        \"pmuludq  %%mm0,     %%mm4      \\n\\t\"   \\\n        \"paddq    %%mm3,     %%mm1      \\n\\t\"   \\\n        \"movd     24(%%esi), %%mm6      \\n\\t\"   \\\n        \"pmuludq  %%mm0,     %%mm6      \\n\\t\"   \\\n        \"movd     %%mm1,     4(%%edi)   \\n\\t\"   \\\n        \"psrlq    $32,       %%mm1      \\n\\t\"   \\\n        \"movd     28(%%esi), %%mm3      \\n\\t\"   \\\n        \"pmuludq  %%mm0,     %%mm3      \\n\\t\"   \\\n        \"paddq    %%mm5,     %%mm1      \\n\\t\"   \\\n        \"movd     16(%%edi), %%mm5      \\n\\t\"   \\\n        \"paddq    %%mm5,     %%mm2      \\n\\t\"   \\\n        \"movd     %%mm1,     8(%%edi)   \\n\\t\"   \\\n        \"psrlq    $32,       %%mm1      \\n\\t\"   \\\n        \"paddq    %%mm7,     %%mm1      \\n\\t\"   \\\n        \"movd     20(%%edi), %%mm5      \\n\\t\"   \\\n        \"paddq    %%mm5,     %%mm4      \\n\\t\"   \\\n        \"movd     %%mm1,     12(%%edi)  \\n\\t\"   \\\n        \"psrlq    $32,       %%mm1      \\n\\t\"   \\\n        \"paddq    %%mm2,     %%mm1      \\n\\t\"   \\\n        \"movd     24(%%edi), %%mm5      \\n\\t\"   \\\n        \"paddq    %%mm5,     %%mm6      \\n\\t\"   \\\n        \"movd     %%mm1,     16(%%edi)  \\n\\t\"   \\\n        \"psrlq    $32,       %%mm1      \\n\\t\"   \\\n        \"paddq    %%mm4,     %%mm1      \\n\\t\"   \\\n        \"movd     28(%%edi), %%mm5      \\n\\t\"   \\\n        \"paddq    %%mm5,     %%mm3      \\n\\t\"   \\\n        \"movd     %%mm1,     20(%%edi)  \\n\\t\"   \\\n        \"psrlq    $32,       %%mm1      \\n\\t\"   \\\n        \"paddq    %%mm6,     %%mm1      \\n\\t\"   \\\n        \"movd     %%mm1,     24(%%edi)  \\n\\t\"   \\\n        \"psrlq    $32,       %%mm1      \\n\\t\"   \\\n        \"paddq    %%mm3,     %%mm1      \\n\\t\"   \\\n        \"movd     %%mm1,     28(%%edi)  \\n\\t\"   \\\n        \"addl     $32,       %%edi      \\n\\t\"   \\\n        \"addl     $32,       %%esi      \\n\\t\"   \\\n        \"psrlq    $32,       %%mm1      \\n\\t\"   \\\n        \"movd     %%mm1,     %%ecx      \\n\\t\"\n\n#define MULADDC_STOP                    \\\n        \"emms                   \\n\\t\"   \\\n        \"movl   %4, %%ebx       \\n\\t\"   \\\n        \"movl   %%ecx, %1       \\n\\t\"   \\\n        \"movl   %%edi, %2       \\n\\t\"   \\\n        \"movl   %%esi, %3       \\n\\t\"   \\\n        : \"=m\" (t), \"=m\" (c), \"=m\" (d), \"=m\" (s)        \\\n        : \"m\" (t), \"m\" (s), \"m\" (d), \"m\" (c), \"m\" (b)   \\\n        : \"eax\", \"ebx\", \"ecx\", \"edx\", \"esi\", \"edi\"      \\\n    );\n\n#else\n\n#define MULADDC_STOP                    \\\n        \"movl   %4, %%ebx       \\n\\t\"   \\\n        \"movl   %%ecx, %1       \\n\\t\"   \\\n        \"movl   %%edi, %2       \\n\\t\"   \\\n        \"movl   %%esi, %3       \\n\\t\"   \\\n        : \"=m\" (t), \"=m\" (c), \"=m\" (d), \"=m\" (s)        \\\n        : \"m\" (t), \"m\" (s), \"m\" (d), \"m\" (c), \"m\" (b)   \\\n        : \"eax\", \"ebx\", \"ecx\", \"edx\", \"esi\", \"edi\"      \\\n    );\n#endif /* SSE2 */\n#endif /* i386 */\n\n#if defined(__amd64__) || defined (__x86_64__)\n\n#define MULADDC_INIT                        \\\n    asm(                                    \\\n        \"xorq   %%r8, %%r8          \\n\\t\"\n\n#define MULADDC_CORE                        \\\n        \"movq   (%%rsi), %%rax      \\n\\t\"   \\\n        \"mulq   %%rbx               \\n\\t\"   \\\n        \"addq   $8,      %%rsi      \\n\\t\"   \\\n        \"addq   %%rcx,   %%rax      \\n\\t\"   \\\n        \"movq   %%r8,    %%rcx      \\n\\t\"   \\\n        \"adcq   $0,      %%rdx      \\n\\t\"   \\\n        \"nop                        \\n\\t\"   \\\n        \"addq   %%rax,   (%%rdi)    \\n\\t\"   \\\n        \"adcq   %%rdx,   %%rcx      \\n\\t\"   \\\n        \"addq   $8,      %%rdi      \\n\\t\"\n\n#define MULADDC_STOP                        \\\n        : \"+c\" (c), \"+D\" (d), \"+S\" (s)      \\\n        : \"b\" (b)                           \\\n        : \"rax\", \"rdx\", \"r8\"                \\\n    );\n\n#endif /* AMD64 */\n\n#if defined(__mc68020__) || defined(__mcpu32__)\n\n#define MULADDC_INIT                    \\\n    asm(                                \\\n        \"movl   %3, %%a2        \\n\\t\"   \\\n        \"movl   %4, %%a3        \\n\\t\"   \\\n        \"movl   %5, %%d3        \\n\\t\"   \\\n        \"movl   %6, %%d2        \\n\\t\"   \\\n        \"moveq  #0, %%d0        \\n\\t\"\n\n#define MULADDC_CORE                    \\\n        \"movel  %%a2@+, %%d1    \\n\\t\"   \\\n        \"mulul  %%d2, %%d4:%%d1 \\n\\t\"   \\\n        \"addl   %%d3, %%d1      \\n\\t\"   \\\n        \"addxl  %%d0, %%d4      \\n\\t\"   \\\n        \"moveq  #0,   %%d3      \\n\\t\"   \\\n        \"addl   %%d1, %%a3@+    \\n\\t\"   \\\n        \"addxl  %%d4, %%d3      \\n\\t\"\n\n#define MULADDC_STOP                    \\\n        \"movl   %%d3, %0        \\n\\t\"   \\\n        \"movl   %%a3, %1        \\n\\t\"   \\\n        \"movl   %%a2, %2        \\n\\t\"   \\\n        : \"=m\" (c), \"=m\" (d), \"=m\" (s)              \\\n        : \"m\" (s), \"m\" (d), \"m\" (c), \"m\" (b)        \\\n        : \"d0\", \"d1\", \"d2\", \"d3\", \"d4\", \"a2\", \"a3\"  \\\n    );\n\n#define MULADDC_HUIT                        \\\n        \"movel  %%a2@+,  %%d1       \\n\\t\"   \\\n        \"mulul  %%d2,    %%d4:%%d1  \\n\\t\"   \\\n        \"addxl  %%d3,    %%d1       \\n\\t\"   \\\n        \"addxl  %%d0,    %%d4       \\n\\t\"   \\\n        \"addl   %%d1,    %%a3@+     \\n\\t\"   \\\n        \"movel  %%a2@+,  %%d1       \\n\\t\"   \\\n        \"mulul  %%d2,    %%d3:%%d1  \\n\\t\"   \\\n        \"addxl  %%d4,    %%d1       \\n\\t\"   \\\n        \"addxl  %%d0,    %%d3       \\n\\t\"   \\\n        \"addl   %%d1,    %%a3@+     \\n\\t\"   \\\n        \"movel  %%a2@+,  %%d1       \\n\\t\"   \\\n        \"mulul  %%d2,    %%d4:%%d1  \\n\\t\"   \\\n        \"addxl  %%d3,    %%d1       \\n\\t\"   \\\n        \"addxl  %%d0,    %%d4       \\n\\t\"   \\\n        \"addl   %%d1,    %%a3@+     \\n\\t\"   \\\n        \"movel  %%a2@+,  %%d1       \\n\\t\"   \\\n        \"mulul  %%d2,    %%d3:%%d1  \\n\\t\"   \\\n        \"addxl  %%d4,    %%d1       \\n\\t\"   \\\n        \"addxl  %%d0,    %%d3       \\n\\t\"   \\\n        \"addl   %%d1,    %%a3@+     \\n\\t\"   \\\n        \"movel  %%a2@+,  %%d1       \\n\\t\"   \\\n        \"mulul  %%d2,    %%d4:%%d1  \\n\\t\"   \\\n        \"addxl  %%d3,    %%d1       \\n\\t\"   \\\n        \"addxl  %%d0,    %%d4       \\n\\t\"   \\\n        \"addl   %%d1,    %%a3@+     \\n\\t\"   \\\n        \"movel  %%a2@+,  %%d1       \\n\\t\"   \\\n        \"mulul  %%d2,    %%d3:%%d1  \\n\\t\"   \\\n        \"addxl  %%d4,    %%d1       \\n\\t\"   \\\n        \"addxl  %%d0,    %%d3       \\n\\t\"   \\\n        \"addl   %%d1,    %%a3@+     \\n\\t\"   \\\n        \"movel  %%a2@+,  %%d1       \\n\\t\"   \\\n        \"mulul  %%d2,    %%d4:%%d1  \\n\\t\"   \\\n        \"addxl  %%d3,    %%d1       \\n\\t\"   \\\n        \"addxl  %%d0,    %%d4       \\n\\t\"   \\\n        \"addl   %%d1,    %%a3@+     \\n\\t\"   \\\n        \"movel  %%a2@+,  %%d1       \\n\\t\"   \\\n        \"mulul  %%d2,    %%d3:%%d1  \\n\\t\"   \\\n        \"addxl  %%d4,    %%d1       \\n\\t\"   \\\n        \"addxl  %%d0,    %%d3       \\n\\t\"   \\\n        \"addl   %%d1,    %%a3@+     \\n\\t\"   \\\n        \"addxl  %%d0,    %%d3       \\n\\t\"\n\n#endif /* MC68000 */\n\n#if defined(__powerpc64__) || defined(__ppc64__)\n\n#if defined(__MACH__) && defined(__APPLE__)\n\n#define MULADDC_INIT                        \\\n    asm(                                    \\\n        \"ld     r3, %3              \\n\\t\"   \\\n        \"ld     r4, %4              \\n\\t\"   \\\n        \"ld     r5, %5              \\n\\t\"   \\\n        \"ld     r6, %6              \\n\\t\"   \\\n        \"addi   r3, r3, -8          \\n\\t\"   \\\n        \"addi   r4, r4, -8          \\n\\t\"   \\\n        \"addic  r5, r5,  0          \\n\\t\"\n\n#define MULADDC_CORE                        \\\n        \"ldu    r7, 8(r3)           \\n\\t\"   \\\n        \"mulld  r8, r7, r6          \\n\\t\"   \\\n        \"mulhdu r9, r7, r6          \\n\\t\"   \\\n        \"adde   r8, r8, r5          \\n\\t\"   \\\n        \"ld     r7, 8(r4)           \\n\\t\"   \\\n        \"addze  r5, r9              \\n\\t\"   \\\n        \"addc   r8, r8, r7          \\n\\t\"   \\\n        \"stdu   r8, 8(r4)           \\n\\t\"\n\n#define MULADDC_STOP                        \\\n        \"addze  r5, r5              \\n\\t\"   \\\n        \"addi   r4, r4, 8           \\n\\t\"   \\\n        \"addi   r3, r3, 8           \\n\\t\"   \\\n        \"std    r5, %0              \\n\\t\"   \\\n        \"std    r4, %1              \\n\\t\"   \\\n        \"std    r3, %2              \\n\\t\"   \\\n        : \"=m\" (c), \"=m\" (d), \"=m\" (s)              \\\n        : \"m\" (s), \"m\" (d), \"m\" (c), \"m\" (b)        \\\n        : \"r3\", \"r4\", \"r5\", \"r6\", \"r7\", \"r8\", \"r9\"  \\\n    );\n\n\n#else /* __MACH__ && __APPLE__ */\n\n#define MULADDC_INIT                        \\\n    asm(                                    \\\n        \"ld     %%r3, %3            \\n\\t\"   \\\n        \"ld     %%r4, %4            \\n\\t\"   \\\n        \"ld     %%r5, %5            \\n\\t\"   \\\n        \"ld     %%r6, %6            \\n\\t\"   \\\n        \"addi   %%r3, %%r3, -8      \\n\\t\"   \\\n        \"addi   %%r4, %%r4, -8      \\n\\t\"   \\\n        \"addic  %%r5, %%r5,  0      \\n\\t\"\n\n#define MULADDC_CORE                        \\\n        \"ldu    %%r7, 8(%%r3)       \\n\\t\"   \\\n        \"mulld  %%r8, %%r7, %%r6    \\n\\t\"   \\\n        \"mulhdu %%r9, %%r7, %%r6    \\n\\t\"   \\\n        \"adde   %%r8, %%r8, %%r5    \\n\\t\"   \\\n        \"ld     %%r7, 8(%%r4)       \\n\\t\"   \\\n        \"addze  %%r5, %%r9          \\n\\t\"   \\\n        \"addc   %%r8, %%r8, %%r7    \\n\\t\"   \\\n        \"stdu   %%r8, 8(%%r4)       \\n\\t\"\n\n#define MULADDC_STOP                        \\\n        \"addze  %%r5, %%r5          \\n\\t\"   \\\n        \"addi   %%r4, %%r4, 8       \\n\\t\"   \\\n        \"addi   %%r3, %%r3, 8       \\n\\t\"   \\\n        \"std    %%r5, %0            \\n\\t\"   \\\n        \"std    %%r4, %1            \\n\\t\"   \\\n        \"std    %%r3, %2            \\n\\t\"   \\\n        : \"=m\" (c), \"=m\" (d), \"=m\" (s)              \\\n        : \"m\" (s), \"m\" (d), \"m\" (c), \"m\" (b)        \\\n        : \"r3\", \"r4\", \"r5\", \"r6\", \"r7\", \"r8\", \"r9\"  \\\n    );\n\n#endif /* __MACH__ && __APPLE__ */\n\n#elif defined(__powerpc__) || defined(__ppc__) /* end PPC64/begin PPC32  */\n\n#if defined(__MACH__) && defined(__APPLE__)\n\n#define MULADDC_INIT                    \\\n    asm(                                \\\n        \"lwz    r3, %3          \\n\\t\"   \\\n        \"lwz    r4, %4          \\n\\t\"   \\\n        \"lwz    r5, %5          \\n\\t\"   \\\n        \"lwz    r6, %6          \\n\\t\"   \\\n        \"addi   r3, r3, -4      \\n\\t\"   \\\n        \"addi   r4, r4, -4      \\n\\t\"   \\\n        \"addic  r5, r5,  0      \\n\\t\"\n\n#define MULADDC_CORE                    \\\n        \"lwzu   r7, 4(r3)       \\n\\t\"   \\\n        \"mullw  r8, r7, r6      \\n\\t\"   \\\n        \"mulhwu r9, r7, r6      \\n\\t\"   \\\n        \"adde   r8, r8, r5      \\n\\t\"   \\\n        \"lwz    r7, 4(r4)       \\n\\t\"   \\\n        \"addze  r5, r9          \\n\\t\"   \\\n        \"addc   r8, r8, r7      \\n\\t\"   \\\n        \"stwu   r8, 4(r4)       \\n\\t\"\n\n#define MULADDC_STOP                    \\\n        \"addze  r5, r5          \\n\\t\"   \\\n        \"addi   r4, r4, 4       \\n\\t\"   \\\n        \"addi   r3, r3, 4       \\n\\t\"   \\\n        \"stw    r5, %0          \\n\\t\"   \\\n        \"stw    r4, %1          \\n\\t\"   \\\n        \"stw    r3, %2          \\n\\t\"   \\\n        : \"=m\" (c), \"=m\" (d), \"=m\" (s)              \\\n        : \"m\" (s), \"m\" (d), \"m\" (c), \"m\" (b)        \\\n        : \"r3\", \"r4\", \"r5\", \"r6\", \"r7\", \"r8\", \"r9\"  \\\n    );\n\n#else /* __MACH__ && __APPLE__ */\n\n#define MULADDC_INIT                        \\\n    asm(                                    \\\n        \"lwz    %%r3, %3            \\n\\t\"   \\\n        \"lwz    %%r4, %4            \\n\\t\"   \\\n        \"lwz    %%r5, %5            \\n\\t\"   \\\n        \"lwz    %%r6, %6            \\n\\t\"   \\\n        \"addi   %%r3, %%r3, -4      \\n\\t\"   \\\n        \"addi   %%r4, %%r4, -4      \\n\\t\"   \\\n        \"addic  %%r5, %%r5,  0      \\n\\t\"\n\n#define MULADDC_CORE                        \\\n        \"lwzu   %%r7, 4(%%r3)       \\n\\t\"   \\\n        \"mullw  %%r8, %%r7, %%r6    \\n\\t\"   \\\n        \"mulhwu %%r9, %%r7, %%r6    \\n\\t\"   \\\n        \"adde   %%r8, %%r8, %%r5    \\n\\t\"   \\\n        \"lwz    %%r7, 4(%%r4)       \\n\\t\"   \\\n        \"addze  %%r5, %%r9          \\n\\t\"   \\\n        \"addc   %%r8, %%r8, %%r7    \\n\\t\"   \\\n        \"stwu   %%r8, 4(%%r4)       \\n\\t\"\n\n#define MULADDC_STOP                        \\\n        \"addze  %%r5, %%r5          \\n\\t\"   \\\n        \"addi   %%r4, %%r4, 4       \\n\\t\"   \\\n        \"addi   %%r3, %%r3, 4       \\n\\t\"   \\\n        \"stw    %%r5, %0            \\n\\t\"   \\\n        \"stw    %%r4, %1            \\n\\t\"   \\\n        \"stw    %%r3, %2            \\n\\t\"   \\\n        : \"=m\" (c), \"=m\" (d), \"=m\" (s)              \\\n        : \"m\" (s), \"m\" (d), \"m\" (c), \"m\" (b)        \\\n        : \"r3\", \"r4\", \"r5\", \"r6\", \"r7\", \"r8\", \"r9\"  \\\n    );\n\n#endif /* __MACH__ && __APPLE__ */\n\n#endif /* PPC32 */\n\n/*\n * The Sparc(64) assembly is reported to be broken.\n * Disable it for now, until we're able to fix it.\n */\n#if 0 && defined(__sparc__)\n#if defined(__sparc64__)\n\n#define MULADDC_INIT                                    \\\n    asm(                                                \\\n                \"ldx     %3, %%o0               \\n\\t\"   \\\n                \"ldx     %4, %%o1               \\n\\t\"   \\\n                \"ld      %5, %%o2               \\n\\t\"   \\\n                \"ld      %6, %%o3               \\n\\t\"\n\n#define MULADDC_CORE                                    \\\n                \"ld      [%%o0], %%o4           \\n\\t\"   \\\n                \"inc     4, %%o0                \\n\\t\"   \\\n                \"ld      [%%o1], %%o5           \\n\\t\"   \\\n                \"umul    %%o3, %%o4, %%o4       \\n\\t\"   \\\n                \"addcc   %%o4, %%o2, %%o4       \\n\\t\"   \\\n                \"rd      %%y, %%g1              \\n\\t\"   \\\n                \"addx    %%g1, 0, %%g1          \\n\\t\"   \\\n                \"addcc   %%o4, %%o5, %%o4       \\n\\t\"   \\\n                \"st      %%o4, [%%o1]           \\n\\t\"   \\\n                \"addx    %%g1, 0, %%o2          \\n\\t\"   \\\n                \"inc     4, %%o1                \\n\\t\"\n\n        #define MULADDC_STOP                            \\\n                \"st      %%o2, %0               \\n\\t\"   \\\n                \"stx     %%o1, %1               \\n\\t\"   \\\n                \"stx     %%o0, %2               \\n\\t\"   \\\n        : \"=m\" (c), \"=m\" (d), \"=m\" (s)          \\\n        : \"m\" (s), \"m\" (d), \"m\" (c), \"m\" (b)    \\\n        : \"g1\", \"o0\", \"o1\", \"o2\", \"o3\", \"o4\",   \\\n          \"o5\"                                  \\\n        );\n\n#else /* __sparc64__ */\n\n#define MULADDC_INIT                                    \\\n    asm(                                                \\\n                \"ld      %3, %%o0               \\n\\t\"   \\\n                \"ld      %4, %%o1               \\n\\t\"   \\\n                \"ld      %5, %%o2               \\n\\t\"   \\\n                \"ld      %6, %%o3               \\n\\t\"\n\n#define MULADDC_CORE                                    \\\n                \"ld      [%%o0], %%o4           \\n\\t\"   \\\n                \"inc     4, %%o0                \\n\\t\"   \\\n                \"ld      [%%o1], %%o5           \\n\\t\"   \\\n                \"umul    %%o3, %%o4, %%o4       \\n\\t\"   \\\n                \"addcc   %%o4, %%o2, %%o4       \\n\\t\"   \\\n                \"rd      %%y, %%g1              \\n\\t\"   \\\n                \"addx    %%g1, 0, %%g1          \\n\\t\"   \\\n                \"addcc   %%o4, %%o5, %%o4       \\n\\t\"   \\\n                \"st      %%o4, [%%o1]           \\n\\t\"   \\\n                \"addx    %%g1, 0, %%o2          \\n\\t\"   \\\n                \"inc     4, %%o1                \\n\\t\"\n\n#define MULADDC_STOP                                    \\\n                \"st      %%o2, %0               \\n\\t\"   \\\n                \"st      %%o1, %1               \\n\\t\"   \\\n                \"st      %%o0, %2               \\n\\t\"   \\\n        : \"=m\" (c), \"=m\" (d), \"=m\" (s)          \\\n        : \"m\" (s), \"m\" (d), \"m\" (c), \"m\" (b)    \\\n        : \"g1\", \"o0\", \"o1\", \"o2\", \"o3\", \"o4\",   \\\n          \"o5\"                                  \\\n        );\n\n#endif /* __sparc64__ */\n#endif /* __sparc__ */\n\n#if defined(__microblaze__) || defined(microblaze)\n\n#define MULADDC_INIT                    \\\n    asm(                                \\\n        \"lwi   r3,   %3         \\n\\t\"   \\\n        \"lwi   r4,   %4         \\n\\t\"   \\\n        \"lwi   r5,   %5         \\n\\t\"   \\\n        \"lwi   r6,   %6         \\n\\t\"   \\\n        \"andi  r7,   r6, 0xffff \\n\\t\"   \\\n        \"bsrli r6,   r6, 16     \\n\\t\"\n\n#define MULADDC_CORE                    \\\n        \"lhui  r8,   r3,   0    \\n\\t\"   \\\n        \"addi  r3,   r3,   2    \\n\\t\"   \\\n        \"lhui  r9,   r3,   0    \\n\\t\"   \\\n        \"addi  r3,   r3,   2    \\n\\t\"   \\\n        \"mul   r10,  r9,  r6    \\n\\t\"   \\\n        \"mul   r11,  r8,  r7    \\n\\t\"   \\\n        \"mul   r12,  r9,  r7    \\n\\t\"   \\\n        \"mul   r13,  r8,  r6    \\n\\t\"   \\\n        \"bsrli  r8, r10,  16    \\n\\t\"   \\\n        \"bsrli  r9, r11,  16    \\n\\t\"   \\\n        \"add   r13, r13,  r8    \\n\\t\"   \\\n        \"add   r13, r13,  r9    \\n\\t\"   \\\n        \"bslli r10, r10,  16    \\n\\t\"   \\\n        \"bslli r11, r11,  16    \\n\\t\"   \\\n        \"add   r12, r12, r10    \\n\\t\"   \\\n        \"addc  r13, r13,  r0    \\n\\t\"   \\\n        \"add   r12, r12, r11    \\n\\t\"   \\\n        \"addc  r13, r13,  r0    \\n\\t\"   \\\n        \"lwi   r10,  r4,   0    \\n\\t\"   \\\n        \"add   r12, r12, r10    \\n\\t\"   \\\n        \"addc  r13, r13,  r0    \\n\\t\"   \\\n        \"add   r12, r12,  r5    \\n\\t\"   \\\n        \"addc   r5, r13,  r0    \\n\\t\"   \\\n        \"swi   r12,  r4,   0    \\n\\t\"   \\\n        \"addi   r4,  r4,   4    \\n\\t\"\n\n#define MULADDC_STOP                    \\\n        \"swi   r5,   %0         \\n\\t\"   \\\n        \"swi   r4,   %1         \\n\\t\"   \\\n        \"swi   r3,   %2         \\n\\t\"   \\\n        : \"=m\" (c), \"=m\" (d), \"=m\" (s)              \\\n        : \"m\" (s), \"m\" (d), \"m\" (c), \"m\" (b)        \\\n        : \"r3\", \"r4\", \"r5\", \"r6\", \"r7\", \"r8\",       \\\n          \"r9\", \"r10\", \"r11\", \"r12\", \"r13\"          \\\n    );\n\n#endif /* MicroBlaze */\n\n#if defined(__tricore__)\n\n#define MULADDC_INIT                            \\\n    asm(                                        \\\n        \"ld.a   %%a2, %3                \\n\\t\"   \\\n        \"ld.a   %%a3, %4                \\n\\t\"   \\\n        \"ld.w   %%d4, %5                \\n\\t\"   \\\n        \"ld.w   %%d1, %6                \\n\\t\"   \\\n        \"xor    %%d5, %%d5              \\n\\t\"\n\n#define MULADDC_CORE                            \\\n        \"ld.w   %%d0,   [%%a2+]         \\n\\t\"   \\\n        \"madd.u %%e2, %%e4, %%d0, %%d1  \\n\\t\"   \\\n        \"ld.w   %%d0,   [%%a3]          \\n\\t\"   \\\n        \"addx   %%d2,    %%d2,  %%d0    \\n\\t\"   \\\n        \"addc   %%d3,    %%d3,    0     \\n\\t\"   \\\n        \"mov    %%d4,    %%d3           \\n\\t\"   \\\n        \"st.w  [%%a3+],  %%d2           \\n\\t\"\n\n#define MULADDC_STOP                            \\\n        \"st.w   %0, %%d4                \\n\\t\"   \\\n        \"st.a   %1, %%a3                \\n\\t\"   \\\n        \"st.a   %2, %%a2                \\n\\t\"   \\\n        : \"=m\" (c), \"=m\" (d), \"=m\" (s)          \\\n        : \"m\" (s), \"m\" (d), \"m\" (c), \"m\" (b)    \\\n        : \"d0\", \"d1\", \"e2\", \"d4\", \"a2\", \"a3\"    \\\n    );\n\n#endif /* TriCore */\n\n/*\n * gcc -O0 by default uses r7 for the frame pointer, so it complains about our\n * use of r7 below, unless -fomit-frame-pointer is passed. Unfortunately,\n * passing that option is not easy when building with yotta.\n *\n * On the other hand, -fomit-frame-pointer is implied by any -Ox options with\n * x !=0, which we can detect using __OPTIMIZE__ (which is also defined by\n * clang and armcc5 under the same conditions).\n *\n * So, only use the optimized assembly below for optimized build, which avoids\n * the build error and is pretty reasonable anyway.\n */\n#if defined(__GNUC__) && !defined(__OPTIMIZE__)\n#define MULADDC_CANNOT_USE_R7\n#endif\n\n#if defined(__arm__) && !defined(MULADDC_CANNOT_USE_R7)\n\n#if defined(__thumb__) && !defined(__thumb2__)\n\n#define MULADDC_INIT                                    \\\n    asm(                                                \\\n            \"ldr    r0, %3                      \\n\\t\"   \\\n            \"ldr    r1, %4                      \\n\\t\"   \\\n            \"ldr    r2, %5                      \\n\\t\"   \\\n            \"ldr    r3, %6                      \\n\\t\"   \\\n            \"lsr    r7, r3, #16                 \\n\\t\"   \\\n            \"mov    r9, r7                      \\n\\t\"   \\\n            \"lsl    r7, r3, #16                 \\n\\t\"   \\\n            \"lsr    r7, r7, #16                 \\n\\t\"   \\\n            \"mov    r8, r7                      \\n\\t\"\n\n#define MULADDC_CORE                                    \\\n            \"ldmia  r0!, {r6}                   \\n\\t\"   \\\n            \"lsr    r7, r6, #16                 \\n\\t\"   \\\n            \"lsl    r6, r6, #16                 \\n\\t\"   \\\n            \"lsr    r6, r6, #16                 \\n\\t\"   \\\n            \"mov    r4, r8                      \\n\\t\"   \\\n            \"mul    r4, r6                      \\n\\t\"   \\\n            \"mov    r3, r9                      \\n\\t\"   \\\n            \"mul    r6, r3                      \\n\\t\"   \\\n            \"mov    r5, r9                      \\n\\t\"   \\\n            \"mul    r5, r7                      \\n\\t\"   \\\n            \"mov    r3, r8                      \\n\\t\"   \\\n            \"mul    r7, r3                      \\n\\t\"   \\\n            \"lsr    r3, r6, #16                 \\n\\t\"   \\\n            \"add    r5, r5, r3                  \\n\\t\"   \\\n            \"lsr    r3, r7, #16                 \\n\\t\"   \\\n            \"add    r5, r5, r3                  \\n\\t\"   \\\n            \"add    r4, r4, r2                  \\n\\t\"   \\\n            \"mov    r2, #0                      \\n\\t\"   \\\n            \"adc    r5, r2                      \\n\\t\"   \\\n            \"lsl    r3, r6, #16                 \\n\\t\"   \\\n            \"add    r4, r4, r3                  \\n\\t\"   \\\n            \"adc    r5, r2                      \\n\\t\"   \\\n            \"lsl    r3, r7, #16                 \\n\\t\"   \\\n            \"add    r4, r4, r3                  \\n\\t\"   \\\n            \"adc    r5, r2                      \\n\\t\"   \\\n            \"ldr    r3, [r1]                    \\n\\t\"   \\\n            \"add    r4, r4, r3                  \\n\\t\"   \\\n            \"adc    r2, r5                      \\n\\t\"   \\\n            \"stmia  r1!, {r4}                   \\n\\t\"\n\n#define MULADDC_STOP                                    \\\n            \"str    r2, %0                      \\n\\t\"   \\\n            \"str    r1, %1                      \\n\\t\"   \\\n            \"str    r0, %2                      \\n\\t\"   \\\n         : \"=m\" (c),  \"=m\" (d), \"=m\" (s)        \\\n         : \"m\" (s), \"m\" (d), \"m\" (c), \"m\" (b)   \\\n         : \"r0\", \"r1\", \"r2\", \"r3\", \"r4\", \"r5\",  \\\n           \"r6\", \"r7\", \"r8\", \"r9\", \"cc\"         \\\n         );\n\n#else\n\n#define MULADDC_INIT                                    \\\n    asm(                                                \\\n            \"ldr    r0, %3                      \\n\\t\"   \\\n            \"ldr    r1, %4                      \\n\\t\"   \\\n            \"ldr    r2, %5                      \\n\\t\"   \\\n            \"ldr    r3, %6                      \\n\\t\"\n\n#define MULADDC_CORE                                    \\\n            \"ldr    r4, [r0], #4                \\n\\t\"   \\\n            \"mov    r5, #0                      \\n\\t\"   \\\n            \"ldr    r6, [r1]                    \\n\\t\"   \\\n            \"umlal  r2, r5, r3, r4              \\n\\t\"   \\\n            \"adds   r7, r6, r2                  \\n\\t\"   \\\n            \"adc    r2, r5, #0                  \\n\\t\"   \\\n            \"str    r7, [r1], #4                \\n\\t\"\n\n#define MULADDC_STOP                                    \\\n            \"str    r2, %0                      \\n\\t\"   \\\n            \"str    r1, %1                      \\n\\t\"   \\\n            \"str    r0, %2                      \\n\\t\"   \\\n         : \"=m\" (c),  \"=m\" (d), \"=m\" (s)        \\\n         : \"m\" (s), \"m\" (d), \"m\" (c), \"m\" (b)   \\\n         : \"r0\", \"r1\", \"r2\", \"r3\", \"r4\", \"r5\",  \\\n           \"r6\", \"r7\", \"cc\"                     \\\n         );\n\n#endif /* Thumb */\n\n#endif /* ARMv3 */\n\n#if defined(__alpha__)\n\n#define MULADDC_INIT                    \\\n    asm(                                \\\n        \"ldq    $1, %3          \\n\\t\"   \\\n        \"ldq    $2, %4          \\n\\t\"   \\\n        \"ldq    $3, %5          \\n\\t\"   \\\n        \"ldq    $4, %6          \\n\\t\"\n\n#define MULADDC_CORE                    \\\n        \"ldq    $6,  0($1)      \\n\\t\"   \\\n        \"addq   $1,  8, $1      \\n\\t\"   \\\n        \"mulq   $6, $4, $7      \\n\\t\"   \\\n        \"umulh  $6, $4, $6      \\n\\t\"   \\\n        \"addq   $7, $3, $7      \\n\\t\"   \\\n        \"cmpult $7, $3, $3      \\n\\t\"   \\\n        \"ldq    $5,  0($2)      \\n\\t\"   \\\n        \"addq   $7, $5, $7      \\n\\t\"   \\\n        \"cmpult $7, $5, $5      \\n\\t\"   \\\n        \"stq    $7,  0($2)      \\n\\t\"   \\\n        \"addq   $2,  8, $2      \\n\\t\"   \\\n        \"addq   $6, $3, $3      \\n\\t\"   \\\n        \"addq   $5, $3, $3      \\n\\t\"\n\n#define MULADDC_STOP                                    \\\n        \"stq    $3, %0          \\n\\t\"   \\\n        \"stq    $2, %1          \\n\\t\"   \\\n        \"stq    $1, %2          \\n\\t\"   \\\n        : \"=m\" (c), \"=m\" (d), \"=m\" (s)              \\\n        : \"m\" (s), \"m\" (d), \"m\" (c), \"m\" (b)        \\\n        : \"$1\", \"$2\", \"$3\", \"$4\", \"$5\", \"$6\", \"$7\"  \\\n    );\n#endif /* Alpha */\n\n#if defined(__mips__) && !defined(__mips64)\n\n#define MULADDC_INIT                    \\\n    asm(                                \\\n        \"lw     $10, %3         \\n\\t\"   \\\n        \"lw     $11, %4         \\n\\t\"   \\\n        \"lw     $12, %5         \\n\\t\"   \\\n        \"lw     $13, %6         \\n\\t\"\n\n#define MULADDC_CORE                    \\\n        \"lw     $14, 0($10)     \\n\\t\"   \\\n        \"multu  $13, $14        \\n\\t\"   \\\n        \"addi   $10, $10, 4     \\n\\t\"   \\\n        \"mflo   $14             \\n\\t\"   \\\n        \"mfhi   $9              \\n\\t\"   \\\n        \"addu   $14, $12, $14   \\n\\t\"   \\\n        \"lw     $15, 0($11)     \\n\\t\"   \\\n        \"sltu   $12, $14, $12   \\n\\t\"   \\\n        \"addu   $15, $14, $15   \\n\\t\"   \\\n        \"sltu   $14, $15, $14   \\n\\t\"   \\\n        \"addu   $12, $12, $9    \\n\\t\"   \\\n        \"sw     $15, 0($11)     \\n\\t\"   \\\n        \"addu   $12, $12, $14   \\n\\t\"   \\\n        \"addi   $11, $11, 4     \\n\\t\"\n\n#define MULADDC_STOP                    \\\n        \"sw     $12, %0         \\n\\t\"   \\\n        \"sw     $11, %1         \\n\\t\"   \\\n        \"sw     $10, %2         \\n\\t\"   \\\n        : \"=m\" (c), \"=m\" (d), \"=m\" (s)                      \\\n        : \"m\" (s), \"m\" (d), \"m\" (c), \"m\" (b)                \\\n        : \"$9\", \"$10\", \"$11\", \"$12\", \"$13\", \"$14\", \"$15\"    \\\n    );\n\n#endif /* MIPS */\n#endif /* GNUC */\n\n#if (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)\n\n#define MULADDC_INIT                            \\\n    __asm   mov     esi, s                      \\\n    __asm   mov     edi, d                      \\\n    __asm   mov     ecx, c                      \\\n    __asm   mov     ebx, b\n\n#define MULADDC_CORE                            \\\n    __asm   lodsd                               \\\n    __asm   mul     ebx                         \\\n    __asm   add     eax, ecx                    \\\n    __asm   adc     edx, 0                      \\\n    __asm   add     eax, [edi]                  \\\n    __asm   adc     edx, 0                      \\\n    __asm   mov     ecx, edx                    \\\n    __asm   stosd\n\n#if defined(MBEDTLS_HAVE_SSE2)\n\n#define EMIT __asm _emit\n\n#define MULADDC_HUIT                            \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0xC9             \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0xC3             \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0x1F             \\\n    EMIT 0x0F  EMIT 0xD4  EMIT 0xCB             \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0x16             \\\n    EMIT 0x0F  EMIT 0xF4  EMIT 0xD0             \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0x66  EMIT 0x04  \\\n    EMIT 0x0F  EMIT 0xF4  EMIT 0xE0             \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0x76  EMIT 0x08  \\\n    EMIT 0x0F  EMIT 0xF4  EMIT 0xF0             \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0x7E  EMIT 0x0C  \\\n    EMIT 0x0F  EMIT 0xF4  EMIT 0xF8             \\\n    EMIT 0x0F  EMIT 0xD4  EMIT 0xCA             \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0x5F  EMIT 0x04  \\\n    EMIT 0x0F  EMIT 0xD4  EMIT 0xDC             \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0x6F  EMIT 0x08  \\\n    EMIT 0x0F  EMIT 0xD4  EMIT 0xEE             \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0x67  EMIT 0x0C  \\\n    EMIT 0x0F  EMIT 0xD4  EMIT 0xFC             \\\n    EMIT 0x0F  EMIT 0x7E  EMIT 0x0F             \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0x56  EMIT 0x10  \\\n    EMIT 0x0F  EMIT 0xF4  EMIT 0xD0             \\\n    EMIT 0x0F  EMIT 0x73  EMIT 0xD1  EMIT 0x20  \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0x66  EMIT 0x14  \\\n    EMIT 0x0F  EMIT 0xF4  EMIT 0xE0             \\\n    EMIT 0x0F  EMIT 0xD4  EMIT 0xCB             \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0x76  EMIT 0x18  \\\n    EMIT 0x0F  EMIT 0xF4  EMIT 0xF0             \\\n    EMIT 0x0F  EMIT 0x7E  EMIT 0x4F  EMIT 0x04  \\\n    EMIT 0x0F  EMIT 0x73  EMIT 0xD1  EMIT 0x20  \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0x5E  EMIT 0x1C  \\\n    EMIT 0x0F  EMIT 0xF4  EMIT 0xD8             \\\n    EMIT 0x0F  EMIT 0xD4  EMIT 0xCD             \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0x6F  EMIT 0x10  \\\n    EMIT 0x0F  EMIT 0xD4  EMIT 0xD5             \\\n    EMIT 0x0F  EMIT 0x7E  EMIT 0x4F  EMIT 0x08  \\\n    EMIT 0x0F  EMIT 0x73  EMIT 0xD1  EMIT 0x20  \\\n    EMIT 0x0F  EMIT 0xD4  EMIT 0xCF             \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0x6F  EMIT 0x14  \\\n    EMIT 0x0F  EMIT 0xD4  EMIT 0xE5             \\\n    EMIT 0x0F  EMIT 0x7E  EMIT 0x4F  EMIT 0x0C  \\\n    EMIT 0x0F  EMIT 0x73  EMIT 0xD1  EMIT 0x20  \\\n    EMIT 0x0F  EMIT 0xD4  EMIT 0xCA             \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0x6F  EMIT 0x18  \\\n    EMIT 0x0F  EMIT 0xD4  EMIT 0xF5             \\\n    EMIT 0x0F  EMIT 0x7E  EMIT 0x4F  EMIT 0x10  \\\n    EMIT 0x0F  EMIT 0x73  EMIT 0xD1  EMIT 0x20  \\\n    EMIT 0x0F  EMIT 0xD4  EMIT 0xCC             \\\n    EMIT 0x0F  EMIT 0x6E  EMIT 0x6F  EMIT 0x1C  \\\n    EMIT 0x0F  EMIT 0xD4  EMIT 0xDD             \\\n    EMIT 0x0F  EMIT 0x7E  EMIT 0x4F  EMIT 0x14  \\\n    EMIT 0x0F  EMIT 0x73  EMIT 0xD1  EMIT 0x20  \\\n    EMIT 0x0F  EMIT 0xD4  EMIT 0xCE             \\\n    EMIT 0x0F  EMIT 0x7E  EMIT 0x4F  EMIT 0x18  \\\n    EMIT 0x0F  EMIT 0x73  EMIT 0xD1  EMIT 0x20  \\\n    EMIT 0x0F  EMIT 0xD4  EMIT 0xCB             \\\n    EMIT 0x0F  EMIT 0x7E  EMIT 0x4F  EMIT 0x1C  \\\n    EMIT 0x83  EMIT 0xC7  EMIT 0x20             \\\n    EMIT 0x83  EMIT 0xC6  EMIT 0x20             \\\n    EMIT 0x0F  EMIT 0x73  EMIT 0xD1  EMIT 0x20  \\\n    EMIT 0x0F  EMIT 0x7E  EMIT 0xC9\n\n#define MULADDC_STOP                            \\\n    EMIT 0x0F  EMIT 0x77                        \\\n    __asm   mov     c, ecx                      \\\n    __asm   mov     d, edi                      \\\n    __asm   mov     s, esi                      \\\n\n#else\n\n#define MULADDC_STOP                            \\\n    __asm   mov     c, ecx                      \\\n    __asm   mov     d, edi                      \\\n    __asm   mov     s, esi                      \\\n\n#endif /* SSE2 */\n#endif /* MSVC */\n\n#endif /* MBEDTLS_HAVE_ASM */\n\n#if !defined(MULADDC_CORE)\n#if defined(MBEDTLS_HAVE_UDBL)\n\n#define MULADDC_INIT                    \\\n{                                       \\\n    mbedtls_t_udbl r;                           \\\n    mbedtls_mpi_uint r0, r1;\n\n#define MULADDC_CORE                    \\\n    r   = *(s++) * (mbedtls_t_udbl) b;          \\\n    r0  = (mbedtls_mpi_uint) r;                   \\\n    r1  = (mbedtls_mpi_uint)( r >> biL );         \\\n    r0 += c;  r1 += (r0 <  c);          \\\n    r0 += *d; r1 += (r0 < *d);          \\\n    c = r1; *(d++) = r0;\n\n#define MULADDC_STOP                    \\\n}\n\n#else\n#define MULADDC_INIT                    \\\n{                                       \\\n    mbedtls_mpi_uint s0, s1, b0, b1;              \\\n    mbedtls_mpi_uint r0, r1, rx, ry;              \\\n    b0 = ( b << biH ) >> biH;           \\\n    b1 = ( b >> biH );\n\n#define MULADDC_CORE                    \\\n    s0 = ( *s << biH ) >> biH;          \\\n    s1 = ( *s >> biH ); s++;            \\\n    rx = s0 * b1; r0 = s0 * b0;         \\\n    ry = s1 * b0; r1 = s1 * b1;         \\\n    r1 += ( rx >> biH );                \\\n    r1 += ( ry >> biH );                \\\n    rx <<= biH; ry <<= biH;             \\\n    r0 += rx; r1 += (r0 < rx);          \\\n    r0 += ry; r1 += (r0 < ry);          \\\n    r0 +=  c; r1 += (r0 <  c);          \\\n    r0 += *d; r1 += (r0 < *d);          \\\n    c = r1; *(d++) = r0;\n\n#define MULADDC_STOP                    \\\n}\n\n#endif /* C (generic)  */\n#endif /* C (longlong) */\n\n#endif /* bn_mul.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/camellia.h",
    "content": "/**\n * \\file camellia.h\n *\n * \\brief Camellia block cipher\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_CAMELLIA_H\n#define MBEDTLS_CAMELLIA_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n#include <stdint.h>\n\n#define MBEDTLS_CAMELLIA_ENCRYPT     1\n#define MBEDTLS_CAMELLIA_DECRYPT     0\n\n#define MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH           -0x0024  /**< Invalid key length. */\n#define MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH         -0x0026  /**< Invalid data input length. */\n#define MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED              -0x0027  /**< Camellia hardware accelerator failed. */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_CAMELLIA_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief          CAMELLIA context structure\n */\ntypedef struct\n{\n    int nr;                     /*!<  number of rounds  */\n    uint32_t rk[68];            /*!<  CAMELLIA round keys    */\n}\nmbedtls_camellia_context;\n\n#else  /* MBEDTLS_CAMELLIA_ALT */\n#include \"camellia_alt.h\"\n#endif /* MBEDTLS_CAMELLIA_ALT */\n\n/**\n * \\brief          Initialize CAMELLIA context\n *\n * \\param ctx      CAMELLIA context to be initialized\n */\nvoid mbedtls_camellia_init( mbedtls_camellia_context *ctx );\n\n/**\n * \\brief          Clear CAMELLIA context\n *\n * \\param ctx      CAMELLIA context to be cleared\n */\nvoid mbedtls_camellia_free( mbedtls_camellia_context *ctx );\n\n/**\n * \\brief          CAMELLIA key schedule (encryption)\n *\n * \\param ctx      CAMELLIA context to be initialized\n * \\param key      encryption key\n * \\param keybits  must be 128, 192 or 256\n *\n * \\return         0 if successful, or MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH\n */\nint mbedtls_camellia_setkey_enc( mbedtls_camellia_context *ctx, const unsigned char *key,\n                         unsigned int keybits );\n\n/**\n * \\brief          CAMELLIA key schedule (decryption)\n *\n * \\param ctx      CAMELLIA context to be initialized\n * \\param key      decryption key\n * \\param keybits  must be 128, 192 or 256\n *\n * \\return         0 if successful, or MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH\n */\nint mbedtls_camellia_setkey_dec( mbedtls_camellia_context *ctx, const unsigned char *key,\n                         unsigned int keybits );\n\n/**\n * \\brief          CAMELLIA-ECB block encryption/decryption\n *\n * \\param ctx      CAMELLIA context\n * \\param mode     MBEDTLS_CAMELLIA_ENCRYPT or MBEDTLS_CAMELLIA_DECRYPT\n * \\param input    16-byte input block\n * \\param output   16-byte output block\n *\n * \\return         0 if successful\n */\nint mbedtls_camellia_crypt_ecb( mbedtls_camellia_context *ctx,\n                    int mode,\n                    const unsigned char input[16],\n                    unsigned char output[16] );\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n/**\n * \\brief          CAMELLIA-CBC buffer encryption/decryption\n *                 Length should be a multiple of the block\n *                 size (16 bytes)\n *\n * \\note           Upon exit, the content of the IV is updated so that you can\n *                 call the function same function again on the following\n *                 block(s) of data and get the same result as if it was\n *                 encrypted in one call. This allows a \"streaming\" usage.\n *                 If on the other hand you need to retain the contents of the\n *                 IV, you should either save it manually or use the cipher\n *                 module instead.\n *\n * \\param ctx      CAMELLIA context\n * \\param mode     MBEDTLS_CAMELLIA_ENCRYPT or MBEDTLS_CAMELLIA_DECRYPT\n * \\param length   length of the input data\n * \\param iv       initialization vector (updated after use)\n * \\param input    buffer holding the input data\n * \\param output   buffer holding the output data\n *\n * \\return         0 if successful, or\n *                 MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH\n */\nint mbedtls_camellia_crypt_cbc( mbedtls_camellia_context *ctx,\n                    int mode,\n                    size_t length,\n                    unsigned char iv[16],\n                    const unsigned char *input,\n                    unsigned char *output );\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n/**\n * \\brief          CAMELLIA-CFB128 buffer encryption/decryption\n *\n * Note: Due to the nature of CFB you should use the same key schedule for\n * both encryption and decryption. So a context initialized with\n * mbedtls_camellia_setkey_enc() for both MBEDTLS_CAMELLIA_ENCRYPT and CAMELLIE_DECRYPT.\n *\n * \\note           Upon exit, the content of the IV is updated so that you can\n *                 call the function same function again on the following\n *                 block(s) of data and get the same result as if it was\n *                 encrypted in one call. This allows a \"streaming\" usage.\n *                 If on the other hand you need to retain the contents of the\n *                 IV, you should either save it manually or use the cipher\n *                 module instead.\n *\n * \\param ctx      CAMELLIA context\n * \\param mode     MBEDTLS_CAMELLIA_ENCRYPT or MBEDTLS_CAMELLIA_DECRYPT\n * \\param length   length of the input data\n * \\param iv_off   offset in IV (updated after use)\n * \\param iv       initialization vector (updated after use)\n * \\param input    buffer holding the input data\n * \\param output   buffer holding the output data\n *\n * \\return         0 if successful, or\n *                 MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH\n */\nint mbedtls_camellia_crypt_cfb128( mbedtls_camellia_context *ctx,\n                       int mode,\n                       size_t length,\n                       size_t *iv_off,\n                       unsigned char iv[16],\n                       const unsigned char *input,\n                       unsigned char *output );\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n/**\n * \\brief               CAMELLIA-CTR buffer encryption/decryption\n *\n * Note: Due to the nature of CTR you should use the same key schedule for\n * both encryption and decryption. So a context initialized with\n * mbedtls_camellia_setkey_enc() for both MBEDTLS_CAMELLIA_ENCRYPT and MBEDTLS_CAMELLIA_DECRYPT.\n *\n * \\warning    You must never reuse a nonce value with the same key. Doing so\n *             would void the encryption for the two messages encrypted with\n *             the same nonce and key.\n *\n *             There are two common strategies for managing nonces with CTR:\n *\n *             1. You can handle everything as a single message processed over\n *             successive calls to this function. In that case, you want to\n *             set \\p nonce_counter and \\p nc_off to 0 for the first call, and\n *             then preserve the values of \\p nonce_counter, \\p nc_off and \\p\n *             stream_block across calls to this function as they will be\n *             updated by this function.\n *\n *             With this strategy, you must not encrypt more than 2**128\n *             blocks of data with the same key.\n *\n *             2. You can encrypt separate messages by dividing the \\p\n *             nonce_counter buffer in two areas: the first one used for a\n *             per-message nonce, handled by yourself, and the second one\n *             updated by this function internally.\n *\n *             For example, you might reserve the first 12 bytes for the\n *             per-message nonce, and the last 4 bytes for internal use. In that\n *             case, before calling this function on a new message you need to\n *             set the first 12 bytes of \\p nonce_counter to your chosen nonce\n *             value, the last 4 to 0, and \\p nc_off to 0 (which will cause \\p\n *             stream_block to be ignored). That way, you can encrypt at most\n *             2**96 messages of up to 2**32 blocks each with the same key.\n *\n *             The per-message nonce (or information sufficient to reconstruct\n *             it) needs to be communicated with the ciphertext and must be unique.\n *             The recommended way to ensure uniqueness is to use a message\n *             counter. An alternative is to generate random nonces, but this\n *             limits the number of messages that can be securely encrypted:\n *             for example, with 96-bit random nonces, you should not encrypt\n *             more than 2**32 messages with the same key.\n *\n *             Note that for both stategies, sizes are measured in blocks and\n *             that a CAMELLIA block is 16 bytes.\n *\n * \\warning    Upon return, \\p stream_block contains sensitive data. Its\n *             content must not be written to insecure storage and should be\n *             securely discarded as soon as it's no longer needed.\n *\n * \\param ctx           CAMELLIA context\n * \\param length        The length of the data\n * \\param nc_off        The offset in the current stream_block (for resuming\n *                      within current cipher stream). The offset pointer to\n *                      should be 0 at the start of a stream.\n * \\param nonce_counter The 128-bit nonce and counter.\n * \\param stream_block  The saved stream-block for resuming. Is overwritten\n *                      by the function.\n * \\param input         The input data stream\n * \\param output        The output data stream\n *\n * \\return         0 if successful\n */\nint mbedtls_camellia_crypt_ctr( mbedtls_camellia_context *ctx,\n                       size_t length,\n                       size_t *nc_off,\n                       unsigned char nonce_counter[16],\n                       unsigned char stream_block[16],\n                       const unsigned char *input,\n                       unsigned char *output );\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\n/**\n * \\brief          Checkup routine\n *\n * \\return         0 if successful, or 1 if the test failed\n */\nint mbedtls_camellia_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* camellia.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/ccm.h",
    "content": "/**\n * \\file ccm.h\n *\n * \\brief This file provides an API for the CCM authenticated encryption\n *        mode for block ciphers.\n *\n * CCM combines Counter mode encryption with CBC-MAC authentication\n * for 128-bit block ciphers.\n *\n * Input to CCM includes the following elements:\n * <ul><li>Payload - data that is both authenticated and encrypted.</li>\n * <li>Associated data (Adata) - data that is authenticated but not\n * encrypted, For example, a header.</li>\n * <li>Nonce - A unique value that is assigned to the payload and the\n * associated data.</li></ul>\n *\n * Definition of CCM:\n * http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf\n * RFC 3610 \"Counter with CBC-MAC (CCM)\"\n *\n * Related:\n * RFC 5116 \"An Interface and Algorithms for Authenticated Encryption\"\n *\n * Definition of CCM*:\n * IEEE 802.15.4 - IEEE Standard for Local and metropolitan area networks\n * Integer representation is fixed most-significant-octet-first order and\n * the representation of octets is most-significant-bit-first order. This is\n * consistent with RFC 3610.\n */\n/*\n *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_CCM_H\n#define MBEDTLS_CCM_H\n\n#include \"cipher.h\"\n\n#define MBEDTLS_ERR_CCM_BAD_INPUT       -0x000D /**< Bad input parameters to the function. */\n#define MBEDTLS_ERR_CCM_AUTH_FAILED     -0x000F /**< Authenticated decryption failed. */\n#define MBEDTLS_ERR_CCM_HW_ACCEL_FAILED -0x0011 /**< CCM hardware accelerator failed. */\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_CCM_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief    The CCM context-type definition. The CCM context is passed\n *           to the APIs called.\n */\ntypedef struct {\n    mbedtls_cipher_context_t cipher_ctx;    /*!< The cipher context used. */\n}\nmbedtls_ccm_context;\n\n#else  /* MBEDTLS_CCM_ALT */\n#include \"ccm_alt.h\"\n#endif /* MBEDTLS_CCM_ALT */\n\n/**\n * \\brief           This function initializes the specified CCM context,\n *                  to make references valid, and prepare the context\n *                  for mbedtls_ccm_setkey() or mbedtls_ccm_free().\n *\n * \\param ctx       The CCM context to initialize.\n */\nvoid mbedtls_ccm_init( mbedtls_ccm_context *ctx );\n\n/**\n * \\brief           This function initializes the CCM context set in the\n *                  \\p ctx parameter and sets the encryption key.\n *\n * \\param ctx       The CCM context to initialize.\n * \\param cipher    The 128-bit block cipher to use.\n * \\param key       The encryption key.\n * \\param keybits   The key size in bits. This must be acceptable by the cipher.\n *\n * \\return          \\c 0 on success.\n * \\return          A CCM or cipher-specific error code on failure.\n */\nint mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,\n                        mbedtls_cipher_id_t cipher,\n                        const unsigned char *key,\n                        unsigned int keybits );\n\n/**\n * \\brief   This function releases and clears the specified CCM context\n *          and underlying cipher sub-context.\n *\n * \\param ctx       The CCM context to clear.\n */\nvoid mbedtls_ccm_free( mbedtls_ccm_context *ctx );\n\n/**\n * \\brief           This function encrypts a buffer using CCM.\n *\n * \\note            The tag is written to a separate buffer. To concatenate\n *                  the \\p tag with the \\p output, as done in <em>RFC-3610:\n *                  Counter with CBC-MAC (CCM)</em>, use\n *                  \\p tag = \\p output + \\p length, and make sure that the\n *                  output buffer is at least \\p length + \\p tag_len wide.\n *\n * \\param ctx       The CCM context to use for encryption.\n * \\param length    The length of the input data in Bytes.\n * \\param iv        Initialization vector (nonce).\n * \\param iv_len    The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,\n *                  or 13. The length L of the message length field is\n *                  15 - \\p iv_len.\n * \\param add       The additional data field.\n * \\param add_len   The length of additional data in Bytes.\n *                  Must be less than 2^16 - 2^8.\n * \\param input     The buffer holding the input data.\n * \\param output    The buffer holding the output data.\n *                  Must be at least \\p length Bytes wide.\n * \\param tag       The buffer holding the authentication field.\n * \\param tag_len   The length of the authentication field to generate in Bytes:\n *                  4, 6, 8, 10, 12, 14 or 16.\n *\n * \\return          \\c 0 on success.\n * \\return          A CCM or cipher-specific error code on failure.\n */\nint mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,\n                         const unsigned char *iv, size_t iv_len,\n                         const unsigned char *add, size_t add_len,\n                         const unsigned char *input, unsigned char *output,\n                         unsigned char *tag, size_t tag_len );\n\n/**\n * \\brief           This function encrypts a buffer using CCM*.\n *\n * \\note            The tag is written to a separate buffer. To concatenate\n *                  the \\p tag with the \\p output, as done in <em>RFC-3610:\n *                  Counter with CBC-MAC (CCM)</em>, use\n *                  \\p tag = \\p output + \\p length, and make sure that the\n *                  output buffer is at least \\p length + \\p tag_len wide.\n *\n * \\note            When using this function in a variable tag length context,\n *                  the tag length has to be encoded into the \\p iv passed to\n *                  this function.\n *\n * \\param ctx       The CCM context to use for encryption.\n * \\param length    The length of the input data in Bytes.\n * \\param iv        Initialization vector (nonce).\n * \\param iv_len    The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,\n *                  or 13. The length L of the message length field is\n *                  15 - \\p iv_len.\n * \\param add       The additional data field.\n * \\param add_len   The length of additional data in Bytes.\n *                  Must be less than 2^16 - 2^8.\n * \\param input     The buffer holding the input data.\n * \\param output    The buffer holding the output data.\n *                  Must be at least \\p length Bytes wide.\n * \\param tag       The buffer holding the authentication field.\n * \\param tag_len   The length of the authentication field to generate in Bytes:\n *                  0, 4, 6, 8, 10, 12, 14 or 16.\n *\n * \\warning         Passing 0 as \\p tag_len means that the message is no\n *                  longer authenticated.\n *\n * \\return          \\c 0 on success.\n * \\return          A CCM or cipher-specific error code on failure.\n */\nint mbedtls_ccm_star_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,\n                         const unsigned char *iv, size_t iv_len,\n                         const unsigned char *add, size_t add_len,\n                         const unsigned char *input, unsigned char *output,\n                         unsigned char *tag, size_t tag_len );\n\n/**\n * \\brief           This function performs a CCM authenticated decryption of a\n *                  buffer.\n *\n * \\param ctx       The CCM context to use for decryption.\n * \\param length    The length of the input data in Bytes.\n * \\param iv        Initialization vector (nonce).\n * \\param iv_len    The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,\n *                  or 13. The length L of the message length field is\n *                  15 - \\p iv_len.\n * \\param add       The additional data field.\n * \\param add_len   The length of additional data in Bytes.\n *                  Must be less than 2^16 - 2^8.\n * \\param input     The buffer holding the input data.\n * \\param output    The buffer holding the output data.\n *                  Must be at least \\p length Bytes wide.\n * \\param tag       The buffer holding the authentication field.\n * \\param tag_len   The length of the authentication field in Bytes.\n *                  4, 6, 8, 10, 12, 14 or 16.\n *\n * \\return          \\c 0 on success. This indicates that the message is authentic.\n * \\return          #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match.\n * \\return          A cipher-specific error code on calculation failure.\n */\nint mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,\n                      const unsigned char *iv, size_t iv_len,\n                      const unsigned char *add, size_t add_len,\n                      const unsigned char *input, unsigned char *output,\n                      const unsigned char *tag, size_t tag_len );\n\n/**\n * \\brief           This function performs a CCM* authenticated decryption of a\n *                  buffer.\n *\n * \\note            When using this function in a variable tag length context,\n *                  the tag length has to be decoded from \\p iv and passed to\n *                  this function as \\p tag_len. (\\p tag needs to be adjusted\n *                  accordingly.)\n *\n * \\param ctx       The CCM context to use for decryption.\n * \\param length    The length of the input data in Bytes.\n * \\param iv        Initialization vector (nonce).\n * \\param iv_len    The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,\n *                  or 13. The length L of the message length field is\n *                  15 - \\p iv_len.\n * \\param add       The additional data field.\n * \\param add_len   The length of additional data in Bytes.\n *                  Must be less than 2^16 - 2^8.\n * \\param input     The buffer holding the input data.\n * \\param output    The buffer holding the output data.\n *                  Must be at least \\p length Bytes wide.\n * \\param tag       The buffer holding the authentication field.\n * \\param tag_len   The length of the authentication field in Bytes.\n *                  0, 4, 6, 8, 10, 12, 14 or 16.\n *\n * \\warning         Passing 0 as \\p tag_len means that the message is no\n *                  longer authenticated.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match.\n * \\return          A cipher-specific error code on calculation failure.\n */\nint mbedtls_ccm_star_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,\n                      const unsigned char *iv, size_t iv_len,\n                      const unsigned char *add, size_t add_len,\n                      const unsigned char *input, unsigned char *output,\n                      const unsigned char *tag, size_t tag_len );\n\n#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)\n/**\n * \\brief          The CCM checkup routine.\n *\n * \\return         \\c 0 on success.\n * \\return         \\c 1 on failure.\n */\nint mbedtls_ccm_self_test( int verbose );\n#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* MBEDTLS_CCM_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/certs.h",
    "content": "/**\n * \\file certs.h\n *\n * \\brief Sample certificates and DHM parameters for testing\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_CERTS_H\n#define MBEDTLS_CERTS_H\n\n#include <stddef.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if defined(MBEDTLS_PEM_PARSE_C)\n/* Concatenation of all CA certificates in PEM format if available */\nextern const char   mbedtls_test_cas_pem[];\nextern const size_t mbedtls_test_cas_pem_len;\n#endif\n\n/* List of all CA certificates, terminated by NULL */\nextern const char * mbedtls_test_cas[];\nextern const size_t mbedtls_test_cas_len[];\n\n/*\n * Convenience for users who just want a certificate:\n * RSA by default, or ECDSA if RSA is not available\n */\nextern const char * mbedtls_test_ca_crt;\nextern const size_t mbedtls_test_ca_crt_len;\nextern const char * mbedtls_test_ca_key;\nextern const size_t mbedtls_test_ca_key_len;\nextern const char * mbedtls_test_ca_pwd;\nextern const size_t mbedtls_test_ca_pwd_len;\nextern const char * mbedtls_test_srv_crt;\nextern const size_t mbedtls_test_srv_crt_len;\nextern const char * mbedtls_test_srv_key;\nextern const size_t mbedtls_test_srv_key_len;\nextern const char * mbedtls_test_cli_crt;\nextern const size_t mbedtls_test_cli_crt_len;\nextern const char * mbedtls_test_cli_key;\nextern const size_t mbedtls_test_cli_key_len;\n\n#if defined(MBEDTLS_ECDSA_C)\nextern const char   mbedtls_test_ca_crt_ec[];\nextern const size_t mbedtls_test_ca_crt_ec_len;\nextern const char   mbedtls_test_ca_key_ec[];\nextern const size_t mbedtls_test_ca_key_ec_len;\nextern const char   mbedtls_test_ca_pwd_ec[];\nextern const size_t mbedtls_test_ca_pwd_ec_len;\nextern const char   mbedtls_test_srv_crt_ec[];\nextern const size_t mbedtls_test_srv_crt_ec_len;\nextern const char   mbedtls_test_srv_key_ec[];\nextern const size_t mbedtls_test_srv_key_ec_len;\nextern const char   mbedtls_test_cli_crt_ec[];\nextern const size_t mbedtls_test_cli_crt_ec_len;\nextern const char   mbedtls_test_cli_key_ec[];\nextern const size_t mbedtls_test_cli_key_ec_len;\n#endif\n\n#if defined(MBEDTLS_RSA_C)\nextern const char   mbedtls_test_ca_crt_rsa[];\nextern const size_t mbedtls_test_ca_crt_rsa_len;\nextern const char   mbedtls_test_ca_key_rsa[];\nextern const size_t mbedtls_test_ca_key_rsa_len;\nextern const char   mbedtls_test_ca_pwd_rsa[];\nextern const size_t mbedtls_test_ca_pwd_rsa_len;\nextern const char   mbedtls_test_srv_crt_rsa[];\nextern const size_t mbedtls_test_srv_crt_rsa_len;\nextern const char   mbedtls_test_srv_key_rsa[];\nextern const size_t mbedtls_test_srv_key_rsa_len;\nextern const char   mbedtls_test_cli_crt_rsa[];\nextern const size_t mbedtls_test_cli_crt_rsa_len;\nextern const char   mbedtls_test_cli_key_rsa[];\nextern const size_t mbedtls_test_cli_key_rsa_len;\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* certs.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/chacha20.h",
    "content": "/**\n * \\file chacha20.h\n *\n * \\brief   This file contains ChaCha20 definitions and functions.\n *\n *          ChaCha20 is a stream cipher that can encrypt and decrypt\n *          information. ChaCha was created by Daniel Bernstein as a variant of\n *          its Salsa cipher https://cr.yp.to/chacha/chacha-20080128.pdf\n *          ChaCha20 is the variant with 20 rounds, that was also standardized\n *          in RFC 7539.\n *\n * \\author Daniel King <damaki.gh@gmail.com>\n */\n\n/*  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved.\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_CHACHA20_H\n#define MBEDTLS_CHACHA20_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stdint.h>\n#include <stddef.h>\n\n#define MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA         -0x0051 /**< Invalid input parameter(s). */\n#define MBEDTLS_ERR_CHACHA20_FEATURE_UNAVAILABLE    -0x0053 /**< Feature not available. For example, s part of the API is not implemented. */\n#define MBEDTLS_ERR_CHACHA20_HW_ACCEL_FAILED        -0x0055  /**< Chacha20 hardware accelerator failed. */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_CHACHA20_ALT)\n\ntypedef struct\n{\n    uint32_t state[16];          /*! The state (before round operations). */\n    uint8_t  keystream8[64];     /*! Leftover keystream bytes. */\n    size_t keystream_bytes_used; /*! Number of keystream bytes already used. */\n}\nmbedtls_chacha20_context;\n\n#else  /* MBEDTLS_CHACHA20_ALT */\n#include \"chacha20_alt.h\"\n#endif /* MBEDTLS_CHACHA20_ALT */\n\n/**\n * \\brief           This function initializes the specified ChaCha20 context.\n *\n *                  It must be the first API called before using\n *                  the context.\n *\n *                  It is usually followed by calls to\n *                  \\c mbedtls_chacha20_setkey() and\n *                  \\c mbedtls_chacha20_starts(), then one or more calls to\n *                  to \\c mbedtls_chacha20_update(), and finally to\n *                  \\c mbedtls_chacha20_free().\n *\n * \\param ctx       The ChaCha20 context to initialize.\n */\nvoid mbedtls_chacha20_init( mbedtls_chacha20_context *ctx );\n\n/**\n * \\brief           This function releases and clears the specified ChaCha20 context.\n *\n * \\param ctx       The ChaCha20 context to clear.\n */\nvoid mbedtls_chacha20_free( mbedtls_chacha20_context *ctx );\n\n/**\n * \\brief           This function sets the encryption/decryption key.\n *\n * \\note            After using this function, you must also call\n *                  \\c mbedtls_chacha20_starts() to set a nonce before you\n *                  start encrypting/decrypting data with\n *                  \\c mbedtls_chacha_update().\n *\n * \\param ctx       The ChaCha20 context to which the key should be bound.\n * \\param key       The encryption/decryption key. Must be 32 bytes in length.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if ctx or key is NULL.\n */\nint mbedtls_chacha20_setkey( mbedtls_chacha20_context *ctx,\n                             const unsigned char key[32] );\n\n/**\n * \\brief           This function sets the nonce and initial counter value.\n *\n * \\note            A ChaCha20 context can be re-used with the same key by\n *                  calling this function to change the nonce.\n *\n * \\warning         You must never use the same nonce twice with the same key.\n *                  This would void any confidentiality guarantees for the\n *                  messages encrypted with the same nonce and key.\n *\n * \\param ctx       The ChaCha20 context to which the nonce should be bound.\n * \\param nonce     The nonce. Must be 12 bytes in size.\n * \\param counter   The initial counter value. This is usually 0.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if ctx or nonce is\n *                  NULL.\n */\nint mbedtls_chacha20_starts( mbedtls_chacha20_context* ctx,\n                             const unsigned char nonce[12],\n                             uint32_t counter );\n\n/**\n * \\brief           This function encrypts or decrypts data.\n *\n *                  Since ChaCha20 is a stream cipher, the same operation is\n *                  used for encrypting and decrypting data.\n *\n * \\note            The \\p input and \\p output pointers must either be equal or\n *                  point to non-overlapping buffers.\n *\n * \\note            \\c mbedtls_chacha20_setkey() and\n *                  \\c mbedtls_chacha20_starts() must be called at least once\n *                  to setup the context before this function can be called.\n *\n * \\note            This function can be called multiple times in a row in\n *                  order to encrypt of decrypt data piecewise with the same\n *                  key and nonce.\n *\n * \\param ctx       The ChaCha20 context to use for encryption or decryption.\n * \\param size      The length of the input data in bytes.\n * \\param input     The buffer holding the input data.\n *                  This pointer can be NULL if size == 0.\n * \\param output    The buffer holding the output data.\n *                  Must be able to hold \\p size bytes.\n *                  This pointer can be NULL if size == 0.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if the ctx, input, or\n *                  output pointers are NULL.\n */\nint mbedtls_chacha20_update( mbedtls_chacha20_context *ctx,\n                             size_t size,\n                             const unsigned char *input,\n                             unsigned char *output );\n\n/**\n * \\brief           This function encrypts or decrypts data with ChaCha20 and\n *                  the given key and nonce.\n *\n *                  Since ChaCha20 is a stream cipher, the same operation is\n *                  used for encrypting and decrypting data.\n *\n * \\warning         You must never use the same (key, nonce) pair more than\n *                  once. This would void any confidentiality guarantees for\n *                  the messages encrypted with the same nonce and key.\n *\n * \\note            The \\p input and \\p output pointers must either be equal or\n *                  point to non-overlapping buffers.\n *\n * \\param key       The encryption/decryption key. Must be 32 bytes in length.\n * \\param nonce     The nonce. Must be 12 bytes in size.\n * \\param counter   The initial counter value. This is usually 0.\n * \\param size      The length of the input data in bytes.\n * \\param input     The buffer holding the input data.\n *                  This pointer can be NULL if size == 0.\n * \\param output    The buffer holding the output data.\n *                  Must be able to hold \\p size bytes.\n *                  This pointer can be NULL if size == 0.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if key, nonce, input,\n *                  or output is NULL.\n */\nint mbedtls_chacha20_crypt( const unsigned char key[32],\n                            const unsigned char nonce[12],\n                            uint32_t counter,\n                            size_t size,\n                            const unsigned char* input,\n                            unsigned char* output );\n\n#if defined(MBEDTLS_SELF_TEST)\n/**\n * \\brief           The ChaCha20 checkup routine.\n *\n * \\return          \\c 0 on success.\n * \\return          \\c 1 on failure.\n */\nint mbedtls_chacha20_self_test( int verbose );\n#endif /* MBEDTLS_SELF_TEST */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* MBEDTLS_CHACHA20_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/chachapoly.h",
    "content": "/**\n * \\file chachapoly.h\n *\n * \\brief   This file contains the AEAD-ChaCha20-Poly1305 definitions and\n *          functions.\n *\n *          ChaCha20-Poly1305 is an algorithm for Authenticated Encryption\n *          with Associated Data (AEAD) that can be used to encrypt and\n *          authenticate data. It is based on ChaCha20 and Poly1305 by Daniel\n *          Bernstein and was standardized in RFC 7539.\n *\n * \\author Daniel King <damaki.gh@gmail.com>\n */\n\n/*  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved.\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_CHACHAPOLY_H\n#define MBEDTLS_CHACHAPOLY_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n/* for shared error codes */\n#include \"poly1305.h\"\n\n#define MBEDTLS_ERR_CHACHAPOLY_BAD_STATE            -0x0054 /**< The requested operation is not permitted in the current state. */\n#define MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED          -0x0056 /**< Authenticated decryption failed: data was not authentic. */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef enum\n{\n    MBEDTLS_CHACHAPOLY_ENCRYPT,     /**< The mode value for performing encryption. */\n    MBEDTLS_CHACHAPOLY_DECRYPT      /**< The mode value for performing decryption. */\n}\nmbedtls_chachapoly_mode_t;\n\n#if !defined(MBEDTLS_CHACHAPOLY_ALT)\n\n#include \"chacha20.h\"\n\ntypedef struct\n{\n    mbedtls_chacha20_context chacha20_ctx;  /**< The ChaCha20 context. */\n    mbedtls_poly1305_context poly1305_ctx;  /**< The Poly1305 context. */\n    uint64_t aad_len;                       /**< The length (bytes) of the Additional Authenticated Data. */\n    uint64_t ciphertext_len;                /**< The length (bytes) of the ciphertext. */\n    int state;                              /**< The current state of the context. */\n    mbedtls_chachapoly_mode_t mode;         /**< Cipher mode (encrypt or decrypt). */\n}\nmbedtls_chachapoly_context;\n\n#else /* !MBEDTLS_CHACHAPOLY_ALT */\n#include \"chachapoly_alt.h\"\n#endif /* !MBEDTLS_CHACHAPOLY_ALT */\n\n/**\n * \\brief           This function initializes the specified ChaCha20-Poly1305 context.\n *\n *                  It must be the first API called before using\n *                  the context. It must be followed by a call to\n *                  \\c mbedtls_chachapoly_setkey() before any operation can be\n *                  done, and to \\c mbedtls_chachapoly_free() once all\n *                  operations with that context have been finished.\n *\n *                  In order to encrypt or decrypt full messages at once, for\n *                  each message you should make a single call to\n *                  \\c mbedtls_chachapoly_crypt_and_tag() or\n *                  \\c mbedtls_chachapoly_auth_decrypt().\n *\n *                  In order to encrypt messages piecewise, for each\n *                  message you should make a call to\n *                  \\c mbedtls_chachapoly_starts(), then 0 or more calls to\n *                  \\c mbedtls_chachapoly_update_aad(), then 0 or more calls to\n *                  \\c mbedtls_chachapoly_update(), then one call to\n *                  \\c mbedtls_chachapoly_finish().\n *\n * \\warning         Decryption with the piecewise API is discouraged! Always\n *                  use \\c mbedtls_chachapoly_auth_decrypt() when possible!\n *\n *                  If however this is not possible because the data is too\n *                  large to fit in memory, you need to:\n *\n *                  - call \\c mbedtls_chachapoly_starts() and (if needed)\n *                  \\c mbedtls_chachapoly_update_aad() as above,\n *                  - call \\c mbedtls_chachapoly_update() multiple times and\n *                  ensure its output (the plaintext) is NOT used in any other\n *                  way than placing it in temporary storage at this point,\n *                  - call \\c mbedtls_chachapoly_finish() to compute the\n *                  authentication tag and compared it in constant time to the\n *                  tag received with the ciphertext.\n *\n *                  If the tags are not equal, you must immediately discard\n *                  all previous outputs of \\c mbedtls_chachapoly_update(),\n *                  otherwise you can now safely use the plaintext.\n *\n * \\param ctx       The ChachaPoly context to initialize.\n */\nvoid mbedtls_chachapoly_init( mbedtls_chachapoly_context *ctx );\n\n/**\n * \\brief           This function releases and clears the specified ChaCha20-Poly1305 context.\n *\n * \\param ctx       The ChachaPoly context to clear.\n */\nvoid mbedtls_chachapoly_free( mbedtls_chachapoly_context *ctx );\n\n/**\n * \\brief           This function sets the ChaCha20-Poly1305 symmetric encryption key.\n *\n * \\param ctx       The ChaCha20-Poly1305 context to which the key should be\n *                  bound.\n * \\param key       The 256-bit (32 bytes) key.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA\n *                  if \\p ctx or \\p key are NULL.\n */\nint mbedtls_chachapoly_setkey( mbedtls_chachapoly_context *ctx,\n                               const unsigned char key[32] );\n\n/**\n * \\brief           This function starts a ChaCha20-Poly1305 encryption or\n *                  decryption operation.\n *\n * \\warning         You must never use the same nonce twice with the same key.\n *                  This would void any confidentiality and authenticity\n *                  guarantees for the messages encrypted with the same nonce\n *                  and key.\n *\n * \\note            If the context is being used for AAD only (no data to\n *                  encrypt or decrypt) then \\p mode can be set to any value.\n *\n * \\warning         Decryption with the piecewise API is discouraged, see the\n *                  warning on \\c mbedtls_chachapoly_init().\n *\n * \\param ctx       The ChaCha20-Poly1305 context.\n * \\param nonce     The nonce/IV to use for the message. Must be 12 bytes.\n * \\param mode      The operation to perform: #MBEDTLS_CHACHAPOLY_ENCRYPT or\n *                  #MBEDTLS_CHACHAPOLY_DECRYPT (discouraged, see warning).\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA\n *                  if \\p ctx or \\p mac are NULL.\n */\nint mbedtls_chachapoly_starts( mbedtls_chachapoly_context *ctx,\n                               const unsigned char nonce[12],\n                               mbedtls_chachapoly_mode_t mode );\n\n/**\n * \\brief           This function feeds additional data to be authenticated\n *                  into an ongoing ChaCha20-Poly1305 operation.\n *\n *                  The Additional Authenticated Data (AAD), also called\n *                  Associated Data (AD) is only authenticated but not\n *                  encrypted nor included in the encrypted output. It is\n *                  usually transmitted separately from the ciphertext or\n *                  computed locally by each party.\n *\n * \\note            This function is called before data is encrypted/decrypted.\n *                  I.e. call this function to process the AAD before calling\n *                  \\c mbedtls_chachapoly_update().\n *\n *                  You may call this function multiple times to process\n *                  an arbitrary amount of AAD. It is permitted to call\n *                  this function 0 times, if no AAD is used.\n *\n *                  This function cannot be called any more if data has\n *                  been processed by \\c mbedtls_chachapoly_update(),\n *                  or if the context has been finished.\n *\n * \\warning         Decryption with the piecewise API is discouraged, see the\n *                  warning on \\c mbedtls_chachapoly_init().\n *\n * \\param ctx       The ChaCha20-Poly1305 context to use.\n * \\param aad_len   The length (in bytes) of the AAD. The length has no\n *                  restrictions.\n * \\param aad       Buffer containing the AAD.\n *                  This pointer can be NULL if aad_len == 0.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA\n *                  if \\p ctx or \\p aad are NULL.\n * \\return          #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE\n *                  if the operations has not been started or has been\n *                  finished, or if the AAD has been finished.\n */\nint mbedtls_chachapoly_update_aad( mbedtls_chachapoly_context *ctx,\n                                   const unsigned char *aad,\n                                   size_t aad_len );\n\n/**\n * \\brief           Thus function feeds data to be encrypted or decrypted\n *                  into an on-going ChaCha20-Poly1305\n *                  operation.\n *\n *                  The direction (encryption or decryption) depends on the\n *                  mode that was given when calling\n *                  \\c mbedtls_chachapoly_starts().\n *\n *                  You may call this function multiple times to process\n *                  an arbitrary amount of data. It is permitted to call\n *                  this function 0 times, if no data is to be encrypted\n *                  or decrypted.\n *\n * \\warning         Decryption with the piecewise API is discouraged, see the\n *                  warning on \\c mbedtls_chachapoly_init().\n *\n * \\param ctx       The ChaCha20-Poly1305 context to use.\n * \\param len       The length (in bytes) of the data to encrypt or decrypt.\n * \\param input     The buffer containing the data to encrypt or decrypt.\n *                  This pointer can be NULL if len == 0.\n * \\param output    The buffer to where the encrypted or decrypted data is written.\n *                  Must be able to hold \\p len bytes.\n *                  This pointer can be NULL if len == 0.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA\n *                  if \\p ctx, \\p input, or \\p output are NULL.\n * \\return          #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE\n *                  if the operation has not been started or has been\n *                  finished.\n */\nint mbedtls_chachapoly_update( mbedtls_chachapoly_context *ctx,\n                               size_t len,\n                               const unsigned char *input,\n                               unsigned char *output );\n\n/**\n * \\brief           This function finished the ChaCha20-Poly1305 operation and\n *                  generates the MAC (authentication tag).\n *\n * \\param ctx       The ChaCha20-Poly1305 context to use.\n * \\param mac       The buffer to where the 128-bit (16 bytes) MAC is written.\n *\n * \\warning         Decryption with the piecewise API is discouraged, see the\n *                  warning on \\c mbedtls_chachapoly_init().\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA\n *                  if \\p ctx or \\p mac are NULL.\n * \\return          #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE\n *                  if the operation has not been started or has been\n *                  finished.\n */\nint mbedtls_chachapoly_finish( mbedtls_chachapoly_context *ctx,\n                               unsigned char mac[16] );\n\n/**\n * \\brief           This function performs a complete ChaCha20-Poly1305\n *                  authenticated encryption with the previously-set key.\n *\n * \\note            Before using this function, you must set the key with\n *                  \\c mbedtls_chachapoly_setkey().\n *\n * \\warning         You must never use the same nonce twice with the same key.\n *                  This would void any confidentiality and authenticity\n *                  guarantees for the messages encrypted with the same nonce\n *                  and key.\n *\n * \\param ctx       The ChaCha20-Poly1305 context to use (holds the key).\n * \\param length    The length (in bytes) of the data to encrypt or decrypt.\n * \\param nonce     The 96-bit (12 bytes) nonce/IV to use.\n * \\param aad       The buffer containing the additional authenticated data (AAD).\n *                  This pointer can be NULL if aad_len == 0.\n * \\param aad_len   The length (in bytes) of the AAD data to process.\n * \\param input     The buffer containing the data to encrypt or decrypt.\n *                  This pointer can be NULL if ilen == 0.\n * \\param output    The buffer to where the encrypted or decrypted data is written.\n *                  This pointer can be NULL if ilen == 0.\n * \\param tag       The buffer to where the computed 128-bit (16 bytes) MAC is written.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA\n *                  if one or more of the required parameters are NULL.\n */\nint mbedtls_chachapoly_encrypt_and_tag( mbedtls_chachapoly_context *ctx,\n                                        size_t length,\n                                        const unsigned char nonce[12],\n                                        const unsigned char *aad,\n                                        size_t aad_len,\n                                        const unsigned char *input,\n                                        unsigned char *output,\n                                        unsigned char tag[16] );\n\n/**\n * \\brief           This function performs a complete ChaCha20-Poly1305\n *                  authenticated decryption with the previously-set key.\n *\n * \\note            Before using this function, you must set the key with\n *                  \\c mbedtls_chachapoly_setkey().\n *\n * \\param ctx       The ChaCha20-Poly1305 context to use (holds the key).\n * \\param length    The length (in bytes) of the data to decrypt.\n * \\param nonce     The 96-bit (12 bytes) nonce/IV to use.\n * \\param aad       The buffer containing the additional authenticated data (AAD).\n *                  This pointer can be NULL if aad_len == 0.\n * \\param aad_len   The length (in bytes) of the AAD data to process.\n * \\param tag       The buffer holding the authentication tag.\n * \\param input     The buffer containing the data to decrypt.\n *                  This pointer can be NULL if ilen == 0.\n * \\param output    The buffer to where the decrypted data is written.\n *                  This pointer can be NULL if ilen == 0.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA\n *                  if one or more of the required parameters are NULL.\n * \\return          #MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED\n *                  if the data was not authentic.\n */\nint mbedtls_chachapoly_auth_decrypt( mbedtls_chachapoly_context *ctx,\n                                     size_t length,\n                                     const unsigned char nonce[12],\n                                     const unsigned char *aad,\n                                     size_t aad_len,\n                                     const unsigned char tag[16],\n                                     const unsigned char *input,\n                                     unsigned char *output );\n\n#if defined(MBEDTLS_SELF_TEST)\n/**\n * \\brief           The ChaCha20-Poly1305 checkup routine.\n *\n * \\return          \\c 0 on success.\n * \\return          \\c 1 on failure.\n */\nint mbedtls_chachapoly_self_test( int verbose );\n#endif /* MBEDTLS_SELF_TEST */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* MBEDTLS_CHACHAPOLY_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/check_config.h",
    "content": "/**\n * \\file check_config.h\n *\n * \\brief Consistency checks for configuration options\n */\n/*\n *  Copyright (C) 2006-2018, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n/*\n * It is recommended to include this file from your config.h\n * in order to catch dependency issues early.\n */\n\n#ifndef MBEDTLS_CHECK_CONFIG_H\n#define MBEDTLS_CHECK_CONFIG_H\n\n/*\n * We assume CHAR_BIT is 8 in many places. In practice, this is true on our\n * target platforms, so not an issue, but let's just be extra sure.\n */\n#include <limits.h>\n#if CHAR_BIT != 8\n#error \"mbed TLS requires a platform with 8-bit chars\"\n#endif\n\n#if defined(_WIN32)\n#if !defined(MBEDTLS_PLATFORM_C)\n#error \"MBEDTLS_PLATFORM_C is required on Windows\"\n#endif\n\n/* Fix the config here. Not convenient to put an #ifdef _WIN32 in config.h as\n * it would confuse config.pl. */\n#if !defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) && \\\n    !defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO)\n#define MBEDTLS_PLATFORM_SNPRINTF_ALT\n#endif\n#endif /* _WIN32 */\n\n#if defined(TARGET_LIKE_MBED) && \\\n    ( defined(MBEDTLS_NET_C) || defined(MBEDTLS_TIMING_C) )\n#error \"The NET and TIMING modules are not available for mbed OS - please use the network and timing functions provided by mbed OS\"\n#endif\n\n#if defined(MBEDTLS_DEPRECATED_WARNING) && \\\n    !defined(__GNUC__) && !defined(__clang__)\n#error \"MBEDTLS_DEPRECATED_WARNING only works with GCC and Clang\"\n#endif\n\n#if defined(MBEDTLS_HAVE_TIME_DATE) && !defined(MBEDTLS_HAVE_TIME)\n#error \"MBEDTLS_HAVE_TIME_DATE without MBEDTLS_HAVE_TIME does not make sense\"\n#endif\n\n#if defined(MBEDTLS_AESNI_C) && !defined(MBEDTLS_HAVE_ASM)\n#error \"MBEDTLS_AESNI_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_CTR_DRBG_C) && !defined(MBEDTLS_AES_C)\n#error \"MBEDTLS_CTR_DRBG_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_DHM_C) && !defined(MBEDTLS_BIGNUM_C)\n#error \"MBEDTLS_DHM_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT) && !defined(MBEDTLS_SSL_TRUNCATED_HMAC)\n#error \"MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_CMAC_C) && \\\n    !defined(MBEDTLS_AES_C) && !defined(MBEDTLS_DES_C)\n#error \"MBEDTLS_CMAC_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_NIST_KW_C) && \\\n    ( !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CIPHER_C) )\n#error \"MBEDTLS_NIST_KW_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_ECDH_C) && !defined(MBEDTLS_ECP_C)\n#error \"MBEDTLS_ECDH_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_ECDSA_C) &&            \\\n    ( !defined(MBEDTLS_ECP_C) ||           \\\n      !defined(MBEDTLS_ASN1_PARSE_C) ||    \\\n      !defined(MBEDTLS_ASN1_WRITE_C) )\n#error \"MBEDTLS_ECDSA_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_ECJPAKE_C) &&           \\\n    ( !defined(MBEDTLS_ECP_C) || !defined(MBEDTLS_MD_C) )\n#error \"MBEDTLS_ECJPAKE_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_ECDSA_DETERMINISTIC) && !defined(MBEDTLS_HMAC_DRBG_C)\n#error \"MBEDTLS_ECDSA_DETERMINISTIC defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_ECP_C) && ( !defined(MBEDTLS_BIGNUM_C) || (   \\\n    !defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) &&                  \\\n    !defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) &&                  \\\n    !defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) &&                  \\\n    !defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) &&                  \\\n    !defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) &&                  \\\n    !defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)   &&                  \\\n    !defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)   &&                  \\\n    !defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)   &&                  \\\n    !defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) &&                  \\\n    !defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) &&                  \\\n    !defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) ) )\n#error \"MBEDTLS_ECP_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_ENTROPY_C) && (!defined(MBEDTLS_SHA512_C) &&      \\\n                                    !defined(MBEDTLS_SHA256_C))\n#error \"MBEDTLS_ENTROPY_C defined, but not all prerequisites\"\n#endif\n#if defined(MBEDTLS_ENTROPY_C) && defined(MBEDTLS_SHA512_C) &&         \\\n    defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) && (MBEDTLS_CTR_DRBG_ENTROPY_LEN > 64)\n#error \"MBEDTLS_CTR_DRBG_ENTROPY_LEN value too high\"\n#endif\n#if defined(MBEDTLS_ENTROPY_C) &&                                            \\\n    ( !defined(MBEDTLS_SHA512_C) || defined(MBEDTLS_ENTROPY_FORCE_SHA256) ) \\\n    && defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) && (MBEDTLS_CTR_DRBG_ENTROPY_LEN > 32)\n#error \"MBEDTLS_CTR_DRBG_ENTROPY_LEN value too high\"\n#endif\n#if defined(MBEDTLS_ENTROPY_C) && \\\n    defined(MBEDTLS_ENTROPY_FORCE_SHA256) && !defined(MBEDTLS_SHA256_C)\n#error \"MBEDTLS_ENTROPY_FORCE_SHA256 defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_TEST_NULL_ENTROPY) && \\\n    ( !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES) )\n#error \"MBEDTLS_TEST_NULL_ENTROPY defined, but not all prerequisites\"\n#endif\n#if defined(MBEDTLS_TEST_NULL_ENTROPY) && \\\n     ( defined(MBEDTLS_ENTROPY_NV_SEED) || defined(MBEDTLS_ENTROPY_HARDWARE_ALT) || \\\n    defined(MBEDTLS_HAVEGE_C) )\n#error \"MBEDTLS_TEST_NULL_ENTROPY defined, but entropy sources too\"\n#endif\n\n#if defined(MBEDTLS_GCM_C) && (                                        \\\n        !defined(MBEDTLS_AES_C) && !defined(MBEDTLS_CAMELLIA_C) )\n#error \"MBEDTLS_GCM_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)\n#error \"MBEDTLS_ECP_RANDOMIZE_JAC_ALT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_ECP_ADD_MIXED_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)\n#error \"MBEDTLS_ECP_ADD_MIXED_ALT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)\n#error \"MBEDTLS_ECP_DOUBLE_JAC_ALT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)\n#error \"MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)\n#error \"MBEDTLS_ECP_NORMALIZE_JAC_ALT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)\n#error \"MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)\n#error \"MBEDTLS_ECP_RANDOMIZE_MXZ_ALT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)\n#error \"MBEDTLS_ECP_NORMALIZE_MXZ_ALT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_HAVEGE_C) && !defined(MBEDTLS_TIMING_C)\n#error \"MBEDTLS_HAVEGE_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_HKDF_C) && !defined(MBEDTLS_MD_C)\n#error \"MBEDTLS_HKDF_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_HMAC_DRBG_C) && !defined(MBEDTLS_MD_C)\n#error \"MBEDTLS_HMAC_DRBG_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) &&                 \\\n    ( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) )\n#error \"MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) &&                 \\\n    ( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) )\n#error \"MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) && !defined(MBEDTLS_DHM_C)\n#error \"MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) &&                     \\\n    !defined(MBEDTLS_ECDH_C)\n#error \"MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) &&                   \\\n    ( !defined(MBEDTLS_DHM_C) || !defined(MBEDTLS_RSA_C) ||           \\\n      !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_PKCS1_V15) )\n#error \"MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) &&                 \\\n    ( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_RSA_C) ||          \\\n      !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_PKCS1_V15) )\n#error \"MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) &&                 \\\n    ( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_ECDSA_C) ||          \\\n      !defined(MBEDTLS_X509_CRT_PARSE_C) )\n#error \"MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) &&                   \\\n    ( !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) || \\\n      !defined(MBEDTLS_PKCS1_V15) )\n#error \"MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) &&                       \\\n    ( !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) || \\\n      !defined(MBEDTLS_PKCS1_V15) )\n#error \"MBEDTLS_KEY_EXCHANGE_RSA_ENABLED defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) &&                    \\\n    ( !defined(MBEDTLS_ECJPAKE_C) || !defined(MBEDTLS_SHA256_C) ||      \\\n      !defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) )\n#error \"MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) &&                          \\\n    ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_PLATFORM_MEMORY) )\n#error \"MBEDTLS_MEMORY_BUFFER_ALLOC_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PADLOCK_C) && !defined(MBEDTLS_HAVE_ASM)\n#error \"MBEDTLS_PADLOCK_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PEM_PARSE_C) && !defined(MBEDTLS_BASE64_C)\n#error \"MBEDTLS_PEM_PARSE_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PEM_WRITE_C) && !defined(MBEDTLS_BASE64_C)\n#error \"MBEDTLS_PEM_WRITE_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PK_C) && \\\n    ( !defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_ECP_C) )\n#error \"MBEDTLS_PK_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PK_PARSE_C) && !defined(MBEDTLS_PK_C)\n#error \"MBEDTLS_PK_PARSE_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PK_WRITE_C) && !defined(MBEDTLS_PK_C)\n#error \"MBEDTLS_PK_WRITE_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PKCS11_C) && !defined(MBEDTLS_PK_C)\n#error \"MBEDTLS_PKCS11_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_EXIT_ALT) && !defined(MBEDTLS_PLATFORM_C)\n#error \"MBEDTLS_PLATFORM_EXIT_ALT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_EXIT_MACRO) && !defined(MBEDTLS_PLATFORM_C)\n#error \"MBEDTLS_PLATFORM_EXIT_MACRO defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_EXIT_MACRO) &&\\\n    ( defined(MBEDTLS_PLATFORM_STD_EXIT) ||\\\n        defined(MBEDTLS_PLATFORM_EXIT_ALT) )\n#error \"MBEDTLS_PLATFORM_EXIT_MACRO and MBEDTLS_PLATFORM_STD_EXIT/MBEDTLS_PLATFORM_EXIT_ALT cannot be defined simultaneously\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_TIME_ALT) &&\\\n    ( !defined(MBEDTLS_PLATFORM_C) ||\\\n        !defined(MBEDTLS_HAVE_TIME) )\n#error \"MBEDTLS_PLATFORM_TIME_ALT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_TIME_MACRO) &&\\\n    ( !defined(MBEDTLS_PLATFORM_C) ||\\\n        !defined(MBEDTLS_HAVE_TIME) )\n#error \"MBEDTLS_PLATFORM_TIME_MACRO defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_TIME_TYPE_MACRO) &&\\\n    ( !defined(MBEDTLS_PLATFORM_C) ||\\\n        !defined(MBEDTLS_HAVE_TIME) )\n#error \"MBEDTLS_PLATFORM_TIME_TYPE_MACRO defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_TIME_MACRO) &&\\\n    ( defined(MBEDTLS_PLATFORM_STD_TIME) ||\\\n        defined(MBEDTLS_PLATFORM_TIME_ALT) )\n#error \"MBEDTLS_PLATFORM_TIME_MACRO and MBEDTLS_PLATFORM_STD_TIME/MBEDTLS_PLATFORM_TIME_ALT cannot be defined simultaneously\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_TIME_TYPE_MACRO) &&\\\n    ( defined(MBEDTLS_PLATFORM_STD_TIME) ||\\\n        defined(MBEDTLS_PLATFORM_TIME_ALT) )\n#error \"MBEDTLS_PLATFORM_TIME_TYPE_MACRO and MBEDTLS_PLATFORM_STD_TIME/MBEDTLS_PLATFORM_TIME_ALT cannot be defined simultaneously\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_FPRINTF_ALT) && !defined(MBEDTLS_PLATFORM_C)\n#error \"MBEDTLS_PLATFORM_FPRINTF_ALT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_FPRINTF_MACRO) && !defined(MBEDTLS_PLATFORM_C)\n#error \"MBEDTLS_PLATFORM_FPRINTF_MACRO defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_FPRINTF_MACRO) &&\\\n    ( defined(MBEDTLS_PLATFORM_STD_FPRINTF) ||\\\n        defined(MBEDTLS_PLATFORM_FPRINTF_ALT) )\n#error \"MBEDTLS_PLATFORM_FPRINTF_MACRO and MBEDTLS_PLATFORM_STD_FPRINTF/MBEDTLS_PLATFORM_FPRINTF_ALT cannot be defined simultaneously\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_FREE_MACRO) &&\\\n    ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_PLATFORM_MEMORY) )\n#error \"MBEDTLS_PLATFORM_FREE_MACRO defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_FREE_MACRO) &&\\\n    defined(MBEDTLS_PLATFORM_STD_FREE)\n#error \"MBEDTLS_PLATFORM_FREE_MACRO and MBEDTLS_PLATFORM_STD_FREE cannot be defined simultaneously\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_FREE_MACRO) && !defined(MBEDTLS_PLATFORM_CALLOC_MACRO)\n#error \"MBEDTLS_PLATFORM_CALLOC_MACRO must be defined if MBEDTLS_PLATFORM_FREE_MACRO is\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_CALLOC_MACRO) &&\\\n    ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_PLATFORM_MEMORY) )\n#error \"MBEDTLS_PLATFORM_CALLOC_MACRO defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_CALLOC_MACRO) &&\\\n    defined(MBEDTLS_PLATFORM_STD_CALLOC)\n#error \"MBEDTLS_PLATFORM_CALLOC_MACRO and MBEDTLS_PLATFORM_STD_CALLOC cannot be defined simultaneously\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_CALLOC_MACRO) && !defined(MBEDTLS_PLATFORM_FREE_MACRO)\n#error \"MBEDTLS_PLATFORM_FREE_MACRO must be defined if MBEDTLS_PLATFORM_CALLOC_MACRO is\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_MEMORY) && !defined(MBEDTLS_PLATFORM_C)\n#error \"MBEDTLS_PLATFORM_MEMORY defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_PRINTF_ALT) && !defined(MBEDTLS_PLATFORM_C)\n#error \"MBEDTLS_PLATFORM_PRINTF_ALT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_PRINTF_MACRO) && !defined(MBEDTLS_PLATFORM_C)\n#error \"MBEDTLS_PLATFORM_PRINTF_MACRO defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_PRINTF_MACRO) &&\\\n    ( defined(MBEDTLS_PLATFORM_STD_PRINTF) ||\\\n        defined(MBEDTLS_PLATFORM_PRINTF_ALT) )\n#error \"MBEDTLS_PLATFORM_PRINTF_MACRO and MBEDTLS_PLATFORM_STD_PRINTF/MBEDTLS_PLATFORM_PRINTF_ALT cannot be defined simultaneously\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) && !defined(MBEDTLS_PLATFORM_C)\n#error \"MBEDTLS_PLATFORM_SNPRINTF_ALT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO) && !defined(MBEDTLS_PLATFORM_C)\n#error \"MBEDTLS_PLATFORM_SNPRINTF_MACRO defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO) &&\\\n    ( defined(MBEDTLS_PLATFORM_STD_SNPRINTF) ||\\\n        defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) )\n#error \"MBEDTLS_PLATFORM_SNPRINTF_MACRO and MBEDTLS_PLATFORM_STD_SNPRINTF/MBEDTLS_PLATFORM_SNPRINTF_ALT cannot be defined simultaneously\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_STD_MEM_HDR) &&\\\n    !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS)\n#error \"MBEDTLS_PLATFORM_STD_MEM_HDR defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_STD_CALLOC) && !defined(MBEDTLS_PLATFORM_MEMORY)\n#error \"MBEDTLS_PLATFORM_STD_CALLOC defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_STD_CALLOC) && !defined(MBEDTLS_PLATFORM_MEMORY)\n#error \"MBEDTLS_PLATFORM_STD_CALLOC defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_STD_FREE) && !defined(MBEDTLS_PLATFORM_MEMORY)\n#error \"MBEDTLS_PLATFORM_STD_FREE defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_STD_EXIT) &&\\\n    !defined(MBEDTLS_PLATFORM_EXIT_ALT)\n#error \"MBEDTLS_PLATFORM_STD_EXIT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_STD_TIME) &&\\\n    ( !defined(MBEDTLS_PLATFORM_TIME_ALT) ||\\\n        !defined(MBEDTLS_HAVE_TIME) )\n#error \"MBEDTLS_PLATFORM_STD_TIME defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_STD_FPRINTF) &&\\\n    !defined(MBEDTLS_PLATFORM_FPRINTF_ALT)\n#error \"MBEDTLS_PLATFORM_STD_FPRINTF defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_STD_PRINTF) &&\\\n    !defined(MBEDTLS_PLATFORM_PRINTF_ALT)\n#error \"MBEDTLS_PLATFORM_STD_PRINTF defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_STD_SNPRINTF) &&\\\n    !defined(MBEDTLS_PLATFORM_SNPRINTF_ALT)\n#error \"MBEDTLS_PLATFORM_STD_SNPRINTF defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_ENTROPY_NV_SEED) &&\\\n    ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_ENTROPY_C) )\n#error \"MBEDTLS_ENTROPY_NV_SEED defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_NV_SEED_ALT) &&\\\n    !defined(MBEDTLS_ENTROPY_NV_SEED)\n#error \"MBEDTLS_PLATFORM_NV_SEED_ALT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ) &&\\\n    !defined(MBEDTLS_PLATFORM_NV_SEED_ALT)\n#error \"MBEDTLS_PLATFORM_STD_NV_SEED_READ defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE) &&\\\n    !defined(MBEDTLS_PLATFORM_NV_SEED_ALT)\n#error \"MBEDTLS_PLATFORM_STD_NV_SEED_WRITE defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_NV_SEED_READ_MACRO) &&\\\n    ( defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ) ||\\\n      defined(MBEDTLS_PLATFORM_NV_SEED_ALT) )\n#error \"MBEDTLS_PLATFORM_NV_SEED_READ_MACRO and MBEDTLS_PLATFORM_STD_NV_SEED_READ cannot be defined simultaneously\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO) &&\\\n    ( defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE) ||\\\n      defined(MBEDTLS_PLATFORM_NV_SEED_ALT) )\n#error \"MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO and MBEDTLS_PLATFORM_STD_NV_SEED_WRITE cannot be defined simultaneously\"\n#endif\n\n#if defined(MBEDTLS_RSA_C) && ( !defined(MBEDTLS_BIGNUM_C) ||         \\\n    !defined(MBEDTLS_OID_C) )\n#error \"MBEDTLS_RSA_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_RSA_C) && ( !defined(MBEDTLS_PKCS1_V21) &&         \\\n    !defined(MBEDTLS_PKCS1_V15) )\n#error \"MBEDTLS_RSA_C defined, but none of the PKCS1 versions enabled\"\n#endif\n\n#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) &&                        \\\n    ( !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_PKCS1_V21) )\n#error \"MBEDTLS_X509_RSASSA_PSS_SUPPORT defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3) && ( !defined(MBEDTLS_MD5_C) ||     \\\n    !defined(MBEDTLS_SHA1_C) )\n#error \"MBEDTLS_SSL_PROTO_SSL3 defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1) && ( !defined(MBEDTLS_MD5_C) ||     \\\n    !defined(MBEDTLS_SHA1_C) )\n#error \"MBEDTLS_SSL_PROTO_TLS1 defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_1) && ( !defined(MBEDTLS_MD5_C) ||     \\\n    !defined(MBEDTLS_SHA1_C) )\n#error \"MBEDTLS_SSL_PROTO_TLS1_1 defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && ( !defined(MBEDTLS_SHA1_C) &&     \\\n    !defined(MBEDTLS_SHA256_C) && !defined(MBEDTLS_SHA512_C) )\n#error \"MBEDTLS_SSL_PROTO_TLS1_2 defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)     && \\\n    !defined(MBEDTLS_SSL_PROTO_TLS1_1)  && \\\n    !defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#error \"MBEDTLS_SSL_PROTO_DTLS defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_SSL_CLI_C) && !defined(MBEDTLS_SSL_TLS_C)\n#error \"MBEDTLS_SSL_CLI_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_SSL_TLS_C) && ( !defined(MBEDTLS_CIPHER_C) ||     \\\n    !defined(MBEDTLS_MD_C) )\n#error \"MBEDTLS_SSL_TLS_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_SSL_SRV_C) && !defined(MBEDTLS_SSL_TLS_C)\n#error \"MBEDTLS_SSL_SRV_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_SSL_TLS_C) && (!defined(MBEDTLS_SSL_PROTO_SSL3) && \\\n    !defined(MBEDTLS_SSL_PROTO_TLS1) && !defined(MBEDTLS_SSL_PROTO_TLS1_1) && \\\n    !defined(MBEDTLS_SSL_PROTO_TLS1_2))\n#error \"MBEDTLS_SSL_TLS_C defined, but no protocols are active\"\n#endif\n\n#if defined(MBEDTLS_SSL_TLS_C) && (defined(MBEDTLS_SSL_PROTO_SSL3) && \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1) && !defined(MBEDTLS_SSL_PROTO_TLS1))\n#error \"Illegal protocol selection\"\n#endif\n\n#if defined(MBEDTLS_SSL_TLS_C) && (defined(MBEDTLS_SSL_PROTO_TLS1) && \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_2) && !defined(MBEDTLS_SSL_PROTO_TLS1_1))\n#error \"Illegal protocol selection\"\n#endif\n\n#if defined(MBEDTLS_SSL_TLS_C) && (defined(MBEDTLS_SSL_PROTO_SSL3) && \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_2) && (!defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    !defined(MBEDTLS_SSL_PROTO_TLS1_1)))\n#error \"Illegal protocol selection\"\n#endif\n\n#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && !defined(MBEDTLS_SSL_PROTO_DTLS)\n#error \"MBEDTLS_SSL_DTLS_HELLO_VERIFY  defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && \\\n    !defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)\n#error \"MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE  defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) &&                              \\\n    ( !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) )\n#error \"MBEDTLS_SSL_DTLS_ANTI_REPLAY  defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) &&                              \\\n    ( !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) )\n#error \"MBEDTLS_SSL_DTLS_BADMAC_LIMIT  defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) &&   \\\n    !defined(MBEDTLS_SSL_PROTO_TLS1)   &&      \\\n    !defined(MBEDTLS_SSL_PROTO_TLS1_1) &&      \\\n    !defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#error \"MBEDTLS_SSL_ENCRYPT_THEN_MAC defined, but not all prerequsites\"\n#endif\n\n#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) && \\\n    !defined(MBEDTLS_SSL_PROTO_TLS1)   &&          \\\n    !defined(MBEDTLS_SSL_PROTO_TLS1_1) &&          \\\n    !defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#error \"MBEDTLS_SSL_EXTENDED_MASTER_SECRET defined, but not all prerequsites\"\n#endif\n\n#if defined(MBEDTLS_SSL_TICKET_C) && !defined(MBEDTLS_CIPHER_C)\n#error \"MBEDTLS_SSL_TICKET_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) && \\\n    !defined(MBEDTLS_SSL_PROTO_SSL3) && !defined(MBEDTLS_SSL_PROTO_TLS1)\n#error \"MBEDTLS_SSL_CBC_RECORD_SPLITTING defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) && \\\n        !defined(MBEDTLS_X509_CRT_PARSE_C)\n#error \"MBEDTLS_SSL_SERVER_NAME_INDICATION defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_THREADING_PTHREAD)\n#if !defined(MBEDTLS_THREADING_C) || defined(MBEDTLS_THREADING_IMPL)\n#error \"MBEDTLS_THREADING_PTHREAD defined, but not all prerequisites\"\n#endif\n#define MBEDTLS_THREADING_IMPL\n#endif\n\n#if defined(MBEDTLS_THREADING_ALT)\n#if !defined(MBEDTLS_THREADING_C) || defined(MBEDTLS_THREADING_IMPL)\n#error \"MBEDTLS_THREADING_ALT defined, but not all prerequisites\"\n#endif\n#define MBEDTLS_THREADING_IMPL\n#endif\n\n#if defined(MBEDTLS_THREADING_C) && !defined(MBEDTLS_THREADING_IMPL)\n#error \"MBEDTLS_THREADING_C defined, single threading implementation required\"\n#endif\n#undef MBEDTLS_THREADING_IMPL\n\n#if defined(MBEDTLS_VERSION_FEATURES) && !defined(MBEDTLS_VERSION_C)\n#error \"MBEDTLS_VERSION_FEATURES defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_X509_USE_C) && ( !defined(MBEDTLS_BIGNUM_C) ||  \\\n    !defined(MBEDTLS_OID_C) || !defined(MBEDTLS_ASN1_PARSE_C) ||      \\\n    !defined(MBEDTLS_PK_PARSE_C) )\n#error \"MBEDTLS_X509_USE_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_X509_CREATE_C) && ( !defined(MBEDTLS_BIGNUM_C) ||  \\\n    !defined(MBEDTLS_OID_C) || !defined(MBEDTLS_ASN1_WRITE_C) ||       \\\n    !defined(MBEDTLS_PK_WRITE_C) )\n#error \"MBEDTLS_X509_CREATE_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C) && ( !defined(MBEDTLS_X509_USE_C) )\n#error \"MBEDTLS_X509_CRT_PARSE_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_X509_CRL_PARSE_C) && ( !defined(MBEDTLS_X509_USE_C) )\n#error \"MBEDTLS_X509_CRL_PARSE_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_X509_CSR_PARSE_C) && ( !defined(MBEDTLS_X509_USE_C) )\n#error \"MBEDTLS_X509_CSR_PARSE_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_X509_CRT_WRITE_C) && ( !defined(MBEDTLS_X509_CREATE_C) )\n#error \"MBEDTLS_X509_CRT_WRITE_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_X509_CSR_WRITE_C) && ( !defined(MBEDTLS_X509_CREATE_C) )\n#error \"MBEDTLS_X509_CSR_WRITE_C defined, but not all prerequisites\"\n#endif\n\n#if defined(MBEDTLS_HAVE_INT32) && defined(MBEDTLS_HAVE_INT64)\n#error \"MBEDTLS_HAVE_INT32 and MBEDTLS_HAVE_INT64 cannot be defined simultaneously\"\n#endif /* MBEDTLS_HAVE_INT32 && MBEDTLS_HAVE_INT64 */\n\n#if ( defined(MBEDTLS_HAVE_INT32) || defined(MBEDTLS_HAVE_INT64) ) && \\\n    defined(MBEDTLS_HAVE_ASM)\n#error \"MBEDTLS_HAVE_INT32/MBEDTLS_HAVE_INT64 and MBEDTLS_HAVE_ASM cannot be defined simultaneously\"\n#endif /* (MBEDTLS_HAVE_INT32 || MBEDTLS_HAVE_INT64) && MBEDTLS_HAVE_ASM */\n\n/*\n * Avoid warning from -pedantic. This is a convenient place for this\n * workaround since this is included by every single file before the\n * #if defined(MBEDTLS_xxx_C) that results in emtpy translation units.\n */\ntypedef int mbedtls_iso_c_forbids_empty_translation_units;\n\n#endif /* MBEDTLS_CHECK_CONFIG_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/cipher.h",
    "content": "/**\n * \\file cipher.h\n *\n * \\brief This file contains an abstraction interface for use with the cipher\n * primitives provided by the library. It provides a common interface to all of\n * the available cipher operations.\n *\n * \\author Adriaan de Jong <dejong@fox-it.com>\n */\n/*\n *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_CIPHER_H\n#define MBEDTLS_CIPHER_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n\n#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C) || defined(MBEDTLS_CHACHAPOLY_C)\n#define MBEDTLS_CIPHER_MODE_AEAD\n#endif\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#define MBEDTLS_CIPHER_MODE_WITH_PADDING\n#endif\n\n#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)\n#define MBEDTLS_CIPHER_MODE_STREAM\n#endif\n\n#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \\\n    !defined(inline) && !defined(__cplusplus)\n#define inline __inline\n#endif\n\n#define MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE  -0x6080  /**< The selected feature is not available. */\n#define MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA       -0x6100  /**< Bad input parameters. */\n#define MBEDTLS_ERR_CIPHER_ALLOC_FAILED         -0x6180  /**< Failed to allocate memory. */\n#define MBEDTLS_ERR_CIPHER_INVALID_PADDING      -0x6200  /**< Input data contains invalid padding and is rejected. */\n#define MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED  -0x6280  /**< Decryption of block requires a full block. */\n#define MBEDTLS_ERR_CIPHER_AUTH_FAILED          -0x6300  /**< Authentication failed (for AEAD modes). */\n#define MBEDTLS_ERR_CIPHER_INVALID_CONTEXT      -0x6380  /**< The context is invalid. For example, because it was freed. */\n#define MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED      -0x6400  /**< Cipher hardware accelerator failed. */\n\n#define MBEDTLS_CIPHER_VARIABLE_IV_LEN     0x01    /**< Cipher accepts IVs of variable length. */\n#define MBEDTLS_CIPHER_VARIABLE_KEY_LEN    0x02    /**< Cipher accepts keys of variable length. */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief     Supported cipher types.\n *\n * \\warning   RC4 and DES are considered weak ciphers and their use\n *            constitutes a security risk. Arm recommends considering stronger\n *            ciphers instead.\n */\ntypedef enum {\n    MBEDTLS_CIPHER_ID_NONE = 0,  /**< Placeholder to mark the end of cipher ID lists. */\n    MBEDTLS_CIPHER_ID_NULL,      /**< The identity cipher, treated as a stream cipher. */\n    MBEDTLS_CIPHER_ID_AES,       /**< The AES cipher. */\n    MBEDTLS_CIPHER_ID_DES,       /**< The DES cipher. */\n    MBEDTLS_CIPHER_ID_3DES,      /**< The Triple DES cipher. */\n    MBEDTLS_CIPHER_ID_CAMELLIA,  /**< The Camellia cipher. */\n    MBEDTLS_CIPHER_ID_BLOWFISH,  /**< The Blowfish cipher. */\n    MBEDTLS_CIPHER_ID_ARC4,      /**< The RC4 cipher. */\n    MBEDTLS_CIPHER_ID_ARIA,      /**< The Aria cipher. */\n    MBEDTLS_CIPHER_ID_CHACHA20,  /**< The ChaCha20 cipher. */\n} mbedtls_cipher_id_t;\n\n/**\n * \\brief     Supported {cipher type, cipher mode} pairs.\n *\n * \\warning   RC4 and DES are considered weak ciphers and their use\n *            constitutes a security risk. Arm recommends considering stronger\n *            ciphers instead.\n */\ntypedef enum {\n    MBEDTLS_CIPHER_NONE = 0,             /**< Placeholder to mark the end of cipher-pair lists. */\n    MBEDTLS_CIPHER_NULL,                 /**< The identity stream cipher. */\n    MBEDTLS_CIPHER_AES_128_ECB,          /**< AES cipher with 128-bit ECB mode. */\n    MBEDTLS_CIPHER_AES_192_ECB,          /**< AES cipher with 192-bit ECB mode. */\n    MBEDTLS_CIPHER_AES_256_ECB,          /**< AES cipher with 256-bit ECB mode. */\n    MBEDTLS_CIPHER_AES_128_CBC,          /**< AES cipher with 128-bit CBC mode. */\n    MBEDTLS_CIPHER_AES_192_CBC,          /**< AES cipher with 192-bit CBC mode. */\n    MBEDTLS_CIPHER_AES_256_CBC,          /**< AES cipher with 256-bit CBC mode. */\n    MBEDTLS_CIPHER_AES_128_CFB128,       /**< AES cipher with 128-bit CFB128 mode. */\n    MBEDTLS_CIPHER_AES_192_CFB128,       /**< AES cipher with 192-bit CFB128 mode. */\n    MBEDTLS_CIPHER_AES_256_CFB128,       /**< AES cipher with 256-bit CFB128 mode. */\n    MBEDTLS_CIPHER_AES_128_CTR,          /**< AES cipher with 128-bit CTR mode. */\n    MBEDTLS_CIPHER_AES_192_CTR,          /**< AES cipher with 192-bit CTR mode. */\n    MBEDTLS_CIPHER_AES_256_CTR,          /**< AES cipher with 256-bit CTR mode. */\n    MBEDTLS_CIPHER_AES_128_GCM,          /**< AES cipher with 128-bit GCM mode. */\n    MBEDTLS_CIPHER_AES_192_GCM,          /**< AES cipher with 192-bit GCM mode. */\n    MBEDTLS_CIPHER_AES_256_GCM,          /**< AES cipher with 256-bit GCM mode. */\n    MBEDTLS_CIPHER_CAMELLIA_128_ECB,     /**< Camellia cipher with 128-bit ECB mode. */\n    MBEDTLS_CIPHER_CAMELLIA_192_ECB,     /**< Camellia cipher with 192-bit ECB mode. */\n    MBEDTLS_CIPHER_CAMELLIA_256_ECB,     /**< Camellia cipher with 256-bit ECB mode. */\n    MBEDTLS_CIPHER_CAMELLIA_128_CBC,     /**< Camellia cipher with 128-bit CBC mode. */\n    MBEDTLS_CIPHER_CAMELLIA_192_CBC,     /**< Camellia cipher with 192-bit CBC mode. */\n    MBEDTLS_CIPHER_CAMELLIA_256_CBC,     /**< Camellia cipher with 256-bit CBC mode. */\n    MBEDTLS_CIPHER_CAMELLIA_128_CFB128,  /**< Camellia cipher with 128-bit CFB128 mode. */\n    MBEDTLS_CIPHER_CAMELLIA_192_CFB128,  /**< Camellia cipher with 192-bit CFB128 mode. */\n    MBEDTLS_CIPHER_CAMELLIA_256_CFB128,  /**< Camellia cipher with 256-bit CFB128 mode. */\n    MBEDTLS_CIPHER_CAMELLIA_128_CTR,     /**< Camellia cipher with 128-bit CTR mode. */\n    MBEDTLS_CIPHER_CAMELLIA_192_CTR,     /**< Camellia cipher with 192-bit CTR mode. */\n    MBEDTLS_CIPHER_CAMELLIA_256_CTR,     /**< Camellia cipher with 256-bit CTR mode. */\n    MBEDTLS_CIPHER_CAMELLIA_128_GCM,     /**< Camellia cipher with 128-bit GCM mode. */\n    MBEDTLS_CIPHER_CAMELLIA_192_GCM,     /**< Camellia cipher with 192-bit GCM mode. */\n    MBEDTLS_CIPHER_CAMELLIA_256_GCM,     /**< Camellia cipher with 256-bit GCM mode. */\n    MBEDTLS_CIPHER_DES_ECB,              /**< DES cipher with ECB mode. */\n    MBEDTLS_CIPHER_DES_CBC,              /**< DES cipher with CBC mode. */\n    MBEDTLS_CIPHER_DES_EDE_ECB,          /**< DES cipher with EDE ECB mode. */\n    MBEDTLS_CIPHER_DES_EDE_CBC,          /**< DES cipher with EDE CBC mode. */\n    MBEDTLS_CIPHER_DES_EDE3_ECB,         /**< DES cipher with EDE3 ECB mode. */\n    MBEDTLS_CIPHER_DES_EDE3_CBC,         /**< DES cipher with EDE3 CBC mode. */\n    MBEDTLS_CIPHER_BLOWFISH_ECB,         /**< Blowfish cipher with ECB mode. */\n    MBEDTLS_CIPHER_BLOWFISH_CBC,         /**< Blowfish cipher with CBC mode. */\n    MBEDTLS_CIPHER_BLOWFISH_CFB64,       /**< Blowfish cipher with CFB64 mode. */\n    MBEDTLS_CIPHER_BLOWFISH_CTR,         /**< Blowfish cipher with CTR mode. */\n    MBEDTLS_CIPHER_ARC4_128,             /**< RC4 cipher with 128-bit mode. */\n    MBEDTLS_CIPHER_AES_128_CCM,          /**< AES cipher with 128-bit CCM mode. */\n    MBEDTLS_CIPHER_AES_192_CCM,          /**< AES cipher with 192-bit CCM mode. */\n    MBEDTLS_CIPHER_AES_256_CCM,          /**< AES cipher with 256-bit CCM mode. */\n    MBEDTLS_CIPHER_CAMELLIA_128_CCM,     /**< Camellia cipher with 128-bit CCM mode. */\n    MBEDTLS_CIPHER_CAMELLIA_192_CCM,     /**< Camellia cipher with 192-bit CCM mode. */\n    MBEDTLS_CIPHER_CAMELLIA_256_CCM,     /**< Camellia cipher with 256-bit CCM mode. */\n    MBEDTLS_CIPHER_ARIA_128_ECB,         /**< Aria cipher with 128-bit key and ECB mode. */\n    MBEDTLS_CIPHER_ARIA_192_ECB,         /**< Aria cipher with 192-bit key and ECB mode. */\n    MBEDTLS_CIPHER_ARIA_256_ECB,         /**< Aria cipher with 256-bit key and ECB mode. */\n    MBEDTLS_CIPHER_ARIA_128_CBC,         /**< Aria cipher with 128-bit key and CBC mode. */\n    MBEDTLS_CIPHER_ARIA_192_CBC,         /**< Aria cipher with 192-bit key and CBC mode. */\n    MBEDTLS_CIPHER_ARIA_256_CBC,         /**< Aria cipher with 256-bit key and CBC mode. */\n    MBEDTLS_CIPHER_ARIA_128_CFB128,      /**< Aria cipher with 128-bit key and CFB-128 mode. */\n    MBEDTLS_CIPHER_ARIA_192_CFB128,      /**< Aria cipher with 192-bit key and CFB-128 mode. */\n    MBEDTLS_CIPHER_ARIA_256_CFB128,      /**< Aria cipher with 256-bit key and CFB-128 mode. */\n    MBEDTLS_CIPHER_ARIA_128_CTR,         /**< Aria cipher with 128-bit key and CTR mode. */\n    MBEDTLS_CIPHER_ARIA_192_CTR,         /**< Aria cipher with 192-bit key and CTR mode. */\n    MBEDTLS_CIPHER_ARIA_256_CTR,         /**< Aria cipher with 256-bit key and CTR mode. */\n    MBEDTLS_CIPHER_ARIA_128_GCM,         /**< Aria cipher with 128-bit key and GCM mode. */\n    MBEDTLS_CIPHER_ARIA_192_GCM,         /**< Aria cipher with 192-bit key and GCM mode. */\n    MBEDTLS_CIPHER_ARIA_256_GCM,         /**< Aria cipher with 256-bit key and GCM mode. */\n    MBEDTLS_CIPHER_ARIA_128_CCM,         /**< Aria cipher with 128-bit key and CCM mode. */\n    MBEDTLS_CIPHER_ARIA_192_CCM,         /**< Aria cipher with 192-bit key and CCM mode. */\n    MBEDTLS_CIPHER_ARIA_256_CCM,         /**< Aria cipher with 256-bit key and CCM mode. */\n    MBEDTLS_CIPHER_AES_128_OFB,          /**< AES 128-bit cipher in OFB mode. */\n    MBEDTLS_CIPHER_AES_192_OFB,          /**< AES 192-bit cipher in OFB mode. */\n    MBEDTLS_CIPHER_AES_256_OFB,          /**< AES 256-bit cipher in OFB mode. */\n    MBEDTLS_CIPHER_AES_128_XTS,          /**< AES 128-bit cipher in XTS block mode. */\n    MBEDTLS_CIPHER_AES_256_XTS,          /**< AES 256-bit cipher in XTS block mode. */\n    MBEDTLS_CIPHER_CHACHA20,             /**< ChaCha20 stream cipher. */\n    MBEDTLS_CIPHER_CHACHA20_POLY1305,    /**< ChaCha20-Poly1305 AEAD cipher. */\n} mbedtls_cipher_type_t;\n\n/** Supported cipher modes. */\ntypedef enum {\n    MBEDTLS_MODE_NONE = 0,               /**< None. */\n    MBEDTLS_MODE_ECB,                    /**< The ECB cipher mode. */\n    MBEDTLS_MODE_CBC,                    /**< The CBC cipher mode. */\n    MBEDTLS_MODE_CFB,                    /**< The CFB cipher mode. */\n    MBEDTLS_MODE_OFB,                    /**< The OFB cipher mode. */\n    MBEDTLS_MODE_CTR,                    /**< The CTR cipher mode. */\n    MBEDTLS_MODE_GCM,                    /**< The GCM cipher mode. */\n    MBEDTLS_MODE_STREAM,                 /**< The stream cipher mode. */\n    MBEDTLS_MODE_CCM,                    /**< The CCM cipher mode. */\n    MBEDTLS_MODE_XTS,                    /**< The XTS cipher mode. */\n    MBEDTLS_MODE_CHACHAPOLY,             /**< The ChaCha-Poly cipher mode. */\n} mbedtls_cipher_mode_t;\n\n/** Supported cipher padding types. */\ntypedef enum {\n    MBEDTLS_PADDING_PKCS7 = 0,     /**< PKCS7 padding (default).        */\n    MBEDTLS_PADDING_ONE_AND_ZEROS, /**< ISO/IEC 7816-4 padding.         */\n    MBEDTLS_PADDING_ZEROS_AND_LEN, /**< ANSI X.923 padding.             */\n    MBEDTLS_PADDING_ZEROS,         /**< Zero padding (not reversible). */\n    MBEDTLS_PADDING_NONE,          /**< Never pad (full blocks only).   */\n} mbedtls_cipher_padding_t;\n\n/** Type of operation. */\ntypedef enum {\n    MBEDTLS_OPERATION_NONE = -1,\n    MBEDTLS_DECRYPT = 0,\n    MBEDTLS_ENCRYPT,\n} mbedtls_operation_t;\n\nenum {\n    /** Undefined key length. */\n    MBEDTLS_KEY_LENGTH_NONE = 0,\n    /** Key length, in bits (including parity), for DES keys. */\n    MBEDTLS_KEY_LENGTH_DES  = 64,\n    /** Key length in bits, including parity, for DES in two-key EDE. */\n    MBEDTLS_KEY_LENGTH_DES_EDE = 128,\n    /** Key length in bits, including parity, for DES in three-key EDE. */\n    MBEDTLS_KEY_LENGTH_DES_EDE3 = 192,\n};\n\n/** Maximum length of any IV, in Bytes. */\n#define MBEDTLS_MAX_IV_LENGTH      16\n/** Maximum block size of any cipher, in Bytes. */\n#define MBEDTLS_MAX_BLOCK_LENGTH   16\n\n/**\n * Base cipher information (opaque struct).\n */\ntypedef struct mbedtls_cipher_base_t mbedtls_cipher_base_t;\n\n/**\n * CMAC context (opaque struct).\n */\ntypedef struct mbedtls_cmac_context_t mbedtls_cmac_context_t;\n\n/**\n * Cipher information. Allows calling cipher functions\n * in a generic way.\n */\ntypedef struct {\n    /** Full cipher identifier. For example,\n     * MBEDTLS_CIPHER_AES_256_CBC.\n     */\n    mbedtls_cipher_type_t type;\n\n    /** The cipher mode. For example, MBEDTLS_MODE_CBC. */\n    mbedtls_cipher_mode_t mode;\n\n    /** The cipher key length, in bits. This is the\n     * default length for variable sized ciphers.\n     * Includes parity bits for ciphers like DES.\n     */\n    unsigned int key_bitlen;\n\n    /** Name of the cipher. */\n    const char * name;\n\n    /** IV or nonce size, in Bytes.\n     * For ciphers that accept variable IV sizes,\n     * this is the recommended size.\n     */\n    unsigned int iv_size;\n\n    /** Bitflag comprised of MBEDTLS_CIPHER_VARIABLE_IV_LEN and\n     *  MBEDTLS_CIPHER_VARIABLE_KEY_LEN indicating whether the\n     *  cipher supports variable IV or variable key sizes, respectively.\n     */\n    int flags;\n\n    /** The block size, in Bytes. */\n    unsigned int block_size;\n\n    /** Struct for base cipher information and functions. */\n    const mbedtls_cipher_base_t *base;\n\n} mbedtls_cipher_info_t;\n\n/**\n * Generic cipher context.\n */\ntypedef struct {\n    /** Information about the associated cipher. */\n    const mbedtls_cipher_info_t *cipher_info;\n\n    /** Key length to use. */\n    int key_bitlen;\n\n    /** Operation that the key of the context has been\n     * initialized for.\n     */\n    mbedtls_operation_t operation;\n\n#if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)\n    /** Padding functions to use, if relevant for\n     * the specific cipher mode.\n     */\n    void (*add_padding)( unsigned char *output, size_t olen, size_t data_len );\n    int (*get_padding)( unsigned char *input, size_t ilen, size_t *data_len );\n#endif\n\n    /** Buffer for input that has not been processed yet. */\n    unsigned char unprocessed_data[MBEDTLS_MAX_BLOCK_LENGTH];\n\n    /** Number of Bytes that have not been processed yet. */\n    size_t unprocessed_len;\n\n    /** Current IV or NONCE_COUNTER for CTR-mode, data unit (or sector) number\n     * for XTS-mode. */\n    unsigned char iv[MBEDTLS_MAX_IV_LENGTH];\n\n    /** IV size in Bytes, for ciphers with variable-length IVs. */\n    size_t iv_size;\n\n    /** The cipher-specific context. */\n    void *cipher_ctx;\n\n#if defined(MBEDTLS_CMAC_C)\n    /** CMAC-specific context. */\n    mbedtls_cmac_context_t *cmac_ctx;\n#endif\n} mbedtls_cipher_context_t;\n\n/**\n * \\brief This function retrieves the list of ciphers supported by the generic\n * cipher module.\n *\n * \\return      A statically-allocated array of ciphers. The last entry\n *              is zero.\n */\nconst int *mbedtls_cipher_list( void );\n\n/**\n * \\brief               This function retrieves the cipher-information\n *                      structure associated with the given cipher name.\n *\n * \\param cipher_name   Name of the cipher to search for.\n *\n * \\return              The cipher information structure associated with the\n *                      given \\p cipher_name.\n * \\return              NULL if the associated cipher information is not found.\n */\nconst mbedtls_cipher_info_t *mbedtls_cipher_info_from_string( const char *cipher_name );\n\n/**\n * \\brief               This function retrieves the cipher-information\n *                      structure associated with the given cipher type.\n *\n * \\param cipher_type   Type of the cipher to search for.\n *\n * \\return              The cipher information structure associated with the\n *                      given \\p cipher_type.\n * \\return              NULL if the associated cipher information is not found.\n */\nconst mbedtls_cipher_info_t *mbedtls_cipher_info_from_type( const mbedtls_cipher_type_t cipher_type );\n\n/**\n * \\brief               This function retrieves the cipher-information\n *                      structure associated with the given cipher ID,\n *                      key size and mode.\n *\n * \\param cipher_id     The ID of the cipher to search for. For example,\n *                      #MBEDTLS_CIPHER_ID_AES.\n * \\param key_bitlen    The length of the key in bits.\n * \\param mode          The cipher mode. For example, #MBEDTLS_MODE_CBC.\n *\n * \\return              The cipher information structure associated with the\n *                      given \\p cipher_id.\n * \\return              NULL if the associated cipher information is not found.\n */\nconst mbedtls_cipher_info_t *mbedtls_cipher_info_from_values( const mbedtls_cipher_id_t cipher_id,\n                                              int key_bitlen,\n                                              const mbedtls_cipher_mode_t mode );\n\n/**\n * \\brief               This function initializes a \\p cipher_context as NONE.\n */\nvoid mbedtls_cipher_init( mbedtls_cipher_context_t *ctx );\n\n/**\n * \\brief               This function frees and clears the cipher-specific\n *                      context of \\p ctx. Freeing \\p ctx itself remains the\n *                      responsibility of the caller.\n */\nvoid mbedtls_cipher_free( mbedtls_cipher_context_t *ctx );\n\n\n/**\n * \\brief               This function initializes and fills the cipher-context\n *                      structure with the appropriate values. It also clears\n *                      the structure.\n *\n * \\param ctx           The context to initialize. May not be NULL.\n * \\param cipher_info   The cipher to use.\n *\n * \\return              \\c 0 on success.\n * \\return              #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on\n *                      parameter-verification failure.\n * \\return              #MBEDTLS_ERR_CIPHER_ALLOC_FAILED if allocation of the\n *                      cipher-specific context fails.\n *\n * \\internal Currently, the function also clears the structure.\n * In future versions, the caller will be required to call\n * mbedtls_cipher_init() on the structure first.\n */\nint mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_info_t *cipher_info );\n\n/**\n * \\brief        This function returns the block size of the given cipher.\n *\n * \\param ctx    The context of the cipher. Must be initialized.\n *\n * \\return       The size of the blocks of the cipher.\n * \\return       0 if \\p ctx has not been initialized.\n */\nstatic inline unsigned int mbedtls_cipher_get_block_size( const mbedtls_cipher_context_t *ctx )\n{\n    if( NULL == ctx || NULL == ctx->cipher_info )\n        return 0;\n\n    return ctx->cipher_info->block_size;\n}\n\n/**\n * \\brief        This function returns the mode of operation for\n *               the cipher. For example, MBEDTLS_MODE_CBC.\n *\n * \\param ctx    The context of the cipher. Must be initialized.\n *\n * \\return       The mode of operation.\n * \\return       #MBEDTLS_MODE_NONE if \\p ctx has not been initialized.\n */\nstatic inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode( const mbedtls_cipher_context_t *ctx )\n{\n    if( NULL == ctx || NULL == ctx->cipher_info )\n        return MBEDTLS_MODE_NONE;\n\n    return ctx->cipher_info->mode;\n}\n\n/**\n * \\brief       This function returns the size of the IV or nonce\n *              of the cipher, in Bytes.\n *\n * \\param ctx   The context of the cipher. Must be initialized.\n *\n * \\return      The recommended IV size if no IV has been set.\n * \\return      \\c 0 for ciphers not using an IV or a nonce.\n * \\return      The actual size if an IV has been set.\n */\nstatic inline int mbedtls_cipher_get_iv_size( const mbedtls_cipher_context_t *ctx )\n{\n    if( NULL == ctx || NULL == ctx->cipher_info )\n        return 0;\n\n    if( ctx->iv_size != 0 )\n        return (int) ctx->iv_size;\n\n    return (int) ctx->cipher_info->iv_size;\n}\n\n/**\n * \\brief               This function returns the type of the given cipher.\n *\n * \\param ctx           The context of the cipher. Must be initialized.\n *\n * \\return              The type of the cipher.\n * \\return              #MBEDTLS_CIPHER_NONE if \\p ctx has not been initialized.\n */\nstatic inline mbedtls_cipher_type_t mbedtls_cipher_get_type( const mbedtls_cipher_context_t *ctx )\n{\n    if( NULL == ctx || NULL == ctx->cipher_info )\n        return MBEDTLS_CIPHER_NONE;\n\n    return ctx->cipher_info->type;\n}\n\n/**\n * \\brief               This function returns the name of the given cipher\n *                      as a string.\n *\n * \\param ctx           The context of the cipher. Must be initialized.\n *\n * \\return              The name of the cipher.\n * \\return              NULL if \\p ctx has not been not initialized.\n */\nstatic inline const char *mbedtls_cipher_get_name( const mbedtls_cipher_context_t *ctx )\n{\n    if( NULL == ctx || NULL == ctx->cipher_info )\n        return 0;\n\n    return ctx->cipher_info->name;\n}\n\n/**\n * \\brief               This function returns the key length of the cipher.\n *\n * \\param ctx           The context of the cipher. Must be initialized.\n *\n * \\return              The key length of the cipher in bits.\n * \\return              #MBEDTLS_KEY_LENGTH_NONE if ctx \\p has not been\n *                      initialized.\n */\nstatic inline int mbedtls_cipher_get_key_bitlen( const mbedtls_cipher_context_t *ctx )\n{\n    if( NULL == ctx || NULL == ctx->cipher_info )\n        return MBEDTLS_KEY_LENGTH_NONE;\n\n    return (int) ctx->cipher_info->key_bitlen;\n}\n\n/**\n * \\brief          This function returns the operation of the given cipher.\n *\n * \\param ctx      The context of the cipher. Must be initialized.\n *\n * \\return         The type of operation: #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT.\n * \\return         #MBEDTLS_OPERATION_NONE if \\p ctx has not been initialized.\n */\nstatic inline mbedtls_operation_t mbedtls_cipher_get_operation( const mbedtls_cipher_context_t *ctx )\n{\n    if( NULL == ctx || NULL == ctx->cipher_info )\n        return MBEDTLS_OPERATION_NONE;\n\n    return ctx->operation;\n}\n\n/**\n * \\brief               This function sets the key to use with the given context.\n *\n * \\param ctx           The generic cipher context. May not be NULL. Must have\n *                      been initialized using mbedtls_cipher_info_from_type()\n *                      or mbedtls_cipher_info_from_string().\n * \\param key           The key to use.\n * \\param key_bitlen    The key length to use, in bits.\n * \\param operation     The operation that the key will be used for:\n *                      #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT.\n *\n * \\return              \\c 0 on success.\n * \\return              #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on\n *                      parameter-verification failure.\n * \\return              A cipher-specific error code on failure.\n */\nint mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *key,\n                   int key_bitlen, const mbedtls_operation_t operation );\n\n#if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)\n/**\n * \\brief               This function sets the padding mode, for cipher modes\n *                      that use padding.\n *\n *                      The default passing mode is PKCS7 padding.\n *\n * \\param ctx           The generic cipher context.\n * \\param mode          The padding mode.\n *\n * \\return              \\c 0 on success.\n * \\return              #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE\n *                      if the selected padding mode is not supported.\n * \\return              #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if the cipher mode\n *                      does not support padding.\n */\nint mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_cipher_padding_t mode );\n#endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */\n\n/**\n * \\brief           This function sets the initialization vector (IV)\n *                  or nonce.\n *\n * \\note            Some ciphers do not use IVs nor nonce. For these\n *                  ciphers, this function has no effect.\n *\n * \\param ctx       The generic cipher context.\n * \\param iv        The IV to use, or NONCE_COUNTER for CTR-mode ciphers.\n * \\param iv_len    The IV length for ciphers with variable-size IV.\n *                  This parameter is discarded by ciphers with fixed-size IV.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on\n *                  parameter-verification failure.\n */\nint mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx,\n                   const unsigned char *iv, size_t iv_len );\n\n/**\n * \\brief         This function resets the cipher state.\n *\n * \\param ctx     The generic cipher context.\n *\n * \\return        \\c 0 on success.\n * \\return        #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on\n *                parameter-verification failure.\n */\nint mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx );\n\n#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)\n/**\n * \\brief               This function adds additional data for AEAD ciphers.\n *                      Currently supported with GCM and ChaCha20+Poly1305.\n *                      Must be called exactly once, after mbedtls_cipher_reset().\n *\n * \\param ctx           The generic cipher context.\n * \\param ad            The additional data to use.\n * \\param ad_len        the Length of \\p ad.\n *\n * \\return              \\c 0 on success.\n * \\return              A specific error code on failure.\n */\nint mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx,\n                      const unsigned char *ad, size_t ad_len );\n#endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */\n\n/**\n * \\brief               The generic cipher update function. It encrypts or\n *                      decrypts using the given cipher context. Writes as\n *                      many block-sized blocks of data as possible to output.\n *                      Any data that cannot be written immediately is either\n *                      added to the next block, or flushed when\n *                      mbedtls_cipher_finish() is called.\n *                      Exception: For MBEDTLS_MODE_ECB, expects a single block\n *                      in size. For example, 16 Bytes for AES.\n *\n * \\note                If the underlying cipher is used in GCM mode, all calls\n *                      to this function, except for the last one before\n *                      mbedtls_cipher_finish(), must have \\p ilen as a\n *                      multiple of the block size of the cipher.\n *\n * \\param ctx           The generic cipher context.\n * \\param input         The buffer holding the input data.\n * \\param ilen          The length of the input data.\n * \\param output        The buffer for the output data. Must be able to hold at\n *                      least \\p ilen + block_size. Must not be the same buffer\n *                      as input.\n * \\param olen          The length of the output data, to be updated with the\n *                      actual number of Bytes written.\n *\n * \\return              \\c 0 on success.\n * \\return              #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on\n *                      parameter-verification failure.\n * \\return              #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE on an\n *                      unsupported mode for a cipher.\n * \\return              A cipher-specific error code on failure.\n */\nint mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input,\n                   size_t ilen, unsigned char *output, size_t *olen );\n\n/**\n * \\brief               The generic cipher finalization function. If data still\n *                      needs to be flushed from an incomplete block, the data\n *                      contained in it is padded to the size of\n *                      the last block, and written to the \\p output buffer.\n *\n * \\param ctx           The generic cipher context.\n * \\param output        The buffer to write data to. Needs block_size available.\n * \\param olen          The length of the data written to the \\p output buffer.\n *\n * \\return              \\c 0 on success.\n * \\return              #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on\n *                      parameter-verification failure.\n * \\return              #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED on decryption\n *                      expecting a full block but not receiving one.\n * \\return              #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding\n *                      while decrypting.\n * \\return              A cipher-specific error code on failure.\n */\nint mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx,\n                   unsigned char *output, size_t *olen );\n\n#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)\n/**\n * \\brief               This function writes a tag for AEAD ciphers.\n *                      Currently supported with GCM and ChaCha20+Poly1305.\n *                      Must be called after mbedtls_cipher_finish().\n *\n * \\param ctx           The generic cipher context.\n * \\param tag           The buffer to write the tag to.\n * \\param tag_len       The length of the tag to write.\n *\n * \\return              \\c 0 on success.\n * \\return              A specific error code on failure.\n */\nint mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx,\n                      unsigned char *tag, size_t tag_len );\n\n/**\n * \\brief               This function checks the tag for AEAD ciphers.\n *                      Currently supported with GCM and ChaCha20+Poly1305.\n *                      Must be called after mbedtls_cipher_finish().\n *\n * \\param ctx           The generic cipher context.\n * \\param tag           The buffer holding the tag.\n * \\param tag_len       The length of the tag to check.\n *\n * \\return              \\c 0 on success.\n * \\return              A specific error code on failure.\n */\nint mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx,\n                      const unsigned char *tag, size_t tag_len );\n#endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */\n\n/**\n * \\brief               The generic all-in-one encryption/decryption function,\n *                      for all ciphers except AEAD constructs.\n *\n * \\param ctx           The generic cipher context.\n * \\param iv            The IV to use, or NONCE_COUNTER for CTR-mode ciphers.\n * \\param iv_len        The IV length for ciphers with variable-size IV.\n *                      This parameter is discarded by ciphers with fixed-size\n *                      IV.\n * \\param input         The buffer holding the input data.\n * \\param ilen          The length of the input data.\n * \\param output        The buffer for the output data. Must be able to hold at\n *                      least \\p ilen + block_size. Must not be the same buffer\n *                      as input.\n * \\param olen          The length of the output data, to be updated with the\n *                      actual number of Bytes written.\n *\n * \\note                Some ciphers do not use IVs nor nonce. For these\n *                      ciphers, use \\p iv = NULL and \\p iv_len = 0.\n *\n * \\return              \\c 0 on success.\n * \\return              #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on\n *                      parameter-verification failure.\n * \\return              #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED on decryption\n *                      expecting a full block but not receiving one.\n * \\return              #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding\n *                      while decrypting.\n * \\return              A cipher-specific error code on failure.\n */\nint mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx,\n                  const unsigned char *iv, size_t iv_len,\n                  const unsigned char *input, size_t ilen,\n                  unsigned char *output, size_t *olen );\n\n#if defined(MBEDTLS_CIPHER_MODE_AEAD)\n/**\n * \\brief               The generic autenticated encryption (AEAD) function.\n *\n * \\param ctx           The generic cipher context.\n * \\param iv            The IV to use, or NONCE_COUNTER for CTR-mode ciphers.\n * \\param iv_len        The IV length for ciphers with variable-size IV.\n *                      This parameter is discarded by ciphers with fixed-size IV.\n * \\param ad            The additional data to authenticate.\n * \\param ad_len        The length of \\p ad.\n * \\param input         The buffer holding the input data.\n * \\param ilen          The length of the input data.\n * \\param output        The buffer for the output data.\n *                      Must be able to hold at least \\p ilen.\n * \\param olen          The length of the output data, to be updated with the\n *                      actual number of Bytes written.\n * \\param tag           The buffer for the authentication tag.\n * \\param tag_len       The desired length of the authentication tag.\n *\n * \\return              \\c 0 on success.\n * \\return              #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on\n *                      parameter-verification failure.\n * \\return              A cipher-specific error code on failure.\n */\nint mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx,\n                         const unsigned char *iv, size_t iv_len,\n                         const unsigned char *ad, size_t ad_len,\n                         const unsigned char *input, size_t ilen,\n                         unsigned char *output, size_t *olen,\n                         unsigned char *tag, size_t tag_len );\n\n/**\n * \\brief               The generic autenticated decryption (AEAD) function.\n *\n * \\note                If the data is not authentic, then the output buffer\n *                      is zeroed out to prevent the unauthentic plaintext being\n *                      used, making this interface safer.\n *\n * \\param ctx           The generic cipher context.\n * \\param iv            The IV to use, or NONCE_COUNTER for CTR-mode ciphers.\n * \\param iv_len        The IV length for ciphers with variable-size IV.\n *                      This parameter is discarded by ciphers with fixed-size IV.\n * \\param ad            The additional data to be authenticated.\n * \\param ad_len        The length of \\p ad.\n * \\param input         The buffer holding the input data.\n * \\param ilen          The length of the input data.\n * \\param output        The buffer for the output data.\n *                      Must be able to hold at least \\p ilen.\n * \\param olen          The length of the output data, to be updated with the\n *                      actual number of Bytes written.\n * \\param tag           The buffer holding the authentication tag.\n * \\param tag_len       The length of the authentication tag.\n *\n * \\return              \\c 0 on success.\n * \\return              #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on\n *                      parameter-verification failure.\n * \\return              #MBEDTLS_ERR_CIPHER_AUTH_FAILED if data is not authentic.\n * \\return              A cipher-specific error code on failure.\n */\nint mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx,\n                         const unsigned char *iv, size_t iv_len,\n                         const unsigned char *ad, size_t ad_len,\n                         const unsigned char *input, size_t ilen,\n                         unsigned char *output, size_t *olen,\n                         const unsigned char *tag, size_t tag_len );\n#endif /* MBEDTLS_CIPHER_MODE_AEAD */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* MBEDTLS_CIPHER_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/cipher_internal.h",
    "content": "/**\n * \\file cipher_internal.h\n *\n * \\brief Cipher wrappers.\n *\n * \\author Adriaan de Jong <dejong@fox-it.com>\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_CIPHER_WRAP_H\n#define MBEDTLS_CIPHER_WRAP_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include \"cipher.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * Base cipher information. The non-mode specific functions and values.\n */\nstruct mbedtls_cipher_base_t\n{\n    /** Base Cipher type (e.g. MBEDTLS_CIPHER_ID_AES) */\n    mbedtls_cipher_id_t cipher;\n\n    /** Encrypt using ECB */\n    int (*ecb_func)( void *ctx, mbedtls_operation_t mode,\n                     const unsigned char *input, unsigned char *output );\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    /** Encrypt using CBC */\n    int (*cbc_func)( void *ctx, mbedtls_operation_t mode, size_t length,\n                     unsigned char *iv, const unsigned char *input,\n                     unsigned char *output );\n#endif\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    /** Encrypt using CFB (Full length) */\n    int (*cfb_func)( void *ctx, mbedtls_operation_t mode, size_t length, size_t *iv_off,\n                     unsigned char *iv, const unsigned char *input,\n                     unsigned char *output );\n#endif\n\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    /** Encrypt using OFB (Full length) */\n    int (*ofb_func)( void *ctx, size_t length, size_t *iv_off,\n                     unsigned char *iv,\n                     const unsigned char *input,\n                     unsigned char *output );\n#endif\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    /** Encrypt using CTR */\n    int (*ctr_func)( void *ctx, size_t length, size_t *nc_off,\n                     unsigned char *nonce_counter, unsigned char *stream_block,\n                     const unsigned char *input, unsigned char *output );\n#endif\n\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    /** Encrypt or decrypt using XTS. */\n    int (*xts_func)( void *ctx, mbedtls_operation_t mode, size_t length,\n                     const unsigned char data_unit[16],\n                     const unsigned char *input, unsigned char *output );\n#endif\n\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    /** Encrypt using STREAM */\n    int (*stream_func)( void *ctx, size_t length,\n                        const unsigned char *input, unsigned char *output );\n#endif\n\n    /** Set key for encryption purposes */\n    int (*setkey_enc_func)( void *ctx, const unsigned char *key,\n                            unsigned int key_bitlen );\n\n    /** Set key for decryption purposes */\n    int (*setkey_dec_func)( void *ctx, const unsigned char *key,\n                            unsigned int key_bitlen);\n\n    /** Allocate a new context */\n    void * (*ctx_alloc_func)( void );\n\n    /** Free the given context */\n    void (*ctx_free_func)( void *ctx );\n\n};\n\ntypedef struct\n{\n    mbedtls_cipher_type_t type;\n    const mbedtls_cipher_info_t *info;\n} mbedtls_cipher_definition_t;\n\nextern const mbedtls_cipher_definition_t mbedtls_cipher_definitions[];\n\nextern int mbedtls_cipher_supported[];\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* MBEDTLS_CIPHER_WRAP_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/cmac.h",
    "content": "/**\n * \\file cmac.h\n *\n * \\brief This file contains CMAC definitions and functions.\n *\n * The Cipher-based Message Authentication Code (CMAC) Mode for\n * Authentication is defined in <em>RFC-4493: The AES-CMAC Algorithm</em>.\n */\n/*\n *  Copyright (C) 2015-2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_CMAC_H\n#define MBEDTLS_CMAC_H\n\n#include \"cipher.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#define MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED -0x007A  /**< CMAC hardware accelerator failed. */\n\n#define MBEDTLS_AES_BLOCK_SIZE          16\n#define MBEDTLS_DES3_BLOCK_SIZE         8\n\n#if defined(MBEDTLS_AES_C)\n#define MBEDTLS_CIPHER_BLKSIZE_MAX      16  /**< The longest block used by CMAC is that of AES. */\n#else\n#define MBEDTLS_CIPHER_BLKSIZE_MAX      8   /**< The longest block used by CMAC is that of 3DES. */\n#endif\n\n#if !defined(MBEDTLS_CMAC_ALT)\n\n/**\n * The CMAC context structure.\n */\nstruct mbedtls_cmac_context_t\n{\n    /** The internal state of the CMAC algorithm.  */\n    unsigned char       state[MBEDTLS_CIPHER_BLKSIZE_MAX];\n\n    /** Unprocessed data - either data that was not block aligned and is still\n     *  pending processing, or the final block. */\n    unsigned char       unprocessed_block[MBEDTLS_CIPHER_BLKSIZE_MAX];\n\n    /** The length of data pending processing. */\n    size_t              unprocessed_len;\n};\n\n#else  /* !MBEDTLS_CMAC_ALT */\n#include \"cmac_alt.h\"\n#endif /* !MBEDTLS_CMAC_ALT */\n\n/**\n * \\brief               This function sets the CMAC key, and prepares to authenticate\n *                      the input data.\n *                      Must be called with an initialized cipher context.\n *\n * \\param ctx           The cipher context used for the CMAC operation, initialized\n *                      as one of the following types: MBEDTLS_CIPHER_AES_128_ECB,\n *                      MBEDTLS_CIPHER_AES_192_ECB, MBEDTLS_CIPHER_AES_256_ECB,\n *                      or MBEDTLS_CIPHER_DES_EDE3_ECB.\n * \\param key           The CMAC key.\n * \\param keybits       The length of the CMAC key in bits.\n *                      Must be supported by the cipher.\n *\n * \\return              \\c 0 on success.\n * \\return              A cipher-specific error code on failure.\n */\nint mbedtls_cipher_cmac_starts( mbedtls_cipher_context_t *ctx,\n                                const unsigned char *key, size_t keybits );\n\n/**\n * \\brief               This function feeds an input buffer into an ongoing CMAC\n *                      computation.\n *\n *                      It is called between mbedtls_cipher_cmac_starts() or\n *                      mbedtls_cipher_cmac_reset(), and mbedtls_cipher_cmac_finish().\n *                      Can be called repeatedly.\n *\n * \\param ctx           The cipher context used for the CMAC operation.\n * \\param input         The buffer holding the input data.\n * \\param ilen          The length of the input data.\n *\n * \\return             \\c 0 on success.\n * \\return             #MBEDTLS_ERR_MD_BAD_INPUT_DATA\n *                     if parameter verification fails.\n */\nint mbedtls_cipher_cmac_update( mbedtls_cipher_context_t *ctx,\n                                const unsigned char *input, size_t ilen );\n\n/**\n * \\brief               This function finishes the CMAC operation, and writes\n *                      the result to the output buffer.\n *\n *                      It is called after mbedtls_cipher_cmac_update().\n *                      It can be followed by mbedtls_cipher_cmac_reset() and\n *                      mbedtls_cipher_cmac_update(), or mbedtls_cipher_free().\n *\n * \\param ctx           The cipher context used for the CMAC operation.\n * \\param output        The output buffer for the CMAC checksum result.\n *\n * \\return              \\c 0 on success.\n * \\return              #MBEDTLS_ERR_MD_BAD_INPUT_DATA\n *                      if parameter verification fails.\n */\nint mbedtls_cipher_cmac_finish( mbedtls_cipher_context_t *ctx,\n                                unsigned char *output );\n\n/**\n * \\brief               This function prepares the authentication of another\n *                      message with the same key as the previous CMAC\n *                      operation.\n *\n *                      It is called after mbedtls_cipher_cmac_finish()\n *                      and before mbedtls_cipher_cmac_update().\n *\n * \\param ctx           The cipher context used for the CMAC operation.\n *\n * \\return              \\c 0 on success.\n * \\return              #MBEDTLS_ERR_MD_BAD_INPUT_DATA\n *                      if parameter verification fails.\n */\nint mbedtls_cipher_cmac_reset( mbedtls_cipher_context_t *ctx );\n\n/**\n * \\brief               This function calculates the full generic CMAC\n *                      on the input buffer with the provided key.\n *\n *                      The function allocates the context, performs the\n *                      calculation, and frees the context.\n *\n *                      The CMAC result is calculated as\n *                      output = generic CMAC(cmac key, input buffer).\n *\n *\n * \\param cipher_info   The cipher information.\n * \\param key           The CMAC key.\n * \\param keylen        The length of the CMAC key in bits.\n * \\param input         The buffer holding the input data.\n * \\param ilen          The length of the input data.\n * \\param output        The buffer for the generic CMAC result.\n *\n * \\return              \\c 0 on success.\n * \\return              #MBEDTLS_ERR_MD_BAD_INPUT_DATA\n *                      if parameter verification fails.\n */\nint mbedtls_cipher_cmac( const mbedtls_cipher_info_t *cipher_info,\n                         const unsigned char *key, size_t keylen,\n                         const unsigned char *input, size_t ilen,\n                         unsigned char *output );\n\n#if defined(MBEDTLS_AES_C)\n/**\n * \\brief           This function implements the AES-CMAC-PRF-128 pseudorandom\n *                  function, as defined in\n *                  <em>RFC-4615: The Advanced Encryption Standard-Cipher-based\n *                  Message Authentication Code-Pseudo-Random Function-128\n *                  (AES-CMAC-PRF-128) Algorithm for the Internet Key\n *                  Exchange Protocol (IKE).</em>\n *\n * \\param key       The key to use.\n * \\param key_len   The key length in Bytes.\n * \\param input     The buffer holding the input data.\n * \\param in_len    The length of the input data in Bytes.\n * \\param output    The buffer holding the generated 16 Bytes of\n *                  pseudorandom output.\n *\n * \\return          \\c 0 on success.\n */\nint mbedtls_aes_cmac_prf_128( const unsigned char *key, size_t key_len,\n                              const unsigned char *input, size_t in_len,\n                              unsigned char output[16] );\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_SELF_TEST) && ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_DES_C) )\n/**\n * \\brief          The CMAC checkup routine.\n *\n * \\return         \\c 0 on success.\n * \\return         \\c 1 on failure.\n */\nint mbedtls_cmac_self_test( int verbose );\n#endif /* MBEDTLS_SELF_TEST && ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* MBEDTLS_CMAC_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/compat-1.3.h",
    "content": "/**\n * \\file compat-1.3.h\n *\n * \\brief Compatibility definitions for using mbed TLS with client code written\n *  for the PolarSSL naming conventions.\n *\n * \\deprecated Use the new names directly instead\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if ! defined(MBEDTLS_DEPRECATED_REMOVED)\n\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#warning \"Including compat-1.3.h is deprecated\"\n#endif\n\n#ifndef MBEDTLS_COMPAT13_H\n#define MBEDTLS_COMPAT13_H\n\n/*\n * config.h options\n */\n#if defined MBEDTLS_AESNI_C\n#define POLARSSL_AESNI_C MBEDTLS_AESNI_C\n#endif\n#if defined MBEDTLS_AES_ALT\n#define POLARSSL_AES_ALT MBEDTLS_AES_ALT\n#endif\n#if defined MBEDTLS_AES_C\n#define POLARSSL_AES_C MBEDTLS_AES_C\n#endif\n#if defined MBEDTLS_AES_ROM_TABLES\n#define POLARSSL_AES_ROM_TABLES MBEDTLS_AES_ROM_TABLES\n#endif\n#if defined MBEDTLS_ARC4_ALT\n#define POLARSSL_ARC4_ALT MBEDTLS_ARC4_ALT\n#endif\n#if defined MBEDTLS_ARC4_C\n#define POLARSSL_ARC4_C MBEDTLS_ARC4_C\n#endif\n#if defined MBEDTLS_ASN1_PARSE_C\n#define POLARSSL_ASN1_PARSE_C MBEDTLS_ASN1_PARSE_C\n#endif\n#if defined MBEDTLS_ASN1_WRITE_C\n#define POLARSSL_ASN1_WRITE_C MBEDTLS_ASN1_WRITE_C\n#endif\n#if defined MBEDTLS_BASE64_C\n#define POLARSSL_BASE64_C MBEDTLS_BASE64_C\n#endif\n#if defined MBEDTLS_BIGNUM_C\n#define POLARSSL_BIGNUM_C MBEDTLS_BIGNUM_C\n#endif\n#if defined MBEDTLS_BLOWFISH_ALT\n#define POLARSSL_BLOWFISH_ALT MBEDTLS_BLOWFISH_ALT\n#endif\n#if defined MBEDTLS_BLOWFISH_C\n#define POLARSSL_BLOWFISH_C MBEDTLS_BLOWFISH_C\n#endif\n#if defined MBEDTLS_CAMELLIA_ALT\n#define POLARSSL_CAMELLIA_ALT MBEDTLS_CAMELLIA_ALT\n#endif\n#if defined MBEDTLS_CAMELLIA_C\n#define POLARSSL_CAMELLIA_C MBEDTLS_CAMELLIA_C\n#endif\n#if defined MBEDTLS_CAMELLIA_SMALL_MEMORY\n#define POLARSSL_CAMELLIA_SMALL_MEMORY MBEDTLS_CAMELLIA_SMALL_MEMORY\n#endif\n#if defined MBEDTLS_CCM_C\n#define POLARSSL_CCM_C MBEDTLS_CCM_C\n#endif\n#if defined MBEDTLS_CERTS_C\n#define POLARSSL_CERTS_C MBEDTLS_CERTS_C\n#endif\n#if defined MBEDTLS_CIPHER_C\n#define POLARSSL_CIPHER_C MBEDTLS_CIPHER_C\n#endif\n#if defined MBEDTLS_CIPHER_MODE_CBC\n#define POLARSSL_CIPHER_MODE_CBC MBEDTLS_CIPHER_MODE_CBC\n#endif\n#if defined MBEDTLS_CIPHER_MODE_CFB\n#define POLARSSL_CIPHER_MODE_CFB MBEDTLS_CIPHER_MODE_CFB\n#endif\n#if defined MBEDTLS_CIPHER_MODE_CTR\n#define POLARSSL_CIPHER_MODE_CTR MBEDTLS_CIPHER_MODE_CTR\n#endif\n#if defined MBEDTLS_CIPHER_NULL_CIPHER\n#define POLARSSL_CIPHER_NULL_CIPHER MBEDTLS_CIPHER_NULL_CIPHER\n#endif\n#if defined MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS\n#define POLARSSL_CIPHER_PADDING_ONE_AND_ZEROS MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS\n#endif\n#if defined MBEDTLS_CIPHER_PADDING_PKCS7\n#define POLARSSL_CIPHER_PADDING_PKCS7 MBEDTLS_CIPHER_PADDING_PKCS7\n#endif\n#if defined MBEDTLS_CIPHER_PADDING_ZEROS\n#define POLARSSL_CIPHER_PADDING_ZEROS MBEDTLS_CIPHER_PADDING_ZEROS\n#endif\n#if defined MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN\n#define POLARSSL_CIPHER_PADDING_ZEROS_AND_LEN MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN\n#endif\n#if defined MBEDTLS_CTR_DRBG_C\n#define POLARSSL_CTR_DRBG_C MBEDTLS_CTR_DRBG_C\n#endif\n#if defined MBEDTLS_DEBUG_C\n#define POLARSSL_DEBUG_C MBEDTLS_DEBUG_C\n#endif\n#if defined MBEDTLS_DEPRECATED_REMOVED\n#define POLARSSL_DEPRECATED_REMOVED MBEDTLS_DEPRECATED_REMOVED\n#endif\n#if defined MBEDTLS_DEPRECATED_WARNING\n#define POLARSSL_DEPRECATED_WARNING MBEDTLS_DEPRECATED_WARNING\n#endif\n#if defined MBEDTLS_DES_ALT\n#define POLARSSL_DES_ALT MBEDTLS_DES_ALT\n#endif\n#if defined MBEDTLS_DES_C\n#define POLARSSL_DES_C MBEDTLS_DES_C\n#endif\n#if defined MBEDTLS_DHM_C\n#define POLARSSL_DHM_C MBEDTLS_DHM_C\n#endif\n#if defined MBEDTLS_ECDH_C\n#define POLARSSL_ECDH_C MBEDTLS_ECDH_C\n#endif\n#if defined MBEDTLS_ECDSA_C\n#define POLARSSL_ECDSA_C MBEDTLS_ECDSA_C\n#endif\n#if defined MBEDTLS_ECDSA_DETERMINISTIC\n#define POLARSSL_ECDSA_DETERMINISTIC MBEDTLS_ECDSA_DETERMINISTIC\n#endif\n#if defined MBEDTLS_ECP_C\n#define POLARSSL_ECP_C MBEDTLS_ECP_C\n#endif\n#if defined MBEDTLS_ECP_DP_BP256R1_ENABLED\n#define POLARSSL_ECP_DP_BP256R1_ENABLED MBEDTLS_ECP_DP_BP256R1_ENABLED\n#endif\n#if defined MBEDTLS_ECP_DP_BP384R1_ENABLED\n#define POLARSSL_ECP_DP_BP384R1_ENABLED MBEDTLS_ECP_DP_BP384R1_ENABLED\n#endif\n#if defined MBEDTLS_ECP_DP_BP512R1_ENABLED\n#define POLARSSL_ECP_DP_BP512R1_ENABLED MBEDTLS_ECP_DP_BP512R1_ENABLED\n#endif\n#if defined MBEDTLS_ECP_DP_CURVE25519_ENABLED\n#define POLARSSL_ECP_DP_M255_ENABLED MBEDTLS_ECP_DP_CURVE25519_ENABLED\n#endif\n#if defined MBEDTLS_ECP_DP_SECP192K1_ENABLED\n#define POLARSSL_ECP_DP_SECP192K1_ENABLED MBEDTLS_ECP_DP_SECP192K1_ENABLED\n#endif\n#if defined MBEDTLS_ECP_DP_SECP192R1_ENABLED\n#define POLARSSL_ECP_DP_SECP192R1_ENABLED MBEDTLS_ECP_DP_SECP192R1_ENABLED\n#endif\n#if defined MBEDTLS_ECP_DP_SECP224K1_ENABLED\n#define POLARSSL_ECP_DP_SECP224K1_ENABLED MBEDTLS_ECP_DP_SECP224K1_ENABLED\n#endif\n#if defined MBEDTLS_ECP_DP_SECP224R1_ENABLED\n#define POLARSSL_ECP_DP_SECP224R1_ENABLED MBEDTLS_ECP_DP_SECP224R1_ENABLED\n#endif\n#if defined MBEDTLS_ECP_DP_SECP256K1_ENABLED\n#define POLARSSL_ECP_DP_SECP256K1_ENABLED MBEDTLS_ECP_DP_SECP256K1_ENABLED\n#endif\n#if defined MBEDTLS_ECP_DP_SECP256R1_ENABLED\n#define POLARSSL_ECP_DP_SECP256R1_ENABLED MBEDTLS_ECP_DP_SECP256R1_ENABLED\n#endif\n#if defined MBEDTLS_ECP_DP_SECP384R1_ENABLED\n#define POLARSSL_ECP_DP_SECP384R1_ENABLED MBEDTLS_ECP_DP_SECP384R1_ENABLED\n#endif\n#if defined MBEDTLS_ECP_DP_SECP521R1_ENABLED\n#define POLARSSL_ECP_DP_SECP521R1_ENABLED MBEDTLS_ECP_DP_SECP521R1_ENABLED\n#endif\n#if defined MBEDTLS_ECP_FIXED_POINT_OPTIM\n#define POLARSSL_ECP_FIXED_POINT_OPTIM MBEDTLS_ECP_FIXED_POINT_OPTIM\n#endif\n#if defined MBEDTLS_ECP_MAX_BITS\n#define POLARSSL_ECP_MAX_BITS MBEDTLS_ECP_MAX_BITS\n#endif\n#if defined MBEDTLS_ECP_NIST_OPTIM\n#define POLARSSL_ECP_NIST_OPTIM MBEDTLS_ECP_NIST_OPTIM\n#endif\n#if defined MBEDTLS_ECP_WINDOW_SIZE\n#define POLARSSL_ECP_WINDOW_SIZE MBEDTLS_ECP_WINDOW_SIZE\n#endif\n#if defined MBEDTLS_ENABLE_WEAK_CIPHERSUITES\n#define POLARSSL_ENABLE_WEAK_CIPHERSUITES MBEDTLS_ENABLE_WEAK_CIPHERSUITES\n#endif\n#if defined MBEDTLS_ENTROPY_C\n#define POLARSSL_ENTROPY_C MBEDTLS_ENTROPY_C\n#endif\n#if defined MBEDTLS_ENTROPY_FORCE_SHA256\n#define POLARSSL_ENTROPY_FORCE_SHA256 MBEDTLS_ENTROPY_FORCE_SHA256\n#endif\n#if defined MBEDTLS_ERROR_C\n#define POLARSSL_ERROR_C MBEDTLS_ERROR_C\n#endif\n#if defined MBEDTLS_ERROR_STRERROR_DUMMY\n#define POLARSSL_ERROR_STRERROR_DUMMY MBEDTLS_ERROR_STRERROR_DUMMY\n#endif\n#if defined MBEDTLS_FS_IO\n#define POLARSSL_FS_IO MBEDTLS_FS_IO\n#endif\n#if defined MBEDTLS_GCM_C\n#define POLARSSL_GCM_C MBEDTLS_GCM_C\n#endif\n#if defined MBEDTLS_GENPRIME\n#define POLARSSL_GENPRIME MBEDTLS_GENPRIME\n#endif\n#if defined MBEDTLS_HAVEGE_C\n#define POLARSSL_HAVEGE_C MBEDTLS_HAVEGE_C\n#endif\n#if defined MBEDTLS_HAVE_ASM\n#define POLARSSL_HAVE_ASM MBEDTLS_HAVE_ASM\n#endif\n#if defined MBEDTLS_HAVE_SSE2\n#define POLARSSL_HAVE_SSE2 MBEDTLS_HAVE_SSE2\n#endif\n#if defined MBEDTLS_HAVE_TIME\n#define POLARSSL_HAVE_TIME MBEDTLS_HAVE_TIME\n#endif\n#if defined MBEDTLS_HMAC_DRBG_C\n#define POLARSSL_HMAC_DRBG_C MBEDTLS_HMAC_DRBG_C\n#endif\n#if defined MBEDTLS_HMAC_DRBG_MAX_INPUT\n#define POLARSSL_HMAC_DRBG_MAX_INPUT MBEDTLS_HMAC_DRBG_MAX_INPUT\n#endif\n#if defined MBEDTLS_HMAC_DRBG_MAX_REQUEST\n#define POLARSSL_HMAC_DRBG_MAX_REQUEST MBEDTLS_HMAC_DRBG_MAX_REQUEST\n#endif\n#if defined MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT\n#define POLARSSL_HMAC_DRBG_MAX_SEED_INPUT MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT\n#endif\n#if defined MBEDTLS_HMAC_DRBG_RESEED_INTERVAL\n#define POLARSSL_HMAC_DRBG_RESEED_INTERVAL MBEDTLS_HMAC_DRBG_RESEED_INTERVAL\n#endif\n#if defined MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED\n#define POLARSSL_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED\n#endif\n#if defined MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED\n#define POLARSSL_KEY_EXCHANGE_DHE_RSA_ENABLED MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED\n#endif\n#if defined MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED\n#define POLARSSL_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED\n#endif\n#if defined MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED\n#define POLARSSL_KEY_EXCHANGE_ECDHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED\n#endif\n#if defined MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED\n#define POLARSSL_KEY_EXCHANGE_ECDHE_RSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED\n#endif\n#if defined MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED\n#define POLARSSL_KEY_EXCHANGE_ECDH_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED\n#endif\n#if defined MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED\n#define POLARSSL_KEY_EXCHANGE_ECDH_RSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED\n#endif\n#if defined MBEDTLS_KEY_EXCHANGE_PSK_ENABLED\n#define POLARSSL_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_PSK_ENABLED\n#endif\n#if defined MBEDTLS_KEY_EXCHANGE_RSA_ENABLED\n#define POLARSSL_KEY_EXCHANGE_RSA_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_ENABLED\n#endif\n#if defined MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED\n#define POLARSSL_KEY_EXCHANGE_RSA_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED\n#endif\n#if defined MBEDTLS_MD2_ALT\n#define POLARSSL_MD2_ALT MBEDTLS_MD2_ALT\n#endif\n#if defined MBEDTLS_MD2_C\n#define POLARSSL_MD2_C MBEDTLS_MD2_C\n#endif\n#if defined MBEDTLS_MD2_PROCESS_ALT\n#define POLARSSL_MD2_PROCESS_ALT MBEDTLS_MD2_PROCESS_ALT\n#endif\n#if defined MBEDTLS_MD4_ALT\n#define POLARSSL_MD4_ALT MBEDTLS_MD4_ALT\n#endif\n#if defined MBEDTLS_MD4_C\n#define POLARSSL_MD4_C MBEDTLS_MD4_C\n#endif\n#if defined MBEDTLS_MD4_PROCESS_ALT\n#define POLARSSL_MD4_PROCESS_ALT MBEDTLS_MD4_PROCESS_ALT\n#endif\n#if defined MBEDTLS_MD5_ALT\n#define POLARSSL_MD5_ALT MBEDTLS_MD5_ALT\n#endif\n#if defined MBEDTLS_MD5_C\n#define POLARSSL_MD5_C MBEDTLS_MD5_C\n#endif\n#if defined MBEDTLS_MD5_PROCESS_ALT\n#define POLARSSL_MD5_PROCESS_ALT MBEDTLS_MD5_PROCESS_ALT\n#endif\n#if defined MBEDTLS_MD_C\n#define POLARSSL_MD_C MBEDTLS_MD_C\n#endif\n#if defined MBEDTLS_MEMORY_ALIGN_MULTIPLE\n#define POLARSSL_MEMORY_ALIGN_MULTIPLE MBEDTLS_MEMORY_ALIGN_MULTIPLE\n#endif\n#if defined MBEDTLS_MEMORY_BACKTRACE\n#define POLARSSL_MEMORY_BACKTRACE MBEDTLS_MEMORY_BACKTRACE\n#endif\n#if defined MBEDTLS_MEMORY_BUFFER_ALLOC_C\n#define POLARSSL_MEMORY_BUFFER_ALLOC_C MBEDTLS_MEMORY_BUFFER_ALLOC_C\n#endif\n#if defined MBEDTLS_MEMORY_DEBUG\n#define POLARSSL_MEMORY_DEBUG MBEDTLS_MEMORY_DEBUG\n#endif\n#if defined MBEDTLS_MPI_MAX_SIZE\n#define POLARSSL_MPI_MAX_SIZE MBEDTLS_MPI_MAX_SIZE\n#endif\n#if defined MBEDTLS_MPI_WINDOW_SIZE\n#define POLARSSL_MPI_WINDOW_SIZE MBEDTLS_MPI_WINDOW_SIZE\n#endif\n#if defined MBEDTLS_NET_C\n#define POLARSSL_NET_C MBEDTLS_NET_C\n#endif\n#if defined MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES\n#define POLARSSL_NO_DEFAULT_ENTROPY_SOURCES MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES\n#endif\n#if defined MBEDTLS_NO_PLATFORM_ENTROPY\n#define POLARSSL_NO_PLATFORM_ENTROPY MBEDTLS_NO_PLATFORM_ENTROPY\n#endif\n#if defined MBEDTLS_OID_C\n#define POLARSSL_OID_C MBEDTLS_OID_C\n#endif\n#if defined MBEDTLS_PADLOCK_C\n#define POLARSSL_PADLOCK_C MBEDTLS_PADLOCK_C\n#endif\n#if defined MBEDTLS_PEM_PARSE_C\n#define POLARSSL_PEM_PARSE_C MBEDTLS_PEM_PARSE_C\n#endif\n#if defined MBEDTLS_PEM_WRITE_C\n#define POLARSSL_PEM_WRITE_C MBEDTLS_PEM_WRITE_C\n#endif\n#if defined MBEDTLS_PKCS11_C\n#define POLARSSL_PKCS11_C MBEDTLS_PKCS11_C\n#endif\n#if defined MBEDTLS_PKCS12_C\n#define POLARSSL_PKCS12_C MBEDTLS_PKCS12_C\n#endif\n#if defined MBEDTLS_PKCS1_V15\n#define POLARSSL_PKCS1_V15 MBEDTLS_PKCS1_V15\n#endif\n#if defined MBEDTLS_PKCS1_V21\n#define POLARSSL_PKCS1_V21 MBEDTLS_PKCS1_V21\n#endif\n#if defined MBEDTLS_PKCS5_C\n#define POLARSSL_PKCS5_C MBEDTLS_PKCS5_C\n#endif\n#if defined MBEDTLS_PK_C\n#define POLARSSL_PK_C MBEDTLS_PK_C\n#endif\n#if defined MBEDTLS_PK_PARSE_C\n#define POLARSSL_PK_PARSE_C MBEDTLS_PK_PARSE_C\n#endif\n#if defined MBEDTLS_PK_PARSE_EC_EXTENDED\n#define POLARSSL_PK_PARSE_EC_EXTENDED MBEDTLS_PK_PARSE_EC_EXTENDED\n#endif\n#if defined MBEDTLS_PK_RSA_ALT_SUPPORT\n#define POLARSSL_PK_RSA_ALT_SUPPORT MBEDTLS_PK_RSA_ALT_SUPPORT\n#endif\n#if defined MBEDTLS_PK_WRITE_C\n#define POLARSSL_PK_WRITE_C MBEDTLS_PK_WRITE_C\n#endif\n#if defined MBEDTLS_PLATFORM_C\n#define POLARSSL_PLATFORM_C MBEDTLS_PLATFORM_C\n#endif\n#if defined MBEDTLS_PLATFORM_EXIT_ALT\n#define POLARSSL_PLATFORM_EXIT_ALT MBEDTLS_PLATFORM_EXIT_ALT\n#endif\n#if defined MBEDTLS_PLATFORM_EXIT_MACRO\n#define POLARSSL_PLATFORM_EXIT_MACRO MBEDTLS_PLATFORM_EXIT_MACRO\n#endif\n#if defined MBEDTLS_PLATFORM_FPRINTF_ALT\n#define POLARSSL_PLATFORM_FPRINTF_ALT MBEDTLS_PLATFORM_FPRINTF_ALT\n#endif\n#if defined MBEDTLS_PLATFORM_FPRINTF_MACRO\n#define POLARSSL_PLATFORM_FPRINTF_MACRO MBEDTLS_PLATFORM_FPRINTF_MACRO\n#endif\n#if defined MBEDTLS_PLATFORM_FREE_MACRO\n#define POLARSSL_PLATFORM_FREE_MACRO MBEDTLS_PLATFORM_FREE_MACRO\n#endif\n#if defined MBEDTLS_PLATFORM_MEMORY\n#define POLARSSL_PLATFORM_MEMORY MBEDTLS_PLATFORM_MEMORY\n#endif\n#if defined MBEDTLS_PLATFORM_NO_STD_FUNCTIONS\n#define POLARSSL_PLATFORM_NO_STD_FUNCTIONS MBEDTLS_PLATFORM_NO_STD_FUNCTIONS\n#endif\n#if defined MBEDTLS_PLATFORM_PRINTF_ALT\n#define POLARSSL_PLATFORM_PRINTF_ALT MBEDTLS_PLATFORM_PRINTF_ALT\n#endif\n#if defined MBEDTLS_PLATFORM_PRINTF_MACRO\n#define POLARSSL_PLATFORM_PRINTF_MACRO MBEDTLS_PLATFORM_PRINTF_MACRO\n#endif\n#if defined MBEDTLS_PLATFORM_SNPRINTF_ALT\n#define POLARSSL_PLATFORM_SNPRINTF_ALT MBEDTLS_PLATFORM_SNPRINTF_ALT\n#endif\n#if defined MBEDTLS_PLATFORM_SNPRINTF_MACRO\n#define POLARSSL_PLATFORM_SNPRINTF_MACRO MBEDTLS_PLATFORM_SNPRINTF_MACRO\n#endif\n#if defined MBEDTLS_PLATFORM_STD_EXIT\n#define POLARSSL_PLATFORM_STD_EXIT MBEDTLS_PLATFORM_STD_EXIT\n#endif\n#if defined MBEDTLS_PLATFORM_STD_FPRINTF\n#define POLARSSL_PLATFORM_STD_FPRINTF MBEDTLS_PLATFORM_STD_FPRINTF\n#endif\n#if defined MBEDTLS_PLATFORM_STD_FREE\n#define POLARSSL_PLATFORM_STD_FREE MBEDTLS_PLATFORM_STD_FREE\n#endif\n#if defined MBEDTLS_PLATFORM_STD_MEM_HDR\n#define POLARSSL_PLATFORM_STD_MEM_HDR MBEDTLS_PLATFORM_STD_MEM_HDR\n#endif\n#if defined MBEDTLS_PLATFORM_STD_PRINTF\n#define POLARSSL_PLATFORM_STD_PRINTF MBEDTLS_PLATFORM_STD_PRINTF\n#endif\n#if defined MBEDTLS_PLATFORM_STD_SNPRINTF\n#define POLARSSL_PLATFORM_STD_SNPRINTF MBEDTLS_PLATFORM_STD_SNPRINTF\n#endif\n#if defined MBEDTLS_PSK_MAX_LEN\n#define POLARSSL_PSK_MAX_LEN MBEDTLS_PSK_MAX_LEN\n#endif\n#if defined MBEDTLS_REMOVE_ARC4_CIPHERSUITES\n#define POLARSSL_REMOVE_ARC4_CIPHERSUITES MBEDTLS_REMOVE_ARC4_CIPHERSUITES\n#endif\n#if defined MBEDTLS_RIPEMD160_ALT\n#define POLARSSL_RIPEMD160_ALT MBEDTLS_RIPEMD160_ALT\n#endif\n#if defined MBEDTLS_RIPEMD160_C\n#define POLARSSL_RIPEMD160_C MBEDTLS_RIPEMD160_C\n#endif\n#if defined MBEDTLS_RIPEMD160_PROCESS_ALT\n#define POLARSSL_RIPEMD160_PROCESS_ALT MBEDTLS_RIPEMD160_PROCESS_ALT\n#endif\n#if defined MBEDTLS_RSA_C\n#define POLARSSL_RSA_C MBEDTLS_RSA_C\n#endif\n#if defined MBEDTLS_RSA_NO_CRT\n#define POLARSSL_RSA_NO_CRT MBEDTLS_RSA_NO_CRT\n#endif\n#if defined MBEDTLS_SELF_TEST\n#define POLARSSL_SELF_TEST MBEDTLS_SELF_TEST\n#endif\n#if defined MBEDTLS_SHA1_ALT\n#define POLARSSL_SHA1_ALT MBEDTLS_SHA1_ALT\n#endif\n#if defined MBEDTLS_SHA1_C\n#define POLARSSL_SHA1_C MBEDTLS_SHA1_C\n#endif\n#if defined MBEDTLS_SHA1_PROCESS_ALT\n#define POLARSSL_SHA1_PROCESS_ALT MBEDTLS_SHA1_PROCESS_ALT\n#endif\n#if defined MBEDTLS_SHA256_ALT\n#define POLARSSL_SHA256_ALT MBEDTLS_SHA256_ALT\n#endif\n#if defined MBEDTLS_SHA256_C\n#define POLARSSL_SHA256_C MBEDTLS_SHA256_C\n#endif\n#if defined MBEDTLS_SHA256_PROCESS_ALT\n#define POLARSSL_SHA256_PROCESS_ALT MBEDTLS_SHA256_PROCESS_ALT\n#endif\n#if defined MBEDTLS_SHA512_ALT\n#define POLARSSL_SHA512_ALT MBEDTLS_SHA512_ALT\n#endif\n#if defined MBEDTLS_SHA512_C\n#define POLARSSL_SHA512_C MBEDTLS_SHA512_C\n#endif\n#if defined MBEDTLS_SHA512_PROCESS_ALT\n#define POLARSSL_SHA512_PROCESS_ALT MBEDTLS_SHA512_PROCESS_ALT\n#endif\n#if defined MBEDTLS_SSL_ALL_ALERT_MESSAGES\n#define POLARSSL_SSL_ALL_ALERT_MESSAGES MBEDTLS_SSL_ALL_ALERT_MESSAGES\n#endif\n#if defined MBEDTLS_SSL_ALPN\n#define POLARSSL_SSL_ALPN MBEDTLS_SSL_ALPN\n#endif\n#if defined MBEDTLS_SSL_CACHE_C\n#define POLARSSL_SSL_CACHE_C MBEDTLS_SSL_CACHE_C\n#endif\n#if defined MBEDTLS_SSL_CBC_RECORD_SPLITTING\n#define POLARSSL_SSL_CBC_RECORD_SPLITTING MBEDTLS_SSL_CBC_RECORD_SPLITTING\n#endif\n#if defined MBEDTLS_SSL_CLI_C\n#define POLARSSL_SSL_CLI_C MBEDTLS_SSL_CLI_C\n#endif\n#if defined MBEDTLS_SSL_COOKIE_C\n#define POLARSSL_SSL_COOKIE_C MBEDTLS_SSL_COOKIE_C\n#endif\n#if defined MBEDTLS_SSL_COOKIE_TIMEOUT\n#define POLARSSL_SSL_COOKIE_TIMEOUT MBEDTLS_SSL_COOKIE_TIMEOUT\n#endif\n#if defined MBEDTLS_SSL_DEBUG_ALL\n#define POLARSSL_SSL_DEBUG_ALL MBEDTLS_SSL_DEBUG_ALL\n#endif\n#if defined MBEDTLS_SSL_DTLS_ANTI_REPLAY\n#define POLARSSL_SSL_DTLS_ANTI_REPLAY MBEDTLS_SSL_DTLS_ANTI_REPLAY\n#endif\n#if defined MBEDTLS_SSL_DTLS_BADMAC_LIMIT\n#define POLARSSL_SSL_DTLS_BADMAC_LIMIT MBEDTLS_SSL_DTLS_BADMAC_LIMIT\n#endif\n#if defined MBEDTLS_SSL_DTLS_HELLO_VERIFY\n#define POLARSSL_SSL_DTLS_HELLO_VERIFY MBEDTLS_SSL_DTLS_HELLO_VERIFY\n#endif\n#if defined MBEDTLS_SSL_ENCRYPT_THEN_MAC\n#define POLARSSL_SSL_ENCRYPT_THEN_MAC MBEDTLS_SSL_ENCRYPT_THEN_MAC\n#endif\n#if defined MBEDTLS_SSL_EXTENDED_MASTER_SECRET\n#define POLARSSL_SSL_EXTENDED_MASTER_SECRET MBEDTLS_SSL_EXTENDED_MASTER_SECRET\n#endif\n#if defined MBEDTLS_SSL_FALLBACK_SCSV\n#define POLARSSL_SSL_FALLBACK_SCSV MBEDTLS_SSL_FALLBACK_SCSV\n#endif\n#if defined MBEDTLS_SSL_HW_RECORD_ACCEL\n#define POLARSSL_SSL_HW_RECORD_ACCEL MBEDTLS_SSL_HW_RECORD_ACCEL\n#endif\n#if defined MBEDTLS_SSL_MAX_FRAGMENT_LENGTH\n#define POLARSSL_SSL_MAX_FRAGMENT_LENGTH MBEDTLS_SSL_MAX_FRAGMENT_LENGTH\n#endif\n#if defined MBEDTLS_SSL_PROTO_DTLS\n#define POLARSSL_SSL_PROTO_DTLS MBEDTLS_SSL_PROTO_DTLS\n#endif\n#if defined MBEDTLS_SSL_PROTO_SSL3\n#define POLARSSL_SSL_PROTO_SSL3 MBEDTLS_SSL_PROTO_SSL3\n#endif\n#if defined MBEDTLS_SSL_PROTO_TLS1\n#define POLARSSL_SSL_PROTO_TLS1 MBEDTLS_SSL_PROTO_TLS1\n#endif\n#if defined MBEDTLS_SSL_PROTO_TLS1_1\n#define POLARSSL_SSL_PROTO_TLS1_1 MBEDTLS_SSL_PROTO_TLS1_1\n#endif\n#if defined MBEDTLS_SSL_PROTO_TLS1_2\n#define POLARSSL_SSL_PROTO_TLS1_2 MBEDTLS_SSL_PROTO_TLS1_2\n#endif\n#if defined MBEDTLS_SSL_RENEGOTIATION\n#define POLARSSL_SSL_RENEGOTIATION MBEDTLS_SSL_RENEGOTIATION\n#endif\n#if defined MBEDTLS_SSL_SERVER_NAME_INDICATION\n#define POLARSSL_SSL_SERVER_NAME_INDICATION MBEDTLS_SSL_SERVER_NAME_INDICATION\n#endif\n#if defined MBEDTLS_SSL_SESSION_TICKETS\n#define POLARSSL_SSL_SESSION_TICKETS MBEDTLS_SSL_SESSION_TICKETS\n#endif\n#if defined MBEDTLS_SSL_SRV_C\n#define POLARSSL_SSL_SRV_C MBEDTLS_SSL_SRV_C\n#endif\n#if defined MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE\n#define POLARSSL_SSL_SRV_RESPECT_CLIENT_PREFERENCE MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE\n#endif\n#if defined MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO\n#define POLARSSL_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO\n#endif\n#if defined MBEDTLS_SSL_TLS_C\n#define POLARSSL_SSL_TLS_C MBEDTLS_SSL_TLS_C\n#endif\n#if defined MBEDTLS_SSL_TRUNCATED_HMAC\n#define POLARSSL_SSL_TRUNCATED_HMAC MBEDTLS_SSL_TRUNCATED_HMAC\n#endif\n#if defined MBEDTLS_THREADING_ALT\n#define POLARSSL_THREADING_ALT MBEDTLS_THREADING_ALT\n#endif\n#if defined MBEDTLS_THREADING_C\n#define POLARSSL_THREADING_C MBEDTLS_THREADING_C\n#endif\n#if defined MBEDTLS_THREADING_PTHREAD\n#define POLARSSL_THREADING_PTHREAD MBEDTLS_THREADING_PTHREAD\n#endif\n#if defined MBEDTLS_TIMING_ALT\n#define POLARSSL_TIMING_ALT MBEDTLS_TIMING_ALT\n#endif\n#if defined MBEDTLS_TIMING_C\n#define POLARSSL_TIMING_C MBEDTLS_TIMING_C\n#endif\n#if defined MBEDTLS_VERSION_C\n#define POLARSSL_VERSION_C MBEDTLS_VERSION_C\n#endif\n#if defined MBEDTLS_VERSION_FEATURES\n#define POLARSSL_VERSION_FEATURES MBEDTLS_VERSION_FEATURES\n#endif\n#if defined MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3\n#define POLARSSL_X509_ALLOW_EXTENSIONS_NON_V3 MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3\n#endif\n#if defined MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION\n#define POLARSSL_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION\n#endif\n#if defined MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE\n#define POLARSSL_X509_CHECK_EXTENDED_KEY_USAGE MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE\n#endif\n#if defined MBEDTLS_X509_CHECK_KEY_USAGE\n#define POLARSSL_X509_CHECK_KEY_USAGE MBEDTLS_X509_CHECK_KEY_USAGE\n#endif\n#if defined MBEDTLS_X509_CREATE_C\n#define POLARSSL_X509_CREATE_C MBEDTLS_X509_CREATE_C\n#endif\n#if defined MBEDTLS_X509_CRL_PARSE_C\n#define POLARSSL_X509_CRL_PARSE_C MBEDTLS_X509_CRL_PARSE_C\n#endif\n#if defined MBEDTLS_X509_CRT_PARSE_C\n#define POLARSSL_X509_CRT_PARSE_C MBEDTLS_X509_CRT_PARSE_C\n#endif\n#if defined MBEDTLS_X509_CRT_WRITE_C\n#define POLARSSL_X509_CRT_WRITE_C MBEDTLS_X509_CRT_WRITE_C\n#endif\n#if defined MBEDTLS_X509_CSR_PARSE_C\n#define POLARSSL_X509_CSR_PARSE_C MBEDTLS_X509_CSR_PARSE_C\n#endif\n#if defined MBEDTLS_X509_CSR_WRITE_C\n#define POLARSSL_X509_CSR_WRITE_C MBEDTLS_X509_CSR_WRITE_C\n#endif\n#if defined MBEDTLS_X509_MAX_INTERMEDIATE_CA\n#define POLARSSL_X509_MAX_INTERMEDIATE_CA MBEDTLS_X509_MAX_INTERMEDIATE_CA\n#endif\n#if defined MBEDTLS_X509_RSASSA_PSS_SUPPORT\n#define POLARSSL_X509_RSASSA_PSS_SUPPORT MBEDTLS_X509_RSASSA_PSS_SUPPORT\n#endif\n#if defined MBEDTLS_X509_USE_C\n#define POLARSSL_X509_USE_C MBEDTLS_X509_USE_C\n#endif\n#if defined MBEDTLS_XTEA_ALT\n#define POLARSSL_XTEA_ALT MBEDTLS_XTEA_ALT\n#endif\n#if defined MBEDTLS_XTEA_C\n#define POLARSSL_XTEA_C MBEDTLS_XTEA_C\n#endif\n#if defined MBEDTLS_ZLIB_SUPPORT\n#define POLARSSL_ZLIB_SUPPORT MBEDTLS_ZLIB_SUPPORT\n#endif\n\n/*\n * Misc names (macros, types, functions, enum constants...)\n */\n#define AES_DECRYPT MBEDTLS_AES_DECRYPT\n#define AES_ENCRYPT MBEDTLS_AES_ENCRYPT\n#define ASN1_BIT_STRING MBEDTLS_ASN1_BIT_STRING\n#define ASN1_BMP_STRING MBEDTLS_ASN1_BMP_STRING\n#define ASN1_BOOLEAN MBEDTLS_ASN1_BOOLEAN\n#define ASN1_CHK_ADD MBEDTLS_ASN1_CHK_ADD\n#define ASN1_CONSTRUCTED MBEDTLS_ASN1_CONSTRUCTED\n#define ASN1_CONTEXT_SPECIFIC MBEDTLS_ASN1_CONTEXT_SPECIFIC\n#define ASN1_GENERALIZED_TIME MBEDTLS_ASN1_GENERALIZED_TIME\n#define ASN1_IA5_STRING MBEDTLS_ASN1_IA5_STRING\n#define ASN1_INTEGER MBEDTLS_ASN1_INTEGER\n#define ASN1_NULL MBEDTLS_ASN1_NULL\n#define ASN1_OCTET_STRING MBEDTLS_ASN1_OCTET_STRING\n#define ASN1_OID MBEDTLS_ASN1_OID\n#define ASN1_PRIMITIVE MBEDTLS_ASN1_PRIMITIVE\n#define ASN1_PRINTABLE_STRING MBEDTLS_ASN1_PRINTABLE_STRING\n#define ASN1_SEQUENCE MBEDTLS_ASN1_SEQUENCE\n#define ASN1_SET MBEDTLS_ASN1_SET\n#define ASN1_T61_STRING MBEDTLS_ASN1_T61_STRING\n#define ASN1_UNIVERSAL_STRING MBEDTLS_ASN1_UNIVERSAL_STRING\n#define ASN1_UTC_TIME MBEDTLS_ASN1_UTC_TIME\n#define ASN1_UTF8_STRING MBEDTLS_ASN1_UTF8_STRING\n#define BADCERT_CN_MISMATCH MBEDTLS_X509_BADCERT_CN_MISMATCH\n#define BADCERT_EXPIRED MBEDTLS_X509_BADCERT_EXPIRED\n#define BADCERT_FUTURE MBEDTLS_X509_BADCERT_FUTURE\n#define BADCERT_MISSING MBEDTLS_X509_BADCERT_MISSING\n#define BADCERT_NOT_TRUSTED MBEDTLS_X509_BADCERT_NOT_TRUSTED\n#define BADCERT_OTHER MBEDTLS_X509_BADCERT_OTHER\n#define BADCERT_REVOKED MBEDTLS_X509_BADCERT_REVOKED\n#define BADCERT_SKIP_VERIFY MBEDTLS_X509_BADCERT_SKIP_VERIFY\n#define BADCRL_EXPIRED MBEDTLS_X509_BADCRL_EXPIRED\n#define BADCRL_FUTURE MBEDTLS_X509_BADCRL_FUTURE\n#define BADCRL_NOT_TRUSTED MBEDTLS_X509_BADCRL_NOT_TRUSTED\n#define BLOWFISH_BLOCKSIZE MBEDTLS_BLOWFISH_BLOCKSIZE\n#define BLOWFISH_DECRYPT MBEDTLS_BLOWFISH_DECRYPT\n#define BLOWFISH_ENCRYPT MBEDTLS_BLOWFISH_ENCRYPT\n#define BLOWFISH_MAX_KEY MBEDTLS_BLOWFISH_MAX_KEY_BITS\n#define BLOWFISH_MIN_KEY MBEDTLS_BLOWFISH_MIN_KEY_BITS\n#define BLOWFISH_ROUNDS MBEDTLS_BLOWFISH_ROUNDS\n#define CAMELLIA_DECRYPT MBEDTLS_CAMELLIA_DECRYPT\n#define CAMELLIA_ENCRYPT MBEDTLS_CAMELLIA_ENCRYPT\n#define COLLECT_SIZE MBEDTLS_HAVEGE_COLLECT_SIZE\n#define CTR_DRBG_BLOCKSIZE MBEDTLS_CTR_DRBG_BLOCKSIZE\n#define CTR_DRBG_ENTROPY_LEN MBEDTLS_CTR_DRBG_ENTROPY_LEN\n#define CTR_DRBG_KEYBITS MBEDTLS_CTR_DRBG_KEYBITS\n#define CTR_DRBG_KEYSIZE MBEDTLS_CTR_DRBG_KEYSIZE\n#define CTR_DRBG_MAX_INPUT MBEDTLS_CTR_DRBG_MAX_INPUT\n#define CTR_DRBG_MAX_REQUEST MBEDTLS_CTR_DRBG_MAX_REQUEST\n#define CTR_DRBG_MAX_SEED_INPUT MBEDTLS_CTR_DRBG_MAX_SEED_INPUT\n#define CTR_DRBG_PR_OFF MBEDTLS_CTR_DRBG_PR_OFF\n#define CTR_DRBG_PR_ON MBEDTLS_CTR_DRBG_PR_ON\n#define CTR_DRBG_RESEED_INTERVAL MBEDTLS_CTR_DRBG_RESEED_INTERVAL\n#define CTR_DRBG_SEEDLEN MBEDTLS_CTR_DRBG_SEEDLEN\n#define DEPRECATED MBEDTLS_DEPRECATED\n#define DES_DECRYPT MBEDTLS_DES_DECRYPT\n#define DES_ENCRYPT MBEDTLS_DES_ENCRYPT\n#define DES_KEY_SIZE MBEDTLS_DES_KEY_SIZE\n#define ENTROPY_BLOCK_SIZE MBEDTLS_ENTROPY_BLOCK_SIZE\n#define ENTROPY_MAX_GATHER MBEDTLS_ENTROPY_MAX_GATHER\n#define ENTROPY_MAX_SEED_SIZE MBEDTLS_ENTROPY_MAX_SEED_SIZE\n#define ENTROPY_MAX_SOURCES MBEDTLS_ENTROPY_MAX_SOURCES\n#define ENTROPY_MIN_HARDCLOCK MBEDTLS_ENTROPY_MIN_HARDCLOCK\n#define ENTROPY_MIN_HAVEGE MBEDTLS_ENTROPY_MIN_HAVEGE\n#define ENTROPY_MIN_PLATFORM MBEDTLS_ENTROPY_MIN_PLATFORM\n#define ENTROPY_SOURCE_MANUAL MBEDTLS_ENTROPY_SOURCE_MANUAL\n#define EXT_AUTHORITY_KEY_IDENTIFIER MBEDTLS_X509_EXT_AUTHORITY_KEY_IDENTIFIER\n#define EXT_BASIC_CONSTRAINTS MBEDTLS_X509_EXT_BASIC_CONSTRAINTS\n#define EXT_CERTIFICATE_POLICIES MBEDTLS_X509_EXT_CERTIFICATE_POLICIES\n#define EXT_CRL_DISTRIBUTION_POINTS MBEDTLS_X509_EXT_CRL_DISTRIBUTION_POINTS\n#define EXT_EXTENDED_KEY_USAGE MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE\n#define EXT_FRESHEST_CRL MBEDTLS_X509_EXT_FRESHEST_CRL\n#define EXT_INIHIBIT_ANYPOLICY MBEDTLS_X509_EXT_INIHIBIT_ANYPOLICY\n#define EXT_ISSUER_ALT_NAME MBEDTLS_X509_EXT_ISSUER_ALT_NAME\n#define EXT_KEY_USAGE MBEDTLS_X509_EXT_KEY_USAGE\n#define EXT_NAME_CONSTRAINTS MBEDTLS_X509_EXT_NAME_CONSTRAINTS\n#define EXT_NS_CERT_TYPE MBEDTLS_X509_EXT_NS_CERT_TYPE\n#define EXT_POLICY_CONSTRAINTS MBEDTLS_X509_EXT_POLICY_CONSTRAINTS\n#define EXT_POLICY_MAPPINGS MBEDTLS_X509_EXT_POLICY_MAPPINGS\n#define EXT_SUBJECT_ALT_NAME MBEDTLS_X509_EXT_SUBJECT_ALT_NAME\n#define EXT_SUBJECT_DIRECTORY_ATTRS MBEDTLS_X509_EXT_SUBJECT_DIRECTORY_ATTRS\n#define EXT_SUBJECT_KEY_IDENTIFIER MBEDTLS_X509_EXT_SUBJECT_KEY_IDENTIFIER\n#define GCM_DECRYPT MBEDTLS_GCM_DECRYPT\n#define GCM_ENCRYPT MBEDTLS_GCM_ENCRYPT\n#define KU_CRL_SIGN MBEDTLS_X509_KU_CRL_SIGN\n#define KU_DATA_ENCIPHERMENT MBEDTLS_X509_KU_DATA_ENCIPHERMENT\n#define KU_DIGITAL_SIGNATURE MBEDTLS_X509_KU_DIGITAL_SIGNATURE\n#define KU_KEY_AGREEMENT MBEDTLS_X509_KU_KEY_AGREEMENT\n#define KU_KEY_CERT_SIGN MBEDTLS_X509_KU_KEY_CERT_SIGN\n#define KU_KEY_ENCIPHERMENT MBEDTLS_X509_KU_KEY_ENCIPHERMENT\n#define KU_NON_REPUDIATION MBEDTLS_X509_KU_NON_REPUDIATION\n#define LN_2_DIV_LN_10_SCALE100 MBEDTLS_LN_2_DIV_LN_10_SCALE100\n#define MEMORY_VERIFY_ALLOC MBEDTLS_MEMORY_VERIFY_ALLOC\n#define MEMORY_VERIFY_ALWAYS MBEDTLS_MEMORY_VERIFY_ALWAYS\n#define MEMORY_VERIFY_FREE MBEDTLS_MEMORY_VERIFY_FREE\n#define MEMORY_VERIFY_NONE MBEDTLS_MEMORY_VERIFY_NONE\n#define MPI_CHK MBEDTLS_MPI_CHK\n#define NET_PROTO_TCP MBEDTLS_NET_PROTO_TCP\n#define NET_PROTO_UDP MBEDTLS_NET_PROTO_UDP\n#define NS_CERT_TYPE_EMAIL MBEDTLS_X509_NS_CERT_TYPE_EMAIL\n#define NS_CERT_TYPE_EMAIL_CA MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA\n#define NS_CERT_TYPE_OBJECT_SIGNING MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING\n#define NS_CERT_TYPE_OBJECT_SIGNING_CA MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA\n#define NS_CERT_TYPE_RESERVED MBEDTLS_X509_NS_CERT_TYPE_RESERVED\n#define NS_CERT_TYPE_SSL_CA MBEDTLS_X509_NS_CERT_TYPE_SSL_CA\n#define NS_CERT_TYPE_SSL_CLIENT MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT\n#define NS_CERT_TYPE_SSL_SERVER MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER\n#define OID_ANSI_X9_62 MBEDTLS_OID_ANSI_X9_62\n#define OID_ANSI_X9_62_FIELD_TYPE MBEDTLS_OID_ANSI_X9_62_FIELD_TYPE\n#define OID_ANSI_X9_62_PRIME_FIELD MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD\n#define OID_ANSI_X9_62_SIG MBEDTLS_OID_ANSI_X9_62_SIG\n#define OID_ANSI_X9_62_SIG_SHA2 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2\n#define OID_ANY_EXTENDED_KEY_USAGE MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE\n#define OID_AT MBEDTLS_OID_AT\n#define OID_AT_CN MBEDTLS_OID_AT_CN\n#define OID_AT_COUNTRY MBEDTLS_OID_AT_COUNTRY\n#define OID_AT_DN_QUALIFIER MBEDTLS_OID_AT_DN_QUALIFIER\n#define OID_AT_GENERATION_QUALIFIER MBEDTLS_OID_AT_GENERATION_QUALIFIER\n#define OID_AT_GIVEN_NAME MBEDTLS_OID_AT_GIVEN_NAME\n#define OID_AT_INITIALS MBEDTLS_OID_AT_INITIALS\n#define OID_AT_LOCALITY MBEDTLS_OID_AT_LOCALITY\n#define OID_AT_ORGANIZATION MBEDTLS_OID_AT_ORGANIZATION\n#define OID_AT_ORG_UNIT MBEDTLS_OID_AT_ORG_UNIT\n#define OID_AT_POSTAL_ADDRESS MBEDTLS_OID_AT_POSTAL_ADDRESS\n#define OID_AT_POSTAL_CODE MBEDTLS_OID_AT_POSTAL_CODE\n#define OID_AT_PSEUDONYM MBEDTLS_OID_AT_PSEUDONYM\n#define OID_AT_SERIAL_NUMBER MBEDTLS_OID_AT_SERIAL_NUMBER\n#define OID_AT_STATE MBEDTLS_OID_AT_STATE\n#define OID_AT_SUR_NAME MBEDTLS_OID_AT_SUR_NAME\n#define OID_AT_TITLE MBEDTLS_OID_AT_TITLE\n#define OID_AT_UNIQUE_IDENTIFIER MBEDTLS_OID_AT_UNIQUE_IDENTIFIER\n#define OID_AUTHORITY_KEY_IDENTIFIER MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER\n#define OID_BASIC_CONSTRAINTS MBEDTLS_OID_BASIC_CONSTRAINTS\n#define OID_CERTICOM MBEDTLS_OID_CERTICOM\n#define OID_CERTIFICATE_POLICIES MBEDTLS_OID_CERTIFICATE_POLICIES\n#define OID_CLIENT_AUTH MBEDTLS_OID_CLIENT_AUTH\n#define OID_CMP MBEDTLS_OID_CMP\n#define OID_CODE_SIGNING MBEDTLS_OID_CODE_SIGNING\n#define OID_COUNTRY_US MBEDTLS_OID_COUNTRY_US\n#define OID_CRL_DISTRIBUTION_POINTS MBEDTLS_OID_CRL_DISTRIBUTION_POINTS\n#define OID_CRL_NUMBER MBEDTLS_OID_CRL_NUMBER\n#define OID_DES_CBC MBEDTLS_OID_DES_CBC\n#define OID_DES_EDE3_CBC MBEDTLS_OID_DES_EDE3_CBC\n#define OID_DIGEST_ALG_MD2 MBEDTLS_OID_DIGEST_ALG_MD2\n#define OID_DIGEST_ALG_MD4 MBEDTLS_OID_DIGEST_ALG_MD4\n#define OID_DIGEST_ALG_MD5 MBEDTLS_OID_DIGEST_ALG_MD5\n#define OID_DIGEST_ALG_SHA1 MBEDTLS_OID_DIGEST_ALG_SHA1\n#define OID_DIGEST_ALG_SHA224 MBEDTLS_OID_DIGEST_ALG_SHA224\n#define OID_DIGEST_ALG_SHA256 MBEDTLS_OID_DIGEST_ALG_SHA256\n#define OID_DIGEST_ALG_SHA384 MBEDTLS_OID_DIGEST_ALG_SHA384\n#define OID_DIGEST_ALG_SHA512 MBEDTLS_OID_DIGEST_ALG_SHA512\n#define OID_DOMAIN_COMPONENT MBEDTLS_OID_DOMAIN_COMPONENT\n#define OID_ECDSA_SHA1 MBEDTLS_OID_ECDSA_SHA1\n#define OID_ECDSA_SHA224 MBEDTLS_OID_ECDSA_SHA224\n#define OID_ECDSA_SHA256 MBEDTLS_OID_ECDSA_SHA256\n#define OID_ECDSA_SHA384 MBEDTLS_OID_ECDSA_SHA384\n#define OID_ECDSA_SHA512 MBEDTLS_OID_ECDSA_SHA512\n#define OID_EC_ALG_ECDH MBEDTLS_OID_EC_ALG_ECDH\n#define OID_EC_ALG_UNRESTRICTED MBEDTLS_OID_EC_ALG_UNRESTRICTED\n#define OID_EC_BRAINPOOL_V1 MBEDTLS_OID_EC_BRAINPOOL_V1\n#define OID_EC_GRP_BP256R1 MBEDTLS_OID_EC_GRP_BP256R1\n#define OID_EC_GRP_BP384R1 MBEDTLS_OID_EC_GRP_BP384R1\n#define OID_EC_GRP_BP512R1 MBEDTLS_OID_EC_GRP_BP512R1\n#define OID_EC_GRP_SECP192K1 MBEDTLS_OID_EC_GRP_SECP192K1\n#define OID_EC_GRP_SECP192R1 MBEDTLS_OID_EC_GRP_SECP192R1\n#define OID_EC_GRP_SECP224K1 MBEDTLS_OID_EC_GRP_SECP224K1\n#define OID_EC_GRP_SECP224R1 MBEDTLS_OID_EC_GRP_SECP224R1\n#define OID_EC_GRP_SECP256K1 MBEDTLS_OID_EC_GRP_SECP256K1\n#define OID_EC_GRP_SECP256R1 MBEDTLS_OID_EC_GRP_SECP256R1\n#define OID_EC_GRP_SECP384R1 MBEDTLS_OID_EC_GRP_SECP384R1\n#define OID_EC_GRP_SECP521R1 MBEDTLS_OID_EC_GRP_SECP521R1\n#define OID_EMAIL_PROTECTION MBEDTLS_OID_EMAIL_PROTECTION\n#define OID_EXTENDED_KEY_USAGE MBEDTLS_OID_EXTENDED_KEY_USAGE\n#define OID_FRESHEST_CRL MBEDTLS_OID_FRESHEST_CRL\n#define OID_GOV MBEDTLS_OID_GOV\n#define OID_HMAC_SHA1 MBEDTLS_OID_HMAC_SHA1\n#define OID_ID_CE MBEDTLS_OID_ID_CE\n#define OID_INIHIBIT_ANYPOLICY MBEDTLS_OID_INIHIBIT_ANYPOLICY\n#define OID_ISO_CCITT_DS MBEDTLS_OID_ISO_CCITT_DS\n#define OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_ISO_IDENTIFIED_ORG\n#define OID_ISO_ITU_COUNTRY MBEDTLS_OID_ISO_ITU_COUNTRY\n#define OID_ISO_ITU_US_ORG MBEDTLS_OID_ISO_ITU_US_ORG\n#define OID_ISO_MEMBER_BODIES MBEDTLS_OID_ISO_MEMBER_BODIES\n#define OID_ISSUER_ALT_NAME MBEDTLS_OID_ISSUER_ALT_NAME\n#define OID_KEY_USAGE MBEDTLS_OID_KEY_USAGE\n#define OID_KP MBEDTLS_OID_KP\n#define OID_MGF1 MBEDTLS_OID_MGF1\n#define OID_NAME_CONSTRAINTS MBEDTLS_OID_NAME_CONSTRAINTS\n#define OID_NETSCAPE MBEDTLS_OID_NETSCAPE\n#define OID_NS_BASE_URL MBEDTLS_OID_NS_BASE_URL\n#define OID_NS_CA_POLICY_URL MBEDTLS_OID_NS_CA_POLICY_URL\n#define OID_NS_CA_REVOCATION_URL MBEDTLS_OID_NS_CA_REVOCATION_URL\n#define OID_NS_CERT MBEDTLS_OID_NS_CERT\n#define OID_NS_CERT_SEQUENCE MBEDTLS_OID_NS_CERT_SEQUENCE\n#define OID_NS_CERT_TYPE MBEDTLS_OID_NS_CERT_TYPE\n#define OID_NS_COMMENT MBEDTLS_OID_NS_COMMENT\n#define OID_NS_DATA_TYPE MBEDTLS_OID_NS_DATA_TYPE\n#define OID_NS_RENEWAL_URL MBEDTLS_OID_NS_RENEWAL_URL\n#define OID_NS_REVOCATION_URL MBEDTLS_OID_NS_REVOCATION_URL\n#define OID_NS_SSL_SERVER_NAME MBEDTLS_OID_NS_SSL_SERVER_NAME\n#define OID_OCSP_SIGNING MBEDTLS_OID_OCSP_SIGNING\n#define OID_OIW_SECSIG MBEDTLS_OID_OIW_SECSIG\n#define OID_OIW_SECSIG_ALG MBEDTLS_OID_OIW_SECSIG_ALG\n#define OID_OIW_SECSIG_SHA1 MBEDTLS_OID_OIW_SECSIG_SHA1\n#define OID_ORGANIZATION MBEDTLS_OID_ORGANIZATION\n#define OID_ORG_ANSI_X9_62 MBEDTLS_OID_ORG_ANSI_X9_62\n#define OID_ORG_CERTICOM MBEDTLS_OID_ORG_CERTICOM\n#define OID_ORG_DOD MBEDTLS_OID_ORG_DOD\n#define OID_ORG_GOV MBEDTLS_OID_ORG_GOV\n#define OID_ORG_NETSCAPE MBEDTLS_OID_ORG_NETSCAPE\n#define OID_ORG_OIW MBEDTLS_OID_ORG_OIW\n#define OID_ORG_RSA_DATA_SECURITY MBEDTLS_OID_ORG_RSA_DATA_SECURITY\n#define OID_ORG_TELETRUST MBEDTLS_OID_ORG_TELETRUST\n#define OID_PKCS MBEDTLS_OID_PKCS\n#define OID_PKCS1 MBEDTLS_OID_PKCS1\n#define OID_PKCS12 MBEDTLS_OID_PKCS12\n#define OID_PKCS12_PBE MBEDTLS_OID_PKCS12_PBE\n#define OID_PKCS12_PBE_SHA1_DES2_EDE_CBC MBEDTLS_OID_PKCS12_PBE_SHA1_DES2_EDE_CBC\n#define OID_PKCS12_PBE_SHA1_DES3_EDE_CBC MBEDTLS_OID_PKCS12_PBE_SHA1_DES3_EDE_CBC\n#define OID_PKCS12_PBE_SHA1_RC2_128_CBC MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_128_CBC\n#define OID_PKCS12_PBE_SHA1_RC2_40_CBC MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_40_CBC\n#define OID_PKCS12_PBE_SHA1_RC4_128 MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_128\n#define OID_PKCS12_PBE_SHA1_RC4_40 MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_40\n#define OID_PKCS1_MD2 MBEDTLS_OID_PKCS1_MD2\n#define OID_PKCS1_MD4 MBEDTLS_OID_PKCS1_MD4\n#define OID_PKCS1_MD5 MBEDTLS_OID_PKCS1_MD5\n#define OID_PKCS1_RSA MBEDTLS_OID_PKCS1_RSA\n#define OID_PKCS1_SHA1 MBEDTLS_OID_PKCS1_SHA1\n#define OID_PKCS1_SHA224 MBEDTLS_OID_PKCS1_SHA224\n#define OID_PKCS1_SHA256 MBEDTLS_OID_PKCS1_SHA256\n#define OID_PKCS1_SHA384 MBEDTLS_OID_PKCS1_SHA384\n#define OID_PKCS1_SHA512 MBEDTLS_OID_PKCS1_SHA512\n#define OID_PKCS5 MBEDTLS_OID_PKCS5\n#define OID_PKCS5_PBES2 MBEDTLS_OID_PKCS5_PBES2\n#define OID_PKCS5_PBE_MD2_DES_CBC MBEDTLS_OID_PKCS5_PBE_MD2_DES_CBC\n#define OID_PKCS5_PBE_MD2_RC2_CBC MBEDTLS_OID_PKCS5_PBE_MD2_RC2_CBC\n#define OID_PKCS5_PBE_MD5_DES_CBC MBEDTLS_OID_PKCS5_PBE_MD5_DES_CBC\n#define OID_PKCS5_PBE_MD5_RC2_CBC MBEDTLS_OID_PKCS5_PBE_MD5_RC2_CBC\n#define OID_PKCS5_PBE_SHA1_DES_CBC MBEDTLS_OID_PKCS5_PBE_SHA1_DES_CBC\n#define OID_PKCS5_PBE_SHA1_RC2_CBC MBEDTLS_OID_PKCS5_PBE_SHA1_RC2_CBC\n#define OID_PKCS5_PBKDF2 MBEDTLS_OID_PKCS5_PBKDF2\n#define OID_PKCS5_PBMAC1 MBEDTLS_OID_PKCS5_PBMAC1\n#define OID_PKCS9 MBEDTLS_OID_PKCS9\n#define OID_PKCS9_CSR_EXT_REQ MBEDTLS_OID_PKCS9_CSR_EXT_REQ\n#define OID_PKCS9_EMAIL MBEDTLS_OID_PKCS9_EMAIL\n#define OID_PKIX MBEDTLS_OID_PKIX\n#define OID_POLICY_CONSTRAINTS MBEDTLS_OID_POLICY_CONSTRAINTS\n#define OID_POLICY_MAPPINGS MBEDTLS_OID_POLICY_MAPPINGS\n#define OID_PRIVATE_KEY_USAGE_PERIOD MBEDTLS_OID_PRIVATE_KEY_USAGE_PERIOD\n#define OID_RSASSA_PSS MBEDTLS_OID_RSASSA_PSS\n#define OID_RSA_COMPANY MBEDTLS_OID_RSA_COMPANY\n#define OID_RSA_SHA_OBS MBEDTLS_OID_RSA_SHA_OBS\n#define OID_SERVER_AUTH MBEDTLS_OID_SERVER_AUTH\n#define OID_SIZE MBEDTLS_OID_SIZE\n#define OID_SUBJECT_ALT_NAME MBEDTLS_OID_SUBJECT_ALT_NAME\n#define OID_SUBJECT_DIRECTORY_ATTRS MBEDTLS_OID_SUBJECT_DIRECTORY_ATTRS\n#define OID_SUBJECT_KEY_IDENTIFIER MBEDTLS_OID_SUBJECT_KEY_IDENTIFIER\n#define OID_TELETRUST MBEDTLS_OID_TELETRUST\n#define OID_TIME_STAMPING MBEDTLS_OID_TIME_STAMPING\n#define PADLOCK_ACE MBEDTLS_PADLOCK_ACE\n#define PADLOCK_ALIGN16 MBEDTLS_PADLOCK_ALIGN16\n#define PADLOCK_PHE MBEDTLS_PADLOCK_PHE\n#define PADLOCK_PMM MBEDTLS_PADLOCK_PMM\n#define PADLOCK_RNG MBEDTLS_PADLOCK_RNG\n#define PKCS12_DERIVE_IV MBEDTLS_PKCS12_DERIVE_IV\n#define PKCS12_DERIVE_KEY MBEDTLS_PKCS12_DERIVE_KEY\n#define PKCS12_DERIVE_MAC_KEY MBEDTLS_PKCS12_DERIVE_MAC_KEY\n#define PKCS12_PBE_DECRYPT MBEDTLS_PKCS12_PBE_DECRYPT\n#define PKCS12_PBE_ENCRYPT MBEDTLS_PKCS12_PBE_ENCRYPT\n#define PKCS5_DECRYPT MBEDTLS_PKCS5_DECRYPT\n#define PKCS5_ENCRYPT MBEDTLS_PKCS5_ENCRYPT\n#define POLARSSL_AESNI_AES MBEDTLS_AESNI_AES\n#define POLARSSL_AESNI_CLMUL MBEDTLS_AESNI_CLMUL\n#define POLARSSL_AESNI_H MBEDTLS_AESNI_H\n#define POLARSSL_AES_H MBEDTLS_AES_H\n#define POLARSSL_ARC4_H MBEDTLS_ARC4_H\n#define POLARSSL_ASN1_H MBEDTLS_ASN1_H\n#define POLARSSL_ASN1_WRITE_H MBEDTLS_ASN1_WRITE_H\n#define POLARSSL_BASE64_H MBEDTLS_BASE64_H\n#define POLARSSL_BIGNUM_H MBEDTLS_BIGNUM_H\n#define POLARSSL_BLOWFISH_H MBEDTLS_BLOWFISH_H\n#define POLARSSL_BN_MUL_H MBEDTLS_BN_MUL_H\n#define POLARSSL_CAMELLIA_H MBEDTLS_CAMELLIA_H\n#define POLARSSL_CCM_H MBEDTLS_CCM_H\n#define POLARSSL_CERTS_H MBEDTLS_CERTS_H\n#define POLARSSL_CHECK_CONFIG_H MBEDTLS_CHECK_CONFIG_H\n#define POLARSSL_CIPHERSUITE_NODTLS MBEDTLS_CIPHERSUITE_NODTLS\n#define POLARSSL_CIPHERSUITE_SHORT_TAG MBEDTLS_CIPHERSUITE_SHORT_TAG\n#define POLARSSL_CIPHERSUITE_WEAK MBEDTLS_CIPHERSUITE_WEAK\n#define POLARSSL_CIPHER_AES_128_CBC MBEDTLS_CIPHER_AES_128_CBC\n#define POLARSSL_CIPHER_AES_128_CCM MBEDTLS_CIPHER_AES_128_CCM\n#define POLARSSL_CIPHER_AES_128_CFB128 MBEDTLS_CIPHER_AES_128_CFB128\n#define POLARSSL_CIPHER_AES_128_CTR MBEDTLS_CIPHER_AES_128_CTR\n#define POLARSSL_CIPHER_AES_128_ECB MBEDTLS_CIPHER_AES_128_ECB\n#define POLARSSL_CIPHER_AES_128_GCM MBEDTLS_CIPHER_AES_128_GCM\n#define POLARSSL_CIPHER_AES_192_CBC MBEDTLS_CIPHER_AES_192_CBC\n#define POLARSSL_CIPHER_AES_192_CCM MBEDTLS_CIPHER_AES_192_CCM\n#define POLARSSL_CIPHER_AES_192_CFB128 MBEDTLS_CIPHER_AES_192_CFB128\n#define POLARSSL_CIPHER_AES_192_CTR MBEDTLS_CIPHER_AES_192_CTR\n#define POLARSSL_CIPHER_AES_192_ECB MBEDTLS_CIPHER_AES_192_ECB\n#define POLARSSL_CIPHER_AES_192_GCM MBEDTLS_CIPHER_AES_192_GCM\n#define POLARSSL_CIPHER_AES_256_CBC MBEDTLS_CIPHER_AES_256_CBC\n#define POLARSSL_CIPHER_AES_256_CCM MBEDTLS_CIPHER_AES_256_CCM\n#define POLARSSL_CIPHER_AES_256_CFB128 MBEDTLS_CIPHER_AES_256_CFB128\n#define POLARSSL_CIPHER_AES_256_CTR MBEDTLS_CIPHER_AES_256_CTR\n#define POLARSSL_CIPHER_AES_256_ECB MBEDTLS_CIPHER_AES_256_ECB\n#define POLARSSL_CIPHER_AES_256_GCM MBEDTLS_CIPHER_AES_256_GCM\n#define POLARSSL_CIPHER_ARC4_128 MBEDTLS_CIPHER_ARC4_128\n#define POLARSSL_CIPHER_BLOWFISH_CBC MBEDTLS_CIPHER_BLOWFISH_CBC\n#define POLARSSL_CIPHER_BLOWFISH_CFB64 MBEDTLS_CIPHER_BLOWFISH_CFB64\n#define POLARSSL_CIPHER_BLOWFISH_CTR MBEDTLS_CIPHER_BLOWFISH_CTR\n#define POLARSSL_CIPHER_BLOWFISH_ECB MBEDTLS_CIPHER_BLOWFISH_ECB\n#define POLARSSL_CIPHER_CAMELLIA_128_CBC MBEDTLS_CIPHER_CAMELLIA_128_CBC\n#define POLARSSL_CIPHER_CAMELLIA_128_CCM MBEDTLS_CIPHER_CAMELLIA_128_CCM\n#define POLARSSL_CIPHER_CAMELLIA_128_CFB128 MBEDTLS_CIPHER_CAMELLIA_128_CFB128\n#define POLARSSL_CIPHER_CAMELLIA_128_CTR MBEDTLS_CIPHER_CAMELLIA_128_CTR\n#define POLARSSL_CIPHER_CAMELLIA_128_ECB MBEDTLS_CIPHER_CAMELLIA_128_ECB\n#define POLARSSL_CIPHER_CAMELLIA_128_GCM MBEDTLS_CIPHER_CAMELLIA_128_GCM\n#define POLARSSL_CIPHER_CAMELLIA_192_CBC MBEDTLS_CIPHER_CAMELLIA_192_CBC\n#define POLARSSL_CIPHER_CAMELLIA_192_CCM MBEDTLS_CIPHER_CAMELLIA_192_CCM\n#define POLARSSL_CIPHER_CAMELLIA_192_CFB128 MBEDTLS_CIPHER_CAMELLIA_192_CFB128\n#define POLARSSL_CIPHER_CAMELLIA_192_CTR MBEDTLS_CIPHER_CAMELLIA_192_CTR\n#define POLARSSL_CIPHER_CAMELLIA_192_ECB MBEDTLS_CIPHER_CAMELLIA_192_ECB\n#define POLARSSL_CIPHER_CAMELLIA_192_GCM MBEDTLS_CIPHER_CAMELLIA_192_GCM\n#define POLARSSL_CIPHER_CAMELLIA_256_CBC MBEDTLS_CIPHER_CAMELLIA_256_CBC\n#define POLARSSL_CIPHER_CAMELLIA_256_CCM MBEDTLS_CIPHER_CAMELLIA_256_CCM\n#define POLARSSL_CIPHER_CAMELLIA_256_CFB128 MBEDTLS_CIPHER_CAMELLIA_256_CFB128\n#define POLARSSL_CIPHER_CAMELLIA_256_CTR MBEDTLS_CIPHER_CAMELLIA_256_CTR\n#define POLARSSL_CIPHER_CAMELLIA_256_ECB MBEDTLS_CIPHER_CAMELLIA_256_ECB\n#define POLARSSL_CIPHER_CAMELLIA_256_GCM MBEDTLS_CIPHER_CAMELLIA_256_GCM\n#define POLARSSL_CIPHER_DES_CBC MBEDTLS_CIPHER_DES_CBC\n#define POLARSSL_CIPHER_DES_ECB MBEDTLS_CIPHER_DES_ECB\n#define POLARSSL_CIPHER_DES_EDE3_CBC MBEDTLS_CIPHER_DES_EDE3_CBC\n#define POLARSSL_CIPHER_DES_EDE3_ECB MBEDTLS_CIPHER_DES_EDE3_ECB\n#define POLARSSL_CIPHER_DES_EDE_CBC MBEDTLS_CIPHER_DES_EDE_CBC\n#define POLARSSL_CIPHER_DES_EDE_ECB MBEDTLS_CIPHER_DES_EDE_ECB\n#define POLARSSL_CIPHER_H MBEDTLS_CIPHER_H\n#define POLARSSL_CIPHER_ID_3DES MBEDTLS_CIPHER_ID_3DES\n#define POLARSSL_CIPHER_ID_AES MBEDTLS_CIPHER_ID_AES\n#define POLARSSL_CIPHER_ID_ARC4 MBEDTLS_CIPHER_ID_ARC4\n#define POLARSSL_CIPHER_ID_BLOWFISH MBEDTLS_CIPHER_ID_BLOWFISH\n#define POLARSSL_CIPHER_ID_CAMELLIA MBEDTLS_CIPHER_ID_CAMELLIA\n#define POLARSSL_CIPHER_ID_DES MBEDTLS_CIPHER_ID_DES\n#define POLARSSL_CIPHER_ID_NONE MBEDTLS_CIPHER_ID_NONE\n#define POLARSSL_CIPHER_ID_NULL MBEDTLS_CIPHER_ID_NULL\n#define POLARSSL_CIPHER_MODE_AEAD MBEDTLS_CIPHER_MODE_AEAD\n#define POLARSSL_CIPHER_MODE_STREAM MBEDTLS_CIPHER_MODE_STREAM\n#define POLARSSL_CIPHER_MODE_WITH_PADDING MBEDTLS_CIPHER_MODE_WITH_PADDING\n#define POLARSSL_CIPHER_NONE MBEDTLS_CIPHER_NONE\n#define POLARSSL_CIPHER_NULL MBEDTLS_CIPHER_NULL\n#define POLARSSL_CIPHER_VARIABLE_IV_LEN MBEDTLS_CIPHER_VARIABLE_IV_LEN\n#define POLARSSL_CIPHER_VARIABLE_KEY_LEN MBEDTLS_CIPHER_VARIABLE_KEY_LEN\n#define POLARSSL_CIPHER_WRAP_H MBEDTLS_CIPHER_WRAP_H\n#define POLARSSL_CONFIG_H MBEDTLS_CONFIG_H\n#define POLARSSL_CTR_DRBG_H MBEDTLS_CTR_DRBG_H\n#define POLARSSL_DEBUG_H MBEDTLS_DEBUG_H\n#define POLARSSL_DECRYPT MBEDTLS_DECRYPT\n#define POLARSSL_DES_H MBEDTLS_DES_H\n#define POLARSSL_DHM_H MBEDTLS_DHM_H\n#define POLARSSL_DHM_RFC3526_MODP_2048_G MBEDTLS_DHM_RFC3526_MODP_2048_G\n#define POLARSSL_DHM_RFC3526_MODP_2048_P MBEDTLS_DHM_RFC3526_MODP_2048_P\n#define POLARSSL_DHM_RFC3526_MODP_3072_G MBEDTLS_DHM_RFC3526_MODP_3072_G\n#define POLARSSL_DHM_RFC3526_MODP_3072_P MBEDTLS_DHM_RFC3526_MODP_3072_P\n#define POLARSSL_DHM_RFC5114_MODP_2048_G MBEDTLS_DHM_RFC5114_MODP_2048_G\n#define POLARSSL_DHM_RFC5114_MODP_2048_P MBEDTLS_DHM_RFC5114_MODP_2048_P\n#define POLARSSL_ECDH_H MBEDTLS_ECDH_H\n#define POLARSSL_ECDH_OURS MBEDTLS_ECDH_OURS\n#define POLARSSL_ECDH_THEIRS MBEDTLS_ECDH_THEIRS\n#define POLARSSL_ECDSA_H MBEDTLS_ECDSA_H\n#define POLARSSL_ECP_DP_BP256R1 MBEDTLS_ECP_DP_BP256R1\n#define POLARSSL_ECP_DP_BP384R1 MBEDTLS_ECP_DP_BP384R1\n#define POLARSSL_ECP_DP_BP512R1 MBEDTLS_ECP_DP_BP512R1\n#define POLARSSL_ECP_DP_M255 MBEDTLS_ECP_DP_CURVE25519\n#define POLARSSL_ECP_DP_MAX MBEDTLS_ECP_DP_MAX\n#define POLARSSL_ECP_DP_NONE MBEDTLS_ECP_DP_NONE\n#define POLARSSL_ECP_DP_SECP192K1 MBEDTLS_ECP_DP_SECP192K1\n#define POLARSSL_ECP_DP_SECP192R1 MBEDTLS_ECP_DP_SECP192R1\n#define POLARSSL_ECP_DP_SECP224K1 MBEDTLS_ECP_DP_SECP224K1\n#define POLARSSL_ECP_DP_SECP224R1 MBEDTLS_ECP_DP_SECP224R1\n#define POLARSSL_ECP_DP_SECP256K1 MBEDTLS_ECP_DP_SECP256K1\n#define POLARSSL_ECP_DP_SECP256R1 MBEDTLS_ECP_DP_SECP256R1\n#define POLARSSL_ECP_DP_SECP384R1 MBEDTLS_ECP_DP_SECP384R1\n#define POLARSSL_ECP_DP_SECP521R1 MBEDTLS_ECP_DP_SECP521R1\n#define POLARSSL_ECP_H MBEDTLS_ECP_H\n#define POLARSSL_ECP_MAX_BYTES MBEDTLS_ECP_MAX_BYTES\n#define POLARSSL_ECP_MAX_PT_LEN MBEDTLS_ECP_MAX_PT_LEN\n#define POLARSSL_ECP_PF_COMPRESSED MBEDTLS_ECP_PF_COMPRESSED\n#define POLARSSL_ECP_PF_UNCOMPRESSED MBEDTLS_ECP_PF_UNCOMPRESSED\n#define POLARSSL_ECP_TLS_NAMED_CURVE MBEDTLS_ECP_TLS_NAMED_CURVE\n#define POLARSSL_ENCRYPT MBEDTLS_ENCRYPT\n#define POLARSSL_ENTROPY_H MBEDTLS_ENTROPY_H\n#define POLARSSL_ENTROPY_POLL_H MBEDTLS_ENTROPY_POLL_H\n#define POLARSSL_ENTROPY_SHA256_ACCUMULATOR MBEDTLS_ENTROPY_SHA256_ACCUMULATOR\n#define POLARSSL_ENTROPY_SHA512_ACCUMULATOR MBEDTLS_ENTROPY_SHA512_ACCUMULATOR\n#define POLARSSL_ERROR_H MBEDTLS_ERROR_H\n#define POLARSSL_ERR_AES_INVALID_INPUT_LENGTH MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH\n#define POLARSSL_ERR_AES_INVALID_KEY_LENGTH MBEDTLS_ERR_AES_INVALID_KEY_LENGTH\n#define POLARSSL_ERR_ASN1_BUF_TOO_SMALL MBEDTLS_ERR_ASN1_BUF_TOO_SMALL\n#define POLARSSL_ERR_ASN1_INVALID_DATA MBEDTLS_ERR_ASN1_INVALID_DATA\n#define POLARSSL_ERR_ASN1_INVALID_LENGTH MBEDTLS_ERR_ASN1_INVALID_LENGTH\n#define POLARSSL_ERR_ASN1_LENGTH_MISMATCH MBEDTLS_ERR_ASN1_LENGTH_MISMATCH\n#define POLARSSL_ERR_ASN1_MALLOC_FAILED MBEDTLS_ERR_ASN1_ALLOC_FAILED\n#define POLARSSL_ERR_ASN1_OUT_OF_DATA MBEDTLS_ERR_ASN1_OUT_OF_DATA\n#define POLARSSL_ERR_ASN1_UNEXPECTED_TAG MBEDTLS_ERR_ASN1_UNEXPECTED_TAG\n#define POLARSSL_ERR_BASE64_BUFFER_TOO_SMALL MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL\n#define POLARSSL_ERR_BASE64_INVALID_CHARACTER MBEDTLS_ERR_BASE64_INVALID_CHARACTER\n#define POLARSSL_ERR_BLOWFISH_INVALID_INPUT_LENGTH MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH\n#define POLARSSL_ERR_BLOWFISH_INVALID_KEY_LENGTH MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH\n#define POLARSSL_ERR_CAMELLIA_INVALID_INPUT_LENGTH MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH\n#define POLARSSL_ERR_CAMELLIA_INVALID_KEY_LENGTH MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH\n#define POLARSSL_ERR_CCM_AUTH_FAILED MBEDTLS_ERR_CCM_AUTH_FAILED\n#define POLARSSL_ERR_CCM_BAD_INPUT MBEDTLS_ERR_CCM_BAD_INPUT\n#define POLARSSL_ERR_CIPHER_ALLOC_FAILED MBEDTLS_ERR_CIPHER_ALLOC_FAILED\n#define POLARSSL_ERR_CIPHER_AUTH_FAILED MBEDTLS_ERR_CIPHER_AUTH_FAILED\n#define POLARSSL_ERR_CIPHER_BAD_INPUT_DATA MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA\n#define POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE\n#define POLARSSL_ERR_CIPHER_FULL_BLOCK_EXPECTED MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED\n#define POLARSSL_ERR_CIPHER_INVALID_PADDING MBEDTLS_ERR_CIPHER_INVALID_PADDING\n#define POLARSSL_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED\n#define POLARSSL_ERR_CTR_DRBG_FILE_IO_ERROR MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR\n#define POLARSSL_ERR_CTR_DRBG_INPUT_TOO_BIG MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG\n#define POLARSSL_ERR_CTR_DRBG_REQUEST_TOO_BIG MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG\n#define POLARSSL_ERR_DES_INVALID_INPUT_LENGTH MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH\n#define POLARSSL_ERR_DHM_BAD_INPUT_DATA MBEDTLS_ERR_DHM_BAD_INPUT_DATA\n#define POLARSSL_ERR_DHM_CALC_SECRET_FAILED MBEDTLS_ERR_DHM_CALC_SECRET_FAILED\n#define POLARSSL_ERR_DHM_FILE_IO_ERROR MBEDTLS_ERR_DHM_FILE_IO_ERROR\n#define POLARSSL_ERR_DHM_INVALID_FORMAT MBEDTLS_ERR_DHM_INVALID_FORMAT\n#define POLARSSL_ERR_DHM_MAKE_PARAMS_FAILED MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED\n#define POLARSSL_ERR_DHM_MAKE_PUBLIC_FAILED MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED\n#define POLARSSL_ERR_DHM_MALLOC_FAILED MBEDTLS_ERR_DHM_ALLOC_FAILED\n#define POLARSSL_ERR_DHM_READ_PARAMS_FAILED MBEDTLS_ERR_DHM_READ_PARAMS_FAILED\n#define POLARSSL_ERR_DHM_READ_PUBLIC_FAILED MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED\n#define POLARSSL_ERR_ECP_BAD_INPUT_DATA MBEDTLS_ERR_ECP_BAD_INPUT_DATA\n#define POLARSSL_ERR_ECP_BUFFER_TOO_SMALL MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL\n#define POLARSSL_ERR_ECP_FEATURE_UNAVAILABLE MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE\n#define POLARSSL_ERR_ECP_INVALID_KEY MBEDTLS_ERR_ECP_INVALID_KEY\n#define POLARSSL_ERR_ECP_MALLOC_FAILED MBEDTLS_ERR_ECP_ALLOC_FAILED\n#define POLARSSL_ERR_ECP_RANDOM_FAILED MBEDTLS_ERR_ECP_RANDOM_FAILED\n#define POLARSSL_ERR_ECP_SIG_LEN_MISMATCH MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH\n#define POLARSSL_ERR_ECP_VERIFY_FAILED MBEDTLS_ERR_ECP_VERIFY_FAILED\n#define POLARSSL_ERR_ENTROPY_FILE_IO_ERROR MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR\n#define POLARSSL_ERR_ENTROPY_MAX_SOURCES MBEDTLS_ERR_ENTROPY_MAX_SOURCES\n#define POLARSSL_ERR_ENTROPY_NO_SOURCES_DEFINED MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED\n#define POLARSSL_ERR_ENTROPY_SOURCE_FAILED MBEDTLS_ERR_ENTROPY_SOURCE_FAILED\n#define POLARSSL_ERR_GCM_AUTH_FAILED MBEDTLS_ERR_GCM_AUTH_FAILED\n#define POLARSSL_ERR_GCM_BAD_INPUT MBEDTLS_ERR_GCM_BAD_INPUT\n#define POLARSSL_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED\n#define POLARSSL_ERR_HMAC_DRBG_FILE_IO_ERROR MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR\n#define POLARSSL_ERR_HMAC_DRBG_INPUT_TOO_BIG MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG\n#define POLARSSL_ERR_HMAC_DRBG_REQUEST_TOO_BIG MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG\n#define POLARSSL_ERR_MD_ALLOC_FAILED MBEDTLS_ERR_MD_ALLOC_FAILED\n#define POLARSSL_ERR_MD_BAD_INPUT_DATA MBEDTLS_ERR_MD_BAD_INPUT_DATA\n#define POLARSSL_ERR_MD_FEATURE_UNAVAILABLE MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE\n#define POLARSSL_ERR_MD_FILE_IO_ERROR MBEDTLS_ERR_MD_FILE_IO_ERROR\n#define POLARSSL_ERR_MPI_BAD_INPUT_DATA MBEDTLS_ERR_MPI_BAD_INPUT_DATA\n#define POLARSSL_ERR_MPI_BUFFER_TOO_SMALL MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL\n#define POLARSSL_ERR_MPI_DIVISION_BY_ZERO MBEDTLS_ERR_MPI_DIVISION_BY_ZERO\n#define POLARSSL_ERR_MPI_FILE_IO_ERROR MBEDTLS_ERR_MPI_FILE_IO_ERROR\n#define POLARSSL_ERR_MPI_INVALID_CHARACTER MBEDTLS_ERR_MPI_INVALID_CHARACTER\n#define POLARSSL_ERR_MPI_MALLOC_FAILED MBEDTLS_ERR_MPI_ALLOC_FAILED\n#define POLARSSL_ERR_MPI_NEGATIVE_VALUE MBEDTLS_ERR_MPI_NEGATIVE_VALUE\n#define POLARSSL_ERR_MPI_NOT_ACCEPTABLE MBEDTLS_ERR_MPI_NOT_ACCEPTABLE\n#define POLARSSL_ERR_NET_ACCEPT_FAILED MBEDTLS_ERR_NET_ACCEPT_FAILED\n#define POLARSSL_ERR_NET_BIND_FAILED MBEDTLS_ERR_NET_BIND_FAILED\n#define POLARSSL_ERR_NET_CONNECT_FAILED MBEDTLS_ERR_NET_CONNECT_FAILED\n#define POLARSSL_ERR_NET_CONN_RESET MBEDTLS_ERR_NET_CONN_RESET\n#define POLARSSL_ERR_NET_LISTEN_FAILED MBEDTLS_ERR_NET_LISTEN_FAILED\n#define POLARSSL_ERR_NET_RECV_FAILED MBEDTLS_ERR_NET_RECV_FAILED\n#define POLARSSL_ERR_NET_SEND_FAILED MBEDTLS_ERR_NET_SEND_FAILED\n#define POLARSSL_ERR_NET_SOCKET_FAILED MBEDTLS_ERR_NET_SOCKET_FAILED\n#define POLARSSL_ERR_NET_TIMEOUT MBEDTLS_ERR_SSL_TIMEOUT\n#define POLARSSL_ERR_NET_UNKNOWN_HOST MBEDTLS_ERR_NET_UNKNOWN_HOST\n#define POLARSSL_ERR_NET_WANT_READ MBEDTLS_ERR_SSL_WANT_READ\n#define POLARSSL_ERR_NET_WANT_WRITE MBEDTLS_ERR_SSL_WANT_WRITE\n#define POLARSSL_ERR_OID_BUF_TOO_SMALL MBEDTLS_ERR_OID_BUF_TOO_SMALL\n#define POLARSSL_ERR_OID_NOT_FOUND MBEDTLS_ERR_OID_NOT_FOUND\n#define POLARSSL_ERR_PADLOCK_DATA_MISALIGNED MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED\n#define POLARSSL_ERR_PEM_BAD_INPUT_DATA MBEDTLS_ERR_PEM_BAD_INPUT_DATA\n#define POLARSSL_ERR_PEM_FEATURE_UNAVAILABLE MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE\n#define POLARSSL_ERR_PEM_INVALID_DATA MBEDTLS_ERR_PEM_INVALID_DATA\n#define POLARSSL_ERR_PEM_INVALID_ENC_IV MBEDTLS_ERR_PEM_INVALID_ENC_IV\n#define POLARSSL_ERR_PEM_MALLOC_FAILED MBEDTLS_ERR_PEM_ALLOC_FAILED\n#define POLARSSL_ERR_PEM_NO_HEADER_FOOTER_PRESENT MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT\n#define POLARSSL_ERR_PEM_PASSWORD_MISMATCH MBEDTLS_ERR_PEM_PASSWORD_MISMATCH\n#define POLARSSL_ERR_PEM_PASSWORD_REQUIRED MBEDTLS_ERR_PEM_PASSWORD_REQUIRED\n#define POLARSSL_ERR_PEM_UNKNOWN_ENC_ALG MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG\n#define POLARSSL_ERR_PKCS12_BAD_INPUT_DATA MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA\n#define POLARSSL_ERR_PKCS12_FEATURE_UNAVAILABLE MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE\n#define POLARSSL_ERR_PKCS12_PASSWORD_MISMATCH MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH\n#define POLARSSL_ERR_PKCS12_PBE_INVALID_FORMAT MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT\n#define POLARSSL_ERR_PKCS5_BAD_INPUT_DATA MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA\n#define POLARSSL_ERR_PKCS5_FEATURE_UNAVAILABLE MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE\n#define POLARSSL_ERR_PKCS5_INVALID_FORMAT MBEDTLS_ERR_PKCS5_INVALID_FORMAT\n#define POLARSSL_ERR_PKCS5_PASSWORD_MISMATCH MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH\n#define POLARSSL_ERR_PK_BAD_INPUT_DATA MBEDTLS_ERR_PK_BAD_INPUT_DATA\n#define POLARSSL_ERR_PK_FEATURE_UNAVAILABLE MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE\n#define POLARSSL_ERR_PK_FILE_IO_ERROR MBEDTLS_ERR_PK_FILE_IO_ERROR\n#define POLARSSL_ERR_PK_INVALID_ALG MBEDTLS_ERR_PK_INVALID_ALG\n#define POLARSSL_ERR_PK_INVALID_PUBKEY MBEDTLS_ERR_PK_INVALID_PUBKEY\n#define POLARSSL_ERR_PK_KEY_INVALID_FORMAT MBEDTLS_ERR_PK_KEY_INVALID_FORMAT\n#define POLARSSL_ERR_PK_KEY_INVALID_VERSION MBEDTLS_ERR_PK_KEY_INVALID_VERSION\n#define POLARSSL_ERR_PK_MALLOC_FAILED MBEDTLS_ERR_PK_ALLOC_FAILED\n#define POLARSSL_ERR_PK_PASSWORD_MISMATCH MBEDTLS_ERR_PK_PASSWORD_MISMATCH\n#define POLARSSL_ERR_PK_PASSWORD_REQUIRED MBEDTLS_ERR_PK_PASSWORD_REQUIRED\n#define POLARSSL_ERR_PK_SIG_LEN_MISMATCH MBEDTLS_ERR_PK_SIG_LEN_MISMATCH\n#define POLARSSL_ERR_PK_TYPE_MISMATCH MBEDTLS_ERR_PK_TYPE_MISMATCH\n#define POLARSSL_ERR_PK_UNKNOWN_NAMED_CURVE MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE\n#define POLARSSL_ERR_PK_UNKNOWN_PK_ALG MBEDTLS_ERR_PK_UNKNOWN_PK_ALG\n#define POLARSSL_ERR_RSA_BAD_INPUT_DATA MBEDTLS_ERR_RSA_BAD_INPUT_DATA\n#define POLARSSL_ERR_RSA_INVALID_PADDING MBEDTLS_ERR_RSA_INVALID_PADDING\n#define POLARSSL_ERR_RSA_KEY_CHECK_FAILED MBEDTLS_ERR_RSA_KEY_CHECK_FAILED\n#define POLARSSL_ERR_RSA_KEY_GEN_FAILED MBEDTLS_ERR_RSA_KEY_GEN_FAILED\n#define POLARSSL_ERR_RSA_OUTPUT_TOO_LARGE MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE\n#define POLARSSL_ERR_RSA_PRIVATE_FAILED MBEDTLS_ERR_RSA_PRIVATE_FAILED\n#define POLARSSL_ERR_RSA_PUBLIC_FAILED MBEDTLS_ERR_RSA_PUBLIC_FAILED\n#define POLARSSL_ERR_RSA_RNG_FAILED MBEDTLS_ERR_RSA_RNG_FAILED\n#define POLARSSL_ERR_RSA_VERIFY_FAILED MBEDTLS_ERR_RSA_VERIFY_FAILED\n#define POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE\n#define POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST\n#define POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY\n#define POLARSSL_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC\n#define POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO\n#define POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE\n#define POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS\n#define POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP\n#define POLARSSL_ERR_SSL_BAD_HS_FINISHED MBEDTLS_ERR_SSL_BAD_HS_FINISHED\n#define POLARSSL_ERR_SSL_BAD_HS_NEW_SESSION_TICKET MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET\n#define POLARSSL_ERR_SSL_BAD_HS_PROTOCOL_VERSION MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION\n#define POLARSSL_ERR_SSL_BAD_HS_SERVER_HELLO MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO\n#define POLARSSL_ERR_SSL_BAD_HS_SERVER_HELLO_DONE MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE\n#define POLARSSL_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE\n#define POLARSSL_ERR_SSL_BAD_INPUT_DATA MBEDTLS_ERR_SSL_BAD_INPUT_DATA\n#define POLARSSL_ERR_SSL_BUFFER_TOO_SMALL MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL\n#define POLARSSL_ERR_SSL_CA_CHAIN_REQUIRED MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED\n#define POLARSSL_ERR_SSL_CERTIFICATE_REQUIRED MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED\n#define POLARSSL_ERR_SSL_CERTIFICATE_TOO_LARGE MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE\n#define POLARSSL_ERR_SSL_COMPRESSION_FAILED MBEDTLS_ERR_SSL_COMPRESSION_FAILED\n#define POLARSSL_ERR_SSL_CONN_EOF MBEDTLS_ERR_SSL_CONN_EOF\n#define POLARSSL_ERR_SSL_COUNTER_WRAPPING MBEDTLS_ERR_SSL_COUNTER_WRAPPING\n#define POLARSSL_ERR_SSL_FATAL_ALERT_MESSAGE MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE\n#define POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE\n#define POLARSSL_ERR_SSL_HELLO_VERIFY_REQUIRED MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED\n#define POLARSSL_ERR_SSL_HW_ACCEL_FAILED MBEDTLS_ERR_SSL_HW_ACCEL_FAILED\n#define POLARSSL_ERR_SSL_HW_ACCEL_FALLTHROUGH MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH\n#define POLARSSL_ERR_SSL_INTERNAL_ERROR MBEDTLS_ERR_SSL_INTERNAL_ERROR\n#define POLARSSL_ERR_SSL_INVALID_MAC MBEDTLS_ERR_SSL_INVALID_MAC\n#define POLARSSL_ERR_SSL_INVALID_RECORD MBEDTLS_ERR_SSL_INVALID_RECORD\n#define POLARSSL_ERR_SSL_MALLOC_FAILED MBEDTLS_ERR_SSL_ALLOC_FAILED\n#define POLARSSL_ERR_SSL_NO_CIPHER_CHOSEN MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN\n#define POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE\n#define POLARSSL_ERR_SSL_NO_RNG MBEDTLS_ERR_SSL_NO_RNG\n#define POLARSSL_ERR_SSL_NO_USABLE_CIPHERSUITE MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE\n#define POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY\n#define POLARSSL_ERR_SSL_PEER_VERIFY_FAILED MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED\n#define POLARSSL_ERR_SSL_PK_TYPE_MISMATCH MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH\n#define POLARSSL_ERR_SSL_PRIVATE_KEY_REQUIRED MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED\n#define POLARSSL_ERR_SSL_SESSION_TICKET_EXPIRED MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED\n#define POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE\n#define POLARSSL_ERR_SSL_UNKNOWN_CIPHER MBEDTLS_ERR_SSL_UNKNOWN_CIPHER\n#define POLARSSL_ERR_SSL_UNKNOWN_IDENTITY MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY\n#define POLARSSL_ERR_SSL_WAITING_SERVER_HELLO_RENEGO MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO\n#define POLARSSL_ERR_THREADING_BAD_INPUT_DATA MBEDTLS_ERR_THREADING_BAD_INPUT_DATA\n#define POLARSSL_ERR_THREADING_FEATURE_UNAVAILABLE MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE\n#define POLARSSL_ERR_THREADING_MUTEX_ERROR MBEDTLS_ERR_THREADING_MUTEX_ERROR\n#define POLARSSL_ERR_X509_BAD_INPUT_DATA MBEDTLS_ERR_X509_BAD_INPUT_DATA\n#define POLARSSL_ERR_X509_CERT_UNKNOWN_FORMAT MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT\n#define POLARSSL_ERR_X509_CERT_VERIFY_FAILED MBEDTLS_ERR_X509_CERT_VERIFY_FAILED\n#define POLARSSL_ERR_X509_FEATURE_UNAVAILABLE MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE\n#define POLARSSL_ERR_X509_FILE_IO_ERROR MBEDTLS_ERR_X509_FILE_IO_ERROR\n#define POLARSSL_ERR_X509_INVALID_ALG MBEDTLS_ERR_X509_INVALID_ALG\n#define POLARSSL_ERR_X509_INVALID_DATE MBEDTLS_ERR_X509_INVALID_DATE\n#define POLARSSL_ERR_X509_INVALID_EXTENSIONS MBEDTLS_ERR_X509_INVALID_EXTENSIONS\n#define POLARSSL_ERR_X509_INVALID_FORMAT MBEDTLS_ERR_X509_INVALID_FORMAT\n#define POLARSSL_ERR_X509_INVALID_NAME MBEDTLS_ERR_X509_INVALID_NAME\n#define POLARSSL_ERR_X509_INVALID_SERIAL MBEDTLS_ERR_X509_INVALID_SERIAL\n#define POLARSSL_ERR_X509_INVALID_SIGNATURE MBEDTLS_ERR_X509_INVALID_SIGNATURE\n#define POLARSSL_ERR_X509_INVALID_VERSION MBEDTLS_ERR_X509_INVALID_VERSION\n#define POLARSSL_ERR_X509_MALLOC_FAILED MBEDTLS_ERR_X509_ALLOC_FAILED\n#define POLARSSL_ERR_X509_SIG_MISMATCH MBEDTLS_ERR_X509_SIG_MISMATCH\n#define POLARSSL_ERR_X509_UNKNOWN_OID MBEDTLS_ERR_X509_UNKNOWN_OID\n#define POLARSSL_ERR_X509_UNKNOWN_SIG_ALG MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG\n#define POLARSSL_ERR_X509_UNKNOWN_VERSION MBEDTLS_ERR_X509_UNKNOWN_VERSION\n#define POLARSSL_ERR_XTEA_INVALID_INPUT_LENGTH MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH\n#define POLARSSL_GCM_H MBEDTLS_GCM_H\n#define POLARSSL_HAVEGE_H MBEDTLS_HAVEGE_H\n#define POLARSSL_HAVE_INT32 MBEDTLS_HAVE_INT32\n#define POLARSSL_HAVE_INT64 MBEDTLS_HAVE_INT64\n#define POLARSSL_HAVE_UDBL MBEDTLS_HAVE_UDBL\n#define POLARSSL_HAVE_X86 MBEDTLS_HAVE_X86\n#define POLARSSL_HAVE_X86_64 MBEDTLS_HAVE_X86_64\n#define POLARSSL_HMAC_DRBG_H MBEDTLS_HMAC_DRBG_H\n#define POLARSSL_HMAC_DRBG_PR_OFF MBEDTLS_HMAC_DRBG_PR_OFF\n#define POLARSSL_HMAC_DRBG_PR_ON MBEDTLS_HMAC_DRBG_PR_ON\n#define POLARSSL_KEY_EXCHANGE_DHE_PSK MBEDTLS_KEY_EXCHANGE_DHE_PSK\n#define POLARSSL_KEY_EXCHANGE_DHE_RSA MBEDTLS_KEY_EXCHANGE_DHE_RSA\n#define POLARSSL_KEY_EXCHANGE_ECDHE_ECDSA MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA\n#define POLARSSL_KEY_EXCHANGE_ECDHE_PSK MBEDTLS_KEY_EXCHANGE_ECDHE_PSK\n#define POLARSSL_KEY_EXCHANGE_ECDHE_RSA MBEDTLS_KEY_EXCHANGE_ECDHE_RSA\n#define POLARSSL_KEY_EXCHANGE_ECDH_ECDSA MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA\n#define POLARSSL_KEY_EXCHANGE_ECDH_RSA MBEDTLS_KEY_EXCHANGE_ECDH_RSA\n#define POLARSSL_KEY_EXCHANGE_NONE MBEDTLS_KEY_EXCHANGE_NONE\n#define POLARSSL_KEY_EXCHANGE_PSK MBEDTLS_KEY_EXCHANGE_PSK\n#define POLARSSL_KEY_EXCHANGE_RSA MBEDTLS_KEY_EXCHANGE_RSA\n#define POLARSSL_KEY_EXCHANGE_RSA_PSK MBEDTLS_KEY_EXCHANGE_RSA_PSK\n#define POLARSSL_KEY_EXCHANGE__SOME__ECDHE_ENABLED MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED\n#define POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED\n#define POLARSSL_KEY_EXCHANGE__WITH_CERT__ENABLED MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED\n#define POLARSSL_KEY_LENGTH_DES MBEDTLS_KEY_LENGTH_DES\n#define POLARSSL_KEY_LENGTH_DES_EDE MBEDTLS_KEY_LENGTH_DES_EDE\n#define POLARSSL_KEY_LENGTH_DES_EDE3 MBEDTLS_KEY_LENGTH_DES_EDE3\n#define POLARSSL_KEY_LENGTH_NONE MBEDTLS_KEY_LENGTH_NONE\n#define POLARSSL_MAX_BLOCK_LENGTH MBEDTLS_MAX_BLOCK_LENGTH\n#define POLARSSL_MAX_IV_LENGTH MBEDTLS_MAX_IV_LENGTH\n#define POLARSSL_MD2_H MBEDTLS_MD2_H\n#define POLARSSL_MD4_H MBEDTLS_MD4_H\n#define POLARSSL_MD5_H MBEDTLS_MD5_H\n#define POLARSSL_MD_H MBEDTLS_MD_H\n#define POLARSSL_MD_MAX_SIZE MBEDTLS_MD_MAX_SIZE\n#define POLARSSL_MD_MD2 MBEDTLS_MD_MD2\n#define POLARSSL_MD_MD4 MBEDTLS_MD_MD4\n#define POLARSSL_MD_MD5 MBEDTLS_MD_MD5\n#define POLARSSL_MD_NONE MBEDTLS_MD_NONE\n#define POLARSSL_MD_RIPEMD160 MBEDTLS_MD_RIPEMD160\n#define POLARSSL_MD_SHA1 MBEDTLS_MD_SHA1\n#define POLARSSL_MD_SHA224 MBEDTLS_MD_SHA224\n#define POLARSSL_MD_SHA256 MBEDTLS_MD_SHA256\n#define POLARSSL_MD_SHA384 MBEDTLS_MD_SHA384\n#define POLARSSL_MD_SHA512 MBEDTLS_MD_SHA512\n#define POLARSSL_MD_WRAP_H MBEDTLS_MD_WRAP_H\n#define POLARSSL_MEMORY_BUFFER_ALLOC_H MBEDTLS_MEMORY_BUFFER_ALLOC_H\n#define POLARSSL_MODE_CBC MBEDTLS_MODE_CBC\n#define POLARSSL_MODE_CCM MBEDTLS_MODE_CCM\n#define POLARSSL_MODE_CFB MBEDTLS_MODE_CFB\n#define POLARSSL_MODE_CTR MBEDTLS_MODE_CTR\n#define POLARSSL_MODE_ECB MBEDTLS_MODE_ECB\n#define POLARSSL_MODE_GCM MBEDTLS_MODE_GCM\n#define POLARSSL_MODE_NONE MBEDTLS_MODE_NONE\n#define POLARSSL_MODE_OFB MBEDTLS_MODE_OFB\n#define POLARSSL_MODE_STREAM MBEDTLS_MODE_STREAM\n#define POLARSSL_MPI_MAX_BITS MBEDTLS_MPI_MAX_BITS\n#define POLARSSL_MPI_MAX_BITS_SCALE100 MBEDTLS_MPI_MAX_BITS_SCALE100\n#define POLARSSL_MPI_MAX_LIMBS MBEDTLS_MPI_MAX_LIMBS\n#define POLARSSL_MPI_RW_BUFFER_SIZE MBEDTLS_MPI_RW_BUFFER_SIZE\n#define POLARSSL_NET_H MBEDTLS_NET_SOCKETS_H\n#define POLARSSL_NET_LISTEN_BACKLOG MBEDTLS_NET_LISTEN_BACKLOG\n#define POLARSSL_OID_H MBEDTLS_OID_H\n#define POLARSSL_OPERATION_NONE MBEDTLS_OPERATION_NONE\n#define POLARSSL_PADDING_NONE MBEDTLS_PADDING_NONE\n#define POLARSSL_PADDING_ONE_AND_ZEROS MBEDTLS_PADDING_ONE_AND_ZEROS\n#define POLARSSL_PADDING_PKCS7 MBEDTLS_PADDING_PKCS7\n#define POLARSSL_PADDING_ZEROS MBEDTLS_PADDING_ZEROS\n#define POLARSSL_PADDING_ZEROS_AND_LEN MBEDTLS_PADDING_ZEROS_AND_LEN\n#define POLARSSL_PADLOCK_H MBEDTLS_PADLOCK_H\n#define POLARSSL_PEM_H MBEDTLS_PEM_H\n#define POLARSSL_PKCS11_H MBEDTLS_PKCS11_H\n#define POLARSSL_PKCS12_H MBEDTLS_PKCS12_H\n#define POLARSSL_PKCS5_H MBEDTLS_PKCS5_H\n#define POLARSSL_PK_DEBUG_ECP MBEDTLS_PK_DEBUG_ECP\n#define POLARSSL_PK_DEBUG_MAX_ITEMS MBEDTLS_PK_DEBUG_MAX_ITEMS\n#define POLARSSL_PK_DEBUG_MPI MBEDTLS_PK_DEBUG_MPI\n#define POLARSSL_PK_DEBUG_NONE MBEDTLS_PK_DEBUG_NONE\n#define POLARSSL_PK_ECDSA MBEDTLS_PK_ECDSA\n#define POLARSSL_PK_ECKEY MBEDTLS_PK_ECKEY\n#define POLARSSL_PK_ECKEY_DH MBEDTLS_PK_ECKEY_DH\n#define POLARSSL_PK_H MBEDTLS_PK_H\n#define POLARSSL_PK_NONE MBEDTLS_PK_NONE\n#define POLARSSL_PK_RSA MBEDTLS_PK_RSA\n#define POLARSSL_PK_RSASSA_PSS MBEDTLS_PK_RSASSA_PSS\n#define POLARSSL_PK_RSA_ALT MBEDTLS_PK_RSA_ALT\n#define POLARSSL_PK_WRAP_H MBEDTLS_PK_WRAP_H\n#define POLARSSL_PLATFORM_H MBEDTLS_PLATFORM_H\n#define POLARSSL_PREMASTER_SIZE MBEDTLS_PREMASTER_SIZE\n#define POLARSSL_RIPEMD160_H MBEDTLS_RIPEMD160_H\n#define POLARSSL_RSA_H MBEDTLS_RSA_H\n#define POLARSSL_SHA1_H MBEDTLS_SHA1_H\n#define POLARSSL_SHA256_H MBEDTLS_SHA256_H\n#define POLARSSL_SHA512_H MBEDTLS_SHA512_H\n#define POLARSSL_SSL_CACHE_H MBEDTLS_SSL_CACHE_H\n#define POLARSSL_SSL_CIPHERSUITES_H MBEDTLS_SSL_CIPHERSUITES_H\n#define POLARSSL_SSL_COOKIE_H MBEDTLS_SSL_COOKIE_H\n#define POLARSSL_SSL_H MBEDTLS_SSL_H\n#define POLARSSL_THREADING_H MBEDTLS_THREADING_H\n#define POLARSSL_THREADING_IMPL MBEDTLS_THREADING_IMPL\n#define POLARSSL_TIMING_H MBEDTLS_TIMING_H\n#define POLARSSL_VERSION_H MBEDTLS_VERSION_H\n#define POLARSSL_VERSION_MAJOR MBEDTLS_VERSION_MAJOR\n#define POLARSSL_VERSION_MINOR MBEDTLS_VERSION_MINOR\n#define POLARSSL_VERSION_NUMBER MBEDTLS_VERSION_NUMBER\n#define POLARSSL_VERSION_PATCH MBEDTLS_VERSION_PATCH\n#define POLARSSL_VERSION_STRING MBEDTLS_VERSION_STRING\n#define POLARSSL_VERSION_STRING_FULL MBEDTLS_VERSION_STRING_FULL\n#define POLARSSL_X509_CRL_H MBEDTLS_X509_CRL_H\n#define POLARSSL_X509_CRT_H MBEDTLS_X509_CRT_H\n#define POLARSSL_X509_CSR_H MBEDTLS_X509_CSR_H\n#define POLARSSL_X509_H MBEDTLS_X509_H\n#define POLARSSL_XTEA_H MBEDTLS_XTEA_H\n#define RSA_CRYPT MBEDTLS_RSA_CRYPT\n#define RSA_PKCS_V15 MBEDTLS_RSA_PKCS_V15\n#define RSA_PKCS_V21 MBEDTLS_RSA_PKCS_V21\n#define RSA_PRIVATE MBEDTLS_RSA_PRIVATE\n#define RSA_PUBLIC MBEDTLS_RSA_PUBLIC\n#define RSA_SALT_LEN_ANY MBEDTLS_RSA_SALT_LEN_ANY\n#define RSA_SIGN MBEDTLS_RSA_SIGN\n#define SSL_ALERT_LEVEL_FATAL MBEDTLS_SSL_ALERT_LEVEL_FATAL\n#define SSL_ALERT_LEVEL_WARNING MBEDTLS_SSL_ALERT_LEVEL_WARNING\n#define SSL_ALERT_MSG_ACCESS_DENIED MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED\n#define SSL_ALERT_MSG_BAD_CERT MBEDTLS_SSL_ALERT_MSG_BAD_CERT\n#define SSL_ALERT_MSG_BAD_RECORD_MAC MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC\n#define SSL_ALERT_MSG_CERT_EXPIRED MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED\n#define SSL_ALERT_MSG_CERT_REVOKED MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED\n#define SSL_ALERT_MSG_CERT_UNKNOWN MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN\n#define SSL_ALERT_MSG_CLOSE_NOTIFY MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY\n#define SSL_ALERT_MSG_DECODE_ERROR MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR\n#define SSL_ALERT_MSG_DECOMPRESSION_FAILURE MBEDTLS_SSL_ALERT_MSG_DECOMPRESSION_FAILURE\n#define SSL_ALERT_MSG_DECRYPTION_FAILED MBEDTLS_SSL_ALERT_MSG_DECRYPTION_FAILED\n#define SSL_ALERT_MSG_DECRYPT_ERROR MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR\n#define SSL_ALERT_MSG_EXPORT_RESTRICTION MBEDTLS_SSL_ALERT_MSG_EXPORT_RESTRICTION\n#define SSL_ALERT_MSG_HANDSHAKE_FAILURE MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE\n#define SSL_ALERT_MSG_ILLEGAL_PARAMETER MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER\n#define SSL_ALERT_MSG_INAPROPRIATE_FALLBACK MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK\n#define SSL_ALERT_MSG_INSUFFICIENT_SECURITY MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY\n#define SSL_ALERT_MSG_INTERNAL_ERROR MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR\n#define SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL\n#define SSL_ALERT_MSG_NO_CERT MBEDTLS_SSL_ALERT_MSG_NO_CERT\n#define SSL_ALERT_MSG_NO_RENEGOTIATION MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION\n#define SSL_ALERT_MSG_PROTOCOL_VERSION MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION\n#define SSL_ALERT_MSG_RECORD_OVERFLOW MBEDTLS_SSL_ALERT_MSG_RECORD_OVERFLOW\n#define SSL_ALERT_MSG_UNEXPECTED_MESSAGE MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE\n#define SSL_ALERT_MSG_UNKNOWN_CA MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA\n#define SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY\n#define SSL_ALERT_MSG_UNRECOGNIZED_NAME MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME\n#define SSL_ALERT_MSG_UNSUPPORTED_CERT MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT\n#define SSL_ALERT_MSG_UNSUPPORTED_EXT MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT\n#define SSL_ALERT_MSG_USER_CANCELED MBEDTLS_SSL_ALERT_MSG_USER_CANCELED\n#define SSL_ANTI_REPLAY_DISABLED MBEDTLS_SSL_ANTI_REPLAY_DISABLED\n#define SSL_ANTI_REPLAY_ENABLED MBEDTLS_SSL_ANTI_REPLAY_ENABLED\n#define SSL_ARC4_DISABLED MBEDTLS_SSL_ARC4_DISABLED\n#define SSL_ARC4_ENABLED MBEDTLS_SSL_ARC4_ENABLED\n#define SSL_BUFFER_LEN ( ( ( MBEDTLS_SSL_IN_BUFFER_LEN ) < ( MBEDTLS_SSL_OUT_BUFFER_LEN ) ) \\\n                         ? ( MBEDTLS_SSL_IN_BUFFER_LEN ) : ( MBEDTLS_SSL_OUT_BUFFER_LEN ) )\n#define SSL_CACHE_DEFAULT_MAX_ENTRIES MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES\n#define SSL_CACHE_DEFAULT_TIMEOUT MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT\n#define SSL_CBC_RECORD_SPLITTING_DISABLED MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED\n#define SSL_CBC_RECORD_SPLITTING_ENABLED MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED\n#define SSL_CERTIFICATE_REQUEST MBEDTLS_SSL_CERTIFICATE_REQUEST\n#define SSL_CERTIFICATE_VERIFY MBEDTLS_SSL_CERTIFICATE_VERIFY\n#define SSL_CERT_TYPE_ECDSA_SIGN MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN\n#define SSL_CERT_TYPE_RSA_SIGN MBEDTLS_SSL_CERT_TYPE_RSA_SIGN\n#define SSL_CHANNEL_INBOUND MBEDTLS_SSL_CHANNEL_INBOUND\n#define SSL_CHANNEL_OUTBOUND MBEDTLS_SSL_CHANNEL_OUTBOUND\n#define SSL_CIPHERSUITES MBEDTLS_SSL_CIPHERSUITES\n#define SSL_CLIENT_CERTIFICATE MBEDTLS_SSL_CLIENT_CERTIFICATE\n#define SSL_CLIENT_CHANGE_CIPHER_SPEC MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC\n#define SSL_CLIENT_FINISHED MBEDTLS_SSL_CLIENT_FINISHED\n#define SSL_CLIENT_HELLO MBEDTLS_SSL_CLIENT_HELLO\n#define SSL_CLIENT_KEY_EXCHANGE MBEDTLS_SSL_CLIENT_KEY_EXCHANGE\n#define SSL_COMPRESSION_ADD MBEDTLS_SSL_COMPRESSION_ADD\n#define SSL_COMPRESS_DEFLATE MBEDTLS_SSL_COMPRESS_DEFLATE\n#define SSL_COMPRESS_NULL MBEDTLS_SSL_COMPRESS_NULL\n#define SSL_DEBUG_BUF MBEDTLS_SSL_DEBUG_BUF\n#define SSL_DEBUG_CRT MBEDTLS_SSL_DEBUG_CRT\n#define SSL_DEBUG_ECP MBEDTLS_SSL_DEBUG_ECP\n#define SSL_DEBUG_MPI MBEDTLS_SSL_DEBUG_MPI\n#define SSL_DEBUG_MSG MBEDTLS_SSL_DEBUG_MSG\n#define SSL_DEBUG_RET MBEDTLS_SSL_DEBUG_RET\n#define SSL_DEFAULT_TICKET_LIFETIME MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME\n#define SSL_DTLS_TIMEOUT_DFL_MAX MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX\n#define SSL_DTLS_TIMEOUT_DFL_MIN MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN\n#define SSL_EMPTY_RENEGOTIATION_INFO MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO\n#define SSL_ETM_DISABLED MBEDTLS_SSL_ETM_DISABLED\n#define SSL_ETM_ENABLED MBEDTLS_SSL_ETM_ENABLED\n#define SSL_EXTENDED_MS_DISABLED MBEDTLS_SSL_EXTENDED_MS_DISABLED\n#define SSL_EXTENDED_MS_ENABLED MBEDTLS_SSL_EXTENDED_MS_ENABLED\n#define SSL_FALLBACK_SCSV MBEDTLS_SSL_FALLBACK_SCSV\n#define SSL_FLUSH_BUFFERS MBEDTLS_SSL_FLUSH_BUFFERS\n#define SSL_HANDSHAKE_OVER MBEDTLS_SSL_HANDSHAKE_OVER\n#define SSL_HANDSHAKE_WRAPUP MBEDTLS_SSL_HANDSHAKE_WRAPUP\n#define SSL_HASH_MD5 MBEDTLS_SSL_HASH_MD5\n#define SSL_HASH_NONE MBEDTLS_SSL_HASH_NONE\n#define SSL_HASH_SHA1 MBEDTLS_SSL_HASH_SHA1\n#define SSL_HASH_SHA224 MBEDTLS_SSL_HASH_SHA224\n#define SSL_HASH_SHA256 MBEDTLS_SSL_HASH_SHA256\n#define SSL_HASH_SHA384 MBEDTLS_SSL_HASH_SHA384\n#define SSL_HASH_SHA512 MBEDTLS_SSL_HASH_SHA512\n#define SSL_HELLO_REQUEST MBEDTLS_SSL_HELLO_REQUEST\n#define SSL_HS_CERTIFICATE MBEDTLS_SSL_HS_CERTIFICATE\n#define SSL_HS_CERTIFICATE_REQUEST MBEDTLS_SSL_HS_CERTIFICATE_REQUEST\n#define SSL_HS_CERTIFICATE_VERIFY MBEDTLS_SSL_HS_CERTIFICATE_VERIFY\n#define SSL_HS_CLIENT_HELLO MBEDTLS_SSL_HS_CLIENT_HELLO\n#define SSL_HS_CLIENT_KEY_EXCHANGE MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE\n#define SSL_HS_FINISHED MBEDTLS_SSL_HS_FINISHED\n#define SSL_HS_HELLO_REQUEST MBEDTLS_SSL_HS_HELLO_REQUEST\n#define SSL_HS_HELLO_VERIFY_REQUEST MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST\n#define SSL_HS_NEW_SESSION_TICKET MBEDTLS_SSL_HS_NEW_SESSION_TICKET\n#define SSL_HS_SERVER_HELLO MBEDTLS_SSL_HS_SERVER_HELLO\n#define SSL_HS_SERVER_HELLO_DONE MBEDTLS_SSL_HS_SERVER_HELLO_DONE\n#define SSL_HS_SERVER_KEY_EXCHANGE MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE\n#define SSL_INITIAL_HANDSHAKE MBEDTLS_SSL_INITIAL_HANDSHAKE\n#define SSL_IS_CLIENT MBEDTLS_SSL_IS_CLIENT\n#define SSL_IS_FALLBACK MBEDTLS_SSL_IS_FALLBACK\n#define SSL_IS_NOT_FALLBACK MBEDTLS_SSL_IS_NOT_FALLBACK\n#define SSL_IS_SERVER MBEDTLS_SSL_IS_SERVER\n#define SSL_LEGACY_ALLOW_RENEGOTIATION MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION\n#define SSL_LEGACY_BREAK_HANDSHAKE MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE\n#define SSL_LEGACY_NO_RENEGOTIATION MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION\n#define SSL_LEGACY_RENEGOTIATION MBEDTLS_SSL_LEGACY_RENEGOTIATION\n#define SSL_MAC_ADD MBEDTLS_SSL_MAC_ADD\n#define SSL_MAJOR_VERSION_3 MBEDTLS_SSL_MAJOR_VERSION_3\n#define SSL_MAX_CONTENT_LEN MBEDTLS_SSL_MAX_CONTENT_LEN\n#define SSL_MAX_FRAG_LEN_1024 MBEDTLS_SSL_MAX_FRAG_LEN_1024\n#define SSL_MAX_FRAG_LEN_2048 MBEDTLS_SSL_MAX_FRAG_LEN_2048\n#define SSL_MAX_FRAG_LEN_4096 MBEDTLS_SSL_MAX_FRAG_LEN_4096\n#define SSL_MAX_FRAG_LEN_512 MBEDTLS_SSL_MAX_FRAG_LEN_512\n#define SSL_MAX_FRAG_LEN_INVALID MBEDTLS_SSL_MAX_FRAG_LEN_INVALID\n#define SSL_MAX_FRAG_LEN_NONE MBEDTLS_SSL_MAX_FRAG_LEN_NONE\n#define SSL_MAX_MAJOR_VERSION MBEDTLS_SSL_MAX_MAJOR_VERSION\n#define SSL_MAX_MINOR_VERSION MBEDTLS_SSL_MAX_MINOR_VERSION\n#define SSL_MINOR_VERSION_0 MBEDTLS_SSL_MINOR_VERSION_0\n#define SSL_MINOR_VERSION_1 MBEDTLS_SSL_MINOR_VERSION_1\n#define SSL_MINOR_VERSION_2 MBEDTLS_SSL_MINOR_VERSION_2\n#define SSL_MINOR_VERSION_3 MBEDTLS_SSL_MINOR_VERSION_3\n#define SSL_MIN_MAJOR_VERSION MBEDTLS_SSL_MIN_MAJOR_VERSION\n#define SSL_MIN_MINOR_VERSION MBEDTLS_SSL_MIN_MINOR_VERSION\n#define SSL_MSG_ALERT MBEDTLS_SSL_MSG_ALERT\n#define SSL_MSG_APPLICATION_DATA MBEDTLS_SSL_MSG_APPLICATION_DATA\n#define SSL_MSG_CHANGE_CIPHER_SPEC MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC\n#define SSL_MSG_HANDSHAKE MBEDTLS_SSL_MSG_HANDSHAKE\n#define SSL_PADDING_ADD MBEDTLS_SSL_PADDING_ADD\n#define SSL_RENEGOTIATION MBEDTLS_SSL_RENEGOTIATION\n#define SSL_RENEGOTIATION_DISABLED MBEDTLS_SSL_RENEGOTIATION_DISABLED\n#define SSL_RENEGOTIATION_DONE MBEDTLS_SSL_RENEGOTIATION_DONE\n#define SSL_RENEGOTIATION_ENABLED MBEDTLS_SSL_RENEGOTIATION_ENABLED\n#define SSL_RENEGOTIATION_NOT_ENFORCED MBEDTLS_SSL_RENEGOTIATION_NOT_ENFORCED\n#define SSL_RENEGOTIATION_PENDING MBEDTLS_SSL_RENEGOTIATION_PENDING\n#define SSL_RENEGO_MAX_RECORDS_DEFAULT MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT\n#define SSL_RETRANS_FINISHED MBEDTLS_SSL_RETRANS_FINISHED\n#define SSL_RETRANS_PREPARING MBEDTLS_SSL_RETRANS_PREPARING\n#define SSL_RETRANS_SENDING MBEDTLS_SSL_RETRANS_SENDING\n#define SSL_RETRANS_WAITING MBEDTLS_SSL_RETRANS_WAITING\n#define SSL_SECURE_RENEGOTIATION MBEDTLS_SSL_SECURE_RENEGOTIATION\n#define SSL_SERVER_CERTIFICATE MBEDTLS_SSL_SERVER_CERTIFICATE\n#define SSL_SERVER_CHANGE_CIPHER_SPEC MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC\n#define SSL_SERVER_FINISHED MBEDTLS_SSL_SERVER_FINISHED\n#define SSL_SERVER_HELLO MBEDTLS_SSL_SERVER_HELLO\n#define SSL_SERVER_HELLO_DONE MBEDTLS_SSL_SERVER_HELLO_DONE\n#define SSL_SERVER_HELLO_VERIFY_REQUEST_SENT MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT\n#define SSL_SERVER_KEY_EXCHANGE MBEDTLS_SSL_SERVER_KEY_EXCHANGE\n#define SSL_SERVER_NEW_SESSION_TICKET MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET\n#define SSL_SESSION_TICKETS_DISABLED MBEDTLS_SSL_SESSION_TICKETS_DISABLED\n#define SSL_SESSION_TICKETS_ENABLED MBEDTLS_SSL_SESSION_TICKETS_ENABLED\n#define SSL_SIG_ANON MBEDTLS_SSL_SIG_ANON\n#define SSL_SIG_ECDSA MBEDTLS_SSL_SIG_ECDSA\n#define SSL_SIG_RSA MBEDTLS_SSL_SIG_RSA\n#define SSL_TRANSPORT_DATAGRAM MBEDTLS_SSL_TRANSPORT_DATAGRAM\n#define SSL_TRANSPORT_STREAM MBEDTLS_SSL_TRANSPORT_STREAM\n#define SSL_TRUNCATED_HMAC_LEN MBEDTLS_SSL_TRUNCATED_HMAC_LEN\n#define SSL_TRUNC_HMAC_DISABLED MBEDTLS_SSL_TRUNC_HMAC_DISABLED\n#define SSL_TRUNC_HMAC_ENABLED MBEDTLS_SSL_TRUNC_HMAC_ENABLED\n#define SSL_VERIFY_DATA_MAX_LEN MBEDTLS_SSL_VERIFY_DATA_MAX_LEN\n#define SSL_VERIFY_NONE MBEDTLS_SSL_VERIFY_NONE\n#define SSL_VERIFY_OPTIONAL MBEDTLS_SSL_VERIFY_OPTIONAL\n#define SSL_VERIFY_REQUIRED MBEDTLS_SSL_VERIFY_REQUIRED\n#define TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA\n#define TLS_DHE_PSK_WITH_AES_128_CBC_SHA MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA\n#define TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256\n#define TLS_DHE_PSK_WITH_AES_128_CCM MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM\n#define TLS_DHE_PSK_WITH_AES_128_CCM_8 MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM_8\n#define TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256\n#define TLS_DHE_PSK_WITH_AES_256_CBC_SHA MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA\n#define TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384\n#define TLS_DHE_PSK_WITH_AES_256_CCM MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM\n#define TLS_DHE_PSK_WITH_AES_256_CCM_8 MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM_8\n#define TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384\n#define TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256\n#define TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256\n#define TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384\n#define TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384\n#define TLS_DHE_PSK_WITH_NULL_SHA MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA\n#define TLS_DHE_PSK_WITH_NULL_SHA256 MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA256\n#define TLS_DHE_PSK_WITH_NULL_SHA384 MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA384\n#define TLS_DHE_PSK_WITH_RC4_128_SHA MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA\n#define TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA\n#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA\n#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256\n#define TLS_DHE_RSA_WITH_AES_128_CCM MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM\n#define TLS_DHE_RSA_WITH_AES_128_CCM_8 MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM_8\n#define TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256\n#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA\n#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256\n#define TLS_DHE_RSA_WITH_AES_256_CCM MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM\n#define TLS_DHE_RSA_WITH_AES_256_CCM_8 MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM_8\n#define TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384\n#define TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA\n#define TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256\n#define TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256\n#define TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA\n#define TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256\n#define TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384\n#define TLS_DHE_RSA_WITH_DES_CBC_SHA MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA\n#define TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA\n#define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA\n#define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256\n#define TLS_ECDHE_ECDSA_WITH_AES_128_CCM MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM\n#define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8\n#define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\n#define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA\n#define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384\n#define TLS_ECDHE_ECDSA_WITH_AES_256_CCM MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM\n#define TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8\n#define TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\n#define TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256\n#define TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256\n#define TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384\n#define TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384\n#define TLS_ECDHE_ECDSA_WITH_NULL_SHA MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA\n#define TLS_ECDHE_ECDSA_WITH_RC4_128_SHA MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA\n#define TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA\n#define TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA\n#define TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256\n#define TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA\n#define TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384\n#define TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256\n#define TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384\n#define TLS_ECDHE_PSK_WITH_NULL_SHA MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA\n#define TLS_ECDHE_PSK_WITH_NULL_SHA256 MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256\n#define TLS_ECDHE_PSK_WITH_NULL_SHA384 MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384\n#define TLS_ECDHE_PSK_WITH_RC4_128_SHA MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA\n#define TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA\n#define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA\n#define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256\n#define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\n#define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA\n#define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384\n#define TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\n#define TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256\n#define TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256\n#define TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384\n#define TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384\n#define TLS_ECDHE_RSA_WITH_NULL_SHA MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA\n#define TLS_ECDHE_RSA_WITH_RC4_128_SHA MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA\n#define TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA\n#define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA\n#define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256\n#define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256\n#define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA\n#define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384\n#define TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384\n#define TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256\n#define TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256\n#define TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384\n#define TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384\n#define TLS_ECDH_ECDSA_WITH_NULL_SHA MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA\n#define TLS_ECDH_ECDSA_WITH_RC4_128_SHA MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA\n#define TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA\n#define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA\n#define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256\n#define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256\n#define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA\n#define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384\n#define TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384\n#define TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256\n#define TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256\n#define TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384\n#define TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384\n#define TLS_ECDH_RSA_WITH_NULL_SHA MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA\n#define TLS_ECDH_RSA_WITH_RC4_128_SHA MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA\n#define TLS_EXT_ALPN MBEDTLS_TLS_EXT_ALPN\n#define TLS_EXT_ENCRYPT_THEN_MAC MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC\n#define TLS_EXT_EXTENDED_MASTER_SECRET MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET\n#define TLS_EXT_MAX_FRAGMENT_LENGTH MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH\n#define TLS_EXT_RENEGOTIATION_INFO MBEDTLS_TLS_EXT_RENEGOTIATION_INFO\n#define TLS_EXT_SERVERNAME MBEDTLS_TLS_EXT_SERVERNAME\n#define TLS_EXT_SERVERNAME_HOSTNAME MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME\n#define TLS_EXT_SESSION_TICKET MBEDTLS_TLS_EXT_SESSION_TICKET\n#define TLS_EXT_SIG_ALG MBEDTLS_TLS_EXT_SIG_ALG\n#define TLS_EXT_SUPPORTED_ELLIPTIC_CURVES MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES\n#define TLS_EXT_SUPPORTED_POINT_FORMATS MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS\n#define TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT\n#define TLS_EXT_TRUNCATED_HMAC MBEDTLS_TLS_EXT_TRUNCATED_HMAC\n#define TLS_PSK_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA\n#define TLS_PSK_WITH_AES_128_CBC_SHA MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA\n#define TLS_PSK_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256\n#define TLS_PSK_WITH_AES_128_CCM MBEDTLS_TLS_PSK_WITH_AES_128_CCM\n#define TLS_PSK_WITH_AES_128_CCM_8 MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8\n#define TLS_PSK_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256\n#define TLS_PSK_WITH_AES_256_CBC_SHA MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA\n#define TLS_PSK_WITH_AES_256_CBC_SHA384 MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384\n#define TLS_PSK_WITH_AES_256_CCM MBEDTLS_TLS_PSK_WITH_AES_256_CCM\n#define TLS_PSK_WITH_AES_256_CCM_8 MBEDTLS_TLS_PSK_WITH_AES_256_CCM_8\n#define TLS_PSK_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384\n#define TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256\n#define TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256\n#define TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384\n#define TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384\n#define TLS_PSK_WITH_NULL_SHA MBEDTLS_TLS_PSK_WITH_NULL_SHA\n#define TLS_PSK_WITH_NULL_SHA256 MBEDTLS_TLS_PSK_WITH_NULL_SHA256\n#define TLS_PSK_WITH_NULL_SHA384 MBEDTLS_TLS_PSK_WITH_NULL_SHA384\n#define TLS_PSK_WITH_RC4_128_SHA MBEDTLS_TLS_PSK_WITH_RC4_128_SHA\n#define TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA\n#define TLS_RSA_PSK_WITH_AES_128_CBC_SHA MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA\n#define TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256\n#define TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256\n#define TLS_RSA_PSK_WITH_AES_256_CBC_SHA MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA\n#define TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384\n#define TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384\n#define TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256\n#define TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256\n#define TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384\n#define TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384\n#define TLS_RSA_PSK_WITH_NULL_SHA MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA\n#define TLS_RSA_PSK_WITH_NULL_SHA256 MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA256\n#define TLS_RSA_PSK_WITH_NULL_SHA384 MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA384\n#define TLS_RSA_PSK_WITH_RC4_128_SHA MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA\n#define TLS_RSA_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA\n#define TLS_RSA_WITH_AES_128_CBC_SHA MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA\n#define TLS_RSA_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256\n#define TLS_RSA_WITH_AES_128_CCM MBEDTLS_TLS_RSA_WITH_AES_128_CCM\n#define TLS_RSA_WITH_AES_128_CCM_8 MBEDTLS_TLS_RSA_WITH_AES_128_CCM_8\n#define TLS_RSA_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256\n#define TLS_RSA_WITH_AES_256_CBC_SHA MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA\n#define TLS_RSA_WITH_AES_256_CBC_SHA256 MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256\n#define TLS_RSA_WITH_AES_256_CCM MBEDTLS_TLS_RSA_WITH_AES_256_CCM\n#define TLS_RSA_WITH_AES_256_CCM_8 MBEDTLS_TLS_RSA_WITH_AES_256_CCM_8\n#define TLS_RSA_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384\n#define TLS_RSA_WITH_CAMELLIA_128_CBC_SHA MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA\n#define TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256\n#define TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256\n#define TLS_RSA_WITH_CAMELLIA_256_CBC_SHA MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA\n#define TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256\n#define TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384\n#define TLS_RSA_WITH_DES_CBC_SHA MBEDTLS_TLS_RSA_WITH_DES_CBC_SHA\n#define TLS_RSA_WITH_NULL_MD5 MBEDTLS_TLS_RSA_WITH_NULL_MD5\n#define TLS_RSA_WITH_NULL_SHA MBEDTLS_TLS_RSA_WITH_NULL_SHA\n#define TLS_RSA_WITH_NULL_SHA256 MBEDTLS_TLS_RSA_WITH_NULL_SHA256\n#define TLS_RSA_WITH_RC4_128_MD5 MBEDTLS_TLS_RSA_WITH_RC4_128_MD5\n#define TLS_RSA_WITH_RC4_128_SHA MBEDTLS_TLS_RSA_WITH_RC4_128_SHA\n#define X509_CRT_VERSION_1 MBEDTLS_X509_CRT_VERSION_1\n#define X509_CRT_VERSION_2 MBEDTLS_X509_CRT_VERSION_2\n#define X509_CRT_VERSION_3 MBEDTLS_X509_CRT_VERSION_3\n#define X509_FORMAT_DER MBEDTLS_X509_FORMAT_DER\n#define X509_FORMAT_PEM MBEDTLS_X509_FORMAT_PEM\n#define X509_MAX_DN_NAME_SIZE MBEDTLS_X509_MAX_DN_NAME_SIZE\n#define X509_RFC5280_MAX_SERIAL_LEN MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN\n#define X509_RFC5280_UTC_TIME_LEN MBEDTLS_X509_RFC5280_UTC_TIME_LEN\n#define XTEA_DECRYPT MBEDTLS_XTEA_DECRYPT\n#define XTEA_ENCRYPT MBEDTLS_XTEA_ENCRYPT\n#define _asn1_bitstring mbedtls_asn1_bitstring\n#define _asn1_buf mbedtls_asn1_buf\n#define _asn1_named_data mbedtls_asn1_named_data\n#define _asn1_sequence mbedtls_asn1_sequence\n#define _ssl_cache_context mbedtls_ssl_cache_context\n#define _ssl_cache_entry mbedtls_ssl_cache_entry\n#define _ssl_ciphersuite_t mbedtls_ssl_ciphersuite_t\n#define _ssl_context mbedtls_ssl_context\n#define _ssl_flight_item mbedtls_ssl_flight_item\n#define _ssl_handshake_params mbedtls_ssl_handshake_params\n#define _ssl_key_cert mbedtls_ssl_key_cert\n#define _ssl_premaster_secret mbedtls_ssl_premaster_secret\n#define _ssl_session mbedtls_ssl_session\n#define _ssl_transform mbedtls_ssl_transform\n#define _x509_crl mbedtls_x509_crl\n#define _x509_crl_entry mbedtls_x509_crl_entry\n#define _x509_crt mbedtls_x509_crt\n#define _x509_csr mbedtls_x509_csr\n#define _x509_time mbedtls_x509_time\n#define _x509write_cert mbedtls_x509write_cert\n#define _x509write_csr mbedtls_x509write_csr\n#define aes_context mbedtls_aes_context\n#define aes_crypt_cbc mbedtls_aes_crypt_cbc\n#define aes_crypt_cfb128 mbedtls_aes_crypt_cfb128\n#define aes_crypt_cfb8 mbedtls_aes_crypt_cfb8\n#define aes_crypt_ctr mbedtls_aes_crypt_ctr\n#define aes_crypt_ecb mbedtls_aes_crypt_ecb\n#define aes_free mbedtls_aes_free\n#define aes_init mbedtls_aes_init\n#define aes_self_test mbedtls_aes_self_test\n#define aes_setkey_dec mbedtls_aes_setkey_dec\n#define aes_setkey_enc mbedtls_aes_setkey_enc\n#define aesni_crypt_ecb mbedtls_aesni_crypt_ecb\n#define aesni_gcm_mult mbedtls_aesni_gcm_mult\n#define aesni_inverse_key mbedtls_aesni_inverse_key\n#define aesni_setkey_enc mbedtls_aesni_setkey_enc\n#define aesni_supports mbedtls_aesni_has_support\n#define alarmed mbedtls_timing_alarmed\n#define arc4_context mbedtls_arc4_context\n#define arc4_crypt mbedtls_arc4_crypt\n#define arc4_free mbedtls_arc4_free\n#define arc4_init mbedtls_arc4_init\n#define arc4_self_test mbedtls_arc4_self_test\n#define arc4_setup mbedtls_arc4_setup\n#define asn1_bitstring mbedtls_asn1_bitstring\n#define asn1_buf mbedtls_asn1_buf\n#define asn1_find_named_data mbedtls_asn1_find_named_data\n#define asn1_free_named_data mbedtls_asn1_free_named_data\n#define asn1_free_named_data_list mbedtls_asn1_free_named_data_list\n#define asn1_get_alg mbedtls_asn1_get_alg\n#define asn1_get_alg_null mbedtls_asn1_get_alg_null\n#define asn1_get_bitstring mbedtls_asn1_get_bitstring\n#define asn1_get_bitstring_null mbedtls_asn1_get_bitstring_null\n#define asn1_get_bool mbedtls_asn1_get_bool\n#define asn1_get_int mbedtls_asn1_get_int\n#define asn1_get_len mbedtls_asn1_get_len\n#define asn1_get_mpi mbedtls_asn1_get_mpi\n#define asn1_get_sequence_of mbedtls_asn1_get_sequence_of\n#define asn1_get_tag mbedtls_asn1_get_tag\n#define asn1_named_data mbedtls_asn1_named_data\n#define asn1_sequence mbedtls_asn1_sequence\n#define asn1_store_named_data mbedtls_asn1_store_named_data\n#define asn1_write_algorithm_identifier mbedtls_asn1_write_algorithm_identifier\n#define asn1_write_bitstring mbedtls_asn1_write_bitstring\n#define asn1_write_bool mbedtls_asn1_write_bool\n#define asn1_write_ia5_string mbedtls_asn1_write_ia5_string\n#define asn1_write_int mbedtls_asn1_write_int\n#define asn1_write_len mbedtls_asn1_write_len\n#define asn1_write_mpi mbedtls_asn1_write_mpi\n#define asn1_write_null mbedtls_asn1_write_null\n#define asn1_write_octet_string mbedtls_asn1_write_octet_string\n#define asn1_write_oid mbedtls_asn1_write_oid\n#define asn1_write_printable_string mbedtls_asn1_write_printable_string\n#define asn1_write_raw_buffer mbedtls_asn1_write_raw_buffer\n#define asn1_write_tag mbedtls_asn1_write_tag\n#define base64_decode mbedtls_base64_decode\n#define base64_encode mbedtls_base64_encode\n#define base64_self_test mbedtls_base64_self_test\n#define blowfish_context mbedtls_blowfish_context\n#define blowfish_crypt_cbc mbedtls_blowfish_crypt_cbc\n#define blowfish_crypt_cfb64 mbedtls_blowfish_crypt_cfb64\n#define blowfish_crypt_ctr mbedtls_blowfish_crypt_ctr\n#define blowfish_crypt_ecb mbedtls_blowfish_crypt_ecb\n#define blowfish_free mbedtls_blowfish_free\n#define blowfish_init mbedtls_blowfish_init\n#define blowfish_setkey mbedtls_blowfish_setkey\n#define camellia_context mbedtls_camellia_context\n#define camellia_crypt_cbc mbedtls_camellia_crypt_cbc\n#define camellia_crypt_cfb128 mbedtls_camellia_crypt_cfb128\n#define camellia_crypt_ctr mbedtls_camellia_crypt_ctr\n#define camellia_crypt_ecb mbedtls_camellia_crypt_ecb\n#define camellia_free mbedtls_camellia_free\n#define camellia_init mbedtls_camellia_init\n#define camellia_self_test mbedtls_camellia_self_test\n#define camellia_setkey_dec mbedtls_camellia_setkey_dec\n#define camellia_setkey_enc mbedtls_camellia_setkey_enc\n#define ccm_auth_decrypt mbedtls_ccm_auth_decrypt\n#define ccm_context mbedtls_ccm_context\n#define ccm_encrypt_and_tag mbedtls_ccm_encrypt_and_tag\n#define ccm_free mbedtls_ccm_free\n#define ccm_init mbedtls_ccm_init\n#define ccm_self_test mbedtls_ccm_self_test\n#define cipher_auth_decrypt mbedtls_cipher_auth_decrypt\n#define cipher_auth_encrypt mbedtls_cipher_auth_encrypt\n#define cipher_base_t mbedtls_cipher_base_t\n#define cipher_check_tag mbedtls_cipher_check_tag\n#define cipher_context_t mbedtls_cipher_context_t\n#define cipher_crypt mbedtls_cipher_crypt\n#define cipher_definition_t mbedtls_cipher_definition_t\n#define cipher_definitions mbedtls_cipher_definitions\n#define cipher_finish mbedtls_cipher_finish\n#define cipher_free mbedtls_cipher_free\n#define cipher_get_block_size mbedtls_cipher_get_block_size\n#define cipher_get_cipher_mode mbedtls_cipher_get_cipher_mode\n#define cipher_get_iv_size mbedtls_cipher_get_iv_size\n#define cipher_get_key_size mbedtls_cipher_get_key_bitlen\n#define cipher_get_name mbedtls_cipher_get_name\n#define cipher_get_operation mbedtls_cipher_get_operation\n#define cipher_get_type mbedtls_cipher_get_type\n#define cipher_id_t mbedtls_cipher_id_t\n#define cipher_info_from_string mbedtls_cipher_info_from_string\n#define cipher_info_from_type mbedtls_cipher_info_from_type\n#define cipher_info_from_values mbedtls_cipher_info_from_values\n#define cipher_info_t mbedtls_cipher_info_t\n#define cipher_init mbedtls_cipher_init\n#define cipher_init_ctx mbedtls_cipher_setup\n#define cipher_list mbedtls_cipher_list\n#define cipher_mode_t mbedtls_cipher_mode_t\n#define cipher_padding_t mbedtls_cipher_padding_t\n#define cipher_reset mbedtls_cipher_reset\n#define cipher_set_iv mbedtls_cipher_set_iv\n#define cipher_set_padding_mode mbedtls_cipher_set_padding_mode\n#define cipher_setkey mbedtls_cipher_setkey\n#define cipher_type_t mbedtls_cipher_type_t\n#define cipher_update mbedtls_cipher_update\n#define cipher_update_ad mbedtls_cipher_update_ad\n#define cipher_write_tag mbedtls_cipher_write_tag\n#define ctr_drbg_context mbedtls_ctr_drbg_context\n#define ctr_drbg_free mbedtls_ctr_drbg_free\n#define ctr_drbg_init mbedtls_ctr_drbg_init\n#define ctr_drbg_random mbedtls_ctr_drbg_random\n#define ctr_drbg_random_with_add mbedtls_ctr_drbg_random_with_add\n#define ctr_drbg_reseed mbedtls_ctr_drbg_reseed\n#define ctr_drbg_self_test mbedtls_ctr_drbg_self_test\n#define ctr_drbg_set_entropy_len mbedtls_ctr_drbg_set_entropy_len\n#define ctr_drbg_set_prediction_resistance mbedtls_ctr_drbg_set_prediction_resistance\n#define ctr_drbg_set_reseed_interval mbedtls_ctr_drbg_set_reseed_interval\n#define ctr_drbg_update mbedtls_ctr_drbg_update\n#define ctr_drbg_update_seed_file mbedtls_ctr_drbg_update_seed_file\n#define ctr_drbg_write_seed_file mbedtls_ctr_drbg_write_seed_file\n#define debug_print_buf mbedtls_debug_print_buf\n#define debug_print_crt mbedtls_debug_print_crt\n#define debug_print_ecp mbedtls_debug_print_ecp\n#define debug_print_mpi mbedtls_debug_print_mpi\n#define debug_print_msg mbedtls_debug_print_msg\n#define debug_print_ret mbedtls_debug_print_ret\n#define debug_set_threshold mbedtls_debug_set_threshold\n#define des3_context mbedtls_des3_context\n#define des3_crypt_cbc mbedtls_des3_crypt_cbc\n#define des3_crypt_ecb mbedtls_des3_crypt_ecb\n#define des3_free mbedtls_des3_free\n#define des3_init mbedtls_des3_init\n#define des3_set2key_dec mbedtls_des3_set2key_dec\n#define des3_set2key_enc mbedtls_des3_set2key_enc\n#define des3_set3key_dec mbedtls_des3_set3key_dec\n#define des3_set3key_enc mbedtls_des3_set3key_enc\n#define des_context mbedtls_des_context\n#define des_crypt_cbc mbedtls_des_crypt_cbc\n#define des_crypt_ecb mbedtls_des_crypt_ecb\n#define des_free mbedtls_des_free\n#define des_init mbedtls_des_init\n#define des_key_check_key_parity mbedtls_des_key_check_key_parity\n#define des_key_check_weak mbedtls_des_key_check_weak\n#define des_key_set_parity mbedtls_des_key_set_parity\n#define des_self_test mbedtls_des_self_test\n#define des_setkey_dec mbedtls_des_setkey_dec\n#define des_setkey_enc mbedtls_des_setkey_enc\n#define dhm_calc_secret mbedtls_dhm_calc_secret\n#define dhm_context mbedtls_dhm_context\n#define dhm_free mbedtls_dhm_free\n#define dhm_init mbedtls_dhm_init\n#define dhm_make_params mbedtls_dhm_make_params\n#define dhm_make_public mbedtls_dhm_make_public\n#define dhm_parse_dhm mbedtls_dhm_parse_dhm\n#define dhm_parse_dhmfile mbedtls_dhm_parse_dhmfile\n#define dhm_read_params mbedtls_dhm_read_params\n#define dhm_read_public mbedtls_dhm_read_public\n#define dhm_self_test mbedtls_dhm_self_test\n#define ecdh_calc_secret mbedtls_ecdh_calc_secret\n#define ecdh_compute_shared mbedtls_ecdh_compute_shared\n#define ecdh_context mbedtls_ecdh_context\n#define ecdh_free mbedtls_ecdh_free\n#define ecdh_gen_public mbedtls_ecdh_gen_public\n#define ecdh_get_params mbedtls_ecdh_get_params\n#define ecdh_init mbedtls_ecdh_init\n#define ecdh_make_params mbedtls_ecdh_make_params\n#define ecdh_make_public mbedtls_ecdh_make_public\n#define ecdh_read_params mbedtls_ecdh_read_params\n#define ecdh_read_public mbedtls_ecdh_read_public\n#define ecdh_side mbedtls_ecdh_side\n#define ecdsa_context mbedtls_ecdsa_context\n#define ecdsa_free mbedtls_ecdsa_free\n#define ecdsa_from_keypair mbedtls_ecdsa_from_keypair\n#define ecdsa_genkey mbedtls_ecdsa_genkey\n#define ecdsa_info mbedtls_ecdsa_info\n#define ecdsa_init mbedtls_ecdsa_init\n#define ecdsa_read_signature mbedtls_ecdsa_read_signature\n#define ecdsa_sign mbedtls_ecdsa_sign\n#define ecdsa_sign_det mbedtls_ecdsa_sign_det\n#define ecdsa_verify mbedtls_ecdsa_verify\n#define ecdsa_write_signature mbedtls_ecdsa_write_signature\n#define ecdsa_write_signature_det mbedtls_ecdsa_write_signature_det\n#define eckey_info mbedtls_eckey_info\n#define eckeydh_info mbedtls_eckeydh_info\n#define ecp_check_privkey mbedtls_ecp_check_privkey\n#define ecp_check_pub_priv mbedtls_ecp_check_pub_priv\n#define ecp_check_pubkey mbedtls_ecp_check_pubkey\n#define ecp_copy mbedtls_ecp_copy\n#define ecp_curve_info mbedtls_ecp_curve_info\n#define ecp_curve_info_from_grp_id mbedtls_ecp_curve_info_from_grp_id\n#define ecp_curve_info_from_name mbedtls_ecp_curve_info_from_name\n#define ecp_curve_info_from_tls_id mbedtls_ecp_curve_info_from_tls_id\n#define ecp_curve_list mbedtls_ecp_curve_list\n#define ecp_gen_key mbedtls_ecp_gen_key\n#define ecp_gen_keypair mbedtls_ecp_gen_keypair\n#define ecp_group mbedtls_ecp_group\n#define ecp_group_copy mbedtls_ecp_group_copy\n#define ecp_group_free mbedtls_ecp_group_free\n#define ecp_group_id mbedtls_ecp_group_id\n#define ecp_group_init mbedtls_ecp_group_init\n#define ecp_grp_id_list mbedtls_ecp_grp_id_list\n#define ecp_is_zero mbedtls_ecp_is_zero\n#define ecp_keypair mbedtls_ecp_keypair\n#define ecp_keypair_free mbedtls_ecp_keypair_free\n#define ecp_keypair_init mbedtls_ecp_keypair_init\n#define ecp_mul mbedtls_ecp_mul\n#define ecp_point mbedtls_ecp_point\n#define ecp_point_free mbedtls_ecp_point_free\n#define ecp_point_init mbedtls_ecp_point_init\n#define ecp_point_read_binary mbedtls_ecp_point_read_binary\n#define ecp_point_read_string mbedtls_ecp_point_read_string\n#define ecp_point_write_binary mbedtls_ecp_point_write_binary\n#define ecp_self_test mbedtls_ecp_self_test\n#define ecp_set_zero mbedtls_ecp_set_zero\n#define ecp_tls_read_group mbedtls_ecp_tls_read_group\n#define ecp_tls_read_point mbedtls_ecp_tls_read_point\n#define ecp_tls_write_group mbedtls_ecp_tls_write_group\n#define ecp_tls_write_point mbedtls_ecp_tls_write_point\n#define ecp_use_known_dp mbedtls_ecp_group_load\n#define entropy_add_source mbedtls_entropy_add_source\n#define entropy_context mbedtls_entropy_context\n#define entropy_free mbedtls_entropy_free\n#define entropy_func mbedtls_entropy_func\n#define entropy_gather mbedtls_entropy_gather\n#define entropy_init mbedtls_entropy_init\n#define entropy_self_test mbedtls_entropy_self_test\n#define entropy_update_manual mbedtls_entropy_update_manual\n#define entropy_update_seed_file mbedtls_entropy_update_seed_file\n#define entropy_write_seed_file mbedtls_entropy_write_seed_file\n#define error_strerror mbedtls_strerror\n#define f_source_ptr mbedtls_entropy_f_source_ptr\n#define gcm_auth_decrypt mbedtls_gcm_auth_decrypt\n#define gcm_context mbedtls_gcm_context\n#define gcm_crypt_and_tag mbedtls_gcm_crypt_and_tag\n#define gcm_finish mbedtls_gcm_finish\n#define gcm_free mbedtls_gcm_free\n#define gcm_init mbedtls_gcm_init\n#define gcm_self_test mbedtls_gcm_self_test\n#define gcm_starts mbedtls_gcm_starts\n#define gcm_update mbedtls_gcm_update\n#define get_timer mbedtls_timing_get_timer\n#define hardclock mbedtls_timing_hardclock\n#define hardclock_poll mbedtls_hardclock_poll\n#define havege_free mbedtls_havege_free\n#define havege_init mbedtls_havege_init\n#define havege_poll mbedtls_havege_poll\n#define havege_random mbedtls_havege_random\n#define havege_state mbedtls_havege_state\n#define hmac_drbg_context mbedtls_hmac_drbg_context\n#define hmac_drbg_free mbedtls_hmac_drbg_free\n#define hmac_drbg_init mbedtls_hmac_drbg_init\n#define hmac_drbg_random mbedtls_hmac_drbg_random\n#define hmac_drbg_random_with_add mbedtls_hmac_drbg_random_with_add\n#define hmac_drbg_reseed mbedtls_hmac_drbg_reseed\n#define hmac_drbg_self_test mbedtls_hmac_drbg_self_test\n#define hmac_drbg_set_entropy_len mbedtls_hmac_drbg_set_entropy_len\n#define hmac_drbg_set_prediction_resistance mbedtls_hmac_drbg_set_prediction_resistance\n#define hmac_drbg_set_reseed_interval mbedtls_hmac_drbg_set_reseed_interval\n#define hmac_drbg_update mbedtls_hmac_drbg_update\n#define hmac_drbg_update_seed_file mbedtls_hmac_drbg_update_seed_file\n#define hmac_drbg_write_seed_file mbedtls_hmac_drbg_write_seed_file\n#define hr_time mbedtls_timing_hr_time\n#define key_exchange_type_t mbedtls_key_exchange_type_t\n#define md mbedtls_md\n#define md2 mbedtls_md2\n#define md2_context mbedtls_md2_context\n#define md2_finish mbedtls_md2_finish\n#define md2_free mbedtls_md2_free\n#define md2_info mbedtls_md2_info\n#define md2_init mbedtls_md2_init\n#define md2_process mbedtls_md2_process\n#define md2_self_test mbedtls_md2_self_test\n#define md2_starts mbedtls_md2_starts\n#define md2_update mbedtls_md2_update\n#define md4 mbedtls_md4\n#define md4_context mbedtls_md4_context\n#define md4_finish mbedtls_md4_finish\n#define md4_free mbedtls_md4_free\n#define md4_info mbedtls_md4_info\n#define md4_init mbedtls_md4_init\n#define md4_process mbedtls_md4_process\n#define md4_self_test mbedtls_md4_self_test\n#define md4_starts mbedtls_md4_starts\n#define md4_update mbedtls_md4_update\n#define md5 mbedtls_md5\n#define md5_context mbedtls_md5_context\n#define md5_finish mbedtls_md5_finish\n#define md5_free mbedtls_md5_free\n#define md5_info mbedtls_md5_info\n#define md5_init mbedtls_md5_init\n#define md5_process mbedtls_md5_process\n#define md5_self_test mbedtls_md5_self_test\n#define md5_starts mbedtls_md5_starts\n#define md5_update mbedtls_md5_update\n#define md_context_t mbedtls_md_context_t\n#define md_file mbedtls_md_file\n#define md_finish mbedtls_md_finish\n#define md_free mbedtls_md_free\n#define md_get_name mbedtls_md_get_name\n#define md_get_size mbedtls_md_get_size\n#define md_get_type mbedtls_md_get_type\n#define md_hmac mbedtls_md_hmac\n#define md_hmac_finish mbedtls_md_hmac_finish\n#define md_hmac_reset mbedtls_md_hmac_reset\n#define md_hmac_starts mbedtls_md_hmac_starts\n#define md_hmac_update mbedtls_md_hmac_update\n#define md_info_from_string mbedtls_md_info_from_string\n#define md_info_from_type mbedtls_md_info_from_type\n#define md_info_t mbedtls_md_info_t\n#define md_init mbedtls_md_init\n#define md_init_ctx mbedtls_md_init_ctx\n#define md_list mbedtls_md_list\n#define md_process mbedtls_md_process\n#define md_starts mbedtls_md_starts\n#define md_type_t mbedtls_md_type_t\n#define md_update mbedtls_md_update\n#define memory_buffer_alloc_cur_get mbedtls_memory_buffer_alloc_cur_get\n#define memory_buffer_alloc_free mbedtls_memory_buffer_alloc_free\n#define memory_buffer_alloc_init mbedtls_memory_buffer_alloc_init\n#define memory_buffer_alloc_max_get mbedtls_memory_buffer_alloc_max_get\n#define memory_buffer_alloc_max_reset mbedtls_memory_buffer_alloc_max_reset\n#define memory_buffer_alloc_self_test mbedtls_memory_buffer_alloc_self_test\n#define memory_buffer_alloc_status mbedtls_memory_buffer_alloc_status\n#define memory_buffer_alloc_verify mbedtls_memory_buffer_alloc_verify\n#define memory_buffer_set_verify mbedtls_memory_buffer_set_verify\n#define mpi mbedtls_mpi\n#define mpi_add_abs mbedtls_mpi_add_abs\n#define mpi_add_int mbedtls_mpi_add_int\n#define mpi_add_mpi mbedtls_mpi_add_mpi\n#define mpi_cmp_abs mbedtls_mpi_cmp_abs\n#define mpi_cmp_int mbedtls_mpi_cmp_int\n#define mpi_cmp_mpi mbedtls_mpi_cmp_mpi\n#define mpi_copy mbedtls_mpi_copy\n#define mpi_div_int mbedtls_mpi_div_int\n#define mpi_div_mpi mbedtls_mpi_div_mpi\n#define mpi_exp_mod mbedtls_mpi_exp_mod\n#define mpi_fill_random mbedtls_mpi_fill_random\n#define mpi_free mbedtls_mpi_free\n#define mpi_gcd mbedtls_mpi_gcd\n#define mpi_gen_prime mbedtls_mpi_gen_prime\n#define mpi_get_bit mbedtls_mpi_get_bit\n#define mpi_grow mbedtls_mpi_grow\n#define mpi_init mbedtls_mpi_init\n#define mpi_inv_mod mbedtls_mpi_inv_mod\n#define mpi_is_prime mbedtls_mpi_is_prime\n#define mpi_lsb mbedtls_mpi_lsb\n#define mpi_lset mbedtls_mpi_lset\n#define mpi_mod_int mbedtls_mpi_mod_int\n#define mpi_mod_mpi mbedtls_mpi_mod_mpi\n#define mpi_msb mbedtls_mpi_bitlen\n#define mpi_mul_int mbedtls_mpi_mul_int\n#define mpi_mul_mpi mbedtls_mpi_mul_mpi\n#define mpi_read_binary mbedtls_mpi_read_binary\n#define mpi_read_file mbedtls_mpi_read_file\n#define mpi_read_string mbedtls_mpi_read_string\n#define mpi_safe_cond_assign mbedtls_mpi_safe_cond_assign\n#define mpi_safe_cond_swap mbedtls_mpi_safe_cond_swap\n#define mpi_self_test mbedtls_mpi_self_test\n#define mpi_set_bit mbedtls_mpi_set_bit\n#define mpi_shift_l mbedtls_mpi_shift_l\n#define mpi_shift_r mbedtls_mpi_shift_r\n#define mpi_shrink mbedtls_mpi_shrink\n#define mpi_size mbedtls_mpi_size\n#define mpi_sub_abs mbedtls_mpi_sub_abs\n#define mpi_sub_int mbedtls_mpi_sub_int\n#define mpi_sub_mpi mbedtls_mpi_sub_mpi\n#define mpi_swap mbedtls_mpi_swap\n#define mpi_write_binary mbedtls_mpi_write_binary\n#define mpi_write_file mbedtls_mpi_write_file\n#define mpi_write_string mbedtls_mpi_write_string\n#define net_accept mbedtls_net_accept\n#define net_bind mbedtls_net_bind\n#define net_close mbedtls_net_free\n#define net_connect mbedtls_net_connect\n#define net_recv mbedtls_net_recv\n#define net_recv_timeout mbedtls_net_recv_timeout\n#define net_send mbedtls_net_send\n#define net_set_block mbedtls_net_set_block\n#define net_set_nonblock mbedtls_net_set_nonblock\n#define net_usleep mbedtls_net_usleep\n#define oid_descriptor_t mbedtls_oid_descriptor_t\n#define oid_get_attr_short_name mbedtls_oid_get_attr_short_name\n#define oid_get_cipher_alg mbedtls_oid_get_cipher_alg\n#define oid_get_ec_grp mbedtls_oid_get_ec_grp\n#define oid_get_extended_key_usage mbedtls_oid_get_extended_key_usage\n#define oid_get_md_alg mbedtls_oid_get_md_alg\n#define oid_get_numeric_string mbedtls_oid_get_numeric_string\n#define oid_get_oid_by_ec_grp mbedtls_oid_get_oid_by_ec_grp\n#define oid_get_oid_by_md mbedtls_oid_get_oid_by_md\n#define oid_get_oid_by_pk_alg mbedtls_oid_get_oid_by_pk_alg\n#define oid_get_oid_by_sig_alg mbedtls_oid_get_oid_by_sig_alg\n#define oid_get_pk_alg mbedtls_oid_get_pk_alg\n#define oid_get_pkcs12_pbe_alg mbedtls_oid_get_pkcs12_pbe_alg\n#define oid_get_sig_alg mbedtls_oid_get_sig_alg\n#define oid_get_sig_alg_desc mbedtls_oid_get_sig_alg_desc\n#define oid_get_x509_ext_type mbedtls_oid_get_x509_ext_type\n#define operation_t mbedtls_operation_t\n#define padlock_supports mbedtls_padlock_has_support\n#define padlock_xcryptcbc mbedtls_padlock_xcryptcbc\n#define padlock_xcryptecb mbedtls_padlock_xcryptecb\n#define pem_context mbedtls_pem_context\n#define pem_free mbedtls_pem_free\n#define pem_init mbedtls_pem_init\n#define pem_read_buffer mbedtls_pem_read_buffer\n#define pem_write_buffer mbedtls_pem_write_buffer\n#define pk_can_do mbedtls_pk_can_do\n#define pk_check_pair mbedtls_pk_check_pair\n#define pk_context mbedtls_pk_context\n#define pk_debug mbedtls_pk_debug\n#define pk_debug_item mbedtls_pk_debug_item\n#define pk_debug_type mbedtls_pk_debug_type\n#define pk_decrypt mbedtls_pk_decrypt\n#define pk_ec mbedtls_pk_ec\n#define pk_encrypt mbedtls_pk_encrypt\n#define pk_free mbedtls_pk_free\n#define pk_get_len mbedtls_pk_get_len\n#define pk_get_name mbedtls_pk_get_name\n#define pk_get_size mbedtls_pk_get_bitlen\n#define pk_get_type mbedtls_pk_get_type\n#define pk_info_from_type mbedtls_pk_info_from_type\n#define pk_info_t mbedtls_pk_info_t\n#define pk_init mbedtls_pk_init\n#define pk_init_ctx mbedtls_pk_setup\n#define pk_init_ctx_rsa_alt mbedtls_pk_setup_rsa_alt\n#define pk_load_file mbedtls_pk_load_file\n#define pk_parse_key mbedtls_pk_parse_key\n#define pk_parse_keyfile mbedtls_pk_parse_keyfile\n#define pk_parse_public_key mbedtls_pk_parse_public_key\n#define pk_parse_public_keyfile mbedtls_pk_parse_public_keyfile\n#define pk_parse_subpubkey mbedtls_pk_parse_subpubkey\n#define pk_rsa mbedtls_pk_rsa\n#define pk_rsa_alt_decrypt_func mbedtls_pk_rsa_alt_decrypt_func\n#define pk_rsa_alt_key_len_func mbedtls_pk_rsa_alt_key_len_func\n#define pk_rsa_alt_sign_func mbedtls_pk_rsa_alt_sign_func\n#define pk_rsassa_pss_options mbedtls_pk_rsassa_pss_options\n#define pk_sign mbedtls_pk_sign\n#define pk_type_t mbedtls_pk_type_t\n#define pk_verify mbedtls_pk_verify\n#define pk_verify_ext mbedtls_pk_verify_ext\n#define pk_write_key_der mbedtls_pk_write_key_der\n#define pk_write_key_pem mbedtls_pk_write_key_pem\n#define pk_write_pubkey mbedtls_pk_write_pubkey\n#define pk_write_pubkey_der mbedtls_pk_write_pubkey_der\n#define pk_write_pubkey_pem mbedtls_pk_write_pubkey_pem\n#define pkcs11_context mbedtls_pkcs11_context\n#define pkcs11_decrypt mbedtls_pkcs11_decrypt\n#define pkcs11_priv_key_free mbedtls_pkcs11_priv_key_free\n#define pkcs11_priv_key_init mbedtls_pkcs11_priv_key_bind\n#define pkcs11_sign mbedtls_pkcs11_sign\n#define pkcs11_x509_cert_init mbedtls_pkcs11_x509_cert_bind\n#define pkcs12_derivation mbedtls_pkcs12_derivation\n#define pkcs12_pbe mbedtls_pkcs12_pbe\n#define pkcs12_pbe_sha1_rc4_128 mbedtls_pkcs12_pbe_sha1_rc4_128\n#define pkcs5_pbes2 mbedtls_pkcs5_pbes2\n#define pkcs5_pbkdf2_hmac mbedtls_pkcs5_pbkdf2_hmac\n#define pkcs5_self_test mbedtls_pkcs5_self_test\n#define platform_entropy_poll mbedtls_platform_entropy_poll\n#define platform_set_exit mbedtls_platform_set_exit\n#define platform_set_fprintf mbedtls_platform_set_fprintf\n#define platform_set_printf mbedtls_platform_set_printf\n#define platform_set_snprintf mbedtls_platform_set_snprintf\n#define polarssl_exit mbedtls_exit\n#define polarssl_fprintf mbedtls_fprintf\n#define polarssl_free mbedtls_free\n#define polarssl_mutex_free mbedtls_mutex_free\n#define polarssl_mutex_init mbedtls_mutex_init\n#define polarssl_mutex_lock mbedtls_mutex_lock\n#define polarssl_mutex_unlock mbedtls_mutex_unlock\n#define polarssl_printf mbedtls_printf\n#define polarssl_snprintf mbedtls_snprintf\n#define polarssl_strerror mbedtls_strerror\n#define ripemd160 mbedtls_ripemd160\n#define ripemd160_context mbedtls_ripemd160_context\n#define ripemd160_finish mbedtls_ripemd160_finish\n#define ripemd160_free mbedtls_ripemd160_free\n#define ripemd160_info mbedtls_ripemd160_info\n#define ripemd160_init mbedtls_ripemd160_init\n#define ripemd160_process mbedtls_ripemd160_process\n#define ripemd160_self_test mbedtls_ripemd160_self_test\n#define ripemd160_starts mbedtls_ripemd160_starts\n#define ripemd160_update mbedtls_ripemd160_update\n#define rsa_alt_context mbedtls_rsa_alt_context\n#define rsa_alt_info mbedtls_rsa_alt_info\n#define rsa_check_privkey mbedtls_rsa_check_privkey\n#define rsa_check_pub_priv mbedtls_rsa_check_pub_priv\n#define rsa_check_pubkey mbedtls_rsa_check_pubkey\n#define rsa_context mbedtls_rsa_context\n#define rsa_copy mbedtls_rsa_copy\n#define rsa_free mbedtls_rsa_free\n#define rsa_gen_key mbedtls_rsa_gen_key\n#define rsa_info mbedtls_rsa_info\n#define rsa_init mbedtls_rsa_init\n#define rsa_pkcs1_decrypt mbedtls_rsa_pkcs1_decrypt\n#define rsa_pkcs1_encrypt mbedtls_rsa_pkcs1_encrypt\n#define rsa_pkcs1_sign mbedtls_rsa_pkcs1_sign\n#define rsa_pkcs1_verify mbedtls_rsa_pkcs1_verify\n#define rsa_private mbedtls_rsa_private\n#define rsa_public mbedtls_rsa_public\n#define rsa_rsaes_oaep_decrypt mbedtls_rsa_rsaes_oaep_decrypt\n#define rsa_rsaes_oaep_encrypt mbedtls_rsa_rsaes_oaep_encrypt\n#define rsa_rsaes_pkcs1_v15_decrypt mbedtls_rsa_rsaes_pkcs1_v15_decrypt\n#define rsa_rsaes_pkcs1_v15_encrypt mbedtls_rsa_rsaes_pkcs1_v15_encrypt\n#define rsa_rsassa_pkcs1_v15_sign mbedtls_rsa_rsassa_pkcs1_v15_sign\n#define rsa_rsassa_pkcs1_v15_verify mbedtls_rsa_rsassa_pkcs1_v15_verify\n#define rsa_rsassa_pss_sign mbedtls_rsa_rsassa_pss_sign\n#define rsa_rsassa_pss_verify mbedtls_rsa_rsassa_pss_verify\n#define rsa_rsassa_pss_verify_ext mbedtls_rsa_rsassa_pss_verify_ext\n#define rsa_self_test mbedtls_rsa_self_test\n#define rsa_set_padding mbedtls_rsa_set_padding\n#define safer_memcmp mbedtls_ssl_safer_memcmp\n#define set_alarm mbedtls_set_alarm\n#define sha1 mbedtls_sha1\n#define sha1_context mbedtls_sha1_context\n#define sha1_finish mbedtls_sha1_finish\n#define sha1_free mbedtls_sha1_free\n#define sha1_info mbedtls_sha1_info\n#define sha1_init mbedtls_sha1_init\n#define sha1_process mbedtls_sha1_process\n#define sha1_self_test mbedtls_sha1_self_test\n#define sha1_starts mbedtls_sha1_starts\n#define sha1_update mbedtls_sha1_update\n#define sha224_info mbedtls_sha224_info\n#define sha256 mbedtls_sha256\n#define sha256_context mbedtls_sha256_context\n#define sha256_finish mbedtls_sha256_finish\n#define sha256_free mbedtls_sha256_free\n#define sha256_info mbedtls_sha256_info\n#define sha256_init mbedtls_sha256_init\n#define sha256_process mbedtls_sha256_process\n#define sha256_self_test mbedtls_sha256_self_test\n#define sha256_starts mbedtls_sha256_starts\n#define sha256_update mbedtls_sha256_update\n#define sha384_info mbedtls_sha384_info\n#define sha512 mbedtls_sha512\n#define sha512_context mbedtls_sha512_context\n#define sha512_finish mbedtls_sha512_finish\n#define sha512_free mbedtls_sha512_free\n#define sha512_info mbedtls_sha512_info\n#define sha512_init mbedtls_sha512_init\n#define sha512_process mbedtls_sha512_process\n#define sha512_self_test mbedtls_sha512_self_test\n#define sha512_starts mbedtls_sha512_starts\n#define sha512_update mbedtls_sha512_update\n#define source_state mbedtls_entropy_source_state\n#define ssl_cache_context mbedtls_ssl_cache_context\n#define ssl_cache_entry mbedtls_ssl_cache_entry\n#define ssl_cache_free mbedtls_ssl_cache_free\n#define ssl_cache_get mbedtls_ssl_cache_get\n#define ssl_cache_init mbedtls_ssl_cache_init\n#define ssl_cache_set mbedtls_ssl_cache_set\n#define ssl_cache_set_max_entries mbedtls_ssl_cache_set_max_entries\n#define ssl_cache_set_timeout mbedtls_ssl_cache_set_timeout\n#define ssl_check_cert_usage mbedtls_ssl_check_cert_usage\n#define ssl_ciphersuite_from_id mbedtls_ssl_ciphersuite_from_id\n#define ssl_ciphersuite_from_string mbedtls_ssl_ciphersuite_from_string\n#define ssl_ciphersuite_t mbedtls_ssl_ciphersuite_t\n#define ssl_ciphersuite_uses_ec mbedtls_ssl_ciphersuite_uses_ec\n#define ssl_ciphersuite_uses_psk mbedtls_ssl_ciphersuite_uses_psk\n#define ssl_close_notify mbedtls_ssl_close_notify\n#define ssl_context mbedtls_ssl_context\n#define ssl_cookie_check mbedtls_ssl_cookie_check\n#define ssl_cookie_check_t mbedtls_ssl_cookie_check_t\n#define ssl_cookie_ctx mbedtls_ssl_cookie_ctx\n#define ssl_cookie_free mbedtls_ssl_cookie_free\n#define ssl_cookie_init mbedtls_ssl_cookie_init\n#define ssl_cookie_set_timeout mbedtls_ssl_cookie_set_timeout\n#define ssl_cookie_setup mbedtls_ssl_cookie_setup\n#define ssl_cookie_write mbedtls_ssl_cookie_write\n#define ssl_cookie_write_t mbedtls_ssl_cookie_write_t\n#define ssl_derive_keys mbedtls_ssl_derive_keys\n#define ssl_dtls_replay_check mbedtls_ssl_dtls_replay_check\n#define ssl_dtls_replay_update mbedtls_ssl_dtls_replay_update\n#define ssl_fetch_input mbedtls_ssl_fetch_input\n#define ssl_flight_item mbedtls_ssl_flight_item\n#define ssl_flush_output mbedtls_ssl_flush_output\n#define ssl_free mbedtls_ssl_free\n#define ssl_get_alpn_protocol mbedtls_ssl_get_alpn_protocol\n#define ssl_get_bytes_avail mbedtls_ssl_get_bytes_avail\n#define ssl_get_ciphersuite mbedtls_ssl_get_ciphersuite\n#define ssl_get_ciphersuite_id mbedtls_ssl_get_ciphersuite_id\n#define ssl_get_ciphersuite_name mbedtls_ssl_get_ciphersuite_name\n#define ssl_get_ciphersuite_sig_pk_alg mbedtls_ssl_get_ciphersuite_sig_pk_alg\n#define ssl_get_peer_cert mbedtls_ssl_get_peer_cert\n#define ssl_get_record_expansion mbedtls_ssl_get_record_expansion\n#define ssl_get_session mbedtls_ssl_get_session\n#define ssl_get_verify_result mbedtls_ssl_get_verify_result\n#define ssl_get_version mbedtls_ssl_get_version\n#define ssl_handshake mbedtls_ssl_handshake\n#define ssl_handshake_client_step mbedtls_ssl_handshake_client_step\n#define ssl_handshake_free mbedtls_ssl_handshake_free\n#define ssl_handshake_params mbedtls_ssl_handshake_params\n#define ssl_handshake_server_step mbedtls_ssl_handshake_server_step\n#define ssl_handshake_step mbedtls_ssl_handshake_step\n#define ssl_handshake_wrapup mbedtls_ssl_handshake_wrapup\n#define ssl_hdr_len mbedtls_ssl_hdr_len\n#define ssl_hs_hdr_len mbedtls_ssl_hs_hdr_len\n#define ssl_hw_record_activate mbedtls_ssl_hw_record_activate\n#define ssl_hw_record_finish mbedtls_ssl_hw_record_finish\n#define ssl_hw_record_init mbedtls_ssl_hw_record_init\n#define ssl_hw_record_read mbedtls_ssl_hw_record_read\n#define ssl_hw_record_reset mbedtls_ssl_hw_record_reset\n#define ssl_hw_record_write mbedtls_ssl_hw_record_write\n#define ssl_init mbedtls_ssl_init\n#define ssl_key_cert mbedtls_ssl_key_cert\n#define ssl_legacy_renegotiation mbedtls_ssl_conf_legacy_renegotiation\n#define ssl_list_ciphersuites mbedtls_ssl_list_ciphersuites\n#define ssl_md_alg_from_hash mbedtls_ssl_md_alg_from_hash\n#define ssl_optimize_checksum mbedtls_ssl_optimize_checksum\n#define ssl_own_cert mbedtls_ssl_own_cert\n#define ssl_own_key mbedtls_ssl_own_key\n#define ssl_parse_certificate mbedtls_ssl_parse_certificate\n#define ssl_parse_change_cipher_spec mbedtls_ssl_parse_change_cipher_spec\n#define ssl_parse_finished mbedtls_ssl_parse_finished\n#define ssl_pk_alg_from_sig mbedtls_ssl_pk_alg_from_sig\n#define ssl_pkcs11_decrypt mbedtls_ssl_pkcs11_decrypt\n#define ssl_pkcs11_key_len mbedtls_ssl_pkcs11_key_len\n#define ssl_pkcs11_sign mbedtls_ssl_pkcs11_sign\n#define ssl_psk_derive_premaster mbedtls_ssl_psk_derive_premaster\n#define ssl_read mbedtls_ssl_read\n#define ssl_read_record mbedtls_ssl_read_record\n#define ssl_read_version mbedtls_ssl_read_version\n#define ssl_recv_flight_completed mbedtls_ssl_recv_flight_completed\n#define ssl_renegotiate mbedtls_ssl_renegotiate\n#define ssl_resend mbedtls_ssl_resend\n#define ssl_reset_checksum mbedtls_ssl_reset_checksum\n#define ssl_send_alert_message mbedtls_ssl_send_alert_message\n#define ssl_send_fatal_handshake_failure mbedtls_ssl_send_fatal_handshake_failure\n#define ssl_send_flight_completed mbedtls_ssl_send_flight_completed\n#define ssl_session mbedtls_ssl_session\n#define ssl_session_free mbedtls_ssl_session_free\n#define ssl_session_init mbedtls_ssl_session_init\n#define ssl_session_reset mbedtls_ssl_session_reset\n#define ssl_set_alpn_protocols mbedtls_ssl_conf_alpn_protocols\n#define ssl_set_arc4_support mbedtls_ssl_conf_arc4_support\n#define ssl_set_authmode mbedtls_ssl_conf_authmode\n#define ssl_set_bio mbedtls_ssl_set_bio\n#define ssl_set_ca_chain mbedtls_ssl_conf_ca_chain\n#define ssl_set_cbc_record_splitting mbedtls_ssl_conf_cbc_record_splitting\n#define ssl_set_ciphersuites mbedtls_ssl_conf_ciphersuites\n#define ssl_set_ciphersuites_for_version mbedtls_ssl_conf_ciphersuites_for_version\n#define ssl_set_client_transport_id mbedtls_ssl_set_client_transport_id\n#define ssl_set_curves mbedtls_ssl_conf_curves\n#define ssl_set_dbg mbedtls_ssl_conf_dbg\n#define ssl_set_dh_param mbedtls_ssl_conf_dh_param\n#define ssl_set_dh_param_ctx mbedtls_ssl_conf_dh_param_ctx\n#define ssl_set_dtls_anti_replay mbedtls_ssl_conf_dtls_anti_replay\n#define ssl_set_dtls_badmac_limit mbedtls_ssl_conf_dtls_badmac_limit\n#define ssl_set_dtls_cookies mbedtls_ssl_conf_dtls_cookies\n#define ssl_set_encrypt_then_mac mbedtls_ssl_conf_encrypt_then_mac\n#define ssl_set_endpoint mbedtls_ssl_conf_endpoint\n#define ssl_set_extended_master_secret mbedtls_ssl_conf_extended_master_secret\n#define ssl_set_fallback mbedtls_ssl_conf_fallback\n#define ssl_set_handshake_timeout mbedtls_ssl_conf_handshake_timeout\n#define ssl_set_hostname mbedtls_ssl_set_hostname\n#define ssl_set_max_frag_len mbedtls_ssl_conf_max_frag_len\n#define ssl_set_max_version mbedtls_ssl_conf_max_version\n#define ssl_set_min_version mbedtls_ssl_conf_min_version\n#define ssl_set_own_cert mbedtls_ssl_conf_own_cert\n#define ssl_set_psk mbedtls_ssl_conf_psk\n#define ssl_set_psk_cb mbedtls_ssl_conf_psk_cb\n#define ssl_set_renegotiation mbedtls_ssl_conf_renegotiation\n#define ssl_set_renegotiation_enforced mbedtls_ssl_conf_renegotiation_enforced\n#define ssl_set_renegotiation_period mbedtls_ssl_conf_renegotiation_period\n#define ssl_set_rng mbedtls_ssl_conf_rng\n#define ssl_set_session mbedtls_ssl_set_session\n#define ssl_set_session_cache mbedtls_ssl_conf_session_cache\n#define ssl_set_session_tickets mbedtls_ssl_conf_session_tickets\n#define ssl_set_sni mbedtls_ssl_conf_sni\n#define ssl_set_transport mbedtls_ssl_conf_transport\n#define ssl_set_truncated_hmac mbedtls_ssl_conf_truncated_hmac\n#define ssl_set_verify mbedtls_ssl_conf_verify\n#define ssl_sig_from_pk mbedtls_ssl_sig_from_pk\n#define ssl_states mbedtls_ssl_states\n#define ssl_transform mbedtls_ssl_transform\n#define ssl_transform_free mbedtls_ssl_transform_free\n#define ssl_write mbedtls_ssl_write\n#define ssl_write_certificate mbedtls_ssl_write_certificate\n#define ssl_write_change_cipher_spec mbedtls_ssl_write_change_cipher_spec\n#define ssl_write_finished mbedtls_ssl_write_finished\n#define ssl_write_record mbedtls_ssl_write_record\n#define ssl_write_version mbedtls_ssl_write_version\n#define supported_ciphers mbedtls_cipher_supported\n#define t_sint mbedtls_mpi_sint\n#define t_udbl mbedtls_t_udbl\n#define t_uint mbedtls_mpi_uint\n#define test_ca_crt mbedtls_test_ca_crt\n#define test_ca_crt_ec mbedtls_test_ca_crt_ec\n#define test_ca_crt_rsa mbedtls_test_ca_crt_rsa\n#define test_ca_key mbedtls_test_ca_key\n#define test_ca_key_ec mbedtls_test_ca_key_ec\n#define test_ca_key_rsa mbedtls_test_ca_key_rsa\n#define test_ca_list mbedtls_test_cas_pem\n#define test_ca_pwd mbedtls_test_ca_pwd\n#define test_ca_pwd_ec mbedtls_test_ca_pwd_ec\n#define test_ca_pwd_rsa mbedtls_test_ca_pwd_rsa\n#define test_cli_crt mbedtls_test_cli_crt\n#define test_cli_crt_ec mbedtls_test_cli_crt_ec\n#define test_cli_crt_rsa mbedtls_test_cli_crt_rsa\n#define test_cli_key mbedtls_test_cli_key\n#define test_cli_key_ec mbedtls_test_cli_key_ec\n#define test_cli_key_rsa mbedtls_test_cli_key_rsa\n#define test_srv_crt mbedtls_test_srv_crt\n#define test_srv_crt_ec mbedtls_test_srv_crt_ec\n#define test_srv_crt_rsa mbedtls_test_srv_crt_rsa\n#define test_srv_key mbedtls_test_srv_key\n#define test_srv_key_ec mbedtls_test_srv_key_ec\n#define test_srv_key_rsa mbedtls_test_srv_key_rsa\n#define threading_mutex_t mbedtls_threading_mutex_t\n#define threading_set_alt mbedtls_threading_set_alt\n#define timing_self_test mbedtls_timing_self_test\n#define version_check_feature mbedtls_version_check_feature\n#define version_get_number mbedtls_version_get_number\n#define version_get_string mbedtls_version_get_string\n#define version_get_string_full mbedtls_version_get_string_full\n#define x509_bitstring mbedtls_x509_bitstring\n#define x509_buf mbedtls_x509_buf\n#define x509_crl mbedtls_x509_crl\n#define x509_crl_entry mbedtls_x509_crl_entry\n#define x509_crl_free mbedtls_x509_crl_free\n#define x509_crl_info mbedtls_x509_crl_info\n#define x509_crl_init mbedtls_x509_crl_init\n#define x509_crl_parse mbedtls_x509_crl_parse\n#define x509_crl_parse_der mbedtls_x509_crl_parse_der\n#define x509_crl_parse_file mbedtls_x509_crl_parse_file\n#define x509_crt mbedtls_x509_crt\n#define x509_crt_check_extended_key_usage mbedtls_x509_crt_check_extended_key_usage\n#define x509_crt_check_key_usage mbedtls_x509_crt_check_key_usage\n#define x509_crt_free mbedtls_x509_crt_free\n#define x509_crt_info mbedtls_x509_crt_info\n#define x509_crt_init mbedtls_x509_crt_init\n#define x509_crt_parse mbedtls_x509_crt_parse\n#define x509_crt_parse_der mbedtls_x509_crt_parse_der\n#define x509_crt_parse_file mbedtls_x509_crt_parse_file\n#define x509_crt_parse_path mbedtls_x509_crt_parse_path\n#define x509_crt_revoked mbedtls_x509_crt_is_revoked\n#define x509_crt_verify mbedtls_x509_crt_verify\n#define x509_csr mbedtls_x509_csr\n#define x509_csr_free mbedtls_x509_csr_free\n#define x509_csr_info mbedtls_x509_csr_info\n#define x509_csr_init mbedtls_x509_csr_init\n#define x509_csr_parse mbedtls_x509_csr_parse\n#define x509_csr_parse_der mbedtls_x509_csr_parse_der\n#define x509_csr_parse_file mbedtls_x509_csr_parse_file\n#define x509_dn_gets mbedtls_x509_dn_gets\n#define x509_get_alg mbedtls_x509_get_alg\n#define x509_get_alg_null mbedtls_x509_get_alg_null\n#define x509_get_ext mbedtls_x509_get_ext\n#define x509_get_name mbedtls_x509_get_name\n#define x509_get_rsassa_pss_params mbedtls_x509_get_rsassa_pss_params\n#define x509_get_serial mbedtls_x509_get_serial\n#define x509_get_sig mbedtls_x509_get_sig\n#define x509_get_sig_alg mbedtls_x509_get_sig_alg\n#define x509_get_time mbedtls_x509_get_time\n#define x509_key_size_helper mbedtls_x509_key_size_helper\n#define x509_name mbedtls_x509_name\n#define x509_self_test mbedtls_x509_self_test\n#define x509_sequence mbedtls_x509_sequence\n#define x509_serial_gets mbedtls_x509_serial_gets\n#define x509_set_extension mbedtls_x509_set_extension\n#define x509_sig_alg_gets mbedtls_x509_sig_alg_gets\n#define x509_string_to_names mbedtls_x509_string_to_names\n#define x509_time mbedtls_x509_time\n#define x509_time_expired mbedtls_x509_time_is_past\n#define x509_time_future mbedtls_x509_time_is_future\n#define x509_write_extensions mbedtls_x509_write_extensions\n#define x509_write_names mbedtls_x509_write_names\n#define x509_write_sig mbedtls_x509_write_sig\n#define x509write_cert mbedtls_x509write_cert\n#define x509write_crt_der mbedtls_x509write_crt_der\n#define x509write_crt_free mbedtls_x509write_crt_free\n#define x509write_crt_init mbedtls_x509write_crt_init\n#define x509write_crt_pem mbedtls_x509write_crt_pem\n#define x509write_crt_set_authority_key_identifier mbedtls_x509write_crt_set_authority_key_identifier\n#define x509write_crt_set_basic_constraints mbedtls_x509write_crt_set_basic_constraints\n#define x509write_crt_set_extension mbedtls_x509write_crt_set_extension\n#define x509write_crt_set_issuer_key mbedtls_x509write_crt_set_issuer_key\n#define x509write_crt_set_issuer_name mbedtls_x509write_crt_set_issuer_name\n#define x509write_crt_set_key_usage mbedtls_x509write_crt_set_key_usage\n#define x509write_crt_set_md_alg mbedtls_x509write_crt_set_md_alg\n#define x509write_crt_set_ns_cert_type mbedtls_x509write_crt_set_ns_cert_type\n#define x509write_crt_set_serial mbedtls_x509write_crt_set_serial\n#define x509write_crt_set_subject_key mbedtls_x509write_crt_set_subject_key\n#define x509write_crt_set_subject_key_identifier mbedtls_x509write_crt_set_subject_key_identifier\n#define x509write_crt_set_subject_name mbedtls_x509write_crt_set_subject_name\n#define x509write_crt_set_validity mbedtls_x509write_crt_set_validity\n#define x509write_crt_set_version mbedtls_x509write_crt_set_version\n#define x509write_csr mbedtls_x509write_csr\n#define x509write_csr_der mbedtls_x509write_csr_der\n#define x509write_csr_free mbedtls_x509write_csr_free\n#define x509write_csr_init mbedtls_x509write_csr_init\n#define x509write_csr_pem mbedtls_x509write_csr_pem\n#define x509write_csr_set_extension mbedtls_x509write_csr_set_extension\n#define x509write_csr_set_key mbedtls_x509write_csr_set_key\n#define x509write_csr_set_key_usage mbedtls_x509write_csr_set_key_usage\n#define x509write_csr_set_md_alg mbedtls_x509write_csr_set_md_alg\n#define x509write_csr_set_ns_cert_type mbedtls_x509write_csr_set_ns_cert_type\n#define x509write_csr_set_subject_name mbedtls_x509write_csr_set_subject_name\n#define xtea_context mbedtls_xtea_context\n#define xtea_crypt_cbc mbedtls_xtea_crypt_cbc\n#define xtea_crypt_ecb mbedtls_xtea_crypt_ecb\n#define xtea_free mbedtls_xtea_free\n#define xtea_init mbedtls_xtea_init\n#define xtea_self_test mbedtls_xtea_self_test\n#define xtea_setup mbedtls_xtea_setup\n\n#endif /* compat-1.3.h */\n#endif /* MBEDTLS_DEPRECATED_REMOVED */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/config.h",
    "content": "/**\n * \\file config.h\n *\n * \\brief Configuration options (set of defines)\n *\n *  This set of compile-time options may be used to enable\n *  or disable features selectively, and reduce the global\n *  memory footprint.\n */\n/*\n *  Copyright (C) 2006-2018, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_CONFIG_H\n#define MBEDTLS_CONFIG_H\n\n#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)\n#define _CRT_SECURE_NO_DEPRECATE 1\n#endif\n\n/**\n * \\name SECTION: System support\n *\n * This section sets system specific settings.\n * \\{\n */\n\n/**\n * \\def MBEDTLS_HAVE_ASM\n *\n * The compiler has support for asm().\n *\n * Requires support for asm() in compiler.\n *\n * Used in:\n *      library/aria.c\n *      library/timing.c\n *      include/mbedtls/bn_mul.h\n *\n * Required by:\n *      MBEDTLS_AESNI_C\n *      MBEDTLS_PADLOCK_C\n *\n * Comment to disable the use of assembly code.\n */\n#define MBEDTLS_HAVE_ASM\n\n/**\n * \\def MBEDTLS_NO_UDBL_DIVISION\n *\n * The platform lacks support for double-width integer division (64-bit\n * division on a 32-bit platform, 128-bit division on a 64-bit platform).\n *\n * Used in:\n *      include/mbedtls/bignum.h\n *      library/bignum.c\n *\n * The bignum code uses double-width division to speed up some operations.\n * Double-width division is often implemented in software that needs to\n * be linked with the program. The presence of a double-width integer\n * type is usually detected automatically through preprocessor macros,\n * but the automatic detection cannot know whether the code needs to\n * and can be linked with an implementation of division for that type.\n * By default division is assumed to be usable if the type is present.\n * Uncomment this option to prevent the use of double-width division.\n *\n * Note that division for the native integer type is always required.\n * Furthermore, a 64-bit type is always required even on a 32-bit\n * platform, but it need not support multiplication or division. In some\n * cases it is also desirable to disable some double-width operations. For\n * example, if double-width division is implemented in software, disabling\n * it can reduce code size in some embedded targets.\n */\n//#define MBEDTLS_NO_UDBL_DIVISION\n\n/**\n * \\def MBEDTLS_NO_64BIT_MULTIPLICATION\n *\n * The platform lacks support for 32x32 -> 64-bit multiplication.\n *\n * Used in:\n *      library/poly1305.c\n *\n * Some parts of the library may use multiplication of two unsigned 32-bit\n * operands with a 64-bit result in order to speed up computations. On some\n * platforms, this is not available in hardware and has to be implemented in\n * software, usually in a library provided by the toolchain.\n *\n * Sometimes it is not desirable to have to link to that library. This option\n * removes the dependency of that library on platforms that lack a hardware\n * 64-bit multiplier by embedding a software implementation in Mbed TLS.\n *\n * Note that depending on the compiler, this may decrease performance compared\n * to using the library function provided by the toolchain.\n */\n//#define MBEDTLS_NO_64BIT_MULTIPLICATION\n\n/**\n * \\def MBEDTLS_HAVE_SSE2\n *\n * CPU supports SSE2 instruction set.\n *\n * Uncomment if the CPU supports SSE2 (IA-32 specific).\n */\n//#define MBEDTLS_HAVE_SSE2\n\n/**\n * \\def MBEDTLS_HAVE_TIME\n *\n * System has time.h and time().\n * The time does not need to be correct, only time differences are used,\n * by contrast with MBEDTLS_HAVE_TIME_DATE\n *\n * Defining MBEDTLS_HAVE_TIME allows you to specify MBEDTLS_PLATFORM_TIME_ALT,\n * MBEDTLS_PLATFORM_TIME_MACRO, MBEDTLS_PLATFORM_TIME_TYPE_MACRO and\n * MBEDTLS_PLATFORM_STD_TIME.\n *\n * Comment if your system does not support time functions\n */\n#define MBEDTLS_HAVE_TIME\n\n/**\n * \\def MBEDTLS_HAVE_TIME_DATE\n *\n * System has time.h and time(), gmtime() and the clock is correct.\n * The time needs to be correct (not necesarily very accurate, but at least\n * the date should be correct). This is used to verify the validity period of\n * X.509 certificates.\n *\n * Comment if your system does not have a correct clock.\n */\n#define MBEDTLS_HAVE_TIME_DATE\n\n/**\n * \\def MBEDTLS_PLATFORM_MEMORY\n *\n * Enable the memory allocation layer.\n *\n * By default mbed TLS uses the system-provided calloc() and free().\n * This allows different allocators (self-implemented or provided) to be\n * provided to the platform abstraction layer.\n *\n * Enabling MBEDTLS_PLATFORM_MEMORY without the\n * MBEDTLS_PLATFORM_{FREE,CALLOC}_MACROs will provide\n * \"mbedtls_platform_set_calloc_free()\" allowing you to set an alternative calloc() and\n * free() function pointer at runtime.\n *\n * Enabling MBEDTLS_PLATFORM_MEMORY and specifying\n * MBEDTLS_PLATFORM_{CALLOC,FREE}_MACROs will allow you to specify the\n * alternate function at compile time.\n *\n * Requires: MBEDTLS_PLATFORM_C\n *\n * Enable this layer to allow use of alternative memory allocators.\n */\n//#define MBEDTLS_PLATFORM_MEMORY\n\n/**\n * \\def MBEDTLS_PLATFORM_NO_STD_FUNCTIONS\n *\n * Do not assign standard functions in the platform layer (e.g. calloc() to\n * MBEDTLS_PLATFORM_STD_CALLOC and printf() to MBEDTLS_PLATFORM_STD_PRINTF)\n *\n * This makes sure there are no linking errors on platforms that do not support\n * these functions. You will HAVE to provide alternatives, either at runtime\n * via the platform_set_xxx() functions or at compile time by setting\n * the MBEDTLS_PLATFORM_STD_XXX defines, or enabling a\n * MBEDTLS_PLATFORM_XXX_MACRO.\n *\n * Requires: MBEDTLS_PLATFORM_C\n *\n * Uncomment to prevent default assignment of standard functions in the\n * platform layer.\n */\n//#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS\n\n/**\n * \\def MBEDTLS_PLATFORM_EXIT_ALT\n *\n * MBEDTLS_PLATFORM_XXX_ALT: Uncomment a macro to let mbed TLS support the\n * function in the platform abstraction layer.\n *\n * Example: In case you uncomment MBEDTLS_PLATFORM_PRINTF_ALT, mbed TLS will\n * provide a function \"mbedtls_platform_set_printf()\" that allows you to set an\n * alternative printf function pointer.\n *\n * All these define require MBEDTLS_PLATFORM_C to be defined!\n *\n * \\note MBEDTLS_PLATFORM_SNPRINTF_ALT is required on Windows;\n * it will be enabled automatically by check_config.h\n *\n * \\warning MBEDTLS_PLATFORM_XXX_ALT cannot be defined at the same time as\n * MBEDTLS_PLATFORM_XXX_MACRO!\n *\n * Requires: MBEDTLS_PLATFORM_TIME_ALT requires MBEDTLS_HAVE_TIME\n *\n * Uncomment a macro to enable alternate implementation of specific base\n * platform function\n */\n//#define MBEDTLS_PLATFORM_EXIT_ALT\n//#define MBEDTLS_PLATFORM_TIME_ALT\n//#define MBEDTLS_PLATFORM_FPRINTF_ALT\n//#define MBEDTLS_PLATFORM_PRINTF_ALT\n//#define MBEDTLS_PLATFORM_SNPRINTF_ALT\n//#define MBEDTLS_PLATFORM_NV_SEED_ALT\n//#define MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT\n\n/**\n * \\def MBEDTLS_DEPRECATED_WARNING\n *\n * Mark deprecated functions so that they generate a warning if used.\n * Functions deprecated in one version will usually be removed in the next\n * version. You can enable this to help you prepare the transition to a new\n * major version by making sure your code is not using these functions.\n *\n * This only works with GCC and Clang. With other compilers, you may want to\n * use MBEDTLS_DEPRECATED_REMOVED\n *\n * Uncomment to get warnings on using deprecated functions.\n */\n//#define MBEDTLS_DEPRECATED_WARNING\n\n/**\n * \\def MBEDTLS_DEPRECATED_REMOVED\n *\n * Remove deprecated functions so that they generate an error if used.\n * Functions deprecated in one version will usually be removed in the next\n * version. You can enable this to help you prepare the transition to a new\n * major version by making sure your code is not using these functions.\n *\n * Uncomment to get errors on using deprecated functions.\n */\n//#define MBEDTLS_DEPRECATED_REMOVED\n\n/* \\} name SECTION: System support */\n\n/**\n * \\name SECTION: mbed TLS feature support\n *\n * This section sets support for features that are or are not needed\n * within the modules that are enabled.\n * \\{\n */\n\n/**\n * \\def MBEDTLS_TIMING_ALT\n *\n * Uncomment to provide your own alternate implementation for mbedtls_timing_hardclock(),\n * mbedtls_timing_get_timer(), mbedtls_set_alarm(), mbedtls_set/get_delay()\n *\n * Only works if you have MBEDTLS_TIMING_C enabled.\n *\n * You will need to provide a header \"timing_alt.h\" and an implementation at\n * compile time.\n */\n//#define MBEDTLS_TIMING_ALT\n\n/**\n * \\def MBEDTLS_AES_ALT\n *\n * MBEDTLS__MODULE_NAME__ALT: Uncomment a macro to let mbed TLS use your\n * alternate core implementation of a symmetric crypto, an arithmetic or hash\n * module (e.g. platform specific assembly optimized implementations). Keep\n * in mind that the function prototypes should remain the same.\n *\n * This replaces the whole module. If you only want to replace one of the\n * functions, use one of the MBEDTLS__FUNCTION_NAME__ALT flags.\n *\n * Example: In case you uncomment MBEDTLS_AES_ALT, mbed TLS will no longer\n * provide the \"struct mbedtls_aes_context\" definition and omit the base\n * function declarations and implementations. \"aes_alt.h\" will be included from\n * \"aes.h\" to include the new function definitions.\n *\n * Uncomment a macro to enable alternate implementation of the corresponding\n * module.\n *\n * \\warning   MD2, MD4, MD5, ARC4, DES and SHA-1 are considered weak and their\n *            use constitutes a security risk. If possible, we recommend\n *            avoiding dependencies on them, and considering stronger message\n *            digests and ciphers instead.\n *\n */\n//#define MBEDTLS_AES_ALT\n//#define MBEDTLS_ARC4_ALT\n//#define MBEDTLS_ARIA_ALT\n//#define MBEDTLS_BLOWFISH_ALT\n//#define MBEDTLS_CAMELLIA_ALT\n//#define MBEDTLS_CCM_ALT\n//#define MBEDTLS_CHACHA20_ALT\n//#define MBEDTLS_CHACHAPOLY_ALT\n//#define MBEDTLS_CMAC_ALT\n//#define MBEDTLS_DES_ALT\n//#define MBEDTLS_DHM_ALT\n//#define MBEDTLS_ECJPAKE_ALT\n//#define MBEDTLS_GCM_ALT\n//#define MBEDTLS_NIST_KW_ALT\n//#define MBEDTLS_MD2_ALT\n//#define MBEDTLS_MD4_ALT\n//#define MBEDTLS_MD5_ALT\n//#define MBEDTLS_POLY1305_ALT\n//#define MBEDTLS_RIPEMD160_ALT\n//#define MBEDTLS_RSA_ALT\n//#define MBEDTLS_SHA1_ALT\n//#define MBEDTLS_SHA256_ALT\n//#define MBEDTLS_SHA512_ALT\n//#define MBEDTLS_XTEA_ALT\n\n/*\n * When replacing the elliptic curve module, pleace consider, that it is\n * implemented with two .c files:\n *      - ecp.c\n *      - ecp_curves.c\n * You can replace them very much like all the other MBEDTLS__MODULE_NAME__ALT\n * macros as described above. The only difference is that you have to make sure\n * that you provide functionality for both .c files.\n */\n//#define MBEDTLS_ECP_ALT\n\n/**\n * \\def MBEDTLS_MD2_PROCESS_ALT\n *\n * MBEDTLS__FUNCTION_NAME__ALT: Uncomment a macro to let mbed TLS use you\n * alternate core implementation of symmetric crypto or hash function. Keep in\n * mind that function prototypes should remain the same.\n *\n * This replaces only one function. The header file from mbed TLS is still\n * used, in contrast to the MBEDTLS__MODULE_NAME__ALT flags.\n *\n * Example: In case you uncomment MBEDTLS_SHA256_PROCESS_ALT, mbed TLS will\n * no longer provide the mbedtls_sha1_process() function, but it will still provide\n * the other function (using your mbedtls_sha1_process() function) and the definition\n * of mbedtls_sha1_context, so your implementation of mbedtls_sha1_process must be compatible\n * with this definition.\n *\n * \\note Because of a signature change, the core AES encryption and decryption routines are\n *       currently named mbedtls_aes_internal_encrypt and mbedtls_aes_internal_decrypt,\n *       respectively. When setting up alternative implementations, these functions should\n *       be overriden, but the wrapper functions mbedtls_aes_decrypt and mbedtls_aes_encrypt\n *       must stay untouched.\n *\n * \\note If you use the AES_xxx_ALT macros, then is is recommended to also set\n *       MBEDTLS_AES_ROM_TABLES in order to help the linker garbage-collect the AES\n *       tables.\n *\n * Uncomment a macro to enable alternate implementation of the corresponding\n * function.\n *\n * \\warning   MD2, MD4, MD5, DES and SHA-1 are considered weak and their use\n *            constitutes a security risk. If possible, we recommend avoiding\n *            dependencies on them, and considering stronger message digests\n *            and ciphers instead.\n *\n */\n//#define MBEDTLS_MD2_PROCESS_ALT\n//#define MBEDTLS_MD4_PROCESS_ALT\n//#define MBEDTLS_MD5_PROCESS_ALT\n//#define MBEDTLS_RIPEMD160_PROCESS_ALT\n//#define MBEDTLS_SHA1_PROCESS_ALT\n//#define MBEDTLS_SHA256_PROCESS_ALT\n//#define MBEDTLS_SHA512_PROCESS_ALT\n//#define MBEDTLS_DES_SETKEY_ALT\n//#define MBEDTLS_DES_CRYPT_ECB_ALT\n//#define MBEDTLS_DES3_CRYPT_ECB_ALT\n//#define MBEDTLS_AES_SETKEY_ENC_ALT\n//#define MBEDTLS_AES_SETKEY_DEC_ALT\n//#define MBEDTLS_AES_ENCRYPT_ALT\n//#define MBEDTLS_AES_DECRYPT_ALT\n//#define MBEDTLS_ECDH_GEN_PUBLIC_ALT\n//#define MBEDTLS_ECDH_COMPUTE_SHARED_ALT\n//#define MBEDTLS_ECDSA_VERIFY_ALT\n//#define MBEDTLS_ECDSA_SIGN_ALT\n//#define MBEDTLS_ECDSA_GENKEY_ALT\n\n/**\n * \\def MBEDTLS_ECP_INTERNAL_ALT\n *\n * Expose a part of the internal interface of the Elliptic Curve Point module.\n *\n * MBEDTLS_ECP__FUNCTION_NAME__ALT: Uncomment a macro to let mbed TLS use your\n * alternative core implementation of elliptic curve arithmetic. Keep in mind\n * that function prototypes should remain the same.\n *\n * This partially replaces one function. The header file from mbed TLS is still\n * used, in contrast to the MBEDTLS_ECP_ALT flag. The original implementation\n * is still present and it is used for group structures not supported by the\n * alternative.\n *\n * Any of these options become available by defining MBEDTLS_ECP_INTERNAL_ALT\n * and implementing the following functions:\n *      unsigned char mbedtls_internal_ecp_grp_capable(\n *          const mbedtls_ecp_group *grp )\n *      int  mbedtls_internal_ecp_init( const mbedtls_ecp_group *grp )\n *      void mbedtls_internal_ecp_deinit( const mbedtls_ecp_group *grp )\n * The mbedtls_internal_ecp_grp_capable function should return 1 if the\n * replacement functions implement arithmetic for the given group and 0\n * otherwise.\n * The functions mbedtls_internal_ecp_init and mbedtls_internal_ecp_deinit are\n * called before and after each point operation and provide an opportunity to\n * implement optimized set up and tear down instructions.\n *\n * Example: In case you uncomment MBEDTLS_ECP_INTERNAL_ALT and\n * MBEDTLS_ECP_DOUBLE_JAC_ALT, mbed TLS will still provide the ecp_double_jac\n * function, but will use your mbedtls_internal_ecp_double_jac if the group is\n * supported (your mbedtls_internal_ecp_grp_capable function returns 1 when\n * receives it as an argument). If the group is not supported then the original\n * implementation is used. The other functions and the definition of\n * mbedtls_ecp_group and mbedtls_ecp_point will not change, so your\n * implementation of mbedtls_internal_ecp_double_jac and\n * mbedtls_internal_ecp_grp_capable must be compatible with this definition.\n *\n * Uncomment a macro to enable alternate implementation of the corresponding\n * function.\n */\n/* Required for all the functions in this section */\n//#define MBEDTLS_ECP_INTERNAL_ALT\n/* Support for Weierstrass curves with Jacobi representation */\n//#define MBEDTLS_ECP_RANDOMIZE_JAC_ALT\n//#define MBEDTLS_ECP_ADD_MIXED_ALT\n//#define MBEDTLS_ECP_DOUBLE_JAC_ALT\n//#define MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT\n//#define MBEDTLS_ECP_NORMALIZE_JAC_ALT\n/* Support for curves with Montgomery arithmetic */\n//#define MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT\n//#define MBEDTLS_ECP_RANDOMIZE_MXZ_ALT\n//#define MBEDTLS_ECP_NORMALIZE_MXZ_ALT\n\n/**\n * \\def MBEDTLS_TEST_NULL_ENTROPY\n *\n * Enables testing and use of mbed TLS without any configured entropy sources.\n * This permits use of the library on platforms before an entropy source has\n * been integrated (see for example the MBEDTLS_ENTROPY_HARDWARE_ALT or the\n * MBEDTLS_ENTROPY_NV_SEED switches).\n *\n * WARNING! This switch MUST be disabled in production builds, and is suitable\n * only for development.\n * Enabling the switch negates any security provided by the library.\n *\n * Requires MBEDTLS_ENTROPY_C, MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES\n *\n */\n//#define MBEDTLS_TEST_NULL_ENTROPY\n\n/**\n * \\def MBEDTLS_ENTROPY_HARDWARE_ALT\n *\n * Uncomment this macro to let mbed TLS use your own implementation of a\n * hardware entropy collector.\n *\n * Your function must be called \\c mbedtls_hardware_poll(), have the same\n * prototype as declared in entropy_poll.h, and accept NULL as first argument.\n *\n * Uncomment to use your own hardware entropy collector.\n */\n//#define MBEDTLS_ENTROPY_HARDWARE_ALT\n\n/**\n * \\def MBEDTLS_AES_ROM_TABLES\n *\n * Use precomputed AES tables stored in ROM.\n *\n * Uncomment this macro to use precomputed AES tables stored in ROM.\n * Comment this macro to generate AES tables in RAM at runtime.\n *\n * Tradeoff: Using precomputed ROM tables reduces RAM usage by ~8kb\n * (or ~2kb if \\c MBEDTLS_AES_FEWER_TABLES is used) and reduces the\n * initialization time before the first AES operation can be performed.\n * It comes at the cost of additional ~8kb ROM use (resp. ~2kb if \\c\n * MBEDTLS_AES_FEWER_TABLES below is used), and potentially degraded\n * performance if ROM access is slower than RAM access.\n *\n * This option is independent of \\c MBEDTLS_AES_FEWER_TABLES.\n *\n */\n//#define MBEDTLS_AES_ROM_TABLES\n\n/**\n * \\def MBEDTLS_AES_FEWER_TABLES\n *\n * Use less ROM/RAM for AES tables.\n *\n * Uncommenting this macro omits 75% of the AES tables from\n * ROM / RAM (depending on the value of \\c MBEDTLS_AES_ROM_TABLES)\n * by computing their values on the fly during operations\n * (the tables are entry-wise rotations of one another).\n *\n * Tradeoff: Uncommenting this reduces the RAM / ROM footprint\n * by ~6kb but at the cost of more arithmetic operations during\n * runtime. Specifically, one has to compare 4 accesses within\n * different tables to 4 accesses with additional arithmetic\n * operations within the same table. The performance gain/loss\n * depends on the system and memory details.\n *\n * This option is independent of \\c MBEDTLS_AES_ROM_TABLES.\n *\n */\n//#define MBEDTLS_AES_FEWER_TABLES\n\n/**\n * \\def MBEDTLS_CAMELLIA_SMALL_MEMORY\n *\n * Use less ROM for the Camellia implementation (saves about 768 bytes).\n *\n * Uncomment this macro to use less memory for Camellia.\n */\n//#define MBEDTLS_CAMELLIA_SMALL_MEMORY\n\n/**\n * \\def MBEDTLS_CIPHER_MODE_CBC\n *\n * Enable Cipher Block Chaining mode (CBC) for symmetric ciphers.\n */\n#define MBEDTLS_CIPHER_MODE_CBC\n\n/**\n * \\def MBEDTLS_CIPHER_MODE_CFB\n *\n * Enable Cipher Feedback mode (CFB) for symmetric ciphers.\n */\n#define MBEDTLS_CIPHER_MODE_CFB\n\n/**\n * \\def MBEDTLS_CIPHER_MODE_CTR\n *\n * Enable Counter Block Cipher mode (CTR) for symmetric ciphers.\n */\n#define MBEDTLS_CIPHER_MODE_CTR\n\n/**\n * \\def MBEDTLS_CIPHER_MODE_OFB\n *\n * Enable Output Feedback mode (OFB) for symmetric ciphers.\n */\n#define MBEDTLS_CIPHER_MODE_OFB\n\n/**\n * \\def MBEDTLS_CIPHER_MODE_XTS\n *\n * Enable Xor-encrypt-xor with ciphertext stealing mode (XTS) for AES.\n */\n#define MBEDTLS_CIPHER_MODE_XTS\n\n/**\n * \\def MBEDTLS_CIPHER_NULL_CIPHER\n *\n * Enable NULL cipher.\n * Warning: Only do so when you know what you are doing. This allows for\n * encryption or channels without any security!\n *\n * Requires MBEDTLS_ENABLE_WEAK_CIPHERSUITES as well to enable\n * the following ciphersuites:\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA\n *      MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA\n *      MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA384\n *      MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA256\n *      MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA\n *      MBEDTLS_TLS_RSA_WITH_NULL_SHA256\n *      MBEDTLS_TLS_RSA_WITH_NULL_SHA\n *      MBEDTLS_TLS_RSA_WITH_NULL_MD5\n *      MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA384\n *      MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA256\n *      MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA\n *      MBEDTLS_TLS_PSK_WITH_NULL_SHA384\n *      MBEDTLS_TLS_PSK_WITH_NULL_SHA256\n *      MBEDTLS_TLS_PSK_WITH_NULL_SHA\n *\n * Uncomment this macro to enable the NULL cipher and ciphersuites\n */\n//#define MBEDTLS_CIPHER_NULL_CIPHER\n\n/**\n * \\def MBEDTLS_CIPHER_PADDING_PKCS7\n *\n * MBEDTLS_CIPHER_PADDING_XXX: Uncomment or comment macros to add support for\n * specific padding modes in the cipher layer with cipher modes that support\n * padding (e.g. CBC)\n *\n * If you disable all padding modes, only full blocks can be used with CBC.\n *\n * Enable padding modes in the cipher layer.\n */\n#define MBEDTLS_CIPHER_PADDING_PKCS7\n#define MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS\n#define MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN\n#define MBEDTLS_CIPHER_PADDING_ZEROS\n\n/**\n * \\def MBEDTLS_ENABLE_WEAK_CIPHERSUITES\n *\n * Enable weak ciphersuites in SSL / TLS.\n * Warning: Only do so when you know what you are doing. This allows for\n * channels with virtually no security at all!\n *\n * This enables the following ciphersuites:\n *      MBEDTLS_TLS_RSA_WITH_DES_CBC_SHA\n *      MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA\n *\n * Uncomment this macro to enable weak ciphersuites\n *\n * \\warning   DES is considered a weak cipher and its use constitutes a\n *            security risk. We recommend considering stronger ciphers instead.\n */\n//#define MBEDTLS_ENABLE_WEAK_CIPHERSUITES\n\n/**\n * \\def MBEDTLS_REMOVE_ARC4_CIPHERSUITES\n *\n * Remove RC4 ciphersuites by default in SSL / TLS.\n * This flag removes the ciphersuites based on RC4 from the default list as\n * returned by mbedtls_ssl_list_ciphersuites(). However, it is still possible to\n * enable (some of) them with mbedtls_ssl_conf_ciphersuites() by including them\n * explicitly.\n *\n * Uncomment this macro to remove RC4 ciphersuites by default.\n */\n#define MBEDTLS_REMOVE_ARC4_CIPHERSUITES\n\n/**\n * \\def MBEDTLS_ECP_DP_SECP192R1_ENABLED\n *\n * MBEDTLS_ECP_XXXX_ENABLED: Enables specific curves within the Elliptic Curve\n * module.  By default all supported curves are enabled.\n *\n * Comment macros to disable the curve and functions for it\n */\n#define MBEDTLS_ECP_DP_SECP192R1_ENABLED\n#define MBEDTLS_ECP_DP_SECP224R1_ENABLED\n#define MBEDTLS_ECP_DP_SECP256R1_ENABLED\n#define MBEDTLS_ECP_DP_SECP384R1_ENABLED\n#define MBEDTLS_ECP_DP_SECP521R1_ENABLED\n#define MBEDTLS_ECP_DP_SECP192K1_ENABLED\n#define MBEDTLS_ECP_DP_SECP224K1_ENABLED\n#define MBEDTLS_ECP_DP_SECP256K1_ENABLED\n#define MBEDTLS_ECP_DP_BP256R1_ENABLED\n#define MBEDTLS_ECP_DP_BP384R1_ENABLED\n#define MBEDTLS_ECP_DP_BP512R1_ENABLED\n#define MBEDTLS_ECP_DP_CURVE25519_ENABLED\n#define MBEDTLS_ECP_DP_CURVE448_ENABLED\n\n/**\n * \\def MBEDTLS_ECP_NIST_OPTIM\n *\n * Enable specific 'modulo p' routines for each NIST prime.\n * Depending on the prime and architecture, makes operations 4 to 8 times\n * faster on the corresponding curve.\n *\n * Comment this macro to disable NIST curves optimisation.\n */\n#define MBEDTLS_ECP_NIST_OPTIM\n\n/**\n * \\def MBEDTLS_ECDSA_DETERMINISTIC\n *\n * Enable deterministic ECDSA (RFC 6979).\n * Standard ECDSA is \"fragile\" in the sense that lack of entropy when signing\n * may result in a compromise of the long-term signing key. This is avoided by\n * the deterministic variant.\n *\n * Requires: MBEDTLS_HMAC_DRBG_C\n *\n * Comment this macro to disable deterministic ECDSA.\n */\n#define MBEDTLS_ECDSA_DETERMINISTIC\n\n/**\n * \\def MBEDTLS_KEY_EXCHANGE_PSK_ENABLED\n *\n * Enable the PSK based ciphersuite modes in SSL / TLS.\n *\n * This enables the following ciphersuites (if other requisites are\n * enabled as well):\n *      MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384\n *      MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384\n *      MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384\n *      MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_PSK_WITH_RC4_128_SHA\n */\n#define MBEDTLS_KEY_EXCHANGE_PSK_ENABLED\n\n/**\n * \\def MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED\n *\n * Enable the DHE-PSK based ciphersuite modes in SSL / TLS.\n *\n * Requires: MBEDTLS_DHM_C\n *\n * This enables the following ciphersuites (if other requisites are\n * enabled as well):\n *      MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384\n *      MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384\n *      MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384\n *      MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA\n *\n * \\warning    Using DHE constitutes a security risk as it\n *             is not possible to validate custom DH parameters.\n *             If possible, it is recommended users should consider\n *             preferring other methods of key exchange.\n *             See dhm.h for more details.\n *\n */\n#define MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED\n\n/**\n * \\def MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED\n *\n * Enable the ECDHE-PSK based ciphersuite modes in SSL / TLS.\n *\n * Requires: MBEDTLS_ECDH_C\n *\n * This enables the following ciphersuites (if other requisites are\n * enabled as well):\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA\n */\n#define MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED\n\n/**\n * \\def MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED\n *\n * Enable the RSA-PSK based ciphersuite modes in SSL / TLS.\n *\n * Requires: MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15,\n *           MBEDTLS_X509_CRT_PARSE_C\n *\n * This enables the following ciphersuites (if other requisites are\n * enabled as well):\n *      MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384\n *      MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384\n *      MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384\n *      MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA\n */\n#define MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED\n\n/**\n * \\def MBEDTLS_KEY_EXCHANGE_RSA_ENABLED\n *\n * Enable the RSA-only based ciphersuite modes in SSL / TLS.\n *\n * Requires: MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15,\n *           MBEDTLS_X509_CRT_PARSE_C\n *\n * This enables the following ciphersuites (if other requisites are\n * enabled as well):\n *      MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256\n *      MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384\n *      MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256\n *      MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA\n *      MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA\n *      MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_RSA_WITH_RC4_128_SHA\n *      MBEDTLS_TLS_RSA_WITH_RC4_128_MD5\n */\n#define MBEDTLS_KEY_EXCHANGE_RSA_ENABLED\n\n/**\n * \\def MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED\n *\n * Enable the DHE-RSA based ciphersuite modes in SSL / TLS.\n *\n * Requires: MBEDTLS_DHM_C, MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15,\n *           MBEDTLS_X509_CRT_PARSE_C\n *\n * This enables the following ciphersuites (if other requisites are\n * enabled as well):\n *      MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256\n *      MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384\n *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256\n *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA\n *      MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA\n *      MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA\n *\n * \\warning    Using DHE constitutes a security risk as it\n *             is not possible to validate custom DH parameters.\n *             If possible, it is recommended users should consider\n *             preferring other methods of key exchange.\n *             See dhm.h for more details.\n *\n */\n#define MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED\n\n/**\n * \\def MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED\n *\n * Enable the ECDHE-RSA based ciphersuite modes in SSL / TLS.\n *\n * Requires: MBEDTLS_ECDH_C, MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15,\n *           MBEDTLS_X509_CRT_PARSE_C\n *\n * This enables the following ciphersuites (if other requisites are\n * enabled as well):\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA\n */\n#define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED\n\n/**\n * \\def MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED\n *\n * Enable the ECDHE-ECDSA based ciphersuite modes in SSL / TLS.\n *\n * Requires: MBEDTLS_ECDH_C, MBEDTLS_ECDSA_C, MBEDTLS_X509_CRT_PARSE_C,\n *\n * This enables the following ciphersuites (if other requisites are\n * enabled as well):\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA\n */\n#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED\n\n/**\n * \\def MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED\n *\n * Enable the ECDH-ECDSA based ciphersuite modes in SSL / TLS.\n *\n * Requires: MBEDTLS_ECDH_C, MBEDTLS_X509_CRT_PARSE_C\n *\n * This enables the following ciphersuites (if other requisites are\n * enabled as well):\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384\n */\n#define MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED\n\n/**\n * \\def MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED\n *\n * Enable the ECDH-RSA based ciphersuite modes in SSL / TLS.\n *\n * Requires: MBEDTLS_ECDH_C, MBEDTLS_X509_CRT_PARSE_C\n *\n * This enables the following ciphersuites (if other requisites are\n * enabled as well):\n *      MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA\n *      MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384\n */\n#define MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED\n\n/**\n * \\def MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED\n *\n * Enable the ECJPAKE based ciphersuite modes in SSL / TLS.\n *\n * \\warning This is currently experimental. EC J-PAKE support is based on the\n * Thread v1.0.0 specification; incompatible changes to the specification\n * might still happen. For this reason, this is disabled by default.\n *\n * Requires: MBEDTLS_ECJPAKE_C\n *           MBEDTLS_SHA256_C\n *           MBEDTLS_ECP_DP_SECP256R1_ENABLED\n *\n * This enables the following ciphersuites (if other requisites are\n * enabled as well):\n *      MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8\n */\n//#define MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED\n\n/**\n * \\def MBEDTLS_PK_PARSE_EC_EXTENDED\n *\n * Enhance support for reading EC keys using variants of SEC1 not allowed by\n * RFC 5915 and RFC 5480.\n *\n * Currently this means parsing the SpecifiedECDomain choice of EC\n * parameters (only known groups are supported, not arbitrary domains, to\n * avoid validation issues).\n *\n * Disable if you only need to support RFC 5915 + 5480 key formats.\n */\n#define MBEDTLS_PK_PARSE_EC_EXTENDED\n\n/**\n * \\def MBEDTLS_ERROR_STRERROR_DUMMY\n *\n * Enable a dummy error function to make use of mbedtls_strerror() in\n * third party libraries easier when MBEDTLS_ERROR_C is disabled\n * (no effect when MBEDTLS_ERROR_C is enabled).\n *\n * You can safely disable this if MBEDTLS_ERROR_C is enabled, or if you're\n * not using mbedtls_strerror() or error_strerror() in your application.\n *\n * Disable if you run into name conflicts and want to really remove the\n * mbedtls_strerror()\n */\n#define MBEDTLS_ERROR_STRERROR_DUMMY\n\n/**\n * \\def MBEDTLS_GENPRIME\n *\n * Enable the prime-number generation code.\n *\n * Requires: MBEDTLS_BIGNUM_C\n */\n#define MBEDTLS_GENPRIME\n\n/**\n * \\def MBEDTLS_FS_IO\n *\n * Enable functions that use the filesystem.\n */\n#define MBEDTLS_FS_IO\n\n/**\n * \\def MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES\n *\n * Do not add default entropy sources. These are the platform specific,\n * mbedtls_timing_hardclock and HAVEGE based poll functions.\n *\n * This is useful to have more control over the added entropy sources in an\n * application.\n *\n * Uncomment this macro to prevent loading of default entropy functions.\n */\n//#define MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES\n\n/**\n * \\def MBEDTLS_NO_PLATFORM_ENTROPY\n *\n * Do not use built-in platform entropy functions.\n * This is useful if your platform does not support\n * standards like the /dev/urandom or Windows CryptoAPI.\n *\n * Uncomment this macro to disable the built-in platform entropy functions.\n */\n//#define MBEDTLS_NO_PLATFORM_ENTROPY\n\n/**\n * \\def MBEDTLS_ENTROPY_FORCE_SHA256\n *\n * Force the entropy accumulator to use a SHA-256 accumulator instead of the\n * default SHA-512 based one (if both are available).\n *\n * Requires: MBEDTLS_SHA256_C\n *\n * On 32-bit systems SHA-256 can be much faster than SHA-512. Use this option\n * if you have performance concerns.\n *\n * This option is only useful if both MBEDTLS_SHA256_C and\n * MBEDTLS_SHA512_C are defined. Otherwise the available hash module is used.\n */\n//#define MBEDTLS_ENTROPY_FORCE_SHA256\n\n/**\n * \\def MBEDTLS_ENTROPY_NV_SEED\n *\n * Enable the non-volatile (NV) seed file-based entropy source.\n * (Also enables the NV seed read/write functions in the platform layer)\n *\n * This is crucial (if not required) on systems that do not have a\n * cryptographic entropy source (in hardware or kernel) available.\n *\n * Requires: MBEDTLS_ENTROPY_C, MBEDTLS_PLATFORM_C\n *\n * \\note The read/write functions that are used by the entropy source are\n *       determined in the platform layer, and can be modified at runtime and/or\n *       compile-time depending on the flags (MBEDTLS_PLATFORM_NV_SEED_*) used.\n *\n * \\note If you use the default implementation functions that read a seedfile\n *       with regular fopen(), please make sure you make a seedfile with the\n *       proper name (defined in MBEDTLS_PLATFORM_STD_NV_SEED_FILE) and at\n *       least MBEDTLS_ENTROPY_BLOCK_SIZE bytes in size that can be read from\n *       and written to or you will get an entropy source error! The default\n *       implementation will only use the first MBEDTLS_ENTROPY_BLOCK_SIZE\n *       bytes from the file.\n *\n * \\note The entropy collector will write to the seed file before entropy is\n *       given to an external source, to update it.\n */\n//#define MBEDTLS_ENTROPY_NV_SEED\n\n/**\n * \\def MBEDTLS_MEMORY_DEBUG\n *\n * Enable debugging of buffer allocator memory issues. Automatically prints\n * (to stderr) all (fatal) messages on memory allocation issues. Enables\n * function for 'debug output' of allocated memory.\n *\n * Requires: MBEDTLS_MEMORY_BUFFER_ALLOC_C\n *\n * Uncomment this macro to let the buffer allocator print out error messages.\n */\n//#define MBEDTLS_MEMORY_DEBUG\n\n/**\n * \\def MBEDTLS_MEMORY_BACKTRACE\n *\n * Include backtrace information with each allocated block.\n *\n * Requires: MBEDTLS_MEMORY_BUFFER_ALLOC_C\n *           GLIBC-compatible backtrace() an backtrace_symbols() support\n *\n * Uncomment this macro to include backtrace information\n */\n//#define MBEDTLS_MEMORY_BACKTRACE\n\n/**\n * \\def MBEDTLS_PK_RSA_ALT_SUPPORT\n *\n * Support external private RSA keys (eg from a HSM) in the PK layer.\n *\n * Comment this macro to disable support for external private RSA keys.\n */\n#define MBEDTLS_PK_RSA_ALT_SUPPORT\n\n/**\n * \\def MBEDTLS_PKCS1_V15\n *\n * Enable support for PKCS#1 v1.5 encoding.\n *\n * Requires: MBEDTLS_RSA_C\n *\n * This enables support for PKCS#1 v1.5 operations.\n */\n#define MBEDTLS_PKCS1_V15\n\n/**\n * \\def MBEDTLS_PKCS1_V21\n *\n * Enable support for PKCS#1 v2.1 encoding.\n *\n * Requires: MBEDTLS_MD_C, MBEDTLS_RSA_C\n *\n * This enables support for RSAES-OAEP and RSASSA-PSS operations.\n */\n#define MBEDTLS_PKCS1_V21\n\n/**\n * \\def MBEDTLS_RSA_NO_CRT\n *\n * Do not use the Chinese Remainder Theorem\n * for the RSA private operation.\n *\n * Uncomment this macro to disable the use of CRT in RSA.\n *\n */\n//#define MBEDTLS_RSA_NO_CRT\n\n/**\n * \\def MBEDTLS_SELF_TEST\n *\n * Enable the checkup functions (*_self_test).\n */\n#define MBEDTLS_SELF_TEST\n\n/**\n * \\def MBEDTLS_SHA256_SMALLER\n *\n * Enable an implementation of SHA-256 that has lower ROM footprint but also\n * lower performance.\n *\n * The default implementation is meant to be a reasonnable compromise between\n * performance and size. This version optimizes more aggressively for size at\n * the expense of performance. Eg on Cortex-M4 it reduces the size of\n * mbedtls_sha256_process() from ~2KB to ~0.5KB for a performance hit of about\n * 30%.\n *\n * Uncomment to enable the smaller implementation of SHA256.\n */\n//#define MBEDTLS_SHA256_SMALLER\n\n/**\n * \\def MBEDTLS_SSL_ALL_ALERT_MESSAGES\n *\n * Enable sending of alert messages in case of encountered errors as per RFC.\n * If you choose not to send the alert messages, mbed TLS can still communicate\n * with other servers, only debugging of failures is harder.\n *\n * The advantage of not sending alert messages, is that no information is given\n * about reasons for failures thus preventing adversaries of gaining intel.\n *\n * Enable sending of all alert messages\n */\n#define MBEDTLS_SSL_ALL_ALERT_MESSAGES\n\n/**\n * \\def MBEDTLS_SSL_ASYNC_PRIVATE\n *\n * Enable asynchronous external private key operations in SSL. This allows\n * you to configure an SSL connection to call an external cryptographic\n * module to perform private key operations instead of performing the\n * operation inside the library.\n *\n */\n//#define MBEDTLS_SSL_ASYNC_PRIVATE\n\n/**\n * \\def MBEDTLS_SSL_DEBUG_ALL\n *\n * Enable the debug messages in SSL module for all issues.\n * Debug messages have been disabled in some places to prevent timing\n * attacks due to (unbalanced) debugging function calls.\n *\n * If you need all error reporting you should enable this during debugging,\n * but remove this for production servers that should log as well.\n *\n * Uncomment this macro to report all debug messages on errors introducing\n * a timing side-channel.\n *\n */\n//#define MBEDTLS_SSL_DEBUG_ALL\n\n/** \\def MBEDTLS_SSL_ENCRYPT_THEN_MAC\n *\n * Enable support for Encrypt-then-MAC, RFC 7366.\n *\n * This allows peers that both support it to use a more robust protection for\n * ciphersuites using CBC, providing deep resistance against timing attacks\n * on the padding or underlying cipher.\n *\n * This only affects CBC ciphersuites, and is useless if none is defined.\n *\n * Requires: MBEDTLS_SSL_PROTO_TLS1    or\n *           MBEDTLS_SSL_PROTO_TLS1_1  or\n *           MBEDTLS_SSL_PROTO_TLS1_2\n *\n * Comment this macro to disable support for Encrypt-then-MAC\n */\n#define MBEDTLS_SSL_ENCRYPT_THEN_MAC\n\n/** \\def MBEDTLS_SSL_EXTENDED_MASTER_SECRET\n *\n * Enable support for Extended Master Secret, aka Session Hash\n * (draft-ietf-tls-session-hash-02).\n *\n * This was introduced as \"the proper fix\" to the Triple Handshake familiy of\n * attacks, but it is recommended to always use it (even if you disable\n * renegotiation), since it actually fixes a more fundamental issue in the\n * original SSL/TLS design, and has implications beyond Triple Handshake.\n *\n * Requires: MBEDTLS_SSL_PROTO_TLS1    or\n *           MBEDTLS_SSL_PROTO_TLS1_1  or\n *           MBEDTLS_SSL_PROTO_TLS1_2\n *\n * Comment this macro to disable support for Extended Master Secret.\n */\n#define MBEDTLS_SSL_EXTENDED_MASTER_SECRET\n\n/**\n * \\def MBEDTLS_SSL_FALLBACK_SCSV\n *\n * Enable support for FALLBACK_SCSV (draft-ietf-tls-downgrade-scsv-00).\n *\n * For servers, it is recommended to always enable this, unless you support\n * only one version of TLS, or know for sure that none of your clients\n * implements a fallback strategy.\n *\n * For clients, you only need this if you're using a fallback strategy, which\n * is not recommended in the first place, unless you absolutely need it to\n * interoperate with buggy (version-intolerant) servers.\n *\n * Comment this macro to disable support for FALLBACK_SCSV\n */\n#define MBEDTLS_SSL_FALLBACK_SCSV\n\n/**\n * \\def MBEDTLS_SSL_HW_RECORD_ACCEL\n *\n * Enable hooking functions in SSL module for hardware acceleration of\n * individual records.\n *\n * Uncomment this macro to enable hooking functions.\n */\n//#define MBEDTLS_SSL_HW_RECORD_ACCEL\n\n/**\n * \\def MBEDTLS_SSL_CBC_RECORD_SPLITTING\n *\n * Enable 1/n-1 record splitting for CBC mode in SSLv3 and TLS 1.0.\n *\n * This is a countermeasure to the BEAST attack, which also minimizes the risk\n * of interoperability issues compared to sending 0-length records.\n *\n * Comment this macro to disable 1/n-1 record splitting.\n */\n#define MBEDTLS_SSL_CBC_RECORD_SPLITTING\n\n/**\n * \\def MBEDTLS_SSL_RENEGOTIATION\n *\n * Disable support for TLS renegotiation.\n *\n * The two main uses of renegotiation are (1) refresh keys on long-lived\n * connections and (2) client authentication after the initial handshake.\n * If you don't need renegotiation, it's probably better to disable it, since\n * it has been associated with security issues in the past and is easy to\n * misuse/misunderstand.\n *\n * Comment this to disable support for renegotiation.\n *\n * \\note   Even if this option is disabled, both client and server are aware\n *         of the Renegotiation Indication Extension (RFC 5746) used to\n *         prevent the SSL renegotiation attack (see RFC 5746 Sect. 1).\n *         (See \\c mbedtls_ssl_conf_legacy_renegotiation for the\n *          configuration of this extension).\n *\n */\n#define MBEDTLS_SSL_RENEGOTIATION\n\n/**\n * \\def MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO\n *\n * Enable support for receiving and parsing SSLv2 Client Hello messages for the\n * SSL Server module (MBEDTLS_SSL_SRV_C).\n *\n * Uncomment this macro to enable support for SSLv2 Client Hello messages.\n */\n//#define MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO\n\n/**\n * \\def MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE\n *\n * Pick the ciphersuite according to the client's preferences rather than ours\n * in the SSL Server module (MBEDTLS_SSL_SRV_C).\n *\n * Uncomment this macro to respect client's ciphersuite order\n */\n//#define MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE\n\n/**\n * \\def MBEDTLS_SSL_MAX_FRAGMENT_LENGTH\n *\n * Enable support for RFC 6066 max_fragment_length extension in SSL.\n *\n * Comment this macro to disable support for the max_fragment_length extension\n */\n#define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH\n\n/**\n * \\def MBEDTLS_SSL_PROTO_SSL3\n *\n * Enable support for SSL 3.0.\n *\n * Requires: MBEDTLS_MD5_C\n *           MBEDTLS_SHA1_C\n *\n * Comment this macro to disable support for SSL 3.0\n */\n//#define MBEDTLS_SSL_PROTO_SSL3\n\n/**\n * \\def MBEDTLS_SSL_PROTO_TLS1\n *\n * Enable support for TLS 1.0.\n *\n * Requires: MBEDTLS_MD5_C\n *           MBEDTLS_SHA1_C\n *\n * Comment this macro to disable support for TLS 1.0\n */\n#define MBEDTLS_SSL_PROTO_TLS1\n\n/**\n * \\def MBEDTLS_SSL_PROTO_TLS1_1\n *\n * Enable support for TLS 1.1 (and DTLS 1.0 if DTLS is enabled).\n *\n * Requires: MBEDTLS_MD5_C\n *           MBEDTLS_SHA1_C\n *\n * Comment this macro to disable support for TLS 1.1 / DTLS 1.0\n */\n#define MBEDTLS_SSL_PROTO_TLS1_1\n\n/**\n * \\def MBEDTLS_SSL_PROTO_TLS1_2\n *\n * Enable support for TLS 1.2 (and DTLS 1.2 if DTLS is enabled).\n *\n * Requires: MBEDTLS_SHA1_C or MBEDTLS_SHA256_C or MBEDTLS_SHA512_C\n *           (Depends on ciphersuites)\n *\n * Comment this macro to disable support for TLS 1.2 / DTLS 1.2\n */\n#define MBEDTLS_SSL_PROTO_TLS1_2\n\n/**\n * \\def MBEDTLS_SSL_PROTO_DTLS\n *\n * Enable support for DTLS (all available versions).\n *\n * Enable this and MBEDTLS_SSL_PROTO_TLS1_1 to enable DTLS 1.0,\n * and/or this and MBEDTLS_SSL_PROTO_TLS1_2 to enable DTLS 1.2.\n *\n * Requires: MBEDTLS_SSL_PROTO_TLS1_1\n *        or MBEDTLS_SSL_PROTO_TLS1_2\n *\n * Comment this macro to disable support for DTLS\n */\n#define MBEDTLS_SSL_PROTO_DTLS\n\n/**\n * \\def MBEDTLS_SSL_ALPN\n *\n * Enable support for RFC 7301 Application Layer Protocol Negotiation.\n *\n * Comment this macro to disable support for ALPN.\n */\n#define MBEDTLS_SSL_ALPN\n\n/**\n * \\def MBEDTLS_SSL_DTLS_ANTI_REPLAY\n *\n * Enable support for the anti-replay mechanism in DTLS.\n *\n * Requires: MBEDTLS_SSL_TLS_C\n *           MBEDTLS_SSL_PROTO_DTLS\n *\n * \\warning Disabling this is often a security risk!\n * See mbedtls_ssl_conf_dtls_anti_replay() for details.\n *\n * Comment this to disable anti-replay in DTLS.\n */\n#define MBEDTLS_SSL_DTLS_ANTI_REPLAY\n\n/**\n * \\def MBEDTLS_SSL_DTLS_HELLO_VERIFY\n *\n * Enable support for HelloVerifyRequest on DTLS servers.\n *\n * This feature is highly recommended to prevent DTLS servers being used as\n * amplifiers in DoS attacks against other hosts. It should always be enabled\n * unless you know for sure amplification cannot be a problem in the\n * environment in which your server operates.\n *\n * \\warning Disabling this can ba a security risk! (see above)\n *\n * Requires: MBEDTLS_SSL_PROTO_DTLS\n *\n * Comment this to disable support for HelloVerifyRequest.\n */\n#define MBEDTLS_SSL_DTLS_HELLO_VERIFY\n\n/**\n * \\def MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE\n *\n * Enable server-side support for clients that reconnect from the same port.\n *\n * Some clients unexpectedly close the connection and try to reconnect using the\n * same source port. This needs special support from the server to handle the\n * new connection securely, as described in section 4.2.8 of RFC 6347. This\n * flag enables that support.\n *\n * Requires: MBEDTLS_SSL_DTLS_HELLO_VERIFY\n *\n * Comment this to disable support for clients reusing the source port.\n */\n#define MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE\n\n/**\n * \\def MBEDTLS_SSL_DTLS_BADMAC_LIMIT\n *\n * Enable support for a limit of records with bad MAC.\n *\n * See mbedtls_ssl_conf_dtls_badmac_limit().\n *\n * Requires: MBEDTLS_SSL_PROTO_DTLS\n */\n#define MBEDTLS_SSL_DTLS_BADMAC_LIMIT\n\n/**\n * \\def MBEDTLS_SSL_SESSION_TICKETS\n *\n * Enable support for RFC 5077 session tickets in SSL.\n * Client-side, provides full support for session tickets (maintainance of a\n * session store remains the responsibility of the application, though).\n * Server-side, you also need to provide callbacks for writing and parsing\n * tickets, including authenticated encryption and key management. Example\n * callbacks are provided by MBEDTLS_SSL_TICKET_C.\n *\n * Comment this macro to disable support for SSL session tickets\n */\n#define MBEDTLS_SSL_SESSION_TICKETS\n\n/**\n * \\def MBEDTLS_SSL_EXPORT_KEYS\n *\n * Enable support for exporting key block and master secret.\n * This is required for certain users of TLS, e.g. EAP-TLS.\n *\n * Comment this macro to disable support for key export\n */\n#define MBEDTLS_SSL_EXPORT_KEYS\n\n/**\n * \\def MBEDTLS_SSL_SERVER_NAME_INDICATION\n *\n * Enable support for RFC 6066 server name indication (SNI) in SSL.\n *\n * Requires: MBEDTLS_X509_CRT_PARSE_C\n *\n * Comment this macro to disable support for server name indication in SSL\n */\n#define MBEDTLS_SSL_SERVER_NAME_INDICATION\n\n/**\n * \\def MBEDTLS_SSL_TRUNCATED_HMAC\n *\n * Enable support for RFC 6066 truncated HMAC in SSL.\n *\n * Comment this macro to disable support for truncated HMAC in SSL\n */\n#define MBEDTLS_SSL_TRUNCATED_HMAC\n\n/**\n * \\def MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT\n *\n * Fallback to old (pre-2.7), non-conforming implementation of the truncated\n * HMAC extension which also truncates the HMAC key. Note that this option is\n * only meant for a transitory upgrade period and is likely to be removed in\n * a future version of the library.\n *\n * \\warning The old implementation is non-compliant and has a security weakness\n *          (2^80 brute force attack on the HMAC key used for a single,\n *          uninterrupted connection). This should only be enabled temporarily\n *          when (1) the use of truncated HMAC is essential in order to save\n *          bandwidth, and (2) the peer is an Mbed TLS stack that doesn't use\n *          the fixed implementation yet (pre-2.7).\n *\n * \\deprecated This option is deprecated and will likely be removed in a\n *             future version of Mbed TLS.\n *\n * Uncomment to fallback to old, non-compliant truncated HMAC implementation.\n *\n * Requires: MBEDTLS_SSL_TRUNCATED_HMAC\n */\n//#define MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT\n\n/**\n * \\def MBEDTLS_THREADING_ALT\n *\n * Provide your own alternate threading implementation.\n *\n * Requires: MBEDTLS_THREADING_C\n *\n * Uncomment this to allow your own alternate threading implementation.\n */\n//#define MBEDTLS_THREADING_ALT\n\n/**\n * \\def MBEDTLS_THREADING_PTHREAD\n *\n * Enable the pthread wrapper layer for the threading layer.\n *\n * Requires: MBEDTLS_THREADING_C\n *\n * Uncomment this to enable pthread mutexes.\n */\n//#define MBEDTLS_THREADING_PTHREAD\n\n/**\n * \\def MBEDTLS_VERSION_FEATURES\n *\n * Allow run-time checking of compile-time enabled features. Thus allowing users\n * to check at run-time if the library is for instance compiled with threading\n * support via mbedtls_version_check_feature().\n *\n * Requires: MBEDTLS_VERSION_C\n *\n * Comment this to disable run-time checking and save ROM space\n */\n#define MBEDTLS_VERSION_FEATURES\n\n/**\n * \\def MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3\n *\n * If set, the X509 parser will not break-off when parsing an X509 certificate\n * and encountering an extension in a v1 or v2 certificate.\n *\n * Uncomment to prevent an error.\n */\n//#define MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3\n\n/**\n * \\def MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION\n *\n * If set, the X509 parser will not break-off when parsing an X509 certificate\n * and encountering an unknown critical extension.\n *\n * \\warning Depending on your PKI use, enabling this can be a security risk!\n *\n * Uncomment to prevent an error.\n */\n//#define MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION\n\n/**\n * \\def MBEDTLS_X509_CHECK_KEY_USAGE\n *\n * Enable verification of the keyUsage extension (CA and leaf certificates).\n *\n * Disabling this avoids problems with mis-issued and/or misused\n * (intermediate) CA and leaf certificates.\n *\n * \\warning Depending on your PKI use, disabling this can be a security risk!\n *\n * Comment to skip keyUsage checking for both CA and leaf certificates.\n */\n#define MBEDTLS_X509_CHECK_KEY_USAGE\n\n/**\n * \\def MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE\n *\n * Enable verification of the extendedKeyUsage extension (leaf certificates).\n *\n * Disabling this avoids problems with mis-issued and/or misused certificates.\n *\n * \\warning Depending on your PKI use, disabling this can be a security risk!\n *\n * Comment to skip extendedKeyUsage checking for certificates.\n */\n#define MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE\n\n/**\n * \\def MBEDTLS_X509_RSASSA_PSS_SUPPORT\n *\n * Enable parsing and verification of X.509 certificates, CRLs and CSRS\n * signed with RSASSA-PSS (aka PKCS#1 v2.1).\n *\n * Comment this macro to disallow using RSASSA-PSS in certificates.\n */\n#define MBEDTLS_X509_RSASSA_PSS_SUPPORT\n\n/**\n * \\def MBEDTLS_ZLIB_SUPPORT\n *\n * If set, the SSL/TLS module uses ZLIB to support compression and\n * decompression of packet data.\n *\n * \\warning TLS-level compression MAY REDUCE SECURITY! See for example the\n * CRIME attack. Before enabling this option, you should examine with care if\n * CRIME or similar exploits may be a applicable to your use case.\n *\n * \\note Currently compression can't be used with DTLS.\n *\n * \\deprecated This feature is deprecated and will be removed\n *             in the next major revision of the library.\n *\n * Used in: library/ssl_tls.c\n *          library/ssl_cli.c\n *          library/ssl_srv.c\n *\n * This feature requires zlib library and headers to be present.\n *\n * Uncomment to enable use of ZLIB\n */\n//#define MBEDTLS_ZLIB_SUPPORT\n/* \\} name SECTION: mbed TLS feature support */\n\n/**\n * \\name SECTION: mbed TLS modules\n *\n * This section enables or disables entire modules in mbed TLS\n * \\{\n */\n\n/**\n * \\def MBEDTLS_AESNI_C\n *\n * Enable AES-NI support on x86-64.\n *\n * Module:  library/aesni.c\n * Caller:  library/aes.c\n *\n * Requires: MBEDTLS_HAVE_ASM\n *\n * This modules adds support for the AES-NI instructions on x86-64\n */\n#define MBEDTLS_AESNI_C\n\n/**\n * \\def MBEDTLS_AES_C\n *\n * Enable the AES block cipher.\n *\n * Module:  library/aes.c\n * Caller:  library/cipher.c\n *          library/pem.c\n *          library/ctr_drbg.c\n *\n * This module enables the following ciphersuites (if other requisites are\n * enabled as well):\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384\n *      MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384\n *      MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256\n *      MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384\n *      MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA\n *      MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384\n *      MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384\n *      MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA\n *      MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256\n *      MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256\n *      MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA\n *\n * PEM_PARSE uses AES for decrypting encrypted keys.\n */\n#define MBEDTLS_AES_C\n\n/**\n * \\def MBEDTLS_ARC4_C\n *\n * Enable the ARCFOUR stream cipher.\n *\n * Module:  library/arc4.c\n * Caller:  library/cipher.c\n *\n * This module enables the following ciphersuites (if other requisites are\n * enabled as well):\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA\n *      MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA\n *      MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA\n *      MBEDTLS_TLS_RSA_WITH_RC4_128_SHA\n *      MBEDTLS_TLS_RSA_WITH_RC4_128_MD5\n *      MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA\n *      MBEDTLS_TLS_PSK_WITH_RC4_128_SHA\n *\n * \\warning   ARC4 is considered a weak cipher and its use constitutes a\n *            security risk. If possible, we recommend avoidng dependencies on\n *            it, and considering stronger ciphers instead.\n *\n */\n#define MBEDTLS_ARC4_C\n\n/**\n * \\def MBEDTLS_ASN1_PARSE_C\n *\n * Enable the generic ASN1 parser.\n *\n * Module:  library/asn1.c\n * Caller:  library/x509.c\n *          library/dhm.c\n *          library/pkcs12.c\n *          library/pkcs5.c\n *          library/pkparse.c\n */\n#define MBEDTLS_ASN1_PARSE_C\n\n/**\n * \\def MBEDTLS_ASN1_WRITE_C\n *\n * Enable the generic ASN1 writer.\n *\n * Module:  library/asn1write.c\n * Caller:  library/ecdsa.c\n *          library/pkwrite.c\n *          library/x509_create.c\n *          library/x509write_crt.c\n *          library/x509write_csr.c\n */\n#define MBEDTLS_ASN1_WRITE_C\n\n/**\n * \\def MBEDTLS_BASE64_C\n *\n * Enable the Base64 module.\n *\n * Module:  library/base64.c\n * Caller:  library/pem.c\n *\n * This module is required for PEM support (required by X.509).\n */\n#define MBEDTLS_BASE64_C\n\n/**\n * \\def MBEDTLS_BIGNUM_C\n *\n * Enable the multi-precision integer library.\n *\n * Module:  library/bignum.c\n * Caller:  library/dhm.c\n *          library/ecp.c\n *          library/ecdsa.c\n *          library/rsa.c\n *          library/rsa_internal.c\n *          library/ssl_tls.c\n *\n * This module is required for RSA, DHM and ECC (ECDH, ECDSA) support.\n */\n#define MBEDTLS_BIGNUM_C\n\n/**\n * \\def MBEDTLS_BLOWFISH_C\n *\n * Enable the Blowfish block cipher.\n *\n * Module:  library/blowfish.c\n */\n#define MBEDTLS_BLOWFISH_C\n\n/**\n * \\def MBEDTLS_CAMELLIA_C\n *\n * Enable the Camellia block cipher.\n *\n * Module:  library/camellia.c\n * Caller:  library/cipher.c\n *\n * This module enables the following ciphersuites (if other requisites are\n * enabled as well):\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384\n *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384\n *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256\n *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA\n *      MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384\n *      MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384\n *      MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384\n *      MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256\n *      MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA\n *      MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA\n *      MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384\n *      MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384\n *      MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256\n *      MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384\n *      MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384\n *      MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256\n *      MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256\n */\n#define MBEDTLS_CAMELLIA_C\n\n/**\n * \\def MBEDTLS_ARIA_C\n *\n * Enable the ARIA block cipher.\n *\n * Module:  library/aria.c\n * Caller:  library/cipher.c\n *\n * This module enables the following ciphersuites (if other requisites are\n * enabled as well):\n *\n *      MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256\n *      MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384\n *      MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256\n *      MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384\n *      MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384\n *      MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256\n *      MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384\n *      MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256\n *      MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256\n *      MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384\n *      MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256\n *      MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384\n *      MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256\n *      MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384\n *      MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256\n *      MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384\n *      MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256\n *      MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384\n *      MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256\n *      MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384\n *      MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256\n *      MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384\n */\n//#define MBEDTLS_ARIA_C\n\n/**\n * \\def MBEDTLS_CCM_C\n *\n * Enable the Counter with CBC-MAC (CCM) mode for 128-bit block cipher.\n *\n * Module:  library/ccm.c\n *\n * Requires: MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C\n *\n * This module enables the AES-CCM ciphersuites, if other requisites are\n * enabled as well.\n */\n#define MBEDTLS_CCM_C\n\n/**\n * \\def MBEDTLS_CERTS_C\n *\n * Enable the test certificates.\n *\n * Module:  library/certs.c\n * Caller:\n *\n * This module is used for testing (ssl_client/server).\n */\n#define MBEDTLS_CERTS_C\n\n/**\n * \\def MBEDTLS_CHACHA20_C\n *\n * Enable the ChaCha20 stream cipher.\n *\n * Module:  library/chacha20.c\n */\n#define MBEDTLS_CHACHA20_C\n\n/**\n * \\def MBEDTLS_CHACHAPOLY_C\n *\n * Enable the ChaCha20-Poly1305 AEAD algorithm.\n *\n * Module:  library/chachapoly.c\n *\n * This module requires: MBEDTLS_CHACHA20_C, MBEDTLS_POLY1305_C\n */\n#define MBEDTLS_CHACHAPOLY_C\n\n/**\n * \\def MBEDTLS_CIPHER_C\n *\n * Enable the generic cipher layer.\n *\n * Module:  library/cipher.c\n * Caller:  library/ssl_tls.c\n *\n * Uncomment to enable generic cipher wrappers.\n */\n#define MBEDTLS_CIPHER_C\n\n/**\n * \\def MBEDTLS_CMAC_C\n *\n * Enable the CMAC (Cipher-based Message Authentication Code) mode for block\n * ciphers.\n *\n * Module:  library/cmac.c\n *\n * Requires: MBEDTLS_AES_C or MBEDTLS_DES_C\n *\n */\n//#define MBEDTLS_CMAC_C\n\n/**\n * \\def MBEDTLS_CTR_DRBG_C\n *\n * Enable the CTR_DRBG AES-256-based random generator.\n *\n * Module:  library/ctr_drbg.c\n * Caller:\n *\n * Requires: MBEDTLS_AES_C\n *\n * This module provides the CTR_DRBG AES-256 random number generator.\n */\n#define MBEDTLS_CTR_DRBG_C\n\n/**\n * \\def MBEDTLS_DEBUG_C\n *\n * Enable the debug functions.\n *\n * Module:  library/debug.c\n * Caller:  library/ssl_cli.c\n *          library/ssl_srv.c\n *          library/ssl_tls.c\n *\n * This module provides debugging functions.\n */\n#define MBEDTLS_DEBUG_C\n\n/**\n * \\def MBEDTLS_DES_C\n *\n * Enable the DES block cipher.\n *\n * Module:  library/des.c\n * Caller:  library/pem.c\n *          library/cipher.c\n *\n * This module enables the following ciphersuites (if other requisites are\n * enabled as well):\n *      MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA\n *      MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA\n *\n * PEM_PARSE uses DES/3DES for decrypting encrypted keys.\n *\n * \\warning   DES is considered a weak cipher and its use constitutes a\n *            security risk. We recommend considering stronger ciphers instead.\n */\n#define MBEDTLS_DES_C\n\n/**\n * \\def MBEDTLS_DHM_C\n *\n * Enable the Diffie-Hellman-Merkle module.\n *\n * Module:  library/dhm.c\n * Caller:  library/ssl_cli.c\n *          library/ssl_srv.c\n *\n * This module is used by the following key exchanges:\n *      DHE-RSA, DHE-PSK\n *\n * \\warning    Using DHE constitutes a security risk as it\n *             is not possible to validate custom DH parameters.\n *             If possible, it is recommended users should consider\n *             preferring other methods of key exchange.\n *             See dhm.h for more details.\n *\n */\n#define MBEDTLS_DHM_C\n\n/**\n * \\def MBEDTLS_ECDH_C\n *\n * Enable the elliptic curve Diffie-Hellman library.\n *\n * Module:  library/ecdh.c\n * Caller:  library/ssl_cli.c\n *          library/ssl_srv.c\n *\n * This module is used by the following key exchanges:\n *      ECDHE-ECDSA, ECDHE-RSA, DHE-PSK\n *\n * Requires: MBEDTLS_ECP_C\n */\n#define MBEDTLS_ECDH_C\n\n/**\n * \\def MBEDTLS_ECDSA_C\n *\n * Enable the elliptic curve DSA library.\n *\n * Module:  library/ecdsa.c\n * Caller:\n *\n * This module is used by the following key exchanges:\n *      ECDHE-ECDSA\n *\n * Requires: MBEDTLS_ECP_C, MBEDTLS_ASN1_WRITE_C, MBEDTLS_ASN1_PARSE_C\n */\n#define MBEDTLS_ECDSA_C\n\n/**\n * \\def MBEDTLS_ECJPAKE_C\n *\n * Enable the elliptic curve J-PAKE library.\n *\n * \\warning This is currently experimental. EC J-PAKE support is based on the\n * Thread v1.0.0 specification; incompatible changes to the specification\n * might still happen. For this reason, this is disabled by default.\n *\n * Module:  library/ecjpake.c\n * Caller:\n *\n * This module is used by the following key exchanges:\n *      ECJPAKE\n *\n * Requires: MBEDTLS_ECP_C, MBEDTLS_MD_C\n */\n//#define MBEDTLS_ECJPAKE_C\n\n/**\n * \\def MBEDTLS_ECP_C\n *\n * Enable the elliptic curve over GF(p) library.\n *\n * Module:  library/ecp.c\n * Caller:  library/ecdh.c\n *          library/ecdsa.c\n *          library/ecjpake.c\n *\n * Requires: MBEDTLS_BIGNUM_C and at least one MBEDTLS_ECP_DP_XXX_ENABLED\n */\n#define MBEDTLS_ECP_C\n\n/**\n * \\def MBEDTLS_ENTROPY_C\n *\n * Enable the platform-specific entropy code.\n *\n * Module:  library/entropy.c\n * Caller:\n *\n * Requires: MBEDTLS_SHA512_C or MBEDTLS_SHA256_C\n *\n * This module provides a generic entropy pool\n */\n#define MBEDTLS_ENTROPY_C\n\n/**\n * \\def MBEDTLS_ERROR_C\n *\n * Enable error code to error string conversion.\n *\n * Module:  library/error.c\n * Caller:\n *\n * This module enables mbedtls_strerror().\n */\n#define MBEDTLS_ERROR_C\n\n/**\n * \\def MBEDTLS_GCM_C\n *\n * Enable the Galois/Counter Mode (GCM) for AES.\n *\n * Module:  library/gcm.c\n *\n * Requires: MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C\n *\n * This module enables the AES-GCM and CAMELLIA-GCM ciphersuites, if other\n * requisites are enabled as well.\n */\n#define MBEDTLS_GCM_C\n\n/**\n * \\def MBEDTLS_HAVEGE_C\n *\n * Enable the HAVEGE random generator.\n *\n * Warning: the HAVEGE random generator is not suitable for virtualized\n *          environments\n *\n * Warning: the HAVEGE random generator is dependent on timing and specific\n *          processor traits. It is therefore not advised to use HAVEGE as\n *          your applications primary random generator or primary entropy pool\n *          input. As a secondary input to your entropy pool, it IS able add\n *          the (limited) extra entropy it provides.\n *\n * Module:  library/havege.c\n * Caller:\n *\n * Requires: MBEDTLS_TIMING_C\n *\n * Uncomment to enable the HAVEGE random generator.\n */\n//#define MBEDTLS_HAVEGE_C\n\n/**\n * \\def MBEDTLS_HKDF_C\n *\n * Enable the HKDF algorithm (RFC 5869).\n *\n * Module:  library/hkdf.c\n * Caller:\n *\n * Requires: MBEDTLS_MD_C\n *\n * This module adds support for the Hashed Message Authentication Code\n * (HMAC)-based key derivation function (HKDF).\n */\n#define MBEDTLS_HKDF_C\n\n/**\n * \\def MBEDTLS_HMAC_DRBG_C\n *\n * Enable the HMAC_DRBG random generator.\n *\n * Module:  library/hmac_drbg.c\n * Caller:\n *\n * Requires: MBEDTLS_MD_C\n *\n * Uncomment to enable the HMAC_DRBG random number geerator.\n */\n#define MBEDTLS_HMAC_DRBG_C\n\n/**\n * \\def MBEDTLS_NIST_KW_C\n *\n * Enable the Key Wrapping mode for 128-bit block ciphers,\n * as defined in NIST SP 800-38F. Only KW and KWP modes\n * are supported. At the moment, only AES is approved by NIST.\n *\n * Module:  library/nist_kw.c\n *\n * Requires: MBEDTLS_AES_C and MBEDTLS_CIPHER_C\n */\n//#define MBEDTLS_NIST_KW_C\n\n/**\n * \\def MBEDTLS_MD_C\n *\n * Enable the generic message digest layer.\n *\n * Module:  library/md.c\n * Caller:\n *\n * Uncomment to enable generic message digest wrappers.\n */\n#define MBEDTLS_MD_C\n\n/**\n * \\def MBEDTLS_MD2_C\n *\n * Enable the MD2 hash algorithm.\n *\n * Module:  library/md2.c\n * Caller:\n *\n * Uncomment to enable support for (rare) MD2-signed X.509 certs.\n *\n * \\warning   MD2 is considered a weak message digest and its use constitutes a\n *            security risk. If possible, we recommend avoiding dependencies on\n *            it, and considering stronger message digests instead.\n *\n */\n//#define MBEDTLS_MD2_C\n\n/**\n * \\def MBEDTLS_MD4_C\n *\n * Enable the MD4 hash algorithm.\n *\n * Module:  library/md4.c\n * Caller:\n *\n * Uncomment to enable support for (rare) MD4-signed X.509 certs.\n *\n * \\warning   MD4 is considered a weak message digest and its use constitutes a\n *            security risk. If possible, we recommend avoiding dependencies on\n *            it, and considering stronger message digests instead.\n *\n */\n//#define MBEDTLS_MD4_C\n\n/**\n * \\def MBEDTLS_MD5_C\n *\n * Enable the MD5 hash algorithm.\n *\n * Module:  library/md5.c\n * Caller:  library/md.c\n *          library/pem.c\n *          library/ssl_tls.c\n *\n * This module is required for SSL/TLS up to version 1.1, and for TLS 1.2\n * depending on the handshake parameters. Further, it is used for checking\n * MD5-signed certificates, and for PBKDF1 when decrypting PEM-encoded\n * encrypted keys.\n *\n * \\warning   MD5 is considered a weak message digest and its use constitutes a\n *            security risk. If possible, we recommend avoiding dependencies on\n *            it, and considering stronger message digests instead.\n *\n */\n#define MBEDTLS_MD5_C\n\n/**\n * \\def MBEDTLS_MEMORY_BUFFER_ALLOC_C\n *\n * Enable the buffer allocator implementation that makes use of a (stack)\n * based buffer to 'allocate' dynamic memory. (replaces calloc() and free()\n * calls)\n *\n * Module:  library/memory_buffer_alloc.c\n *\n * Requires: MBEDTLS_PLATFORM_C\n *           MBEDTLS_PLATFORM_MEMORY (to use it within mbed TLS)\n *\n * Enable this module to enable the buffer memory allocator.\n */\n//#define MBEDTLS_MEMORY_BUFFER_ALLOC_C\n\n/**\n * \\def MBEDTLS_NET_C\n *\n * Enable the TCP and UDP over IPv6/IPv4 networking routines.\n *\n * \\note This module only works on POSIX/Unix (including Linux, BSD and OS X)\n * and Windows. For other platforms, you'll want to disable it, and write your\n * own networking callbacks to be passed to \\c mbedtls_ssl_set_bio().\n *\n * \\note See also our Knowledge Base article about porting to a new\n * environment:\n * https://tls.mbed.org/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS\n *\n * Module:  library/net_sockets.c\n *\n * This module provides networking routines.\n */\n#define MBEDTLS_NET_C\n\n/**\n * \\def MBEDTLS_OID_C\n *\n * Enable the OID database.\n *\n * Module:  library/oid.c\n * Caller:  library/asn1write.c\n *          library/pkcs5.c\n *          library/pkparse.c\n *          library/pkwrite.c\n *          library/rsa.c\n *          library/x509.c\n *          library/x509_create.c\n *          library/x509_crl.c\n *          library/x509_crt.c\n *          library/x509_csr.c\n *          library/x509write_crt.c\n *          library/x509write_csr.c\n *\n * This modules translates between OIDs and internal values.\n */\n#define MBEDTLS_OID_C\n\n/**\n * \\def MBEDTLS_PADLOCK_C\n *\n * Enable VIA Padlock support on x86.\n *\n * Module:  library/padlock.c\n * Caller:  library/aes.c\n *\n * Requires: MBEDTLS_HAVE_ASM\n *\n * This modules adds support for the VIA PadLock on x86.\n */\n#define MBEDTLS_PADLOCK_C\n\n/**\n * \\def MBEDTLS_PEM_PARSE_C\n *\n * Enable PEM decoding / parsing.\n *\n * Module:  library/pem.c\n * Caller:  library/dhm.c\n *          library/pkparse.c\n *          library/x509_crl.c\n *          library/x509_crt.c\n *          library/x509_csr.c\n *\n * Requires: MBEDTLS_BASE64_C\n *\n * This modules adds support for decoding / parsing PEM files.\n */\n#define MBEDTLS_PEM_PARSE_C\n\n/**\n * \\def MBEDTLS_PEM_WRITE_C\n *\n * Enable PEM encoding / writing.\n *\n * Module:  library/pem.c\n * Caller:  library/pkwrite.c\n *          library/x509write_crt.c\n *          library/x509write_csr.c\n *\n * Requires: MBEDTLS_BASE64_C\n *\n * This modules adds support for encoding / writing PEM files.\n */\n#define MBEDTLS_PEM_WRITE_C\n\n/**\n * \\def MBEDTLS_PK_C\n *\n * Enable the generic public (asymetric) key layer.\n *\n * Module:  library/pk.c\n * Caller:  library/ssl_tls.c\n *          library/ssl_cli.c\n *          library/ssl_srv.c\n *\n * Requires: MBEDTLS_RSA_C or MBEDTLS_ECP_C\n *\n * Uncomment to enable generic public key wrappers.\n */\n#define MBEDTLS_PK_C\n\n/**\n * \\def MBEDTLS_PK_PARSE_C\n *\n * Enable the generic public (asymetric) key parser.\n *\n * Module:  library/pkparse.c\n * Caller:  library/x509_crt.c\n *          library/x509_csr.c\n *\n * Requires: MBEDTLS_PK_C\n *\n * Uncomment to enable generic public key parse functions.\n */\n#define MBEDTLS_PK_PARSE_C\n\n/**\n * \\def MBEDTLS_PK_WRITE_C\n *\n * Enable the generic public (asymetric) key writer.\n *\n * Module:  library/pkwrite.c\n * Caller:  library/x509write.c\n *\n * Requires: MBEDTLS_PK_C\n *\n * Uncomment to enable generic public key write functions.\n */\n#define MBEDTLS_PK_WRITE_C\n\n/**\n * \\def MBEDTLS_PKCS5_C\n *\n * Enable PKCS#5 functions.\n *\n * Module:  library/pkcs5.c\n *\n * Requires: MBEDTLS_MD_C\n *\n * This module adds support for the PKCS#5 functions.\n */\n#define MBEDTLS_PKCS5_C\n\n/**\n * \\def MBEDTLS_PKCS11_C\n *\n * Enable wrapper for PKCS#11 smartcard support.\n *\n * Module:  library/pkcs11.c\n * Caller:  library/pk.c\n *\n * Requires: MBEDTLS_PK_C\n *\n * This module enables SSL/TLS PKCS #11 smartcard support.\n * Requires the presence of the PKCS#11 helper library (libpkcs11-helper)\n */\n//#define MBEDTLS_PKCS11_C\n\n/**\n * \\def MBEDTLS_PKCS12_C\n *\n * Enable PKCS#12 PBE functions.\n * Adds algorithms for parsing PKCS#8 encrypted private keys\n *\n * Module:  library/pkcs12.c\n * Caller:  library/pkparse.c\n *\n * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_CIPHER_C, MBEDTLS_MD_C\n * Can use:  MBEDTLS_ARC4_C\n *\n * This module enables PKCS#12 functions.\n */\n#define MBEDTLS_PKCS12_C\n\n/**\n * \\def MBEDTLS_PLATFORM_C\n *\n * Enable the platform abstraction layer that allows you to re-assign\n * functions like calloc(), free(), snprintf(), printf(), fprintf(), exit().\n *\n * Enabling MBEDTLS_PLATFORM_C enables to use of MBEDTLS_PLATFORM_XXX_ALT\n * or MBEDTLS_PLATFORM_XXX_MACRO directives, allowing the functions mentioned\n * above to be specified at runtime or compile time respectively.\n *\n * \\note This abstraction layer must be enabled on Windows (including MSYS2)\n * as other module rely on it for a fixed snprintf implementation.\n *\n * Module:  library/platform.c\n * Caller:  Most other .c files\n *\n * This module enables abstraction of common (libc) functions.\n */\n#define MBEDTLS_PLATFORM_C\n\n/**\n * \\def MBEDTLS_POLY1305_C\n *\n * Enable the Poly1305 MAC algorithm.\n *\n * Module:  library/poly1305.c\n * Caller:  library/chachapoly.c\n */\n#define MBEDTLS_POLY1305_C\n\n/**\n * \\def MBEDTLS_RIPEMD160_C\n *\n * Enable the RIPEMD-160 hash algorithm.\n *\n * Module:  library/ripemd160.c\n * Caller:  library/md.c\n *\n */\n#define MBEDTLS_RIPEMD160_C\n\n/**\n * \\def MBEDTLS_RSA_C\n *\n * Enable the RSA public-key cryptosystem.\n *\n * Module:  library/rsa.c\n *          library/rsa_internal.c\n * Caller:  library/ssl_cli.c\n *          library/ssl_srv.c\n *          library/ssl_tls.c\n *          library/x509.c\n *\n * This module is used by the following key exchanges:\n *      RSA, DHE-RSA, ECDHE-RSA, RSA-PSK\n *\n * Requires: MBEDTLS_BIGNUM_C, MBEDTLS_OID_C\n */\n#define MBEDTLS_RSA_C\n\n/**\n * \\def MBEDTLS_SHA1_C\n *\n * Enable the SHA1 cryptographic hash algorithm.\n *\n * Module:  library/sha1.c\n * Caller:  library/md.c\n *          library/ssl_cli.c\n *          library/ssl_srv.c\n *          library/ssl_tls.c\n *          library/x509write_crt.c\n *\n * This module is required for SSL/TLS up to version 1.1, for TLS 1.2\n * depending on the handshake parameters, and for SHA1-signed certificates.\n *\n * \\warning   SHA-1 is considered a weak message digest and its use constitutes\n *            a security risk. If possible, we recommend avoiding dependencies\n *            on it, and considering stronger message digests instead.\n *\n */\n#define MBEDTLS_SHA1_C\n\n/**\n * \\def MBEDTLS_SHA256_C\n *\n * Enable the SHA-224 and SHA-256 cryptographic hash algorithms.\n *\n * Module:  library/sha256.c\n * Caller:  library/entropy.c\n *          library/md.c\n *          library/ssl_cli.c\n *          library/ssl_srv.c\n *          library/ssl_tls.c\n *\n * This module adds support for SHA-224 and SHA-256.\n * This module is required for the SSL/TLS 1.2 PRF function.\n */\n#define MBEDTLS_SHA256_C\n\n/**\n * \\def MBEDTLS_SHA512_C\n *\n * Enable the SHA-384 and SHA-512 cryptographic hash algorithms.\n *\n * Module:  library/sha512.c\n * Caller:  library/entropy.c\n *          library/md.c\n *          library/ssl_cli.c\n *          library/ssl_srv.c\n *\n * This module adds support for SHA-384 and SHA-512.\n */\n#define MBEDTLS_SHA512_C\n\n/**\n * \\def MBEDTLS_SSL_CACHE_C\n *\n * Enable simple SSL cache implementation.\n *\n * Module:  library/ssl_cache.c\n * Caller:\n *\n * Requires: MBEDTLS_SSL_CACHE_C\n */\n#define MBEDTLS_SSL_CACHE_C\n\n/**\n * \\def MBEDTLS_SSL_COOKIE_C\n *\n * Enable basic implementation of DTLS cookies for hello verification.\n *\n * Module:  library/ssl_cookie.c\n * Caller:\n */\n#define MBEDTLS_SSL_COOKIE_C\n\n/**\n * \\def MBEDTLS_SSL_TICKET_C\n *\n * Enable an implementation of TLS server-side callbacks for session tickets.\n *\n * Module:  library/ssl_ticket.c\n * Caller:\n *\n * Requires: MBEDTLS_CIPHER_C\n */\n#define MBEDTLS_SSL_TICKET_C\n\n/**\n * \\def MBEDTLS_SSL_CLI_C\n *\n * Enable the SSL/TLS client code.\n *\n * Module:  library/ssl_cli.c\n * Caller:\n *\n * Requires: MBEDTLS_SSL_TLS_C\n *\n * This module is required for SSL/TLS client support.\n */\n#define MBEDTLS_SSL_CLI_C\n\n/**\n * \\def MBEDTLS_SSL_SRV_C\n *\n * Enable the SSL/TLS server code.\n *\n * Module:  library/ssl_srv.c\n * Caller:\n *\n * Requires: MBEDTLS_SSL_TLS_C\n *\n * This module is required for SSL/TLS server support.\n */\n#define MBEDTLS_SSL_SRV_C\n\n/**\n * \\def MBEDTLS_SSL_TLS_C\n *\n * Enable the generic SSL/TLS code.\n *\n * Module:  library/ssl_tls.c\n * Caller:  library/ssl_cli.c\n *          library/ssl_srv.c\n *\n * Requires: MBEDTLS_CIPHER_C, MBEDTLS_MD_C\n *           and at least one of the MBEDTLS_SSL_PROTO_XXX defines\n *\n * This module is required for SSL/TLS.\n */\n#define MBEDTLS_SSL_TLS_C\n\n/**\n * \\def MBEDTLS_THREADING_C\n *\n * Enable the threading abstraction layer.\n * By default mbed TLS assumes it is used in a non-threaded environment or that\n * contexts are not shared between threads. If you do intend to use contexts\n * between threads, you will need to enable this layer to prevent race\n * conditions. See also our Knowledge Base article about threading:\n * https://tls.mbed.org/kb/development/thread-safety-and-multi-threading\n *\n * Module:  library/threading.c\n *\n * This allows different threading implementations (self-implemented or\n * provided).\n *\n * You will have to enable either MBEDTLS_THREADING_ALT or\n * MBEDTLS_THREADING_PTHREAD.\n *\n * Enable this layer to allow use of mutexes within mbed TLS\n */\n//#define MBEDTLS_THREADING_C\n\n/**\n * \\def MBEDTLS_TIMING_C\n *\n * Enable the semi-portable timing interface.\n *\n * \\note The provided implementation only works on POSIX/Unix (including Linux,\n * BSD and OS X) and Windows. On other platforms, you can either disable that\n * module and provide your own implementations of the callbacks needed by\n * \\c mbedtls_ssl_set_timer_cb() for DTLS, or leave it enabled and provide\n * your own implementation of the whole module by setting\n * \\c MBEDTLS_TIMING_ALT in the current file.\n *\n * \\note See also our Knowledge Base article about porting to a new\n * environment:\n * https://tls.mbed.org/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS\n *\n * Module:  library/timing.c\n * Caller:  library/havege.c\n *\n * This module is used by the HAVEGE random number generator.\n */\n#define MBEDTLS_TIMING_C\n\n/**\n * \\def MBEDTLS_VERSION_C\n *\n * Enable run-time version information.\n *\n * Module:  library/version.c\n *\n * This module provides run-time version information.\n */\n#define MBEDTLS_VERSION_C\n\n/**\n * \\def MBEDTLS_X509_USE_C\n *\n * Enable X.509 core for using certificates.\n *\n * Module:  library/x509.c\n * Caller:  library/x509_crl.c\n *          library/x509_crt.c\n *          library/x509_csr.c\n *\n * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_BIGNUM_C, MBEDTLS_OID_C,\n *           MBEDTLS_PK_PARSE_C\n *\n * This module is required for the X.509 parsing modules.\n */\n#define MBEDTLS_X509_USE_C\n\n/**\n * \\def MBEDTLS_X509_CRT_PARSE_C\n *\n * Enable X.509 certificate parsing.\n *\n * Module:  library/x509_crt.c\n * Caller:  library/ssl_cli.c\n *          library/ssl_srv.c\n *          library/ssl_tls.c\n *\n * Requires: MBEDTLS_X509_USE_C\n *\n * This module is required for X.509 certificate parsing.\n */\n#define MBEDTLS_X509_CRT_PARSE_C\n\n/**\n * \\def MBEDTLS_X509_CRL_PARSE_C\n *\n * Enable X.509 CRL parsing.\n *\n * Module:  library/x509_crl.c\n * Caller:  library/x509_crt.c\n *\n * Requires: MBEDTLS_X509_USE_C\n *\n * This module is required for X.509 CRL parsing.\n */\n#define MBEDTLS_X509_CRL_PARSE_C\n\n/**\n * \\def MBEDTLS_X509_CSR_PARSE_C\n *\n * Enable X.509 Certificate Signing Request (CSR) parsing.\n *\n * Module:  library/x509_csr.c\n * Caller:  library/x509_crt_write.c\n *\n * Requires: MBEDTLS_X509_USE_C\n *\n * This module is used for reading X.509 certificate request.\n */\n#define MBEDTLS_X509_CSR_PARSE_C\n\n/**\n * \\def MBEDTLS_X509_CREATE_C\n *\n * Enable X.509 core for creating certificates.\n *\n * Module:  library/x509_create.c\n *\n * Requires: MBEDTLS_BIGNUM_C, MBEDTLS_OID_C, MBEDTLS_PK_WRITE_C\n *\n * This module is the basis for creating X.509 certificates and CSRs.\n */\n#define MBEDTLS_X509_CREATE_C\n\n/**\n * \\def MBEDTLS_X509_CRT_WRITE_C\n *\n * Enable creating X.509 certificates.\n *\n * Module:  library/x509_crt_write.c\n *\n * Requires: MBEDTLS_X509_CREATE_C\n *\n * This module is required for X.509 certificate creation.\n */\n#define MBEDTLS_X509_CRT_WRITE_C\n\n/**\n * \\def MBEDTLS_X509_CSR_WRITE_C\n *\n * Enable creating X.509 Certificate Signing Requests (CSR).\n *\n * Module:  library/x509_csr_write.c\n *\n * Requires: MBEDTLS_X509_CREATE_C\n *\n * This module is required for X.509 certificate request writing.\n */\n#define MBEDTLS_X509_CSR_WRITE_C\n\n/**\n * \\def MBEDTLS_XTEA_C\n *\n * Enable the XTEA block cipher.\n *\n * Module:  library/xtea.c\n * Caller:\n */\n#define MBEDTLS_XTEA_C\n\n/* \\} name SECTION: mbed TLS modules */\n\n/**\n * \\name SECTION: Module configuration options\n *\n * This section allows for the setting of module specific sizes and\n * configuration options. The default values are already present in the\n * relevant header files and should suffice for the regular use cases.\n *\n * Our advice is to enable options and change their values here\n * only if you have a good reason and know the consequences.\n *\n * Please check the respective header file for documentation on these\n * parameters (to prevent duplicate documentation).\n * \\{\n */\n\n/* MPI / BIGNUM options */\n//#define MBEDTLS_MPI_WINDOW_SIZE            6 /**< Maximum windows size used. */\n//#define MBEDTLS_MPI_MAX_SIZE            1024 /**< Maximum number of bytes for usable MPIs. */\n\n/* CTR_DRBG options */\n//#define MBEDTLS_CTR_DRBG_ENTROPY_LEN               48 /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */\n//#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL        10000 /**< Interval before reseed is performed by default */\n//#define MBEDTLS_CTR_DRBG_MAX_INPUT                256 /**< Maximum number of additional input bytes */\n//#define MBEDTLS_CTR_DRBG_MAX_REQUEST             1024 /**< Maximum number of requested bytes per call */\n//#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT           384 /**< Maximum size of (re)seed buffer */\n\n/* HMAC_DRBG options */\n//#define MBEDTLS_HMAC_DRBG_RESEED_INTERVAL   10000 /**< Interval before reseed is performed by default */\n//#define MBEDTLS_HMAC_DRBG_MAX_INPUT           256 /**< Maximum number of additional input bytes */\n//#define MBEDTLS_HMAC_DRBG_MAX_REQUEST        1024 /**< Maximum number of requested bytes per call */\n//#define MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT      384 /**< Maximum size of (re)seed buffer */\n\n/* ECP options */\n//#define MBEDTLS_ECP_MAX_BITS             521 /**< Maximum bit size of groups */\n//#define MBEDTLS_ECP_WINDOW_SIZE            6 /**< Maximum window size used */\n//#define MBEDTLS_ECP_FIXED_POINT_OPTIM      1 /**< Enable fixed-point speed-up */\n\n/* Entropy options */\n//#define MBEDTLS_ENTROPY_MAX_SOURCES                20 /**< Maximum number of sources supported */\n//#define MBEDTLS_ENTROPY_MAX_GATHER                128 /**< Maximum amount requested from entropy sources */\n//#define MBEDTLS_ENTROPY_MIN_HARDWARE               32 /**< Default minimum number of bytes required for the hardware entropy source mbedtls_hardware_poll() before entropy is released */\n\n/* Memory buffer allocator options */\n//#define MBEDTLS_MEMORY_ALIGN_MULTIPLE      4 /**< Align on multiples of this value */\n\n/* Platform options */\n//#define MBEDTLS_PLATFORM_STD_MEM_HDR   <stdlib.h> /**< Header to include if MBEDTLS_PLATFORM_NO_STD_FUNCTIONS is defined. Don't define if no header is needed. */\n//#define MBEDTLS_PLATFORM_STD_CALLOC        calloc /**< Default allocator to use, can be undefined */\n//#define MBEDTLS_PLATFORM_STD_FREE            free /**< Default free to use, can be undefined */\n//#define MBEDTLS_PLATFORM_STD_EXIT            exit /**< Default exit to use, can be undefined */\n//#define MBEDTLS_PLATFORM_STD_TIME            time /**< Default time to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */\n//#define MBEDTLS_PLATFORM_STD_FPRINTF      fprintf /**< Default fprintf to use, can be undefined */\n//#define MBEDTLS_PLATFORM_STD_PRINTF        printf /**< Default printf to use, can be undefined */\n/* Note: your snprintf must correclty zero-terminate the buffer! */\n//#define MBEDTLS_PLATFORM_STD_SNPRINTF    snprintf /**< Default snprintf to use, can be undefined */\n//#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS       0 /**< Default exit value to use, can be undefined */\n//#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE       1 /**< Default exit value to use, can be undefined */\n//#define MBEDTLS_PLATFORM_STD_NV_SEED_READ   mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be undefined */\n//#define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE  mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function to use, can be undefined */\n//#define MBEDTLS_PLATFORM_STD_NV_SEED_FILE  \"seedfile\" /**< Seed file to read/write with default implementation */\n\n/* To Use Function Macros MBEDTLS_PLATFORM_C must be enabled */\n/* MBEDTLS_PLATFORM_XXX_MACRO and MBEDTLS_PLATFORM_XXX_ALT cannot both be defined */\n//#define MBEDTLS_PLATFORM_CALLOC_MACRO        calloc /**< Default allocator macro to use, can be undefined */\n//#define MBEDTLS_PLATFORM_FREE_MACRO            free /**< Default free macro to use, can be undefined */\n//#define MBEDTLS_PLATFORM_EXIT_MACRO            exit /**< Default exit macro to use, can be undefined */\n//#define MBEDTLS_PLATFORM_TIME_MACRO            time /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */\n//#define MBEDTLS_PLATFORM_TIME_TYPE_MACRO       time_t /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */\n//#define MBEDTLS_PLATFORM_FPRINTF_MACRO      fprintf /**< Default fprintf macro to use, can be undefined */\n//#define MBEDTLS_PLATFORM_PRINTF_MACRO        printf /**< Default printf macro to use, can be undefined */\n/* Note: your snprintf must correclty zero-terminate the buffer! */\n//#define MBEDTLS_PLATFORM_SNPRINTF_MACRO    snprintf /**< Default snprintf macro to use, can be undefined */\n//#define MBEDTLS_PLATFORM_NV_SEED_READ_MACRO   mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be undefined */\n//#define MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO  mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function to use, can be undefined */\n\n/* SSL Cache options */\n//#define MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT       86400 /**< 1 day  */\n//#define MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES      50 /**< Maximum entries in cache */\n\n/* SSL options */\n\n/** \\def MBEDTLS_SSL_MAX_CONTENT_LEN\n *\n * Maximum fragment length in bytes.\n *\n * Determines the size of both the incoming and outgoing TLS I/O buffers.\n *\n * Uncommenting MBEDTLS_SSL_IN_CONTENT_LEN and/or MBEDTLS_SSL_OUT_CONTENT_LEN\n * will override this length by setting maximum incoming and/or outgoing\n * fragment length, respectively.\n */\n//#define MBEDTLS_SSL_MAX_CONTENT_LEN             16384\n\n/** \\def MBEDTLS_SSL_IN_CONTENT_LEN\n *\n * Maximum incoming fragment length in bytes.\n *\n * Uncomment to set the size of the inward TLS buffer independently of the\n * outward buffer.\n */\n//#define MBEDTLS_SSL_IN_CONTENT_LEN              16384\n\n/** \\def MBEDTLS_SSL_OUT_CONTENT_LEN\n *\n * Maximum outgoing fragment length in bytes.\n *\n * Uncomment to set the size of the outward TLS buffer independently of the\n * inward buffer.\n *\n * It is possible to save RAM by setting a smaller outward buffer, while keeping\n * the default inward 16384 byte buffer to conform to the TLS specification.\n *\n * The minimum required outward buffer size is determined by the handshake\n * protocol's usage. Handshaking will fail if the outward buffer is too small.\n * The specific size requirement depends on the configured ciphers and any\n * certificate data which is sent during the handshake.\n *\n * For absolute minimum RAM usage, it's best to enable\n * MBEDTLS_SSL_MAX_FRAGMENT_LENGTH and reduce MBEDTLS_SSL_MAX_CONTENT_LEN. This\n * reduces both incoming and outgoing buffer sizes. However this is only\n * guaranteed if the other end of the connection also supports the TLS\n * max_fragment_len extension. Otherwise the connection may fail.\n */\n//#define MBEDTLS_SSL_OUT_CONTENT_LEN             16384\n\n//#define MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME     86400 /**< Lifetime of session tickets (if enabled) */\n//#define MBEDTLS_PSK_MAX_LEN               32 /**< Max size of TLS pre-shared keys, in bytes (default 256 bits) */\n//#define MBEDTLS_SSL_COOKIE_TIMEOUT        60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number of cookies issued */\n\n/**\n * Complete list of ciphersuites to use, in order of preference.\n *\n * \\warning No dependency checking is done on that field! This option can only\n * be used to restrict the set of available ciphersuites. It is your\n * responsibility to make sure the needed modules are active.\n *\n * Use this to save a few hundred bytes of ROM (default ordering of all\n * available ciphersuites) and a few to a few hundred bytes of RAM.\n *\n * The value below is only an example, not the default.\n */\n//#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\n\n/* X509 options */\n//#define MBEDTLS_X509_MAX_INTERMEDIATE_CA   8   /**< Maximum number of intermediate CAs in a verification chain. */\n//#define MBEDTLS_X509_MAX_FILE_PATH_LEN     512 /**< Maximum length of a path/filename string in bytes including the null terminator character ('\\0'). */\n\n/**\n * Allow SHA-1 in the default TLS configuration for certificate signing.\n * Without this build-time option, SHA-1 support must be activated explicitly\n * through mbedtls_ssl_conf_cert_profile. Turning on this option is not\n * recommended because of it is possible to generate SHA-1 collisions, however\n * this may be safe for legacy infrastructure where additional controls apply.\n *\n * \\warning   SHA-1 is considered a weak message digest and its use constitutes\n *            a security risk. If possible, we recommend avoiding dependencies\n *            on it, and considering stronger message digests instead.\n *\n */\n// #define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES\n\n/**\n * Allow SHA-1 in the default TLS configuration for TLS 1.2 handshake\n * signature and ciphersuite selection. Without this build-time option, SHA-1\n * support must be activated explicitly through mbedtls_ssl_conf_sig_hashes.\n * The use of SHA-1 in TLS <= 1.1 and in HMAC-SHA-1 is always allowed by\n * default. At the time of writing, there is no practical attack on the use\n * of SHA-1 in handshake signatures, hence this option is turned on by default\n * to preserve compatibility with existing peers, but the general\n * warning applies nonetheless:\n *\n * \\warning   SHA-1 is considered a weak message digest and its use constitutes\n *            a security risk. If possible, we recommend avoiding dependencies\n *            on it, and considering stronger message digests instead.\n *\n */\n#define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE\n\n/**\n * Uncomment the macro to let mbed TLS use your alternate implementation of\n * mbedtls_platform_zeroize(). This replaces the default implementation in\n * platform_util.c.\n *\n * mbedtls_platform_zeroize() is a widely used function across the library to\n * zero a block of memory. The implementation is expected to be secure in the\n * sense that it has been written to prevent the compiler from removing calls\n * to mbedtls_platform_zeroize() as part of redundant code elimination\n * optimizations. However, it is difficult to guarantee that calls to\n * mbedtls_platform_zeroize() will not be optimized by the compiler as older\n * versions of the C language standards do not provide a secure implementation\n * of memset(). Therefore, MBEDTLS_PLATFORM_ZEROIZE_ALT enables users to\n * configure their own implementation of mbedtls_platform_zeroize(), for\n * example by using directives specific to their compiler, features from newer\n * C standards (e.g using memset_s() in C11) or calling a secure memset() from\n * their system (e.g explicit_bzero() in BSD).\n */\n//#define MBEDTLS_PLATFORM_ZEROIZE_ALT\n\n/* \\} name SECTION: Customisation configuration options */\n\n/* Target and application specific configurations */\n//#define YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE \"target_config.h\"\n\n#if defined(TARGET_LIKE_MBED) && defined(YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE)\n#include YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE\n#endif\n\n/*\n * Allow user to override any previous default.\n *\n * Use two macro names for that, as:\n * - with yotta the prefix YOTTA_CFG_ is forced\n * - without yotta is looks weird to have a YOTTA prefix.\n */\n#if defined(YOTTA_CFG_MBEDTLS_USER_CONFIG_FILE)\n#include YOTTA_CFG_MBEDTLS_USER_CONFIG_FILE\n#elif defined(MBEDTLS_USER_CONFIG_FILE)\n#include MBEDTLS_USER_CONFIG_FILE\n#endif\n\n#include \"check_config.h\"\n\n#endif /* MBEDTLS_CONFIG_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/ctr_drbg.h",
    "content": "/**\n * \\file ctr_drbg.h\n *\n * \\brief    This file contains CTR_DRBG definitions and functions.\n *\n * CTR_DRBG is a standardized way of building a PRNG from a block-cipher\n * in counter mode operation, as defined in <em>NIST SP 800-90A:\n * Recommendation for Random Number Generation Using Deterministic Random\n * Bit Generators</em>.\n *\n * The Mbed TLS implementation of CTR_DRBG uses AES-256 as the underlying\n * block cipher.\n */\n/*\n *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_CTR_DRBG_H\n#define MBEDTLS_CTR_DRBG_H\n\n#include \"aes.h\"\n\n#if defined(MBEDTLS_THREADING_C)\n#include \"threading.h\"\n#endif\n\n#define MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED        -0x0034  /**< The entropy source failed. */\n#define MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG              -0x0036  /**< The requested random buffer length is too big. */\n#define MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG                -0x0038  /**< The input (entropy + additional data) is too large. */\n#define MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR                -0x003A  /**< Read or write error in file. */\n\n#define MBEDTLS_CTR_DRBG_BLOCKSIZE          16 /**< The block size used by the cipher. */\n#define MBEDTLS_CTR_DRBG_KEYSIZE            32 /**< The key size used by the cipher. */\n#define MBEDTLS_CTR_DRBG_KEYBITS            ( MBEDTLS_CTR_DRBG_KEYSIZE * 8 ) /**< The key size for the DRBG operation, in bits. */\n#define MBEDTLS_CTR_DRBG_SEEDLEN            ( MBEDTLS_CTR_DRBG_KEYSIZE + MBEDTLS_CTR_DRBG_BLOCKSIZE ) /**< The seed length, calculated as (counter + AES key). */\n\n/**\n * \\name SECTION: Module settings\n *\n * The configuration options you can set for this module are in this section.\n * Either change them in config.h or define them using the compiler command\n * line.\n * \\{\n */\n\n#if !defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN)\n#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256)\n#define MBEDTLS_CTR_DRBG_ENTROPY_LEN        48\n/**< The amount of entropy used per seed by default:\n * <ul><li>48 with SHA-512.</li>\n * <li>32 with SHA-256.</li></ul>\n */\n#else\n#define MBEDTLS_CTR_DRBG_ENTROPY_LEN        32\n/**< Amount of entropy used per seed by default:\n * <ul><li>48 with SHA-512.</li>\n * <li>32 with SHA-256.</li></ul>\n */\n#endif\n#endif\n\n#if !defined(MBEDTLS_CTR_DRBG_RESEED_INTERVAL)\n#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL    10000\n/**< The interval before reseed is performed by default. */\n#endif\n\n#if !defined(MBEDTLS_CTR_DRBG_MAX_INPUT)\n#define MBEDTLS_CTR_DRBG_MAX_INPUT          256\n/**< The maximum number of additional input Bytes. */\n#endif\n\n#if !defined(MBEDTLS_CTR_DRBG_MAX_REQUEST)\n#define MBEDTLS_CTR_DRBG_MAX_REQUEST        1024\n/**< The maximum number of requested Bytes per call. */\n#endif\n\n#if !defined(MBEDTLS_CTR_DRBG_MAX_SEED_INPUT)\n#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT     384\n/**< The maximum size of seed or reseed buffer. */\n#endif\n\n/* \\} name SECTION: Module settings */\n\n#define MBEDTLS_CTR_DRBG_PR_OFF             0\n/**< Prediction resistance is disabled. */\n#define MBEDTLS_CTR_DRBG_PR_ON              1\n/**< Prediction resistance is enabled. */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief          The CTR_DRBG context structure.\n */\ntypedef struct\n{\n    unsigned char counter[16];  /*!< The counter (V). */\n    int reseed_counter;         /*!< The reseed counter. */\n    int prediction_resistance;  /*!< This determines whether prediction\n                                     resistance is enabled, that is\n                                     whether to systematically reseed before\n                                     each random generation. */\n    size_t entropy_len;         /*!< The amount of entropy grabbed on each\n                                     seed or reseed operation. */\n    int reseed_interval;        /*!< The reseed interval. */\n\n    mbedtls_aes_context aes_ctx;        /*!< The AES context. */\n\n    /*\n     * Callbacks (Entropy)\n     */\n    int (*f_entropy)(void *, unsigned char *, size_t);\n                                /*!< The entropy callback function. */\n\n    void *p_entropy;            /*!< The context for the entropy function. */\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_threading_mutex_t mutex;\n#endif\n}\nmbedtls_ctr_drbg_context;\n\n/**\n * \\brief               This function initializes the CTR_DRBG context,\n *                      and prepares it for mbedtls_ctr_drbg_seed()\n *                      or mbedtls_ctr_drbg_free().\n *\n * \\param ctx           The CTR_DRBG context to initialize.\n */\nvoid mbedtls_ctr_drbg_init( mbedtls_ctr_drbg_context *ctx );\n\n/**\n * \\brief               This function seeds and sets up the CTR_DRBG\n *                      entropy source for future reseeds.\n *\n * \\note Personalization data can be provided in addition to the more generic\n *       entropy source, to make this instantiation as unique as possible.\n *\n * \\param ctx           The CTR_DRBG context to seed.\n * \\param f_entropy     The entropy callback, taking as arguments the\n *                      \\p p_entropy context, the buffer to fill, and the\n                        length of the buffer.\n * \\param p_entropy     The entropy context.\n * \\param custom        Personalization data, that is device-specific\n                        identifiers. Can be NULL.\n * \\param len           The length of the personalization data.\n *\n * \\return              \\c 0 on success.\n * \\return              #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure.\n */\nint mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx,\n                   int (*f_entropy)(void *, unsigned char *, size_t),\n                   void *p_entropy,\n                   const unsigned char *custom,\n                   size_t len );\n\n/**\n * \\brief               This function clears CTR_CRBG context data.\n *\n * \\param ctx           The CTR_DRBG context to clear.\n */\nvoid mbedtls_ctr_drbg_free( mbedtls_ctr_drbg_context *ctx );\n\n/**\n * \\brief               This function turns prediction resistance on or off.\n *                      The default value is off.\n *\n * \\note                If enabled, entropy is gathered at the beginning of\n *                      every call to mbedtls_ctr_drbg_random_with_add().\n *                      Only use this if your entropy source has sufficient\n *                      throughput.\n *\n * \\param ctx           The CTR_DRBG context.\n * \\param resistance    #MBEDTLS_CTR_DRBG_PR_ON or #MBEDTLS_CTR_DRBG_PR_OFF.\n */\nvoid mbedtls_ctr_drbg_set_prediction_resistance( mbedtls_ctr_drbg_context *ctx,\n                                         int resistance );\n\n/**\n * \\brief               This function sets the amount of entropy grabbed on each\n *                      seed or reseed. The default value is\n *                      #MBEDTLS_CTR_DRBG_ENTROPY_LEN.\n *\n * \\param ctx           The CTR_DRBG context.\n * \\param len           The amount of entropy to grab.\n */\nvoid mbedtls_ctr_drbg_set_entropy_len( mbedtls_ctr_drbg_context *ctx,\n                               size_t len );\n\n/**\n * \\brief               This function sets the reseed interval.\n *                      The default value is #MBEDTLS_CTR_DRBG_RESEED_INTERVAL.\n *\n * \\param ctx           The CTR_DRBG context.\n * \\param interval      The reseed interval.\n */\nvoid mbedtls_ctr_drbg_set_reseed_interval( mbedtls_ctr_drbg_context *ctx,\n                                   int interval );\n\n/**\n * \\brief               This function reseeds the CTR_DRBG context, that is\n *                      extracts data from the entropy source.\n *\n * \\param ctx           The CTR_DRBG context.\n * \\param additional    Additional data to add to the state. Can be NULL.\n * \\param len           The length of the additional data.\n *\n * \\return              \\c 0 on success.\n * \\return              #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure.\n */\nint mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,\n                     const unsigned char *additional, size_t len );\n\n/**\n * \\brief              This function updates the state of the CTR_DRBG context.\n *\n * \\note               If \\p add_len is greater than\n *                     #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT, only the first\n *                     #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT Bytes are used.\n *                     The remaining Bytes are silently discarded.\n *\n * \\param ctx          The CTR_DRBG context.\n * \\param additional   The data to update the state with.\n * \\param add_len      Length of \\p additional data.\n *\n */\nvoid mbedtls_ctr_drbg_update( mbedtls_ctr_drbg_context *ctx,\n                      const unsigned char *additional, size_t add_len );\n\n/**\n * \\brief   This function updates a CTR_DRBG instance with additional\n *          data and uses it to generate random data.\n *\n * \\note    The function automatically reseeds if the reseed counter is exceeded.\n *\n * \\param p_rng         The CTR_DRBG context. This must be a pointer to a\n *                      #mbedtls_ctr_drbg_context structure.\n * \\param output        The buffer to fill.\n * \\param output_len    The length of the buffer.\n * \\param additional    Additional data to update. Can be NULL.\n * \\param add_len       The length of the additional data.\n *\n * \\return    \\c 0 on success.\n * \\return    #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or\n *            #MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG on failure.\n */\nint mbedtls_ctr_drbg_random_with_add( void *p_rng,\n                              unsigned char *output, size_t output_len,\n                              const unsigned char *additional, size_t add_len );\n\n/**\n * \\brief   This function uses CTR_DRBG to generate random data.\n *\n * \\note    The function automatically reseeds if the reseed counter is exceeded.\n *\n * \\param p_rng         The CTR_DRBG context. This must be a pointer to a\n *                      #mbedtls_ctr_drbg_context structure.\n * \\param output        The buffer to fill.\n * \\param output_len    The length of the buffer.\n *\n * \\return              \\c 0 on success.\n * \\return              #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or\n *                      #MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG on failure.\n */\nint mbedtls_ctr_drbg_random( void *p_rng,\n                     unsigned char *output, size_t output_len );\n\n#if defined(MBEDTLS_FS_IO)\n/**\n * \\brief               This function writes a seed file.\n *\n * \\param ctx           The CTR_DRBG context.\n * \\param path          The name of the file.\n *\n * \\return              \\c 0 on success.\n * \\return              #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error.\n * \\return              #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on\n *                      failure.\n */\nint mbedtls_ctr_drbg_write_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path );\n\n/**\n * \\brief               This function reads and updates a seed file. The seed\n *                      is added to this instance.\n *\n * \\param ctx           The CTR_DRBG context.\n * \\param path          The name of the file.\n *\n * \\return              \\c 0 on success.\n * \\return              #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error.\n * \\return              #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or\n *                      #MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG on failure.\n */\nint mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path );\n#endif /* MBEDTLS_FS_IO */\n\n/**\n * \\brief               The CTR_DRBG checkup routine.\n *\n * \\return              \\c 0 on success.\n * \\return              \\c 1 on failure.\n */\nint mbedtls_ctr_drbg_self_test( int verbose );\n\n/* Internal functions (do not call directly) */\nint mbedtls_ctr_drbg_seed_entropy_len( mbedtls_ctr_drbg_context *,\n                               int (*)(void *, unsigned char *, size_t), void *,\n                               const unsigned char *, size_t, size_t );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* ctr_drbg.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/debug.h",
    "content": "/**\n * \\file debug.h\n *\n * \\brief Functions for controlling and providing debug output from the library.\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_DEBUG_H\n#define MBEDTLS_DEBUG_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include \"ssl.h\"\n\n#if defined(MBEDTLS_ECP_C)\n#include \"ecp.h\"\n#endif\n\n#if defined(MBEDTLS_DEBUG_C)\n\n#define MBEDTLS_DEBUG_STRIP_PARENS( ... )   __VA_ARGS__\n\n#define MBEDTLS_SSL_DEBUG_MSG( level, args )                    \\\n    mbedtls_debug_print_msg( ssl, level, __FILE__, __LINE__,    \\\n                             MBEDTLS_DEBUG_STRIP_PARENS args )\n\n#define MBEDTLS_SSL_DEBUG_RET( level, text, ret )                \\\n    mbedtls_debug_print_ret( ssl, level, __FILE__, __LINE__, text, ret )\n\n#define MBEDTLS_SSL_DEBUG_BUF( level, text, buf, len )           \\\n    mbedtls_debug_print_buf( ssl, level, __FILE__, __LINE__, text, buf, len )\n\n#if defined(MBEDTLS_BIGNUM_C)\n#define MBEDTLS_SSL_DEBUG_MPI( level, text, X )                  \\\n    mbedtls_debug_print_mpi( ssl, level, __FILE__, __LINE__, text, X )\n#endif\n\n#if defined(MBEDTLS_ECP_C)\n#define MBEDTLS_SSL_DEBUG_ECP( level, text, X )                  \\\n    mbedtls_debug_print_ecp( ssl, level, __FILE__, __LINE__, text, X )\n#endif\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n#define MBEDTLS_SSL_DEBUG_CRT( level, text, crt )                \\\n    mbedtls_debug_print_crt( ssl, level, __FILE__, __LINE__, text, crt )\n#endif\n\n#else /* MBEDTLS_DEBUG_C */\n\n#define MBEDTLS_SSL_DEBUG_MSG( level, args )            do { } while( 0 )\n#define MBEDTLS_SSL_DEBUG_RET( level, text, ret )       do { } while( 0 )\n#define MBEDTLS_SSL_DEBUG_BUF( level, text, buf, len )  do { } while( 0 )\n#define MBEDTLS_SSL_DEBUG_MPI( level, text, X )         do { } while( 0 )\n#define MBEDTLS_SSL_DEBUG_ECP( level, text, X )         do { } while( 0 )\n#define MBEDTLS_SSL_DEBUG_CRT( level, text, crt )       do { } while( 0 )\n\n#endif /* MBEDTLS_DEBUG_C */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief   Set the threshold error level to handle globally all debug output.\n *          Debug messages that have a level over the threshold value are\n *          discarded.\n *          (Default value: 0 = No debug )\n *\n * \\param threshold     theshold level of messages to filter on. Messages at a\n *                      higher level will be discarded.\n *                          - Debug levels\n *                              - 0 No debug\n *                              - 1 Error\n *                              - 2 State change\n *                              - 3 Informational\n *                              - 4 Verbose\n */\nvoid mbedtls_debug_set_threshold( int threshold );\n\n/**\n * \\brief    Print a message to the debug output. This function is always used\n *          through the MBEDTLS_SSL_DEBUG_MSG() macro, which supplies the ssl\n *          context, file and line number parameters.\n *\n * \\param ssl       SSL context\n * \\param level     error level of the debug message\n * \\param file      file the message has occurred in\n * \\param line      line number the message has occurred at\n * \\param format    format specifier, in printf format\n * \\param ...       variables used by the format specifier\n *\n * \\attention       This function is intended for INTERNAL usage within the\n *                  library only.\n */\nvoid mbedtls_debug_print_msg( const mbedtls_ssl_context *ssl, int level,\n                              const char *file, int line,\n                              const char *format, ... );\n\n/**\n * \\brief   Print the return value of a function to the debug output. This\n *          function is always used through the MBEDTLS_SSL_DEBUG_RET() macro,\n *          which supplies the ssl context, file and line number parameters.\n *\n * \\param ssl       SSL context\n * \\param level     error level of the debug message\n * \\param file      file the error has occurred in\n * \\param line      line number the error has occurred in\n * \\param text      the name of the function that returned the error\n * \\param ret       the return code value\n *\n * \\attention       This function is intended for INTERNAL usage within the\n *                  library only.\n */\nvoid mbedtls_debug_print_ret( const mbedtls_ssl_context *ssl, int level,\n                      const char *file, int line,\n                      const char *text, int ret );\n\n/**\n * \\brief   Output a buffer of size len bytes to the debug output. This function\n *          is always used through the MBEDTLS_SSL_DEBUG_BUF() macro,\n *          which supplies the ssl context, file and line number parameters.\n *\n * \\param ssl       SSL context\n * \\param level     error level of the debug message\n * \\param file      file the error has occurred in\n * \\param line      line number the error has occurred in\n * \\param text      a name or label for the buffer being dumped. Normally the\n *                  variable or buffer name\n * \\param buf       the buffer to be outputted\n * \\param len       length of the buffer\n *\n * \\attention       This function is intended for INTERNAL usage within the\n *                  library only.\n */\nvoid mbedtls_debug_print_buf( const mbedtls_ssl_context *ssl, int level,\n                      const char *file, int line, const char *text,\n                      const unsigned char *buf, size_t len );\n\n#if defined(MBEDTLS_BIGNUM_C)\n/**\n * \\brief   Print a MPI variable to the debug output. This function is always\n *          used through the MBEDTLS_SSL_DEBUG_MPI() macro, which supplies the\n *          ssl context, file and line number parameters.\n *\n * \\param ssl       SSL context\n * \\param level     error level of the debug message\n * \\param file      file the error has occurred in\n * \\param line      line number the error has occurred in\n * \\param text      a name or label for the MPI being output. Normally the\n *                  variable name\n * \\param X         the MPI variable\n *\n * \\attention       This function is intended for INTERNAL usage within the\n *                  library only.\n */\nvoid mbedtls_debug_print_mpi( const mbedtls_ssl_context *ssl, int level,\n                      const char *file, int line,\n                      const char *text, const mbedtls_mpi *X );\n#endif\n\n#if defined(MBEDTLS_ECP_C)\n/**\n * \\brief   Print an ECP point to the debug output. This function is always\n *          used through the MBEDTLS_SSL_DEBUG_ECP() macro, which supplies the\n *          ssl context, file and line number parameters.\n *\n * \\param ssl       SSL context\n * \\param level     error level of the debug message\n * \\param file      file the error has occurred in\n * \\param line      line number the error has occurred in\n * \\param text      a name or label for the ECP point being output. Normally the\n *                  variable name\n * \\param X         the ECP point\n *\n * \\attention       This function is intended for INTERNAL usage within the\n *                  library only.\n */\nvoid mbedtls_debug_print_ecp( const mbedtls_ssl_context *ssl, int level,\n                      const char *file, int line,\n                      const char *text, const mbedtls_ecp_point *X );\n#endif\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n/**\n * \\brief   Print a X.509 certificate structure to the debug output. This\n *          function is always used through the MBEDTLS_SSL_DEBUG_CRT() macro,\n *          which supplies the ssl context, file and line number parameters.\n *\n * \\param ssl       SSL context\n * \\param level     error level of the debug message\n * \\param file      file the error has occurred in\n * \\param line      line number the error has occurred in\n * \\param text      a name or label for the certificate being output\n * \\param crt       X.509 certificate structure\n *\n * \\attention       This function is intended for INTERNAL usage within the\n *                  library only.\n */\nvoid mbedtls_debug_print_crt( const mbedtls_ssl_context *ssl, int level,\n                      const char *file, int line,\n                      const char *text, const mbedtls_x509_crt *crt );\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* debug.h */\n\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/des.h",
    "content": "/**\n * \\file des.h\n *\n * \\brief DES block cipher\n *\n * \\warning   DES is considered a weak cipher and its use constitutes a\n *            security risk. We recommend considering stronger ciphers\n *            instead.\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n *\n */\n#ifndef MBEDTLS_DES_H\n#define MBEDTLS_DES_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n#include <stdint.h>\n\n#define MBEDTLS_DES_ENCRYPT     1\n#define MBEDTLS_DES_DECRYPT     0\n\n#define MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH              -0x0032  /**< The data input has an invalid length. */\n#define MBEDTLS_ERR_DES_HW_ACCEL_FAILED                   -0x0033  /**< DES hardware accelerator failed. */\n\n#define MBEDTLS_DES_KEY_SIZE    8\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_DES_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief          DES context structure\n *\n * \\warning        DES is considered a weak cipher and its use constitutes a\n *                 security risk. We recommend considering stronger ciphers\n *                 instead.\n */\ntypedef struct\n{\n    uint32_t sk[32];            /*!<  DES subkeys       */\n}\nmbedtls_des_context;\n\n/**\n * \\brief          Triple-DES context structure\n */\ntypedef struct\n{\n    uint32_t sk[96];            /*!<  3DES subkeys      */\n}\nmbedtls_des3_context;\n\n#else  /* MBEDTLS_DES_ALT */\n#include \"des_alt.h\"\n#endif /* MBEDTLS_DES_ALT */\n\n/**\n * \\brief          Initialize DES context\n *\n * \\param ctx      DES context to be initialized\n *\n * \\warning        DES is considered a weak cipher and its use constitutes a\n *                 security risk. We recommend considering stronger ciphers\n *                 instead.\n */\nvoid mbedtls_des_init( mbedtls_des_context *ctx );\n\n/**\n * \\brief          Clear DES context\n *\n * \\param ctx      DES context to be cleared\n *\n * \\warning        DES is considered a weak cipher and its use constitutes a\n *                 security risk. We recommend considering stronger ciphers\n *                 instead.\n */\nvoid mbedtls_des_free( mbedtls_des_context *ctx );\n\n/**\n * \\brief          Initialize Triple-DES context\n *\n * \\param ctx      DES3 context to be initialized\n */\nvoid mbedtls_des3_init( mbedtls_des3_context *ctx );\n\n/**\n * \\brief          Clear Triple-DES context\n *\n * \\param ctx      DES3 context to be cleared\n */\nvoid mbedtls_des3_free( mbedtls_des3_context *ctx );\n\n/**\n * \\brief          Set key parity on the given key to odd.\n *\n *                 DES keys are 56 bits long, but each byte is padded with\n *                 a parity bit to allow verification.\n *\n * \\param key      8-byte secret key\n *\n * \\warning        DES is considered a weak cipher and its use constitutes a\n *                 security risk. We recommend considering stronger ciphers\n *                 instead.\n */\nvoid mbedtls_des_key_set_parity( unsigned char key[MBEDTLS_DES_KEY_SIZE] );\n\n/**\n * \\brief          Check that key parity on the given key is odd.\n *\n *                 DES keys are 56 bits long, but each byte is padded with\n *                 a parity bit to allow verification.\n *\n * \\param key      8-byte secret key\n *\n * \\return         0 is parity was ok, 1 if parity was not correct.\n *\n * \\warning        DES is considered a weak cipher and its use constitutes a\n *                 security risk. We recommend considering stronger ciphers\n *                 instead.\n */\nint mbedtls_des_key_check_key_parity( const unsigned char key[MBEDTLS_DES_KEY_SIZE] );\n\n/**\n * \\brief          Check that key is not a weak or semi-weak DES key\n *\n * \\param key      8-byte secret key\n *\n * \\return         0 if no weak key was found, 1 if a weak key was identified.\n *\n * \\warning        DES is considered a weak cipher and its use constitutes a\n *                 security risk. We recommend considering stronger ciphers\n *                 instead.\n */\nint mbedtls_des_key_check_weak( const unsigned char key[MBEDTLS_DES_KEY_SIZE] );\n\n/**\n * \\brief          DES key schedule (56-bit, encryption)\n *\n * \\param ctx      DES context to be initialized\n * \\param key      8-byte secret key\n *\n * \\return         0\n *\n * \\warning        DES is considered a weak cipher and its use constitutes a\n *                 security risk. We recommend considering stronger ciphers\n *                 instead.\n */\nint mbedtls_des_setkey_enc( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] );\n\n/**\n * \\brief          DES key schedule (56-bit, decryption)\n *\n * \\param ctx      DES context to be initialized\n * \\param key      8-byte secret key\n *\n * \\return         0\n *\n * \\warning        DES is considered a weak cipher and its use constitutes a\n *                 security risk. We recommend considering stronger ciphers\n *                 instead.\n */\nint mbedtls_des_setkey_dec( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] );\n\n/**\n * \\brief          Triple-DES key schedule (112-bit, encryption)\n *\n * \\param ctx      3DES context to be initialized\n * \\param key      16-byte secret key\n *\n * \\return         0\n */\nint mbedtls_des3_set2key_enc( mbedtls_des3_context *ctx,\n                      const unsigned char key[MBEDTLS_DES_KEY_SIZE * 2] );\n\n/**\n * \\brief          Triple-DES key schedule (112-bit, decryption)\n *\n * \\param ctx      3DES context to be initialized\n * \\param key      16-byte secret key\n *\n * \\return         0\n */\nint mbedtls_des3_set2key_dec( mbedtls_des3_context *ctx,\n                      const unsigned char key[MBEDTLS_DES_KEY_SIZE * 2] );\n\n/**\n * \\brief          Triple-DES key schedule (168-bit, encryption)\n *\n * \\param ctx      3DES context to be initialized\n * \\param key      24-byte secret key\n *\n * \\return         0\n */\nint mbedtls_des3_set3key_enc( mbedtls_des3_context *ctx,\n                      const unsigned char key[MBEDTLS_DES_KEY_SIZE * 3] );\n\n/**\n * \\brief          Triple-DES key schedule (168-bit, decryption)\n *\n * \\param ctx      3DES context to be initialized\n * \\param key      24-byte secret key\n *\n * \\return         0\n */\nint mbedtls_des3_set3key_dec( mbedtls_des3_context *ctx,\n                      const unsigned char key[MBEDTLS_DES_KEY_SIZE * 3] );\n\n/**\n * \\brief          DES-ECB block encryption/decryption\n *\n * \\param ctx      DES context\n * \\param input    64-bit input block\n * \\param output   64-bit output block\n *\n * \\return         0 if successful\n *\n * \\warning        DES is considered a weak cipher and its use constitutes a\n *                 security risk. We recommend considering stronger ciphers\n *                 instead.\n */\nint mbedtls_des_crypt_ecb( mbedtls_des_context *ctx,\n                    const unsigned char input[8],\n                    unsigned char output[8] );\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n/**\n * \\brief          DES-CBC buffer encryption/decryption\n *\n * \\note           Upon exit, the content of the IV is updated so that you can\n *                 call the function same function again on the following\n *                 block(s) of data and get the same result as if it was\n *                 encrypted in one call. This allows a \"streaming\" usage.\n *                 If on the other hand you need to retain the contents of the\n *                 IV, you should either save it manually or use the cipher\n *                 module instead.\n *\n * \\param ctx      DES context\n * \\param mode     MBEDTLS_DES_ENCRYPT or MBEDTLS_DES_DECRYPT\n * \\param length   length of the input data\n * \\param iv       initialization vector (updated after use)\n * \\param input    buffer holding the input data\n * \\param output   buffer holding the output data\n *\n * \\warning        DES is considered a weak cipher and its use constitutes a\n *                 security risk. We recommend considering stronger ciphers\n *                 instead.\n */\nint mbedtls_des_crypt_cbc( mbedtls_des_context *ctx,\n                    int mode,\n                    size_t length,\n                    unsigned char iv[8],\n                    const unsigned char *input,\n                    unsigned char *output );\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n/**\n * \\brief          3DES-ECB block encryption/decryption\n *\n * \\param ctx      3DES context\n * \\param input    64-bit input block\n * \\param output   64-bit output block\n *\n * \\return         0 if successful\n */\nint mbedtls_des3_crypt_ecb( mbedtls_des3_context *ctx,\n                     const unsigned char input[8],\n                     unsigned char output[8] );\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n/**\n * \\brief          3DES-CBC buffer encryption/decryption\n *\n * \\note           Upon exit, the content of the IV is updated so that you can\n *                 call the function same function again on the following\n *                 block(s) of data and get the same result as if it was\n *                 encrypted in one call. This allows a \"streaming\" usage.\n *                 If on the other hand you need to retain the contents of the\n *                 IV, you should either save it manually or use the cipher\n *                 module instead.\n *\n * \\param ctx      3DES context\n * \\param mode     MBEDTLS_DES_ENCRYPT or MBEDTLS_DES_DECRYPT\n * \\param length   length of the input data\n * \\param iv       initialization vector (updated after use)\n * \\param input    buffer holding the input data\n * \\param output   buffer holding the output data\n *\n * \\return         0 if successful, or MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH\n */\nint mbedtls_des3_crypt_cbc( mbedtls_des3_context *ctx,\n                     int mode,\n                     size_t length,\n                     unsigned char iv[8],\n                     const unsigned char *input,\n                     unsigned char *output );\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n/**\n * \\brief          Internal function for key expansion.\n *                 (Only exposed to allow overriding it,\n *                 see MBEDTLS_DES_SETKEY_ALT)\n *\n * \\param SK       Round keys\n * \\param key      Base key\n *\n * \\warning        DES is considered a weak cipher and its use constitutes a\n *                 security risk. We recommend considering stronger ciphers\n *                 instead.\n */\nvoid mbedtls_des_setkey( uint32_t SK[32],\n                         const unsigned char key[MBEDTLS_DES_KEY_SIZE] );\n\n/**\n * \\brief          Checkup routine\n *\n * \\return         0 if successful, or 1 if the test failed\n */\nint mbedtls_des_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* des.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/dhm.h",
    "content": "/**\n * \\file dhm.h\n *\n * \\brief   This file contains Diffie-Hellman-Merkle (DHM) key exchange\n *          definitions and functions.\n *\n * Diffie-Hellman-Merkle (DHM) key exchange is defined in\n * <em>RFC-2631: Diffie-Hellman Key Agreement Method</em> and\n * <em>Public-Key Cryptography Standards (PKCS) #3: Diffie\n * Hellman Key Agreement Standard</em>.\n *\n * <em>RFC-3526: More Modular Exponential (MODP) Diffie-Hellman groups for\n * Internet Key Exchange (IKE)</em> defines a number of standardized\n * Diffie-Hellman groups for IKE.\n *\n * <em>RFC-5114: Additional Diffie-Hellman Groups for Use with IETF\n * Standards</em> defines a number of standardized Diffie-Hellman\n * groups that can be used.\n *\n * \\warning  The security of the DHM key exchange relies on the proper choice\n *           of prime modulus - optimally, it should be a safe prime. The usage\n *           of non-safe primes both decreases the difficulty of the underlying\n *           discrete logarithm problem and can lead to small subgroup attacks\n *           leaking private exponent bits when invalid public keys are used\n *           and not detected. This is especially relevant if the same DHM\n *           parameters are reused for multiple key exchanges as in static DHM,\n *           while the criticality of small-subgroup attacks is lower for\n *           ephemeral DHM.\n *\n * \\warning  For performance reasons, the code does neither perform primality\n *           nor safe primality tests, nor the expensive checks for invalid\n *           subgroups. Moreover, even if these were performed, non-standardized\n *           primes cannot be trusted because of the possibility of backdoors\n *           that can't be effectively checked for.\n *\n * \\warning  Diffie-Hellman-Merkle is therefore a security risk when not using\n *           standardized primes generated using a trustworthy (\"nothing up\n *           my sleeve\") method, such as the RFC 3526 / 7919 primes. In the TLS\n *           protocol, DH parameters need to be negotiated, so using the default\n *           primes systematically is not always an option. If possible, use\n *           Elliptic Curve Diffie-Hellman (ECDH), which has better performance,\n *           and for which the TLS protocol mandates the use of standard\n *           parameters.\n *\n */\n/*\n *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_DHM_H\n#define MBEDTLS_DHM_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n#include \"bignum.h\"\n\n/*\n * DHM Error codes\n */\n#define MBEDTLS_ERR_DHM_BAD_INPUT_DATA                    -0x3080  /**< Bad input parameters. */\n#define MBEDTLS_ERR_DHM_READ_PARAMS_FAILED                -0x3100  /**< Reading of the DHM parameters failed. */\n#define MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED                -0x3180  /**< Making of the DHM parameters failed. */\n#define MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED                -0x3200  /**< Reading of the public values failed. */\n#define MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED                -0x3280  /**< Making of the public value failed. */\n#define MBEDTLS_ERR_DHM_CALC_SECRET_FAILED                -0x3300  /**< Calculation of the DHM secret failed. */\n#define MBEDTLS_ERR_DHM_INVALID_FORMAT                    -0x3380  /**< The ASN.1 data is not formatted correctly. */\n#define MBEDTLS_ERR_DHM_ALLOC_FAILED                      -0x3400  /**< Allocation of memory failed. */\n#define MBEDTLS_ERR_DHM_FILE_IO_ERROR                     -0x3480  /**< Read or write of file failed. */\n#define MBEDTLS_ERR_DHM_HW_ACCEL_FAILED                   -0x3500  /**< DHM hardware accelerator failed. */\n#define MBEDTLS_ERR_DHM_SET_GROUP_FAILED                  -0x3580  /**< Setting the modulus and generator failed. */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_DHM_ALT)\n\n/**\n * \\brief          The DHM context structure.\n */\ntypedef struct\n{\n    size_t len;         /*!<  The size of \\p P in Bytes. */\n    mbedtls_mpi P;      /*!<  The prime modulus. */\n    mbedtls_mpi G;      /*!<  The generator. */\n    mbedtls_mpi X;      /*!<  Our secret value. */\n    mbedtls_mpi GX;     /*!<  Our public key = \\c G^X mod \\c P. */\n    mbedtls_mpi GY;     /*!<  The public key of the peer = \\c G^Y mod \\c P. */\n    mbedtls_mpi K;      /*!<  The shared secret = \\c G^(XY) mod \\c P. */\n    mbedtls_mpi RP;     /*!<  The cached value = \\c R^2 mod \\c P. */\n    mbedtls_mpi Vi;     /*!<  The blinding value. */\n    mbedtls_mpi Vf;     /*!<  The unblinding value. */\n    mbedtls_mpi pX;     /*!<  The previous \\c X. */\n}\nmbedtls_dhm_context;\n\n#else /* MBEDTLS_DHM_ALT */\n#include \"dhm_alt.h\"\n#endif /* MBEDTLS_DHM_ALT */\n\n/**\n * \\brief          This function initializes the DHM context.\n *\n * \\param ctx      The DHM context to initialize.\n */\nvoid mbedtls_dhm_init( mbedtls_dhm_context *ctx );\n\n/**\n * \\brief          This function parses the ServerKeyExchange parameters.\n *\n * \\param ctx      The DHM context.\n * \\param p        On input, *p must be the start of the input buffer.\n *                 On output, *p is updated to point to the end of the data\n *                 that has been read. On success, this is the first byte\n *                 past the end of the ServerKeyExchange parameters.\n *                 On error, this is the point at which an error has been\n *                 detected, which is usually not useful except to debug\n *                 failures.\n * \\param end      The end of the input buffer.\n *\n * \\return         \\c 0 on success.\n * \\return         An \\c MBEDTLS_ERR_DHM_XXX error code on failure.\n */\nint mbedtls_dhm_read_params( mbedtls_dhm_context *ctx,\n                     unsigned char **p,\n                     const unsigned char *end );\n\n/**\n * \\brief          This function sets up and writes the ServerKeyExchange\n *                 parameters.\n *\n * \\note           The destination buffer must be large enough to hold\n *                 the reduced binary presentation of the modulus, the generator\n *                 and the public key, each wrapped with a 2-byte length field.\n *                 It is the responsibility of the caller to ensure that enough\n *                 space is available. Refer to \\c mbedtls_mpi_size to computing\n *                 the byte-size of an MPI.\n *\n * \\note           This function assumes that \\c ctx->P and \\c ctx->G\n *                 have already been properly set. For that, use\n *                 mbedtls_dhm_set_group() below in conjunction with\n *                 mbedtls_mpi_read_binary() and mbedtls_mpi_read_string().\n *\n * \\param ctx      The DHM context.\n * \\param x_size   The private key size in Bytes.\n * \\param olen     The number of characters written.\n * \\param output   The destination buffer.\n * \\param f_rng    The RNG function.\n * \\param p_rng    The RNG context.\n *\n * \\return         \\c 0 on success.\n * \\return         An \\c MBEDTLS_ERR_DHM_XXX error code on failure.\n */\nint mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size,\n                     unsigned char *output, size_t *olen,\n                     int (*f_rng)(void *, unsigned char *, size_t),\n                     void *p_rng );\n\n/**\n * \\brief          This function sets the prime modulus and generator.\n *\n * \\note           This function can be used to set \\p P, \\p G\n *                 in preparation for mbedtls_dhm_make_params().\n *\n * \\param ctx      The DHM context.\n * \\param P        The MPI holding the DHM prime modulus.\n * \\param G        The MPI holding the DHM generator.\n *\n * \\return         \\c 0 if successful.\n * \\return         An \\c MBEDTLS_ERR_DHM_XXX error code on failure.\n */\nint mbedtls_dhm_set_group( mbedtls_dhm_context *ctx,\n                           const mbedtls_mpi *P,\n                           const mbedtls_mpi *G );\n\n/**\n * \\brief          This function imports the public value of the peer, G^Y.\n *\n * \\param ctx      The DHM context.\n * \\param input    The input buffer containing the G^Y value of the peer.\n * \\param ilen     The size of the input buffer.\n *\n * \\return         \\c 0 on success.\n * \\return         An \\c MBEDTLS_ERR_DHM_XXX error code on failure.\n */\nint mbedtls_dhm_read_public( mbedtls_dhm_context *ctx,\n                     const unsigned char *input, size_t ilen );\n\n/**\n * \\brief          This function creates its own private key, \\c X, and\n *                 exports \\c G^X.\n *\n * \\note           The destination buffer is always fully written\n *                 so as to contain a big-endian representation of G^X mod P.\n *                 If it is larger than ctx->len, it is padded accordingly\n *                 with zero-bytes at the beginning.\n *\n * \\param ctx      The DHM context.\n * \\param x_size   The private key size in Bytes.\n * \\param output   The destination buffer.\n * \\param olen     The length of the destination buffer. Must be at least\n *                  equal to ctx->len (the size of \\c P).\n * \\param f_rng    The RNG function.\n * \\param p_rng    The RNG context.\n *\n * \\return         \\c 0 on success.\n * \\return         An \\c MBEDTLS_ERR_DHM_XXX error code on failure.\n */\nint mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size,\n                     unsigned char *output, size_t olen,\n                     int (*f_rng)(void *, unsigned char *, size_t),\n                     void *p_rng );\n\n/**\n * \\brief               This function derives and exports the shared secret\n *                      \\c (G^Y)^X mod \\c P.\n *\n * \\note                If \\p f_rng is not NULL, it is used to blind the input as\n *                      a countermeasure against timing attacks. Blinding is used\n *                      only if our private key \\c X is re-used, and not used\n *                      otherwise. We recommend always passing a non-NULL\n *                      \\p f_rng argument.\n *\n * \\param ctx           The DHM context.\n * \\param output        The destination buffer.\n * \\param output_size   The size of the destination buffer. Must be at least\n *                      the size of ctx->len (the size of \\c P).\n * \\param olen          On exit, holds the actual number of Bytes written.\n * \\param f_rng         The RNG function, for blinding purposes.\n * \\param p_rng         The RNG context.\n *\n * \\return              \\c 0 on success.\n * \\return              An \\c MBEDTLS_ERR_DHM_XXX error code on failure.\n */\nint mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx,\n                     unsigned char *output, size_t output_size, size_t *olen,\n                     int (*f_rng)(void *, unsigned char *, size_t),\n                     void *p_rng );\n\n/**\n * \\brief          This function frees and clears the components of a DHM context.\n *\n * \\param ctx      The DHM context to free and clear.\n */\nvoid mbedtls_dhm_free( mbedtls_dhm_context *ctx );\n\n#if defined(MBEDTLS_ASN1_PARSE_C)\n/** \\ingroup x509_module */\n/**\n * \\brief             This function parses DHM parameters in PEM or DER format.\n *\n * \\param dhm         The DHM context to initialize.\n * \\param dhmin       The input buffer.\n * \\param dhminlen    The size of the buffer, including the terminating null\n *                    Byte for PEM data.\n *\n * \\return            \\c 0 on success.\n * \\return            An \\c MBEDTLS_ERR_DHM_XXX or \\c MBEDTLS_ERR_PEM_XXX error code\n *                    error code on failure.\n */\nint mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin,\n                   size_t dhminlen );\n\n#if defined(MBEDTLS_FS_IO)\n/** \\ingroup x509_module */\n/**\n * \\brief          This function loads and parses DHM parameters from a file.\n *\n * \\param dhm      The DHM context to load the parameters to.\n * \\param path     The filename to read the DHM parameters from.\n *\n * \\return         \\c 0 on success.\n * \\return            An \\c MBEDTLS_ERR_DHM_XXX or \\c MBEDTLS_ERR_PEM_XXX error code\n *                    error code on failure.\n */\nint mbedtls_dhm_parse_dhmfile( mbedtls_dhm_context *dhm, const char *path );\n#endif /* MBEDTLS_FS_IO */\n#endif /* MBEDTLS_ASN1_PARSE_C */\n\n/**\n * \\brief          The DMH checkup routine.\n *\n * \\return         \\c 0 on success.\n * \\return         \\c 1 on failure.\n */\nint mbedtls_dhm_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n/**\n * RFC 3526, RFC 5114 and RFC 7919 standardize a number of\n * Diffie-Hellman groups, some of which are included here\n * for use within the SSL/TLS module and the user's convenience\n * when configuring the Diffie-Hellman parameters by hand\n * through \\c mbedtls_ssl_conf_dh_param.\n *\n * The following lists the source of the above groups in the standards:\n * - RFC 5114 section 2.2:  2048-bit MODP Group with 224-bit Prime Order Subgroup\n * - RFC 3526 section 3:    2048-bit MODP Group\n * - RFC 3526 section 4:    3072-bit MODP Group\n * - RFC 3526 section 5:    4096-bit MODP Group\n * - RFC 7919 section A.1:  ffdhe2048\n * - RFC 7919 section A.2:  ffdhe3072\n * - RFC 7919 section A.3:  ffdhe4096\n * - RFC 7919 section A.4:  ffdhe6144\n * - RFC 7919 section A.5:  ffdhe8192\n *\n * The constants with suffix \"_p\" denote the chosen prime moduli, while\n * the constants with suffix \"_g\" denote the chosen generator\n * of the associated prime field.\n *\n * The constants further suffixed with \"_bin\" are provided in binary format,\n * while all other constants represent null-terminated strings holding the\n * hexadecimal presentation of the respective numbers.\n *\n * The primes from RFC 3526 and RFC 7919 have been generating by the following\n * trust-worthy procedure:\n * - Fix N in { 2048, 3072, 4096, 6144, 8192 } and consider the N-bit number\n *   the first and last 64 bits are all 1, and the remaining N - 128 bits of\n *   which are 0x7ff...ff.\n * - Add the smallest multiple of the first N - 129 bits of the binary expansion\n *   of pi (for RFC 5236) or e (for RFC 7919) to this intermediate bit-string\n *   such that the resulting integer is a safe-prime.\n * - The result is the respective RFC 3526 / 7919 prime, and the corresponding\n *   generator is always chosen to be 2 (which is a square for these prime,\n *   hence the corresponding subgroup has order (p-1)/2 and avoids leaking a\n *   bit in the private exponent).\n *\n */\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED __attribute__((deprecated))\nMBEDTLS_DEPRECATED typedef char const * mbedtls_deprecated_constant_t;\n#define MBEDTLS_DEPRECATED_STRING_CONSTANT( VAL )       \\\n    ( (mbedtls_deprecated_constant_t) ( VAL ) )\n#else\n#define MBEDTLS_DEPRECATED_STRING_CONSTANT( VAL ) VAL\n#endif /* ! MBEDTLS_DEPRECATED_WARNING */\n\n/**\n * \\warning The origin of the primes in RFC 5114 is not documented and\n *          their use therefore constitutes a security risk!\n *\n * \\deprecated The hex-encoded primes from RFC 5114 are deprecated and are\n *             likely to be removed in a future version of the library without\n *             replacement.\n */\n\n/**\n * The hexadecimal presentation of the prime underlying the\n * 2048-bit MODP Group with 224-bit Prime Order Subgroup, as defined\n * in <em>RFC-5114: Additional Diffie-Hellman Groups for Use with\n * IETF Standards</em>.\n */\n#define MBEDTLS_DHM_RFC5114_MODP_2048_P                         \\\n    MBEDTLS_DEPRECATED_STRING_CONSTANT(                         \\\n        \"AD107E1E9123A9D0D660FAA79559C51FA20D64E5683B9FD1\"      \\\n        \"B54B1597B61D0A75E6FA141DF95A56DBAF9A3C407BA1DF15\"      \\\n        \"EB3D688A309C180E1DE6B85A1274A0A66D3F8152AD6AC212\"      \\\n        \"9037C9EDEFDA4DF8D91E8FEF55B7394B7AD5B7D0B6C12207\"      \\\n        \"C9F98D11ED34DBF6C6BA0B2C8BBC27BE6A00E0A0B9C49708\"      \\\n        \"B3BF8A317091883681286130BC8985DB1602E714415D9330\"      \\\n        \"278273C7DE31EFDC7310F7121FD5A07415987D9ADC0A486D\"      \\\n        \"CDF93ACC44328387315D75E198C641A480CD86A1B9E587E8\"      \\\n        \"BE60E69CC928B2B9C52172E413042E9B23F10B0E16E79763\"      \\\n        \"C9B53DCF4BA80A29E3FB73C16B8E75B97EF363E2FFA31F71\"      \\\n        \"CF9DE5384E71B81C0AC4DFFE0C10E64F\" )\n\n/**\n * The hexadecimal presentation of the chosen generator of the 2048-bit MODP\n * Group with 224-bit Prime Order Subgroup, as defined in <em>RFC-5114:\n * Additional Diffie-Hellman Groups for Use with IETF Standards</em>.\n */\n#define MBEDTLS_DHM_RFC5114_MODP_2048_G                         \\\n    MBEDTLS_DEPRECATED_STRING_CONSTANT(                         \\\n        \"AC4032EF4F2D9AE39DF30B5C8FFDAC506CDEBE7B89998CAF\"      \\\n        \"74866A08CFE4FFE3A6824A4E10B9A6F0DD921F01A70C4AFA\"      \\\n        \"AB739D7700C29F52C57DB17C620A8652BE5E9001A8D66AD7\"      \\\n        \"C17669101999024AF4D027275AC1348BB8A762D0521BC98A\"      \\\n        \"E247150422EA1ED409939D54DA7460CDB5F6C6B250717CBE\"      \\\n        \"F180EB34118E98D119529A45D6F834566E3025E316A330EF\"      \\\n        \"BB77A86F0C1AB15B051AE3D428C8F8ACB70A8137150B8EEB\"      \\\n        \"10E183EDD19963DDD9E263E4770589EF6AA21E7F5F2FF381\"      \\\n        \"B539CCE3409D13CD566AFBB48D6C019181E1BCFE94B30269\"      \\\n        \"EDFE72FE9B6AA4BD7B5A0F1C71CFFF4C19C418E1F6EC0179\"      \\\n        \"81BC087F2A7065B384B890D3191F2BFA\" )\n\n/**\n * The hexadecimal presentation of the prime underlying the 2048-bit MODP\n * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP)\n * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.\n *\n * \\deprecated The hex-encoded primes from RFC 3625 are deprecated and\n *             superseded by the corresponding macros providing them as\n *             binary constants. Their hex-encoded constants are likely\n *             to be removed in a future version of the library.\n *\n */\n#define MBEDTLS_DHM_RFC3526_MODP_2048_P                         \\\n    MBEDTLS_DEPRECATED_STRING_CONSTANT(                         \\\n        \"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\"      \\\n        \"29024E088A67CC74020BBEA63B139B22514A08798E3404DD\"      \\\n        \"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\"      \\\n        \"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\"      \\\n        \"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\"      \\\n        \"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\"      \\\n        \"83655D23DCA3AD961C62F356208552BB9ED529077096966D\"      \\\n        \"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B\"      \\\n        \"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9\"      \\\n        \"DE2BCBF6955817183995497CEA956AE515D2261898FA0510\"      \\\n        \"15728E5A8AACAA68FFFFFFFFFFFFFFFF\" )\n\n/**\n * The hexadecimal presentation of the chosen generator of the 2048-bit MODP\n * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP)\n * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.\n */\n#define MBEDTLS_DHM_RFC3526_MODP_2048_G                         \\\n    MBEDTLS_DEPRECATED_STRING_CONSTANT( \"02\" )\n\n/**\n * The hexadecimal presentation of the prime underlying the 3072-bit MODP\n * Group, as defined in <em>RFC-3072: More Modular Exponential (MODP)\n * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.\n */\n#define MBEDTLS_DHM_RFC3526_MODP_3072_P                         \\\n    MBEDTLS_DEPRECATED_STRING_CONSTANT(                         \\\n        \"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\"      \\\n        \"29024E088A67CC74020BBEA63B139B22514A08798E3404DD\"      \\\n        \"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\"      \\\n        \"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\"      \\\n        \"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\"      \\\n        \"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\"      \\\n        \"83655D23DCA3AD961C62F356208552BB9ED529077096966D\"      \\\n        \"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B\"      \\\n        \"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9\"      \\\n        \"DE2BCBF6955817183995497CEA956AE515D2261898FA0510\"      \\\n        \"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64\"      \\\n        \"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7\"      \\\n        \"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B\"      \\\n        \"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C\"      \\\n        \"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31\"      \\\n        \"43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF\" )\n\n/**\n * The hexadecimal presentation of the chosen generator of the 3072-bit MODP\n * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP)\n * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.\n */\n#define MBEDTLS_DHM_RFC3526_MODP_3072_G                      \\\n    MBEDTLS_DEPRECATED_STRING_CONSTANT( \"02\" )\n\n/**\n * The hexadecimal presentation of the prime underlying the 4096-bit MODP\n * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP)\n * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.\n */\n#define MBEDTLS_DHM_RFC3526_MODP_4096_P                      \\\n    MBEDTLS_DEPRECATED_STRING_CONSTANT(                      \\\n        \"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\"   \\\n        \"29024E088A67CC74020BBEA63B139B22514A08798E3404DD\"   \\\n        \"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\"   \\\n        \"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\"   \\\n        \"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\"   \\\n        \"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\"   \\\n        \"83655D23DCA3AD961C62F356208552BB9ED529077096966D\"   \\\n        \"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B\"   \\\n        \"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9\"   \\\n        \"DE2BCBF6955817183995497CEA956AE515D2261898FA0510\"   \\\n        \"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64\"   \\\n        \"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7\"   \\\n        \"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B\"   \\\n        \"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C\"   \\\n        \"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31\"   \\\n        \"43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7\"   \\\n        \"88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA\"   \\\n        \"2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6\"   \\\n        \"287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED\"   \\\n        \"1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9\"   \\\n        \"93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199\"   \\\n        \"FFFFFFFFFFFFFFFF\" )\n\n/**\n * The hexadecimal presentation of the chosen generator of the 4096-bit MODP\n * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP)\n * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.\n */\n#define MBEDTLS_DHM_RFC3526_MODP_4096_G                      \\\n    MBEDTLS_DEPRECATED_STRING_CONSTANT( \"02\" )\n\n#endif /* MBEDTLS_DEPRECATED_REMOVED */\n\n/*\n * Trustworthy DHM parameters in binary form\n */\n\n#define MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN {        \\\n     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \\\n     0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \\\n     0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \\\n     0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \\\n     0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \\\n     0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \\\n     0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \\\n     0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \\\n     0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \\\n     0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \\\n     0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \\\n     0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \\\n     0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \\\n     0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \\\n     0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \\\n     0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \\\n     0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \\\n     0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \\\n     0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \\\n     0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \\\n     0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \\\n     0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \\\n     0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \\\n     0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \\\n     0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \\\n     0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \\\n     0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \\\n     0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \\\n     0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \\\n     0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \\\n     0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAC, 0xAA, 0x68, \\\n     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }\n\n#define MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN { 0x02 }\n\n#define MBEDTLS_DHM_RFC3526_MODP_3072_P_BIN {       \\\n    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \\\n    0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \\\n    0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \\\n    0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \\\n    0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \\\n    0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \\\n    0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \\\n    0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \\\n    0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \\\n    0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \\\n    0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \\\n    0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \\\n    0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \\\n    0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \\\n    0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \\\n    0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \\\n    0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \\\n    0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \\\n    0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \\\n    0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \\\n    0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \\\n    0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \\\n    0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \\\n    0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \\\n    0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \\\n    0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \\\n    0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \\\n    0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \\\n    0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \\\n    0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \\\n    0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D, \\\n    0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33, \\\n    0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64, \\\n    0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A, \\\n    0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D, \\\n    0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7, \\\n    0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7, \\\n    0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D, \\\n    0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B, \\\n    0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64, \\\n    0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64, \\\n    0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C, \\\n    0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C, \\\n    0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2, \\\n    0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31, \\\n    0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E, \\\n    0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x3A, 0xD2, 0xCA, \\\n    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }\n\n#define MBEDTLS_DHM_RFC3526_MODP_3072_G_BIN { 0x02 }\n\n#define MBEDTLS_DHM_RFC3526_MODP_4096_P_BIN  {       \\\n    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  \\\n    0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,  \\\n    0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1,  \\\n    0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,  \\\n    0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22,  \\\n    0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,  \\\n    0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B,  \\\n    0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,  \\\n    0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45,  \\\n    0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,  \\\n    0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B,  \\\n    0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,  \\\n    0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5,  \\\n    0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,  \\\n    0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D,  \\\n    0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,  \\\n    0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A,  \\\n    0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,  \\\n    0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96,  \\\n    0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,  \\\n    0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D,  \\\n    0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,  \\\n    0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C,  \\\n    0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B,  \\\n    0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03,  \\\n    0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F,  \\\n    0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9,  \\\n    0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18,  \\\n    0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5,  \\\n    0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10,  \\\n    0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D,  \\\n    0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33,  \\\n    0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64,  \\\n    0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A,  \\\n    0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D,  \\\n    0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7,  \\\n    0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7,  \\\n    0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D,  \\\n    0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B,  \\\n    0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64,  \\\n    0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64,  \\\n    0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C,  \\\n    0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C,  \\\n    0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2,  \\\n    0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31,  \\\n    0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E,  \\\n    0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x21, 0x08, 0x01,  \\\n    0x1A, 0x72, 0x3C, 0x12, 0xA7, 0x87, 0xE6, 0xD7,  \\\n    0x88, 0x71, 0x9A, 0x10, 0xBD, 0xBA, 0x5B, 0x26,  \\\n    0x99, 0xC3, 0x27, 0x18, 0x6A, 0xF4, 0xE2, 0x3C,  \\\n    0x1A, 0x94, 0x68, 0x34, 0xB6, 0x15, 0x0B, 0xDA,  \\\n    0x25, 0x83, 0xE9, 0xCA, 0x2A, 0xD4, 0x4C, 0xE8,  \\\n    0xDB, 0xBB, 0xC2, 0xDB, 0x04, 0xDE, 0x8E, 0xF9,  \\\n    0x2E, 0x8E, 0xFC, 0x14, 0x1F, 0xBE, 0xCA, 0xA6,  \\\n    0x28, 0x7C, 0x59, 0x47, 0x4E, 0x6B, 0xC0, 0x5D,  \\\n    0x99, 0xB2, 0x96, 0x4F, 0xA0, 0x90, 0xC3, 0xA2,  \\\n    0x23, 0x3B, 0xA1, 0x86, 0x51, 0x5B, 0xE7, 0xED,  \\\n    0x1F, 0x61, 0x29, 0x70, 0xCE, 0xE2, 0xD7, 0xAF,  \\\n    0xB8, 0x1B, 0xDD, 0x76, 0x21, 0x70, 0x48, 0x1C,  \\\n    0xD0, 0x06, 0x91, 0x27, 0xD5, 0xB0, 0x5A, 0xA9,  \\\n    0x93, 0xB4, 0xEA, 0x98, 0x8D, 0x8F, 0xDD, 0xC1,  \\\n    0x86, 0xFF, 0xB7, 0xDC, 0x90, 0xA6, 0xC0, 0x8F,  \\\n    0x4D, 0xF4, 0x35, 0xC9, 0x34, 0x06, 0x31, 0x99,  \\\n    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }\n\n#define MBEDTLS_DHM_RFC3526_MODP_4096_G_BIN { 0x02 }\n\n#define MBEDTLS_DHM_RFC7919_FFDHE2048_P_BIN {        \\\n     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \\\n     0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \\\n     0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \\\n     0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \\\n     0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \\\n     0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \\\n     0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \\\n     0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \\\n     0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \\\n     0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \\\n     0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \\\n     0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \\\n     0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \\\n     0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \\\n     0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \\\n     0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \\\n     0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \\\n     0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \\\n     0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \\\n     0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \\\n     0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \\\n     0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \\\n     0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \\\n     0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \\\n     0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \\\n     0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \\\n     0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \\\n     0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \\\n     0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \\\n     0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \\\n     0x88, 0x6B, 0x42, 0x38, 0x61, 0x28, 0x5C, 0x97, \\\n     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }\n\n#define MBEDTLS_DHM_RFC7919_FFDHE2048_G_BIN { 0x02 }\n\n#define MBEDTLS_DHM_RFC7919_FFDHE3072_P_BIN { \\\n     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \\\n     0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \\\n     0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \\\n     0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \\\n     0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \\\n     0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \\\n     0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \\\n     0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \\\n     0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \\\n     0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \\\n     0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \\\n     0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \\\n     0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \\\n     0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \\\n     0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \\\n     0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \\\n     0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \\\n     0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \\\n     0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \\\n     0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \\\n     0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \\\n     0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \\\n     0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \\\n     0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \\\n     0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \\\n     0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \\\n     0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \\\n     0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \\\n     0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \\\n     0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \\\n     0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \\\n     0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \\\n     0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \\\n     0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \\\n     0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \\\n     0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \\\n     0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \\\n     0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \\\n     0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \\\n     0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \\\n     0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \\\n     0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \\\n     0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \\\n     0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \\\n     0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \\\n     0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \\\n     0x25, 0xE4, 0x1D, 0x2B, 0x66, 0xC6, 0x2E, 0x37, \\\n     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }\n\n#define MBEDTLS_DHM_RFC7919_FFDHE3072_G_BIN { 0x02 }\n\n#define MBEDTLS_DHM_RFC7919_FFDHE4096_P_BIN {        \\\n     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \\\n     0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \\\n     0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \\\n     0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \\\n     0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \\\n     0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \\\n     0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \\\n     0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \\\n     0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \\\n     0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \\\n     0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \\\n     0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \\\n     0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \\\n     0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \\\n     0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \\\n     0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \\\n     0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \\\n     0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \\\n     0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \\\n     0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \\\n     0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \\\n     0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \\\n     0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \\\n     0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \\\n     0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \\\n     0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \\\n     0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \\\n     0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \\\n     0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \\\n     0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \\\n     0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \\\n     0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \\\n     0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \\\n     0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \\\n     0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \\\n     0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \\\n     0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \\\n     0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \\\n     0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \\\n     0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \\\n     0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \\\n     0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \\\n     0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \\\n     0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \\\n     0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \\\n     0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \\\n     0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \\\n     0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \\\n     0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \\\n     0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \\\n     0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \\\n     0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \\\n     0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \\\n     0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \\\n     0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \\\n     0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \\\n     0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \\\n     0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \\\n     0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \\\n     0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \\\n     0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \\\n     0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \\\n     0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x65, 0x5F, 0x6A, \\\n     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }\n\n#define MBEDTLS_DHM_RFC7919_FFDHE4096_G_BIN { 0x02 }\n\n#define MBEDTLS_DHM_RFC7919_FFDHE6144_P_BIN {        \\\n     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \\\n     0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \\\n     0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \\\n     0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \\\n     0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \\\n     0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \\\n     0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \\\n     0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \\\n     0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \\\n     0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \\\n     0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \\\n     0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \\\n     0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \\\n     0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \\\n     0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \\\n     0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \\\n     0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \\\n     0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \\\n     0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \\\n     0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \\\n     0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \\\n     0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \\\n     0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \\\n     0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \\\n     0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \\\n     0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \\\n     0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \\\n     0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \\\n     0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \\\n     0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \\\n     0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \\\n     0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \\\n     0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \\\n     0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \\\n     0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \\\n     0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \\\n     0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \\\n     0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \\\n     0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \\\n     0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \\\n     0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \\\n     0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \\\n     0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \\\n     0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \\\n     0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \\\n     0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \\\n     0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \\\n     0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \\\n     0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \\\n     0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \\\n     0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \\\n     0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \\\n     0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \\\n     0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \\\n     0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \\\n     0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \\\n     0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \\\n     0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \\\n     0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \\\n     0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \\\n     0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \\\n     0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \\\n     0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02, \\\n     0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A, \\\n     0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A, \\\n     0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6, \\\n     0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8, \\\n     0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C, \\\n     0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A, \\\n     0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71, \\\n     0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F, \\\n     0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77, \\\n     0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10, \\\n     0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8, \\\n     0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3, \\\n     0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E, \\\n     0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3, \\\n     0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4, \\\n     0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1, \\\n     0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92, \\\n     0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6, \\\n     0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82, \\\n     0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE, \\\n     0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C, \\\n     0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E, \\\n     0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46, \\\n     0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A, \\\n     0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17, \\\n     0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03, \\\n     0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04, \\\n     0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6, \\\n     0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69, \\\n     0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1, \\\n     0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4, \\\n     0xA4, 0x0E, 0x32, 0x9C, 0xD0, 0xE4, 0x0E, 0x65, \\\n     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }\n\n#define MBEDTLS_DHM_RFC7919_FFDHE6144_G_BIN { 0x02 }\n\n#define MBEDTLS_DHM_RFC7919_FFDHE8192_P_BIN {        \\\n     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \\\n     0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \\\n     0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \\\n     0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \\\n     0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \\\n     0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \\\n     0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \\\n     0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \\\n     0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \\\n     0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \\\n     0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \\\n     0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \\\n     0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \\\n     0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \\\n     0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \\\n     0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \\\n     0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \\\n     0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \\\n     0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \\\n     0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \\\n     0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \\\n     0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \\\n     0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \\\n     0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \\\n     0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \\\n     0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \\\n     0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \\\n     0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \\\n     0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \\\n     0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \\\n     0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \\\n     0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \\\n     0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \\\n     0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \\\n     0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \\\n     0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \\\n     0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \\\n     0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \\\n     0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \\\n     0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \\\n     0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \\\n     0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \\\n     0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \\\n     0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \\\n     0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \\\n     0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \\\n     0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \\\n     0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \\\n     0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \\\n     0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \\\n     0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \\\n     0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \\\n     0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \\\n     0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \\\n     0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \\\n     0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \\\n     0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \\\n     0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \\\n     0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \\\n     0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \\\n     0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \\\n     0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \\\n     0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02, \\\n     0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A, \\\n     0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A, \\\n     0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6, \\\n     0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8, \\\n     0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C, \\\n     0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A, \\\n     0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71, \\\n     0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F, \\\n     0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77, \\\n     0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10, \\\n     0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8, \\\n     0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3, \\\n     0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E, \\\n     0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3, \\\n     0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4, \\\n     0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1, \\\n     0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92, \\\n     0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6, \\\n     0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82, \\\n     0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE, \\\n     0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C, \\\n     0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E, \\\n     0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46, \\\n     0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A, \\\n     0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17, \\\n     0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03, \\\n     0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04, \\\n     0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6, \\\n     0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69, \\\n     0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1, \\\n     0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4, \\\n     0xA4, 0x0E, 0x32, 0x9C, 0xCF, 0xF4, 0x6A, 0xAA, \\\n     0x36, 0xAD, 0x00, 0x4C, 0xF6, 0x00, 0xC8, 0x38, \\\n     0x1E, 0x42, 0x5A, 0x31, 0xD9, 0x51, 0xAE, 0x64, \\\n     0xFD, 0xB2, 0x3F, 0xCE, 0xC9, 0x50, 0x9D, 0x43, \\\n     0x68, 0x7F, 0xEB, 0x69, 0xED, 0xD1, 0xCC, 0x5E, \\\n     0x0B, 0x8C, 0xC3, 0xBD, 0xF6, 0x4B, 0x10, 0xEF, \\\n     0x86, 0xB6, 0x31, 0x42, 0xA3, 0xAB, 0x88, 0x29, \\\n     0x55, 0x5B, 0x2F, 0x74, 0x7C, 0x93, 0x26, 0x65, \\\n     0xCB, 0x2C, 0x0F, 0x1C, 0xC0, 0x1B, 0xD7, 0x02, \\\n     0x29, 0x38, 0x88, 0x39, 0xD2, 0xAF, 0x05, 0xE4, \\\n     0x54, 0x50, 0x4A, 0xC7, 0x8B, 0x75, 0x82, 0x82, \\\n     0x28, 0x46, 0xC0, 0xBA, 0x35, 0xC3, 0x5F, 0x5C, \\\n     0x59, 0x16, 0x0C, 0xC0, 0x46, 0xFD, 0x82, 0x51, \\\n     0x54, 0x1F, 0xC6, 0x8C, 0x9C, 0x86, 0xB0, 0x22, \\\n     0xBB, 0x70, 0x99, 0x87, 0x6A, 0x46, 0x0E, 0x74, \\\n     0x51, 0xA8, 0xA9, 0x31, 0x09, 0x70, 0x3F, 0xEE, \\\n     0x1C, 0x21, 0x7E, 0x6C, 0x38, 0x26, 0xE5, 0x2C, \\\n     0x51, 0xAA, 0x69, 0x1E, 0x0E, 0x42, 0x3C, 0xFC, \\\n     0x99, 0xE9, 0xE3, 0x16, 0x50, 0xC1, 0x21, 0x7B, \\\n     0x62, 0x48, 0x16, 0xCD, 0xAD, 0x9A, 0x95, 0xF9, \\\n     0xD5, 0xB8, 0x01, 0x94, 0x88, 0xD9, 0xC0, 0xA0, \\\n     0xA1, 0xFE, 0x30, 0x75, 0xA5, 0x77, 0xE2, 0x31, \\\n     0x83, 0xF8, 0x1D, 0x4A, 0x3F, 0x2F, 0xA4, 0x57, \\\n     0x1E, 0xFC, 0x8C, 0xE0, 0xBA, 0x8A, 0x4F, 0xE8, \\\n     0xB6, 0x85, 0x5D, 0xFE, 0x72, 0xB0, 0xA6, 0x6E, \\\n     0xDE, 0xD2, 0xFB, 0xAB, 0xFB, 0xE5, 0x8A, 0x30, \\\n     0xFA, 0xFA, 0xBE, 0x1C, 0x5D, 0x71, 0xA8, 0x7E, \\\n     0x2F, 0x74, 0x1E, 0xF8, 0xC1, 0xFE, 0x86, 0xFE, \\\n     0xA6, 0xBB, 0xFD, 0xE5, 0x30, 0x67, 0x7F, 0x0D, \\\n     0x97, 0xD1, 0x1D, 0x49, 0xF7, 0xA8, 0x44, 0x3D, \\\n     0x08, 0x22, 0xE5, 0x06, 0xA9, 0xF4, 0x61, 0x4E, \\\n     0x01, 0x1E, 0x2A, 0x94, 0x83, 0x8F, 0xF8, 0x8C, \\\n     0xD6, 0x8C, 0x8B, 0xB7, 0xC5, 0xC6, 0x42, 0x4C, \\\n     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }\n\n#define MBEDTLS_DHM_RFC7919_FFDHE8192_G_BIN { 0x02 }\n\n#endif /* dhm.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/ecdh.h",
    "content": "/**\n * \\file ecdh.h\n *\n * \\brief This file contains ECDH definitions and functions.\n *\n * The Elliptic Curve Diffie-Hellman (ECDH) protocol is an anonymous\n * key agreement protocol allowing two parties to establish a shared\n * secret over an insecure channel. Each party must have an\n * elliptic-curve public–private key pair.\n *\n * For more information, see <em>NIST SP 800-56A Rev. 2: Recommendation for\n * Pair-Wise Key Establishment Schemes Using Discrete Logarithm\n * Cryptography</em>.\n */\n/*\n *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_ECDH_H\n#define MBEDTLS_ECDH_H\n\n#include \"ecp.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * Defines the source of the imported EC key.\n */\ntypedef enum\n{\n    MBEDTLS_ECDH_OURS,   /**< Our key. */\n    MBEDTLS_ECDH_THEIRS, /**< The key of the peer. */\n} mbedtls_ecdh_side;\n\n/**\n * \\brief           The ECDH context structure.\n */\ntypedef struct\n{\n    mbedtls_ecp_group grp;   /*!< The elliptic curve used. */\n    mbedtls_mpi d;           /*!< The private key. */\n    mbedtls_ecp_point Q;     /*!< The public key. */\n    mbedtls_ecp_point Qp;    /*!< The value of the public key of the peer. */\n    mbedtls_mpi z;           /*!< The shared secret. */\n    int point_format;        /*!< The format of point export in TLS messages. */\n    mbedtls_ecp_point Vi;    /*!< The blinding value. */\n    mbedtls_ecp_point Vf;    /*!< The unblinding value. */\n    mbedtls_mpi _d;          /*!< The previous \\p d. */\n}\nmbedtls_ecdh_context;\n\n/**\n * \\brief           This function generates an ECDH keypair on an elliptic\n *                  curve.\n *\n *                  This function performs the first of two core computations\n *                  implemented during the ECDH key exchange. The second core\n *                  computation is performed by mbedtls_ecdh_compute_shared().\n *\n * \\see             ecp.h\n *\n * \\param grp       The ECP group.\n * \\param d         The destination MPI (private key).\n * \\param Q         The destination point (public key).\n * \\param f_rng     The RNG function.\n * \\param p_rng     The RNG context.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX or\n *                  \\c MBEDTLS_MPI_XXX error code on failure.\n *\n */\nint mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q,\n                     int (*f_rng)(void *, unsigned char *, size_t),\n                     void *p_rng );\n\n/**\n * \\brief           This function computes the shared secret.\n *\n *                  This function performs the second of two core computations\n *                  implemented during the ECDH key exchange. The first core\n *                  computation is performed by mbedtls_ecdh_gen_public().\n *\n * \\see             ecp.h\n *\n * \\note            If \\p f_rng is not NULL, it is used to implement\n *                  countermeasures against side-channel attacks.\n *                  For more information, see mbedtls_ecp_mul().\n *\n * \\param grp       The ECP group.\n * \\param z         The destination MPI (shared secret).\n * \\param Q         The public key from another party.\n * \\param d         Our secret exponent (private key).\n * \\param f_rng     The RNG function.\n * \\param p_rng     The RNG context.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX or\n *                  \\c MBEDTLS_MPI_XXX error code on failure.\n */\nint mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z,\n                         const mbedtls_ecp_point *Q, const mbedtls_mpi *d,\n                         int (*f_rng)(void *, unsigned char *, size_t),\n                         void *p_rng );\n\n/**\n * \\brief           This function initializes an ECDH context.\n *\n * \\param ctx       The ECDH context to initialize.\n */\nvoid mbedtls_ecdh_init( mbedtls_ecdh_context *ctx );\n\n/**\n * \\brief           This function frees a context.\n *\n * \\param ctx       The context to free.\n */\nvoid mbedtls_ecdh_free( mbedtls_ecdh_context *ctx );\n\n/**\n * \\brief           This function generates a public key and a TLS\n *                  ServerKeyExchange payload.\n *\n *                  This is the first function used by a TLS server for ECDHE\n *                  ciphersuites.\n *\n * \\note            This function assumes that the ECP group (grp) of the\n *                  \\p ctx context has already been properly set,\n *                  for example, using mbedtls_ecp_group_load().\n *\n * \\see             ecp.h\n *\n * \\param ctx       The ECDH context.\n * \\param olen      The number of characters written.\n * \\param buf       The destination buffer.\n * \\param blen      The length of the destination buffer.\n * \\param f_rng     The RNG function.\n * \\param p_rng     The RNG context.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX error code on failure.\n */\nint mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen,\n                      unsigned char *buf, size_t blen,\n                      int (*f_rng)(void *, unsigned char *, size_t),\n                      void *p_rng );\n\n/**\n * \\brief           This function parses and processes a TLS ServerKeyExhange\n *                  payload.\n *\n *                  This is the first function used by a TLS client for ECDHE\n *                  ciphersuites.\n *\n * \\see             ecp.h\n *\n * \\param ctx       The ECDH context.\n * \\param buf       The pointer to the start of the input buffer.\n * \\param end       The address for one Byte past the end of the buffer.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX error code on failure.\n *\n */\nint mbedtls_ecdh_read_params( mbedtls_ecdh_context *ctx,\n                      const unsigned char **buf, const unsigned char *end );\n\n/**\n * \\brief           This function sets up an ECDH context from an EC key.\n *\n *                  It is used by clients and servers in place of the\n *                  ServerKeyEchange for static ECDH, and imports ECDH\n *                  parameters from the EC key information of a certificate.\n *\n * \\see             ecp.h\n *\n * \\param ctx       The ECDH context to set up.\n * \\param key       The EC key to use.\n * \\param side      Defines the source of the key: 1: Our key, or\n *                  0: The key of the peer.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX error code on failure.\n *\n */\nint mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx, const mbedtls_ecp_keypair *key,\n                     mbedtls_ecdh_side side );\n\n/**\n * \\brief           This function generates a public key and a TLS\n *                  ClientKeyExchange payload.\n *\n *                  This is the second function used by a TLS client for ECDH(E)\n *                  ciphersuites.\n *\n * \\see             ecp.h\n *\n * \\param ctx       The ECDH context.\n * \\param olen      The number of Bytes written.\n * \\param buf       The destination buffer.\n * \\param blen      The size of the destination buffer.\n * \\param f_rng     The RNG function.\n * \\param p_rng     The RNG context.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX error code on failure.\n */\nint mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen,\n                      unsigned char *buf, size_t blen,\n                      int (*f_rng)(void *, unsigned char *, size_t),\n                      void *p_rng );\n\n/**\n * \\brief       This function parses and processes a TLS ClientKeyExchange\n *              payload.\n *\n *              This is the second function used by a TLS server for ECDH(E)\n *              ciphersuites.\n *\n * \\see         ecp.h\n *\n * \\param ctx   The ECDH context.\n * \\param buf   The start of the input buffer.\n * \\param blen  The length of the input buffer.\n *\n * \\return      \\c 0 on success.\n * \\return      An \\c MBEDTLS_ERR_ECP_XXX error code on failure.\n */\nint mbedtls_ecdh_read_public( mbedtls_ecdh_context *ctx,\n                      const unsigned char *buf, size_t blen );\n\n/**\n * \\brief           This function derives and exports the shared secret.\n *\n *                  This is the last function used by both TLS client\n *                  and servers.\n *\n * \\note            If \\p f_rng is not NULL, it is used to implement\n *                  countermeasures against side-channel attacks.\n *                  For more information, see mbedtls_ecp_mul().\n *\n * \\see             ecp.h\n *\n * \\param ctx       The ECDH context.\n * \\param olen      The number of Bytes written.\n * \\param buf       The destination buffer.\n * \\param blen      The length of the destination buffer.\n * \\param f_rng     The RNG function.\n * \\param p_rng     The RNG context.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX error code on failure.\n */\nint mbedtls_ecdh_calc_secret( mbedtls_ecdh_context *ctx, size_t *olen,\n                      unsigned char *buf, size_t blen,\n                      int (*f_rng)(void *, unsigned char *, size_t),\n                      void *p_rng );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* ecdh.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/ecdsa.h",
    "content": "/**\n * \\file ecdsa.h\n *\n * \\brief This file contains ECDSA definitions and functions.\n *\n * The Elliptic Curve Digital Signature Algorithm (ECDSA) is defined in\n * <em>Standards for Efficient Cryptography Group (SECG):\n * SEC1 Elliptic Curve Cryptography</em>.\n * The use of ECDSA for TLS is defined in <em>RFC-4492: Elliptic Curve\n * Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS)</em>.\n *\n */\n/*\n *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_ECDSA_H\n#define MBEDTLS_ECDSA_H\n\n#include \"ecp.h\"\n#include \"md.h\"\n\n/*\n * RFC-4492 page 20:\n *\n *     Ecdsa-Sig-Value ::= SEQUENCE {\n *         r       INTEGER,\n *         s       INTEGER\n *     }\n *\n * Size is at most\n *    1 (tag) + 1 (len) + 1 (initial 0) + ECP_MAX_BYTES for each of r and s,\n *    twice that + 1 (tag) + 2 (len) for the sequence\n * (assuming ECP_MAX_BYTES is less than 126 for r and s,\n * and less than 124 (total len <= 255) for the sequence)\n */\n#if MBEDTLS_ECP_MAX_BYTES > 124\n#error \"MBEDTLS_ECP_MAX_BYTES bigger than expected, please fix MBEDTLS_ECDSA_MAX_LEN\"\n#endif\n/** The maximal size of an ECDSA signature in Bytes. */\n#define MBEDTLS_ECDSA_MAX_LEN  ( 3 + 2 * ( 3 + MBEDTLS_ECP_MAX_BYTES ) )\n\n/**\n * \\brief           The ECDSA context structure.\n */\ntypedef mbedtls_ecp_keypair mbedtls_ecdsa_context;\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief           This function computes the ECDSA signature of a\n *                  previously-hashed message.\n *\n * \\note            The deterministic version is usually preferred.\n *\n * \\note            If the bitlength of the message hash is larger than the\n *                  bitlength of the group order, then the hash is truncated\n *                  as defined in <em>Standards for Efficient Cryptography Group\n *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section\n *                  4.1.3, step 5.\n *\n * \\see             ecp.h\n *\n * \\param grp       The ECP group.\n * \\param r         The first output integer.\n * \\param s         The second output integer.\n * \\param d         The private signing key.\n * \\param buf       The message hash.\n * \\param blen      The length of \\p buf.\n * \\param f_rng     The RNG function.\n * \\param p_rng     The RNG context.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX\n *                  or \\c MBEDTLS_MPI_XXX error code on failure.\n */\nint mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,\n                const mbedtls_mpi *d, const unsigned char *buf, size_t blen,\n                int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );\n\n#if defined(MBEDTLS_ECDSA_DETERMINISTIC)\n/**\n * \\brief           This function computes the ECDSA signature of a\n *                  previously-hashed message, deterministic version.\n *\n *                  For more information, see <em>RFC-6979: Deterministic\n *                  Usage of the Digital Signature Algorithm (DSA) and Elliptic\n *                  Curve Digital Signature Algorithm (ECDSA)</em>.\n *\n * \\note            If the bitlength of the message hash is larger than the\n *                  bitlength of the group order, then the hash is truncated as\n *                  defined in <em>Standards for Efficient Cryptography Group\n *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section\n *                  4.1.3, step 5.\n *\n * \\see             ecp.h\n *\n * \\param grp       The ECP group.\n * \\param r         The first output integer.\n * \\param s         The second output integer.\n * \\param d         The private signing key.\n * \\param buf       The message hash.\n * \\param blen      The length of \\p buf.\n * \\param md_alg    The MD algorithm used to hash the message.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX or \\c MBEDTLS_MPI_XXX\n *                  error code on failure.\n */\nint mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,\n                    const mbedtls_mpi *d, const unsigned char *buf, size_t blen,\n                    mbedtls_md_type_t md_alg );\n#endif /* MBEDTLS_ECDSA_DETERMINISTIC */\n\n/**\n * \\brief           This function verifies the ECDSA signature of a\n *                  previously-hashed message.\n *\n * \\note            If the bitlength of the message hash is larger than the\n *                  bitlength of the group order, then the hash is truncated as\n *                  defined in <em>Standards for Efficient Cryptography Group\n *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section\n *                  4.1.4, step 3.\n *\n * \\see             ecp.h\n *\n * \\param grp       The ECP group.\n * \\param buf       The message hash.\n * \\param blen      The length of \\p buf.\n * \\param Q         The public key to use for verification.\n * \\param r         The first integer of the signature.\n * \\param s         The second integer of the signature.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the signature\n *                  is invalid.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX or \\c MBEDTLS_MPI_XXX\n *                  error code on failure for any other reason.\n */\nint mbedtls_ecdsa_verify( mbedtls_ecp_group *grp,\n                  const unsigned char *buf, size_t blen,\n                  const mbedtls_ecp_point *Q, const mbedtls_mpi *r, const mbedtls_mpi *s);\n\n/**\n * \\brief           This function computes the ECDSA signature and writes it\n *                  to a buffer, serialized as defined in <em>RFC-4492:\n *                  Elliptic Curve Cryptography (ECC) Cipher Suites for\n *                  Transport Layer Security (TLS)</em>.\n *\n * \\warning         It is not thread-safe to use the same context in\n *                  multiple threads.\n *\n * \\note            The deterministic version is used if\n *                  #MBEDTLS_ECDSA_DETERMINISTIC is defined. For more\n *                  information, see <em>RFC-6979: Deterministic Usage\n *                  of the Digital Signature Algorithm (DSA) and Elliptic\n *                  Curve Digital Signature Algorithm (ECDSA)</em>.\n *\n * \\note            The \\p sig buffer must be at least twice as large as the\n *                  size of the curve used, plus 9. For example, 73 Bytes if\n *                  a 256-bit curve is used. A buffer length of\n *                  #MBEDTLS_ECDSA_MAX_LEN is always safe.\n *\n * \\note            If the bitlength of the message hash is larger than the\n *                  bitlength of the group order, then the hash is truncated as\n *                  defined in <em>Standards for Efficient Cryptography Group\n *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section\n *                  4.1.3, step 5.\n *\n * \\see             ecp.h\n *\n * \\param ctx       The ECDSA context.\n * \\param md_alg    The message digest that was used to hash the message.\n * \\param hash      The message hash.\n * \\param hlen      The length of the hash.\n * \\param sig       The buffer that holds the signature.\n * \\param slen      The length of the signature written.\n * \\param f_rng     The RNG function.\n * \\param p_rng     The RNG context.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX, \\c MBEDTLS_ERR_MPI_XXX or\n *                  \\c MBEDTLS_ERR_ASN1_XXX error code on failure.\n */\nint mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg,\n                           const unsigned char *hash, size_t hlen,\n                           unsigned char *sig, size_t *slen,\n                           int (*f_rng)(void *, unsigned char *, size_t),\n                           void *p_rng );\n\n#if defined(MBEDTLS_ECDSA_DETERMINISTIC)\n#if ! defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED    __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n/**\n * \\brief           This function computes an ECDSA signature and writes\n *                  it to a buffer, serialized as defined in <em>RFC-4492:\n *                  Elliptic Curve Cryptography (ECC) Cipher Suites for\n *                  Transport Layer Security (TLS)</em>.\n *\n *                  The deterministic version is defined in <em>RFC-6979:\n *                  Deterministic Usage of the Digital Signature Algorithm (DSA)\n *                  and Elliptic Curve Digital Signature Algorithm (ECDSA)</em>.\n *\n * \\warning         It is not thread-safe to use the same context in\n *                  multiple threads.\n *\n * \\note            The \\p sig buffer must be at least twice as large as the\n *                  size of the curve used, plus 9. For example, 73 Bytes if a\n *                  256-bit curve is used. A buffer length of\n *                  #MBEDTLS_ECDSA_MAX_LEN is always safe.\n *\n * \\note            If the bitlength of the message hash is larger than the\n *                  bitlength of the group order, then the hash is truncated as\n *                  defined in <em>Standards for Efficient Cryptography Group\n *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section\n *                  4.1.3, step 5.\n *\n * \\see             ecp.h\n *\n * \\deprecated      Superseded by mbedtls_ecdsa_write_signature() in\n *                  Mbed TLS version 2.0 and later.\n *\n * \\param ctx       The ECDSA context.\n * \\param hash      The message hash.\n * \\param hlen      The length of the hash.\n * \\param sig       The buffer that holds the signature.\n * \\param slen      The length of the signature written.\n * \\param md_alg    The MD algorithm used to hash the message.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX, \\c MBEDTLS_ERR_MPI_XXX or\n *                  \\c MBEDTLS_ERR_ASN1_XXX error code on failure.\n */\nint mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx,\n                               const unsigned char *hash, size_t hlen,\n                               unsigned char *sig, size_t *slen,\n                               mbedtls_md_type_t md_alg ) MBEDTLS_DEPRECATED;\n#undef MBEDTLS_DEPRECATED\n#endif /* MBEDTLS_DEPRECATED_REMOVED */\n#endif /* MBEDTLS_ECDSA_DETERMINISTIC */\n\n/**\n * \\brief           This function reads and verifies an ECDSA signature.\n *\n * \\note            If the bitlength of the message hash is larger than the\n *                  bitlength of the group order, then the hash is truncated as\n *                  defined in <em>Standards for Efficient Cryptography Group\n *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section\n *                  4.1.4, step 3.\n *\n * \\see             ecp.h\n *\n * \\param ctx       The ECDSA context.\n * \\param hash      The message hash.\n * \\param hlen      The size of the hash.\n * \\param sig       The signature to read and verify.\n * \\param slen      The size of \\p sig.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid.\n * \\return          #MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if there is a valid\n *                  signature in \\p sig, but its length is less than \\p siglen.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX or \\c MBEDTLS_ERR_MPI_XXX\n *                  error code on failure for any other reason.\n */\nint mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx,\n                          const unsigned char *hash, size_t hlen,\n                          const unsigned char *sig, size_t slen );\n\n/**\n * \\brief          This function generates an ECDSA keypair on the given curve.\n *\n * \\see            ecp.h\n *\n * \\param ctx      The ECDSA context to store the keypair in.\n * \\param gid      The elliptic curve to use. One of the various\n *                 \\c MBEDTLS_ECP_DP_XXX macros depending on configuration.\n * \\param f_rng    The RNG function.\n * \\param p_rng    The RNG context.\n *\n * \\return         \\c 0 on success.\n * \\return         An \\c MBEDTLS_ERR_ECP_XXX code on failure.\n */\nint mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid,\n                  int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );\n\n/**\n * \\brief           This function sets an ECDSA context from an EC key pair.\n *\n * \\see             ecp.h\n *\n * \\param ctx       The ECDSA context to set.\n * \\param key       The EC key to use.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX code on failure.\n */\nint mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key );\n\n/**\n * \\brief           This function initializes an ECDSA context.\n *\n * \\param ctx       The ECDSA context to initialize.\n */\nvoid mbedtls_ecdsa_init( mbedtls_ecdsa_context *ctx );\n\n/**\n * \\brief           This function frees an ECDSA context.\n *\n * \\param ctx       The ECDSA context to free.\n */\nvoid mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* ecdsa.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/ecjpake.h",
    "content": "/**\n * \\file ecjpake.h\n *\n * \\brief Elliptic curve J-PAKE\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_ECJPAKE_H\n#define MBEDTLS_ECJPAKE_H\n\n/*\n * J-PAKE is a password-authenticated key exchange that allows deriving a\n * strong shared secret from a (potentially low entropy) pre-shared\n * passphrase, with forward secrecy and mutual authentication.\n * https://en.wikipedia.org/wiki/Password_Authenticated_Key_Exchange_by_Juggling\n *\n * This file implements the Elliptic Curve variant of J-PAKE,\n * as defined in Chapter 7.4 of the Thread v1.0 Specification,\n * available to members of the Thread Group http://threadgroup.org/\n *\n * As the J-PAKE algorithm is inherently symmetric, so is our API.\n * Each party needs to send its first round message, in any order, to the\n * other party, then each sends its second round message, in any order.\n * The payloads are serialized in a way suitable for use in TLS, but could\n * also be use outside TLS.\n */\n\n#include \"ecp.h\"\n#include \"md.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * Roles in the EC J-PAKE exchange\n */\ntypedef enum {\n    MBEDTLS_ECJPAKE_CLIENT = 0,         /**< Client                         */\n    MBEDTLS_ECJPAKE_SERVER,             /**< Server                         */\n} mbedtls_ecjpake_role;\n\n#if !defined(MBEDTLS_ECJPAKE_ALT)\n/**\n * EC J-PAKE context structure.\n *\n * J-PAKE is a symmetric protocol, except for the identifiers used in\n * Zero-Knowledge Proofs, and the serialization of the second message\n * (KeyExchange) as defined by the Thread spec.\n *\n * In order to benefit from this symmetry, we choose a different naming\n * convetion from the Thread v1.0 spec. Correspondance is indicated in the\n * description as a pair C: client name, S: server name\n */\ntypedef struct\n{\n    const mbedtls_md_info_t *md_info;   /**< Hash to use                    */\n    mbedtls_ecp_group grp;              /**< Elliptic curve                 */\n    mbedtls_ecjpake_role role;          /**< Are we client or server?       */\n    int point_format;                   /**< Format for point export        */\n\n    mbedtls_ecp_point Xm1;              /**< My public key 1   C: X1, S: X3 */\n    mbedtls_ecp_point Xm2;              /**< My public key 2   C: X2, S: X4 */\n    mbedtls_ecp_point Xp1;              /**< Peer public key 1 C: X3, S: X1 */\n    mbedtls_ecp_point Xp2;              /**< Peer public key 2 C: X4, S: X2 */\n    mbedtls_ecp_point Xp;               /**< Peer public key   C: Xs, S: Xc */\n\n    mbedtls_mpi xm1;                    /**< My private key 1  C: x1, S: x3 */\n    mbedtls_mpi xm2;                    /**< My private key 2  C: x2, S: x4 */\n\n    mbedtls_mpi s;                      /**< Pre-shared secret (passphrase) */\n} mbedtls_ecjpake_context;\n\n#else  /* MBEDTLS_ECJPAKE_ALT */\n#include \"ecjpake_alt.h\"\n#endif /* MBEDTLS_ECJPAKE_ALT */\n\n/**\n * \\brief           Initialize a context\n *                  (just makes it ready for setup() or free()).\n *\n * \\param ctx       context to initialize\n */\nvoid mbedtls_ecjpake_init( mbedtls_ecjpake_context *ctx );\n\n/**\n * \\brief           Set up a context for use\n *\n * \\note            Currently the only values for hash/curve allowed by the\n *                  standard are MBEDTLS_MD_SHA256/MBEDTLS_ECP_DP_SECP256R1.\n *\n * \\param ctx       context to set up\n * \\param role      Our role: client or server\n * \\param hash      hash function to use (MBEDTLS_MD_XXX)\n * \\param curve     elliptic curve identifier (MBEDTLS_ECP_DP_XXX)\n * \\param secret    pre-shared secret (passphrase)\n * \\param len       length of the shared secret\n *\n * \\return          0 if successfull,\n *                  a negative error code otherwise\n */\nint mbedtls_ecjpake_setup( mbedtls_ecjpake_context *ctx,\n                           mbedtls_ecjpake_role role,\n                           mbedtls_md_type_t hash,\n                           mbedtls_ecp_group_id curve,\n                           const unsigned char *secret,\n                           size_t len );\n\n/**\n * \\brief           Check if a context is ready for use\n *\n * \\param ctx       Context to check\n *\n * \\return          0 if the context is ready for use,\n *                  MBEDTLS_ERR_ECP_BAD_INPUT_DATA otherwise\n */\nint mbedtls_ecjpake_check( const mbedtls_ecjpake_context *ctx );\n\n/**\n * \\brief           Generate and write the first round message\n *                  (TLS: contents of the Client/ServerHello extension,\n *                  excluding extension type and length bytes)\n *\n * \\param ctx       Context to use\n * \\param buf       Buffer to write the contents to\n * \\param len       Buffer size\n * \\param olen      Will be updated with the number of bytes written\n * \\param f_rng     RNG function\n * \\param p_rng     RNG parameter\n *\n * \\return          0 if successfull,\n *                  a negative error code otherwise\n */\nint mbedtls_ecjpake_write_round_one( mbedtls_ecjpake_context *ctx,\n                            unsigned char *buf, size_t len, size_t *olen,\n                            int (*f_rng)(void *, unsigned char *, size_t),\n                            void *p_rng );\n\n/**\n * \\brief           Read and process the first round message\n *                  (TLS: contents of the Client/ServerHello extension,\n *                  excluding extension type and length bytes)\n *\n * \\param ctx       Context to use\n * \\param buf       Pointer to extension contents\n * \\param len       Extension length\n *\n * \\return          0 if successfull,\n *                  a negative error code otherwise\n */\nint mbedtls_ecjpake_read_round_one( mbedtls_ecjpake_context *ctx,\n                                    const unsigned char *buf,\n                                    size_t len );\n\n/**\n * \\brief           Generate and write the second round message\n *                  (TLS: contents of the Client/ServerKeyExchange)\n *\n * \\param ctx       Context to use\n * \\param buf       Buffer to write the contents to\n * \\param len       Buffer size\n * \\param olen      Will be updated with the number of bytes written\n * \\param f_rng     RNG function\n * \\param p_rng     RNG parameter\n *\n * \\return          0 if successfull,\n *                  a negative error code otherwise\n */\nint mbedtls_ecjpake_write_round_two( mbedtls_ecjpake_context *ctx,\n                            unsigned char *buf, size_t len, size_t *olen,\n                            int (*f_rng)(void *, unsigned char *, size_t),\n                            void *p_rng );\n\n/**\n * \\brief           Read and process the second round message\n *                  (TLS: contents of the Client/ServerKeyExchange)\n *\n * \\param ctx       Context to use\n * \\param buf       Pointer to the message\n * \\param len       Message length\n *\n * \\return          0 if successfull,\n *                  a negative error code otherwise\n */\nint mbedtls_ecjpake_read_round_two( mbedtls_ecjpake_context *ctx,\n                                    const unsigned char *buf,\n                                    size_t len );\n\n/**\n * \\brief           Derive the shared secret\n *                  (TLS: Pre-Master Secret)\n *\n * \\param ctx       Context to use\n * \\param buf       Buffer to write the contents to\n * \\param len       Buffer size\n * \\param olen      Will be updated with the number of bytes written\n * \\param f_rng     RNG function\n * \\param p_rng     RNG parameter\n *\n * \\return          0 if successfull,\n *                  a negative error code otherwise\n */\nint mbedtls_ecjpake_derive_secret( mbedtls_ecjpake_context *ctx,\n                            unsigned char *buf, size_t len, size_t *olen,\n                            int (*f_rng)(void *, unsigned char *, size_t),\n                            void *p_rng );\n\n/**\n * \\brief           Free a context's content\n *\n * \\param ctx       context to free\n */\nvoid mbedtls_ecjpake_free( mbedtls_ecjpake_context *ctx );\n\n\n\n#if defined(MBEDTLS_SELF_TEST)\n\n/**\n * \\brief          Checkup routine\n *\n * \\return         0 if successful, or 1 if a test failed\n */\nint mbedtls_ecjpake_self_test( int verbose );\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#ifdef __cplusplus\n}\n#endif\n\n\n#endif /* ecjpake.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/ecp.h",
    "content": "/**\n * \\file ecp.h\n *\n * \\brief This file provides an API for Elliptic Curves over GF(P) (ECP).\n *\n * The use of ECP in cryptography and TLS is defined in\n * <em>Standards for Efficient Cryptography Group (SECG): SEC1\n * Elliptic Curve Cryptography</em> and\n * <em>RFC-4492: Elliptic Curve Cryptography (ECC) Cipher Suites\n * for Transport Layer Security (TLS)</em>.\n *\n * <em>RFC-2409: The Internet Key Exchange (IKE)</em> defines ECP\n * group types.\n *\n */\n\n/*\n *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_ECP_H\n#define MBEDTLS_ECP_H\n\n#include \"bignum.h\"\n\n/*\n * ECP error codes\n */\n#define MBEDTLS_ERR_ECP_BAD_INPUT_DATA                    -0x4F80  /**< Bad input parameters to function. */\n#define MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL                  -0x4F00  /**< The buffer is too small to write to. */\n#define MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE               -0x4E80  /**< The requested feature is not available, for example, the requested curve is not supported. */\n#define MBEDTLS_ERR_ECP_VERIFY_FAILED                     -0x4E00  /**< The signature is not valid. */\n#define MBEDTLS_ERR_ECP_ALLOC_FAILED                      -0x4D80  /**< Memory allocation failed. */\n#define MBEDTLS_ERR_ECP_RANDOM_FAILED                     -0x4D00  /**< Generation of random value, such as ephemeral key, failed. */\n#define MBEDTLS_ERR_ECP_INVALID_KEY                       -0x4C80  /**< Invalid private or public key. */\n#define MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH                  -0x4C00  /**< The buffer contains a valid signature followed by more data. */\n#define MBEDTLS_ERR_ECP_HW_ACCEL_FAILED                   -0x4B80  /**< The ECP hardware accelerator failed. */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * Domain-parameter identifiers: curve, subgroup, and generator.\n *\n * \\note Only curves over prime fields are supported.\n *\n * \\warning This library does not support validation of arbitrary domain\n * parameters. Therefore, only standardized domain parameters from trusted\n * sources should be used. See mbedtls_ecp_group_load().\n */\ntypedef enum\n{\n    MBEDTLS_ECP_DP_NONE = 0,       /*!< Curve not defined. */\n    MBEDTLS_ECP_DP_SECP192R1,      /*!< Domain parameters for the 192-bit curve defined by FIPS 186-4 and SEC1. */\n    MBEDTLS_ECP_DP_SECP224R1,      /*!< Domain parameters for the 224-bit curve defined by FIPS 186-4 and SEC1. */\n    MBEDTLS_ECP_DP_SECP256R1,      /*!< Domain parameters for the 256-bit curve defined by FIPS 186-4 and SEC1. */\n    MBEDTLS_ECP_DP_SECP384R1,      /*!< Domain parameters for the 384-bit curve defined by FIPS 186-4 and SEC1. */\n    MBEDTLS_ECP_DP_SECP521R1,      /*!< Domain parameters for the 521-bit curve defined by FIPS 186-4 and SEC1. */\n    MBEDTLS_ECP_DP_BP256R1,        /*!< Domain parameters for 256-bit Brainpool curve. */\n    MBEDTLS_ECP_DP_BP384R1,        /*!< Domain parameters for 384-bit Brainpool curve. */\n    MBEDTLS_ECP_DP_BP512R1,        /*!< Domain parameters for 512-bit Brainpool curve. */\n    MBEDTLS_ECP_DP_CURVE25519,     /*!< Domain parameters for Curve25519. */\n    MBEDTLS_ECP_DP_SECP192K1,      /*!< Domain parameters for 192-bit \"Koblitz\" curve. */\n    MBEDTLS_ECP_DP_SECP224K1,      /*!< Domain parameters for 224-bit \"Koblitz\" curve. */\n    MBEDTLS_ECP_DP_SECP256K1,      /*!< Domain parameters for 256-bit \"Koblitz\" curve. */\n    MBEDTLS_ECP_DP_CURVE448,       /*!< Domain parameters for Curve448. */\n} mbedtls_ecp_group_id;\n\n/**\n * The number of supported curves, plus one for #MBEDTLS_ECP_DP_NONE.\n *\n * \\note Montgomery curves are currently excluded.\n */\n#define MBEDTLS_ECP_DP_MAX     12\n\n/**\n * Curve information, for use by other modules.\n */\ntypedef struct\n{\n    mbedtls_ecp_group_id grp_id;    /*!< An internal identifier. */\n    uint16_t tls_id;                /*!< The TLS NamedCurve identifier. */\n    uint16_t bit_size;              /*!< The curve size in bits. */\n    const char *name;               /*!< A human-friendly name. */\n} mbedtls_ecp_curve_info;\n\n/**\n * \\brief           The ECP point structure, in Jacobian coordinates.\n *\n * \\note            All functions expect and return points satisfying\n *                  the following condition: <code>Z == 0</code> or\n *                  <code>Z == 1</code>. Other values of \\p Z are\n *                  used only by internal functions.\n *                  The point is zero, or \"at infinity\", if <code>Z == 0</code>.\n *                  Otherwise, \\p X and \\p Y are its standard (affine)\n *                  coordinates.\n */\ntypedef struct\n{\n    mbedtls_mpi X;          /*!< The X coordinate of the ECP point. */\n    mbedtls_mpi Y;          /*!< The Y coordinate of the ECP point. */\n    mbedtls_mpi Z;          /*!< The Z coordinate of the ECP point. */\n}\nmbedtls_ecp_point;\n\n#if !defined(MBEDTLS_ECP_ALT)\n/*\n * default mbed TLS elliptic curve arithmetic implementation\n *\n * (in case MBEDTLS_ECP_ALT is defined then the developer has to provide an\n * alternative implementation for the whole module and it will replace this\n * one.)\n */\n\n/**\n * \\brief           The ECP group structure.\n *\n * We consider two types of curve equations:\n * <ul><li>Short Weierstrass: <code>y^2 = x^3 + A x + B mod P</code>\n * (SEC1 + RFC-4492)</li>\n * <li>Montgomery: <code>y^2 = x^3 + A x^2 + x mod P</code> (Curve25519,\n * Curve448)</li></ul>\n * In both cases, the generator (\\p G) for a prime-order subgroup is fixed.\n *\n * For Short Weierstrass, this subgroup is the whole curve, and its\n * cardinality is denoted by \\p N. Our code requires that \\p N is an\n * odd prime as mbedtls_ecp_mul() requires an odd number, and\n * mbedtls_ecdsa_sign() requires that it is prime for blinding purposes.\n *\n * For Montgomery curves, we do not store \\p A, but <code>(A + 2) / 4</code>,\n * which is the quantity used in the formulas. Additionally, \\p nbits is\n * not the size of \\p N but the required size for private keys.\n *\n * If \\p modp is NULL, reduction modulo \\p P is done using a generic algorithm.\n * Otherwise, \\p modp must point to a function that takes an \\p mbedtls_mpi in the\n * range of <code>0..2^(2*pbits)-1</code>, and transforms it in-place to an integer\n * which is congruent mod \\p P to the given MPI, and is close enough to \\p pbits\n * in size, so that it may be efficiently brought in the 0..P-1 range by a few\n * additions or subtractions. Therefore, it is only an approximative modular\n * reduction. It must return 0 on success and non-zero on failure.\n *\n */\ntypedef struct\n{\n    mbedtls_ecp_group_id id;    /*!< An internal group identifier. */\n    mbedtls_mpi P;              /*!< The prime modulus of the base field. */\n    mbedtls_mpi A;              /*!< For Short Weierstrass: \\p A in the equation. For\n                                     Montgomery curves: <code>(A + 2) / 4</code>. */\n    mbedtls_mpi B;              /*!< For Short Weierstrass: \\p B in the equation.\n                                     For Montgomery curves: unused. */\n    mbedtls_ecp_point G;        /*!< The generator of the subgroup used. */\n    mbedtls_mpi N;              /*!< The order of \\p G. */\n    size_t pbits;               /*!< The number of bits in \\p P.*/\n    size_t nbits;               /*!< For Short Weierstrass: The number of bits in \\p P.\n                                     For Montgomery curves: the number of bits in the\n                                     private keys. */\n    unsigned int h;             /*!< \\internal 1 if the constants are static. */\n    int (*modp)(mbedtls_mpi *); /*!< The function for fast pseudo-reduction\n                                     mod \\p P (see above).*/\n    int (*t_pre)(mbedtls_ecp_point *, void *);  /*!< Unused. */\n    int (*t_post)(mbedtls_ecp_point *, void *); /*!< Unused. */\n    void *t_data;               /*!< Unused. */\n    mbedtls_ecp_point *T;       /*!< Pre-computed points for ecp_mul_comb(). */\n    size_t T_size;              /*!< The number of pre-computed points. */\n}\nmbedtls_ecp_group;\n\n/**\n * \\name SECTION: Module settings\n *\n * The configuration options you can set for this module are in this section.\n * Either change them in config.h, or define them using the compiler command line.\n * \\{\n */\n\n#if !defined(MBEDTLS_ECP_MAX_BITS)\n/**\n * The maximum size of the groups, that is, of \\c N and \\c P.\n */\n#define MBEDTLS_ECP_MAX_BITS     521   /**< The maximum size of groups, in bits. */\n#endif\n\n#define MBEDTLS_ECP_MAX_BYTES    ( ( MBEDTLS_ECP_MAX_BITS + 7 ) / 8 )\n#define MBEDTLS_ECP_MAX_PT_LEN   ( 2 * MBEDTLS_ECP_MAX_BYTES + 1 )\n\n#if !defined(MBEDTLS_ECP_WINDOW_SIZE)\n/*\n * Maximum \"window\" size used for point multiplication.\n * Default: 6.\n * Minimum value: 2. Maximum value: 7.\n *\n * Result is an array of at most ( 1 << ( MBEDTLS_ECP_WINDOW_SIZE - 1 ) )\n * points used for point multiplication. This value is directly tied to EC\n * peak memory usage, so decreasing it by one should roughly cut memory usage\n * by two (if large curves are in use).\n *\n * Reduction in size may reduce speed, but larger curves are impacted first.\n * Sample performances (in ECDHE handshakes/s, with FIXED_POINT_OPTIM = 1):\n *      w-size:     6       5       4       3       2\n *      521       145     141     135     120      97\n *      384       214     209     198     177     146\n *      256       320     320     303     262     226\n *      224       475     475     453     398     342\n *      192       640     640     633     587     476\n */\n#define MBEDTLS_ECP_WINDOW_SIZE    6   /**< The maximum window size used. */\n#endif /* MBEDTLS_ECP_WINDOW_SIZE */\n\n#if !defined(MBEDTLS_ECP_FIXED_POINT_OPTIM)\n/*\n * Trade memory for speed on fixed-point multiplication.\n *\n * This speeds up repeated multiplication of the generator (that is, the\n * multiplication in ECDSA signatures, and half of the multiplications in\n * ECDSA verification and ECDHE) by a factor roughly 3 to 4.\n *\n * The cost is increasing EC peak memory usage by a factor roughly 2.\n *\n * Change this value to 0 to reduce peak memory usage.\n */\n#define MBEDTLS_ECP_FIXED_POINT_OPTIM  1   /**< Enable fixed-point speed-up. */\n#endif /* MBEDTLS_ECP_FIXED_POINT_OPTIM */\n\n/* \\} name SECTION: Module settings */\n\n#else  /* MBEDTLS_ECP_ALT */\n#include \"ecp_alt.h\"\n#endif /* MBEDTLS_ECP_ALT */\n\n/**\n * \\brief    The ECP key-pair structure.\n *\n * A generic key-pair that may be used for ECDSA and fixed ECDH, for example.\n *\n * \\note    Members are deliberately in the same order as in the\n *          ::mbedtls_ecdsa_context structure.\n */\ntypedef struct\n{\n    mbedtls_ecp_group grp;      /*!<  Elliptic curve and base point     */\n    mbedtls_mpi d;              /*!<  our secret value                  */\n    mbedtls_ecp_point Q;        /*!<  our public value                  */\n}\nmbedtls_ecp_keypair;\n\n/*\n * Point formats, from RFC 4492's enum ECPointFormat\n */\n#define MBEDTLS_ECP_PF_UNCOMPRESSED    0   /**< Uncompressed point format. */\n#define MBEDTLS_ECP_PF_COMPRESSED      1   /**< Compressed point format. */\n\n/*\n * Some other constants from RFC 4492\n */\n#define MBEDTLS_ECP_TLS_NAMED_CURVE    3   /**< The named_curve of ECCurveType. */\n\n/**\n * \\brief           This function retrieves the information defined in\n *                  mbedtls_ecp_curve_info() for all supported curves in order\n *                  of preference.\n *\n * \\return          A statically allocated array. The last entry is 0.\n */\nconst mbedtls_ecp_curve_info *mbedtls_ecp_curve_list( void );\n\n/**\n * \\brief           This function retrieves the list of internal group\n *                  identifiers of all supported curves in the order of\n *                  preference.\n *\n * \\return          A statically allocated array,\n *                  terminated with MBEDTLS_ECP_DP_NONE.\n */\nconst mbedtls_ecp_group_id *mbedtls_ecp_grp_id_list( void );\n\n/**\n * \\brief           This function retrieves curve information from an internal\n *                  group identifier.\n *\n * \\param grp_id    An \\c MBEDTLS_ECP_DP_XXX value.\n *\n * \\return          The associated curve information on success.\n * \\return          NULL on failure.\n */\nconst mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_grp_id( mbedtls_ecp_group_id grp_id );\n\n/**\n * \\brief           This function retrieves curve information from a TLS\n *                  NamedCurve value.\n *\n * \\param tls_id    An \\c MBEDTLS_ECP_DP_XXX value.\n *\n * \\return          The associated curve information on success.\n * \\return          NULL on failure.\n */\nconst mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_tls_id( uint16_t tls_id );\n\n/**\n * \\brief           This function retrieves curve information from a\n *                  human-readable name.\n *\n * \\param name      The human-readable name.\n *\n * \\return          The associated curve information on success.\n * \\return          NULL on failure.\n */\nconst mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_name( const char *name );\n\n/**\n * \\brief           This function initializes a point as zero.\n *\n * \\param pt        The point to initialize.\n */\nvoid mbedtls_ecp_point_init( mbedtls_ecp_point *pt );\n\n/**\n * \\brief           This function initializes an ECP group context\n *                  without loading any domain parameters.\n *\n * \\note            After this function is called, domain parameters\n *                  for various ECP groups can be loaded through the\n *                  mbedtls_ecp_load() or mbedtls_ecp_tls_read_group()\n *                  functions.\n */\nvoid mbedtls_ecp_group_init( mbedtls_ecp_group *grp );\n\n/**\n * \\brief           This function initializes a key pair as an invalid one.\n *\n * \\param key       The key pair to initialize.\n */\nvoid mbedtls_ecp_keypair_init( mbedtls_ecp_keypair *key );\n\n/**\n * \\brief           This function frees the components of a point.\n *\n * \\param pt        The point to free.\n */\nvoid mbedtls_ecp_point_free( mbedtls_ecp_point *pt );\n\n/**\n * \\brief           This function frees the components of an ECP group.\n * \\param grp       The group to free.\n */\nvoid mbedtls_ecp_group_free( mbedtls_ecp_group *grp );\n\n/**\n * \\brief           This function frees the components of a key pair.\n * \\param key       The key pair to free.\n */\nvoid mbedtls_ecp_keypair_free( mbedtls_ecp_keypair *key );\n\n/**\n * \\brief           This function copies the contents of point \\p Q into\n *                  point \\p P.\n *\n * \\param P         The destination point.\n * \\param Q         The source point.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.\n */\nint mbedtls_ecp_copy( mbedtls_ecp_point *P, const mbedtls_ecp_point *Q );\n\n/**\n * \\brief           This function copies the contents of group \\p src into\n *                  group \\p dst.\n *\n * \\param dst       The destination group.\n * \\param src       The source group.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.\n */\nint mbedtls_ecp_group_copy( mbedtls_ecp_group *dst, const mbedtls_ecp_group *src );\n\n/**\n * \\brief           This function sets a point to zero.\n *\n * \\param pt        The point to set.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.\n */\nint mbedtls_ecp_set_zero( mbedtls_ecp_point *pt );\n\n/**\n * \\brief           This function checks if a point is zero.\n *\n * \\param pt        The point to test.\n *\n * \\return          \\c 1 if the point is zero.\n * \\return          \\c 0 if the point is non-zero.\n */\nint mbedtls_ecp_is_zero( mbedtls_ecp_point *pt );\n\n/**\n * \\brief           This function compares two points.\n *\n * \\note            This assumes that the points are normalized. Otherwise,\n *                  they may compare as \"not equal\" even if they are.\n *\n * \\param P         The first point to compare.\n * \\param Q         The second point to compare.\n *\n * \\return          \\c 0 if the points are equal.\n * \\return          #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the points are not equal.\n */\nint mbedtls_ecp_point_cmp( const mbedtls_ecp_point *P,\n                           const mbedtls_ecp_point *Q );\n\n/**\n * \\brief           This function imports a non-zero point from two ASCII\n *                  strings.\n *\n * \\param P         The destination point.\n * \\param radix     The numeric base of the input.\n * \\param x         The first affine coordinate, as a null-terminated string.\n * \\param y         The second affine coordinate, as a null-terminated string.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_MPI_XXX error code on failure.\n */\nint mbedtls_ecp_point_read_string( mbedtls_ecp_point *P, int radix,\n                           const char *x, const char *y );\n\n/**\n * \\brief           This function exports a point into unsigned binary data.\n *\n * \\param grp       The group to which the point should belong.\n * \\param P         The point to export.\n * \\param format    The point format. Should be an \\c MBEDTLS_ECP_PF_XXX macro.\n * \\param olen      The length of the output.\n * \\param buf       The output buffer.\n * \\param buflen    The length of the output buffer.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_ECP_BAD_INPUT_DATA\n *                  or #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL on failure.\n */\nint mbedtls_ecp_point_write_binary( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *P,\n                            int format, size_t *olen,\n                            unsigned char *buf, size_t buflen );\n\n/**\n * \\brief           This function imports a point from unsigned binary data.\n *\n * \\note            This function does not check that the point actually\n *                  belongs to the given group, see mbedtls_ecp_check_pubkey()\n *                  for that.\n *\n * \\param grp       The group to which the point should belong.\n * \\param P         The point to import.\n * \\param buf       The input buffer.\n * \\param ilen      The length of the input.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid.\n * \\return          #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.\n * \\return          #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the point format\n *                  is not implemented.\n *\n */\nint mbedtls_ecp_point_read_binary( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P,\n                           const unsigned char *buf, size_t ilen );\n\n/**\n * \\brief           This function imports a point from a TLS ECPoint record.\n *\n * \\note            On function return, \\p buf is updated to point to immediately\n *                  after the ECPoint record.\n *\n * \\param grp       The ECP group used.\n * \\param pt        The destination point.\n * \\param buf       The address of the pointer to the start of the input buffer.\n * \\param len       The length of the buffer.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_MPI_XXX error code on initialization failure.\n * \\return          #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid.\n */\nint mbedtls_ecp_tls_read_point( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt,\n                        const unsigned char **buf, size_t len );\n\n/**\n * \\brief           This function exports a point as a TLS ECPoint record.\n *\n * \\param grp       The ECP group used.\n * \\param pt        The point format to export to. The point format is an\n *                  \\c MBEDTLS_ECP_PF_XXX constant.\n * \\param format    The export format.\n * \\param olen      The length of the data written.\n * \\param buf       The buffer to write to.\n * \\param blen      The length of the buffer.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_ECP_BAD_INPUT_DATA or\n *                  #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL on failure.\n */\nint mbedtls_ecp_tls_write_point( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt,\n                         int format, size_t *olen,\n                         unsigned char *buf, size_t blen );\n\n/**\n * \\brief           This function sets a group using standardized domain parameters.\n *\n * \\note            The index should be a value of the NamedCurve enum,\n *                  as defined in <em>RFC-4492: Elliptic Curve Cryptography\n *                  (ECC) Cipher Suites for Transport Layer Security (TLS)</em>,\n *                  usually in the form of an \\c MBEDTLS_ECP_DP_XXX macro.\n *\n * \\param grp       The destination group.\n * \\param id        The identifier of the domain parameter set to load.\n *\n * \\return          \\c 0 on success,\n * \\return          An \\c MBEDTLS_ERR_MPI_XXX error code on initialization failure.\n * \\return          #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE for unkownn groups.\n\n */\nint mbedtls_ecp_group_load( mbedtls_ecp_group *grp, mbedtls_ecp_group_id id );\n\n/**\n * \\brief           This function sets a group from a TLS ECParameters record.\n *\n * \\note            \\p buf is updated to point right after the ECParameters record\n *                  on exit.\n *\n * \\param grp       The destination group.\n * \\param buf       The address of the pointer to the start of the input buffer.\n * \\param len       The length of the buffer.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_MPI_XXX error code on initialization failure.\n * \\return          #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid.\n */\nint mbedtls_ecp_tls_read_group( mbedtls_ecp_group *grp, const unsigned char **buf, size_t len );\n\n/**\n * \\brief           This function writes the TLS ECParameters record for a group.\n *\n * \\param grp       The ECP group used.\n * \\param olen      The number of Bytes written.\n * \\param buf       The buffer to write to.\n * \\param blen      The length of the buffer.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL on failure.\n */\nint mbedtls_ecp_tls_write_group( const mbedtls_ecp_group *grp, size_t *olen,\n                         unsigned char *buf, size_t blen );\n\n/**\n * \\brief           This function performs multiplication of a point by\n *                  an integer: \\p R = \\p m * \\p P.\n *\n *                  It is not thread-safe to use same group in multiple threads.\n *\n * \\note            To prevent timing attacks, this function\n *                  executes the exact same sequence of base-field\n *                  operations for any valid \\p m. It avoids any if-branch or\n *                  array index depending on the value of \\p m.\n *\n * \\note            If \\p f_rng is not NULL, it is used to randomize\n *                  intermediate results to prevent potential timing attacks\n *                  targeting these results. We recommend always providing\n *                  a non-NULL \\p f_rng. The overhead is negligible.\n *\n * \\param grp       The ECP group.\n * \\param R         The destination point.\n * \\param m         The integer by which to multiply.\n * \\param P         The point to multiply.\n * \\param f_rng     The RNG function.\n * \\param p_rng     The RNG context.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_ECP_INVALID_KEY if \\p m is not a valid private\n *                  key, or \\p P is not a valid public key.\n * \\return          #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.\n */\nint mbedtls_ecp_mul( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,\n             const mbedtls_mpi *m, const mbedtls_ecp_point *P,\n             int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );\n\n/**\n * \\brief           This function performs multiplication and addition of two\n *                  points by integers: \\p R = \\p m * \\p P + \\p n * \\p Q\n *\n *                  It is not thread-safe to use same group in multiple threads.\n *\n * \\note            In contrast to mbedtls_ecp_mul(), this function does not\n *                  guarantee a constant execution flow and timing.\n *\n * \\param grp       The ECP group.\n * \\param R         The destination point.\n * \\param m         The integer by which to multiply \\p P.\n * \\param P         The point to multiply by \\p m.\n * \\param n         The integer by which to multiply \\p Q.\n * \\param Q         The point to be multiplied by \\p n.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_ECP_INVALID_KEY if \\p m or \\p n are not\n *                  valid private keys, or \\p P or \\p Q are not valid public\n *                  keys.\n * \\return          #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.\n */\nint mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,\n             const mbedtls_mpi *m, const mbedtls_ecp_point *P,\n             const mbedtls_mpi *n, const mbedtls_ecp_point *Q );\n\n/**\n * \\brief           This function checks that a point is a valid public key\n *                  on this curve.\n *\n *                  It only checks that the point is non-zero, has\n *                  valid coordinates and lies on the curve. It does not verify\n *                  that it is indeed a multiple of \\p G. This additional\n *                  check is computationally more expensive, is not required\n *                  by standards, and should not be necessary if the group\n *                  used has a small cofactor. In particular, it is useless for\n *                  the NIST groups which all have a cofactor of 1.\n *\n * \\note            This function uses bare components rather than an\n *                  ::mbedtls_ecp_keypair structure, to ease use with other\n *                  structures, such as ::mbedtls_ecdh_context or\n *                  ::mbedtls_ecdsa_context.\n *\n * \\param grp       The curve the point should lie on.\n * \\param pt        The point to check.\n *\n * \\return          \\c 0 if the point is a valid public key.\n * \\return          #MBEDTLS_ERR_ECP_INVALID_KEY on failure.\n */\nint mbedtls_ecp_check_pubkey( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt );\n\n/**\n * \\brief           This function checks that an \\p mbedtls_mpi is a valid private\n *                  key for this curve.\n *\n * \\note            This function uses bare components rather than an\n *                  ::mbedtls_ecp_keypair structure to ease use with other\n *                  structures, such as ::mbedtls_ecdh_context or\n *                  ::mbedtls_ecdsa_context.\n *\n * \\param grp       The group used.\n * \\param d         The integer to check.\n *\n * \\return          \\c 0 if the point is a valid private key.\n * \\return          #MBEDTLS_ERR_ECP_INVALID_KEY on failure.\n */\nint mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp, const mbedtls_mpi *d );\n\n/**\n * \\brief           This function generates a keypair with a configurable base\n *                  point.\n *\n * \\note            This function uses bare components rather than an\n *                  ::mbedtls_ecp_keypair structure to ease use with other\n *                  structures, such as ::mbedtls_ecdh_context or\n *                  ::mbedtls_ecdsa_context.\n *\n * \\param grp       The ECP group.\n * \\param G         The chosen base point.\n * \\param d         The destination MPI (secret part).\n * \\param Q         The destination point (public part).\n * \\param f_rng     The RNG function.\n * \\param p_rng     The RNG context.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX or \\c MBEDTLS_MPI_XXX error code\n *                  on failure.\n */\nint mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp,\n                     const mbedtls_ecp_point *G,\n                     mbedtls_mpi *d, mbedtls_ecp_point *Q,\n                     int (*f_rng)(void *, unsigned char *, size_t),\n                     void *p_rng );\n\n/**\n * \\brief           This function generates an ECP keypair.\n *\n * \\note            This function uses bare components rather than an\n *                  ::mbedtls_ecp_keypair structure to ease use with other\n *                  structures, such as ::mbedtls_ecdh_context or\n *                  ::mbedtls_ecdsa_context.\n *\n * \\param grp       The ECP group.\n * \\param d         The destination MPI (secret part).\n * \\param Q         The destination point (public part).\n * \\param f_rng     The RNG function.\n * \\param p_rng     The RNG context.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX or \\c MBEDTLS_MPI_XXX error code\n *                  on failure.\n */\nint mbedtls_ecp_gen_keypair( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q,\n                     int (*f_rng)(void *, unsigned char *, size_t),\n                     void *p_rng );\n\n/**\n * \\brief           This function generates an ECP key.\n *\n * \\param grp_id    The ECP group identifier.\n * \\param key       The destination key.\n * \\param f_rng     The RNG function.\n * \\param p_rng     The RNG context.\n *\n * \\return          \\c 0 on success.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX or \\c MBEDTLS_MPI_XXX error code\n *                  on failure.\n */\nint mbedtls_ecp_gen_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key,\n                int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );\n\n/**\n * \\brief           This function checks that the keypair objects\n *                  \\p pub and \\p prv have the same group and the\n *                  same public point, and that the private key in\n *                  \\p prv is consistent with the public key.\n *\n * \\param pub       The keypair structure holding the public key.\n *                  If it contains a private key, that part is ignored.\n * \\param prv       The keypair structure holding the full keypair.\n *\n * \\return          \\c 0 on success, meaning that the keys are valid and match.\n * \\return          #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the keys are invalid or do not match.\n * \\return          An \\c MBEDTLS_ERR_ECP_XXX or an \\c MBEDTLS_ERR_MPI_XXX\n *                  error code on calculation failure.\n */\nint mbedtls_ecp_check_pub_priv( const mbedtls_ecp_keypair *pub, const mbedtls_ecp_keypair *prv );\n\n#if defined(MBEDTLS_SELF_TEST)\n\n/**\n * \\brief          The ECP checkup routine.\n *\n * \\return         \\c 0 on success.\n * \\return         \\c 1 on failure.\n */\nint mbedtls_ecp_self_test( int verbose );\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* ecp.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/ecp_internal.h",
    "content": "/**\n * \\file ecp_internal.h\n *\n * \\brief Function declarations for alternative implementation of elliptic curve\n * point arithmetic.\n */\n/*\n *  Copyright (C) 2016, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n/*\n * References:\n *\n * [1] BERNSTEIN, Daniel J. Curve25519: new Diffie-Hellman speed records.\n *     <http://cr.yp.to/ecdh/curve25519-20060209.pdf>\n *\n * [2] CORON, Jean-S'ebastien. Resistance against differential power analysis\n *     for elliptic curve cryptosystems. In : Cryptographic Hardware and\n *     Embedded Systems. Springer Berlin Heidelberg, 1999. p. 292-302.\n *     <http://link.springer.com/chapter/10.1007/3-540-48059-5_25>\n *\n * [3] HEDABOU, Mustapha, PINEL, Pierre, et B'EN'ETEAU, Lucien. A comb method to\n *     render ECC resistant against Side Channel Attacks. IACR Cryptology\n *     ePrint Archive, 2004, vol. 2004, p. 342.\n *     <http://eprint.iacr.org/2004/342.pdf>\n *\n * [4] Certicom Research. SEC 2: Recommended Elliptic Curve Domain Parameters.\n *     <http://www.secg.org/sec2-v2.pdf>\n *\n * [5] HANKERSON, Darrel, MENEZES, Alfred J., VANSTONE, Scott. Guide to Elliptic\n *     Curve Cryptography.\n *\n * [6] Digital Signature Standard (DSS), FIPS 186-4.\n *     <http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf>\n *\n * [7] Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer\n *     Security (TLS), RFC 4492.\n *     <https://tools.ietf.org/search/rfc4492>\n *\n * [8] <http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html>\n *\n * [9] COHEN, Henri. A Course in Computational Algebraic Number Theory.\n *     Springer Science & Business Media, 1 Aug 2000\n */\n\n#ifndef MBEDTLS_ECP_INTERNAL_H\n#define MBEDTLS_ECP_INTERNAL_H\n\n#if defined(MBEDTLS_ECP_INTERNAL_ALT)\n\n/**\n * \\brief           Indicate if the Elliptic Curve Point module extension can\n *                  handle the group.\n *\n * \\param grp       The pointer to the elliptic curve group that will be the\n *                  basis of the cryptographic computations.\n *\n * \\return          Non-zero if successful.\n */\nunsigned char mbedtls_internal_ecp_grp_capable( const mbedtls_ecp_group *grp );\n\n/**\n * \\brief           Initialise the Elliptic Curve Point module extension.\n *\n *                  If mbedtls_internal_ecp_grp_capable returns true for a\n *                  group, this function has to be able to initialise the\n *                  module for it.\n *\n *                  This module can be a driver to a crypto hardware\n *                  accelerator, for which this could be an initialise function.\n *\n * \\param grp       The pointer to the group the module needs to be\n *                  initialised for.\n *\n * \\return          0 if successful.\n */\nint mbedtls_internal_ecp_init( const mbedtls_ecp_group *grp );\n\n/**\n * \\brief           Frees and deallocates the Elliptic Curve Point module\n *                  extension.\n *\n * \\param grp       The pointer to the group the module was initialised for.\n */\nvoid mbedtls_internal_ecp_free( const mbedtls_ecp_group *grp );\n\n#if defined(ECP_SHORTWEIERSTRASS)\n\n#if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT)\n/**\n * \\brief           Randomize jacobian coordinates:\n *                  (X, Y, Z) -> (l^2 X, l^3 Y, l Z) for random l.\n *\n * \\param grp       Pointer to the group representing the curve.\n *\n * \\param pt        The point on the curve to be randomised, given with Jacobian\n *                  coordinates.\n *\n * \\param f_rng     A function pointer to the random number generator.\n *\n * \\param p_rng     A pointer to the random number generator state.\n *\n * \\return          0 if successful.\n */\nint mbedtls_internal_ecp_randomize_jac( const mbedtls_ecp_group *grp,\n        mbedtls_ecp_point *pt, int (*f_rng)(void *, unsigned char *, size_t),\n        void *p_rng );\n#endif\n\n#if defined(MBEDTLS_ECP_ADD_MIXED_ALT)\n/**\n * \\brief           Addition: R = P + Q, mixed affine-Jacobian coordinates.\n *\n *                  The coordinates of Q must be normalized (= affine),\n *                  but those of P don't need to. R is not normalized.\n *\n *                  This function is used only as a subrutine of\n *                  ecp_mul_comb().\n *\n *                  Special cases: (1) P or Q is zero, (2) R is zero,\n *                      (3) P == Q.\n *                  None of these cases can happen as intermediate step in\n *                  ecp_mul_comb():\n *                      - at each step, P, Q and R are multiples of the base\n *                      point, the factor being less than its order, so none of\n *                      them is zero;\n *                      - Q is an odd multiple of the base point, P an even\n *                      multiple, due to the choice of precomputed points in the\n *                      modified comb method.\n *                  So branches for these cases do not leak secret information.\n *\n *                  We accept Q->Z being unset (saving memory in tables) as\n *                  meaning 1.\n *\n *                  Cost in field operations if done by [5] 3.22:\n *                      1A := 8M + 3S\n *\n * \\param grp       Pointer to the group representing the curve.\n *\n * \\param R         Pointer to a point structure to hold the result.\n *\n * \\param P         Pointer to the first summand, given with Jacobian\n *                  coordinates\n *\n * \\param Q         Pointer to the second summand, given with affine\n *                  coordinates.\n *\n * \\return          0 if successful.\n */\nint mbedtls_internal_ecp_add_mixed( const mbedtls_ecp_group *grp,\n        mbedtls_ecp_point *R, const mbedtls_ecp_point *P,\n        const mbedtls_ecp_point *Q );\n#endif\n\n/**\n * \\brief           Point doubling R = 2 P, Jacobian coordinates.\n *\n *                  Cost:   1D := 3M + 4S    (A ==  0)\n *                          4M + 4S          (A == -3)\n *                          3M + 6S + 1a     otherwise\n *                  when the implementation is based on the \"dbl-1998-cmo-2\"\n *                  doubling formulas in [8] and standard optimizations are\n *                  applied when curve parameter A is one of { 0, -3 }.\n *\n * \\param grp       Pointer to the group representing the curve.\n *\n * \\param R         Pointer to a point structure to hold the result.\n *\n * \\param P         Pointer to the point that has to be doubled, given with\n *                  Jacobian coordinates.\n *\n * \\return          0 if successful.\n */\n#if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT)\nint mbedtls_internal_ecp_double_jac( const mbedtls_ecp_group *grp,\n        mbedtls_ecp_point *R, const mbedtls_ecp_point *P );\n#endif\n\n/**\n * \\brief           Normalize jacobian coordinates of an array of (pointers to)\n *                  points.\n *\n *                  Using Montgomery's trick to perform only one inversion mod P\n *                  the cost is:\n *                      1N(t) := 1I + (6t - 3)M + 1S\n *                  (See for example Algorithm 10.3.4. in [9])\n *\n *                  This function is used only as a subrutine of\n *                  ecp_mul_comb().\n *\n *                  Warning: fails (returning an error) if one of the points is\n *                  zero!\n *                  This should never happen, see choice of w in ecp_mul_comb().\n *\n * \\param grp       Pointer to the group representing the curve.\n *\n * \\param T         Array of pointers to the points to normalise.\n *\n * \\param t_len     Number of elements in the array.\n *\n * \\return          0 if successful,\n *                      an error if one of the points is zero.\n */\n#if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT)\nint mbedtls_internal_ecp_normalize_jac_many( const mbedtls_ecp_group *grp,\n        mbedtls_ecp_point *T[], size_t t_len );\n#endif\n\n/**\n * \\brief           Normalize jacobian coordinates so that Z == 0 || Z == 1.\n *\n *                  Cost in field operations if done by [5] 3.2.1:\n *                      1N := 1I + 3M + 1S\n *\n * \\param grp       Pointer to the group representing the curve.\n *\n * \\param pt        pointer to the point to be normalised. This is an\n *                  input/output parameter.\n *\n * \\return          0 if successful.\n */\n#if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT)\nint mbedtls_internal_ecp_normalize_jac( const mbedtls_ecp_group *grp,\n        mbedtls_ecp_point *pt );\n#endif\n\n#endif /* ECP_SHORTWEIERSTRASS */\n\n#if defined(ECP_MONTGOMERY)\n\n#if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT)\nint mbedtls_internal_ecp_double_add_mxz( const mbedtls_ecp_group *grp,\n        mbedtls_ecp_point *R, mbedtls_ecp_point *S, const mbedtls_ecp_point *P,\n        const mbedtls_ecp_point *Q, const mbedtls_mpi *d );\n#endif\n\n/**\n * \\brief           Randomize projective x/z coordinates:\n *                      (X, Z) -> (l X, l Z) for random l\n *\n * \\param grp       pointer to the group representing the curve\n *\n * \\param P         the point on the curve to be randomised given with\n *                  projective coordinates. This is an input/output parameter.\n *\n * \\param f_rng     a function pointer to the random number generator\n *\n * \\param p_rng     a pointer to the random number generator state\n *\n * \\return          0 if successful\n */\n#if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT)\nint mbedtls_internal_ecp_randomize_mxz( const mbedtls_ecp_group *grp,\n        mbedtls_ecp_point *P, int (*f_rng)(void *, unsigned char *, size_t),\n        void *p_rng );\n#endif\n\n/**\n * \\brief           Normalize Montgomery x/z coordinates: X = X/Z, Z = 1.\n *\n * \\param grp       pointer to the group representing the curve\n *\n * \\param P         pointer to the point to be normalised. This is an\n *                  input/output parameter.\n *\n * \\return          0 if successful\n */\n#if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)\nint mbedtls_internal_ecp_normalize_mxz( const mbedtls_ecp_group *grp,\n        mbedtls_ecp_point *P );\n#endif\n\n#endif /* ECP_MONTGOMERY */\n\n#endif /* MBEDTLS_ECP_INTERNAL_ALT */\n\n#endif /* ecp_internal.h */\n\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/entropy.h",
    "content": "/**\n * \\file entropy.h\n *\n * \\brief Entropy accumulator implementation\n */\n/*\n *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_ENTROPY_H\n#define MBEDTLS_ENTROPY_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n\n#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256)\n#include \"sha512.h\"\n#define MBEDTLS_ENTROPY_SHA512_ACCUMULATOR\n#else\n#if defined(MBEDTLS_SHA256_C)\n#define MBEDTLS_ENTROPY_SHA256_ACCUMULATOR\n#include \"sha256.h\"\n#endif\n#endif\n\n#if defined(MBEDTLS_THREADING_C)\n#include \"threading.h\"\n#endif\n\n#if defined(MBEDTLS_HAVEGE_C)\n#include \"havege.h\"\n#endif\n\n#define MBEDTLS_ERR_ENTROPY_SOURCE_FAILED                 -0x003C  /**< Critical entropy source failure. */\n#define MBEDTLS_ERR_ENTROPY_MAX_SOURCES                   -0x003E  /**< No more sources can be added. */\n#define MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED            -0x0040  /**< No sources have been added to poll. */\n#define MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE              -0x003D  /**< No strong sources have been added to poll. */\n#define MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR                 -0x003F  /**< Read/write error in file. */\n\n/**\n * \\name SECTION: Module settings\n *\n * The configuration options you can set for this module are in this section.\n * Either change them in config.h or define them on the compiler command line.\n * \\{\n */\n\n#if !defined(MBEDTLS_ENTROPY_MAX_SOURCES)\n#define MBEDTLS_ENTROPY_MAX_SOURCES     20      /**< Maximum number of sources supported */\n#endif\n\n#if !defined(MBEDTLS_ENTROPY_MAX_GATHER)\n#define MBEDTLS_ENTROPY_MAX_GATHER      128     /**< Maximum amount requested from entropy sources */\n#endif\n\n/* \\} name SECTION: Module settings */\n\n#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)\n#define MBEDTLS_ENTROPY_BLOCK_SIZE      64      /**< Block size of entropy accumulator (SHA-512) */\n#else\n#define MBEDTLS_ENTROPY_BLOCK_SIZE      32      /**< Block size of entropy accumulator (SHA-256) */\n#endif\n\n#define MBEDTLS_ENTROPY_MAX_SEED_SIZE   1024    /**< Maximum size of seed we read from seed file */\n#define MBEDTLS_ENTROPY_SOURCE_MANUAL   MBEDTLS_ENTROPY_MAX_SOURCES\n\n#define MBEDTLS_ENTROPY_SOURCE_STRONG   1       /**< Entropy source is strong   */\n#define MBEDTLS_ENTROPY_SOURCE_WEAK     0       /**< Entropy source is weak     */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief           Entropy poll callback pointer\n *\n * \\param data      Callback-specific data pointer\n * \\param output    Data to fill\n * \\param len       Maximum size to provide\n * \\param olen      The actual amount of bytes put into the buffer (Can be 0)\n *\n * \\return          0 if no critical failures occurred,\n *                  MBEDTLS_ERR_ENTROPY_SOURCE_FAILED otherwise\n */\ntypedef int (*mbedtls_entropy_f_source_ptr)(void *data, unsigned char *output, size_t len,\n                            size_t *olen);\n\n/**\n * \\brief           Entropy source state\n */\ntypedef struct\n{\n    mbedtls_entropy_f_source_ptr    f_source;   /**< The entropy source callback */\n    void *          p_source;   /**< The callback data pointer */\n    size_t          size;       /**< Amount received in bytes */\n    size_t          threshold;  /**< Minimum bytes required before release */\n    int             strong;     /**< Is the source strong? */\n}\nmbedtls_entropy_source_state;\n\n/**\n * \\brief           Entropy context structure\n */\ntypedef struct\n{\n    int accumulator_started;\n#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)\n    mbedtls_sha512_context  accumulator;\n#else\n    mbedtls_sha256_context  accumulator;\n#endif\n    int             source_count;\n    mbedtls_entropy_source_state    source[MBEDTLS_ENTROPY_MAX_SOURCES];\n#if defined(MBEDTLS_HAVEGE_C)\n    mbedtls_havege_state    havege_data;\n#endif\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_threading_mutex_t mutex;    /*!< mutex                  */\n#endif\n#if defined(MBEDTLS_ENTROPY_NV_SEED)\n    int initial_entropy_run;\n#endif\n}\nmbedtls_entropy_context;\n\n/**\n * \\brief           Initialize the context\n *\n * \\param ctx       Entropy context to initialize\n */\nvoid mbedtls_entropy_init( mbedtls_entropy_context *ctx );\n\n/**\n * \\brief           Free the data in the context\n *\n * \\param ctx       Entropy context to free\n */\nvoid mbedtls_entropy_free( mbedtls_entropy_context *ctx );\n\n/**\n * \\brief           Adds an entropy source to poll\n *                  (Thread-safe if MBEDTLS_THREADING_C is enabled)\n *\n * \\param ctx       Entropy context\n * \\param f_source  Entropy function\n * \\param p_source  Function data\n * \\param threshold Minimum required from source before entropy is released\n *                  ( with mbedtls_entropy_func() ) (in bytes)\n * \\param strong    MBEDTLS_ENTROPY_SOURCE_STRONG or\n *                  MBEDTLS_ENTROPY_SOURCE_WEAK.\n *                  At least one strong source needs to be added.\n *                  Weaker sources (such as the cycle counter) can be used as\n *                  a complement.\n *\n * \\return          0 if successful or MBEDTLS_ERR_ENTROPY_MAX_SOURCES\n */\nint mbedtls_entropy_add_source( mbedtls_entropy_context *ctx,\n                        mbedtls_entropy_f_source_ptr f_source, void *p_source,\n                        size_t threshold, int strong );\n\n/**\n * \\brief           Trigger an extra gather poll for the accumulator\n *                  (Thread-safe if MBEDTLS_THREADING_C is enabled)\n *\n * \\param ctx       Entropy context\n *\n * \\return          0 if successful, or MBEDTLS_ERR_ENTROPY_SOURCE_FAILED\n */\nint mbedtls_entropy_gather( mbedtls_entropy_context *ctx );\n\n/**\n * \\brief           Retrieve entropy from the accumulator\n *                  (Maximum length: MBEDTLS_ENTROPY_BLOCK_SIZE)\n *                  (Thread-safe if MBEDTLS_THREADING_C is enabled)\n *\n * \\param data      Entropy context\n * \\param output    Buffer to fill\n * \\param len       Number of bytes desired, must be at most MBEDTLS_ENTROPY_BLOCK_SIZE\n *\n * \\return          0 if successful, or MBEDTLS_ERR_ENTROPY_SOURCE_FAILED\n */\nint mbedtls_entropy_func( void *data, unsigned char *output, size_t len );\n\n/**\n * \\brief           Add data to the accumulator manually\n *                  (Thread-safe if MBEDTLS_THREADING_C is enabled)\n *\n * \\param ctx       Entropy context\n * \\param data      Data to add\n * \\param len       Length of data\n *\n * \\return          0 if successful\n */\nint mbedtls_entropy_update_manual( mbedtls_entropy_context *ctx,\n                           const unsigned char *data, size_t len );\n\n#if defined(MBEDTLS_ENTROPY_NV_SEED)\n/**\n * \\brief           Trigger an update of the seed file in NV by using the\n *                  current entropy pool.\n *\n * \\param ctx       Entropy context\n *\n * \\return          0 if successful\n */\nint mbedtls_entropy_update_nv_seed( mbedtls_entropy_context *ctx );\n#endif /* MBEDTLS_ENTROPY_NV_SEED */\n\n#if defined(MBEDTLS_FS_IO)\n/**\n * \\brief               Write a seed file\n *\n * \\param ctx           Entropy context\n * \\param path          Name of the file\n *\n * \\return              0 if successful,\n *                      MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR on file error, or\n *                      MBEDTLS_ERR_ENTROPY_SOURCE_FAILED\n */\nint mbedtls_entropy_write_seed_file( mbedtls_entropy_context *ctx, const char *path );\n\n/**\n * \\brief               Read and update a seed file. Seed is added to this\n *                      instance. No more than MBEDTLS_ENTROPY_MAX_SEED_SIZE bytes are\n *                      read from the seed file. The rest is ignored.\n *\n * \\param ctx           Entropy context\n * \\param path          Name of the file\n *\n * \\return              0 if successful,\n *                      MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR on file error,\n *                      MBEDTLS_ERR_ENTROPY_SOURCE_FAILED\n */\nint mbedtls_entropy_update_seed_file( mbedtls_entropy_context *ctx, const char *path );\n#endif /* MBEDTLS_FS_IO */\n\n#if defined(MBEDTLS_SELF_TEST)\n/**\n * \\brief          Checkup routine\n *\n *                 This module self-test also calls the entropy self-test,\n *                 mbedtls_entropy_source_self_test();\n *\n * \\return         0 if successful, or 1 if a test failed\n */\nint mbedtls_entropy_self_test( int verbose );\n\n#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)\n/**\n * \\brief          Checkup routine\n *\n *                 Verifies the integrity of the hardware entropy source\n *                 provided by the function 'mbedtls_hardware_poll()'.\n *\n *                 Note this is the only hardware entropy source that is known\n *                 at link time, and other entropy sources configured\n *                 dynamically at runtime by the function\n *                 mbedtls_entropy_add_source() will not be tested.\n *\n * \\return         0 if successful, or 1 if a test failed\n */\nint mbedtls_entropy_source_self_test( int verbose );\n#endif /* MBEDTLS_ENTROPY_HARDWARE_ALT */\n#endif /* MBEDTLS_SELF_TEST */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* entropy.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/entropy_poll.h",
    "content": "/**\n * \\file entropy_poll.h\n *\n * \\brief Platform-specific and custom entropy polling functions\n */\n/*\n *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_ENTROPY_POLL_H\n#define MBEDTLS_ENTROPY_POLL_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*\n * Default thresholds for built-in sources, in bytes\n */\n#define MBEDTLS_ENTROPY_MIN_PLATFORM     32     /**< Minimum for platform source    */\n#define MBEDTLS_ENTROPY_MIN_HAVEGE       32     /**< Minimum for HAVEGE             */\n#define MBEDTLS_ENTROPY_MIN_HARDCLOCK     4     /**< Minimum for mbedtls_timing_hardclock()        */\n#if !defined(MBEDTLS_ENTROPY_MIN_HARDWARE)\n#define MBEDTLS_ENTROPY_MIN_HARDWARE     32     /**< Minimum for the hardware source */\n#endif\n\n/**\n * \\brief           Entropy poll callback that provides 0 entropy.\n */\n#if defined(MBEDTLS_TEST_NULL_ENTROPY)\n    int mbedtls_null_entropy_poll( void *data,\n                                unsigned char *output, size_t len, size_t *olen );\n#endif\n\n#if !defined(MBEDTLS_NO_PLATFORM_ENTROPY)\n/**\n * \\brief           Platform-specific entropy poll callback\n */\nint mbedtls_platform_entropy_poll( void *data,\n                           unsigned char *output, size_t len, size_t *olen );\n#endif\n\n#if defined(MBEDTLS_HAVEGE_C)\n/**\n * \\brief           HAVEGE based entropy poll callback\n *\n * Requires an HAVEGE state as its data pointer.\n */\nint mbedtls_havege_poll( void *data,\n                 unsigned char *output, size_t len, size_t *olen );\n#endif\n\n#if defined(MBEDTLS_TIMING_C)\n/**\n * \\brief           mbedtls_timing_hardclock-based entropy poll callback\n */\nint mbedtls_hardclock_poll( void *data,\n                    unsigned char *output, size_t len, size_t *olen );\n#endif\n\n#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)\n/**\n * \\brief           Entropy poll callback for a hardware source\n *\n * \\warning         This is not provided by mbed TLS!\n *                  See \\c MBEDTLS_ENTROPY_HARDWARE_ALT in config.h.\n *\n * \\note            This must accept NULL as its first argument.\n */\nint mbedtls_hardware_poll( void *data,\n                           unsigned char *output, size_t len, size_t *olen );\n#endif\n\n#if defined(MBEDTLS_ENTROPY_NV_SEED)\n/**\n * \\brief           Entropy poll callback for a non-volatile seed file\n *\n * \\note            This must accept NULL as its first argument.\n */\nint mbedtls_nv_seed_poll( void *data,\n                          unsigned char *output, size_t len, size_t *olen );\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* entropy_poll.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/error.h",
    "content": "/**\n * \\file error.h\n *\n * \\brief Error to string translation\n */\n/*\n *  Copyright (C) 2006-2018, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_ERROR_H\n#define MBEDTLS_ERROR_H\n\n#include <stddef.h>\n\n/**\n * Error code layout.\n *\n * Currently we try to keep all error codes within the negative space of 16\n * bits signed integers to support all platforms (-0x0001 - -0x7FFF). In\n * addition we'd like to give two layers of information on the error if\n * possible.\n *\n * For that purpose the error codes are segmented in the following manner:\n *\n * 16 bit error code bit-segmentation\n *\n * 1 bit  - Unused (sign bit)\n * 3 bits - High level module ID\n * 5 bits - Module-dependent error code\n * 7 bits - Low level module errors\n *\n * For historical reasons, low-level error codes are divided in even and odd,\n * even codes were assigned first, and -1 is reserved for other errors.\n *\n * Low-level module errors (0x0002-0x007E, 0x0003-0x007F)\n *\n * Module   Nr  Codes assigned\n * MPI       7  0x0002-0x0010\n * GCM       3  0x0012-0x0014   0x0013-0x0013\n * BLOWFISH  3  0x0016-0x0018   0x0017-0x0017\n * THREADING 3  0x001A-0x001E\n * AES       5  0x0020-0x0022   0x0021-0x0025\n * CAMELLIA  3  0x0024-0x0026   0x0027-0x0027\n * XTEA      2  0x0028-0x0028   0x0029-0x0029\n * BASE64    2  0x002A-0x002C\n * OID       1  0x002E-0x002E   0x000B-0x000B\n * PADLOCK   1  0x0030-0x0030\n * DES       2  0x0032-0x0032   0x0033-0x0033\n * CTR_DBRG  4  0x0034-0x003A\n * ENTROPY   3  0x003C-0x0040   0x003D-0x003F\n * NET      13  0x0042-0x0052   0x0043-0x0049\n * ARIA      4  0x0058-0x005E\n * ASN1      7  0x0060-0x006C\n * CMAC      1  0x007A-0x007A\n * PBKDF2    1  0x007C-0x007C\n * HMAC_DRBG 4                  0x0003-0x0009\n * CCM       3                  0x000D-0x0011\n * ARC4      1                  0x0019-0x0019\n * MD2       1                  0x002B-0x002B\n * MD4       1                  0x002D-0x002D\n * MD5       1                  0x002F-0x002F\n * RIPEMD160 1                  0x0031-0x0031\n * SHA1      1                  0x0035-0x0035\n * SHA256    1                  0x0037-0x0037\n * SHA512    1                  0x0039-0x0039\n * CHACHA20  3                  0x0051-0x0055\n * POLY1305  3                  0x0057-0x005B\n * CHACHAPOLY 2 0x0054-0x0056\n *\n * High-level module nr (3 bits - 0x0...-0x7...)\n * Name      ID  Nr of Errors\n * PEM       1   9\n * PKCS#12   1   4 (Started from top)\n * X509      2   20\n * PKCS5     2   4 (Started from top)\n * DHM       3   11\n * PK        3   15 (Started from top)\n * RSA       4   11\n * ECP       4   9 (Started from top)\n * MD        5   5\n * HKDF      5   1 (Started from top)\n * CIPHER    6   8\n * SSL       6   22 (Started from top)\n * SSL       7   31\n *\n * Module dependent error code (5 bits 0x.00.-0x.F8.)\n */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief Translate a mbed TLS error code into a string representation,\n *        Result is truncated if necessary and always includes a terminating\n *        null byte.\n *\n * \\param errnum    error code\n * \\param buffer    buffer to place representation in\n * \\param buflen    length of the buffer\n */\nvoid mbedtls_strerror( int errnum, char *buffer, size_t buflen );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* error.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/gcm.h",
    "content": "/**\n * \\file gcm.h\n *\n * \\brief This file contains GCM definitions and functions.\n *\n * The Galois/Counter Mode (GCM) for 128-bit block ciphers is defined\n * in <em>D. McGrew, J. Viega, The Galois/Counter Mode of Operation\n * (GCM), Natl. Inst. Stand. Technol.</em>\n *\n * For more information on GCM, see <em>NIST SP 800-38D: Recommendation for\n * Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC</em>.\n *\n */\n/*\n *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_GCM_H\n#define MBEDTLS_GCM_H\n\n#include \"cipher.h\"\n\n#include <stdint.h>\n\n#define MBEDTLS_GCM_ENCRYPT     1\n#define MBEDTLS_GCM_DECRYPT     0\n\n#define MBEDTLS_ERR_GCM_AUTH_FAILED                       -0x0012  /**< Authenticated decryption failed. */\n#define MBEDTLS_ERR_GCM_HW_ACCEL_FAILED                   -0x0013  /**< GCM hardware accelerator failed. */\n#define MBEDTLS_ERR_GCM_BAD_INPUT                         -0x0014  /**< Bad input parameters to function. */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_GCM_ALT)\n\n/**\n * \\brief          The GCM context structure.\n */\ntypedef struct {\n    mbedtls_cipher_context_t cipher_ctx;  /*!< The cipher context used. */\n    uint64_t HL[16];                      /*!< Precalculated HTable low. */\n    uint64_t HH[16];                      /*!< Precalculated HTable high. */\n    uint64_t len;                         /*!< The total length of the encrypted data. */\n    uint64_t add_len;                     /*!< The total length of the additional data. */\n    unsigned char base_ectr[16];          /*!< The first ECTR for tag. */\n    unsigned char y[16];                  /*!< The Y working value. */\n    unsigned char buf[16];                /*!< The buf working value. */\n    int mode;                             /*!< The operation to perform:\n                                               #MBEDTLS_GCM_ENCRYPT or\n                                               #MBEDTLS_GCM_DECRYPT. */\n}\nmbedtls_gcm_context;\n\n#else  /* !MBEDTLS_GCM_ALT */\n#include \"gcm_alt.h\"\n#endif /* !MBEDTLS_GCM_ALT */\n\n/**\n * \\brief           This function initializes the specified GCM context,\n *                  to make references valid, and prepares the context\n *                  for mbedtls_gcm_setkey() or mbedtls_gcm_free().\n *\n *                  The function does not bind the GCM context to a particular\n *                  cipher, nor set the key. For this purpose, use\n *                  mbedtls_gcm_setkey().\n *\n * \\param ctx       The GCM context to initialize.\n */\nvoid mbedtls_gcm_init( mbedtls_gcm_context *ctx );\n\n/**\n * \\brief           This function associates a GCM context with a\n *                  cipher algorithm and a key.\n *\n * \\param ctx       The GCM context to initialize.\n * \\param cipher    The 128-bit block cipher to use.\n * \\param key       The encryption key.\n * \\param keybits   The key size in bits. Valid options are:\n *                  <ul><li>128 bits</li>\n *                  <li>192 bits</li>\n *                  <li>256 bits</li></ul>\n *\n * \\return          \\c 0 on success.\n * \\return          A cipher-specific error code on failure.\n */\nint mbedtls_gcm_setkey( mbedtls_gcm_context *ctx,\n                        mbedtls_cipher_id_t cipher,\n                        const unsigned char *key,\n                        unsigned int keybits );\n\n/**\n * \\brief           This function performs GCM encryption or decryption of a buffer.\n *\n * \\note            For encryption, the output buffer can be the same as the\n *                  input buffer. For decryption, the output buffer cannot be\n *                  the same as input buffer. If the buffers overlap, the output\n *                  buffer must trail at least 8 Bytes behind the input buffer.\n *\n * \\warning         When this function performs a decryption, it outputs the\n *                  authentication tag and does not verify that the data is\n *                  authentic. You should use this function to perform encryption\n *                  only. For decryption, use mbedtls_gcm_auth_decrypt() instead.\n *\n * \\param ctx       The GCM context to use for encryption or decryption.\n * \\param mode      The operation to perform:\n *                  - #MBEDTLS_GCM_ENCRYPT to perform authenticated encryption.\n *                    The ciphertext is written to \\p output and the\n *                    authentication tag is written to \\p tag.\n *                  - #MBEDTLS_GCM_DECRYPT to perform decryption.\n *                    The plaintext is written to \\p output and the\n *                    authentication tag is written to \\p tag.\n *                    Note that this mode is not recommended, because it does\n *                    not verify the authenticity of the data. For this reason,\n *                    you should use mbedtls_gcm_auth_decrypt() instead of\n *                    calling this function in decryption mode.\n * \\param length    The length of the input data, which is equal to the length\n *                  of the output data.\n * \\param iv        The initialization vector.\n * \\param iv_len    The length of the IV.\n * \\param add       The buffer holding the additional data.\n * \\param add_len   The length of the additional data.\n * \\param input     The buffer holding the input data. Its size is \\b length.\n * \\param output    The buffer for holding the output data. It must have room\n *                  for \\b length bytes.\n * \\param tag_len   The length of the tag to generate.\n * \\param tag       The buffer for holding the tag.\n *\n * \\return          \\c 0 if the encryption or decryption was performed\n *                  successfully. Note that in #MBEDTLS_GCM_DECRYPT mode,\n *                  this does not indicate that the data is authentic.\n * \\return          #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths are not valid.\n * \\return          #MBEDTLS_ERR_GCM_HW_ACCEL_FAILED or a cipher-specific\n *                  error code if the encryption or decryption failed.\n */\nint mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx,\n                       int mode,\n                       size_t length,\n                       const unsigned char *iv,\n                       size_t iv_len,\n                       const unsigned char *add,\n                       size_t add_len,\n                       const unsigned char *input,\n                       unsigned char *output,\n                       size_t tag_len,\n                       unsigned char *tag );\n\n/**\n * \\brief           This function performs a GCM authenticated decryption of a\n *                  buffer.\n *\n * \\note            For decryption, the output buffer cannot be the same as\n *                  input buffer. If the buffers overlap, the output buffer\n *                  must trail at least 8 Bytes behind the input buffer.\n *\n * \\param ctx       The GCM context.\n * \\param length    The length of the ciphertext to decrypt, which is also\n *                  the length of the decrypted plaintext.\n * \\param iv        The initialization vector.\n * \\param iv_len    The length of the IV.\n * \\param add       The buffer holding the additional data.\n * \\param add_len   The length of the additional data.\n * \\param tag       The buffer holding the tag to verify.\n * \\param tag_len   The length of the tag to verify.\n * \\param input     The buffer holding the ciphertext. Its size is \\b length.\n * \\param output    The buffer for holding the decrypted plaintext. It must\n *                  have room for \\b length bytes.\n *\n * \\return          \\c 0 if successful and authenticated.\n * \\return          #MBEDTLS_ERR_GCM_AUTH_FAILED if the tag does not match.\n * \\return          #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths are not valid.\n * \\return          #MBEDTLS_ERR_GCM_HW_ACCEL_FAILED or a cipher-specific\n *                  error code if the decryption failed.\n */\nint mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx,\n                      size_t length,\n                      const unsigned char *iv,\n                      size_t iv_len,\n                      const unsigned char *add,\n                      size_t add_len,\n                      const unsigned char *tag,\n                      size_t tag_len,\n                      const unsigned char *input,\n                      unsigned char *output );\n\n/**\n * \\brief           This function starts a GCM encryption or decryption\n *                  operation.\n *\n * \\param ctx       The GCM context.\n * \\param mode      The operation to perform: #MBEDTLS_GCM_ENCRYPT or\n *                  #MBEDTLS_GCM_DECRYPT.\n * \\param iv        The initialization vector.\n * \\param iv_len    The length of the IV.\n * \\param add       The buffer holding the additional data, or NULL\n *                  if \\p add_len is 0.\n * \\param add_len   The length of the additional data. If 0,\n *                  \\p add is NULL.\n *\n * \\return          \\c 0 on success.\n */\nint mbedtls_gcm_starts( mbedtls_gcm_context *ctx,\n                int mode,\n                const unsigned char *iv,\n                size_t iv_len,\n                const unsigned char *add,\n                size_t add_len );\n\n/**\n * \\brief           This function feeds an input buffer into an ongoing GCM\n *                  encryption or decryption operation.\n *\n *    `             The function expects input to be a multiple of 16\n *                  Bytes. Only the last call before calling\n *                  mbedtls_gcm_finish() can be less than 16 Bytes.\n *\n * \\note            For decryption, the output buffer cannot be the same as\n *                  input buffer. If the buffers overlap, the output buffer\n *                  must trail at least 8 Bytes behind the input buffer.\n *\n * \\param ctx       The GCM context.\n * \\param length    The length of the input data. This must be a multiple of\n *                  16 except in the last call before mbedtls_gcm_finish().\n * \\param input     The buffer holding the input data.\n * \\param output    The buffer for holding the output data.\n *\n * \\return         \\c 0 on success.\n * \\return         #MBEDTLS_ERR_GCM_BAD_INPUT on failure.\n */\nint mbedtls_gcm_update( mbedtls_gcm_context *ctx,\n                size_t length,\n                const unsigned char *input,\n                unsigned char *output );\n\n/**\n * \\brief           This function finishes the GCM operation and generates\n *                  the authentication tag.\n *\n *                  It wraps up the GCM stream, and generates the\n *                  tag. The tag can have a maximum length of 16 Bytes.\n *\n * \\param ctx       The GCM context.\n * \\param tag       The buffer for holding the tag.\n * \\param tag_len   The length of the tag to generate. Must be at least four.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_GCM_BAD_INPUT on failure.\n */\nint mbedtls_gcm_finish( mbedtls_gcm_context *ctx,\n                unsigned char *tag,\n                size_t tag_len );\n\n/**\n * \\brief           This function clears a GCM context and the underlying\n *                  cipher sub-context.\n *\n * \\param ctx       The GCM context to clear.\n */\nvoid mbedtls_gcm_free( mbedtls_gcm_context *ctx );\n\n/**\n * \\brief          The GCM checkup routine.\n *\n * \\return         \\c 0 on success.\n * \\return         \\c 1 on failure.\n */\nint mbedtls_gcm_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n\n#endif /* gcm.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/havege.h",
    "content": "/**\n * \\file havege.h\n *\n * \\brief HAVEGE: HArdware Volatile Entropy Gathering and Expansion\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_HAVEGE_H\n#define MBEDTLS_HAVEGE_H\n\n#include <stddef.h>\n\n#define MBEDTLS_HAVEGE_COLLECT_SIZE 1024\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief          HAVEGE state structure\n */\ntypedef struct\n{\n    int PT1, PT2, offset[2];\n    int pool[MBEDTLS_HAVEGE_COLLECT_SIZE];\n    int WALK[8192];\n}\nmbedtls_havege_state;\n\n/**\n * \\brief          HAVEGE initialization\n *\n * \\param hs       HAVEGE state to be initialized\n */\nvoid mbedtls_havege_init( mbedtls_havege_state *hs );\n\n/**\n * \\brief          Clear HAVEGE state\n *\n * \\param hs       HAVEGE state to be cleared\n */\nvoid mbedtls_havege_free( mbedtls_havege_state *hs );\n\n/**\n * \\brief          HAVEGE rand function\n *\n * \\param p_rng    A HAVEGE state\n * \\param output   Buffer to fill\n * \\param len      Length of buffer\n *\n * \\return         0\n */\nint mbedtls_havege_random( void *p_rng, unsigned char *output, size_t len );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* havege.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/hkdf.h",
    "content": "/**\n * \\file hkdf.h\n *\n * \\brief   This file contains the HKDF interface.\n *\n *          The HMAC-based Extract-and-Expand Key Derivation Function (HKDF) is\n *          specified by RFC 5869.\n */\n/*\n * Copyright (C) 2016-2018, ARM Limited, All Rights Reserved\n * SPDX-License-Identifier: Apache-2.0\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_HKDF_H\n#define MBEDTLS_HKDF_H\n\n#include \"md.h\"\n\n/**\n *  \\name HKDF Error codes\n *  \\{\n */\n#define MBEDTLS_ERR_HKDF_BAD_INPUT_DATA  -0x5F80  /**< Bad input parameters to function. */\n/* \\} name */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n *  \\brief  This is the HMAC-based Extract-and-Expand Key Derivation Function\n *          (HKDF).\n *\n *  \\param  md        A hash function; md.size denotes the length of the hash\n *                    function output in bytes.\n *  \\param  salt      An optional salt value (a non-secret random value);\n *                    if the salt is not provided, a string of all zeros of\n *                    md.size length is used as the salt.\n *  \\param  salt_len  The length in bytes of the optional \\p salt.\n *  \\param  ikm       The input keying material.\n *  \\param  ikm_len   The length in bytes of \\p ikm.\n *  \\param  info      An optional context and application specific information\n *                    string. This can be a zero-length string.\n *  \\param  info_len  The length of \\p info in bytes.\n *  \\param  okm       The output keying material of \\p okm_len bytes.\n *  \\param  okm_len   The length of the output keying material in bytes. This\n *                    must be less than or equal to 255 * md.size bytes.\n *\n *  \\return 0 on success.\n *  \\return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid.\n *  \\return An MBEDTLS_ERR_MD_* error for errors returned from the underlying\n *          MD layer.\n */\nint mbedtls_hkdf( const mbedtls_md_info_t *md, const unsigned char *salt,\n                  size_t salt_len, const unsigned char *ikm, size_t ikm_len,\n                  const unsigned char *info, size_t info_len,\n                  unsigned char *okm, size_t okm_len );\n\n/**\n *  \\brief  Take the input keying material \\p ikm and extract from it a\n *          fixed-length pseudorandom key \\p prk.\n *\n *  \\param       md        A hash function; md.size denotes the length of the\n *                         hash function output in bytes.\n *  \\param       salt      An optional salt value (a non-secret random value);\n *                         if the salt is not provided, a string of all zeros\n *                         of md.size length is used as the salt.\n *  \\param       salt_len  The length in bytes of the optional \\p salt.\n *  \\param       ikm       The input keying material.\n *  \\param       ikm_len   The length in bytes of \\p ikm.\n *  \\param[out]  prk       A pseudorandom key of at least md.size bytes.\n *\n *  \\return 0 on success.\n *  \\return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid.\n *  \\return An MBEDTLS_ERR_MD_* error for errors returned from the underlying\n *          MD layer.\n */\nint mbedtls_hkdf_extract( const mbedtls_md_info_t *md,\n                          const unsigned char *salt, size_t salt_len,\n                          const unsigned char *ikm, size_t ikm_len,\n                          unsigned char *prk );\n\n/**\n *  \\brief  Expand the supplied \\p prk into several additional pseudorandom\n *          keys, which is the output of the HKDF.\n *\n *  \\param  md        A hash function; md.size denotes the length of the hash\n *                    function output in bytes.\n *  \\param  prk       A pseudorandom key of at least md.size bytes. \\p prk is usually,\n *                    the output from the HKDF extract step.\n *  \\param  prk_len   The length in bytes of \\p prk.\n *  \\param  info      An optional context and application specific information\n *                    string. This can be a zero-length string.\n *  \\param  info_len  The length of \\p info in bytes.\n *  \\param  okm       The output keying material of \\p okm_len bytes.\n *  \\param  okm_len   The length of the output keying material in bytes. This\n *                    must be less than or equal to 255 * md.size bytes.\n *\n *  \\return 0 on success.\n *  \\return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid.\n *  \\return An MBEDTLS_ERR_MD_* error for errors returned from the underlying\n *          MD layer.\n */\nint mbedtls_hkdf_expand( const mbedtls_md_info_t *md, const unsigned char *prk,\n                         size_t prk_len, const unsigned char *info,\n                         size_t info_len, unsigned char *okm, size_t okm_len );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* hkdf.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/hmac_drbg.h",
    "content": "/**\n * \\file hmac_drbg.h\n *\n * \\brief HMAC_DRBG (NIST SP 800-90A)\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_HMAC_DRBG_H\n#define MBEDTLS_HMAC_DRBG_H\n\n#include \"md.h\"\n\n#if defined(MBEDTLS_THREADING_C)\n#include \"threading.h\"\n#endif\n\n/*\n * Error codes\n */\n#define MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG              -0x0003  /**< Too many random requested in single call. */\n#define MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG                -0x0005  /**< Input too large (Entropy + additional). */\n#define MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR                -0x0007  /**< Read/write error in file. */\n#define MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED        -0x0009  /**< The entropy source failed. */\n\n/**\n * \\name SECTION: Module settings\n *\n * The configuration options you can set for this module are in this section.\n * Either change them in config.h or define them on the compiler command line.\n * \\{\n */\n\n#if !defined(MBEDTLS_HMAC_DRBG_RESEED_INTERVAL)\n#define MBEDTLS_HMAC_DRBG_RESEED_INTERVAL   10000   /**< Interval before reseed is performed by default */\n#endif\n\n#if !defined(MBEDTLS_HMAC_DRBG_MAX_INPUT)\n#define MBEDTLS_HMAC_DRBG_MAX_INPUT         256     /**< Maximum number of additional input bytes */\n#endif\n\n#if !defined(MBEDTLS_HMAC_DRBG_MAX_REQUEST)\n#define MBEDTLS_HMAC_DRBG_MAX_REQUEST       1024    /**< Maximum number of requested bytes per call */\n#endif\n\n#if !defined(MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT)\n#define MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT    384     /**< Maximum size of (re)seed buffer */\n#endif\n\n/* \\} name SECTION: Module settings */\n\n#define MBEDTLS_HMAC_DRBG_PR_OFF   0   /**< No prediction resistance       */\n#define MBEDTLS_HMAC_DRBG_PR_ON    1   /**< Prediction resistance enabled  */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * HMAC_DRBG context.\n */\ntypedef struct\n{\n    /* Working state: the key K is not stored explicitely,\n     * but is implied by the HMAC context */\n    mbedtls_md_context_t md_ctx;                    /*!< HMAC context (inc. K)  */\n    unsigned char V[MBEDTLS_MD_MAX_SIZE];  /*!< V in the spec          */\n    int reseed_counter;                     /*!< reseed counter         */\n\n    /* Administrative state */\n    size_t entropy_len;         /*!< entropy bytes grabbed on each (re)seed */\n    int prediction_resistance;  /*!< enable prediction resistance (Automatic\n                                     reseed before every random generation) */\n    int reseed_interval;        /*!< reseed interval   */\n\n    /* Callbacks */\n    int (*f_entropy)(void *, unsigned char *, size_t); /*!< entropy function */\n    void *p_entropy;            /*!< context for the entropy function        */\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_threading_mutex_t mutex;\n#endif\n} mbedtls_hmac_drbg_context;\n\n/**\n * \\brief               HMAC_DRBG context initialization\n *                      Makes the context ready for mbedtls_hmac_drbg_seed(),\n *                      mbedtls_hmac_drbg_seed_buf() or\n *                      mbedtls_hmac_drbg_free().\n *\n * \\param ctx           HMAC_DRBG context to be initialized\n */\nvoid mbedtls_hmac_drbg_init( mbedtls_hmac_drbg_context *ctx );\n\n/**\n * \\brief               HMAC_DRBG initial seeding\n *                      Seed and setup entropy source for future reseeds.\n *\n * \\param ctx           HMAC_DRBG context to be seeded\n * \\param md_info       MD algorithm to use for HMAC_DRBG\n * \\param f_entropy     Entropy callback (p_entropy, buffer to fill, buffer\n *                      length)\n * \\param p_entropy     Entropy context\n * \\param custom        Personalization data (Device specific identifiers)\n *                      (Can be NULL)\n * \\param len           Length of personalization data\n *\n * \\note                The \"security strength\" as defined by NIST is set to:\n *                      128 bits if md_alg is SHA-1,\n *                      192 bits if md_alg is SHA-224,\n *                      256 bits if md_alg is SHA-256 or higher.\n *                      Note that SHA-256 is just as efficient as SHA-224.\n *\n * \\return              0 if successful, or\n *                      MBEDTLS_ERR_MD_BAD_INPUT_DATA, or\n *                      MBEDTLS_ERR_MD_ALLOC_FAILED, or\n *                      MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED.\n */\nint mbedtls_hmac_drbg_seed( mbedtls_hmac_drbg_context *ctx,\n                    const mbedtls_md_info_t * md_info,\n                    int (*f_entropy)(void *, unsigned char *, size_t),\n                    void *p_entropy,\n                    const unsigned char *custom,\n                    size_t len );\n\n/**\n * \\brief               Initilisation of simpified HMAC_DRBG (never reseeds).\n *                      (For use with deterministic ECDSA.)\n *\n * \\param ctx           HMAC_DRBG context to be initialised\n * \\param md_info       MD algorithm to use for HMAC_DRBG\n * \\param data          Concatenation of entropy string and additional data\n * \\param data_len      Length of data in bytes\n *\n * \\return              0 if successful, or\n *                      MBEDTLS_ERR_MD_BAD_INPUT_DATA, or\n *                      MBEDTLS_ERR_MD_ALLOC_FAILED.\n */\nint mbedtls_hmac_drbg_seed_buf( mbedtls_hmac_drbg_context *ctx,\n                        const mbedtls_md_info_t * md_info,\n                        const unsigned char *data, size_t data_len );\n\n/**\n * \\brief               Enable / disable prediction resistance (Default: Off)\n *\n * Note: If enabled, entropy is used for ctx->entropy_len before each call!\n *       Only use this if you have ample supply of good entropy!\n *\n * \\param ctx           HMAC_DRBG context\n * \\param resistance    MBEDTLS_HMAC_DRBG_PR_ON or MBEDTLS_HMAC_DRBG_PR_OFF\n */\nvoid mbedtls_hmac_drbg_set_prediction_resistance( mbedtls_hmac_drbg_context *ctx,\n                                          int resistance );\n\n/**\n * \\brief               Set the amount of entropy grabbed on each reseed\n *                      (Default: given by the security strength, which\n *                      depends on the hash used, see \\c mbedtls_hmac_drbg_init() )\n *\n * \\param ctx           HMAC_DRBG context\n * \\param len           Amount of entropy to grab, in bytes\n */\nvoid mbedtls_hmac_drbg_set_entropy_len( mbedtls_hmac_drbg_context *ctx,\n                                size_t len );\n\n/**\n * \\brief               Set the reseed interval\n *                      (Default: MBEDTLS_HMAC_DRBG_RESEED_INTERVAL)\n *\n * \\param ctx           HMAC_DRBG context\n * \\param interval      Reseed interval\n */\nvoid mbedtls_hmac_drbg_set_reseed_interval( mbedtls_hmac_drbg_context *ctx,\n                                    int interval );\n\n/**\n * \\brief               HMAC_DRBG update state\n *\n * \\param ctx           HMAC_DRBG context\n * \\param additional    Additional data to update state with, or NULL\n * \\param add_len       Length of additional data, or 0\n *\n * \\note                Additional data is optional, pass NULL and 0 as second\n *                      third argument if no additional data is being used.\n */\nvoid mbedtls_hmac_drbg_update( mbedtls_hmac_drbg_context *ctx,\n                       const unsigned char *additional, size_t add_len );\n\n/**\n * \\brief               HMAC_DRBG reseeding (extracts data from entropy source)\n *\n * \\param ctx           HMAC_DRBG context\n * \\param additional    Additional data to add to state (Can be NULL)\n * \\param len           Length of additional data\n *\n * \\return              0 if successful, or\n *                      MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED\n */\nint mbedtls_hmac_drbg_reseed( mbedtls_hmac_drbg_context *ctx,\n                      const unsigned char *additional, size_t len );\n\n/**\n * \\brief               HMAC_DRBG generate random with additional update input\n *\n * Note: Automatically reseeds if reseed_counter is reached or PR is enabled.\n *\n * \\param p_rng         HMAC_DRBG context\n * \\param output        Buffer to fill\n * \\param output_len    Length of the buffer\n * \\param additional    Additional data to update with (can be NULL)\n * \\param add_len       Length of additional data (can be 0)\n *\n * \\return              0 if successful, or\n *                      MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED, or\n *                      MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG, or\n *                      MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG.\n */\nint mbedtls_hmac_drbg_random_with_add( void *p_rng,\n                               unsigned char *output, size_t output_len,\n                               const unsigned char *additional,\n                               size_t add_len );\n\n/**\n * \\brief               HMAC_DRBG generate random\n *\n * Note: Automatically reseeds if reseed_counter is reached or PR is enabled.\n *\n * \\param p_rng         HMAC_DRBG context\n * \\param output        Buffer to fill\n * \\param out_len       Length of the buffer\n *\n * \\return              0 if successful, or\n *                      MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED, or\n *                      MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG\n */\nint mbedtls_hmac_drbg_random( void *p_rng, unsigned char *output, size_t out_len );\n\n/**\n * \\brief               Free an HMAC_DRBG context\n *\n * \\param ctx           HMAC_DRBG context to free.\n */\nvoid mbedtls_hmac_drbg_free( mbedtls_hmac_drbg_context *ctx );\n\n#if defined(MBEDTLS_FS_IO)\n/**\n * \\brief               Write a seed file\n *\n * \\param ctx           HMAC_DRBG context\n * \\param path          Name of the file\n *\n * \\return              0 if successful, 1 on file error, or\n *                      MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED\n */\nint mbedtls_hmac_drbg_write_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path );\n\n/**\n * \\brief               Read and update a seed file. Seed is added to this\n *                      instance\n *\n * \\param ctx           HMAC_DRBG context\n * \\param path          Name of the file\n *\n * \\return              0 if successful, 1 on file error,\n *                      MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED or\n *                      MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG\n */\nint mbedtls_hmac_drbg_update_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path );\n#endif /* MBEDTLS_FS_IO */\n\n\n#if defined(MBEDTLS_SELF_TEST)\n/**\n * \\brief               Checkup routine\n *\n * \\return              0 if successful, or 1 if the test failed\n */\nint mbedtls_hmac_drbg_self_test( int verbose );\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* hmac_drbg.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/md.h",
    "content": " /**\n * \\file md.h\n *\n * \\brief This file contains the generic message-digest wrapper.\n *\n * \\author Adriaan de Jong <dejong@fox-it.com>\n */\n/*\n *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_MD_H\n#define MBEDTLS_MD_H\n\n#include <stddef.h>\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#define MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE                -0x5080  /**< The selected feature is not available. */\n#define MBEDTLS_ERR_MD_BAD_INPUT_DATA                     -0x5100  /**< Bad input parameters to function. */\n#define MBEDTLS_ERR_MD_ALLOC_FAILED                       -0x5180  /**< Failed to allocate memory. */\n#define MBEDTLS_ERR_MD_FILE_IO_ERROR                      -0x5200  /**< Opening or reading of file failed. */\n#define MBEDTLS_ERR_MD_HW_ACCEL_FAILED                    -0x5280  /**< MD hardware accelerator failed. */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief     Supported message digests.\n *\n * \\warning   MD2, MD4, MD5 and SHA-1 are considered weak message digests and\n *            their use constitutes a security risk. We recommend considering\n *            stronger message digests instead.\n *\n */\ntypedef enum {\n    MBEDTLS_MD_NONE=0,    /**< None. */\n    MBEDTLS_MD_MD2,       /**< The MD2 message digest. */\n    MBEDTLS_MD_MD4,       /**< The MD4 message digest. */\n    MBEDTLS_MD_MD5,       /**< The MD5 message digest. */\n    MBEDTLS_MD_SHA1,      /**< The SHA-1 message digest. */\n    MBEDTLS_MD_SHA224,    /**< The SHA-224 message digest. */\n    MBEDTLS_MD_SHA256,    /**< The SHA-256 message digest. */\n    MBEDTLS_MD_SHA384,    /**< The SHA-384 message digest. */\n    MBEDTLS_MD_SHA512,    /**< The SHA-512 message digest. */\n    MBEDTLS_MD_RIPEMD160, /**< The RIPEMD-160 message digest. */\n} mbedtls_md_type_t;\n\n#if defined(MBEDTLS_SHA512_C)\n#define MBEDTLS_MD_MAX_SIZE         64  /* longest known is SHA512 */\n#else\n#define MBEDTLS_MD_MAX_SIZE         32  /* longest known is SHA256 or less */\n#endif\n\n/**\n * Opaque struct defined in md_internal.h.\n */\ntypedef struct mbedtls_md_info_t mbedtls_md_info_t;\n\n/**\n * The generic message-digest context.\n */\ntypedef struct {\n    /** Information about the associated message digest. */\n    const mbedtls_md_info_t *md_info;\n\n    /** The digest-specific context. */\n    void *md_ctx;\n\n    /** The HMAC part of the context. */\n    void *hmac_ctx;\n} mbedtls_md_context_t;\n\n/**\n * \\brief           This function returns the list of digests supported by the\n *                  generic digest module.\n *\n * \\return          A statically allocated array of digests. Each element\n *                  in the returned list is an integer belonging to the\n *                  message-digest enumeration #mbedtls_md_type_t.\n *                  The last entry is 0.\n */\nconst int *mbedtls_md_list( void );\n\n/**\n * \\brief           This function returns the message-digest information\n *                  associated with the given digest name.\n *\n * \\param md_name   The name of the digest to search for.\n *\n * \\return          The message-digest information associated with \\p md_name.\n * \\return          NULL if the associated message-digest information is not found.\n */\nconst mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name );\n\n/**\n * \\brief           This function returns the message-digest information\n *                  associated with the given digest type.\n *\n * \\param md_type   The type of digest to search for.\n *\n * \\return          The message-digest information associated with \\p md_type.\n * \\return          NULL if the associated message-digest information is not found.\n */\nconst mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type );\n\n/**\n * \\brief           This function initializes a message-digest context without\n *                  binding it to a particular message-digest algorithm.\n *\n *                  This function should always be called first. It prepares the\n *                  context for mbedtls_md_setup() for binding it to a\n *                  message-digest algorithm.\n */\nvoid mbedtls_md_init( mbedtls_md_context_t *ctx );\n\n/**\n * \\brief           This function clears the internal structure of \\p ctx and\n *                  frees any embedded internal structure, but does not free\n *                  \\p ctx itself.\n *\n *                  If you have called mbedtls_md_setup() on \\p ctx, you must\n *                  call mbedtls_md_free() when you are no longer using the\n *                  context.\n *                  Calling this function if you have previously\n *                  called mbedtls_md_init() and nothing else is optional.\n *                  You must not call this function if you have not called\n *                  mbedtls_md_init().\n */\nvoid mbedtls_md_free( mbedtls_md_context_t *ctx );\n\n#if ! defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED    __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n/**\n * \\brief           This function selects the message digest algorithm to use,\n *                  and allocates internal structures.\n *\n *                  It should be called after mbedtls_md_init() or mbedtls_md_free().\n *                  Makes it necessary to call mbedtls_md_free() later.\n *\n * \\deprecated      Superseded by mbedtls_md_setup() in 2.0.0\n *\n * \\param ctx       The context to set up.\n * \\param md_info   The information structure of the message-digest algorithm\n *                  to use.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification\n *                  failure.\n * \\return          #MBEDTLS_ERR_MD_ALLOC_FAILED on memory-allocation failure.\n */\nint mbedtls_md_init_ctx( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info ) MBEDTLS_DEPRECATED;\n#undef MBEDTLS_DEPRECATED\n#endif /* MBEDTLS_DEPRECATED_REMOVED */\n\n/**\n * \\brief           This function selects the message digest algorithm to use,\n *                  and allocates internal structures.\n *\n *                  It should be called after mbedtls_md_init() or\n *                  mbedtls_md_free(). Makes it necessary to call\n *                  mbedtls_md_free() later.\n *\n * \\param ctx       The context to set up.\n * \\param md_info   The information structure of the message-digest algorithm\n *                  to use.\n * \\param hmac      Defines if HMAC is used. 0: HMAC is not used (saves some memory),\n *                  or non-zero: HMAC is used with this context.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification\n *                  failure.\n * \\return          #MBEDTLS_ERR_MD_ALLOC_FAILED on memory-allocation failure.\n */\nint mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info, int hmac );\n\n/**\n * \\brief           This function clones the state of an message-digest\n *                  context.\n *\n * \\note            You must call mbedtls_md_setup() on \\c dst before calling\n *                  this function.\n *\n * \\note            The two contexts must have the same type,\n *                  for example, both are SHA-256.\n *\n * \\warning         This function clones the message-digest state, not the\n *                  HMAC state.\n *\n * \\param dst       The destination context.\n * \\param src       The context to be cloned.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification failure.\n */\nint mbedtls_md_clone( mbedtls_md_context_t *dst,\n                      const mbedtls_md_context_t *src );\n\n/**\n * \\brief           This function extracts the message-digest size from the\n *                  message-digest information structure.\n *\n * \\param md_info   The information structure of the message-digest algorithm\n *                  to use.\n *\n * \\return          The size of the message-digest output in Bytes.\n */\nunsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info );\n\n/**\n * \\brief           This function extracts the message-digest type from the\n *                  message-digest information structure.\n *\n * \\param md_info   The information structure of the message-digest algorithm\n *                  to use.\n *\n * \\return          The type of the message digest.\n */\nmbedtls_md_type_t mbedtls_md_get_type( const mbedtls_md_info_t *md_info );\n\n/**\n * \\brief           This function extracts the message-digest name from the\n *                  message-digest information structure.\n *\n * \\param md_info   The information structure of the message-digest algorithm\n *                  to use.\n *\n * \\return          The name of the message digest.\n */\nconst char *mbedtls_md_get_name( const mbedtls_md_info_t *md_info );\n\n/**\n * \\brief           This function starts a message-digest computation.\n *\n *                  You must call this function after setting up the context\n *                  with mbedtls_md_setup(), and before passing data with\n *                  mbedtls_md_update().\n *\n * \\param ctx       The generic message-digest context.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification\n *                  failure.\n */\nint mbedtls_md_starts( mbedtls_md_context_t *ctx );\n\n/**\n * \\brief           This function feeds an input buffer into an ongoing\n *                  message-digest computation.\n *\n *                  You must call mbedtls_md_starts() before calling this\n *                  function. You may call this function multiple times.\n *                  Afterwards, call mbedtls_md_finish().\n *\n * \\param ctx       The generic message-digest context.\n * \\param input     The buffer holding the input data.\n * \\param ilen      The length of the input data.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification\n *                  failure.\n */\nint mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen );\n\n/**\n * \\brief           This function finishes the digest operation,\n *                  and writes the result to the output buffer.\n *\n *                  Call this function after a call to mbedtls_md_starts(),\n *                  followed by any number of calls to mbedtls_md_update().\n *                  Afterwards, you may either clear the context with\n *                  mbedtls_md_free(), or call mbedtls_md_starts() to reuse\n *                  the context for another digest operation with the same\n *                  algorithm.\n *\n * \\param ctx       The generic message-digest context.\n * \\param output    The buffer for the generic message-digest checksum result.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification\n *                  failure.\n */\nint mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output );\n\n/**\n * \\brief          This function calculates the message-digest of a buffer,\n *                 with respect to a configurable message-digest algorithm\n *                 in a single call.\n *\n *                 The result is calculated as\n *                 Output = message_digest(input buffer).\n *\n * \\param md_info  The information structure of the message-digest algorithm\n *                 to use.\n * \\param input    The buffer holding the data.\n * \\param ilen     The length of the input data.\n * \\param output   The generic message-digest checksum result.\n *\n * \\return         \\c 0 on success.\n * \\return         #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification\n *                 failure.\n */\nint mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen,\n        unsigned char *output );\n\n#if defined(MBEDTLS_FS_IO)\n/**\n * \\brief          This function calculates the message-digest checksum\n *                 result of the contents of the provided file.\n *\n *                 The result is calculated as\n *                 Output = message_digest(file contents).\n *\n * \\param md_info  The information structure of the message-digest algorithm\n *                 to use.\n * \\param path     The input file name.\n * \\param output   The generic message-digest checksum result.\n *\n * \\return         \\c 0 on success.\n * \\return         #MBEDTLS_ERR_MD_FILE_IO_ERROR on an I/O error accessing\n *                 the file pointed by \\p path.\n * \\return         #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \\p md_info was NULL.\n */\nint mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path,\n                     unsigned char *output );\n#endif /* MBEDTLS_FS_IO */\n\n/**\n * \\brief           This function sets the HMAC key and prepares to\n *                  authenticate a new message.\n *\n *                  Call this function after mbedtls_md_setup(), to use\n *                  the MD context for an HMAC calculation, then call\n *                  mbedtls_md_hmac_update() to provide the input data, and\n *                  mbedtls_md_hmac_finish() to get the HMAC value.\n *\n * \\param ctx       The message digest context containing an embedded HMAC\n *                  context.\n * \\param key       The HMAC secret key.\n * \\param keylen    The length of the HMAC key in Bytes.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification\n *                  failure.\n */\nint mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key,\n                    size_t keylen );\n\n/**\n * \\brief           This function feeds an input buffer into an ongoing HMAC\n *                  computation.\n *\n *                  Call mbedtls_md_hmac_starts() or mbedtls_md_hmac_reset()\n *                  before calling this function.\n *                  You may call this function multiple times to pass the\n *                  input piecewise.\n *                  Afterwards, call mbedtls_md_hmac_finish().\n *\n * \\param ctx       The message digest context containing an embedded HMAC\n *                  context.\n * \\param input     The buffer holding the input data.\n * \\param ilen      The length of the input data.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification\n *                  failure.\n */\nint mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *input,\n                    size_t ilen );\n\n/**\n * \\brief           This function finishes the HMAC operation, and writes\n *                  the result to the output buffer.\n *\n *                  Call this function after mbedtls_md_hmac_starts() and\n *                  mbedtls_md_hmac_update() to get the HMAC value. Afterwards\n *                  you may either call mbedtls_md_free() to clear the context,\n *                  or call mbedtls_md_hmac_reset() to reuse the context with\n *                  the same HMAC key.\n *\n * \\param ctx       The message digest context containing an embedded HMAC\n *                  context.\n * \\param output    The generic HMAC checksum result.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification\n *                  failure.\n */\nint mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output);\n\n/**\n * \\brief           This function prepares to authenticate a new message with\n *                  the same key as the previous HMAC operation.\n *\n *                  You may call this function after mbedtls_md_hmac_finish().\n *                  Afterwards call mbedtls_md_hmac_update() to pass the new\n *                  input.\n *\n * \\param ctx       The message digest context containing an embedded HMAC\n *                  context.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification\n *                  failure.\n */\nint mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx );\n\n/**\n * \\brief          This function calculates the full generic HMAC\n *                 on the input buffer with the provided key.\n *\n *                 The function allocates the context, performs the\n *                 calculation, and frees the context.\n *\n *                 The HMAC result is calculated as\n *                 output = generic HMAC(hmac key, input buffer).\n *\n * \\param md_info  The information structure of the message-digest algorithm\n *                 to use.\n * \\param key      The HMAC secret key.\n * \\param keylen   The length of the HMAC secret key in Bytes.\n * \\param input    The buffer holding the input data.\n * \\param ilen     The length of the input data.\n * \\param output   The generic HMAC result.\n *\n * \\return         \\c 0 on success.\n * \\return         #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification\n *                 failure.\n */\nint mbedtls_md_hmac( const mbedtls_md_info_t *md_info, const unsigned char *key, size_t keylen,\n                const unsigned char *input, size_t ilen,\n                unsigned char *output );\n\n/* Internal use */\nint mbedtls_md_process( mbedtls_md_context_t *ctx, const unsigned char *data );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* MBEDTLS_MD_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/md2.h",
    "content": "/**\n * \\file md2.h\n *\n * \\brief MD2 message digest algorithm (hash function)\n *\n * \\warning MD2 is considered a weak message digest and its use constitutes a\n *          security risk. We recommend considering stronger message digests\n *          instead.\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n *\n */\n#ifndef MBEDTLS_MD2_H\n#define MBEDTLS_MD2_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n\n#define MBEDTLS_ERR_MD2_HW_ACCEL_FAILED                   -0x002B  /**< MD2 hardware accelerator failed */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_MD2_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief          MD2 context structure\n *\n * \\warning        MD2 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\ntypedef struct\n{\n    unsigned char cksum[16];    /*!< checksum of the data block */\n    unsigned char state[48];    /*!< intermediate digest state  */\n    unsigned char buffer[16];   /*!< data block being processed */\n    size_t left;                /*!< amount of data in buffer   */\n}\nmbedtls_md2_context;\n\n#else  /* MBEDTLS_MD2_ALT */\n#include \"md2_alt.h\"\n#endif /* MBEDTLS_MD2_ALT */\n\n/**\n * \\brief          Initialize MD2 context\n *\n * \\param ctx      MD2 context to be initialized\n *\n * \\warning        MD2 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nvoid mbedtls_md2_init( mbedtls_md2_context *ctx );\n\n/**\n * \\brief          Clear MD2 context\n *\n * \\param ctx      MD2 context to be cleared\n *\n * \\warning        MD2 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nvoid mbedtls_md2_free( mbedtls_md2_context *ctx );\n\n/**\n * \\brief          Clone (the state of) an MD2 context\n *\n * \\param dst      The destination context\n * \\param src      The context to be cloned\n *\n * \\warning        MD2 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nvoid mbedtls_md2_clone( mbedtls_md2_context *dst,\n                        const mbedtls_md2_context *src );\n\n/**\n * \\brief          MD2 context setup\n *\n * \\param ctx      context to be initialized\n *\n * \\return         0 if successful\n *\n * \\warning        MD2 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_md2_starts_ret( mbedtls_md2_context *ctx );\n\n/**\n * \\brief          MD2 process buffer\n *\n * \\param ctx      MD2 context\n * \\param input    buffer holding the data\n * \\param ilen     length of the input data\n *\n * \\return         0 if successful\n *\n * \\warning        MD2 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_md2_update_ret( mbedtls_md2_context *ctx,\n                            const unsigned char *input,\n                            size_t ilen );\n\n/**\n * \\brief          MD2 final digest\n *\n * \\param ctx      MD2 context\n * \\param output   MD2 checksum result\n *\n * \\return         0 if successful\n *\n * \\warning        MD2 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_md2_finish_ret( mbedtls_md2_context *ctx,\n                            unsigned char output[16] );\n\n/**\n * \\brief          MD2 process data block (internal use only)\n *\n * \\param ctx      MD2 context\n *\n * \\return         0 if successful\n *\n * \\warning        MD2 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_internal_md2_process( mbedtls_md2_context *ctx );\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED      __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n/**\n * \\brief          MD2 context setup\n *\n * \\deprecated     Superseded by mbedtls_md2_starts_ret() in 2.7.0\n *\n * \\param ctx      context to be initialized\n *\n * \\warning        MD2 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_md2_starts( mbedtls_md2_context *ctx );\n\n/**\n * \\brief          MD2 process buffer\n *\n * \\deprecated     Superseded by mbedtls_md2_update_ret() in 2.7.0\n *\n * \\param ctx      MD2 context\n * \\param input    buffer holding the data\n * \\param ilen     length of the input data\n *\n * \\warning        MD2 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_md2_update( mbedtls_md2_context *ctx,\n                                            const unsigned char *input,\n                                            size_t ilen );\n\n/**\n * \\brief          MD2 final digest\n *\n * \\deprecated     Superseded by mbedtls_md2_finish_ret() in 2.7.0\n *\n * \\param ctx      MD2 context\n * \\param output   MD2 checksum result\n *\n * \\warning        MD2 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_md2_finish( mbedtls_md2_context *ctx,\n                                            unsigned char output[16] );\n\n/**\n * \\brief          MD2 process data block (internal use only)\n *\n * \\deprecated     Superseded by mbedtls_internal_md2_process() in 2.7.0\n *\n * \\param ctx      MD2 context\n *\n * \\warning        MD2 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_md2_process( mbedtls_md2_context *ctx );\n\n#undef MBEDTLS_DEPRECATED\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n\n/**\n * \\brief          Output = MD2( input buffer )\n *\n * \\param input    buffer holding the data\n * \\param ilen     length of the input data\n * \\param output   MD2 checksum result\n *\n * \\warning        MD2 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_md2_ret( const unsigned char *input,\n                     size_t ilen,\n                     unsigned char output[16] );\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED      __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n/**\n * \\brief          Output = MD2( input buffer )\n *\n * \\deprecated     Superseded by mbedtls_md2_ret() in 2.7.0\n *\n * \\param input    buffer holding the data\n * \\param ilen     length of the input data\n * \\param output   MD2 checksum result\n *\n * \\warning        MD2 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_md2( const unsigned char *input,\n                                     size_t ilen,\n                                     unsigned char output[16] );\n\n#undef MBEDTLS_DEPRECATED\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n\n/**\n * \\brief          Checkup routine\n *\n * \\return         0 if successful, or 1 if the test failed\n *\n * \\warning        MD2 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_md2_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* mbedtls_md2.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/md4.h",
    "content": "/**\n * \\file md4.h\n *\n * \\brief MD4 message digest algorithm (hash function)\n *\n * \\warning MD4 is considered a weak message digest and its use constitutes a\n *          security risk. We recommend considering stronger message digests\n *          instead.\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n *\n */\n#ifndef MBEDTLS_MD4_H\n#define MBEDTLS_MD4_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n#include <stdint.h>\n\n#define MBEDTLS_ERR_MD4_HW_ACCEL_FAILED                   -0x002D  /**< MD4 hardware accelerator failed */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_MD4_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief          MD4 context structure\n *\n * \\warning        MD4 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\ntypedef struct\n{\n    uint32_t total[2];          /*!< number of bytes processed  */\n    uint32_t state[4];          /*!< intermediate digest state  */\n    unsigned char buffer[64];   /*!< data block being processed */\n}\nmbedtls_md4_context;\n\n#else  /* MBEDTLS_MD4_ALT */\n#include \"md4_alt.h\"\n#endif /* MBEDTLS_MD4_ALT */\n\n/**\n * \\brief          Initialize MD4 context\n *\n * \\param ctx      MD4 context to be initialized\n *\n * \\warning        MD4 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nvoid mbedtls_md4_init( mbedtls_md4_context *ctx );\n\n/**\n * \\brief          Clear MD4 context\n *\n * \\param ctx      MD4 context to be cleared\n *\n * \\warning        MD4 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nvoid mbedtls_md4_free( mbedtls_md4_context *ctx );\n\n/**\n * \\brief          Clone (the state of) an MD4 context\n *\n * \\param dst      The destination context\n * \\param src      The context to be cloned\n *\n * \\warning        MD4 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nvoid mbedtls_md4_clone( mbedtls_md4_context *dst,\n                        const mbedtls_md4_context *src );\n\n/**\n * \\brief          MD4 context setup\n *\n * \\param ctx      context to be initialized\n *\n * \\return         0 if successful\n *\n * \\warning        MD4 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n */\nint mbedtls_md4_starts_ret( mbedtls_md4_context *ctx );\n\n/**\n * \\brief          MD4 process buffer\n *\n * \\param ctx      MD4 context\n * \\param input    buffer holding the data\n * \\param ilen     length of the input data\n *\n * \\return         0 if successful\n *\n * \\warning        MD4 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_md4_update_ret( mbedtls_md4_context *ctx,\n                            const unsigned char *input,\n                            size_t ilen );\n\n/**\n * \\brief          MD4 final digest\n *\n * \\param ctx      MD4 context\n * \\param output   MD4 checksum result\n *\n * \\return         0 if successful\n *\n * \\warning        MD4 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_md4_finish_ret( mbedtls_md4_context *ctx,\n                            unsigned char output[16] );\n\n/**\n * \\brief          MD4 process data block (internal use only)\n *\n * \\param ctx      MD4 context\n * \\param data     buffer holding one block of data\n *\n * \\return         0 if successful\n *\n * \\warning        MD4 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_internal_md4_process( mbedtls_md4_context *ctx,\n                                  const unsigned char data[64] );\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED      __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n/**\n * \\brief          MD4 context setup\n *\n * \\deprecated     Superseded by mbedtls_md4_starts_ret() in 2.7.0\n *\n * \\param ctx      context to be initialized\n *\n * \\warning        MD4 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_md4_starts( mbedtls_md4_context *ctx );\n\n/**\n * \\brief          MD4 process buffer\n *\n * \\deprecated     Superseded by mbedtls_md4_update_ret() in 2.7.0\n *\n * \\param ctx      MD4 context\n * \\param input    buffer holding the data\n * \\param ilen     length of the input data\n *\n * \\warning        MD4 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_md4_update( mbedtls_md4_context *ctx,\n                                            const unsigned char *input,\n                                            size_t ilen );\n\n/**\n * \\brief          MD4 final digest\n *\n * \\deprecated     Superseded by mbedtls_md4_finish_ret() in 2.7.0\n *\n * \\param ctx      MD4 context\n * \\param output   MD4 checksum result\n *\n * \\warning        MD4 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_md4_finish( mbedtls_md4_context *ctx,\n                                            unsigned char output[16] );\n\n/**\n * \\brief          MD4 process data block (internal use only)\n *\n * \\deprecated     Superseded by mbedtls_internal_md4_process() in 2.7.0\n *\n * \\param ctx      MD4 context\n * \\param data     buffer holding one block of data\n *\n * \\warning        MD4 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_md4_process( mbedtls_md4_context *ctx,\n                                             const unsigned char data[64] );\n\n#undef MBEDTLS_DEPRECATED\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n\n/**\n * \\brief          Output = MD4( input buffer )\n *\n * \\param input    buffer holding the data\n * \\param ilen     length of the input data\n * \\param output   MD4 checksum result\n *\n * \\return         0 if successful\n *\n * \\warning        MD4 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_md4_ret( const unsigned char *input,\n                     size_t ilen,\n                     unsigned char output[16] );\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED      __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n/**\n * \\brief          Output = MD4( input buffer )\n *\n * \\deprecated     Superseded by mbedtls_md4_ret() in 2.7.0\n *\n * \\param input    buffer holding the data\n * \\param ilen     length of the input data\n * \\param output   MD4 checksum result\n *\n * \\warning        MD4 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_md4( const unsigned char *input,\n                                     size_t ilen,\n                                     unsigned char output[16] );\n\n#undef MBEDTLS_DEPRECATED\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n\n/**\n * \\brief          Checkup routine\n *\n * \\return         0 if successful, or 1 if the test failed\n *\n * \\warning        MD4 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_md4_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* mbedtls_md4.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/md5.h",
    "content": "/**\n * \\file md5.h\n *\n * \\brief MD5 message digest algorithm (hash function)\n *\n * \\warning   MD5 is considered a weak message digest and its use constitutes a\n *            security risk. We recommend considering stronger message\n *            digests instead.\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_MD5_H\n#define MBEDTLS_MD5_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n#include <stdint.h>\n\n#define MBEDTLS_ERR_MD5_HW_ACCEL_FAILED                   -0x002F  /**< MD5 hardware accelerator failed */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_MD5_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief          MD5 context structure\n *\n * \\warning        MD5 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\ntypedef struct\n{\n    uint32_t total[2];          /*!< number of bytes processed  */\n    uint32_t state[4];          /*!< intermediate digest state  */\n    unsigned char buffer[64];   /*!< data block being processed */\n}\nmbedtls_md5_context;\n\n#else  /* MBEDTLS_MD5_ALT */\n#include \"md5_alt.h\"\n#endif /* MBEDTLS_MD5_ALT */\n\n/**\n * \\brief          Initialize MD5 context\n *\n * \\param ctx      MD5 context to be initialized\n *\n * \\warning        MD5 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nvoid mbedtls_md5_init( mbedtls_md5_context *ctx );\n\n/**\n * \\brief          Clear MD5 context\n *\n * \\param ctx      MD5 context to be cleared\n *\n * \\warning        MD5 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nvoid mbedtls_md5_free( mbedtls_md5_context *ctx );\n\n/**\n * \\brief          Clone (the state of) an MD5 context\n *\n * \\param dst      The destination context\n * \\param src      The context to be cloned\n *\n * \\warning        MD5 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nvoid mbedtls_md5_clone( mbedtls_md5_context *dst,\n                        const mbedtls_md5_context *src );\n\n/**\n * \\brief          MD5 context setup\n *\n * \\param ctx      context to be initialized\n *\n * \\return         0 if successful\n *\n * \\warning        MD5 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_md5_starts_ret( mbedtls_md5_context *ctx );\n\n/**\n * \\brief          MD5 process buffer\n *\n * \\param ctx      MD5 context\n * \\param input    buffer holding the data\n * \\param ilen     length of the input data\n *\n * \\return         0 if successful\n *\n * \\warning        MD5 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_md5_update_ret( mbedtls_md5_context *ctx,\n                            const unsigned char *input,\n                            size_t ilen );\n\n/**\n * \\brief          MD5 final digest\n *\n * \\param ctx      MD5 context\n * \\param output   MD5 checksum result\n *\n * \\return         0 if successful\n *\n * \\warning        MD5 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_md5_finish_ret( mbedtls_md5_context *ctx,\n                            unsigned char output[16] );\n\n/**\n * \\brief          MD5 process data block (internal use only)\n *\n * \\param ctx      MD5 context\n * \\param data     buffer holding one block of data\n *\n * \\return         0 if successful\n *\n * \\warning        MD5 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_internal_md5_process( mbedtls_md5_context *ctx,\n                                  const unsigned char data[64] );\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED      __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n/**\n * \\brief          MD5 context setup\n *\n * \\deprecated     Superseded by mbedtls_md5_starts_ret() in 2.7.0\n *\n * \\param ctx      context to be initialized\n *\n * \\warning        MD5 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_md5_starts( mbedtls_md5_context *ctx );\n\n/**\n * \\brief          MD5 process buffer\n *\n * \\deprecated     Superseded by mbedtls_md5_update_ret() in 2.7.0\n *\n * \\param ctx      MD5 context\n * \\param input    buffer holding the data\n * \\param ilen     length of the input data\n *\n * \\warning        MD5 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_md5_update( mbedtls_md5_context *ctx,\n                                            const unsigned char *input,\n                                            size_t ilen );\n\n/**\n * \\brief          MD5 final digest\n *\n * \\deprecated     Superseded by mbedtls_md5_finish_ret() in 2.7.0\n *\n * \\param ctx      MD5 context\n * \\param output   MD5 checksum result\n *\n * \\warning        MD5 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_md5_finish( mbedtls_md5_context *ctx,\n                                            unsigned char output[16] );\n\n/**\n * \\brief          MD5 process data block (internal use only)\n *\n * \\deprecated     Superseded by mbedtls_internal_md5_process() in 2.7.0\n *\n * \\param ctx      MD5 context\n * \\param data     buffer holding one block of data\n *\n * \\warning        MD5 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_md5_process( mbedtls_md5_context *ctx,\n                                             const unsigned char data[64] );\n\n#undef MBEDTLS_DEPRECATED\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n\n/**\n * \\brief          Output = MD5( input buffer )\n *\n * \\param input    buffer holding the data\n * \\param ilen     length of the input data\n * \\param output   MD5 checksum result\n *\n * \\return         0 if successful\n *\n * \\warning        MD5 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_md5_ret( const unsigned char *input,\n                     size_t ilen,\n                     unsigned char output[16] );\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED      __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n/**\n * \\brief          Output = MD5( input buffer )\n *\n * \\deprecated     Superseded by mbedtls_md5_ret() in 2.7.0\n *\n * \\param input    buffer holding the data\n * \\param ilen     length of the input data\n * \\param output   MD5 checksum result\n *\n * \\warning        MD5 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_md5( const unsigned char *input,\n                                     size_t ilen,\n                                     unsigned char output[16] );\n\n#undef MBEDTLS_DEPRECATED\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n\n/**\n * \\brief          Checkup routine\n *\n * \\return         0 if successful, or 1 if the test failed\n *\n * \\warning        MD5 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\nint mbedtls_md5_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* mbedtls_md5.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/md_internal.h",
    "content": "/**\n * \\file md_internal.h\n *\n * \\brief Message digest wrappers.\n *\n * \\warning This in an internal header. Do not include directly.\n *\n * \\author Adriaan de Jong <dejong@fox-it.com>\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_MD_WRAP_H\n#define MBEDTLS_MD_WRAP_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include \"md.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * Message digest information.\n * Allows message digest functions to be called in a generic way.\n */\nstruct mbedtls_md_info_t\n{\n    /** Digest identifier */\n    mbedtls_md_type_t type;\n\n    /** Name of the message digest */\n    const char * name;\n\n    /** Output length of the digest function in bytes */\n    int size;\n\n    /** Block length of the digest function in bytes */\n    int block_size;\n\n    /** Digest initialisation function */\n    int (*starts_func)( void *ctx );\n\n    /** Digest update function */\n    int (*update_func)( void *ctx, const unsigned char *input, size_t ilen );\n\n    /** Digest finalisation function */\n    int (*finish_func)( void *ctx, unsigned char *output );\n\n    /** Generic digest function */\n    int (*digest_func)( const unsigned char *input, size_t ilen,\n                        unsigned char *output );\n\n    /** Allocate a new context */\n    void * (*ctx_alloc_func)( void );\n\n    /** Free the given context */\n    void (*ctx_free_func)( void *ctx );\n\n    /** Clone state from a context */\n    void (*clone_func)( void *dst, const void *src );\n\n    /** Internal use only */\n    int (*process_func)( void *ctx, const unsigned char *input );\n};\n\n#if defined(MBEDTLS_MD2_C)\nextern const mbedtls_md_info_t mbedtls_md2_info;\n#endif\n#if defined(MBEDTLS_MD4_C)\nextern const mbedtls_md_info_t mbedtls_md4_info;\n#endif\n#if defined(MBEDTLS_MD5_C)\nextern const mbedtls_md_info_t mbedtls_md5_info;\n#endif\n#if defined(MBEDTLS_RIPEMD160_C)\nextern const mbedtls_md_info_t mbedtls_ripemd160_info;\n#endif\n#if defined(MBEDTLS_SHA1_C)\nextern const mbedtls_md_info_t mbedtls_sha1_info;\n#endif\n#if defined(MBEDTLS_SHA256_C)\nextern const mbedtls_md_info_t mbedtls_sha224_info;\nextern const mbedtls_md_info_t mbedtls_sha256_info;\n#endif\n#if defined(MBEDTLS_SHA512_C)\nextern const mbedtls_md_info_t mbedtls_sha384_info;\nextern const mbedtls_md_info_t mbedtls_sha512_info;\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* MBEDTLS_MD_WRAP_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/memory_buffer_alloc.h",
    "content": "/**\n * \\file memory_buffer_alloc.h\n *\n * \\brief Buffer-based memory allocator\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_MEMORY_BUFFER_ALLOC_H\n#define MBEDTLS_MEMORY_BUFFER_ALLOC_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n\n/**\n * \\name SECTION: Module settings\n *\n * The configuration options you can set for this module are in this section.\n * Either change them in config.h or define them on the compiler command line.\n * \\{\n */\n\n#if !defined(MBEDTLS_MEMORY_ALIGN_MULTIPLE)\n#define MBEDTLS_MEMORY_ALIGN_MULTIPLE       4 /**< Align on multiples of this value */\n#endif\n\n/* \\} name SECTION: Module settings */\n\n#define MBEDTLS_MEMORY_VERIFY_NONE         0\n#define MBEDTLS_MEMORY_VERIFY_ALLOC        (1 << 0)\n#define MBEDTLS_MEMORY_VERIFY_FREE         (1 << 1)\n#define MBEDTLS_MEMORY_VERIFY_ALWAYS       (MBEDTLS_MEMORY_VERIFY_ALLOC | MBEDTLS_MEMORY_VERIFY_FREE)\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief   Initialize use of stack-based memory allocator.\n *          The stack-based allocator does memory management inside the\n *          presented buffer and does not call calloc() and free().\n *          It sets the global mbedtls_calloc() and mbedtls_free() pointers\n *          to its own functions.\n *          (Provided mbedtls_calloc() and mbedtls_free() are thread-safe if\n *           MBEDTLS_THREADING_C is defined)\n *\n * \\note    This code is not optimized and provides a straight-forward\n *          implementation of a stack-based memory allocator.\n *\n * \\param buf   buffer to use as heap\n * \\param len   size of the buffer\n */\nvoid mbedtls_memory_buffer_alloc_init( unsigned char *buf, size_t len );\n\n/**\n * \\brief   Free the mutex for thread-safety and clear remaining memory\n */\nvoid mbedtls_memory_buffer_alloc_free( void );\n\n/**\n * \\brief   Determine when the allocator should automatically verify the state\n *          of the entire chain of headers / meta-data.\n *          (Default: MBEDTLS_MEMORY_VERIFY_NONE)\n *\n * \\param verify    One of MBEDTLS_MEMORY_VERIFY_NONE, MBEDTLS_MEMORY_VERIFY_ALLOC,\n *                  MBEDTLS_MEMORY_VERIFY_FREE or MBEDTLS_MEMORY_VERIFY_ALWAYS\n */\nvoid mbedtls_memory_buffer_set_verify( int verify );\n\n#if defined(MBEDTLS_MEMORY_DEBUG)\n/**\n * \\brief   Print out the status of the allocated memory (primarily for use\n *          after a program should have de-allocated all memory)\n *          Prints out a list of 'still allocated' blocks and their stack\n *          trace if MBEDTLS_MEMORY_BACKTRACE is defined.\n */\nvoid mbedtls_memory_buffer_alloc_status( void );\n\n/**\n * \\brief   Get the peak heap usage so far\n *\n * \\param max_used      Peak number of bytes in use or committed. This\n *                      includes bytes in allocated blocks too small to split\n *                      into smaller blocks but larger than the requested size.\n * \\param max_blocks    Peak number of blocks in use, including free and used\n */\nvoid mbedtls_memory_buffer_alloc_max_get( size_t *max_used, size_t *max_blocks );\n\n/**\n * \\brief   Reset peak statistics\n */\nvoid mbedtls_memory_buffer_alloc_max_reset( void );\n\n/**\n * \\brief   Get the current heap usage\n *\n * \\param cur_used      Current number of bytes in use or committed. This\n *                      includes bytes in allocated blocks too small to split\n *                      into smaller blocks but larger than the requested size.\n * \\param cur_blocks    Current number of blocks in use, including free and used\n */\nvoid mbedtls_memory_buffer_alloc_cur_get( size_t *cur_used, size_t *cur_blocks );\n#endif /* MBEDTLS_MEMORY_DEBUG */\n\n/**\n * \\brief   Verifies that all headers in the memory buffer are correct\n *          and contain sane values. Helps debug buffer-overflow errors.\n *\n *          Prints out first failure if MBEDTLS_MEMORY_DEBUG is defined.\n *          Prints out full header information if MBEDTLS_MEMORY_DEBUG\n *          is defined. (Includes stack trace information for each block if\n *          MBEDTLS_MEMORY_BACKTRACE is defined as well).\n *\n * \\return             0 if verified, 1 otherwise\n */\nint mbedtls_memory_buffer_alloc_verify( void );\n\n#if defined(MBEDTLS_SELF_TEST)\n/**\n * \\brief          Checkup routine\n *\n * \\return         0 if successful, or 1 if a test failed\n */\nint mbedtls_memory_buffer_alloc_self_test( int verbose );\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* memory_buffer_alloc.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/net.h",
    "content": "/**\n * \\file net.h\n *\n * \\brief Deprecated header file that includes net_sockets.h\n *\n * \\deprecated Superseded by mbedtls/net_sockets.h\n */\n/*\n *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n#include \"net_sockets.h\"\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#warning \"Deprecated header file: Superseded by mbedtls/net_sockets.h\"\n#endif /* MBEDTLS_DEPRECATED_WARNING */\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/net_sockets.h",
    "content": "/**\n * \\file net_sockets.h\n *\n * \\brief   Network sockets abstraction layer to integrate Mbed TLS into a\n *          BSD-style sockets API.\n *\n *          The network sockets module provides an example integration of the\n *          Mbed TLS library into a BSD sockets implementation. The module is\n *          intended to be an example of how Mbed TLS can be integrated into a\n *          networking stack, as well as to be Mbed TLS's network integration\n *          for its supported platforms.\n *\n *          The module is intended only to be used with the Mbed TLS library and\n *          is not intended to be used by third party application software\n *          directly.\n *\n *          The supported platforms are as follows:\n *              * Microsoft Windows and Windows CE\n *              * POSIX/Unix platforms including Linux, OS X\n *\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_NET_SOCKETS_H\n#define MBEDTLS_NET_SOCKETS_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include \"ssl.h\"\n\n#include <stddef.h>\n#include <stdint.h>\n\n#define MBEDTLS_ERR_NET_SOCKET_FAILED                     -0x0042  /**< Failed to open a socket. */\n#define MBEDTLS_ERR_NET_CONNECT_FAILED                    -0x0044  /**< The connection to the given server / port failed. */\n#define MBEDTLS_ERR_NET_BIND_FAILED                       -0x0046  /**< Binding of the socket failed. */\n#define MBEDTLS_ERR_NET_LISTEN_FAILED                     -0x0048  /**< Could not listen on the socket. */\n#define MBEDTLS_ERR_NET_ACCEPT_FAILED                     -0x004A  /**< Could not accept the incoming connection. */\n#define MBEDTLS_ERR_NET_RECV_FAILED                       -0x004C  /**< Reading information from the socket failed. */\n#define MBEDTLS_ERR_NET_SEND_FAILED                       -0x004E  /**< Sending information through the socket failed. */\n#define MBEDTLS_ERR_NET_CONN_RESET                        -0x0050  /**< Connection was reset by peer. */\n#define MBEDTLS_ERR_NET_UNKNOWN_HOST                      -0x0052  /**< Failed to get an IP address for the given hostname. */\n#define MBEDTLS_ERR_NET_BUFFER_TOO_SMALL                  -0x0043  /**< Buffer is too small to hold the data. */\n#define MBEDTLS_ERR_NET_INVALID_CONTEXT                   -0x0045  /**< The context is invalid, eg because it was free()ed. */\n#define MBEDTLS_ERR_NET_POLL_FAILED                       -0x0047  /**< Polling the net context failed. */\n#define MBEDTLS_ERR_NET_BAD_INPUT_DATA                    -0x0049  /**< Input invalid. */\n\n#define MBEDTLS_NET_LISTEN_BACKLOG         10 /**< The backlog that listen() should use. */\n\n#define MBEDTLS_NET_PROTO_TCP 0 /**< The TCP transport protocol */\n#define MBEDTLS_NET_PROTO_UDP 1 /**< The UDP transport protocol */\n\n#define MBEDTLS_NET_POLL_READ  1 /**< Used in \\c mbedtls_net_poll to check for pending data  */\n#define MBEDTLS_NET_POLL_WRITE 2 /**< Used in \\c mbedtls_net_poll to check if write possible */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * Wrapper type for sockets.\n *\n * Currently backed by just a file descriptor, but might be more in the future\n * (eg two file descriptors for combined IPv4 + IPv6 support, or additional\n * structures for hand-made UDP demultiplexing).\n */\ntypedef struct\n{\n    int fd;             /**< The underlying file descriptor                 */\n}\nmbedtls_net_context;\n\n/**\n * \\brief          Initialize a context\n *                 Just makes the context ready to be used or freed safely.\n *\n * \\param ctx      Context to initialize\n */\nvoid mbedtls_net_init( mbedtls_net_context *ctx );\n\n/**\n * \\brief          Initiate a connection with host:port in the given protocol\n *\n * \\param ctx      Socket to use\n * \\param host     Host to connect to\n * \\param port     Port to connect to\n * \\param proto    Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP\n *\n * \\return         0 if successful, or one of:\n *                      MBEDTLS_ERR_NET_SOCKET_FAILED,\n *                      MBEDTLS_ERR_NET_UNKNOWN_HOST,\n *                      MBEDTLS_ERR_NET_CONNECT_FAILED\n *\n * \\note           Sets the socket in connected mode even with UDP.\n */\nint mbedtls_net_connect( mbedtls_net_context *ctx, const char *host, const char *port, int proto );\n\n/**\n * \\brief          Create a receiving socket on bind_ip:port in the chosen\n *                 protocol. If bind_ip == NULL, all interfaces are bound.\n *\n * \\param ctx      Socket to use\n * \\param bind_ip  IP to bind to, can be NULL\n * \\param port     Port number to use\n * \\param proto    Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP\n *\n * \\return         0 if successful, or one of:\n *                      MBEDTLS_ERR_NET_SOCKET_FAILED,\n *                      MBEDTLS_ERR_NET_BIND_FAILED,\n *                      MBEDTLS_ERR_NET_LISTEN_FAILED\n *\n * \\note           Regardless of the protocol, opens the sockets and binds it.\n *                 In addition, make the socket listening if protocol is TCP.\n */\nint mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto );\n\n/**\n * \\brief           Accept a connection from a remote client\n *\n * \\param bind_ctx  Relevant socket\n * \\param client_ctx Will contain the connected client socket\n * \\param client_ip Will contain the client IP address, can be NULL\n * \\param buf_size  Size of the client_ip buffer\n * \\param ip_len    Will receive the size of the client IP written,\n *                  can be NULL if client_ip is null\n *\n * \\return          0 if successful, or\n *                  MBEDTLS_ERR_NET_ACCEPT_FAILED, or\n *                  MBEDTLS_ERR_NET_BUFFER_TOO_SMALL if buf_size is too small,\n *                  MBEDTLS_ERR_SSL_WANT_READ if bind_fd was set to\n *                  non-blocking and accept() would block.\n */\nint mbedtls_net_accept( mbedtls_net_context *bind_ctx,\n                        mbedtls_net_context *client_ctx,\n                        void *client_ip, size_t buf_size, size_t *ip_len );\n\n/**\n * \\brief          Check and wait for the context to be ready for read/write\n *\n * \\param ctx      Socket to check\n * \\param rw       Bitflag composed of MBEDTLS_NET_POLL_READ and\n *                 MBEDTLS_NET_POLL_WRITE specifying the events\n *                 to wait for:\n *                 - If MBEDTLS_NET_POLL_READ is set, the function\n *                   will return as soon as the net context is available\n *                   for reading.\n *                 - If MBEDTLS_NET_POLL_WRITE is set, the function\n *                   will return as soon as the net context is available\n *                   for writing.\n * \\param timeout  Maximal amount of time to wait before returning,\n *                 in milliseconds. If \\c timeout is zero, the\n *                 function returns immediately. If \\c timeout is\n *                 -1u, the function blocks potentially indefinitely.\n *\n * \\return         Bitmask composed of MBEDTLS_NET_POLL_READ/WRITE\n *                 on success or timeout, or a negative return code otherwise.\n */\nint mbedtls_net_poll( mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout );\n\n/**\n * \\brief          Set the socket blocking\n *\n * \\param ctx      Socket to set\n *\n * \\return         0 if successful, or a non-zero error code\n */\nint mbedtls_net_set_block( mbedtls_net_context *ctx );\n\n/**\n * \\brief          Set the socket non-blocking\n *\n * \\param ctx      Socket to set\n *\n * \\return         0 if successful, or a non-zero error code\n */\nint mbedtls_net_set_nonblock( mbedtls_net_context *ctx );\n\n/**\n * \\brief          Portable usleep helper\n *\n * \\param usec     Amount of microseconds to sleep\n *\n * \\note           Real amount of time slept will not be less than\n *                 select()'s timeout granularity (typically, 10ms).\n */\nvoid mbedtls_net_usleep( unsigned long usec );\n\n/**\n * \\brief          Read at most 'len' characters. If no error occurs,\n *                 the actual amount read is returned.\n *\n * \\param ctx      Socket\n * \\param buf      The buffer to write to\n * \\param len      Maximum length of the buffer\n *\n * \\return         the number of bytes received,\n *                 or a non-zero error code; with a non-blocking socket,\n *                 MBEDTLS_ERR_SSL_WANT_READ indicates read() would block.\n */\nint mbedtls_net_recv( void *ctx, unsigned char *buf, size_t len );\n\n/**\n * \\brief          Write at most 'len' characters. If no error occurs,\n *                 the actual amount read is returned.\n *\n * \\param ctx      Socket\n * \\param buf      The buffer to read from\n * \\param len      The length of the buffer\n *\n * \\return         the number of bytes sent,\n *                 or a non-zero error code; with a non-blocking socket,\n *                 MBEDTLS_ERR_SSL_WANT_WRITE indicates write() would block.\n */\nint mbedtls_net_send( void *ctx, const unsigned char *buf, size_t len );\n\n/**\n * \\brief          Read at most 'len' characters, blocking for at most\n *                 'timeout' seconds. If no error occurs, the actual amount\n *                 read is returned.\n *\n * \\param ctx      Socket\n * \\param buf      The buffer to write to\n * \\param len      Maximum length of the buffer\n * \\param timeout  Maximum number of milliseconds to wait for data\n *                 0 means no timeout (wait forever)\n *\n * \\return         the number of bytes received,\n *                 or a non-zero error code:\n *                 MBEDTLS_ERR_SSL_TIMEOUT if the operation timed out,\n *                 MBEDTLS_ERR_SSL_WANT_READ if interrupted by a signal.\n *\n * \\note           This function will block (until data becomes available or\n *                 timeout is reached) even if the socket is set to\n *                 non-blocking. Handling timeouts with non-blocking reads\n *                 requires a different strategy.\n */\nint mbedtls_net_recv_timeout( void *ctx, unsigned char *buf, size_t len,\n                      uint32_t timeout );\n\n/**\n * \\brief          Gracefully shutdown the connection and free associated data\n *\n * \\param ctx      The context to free\n */\nvoid mbedtls_net_free( mbedtls_net_context *ctx );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* net_sockets.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/nist_kw.h",
    "content": "/**\n * \\file nist_kw.h\n *\n * \\brief This file provides an API for key wrapping (KW) and key wrapping with\n *        padding (KWP) as defined in NIST SP 800-38F.\n *        https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf\n *\n *        Key wrapping specifies a deterministic authenticated-encryption mode\n *        of operation, according to <em>NIST SP 800-38F: Recommendation for\n *        Block Cipher Modes of Operation: Methods for Key Wrapping</em>. Its\n *        purpose is to protect cryptographic keys.\n *\n *        Its equivalent is RFC 3394 for KW, and RFC 5649 for KWP.\n *        https://tools.ietf.org/html/rfc3394\n *        https://tools.ietf.org/html/rfc5649\n *\n */\n/*\n *  Copyright (C) 2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_NIST_KW_H\n#define MBEDTLS_NIST_KW_H\n\n#include \"cipher.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef enum\n{\n    MBEDTLS_KW_MODE_KW = 0,\n    MBEDTLS_KW_MODE_KWP = 1\n} mbedtls_nist_kw_mode_t;\n\n#if !defined(MBEDTLS_NIST_KW_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief    The key wrapping context-type definition. The key wrapping context is passed\n *           to the APIs called.\n *\n * \\note     The definition of this type may change in future library versions.\n *           Don't make any assumptions on this context!\n */\ntypedef struct {\n    mbedtls_cipher_context_t cipher_ctx;    /*!< The cipher context used. */\n} mbedtls_nist_kw_context;\n\n#else  /* MBEDTLS_NIST_key wrapping_ALT */\n#include \"nist_kw_alt.h\"\n#endif /* MBEDTLS_NIST_KW_ALT */\n\n/**\n * \\brief           This function initializes the specified key wrapping context\n *                  to make references valid and prepare the context\n *                  for mbedtls_nist_kw_setkey() or mbedtls_nist_kw_free().\n *\n * \\param ctx       The key wrapping context to initialize.\n *\n */\nvoid mbedtls_nist_kw_init( mbedtls_nist_kw_context *ctx );\n\n/**\n * \\brief           This function initializes the key wrapping context set in the\n *                  \\p ctx parameter and sets the encryption key.\n *\n * \\param ctx       The key wrapping context.\n * \\param cipher    The 128-bit block cipher to use. Only AES is supported.\n * \\param key       The Key Encryption Key (KEK).\n * \\param keybits   The KEK size in bits. This must be acceptable by the cipher.\n * \\param is_wrap   Specify whether the operation within the context is wrapping or unwrapping\n *\n * \\return          \\c 0 on success.\n * \\return          \\c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for any invalid input.\n * \\return          \\c MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE for 128-bit block ciphers\n *                  which are not supported.\n * \\return          cipher-specific error code on failure of the underlying cipher.\n */\nint mbedtls_nist_kw_setkey( mbedtls_nist_kw_context *ctx,\n                            mbedtls_cipher_id_t cipher,\n                            const unsigned char *key,\n                            unsigned int keybits,\n                            const int is_wrap );\n\n/**\n * \\brief   This function releases and clears the specified key wrapping context\n *          and underlying cipher sub-context.\n *\n * \\param ctx       The key wrapping context to clear.\n */\nvoid mbedtls_nist_kw_free( mbedtls_nist_kw_context *ctx );\n\n/**\n * \\brief           This function encrypts a buffer using key wrapping.\n *\n * \\param ctx       The key wrapping context to use for encryption.\n * \\param mode      The key wrapping mode to use (MBEDTLS_KW_MODE_KW or MBEDTLS_KW_MODE_KWP)\n * \\param input     The buffer holding the input data.\n * \\param in_len    The length of the input data in Bytes.\n *                  The input uses units of 8 Bytes called semiblocks.\n *                  <ul><li>For KW mode: a multiple of 8 bytes between 16 and 2^57-8 inclusive. </li>\n *                  <li>For KWP mode: any length between 1 and 2^32-1 inclusive.</li></ul>\n * \\param[out] output    The buffer holding the output data.\n *                  <ul><li>For KW mode: Must be at least 8 bytes larger than \\p in_len.</li>\n *                  <li>For KWP mode: Must be at least 8 bytes larger rounded up to a multiple of\n *                  8 bytes for KWP (15 bytes at most).</li></ul>\n * \\param[out] out_len The number of bytes written to the output buffer. \\c 0 on failure.\n * \\param[in] out_size The capacity of the output buffer.\n *\n * \\return          \\c 0 on success.\n * \\return          \\c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for invalid input length.\n * \\return          cipher-specific error code on failure of the underlying cipher.\n */\nint mbedtls_nist_kw_wrap( mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode,\n                          const unsigned char *input, size_t in_len,\n                          unsigned char *output, size_t* out_len, size_t out_size );\n\n/**\n * \\brief           This function decrypts a buffer using key wrapping.\n *\n * \\param ctx       The key wrapping context to use for decryption.\n * \\param mode      The key wrapping mode to use (MBEDTLS_KW_MODE_KW or MBEDTLS_KW_MODE_KWP)\n * \\param input     The buffer holding the input data.\n * \\param in_len    The length of the input data in Bytes.\n *                  The input uses units of 8 Bytes called semiblocks.\n *                  The input must be a multiple of semiblocks.\n *                  <ul><li>For KW mode: a multiple of 8 bytes between 24 and 2^57 inclusive. </li>\n *                  <li>For KWP mode: a multiple of 8 bytes between 16 and 2^32 inclusive.</li></ul>\n * \\param[out] output    The buffer holding the output data.\n *                  The output buffer's minimal length is 8 bytes shorter than \\p in_len.\n * \\param[out] out_len The number of bytes written to the output buffer. \\c 0 on failure.\n *                  For KWP mode, the length could be up to 15 bytes shorter than \\p in_len,\n *                  depending on how much padding was added to the data.\n * \\param[in] out_size The capacity of the output buffer.\n *\n * \\return          \\c 0 on success.\n * \\return          \\c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for invalid input length.\n * \\return          \\c MBEDTLS_ERR_CIPHER_AUTH_FAILED for verification failure of the ciphertext.\n * \\return          cipher-specific error code on failure of the underlying cipher.\n */\nint mbedtls_nist_kw_unwrap( mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode,\n                            const unsigned char *input, size_t in_len,\n                            unsigned char *output, size_t* out_len, size_t out_size);\n\n\n#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)\n/**\n * \\brief          The key wrapping checkup routine.\n *\n * \\return         \\c 0 on success.\n * \\return         \\c 1 on failure.\n */\nint mbedtls_nist_kw_self_test( int verbose );\n#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* MBEDTLS_NIST_KW_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/oid.h",
    "content": "/**\n * \\file oid.h\n *\n * \\brief Object Identifier (OID) database\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_OID_H\n#define MBEDTLS_OID_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include \"asn1.h\"\n#include \"pk.h\"\n\n#include <stddef.h>\n\n#if defined(MBEDTLS_CIPHER_C)\n#include \"cipher.h\"\n#endif\n\n#if defined(MBEDTLS_MD_C)\n#include \"md.h\"\n#endif\n\n#if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C)\n#include \"x509.h\"\n#endif\n\n#define MBEDTLS_ERR_OID_NOT_FOUND                         -0x002E  /**< OID is not found. */\n#define MBEDTLS_ERR_OID_BUF_TOO_SMALL                     -0x000B  /**< output buffer is too small */\n\n/*\n * Top level OID tuples\n */\n#define MBEDTLS_OID_ISO_MEMBER_BODIES           \"\\x2a\"          /* {iso(1) member-body(2)} */\n#define MBEDTLS_OID_ISO_IDENTIFIED_ORG          \"\\x2b\"          /* {iso(1) identified-organization(3)} */\n#define MBEDTLS_OID_ISO_CCITT_DS                \"\\x55\"          /* {joint-iso-ccitt(2) ds(5)} */\n#define MBEDTLS_OID_ISO_ITU_COUNTRY             \"\\x60\"          /* {joint-iso-itu-t(2) country(16)} */\n\n/*\n * ISO Member bodies OID parts\n */\n#define MBEDTLS_OID_COUNTRY_US                  \"\\x86\\x48\"      /* {us(840)} */\n#define MBEDTLS_OID_ORG_RSA_DATA_SECURITY       \"\\x86\\xf7\\x0d\"  /* {rsadsi(113549)} */\n#define MBEDTLS_OID_RSA_COMPANY                 MBEDTLS_OID_ISO_MEMBER_BODIES MBEDTLS_OID_COUNTRY_US \\\n                                        MBEDTLS_OID_ORG_RSA_DATA_SECURITY /* {iso(1) member-body(2) us(840) rsadsi(113549)} */\n#define MBEDTLS_OID_ORG_ANSI_X9_62              \"\\xce\\x3d\" /* ansi-X9-62(10045) */\n#define MBEDTLS_OID_ANSI_X9_62                  MBEDTLS_OID_ISO_MEMBER_BODIES MBEDTLS_OID_COUNTRY_US \\\n                                        MBEDTLS_OID_ORG_ANSI_X9_62\n\n/*\n * ISO Identified organization OID parts\n */\n#define MBEDTLS_OID_ORG_DOD                     \"\\x06\"          /* {dod(6)} */\n#define MBEDTLS_OID_ORG_OIW                     \"\\x0e\"\n#define MBEDTLS_OID_OIW_SECSIG                  MBEDTLS_OID_ORG_OIW \"\\x03\"\n#define MBEDTLS_OID_OIW_SECSIG_ALG              MBEDTLS_OID_OIW_SECSIG \"\\x02\"\n#define MBEDTLS_OID_OIW_SECSIG_SHA1             MBEDTLS_OID_OIW_SECSIG_ALG \"\\x1a\"\n#define MBEDTLS_OID_ORG_CERTICOM                \"\\x81\\x04\"  /* certicom(132) */\n#define MBEDTLS_OID_CERTICOM                    MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_ORG_CERTICOM\n#define MBEDTLS_OID_ORG_TELETRUST               \"\\x24\" /* teletrust(36) */\n#define MBEDTLS_OID_TELETRUST                   MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_ORG_TELETRUST\n\n/*\n * ISO ITU OID parts\n */\n#define MBEDTLS_OID_ORGANIZATION                \"\\x01\"          /* {organization(1)} */\n#define MBEDTLS_OID_ISO_ITU_US_ORG              MBEDTLS_OID_ISO_ITU_COUNTRY MBEDTLS_OID_COUNTRY_US MBEDTLS_OID_ORGANIZATION /* {joint-iso-itu-t(2) country(16) us(840) organization(1)} */\n\n#define MBEDTLS_OID_ORG_GOV                     \"\\x65\"          /* {gov(101)} */\n#define MBEDTLS_OID_GOV                         MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ORG_GOV /* {joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101)} */\n\n#define MBEDTLS_OID_ORG_NETSCAPE                \"\\x86\\xF8\\x42\"  /* {netscape(113730)} */\n#define MBEDTLS_OID_NETSCAPE                    MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ORG_NETSCAPE /* Netscape OID {joint-iso-itu-t(2) country(16) us(840) organization(1) netscape(113730)} */\n\n/* ISO arc for standard certificate and CRL extensions */\n#define MBEDTLS_OID_ID_CE                       MBEDTLS_OID_ISO_CCITT_DS \"\\x1D\" /**< id-ce OBJECT IDENTIFIER  ::=  {joint-iso-ccitt(2) ds(5) 29} */\n\n#define MBEDTLS_OID_NIST_ALG                    MBEDTLS_OID_GOV \"\\x03\\x04\" /** { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) */\n\n/**\n * Private Internet Extensions\n * { iso(1) identified-organization(3) dod(6) internet(1)\n *                      security(5) mechanisms(5) pkix(7) }\n */\n#define MBEDTLS_OID_PKIX                        MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_ORG_DOD \"\\x01\\x05\\x05\\x07\"\n\n/*\n * Arc for standard naming attributes\n */\n#define MBEDTLS_OID_AT                          MBEDTLS_OID_ISO_CCITT_DS \"\\x04\" /**< id-at OBJECT IDENTIFIER ::= {joint-iso-ccitt(2) ds(5) 4} */\n#define MBEDTLS_OID_AT_CN                       MBEDTLS_OID_AT \"\\x03\" /**< id-at-commonName AttributeType:= {id-at 3} */\n#define MBEDTLS_OID_AT_SUR_NAME                 MBEDTLS_OID_AT \"\\x04\" /**< id-at-surName AttributeType:= {id-at 4} */\n#define MBEDTLS_OID_AT_SERIAL_NUMBER            MBEDTLS_OID_AT \"\\x05\" /**< id-at-serialNumber AttributeType:= {id-at 5} */\n#define MBEDTLS_OID_AT_COUNTRY                  MBEDTLS_OID_AT \"\\x06\" /**< id-at-countryName AttributeType:= {id-at 6} */\n#define MBEDTLS_OID_AT_LOCALITY                 MBEDTLS_OID_AT \"\\x07\" /**< id-at-locality AttributeType:= {id-at 7} */\n#define MBEDTLS_OID_AT_STATE                    MBEDTLS_OID_AT \"\\x08\" /**< id-at-state AttributeType:= {id-at 8} */\n#define MBEDTLS_OID_AT_ORGANIZATION             MBEDTLS_OID_AT \"\\x0A\" /**< id-at-organizationName AttributeType:= {id-at 10} */\n#define MBEDTLS_OID_AT_ORG_UNIT                 MBEDTLS_OID_AT \"\\x0B\" /**< id-at-organizationalUnitName AttributeType:= {id-at 11} */\n#define MBEDTLS_OID_AT_TITLE                    MBEDTLS_OID_AT \"\\x0C\" /**< id-at-title AttributeType:= {id-at 12} */\n#define MBEDTLS_OID_AT_POSTAL_ADDRESS           MBEDTLS_OID_AT \"\\x10\" /**< id-at-postalAddress AttributeType:= {id-at 16} */\n#define MBEDTLS_OID_AT_POSTAL_CODE              MBEDTLS_OID_AT \"\\x11\" /**< id-at-postalCode AttributeType:= {id-at 17} */\n#define MBEDTLS_OID_AT_GIVEN_NAME               MBEDTLS_OID_AT \"\\x2A\" /**< id-at-givenName AttributeType:= {id-at 42} */\n#define MBEDTLS_OID_AT_INITIALS                 MBEDTLS_OID_AT \"\\x2B\" /**< id-at-initials AttributeType:= {id-at 43} */\n#define MBEDTLS_OID_AT_GENERATION_QUALIFIER     MBEDTLS_OID_AT \"\\x2C\" /**< id-at-generationQualifier AttributeType:= {id-at 44} */\n#define MBEDTLS_OID_AT_UNIQUE_IDENTIFIER        MBEDTLS_OID_AT \"\\x2D\" /**< id-at-uniqueIdentifier AttributType:= {id-at 45} */\n#define MBEDTLS_OID_AT_DN_QUALIFIER             MBEDTLS_OID_AT \"\\x2E\" /**< id-at-dnQualifier AttributeType:= {id-at 46} */\n#define MBEDTLS_OID_AT_PSEUDONYM                MBEDTLS_OID_AT \"\\x41\" /**< id-at-pseudonym AttributeType:= {id-at 65} */\n\n#define MBEDTLS_OID_DOMAIN_COMPONENT            \"\\x09\\x92\\x26\\x89\\x93\\xF2\\x2C\\x64\\x01\\x19\" /** id-domainComponent AttributeType:= {itu-t(0) data(9) pss(2342) ucl(19200300) pilot(100) pilotAttributeType(1) domainComponent(25)} */\n\n/*\n * OIDs for standard certificate extensions\n */\n#define MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER    MBEDTLS_OID_ID_CE \"\\x23\" /**< id-ce-authorityKeyIdentifier OBJECT IDENTIFIER ::=  { id-ce 35 } */\n#define MBEDTLS_OID_SUBJECT_KEY_IDENTIFIER      MBEDTLS_OID_ID_CE \"\\x0E\" /**< id-ce-subjectKeyIdentifier OBJECT IDENTIFIER ::=  { id-ce 14 } */\n#define MBEDTLS_OID_KEY_USAGE                   MBEDTLS_OID_ID_CE \"\\x0F\" /**< id-ce-keyUsage OBJECT IDENTIFIER ::=  { id-ce 15 } */\n#define MBEDTLS_OID_CERTIFICATE_POLICIES        MBEDTLS_OID_ID_CE \"\\x20\" /**< id-ce-certificatePolicies OBJECT IDENTIFIER ::=  { id-ce 32 } */\n#define MBEDTLS_OID_POLICY_MAPPINGS             MBEDTLS_OID_ID_CE \"\\x21\" /**< id-ce-policyMappings OBJECT IDENTIFIER ::=  { id-ce 33 } */\n#define MBEDTLS_OID_SUBJECT_ALT_NAME            MBEDTLS_OID_ID_CE \"\\x11\" /**< id-ce-subjectAltName OBJECT IDENTIFIER ::=  { id-ce 17 } */\n#define MBEDTLS_OID_ISSUER_ALT_NAME             MBEDTLS_OID_ID_CE \"\\x12\" /**< id-ce-issuerAltName OBJECT IDENTIFIER ::=  { id-ce 18 } */\n#define MBEDTLS_OID_SUBJECT_DIRECTORY_ATTRS     MBEDTLS_OID_ID_CE \"\\x09\" /**< id-ce-subjectDirectoryAttributes OBJECT IDENTIFIER ::=  { id-ce 9 } */\n#define MBEDTLS_OID_BASIC_CONSTRAINTS           MBEDTLS_OID_ID_CE \"\\x13\" /**< id-ce-basicConstraints OBJECT IDENTIFIER ::=  { id-ce 19 } */\n#define MBEDTLS_OID_NAME_CONSTRAINTS            MBEDTLS_OID_ID_CE \"\\x1E\" /**< id-ce-nameConstraints OBJECT IDENTIFIER ::=  { id-ce 30 } */\n#define MBEDTLS_OID_POLICY_CONSTRAINTS          MBEDTLS_OID_ID_CE \"\\x24\" /**< id-ce-policyConstraints OBJECT IDENTIFIER ::=  { id-ce 36 } */\n#define MBEDTLS_OID_EXTENDED_KEY_USAGE          MBEDTLS_OID_ID_CE \"\\x25\" /**< id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 } */\n#define MBEDTLS_OID_CRL_DISTRIBUTION_POINTS     MBEDTLS_OID_ID_CE \"\\x1F\" /**< id-ce-cRLDistributionPoints OBJECT IDENTIFIER ::=  { id-ce 31 } */\n#define MBEDTLS_OID_INIHIBIT_ANYPOLICY          MBEDTLS_OID_ID_CE \"\\x36\" /**< id-ce-inhibitAnyPolicy OBJECT IDENTIFIER ::=  { id-ce 54 } */\n#define MBEDTLS_OID_FRESHEST_CRL                MBEDTLS_OID_ID_CE \"\\x2E\" /**< id-ce-freshestCRL OBJECT IDENTIFIER ::=  { id-ce 46 } */\n\n/*\n * Netscape certificate extensions\n */\n#define MBEDTLS_OID_NS_CERT                 MBEDTLS_OID_NETSCAPE \"\\x01\"\n#define MBEDTLS_OID_NS_CERT_TYPE            MBEDTLS_OID_NS_CERT  \"\\x01\"\n#define MBEDTLS_OID_NS_BASE_URL             MBEDTLS_OID_NS_CERT  \"\\x02\"\n#define MBEDTLS_OID_NS_REVOCATION_URL       MBEDTLS_OID_NS_CERT  \"\\x03\"\n#define MBEDTLS_OID_NS_CA_REVOCATION_URL    MBEDTLS_OID_NS_CERT  \"\\x04\"\n#define MBEDTLS_OID_NS_RENEWAL_URL          MBEDTLS_OID_NS_CERT  \"\\x07\"\n#define MBEDTLS_OID_NS_CA_POLICY_URL        MBEDTLS_OID_NS_CERT  \"\\x08\"\n#define MBEDTLS_OID_NS_SSL_SERVER_NAME      MBEDTLS_OID_NS_CERT  \"\\x0C\"\n#define MBEDTLS_OID_NS_COMMENT              MBEDTLS_OID_NS_CERT  \"\\x0D\"\n#define MBEDTLS_OID_NS_DATA_TYPE            MBEDTLS_OID_NETSCAPE \"\\x02\"\n#define MBEDTLS_OID_NS_CERT_SEQUENCE        MBEDTLS_OID_NS_DATA_TYPE \"\\x05\"\n\n/*\n * OIDs for CRL extensions\n */\n#define MBEDTLS_OID_PRIVATE_KEY_USAGE_PERIOD    MBEDTLS_OID_ID_CE \"\\x10\"\n#define MBEDTLS_OID_CRL_NUMBER                  MBEDTLS_OID_ID_CE \"\\x14\" /**< id-ce-cRLNumber OBJECT IDENTIFIER ::= { id-ce 20 } */\n\n/*\n * X.509 v3 Extended key usage OIDs\n */\n#define MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE      MBEDTLS_OID_EXTENDED_KEY_USAGE \"\\x00\" /**< anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 } */\n\n#define MBEDTLS_OID_KP                          MBEDTLS_OID_PKIX \"\\x03\" /**< id-kp OBJECT IDENTIFIER ::= { id-pkix 3 } */\n#define MBEDTLS_OID_SERVER_AUTH                 MBEDTLS_OID_KP \"\\x01\" /**< id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 } */\n#define MBEDTLS_OID_CLIENT_AUTH                 MBEDTLS_OID_KP \"\\x02\" /**< id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 } */\n#define MBEDTLS_OID_CODE_SIGNING                MBEDTLS_OID_KP \"\\x03\" /**< id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 } */\n#define MBEDTLS_OID_EMAIL_PROTECTION            MBEDTLS_OID_KP \"\\x04\" /**< id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 } */\n#define MBEDTLS_OID_TIME_STAMPING               MBEDTLS_OID_KP \"\\x08\" /**< id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 } */\n#define MBEDTLS_OID_OCSP_SIGNING                MBEDTLS_OID_KP \"\\x09\" /**< id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 } */\n\n/*\n * PKCS definition OIDs\n */\n\n#define MBEDTLS_OID_PKCS                MBEDTLS_OID_RSA_COMPANY \"\\x01\" /**< pkcs OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) 1 } */\n#define MBEDTLS_OID_PKCS1               MBEDTLS_OID_PKCS \"\\x01\" /**< pkcs-1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 } */\n#define MBEDTLS_OID_PKCS5               MBEDTLS_OID_PKCS \"\\x05\" /**< pkcs-5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 5 } */\n#define MBEDTLS_OID_PKCS9               MBEDTLS_OID_PKCS \"\\x09\" /**< pkcs-9 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 9 } */\n#define MBEDTLS_OID_PKCS12              MBEDTLS_OID_PKCS \"\\x0c\" /**< pkcs-12 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 12 } */\n\n/*\n * PKCS#1 OIDs\n */\n#define MBEDTLS_OID_PKCS1_RSA           MBEDTLS_OID_PKCS1 \"\\x01\" /**< rsaEncryption OBJECT IDENTIFIER ::= { pkcs-1 1 } */\n#define MBEDTLS_OID_PKCS1_MD2           MBEDTLS_OID_PKCS1 \"\\x02\" /**< md2WithRSAEncryption ::= { pkcs-1 2 } */\n#define MBEDTLS_OID_PKCS1_MD4           MBEDTLS_OID_PKCS1 \"\\x03\" /**< md4WithRSAEncryption ::= { pkcs-1 3 } */\n#define MBEDTLS_OID_PKCS1_MD5           MBEDTLS_OID_PKCS1 \"\\x04\" /**< md5WithRSAEncryption ::= { pkcs-1 4 } */\n#define MBEDTLS_OID_PKCS1_SHA1          MBEDTLS_OID_PKCS1 \"\\x05\" /**< sha1WithRSAEncryption ::= { pkcs-1 5 } */\n#define MBEDTLS_OID_PKCS1_SHA224        MBEDTLS_OID_PKCS1 \"\\x0e\" /**< sha224WithRSAEncryption ::= { pkcs-1 14 } */\n#define MBEDTLS_OID_PKCS1_SHA256        MBEDTLS_OID_PKCS1 \"\\x0b\" /**< sha256WithRSAEncryption ::= { pkcs-1 11 } */\n#define MBEDTLS_OID_PKCS1_SHA384        MBEDTLS_OID_PKCS1 \"\\x0c\" /**< sha384WithRSAEncryption ::= { pkcs-1 12 } */\n#define MBEDTLS_OID_PKCS1_SHA512        MBEDTLS_OID_PKCS1 \"\\x0d\" /**< sha512WithRSAEncryption ::= { pkcs-1 13 } */\n\n#define MBEDTLS_OID_RSA_SHA_OBS         \"\\x2B\\x0E\\x03\\x02\\x1D\"\n\n#define MBEDTLS_OID_PKCS9_EMAIL         MBEDTLS_OID_PKCS9 \"\\x01\" /**< emailAddress AttributeType ::= { pkcs-9 1 } */\n\n/* RFC 4055 */\n#define MBEDTLS_OID_RSASSA_PSS          MBEDTLS_OID_PKCS1 \"\\x0a\" /**< id-RSASSA-PSS ::= { pkcs-1 10 } */\n#define MBEDTLS_OID_MGF1                MBEDTLS_OID_PKCS1 \"\\x08\" /**< id-mgf1 ::= { pkcs-1 8 } */\n\n/*\n * Digest algorithms\n */\n#define MBEDTLS_OID_DIGEST_ALG_MD2              MBEDTLS_OID_RSA_COMPANY \"\\x02\\x02\" /**< id-mbedtls_md2 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 2 } */\n#define MBEDTLS_OID_DIGEST_ALG_MD4              MBEDTLS_OID_RSA_COMPANY \"\\x02\\x04\" /**< id-mbedtls_md4 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 4 } */\n#define MBEDTLS_OID_DIGEST_ALG_MD5              MBEDTLS_OID_RSA_COMPANY \"\\x02\\x05\" /**< id-mbedtls_md5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 5 } */\n#define MBEDTLS_OID_DIGEST_ALG_SHA1             MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_OIW_SECSIG_SHA1 /**< id-mbedtls_sha1 OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 26 } */\n#define MBEDTLS_OID_DIGEST_ALG_SHA224           MBEDTLS_OID_NIST_ALG \"\\x02\\x04\" /**< id-sha224 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 4 } */\n#define MBEDTLS_OID_DIGEST_ALG_SHA256           MBEDTLS_OID_NIST_ALG \"\\x02\\x01\" /**< id-mbedtls_sha256 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 1 } */\n\n#define MBEDTLS_OID_DIGEST_ALG_SHA384           MBEDTLS_OID_NIST_ALG \"\\x02\\x02\" /**< id-sha384 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 2 } */\n\n#define MBEDTLS_OID_DIGEST_ALG_SHA512           MBEDTLS_OID_NIST_ALG \"\\x02\\x03\" /**< id-mbedtls_sha512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 3 } */\n\n#define MBEDTLS_OID_HMAC_SHA1                   MBEDTLS_OID_RSA_COMPANY \"\\x02\\x07\" /**< id-hmacWithSHA1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 7 } */\n\n#define MBEDTLS_OID_HMAC_SHA224                 MBEDTLS_OID_RSA_COMPANY \"\\x02\\x08\" /**< id-hmacWithSHA224 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 8 } */\n\n#define MBEDTLS_OID_HMAC_SHA256                 MBEDTLS_OID_RSA_COMPANY \"\\x02\\x09\" /**< id-hmacWithSHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 9 } */\n\n#define MBEDTLS_OID_HMAC_SHA384                 MBEDTLS_OID_RSA_COMPANY \"\\x02\\x0A\" /**< id-hmacWithSHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 10 } */\n\n#define MBEDTLS_OID_HMAC_SHA512                 MBEDTLS_OID_RSA_COMPANY \"\\x02\\x0B\" /**< id-hmacWithSHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 11 } */\n\n/*\n * Encryption algorithms\n */\n#define MBEDTLS_OID_DES_CBC                     MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_OIW_SECSIG_ALG \"\\x07\" /**< desCBC OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 7 } */\n#define MBEDTLS_OID_DES_EDE3_CBC                MBEDTLS_OID_RSA_COMPANY \"\\x03\\x07\" /**< des-ede3-cbc OBJECT IDENTIFIER ::= { iso(1) member-body(2) -- us(840) rsadsi(113549) encryptionAlgorithm(3) 7 } */\n#define MBEDTLS_OID_AES                         MBEDTLS_OID_NIST_ALG \"\\x01\" /** aes OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) 1 } */\n\n/*\n * Key Wrapping algorithms\n */\n/*\n * RFC 5649\n */\n#define MBEDTLS_OID_AES128_KW                   MBEDTLS_OID_AES \"\\x05\" /** id-aes128-wrap     OBJECT IDENTIFIER ::= { aes 5 } */\n#define MBEDTLS_OID_AES128_KWP                  MBEDTLS_OID_AES \"\\x08\" /** id-aes128-wrap-pad OBJECT IDENTIFIER ::= { aes 8 } */\n#define MBEDTLS_OID_AES192_KW                   MBEDTLS_OID_AES \"\\x19\" /** id-aes192-wrap     OBJECT IDENTIFIER ::= { aes 25 } */\n#define MBEDTLS_OID_AES192_KWP                  MBEDTLS_OID_AES \"\\x1c\" /** id-aes192-wrap-pad OBJECT IDENTIFIER ::= { aes 28 } */\n#define MBEDTLS_OID_AES256_KW                   MBEDTLS_OID_AES \"\\x2d\" /** id-aes256-wrap     OBJECT IDENTIFIER ::= { aes 45 } */\n#define MBEDTLS_OID_AES256_KWP                  MBEDTLS_OID_AES \"\\x30\" /** id-aes256-wrap-pad OBJECT IDENTIFIER ::= { aes 48 } */\n/*\n * PKCS#5 OIDs\n */\n#define MBEDTLS_OID_PKCS5_PBKDF2                MBEDTLS_OID_PKCS5 \"\\x0c\" /**< id-PBKDF2 OBJECT IDENTIFIER ::= {pkcs-5 12} */\n#define MBEDTLS_OID_PKCS5_PBES2                 MBEDTLS_OID_PKCS5 \"\\x0d\" /**< id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13} */\n#define MBEDTLS_OID_PKCS5_PBMAC1                MBEDTLS_OID_PKCS5 \"\\x0e\" /**< id-PBMAC1 OBJECT IDENTIFIER ::= {pkcs-5 14} */\n\n/*\n * PKCS#5 PBES1 algorithms\n */\n#define MBEDTLS_OID_PKCS5_PBE_MD2_DES_CBC       MBEDTLS_OID_PKCS5 \"\\x01\" /**< pbeWithMD2AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 1} */\n#define MBEDTLS_OID_PKCS5_PBE_MD2_RC2_CBC       MBEDTLS_OID_PKCS5 \"\\x04\" /**< pbeWithMD2AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 4} */\n#define MBEDTLS_OID_PKCS5_PBE_MD5_DES_CBC       MBEDTLS_OID_PKCS5 \"\\x03\" /**< pbeWithMD5AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 3} */\n#define MBEDTLS_OID_PKCS5_PBE_MD5_RC2_CBC       MBEDTLS_OID_PKCS5 \"\\x06\" /**< pbeWithMD5AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 6} */\n#define MBEDTLS_OID_PKCS5_PBE_SHA1_DES_CBC      MBEDTLS_OID_PKCS5 \"\\x0a\" /**< pbeWithSHA1AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 10} */\n#define MBEDTLS_OID_PKCS5_PBE_SHA1_RC2_CBC      MBEDTLS_OID_PKCS5 \"\\x0b\" /**< pbeWithSHA1AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 11} */\n\n/*\n * PKCS#8 OIDs\n */\n#define MBEDTLS_OID_PKCS9_CSR_EXT_REQ           MBEDTLS_OID_PKCS9 \"\\x0e\" /**< extensionRequest OBJECT IDENTIFIER ::= {pkcs-9 14} */\n\n/*\n * PKCS#12 PBE OIDs\n */\n#define MBEDTLS_OID_PKCS12_PBE                      MBEDTLS_OID_PKCS12 \"\\x01\" /**< pkcs-12PbeIds OBJECT IDENTIFIER ::= {pkcs-12 1} */\n\n#define MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_128         MBEDTLS_OID_PKCS12_PBE \"\\x01\" /**< pbeWithSHAAnd128BitRC4 OBJECT IDENTIFIER ::= {pkcs-12PbeIds 1} */\n#define MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_40          MBEDTLS_OID_PKCS12_PBE \"\\x02\" /**< pbeWithSHAAnd40BitRC4 OBJECT IDENTIFIER ::= {pkcs-12PbeIds 2} */\n#define MBEDTLS_OID_PKCS12_PBE_SHA1_DES3_EDE_CBC    MBEDTLS_OID_PKCS12_PBE \"\\x03\" /**< pbeWithSHAAnd3-KeyTripleDES-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 3} */\n#define MBEDTLS_OID_PKCS12_PBE_SHA1_DES2_EDE_CBC    MBEDTLS_OID_PKCS12_PBE \"\\x04\" /**< pbeWithSHAAnd2-KeyTripleDES-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 4} */\n#define MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_128_CBC     MBEDTLS_OID_PKCS12_PBE \"\\x05\" /**< pbeWithSHAAnd128BitRC2-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 5} */\n#define MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_40_CBC      MBEDTLS_OID_PKCS12_PBE \"\\x06\" /**< pbeWithSHAAnd40BitRC2-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 6} */\n\n/*\n * EC key algorithms from RFC 5480\n */\n\n/* id-ecPublicKey OBJECT IDENTIFIER ::= {\n *       iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 } */\n#define MBEDTLS_OID_EC_ALG_UNRESTRICTED         MBEDTLS_OID_ANSI_X9_62 \"\\x02\\01\"\n\n/*   id-ecDH OBJECT IDENTIFIER ::= {\n *     iso(1) identified-organization(3) certicom(132)\n *     schemes(1) ecdh(12) } */\n#define MBEDTLS_OID_EC_ALG_ECDH                 MBEDTLS_OID_CERTICOM \"\\x01\\x0c\"\n\n/*\n * ECParameters namedCurve identifiers, from RFC 5480, RFC 5639, and SEC2\n */\n\n/* secp192r1 OBJECT IDENTIFIER ::= {\n *   iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) prime(1) 1 } */\n#define MBEDTLS_OID_EC_GRP_SECP192R1        MBEDTLS_OID_ANSI_X9_62 \"\\x03\\x01\\x01\"\n\n/* secp224r1 OBJECT IDENTIFIER ::= {\n *   iso(1) identified-organization(3) certicom(132) curve(0) 33 } */\n#define MBEDTLS_OID_EC_GRP_SECP224R1        MBEDTLS_OID_CERTICOM \"\\x00\\x21\"\n\n/* secp256r1 OBJECT IDENTIFIER ::= {\n *   iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) prime(1) 7 } */\n#define MBEDTLS_OID_EC_GRP_SECP256R1        MBEDTLS_OID_ANSI_X9_62 \"\\x03\\x01\\x07\"\n\n/* secp384r1 OBJECT IDENTIFIER ::= {\n *   iso(1) identified-organization(3) certicom(132) curve(0) 34 } */\n#define MBEDTLS_OID_EC_GRP_SECP384R1        MBEDTLS_OID_CERTICOM \"\\x00\\x22\"\n\n/* secp521r1 OBJECT IDENTIFIER ::= {\n *   iso(1) identified-organization(3) certicom(132) curve(0) 35 } */\n#define MBEDTLS_OID_EC_GRP_SECP521R1        MBEDTLS_OID_CERTICOM \"\\x00\\x23\"\n\n/* secp192k1 OBJECT IDENTIFIER ::= {\n *   iso(1) identified-organization(3) certicom(132) curve(0) 31 } */\n#define MBEDTLS_OID_EC_GRP_SECP192K1        MBEDTLS_OID_CERTICOM \"\\x00\\x1f\"\n\n/* secp224k1 OBJECT IDENTIFIER ::= {\n *   iso(1) identified-organization(3) certicom(132) curve(0) 32 } */\n#define MBEDTLS_OID_EC_GRP_SECP224K1        MBEDTLS_OID_CERTICOM \"\\x00\\x20\"\n\n/* secp256k1 OBJECT IDENTIFIER ::= {\n *   iso(1) identified-organization(3) certicom(132) curve(0) 10 } */\n#define MBEDTLS_OID_EC_GRP_SECP256K1        MBEDTLS_OID_CERTICOM \"\\x00\\x0a\"\n\n/* RFC 5639 4.1\n * ecStdCurvesAndGeneration OBJECT IDENTIFIER::= {iso(1)\n * identified-organization(3) teletrust(36) algorithm(3) signature-\n * algorithm(3) ecSign(2) 8}\n * ellipticCurve OBJECT IDENTIFIER ::= {ecStdCurvesAndGeneration 1}\n * versionOne OBJECT IDENTIFIER ::= {ellipticCurve 1} */\n#define MBEDTLS_OID_EC_BRAINPOOL_V1         MBEDTLS_OID_TELETRUST \"\\x03\\x03\\x02\\x08\\x01\\x01\"\n\n/* brainpoolP256r1 OBJECT IDENTIFIER ::= {versionOne 7} */\n#define MBEDTLS_OID_EC_GRP_BP256R1          MBEDTLS_OID_EC_BRAINPOOL_V1 \"\\x07\"\n\n/* brainpoolP384r1 OBJECT IDENTIFIER ::= {versionOne 11} */\n#define MBEDTLS_OID_EC_GRP_BP384R1          MBEDTLS_OID_EC_BRAINPOOL_V1 \"\\x0B\"\n\n/* brainpoolP512r1 OBJECT IDENTIFIER ::= {versionOne 13} */\n#define MBEDTLS_OID_EC_GRP_BP512R1          MBEDTLS_OID_EC_BRAINPOOL_V1 \"\\x0D\"\n\n/*\n * SEC1 C.1\n *\n * prime-field OBJECT IDENTIFIER ::= { id-fieldType 1 }\n * id-fieldType OBJECT IDENTIFIER ::= { ansi-X9-62 fieldType(1)}\n */\n#define MBEDTLS_OID_ANSI_X9_62_FIELD_TYPE   MBEDTLS_OID_ANSI_X9_62 \"\\x01\"\n#define MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD  MBEDTLS_OID_ANSI_X9_62_FIELD_TYPE \"\\x01\"\n\n/*\n * ECDSA signature identifiers, from RFC 5480\n */\n#define MBEDTLS_OID_ANSI_X9_62_SIG          MBEDTLS_OID_ANSI_X9_62 \"\\x04\" /* signatures(4) */\n#define MBEDTLS_OID_ANSI_X9_62_SIG_SHA2     MBEDTLS_OID_ANSI_X9_62_SIG \"\\x03\" /* ecdsa-with-SHA2(3) */\n\n/* ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {\n *   iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) 1 } */\n#define MBEDTLS_OID_ECDSA_SHA1              MBEDTLS_OID_ANSI_X9_62_SIG \"\\x01\"\n\n/* ecdsa-with-SHA224 OBJECT IDENTIFIER ::= {\n *   iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)\n *   ecdsa-with-SHA2(3) 1 } */\n#define MBEDTLS_OID_ECDSA_SHA224            MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 \"\\x01\"\n\n/* ecdsa-with-SHA256 OBJECT IDENTIFIER ::= {\n *   iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)\n *   ecdsa-with-SHA2(3) 2 } */\n#define MBEDTLS_OID_ECDSA_SHA256            MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 \"\\x02\"\n\n/* ecdsa-with-SHA384 OBJECT IDENTIFIER ::= {\n *   iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)\n *   ecdsa-with-SHA2(3) 3 } */\n#define MBEDTLS_OID_ECDSA_SHA384            MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 \"\\x03\"\n\n/* ecdsa-with-SHA512 OBJECT IDENTIFIER ::= {\n *   iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)\n *   ecdsa-with-SHA2(3) 4 } */\n#define MBEDTLS_OID_ECDSA_SHA512            MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 \"\\x04\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief Base OID descriptor structure\n */\ntypedef struct {\n    const char *asn1;               /*!< OID ASN.1 representation       */\n    size_t asn1_len;                /*!< length of asn1                 */\n    const char *name;               /*!< official name (e.g. from RFC)  */\n    const char *description;        /*!< human friendly description     */\n} mbedtls_oid_descriptor_t;\n\n/**\n * \\brief           Translate an ASN.1 OID into its numeric representation\n *                  (e.g. \"\\x2A\\x86\\x48\\x86\\xF7\\x0D\" into \"1.2.840.113549\")\n *\n * \\param buf       buffer to put representation in\n * \\param size      size of the buffer\n * \\param oid       OID to translate\n *\n * \\return          Length of the string written (excluding final NULL) or\n *                  MBEDTLS_ERR_OID_BUF_TOO_SMALL in case of error\n */\nint mbedtls_oid_get_numeric_string( char *buf, size_t size, const mbedtls_asn1_buf *oid );\n\n#if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C)\n/**\n * \\brief          Translate an X.509 extension OID into local values\n *\n * \\param oid      OID to use\n * \\param ext_type place to store the extension type\n *\n * \\return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND\n */\nint mbedtls_oid_get_x509_ext_type( const mbedtls_asn1_buf *oid, int *ext_type );\n#endif\n\n/**\n * \\brief          Translate an X.509 attribute type OID into the short name\n *                 (e.g. the OID for an X520 Common Name into \"CN\")\n *\n * \\param oid      OID to use\n * \\param short_name    place to store the string pointer\n *\n * \\return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND\n */\nint mbedtls_oid_get_attr_short_name( const mbedtls_asn1_buf *oid, const char **short_name );\n\n/**\n * \\brief          Translate PublicKeyAlgorithm OID into pk_type\n *\n * \\param oid      OID to use\n * \\param pk_alg   place to store public key algorithm\n *\n * \\return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND\n */\nint mbedtls_oid_get_pk_alg( const mbedtls_asn1_buf *oid, mbedtls_pk_type_t *pk_alg );\n\n/**\n * \\brief          Translate pk_type into PublicKeyAlgorithm OID\n *\n * \\param pk_alg   Public key type to look for\n * \\param oid      place to store ASN.1 OID string pointer\n * \\param olen     length of the OID\n *\n * \\return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND\n */\nint mbedtls_oid_get_oid_by_pk_alg( mbedtls_pk_type_t pk_alg,\n                           const char **oid, size_t *olen );\n\n#if defined(MBEDTLS_ECP_C)\n/**\n * \\brief          Translate NamedCurve OID into an EC group identifier\n *\n * \\param oid      OID to use\n * \\param grp_id   place to store group id\n *\n * \\return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND\n */\nint mbedtls_oid_get_ec_grp( const mbedtls_asn1_buf *oid, mbedtls_ecp_group_id *grp_id );\n\n/**\n * \\brief          Translate EC group identifier into NamedCurve OID\n *\n * \\param grp_id   EC group identifier\n * \\param oid      place to store ASN.1 OID string pointer\n * \\param olen     length of the OID\n *\n * \\return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND\n */\nint mbedtls_oid_get_oid_by_ec_grp( mbedtls_ecp_group_id grp_id,\n                           const char **oid, size_t *olen );\n#endif /* MBEDTLS_ECP_C */\n\n#if defined(MBEDTLS_MD_C)\n/**\n * \\brief          Translate SignatureAlgorithm OID into md_type and pk_type\n *\n * \\param oid      OID to use\n * \\param md_alg   place to store message digest algorithm\n * \\param pk_alg   place to store public key algorithm\n *\n * \\return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND\n */\nint mbedtls_oid_get_sig_alg( const mbedtls_asn1_buf *oid,\n                     mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg );\n\n/**\n * \\brief          Translate SignatureAlgorithm OID into description\n *\n * \\param oid      OID to use\n * \\param desc     place to store string pointer\n *\n * \\return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND\n */\nint mbedtls_oid_get_sig_alg_desc( const mbedtls_asn1_buf *oid, const char **desc );\n\n/**\n * \\brief          Translate md_type and pk_type into SignatureAlgorithm OID\n *\n * \\param md_alg   message digest algorithm\n * \\param pk_alg   public key algorithm\n * \\param oid      place to store ASN.1 OID string pointer\n * \\param olen     length of the OID\n *\n * \\return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND\n */\nint mbedtls_oid_get_oid_by_sig_alg( mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg,\n                            const char **oid, size_t *olen );\n\n/**\n * \\brief          Translate hash algorithm OID into md_type\n *\n * \\param oid      OID to use\n * \\param md_alg   place to store message digest algorithm\n *\n * \\return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND\n */\nint mbedtls_oid_get_md_alg( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg );\n\n/**\n * \\brief          Translate hmac algorithm OID into md_type\n *\n * \\param oid      OID to use\n * \\param md_hmac  place to store message hmac algorithm\n *\n * \\return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND\n */\nint mbedtls_oid_get_md_hmac( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_hmac );\n#endif /* MBEDTLS_MD_C */\n\n/**\n * \\brief          Translate Extended Key Usage OID into description\n *\n * \\param oid      OID to use\n * \\param desc     place to store string pointer\n *\n * \\return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND\n */\nint mbedtls_oid_get_extended_key_usage( const mbedtls_asn1_buf *oid, const char **desc );\n\n/**\n * \\brief          Translate md_type into hash algorithm OID\n *\n * \\param md_alg   message digest algorithm\n * \\param oid      place to store ASN.1 OID string pointer\n * \\param olen     length of the OID\n *\n * \\return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND\n */\nint mbedtls_oid_get_oid_by_md( mbedtls_md_type_t md_alg, const char **oid, size_t *olen );\n\n#if defined(MBEDTLS_CIPHER_C)\n/**\n * \\brief          Translate encryption algorithm OID into cipher_type\n *\n * \\param oid           OID to use\n * \\param cipher_alg    place to store cipher algorithm\n *\n * \\return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND\n */\nint mbedtls_oid_get_cipher_alg( const mbedtls_asn1_buf *oid, mbedtls_cipher_type_t *cipher_alg );\n#endif /* MBEDTLS_CIPHER_C */\n\n#if defined(MBEDTLS_PKCS12_C)\n/**\n * \\brief          Translate PKCS#12 PBE algorithm OID into md_type and\n *                 cipher_type\n *\n * \\param oid           OID to use\n * \\param md_alg        place to store message digest algorithm\n * \\param cipher_alg    place to store cipher algorithm\n *\n * \\return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND\n */\nint mbedtls_oid_get_pkcs12_pbe_alg( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg,\n                            mbedtls_cipher_type_t *cipher_alg );\n#endif /* MBEDTLS_PKCS12_C */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* oid.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/padlock.h",
    "content": "/**\n * \\file padlock.h\n *\n * \\brief VIA PadLock ACE for HW encryption/decryption supported by some\n *        processors\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_PADLOCK_H\n#define MBEDTLS_PADLOCK_H\n\n#include \"aes.h\"\n\n#define MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED               -0x0030  /**< Input data should be aligned. */\n\n#if defined(__has_feature)\n#if __has_feature(address_sanitizer)\n#define MBEDTLS_HAVE_ASAN\n#endif\n#endif\n\n/* Some versions of ASan result in errors about not enough registers */\n#if defined(MBEDTLS_HAVE_ASM) && defined(__GNUC__) && defined(__i386__) && \\\n    !defined(MBEDTLS_HAVE_ASAN)\n\n#ifndef MBEDTLS_HAVE_X86\n#define MBEDTLS_HAVE_X86\n#endif\n\n#include <stdint.h>\n\n#define MBEDTLS_PADLOCK_RNG 0x000C\n#define MBEDTLS_PADLOCK_ACE 0x00C0\n#define MBEDTLS_PADLOCK_PHE 0x0C00\n#define MBEDTLS_PADLOCK_PMM 0x3000\n\n#define MBEDTLS_PADLOCK_ALIGN16(x) (uint32_t *) (16 + ((int32_t) x & ~15))\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief          PadLock detection routine\n *\n * \\param feature  The feature to detect\n *\n * \\return         1 if CPU has support for the feature, 0 otherwise\n */\nint mbedtls_padlock_has_support( int feature );\n\n/**\n * \\brief          PadLock AES-ECB block en(de)cryption\n *\n * \\param ctx      AES context\n * \\param mode     MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT\n * \\param input    16-byte input block\n * \\param output   16-byte output block\n *\n * \\return         0 if success, 1 if operation failed\n */\nint mbedtls_padlock_xcryptecb( mbedtls_aes_context *ctx,\n                       int mode,\n                       const unsigned char input[16],\n                       unsigned char output[16] );\n\n/**\n * \\brief          PadLock AES-CBC buffer en(de)cryption\n *\n * \\param ctx      AES context\n * \\param mode     MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT\n * \\param length   length of the input data\n * \\param iv       initialization vector (updated after use)\n * \\param input    buffer holding the input data\n * \\param output   buffer holding the output data\n *\n * \\return         0 if success, 1 if operation failed\n */\nint mbedtls_padlock_xcryptcbc( mbedtls_aes_context *ctx,\n                       int mode,\n                       size_t length,\n                       unsigned char iv[16],\n                       const unsigned char *input,\n                       unsigned char *output );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* HAVE_X86  */\n\n#endif /* padlock.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/pem.h",
    "content": "/**\n * \\file pem.h\n *\n * \\brief Privacy Enhanced Mail (PEM) decoding\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_PEM_H\n#define MBEDTLS_PEM_H\n\n#include <stddef.h>\n\n/**\n * \\name PEM Error codes\n * These error codes are returned in case of errors reading the\n * PEM data.\n * \\{\n */\n#define MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT          -0x1080  /**< No PEM header or footer found. */\n#define MBEDTLS_ERR_PEM_INVALID_DATA                      -0x1100  /**< PEM string is not as expected. */\n#define MBEDTLS_ERR_PEM_ALLOC_FAILED                      -0x1180  /**< Failed to allocate memory. */\n#define MBEDTLS_ERR_PEM_INVALID_ENC_IV                    -0x1200  /**< RSA IV is not in hex-format. */\n#define MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG                   -0x1280  /**< Unsupported key encryption algorithm. */\n#define MBEDTLS_ERR_PEM_PASSWORD_REQUIRED                 -0x1300  /**< Private key password can't be empty. */\n#define MBEDTLS_ERR_PEM_PASSWORD_MISMATCH                 -0x1380  /**< Given private key password does not allow for correct decryption. */\n#define MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE               -0x1400  /**< Unavailable feature, e.g. hashing/encryption combination. */\n#define MBEDTLS_ERR_PEM_BAD_INPUT_DATA                    -0x1480  /**< Bad input parameters to function. */\n/* \\} name */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if defined(MBEDTLS_PEM_PARSE_C)\n/**\n * \\brief       PEM context structure\n */\ntypedef struct\n{\n    unsigned char *buf;     /*!< buffer for decoded data             */\n    size_t buflen;          /*!< length of the buffer                */\n    unsigned char *info;    /*!< buffer for extra header information */\n}\nmbedtls_pem_context;\n\n/**\n * \\brief       PEM context setup\n *\n * \\param ctx   context to be initialized\n */\nvoid mbedtls_pem_init( mbedtls_pem_context *ctx );\n\n/**\n * \\brief       Read a buffer for PEM information and store the resulting\n *              data into the specified context buffers.\n *\n * \\param ctx       context to use\n * \\param header    header string to seek and expect\n * \\param footer    footer string to seek and expect\n * \\param data      source data to look in (must be nul-terminated)\n * \\param pwd       password for decryption (can be NULL)\n * \\param pwdlen    length of password\n * \\param use_len   destination for total length used (set after header is\n *                  correctly read, so unless you get\n *                  MBEDTLS_ERR_PEM_BAD_INPUT_DATA or\n *                  MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT, use_len is\n *                  the length to skip)\n *\n * \\note            Attempts to check password correctness by verifying if\n *                  the decrypted text starts with an ASN.1 sequence of\n *                  appropriate length\n *\n * \\return          0 on success, or a specific PEM error code\n */\nint mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const char *footer,\n                     const unsigned char *data,\n                     const unsigned char *pwd,\n                     size_t pwdlen, size_t *use_len );\n\n/**\n * \\brief       PEM context memory freeing\n *\n * \\param ctx   context to be freed\n */\nvoid mbedtls_pem_free( mbedtls_pem_context *ctx );\n#endif /* MBEDTLS_PEM_PARSE_C */\n\n#if defined(MBEDTLS_PEM_WRITE_C)\n/**\n * \\brief           Write a buffer of PEM information from a DER encoded\n *                  buffer.\n *\n * \\param header    header string to write\n * \\param footer    footer string to write\n * \\param der_data  DER data to write\n * \\param der_len   length of the DER data\n * \\param buf       buffer to write to\n * \\param buf_len   length of output buffer\n * \\param olen      total length written / required (if buf_len is not enough)\n *\n * \\return          0 on success, or a specific PEM or BASE64 error code. On\n *                  MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL olen is the required\n *                  size.\n */\nint mbedtls_pem_write_buffer( const char *header, const char *footer,\n                      const unsigned char *der_data, size_t der_len,\n                      unsigned char *buf, size_t buf_len, size_t *olen );\n#endif /* MBEDTLS_PEM_WRITE_C */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* pem.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/pk.h",
    "content": "/**\n * \\file pk.h\n *\n * \\brief Public Key abstraction layer\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_PK_H\n#define MBEDTLS_PK_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include \"md.h\"\n\n#if defined(MBEDTLS_RSA_C)\n#include \"rsa.h\"\n#endif\n\n#if defined(MBEDTLS_ECP_C)\n#include \"ecp.h\"\n#endif\n\n#if defined(MBEDTLS_ECDSA_C)\n#include \"ecdsa.h\"\n#endif\n\n#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \\\n    !defined(inline) && !defined(__cplusplus)\n#define inline __inline\n#endif\n\n#define MBEDTLS_ERR_PK_ALLOC_FAILED        -0x3F80  /**< Memory allocation failed. */\n#define MBEDTLS_ERR_PK_TYPE_MISMATCH       -0x3F00  /**< Type mismatch, eg attempt to encrypt with an ECDSA key */\n#define MBEDTLS_ERR_PK_BAD_INPUT_DATA      -0x3E80  /**< Bad input parameters to function. */\n#define MBEDTLS_ERR_PK_FILE_IO_ERROR       -0x3E00  /**< Read/write of file failed. */\n#define MBEDTLS_ERR_PK_KEY_INVALID_VERSION -0x3D80  /**< Unsupported key version */\n#define MBEDTLS_ERR_PK_KEY_INVALID_FORMAT  -0x3D00  /**< Invalid key tag or value. */\n#define MBEDTLS_ERR_PK_UNKNOWN_PK_ALG      -0x3C80  /**< Key algorithm is unsupported (only RSA and EC are supported). */\n#define MBEDTLS_ERR_PK_PASSWORD_REQUIRED   -0x3C00  /**< Private key password can't be empty. */\n#define MBEDTLS_ERR_PK_PASSWORD_MISMATCH   -0x3B80  /**< Given private key password does not allow for correct decryption. */\n#define MBEDTLS_ERR_PK_INVALID_PUBKEY      -0x3B00  /**< The pubkey tag or value is invalid (only RSA and EC are supported). */\n#define MBEDTLS_ERR_PK_INVALID_ALG         -0x3A80  /**< The algorithm tag or value is invalid. */\n#define MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE -0x3A00  /**< Elliptic curve is unsupported (only NIST curves are supported). */\n#define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980  /**< Unavailable feature, e.g. RSA disabled for RSA key. */\n#define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH    -0x3900  /**< The buffer contains a valid signature followed by more data. */\n#define MBEDTLS_ERR_PK_HW_ACCEL_FAILED     -0x3880  /**< PK hardware accelerator failed. */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief          Public key types\n */\ntypedef enum {\n    MBEDTLS_PK_NONE=0,\n    MBEDTLS_PK_RSA,\n    MBEDTLS_PK_ECKEY,\n    MBEDTLS_PK_ECKEY_DH,\n    MBEDTLS_PK_ECDSA,\n    MBEDTLS_PK_RSA_ALT,\n    MBEDTLS_PK_RSASSA_PSS,\n} mbedtls_pk_type_t;\n\n/**\n * \\brief           Options for RSASSA-PSS signature verification.\n *                  See \\c mbedtls_rsa_rsassa_pss_verify_ext()\n */\ntypedef struct\n{\n    mbedtls_md_type_t mgf1_hash_id;\n    int expected_salt_len;\n\n} mbedtls_pk_rsassa_pss_options;\n\n/**\n * \\brief           Types for interfacing with the debug module\n */\ntypedef enum\n{\n    MBEDTLS_PK_DEBUG_NONE = 0,\n    MBEDTLS_PK_DEBUG_MPI,\n    MBEDTLS_PK_DEBUG_ECP,\n} mbedtls_pk_debug_type;\n\n/**\n * \\brief           Item to send to the debug module\n */\ntypedef struct\n{\n    mbedtls_pk_debug_type type;\n    const char *name;\n    void *value;\n} mbedtls_pk_debug_item;\n\n/** Maximum number of item send for debugging, plus 1 */\n#define MBEDTLS_PK_DEBUG_MAX_ITEMS 3\n\n/**\n * \\brief           Public key information and operations\n */\ntypedef struct mbedtls_pk_info_t mbedtls_pk_info_t;\n\n/**\n * \\brief           Public key container\n */\ntypedef struct\n{\n    const mbedtls_pk_info_t *   pk_info; /**< Public key informations        */\n    void *                      pk_ctx;  /**< Underlying public key context  */\n} mbedtls_pk_context;\n\n#if defined(MBEDTLS_RSA_C)\n/**\n * Quick access to an RSA context inside a PK context.\n *\n * \\warning You must make sure the PK context actually holds an RSA context\n * before using this function!\n */\nstatic inline mbedtls_rsa_context *mbedtls_pk_rsa( const mbedtls_pk_context pk )\n{\n    return( (mbedtls_rsa_context *) (pk).pk_ctx );\n}\n#endif /* MBEDTLS_RSA_C */\n\n#if defined(MBEDTLS_ECP_C)\n/**\n * Quick access to an EC context inside a PK context.\n *\n * \\warning You must make sure the PK context actually holds an EC context\n * before using this function!\n */\nstatic inline mbedtls_ecp_keypair *mbedtls_pk_ec( const mbedtls_pk_context pk )\n{\n    return( (mbedtls_ecp_keypair *) (pk).pk_ctx );\n}\n#endif /* MBEDTLS_ECP_C */\n\n#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)\n/**\n * \\brief           Types for RSA-alt abstraction\n */\ntypedef int (*mbedtls_pk_rsa_alt_decrypt_func)( void *ctx, int mode, size_t *olen,\n                    const unsigned char *input, unsigned char *output,\n                    size_t output_max_len );\ntypedef int (*mbedtls_pk_rsa_alt_sign_func)( void *ctx,\n                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,\n                    int mode, mbedtls_md_type_t md_alg, unsigned int hashlen,\n                    const unsigned char *hash, unsigned char *sig );\ntypedef size_t (*mbedtls_pk_rsa_alt_key_len_func)( void *ctx );\n#endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */\n\n/**\n * \\brief           Return information associated with the given PK type\n *\n * \\param pk_type   PK type to search for.\n *\n * \\return          The PK info associated with the type or NULL if not found.\n */\nconst mbedtls_pk_info_t *mbedtls_pk_info_from_type( mbedtls_pk_type_t pk_type );\n\n/**\n * \\brief           Initialize a mbedtls_pk_context (as NONE)\n */\nvoid mbedtls_pk_init( mbedtls_pk_context *ctx );\n\n/**\n * \\brief           Free a mbedtls_pk_context\n */\nvoid mbedtls_pk_free( mbedtls_pk_context *ctx );\n\n/**\n * \\brief           Initialize a PK context with the information given\n *                  and allocates the type-specific PK subcontext.\n *\n * \\param ctx       Context to initialize. Must be empty (type NONE).\n * \\param info      Information to use\n *\n * \\return          0 on success,\n *                  MBEDTLS_ERR_PK_BAD_INPUT_DATA on invalid input,\n *                  MBEDTLS_ERR_PK_ALLOC_FAILED on allocation failure.\n *\n * \\note            For contexts holding an RSA-alt key, use\n *                  \\c mbedtls_pk_setup_rsa_alt() instead.\n */\nint mbedtls_pk_setup( mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info );\n\n#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)\n/**\n * \\brief           Initialize an RSA-alt context\n *\n * \\param ctx       Context to initialize. Must be empty (type NONE).\n * \\param key       RSA key pointer\n * \\param decrypt_func  Decryption function\n * \\param sign_func     Signing function\n * \\param key_len_func  Function returning key length in bytes\n *\n * \\return          0 on success, or MBEDTLS_ERR_PK_BAD_INPUT_DATA if the\n *                  context wasn't already initialized as RSA_ALT.\n *\n * \\note            This function replaces \\c mbedtls_pk_setup() for RSA-alt.\n */\nint mbedtls_pk_setup_rsa_alt( mbedtls_pk_context *ctx, void * key,\n                         mbedtls_pk_rsa_alt_decrypt_func decrypt_func,\n                         mbedtls_pk_rsa_alt_sign_func sign_func,\n                         mbedtls_pk_rsa_alt_key_len_func key_len_func );\n#endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */\n\n/**\n * \\brief           Get the size in bits of the underlying key\n *\n * \\param ctx       Context to use\n *\n * \\return          Key size in bits, or 0 on error\n */\nsize_t mbedtls_pk_get_bitlen( const mbedtls_pk_context *ctx );\n\n/**\n * \\brief           Get the length in bytes of the underlying key\n * \\param ctx       Context to use\n *\n * \\return          Key length in bytes, or 0 on error\n */\nstatic inline size_t mbedtls_pk_get_len( const mbedtls_pk_context *ctx )\n{\n    return( ( mbedtls_pk_get_bitlen( ctx ) + 7 ) / 8 );\n}\n\n/**\n * \\brief           Tell if a context can do the operation given by type\n *\n * \\param ctx       Context to test\n * \\param type      Target type\n *\n * \\return          0 if context can't do the operations,\n *                  1 otherwise.\n */\nint mbedtls_pk_can_do( const mbedtls_pk_context *ctx, mbedtls_pk_type_t type );\n\n/**\n * \\brief           Verify signature (including padding if relevant).\n *\n * \\param ctx       PK context to use\n * \\param md_alg    Hash algorithm used (see notes)\n * \\param hash      Hash of the message to sign\n * \\param hash_len  Hash length or 0 (see notes)\n * \\param sig       Signature to verify\n * \\param sig_len   Signature length\n *\n * \\return          0 on success (signature is valid),\n *                  #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid\n *                  signature in sig but its length is less than \\p siglen,\n *                  or a specific error code.\n *\n * \\note            For RSA keys, the default padding type is PKCS#1 v1.5.\n *                  Use \\c mbedtls_pk_verify_ext( MBEDTLS_PK_RSASSA_PSS, ... )\n *                  to verify RSASSA_PSS signatures.\n *\n * \\note            If hash_len is 0, then the length associated with md_alg\n *                  is used instead, or an error returned if it is invalid.\n *\n * \\note            md_alg may be MBEDTLS_MD_NONE, only if hash_len != 0\n */\nint mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,\n               const unsigned char *hash, size_t hash_len,\n               const unsigned char *sig, size_t sig_len );\n\n/**\n * \\brief           Verify signature, with options.\n *                  (Includes verification of the padding depending on type.)\n *\n * \\param type      Signature type (inc. possible padding type) to verify\n * \\param options   Pointer to type-specific options, or NULL\n * \\param ctx       PK context to use\n * \\param md_alg    Hash algorithm used (see notes)\n * \\param hash      Hash of the message to sign\n * \\param hash_len  Hash length or 0 (see notes)\n * \\param sig       Signature to verify\n * \\param sig_len   Signature length\n *\n * \\return          0 on success (signature is valid),\n *                  #MBEDTLS_ERR_PK_TYPE_MISMATCH if the PK context can't be\n *                  used for this type of signatures,\n *                  #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid\n *                  signature in sig but its length is less than \\p siglen,\n *                  or a specific error code.\n *\n * \\note            If hash_len is 0, then the length associated with md_alg\n *                  is used instead, or an error returned if it is invalid.\n *\n * \\note            md_alg may be MBEDTLS_MD_NONE, only if hash_len != 0\n *\n * \\note            If type is MBEDTLS_PK_RSASSA_PSS, then options must point\n *                  to a mbedtls_pk_rsassa_pss_options structure,\n *                  otherwise it must be NULL.\n */\nint mbedtls_pk_verify_ext( mbedtls_pk_type_t type, const void *options,\n                   mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,\n                   const unsigned char *hash, size_t hash_len,\n                   const unsigned char *sig, size_t sig_len );\n\n/**\n * \\brief           Make signature, including padding if relevant.\n *\n * \\param ctx       PK context to use - must hold a private key\n * \\param md_alg    Hash algorithm used (see notes)\n * \\param hash      Hash of the message to sign\n * \\param hash_len  Hash length or 0 (see notes)\n * \\param sig       Place to write the signature\n * \\param sig_len   Number of bytes written\n * \\param f_rng     RNG function\n * \\param p_rng     RNG parameter\n *\n * \\return          0 on success, or a specific error code.\n *\n * \\note            For RSA keys, the default padding type is PKCS#1 v1.5.\n *                  There is no interface in the PK module to make RSASSA-PSS\n *                  signatures yet.\n *\n * \\note            If hash_len is 0, then the length associated with md_alg\n *                  is used instead, or an error returned if it is invalid.\n *\n * \\note            For RSA, md_alg may be MBEDTLS_MD_NONE if hash_len != 0.\n *                  For ECDSA, md_alg may never be MBEDTLS_MD_NONE.\n */\nint mbedtls_pk_sign( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,\n             const unsigned char *hash, size_t hash_len,\n             unsigned char *sig, size_t *sig_len,\n             int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );\n\n/**\n * \\brief           Decrypt message (including padding if relevant).\n *\n * \\param ctx       PK context to use - must hold a private key\n * \\param input     Input to decrypt\n * \\param ilen      Input size\n * \\param output    Decrypted output\n * \\param olen      Decrypted message length\n * \\param osize     Size of the output buffer\n * \\param f_rng     RNG function\n * \\param p_rng     RNG parameter\n *\n * \\note            For RSA keys, the default padding type is PKCS#1 v1.5.\n *\n * \\return          0 on success, or a specific error code.\n */\nint mbedtls_pk_decrypt( mbedtls_pk_context *ctx,\n                const unsigned char *input, size_t ilen,\n                unsigned char *output, size_t *olen, size_t osize,\n                int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );\n\n/**\n * \\brief           Encrypt message (including padding if relevant).\n *\n * \\param ctx       PK context to use\n * \\param input     Message to encrypt\n * \\param ilen      Message size\n * \\param output    Encrypted output\n * \\param olen      Encrypted output length\n * \\param osize     Size of the output buffer\n * \\param f_rng     RNG function\n * \\param p_rng     RNG parameter\n *\n * \\note            For RSA keys, the default padding type is PKCS#1 v1.5.\n *\n * \\return          0 on success, or a specific error code.\n */\nint mbedtls_pk_encrypt( mbedtls_pk_context *ctx,\n                const unsigned char *input, size_t ilen,\n                unsigned char *output, size_t *olen, size_t osize,\n                int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );\n\n/**\n * \\brief           Check if a public-private pair of keys matches.\n *\n * \\param pub       Context holding a public key.\n * \\param prv       Context holding a private (and public) key.\n *\n * \\return          0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA\n */\nint mbedtls_pk_check_pair( const mbedtls_pk_context *pub, const mbedtls_pk_context *prv );\n\n/**\n * \\brief           Export debug information\n *\n * \\param ctx       Context to use\n * \\param items     Place to write debug items\n *\n * \\return          0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA\n */\nint mbedtls_pk_debug( const mbedtls_pk_context *ctx, mbedtls_pk_debug_item *items );\n\n/**\n * \\brief           Access the type name\n *\n * \\param ctx       Context to use\n *\n * \\return          Type name on success, or \"invalid PK\"\n */\nconst char * mbedtls_pk_get_name( const mbedtls_pk_context *ctx );\n\n/**\n * \\brief           Get the key type\n *\n * \\param ctx       Context to use\n *\n * \\return          Type on success, or MBEDTLS_PK_NONE\n */\nmbedtls_pk_type_t mbedtls_pk_get_type( const mbedtls_pk_context *ctx );\n\n#if defined(MBEDTLS_PK_PARSE_C)\n/** \\ingroup pk_module */\n/**\n * \\brief           Parse a private key in PEM or DER format\n *\n * \\param ctx       key to be initialized\n * \\param key       input buffer\n * \\param keylen    size of the buffer\n *                  (including the terminating null byte for PEM data)\n * \\param pwd       password for decryption (optional)\n * \\param pwdlen    size of the password\n *\n * \\note            On entry, ctx must be empty, either freshly initialised\n *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a\n *                  specific key type, check the result with mbedtls_pk_can_do().\n *\n * \\note            The key is also checked for correctness.\n *\n * \\return          0 if successful, or a specific PK or PEM error code\n */\nint mbedtls_pk_parse_key( mbedtls_pk_context *ctx,\n                  const unsigned char *key, size_t keylen,\n                  const unsigned char *pwd, size_t pwdlen );\n\n/** \\ingroup pk_module */\n/**\n * \\brief           Parse a public key in PEM or DER format\n *\n * \\param ctx       key to be initialized\n * \\param key       input buffer\n * \\param keylen    size of the buffer\n *                  (including the terminating null byte for PEM data)\n *\n * \\note            On entry, ctx must be empty, either freshly initialised\n *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a\n *                  specific key type, check the result with mbedtls_pk_can_do().\n *\n * \\note            The key is also checked for correctness.\n *\n * \\return          0 if successful, or a specific PK or PEM error code\n */\nint mbedtls_pk_parse_public_key( mbedtls_pk_context *ctx,\n                         const unsigned char *key, size_t keylen );\n\n#if defined(MBEDTLS_FS_IO)\n/** \\ingroup pk_module */\n/**\n * \\brief           Load and parse a private key\n *\n * \\param ctx       key to be initialized\n * \\param path      filename to read the private key from\n * \\param password  password to decrypt the file (can be NULL)\n *\n * \\note            On entry, ctx must be empty, either freshly initialised\n *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a\n *                  specific key type, check the result with mbedtls_pk_can_do().\n *\n * \\note            The key is also checked for correctness.\n *\n * \\return          0 if successful, or a specific PK or PEM error code\n */\nint mbedtls_pk_parse_keyfile( mbedtls_pk_context *ctx,\n                      const char *path, const char *password );\n\n/** \\ingroup pk_module */\n/**\n * \\brief           Load and parse a public key\n *\n * \\param ctx       key to be initialized\n * \\param path      filename to read the public key from\n *\n * \\note            On entry, ctx must be empty, either freshly initialised\n *                  with mbedtls_pk_init() or reset with mbedtls_pk_free(). If\n *                  you need a specific key type, check the result with\n *                  mbedtls_pk_can_do().\n *\n * \\note            The key is also checked for correctness.\n *\n * \\return          0 if successful, or a specific PK or PEM error code\n */\nint mbedtls_pk_parse_public_keyfile( mbedtls_pk_context *ctx, const char *path );\n#endif /* MBEDTLS_FS_IO */\n#endif /* MBEDTLS_PK_PARSE_C */\n\n#if defined(MBEDTLS_PK_WRITE_C)\n/**\n * \\brief           Write a private key to a PKCS#1 or SEC1 DER structure\n *                  Note: data is written at the end of the buffer! Use the\n *                        return value to determine where you should start\n *                        using the buffer\n *\n * \\param ctx       private to write away\n * \\param buf       buffer to write to\n * \\param size      size of the buffer\n *\n * \\return          length of data written if successful, or a specific\n *                  error code\n */\nint mbedtls_pk_write_key_der( mbedtls_pk_context *ctx, unsigned char *buf, size_t size );\n\n/**\n * \\brief           Write a public key to a SubjectPublicKeyInfo DER structure\n *                  Note: data is written at the end of the buffer! Use the\n *                        return value to determine where you should start\n *                        using the buffer\n *\n * \\param ctx       public key to write away\n * \\param buf       buffer to write to\n * \\param size      size of the buffer\n *\n * \\return          length of data written if successful, or a specific\n *                  error code\n */\nint mbedtls_pk_write_pubkey_der( mbedtls_pk_context *ctx, unsigned char *buf, size_t size );\n\n#if defined(MBEDTLS_PEM_WRITE_C)\n/**\n * \\brief           Write a public key to a PEM string\n *\n * \\param ctx       public key to write away\n * \\param buf       buffer to write to\n * \\param size      size of the buffer\n *\n * \\return          0 if successful, or a specific error code\n */\nint mbedtls_pk_write_pubkey_pem( mbedtls_pk_context *ctx, unsigned char *buf, size_t size );\n\n/**\n * \\brief           Write a private key to a PKCS#1 or SEC1 PEM string\n *\n * \\param ctx       private to write away\n * \\param buf       buffer to write to\n * \\param size      size of the buffer\n *\n * \\return          0 if successful, or a specific error code\n */\nint mbedtls_pk_write_key_pem( mbedtls_pk_context *ctx, unsigned char *buf, size_t size );\n#endif /* MBEDTLS_PEM_WRITE_C */\n#endif /* MBEDTLS_PK_WRITE_C */\n\n/*\n * WARNING: Low-level functions. You probably do not want to use these unless\n *          you are certain you do ;)\n */\n\n#if defined(MBEDTLS_PK_PARSE_C)\n/**\n * \\brief           Parse a SubjectPublicKeyInfo DER structure\n *\n * \\param p         the position in the ASN.1 data\n * \\param end       end of the buffer\n * \\param pk        the key to fill\n *\n * \\return          0 if successful, or a specific PK error code\n */\nint mbedtls_pk_parse_subpubkey( unsigned char **p, const unsigned char *end,\n                        mbedtls_pk_context *pk );\n#endif /* MBEDTLS_PK_PARSE_C */\n\n#if defined(MBEDTLS_PK_WRITE_C)\n/**\n * \\brief           Write a subjectPublicKey to ASN.1 data\n *                  Note: function works backwards in data buffer\n *\n * \\param p         reference to current position pointer\n * \\param start     start of the buffer (for bounds-checking)\n * \\param key       public key to write away\n *\n * \\return          the length written or a negative error code\n */\nint mbedtls_pk_write_pubkey( unsigned char **p, unsigned char *start,\n                     const mbedtls_pk_context *key );\n#endif /* MBEDTLS_PK_WRITE_C */\n\n/*\n * Internal module functions. You probably do not want to use these unless you\n * know you do.\n */\n#if defined(MBEDTLS_FS_IO)\nint mbedtls_pk_load_file( const char *path, unsigned char **buf, size_t *n );\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* MBEDTLS_PK_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/pk_internal.h",
    "content": "/**\n * \\file pk_internal.h\n *\n * \\brief Public Key abstraction layer: wrapper functions\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_PK_WRAP_H\n#define MBEDTLS_PK_WRAP_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include \"pk.h\"\n\nstruct mbedtls_pk_info_t\n{\n    /** Public key type */\n    mbedtls_pk_type_t type;\n\n    /** Type name */\n    const char *name;\n\n    /** Get key size in bits */\n    size_t (*get_bitlen)( const void * );\n\n    /** Tell if the context implements this type (e.g. ECKEY can do ECDSA) */\n    int (*can_do)( mbedtls_pk_type_t type );\n\n    /** Verify signature */\n    int (*verify_func)( void *ctx, mbedtls_md_type_t md_alg,\n                        const unsigned char *hash, size_t hash_len,\n                        const unsigned char *sig, size_t sig_len );\n\n    /** Make signature */\n    int (*sign_func)( void *ctx, mbedtls_md_type_t md_alg,\n                      const unsigned char *hash, size_t hash_len,\n                      unsigned char *sig, size_t *sig_len,\n                      int (*f_rng)(void *, unsigned char *, size_t),\n                      void *p_rng );\n\n    /** Decrypt message */\n    int (*decrypt_func)( void *ctx, const unsigned char *input, size_t ilen,\n                         unsigned char *output, size_t *olen, size_t osize,\n                         int (*f_rng)(void *, unsigned char *, size_t),\n                         void *p_rng );\n\n    /** Encrypt message */\n    int (*encrypt_func)( void *ctx, const unsigned char *input, size_t ilen,\n                         unsigned char *output, size_t *olen, size_t osize,\n                         int (*f_rng)(void *, unsigned char *, size_t),\n                         void *p_rng );\n\n    /** Check public-private key pair */\n    int (*check_pair_func)( const void *pub, const void *prv );\n\n    /** Allocate a new context */\n    void * (*ctx_alloc_func)( void );\n\n    /** Free the given context */\n    void (*ctx_free_func)( void *ctx );\n\n    /** Interface with the debug module */\n    void (*debug_func)( const void *ctx, mbedtls_pk_debug_item *items );\n\n};\n#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)\n/* Container for RSA-alt */\ntypedef struct\n{\n    void *key;\n    mbedtls_pk_rsa_alt_decrypt_func decrypt_func;\n    mbedtls_pk_rsa_alt_sign_func sign_func;\n    mbedtls_pk_rsa_alt_key_len_func key_len_func;\n} mbedtls_rsa_alt_context;\n#endif\n\n#if defined(MBEDTLS_RSA_C)\nextern const mbedtls_pk_info_t mbedtls_rsa_info;\n#endif\n\n#if defined(MBEDTLS_ECP_C)\nextern const mbedtls_pk_info_t mbedtls_eckey_info;\nextern const mbedtls_pk_info_t mbedtls_eckeydh_info;\n#endif\n\n#if defined(MBEDTLS_ECDSA_C)\nextern const mbedtls_pk_info_t mbedtls_ecdsa_info;\n#endif\n\n#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)\nextern const mbedtls_pk_info_t mbedtls_rsa_alt_info;\n#endif\n\n#endif /* MBEDTLS_PK_WRAP_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/pkcs11.h",
    "content": "/**\n * \\file pkcs11.h\n *\n * \\brief Wrapper for PKCS#11 library libpkcs11-helper\n *\n * \\author Adriaan de Jong <dejong@fox-it.com>\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_PKCS11_H\n#define MBEDTLS_PKCS11_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_PKCS11_C)\n\n#include \"x509_crt.h\"\n\n#include <pkcs11-helper-1.0/pkcs11h-certificate.h>\n\n#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \\\n    !defined(inline) && !defined(__cplusplus)\n#define inline __inline\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * Context for PKCS #11 private keys.\n */\ntypedef struct {\n        pkcs11h_certificate_t pkcs11h_cert;\n        int len;\n} mbedtls_pkcs11_context;\n\n/**\n * Initialize a mbedtls_pkcs11_context.\n * (Just making memory references valid.)\n */\nvoid mbedtls_pkcs11_init( mbedtls_pkcs11_context *ctx );\n\n/**\n * Fill in a mbed TLS certificate, based on the given PKCS11 helper certificate.\n *\n * \\param cert          X.509 certificate to fill\n * \\param pkcs11h_cert  PKCS #11 helper certificate\n *\n * \\return              0 on success.\n */\nint mbedtls_pkcs11_x509_cert_bind( mbedtls_x509_crt *cert, pkcs11h_certificate_t pkcs11h_cert );\n\n/**\n * Set up a mbedtls_pkcs11_context storing the given certificate. Note that the\n * mbedtls_pkcs11_context will take over control of the certificate, freeing it when\n * done.\n *\n * \\param priv_key      Private key structure to fill.\n * \\param pkcs11_cert   PKCS #11 helper certificate\n *\n * \\return              0 on success\n */\nint mbedtls_pkcs11_priv_key_bind( mbedtls_pkcs11_context *priv_key,\n        pkcs11h_certificate_t pkcs11_cert );\n\n/**\n * Free the contents of the given private key context. Note that the structure\n * itself is not freed.\n *\n * \\param priv_key      Private key structure to cleanup\n */\nvoid mbedtls_pkcs11_priv_key_free( mbedtls_pkcs11_context *priv_key );\n\n/**\n * \\brief          Do an RSA private key decrypt, then remove the message\n *                 padding\n *\n * \\param ctx      PKCS #11 context\n * \\param mode     must be MBEDTLS_RSA_PRIVATE, for compatibility with rsa.c's signature\n * \\param input    buffer holding the encrypted data\n * \\param output   buffer that will hold the plaintext\n * \\param olen     will contain the plaintext length\n * \\param output_max_len    maximum length of the output buffer\n *\n * \\return         0 if successful, or an MBEDTLS_ERR_RSA_XXX error code\n *\n * \\note           The output buffer must be as large as the size\n *                 of ctx->N (eg. 128 bytes if RSA-1024 is used) otherwise\n *                 an error is thrown.\n */\nint mbedtls_pkcs11_decrypt( mbedtls_pkcs11_context *ctx,\n                       int mode, size_t *olen,\n                       const unsigned char *input,\n                       unsigned char *output,\n                       size_t output_max_len );\n\n/**\n * \\brief          Do a private RSA to sign a message digest\n *\n * \\param ctx      PKCS #11 context\n * \\param mode     must be MBEDTLS_RSA_PRIVATE, for compatibility with rsa.c's signature\n * \\param md_alg   a MBEDTLS_MD_XXX (use MBEDTLS_MD_NONE for signing raw data)\n * \\param hashlen  message digest length (for MBEDTLS_MD_NONE only)\n * \\param hash     buffer holding the message digest\n * \\param sig      buffer that will hold the ciphertext\n *\n * \\return         0 if the signing operation was successful,\n *                 or an MBEDTLS_ERR_RSA_XXX error code\n *\n * \\note           The \"sig\" buffer must be as large as the size\n *                 of ctx->N (eg. 128 bytes if RSA-1024 is used).\n */\nint mbedtls_pkcs11_sign( mbedtls_pkcs11_context *ctx,\n                    int mode,\n                    mbedtls_md_type_t md_alg,\n                    unsigned int hashlen,\n                    const unsigned char *hash,\n                    unsigned char *sig );\n\n/**\n * SSL/TLS wrappers for PKCS#11 functions\n */\nstatic inline int mbedtls_ssl_pkcs11_decrypt( void *ctx, int mode, size_t *olen,\n                        const unsigned char *input, unsigned char *output,\n                        size_t output_max_len )\n{\n    return mbedtls_pkcs11_decrypt( (mbedtls_pkcs11_context *) ctx, mode, olen, input, output,\n                           output_max_len );\n}\n\nstatic inline int mbedtls_ssl_pkcs11_sign( void *ctx,\n                     int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,\n                     int mode, mbedtls_md_type_t md_alg, unsigned int hashlen,\n                     const unsigned char *hash, unsigned char *sig )\n{\n    ((void) f_rng);\n    ((void) p_rng);\n    return mbedtls_pkcs11_sign( (mbedtls_pkcs11_context *) ctx, mode, md_alg,\n                        hashlen, hash, sig );\n}\n\nstatic inline size_t mbedtls_ssl_pkcs11_key_len( void *ctx )\n{\n    return ( (mbedtls_pkcs11_context *) ctx )->len;\n}\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* MBEDTLS_PKCS11_C */\n\n#endif /* MBEDTLS_PKCS11_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/pkcs12.h",
    "content": "/**\n * \\file pkcs12.h\n *\n * \\brief PKCS#12 Personal Information Exchange Syntax\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_PKCS12_H\n#define MBEDTLS_PKCS12_H\n\n#include \"md.h\"\n#include \"cipher.h\"\n#include \"asn1.h\"\n\n#include <stddef.h>\n\n#define MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA                 -0x1F80  /**< Bad input parameters to function. */\n#define MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE            -0x1F00  /**< Feature not available, e.g. unsupported encryption scheme. */\n#define MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT             -0x1E80  /**< PBE ASN.1 data not as expected. */\n#define MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH              -0x1E00  /**< Given private key password does not allow for correct decryption. */\n\n#define MBEDTLS_PKCS12_DERIVE_KEY       1   /**< encryption/decryption key */\n#define MBEDTLS_PKCS12_DERIVE_IV        2   /**< initialization vector     */\n#define MBEDTLS_PKCS12_DERIVE_MAC_KEY   3   /**< integrity / MAC key       */\n\n#define MBEDTLS_PKCS12_PBE_DECRYPT      0\n#define MBEDTLS_PKCS12_PBE_ENCRYPT      1\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief            PKCS12 Password Based function (encryption / decryption)\n *                   for pbeWithSHAAnd128BitRC4\n *\n * \\param pbe_params an ASN1 buffer containing the pkcs-12PbeParams structure\n * \\param mode       either MBEDTLS_PKCS12_PBE_ENCRYPT or MBEDTLS_PKCS12_PBE_DECRYPT\n * \\param pwd        the password used (may be NULL if no password is used)\n * \\param pwdlen     length of the password (may be 0)\n * \\param input      the input data\n * \\param len        data length\n * \\param output     the output buffer\n *\n * \\return           0 if successful, or a MBEDTLS_ERR_XXX code\n */\nint mbedtls_pkcs12_pbe_sha1_rc4_128( mbedtls_asn1_buf *pbe_params, int mode,\n                             const unsigned char *pwd,  size_t pwdlen,\n                             const unsigned char *input, size_t len,\n                             unsigned char *output );\n\n/**\n * \\brief            PKCS12 Password Based function (encryption / decryption)\n *                   for cipher-based and mbedtls_md-based PBE's\n *\n * \\param pbe_params an ASN1 buffer containing the pkcs-12PbeParams structure\n * \\param mode       either MBEDTLS_PKCS12_PBE_ENCRYPT or MBEDTLS_PKCS12_PBE_DECRYPT\n * \\param cipher_type the cipher used\n * \\param md_type     the mbedtls_md used\n * \\param pwd        the password used (may be NULL if no password is used)\n * \\param pwdlen     length of the password (may be 0)\n * \\param input      the input data\n * \\param len        data length\n * \\param output     the output buffer\n *\n * \\return           0 if successful, or a MBEDTLS_ERR_XXX code\n */\nint mbedtls_pkcs12_pbe( mbedtls_asn1_buf *pbe_params, int mode,\n                mbedtls_cipher_type_t cipher_type, mbedtls_md_type_t md_type,\n                const unsigned char *pwd,  size_t pwdlen,\n                const unsigned char *input, size_t len,\n                unsigned char *output );\n\n/**\n * \\brief            The PKCS#12 derivation function uses a password and a salt\n *                   to produce pseudo-random bits for a particular \"purpose\".\n *\n *                   Depending on the given id, this function can produce an\n *                   encryption/decryption key, an nitialization vector or an\n *                   integrity key.\n *\n * \\param data       buffer to store the derived data in\n * \\param datalen    length to fill\n * \\param pwd        password to use (may be NULL if no password is used)\n * \\param pwdlen     length of the password (may be 0)\n * \\param salt       salt buffer to use\n * \\param saltlen    length of the salt\n * \\param mbedtls_md         mbedtls_md type to use during the derivation\n * \\param id         id that describes the purpose (can be MBEDTLS_PKCS12_DERIVE_KEY,\n *                   MBEDTLS_PKCS12_DERIVE_IV or MBEDTLS_PKCS12_DERIVE_MAC_KEY)\n * \\param iterations number of iterations\n *\n * \\return          0 if successful, or a MD, BIGNUM type error.\n */\nint mbedtls_pkcs12_derivation( unsigned char *data, size_t datalen,\n                       const unsigned char *pwd, size_t pwdlen,\n                       const unsigned char *salt, size_t saltlen,\n                       mbedtls_md_type_t mbedtls_md, int id, int iterations );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* pkcs12.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/pkcs5.h",
    "content": "/**\n * \\file pkcs5.h\n *\n * \\brief PKCS#5 functions\n *\n * \\author Mathias Olsson <mathias@kompetensum.com>\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_PKCS5_H\n#define MBEDTLS_PKCS5_H\n\n#include \"asn1.h\"\n#include \"md.h\"\n\n#include <stddef.h>\n#include <stdint.h>\n\n#define MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA                  -0x2f80  /**< Bad input parameters to function. */\n#define MBEDTLS_ERR_PKCS5_INVALID_FORMAT                  -0x2f00  /**< Unexpected ASN.1 data. */\n#define MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE             -0x2e80  /**< Requested encryption or digest alg not available. */\n#define MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH               -0x2e00  /**< Given private key password does not allow for correct decryption. */\n\n#define MBEDTLS_PKCS5_DECRYPT      0\n#define MBEDTLS_PKCS5_ENCRYPT      1\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief          PKCS#5 PBES2 function\n *\n * \\param pbe_params the ASN.1 algorithm parameters\n * \\param mode       either MBEDTLS_PKCS5_DECRYPT or MBEDTLS_PKCS5_ENCRYPT\n * \\param pwd        password to use when generating key\n * \\param pwdlen     length of password\n * \\param data       data to process\n * \\param datalen    length of data\n * \\param output     output buffer\n *\n * \\returns        0 on success, or a MBEDTLS_ERR_XXX code if verification fails.\n */\nint mbedtls_pkcs5_pbes2( const mbedtls_asn1_buf *pbe_params, int mode,\n                 const unsigned char *pwd,  size_t pwdlen,\n                 const unsigned char *data, size_t datalen,\n                 unsigned char *output );\n\n/**\n * \\brief          PKCS#5 PBKDF2 using HMAC\n *\n * \\param ctx      Generic HMAC context\n * \\param password Password to use when generating key\n * \\param plen     Length of password\n * \\param salt     Salt to use when generating key\n * \\param slen     Length of salt\n * \\param iteration_count       Iteration count\n * \\param key_length            Length of generated key in bytes\n * \\param output   Generated key. Must be at least as big as key_length\n *\n * \\returns        0 on success, or a MBEDTLS_ERR_XXX code if verification fails.\n */\nint mbedtls_pkcs5_pbkdf2_hmac( mbedtls_md_context_t *ctx, const unsigned char *password,\n                       size_t plen, const unsigned char *salt, size_t slen,\n                       unsigned int iteration_count,\n                       uint32_t key_length, unsigned char *output );\n\n/**\n * \\brief          Checkup routine\n *\n * \\return         0 if successful, or 1 if the test failed\n */\nint mbedtls_pkcs5_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* pkcs5.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/platform.h",
    "content": "/**\n * \\file platform.h\n *\n * \\brief This file contains the definitions and functions of the\n *        Mbed TLS platform abstraction layer.\n *\n *        The platform abstraction layer removes the need for the library\n *        to directly link to standard C library functions or operating\n *        system services, making the library easier to port and embed.\n *        Application developers and users of the library can provide their own\n *        implementations of these functions, or implementations specific to\n *        their platform, which can be statically linked to the library or\n *        dynamically configured at runtime.\n */\n/*\n *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_PLATFORM_H\n#define MBEDTLS_PLATFORM_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_HAVE_TIME)\n#include \"platform_time.h\"\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\name SECTION: Module settings\n *\n * The configuration options you can set for this module are in this section.\n * Either change them in config.h or define them on the compiler command line.\n * \\{\n */\n\n#if !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS)\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#if !defined(MBEDTLS_PLATFORM_STD_SNPRINTF)\n#if defined(_WIN32)\n#define MBEDTLS_PLATFORM_STD_SNPRINTF   mbedtls_platform_win32_snprintf /**< The default \\c snprintf function to use.  */\n#else\n#define MBEDTLS_PLATFORM_STD_SNPRINTF   snprintf /**< The default \\c snprintf function to use.  */\n#endif\n#endif\n#if !defined(MBEDTLS_PLATFORM_STD_PRINTF)\n#define MBEDTLS_PLATFORM_STD_PRINTF   printf /**< The default \\c printf function to use. */\n#endif\n#if !defined(MBEDTLS_PLATFORM_STD_FPRINTF)\n#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< The default \\c fprintf function to use. */\n#endif\n#if !defined(MBEDTLS_PLATFORM_STD_CALLOC)\n#define MBEDTLS_PLATFORM_STD_CALLOC   calloc /**< The default \\c calloc function to use. */\n#endif\n#if !defined(MBEDTLS_PLATFORM_STD_FREE)\n#define MBEDTLS_PLATFORM_STD_FREE       free /**< The default \\c free function to use. */\n#endif\n#if !defined(MBEDTLS_PLATFORM_STD_EXIT)\n#define MBEDTLS_PLATFORM_STD_EXIT      exit /**< The default \\c exit function to use. */\n#endif\n#if !defined(MBEDTLS_PLATFORM_STD_TIME)\n#define MBEDTLS_PLATFORM_STD_TIME       time    /**< The default \\c time function to use. */\n#endif\n#if !defined(MBEDTLS_PLATFORM_STD_EXIT_SUCCESS)\n#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS  EXIT_SUCCESS /**< The default exit value to use. */\n#endif\n#if !defined(MBEDTLS_PLATFORM_STD_EXIT_FAILURE)\n#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE  EXIT_FAILURE /**< The default exit value to use. */\n#endif\n#if defined(MBEDTLS_FS_IO)\n#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ)\n#define MBEDTLS_PLATFORM_STD_NV_SEED_READ   mbedtls_platform_std_nv_seed_read\n#endif\n#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE)\n#define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE  mbedtls_platform_std_nv_seed_write\n#endif\n#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_FILE)\n#define MBEDTLS_PLATFORM_STD_NV_SEED_FILE   \"seedfile\"\n#endif\n#endif /* MBEDTLS_FS_IO */\n#else /* MBEDTLS_PLATFORM_NO_STD_FUNCTIONS */\n#if defined(MBEDTLS_PLATFORM_STD_MEM_HDR)\n#include MBEDTLS_PLATFORM_STD_MEM_HDR\n#endif\n#endif /* MBEDTLS_PLATFORM_NO_STD_FUNCTIONS */\n\n\n/* \\} name SECTION: Module settings */\n\n/*\n * The function pointers for calloc and free.\n */\n#if defined(MBEDTLS_PLATFORM_MEMORY)\n#if defined(MBEDTLS_PLATFORM_FREE_MACRO) && \\\n    defined(MBEDTLS_PLATFORM_CALLOC_MACRO)\n#define mbedtls_free       MBEDTLS_PLATFORM_FREE_MACRO\n#define mbedtls_calloc     MBEDTLS_PLATFORM_CALLOC_MACRO\n#else\n/* For size_t */\n#include <stddef.h>\nextern void *mbedtls_calloc( size_t n, size_t size );\nextern void mbedtls_free( void *ptr );\n\n/**\n * \\brief               This function dynamically sets the memory-management\n *                      functions used by the library, during runtime.\n *\n * \\param calloc_func   The \\c calloc function implementation.\n * \\param free_func     The \\c free function implementation.\n *\n * \\return              \\c 0.\n */\nint mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ),\n                              void (*free_func)( void * ) );\n#endif /* MBEDTLS_PLATFORM_FREE_MACRO && MBEDTLS_PLATFORM_CALLOC_MACRO */\n#else /* !MBEDTLS_PLATFORM_MEMORY */\n#define mbedtls_free       free\n#define mbedtls_calloc     calloc\n#endif /* MBEDTLS_PLATFORM_MEMORY && !MBEDTLS_PLATFORM_{FREE,CALLOC}_MACRO */\n\n/*\n * The function pointers for fprintf\n */\n#if defined(MBEDTLS_PLATFORM_FPRINTF_ALT)\n/* We need FILE * */\n#include <stdio.h>\nextern int (*mbedtls_fprintf)( FILE *stream, const char *format, ... );\n\n/**\n * \\brief                This function dynamically configures the fprintf\n *                       function that is called when the\n *                       mbedtls_fprintf() function is invoked by the library.\n *\n * \\param fprintf_func   The \\c fprintf function implementation.\n *\n * \\return               \\c 0.\n */\nint mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *stream, const char *,\n                                               ... ) );\n#else\n#if defined(MBEDTLS_PLATFORM_FPRINTF_MACRO)\n#define mbedtls_fprintf    MBEDTLS_PLATFORM_FPRINTF_MACRO\n#else\n#define mbedtls_fprintf    fprintf\n#endif /* MBEDTLS_PLATFORM_FPRINTF_MACRO */\n#endif /* MBEDTLS_PLATFORM_FPRINTF_ALT */\n\n/*\n * The function pointers for printf\n */\n#if defined(MBEDTLS_PLATFORM_PRINTF_ALT)\nextern int (*mbedtls_printf)( const char *format, ... );\n\n/**\n * \\brief               This function dynamically configures the snprintf\n *                      function that is called when the mbedtls_snprintf()\n *                      function is invoked by the library.\n *\n * \\param printf_func   The \\c printf function implementation.\n *\n * \\return              \\c 0 on success.\n */\nint mbedtls_platform_set_printf( int (*printf_func)( const char *, ... ) );\n#else /* !MBEDTLS_PLATFORM_PRINTF_ALT */\n#if defined(MBEDTLS_PLATFORM_PRINTF_MACRO)\n#define mbedtls_printf     MBEDTLS_PLATFORM_PRINTF_MACRO\n#else\n#define mbedtls_printf     printf\n#endif /* MBEDTLS_PLATFORM_PRINTF_MACRO */\n#endif /* MBEDTLS_PLATFORM_PRINTF_ALT */\n\n/*\n * The function pointers for snprintf\n *\n * The snprintf implementation should conform to C99:\n * - it *must* always correctly zero-terminate the buffer\n *   (except when n == 0, then it must leave the buffer untouched)\n * - however it is acceptable to return -1 instead of the required length when\n *   the destination buffer is too short.\n */\n#if defined(_WIN32)\n/* For Windows (inc. MSYS2), we provide our own fixed implementation */\nint mbedtls_platform_win32_snprintf( char *s, size_t n, const char *fmt, ... );\n#endif\n\n#if defined(MBEDTLS_PLATFORM_SNPRINTF_ALT)\nextern int (*mbedtls_snprintf)( char * s, size_t n, const char * format, ... );\n\n/**\n * \\brief                 This function allows configuring a custom\n *                        \\c snprintf function pointer.\n *\n * \\param snprintf_func   The \\c snprintf function implementation.\n *\n * \\return                \\c 0 on success.\n */\nint mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n,\n                                                 const char * format, ... ) );\n#else /* MBEDTLS_PLATFORM_SNPRINTF_ALT */\n#if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO)\n#define mbedtls_snprintf   MBEDTLS_PLATFORM_SNPRINTF_MACRO\n#else\n#define mbedtls_snprintf   MBEDTLS_PLATFORM_STD_SNPRINTF\n#endif /* MBEDTLS_PLATFORM_SNPRINTF_MACRO */\n#endif /* MBEDTLS_PLATFORM_SNPRINTF_ALT */\n\n/*\n * The function pointers for exit\n */\n#if defined(MBEDTLS_PLATFORM_EXIT_ALT)\nextern void (*mbedtls_exit)( int status );\n\n/**\n * \\brief             This function dynamically configures the exit\n *                    function that is called when the mbedtls_exit()\n *                    function is invoked by the library.\n *\n * \\param exit_func   The \\c exit function implementation.\n *\n * \\return            \\c 0 on success.\n */\nint mbedtls_platform_set_exit( void (*exit_func)( int status ) );\n#else\n#if defined(MBEDTLS_PLATFORM_EXIT_MACRO)\n#define mbedtls_exit   MBEDTLS_PLATFORM_EXIT_MACRO\n#else\n#define mbedtls_exit   exit\n#endif /* MBEDTLS_PLATFORM_EXIT_MACRO */\n#endif /* MBEDTLS_PLATFORM_EXIT_ALT */\n\n/*\n * The default exit values\n */\n#if defined(MBEDTLS_PLATFORM_STD_EXIT_SUCCESS)\n#define MBEDTLS_EXIT_SUCCESS MBEDTLS_PLATFORM_STD_EXIT_SUCCESS\n#else\n#define MBEDTLS_EXIT_SUCCESS 0\n#endif\n#if defined(MBEDTLS_PLATFORM_STD_EXIT_FAILURE)\n#define MBEDTLS_EXIT_FAILURE MBEDTLS_PLATFORM_STD_EXIT_FAILURE\n#else\n#define MBEDTLS_EXIT_FAILURE 1\n#endif\n\n/*\n * The function pointers for reading from and writing a seed file to\n * Non-Volatile storage (NV) in a platform-independent way\n *\n * Only enabled when the NV seed entropy source is enabled\n */\n#if defined(MBEDTLS_ENTROPY_NV_SEED)\n#if !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS) && defined(MBEDTLS_FS_IO)\n/* Internal standard platform definitions */\nint mbedtls_platform_std_nv_seed_read( unsigned char *buf, size_t buf_len );\nint mbedtls_platform_std_nv_seed_write( unsigned char *buf, size_t buf_len );\n#endif\n\n#if defined(MBEDTLS_PLATFORM_NV_SEED_ALT)\nextern int (*mbedtls_nv_seed_read)( unsigned char *buf, size_t buf_len );\nextern int (*mbedtls_nv_seed_write)( unsigned char *buf, size_t buf_len );\n\n/**\n * \\brief   This function allows configuring custom seed file writing and\n *          reading functions.\n *\n * \\param   nv_seed_read_func   The seed reading function implementation.\n * \\param   nv_seed_write_func  The seed writing function implementation.\n *\n * \\return  \\c 0 on success.\n */\nint mbedtls_platform_set_nv_seed(\n            int (*nv_seed_read_func)( unsigned char *buf, size_t buf_len ),\n            int (*nv_seed_write_func)( unsigned char *buf, size_t buf_len )\n            );\n#else\n#if defined(MBEDTLS_PLATFORM_NV_SEED_READ_MACRO) && \\\n    defined(MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO)\n#define mbedtls_nv_seed_read    MBEDTLS_PLATFORM_NV_SEED_READ_MACRO\n#define mbedtls_nv_seed_write   MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO\n#else\n#define mbedtls_nv_seed_read    mbedtls_platform_std_nv_seed_read\n#define mbedtls_nv_seed_write   mbedtls_platform_std_nv_seed_write\n#endif\n#endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */\n#endif /* MBEDTLS_ENTROPY_NV_SEED */\n\n#if !defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT)\n\n/**\n * \\brief   The platform context structure.\n *\n * \\note    This structure may be used to assist platform-specific\n *          setup or teardown operations.\n */\ntypedef struct {\n    char dummy; /**< A placeholder member, as empty structs are not portable. */\n}\nmbedtls_platform_context;\n\n#else\n#include \"platform_alt.h\"\n#endif /* !MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */\n\n/**\n * \\brief   This function performs any platform-specific initialization\n *          operations.\n *\n * \\note    This function should be called before any other library functions.\n *\n *          Its implementation is platform-specific, and unless\n *          platform-specific code is provided, it does nothing.\n *\n * \\note    The usage and necessity of this function is dependent on the platform.\n *\n * \\param   ctx     The platform context.\n *\n * \\return  \\c 0 on success.\n */\nint mbedtls_platform_setup( mbedtls_platform_context *ctx );\n/**\n * \\brief   This function performs any platform teardown operations.\n *\n * \\note    This function should be called after every other Mbed TLS module\n *          has been correctly freed using the appropriate free function.\n *\n *          Its implementation is platform-specific, and unless\n *          platform-specific code is provided, it does nothing.\n *\n * \\note    The usage and necessity of this function is dependent on the platform.\n *\n * \\param   ctx     The platform context.\n *\n */\nvoid mbedtls_platform_teardown( mbedtls_platform_context *ctx );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* platform.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/platform_time.h",
    "content": "/**\n * \\file platform_time.h\n *\n * \\brief mbed TLS Platform time abstraction\n */\n/*\n *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_PLATFORM_TIME_H\n#define MBEDTLS_PLATFORM_TIME_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\name SECTION: Module settings\n *\n * The configuration options you can set for this module are in this section.\n * Either change them in config.h or define them on the compiler command line.\n * \\{\n */\n\n/*\n * The time_t datatype\n */\n#if defined(MBEDTLS_PLATFORM_TIME_TYPE_MACRO)\ntypedef MBEDTLS_PLATFORM_TIME_TYPE_MACRO mbedtls_time_t;\n#else\n/* For time_t */\n#include <time.h>\ntypedef time_t mbedtls_time_t;\n#endif /* MBEDTLS_PLATFORM_TIME_TYPE_MACRO */\n\n/*\n * The function pointers for time\n */\n#if defined(MBEDTLS_PLATFORM_TIME_ALT)\nextern mbedtls_time_t (*mbedtls_time)( mbedtls_time_t* time );\n\n/**\n * \\brief   Set your own time function pointer\n *\n * \\param   time_func   the time function implementation\n *\n * \\return              0\n */\nint mbedtls_platform_set_time( mbedtls_time_t (*time_func)( mbedtls_time_t* time ) );\n#else\n#if defined(MBEDTLS_PLATFORM_TIME_MACRO)\n#define mbedtls_time    MBEDTLS_PLATFORM_TIME_MACRO\n#else\n#define mbedtls_time   time\n#endif /* MBEDTLS_PLATFORM_TIME_MACRO */\n#endif /* MBEDTLS_PLATFORM_TIME_ALT */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* platform_time.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/platform_util.h",
    "content": "/**\n * \\file platform_util.h\n *\n * \\brief Common and shared functions used by multiple modules in the Mbed TLS\n *        library.\n */\n/*\n *  Copyright (C) 2018, Arm Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_PLATFORM_UTIL_H\n#define MBEDTLS_PLATFORM_UTIL_H\n\n#include <stddef.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief       Securely zeroize a buffer\n *\n *              The function is meant to wipe the data contained in a buffer so\n *              that it can no longer be recovered even if the program memory\n *              is later compromised. Call this function on sensitive data\n *              stored on the stack before returning from a function, and on\n *              sensitive data stored on the heap before freeing the heap\n *              object.\n *\n *              It is extremely difficult to guarantee that calls to\n *              mbedtls_platform_zeroize() are not removed by aggressive\n *              compiler optimizations in a portable way. For this reason, Mbed\n *              TLS provides the configuration option\n *              MBEDTLS_PLATFORM_ZEROIZE_ALT, which allows users to configure\n *              mbedtls_platform_zeroize() to use a suitable implementation for\n *              their platform and needs\n *\n * \\param buf   Buffer to be zeroized\n * \\param len   Length of the buffer in bytes\n *\n */\nvoid mbedtls_platform_zeroize( void *buf, size_t len );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* MBEDTLS_PLATFORM_UTIL_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/poly1305.h",
    "content": "/**\n * \\file poly1305.h\n *\n * \\brief   This file contains Poly1305 definitions and functions.\n *\n *          Poly1305 is a one-time message authenticator that can be used to\n *          authenticate messages. Poly1305-AES was created by Daniel\n *          Bernstein https://cr.yp.to/mac/poly1305-20050329.pdf The generic\n *          Poly1305 algorithm (not tied to AES) was also standardized in RFC\n *          7539.\n *\n * \\author Daniel King <damaki.gh@gmail.com>\n */\n\n/*  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved.\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n\n#ifndef MBEDTLS_POLY1305_H\n#define MBEDTLS_POLY1305_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stdint.h>\n#include <stddef.h>\n\n#define MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA         -0x0057 /**< Invalid input parameter(s). */\n#define MBEDTLS_ERR_POLY1305_FEATURE_UNAVAILABLE    -0x0059 /**< Feature not available. For example, s part of the API is not implemented. */\n#define MBEDTLS_ERR_POLY1305_HW_ACCEL_FAILED        -0x005B  /**< Poly1305 hardware accelerator failed. */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_POLY1305_ALT)\n\ntypedef struct\n{\n    uint32_t r[4];      /** The value for 'r' (low 128 bits of the key). */\n    uint32_t s[4];      /** The value for 's' (high 128 bits of the key). */\n    uint32_t acc[5];    /** The accumulator number. */\n    uint8_t queue[16];  /** The current partial block of data. */\n    size_t queue_len;   /** The number of bytes stored in 'queue'. */\n}\nmbedtls_poly1305_context;\n\n#else  /* MBEDTLS_POLY1305_ALT */\n#include \"poly1305_alt.h\"\n#endif /* MBEDTLS_POLY1305_ALT */\n\n/**\n * \\brief           This function initializes the specified Poly1305 context.\n *\n *                  It must be the first API called before using\n *                  the context.\n *\n *                  It is usually followed by a call to\n *                  \\c mbedtls_poly1305_starts(), then one or more calls to\n *                  \\c mbedtls_poly1305_update(), then one call to\n *                  \\c mbedtls_poly1305_finish(), then finally\n *                  \\c mbedtls_poly1305_free().\n *\n * \\param ctx       The Poly1305 context to initialize.\n */\nvoid mbedtls_poly1305_init( mbedtls_poly1305_context *ctx );\n\n/**\n * \\brief           This function releases and clears the specified Poly1305 context.\n *\n * \\param ctx       The Poly1305 context to clear.\n */\nvoid mbedtls_poly1305_free( mbedtls_poly1305_context *ctx );\n\n/**\n * \\brief           This function sets the one-time authentication key.\n *\n * \\warning         The key must be unique and unpredictable for each\n *                  invocation of Poly1305.\n *\n * \\param ctx       The Poly1305 context to which the key should be bound.\n * \\param key       The buffer containing the 256-bit key.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA\n *                  if ctx or key are NULL.\n */\nint mbedtls_poly1305_starts( mbedtls_poly1305_context *ctx,\n                             const unsigned char key[32] );\n\n/**\n * \\brief           This functions feeds an input buffer into an ongoing\n *                  Poly1305 computation.\n *\n *                  It is called between \\c mbedtls_cipher_poly1305_starts() and\n *                  \\c mbedtls_cipher_poly1305_finish().\n *                  It can be called repeatedly to process a stream of data.\n *\n * \\param ctx       The Poly1305 context to use for the Poly1305 operation.\n * \\param ilen      The length of the input data (in bytes). Any value is accepted.\n * \\param input     The buffer holding the input data.\n *                  This pointer can be NULL if ilen == 0.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA\n *                  if ctx or input are NULL.\n */\nint mbedtls_poly1305_update( mbedtls_poly1305_context *ctx,\n                             const unsigned char *input,\n                             size_t ilen );\n\n/**\n * \\brief           This function generates the Poly1305 Message\n *                  Authentication Code (MAC).\n *\n * \\param ctx       The Poly1305 context to use for the Poly1305 operation.\n * \\param mac       The buffer to where the MAC is written. Must be big enough\n *                  to hold the 16-byte MAC.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA\n *                  if ctx or mac are NULL.\n */\nint mbedtls_poly1305_finish( mbedtls_poly1305_context *ctx,\n                             unsigned char mac[16] );\n\n/**\n * \\brief           This function calculates the Poly1305 MAC of the input\n *                  buffer with the provided key.\n *\n * \\warning         The key must be unique and unpredictable for each\n *                  invocation of Poly1305.\n *\n * \\param key       The buffer containing the 256-bit key.\n * \\param ilen      The length of the input data (in bytes). Any value is accepted.\n * \\param input     The buffer holding the input data.\n *                  This pointer can be NULL if ilen == 0.\n * \\param mac       The buffer to where the MAC is written. Must be big enough\n *                  to hold the 16-byte MAC.\n *\n * \\return          \\c 0 on success.\n * \\return          #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA\n *                  if key, input, or mac are NULL.\n */\nint mbedtls_poly1305_mac( const unsigned char key[32],\n                          const unsigned char *input,\n                          size_t ilen,\n                          unsigned char mac[16] );\n\n#if defined(MBEDTLS_SELF_TEST)\n/**\n * \\brief           The Poly1305 checkup routine.\n *\n * \\return          \\c 0 on success.\n * \\return          \\c 1 on failure.\n */\nint mbedtls_poly1305_self_test( int verbose );\n#endif /* MBEDTLS_SELF_TEST */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* MBEDTLS_POLY1305_H */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/ripemd160.h",
    "content": "/**\n * \\file ripemd160.h\n *\n * \\brief RIPE MD-160 message digest\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_RIPEMD160_H\n#define MBEDTLS_RIPEMD160_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n#include <stdint.h>\n\n#define MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED             -0x0031  /**< RIPEMD160 hardware accelerator failed */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_RIPEMD160_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief          RIPEMD-160 context structure\n */\ntypedef struct\n{\n    uint32_t total[2];          /*!< number of bytes processed  */\n    uint32_t state[5];          /*!< intermediate digest state  */\n    unsigned char buffer[64];   /*!< data block being processed */\n}\nmbedtls_ripemd160_context;\n\n#else  /* MBEDTLS_RIPEMD160_ALT */\n#include \"ripemd160.h\"\n#endif /* MBEDTLS_RIPEMD160_ALT */\n\n/**\n * \\brief          Initialize RIPEMD-160 context\n *\n * \\param ctx      RIPEMD-160 context to be initialized\n */\nvoid mbedtls_ripemd160_init( mbedtls_ripemd160_context *ctx );\n\n/**\n * \\brief          Clear RIPEMD-160 context\n *\n * \\param ctx      RIPEMD-160 context to be cleared\n */\nvoid mbedtls_ripemd160_free( mbedtls_ripemd160_context *ctx );\n\n/**\n * \\brief          Clone (the state of) an RIPEMD-160 context\n *\n * \\param dst      The destination context\n * \\param src      The context to be cloned\n */\nvoid mbedtls_ripemd160_clone( mbedtls_ripemd160_context *dst,\n                        const mbedtls_ripemd160_context *src );\n\n/**\n * \\brief          RIPEMD-160 context setup\n *\n * \\param ctx      context to be initialized\n *\n * \\return         0 if successful\n */\nint mbedtls_ripemd160_starts_ret( mbedtls_ripemd160_context *ctx );\n\n/**\n * \\brief          RIPEMD-160 process buffer\n *\n * \\param ctx      RIPEMD-160 context\n * \\param input    buffer holding the data\n * \\param ilen     length of the input data\n *\n * \\return         0 if successful\n */\nint mbedtls_ripemd160_update_ret( mbedtls_ripemd160_context *ctx,\n                                  const unsigned char *input,\n                                  size_t ilen );\n\n/**\n * \\brief          RIPEMD-160 final digest\n *\n * \\param ctx      RIPEMD-160 context\n * \\param output   RIPEMD-160 checksum result\n *\n * \\return         0 if successful\n */\nint mbedtls_ripemd160_finish_ret( mbedtls_ripemd160_context *ctx,\n                                  unsigned char output[20] );\n\n/**\n * \\brief          RIPEMD-160 process data block (internal use only)\n *\n * \\param ctx      RIPEMD-160 context\n * \\param data     buffer holding one block of data\n *\n * \\return         0 if successful\n */\nint mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx,\n                                        const unsigned char data[64] );\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED      __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n/**\n * \\brief          RIPEMD-160 context setup\n *\n * \\deprecated     Superseded by mbedtls_ripemd160_starts_ret() in 2.7.0\n *\n * \\param ctx      context to be initialized\n */\nMBEDTLS_DEPRECATED void mbedtls_ripemd160_starts(\n                                            mbedtls_ripemd160_context *ctx );\n\n/**\n * \\brief          RIPEMD-160 process buffer\n *\n * \\deprecated     Superseded by mbedtls_ripemd160_update_ret() in 2.7.0\n *\n * \\param ctx      RIPEMD-160 context\n * \\param input    buffer holding the data\n * \\param ilen     length of the input data\n */\nMBEDTLS_DEPRECATED void mbedtls_ripemd160_update(\n                                                mbedtls_ripemd160_context *ctx,\n                                                const unsigned char *input,\n                                                size_t ilen );\n\n/**\n * \\brief          RIPEMD-160 final digest\n *\n * \\deprecated     Superseded by mbedtls_ripemd160_finish_ret() in 2.7.0\n *\n * \\param ctx      RIPEMD-160 context\n * \\param output   RIPEMD-160 checksum result\n */\nMBEDTLS_DEPRECATED void mbedtls_ripemd160_finish(\n                                                mbedtls_ripemd160_context *ctx,\n                                                unsigned char output[20] );\n\n/**\n * \\brief          RIPEMD-160 process data block (internal use only)\n *\n * \\deprecated     Superseded by mbedtls_internal_ripemd160_process() in 2.7.0\n *\n * \\param ctx      RIPEMD-160 context\n * \\param data     buffer holding one block of data\n */\nMBEDTLS_DEPRECATED void mbedtls_ripemd160_process(\n                                            mbedtls_ripemd160_context *ctx,\n                                            const unsigned char data[64] );\n\n#undef MBEDTLS_DEPRECATED\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n\n/**\n * \\brief          Output = RIPEMD-160( input buffer )\n *\n * \\param input    buffer holding the data\n * \\param ilen     length of the input data\n * \\param output   RIPEMD-160 checksum result\n *\n * \\return         0 if successful\n */\nint mbedtls_ripemd160_ret( const unsigned char *input,\n                           size_t ilen,\n                           unsigned char output[20] );\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED      __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n/**\n * \\brief          Output = RIPEMD-160( input buffer )\n *\n * \\deprecated     Superseded by mbedtls_ripemd160_ret() in 2.7.0\n *\n * \\param input    buffer holding the data\n * \\param ilen     length of the input data\n * \\param output   RIPEMD-160 checksum result\n */\nMBEDTLS_DEPRECATED void mbedtls_ripemd160( const unsigned char *input,\n                                           size_t ilen,\n                                           unsigned char output[20] );\n\n#undef MBEDTLS_DEPRECATED\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n\n/**\n * \\brief          Checkup routine\n *\n * \\return         0 if successful, or 1 if the test failed\n */\nint mbedtls_ripemd160_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* mbedtls_ripemd160.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/rsa.h",
    "content": "/**\n * \\file rsa.h\n *\n * \\brief This file provides an API for the RSA public-key cryptosystem.\n *\n * The RSA public-key cryptosystem is defined in <em>Public-Key\n * Cryptography Standards (PKCS) #1 v1.5: RSA Encryption</em>\n * and <em>Public-Key Cryptography Standards (PKCS) #1 v2.1:\n * RSA Cryptography Specifications</em>.\n *\n */\n/*\n *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_RSA_H\n#define MBEDTLS_RSA_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include \"bignum.h\"\n#include \"md.h\"\n\n#if defined(MBEDTLS_THREADING_C)\n#include \"threading.h\"\n#endif\n\n/*\n * RSA Error codes\n */\n#define MBEDTLS_ERR_RSA_BAD_INPUT_DATA                    -0x4080  /**< Bad input parameters to function. */\n#define MBEDTLS_ERR_RSA_INVALID_PADDING                   -0x4100  /**< Input data contains invalid padding and is rejected. */\n#define MBEDTLS_ERR_RSA_KEY_GEN_FAILED                    -0x4180  /**< Something failed during generation of a key. */\n#define MBEDTLS_ERR_RSA_KEY_CHECK_FAILED                  -0x4200  /**< Key failed to pass the validity check of the library. */\n#define MBEDTLS_ERR_RSA_PUBLIC_FAILED                     -0x4280  /**< The public key operation failed. */\n#define MBEDTLS_ERR_RSA_PRIVATE_FAILED                    -0x4300  /**< The private key operation failed. */\n#define MBEDTLS_ERR_RSA_VERIFY_FAILED                     -0x4380  /**< The PKCS#1 verification failed. */\n#define MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE                  -0x4400  /**< The output buffer for decryption is not large enough. */\n#define MBEDTLS_ERR_RSA_RNG_FAILED                        -0x4480  /**< The random generator failed to generate non-zeros. */\n#define MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION             -0x4500  /**< The implementation does not offer the requested operation, for example, because of security violations or lack of functionality. */\n#define MBEDTLS_ERR_RSA_HW_ACCEL_FAILED                   -0x4580  /**< RSA hardware accelerator failed. */\n\n/*\n * RSA constants\n */\n#define MBEDTLS_RSA_PUBLIC      0 /**< Request private key operation. */\n#define MBEDTLS_RSA_PRIVATE     1 /**< Request public key operation. */\n\n#define MBEDTLS_RSA_PKCS_V15    0 /**< Use PKCS#1 v1.5 encoding. */\n#define MBEDTLS_RSA_PKCS_V21    1 /**< Use PKCS#1 v2.1 encoding. */\n\n#define MBEDTLS_RSA_SIGN        1 /**< Identifier for RSA signature operations. */\n#define MBEDTLS_RSA_CRYPT       2 /**< Identifier for RSA encryption and decryption operations. */\n\n#define MBEDTLS_RSA_SALT_LEN_ANY    -1\n\n/*\n * The above constants may be used even if the RSA module is compile out,\n * eg for alternative (PKCS#11) RSA implemenations in the PK layers.\n */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_RSA_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief   The RSA context structure.\n *\n * \\note    Direct manipulation of the members of this structure\n *          is deprecated. All manipulation should instead be done through\n *          the public interface functions.\n */\ntypedef struct\n{\n    int ver;                    /*!<  Always 0.*/\n    size_t len;                 /*!<  The size of \\p N in Bytes. */\n\n    mbedtls_mpi N;              /*!<  The public modulus. */\n    mbedtls_mpi E;              /*!<  The public exponent. */\n\n    mbedtls_mpi D;              /*!<  The private exponent. */\n    mbedtls_mpi P;              /*!<  The first prime factor. */\n    mbedtls_mpi Q;              /*!<  The second prime factor. */\n\n    mbedtls_mpi DP;             /*!<  <code>D % (P - 1)</code>. */\n    mbedtls_mpi DQ;             /*!<  <code>D % (Q - 1)</code>. */\n    mbedtls_mpi QP;             /*!<  <code>1 / (Q % P)</code>. */\n\n    mbedtls_mpi RN;             /*!<  cached <code>R^2 mod N</code>. */\n\n    mbedtls_mpi RP;             /*!<  cached <code>R^2 mod P</code>. */\n    mbedtls_mpi RQ;             /*!<  cached <code>R^2 mod Q</code>. */\n\n    mbedtls_mpi Vi;             /*!<  The cached blinding value. */\n    mbedtls_mpi Vf;             /*!<  The cached un-blinding value. */\n\n    int padding;                /*!< Selects padding mode:\n                                     #MBEDTLS_RSA_PKCS_V15 for 1.5 padding and\n                                     #MBEDTLS_RSA_PKCS_V21 for OAEP or PSS. */\n    int hash_id;                /*!< Hash identifier of mbedtls_md_type_t type,\n                                     as specified in md.h for use in the MGF\n                                     mask generating function used in the\n                                     EME-OAEP and EMSA-PSS encodings. */\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_threading_mutex_t mutex;    /*!<  Thread-safety mutex. */\n#endif\n}\nmbedtls_rsa_context;\n\n#else  /* MBEDTLS_RSA_ALT */\n#include \"rsa_alt.h\"\n#endif /* MBEDTLS_RSA_ALT */\n\n/**\n * \\brief          This function initializes an RSA context.\n *\n * \\note           Set padding to #MBEDTLS_RSA_PKCS_V21 for the RSAES-OAEP\n *                 encryption scheme and the RSASSA-PSS signature scheme.\n *\n * \\note           The \\p hash_id parameter is ignored when using\n *                 #MBEDTLS_RSA_PKCS_V15 padding.\n *\n * \\note           The choice of padding mode is strictly enforced for private key\n *                 operations, since there might be security concerns in\n *                 mixing padding modes. For public key operations it is\n *                 a default value, which can be overriden by calling specific\n *                 \\c rsa_rsaes_xxx or \\c rsa_rsassa_xxx functions.\n *\n * \\note           The hash selected in \\p hash_id is always used for OEAP\n *                 encryption. For PSS signatures, it is always used for\n *                 making signatures, but can be overriden for verifying them.\n *                 If set to #MBEDTLS_MD_NONE, it is always overriden.\n *\n * \\param ctx      The RSA context to initialize.\n * \\param padding  Selects padding mode: #MBEDTLS_RSA_PKCS_V15 or\n *                 #MBEDTLS_RSA_PKCS_V21.\n * \\param hash_id  The hash identifier of #mbedtls_md_type_t type, if\n *                 \\p padding is #MBEDTLS_RSA_PKCS_V21.\n */\nvoid mbedtls_rsa_init( mbedtls_rsa_context *ctx,\n                       int padding,\n                       int hash_id);\n\n/**\n * \\brief          This function imports a set of core parameters into an\n *                 RSA context.\n *\n * \\note           This function can be called multiple times for successive\n *                 imports, if the parameters are not simultaneously present.\n *\n *                 Any sequence of calls to this function should be followed\n *                 by a call to mbedtls_rsa_complete(), which checks and\n *                 completes the provided information to a ready-for-use\n *                 public or private RSA key.\n *\n * \\note           See mbedtls_rsa_complete() for more information on which\n *                 parameters are necessary to set up a private or public\n *                 RSA key.\n *\n * \\note           The imported parameters are copied and need not be preserved\n *                 for the lifetime of the RSA context being set up.\n *\n * \\param ctx      The initialized RSA context to store the parameters in.\n * \\param N        The RSA modulus, or NULL.\n * \\param P        The first prime factor of \\p N, or NULL.\n * \\param Q        The second prime factor of \\p N, or NULL.\n * \\param D        The private exponent, or NULL.\n * \\param E        The public exponent, or NULL.\n *\n * \\return         \\c 0 on success.\n * \\return         A non-zero error code on failure.\n */\nint mbedtls_rsa_import( mbedtls_rsa_context *ctx,\n                        const mbedtls_mpi *N,\n                        const mbedtls_mpi *P, const mbedtls_mpi *Q,\n                        const mbedtls_mpi *D, const mbedtls_mpi *E );\n\n/**\n * \\brief          This function imports core RSA parameters, in raw big-endian\n *                 binary format, into an RSA context.\n *\n * \\note           This function can be called multiple times for successive\n *                 imports, if the parameters are not simultaneously present.\n *\n *                 Any sequence of calls to this function should be followed\n *                 by a call to mbedtls_rsa_complete(), which checks and\n *                 completes the provided information to a ready-for-use\n *                 public or private RSA key.\n *\n * \\note           See mbedtls_rsa_complete() for more information on which\n *                 parameters are necessary to set up a private or public\n *                 RSA key.\n *\n * \\note           The imported parameters are copied and need not be preserved\n *                 for the lifetime of the RSA context being set up.\n *\n * \\param ctx      The initialized RSA context to store the parameters in.\n * \\param N        The RSA modulus, or NULL.\n * \\param N_len    The Byte length of \\p N, ignored if \\p N == NULL.\n * \\param P        The first prime factor of \\p N, or NULL.\n * \\param P_len    The Byte length of \\p P, ignored if \\p P == NULL.\n * \\param Q        The second prime factor of \\p N, or NULL.\n * \\param Q_len    The Byte length of \\p Q, ignored if \\p Q == NULL.\n * \\param D        The private exponent, or NULL.\n * \\param D_len    The Byte length of \\p D, ignored if \\p D == NULL.\n * \\param E        The public exponent, or NULL.\n * \\param E_len    The Byte length of \\p E, ignored if \\p E == NULL.\n *\n * \\return         \\c 0 on success.\n * \\return         A non-zero error code on failure.\n */\nint mbedtls_rsa_import_raw( mbedtls_rsa_context *ctx,\n                            unsigned char const *N, size_t N_len,\n                            unsigned char const *P, size_t P_len,\n                            unsigned char const *Q, size_t Q_len,\n                            unsigned char const *D, size_t D_len,\n                            unsigned char const *E, size_t E_len );\n\n/**\n * \\brief          This function completes an RSA context from\n *                 a set of imported core parameters.\n *\n *                 To setup an RSA public key, precisely \\p N and \\p E\n *                 must have been imported.\n *\n *                 To setup an RSA private key, sufficient information must\n *                 be present for the other parameters to be derivable.\n *\n *                 The default implementation supports the following:\n *                 <ul><li>Derive \\p P, \\p Q from \\p N, \\p D, \\p E.</li>\n *                 <li>Derive \\p N, \\p D from \\p P, \\p Q, \\p E.</li></ul>\n *                 Alternative implementations need not support these.\n *\n *                 If this function runs successfully, it guarantees that\n *                 the RSA context can be used for RSA operations without\n *                 the risk of failure or crash.\n *\n * \\warning        This function need not perform consistency checks\n *                 for the imported parameters. In particular, parameters that\n *                 are not needed by the implementation might be silently\n *                 discarded and left unchecked. To check the consistency\n *                 of the key material, see mbedtls_rsa_check_privkey().\n *\n * \\param ctx      The initialized RSA context holding imported parameters.\n *\n * \\return         \\c 0 on success.\n * \\return         #MBEDTLS_ERR_RSA_BAD_INPUT_DATA if the attempted derivations\n *                 failed.\n *\n */\nint mbedtls_rsa_complete( mbedtls_rsa_context *ctx );\n\n/**\n * \\brief          This function exports the core parameters of an RSA key.\n *\n *                 If this function runs successfully, the non-NULL buffers\n *                 pointed to by \\p N, \\p P, \\p Q, \\p D, and \\p E are fully\n *                 written, with additional unused space filled leading by\n *                 zero Bytes.\n *\n *                 Possible reasons for returning\n *                 #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION:<ul>\n *                 <li>An alternative RSA implementation is in use, which\n *                 stores the key externally, and either cannot or should\n *                 not export it into RAM.</li>\n *                 <li>A SW or HW implementation might not support a certain\n *                 deduction. For example, \\p P, \\p Q from \\p N, \\p D,\n *                 and \\p E if the former are not part of the\n *                 implementation.</li></ul>\n *\n *                 If the function fails due to an unsupported operation,\n *                 the RSA context stays intact and remains usable.\n *\n * \\param ctx      The initialized RSA context.\n * \\param N        The MPI to hold the RSA modulus, or NULL.\n * \\param P        The MPI to hold the first prime factor of \\p N, or NULL.\n * \\param Q        The MPI to hold the second prime factor of \\p N, or NULL.\n * \\param D        The MPI to hold the private exponent, or NULL.\n * \\param E        The MPI to hold the public exponent, or NULL.\n *\n * \\return         \\c 0 on success.\n * \\return         #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION if exporting the\n *                 requested parameters cannot be done due to missing\n *                 functionality or because of security policies.\n * \\return         A non-zero return code on any other failure.\n *\n */\nint mbedtls_rsa_export( const mbedtls_rsa_context *ctx,\n                        mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q,\n                        mbedtls_mpi *D, mbedtls_mpi *E );\n\n/**\n * \\brief          This function exports core parameters of an RSA key\n *                 in raw big-endian binary format.\n *\n *                 If this function runs successfully, the non-NULL buffers\n *                 pointed to by \\p N, \\p P, \\p Q, \\p D, and \\p E are fully\n *                 written, with additional unused space filled leading by\n *                 zero Bytes.\n *\n *                 Possible reasons for returning\n *                 #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION:<ul>\n *                 <li>An alternative RSA implementation is in use, which\n *                 stores the key externally, and either cannot or should\n *                 not export it into RAM.</li>\n *                 <li>A SW or HW implementation might not support a certain\n *                 deduction. For example, \\p P, \\p Q from \\p N, \\p D,\n *                 and \\p E if the former are not part of the\n *                 implementation.</li></ul>\n *                 If the function fails due to an unsupported operation,\n *                 the RSA context stays intact and remains usable.\n *\n * \\note           The length parameters are ignored if the corresponding\n *                 buffer pointers are NULL.\n *\n * \\param ctx      The initialized RSA context.\n * \\param N        The Byte array to store the RSA modulus, or NULL.\n * \\param N_len    The size of the buffer for the modulus.\n * \\param P        The Byte array to hold the first prime factor of \\p N, or\n *                 NULL.\n * \\param P_len    The size of the buffer for the first prime factor.\n * \\param Q        The Byte array to hold the second prime factor of \\p N, or\n *                 NULL.\n * \\param Q_len    The size of the buffer for the second prime factor.\n * \\param D        The Byte array to hold the private exponent, or NULL.\n * \\param D_len    The size of the buffer for the private exponent.\n * \\param E        The Byte array to hold the public exponent, or NULL.\n * \\param E_len    The size of the buffer for the public exponent.\n *\n * \\return         \\c 0 on success.\n * \\return         #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION if exporting the\n *                 requested parameters cannot be done due to missing\n *                 functionality or because of security policies.\n * \\return         A non-zero return code on any other failure.\n */\nint mbedtls_rsa_export_raw( const mbedtls_rsa_context *ctx,\n                            unsigned char *N, size_t N_len,\n                            unsigned char *P, size_t P_len,\n                            unsigned char *Q, size_t Q_len,\n                            unsigned char *D, size_t D_len,\n                            unsigned char *E, size_t E_len );\n\n/**\n * \\brief          This function exports CRT parameters of a private RSA key.\n *\n * \\note           Alternative RSA implementations not using CRT-parameters\n *                 internally can implement this function based on\n *                 mbedtls_rsa_deduce_opt().\n *\n * \\param ctx      The initialized RSA context.\n * \\param DP       The MPI to hold D modulo P-1, or NULL.\n * \\param DQ       The MPI to hold D modulo Q-1, or NULL.\n * \\param QP       The MPI to hold modular inverse of Q modulo P, or NULL.\n *\n * \\return         \\c 0 on success.\n * \\return         A non-zero error code on failure.\n *\n */\nint mbedtls_rsa_export_crt( const mbedtls_rsa_context *ctx,\n                            mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP );\n\n/**\n * \\brief          This function sets padding for an already initialized RSA\n *                 context. See mbedtls_rsa_init() for details.\n *\n * \\param ctx      The RSA context to be set.\n * \\param padding  Selects padding mode: #MBEDTLS_RSA_PKCS_V15 or\n *                 #MBEDTLS_RSA_PKCS_V21.\n * \\param hash_id  The #MBEDTLS_RSA_PKCS_V21 hash identifier.\n */\nvoid mbedtls_rsa_set_padding( mbedtls_rsa_context *ctx, int padding,\n                              int hash_id);\n\n/**\n * \\brief          This function retrieves the length of RSA modulus in Bytes.\n *\n * \\param ctx      The initialized RSA context.\n *\n * \\return         The length of the RSA modulus in Bytes.\n *\n */\nsize_t mbedtls_rsa_get_len( const mbedtls_rsa_context *ctx );\n\n/**\n * \\brief          This function generates an RSA keypair.\n *\n * \\note           mbedtls_rsa_init() must be called before this function,\n *                 to set up the RSA context.\n *\n * \\param ctx      The RSA context used to hold the key.\n * \\param f_rng    The RNG function.\n * \\param p_rng    The RNG context.\n * \\param nbits    The size of the public key in bits.\n * \\param exponent The public exponent. For example, 65537.\n *\n * \\return         \\c 0 on success.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n */\nint mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx,\n                         int (*f_rng)(void *, unsigned char *, size_t),\n                         void *p_rng,\n                         unsigned int nbits, int exponent );\n\n/**\n * \\brief          This function checks if a context contains at least an RSA\n *                 public key.\n *\n *                 If the function runs successfully, it is guaranteed that\n *                 enough information is present to perform an RSA public key\n *                 operation using mbedtls_rsa_public().\n *\n * \\param ctx      The RSA context to check.\n *\n * \\return         \\c 0 on success.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n *\n */\nint mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx );\n\n/**\n * \\brief      This function checks if a context contains an RSA private key\n *             and perform basic consistency checks.\n *\n * \\note       The consistency checks performed by this function not only\n *             ensure that mbedtls_rsa_private() can be called successfully\n *             on the given context, but that the various parameters are\n *             mutually consistent with high probability, in the sense that\n *             mbedtls_rsa_public() and mbedtls_rsa_private() are inverses.\n *\n * \\warning    This function should catch accidental misconfigurations\n *             like swapping of parameters, but it cannot establish full\n *             trust in neither the quality nor the consistency of the key\n *             material that was used to setup the given RSA context:\n *             <ul><li>Consistency: Imported parameters that are irrelevant\n *             for the implementation might be silently dropped. If dropped,\n *             the current function does not have access to them,\n *             and therefore cannot check them. See mbedtls_rsa_complete().\n *             If you want to check the consistency of the entire\n *             content of an PKCS1-encoded RSA private key, for example, you\n *             should use mbedtls_rsa_validate_params() before setting\n *             up the RSA context.\n *             Additionally, if the implementation performs empirical checks,\n *             these checks substantiate but do not guarantee consistency.</li>\n *             <li>Quality: This function is not expected to perform\n *             extended quality assessments like checking that the prime\n *             factors are safe. Additionally, it is the responsibility of the\n *             user to ensure the trustworthiness of the source of his RSA\n *             parameters, which goes beyond what is effectively checkable\n *             by the library.</li></ul>\n *\n * \\param ctx  The RSA context to check.\n *\n * \\return     \\c 0 on success.\n * \\return     An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n */\nint mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx );\n\n/**\n * \\brief          This function checks a public-private RSA key pair.\n *\n *                 It checks each of the contexts, and makes sure they match.\n *\n * \\param pub      The RSA context holding the public key.\n * \\param prv      The RSA context holding the private key.\n *\n * \\return         \\c 0 on success.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n */\nint mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub,\n                                const mbedtls_rsa_context *prv );\n\n/**\n * \\brief          This function performs an RSA public key operation.\n *\n * \\note           This function does not handle message padding.\n *\n * \\note           Make sure to set \\p input[0] = 0 or ensure that\n *                 input is smaller than \\p N.\n *\n * \\note           The input and output buffers must be large\n *                 enough. For example, 128 Bytes if RSA-1024 is used.\n *\n * \\param ctx      The RSA context.\n * \\param input    The input buffer.\n * \\param output   The output buffer.\n *\n * \\return         \\c 0 on success.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n */\nint mbedtls_rsa_public( mbedtls_rsa_context *ctx,\n                const unsigned char *input,\n                unsigned char *output );\n\n/**\n * \\brief          This function performs an RSA private key operation.\n *\n * \\note           The input and output buffers must be large\n *                 enough. For example, 128 Bytes if RSA-1024 is used.\n *\n * \\note           Blinding is used if and only if a PRNG is provided.\n *\n * \\note           If blinding is used, both the base of exponentation\n *                 and the exponent are blinded, providing protection\n *                 against some side-channel attacks.\n *\n * \\warning        It is deprecated and a security risk to not provide\n *                 a PRNG here and thereby prevent the use of blinding.\n *                 Future versions of the library may enforce the presence\n *                 of a PRNG.\n *\n * \\param ctx      The RSA context.\n * \\param f_rng    The RNG function. Needed for blinding.\n * \\param p_rng    The RNG context.\n * \\param input    The input buffer.\n * \\param output   The output buffer.\n *\n * \\return         \\c 0 on success.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n *\n */\nint mbedtls_rsa_private( mbedtls_rsa_context *ctx,\n                 int (*f_rng)(void *, unsigned char *, size_t),\n                 void *p_rng,\n                 const unsigned char *input,\n                 unsigned char *output );\n\n/**\n * \\brief          This function adds the message padding, then performs an RSA\n *                 operation.\n *\n *                 It is the generic wrapper for performing a PKCS#1 encryption\n *                 operation using the \\p mode from the context.\n *\n * \\note           The input and output buffers must be as large as the size\n *                 of \\p ctx->N. For example, 128 Bytes if RSA-1024 is used.\n *\n * \\deprecated     It is deprecated and discouraged to call this function\n *                 in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library\n *                 are likely to remove the \\p mode argument and have it\n *                 implicitly set to #MBEDTLS_RSA_PUBLIC.\n *\n * \\note           Alternative implementations of RSA need not support\n *                 mode being set to #MBEDTLS_RSA_PRIVATE and might instead\n *                 return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.\n *\n * \\param ctx      The RSA context.\n * \\param f_rng    The RNG function. Needed for padding, PKCS#1 v2.1\n *                 encoding, and #MBEDTLS_RSA_PRIVATE.\n * \\param p_rng    The RNG context.\n * \\param mode     #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE.\n * \\param ilen     The length of the plaintext.\n * \\param input    The buffer holding the data to encrypt.\n * \\param output   The buffer used to hold the ciphertext.\n *\n * \\return         \\c 0 on success.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n */\nint mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx,\n                       int (*f_rng)(void *, unsigned char *, size_t),\n                       void *p_rng,\n                       int mode, size_t ilen,\n                       const unsigned char *input,\n                       unsigned char *output );\n\n/**\n * \\brief          This function performs a PKCS#1 v1.5 encryption operation\n *                 (RSAES-PKCS1-v1_5-ENCRYPT).\n *\n * \\note           The output buffer must be as large as the size\n *                 of \\p ctx->N. For example, 128 Bytes if RSA-1024 is used.\n *\n * \\deprecated     It is deprecated and discouraged to call this function\n *                 in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library\n *                 are likely to remove the \\p mode argument and have it\n *                 implicitly set to #MBEDTLS_RSA_PUBLIC.\n *\n * \\note           Alternative implementations of RSA need not support\n *                 mode being set to #MBEDTLS_RSA_PRIVATE and might instead\n *                 return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.\n *\n * \\param ctx      The RSA context.\n * \\param f_rng    The RNG function. Needed for padding and\n *                 #MBEDTLS_RSA_PRIVATE.\n * \\param p_rng    The RNG context.\n * \\param mode     #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE.\n * \\param ilen     The length of the plaintext.\n * \\param input    The buffer holding the data to encrypt.\n * \\param output   The buffer used to hold the ciphertext.\n *\n * \\return         \\c 0 on success.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n */\nint mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx,\n                                 int (*f_rng)(void *, unsigned char *, size_t),\n                                 void *p_rng,\n                                 int mode, size_t ilen,\n                                 const unsigned char *input,\n                                 unsigned char *output );\n\n/**\n * \\brief            This function performs a PKCS#1 v2.1 OAEP encryption\n *                   operation (RSAES-OAEP-ENCRYPT).\n *\n * \\note             The output buffer must be as large as the size\n *                   of ctx->N. For example, 128 Bytes if RSA-1024 is used.\n *\n * \\deprecated       It is deprecated and discouraged to call this function\n *                   in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library\n *                   are likely to remove the \\p mode argument and have it\n *                   implicitly set to #MBEDTLS_RSA_PUBLIC.\n *\n * \\note             Alternative implementations of RSA need not support\n *                   mode being set to #MBEDTLS_RSA_PRIVATE and might instead\n *                   return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.\n *\n * \\param ctx        The RSA context.\n * \\param f_rng      The RNG function. Needed for padding and PKCS#1 v2.1\n *                   encoding and #MBEDTLS_RSA_PRIVATE.\n * \\param p_rng      The RNG context.\n * \\param mode       #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE.\n * \\param label      The buffer holding the custom label to use.\n * \\param label_len  The length of the label.\n * \\param ilen       The length of the plaintext.\n * \\param input      The buffer holding the data to encrypt.\n * \\param output     The buffer used to hold the ciphertext.\n *\n * \\return           \\c 0 on success.\n * \\return           An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n */\nint mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx,\n                            int (*f_rng)(void *, unsigned char *, size_t),\n                            void *p_rng,\n                            int mode,\n                            const unsigned char *label, size_t label_len,\n                            size_t ilen,\n                            const unsigned char *input,\n                            unsigned char *output );\n\n/**\n * \\brief          This function performs an RSA operation, then removes the\n *                 message padding.\n *\n *                 It is the generic wrapper for performing a PKCS#1 decryption\n *                 operation using the \\p mode from the context.\n *\n * \\note           The output buffer length \\c output_max_len should be\n *                 as large as the size \\p ctx->len of \\p ctx->N (for example,\n *                 128 Bytes if RSA-1024 is used) to be able to hold an\n *                 arbitrary decrypted message. If it is not large enough to\n *                 hold the decryption of the particular ciphertext provided,\n *                 the function returns \\c MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE.\n *\n * \\note           The input buffer must be as large as the size\n *                 of \\p ctx->N. For example, 128 Bytes if RSA-1024 is used.\n *\n * \\deprecated     It is deprecated and discouraged to call this function\n *                 in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library\n *                 are likely to remove the \\p mode argument and have it\n *                 implicitly set to #MBEDTLS_RSA_PRIVATE.\n *\n * \\note           Alternative implementations of RSA need not support\n *                 mode being set to #MBEDTLS_RSA_PUBLIC and might instead\n *                 return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.\n *\n * \\param ctx      The RSA context.\n * \\param f_rng    The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE.\n * \\param p_rng    The RNG context.\n * \\param mode     #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE.\n * \\param olen     The length of the plaintext.\n * \\param input    The buffer holding the encrypted data.\n * \\param output   The buffer used to hold the plaintext.\n * \\param output_max_len    The maximum length of the output buffer.\n *\n * \\return         \\c 0 on success.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n */\nint mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx,\n                       int (*f_rng)(void *, unsigned char *, size_t),\n                       void *p_rng,\n                       int mode, size_t *olen,\n                       const unsigned char *input,\n                       unsigned char *output,\n                       size_t output_max_len );\n\n/**\n * \\brief          This function performs a PKCS#1 v1.5 decryption\n *                 operation (RSAES-PKCS1-v1_5-DECRYPT).\n *\n * \\note           The output buffer length \\c output_max_len should be\n *                 as large as the size \\p ctx->len of \\p ctx->N, for example,\n *                 128 Bytes if RSA-1024 is used, to be able to hold an\n *                 arbitrary decrypted message. If it is not large enough to\n *                 hold the decryption of the particular ciphertext provided,\n *                 the function returns #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE.\n *\n * \\note           The input buffer must be as large as the size\n *                 of \\p ctx->N. For example, 128 Bytes if RSA-1024 is used.\n *\n * \\deprecated     It is deprecated and discouraged to call this function\n *                 in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library\n *                 are likely to remove the \\p mode argument and have it\n *                 implicitly set to #MBEDTLS_RSA_PRIVATE.\n *\n * \\note           Alternative implementations of RSA need not support\n *                 mode being set to #MBEDTLS_RSA_PUBLIC and might instead\n *                 return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.\n *\n * \\param ctx      The RSA context.\n * \\param f_rng    The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE.\n * \\param p_rng    The RNG context.\n * \\param mode     #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE.\n * \\param olen     The length of the plaintext.\n * \\param input    The buffer holding the encrypted data.\n * \\param output   The buffer to hold the plaintext.\n * \\param output_max_len    The maximum length of the output buffer.\n *\n * \\return         \\c 0 on success.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n *\n */\nint mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx,\n                                 int (*f_rng)(void *, unsigned char *, size_t),\n                                 void *p_rng,\n                                 int mode, size_t *olen,\n                                 const unsigned char *input,\n                                 unsigned char *output,\n                                 size_t output_max_len );\n\n/**\n * \\brief            This function performs a PKCS#1 v2.1 OAEP decryption\n *                   operation (RSAES-OAEP-DECRYPT).\n *\n * \\note             The output buffer length \\c output_max_len should be\n *                   as large as the size \\p ctx->len of \\p ctx->N, for\n *                   example, 128 Bytes if RSA-1024 is used, to be able to\n *                   hold an arbitrary decrypted message. If it is not\n *                   large enough to hold the decryption of the particular\n *                   ciphertext provided, the function returns\n *                   #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE.\n *\n * \\note             The input buffer must be as large as the size\n *                   of \\p ctx->N. For example, 128 Bytes if RSA-1024 is used.\n *\n * \\deprecated       It is deprecated and discouraged to call this function\n *                   in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library\n *                   are likely to remove the \\p mode argument and have it\n *                   implicitly set to #MBEDTLS_RSA_PRIVATE.\n *\n * \\note             Alternative implementations of RSA need not support\n *                   mode being set to #MBEDTLS_RSA_PUBLIC and might instead\n *                   return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.\n *\n * \\param ctx        The RSA context.\n * \\param f_rng      The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE.\n * \\param p_rng      The RNG context.\n * \\param mode       #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE.\n * \\param label      The buffer holding the custom label to use.\n * \\param label_len  The length of the label.\n * \\param olen       The length of the plaintext.\n * \\param input      The buffer holding the encrypted data.\n * \\param output     The buffer to hold the plaintext.\n * \\param output_max_len    The maximum length of the output buffer.\n *\n * \\return         \\c 0 on success.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n */\nint mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx,\n                            int (*f_rng)(void *, unsigned char *, size_t),\n                            void *p_rng,\n                            int mode,\n                            const unsigned char *label, size_t label_len,\n                            size_t *olen,\n                            const unsigned char *input,\n                            unsigned char *output,\n                            size_t output_max_len );\n\n/**\n * \\brief          This function performs a private RSA operation to sign\n *                 a message digest using PKCS#1.\n *\n *                 It is the generic wrapper for performing a PKCS#1\n *                 signature using the \\p mode from the context.\n *\n * \\note           The \\p sig buffer must be as large as the size\n *                 of \\p ctx->N. For example, 128 Bytes if RSA-1024 is used.\n *\n * \\note           For PKCS#1 v2.1 encoding, see comments on\n *                 mbedtls_rsa_rsassa_pss_sign() for details on\n *                 \\p md_alg and \\p hash_id.\n *\n * \\deprecated     It is deprecated and discouraged to call this function\n *                 in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library\n *                 are likely to remove the \\p mode argument and have it\n *                 implicitly set to #MBEDTLS_RSA_PRIVATE.\n *\n * \\note           Alternative implementations of RSA need not support\n *                 mode being set to #MBEDTLS_RSA_PUBLIC and might instead\n *                 return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.\n *\n * \\param ctx      The RSA context.\n * \\param f_rng    The RNG function. Needed for PKCS#1 v2.1 encoding and for\n *                 #MBEDTLS_RSA_PRIVATE.\n * \\param p_rng    The RNG context.\n * \\param mode     #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE.\n * \\param md_alg   The message-digest algorithm used to hash the original data.\n *                 Use #MBEDTLS_MD_NONE for signing raw data.\n * \\param hashlen  The length of the message digest. Only used if \\p md_alg is #MBEDTLS_MD_NONE.\n * \\param hash     The buffer holding the message digest.\n * \\param sig      The buffer to hold the ciphertext.\n *\n * \\return         \\c 0 if the signing operation was successful.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n */\nint mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx,\n                    int (*f_rng)(void *, unsigned char *, size_t),\n                    void *p_rng,\n                    int mode,\n                    mbedtls_md_type_t md_alg,\n                    unsigned int hashlen,\n                    const unsigned char *hash,\n                    unsigned char *sig );\n\n/**\n * \\brief          This function performs a PKCS#1 v1.5 signature\n *                 operation (RSASSA-PKCS1-v1_5-SIGN).\n *\n * \\note           The \\p sig buffer must be as large as the size\n *                 of \\p ctx->N. For example, 128 Bytes if RSA-1024 is used.\n *\n * \\deprecated     It is deprecated and discouraged to call this function\n *                 in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library\n *                 are likely to remove the \\p mode argument and have it\n *                 implicitly set to #MBEDTLS_RSA_PRIVATE.\n *\n * \\note           Alternative implementations of RSA need not support\n *                 mode being set to #MBEDTLS_RSA_PUBLIC and might instead\n *                 return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.\n *\n * \\param ctx      The RSA context.\n * \\param f_rng    The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE.\n * \\param p_rng    The RNG context.\n * \\param mode     #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE.\n * \\param md_alg   The message-digest algorithm used to hash the original data.\n *                 Use #MBEDTLS_MD_NONE for signing raw data.\n * \\param hashlen  The length of the message digest. Only used if \\p md_alg is #MBEDTLS_MD_NONE.\n * \\param hash     The buffer holding the message digest.\n * \\param sig      The buffer to hold the ciphertext.\n *\n * \\return         \\c 0 if the signing operation was successful.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n */\nint mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx,\n                               int (*f_rng)(void *, unsigned char *, size_t),\n                               void *p_rng,\n                               int mode,\n                               mbedtls_md_type_t md_alg,\n                               unsigned int hashlen,\n                               const unsigned char *hash,\n                               unsigned char *sig );\n\n/**\n * \\brief          This function performs a PKCS#1 v2.1 PSS signature\n *                 operation (RSASSA-PSS-SIGN).\n *\n * \\note           The \\p sig buffer must be as large as the size\n *                 of \\p ctx->N. For example, 128 Bytes if RSA-1024 is used.\n *\n * \\note           The \\p hash_id in the RSA context is the one used for the\n *                 encoding. \\p md_alg in the function call is the type of hash\n *                 that is encoded. According to <em>RFC-3447: Public-Key\n *                 Cryptography Standards (PKCS) #1 v2.1: RSA Cryptography\n *                 Specifications</em> it is advised to keep both hashes the\n *                 same.\n *\n * \\deprecated     It is deprecated and discouraged to call this function\n *                 in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library\n *                 are likely to remove the \\p mode argument and have it\n *                 implicitly set to #MBEDTLS_RSA_PRIVATE.\n *\n * \\note           Alternative implementations of RSA need not support\n *                 mode being set to #MBEDTLS_RSA_PUBLIC and might instead\n *                 return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.\n *\n * \\param ctx      The RSA context.\n * \\param f_rng    The RNG function. Needed for PKCS#1 v2.1 encoding and for\n *                 #MBEDTLS_RSA_PRIVATE.\n * \\param p_rng    The RNG context.\n * \\param mode     #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE.\n * \\param md_alg   The message-digest algorithm used to hash the original data.\n *                 Use #MBEDTLS_MD_NONE for signing raw data.\n * \\param hashlen  The length of the message digest. Only used if \\p md_alg is #MBEDTLS_MD_NONE.\n * \\param hash     The buffer holding the message digest.\n * \\param sig      The buffer to hold the ciphertext.\n *\n * \\return         \\c 0 if the signing operation was successful.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n */\nint mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx,\n                         int (*f_rng)(void *, unsigned char *, size_t),\n                         void *p_rng,\n                         int mode,\n                         mbedtls_md_type_t md_alg,\n                         unsigned int hashlen,\n                         const unsigned char *hash,\n                         unsigned char *sig );\n\n/**\n * \\brief          This function performs a public RSA operation and checks\n *                 the message digest.\n *\n *                 This is the generic wrapper for performing a PKCS#1\n *                 verification using the mode from the context.\n *\n * \\note           The \\p sig buffer must be as large as the size\n *                 of \\p ctx->N. For example, 128 Bytes if RSA-1024 is used.\n *\n * \\note           For PKCS#1 v2.1 encoding, see comments on\n *                 mbedtls_rsa_rsassa_pss_verify() about \\p md_alg and\n *                 \\p hash_id.\n *\n * \\deprecated     It is deprecated and discouraged to call this function\n *                 in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library\n *                 are likely to remove the \\p mode argument and have it\n *                 set to #MBEDTLS_RSA_PUBLIC.\n *\n * \\note           Alternative implementations of RSA need not support\n *                 mode being set to #MBEDTLS_RSA_PRIVATE and might instead\n *                 return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.\n *\n * \\param ctx      The RSA public key context.\n * \\param f_rng    The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE.\n * \\param p_rng    The RNG context.\n * \\param mode     #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE.\n * \\param md_alg   The message-digest algorithm used to hash the original data.\n *                 Use #MBEDTLS_MD_NONE for signing raw data.\n * \\param hashlen  The length of the message digest. Only used if \\p md_alg is #MBEDTLS_MD_NONE.\n * \\param hash     The buffer holding the message digest.\n * \\param sig      The buffer holding the ciphertext.\n *\n * \\return         \\c 0 if the verify operation was successful.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n */\nint mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx,\n                      int (*f_rng)(void *, unsigned char *, size_t),\n                      void *p_rng,\n                      int mode,\n                      mbedtls_md_type_t md_alg,\n                      unsigned int hashlen,\n                      const unsigned char *hash,\n                      const unsigned char *sig );\n\n/**\n * \\brief          This function performs a PKCS#1 v1.5 verification\n *                 operation (RSASSA-PKCS1-v1_5-VERIFY).\n *\n * \\note           The \\p sig buffer must be as large as the size\n *                 of \\p ctx->N. For example, 128 Bytes if RSA-1024 is used.\n *\n * \\deprecated     It is deprecated and discouraged to call this function\n *                 in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library\n *                 are likely to remove the \\p mode argument and have it\n *                 set to #MBEDTLS_RSA_PUBLIC.\n *\n * \\note           Alternative implementations of RSA need not support\n *                 mode being set to #MBEDTLS_RSA_PRIVATE and might instead\n *                 return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.\n *\n * \\param ctx      The RSA public key context.\n * \\param f_rng    The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE.\n * \\param p_rng    The RNG context.\n * \\param mode     #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE.\n * \\param md_alg   The message-digest algorithm used to hash the original data.\n *                 Use #MBEDTLS_MD_NONE for signing raw data.\n * \\param hashlen  The length of the message digest. Only used if \\p md_alg is #MBEDTLS_MD_NONE.\n * \\param hash     The buffer holding the message digest.\n * \\param sig      The buffer holding the ciphertext.\n *\n * \\return         \\c 0 if the verify operation was successful.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n */\nint mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx,\n                                 int (*f_rng)(void *, unsigned char *, size_t),\n                                 void *p_rng,\n                                 int mode,\n                                 mbedtls_md_type_t md_alg,\n                                 unsigned int hashlen,\n                                 const unsigned char *hash,\n                                 const unsigned char *sig );\n\n/**\n * \\brief          This function performs a PKCS#1 v2.1 PSS verification\n *                 operation (RSASSA-PSS-VERIFY).\n *\n *                 The hash function for the MGF mask generating function\n *                 is that specified in the RSA context.\n *\n * \\note           The \\p sig buffer must be as large as the size\n *                 of \\p ctx->N. For example, 128 Bytes if RSA-1024 is used.\n *\n * \\note           The \\p hash_id in the RSA context is the one used for the\n *                 verification. \\p md_alg in the function call is the type of\n *                 hash that is verified. According to <em>RFC-3447: Public-Key\n *                 Cryptography Standards (PKCS) #1 v2.1: RSA Cryptography\n *                 Specifications</em> it is advised to keep both hashes the\n *                 same. If \\p hash_id in the RSA context is unset,\n *                 the \\p md_alg from the function call is used.\n *\n * \\deprecated     It is deprecated and discouraged to call this function\n *                 in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library\n *                 are likely to remove the \\p mode argument and have it\n *                 implicitly set to #MBEDTLS_RSA_PUBLIC.\n *\n * \\note           Alternative implementations of RSA need not support\n *                 mode being set to #MBEDTLS_RSA_PRIVATE and might instead\n *                 return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.\n *\n * \\param ctx      The RSA public key context.\n * \\param f_rng    The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE.\n * \\param p_rng    The RNG context.\n * \\param mode     #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE.\n * \\param md_alg   The message-digest algorithm used to hash the original data.\n *                 Use #MBEDTLS_MD_NONE for signing raw data.\n * \\param hashlen  The length of the message digest. Only used if \\p md_alg is #MBEDTLS_MD_NONE.\n * \\param hash     The buffer holding the message digest.\n * \\param sig      The buffer holding the ciphertext.\n *\n * \\return         \\c 0 if the verify operation was successful.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n */\nint mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx,\n                           int (*f_rng)(void *, unsigned char *, size_t),\n                           void *p_rng,\n                           int mode,\n                           mbedtls_md_type_t md_alg,\n                           unsigned int hashlen,\n                           const unsigned char *hash,\n                           const unsigned char *sig );\n\n/**\n * \\brief          This function performs a PKCS#1 v2.1 PSS verification\n *                 operation (RSASSA-PSS-VERIFY).\n *\n *                 The hash function for the MGF mask generating function\n *                 is that specified in \\p mgf1_hash_id.\n *\n * \\note           The \\p sig buffer must be as large as the size\n *                 of \\p ctx->N. For example, 128 Bytes if RSA-1024 is used.\n *\n * \\note           The \\p hash_id in the RSA context is ignored.\n *\n * \\param ctx      The RSA public key context.\n * \\param f_rng    The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE.\n * \\param p_rng    The RNG context.\n * \\param mode     #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE.\n * \\param md_alg   The message-digest algorithm used to hash the original data.\n *                 Use #MBEDTLS_MD_NONE for signing raw data.\n * \\param hashlen  The length of the message digest. Only used if \\p md_alg is\n *                 #MBEDTLS_MD_NONE.\n * \\param hash     The buffer holding the message digest.\n * \\param mgf1_hash_id       The message digest used for mask generation.\n * \\param expected_salt_len  The length of the salt used in padding. Use\n *                           #MBEDTLS_RSA_SALT_LEN_ANY to accept any salt length.\n * \\param sig      The buffer holding the ciphertext.\n *\n * \\return         \\c 0 if the verify operation was successful.\n * \\return         An \\c MBEDTLS_ERR_RSA_XXX error code on failure.\n */\nint mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx,\n                               int (*f_rng)(void *, unsigned char *, size_t),\n                               void *p_rng,\n                               int mode,\n                               mbedtls_md_type_t md_alg,\n                               unsigned int hashlen,\n                               const unsigned char *hash,\n                               mbedtls_md_type_t mgf1_hash_id,\n                               int expected_salt_len,\n                               const unsigned char *sig );\n\n/**\n * \\brief          This function copies the components of an RSA context.\n *\n * \\param dst      The destination context.\n * \\param src      The source context.\n *\n * \\return         \\c 0 on success.\n * \\return         #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory allocation failure.\n */\nint mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src );\n\n/**\n * \\brief          This function frees the components of an RSA key.\n *\n * \\param ctx      The RSA Context to free.\n */\nvoid mbedtls_rsa_free( mbedtls_rsa_context *ctx );\n\n/**\n * \\brief          The RSA checkup routine.\n *\n * \\return         \\c 0 on success.\n * \\return         \\c 1 on failure.\n */\nint mbedtls_rsa_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* rsa.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/rsa_internal.h",
    "content": "/**\n * \\file rsa_internal.h\n *\n * \\brief Context-independent RSA helper functions\n *\n *  This module declares some RSA-related helper functions useful when\n *  implementing the RSA interface. These functions are provided in a separate\n *  compilation unit in order to make it easy for designers of alternative RSA\n *  implementations to use them in their own code, as it is conceived that the\n *  functionality they provide will be necessary for most complete\n *  implementations.\n *\n *  End-users of Mbed TLS who are not providing their own alternative RSA\n *  implementations should not use these functions directly, and should instead\n *  use only the functions declared in rsa.h.\n *\n *  The interface provided by this module will be maintained through LTS (Long\n *  Term Support) branches of Mbed TLS, but may otherwise be subject to change,\n *  and must be considered an internal interface of the library.\n *\n *  There are two classes of helper functions:\n *\n *  (1) Parameter-generating helpers. These are:\n *      - mbedtls_rsa_deduce_primes\n *      - mbedtls_rsa_deduce_private_exponent\n *      - mbedtls_rsa_deduce_crt\n *       Each of these functions takes a set of core RSA parameters and\n *       generates some other, or CRT related parameters.\n *\n *  (2) Parameter-checking helpers. These are:\n *      - mbedtls_rsa_validate_params\n *      - mbedtls_rsa_validate_crt\n *      They take a set of core or CRT related RSA parameters and check their\n *      validity.\n *\n */\n/*\n *  Copyright (C) 2006-2017, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n *\n */\n\n#ifndef MBEDTLS_RSA_INTERNAL_H\n#define MBEDTLS_RSA_INTERNAL_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include \"bignum.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\n/**\n * \\brief          Compute RSA prime moduli P, Q from public modulus N=PQ\n *                 and a pair of private and public key.\n *\n * \\note           This is a 'static' helper function not operating on\n *                 an RSA context. Alternative implementations need not\n *                 overwrite it.\n *\n * \\param N        RSA modulus N = PQ, with P, Q to be found\n * \\param E        RSA public exponent\n * \\param D        RSA private exponent\n * \\param P        Pointer to MPI holding first prime factor of N on success\n * \\param Q        Pointer to MPI holding second prime factor of N on success\n *\n * \\return\n *                 - 0 if successful. In this case, P and Q constitute a\n *                   factorization of N.\n *                 - A non-zero error code otherwise.\n *\n * \\note           It is neither checked that P, Q are prime nor that\n *                 D, E are modular inverses wrt. P-1 and Q-1. For that,\n *                 use the helper function \\c mbedtls_rsa_validate_params.\n *\n */\nint mbedtls_rsa_deduce_primes( mbedtls_mpi const *N, mbedtls_mpi const *E,\n                               mbedtls_mpi const *D,\n                               mbedtls_mpi *P, mbedtls_mpi *Q );\n\n/**\n * \\brief          Compute RSA private exponent from\n *                 prime moduli and public key.\n *\n * \\note           This is a 'static' helper function not operating on\n *                 an RSA context. Alternative implementations need not\n *                 overwrite it.\n *\n * \\param P        First prime factor of RSA modulus\n * \\param Q        Second prime factor of RSA modulus\n * \\param E        RSA public exponent\n * \\param D        Pointer to MPI holding the private exponent on success.\n *\n * \\return\n *                 - 0 if successful. In this case, D is set to a simultaneous\n *                   modular inverse of E modulo both P-1 and Q-1.\n *                 - A non-zero error code otherwise.\n *\n * \\note           This function does not check whether P and Q are primes.\n *\n */\nint mbedtls_rsa_deduce_private_exponent( mbedtls_mpi const *P,\n                                         mbedtls_mpi const *Q,\n                                         mbedtls_mpi const *E,\n                                         mbedtls_mpi *D );\n\n\n/**\n * \\brief          Generate RSA-CRT parameters\n *\n * \\note           This is a 'static' helper function not operating on\n *                 an RSA context. Alternative implementations need not\n *                 overwrite it.\n *\n * \\param P        First prime factor of N\n * \\param Q        Second prime factor of N\n * \\param D        RSA private exponent\n * \\param DP       Output variable for D modulo P-1\n * \\param DQ       Output variable for D modulo Q-1\n * \\param QP       Output variable for the modular inverse of Q modulo P.\n *\n * \\return         0 on success, non-zero error code otherwise.\n *\n * \\note           This function does not check whether P, Q are\n *                 prime and whether D is a valid private exponent.\n *\n */\nint mbedtls_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,\n                            const mbedtls_mpi *D, mbedtls_mpi *DP,\n                            mbedtls_mpi *DQ, mbedtls_mpi *QP );\n\n\n/**\n * \\brief          Check validity of core RSA parameters\n *\n * \\note           This is a 'static' helper function not operating on\n *                 an RSA context. Alternative implementations need not\n *                 overwrite it.\n *\n * \\param N        RSA modulus N = PQ\n * \\param P        First prime factor of N\n * \\param Q        Second prime factor of N\n * \\param D        RSA private exponent\n * \\param E        RSA public exponent\n * \\param f_rng    PRNG to be used for primality check, or NULL\n * \\param p_rng    PRNG context for f_rng, or NULL\n *\n * \\return\n *                 - 0 if the following conditions are satisfied\n *                   if all relevant parameters are provided:\n *                    - P prime if f_rng != NULL (%)\n *                    - Q prime if f_rng != NULL (%)\n *                    - 1 < N = P * Q\n *                    - 1 < D, E < N\n *                    - D and E are modular inverses modulo P-1 and Q-1\n *                   (%) This is only done if MBEDTLS_GENPRIME is defined.\n *                 - A non-zero error code otherwise.\n *\n * \\note           The function can be used with a restricted set of arguments\n *                 to perform specific checks only. E.g., calling it with\n *                 (-,P,-,-,-) and a PRNG amounts to a primality check for P.\n */\nint mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P,\n                                 const mbedtls_mpi *Q, const mbedtls_mpi *D,\n                                 const mbedtls_mpi *E,\n                                 int (*f_rng)(void *, unsigned char *, size_t),\n                                 void *p_rng );\n\n/**\n * \\brief          Check validity of RSA CRT parameters\n *\n * \\note           This is a 'static' helper function not operating on\n *                 an RSA context. Alternative implementations need not\n *                 overwrite it.\n *\n * \\param P        First prime factor of RSA modulus\n * \\param Q        Second prime factor of RSA modulus\n * \\param D        RSA private exponent\n * \\param DP       MPI to check for D modulo P-1\n * \\param DQ       MPI to check for D modulo P-1\n * \\param QP       MPI to check for the modular inverse of Q modulo P.\n *\n * \\return\n *                 - 0 if the following conditions are satisfied:\n *                    - D = DP mod P-1 if P, D, DP != NULL\n *                    - Q = DQ mod P-1 if P, D, DQ != NULL\n *                    - QP = Q^-1 mod P if P, Q, QP != NULL\n *                 - \\c MBEDTLS_ERR_RSA_KEY_CHECK_FAILED if check failed,\n *                   potentially including \\c MBEDTLS_ERR_MPI_XXX if some\n *                   MPI calculations failed.\n *                 - \\c MBEDTLS_ERR_RSA_BAD_INPUT_DATA if insufficient\n *                   data was provided to check DP, DQ or QP.\n *\n * \\note           The function can be used with a restricted set of arguments\n *                 to perform specific checks only. E.g., calling it with the\n *                 parameters (P, -, D, DP, -, -) will check DP = D mod P-1.\n */\nint mbedtls_rsa_validate_crt( const mbedtls_mpi *P,  const mbedtls_mpi *Q,\n                              const mbedtls_mpi *D,  const mbedtls_mpi *DP,\n                              const mbedtls_mpi *DQ, const mbedtls_mpi *QP );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* rsa_internal.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/sha1.h",
    "content": "/**\n * \\file sha1.h\n *\n * \\brief This file contains SHA-1 definitions and functions.\n *\n * The Secure Hash Algorithm 1 (SHA-1) cryptographic hash function is defined in\n * <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.\n *\n * \\warning   SHA-1 is considered a weak message digest and its use constitutes\n *            a security risk. We recommend considering stronger message\n *            digests instead.\n */\n/*\n *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_SHA1_H\n#define MBEDTLS_SHA1_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n#include <stdint.h>\n\n#define MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED                  -0x0035  /**< SHA-1 hardware accelerator failed */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_SHA1_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief          The SHA-1 context structure.\n *\n * \\warning        SHA-1 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n */\ntypedef struct\n{\n    uint32_t total[2];          /*!< The number of Bytes processed.  */\n    uint32_t state[5];          /*!< The intermediate digest state.  */\n    unsigned char buffer[64];   /*!< The data block being processed. */\n}\nmbedtls_sha1_context;\n\n#else  /* MBEDTLS_SHA1_ALT */\n#include \"sha1_alt.h\"\n#endif /* MBEDTLS_SHA1_ALT */\n\n/**\n * \\brief          This function initializes a SHA-1 context.\n *\n * \\warning        SHA-1 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n * \\param ctx      The SHA-1 context to initialize.\n *\n */\nvoid mbedtls_sha1_init( mbedtls_sha1_context *ctx );\n\n/**\n * \\brief          This function clears a SHA-1 context.\n *\n * \\warning        SHA-1 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n * \\param ctx      The SHA-1 context to clear.\n *\n */\nvoid mbedtls_sha1_free( mbedtls_sha1_context *ctx );\n\n/**\n * \\brief          This function clones the state of a SHA-1 context.\n *\n * \\warning        SHA-1 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n * \\param dst      The SHA-1 context to clone to.\n * \\param src      The SHA-1 context to clone from.\n *\n */\nvoid mbedtls_sha1_clone( mbedtls_sha1_context *dst,\n                         const mbedtls_sha1_context *src );\n\n/**\n * \\brief          This function starts a SHA-1 checksum calculation.\n *\n * \\warning        SHA-1 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n * \\param ctx      The SHA-1 context to initialize.\n *\n * \\return         \\c 0 on success.\n *\n */\nint mbedtls_sha1_starts_ret( mbedtls_sha1_context *ctx );\n\n/**\n * \\brief          This function feeds an input buffer into an ongoing SHA-1\n *                 checksum calculation.\n *\n * \\warning        SHA-1 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n * \\param ctx      The SHA-1 context.\n * \\param input    The buffer holding the input data.\n * \\param ilen     The length of the input data.\n *\n * \\return         \\c 0 on success.\n */\nint mbedtls_sha1_update_ret( mbedtls_sha1_context *ctx,\n                             const unsigned char *input,\n                             size_t ilen );\n\n/**\n * \\brief          This function finishes the SHA-1 operation, and writes\n *                 the result to the output buffer.\n *\n * \\warning        SHA-1 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n * \\param ctx      The SHA-1 context.\n * \\param output   The SHA-1 checksum result.\n *\n * \\return         \\c 0 on success.\n */\nint mbedtls_sha1_finish_ret( mbedtls_sha1_context *ctx,\n                             unsigned char output[20] );\n\n/**\n * \\brief          SHA-1 process data block (internal use only).\n *\n * \\warning        SHA-1 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n * \\param ctx      The SHA-1 context.\n * \\param data     The data block being processed.\n *\n * \\return         \\c 0 on success.\n *\n */\nint mbedtls_internal_sha1_process( mbedtls_sha1_context *ctx,\n                                   const unsigned char data[64] );\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED      __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n/**\n * \\brief          This function starts a SHA-1 checksum calculation.\n *\n * \\warning        SHA-1 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n * \\deprecated     Superseded by mbedtls_sha1_starts_ret() in 2.7.0.\n *\n * \\param ctx      The SHA-1 context to initialize.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_sha1_starts( mbedtls_sha1_context *ctx );\n\n/**\n * \\brief          This function feeds an input buffer into an ongoing SHA-1\n *                 checksum calculation.\n *\n * \\warning        SHA-1 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n * \\deprecated     Superseded by mbedtls_sha1_update_ret() in 2.7.0.\n *\n * \\param ctx      The SHA-1 context.\n * \\param input    The buffer holding the input data.\n * \\param ilen     The length of the input data.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_sha1_update( mbedtls_sha1_context *ctx,\n                                             const unsigned char *input,\n                                             size_t ilen );\n\n/**\n * \\brief          This function finishes the SHA-1 operation, and writes\n *                 the result to the output buffer.\n *\n * \\warning        SHA-1 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n * \\deprecated     Superseded by mbedtls_sha1_finish_ret() in 2.7.0.\n *\n * \\param ctx      The SHA-1 context.\n * \\param output   The SHA-1 checksum result.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_sha1_finish( mbedtls_sha1_context *ctx,\n                                             unsigned char output[20] );\n\n/**\n * \\brief          SHA-1 process data block (internal use only).\n *\n * \\warning        SHA-1 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n * \\deprecated     Superseded by mbedtls_internal_sha1_process() in 2.7.0.\n *\n * \\param ctx      The SHA-1 context.\n * \\param data     The data block being processed.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_sha1_process( mbedtls_sha1_context *ctx,\n                                              const unsigned char data[64] );\n\n#undef MBEDTLS_DEPRECATED\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n\n/**\n * \\brief          This function calculates the SHA-1 checksum of a buffer.\n *\n *                 The function allocates the context, performs the\n *                 calculation, and frees the context.\n *\n *                 The SHA-1 result is calculated as\n *                 output = SHA-1(input buffer).\n *\n * \\warning        SHA-1 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n * \\param input    The buffer holding the input data.\n * \\param ilen     The length of the input data.\n * \\param output   The SHA-1 checksum result.\n *\n * \\return         \\c 0 on success.\n *\n */\nint mbedtls_sha1_ret( const unsigned char *input,\n                      size_t ilen,\n                      unsigned char output[20] );\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED      __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n/**\n * \\brief          This function calculates the SHA-1 checksum of a buffer.\n *\n *                 The function allocates the context, performs the\n *                 calculation, and frees the context.\n *\n *                 The SHA-1 result is calculated as\n *                 output = SHA-1(input buffer).\n *\n * \\warning        SHA-1 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n * \\deprecated     Superseded by mbedtls_sha1_ret() in 2.7.0\n *\n * \\param input    The buffer holding the input data.\n * \\param ilen     The length of the input data.\n * \\param output   The SHA-1 checksum result.\n *\n */\nMBEDTLS_DEPRECATED void mbedtls_sha1( const unsigned char *input,\n                                      size_t ilen,\n                                      unsigned char output[20] );\n\n#undef MBEDTLS_DEPRECATED\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n\n/**\n * \\brief          The SHA-1 checkup routine.\n *\n * \\warning        SHA-1 is considered a weak message digest and its use\n *                 constitutes a security risk. We recommend considering\n *                 stronger message digests instead.\n *\n * \\return         \\c 0 on success.\n * \\return         \\c 1 on failure.\n *\n */\nint mbedtls_sha1_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* mbedtls_sha1.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/sha256.h",
    "content": "/**\n * \\file sha256.h\n *\n * \\brief This file contains SHA-224 and SHA-256 definitions and functions.\n *\n * The Secure Hash Algorithms 224 and 256 (SHA-224 and SHA-256) cryptographic\n * hash functions are defined in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.\n */\n/*\n *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_SHA256_H\n#define MBEDTLS_SHA256_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n#include <stdint.h>\n\n#define MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED                -0x0037  /**< SHA-256 hardware accelerator failed */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_SHA256_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief          The SHA-256 context structure.\n *\n *                 The structure is used both for SHA-256 and for SHA-224\n *                 checksum calculations. The choice between these two is\n *                 made in the call to mbedtls_sha256_starts_ret().\n */\ntypedef struct\n{\n    uint32_t total[2];          /*!< The number of Bytes processed.  */\n    uint32_t state[8];          /*!< The intermediate digest state.  */\n    unsigned char buffer[64];   /*!< The data block being processed. */\n    int is224;                  /*!< Determines which function to use:\n                                     0: Use SHA-256, or 1: Use SHA-224. */\n}\nmbedtls_sha256_context;\n\n#else  /* MBEDTLS_SHA256_ALT */\n#include \"sha256_alt.h\"\n#endif /* MBEDTLS_SHA256_ALT */\n\n/**\n * \\brief          This function initializes a SHA-256 context.\n *\n * \\param ctx      The SHA-256 context to initialize.\n */\nvoid mbedtls_sha256_init( mbedtls_sha256_context *ctx );\n\n/**\n * \\brief          This function clears a SHA-256 context.\n *\n * \\param ctx      The SHA-256 context to clear.\n */\nvoid mbedtls_sha256_free( mbedtls_sha256_context *ctx );\n\n/**\n * \\brief          This function clones the state of a SHA-256 context.\n *\n * \\param dst      The destination context.\n * \\param src      The context to clone.\n */\nvoid mbedtls_sha256_clone( mbedtls_sha256_context *dst,\n                           const mbedtls_sha256_context *src );\n\n/**\n * \\brief          This function starts a SHA-224 or SHA-256 checksum\n *                 calculation.\n *\n * \\param ctx      The context to initialize.\n * \\param is224    Determines which function to use:\n *                 0: Use SHA-256, or 1: Use SHA-224.\n *\n * \\return         \\c 0 on success.\n */\nint mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 );\n\n/**\n * \\brief          This function feeds an input buffer into an ongoing\n *                 SHA-256 checksum calculation.\n *\n * \\param ctx      The SHA-256 context.\n * \\param input    The buffer holding the data.\n * \\param ilen     The length of the input data.\n *\n * \\return         \\c 0 on success.\n */\nint mbedtls_sha256_update_ret( mbedtls_sha256_context *ctx,\n                               const unsigned char *input,\n                               size_t ilen );\n\n/**\n * \\brief          This function finishes the SHA-256 operation, and writes\n *                 the result to the output buffer.\n *\n * \\param ctx      The SHA-256 context.\n * \\param output   The SHA-224 or SHA-256 checksum result.\n *\n * \\return         \\c 0 on success.\n */\nint mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx,\n                               unsigned char output[32] );\n\n/**\n * \\brief          This function processes a single data block within\n *                 the ongoing SHA-256 computation. This function is for\n *                 internal use only.\n *\n * \\param ctx      The SHA-256 context.\n * \\param data     The buffer holding one block of data.\n *\n * \\return         \\c 0 on success.\n */\nint mbedtls_internal_sha256_process( mbedtls_sha256_context *ctx,\n                                     const unsigned char data[64] );\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED      __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n/**\n * \\brief          This function starts a SHA-224 or SHA-256 checksum\n *                 calculation.\n *\n *\n * \\deprecated     Superseded by mbedtls_sha256_starts_ret() in 2.7.0.\n *\n * \\param ctx      The context to initialize.\n * \\param is224    Determines which function to use:\n *                 0: Use SHA-256, or 1: Use SHA-224.\n */\nMBEDTLS_DEPRECATED void mbedtls_sha256_starts( mbedtls_sha256_context *ctx,\n                                               int is224 );\n\n/**\n * \\brief          This function feeds an input buffer into an ongoing\n *                 SHA-256 checksum calculation.\n *\n * \\deprecated     Superseded by mbedtls_sha256_update_ret() in 2.7.0.\n *\n * \\param ctx      The SHA-256 context to initialize.\n * \\param input    The buffer holding the data.\n * \\param ilen     The length of the input data.\n */\nMBEDTLS_DEPRECATED void mbedtls_sha256_update( mbedtls_sha256_context *ctx,\n                                               const unsigned char *input,\n                                               size_t ilen );\n\n/**\n * \\brief          This function finishes the SHA-256 operation, and writes\n *                 the result to the output buffer.\n *\n * \\deprecated     Superseded by mbedtls_sha256_finish_ret() in 2.7.0.\n *\n * \\param ctx      The SHA-256 context.\n * \\param output   The SHA-224 or SHA-256 checksum result.\n */\nMBEDTLS_DEPRECATED void mbedtls_sha256_finish( mbedtls_sha256_context *ctx,\n                                               unsigned char output[32] );\n\n/**\n * \\brief          This function processes a single data block within\n *                 the ongoing SHA-256 computation. This function is for\n *                 internal use only.\n *\n * \\deprecated     Superseded by mbedtls_internal_sha256_process() in 2.7.0.\n *\n * \\param ctx      The SHA-256 context.\n * \\param data     The buffer holding one block of data.\n */\nMBEDTLS_DEPRECATED void mbedtls_sha256_process( mbedtls_sha256_context *ctx,\n                                                const unsigned char data[64] );\n\n#undef MBEDTLS_DEPRECATED\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n\n/**\n * \\brief          This function calculates the SHA-224 or SHA-256\n *                 checksum of a buffer.\n *\n *                 The function allocates the context, performs the\n *                 calculation, and frees the context.\n *\n *                 The SHA-256 result is calculated as\n *                 output = SHA-256(input buffer).\n *\n * \\param input    The buffer holding the input data.\n * \\param ilen     The length of the input data.\n * \\param output   The SHA-224 or SHA-256 checksum result.\n * \\param is224    Determines which function to use:\n *                 0: Use SHA-256, or 1: Use SHA-224.\n */\nint mbedtls_sha256_ret( const unsigned char *input,\n                        size_t ilen,\n                        unsigned char output[32],\n                        int is224 );\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED      __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n\n/**\n * \\brief          This function calculates the SHA-224 or SHA-256 checksum\n *                 of a buffer.\n *\n *                 The function allocates the context, performs the\n *                 calculation, and frees the context.\n *\n *                 The SHA-256 result is calculated as\n *                 output = SHA-256(input buffer).\n *\n * \\deprecated     Superseded by mbedtls_sha256_ret() in 2.7.0.\n *\n * \\param input    The buffer holding the data.\n * \\param ilen     The length of the input data.\n * \\param output   The SHA-224 or SHA-256 checksum result.\n * \\param is224    Determines which function to use:\n *                 0: Use SHA-256, or 1: Use SHA-224.\n */\nMBEDTLS_DEPRECATED void mbedtls_sha256( const unsigned char *input,\n                                        size_t ilen,\n                                        unsigned char output[32],\n                                        int is224 );\n\n#undef MBEDTLS_DEPRECATED\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n\n/**\n * \\brief          The SHA-224 and SHA-256 checkup routine.\n *\n * \\return         \\c 0 on success.\n * \\return         \\c 1 on failure.\n */\nint mbedtls_sha256_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* mbedtls_sha256.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/sha512.h",
    "content": "/**\n * \\file sha512.h\n * \\brief This file contains SHA-384 and SHA-512 definitions and functions.\n *\n * The Secure Hash Algorithms 384 and 512 (SHA-384 and SHA-512) cryptographic\n * hash functions are defined in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.\n */\n/*\n *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_SHA512_H\n#define MBEDTLS_SHA512_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n#include <stdint.h>\n\n#define MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED                -0x0039  /**< SHA-512 hardware accelerator failed */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_SHA512_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief          The SHA-512 context structure.\n *\n *                 The structure is used both for SHA-384 and for SHA-512\n *                 checksum calculations. The choice between these two is\n *                 made in the call to mbedtls_sha512_starts_ret().\n */\ntypedef struct\n{\n    uint64_t total[2];          /*!< The number of Bytes processed. */\n    uint64_t state[8];          /*!< The intermediate digest state. */\n    unsigned char buffer[128];  /*!< The data block being processed. */\n    int is384;                  /*!< Determines which function to use:\n                                     0: Use SHA-512, or 1: Use SHA-384. */\n}\nmbedtls_sha512_context;\n\n#else  /* MBEDTLS_SHA512_ALT */\n#include \"sha512_alt.h\"\n#endif /* MBEDTLS_SHA512_ALT */\n\n/**\n * \\brief          This function initializes a SHA-512 context.\n *\n * \\param ctx      The SHA-512 context to initialize.\n */\nvoid mbedtls_sha512_init( mbedtls_sha512_context *ctx );\n\n/**\n * \\brief          This function clears a SHA-512 context.\n *\n * \\param ctx      The SHA-512 context to clear.\n */\nvoid mbedtls_sha512_free( mbedtls_sha512_context *ctx );\n\n/**\n * \\brief          This function clones the state of a SHA-512 context.\n *\n * \\param dst      The destination context.\n * \\param src      The context to clone.\n */\nvoid mbedtls_sha512_clone( mbedtls_sha512_context *dst,\n                           const mbedtls_sha512_context *src );\n\n/**\n * \\brief          This function starts a SHA-384 or SHA-512 checksum\n *                 calculation.\n *\n * \\param ctx      The SHA-512 context to initialize.\n * \\param is384    Determines which function to use:\n *                 0: Use SHA-512, or 1: Use SHA-384.\n *\n * \\return         \\c 0 on success.\n */\nint mbedtls_sha512_starts_ret( mbedtls_sha512_context *ctx, int is384 );\n\n/**\n * \\brief          This function feeds an input buffer into an ongoing\n *                 SHA-512 checksum calculation.\n *\n * \\param ctx      The SHA-512 context.\n * \\param input    The buffer holding the input data.\n * \\param ilen     The length of the input data.\n *\n * \\return         \\c 0 on success.\n */\nint mbedtls_sha512_update_ret( mbedtls_sha512_context *ctx,\n                    const unsigned char *input,\n                    size_t ilen );\n\n/**\n * \\brief          This function finishes the SHA-512 operation, and writes\n *                 the result to the output buffer. This function is for\n *                 internal use only.\n *\n * \\param ctx      The SHA-512 context.\n * \\param output   The SHA-384 or SHA-512 checksum result.\n *\n * \\return         \\c 0 on success.\n */\nint mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx,\n                               unsigned char output[64] );\n\n/**\n * \\brief          This function processes a single data block within\n *                 the ongoing SHA-512 computation.\n *\n * \\param ctx      The SHA-512 context.\n * \\param data     The buffer holding one block of data.\n *\n * \\return         \\c 0 on success.\n */\nint mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx,\n                                     const unsigned char data[128] );\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED      __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n/**\n * \\brief          This function starts a SHA-384 or SHA-512 checksum\n *                 calculation.\n *\n * \\deprecated     Superseded by mbedtls_sha512_starts_ret() in 2.7.0\n *\n * \\param ctx      The SHA-512 context to initialize.\n * \\param is384    Determines which function to use:\n *                 0: Use SHA-512, or 1: Use SHA-384.\n */\nMBEDTLS_DEPRECATED void mbedtls_sha512_starts( mbedtls_sha512_context *ctx,\n                                               int is384 );\n\n/**\n * \\brief          This function feeds an input buffer into an ongoing\n *                 SHA-512 checksum calculation.\n *\n * \\deprecated     Superseded by mbedtls_sha512_update_ret() in 2.7.0.\n *\n * \\param ctx      The SHA-512 context.\n * \\param input    The buffer holding the data.\n * \\param ilen     The length of the input data.\n */\nMBEDTLS_DEPRECATED void mbedtls_sha512_update( mbedtls_sha512_context *ctx,\n                                               const unsigned char *input,\n                                               size_t ilen );\n\n/**\n * \\brief          This function finishes the SHA-512 operation, and writes\n *                 the result to the output buffer.\n *\n * \\deprecated     Superseded by mbedtls_sha512_finish_ret() in 2.7.0.\n *\n * \\param ctx      The SHA-512 context.\n * \\param output   The SHA-384 or SHA-512 checksum result.\n */\nMBEDTLS_DEPRECATED void mbedtls_sha512_finish( mbedtls_sha512_context *ctx,\n                                               unsigned char output[64] );\n\n/**\n * \\brief          This function processes a single data block within\n *                 the ongoing SHA-512 computation. This function is for\n *                 internal use only.\n *\n * \\deprecated     Superseded by mbedtls_internal_sha512_process() in 2.7.0.\n *\n * \\param ctx      The SHA-512 context.\n * \\param data     The buffer holding one block of data.\n */\nMBEDTLS_DEPRECATED void mbedtls_sha512_process(\n                                            mbedtls_sha512_context *ctx,\n                                            const unsigned char data[128] );\n\n#undef MBEDTLS_DEPRECATED\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n\n/**\n * \\brief          This function calculates the SHA-512 or SHA-384\n *                 checksum of a buffer.\n *\n *                 The function allocates the context, performs the\n *                 calculation, and frees the context.\n *\n *                 The SHA-512 result is calculated as\n *                 output = SHA-512(input buffer).\n *\n * \\param input    The buffer holding the input data.\n * \\param ilen     The length of the input data.\n * \\param output   The SHA-384 or SHA-512 checksum result.\n * \\param is384    Determines which function to use:\n *                 0: Use SHA-512, or 1: Use SHA-384.\n *\n * \\return         \\c 0 on success.\n */\nint mbedtls_sha512_ret( const unsigned char *input,\n                        size_t ilen,\n                        unsigned char output[64],\n                        int is384 );\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED      __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n/**\n * \\brief          This function calculates the SHA-512 or SHA-384\n *                 checksum of a buffer.\n *\n *                 The function allocates the context, performs the\n *                 calculation, and frees the context.\n *\n *                 The SHA-512 result is calculated as\n *                 output = SHA-512(input buffer).\n *\n * \\deprecated     Superseded by mbedtls_sha512_ret() in 2.7.0\n *\n * \\param input    The buffer holding the data.\n * \\param ilen     The length of the input data.\n * \\param output   The SHA-384 or SHA-512 checksum result.\n * \\param is384    Determines which function to use:\n *                 0: Use SHA-512, or 1: Use SHA-384.\n */\nMBEDTLS_DEPRECATED void mbedtls_sha512( const unsigned char *input,\n                                        size_t ilen,\n                                        unsigned char output[64],\n                                        int is384 );\n\n#undef MBEDTLS_DEPRECATED\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n /**\n * \\brief          The SHA-384 or SHA-512 checkup routine.\n *\n * \\return         \\c 0 on success.\n * \\return         \\c 1 on failure.\n */\nint mbedtls_sha512_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* mbedtls_sha512.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/ssl.h",
    "content": "/**\n * \\file ssl.h\n *\n * \\brief SSL/TLS functions.\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_SSL_H\n#define MBEDTLS_SSL_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include \"bignum.h\"\n#include \"ecp.h\"\n\n#include \"ssl_ciphersuites.h\"\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n#include \"x509_crt.h\"\n#include \"x509_crl.h\"\n#endif\n\n#if defined(MBEDTLS_DHM_C)\n#include \"dhm.h\"\n#endif\n\n#if defined(MBEDTLS_ECDH_C)\n#include \"ecdh.h\"\n#endif\n\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#warning \"Record compression support via MBEDTLS_ZLIB_SUPPORT is deprecated and will be removed in the next major revision of the library\"\n#endif\n\n#if defined(MBEDTLS_DEPRECATED_REMOVED)\n#error \"Record compression support via MBEDTLS_ZLIB_SUPPORT is deprecated and cannot be used if MBEDTLS_DEPRECATED_REMOVED is set\"\n#endif\n\n#include \"zlib.h\"\n#endif\n\n#if defined(MBEDTLS_HAVE_TIME)\n#include \"platform_time.h\"\n#endif\n\n/*\n * SSL Error codes\n */\n#define MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE               -0x7080  /**< The requested feature is not available. */\n#define MBEDTLS_ERR_SSL_BAD_INPUT_DATA                    -0x7100  /**< Bad input parameters to function. */\n#define MBEDTLS_ERR_SSL_INVALID_MAC                       -0x7180  /**< Verification of the message MAC failed. */\n#define MBEDTLS_ERR_SSL_INVALID_RECORD                    -0x7200  /**< An invalid SSL record was received. */\n#define MBEDTLS_ERR_SSL_CONN_EOF                          -0x7280  /**< The connection indicated an EOF. */\n#define MBEDTLS_ERR_SSL_UNKNOWN_CIPHER                    -0x7300  /**< An unknown cipher was received. */\n#define MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN                  -0x7380  /**< The server has no ciphersuites in common with the client. */\n#define MBEDTLS_ERR_SSL_NO_RNG                            -0x7400  /**< No RNG was provided to the SSL module. */\n#define MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE             -0x7480  /**< No client certification received from the client, but required by the authentication mode. */\n#define MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE             -0x7500  /**< Our own certificate(s) is/are too large to send in an SSL message. */\n#define MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED              -0x7580  /**< The own certificate is not set, but needed by the server. */\n#define MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED              -0x7600  /**< The own private key or pre-shared key is not set, but needed. */\n#define MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED                 -0x7680  /**< No CA Chain is set, but required to operate. */\n#define MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE                -0x7700  /**< An unexpected message was received from our peer. */\n#define MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE               -0x7780  /**< A fatal alert message was received from our peer. */\n#define MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED                -0x7800  /**< Verification of our peer failed. */\n#define MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY                 -0x7880  /**< The peer notified us that the connection is going to be closed. */\n#define MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO               -0x7900  /**< Processing of the ClientHello handshake message failed. */\n#define MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO               -0x7980  /**< Processing of the ServerHello handshake message failed. */\n#define MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE                -0x7A00  /**< Processing of the Certificate handshake message failed. */\n#define MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST        -0x7A80  /**< Processing of the CertificateRequest handshake message failed. */\n#define MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE        -0x7B00  /**< Processing of the ServerKeyExchange handshake message failed. */\n#define MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE          -0x7B80  /**< Processing of the ServerHelloDone handshake message failed. */\n#define MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE        -0x7C00  /**< Processing of the ClientKeyExchange handshake message failed. */\n#define MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP     -0x7C80  /**< Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Read Public. */\n#define MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS     -0x7D00  /**< Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Calculate Secret. */\n#define MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY         -0x7D80  /**< Processing of the CertificateVerify handshake message failed. */\n#define MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC         -0x7E00  /**< Processing of the ChangeCipherSpec handshake message failed. */\n#define MBEDTLS_ERR_SSL_BAD_HS_FINISHED                   -0x7E80  /**< Processing of the Finished handshake message failed. */\n#define MBEDTLS_ERR_SSL_ALLOC_FAILED                      -0x7F00  /**< Memory allocation failed */\n#define MBEDTLS_ERR_SSL_HW_ACCEL_FAILED                   -0x7F80  /**< Hardware acceleration function returned with error */\n#define MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH              -0x6F80  /**< Hardware acceleration function skipped / left alone data */\n#define MBEDTLS_ERR_SSL_COMPRESSION_FAILED                -0x6F00  /**< Processing of the compression / decompression failed */\n#define MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION           -0x6E80  /**< Handshake protocol not within min/max boundaries */\n#define MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET         -0x6E00  /**< Processing of the NewSessionTicket handshake message failed. */\n#define MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED            -0x6D80  /**< Session ticket has expired. */\n#define MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH                  -0x6D00  /**< Public key type mismatch (eg, asked for RSA key exchange and presented EC key) */\n#define MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY                  -0x6C80  /**< Unknown identity received (eg, PSK identity) */\n#define MBEDTLS_ERR_SSL_INTERNAL_ERROR                    -0x6C00  /**< Internal error (eg, unexpected failure in lower-level module) */\n#define MBEDTLS_ERR_SSL_COUNTER_WRAPPING                  -0x6B80  /**< A counter would wrap (eg, too many messages exchanged). */\n#define MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO       -0x6B00  /**< Unexpected message at ServerHello in renegotiation. */\n#define MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED             -0x6A80  /**< DTLS client must retry for hello verification */\n#define MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL                  -0x6A00  /**< A buffer is too small to receive or write a message */\n#define MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE             -0x6980  /**< None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages). */\n#define MBEDTLS_ERR_SSL_WANT_READ                         -0x6900  /**< No data of requested type currently available on underlying transport. */\n#define MBEDTLS_ERR_SSL_WANT_WRITE                        -0x6880  /**< Connection requires a write call. */\n#define MBEDTLS_ERR_SSL_TIMEOUT                           -0x6800  /**< The operation timed out. */\n#define MBEDTLS_ERR_SSL_CLIENT_RECONNECT                  -0x6780  /**< The client initiated a reconnect from the same port. */\n#define MBEDTLS_ERR_SSL_UNEXPECTED_RECORD                 -0x6700  /**< Record header looks valid but is not expected. */\n#define MBEDTLS_ERR_SSL_NON_FATAL                         -0x6680  /**< The alert message received indicates a non-fatal error. */\n#define MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH               -0x6600  /**< Couldn't set the hash for verifying CertificateVerify */\n#define MBEDTLS_ERR_SSL_CONTINUE_PROCESSING               -0x6580  /**< Internal-only message signaling that further message-processing should be done */\n#define MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS                 -0x6500  /**< The asynchronous operation is not completed yet. */\n\n/*\n * Various constants\n */\n#define MBEDTLS_SSL_MAJOR_VERSION_3             3\n#define MBEDTLS_SSL_MINOR_VERSION_0             0   /*!< SSL v3.0 */\n#define MBEDTLS_SSL_MINOR_VERSION_1             1   /*!< TLS v1.0 */\n#define MBEDTLS_SSL_MINOR_VERSION_2             2   /*!< TLS v1.1 */\n#define MBEDTLS_SSL_MINOR_VERSION_3             3   /*!< TLS v1.2 */\n\n#define MBEDTLS_SSL_TRANSPORT_STREAM            0   /*!< TLS      */\n#define MBEDTLS_SSL_TRANSPORT_DATAGRAM          1   /*!< DTLS     */\n\n#define MBEDTLS_SSL_MAX_HOST_NAME_LEN           255 /*!< Maximum host name defined in RFC 1035 */\n\n/* RFC 6066 section 4, see also mfl_code_to_length in ssl_tls.c\n * NONE must be zero so that memset()ing structure to zero works */\n#define MBEDTLS_SSL_MAX_FRAG_LEN_NONE           0   /*!< don't use this extension   */\n#define MBEDTLS_SSL_MAX_FRAG_LEN_512            1   /*!< MaxFragmentLength 2^9      */\n#define MBEDTLS_SSL_MAX_FRAG_LEN_1024           2   /*!< MaxFragmentLength 2^10     */\n#define MBEDTLS_SSL_MAX_FRAG_LEN_2048           3   /*!< MaxFragmentLength 2^11     */\n#define MBEDTLS_SSL_MAX_FRAG_LEN_4096           4   /*!< MaxFragmentLength 2^12     */\n#define MBEDTLS_SSL_MAX_FRAG_LEN_INVALID        5   /*!< first invalid value        */\n\n#define MBEDTLS_SSL_IS_CLIENT                   0\n#define MBEDTLS_SSL_IS_SERVER                   1\n\n#define MBEDTLS_SSL_IS_NOT_FALLBACK             0\n#define MBEDTLS_SSL_IS_FALLBACK                 1\n\n#define MBEDTLS_SSL_EXTENDED_MS_DISABLED        0\n#define MBEDTLS_SSL_EXTENDED_MS_ENABLED         1\n\n#define MBEDTLS_SSL_ETM_DISABLED                0\n#define MBEDTLS_SSL_ETM_ENABLED                 1\n\n#define MBEDTLS_SSL_COMPRESS_NULL               0\n#define MBEDTLS_SSL_COMPRESS_DEFLATE            1\n\n#define MBEDTLS_SSL_VERIFY_NONE                 0\n#define MBEDTLS_SSL_VERIFY_OPTIONAL             1\n#define MBEDTLS_SSL_VERIFY_REQUIRED             2\n#define MBEDTLS_SSL_VERIFY_UNSET                3 /* Used only for sni_authmode */\n\n#define MBEDTLS_SSL_LEGACY_RENEGOTIATION        0\n#define MBEDTLS_SSL_SECURE_RENEGOTIATION        1\n\n#define MBEDTLS_SSL_RENEGOTIATION_DISABLED      0\n#define MBEDTLS_SSL_RENEGOTIATION_ENABLED       1\n\n#define MBEDTLS_SSL_ANTI_REPLAY_DISABLED        0\n#define MBEDTLS_SSL_ANTI_REPLAY_ENABLED         1\n\n#define MBEDTLS_SSL_RENEGOTIATION_NOT_ENFORCED  -1\n#define MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT  16\n\n#define MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION     0\n#define MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION  1\n#define MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE      2\n\n#define MBEDTLS_SSL_TRUNC_HMAC_DISABLED         0\n#define MBEDTLS_SSL_TRUNC_HMAC_ENABLED          1\n#define MBEDTLS_SSL_TRUNCATED_HMAC_LEN          10  /* 80 bits, rfc 6066 section 7 */\n\n#define MBEDTLS_SSL_SESSION_TICKETS_DISABLED     0\n#define MBEDTLS_SSL_SESSION_TICKETS_ENABLED      1\n\n#define MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED    0\n#define MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED     1\n\n#define MBEDTLS_SSL_ARC4_ENABLED                0\n#define MBEDTLS_SSL_ARC4_DISABLED               1\n\n#define MBEDTLS_SSL_PRESET_DEFAULT              0\n#define MBEDTLS_SSL_PRESET_SUITEB               2\n\n#define MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED       1\n#define MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED      0\n\n/*\n * Default range for DTLS retransmission timer value, in milliseconds.\n * RFC 6347 4.2.4.1 says from 1 second to 60 seconds.\n */\n#define MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN    1000\n#define MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX   60000\n\n/**\n * \\name SECTION: Module settings\n *\n * The configuration options you can set for this module are in this section.\n * Either change them in config.h or define them on the compiler command line.\n * \\{\n */\n\n#if !defined(MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME)\n#define MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME     86400 /**< Lifetime of session tickets (if enabled) */\n#endif\n\n/*\n * Maximum fragment length in bytes,\n * determines the size of each of the two internal I/O buffers.\n *\n * Note: the RFC defines the default size of SSL / TLS messages. If you\n * change the value here, other clients / servers may not be able to\n * communicate with you anymore. Only change this value if you control\n * both sides of the connection and have it reduced at both sides, or\n * if you're using the Max Fragment Length extension and you know all your\n * peers are using it too!\n */\n#if !defined(MBEDTLS_SSL_MAX_CONTENT_LEN)\n#define MBEDTLS_SSL_MAX_CONTENT_LEN         16384   /**< Size of the input / output buffer */\n#endif\n\n#if !defined(MBEDTLS_SSL_IN_CONTENT_LEN)\n#define MBEDTLS_SSL_IN_CONTENT_LEN MBEDTLS_SSL_MAX_CONTENT_LEN\n#endif\n\n#if !defined(MBEDTLS_SSL_OUT_CONTENT_LEN)\n#define MBEDTLS_SSL_OUT_CONTENT_LEN MBEDTLS_SSL_MAX_CONTENT_LEN\n#endif\n\n/* \\} name SECTION: Module settings */\n\n/*\n * Length of the verify data for secure renegotiation\n */\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n#define MBEDTLS_SSL_VERIFY_DATA_MAX_LEN 36\n#else\n#define MBEDTLS_SSL_VERIFY_DATA_MAX_LEN 12\n#endif\n\n/*\n * Signaling ciphersuite values (SCSV)\n */\n#define MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO    0xFF   /**< renegotiation info ext */\n#define MBEDTLS_SSL_FALLBACK_SCSV_VALUE         0x5600 /**< RFC 7507 section 2 */\n\n/*\n * Supported Signature and Hash algorithms (For TLS 1.2)\n * RFC 5246 section 7.4.1.4.1\n */\n#define MBEDTLS_SSL_HASH_NONE                0\n#define MBEDTLS_SSL_HASH_MD5                 1\n#define MBEDTLS_SSL_HASH_SHA1                2\n#define MBEDTLS_SSL_HASH_SHA224              3\n#define MBEDTLS_SSL_HASH_SHA256              4\n#define MBEDTLS_SSL_HASH_SHA384              5\n#define MBEDTLS_SSL_HASH_SHA512              6\n\n#define MBEDTLS_SSL_SIG_ANON                 0\n#define MBEDTLS_SSL_SIG_RSA                  1\n#define MBEDTLS_SSL_SIG_ECDSA                3\n\n/*\n * Client Certificate Types\n * RFC 5246 section 7.4.4 plus RFC 4492 section 5.5\n */\n#define MBEDTLS_SSL_CERT_TYPE_RSA_SIGN       1\n#define MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN    64\n\n/*\n * Message, alert and handshake types\n */\n#define MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC     20\n#define MBEDTLS_SSL_MSG_ALERT                  21\n#define MBEDTLS_SSL_MSG_HANDSHAKE              22\n#define MBEDTLS_SSL_MSG_APPLICATION_DATA       23\n\n#define MBEDTLS_SSL_ALERT_LEVEL_WARNING         1\n#define MBEDTLS_SSL_ALERT_LEVEL_FATAL           2\n\n#define MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY           0  /* 0x00 */\n#define MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE    10  /* 0x0A */\n#define MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC        20  /* 0x14 */\n#define MBEDTLS_SSL_ALERT_MSG_DECRYPTION_FAILED     21  /* 0x15 */\n#define MBEDTLS_SSL_ALERT_MSG_RECORD_OVERFLOW       22  /* 0x16 */\n#define MBEDTLS_SSL_ALERT_MSG_DECOMPRESSION_FAILURE 30  /* 0x1E */\n#define MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE     40  /* 0x28 */\n#define MBEDTLS_SSL_ALERT_MSG_NO_CERT               41  /* 0x29 */\n#define MBEDTLS_SSL_ALERT_MSG_BAD_CERT              42  /* 0x2A */\n#define MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT      43  /* 0x2B */\n#define MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED          44  /* 0x2C */\n#define MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED          45  /* 0x2D */\n#define MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN          46  /* 0x2E */\n#define MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER     47  /* 0x2F */\n#define MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA            48  /* 0x30 */\n#define MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED         49  /* 0x31 */\n#define MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR          50  /* 0x32 */\n#define MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR         51  /* 0x33 */\n#define MBEDTLS_SSL_ALERT_MSG_EXPORT_RESTRICTION    60  /* 0x3C */\n#define MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION      70  /* 0x46 */\n#define MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY 71  /* 0x47 */\n#define MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR        80  /* 0x50 */\n#define MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK 86  /* 0x56 */\n#define MBEDTLS_SSL_ALERT_MSG_USER_CANCELED         90  /* 0x5A */\n#define MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION     100  /* 0x64 */\n#define MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT      110  /* 0x6E */\n#define MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME    112  /* 0x70 */\n#define MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY 115  /* 0x73 */\n#define MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL 120 /* 0x78 */\n\n#define MBEDTLS_SSL_HS_HELLO_REQUEST            0\n#define MBEDTLS_SSL_HS_CLIENT_HELLO             1\n#define MBEDTLS_SSL_HS_SERVER_HELLO             2\n#define MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST     3\n#define MBEDTLS_SSL_HS_NEW_SESSION_TICKET       4\n#define MBEDTLS_SSL_HS_CERTIFICATE             11\n#define MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE     12\n#define MBEDTLS_SSL_HS_CERTIFICATE_REQUEST     13\n#define MBEDTLS_SSL_HS_SERVER_HELLO_DONE       14\n#define MBEDTLS_SSL_HS_CERTIFICATE_VERIFY      15\n#define MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE     16\n#define MBEDTLS_SSL_HS_FINISHED                20\n\n/*\n * TLS extensions\n */\n#define MBEDTLS_TLS_EXT_SERVERNAME                   0\n#define MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME          0\n\n#define MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH          1\n\n#define MBEDTLS_TLS_EXT_TRUNCATED_HMAC               4\n\n#define MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES   10\n#define MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS     11\n\n#define MBEDTLS_TLS_EXT_SIG_ALG                     13\n\n#define MBEDTLS_TLS_EXT_ALPN                        16\n\n#define MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC            22 /* 0x16 */\n#define MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET  0x0017 /* 23 */\n\n#define MBEDTLS_TLS_EXT_SESSION_TICKET              35\n\n#define MBEDTLS_TLS_EXT_ECJPAKE_KKPP               256 /* experimental */\n\n#define MBEDTLS_TLS_EXT_RENEGOTIATION_INFO      0xFF01\n\n/*\n * Size defines\n */\n#if !defined(MBEDTLS_PSK_MAX_LEN)\n#define MBEDTLS_PSK_MAX_LEN            32 /* 256 bits */\n#endif\n\n/* Dummy type used only for its size */\nunion mbedtls_ssl_premaster_secret\n{\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)\n    unsigned char _pms_rsa[48];                         /* RFC 5246 8.1.1 */\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)\n    unsigned char _pms_dhm[MBEDTLS_MPI_MAX_SIZE];      /* RFC 5246 8.1.2 */\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)    || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)  || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)     || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)\n    unsigned char _pms_ecdh[MBEDTLS_ECP_MAX_BYTES];    /* RFC 4492 5.10 */\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)\n    unsigned char _pms_psk[4 + 2 * MBEDTLS_PSK_MAX_LEN];       /* RFC 4279 2 */\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)\n    unsigned char _pms_dhe_psk[4 + MBEDTLS_MPI_MAX_SIZE\n                                 + MBEDTLS_PSK_MAX_LEN];       /* RFC 4279 3 */\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)\n    unsigned char _pms_rsa_psk[52 + MBEDTLS_PSK_MAX_LEN];      /* RFC 4279 4 */\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)\n    unsigned char _pms_ecdhe_psk[4 + MBEDTLS_ECP_MAX_BYTES\n                                   + MBEDTLS_PSK_MAX_LEN];     /* RFC 5489 2 */\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    unsigned char _pms_ecjpake[32];     /* Thread spec: SHA-256 output */\n#endif\n};\n\n#define MBEDTLS_PREMASTER_SIZE     sizeof( union mbedtls_ssl_premaster_secret )\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*\n * SSL state machine\n */\ntypedef enum\n{\n    MBEDTLS_SSL_HELLO_REQUEST,\n    MBEDTLS_SSL_CLIENT_HELLO,\n    MBEDTLS_SSL_SERVER_HELLO,\n    MBEDTLS_SSL_SERVER_CERTIFICATE,\n    MBEDTLS_SSL_SERVER_KEY_EXCHANGE,\n    MBEDTLS_SSL_CERTIFICATE_REQUEST,\n    MBEDTLS_SSL_SERVER_HELLO_DONE,\n    MBEDTLS_SSL_CLIENT_CERTIFICATE,\n    MBEDTLS_SSL_CLIENT_KEY_EXCHANGE,\n    MBEDTLS_SSL_CERTIFICATE_VERIFY,\n    MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC,\n    MBEDTLS_SSL_CLIENT_FINISHED,\n    MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC,\n    MBEDTLS_SSL_SERVER_FINISHED,\n    MBEDTLS_SSL_FLUSH_BUFFERS,\n    MBEDTLS_SSL_HANDSHAKE_WRAPUP,\n    MBEDTLS_SSL_HANDSHAKE_OVER,\n    MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET,\n    MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT,\n}\nmbedtls_ssl_states;\n\n/**\n * \\brief          Callback type: send data on the network.\n *\n * \\note           That callback may be either blocking or non-blocking.\n *\n * \\param ctx      Context for the send callback (typically a file descriptor)\n * \\param buf      Buffer holding the data to send\n * \\param len      Length of the data to send\n *\n * \\return         The callback must return the number of bytes sent if any,\n *                 or a non-zero error code.\n *                 If performing non-blocking I/O, \\c MBEDTLS_ERR_SSL_WANT_WRITE\n *                 must be returned when the operation would block.\n *\n * \\note           The callback is allowed to send fewer bytes than requested.\n *                 It must always return the number of bytes actually sent.\n */\ntypedef int mbedtls_ssl_send_t( void *ctx,\n                                const unsigned char *buf,\n                                size_t len );\n\n/**\n * \\brief          Callback type: receive data from the network.\n *\n * \\note           That callback may be either blocking or non-blocking.\n *\n * \\param ctx      Context for the receive callback (typically a file\n *                 descriptor)\n * \\param buf      Buffer to write the received data to\n * \\param len      Length of the receive buffer\n *\n * \\return         The callback must return the number of bytes received,\n *                 or a non-zero error code.\n *                 If performing non-blocking I/O, \\c MBEDTLS_ERR_SSL_WANT_READ\n *                 must be returned when the operation would block.\n *\n * \\note           The callback may receive fewer bytes than the length of the\n *                 buffer. It must always return the number of bytes actually\n *                 received and written to the buffer.\n */\ntypedef int mbedtls_ssl_recv_t( void *ctx,\n                                unsigned char *buf,\n                                size_t len );\n\n/**\n * \\brief          Callback type: receive data from the network, with timeout\n *\n * \\note           That callback must block until data is received, or the\n *                 timeout delay expires, or the operation is interrupted by a\n *                 signal.\n *\n * \\param ctx      Context for the receive callback (typically a file descriptor)\n * \\param buf      Buffer to write the received data to\n * \\param len      Length of the receive buffer\n * \\param timeout  Maximum nomber of millisecondes to wait for data\n *                 0 means no timeout (potentially waiting forever)\n *\n * \\return         The callback must return the number of bytes received,\n *                 or a non-zero error code:\n *                 \\c MBEDTLS_ERR_SSL_TIMEOUT if the operation timed out,\n *                 \\c MBEDTLS_ERR_SSL_WANT_READ if interrupted by a signal.\n *\n * \\note           The callback may receive fewer bytes than the length of the\n *                 buffer. It must always return the number of bytes actually\n *                 received and written to the buffer.\n */\ntypedef int mbedtls_ssl_recv_timeout_t( void *ctx,\n                                        unsigned char *buf,\n                                        size_t len,\n                                        uint32_t timeout );\n/**\n * \\brief          Callback type: set a pair of timers/delays to watch\n *\n * \\param ctx      Context pointer\n * \\param int_ms   Intermediate delay in milliseconds\n * \\param fin_ms   Final delay in milliseconds\n *                 0 cancels the current timer.\n *\n * \\note           This callback must at least store the necessary information\n *                 for the associated \\c mbedtls_ssl_get_timer_t callback to\n *                 return correct information.\n *\n * \\note           If using a event-driven style of programming, an event must\n *                 be generated when the final delay is passed. The event must\n *                 cause a call to \\c mbedtls_ssl_handshake() with the proper\n *                 SSL context to be scheduled. Care must be taken to ensure\n *                 that at most one such call happens at a time.\n *\n * \\note           Only one timer at a time must be running. Calling this\n *                 function while a timer is running must cancel it. Cancelled\n *                 timers must not generate any event.\n */\ntypedef void mbedtls_ssl_set_timer_t( void * ctx,\n                                      uint32_t int_ms,\n                                      uint32_t fin_ms );\n\n/**\n * \\brief          Callback type: get status of timers/delays\n *\n * \\param ctx      Context pointer\n *\n * \\return         This callback must return:\n *                 -1 if cancelled (fin_ms == 0),\n *                  0 if none of the delays have passed,\n *                  1 if only the intermediate delay has passed,\n *                  2 if the final delay has passed.\n */\ntypedef int mbedtls_ssl_get_timer_t( void * ctx );\n\n/* Defined below */\ntypedef struct mbedtls_ssl_session mbedtls_ssl_session;\ntypedef struct mbedtls_ssl_context mbedtls_ssl_context;\ntypedef struct mbedtls_ssl_config  mbedtls_ssl_config;\n\n/* Defined in ssl_internal.h */\ntypedef struct mbedtls_ssl_transform mbedtls_ssl_transform;\ntypedef struct mbedtls_ssl_handshake_params mbedtls_ssl_handshake_params;\ntypedef struct mbedtls_ssl_sig_hash_set_t mbedtls_ssl_sig_hash_set_t;\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\ntypedef struct mbedtls_ssl_key_cert mbedtls_ssl_key_cert;\n#endif\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\ntypedef struct mbedtls_ssl_flight_item mbedtls_ssl_flight_item;\n#endif\n\n#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n/**\n * \\brief           Callback type: start external signature operation.\n *\n *                  This callback is called during an SSL handshake to start\n *                  a signature decryption operation using an\n *                  external processor. The parameter \\p cert contains\n *                  the public key; it is up to the callback function to\n *                  determine how to access the associated private key.\n *\n *                  This function typically sends or enqueues a request, and\n *                  does not wait for the operation to complete. This allows\n *                  the handshake step to be non-blocking.\n *\n *                  The parameters \\p ssl and \\p cert are guaranteed to remain\n *                  valid throughout the handshake. On the other hand, this\n *                  function must save the contents of \\p hash if the value\n *                  is needed for later processing, because the \\p hash buffer\n *                  is no longer valid after this function returns.\n *\n *                  This function may call mbedtls_ssl_set_async_operation_data()\n *                  to store an operation context for later retrieval\n *                  by the resume or cancel callback.\n *\n * \\note            For RSA signatures, this function must produce output\n *                  that is consistent with PKCS#1 v1.5 in the same way as\n *                  mbedtls_rsa_pkcs1_sign(). Before the private key operation,\n *                  apply the padding steps described in RFC 8017, section 9.2\n *                  \"EMSA-PKCS1-v1_5\" as follows.\n *                  - If \\p md_alg is #MBEDTLS_MD_NONE, apply the PKCS#1 v1.5\n *                    encoding, treating \\p hash as the DigestInfo to be\n *                    padded. In other words, apply EMSA-PKCS1-v1_5 starting\n *                    from step 3, with `T = hash` and `tLen = hash_len`.\n *                  - If `md_alg != MBEDTLS_MD_NONE`, apply the PKCS#1 v1.5\n *                    encoding, treating \\p hash as the hash to be encoded and\n *                    padded. In other words, apply EMSA-PKCS1-v1_5 starting\n *                    from step 2, with `digestAlgorithm` obtained by calling\n *                    mbedtls_oid_get_oid_by_md() on \\p md_alg.\n *\n * \\note            For ECDSA signatures, the output format is the DER encoding\n *                  `Ecdsa-Sig-Value` defined in\n *                  [RFC 4492 section 5.4](https://tools.ietf.org/html/rfc4492#section-5.4).\n *\n * \\param ssl             The SSL connection instance. It should not be\n *                        modified other than via\n *                        mbedtls_ssl_set_async_operation_data().\n * \\param cert            Certificate containing the public key.\n *                        In simple cases, this is one of the pointers passed to\n *                        mbedtls_ssl_conf_own_cert() when configuring the SSL\n *                        connection. However, if other callbacks are used, this\n *                        property may not hold. For example, if an SNI callback\n *                        is registered with mbedtls_ssl_conf_sni(), then\n *                        this callback determines what certificate is used.\n * \\param md_alg          Hash algorithm.\n * \\param hash            Buffer containing the hash. This buffer is\n *                        no longer valid when the function returns.\n * \\param hash_len        Size of the \\c hash buffer in bytes.\n *\n * \\return          0 if the operation was started successfully and the SSL\n *                  stack should call the resume callback immediately.\n * \\return          #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation\n *                  was started successfully and the SSL stack should return\n *                  immediately without calling the resume callback yet.\n * \\return          #MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH if the external\n *                  processor does not support this key. The SSL stack will\n *                  use the private key object instead.\n * \\return          Any other error indicates a fatal failure and is\n *                  propagated up the call chain. The callback should\n *                  use \\c MBEDTLS_ERR_PK_xxx error codes, and <b>must not</b>\n *                  use \\c MBEDTLS_ERR_SSL_xxx error codes except as\n *                  directed in the documentation of this callback.\n */\ntypedef int mbedtls_ssl_async_sign_t( mbedtls_ssl_context *ssl,\n                                      mbedtls_x509_crt *cert,\n                                      mbedtls_md_type_t md_alg,\n                                      const unsigned char *hash,\n                                      size_t hash_len );\n\n/**\n * \\brief           Callback type: start external decryption operation.\n *\n *                  This callback is called during an SSL handshake to start\n *                  an RSA decryption operation using an\n *                  external processor. The parameter \\p cert contains\n *                  the public key; it is up to the callback function to\n *                  determine how to access the associated private key.\n *\n *                  This function typically sends or enqueues a request, and\n *                  does not wait for the operation to complete. This allows\n *                  the handshake step to be non-blocking.\n *\n *                  The parameters \\p ssl and \\p cert are guaranteed to remain\n *                  valid throughout the handshake. On the other hand, this\n *                  function must save the contents of \\p input if the value\n *                  is needed for later processing, because the \\p input buffer\n *                  is no longer valid after this function returns.\n *\n *                  This function may call mbedtls_ssl_set_async_operation_data()\n *                  to store an operation context for later retrieval\n *                  by the resume or cancel callback.\n *\n * \\warning         RSA decryption as used in TLS is subject to a potential\n *                  timing side channel attack first discovered by Bleichenbacher\n *                  in 1998. This attack can be remotely exploitable\n *                  in practice. To avoid this attack, you must ensure that\n *                  if the callback performs an RSA decryption, the time it\n *                  takes to execute and return the result does not depend\n *                  on whether the RSA decryption succeeded or reported\n *                  invalid padding.\n *\n * \\param ssl             The SSL connection instance. It should not be\n *                        modified other than via\n *                        mbedtls_ssl_set_async_operation_data().\n * \\param cert            Certificate containing the public key.\n *                        In simple cases, this is one of the pointers passed to\n *                        mbedtls_ssl_conf_own_cert() when configuring the SSL\n *                        connection. However, if other callbacks are used, this\n *                        property may not hold. For example, if an SNI callback\n *                        is registered with mbedtls_ssl_conf_sni(), then\n *                        this callback determines what certificate is used.\n * \\param input           Buffer containing the input ciphertext. This buffer\n *                        is no longer valid when the function returns.\n * \\param input_len       Size of the \\p input buffer in bytes.\n *\n * \\return          0 if the operation was started successfully and the SSL\n *                  stack should call the resume callback immediately.\n * \\return          #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation\n *                  was started successfully and the SSL stack should return\n *                  immediately without calling the resume callback yet.\n * \\return          #MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH if the external\n *                  processor does not support this key. The SSL stack will\n *                  use the private key object instead.\n * \\return          Any other error indicates a fatal failure and is\n *                  propagated up the call chain. The callback should\n *                  use \\c MBEDTLS_ERR_PK_xxx error codes, and <b>must not</b>\n *                  use \\c MBEDTLS_ERR_SSL_xxx error codes except as\n *                  directed in the documentation of this callback.\n */\ntypedef int mbedtls_ssl_async_decrypt_t( mbedtls_ssl_context *ssl,\n                                         mbedtls_x509_crt *cert,\n                                         const unsigned char *input,\n                                         size_t input_len );\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n/**\n * \\brief           Callback type: resume external operation.\n *\n *                  This callback is called during an SSL handshake to resume\n *                  an external operation started by the\n *                  ::mbedtls_ssl_async_sign_t or\n *                  ::mbedtls_ssl_async_decrypt_t callback.\n *\n *                  This function typically checks the status of a pending\n *                  request or causes the request queue to make progress, and\n *                  does not wait for the operation to complete. This allows\n *                  the handshake step to be non-blocking.\n *\n *                  This function may call mbedtls_ssl_get_async_operation_data()\n *                  to retrieve an operation context set by the start callback.\n *                  It may call mbedtls_ssl_set_async_operation_data() to modify\n *                  this context.\n *\n *                  Note that when this function returns a status other than\n *                  #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS, it must free any\n *                  resources associated with the operation.\n *\n * \\param ssl             The SSL connection instance. It should not be\n *                        modified other than via\n *                        mbedtls_ssl_set_async_operation_data().\n * \\param output          Buffer containing the output (signature or decrypted\n *                        data) on success.\n * \\param output_len      On success, number of bytes written to \\p output.\n * \\param output_size     Size of the \\p output buffer in bytes.\n *\n * \\return          0 if output of the operation is available in the\n *                  \\p output buffer.\n * \\return          #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation\n *                  is still in progress. Subsequent requests for progress\n *                  on the SSL connection will call the resume callback\n *                  again.\n * \\return          Any other error means that the operation is aborted.\n *                  The SSL handshake is aborted. The callback should\n *                  use \\c MBEDTLS_ERR_PK_xxx error codes, and <b>must not</b>\n *                  use \\c MBEDTLS_ERR_SSL_xxx error codes except as\n *                  directed in the documentation of this callback.\n */\ntypedef int mbedtls_ssl_async_resume_t( mbedtls_ssl_context *ssl,\n                                        unsigned char *output,\n                                        size_t *output_len,\n                                        size_t output_size );\n\n/**\n * \\brief           Callback type: cancel external operation.\n *\n *                  This callback is called if an SSL connection is closed\n *                  while an asynchronous operation is in progress. Note that\n *                  this callback is not called if the\n *                  ::mbedtls_ssl_async_resume_t callback has run and has\n *                  returned a value other than\n *                  #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS, since in that case\n *                  the asynchronous operation has already completed.\n *\n *                  This function may call mbedtls_ssl_get_async_operation_data()\n *                  to retrieve an operation context set by the start callback.\n *\n * \\param ssl             The SSL connection instance. It should not be\n *                        modified.\n */\ntypedef void mbedtls_ssl_async_cancel_t( mbedtls_ssl_context *ssl );\n#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */\n\n/*\n * This structure is used for storing current session data.\n */\nstruct mbedtls_ssl_session\n{\n#if defined(MBEDTLS_HAVE_TIME)\n    mbedtls_time_t start;       /*!< starting time      */\n#endif\n    int ciphersuite;            /*!< chosen ciphersuite */\n    int compression;            /*!< chosen compression */\n    size_t id_len;              /*!< session id length  */\n    unsigned char id[32];       /*!< session identifier */\n    unsigned char master[48];   /*!< the master secret  */\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    mbedtls_x509_crt *peer_cert;        /*!< peer X.509 cert chain */\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n    uint32_t verify_result;          /*!<  verification result     */\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)\n    unsigned char *ticket;      /*!< RFC 5077 session ticket */\n    size_t ticket_len;          /*!< session ticket length   */\n    uint32_t ticket_lifetime;   /*!< ticket lifetime hint    */\n#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */\n\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\n    unsigned char mfl_code;     /*!< MaxFragmentLength negotiated by peer */\n#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */\n\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)\n    int trunc_hmac;             /*!< flag for truncated hmac activation   */\n#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */\n\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\n    int encrypt_then_mac;       /*!< flag for EtM activation                */\n#endif\n};\n\n/**\n * SSL/TLS configuration to be shared between mbedtls_ssl_context structures.\n */\nstruct mbedtls_ssl_config\n{\n    /* Group items by size (largest first) to minimize padding overhead */\n\n    /*\n     * Pointers\n     */\n\n    const int *ciphersuite_list[4]; /*!< allowed ciphersuites per version   */\n\n    /** Callback for printing debug output                                  */\n    void (*f_dbg)(void *, int, const char *, int, const char *);\n    void *p_dbg;                    /*!< context for the debug function     */\n\n    /** Callback for getting (pseudo-)random numbers                        */\n    int  (*f_rng)(void *, unsigned char *, size_t);\n    void *p_rng;                    /*!< context for the RNG function       */\n\n    /** Callback to retrieve a session from the cache                       */\n    int (*f_get_cache)(void *, mbedtls_ssl_session *);\n    /** Callback to store a session into the cache                          */\n    int (*f_set_cache)(void *, const mbedtls_ssl_session *);\n    void *p_cache;                  /*!< context for cache callbacks        */\n\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\n    /** Callback for setting cert according to SNI extension                */\n    int (*f_sni)(void *, mbedtls_ssl_context *, const unsigned char *, size_t);\n    void *p_sni;                    /*!< context for SNI callback           */\n#endif\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    /** Callback to customize X.509 certificate chain verification          */\n    int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *);\n    void *p_vrfy;                   /*!< context for X.509 verify calllback */\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)\n    /** Callback to retrieve PSK key from identity                          */\n    int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *, size_t);\n    void *p_psk;                    /*!< context for PSK callback           */\n#endif\n\n#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)\n    /** Callback to create & write a cookie for ClientHello veirifcation    */\n    int (*f_cookie_write)( void *, unsigned char **, unsigned char *,\n                           const unsigned char *, size_t );\n    /** Callback to verify validity of a ClientHello cookie                 */\n    int (*f_cookie_check)( void *, const unsigned char *, size_t,\n                           const unsigned char *, size_t );\n    void *p_cookie;                 /*!< context for the cookie callbacks   */\n#endif\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_SRV_C)\n    /** Callback to create & write a session ticket                         */\n    int (*f_ticket_write)( void *, const mbedtls_ssl_session *,\n            unsigned char *, const unsigned char *, size_t *, uint32_t * );\n    /** Callback to parse a session ticket into a session structure         */\n    int (*f_ticket_parse)( void *, mbedtls_ssl_session *, unsigned char *, size_t);\n    void *p_ticket;                 /*!< context for the ticket callbacks   */\n#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_SRV_C */\n\n#if defined(MBEDTLS_SSL_EXPORT_KEYS)\n    /** Callback to export key block and master secret                      */\n    int (*f_export_keys)( void *, const unsigned char *,\n            const unsigned char *, size_t, size_t, size_t );\n    void *p_export_keys;            /*!< context for key export callback    */\n#endif\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    const mbedtls_x509_crt_profile *cert_profile; /*!< verification profile */\n    mbedtls_ssl_key_cert *key_cert; /*!< own certificate/key pair(s)        */\n    mbedtls_x509_crt *ca_chain;     /*!< trusted CAs                        */\n    mbedtls_x509_crl *ca_crl;       /*!< trusted CAs CRLs                   */\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    mbedtls_ssl_async_sign_t *f_async_sign_start; /*!< start asynchronous signature operation */\n    mbedtls_ssl_async_decrypt_t *f_async_decrypt_start; /*!< start asynchronous decryption operation */\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n    mbedtls_ssl_async_resume_t *f_async_resume; /*!< resume asynchronous operation */\n    mbedtls_ssl_async_cancel_t *f_async_cancel; /*!< cancel asynchronous operation */\n    void *p_async_config_data; /*!< Configuration data set by mbedtls_ssl_conf_async_private_cb(). */\n#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */\n\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n    const int *sig_hashes;          /*!< allowed signature hashes           */\n#endif\n\n#if defined(MBEDTLS_ECP_C)\n    const mbedtls_ecp_group_id *curve_list; /*!< allowed curves             */\n#endif\n\n#if defined(MBEDTLS_DHM_C)\n    mbedtls_mpi dhm_P;              /*!< prime modulus for DHM              */\n    mbedtls_mpi dhm_G;              /*!< generator for DHM                  */\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)\n    unsigned char *psk;             /*!< pre-shared key. This field should\n                                         only be set via\n                                         mbedtls_ssl_conf_psk() */\n    size_t         psk_len;         /*!< length of the pre-shared key. This\n                                         field should only be set via\n                                         mbedtls_ssl_conf_psk() */\n    unsigned char *psk_identity;    /*!< identity for PSK negotiation. This\n                                         field should only be set via\n                                         mbedtls_ssl_conf_psk() */\n    size_t         psk_identity_len;/*!< length of identity. This field should\n                                         only be set via\n                                         mbedtls_ssl_conf_psk() */\n#endif\n\n#if defined(MBEDTLS_SSL_ALPN)\n    const char **alpn_list;         /*!< ordered list of protocols          */\n#endif\n\n    /*\n     * Numerical settings (int then char)\n     */\n\n    uint32_t read_timeout;          /*!< timeout for mbedtls_ssl_read (ms)  */\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    uint32_t hs_timeout_min;        /*!< initial value of the handshake\n                                         retransmission timeout (ms)        */\n    uint32_t hs_timeout_max;        /*!< maximum value of the handshake\n                                         retransmission timeout (ms)        */\n#endif\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    int renego_max_records;         /*!< grace period for renegotiation     */\n    unsigned char renego_period[8]; /*!< value of the record counters\n                                         that triggers renegotiation        */\n#endif\n\n#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)\n    unsigned int badmac_limit;      /*!< limit of records with a bad MAC    */\n#endif\n\n#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)\n    unsigned int dhm_min_bitlen;    /*!< min. bit length of the DHM prime   */\n#endif\n\n    unsigned char max_major_ver;    /*!< max. major version used            */\n    unsigned char max_minor_ver;    /*!< max. minor version used            */\n    unsigned char min_major_ver;    /*!< min. major version used            */\n    unsigned char min_minor_ver;    /*!< min. minor version used            */\n\n    /*\n     * Flags (bitfields)\n     */\n\n    unsigned int endpoint : 1;      /*!< 0: client, 1: server               */\n    unsigned int transport : 1;     /*!< stream (TLS) or datagram (DTLS)    */\n    unsigned int authmode : 2;      /*!< MBEDTLS_SSL_VERIFY_XXX             */\n    /* needed even with renego disabled for LEGACY_BREAK_HANDSHAKE          */\n    unsigned int allow_legacy_renegotiation : 2 ; /*!< MBEDTLS_LEGACY_XXX   */\n#if defined(MBEDTLS_ARC4_C)\n    unsigned int arc4_disabled : 1; /*!< blacklist RC4 ciphersuites?        */\n#endif\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\n    unsigned int mfl_code : 3;      /*!< desired fragment length            */\n#endif\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\n    unsigned int encrypt_then_mac : 1 ; /*!< negotiate encrypt-then-mac?    */\n#endif\n#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)\n    unsigned int extended_ms : 1;   /*!< negotiate extended master secret?  */\n#endif\n#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)\n    unsigned int anti_replay : 1;   /*!< detect and prevent replay?         */\n#endif\n#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)\n    unsigned int cbc_record_splitting : 1;  /*!< do cbc record splitting    */\n#endif\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    unsigned int disable_renegotiation : 1; /*!< disable renegotiation?     */\n#endif\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)\n    unsigned int trunc_hmac : 1;    /*!< negotiate truncated hmac?          */\n#endif\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\n    unsigned int session_tickets : 1;   /*!< use session tickets?           */\n#endif\n#if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)\n    unsigned int fallback : 1;      /*!< is this a fallback?                */\n#endif\n#if defined(MBEDTLS_SSL_SRV_C)\n    unsigned int cert_req_ca_list : 1;  /*!< enable sending CA list in\n                                          Certificate Request messages?     */\n#endif\n};\n\n\nstruct mbedtls_ssl_context\n{\n    const mbedtls_ssl_config *conf; /*!< configuration information          */\n\n    /*\n     * Miscellaneous\n     */\n    int state;                  /*!< SSL handshake: current state     */\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    int renego_status;          /*!< Initial, in progress, pending?   */\n    int renego_records_seen;    /*!< Records since renego request, or with DTLS,\n                                  number of retransmissions of request if\n                                  renego_max_records is < 0           */\n#endif\n\n    int major_ver;              /*!< equal to  MBEDTLS_SSL_MAJOR_VERSION_3    */\n    int minor_ver;              /*!< either 0 (SSL3) or 1 (TLS1.0)    */\n\n#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)\n    unsigned badmac_seen;       /*!< records with a bad MAC received    */\n#endif\n\n    mbedtls_ssl_send_t *f_send; /*!< Callback for network send */\n    mbedtls_ssl_recv_t *f_recv; /*!< Callback for network receive */\n    mbedtls_ssl_recv_timeout_t *f_recv_timeout;\n                                /*!< Callback for network receive with timeout */\n\n    void *p_bio;                /*!< context for I/O operations   */\n\n    /*\n     * Session layer\n     */\n    mbedtls_ssl_session *session_in;            /*!<  current session data (in)   */\n    mbedtls_ssl_session *session_out;           /*!<  current session data (out)  */\n    mbedtls_ssl_session *session;               /*!<  negotiated session data     */\n    mbedtls_ssl_session *session_negotiate;     /*!<  session data in negotiation */\n\n    mbedtls_ssl_handshake_params *handshake;    /*!<  params required only during\n                                              the handshake process        */\n\n    /*\n     * Record layer transformations\n     */\n    mbedtls_ssl_transform *transform_in;        /*!<  current transform params (in)   */\n    mbedtls_ssl_transform *transform_out;       /*!<  current transform params (in)   */\n    mbedtls_ssl_transform *transform;           /*!<  negotiated transform params     */\n    mbedtls_ssl_transform *transform_negotiate; /*!<  transform params in negotiation */\n\n    /*\n     * Timers\n     */\n    void *p_timer;              /*!< context for the timer callbacks */\n\n    mbedtls_ssl_set_timer_t *f_set_timer;       /*!< set timer callback */\n    mbedtls_ssl_get_timer_t *f_get_timer;       /*!< get timer callback */\n\n    /*\n     * Record layer (incoming data)\n     */\n    unsigned char *in_buf;      /*!< input buffer                     */\n    unsigned char *in_ctr;      /*!< 64-bit incoming message counter\n                                     TLS: maintained by us\n                                     DTLS: read from peer             */\n    unsigned char *in_hdr;      /*!< start of record header           */\n    unsigned char *in_len;      /*!< two-bytes message length field   */\n    unsigned char *in_iv;       /*!< ivlen-byte IV                    */\n    unsigned char *in_msg;      /*!< message contents (in_iv+ivlen)   */\n    unsigned char *in_offt;     /*!< read offset in application data  */\n\n    int in_msgtype;             /*!< record header: message type      */\n    size_t in_msglen;           /*!< record header: message length    */\n    size_t in_left;             /*!< amount of data read so far       */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    uint16_t in_epoch;          /*!< DTLS epoch for incoming records  */\n    size_t next_record_offset;  /*!< offset of the next record in datagram\n                                     (equal to in_left if none)       */\n#endif\n#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)\n    uint64_t in_window_top;     /*!< last validated record seq_num    */\n    uint64_t in_window;         /*!< bitmask for replay detection     */\n#endif\n\n    size_t in_hslen;            /*!< current handshake message length,\n                                     including the handshake header   */\n    int nb_zero;                /*!< # of 0-length encrypted messages */\n\n    int keep_current_message;   /*!< drop or reuse current message\n                                     on next call to record layer? */\n\n    /*\n     * Record layer (outgoing data)\n     */\n    unsigned char *out_buf;     /*!< output buffer                    */\n    unsigned char *out_ctr;     /*!< 64-bit outgoing message counter  */\n    unsigned char *out_hdr;     /*!< start of record header           */\n    unsigned char *out_len;     /*!< two-bytes message length field   */\n    unsigned char *out_iv;      /*!< ivlen-byte IV                    */\n    unsigned char *out_msg;     /*!< message contents (out_iv+ivlen)  */\n\n    int out_msgtype;            /*!< record header: message type      */\n    size_t out_msglen;          /*!< record header: message length    */\n    size_t out_left;            /*!< amount of data not yet written   */\n\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n    unsigned char *compress_buf;        /*!<  zlib data buffer        */\n#endif\n#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)\n    signed char split_done;     /*!< current record already splitted? */\n#endif\n\n    /*\n     * PKI layer\n     */\n    int client_auth;                    /*!<  flag for client auth.   */\n\n    /*\n     * User settings\n     */\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    char *hostname;             /*!< expected peer CN for verification\n                                     (and SNI if available)                 */\n#endif\n\n#if defined(MBEDTLS_SSL_ALPN)\n    const char *alpn_chosen;    /*!<  negotiated protocol                   */\n#endif\n\n    /*\n     * Information for DTLS hello verify\n     */\n#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)\n    unsigned char  *cli_id;         /*!<  transport-level ID of the client  */\n    size_t          cli_id_len;     /*!<  length of cli_id                  */\n#endif\n\n    /*\n     * Secure renegotiation\n     */\n    /* needed to know when to send extension on server */\n    int secure_renegotiation;           /*!<  does peer support legacy or\n                                              secure renegotiation           */\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    size_t verify_data_len;             /*!<  length of verify data stored   */\n    char own_verify_data[MBEDTLS_SSL_VERIFY_DATA_MAX_LEN]; /*!<  previous handshake verify data */\n    char peer_verify_data[MBEDTLS_SSL_VERIFY_DATA_MAX_LEN]; /*!<  previous handshake verify data */\n#endif\n};\n\n#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)\n\n#define MBEDTLS_SSL_CHANNEL_OUTBOUND    0\n#define MBEDTLS_SSL_CHANNEL_INBOUND     1\n\nextern int (*mbedtls_ssl_hw_record_init)(mbedtls_ssl_context *ssl,\n                const unsigned char *key_enc, const unsigned char *key_dec,\n                size_t keylen,\n                const unsigned char *iv_enc,  const unsigned char *iv_dec,\n                size_t ivlen,\n                const unsigned char *mac_enc, const unsigned char *mac_dec,\n                size_t maclen);\nextern int (*mbedtls_ssl_hw_record_activate)(mbedtls_ssl_context *ssl, int direction);\nextern int (*mbedtls_ssl_hw_record_reset)(mbedtls_ssl_context *ssl);\nextern int (*mbedtls_ssl_hw_record_write)(mbedtls_ssl_context *ssl);\nextern int (*mbedtls_ssl_hw_record_read)(mbedtls_ssl_context *ssl);\nextern int (*mbedtls_ssl_hw_record_finish)(mbedtls_ssl_context *ssl);\n#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */\n\n/**\n * \\brief               Return the name of the ciphersuite associated with the\n *                      given ID\n *\n * \\param ciphersuite_id SSL ciphersuite ID\n *\n * \\return              a string containing the ciphersuite name\n */\nconst char *mbedtls_ssl_get_ciphersuite_name( const int ciphersuite_id );\n\n/**\n * \\brief               Return the ID of the ciphersuite associated with the\n *                      given name\n *\n * \\param ciphersuite_name SSL ciphersuite name\n *\n * \\return              the ID with the ciphersuite or 0 if not found\n */\nint mbedtls_ssl_get_ciphersuite_id( const char *ciphersuite_name );\n\n/**\n * \\brief          Initialize an SSL context\n *                 Just makes the context ready for mbedtls_ssl_setup() or\n *                 mbedtls_ssl_free()\n *\n * \\param ssl      SSL context\n */\nvoid mbedtls_ssl_init( mbedtls_ssl_context *ssl );\n\n/**\n * \\brief          Set up an SSL context for use\n *\n * \\note           No copy of the configuration context is made, it can be\n *                 shared by many mbedtls_ssl_context structures.\n *\n * \\warning        The conf structure will be accessed during the session.\n *                 It must not be modified or freed as long as the session\n *                 is active.\n *\n * \\warning        This function must be called exactly once per context.\n *                 Calling mbedtls_ssl_setup again is not supported, even\n *                 if no session is active.\n *\n * \\param ssl      SSL context\n * \\param conf     SSL configuration to use\n *\n * \\return         0 if successful, or MBEDTLS_ERR_SSL_ALLOC_FAILED if\n *                 memory allocation failed\n */\nint mbedtls_ssl_setup( mbedtls_ssl_context *ssl,\n                       const mbedtls_ssl_config *conf );\n\n/**\n * \\brief          Reset an already initialized SSL context for re-use\n *                 while retaining application-set variables, function\n *                 pointers and data.\n *\n * \\param ssl      SSL context\n * \\return         0 if successful, or MBEDTLS_ERR_SSL_ALLOC_FAILED,\n                   MBEDTLS_ERR_SSL_HW_ACCEL_FAILED or\n *                 MBEDTLS_ERR_SSL_COMPRESSION_FAILED\n */\nint mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl );\n\n/**\n * \\brief          Set the current endpoint type\n *\n * \\param conf     SSL configuration\n * \\param endpoint must be MBEDTLS_SSL_IS_CLIENT or MBEDTLS_SSL_IS_SERVER\n */\nvoid mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint );\n\n/**\n * \\brief           Set the transport type (TLS or DTLS).\n *                  Default: TLS\n *\n * \\note            For DTLS, you must either provide a recv callback that\n *                  doesn't block, or one that handles timeouts, see\n *                  \\c mbedtls_ssl_set_bio(). You also need to provide timer\n *                  callbacks with \\c mbedtls_ssl_set_timer_cb().\n *\n * \\param conf      SSL configuration\n * \\param transport transport type:\n *                  MBEDTLS_SSL_TRANSPORT_STREAM for TLS,\n *                  MBEDTLS_SSL_TRANSPORT_DATAGRAM for DTLS.\n */\nvoid mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport );\n\n/**\n * \\brief          Set the certificate verification mode\n *                 Default: NONE on server, REQUIRED on client\n *\n * \\param conf     SSL configuration\n * \\param authmode can be:\n *\n *  MBEDTLS_SSL_VERIFY_NONE:      peer certificate is not checked\n *                        (default on server)\n *                        (insecure on client)\n *\n *  MBEDTLS_SSL_VERIFY_OPTIONAL:  peer certificate is checked, however the\n *                        handshake continues even if verification failed;\n *                        mbedtls_ssl_get_verify_result() can be called after the\n *                        handshake is complete.\n *\n *  MBEDTLS_SSL_VERIFY_REQUIRED:  peer *must* present a valid certificate,\n *                        handshake is aborted if verification failed.\n *                        (default on client)\n *\n * \\note On client, MBEDTLS_SSL_VERIFY_REQUIRED is the recommended mode.\n * With MBEDTLS_SSL_VERIFY_OPTIONAL, the user needs to call mbedtls_ssl_get_verify_result() at\n * the right time(s), which may not be obvious, while REQUIRED always perform\n * the verification as soon as possible. For example, REQUIRED was protecting\n * against the \"triple handshake\" attack even before it was found.\n */\nvoid mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode );\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n/**\n * \\brief          Set the verification callback (Optional).\n *\n *                 If set, the verify callback is called for each\n *                 certificate in the chain. For implementation\n *                 information, please see \\c mbedtls_x509_crt_verify()\n *\n * \\param conf     SSL configuration\n * \\param f_vrfy   verification function\n * \\param p_vrfy   verification parameter\n */\nvoid mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf,\n                     int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),\n                     void *p_vrfy );\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n/**\n * \\brief          Set the random number generator callback\n *\n * \\param conf     SSL configuration\n * \\param f_rng    RNG function\n * \\param p_rng    RNG parameter\n */\nvoid mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf,\n                  int (*f_rng)(void *, unsigned char *, size_t),\n                  void *p_rng );\n\n/**\n * \\brief          Set the debug callback\n *\n *                 The callback has the following argument:\n *                 void *           opaque context for the callback\n *                 int              debug level\n *                 const char *     file name\n *                 int              line number\n *                 const char *     message\n *\n * \\param conf     SSL configuration\n * \\param f_dbg    debug function\n * \\param p_dbg    debug parameter\n */\nvoid mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf,\n                  void (*f_dbg)(void *, int, const char *, int, const char *),\n                  void  *p_dbg );\n\n/**\n * \\brief          Set the underlying BIO callbacks for write, read and\n *                 read-with-timeout.\n *\n * \\param ssl      SSL context\n * \\param p_bio    parameter (context) shared by BIO callbacks\n * \\param f_send   write callback\n * \\param f_recv   read callback\n * \\param f_recv_timeout blocking read callback with timeout.\n *\n * \\note           One of f_recv or f_recv_timeout can be NULL, in which case\n *                 the other is used. If both are non-NULL, f_recv_timeout is\n *                 used and f_recv is ignored (as if it were NULL).\n *\n * \\note           The two most common use cases are:\n *                 - non-blocking I/O, f_recv != NULL, f_recv_timeout == NULL\n *                 - blocking I/O, f_recv == NULL, f_recv_timout != NULL\n *\n * \\note           For DTLS, you need to provide either a non-NULL\n *                 f_recv_timeout callback, or a f_recv that doesn't block.\n *\n * \\note           See the documentations of \\c mbedtls_ssl_sent_t,\n *                 \\c mbedtls_ssl_recv_t and \\c mbedtls_ssl_recv_timeout_t for\n *                 the conventions those callbacks must follow.\n *\n * \\note           On some platforms, net_sockets.c provides\n *                 \\c mbedtls_net_send(), \\c mbedtls_net_recv() and\n *                 \\c mbedtls_net_recv_timeout() that are suitable to be used\n *                 here.\n */\nvoid mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl,\n                          void *p_bio,\n                          mbedtls_ssl_send_t *f_send,\n                          mbedtls_ssl_recv_t *f_recv,\n                          mbedtls_ssl_recv_timeout_t *f_recv_timeout );\n\n/**\n * \\brief          Set the timeout period for mbedtls_ssl_read()\n *                 (Default: no timeout.)\n *\n * \\param conf     SSL configuration context\n * \\param timeout  Timeout value in milliseconds.\n *                 Use 0 for no timeout (default).\n *\n * \\note           With blocking I/O, this will only work if a non-NULL\n *                 \\c f_recv_timeout was set with \\c mbedtls_ssl_set_bio().\n *                 With non-blocking I/O, this will only work if timer\n *                 callbacks were set with \\c mbedtls_ssl_set_timer_cb().\n *\n * \\note           With non-blocking I/O, you may also skip this function\n *                 altogether and handle timeouts at the application layer.\n */\nvoid mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout );\n\n/**\n * \\brief          Set the timer callbacks (Mandatory for DTLS.)\n *\n * \\param ssl      SSL context\n * \\param p_timer  parameter (context) shared by timer callbacks\n * \\param f_set_timer   set timer callback\n * \\param f_get_timer   get timer callback. Must return:\n *\n * \\note           See the documentation of \\c mbedtls_ssl_set_timer_t and\n *                 \\c mbedtls_ssl_get_timer_t for the conventions this pair of\n *                 callbacks must follow.\n *\n * \\note           On some platforms, timing.c provides\n *                 \\c mbedtls_timing_set_delay() and\n *                 \\c mbedtls_timing_get_delay() that are suitable for using\n *                 here, except if using an event-driven style.\n *\n * \\note           See also the \"DTLS tutorial\" article in our knowledge base.\n *                 https://tls.mbed.org/kb/how-to/dtls-tutorial\n */\nvoid mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl,\n                               void *p_timer,\n                               mbedtls_ssl_set_timer_t *f_set_timer,\n                               mbedtls_ssl_get_timer_t *f_get_timer );\n\n/**\n * \\brief           Callback type: generate and write session ticket\n *\n * \\note            This describes what a callback implementation should do.\n *                  This callback should generate an encrypted and\n *                  authenticated ticket for the session and write it to the\n *                  output buffer. Here, ticket means the opaque ticket part\n *                  of the NewSessionTicket structure of RFC 5077.\n *\n * \\param p_ticket  Context for the callback\n * \\param session   SSL session to be written in the ticket\n * \\param start     Start of the output buffer\n * \\param end       End of the output buffer\n * \\param tlen      On exit, holds the length written\n * \\param lifetime  On exit, holds the lifetime of the ticket in seconds\n *\n * \\return          0 if successful, or\n *                  a specific MBEDTLS_ERR_XXX code.\n */\ntypedef int mbedtls_ssl_ticket_write_t( void *p_ticket,\n                                        const mbedtls_ssl_session *session,\n                                        unsigned char *start,\n                                        const unsigned char *end,\n                                        size_t *tlen,\n                                        uint32_t *lifetime );\n\n#if defined(MBEDTLS_SSL_EXPORT_KEYS)\n/**\n * \\brief           Callback type: Export key block and master secret\n *\n * \\note            This is required for certain uses of TLS, e.g. EAP-TLS\n *                  (RFC 5216) and Thread. The key pointers are ephemeral and\n *                  therefore must not be stored. The master secret and keys\n *                  should not be used directly except as an input to a key\n *                  derivation function.\n *\n * \\param p_expkey  Context for the callback\n * \\param ms        Pointer to master secret (fixed length: 48 bytes)\n * \\param kb        Pointer to key block, see RFC 5246 section 6.3\n *                  (variable length: 2 * maclen + 2 * keylen + 2 * ivlen).\n * \\param maclen    MAC length\n * \\param keylen    Key length\n * \\param ivlen     IV length\n *\n * \\return          0 if successful, or\n *                  a specific MBEDTLS_ERR_XXX code.\n */\ntypedef int mbedtls_ssl_export_keys_t( void *p_expkey,\n                                const unsigned char *ms,\n                                const unsigned char *kb,\n                                size_t maclen,\n                                size_t keylen,\n                                size_t ivlen );\n#endif /* MBEDTLS_SSL_EXPORT_KEYS */\n\n/**\n * \\brief           Callback type: parse and load session ticket\n *\n * \\note            This describes what a callback implementation should do.\n *                  This callback should parse a session ticket as generated\n *                  by the corresponding mbedtls_ssl_ticket_write_t function,\n *                  and, if the ticket is authentic and valid, load the\n *                  session.\n *\n * \\note            The implementation is allowed to modify the first len\n *                  bytes of the input buffer, eg to use it as a temporary\n *                  area for the decrypted ticket contents.\n *\n * \\param p_ticket  Context for the callback\n * \\param session   SSL session to be loaded\n * \\param buf       Start of the buffer containing the ticket\n * \\param len       Length of the ticket.\n *\n * \\return          0 if successful, or\n *                  MBEDTLS_ERR_SSL_INVALID_MAC if not authentic, or\n *                  MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED if expired, or\n *                  any other non-zero code for other failures.\n */\ntypedef int mbedtls_ssl_ticket_parse_t( void *p_ticket,\n                                        mbedtls_ssl_session *session,\n                                        unsigned char *buf,\n                                        size_t len );\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_SRV_C)\n/**\n * \\brief           Configure SSL session ticket callbacks (server only).\n *                  (Default: none.)\n *\n * \\note            On server, session tickets are enabled by providing\n *                  non-NULL callbacks.\n *\n * \\note            On client, use \\c mbedtls_ssl_conf_session_tickets().\n *\n * \\param conf      SSL configuration context\n * \\param f_ticket_write    Callback for writing a ticket\n * \\param f_ticket_parse    Callback for parsing a ticket\n * \\param p_ticket          Context shared by the two callbacks\n */\nvoid mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf,\n        mbedtls_ssl_ticket_write_t *f_ticket_write,\n        mbedtls_ssl_ticket_parse_t *f_ticket_parse,\n        void *p_ticket );\n#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_SRV_C */\n\n#if defined(MBEDTLS_SSL_EXPORT_KEYS)\n/**\n * \\brief           Configure key export callback.\n *                  (Default: none.)\n *\n * \\note            See \\c mbedtls_ssl_export_keys_t.\n *\n * \\param conf      SSL configuration context\n * \\param f_export_keys     Callback for exporting keys\n * \\param p_export_keys     Context for the callback\n */\nvoid mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf,\n        mbedtls_ssl_export_keys_t *f_export_keys,\n        void *p_export_keys );\n#endif /* MBEDTLS_SSL_EXPORT_KEYS */\n\n#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)\n/**\n * \\brief           Configure asynchronous private key operation callbacks.\n *\n * \\param conf              SSL configuration context\n * \\param f_async_sign      Callback to start a signature operation. See\n *                          the description of ::mbedtls_ssl_async_sign_t\n *                          for more information. This may be \\c NULL if the\n *                          external processor does not support any signature\n *                          operation; in this case the private key object\n *                          associated with the certificate will be used.\n * \\param f_async_decrypt   Callback to start a decryption operation. See\n *                          the description of ::mbedtls_ssl_async_decrypt_t\n *                          for more information. This may be \\c NULL if the\n *                          external processor does not support any decryption\n *                          operation; in this case the private key object\n *                          associated with the certificate will be used.\n * \\param f_async_resume    Callback to resume an asynchronous operation. See\n *                          the description of ::mbedtls_ssl_async_resume_t\n *                          for more information. This may not be \\c NULL unless\n *                          \\p f_async_sign and \\p f_async_decrypt are both\n *                          \\c NULL.\n * \\param f_async_cancel    Callback to cancel an asynchronous operation. See\n *                          the description of ::mbedtls_ssl_async_cancel_t\n *                          for more information. This may be \\c NULL if\n *                          no cleanup is needed.\n * \\param config_data       A pointer to configuration data which can be\n *                          retrieved with\n *                          mbedtls_ssl_conf_get_async_config_data(). The\n *                          library stores this value without dereferencing it.\n */\nvoid mbedtls_ssl_conf_async_private_cb( mbedtls_ssl_config *conf,\n                                        mbedtls_ssl_async_sign_t *f_async_sign,\n                                        mbedtls_ssl_async_decrypt_t *f_async_decrypt,\n                                        mbedtls_ssl_async_resume_t *f_async_resume,\n                                        mbedtls_ssl_async_cancel_t *f_async_cancel,\n                                        void *config_data );\n\n/**\n * \\brief           Retrieve the configuration data set by\n *                  mbedtls_ssl_conf_async_private_cb().\n *\n * \\param conf      SSL configuration context\n * \\return          The configuration data set by\n *                  mbedtls_ssl_conf_async_private_cb().\n */\nvoid *mbedtls_ssl_conf_get_async_config_data( const mbedtls_ssl_config *conf );\n\n/**\n * \\brief           Retrieve the asynchronous operation user context.\n *\n * \\note            This function may only be called while a handshake\n *                  is in progress.\n *\n * \\param ssl       The SSL context to access.\n *\n * \\return          The asynchronous operation user context that was last\n *                  set during the current handshake. If\n *                  mbedtls_ssl_set_async_operation_data() has not yet been\n *                  called during the current handshake, this function returns\n *                  \\c NULL.\n */\nvoid *mbedtls_ssl_get_async_operation_data( const mbedtls_ssl_context *ssl );\n\n/**\n * \\brief           Retrieve the asynchronous operation user context.\n *\n * \\note            This function may only be called while a handshake\n *                  is in progress.\n *\n * \\param ssl       The SSL context to access.\n * \\param ctx       The new value of the asynchronous operation user context.\n *                  Call mbedtls_ssl_get_async_operation_data() later during the\n *                  same handshake to retrieve this value.\n */\nvoid mbedtls_ssl_set_async_operation_data( mbedtls_ssl_context *ssl,\n                                 void *ctx );\n#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */\n\n/**\n * \\brief          Callback type: generate a cookie\n *\n * \\param ctx      Context for the callback\n * \\param p        Buffer to write to,\n *                 must be updated to point right after the cookie\n * \\param end      Pointer to one past the end of the output buffer\n * \\param info     Client ID info that was passed to\n *                 \\c mbedtls_ssl_set_client_transport_id()\n * \\param ilen     Length of info in bytes\n *\n * \\return         The callback must return 0 on success,\n *                 or a negative error code.\n */\ntypedef int mbedtls_ssl_cookie_write_t( void *ctx,\n                                unsigned char **p, unsigned char *end,\n                                const unsigned char *info, size_t ilen );\n\n/**\n * \\brief          Callback type: verify a cookie\n *\n * \\param ctx      Context for the callback\n * \\param cookie   Cookie to verify\n * \\param clen     Length of cookie\n * \\param info     Client ID info that was passed to\n *                 \\c mbedtls_ssl_set_client_transport_id()\n * \\param ilen     Length of info in bytes\n *\n * \\return         The callback must return 0 if cookie is valid,\n *                 or a negative error code.\n */\ntypedef int mbedtls_ssl_cookie_check_t( void *ctx,\n                                const unsigned char *cookie, size_t clen,\n                                const unsigned char *info, size_t ilen );\n\n#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)\n/**\n * \\brief           Register callbacks for DTLS cookies\n *                  (Server only. DTLS only.)\n *\n *                  Default: dummy callbacks that fail, in order to force you to\n *                  register working callbacks (and initialize their context).\n *\n *                  To disable HelloVerifyRequest, register NULL callbacks.\n *\n * \\warning         Disabling hello verification allows your server to be used\n *                  for amplification in DoS attacks against other hosts.\n *                  Only disable if you known this can't happen in your\n *                  particular environment.\n *\n * \\note            See comments on \\c mbedtls_ssl_handshake() about handling\n *                  the MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED that is expected\n *                  on the first handshake attempt when this is enabled.\n *\n * \\note            This is also necessary to handle client reconnection from\n *                  the same port as described in RFC 6347 section 4.2.8 (only\n *                  the variant with cookies is supported currently). See\n *                  comments on \\c mbedtls_ssl_read() for details.\n *\n * \\param conf              SSL configuration\n * \\param f_cookie_write    Cookie write callback\n * \\param f_cookie_check    Cookie check callback\n * \\param p_cookie          Context for both callbacks\n */\nvoid mbedtls_ssl_conf_dtls_cookies( mbedtls_ssl_config *conf,\n                           mbedtls_ssl_cookie_write_t *f_cookie_write,\n                           mbedtls_ssl_cookie_check_t *f_cookie_check,\n                           void *p_cookie );\n\n/**\n * \\brief          Set client's transport-level identification info.\n *                 (Server only. DTLS only.)\n *\n *                 This is usually the IP address (and port), but could be\n *                 anything identify the client depending on the underlying\n *                 network stack. Used for HelloVerifyRequest with DTLS.\n *                 This is *not* used to route the actual packets.\n *\n * \\param ssl      SSL context\n * \\param info     Transport-level info identifying the client (eg IP + port)\n * \\param ilen     Length of info in bytes\n *\n * \\note           An internal copy is made, so the info buffer can be reused.\n *\n * \\return         0 on success,\n *                 MBEDTLS_ERR_SSL_BAD_INPUT_DATA if used on client,\n *                 MBEDTLS_ERR_SSL_ALLOC_FAILED if out of memory.\n */\nint mbedtls_ssl_set_client_transport_id( mbedtls_ssl_context *ssl,\n                                 const unsigned char *info,\n                                 size_t ilen );\n\n#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */\n\n#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)\n/**\n * \\brief          Enable or disable anti-replay protection for DTLS.\n *                 (DTLS only, no effect on TLS.)\n *                 Default: enabled.\n *\n * \\param conf     SSL configuration\n * \\param mode     MBEDTLS_SSL_ANTI_REPLAY_ENABLED or MBEDTLS_SSL_ANTI_REPLAY_DISABLED.\n *\n * \\warning        Disabling this is a security risk unless the application\n *                 protocol handles duplicated packets in a safe way. You\n *                 should not disable this without careful consideration.\n *                 However, if your application already detects duplicated\n *                 packets and needs information about them to adjust its\n *                 transmission strategy, then you'll want to disable this.\n */\nvoid mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode );\n#endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */\n\n#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)\n/**\n * \\brief          Set a limit on the number of records with a bad MAC\n *                 before terminating the connection.\n *                 (DTLS only, no effect on TLS.)\n *                 Default: 0 (disabled).\n *\n * \\param conf     SSL configuration\n * \\param limit    Limit, or 0 to disable.\n *\n * \\note           If the limit is N, then the connection is terminated when\n *                 the Nth non-authentic record is seen.\n *\n * \\note           Records with an invalid header are not counted, only the\n *                 ones going through the authentication-decryption phase.\n *\n * \\note           This is a security trade-off related to the fact that it's\n *                 often relatively easy for an active attacker ot inject UDP\n *                 datagrams. On one hand, setting a low limit here makes it\n *                 easier for such an attacker to forcibly terminated a\n *                 connection. On the other hand, a high limit or no limit\n *                 might make us waste resources checking authentication on\n *                 many bogus packets.\n */\nvoid mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit );\n#endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n/**\n * \\brief          Set retransmit timeout values for the DTLS handshake.\n *                 (DTLS only, no effect on TLS.)\n *\n * \\param conf     SSL configuration\n * \\param min      Initial timeout value in milliseconds.\n *                 Default: 1000 (1 second).\n * \\param max      Maximum timeout value in milliseconds.\n *                 Default: 60000 (60 seconds).\n *\n * \\note           Default values are from RFC 6347 section 4.2.4.1.\n *\n * \\note           The 'min' value should typically be slightly above the\n *                 expected round-trip time to your peer, plus whatever time\n *                 it takes for the peer to process the message. For example,\n *                 if your RTT is about 600ms and you peer needs up to 1s to\n *                 do the cryptographic operations in the handshake, then you\n *                 should set 'min' slightly above 1600. Lower values of 'min'\n *                 might cause spurious resends which waste network resources,\n *                 while larger value of 'min' will increase overall latency\n *                 on unreliable network links.\n *\n * \\note           The more unreliable your network connection is, the larger\n *                 your max / min ratio needs to be in order to achieve\n *                 reliable handshakes.\n *\n * \\note           Messages are retransmitted up to log2(ceil(max/min)) times.\n *                 For example, if min = 1s and max = 5s, the retransmit plan\n *                 goes: send ... 1s -> resend ... 2s -> resend ... 4s ->\n *                 resend ... 5s -> give up and return a timeout error.\n */\nvoid mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf, uint32_t min, uint32_t max );\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n\n#if defined(MBEDTLS_SSL_SRV_C)\n/**\n * \\brief          Set the session cache callbacks (server-side only)\n *                 If not set, no session resuming is done (except if session\n *                 tickets are enabled too).\n *\n *                 The session cache has the responsibility to check for stale\n *                 entries based on timeout. See RFC 5246 for recommendations.\n *\n *                 Warning: session.peer_cert is cleared by the SSL/TLS layer on\n *                 connection shutdown, so do not cache the pointer! Either set\n *                 it to NULL or make a full copy of the certificate.\n *\n *                 The get callback is called once during the initial handshake\n *                 to enable session resuming. The get function has the\n *                 following parameters: (void *parameter, mbedtls_ssl_session *session)\n *                 If a valid entry is found, it should fill the master of\n *                 the session object with the cached values and return 0,\n *                 return 1 otherwise. Optionally peer_cert can be set as well\n *                 if it is properly present in cache entry.\n *\n *                 The set callback is called once during the initial handshake\n *                 to enable session resuming after the entire handshake has\n *                 been finished. The set function has the following parameters:\n *                 (void *parameter, const mbedtls_ssl_session *session). The function\n *                 should create a cache entry for future retrieval based on\n *                 the data in the session structure and should keep in mind\n *                 that the mbedtls_ssl_session object presented (and all its referenced\n *                 data) is cleared by the SSL/TLS layer when the connection is\n *                 terminated. It is recommended to add metadata to determine if\n *                 an entry is still valid in the future. Return 0 if\n *                 successfully cached, return 1 otherwise.\n *\n * \\param conf           SSL configuration\n * \\param p_cache        parmater (context) for both callbacks\n * \\param f_get_cache    session get callback\n * \\param f_set_cache    session set callback\n */\nvoid mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf,\n        void *p_cache,\n        int (*f_get_cache)(void *, mbedtls_ssl_session *),\n        int (*f_set_cache)(void *, const mbedtls_ssl_session *) );\n#endif /* MBEDTLS_SSL_SRV_C */\n\n#if defined(MBEDTLS_SSL_CLI_C)\n/**\n * \\brief          Request resumption of session (client-side only)\n *                 Session data is copied from presented session structure.\n *\n * \\param ssl      SSL context\n * \\param session  session context\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed,\n *                 MBEDTLS_ERR_SSL_BAD_INPUT_DATA if used server-side or\n *                 arguments are otherwise invalid\n *\n * \\sa             mbedtls_ssl_get_session()\n */\nint mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session );\n#endif /* MBEDTLS_SSL_CLI_C */\n\n/**\n * \\brief               Set the list of allowed ciphersuites and the preference\n *                      order. First in the list has the highest preference.\n *                      (Overrides all version-specific lists)\n *\n *                      The ciphersuites array is not copied, and must remain\n *                      valid for the lifetime of the ssl_config.\n *\n *                      Note: The server uses its own preferences\n *                      over the preference of the client unless\n *                      MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE is defined!\n *\n * \\param conf          SSL configuration\n * \\param ciphersuites  0-terminated list of allowed ciphersuites\n */\nvoid mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf,\n                                   const int *ciphersuites );\n\n/**\n * \\brief               Set the list of allowed ciphersuites and the\n *                      preference order for a specific version of the protocol.\n *                      (Only useful on the server side)\n *\n *                      The ciphersuites array is not copied, and must remain\n *                      valid for the lifetime of the ssl_config.\n *\n * \\param conf          SSL configuration\n * \\param ciphersuites  0-terminated list of allowed ciphersuites\n * \\param major         Major version number (only MBEDTLS_SSL_MAJOR_VERSION_3\n *                      supported)\n * \\param minor         Minor version number (MBEDTLS_SSL_MINOR_VERSION_0,\n *                      MBEDTLS_SSL_MINOR_VERSION_1 and MBEDTLS_SSL_MINOR_VERSION_2,\n *                      MBEDTLS_SSL_MINOR_VERSION_3 supported)\n *\n * \\note                With DTLS, use MBEDTLS_SSL_MINOR_VERSION_2 for DTLS 1.0\n *                      and MBEDTLS_SSL_MINOR_VERSION_3 for DTLS 1.2\n */\nvoid mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf,\n                                       const int *ciphersuites,\n                                       int major, int minor );\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n/**\n * \\brief          Set the X.509 security profile used for verification\n *\n * \\note           The restrictions are enforced for all certificates in the\n *                 chain. However, signatures in the handshake are not covered\n *                 by this setting but by \\b mbedtls_ssl_conf_sig_hashes().\n *\n * \\param conf     SSL configuration\n * \\param profile  Profile to use\n */\nvoid mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf,\n                                    const mbedtls_x509_crt_profile *profile );\n\n/**\n * \\brief          Set the data required to verify peer certificate\n *\n * \\note           See \\c mbedtls_x509_crt_verify() for notes regarding the\n *                 parameters ca_chain (maps to trust_ca for that function)\n *                 and ca_crl.\n *\n * \\param conf     SSL configuration\n * \\param ca_chain trusted CA chain (meaning all fully trusted top-level CAs)\n * \\param ca_crl   trusted CA CRLs\n */\nvoid mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf,\n                               mbedtls_x509_crt *ca_chain,\n                               mbedtls_x509_crl *ca_crl );\n\n/**\n * \\brief          Set own certificate chain and private key\n *\n * \\note           own_cert should contain in order from the bottom up your\n *                 certificate chain. The top certificate (self-signed)\n *                 can be omitted.\n *\n * \\note           On server, this function can be called multiple times to\n *                 provision more than one cert/key pair (eg one ECDSA, one\n *                 RSA with SHA-256, one RSA with SHA-1). An adequate\n *                 certificate will be selected according to the client's\n *                 advertised capabilities. In case mutliple certificates are\n *                 adequate, preference is given to the one set by the first\n *                 call to this function, then second, etc.\n *\n * \\note           On client, only the first call has any effect. That is,\n *                 only one client certificate can be provisioned. The\n *                 server's preferences in its CertficateRequest message will\n *                 be ignored and our only cert will be sent regardless of\n *                 whether it matches those preferences - the server can then\n *                 decide what it wants to do with it.\n *\n * \\param conf     SSL configuration\n * \\param own_cert own public certificate chain\n * \\param pk_key   own private key\n *\n * \\return         0 on success or MBEDTLS_ERR_SSL_ALLOC_FAILED\n */\nint mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,\n                              mbedtls_x509_crt *own_cert,\n                              mbedtls_pk_context *pk_key );\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)\n/**\n * \\brief          Set the Pre Shared Key (PSK) and the expected identity name\n *\n * \\note           This is mainly useful for clients. Servers will usually\n *                 want to use \\c mbedtls_ssl_conf_psk_cb() instead.\n *\n * \\note           Currently clients can only register one pre-shared key.\n *                 In other words, the servers' identity hint is ignored.\n *                 Support for setting multiple PSKs on clients and selecting\n *                 one based on the identity hint is not a planned feature but\n *                 feedback is welcomed.\n *\n * \\param conf     SSL configuration\n * \\param psk      pointer to the pre-shared key\n * \\param psk_len  pre-shared key length\n * \\param psk_identity      pointer to the pre-shared key identity\n * \\param psk_identity_len  identity key length\n *\n * \\return         0 if successful or MBEDTLS_ERR_SSL_ALLOC_FAILED\n */\nint mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,\n                const unsigned char *psk, size_t psk_len,\n                const unsigned char *psk_identity, size_t psk_identity_len );\n\n\n/**\n * \\brief          Set the Pre Shared Key (PSK) for the current handshake\n *\n * \\note           This should only be called inside the PSK callback,\n *                 ie the function passed to \\c mbedtls_ssl_conf_psk_cb().\n *\n * \\param ssl      SSL context\n * \\param psk      pointer to the pre-shared key\n * \\param psk_len  pre-shared key length\n *\n * \\return         0 if successful or MBEDTLS_ERR_SSL_ALLOC_FAILED\n */\nint mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl,\n                            const unsigned char *psk, size_t psk_len );\n\n/**\n * \\brief          Set the PSK callback (server-side only).\n *\n *                 If set, the PSK callback is called for each\n *                 handshake where a PSK ciphersuite was negotiated.\n *                 The caller provides the identity received and wants to\n *                 receive the actual PSK data and length.\n *\n *                 The callback has the following parameters: (void *parameter,\n *                 mbedtls_ssl_context *ssl, const unsigned char *psk_identity,\n *                 size_t identity_len)\n *                 If a valid PSK identity is found, the callback should use\n *                 \\c mbedtls_ssl_set_hs_psk() on the ssl context to set the\n *                 correct PSK and return 0.\n *                 Any other return value will result in a denied PSK identity.\n *\n * \\note           If you set a PSK callback using this function, then you\n *                 don't need to set a PSK key and identity using\n *                 \\c mbedtls_ssl_conf_psk().\n *\n * \\param conf     SSL configuration\n * \\param f_psk    PSK identity function\n * \\param p_psk    PSK identity parameter\n */\nvoid mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf,\n                     int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,\n                                  size_t),\n                     void *p_psk );\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */\n\n#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\n\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n#define MBEDTLS_DEPRECATED    __attribute__((deprecated))\n#else\n#define MBEDTLS_DEPRECATED\n#endif\n\n/**\n * \\brief          Set the Diffie-Hellman public P and G values,\n *                 read as hexadecimal strings (server-side only)\n *                 (Default values: MBEDTLS_DHM_RFC3526_MODP_2048_[PG])\n *\n * \\param conf     SSL configuration\n * \\param dhm_P    Diffie-Hellman-Merkle modulus\n * \\param dhm_G    Diffie-Hellman-Merkle generator\n *\n * \\deprecated     Superseded by \\c mbedtls_ssl_conf_dh_param_bin.\n *\n * \\return         0 if successful\n */\nMBEDTLS_DEPRECATED int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf,\n                                                  const char *dhm_P,\n                                                  const char *dhm_G );\n\n#endif /* MBEDTLS_DEPRECATED_REMOVED */\n\n/**\n * \\brief          Set the Diffie-Hellman public P and G values\n *                 from big-endian binary presentations.\n *                 (Default values: MBEDTLS_DHM_RFC3526_MODP_2048_[PG]_BIN)\n *\n * \\param conf     SSL configuration\n * \\param dhm_P    Diffie-Hellman-Merkle modulus in big-endian binary form\n * \\param P_len    Length of DHM modulus\n * \\param dhm_G    Diffie-Hellman-Merkle generator in big-endian binary form\n * \\param G_len    Length of DHM generator\n *\n * \\return         0 if successful\n */\nint mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf,\n                                   const unsigned char *dhm_P, size_t P_len,\n                                   const unsigned char *dhm_G,  size_t G_len );\n\n/**\n * \\brief          Set the Diffie-Hellman public P and G values,\n *                 read from existing context (server-side only)\n *\n * \\param conf     SSL configuration\n * \\param dhm_ctx  Diffie-Hellman-Merkle context\n *\n * \\return         0 if successful\n */\nint mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx );\n#endif /* MBEDTLS_DHM_C && defined(MBEDTLS_SSL_SRV_C) */\n\n#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)\n/**\n * \\brief          Set the minimum length for Diffie-Hellman parameters.\n *                 (Client-side only.)\n *                 (Default: 1024 bits.)\n *\n * \\param conf     SSL configuration\n * \\param bitlen   Minimum bit length of the DHM prime\n */\nvoid mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf,\n                                      unsigned int bitlen );\n#endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */\n\n#if defined(MBEDTLS_ECP_C)\n/**\n * \\brief          Set the allowed curves in order of preference.\n *                 (Default: all defined curves.)\n *\n *                 On server: this only affects selection of the ECDHE curve;\n *                 the curves used for ECDH and ECDSA are determined by the\n *                 list of available certificates instead.\n *\n *                 On client: this affects the list of curves offered for any\n *                 use. The server can override our preference order.\n *\n *                 Both sides: limits the set of curves accepted for use in\n *                 ECDHE and in the peer's end-entity certificate.\n *\n * \\note           This has no influence on which curves are allowed inside the\n *                 certificate chains, see \\c mbedtls_ssl_conf_cert_profile()\n *                 for that. For the end-entity certificate however, the key\n *                 will be accepted only if it is allowed both by this list\n *                 and by the cert profile.\n *\n * \\note           This list should be ordered by decreasing preference\n *                 (preferred curve first).\n *\n * \\param conf     SSL configuration\n * \\param curves   Ordered list of allowed curves,\n *                 terminated by MBEDTLS_ECP_DP_NONE.\n */\nvoid mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf,\n                              const mbedtls_ecp_group_id *curves );\n#endif /* MBEDTLS_ECP_C */\n\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n/**\n * \\brief          Set the allowed hashes for signatures during the handshake.\n *                 (Default: all available hashes except MD5.)\n *\n * \\note           This only affects which hashes are offered and can be used\n *                 for signatures during the handshake. Hashes for message\n *                 authentication and the TLS PRF are controlled by the\n *                 ciphersuite, see \\c mbedtls_ssl_conf_ciphersuites(). Hashes\n *                 used for certificate signature are controlled by the\n *                 verification profile, see \\c mbedtls_ssl_conf_cert_profile().\n *\n * \\note           This list should be ordered by decreasing preference\n *                 (preferred hash first).\n *\n * \\param conf     SSL configuration\n * \\param hashes   Ordered list of allowed signature hashes,\n *                 terminated by \\c MBEDTLS_MD_NONE.\n */\nvoid mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,\n                                  const int *hashes );\n#endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n/**\n * \\brief          Set or reset the hostname to check against the received\n *                 server certificate. It sets the ServerName TLS extension,\n *                 too, if that extension is enabled. (client-side only)\n *\n * \\param ssl      SSL context\n * \\param hostname the server hostname, may be NULL to clear hostname\n\n * \\note           Maximum hostname length MBEDTLS_SSL_MAX_HOST_NAME_LEN.\n *\n * \\return         0 if successful, MBEDTLS_ERR_SSL_ALLOC_FAILED on\n *                 allocation failure, MBEDTLS_ERR_SSL_BAD_INPUT_DATA on\n *                 too long input hostname.\n *\n *                 Hostname set to the one provided on success (cleared\n *                 when NULL). On allocation failure hostname is cleared.\n *                 On too long input failure, old hostname is unchanged.\n */\nint mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname );\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\n/**\n * \\brief          Set own certificate and key for the current handshake\n *\n * \\note           Same as \\c mbedtls_ssl_conf_own_cert() but for use within\n *                 the SNI callback.\n *\n * \\param ssl      SSL context\n * \\param own_cert own public certificate chain\n * \\param pk_key   own private key\n *\n * \\return         0 on success or MBEDTLS_ERR_SSL_ALLOC_FAILED\n */\nint mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl,\n                                 mbedtls_x509_crt *own_cert,\n                                 mbedtls_pk_context *pk_key );\n\n/**\n * \\brief          Set the data required to verify peer certificate for the\n *                 current handshake\n *\n * \\note           Same as \\c mbedtls_ssl_conf_ca_chain() but for use within\n *                 the SNI callback.\n *\n * \\param ssl      SSL context\n * \\param ca_chain trusted CA chain (meaning all fully trusted top-level CAs)\n * \\param ca_crl   trusted CA CRLs\n */\nvoid mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl,\n                                  mbedtls_x509_crt *ca_chain,\n                                  mbedtls_x509_crl *ca_crl );\n\n/**\n * \\brief          Set authmode for the current handshake.\n *\n * \\note           Same as \\c mbedtls_ssl_conf_authmode() but for use within\n *                 the SNI callback.\n *\n * \\param ssl      SSL context\n * \\param authmode MBEDTLS_SSL_VERIFY_NONE, MBEDTLS_SSL_VERIFY_OPTIONAL or\n *                 MBEDTLS_SSL_VERIFY_REQUIRED\n */\nvoid mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl,\n                                  int authmode );\n\n/**\n * \\brief          Set server side ServerName TLS extension callback\n *                 (optional, server-side only).\n *\n *                 If set, the ServerName callback is called whenever the\n *                 server receives a ServerName TLS extension from the client\n *                 during a handshake. The ServerName callback has the\n *                 following parameters: (void *parameter, mbedtls_ssl_context *ssl,\n *                 const unsigned char *hostname, size_t len). If a suitable\n *                 certificate is found, the callback must set the\n *                 certificate(s) and key(s) to use with \\c\n *                 mbedtls_ssl_set_hs_own_cert() (can be called repeatedly),\n *                 and may optionally adjust the CA and associated CRL with \\c\n *                 mbedtls_ssl_set_hs_ca_chain() as well as the client\n *                 authentication mode with \\c mbedtls_ssl_set_hs_authmode(),\n *                 then must return 0. If no matching name is found, the\n *                 callback must either set a default cert, or\n *                 return non-zero to abort the handshake at this point.\n *\n * \\param conf     SSL configuration\n * \\param f_sni    verification function\n * \\param p_sni    verification parameter\n */\nvoid mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf,\n                  int (*f_sni)(void *, mbedtls_ssl_context *, const unsigned char *,\n                               size_t),\n                  void *p_sni );\n#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n/**\n * \\brief          Set the EC J-PAKE password for current handshake.\n *\n * \\note           An internal copy is made, and destroyed as soon as the\n *                 handshake is completed, or when the SSL context is reset or\n *                 freed.\n *\n * \\note           The SSL context needs to be already set up. The right place\n *                 to call this function is between \\c mbedtls_ssl_setup() or\n *                 \\c mbedtls_ssl_reset() and \\c mbedtls_ssl_handshake().\n *\n * \\param ssl      SSL context\n * \\param pw       EC J-PAKE password (pre-shared secret)\n * \\param pw_len   length of pw in bytes\n *\n * \\return         0 on success, or a negative error code.\n */\nint mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,\n                                         const unsigned char *pw,\n                                         size_t pw_len );\n#endif /*MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n\n#if defined(MBEDTLS_SSL_ALPN)\n/**\n * \\brief          Set the supported Application Layer Protocols.\n *\n * \\param conf     SSL configuration\n * \\param protos   Pointer to a NULL-terminated list of supported protocols,\n *                 in decreasing preference order. The pointer to the list is\n *                 recorded by the library for later reference as required, so\n *                 the lifetime of the table must be atleast as long as the\n *                 lifetime of the SSL configuration structure.\n *\n * \\return         0 on success, or MBEDTLS_ERR_SSL_BAD_INPUT_DATA.\n */\nint mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos );\n\n/**\n * \\brief          Get the name of the negotiated Application Layer Protocol.\n *                 This function should be called after the handshake is\n *                 completed.\n *\n * \\param ssl      SSL context\n *\n * \\return         Protcol name, or NULL if no protocol was negotiated.\n */\nconst char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl );\n#endif /* MBEDTLS_SSL_ALPN */\n\n/**\n * \\brief          Set the maximum supported version sent from the client side\n *                 and/or accepted at the server side\n *                 (Default: MBEDTLS_SSL_MAX_MAJOR_VERSION, MBEDTLS_SSL_MAX_MINOR_VERSION)\n *\n * \\note           This ignores ciphersuites from higher versions.\n *\n * \\note           With DTLS, use MBEDTLS_SSL_MINOR_VERSION_2 for DTLS 1.0 and\n *                 MBEDTLS_SSL_MINOR_VERSION_3 for DTLS 1.2\n *\n * \\param conf     SSL configuration\n * \\param major    Major version number (only MBEDTLS_SSL_MAJOR_VERSION_3 supported)\n * \\param minor    Minor version number (MBEDTLS_SSL_MINOR_VERSION_0,\n *                 MBEDTLS_SSL_MINOR_VERSION_1 and MBEDTLS_SSL_MINOR_VERSION_2,\n *                 MBEDTLS_SSL_MINOR_VERSION_3 supported)\n */\nvoid mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor );\n\n/**\n * \\brief          Set the minimum accepted SSL/TLS protocol version\n *                 (Default: TLS 1.0)\n *\n * \\note           Input outside of the SSL_MAX_XXXXX_VERSION and\n *                 SSL_MIN_XXXXX_VERSION range is ignored.\n *\n * \\note           MBEDTLS_SSL_MINOR_VERSION_0 (SSL v3) should be avoided.\n *\n * \\note           With DTLS, use MBEDTLS_SSL_MINOR_VERSION_2 for DTLS 1.0 and\n *                 MBEDTLS_SSL_MINOR_VERSION_3 for DTLS 1.2\n *\n * \\param conf     SSL configuration\n * \\param major    Major version number (only MBEDTLS_SSL_MAJOR_VERSION_3 supported)\n * \\param minor    Minor version number (MBEDTLS_SSL_MINOR_VERSION_0,\n *                 MBEDTLS_SSL_MINOR_VERSION_1 and MBEDTLS_SSL_MINOR_VERSION_2,\n *                 MBEDTLS_SSL_MINOR_VERSION_3 supported)\n */\nvoid mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor );\n\n#if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)\n/**\n * \\brief          Set the fallback flag (client-side only).\n *                 (Default: MBEDTLS_SSL_IS_NOT_FALLBACK).\n *\n * \\note           Set to MBEDTLS_SSL_IS_FALLBACK when preparing a fallback\n *                 connection, that is a connection with max_version set to a\n *                 lower value than the value you're willing to use. Such\n *                 fallback connections are not recommended but are sometimes\n *                 necessary to interoperate with buggy (version-intolerant)\n *                 servers.\n *\n * \\warning        You should NOT set this to MBEDTLS_SSL_IS_FALLBACK for\n *                 non-fallback connections! This would appear to work for a\n *                 while, then cause failures when the server is upgraded to\n *                 support a newer TLS version.\n *\n * \\param conf     SSL configuration\n * \\param fallback MBEDTLS_SSL_IS_NOT_FALLBACK or MBEDTLS_SSL_IS_FALLBACK\n */\nvoid mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback );\n#endif /* MBEDTLS_SSL_FALLBACK_SCSV && MBEDTLS_SSL_CLI_C */\n\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\n/**\n * \\brief           Enable or disable Encrypt-then-MAC\n *                  (Default: MBEDTLS_SSL_ETM_ENABLED)\n *\n * \\note            This should always be enabled, it is a security\n *                  improvement, and should not cause any interoperability\n *                  issue (used only if the peer supports it too).\n *\n * \\param conf      SSL configuration\n * \\param etm       MBEDTLS_SSL_ETM_ENABLED or MBEDTLS_SSL_ETM_DISABLED\n */\nvoid mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm );\n#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */\n\n#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)\n/**\n * \\brief           Enable or disable Extended Master Secret negotiation.\n *                  (Default: MBEDTLS_SSL_EXTENDED_MS_ENABLED)\n *\n * \\note            This should always be enabled, it is a security fix to the\n *                  protocol, and should not cause any interoperability issue\n *                  (used only if the peer supports it too).\n *\n * \\param conf      SSL configuration\n * \\param ems       MBEDTLS_SSL_EXTENDED_MS_ENABLED or MBEDTLS_SSL_EXTENDED_MS_DISABLED\n */\nvoid mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems );\n#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */\n\n#if defined(MBEDTLS_ARC4_C)\n/**\n * \\brief          Disable or enable support for RC4\n *                 (Default: MBEDTLS_SSL_ARC4_DISABLED)\n *\n * \\warning        Use of RC4 in DTLS/TLS has been prohibited by RFC 7465\n *                 for security reasons. Use at your own risk.\n *\n * \\note           This function is deprecated and will likely be removed in\n *                 a future version of the library.\n *                 RC4 is disabled by default at compile time and needs to be\n *                 actively enabled for use with legacy systems.\n *\n * \\param conf     SSL configuration\n * \\param arc4     MBEDTLS_SSL_ARC4_ENABLED or MBEDTLS_SSL_ARC4_DISABLED\n */\nvoid mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 );\n#endif /* MBEDTLS_ARC4_C */\n\n#if defined(MBEDTLS_SSL_SRV_C)\n/**\n * \\brief          Whether to send a list of acceptable CAs in\n *                 CertificateRequest messages.\n *                 (Default: do send)\n *\n * \\param conf     SSL configuration\n * \\param cert_req_ca_list   MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED or\n *                          MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED\n */\nvoid mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf,\n                                          char cert_req_ca_list );\n#endif /* MBEDTLS_SSL_SRV_C */\n\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\n/**\n * \\brief          Set the maximum fragment length to emit and/or negotiate\n *                 (Default: the smaller of MBEDTLS_SSL_IN_CONTENT_LEN and\n *                 MBEDTLS_SSL_OUT_CONTENT_LEN, usually 2^14 bytes)\n *                 (Server: set maximum fragment length to emit,\n *                 usually negotiated by the client during handshake\n *                 (Client: set maximum fragment length to emit *and*\n *                 negotiate with the server during handshake)\n *\n * \\param conf     SSL configuration\n * \\param mfl_code Code for maximum fragment length (allowed values:\n *                 MBEDTLS_SSL_MAX_FRAG_LEN_512,  MBEDTLS_SSL_MAX_FRAG_LEN_1024,\n *                 MBEDTLS_SSL_MAX_FRAG_LEN_2048, MBEDTLS_SSL_MAX_FRAG_LEN_4096)\n *\n * \\return         0 if successful or MBEDTLS_ERR_SSL_BAD_INPUT_DATA\n */\nint mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code );\n#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */\n\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)\n/**\n * \\brief          Activate negotiation of truncated HMAC\n *                 (Default: MBEDTLS_SSL_TRUNC_HMAC_DISABLED)\n *\n * \\param conf     SSL configuration\n * \\param truncate Enable or disable (MBEDTLS_SSL_TRUNC_HMAC_ENABLED or\n *                                    MBEDTLS_SSL_TRUNC_HMAC_DISABLED)\n */\nvoid mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate );\n#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */\n\n#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)\n/**\n * \\brief          Enable / Disable 1/n-1 record splitting\n *                 (Default: MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED)\n *\n * \\note           Only affects SSLv3 and TLS 1.0, not higher versions.\n *                 Does not affect non-CBC ciphersuites in any version.\n *\n * \\param conf     SSL configuration\n * \\param split    MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED or\n *                 MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED\n */\nvoid mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split );\n#endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)\n/**\n * \\brief          Enable / Disable session tickets (client only).\n *                 (Default: MBEDTLS_SSL_SESSION_TICKETS_ENABLED.)\n *\n * \\note           On server, use \\c mbedtls_ssl_conf_session_tickets_cb().\n *\n * \\param conf     SSL configuration\n * \\param use_tickets   Enable or disable (MBEDTLS_SSL_SESSION_TICKETS_ENABLED or\n *                                         MBEDTLS_SSL_SESSION_TICKETS_DISABLED)\n */\nvoid mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets );\n#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n/**\n * \\brief          Enable / Disable renegotiation support for connection when\n *                 initiated by peer\n *                 (Default: MBEDTLS_SSL_RENEGOTIATION_DISABLED)\n *\n * \\warning        It is recommended to always disable renegotation unless you\n *                 know you need it and you know what you're doing. In the\n *                 past, there have been several issues associated with\n *                 renegotiation or a poor understanding of its properties.\n *\n * \\note           Server-side, enabling renegotiation also makes the server\n *                 susceptible to a resource DoS by a malicious client.\n *\n * \\param conf    SSL configuration\n * \\param renegotiation     Enable or disable (MBEDTLS_SSL_RENEGOTIATION_ENABLED or\n *                                             MBEDTLS_SSL_RENEGOTIATION_DISABLED)\n */\nvoid mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation );\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n\n/**\n * \\brief          Prevent or allow legacy renegotiation.\n *                 (Default: MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION)\n *\n *                 MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION allows connections to\n *                 be established even if the peer does not support\n *                 secure renegotiation, but does not allow renegotiation\n *                 to take place if not secure.\n *                 (Interoperable and secure option)\n *\n *                 MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION allows renegotiations\n *                 with non-upgraded peers. Allowing legacy renegotiation\n *                 makes the connection vulnerable to specific man in the\n *                 middle attacks. (See RFC 5746)\n *                 (Most interoperable and least secure option)\n *\n *                 MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE breaks off connections\n *                 if peer does not support secure renegotiation. Results\n *                 in interoperability issues with non-upgraded peers\n *                 that do not support renegotiation altogether.\n *                 (Most secure option, interoperability issues)\n *\n * \\param conf     SSL configuration\n * \\param allow_legacy  Prevent or allow (SSL_NO_LEGACY_RENEGOTIATION,\n *                                        SSL_ALLOW_LEGACY_RENEGOTIATION or\n *                                        MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE)\n */\nvoid mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy );\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n/**\n * \\brief          Enforce renegotiation requests.\n *                 (Default: enforced, max_records = 16)\n *\n *                 When we request a renegotiation, the peer can comply or\n *                 ignore the request. This function allows us to decide\n *                 whether to enforce our renegotiation requests by closing\n *                 the connection if the peer doesn't comply.\n *\n *                 However, records could already be in transit from the peer\n *                 when the request is emitted. In order to increase\n *                 reliability, we can accept a number of records before the\n *                 expected handshake records.\n *\n *                 The optimal value is highly dependent on the specific usage\n *                 scenario.\n *\n * \\note           With DTLS and server-initiated renegotiation, the\n *                 HelloRequest is retransmited every time mbedtls_ssl_read() times\n *                 out or receives Application Data, until:\n *                 - max_records records have beens seen, if it is >= 0, or\n *                 - the number of retransmits that would happen during an\n *                 actual handshake has been reached.\n *                 Please remember the request might be lost a few times\n *                 if you consider setting max_records to a really low value.\n *\n * \\warning        On client, the grace period can only happen during\n *                 mbedtls_ssl_read(), as opposed to mbedtls_ssl_write() and mbedtls_ssl_renegotiate()\n *                 which always behave as if max_record was 0. The reason is,\n *                 if we receive application data from the server, we need a\n *                 place to write it, which only happens during mbedtls_ssl_read().\n *\n * \\param conf     SSL configuration\n * \\param max_records Use MBEDTLS_SSL_RENEGOTIATION_NOT_ENFORCED if you don't want to\n *                 enforce renegotiation, or a non-negative value to enforce\n *                 it but allow for a grace period of max_records records.\n */\nvoid mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records );\n\n/**\n * \\brief          Set record counter threshold for periodic renegotiation.\n *                 (Default: 2^48 - 1)\n *\n *                 Renegotiation is automatically triggered when a record\n *                 counter (outgoing or ingoing) crosses the defined\n *                 threshold. The default value is meant to prevent the\n *                 connection from being closed when the counter is about to\n *                 reached its maximal value (it is not allowed to wrap).\n *\n *                 Lower values can be used to enforce policies such as \"keys\n *                 must be refreshed every N packets with cipher X\".\n *\n *                 The renegotiation period can be disabled by setting\n *                 conf->disable_renegotiation to\n *                 MBEDTLS_SSL_RENEGOTIATION_DISABLED.\n *\n * \\note           When the configured transport is\n *                 MBEDTLS_SSL_TRANSPORT_DATAGRAM the maximum renegotiation\n *                 period is 2^48 - 1, and for MBEDTLS_SSL_TRANSPORT_STREAM,\n *                 the maximum renegotiation period is 2^64 - 1.\n *\n * \\param conf     SSL configuration\n * \\param period   The threshold value: a big-endian 64-bit number.\n */\nvoid mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf,\n                                   const unsigned char period[8] );\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n\n/**\n * \\brief          Check if there is data already read from the\n *                 underlying transport but not yet processed.\n *\n * \\param ssl      SSL context\n *\n * \\return         0 if nothing's pending, 1 otherwise.\n *\n * \\note           This is different in purpose and behaviour from\n *                 \\c mbedtls_ssl_get_bytes_avail in that it considers\n *                 any kind of unprocessed data, not only unread\n *                 application data. If \\c mbedtls_ssl_get_bytes\n *                 returns a non-zero value, this function will\n *                 also signal pending data, but the converse does\n *                 not hold. For example, in DTLS there might be\n *                 further records waiting to be processed from\n *                 the current underlying transport's datagram.\n *\n * \\note           If this function returns 1 (data pending), this\n *                 does not imply that a subsequent call to\n *                 \\c mbedtls_ssl_read will provide any data;\n *                 e.g., the unprocessed data might turn out\n *                 to be an alert or a handshake message.\n *\n * \\note           This function is useful in the following situation:\n *                 If the SSL/TLS module successfully returns from an\n *                 operation - e.g. a handshake or an application record\n *                 read - and you're awaiting incoming data next, you\n *                 must not immediately idle on the underlying transport\n *                 to have data ready, but you need to check the value\n *                 of this function first. The reason is that the desired\n *                 data might already be read but not yet processed.\n *                 If, in contrast, a previous call to the SSL/TLS module\n *                 returned MBEDTLS_ERR_SSL_WANT_READ, it is not necessary\n *                 to call this function, as the latter error code entails\n *                 that all internal data has been processed.\n *\n */\nint mbedtls_ssl_check_pending( const mbedtls_ssl_context *ssl );\n\n/**\n * \\brief          Return the number of application data bytes\n *                 remaining to be read from the current record.\n *\n * \\param ssl      SSL context\n *\n * \\return         How many bytes are available in the application\n *                 data record read buffer.\n *\n * \\note           When working over a datagram transport, this is\n *                 useful to detect the current datagram's boundary\n *                 in case \\c mbedtls_ssl_read has written the maximal\n *                 amount of data fitting into the input buffer.\n *\n */\nsize_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl );\n\n/**\n * \\brief          Return the result of the certificate verification\n *\n * \\param ssl      SSL context\n *\n * \\return         0 if successful,\n *                 -1 if result is not available (eg because the handshake was\n *                 aborted too early), or\n *                 a combination of BADCERT_xxx and BADCRL_xxx flags, see\n *                 x509.h\n */\nuint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl );\n\n/**\n * \\brief          Return the name of the current ciphersuite\n *\n * \\param ssl      SSL context\n *\n * \\return         a string containing the ciphersuite name\n */\nconst char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl );\n\n/**\n * \\brief          Return the current SSL version (SSLv3/TLSv1/etc)\n *\n * \\param ssl      SSL context\n *\n * \\return         a string containing the SSL version\n */\nconst char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl );\n\n/**\n * \\brief          Return the (maximum) number of bytes added by the record\n *                 layer: header + encryption/MAC overhead (inc. padding)\n *\n * \\param ssl      SSL context\n *\n * \\return         Current maximum record expansion in bytes, or\n *                 MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE if compression is\n *                 enabled, which makes expansion much less predictable\n */\nint mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl );\n\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\n/**\n * \\brief          Return the maximum fragment length (payload, in bytes).\n *                 This is the value negotiated with peer if any,\n *                 or the locally configured value.\n *\n * \\note           With DTLS, \\c mbedtls_ssl_write() will return an error if\n *                 called with a larger length value.\n *                 With TLS, \\c mbedtls_ssl_write() will fragment the input if\n *                 necessary and return the number of bytes written; it is up\n *                 to the caller to call \\c mbedtls_ssl_write() again in\n *                 order to send the remaining bytes if any.\n *\n * \\param ssl      SSL context\n *\n * \\return         Current maximum fragment length.\n */\nsize_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl );\n#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n/**\n * \\brief          Return the peer certificate from the current connection\n *\n *                 Note: Can be NULL in case no certificate was sent during\n *                 the handshake. Different calls for the same connection can\n *                 return the same or different pointers for the same\n *                 certificate and even a different certificate altogether.\n *                 The peer cert CAN change in a single connection if\n *                 renegotiation is performed.\n *\n * \\param ssl      SSL context\n *\n * \\return         the current peer certificate\n */\nconst mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl );\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n#if defined(MBEDTLS_SSL_CLI_C)\n/**\n * \\brief          Save session in order to resume it later (client-side only)\n *                 Session data is copied to presented session structure.\n *\n *\n * \\param ssl      SSL context\n * \\param session  session context\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed,\n *                 MBEDTLS_ERR_SSL_BAD_INPUT_DATA if used server-side or\n *                 arguments are otherwise invalid.\n *\n * \\note           Only the server certificate is copied, and not the full chain,\n *                 so you should not attempt to validate the certificate again\n *                 by calling \\c mbedtls_x509_crt_verify() on it.\n *                 Instead, you should use the results from the verification\n *                 in the original handshake by calling \\c mbedtls_ssl_get_verify_result()\n *                 after loading the session again into a new SSL context\n *                 using \\c mbedtls_ssl_set_session().\n *\n * \\note           Once the session object is not needed anymore, you should\n *                 free it by calling \\c mbedtls_ssl_session_free().\n *\n * \\sa             mbedtls_ssl_set_session()\n */\nint mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session *session );\n#endif /* MBEDTLS_SSL_CLI_C */\n\n/**\n * \\brief          Perform the SSL handshake\n *\n * \\param ssl      SSL context\n *\n * \\return         0 if successful, or\n *                 MBEDTLS_ERR_SSL_WANT_READ or MBEDTLS_ERR_SSL_WANT_WRITE, or\n *                 MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED (see below), or\n *                 a specific SSL error code.\n *\n *                 If this function returns MBEDTLS_ERR_SSL_WANT_READ, the\n *                 handshake is unfinished and no further data is available\n *                 from the underlying transport. In this case, you must call\n *                 the function again at some later stage.\n *\n * \\note           Remarks regarding event-driven DTLS:\n *                 If the function returns MBEDTLS_ERR_SSL_WANT_READ, no datagram\n *                 from the underlying transport layer is currently being processed,\n *                 and it is safe to idle until the timer or the underlying transport\n *                 signal a new event. This is not true for a successful handshake,\n *                 in which case the datagram of the underlying transport that is\n *                 currently being processed might or might not contain further\n *                 DTLS records.\n *\n * \\note           If this function returns something other than 0 or\n *                 MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using\n *                 the SSL context for reading or writing, and either free it or\n *                 call \\c mbedtls_ssl_session_reset() on it before re-using it\n *                 for a new connection; the current connection must be closed.\n *\n * \\note           If DTLS is in use, then you may choose to handle\n *                 MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED specially for logging\n *                 purposes, as it is an expected return value rather than an\n *                 actual error, but you still need to reset/free the context.\n */\nint mbedtls_ssl_handshake( mbedtls_ssl_context *ssl );\n\n/**\n * \\brief          Perform a single step of the SSL handshake\n *\n * \\note           The state of the context (ssl->state) will be at\n *                 the next state after execution of this function. Do not\n *                 call this function if state is MBEDTLS_SSL_HANDSHAKE_OVER.\n *\n * \\note           If this function returns something other than 0 or\n *                 MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using\n *                 the SSL context for reading or writing, and either free it or\n *                 call \\c mbedtls_ssl_session_reset() on it before re-using it\n *                 for a new connection; the current connection must be closed.\n *\n * \\param ssl      SSL context\n *\n * \\return         0 if successful, or\n *                 MBEDTLS_ERR_SSL_WANT_READ or MBEDTLS_ERR_SSL_WANT_WRITE, or\n *                 a specific SSL error code.\n */\nint mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl );\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n/**\n * \\brief          Initiate an SSL renegotiation on the running connection.\n *                 Client: perform the renegotiation right now.\n *                 Server: request renegotiation, which will be performed\n *                 during the next call to mbedtls_ssl_read() if honored by\n *                 client.\n *\n * \\param ssl      SSL context\n *\n * \\return         0 if successful, or any mbedtls_ssl_handshake() return\n *                 value.\n *\n * \\note           If this function returns something other than 0 or\n *                 MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using\n *                 the SSL context for reading or writing, and either free it or\n *                 call \\c mbedtls_ssl_session_reset() on it before re-using it\n *                 for a new connection; the current connection must be closed.\n */\nint mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl );\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n\n/**\n * \\brief          Read at most 'len' application data bytes\n *\n * \\param ssl      SSL context\n * \\param buf      buffer that will hold the data\n * \\param len      maximum number of bytes to read\n *\n * \\return         One of the following:\n *                 - 0 if the read end of the underlying transport was closed,\n *                 - the (positive) number of bytes read, or\n *                 - a negative error code on failure.\n *\n *                 If MBEDTLS_ERR_SSL_WANT_READ is returned, no application data\n *                 is available from the underlying transport. In this case,\n *                 the function needs to be called again at some later stage.\n *\n *                 If MBEDTLS_ERR_SSL_WANT_WRITE is returned, a write is pending\n *                 but the underlying transport isn't available for writing. In this\n *                 case, the function needs to be called again at some later stage.\n *\n *                 When this function return MBEDTLS_ERR_SSL_CLIENT_RECONNECT\n *                 (which can only happen server-side), it means that a client\n *                 is initiating a new connection using the same source port.\n *                 You can either treat that as a connection close and wait\n *                 for the client to resend a ClientHello, or directly\n *                 continue with \\c mbedtls_ssl_handshake() with the same\n *                 context (as it has beeen reset internally). Either way, you\n *                 should make sure this is seen by the application as a new\n *                 connection: application state, if any, should be reset, and\n *                 most importantly the identity of the client must be checked\n *                 again. WARNING: not validating the identity of the client\n *                 again, or not transmitting the new identity to the\n *                 application layer, would allow authentication bypass!\n *\n * \\note           If this function returns something other than a positive value\n *                 or MBEDTLS_ERR_SSL_WANT_READ/WRITE or MBEDTLS_ERR_SSL_CLIENT_RECONNECT,\n *                 you must stop using the SSL context for reading or writing,\n *                 and either free it or call \\c mbedtls_ssl_session_reset() on it\n *                 before re-using it for a new connection; the current connection\n *                 must be closed.\n *\n * \\note           Remarks regarding event-driven DTLS:\n *                 - If the function returns MBEDTLS_ERR_SSL_WANT_READ, no datagram\n *                   from the underlying transport layer is currently being processed,\n *                   and it is safe to idle until the timer or the underlying transport\n *                   signal a new event.\n *                 - This function may return MBEDTLS_ERR_SSL_WANT_READ even if data was\n *                   initially available on the underlying transport, as this data may have\n *                   been only e.g. duplicated messages or a renegotiation request.\n *                   Therefore, you must be prepared to receive MBEDTLS_ERR_SSL_WANT_READ even\n *                   when reacting to an incoming-data event from the underlying transport.\n *                 - On success, the datagram of the underlying transport that is currently\n *                   being processed may contain further DTLS records. You should call\n *                   \\c mbedtls_ssl_check_pending to check for remaining records.\n *\n */\nint mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len );\n\n/**\n * \\brief          Try to write exactly 'len' application data bytes\n *\n * \\warning        This function will do partial writes in some cases. If the\n *                 return value is non-negative but less than length, the\n *                 function must be called again with updated arguments:\n *                 buf + ret, len - ret (if ret is the return value) until\n *                 it returns a value equal to the last 'len' argument.\n *\n * \\param ssl      SSL context\n * \\param buf      buffer holding the data\n * \\param len      how many bytes must be written\n *\n * \\return         the number of bytes actually written (may be less than len),\n *                 or MBEDTLS_ERR_SSL_WANT_WRITE or MBEDTLS_ERR_SSL_WANT_READ,\n *                 or another negative error code.\n *\n * \\note           If this function returns something other than 0, a positive\n *                 value or MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop\n *                 using the SSL context for reading or writing, and either\n *                 free it or call \\c mbedtls_ssl_session_reset() on it before\n *                 re-using it for a new connection; the current connection\n *                 must be closed.\n *\n * \\note           When this function returns MBEDTLS_ERR_SSL_WANT_WRITE/READ,\n *                 it must be called later with the *same* arguments,\n *                 until it returns a value greater that or equal to 0. When\n *                 the function returns MBEDTLS_ERR_SSL_WANT_WRITE there may be\n *                 some partial data in the output buffer, however this is not\n *                 yet sent.\n *\n * \\note           If the requested length is greater than the maximum\n *                 fragment length (either the built-in limit or the one set\n *                 or negotiated with the peer), then:\n *                 - with TLS, less bytes than requested are written.\n *                 - with DTLS, MBEDTLS_ERR_SSL_BAD_INPUT_DATA is returned.\n *                 \\c mbedtls_ssl_get_max_frag_len() may be used to query the\n *                 active maximum fragment length.\n *\n * \\note           Attempting to write 0 bytes will result in an empty TLS\n *                 application record being sent.\n */\nint mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len );\n\n/**\n * \\brief           Send an alert message\n *\n * \\param ssl       SSL context\n * \\param level     The alert level of the message\n *                  (MBEDTLS_SSL_ALERT_LEVEL_WARNING or MBEDTLS_SSL_ALERT_LEVEL_FATAL)\n * \\param message   The alert message (SSL_ALERT_MSG_*)\n *\n * \\return          0 if successful, or a specific SSL error code.\n *\n * \\note           If this function returns something other than 0 or\n *                 MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using\n *                 the SSL context for reading or writing, and either free it or\n *                 call \\c mbedtls_ssl_session_reset() on it before re-using it\n *                 for a new connection; the current connection must be closed.\n */\nint mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl,\n                            unsigned char level,\n                            unsigned char message );\n/**\n * \\brief          Notify the peer that the connection is being closed\n *\n * \\param ssl      SSL context\n *\n * \\return          0 if successful, or a specific SSL error code.\n *\n * \\note           If this function returns something other than 0 or\n *                 MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using\n *                 the SSL context for reading or writing, and either free it or\n *                 call \\c mbedtls_ssl_session_reset() on it before re-using it\n *                 for a new connection; the current connection must be closed.\n */\nint mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl );\n\n/**\n * \\brief          Free referenced items in an SSL context and clear memory\n *\n * \\param ssl      SSL context\n */\nvoid mbedtls_ssl_free( mbedtls_ssl_context *ssl );\n\n/**\n * \\brief          Initialize an SSL configuration context\n *                 Just makes the context ready for\n *                 mbedtls_ssl_config_defaults() or mbedtls_ssl_config_free().\n *\n * \\note           You need to call mbedtls_ssl_config_defaults() unless you\n *                 manually set all of the relevent fields yourself.\n *\n * \\param conf     SSL configuration context\n */\nvoid mbedtls_ssl_config_init( mbedtls_ssl_config *conf );\n\n/**\n * \\brief          Load reasonnable default SSL configuration values.\n *                 (You need to call mbedtls_ssl_config_init() first.)\n *\n * \\param conf     SSL configuration context\n * \\param endpoint MBEDTLS_SSL_IS_CLIENT or MBEDTLS_SSL_IS_SERVER\n * \\param transport MBEDTLS_SSL_TRANSPORT_STREAM for TLS, or\n *                  MBEDTLS_SSL_TRANSPORT_DATAGRAM for DTLS\n * \\param preset   a MBEDTLS_SSL_PRESET_XXX value\n *\n * \\note           See \\c mbedtls_ssl_conf_transport() for notes on DTLS.\n *\n * \\return         0 if successful, or\n *                 MBEDTLS_ERR_XXX_ALLOC_FAILED on memory allocation error.\n */\nint mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,\n                                 int endpoint, int transport, int preset );\n\n/**\n * \\brief          Free an SSL configuration context\n *\n * \\param conf     SSL configuration context\n */\nvoid mbedtls_ssl_config_free( mbedtls_ssl_config *conf );\n\n/**\n * \\brief          Initialize SSL session structure\n *\n * \\param session  SSL session\n */\nvoid mbedtls_ssl_session_init( mbedtls_ssl_session *session );\n\n/**\n * \\brief          Free referenced items in an SSL session including the\n *                 peer certificate and clear memory\n *\n * \\note           A session object can be freed even if the SSL context\n *                 that was used to retrieve the session is still in use.\n *\n * \\param session  SSL session\n */\nvoid mbedtls_ssl_session_free( mbedtls_ssl_session *session );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* ssl.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/ssl_cache.h",
    "content": "/**\n * \\file ssl_cache.h\n *\n * \\brief SSL session cache implementation\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_SSL_CACHE_H\n#define MBEDTLS_SSL_CACHE_H\n\n#include \"ssl.h\"\n\n#if defined(MBEDTLS_THREADING_C)\n#include \"threading.h\"\n#endif\n\n/**\n * \\name SECTION: Module settings\n *\n * The configuration options you can set for this module are in this section.\n * Either change them in config.h or define them on the compiler command line.\n * \\{\n */\n\n#if !defined(MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT)\n#define MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT       86400   /*!< 1 day  */\n#endif\n\n#if !defined(MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES)\n#define MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES      50   /*!< Maximum entries in cache */\n#endif\n\n/* \\} name SECTION: Module settings */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef struct mbedtls_ssl_cache_context mbedtls_ssl_cache_context;\ntypedef struct mbedtls_ssl_cache_entry mbedtls_ssl_cache_entry;\n\n/**\n * \\brief   This structure is used for storing cache entries\n */\nstruct mbedtls_ssl_cache_entry\n{\n#if defined(MBEDTLS_HAVE_TIME)\n    mbedtls_time_t timestamp;           /*!< entry timestamp    */\n#endif\n    mbedtls_ssl_session session;        /*!< entry session      */\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    mbedtls_x509_buf peer_cert;         /*!< entry peer_cert    */\n#endif\n    mbedtls_ssl_cache_entry *next;      /*!< chain pointer      */\n};\n\n/**\n * \\brief Cache context\n */\nstruct mbedtls_ssl_cache_context\n{\n    mbedtls_ssl_cache_entry *chain;     /*!< start of the chain     */\n    int timeout;                /*!< cache entry timeout    */\n    int max_entries;            /*!< maximum entries        */\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_threading_mutex_t mutex;    /*!< mutex                  */\n#endif\n};\n\n/**\n * \\brief          Initialize an SSL cache context\n *\n * \\param cache    SSL cache context\n */\nvoid mbedtls_ssl_cache_init( mbedtls_ssl_cache_context *cache );\n\n/**\n * \\brief          Cache get callback implementation\n *                 (Thread-safe if MBEDTLS_THREADING_C is enabled)\n *\n * \\param data     SSL cache context\n * \\param session  session to retrieve entry for\n */\nint mbedtls_ssl_cache_get( void *data, mbedtls_ssl_session *session );\n\n/**\n * \\brief          Cache set callback implementation\n *                 (Thread-safe if MBEDTLS_THREADING_C is enabled)\n *\n * \\param data     SSL cache context\n * \\param session  session to store entry for\n */\nint mbedtls_ssl_cache_set( void *data, const mbedtls_ssl_session *session );\n\n#if defined(MBEDTLS_HAVE_TIME)\n/**\n * \\brief          Set the cache timeout\n *                 (Default: MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT (1 day))\n *\n *                 A timeout of 0 indicates no timeout.\n *\n * \\param cache    SSL cache context\n * \\param timeout  cache entry timeout in seconds\n */\nvoid mbedtls_ssl_cache_set_timeout( mbedtls_ssl_cache_context *cache, int timeout );\n#endif /* MBEDTLS_HAVE_TIME */\n\n/**\n * \\brief          Set the maximum number of cache entries\n *                 (Default: MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES (50))\n *\n * \\param cache    SSL cache context\n * \\param max      cache entry maximum\n */\nvoid mbedtls_ssl_cache_set_max_entries( mbedtls_ssl_cache_context *cache, int max );\n\n/**\n * \\brief          Free referenced items in a cache context and clear memory\n *\n * \\param cache    SSL cache context\n */\nvoid mbedtls_ssl_cache_free( mbedtls_ssl_cache_context *cache );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* ssl_cache.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/ssl_ciphersuites.h",
    "content": "/**\n * \\file ssl_ciphersuites.h\n *\n * \\brief SSL Ciphersuites for mbed TLS\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_SSL_CIPHERSUITES_H\n#define MBEDTLS_SSL_CIPHERSUITES_H\n\n#include \"pk.h\"\n#include \"cipher.h\"\n#include \"md.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*\n * Supported ciphersuites (Official IANA names)\n */\n#define MBEDTLS_TLS_RSA_WITH_NULL_MD5                    0x01   /**< Weak! */\n#define MBEDTLS_TLS_RSA_WITH_NULL_SHA                    0x02   /**< Weak! */\n\n#define MBEDTLS_TLS_RSA_WITH_RC4_128_MD5                 0x04\n#define MBEDTLS_TLS_RSA_WITH_RC4_128_SHA                 0x05\n#define MBEDTLS_TLS_RSA_WITH_DES_CBC_SHA                 0x09   /**< Weak! Not in TLS 1.2 */\n\n#define MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA            0x0A\n\n#define MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA             0x15   /**< Weak! Not in TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA        0x16\n\n#define MBEDTLS_TLS_PSK_WITH_NULL_SHA                    0x2C   /**< Weak! */\n#define MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA                0x2D   /**< Weak! */\n#define MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA                0x2E   /**< Weak! */\n#define MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA             0x2F\n\n#define MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA         0x33\n#define MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA             0x35\n#define MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA         0x39\n\n#define MBEDTLS_TLS_RSA_WITH_NULL_SHA256                 0x3B   /**< Weak! */\n#define MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256          0x3C   /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256          0x3D   /**< TLS 1.2 */\n\n#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA        0x41\n#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA    0x45\n\n#define MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256      0x67   /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256      0x6B   /**< TLS 1.2 */\n\n#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA        0x84\n#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA    0x88\n\n#define MBEDTLS_TLS_PSK_WITH_RC4_128_SHA                 0x8A\n#define MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA            0x8B\n#define MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA             0x8C\n#define MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA             0x8D\n\n#define MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA             0x8E\n#define MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA        0x8F\n#define MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA         0x90\n#define MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA         0x91\n\n#define MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA             0x92\n#define MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA        0x93\n#define MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA         0x94\n#define MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA         0x95\n\n#define MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256          0x9C   /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384          0x9D   /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256      0x9E   /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384      0x9F   /**< TLS 1.2 */\n\n#define MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256          0xA8   /**< TLS 1.2 */\n#define MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384          0xA9   /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256      0xAA   /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384      0xAB   /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256      0xAC   /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384      0xAD   /**< TLS 1.2 */\n\n#define MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256          0xAE\n#define MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384          0xAF\n#define MBEDTLS_TLS_PSK_WITH_NULL_SHA256                 0xB0   /**< Weak! */\n#define MBEDTLS_TLS_PSK_WITH_NULL_SHA384                 0xB1   /**< Weak! */\n\n#define MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256      0xB2\n#define MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384      0xB3\n#define MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA256             0xB4   /**< Weak! */\n#define MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA384             0xB5   /**< Weak! */\n\n#define MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256      0xB6\n#define MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384      0xB7\n#define MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA256             0xB8   /**< Weak! */\n#define MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA384             0xB9   /**< Weak! */\n\n#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256     0xBA   /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 0xBE   /**< TLS 1.2 */\n\n#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256     0xC0   /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 0xC4   /**< TLS 1.2 */\n\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA             0xC001 /**< Weak! */\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA          0xC002 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA     0xC003 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA      0xC004 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA      0xC005 /**< Not in SSL3! */\n\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA            0xC006 /**< Weak! */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA         0xC007 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA    0xC008 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA     0xC009 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA     0xC00A /**< Not in SSL3! */\n\n#define MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA               0xC00B /**< Weak! */\n#define MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA            0xC00C /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA       0xC00D /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA        0xC00E /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA        0xC00F /**< Not in SSL3! */\n\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA              0xC010 /**< Weak! */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA           0xC011 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA      0xC012 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA       0xC013 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA       0xC014 /**< Not in SSL3! */\n\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256  0xC023 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384  0xC024 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256   0xC025 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384   0xC026 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256    0xC027 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384    0xC028 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256     0xC029 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384     0xC02A /**< TLS 1.2 */\n\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256  0xC02B /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384  0xC02C /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256   0xC02D /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384   0xC02E /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256    0xC02F /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384    0xC030 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256     0xC031 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384     0xC032 /**< TLS 1.2 */\n\n#define MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA           0xC033 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA      0xC034 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA       0xC035 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA       0xC036 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256    0xC037 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384    0xC038 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA              0xC039 /**< Weak! No SSL3! */\n#define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256           0xC03A /**< Weak! No SSL3! */\n#define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384           0xC03B /**< Weak! No SSL3! */\n\n#define MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256         0xC03C /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384         0xC03D /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256     0xC044 /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384     0xC045 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 0xC048 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 0xC049 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256  0xC04A /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384  0xC04B /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256   0xC04C /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384   0xC04D /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256    0xC04E /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384    0xC04F /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256         0xC050 /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384         0xC051 /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256     0xC052 /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384     0xC053 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 0xC05C /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 0xC05D /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256  0xC05E /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384  0xC05F /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256   0xC060 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384   0xC061 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256    0xC062 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384    0xC063 /**< TLS 1.2 */\n#define MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256         0xC064 /**< TLS 1.2 */\n#define MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384         0xC065 /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256     0xC066 /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384     0xC067 /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256     0xC068 /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384     0xC069 /**< TLS 1.2 */\n#define MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256         0xC06A /**< TLS 1.2 */\n#define MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384         0xC06B /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256     0xC06C /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384     0xC06D /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256     0xC06E /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384     0xC06F /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256   0xC070 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384   0xC071 /**< TLS 1.2 */\n\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0xC072 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 0xC073 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256  0xC074 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384  0xC075 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256   0xC076 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384   0xC077 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256    0xC078 /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384    0xC079 /**< Not in SSL3! */\n\n#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256         0xC07A /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384         0xC07B /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256     0xC07C /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384     0xC07D /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 0xC086 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 0xC087 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256  0xC088 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384  0xC089 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256   0xC08A /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384   0xC08B /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256    0xC08C /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384    0xC08D /**< TLS 1.2 */\n\n#define MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256       0xC08E /**< TLS 1.2 */\n#define MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384       0xC08F /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256   0xC090 /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384   0xC091 /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256   0xC092 /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384   0xC093 /**< TLS 1.2 */\n\n#define MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256       0xC094\n#define MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384       0xC095\n#define MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256   0xC096\n#define MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384   0xC097\n#define MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256   0xC098\n#define MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384   0xC099\n#define MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 0xC09A /**< Not in SSL3! */\n#define MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 0xC09B /**< Not in SSL3! */\n\n#define MBEDTLS_TLS_RSA_WITH_AES_128_CCM                0xC09C  /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_WITH_AES_256_CCM                0xC09D  /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM            0xC09E  /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM            0xC09F  /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_WITH_AES_128_CCM_8              0xC0A0  /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_WITH_AES_256_CCM_8              0xC0A1  /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM_8          0xC0A2  /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM_8          0xC0A3  /**< TLS 1.2 */\n#define MBEDTLS_TLS_PSK_WITH_AES_128_CCM                0xC0A4  /**< TLS 1.2 */\n#define MBEDTLS_TLS_PSK_WITH_AES_256_CCM                0xC0A5  /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM            0xC0A6  /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM            0xC0A7  /**< TLS 1.2 */\n#define MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8              0xC0A8  /**< TLS 1.2 */\n#define MBEDTLS_TLS_PSK_WITH_AES_256_CCM_8              0xC0A9  /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM_8          0xC0AA  /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM_8          0xC0AB  /**< TLS 1.2 */\n/* The last two are named with PSK_DHE in the RFC, which looks like a typo */\n\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM        0xC0AC  /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM        0xC0AD  /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8      0xC0AE  /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8      0xC0AF  /**< TLS 1.2 */\n\n#define MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8          0xC0FF  /**< experimental */\n\n/* RFC 7905 */\n#define MBEDTLS_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   0xCCA8 /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9 /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256     0xCCAA /**< TLS 1.2 */\n#define MBEDTLS_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256         0xCCAB /**< TLS 1.2 */\n#define MBEDTLS_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256   0xCCAC /**< TLS 1.2 */\n#define MBEDTLS_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256     0xCCAD /**< TLS 1.2 */\n#define MBEDTLS_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256     0xCCAE /**< TLS 1.2 */\n\n/* Reminder: update mbedtls_ssl_premaster_secret when adding a new key exchange.\n * Reminder: update MBEDTLS_KEY_EXCHANGE__xxx below\n */\ntypedef enum {\n    MBEDTLS_KEY_EXCHANGE_NONE = 0,\n    MBEDTLS_KEY_EXCHANGE_RSA,\n    MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n    MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n    MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n    MBEDTLS_KEY_EXCHANGE_PSK,\n    MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n    MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n    MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,\n    MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n    MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n    MBEDTLS_KEY_EXCHANGE_ECJPAKE,\n} mbedtls_key_exchange_type_t;\n\n/* Key exchanges using a certificate */\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)           || \\\n    defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)       || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)     || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)   || \\\n    defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)       || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)      || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)\n#define MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED\n#endif\n\n/* Key exchanges allowing client certificate requests */\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)           ||       \\\n    defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)       ||       \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)      ||       \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)     ||       \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)    ||       \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)\n#define MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED\n#endif\n\n/* Key exchanges involving server signature in ServerKeyExchange */\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)       || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)     || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)\n#define MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED\n#endif\n\n/* Key exchanges using ECDH */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)      || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)\n#define MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED\n#endif\n\n/* Key exchanges that don't involve ephemeral keys */\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)           || \\\n    defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)           || \\\n    defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)       || \\\n    defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED)\n#define MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED\n#endif\n\n/* Key exchanges that involve ephemeral keys */\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)       || \\\n    defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)       || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)     || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)     || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)   || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n#define MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED\n#endif\n\n/* Key exchanges using a PSK */\n#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)           || \\\n    defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)       || \\\n    defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)       || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)\n#define MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED\n#endif\n\n/* Key exchanges using DHE */\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)       || \\\n    defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)\n#define MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED\n#endif\n\n/* Key exchanges using ECDHE */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)     || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)   || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)\n#define MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED\n#endif\n\ntypedef struct mbedtls_ssl_ciphersuite_t mbedtls_ssl_ciphersuite_t;\n\n#define MBEDTLS_CIPHERSUITE_WEAK       0x01    /**< Weak ciphersuite flag  */\n#define MBEDTLS_CIPHERSUITE_SHORT_TAG  0x02    /**< Short authentication tag,\n                                                     eg for CCM_8 */\n#define MBEDTLS_CIPHERSUITE_NODTLS     0x04    /**< Can't be used with DTLS */\n\n/**\n * \\brief   This structure is used for storing ciphersuite information\n */\nstruct mbedtls_ssl_ciphersuite_t\n{\n    int id;\n    const char * name;\n\n    mbedtls_cipher_type_t cipher;\n    mbedtls_md_type_t mac;\n    mbedtls_key_exchange_type_t key_exchange;\n\n    int min_major_ver;\n    int min_minor_ver;\n    int max_major_ver;\n    int max_minor_ver;\n\n    unsigned char flags;\n};\n\nconst int *mbedtls_ssl_list_ciphersuites( void );\n\nconst mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_string( const char *ciphersuite_name );\nconst mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_id( int ciphersuite_id );\n\n#if defined(MBEDTLS_PK_C)\nmbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_pk_alg( const mbedtls_ssl_ciphersuite_t *info );\nmbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg( const mbedtls_ssl_ciphersuite_t *info );\n#endif\n\nint mbedtls_ssl_ciphersuite_uses_ec( const mbedtls_ssl_ciphersuite_t *info );\nint mbedtls_ssl_ciphersuite_uses_psk( const mbedtls_ssl_ciphersuite_t *info );\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED)\nstatic inline int mbedtls_ssl_ciphersuite_has_pfs( const mbedtls_ssl_ciphersuite_t *info )\n{\n    switch( info->key_exchange )\n    {\n        case MBEDTLS_KEY_EXCHANGE_DHE_RSA:\n        case MBEDTLS_KEY_EXCHANGE_DHE_PSK:\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:\n        case MBEDTLS_KEY_EXCHANGE_ECJPAKE:\n            return( 1 );\n\n        default:\n            return( 0 );\n    }\n}\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED)\nstatic inline int mbedtls_ssl_ciphersuite_no_pfs( const mbedtls_ssl_ciphersuite_t *info )\n{\n    switch( info->key_exchange )\n    {\n        case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:\n        case MBEDTLS_KEY_EXCHANGE_RSA:\n        case MBEDTLS_KEY_EXCHANGE_PSK:\n        case MBEDTLS_KEY_EXCHANGE_RSA_PSK:\n            return( 1 );\n\n        default:\n            return( 0 );\n    }\n}\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED)\nstatic inline int mbedtls_ssl_ciphersuite_uses_ecdh( const mbedtls_ssl_ciphersuite_t *info )\n{\n    switch( info->key_exchange )\n    {\n        case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:\n            return( 1 );\n\n        default:\n            return( 0 );\n    }\n}\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED */\n\nstatic inline int mbedtls_ssl_ciphersuite_cert_req_allowed( const mbedtls_ssl_ciphersuite_t *info )\n{\n    switch( info->key_exchange )\n    {\n        case MBEDTLS_KEY_EXCHANGE_RSA:\n        case MBEDTLS_KEY_EXCHANGE_DHE_RSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:\n            return( 1 );\n\n        default:\n            return( 0 );\n    }\n}\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED)\nstatic inline int mbedtls_ssl_ciphersuite_uses_dhe( const mbedtls_ssl_ciphersuite_t *info )\n{\n    switch( info->key_exchange )\n    {\n        case MBEDTLS_KEY_EXCHANGE_DHE_RSA:\n        case MBEDTLS_KEY_EXCHANGE_DHE_PSK:\n            return( 1 );\n\n        default:\n            return( 0 );\n    }\n}\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED) */\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED)\nstatic inline int mbedtls_ssl_ciphersuite_uses_ecdhe( const mbedtls_ssl_ciphersuite_t *info )\n{\n    switch( info->key_exchange )\n    {\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:\n            return( 1 );\n\n        default:\n            return( 0 );\n    }\n}\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED) */\n\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)\nstatic inline int mbedtls_ssl_ciphersuite_uses_server_signature( const mbedtls_ssl_ciphersuite_t *info )\n{\n    switch( info->key_exchange )\n    {\n        case MBEDTLS_KEY_EXCHANGE_DHE_RSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:\n            return( 1 );\n\n        default:\n            return( 0 );\n    }\n}\n#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* ssl_ciphersuites.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/ssl_cookie.h",
    "content": "/**\n * \\file ssl_cookie.h\n *\n * \\brief DTLS cookie callbacks implementation\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_SSL_COOKIE_H\n#define MBEDTLS_SSL_COOKIE_H\n\n#include \"ssl.h\"\n\n#if defined(MBEDTLS_THREADING_C)\n#include \"threading.h\"\n#endif\n\n/**\n * \\name SECTION: Module settings\n *\n * The configuration options you can set for this module are in this section.\n * Either change them in config.h or define them on the compiler command line.\n * \\{\n */\n#ifndef MBEDTLS_SSL_COOKIE_TIMEOUT\n#define MBEDTLS_SSL_COOKIE_TIMEOUT     60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number of cookies issued */\n#endif\n\n/* \\} name SECTION: Module settings */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief          Context for the default cookie functions.\n */\ntypedef struct\n{\n    mbedtls_md_context_t    hmac_ctx;   /*!< context for the HMAC portion   */\n#if !defined(MBEDTLS_HAVE_TIME)\n    unsigned long   serial;     /*!< serial number for expiration   */\n#endif\n    unsigned long   timeout;    /*!< timeout delay, in seconds if HAVE_TIME,\n                                     or in number of tickets issued */\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_threading_mutex_t mutex;\n#endif\n} mbedtls_ssl_cookie_ctx;\n\n/**\n * \\brief          Initialize cookie context\n */\nvoid mbedtls_ssl_cookie_init( mbedtls_ssl_cookie_ctx *ctx );\n\n/**\n * \\brief          Setup cookie context (generate keys)\n */\nint mbedtls_ssl_cookie_setup( mbedtls_ssl_cookie_ctx *ctx,\n                      int (*f_rng)(void *, unsigned char *, size_t),\n                      void *p_rng );\n\n/**\n * \\brief          Set expiration delay for cookies\n *                 (Default MBEDTLS_SSL_COOKIE_TIMEOUT)\n *\n * \\param ctx      Cookie contex\n * \\param delay    Delay, in seconds if HAVE_TIME, or in number of cookies\n *                 issued in the meantime.\n *                 0 to disable expiration (NOT recommended)\n */\nvoid mbedtls_ssl_cookie_set_timeout( mbedtls_ssl_cookie_ctx *ctx, unsigned long delay );\n\n/**\n * \\brief          Free cookie context\n */\nvoid mbedtls_ssl_cookie_free( mbedtls_ssl_cookie_ctx *ctx );\n\n/**\n * \\brief          Generate cookie, see \\c mbedtls_ssl_cookie_write_t\n */\nmbedtls_ssl_cookie_write_t mbedtls_ssl_cookie_write;\n\n/**\n * \\brief          Verify cookie, see \\c mbedtls_ssl_cookie_write_t\n */\nmbedtls_ssl_cookie_check_t mbedtls_ssl_cookie_check;\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* ssl_cookie.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/ssl_internal.h",
    "content": "/**\n * \\file ssl_internal.h\n *\n * \\brief Internal functions shared by the SSL modules\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_SSL_INTERNAL_H\n#define MBEDTLS_SSL_INTERNAL_H\n\n#include \"ssl.h\"\n#include \"cipher.h\"\n\n#if defined(MBEDTLS_MD5_C)\n#include \"md5.h\"\n#endif\n\n#if defined(MBEDTLS_SHA1_C)\n#include \"sha1.h\"\n#endif\n\n#if defined(MBEDTLS_SHA256_C)\n#include \"sha256.h\"\n#endif\n\n#if defined(MBEDTLS_SHA512_C)\n#include \"sha512.h\"\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n#include \"ecjpake.h\"\n#endif\n\n#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \\\n    !defined(inline) && !defined(__cplusplus)\n#define inline __inline\n#endif\n\n/* Determine minimum supported version */\n#define MBEDTLS_SSL_MIN_MAJOR_VERSION           MBEDTLS_SSL_MAJOR_VERSION_3\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n#define MBEDTLS_SSL_MIN_MINOR_VERSION           MBEDTLS_SSL_MINOR_VERSION_0\n#else\n#if defined(MBEDTLS_SSL_PROTO_TLS1)\n#define MBEDTLS_SSL_MIN_MINOR_VERSION           MBEDTLS_SSL_MINOR_VERSION_1\n#else\n#if defined(MBEDTLS_SSL_PROTO_TLS1_1)\n#define MBEDTLS_SSL_MIN_MINOR_VERSION           MBEDTLS_SSL_MINOR_VERSION_2\n#else\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#define MBEDTLS_SSL_MIN_MINOR_VERSION           MBEDTLS_SSL_MINOR_VERSION_3\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n#endif /* MBEDTLS_SSL_PROTO_TLS1_1 */\n#endif /* MBEDTLS_SSL_PROTO_TLS1   */\n#endif /* MBEDTLS_SSL_PROTO_SSL3   */\n\n#define MBEDTLS_SSL_MIN_VALID_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_1\n#define MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION MBEDTLS_SSL_MAJOR_VERSION_3\n\n/* Determine maximum supported version */\n#define MBEDTLS_SSL_MAX_MAJOR_VERSION           MBEDTLS_SSL_MAJOR_VERSION_3\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#define MBEDTLS_SSL_MAX_MINOR_VERSION           MBEDTLS_SSL_MINOR_VERSION_3\n#else\n#if defined(MBEDTLS_SSL_PROTO_TLS1_1)\n#define MBEDTLS_SSL_MAX_MINOR_VERSION           MBEDTLS_SSL_MINOR_VERSION_2\n#else\n#if defined(MBEDTLS_SSL_PROTO_TLS1)\n#define MBEDTLS_SSL_MAX_MINOR_VERSION           MBEDTLS_SSL_MINOR_VERSION_1\n#else\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n#define MBEDTLS_SSL_MAX_MINOR_VERSION           MBEDTLS_SSL_MINOR_VERSION_0\n#endif /* MBEDTLS_SSL_PROTO_SSL3   */\n#endif /* MBEDTLS_SSL_PROTO_TLS1   */\n#endif /* MBEDTLS_SSL_PROTO_TLS1_1 */\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n\n#define MBEDTLS_SSL_INITIAL_HANDSHAKE           0\n#define MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS   1   /* In progress */\n#define MBEDTLS_SSL_RENEGOTIATION_DONE          2   /* Done or aborted */\n#define MBEDTLS_SSL_RENEGOTIATION_PENDING       3   /* Requested (server only) */\n\n/*\n * DTLS retransmission states, see RFC 6347 4.2.4\n *\n * The SENDING state is merged in PREPARING for initial sends,\n * but is distinct for resends.\n *\n * Note: initial state is wrong for server, but is not used anyway.\n */\n#define MBEDTLS_SSL_RETRANS_PREPARING       0\n#define MBEDTLS_SSL_RETRANS_SENDING         1\n#define MBEDTLS_SSL_RETRANS_WAITING         2\n#define MBEDTLS_SSL_RETRANS_FINISHED        3\n\n/*\n * Allow extra bytes for record, authentication and encryption overhead:\n * counter (8) + header (5) + IV(16) + MAC (16-48) + padding (0-256)\n * and allow for a maximum of 1024 of compression expansion if\n * enabled.\n */\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n#define MBEDTLS_SSL_COMPRESSION_ADD          1024\n#else\n#define MBEDTLS_SSL_COMPRESSION_ADD             0\n#endif\n\n#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_MODE_CBC)\n/* Ciphersuites using HMAC */\n#if defined(MBEDTLS_SHA512_C)\n#define MBEDTLS_SSL_MAC_ADD                 48  /* SHA-384 used for HMAC */\n#elif defined(MBEDTLS_SHA256_C)\n#define MBEDTLS_SSL_MAC_ADD                 32  /* SHA-256 used for HMAC */\n#else\n#define MBEDTLS_SSL_MAC_ADD                 20  /* SHA-1   used for HMAC */\n#endif\n#else\n/* AEAD ciphersuites: GCM and CCM use a 128 bits tag */\n#define MBEDTLS_SSL_MAC_ADD                 16\n#endif\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#define MBEDTLS_SSL_PADDING_ADD            256\n#else\n#define MBEDTLS_SSL_PADDING_ADD              0\n#endif\n\n#define MBEDTLS_SSL_PAYLOAD_OVERHEAD ( MBEDTLS_SSL_COMPRESSION_ADD +    \\\n                                       MBEDTLS_MAX_IV_LENGTH +          \\\n                                       MBEDTLS_SSL_MAC_ADD +            \\\n                                       MBEDTLS_SSL_PADDING_ADD          \\\n                                       )\n\n#define MBEDTLS_SSL_IN_PAYLOAD_LEN ( MBEDTLS_SSL_PAYLOAD_OVERHEAD + \\\n                                     ( MBEDTLS_SSL_IN_CONTENT_LEN ) )\n\n#define MBEDTLS_SSL_OUT_PAYLOAD_LEN ( MBEDTLS_SSL_PAYLOAD_OVERHEAD + \\\n                                      ( MBEDTLS_SSL_OUT_CONTENT_LEN ) )\n\n/* Maximum length we can advertise as our max content length for\n   RFC 6066 max_fragment_length extension negotiation purposes\n   (the lesser of both sizes, if they are unequal.)\n */\n#define MBEDTLS_TLS_EXT_ADV_CONTENT_LEN (                            \\\n        (MBEDTLS_SSL_IN_CONTENT_LEN > MBEDTLS_SSL_OUT_CONTENT_LEN)   \\\n        ? ( MBEDTLS_SSL_OUT_CONTENT_LEN )                            \\\n        : ( MBEDTLS_SSL_IN_CONTENT_LEN )                             \\\n        )\n\n/*\n * Check that we obey the standard's message size bounds\n */\n\n#if MBEDTLS_SSL_MAX_CONTENT_LEN > 16384\n#error \"Bad configuration - record content too large.\"\n#endif\n\n#if MBEDTLS_SSL_IN_CONTENT_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN\n#error \"Bad configuration - incoming record content should not be larger than MBEDTLS_SSL_MAX_CONTENT_LEN.\"\n#endif\n\n#if MBEDTLS_SSL_OUT_CONTENT_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN\n#error \"Bad configuration - outgoing record content should not be larger than MBEDTLS_SSL_MAX_CONTENT_LEN.\"\n#endif\n\n#if MBEDTLS_SSL_IN_PAYLOAD_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN + 2048\n#error \"Bad configuration - incoming protected record payload too large.\"\n#endif\n\n#if MBEDTLS_SSL_OUT_PAYLOAD_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN + 2048\n#error \"Bad configuration - outgoing protected record payload too large.\"\n#endif\n\n/* Calculate buffer sizes */\n\n/* Note: Even though the TLS record header is only 5 bytes\n   long, we're internally using 8 bytes to store the\n   implicit sequence number. */\n#define MBEDTLS_SSL_HEADER_LEN 13\n\n#define MBEDTLS_SSL_IN_BUFFER_LEN  \\\n    ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_IN_PAYLOAD_LEN ) )\n\n#define MBEDTLS_SSL_OUT_BUFFER_LEN  \\\n    ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_OUT_PAYLOAD_LEN ) )\n\n#ifdef MBEDTLS_ZLIB_SUPPORT\n/* Compression buffer holds both IN and OUT buffers, so should be size of the larger */\n#define MBEDTLS_SSL_COMPRESS_BUFFER_LEN (                               \\\n        ( MBEDTLS_SSL_IN_BUFFER_LEN > MBEDTLS_SSL_OUT_BUFFER_LEN )      \\\n        ? MBEDTLS_SSL_IN_BUFFER_LEN                                     \\\n        : MBEDTLS_SSL_OUT_BUFFER_LEN                                    \\\n        )\n#endif\n\n/*\n * TLS extension flags (for extensions with outgoing ServerHello content\n * that need it (e.g. for RENEGOTIATION_INFO the server already knows because\n * of state of the renegotiation flag, so no indicator is required)\n */\n#define MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT (1 << 0)\n#define MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK                 (1 << 1)\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \\\n    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n/*\n * Abstraction for a grid of allowed signature-hash-algorithm pairs.\n */\nstruct mbedtls_ssl_sig_hash_set_t\n{\n    /* At the moment, we only need to remember a single suitable\n     * hash algorithm per signature algorithm. As long as that's\n     * the case - and we don't need a general lookup function -\n     * we can implement the sig-hash-set as a map from signatures\n     * to hash algorithms. */\n    mbedtls_md_type_t rsa;\n    mbedtls_md_type_t ecdsa;\n};\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&\n          MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */\n\n/*\n * This structure contains the parameters only needed during handshake.\n */\nstruct mbedtls_ssl_handshake_params\n{\n    /*\n     * Handshake specific crypto variables\n     */\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \\\n    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n    mbedtls_ssl_sig_hash_set_t hash_algs;             /*!<  Set of suitable sig-hash pairs */\n#endif\n#if defined(MBEDTLS_DHM_C)\n    mbedtls_dhm_context dhm_ctx;                /*!<  DHM key exchange        */\n#endif\n#if defined(MBEDTLS_ECDH_C)\n    mbedtls_ecdh_context ecdh_ctx;              /*!<  ECDH key exchange       */\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    mbedtls_ecjpake_context ecjpake_ctx;        /*!< EC J-PAKE key exchange */\n#if defined(MBEDTLS_SSL_CLI_C)\n    unsigned char *ecjpake_cache;               /*!< Cache for ClientHello ext */\n    size_t ecjpake_cache_len;                   /*!< Length of cached data */\n#endif\n#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    const mbedtls_ecp_curve_info **curves;      /*!<  Supported elliptic curves */\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)\n    unsigned char *psk;                 /*!<  PSK from the callback         */\n    size_t psk_len;                     /*!<  Length of PSK from callback   */\n#endif\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    mbedtls_ssl_key_cert *key_cert;     /*!< chosen key/cert pair (server)  */\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\n    int sni_authmode;                   /*!< authmode from SNI callback     */\n    mbedtls_ssl_key_cert *sni_key_cert; /*!< key/cert list from SNI         */\n    mbedtls_x509_crt *sni_ca_chain;     /*!< trusted CAs from SNI callback  */\n    mbedtls_x509_crl *sni_ca_crl;       /*!< trusted CAs CRLs from SNI      */\n#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    unsigned int out_msg_seq;           /*!<  Outgoing handshake sequence number */\n    unsigned int in_msg_seq;            /*!<  Incoming handshake sequence number */\n\n    unsigned char *verify_cookie;       /*!<  Cli: HelloVerifyRequest cookie\n                                              Srv: unused                    */\n    unsigned char verify_cookie_len;    /*!<  Cli: cookie length\n                                              Srv: flag for sending a cookie */\n\n    unsigned char *hs_msg;              /*!<  Reassembled handshake message  */\n\n    uint32_t retransmit_timeout;        /*!<  Current value of timeout       */\n    unsigned char retransmit_state;     /*!<  Retransmission state           */\n    mbedtls_ssl_flight_item *flight;            /*!<  Current outgoing flight        */\n    mbedtls_ssl_flight_item *cur_msg;           /*!<  Current message in flight      */\n    unsigned int in_flight_start_seq;   /*!<  Minimum message sequence in the\n                                              flight being received          */\n    mbedtls_ssl_transform *alt_transform_out;   /*!<  Alternative transform for\n                                              resending messages             */\n    unsigned char alt_out_ctr[8];       /*!<  Alternative record epoch/counter\n                                              for resending messages         */\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n\n    /*\n     * Checksum contexts\n     */\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1)\n       mbedtls_md5_context fin_md5;\n      mbedtls_sha1_context fin_sha1;\n#endif\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#if defined(MBEDTLS_SHA256_C)\n    mbedtls_sha256_context fin_sha256;\n#endif\n#if defined(MBEDTLS_SHA512_C)\n    mbedtls_sha512_context fin_sha512;\n#endif\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n\n    void (*update_checksum)(mbedtls_ssl_context *, const unsigned char *, size_t);\n    void (*calc_verify)(mbedtls_ssl_context *, unsigned char *);\n    void (*calc_finished)(mbedtls_ssl_context *, unsigned char *, int);\n    int  (*tls_prf)(const unsigned char *, size_t, const char *,\n                    const unsigned char *, size_t,\n                    unsigned char *, size_t);\n\n    size_t pmslen;                      /*!<  premaster length        */\n\n    unsigned char randbytes[64];        /*!<  random bytes            */\n    unsigned char premaster[MBEDTLS_PREMASTER_SIZE];\n                                        /*!<  premaster secret        */\n\n    int resume;                         /*!<  session resume indicator*/\n    int max_major_ver;                  /*!< max. major version client*/\n    int max_minor_ver;                  /*!< max. minor version client*/\n    int cli_exts;                       /*!< client extension presence*/\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\n    int new_session_ticket;             /*!< use NewSessionTicket?    */\n#endif /* MBEDTLS_SSL_SESSION_TICKETS */\n#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)\n    int extended_ms;                    /*!< use Extended Master Secret? */\n#endif\n\n#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)\n    unsigned int async_in_progress : 1; /*!< an asynchronous operation is in progress */\n#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */\n\n#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)\n    /** Asynchronous operation context. This field is meant for use by the\n     * asynchronous operation callbacks (mbedtls_ssl_config::f_async_sign_start,\n     * mbedtls_ssl_config::f_async_decrypt_start,\n     * mbedtls_ssl_config::f_async_resume, mbedtls_ssl_config::f_async_cancel).\n     * The library does not use it internally. */\n    void *user_async_ctx;\n#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */\n};\n\n/*\n * This structure contains a full set of runtime transform parameters\n * either in negotiation or active.\n */\nstruct mbedtls_ssl_transform\n{\n    /*\n     * Session specific crypto layer\n     */\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info;\n                                        /*!<  Chosen cipersuite_info  */\n    unsigned int keylen;                /*!<  symmetric key length (bytes)  */\n    size_t minlen;                      /*!<  min. ciphertext length  */\n    size_t ivlen;                       /*!<  IV length               */\n    size_t fixed_ivlen;                 /*!<  Fixed part of IV (AEAD) */\n    size_t maclen;                      /*!<  MAC length              */\n\n    unsigned char iv_enc[16];           /*!<  IV (encryption)         */\n    unsigned char iv_dec[16];           /*!<  IV (decryption)         */\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n    /* Needed only for SSL v3.0 secret */\n    unsigned char mac_enc[20];          /*!<  SSL v3.0 secret (enc)   */\n    unsigned char mac_dec[20];          /*!<  SSL v3.0 secret (dec)   */\n#endif /* MBEDTLS_SSL_PROTO_SSL3 */\n\n    mbedtls_md_context_t md_ctx_enc;            /*!<  MAC (encryption)        */\n    mbedtls_md_context_t md_ctx_dec;            /*!<  MAC (decryption)        */\n\n    mbedtls_cipher_context_t cipher_ctx_enc;    /*!<  encryption context      */\n    mbedtls_cipher_context_t cipher_ctx_dec;    /*!<  decryption context      */\n\n    /*\n     * Session specific compression layer\n     */\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n    z_stream ctx_deflate;               /*!<  compression context     */\n    z_stream ctx_inflate;               /*!<  decompression context   */\n#endif\n};\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n/*\n * List of certificate + private key pairs\n */\nstruct mbedtls_ssl_key_cert\n{\n    mbedtls_x509_crt *cert;                 /*!< cert                       */\n    mbedtls_pk_context *key;                /*!< private key                */\n    mbedtls_ssl_key_cert *next;             /*!< next key/cert pair         */\n};\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n/*\n * List of handshake messages kept around for resending\n */\nstruct mbedtls_ssl_flight_item\n{\n    unsigned char *p;       /*!< message, including handshake headers   */\n    size_t len;             /*!< length of p                            */\n    unsigned char type;     /*!< type of the message: handshake or CCS  */\n    mbedtls_ssl_flight_item *next;  /*!< next handshake message(s)              */\n};\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \\\n    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n\n/* Find an entry in a signature-hash set matching a given hash algorithm. */\nmbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set,\n                                                 mbedtls_pk_type_t sig_alg );\n/* Add a signature-hash-pair to a signature-hash set */\nvoid mbedtls_ssl_sig_hash_set_add( mbedtls_ssl_sig_hash_set_t *set,\n                                   mbedtls_pk_type_t sig_alg,\n                                   mbedtls_md_type_t md_alg );\n/* Allow exactly one hash algorithm for each signature. */\nvoid mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set,\n                                          mbedtls_md_type_t md_alg );\n\n/* Setup an empty signature-hash set */\nstatic inline void mbedtls_ssl_sig_hash_set_init( mbedtls_ssl_sig_hash_set_t *set )\n{\n    mbedtls_ssl_sig_hash_set_const_hash( set, MBEDTLS_MD_NONE );\n}\n\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2) &&\n          MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */\n\n/**\n * \\brief           Free referenced items in an SSL transform context and clear\n *                  memory\n *\n * \\param transform SSL transform context\n */\nvoid mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform );\n\n/**\n * \\brief           Free referenced items in an SSL handshake context and clear\n *                  memory\n *\n * \\param ssl       SSL context\n */\nvoid mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl );\n\nint mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl );\nint mbedtls_ssl_handshake_server_step( mbedtls_ssl_context *ssl );\nvoid mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl );\n\nint mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl );\n\nvoid mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl );\nint mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl );\n\nint mbedtls_ssl_read_record_layer( mbedtls_ssl_context *ssl );\nint mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl );\nint mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl );\nvoid mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl );\n\n/**\n * \\brief       Update record layer\n *\n *              This function roughly separates the implementation\n *              of the logic of (D)TLS from the implementation\n *              of the secure transport.\n *\n * \\param  ssl  SSL context to use\n *\n * \\return      0 or non-zero error code.\n *\n * \\note        A clarification on what is called 'record layer' here\n *              is in order, as many sensible definitions are possible:\n *\n *              The record layer takes as input an untrusted underlying\n *              transport (stream or datagram) and transforms it into\n *              a serially multiplexed, secure transport, which\n *              conceptually provides the following:\n *\n *              (1) Three datagram based, content-agnostic transports\n *                  for handshake, alert and CCS messages.\n *              (2) One stream- or datagram-based transport\n *                  for application data.\n *              (3) Functionality for changing the underlying transform\n *                  securing the contents.\n *\n *              The interface to this functionality is given as follows:\n *\n *              a Updating\n *                [Currently implemented by mbedtls_ssl_read_record]\n *\n *                Check if and on which of the four 'ports' data is pending:\n *                Nothing, a controlling datagram of type (1), or application\n *                data (2). In any case data is present, internal buffers\n *                provide access to the data for the user to process it.\n *                Consumption of type (1) datagrams is done automatically\n *                on the next update, invalidating that the internal buffers\n *                for previous datagrams, while consumption of application\n *                data (2) is user-controlled.\n *\n *              b Reading of application data\n *                [Currently manual adaption of ssl->in_offt pointer]\n *\n *                As mentioned in the last paragraph, consumption of data\n *                is different from the automatic consumption of control\n *                datagrams (1) because application data is treated as a stream.\n *\n *              c Tracking availability of application data\n *                [Currently manually through decreasing ssl->in_msglen]\n *\n *                For efficiency and to retain datagram semantics for\n *                application data in case of DTLS, the record layer\n *                provides functionality for checking how much application\n *                data is still available in the internal buffer.\n *\n *              d Changing the transformation securing the communication.\n *\n *              Given an opaque implementation of the record layer in the\n *              above sense, it should be possible to implement the logic\n *              of (D)TLS on top of it without the need to know anything\n *              about the record layer's internals. This is done e.g.\n *              in all the handshake handling functions, and in the\n *              application data reading function mbedtls_ssl_read.\n *\n * \\note        The above tries to give a conceptual picture of the\n *              record layer, but the current implementation deviates\n *              from it in some places. For example, our implementation of\n *              the update functionality through mbedtls_ssl_read_record\n *              discards datagrams depending on the current state, which\n *              wouldn't fall under the record layer's responsibility\n *              following the above definition.\n *\n */\nint mbedtls_ssl_read_record( mbedtls_ssl_context *ssl );\nint mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want );\n\nint mbedtls_ssl_write_record( mbedtls_ssl_context *ssl );\nint mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl );\n\nint mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl );\nint mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl );\n\nint mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl );\nint mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl );\n\nint mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl );\nint mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl );\n\nvoid mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl,\n                            const mbedtls_ssl_ciphersuite_t *ciphersuite_info );\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)\nint mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex );\n#endif\n\n#if defined(MBEDTLS_PK_C)\nunsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk );\nunsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type );\nmbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig );\n#endif\n\nmbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash );\nunsigned char mbedtls_ssl_hash_from_md_alg( int md );\nint mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md );\n\n#if defined(MBEDTLS_ECP_C)\nint mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id );\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\nint mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl,\n                                mbedtls_md_type_t md );\n#endif\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\nstatic inline mbedtls_pk_context *mbedtls_ssl_own_key( mbedtls_ssl_context *ssl )\n{\n    mbedtls_ssl_key_cert *key_cert;\n\n    if( ssl->handshake != NULL && ssl->handshake->key_cert != NULL )\n        key_cert = ssl->handshake->key_cert;\n    else\n        key_cert = ssl->conf->key_cert;\n\n    return( key_cert == NULL ? NULL : key_cert->key );\n}\n\nstatic inline mbedtls_x509_crt *mbedtls_ssl_own_cert( mbedtls_ssl_context *ssl )\n{\n    mbedtls_ssl_key_cert *key_cert;\n\n    if( ssl->handshake != NULL && ssl->handshake->key_cert != NULL )\n        key_cert = ssl->handshake->key_cert;\n    else\n        key_cert = ssl->conf->key_cert;\n\n    return( key_cert == NULL ? NULL : key_cert->cert );\n}\n\n/*\n * Check usage of a certificate wrt extensions:\n * keyUsage, extendedKeyUsage (later), and nSCertType (later).\n *\n * Warning: cert_endpoint is the endpoint of the cert (ie, of our peer when we\n * check a cert we received from them)!\n *\n * Return 0 if everything is OK, -1 if not.\n */\nint mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert,\n                          const mbedtls_ssl_ciphersuite_t *ciphersuite,\n                          int cert_endpoint,\n                          uint32_t *flags );\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\nvoid mbedtls_ssl_write_version( int major, int minor, int transport,\n                        unsigned char ver[2] );\nvoid mbedtls_ssl_read_version( int *major, int *minor, int transport,\n                       const unsigned char ver[2] );\n\nstatic inline size_t mbedtls_ssl_hdr_len( const mbedtls_ssl_context *ssl )\n{\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n        return( 13 );\n#else\n    ((void) ssl);\n#endif\n    return( 5 );\n}\n\nstatic inline size_t mbedtls_ssl_hs_hdr_len( const mbedtls_ssl_context *ssl )\n{\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n        return( 12 );\n#else\n    ((void) ssl);\n#endif\n    return( 4 );\n}\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\nvoid mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl );\nvoid mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl );\nint mbedtls_ssl_resend( mbedtls_ssl_context *ssl );\n#endif\n\n/* Visible for testing purposes only */\n#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)\nint mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context *ssl );\nvoid mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl );\n#endif\n\n/* constant-time buffer comparison */\nstatic inline int mbedtls_ssl_safer_memcmp( const void *a, const void *b, size_t n )\n{\n    size_t i;\n    volatile const unsigned char *A = (volatile const unsigned char *) a;\n    volatile const unsigned char *B = (volatile const unsigned char *) b;\n    volatile unsigned char diff = 0;\n\n    for( i = 0; i < n; i++ )\n    {\n        /* Read volatile data in order before computing diff.\n         * This avoids IAR compiler warning:\n         * 'the order of volatile accesses is undefined ..' */\n        unsigned char x = A[i], y = B[i];\n        diff |= x ^ y;\n    }\n\n    return( diff );\n}\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1)\nint mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl,\n                                        unsigned char *output,\n                                        unsigned char *data, size_t data_len );\n#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \\\n          MBEDTLS_SSL_PROTO_TLS1_1 */\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_2)\nint mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,\n                                            unsigned char *hash, size_t *hashlen,\n                                            unsigned char *data, size_t data_len,\n                                            mbedtls_md_type_t md_alg );\n#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \\\n          MBEDTLS_SSL_PROTO_TLS1_2 */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* ssl_internal.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/ssl_ticket.h",
    "content": "/**\n * \\file ssl_ticket.h\n *\n * \\brief TLS server ticket callbacks implementation\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_SSL_TICKET_H\n#define MBEDTLS_SSL_TICKET_H\n\n/*\n * This implementation of the session ticket callbacks includes key\n * management, rotating the keys periodically in order to preserve forward\n * secrecy, when MBEDTLS_HAVE_TIME is defined.\n */\n\n#include \"ssl.h\"\n#include \"cipher.h\"\n\n#if defined(MBEDTLS_THREADING_C)\n#include \"threading.h\"\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief   Information for session ticket protection\n */\ntypedef struct\n{\n    unsigned char name[4];          /*!< random key identifier              */\n    uint32_t generation_time;       /*!< key generation timestamp (seconds) */\n    mbedtls_cipher_context_t ctx;   /*!< context for auth enc/decryption    */\n}\nmbedtls_ssl_ticket_key;\n\n/**\n * \\brief   Context for session ticket handling functions\n */\ntypedef struct\n{\n    mbedtls_ssl_ticket_key keys[2]; /*!< ticket protection keys             */\n    unsigned char active;           /*!< index of the currently active key  */\n\n    uint32_t ticket_lifetime;       /*!< lifetime of tickets in seconds     */\n\n    /** Callback for getting (pseudo-)random numbers                        */\n    int  (*f_rng)(void *, unsigned char *, size_t);\n    void *p_rng;                    /*!< context for the RNG function       */\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_threading_mutex_t mutex;\n#endif\n}\nmbedtls_ssl_ticket_context;\n\n/**\n * \\brief           Initialize a ticket context.\n *                  (Just make it ready for mbedtls_ssl_ticket_setup()\n *                  or mbedtls_ssl_ticket_free().)\n *\n * \\param ctx       Context to be initialized\n */\nvoid mbedtls_ssl_ticket_init( mbedtls_ssl_ticket_context *ctx );\n\n/**\n * \\brief           Prepare context to be actually used\n *\n * \\param ctx       Context to be set up\n * \\param f_rng     RNG callback function\n * \\param p_rng     RNG callback context\n * \\param cipher    AEAD cipher to use for ticket protection.\n *                  Recommended value: MBEDTLS_CIPHER_AES_256_GCM.\n * \\param lifetime  Tickets lifetime in seconds\n *                  Recommended value: 86400 (one day).\n *\n * \\note            It is highly recommended to select a cipher that is at\n *                  least as strong as the the strongest ciphersuite\n *                  supported. Usually that means a 256-bit key.\n *\n * \\note            The lifetime of the keys is twice the lifetime of tickets.\n *                  It is recommended to pick a reasonnable lifetime so as not\n *                  to negate the benefits of forward secrecy.\n *\n * \\return          0 if successful,\n *                  or a specific MBEDTLS_ERR_XXX error code\n */\nint mbedtls_ssl_ticket_setup( mbedtls_ssl_ticket_context *ctx,\n    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,\n    mbedtls_cipher_type_t cipher,\n    uint32_t lifetime );\n\n/**\n * \\brief           Implementation of the ticket write callback\n *\n * \\note            See \\c mbedlts_ssl_ticket_write_t for description\n */\nmbedtls_ssl_ticket_write_t mbedtls_ssl_ticket_write;\n\n/**\n * \\brief           Implementation of the ticket parse callback\n *\n * \\note            See \\c mbedlts_ssl_ticket_parse_t for description\n */\nmbedtls_ssl_ticket_parse_t mbedtls_ssl_ticket_parse;\n\n/**\n * \\brief           Free a context's content and zeroize it.\n *\n * \\param ctx       Context to be cleaned up\n */\nvoid mbedtls_ssl_ticket_free( mbedtls_ssl_ticket_context *ctx );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* ssl_ticket.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/threading.h",
    "content": "/**\n * \\file threading.h\n *\n * \\brief Threading abstraction layer\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_THREADING_H\n#define MBEDTLS_THREADING_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stdlib.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#define MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE         -0x001A  /**< The selected feature is not available. */\n#define MBEDTLS_ERR_THREADING_BAD_INPUT_DATA              -0x001C  /**< Bad input parameters to function. */\n#define MBEDTLS_ERR_THREADING_MUTEX_ERROR                 -0x001E  /**< Locking / unlocking / free failed with error code. */\n\n#if defined(MBEDTLS_THREADING_PTHREAD)\n#include <pthread.h>\ntypedef struct\n{\n    pthread_mutex_t mutex;\n    char is_valid;\n} mbedtls_threading_mutex_t;\n#endif\n\n#if defined(MBEDTLS_THREADING_ALT)\n/* You should define the mbedtls_threading_mutex_t type in your header */\n#include \"threading_alt.h\"\n\n/**\n * \\brief           Set your alternate threading implementation function\n *                  pointers and initialize global mutexes. If used, this\n *                  function must be called once in the main thread before any\n *                  other mbed TLS function is called, and\n *                  mbedtls_threading_free_alt() must be called once in the main\n *                  thread after all other mbed TLS functions.\n *\n * \\note            mutex_init() and mutex_free() don't return a status code.\n *                  If mutex_init() fails, it should leave its argument (the\n *                  mutex) in a state such that mutex_lock() will fail when\n *                  called with this argument.\n *\n * \\param mutex_init    the init function implementation\n * \\param mutex_free    the free function implementation\n * \\param mutex_lock    the lock function implementation\n * \\param mutex_unlock  the unlock function implementation\n */\nvoid mbedtls_threading_set_alt( void (*mutex_init)( mbedtls_threading_mutex_t * ),\n                       void (*mutex_free)( mbedtls_threading_mutex_t * ),\n                       int (*mutex_lock)( mbedtls_threading_mutex_t * ),\n                       int (*mutex_unlock)( mbedtls_threading_mutex_t * ) );\n\n/**\n * \\brief               Free global mutexes.\n */\nvoid mbedtls_threading_free_alt( void );\n#endif /* MBEDTLS_THREADING_ALT */\n\n#if defined(MBEDTLS_THREADING_C)\n/*\n * The function pointers for mutex_init, mutex_free, mutex_ and mutex_unlock\n *\n * All these functions are expected to work or the result will be undefined.\n */\nextern void (*mbedtls_mutex_init)( mbedtls_threading_mutex_t *mutex );\nextern void (*mbedtls_mutex_free)( mbedtls_threading_mutex_t *mutex );\nextern int (*mbedtls_mutex_lock)( mbedtls_threading_mutex_t *mutex );\nextern int (*mbedtls_mutex_unlock)( mbedtls_threading_mutex_t *mutex );\n\n/*\n * Global mutexes\n */\n#if defined(MBEDTLS_FS_IO)\nextern mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex;\n#endif\n#endif /* MBEDTLS_THREADING_C */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* threading.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/timing.h",
    "content": "/**\n * \\file timing.h\n *\n * \\brief Portable interface to timeouts and to the CPU cycle counter\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_TIMING_H\n#define MBEDTLS_TIMING_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stdint.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_TIMING_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief          timer structure\n */\nstruct mbedtls_timing_hr_time\n{\n    unsigned char opaque[32];\n};\n\n/**\n * \\brief          Context for mbedtls_timing_set/get_delay()\n */\ntypedef struct\n{\n    struct mbedtls_timing_hr_time   timer;\n    uint32_t                        int_ms;\n    uint32_t                        fin_ms;\n} mbedtls_timing_delay_context;\n\n#else  /* MBEDTLS_TIMING_ALT */\n#include \"timing_alt.h\"\n#endif /* MBEDTLS_TIMING_ALT */\n\nextern volatile int mbedtls_timing_alarmed;\n\n/**\n * \\brief          Return the CPU cycle counter value\n *\n * \\warning        This is only a best effort! Do not rely on this!\n *                 In particular, it is known to be unreliable on virtual\n *                 machines.\n *\n * \\note           This value starts at an unspecified origin and\n *                 may wrap around.\n */\nunsigned long mbedtls_timing_hardclock( void );\n\n/**\n * \\brief          Return the elapsed time in milliseconds\n *\n * \\param val      points to a timer structure\n * \\param reset    If 0, query the elapsed time. Otherwise (re)start the timer.\n *\n * \\return         Elapsed time since the previous reset in ms. When\n *                 restarting, this is always 0.\n *\n * \\note           To initialize a timer, call this function with reset=1.\n *\n *                 Determining the elapsed time and resetting the timer is not\n *                 atomic on all platforms, so after the sequence\n *                 `{ get_timer(1); ...; time1 = get_timer(1); ...; time2 =\n *                 get_timer(0) }` the value time1+time2 is only approximately\n *                 the delay since the first reset.\n */\nunsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset );\n\n/**\n * \\brief          Setup an alarm clock\n *\n * \\param seconds  delay before the \"mbedtls_timing_alarmed\" flag is set\n *                 (must be >=0)\n *\n * \\warning        Only one alarm at a time  is supported. In a threaded\n *                 context, this means one for the whole process, not one per\n *                 thread.\n */\nvoid mbedtls_set_alarm( int seconds );\n\n/**\n * \\brief          Set a pair of delays to watch\n *                 (See \\c mbedtls_timing_get_delay().)\n *\n * \\param data     Pointer to timing data.\n *                 Must point to a valid \\c mbedtls_timing_delay_context struct.\n * \\param int_ms   First (intermediate) delay in milliseconds.\n *                 The effect if int_ms > fin_ms is unspecified.\n * \\param fin_ms   Second (final) delay in milliseconds.\n *                 Pass 0 to cancel the current delay.\n *\n * \\note           To set a single delay, either use \\c mbedtls_timing_set_timer\n *                 directly or use this function with int_ms == fin_ms.\n */\nvoid mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms );\n\n/**\n * \\brief          Get the status of delays\n *                 (Memory helper: number of delays passed.)\n *\n * \\param data     Pointer to timing data\n *                 Must point to a valid \\c mbedtls_timing_delay_context struct.\n *\n * \\return         -1 if cancelled (fin_ms = 0),\n *                  0 if none of the delays are passed,\n *                  1 if only the intermediate delay is passed,\n *                  2 if the final delay is passed.\n */\nint mbedtls_timing_get_delay( void *data );\n\n#if defined(MBEDTLS_SELF_TEST)\n/**\n * \\brief          Checkup routine\n *\n * \\return         0 if successful, or 1 if a test failed\n */\nint mbedtls_timing_self_test( int verbose );\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* timing.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/version.h",
    "content": "/**\n * \\file version.h\n *\n * \\brief Run-time version information\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n * This set of compile-time defines and run-time variables can be used to\n * determine the version number of the mbed TLS library used.\n */\n#ifndef MBEDTLS_VERSION_H\n#define MBEDTLS_VERSION_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n/**\n * The version number x.y.z is split into three parts.\n * Major, Minor, Patchlevel\n */\n#define MBEDTLS_VERSION_MAJOR  2\n#define MBEDTLS_VERSION_MINOR  12\n#define MBEDTLS_VERSION_PATCH  0\n\n/**\n * The single version number has the following structure:\n *    MMNNPP00\n *    Major version | Minor version | Patch version\n */\n#define MBEDTLS_VERSION_NUMBER         0x020C0000\n#define MBEDTLS_VERSION_STRING         \"2.12.0\"\n#define MBEDTLS_VERSION_STRING_FULL    \"mbed TLS 2.12.0\"\n\n#if defined(MBEDTLS_VERSION_C)\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * Get the version number.\n *\n * \\return          The constructed version number in the format\n *                  MMNNPP00 (Major, Minor, Patch).\n */\nunsigned int mbedtls_version_get_number( void );\n\n/**\n * Get the version string (\"x.y.z\").\n *\n * \\param string    The string that will receive the value.\n *                  (Should be at least 9 bytes in size)\n */\nvoid mbedtls_version_get_string( char *string );\n\n/**\n * Get the full version string (\"mbed TLS x.y.z\").\n *\n * \\param string    The string that will receive the value. The mbed TLS version\n *                  string will use 18 bytes AT MOST including a terminating\n *                  null byte.\n *                  (So the buffer should be at least 18 bytes to receive this\n *                  version string).\n */\nvoid mbedtls_version_get_string_full( char *string );\n\n/**\n * \\brief           Check if support for a feature was compiled into this\n *                  mbed TLS binary. This allows you to see at runtime if the\n *                  library was for instance compiled with or without\n *                  Multi-threading support.\n *\n * \\note            only checks against defines in the sections \"System\n *                  support\", \"mbed TLS modules\" and \"mbed TLS feature\n *                  support\" in config.h\n *\n * \\param feature   The string for the define to check (e.g. \"MBEDTLS_AES_C\")\n *\n * \\return          0 if the feature is present,\n *                  -1 if the feature is not present and\n *                  -2 if support for feature checking as a whole was not\n *                  compiled in.\n */\nint mbedtls_version_check_feature( const char *feature );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* MBEDTLS_VERSION_C */\n\n#endif /* version.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/x509.h",
    "content": "/**\n * \\file x509.h\n *\n * \\brief X.509 generic defines and structures\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_X509_H\n#define MBEDTLS_X509_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include \"asn1.h\"\n#include \"pk.h\"\n\n#if defined(MBEDTLS_RSA_C)\n#include \"rsa.h\"\n#endif\n\n/**\n * \\addtogroup x509_module\n * \\{\n */\n\n#if !defined(MBEDTLS_X509_MAX_INTERMEDIATE_CA)\n/**\n * Maximum number of intermediate CAs in a verification chain.\n * That is, maximum length of the chain, excluding the end-entity certificate\n * and the trusted root certificate.\n *\n * Set this to a low value to prevent an adversary from making you waste\n * resources verifying an overlong certificate chain.\n */\n#define MBEDTLS_X509_MAX_INTERMEDIATE_CA   8\n#endif\n\n/**\n * \\name X509 Error codes\n * \\{\n */\n#define MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE              -0x2080  /**< Unavailable feature, e.g. RSA hashing/encryption combination. */\n#define MBEDTLS_ERR_X509_UNKNOWN_OID                      -0x2100  /**< Requested OID is unknown. */\n#define MBEDTLS_ERR_X509_INVALID_FORMAT                   -0x2180  /**< The CRT/CRL/CSR format is invalid, e.g. different type expected. */\n#define MBEDTLS_ERR_X509_INVALID_VERSION                  -0x2200  /**< The CRT/CRL/CSR version element is invalid. */\n#define MBEDTLS_ERR_X509_INVALID_SERIAL                   -0x2280  /**< The serial tag or value is invalid. */\n#define MBEDTLS_ERR_X509_INVALID_ALG                      -0x2300  /**< The algorithm tag or value is invalid. */\n#define MBEDTLS_ERR_X509_INVALID_NAME                     -0x2380  /**< The name tag or value is invalid. */\n#define MBEDTLS_ERR_X509_INVALID_DATE                     -0x2400  /**< The date tag or value is invalid. */\n#define MBEDTLS_ERR_X509_INVALID_SIGNATURE                -0x2480  /**< The signature tag or value invalid. */\n#define MBEDTLS_ERR_X509_INVALID_EXTENSIONS               -0x2500  /**< The extension tag or value is invalid. */\n#define MBEDTLS_ERR_X509_UNKNOWN_VERSION                  -0x2580  /**< CRT/CRL/CSR has an unsupported version number. */\n#define MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG                  -0x2600  /**< Signature algorithm (oid) is unsupported. */\n#define MBEDTLS_ERR_X509_SIG_MISMATCH                     -0x2680  /**< Signature algorithms do not match. (see \\c ::mbedtls_x509_crt sig_oid) */\n#define MBEDTLS_ERR_X509_CERT_VERIFY_FAILED               -0x2700  /**< Certificate verification failed, e.g. CRL, CA or signature check failed. */\n#define MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT              -0x2780  /**< Format not recognized as DER or PEM. */\n#define MBEDTLS_ERR_X509_BAD_INPUT_DATA                   -0x2800  /**< Input invalid. */\n#define MBEDTLS_ERR_X509_ALLOC_FAILED                     -0x2880  /**< Allocation of memory failed. */\n#define MBEDTLS_ERR_X509_FILE_IO_ERROR                    -0x2900  /**< Read/write of file failed. */\n#define MBEDTLS_ERR_X509_BUFFER_TOO_SMALL                 -0x2980  /**< Destination buffer is too small. */\n#define MBEDTLS_ERR_X509_FATAL_ERROR                      -0x3000  /**< A fatal error occured, eg the chain is too long or the vrfy callback failed. */\n/* \\} name */\n\n/**\n * \\name X509 Verify codes\n * \\{\n */\n/* Reminder: update x509_crt_verify_strings[] in library/x509_crt.c */\n#define MBEDTLS_X509_BADCERT_EXPIRED             0x01  /**< The certificate validity has expired. */\n#define MBEDTLS_X509_BADCERT_REVOKED             0x02  /**< The certificate has been revoked (is on a CRL). */\n#define MBEDTLS_X509_BADCERT_CN_MISMATCH         0x04  /**< The certificate Common Name (CN) does not match with the expected CN. */\n#define MBEDTLS_X509_BADCERT_NOT_TRUSTED         0x08  /**< The certificate is not correctly signed by the trusted CA. */\n#define MBEDTLS_X509_BADCRL_NOT_TRUSTED          0x10  /**< The CRL is not correctly signed by the trusted CA. */\n#define MBEDTLS_X509_BADCRL_EXPIRED              0x20  /**< The CRL is expired. */\n#define MBEDTLS_X509_BADCERT_MISSING             0x40  /**< Certificate was missing. */\n#define MBEDTLS_X509_BADCERT_SKIP_VERIFY         0x80  /**< Certificate verification was skipped. */\n#define MBEDTLS_X509_BADCERT_OTHER             0x0100  /**< Other reason (can be used by verify callback) */\n#define MBEDTLS_X509_BADCERT_FUTURE            0x0200  /**< The certificate validity starts in the future. */\n#define MBEDTLS_X509_BADCRL_FUTURE             0x0400  /**< The CRL is from the future */\n#define MBEDTLS_X509_BADCERT_KEY_USAGE         0x0800  /**< Usage does not match the keyUsage extension. */\n#define MBEDTLS_X509_BADCERT_EXT_KEY_USAGE     0x1000  /**< Usage does not match the extendedKeyUsage extension. */\n#define MBEDTLS_X509_BADCERT_NS_CERT_TYPE      0x2000  /**< Usage does not match the nsCertType extension. */\n#define MBEDTLS_X509_BADCERT_BAD_MD            0x4000  /**< The certificate is signed with an unacceptable hash. */\n#define MBEDTLS_X509_BADCERT_BAD_PK            0x8000  /**< The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA). */\n#define MBEDTLS_X509_BADCERT_BAD_KEY         0x010000  /**< The certificate is signed with an unacceptable key (eg bad curve, RSA too short). */\n#define MBEDTLS_X509_BADCRL_BAD_MD           0x020000  /**< The CRL is signed with an unacceptable hash. */\n#define MBEDTLS_X509_BADCRL_BAD_PK           0x040000  /**< The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA). */\n#define MBEDTLS_X509_BADCRL_BAD_KEY          0x080000  /**< The CRL is signed with an unacceptable key (eg bad curve, RSA too short). */\n\n/* \\} name */\n/* \\} addtogroup x509_module */\n\n/*\n * X.509 v3 Key Usage Extension flags\n * Reminder: update x509_info_key_usage() when adding new flags.\n */\n#define MBEDTLS_X509_KU_DIGITAL_SIGNATURE            (0x80)  /* bit 0 */\n#define MBEDTLS_X509_KU_NON_REPUDIATION              (0x40)  /* bit 1 */\n#define MBEDTLS_X509_KU_KEY_ENCIPHERMENT             (0x20)  /* bit 2 */\n#define MBEDTLS_X509_KU_DATA_ENCIPHERMENT            (0x10)  /* bit 3 */\n#define MBEDTLS_X509_KU_KEY_AGREEMENT                (0x08)  /* bit 4 */\n#define MBEDTLS_X509_KU_KEY_CERT_SIGN                (0x04)  /* bit 5 */\n#define MBEDTLS_X509_KU_CRL_SIGN                     (0x02)  /* bit 6 */\n#define MBEDTLS_X509_KU_ENCIPHER_ONLY                (0x01)  /* bit 7 */\n#define MBEDTLS_X509_KU_DECIPHER_ONLY              (0x8000)  /* bit 8 */\n\n/*\n * Netscape certificate types\n * (http://www.mozilla.org/projects/security/pki/nss/tech-notes/tn3.html)\n */\n\n#define MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT         (0x80)  /* bit 0 */\n#define MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER         (0x40)  /* bit 1 */\n#define MBEDTLS_X509_NS_CERT_TYPE_EMAIL              (0x20)  /* bit 2 */\n#define MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING     (0x10)  /* bit 3 */\n#define MBEDTLS_X509_NS_CERT_TYPE_RESERVED           (0x08)  /* bit 4 */\n#define MBEDTLS_X509_NS_CERT_TYPE_SSL_CA             (0x04)  /* bit 5 */\n#define MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA           (0x02)  /* bit 6 */\n#define MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA  (0x01)  /* bit 7 */\n\n/*\n * X.509 extension types\n *\n * Comments refer to the status for using certificates. Status can be\n * different for writing certificates or reading CRLs or CSRs.\n */\n#define MBEDTLS_X509_EXT_AUTHORITY_KEY_IDENTIFIER    (1 << 0)\n#define MBEDTLS_X509_EXT_SUBJECT_KEY_IDENTIFIER      (1 << 1)\n#define MBEDTLS_X509_EXT_KEY_USAGE                   (1 << 2)\n#define MBEDTLS_X509_EXT_CERTIFICATE_POLICIES        (1 << 3)\n#define MBEDTLS_X509_EXT_POLICY_MAPPINGS             (1 << 4)\n#define MBEDTLS_X509_EXT_SUBJECT_ALT_NAME            (1 << 5)    /* Supported (DNS) */\n#define MBEDTLS_X509_EXT_ISSUER_ALT_NAME             (1 << 6)\n#define MBEDTLS_X509_EXT_SUBJECT_DIRECTORY_ATTRS     (1 << 7)\n#define MBEDTLS_X509_EXT_BASIC_CONSTRAINTS           (1 << 8)    /* Supported */\n#define MBEDTLS_X509_EXT_NAME_CONSTRAINTS            (1 << 9)\n#define MBEDTLS_X509_EXT_POLICY_CONSTRAINTS          (1 << 10)\n#define MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE          (1 << 11)\n#define MBEDTLS_X509_EXT_CRL_DISTRIBUTION_POINTS     (1 << 12)\n#define MBEDTLS_X509_EXT_INIHIBIT_ANYPOLICY          (1 << 13)\n#define MBEDTLS_X509_EXT_FRESHEST_CRL                (1 << 14)\n\n#define MBEDTLS_X509_EXT_NS_CERT_TYPE                (1 << 16)\n\n/*\n * Storage format identifiers\n * Recognized formats: PEM and DER\n */\n#define MBEDTLS_X509_FORMAT_DER                 1\n#define MBEDTLS_X509_FORMAT_PEM                 2\n\n#define MBEDTLS_X509_MAX_DN_NAME_SIZE         256 /**< Maximum value size of a DN entry */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\addtogroup x509_module\n * \\{ */\n\n/**\n * \\name Structures for parsing X.509 certificates, CRLs and CSRs\n * \\{\n */\n\n/**\n * Type-length-value structure that allows for ASN1 using DER.\n */\ntypedef mbedtls_asn1_buf mbedtls_x509_buf;\n\n/**\n * Container for ASN1 bit strings.\n */\ntypedef mbedtls_asn1_bitstring mbedtls_x509_bitstring;\n\n/**\n * Container for ASN1 named information objects.\n * It allows for Relative Distinguished Names (e.g. cn=localhost,ou=code,etc.).\n */\ntypedef mbedtls_asn1_named_data mbedtls_x509_name;\n\n/**\n * Container for a sequence of ASN.1 items\n */\ntypedef mbedtls_asn1_sequence mbedtls_x509_sequence;\n\n/** Container for date and time (precision in seconds). */\ntypedef struct mbedtls_x509_time\n{\n    int year, mon, day;         /**< Date. */\n    int hour, min, sec;         /**< Time. */\n}\nmbedtls_x509_time;\n\n/** \\} name Structures for parsing X.509 certificates, CRLs and CSRs */\n/** \\} addtogroup x509_module */\n\n/**\n * \\brief          Store the certificate DN in printable form into buf;\n *                 no more than size characters will be written.\n *\n * \\param buf      Buffer to write to\n * \\param size     Maximum size of buffer\n * \\param dn       The X509 name to represent\n *\n * \\return         The length of the string written (not including the\n *                 terminated nul byte), or a negative error code.\n */\nint mbedtls_x509_dn_gets( char *buf, size_t size, const mbedtls_x509_name *dn );\n\n/**\n * \\brief          Store the certificate serial in printable form into buf;\n *                 no more than size characters will be written.\n *\n * \\param buf      Buffer to write to\n * \\param size     Maximum size of buffer\n * \\param serial   The X509 serial to represent\n *\n * \\return         The length of the string written (not including the\n *                 terminated nul byte), or a negative error code.\n */\nint mbedtls_x509_serial_gets( char *buf, size_t size, const mbedtls_x509_buf *serial );\n\n/**\n * \\brief          Check a given mbedtls_x509_time against the system time\n *                 and tell if it's in the past.\n *\n * \\note           Intended usage is \"if( is_past( valid_to ) ) ERROR\".\n *                 Hence the return value of 1 if on internal errors.\n *\n * \\param to       mbedtls_x509_time to check\n *\n * \\return         1 if the given time is in the past or an error occured,\n *                 0 otherwise.\n */\nint mbedtls_x509_time_is_past( const mbedtls_x509_time *to );\n\n/**\n * \\brief          Check a given mbedtls_x509_time against the system time\n *                 and tell if it's in the future.\n *\n * \\note           Intended usage is \"if( is_future( valid_from ) ) ERROR\".\n *                 Hence the return value of 1 if on internal errors.\n *\n * \\param from     mbedtls_x509_time to check\n *\n * \\return         1 if the given time is in the future or an error occured,\n *                 0 otherwise.\n */\nint mbedtls_x509_time_is_future( const mbedtls_x509_time *from );\n\n/**\n * \\brief          Checkup routine\n *\n * \\return         0 if successful, or 1 if the test failed\n */\nint mbedtls_x509_self_test( int verbose );\n\n/*\n * Internal module functions. You probably do not want to use these unless you\n * know you do.\n */\nint mbedtls_x509_get_name( unsigned char **p, const unsigned char *end,\n                   mbedtls_x509_name *cur );\nint mbedtls_x509_get_alg_null( unsigned char **p, const unsigned char *end,\n                       mbedtls_x509_buf *alg );\nint mbedtls_x509_get_alg( unsigned char **p, const unsigned char *end,\n                  mbedtls_x509_buf *alg, mbedtls_x509_buf *params );\n#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)\nint mbedtls_x509_get_rsassa_pss_params( const mbedtls_x509_buf *params,\n                                mbedtls_md_type_t *md_alg, mbedtls_md_type_t *mgf_md,\n                                int *salt_len );\n#endif\nint mbedtls_x509_get_sig( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *sig );\nint mbedtls_x509_get_sig_alg( const mbedtls_x509_buf *sig_oid, const mbedtls_x509_buf *sig_params,\n                      mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg,\n                      void **sig_opts );\nint mbedtls_x509_get_time( unsigned char **p, const unsigned char *end,\n                   mbedtls_x509_time *t );\nint mbedtls_x509_get_serial( unsigned char **p, const unsigned char *end,\n                     mbedtls_x509_buf *serial );\nint mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end,\n                  mbedtls_x509_buf *ext, int tag );\nint mbedtls_x509_sig_alg_gets( char *buf, size_t size, const mbedtls_x509_buf *sig_oid,\n                       mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg,\n                       const void *sig_opts );\nint mbedtls_x509_key_size_helper( char *buf, size_t buf_size, const char *name );\nint mbedtls_x509_string_to_names( mbedtls_asn1_named_data **head, const char *name );\nint mbedtls_x509_set_extension( mbedtls_asn1_named_data **head, const char *oid, size_t oid_len,\n                        int critical, const unsigned char *val,\n                        size_t val_len );\nint mbedtls_x509_write_extensions( unsigned char **p, unsigned char *start,\n                           mbedtls_asn1_named_data *first );\nint mbedtls_x509_write_names( unsigned char **p, unsigned char *start,\n                      mbedtls_asn1_named_data *first );\nint mbedtls_x509_write_sig( unsigned char **p, unsigned char *start,\n                    const char *oid, size_t oid_len,\n                    unsigned char *sig, size_t size );\n\n#define MBEDTLS_X509_SAFE_SNPRINTF                          \\\n    do {                                                    \\\n        if( ret < 0 || (size_t) ret >= n )                  \\\n            return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL );    \\\n                                                            \\\n        n -= (size_t) ret;                                  \\\n        p += (size_t) ret;                                  \\\n    } while( 0 )\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* x509.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/x509_crl.h",
    "content": "/**\n * \\file x509_crl.h\n *\n * \\brief X.509 certificate revocation list parsing\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_X509_CRL_H\n#define MBEDTLS_X509_CRL_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include \"x509.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\addtogroup x509_module\n * \\{ */\n\n/**\n * \\name Structures and functions for parsing CRLs\n * \\{\n */\n\n/**\n * Certificate revocation list entry.\n * Contains the CA-specific serial numbers and revocation dates.\n */\ntypedef struct mbedtls_x509_crl_entry\n{\n    mbedtls_x509_buf raw;\n\n    mbedtls_x509_buf serial;\n\n    mbedtls_x509_time revocation_date;\n\n    mbedtls_x509_buf entry_ext;\n\n    struct mbedtls_x509_crl_entry *next;\n}\nmbedtls_x509_crl_entry;\n\n/**\n * Certificate revocation list structure.\n * Every CRL may have multiple entries.\n */\ntypedef struct mbedtls_x509_crl\n{\n    mbedtls_x509_buf raw;           /**< The raw certificate data (DER). */\n    mbedtls_x509_buf tbs;           /**< The raw certificate body (DER). The part that is To Be Signed. */\n\n    int version;            /**< CRL version (1=v1, 2=v2) */\n    mbedtls_x509_buf sig_oid;       /**< CRL signature type identifier */\n\n    mbedtls_x509_buf issuer_raw;    /**< The raw issuer data (DER). */\n\n    mbedtls_x509_name issuer;       /**< The parsed issuer data (named information object). */\n\n    mbedtls_x509_time this_update;\n    mbedtls_x509_time next_update;\n\n    mbedtls_x509_crl_entry entry;   /**< The CRL entries containing the certificate revocation times for this CA. */\n\n    mbedtls_x509_buf crl_ext;\n\n    mbedtls_x509_buf sig_oid2;\n    mbedtls_x509_buf sig;\n    mbedtls_md_type_t sig_md;           /**< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */\n    mbedtls_pk_type_t sig_pk;           /**< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */\n    void *sig_opts;             /**< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */\n\n    struct mbedtls_x509_crl *next;\n}\nmbedtls_x509_crl;\n\n/**\n * \\brief          Parse a DER-encoded CRL and append it to the chained list\n *\n * \\param chain    points to the start of the chain\n * \\param buf      buffer holding the CRL data in DER format\n * \\param buflen   size of the buffer\n *                 (including the terminating null byte for PEM data)\n *\n * \\return         0 if successful, or a specific X509 or PEM error code\n */\nint mbedtls_x509_crl_parse_der( mbedtls_x509_crl *chain,\n                        const unsigned char *buf, size_t buflen );\n/**\n * \\brief          Parse one or more CRLs and append them to the chained list\n *\n * \\note           Mutliple CRLs are accepted only if using PEM format\n *\n * \\param chain    points to the start of the chain\n * \\param buf      buffer holding the CRL data in PEM or DER format\n * \\param buflen   size of the buffer\n *                 (including the terminating null byte for PEM data)\n *\n * \\return         0 if successful, or a specific X509 or PEM error code\n */\nint mbedtls_x509_crl_parse( mbedtls_x509_crl *chain, const unsigned char *buf, size_t buflen );\n\n#if defined(MBEDTLS_FS_IO)\n/**\n * \\brief          Load one or more CRLs and append them to the chained list\n *\n * \\note           Mutliple CRLs are accepted only if using PEM format\n *\n * \\param chain    points to the start of the chain\n * \\param path     filename to read the CRLs from (in PEM or DER encoding)\n *\n * \\return         0 if successful, or a specific X509 or PEM error code\n */\nint mbedtls_x509_crl_parse_file( mbedtls_x509_crl *chain, const char *path );\n#endif /* MBEDTLS_FS_IO */\n\n/**\n * \\brief          Returns an informational string about the CRL.\n *\n * \\param buf      Buffer to write to\n * \\param size     Maximum size of buffer\n * \\param prefix   A line prefix\n * \\param crl      The X509 CRL to represent\n *\n * \\return         The length of the string written (not including the\n *                 terminated nul byte), or a negative error code.\n */\nint mbedtls_x509_crl_info( char *buf, size_t size, const char *prefix,\n                   const mbedtls_x509_crl *crl );\n\n/**\n * \\brief          Initialize a CRL (chain)\n *\n * \\param crl      CRL chain to initialize\n */\nvoid mbedtls_x509_crl_init( mbedtls_x509_crl *crl );\n\n/**\n * \\brief          Unallocate all CRL data\n *\n * \\param crl      CRL chain to free\n */\nvoid mbedtls_x509_crl_free( mbedtls_x509_crl *crl );\n\n/* \\} name */\n/* \\} addtogroup x509_module */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* mbedtls_x509_crl.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/x509_crt.h",
    "content": "/**\n * \\file x509_crt.h\n *\n * \\brief X.509 certificate parsing and writing\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_X509_CRT_H\n#define MBEDTLS_X509_CRT_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include \"x509.h\"\n#include \"x509_crl.h\"\n\n/**\n * \\addtogroup x509_module\n * \\{\n */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\name Structures and functions for parsing and writing X.509 certificates\n * \\{\n */\n\n/**\n * Container for an X.509 certificate. The certificate may be chained.\n */\ntypedef struct mbedtls_x509_crt\n{\n    mbedtls_x509_buf raw;               /**< The raw certificate data (DER). */\n    mbedtls_x509_buf tbs;               /**< The raw certificate body (DER). The part that is To Be Signed. */\n\n    int version;                /**< The X.509 version. (1=v1, 2=v2, 3=v3) */\n    mbedtls_x509_buf serial;            /**< Unique id for certificate issued by a specific CA. */\n    mbedtls_x509_buf sig_oid;           /**< Signature algorithm, e.g. sha1RSA */\n\n    mbedtls_x509_buf issuer_raw;        /**< The raw issuer data (DER). Used for quick comparison. */\n    mbedtls_x509_buf subject_raw;       /**< The raw subject data (DER). Used for quick comparison. */\n\n    mbedtls_x509_name issuer;           /**< The parsed issuer data (named information object). */\n    mbedtls_x509_name subject;          /**< The parsed subject data (named information object). */\n\n    mbedtls_x509_time valid_from;       /**< Start time of certificate validity. */\n    mbedtls_x509_time valid_to;         /**< End time of certificate validity. */\n\n    mbedtls_pk_context pk;              /**< Container for the public key context. */\n\n    mbedtls_x509_buf issuer_id;         /**< Optional X.509 v2/v3 issuer unique identifier. */\n    mbedtls_x509_buf subject_id;        /**< Optional X.509 v2/v3 subject unique identifier. */\n    mbedtls_x509_buf v3_ext;            /**< Optional X.509 v3 extensions.  */\n    mbedtls_x509_sequence subject_alt_names;    /**< Optional list of Subject Alternative Names (Only dNSName supported). */\n\n    int ext_types;              /**< Bit string containing detected and parsed extensions */\n    int ca_istrue;              /**< Optional Basic Constraint extension value: 1 if this certificate belongs to a CA, 0 otherwise. */\n    int max_pathlen;            /**< Optional Basic Constraint extension value: The maximum path length to the root certificate. Path length is 1 higher than RFC 5280 'meaning', so 1+ */\n\n    unsigned int key_usage;     /**< Optional key usage extension value: See the values in x509.h */\n\n    mbedtls_x509_sequence ext_key_usage; /**< Optional list of extended key usage OIDs. */\n\n    unsigned char ns_cert_type; /**< Optional Netscape certificate type extension value: See the values in x509.h */\n\n    mbedtls_x509_buf sig;               /**< Signature: hash of the tbs part signed with the private key. */\n    mbedtls_md_type_t sig_md;           /**< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */\n    mbedtls_pk_type_t sig_pk;           /**< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */\n    void *sig_opts;             /**< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */\n\n    struct mbedtls_x509_crt *next;     /**< Next certificate in the CA-chain. */\n}\nmbedtls_x509_crt;\n\n/**\n * Build flag from an algorithm/curve identifier (pk, md, ecp)\n * Since 0 is always XXX_NONE, ignore it.\n */\n#define MBEDTLS_X509_ID_FLAG( id )   ( 1 << ( id - 1 ) )\n\n/**\n * Security profile for certificate verification.\n *\n * All lists are bitfields, built by ORing flags from MBEDTLS_X509_ID_FLAG().\n */\ntypedef struct\n{\n    uint32_t allowed_mds;       /**< MDs for signatures         */\n    uint32_t allowed_pks;       /**< PK algs for signatures     */\n    uint32_t allowed_curves;    /**< Elliptic curves for ECDSA  */\n    uint32_t rsa_min_bitlen;    /**< Minimum size for RSA keys  */\n}\nmbedtls_x509_crt_profile;\n\n#define MBEDTLS_X509_CRT_VERSION_1              0\n#define MBEDTLS_X509_CRT_VERSION_2              1\n#define MBEDTLS_X509_CRT_VERSION_3              2\n\n#define MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN 32\n#define MBEDTLS_X509_RFC5280_UTC_TIME_LEN   15\n\n#if !defined( MBEDTLS_X509_MAX_FILE_PATH_LEN )\n#define MBEDTLS_X509_MAX_FILE_PATH_LEN 512\n#endif\n\n/**\n * Container for writing a certificate (CRT)\n */\ntypedef struct mbedtls_x509write_cert\n{\n    int version;\n    mbedtls_mpi serial;\n    mbedtls_pk_context *subject_key;\n    mbedtls_pk_context *issuer_key;\n    mbedtls_asn1_named_data *subject;\n    mbedtls_asn1_named_data *issuer;\n    mbedtls_md_type_t md_alg;\n    char not_before[MBEDTLS_X509_RFC5280_UTC_TIME_LEN + 1];\n    char not_after[MBEDTLS_X509_RFC5280_UTC_TIME_LEN + 1];\n    mbedtls_asn1_named_data *extensions;\n}\nmbedtls_x509write_cert;\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n/**\n * Default security profile. Should provide a good balance between security\n * and compatibility with current deployments.\n */\nextern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default;\n\n/**\n * Expected next default profile. Recommended for new deployments.\n * Currently targets a 128-bit security level, except for RSA-2048.\n */\nextern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next;\n\n/**\n * NSA Suite B profile.\n */\nextern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb;\n\n/**\n * \\brief          Parse a single DER formatted certificate and add it\n *                 to the chained list.\n *\n * \\param chain    points to the start of the chain\n * \\param buf      buffer holding the certificate DER data\n * \\param buflen   size of the buffer\n *\n * \\return         0 if successful, or a specific X509 or PEM error code\n */\nint mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf,\n                        size_t buflen );\n\n/**\n * \\brief          Parse one or more certificates and add them\n *                 to the chained list. Parses permissively. If some\n *                 certificates can be parsed, the result is the number\n *                 of failed certificates it encountered. If none complete\n *                 correctly, the first error is returned.\n *\n * \\param chain    points to the start of the chain\n * \\param buf      buffer holding the certificate data in PEM or DER format\n * \\param buflen   size of the buffer\n *                 (including the terminating null byte for PEM data)\n *\n * \\return         0 if all certificates parsed successfully, a positive number\n *                 if partly successful or a specific X509 or PEM error code\n */\nint mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen );\n\n#if defined(MBEDTLS_FS_IO)\n/**\n * \\brief          Load one or more certificates and add them\n *                 to the chained list. Parses permissively. If some\n *                 certificates can be parsed, the result is the number\n *                 of failed certificates it encountered. If none complete\n *                 correctly, the first error is returned.\n *\n * \\param chain    points to the start of the chain\n * \\param path     filename to read the certificates from\n *\n * \\return         0 if all certificates parsed successfully, a positive number\n *                 if partly successful or a specific X509 or PEM error code\n */\nint mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path );\n\n/**\n * \\brief          Load one or more certificate files from a path and add them\n *                 to the chained list. Parses permissively. If some\n *                 certificates can be parsed, the result is the number\n *                 of failed certificates it encountered. If none complete\n *                 correctly, the first error is returned.\n *\n * \\param chain    points to the start of the chain\n * \\param path     directory / folder to read the certificate files from\n *\n * \\return         0 if all certificates parsed successfully, a positive number\n *                 if partly successful or a specific X509 or PEM error code\n */\nint mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path );\n#endif /* MBEDTLS_FS_IO */\n\n/**\n * \\brief          Returns an informational string about the\n *                 certificate.\n *\n * \\param buf      Buffer to write to\n * \\param size     Maximum size of buffer\n * \\param prefix   A line prefix\n * \\param crt      The X509 certificate to represent\n *\n * \\return         The length of the string written (not including the\n *                 terminated nul byte), or a negative error code.\n */\nint mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix,\n                   const mbedtls_x509_crt *crt );\n\n/**\n * \\brief          Returns an informational string about the\n *                 verification status of a certificate.\n *\n * \\param buf      Buffer to write to\n * \\param size     Maximum size of buffer\n * \\param prefix   A line prefix\n * \\param flags    Verification flags created by mbedtls_x509_crt_verify()\n *\n * \\return         The length of the string written (not including the\n *                 terminated nul byte), or a negative error code.\n */\nint mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,\n                          uint32_t flags );\n\n/**\n * \\brief          Verify the certificate signature\n *\n *                 The verify callback is a user-supplied callback that\n *                 can clear / modify / add flags for a certificate. If set,\n *                 the verification callback is called for each\n *                 certificate in the chain (from the trust-ca down to the\n *                 presented crt). The parameters for the callback are:\n *                 (void *parameter, mbedtls_x509_crt *crt, int certificate_depth,\n *                 int *flags). With the flags representing current flags for\n *                 that specific certificate and the certificate depth from\n *                 the bottom (Peer cert depth = 0).\n *\n *                 All flags left after returning from the callback\n *                 are also returned to the application. The function should\n *                 return 0 for anything (including invalid certificates)\n *                 other than fatal error, as a non-zero return code\n *                 immediately aborts the verification process. For fatal\n *                 errors, a specific error code should be used (different\n *                 from MBEDTLS_ERR_X509_CERT_VERIFY_FAILED which should not\n *                 be returned at this point), or MBEDTLS_ERR_X509_FATAL_ERROR\n *                 can be used if no better code is available.\n *\n * \\note           In case verification failed, the results can be displayed\n *                 using \\c mbedtls_x509_crt_verify_info()\n *\n * \\note           Same as \\c mbedtls_x509_crt_verify_with_profile() with the\n *                 default security profile.\n *\n * \\note           It is your responsibility to provide up-to-date CRLs for\n *                 all trusted CAs. If no CRL is provided for the CA that was\n *                 used to sign the certificate, CRL verification is skipped\n *                 silently, that is *without* setting any flag.\n *\n * \\note           The \\c trust_ca list can contain two types of certificates:\n *                 (1) those of trusted root CAs, so that certificates\n *                 chaining up to those CAs will be trusted, and (2)\n *                 self-signed end-entity certificates to be trusted (for\n *                 specific peers you know) - in that case, the self-signed\n *                 certificate doesn't need to have the CA bit set.\n *\n * \\param crt      a certificate (chain) to be verified\n * \\param trust_ca the list of trusted CAs (see note above)\n * \\param ca_crl   the list of CRLs for trusted CAs (see note above)\n * \\param cn       expected Common Name (can be set to\n *                 NULL if the CN must not be verified)\n * \\param flags    result of the verification\n * \\param f_vrfy   verification function\n * \\param p_vrfy   verification parameter\n *\n * \\return         0 (and flags set to 0) if the chain was verified and valid,\n *                 MBEDTLS_ERR_X509_CERT_VERIFY_FAILED if the chain was verified\n *                 but found to be invalid, in which case *flags will have one\n *                 or more MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX\n *                 flags set, or another error (and flags set to 0xffffffff)\n *                 in case of a fatal error encountered during the\n *                 verification process.\n */\nint mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,\n                     mbedtls_x509_crt *trust_ca,\n                     mbedtls_x509_crl *ca_crl,\n                     const char *cn, uint32_t *flags,\n                     int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),\n                     void *p_vrfy );\n\n/**\n * \\brief          Verify the certificate signature according to profile\n *\n * \\note           Same as \\c mbedtls_x509_crt_verify(), but with explicit\n *                 security profile.\n *\n * \\note           The restrictions on keys (RSA minimum size, allowed curves\n *                 for ECDSA) apply to all certificates: trusted root,\n *                 intermediate CAs if any, and end entity certificate.\n *\n * \\param crt      a certificate (chain) to be verified\n * \\param trust_ca the list of trusted CAs\n * \\param ca_crl   the list of CRLs for trusted CAs\n * \\param profile  security profile for verification\n * \\param cn       expected Common Name (can be set to\n *                 NULL if the CN must not be verified)\n * \\param flags    result of the verification\n * \\param f_vrfy   verification function\n * \\param p_vrfy   verification parameter\n *\n * \\return         0 if successful or MBEDTLS_ERR_X509_CERT_VERIFY_FAILED\n *                 in which case *flags will have one or more\n *                 MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX flags\n *                 set,\n *                 or another error in case of a fatal error encountered\n *                 during the verification process.\n */\nint mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,\n                     mbedtls_x509_crt *trust_ca,\n                     mbedtls_x509_crl *ca_crl,\n                     const mbedtls_x509_crt_profile *profile,\n                     const char *cn, uint32_t *flags,\n                     int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),\n                     void *p_vrfy );\n\n#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)\n/**\n * \\brief          Check usage of certificate against keyUsage extension.\n *\n * \\param crt      Leaf certificate used.\n * \\param usage    Intended usage(s) (eg MBEDTLS_X509_KU_KEY_ENCIPHERMENT\n *                 before using the certificate to perform an RSA key\n *                 exchange).\n *\n * \\note           Except for decipherOnly and encipherOnly, a bit set in the\n *                 usage argument means this bit MUST be set in the\n *                 certificate. For decipherOnly and encipherOnly, it means\n *                 that bit MAY be set.\n *\n * \\return         0 is these uses of the certificate are allowed,\n *                 MBEDTLS_ERR_X509_BAD_INPUT_DATA if the keyUsage extension\n *                 is present but does not match the usage argument.\n *\n * \\note           You should only call this function on leaf certificates, on\n *                 (intermediate) CAs the keyUsage extension is automatically\n *                 checked by \\c mbedtls_x509_crt_verify().\n */\nint mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,\n                                      unsigned int usage );\n#endif /* MBEDTLS_X509_CHECK_KEY_USAGE) */\n\n#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)\n/**\n * \\brief           Check usage of certificate against extendedKeyUsage.\n *\n * \\param crt       Leaf certificate used.\n * \\param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or\n *                  MBEDTLS_OID_CLIENT_AUTH).\n * \\param usage_len Length of usage_oid (eg given by MBEDTLS_OID_SIZE()).\n *\n * \\return          0 if this use of the certificate is allowed,\n *                  MBEDTLS_ERR_X509_BAD_INPUT_DATA if not.\n *\n * \\note            Usually only makes sense on leaf certificates.\n */\nint mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,\n                                               const char *usage_oid,\n                                               size_t usage_len );\n#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */\n\n#if defined(MBEDTLS_X509_CRL_PARSE_C)\n/**\n * \\brief          Verify the certificate revocation status\n *\n * \\param crt      a certificate to be verified\n * \\param crl      the CRL to verify against\n *\n * \\return         1 if the certificate is revoked, 0 otherwise\n *\n */\nint mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl );\n#endif /* MBEDTLS_X509_CRL_PARSE_C */\n\n/**\n * \\brief          Initialize a certificate (chain)\n *\n * \\param crt      Certificate chain to initialize\n */\nvoid mbedtls_x509_crt_init( mbedtls_x509_crt *crt );\n\n/**\n * \\brief          Unallocate all certificate data\n *\n * \\param crt      Certificate chain to free\n */\nvoid mbedtls_x509_crt_free( mbedtls_x509_crt *crt );\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n/* \\} name */\n/* \\} addtogroup x509_module */\n\n#if defined(MBEDTLS_X509_CRT_WRITE_C)\n/**\n * \\brief           Initialize a CRT writing context\n *\n * \\param ctx       CRT context to initialize\n */\nvoid mbedtls_x509write_crt_init( mbedtls_x509write_cert *ctx );\n\n/**\n * \\brief           Set the verion for a Certificate\n *                  Default: MBEDTLS_X509_CRT_VERSION_3\n *\n * \\param ctx       CRT context to use\n * \\param version   version to set (MBEDTLS_X509_CRT_VERSION_1, MBEDTLS_X509_CRT_VERSION_2 or\n *                                  MBEDTLS_X509_CRT_VERSION_3)\n */\nvoid mbedtls_x509write_crt_set_version( mbedtls_x509write_cert *ctx, int version );\n\n/**\n * \\brief           Set the serial number for a Certificate.\n *\n * \\param ctx       CRT context to use\n * \\param serial    serial number to set\n *\n * \\return          0 if successful\n */\nint mbedtls_x509write_crt_set_serial( mbedtls_x509write_cert *ctx, const mbedtls_mpi *serial );\n\n/**\n * \\brief           Set the validity period for a Certificate\n *                  Timestamps should be in string format for UTC timezone\n *                  i.e. \"YYYYMMDDhhmmss\"\n *                  e.g. \"20131231235959\" for December 31st 2013\n *                       at 23:59:59\n *\n * \\param ctx       CRT context to use\n * \\param not_before    not_before timestamp\n * \\param not_after     not_after timestamp\n *\n * \\return          0 if timestamp was parsed successfully, or\n *                  a specific error code\n */\nint mbedtls_x509write_crt_set_validity( mbedtls_x509write_cert *ctx, const char *not_before,\n                                const char *not_after );\n\n/**\n * \\brief           Set the issuer name for a Certificate\n *                  Issuer names should contain a comma-separated list\n *                  of OID types and values:\n *                  e.g. \"C=UK,O=ARM,CN=mbed TLS CA\"\n *\n * \\param ctx           CRT context to use\n * \\param issuer_name   issuer name to set\n *\n * \\return          0 if issuer name was parsed successfully, or\n *                  a specific error code\n */\nint mbedtls_x509write_crt_set_issuer_name( mbedtls_x509write_cert *ctx,\n                                   const char *issuer_name );\n\n/**\n * \\brief           Set the subject name for a Certificate\n *                  Subject names should contain a comma-separated list\n *                  of OID types and values:\n *                  e.g. \"C=UK,O=ARM,CN=mbed TLS Server 1\"\n *\n * \\param ctx           CRT context to use\n * \\param subject_name  subject name to set\n *\n * \\return          0 if subject name was parsed successfully, or\n *                  a specific error code\n */\nint mbedtls_x509write_crt_set_subject_name( mbedtls_x509write_cert *ctx,\n                                    const char *subject_name );\n\n/**\n * \\brief           Set the subject public key for the certificate\n *\n * \\param ctx       CRT context to use\n * \\param key       public key to include\n */\nvoid mbedtls_x509write_crt_set_subject_key( mbedtls_x509write_cert *ctx, mbedtls_pk_context *key );\n\n/**\n * \\brief           Set the issuer key used for signing the certificate\n *\n * \\param ctx       CRT context to use\n * \\param key       private key to sign with\n */\nvoid mbedtls_x509write_crt_set_issuer_key( mbedtls_x509write_cert *ctx, mbedtls_pk_context *key );\n\n/**\n * \\brief           Set the MD algorithm to use for the signature\n *                  (e.g. MBEDTLS_MD_SHA1)\n *\n * \\param ctx       CRT context to use\n * \\param md_alg    MD algorithm to use\n */\nvoid mbedtls_x509write_crt_set_md_alg( mbedtls_x509write_cert *ctx, mbedtls_md_type_t md_alg );\n\n/**\n * \\brief           Generic function to add to or replace an extension in the\n *                  CRT\n *\n * \\param ctx       CRT context to use\n * \\param oid       OID of the extension\n * \\param oid_len   length of the OID\n * \\param critical  if the extension is critical (per the RFC's definition)\n * \\param val       value of the extension OCTET STRING\n * \\param val_len   length of the value data\n *\n * \\return          0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED\n */\nint mbedtls_x509write_crt_set_extension( mbedtls_x509write_cert *ctx,\n                                 const char *oid, size_t oid_len,\n                                 int critical,\n                                 const unsigned char *val, size_t val_len );\n\n/**\n * \\brief           Set the basicConstraints extension for a CRT\n *\n * \\param ctx       CRT context to use\n * \\param is_ca     is this a CA certificate\n * \\param max_pathlen   maximum length of certificate chains below this\n *                      certificate (only for CA certificates, -1 is\n *                      inlimited)\n *\n * \\return          0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED\n */\nint mbedtls_x509write_crt_set_basic_constraints( mbedtls_x509write_cert *ctx,\n                                         int is_ca, int max_pathlen );\n\n#if defined(MBEDTLS_SHA1_C)\n/**\n * \\brief           Set the subjectKeyIdentifier extension for a CRT\n *                  Requires that mbedtls_x509write_crt_set_subject_key() has been\n *                  called before\n *\n * \\param ctx       CRT context to use\n *\n * \\return          0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED\n */\nint mbedtls_x509write_crt_set_subject_key_identifier( mbedtls_x509write_cert *ctx );\n\n/**\n * \\brief           Set the authorityKeyIdentifier extension for a CRT\n *                  Requires that mbedtls_x509write_crt_set_issuer_key() has been\n *                  called before\n *\n * \\param ctx       CRT context to use\n *\n * \\return          0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED\n */\nint mbedtls_x509write_crt_set_authority_key_identifier( mbedtls_x509write_cert *ctx );\n#endif /* MBEDTLS_SHA1_C */\n\n/**\n * \\brief           Set the Key Usage Extension flags\n *                  (e.g. MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_KEY_CERT_SIGN)\n *\n * \\param ctx       CRT context to use\n * \\param key_usage key usage flags to set\n *\n * \\return          0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED\n */\nint mbedtls_x509write_crt_set_key_usage( mbedtls_x509write_cert *ctx,\n                                         unsigned int key_usage );\n\n/**\n * \\brief           Set the Netscape Cert Type flags\n *                  (e.g. MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT | MBEDTLS_X509_NS_CERT_TYPE_EMAIL)\n *\n * \\param ctx           CRT context to use\n * \\param ns_cert_type  Netscape Cert Type flags to set\n *\n * \\return          0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED\n */\nint mbedtls_x509write_crt_set_ns_cert_type( mbedtls_x509write_cert *ctx,\n                                    unsigned char ns_cert_type );\n\n/**\n * \\brief           Free the contents of a CRT write context\n *\n * \\param ctx       CRT context to free\n */\nvoid mbedtls_x509write_crt_free( mbedtls_x509write_cert *ctx );\n\n/**\n * \\brief           Write a built up certificate to a X509 DER structure\n *                  Note: data is written at the end of the buffer! Use the\n *                        return value to determine where you should start\n *                        using the buffer\n *\n * \\param ctx       certificate to write away\n * \\param buf       buffer to write to\n * \\param size      size of the buffer\n * \\param f_rng     RNG function (for signature, see note)\n * \\param p_rng     RNG parameter\n *\n * \\return          length of data written if successful, or a specific\n *                  error code\n *\n * \\note            f_rng may be NULL if RSA is used for signature and the\n *                  signature is made offline (otherwise f_rng is desirable\n *                  for countermeasures against timing attacks).\n *                  ECDSA signatures always require a non-NULL f_rng.\n */\nint mbedtls_x509write_crt_der( mbedtls_x509write_cert *ctx, unsigned char *buf, size_t size,\n                       int (*f_rng)(void *, unsigned char *, size_t),\n                       void *p_rng );\n\n#if defined(MBEDTLS_PEM_WRITE_C)\n/**\n * \\brief           Write a built up certificate to a X509 PEM string\n *\n * \\param ctx       certificate to write away\n * \\param buf       buffer to write to\n * \\param size      size of the buffer\n * \\param f_rng     RNG function (for signature, see note)\n * \\param p_rng     RNG parameter\n *\n * \\return          0 if successful, or a specific error code\n *\n * \\note            f_rng may be NULL if RSA is used for signature and the\n *                  signature is made offline (otherwise f_rng is desirable\n *                  for countermeasures against timing attacks).\n *                  ECDSA signatures always require a non-NULL f_rng.\n */\nint mbedtls_x509write_crt_pem( mbedtls_x509write_cert *ctx, unsigned char *buf, size_t size,\n                       int (*f_rng)(void *, unsigned char *, size_t),\n                       void *p_rng );\n#endif /* MBEDTLS_PEM_WRITE_C */\n#endif /* MBEDTLS_X509_CRT_WRITE_C */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* mbedtls_x509_crt.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/x509_csr.h",
    "content": "/**\n * \\file x509_csr.h\n *\n * \\brief X.509 certificate signing request parsing and writing\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_X509_CSR_H\n#define MBEDTLS_X509_CSR_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include \"x509.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\addtogroup x509_module\n * \\{ */\n\n/**\n * \\name Structures and functions for X.509 Certificate Signing Requests (CSR)\n * \\{\n */\n\n/**\n * Certificate Signing Request (CSR) structure.\n */\ntypedef struct mbedtls_x509_csr\n{\n    mbedtls_x509_buf raw;           /**< The raw CSR data (DER). */\n    mbedtls_x509_buf cri;           /**< The raw CertificateRequestInfo body (DER). */\n\n    int version;            /**< CSR version (1=v1). */\n\n    mbedtls_x509_buf  subject_raw;  /**< The raw subject data (DER). */\n    mbedtls_x509_name subject;      /**< The parsed subject data (named information object). */\n\n    mbedtls_pk_context pk;          /**< Container for the public key context. */\n\n    mbedtls_x509_buf sig_oid;\n    mbedtls_x509_buf sig;\n    mbedtls_md_type_t sig_md;       /**< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */\n    mbedtls_pk_type_t sig_pk;       /**< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */\n    void *sig_opts;         /**< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */\n}\nmbedtls_x509_csr;\n\n/**\n * Container for writing a CSR\n */\ntypedef struct mbedtls_x509write_csr\n{\n    mbedtls_pk_context *key;\n    mbedtls_asn1_named_data *subject;\n    mbedtls_md_type_t md_alg;\n    mbedtls_asn1_named_data *extensions;\n}\nmbedtls_x509write_csr;\n\n#if defined(MBEDTLS_X509_CSR_PARSE_C)\n/**\n * \\brief          Load a Certificate Signing Request (CSR) in DER format\n *\n * \\note           CSR attributes (if any) are currently silently ignored.\n *\n * \\param csr      CSR context to fill\n * \\param buf      buffer holding the CRL data\n * \\param buflen   size of the buffer\n *\n * \\return         0 if successful, or a specific X509 error code\n */\nint mbedtls_x509_csr_parse_der( mbedtls_x509_csr *csr,\n                        const unsigned char *buf, size_t buflen );\n\n/**\n * \\brief          Load a Certificate Signing Request (CSR), DER or PEM format\n *\n * \\note           See notes for \\c mbedtls_x509_csr_parse_der()\n *\n * \\param csr      CSR context to fill\n * \\param buf      buffer holding the CRL data\n * \\param buflen   size of the buffer\n *                 (including the terminating null byte for PEM data)\n *\n * \\return         0 if successful, or a specific X509 or PEM error code\n */\nint mbedtls_x509_csr_parse( mbedtls_x509_csr *csr, const unsigned char *buf, size_t buflen );\n\n#if defined(MBEDTLS_FS_IO)\n/**\n * \\brief          Load a Certificate Signing Request (CSR)\n *\n * \\note           See notes for \\c mbedtls_x509_csr_parse()\n *\n * \\param csr      CSR context to fill\n * \\param path     filename to read the CSR from\n *\n * \\return         0 if successful, or a specific X509 or PEM error code\n */\nint mbedtls_x509_csr_parse_file( mbedtls_x509_csr *csr, const char *path );\n#endif /* MBEDTLS_FS_IO */\n\n/**\n * \\brief          Returns an informational string about the\n *                 CSR.\n *\n * \\param buf      Buffer to write to\n * \\param size     Maximum size of buffer\n * \\param prefix   A line prefix\n * \\param csr      The X509 CSR to represent\n *\n * \\return         The length of the string written (not including the\n *                 terminated nul byte), or a negative error code.\n */\nint mbedtls_x509_csr_info( char *buf, size_t size, const char *prefix,\n                   const mbedtls_x509_csr *csr );\n\n/**\n * \\brief          Initialize a CSR\n *\n * \\param csr      CSR to initialize\n */\nvoid mbedtls_x509_csr_init( mbedtls_x509_csr *csr );\n\n/**\n * \\brief          Unallocate all CSR data\n *\n * \\param csr      CSR to free\n */\nvoid mbedtls_x509_csr_free( mbedtls_x509_csr *csr );\n#endif /* MBEDTLS_X509_CSR_PARSE_C */\n\n/* \\} name */\n/* \\} addtogroup x509_module */\n\n#if defined(MBEDTLS_X509_CSR_WRITE_C)\n/**\n * \\brief           Initialize a CSR context\n *\n * \\param ctx       CSR context to initialize\n */\nvoid mbedtls_x509write_csr_init( mbedtls_x509write_csr *ctx );\n\n/**\n * \\brief           Set the subject name for a CSR\n *                  Subject names should contain a comma-separated list\n *                  of OID types and values:\n *                  e.g. \"C=UK,O=ARM,CN=mbed TLS Server 1\"\n *\n * \\param ctx           CSR context to use\n * \\param subject_name  subject name to set\n *\n * \\return          0 if subject name was parsed successfully, or\n *                  a specific error code\n */\nint mbedtls_x509write_csr_set_subject_name( mbedtls_x509write_csr *ctx,\n                                    const char *subject_name );\n\n/**\n * \\brief           Set the key for a CSR (public key will be included,\n *                  private key used to sign the CSR when writing it)\n *\n * \\param ctx       CSR context to use\n * \\param key       Asymetric key to include\n */\nvoid mbedtls_x509write_csr_set_key( mbedtls_x509write_csr *ctx, mbedtls_pk_context *key );\n\n/**\n * \\brief           Set the MD algorithm to use for the signature\n *                  (e.g. MBEDTLS_MD_SHA1)\n *\n * \\param ctx       CSR context to use\n * \\param md_alg    MD algorithm to use\n */\nvoid mbedtls_x509write_csr_set_md_alg( mbedtls_x509write_csr *ctx, mbedtls_md_type_t md_alg );\n\n/**\n * \\brief           Set the Key Usage Extension flags\n *                  (e.g. MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_KEY_CERT_SIGN)\n *\n * \\param ctx       CSR context to use\n * \\param key_usage key usage flags to set\n *\n * \\return          0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED\n */\nint mbedtls_x509write_csr_set_key_usage( mbedtls_x509write_csr *ctx, unsigned char key_usage );\n\n/**\n * \\brief           Set the Netscape Cert Type flags\n *                  (e.g. MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT | MBEDTLS_X509_NS_CERT_TYPE_EMAIL)\n *\n * \\param ctx           CSR context to use\n * \\param ns_cert_type  Netscape Cert Type flags to set\n *\n * \\return          0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED\n */\nint mbedtls_x509write_csr_set_ns_cert_type( mbedtls_x509write_csr *ctx,\n                                    unsigned char ns_cert_type );\n\n/**\n * \\brief           Generic function to add to or replace an extension in the\n *                  CSR\n *\n * \\param ctx       CSR context to use\n * \\param oid       OID of the extension\n * \\param oid_len   length of the OID\n * \\param val       value of the extension OCTET STRING\n * \\param val_len   length of the value data\n *\n * \\return          0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED\n */\nint mbedtls_x509write_csr_set_extension( mbedtls_x509write_csr *ctx,\n                                 const char *oid, size_t oid_len,\n                                 const unsigned char *val, size_t val_len );\n\n/**\n * \\brief           Free the contents of a CSR context\n *\n * \\param ctx       CSR context to free\n */\nvoid mbedtls_x509write_csr_free( mbedtls_x509write_csr *ctx );\n\n/**\n * \\brief           Write a CSR (Certificate Signing Request) to a\n *                  DER structure\n *                  Note: data is written at the end of the buffer! Use the\n *                        return value to determine where you should start\n *                        using the buffer\n *\n * \\param ctx       CSR to write away\n * \\param buf       buffer to write to\n * \\param size      size of the buffer\n * \\param f_rng     RNG function (for signature, see note)\n * \\param p_rng     RNG parameter\n *\n * \\return          length of data written if successful, or a specific\n *                  error code\n *\n * \\note            f_rng may be NULL if RSA is used for signature and the\n *                  signature is made offline (otherwise f_rng is desirable\n *                  for countermeasures against timing attacks).\n *                  ECDSA signatures always require a non-NULL f_rng.\n */\nint mbedtls_x509write_csr_der( mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size,\n                       int (*f_rng)(void *, unsigned char *, size_t),\n                       void *p_rng );\n\n#if defined(MBEDTLS_PEM_WRITE_C)\n/**\n * \\brief           Write a CSR (Certificate Signing Request) to a\n *                  PEM string\n *\n * \\param ctx       CSR to write away\n * \\param buf       buffer to write to\n * \\param size      size of the buffer\n * \\param f_rng     RNG function (for signature, see note)\n * \\param p_rng     RNG parameter\n *\n * \\return          0 if successful, or a specific error code\n *\n * \\note            f_rng may be NULL if RSA is used for signature and the\n *                  signature is made offline (otherwise f_rng is desirable\n *                  for countermeasures against timing attacks).\n *                  ECDSA signatures always require a non-NULL f_rng.\n */\nint mbedtls_x509write_csr_pem( mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size,\n                       int (*f_rng)(void *, unsigned char *, size_t),\n                       void *p_rng );\n#endif /* MBEDTLS_PEM_WRITE_C */\n#endif /* MBEDTLS_X509_CSR_WRITE_C */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* mbedtls_x509_csr.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/include/mbedtls/xtea.h",
    "content": "/**\n * \\file xtea.h\n *\n * \\brief XTEA block cipher (32-bit)\n */\n/*\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#ifndef MBEDTLS_XTEA_H\n#define MBEDTLS_XTEA_H\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <stddef.h>\n#include <stdint.h>\n\n#define MBEDTLS_XTEA_ENCRYPT     1\n#define MBEDTLS_XTEA_DECRYPT     0\n\n#define MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH             -0x0028  /**< The data input has an invalid length. */\n#define MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED                  -0x0029  /**< XTEA hardware accelerator failed. */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if !defined(MBEDTLS_XTEA_ALT)\n// Regular implementation\n//\n\n/**\n * \\brief          XTEA context structure\n */\ntypedef struct\n{\n    uint32_t k[4];       /*!< key */\n}\nmbedtls_xtea_context;\n\n#else  /* MBEDTLS_XTEA_ALT */\n#include \"xtea_alt.h\"\n#endif /* MBEDTLS_XTEA_ALT */\n\n/**\n * \\brief          Initialize XTEA context\n *\n * \\param ctx      XTEA context to be initialized\n */\nvoid mbedtls_xtea_init( mbedtls_xtea_context *ctx );\n\n/**\n * \\brief          Clear XTEA context\n *\n * \\param ctx      XTEA context to be cleared\n */\nvoid mbedtls_xtea_free( mbedtls_xtea_context *ctx );\n\n/**\n * \\brief          XTEA key schedule\n *\n * \\param ctx      XTEA context to be initialized\n * \\param key      the secret key\n */\nvoid mbedtls_xtea_setup( mbedtls_xtea_context *ctx, const unsigned char key[16] );\n\n/**\n * \\brief          XTEA cipher function\n *\n * \\param ctx      XTEA context\n * \\param mode     MBEDTLS_XTEA_ENCRYPT or MBEDTLS_XTEA_DECRYPT\n * \\param input    8-byte input block\n * \\param output   8-byte output block\n *\n * \\return         0 if successful\n */\nint mbedtls_xtea_crypt_ecb( mbedtls_xtea_context *ctx,\n                    int mode,\n                    const unsigned char input[8],\n                    unsigned char output[8] );\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n/**\n * \\brief          XTEA CBC cipher function\n *\n * \\param ctx      XTEA context\n * \\param mode     MBEDTLS_XTEA_ENCRYPT or MBEDTLS_XTEA_DECRYPT\n * \\param length   the length of input, multiple of 8\n * \\param iv       initialization vector for CBC mode\n * \\param input    input block\n * \\param output   output block\n *\n * \\return         0 if successful,\n *                 MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH if the length % 8 != 0\n */\nint mbedtls_xtea_crypt_cbc( mbedtls_xtea_context *ctx,\n                    int mode,\n                    size_t length,\n                    unsigned char iv[8],\n                    const unsigned char *input,\n                    unsigned char *output);\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n/**\n * \\brief          Checkup routine\n *\n * \\return         0 if successful, or 1 if the test failed\n */\nint mbedtls_xtea_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* xtea.h */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/aes.c",
    "content": "/*\n *  FIPS-197 compliant AES implementation\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The AES block cipher was designed by Vincent Rijmen and Joan Daemen.\n *\n *  http://csrc.nist.gov/encryption/aes/rijndael/Rijndael.pdf\n *  http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_AES_C)\n\n#include <string.h>\n\n#include \"mbedtls/aes.h\"\n#include \"mbedtls/platform_util.h\"\n#if defined(MBEDTLS_PADLOCK_C)\n#include \"mbedtls/padlock.h\"\n#endif\n#if defined(MBEDTLS_AESNI_C)\n#include \"mbedtls/aesni.h\"\n#endif\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if !defined(MBEDTLS_AES_ALT)\n\n/*\n * 32-bit integer manipulation macros (little endian)\n */\n#ifndef GET_UINT32_LE\n#define GET_UINT32_LE(n,b,i)                            \\\n{                                                       \\\n    (n) = ( (uint32_t) (b)[(i)    ]       )             \\\n        | ( (uint32_t) (b)[(i) + 1] <<  8 )             \\\n        | ( (uint32_t) (b)[(i) + 2] << 16 )             \\\n        | ( (uint32_t) (b)[(i) + 3] << 24 );            \\\n}\n#endif\n\n#ifndef PUT_UINT32_LE\n#define PUT_UINT32_LE(n,b,i)                                    \\\n{                                                               \\\n    (b)[(i)    ] = (unsigned char) ( ( (n)       ) & 0xFF );    \\\n    (b)[(i) + 1] = (unsigned char) ( ( (n) >>  8 ) & 0xFF );    \\\n    (b)[(i) + 2] = (unsigned char) ( ( (n) >> 16 ) & 0xFF );    \\\n    (b)[(i) + 3] = (unsigned char) ( ( (n) >> 24 ) & 0xFF );    \\\n}\n#endif\n\n#if defined(MBEDTLS_PADLOCK_C) &&                      \\\n    ( defined(MBEDTLS_HAVE_X86) || defined(MBEDTLS_PADLOCK_ALIGN16) )\nstatic int aes_padlock_ace = -1;\n#endif\n\n#if defined(MBEDTLS_AES_ROM_TABLES)\n/*\n * Forward S-box\n */\nstatic const unsigned char FSb[256] =\n{\n    0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5,\n    0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,\n    0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0,\n    0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,\n    0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC,\n    0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\n    0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A,\n    0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,\n    0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0,\n    0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,\n    0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B,\n    0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,\n    0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85,\n    0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,\n    0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5,\n    0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,\n    0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17,\n    0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,\n    0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88,\n    0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,\n    0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C,\n    0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,\n    0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9,\n    0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,\n    0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6,\n    0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,\n    0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E,\n    0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,\n    0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94,\n    0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\n    0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68,\n    0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16\n};\n\n/*\n * Forward tables\n */\n#define FT \\\n\\\n    V(A5,63,63,C6), V(84,7C,7C,F8), V(99,77,77,EE), V(8D,7B,7B,F6), \\\n    V(0D,F2,F2,FF), V(BD,6B,6B,D6), V(B1,6F,6F,DE), V(54,C5,C5,91), \\\n    V(50,30,30,60), V(03,01,01,02), V(A9,67,67,CE), V(7D,2B,2B,56), \\\n    V(19,FE,FE,E7), V(62,D7,D7,B5), V(E6,AB,AB,4D), V(9A,76,76,EC), \\\n    V(45,CA,CA,8F), V(9D,82,82,1F), V(40,C9,C9,89), V(87,7D,7D,FA), \\\n    V(15,FA,FA,EF), V(EB,59,59,B2), V(C9,47,47,8E), V(0B,F0,F0,FB), \\\n    V(EC,AD,AD,41), V(67,D4,D4,B3), V(FD,A2,A2,5F), V(EA,AF,AF,45), \\\n    V(BF,9C,9C,23), V(F7,A4,A4,53), V(96,72,72,E4), V(5B,C0,C0,9B), \\\n    V(C2,B7,B7,75), V(1C,FD,FD,E1), V(AE,93,93,3D), V(6A,26,26,4C), \\\n    V(5A,36,36,6C), V(41,3F,3F,7E), V(02,F7,F7,F5), V(4F,CC,CC,83), \\\n    V(5C,34,34,68), V(F4,A5,A5,51), V(34,E5,E5,D1), V(08,F1,F1,F9), \\\n    V(93,71,71,E2), V(73,D8,D8,AB), V(53,31,31,62), V(3F,15,15,2A), \\\n    V(0C,04,04,08), V(52,C7,C7,95), V(65,23,23,46), V(5E,C3,C3,9D), \\\n    V(28,18,18,30), V(A1,96,96,37), V(0F,05,05,0A), V(B5,9A,9A,2F), \\\n    V(09,07,07,0E), V(36,12,12,24), V(9B,80,80,1B), V(3D,E2,E2,DF), \\\n    V(26,EB,EB,CD), V(69,27,27,4E), V(CD,B2,B2,7F), V(9F,75,75,EA), \\\n    V(1B,09,09,12), V(9E,83,83,1D), V(74,2C,2C,58), V(2E,1A,1A,34), \\\n    V(2D,1B,1B,36), V(B2,6E,6E,DC), V(EE,5A,5A,B4), V(FB,A0,A0,5B), \\\n    V(F6,52,52,A4), V(4D,3B,3B,76), V(61,D6,D6,B7), V(CE,B3,B3,7D), \\\n    V(7B,29,29,52), V(3E,E3,E3,DD), V(71,2F,2F,5E), V(97,84,84,13), \\\n    V(F5,53,53,A6), V(68,D1,D1,B9), V(00,00,00,00), V(2C,ED,ED,C1), \\\n    V(60,20,20,40), V(1F,FC,FC,E3), V(C8,B1,B1,79), V(ED,5B,5B,B6), \\\n    V(BE,6A,6A,D4), V(46,CB,CB,8D), V(D9,BE,BE,67), V(4B,39,39,72), \\\n    V(DE,4A,4A,94), V(D4,4C,4C,98), V(E8,58,58,B0), V(4A,CF,CF,85), \\\n    V(6B,D0,D0,BB), V(2A,EF,EF,C5), V(E5,AA,AA,4F), V(16,FB,FB,ED), \\\n    V(C5,43,43,86), V(D7,4D,4D,9A), V(55,33,33,66), V(94,85,85,11), \\\n    V(CF,45,45,8A), V(10,F9,F9,E9), V(06,02,02,04), V(81,7F,7F,FE), \\\n    V(F0,50,50,A0), V(44,3C,3C,78), V(BA,9F,9F,25), V(E3,A8,A8,4B), \\\n    V(F3,51,51,A2), V(FE,A3,A3,5D), V(C0,40,40,80), V(8A,8F,8F,05), \\\n    V(AD,92,92,3F), V(BC,9D,9D,21), V(48,38,38,70), V(04,F5,F5,F1), \\\n    V(DF,BC,BC,63), V(C1,B6,B6,77), V(75,DA,DA,AF), V(63,21,21,42), \\\n    V(30,10,10,20), V(1A,FF,FF,E5), V(0E,F3,F3,FD), V(6D,D2,D2,BF), \\\n    V(4C,CD,CD,81), V(14,0C,0C,18), V(35,13,13,26), V(2F,EC,EC,C3), \\\n    V(E1,5F,5F,BE), V(A2,97,97,35), V(CC,44,44,88), V(39,17,17,2E), \\\n    V(57,C4,C4,93), V(F2,A7,A7,55), V(82,7E,7E,FC), V(47,3D,3D,7A), \\\n    V(AC,64,64,C8), V(E7,5D,5D,BA), V(2B,19,19,32), V(95,73,73,E6), \\\n    V(A0,60,60,C0), V(98,81,81,19), V(D1,4F,4F,9E), V(7F,DC,DC,A3), \\\n    V(66,22,22,44), V(7E,2A,2A,54), V(AB,90,90,3B), V(83,88,88,0B), \\\n    V(CA,46,46,8C), V(29,EE,EE,C7), V(D3,B8,B8,6B), V(3C,14,14,28), \\\n    V(79,DE,DE,A7), V(E2,5E,5E,BC), V(1D,0B,0B,16), V(76,DB,DB,AD), \\\n    V(3B,E0,E0,DB), V(56,32,32,64), V(4E,3A,3A,74), V(1E,0A,0A,14), \\\n    V(DB,49,49,92), V(0A,06,06,0C), V(6C,24,24,48), V(E4,5C,5C,B8), \\\n    V(5D,C2,C2,9F), V(6E,D3,D3,BD), V(EF,AC,AC,43), V(A6,62,62,C4), \\\n    V(A8,91,91,39), V(A4,95,95,31), V(37,E4,E4,D3), V(8B,79,79,F2), \\\n    V(32,E7,E7,D5), V(43,C8,C8,8B), V(59,37,37,6E), V(B7,6D,6D,DA), \\\n    V(8C,8D,8D,01), V(64,D5,D5,B1), V(D2,4E,4E,9C), V(E0,A9,A9,49), \\\n    V(B4,6C,6C,D8), V(FA,56,56,AC), V(07,F4,F4,F3), V(25,EA,EA,CF), \\\n    V(AF,65,65,CA), V(8E,7A,7A,F4), V(E9,AE,AE,47), V(18,08,08,10), \\\n    V(D5,BA,BA,6F), V(88,78,78,F0), V(6F,25,25,4A), V(72,2E,2E,5C), \\\n    V(24,1C,1C,38), V(F1,A6,A6,57), V(C7,B4,B4,73), V(51,C6,C6,97), \\\n    V(23,E8,E8,CB), V(7C,DD,DD,A1), V(9C,74,74,E8), V(21,1F,1F,3E), \\\n    V(DD,4B,4B,96), V(DC,BD,BD,61), V(86,8B,8B,0D), V(85,8A,8A,0F), \\\n    V(90,70,70,E0), V(42,3E,3E,7C), V(C4,B5,B5,71), V(AA,66,66,CC), \\\n    V(D8,48,48,90), V(05,03,03,06), V(01,F6,F6,F7), V(12,0E,0E,1C), \\\n    V(A3,61,61,C2), V(5F,35,35,6A), V(F9,57,57,AE), V(D0,B9,B9,69), \\\n    V(91,86,86,17), V(58,C1,C1,99), V(27,1D,1D,3A), V(B9,9E,9E,27), \\\n    V(38,E1,E1,D9), V(13,F8,F8,EB), V(B3,98,98,2B), V(33,11,11,22), \\\n    V(BB,69,69,D2), V(70,D9,D9,A9), V(89,8E,8E,07), V(A7,94,94,33), \\\n    V(B6,9B,9B,2D), V(22,1E,1E,3C), V(92,87,87,15), V(20,E9,E9,C9), \\\n    V(49,CE,CE,87), V(FF,55,55,AA), V(78,28,28,50), V(7A,DF,DF,A5), \\\n    V(8F,8C,8C,03), V(F8,A1,A1,59), V(80,89,89,09), V(17,0D,0D,1A), \\\n    V(DA,BF,BF,65), V(31,E6,E6,D7), V(C6,42,42,84), V(B8,68,68,D0), \\\n    V(C3,41,41,82), V(B0,99,99,29), V(77,2D,2D,5A), V(11,0F,0F,1E), \\\n    V(CB,B0,B0,7B), V(FC,54,54,A8), V(D6,BB,BB,6D), V(3A,16,16,2C)\n\n#define V(a,b,c,d) 0x##a##b##c##d\nstatic const uint32_t FT0[256] = { FT };\n#undef V\n\n#if !defined(MBEDTLS_AES_FEWER_TABLES)\n\n#define V(a,b,c,d) 0x##b##c##d##a\nstatic const uint32_t FT1[256] = { FT };\n#undef V\n\n#define V(a,b,c,d) 0x##c##d##a##b\nstatic const uint32_t FT2[256] = { FT };\n#undef V\n\n#define V(a,b,c,d) 0x##d##a##b##c\nstatic const uint32_t FT3[256] = { FT };\n#undef V\n\n#endif /* !MBEDTLS_AES_FEWER_TABLES */\n\n#undef FT\n\n/*\n * Reverse S-box\n */\nstatic const unsigned char RSb[256] =\n{\n    0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38,\n    0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,\n    0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87,\n    0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,\n    0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D,\n    0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,\n    0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2,\n    0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,\n    0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16,\n    0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,\n    0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA,\n    0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,\n    0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A,\n    0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,\n    0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02,\n    0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,\n    0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA,\n    0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,\n    0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85,\n    0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,\n    0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89,\n    0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,\n    0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20,\n    0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,\n    0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31,\n    0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,\n    0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D,\n    0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,\n    0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0,\n    0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,\n    0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26,\n    0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D\n};\n\n/*\n * Reverse tables\n */\n#define RT \\\n\\\n    V(50,A7,F4,51), V(53,65,41,7E), V(C3,A4,17,1A), V(96,5E,27,3A), \\\n    V(CB,6B,AB,3B), V(F1,45,9D,1F), V(AB,58,FA,AC), V(93,03,E3,4B), \\\n    V(55,FA,30,20), V(F6,6D,76,AD), V(91,76,CC,88), V(25,4C,02,F5), \\\n    V(FC,D7,E5,4F), V(D7,CB,2A,C5), V(80,44,35,26), V(8F,A3,62,B5), \\\n    V(49,5A,B1,DE), V(67,1B,BA,25), V(98,0E,EA,45), V(E1,C0,FE,5D), \\\n    V(02,75,2F,C3), V(12,F0,4C,81), V(A3,97,46,8D), V(C6,F9,D3,6B), \\\n    V(E7,5F,8F,03), V(95,9C,92,15), V(EB,7A,6D,BF), V(DA,59,52,95), \\\n    V(2D,83,BE,D4), V(D3,21,74,58), V(29,69,E0,49), V(44,C8,C9,8E), \\\n    V(6A,89,C2,75), V(78,79,8E,F4), V(6B,3E,58,99), V(DD,71,B9,27), \\\n    V(B6,4F,E1,BE), V(17,AD,88,F0), V(66,AC,20,C9), V(B4,3A,CE,7D), \\\n    V(18,4A,DF,63), V(82,31,1A,E5), V(60,33,51,97), V(45,7F,53,62), \\\n    V(E0,77,64,B1), V(84,AE,6B,BB), V(1C,A0,81,FE), V(94,2B,08,F9), \\\n    V(58,68,48,70), V(19,FD,45,8F), V(87,6C,DE,94), V(B7,F8,7B,52), \\\n    V(23,D3,73,AB), V(E2,02,4B,72), V(57,8F,1F,E3), V(2A,AB,55,66), \\\n    V(07,28,EB,B2), V(03,C2,B5,2F), V(9A,7B,C5,86), V(A5,08,37,D3), \\\n    V(F2,87,28,30), V(B2,A5,BF,23), V(BA,6A,03,02), V(5C,82,16,ED), \\\n    V(2B,1C,CF,8A), V(92,B4,79,A7), V(F0,F2,07,F3), V(A1,E2,69,4E), \\\n    V(CD,F4,DA,65), V(D5,BE,05,06), V(1F,62,34,D1), V(8A,FE,A6,C4), \\\n    V(9D,53,2E,34), V(A0,55,F3,A2), V(32,E1,8A,05), V(75,EB,F6,A4), \\\n    V(39,EC,83,0B), V(AA,EF,60,40), V(06,9F,71,5E), V(51,10,6E,BD), \\\n    V(F9,8A,21,3E), V(3D,06,DD,96), V(AE,05,3E,DD), V(46,BD,E6,4D), \\\n    V(B5,8D,54,91), V(05,5D,C4,71), V(6F,D4,06,04), V(FF,15,50,60), \\\n    V(24,FB,98,19), V(97,E9,BD,D6), V(CC,43,40,89), V(77,9E,D9,67), \\\n    V(BD,42,E8,B0), V(88,8B,89,07), V(38,5B,19,E7), V(DB,EE,C8,79), \\\n    V(47,0A,7C,A1), V(E9,0F,42,7C), V(C9,1E,84,F8), V(00,00,00,00), \\\n    V(83,86,80,09), V(48,ED,2B,32), V(AC,70,11,1E), V(4E,72,5A,6C), \\\n    V(FB,FF,0E,FD), V(56,38,85,0F), V(1E,D5,AE,3D), V(27,39,2D,36), \\\n    V(64,D9,0F,0A), V(21,A6,5C,68), V(D1,54,5B,9B), V(3A,2E,36,24), \\\n    V(B1,67,0A,0C), V(0F,E7,57,93), V(D2,96,EE,B4), V(9E,91,9B,1B), \\\n    V(4F,C5,C0,80), V(A2,20,DC,61), V(69,4B,77,5A), V(16,1A,12,1C), \\\n    V(0A,BA,93,E2), V(E5,2A,A0,C0), V(43,E0,22,3C), V(1D,17,1B,12), \\\n    V(0B,0D,09,0E), V(AD,C7,8B,F2), V(B9,A8,B6,2D), V(C8,A9,1E,14), \\\n    V(85,19,F1,57), V(4C,07,75,AF), V(BB,DD,99,EE), V(FD,60,7F,A3), \\\n    V(9F,26,01,F7), V(BC,F5,72,5C), V(C5,3B,66,44), V(34,7E,FB,5B), \\\n    V(76,29,43,8B), V(DC,C6,23,CB), V(68,FC,ED,B6), V(63,F1,E4,B8), \\\n    V(CA,DC,31,D7), V(10,85,63,42), V(40,22,97,13), V(20,11,C6,84), \\\n    V(7D,24,4A,85), V(F8,3D,BB,D2), V(11,32,F9,AE), V(6D,A1,29,C7), \\\n    V(4B,2F,9E,1D), V(F3,30,B2,DC), V(EC,52,86,0D), V(D0,E3,C1,77), \\\n    V(6C,16,B3,2B), V(99,B9,70,A9), V(FA,48,94,11), V(22,64,E9,47), \\\n    V(C4,8C,FC,A8), V(1A,3F,F0,A0), V(D8,2C,7D,56), V(EF,90,33,22), \\\n    V(C7,4E,49,87), V(C1,D1,38,D9), V(FE,A2,CA,8C), V(36,0B,D4,98), \\\n    V(CF,81,F5,A6), V(28,DE,7A,A5), V(26,8E,B7,DA), V(A4,BF,AD,3F), \\\n    V(E4,9D,3A,2C), V(0D,92,78,50), V(9B,CC,5F,6A), V(62,46,7E,54), \\\n    V(C2,13,8D,F6), V(E8,B8,D8,90), V(5E,F7,39,2E), V(F5,AF,C3,82), \\\n    V(BE,80,5D,9F), V(7C,93,D0,69), V(A9,2D,D5,6F), V(B3,12,25,CF), \\\n    V(3B,99,AC,C8), V(A7,7D,18,10), V(6E,63,9C,E8), V(7B,BB,3B,DB), \\\n    V(09,78,26,CD), V(F4,18,59,6E), V(01,B7,9A,EC), V(A8,9A,4F,83), \\\n    V(65,6E,95,E6), V(7E,E6,FF,AA), V(08,CF,BC,21), V(E6,E8,15,EF), \\\n    V(D9,9B,E7,BA), V(CE,36,6F,4A), V(D4,09,9F,EA), V(D6,7C,B0,29), \\\n    V(AF,B2,A4,31), V(31,23,3F,2A), V(30,94,A5,C6), V(C0,66,A2,35), \\\n    V(37,BC,4E,74), V(A6,CA,82,FC), V(B0,D0,90,E0), V(15,D8,A7,33), \\\n    V(4A,98,04,F1), V(F7,DA,EC,41), V(0E,50,CD,7F), V(2F,F6,91,17), \\\n    V(8D,D6,4D,76), V(4D,B0,EF,43), V(54,4D,AA,CC), V(DF,04,96,E4), \\\n    V(E3,B5,D1,9E), V(1B,88,6A,4C), V(B8,1F,2C,C1), V(7F,51,65,46), \\\n    V(04,EA,5E,9D), V(5D,35,8C,01), V(73,74,87,FA), V(2E,41,0B,FB), \\\n    V(5A,1D,67,B3), V(52,D2,DB,92), V(33,56,10,E9), V(13,47,D6,6D), \\\n    V(8C,61,D7,9A), V(7A,0C,A1,37), V(8E,14,F8,59), V(89,3C,13,EB), \\\n    V(EE,27,A9,CE), V(35,C9,61,B7), V(ED,E5,1C,E1), V(3C,B1,47,7A), \\\n    V(59,DF,D2,9C), V(3F,73,F2,55), V(79,CE,14,18), V(BF,37,C7,73), \\\n    V(EA,CD,F7,53), V(5B,AA,FD,5F), V(14,6F,3D,DF), V(86,DB,44,78), \\\n    V(81,F3,AF,CA), V(3E,C4,68,B9), V(2C,34,24,38), V(5F,40,A3,C2), \\\n    V(72,C3,1D,16), V(0C,25,E2,BC), V(8B,49,3C,28), V(41,95,0D,FF), \\\n    V(71,01,A8,39), V(DE,B3,0C,08), V(9C,E4,B4,D8), V(90,C1,56,64), \\\n    V(61,84,CB,7B), V(70,B6,32,D5), V(74,5C,6C,48), V(42,57,B8,D0)\n\n#define V(a,b,c,d) 0x##a##b##c##d\nstatic const uint32_t RT0[256] = { RT };\n#undef V\n\n#if !defined(MBEDTLS_AES_FEWER_TABLES)\n\n#define V(a,b,c,d) 0x##b##c##d##a\nstatic const uint32_t RT1[256] = { RT };\n#undef V\n\n#define V(a,b,c,d) 0x##c##d##a##b\nstatic const uint32_t RT2[256] = { RT };\n#undef V\n\n#define V(a,b,c,d) 0x##d##a##b##c\nstatic const uint32_t RT3[256] = { RT };\n#undef V\n\n#endif /* !MBEDTLS_AES_FEWER_TABLES */\n\n#undef RT\n\n/*\n * Round constants\n */\nstatic const uint32_t RCON[10] =\n{\n    0x00000001, 0x00000002, 0x00000004, 0x00000008,\n    0x00000010, 0x00000020, 0x00000040, 0x00000080,\n    0x0000001B, 0x00000036\n};\n\n#else /* MBEDTLS_AES_ROM_TABLES */\n\n/*\n * Forward S-box & tables\n */\nstatic unsigned char FSb[256];\nstatic uint32_t FT0[256];\n#if !defined(MBEDTLS_AES_FEWER_TABLES)\nstatic uint32_t FT1[256];\nstatic uint32_t FT2[256];\nstatic uint32_t FT3[256];\n#endif /* !MBEDTLS_AES_FEWER_TABLES */\n\n/*\n * Reverse S-box & tables\n */\nstatic unsigned char RSb[256];\nstatic uint32_t RT0[256];\n#if !defined(MBEDTLS_AES_FEWER_TABLES)\nstatic uint32_t RT1[256];\nstatic uint32_t RT2[256];\nstatic uint32_t RT3[256];\n#endif /* !MBEDTLS_AES_FEWER_TABLES */\n\n/*\n * Round constants\n */\nstatic uint32_t RCON[10];\n\n/*\n * Tables generation code\n */\n#define ROTL8(x) ( ( x << 8 ) & 0xFFFFFFFF ) | ( x >> 24 )\n#define XTIME(x) ( ( x << 1 ) ^ ( ( x & 0x80 ) ? 0x1B : 0x00 ) )\n#define MUL(x,y) ( ( x && y ) ? pow[(log[x]+log[y]) % 255] : 0 )\n\nstatic int aes_init_done = 0;\n\nstatic void aes_gen_tables( void )\n{\n    int i, x, y, z;\n    int pow[256];\n    int log[256];\n\n    /*\n     * compute pow and log tables over GF(2^8)\n     */\n    for( i = 0, x = 1; i < 256; i++ )\n    {\n        pow[i] = x;\n        log[x] = i;\n        x = ( x ^ XTIME( x ) ) & 0xFF;\n    }\n\n    /*\n     * calculate the round constants\n     */\n    for( i = 0, x = 1; i < 10; i++ )\n    {\n        RCON[i] = (uint32_t) x;\n        x = XTIME( x ) & 0xFF;\n    }\n\n    /*\n     * generate the forward and reverse S-boxes\n     */\n    FSb[0x00] = 0x63;\n    RSb[0x63] = 0x00;\n\n    for( i = 1; i < 256; i++ )\n    {\n        x = pow[255 - log[i]];\n\n        y  = x; y = ( ( y << 1 ) | ( y >> 7 ) ) & 0xFF;\n        x ^= y; y = ( ( y << 1 ) | ( y >> 7 ) ) & 0xFF;\n        x ^= y; y = ( ( y << 1 ) | ( y >> 7 ) ) & 0xFF;\n        x ^= y; y = ( ( y << 1 ) | ( y >> 7 ) ) & 0xFF;\n        x ^= y ^ 0x63;\n\n        FSb[i] = (unsigned char) x;\n        RSb[x] = (unsigned char) i;\n    }\n\n    /*\n     * generate the forward and reverse tables\n     */\n    for( i = 0; i < 256; i++ )\n    {\n        x = FSb[i];\n        y = XTIME( x ) & 0xFF;\n        z =  ( y ^ x ) & 0xFF;\n\n        FT0[i] = ( (uint32_t) y       ) ^\n                 ( (uint32_t) x <<  8 ) ^\n                 ( (uint32_t) x << 16 ) ^\n                 ( (uint32_t) z << 24 );\n\n#if !defined(MBEDTLS_AES_FEWER_TABLES)\n        FT1[i] = ROTL8( FT0[i] );\n        FT2[i] = ROTL8( FT1[i] );\n        FT3[i] = ROTL8( FT2[i] );\n#endif /* !MBEDTLS_AES_FEWER_TABLES */\n\n        x = RSb[i];\n\n        RT0[i] = ( (uint32_t) MUL( 0x0E, x )       ) ^\n                 ( (uint32_t) MUL( 0x09, x ) <<  8 ) ^\n                 ( (uint32_t) MUL( 0x0D, x ) << 16 ) ^\n                 ( (uint32_t) MUL( 0x0B, x ) << 24 );\n\n#if !defined(MBEDTLS_AES_FEWER_TABLES)\n        RT1[i] = ROTL8( RT0[i] );\n        RT2[i] = ROTL8( RT1[i] );\n        RT3[i] = ROTL8( RT2[i] );\n#endif /* !MBEDTLS_AES_FEWER_TABLES */\n    }\n}\n\n#undef ROTL8\n\n#endif /* MBEDTLS_AES_ROM_TABLES */\n\n#if defined(MBEDTLS_AES_FEWER_TABLES)\n\n#define ROTL8(x)  ( (uint32_t)( ( x ) <<  8 ) + (uint32_t)( ( x ) >> 24 ) )\n#define ROTL16(x) ( (uint32_t)( ( x ) << 16 ) + (uint32_t)( ( x ) >> 16 ) )\n#define ROTL24(x) ( (uint32_t)( ( x ) << 24 ) + (uint32_t)( ( x ) >>  8 ) )\n\n#define AES_RT0(idx) RT0[idx]\n#define AES_RT1(idx) ROTL8(  RT0[idx] )\n#define AES_RT2(idx) ROTL16( RT0[idx] )\n#define AES_RT3(idx) ROTL24( RT0[idx] )\n\n#define AES_FT0(idx) FT0[idx]\n#define AES_FT1(idx) ROTL8(  FT0[idx] )\n#define AES_FT2(idx) ROTL16( FT0[idx] )\n#define AES_FT3(idx) ROTL24( FT0[idx] )\n\n#else /* MBEDTLS_AES_FEWER_TABLES */\n\n#define AES_RT0(idx) RT0[idx]\n#define AES_RT1(idx) RT1[idx]\n#define AES_RT2(idx) RT2[idx]\n#define AES_RT3(idx) RT3[idx]\n\n#define AES_FT0(idx) FT0[idx]\n#define AES_FT1(idx) FT1[idx]\n#define AES_FT2(idx) FT2[idx]\n#define AES_FT3(idx) FT3[idx]\n\n#endif /* MBEDTLS_AES_FEWER_TABLES */\n\nvoid mbedtls_aes_init( mbedtls_aes_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_aes_context ) );\n}\n\nvoid mbedtls_aes_free( mbedtls_aes_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_aes_context ) );\n}\n\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\nvoid mbedtls_aes_xts_init( mbedtls_aes_xts_context *ctx )\n{\n    mbedtls_aes_init( &ctx->crypt );\n    mbedtls_aes_init( &ctx->tweak );\n}\n\nvoid mbedtls_aes_xts_free( mbedtls_aes_xts_context *ctx )\n{\n    mbedtls_aes_free( &ctx->crypt );\n    mbedtls_aes_free( &ctx->tweak );\n}\n#endif /* MBEDTLS_CIPHER_MODE_XTS */\n\n/*\n * AES key schedule (encryption)\n */\n#if !defined(MBEDTLS_AES_SETKEY_ENC_ALT)\nint mbedtls_aes_setkey_enc( mbedtls_aes_context *ctx, const unsigned char *key,\n                    unsigned int keybits )\n{\n    unsigned int i;\n    uint32_t *RK;\n\n#if !defined(MBEDTLS_AES_ROM_TABLES)\n    if( aes_init_done == 0 )\n    {\n        aes_gen_tables();\n        aes_init_done = 1;\n\n    }\n#endif\n\n    switch( keybits )\n    {\n        case 128: ctx->nr = 10; break;\n        case 192: ctx->nr = 12; break;\n        case 256: ctx->nr = 14; break;\n        default : return( MBEDTLS_ERR_AES_INVALID_KEY_LENGTH );\n    }\n\n#if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_PADLOCK_ALIGN16)\n    if( aes_padlock_ace == -1 )\n        aes_padlock_ace = mbedtls_padlock_has_support( MBEDTLS_PADLOCK_ACE );\n\n    if( aes_padlock_ace )\n        ctx->rk = RK = MBEDTLS_PADLOCK_ALIGN16( ctx->buf );\n    else\n#endif\n    ctx->rk = RK = ctx->buf;\n\n#if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64)\n    if( mbedtls_aesni_has_support( MBEDTLS_AESNI_AES ) )\n        return( mbedtls_aesni_setkey_enc( (unsigned char *) ctx->rk, key, keybits ) );\n#endif\n\n    for( i = 0; i < ( keybits >> 5 ); i++ )\n    {\n        GET_UINT32_LE( RK[i], key, i << 2 );\n    }\n\n    switch( ctx->nr )\n    {\n        case 10:\n\n            for( i = 0; i < 10; i++, RK += 4 )\n            {\n                RK[4]  = RK[0] ^ RCON[i] ^\n                ( (uint32_t) FSb[ ( RK[3] >>  8 ) & 0xFF ]       ) ^\n                ( (uint32_t) FSb[ ( RK[3] >> 16 ) & 0xFF ] <<  8 ) ^\n                ( (uint32_t) FSb[ ( RK[3] >> 24 ) & 0xFF ] << 16 ) ^\n                ( (uint32_t) FSb[ ( RK[3]       ) & 0xFF ] << 24 );\n\n                RK[5]  = RK[1] ^ RK[4];\n                RK[6]  = RK[2] ^ RK[5];\n                RK[7]  = RK[3] ^ RK[6];\n            }\n            break;\n\n        case 12:\n\n            for( i = 0; i < 8; i++, RK += 6 )\n            {\n                RK[6]  = RK[0] ^ RCON[i] ^\n                ( (uint32_t) FSb[ ( RK[5] >>  8 ) & 0xFF ]       ) ^\n                ( (uint32_t) FSb[ ( RK[5] >> 16 ) & 0xFF ] <<  8 ) ^\n                ( (uint32_t) FSb[ ( RK[5] >> 24 ) & 0xFF ] << 16 ) ^\n                ( (uint32_t) FSb[ ( RK[5]       ) & 0xFF ] << 24 );\n\n                RK[7]  = RK[1] ^ RK[6];\n                RK[8]  = RK[2] ^ RK[7];\n                RK[9]  = RK[3] ^ RK[8];\n                RK[10] = RK[4] ^ RK[9];\n                RK[11] = RK[5] ^ RK[10];\n            }\n            break;\n\n        case 14:\n\n            for( i = 0; i < 7; i++, RK += 8 )\n            {\n                RK[8]  = RK[0] ^ RCON[i] ^\n                ( (uint32_t) FSb[ ( RK[7] >>  8 ) & 0xFF ]       ) ^\n                ( (uint32_t) FSb[ ( RK[7] >> 16 ) & 0xFF ] <<  8 ) ^\n                ( (uint32_t) FSb[ ( RK[7] >> 24 ) & 0xFF ] << 16 ) ^\n                ( (uint32_t) FSb[ ( RK[7]       ) & 0xFF ] << 24 );\n\n                RK[9]  = RK[1] ^ RK[8];\n                RK[10] = RK[2] ^ RK[9];\n                RK[11] = RK[3] ^ RK[10];\n\n                RK[12] = RK[4] ^\n                ( (uint32_t) FSb[ ( RK[11]       ) & 0xFF ]       ) ^\n                ( (uint32_t) FSb[ ( RK[11] >>  8 ) & 0xFF ] <<  8 ) ^\n                ( (uint32_t) FSb[ ( RK[11] >> 16 ) & 0xFF ] << 16 ) ^\n                ( (uint32_t) FSb[ ( RK[11] >> 24 ) & 0xFF ] << 24 );\n\n                RK[13] = RK[5] ^ RK[12];\n                RK[14] = RK[6] ^ RK[13];\n                RK[15] = RK[7] ^ RK[14];\n            }\n            break;\n    }\n\n    return( 0 );\n}\n#endif /* !MBEDTLS_AES_SETKEY_ENC_ALT */\n\n/*\n * AES key schedule (decryption)\n */\n#if !defined(MBEDTLS_AES_SETKEY_DEC_ALT)\nint mbedtls_aes_setkey_dec( mbedtls_aes_context *ctx, const unsigned char *key,\n                    unsigned int keybits )\n{\n    int i, j, ret;\n    mbedtls_aes_context cty;\n    uint32_t *RK;\n    uint32_t *SK;\n\n    mbedtls_aes_init( &cty );\n\n#if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_PADLOCK_ALIGN16)\n    if( aes_padlock_ace == -1 )\n        aes_padlock_ace = mbedtls_padlock_has_support( MBEDTLS_PADLOCK_ACE );\n\n    if( aes_padlock_ace )\n        ctx->rk = RK = MBEDTLS_PADLOCK_ALIGN16( ctx->buf );\n    else\n#endif\n    ctx->rk = RK = ctx->buf;\n\n    /* Also checks keybits */\n    if( ( ret = mbedtls_aes_setkey_enc( &cty, key, keybits ) ) != 0 )\n        goto exit;\n\n    ctx->nr = cty.nr;\n\n#if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64)\n    if( mbedtls_aesni_has_support( MBEDTLS_AESNI_AES ) )\n    {\n        mbedtls_aesni_inverse_key( (unsigned char *) ctx->rk,\n                           (const unsigned char *) cty.rk, ctx->nr );\n        goto exit;\n    }\n#endif\n\n    SK = cty.rk + cty.nr * 4;\n\n    *RK++ = *SK++;\n    *RK++ = *SK++;\n    *RK++ = *SK++;\n    *RK++ = *SK++;\n\n    for( i = ctx->nr - 1, SK -= 8; i > 0; i--, SK -= 8 )\n    {\n        for( j = 0; j < 4; j++, SK++ )\n        {\n            *RK++ = AES_RT0( FSb[ ( *SK       ) & 0xFF ] ) ^\n                    AES_RT1( FSb[ ( *SK >>  8 ) & 0xFF ] ) ^\n                    AES_RT2( FSb[ ( *SK >> 16 ) & 0xFF ] ) ^\n                    AES_RT3( FSb[ ( *SK >> 24 ) & 0xFF ] );\n        }\n    }\n\n    *RK++ = *SK++;\n    *RK++ = *SK++;\n    *RK++ = *SK++;\n    *RK++ = *SK++;\n\nexit:\n    mbedtls_aes_free( &cty );\n\n    return( ret );\n}\n\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\nstatic int mbedtls_aes_xts_decode_keys( const unsigned char *key,\n                                        unsigned int keybits,\n                                        const unsigned char **key1,\n                                        unsigned int *key1bits,\n                                        const unsigned char **key2,\n                                        unsigned int *key2bits )\n{\n    const unsigned int half_keybits = keybits / 2;\n    const unsigned int half_keybytes = half_keybits / 8;\n\n    switch( keybits )\n    {\n        case 256: break;\n        case 512: break;\n        default : return( MBEDTLS_ERR_AES_INVALID_KEY_LENGTH );\n    }\n\n    *key1bits = half_keybits;\n    *key2bits = half_keybits;\n    *key1 = &key[0];\n    *key2 = &key[half_keybytes];\n\n    return 0;\n}\n\nint mbedtls_aes_xts_setkey_enc( mbedtls_aes_xts_context *ctx,\n                                const unsigned char *key,\n                                unsigned int keybits)\n{\n    int ret;\n    const unsigned char *key1, *key2;\n    unsigned int key1bits, key2bits;\n\n    ret = mbedtls_aes_xts_decode_keys( key, keybits, &key1, &key1bits,\n                                       &key2, &key2bits );\n    if( ret != 0 )\n        return( ret );\n\n    /* Set the tweak key. Always set tweak key for the encryption mode. */\n    ret = mbedtls_aes_setkey_enc( &ctx->tweak, key2, key2bits );\n    if( ret != 0 )\n        return( ret );\n\n    /* Set crypt key for encryption. */\n    return mbedtls_aes_setkey_enc( &ctx->crypt, key1, key1bits );\n}\n\nint mbedtls_aes_xts_setkey_dec( mbedtls_aes_xts_context *ctx,\n                                const unsigned char *key,\n                                unsigned int keybits)\n{\n    int ret;\n    const unsigned char *key1, *key2;\n    unsigned int key1bits, key2bits;\n\n    ret = mbedtls_aes_xts_decode_keys( key, keybits, &key1, &key1bits,\n                                       &key2, &key2bits );\n    if( ret != 0 )\n        return( ret );\n\n    /* Set the tweak key. Always set tweak key for encryption. */\n    ret = mbedtls_aes_setkey_enc( &ctx->tweak, key2, key2bits );\n    if( ret != 0 )\n        return( ret );\n\n    /* Set crypt key for decryption. */\n    return mbedtls_aes_setkey_dec( &ctx->crypt, key1, key1bits );\n}\n#endif /* MBEDTLS_CIPHER_MODE_XTS */\n\n#endif /* !MBEDTLS_AES_SETKEY_DEC_ALT */\n\n#define AES_FROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3)         \\\n{                                                   \\\n    X0 = *RK++ ^ AES_FT0( ( Y0       ) & 0xFF ) ^   \\\n                 AES_FT1( ( Y1 >>  8 ) & 0xFF ) ^   \\\n                 AES_FT2( ( Y2 >> 16 ) & 0xFF ) ^   \\\n                 AES_FT3( ( Y3 >> 24 ) & 0xFF );    \\\n                                                    \\\n    X1 = *RK++ ^ AES_FT0( ( Y1       ) & 0xFF ) ^   \\\n                 AES_FT1( ( Y2 >>  8 ) & 0xFF ) ^   \\\n                 AES_FT2( ( Y3 >> 16 ) & 0xFF ) ^   \\\n                 AES_FT3( ( Y0 >> 24 ) & 0xFF );    \\\n                                                    \\\n    X2 = *RK++ ^ AES_FT0( ( Y2       ) & 0xFF ) ^   \\\n                 AES_FT1( ( Y3 >>  8 ) & 0xFF ) ^   \\\n                 AES_FT2( ( Y0 >> 16 ) & 0xFF ) ^   \\\n                 AES_FT3( ( Y1 >> 24 ) & 0xFF );    \\\n                                                    \\\n    X3 = *RK++ ^ AES_FT0( ( Y3       ) & 0xFF ) ^   \\\n                 AES_FT1( ( Y0 >>  8 ) & 0xFF ) ^   \\\n                 AES_FT2( ( Y1 >> 16 ) & 0xFF ) ^   \\\n                 AES_FT3( ( Y2 >> 24 ) & 0xFF );    \\\n}\n\n#define AES_RROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3)         \\\n{                                                   \\\n    X0 = *RK++ ^ AES_RT0( ( Y0       ) & 0xFF ) ^   \\\n                 AES_RT1( ( Y3 >>  8 ) & 0xFF ) ^   \\\n                 AES_RT2( ( Y2 >> 16 ) & 0xFF ) ^   \\\n                 AES_RT3( ( Y1 >> 24 ) & 0xFF );    \\\n                                                    \\\n    X1 = *RK++ ^ AES_RT0( ( Y1       ) & 0xFF ) ^   \\\n                 AES_RT1( ( Y0 >>  8 ) & 0xFF ) ^   \\\n                 AES_RT2( ( Y3 >> 16 ) & 0xFF ) ^   \\\n                 AES_RT3( ( Y2 >> 24 ) & 0xFF );    \\\n                                                    \\\n    X2 = *RK++ ^ AES_RT0( ( Y2       ) & 0xFF ) ^   \\\n                 AES_RT1( ( Y1 >>  8 ) & 0xFF ) ^   \\\n                 AES_RT2( ( Y0 >> 16 ) & 0xFF ) ^   \\\n                 AES_RT3( ( Y3 >> 24 ) & 0xFF );    \\\n                                                    \\\n    X3 = *RK++ ^ AES_RT0( ( Y3       ) & 0xFF ) ^   \\\n                 AES_RT1( ( Y2 >>  8 ) & 0xFF ) ^   \\\n                 AES_RT2( ( Y1 >> 16 ) & 0xFF ) ^   \\\n                 AES_RT3( ( Y0 >> 24 ) & 0xFF );    \\\n}\n\n/*\n * AES-ECB block encryption\n */\n#if !defined(MBEDTLS_AES_ENCRYPT_ALT)\nint mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx,\n                                  const unsigned char input[16],\n                                  unsigned char output[16] )\n{\n    int i;\n    uint32_t *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3;\n\n    RK = ctx->rk;\n\n    GET_UINT32_LE( X0, input,  0 ); X0 ^= *RK++;\n    GET_UINT32_LE( X1, input,  4 ); X1 ^= *RK++;\n    GET_UINT32_LE( X2, input,  8 ); X2 ^= *RK++;\n    GET_UINT32_LE( X3, input, 12 ); X3 ^= *RK++;\n\n    for( i = ( ctx->nr >> 1 ) - 1; i > 0; i-- )\n    {\n        AES_FROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );\n        AES_FROUND( X0, X1, X2, X3, Y0, Y1, Y2, Y3 );\n    }\n\n    AES_FROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );\n\n    X0 = *RK++ ^ \\\n            ( (uint32_t) FSb[ ( Y0       ) & 0xFF ]       ) ^\n            ( (uint32_t) FSb[ ( Y1 >>  8 ) & 0xFF ] <<  8 ) ^\n            ( (uint32_t) FSb[ ( Y2 >> 16 ) & 0xFF ] << 16 ) ^\n            ( (uint32_t) FSb[ ( Y3 >> 24 ) & 0xFF ] << 24 );\n\n    X1 = *RK++ ^ \\\n            ( (uint32_t) FSb[ ( Y1       ) & 0xFF ]       ) ^\n            ( (uint32_t) FSb[ ( Y2 >>  8 ) & 0xFF ] <<  8 ) ^\n            ( (uint32_t) FSb[ ( Y3 >> 16 ) & 0xFF ] << 16 ) ^\n            ( (uint32_t) FSb[ ( Y0 >> 24 ) & 0xFF ] << 24 );\n\n    X2 = *RK++ ^ \\\n            ( (uint32_t) FSb[ ( Y2       ) & 0xFF ]       ) ^\n            ( (uint32_t) FSb[ ( Y3 >>  8 ) & 0xFF ] <<  8 ) ^\n            ( (uint32_t) FSb[ ( Y0 >> 16 ) & 0xFF ] << 16 ) ^\n            ( (uint32_t) FSb[ ( Y1 >> 24 ) & 0xFF ] << 24 );\n\n    X3 = *RK++ ^ \\\n            ( (uint32_t) FSb[ ( Y3       ) & 0xFF ]       ) ^\n            ( (uint32_t) FSb[ ( Y0 >>  8 ) & 0xFF ] <<  8 ) ^\n            ( (uint32_t) FSb[ ( Y1 >> 16 ) & 0xFF ] << 16 ) ^\n            ( (uint32_t) FSb[ ( Y2 >> 24 ) & 0xFF ] << 24 );\n\n    PUT_UINT32_LE( X0, output,  0 );\n    PUT_UINT32_LE( X1, output,  4 );\n    PUT_UINT32_LE( X2, output,  8 );\n    PUT_UINT32_LE( X3, output, 12 );\n\n    return( 0 );\n}\n#endif /* !MBEDTLS_AES_ENCRYPT_ALT */\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_aes_encrypt( mbedtls_aes_context *ctx,\n                          const unsigned char input[16],\n                          unsigned char output[16] )\n{\n    mbedtls_internal_aes_encrypt( ctx, input, output );\n}\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n\n/*\n * AES-ECB block decryption\n */\n#if !defined(MBEDTLS_AES_DECRYPT_ALT)\nint mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx,\n                                  const unsigned char input[16],\n                                  unsigned char output[16] )\n{\n    int i;\n    uint32_t *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3;\n\n    RK = ctx->rk;\n\n    GET_UINT32_LE( X0, input,  0 ); X0 ^= *RK++;\n    GET_UINT32_LE( X1, input,  4 ); X1 ^= *RK++;\n    GET_UINT32_LE( X2, input,  8 ); X2 ^= *RK++;\n    GET_UINT32_LE( X3, input, 12 ); X3 ^= *RK++;\n\n    for( i = ( ctx->nr >> 1 ) - 1; i > 0; i-- )\n    {\n        AES_RROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );\n        AES_RROUND( X0, X1, X2, X3, Y0, Y1, Y2, Y3 );\n    }\n\n    AES_RROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );\n\n    X0 = *RK++ ^ \\\n            ( (uint32_t) RSb[ ( Y0       ) & 0xFF ]       ) ^\n            ( (uint32_t) RSb[ ( Y3 >>  8 ) & 0xFF ] <<  8 ) ^\n            ( (uint32_t) RSb[ ( Y2 >> 16 ) & 0xFF ] << 16 ) ^\n            ( (uint32_t) RSb[ ( Y1 >> 24 ) & 0xFF ] << 24 );\n\n    X1 = *RK++ ^ \\\n            ( (uint32_t) RSb[ ( Y1       ) & 0xFF ]       ) ^\n            ( (uint32_t) RSb[ ( Y0 >>  8 ) & 0xFF ] <<  8 ) ^\n            ( (uint32_t) RSb[ ( Y3 >> 16 ) & 0xFF ] << 16 ) ^\n            ( (uint32_t) RSb[ ( Y2 >> 24 ) & 0xFF ] << 24 );\n\n    X2 = *RK++ ^ \\\n            ( (uint32_t) RSb[ ( Y2       ) & 0xFF ]       ) ^\n            ( (uint32_t) RSb[ ( Y1 >>  8 ) & 0xFF ] <<  8 ) ^\n            ( (uint32_t) RSb[ ( Y0 >> 16 ) & 0xFF ] << 16 ) ^\n            ( (uint32_t) RSb[ ( Y3 >> 24 ) & 0xFF ] << 24 );\n\n    X3 = *RK++ ^ \\\n            ( (uint32_t) RSb[ ( Y3       ) & 0xFF ]       ) ^\n            ( (uint32_t) RSb[ ( Y2 >>  8 ) & 0xFF ] <<  8 ) ^\n            ( (uint32_t) RSb[ ( Y1 >> 16 ) & 0xFF ] << 16 ) ^\n            ( (uint32_t) RSb[ ( Y0 >> 24 ) & 0xFF ] << 24 );\n\n    PUT_UINT32_LE( X0, output,  0 );\n    PUT_UINT32_LE( X1, output,  4 );\n    PUT_UINT32_LE( X2, output,  8 );\n    PUT_UINT32_LE( X3, output, 12 );\n\n    return( 0 );\n}\n#endif /* !MBEDTLS_AES_DECRYPT_ALT */\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_aes_decrypt( mbedtls_aes_context *ctx,\n                          const unsigned char input[16],\n                          unsigned char output[16] )\n{\n    mbedtls_internal_aes_decrypt( ctx, input, output );\n}\n#endif /* !MBEDTLS_DEPRECATED_REMOVED */\n\n/*\n * AES-ECB block encryption/decryption\n */\nint mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx,\n                    int mode,\n                    const unsigned char input[16],\n                    unsigned char output[16] )\n{\n#if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64)\n    if( mbedtls_aesni_has_support( MBEDTLS_AESNI_AES ) )\n        return( mbedtls_aesni_crypt_ecb( ctx, mode, input, output ) );\n#endif\n\n#if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_HAVE_X86)\n    if( aes_padlock_ace )\n    {\n        if( mbedtls_padlock_xcryptecb( ctx, mode, input, output ) == 0 )\n            return( 0 );\n\n        // If padlock data misaligned, we just fall back to\n        // unaccelerated mode\n        //\n    }\n#endif\n\n    if( mode == MBEDTLS_AES_ENCRYPT )\n        return( mbedtls_internal_aes_encrypt( ctx, input, output ) );\n    else\n        return( mbedtls_internal_aes_decrypt( ctx, input, output ) );\n}\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n/*\n * AES-CBC buffer encryption/decryption\n */\nint mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx,\n                    int mode,\n                    size_t length,\n                    unsigned char iv[16],\n                    const unsigned char *input,\n                    unsigned char *output )\n{\n    int i;\n    unsigned char temp[16];\n\n    if( length % 16 )\n        return( MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH );\n\n#if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_HAVE_X86)\n    if( aes_padlock_ace )\n    {\n        if( mbedtls_padlock_xcryptcbc( ctx, mode, length, iv, input, output ) == 0 )\n            return( 0 );\n\n        // If padlock data misaligned, we just fall back to\n        // unaccelerated mode\n        //\n    }\n#endif\n\n    if( mode == MBEDTLS_AES_DECRYPT )\n    {\n        while( length > 0 )\n        {\n            memcpy( temp, input, 16 );\n            mbedtls_aes_crypt_ecb( ctx, mode, input, output );\n\n            for( i = 0; i < 16; i++ )\n                output[i] = (unsigned char)( output[i] ^ iv[i] );\n\n            memcpy( iv, temp, 16 );\n\n            input  += 16;\n            output += 16;\n            length -= 16;\n        }\n    }\n    else\n    {\n        while( length > 0 )\n        {\n            for( i = 0; i < 16; i++ )\n                output[i] = (unsigned char)( input[i] ^ iv[i] );\n\n            mbedtls_aes_crypt_ecb( ctx, mode, output, output );\n            memcpy( iv, output, 16 );\n\n            input  += 16;\n            output += 16;\n            length -= 16;\n        }\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n\n/* Endianess with 64 bits values */\n#ifndef GET_UINT64_LE\n#define GET_UINT64_LE(n,b,i)                            \\\n{                                                       \\\n    (n) = ( (uint64_t) (b)[(i) + 7] << 56 )             \\\n        | ( (uint64_t) (b)[(i) + 6] << 48 )             \\\n        | ( (uint64_t) (b)[(i) + 5] << 40 )             \\\n        | ( (uint64_t) (b)[(i) + 4] << 32 )             \\\n        | ( (uint64_t) (b)[(i) + 3] << 24 )             \\\n        | ( (uint64_t) (b)[(i) + 2] << 16 )             \\\n        | ( (uint64_t) (b)[(i) + 1] <<  8 )             \\\n        | ( (uint64_t) (b)[(i)    ]       );            \\\n}\n#endif\n\n#ifndef PUT_UINT64_LE\n#define PUT_UINT64_LE(n,b,i)                            \\\n{                                                       \\\n    (b)[(i) + 7] = (unsigned char) ( (n) >> 56 );       \\\n    (b)[(i) + 6] = (unsigned char) ( (n) >> 48 );       \\\n    (b)[(i) + 5] = (unsigned char) ( (n) >> 40 );       \\\n    (b)[(i) + 4] = (unsigned char) ( (n) >> 32 );       \\\n    (b)[(i) + 3] = (unsigned char) ( (n) >> 24 );       \\\n    (b)[(i) + 2] = (unsigned char) ( (n) >> 16 );       \\\n    (b)[(i) + 1] = (unsigned char) ( (n) >>  8 );       \\\n    (b)[(i)    ] = (unsigned char) ( (n)       );       \\\n}\n#endif\n\ntypedef unsigned char mbedtls_be128[16];\n\n/*\n * GF(2^128) multiplication function\n *\n * This function multiplies a field element by x in the polynomial field\n * representation. It uses 64-bit word operations to gain speed but compensates\n * for machine endianess and hence works correctly on both big and little\n * endian machines.\n */\nstatic void mbedtls_gf128mul_x_ble( unsigned char r[16],\n                                    const unsigned char x[16] )\n{\n    uint64_t a, b, ra, rb;\n\n    GET_UINT64_LE( a, x, 0 );\n    GET_UINT64_LE( b, x, 8 );\n\n    ra = ( a << 1 )  ^ 0x0087 >> ( 8 - ( ( b >> 63 ) << 3 ) );\n    rb = ( a >> 63 ) | ( b << 1 );\n\n    PUT_UINT64_LE( ra, r, 0 );\n    PUT_UINT64_LE( rb, r, 8 );\n}\n\n/*\n * AES-XTS buffer encryption/decryption\n */\nint mbedtls_aes_crypt_xts( mbedtls_aes_xts_context *ctx,\n                           int mode,\n                           size_t length,\n                           const unsigned char data_unit[16],\n                           const unsigned char *input,\n                           unsigned char *output )\n{\n    int ret;\n    size_t blocks = length / 16;\n    size_t leftover = length % 16;\n    unsigned char tweak[16];\n    unsigned char prev_tweak[16];\n    unsigned char tmp[16];\n\n    /* Sectors must be at least 16 bytes. */\n    if( length < 16 )\n        return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH;\n\n    /* NIST SP 80-38E disallows data units larger than 2**20 blocks. */\n    if( length > ( 1 << 20 ) * 16 )\n        return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH;\n\n    /* Compute the tweak. */\n    ret = mbedtls_aes_crypt_ecb( &ctx->tweak, MBEDTLS_AES_ENCRYPT,\n                                 data_unit, tweak );\n    if( ret != 0 )\n        return( ret );\n\n    while( blocks-- )\n    {\n        size_t i;\n\n        if( leftover && ( mode == MBEDTLS_AES_DECRYPT ) && blocks == 0 )\n        {\n            /* We are on the last block in a decrypt operation that has\n             * leftover bytes, so we need to use the next tweak for this block,\n             * and this tweak for the lefover bytes. Save the current tweak for\n             * the leftovers and then update the current tweak for use on this,\n             * the last full block. */\n            memcpy( prev_tweak, tweak, sizeof( tweak ) );\n            mbedtls_gf128mul_x_ble( tweak, tweak );\n        }\n\n        for( i = 0; i < 16; i++ )\n            tmp[i] = input[i] ^ tweak[i];\n\n        ret = mbedtls_aes_crypt_ecb( &ctx->crypt, mode, tmp, tmp );\n        if( ret != 0 )\n            return( ret );\n\n        for( i = 0; i < 16; i++ )\n            output[i] = tmp[i] ^ tweak[i];\n\n        /* Update the tweak for the next block. */\n        mbedtls_gf128mul_x_ble( tweak, tweak );\n\n        output += 16;\n        input += 16;\n    }\n\n    if( leftover )\n    {\n        /* If we are on the leftover bytes in a decrypt operation, we need to\n         * use the previous tweak for these bytes (as saved in prev_tweak). */\n        unsigned char *t = mode == MBEDTLS_AES_DECRYPT ? prev_tweak : tweak;\n\n        /* We are now on the final part of the data unit, which doesn't divide\n         * evenly by 16. It's time for ciphertext stealing. */\n        size_t i;\n        unsigned char *prev_output = output - 16;\n\n        /* Copy ciphertext bytes from the previous block to our output for each\n         * byte of cyphertext we won't steal. At the same time, copy the\n         * remainder of the input for this final round (since the loop bounds\n         * are the same). */\n        for( i = 0; i < leftover; i++ )\n        {\n            output[i] = prev_output[i];\n            tmp[i] = input[i] ^ t[i];\n        }\n\n        /* Copy ciphertext bytes from the previous block for input in this\n         * round. */\n        for( ; i < 16; i++ )\n            tmp[i] = prev_output[i] ^ t[i];\n\n        ret = mbedtls_aes_crypt_ecb( &ctx->crypt, mode, tmp, tmp );\n        if( ret != 0 )\n            return ret;\n\n        /* Write the result back to the previous block, overriding the previous\n         * output we copied. */\n        for( i = 0; i < 16; i++ )\n            prev_output[i] = tmp[i] ^ t[i];\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_XTS */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n/*\n * AES-CFB128 buffer encryption/decryption\n */\nint mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx,\n                       int mode,\n                       size_t length,\n                       size_t *iv_off,\n                       unsigned char iv[16],\n                       const unsigned char *input,\n                       unsigned char *output )\n{\n    int c;\n    size_t n = *iv_off;\n\n    if( mode == MBEDTLS_AES_DECRYPT )\n    {\n        while( length-- )\n        {\n            if( n == 0 )\n                mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, iv, iv );\n\n            c = *input++;\n            *output++ = (unsigned char)( c ^ iv[n] );\n            iv[n] = (unsigned char) c;\n\n            n = ( n + 1 ) & 0x0F;\n        }\n    }\n    else\n    {\n        while( length-- )\n        {\n            if( n == 0 )\n                mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, iv, iv );\n\n            iv[n] = *output++ = (unsigned char)( iv[n] ^ *input++ );\n\n            n = ( n + 1 ) & 0x0F;\n        }\n    }\n\n    *iv_off = n;\n\n    return( 0 );\n}\n\n/*\n * AES-CFB8 buffer encryption/decryption\n */\nint mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx,\n                       int mode,\n                       size_t length,\n                       unsigned char iv[16],\n                       const unsigned char *input,\n                       unsigned char *output )\n{\n    unsigned char c;\n    unsigned char ov[17];\n\n    while( length-- )\n    {\n        memcpy( ov, iv, 16 );\n        mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, iv, iv );\n\n        if( mode == MBEDTLS_AES_DECRYPT )\n            ov[16] = *input;\n\n        c = *output++ = (unsigned char)( iv[0] ^ *input++ );\n\n        if( mode == MBEDTLS_AES_ENCRYPT )\n            ov[16] = c;\n\n        memcpy( iv, ov + 1, 16 );\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n/*\n * AES-OFB (Output Feedback Mode) buffer encryption/decryption\n */\nint mbedtls_aes_crypt_ofb( mbedtls_aes_context *ctx,\n                           size_t length,\n                           size_t *iv_off,\n                           unsigned char iv[16],\n                           const unsigned char *input,\n                           unsigned char *output )\n{\n    int ret = 0;\n    size_t n = *iv_off;\n\n    while( length-- )\n    {\n        if( n == 0 )\n        {\n            ret = mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, iv, iv );\n            if( ret != 0 )\n                goto exit;\n        }\n        *output++ =  *input++ ^ iv[n];\n\n        n = ( n + 1 ) & 0x0F;\n    }\n\n    *iv_off = n;\n\nexit:\n    return( ret );\n}\n#endif /* MBEDTLS_CIPHER_MODE_OFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n/*\n * AES-CTR buffer encryption/decryption\n */\nint mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx,\n                       size_t length,\n                       size_t *nc_off,\n                       unsigned char nonce_counter[16],\n                       unsigned char stream_block[16],\n                       const unsigned char *input,\n                       unsigned char *output )\n{\n    int c, i;\n    size_t n = *nc_off;\n\n    if ( n > 0x0F )\n        return( MBEDTLS_ERR_AES_BAD_INPUT_DATA );\n\n    while( length-- )\n    {\n        if( n == 0 ) {\n            mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, nonce_counter, stream_block );\n\n            for( i = 16; i > 0; i-- )\n                if( ++nonce_counter[i - 1] != 0 )\n                    break;\n        }\n        c = *input++;\n        *output++ = (unsigned char)( c ^ stream_block[n] );\n\n        n = ( n + 1 ) & 0x0F;\n    }\n\n    *nc_off = n;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\n#endif /* !MBEDTLS_AES_ALT */\n\n#if defined(MBEDTLS_SELF_TEST)\n/*\n * AES test vectors from:\n *\n * http://csrc.nist.gov/archive/aes/rijndael/rijndael-vals.zip\n */\nstatic const unsigned char aes_test_ecb_dec[3][16] =\n{\n    { 0x44, 0x41, 0x6A, 0xC2, 0xD1, 0xF5, 0x3C, 0x58,\n      0x33, 0x03, 0x91, 0x7E, 0x6B, 0xE9, 0xEB, 0xE0 },\n    { 0x48, 0xE3, 0x1E, 0x9E, 0x25, 0x67, 0x18, 0xF2,\n      0x92, 0x29, 0x31, 0x9C, 0x19, 0xF1, 0x5B, 0xA4 },\n    { 0x05, 0x8C, 0xCF, 0xFD, 0xBB, 0xCB, 0x38, 0x2D,\n      0x1F, 0x6F, 0x56, 0x58, 0x5D, 0x8A, 0x4A, 0xDE }\n};\n\nstatic const unsigned char aes_test_ecb_enc[3][16] =\n{\n    { 0xC3, 0x4C, 0x05, 0x2C, 0xC0, 0xDA, 0x8D, 0x73,\n      0x45, 0x1A, 0xFE, 0x5F, 0x03, 0xBE, 0x29, 0x7F },\n    { 0xF3, 0xF6, 0x75, 0x2A, 0xE8, 0xD7, 0x83, 0x11,\n      0x38, 0xF0, 0x41, 0x56, 0x06, 0x31, 0xB1, 0x14 },\n    { 0x8B, 0x79, 0xEE, 0xCC, 0x93, 0xA0, 0xEE, 0x5D,\n      0xFF, 0x30, 0xB4, 0xEA, 0x21, 0x63, 0x6D, 0xA4 }\n};\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\nstatic const unsigned char aes_test_cbc_dec[3][16] =\n{\n    { 0xFA, 0xCA, 0x37, 0xE0, 0xB0, 0xC8, 0x53, 0x73,\n      0xDF, 0x70, 0x6E, 0x73, 0xF7, 0xC9, 0xAF, 0x86 },\n    { 0x5D, 0xF6, 0x78, 0xDD, 0x17, 0xBA, 0x4E, 0x75,\n      0xB6, 0x17, 0x68, 0xC6, 0xAD, 0xEF, 0x7C, 0x7B },\n    { 0x48, 0x04, 0xE1, 0x81, 0x8F, 0xE6, 0x29, 0x75,\n      0x19, 0xA3, 0xE8, 0x8C, 0x57, 0x31, 0x04, 0x13 }\n};\n\nstatic const unsigned char aes_test_cbc_enc[3][16] =\n{\n    { 0x8A, 0x05, 0xFC, 0x5E, 0x09, 0x5A, 0xF4, 0x84,\n      0x8A, 0x08, 0xD3, 0x28, 0xD3, 0x68, 0x8E, 0x3D },\n    { 0x7B, 0xD9, 0x66, 0xD5, 0x3A, 0xD8, 0xC1, 0xBB,\n      0x85, 0xD2, 0xAD, 0xFA, 0xE8, 0x7B, 0xB1, 0x04 },\n    { 0xFE, 0x3C, 0x53, 0x65, 0x3E, 0x2F, 0x45, 0xB5,\n      0x6F, 0xCD, 0x88, 0xB2, 0xCC, 0x89, 0x8F, 0xF0 }\n};\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n/*\n * AES-CFB128 test vectors from:\n *\n * http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf\n */\nstatic const unsigned char aes_test_cfb128_key[3][32] =\n{\n    { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6,\n      0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C },\n    { 0x8E, 0x73, 0xB0, 0xF7, 0xDA, 0x0E, 0x64, 0x52,\n      0xC8, 0x10, 0xF3, 0x2B, 0x80, 0x90, 0x79, 0xE5,\n      0x62, 0xF8, 0xEA, 0xD2, 0x52, 0x2C, 0x6B, 0x7B },\n    { 0x60, 0x3D, 0xEB, 0x10, 0x15, 0xCA, 0x71, 0xBE,\n      0x2B, 0x73, 0xAE, 0xF0, 0x85, 0x7D, 0x77, 0x81,\n      0x1F, 0x35, 0x2C, 0x07, 0x3B, 0x61, 0x08, 0xD7,\n      0x2D, 0x98, 0x10, 0xA3, 0x09, 0x14, 0xDF, 0xF4 }\n};\n\nstatic const unsigned char aes_test_cfb128_iv[16] =\n{\n    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n    0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F\n};\n\nstatic const unsigned char aes_test_cfb128_pt[64] =\n{\n    0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96,\n    0xE9, 0x3D, 0x7E, 0x11, 0x73, 0x93, 0x17, 0x2A,\n    0xAE, 0x2D, 0x8A, 0x57, 0x1E, 0x03, 0xAC, 0x9C,\n    0x9E, 0xB7, 0x6F, 0xAC, 0x45, 0xAF, 0x8E, 0x51,\n    0x30, 0xC8, 0x1C, 0x46, 0xA3, 0x5C, 0xE4, 0x11,\n    0xE5, 0xFB, 0xC1, 0x19, 0x1A, 0x0A, 0x52, 0xEF,\n    0xF6, 0x9F, 0x24, 0x45, 0xDF, 0x4F, 0x9B, 0x17,\n    0xAD, 0x2B, 0x41, 0x7B, 0xE6, 0x6C, 0x37, 0x10\n};\n\nstatic const unsigned char aes_test_cfb128_ct[3][64] =\n{\n    { 0x3B, 0x3F, 0xD9, 0x2E, 0xB7, 0x2D, 0xAD, 0x20,\n      0x33, 0x34, 0x49, 0xF8, 0xE8, 0x3C, 0xFB, 0x4A,\n      0xC8, 0xA6, 0x45, 0x37, 0xA0, 0xB3, 0xA9, 0x3F,\n      0xCD, 0xE3, 0xCD, 0xAD, 0x9F, 0x1C, 0xE5, 0x8B,\n      0x26, 0x75, 0x1F, 0x67, 0xA3, 0xCB, 0xB1, 0x40,\n      0xB1, 0x80, 0x8C, 0xF1, 0x87, 0xA4, 0xF4, 0xDF,\n      0xC0, 0x4B, 0x05, 0x35, 0x7C, 0x5D, 0x1C, 0x0E,\n      0xEA, 0xC4, 0xC6, 0x6F, 0x9F, 0xF7, 0xF2, 0xE6 },\n    { 0xCD, 0xC8, 0x0D, 0x6F, 0xDD, 0xF1, 0x8C, 0xAB,\n      0x34, 0xC2, 0x59, 0x09, 0xC9, 0x9A, 0x41, 0x74,\n      0x67, 0xCE, 0x7F, 0x7F, 0x81, 0x17, 0x36, 0x21,\n      0x96, 0x1A, 0x2B, 0x70, 0x17, 0x1D, 0x3D, 0x7A,\n      0x2E, 0x1E, 0x8A, 0x1D, 0xD5, 0x9B, 0x88, 0xB1,\n      0xC8, 0xE6, 0x0F, 0xED, 0x1E, 0xFA, 0xC4, 0xC9,\n      0xC0, 0x5F, 0x9F, 0x9C, 0xA9, 0x83, 0x4F, 0xA0,\n      0x42, 0xAE, 0x8F, 0xBA, 0x58, 0x4B, 0x09, 0xFF },\n    { 0xDC, 0x7E, 0x84, 0xBF, 0xDA, 0x79, 0x16, 0x4B,\n      0x7E, 0xCD, 0x84, 0x86, 0x98, 0x5D, 0x38, 0x60,\n      0x39, 0xFF, 0xED, 0x14, 0x3B, 0x28, 0xB1, 0xC8,\n      0x32, 0x11, 0x3C, 0x63, 0x31, 0xE5, 0x40, 0x7B,\n      0xDF, 0x10, 0x13, 0x24, 0x15, 0xE5, 0x4B, 0x92,\n      0xA1, 0x3E, 0xD0, 0xA8, 0x26, 0x7A, 0xE2, 0xF9,\n      0x75, 0xA3, 0x85, 0x74, 0x1A, 0xB9, 0xCE, 0xF8,\n      0x20, 0x31, 0x62, 0x3D, 0x55, 0xB1, 0xE4, 0x71 }\n};\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n/*\n * AES-OFB test vectors from:\n *\n * https://csrc.nist.gov/publications/detail/sp/800-38a/final\n */\nstatic const unsigned char aes_test_ofb_key[3][32] =\n{\n    { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6,\n      0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C },\n    { 0x8E, 0x73, 0xB0, 0xF7, 0xDA, 0x0E, 0x64, 0x52,\n      0xC8, 0x10, 0xF3, 0x2B, 0x80, 0x90, 0x79, 0xE5,\n      0x62, 0xF8, 0xEA, 0xD2, 0x52, 0x2C, 0x6B, 0x7B },\n    { 0x60, 0x3D, 0xEB, 0x10, 0x15, 0xCA, 0x71, 0xBE,\n      0x2B, 0x73, 0xAE, 0xF0, 0x85, 0x7D, 0x77, 0x81,\n      0x1F, 0x35, 0x2C, 0x07, 0x3B, 0x61, 0x08, 0xD7,\n      0x2D, 0x98, 0x10, 0xA3, 0x09, 0x14, 0xDF, 0xF4 }\n};\n\nstatic const unsigned char aes_test_ofb_iv[16] =\n{\n    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n    0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F\n};\n\nstatic const unsigned char aes_test_ofb_pt[64] =\n{\n    0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96,\n    0xE9, 0x3D, 0x7E, 0x11, 0x73, 0x93, 0x17, 0x2A,\n    0xAE, 0x2D, 0x8A, 0x57, 0x1E, 0x03, 0xAC, 0x9C,\n    0x9E, 0xB7, 0x6F, 0xAC, 0x45, 0xAF, 0x8E, 0x51,\n    0x30, 0xC8, 0x1C, 0x46, 0xA3, 0x5C, 0xE4, 0x11,\n    0xE5, 0xFB, 0xC1, 0x19, 0x1A, 0x0A, 0x52, 0xEF,\n    0xF6, 0x9F, 0x24, 0x45, 0xDF, 0x4F, 0x9B, 0x17,\n    0xAD, 0x2B, 0x41, 0x7B, 0xE6, 0x6C, 0x37, 0x10\n};\n\nstatic const unsigned char aes_test_ofb_ct[3][64] =\n{\n    { 0x3B, 0x3F, 0xD9, 0x2E, 0xB7, 0x2D, 0xAD, 0x20,\n      0x33, 0x34, 0x49, 0xF8, 0xE8, 0x3C, 0xFB, 0x4A,\n      0x77, 0x89, 0x50, 0x8d, 0x16, 0x91, 0x8f, 0x03,\n      0xf5, 0x3c, 0x52, 0xda, 0xc5, 0x4e, 0xd8, 0x25,\n      0x97, 0x40, 0x05, 0x1e, 0x9c, 0x5f, 0xec, 0xf6,\n      0x43, 0x44, 0xf7, 0xa8, 0x22, 0x60, 0xed, 0xcc,\n      0x30, 0x4c, 0x65, 0x28, 0xf6, 0x59, 0xc7, 0x78,\n      0x66, 0xa5, 0x10, 0xd9, 0xc1, 0xd6, 0xae, 0x5e },\n    { 0xCD, 0xC8, 0x0D, 0x6F, 0xDD, 0xF1, 0x8C, 0xAB,\n      0x34, 0xC2, 0x59, 0x09, 0xC9, 0x9A, 0x41, 0x74,\n      0xfc, 0xc2, 0x8b, 0x8d, 0x4c, 0x63, 0x83, 0x7c,\n      0x09, 0xe8, 0x17, 0x00, 0xc1, 0x10, 0x04, 0x01,\n      0x8d, 0x9a, 0x9a, 0xea, 0xc0, 0xf6, 0x59, 0x6f,\n      0x55, 0x9c, 0x6d, 0x4d, 0xaf, 0x59, 0xa5, 0xf2,\n      0x6d, 0x9f, 0x20, 0x08, 0x57, 0xca, 0x6c, 0x3e,\n      0x9c, 0xac, 0x52, 0x4b, 0xd9, 0xac, 0xc9, 0x2a },\n    { 0xDC, 0x7E, 0x84, 0xBF, 0xDA, 0x79, 0x16, 0x4B,\n      0x7E, 0xCD, 0x84, 0x86, 0x98, 0x5D, 0x38, 0x60,\n      0x4f, 0xeb, 0xdc, 0x67, 0x40, 0xd2, 0x0b, 0x3a,\n      0xc8, 0x8f, 0x6a, 0xd8, 0x2a, 0x4f, 0xb0, 0x8d,\n      0x71, 0xab, 0x47, 0xa0, 0x86, 0xe8, 0x6e, 0xed,\n      0xf3, 0x9d, 0x1c, 0x5b, 0xba, 0x97, 0xc4, 0x08,\n      0x01, 0x26, 0x14, 0x1d, 0x67, 0xf3, 0x7b, 0xe8,\n      0x53, 0x8f, 0x5a, 0x8b, 0xe7, 0x40, 0xe4, 0x84 }\n};\n#endif /* MBEDTLS_CIPHER_MODE_OFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n/*\n * AES-CTR test vectors from:\n *\n * http://www.faqs.org/rfcs/rfc3686.html\n */\n\nstatic const unsigned char aes_test_ctr_key[3][16] =\n{\n    { 0xAE, 0x68, 0x52, 0xF8, 0x12, 0x10, 0x67, 0xCC,\n      0x4B, 0xF7, 0xA5, 0x76, 0x55, 0x77, 0xF3, 0x9E },\n    { 0x7E, 0x24, 0x06, 0x78, 0x17, 0xFA, 0xE0, 0xD7,\n      0x43, 0xD6, 0xCE, 0x1F, 0x32, 0x53, 0x91, 0x63 },\n    { 0x76, 0x91, 0xBE, 0x03, 0x5E, 0x50, 0x20, 0xA8,\n      0xAC, 0x6E, 0x61, 0x85, 0x29, 0xF9, 0xA0, 0xDC }\n};\n\nstatic const unsigned char aes_test_ctr_nonce_counter[3][16] =\n{\n    { 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 },\n    { 0x00, 0x6C, 0xB6, 0xDB, 0xC0, 0x54, 0x3B, 0x59,\n      0xDA, 0x48, 0xD9, 0x0B, 0x00, 0x00, 0x00, 0x01 },\n    { 0x00, 0xE0, 0x01, 0x7B, 0x27, 0x77, 0x7F, 0x3F,\n      0x4A, 0x17, 0x86, 0xF0, 0x00, 0x00, 0x00, 0x01 }\n};\n\nstatic const unsigned char aes_test_ctr_pt[3][48] =\n{\n    { 0x53, 0x69, 0x6E, 0x67, 0x6C, 0x65, 0x20, 0x62,\n      0x6C, 0x6F, 0x63, 0x6B, 0x20, 0x6D, 0x73, 0x67 },\n\n    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n      0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,\n      0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,\n      0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F },\n\n    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n      0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,\n      0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,\n      0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,\n      0x20, 0x21, 0x22, 0x23 }\n};\n\nstatic const unsigned char aes_test_ctr_ct[3][48] =\n{\n    { 0xE4, 0x09, 0x5D, 0x4F, 0xB7, 0xA7, 0xB3, 0x79,\n      0x2D, 0x61, 0x75, 0xA3, 0x26, 0x13, 0x11, 0xB8 },\n    { 0x51, 0x04, 0xA1, 0x06, 0x16, 0x8A, 0x72, 0xD9,\n      0x79, 0x0D, 0x41, 0xEE, 0x8E, 0xDA, 0xD3, 0x88,\n      0xEB, 0x2E, 0x1E, 0xFC, 0x46, 0xDA, 0x57, 0xC8,\n      0xFC, 0xE6, 0x30, 0xDF, 0x91, 0x41, 0xBE, 0x28 },\n    { 0xC1, 0xCF, 0x48, 0xA8, 0x9F, 0x2F, 0xFD, 0xD9,\n      0xCF, 0x46, 0x52, 0xE9, 0xEF, 0xDB, 0x72, 0xD7,\n      0x45, 0x40, 0xA4, 0x2B, 0xDE, 0x6D, 0x78, 0x36,\n      0xD5, 0x9A, 0x5C, 0xEA, 0xAE, 0xF3, 0x10, 0x53,\n      0x25, 0xB2, 0x07, 0x2F }\n};\n\nstatic const int aes_test_ctr_len[3] =\n    { 16, 32, 36 };\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n/*\n * AES-XTS test vectors from:\n *\n * IEEE P1619/D16 Annex B\n * https://web.archive.org/web/20150629024421/http://grouper.ieee.org/groups/1619/email/pdf00086.pdf\n * (Archived from original at http://grouper.ieee.org/groups/1619/email/pdf00086.pdf)\n */\nstatic const unsigned char aes_test_xts_key[][32] =\n{\n    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },\n    { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,\n      0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,\n      0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,\n      0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22 },\n    { 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8,\n      0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0,\n      0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,\n      0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22 },\n};\n\nstatic const unsigned char aes_test_xts_pt32[][32] =\n{\n    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },\n    { 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,\n      0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,\n      0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,\n      0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44 },\n    { 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,\n      0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,\n      0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,\n      0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44 },\n};\n\nstatic const unsigned char aes_test_xts_ct32[][32] =\n{\n    { 0x91, 0x7c, 0xf6, 0x9e, 0xbd, 0x68, 0xb2, 0xec,\n      0x9b, 0x9f, 0xe9, 0xa3, 0xea, 0xdd, 0xa6, 0x92,\n      0xcd, 0x43, 0xd2, 0xf5, 0x95, 0x98, 0xed, 0x85,\n      0x8c, 0x02, 0xc2, 0x65, 0x2f, 0xbf, 0x92, 0x2e },\n    { 0xc4, 0x54, 0x18, 0x5e, 0x6a, 0x16, 0x93, 0x6e,\n      0x39, 0x33, 0x40, 0x38, 0xac, 0xef, 0x83, 0x8b,\n      0xfb, 0x18, 0x6f, 0xff, 0x74, 0x80, 0xad, 0xc4,\n      0x28, 0x93, 0x82, 0xec, 0xd6, 0xd3, 0x94, 0xf0 },\n    { 0xaf, 0x85, 0x33, 0x6b, 0x59, 0x7a, 0xfc, 0x1a,\n      0x90, 0x0b, 0x2e, 0xb2, 0x1e, 0xc9, 0x49, 0xd2,\n      0x92, 0xdf, 0x4c, 0x04, 0x7e, 0x0b, 0x21, 0x53,\n      0x21, 0x86, 0xa5, 0x97, 0x1a, 0x22, 0x7a, 0x89 },\n};\n\nstatic const unsigned char aes_test_xts_data_unit[][16] =\n{\n   { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },\n   { 0x33, 0x33, 0x33, 0x33, 0x33, 0x00, 0x00, 0x00,\n     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },\n   { 0x33, 0x33, 0x33, 0x33, 0x33, 0x00, 0x00, 0x00,\n     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },\n};\n\n#endif /* MBEDTLS_CIPHER_MODE_XTS */\n\n/*\n * Checkup routine\n */\nint mbedtls_aes_self_test( int verbose )\n{\n    int ret = 0, i, j, u, mode;\n    unsigned int keybits;\n    unsigned char key[32];\n    unsigned char buf[64];\n    const unsigned char *aes_tests;\n#if defined(MBEDTLS_CIPHER_MODE_CBC) || defined(MBEDTLS_CIPHER_MODE_CFB)\n    unsigned char iv[16];\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    unsigned char prv[16];\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR) || defined(MBEDTLS_CIPHER_MODE_CFB) || \\\n    defined(MBEDTLS_CIPHER_MODE_OFB)\n    size_t offset;\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR) || defined(MBEDTLS_CIPHER_MODE_XTS)\n    int len;\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    unsigned char nonce_counter[16];\n    unsigned char stream_block[16];\n#endif\n    mbedtls_aes_context ctx;\n\n    memset( key, 0, 32 );\n    mbedtls_aes_init( &ctx );\n\n    /*\n     * ECB mode\n     */\n    for( i = 0; i < 6; i++ )\n    {\n        u = i >> 1;\n        keybits = 128 + u * 64;\n        mode = i & 1;\n\n        if( verbose != 0 )\n            mbedtls_printf( \"  AES-ECB-%3d (%s): \", keybits,\n                            ( mode == MBEDTLS_AES_DECRYPT ) ? \"dec\" : \"enc\" );\n\n        memset( buf, 0, 16 );\n\n        if( mode == MBEDTLS_AES_DECRYPT )\n        {\n            ret = mbedtls_aes_setkey_dec( &ctx, key, keybits );\n            aes_tests = aes_test_ecb_dec[u];\n        }\n        else\n        {\n            ret = mbedtls_aes_setkey_enc( &ctx, key, keybits );\n            aes_tests = aes_test_ecb_enc[u];\n        }\n\n        /*\n         * AES-192 is an optional feature that may be unavailable when\n         * there is an alternative underlying implementation i.e. when\n         * MBEDTLS_AES_ALT is defined.\n         */\n        if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && keybits == 192 )\n        {\n            mbedtls_printf( \"skipped\\n\" );\n            continue;\n        }\n        else if( ret != 0 )\n        {\n            goto exit;\n        }\n\n        for( j = 0; j < 10000; j++ )\n        {\n            ret = mbedtls_aes_crypt_ecb( &ctx, mode, buf, buf );\n            if( ret != 0 )\n                goto exit;\n        }\n\n        if( memcmp( buf, aes_tests, 16 ) != 0 )\n        {\n            ret = 1;\n            goto exit;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    /*\n     * CBC mode\n     */\n    for( i = 0; i < 6; i++ )\n    {\n        u = i >> 1;\n        keybits = 128 + u * 64;\n        mode = i & 1;\n\n        if( verbose != 0 )\n            mbedtls_printf( \"  AES-CBC-%3d (%s): \", keybits,\n                            ( mode == MBEDTLS_AES_DECRYPT ) ? \"dec\" : \"enc\" );\n\n        memset( iv , 0, 16 );\n        memset( prv, 0, 16 );\n        memset( buf, 0, 16 );\n\n        if( mode == MBEDTLS_AES_DECRYPT )\n        {\n            ret = mbedtls_aes_setkey_dec( &ctx, key, keybits );\n            aes_tests = aes_test_cbc_dec[u];\n        }\n        else\n        {\n            ret = mbedtls_aes_setkey_enc( &ctx, key, keybits );\n            aes_tests = aes_test_cbc_enc[u];\n        }\n\n        /*\n         * AES-192 is an optional feature that may be unavailable when\n         * there is an alternative underlying implementation i.e. when\n         * MBEDTLS_AES_ALT is defined.\n         */\n        if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && keybits == 192 )\n        {\n            mbedtls_printf( \"skipped\\n\" );\n            continue;\n        }\n        else if( ret != 0 )\n        {\n            goto exit;\n        }\n\n        for( j = 0; j < 10000; j++ )\n        {\n            if( mode == MBEDTLS_AES_ENCRYPT )\n            {\n                unsigned char tmp[16];\n\n                memcpy( tmp, prv, 16 );\n                memcpy( prv, buf, 16 );\n                memcpy( buf, tmp, 16 );\n            }\n\n            ret = mbedtls_aes_crypt_cbc( &ctx, mode, 16, iv, buf, buf );\n            if( ret != 0 )\n                goto exit;\n\n        }\n\n        if( memcmp( buf, aes_tests, 16 ) != 0 )\n        {\n            ret = 1;\n            goto exit;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    /*\n     * CFB128 mode\n     */\n    for( i = 0; i < 6; i++ )\n    {\n        u = i >> 1;\n        keybits = 128 + u * 64;\n        mode = i & 1;\n\n        if( verbose != 0 )\n            mbedtls_printf( \"  AES-CFB128-%3d (%s): \", keybits,\n                            ( mode == MBEDTLS_AES_DECRYPT ) ? \"dec\" : \"enc\" );\n\n        memcpy( iv,  aes_test_cfb128_iv, 16 );\n        memcpy( key, aes_test_cfb128_key[u], keybits / 8 );\n\n        offset = 0;\n        ret = mbedtls_aes_setkey_enc( &ctx, key, keybits );\n        /*\n         * AES-192 is an optional feature that may be unavailable when\n         * there is an alternative underlying implementation i.e. when\n         * MBEDTLS_AES_ALT is defined.\n         */\n        if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && keybits == 192 )\n        {\n            mbedtls_printf( \"skipped\\n\" );\n            continue;\n        }\n        else if( ret != 0 )\n        {\n            goto exit;\n        }\n\n        if( mode == MBEDTLS_AES_DECRYPT )\n        {\n            memcpy( buf, aes_test_cfb128_ct[u], 64 );\n            aes_tests = aes_test_cfb128_pt;\n        }\n        else\n        {\n            memcpy( buf, aes_test_cfb128_pt, 64 );\n            aes_tests = aes_test_cfb128_ct[u];\n        }\n\n        ret = mbedtls_aes_crypt_cfb128( &ctx, mode, 64, &offset, iv, buf, buf );\n        if( ret != 0 )\n            goto exit;\n\n        if( memcmp( buf, aes_tests, 64 ) != 0 )\n        {\n            ret = 1;\n            goto exit;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    /*\n     * OFB mode\n     */\n    for( i = 0; i < 6; i++ )\n    {\n        u = i >> 1;\n        keybits = 128 + u * 64;\n        mode = i & 1;\n\n        if( verbose != 0 )\n            mbedtls_printf( \"  AES-OFB-%3d (%s): \", keybits,\n                            ( mode == MBEDTLS_AES_DECRYPT ) ? \"dec\" : \"enc\" );\n\n        memcpy( iv,  aes_test_ofb_iv, 16 );\n        memcpy( key, aes_test_ofb_key[u], keybits / 8 );\n\n        offset = 0;\n        ret = mbedtls_aes_setkey_enc( &ctx, key, keybits );\n        /*\n         * AES-192 is an optional feature that may be unavailable when\n         * there is an alternative underlying implementation i.e. when\n         * MBEDTLS_AES_ALT is defined.\n         */\n        if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && keybits == 192 )\n        {\n            mbedtls_printf( \"skipped\\n\" );\n            continue;\n        }\n        else if( ret != 0 )\n        {\n            goto exit;\n        }\n\n        if( mode == MBEDTLS_AES_DECRYPT )\n        {\n            memcpy( buf, aes_test_ofb_ct[u], 64 );\n            aes_tests = aes_test_ofb_pt;\n        }\n        else\n        {\n            memcpy( buf, aes_test_ofb_pt, 64 );\n            aes_tests = aes_test_ofb_ct[u];\n        }\n\n        ret = mbedtls_aes_crypt_ofb( &ctx, 64, &offset, iv, buf, buf );\n        if( ret != 0 )\n            goto exit;\n\n        if( memcmp( buf, aes_tests, 64 ) != 0 )\n        {\n            ret = 1;\n            goto exit;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n#endif /* MBEDTLS_CIPHER_MODE_OFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    /*\n     * CTR mode\n     */\n    for( i = 0; i < 6; i++ )\n    {\n        u = i >> 1;\n        mode = i & 1;\n\n        if( verbose != 0 )\n            mbedtls_printf( \"  AES-CTR-128 (%s): \",\n                            ( mode == MBEDTLS_AES_DECRYPT ) ? \"dec\" : \"enc\" );\n\n        memcpy( nonce_counter, aes_test_ctr_nonce_counter[u], 16 );\n        memcpy( key, aes_test_ctr_key[u], 16 );\n\n        offset = 0;\n        if( ( ret = mbedtls_aes_setkey_enc( &ctx, key, 128 ) ) != 0 )\n            goto exit;\n\n        len = aes_test_ctr_len[u];\n\n        if( mode == MBEDTLS_AES_DECRYPT )\n        {\n            memcpy( buf, aes_test_ctr_ct[u], len );\n            aes_tests = aes_test_ctr_pt[u];\n        }\n        else\n        {\n            memcpy( buf, aes_test_ctr_pt[u], len );\n            aes_tests = aes_test_ctr_ct[u];\n        }\n\n        ret = mbedtls_aes_crypt_ctr( &ctx, len, &offset, nonce_counter,\n                                     stream_block, buf, buf );\n        if( ret != 0 )\n            goto exit;\n\n        if( memcmp( buf, aes_tests, len ) != 0 )\n        {\n            ret = 1;\n            goto exit;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    {\n    static const int num_tests =\n        sizeof(aes_test_xts_key) / sizeof(*aes_test_xts_key);\n    mbedtls_aes_xts_context ctx_xts;\n\n    /*\n     * XTS mode\n     */\n    mbedtls_aes_xts_init( &ctx_xts );\n\n    for( i = 0; i < num_tests << 1; i++ )\n    {\n        const unsigned char *data_unit;\n        u = i >> 1;\n        mode = i & 1;\n\n        if( verbose != 0 )\n            mbedtls_printf( \"  AES-XTS-128 (%s): \",\n                            ( mode == MBEDTLS_AES_DECRYPT ) ? \"dec\" : \"enc\" );\n\n        memset( key, 0, sizeof( key ) );\n        memcpy( key, aes_test_xts_key[u], 32 );\n        data_unit = aes_test_xts_data_unit[u];\n\n        len = sizeof( *aes_test_xts_ct32 );\n\n        if( mode == MBEDTLS_AES_DECRYPT )\n        {\n            ret = mbedtls_aes_xts_setkey_dec( &ctx_xts, key, 256 );\n            if( ret != 0)\n                goto exit;\n            memcpy( buf, aes_test_xts_ct32[u], len );\n            aes_tests = aes_test_xts_pt32[u];\n        }\n        else\n        {\n            ret = mbedtls_aes_xts_setkey_enc( &ctx_xts, key, 256 );\n            if( ret != 0)\n                goto exit;\n            memcpy( buf, aes_test_xts_pt32[u], len );\n            aes_tests = aes_test_xts_ct32[u];\n        }\n\n\n        ret = mbedtls_aes_crypt_xts( &ctx_xts, mode, len, data_unit,\n                                     buf, buf );\n        if( ret != 0 )\n            goto exit;\n\n        if( memcmp( buf, aes_tests, len ) != 0 )\n        {\n            ret = 1;\n            goto exit;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    mbedtls_aes_xts_free( &ctx_xts );\n    }\n#endif /* MBEDTLS_CIPHER_MODE_XTS */\n\n    ret = 0;\n\nexit:\n    if( ret != 0 && verbose != 0 )\n        mbedtls_printf( \"failed\\n\" );\n\n    mbedtls_aes_free( &ctx );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_AES_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/aesni.c",
    "content": "/*\n *  AES-NI support functions\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n/*\n * [AES-WP] http://software.intel.com/en-us/articles/intel-advanced-encryption-standard-aes-instructions-set\n * [CLMUL-WP] http://software.intel.com/en-us/articles/intel-carry-less-multiplication-instruction-and-its-usage-for-computing-the-gcm-mode/\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_AESNI_C)\n\n#if defined(__has_feature)\n#if __has_feature(memory_sanitizer)\n#warning \"MBEDTLS_AESNI_C is known to cause spurious error reports with some memory sanitizers as they do not understand the assembly code.\"\n#endif\n#endif\n\n#include \"mbedtls/aesni.h\"\n\n#include <string.h>\n\n#ifndef asm\n#define asm __asm\n#endif\n\n#if defined(MBEDTLS_HAVE_X86_64)\n\n/*\n * AES-NI support detection routine\n */\nint mbedtls_aesni_has_support( unsigned int what )\n{\n    static int done = 0;\n    static unsigned int c = 0;\n\n    if( ! done )\n    {\n        asm( \"movl  $1, %%eax   \\n\\t\"\n             \"cpuid             \\n\\t\"\n             : \"=c\" (c)\n             :\n             : \"eax\", \"ebx\", \"edx\" );\n        done = 1;\n    }\n\n    return( ( c & what ) != 0 );\n}\n\n/*\n * Binutils needs to be at least 2.19 to support AES-NI instructions.\n * Unfortunately, a lot of users have a lower version now (2014-04).\n * Emit bytecode directly in order to support \"old\" version of gas.\n *\n * Opcodes from the Intel architecture reference manual, vol. 3.\n * We always use registers, so we don't need prefixes for memory operands.\n * Operand macros are in gas order (src, dst) as opposed to Intel order\n * (dst, src) in order to blend better into the surrounding assembly code.\n */\n#define AESDEC      \".byte 0x66,0x0F,0x38,0xDE,\"\n#define AESDECLAST  \".byte 0x66,0x0F,0x38,0xDF,\"\n#define AESENC      \".byte 0x66,0x0F,0x38,0xDC,\"\n#define AESENCLAST  \".byte 0x66,0x0F,0x38,0xDD,\"\n#define AESIMC      \".byte 0x66,0x0F,0x38,0xDB,\"\n#define AESKEYGENA  \".byte 0x66,0x0F,0x3A,0xDF,\"\n#define PCLMULQDQ   \".byte 0x66,0x0F,0x3A,0x44,\"\n\n#define xmm0_xmm0   \"0xC0\"\n#define xmm0_xmm1   \"0xC8\"\n#define xmm0_xmm2   \"0xD0\"\n#define xmm0_xmm3   \"0xD8\"\n#define xmm0_xmm4   \"0xE0\"\n#define xmm1_xmm0   \"0xC1\"\n#define xmm1_xmm2   \"0xD1\"\n\n/*\n * AES-NI AES-ECB block en(de)cryption\n */\nint mbedtls_aesni_crypt_ecb( mbedtls_aes_context *ctx,\n                     int mode,\n                     const unsigned char input[16],\n                     unsigned char output[16] )\n{\n    asm( \"movdqu    (%3), %%xmm0    \\n\\t\" // load input\n         \"movdqu    (%1), %%xmm1    \\n\\t\" // load round key 0\n         \"pxor      %%xmm1, %%xmm0  \\n\\t\" // round 0\n         \"add       $16, %1         \\n\\t\" // point to next round key\n         \"subl      $1, %0          \\n\\t\" // normal rounds = nr - 1\n         \"test      %2, %2          \\n\\t\" // mode?\n         \"jz        2f              \\n\\t\" // 0 = decrypt\n\n         \"1:                        \\n\\t\" // encryption loop\n         \"movdqu    (%1), %%xmm1    \\n\\t\" // load round key\n         AESENC     xmm1_xmm0      \"\\n\\t\" // do round\n         \"add       $16, %1         \\n\\t\" // point to next round key\n         \"subl      $1, %0          \\n\\t\" // loop\n         \"jnz       1b              \\n\\t\"\n         \"movdqu    (%1), %%xmm1    \\n\\t\" // load round key\n         AESENCLAST xmm1_xmm0      \"\\n\\t\" // last round\n         \"jmp       3f              \\n\\t\"\n\n         \"2:                        \\n\\t\" // decryption loop\n         \"movdqu    (%1), %%xmm1    \\n\\t\"\n         AESDEC     xmm1_xmm0      \"\\n\\t\" // do round\n         \"add       $16, %1         \\n\\t\"\n         \"subl      $1, %0          \\n\\t\"\n         \"jnz       2b              \\n\\t\"\n         \"movdqu    (%1), %%xmm1    \\n\\t\" // load round key\n         AESDECLAST xmm1_xmm0      \"\\n\\t\" // last round\n\n         \"3:                        \\n\\t\"\n         \"movdqu    %%xmm0, (%4)    \\n\\t\" // export output\n         :\n         : \"r\" (ctx->nr), \"r\" (ctx->rk), \"r\" (mode), \"r\" (input), \"r\" (output)\n         : \"memory\", \"cc\", \"xmm0\", \"xmm1\" );\n\n\n    return( 0 );\n}\n\n/*\n * GCM multiplication: c = a times b in GF(2^128)\n * Based on [CLMUL-WP] algorithms 1 (with equation 27) and 5.\n */\nvoid mbedtls_aesni_gcm_mult( unsigned char c[16],\n                     const unsigned char a[16],\n                     const unsigned char b[16] )\n{\n    unsigned char aa[16], bb[16], cc[16];\n    size_t i;\n\n    /* The inputs are in big-endian order, so byte-reverse them */\n    for( i = 0; i < 16; i++ )\n    {\n        aa[i] = a[15 - i];\n        bb[i] = b[15 - i];\n    }\n\n    asm( \"movdqu (%0), %%xmm0               \\n\\t\" // a1:a0\n         \"movdqu (%1), %%xmm1               \\n\\t\" // b1:b0\n\n         /*\n          * Caryless multiplication xmm2:xmm1 = xmm0 * xmm1\n          * using [CLMUL-WP] algorithm 1 (p. 13).\n          */\n         \"movdqa %%xmm1, %%xmm2             \\n\\t\" // copy of b1:b0\n         \"movdqa %%xmm1, %%xmm3             \\n\\t\" // same\n         \"movdqa %%xmm1, %%xmm4             \\n\\t\" // same\n         PCLMULQDQ xmm0_xmm1 \",0x00         \\n\\t\" // a0*b0 = c1:c0\n         PCLMULQDQ xmm0_xmm2 \",0x11         \\n\\t\" // a1*b1 = d1:d0\n         PCLMULQDQ xmm0_xmm3 \",0x10         \\n\\t\" // a0*b1 = e1:e0\n         PCLMULQDQ xmm0_xmm4 \",0x01         \\n\\t\" // a1*b0 = f1:f0\n         \"pxor %%xmm3, %%xmm4               \\n\\t\" // e1+f1:e0+f0\n         \"movdqa %%xmm4, %%xmm3             \\n\\t\" // same\n         \"psrldq $8, %%xmm4                 \\n\\t\" // 0:e1+f1\n         \"pslldq $8, %%xmm3                 \\n\\t\" // e0+f0:0\n         \"pxor %%xmm4, %%xmm2               \\n\\t\" // d1:d0+e1+f1\n         \"pxor %%xmm3, %%xmm1               \\n\\t\" // c1+e0+f1:c0\n\n         /*\n          * Now shift the result one bit to the left,\n          * taking advantage of [CLMUL-WP] eq 27 (p. 20)\n          */\n         \"movdqa %%xmm1, %%xmm3             \\n\\t\" // r1:r0\n         \"movdqa %%xmm2, %%xmm4             \\n\\t\" // r3:r2\n         \"psllq $1, %%xmm1                  \\n\\t\" // r1<<1:r0<<1\n         \"psllq $1, %%xmm2                  \\n\\t\" // r3<<1:r2<<1\n         \"psrlq $63, %%xmm3                 \\n\\t\" // r1>>63:r0>>63\n         \"psrlq $63, %%xmm4                 \\n\\t\" // r3>>63:r2>>63\n         \"movdqa %%xmm3, %%xmm5             \\n\\t\" // r1>>63:r0>>63\n         \"pslldq $8, %%xmm3                 \\n\\t\" // r0>>63:0\n         \"pslldq $8, %%xmm4                 \\n\\t\" // r2>>63:0\n         \"psrldq $8, %%xmm5                 \\n\\t\" // 0:r1>>63\n         \"por %%xmm3, %%xmm1                \\n\\t\" // r1<<1|r0>>63:r0<<1\n         \"por %%xmm4, %%xmm2                \\n\\t\" // r3<<1|r2>>62:r2<<1\n         \"por %%xmm5, %%xmm2                \\n\\t\" // r3<<1|r2>>62:r2<<1|r1>>63\n\n         /*\n          * Now reduce modulo the GCM polynomial x^128 + x^7 + x^2 + x + 1\n          * using [CLMUL-WP] algorithm 5 (p. 20).\n          * Currently xmm2:xmm1 holds x3:x2:x1:x0 (already shifted).\n          */\n         /* Step 2 (1) */\n         \"movdqa %%xmm1, %%xmm3             \\n\\t\" // x1:x0\n         \"movdqa %%xmm1, %%xmm4             \\n\\t\" // same\n         \"movdqa %%xmm1, %%xmm5             \\n\\t\" // same\n         \"psllq $63, %%xmm3                 \\n\\t\" // x1<<63:x0<<63 = stuff:a\n         \"psllq $62, %%xmm4                 \\n\\t\" // x1<<62:x0<<62 = stuff:b\n         \"psllq $57, %%xmm5                 \\n\\t\" // x1<<57:x0<<57 = stuff:c\n\n         /* Step 2 (2) */\n         \"pxor %%xmm4, %%xmm3               \\n\\t\" // stuff:a+b\n         \"pxor %%xmm5, %%xmm3               \\n\\t\" // stuff:a+b+c\n         \"pslldq $8, %%xmm3                 \\n\\t\" // a+b+c:0\n         \"pxor %%xmm3, %%xmm1               \\n\\t\" // x1+a+b+c:x0 = d:x0\n\n         /* Steps 3 and 4 */\n         \"movdqa %%xmm1,%%xmm0              \\n\\t\" // d:x0\n         \"movdqa %%xmm1,%%xmm4              \\n\\t\" // same\n         \"movdqa %%xmm1,%%xmm5              \\n\\t\" // same\n         \"psrlq $1, %%xmm0                  \\n\\t\" // e1:x0>>1 = e1:e0'\n         \"psrlq $2, %%xmm4                  \\n\\t\" // f1:x0>>2 = f1:f0'\n         \"psrlq $7, %%xmm5                  \\n\\t\" // g1:x0>>7 = g1:g0'\n         \"pxor %%xmm4, %%xmm0               \\n\\t\" // e1+f1:e0'+f0'\n         \"pxor %%xmm5, %%xmm0               \\n\\t\" // e1+f1+g1:e0'+f0'+g0'\n         // e0'+f0'+g0' is almost e0+f0+g0, ex\\tcept for some missing\n         // bits carried from d. Now get those\\t bits back in.\n         \"movdqa %%xmm1,%%xmm3              \\n\\t\" // d:x0\n         \"movdqa %%xmm1,%%xmm4              \\n\\t\" // same\n         \"movdqa %%xmm1,%%xmm5              \\n\\t\" // same\n         \"psllq $63, %%xmm3                 \\n\\t\" // d<<63:stuff\n         \"psllq $62, %%xmm4                 \\n\\t\" // d<<62:stuff\n         \"psllq $57, %%xmm5                 \\n\\t\" // d<<57:stuff\n         \"pxor %%xmm4, %%xmm3               \\n\\t\" // d<<63+d<<62:stuff\n         \"pxor %%xmm5, %%xmm3               \\n\\t\" // missing bits of d:stuff\n         \"psrldq $8, %%xmm3                 \\n\\t\" // 0:missing bits of d\n         \"pxor %%xmm3, %%xmm0               \\n\\t\" // e1+f1+g1:e0+f0+g0\n         \"pxor %%xmm1, %%xmm0               \\n\\t\" // h1:h0\n         \"pxor %%xmm2, %%xmm0               \\n\\t\" // x3+h1:x2+h0\n\n         \"movdqu %%xmm0, (%2)               \\n\\t\" // done\n         :\n         : \"r\" (aa), \"r\" (bb), \"r\" (cc)\n         : \"memory\", \"cc\", \"xmm0\", \"xmm1\", \"xmm2\", \"xmm3\", \"xmm4\", \"xmm5\" );\n\n    /* Now byte-reverse the outputs */\n    for( i = 0; i < 16; i++ )\n        c[i] = cc[15 - i];\n\n    return;\n}\n\n/*\n * Compute decryption round keys from encryption round keys\n */\nvoid mbedtls_aesni_inverse_key( unsigned char *invkey,\n                        const unsigned char *fwdkey, int nr )\n{\n    unsigned char *ik = invkey;\n    const unsigned char *fk = fwdkey + 16 * nr;\n\n    memcpy( ik, fk, 16 );\n\n    for( fk -= 16, ik += 16; fk > fwdkey; fk -= 16, ik += 16 )\n        asm( \"movdqu (%0), %%xmm0       \\n\\t\"\n             AESIMC  xmm0_xmm0         \"\\n\\t\"\n             \"movdqu %%xmm0, (%1)       \\n\\t\"\n             :\n             : \"r\" (fk), \"r\" (ik)\n             : \"memory\", \"xmm0\" );\n\n    memcpy( ik, fk, 16 );\n}\n\n/*\n * Key expansion, 128-bit case\n */\nstatic void aesni_setkey_enc_128( unsigned char *rk,\n                                  const unsigned char *key )\n{\n    asm( \"movdqu (%1), %%xmm0               \\n\\t\" // copy the original key\n         \"movdqu %%xmm0, (%0)               \\n\\t\" // as round key 0\n         \"jmp 2f                            \\n\\t\" // skip auxiliary routine\n\n         /*\n          * Finish generating the next round key.\n          *\n          * On entry xmm0 is r3:r2:r1:r0 and xmm1 is X:stuff:stuff:stuff\n          * with X = rot( sub( r3 ) ) ^ RCON.\n          *\n          * On exit, xmm0 is r7:r6:r5:r4\n          * with r4 = X + r0, r5 = r4 + r1, r6 = r5 + r2, r7 = r6 + r3\n          * and those are written to the round key buffer.\n          */\n         \"1:                                \\n\\t\"\n         \"pshufd $0xff, %%xmm1, %%xmm1      \\n\\t\" // X:X:X:X\n         \"pxor %%xmm0, %%xmm1               \\n\\t\" // X+r3:X+r2:X+r1:r4\n         \"pslldq $4, %%xmm0                 \\n\\t\" // r2:r1:r0:0\n         \"pxor %%xmm0, %%xmm1               \\n\\t\" // X+r3+r2:X+r2+r1:r5:r4\n         \"pslldq $4, %%xmm0                 \\n\\t\" // etc\n         \"pxor %%xmm0, %%xmm1               \\n\\t\"\n         \"pslldq $4, %%xmm0                 \\n\\t\"\n         \"pxor %%xmm1, %%xmm0               \\n\\t\" // update xmm0 for next time!\n         \"add $16, %0                       \\n\\t\" // point to next round key\n         \"movdqu %%xmm0, (%0)               \\n\\t\" // write it\n         \"ret                               \\n\\t\"\n\n         /* Main \"loop\" */\n         \"2:                                \\n\\t\"\n         AESKEYGENA xmm0_xmm1 \",0x01        \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm0_xmm1 \",0x02        \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm0_xmm1 \",0x04        \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm0_xmm1 \",0x08        \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm0_xmm1 \",0x10        \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm0_xmm1 \",0x20        \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm0_xmm1 \",0x40        \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm0_xmm1 \",0x80        \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm0_xmm1 \",0x1B        \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm0_xmm1 \",0x36        \\n\\tcall 1b \\n\\t\"\n         :\n         : \"r\" (rk), \"r\" (key)\n         : \"memory\", \"cc\", \"0\" );\n}\n\n/*\n * Key expansion, 192-bit case\n */\nstatic void aesni_setkey_enc_192( unsigned char *rk,\n                                  const unsigned char *key )\n{\n    asm( \"movdqu (%1), %%xmm0   \\n\\t\" // copy original round key\n         \"movdqu %%xmm0, (%0)   \\n\\t\"\n         \"add $16, %0           \\n\\t\"\n         \"movq 16(%1), %%xmm1   \\n\\t\"\n         \"movq %%xmm1, (%0)     \\n\\t\"\n         \"add $8, %0            \\n\\t\"\n         \"jmp 2f                \\n\\t\" // skip auxiliary routine\n\n         /*\n          * Finish generating the next 6 quarter-keys.\n          *\n          * On entry xmm0 is r3:r2:r1:r0, xmm1 is stuff:stuff:r5:r4\n          * and xmm2 is stuff:stuff:X:stuff with X = rot( sub( r3 ) ) ^ RCON.\n          *\n          * On exit, xmm0 is r9:r8:r7:r6 and xmm1 is stuff:stuff:r11:r10\n          * and those are written to the round key buffer.\n          */\n         \"1:                            \\n\\t\"\n         \"pshufd $0x55, %%xmm2, %%xmm2  \\n\\t\" // X:X:X:X\n         \"pxor %%xmm0, %%xmm2           \\n\\t\" // X+r3:X+r2:X+r1:r4\n         \"pslldq $4, %%xmm0             \\n\\t\" // etc\n         \"pxor %%xmm0, %%xmm2           \\n\\t\"\n         \"pslldq $4, %%xmm0             \\n\\t\"\n         \"pxor %%xmm0, %%xmm2           \\n\\t\"\n         \"pslldq $4, %%xmm0             \\n\\t\"\n         \"pxor %%xmm2, %%xmm0           \\n\\t\" // update xmm0 = r9:r8:r7:r6\n         \"movdqu %%xmm0, (%0)           \\n\\t\"\n         \"add $16, %0                   \\n\\t\"\n         \"pshufd $0xff, %%xmm0, %%xmm2  \\n\\t\" // r9:r9:r9:r9\n         \"pxor %%xmm1, %%xmm2           \\n\\t\" // stuff:stuff:r9+r5:r10\n         \"pslldq $4, %%xmm1             \\n\\t\" // r2:r1:r0:0\n         \"pxor %%xmm2, %%xmm1           \\n\\t\" // xmm1 = stuff:stuff:r11:r10\n         \"movq %%xmm1, (%0)             \\n\\t\"\n         \"add $8, %0                    \\n\\t\"\n         \"ret                           \\n\\t\"\n\n         \"2:                            \\n\\t\"\n         AESKEYGENA xmm1_xmm2 \",0x01    \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm1_xmm2 \",0x02    \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm1_xmm2 \",0x04    \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm1_xmm2 \",0x08    \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm1_xmm2 \",0x10    \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm1_xmm2 \",0x20    \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm1_xmm2 \",0x40    \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm1_xmm2 \",0x80    \\n\\tcall 1b \\n\\t\"\n\n         :\n         : \"r\" (rk), \"r\" (key)\n         : \"memory\", \"cc\", \"0\" );\n}\n\n/*\n * Key expansion, 256-bit case\n */\nstatic void aesni_setkey_enc_256( unsigned char *rk,\n                                  const unsigned char *key )\n{\n    asm( \"movdqu (%1), %%xmm0           \\n\\t\"\n         \"movdqu %%xmm0, (%0)           \\n\\t\"\n         \"add $16, %0                   \\n\\t\"\n         \"movdqu 16(%1), %%xmm1         \\n\\t\"\n         \"movdqu %%xmm1, (%0)           \\n\\t\"\n         \"jmp 2f                        \\n\\t\" // skip auxiliary routine\n\n         /*\n          * Finish generating the next two round keys.\n          *\n          * On entry xmm0 is r3:r2:r1:r0, xmm1 is r7:r6:r5:r4 and\n          * xmm2 is X:stuff:stuff:stuff with X = rot( sub( r7 )) ^ RCON\n          *\n          * On exit, xmm0 is r11:r10:r9:r8 and xmm1 is r15:r14:r13:r12\n          * and those have been written to the output buffer.\n          */\n         \"1:                                \\n\\t\"\n         \"pshufd $0xff, %%xmm2, %%xmm2      \\n\\t\"\n         \"pxor %%xmm0, %%xmm2               \\n\\t\"\n         \"pslldq $4, %%xmm0                 \\n\\t\"\n         \"pxor %%xmm0, %%xmm2               \\n\\t\"\n         \"pslldq $4, %%xmm0                 \\n\\t\"\n         \"pxor %%xmm0, %%xmm2               \\n\\t\"\n         \"pslldq $4, %%xmm0                 \\n\\t\"\n         \"pxor %%xmm2, %%xmm0               \\n\\t\"\n         \"add $16, %0                       \\n\\t\"\n         \"movdqu %%xmm0, (%0)               \\n\\t\"\n\n         /* Set xmm2 to stuff:Y:stuff:stuff with Y = subword( r11 )\n          * and proceed to generate next round key from there */\n         AESKEYGENA xmm0_xmm2 \",0x00        \\n\\t\"\n         \"pshufd $0xaa, %%xmm2, %%xmm2      \\n\\t\"\n         \"pxor %%xmm1, %%xmm2               \\n\\t\"\n         \"pslldq $4, %%xmm1                 \\n\\t\"\n         \"pxor %%xmm1, %%xmm2               \\n\\t\"\n         \"pslldq $4, %%xmm1                 \\n\\t\"\n         \"pxor %%xmm1, %%xmm2               \\n\\t\"\n         \"pslldq $4, %%xmm1                 \\n\\t\"\n         \"pxor %%xmm2, %%xmm1               \\n\\t\"\n         \"add $16, %0                       \\n\\t\"\n         \"movdqu %%xmm1, (%0)               \\n\\t\"\n         \"ret                               \\n\\t\"\n\n         /*\n          * Main \"loop\" - Generating one more key than necessary,\n          * see definition of mbedtls_aes_context.buf\n          */\n         \"2:                                \\n\\t\"\n         AESKEYGENA xmm1_xmm2 \",0x01        \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm1_xmm2 \",0x02        \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm1_xmm2 \",0x04        \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm1_xmm2 \",0x08        \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm1_xmm2 \",0x10        \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm1_xmm2 \",0x20        \\n\\tcall 1b \\n\\t\"\n         AESKEYGENA xmm1_xmm2 \",0x40        \\n\\tcall 1b \\n\\t\"\n         :\n         : \"r\" (rk), \"r\" (key)\n         : \"memory\", \"cc\", \"0\" );\n}\n\n/*\n * Key expansion, wrapper\n */\nint mbedtls_aesni_setkey_enc( unsigned char *rk,\n                      const unsigned char *key,\n                      size_t bits )\n{\n    switch( bits )\n    {\n        case 128: aesni_setkey_enc_128( rk, key ); break;\n        case 192: aesni_setkey_enc_192( rk, key ); break;\n        case 256: aesni_setkey_enc_256( rk, key ); break;\n        default : return( MBEDTLS_ERR_AES_INVALID_KEY_LENGTH );\n    }\n\n    return( 0 );\n}\n\n#endif /* MBEDTLS_HAVE_X86_64 */\n\n#endif /* MBEDTLS_AESNI_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/arc4.c",
    "content": "/*\n *  An implementation of the ARCFOUR algorithm\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The ARCFOUR algorithm was publicly disclosed on 94/09.\n *\n *  http://groups.google.com/group/sci.crypt/msg/10a300c9d21afca0\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_ARC4_C)\n\n#include \"mbedtls/arc4.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if !defined(MBEDTLS_ARC4_ALT)\n\nvoid mbedtls_arc4_init( mbedtls_arc4_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_arc4_context ) );\n}\n\nvoid mbedtls_arc4_free( mbedtls_arc4_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_arc4_context ) );\n}\n\n/*\n * ARC4 key schedule\n */\nvoid mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key,\n                 unsigned int keylen )\n{\n    int i, j, a;\n    unsigned int k;\n    unsigned char *m;\n\n    ctx->x = 0;\n    ctx->y = 0;\n    m = ctx->m;\n\n    for( i = 0; i < 256; i++ )\n        m[i] = (unsigned char) i;\n\n    j = k = 0;\n\n    for( i = 0; i < 256; i++, k++ )\n    {\n        if( k >= keylen ) k = 0;\n\n        a = m[i];\n        j = ( j + a + key[k] ) & 0xFF;\n        m[i] = m[j];\n        m[j] = (unsigned char) a;\n    }\n}\n\n/*\n * ARC4 cipher function\n */\nint mbedtls_arc4_crypt( mbedtls_arc4_context *ctx, size_t length, const unsigned char *input,\n                unsigned char *output )\n{\n    int x, y, a, b;\n    size_t i;\n    unsigned char *m;\n\n    x = ctx->x;\n    y = ctx->y;\n    m = ctx->m;\n\n    for( i = 0; i < length; i++ )\n    {\n        x = ( x + 1 ) & 0xFF; a = m[x];\n        y = ( y + a ) & 0xFF; b = m[y];\n\n        m[x] = (unsigned char) b;\n        m[y] = (unsigned char) a;\n\n        output[i] = (unsigned char)\n            ( input[i] ^ m[(unsigned char)( a + b )] );\n    }\n\n    ctx->x = x;\n    ctx->y = y;\n\n    return( 0 );\n}\n\n#endif /* !MBEDTLS_ARC4_ALT */\n\n#if defined(MBEDTLS_SELF_TEST)\n/*\n * ARC4 tests vectors as posted by Eric Rescorla in sep. 1994:\n *\n * http://groups.google.com/group/comp.security.misc/msg/10a300c9d21afca0\n */\nstatic const unsigned char arc4_test_key[3][8] =\n{\n    { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF },\n    { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF },\n    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }\n};\n\nstatic const unsigned char arc4_test_pt[3][8] =\n{\n    { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF },\n    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },\n    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }\n};\n\nstatic const unsigned char arc4_test_ct[3][8] =\n{\n    { 0x75, 0xB7, 0x87, 0x80, 0x99, 0xE0, 0xC5, 0x96 },\n    { 0x74, 0x94, 0xC2, 0xE7, 0x10, 0x4B, 0x08, 0x79 },\n    { 0xDE, 0x18, 0x89, 0x41, 0xA3, 0x37, 0x5D, 0x3A }\n};\n\n/*\n * Checkup routine\n */\nint mbedtls_arc4_self_test( int verbose )\n{\n    int i, ret = 0;\n    unsigned char ibuf[8];\n    unsigned char obuf[8];\n    mbedtls_arc4_context ctx;\n\n    mbedtls_arc4_init( &ctx );\n\n    for( i = 0; i < 3; i++ )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"  ARC4 test #%d: \", i + 1 );\n\n        memcpy( ibuf, arc4_test_pt[i], 8 );\n\n        mbedtls_arc4_setup( &ctx, arc4_test_key[i], 8 );\n        mbedtls_arc4_crypt( &ctx, 8, ibuf, obuf );\n\n        if( memcmp( obuf, arc4_test_ct[i], 8 ) != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed\\n\" );\n\n            ret = 1;\n            goto exit;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\nexit:\n    mbedtls_arc4_free( &ctx );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_ARC4_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/aria.c",
    "content": "/*\n *  ARIA implementation\n *\n *  Copyright (C) 2006-2017, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n/*\n * This implementation is based on the following standards:\n * [1] http://210.104.33.10/ARIA/doc/ARIA-specification-e.pdf\n * [2] https://tools.ietf.org/html/rfc5794\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_ARIA_C)\n\n#include \"mbedtls/aria.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if !defined(MBEDTLS_ARIA_ALT)\n\n#include \"mbedtls/platform_util.h\"\n\n#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \\\n    !defined(inline) && !defined(__cplusplus)\n#define inline __inline\n#endif\n\n/*\n * 32-bit integer manipulation macros (little endian)\n */\n#ifndef GET_UINT32_LE\n#define GET_UINT32_LE( n, b, i )                \\\n{                                               \\\n    (n) = ( (uint32_t) (b)[(i)    ]       )     \\\n        | ( (uint32_t) (b)[(i) + 1] <<  8 )     \\\n        | ( (uint32_t) (b)[(i) + 2] << 16 )     \\\n        | ( (uint32_t) (b)[(i) + 3] << 24 );    \\\n}\n#endif\n\n#ifndef PUT_UINT32_LE\n#define PUT_UINT32_LE( n, b, i )                                \\\n{                                                               \\\n    (b)[(i)    ] = (unsigned char) ( ( (n)       ) & 0xFF );    \\\n    (b)[(i) + 1] = (unsigned char) ( ( (n) >>  8 ) & 0xFF );    \\\n    (b)[(i) + 2] = (unsigned char) ( ( (n) >> 16 ) & 0xFF );    \\\n    (b)[(i) + 3] = (unsigned char) ( ( (n) >> 24 ) & 0xFF );    \\\n}\n#endif\n\n/*\n * modify byte order: ( A B C D ) -> ( B A D C ), i.e. swap pairs of bytes\n *\n * This is submatrix P1 in [1] Appendix B.1\n *\n * Common compilers fail to translate this to minimal number of instructions,\n * so let's provide asm versions for common platforms with C fallback.\n */\n#if defined(MBEDTLS_HAVE_ASM)\n#if defined(__arm__) /* rev16 available from v6 up */\n/* armcc5 --gnu defines __GNUC__ but doesn't support GNU's extended asm */\n#if defined(__GNUC__) && \\\n    ( !defined(__ARMCC_VERSION) || __ARMCC_VERSION >= 6000000 ) && \\\n    __ARM_ARCH >= 6\nstatic inline uint32_t aria_p1( uint32_t x )\n{\n    uint32_t r;\n    __asm( \"rev16 %0, %1\" : \"=l\" (r) : \"l\" (x) );\n    return( r );\n}\n#define ARIA_P1 aria_p1\n#elif defined(__ARMCC_VERSION) && __ARMCC_VERSION < 6000000 && \\\n    ( __TARGET_ARCH_ARM >= 6 || __TARGET_ARCH_THUMB >= 3 )\nstatic inline uint32_t aria_p1( uint32_t x )\n{\n    uint32_t r;\n    __asm( \"rev16 r, x\" );\n    return( r );\n}\n#define ARIA_P1 aria_p1\n#endif\n#endif /* arm */\n#if defined(__GNUC__) && \\\n    defined(__i386__) || defined(__amd64__) || defined( __x86_64__)\n/* I couldn't find an Intel equivalent of rev16, so two instructions */\n#define ARIA_P1(x) ARIA_P2( ARIA_P3( x ) )\n#endif /* x86 gnuc */\n#endif /* MBEDTLS_HAVE_ASM && GNUC */\n#if !defined(ARIA_P1)\n#define ARIA_P1(x) ((((x) >> 8) & 0x00FF00FF) ^ (((x) & 0x00FF00FF) << 8))\n#endif\n\n/*\n * modify byte order: ( A B C D ) -> ( C D A B ), i.e. rotate by 16 bits\n *\n * This is submatrix P2 in [1] Appendix B.1\n *\n * Common compilers will translate this to a single instruction.\n */\n#define ARIA_P2(x) (((x) >> 16) ^ ((x) << 16))\n\n/*\n * modify byte order: ( A B C D ) -> ( D C B A ), i.e. change endianness\n *\n * This is submatrix P3 in [1] Appendix B.1\n *\n * Some compilers fail to translate this to a single instruction,\n * so let's provide asm versions for common platforms with C fallback.\n */\n#if defined(MBEDTLS_HAVE_ASM)\n#if defined(__arm__) /* rev available from v6 up */\n/* armcc5 --gnu defines __GNUC__ but doesn't support GNU's extended asm */\n#if defined(__GNUC__) && \\\n    ( !defined(__ARMCC_VERSION) || __ARMCC_VERSION >= 6000000 ) && \\\n    __ARM_ARCH >= 6\nstatic inline uint32_t aria_p3( uint32_t x )\n{\n    uint32_t r;\n    __asm( \"rev %0, %1\" : \"=l\" (r) : \"l\" (x) );\n    return( r );\n}\n#define ARIA_P3 aria_p3\n#elif defined(__ARMCC_VERSION) && __ARMCC_VERSION < 6000000 && \\\n    ( __TARGET_ARCH_ARM >= 6 || __TARGET_ARCH_THUMB >= 3 )\nstatic inline uint32_t aria_p3( uint32_t x )\n{\n    uint32_t r;\n    __asm( \"rev r, x\" );\n    return( r );\n}\n#define ARIA_P3 aria_p3\n#endif\n#endif /* arm */\n#if defined(__GNUC__) && \\\n    defined(__i386__) || defined(__amd64__) || defined( __x86_64__)\nstatic inline uint32_t aria_p3( uint32_t x )\n{\n    __asm( \"bswap %0\" : \"=r\" (x) : \"0\" (x) );\n    return( x );\n}\n#define ARIA_P3 aria_p3\n#endif /* x86 gnuc */\n#endif /* MBEDTLS_HAVE_ASM && GNUC */\n#if !defined(ARIA_P3)\n#define ARIA_P3(x) ARIA_P2( ARIA_P1 ( x ) )\n#endif\n\n/*\n * ARIA Affine Transform\n * (a, b, c, d) = state in/out\n *\n * If we denote the first byte of input by 0, ..., the last byte by f,\n * then inputs are: a = 0123, b = 4567, c = 89ab, d = cdef.\n *\n * Reading [1] 2.4 or [2] 2.4.3 in columns and performing simple\n * rearrangements on adjacent pairs, output is:\n *\n * a = 3210 + 4545 + 6767 + 88aa + 99bb + dccd + effe\n *   = 3210 + 4567 + 6745 + 89ab + 98ba + dcfe + efcd\n * b = 0101 + 2323 + 5476 + 8998 + baab + eecc + ffdd\n *   = 0123 + 2301 + 5476 + 89ab + ba98 + efcd + fedc\n * c = 0022 + 1133 + 4554 + 7667 + ab89 + dcdc + fefe\n *   = 0123 + 1032 + 4567 + 7654 + ab89 + dcfe + fedc\n * d = 1001 + 2332 + 6644 + 7755 + 9898 + baba + cdef\n *   = 1032 + 2301 + 6745 + 7654 + 98ba + ba98 + cdef\n *\n * Note: another presentation of the A transform can be found as the first\n * half of App. B.1 in [1] in terms of 4-byte operators P1, P2, P3 and P4.\n * The implementation below uses only P1 and P2 as they are sufficient.\n */\nstatic inline void aria_a( uint32_t *a, uint32_t *b,\n                           uint32_t *c, uint32_t *d )\n{\n    uint32_t ta, tb, tc;\n    ta  =  *b;                      // 4567\n    *b  =  *a;                      // 0123\n    *a  =  ARIA_P2( ta );           // 6745\n    tb  =  ARIA_P2( *d );           // efcd\n    *d  =  ARIA_P1( *c );           // 98ba\n    *c  =  ARIA_P1( tb );           // fedc\n    ta  ^= *d;                      // 4567+98ba\n    tc  =  ARIA_P2( *b );           // 2301\n    ta  =  ARIA_P1( ta ) ^ tc ^ *c; // 2301+5476+89ab+fedc\n    tb  ^= ARIA_P2( *d );           // ba98+efcd\n    tc  ^= ARIA_P1( *a );           // 2301+7654\n    *b  ^= ta ^ tb;                 // 0123+2301+5476+89ab+ba98+efcd+fedc OUT\n    tb  =  ARIA_P2( tb ) ^ ta;      // 2301+5476+89ab+98ba+cdef+fedc\n    *a  ^= ARIA_P1( tb );           // 3210+4567+6745+89ab+98ba+dcfe+efcd OUT\n    ta  =  ARIA_P2( ta );           // 0123+7654+ab89+dcfe\n    *d  ^= ARIA_P1( ta ) ^ tc;      // 1032+2301+6745+7654+98ba+ba98+cdef OUT\n    tc  =  ARIA_P2( tc );           // 0123+5476\n    *c  ^= ARIA_P1( tc ) ^ ta;      // 0123+1032+4567+7654+ab89+dcfe+fedc OUT\n}\n\n/*\n * ARIA Substitution Layer SL1 / SL2\n * (a, b, c, d) = state in/out\n * (sa, sb, sc, sd) = 256 8-bit S-Boxes (see below)\n *\n * By passing sb1, sb2, is1, is2 as S-Boxes you get SL1\n * By passing is1, is2, sb1, sb2 as S-Boxes you get SL2\n */\nstatic inline void aria_sl( uint32_t *a, uint32_t *b,\n                            uint32_t *c, uint32_t *d,\n                            const uint8_t sa[256], const uint8_t sb[256],\n                            const uint8_t sc[256], const uint8_t sd[256] )\n{\n    *a = ( (uint32_t) sa[ *a        & 0xFF]       ) ^\n         (((uint32_t) sb[(*a >>  8) & 0xFF]) <<  8) ^\n         (((uint32_t) sc[(*a >> 16) & 0xFF]) << 16) ^\n         (((uint32_t) sd[ *a >> 24        ]) << 24);\n    *b = ( (uint32_t) sa[ *b        & 0xFF]       ) ^\n         (((uint32_t) sb[(*b >>  8) & 0xFF]) <<  8) ^\n         (((uint32_t) sc[(*b >> 16) & 0xFF]) << 16) ^\n         (((uint32_t) sd[ *b >> 24        ]) << 24);\n    *c = ( (uint32_t) sa[ *c        & 0xFF]       ) ^\n         (((uint32_t) sb[(*c >>  8) & 0xFF]) <<  8) ^\n         (((uint32_t) sc[(*c >> 16) & 0xFF]) << 16) ^\n         (((uint32_t) sd[ *c >> 24        ]) << 24);\n    *d = ( (uint32_t) sa[ *d        & 0xFF]       ) ^\n         (((uint32_t) sb[(*d >>  8) & 0xFF]) <<  8) ^\n         (((uint32_t) sc[(*d >> 16) & 0xFF]) << 16) ^\n         (((uint32_t) sd[ *d >> 24        ]) << 24);\n}\n\n/*\n * S-Boxes\n */\nstatic const uint8_t aria_sb1[256] =\n{\n    0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B,\n    0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0,\n    0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26,\n    0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\n    0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2,\n    0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0,\n    0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED,\n    0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,\n    0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F,\n    0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5,\n    0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC,\n    0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,\n    0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14,\n    0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C,\n    0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D,\n    0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,\n    0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F,\n    0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E,\n    0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11,\n    0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\n    0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F,\n    0xB0, 0x54, 0xBB, 0x16\n};\n\nstatic const uint8_t aria_sb2[256] =\n{\n    0xE2, 0x4E, 0x54, 0xFC, 0x94, 0xC2, 0x4A, 0xCC, 0x62, 0x0D, 0x6A, 0x46,\n    0x3C, 0x4D, 0x8B, 0xD1, 0x5E, 0xFA, 0x64, 0xCB, 0xB4, 0x97, 0xBE, 0x2B,\n    0xBC, 0x77, 0x2E, 0x03, 0xD3, 0x19, 0x59, 0xC1, 0x1D, 0x06, 0x41, 0x6B,\n    0x55, 0xF0, 0x99, 0x69, 0xEA, 0x9C, 0x18, 0xAE, 0x63, 0xDF, 0xE7, 0xBB,\n    0x00, 0x73, 0x66, 0xFB, 0x96, 0x4C, 0x85, 0xE4, 0x3A, 0x09, 0x45, 0xAA,\n    0x0F, 0xEE, 0x10, 0xEB, 0x2D, 0x7F, 0xF4, 0x29, 0xAC, 0xCF, 0xAD, 0x91,\n    0x8D, 0x78, 0xC8, 0x95, 0xF9, 0x2F, 0xCE, 0xCD, 0x08, 0x7A, 0x88, 0x38,\n    0x5C, 0x83, 0x2A, 0x28, 0x47, 0xDB, 0xB8, 0xC7, 0x93, 0xA4, 0x12, 0x53,\n    0xFF, 0x87, 0x0E, 0x31, 0x36, 0x21, 0x58, 0x48, 0x01, 0x8E, 0x37, 0x74,\n    0x32, 0xCA, 0xE9, 0xB1, 0xB7, 0xAB, 0x0C, 0xD7, 0xC4, 0x56, 0x42, 0x26,\n    0x07, 0x98, 0x60, 0xD9, 0xB6, 0xB9, 0x11, 0x40, 0xEC, 0x20, 0x8C, 0xBD,\n    0xA0, 0xC9, 0x84, 0x04, 0x49, 0x23, 0xF1, 0x4F, 0x50, 0x1F, 0x13, 0xDC,\n    0xD8, 0xC0, 0x9E, 0x57, 0xE3, 0xC3, 0x7B, 0x65, 0x3B, 0x02, 0x8F, 0x3E,\n    0xE8, 0x25, 0x92, 0xE5, 0x15, 0xDD, 0xFD, 0x17, 0xA9, 0xBF, 0xD4, 0x9A,\n    0x7E, 0xC5, 0x39, 0x67, 0xFE, 0x76, 0x9D, 0x43, 0xA7, 0xE1, 0xD0, 0xF5,\n    0x68, 0xF2, 0x1B, 0x34, 0x70, 0x05, 0xA3, 0x8A, 0xD5, 0x79, 0x86, 0xA8,\n    0x30, 0xC6, 0x51, 0x4B, 0x1E, 0xA6, 0x27, 0xF6, 0x35, 0xD2, 0x6E, 0x24,\n    0x16, 0x82, 0x5F, 0xDA, 0xE6, 0x75, 0xA2, 0xEF, 0x2C, 0xB2, 0x1C, 0x9F,\n    0x5D, 0x6F, 0x80, 0x0A, 0x72, 0x44, 0x9B, 0x6C, 0x90, 0x0B, 0x5B, 0x33,\n    0x7D, 0x5A, 0x52, 0xF3, 0x61, 0xA1, 0xF7, 0xB0, 0xD6, 0x3F, 0x7C, 0x6D,\n    0xED, 0x14, 0xE0, 0xA5, 0x3D, 0x22, 0xB3, 0xF8, 0x89, 0xDE, 0x71, 0x1A,\n    0xAF, 0xBA, 0xB5, 0x81\n};\n\nstatic const uint8_t aria_is1[256] =\n{\n    0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E,\n    0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87,\n    0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32,\n    0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,\n    0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49,\n    0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16,\n    0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50,\n    0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,\n    0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05,\n    0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02,\n    0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41,\n    0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,\n    0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8,\n    0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89,\n    0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B,\n    0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,\n    0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59,\n    0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D,\n    0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D,\n    0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,\n    0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63,\n    0x55, 0x21, 0x0C, 0x7D\n};\n\nstatic const uint8_t aria_is2[256] =\n{\n    0x30, 0x68, 0x99, 0x1B, 0x87, 0xB9, 0x21, 0x78, 0x50, 0x39, 0xDB, 0xE1,\n    0x72, 0x09, 0x62, 0x3C, 0x3E, 0x7E, 0x5E, 0x8E, 0xF1, 0xA0, 0xCC, 0xA3,\n    0x2A, 0x1D, 0xFB, 0xB6, 0xD6, 0x20, 0xC4, 0x8D, 0x81, 0x65, 0xF5, 0x89,\n    0xCB, 0x9D, 0x77, 0xC6, 0x57, 0x43, 0x56, 0x17, 0xD4, 0x40, 0x1A, 0x4D,\n    0xC0, 0x63, 0x6C, 0xE3, 0xB7, 0xC8, 0x64, 0x6A, 0x53, 0xAA, 0x38, 0x98,\n    0x0C, 0xF4, 0x9B, 0xED, 0x7F, 0x22, 0x76, 0xAF, 0xDD, 0x3A, 0x0B, 0x58,\n    0x67, 0x88, 0x06, 0xC3, 0x35, 0x0D, 0x01, 0x8B, 0x8C, 0xC2, 0xE6, 0x5F,\n    0x02, 0x24, 0x75, 0x93, 0x66, 0x1E, 0xE5, 0xE2, 0x54, 0xD8, 0x10, 0xCE,\n    0x7A, 0xE8, 0x08, 0x2C, 0x12, 0x97, 0x32, 0xAB, 0xB4, 0x27, 0x0A, 0x23,\n    0xDF, 0xEF, 0xCA, 0xD9, 0xB8, 0xFA, 0xDC, 0x31, 0x6B, 0xD1, 0xAD, 0x19,\n    0x49, 0xBD, 0x51, 0x96, 0xEE, 0xE4, 0xA8, 0x41, 0xDA, 0xFF, 0xCD, 0x55,\n    0x86, 0x36, 0xBE, 0x61, 0x52, 0xF8, 0xBB, 0x0E, 0x82, 0x48, 0x69, 0x9A,\n    0xE0, 0x47, 0x9E, 0x5C, 0x04, 0x4B, 0x34, 0x15, 0x79, 0x26, 0xA7, 0xDE,\n    0x29, 0xAE, 0x92, 0xD7, 0x84, 0xE9, 0xD2, 0xBA, 0x5D, 0xF3, 0xC5, 0xB0,\n    0xBF, 0xA4, 0x3B, 0x71, 0x44, 0x46, 0x2B, 0xFC, 0xEB, 0x6F, 0xD5, 0xF6,\n    0x14, 0xFE, 0x7C, 0x70, 0x5A, 0x7D, 0xFD, 0x2F, 0x18, 0x83, 0x16, 0xA5,\n    0x91, 0x1F, 0x05, 0x95, 0x74, 0xA9, 0xC1, 0x5B, 0x4A, 0x85, 0x6D, 0x13,\n    0x07, 0x4F, 0x4E, 0x45, 0xB2, 0x0F, 0xC9, 0x1C, 0xA6, 0xBC, 0xEC, 0x73,\n    0x90, 0x7B, 0xCF, 0x59, 0x8F, 0xA1, 0xF9, 0x2D, 0xF2, 0xB1, 0x00, 0x94,\n    0x37, 0x9F, 0xD0, 0x2E, 0x9C, 0x6E, 0x28, 0x3F, 0x80, 0xF0, 0x3D, 0xD3,\n    0x25, 0x8A, 0xB5, 0xE7, 0x42, 0xB3, 0xC7, 0xEA, 0xF7, 0x4C, 0x11, 0x33,\n    0x03, 0xA2, 0xAC, 0x60\n};\n\n/*\n * Helper for key schedule: r = FO( p, k ) ^ x\n */\nstatic void aria_fo_xor( uint32_t r[4], const uint32_t p[4],\n                         const uint32_t k[4], const uint32_t x[4] )\n{\n    uint32_t a, b, c, d;\n\n    a = p[0] ^ k[0];\n    b = p[1] ^ k[1];\n    c = p[2] ^ k[2];\n    d = p[3] ^ k[3];\n\n    aria_sl( &a, &b, &c, &d, aria_sb1, aria_sb2, aria_is1, aria_is2 );\n    aria_a( &a, &b, &c, &d );\n\n    r[0] = a ^ x[0];\n    r[1] = b ^ x[1];\n    r[2] = c ^ x[2];\n    r[3] = d ^ x[3];\n}\n\n/*\n * Helper for key schedule: r = FE( p, k ) ^ x\n */\nstatic void aria_fe_xor( uint32_t r[4], const uint32_t p[4],\n                         const uint32_t k[4], const uint32_t x[4] )\n{\n    uint32_t a, b, c, d;\n\n    a = p[0] ^ k[0];\n    b = p[1] ^ k[1];\n    c = p[2] ^ k[2];\n    d = p[3] ^ k[3];\n\n    aria_sl( &a, &b, &c, &d, aria_is1, aria_is2, aria_sb1, aria_sb2 );\n    aria_a( &a, &b, &c, &d );\n\n    r[0] = a ^ x[0];\n    r[1] = b ^ x[1];\n    r[2] = c ^ x[2];\n    r[3] = d ^ x[3];\n}\n\n/*\n * Big endian 128-bit rotation: r = a ^ (b <<< n), used only in key setup.\n *\n * We chose to store bytes into 32-bit words in little-endian format (see\n * GET/PUT_UINT32_LE) so we need to reverse bytes here.\n */\nstatic void aria_rot128( uint32_t r[4], const uint32_t a[4],\n                         const uint32_t b[4], uint8_t n )\n{\n    uint8_t i, j;\n    uint32_t t, u;\n\n    const uint8_t n1 = n % 32;              // bit offset\n    const uint8_t n2 = n1 ? 32 - n1 : 0;    // reverse bit offset\n\n    j = ( n / 32 ) % 4;                     // initial word offset\n    t = ARIA_P3( b[j] );                    // big endian\n    for( i = 0; i < 4; i++ )\n    {\n        j = ( j + 1 ) % 4;                  // get next word, big endian\n        u = ARIA_P3( b[j] );\n        t <<= n1;                           // rotate\n        t |= u >> n2;\n        t = ARIA_P3( t );                   // back to little endian\n        r[i] = a[i] ^ t;                    // store\n        t = u;                              // move to next word\n    }\n}\n\n/*\n * Set encryption key\n */\nint mbedtls_aria_setkey_enc( mbedtls_aria_context *ctx,\n                             const unsigned char *key, unsigned int keybits )\n{\n    /* round constant masks */\n    const uint32_t rc[3][4] =\n    {\n        {   0xB7C17C51, 0x940A2227, 0xE8AB13FE, 0xE06E9AFA  },\n        {   0xCC4AB16D, 0x20C8219E, 0xD5B128FF, 0xB0E25DEF  },\n        {   0x1D3792DB, 0x70E92621, 0x75972403, 0x0EC9E804  }\n    };\n\n    int i;\n    uint32_t w[4][4], *w2;\n\n    if( keybits != 128 && keybits != 192 && keybits != 256 )\n        return( MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH );\n\n    /* Copy key to W0 (and potential remainder to W1) */\n    GET_UINT32_LE( w[0][0], key,  0 );\n    GET_UINT32_LE( w[0][1], key,  4 );\n    GET_UINT32_LE( w[0][2], key,  8 );\n    GET_UINT32_LE( w[0][3], key, 12 );\n\n    memset( w[1], 0, 16 );\n    if( keybits >= 192 )\n    {\n        GET_UINT32_LE( w[1][0], key, 16 );  // 192 bit key\n        GET_UINT32_LE( w[1][1], key, 20 );\n    }\n    if( keybits == 256 )\n    {\n        GET_UINT32_LE( w[1][2], key, 24 );  // 256 bit key\n        GET_UINT32_LE( w[1][3], key, 28 );\n    }\n\n    i = ( keybits - 128 ) >> 6;             // index: 0, 1, 2\n    ctx->nr = 12 + 2 * i;                   // no. rounds: 12, 14, 16\n\n    aria_fo_xor( w[1], w[0], rc[i], w[1] ); // W1 = FO(W0, CK1) ^ KR\n    i = i < 2 ? i + 1 : 0;\n    aria_fe_xor( w[2], w[1], rc[i], w[0] ); // W2 = FE(W1, CK2) ^ W0\n    i = i < 2 ? i + 1 : 0;\n    aria_fo_xor( w[3], w[2], rc[i], w[1] ); // W3 = FO(W2, CK3) ^ W1\n\n    for( i = 0; i < 4; i++ )                // create round keys\n    {\n        w2 = w[(i + 1) & 3];\n        aria_rot128( ctx->rk[i     ], w[i], w2, 128 - 19 );\n        aria_rot128( ctx->rk[i +  4], w[i], w2, 128 - 31 );\n        aria_rot128( ctx->rk[i +  8], w[i], w2,       61 );\n        aria_rot128( ctx->rk[i + 12], w[i], w2,       31 );\n    }\n    aria_rot128( ctx->rk[16], w[0], w[1], 19 );\n\n    /* w holds enough info to reconstruct the round keys */\n    mbedtls_platform_zeroize( w, sizeof( w ) );\n\n    return( 0 );\n}\n\n/*\n * Set decryption key\n */\nint mbedtls_aria_setkey_dec( mbedtls_aria_context *ctx,\n                             const unsigned char *key, unsigned int keybits )\n{\n    int i, j, k, ret;\n\n    ret = mbedtls_aria_setkey_enc( ctx, key, keybits );\n    if( ret != 0 )\n        return( ret );\n\n    /* flip the order of round keys */\n    for( i = 0, j = ctx->nr; i < j; i++, j-- )\n    {\n        for( k = 0; k < 4; k++ )\n        {\n            uint32_t t = ctx->rk[i][k];\n            ctx->rk[i][k] = ctx->rk[j][k];\n            ctx->rk[j][k] = t;\n        }\n    }\n\n    /* apply affine transform to middle keys */\n    for( i = 1; i < ctx->nr; i++ )\n    {\n        aria_a( &ctx->rk[i][0], &ctx->rk[i][1],\n                &ctx->rk[i][2], &ctx->rk[i][3] );\n    }\n\n    return( 0 );\n}\n\n/*\n * Encrypt a block\n */\nint mbedtls_aria_crypt_ecb( mbedtls_aria_context *ctx,\n                            const unsigned char input[MBEDTLS_ARIA_BLOCKSIZE],\n                            unsigned char output[MBEDTLS_ARIA_BLOCKSIZE] )\n{\n    int i;\n\n    uint32_t a, b, c, d;\n\n    GET_UINT32_LE( a, input,  0 );\n    GET_UINT32_LE( b, input,  4 );\n    GET_UINT32_LE( c, input,  8 );\n    GET_UINT32_LE( d, input, 12 );\n\n    i = 0;\n    while( 1 )\n    {\n        a ^= ctx->rk[i][0];\n        b ^= ctx->rk[i][1];\n        c ^= ctx->rk[i][2];\n        d ^= ctx->rk[i][3];\n        i++;\n\n        aria_sl( &a, &b, &c, &d, aria_sb1, aria_sb2, aria_is1, aria_is2 );\n        aria_a( &a, &b, &c, &d );\n\n        a ^= ctx->rk[i][0];\n        b ^= ctx->rk[i][1];\n        c ^= ctx->rk[i][2];\n        d ^= ctx->rk[i][3];\n        i++;\n\n        aria_sl( &a, &b, &c, &d, aria_is1, aria_is2, aria_sb1, aria_sb2 );\n        if( i >= ctx->nr )\n            break;\n        aria_a( &a, &b, &c, &d );\n    }\n\n    /* final key mixing */\n    a ^= ctx->rk[i][0];\n    b ^= ctx->rk[i][1];\n    c ^= ctx->rk[i][2];\n    d ^= ctx->rk[i][3];\n\n    PUT_UINT32_LE( a, output,  0 );\n    PUT_UINT32_LE( b, output,  4 );\n    PUT_UINT32_LE( c, output,  8 );\n    PUT_UINT32_LE( d, output, 12 );\n\n    return( 0 );\n}\n\n/* Initialize context */\nvoid mbedtls_aria_init( mbedtls_aria_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_aria_context ) );\n}\n\n/* Clear context */\nvoid mbedtls_aria_free( mbedtls_aria_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_aria_context ) );\n}\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n/*\n * ARIA-CBC buffer encryption/decryption\n */\nint mbedtls_aria_crypt_cbc( mbedtls_aria_context *ctx,\n                            int mode,\n                            size_t length,\n                            unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE],\n                            const unsigned char *input,\n                            unsigned char *output )\n{\n    int i;\n    unsigned char temp[MBEDTLS_ARIA_BLOCKSIZE];\n\n    if( length % MBEDTLS_ARIA_BLOCKSIZE )\n        return( MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH );\n\n    if( mode == MBEDTLS_ARIA_DECRYPT )\n    {\n        while( length > 0 )\n        {\n            memcpy( temp, input, MBEDTLS_ARIA_BLOCKSIZE );\n            mbedtls_aria_crypt_ecb( ctx, input, output );\n\n            for( i = 0; i < MBEDTLS_ARIA_BLOCKSIZE; i++ )\n                output[i] = (unsigned char)( output[i] ^ iv[i] );\n\n            memcpy( iv, temp, MBEDTLS_ARIA_BLOCKSIZE );\n\n            input  += MBEDTLS_ARIA_BLOCKSIZE;\n            output += MBEDTLS_ARIA_BLOCKSIZE;\n            length -= MBEDTLS_ARIA_BLOCKSIZE;\n        }\n    }\n    else\n    {\n        while( length > 0 )\n        {\n            for( i = 0; i < MBEDTLS_ARIA_BLOCKSIZE; i++ )\n                output[i] = (unsigned char)( input[i] ^ iv[i] );\n\n            mbedtls_aria_crypt_ecb( ctx, output, output );\n            memcpy( iv, output, MBEDTLS_ARIA_BLOCKSIZE );\n\n            input  += MBEDTLS_ARIA_BLOCKSIZE;\n            output += MBEDTLS_ARIA_BLOCKSIZE;\n            length -= MBEDTLS_ARIA_BLOCKSIZE;\n        }\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n/*\n * ARIA-CFB128 buffer encryption/decryption\n */\nint mbedtls_aria_crypt_cfb128( mbedtls_aria_context *ctx,\n                               int mode,\n                               size_t length,\n                               size_t *iv_off,\n                               unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE],\n                               const unsigned char *input,\n                               unsigned char *output )\n{\n    unsigned char c;\n    size_t n = *iv_off;\n\n    if( mode == MBEDTLS_ARIA_DECRYPT )\n    {\n        while( length-- )\n        {\n            if( n == 0 )\n                mbedtls_aria_crypt_ecb( ctx, iv, iv );\n\n            c = *input++;\n            *output++ = c ^ iv[n];\n            iv[n] = c;\n\n            n = ( n + 1 ) & 0x0F;\n        }\n    }\n    else\n    {\n        while( length-- )\n        {\n            if( n == 0 )\n                mbedtls_aria_crypt_ecb( ctx, iv, iv );\n\n            iv[n] = *output++ = (unsigned char)( iv[n] ^ *input++ );\n\n            n = ( n + 1 ) & 0x0F;\n        }\n    }\n\n    *iv_off = n;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n/*\n * ARIA-CTR buffer encryption/decryption\n */\nint mbedtls_aria_crypt_ctr( mbedtls_aria_context *ctx,\n                            size_t length,\n                            size_t *nc_off,\n                            unsigned char nonce_counter[MBEDTLS_ARIA_BLOCKSIZE],\n                            unsigned char stream_block[MBEDTLS_ARIA_BLOCKSIZE],\n                            const unsigned char *input,\n                            unsigned char *output )\n{\n    int c, i;\n    size_t n = *nc_off;\n\n    while( length-- )\n    {\n        if( n == 0 ) {\n            mbedtls_aria_crypt_ecb( ctx, nonce_counter,\n                                stream_block );\n\n            for( i = MBEDTLS_ARIA_BLOCKSIZE; i > 0; i-- )\n                if( ++nonce_counter[i - 1] != 0 )\n                    break;\n        }\n        c = *input++;\n        *output++ = (unsigned char)( c ^ stream_block[n] );\n\n        n = ( n + 1 ) & 0x0F;\n    }\n\n    *nc_off = n;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n#endif /* !MBEDTLS_ARIA_ALT */\n\n#if defined(MBEDTLS_SELF_TEST)\n\n/*\n * Basic ARIA ECB test vectors from RFC 5794\n */\nstatic const uint8_t aria_test1_ecb_key[32] =           // test key\n{\n    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,     // 128 bit\n    0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,\n    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,     // 192 bit\n    0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F      // 256 bit\n};\n\nstatic const uint8_t aria_test1_ecb_pt[MBEDTLS_ARIA_BLOCKSIZE] =            // plaintext\n{\n    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,     // same for all\n    0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF      // key sizes\n};\n\nstatic const uint8_t aria_test1_ecb_ct[3][MBEDTLS_ARIA_BLOCKSIZE] =         // ciphertext\n{\n    { 0xD7, 0x18, 0xFB, 0xD6, 0xAB, 0x64, 0x4C, 0x73,   // 128 bit\n      0x9D, 0xA9, 0x5F, 0x3B, 0xE6, 0x45, 0x17, 0x78 },\n    { 0x26, 0x44, 0x9C, 0x18, 0x05, 0xDB, 0xE7, 0xAA,   // 192 bit\n      0x25, 0xA4, 0x68, 0xCE, 0x26, 0x3A, 0x9E, 0x79 },\n    { 0xF9, 0x2B, 0xD7, 0xC7, 0x9F, 0xB7, 0x2E, 0x2F,   // 256 bit\n      0x2B, 0x8F, 0x80, 0xC1, 0x97, 0x2D, 0x24, 0xFC }\n};\n\n/*\n * Mode tests from \"Test Vectors for ARIA\"  Version 1.0\n * http://210.104.33.10/ARIA/doc/ARIA-testvector-e.pdf\n */\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) || defined(MBEDTLS_CIPHER_MODE_CFB) || \\\n    defined(MBEDTLS_CIPHER_MODE_CTR))\nstatic const uint8_t aria_test2_key[32] =\n{\n    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,     // 128 bit\n    0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff,\n    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,     // 192 bit\n    0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff      // 256 bit\n};\n\nstatic const uint8_t aria_test2_pt[48] =\n{\n    0x11, 0x11, 0x11, 0x11, 0xaa, 0xaa, 0xaa, 0xaa,     // same for all\n    0x11, 0x11, 0x11, 0x11, 0xbb, 0xbb, 0xbb, 0xbb,\n    0x11, 0x11, 0x11, 0x11, 0xcc, 0xcc, 0xcc, 0xcc,\n    0x11, 0x11, 0x11, 0x11, 0xdd, 0xdd, 0xdd, 0xdd,\n    0x22, 0x22, 0x22, 0x22, 0xaa, 0xaa, 0xaa, 0xaa,\n    0x22, 0x22, 0x22, 0x22, 0xbb, 0xbb, 0xbb, 0xbb,\n};\n#endif\n\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) || defined(MBEDTLS_CIPHER_MODE_CFB))\nstatic const uint8_t aria_test2_iv[MBEDTLS_ARIA_BLOCKSIZE] =\n{\n    0x0f, 0x1e, 0x2d, 0x3c, 0x4b, 0x5a, 0x69, 0x78,     // same for CBC, CFB\n    0x87, 0x96, 0xa5, 0xb4, 0xc3, 0xd2, 0xe1, 0xf0      // CTR has zero IV\n};\n#endif\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\nstatic const uint8_t aria_test2_cbc_ct[3][48] =         // CBC ciphertext\n{\n    { 0x49, 0xd6, 0x18, 0x60, 0xb1, 0x49, 0x09, 0x10,   // 128-bit key\n      0x9c, 0xef, 0x0d, 0x22, 0xa9, 0x26, 0x81, 0x34,\n      0xfa, 0xdf, 0x9f, 0xb2, 0x31, 0x51, 0xe9, 0x64,\n      0x5f, 0xba, 0x75, 0x01, 0x8b, 0xdb, 0x15, 0x38,\n      0xb5, 0x33, 0x34, 0x63, 0x4b, 0xbf, 0x7d, 0x4c,\n      0xd4, 0xb5, 0x37, 0x70, 0x33, 0x06, 0x0c, 0x15 },\n    { 0xaf, 0xe6, 0xcf, 0x23, 0x97, 0x4b, 0x53, 0x3c,   // 192-bit key\n      0x67, 0x2a, 0x82, 0x62, 0x64, 0xea, 0x78, 0x5f,\n      0x4e, 0x4f, 0x7f, 0x78, 0x0d, 0xc7, 0xf3, 0xf1,\n      0xe0, 0x96, 0x2b, 0x80, 0x90, 0x23, 0x86, 0xd5,\n      0x14, 0xe9, 0xc3, 0xe7, 0x72, 0x59, 0xde, 0x92,\n      0xdd, 0x11, 0x02, 0xff, 0xab, 0x08, 0x6c, 0x1e },\n    { 0x52, 0x3a, 0x8a, 0x80, 0x6a, 0xe6, 0x21, 0xf1,   // 256-bit key\n      0x55, 0xfd, 0xd2, 0x8d, 0xbc, 0x34, 0xe1, 0xab,\n      0x7b, 0x9b, 0x42, 0x43, 0x2a, 0xd8, 0xb2, 0xef,\n      0xb9, 0x6e, 0x23, 0xb1, 0x3f, 0x0a, 0x6e, 0x52,\n      0xf3, 0x61, 0x85, 0xd5, 0x0a, 0xd0, 0x02, 0xc5,\n      0xf6, 0x01, 0xbe, 0xe5, 0x49, 0x3f, 0x11, 0x8b }\n};\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\nstatic const uint8_t aria_test2_cfb_ct[3][48] =         // CFB ciphertext\n{\n    { 0x37, 0x20, 0xe5, 0x3b, 0xa7, 0xd6, 0x15, 0x38,   // 128-bit key\n      0x34, 0x06, 0xb0, 0x9f, 0x0a, 0x05, 0xa2, 0x00,\n      0xc0, 0x7c, 0x21, 0xe6, 0x37, 0x0f, 0x41, 0x3a,\n      0x5d, 0x13, 0x25, 0x00, 0xa6, 0x82, 0x85, 0x01,\n      0x7c, 0x61, 0xb4, 0x34, 0xc7, 0xb7, 0xca, 0x96,\n      0x85, 0xa5, 0x10, 0x71, 0x86, 0x1e, 0x4d, 0x4b },\n    { 0x41, 0x71, 0xf7, 0x19, 0x2b, 0xf4, 0x49, 0x54,   // 192-bit key\n      0x94, 0xd2, 0x73, 0x61, 0x29, 0x64, 0x0f, 0x5c,\n      0x4d, 0x87, 0xa9, 0xa2, 0x13, 0x66, 0x4c, 0x94,\n      0x48, 0x47, 0x7c, 0x6e, 0xcc, 0x20, 0x13, 0x59,\n      0x8d, 0x97, 0x66, 0x95, 0x2d, 0xd8, 0xc3, 0x86,\n      0x8f, 0x17, 0xe3, 0x6e, 0xf6, 0x6f, 0xd8, 0x4b },\n    { 0x26, 0x83, 0x47, 0x05, 0xb0, 0xf2, 0xc0, 0xe2,   // 256-bit key\n      0x58, 0x8d, 0x4a, 0x7f, 0x09, 0x00, 0x96, 0x35,\n      0xf2, 0x8b, 0xb9, 0x3d, 0x8c, 0x31, 0xf8, 0x70,\n      0xec, 0x1e, 0x0b, 0xdb, 0x08, 0x2b, 0x66, 0xfa,\n      0x40, 0x2d, 0xd9, 0xc2, 0x02, 0xbe, 0x30, 0x0c,\n      0x45, 0x17, 0xd1, 0x96, 0xb1, 0x4d, 0x4c, 0xe1 }\n};\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\nstatic const uint8_t aria_test2_ctr_ct[3][48] =         // CTR ciphertext\n{\n    { 0xac, 0x5d, 0x7d, 0xe8, 0x05, 0xa0, 0xbf, 0x1c,   // 128-bit key\n      0x57, 0xc8, 0x54, 0x50, 0x1a, 0xf6, 0x0f, 0xa1,\n      0x14, 0x97, 0xe2, 0xa3, 0x45, 0x19, 0xde, 0xa1,\n      0x56, 0x9e, 0x91, 0xe5, 0xb5, 0xcc, 0xae, 0x2f,\n      0xf3, 0xbf, 0xa1, 0xbf, 0x97, 0x5f, 0x45, 0x71,\n      0xf4, 0x8b, 0xe1, 0x91, 0x61, 0x35, 0x46, 0xc3 },\n    { 0x08, 0x62, 0x5c, 0xa8, 0xfe, 0x56, 0x9c, 0x19,   // 192-bit key\n      0xba, 0x7a, 0xf3, 0x76, 0x0a, 0x6e, 0xd1, 0xce,\n      0xf4, 0xd1, 0x99, 0x26, 0x3e, 0x99, 0x9d, 0xde,\n      0x14, 0x08, 0x2d, 0xbb, 0xa7, 0x56, 0x0b, 0x79,\n      0xa4, 0xc6, 0xb4, 0x56, 0xb8, 0x70, 0x7d, 0xce,\n      0x75, 0x1f, 0x98, 0x54, 0xf1, 0x88, 0x93, 0xdf },\n    { 0x30, 0x02, 0x6c, 0x32, 0x96, 0x66, 0x14, 0x17,   // 256-bit key\n      0x21, 0x17, 0x8b, 0x99, 0xc0, 0xa1, 0xf1, 0xb2,\n      0xf0, 0x69, 0x40, 0x25, 0x3f, 0x7b, 0x30, 0x89,\n      0xe2, 0xa3, 0x0e, 0xa8, 0x6a, 0xa3, 0xc8, 0x8f,\n      0x59, 0x40, 0xf0, 0x5a, 0xd7, 0xee, 0x41, 0xd7,\n      0x13, 0x47, 0xbb, 0x72, 0x61, 0xe3, 0x48, 0xf1 }\n};\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#define ARIA_SELF_TEST_IF_FAIL              \\\n        {                                   \\\n            if( verbose )                   \\\n                printf( \"failed\\n\" );       \\\n            return( 1 );                    \\\n        } else {                            \\\n            if( verbose )                   \\\n                printf( \"passed\\n\" );       \\\n        }\n\n/*\n * Checkup routine\n */\nint mbedtls_aria_self_test( int verbose )\n{\n    int i;\n    uint8_t blk[MBEDTLS_ARIA_BLOCKSIZE];\n    mbedtls_aria_context ctx;\n\n#if (defined(MBEDTLS_CIPHER_MODE_CFB) || defined(MBEDTLS_CIPHER_MODE_CTR))\n    size_t j;\n#endif\n\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) || \\\n     defined(MBEDTLS_CIPHER_MODE_CFB) || \\\n     defined(MBEDTLS_CIPHER_MODE_CTR))\n    uint8_t buf[48], iv[MBEDTLS_ARIA_BLOCKSIZE];\n#endif\n\n    /*\n     * Test set 1\n     */\n    for( i = 0; i < 3; i++ )\n    {\n        /* test ECB encryption */\n        if( verbose )\n            printf( \"  ARIA-ECB-%d (enc): \", 128 + 64 * i );\n        mbedtls_aria_setkey_enc( &ctx, aria_test1_ecb_key, 128 + 64 * i );\n        mbedtls_aria_crypt_ecb( &ctx, aria_test1_ecb_pt, blk );\n        if( memcmp( blk, aria_test1_ecb_ct[i], MBEDTLS_ARIA_BLOCKSIZE ) != 0 )\n            ARIA_SELF_TEST_IF_FAIL;\n\n        /* test ECB decryption */\n        if( verbose )\n            printf( \"  ARIA-ECB-%d (dec): \", 128 + 64 * i );\n        mbedtls_aria_setkey_dec( &ctx, aria_test1_ecb_key, 128 + 64 * i );\n        mbedtls_aria_crypt_ecb( &ctx, aria_test1_ecb_ct[i], blk );\n        if( memcmp( blk, aria_test1_ecb_pt, MBEDTLS_ARIA_BLOCKSIZE ) != 0 )\n            ARIA_SELF_TEST_IF_FAIL;\n    }\n    if( verbose )\n        printf( \"\\n\" );\n\n    /*\n     * Test set 2\n     */\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    for( i = 0; i < 3; i++ )\n    {\n        /* Test CBC encryption */\n        if( verbose )\n            printf( \"  ARIA-CBC-%d (enc): \", 128 + 64 * i );\n        mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i );\n        memcpy( iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE );\n        memset( buf, 0x55, sizeof( buf ) );\n        mbedtls_aria_crypt_cbc( &ctx, MBEDTLS_ARIA_ENCRYPT, 48, iv,\n            aria_test2_pt, buf );\n        if( memcmp( buf, aria_test2_cbc_ct[i], 48 ) != 0 )\n            ARIA_SELF_TEST_IF_FAIL;\n\n        /* Test CBC decryption */\n        if( verbose )\n            printf( \"  ARIA-CBC-%d (dec): \", 128 + 64 * i );\n        mbedtls_aria_setkey_dec( &ctx, aria_test2_key, 128 + 64 * i );\n        memcpy( iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE );\n        memset( buf, 0xAA, sizeof( buf ) );\n        mbedtls_aria_crypt_cbc( &ctx, MBEDTLS_ARIA_DECRYPT, 48, iv,\n            aria_test2_cbc_ct[i], buf );\n        if( memcmp( buf, aria_test2_pt, 48 ) != 0 )\n            ARIA_SELF_TEST_IF_FAIL;\n    }\n    if( verbose )\n        printf( \"\\n\" );\n\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    for( i = 0; i < 3; i++ )\n    {\n        /* Test CFB encryption */\n        if( verbose )\n            printf( \"  ARIA-CFB-%d (enc): \", 128 + 64 * i );\n        mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i );\n        memcpy( iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE );\n        memset( buf, 0x55, sizeof( buf ) );\n        j = 0;\n        mbedtls_aria_crypt_cfb128( &ctx, MBEDTLS_ARIA_ENCRYPT, 48, &j, iv,\n            aria_test2_pt, buf );\n        if( memcmp( buf, aria_test2_cfb_ct[i], 48 ) != 0 )\n            ARIA_SELF_TEST_IF_FAIL;\n\n        /* Test CFB decryption */\n        if( verbose )\n            printf( \"  ARIA-CFB-%d (dec): \", 128 + 64 * i );\n        mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i );\n        memcpy( iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE );\n        memset( buf, 0xAA, sizeof( buf ) );\n        j = 0;\n        mbedtls_aria_crypt_cfb128( &ctx, MBEDTLS_ARIA_DECRYPT, 48, &j,\n            iv, aria_test2_cfb_ct[i], buf );\n        if( memcmp( buf, aria_test2_pt, 48 ) != 0 )\n            ARIA_SELF_TEST_IF_FAIL;\n    }\n    if( verbose )\n        printf( \"\\n\" );\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    for( i = 0; i < 3; i++ )\n    {\n        /* Test CTR encryption */\n        if( verbose )\n            printf( \"  ARIA-CTR-%d (enc): \", 128 + 64 * i );\n        mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i );\n        memset( iv, 0, MBEDTLS_ARIA_BLOCKSIZE );                    // IV = 0\n        memset( buf, 0x55, sizeof( buf ) );\n        j = 0;\n        mbedtls_aria_crypt_ctr( &ctx, 48, &j, iv, blk,\n            aria_test2_pt, buf );\n        if( memcmp( buf, aria_test2_ctr_ct[i], 48 ) != 0 )\n            ARIA_SELF_TEST_IF_FAIL;\n\n        /* Test CTR decryption */\n        if( verbose )\n            printf( \"  ARIA-CTR-%d (dec): \", 128 + 64 * i );\n        mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i );\n        memset( iv, 0, MBEDTLS_ARIA_BLOCKSIZE );                    // IV = 0\n        memset( buf, 0xAA, sizeof( buf ) );\n        j = 0;\n        mbedtls_aria_crypt_ctr( &ctx, 48, &j, iv, blk,\n            aria_test2_ctr_ct[i], buf );\n        if( memcmp( buf, aria_test2_pt, 48 ) != 0 )\n            ARIA_SELF_TEST_IF_FAIL;\n    }\n    if( verbose )\n        printf( \"\\n\" );\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\n    return( 0 );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_ARIA_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/asn1parse.c",
    "content": "/*\n *  Generic ASN.1 parsing\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_ASN1_PARSE_C)\n\n#include \"mbedtls/asn1.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_BIGNUM_C)\n#include \"mbedtls/bignum.h\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc    calloc\n#define mbedtls_free       free\n#endif\n\n/*\n * ASN.1 DER decoding routines\n */\nint mbedtls_asn1_get_len( unsigned char **p,\n                  const unsigned char *end,\n                  size_t *len )\n{\n    if( ( end - *p ) < 1 )\n        return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n    if( ( **p & 0x80 ) == 0 )\n        *len = *(*p)++;\n    else\n    {\n        switch( **p & 0x7F )\n        {\n        case 1:\n            if( ( end - *p ) < 2 )\n                return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n            *len = (*p)[1];\n            (*p) += 2;\n            break;\n\n        case 2:\n            if( ( end - *p ) < 3 )\n                return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n            *len = ( (size_t)(*p)[1] << 8 ) | (*p)[2];\n            (*p) += 3;\n            break;\n\n        case 3:\n            if( ( end - *p ) < 4 )\n                return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n            *len = ( (size_t)(*p)[1] << 16 ) |\n                   ( (size_t)(*p)[2] << 8  ) | (*p)[3];\n            (*p) += 4;\n            break;\n\n        case 4:\n            if( ( end - *p ) < 5 )\n                return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n            *len = ( (size_t)(*p)[1] << 24 ) | ( (size_t)(*p)[2] << 16 ) |\n                   ( (size_t)(*p)[3] << 8  ) |           (*p)[4];\n            (*p) += 5;\n            break;\n\n        default:\n            return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );\n        }\n    }\n\n    if( *len > (size_t) ( end - *p ) )\n        return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n    return( 0 );\n}\n\nint mbedtls_asn1_get_tag( unsigned char **p,\n                  const unsigned char *end,\n                  size_t *len, int tag )\n{\n    if( ( end - *p ) < 1 )\n        return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n    if( **p != tag )\n        return( MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );\n\n    (*p)++;\n\n    return( mbedtls_asn1_get_len( p, end, len ) );\n}\n\nint mbedtls_asn1_get_bool( unsigned char **p,\n                   const unsigned char *end,\n                   int *val )\n{\n    int ret;\n    size_t len;\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_BOOLEAN ) ) != 0 )\n        return( ret );\n\n    if( len != 1 )\n        return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );\n\n    *val = ( **p != 0 ) ? 1 : 0;\n    (*p)++;\n\n    return( 0 );\n}\n\nint mbedtls_asn1_get_int( unsigned char **p,\n                  const unsigned char *end,\n                  int *val )\n{\n    int ret;\n    size_t len;\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ) ) != 0 )\n        return( ret );\n\n    if( len == 0 || len > sizeof( int ) || ( **p & 0x80 ) != 0 )\n        return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );\n\n    *val = 0;\n\n    while( len-- > 0 )\n    {\n        *val = ( *val << 8 ) | **p;\n        (*p)++;\n    }\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_BIGNUM_C)\nint mbedtls_asn1_get_mpi( unsigned char **p,\n                  const unsigned char *end,\n                  mbedtls_mpi *X )\n{\n    int ret;\n    size_t len;\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ) ) != 0 )\n        return( ret );\n\n    ret = mbedtls_mpi_read_binary( X, *p, len );\n\n    *p += len;\n\n    return( ret );\n}\n#endif /* MBEDTLS_BIGNUM_C */\n\nint mbedtls_asn1_get_bitstring( unsigned char **p, const unsigned char *end,\n                        mbedtls_asn1_bitstring *bs)\n{\n    int ret;\n\n    /* Certificate type is a single byte bitstring */\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &bs->len, MBEDTLS_ASN1_BIT_STRING ) ) != 0 )\n        return( ret );\n\n    /* Check length, subtract one for actual bit string length */\n    if( bs->len < 1 )\n        return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n    bs->len -= 1;\n\n    /* Get number of unused bits, ensure unused bits <= 7 */\n    bs->unused_bits = **p;\n    if( bs->unused_bits > 7 )\n        return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );\n    (*p)++;\n\n    /* Get actual bitstring */\n    bs->p = *p;\n    *p += bs->len;\n\n    if( *p != end )\n        return( MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    return( 0 );\n}\n\n/*\n * Get a bit string without unused bits\n */\nint mbedtls_asn1_get_bitstring_null( unsigned char **p, const unsigned char *end,\n                             size_t *len )\n{\n    int ret;\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, len, MBEDTLS_ASN1_BIT_STRING ) ) != 0 )\n        return( ret );\n\n    if( (*len)-- < 2 || *(*p)++ != 0 )\n        return( MBEDTLS_ERR_ASN1_INVALID_DATA );\n\n    return( 0 );\n}\n\n\n\n/*\n *  Parses and splits an ASN.1 \"SEQUENCE OF <tag>\"\n */\nint mbedtls_asn1_get_sequence_of( unsigned char **p,\n                          const unsigned char *end,\n                          mbedtls_asn1_sequence *cur,\n                          int tag)\n{\n    int ret;\n    size_t len;\n    mbedtls_asn1_buf *buf;\n\n    /* Get main sequence tag */\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n        return( ret );\n\n    if( *p + len != end )\n        return( MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    while( *p < end )\n    {\n        buf = &(cur->buf);\n        buf->tag = **p;\n\n        if( ( ret = mbedtls_asn1_get_tag( p, end, &buf->len, tag ) ) != 0 )\n            return( ret );\n\n        buf->p = *p;\n        *p += buf->len;\n\n        /* Allocate and assign next pointer */\n        if( *p < end )\n        {\n            cur->next = (mbedtls_asn1_sequence*)mbedtls_calloc( 1,\n                                            sizeof( mbedtls_asn1_sequence ) );\n\n            if( cur->next == NULL )\n                return( MBEDTLS_ERR_ASN1_ALLOC_FAILED );\n\n            cur = cur->next;\n        }\n    }\n\n    /* Set final sequence entry's next pointer to NULL */\n    cur->next = NULL;\n\n    if( *p != end )\n        return( MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    return( 0 );\n}\n\nint mbedtls_asn1_get_alg( unsigned char **p,\n                  const unsigned char *end,\n                  mbedtls_asn1_buf *alg, mbedtls_asn1_buf *params )\n{\n    int ret;\n    size_t len;\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n        return( ret );\n\n    if( ( end - *p ) < 1 )\n        return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n    alg->tag = **p;\n    end = *p + len;\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &alg->len, MBEDTLS_ASN1_OID ) ) != 0 )\n        return( ret );\n\n    alg->p = *p;\n    *p += alg->len;\n\n    if( *p == end )\n    {\n        mbedtls_platform_zeroize( params, sizeof(mbedtls_asn1_buf) );\n        return( 0 );\n    }\n\n    params->tag = **p;\n    (*p)++;\n\n    if( ( ret = mbedtls_asn1_get_len( p, end, &params->len ) ) != 0 )\n        return( ret );\n\n    params->p = *p;\n    *p += params->len;\n\n    if( *p != end )\n        return( MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    return( 0 );\n}\n\nint mbedtls_asn1_get_alg_null( unsigned char **p,\n                       const unsigned char *end,\n                       mbedtls_asn1_buf *alg )\n{\n    int ret;\n    mbedtls_asn1_buf params;\n\n    memset( &params, 0, sizeof(mbedtls_asn1_buf) );\n\n    if( ( ret = mbedtls_asn1_get_alg( p, end, alg, &params ) ) != 0 )\n        return( ret );\n\n    if( ( params.tag != MBEDTLS_ASN1_NULL && params.tag != 0 ) || params.len != 0 )\n        return( MBEDTLS_ERR_ASN1_INVALID_DATA );\n\n    return( 0 );\n}\n\nvoid mbedtls_asn1_free_named_data( mbedtls_asn1_named_data *cur )\n{\n    if( cur == NULL )\n        return;\n\n    mbedtls_free( cur->oid.p );\n    mbedtls_free( cur->val.p );\n\n    mbedtls_platform_zeroize( cur, sizeof( mbedtls_asn1_named_data ) );\n}\n\nvoid mbedtls_asn1_free_named_data_list( mbedtls_asn1_named_data **head )\n{\n    mbedtls_asn1_named_data *cur;\n\n    while( ( cur = *head ) != NULL )\n    {\n        *head = cur->next;\n        mbedtls_asn1_free_named_data( cur );\n        mbedtls_free( cur );\n    }\n}\n\nmbedtls_asn1_named_data *mbedtls_asn1_find_named_data( mbedtls_asn1_named_data *list,\n                                       const char *oid, size_t len )\n{\n    while( list != NULL )\n    {\n        if( list->oid.len == len &&\n            memcmp( list->oid.p, oid, len ) == 0 )\n        {\n            break;\n        }\n\n        list = list->next;\n    }\n\n    return( list );\n}\n\n#endif /* MBEDTLS_ASN1_PARSE_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/asn1write.c",
    "content": "/*\n * ASN.1 buffer writing functionality\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_ASN1_WRITE_C)\n\n#include \"mbedtls/asn1write.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc    calloc\n#define mbedtls_free       free\n#endif\n\nint mbedtls_asn1_write_len( unsigned char **p, unsigned char *start, size_t len )\n{\n    if( len < 0x80 )\n    {\n        if( *p - start < 1 )\n            return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n        *--(*p) = (unsigned char) len;\n        return( 1 );\n    }\n\n    if( len <= 0xFF )\n    {\n        if( *p - start < 2 )\n            return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n        *--(*p) = (unsigned char) len;\n        *--(*p) = 0x81;\n        return( 2 );\n    }\n\n    if( len <= 0xFFFF )\n    {\n        if( *p - start < 3 )\n            return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n        *--(*p) = ( len       ) & 0xFF;\n        *--(*p) = ( len >>  8 ) & 0xFF;\n        *--(*p) = 0x82;\n        return( 3 );\n    }\n\n    if( len <= 0xFFFFFF )\n    {\n        if( *p - start < 4 )\n            return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n        *--(*p) = ( len       ) & 0xFF;\n        *--(*p) = ( len >>  8 ) & 0xFF;\n        *--(*p) = ( len >> 16 ) & 0xFF;\n        *--(*p) = 0x83;\n        return( 4 );\n    }\n\n#if SIZE_MAX > 0xFFFFFFFF\n    if( len <= 0xFFFFFFFF )\n#endif\n    {\n        if( *p - start < 5 )\n            return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n        *--(*p) = ( len       ) & 0xFF;\n        *--(*p) = ( len >>  8 ) & 0xFF;\n        *--(*p) = ( len >> 16 ) & 0xFF;\n        *--(*p) = ( len >> 24 ) & 0xFF;\n        *--(*p) = 0x84;\n        return( 5 );\n    }\n\n#if SIZE_MAX > 0xFFFFFFFF\n    return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );\n#endif\n}\n\nint mbedtls_asn1_write_tag( unsigned char **p, unsigned char *start, unsigned char tag )\n{\n    if( *p - start < 1 )\n        return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n    *--(*p) = tag;\n\n    return( 1 );\n}\n\nint mbedtls_asn1_write_raw_buffer( unsigned char **p, unsigned char *start,\n                           const unsigned char *buf, size_t size )\n{\n    size_t len = 0;\n\n    if( *p < start || (size_t)( *p - start ) < size )\n        return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n    len = size;\n    (*p) -= len;\n    memcpy( *p, buf, len );\n\n    return( (int) len );\n}\n\n#if defined(MBEDTLS_BIGNUM_C)\nint mbedtls_asn1_write_mpi( unsigned char **p, unsigned char *start, const mbedtls_mpi *X )\n{\n    int ret;\n    size_t len = 0;\n\n    // Write the MPI\n    //\n    len = mbedtls_mpi_size( X );\n\n    if( *p < start || (size_t)( *p - start ) < len )\n        return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n    (*p) -= len;\n    MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( X, *p, len ) );\n\n    // DER format assumes 2s complement for numbers, so the leftmost bit\n    // should be 0 for positive numbers and 1 for negative numbers.\n    //\n    if( X->s ==1 && **p & 0x80 )\n    {\n        if( *p - start < 1 )\n            return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n        *--(*p) = 0x00;\n        len += 1;\n    }\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_INTEGER ) );\n\n    ret = (int) len;\n\ncleanup:\n    return( ret );\n}\n#endif /* MBEDTLS_BIGNUM_C */\n\nint mbedtls_asn1_write_null( unsigned char **p, unsigned char *start )\n{\n    int ret;\n    size_t len = 0;\n\n    // Write NULL\n    //\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, 0) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_NULL ) );\n\n    return( (int) len );\n}\n\nint mbedtls_asn1_write_oid( unsigned char **p, unsigned char *start,\n                    const char *oid, size_t oid_len )\n{\n    int ret;\n    size_t len = 0;\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start,\n                                  (const unsigned char *) oid, oid_len ) );\n    MBEDTLS_ASN1_CHK_ADD( len , mbedtls_asn1_write_len( p, start, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len , mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_OID ) );\n\n    return( (int) len );\n}\n\nint mbedtls_asn1_write_algorithm_identifier( unsigned char **p, unsigned char *start,\n                                     const char *oid, size_t oid_len,\n                                     size_t par_len )\n{\n    int ret;\n    size_t len = 0;\n\n    if( par_len == 0 )\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_null( p, start ) );\n    else\n        len += par_len;\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_oid( p, start, oid, oid_len ) );\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start,\n                                       MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) );\n\n    return( (int) len );\n}\n\nint mbedtls_asn1_write_bool( unsigned char **p, unsigned char *start, int boolean )\n{\n    int ret;\n    size_t len = 0;\n\n    if( *p - start < 1 )\n        return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n    *--(*p) = (boolean) ? 255 : 0;\n    len++;\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_BOOLEAN ) );\n\n    return( (int) len );\n}\n\nint mbedtls_asn1_write_int( unsigned char **p, unsigned char *start, int val )\n{\n    int ret;\n    size_t len = 0;\n\n    if( *p - start < 1 )\n        return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n    len += 1;\n    *--(*p) = val;\n\n    if( val > 0 && **p & 0x80 )\n    {\n        if( *p - start < 1 )\n            return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n        *--(*p) = 0x00;\n        len += 1;\n    }\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_INTEGER ) );\n\n    return( (int) len );\n}\n\nint mbedtls_asn1_write_printable_string( unsigned char **p, unsigned char *start,\n                                 const char *text, size_t text_len )\n{\n    int ret;\n    size_t len = 0;\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start,\n                  (const unsigned char *) text, text_len ) );\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_PRINTABLE_STRING ) );\n\n    return( (int) len );\n}\n\nint mbedtls_asn1_write_ia5_string( unsigned char **p, unsigned char *start,\n                           const char *text, size_t text_len )\n{\n    int ret;\n    size_t len = 0;\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start,\n                  (const unsigned char *) text, text_len ) );\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_IA5_STRING ) );\n\n    return( (int) len );\n}\n\nint mbedtls_asn1_write_bitstring( unsigned char **p, unsigned char *start,\n                          const unsigned char *buf, size_t bits )\n{\n    int ret;\n    size_t len = 0, size;\n\n    size = ( bits / 8 ) + ( ( bits % 8 ) ? 1 : 0 );\n\n    // Calculate byte length\n    //\n    if( *p < start || (size_t)( *p - start ) < size + 1 )\n        return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n    len = size + 1;\n    (*p) -= size;\n    memcpy( *p, buf, size );\n\n    // Write unused bits\n    //\n    *--(*p) = (unsigned char) (size * 8 - bits);\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_BIT_STRING ) );\n\n    return( (int) len );\n}\n\nint mbedtls_asn1_write_octet_string( unsigned char **p, unsigned char *start,\n                             const unsigned char *buf, size_t size )\n{\n    int ret;\n    size_t len = 0;\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, buf, size ) );\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_OCTET_STRING ) );\n\n    return( (int) len );\n}\n\nmbedtls_asn1_named_data *mbedtls_asn1_store_named_data( mbedtls_asn1_named_data **head,\n                                        const char *oid, size_t oid_len,\n                                        const unsigned char *val,\n                                        size_t val_len )\n{\n    mbedtls_asn1_named_data *cur;\n\n    if( ( cur = mbedtls_asn1_find_named_data( *head, oid, oid_len ) ) == NULL )\n    {\n        // Add new entry if not present yet based on OID\n        //\n        cur = (mbedtls_asn1_named_data*)mbedtls_calloc( 1,\n                                            sizeof(mbedtls_asn1_named_data) );\n        if( cur == NULL )\n            return( NULL );\n\n        cur->oid.len = oid_len;\n        cur->oid.p = mbedtls_calloc( 1, oid_len );\n        if( cur->oid.p == NULL )\n        {\n            mbedtls_free( cur );\n            return( NULL );\n        }\n\n        memcpy( cur->oid.p, oid, oid_len );\n\n        cur->val.len = val_len;\n        cur->val.p = mbedtls_calloc( 1, val_len );\n        if( cur->val.p == NULL )\n        {\n            mbedtls_free( cur->oid.p );\n            mbedtls_free( cur );\n            return( NULL );\n        }\n\n        cur->next = *head;\n        *head = cur;\n    }\n    else if( cur->val.len < val_len )\n    {\n        /*\n         * Enlarge existing value buffer if needed\n         * Preserve old data until the allocation succeeded, to leave list in\n         * a consistent state in case allocation fails.\n         */\n        void *p = mbedtls_calloc( 1, val_len );\n        if( p == NULL )\n            return( NULL );\n\n        mbedtls_free( cur->val.p );\n        cur->val.p = p;\n        cur->val.len = val_len;\n    }\n\n    if( val != NULL )\n        memcpy( cur->val.p, val, val_len );\n\n    return( cur );\n}\n#endif /* MBEDTLS_ASN1_WRITE_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/base64.c",
    "content": "/*\n *  RFC 1521 base64 encoding/decoding\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_BASE64_C)\n\n#include \"mbedtls/base64.h\"\n\n#include <stdint.h>\n\n#if defined(MBEDTLS_SELF_TEST)\n#include <string.h>\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\nstatic const unsigned char base64_enc_map[64] =\n{\n    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',\n    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',\n    'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',\n    'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',\n    'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',\n    'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',\n    '8', '9', '+', '/'\n};\n\nstatic const unsigned char base64_dec_map[128] =\n{\n    127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n    127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n    127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n    127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n    127, 127, 127,  62, 127, 127, 127,  63,  52,  53,\n     54,  55,  56,  57,  58,  59,  60,  61, 127, 127,\n    127,  64, 127, 127, 127,   0,   1,   2,   3,   4,\n      5,   6,   7,   8,   9,  10,  11,  12,  13,  14,\n     15,  16,  17,  18,  19,  20,  21,  22,  23,  24,\n     25, 127, 127, 127, 127, 127, 127,  26,  27,  28,\n     29,  30,  31,  32,  33,  34,  35,  36,  37,  38,\n     39,  40,  41,  42,  43,  44,  45,  46,  47,  48,\n     49,  50,  51, 127, 127, 127, 127, 127\n};\n\n#define BASE64_SIZE_T_MAX   ( (size_t) -1 ) /* SIZE_T_MAX is not standard */\n\n/*\n * Encode a buffer into base64 format\n */\nint mbedtls_base64_encode( unsigned char *dst, size_t dlen, size_t *olen,\n                   const unsigned char *src, size_t slen )\n{\n    size_t i, n;\n    int C1, C2, C3;\n    unsigned char *p;\n\n    if( slen == 0 )\n    {\n        *olen = 0;\n        return( 0 );\n    }\n\n    n = slen / 3 + ( slen % 3 != 0 );\n\n    if( n > ( BASE64_SIZE_T_MAX - 1 ) / 4 )\n    {\n        *olen = BASE64_SIZE_T_MAX;\n        return( MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL );\n    }\n\n    n *= 4;\n\n    if( ( dlen < n + 1 ) || ( NULL == dst ) )\n    {\n        *olen = n + 1;\n        return( MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL );\n    }\n\n    n = ( slen / 3 ) * 3;\n\n    for( i = 0, p = dst; i < n; i += 3 )\n    {\n        C1 = *src++;\n        C2 = *src++;\n        C3 = *src++;\n\n        *p++ = base64_enc_map[(C1 >> 2) & 0x3F];\n        *p++ = base64_enc_map[(((C1 &  3) << 4) + (C2 >> 4)) & 0x3F];\n        *p++ = base64_enc_map[(((C2 & 15) << 2) + (C3 >> 6)) & 0x3F];\n        *p++ = base64_enc_map[C3 & 0x3F];\n    }\n\n    if( i < slen )\n    {\n        C1 = *src++;\n        C2 = ( ( i + 1 ) < slen ) ? *src++ : 0;\n\n        *p++ = base64_enc_map[(C1 >> 2) & 0x3F];\n        *p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F];\n\n        if( ( i + 1 ) < slen )\n             *p++ = base64_enc_map[((C2 & 15) << 2) & 0x3F];\n        else *p++ = '=';\n\n        *p++ = '=';\n    }\n\n    *olen = p - dst;\n    *p = 0;\n\n    return( 0 );\n}\n\n/*\n * Decode a base64-formatted buffer\n */\nint mbedtls_base64_decode( unsigned char *dst, size_t dlen, size_t *olen,\n                   const unsigned char *src, size_t slen )\n{\n    size_t i, n;\n    uint32_t j, x;\n    unsigned char *p;\n\n    /* First pass: check for validity and get output length */\n    for( i = n = j = 0; i < slen; i++ )\n    {\n        /* Skip spaces before checking for EOL */\n        x = 0;\n        while( i < slen && src[i] == ' ' )\n        {\n            ++i;\n            ++x;\n        }\n\n        /* Spaces at end of buffer are OK */\n        if( i == slen )\n            break;\n\n        if( ( slen - i ) >= 2 &&\n            src[i] == '\\r' && src[i + 1] == '\\n' )\n            continue;\n\n        if( src[i] == '\\n' )\n            continue;\n\n        /* Space inside a line is an error */\n        if( x != 0 )\n            return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );\n\n        if( src[i] == '=' && ++j > 2 )\n            return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );\n\n        if( src[i] > 127 || base64_dec_map[src[i]] == 127 )\n            return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );\n\n        if( base64_dec_map[src[i]] < 64 && j != 0 )\n            return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );\n\n        n++;\n    }\n\n    if( n == 0 )\n    {\n        *olen = 0;\n        return( 0 );\n    }\n\n    /* The following expression is to calculate the following formula without\n     * risk of integer overflow in n:\n     *     n = ( ( n * 6 ) + 7 ) >> 3;\n     */\n    n = ( 6 * ( n >> 3 ) ) + ( ( 6 * ( n & 0x7 ) + 7 ) >> 3 );\n    n -= j;\n\n    if( dst == NULL || dlen < n )\n    {\n        *olen = n;\n        return( MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL );\n    }\n\n   for( j = 3, n = x = 0, p = dst; i > 0; i--, src++ )\n   {\n        if( *src == '\\r' || *src == '\\n' || *src == ' ' )\n            continue;\n\n        j -= ( base64_dec_map[*src] == 64 );\n        x  = ( x << 6 ) | ( base64_dec_map[*src] & 0x3F );\n\n        if( ++n == 4 )\n        {\n            n = 0;\n            if( j > 0 ) *p++ = (unsigned char)( x >> 16 );\n            if( j > 1 ) *p++ = (unsigned char)( x >>  8 );\n            if( j > 2 ) *p++ = (unsigned char)( x       );\n        }\n    }\n\n    *olen = p - dst;\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_SELF_TEST)\n\nstatic const unsigned char base64_test_dec[64] =\n{\n    0x24, 0x48, 0x6E, 0x56, 0x87, 0x62, 0x5A, 0xBD,\n    0xBF, 0x17, 0xD9, 0xA2, 0xC4, 0x17, 0x1A, 0x01,\n    0x94, 0xED, 0x8F, 0x1E, 0x11, 0xB3, 0xD7, 0x09,\n    0x0C, 0xB6, 0xE9, 0x10, 0x6F, 0x22, 0xEE, 0x13,\n    0xCA, 0xB3, 0x07, 0x05, 0x76, 0xC9, 0xFA, 0x31,\n    0x6C, 0x08, 0x34, 0xFF, 0x8D, 0xC2, 0x6C, 0x38,\n    0x00, 0x43, 0xE9, 0x54, 0x97, 0xAF, 0x50, 0x4B,\n    0xD1, 0x41, 0xBA, 0x95, 0x31, 0x5A, 0x0B, 0x97\n};\n\nstatic const unsigned char base64_test_enc[] =\n    \"JEhuVodiWr2/F9mixBcaAZTtjx4Rs9cJDLbpEG8i7hPK\"\n    \"swcFdsn6MWwINP+Nwmw4AEPpVJevUEvRQbqVMVoLlw==\";\n\n/*\n * Checkup routine\n */\nint mbedtls_base64_self_test( int verbose )\n{\n    size_t len;\n    const unsigned char *src;\n    unsigned char buffer[128];\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  Base64 encoding test: \" );\n\n    src = base64_test_dec;\n\n    if( mbedtls_base64_encode( buffer, sizeof( buffer ), &len, src, 64 ) != 0 ||\n         memcmp( base64_test_enc, buffer, 88 ) != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        return( 1 );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n  Base64 decoding test: \" );\n\n    src = base64_test_enc;\n\n    if( mbedtls_base64_decode( buffer, sizeof( buffer ), &len, src, 88 ) != 0 ||\n         memcmp( base64_test_dec, buffer, 64 ) != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        return( 1 );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\\n\" );\n\n    return( 0 );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_BASE64_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/bignum.c",
    "content": "/*\n *  Multi-precision integer library\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n/*\n *  The following sources were referenced in the design of this Multi-precision\n *  Integer library:\n *\n *  [1] Handbook of Applied Cryptography - 1997\n *      Menezes, van Oorschot and Vanstone\n *\n *  [2] Multi-Precision Math\n *      Tom St Denis\n *      https://github.com/libtom/libtommath/blob/develop/tommath.pdf\n *\n *  [3] GNU Multi-Precision Arithmetic Library\n *      https://gmplib.org/manual/index.html\n *\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_BIGNUM_C)\n\n#include \"mbedtls/bignum.h\"\n#include \"mbedtls/bn_mul.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#include <stdlib.h>\n#define mbedtls_printf     printf\n#define mbedtls_calloc    calloc\n#define mbedtls_free       free\n#endif\n\n#define ciL    (sizeof(mbedtls_mpi_uint))         /* chars in limb  */\n#define biL    (ciL << 3)               /* bits  in limb  */\n#define biH    (ciL << 2)               /* half limb size */\n\n#define MPI_SIZE_T_MAX  ( (size_t) -1 ) /* SIZE_T_MAX is not standard */\n\n/*\n * Convert between bits/chars and number of limbs\n * Divide first in order to avoid potential overflows\n */\n#define BITS_TO_LIMBS(i)  ( (i) / biL + ( (i) % biL != 0 ) )\n#define CHARS_TO_LIMBS(i) ( (i) / ciL + ( (i) % ciL != 0 ) )\n\n/* Implementation that should never be optimized out by the compiler */\nstatic void mbedtls_mpi_zeroize( mbedtls_mpi_uint *v, size_t n )\n{\n    mbedtls_platform_zeroize( v, ciL * n );\n}\n\n/*\n * Initialize one MPI\n */\nvoid mbedtls_mpi_init( mbedtls_mpi *X )\n{\n    if( X == NULL )\n        return;\n\n    X->s = 1;\n    X->n = 0;\n    X->p = NULL;\n}\n\n/*\n * Unallocate one MPI\n */\nvoid mbedtls_mpi_free( mbedtls_mpi *X )\n{\n    if( X == NULL )\n        return;\n\n    if( X->p != NULL )\n    {\n        mbedtls_mpi_zeroize( X->p, X->n );\n        mbedtls_free( X->p );\n    }\n\n    X->s = 1;\n    X->n = 0;\n    X->p = NULL;\n}\n\n/*\n * Enlarge to the specified number of limbs\n */\nint mbedtls_mpi_grow( mbedtls_mpi *X, size_t nblimbs )\n{\n    mbedtls_mpi_uint *p;\n\n    if( nblimbs > MBEDTLS_MPI_MAX_LIMBS )\n        return( MBEDTLS_ERR_MPI_ALLOC_FAILED );\n\n    if( X->n < nblimbs )\n    {\n        if( ( p = (mbedtls_mpi_uint*)mbedtls_calloc( nblimbs, ciL ) ) == NULL )\n            return( MBEDTLS_ERR_MPI_ALLOC_FAILED );\n\n        if( X->p != NULL )\n        {\n            memcpy( p, X->p, X->n * ciL );\n            mbedtls_mpi_zeroize( X->p, X->n );\n            mbedtls_free( X->p );\n        }\n\n        X->n = nblimbs;\n        X->p = p;\n    }\n\n    return( 0 );\n}\n\n/*\n * Resize down as much as possible,\n * while keeping at least the specified number of limbs\n */\nint mbedtls_mpi_shrink( mbedtls_mpi *X, size_t nblimbs )\n{\n    mbedtls_mpi_uint *p;\n    size_t i;\n\n    /* Actually resize up in this case */\n    if( X->n <= nblimbs )\n        return( mbedtls_mpi_grow( X, nblimbs ) );\n\n    for( i = X->n - 1; i > 0; i-- )\n        if( X->p[i] != 0 )\n            break;\n    i++;\n\n    if( i < nblimbs )\n        i = nblimbs;\n\n    if( ( p = (mbedtls_mpi_uint*)mbedtls_calloc( i, ciL ) ) == NULL )\n        return( MBEDTLS_ERR_MPI_ALLOC_FAILED );\n\n    if( X->p != NULL )\n    {\n        memcpy( p, X->p, i * ciL );\n        mbedtls_mpi_zeroize( X->p, X->n );\n        mbedtls_free( X->p );\n    }\n\n    X->n = i;\n    X->p = p;\n\n    return( 0 );\n}\n\n/*\n * Copy the contents of Y into X\n */\nint mbedtls_mpi_copy( mbedtls_mpi *X, const mbedtls_mpi *Y )\n{\n    int ret = 0;\n    size_t i;\n\n    if( X == Y )\n        return( 0 );\n\n    if( Y->p == NULL )\n    {\n        mbedtls_mpi_free( X );\n        return( 0 );\n    }\n\n    for( i = Y->n - 1; i > 0; i-- )\n        if( Y->p[i] != 0 )\n            break;\n    i++;\n\n    X->s = Y->s;\n\n    if( X->n < i )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i ) );\n    }\n    else\n    {\n        memset( X->p + i, 0, ( X->n - i ) * ciL );\n    }\n\n    memcpy( X->p, Y->p, i * ciL );\n\ncleanup:\n\n    return( ret );\n}\n\n/*\n * Swap the contents of X and Y\n */\nvoid mbedtls_mpi_swap( mbedtls_mpi *X, mbedtls_mpi *Y )\n{\n    mbedtls_mpi T;\n\n    memcpy( &T,  X, sizeof( mbedtls_mpi ) );\n    memcpy(  X,  Y, sizeof( mbedtls_mpi ) );\n    memcpy(  Y, &T, sizeof( mbedtls_mpi ) );\n}\n\n/*\n * Conditionally assign X = Y, without leaking information\n * about whether the assignment was made or not.\n * (Leaking information about the respective sizes of X and Y is ok however.)\n */\nint mbedtls_mpi_safe_cond_assign( mbedtls_mpi *X, const mbedtls_mpi *Y, unsigned char assign )\n{\n    int ret = 0;\n    size_t i;\n\n    /* make sure assign is 0 or 1 in a time-constant manner */\n    assign = (assign | (unsigned char)-assign) >> 7;\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );\n\n    X->s = X->s * ( 1 - assign ) + Y->s * assign;\n\n    for( i = 0; i < Y->n; i++ )\n        X->p[i] = X->p[i] * ( 1 - assign ) + Y->p[i] * assign;\n\n    for( ; i < X->n; i++ )\n        X->p[i] *= ( 1 - assign );\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Conditionally swap X and Y, without leaking information\n * about whether the swap was made or not.\n * Here it is not ok to simply swap the pointers, which whould lead to\n * different memory access patterns when X and Y are used afterwards.\n */\nint mbedtls_mpi_safe_cond_swap( mbedtls_mpi *X, mbedtls_mpi *Y, unsigned char swap )\n{\n    int ret, s;\n    size_t i;\n    mbedtls_mpi_uint tmp;\n\n    if( X == Y )\n        return( 0 );\n\n    /* make sure swap is 0 or 1 in a time-constant manner */\n    swap = (swap | (unsigned char)-swap) >> 7;\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_grow( Y, X->n ) );\n\n    s = X->s;\n    X->s = X->s * ( 1 - swap ) + Y->s * swap;\n    Y->s = Y->s * ( 1 - swap ) +    s * swap;\n\n\n    for( i = 0; i < X->n; i++ )\n    {\n        tmp = X->p[i];\n        X->p[i] = X->p[i] * ( 1 - swap ) + Y->p[i] * swap;\n        Y->p[i] = Y->p[i] * ( 1 - swap ) +     tmp * swap;\n    }\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Set value from integer\n */\nint mbedtls_mpi_lset( mbedtls_mpi *X, mbedtls_mpi_sint z )\n{\n    int ret;\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, 1 ) );\n    memset( X->p, 0, X->n * ciL );\n\n    X->p[0] = ( z < 0 ) ? -z : z;\n    X->s    = ( z < 0 ) ? -1 : 1;\n\ncleanup:\n\n    return( ret );\n}\n\n/*\n * Get a specific bit\n */\nint mbedtls_mpi_get_bit( const mbedtls_mpi *X, size_t pos )\n{\n    if( X->n * biL <= pos )\n        return( 0 );\n\n    return( ( X->p[pos / biL] >> ( pos % biL ) ) & 0x01 );\n}\n\n/*\n * Set a bit to a specific value of 0 or 1\n */\nint mbedtls_mpi_set_bit( mbedtls_mpi *X, size_t pos, unsigned char val )\n{\n    int ret = 0;\n    size_t off = pos / biL;\n    size_t idx = pos % biL;\n\n    if( val != 0 && val != 1 )\n        return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );\n\n    if( X->n * biL <= pos )\n    {\n        if( val == 0 )\n            return( 0 );\n\n        MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, off + 1 ) );\n    }\n\n    X->p[off] &= ~( (mbedtls_mpi_uint) 0x01 << idx );\n    X->p[off] |= (mbedtls_mpi_uint) val << idx;\n\ncleanup:\n\n    return( ret );\n}\n\n/*\n * Return the number of less significant zero-bits\n */\nsize_t mbedtls_mpi_lsb( const mbedtls_mpi *X )\n{\n    size_t i, j, count = 0;\n\n    for( i = 0; i < X->n; i++ )\n        for( j = 0; j < biL; j++, count++ )\n            if( ( ( X->p[i] >> j ) & 1 ) != 0 )\n                return( count );\n\n    return( 0 );\n}\n\n/*\n * Count leading zero bits in a given integer\n */\nstatic size_t mbedtls_clz( const mbedtls_mpi_uint x )\n{\n    size_t j;\n    mbedtls_mpi_uint mask = (mbedtls_mpi_uint) 1 << (biL - 1);\n\n    for( j = 0; j < biL; j++ )\n    {\n        if( x & mask ) break;\n\n        mask >>= 1;\n    }\n\n    return j;\n}\n\n/*\n * Return the number of bits\n */\nsize_t mbedtls_mpi_bitlen( const mbedtls_mpi *X )\n{\n    size_t i, j;\n\n    if( X->n == 0 )\n        return( 0 );\n\n    for( i = X->n - 1; i > 0; i-- )\n        if( X->p[i] != 0 )\n            break;\n\n    j = biL - mbedtls_clz( X->p[i] );\n\n    return( ( i * biL ) + j );\n}\n\n/*\n * Return the total size in bytes\n */\nsize_t mbedtls_mpi_size( const mbedtls_mpi *X )\n{\n    return( ( mbedtls_mpi_bitlen( X ) + 7 ) >> 3 );\n}\n\n/*\n * Convert an ASCII character to digit value\n */\nstatic int mpi_get_digit( mbedtls_mpi_uint *d, int radix, char c )\n{\n    *d = 255;\n\n    if( c >= 0x30 && c <= 0x39 ) *d = c - 0x30;\n    if( c >= 0x41 && c <= 0x46 ) *d = c - 0x37;\n    if( c >= 0x61 && c <= 0x66 ) *d = c - 0x57;\n\n    if( *d >= (mbedtls_mpi_uint) radix )\n        return( MBEDTLS_ERR_MPI_INVALID_CHARACTER );\n\n    return( 0 );\n}\n\n/*\n * Import from an ASCII string\n */\nint mbedtls_mpi_read_string( mbedtls_mpi *X, int radix, const char *s )\n{\n    int ret;\n    size_t i, j, slen, n;\n    mbedtls_mpi_uint d;\n    mbedtls_mpi T;\n\n    if( radix < 2 || radix > 16 )\n        return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );\n\n    mbedtls_mpi_init( &T );\n\n    slen = strlen( s );\n\n    if( radix == 16 )\n    {\n        if( slen > MPI_SIZE_T_MAX >> 2 )\n            return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );\n\n        n = BITS_TO_LIMBS( slen << 2 );\n\n        MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, n ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );\n\n        for( i = slen, j = 0; i > 0; i--, j++ )\n        {\n            if( i == 1 && s[i - 1] == '-' )\n            {\n                X->s = -1;\n                break;\n            }\n\n            MBEDTLS_MPI_CHK( mpi_get_digit( &d, radix, s[i - 1] ) );\n            X->p[j / ( 2 * ciL )] |= d << ( ( j % ( 2 * ciL ) ) << 2 );\n        }\n    }\n    else\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );\n\n        for( i = 0; i < slen; i++ )\n        {\n            if( i == 0 && s[i] == '-' )\n            {\n                X->s = -1;\n                continue;\n            }\n\n            MBEDTLS_MPI_CHK( mpi_get_digit( &d, radix, s[i] ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &T, X, radix ) );\n\n            if( X->s == 1 )\n            {\n                MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, &T, d ) );\n            }\n            else\n            {\n                MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( X, &T, d ) );\n            }\n        }\n    }\n\ncleanup:\n\n    mbedtls_mpi_free( &T );\n\n    return( ret );\n}\n\n/*\n * Helper to write the digits high-order first\n */\nstatic int mpi_write_hlp( mbedtls_mpi *X, int radix, char **p )\n{\n    int ret;\n    mbedtls_mpi_uint r;\n\n    if( radix < 2 || radix > 16 )\n        return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, radix ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_div_int( X, NULL, X, radix ) );\n\n    if( mbedtls_mpi_cmp_int( X, 0 ) != 0 )\n        MBEDTLS_MPI_CHK( mpi_write_hlp( X, radix, p ) );\n\n    if( r < 10 )\n        *(*p)++ = (char)( r + 0x30 );\n    else\n        *(*p)++ = (char)( r + 0x37 );\n\ncleanup:\n\n    return( ret );\n}\n\n/*\n * Export into an ASCII string\n */\nint mbedtls_mpi_write_string( const mbedtls_mpi *X, int radix,\n                              char *buf, size_t buflen, size_t *olen )\n{\n    int ret = 0;\n    size_t n;\n    char *p;\n    mbedtls_mpi T;\n\n    if( radix < 2 || radix > 16 )\n        return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );\n\n    n = mbedtls_mpi_bitlen( X );\n    if( radix >=  4 ) n >>= 1;\n    if( radix >= 16 ) n >>= 1;\n    /*\n     * Round up the buffer length to an even value to ensure that there is\n     * enough room for hexadecimal values that can be represented in an odd\n     * number of digits.\n     */\n    n += 3 + ( ( n + 1 ) & 1 );\n\n    if( buflen < n )\n    {\n        *olen = n;\n        return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );\n    }\n\n    p = buf;\n    mbedtls_mpi_init( &T );\n\n    if( X->s == -1 )\n        *p++ = '-';\n\n    if( radix == 16 )\n    {\n        int c;\n        size_t i, j, k;\n\n        for( i = X->n, k = 0; i > 0; i-- )\n        {\n            for( j = ciL; j > 0; j-- )\n            {\n                c = ( X->p[i - 1] >> ( ( j - 1 ) << 3) ) & 0xFF;\n\n                if( c == 0 && k == 0 && ( i + j ) != 2 )\n                    continue;\n\n                *(p++) = \"0123456789ABCDEF\" [c / 16];\n                *(p++) = \"0123456789ABCDEF\" [c % 16];\n                k = 1;\n            }\n        }\n    }\n    else\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &T, X ) );\n\n        if( T.s == -1 )\n            T.s = 1;\n\n        MBEDTLS_MPI_CHK( mpi_write_hlp( &T, radix, &p ) );\n    }\n\n    *p++ = '\\0';\n    *olen = p - buf;\n\ncleanup:\n\n    mbedtls_mpi_free( &T );\n\n    return( ret );\n}\n\n#if defined(MBEDTLS_FS_IO)\n/*\n * Read X from an opened file\n */\nint mbedtls_mpi_read_file( mbedtls_mpi *X, int radix, FILE *fin )\n{\n    mbedtls_mpi_uint d;\n    size_t slen;\n    char *p;\n    /*\n     * Buffer should have space for (short) label and decimal formatted MPI,\n     * newline characters and '\\0'\n     */\n    char s[ MBEDTLS_MPI_RW_BUFFER_SIZE ];\n\n    memset( s, 0, sizeof( s ) );\n    if( fgets( s, sizeof( s ) - 1, fin ) == NULL )\n        return( MBEDTLS_ERR_MPI_FILE_IO_ERROR );\n\n    slen = strlen( s );\n    if( slen == sizeof( s ) - 2 )\n        return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );\n\n    if( slen > 0 && s[slen - 1] == '\\n' ) { slen--; s[slen] = '\\0'; }\n    if( slen > 0 && s[slen - 1] == '\\r' ) { slen--; s[slen] = '\\0'; }\n\n    p = s + slen;\n    while( p-- > s )\n        if( mpi_get_digit( &d, radix, *p ) != 0 )\n            break;\n\n    return( mbedtls_mpi_read_string( X, radix, p + 1 ) );\n}\n\n/*\n * Write X into an opened file (or stdout if fout == NULL)\n */\nint mbedtls_mpi_write_file( const char *p, const mbedtls_mpi *X, int radix, FILE *fout )\n{\n    int ret;\n    size_t n, slen, plen;\n    /*\n     * Buffer should have space for (short) label and decimal formatted MPI,\n     * newline characters and '\\0'\n     */\n    char s[ MBEDTLS_MPI_RW_BUFFER_SIZE ];\n\n    memset( s, 0, sizeof( s ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_write_string( X, radix, s, sizeof( s ) - 2, &n ) );\n\n    if( p == NULL ) p = \"\";\n\n    plen = strlen( p );\n    slen = strlen( s );\n    s[slen++] = '\\r';\n    s[slen++] = '\\n';\n\n    if( fout != NULL )\n    {\n        if( fwrite( p, 1, plen, fout ) != plen ||\n            fwrite( s, 1, slen, fout ) != slen )\n            return( MBEDTLS_ERR_MPI_FILE_IO_ERROR );\n    }\n    else\n        mbedtls_printf( \"%s%s\", p, s );\n\ncleanup:\n\n    return( ret );\n}\n#endif /* MBEDTLS_FS_IO */\n\n/*\n * Import X from unsigned binary data, big endian\n */\nint mbedtls_mpi_read_binary( mbedtls_mpi *X, const unsigned char *buf, size_t buflen )\n{\n    int ret;\n    size_t i, j;\n    size_t const limbs = CHARS_TO_LIMBS( buflen );\n\n    /* Ensure that target MPI has exactly the necessary number of limbs */\n    if( X->n != limbs )\n    {\n        mbedtls_mpi_free( X );\n        mbedtls_mpi_init( X );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, limbs ) );\n    }\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );\n\n    for( i = buflen, j = 0; i > 0; i--, j++ )\n        X->p[j / ciL] |= ((mbedtls_mpi_uint) buf[i - 1]) << ((j % ciL) << 3);\n\ncleanup:\n\n    return( ret );\n}\n\n/*\n * Export X into unsigned binary data, big endian\n */\nint mbedtls_mpi_write_binary( const mbedtls_mpi *X, unsigned char *buf, size_t buflen )\n{\n    size_t i, j, n;\n\n    n = mbedtls_mpi_size( X );\n\n    if( buflen < n )\n        return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );\n\n    memset( buf, 0, buflen );\n\n    for( i = buflen - 1, j = 0; n > 0; i--, j++, n-- )\n        buf[i] = (unsigned char)( X->p[j / ciL] >> ((j % ciL) << 3) );\n\n    return( 0 );\n}\n\n/*\n * Left-shift: X <<= count\n */\nint mbedtls_mpi_shift_l( mbedtls_mpi *X, size_t count )\n{\n    int ret;\n    size_t i, v0, t1;\n    mbedtls_mpi_uint r0 = 0, r1;\n\n    v0 = count / (biL    );\n    t1 = count & (biL - 1);\n\n    i = mbedtls_mpi_bitlen( X ) + count;\n\n    if( X->n * biL < i )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, BITS_TO_LIMBS( i ) ) );\n\n    ret = 0;\n\n    /*\n     * shift by count / limb_size\n     */\n    if( v0 > 0 )\n    {\n        for( i = X->n; i > v0; i-- )\n            X->p[i - 1] = X->p[i - v0 - 1];\n\n        for( ; i > 0; i-- )\n            X->p[i - 1] = 0;\n    }\n\n    /*\n     * shift by count % limb_size\n     */\n    if( t1 > 0 )\n    {\n        for( i = v0; i < X->n; i++ )\n        {\n            r1 = X->p[i] >> (biL - t1);\n            X->p[i] <<= t1;\n            X->p[i] |= r0;\n            r0 = r1;\n        }\n    }\n\ncleanup:\n\n    return( ret );\n}\n\n/*\n * Right-shift: X >>= count\n */\nint mbedtls_mpi_shift_r( mbedtls_mpi *X, size_t count )\n{\n    size_t i, v0, v1;\n    mbedtls_mpi_uint r0 = 0, r1;\n\n    v0 = count /  biL;\n    v1 = count & (biL - 1);\n\n    if( v0 > X->n || ( v0 == X->n && v1 > 0 ) )\n        return mbedtls_mpi_lset( X, 0 );\n\n    /*\n     * shift by count / limb_size\n     */\n    if( v0 > 0 )\n    {\n        for( i = 0; i < X->n - v0; i++ )\n            X->p[i] = X->p[i + v0];\n\n        for( ; i < X->n; i++ )\n            X->p[i] = 0;\n    }\n\n    /*\n     * shift by count % limb_size\n     */\n    if( v1 > 0 )\n    {\n        for( i = X->n; i > 0; i-- )\n        {\n            r1 = X->p[i - 1] << (biL - v1);\n            X->p[i - 1] >>= v1;\n            X->p[i - 1] |= r0;\n            r0 = r1;\n        }\n    }\n\n    return( 0 );\n}\n\n/*\n * Compare unsigned values\n */\nint mbedtls_mpi_cmp_abs( const mbedtls_mpi *X, const mbedtls_mpi *Y )\n{\n    size_t i, j;\n\n    for( i = X->n; i > 0; i-- )\n        if( X->p[i - 1] != 0 )\n            break;\n\n    for( j = Y->n; j > 0; j-- )\n        if( Y->p[j - 1] != 0 )\n            break;\n\n    if( i == 0 && j == 0 )\n        return( 0 );\n\n    if( i > j ) return(  1 );\n    if( j > i ) return( -1 );\n\n    for( ; i > 0; i-- )\n    {\n        if( X->p[i - 1] > Y->p[i - 1] ) return(  1 );\n        if( X->p[i - 1] < Y->p[i - 1] ) return( -1 );\n    }\n\n    return( 0 );\n}\n\n/*\n * Compare signed values\n */\nint mbedtls_mpi_cmp_mpi( const mbedtls_mpi *X, const mbedtls_mpi *Y )\n{\n    size_t i, j;\n\n    for( i = X->n; i > 0; i-- )\n        if( X->p[i - 1] != 0 )\n            break;\n\n    for( j = Y->n; j > 0; j-- )\n        if( Y->p[j - 1] != 0 )\n            break;\n\n    if( i == 0 && j == 0 )\n        return( 0 );\n\n    if( i > j ) return(  X->s );\n    if( j > i ) return( -Y->s );\n\n    if( X->s > 0 && Y->s < 0 ) return(  1 );\n    if( Y->s > 0 && X->s < 0 ) return( -1 );\n\n    for( ; i > 0; i-- )\n    {\n        if( X->p[i - 1] > Y->p[i - 1] ) return(  X->s );\n        if( X->p[i - 1] < Y->p[i - 1] ) return( -X->s );\n    }\n\n    return( 0 );\n}\n\n/*\n * Compare signed values\n */\nint mbedtls_mpi_cmp_int( const mbedtls_mpi *X, mbedtls_mpi_sint z )\n{\n    mbedtls_mpi Y;\n    mbedtls_mpi_uint p[1];\n\n    *p  = ( z < 0 ) ? -z : z;\n    Y.s = ( z < 0 ) ? -1 : 1;\n    Y.n = 1;\n    Y.p = p;\n\n    return( mbedtls_mpi_cmp_mpi( X, &Y ) );\n}\n\n/*\n * Unsigned addition: X = |A| + |B|  (HAC 14.7)\n */\nint mbedtls_mpi_add_abs( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )\n{\n    int ret;\n    size_t i, j;\n    mbedtls_mpi_uint *o, *p, c, tmp;\n\n    if( X == B )\n    {\n        const mbedtls_mpi *T = A; A = X; B = T;\n    }\n\n    if( X != A )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, A ) );\n\n    /*\n     * X should always be positive as a result of unsigned additions.\n     */\n    X->s = 1;\n\n    for( j = B->n; j > 0; j-- )\n        if( B->p[j - 1] != 0 )\n            break;\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, j ) );\n\n    o = B->p; p = X->p; c = 0;\n\n    /*\n     * tmp is used because it might happen that p == o\n     */\n    for( i = 0; i < j; i++, o++, p++ )\n    {\n        tmp= *o;\n        *p +=  c; c  = ( *p <  c );\n        *p += tmp; c += ( *p < tmp );\n    }\n\n    while( c != 0 )\n    {\n        if( i >= X->n )\n        {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i + 1 ) );\n            p = X->p + i;\n        }\n\n        *p += c; c = ( *p < c ); i++; p++;\n    }\n\ncleanup:\n\n    return( ret );\n}\n\n/*\n * Helper for mbedtls_mpi subtraction\n */\nstatic void mpi_sub_hlp( size_t n, mbedtls_mpi_uint *s, mbedtls_mpi_uint *d )\n{\n    size_t i;\n    mbedtls_mpi_uint c, z;\n\n    for( i = c = 0; i < n; i++, s++, d++ )\n    {\n        z = ( *d <  c );     *d -=  c;\n        c = ( *d < *s ) + z; *d -= *s;\n    }\n\n    while( c != 0 )\n    {\n        z = ( *d < c ); *d -= c;\n        c = z; d++;\n    }\n}\n\n/*\n * Unsigned subtraction: X = |A| - |B|  (HAC 14.9)\n */\nint mbedtls_mpi_sub_abs( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )\n{\n    mbedtls_mpi TB;\n    int ret;\n    size_t n;\n\n    if( mbedtls_mpi_cmp_abs( A, B ) < 0 )\n        return( MBEDTLS_ERR_MPI_NEGATIVE_VALUE );\n\n    mbedtls_mpi_init( &TB );\n\n    if( X == B )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, B ) );\n        B = &TB;\n    }\n\n    if( X != A )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, A ) );\n\n    /*\n     * X should always be positive as a result of unsigned subtractions.\n     */\n    X->s = 1;\n\n    ret = 0;\n\n    for( n = B->n; n > 0; n-- )\n        if( B->p[n - 1] != 0 )\n            break;\n\n    mpi_sub_hlp( n, B->p, X->p );\n\ncleanup:\n\n    mbedtls_mpi_free( &TB );\n\n    return( ret );\n}\n\n/*\n * Signed addition: X = A + B\n */\nint mbedtls_mpi_add_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )\n{\n    int ret, s = A->s;\n\n    if( A->s * B->s < 0 )\n    {\n        if( mbedtls_mpi_cmp_abs( A, B ) >= 0 )\n        {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( X, A, B ) );\n            X->s =  s;\n        }\n        else\n        {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( X, B, A ) );\n            X->s = -s;\n        }\n    }\n    else\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( X, A, B ) );\n        X->s = s;\n    }\n\ncleanup:\n\n    return( ret );\n}\n\n/*\n * Signed subtraction: X = A - B\n */\nint mbedtls_mpi_sub_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )\n{\n    int ret, s = A->s;\n\n    if( A->s * B->s > 0 )\n    {\n        if( mbedtls_mpi_cmp_abs( A, B ) >= 0 )\n        {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( X, A, B ) );\n            X->s =  s;\n        }\n        else\n        {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( X, B, A ) );\n            X->s = -s;\n        }\n    }\n    else\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( X, A, B ) );\n        X->s = s;\n    }\n\ncleanup:\n\n    return( ret );\n}\n\n/*\n * Signed addition: X = A + b\n */\nint mbedtls_mpi_add_int( mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_sint b )\n{\n    mbedtls_mpi _B;\n    mbedtls_mpi_uint p[1];\n\n    p[0] = ( b < 0 ) ? -b : b;\n    _B.s = ( b < 0 ) ? -1 : 1;\n    _B.n = 1;\n    _B.p = p;\n\n    return( mbedtls_mpi_add_mpi( X, A, &_B ) );\n}\n\n/*\n * Signed subtraction: X = A - b\n */\nint mbedtls_mpi_sub_int( mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_sint b )\n{\n    mbedtls_mpi _B;\n    mbedtls_mpi_uint p[1];\n\n    p[0] = ( b < 0 ) ? -b : b;\n    _B.s = ( b < 0 ) ? -1 : 1;\n    _B.n = 1;\n    _B.p = p;\n\n    return( mbedtls_mpi_sub_mpi( X, A, &_B ) );\n}\n\n/*\n * Helper for mbedtls_mpi multiplication\n */\nstatic\n#if defined(__APPLE__) && defined(__arm__)\n/*\n * Apple LLVM version 4.2 (clang-425.0.24) (based on LLVM 3.2svn)\n * appears to need this to prevent bad ARM code generation at -O3.\n */\n__attribute__ ((noinline))\n#endif\nvoid mpi_mul_hlp( size_t i, mbedtls_mpi_uint *s, mbedtls_mpi_uint *d, mbedtls_mpi_uint b )\n{\n    mbedtls_mpi_uint c = 0, t = 0;\n\n#if defined(MULADDC_HUIT)\n    for( ; i >= 8; i -= 8 )\n    {\n        MULADDC_INIT\n        MULADDC_HUIT\n        MULADDC_STOP\n    }\n\n    for( ; i > 0; i-- )\n    {\n        MULADDC_INIT\n        MULADDC_CORE\n        MULADDC_STOP\n    }\n#else /* MULADDC_HUIT */\n    for( ; i >= 16; i -= 16 )\n    {\n        MULADDC_INIT\n        MULADDC_CORE   MULADDC_CORE\n        MULADDC_CORE   MULADDC_CORE\n        MULADDC_CORE   MULADDC_CORE\n        MULADDC_CORE   MULADDC_CORE\n\n        MULADDC_CORE   MULADDC_CORE\n        MULADDC_CORE   MULADDC_CORE\n        MULADDC_CORE   MULADDC_CORE\n        MULADDC_CORE   MULADDC_CORE\n        MULADDC_STOP\n    }\n\n    for( ; i >= 8; i -= 8 )\n    {\n        MULADDC_INIT\n        MULADDC_CORE   MULADDC_CORE\n        MULADDC_CORE   MULADDC_CORE\n\n        MULADDC_CORE   MULADDC_CORE\n        MULADDC_CORE   MULADDC_CORE\n        MULADDC_STOP\n    }\n\n    for( ; i > 0; i-- )\n    {\n        MULADDC_INIT\n        MULADDC_CORE\n        MULADDC_STOP\n    }\n#endif /* MULADDC_HUIT */\n\n    t++;\n\n    do {\n        *d += c; c = ( *d < c ); d++;\n    }\n    while( c != 0 );\n}\n\n/*\n * Baseline multiplication: X = A * B  (HAC 14.12)\n */\nint mbedtls_mpi_mul_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B )\n{\n    int ret;\n    size_t i, j;\n    mbedtls_mpi TA, TB;\n\n    mbedtls_mpi_init( &TA ); mbedtls_mpi_init( &TB );\n\n    if( X == A ) { MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TA, A ) ); A = &TA; }\n    if( X == B ) { MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, B ) ); B = &TB; }\n\n    for( i = A->n; i > 0; i-- )\n        if( A->p[i - 1] != 0 )\n            break;\n\n    for( j = B->n; j > 0; j-- )\n        if( B->p[j - 1] != 0 )\n            break;\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i + j ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );\n\n    for( ; j > 0; j-- )\n        mpi_mul_hlp( i, A->p, X->p + j - 1, B->p[j - 1] );\n\n    X->s = A->s * B->s;\n\ncleanup:\n\n    mbedtls_mpi_free( &TB ); mbedtls_mpi_free( &TA );\n\n    return( ret );\n}\n\n/*\n * Baseline multiplication: X = A * b\n */\nint mbedtls_mpi_mul_int( mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_uint b )\n{\n    mbedtls_mpi _B;\n    mbedtls_mpi_uint p[1];\n\n    _B.s = 1;\n    _B.n = 1;\n    _B.p = p;\n    p[0] = b;\n\n    return( mbedtls_mpi_mul_mpi( X, A, &_B ) );\n}\n\n/*\n * Unsigned integer divide - double mbedtls_mpi_uint dividend, u1/u0, and\n * mbedtls_mpi_uint divisor, d\n */\nstatic mbedtls_mpi_uint mbedtls_int_div_int( mbedtls_mpi_uint u1,\n            mbedtls_mpi_uint u0, mbedtls_mpi_uint d, mbedtls_mpi_uint *r )\n{\n#if defined(MBEDTLS_HAVE_UDBL)\n    mbedtls_t_udbl dividend, quotient;\n#else\n    const mbedtls_mpi_uint radix = (mbedtls_mpi_uint) 1 << biH;\n    const mbedtls_mpi_uint uint_halfword_mask = ( (mbedtls_mpi_uint) 1 << biH ) - 1;\n    mbedtls_mpi_uint d0, d1, q0, q1, rAX, r0, quotient;\n    mbedtls_mpi_uint u0_msw, u0_lsw;\n    size_t s;\n#endif\n\n    /*\n     * Check for overflow\n     */\n    if( 0 == d || u1 >= d )\n    {\n        if (r != NULL) *r = ~0;\n\n        return ( ~0 );\n    }\n\n#if defined(MBEDTLS_HAVE_UDBL)\n    dividend  = (mbedtls_t_udbl) u1 << biL;\n    dividend |= (mbedtls_t_udbl) u0;\n    quotient = dividend / d;\n    if( quotient > ( (mbedtls_t_udbl) 1 << biL ) - 1 )\n        quotient = ( (mbedtls_t_udbl) 1 << biL ) - 1;\n\n    if( r != NULL )\n        *r = (mbedtls_mpi_uint)( dividend - (quotient * d ) );\n\n    return (mbedtls_mpi_uint) quotient;\n#else\n\n    /*\n     * Algorithm D, Section 4.3.1 - The Art of Computer Programming\n     *   Vol. 2 - Seminumerical Algorithms, Knuth\n     */\n\n    /*\n     * Normalize the divisor, d, and dividend, u0, u1\n     */\n    s = mbedtls_clz( d );\n    d = d << s;\n\n    u1 = u1 << s;\n    u1 |= ( u0 >> ( biL - s ) ) & ( -(mbedtls_mpi_sint)s >> ( biL - 1 ) );\n    u0 =  u0 << s;\n\n    d1 = d >> biH;\n    d0 = d & uint_halfword_mask;\n\n    u0_msw = u0 >> biH;\n    u0_lsw = u0 & uint_halfword_mask;\n\n    /*\n     * Find the first quotient and remainder\n     */\n    q1 = u1 / d1;\n    r0 = u1 - d1 * q1;\n\n    while( q1 >= radix || ( q1 * d0 > radix * r0 + u0_msw ) )\n    {\n        q1 -= 1;\n        r0 += d1;\n\n        if ( r0 >= radix ) break;\n    }\n\n    rAX = ( u1 * radix ) + ( u0_msw - q1 * d );\n    q0 = rAX / d1;\n    r0 = rAX - q0 * d1;\n\n    while( q0 >= radix || ( q0 * d0 > radix * r0 + u0_lsw ) )\n    {\n        q0 -= 1;\n        r0 += d1;\n\n        if ( r0 >= radix ) break;\n    }\n\n    if (r != NULL)\n        *r = ( rAX * radix + u0_lsw - q0 * d ) >> s;\n\n    quotient = q1 * radix + q0;\n\n    return quotient;\n#endif\n}\n\n/*\n * Division by mbedtls_mpi: A = Q * B + R  (HAC 14.20)\n */\nint mbedtls_mpi_div_mpi( mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A, const mbedtls_mpi *B )\n{\n    int ret;\n    size_t i, n, t, k;\n    mbedtls_mpi X, Y, Z, T1, T2;\n\n    if( mbedtls_mpi_cmp_int( B, 0 ) == 0 )\n        return( MBEDTLS_ERR_MPI_DIVISION_BY_ZERO );\n\n    mbedtls_mpi_init( &X ); mbedtls_mpi_init( &Y ); mbedtls_mpi_init( &Z );\n    mbedtls_mpi_init( &T1 ); mbedtls_mpi_init( &T2 );\n\n    if( mbedtls_mpi_cmp_abs( A, B ) < 0 )\n    {\n        if( Q != NULL ) MBEDTLS_MPI_CHK( mbedtls_mpi_lset( Q, 0 ) );\n        if( R != NULL ) MBEDTLS_MPI_CHK( mbedtls_mpi_copy( R, A ) );\n        return( 0 );\n    }\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &X, A ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Y, B ) );\n    X.s = Y.s = 1;\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &Z, A->n + 2 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &Z,  0 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &T1, 2 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &T2, 3 ) );\n\n    k = mbedtls_mpi_bitlen( &Y ) % biL;\n    if( k < biL - 1 )\n    {\n        k = biL - 1 - k;\n        MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &X, k ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &Y, k ) );\n    }\n    else k = 0;\n\n    n = X.n - 1;\n    t = Y.n - 1;\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &Y, biL * ( n - t ) ) );\n\n    while( mbedtls_mpi_cmp_mpi( &X, &Y ) >= 0 )\n    {\n        Z.p[n - t]++;\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &X, &X, &Y ) );\n    }\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &Y, biL * ( n - t ) ) );\n\n    for( i = n; i > t ; i-- )\n    {\n        if( X.p[i] >= Y.p[t] )\n            Z.p[i - t - 1] = ~0;\n        else\n        {\n            Z.p[i - t - 1] = mbedtls_int_div_int( X.p[i], X.p[i - 1],\n                                                            Y.p[t], NULL);\n        }\n\n        Z.p[i - t - 1]++;\n        do\n        {\n            Z.p[i - t - 1]--;\n\n            MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &T1, 0 ) );\n            T1.p[0] = ( t < 1 ) ? 0 : Y.p[t - 1];\n            T1.p[1] = Y.p[t];\n            MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &T1, &T1, Z.p[i - t - 1] ) );\n\n            MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &T2, 0 ) );\n            T2.p[0] = ( i < 2 ) ? 0 : X.p[i - 2];\n            T2.p[1] = ( i < 1 ) ? 0 : X.p[i - 1];\n            T2.p[2] = X.p[i];\n        }\n        while( mbedtls_mpi_cmp_mpi( &T1, &T2 ) > 0 );\n\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &T1, &Y, Z.p[i - t - 1] ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &T1,  biL * ( i - t - 1 ) ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &X, &X, &T1 ) );\n\n        if( mbedtls_mpi_cmp_int( &X, 0 ) < 0 )\n        {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &T1, &Y ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &T1, biL * ( i - t - 1 ) ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &X, &X, &T1 ) );\n            Z.p[i - t - 1]--;\n        }\n    }\n\n    if( Q != NULL )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_copy( Q, &Z ) );\n        Q->s = A->s * B->s;\n    }\n\n    if( R != NULL )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &X, k ) );\n        X.s = A->s;\n        MBEDTLS_MPI_CHK( mbedtls_mpi_copy( R, &X ) );\n\n        if( mbedtls_mpi_cmp_int( R, 0 ) == 0 )\n            R->s = 1;\n    }\n\ncleanup:\n\n    mbedtls_mpi_free( &X ); mbedtls_mpi_free( &Y ); mbedtls_mpi_free( &Z );\n    mbedtls_mpi_free( &T1 ); mbedtls_mpi_free( &T2 );\n\n    return( ret );\n}\n\n/*\n * Division by int: A = Q * b + R\n */\nint mbedtls_mpi_div_int( mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A, mbedtls_mpi_sint b )\n{\n    mbedtls_mpi _B;\n    mbedtls_mpi_uint p[1];\n\n    p[0] = ( b < 0 ) ? -b : b;\n    _B.s = ( b < 0 ) ? -1 : 1;\n    _B.n = 1;\n    _B.p = p;\n\n    return( mbedtls_mpi_div_mpi( Q, R, A, &_B ) );\n}\n\n/*\n * Modulo: R = A mod B\n */\nint mbedtls_mpi_mod_mpi( mbedtls_mpi *R, const mbedtls_mpi *A, const mbedtls_mpi *B )\n{\n    int ret;\n\n    if( mbedtls_mpi_cmp_int( B, 0 ) < 0 )\n        return( MBEDTLS_ERR_MPI_NEGATIVE_VALUE );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( NULL, R, A, B ) );\n\n    while( mbedtls_mpi_cmp_int( R, 0 ) < 0 )\n      MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( R, R, B ) );\n\n    while( mbedtls_mpi_cmp_mpi( R, B ) >= 0 )\n      MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( R, R, B ) );\n\ncleanup:\n\n    return( ret );\n}\n\n/*\n * Modulo: r = A mod b\n */\nint mbedtls_mpi_mod_int( mbedtls_mpi_uint *r, const mbedtls_mpi *A, mbedtls_mpi_sint b )\n{\n    size_t i;\n    mbedtls_mpi_uint x, y, z;\n\n    if( b == 0 )\n        return( MBEDTLS_ERR_MPI_DIVISION_BY_ZERO );\n\n    if( b < 0 )\n        return( MBEDTLS_ERR_MPI_NEGATIVE_VALUE );\n\n    /*\n     * handle trivial cases\n     */\n    if( b == 1 )\n    {\n        *r = 0;\n        return( 0 );\n    }\n\n    if( b == 2 )\n    {\n        *r = A->p[0] & 1;\n        return( 0 );\n    }\n\n    /*\n     * general case\n     */\n    for( i = A->n, y = 0; i > 0; i-- )\n    {\n        x  = A->p[i - 1];\n        y  = ( y << biH ) | ( x >> biH );\n        z  = y / b;\n        y -= z * b;\n\n        x <<= biH;\n        y  = ( y << biH ) | ( x >> biH );\n        z  = y / b;\n        y -= z * b;\n    }\n\n    /*\n     * If A is negative, then the current y represents a negative value.\n     * Flipping it to the positive side.\n     */\n    if( A->s < 0 && y != 0 )\n        y = b - y;\n\n    *r = y;\n\n    return( 0 );\n}\n\n/*\n * Fast Montgomery initialization (thanks to Tom St Denis)\n */\nstatic void mpi_montg_init( mbedtls_mpi_uint *mm, const mbedtls_mpi *N )\n{\n    mbedtls_mpi_uint x, m0 = N->p[0];\n    unsigned int i;\n\n    x  = m0;\n    x += ( ( m0 + 2 ) & 4 ) << 1;\n\n    for( i = biL; i >= 8; i /= 2 )\n        x *= ( 2 - ( m0 * x ) );\n\n    *mm = ~x + 1;\n}\n\n/*\n * Montgomery multiplication: A = A * B * R^-1 mod N  (HAC 14.36)\n */\nstatic int mpi_montmul( mbedtls_mpi *A, const mbedtls_mpi *B, const mbedtls_mpi *N, mbedtls_mpi_uint mm,\n                         const mbedtls_mpi *T )\n{\n    size_t i, n, m;\n    mbedtls_mpi_uint u0, u1, *d;\n\n    if( T->n < N->n + 1 || T->p == NULL )\n        return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );\n\n    memset( T->p, 0, T->n * ciL );\n\n    d = T->p;\n    n = N->n;\n    m = ( B->n < n ) ? B->n : n;\n\n    for( i = 0; i < n; i++ )\n    {\n        /*\n         * T = (T + u0*B + u1*N) / 2^biL\n         */\n        u0 = A->p[i];\n        u1 = ( d[0] + u0 * B->p[0] ) * mm;\n\n        mpi_mul_hlp( m, B->p, d, u0 );\n        mpi_mul_hlp( n, N->p, d, u1 );\n\n        *d++ = u0; d[n + 1] = 0;\n    }\n\n    memcpy( A->p, d, ( n + 1 ) * ciL );\n\n    if( mbedtls_mpi_cmp_abs( A, N ) >= 0 )\n        mpi_sub_hlp( n, N->p, A->p );\n    else\n        /* prevent timing attacks */\n        mpi_sub_hlp( n, A->p, T->p );\n\n    return( 0 );\n}\n\n/*\n * Montgomery reduction: A = A * R^-1 mod N\n */\nstatic int mpi_montred( mbedtls_mpi *A, const mbedtls_mpi *N, mbedtls_mpi_uint mm, const mbedtls_mpi *T )\n{\n    mbedtls_mpi_uint z = 1;\n    mbedtls_mpi U;\n\n    U.n = U.s = (int) z;\n    U.p = &z;\n\n    return( mpi_montmul( A, &U, N, mm, T ) );\n}\n\n/*\n * Sliding-window exponentiation: X = A^E mod N  (HAC 14.85)\n */\nint mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *E, const mbedtls_mpi *N, mbedtls_mpi *_RR )\n{\n    int ret;\n    size_t wbits, wsize, one = 1;\n    size_t i, j, nblimbs;\n    size_t bufsize, nbits;\n    mbedtls_mpi_uint ei, mm, state;\n    mbedtls_mpi RR, T, W[ 2 << MBEDTLS_MPI_WINDOW_SIZE ], Apos;\n    int neg;\n\n    if( mbedtls_mpi_cmp_int( N, 0 ) <= 0 || ( N->p[0] & 1 ) == 0 )\n        return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );\n\n    if( mbedtls_mpi_cmp_int( E, 0 ) < 0 )\n        return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );\n\n    /*\n     * Init temps and window size\n     */\n    mpi_montg_init( &mm, N );\n    mbedtls_mpi_init( &RR ); mbedtls_mpi_init( &T );\n    mbedtls_mpi_init( &Apos );\n    memset( W, 0, sizeof( W ) );\n\n    i = mbedtls_mpi_bitlen( E );\n\n    wsize = ( i > 671 ) ? 6 : ( i > 239 ) ? 5 :\n            ( i >  79 ) ? 4 : ( i >  23 ) ? 3 : 1;\n\n    if( wsize > MBEDTLS_MPI_WINDOW_SIZE )\n        wsize = MBEDTLS_MPI_WINDOW_SIZE;\n\n    j = N->n + 1;\n    MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, j ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[1],  j ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &T, j * 2 ) );\n\n    /*\n     * Compensate for negative A (and correct at the end)\n     */\n    neg = ( A->s == -1 );\n    if( neg )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Apos, A ) );\n        Apos.s = 1;\n        A = &Apos;\n    }\n\n    /*\n     * If 1st call, pre-compute R^2 mod N\n     */\n    if( _RR == NULL || _RR->p == NULL )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &RR, 1 ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &RR, N->n * 2 * biL ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &RR, &RR, N ) );\n\n        if( _RR != NULL )\n            memcpy( _RR, &RR, sizeof( mbedtls_mpi ) );\n    }\n    else\n        memcpy( &RR, _RR, sizeof( mbedtls_mpi ) );\n\n    /*\n     * W[1] = A * R^2 * R^-1 mod N = A * R mod N\n     */\n    if( mbedtls_mpi_cmp_mpi( A, N ) >= 0 )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &W[1], A, N ) );\n    else\n        MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[1], A ) );\n\n    MBEDTLS_MPI_CHK( mpi_montmul( &W[1], &RR, N, mm, &T ) );\n\n    /*\n     * X = R^2 * R^-1 mod N = R mod N\n     */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, &RR ) );\n    MBEDTLS_MPI_CHK( mpi_montred( X, N, mm, &T ) );\n\n    if( wsize > 1 )\n    {\n        /*\n         * W[1 << (wsize - 1)] = W[1] ^ (wsize - 1)\n         */\n        j =  one << ( wsize - 1 );\n\n        MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[j], N->n + 1 ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[j], &W[1]    ) );\n\n        for( i = 0; i < wsize - 1; i++ )\n            MBEDTLS_MPI_CHK( mpi_montmul( &W[j], &W[j], N, mm, &T ) );\n\n        /*\n         * W[i] = W[i - 1] * W[1]\n         */\n        for( i = j + 1; i < ( one << wsize ); i++ )\n        {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[i], N->n + 1 ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[i], &W[i - 1] ) );\n\n            MBEDTLS_MPI_CHK( mpi_montmul( &W[i], &W[1], N, mm, &T ) );\n        }\n    }\n\n    nblimbs = E->n;\n    bufsize = 0;\n    nbits   = 0;\n    wbits   = 0;\n    state   = 0;\n\n    while( 1 )\n    {\n        if( bufsize == 0 )\n        {\n            if( nblimbs == 0 )\n                break;\n\n            nblimbs--;\n\n            bufsize = sizeof( mbedtls_mpi_uint ) << 3;\n        }\n\n        bufsize--;\n\n        ei = (E->p[nblimbs] >> bufsize) & 1;\n\n        /*\n         * skip leading 0s\n         */\n        if( ei == 0 && state == 0 )\n            continue;\n\n        if( ei == 0 && state == 1 )\n        {\n            /*\n             * out of window, square X\n             */\n            MBEDTLS_MPI_CHK( mpi_montmul( X, X, N, mm, &T ) );\n            continue;\n        }\n\n        /*\n         * add ei to current window\n         */\n        state = 2;\n\n        nbits++;\n        wbits |= ( ei << ( wsize - nbits ) );\n\n        if( nbits == wsize )\n        {\n            /*\n             * X = X^wsize R^-1 mod N\n             */\n            for( i = 0; i < wsize; i++ )\n                MBEDTLS_MPI_CHK( mpi_montmul( X, X, N, mm, &T ) );\n\n            /*\n             * X = X * W[wbits] R^-1 mod N\n             */\n            MBEDTLS_MPI_CHK( mpi_montmul( X, &W[wbits], N, mm, &T ) );\n\n            state--;\n            nbits = 0;\n            wbits = 0;\n        }\n    }\n\n    /*\n     * process the remaining bits\n     */\n    for( i = 0; i < nbits; i++ )\n    {\n        MBEDTLS_MPI_CHK( mpi_montmul( X, X, N, mm, &T ) );\n\n        wbits <<= 1;\n\n        if( ( wbits & ( one << wsize ) ) != 0 )\n            MBEDTLS_MPI_CHK( mpi_montmul( X, &W[1], N, mm, &T ) );\n    }\n\n    /*\n     * X = A^E * R * R^-1 mod N = A^E mod N\n     */\n    MBEDTLS_MPI_CHK( mpi_montred( X, N, mm, &T ) );\n\n    if( neg && E->n != 0 && ( E->p[0] & 1 ) != 0 )\n    {\n        X->s = -1;\n        MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( X, N, X ) );\n    }\n\ncleanup:\n\n    for( i = ( one << ( wsize - 1 ) ); i < ( one << wsize ); i++ )\n        mbedtls_mpi_free( &W[i] );\n\n    mbedtls_mpi_free( &W[1] ); mbedtls_mpi_free( &T ); mbedtls_mpi_free( &Apos );\n\n    if( _RR == NULL || _RR->p == NULL )\n        mbedtls_mpi_free( &RR );\n\n    return( ret );\n}\n\n/*\n * Greatest common divisor: G = gcd(A, B)  (HAC 14.54)\n */\nint mbedtls_mpi_gcd( mbedtls_mpi *G, const mbedtls_mpi *A, const mbedtls_mpi *B )\n{\n    int ret;\n    size_t lz, lzt;\n    mbedtls_mpi TG, TA, TB;\n\n    mbedtls_mpi_init( &TG ); mbedtls_mpi_init( &TA ); mbedtls_mpi_init( &TB );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TA, A ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, B ) );\n\n    lz = mbedtls_mpi_lsb( &TA );\n    lzt = mbedtls_mpi_lsb( &TB );\n\n    if( lzt < lz )\n        lz = lzt;\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TA, lz ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TB, lz ) );\n\n    TA.s = TB.s = 1;\n\n    while( mbedtls_mpi_cmp_int( &TA, 0 ) != 0 )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TA, mbedtls_mpi_lsb( &TA ) ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TB, mbedtls_mpi_lsb( &TB ) ) );\n\n        if( mbedtls_mpi_cmp_mpi( &TA, &TB ) >= 0 )\n        {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( &TA, &TA, &TB ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TA, 1 ) );\n        }\n        else\n        {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( &TB, &TB, &TA ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TB, 1 ) );\n        }\n    }\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &TB, lz ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( G, &TB ) );\n\ncleanup:\n\n    mbedtls_mpi_free( &TG ); mbedtls_mpi_free( &TA ); mbedtls_mpi_free( &TB );\n\n    return( ret );\n}\n\n/*\n * Fill X with size bytes of random.\n *\n * Use a temporary bytes representation to make sure the result is the same\n * regardless of the platform endianness (useful when f_rng is actually\n * deterministic, eg for tests).\n */\nint mbedtls_mpi_fill_random( mbedtls_mpi *X, size_t size,\n                     int (*f_rng)(void *, unsigned char *, size_t),\n                     void *p_rng )\n{\n    int ret;\n    unsigned char buf[MBEDTLS_MPI_MAX_SIZE];\n\n    if( size > MBEDTLS_MPI_MAX_SIZE )\n        return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );\n\n    MBEDTLS_MPI_CHK( f_rng( p_rng, buf, size ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( X, buf, size ) );\n\ncleanup:\n    mbedtls_platform_zeroize( buf, sizeof( buf ) );\n    return( ret );\n}\n\n/*\n * Modular inverse: X = A^-1 mod N  (HAC 14.61 / 14.64)\n */\nint mbedtls_mpi_inv_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *N )\n{\n    int ret;\n    mbedtls_mpi G, TA, TU, U1, U2, TB, TV, V1, V2;\n\n    if( mbedtls_mpi_cmp_int( N, 1 ) <= 0 )\n        return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );\n\n    mbedtls_mpi_init( &TA ); mbedtls_mpi_init( &TU ); mbedtls_mpi_init( &U1 ); mbedtls_mpi_init( &U2 );\n    mbedtls_mpi_init( &G ); mbedtls_mpi_init( &TB ); mbedtls_mpi_init( &TV );\n    mbedtls_mpi_init( &V1 ); mbedtls_mpi_init( &V2 );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, A, N ) );\n\n    if( mbedtls_mpi_cmp_int( &G, 1 ) != 0 )\n    {\n        ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;\n        goto cleanup;\n    }\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &TA, A, N ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TU, &TA ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TB, N ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &TV, N ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &U1, 1 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &U2, 0 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &V1, 0 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &V2, 1 ) );\n\n    do\n    {\n        while( ( TU.p[0] & 1 ) == 0 )\n        {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TU, 1 ) );\n\n            if( ( U1.p[0] & 1 ) != 0 || ( U2.p[0] & 1 ) != 0 )\n            {\n                MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &U1, &U1, &TB ) );\n                MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U2, &U2, &TA ) );\n            }\n\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &U1, 1 ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &U2, 1 ) );\n        }\n\n        while( ( TV.p[0] & 1 ) == 0 )\n        {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &TV, 1 ) );\n\n            if( ( V1.p[0] & 1 ) != 0 || ( V2.p[0] & 1 ) != 0 )\n            {\n                MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &V1, &V1, &TB ) );\n                MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V2, &V2, &TA ) );\n            }\n\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &V1, 1 ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &V2, 1 ) );\n        }\n\n        if( mbedtls_mpi_cmp_mpi( &TU, &TV ) >= 0 )\n        {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &TU, &TU, &TV ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U1, &U1, &V1 ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U2, &U2, &V2 ) );\n        }\n        else\n        {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &TV, &TV, &TU ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V1, &V1, &U1 ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V2, &V2, &U2 ) );\n        }\n    }\n    while( mbedtls_mpi_cmp_int( &TU, 0 ) != 0 );\n\n    while( mbedtls_mpi_cmp_int( &V1, 0 ) < 0 )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &V1, &V1, N ) );\n\n    while( mbedtls_mpi_cmp_mpi( &V1, N ) >= 0 )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &V1, &V1, N ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, &V1 ) );\n\ncleanup:\n\n    mbedtls_mpi_free( &TA ); mbedtls_mpi_free( &TU ); mbedtls_mpi_free( &U1 ); mbedtls_mpi_free( &U2 );\n    mbedtls_mpi_free( &G ); mbedtls_mpi_free( &TB ); mbedtls_mpi_free( &TV );\n    mbedtls_mpi_free( &V1 ); mbedtls_mpi_free( &V2 );\n\n    return( ret );\n}\n\n#if defined(MBEDTLS_GENPRIME)\n\nstatic const int small_prime[] =\n{\n        3,    5,    7,   11,   13,   17,   19,   23,\n       29,   31,   37,   41,   43,   47,   53,   59,\n       61,   67,   71,   73,   79,   83,   89,   97,\n      101,  103,  107,  109,  113,  127,  131,  137,\n      139,  149,  151,  157,  163,  167,  173,  179,\n      181,  191,  193,  197,  199,  211,  223,  227,\n      229,  233,  239,  241,  251,  257,  263,  269,\n      271,  277,  281,  283,  293,  307,  311,  313,\n      317,  331,  337,  347,  349,  353,  359,  367,\n      373,  379,  383,  389,  397,  401,  409,  419,\n      421,  431,  433,  439,  443,  449,  457,  461,\n      463,  467,  479,  487,  491,  499,  503,  509,\n      521,  523,  541,  547,  557,  563,  569,  571,\n      577,  587,  593,  599,  601,  607,  613,  617,\n      619,  631,  641,  643,  647,  653,  659,  661,\n      673,  677,  683,  691,  701,  709,  719,  727,\n      733,  739,  743,  751,  757,  761,  769,  773,\n      787,  797,  809,  811,  821,  823,  827,  829,\n      839,  853,  857,  859,  863,  877,  881,  883,\n      887,  907,  911,  919,  929,  937,  941,  947,\n      953,  967,  971,  977,  983,  991,  997, -103\n};\n\n/*\n * Small divisors test (X must be positive)\n *\n * Return values:\n * 0: no small factor (possible prime, more tests needed)\n * 1: certain prime\n * MBEDTLS_ERR_MPI_NOT_ACCEPTABLE: certain non-prime\n * other negative: error\n */\nstatic int mpi_check_small_factors( const mbedtls_mpi *X )\n{\n    int ret = 0;\n    size_t i;\n    mbedtls_mpi_uint r;\n\n    if( ( X->p[0] & 1 ) == 0 )\n        return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );\n\n    for( i = 0; small_prime[i] > 0; i++ )\n    {\n        if( mbedtls_mpi_cmp_int( X, small_prime[i] ) <= 0 )\n            return( 1 );\n\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, small_prime[i] ) );\n\n        if( r == 0 )\n            return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );\n    }\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Miller-Rabin pseudo-primality test  (HAC 4.24)\n */\nstatic int mpi_miller_rabin( const mbedtls_mpi *X,\n                             int (*f_rng)(void *, unsigned char *, size_t),\n                             void *p_rng )\n{\n    int ret, count;\n    size_t i, j, k, n, s;\n    mbedtls_mpi W, R, T, A, RR;\n\n    mbedtls_mpi_init( &W ); mbedtls_mpi_init( &R ); mbedtls_mpi_init( &T ); mbedtls_mpi_init( &A );\n    mbedtls_mpi_init( &RR );\n\n    /*\n     * W = |X| - 1\n     * R = W >> lsb( W )\n     */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &W, X, 1 ) );\n    s = mbedtls_mpi_lsb( &W );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R, &W ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &R, s ) );\n\n    i = mbedtls_mpi_bitlen( X );\n    /*\n     * HAC, table 4.4\n     */\n    n = ( ( i >= 1300 ) ?  2 : ( i >=  850 ) ?  3 :\n          ( i >=  650 ) ?  4 : ( i >=  350 ) ?  8 :\n          ( i >=  250 ) ? 12 : ( i >=  150 ) ? 18 : 27 );\n\n    for( i = 0; i < n; i++ )\n    {\n        /*\n         * pick a random A, 1 < A < |X| - 1\n         */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &A, X->n * ciL, f_rng, p_rng ) );\n\n        if( mbedtls_mpi_cmp_mpi( &A, &W ) >= 0 )\n        {\n            j = mbedtls_mpi_bitlen( &A ) - mbedtls_mpi_bitlen( &W );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &A, j + 1 ) );\n        }\n        A.p[0] |= 3;\n\n        count = 0;\n        do {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &A, X->n * ciL, f_rng, p_rng ) );\n\n            j = mbedtls_mpi_bitlen( &A );\n            k = mbedtls_mpi_bitlen( &W );\n            if (j > k) {\n                MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &A, j - k ) );\n            }\n\n            if (count++ > 30) {\n                return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;\n            }\n\n        } while ( mbedtls_mpi_cmp_mpi( &A, &W ) >= 0 ||\n                  mbedtls_mpi_cmp_int( &A, 1 )  <= 0    );\n\n        /*\n         * A = A^R mod |X|\n         */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &A, &A, &R, X, &RR ) );\n\n        if( mbedtls_mpi_cmp_mpi( &A, &W ) == 0 ||\n            mbedtls_mpi_cmp_int( &A,  1 ) == 0 )\n            continue;\n\n        j = 1;\n        while( j < s && mbedtls_mpi_cmp_mpi( &A, &W ) != 0 )\n        {\n            /*\n             * A = A * A mod |X|\n             */\n            MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &A, &A ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &A, &T, X  ) );\n\n            if( mbedtls_mpi_cmp_int( &A, 1 ) == 0 )\n                break;\n\n            j++;\n        }\n\n        /*\n         * not prime if A != |X| - 1 or A == 1\n         */\n        if( mbedtls_mpi_cmp_mpi( &A, &W ) != 0 ||\n            mbedtls_mpi_cmp_int( &A,  1 ) == 0 )\n        {\n            ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;\n            break;\n        }\n    }\n\ncleanup:\n    mbedtls_mpi_free( &W ); mbedtls_mpi_free( &R ); mbedtls_mpi_free( &T ); mbedtls_mpi_free( &A );\n    mbedtls_mpi_free( &RR );\n\n    return( ret );\n}\n\n/*\n * Pseudo-primality test: small factors, then Miller-Rabin\n */\nint mbedtls_mpi_is_prime( const mbedtls_mpi *X,\n                  int (*f_rng)(void *, unsigned char *, size_t),\n                  void *p_rng )\n{\n    int ret;\n    mbedtls_mpi XX;\n\n    XX.s = 1;\n    XX.n = X->n;\n    XX.p = X->p;\n\n    if( mbedtls_mpi_cmp_int( &XX, 0 ) == 0 ||\n        mbedtls_mpi_cmp_int( &XX, 1 ) == 0 )\n        return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );\n\n    if( mbedtls_mpi_cmp_int( &XX, 2 ) == 0 )\n        return( 0 );\n\n    if( ( ret = mpi_check_small_factors( &XX ) ) != 0 )\n    {\n        if( ret == 1 )\n            return( 0 );\n\n        return( ret );\n    }\n\n    return( mpi_miller_rabin( &XX, f_rng, p_rng ) );\n}\n\n/*\n * Prime number generation\n *\n * If dh_flag is 0 and nbits is at least 1024, then the procedure\n * follows the RSA probably-prime generation method of FIPS 186-4.\n * NB. FIPS 186-4 only allows the specific bit lengths of 1024 and 1536.\n */\nint mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int dh_flag,\n                   int (*f_rng)(void *, unsigned char *, size_t),\n                   void *p_rng )\n{\n#ifdef MBEDTLS_HAVE_INT64\n// ceil(2^63.5)\n#define CEIL_MAXUINT_DIV_SQRT2 0xb504f333f9de6485ULL\n#else\n// ceil(2^31.5)\n#define CEIL_MAXUINT_DIV_SQRT2 0xb504f334U\n#endif\n    int ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;\n    size_t k, n;\n    mbedtls_mpi_uint r;\n    mbedtls_mpi Y;\n\n    if( nbits < 3 || nbits > MBEDTLS_MPI_MAX_BITS )\n        return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );\n\n    mbedtls_mpi_init( &Y );\n\n    n = BITS_TO_LIMBS( nbits );\n\n    while( 1 )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( X, n * ciL, f_rng, p_rng ) );\n        /* make sure generated number is at least (nbits-1)+0.5 bits (FIPS 186-4 §B.3.3 steps 4.4, 5.5) */\n        if( X->p[n-1] < CEIL_MAXUINT_DIV_SQRT2 ) continue;\n\n        k = n * biL;\n        if( k > nbits ) MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( X, k - nbits ) );\n        X->p[0] |= 1;\n\n        if( dh_flag == 0 )\n        {\n            ret = mbedtls_mpi_is_prime( X, f_rng, p_rng );\n\n            if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )\n                goto cleanup;\n        }\n        else\n        {\n            /*\n             * An necessary condition for Y and X = 2Y + 1 to be prime\n             * is X = 2 mod 3 (which is equivalent to Y = 2 mod 3).\n             * Make sure it is satisfied, while keeping X = 3 mod 4\n             */\n\n            X->p[0] |= 2;\n\n            MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, 3 ) );\n            if( r == 0 )\n                MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 8 ) );\n            else if( r == 1 )\n                MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( X, X, 4 ) );\n\n            /* Set Y = (X-1) / 2, which is X / 2 because X is odd */\n            MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Y, X ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &Y, 1 ) );\n\n            while( 1 )\n            {\n                /*\n                 * First, check small factors for X and Y\n                 * before doing Miller-Rabin on any of them\n                 */\n                if( ( ret = mpi_check_small_factors(  X         ) ) == 0 &&\n                    ( ret = mpi_check_small_factors( &Y         ) ) == 0 &&\n                    ( ret = mpi_miller_rabin(  X, f_rng, p_rng  ) ) == 0 &&\n                    ( ret = mpi_miller_rabin( &Y, f_rng, p_rng  ) ) == 0 )\n                    goto cleanup;\n\n                if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )\n                    goto cleanup;\n\n                /*\n                 * Next candidates. We want to preserve Y = (X-1) / 2 and\n                 * Y = 1 mod 2 and Y = 2 mod 3 (eq X = 3 mod 4 and X = 2 mod 3)\n                 * so up Y by 6 and X by 12.\n                 */\n                MBEDTLS_MPI_CHK( mbedtls_mpi_add_int(  X,  X, 12 ) );\n                MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &Y, &Y, 6  ) );\n            }\n        }\n    }\n\ncleanup:\n\n    mbedtls_mpi_free( &Y );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_GENPRIME */\n\n#if defined(MBEDTLS_SELF_TEST)\n\n#define GCD_PAIR_COUNT  3\n\nstatic const int gcd_pairs[GCD_PAIR_COUNT][3] =\n{\n    { 693, 609, 21 },\n    { 1764, 868, 28 },\n    { 768454923, 542167814, 1 }\n};\n\n/*\n * Checkup routine\n */\nint mbedtls_mpi_self_test( int verbose )\n{\n    int ret, i;\n    mbedtls_mpi A, E, N, X, Y, U, V;\n\n    mbedtls_mpi_init( &A ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &N ); mbedtls_mpi_init( &X );\n    mbedtls_mpi_init( &Y ); mbedtls_mpi_init( &U ); mbedtls_mpi_init( &V );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &A, 16,\n        \"EFE021C2645FD1DC586E69184AF4A31E\" \\\n        \"D5F53E93B5F123FA41680867BA110131\" \\\n        \"944FE7952E2517337780CB0DB80E61AA\" \\\n        \"E7C8DDC6C5C6AADEB34EB38A2F40D5E6\" ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &E, 16,\n        \"B2E7EFD37075B9F03FF989C7C5051C20\" \\\n        \"34D2A323810251127E7BF8625A4F49A5\" \\\n        \"F3E27F4DA8BD59C47D6DAABA4C8127BD\" \\\n        \"5B5C25763222FEFCCFC38B832366C29E\" ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &N, 16,\n        \"0066A198186C18C10B2F5ED9B522752A\" \\\n        \"9830B69916E535C8F047518A889A43A5\" \\\n        \"94B6BED27A168D31D4A52F88925AA8F5\" ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &X, &A, &N ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,\n        \"602AB7ECA597A3D6B56FF9829A5E8B85\" \\\n        \"9E857EA95A03512E2BAE7391688D264A\" \\\n        \"A5663B0341DB9CCFD2C4C5F421FEC814\" \\\n        \"8001B72E848A38CAE1C65F78E56ABDEF\" \\\n        \"E12D3C039B8A02D6BE593F0BBBDA56F1\" \\\n        \"ECF677152EF804370C1A305CAF3B5BF1\" \\\n        \"30879B56C61DE584A0F53A2447A51E\" ) );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  MPI test #1 (mul_mpi): \" );\n\n    if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        ret = 1;\n        goto cleanup;\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &X, &Y, &A, &N ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,\n        \"256567336059E52CAE22925474705F39A94\" ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &V, 16,\n        \"6613F26162223DF488E9CD48CC132C7A\" \\\n        \"0AC93C701B001B092E4E5B9F73BCD27B\" \\\n        \"9EE50D0657C77F374E903CDFA4C642\" ) );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  MPI test #2 (div_mpi): \" );\n\n    if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 ||\n        mbedtls_mpi_cmp_mpi( &Y, &V ) != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        ret = 1;\n        goto cleanup;\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &X, &A, &E, &N, NULL ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,\n        \"36E139AEA55215609D2816998ED020BB\" \\\n        \"BD96C37890F65171D948E9BC7CBAA4D9\" \\\n        \"325D24D6A3C12710F10A09FA08AB87\" ) );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  MPI test #3 (exp_mod): \" );\n\n    if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        ret = 1;\n        goto cleanup;\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &X, &A, &N ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &U, 16,\n        \"003A0AAEDD7E784FC07D8F9EC6E3BFD5\" \\\n        \"C3DBA76456363A10869622EAC2DD84EC\" \\\n        \"C5B8A74DAC4D09E03B5E0BE779F2DF61\" ) );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  MPI test #4 (inv_mod): \" );\n\n    if( mbedtls_mpi_cmp_mpi( &X, &U ) != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        ret = 1;\n        goto cleanup;\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  MPI test #5 (simple gcd): \" );\n\n    for( i = 0; i < GCD_PAIR_COUNT; i++ )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &X, gcd_pairs[i][0] ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &Y, gcd_pairs[i][1] ) );\n\n        MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &A, &X, &Y ) );\n\n        if( mbedtls_mpi_cmp_int( &A, gcd_pairs[i][2] ) != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed at %d\\n\", i );\n\n            ret = 1;\n            goto cleanup;\n        }\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\ncleanup:\n\n    if( ret != 0 && verbose != 0 )\n        mbedtls_printf( \"Unexpected error, return code = %08X\\n\", ret );\n\n    mbedtls_mpi_free( &A ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &N ); mbedtls_mpi_free( &X );\n    mbedtls_mpi_free( &Y ); mbedtls_mpi_free( &U ); mbedtls_mpi_free( &V );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_BIGNUM_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/blowfish.c",
    "content": "/*\n *  Blowfish implementation\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The Blowfish block cipher was designed by Bruce Schneier in 1993.\n *  http://www.schneier.com/blowfish.html\n *  http://en.wikipedia.org/wiki/Blowfish_%28cipher%29\n *\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_BLOWFISH_C)\n\n#include \"mbedtls/blowfish.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if !defined(MBEDTLS_BLOWFISH_ALT)\n\n/*\n * 32-bit integer manipulation macros (big endian)\n */\n#ifndef GET_UINT32_BE\n#define GET_UINT32_BE(n,b,i)                            \\\n{                                                       \\\n    (n) = ( (uint32_t) (b)[(i)    ] << 24 )             \\\n        | ( (uint32_t) (b)[(i) + 1] << 16 )             \\\n        | ( (uint32_t) (b)[(i) + 2] <<  8 )             \\\n        | ( (uint32_t) (b)[(i) + 3]       );            \\\n}\n#endif\n\n#ifndef PUT_UINT32_BE\n#define PUT_UINT32_BE(n,b,i)                            \\\n{                                                       \\\n    (b)[(i)    ] = (unsigned char) ( (n) >> 24 );       \\\n    (b)[(i) + 1] = (unsigned char) ( (n) >> 16 );       \\\n    (b)[(i) + 2] = (unsigned char) ( (n) >>  8 );       \\\n    (b)[(i) + 3] = (unsigned char) ( (n)       );       \\\n}\n#endif\n\nstatic const uint32_t P[MBEDTLS_BLOWFISH_ROUNDS + 2] = {\n        0x243F6A88L, 0x85A308D3L, 0x13198A2EL, 0x03707344L,\n        0xA4093822L, 0x299F31D0L, 0x082EFA98L, 0xEC4E6C89L,\n        0x452821E6L, 0x38D01377L, 0xBE5466CFL, 0x34E90C6CL,\n        0xC0AC29B7L, 0xC97C50DDL, 0x3F84D5B5L, 0xB5470917L,\n        0x9216D5D9L, 0x8979FB1BL\n};\n\n/* declarations of data at the end of this file */\nstatic const uint32_t S[4][256];\n\nstatic uint32_t F( mbedtls_blowfish_context *ctx, uint32_t x )\n{\n   unsigned short a, b, c, d;\n   uint32_t  y;\n\n   d = (unsigned short)(x & 0xFF);\n   x >>= 8;\n   c = (unsigned short)(x & 0xFF);\n   x >>= 8;\n   b = (unsigned short)(x & 0xFF);\n   x >>= 8;\n   a = (unsigned short)(x & 0xFF);\n   y = ctx->S[0][a] + ctx->S[1][b];\n   y = y ^ ctx->S[2][c];\n   y = y + ctx->S[3][d];\n\n   return( y );\n}\n\nstatic void blowfish_enc( mbedtls_blowfish_context *ctx, uint32_t *xl, uint32_t *xr )\n{\n    uint32_t  Xl, Xr, temp;\n    short i;\n\n    Xl = *xl;\n    Xr = *xr;\n\n    for( i = 0; i < MBEDTLS_BLOWFISH_ROUNDS; ++i )\n    {\n        Xl = Xl ^ ctx->P[i];\n        Xr = F( ctx, Xl ) ^ Xr;\n\n        temp = Xl;\n        Xl = Xr;\n        Xr = temp;\n    }\n\n    temp = Xl;\n    Xl = Xr;\n    Xr = temp;\n\n    Xr = Xr ^ ctx->P[MBEDTLS_BLOWFISH_ROUNDS];\n    Xl = Xl ^ ctx->P[MBEDTLS_BLOWFISH_ROUNDS + 1];\n\n    *xl = Xl;\n    *xr = Xr;\n}\n\nstatic void blowfish_dec( mbedtls_blowfish_context *ctx, uint32_t *xl, uint32_t *xr )\n{\n    uint32_t  Xl, Xr, temp;\n    short i;\n\n    Xl = *xl;\n    Xr = *xr;\n\n    for( i = MBEDTLS_BLOWFISH_ROUNDS + 1; i > 1; --i )\n    {\n        Xl = Xl ^ ctx->P[i];\n        Xr = F( ctx, Xl ) ^ Xr;\n\n        temp = Xl;\n        Xl = Xr;\n        Xr = temp;\n    }\n\n    temp = Xl;\n    Xl = Xr;\n    Xr = temp;\n\n    Xr = Xr ^ ctx->P[1];\n    Xl = Xl ^ ctx->P[0];\n\n    *xl = Xl;\n    *xr = Xr;\n}\n\nvoid mbedtls_blowfish_init( mbedtls_blowfish_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_blowfish_context ) );\n}\n\nvoid mbedtls_blowfish_free( mbedtls_blowfish_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_blowfish_context ) );\n}\n\n/*\n * Blowfish key schedule\n */\nint mbedtls_blowfish_setkey( mbedtls_blowfish_context *ctx, const unsigned char *key,\n                     unsigned int keybits )\n{\n    unsigned int i, j, k;\n    uint32_t data, datal, datar;\n\n    if( keybits < MBEDTLS_BLOWFISH_MIN_KEY_BITS || keybits > MBEDTLS_BLOWFISH_MAX_KEY_BITS ||\n        ( keybits % 8 ) )\n    {\n        return( MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH );\n    }\n\n    keybits >>= 3;\n\n    for( i = 0; i < 4; i++ )\n    {\n        for( j = 0; j < 256; j++ )\n            ctx->S[i][j] = S[i][j];\n    }\n\n    j = 0;\n    for( i = 0; i < MBEDTLS_BLOWFISH_ROUNDS + 2; ++i )\n    {\n        data = 0x00000000;\n        for( k = 0; k < 4; ++k )\n        {\n            data = ( data << 8 ) | key[j++];\n            if( j >= keybits )\n                j = 0;\n        }\n        ctx->P[i] = P[i] ^ data;\n    }\n\n    datal = 0x00000000;\n    datar = 0x00000000;\n\n    for( i = 0; i < MBEDTLS_BLOWFISH_ROUNDS + 2; i += 2 )\n    {\n        blowfish_enc( ctx, &datal, &datar );\n        ctx->P[i] = datal;\n        ctx->P[i + 1] = datar;\n    }\n\n    for( i = 0; i < 4; i++ )\n    {\n       for( j = 0; j < 256; j += 2 )\n       {\n            blowfish_enc( ctx, &datal, &datar );\n            ctx->S[i][j] = datal;\n            ctx->S[i][j + 1] = datar;\n        }\n    }\n    return( 0 );\n}\n\n/*\n * Blowfish-ECB block encryption/decryption\n */\nint mbedtls_blowfish_crypt_ecb( mbedtls_blowfish_context *ctx,\n                    int mode,\n                    const unsigned char input[MBEDTLS_BLOWFISH_BLOCKSIZE],\n                    unsigned char output[MBEDTLS_BLOWFISH_BLOCKSIZE] )\n{\n    uint32_t X0, X1;\n\n    GET_UINT32_BE( X0, input,  0 );\n    GET_UINT32_BE( X1, input,  4 );\n\n    if( mode == MBEDTLS_BLOWFISH_DECRYPT )\n    {\n        blowfish_dec( ctx, &X0, &X1 );\n    }\n    else /* MBEDTLS_BLOWFISH_ENCRYPT */\n    {\n        blowfish_enc( ctx, &X0, &X1 );\n    }\n\n    PUT_UINT32_BE( X0, output,  0 );\n    PUT_UINT32_BE( X1, output,  4 );\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n/*\n * Blowfish-CBC buffer encryption/decryption\n */\nint mbedtls_blowfish_crypt_cbc( mbedtls_blowfish_context *ctx,\n                    int mode,\n                    size_t length,\n                    unsigned char iv[MBEDTLS_BLOWFISH_BLOCKSIZE],\n                    const unsigned char *input,\n                    unsigned char *output )\n{\n    int i;\n    unsigned char temp[MBEDTLS_BLOWFISH_BLOCKSIZE];\n\n    if( length % MBEDTLS_BLOWFISH_BLOCKSIZE )\n        return( MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH );\n\n    if( mode == MBEDTLS_BLOWFISH_DECRYPT )\n    {\n        while( length > 0 )\n        {\n            memcpy( temp, input, MBEDTLS_BLOWFISH_BLOCKSIZE );\n            mbedtls_blowfish_crypt_ecb( ctx, mode, input, output );\n\n            for( i = 0; i < MBEDTLS_BLOWFISH_BLOCKSIZE;i++ )\n                output[i] = (unsigned char)( output[i] ^ iv[i] );\n\n            memcpy( iv, temp, MBEDTLS_BLOWFISH_BLOCKSIZE );\n\n            input  += MBEDTLS_BLOWFISH_BLOCKSIZE;\n            output += MBEDTLS_BLOWFISH_BLOCKSIZE;\n            length -= MBEDTLS_BLOWFISH_BLOCKSIZE;\n        }\n    }\n    else\n    {\n        while( length > 0 )\n        {\n            for( i = 0; i < MBEDTLS_BLOWFISH_BLOCKSIZE; i++ )\n                output[i] = (unsigned char)( input[i] ^ iv[i] );\n\n            mbedtls_blowfish_crypt_ecb( ctx, mode, output, output );\n            memcpy( iv, output, MBEDTLS_BLOWFISH_BLOCKSIZE );\n\n            input  += MBEDTLS_BLOWFISH_BLOCKSIZE;\n            output += MBEDTLS_BLOWFISH_BLOCKSIZE;\n            length -= MBEDTLS_BLOWFISH_BLOCKSIZE;\n        }\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n/*\n * Blowfish CFB buffer encryption/decryption\n */\nint mbedtls_blowfish_crypt_cfb64( mbedtls_blowfish_context *ctx,\n                       int mode,\n                       size_t length,\n                       size_t *iv_off,\n                       unsigned char iv[MBEDTLS_BLOWFISH_BLOCKSIZE],\n                       const unsigned char *input,\n                       unsigned char *output )\n{\n    int c;\n    size_t n = *iv_off;\n\n    if( mode == MBEDTLS_BLOWFISH_DECRYPT )\n    {\n        while( length-- )\n        {\n            if( n == 0 )\n                mbedtls_blowfish_crypt_ecb( ctx, MBEDTLS_BLOWFISH_ENCRYPT, iv, iv );\n\n            c = *input++;\n            *output++ = (unsigned char)( c ^ iv[n] );\n            iv[n] = (unsigned char) c;\n\n            n = ( n + 1 ) % MBEDTLS_BLOWFISH_BLOCKSIZE;\n        }\n    }\n    else\n    {\n        while( length-- )\n        {\n            if( n == 0 )\n                mbedtls_blowfish_crypt_ecb( ctx, MBEDTLS_BLOWFISH_ENCRYPT, iv, iv );\n\n            iv[n] = *output++ = (unsigned char)( iv[n] ^ *input++ );\n\n            n = ( n + 1 ) % MBEDTLS_BLOWFISH_BLOCKSIZE;\n        }\n    }\n\n    *iv_off = n;\n\n    return( 0 );\n}\n#endif /*MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n/*\n * Blowfish CTR buffer encryption/decryption\n */\nint mbedtls_blowfish_crypt_ctr( mbedtls_blowfish_context *ctx,\n                       size_t length,\n                       size_t *nc_off,\n                       unsigned char nonce_counter[MBEDTLS_BLOWFISH_BLOCKSIZE],\n                       unsigned char stream_block[MBEDTLS_BLOWFISH_BLOCKSIZE],\n                       const unsigned char *input,\n                       unsigned char *output )\n{\n    int c, i;\n    size_t n = *nc_off;\n\n    while( length-- )\n    {\n        if( n == 0 ) {\n            mbedtls_blowfish_crypt_ecb( ctx, MBEDTLS_BLOWFISH_ENCRYPT, nonce_counter,\n                                stream_block );\n\n            for( i = MBEDTLS_BLOWFISH_BLOCKSIZE; i > 0; i-- )\n                if( ++nonce_counter[i - 1] != 0 )\n                    break;\n        }\n        c = *input++;\n        *output++ = (unsigned char)( c ^ stream_block[n] );\n\n        n = ( n + 1 ) % MBEDTLS_BLOWFISH_BLOCKSIZE;\n    }\n\n    *nc_off = n;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\nstatic const uint32_t S[4][256] = {\n    {   0xD1310BA6L, 0x98DFB5ACL, 0x2FFD72DBL, 0xD01ADFB7L,\n        0xB8E1AFEDL, 0x6A267E96L, 0xBA7C9045L, 0xF12C7F99L,\n        0x24A19947L, 0xB3916CF7L, 0x0801F2E2L, 0x858EFC16L,\n        0x636920D8L, 0x71574E69L, 0xA458FEA3L, 0xF4933D7EL,\n        0x0D95748FL, 0x728EB658L, 0x718BCD58L, 0x82154AEEL,\n        0x7B54A41DL, 0xC25A59B5L, 0x9C30D539L, 0x2AF26013L,\n        0xC5D1B023L, 0x286085F0L, 0xCA417918L, 0xB8DB38EFL,\n        0x8E79DCB0L, 0x603A180EL, 0x6C9E0E8BL, 0xB01E8A3EL,\n        0xD71577C1L, 0xBD314B27L, 0x78AF2FDAL, 0x55605C60L,\n        0xE65525F3L, 0xAA55AB94L, 0x57489862L, 0x63E81440L,\n        0x55CA396AL, 0x2AAB10B6L, 0xB4CC5C34L, 0x1141E8CEL,\n        0xA15486AFL, 0x7C72E993L, 0xB3EE1411L, 0x636FBC2AL,\n        0x2BA9C55DL, 0x741831F6L, 0xCE5C3E16L, 0x9B87931EL,\n        0xAFD6BA33L, 0x6C24CF5CL, 0x7A325381L, 0x28958677L,\n        0x3B8F4898L, 0x6B4BB9AFL, 0xC4BFE81BL, 0x66282193L,\n        0x61D809CCL, 0xFB21A991L, 0x487CAC60L, 0x5DEC8032L,\n        0xEF845D5DL, 0xE98575B1L, 0xDC262302L, 0xEB651B88L,\n        0x23893E81L, 0xD396ACC5L, 0x0F6D6FF3L, 0x83F44239L,\n        0x2E0B4482L, 0xA4842004L, 0x69C8F04AL, 0x9E1F9B5EL,\n        0x21C66842L, 0xF6E96C9AL, 0x670C9C61L, 0xABD388F0L,\n        0x6A51A0D2L, 0xD8542F68L, 0x960FA728L, 0xAB5133A3L,\n        0x6EEF0B6CL, 0x137A3BE4L, 0xBA3BF050L, 0x7EFB2A98L,\n        0xA1F1651DL, 0x39AF0176L, 0x66CA593EL, 0x82430E88L,\n        0x8CEE8619L, 0x456F9FB4L, 0x7D84A5C3L, 0x3B8B5EBEL,\n        0xE06F75D8L, 0x85C12073L, 0x401A449FL, 0x56C16AA6L,\n        0x4ED3AA62L, 0x363F7706L, 0x1BFEDF72L, 0x429B023DL,\n        0x37D0D724L, 0xD00A1248L, 0xDB0FEAD3L, 0x49F1C09BL,\n        0x075372C9L, 0x80991B7BL, 0x25D479D8L, 0xF6E8DEF7L,\n        0xE3FE501AL, 0xB6794C3BL, 0x976CE0BDL, 0x04C006BAL,\n        0xC1A94FB6L, 0x409F60C4L, 0x5E5C9EC2L, 0x196A2463L,\n        0x68FB6FAFL, 0x3E6C53B5L, 0x1339B2EBL, 0x3B52EC6FL,\n        0x6DFC511FL, 0x9B30952CL, 0xCC814544L, 0xAF5EBD09L,\n        0xBEE3D004L, 0xDE334AFDL, 0x660F2807L, 0x192E4BB3L,\n        0xC0CBA857L, 0x45C8740FL, 0xD20B5F39L, 0xB9D3FBDBL,\n        0x5579C0BDL, 0x1A60320AL, 0xD6A100C6L, 0x402C7279L,\n        0x679F25FEL, 0xFB1FA3CCL, 0x8EA5E9F8L, 0xDB3222F8L,\n        0x3C7516DFL, 0xFD616B15L, 0x2F501EC8L, 0xAD0552ABL,\n        0x323DB5FAL, 0xFD238760L, 0x53317B48L, 0x3E00DF82L,\n        0x9E5C57BBL, 0xCA6F8CA0L, 0x1A87562EL, 0xDF1769DBL,\n        0xD542A8F6L, 0x287EFFC3L, 0xAC6732C6L, 0x8C4F5573L,\n        0x695B27B0L, 0xBBCA58C8L, 0xE1FFA35DL, 0xB8F011A0L,\n        0x10FA3D98L, 0xFD2183B8L, 0x4AFCB56CL, 0x2DD1D35BL,\n        0x9A53E479L, 0xB6F84565L, 0xD28E49BCL, 0x4BFB9790L,\n        0xE1DDF2DAL, 0xA4CB7E33L, 0x62FB1341L, 0xCEE4C6E8L,\n        0xEF20CADAL, 0x36774C01L, 0xD07E9EFEL, 0x2BF11FB4L,\n        0x95DBDA4DL, 0xAE909198L, 0xEAAD8E71L, 0x6B93D5A0L,\n        0xD08ED1D0L, 0xAFC725E0L, 0x8E3C5B2FL, 0x8E7594B7L,\n        0x8FF6E2FBL, 0xF2122B64L, 0x8888B812L, 0x900DF01CL,\n        0x4FAD5EA0L, 0x688FC31CL, 0xD1CFF191L, 0xB3A8C1ADL,\n        0x2F2F2218L, 0xBE0E1777L, 0xEA752DFEL, 0x8B021FA1L,\n        0xE5A0CC0FL, 0xB56F74E8L, 0x18ACF3D6L, 0xCE89E299L,\n        0xB4A84FE0L, 0xFD13E0B7L, 0x7CC43B81L, 0xD2ADA8D9L,\n        0x165FA266L, 0x80957705L, 0x93CC7314L, 0x211A1477L,\n        0xE6AD2065L, 0x77B5FA86L, 0xC75442F5L, 0xFB9D35CFL,\n        0xEBCDAF0CL, 0x7B3E89A0L, 0xD6411BD3L, 0xAE1E7E49L,\n        0x00250E2DL, 0x2071B35EL, 0x226800BBL, 0x57B8E0AFL,\n        0x2464369BL, 0xF009B91EL, 0x5563911DL, 0x59DFA6AAL,\n        0x78C14389L, 0xD95A537FL, 0x207D5BA2L, 0x02E5B9C5L,\n        0x83260376L, 0x6295CFA9L, 0x11C81968L, 0x4E734A41L,\n        0xB3472DCAL, 0x7B14A94AL, 0x1B510052L, 0x9A532915L,\n        0xD60F573FL, 0xBC9BC6E4L, 0x2B60A476L, 0x81E67400L,\n        0x08BA6FB5L, 0x571BE91FL, 0xF296EC6BL, 0x2A0DD915L,\n        0xB6636521L, 0xE7B9F9B6L, 0xFF34052EL, 0xC5855664L,\n        0x53B02D5DL, 0xA99F8FA1L, 0x08BA4799L, 0x6E85076AL   },\n    {   0x4B7A70E9L, 0xB5B32944L, 0xDB75092EL, 0xC4192623L,\n        0xAD6EA6B0L, 0x49A7DF7DL, 0x9CEE60B8L, 0x8FEDB266L,\n        0xECAA8C71L, 0x699A17FFL, 0x5664526CL, 0xC2B19EE1L,\n        0x193602A5L, 0x75094C29L, 0xA0591340L, 0xE4183A3EL,\n        0x3F54989AL, 0x5B429D65L, 0x6B8FE4D6L, 0x99F73FD6L,\n        0xA1D29C07L, 0xEFE830F5L, 0x4D2D38E6L, 0xF0255DC1L,\n        0x4CDD2086L, 0x8470EB26L, 0x6382E9C6L, 0x021ECC5EL,\n        0x09686B3FL, 0x3EBAEFC9L, 0x3C971814L, 0x6B6A70A1L,\n        0x687F3584L, 0x52A0E286L, 0xB79C5305L, 0xAA500737L,\n        0x3E07841CL, 0x7FDEAE5CL, 0x8E7D44ECL, 0x5716F2B8L,\n        0xB03ADA37L, 0xF0500C0DL, 0xF01C1F04L, 0x0200B3FFL,\n        0xAE0CF51AL, 0x3CB574B2L, 0x25837A58L, 0xDC0921BDL,\n        0xD19113F9L, 0x7CA92FF6L, 0x94324773L, 0x22F54701L,\n        0x3AE5E581L, 0x37C2DADCL, 0xC8B57634L, 0x9AF3DDA7L,\n        0xA9446146L, 0x0FD0030EL, 0xECC8C73EL, 0xA4751E41L,\n        0xE238CD99L, 0x3BEA0E2FL, 0x3280BBA1L, 0x183EB331L,\n        0x4E548B38L, 0x4F6DB908L, 0x6F420D03L, 0xF60A04BFL,\n        0x2CB81290L, 0x24977C79L, 0x5679B072L, 0xBCAF89AFL,\n        0xDE9A771FL, 0xD9930810L, 0xB38BAE12L, 0xDCCF3F2EL,\n        0x5512721FL, 0x2E6B7124L, 0x501ADDE6L, 0x9F84CD87L,\n        0x7A584718L, 0x7408DA17L, 0xBC9F9ABCL, 0xE94B7D8CL,\n        0xEC7AEC3AL, 0xDB851DFAL, 0x63094366L, 0xC464C3D2L,\n        0xEF1C1847L, 0x3215D908L, 0xDD433B37L, 0x24C2BA16L,\n        0x12A14D43L, 0x2A65C451L, 0x50940002L, 0x133AE4DDL,\n        0x71DFF89EL, 0x10314E55L, 0x81AC77D6L, 0x5F11199BL,\n        0x043556F1L, 0xD7A3C76BL, 0x3C11183BL, 0x5924A509L,\n        0xF28FE6EDL, 0x97F1FBFAL, 0x9EBABF2CL, 0x1E153C6EL,\n        0x86E34570L, 0xEAE96FB1L, 0x860E5E0AL, 0x5A3E2AB3L,\n        0x771FE71CL, 0x4E3D06FAL, 0x2965DCB9L, 0x99E71D0FL,\n        0x803E89D6L, 0x5266C825L, 0x2E4CC978L, 0x9C10B36AL,\n        0xC6150EBAL, 0x94E2EA78L, 0xA5FC3C53L, 0x1E0A2DF4L,\n        0xF2F74EA7L, 0x361D2B3DL, 0x1939260FL, 0x19C27960L,\n        0x5223A708L, 0xF71312B6L, 0xEBADFE6EL, 0xEAC31F66L,\n        0xE3BC4595L, 0xA67BC883L, 0xB17F37D1L, 0x018CFF28L,\n        0xC332DDEFL, 0xBE6C5AA5L, 0x65582185L, 0x68AB9802L,\n        0xEECEA50FL, 0xDB2F953BL, 0x2AEF7DADL, 0x5B6E2F84L,\n        0x1521B628L, 0x29076170L, 0xECDD4775L, 0x619F1510L,\n        0x13CCA830L, 0xEB61BD96L, 0x0334FE1EL, 0xAA0363CFL,\n        0xB5735C90L, 0x4C70A239L, 0xD59E9E0BL, 0xCBAADE14L,\n        0xEECC86BCL, 0x60622CA7L, 0x9CAB5CABL, 0xB2F3846EL,\n        0x648B1EAFL, 0x19BDF0CAL, 0xA02369B9L, 0x655ABB50L,\n        0x40685A32L, 0x3C2AB4B3L, 0x319EE9D5L, 0xC021B8F7L,\n        0x9B540B19L, 0x875FA099L, 0x95F7997EL, 0x623D7DA8L,\n        0xF837889AL, 0x97E32D77L, 0x11ED935FL, 0x16681281L,\n        0x0E358829L, 0xC7E61FD6L, 0x96DEDFA1L, 0x7858BA99L,\n        0x57F584A5L, 0x1B227263L, 0x9B83C3FFL, 0x1AC24696L,\n        0xCDB30AEBL, 0x532E3054L, 0x8FD948E4L, 0x6DBC3128L,\n        0x58EBF2EFL, 0x34C6FFEAL, 0xFE28ED61L, 0xEE7C3C73L,\n        0x5D4A14D9L, 0xE864B7E3L, 0x42105D14L, 0x203E13E0L,\n        0x45EEE2B6L, 0xA3AAABEAL, 0xDB6C4F15L, 0xFACB4FD0L,\n        0xC742F442L, 0xEF6ABBB5L, 0x654F3B1DL, 0x41CD2105L,\n        0xD81E799EL, 0x86854DC7L, 0xE44B476AL, 0x3D816250L,\n        0xCF62A1F2L, 0x5B8D2646L, 0xFC8883A0L, 0xC1C7B6A3L,\n        0x7F1524C3L, 0x69CB7492L, 0x47848A0BL, 0x5692B285L,\n        0x095BBF00L, 0xAD19489DL, 0x1462B174L, 0x23820E00L,\n        0x58428D2AL, 0x0C55F5EAL, 0x1DADF43EL, 0x233F7061L,\n        0x3372F092L, 0x8D937E41L, 0xD65FECF1L, 0x6C223BDBL,\n        0x7CDE3759L, 0xCBEE7460L, 0x4085F2A7L, 0xCE77326EL,\n        0xA6078084L, 0x19F8509EL, 0xE8EFD855L, 0x61D99735L,\n        0xA969A7AAL, 0xC50C06C2L, 0x5A04ABFCL, 0x800BCADCL,\n        0x9E447A2EL, 0xC3453484L, 0xFDD56705L, 0x0E1E9EC9L,\n        0xDB73DBD3L, 0x105588CDL, 0x675FDA79L, 0xE3674340L,\n        0xC5C43465L, 0x713E38D8L, 0x3D28F89EL, 0xF16DFF20L,\n        0x153E21E7L, 0x8FB03D4AL, 0xE6E39F2BL, 0xDB83ADF7L   },\n    {   0xE93D5A68L, 0x948140F7L, 0xF64C261CL, 0x94692934L,\n        0x411520F7L, 0x7602D4F7L, 0xBCF46B2EL, 0xD4A20068L,\n        0xD4082471L, 0x3320F46AL, 0x43B7D4B7L, 0x500061AFL,\n        0x1E39F62EL, 0x97244546L, 0x14214F74L, 0xBF8B8840L,\n        0x4D95FC1DL, 0x96B591AFL, 0x70F4DDD3L, 0x66A02F45L,\n        0xBFBC09ECL, 0x03BD9785L, 0x7FAC6DD0L, 0x31CB8504L,\n        0x96EB27B3L, 0x55FD3941L, 0xDA2547E6L, 0xABCA0A9AL,\n        0x28507825L, 0x530429F4L, 0x0A2C86DAL, 0xE9B66DFBL,\n        0x68DC1462L, 0xD7486900L, 0x680EC0A4L, 0x27A18DEEL,\n        0x4F3FFEA2L, 0xE887AD8CL, 0xB58CE006L, 0x7AF4D6B6L,\n        0xAACE1E7CL, 0xD3375FECL, 0xCE78A399L, 0x406B2A42L,\n        0x20FE9E35L, 0xD9F385B9L, 0xEE39D7ABL, 0x3B124E8BL,\n        0x1DC9FAF7L, 0x4B6D1856L, 0x26A36631L, 0xEAE397B2L,\n        0x3A6EFA74L, 0xDD5B4332L, 0x6841E7F7L, 0xCA7820FBL,\n        0xFB0AF54EL, 0xD8FEB397L, 0x454056ACL, 0xBA489527L,\n        0x55533A3AL, 0x20838D87L, 0xFE6BA9B7L, 0xD096954BL,\n        0x55A867BCL, 0xA1159A58L, 0xCCA92963L, 0x99E1DB33L,\n        0xA62A4A56L, 0x3F3125F9L, 0x5EF47E1CL, 0x9029317CL,\n        0xFDF8E802L, 0x04272F70L, 0x80BB155CL, 0x05282CE3L,\n        0x95C11548L, 0xE4C66D22L, 0x48C1133FL, 0xC70F86DCL,\n        0x07F9C9EEL, 0x41041F0FL, 0x404779A4L, 0x5D886E17L,\n        0x325F51EBL, 0xD59BC0D1L, 0xF2BCC18FL, 0x41113564L,\n        0x257B7834L, 0x602A9C60L, 0xDFF8E8A3L, 0x1F636C1BL,\n        0x0E12B4C2L, 0x02E1329EL, 0xAF664FD1L, 0xCAD18115L,\n        0x6B2395E0L, 0x333E92E1L, 0x3B240B62L, 0xEEBEB922L,\n        0x85B2A20EL, 0xE6BA0D99L, 0xDE720C8CL, 0x2DA2F728L,\n        0xD0127845L, 0x95B794FDL, 0x647D0862L, 0xE7CCF5F0L,\n        0x5449A36FL, 0x877D48FAL, 0xC39DFD27L, 0xF33E8D1EL,\n        0x0A476341L, 0x992EFF74L, 0x3A6F6EABL, 0xF4F8FD37L,\n        0xA812DC60L, 0xA1EBDDF8L, 0x991BE14CL, 0xDB6E6B0DL,\n        0xC67B5510L, 0x6D672C37L, 0x2765D43BL, 0xDCD0E804L,\n        0xF1290DC7L, 0xCC00FFA3L, 0xB5390F92L, 0x690FED0BL,\n        0x667B9FFBL, 0xCEDB7D9CL, 0xA091CF0BL, 0xD9155EA3L,\n        0xBB132F88L, 0x515BAD24L, 0x7B9479BFL, 0x763BD6EBL,\n        0x37392EB3L, 0xCC115979L, 0x8026E297L, 0xF42E312DL,\n        0x6842ADA7L, 0xC66A2B3BL, 0x12754CCCL, 0x782EF11CL,\n        0x6A124237L, 0xB79251E7L, 0x06A1BBE6L, 0x4BFB6350L,\n        0x1A6B1018L, 0x11CAEDFAL, 0x3D25BDD8L, 0xE2E1C3C9L,\n        0x44421659L, 0x0A121386L, 0xD90CEC6EL, 0xD5ABEA2AL,\n        0x64AF674EL, 0xDA86A85FL, 0xBEBFE988L, 0x64E4C3FEL,\n        0x9DBC8057L, 0xF0F7C086L, 0x60787BF8L, 0x6003604DL,\n        0xD1FD8346L, 0xF6381FB0L, 0x7745AE04L, 0xD736FCCCL,\n        0x83426B33L, 0xF01EAB71L, 0xB0804187L, 0x3C005E5FL,\n        0x77A057BEL, 0xBDE8AE24L, 0x55464299L, 0xBF582E61L,\n        0x4E58F48FL, 0xF2DDFDA2L, 0xF474EF38L, 0x8789BDC2L,\n        0x5366F9C3L, 0xC8B38E74L, 0xB475F255L, 0x46FCD9B9L,\n        0x7AEB2661L, 0x8B1DDF84L, 0x846A0E79L, 0x915F95E2L,\n        0x466E598EL, 0x20B45770L, 0x8CD55591L, 0xC902DE4CL,\n        0xB90BACE1L, 0xBB8205D0L, 0x11A86248L, 0x7574A99EL,\n        0xB77F19B6L, 0xE0A9DC09L, 0x662D09A1L, 0xC4324633L,\n        0xE85A1F02L, 0x09F0BE8CL, 0x4A99A025L, 0x1D6EFE10L,\n        0x1AB93D1DL, 0x0BA5A4DFL, 0xA186F20FL, 0x2868F169L,\n        0xDCB7DA83L, 0x573906FEL, 0xA1E2CE9BL, 0x4FCD7F52L,\n        0x50115E01L, 0xA70683FAL, 0xA002B5C4L, 0x0DE6D027L,\n        0x9AF88C27L, 0x773F8641L, 0xC3604C06L, 0x61A806B5L,\n        0xF0177A28L, 0xC0F586E0L, 0x006058AAL, 0x30DC7D62L,\n        0x11E69ED7L, 0x2338EA63L, 0x53C2DD94L, 0xC2C21634L,\n        0xBBCBEE56L, 0x90BCB6DEL, 0xEBFC7DA1L, 0xCE591D76L,\n        0x6F05E409L, 0x4B7C0188L, 0x39720A3DL, 0x7C927C24L,\n        0x86E3725FL, 0x724D9DB9L, 0x1AC15BB4L, 0xD39EB8FCL,\n        0xED545578L, 0x08FCA5B5L, 0xD83D7CD3L, 0x4DAD0FC4L,\n        0x1E50EF5EL, 0xB161E6F8L, 0xA28514D9L, 0x6C51133CL,\n        0x6FD5C7E7L, 0x56E14EC4L, 0x362ABFCEL, 0xDDC6C837L,\n        0xD79A3234L, 0x92638212L, 0x670EFA8EL, 0x406000E0L  },\n    {   0x3A39CE37L, 0xD3FAF5CFL, 0xABC27737L, 0x5AC52D1BL,\n        0x5CB0679EL, 0x4FA33742L, 0xD3822740L, 0x99BC9BBEL,\n        0xD5118E9DL, 0xBF0F7315L, 0xD62D1C7EL, 0xC700C47BL,\n        0xB78C1B6BL, 0x21A19045L, 0xB26EB1BEL, 0x6A366EB4L,\n        0x5748AB2FL, 0xBC946E79L, 0xC6A376D2L, 0x6549C2C8L,\n        0x530FF8EEL, 0x468DDE7DL, 0xD5730A1DL, 0x4CD04DC6L,\n        0x2939BBDBL, 0xA9BA4650L, 0xAC9526E8L, 0xBE5EE304L,\n        0xA1FAD5F0L, 0x6A2D519AL, 0x63EF8CE2L, 0x9A86EE22L,\n        0xC089C2B8L, 0x43242EF6L, 0xA51E03AAL, 0x9CF2D0A4L,\n        0x83C061BAL, 0x9BE96A4DL, 0x8FE51550L, 0xBA645BD6L,\n        0x2826A2F9L, 0xA73A3AE1L, 0x4BA99586L, 0xEF5562E9L,\n        0xC72FEFD3L, 0xF752F7DAL, 0x3F046F69L, 0x77FA0A59L,\n        0x80E4A915L, 0x87B08601L, 0x9B09E6ADL, 0x3B3EE593L,\n        0xE990FD5AL, 0x9E34D797L, 0x2CF0B7D9L, 0x022B8B51L,\n        0x96D5AC3AL, 0x017DA67DL, 0xD1CF3ED6L, 0x7C7D2D28L,\n        0x1F9F25CFL, 0xADF2B89BL, 0x5AD6B472L, 0x5A88F54CL,\n        0xE029AC71L, 0xE019A5E6L, 0x47B0ACFDL, 0xED93FA9BL,\n        0xE8D3C48DL, 0x283B57CCL, 0xF8D56629L, 0x79132E28L,\n        0x785F0191L, 0xED756055L, 0xF7960E44L, 0xE3D35E8CL,\n        0x15056DD4L, 0x88F46DBAL, 0x03A16125L, 0x0564F0BDL,\n        0xC3EB9E15L, 0x3C9057A2L, 0x97271AECL, 0xA93A072AL,\n        0x1B3F6D9BL, 0x1E6321F5L, 0xF59C66FBL, 0x26DCF319L,\n        0x7533D928L, 0xB155FDF5L, 0x03563482L, 0x8ABA3CBBL,\n        0x28517711L, 0xC20AD9F8L, 0xABCC5167L, 0xCCAD925FL,\n        0x4DE81751L, 0x3830DC8EL, 0x379D5862L, 0x9320F991L,\n        0xEA7A90C2L, 0xFB3E7BCEL, 0x5121CE64L, 0x774FBE32L,\n        0xA8B6E37EL, 0xC3293D46L, 0x48DE5369L, 0x6413E680L,\n        0xA2AE0810L, 0xDD6DB224L, 0x69852DFDL, 0x09072166L,\n        0xB39A460AL, 0x6445C0DDL, 0x586CDECFL, 0x1C20C8AEL,\n        0x5BBEF7DDL, 0x1B588D40L, 0xCCD2017FL, 0x6BB4E3BBL,\n        0xDDA26A7EL, 0x3A59FF45L, 0x3E350A44L, 0xBCB4CDD5L,\n        0x72EACEA8L, 0xFA6484BBL, 0x8D6612AEL, 0xBF3C6F47L,\n        0xD29BE463L, 0x542F5D9EL, 0xAEC2771BL, 0xF64E6370L,\n        0x740E0D8DL, 0xE75B1357L, 0xF8721671L, 0xAF537D5DL,\n        0x4040CB08L, 0x4EB4E2CCL, 0x34D2466AL, 0x0115AF84L,\n        0xE1B00428L, 0x95983A1DL, 0x06B89FB4L, 0xCE6EA048L,\n        0x6F3F3B82L, 0x3520AB82L, 0x011A1D4BL, 0x277227F8L,\n        0x611560B1L, 0xE7933FDCL, 0xBB3A792BL, 0x344525BDL,\n        0xA08839E1L, 0x51CE794BL, 0x2F32C9B7L, 0xA01FBAC9L,\n        0xE01CC87EL, 0xBCC7D1F6L, 0xCF0111C3L, 0xA1E8AAC7L,\n        0x1A908749L, 0xD44FBD9AL, 0xD0DADECBL, 0xD50ADA38L,\n        0x0339C32AL, 0xC6913667L, 0x8DF9317CL, 0xE0B12B4FL,\n        0xF79E59B7L, 0x43F5BB3AL, 0xF2D519FFL, 0x27D9459CL,\n        0xBF97222CL, 0x15E6FC2AL, 0x0F91FC71L, 0x9B941525L,\n        0xFAE59361L, 0xCEB69CEBL, 0xC2A86459L, 0x12BAA8D1L,\n        0xB6C1075EL, 0xE3056A0CL, 0x10D25065L, 0xCB03A442L,\n        0xE0EC6E0EL, 0x1698DB3BL, 0x4C98A0BEL, 0x3278E964L,\n        0x9F1F9532L, 0xE0D392DFL, 0xD3A0342BL, 0x8971F21EL,\n        0x1B0A7441L, 0x4BA3348CL, 0xC5BE7120L, 0xC37632D8L,\n        0xDF359F8DL, 0x9B992F2EL, 0xE60B6F47L, 0x0FE3F11DL,\n        0xE54CDA54L, 0x1EDAD891L, 0xCE6279CFL, 0xCD3E7E6FL,\n        0x1618B166L, 0xFD2C1D05L, 0x848FD2C5L, 0xF6FB2299L,\n        0xF523F357L, 0xA6327623L, 0x93A83531L, 0x56CCCD02L,\n        0xACF08162L, 0x5A75EBB5L, 0x6E163697L, 0x88D273CCL,\n        0xDE966292L, 0x81B949D0L, 0x4C50901BL, 0x71C65614L,\n        0xE6C6C7BDL, 0x327A140AL, 0x45E1D006L, 0xC3F27B9AL,\n        0xC9AA53FDL, 0x62A80F00L, 0xBB25BFE2L, 0x35BDD2F6L,\n        0x71126905L, 0xB2040222L, 0xB6CBCF7CL, 0xCD769C2BL,\n        0x53113EC0L, 0x1640E3D3L, 0x38ABBD60L, 0x2547ADF0L,\n        0xBA38209CL, 0xF746CE76L, 0x77AFA1C5L, 0x20756060L,\n        0x85CBFE4EL, 0x8AE88DD8L, 0x7AAAF9B0L, 0x4CF9AA7EL,\n        0x1948C25CL, 0x02FB8A8CL, 0x01C36AE4L, 0xD6EBE1F9L,\n        0x90D4F869L, 0xA65CDEA0L, 0x3F09252DL, 0xC208E69FL,\n        0xB74E6132L, 0xCE77E25BL, 0x578FDFE3L, 0x3AC372E6L  }\n};\n\n#endif /* !MBEDTLS_BLOWFISH_ALT */\n#endif /* MBEDTLS_BLOWFISH_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/camellia.c",
    "content": "/*\n *  Camellia implementation\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The Camellia block cipher was designed by NTT and Mitsubishi Electric\n *  Corporation.\n *\n *  http://info.isl.ntt.co.jp/crypt/eng/camellia/dl/01espec.pdf\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_CAMELLIA_C)\n\n#include \"mbedtls/camellia.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if !defined(MBEDTLS_CAMELLIA_ALT)\n\n/*\n * 32-bit integer manipulation macros (big endian)\n */\n#ifndef GET_UINT32_BE\n#define GET_UINT32_BE(n,b,i)                            \\\n{                                                       \\\n    (n) = ( (uint32_t) (b)[(i)    ] << 24 )             \\\n        | ( (uint32_t) (b)[(i) + 1] << 16 )             \\\n        | ( (uint32_t) (b)[(i) + 2] <<  8 )             \\\n        | ( (uint32_t) (b)[(i) + 3]       );            \\\n}\n#endif\n\n#ifndef PUT_UINT32_BE\n#define PUT_UINT32_BE(n,b,i)                            \\\n{                                                       \\\n    (b)[(i)    ] = (unsigned char) ( (n) >> 24 );       \\\n    (b)[(i) + 1] = (unsigned char) ( (n) >> 16 );       \\\n    (b)[(i) + 2] = (unsigned char) ( (n) >>  8 );       \\\n    (b)[(i) + 3] = (unsigned char) ( (n)       );       \\\n}\n#endif\n\nstatic const unsigned char SIGMA_CHARS[6][8] =\n{\n    { 0xa0, 0x9e, 0x66, 0x7f, 0x3b, 0xcc, 0x90, 0x8b },\n    { 0xb6, 0x7a, 0xe8, 0x58, 0x4c, 0xaa, 0x73, 0xb2 },\n    { 0xc6, 0xef, 0x37, 0x2f, 0xe9, 0x4f, 0x82, 0xbe },\n    { 0x54, 0xff, 0x53, 0xa5, 0xf1, 0xd3, 0x6f, 0x1c },\n    { 0x10, 0xe5, 0x27, 0xfa, 0xde, 0x68, 0x2d, 0x1d },\n    { 0xb0, 0x56, 0x88, 0xc2, 0xb3, 0xe6, 0xc1, 0xfd }\n};\n\n#if defined(MBEDTLS_CAMELLIA_SMALL_MEMORY)\n\nstatic const unsigned char FSb[256] =\n{\n    112,130, 44,236,179, 39,192,229,228,133, 87, 53,234, 12,174, 65,\n     35,239,107,147, 69, 25,165, 33,237, 14, 79, 78, 29,101,146,189,\n    134,184,175,143,124,235, 31,206, 62, 48,220, 95, 94,197, 11, 26,\n    166,225, 57,202,213, 71, 93, 61,217,  1, 90,214, 81, 86,108, 77,\n    139, 13,154,102,251,204,176, 45,116, 18, 43, 32,240,177,132,153,\n    223, 76,203,194, 52,126,118,  5,109,183,169, 49,209, 23,  4,215,\n     20, 88, 58, 97,222, 27, 17, 28, 50, 15,156, 22, 83, 24,242, 34,\n    254, 68,207,178,195,181,122,145, 36,  8,232,168, 96,252,105, 80,\n    170,208,160,125,161,137, 98,151, 84, 91, 30,149,224,255,100,210,\n     16,196,  0, 72,163,247,117,219,138,  3,230,218,  9, 63,221,148,\n    135, 92,131,  2,205, 74,144, 51,115,103,246,243,157,127,191,226,\n     82,155,216, 38,200, 55,198, 59,129,150,111, 75, 19,190, 99, 46,\n    233,121,167,140,159,110,188,142, 41,245,249,182, 47,253,180, 89,\n    120,152,  6,106,231, 70,113,186,212, 37,171, 66,136,162,141,250,\n    114,  7,185, 85,248,238,172, 10, 54, 73, 42,104, 60, 56,241,164,\n     64, 40,211,123,187,201, 67,193, 21,227,173,244,119,199,128,158\n};\n\n#define SBOX1(n) FSb[(n)]\n#define SBOX2(n) (unsigned char)((FSb[(n)] >> 7 ^ FSb[(n)] << 1) & 0xff)\n#define SBOX3(n) (unsigned char)((FSb[(n)] >> 1 ^ FSb[(n)] << 7) & 0xff)\n#define SBOX4(n) FSb[((n) << 1 ^ (n) >> 7) &0xff]\n\n#else /* MBEDTLS_CAMELLIA_SMALL_MEMORY */\n\nstatic const unsigned char FSb[256] =\n{\n 112, 130,  44, 236, 179,  39, 192, 229, 228, 133,  87,  53, 234,  12, 174,  65,\n  35, 239, 107, 147,  69,  25, 165,  33, 237,  14,  79,  78,  29, 101, 146, 189,\n 134, 184, 175, 143, 124, 235,  31, 206,  62,  48, 220,  95,  94, 197,  11,  26,\n 166, 225,  57, 202, 213,  71,  93,  61, 217,   1,  90, 214,  81,  86, 108,  77,\n 139,  13, 154, 102, 251, 204, 176,  45, 116,  18,  43,  32, 240, 177, 132, 153,\n 223,  76, 203, 194,  52, 126, 118,   5, 109, 183, 169,  49, 209,  23,   4, 215,\n  20,  88,  58,  97, 222,  27,  17,  28,  50,  15, 156,  22,  83,  24, 242,  34,\n 254,  68, 207, 178, 195, 181, 122, 145,  36,   8, 232, 168,  96, 252, 105,  80,\n 170, 208, 160, 125, 161, 137,  98, 151,  84,  91,  30, 149, 224, 255, 100, 210,\n  16, 196,   0,  72, 163, 247, 117, 219, 138,   3, 230, 218,   9,  63, 221, 148,\n 135,  92, 131,   2, 205,  74, 144,  51, 115, 103, 246, 243, 157, 127, 191, 226,\n  82, 155, 216,  38, 200,  55, 198,  59, 129, 150, 111,  75,  19, 190,  99,  46,\n 233, 121, 167, 140, 159, 110, 188, 142,  41, 245, 249, 182,  47, 253, 180,  89,\n 120, 152,   6, 106, 231,  70, 113, 186, 212,  37, 171,  66, 136, 162, 141, 250,\n 114,   7, 185,  85, 248, 238, 172,  10,  54,  73,  42, 104,  60,  56, 241, 164,\n 64,  40, 211, 123, 187, 201,  67, 193,  21, 227, 173, 244, 119, 199, 128, 158\n};\n\nstatic const unsigned char FSb2[256] =\n{\n 224,   5,  88, 217, 103,  78, 129, 203, 201,  11, 174, 106, 213,  24,  93, 130,\n  70, 223, 214,  39, 138,  50,  75,  66, 219,  28, 158, 156,  58, 202,  37, 123,\n  13, 113,  95,  31, 248, 215,  62, 157, 124,  96, 185, 190, 188, 139,  22,  52,\n  77, 195, 114, 149, 171, 142, 186, 122, 179,   2, 180, 173, 162, 172, 216, 154,\n  23,  26,  53, 204, 247, 153,  97,  90, 232,  36,  86,  64, 225,  99,   9,  51,\n 191, 152, 151, 133, 104, 252, 236,  10, 218, 111,  83,  98, 163,  46,   8, 175,\n  40, 176, 116, 194, 189,  54,  34,  56, 100,  30,  57,  44, 166,  48, 229,  68,\n 253, 136, 159, 101, 135, 107, 244,  35,  72,  16, 209,  81, 192, 249, 210, 160,\n  85, 161,  65, 250,  67,  19, 196,  47, 168, 182,  60,  43, 193, 255, 200, 165,\n  32, 137,   0, 144,  71, 239, 234, 183,  21,   6, 205, 181,  18, 126, 187,  41,\n  15, 184,   7,   4, 155, 148,  33, 102, 230, 206, 237, 231,  59, 254, 127, 197,\n 164,  55, 177,  76, 145, 110, 141, 118,   3,  45, 222, 150,  38, 125, 198,  92,\n 211, 242,  79,  25,  63, 220, 121,  29,  82, 235, 243, 109,  94, 251, 105, 178,\n 240,  49,  12, 212, 207, 140, 226, 117, 169,  74,  87, 132,  17,  69,  27, 245,\n 228,  14, 115, 170, 241, 221,  89,  20, 108, 146,  84, 208, 120, 112, 227,  73,\n 128,  80, 167, 246, 119, 147, 134, 131,  42, 199,  91, 233, 238, 143,   1,  61\n};\n\nstatic const unsigned char FSb3[256] =\n{\n  56,  65,  22, 118, 217, 147,  96, 242, 114, 194, 171, 154, 117,   6,  87, 160,\n 145, 247, 181, 201, 162, 140, 210, 144, 246,   7, 167,  39, 142, 178,  73, 222,\n  67,  92, 215, 199,  62, 245, 143, 103,  31,  24, 110, 175,  47, 226, 133,  13,\n  83, 240, 156, 101, 234, 163, 174, 158, 236, 128,  45, 107, 168,  43,  54, 166,\n 197, 134,  77,  51, 253, 102,  88, 150,  58,   9, 149,  16, 120, 216,  66, 204,\n 239,  38, 229,  97,  26,  63,  59, 130, 182, 219, 212, 152, 232, 139,   2, 235,\n  10,  44,  29, 176, 111, 141, 136,  14,  25, 135,  78,  11, 169,  12, 121,  17,\n 127,  34, 231,  89, 225, 218,  61, 200,  18,   4, 116,  84,  48, 126, 180,  40,\n  85, 104,  80, 190, 208, 196,  49, 203,  42, 173,  15, 202, 112, 255,  50, 105,\n   8,  98,   0,  36, 209, 251, 186, 237,  69, 129, 115, 109, 132, 159, 238,  74,\n 195,  46, 193,   1, 230,  37,  72, 153, 185, 179, 123, 249, 206, 191, 223, 113,\n  41, 205, 108,  19, 100, 155,  99, 157, 192,  75, 183, 165, 137,  95, 177,  23,\n 244, 188, 211,  70, 207,  55,  94,  71, 148, 250, 252,  91, 151, 254,  90, 172,\n  60,  76,   3,  53, 243,  35, 184,  93, 106, 146, 213,  33,  68,  81, 198, 125,\n  57, 131, 220, 170, 124, 119,  86,   5,  27, 164,  21,  52,  30,  28, 248,  82,\n  32,  20, 233, 189, 221, 228, 161, 224, 138, 241, 214, 122, 187, 227,  64,  79\n};\n\nstatic const unsigned char FSb4[256] =\n{\n 112,  44, 179, 192, 228,  87, 234, 174,  35, 107,  69, 165, 237,  79,  29, 146,\n 134, 175, 124,  31,  62, 220,  94,  11, 166,  57, 213,  93, 217,  90,  81, 108,\n 139, 154, 251, 176, 116,  43, 240, 132, 223, 203,  52, 118, 109, 169, 209,   4,\n  20,  58, 222,  17,  50, 156,  83, 242, 254, 207, 195, 122,  36, 232,  96, 105,\n 170, 160, 161,  98,  84,  30, 224, 100,  16,   0, 163, 117, 138, 230,   9, 221,\n 135, 131, 205, 144, 115, 246, 157, 191,  82, 216, 200, 198, 129, 111,  19,  99,\n 233, 167, 159, 188,  41, 249,  47, 180, 120,   6, 231, 113, 212, 171, 136, 141,\n 114, 185, 248, 172,  54,  42,  60, 241,  64, 211, 187,  67,  21, 173, 119, 128,\n 130, 236,  39, 229, 133,  53,  12,  65, 239, 147,  25,  33,  14,  78, 101, 189,\n 184, 143, 235, 206,  48,  95, 197,  26, 225, 202,  71,  61,   1, 214,  86,  77,\n  13, 102, 204,  45,  18,  32, 177, 153,  76, 194, 126,   5, 183,  49,  23, 215,\n  88,  97,  27,  28,  15,  22,  24,  34,  68, 178, 181, 145,   8, 168, 252,  80,\n 208, 125, 137, 151,  91, 149, 255, 210, 196,  72, 247, 219,   3, 218,  63, 148,\n  92,   2,  74,  51, 103, 243, 127, 226, 155,  38,  55,  59, 150,  75, 190,  46,\n 121, 140, 110, 142, 245, 182, 253,  89, 152, 106,  70, 186,  37,  66, 162, 250,\n  7,  85, 238,  10,  73, 104,  56, 164,  40, 123, 201, 193, 227, 244, 199, 158\n};\n\n#define SBOX1(n) FSb[(n)]\n#define SBOX2(n) FSb2[(n)]\n#define SBOX3(n) FSb3[(n)]\n#define SBOX4(n) FSb4[(n)]\n\n#endif /* MBEDTLS_CAMELLIA_SMALL_MEMORY */\n\nstatic const unsigned char shifts[2][4][4] =\n{\n    {\n        { 1, 1, 1, 1 }, /* KL */\n        { 0, 0, 0, 0 }, /* KR */\n        { 1, 1, 1, 1 }, /* KA */\n        { 0, 0, 0, 0 }  /* KB */\n    },\n    {\n        { 1, 0, 1, 1 }, /* KL */\n        { 1, 1, 0, 1 }, /* KR */\n        { 1, 1, 1, 0 }, /* KA */\n        { 1, 1, 0, 1 }  /* KB */\n    }\n};\n\nstatic const signed char indexes[2][4][20] =\n{\n    {\n        {  0,  1,  2,  3,  8,  9, 10, 11, 38, 39,\n          36, 37, 23, 20, 21, 22, 27, -1, -1, 26 }, /* KL -> RK */\n        { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n          -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /* KR -> RK */\n        {  4,  5,  6,  7, 12, 13, 14, 15, 16, 17,\n          18, 19, -1, 24, 25, -1, 31, 28, 29, 30 }, /* KA -> RK */\n        { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n          -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }  /* KB -> RK */\n    },\n    {\n        {  0,  1,  2,  3, 61, 62, 63, 60, -1, -1,\n          -1, -1, 27, 24, 25, 26, 35, 32, 33, 34 }, /* KL -> RK */\n        { -1, -1, -1, -1,  8,  9, 10, 11, 16, 17,\n          18, 19, -1, -1, -1, -1, 39, 36, 37, 38 }, /* KR -> RK */\n        { -1, -1, -1, -1, 12, 13, 14, 15, 58, 59,\n          56, 57, 31, 28, 29, 30, -1, -1, -1, -1 }, /* KA -> RK */\n        {  4,  5,  6,  7, 65, 66, 67, 64, 20, 21,\n          22, 23, -1, -1, -1, -1, 43, 40, 41, 42 }  /* KB -> RK */\n    }\n};\n\nstatic const signed char transposes[2][20] =\n{\n    {\n        21, 22, 23, 20,\n        -1, -1, -1, -1,\n        18, 19, 16, 17,\n        11,  8,  9, 10,\n        15, 12, 13, 14\n    },\n    {\n        25, 26, 27, 24,\n        29, 30, 31, 28,\n        18, 19, 16, 17,\n        -1, -1, -1, -1,\n        -1, -1, -1, -1\n    }\n};\n\n/* Shift macro for 128 bit strings with rotation smaller than 32 bits (!) */\n#define ROTL(DEST, SRC, SHIFT)                                      \\\n{                                                                   \\\n    (DEST)[0] = (SRC)[0] << (SHIFT) ^ (SRC)[1] >> (32 - (SHIFT));   \\\n    (DEST)[1] = (SRC)[1] << (SHIFT) ^ (SRC)[2] >> (32 - (SHIFT));   \\\n    (DEST)[2] = (SRC)[2] << (SHIFT) ^ (SRC)[3] >> (32 - (SHIFT));   \\\n    (DEST)[3] = (SRC)[3] << (SHIFT) ^ (SRC)[0] >> (32 - (SHIFT));   \\\n}\n\n#define FL(XL, XR, KL, KR)                                          \\\n{                                                                   \\\n    (XR) = ((((XL) & (KL)) << 1) | (((XL) & (KL)) >> 31)) ^ (XR);   \\\n    (XL) = ((XR) | (KR)) ^ (XL);                                    \\\n}\n\n#define FLInv(YL, YR, KL, KR)                                       \\\n{                                                                   \\\n    (YL) = ((YR) | (KR)) ^ (YL);                                    \\\n    (YR) = ((((YL) & (KL)) << 1) | (((YL) & (KL)) >> 31)) ^ (YR);   \\\n}\n\n#define SHIFT_AND_PLACE(INDEX, OFFSET)                      \\\n{                                                           \\\n    TK[0] = KC[(OFFSET) * 4 + 0];                           \\\n    TK[1] = KC[(OFFSET) * 4 + 1];                           \\\n    TK[2] = KC[(OFFSET) * 4 + 2];                           \\\n    TK[3] = KC[(OFFSET) * 4 + 3];                           \\\n                                                            \\\n    for( i = 1; i <= 4; i++ )                               \\\n        if( shifts[(INDEX)][(OFFSET)][i -1] )               \\\n            ROTL(TK + i * 4, TK, ( 15 * i ) % 32);          \\\n                                                            \\\n    for( i = 0; i < 20; i++ )                               \\\n        if( indexes[(INDEX)][(OFFSET)][i] != -1 ) {         \\\n            RK[indexes[(INDEX)][(OFFSET)][i]] = TK[ i ];    \\\n        }                                                   \\\n}\n\nstatic void camellia_feistel( const uint32_t x[2], const uint32_t k[2],\n                              uint32_t z[2])\n{\n    uint32_t I0, I1;\n    I0 = x[0] ^ k[0];\n    I1 = x[1] ^ k[1];\n\n    I0 = ((uint32_t) SBOX1((I0 >> 24) & 0xFF) << 24) |\n         ((uint32_t) SBOX2((I0 >> 16) & 0xFF) << 16) |\n         ((uint32_t) SBOX3((I0 >>  8) & 0xFF) <<  8) |\n         ((uint32_t) SBOX4((I0      ) & 0xFF)      );\n    I1 = ((uint32_t) SBOX2((I1 >> 24) & 0xFF) << 24) |\n         ((uint32_t) SBOX3((I1 >> 16) & 0xFF) << 16) |\n         ((uint32_t) SBOX4((I1 >>  8) & 0xFF) <<  8) |\n         ((uint32_t) SBOX1((I1      ) & 0xFF)      );\n\n    I0 ^= (I1 << 8) | (I1 >> 24);\n    I1 ^= (I0 << 16) | (I0 >> 16);\n    I0 ^= (I1 >> 8) | (I1 << 24);\n    I1 ^= (I0 >> 8) | (I0 << 24);\n\n    z[0] ^= I1;\n    z[1] ^= I0;\n}\n\nvoid mbedtls_camellia_init( mbedtls_camellia_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_camellia_context ) );\n}\n\nvoid mbedtls_camellia_free( mbedtls_camellia_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_camellia_context ) );\n}\n\n/*\n * Camellia key schedule (encryption)\n */\nint mbedtls_camellia_setkey_enc( mbedtls_camellia_context *ctx, const unsigned char *key,\n                         unsigned int keybits )\n{\n    int idx;\n    size_t i;\n    uint32_t *RK;\n    unsigned char t[64];\n    uint32_t SIGMA[6][2];\n    uint32_t KC[16];\n    uint32_t TK[20];\n\n    RK = ctx->rk;\n\n    memset( t, 0, 64 );\n    memset( RK, 0, sizeof(ctx->rk) );\n\n    switch( keybits )\n    {\n        case 128: ctx->nr = 3; idx = 0; break;\n        case 192:\n        case 256: ctx->nr = 4; idx = 1; break;\n        default : return( MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH );\n    }\n\n    for( i = 0; i < keybits / 8; ++i )\n        t[i] = key[i];\n\n    if( keybits == 192 ) {\n        for( i = 0; i < 8; i++ )\n            t[24 + i] = ~t[16 + i];\n    }\n\n    /*\n     * Prepare SIGMA values\n     */\n    for( i = 0; i < 6; i++ ) {\n        GET_UINT32_BE( SIGMA[i][0], SIGMA_CHARS[i], 0 );\n        GET_UINT32_BE( SIGMA[i][1], SIGMA_CHARS[i], 4 );\n    }\n\n    /*\n     * Key storage in KC\n     * Order: KL, KR, KA, KB\n     */\n    memset( KC, 0, sizeof(KC) );\n\n    /* Store KL, KR */\n    for( i = 0; i < 8; i++ )\n        GET_UINT32_BE( KC[i], t, i * 4 );\n\n    /* Generate KA */\n    for( i = 0; i < 4; ++i )\n        KC[8 + i] = KC[i] ^ KC[4 + i];\n\n    camellia_feistel( KC + 8, SIGMA[0], KC + 10 );\n    camellia_feistel( KC + 10, SIGMA[1], KC + 8 );\n\n    for( i = 0; i < 4; ++i )\n        KC[8 + i] ^= KC[i];\n\n    camellia_feistel( KC + 8, SIGMA[2], KC + 10 );\n    camellia_feistel( KC + 10, SIGMA[3], KC + 8 );\n\n    if( keybits > 128 ) {\n        /* Generate KB */\n        for( i = 0; i < 4; ++i )\n            KC[12 + i] = KC[4 + i] ^ KC[8 + i];\n\n        camellia_feistel( KC + 12, SIGMA[4], KC + 14 );\n        camellia_feistel( KC + 14, SIGMA[5], KC + 12 );\n    }\n\n    /*\n     * Generating subkeys\n     */\n\n    /* Manipulating KL */\n    SHIFT_AND_PLACE( idx, 0 );\n\n    /* Manipulating KR */\n    if( keybits > 128 ) {\n        SHIFT_AND_PLACE( idx, 1 );\n    }\n\n    /* Manipulating KA */\n    SHIFT_AND_PLACE( idx, 2 );\n\n    /* Manipulating KB */\n    if( keybits > 128 ) {\n        SHIFT_AND_PLACE( idx, 3 );\n    }\n\n    /* Do transpositions */\n    for( i = 0; i < 20; i++ ) {\n        if( transposes[idx][i] != -1 ) {\n            RK[32 + 12 * idx + i] = RK[transposes[idx][i]];\n        }\n    }\n\n    return( 0 );\n}\n\n/*\n * Camellia key schedule (decryption)\n */\nint mbedtls_camellia_setkey_dec( mbedtls_camellia_context *ctx, const unsigned char *key,\n                         unsigned int keybits )\n{\n    int idx, ret;\n    size_t i;\n    mbedtls_camellia_context cty;\n    uint32_t *RK;\n    uint32_t *SK;\n\n    mbedtls_camellia_init( &cty );\n\n    /* Also checks keybits */\n    if( ( ret = mbedtls_camellia_setkey_enc( &cty, key, keybits ) ) != 0 )\n        goto exit;\n\n    ctx->nr = cty.nr;\n    idx = ( ctx->nr == 4 );\n\n    RK = ctx->rk;\n    SK = cty.rk + 24 * 2 + 8 * idx * 2;\n\n    *RK++ = *SK++;\n    *RK++ = *SK++;\n    *RK++ = *SK++;\n    *RK++ = *SK++;\n\n    for( i = 22 + 8 * idx, SK -= 6; i > 0; i--, SK -= 4 )\n    {\n        *RK++ = *SK++;\n        *RK++ = *SK++;\n    }\n\n    SK -= 2;\n\n    *RK++ = *SK++;\n    *RK++ = *SK++;\n    *RK++ = *SK++;\n    *RK++ = *SK++;\n\nexit:\n    mbedtls_camellia_free( &cty );\n\n    return( ret );\n}\n\n/*\n * Camellia-ECB block encryption/decryption\n */\nint mbedtls_camellia_crypt_ecb( mbedtls_camellia_context *ctx,\n                    int mode,\n                    const unsigned char input[16],\n                    unsigned char output[16] )\n{\n    int NR;\n    uint32_t *RK, X[4];\n\n    ( (void) mode );\n\n    NR = ctx->nr;\n    RK = ctx->rk;\n\n    GET_UINT32_BE( X[0], input,  0 );\n    GET_UINT32_BE( X[1], input,  4 );\n    GET_UINT32_BE( X[2], input,  8 );\n    GET_UINT32_BE( X[3], input, 12 );\n\n    X[0] ^= *RK++;\n    X[1] ^= *RK++;\n    X[2] ^= *RK++;\n    X[3] ^= *RK++;\n\n    while( NR ) {\n        --NR;\n        camellia_feistel( X, RK, X + 2 );\n        RK += 2;\n        camellia_feistel( X + 2, RK, X );\n        RK += 2;\n        camellia_feistel( X, RK, X + 2 );\n        RK += 2;\n        camellia_feistel( X + 2, RK, X );\n        RK += 2;\n        camellia_feistel( X, RK, X + 2 );\n        RK += 2;\n        camellia_feistel( X + 2, RK, X );\n        RK += 2;\n\n        if( NR ) {\n            FL(X[0], X[1], RK[0], RK[1]);\n            RK += 2;\n            FLInv(X[2], X[3], RK[0], RK[1]);\n            RK += 2;\n        }\n    }\n\n    X[2] ^= *RK++;\n    X[3] ^= *RK++;\n    X[0] ^= *RK++;\n    X[1] ^= *RK++;\n\n    PUT_UINT32_BE( X[2], output,  0 );\n    PUT_UINT32_BE( X[3], output,  4 );\n    PUT_UINT32_BE( X[0], output,  8 );\n    PUT_UINT32_BE( X[1], output, 12 );\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n/*\n * Camellia-CBC buffer encryption/decryption\n */\nint mbedtls_camellia_crypt_cbc( mbedtls_camellia_context *ctx,\n                    int mode,\n                    size_t length,\n                    unsigned char iv[16],\n                    const unsigned char *input,\n                    unsigned char *output )\n{\n    int i;\n    unsigned char temp[16];\n\n    if( length % 16 )\n        return( MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH );\n\n    if( mode == MBEDTLS_CAMELLIA_DECRYPT )\n    {\n        while( length > 0 )\n        {\n            memcpy( temp, input, 16 );\n            mbedtls_camellia_crypt_ecb( ctx, mode, input, output );\n\n            for( i = 0; i < 16; i++ )\n                output[i] = (unsigned char)( output[i] ^ iv[i] );\n\n            memcpy( iv, temp, 16 );\n\n            input  += 16;\n            output += 16;\n            length -= 16;\n        }\n    }\n    else\n    {\n        while( length > 0 )\n        {\n            for( i = 0; i < 16; i++ )\n                output[i] = (unsigned char)( input[i] ^ iv[i] );\n\n            mbedtls_camellia_crypt_ecb( ctx, mode, output, output );\n            memcpy( iv, output, 16 );\n\n            input  += 16;\n            output += 16;\n            length -= 16;\n        }\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n/*\n * Camellia-CFB128 buffer encryption/decryption\n */\nint mbedtls_camellia_crypt_cfb128( mbedtls_camellia_context *ctx,\n                       int mode,\n                       size_t length,\n                       size_t *iv_off,\n                       unsigned char iv[16],\n                       const unsigned char *input,\n                       unsigned char *output )\n{\n    int c;\n    size_t n = *iv_off;\n\n    if( mode == MBEDTLS_CAMELLIA_DECRYPT )\n    {\n        while( length-- )\n        {\n            if( n == 0 )\n                mbedtls_camellia_crypt_ecb( ctx, MBEDTLS_CAMELLIA_ENCRYPT, iv, iv );\n\n            c = *input++;\n            *output++ = (unsigned char)( c ^ iv[n] );\n            iv[n] = (unsigned char) c;\n\n            n = ( n + 1 ) & 0x0F;\n        }\n    }\n    else\n    {\n        while( length-- )\n        {\n            if( n == 0 )\n                mbedtls_camellia_crypt_ecb( ctx, MBEDTLS_CAMELLIA_ENCRYPT, iv, iv );\n\n            iv[n] = *output++ = (unsigned char)( iv[n] ^ *input++ );\n\n            n = ( n + 1 ) & 0x0F;\n        }\n    }\n\n    *iv_off = n;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n/*\n * Camellia-CTR buffer encryption/decryption\n */\nint mbedtls_camellia_crypt_ctr( mbedtls_camellia_context *ctx,\n                       size_t length,\n                       size_t *nc_off,\n                       unsigned char nonce_counter[16],\n                       unsigned char stream_block[16],\n                       const unsigned char *input,\n                       unsigned char *output )\n{\n    int c, i;\n    size_t n = *nc_off;\n\n    while( length-- )\n    {\n        if( n == 0 ) {\n            mbedtls_camellia_crypt_ecb( ctx, MBEDTLS_CAMELLIA_ENCRYPT, nonce_counter,\n                                stream_block );\n\n            for( i = 16; i > 0; i-- )\n                if( ++nonce_counter[i - 1] != 0 )\n                    break;\n        }\n        c = *input++;\n        *output++ = (unsigned char)( c ^ stream_block[n] );\n\n        n = ( n + 1 ) & 0x0F;\n    }\n\n    *nc_off = n;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n#endif /* !MBEDTLS_CAMELLIA_ALT */\n\n#if defined(MBEDTLS_SELF_TEST)\n\n/*\n * Camellia test vectors from:\n *\n * http://info.isl.ntt.co.jp/crypt/eng/camellia/technology.html:\n *   http://info.isl.ntt.co.jp/crypt/eng/camellia/dl/cryptrec/intermediate.txt\n *   http://info.isl.ntt.co.jp/crypt/eng/camellia/dl/cryptrec/t_camellia.txt\n *                      (For each bitlength: Key 0, Nr 39)\n */\n#define CAMELLIA_TESTS_ECB  2\n\nstatic const unsigned char camellia_test_ecb_key[3][CAMELLIA_TESTS_ECB][32] =\n{\n    {\n        { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,\n          0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10 },\n        { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }\n    },\n    {\n        { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,\n          0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10,\n          0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77 },\n        { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }\n    },\n    {\n        { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,\n          0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10,\n          0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,\n          0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff },\n        { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }\n    },\n};\n\nstatic const unsigned char camellia_test_ecb_plain[CAMELLIA_TESTS_ECB][16] =\n{\n    { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,\n      0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10 },\n    { 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }\n};\n\nstatic const unsigned char camellia_test_ecb_cipher[3][CAMELLIA_TESTS_ECB][16] =\n{\n    {\n        { 0x67, 0x67, 0x31, 0x38, 0x54, 0x96, 0x69, 0x73,\n          0x08, 0x57, 0x06, 0x56, 0x48, 0xea, 0xbe, 0x43 },\n        { 0x38, 0x3C, 0x6C, 0x2A, 0xAB, 0xEF, 0x7F, 0xDE,\n          0x25, 0xCD, 0x47, 0x0B, 0xF7, 0x74, 0xA3, 0x31 }\n    },\n    {\n        { 0xb4, 0x99, 0x34, 0x01, 0xb3, 0xe9, 0x96, 0xf8,\n          0x4e, 0xe5, 0xce, 0xe7, 0xd7, 0x9b, 0x09, 0xb9 },\n        { 0xD1, 0x76, 0x3F, 0xC0, 0x19, 0xD7, 0x7C, 0xC9,\n          0x30, 0xBF, 0xF2, 0xA5, 0x6F, 0x7C, 0x93, 0x64 }\n    },\n    {\n        { 0x9a, 0xcc, 0x23, 0x7d, 0xff, 0x16, 0xd7, 0x6c,\n          0x20, 0xef, 0x7c, 0x91, 0x9e, 0x3a, 0x75, 0x09 },\n        { 0x05, 0x03, 0xFB, 0x10, 0xAB, 0x24, 0x1E, 0x7C,\n          0xF4, 0x5D, 0x8C, 0xDE, 0xEE, 0x47, 0x43, 0x35 }\n    }\n};\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#define CAMELLIA_TESTS_CBC  3\n\nstatic const unsigned char camellia_test_cbc_key[3][32] =\n{\n        { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6,\n          0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C }\n    ,\n        { 0x8E, 0x73, 0xB0, 0xF7, 0xDA, 0x0E, 0x64, 0x52,\n          0xC8, 0x10, 0xF3, 0x2B, 0x80, 0x90, 0x79, 0xE5,\n          0x62, 0xF8, 0xEA, 0xD2, 0x52, 0x2C, 0x6B, 0x7B }\n    ,\n        { 0x60, 0x3D, 0xEB, 0x10, 0x15, 0xCA, 0x71, 0xBE,\n          0x2B, 0x73, 0xAE, 0xF0, 0x85, 0x7D, 0x77, 0x81,\n          0x1F, 0x35, 0x2C, 0x07, 0x3B, 0x61, 0x08, 0xD7,\n          0x2D, 0x98, 0x10, 0xA3, 0x09, 0x14, 0xDF, 0xF4 }\n};\n\nstatic const unsigned char camellia_test_cbc_iv[16] =\n\n    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n      0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }\n;\n\nstatic const unsigned char camellia_test_cbc_plain[CAMELLIA_TESTS_CBC][16] =\n{\n    { 0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96,\n      0xE9, 0x3D, 0x7E, 0x11, 0x73, 0x93, 0x17, 0x2A },\n    { 0xAE, 0x2D, 0x8A, 0x57, 0x1E, 0x03, 0xAC, 0x9C,\n      0x9E, 0xB7, 0x6F, 0xAC, 0x45, 0xAF, 0x8E, 0x51 },\n    { 0x30, 0xC8, 0x1C, 0x46, 0xA3, 0x5C, 0xE4, 0x11,\n      0xE5, 0xFB, 0xC1, 0x19, 0x1A, 0x0A, 0x52, 0xEF }\n\n};\n\nstatic const unsigned char camellia_test_cbc_cipher[3][CAMELLIA_TESTS_CBC][16] =\n{\n    {\n        { 0x16, 0x07, 0xCF, 0x49, 0x4B, 0x36, 0xBB, 0xF0,\n          0x0D, 0xAE, 0xB0, 0xB5, 0x03, 0xC8, 0x31, 0xAB },\n        { 0xA2, 0xF2, 0xCF, 0x67, 0x16, 0x29, 0xEF, 0x78,\n          0x40, 0xC5, 0xA5, 0xDF, 0xB5, 0x07, 0x48, 0x87 },\n        { 0x0F, 0x06, 0x16, 0x50, 0x08, 0xCF, 0x8B, 0x8B,\n          0x5A, 0x63, 0x58, 0x63, 0x62, 0x54, 0x3E, 0x54 }\n    },\n    {\n        { 0x2A, 0x48, 0x30, 0xAB, 0x5A, 0xC4, 0xA1, 0xA2,\n          0x40, 0x59, 0x55, 0xFD, 0x21, 0x95, 0xCF, 0x93 },\n        { 0x5D, 0x5A, 0x86, 0x9B, 0xD1, 0x4C, 0xE5, 0x42,\n          0x64, 0xF8, 0x92, 0xA6, 0xDD, 0x2E, 0xC3, 0xD5 },\n        { 0x37, 0xD3, 0x59, 0xC3, 0x34, 0x98, 0x36, 0xD8,\n          0x84, 0xE3, 0x10, 0xAD, 0xDF, 0x68, 0xC4, 0x49 }\n    },\n    {\n        { 0xE6, 0xCF, 0xA3, 0x5F, 0xC0, 0x2B, 0x13, 0x4A,\n          0x4D, 0x2C, 0x0B, 0x67, 0x37, 0xAC, 0x3E, 0xDA },\n        { 0x36, 0xCB, 0xEB, 0x73, 0xBD, 0x50, 0x4B, 0x40,\n          0x70, 0xB1, 0xB7, 0xDE, 0x2B, 0x21, 0xEB, 0x50 },\n        { 0xE3, 0x1A, 0x60, 0x55, 0x29, 0x7D, 0x96, 0xCA,\n          0x33, 0x30, 0xCD, 0xF1, 0xB1, 0x86, 0x0A, 0x83 }\n    }\n};\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n/*\n * Camellia-CTR test vectors from:\n *\n * http://www.faqs.org/rfcs/rfc5528.html\n */\n\nstatic const unsigned char camellia_test_ctr_key[3][16] =\n{\n    { 0xAE, 0x68, 0x52, 0xF8, 0x12, 0x10, 0x67, 0xCC,\n      0x4B, 0xF7, 0xA5, 0x76, 0x55, 0x77, 0xF3, 0x9E },\n    { 0x7E, 0x24, 0x06, 0x78, 0x17, 0xFA, 0xE0, 0xD7,\n      0x43, 0xD6, 0xCE, 0x1F, 0x32, 0x53, 0x91, 0x63 },\n    { 0x76, 0x91, 0xBE, 0x03, 0x5E, 0x50, 0x20, 0xA8,\n      0xAC, 0x6E, 0x61, 0x85, 0x29, 0xF9, 0xA0, 0xDC }\n};\n\nstatic const unsigned char camellia_test_ctr_nonce_counter[3][16] =\n{\n    { 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 },\n    { 0x00, 0x6C, 0xB6, 0xDB, 0xC0, 0x54, 0x3B, 0x59,\n      0xDA, 0x48, 0xD9, 0x0B, 0x00, 0x00, 0x00, 0x01 },\n    { 0x00, 0xE0, 0x01, 0x7B, 0x27, 0x77, 0x7F, 0x3F,\n      0x4A, 0x17, 0x86, 0xF0, 0x00, 0x00, 0x00, 0x01 }\n};\n\nstatic const unsigned char camellia_test_ctr_pt[3][48] =\n{\n    { 0x53, 0x69, 0x6E, 0x67, 0x6C, 0x65, 0x20, 0x62,\n      0x6C, 0x6F, 0x63, 0x6B, 0x20, 0x6D, 0x73, 0x67 },\n\n    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n      0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,\n      0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,\n      0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F },\n\n    { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n      0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,\n      0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,\n      0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,\n      0x20, 0x21, 0x22, 0x23 }\n};\n\nstatic const unsigned char camellia_test_ctr_ct[3][48] =\n{\n    { 0xD0, 0x9D, 0xC2, 0x9A, 0x82, 0x14, 0x61, 0x9A,\n      0x20, 0x87, 0x7C, 0x76, 0xDB, 0x1F, 0x0B, 0x3F },\n    { 0xDB, 0xF3, 0xC7, 0x8D, 0xC0, 0x83, 0x96, 0xD4,\n      0xDA, 0x7C, 0x90, 0x77, 0x65, 0xBB, 0xCB, 0x44,\n      0x2B, 0x8E, 0x8E, 0x0F, 0x31, 0xF0, 0xDC, 0xA7,\n      0x2C, 0x74, 0x17, 0xE3, 0x53, 0x60, 0xE0, 0x48 },\n    { 0xB1, 0x9D, 0x1F, 0xCD, 0xCB, 0x75, 0xEB, 0x88,\n      0x2F, 0x84, 0x9C, 0xE2, 0x4D, 0x85, 0xCF, 0x73,\n      0x9C, 0xE6, 0x4B, 0x2B, 0x5C, 0x9D, 0x73, 0xF1,\n      0x4F, 0x2D, 0x5D, 0x9D, 0xCE, 0x98, 0x89, 0xCD,\n      0xDF, 0x50, 0x86, 0x96 }\n};\n\nstatic const int camellia_test_ctr_len[3] =\n    { 16, 32, 36 };\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\n/*\n * Checkup routine\n */\nint mbedtls_camellia_self_test( int verbose )\n{\n    int i, j, u, v;\n    unsigned char key[32];\n    unsigned char buf[64];\n    unsigned char src[16];\n    unsigned char dst[16];\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    unsigned char iv[16];\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    size_t offset, len;\n    unsigned char nonce_counter[16];\n    unsigned char stream_block[16];\n#endif\n\n    mbedtls_camellia_context ctx;\n\n    memset( key, 0, 32 );\n\n    for( j = 0; j < 6; j++ ) {\n        u = j >> 1;\n    v = j & 1;\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  CAMELLIA-ECB-%3d (%s): \", 128 + u * 64,\n                         (v == MBEDTLS_CAMELLIA_DECRYPT) ? \"dec\" : \"enc\");\n\n    for( i = 0; i < CAMELLIA_TESTS_ECB; i++ ) {\n        memcpy( key, camellia_test_ecb_key[u][i], 16 + 8 * u );\n\n        if( v == MBEDTLS_CAMELLIA_DECRYPT ) {\n            mbedtls_camellia_setkey_dec( &ctx, key, 128 + u * 64 );\n            memcpy( src, camellia_test_ecb_cipher[u][i], 16 );\n            memcpy( dst, camellia_test_ecb_plain[i], 16 );\n        } else { /* MBEDTLS_CAMELLIA_ENCRYPT */\n            mbedtls_camellia_setkey_enc( &ctx, key, 128 + u * 64 );\n            memcpy( src, camellia_test_ecb_plain[i], 16 );\n            memcpy( dst, camellia_test_ecb_cipher[u][i], 16 );\n        }\n\n        mbedtls_camellia_crypt_ecb( &ctx, v, src, buf );\n\n        if( memcmp( buf, dst, 16 ) != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed\\n\" );\n\n            return( 1 );\n        }\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    /*\n     * CBC mode\n     */\n    for( j = 0; j < 6; j++ )\n    {\n        u = j >> 1;\n        v = j  & 1;\n\n        if( verbose != 0 )\n            mbedtls_printf( \"  CAMELLIA-CBC-%3d (%s): \", 128 + u * 64,\n                             ( v == MBEDTLS_CAMELLIA_DECRYPT ) ? \"dec\" : \"enc\" );\n\n        memcpy( src, camellia_test_cbc_iv, 16 );\n        memcpy( dst, camellia_test_cbc_iv, 16 );\n        memcpy( key, camellia_test_cbc_key[u], 16 + 8 * u );\n\n        if( v == MBEDTLS_CAMELLIA_DECRYPT ) {\n            mbedtls_camellia_setkey_dec( &ctx, key, 128 + u * 64 );\n        } else {\n            mbedtls_camellia_setkey_enc( &ctx, key, 128 + u * 64 );\n        }\n\n        for( i = 0; i < CAMELLIA_TESTS_CBC; i++ ) {\n\n            if( v == MBEDTLS_CAMELLIA_DECRYPT ) {\n                memcpy( iv , src, 16 );\n                memcpy( src, camellia_test_cbc_cipher[u][i], 16 );\n                memcpy( dst, camellia_test_cbc_plain[i], 16 );\n            } else { /* MBEDTLS_CAMELLIA_ENCRYPT */\n                memcpy( iv , dst, 16 );\n                memcpy( src, camellia_test_cbc_plain[i], 16 );\n                memcpy( dst, camellia_test_cbc_cipher[u][i], 16 );\n            }\n\n            mbedtls_camellia_crypt_cbc( &ctx, v, 16, iv, src, buf );\n\n            if( memcmp( buf, dst, 16 ) != 0 )\n            {\n                if( verbose != 0 )\n                    mbedtls_printf( \"failed\\n\" );\n\n                return( 1 );\n            }\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    /*\n     * CTR mode\n     */\n    for( i = 0; i < 6; i++ )\n    {\n        u = i >> 1;\n        v = i  & 1;\n\n        if( verbose != 0 )\n            mbedtls_printf( \"  CAMELLIA-CTR-128 (%s): \",\n                             ( v == MBEDTLS_CAMELLIA_DECRYPT ) ? \"dec\" : \"enc\" );\n\n        memcpy( nonce_counter, camellia_test_ctr_nonce_counter[u], 16 );\n        memcpy( key, camellia_test_ctr_key[u], 16 );\n\n        offset = 0;\n        mbedtls_camellia_setkey_enc( &ctx, key, 128 );\n\n        if( v == MBEDTLS_CAMELLIA_DECRYPT )\n        {\n            len = camellia_test_ctr_len[u];\n            memcpy( buf, camellia_test_ctr_ct[u], len );\n\n            mbedtls_camellia_crypt_ctr( &ctx, len, &offset, nonce_counter, stream_block,\n                                buf, buf );\n\n            if( memcmp( buf, camellia_test_ctr_pt[u], len ) != 0 )\n            {\n                if( verbose != 0 )\n                    mbedtls_printf( \"failed\\n\" );\n\n                return( 1 );\n            }\n        }\n        else\n        {\n            len = camellia_test_ctr_len[u];\n            memcpy( buf, camellia_test_ctr_pt[u], len );\n\n            mbedtls_camellia_crypt_ctr( &ctx, len, &offset, nonce_counter, stream_block,\n                                buf, buf );\n\n            if( memcmp( buf, camellia_test_ctr_ct[u], len ) != 0 )\n            {\n                if( verbose != 0 )\n                    mbedtls_printf( \"failed\\n\" );\n\n                return( 1 );\n            }\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\n    return( 0 );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_CAMELLIA_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/ccm.c",
    "content": "/*\n *  NIST SP800-38C compliant CCM implementation\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n/*\n * Definition of CCM:\n * http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf\n * RFC 3610 \"Counter with CBC-MAC (CCM)\"\n *\n * Related:\n * RFC 5116 \"An Interface and Algorithms for Authenticated Encryption\"\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_CCM_C)\n\n#include \"mbedtls/ccm.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */\n\n#if !defined(MBEDTLS_CCM_ALT)\n\n#define CCM_ENCRYPT 0\n#define CCM_DECRYPT 1\n\n/*\n * Initialize context\n */\nvoid mbedtls_ccm_init( mbedtls_ccm_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_ccm_context ) );\n}\n\nint mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,\n                        mbedtls_cipher_id_t cipher,\n                        const unsigned char *key,\n                        unsigned int keybits )\n{\n    int ret;\n    const mbedtls_cipher_info_t *cipher_info;\n\n    cipher_info = mbedtls_cipher_info_from_values( cipher, keybits, MBEDTLS_MODE_ECB );\n    if( cipher_info == NULL )\n        return( MBEDTLS_ERR_CCM_BAD_INPUT );\n\n    if( cipher_info->block_size != 16 )\n        return( MBEDTLS_ERR_CCM_BAD_INPUT );\n\n    mbedtls_cipher_free( &ctx->cipher_ctx );\n\n    if( ( ret = mbedtls_cipher_setup( &ctx->cipher_ctx, cipher_info ) ) != 0 )\n        return( ret );\n\n    if( ( ret = mbedtls_cipher_setkey( &ctx->cipher_ctx, key, keybits,\n                               MBEDTLS_ENCRYPT ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    return( 0 );\n}\n\n/*\n * Free context\n */\nvoid mbedtls_ccm_free( mbedtls_ccm_context *ctx )\n{\n    mbedtls_cipher_free( &ctx->cipher_ctx );\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ccm_context ) );\n}\n\n/*\n * Macros for common operations.\n * Results in smaller compiled code than static inline functions.\n */\n\n/*\n * Update the CBC-MAC state in y using a block in b\n * (Always using b as the source helps the compiler optimise a bit better.)\n */\n#define UPDATE_CBC_MAC                                                      \\\n    for( i = 0; i < 16; i++ )                                               \\\n        y[i] ^= b[i];                                                       \\\n                                                                            \\\n    if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, y, 16, y, &olen ) ) != 0 ) \\\n        return( ret );\n\n/*\n * Encrypt or decrypt a partial block with CTR\n * Warning: using b for temporary storage! src and dst must not be b!\n * This avoids allocating one more 16 bytes buffer while allowing src == dst.\n */\n#define CTR_CRYPT( dst, src, len  )                                            \\\n    if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, ctr, 16, b, &olen ) ) != 0 )  \\\n        return( ret );                                                         \\\n                                                                               \\\n    for( i = 0; i < len; i++ )                                                 \\\n        dst[i] = src[i] ^ b[i];\n\n/*\n * Authenticated encryption or decryption\n */\nstatic int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,\n                           const unsigned char *iv, size_t iv_len,\n                           const unsigned char *add, size_t add_len,\n                           const unsigned char *input, unsigned char *output,\n                           unsigned char *tag, size_t tag_len )\n{\n    int ret;\n    unsigned char i;\n    unsigned char q;\n    size_t len_left, olen;\n    unsigned char b[16];\n    unsigned char y[16];\n    unsigned char ctr[16];\n    const unsigned char *src;\n    unsigned char *dst;\n\n    /*\n     * Check length requirements: SP800-38C A.1\n     * Additional requirement: a < 2^16 - 2^8 to simplify the code.\n     * 'length' checked later (when writing it to the first block)\n     *\n     * Also, loosen the requirements to enable support for CCM* (IEEE 802.15.4).\n     */\n    if( tag_len == 2 || tag_len > 16 || tag_len % 2 != 0 )\n        return( MBEDTLS_ERR_CCM_BAD_INPUT );\n\n    /* Also implies q is within bounds */\n    if( iv_len < 7 || iv_len > 13 )\n        return( MBEDTLS_ERR_CCM_BAD_INPUT );\n\n    if( add_len > 0xFF00 )\n        return( MBEDTLS_ERR_CCM_BAD_INPUT );\n\n    q = 16 - 1 - (unsigned char) iv_len;\n\n    /*\n     * First block B_0:\n     * 0        .. 0        flags\n     * 1        .. iv_len   nonce (aka iv)\n     * iv_len+1 .. 15       length\n     *\n     * With flags as (bits):\n     * 7        0\n     * 6        add present?\n     * 5 .. 3   (t - 2) / 2\n     * 2 .. 0   q - 1\n     */\n    b[0] = 0;\n    b[0] |= ( add_len > 0 ) << 6;\n    b[0] |= ( ( tag_len - 2 ) / 2 ) << 3;\n    b[0] |= q - 1;\n\n    memcpy( b + 1, iv, iv_len );\n\n    for( i = 0, len_left = length; i < q; i++, len_left >>= 8 )\n        b[15-i] = (unsigned char)( len_left & 0xFF );\n\n    if( len_left > 0 )\n        return( MBEDTLS_ERR_CCM_BAD_INPUT );\n\n\n    /* Start CBC-MAC with first block */\n    memset( y, 0, 16 );\n    UPDATE_CBC_MAC;\n\n    /*\n     * If there is additional data, update CBC-MAC with\n     * add_len, add, 0 (padding to a block boundary)\n     */\n    if( add_len > 0 )\n    {\n        size_t use_len;\n        len_left = add_len;\n        src = add;\n\n        memset( b, 0, 16 );\n        b[0] = (unsigned char)( ( add_len >> 8 ) & 0xFF );\n        b[1] = (unsigned char)( ( add_len      ) & 0xFF );\n\n        use_len = len_left < 16 - 2 ? len_left : 16 - 2;\n        memcpy( b + 2, src, use_len );\n        len_left -= use_len;\n        src += use_len;\n\n        UPDATE_CBC_MAC;\n\n        while( len_left > 0 )\n        {\n            use_len = len_left > 16 ? 16 : len_left;\n\n            memset( b, 0, 16 );\n            memcpy( b, src, use_len );\n            UPDATE_CBC_MAC;\n\n            len_left -= use_len;\n            src += use_len;\n        }\n    }\n\n    /*\n     * Prepare counter block for encryption:\n     * 0        .. 0        flags\n     * 1        .. iv_len   nonce (aka iv)\n     * iv_len+1 .. 15       counter (initially 1)\n     *\n     * With flags as (bits):\n     * 7 .. 3   0\n     * 2 .. 0   q - 1\n     */\n    ctr[0] = q - 1;\n    memcpy( ctr + 1, iv, iv_len );\n    memset( ctr + 1 + iv_len, 0, q );\n    ctr[15] = 1;\n\n    /*\n     * Authenticate and {en,de}crypt the message.\n     *\n     * The only difference between encryption and decryption is\n     * the respective order of authentication and {en,de}cryption.\n     */\n    len_left = length;\n    src = input;\n    dst = output;\n\n    while( len_left > 0 )\n    {\n        size_t use_len = len_left > 16 ? 16 : len_left;\n\n        if( mode == CCM_ENCRYPT )\n        {\n            memset( b, 0, 16 );\n            memcpy( b, src, use_len );\n            UPDATE_CBC_MAC;\n        }\n\n        CTR_CRYPT( dst, src, use_len );\n\n        if( mode == CCM_DECRYPT )\n        {\n            memset( b, 0, 16 );\n            memcpy( b, dst, use_len );\n            UPDATE_CBC_MAC;\n        }\n\n        dst += use_len;\n        src += use_len;\n        len_left -= use_len;\n\n        /*\n         * Increment counter.\n         * No need to check for overflow thanks to the length check above.\n         */\n        for( i = 0; i < q; i++ )\n            if( ++ctr[15-i] != 0 )\n                break;\n    }\n\n    /*\n     * Authentication: reset counter and crypt/mask internal tag\n     */\n    for( i = 0; i < q; i++ )\n        ctr[15-i] = 0;\n\n    CTR_CRYPT( y, y, 16 );\n    memcpy( tag, y, tag_len );\n\n    return( 0 );\n}\n\n/*\n * Authenticated encryption\n */\nint mbedtls_ccm_star_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,\n                         const unsigned char *iv, size_t iv_len,\n                         const unsigned char *add, size_t add_len,\n                         const unsigned char *input, unsigned char *output,\n                         unsigned char *tag, size_t tag_len )\n{\n    return( ccm_auth_crypt( ctx, CCM_ENCRYPT, length, iv, iv_len,\n                            add, add_len, input, output, tag, tag_len ) );\n}\n\nint mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,\n                         const unsigned char *iv, size_t iv_len,\n                         const unsigned char *add, size_t add_len,\n                         const unsigned char *input, unsigned char *output,\n                         unsigned char *tag, size_t tag_len )\n{\n    if( tag_len == 0 )\n        return( MBEDTLS_ERR_CCM_BAD_INPUT );\n\n    return( mbedtls_ccm_star_encrypt_and_tag( ctx, length, iv, iv_len, add,\n                add_len, input, output, tag, tag_len ) );\n}\n\n/*\n * Authenticated decryption\n */\nint mbedtls_ccm_star_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,\n                      const unsigned char *iv, size_t iv_len,\n                      const unsigned char *add, size_t add_len,\n                      const unsigned char *input, unsigned char *output,\n                      const unsigned char *tag, size_t tag_len )\n{\n    int ret;\n    unsigned char check_tag[16];\n    unsigned char i;\n    int diff;\n\n    if( ( ret = ccm_auth_crypt( ctx, CCM_DECRYPT, length,\n                                iv, iv_len, add, add_len,\n                                input, output, check_tag, tag_len ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    /* Check tag in \"constant-time\" */\n    for( diff = 0, i = 0; i < tag_len; i++ )\n        diff |= tag[i] ^ check_tag[i];\n\n    if( diff != 0 )\n    {\n        mbedtls_platform_zeroize( output, length );\n        return( MBEDTLS_ERR_CCM_AUTH_FAILED );\n    }\n\n    return( 0 );\n}\n\nint mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,\n                      const unsigned char *iv, size_t iv_len,\n                      const unsigned char *add, size_t add_len,\n                      const unsigned char *input, unsigned char *output,\n                      const unsigned char *tag, size_t tag_len )\n{\n    if( tag_len == 0 )\n        return( MBEDTLS_ERR_CCM_BAD_INPUT );\n\n    return( mbedtls_ccm_star_auth_decrypt( ctx, length, iv, iv_len, add,\n                add_len, input, output, tag, tag_len ) );\n}\n#endif /* !MBEDTLS_CCM_ALT */\n\n#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)\n/*\n * Examples 1 to 3 from SP800-38C Appendix C\n */\n\n#define NB_TESTS 3\n\n/*\n * The data is the same for all tests, only the used length changes\n */\nstatic const unsigned char key[] = {\n    0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,\n    0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f\n};\n\nstatic const unsigned char iv[] = {\n    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,\n    0x18, 0x19, 0x1a, 0x1b\n};\n\nstatic const unsigned char ad[] = {\n    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,\n    0x10, 0x11, 0x12, 0x13\n};\n\nstatic const unsigned char msg[] = {\n    0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,\n    0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,\n    0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,\n};\n\nstatic const size_t iv_len [NB_TESTS] = { 7, 8,  12 };\nstatic const size_t add_len[NB_TESTS] = { 8, 16, 20 };\nstatic const size_t msg_len[NB_TESTS] = { 4, 16, 24 };\nstatic const size_t tag_len[NB_TESTS] = { 4, 6,  8  };\n\nstatic const unsigned char res[NB_TESTS][32] = {\n    {   0x71, 0x62, 0x01, 0x5b, 0x4d, 0xac, 0x25, 0x5d },\n    {   0xd2, 0xa1, 0xf0, 0xe0, 0x51, 0xea, 0x5f, 0x62,\n        0x08, 0x1a, 0x77, 0x92, 0x07, 0x3d, 0x59, 0x3d,\n        0x1f, 0xc6, 0x4f, 0xbf, 0xac, 0xcd },\n    {   0xe3, 0xb2, 0x01, 0xa9, 0xf5, 0xb7, 0x1a, 0x7a,\n        0x9b, 0x1c, 0xea, 0xec, 0xcd, 0x97, 0xe7, 0x0b,\n        0x61, 0x76, 0xaa, 0xd9, 0xa4, 0x42, 0x8a, 0xa5,\n        0x48, 0x43, 0x92, 0xfb, 0xc1, 0xb0, 0x99, 0x51 }\n};\n\nint mbedtls_ccm_self_test( int verbose )\n{\n    mbedtls_ccm_context ctx;\n    unsigned char out[32];\n    size_t i;\n    int ret;\n\n    mbedtls_ccm_init( &ctx );\n\n    if( mbedtls_ccm_setkey( &ctx, MBEDTLS_CIPHER_ID_AES, key, 8 * sizeof key ) != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"  CCM: setup failed\" );\n\n        return( 1 );\n    }\n\n    for( i = 0; i < NB_TESTS; i++ )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"  CCM-AES #%u: \", (unsigned int) i + 1 );\n\n        ret = mbedtls_ccm_encrypt_and_tag( &ctx, msg_len[i],\n                                   iv, iv_len[i], ad, add_len[i],\n                                   msg, out,\n                                   out + msg_len[i], tag_len[i] );\n\n        if( ret != 0 ||\n            memcmp( out, res[i], msg_len[i] + tag_len[i] ) != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed\\n\" );\n\n            return( 1 );\n        }\n\n        ret = mbedtls_ccm_auth_decrypt( &ctx, msg_len[i],\n                                iv, iv_len[i], ad, add_len[i],\n                                res[i], out,\n                                res[i] + msg_len[i], tag_len[i] );\n\n        if( ret != 0 ||\n            memcmp( out, msg, msg_len[i] ) != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed\\n\" );\n\n            return( 1 );\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    mbedtls_ccm_free( &ctx );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    return( 0 );\n}\n\n#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */\n\n#endif /* MBEDTLS_CCM_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/certs.c",
    "content": "/*\n *  X.509 test certificates\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include \"mbedtls/certs.h\"\n\n#if defined(MBEDTLS_CERTS_C)\n\n#if defined(MBEDTLS_ECDSA_C)\n#define TEST_CA_CRT_EC                                                  \\\n\"-----BEGIN CERTIFICATE-----\\r\\n\"                                       \\\n\"MIICUjCCAdegAwIBAgIJAMFD4n5iQ8zoMAoGCCqGSM49BAMCMD4xCzAJBgNVBAYT\\r\\n\"  \\\n\"Ak5MMREwDwYDVQQKEwhQb2xhclNTTDEcMBoGA1UEAxMTUG9sYXJzc2wgVGVzdCBF\\r\\n\"  \\\n\"QyBDQTAeFw0xMzA5MjQxNTQ5NDhaFw0yMzA5MjIxNTQ5NDhaMD4xCzAJBgNVBAYT\\r\\n\"  \\\n\"Ak5MMREwDwYDVQQKEwhQb2xhclNTTDEcMBoGA1UEAxMTUG9sYXJzc2wgVGVzdCBF\\r\\n\"  \\\n\"QyBDQTB2MBAGByqGSM49AgEGBSuBBAAiA2IABMPaKzRBN1gvh1b+/Im6KUNLTuBu\\r\\n\"  \\\n\"ww5XUzM5WNRStJGVOQsj318XJGJI/BqVKc4sLYfCiFKAr9ZqqyHduNMcbli4yuiy\\r\\n\"  \\\n\"aY7zQa0pw7RfdadHb9UZKVVpmlM7ILRmFmAzHqOBoDCBnTAdBgNVHQ4EFgQUnW0g\\r\\n\"  \\\n\"JEkBPyvLeLUZvH4kydv7NnwwbgYDVR0jBGcwZYAUnW0gJEkBPyvLeLUZvH4kydv7\\r\\n\"  \\\n\"NnyhQqRAMD4xCzAJBgNVBAYTAk5MMREwDwYDVQQKEwhQb2xhclNTTDEcMBoGA1UE\\r\\n\"  \\\n\"AxMTUG9sYXJzc2wgVGVzdCBFQyBDQYIJAMFD4n5iQ8zoMAwGA1UdEwQFMAMBAf8w\\r\\n\"  \\\n\"CgYIKoZIzj0EAwIDaQAwZgIxAMO0YnNWKJUAfXgSJtJxexn4ipg+kv4znuR50v56\\r\\n\"  \\\n\"t4d0PCu412mUC6Nnd7izvtE2MgIxAP1nnJQjZ8BWukszFQDG48wxCCyci9qpdSMv\\r\\n\"  \\\n\"uCjn8pwUOkABXK8Mss90fzCfCEOtIA==\\r\\n\"                                  \\\n\"-----END CERTIFICATE-----\\r\\n\"\nconst char mbedtls_test_ca_crt_ec[] = TEST_CA_CRT_EC;\nconst size_t mbedtls_test_ca_crt_ec_len = sizeof( mbedtls_test_ca_crt_ec );\n\nconst char mbedtls_test_ca_key_ec[] =\n\"-----BEGIN EC PRIVATE KEY-----\\r\\n\"\n\"Proc-Type: 4,ENCRYPTED\\r\\n\"\n\"DEK-Info: DES-EDE3-CBC,307EAB469933D64E\\r\\n\"\n\"\\r\\n\"\n\"IxbrRmKcAzctJqPdTQLA4SWyBYYGYJVkYEna+F7Pa5t5Yg/gKADrFKcm6B72e7DG\\r\\n\"\n\"ihExtZI648s0zdYw6qSJ74vrPSuWDe5qm93BqsfVH9svtCzWHW0pm1p0KTBCFfUq\\r\\n\"\n\"UsuWTITwJImcnlAs1gaRZ3sAWm7cOUidL0fo2G0fYUFNcYoCSLffCFTEHBuPnagb\\r\\n\"\n\"a77x/sY1Bvii8S9/XhDTb6pTMx06wzrm\\r\\n\"\n\"-----END EC PRIVATE KEY-----\\r\\n\";\nconst size_t mbedtls_test_ca_key_ec_len = sizeof( mbedtls_test_ca_key_ec );\n\nconst char mbedtls_test_ca_pwd_ec[] = \"PolarSSLTest\";\nconst size_t mbedtls_test_ca_pwd_ec_len = sizeof( mbedtls_test_ca_pwd_ec ) - 1;\n\nconst char mbedtls_test_srv_crt_ec[] =\n\"-----BEGIN CERTIFICATE-----\\r\\n\"\n\"MIICHzCCAaWgAwIBAgIBCTAKBggqhkjOPQQDAjA+MQswCQYDVQQGEwJOTDERMA8G\\r\\n\"\n\"A1UEChMIUG9sYXJTU0wxHDAaBgNVBAMTE1BvbGFyc3NsIFRlc3QgRUMgQ0EwHhcN\\r\\n\"\n\"MTMwOTI0MTU1MjA0WhcNMjMwOTIyMTU1MjA0WjA0MQswCQYDVQQGEwJOTDERMA8G\\r\\n\"\n\"A1UEChMIUG9sYXJTU0wxEjAQBgNVBAMTCWxvY2FsaG9zdDBZMBMGByqGSM49AgEG\\r\\n\"\n\"CCqGSM49AwEHA0IABDfMVtl2CR5acj7HWS3/IG7ufPkGkXTQrRS192giWWKSTuUA\\r\\n\"\n\"2CMR/+ov0jRdXRa9iojCa3cNVc2KKg76Aci07f+jgZ0wgZowCQYDVR0TBAIwADAd\\r\\n\"\n\"BgNVHQ4EFgQUUGGlj9QH2deCAQzlZX+MY0anE74wbgYDVR0jBGcwZYAUnW0gJEkB\\r\\n\"\n\"PyvLeLUZvH4kydv7NnyhQqRAMD4xCzAJBgNVBAYTAk5MMREwDwYDVQQKEwhQb2xh\\r\\n\"\n\"clNTTDEcMBoGA1UEAxMTUG9sYXJzc2wgVGVzdCBFQyBDQYIJAMFD4n5iQ8zoMAoG\\r\\n\"\n\"CCqGSM49BAMCA2gAMGUCMQCaLFzXptui5WQN8LlO3ddh1hMxx6tzgLvT03MTVK2S\\r\\n\"\n\"C12r0Lz3ri/moSEpNZWqPjkCMCE2f53GXcYLqyfyJR078c/xNSUU5+Xxl7VZ414V\\r\\n\"\n\"fGa5kHvHARBPc8YAIVIqDvHH1Q==\\r\\n\"\n\"-----END CERTIFICATE-----\\r\\n\";\nconst size_t mbedtls_test_srv_crt_ec_len = sizeof( mbedtls_test_srv_crt_ec );\n\nconst char mbedtls_test_srv_key_ec[] =\n\"-----BEGIN EC PRIVATE KEY-----\\r\\n\"\n\"MHcCAQEEIPEqEyB2AnCoPL/9U/YDHvdqXYbIogTywwyp6/UfDw6noAoGCCqGSM49\\r\\n\"\n\"AwEHoUQDQgAEN8xW2XYJHlpyPsdZLf8gbu58+QaRdNCtFLX3aCJZYpJO5QDYIxH/\\r\\n\"\n\"6i/SNF1dFr2KiMJrdw1VzYoqDvoByLTt/w==\\r\\n\"\n\"-----END EC PRIVATE KEY-----\\r\\n\";\nconst size_t mbedtls_test_srv_key_ec_len = sizeof( mbedtls_test_srv_key_ec );\n\nconst char mbedtls_test_cli_crt_ec[] =\n\"-----BEGIN CERTIFICATE-----\\r\\n\"\n\"MIICLDCCAbKgAwIBAgIBDTAKBggqhkjOPQQDAjA+MQswCQYDVQQGEwJOTDERMA8G\\r\\n\"\n\"A1UEChMIUG9sYXJTU0wxHDAaBgNVBAMTE1BvbGFyc3NsIFRlc3QgRUMgQ0EwHhcN\\r\\n\"\n\"MTMwOTI0MTU1MjA0WhcNMjMwOTIyMTU1MjA0WjBBMQswCQYDVQQGEwJOTDERMA8G\\r\\n\"\n\"A1UEChMIUG9sYXJTU0wxHzAdBgNVBAMTFlBvbGFyU1NMIFRlc3QgQ2xpZW50IDIw\\r\\n\"\n\"WTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAARX5a6xc9/TrLuTuIH/Eq7u5lOszlVT\\r\\n\"\n\"9jQOzC7jYyUL35ji81xgNpbA1RgUcOV/n9VLRRjlsGzVXPiWj4dwo+THo4GdMIGa\\r\\n\"\n\"MAkGA1UdEwQCMAAwHQYDVR0OBBYEFHoAX4Zk/OBd5REQO7LmO8QmP8/iMG4GA1Ud\\r\\n\"\n\"IwRnMGWAFJ1tICRJAT8ry3i1Gbx+JMnb+zZ8oUKkQDA+MQswCQYDVQQGEwJOTDER\\r\\n\"\n\"MA8GA1UEChMIUG9sYXJTU0wxHDAaBgNVBAMTE1BvbGFyc3NsIFRlc3QgRUMgQ0GC\\r\\n\"\n\"CQDBQ+J+YkPM6DAKBggqhkjOPQQDAgNoADBlAjBKZQ17IIOimbmoD/yN7o89u3BM\\r\\n\"\n\"lgOsjnhw3fIOoLIWy2WOGsk/LGF++DzvrRzuNiACMQCd8iem1XS4JK7haj8xocpU\\r\\n\"\n\"LwjQje5PDGHfd3h9tP38Qknu5bJqws0md2KOKHyeV0U=\\r\\n\"\n\"-----END CERTIFICATE-----\\r\\n\";\nconst size_t mbedtls_test_cli_crt_ec_len = sizeof( mbedtls_test_cli_crt_ec );\n\nconst char mbedtls_test_cli_key_ec[] =\n\"-----BEGIN EC PRIVATE KEY-----\\r\\n\"\n\"MHcCAQEEIPb3hmTxZ3/mZI3vyk7p3U3wBf+WIop6hDhkFzJhmLcqoAoGCCqGSM49\\r\\n\"\n\"AwEHoUQDQgAEV+WusXPf06y7k7iB/xKu7uZTrM5VU/Y0Dswu42MlC9+Y4vNcYDaW\\r\\n\"\n\"wNUYFHDlf5/VS0UY5bBs1Vz4lo+HcKPkxw==\\r\\n\"\n\"-----END EC PRIVATE KEY-----\\r\\n\";\nconst size_t mbedtls_test_cli_key_ec_len = sizeof( mbedtls_test_cli_key_ec );\n#endif /* MBEDTLS_ECDSA_C */\n\n#if defined(MBEDTLS_RSA_C)\n\n#if defined(MBEDTLS_SHA256_C)\n#define TEST_CA_CRT_RSA_SHA256                                          \\\n\"-----BEGIN CERTIFICATE-----\\r\\n\"                                       \\\n\"MIIDhzCCAm+gAwIBAgIBADANBgkqhkiG9w0BAQsFADA7MQswCQYDVQQGEwJOTDER\\r\\n\"  \\\n\"MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\\r\\n\"  \\\n\"MTcwNTA0MTY1NzAxWhcNMjcwNTA1MTY1NzAxWjA7MQswCQYDVQQGEwJOTDERMA8G\\r\\n\"  \\\n\"A1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwggEiMA0G\\r\\n\"  \\\n\"CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDA3zf8F7vglp0/ht6WMn1EpRagzSHx\\r\\n\"  \\\n\"mdTs6st8GFgIlKXsm8WL3xoemTiZhx57wI053zhdcHgH057Zk+i5clHFzqMwUqny\\r\\n\"  \\\n\"50BwFMtEonILwuVA+T7lpg6z+exKY8C4KQB0nFc7qKUEkHHxvYPZP9al4jwqj+8n\\r\\n\"  \\\n\"YMPGn8u67GB9t+aEMr5P+1gmIgNb1LTV+/Xjli5wwOQuvfwu7uJBVcA0Ln0kcmnL\\r\\n\"  \\\n\"R7EUQIN9Z/SG9jGr8XmksrUuEvmEF/Bibyc+E1ixVA0hmnM3oTDPb5Lc9un8rNsu\\r\\n\"  \\\n\"KNF+AksjoBXyOGVkCeoMbo4bF6BxyLObyavpw/LPh5aPgAIynplYb6LVAgMBAAGj\\r\\n\"  \\\n\"gZUwgZIwHQYDVR0OBBYEFLRa5KWz3tJS9rnVppUP6z68x/3/MGMGA1UdIwRcMFqA\\r\\n\"  \\\n\"FLRa5KWz3tJS9rnVppUP6z68x/3/oT+kPTA7MQswCQYDVQQGEwJOTDERMA8GA1UE\\r\\n\"  \\\n\"CgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0GCAQAwDAYDVR0T\\r\\n\"  \\\n\"BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAHK/HHrTZMnnVMpde1io+voAtql7j\\r\\n\"  \\\n\"4sRhLrjD7o3THtwRbDa2diCvpq0Sq23Ng2LMYoXsOxoL/RQK3iN7UKxV3MKPEr0w\\r\\n\"  \\\n\"XQS+kKQqiT2bsfrjnWMVHZtUOMpm6FNqcdGm/Rss3vKda2lcKl8kUnq/ylc1+QbB\\r\\n\"  \\\n\"G6A6tUvQcr2ZyWfVg+mM5XkhTrOOXus2OLikb4WwEtJTJRNE0f+yPODSUz0/vT57\\r\\n\"  \\\n\"ApH0CnB80bYJshYHPHHymOtleAB8KSYtqm75g/YNobjnjB6cm4HkW3OZRVIl6fYY\\r\\n\"  \\\n\"n20NRVA1Vjs6GAROr4NqW4k/+LofY9y0LLDE+p0oIEKXIsIvhPr39swxSA==\\r\\n\"      \\\n\"-----END CERTIFICATE-----\\r\\n\"\n\nconst char   mbedtls_test_ca_crt_rsa[]   = TEST_CA_CRT_RSA_SHA256;\nconst size_t mbedtls_test_ca_crt_rsa_len = sizeof( mbedtls_test_ca_crt_rsa );\n#define TEST_CA_CRT_RSA_SOME\n\nstatic const char mbedtls_test_ca_crt_rsa_sha256[] = TEST_CA_CRT_RSA_SHA256;\n\n#endif\n\n#if !defined(TEST_CA_CRT_RSA_SOME) || defined(MBEDTLS_SHA1_C)\n#define TEST_CA_CRT_RSA_SHA1                                            \\\n\"-----BEGIN CERTIFICATE-----\\r\\n\"                                       \\\n\"MIIDhzCCAm+gAwIBAgIBADANBgkqhkiG9w0BAQUFADA7MQswCQYDVQQGEwJOTDER\\r\\n\"  \\\n\"MA8GA1UEChMIUG9sYXJTU0wxGTAXBgNVBAMTEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\\r\\n\"  \\\n\"MTEwMjEyMTQ0NDAwWhcNMjEwMjEyMTQ0NDAwWjA7MQswCQYDVQQGEwJOTDERMA8G\\r\\n\"  \\\n\"A1UEChMIUG9sYXJTU0wxGTAXBgNVBAMTEFBvbGFyU1NMIFRlc3QgQ0EwggEiMA0G\\r\\n\"  \\\n\"CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDA3zf8F7vglp0/ht6WMn1EpRagzSHx\\r\\n\"  \\\n\"mdTs6st8GFgIlKXsm8WL3xoemTiZhx57wI053zhdcHgH057Zk+i5clHFzqMwUqny\\r\\n\"  \\\n\"50BwFMtEonILwuVA+T7lpg6z+exKY8C4KQB0nFc7qKUEkHHxvYPZP9al4jwqj+8n\\r\\n\"  \\\n\"YMPGn8u67GB9t+aEMr5P+1gmIgNb1LTV+/Xjli5wwOQuvfwu7uJBVcA0Ln0kcmnL\\r\\n\"  \\\n\"R7EUQIN9Z/SG9jGr8XmksrUuEvmEF/Bibyc+E1ixVA0hmnM3oTDPb5Lc9un8rNsu\\r\\n\"  \\\n\"KNF+AksjoBXyOGVkCeoMbo4bF6BxyLObyavpw/LPh5aPgAIynplYb6LVAgMBAAGj\\r\\n\"  \\\n\"gZUwgZIwDAYDVR0TBAUwAwEB/zAdBgNVHQ4EFgQUtFrkpbPe0lL2udWmlQ/rPrzH\\r\\n\"  \\\n\"/f8wYwYDVR0jBFwwWoAUtFrkpbPe0lL2udWmlQ/rPrzH/f+hP6Q9MDsxCzAJBgNV\\r\\n\"  \\\n\"BAYTAk5MMREwDwYDVQQKEwhQb2xhclNTTDEZMBcGA1UEAxMQUG9sYXJTU0wgVGVz\\r\\n\"  \\\n\"dCBDQYIBADANBgkqhkiG9w0BAQUFAAOCAQEAuP1U2ABUkIslsCfdlc2i94QHHYeJ\\r\\n\"  \\\n\"SsR4EdgHtdciUI5I62J6Mom+Y0dT/7a+8S6MVMCZP6C5NyNyXw1GWY/YR82XTJ8H\\r\\n\"  \\\n\"DBJiCTok5DbZ6SzaONBzdWHXwWwmi5vg1dxn7YxrM9d0IjxM27WNKs4sDQhZBQkF\\r\\n\"  \\\n\"pjmfs2cb4oPl4Y9T9meTx/lvdkRYEug61Jfn6cA+qHpyPYdTH+UshITnmp5/Ztkf\\r\\n\"  \\\n\"m/UTSLBNFNHesiTZeH31NcxYGdHSme9Nc/gfidRa0FLOCfWxRlFqAI47zG9jAQCZ\\r\\n\"  \\\n\"7Z2mCGDNMhjQc+BYcdnl0lPXjdDK6V0qCg1dVewhUBcW5gZKzV7e9+DpVA==\\r\\n\"      \\\n\"-----END CERTIFICATE-----\\r\\n\"\n\n#if !defined (TEST_CA_CRT_RSA_SOME)\nconst char   mbedtls_test_ca_crt_rsa[]   = TEST_CA_CRT_RSA_SHA1;\nconst size_t mbedtls_test_ca_crt_rsa_len = sizeof( mbedtls_test_ca_crt_rsa );\n#endif\n\nstatic const char mbedtls_test_ca_crt_rsa_sha1[] = TEST_CA_CRT_RSA_SHA1;\n\n#endif\n\nconst char mbedtls_test_ca_key_rsa[] =\n\"-----BEGIN RSA PRIVATE KEY-----\\r\\n\"\n\"Proc-Type: 4,ENCRYPTED\\r\\n\"\n\"DEK-Info: DES-EDE3-CBC,A8A95B05D5B7206B\\r\\n\"\n\"\\r\\n\"\n\"9Qd9GeArejl1GDVh2lLV1bHt0cPtfbh5h/5zVpAVaFpqtSPMrElp50Rntn9et+JA\\r\\n\"\n\"7VOyboR+Iy2t/HU4WvA687k3Bppe9GwKHjHhtl//8xFKwZr3Xb5yO5JUP8AUctQq\\r\\n\"\n\"Nb8CLlZyuUC+52REAAthdWgsX+7dJO4yabzUcQ22Tp9JSD0hiL43BlkWYUNK3dAo\\r\\n\"\n\"PZlmiptjnzVTjg1MxsBSydZinWOLBV8/JQgxSPo2yD4uEfig28qbvQ2wNIn0pnAb\\r\\n\"\n\"GxnSAOazkongEGfvcjIIs+LZN9gXFhxcOh6kc4Q/c99B7QWETwLLkYgZ+z1a9VY9\\r\\n\"\n\"gEU7CwCxYCD+h9hY6FPmsK0/lC4O7aeRKpYq00rPPxs6i7phiexg6ax6yTMmArQq\\r\\n\"\n\"QmK3TAsJm8V/J5AWpLEV6jAFgRGymGGHnof0DXzVWZidrcZJWTNuGEX90nB3ee2w\\r\\n\"\n\"PXJEFWKoD3K3aFcSLdHYr3mLGxP7H9ThQai9VsycxZKS5kwvBKQ//YMrmFfwPk8x\\r\\n\"\n\"vTeY4KZMaUrveEel5tWZC94RSMKgxR6cyE1nBXyTQnDOGbfpNNgBKxyKbINWoOJU\\r\\n\"\n\"WJZAwlsQn+QzCDwpri7+sV1mS3gBE6UY7aQmnmiiaC2V3Hbphxct/en5QsfDOt1X\\r\\n\"\n\"JczSfpRWLlbPznZg8OQh/VgCMA58N5DjOzTIK7sJJ5r+94ZBTCpgAMbF588f0NTR\\r\\n\"\n\"KCe4yrxGJR7X02M4nvD4IwOlpsQ8xQxZtOSgXv4LkxvdU9XJJKWZ/XNKJeWztxSe\\r\\n\"\n\"Z1vdTc2YfsDBA2SEv33vxHx2g1vqtw8SjDRT2RaQSS0QuSaMJimdOX6mTOCBKk1J\\r\\n\"\n\"9Q5mXTrER+/LnK0jEmXsBXWA5bqqVZIyahXSx4VYZ7l7w/PHiUDtDgyRhMMKi4n2\\r\\n\"\n\"iQvQcWSQTjrpnlJbca1/DkpRt3YwrvJwdqb8asZU2VrNETh5x0QVefDRLFiVpif/\\r\\n\"\n\"tUaeAe/P1F8OkS7OIZDs1SUbv/sD2vMbhNkUoCms3/PvNtdnvgL4F0zhaDpKCmlT\\r\\n\"\n\"P8vx49E7v5CyRNmED9zZg4o3wmMqrQO93PtTug3Eu9oVx1zPQM1NVMyBa2+f29DL\\r\\n\"\n\"1nuTCeXdo9+ni45xx+jAI4DCwrRdhJ9uzZyC6962H37H6D+5naNvClFR1s6li1Gb\\r\\n\"\n\"nqPoiy/OBsEx9CaDGcqQBp5Wme/3XW+6z1ISOx+igwNTVCT14mHdBMbya0eIKft5\\r\\n\"\n\"X+GnwtgEMyCYyyWuUct8g4RzErcY9+yW9Om5Hzpx4zOuW4NPZgPDTgK+t2RSL/Yq\\r\\n\"\n\"rE1njrgeGYcVeG3f+OftH4s6fPbq7t1A5ZgUscbLMBqr9tK+OqygR4EgKBPsH6Cz\\r\\n\"\n\"L6zlv/2RV0qAHvVuDJcIDIgwY5rJtINEm32rhOeFNJwZS5MNIC1czXZx5//ugX7l\\r\\n\"\n\"I4sy5nbVhwSjtAk8Xg5dZbdTZ6mIrb7xqH+fdakZor1khG7bC2uIwibD3cSl2XkR\\r\\n\"\n\"wN48lslbHnqqagr6Xm1nNOSVl8C/6kbJEsMpLhAezfRtGwvOucoaE+WbeUNolGde\\r\\n\"\n\"P/eQiddSf0brnpiLJRh7qZrl9XuqYdpUqnoEdMAfotDOID8OtV7gt8a48ad8VPW2\\r\\n\"\n\"-----END RSA PRIVATE KEY-----\\r\\n\";\nconst size_t mbedtls_test_ca_key_rsa_len = sizeof( mbedtls_test_ca_key_rsa );\n\nconst char mbedtls_test_ca_pwd_rsa[] = \"PolarSSLTest\";\nconst size_t mbedtls_test_ca_pwd_rsa_len = sizeof( mbedtls_test_ca_pwd_rsa ) - 1;\n\nconst char mbedtls_test_srv_crt_rsa[] =\n\"-----BEGIN CERTIFICATE-----\\r\\n\"\n\"MIIDNzCCAh+gAwIBAgIBAjANBgkqhkiG9w0BAQUFADA7MQswCQYDVQQGEwJOTDER\\r\\n\"\n\"MA8GA1UEChMIUG9sYXJTU0wxGTAXBgNVBAMTEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\\r\\n\"\n\"MTEwMjEyMTQ0NDA2WhcNMjEwMjEyMTQ0NDA2WjA0MQswCQYDVQQGEwJOTDERMA8G\\r\\n\"\n\"A1UEChMIUG9sYXJTU0wxEjAQBgNVBAMTCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcN\\r\\n\"\n\"AQEBBQADggEPADCCAQoCggEBAMFNo93nzR3RBNdJcriZrA545Do8Ss86ExbQWuTN\\r\\n\"\n\"owCIp+4ea5anUrSQ7y1yej4kmvy2NKwk9XfgJmSMnLAofaHa6ozmyRyWvP7BBFKz\\r\\n\"\n\"NtSj+uGxdtiQwWG0ZlI2oiZTqqt0Xgd9GYLbKtgfoNkNHC1JZvdbJXNG6AuKT2kM\\r\\n\"\n\"tQCQ4dqCEGZ9rlQri2V5kaHiYcPNQEkI7mgM8YuG0ka/0LiqEQMef1aoGh5EGA8P\\r\\n\"\n\"hYvai0Re4hjGYi/HZo36Xdh98yeJKQHFkA4/J/EwyEoO79bex8cna8cFPXrEAjya\\r\\n\"\n\"HT4P6DSYW8tzS1KW2BGiLICIaTla0w+w3lkvEcf36hIBMJcCAwEAAaNNMEswCQYD\\r\\n\"\n\"VR0TBAIwADAdBgNVHQ4EFgQUpQXoZLjc32APUBJNYKhkr02LQ5MwHwYDVR0jBBgw\\r\\n\"\n\"FoAUtFrkpbPe0lL2udWmlQ/rPrzH/f8wDQYJKoZIhvcNAQEFBQADggEBAJxnXClY\\r\\n\"\n\"oHkbp70cqBrsGXLybA74czbO5RdLEgFs7rHVS9r+c293luS/KdliLScZqAzYVylw\\r\\n\"\n\"UfRWvKMoWhHYKp3dEIS4xTXk6/5zXxhv9Rw8SGc8qn6vITHk1S1mPevtekgasY5Y\\r\\n\"\n\"iWQuM3h4YVlRH3HHEMAD1TnAexfXHHDFQGe+Bd1iAbz1/sH9H8l4StwX6egvTK3M\\r\\n\"\n\"wXRwkKkvjKaEDA9ATbZx0mI8LGsxSuCqe9r9dyjmttd47J1p1Rulz3CLzaRcVIuS\\r\\n\"\n\"RRQfaD8neM9c1S/iJ/amTVqJxA1KOdOS5780WhPfSArA+g4qAmSjelc3p4wWpha8\\r\\n\"\n\"zhuYwjVuX6JHG0c=\\r\\n\"\n\"-----END CERTIFICATE-----\\r\\n\";\nconst size_t mbedtls_test_srv_crt_rsa_len = sizeof( mbedtls_test_srv_crt_rsa );\n\nconst char mbedtls_test_srv_key_rsa[] =\n\"-----BEGIN RSA PRIVATE KEY-----\\r\\n\"\n\"MIIEpAIBAAKCAQEAwU2j3efNHdEE10lyuJmsDnjkOjxKzzoTFtBa5M2jAIin7h5r\\r\\n\"\n\"lqdStJDvLXJ6PiSa/LY0rCT1d+AmZIycsCh9odrqjObJHJa8/sEEUrM21KP64bF2\\r\\n\"\n\"2JDBYbRmUjaiJlOqq3ReB30Zgtsq2B+g2Q0cLUlm91slc0boC4pPaQy1AJDh2oIQ\\r\\n\"\n\"Zn2uVCuLZXmRoeJhw81ASQjuaAzxi4bSRr/QuKoRAx5/VqgaHkQYDw+Fi9qLRF7i\\r\\n\"\n\"GMZiL8dmjfpd2H3zJ4kpAcWQDj8n8TDISg7v1t7HxydrxwU9esQCPJodPg/oNJhb\\r\\n\"\n\"y3NLUpbYEaIsgIhpOVrTD7DeWS8Rx/fqEgEwlwIDAQABAoIBAQCXR0S8EIHFGORZ\\r\\n\"\n\"++AtOg6eENxD+xVs0f1IeGz57Tjo3QnXX7VBZNdj+p1ECvhCE/G7XnkgU5hLZX+G\\r\\n\"\n\"Z0jkz/tqJOI0vRSdLBbipHnWouyBQ4e/A1yIJdlBtqXxJ1KE/ituHRbNc4j4kL8Z\\r\\n\"\n\"/r6pvwnTI0PSx2Eqs048YdS92LT6qAv4flbNDxMn2uY7s4ycS4Q8w1JXnCeaAnYm\\r\\n\"\n\"WYI5wxO+bvRELR2Mcz5DmVnL8jRyml6l6582bSv5oufReFIbyPZbQWlXgYnpu6He\\r\\n\"\n\"GTc7E1zKYQGG/9+DQUl/1vQuCPqQwny0tQoX2w5tdYpdMdVm+zkLtbajzdTviJJa\\r\\n\"\n\"TWzL6lt5AoGBAN86+SVeJDcmQJcv4Eq6UhtRr4QGMiQMz0Sod6ettYxYzMgxtw28\\r\\n\"\n\"CIrgpozCc+UaZJLo7UxvC6an85r1b2nKPCLQFaggJ0H4Q0J/sZOhBIXaoBzWxveK\\r\\n\"\n\"nupceKdVxGsFi8CDy86DBfiyFivfBj+47BbaQzPBj7C4rK7UlLjab2rDAoGBAN2u\\r\\n\"\n\"AM2gchoFiu4v1HFL8D7lweEpi6ZnMJjnEu/dEgGQJFjwdpLnPbsj4c75odQ4Gz8g\\r\\n\"\n\"sw9lao9VVzbusoRE/JGI4aTdO0pATXyG7eG1Qu+5Yc1YGXcCrliA2xM9xx+d7f+s\\r\\n\"\n\"mPzN+WIEg5GJDYZDjAzHG5BNvi/FfM1C9dOtjv2dAoGAF0t5KmwbjWHBhcVqO4Ic\\r\\n\"\n\"BVvN3BIlc1ue2YRXEDlxY5b0r8N4XceMgKmW18OHApZxfl8uPDauWZLXOgl4uepv\\r\\n\"\n\"whZC3EuWrSyyICNhLY21Ah7hbIEBPF3L3ZsOwC+UErL+dXWLdB56Jgy3gZaBeW7b\\r\\n\"\n\"vDrEnocJbqCm7IukhXHOBK8CgYEAwqdHB0hqyNSzIOGY7v9abzB6pUdA3BZiQvEs\\r\\n\"\n\"3LjHVd4HPJ2x0N8CgrBIWOE0q8+0hSMmeE96WW/7jD3fPWwCR5zlXknxBQsfv0gP\\r\\n\"\n\"3BC5PR0Qdypz+d+9zfMf625kyit4T/hzwhDveZUzHnk1Cf+IG7Q+TOEnLnWAWBED\\r\\n\"\n\"ISOWmrUCgYAFEmRxgwAc/u+D6t0syCwAYh6POtscq9Y0i9GyWk89NzgC4NdwwbBH\\r\\n\"\n\"4AgahOxIxXx2gxJnq3yfkJfIjwf0s2DyP0kY2y6Ua1OeomPeY9mrIS4tCuDQ6LrE\\r\\n\"\n\"TB6l9VGoxJL4fyHnZb8L5gGvnB1bbD8cL6YPaDiOhcRseC9vBiEuVg==\\r\\n\"\n\"-----END RSA PRIVATE KEY-----\\r\\n\";\nconst size_t mbedtls_test_srv_key_rsa_len = sizeof( mbedtls_test_srv_key_rsa );\n\nconst char mbedtls_test_cli_crt_rsa[] =\n\"-----BEGIN CERTIFICATE-----\\r\\n\"\n\"MIIDhTCCAm2gAwIBAgIBBDANBgkqhkiG9w0BAQsFADA7MQswCQYDVQQGEwJOTDER\\r\\n\"\n\"MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\\r\\n\"\n\"MTcwNTA1MTMwNzU5WhcNMjcwNTA2MTMwNzU5WjA8MQswCQYDVQQGEwJOTDERMA8G\\r\\n\"\n\"A1UECgwIUG9sYXJTU0wxGjAYBgNVBAMMEVBvbGFyU1NMIENsaWVudCAyMIIBIjAN\\r\\n\"\n\"BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyHTEzLn5tXnpRdkUYLB9u5Pyax6f\\r\\n\"\n\"M60Nj4o8VmXl3ETZzGaFB9X4J7BKNdBjngpuG7fa8H6r7gwQk4ZJGDTzqCrSV/Uu\\r\\n\"\n\"1C93KYRhTYJQj6eVSHD1bk2y1RPD0hrt5kPqQhTrdOrA7R/UV06p86jt0uDBMHEw\\r\\n\"\n\"MjDV0/YI0FZPRo7yX/k9Z5GIMC5Cst99++UMd//sMcB4j7/Cf8qtbCHWjdmLao5v\\r\\n\"\n\"4Jv4EFbMs44TFeY0BGbH7vk2DmqV9gmaBmf0ZXH4yqSxJeD+PIs1BGe64E92hfx/\\r\\n\"\n\"/DZrtenNLQNiTrM9AM+vdqBpVoNq0qjU51Bx5rU2BXcFbXvI5MT9TNUhXwIDAQAB\\r\\n\"\n\"o4GSMIGPMB0GA1UdDgQWBBRxoQBzckAvVHZeM/xSj7zx3WtGITBjBgNVHSMEXDBa\\r\\n\"\n\"gBS0WuSls97SUva51aaVD+s+vMf9/6E/pD0wOzELMAkGA1UEBhMCTkwxETAPBgNV\\r\\n\"\n\"BAoMCFBvbGFyU1NMMRkwFwYDVQQDDBBQb2xhclNTTCBUZXN0IENBggEAMAkGA1Ud\\r\\n\"\n\"EwQCMAAwDQYJKoZIhvcNAQELBQADggEBAC7yO786NvcHpK8UovKIG9cB32oSQQom\\r\\n\"\n\"LoR0eHDRzdqEkoq7yGZufHFiRAAzbMqJfogRtxlrWAeB4y/jGaMBV25IbFOIcH2W\\r\\n\"\n\"iCEaMMbG+VQLKNvuC63kmw/Zewc9ThM6Pa1Hcy0axT0faf1B/U01j0FIcw/6mTfK\\r\\n\"\n\"D8w48OIwc1yr0JtutCVjig5DC0yznGMt32RyseOLcUe+lfq005v2PAiCozr5X8rE\\r\\n\"\n\"ofGZpiM2NqRPePgYy+Vc75Zk28xkRQq1ncprgQb3S4vTsZdScpM9hLf+eMlrgqlj\\r\\n\"\n\"c5PLSkXBeLE5+fedkyfTaLxxQlgCpuoOhKBm04/R1pWNzUHyqagjO9Q=\\r\\n\"\n\"-----END CERTIFICATE-----\\r\\n\";\nconst size_t mbedtls_test_cli_crt_rsa_len = sizeof( mbedtls_test_cli_crt_rsa );\n\nconst char mbedtls_test_cli_key_rsa[] =\n\"-----BEGIN RSA PRIVATE KEY-----\\r\\n\"\n\"MIIEpAIBAAKCAQEAyHTEzLn5tXnpRdkUYLB9u5Pyax6fM60Nj4o8VmXl3ETZzGaF\\r\\n\"\n\"B9X4J7BKNdBjngpuG7fa8H6r7gwQk4ZJGDTzqCrSV/Uu1C93KYRhTYJQj6eVSHD1\\r\\n\"\n\"bk2y1RPD0hrt5kPqQhTrdOrA7R/UV06p86jt0uDBMHEwMjDV0/YI0FZPRo7yX/k9\\r\\n\"\n\"Z5GIMC5Cst99++UMd//sMcB4j7/Cf8qtbCHWjdmLao5v4Jv4EFbMs44TFeY0BGbH\\r\\n\"\n\"7vk2DmqV9gmaBmf0ZXH4yqSxJeD+PIs1BGe64E92hfx//DZrtenNLQNiTrM9AM+v\\r\\n\"\n\"dqBpVoNq0qjU51Bx5rU2BXcFbXvI5MT9TNUhXwIDAQABAoIBAGdNtfYDiap6bzst\\r\\n\"\n\"yhCiI8m9TtrhZw4MisaEaN/ll3XSjaOG2dvV6xMZCMV+5TeXDHOAZnY18Yi18vzz\\r\\n\"\n\"4Ut2TnNFzizCECYNaA2fST3WgInnxUkV3YXAyP6CNxJaCmv2aA0yFr2kFVSeaKGt\\r\\n\"\n\"ymvljNp2NVkvm7Th8fBQBO7I7AXhz43k0mR7XmPgewe8ApZOG3hstkOaMvbWAvWA\\r\\n\"\n\"zCZupdDjZYjOJqlA4eEA4H8/w7F83r5CugeBE8LgEREjLPiyejrU5H1fubEY+h0d\\r\\n\"\n\"l5HZBJ68ybTXfQ5U9o/QKA3dd0toBEhhdRUDGzWtjvwkEQfqF1reGWj/tod/gCpf\\r\\n\"\n\"DFi6X0ECgYEA4wOv/pjSC3ty6TuOvKX2rOUiBrLXXv2JSxZnMoMiWI5ipLQt+RYT\\r\\n\"\n\"VPafL/m7Dn6MbwjayOkcZhBwk5CNz5A6Q4lJ64Mq/lqHznRCQQ2Mc1G8eyDF/fYL\\r\\n\"\n\"Ze2pLvwP9VD5jTc2miDfw+MnvJhywRRLcemDFP8k4hQVtm8PMp3ZmNECgYEA4gz7\\r\\n\"\n\"wzObR4gn8ibe617uQPZjWzUj9dUHYd+in1gwBCIrtNnaRn9I9U/Q6tegRYpii4ys\\r\\n\"\n\"c176NmU+umy6XmuSKV5qD9bSpZWG2nLFnslrN15Lm3fhZxoeMNhBaEDTnLT26yoi\\r\\n\"\n\"33gp0mSSWy94ZEqipms+ULF6sY1ZtFW6tpGFoy8CgYAQHhnnvJflIs2ky4q10B60\\r\\n\"\n\"ZcxFp3rtDpkp0JxhFLhiizFrujMtZSjYNm5U7KkgPVHhLELEUvCmOnKTt4ap/vZ0\\r\\n\"\n\"BxJNe1GZH3pW6SAvGDQpl9sG7uu/vTFP+lCxukmzxB0DrrDcvorEkKMom7ZCCRvW\\r\\n\"\n\"KZsZ6YeH2Z81BauRj218kQKBgQCUV/DgKP2985xDTT79N08jUo3hTP5MVYCCuj/+\\r\\n\"\n\"UeEw1TvZcx3LJby7P6Xad6a1/BqveaGyFKIfEFIaBUBItk801sDDpDaYc4gL00Xc\\r\\n\"\n\"7lFuBHOZkxJYlss5QrGpuOEl9ZwUt5IrFLBdYaKqNHzNVC1pCPfb/JyH6Dr2HUxq\\r\\n\"\n\"gxUwAQKBgQCcU6G2L8AG9d9c0UpOyL1tMvFe5Ttw0KjlQVdsh1MP6yigYo9DYuwu\\r\\n\"\n\"bHFVW2r0dBTqegP2/KTOxKzaHfC1qf0RGDsUoJCNJrd1cwoCLG8P2EF4w3OBrKqv\\r\\n\"\n\"8u4ytY0F+Vlanj5lm3TaoHSVF1+NWPyOTiwevIECGKwSxvlki4fDAA==\\r\\n\"\n\"-----END RSA PRIVATE KEY-----\\r\\n\";\nconst size_t mbedtls_test_cli_key_rsa_len = sizeof( mbedtls_test_cli_key_rsa );\n#endif /* MBEDTLS_RSA_C */\n\n#if defined(MBEDTLS_PEM_PARSE_C)\n/* Concatenation of all available CA certificates */\nconst char mbedtls_test_cas_pem[] =\n#ifdef TEST_CA_CRT_RSA_SHA1\n    TEST_CA_CRT_RSA_SHA1\n#endif\n#ifdef TEST_CA_CRT_RSA_SHA256\n    TEST_CA_CRT_RSA_SHA256\n#endif\n#ifdef TEST_CA_CRT_EC\n    TEST_CA_CRT_EC\n#endif\n    \"\";\nconst size_t mbedtls_test_cas_pem_len = sizeof( mbedtls_test_cas_pem );\n#endif\n\n/* List of all available CA certificates */\nconst char * mbedtls_test_cas[] = {\n#if defined(TEST_CA_CRT_RSA_SHA1)\n    mbedtls_test_ca_crt_rsa_sha1,\n#endif\n#if defined(TEST_CA_CRT_RSA_SHA256)\n    mbedtls_test_ca_crt_rsa_sha256,\n#endif\n#if defined(MBEDTLS_ECDSA_C)\n    mbedtls_test_ca_crt_ec,\n#endif\n    NULL\n};\nconst size_t mbedtls_test_cas_len[] = {\n#if defined(TEST_CA_CRT_RSA_SHA1)\n    sizeof( mbedtls_test_ca_crt_rsa_sha1 ),\n#endif\n#if defined(TEST_CA_CRT_RSA_SHA256)\n    sizeof( mbedtls_test_ca_crt_rsa_sha256 ),\n#endif\n#if defined(MBEDTLS_ECDSA_C)\n    sizeof( mbedtls_test_ca_crt_ec ),\n#endif\n    0\n};\n\n#if defined(MBEDTLS_RSA_C)\nconst char *mbedtls_test_ca_crt  = mbedtls_test_ca_crt_rsa; /* SHA1 or SHA256 */\nconst char *mbedtls_test_ca_key  = mbedtls_test_ca_key_rsa;\nconst char *mbedtls_test_ca_pwd  = mbedtls_test_ca_pwd_rsa;\nconst char *mbedtls_test_srv_crt = mbedtls_test_srv_crt_rsa;\nconst char *mbedtls_test_srv_key = mbedtls_test_srv_key_rsa;\nconst char *mbedtls_test_cli_crt = mbedtls_test_cli_crt_rsa;\nconst char *mbedtls_test_cli_key = mbedtls_test_cli_key_rsa;\nconst size_t mbedtls_test_ca_crt_len  = sizeof( mbedtls_test_ca_crt_rsa );\nconst size_t mbedtls_test_ca_key_len  = sizeof( mbedtls_test_ca_key_rsa );\nconst size_t mbedtls_test_ca_pwd_len  = sizeof( mbedtls_test_ca_pwd_rsa ) - 1;\nconst size_t mbedtls_test_srv_crt_len = sizeof( mbedtls_test_srv_crt_rsa );\nconst size_t mbedtls_test_srv_key_len = sizeof( mbedtls_test_srv_key_rsa );\nconst size_t mbedtls_test_cli_crt_len = sizeof( mbedtls_test_cli_crt_rsa );\nconst size_t mbedtls_test_cli_key_len = sizeof( mbedtls_test_cli_key_rsa );\n#else /* ! MBEDTLS_RSA_C, so MBEDTLS_ECDSA_C */\nconst char *mbedtls_test_ca_crt  = mbedtls_test_ca_crt_ec;\nconst char *mbedtls_test_ca_key  = mbedtls_test_ca_key_ec;\nconst char *mbedtls_test_ca_pwd  = mbedtls_test_ca_pwd_ec;\nconst char *mbedtls_test_srv_crt = mbedtls_test_srv_crt_ec;\nconst char *mbedtls_test_srv_key = mbedtls_test_srv_key_ec;\nconst char *mbedtls_test_cli_crt = mbedtls_test_cli_crt_ec;\nconst char *mbedtls_test_cli_key = mbedtls_test_cli_key_ec;\nconst size_t mbedtls_test_ca_crt_len  = sizeof( mbedtls_test_ca_crt_ec );\nconst size_t mbedtls_test_ca_key_len  = sizeof( mbedtls_test_ca_key_ec );\nconst size_t mbedtls_test_ca_pwd_len  = sizeof( mbedtls_test_ca_pwd_ec ) - 1;\nconst size_t mbedtls_test_srv_crt_len = sizeof( mbedtls_test_srv_crt_ec );\nconst size_t mbedtls_test_srv_key_len = sizeof( mbedtls_test_srv_key_ec );\nconst size_t mbedtls_test_cli_crt_len = sizeof( mbedtls_test_cli_crt_ec );\nconst size_t mbedtls_test_cli_key_len = sizeof( mbedtls_test_cli_key_ec );\n#endif /* MBEDTLS_RSA_C */\n\n#endif /* MBEDTLS_CERTS_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/chacha20.c",
    "content": "/**\n * \\file chacha20.c\n *\n * \\brief ChaCha20 cipher.\n *\n * \\author Daniel King <damaki.gh@gmail.com>\n *\n *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_CHACHA20_C)\n\n#include \"mbedtls/chacha20.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <stddef.h>\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if !defined(MBEDTLS_CHACHA20_ALT)\n\n#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \\\n    !defined(inline) && !defined(__cplusplus)\n#define inline __inline\n#endif\n\n#define BYTES_TO_U32_LE( data, offset )                           \\\n    ( (uint32_t) data[offset]                                     \\\n          | (uint32_t) ( (uint32_t) data[( offset ) + 1] << 8 )   \\\n          | (uint32_t) ( (uint32_t) data[( offset ) + 2] << 16 )  \\\n          | (uint32_t) ( (uint32_t) data[( offset ) + 3] << 24 )  \\\n    )\n\n#define ROTL32( value, amount ) \\\n        ( (uint32_t) ( value << amount ) | ( value >> ( 32 - amount ) ) )\n\n#define CHACHA20_CTR_INDEX ( 12U )\n\n#define CHACHA20_BLOCK_SIZE_BYTES ( 4U * 16U )\n\n/**\n * \\brief           ChaCha20 quarter round operation.\n *\n *                  The quarter round is defined as follows (from RFC 7539):\n *                      1.  a += b; d ^= a; d <<<= 16;\n *                      2.  c += d; b ^= c; b <<<= 12;\n *                      3.  a += b; d ^= a; d <<<= 8;\n *                      4.  c += d; b ^= c; b <<<= 7;\n *\n * \\param state     ChaCha20 state to modify.\n * \\param a         The index of 'a' in the state.\n * \\param b         The index of 'b' in the state.\n * \\param c         The index of 'c' in the state.\n * \\param d         The index of 'd' in the state.\n */\nstatic inline void chacha20_quarter_round( uint32_t state[16],\n                                           size_t a,\n                                           size_t b,\n                                           size_t c,\n                                           size_t d )\n{\n    /* a += b; d ^= a; d <<<= 16; */\n    state[a] += state[b];\n    state[d] ^= state[a];\n    state[d] = ROTL32( state[d], 16 );\n\n    /* c += d; b ^= c; b <<<= 12 */\n    state[c] += state[d];\n    state[b] ^= state[c];\n    state[b] = ROTL32( state[b], 12 );\n\n    /* a += b; d ^= a; d <<<= 8; */\n    state[a] += state[b];\n    state[d] ^= state[a];\n    state[d] = ROTL32( state[d], 8 );\n\n    /* c += d; b ^= c; b <<<= 7; */\n    state[c] += state[d];\n    state[b] ^= state[c];\n    state[b] = ROTL32( state[b], 7 );\n}\n\n/**\n * \\brief           Perform the ChaCha20 inner block operation.\n *\n *                  This function performs two rounds: the column round and the\n *                  diagonal round.\n *\n * \\param state     The ChaCha20 state to update.\n */\nstatic void chacha20_inner_block( uint32_t state[16] )\n{\n    chacha20_quarter_round( state, 0, 4, 8,  12 );\n    chacha20_quarter_round( state, 1, 5, 9,  13 );\n    chacha20_quarter_round( state, 2, 6, 10, 14 );\n    chacha20_quarter_round( state, 3, 7, 11, 15 );\n\n    chacha20_quarter_round( state, 0, 5, 10, 15 );\n    chacha20_quarter_round( state, 1, 6, 11, 12 );\n    chacha20_quarter_round( state, 2, 7, 8,  13 );\n    chacha20_quarter_round( state, 3, 4, 9,  14 );\n}\n\n/**\n * \\brief               Generates a keystream block.\n *\n * \\param initial_state The initial ChaCha20 state (key, nonce, counter).\n * \\param keystream     Generated keystream bytes are written to this buffer.\n */\nstatic void chacha20_block( const uint32_t initial_state[16],\n                            unsigned char keystream[64] )\n{\n    uint32_t working_state[16];\n    size_t i;\n\n    memcpy( working_state,\n            initial_state,\n            CHACHA20_BLOCK_SIZE_BYTES );\n\n    for( i = 0U; i < 10U; i++ )\n        chacha20_inner_block( working_state );\n\n    working_state[ 0] += initial_state[ 0];\n    working_state[ 1] += initial_state[ 1];\n    working_state[ 2] += initial_state[ 2];\n    working_state[ 3] += initial_state[ 3];\n    working_state[ 4] += initial_state[ 4];\n    working_state[ 5] += initial_state[ 5];\n    working_state[ 6] += initial_state[ 6];\n    working_state[ 7] += initial_state[ 7];\n    working_state[ 8] += initial_state[ 8];\n    working_state[ 9] += initial_state[ 9];\n    working_state[10] += initial_state[10];\n    working_state[11] += initial_state[11];\n    working_state[12] += initial_state[12];\n    working_state[13] += initial_state[13];\n    working_state[14] += initial_state[14];\n    working_state[15] += initial_state[15];\n\n    for( i = 0U; i < 16; i++ )\n    {\n        size_t offset = i * 4U;\n\n        keystream[offset     ] = (unsigned char)( working_state[i]       );\n        keystream[offset + 1U] = (unsigned char)( working_state[i] >>  8 );\n        keystream[offset + 2U] = (unsigned char)( working_state[i] >> 16 );\n        keystream[offset + 3U] = (unsigned char)( working_state[i] >> 24 );\n    }\n\n    mbedtls_platform_zeroize( working_state, sizeof( working_state ) );\n}\n\nvoid mbedtls_chacha20_init( mbedtls_chacha20_context *ctx )\n{\n    if( ctx != NULL )\n    {\n        mbedtls_platform_zeroize( ctx->state, sizeof( ctx->state ) );\n        mbedtls_platform_zeroize( ctx->keystream8, sizeof( ctx->keystream8 ) );\n\n        /* Initially, there's no keystream bytes available */\n        ctx->keystream_bytes_used = CHACHA20_BLOCK_SIZE_BYTES;\n    }\n}\n\nvoid mbedtls_chacha20_free( mbedtls_chacha20_context *ctx )\n{\n    if( ctx != NULL )\n    {\n        mbedtls_platform_zeroize( ctx, sizeof( mbedtls_chacha20_context ) );\n    }\n}\n\nint mbedtls_chacha20_setkey( mbedtls_chacha20_context *ctx,\n                            const unsigned char key[32] )\n{\n    if( ( ctx == NULL ) || ( key == NULL ) )\n    {\n        return( MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA );\n    }\n\n    /* ChaCha20 constants - the string \"expand 32-byte k\" */\n    ctx->state[0] = 0x61707865;\n    ctx->state[1] = 0x3320646e;\n    ctx->state[2] = 0x79622d32;\n    ctx->state[3] = 0x6b206574;\n\n    /* Set key */\n    ctx->state[4]  = BYTES_TO_U32_LE( key, 0 );\n    ctx->state[5]  = BYTES_TO_U32_LE( key, 4 );\n    ctx->state[6]  = BYTES_TO_U32_LE( key, 8 );\n    ctx->state[7]  = BYTES_TO_U32_LE( key, 12 );\n    ctx->state[8]  = BYTES_TO_U32_LE( key, 16 );\n    ctx->state[9]  = BYTES_TO_U32_LE( key, 20 );\n    ctx->state[10] = BYTES_TO_U32_LE( key, 24 );\n    ctx->state[11] = BYTES_TO_U32_LE( key, 28 );\n\n    return( 0 );\n}\n\nint mbedtls_chacha20_starts( mbedtls_chacha20_context* ctx,\n                             const unsigned char nonce[12],\n                             uint32_t counter )\n{\n    if( ( ctx == NULL ) || ( nonce == NULL ) )\n    {\n        return( MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA );\n    }\n\n    /* Counter */\n    ctx->state[12] = counter;\n\n    /* Nonce */\n    ctx->state[13] = BYTES_TO_U32_LE( nonce, 0 );\n    ctx->state[14] = BYTES_TO_U32_LE( nonce, 4 );\n    ctx->state[15] = BYTES_TO_U32_LE( nonce, 8 );\n\n    mbedtls_platform_zeroize( ctx->keystream8, sizeof( ctx->keystream8 ) );\n\n    /* Initially, there's no keystream bytes available */\n    ctx->keystream_bytes_used = CHACHA20_BLOCK_SIZE_BYTES;\n\n    return( 0 );\n}\n\nint mbedtls_chacha20_update( mbedtls_chacha20_context *ctx,\n                              size_t size,\n                              const unsigned char *input,\n                              unsigned char *output )\n{\n    size_t offset = 0U;\n    size_t i;\n\n    if( ctx == NULL )\n    {\n        return( MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA );\n    }\n    else if( ( size > 0U ) && ( ( input == NULL ) || ( output == NULL ) ) )\n    {\n        /* input and output pointers are allowed to be NULL only if size == 0 */\n        return( MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA );\n    }\n\n    /* Use leftover keystream bytes, if available */\n    while( size > 0U && ctx->keystream_bytes_used < CHACHA20_BLOCK_SIZE_BYTES )\n    {\n        output[offset] = input[offset]\n                       ^ ctx->keystream8[ctx->keystream_bytes_used];\n\n        ctx->keystream_bytes_used++;\n        offset++;\n        size--;\n    }\n\n    /* Process full blocks */\n    while( size >= CHACHA20_BLOCK_SIZE_BYTES )\n    {\n        /* Generate new keystream block and increment counter */\n        chacha20_block( ctx->state, ctx->keystream8 );\n        ctx->state[CHACHA20_CTR_INDEX]++;\n\n        for( i = 0U; i < 64U; i += 8U )\n        {\n            output[offset + i  ] = input[offset + i  ] ^ ctx->keystream8[i  ];\n            output[offset + i+1] = input[offset + i+1] ^ ctx->keystream8[i+1];\n            output[offset + i+2] = input[offset + i+2] ^ ctx->keystream8[i+2];\n            output[offset + i+3] = input[offset + i+3] ^ ctx->keystream8[i+3];\n            output[offset + i+4] = input[offset + i+4] ^ ctx->keystream8[i+4];\n            output[offset + i+5] = input[offset + i+5] ^ ctx->keystream8[i+5];\n            output[offset + i+6] = input[offset + i+6] ^ ctx->keystream8[i+6];\n            output[offset + i+7] = input[offset + i+7] ^ ctx->keystream8[i+7];\n        }\n\n        offset += CHACHA20_BLOCK_SIZE_BYTES;\n        size   -= CHACHA20_BLOCK_SIZE_BYTES;\n    }\n\n    /* Last (partial) block */\n    if( size > 0U )\n    {\n        /* Generate new keystream block and increment counter */\n        chacha20_block( ctx->state, ctx->keystream8 );\n        ctx->state[CHACHA20_CTR_INDEX]++;\n\n        for( i = 0U; i < size; i++)\n        {\n            output[offset + i] = input[offset + i] ^ ctx->keystream8[i];\n        }\n\n        ctx->keystream_bytes_used = size;\n\n    }\n\n    return( 0 );\n}\n\nint mbedtls_chacha20_crypt( const unsigned char key[32],\n                            const unsigned char nonce[12],\n                            uint32_t counter,\n                            size_t data_len,\n                            const unsigned char* input,\n                            unsigned char* output )\n{\n    mbedtls_chacha20_context ctx;\n    int ret;\n\n    mbedtls_chacha20_init( &ctx );\n\n    ret = mbedtls_chacha20_setkey( &ctx, key );\n    if( ret != 0 )\n        goto cleanup;\n\n    ret = mbedtls_chacha20_starts( &ctx, nonce, counter );\n    if( ret != 0 )\n        goto cleanup;\n\n    ret = mbedtls_chacha20_update( &ctx, data_len, input, output );\n\ncleanup:\n    mbedtls_chacha20_free( &ctx );\n    return( ret );\n}\n\n#endif /* !MBEDTLS_CHACHA20_ALT */\n\n#if defined(MBEDTLS_SELF_TEST)\n\nstatic const unsigned char test_keys[2][32] =\n{\n    {\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n    },\n    {\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01\n    }\n};\n\nstatic const unsigned char test_nonces[2][12] =\n{\n    {\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x00\n    },\n    {\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x02\n    }\n};\n\nstatic const uint32_t test_counters[2] =\n{\n    0U,\n    1U\n};\n\nstatic const unsigned char test_input[2][375] =\n{\n    {\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n    },\n    {\n        0x41, 0x6e, 0x79, 0x20, 0x73, 0x75, 0x62, 0x6d,\n        0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x74,\n        0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x49, 0x45,\n        0x54, 0x46, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x6e,\n        0x64, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x74,\n        0x68, 0x65, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72,\n        0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, 0x20, 0x66,\n        0x6f, 0x72, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69,\n        0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61,\n        0x73, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x6f, 0x72,\n        0x20, 0x70, 0x61, 0x72, 0x74, 0x20, 0x6f, 0x66,\n        0x20, 0x61, 0x6e, 0x20, 0x49, 0x45, 0x54, 0x46,\n        0x20, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65,\n        0x74, 0x2d, 0x44, 0x72, 0x61, 0x66, 0x74, 0x20,\n        0x6f, 0x72, 0x20, 0x52, 0x46, 0x43, 0x20, 0x61,\n        0x6e, 0x64, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x73,\n        0x74, 0x61, 0x74, 0x65, 0x6d, 0x65, 0x6e, 0x74,\n        0x20, 0x6d, 0x61, 0x64, 0x65, 0x20, 0x77, 0x69,\n        0x74, 0x68, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65,\n        0x20, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74,\n        0x20, 0x6f, 0x66, 0x20, 0x61, 0x6e, 0x20, 0x49,\n        0x45, 0x54, 0x46, 0x20, 0x61, 0x63, 0x74, 0x69,\n        0x76, 0x69, 0x74, 0x79, 0x20, 0x69, 0x73, 0x20,\n        0x63, 0x6f, 0x6e, 0x73, 0x69, 0x64, 0x65, 0x72,\n        0x65, 0x64, 0x20, 0x61, 0x6e, 0x20, 0x22, 0x49,\n        0x45, 0x54, 0x46, 0x20, 0x43, 0x6f, 0x6e, 0x74,\n        0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e,\n        0x22, 0x2e, 0x20, 0x53, 0x75, 0x63, 0x68, 0x20,\n        0x73, 0x74, 0x61, 0x74, 0x65, 0x6d, 0x65, 0x6e,\n        0x74, 0x73, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75,\n        0x64, 0x65, 0x20, 0x6f, 0x72, 0x61, 0x6c, 0x20,\n        0x73, 0x74, 0x61, 0x74, 0x65, 0x6d, 0x65, 0x6e,\n        0x74, 0x73, 0x20, 0x69, 0x6e, 0x20, 0x49, 0x45,\n        0x54, 0x46, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69,\n        0x6f, 0x6e, 0x73, 0x2c, 0x20, 0x61, 0x73, 0x20,\n        0x77, 0x65, 0x6c, 0x6c, 0x20, 0x61, 0x73, 0x20,\n        0x77, 0x72, 0x69, 0x74, 0x74, 0x65, 0x6e, 0x20,\n        0x61, 0x6e, 0x64, 0x20, 0x65, 0x6c, 0x65, 0x63,\n        0x74, 0x72, 0x6f, 0x6e, 0x69, 0x63, 0x20, 0x63,\n        0x6f, 0x6d, 0x6d, 0x75, 0x6e, 0x69, 0x63, 0x61,\n        0x74, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x6d, 0x61,\n        0x64, 0x65, 0x20, 0x61, 0x74, 0x20, 0x61, 0x6e,\n        0x79, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x20, 0x6f,\n        0x72, 0x20, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x2c,\n        0x20, 0x77, 0x68, 0x69, 0x63, 0x68, 0x20, 0x61,\n        0x72, 0x65, 0x20, 0x61, 0x64, 0x64, 0x72, 0x65,\n        0x73, 0x73, 0x65, 0x64, 0x20, 0x74, 0x6f\n    }\n};\n\nstatic const unsigned char test_output[2][375] =\n{\n    {\n        0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90,\n        0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86, 0xbd, 0x28,\n        0xbd, 0xd2, 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a,\n        0xa8, 0x36, 0xef, 0xcc, 0x8b, 0x77, 0x0d, 0xc7,\n        0xda, 0x41, 0x59, 0x7c, 0x51, 0x57, 0x48, 0x8d,\n        0x77, 0x24, 0xe0, 0x3f, 0xb8, 0xd8, 0x4a, 0x37,\n        0x6a, 0x43, 0xb8, 0xf4, 0x15, 0x18, 0xa1, 0x1c,\n        0xc3, 0x87, 0xb6, 0x69, 0xb2, 0xee, 0x65, 0x86\n    },\n    {\n        0xa3, 0xfb, 0xf0, 0x7d, 0xf3, 0xfa, 0x2f, 0xde,\n        0x4f, 0x37, 0x6c, 0xa2, 0x3e, 0x82, 0x73, 0x70,\n        0x41, 0x60, 0x5d, 0x9f, 0x4f, 0x4f, 0x57, 0xbd,\n        0x8c, 0xff, 0x2c, 0x1d, 0x4b, 0x79, 0x55, 0xec,\n        0x2a, 0x97, 0x94, 0x8b, 0xd3, 0x72, 0x29, 0x15,\n        0xc8, 0xf3, 0xd3, 0x37, 0xf7, 0xd3, 0x70, 0x05,\n        0x0e, 0x9e, 0x96, 0xd6, 0x47, 0xb7, 0xc3, 0x9f,\n        0x56, 0xe0, 0x31, 0xca, 0x5e, 0xb6, 0x25, 0x0d,\n        0x40, 0x42, 0xe0, 0x27, 0x85, 0xec, 0xec, 0xfa,\n        0x4b, 0x4b, 0xb5, 0xe8, 0xea, 0xd0, 0x44, 0x0e,\n        0x20, 0xb6, 0xe8, 0xdb, 0x09, 0xd8, 0x81, 0xa7,\n        0xc6, 0x13, 0x2f, 0x42, 0x0e, 0x52, 0x79, 0x50,\n        0x42, 0xbd, 0xfa, 0x77, 0x73, 0xd8, 0xa9, 0x05,\n        0x14, 0x47, 0xb3, 0x29, 0x1c, 0xe1, 0x41, 0x1c,\n        0x68, 0x04, 0x65, 0x55, 0x2a, 0xa6, 0xc4, 0x05,\n        0xb7, 0x76, 0x4d, 0x5e, 0x87, 0xbe, 0xa8, 0x5a,\n        0xd0, 0x0f, 0x84, 0x49, 0xed, 0x8f, 0x72, 0xd0,\n        0xd6, 0x62, 0xab, 0x05, 0x26, 0x91, 0xca, 0x66,\n        0x42, 0x4b, 0xc8, 0x6d, 0x2d, 0xf8, 0x0e, 0xa4,\n        0x1f, 0x43, 0xab, 0xf9, 0x37, 0xd3, 0x25, 0x9d,\n        0xc4, 0xb2, 0xd0, 0xdf, 0xb4, 0x8a, 0x6c, 0x91,\n        0x39, 0xdd, 0xd7, 0xf7, 0x69, 0x66, 0xe9, 0x28,\n        0xe6, 0x35, 0x55, 0x3b, 0xa7, 0x6c, 0x5c, 0x87,\n        0x9d, 0x7b, 0x35, 0xd4, 0x9e, 0xb2, 0xe6, 0x2b,\n        0x08, 0x71, 0xcd, 0xac, 0x63, 0x89, 0x39, 0xe2,\n        0x5e, 0x8a, 0x1e, 0x0e, 0xf9, 0xd5, 0x28, 0x0f,\n        0xa8, 0xca, 0x32, 0x8b, 0x35, 0x1c, 0x3c, 0x76,\n        0x59, 0x89, 0xcb, 0xcf, 0x3d, 0xaa, 0x8b, 0x6c,\n        0xcc, 0x3a, 0xaf, 0x9f, 0x39, 0x79, 0xc9, 0x2b,\n        0x37, 0x20, 0xfc, 0x88, 0xdc, 0x95, 0xed, 0x84,\n        0xa1, 0xbe, 0x05, 0x9c, 0x64, 0x99, 0xb9, 0xfd,\n        0xa2, 0x36, 0xe7, 0xe8, 0x18, 0xb0, 0x4b, 0x0b,\n        0xc3, 0x9c, 0x1e, 0x87, 0x6b, 0x19, 0x3b, 0xfe,\n        0x55, 0x69, 0x75, 0x3f, 0x88, 0x12, 0x8c, 0xc0,\n        0x8a, 0xaa, 0x9b, 0x63, 0xd1, 0xa1, 0x6f, 0x80,\n        0xef, 0x25, 0x54, 0xd7, 0x18, 0x9c, 0x41, 0x1f,\n        0x58, 0x69, 0xca, 0x52, 0xc5, 0xb8, 0x3f, 0xa3,\n        0x6f, 0xf2, 0x16, 0xb9, 0xc1, 0xd3, 0x00, 0x62,\n        0xbe, 0xbc, 0xfd, 0x2d, 0xc5, 0xbc, 0xe0, 0x91,\n        0x19, 0x34, 0xfd, 0xa7, 0x9a, 0x86, 0xf6, 0xe6,\n        0x98, 0xce, 0xd7, 0x59, 0xc3, 0xff, 0x9b, 0x64,\n        0x77, 0x33, 0x8f, 0x3d, 0xa4, 0xf9, 0xcd, 0x85,\n        0x14, 0xea, 0x99, 0x82, 0xcc, 0xaf, 0xb3, 0x41,\n        0xb2, 0x38, 0x4d, 0xd9, 0x02, 0xf3, 0xd1, 0xab,\n        0x7a, 0xc6, 0x1d, 0xd2, 0x9c, 0x6f, 0x21, 0xba,\n        0x5b, 0x86, 0x2f, 0x37, 0x30, 0xe3, 0x7c, 0xfd,\n        0xc4, 0xfd, 0x80, 0x6c, 0x22, 0xf2, 0x21\n    }\n};\n\nstatic const size_t test_lengths[2] =\n{\n    64U,\n    375U\n};\n\n#define ASSERT( cond, args )            \\\n    do                                  \\\n    {                                   \\\n        if( ! ( cond ) )                \\\n        {                               \\\n            if( verbose != 0 )          \\\n                mbedtls_printf args;    \\\n                                        \\\n            return( -1 );               \\\n        }                               \\\n    }                                   \\\n    while( 0 )\n\nint mbedtls_chacha20_self_test( int verbose )\n{\n    unsigned char output[381];\n    unsigned i;\n    int ret;\n\n    for( i = 0U; i < 2U; i++ )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"  ChaCha20 test %u \", i );\n\n        ret = mbedtls_chacha20_crypt( test_keys[i],\n                                      test_nonces[i],\n                                      test_counters[i],\n                                      test_lengths[i],\n                                      test_input[i],\n                                      output );\n\n        ASSERT( 0 == ret, ( \"error code: %i\\n\", ret ) );\n\n        ASSERT( 0 == memcmp( output, test_output[i], test_lengths[i] ),\n                ( \"failed (output)\\n\" ) );\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    return( 0 );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* !MBEDTLS_CHACHA20_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/chachapoly.c",
    "content": "/**\n * \\file chachapoly.c\n *\n * \\brief ChaCha20-Poly1305 AEAD construction based on RFC 7539.\n *\n *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_CHACHAPOLY_C)\n\n#include \"mbedtls/chachapoly.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if !defined(MBEDTLS_CHACHAPOLY_ALT)\n\n#define CHACHAPOLY_STATE_INIT       ( 0 )\n#define CHACHAPOLY_STATE_AAD        ( 1 )\n#define CHACHAPOLY_STATE_CIPHERTEXT ( 2 ) /* Encrypting or decrypting */\n#define CHACHAPOLY_STATE_FINISHED   ( 3 )\n\n/**\n * \\brief           Adds nul bytes to pad the AAD for Poly1305.\n *\n * \\param ctx       The ChaCha20-Poly1305 context.\n */\nstatic int chachapoly_pad_aad( mbedtls_chachapoly_context *ctx )\n{\n    uint32_t partial_block_len = (uint32_t) ( ctx->aad_len % 16U );\n    unsigned char zeroes[15];\n\n    if( partial_block_len == 0U )\n        return( 0 );\n\n    memset( zeroes, 0, sizeof( zeroes ) );\n\n    return( mbedtls_poly1305_update( &ctx->poly1305_ctx,\n                                     zeroes,\n                                     16U - partial_block_len ) );\n}\n\n/**\n * \\brief           Adds nul bytes to pad the ciphertext for Poly1305.\n *\n * \\param ctx       The ChaCha20-Poly1305 context.\n */\nstatic int chachapoly_pad_ciphertext( mbedtls_chachapoly_context *ctx )\n{\n    uint32_t partial_block_len = (uint32_t) ( ctx->ciphertext_len % 16U );\n    unsigned char zeroes[15];\n\n    if( partial_block_len == 0U )\n        return( 0 );\n\n    memset( zeroes, 0, sizeof( zeroes ) );\n    return( mbedtls_poly1305_update( &ctx->poly1305_ctx,\n                                     zeroes,\n                                     16U - partial_block_len ) );\n}\n\nvoid mbedtls_chachapoly_init( mbedtls_chachapoly_context *ctx )\n{\n    if( ctx != NULL )\n    {\n        mbedtls_chacha20_init( &ctx->chacha20_ctx );\n        mbedtls_poly1305_init( &ctx->poly1305_ctx );\n        ctx->aad_len        = 0U;\n        ctx->ciphertext_len = 0U;\n        ctx->state          = CHACHAPOLY_STATE_INIT;\n        ctx->mode           = MBEDTLS_CHACHAPOLY_ENCRYPT;\n    }\n}\n\nvoid mbedtls_chachapoly_free( mbedtls_chachapoly_context *ctx )\n{\n    if( ctx != NULL )\n    {\n        mbedtls_chacha20_free( &ctx->chacha20_ctx );\n        mbedtls_poly1305_free( &ctx->poly1305_ctx );\n        ctx->aad_len        = 0U;\n        ctx->ciphertext_len = 0U;\n        ctx->state          = CHACHAPOLY_STATE_INIT;\n        ctx->mode           = MBEDTLS_CHACHAPOLY_ENCRYPT;\n    }\n}\n\nint mbedtls_chachapoly_setkey( mbedtls_chachapoly_context *ctx,\n                               const unsigned char key[32] )\n{\n    int ret;\n\n    if( ( ctx == NULL ) || ( key == NULL ) )\n    {\n        return( MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA );\n    }\n\n    ret = mbedtls_chacha20_setkey( &ctx->chacha20_ctx, key );\n\n    return( ret );\n}\n\nint mbedtls_chachapoly_starts( mbedtls_chachapoly_context *ctx,\n                               const unsigned char nonce[12],\n                               mbedtls_chachapoly_mode_t mode  )\n{\n    int ret;\n    unsigned char poly1305_key[64];\n\n    if( ( ctx == NULL ) || ( nonce == NULL ) )\n    {\n        return( MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA );\n    }\n\n    /* Set counter = 0, will be update to 1 when generating Poly1305 key */\n    ret = mbedtls_chacha20_starts( &ctx->chacha20_ctx, nonce, 0U );\n    if( ret != 0 )\n        goto cleanup;\n\n    /* Generate the Poly1305 key by getting the ChaCha20 keystream output with\n     * counter = 0.  This is the same as encrypting a buffer of zeroes.\n     * Only the first 256-bits (32 bytes) of the key is used for Poly1305.\n     * The other 256 bits are discarded.\n     */\n    memset( poly1305_key, 0, sizeof( poly1305_key ) );\n    ret = mbedtls_chacha20_update( &ctx->chacha20_ctx, sizeof( poly1305_key ),\n                                      poly1305_key, poly1305_key );\n    if( ret != 0 )\n        goto cleanup;\n\n    ret = mbedtls_poly1305_starts( &ctx->poly1305_ctx, poly1305_key );\n\n    if( ret == 0 )\n    {\n        ctx->aad_len        = 0U;\n        ctx->ciphertext_len = 0U;\n        ctx->state          = CHACHAPOLY_STATE_AAD;\n        ctx->mode           = mode;\n    }\n\ncleanup:\n    mbedtls_platform_zeroize( poly1305_key, 64U );\n    return( ret );\n}\n\nint mbedtls_chachapoly_update_aad( mbedtls_chachapoly_context *ctx,\n                                   const unsigned char *aad,\n                                   size_t aad_len )\n{\n    if( ctx == NULL )\n    {\n        return( MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA );\n    }\n    else if( ( aad_len > 0U ) && ( aad == NULL ) )\n    {\n        /* aad pointer is allowed to be NULL if aad_len == 0 */\n        return( MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA );\n    }\n    else if( ctx->state != CHACHAPOLY_STATE_AAD )\n    {\n        return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );\n    }\n\n    ctx->aad_len += aad_len;\n\n    return( mbedtls_poly1305_update( &ctx->poly1305_ctx, aad, aad_len ) );\n}\n\nint mbedtls_chachapoly_update( mbedtls_chachapoly_context *ctx,\n                               size_t len,\n                               const unsigned char *input,\n                               unsigned char *output )\n{\n    int ret;\n\n    if( ctx == NULL )\n    {\n        return( MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA );\n    }\n    else if( ( len > 0U ) && ( ( input == NULL ) || ( output == NULL ) ) )\n    {\n        /* input and output pointers are allowed to be NULL if len == 0 */\n        return( MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA );\n    }\n    else if( ( ctx->state != CHACHAPOLY_STATE_AAD ) &&\n              ( ctx->state != CHACHAPOLY_STATE_CIPHERTEXT ) )\n    {\n        return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );\n    }\n\n    if( ctx->state == CHACHAPOLY_STATE_AAD )\n    {\n        ctx->state = CHACHAPOLY_STATE_CIPHERTEXT;\n\n        ret = chachapoly_pad_aad( ctx );\n        if( ret != 0 )\n            return( ret );\n    }\n\n    ctx->ciphertext_len += len;\n\n    if( ctx->mode == MBEDTLS_CHACHAPOLY_ENCRYPT )\n    {\n        ret = mbedtls_chacha20_update( &ctx->chacha20_ctx, len, input, output );\n        if( ret != 0 )\n            return( ret );\n\n        ret = mbedtls_poly1305_update( &ctx->poly1305_ctx, output, len );\n        if( ret != 0 )\n            return( ret );\n    }\n    else /* DECRYPT */\n    {\n        ret = mbedtls_poly1305_update( &ctx->poly1305_ctx, input, len );\n        if( ret != 0 )\n            return( ret );\n\n        ret = mbedtls_chacha20_update( &ctx->chacha20_ctx, len, input, output );\n        if( ret != 0 )\n            return( ret );\n    }\n\n    return( 0 );\n}\n\nint mbedtls_chachapoly_finish( mbedtls_chachapoly_context *ctx,\n                               unsigned char mac[16] )\n{\n    int ret;\n    unsigned char len_block[16];\n\n    if( ( ctx == NULL ) || ( mac == NULL ) )\n    {\n        return( MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA );\n    }\n    else if( ctx->state == CHACHAPOLY_STATE_INIT )\n    {\n        return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );\n    }\n\n    if( ctx->state == CHACHAPOLY_STATE_AAD )\n    {\n        ret = chachapoly_pad_aad( ctx );\n        if( ret != 0 )\n            return( ret );\n    }\n    else if( ctx->state == CHACHAPOLY_STATE_CIPHERTEXT )\n    {\n        ret = chachapoly_pad_ciphertext( ctx );\n        if( ret != 0 )\n            return( ret );\n    }\n\n    ctx->state = CHACHAPOLY_STATE_FINISHED;\n\n    /* The lengths of the AAD and ciphertext are processed by\n     * Poly1305 as the final 128-bit block, encoded as little-endian integers.\n     */\n    len_block[ 0] = (unsigned char)( ctx->aad_len       );\n    len_block[ 1] = (unsigned char)( ctx->aad_len >>  8 );\n    len_block[ 2] = (unsigned char)( ctx->aad_len >> 16 );\n    len_block[ 3] = (unsigned char)( ctx->aad_len >> 24 );\n    len_block[ 4] = (unsigned char)( ctx->aad_len >> 32 );\n    len_block[ 5] = (unsigned char)( ctx->aad_len >> 40 );\n    len_block[ 6] = (unsigned char)( ctx->aad_len >> 48 );\n    len_block[ 7] = (unsigned char)( ctx->aad_len >> 56 );\n    len_block[ 8] = (unsigned char)( ctx->ciphertext_len       );\n    len_block[ 9] = (unsigned char)( ctx->ciphertext_len >>  8 );\n    len_block[10] = (unsigned char)( ctx->ciphertext_len >> 16 );\n    len_block[11] = (unsigned char)( ctx->ciphertext_len >> 24 );\n    len_block[12] = (unsigned char)( ctx->ciphertext_len >> 32 );\n    len_block[13] = (unsigned char)( ctx->ciphertext_len >> 40 );\n    len_block[14] = (unsigned char)( ctx->ciphertext_len >> 48 );\n    len_block[15] = (unsigned char)( ctx->ciphertext_len >> 56 );\n\n    ret = mbedtls_poly1305_update( &ctx->poly1305_ctx, len_block, 16U );\n    if( ret != 0 )\n        return( ret );\n\n    ret = mbedtls_poly1305_finish( &ctx->poly1305_ctx, mac );\n\n    return( ret );\n}\n\nstatic int chachapoly_crypt_and_tag( mbedtls_chachapoly_context *ctx,\n                                     mbedtls_chachapoly_mode_t mode,\n                                     size_t length,\n                                     const unsigned char nonce[12],\n                                     const unsigned char *aad,\n                                     size_t aad_len,\n                                     const unsigned char *input,\n                                     unsigned char *output,\n                                     unsigned char tag[16] )\n{\n    int ret;\n\n    ret = mbedtls_chachapoly_starts( ctx, nonce, mode );\n    if( ret != 0 )\n        goto cleanup;\n\n    ret = mbedtls_chachapoly_update_aad( ctx, aad, aad_len );\n    if( ret != 0 )\n        goto cleanup;\n\n    ret = mbedtls_chachapoly_update( ctx, length, input, output );\n    if( ret != 0 )\n        goto cleanup;\n\n    ret = mbedtls_chachapoly_finish( ctx, tag );\n\ncleanup:\n    return( ret );\n}\n\nint mbedtls_chachapoly_encrypt_and_tag( mbedtls_chachapoly_context *ctx,\n                                        size_t length,\n                                        const unsigned char nonce[12],\n                                        const unsigned char *aad,\n                                        size_t aad_len,\n                                        const unsigned char *input,\n                                        unsigned char *output,\n                                        unsigned char tag[16] )\n{\n    return( chachapoly_crypt_and_tag( ctx, MBEDTLS_CHACHAPOLY_ENCRYPT,\n                                      length, nonce, aad, aad_len,\n                                      input, output, tag ) );\n}\n\nint mbedtls_chachapoly_auth_decrypt( mbedtls_chachapoly_context *ctx,\n                                     size_t length,\n                                     const unsigned char nonce[12],\n                                     const unsigned char *aad,\n                                     size_t aad_len,\n                                     const unsigned char tag[16],\n                                     const unsigned char *input,\n                                     unsigned char *output )\n{\n    int ret;\n    unsigned char check_tag[16];\n    size_t i;\n    int diff;\n\n    if( tag == NULL )\n        return( MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA );\n\n    if( ( ret = chachapoly_crypt_and_tag( ctx,\n                        MBEDTLS_CHACHAPOLY_DECRYPT, length, nonce,\n                        aad, aad_len, input, output, check_tag ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    /* Check tag in \"constant-time\" */\n    for( diff = 0, i = 0; i < sizeof( check_tag ); i++ )\n        diff |= tag[i] ^ check_tag[i];\n\n    if( diff != 0 )\n    {\n        mbedtls_platform_zeroize( output, length );\n        return( MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED );\n    }\n\n    return( 0 );\n}\n\n#endif /* MBEDTLS_CHACHAPOLY_ALT */\n\n#if defined(MBEDTLS_SELF_TEST)\n\nstatic const unsigned char test_key[1][32] =\n{\n    {\n        0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,\n        0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,\n        0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,\n        0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f\n    }\n};\n\nstatic const unsigned char test_nonce[1][12] =\n{\n    {\n        0x07, 0x00, 0x00, 0x00,                         /* 32-bit common part */\n        0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47  /* 64-bit IV */\n    }\n};\n\nstatic const unsigned char test_aad[1][12] =\n{\n    {\n        0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2, 0xc3,\n        0xc4, 0xc5, 0xc6, 0xc7\n    }\n};\n\nstatic const size_t test_aad_len[1] =\n{\n    12U\n};\n\nstatic const unsigned char test_input[1][114] =\n{\n    {\n        0x4c, 0x61, 0x64, 0x69, 0x65, 0x73, 0x20, 0x61,\n        0x6e, 0x64, 0x20, 0x47, 0x65, 0x6e, 0x74, 0x6c,\n        0x65, 0x6d, 0x65, 0x6e, 0x20, 0x6f, 0x66, 0x20,\n        0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73,\n        0x73, 0x20, 0x6f, 0x66, 0x20, 0x27, 0x39, 0x39,\n        0x3a, 0x20, 0x49, 0x66, 0x20, 0x49, 0x20, 0x63,\n        0x6f, 0x75, 0x6c, 0x64, 0x20, 0x6f, 0x66, 0x66,\n        0x65, 0x72, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6f,\n        0x6e, 0x6c, 0x79, 0x20, 0x6f, 0x6e, 0x65, 0x20,\n        0x74, 0x69, 0x70, 0x20, 0x66, 0x6f, 0x72, 0x20,\n        0x74, 0x68, 0x65, 0x20, 0x66, 0x75, 0x74, 0x75,\n        0x72, 0x65, 0x2c, 0x20, 0x73, 0x75, 0x6e, 0x73,\n        0x63, 0x72, 0x65, 0x65, 0x6e, 0x20, 0x77, 0x6f,\n        0x75, 0x6c, 0x64, 0x20, 0x62, 0x65, 0x20, 0x69,\n        0x74, 0x2e\n    }\n};\n\nstatic const unsigned char test_output[1][114] =\n{\n    {\n        0xd3, 0x1a, 0x8d, 0x34, 0x64, 0x8e, 0x60, 0xdb,\n        0x7b, 0x86, 0xaf, 0xbc, 0x53, 0xef, 0x7e, 0xc2,\n        0xa4, 0xad, 0xed, 0x51, 0x29, 0x6e, 0x08, 0xfe,\n        0xa9, 0xe2, 0xb5, 0xa7, 0x36, 0xee, 0x62, 0xd6,\n        0x3d, 0xbe, 0xa4, 0x5e, 0x8c, 0xa9, 0x67, 0x12,\n        0x82, 0xfa, 0xfb, 0x69, 0xda, 0x92, 0x72, 0x8b,\n        0x1a, 0x71, 0xde, 0x0a, 0x9e, 0x06, 0x0b, 0x29,\n        0x05, 0xd6, 0xa5, 0xb6, 0x7e, 0xcd, 0x3b, 0x36,\n        0x92, 0xdd, 0xbd, 0x7f, 0x2d, 0x77, 0x8b, 0x8c,\n        0x98, 0x03, 0xae, 0xe3, 0x28, 0x09, 0x1b, 0x58,\n        0xfa, 0xb3, 0x24, 0xe4, 0xfa, 0xd6, 0x75, 0x94,\n        0x55, 0x85, 0x80, 0x8b, 0x48, 0x31, 0xd7, 0xbc,\n        0x3f, 0xf4, 0xde, 0xf0, 0x8e, 0x4b, 0x7a, 0x9d,\n        0xe5, 0x76, 0xd2, 0x65, 0x86, 0xce, 0xc6, 0x4b,\n        0x61, 0x16\n    }\n};\n\nstatic const size_t test_input_len[1] =\n{\n    114U\n};\n\nstatic const unsigned char test_mac[1][16] =\n{\n    {\n        0x1a, 0xe1, 0x0b, 0x59, 0x4f, 0x09, 0xe2, 0x6a,\n        0x7e, 0x90, 0x2e, 0xcb, 0xd0, 0x60, 0x06, 0x91\n    }\n};\n\n#define ASSERT( cond, args )            \\\n    do                                  \\\n    {                                   \\\n        if( ! ( cond ) )                \\\n        {                               \\\n            if( verbose != 0 )          \\\n                mbedtls_printf args;    \\\n                                        \\\n            return( -1 );               \\\n        }                               \\\n    }                                   \\\n    while( 0 )\n\nint mbedtls_chachapoly_self_test( int verbose )\n{\n    mbedtls_chachapoly_context ctx;\n    unsigned i;\n    int ret;\n    unsigned char output[200];\n    unsigned char mac[16];\n\n    for( i = 0U; i < 1U; i++ )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"  ChaCha20-Poly1305 test %u \", i );\n\n        mbedtls_chachapoly_init( &ctx );\n\n        ret = mbedtls_chachapoly_setkey( &ctx, test_key[i] );\n        ASSERT( 0 == ret, ( \"setkey() error code: %i\\n\", ret ) );\n\n        ret = mbedtls_chachapoly_encrypt_and_tag( &ctx,\n                                                  test_input_len[i],\n                                                  test_nonce[i],\n                                                  test_aad[i],\n                                                  test_aad_len[i],\n                                                  test_input[i],\n                                                  output,\n                                                  mac );\n\n        ASSERT( 0 == ret, ( \"crypt_and_tag() error code: %i\\n\", ret ) );\n\n        ASSERT( 0 == memcmp( output, test_output[i], test_input_len[i] ),\n                ( \"failure (wrong output)\\n\" ) );\n\n        ASSERT( 0 == memcmp( mac, test_mac[i], 16U ),\n                ( \"failure (wrong MAC)\\n\" ) );\n\n        mbedtls_chachapoly_free( &ctx );\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    return( 0 );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_CHACHAPOLY_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/cipher.c",
    "content": "/**\n * \\file cipher.c\n *\n * \\brief Generic cipher wrapper for mbed TLS\n *\n * \\author Adriaan de Jong <dejong@fox-it.com>\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_CIPHER_C)\n\n#include \"mbedtls/cipher.h\"\n#include \"mbedtls/cipher_internal.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <stdlib.h>\n#include <string.h>\n\n#if defined(MBEDTLS_CHACHAPOLY_C)\n#include \"mbedtls/chachapoly.h\"\n#endif\n\n#if defined(MBEDTLS_GCM_C)\n#include \"mbedtls/gcm.h\"\n#endif\n\n#if defined(MBEDTLS_CCM_C)\n#include \"mbedtls/ccm.h\"\n#endif\n\n#if defined(MBEDTLS_CHACHA20_C)\n#include \"mbedtls/chacha20.h\"\n#endif\n\n#if defined(MBEDTLS_CMAC_C)\n#include \"mbedtls/cmac.h\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#define mbedtls_calloc calloc\n#define mbedtls_free   free\n#endif\n\n#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)\n/* Compare the contents of two buffers in constant time.\n * Returns 0 if the contents are bitwise identical, otherwise returns\n * a non-zero value.\n * This is currently only used by GCM and ChaCha20+Poly1305.\n */\nstatic int mbedtls_constant_time_memcmp( const void *v1, const void *v2, size_t len )\n{\n    const unsigned char *p1 = (const unsigned char*) v1;\n    const unsigned char *p2 = (const unsigned char*) v2;\n    size_t i;\n    unsigned char diff;\n\n    for( diff = 0, i = 0; i < len; i++ )\n        diff |= p1[i] ^ p2[i];\n\n    return (int)diff;\n}\n#endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */\n\nstatic int supported_init = 0;\n\nconst int *mbedtls_cipher_list( void )\n{\n    const mbedtls_cipher_definition_t *def;\n    int *type;\n\n    if( ! supported_init )\n    {\n        def = mbedtls_cipher_definitions;\n        type = mbedtls_cipher_supported;\n\n        while( def->type != 0 )\n            *type++ = (*def++).type;\n\n        *type = 0;\n\n        supported_init = 1;\n    }\n\n    return( mbedtls_cipher_supported );\n}\n\nconst mbedtls_cipher_info_t *mbedtls_cipher_info_from_type( const mbedtls_cipher_type_t cipher_type )\n{\n    const mbedtls_cipher_definition_t *def;\n\n    for( def = mbedtls_cipher_definitions; def->info != NULL; def++ )\n        if( def->type == cipher_type )\n            return( def->info );\n\n    return( NULL );\n}\n\nconst mbedtls_cipher_info_t *mbedtls_cipher_info_from_string( const char *cipher_name )\n{\n    const mbedtls_cipher_definition_t *def;\n\n    if( NULL == cipher_name )\n        return( NULL );\n\n    for( def = mbedtls_cipher_definitions; def->info != NULL; def++ )\n        if( !  strcmp( def->info->name, cipher_name ) )\n            return( def->info );\n\n    return( NULL );\n}\n\nconst mbedtls_cipher_info_t *mbedtls_cipher_info_from_values( const mbedtls_cipher_id_t cipher_id,\n                                              int key_bitlen,\n                                              const mbedtls_cipher_mode_t mode )\n{\n    const mbedtls_cipher_definition_t *def;\n\n    for( def = mbedtls_cipher_definitions; def->info != NULL; def++ )\n        if( def->info->base->cipher == cipher_id &&\n            def->info->key_bitlen == (unsigned) key_bitlen &&\n            def->info->mode == mode )\n            return( def->info );\n\n    return( NULL );\n}\n\nvoid mbedtls_cipher_init( mbedtls_cipher_context_t *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_cipher_context_t ) );\n}\n\nvoid mbedtls_cipher_free( mbedtls_cipher_context_t *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n#if defined(MBEDTLS_CMAC_C)\n    if( ctx->cmac_ctx )\n    {\n       mbedtls_platform_zeroize( ctx->cmac_ctx,\n                                 sizeof( mbedtls_cmac_context_t ) );\n       mbedtls_free( ctx->cmac_ctx );\n    }\n#endif\n\n    if( ctx->cipher_ctx )\n        ctx->cipher_info->base->ctx_free_func( ctx->cipher_ctx );\n\n    mbedtls_platform_zeroize( ctx, sizeof(mbedtls_cipher_context_t) );\n}\n\nint mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_info_t *cipher_info )\n{\n    if( NULL == cipher_info || NULL == ctx )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    memset( ctx, 0, sizeof( mbedtls_cipher_context_t ) );\n\n    if( NULL == ( ctx->cipher_ctx = cipher_info->base->ctx_alloc_func() ) )\n        return( MBEDTLS_ERR_CIPHER_ALLOC_FAILED );\n\n    ctx->cipher_info = cipher_info;\n\n#if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)\n    /*\n     * Ignore possible errors caused by a cipher mode that doesn't use padding\n     */\n#if defined(MBEDTLS_CIPHER_PADDING_PKCS7)\n    (void) mbedtls_cipher_set_padding_mode( ctx, MBEDTLS_PADDING_PKCS7 );\n#else\n    (void) mbedtls_cipher_set_padding_mode( ctx, MBEDTLS_PADDING_NONE );\n#endif\n#endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */\n\n    return( 0 );\n}\n\nint mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *key,\n        int key_bitlen, const mbedtls_operation_t operation )\n{\n    if( NULL == ctx || NULL == ctx->cipher_info )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    if( ( ctx->cipher_info->flags & MBEDTLS_CIPHER_VARIABLE_KEY_LEN ) == 0 &&\n        (int) ctx->cipher_info->key_bitlen != key_bitlen )\n    {\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n    }\n\n    ctx->key_bitlen = key_bitlen;\n    ctx->operation = operation;\n\n    /*\n     * For OFB, CFB and CTR mode always use the encryption key schedule\n     */\n    if( MBEDTLS_ENCRYPT == operation ||\n        MBEDTLS_MODE_CFB == ctx->cipher_info->mode ||\n        MBEDTLS_MODE_OFB == ctx->cipher_info->mode ||\n        MBEDTLS_MODE_CTR == ctx->cipher_info->mode )\n    {\n        return ctx->cipher_info->base->setkey_enc_func( ctx->cipher_ctx, key,\n                ctx->key_bitlen );\n    }\n\n    if( MBEDTLS_DECRYPT == operation )\n        return ctx->cipher_info->base->setkey_dec_func( ctx->cipher_ctx, key,\n                ctx->key_bitlen );\n\n    return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n}\n\nint mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx,\n                   const unsigned char *iv, size_t iv_len )\n{\n    size_t actual_iv_size;\n\n    if( NULL == ctx || NULL == ctx->cipher_info || NULL == iv )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    /* avoid buffer overflow in ctx->iv */\n    if( iv_len > MBEDTLS_MAX_IV_LENGTH )\n        return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );\n\n    if( ( ctx->cipher_info->flags & MBEDTLS_CIPHER_VARIABLE_IV_LEN ) != 0 )\n        actual_iv_size = iv_len;\n    else\n    {\n        actual_iv_size = ctx->cipher_info->iv_size;\n\n        /* avoid reading past the end of input buffer */\n        if( actual_iv_size > iv_len )\n            return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n    }\n\n#if defined(MBEDTLS_CHACHA20_C)\n    if ( ctx->cipher_info->type == MBEDTLS_CIPHER_CHACHA20 )\n    {\n        if ( 0 != mbedtls_chacha20_starts( (mbedtls_chacha20_context*)ctx->cipher_ctx,\n                                           iv,\n                                           0U ) ) /* Initial counter value */\n        {\n            return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n        }\n    }\n#endif\n\n    memcpy( ctx->iv, iv, actual_iv_size );\n    ctx->iv_size = actual_iv_size;\n\n    return( 0 );\n}\n\nint mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx )\n{\n    if( NULL == ctx || NULL == ctx->cipher_info )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    ctx->unprocessed_len = 0;\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)\nint mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx,\n                      const unsigned char *ad, size_t ad_len )\n{\n    if( NULL == ctx || NULL == ctx->cipher_info )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n#if defined(MBEDTLS_GCM_C)\n    if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )\n    {\n        return mbedtls_gcm_starts( (mbedtls_gcm_context *) ctx->cipher_ctx, ctx->operation,\n                           ctx->iv, ctx->iv_size, ad, ad_len );\n    }\n#endif\n\n#if defined(MBEDTLS_CHACHAPOLY_C)\n    if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )\n    {\n        int result;\n        mbedtls_chachapoly_mode_t mode;\n\n        mode = ( ctx->operation == MBEDTLS_ENCRYPT )\n                ? MBEDTLS_CHACHAPOLY_ENCRYPT\n                : MBEDTLS_CHACHAPOLY_DECRYPT;\n\n        result = mbedtls_chachapoly_starts( (mbedtls_chachapoly_context*) ctx->cipher_ctx,\n                                                        ctx->iv,\n                                                        mode );\n        if ( result != 0 )\n            return( result );\n\n        return mbedtls_chachapoly_update_aad( (mbedtls_chachapoly_context*) ctx->cipher_ctx,\n                                                          ad, ad_len );\n    }\n#endif\n\n    return( 0 );\n}\n#endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */\n\nint mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input,\n                   size_t ilen, unsigned char *output, size_t *olen )\n{\n    int ret;\n    size_t block_size = 0;\n\n    if( NULL == ctx || NULL == ctx->cipher_info || NULL == olen )\n    {\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n    }\n\n    *olen = 0;\n    block_size = mbedtls_cipher_get_block_size( ctx );\n\n    if( ctx->cipher_info->mode == MBEDTLS_MODE_ECB )\n    {\n        if( ilen != block_size )\n            return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED );\n\n        *olen = ilen;\n\n        if( 0 != ( ret = ctx->cipher_info->base->ecb_func( ctx->cipher_ctx,\n                    ctx->operation, input, output ) ) )\n        {\n            return( ret );\n        }\n\n        return( 0 );\n    }\n\n#if defined(MBEDTLS_GCM_C)\n    if( ctx->cipher_info->mode == MBEDTLS_MODE_GCM )\n    {\n        *olen = ilen;\n        return mbedtls_gcm_update( (mbedtls_gcm_context *) ctx->cipher_ctx, ilen, input,\n                           output );\n    }\n#endif\n\n#if defined(MBEDTLS_CHACHAPOLY_C)\n    if ( ctx->cipher_info->type == MBEDTLS_CIPHER_CHACHA20_POLY1305 )\n    {\n        *olen = ilen;\n        return mbedtls_chachapoly_update( (mbedtls_chachapoly_context*) ctx->cipher_ctx,\n                                                      ilen, input, output );\n    }\n#endif\n\n    if ( 0 == block_size )\n    {\n        return MBEDTLS_ERR_CIPHER_INVALID_CONTEXT;\n    }\n\n    if( input == output &&\n       ( ctx->unprocessed_len != 0 || ilen % block_size ) )\n    {\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n    }\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    if( ctx->cipher_info->mode == MBEDTLS_MODE_CBC )\n    {\n        size_t copy_len = 0;\n\n        /*\n         * If there is not enough data for a full block, cache it.\n         */\n        if( ( ctx->operation == MBEDTLS_DECRYPT && NULL != ctx->add_padding &&\n                ilen <= block_size - ctx->unprocessed_len ) ||\n            ( ctx->operation == MBEDTLS_DECRYPT && NULL == ctx->add_padding &&\n                ilen < block_size - ctx->unprocessed_len ) ||\n             ( ctx->operation == MBEDTLS_ENCRYPT &&\n                ilen < block_size - ctx->unprocessed_len ) )\n        {\n            memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ), input,\n                    ilen );\n\n            ctx->unprocessed_len += ilen;\n            return( 0 );\n        }\n\n        /*\n         * Process cached data first\n         */\n        if( 0 != ctx->unprocessed_len )\n        {\n            copy_len = block_size - ctx->unprocessed_len;\n\n            memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ), input,\n                    copy_len );\n\n            if( 0 != ( ret = ctx->cipher_info->base->cbc_func( ctx->cipher_ctx,\n                    ctx->operation, block_size, ctx->iv,\n                    ctx->unprocessed_data, output ) ) )\n            {\n                return( ret );\n            }\n\n            *olen += block_size;\n            output += block_size;\n            ctx->unprocessed_len = 0;\n\n            input += copy_len;\n            ilen -= copy_len;\n        }\n\n        /*\n         * Cache final, incomplete block\n         */\n        if( 0 != ilen )\n        {\n            if( 0 == block_size )\n            {\n                return MBEDTLS_ERR_CIPHER_INVALID_CONTEXT;\n            }\n\n            /* Encryption: only cache partial blocks\n             * Decryption w/ padding: always keep at least one whole block\n             * Decryption w/o padding: only cache partial blocks\n             */\n            copy_len = ilen % block_size;\n            if( copy_len == 0 &&\n                ctx->operation == MBEDTLS_DECRYPT &&\n                NULL != ctx->add_padding)\n            {\n                copy_len = block_size;\n            }\n\n            memcpy( ctx->unprocessed_data, &( input[ilen - copy_len] ),\n                    copy_len );\n\n            ctx->unprocessed_len += copy_len;\n            ilen -= copy_len;\n        }\n\n        /*\n         * Process remaining full blocks\n         */\n        if( ilen )\n        {\n            if( 0 != ( ret = ctx->cipher_info->base->cbc_func( ctx->cipher_ctx,\n                    ctx->operation, ilen, ctx->iv, input, output ) ) )\n            {\n                return( ret );\n            }\n\n            *olen += ilen;\n        }\n\n        return( 0 );\n    }\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    if( ctx->cipher_info->mode == MBEDTLS_MODE_CFB )\n    {\n        if( 0 != ( ret = ctx->cipher_info->base->cfb_func( ctx->cipher_ctx,\n                ctx->operation, ilen, &ctx->unprocessed_len, ctx->iv,\n                input, output ) ) )\n        {\n            return( ret );\n        }\n\n        *olen = ilen;\n\n        return( 0 );\n    }\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    if( ctx->cipher_info->mode == MBEDTLS_MODE_OFB )\n    {\n        if( 0 != ( ret = ctx->cipher_info->base->ofb_func( ctx->cipher_ctx,\n                ilen, &ctx->unprocessed_len, ctx->iv, input, output ) ) )\n        {\n            return( ret );\n        }\n\n        *olen = ilen;\n\n        return( 0 );\n    }\n#endif /* MBEDTLS_CIPHER_MODE_OFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    if( ctx->cipher_info->mode == MBEDTLS_MODE_CTR )\n    {\n        if( 0 != ( ret = ctx->cipher_info->base->ctr_func( ctx->cipher_ctx,\n                ilen, &ctx->unprocessed_len, ctx->iv,\n                ctx->unprocessed_data, input, output ) ) )\n        {\n            return( ret );\n        }\n\n        *olen = ilen;\n\n        return( 0 );\n    }\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    if( ctx->cipher_info->mode == MBEDTLS_MODE_XTS )\n    {\n        if( ctx->unprocessed_len > 0 ) {\n            /* We can only process an entire data unit at a time. */\n            return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );\n        }\n\n        ret = ctx->cipher_info->base->xts_func( ctx->cipher_ctx,\n                ctx->operation, ilen, ctx->iv, input, output );\n        if( ret != 0 )\n        {\n            return( ret );\n        }\n\n        *olen = ilen;\n\n        return( 0 );\n    }\n#endif /* MBEDTLS_CIPHER_MODE_XTS */\n\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    if( ctx->cipher_info->mode == MBEDTLS_MODE_STREAM )\n    {\n        if( 0 != ( ret = ctx->cipher_info->base->stream_func( ctx->cipher_ctx,\n                                                    ilen, input, output ) ) )\n        {\n            return( ret );\n        }\n\n        *olen = ilen;\n\n        return( 0 );\n    }\n#endif /* MBEDTLS_CIPHER_MODE_STREAM */\n\n    return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );\n}\n\n#if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)\n#if defined(MBEDTLS_CIPHER_PADDING_PKCS7)\n/*\n * PKCS7 (and PKCS5) padding: fill with ll bytes, with ll = padding_len\n */\nstatic void add_pkcs_padding( unsigned char *output, size_t output_len,\n        size_t data_len )\n{\n    size_t padding_len = output_len - data_len;\n    unsigned char i;\n\n    for( i = 0; i < padding_len; i++ )\n        output[data_len + i] = (unsigned char) padding_len;\n}\n\nstatic int get_pkcs_padding( unsigned char *input, size_t input_len,\n        size_t *data_len )\n{\n    size_t i, pad_idx;\n    unsigned char padding_len, bad = 0;\n\n    if( NULL == input || NULL == data_len )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    padding_len = input[input_len - 1];\n    *data_len = input_len - padding_len;\n\n    /* Avoid logical || since it results in a branch */\n    bad |= padding_len > input_len;\n    bad |= padding_len == 0;\n\n    /* The number of bytes checked must be independent of padding_len,\n     * so pick input_len, which is usually 8 or 16 (one block) */\n    pad_idx = input_len - padding_len;\n    for( i = 0; i < input_len; i++ )\n        bad |= ( input[i] ^ padding_len ) * ( i >= pad_idx );\n\n    return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) );\n}\n#endif /* MBEDTLS_CIPHER_PADDING_PKCS7 */\n\n#if defined(MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS)\n/*\n * One and zeros padding: fill with 80 00 ... 00\n */\nstatic void add_one_and_zeros_padding( unsigned char *output,\n                                       size_t output_len, size_t data_len )\n{\n    size_t padding_len = output_len - data_len;\n    unsigned char i = 0;\n\n    output[data_len] = 0x80;\n    for( i = 1; i < padding_len; i++ )\n        output[data_len + i] = 0x00;\n}\n\nstatic int get_one_and_zeros_padding( unsigned char *input, size_t input_len,\n                                      size_t *data_len )\n{\n    size_t i;\n    unsigned char done = 0, prev_done, bad;\n\n    if( NULL == input || NULL == data_len )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    bad = 0x80;\n    *data_len = 0;\n    for( i = input_len; i > 0; i-- )\n    {\n        prev_done = done;\n        done |= ( input[i - 1] != 0 );\n        *data_len |= ( i - 1 ) * ( done != prev_done );\n        bad ^= input[i - 1] * ( done != prev_done );\n    }\n\n    return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) );\n\n}\n#endif /* MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS */\n\n#if defined(MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN)\n/*\n * Zeros and len padding: fill with 00 ... 00 ll, where ll is padding length\n */\nstatic void add_zeros_and_len_padding( unsigned char *output,\n                                       size_t output_len, size_t data_len )\n{\n    size_t padding_len = output_len - data_len;\n    unsigned char i = 0;\n\n    for( i = 1; i < padding_len; i++ )\n        output[data_len + i - 1] = 0x00;\n    output[output_len - 1] = (unsigned char) padding_len;\n}\n\nstatic int get_zeros_and_len_padding( unsigned char *input, size_t input_len,\n                                      size_t *data_len )\n{\n    size_t i, pad_idx;\n    unsigned char padding_len, bad = 0;\n\n    if( NULL == input || NULL == data_len )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    padding_len = input[input_len - 1];\n    *data_len = input_len - padding_len;\n\n    /* Avoid logical || since it results in a branch */\n    bad |= padding_len > input_len;\n    bad |= padding_len == 0;\n\n    /* The number of bytes checked must be independent of padding_len */\n    pad_idx = input_len - padding_len;\n    for( i = 0; i < input_len - 1; i++ )\n        bad |= input[i] * ( i >= pad_idx );\n\n    return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) );\n}\n#endif /* MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN */\n\n#if defined(MBEDTLS_CIPHER_PADDING_ZEROS)\n/*\n * Zero padding: fill with 00 ... 00\n */\nstatic void add_zeros_padding( unsigned char *output,\n                               size_t output_len, size_t data_len )\n{\n    size_t i;\n\n    for( i = data_len; i < output_len; i++ )\n        output[i] = 0x00;\n}\n\nstatic int get_zeros_padding( unsigned char *input, size_t input_len,\n                              size_t *data_len )\n{\n    size_t i;\n    unsigned char done = 0, prev_done;\n\n    if( NULL == input || NULL == data_len )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    *data_len = 0;\n    for( i = input_len; i > 0; i-- )\n    {\n        prev_done = done;\n        done |= ( input[i-1] != 0 );\n        *data_len |= i * ( done != prev_done );\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_PADDING_ZEROS */\n\n/*\n * No padding: don't pad :)\n *\n * There is no add_padding function (check for NULL in mbedtls_cipher_finish)\n * but a trivial get_padding function\n */\nstatic int get_no_padding( unsigned char *input, size_t input_len,\n                              size_t *data_len )\n{\n    if( NULL == input || NULL == data_len )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    *data_len = input_len;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */\n\nint mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx,\n                   unsigned char *output, size_t *olen )\n{\n    if( NULL == ctx || NULL == ctx->cipher_info || NULL == olen )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    *olen = 0;\n\n    if( MBEDTLS_MODE_CFB == ctx->cipher_info->mode ||\n        MBEDTLS_MODE_OFB == ctx->cipher_info->mode ||\n        MBEDTLS_MODE_CTR == ctx->cipher_info->mode ||\n        MBEDTLS_MODE_GCM == ctx->cipher_info->mode ||\n        MBEDTLS_MODE_XTS == ctx->cipher_info->mode ||\n        MBEDTLS_MODE_STREAM == ctx->cipher_info->mode )\n    {\n        return( 0 );\n    }\n\n    if ( ( MBEDTLS_CIPHER_CHACHA20          == ctx->cipher_info->type ) ||\n         ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type ) )\n    {\n        return( 0 );\n    }\n\n    if( MBEDTLS_MODE_ECB == ctx->cipher_info->mode )\n    {\n        if( ctx->unprocessed_len != 0 )\n            return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED );\n\n        return( 0 );\n    }\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    if( MBEDTLS_MODE_CBC == ctx->cipher_info->mode )\n    {\n        int ret = 0;\n\n        if( MBEDTLS_ENCRYPT == ctx->operation )\n        {\n            /* check for 'no padding' mode */\n            if( NULL == ctx->add_padding )\n            {\n                if( 0 != ctx->unprocessed_len )\n                    return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED );\n\n                return( 0 );\n            }\n\n            ctx->add_padding( ctx->unprocessed_data, mbedtls_cipher_get_iv_size( ctx ),\n                    ctx->unprocessed_len );\n        }\n        else if( mbedtls_cipher_get_block_size( ctx ) != ctx->unprocessed_len )\n        {\n            /*\n             * For decrypt operations, expect a full block,\n             * or an empty block if no padding\n             */\n            if( NULL == ctx->add_padding && 0 == ctx->unprocessed_len )\n                return( 0 );\n\n            return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED );\n        }\n\n        /* cipher block */\n        if( 0 != ( ret = ctx->cipher_info->base->cbc_func( ctx->cipher_ctx,\n                ctx->operation, mbedtls_cipher_get_block_size( ctx ), ctx->iv,\n                ctx->unprocessed_data, output ) ) )\n        {\n            return( ret );\n        }\n\n        /* Set output size for decryption */\n        if( MBEDTLS_DECRYPT == ctx->operation )\n            return ctx->get_padding( output, mbedtls_cipher_get_block_size( ctx ),\n                                     olen );\n\n        /* Set output size for encryption */\n        *olen = mbedtls_cipher_get_block_size( ctx );\n        return( 0 );\n    }\n#else\n    ((void) output);\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n    return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );\n}\n\n#if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)\nint mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_cipher_padding_t mode )\n{\n    if( NULL == ctx ||\n        MBEDTLS_MODE_CBC != ctx->cipher_info->mode )\n    {\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n    }\n\n    switch( mode )\n    {\n#if defined(MBEDTLS_CIPHER_PADDING_PKCS7)\n    case MBEDTLS_PADDING_PKCS7:\n        ctx->add_padding = add_pkcs_padding;\n        ctx->get_padding = get_pkcs_padding;\n        break;\n#endif\n#if defined(MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS)\n    case MBEDTLS_PADDING_ONE_AND_ZEROS:\n        ctx->add_padding = add_one_and_zeros_padding;\n        ctx->get_padding = get_one_and_zeros_padding;\n        break;\n#endif\n#if defined(MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN)\n    case MBEDTLS_PADDING_ZEROS_AND_LEN:\n        ctx->add_padding = add_zeros_and_len_padding;\n        ctx->get_padding = get_zeros_and_len_padding;\n        break;\n#endif\n#if defined(MBEDTLS_CIPHER_PADDING_ZEROS)\n    case MBEDTLS_PADDING_ZEROS:\n        ctx->add_padding = add_zeros_padding;\n        ctx->get_padding = get_zeros_padding;\n        break;\n#endif\n    case MBEDTLS_PADDING_NONE:\n        ctx->add_padding = NULL;\n        ctx->get_padding = get_no_padding;\n        break;\n\n    default:\n        return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */\n\n#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)\nint mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx,\n                      unsigned char *tag, size_t tag_len )\n{\n    if( NULL == ctx || NULL == ctx->cipher_info || NULL == tag )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    if( MBEDTLS_ENCRYPT != ctx->operation )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n#if defined(MBEDTLS_GCM_C)\n    if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )\n        return mbedtls_gcm_finish( (mbedtls_gcm_context *) ctx->cipher_ctx, tag, tag_len );\n#endif\n\n#if defined(MBEDTLS_CHACHAPOLY_C)\n    if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )\n    {\n        /* Don't allow truncated MAC for Poly1305 */\n        if ( tag_len != 16U )\n            return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n        return mbedtls_chachapoly_finish( (mbedtls_chachapoly_context*) ctx->cipher_ctx,\n                                                      tag );\n    }\n#endif\n\n    return( 0 );\n}\n\nint mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx,\n                      const unsigned char *tag, size_t tag_len )\n{\n    unsigned char check_tag[16];\n    int ret;\n\n    if( NULL == ctx || NULL == ctx->cipher_info ||\n        MBEDTLS_DECRYPT != ctx->operation )\n    {\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n    }\n\n#if defined(MBEDTLS_GCM_C)\n    if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )\n    {\n        if( tag_len > sizeof( check_tag ) )\n            return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n        if( 0 != ( ret = mbedtls_gcm_finish( (mbedtls_gcm_context *) ctx->cipher_ctx,\n                                     check_tag, tag_len ) ) )\n        {\n            return( ret );\n        }\n\n        /* Check the tag in \"constant-time\" */\n        if( mbedtls_constant_time_memcmp( tag, check_tag, tag_len ) != 0 )\n            return( MBEDTLS_ERR_CIPHER_AUTH_FAILED );\n\n        return( 0 );\n    }\n#endif /* MBEDTLS_GCM_C */\n\n#if defined(MBEDTLS_CHACHAPOLY_C)\n    if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )\n    {\n        /* Don't allow truncated MAC for Poly1305 */\n        if ( tag_len != sizeof( check_tag ) )\n            return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n        ret = mbedtls_chachapoly_finish( (mbedtls_chachapoly_context*) ctx->cipher_ctx,\n                                                     check_tag );\n        if ( ret != 0 )\n        {\n            return( ret );\n        }\n\n        /* Check the tag in \"constant-time\" */\n        if( mbedtls_constant_time_memcmp( tag, check_tag, tag_len ) != 0 )\n            return( MBEDTLS_ERR_CIPHER_AUTH_FAILED );\n\n        return( 0 );\n    }\n#endif /* MBEDTLS_CHACHAPOLY_C */\n\n    return( 0 );\n}\n#endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */\n\n/*\n * Packet-oriented wrapper for non-AEAD modes\n */\nint mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx,\n                  const unsigned char *iv, size_t iv_len,\n                  const unsigned char *input, size_t ilen,\n                  unsigned char *output, size_t *olen )\n{\n    int ret;\n    size_t finish_olen;\n\n    if( ( ret = mbedtls_cipher_set_iv( ctx, iv, iv_len ) ) != 0 )\n        return( ret );\n\n    if( ( ret = mbedtls_cipher_reset( ctx ) ) != 0 )\n        return( ret );\n\n    if( ( ret = mbedtls_cipher_update( ctx, input, ilen, output, olen ) ) != 0 )\n        return( ret );\n\n    if( ( ret = mbedtls_cipher_finish( ctx, output + *olen, &finish_olen ) ) != 0 )\n        return( ret );\n\n    *olen += finish_olen;\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_CIPHER_MODE_AEAD)\n/*\n * Packet-oriented encryption for AEAD modes\n */\nint mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx,\n                         const unsigned char *iv, size_t iv_len,\n                         const unsigned char *ad, size_t ad_len,\n                         const unsigned char *input, size_t ilen,\n                         unsigned char *output, size_t *olen,\n                         unsigned char *tag, size_t tag_len )\n{\n#if defined(MBEDTLS_GCM_C)\n    if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )\n    {\n        *olen = ilen;\n        return( mbedtls_gcm_crypt_and_tag( ctx->cipher_ctx, MBEDTLS_GCM_ENCRYPT, ilen,\n                                   iv, iv_len, ad, ad_len, input, output,\n                                   tag_len, tag ) );\n    }\n#endif /* MBEDTLS_GCM_C */\n#if defined(MBEDTLS_CCM_C)\n    if( MBEDTLS_MODE_CCM == ctx->cipher_info->mode )\n    {\n        *olen = ilen;\n        return( mbedtls_ccm_encrypt_and_tag( ctx->cipher_ctx, ilen,\n                                     iv, iv_len, ad, ad_len, input, output,\n                                     tag, tag_len ) );\n    }\n#endif /* MBEDTLS_CCM_C */\n#if defined(MBEDTLS_CHACHAPOLY_C)\n    if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )\n    {\n        /* ChachaPoly has fixed length nonce and MAC (tag) */\n        if ( ( iv_len != ctx->cipher_info->iv_size ) ||\n             ( tag_len != 16U ) )\n        {\n            return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n        }\n\n        *olen = ilen;\n        return( mbedtls_chachapoly_encrypt_and_tag( ctx->cipher_ctx,\n                                ilen, iv, ad, ad_len, input, output, tag ) );\n    }\n#endif /* MBEDTLS_CHACHAPOLY_C */\n\n    return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );\n}\n\n/*\n * Packet-oriented decryption for AEAD modes\n */\nint mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx,\n                         const unsigned char *iv, size_t iv_len,\n                         const unsigned char *ad, size_t ad_len,\n                         const unsigned char *input, size_t ilen,\n                         unsigned char *output, size_t *olen,\n                         const unsigned char *tag, size_t tag_len )\n{\n#if defined(MBEDTLS_GCM_C)\n    if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )\n    {\n        int ret;\n\n        *olen = ilen;\n        ret = mbedtls_gcm_auth_decrypt( ctx->cipher_ctx, ilen,\n                                iv, iv_len, ad, ad_len,\n                                tag, tag_len, input, output );\n\n        if( ret == MBEDTLS_ERR_GCM_AUTH_FAILED )\n            ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;\n\n        return( ret );\n    }\n#endif /* MBEDTLS_GCM_C */\n#if defined(MBEDTLS_CCM_C)\n    if( MBEDTLS_MODE_CCM == ctx->cipher_info->mode )\n    {\n        int ret;\n\n        *olen = ilen;\n        ret = mbedtls_ccm_auth_decrypt( ctx->cipher_ctx, ilen,\n                                iv, iv_len, ad, ad_len,\n                                input, output, tag, tag_len );\n\n        if( ret == MBEDTLS_ERR_CCM_AUTH_FAILED )\n            ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;\n\n        return( ret );\n    }\n#endif /* MBEDTLS_CCM_C */\n#if defined(MBEDTLS_CHACHAPOLY_C)\n    if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )\n    {\n        int ret;\n\n        /* ChachaPoly has fixed length nonce and MAC (tag) */\n        if ( ( iv_len != ctx->cipher_info->iv_size ) ||\n             ( tag_len != 16U ) )\n        {\n            return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n        }\n\n        *olen = ilen;\n        ret = mbedtls_chachapoly_auth_decrypt( ctx->cipher_ctx, ilen,\n                                iv, ad, ad_len, tag, input, output );\n\n        if( ret == MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED )\n            ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;\n\n        return( ret );\n    }\n#endif /* MBEDTLS_CHACHAPOLY_C */\n\n    return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );\n}\n#endif /* MBEDTLS_CIPHER_MODE_AEAD */\n\n#endif /* MBEDTLS_CIPHER_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/cipher_wrap.c",
    "content": "/**\n * \\file cipher_wrap.c\n *\n * \\brief Generic cipher wrapper for mbed TLS\n *\n * \\author Adriaan de Jong <dejong@fox-it.com>\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_CIPHER_C)\n\n#include \"mbedtls/cipher_internal.h\"\n\n#if defined(MBEDTLS_CHACHAPOLY_C)\n#include \"mbedtls/chachapoly.h\"\n#endif\n\n#if defined(MBEDTLS_AES_C)\n#include \"mbedtls/aes.h\"\n#endif\n\n#if defined(MBEDTLS_ARC4_C)\n#include \"mbedtls/arc4.h\"\n#endif\n\n#if defined(MBEDTLS_CAMELLIA_C)\n#include \"mbedtls/camellia.h\"\n#endif\n\n#if defined(MBEDTLS_ARIA_C)\n#include \"mbedtls/aria.h\"\n#endif\n\n#if defined(MBEDTLS_DES_C)\n#include \"mbedtls/des.h\"\n#endif\n\n#if defined(MBEDTLS_BLOWFISH_C)\n#include \"mbedtls/blowfish.h\"\n#endif\n\n#if defined(MBEDTLS_CHACHA20_C)\n#include \"mbedtls/chacha20.h\"\n#endif\n\n#if defined(MBEDTLS_GCM_C)\n#include \"mbedtls/gcm.h\"\n#endif\n\n#if defined(MBEDTLS_CCM_C)\n#include \"mbedtls/ccm.h\"\n#endif\n\n#if defined(MBEDTLS_CIPHER_NULL_CIPHER)\n#include <string.h>\n#endif\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc    calloc\n#define mbedtls_free       free\n#endif\n\n#if defined(MBEDTLS_GCM_C)\n/* shared by all GCM ciphers */\nstatic void *gcm_ctx_alloc( void )\n{\n    void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_gcm_context ) );\n\n    if( ctx != NULL )\n        mbedtls_gcm_init( (mbedtls_gcm_context *) ctx );\n\n    return( ctx );\n}\n\nstatic void gcm_ctx_free( void *ctx )\n{\n    mbedtls_gcm_free( ctx );\n    mbedtls_free( ctx );\n}\n#endif /* MBEDTLS_GCM_C */\n\n#if defined(MBEDTLS_CCM_C)\n/* shared by all CCM ciphers */\nstatic void *ccm_ctx_alloc( void )\n{\n    void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ccm_context ) );\n\n    if( ctx != NULL )\n        mbedtls_ccm_init( (mbedtls_ccm_context *) ctx );\n\n    return( ctx );\n}\n\nstatic void ccm_ctx_free( void *ctx )\n{\n    mbedtls_ccm_free( ctx );\n    mbedtls_free( ctx );\n}\n#endif /* MBEDTLS_CCM_C */\n\n#if defined(MBEDTLS_AES_C)\n\nstatic int aes_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,\n        const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_aes_crypt_ecb( (mbedtls_aes_context *) ctx, operation, input, output );\n}\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\nstatic int aes_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation, size_t length,\n        unsigned char *iv, const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_aes_crypt_cbc( (mbedtls_aes_context *) ctx, operation, length, iv, input,\n                          output );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\nstatic int aes_crypt_cfb128_wrap( void *ctx, mbedtls_operation_t operation,\n        size_t length, size_t *iv_off, unsigned char *iv,\n        const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_aes_crypt_cfb128( (mbedtls_aes_context *) ctx, operation, length, iv_off, iv,\n                             input, output );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\nstatic int aes_crypt_ofb_wrap( void *ctx, size_t length, size_t *iv_off,\n        unsigned char *iv, const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_aes_crypt_ofb( (mbedtls_aes_context *) ctx, length, iv_off,\n                                    iv, input, output );\n}\n#endif /* MBEDTLS_CIPHER_MODE_OFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\nstatic int aes_crypt_ctr_wrap( void *ctx, size_t length, size_t *nc_off,\n        unsigned char *nonce_counter, unsigned char *stream_block,\n        const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_aes_crypt_ctr( (mbedtls_aes_context *) ctx, length, nc_off, nonce_counter,\n                          stream_block, input, output );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\nstatic int aes_crypt_xts_wrap( void *ctx, mbedtls_operation_t operation,\n                               size_t length,\n                               const unsigned char data_unit[16],\n                               const unsigned char *input,\n                               unsigned char *output )\n{\n    mbedtls_aes_xts_context *xts_ctx = ctx;\n    int mode;\n\n    switch( operation )\n    {\n        case MBEDTLS_ENCRYPT:\n            mode = MBEDTLS_AES_ENCRYPT;\n            break;\n        case MBEDTLS_DECRYPT:\n            mode = MBEDTLS_AES_DECRYPT;\n            break;\n        default:\n            return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;\n    }\n\n    return mbedtls_aes_crypt_xts( xts_ctx, mode, length,\n                                  data_unit, input, output );\n}\n#endif /* MBEDTLS_CIPHER_MODE_XTS */\n\nstatic int aes_setkey_dec_wrap( void *ctx, const unsigned char *key,\n                                unsigned int key_bitlen )\n{\n    return mbedtls_aes_setkey_dec( (mbedtls_aes_context *) ctx, key, key_bitlen );\n}\n\nstatic int aes_setkey_enc_wrap( void *ctx, const unsigned char *key,\n                                unsigned int key_bitlen )\n{\n    return mbedtls_aes_setkey_enc( (mbedtls_aes_context *) ctx, key, key_bitlen );\n}\n\nstatic void * aes_ctx_alloc( void )\n{\n    mbedtls_aes_context *aes = mbedtls_calloc( 1, sizeof( mbedtls_aes_context ) );\n\n    if( aes == NULL )\n        return( NULL );\n\n    mbedtls_aes_init( aes );\n\n    return( aes );\n}\n\nstatic void aes_ctx_free( void *ctx )\n{\n    mbedtls_aes_free( (mbedtls_aes_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic const mbedtls_cipher_base_t aes_info = {\n    MBEDTLS_CIPHER_ID_AES,\n    aes_crypt_ecb_wrap,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    aes_crypt_cbc_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    aes_crypt_cfb128_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    aes_crypt_ofb_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    aes_crypt_ctr_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    NULL,\n#endif\n    aes_setkey_enc_wrap,\n    aes_setkey_dec_wrap,\n    aes_ctx_alloc,\n    aes_ctx_free\n};\n\nstatic const mbedtls_cipher_info_t aes_128_ecb_info = {\n    MBEDTLS_CIPHER_AES_128_ECB,\n    MBEDTLS_MODE_ECB,\n    128,\n    \"AES-128-ECB\",\n    16,\n    0,\n    16,\n    &aes_info\n};\n\nstatic const mbedtls_cipher_info_t aes_192_ecb_info = {\n    MBEDTLS_CIPHER_AES_192_ECB,\n    MBEDTLS_MODE_ECB,\n    192,\n    \"AES-192-ECB\",\n    16,\n    0,\n    16,\n    &aes_info\n};\n\nstatic const mbedtls_cipher_info_t aes_256_ecb_info = {\n    MBEDTLS_CIPHER_AES_256_ECB,\n    MBEDTLS_MODE_ECB,\n    256,\n    \"AES-256-ECB\",\n    16,\n    0,\n    16,\n    &aes_info\n};\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\nstatic const mbedtls_cipher_info_t aes_128_cbc_info = {\n    MBEDTLS_CIPHER_AES_128_CBC,\n    MBEDTLS_MODE_CBC,\n    128,\n    \"AES-128-CBC\",\n    16,\n    0,\n    16,\n    &aes_info\n};\n\nstatic const mbedtls_cipher_info_t aes_192_cbc_info = {\n    MBEDTLS_CIPHER_AES_192_CBC,\n    MBEDTLS_MODE_CBC,\n    192,\n    \"AES-192-CBC\",\n    16,\n    0,\n    16,\n    &aes_info\n};\n\nstatic const mbedtls_cipher_info_t aes_256_cbc_info = {\n    MBEDTLS_CIPHER_AES_256_CBC,\n    MBEDTLS_MODE_CBC,\n    256,\n    \"AES-256-CBC\",\n    16,\n    0,\n    16,\n    &aes_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\nstatic const mbedtls_cipher_info_t aes_128_cfb128_info = {\n    MBEDTLS_CIPHER_AES_128_CFB128,\n    MBEDTLS_MODE_CFB,\n    128,\n    \"AES-128-CFB128\",\n    16,\n    0,\n    16,\n    &aes_info\n};\n\nstatic const mbedtls_cipher_info_t aes_192_cfb128_info = {\n    MBEDTLS_CIPHER_AES_192_CFB128,\n    MBEDTLS_MODE_CFB,\n    192,\n    \"AES-192-CFB128\",\n    16,\n    0,\n    16,\n    &aes_info\n};\n\nstatic const mbedtls_cipher_info_t aes_256_cfb128_info = {\n    MBEDTLS_CIPHER_AES_256_CFB128,\n    MBEDTLS_MODE_CFB,\n    256,\n    \"AES-256-CFB128\",\n    16,\n    0,\n    16,\n    &aes_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\nstatic const mbedtls_cipher_info_t aes_128_ofb_info = {\n    MBEDTLS_CIPHER_AES_128_OFB,\n    MBEDTLS_MODE_OFB,\n    128,\n    \"AES-128-OFB\",\n    16,\n    0,\n    16,\n    &aes_info\n};\n\nstatic const mbedtls_cipher_info_t aes_192_ofb_info = {\n    MBEDTLS_CIPHER_AES_192_OFB,\n    MBEDTLS_MODE_OFB,\n    192,\n    \"AES-192-OFB\",\n    16,\n    0,\n    16,\n    &aes_info\n};\n\nstatic const mbedtls_cipher_info_t aes_256_ofb_info = {\n    MBEDTLS_CIPHER_AES_256_OFB,\n    MBEDTLS_MODE_OFB,\n    256,\n    \"AES-256-OFB\",\n    16,\n    0,\n    16,\n    &aes_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_OFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\nstatic const mbedtls_cipher_info_t aes_128_ctr_info = {\n    MBEDTLS_CIPHER_AES_128_CTR,\n    MBEDTLS_MODE_CTR,\n    128,\n    \"AES-128-CTR\",\n    16,\n    0,\n    16,\n    &aes_info\n};\n\nstatic const mbedtls_cipher_info_t aes_192_ctr_info = {\n    MBEDTLS_CIPHER_AES_192_CTR,\n    MBEDTLS_MODE_CTR,\n    192,\n    \"AES-192-CTR\",\n    16,\n    0,\n    16,\n    &aes_info\n};\n\nstatic const mbedtls_cipher_info_t aes_256_ctr_info = {\n    MBEDTLS_CIPHER_AES_256_CTR,\n    MBEDTLS_MODE_CTR,\n    256,\n    \"AES-256-CTR\",\n    16,\n    0,\n    16,\n    &aes_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\nstatic int xts_aes_setkey_enc_wrap( void *ctx, const unsigned char *key,\n                                    unsigned int key_bitlen )\n{\n    mbedtls_aes_xts_context *xts_ctx = ctx;\n    return( mbedtls_aes_xts_setkey_enc( xts_ctx, key, key_bitlen ) );\n}\n\nstatic int xts_aes_setkey_dec_wrap( void *ctx, const unsigned char *key,\n                                    unsigned int key_bitlen )\n{\n    mbedtls_aes_xts_context *xts_ctx = ctx;\n    return( mbedtls_aes_xts_setkey_dec( xts_ctx, key, key_bitlen ) );\n}\n\nstatic void *xts_aes_ctx_alloc( void )\n{\n    mbedtls_aes_xts_context *xts_ctx = mbedtls_calloc( 1, sizeof( *xts_ctx ) );\n\n    if( xts_ctx != NULL )\n        mbedtls_aes_xts_init( xts_ctx );\n\n    return( xts_ctx );\n}\n\nstatic void xts_aes_ctx_free( void *ctx )\n{\n    mbedtls_aes_xts_context *xts_ctx = ctx;\n\n    if( xts_ctx == NULL )\n        return;\n\n    mbedtls_aes_xts_free( xts_ctx );\n    mbedtls_free( xts_ctx );\n}\n\nstatic const mbedtls_cipher_base_t xts_aes_info = {\n    MBEDTLS_CIPHER_ID_AES,\n    NULL,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    aes_crypt_xts_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    NULL,\n#endif\n    xts_aes_setkey_enc_wrap,\n    xts_aes_setkey_dec_wrap,\n    xts_aes_ctx_alloc,\n    xts_aes_ctx_free\n};\n\nstatic const mbedtls_cipher_info_t aes_128_xts_info = {\n    MBEDTLS_CIPHER_AES_128_XTS,\n    MBEDTLS_MODE_XTS,\n    256,\n    \"AES-128-XTS\",\n    16,\n    0,\n    16,\n    &xts_aes_info\n};\n\nstatic const mbedtls_cipher_info_t aes_256_xts_info = {\n    MBEDTLS_CIPHER_AES_256_XTS,\n    MBEDTLS_MODE_XTS,\n    512,\n    \"AES-256-XTS\",\n    16,\n    0,\n    16,\n    &xts_aes_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_XTS */\n\n#if defined(MBEDTLS_GCM_C)\nstatic int gcm_aes_setkey_wrap( void *ctx, const unsigned char *key,\n                                unsigned int key_bitlen )\n{\n    return mbedtls_gcm_setkey( (mbedtls_gcm_context *) ctx, MBEDTLS_CIPHER_ID_AES,\n                     key, key_bitlen );\n}\n\nstatic const mbedtls_cipher_base_t gcm_aes_info = {\n    MBEDTLS_CIPHER_ID_AES,\n    NULL,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    NULL,\n#endif\n    gcm_aes_setkey_wrap,\n    gcm_aes_setkey_wrap,\n    gcm_ctx_alloc,\n    gcm_ctx_free,\n};\n\nstatic const mbedtls_cipher_info_t aes_128_gcm_info = {\n    MBEDTLS_CIPHER_AES_128_GCM,\n    MBEDTLS_MODE_GCM,\n    128,\n    \"AES-128-GCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &gcm_aes_info\n};\n\nstatic const mbedtls_cipher_info_t aes_192_gcm_info = {\n    MBEDTLS_CIPHER_AES_192_GCM,\n    MBEDTLS_MODE_GCM,\n    192,\n    \"AES-192-GCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &gcm_aes_info\n};\n\nstatic const mbedtls_cipher_info_t aes_256_gcm_info = {\n    MBEDTLS_CIPHER_AES_256_GCM,\n    MBEDTLS_MODE_GCM,\n    256,\n    \"AES-256-GCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &gcm_aes_info\n};\n#endif /* MBEDTLS_GCM_C */\n\n#if defined(MBEDTLS_CCM_C)\nstatic int ccm_aes_setkey_wrap( void *ctx, const unsigned char *key,\n                                unsigned int key_bitlen )\n{\n    return mbedtls_ccm_setkey( (mbedtls_ccm_context *) ctx, MBEDTLS_CIPHER_ID_AES,\n                     key, key_bitlen );\n}\n\nstatic const mbedtls_cipher_base_t ccm_aes_info = {\n    MBEDTLS_CIPHER_ID_AES,\n    NULL,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    NULL,\n#endif\n    ccm_aes_setkey_wrap,\n    ccm_aes_setkey_wrap,\n    ccm_ctx_alloc,\n    ccm_ctx_free,\n};\n\nstatic const mbedtls_cipher_info_t aes_128_ccm_info = {\n    MBEDTLS_CIPHER_AES_128_CCM,\n    MBEDTLS_MODE_CCM,\n    128,\n    \"AES-128-CCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &ccm_aes_info\n};\n\nstatic const mbedtls_cipher_info_t aes_192_ccm_info = {\n    MBEDTLS_CIPHER_AES_192_CCM,\n    MBEDTLS_MODE_CCM,\n    192,\n    \"AES-192-CCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &ccm_aes_info\n};\n\nstatic const mbedtls_cipher_info_t aes_256_ccm_info = {\n    MBEDTLS_CIPHER_AES_256_CCM,\n    MBEDTLS_MODE_CCM,\n    256,\n    \"AES-256-CCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &ccm_aes_info\n};\n#endif /* MBEDTLS_CCM_C */\n\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_CAMELLIA_C)\n\nstatic int camellia_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,\n        const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_camellia_crypt_ecb( (mbedtls_camellia_context *) ctx, operation, input,\n                               output );\n}\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\nstatic int camellia_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation,\n        size_t length, unsigned char *iv,\n        const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_camellia_crypt_cbc( (mbedtls_camellia_context *) ctx, operation, length, iv,\n                               input, output );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\nstatic int camellia_crypt_cfb128_wrap( void *ctx, mbedtls_operation_t operation,\n        size_t length, size_t *iv_off, unsigned char *iv,\n        const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_camellia_crypt_cfb128( (mbedtls_camellia_context *) ctx, operation, length,\n                                  iv_off, iv, input, output );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\nstatic int camellia_crypt_ctr_wrap( void *ctx, size_t length, size_t *nc_off,\n        unsigned char *nonce_counter, unsigned char *stream_block,\n        const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_camellia_crypt_ctr( (mbedtls_camellia_context *) ctx, length, nc_off,\n                               nonce_counter, stream_block, input, output );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\nstatic int camellia_setkey_dec_wrap( void *ctx, const unsigned char *key,\n                                     unsigned int key_bitlen )\n{\n    return mbedtls_camellia_setkey_dec( (mbedtls_camellia_context *) ctx, key, key_bitlen );\n}\n\nstatic int camellia_setkey_enc_wrap( void *ctx, const unsigned char *key,\n                                     unsigned int key_bitlen )\n{\n    return mbedtls_camellia_setkey_enc( (mbedtls_camellia_context *) ctx, key, key_bitlen );\n}\n\nstatic void * camellia_ctx_alloc( void )\n{\n    mbedtls_camellia_context *ctx;\n    ctx = mbedtls_calloc( 1, sizeof( mbedtls_camellia_context ) );\n\n    if( ctx == NULL )\n        return( NULL );\n\n    mbedtls_camellia_init( ctx );\n\n    return( ctx );\n}\n\nstatic void camellia_ctx_free( void *ctx )\n{\n    mbedtls_camellia_free( (mbedtls_camellia_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic const mbedtls_cipher_base_t camellia_info = {\n    MBEDTLS_CIPHER_ID_CAMELLIA,\n    camellia_crypt_ecb_wrap,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    camellia_crypt_cbc_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    camellia_crypt_cfb128_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    camellia_crypt_ctr_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    NULL,\n#endif\n    camellia_setkey_enc_wrap,\n    camellia_setkey_dec_wrap,\n    camellia_ctx_alloc,\n    camellia_ctx_free\n};\n\nstatic const mbedtls_cipher_info_t camellia_128_ecb_info = {\n    MBEDTLS_CIPHER_CAMELLIA_128_ECB,\n    MBEDTLS_MODE_ECB,\n    128,\n    \"CAMELLIA-128-ECB\",\n    16,\n    0,\n    16,\n    &camellia_info\n};\n\nstatic const mbedtls_cipher_info_t camellia_192_ecb_info = {\n    MBEDTLS_CIPHER_CAMELLIA_192_ECB,\n    MBEDTLS_MODE_ECB,\n    192,\n    \"CAMELLIA-192-ECB\",\n    16,\n    0,\n    16,\n    &camellia_info\n};\n\nstatic const mbedtls_cipher_info_t camellia_256_ecb_info = {\n    MBEDTLS_CIPHER_CAMELLIA_256_ECB,\n    MBEDTLS_MODE_ECB,\n    256,\n    \"CAMELLIA-256-ECB\",\n    16,\n    0,\n    16,\n    &camellia_info\n};\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\nstatic const mbedtls_cipher_info_t camellia_128_cbc_info = {\n    MBEDTLS_CIPHER_CAMELLIA_128_CBC,\n    MBEDTLS_MODE_CBC,\n    128,\n    \"CAMELLIA-128-CBC\",\n    16,\n    0,\n    16,\n    &camellia_info\n};\n\nstatic const mbedtls_cipher_info_t camellia_192_cbc_info = {\n    MBEDTLS_CIPHER_CAMELLIA_192_CBC,\n    MBEDTLS_MODE_CBC,\n    192,\n    \"CAMELLIA-192-CBC\",\n    16,\n    0,\n    16,\n    &camellia_info\n};\n\nstatic const mbedtls_cipher_info_t camellia_256_cbc_info = {\n    MBEDTLS_CIPHER_CAMELLIA_256_CBC,\n    MBEDTLS_MODE_CBC,\n    256,\n    \"CAMELLIA-256-CBC\",\n    16,\n    0,\n    16,\n    &camellia_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\nstatic const mbedtls_cipher_info_t camellia_128_cfb128_info = {\n    MBEDTLS_CIPHER_CAMELLIA_128_CFB128,\n    MBEDTLS_MODE_CFB,\n    128,\n    \"CAMELLIA-128-CFB128\",\n    16,\n    0,\n    16,\n    &camellia_info\n};\n\nstatic const mbedtls_cipher_info_t camellia_192_cfb128_info = {\n    MBEDTLS_CIPHER_CAMELLIA_192_CFB128,\n    MBEDTLS_MODE_CFB,\n    192,\n    \"CAMELLIA-192-CFB128\",\n    16,\n    0,\n    16,\n    &camellia_info\n};\n\nstatic const mbedtls_cipher_info_t camellia_256_cfb128_info = {\n    MBEDTLS_CIPHER_CAMELLIA_256_CFB128,\n    MBEDTLS_MODE_CFB,\n    256,\n    \"CAMELLIA-256-CFB128\",\n    16,\n    0,\n    16,\n    &camellia_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\nstatic const mbedtls_cipher_info_t camellia_128_ctr_info = {\n    MBEDTLS_CIPHER_CAMELLIA_128_CTR,\n    MBEDTLS_MODE_CTR,\n    128,\n    \"CAMELLIA-128-CTR\",\n    16,\n    0,\n    16,\n    &camellia_info\n};\n\nstatic const mbedtls_cipher_info_t camellia_192_ctr_info = {\n    MBEDTLS_CIPHER_CAMELLIA_192_CTR,\n    MBEDTLS_MODE_CTR,\n    192,\n    \"CAMELLIA-192-CTR\",\n    16,\n    0,\n    16,\n    &camellia_info\n};\n\nstatic const mbedtls_cipher_info_t camellia_256_ctr_info = {\n    MBEDTLS_CIPHER_CAMELLIA_256_CTR,\n    MBEDTLS_MODE_CTR,\n    256,\n    \"CAMELLIA-256-CTR\",\n    16,\n    0,\n    16,\n    &camellia_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\n#if defined(MBEDTLS_GCM_C)\nstatic int gcm_camellia_setkey_wrap( void *ctx, const unsigned char *key,\n                                     unsigned int key_bitlen )\n{\n    return mbedtls_gcm_setkey( (mbedtls_gcm_context *) ctx, MBEDTLS_CIPHER_ID_CAMELLIA,\n                     key, key_bitlen );\n}\n\nstatic const mbedtls_cipher_base_t gcm_camellia_info = {\n    MBEDTLS_CIPHER_ID_CAMELLIA,\n    NULL,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    NULL,\n#endif\n    gcm_camellia_setkey_wrap,\n    gcm_camellia_setkey_wrap,\n    gcm_ctx_alloc,\n    gcm_ctx_free,\n};\n\nstatic const mbedtls_cipher_info_t camellia_128_gcm_info = {\n    MBEDTLS_CIPHER_CAMELLIA_128_GCM,\n    MBEDTLS_MODE_GCM,\n    128,\n    \"CAMELLIA-128-GCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &gcm_camellia_info\n};\n\nstatic const mbedtls_cipher_info_t camellia_192_gcm_info = {\n    MBEDTLS_CIPHER_CAMELLIA_192_GCM,\n    MBEDTLS_MODE_GCM,\n    192,\n    \"CAMELLIA-192-GCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &gcm_camellia_info\n};\n\nstatic const mbedtls_cipher_info_t camellia_256_gcm_info = {\n    MBEDTLS_CIPHER_CAMELLIA_256_GCM,\n    MBEDTLS_MODE_GCM,\n    256,\n    \"CAMELLIA-256-GCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &gcm_camellia_info\n};\n#endif /* MBEDTLS_GCM_C */\n\n#if defined(MBEDTLS_CCM_C)\nstatic int ccm_camellia_setkey_wrap( void *ctx, const unsigned char *key,\n                                     unsigned int key_bitlen )\n{\n    return mbedtls_ccm_setkey( (mbedtls_ccm_context *) ctx, MBEDTLS_CIPHER_ID_CAMELLIA,\n                     key, key_bitlen );\n}\n\nstatic const mbedtls_cipher_base_t ccm_camellia_info = {\n    MBEDTLS_CIPHER_ID_CAMELLIA,\n    NULL,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    NULL,\n#endif\n    ccm_camellia_setkey_wrap,\n    ccm_camellia_setkey_wrap,\n    ccm_ctx_alloc,\n    ccm_ctx_free,\n};\n\nstatic const mbedtls_cipher_info_t camellia_128_ccm_info = {\n    MBEDTLS_CIPHER_CAMELLIA_128_CCM,\n    MBEDTLS_MODE_CCM,\n    128,\n    \"CAMELLIA-128-CCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &ccm_camellia_info\n};\n\nstatic const mbedtls_cipher_info_t camellia_192_ccm_info = {\n    MBEDTLS_CIPHER_CAMELLIA_192_CCM,\n    MBEDTLS_MODE_CCM,\n    192,\n    \"CAMELLIA-192-CCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &ccm_camellia_info\n};\n\nstatic const mbedtls_cipher_info_t camellia_256_ccm_info = {\n    MBEDTLS_CIPHER_CAMELLIA_256_CCM,\n    MBEDTLS_MODE_CCM,\n    256,\n    \"CAMELLIA-256-CCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &ccm_camellia_info\n};\n#endif /* MBEDTLS_CCM_C */\n\n#endif /* MBEDTLS_CAMELLIA_C */\n\n#if defined(MBEDTLS_ARIA_C)\n\nstatic int aria_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,\n        const unsigned char *input, unsigned char *output )\n{\n    (void) operation;\n    return mbedtls_aria_crypt_ecb( (mbedtls_aria_context *) ctx, input,\n                               output );\n}\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\nstatic int aria_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation,\n        size_t length, unsigned char *iv,\n        const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_aria_crypt_cbc( (mbedtls_aria_context *) ctx, operation, length, iv,\n                               input, output );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\nstatic int aria_crypt_cfb128_wrap( void *ctx, mbedtls_operation_t operation,\n        size_t length, size_t *iv_off, unsigned char *iv,\n        const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_aria_crypt_cfb128( (mbedtls_aria_context *) ctx, operation, length,\n                                  iv_off, iv, input, output );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\nstatic int aria_crypt_ctr_wrap( void *ctx, size_t length, size_t *nc_off,\n        unsigned char *nonce_counter, unsigned char *stream_block,\n        const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_aria_crypt_ctr( (mbedtls_aria_context *) ctx, length, nc_off,\n                               nonce_counter, stream_block, input, output );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\nstatic int aria_setkey_dec_wrap( void *ctx, const unsigned char *key,\n                                     unsigned int key_bitlen )\n{\n    return mbedtls_aria_setkey_dec( (mbedtls_aria_context *) ctx, key, key_bitlen );\n}\n\nstatic int aria_setkey_enc_wrap( void *ctx, const unsigned char *key,\n                                     unsigned int key_bitlen )\n{\n    return mbedtls_aria_setkey_enc( (mbedtls_aria_context *) ctx, key, key_bitlen );\n}\n\nstatic void * aria_ctx_alloc( void )\n{\n    mbedtls_aria_context *ctx;\n    ctx = mbedtls_calloc( 1, sizeof( mbedtls_aria_context ) );\n\n    if( ctx == NULL )\n        return( NULL );\n\n    mbedtls_aria_init( ctx );\n\n    return( ctx );\n}\n\nstatic void aria_ctx_free( void *ctx )\n{\n    mbedtls_aria_free( (mbedtls_aria_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic const mbedtls_cipher_base_t aria_info = {\n    MBEDTLS_CIPHER_ID_ARIA,\n    aria_crypt_ecb_wrap,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    aria_crypt_cbc_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    aria_crypt_cfb128_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    aria_crypt_ctr_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    NULL,\n#endif\n    aria_setkey_enc_wrap,\n    aria_setkey_dec_wrap,\n    aria_ctx_alloc,\n    aria_ctx_free\n};\n\nstatic const mbedtls_cipher_info_t aria_128_ecb_info = {\n    MBEDTLS_CIPHER_ARIA_128_ECB,\n    MBEDTLS_MODE_ECB,\n    128,\n    \"ARIA-128-ECB\",\n    16,\n    0,\n    16,\n    &aria_info\n};\n\nstatic const mbedtls_cipher_info_t aria_192_ecb_info = {\n    MBEDTLS_CIPHER_ARIA_192_ECB,\n    MBEDTLS_MODE_ECB,\n    192,\n    \"ARIA-192-ECB\",\n    16,\n    0,\n    16,\n    &aria_info\n};\n\nstatic const mbedtls_cipher_info_t aria_256_ecb_info = {\n    MBEDTLS_CIPHER_ARIA_256_ECB,\n    MBEDTLS_MODE_ECB,\n    256,\n    \"ARIA-256-ECB\",\n    16,\n    0,\n    16,\n    &aria_info\n};\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\nstatic const mbedtls_cipher_info_t aria_128_cbc_info = {\n    MBEDTLS_CIPHER_ARIA_128_CBC,\n    MBEDTLS_MODE_CBC,\n    128,\n    \"ARIA-128-CBC\",\n    16,\n    0,\n    16,\n    &aria_info\n};\n\nstatic const mbedtls_cipher_info_t aria_192_cbc_info = {\n    MBEDTLS_CIPHER_ARIA_192_CBC,\n    MBEDTLS_MODE_CBC,\n    192,\n    \"ARIA-192-CBC\",\n    16,\n    0,\n    16,\n    &aria_info\n};\n\nstatic const mbedtls_cipher_info_t aria_256_cbc_info = {\n    MBEDTLS_CIPHER_ARIA_256_CBC,\n    MBEDTLS_MODE_CBC,\n    256,\n    \"ARIA-256-CBC\",\n    16,\n    0,\n    16,\n    &aria_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\nstatic const mbedtls_cipher_info_t aria_128_cfb128_info = {\n    MBEDTLS_CIPHER_ARIA_128_CFB128,\n    MBEDTLS_MODE_CFB,\n    128,\n    \"ARIA-128-CFB128\",\n    16,\n    0,\n    16,\n    &aria_info\n};\n\nstatic const mbedtls_cipher_info_t aria_192_cfb128_info = {\n    MBEDTLS_CIPHER_ARIA_192_CFB128,\n    MBEDTLS_MODE_CFB,\n    192,\n    \"ARIA-192-CFB128\",\n    16,\n    0,\n    16,\n    &aria_info\n};\n\nstatic const mbedtls_cipher_info_t aria_256_cfb128_info = {\n    MBEDTLS_CIPHER_ARIA_256_CFB128,\n    MBEDTLS_MODE_CFB,\n    256,\n    \"ARIA-256-CFB128\",\n    16,\n    0,\n    16,\n    &aria_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\nstatic const mbedtls_cipher_info_t aria_128_ctr_info = {\n    MBEDTLS_CIPHER_ARIA_128_CTR,\n    MBEDTLS_MODE_CTR,\n    128,\n    \"ARIA-128-CTR\",\n    16,\n    0,\n    16,\n    &aria_info\n};\n\nstatic const mbedtls_cipher_info_t aria_192_ctr_info = {\n    MBEDTLS_CIPHER_ARIA_192_CTR,\n    MBEDTLS_MODE_CTR,\n    192,\n    \"ARIA-192-CTR\",\n    16,\n    0,\n    16,\n    &aria_info\n};\n\nstatic const mbedtls_cipher_info_t aria_256_ctr_info = {\n    MBEDTLS_CIPHER_ARIA_256_CTR,\n    MBEDTLS_MODE_CTR,\n    256,\n    \"ARIA-256-CTR\",\n    16,\n    0,\n    16,\n    &aria_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\n#if defined(MBEDTLS_GCM_C)\nstatic int gcm_aria_setkey_wrap( void *ctx, const unsigned char *key,\n                                     unsigned int key_bitlen )\n{\n    return mbedtls_gcm_setkey( (mbedtls_gcm_context *) ctx, MBEDTLS_CIPHER_ID_ARIA,\n                     key, key_bitlen );\n}\n\nstatic const mbedtls_cipher_base_t gcm_aria_info = {\n    MBEDTLS_CIPHER_ID_ARIA,\n    NULL,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    NULL,\n#endif\n    gcm_aria_setkey_wrap,\n    gcm_aria_setkey_wrap,\n    gcm_ctx_alloc,\n    gcm_ctx_free,\n};\n\nstatic const mbedtls_cipher_info_t aria_128_gcm_info = {\n    MBEDTLS_CIPHER_ARIA_128_GCM,\n    MBEDTLS_MODE_GCM,\n    128,\n    \"ARIA-128-GCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &gcm_aria_info\n};\n\nstatic const mbedtls_cipher_info_t aria_192_gcm_info = {\n    MBEDTLS_CIPHER_ARIA_192_GCM,\n    MBEDTLS_MODE_GCM,\n    192,\n    \"ARIA-192-GCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &gcm_aria_info\n};\n\nstatic const mbedtls_cipher_info_t aria_256_gcm_info = {\n    MBEDTLS_CIPHER_ARIA_256_GCM,\n    MBEDTLS_MODE_GCM,\n    256,\n    \"ARIA-256-GCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &gcm_aria_info\n};\n#endif /* MBEDTLS_GCM_C */\n\n#if defined(MBEDTLS_CCM_C)\nstatic int ccm_aria_setkey_wrap( void *ctx, const unsigned char *key,\n                                     unsigned int key_bitlen )\n{\n    return mbedtls_ccm_setkey( (mbedtls_ccm_context *) ctx, MBEDTLS_CIPHER_ID_ARIA,\n                     key, key_bitlen );\n}\n\nstatic const mbedtls_cipher_base_t ccm_aria_info = {\n    MBEDTLS_CIPHER_ID_ARIA,\n    NULL,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    NULL,\n#endif\n    ccm_aria_setkey_wrap,\n    ccm_aria_setkey_wrap,\n    ccm_ctx_alloc,\n    ccm_ctx_free,\n};\n\nstatic const mbedtls_cipher_info_t aria_128_ccm_info = {\n    MBEDTLS_CIPHER_ARIA_128_CCM,\n    MBEDTLS_MODE_CCM,\n    128,\n    \"ARIA-128-CCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &ccm_aria_info\n};\n\nstatic const mbedtls_cipher_info_t aria_192_ccm_info = {\n    MBEDTLS_CIPHER_ARIA_192_CCM,\n    MBEDTLS_MODE_CCM,\n    192,\n    \"ARIA-192-CCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &ccm_aria_info\n};\n\nstatic const mbedtls_cipher_info_t aria_256_ccm_info = {\n    MBEDTLS_CIPHER_ARIA_256_CCM,\n    MBEDTLS_MODE_CCM,\n    256,\n    \"ARIA-256-CCM\",\n    12,\n    MBEDTLS_CIPHER_VARIABLE_IV_LEN,\n    16,\n    &ccm_aria_info\n};\n#endif /* MBEDTLS_CCM_C */\n\n#endif /* MBEDTLS_ARIA_C */\n\n#if defined(MBEDTLS_DES_C)\n\nstatic int des_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,\n        const unsigned char *input, unsigned char *output )\n{\n    ((void) operation);\n    return mbedtls_des_crypt_ecb( (mbedtls_des_context *) ctx, input, output );\n}\n\nstatic int des3_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,\n        const unsigned char *input, unsigned char *output )\n{\n    ((void) operation);\n    return mbedtls_des3_crypt_ecb( (mbedtls_des3_context *) ctx, input, output );\n}\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\nstatic int des_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation, size_t length,\n        unsigned char *iv, const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_des_crypt_cbc( (mbedtls_des_context *) ctx, operation, length, iv, input,\n                          output );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\nstatic int des3_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation, size_t length,\n        unsigned char *iv, const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_des3_crypt_cbc( (mbedtls_des3_context *) ctx, operation, length, iv, input,\n                           output );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\nstatic int des_setkey_dec_wrap( void *ctx, const unsigned char *key,\n                                unsigned int key_bitlen )\n{\n    ((void) key_bitlen);\n\n    return mbedtls_des_setkey_dec( (mbedtls_des_context *) ctx, key );\n}\n\nstatic int des_setkey_enc_wrap( void *ctx, const unsigned char *key,\n                                unsigned int key_bitlen )\n{\n    ((void) key_bitlen);\n\n    return mbedtls_des_setkey_enc( (mbedtls_des_context *) ctx, key );\n}\n\nstatic int des3_set2key_dec_wrap( void *ctx, const unsigned char *key,\n                                  unsigned int key_bitlen )\n{\n    ((void) key_bitlen);\n\n    return mbedtls_des3_set2key_dec( (mbedtls_des3_context *) ctx, key );\n}\n\nstatic int des3_set2key_enc_wrap( void *ctx, const unsigned char *key,\n                                  unsigned int key_bitlen )\n{\n    ((void) key_bitlen);\n\n    return mbedtls_des3_set2key_enc( (mbedtls_des3_context *) ctx, key );\n}\n\nstatic int des3_set3key_dec_wrap( void *ctx, const unsigned char *key,\n                                  unsigned int key_bitlen )\n{\n    ((void) key_bitlen);\n\n    return mbedtls_des3_set3key_dec( (mbedtls_des3_context *) ctx, key );\n}\n\nstatic int des3_set3key_enc_wrap( void *ctx, const unsigned char *key,\n                                  unsigned int key_bitlen )\n{\n    ((void) key_bitlen);\n\n    return mbedtls_des3_set3key_enc( (mbedtls_des3_context *) ctx, key );\n}\n\nstatic void * des_ctx_alloc( void )\n{\n    mbedtls_des_context *des = mbedtls_calloc( 1, sizeof( mbedtls_des_context ) );\n\n    if( des == NULL )\n        return( NULL );\n\n    mbedtls_des_init( des );\n\n    return( des );\n}\n\nstatic void des_ctx_free( void *ctx )\n{\n    mbedtls_des_free( (mbedtls_des_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic void * des3_ctx_alloc( void )\n{\n    mbedtls_des3_context *des3;\n    des3 = mbedtls_calloc( 1, sizeof( mbedtls_des3_context ) );\n\n    if( des3 == NULL )\n        return( NULL );\n\n    mbedtls_des3_init( des3 );\n\n    return( des3 );\n}\n\nstatic void des3_ctx_free( void *ctx )\n{\n    mbedtls_des3_free( (mbedtls_des3_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic const mbedtls_cipher_base_t des_info = {\n    MBEDTLS_CIPHER_ID_DES,\n    des_crypt_ecb_wrap,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    des_crypt_cbc_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    NULL,\n#endif\n    des_setkey_enc_wrap,\n    des_setkey_dec_wrap,\n    des_ctx_alloc,\n    des_ctx_free\n};\n\nstatic const mbedtls_cipher_info_t des_ecb_info = {\n    MBEDTLS_CIPHER_DES_ECB,\n    MBEDTLS_MODE_ECB,\n    MBEDTLS_KEY_LENGTH_DES,\n    \"DES-ECB\",\n    8,\n    0,\n    8,\n    &des_info\n};\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\nstatic const mbedtls_cipher_info_t des_cbc_info = {\n    MBEDTLS_CIPHER_DES_CBC,\n    MBEDTLS_MODE_CBC,\n    MBEDTLS_KEY_LENGTH_DES,\n    \"DES-CBC\",\n    8,\n    0,\n    8,\n    &des_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\nstatic const mbedtls_cipher_base_t des_ede_info = {\n    MBEDTLS_CIPHER_ID_DES,\n    des3_crypt_ecb_wrap,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    des3_crypt_cbc_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    NULL,\n#endif\n    des3_set2key_enc_wrap,\n    des3_set2key_dec_wrap,\n    des3_ctx_alloc,\n    des3_ctx_free\n};\n\nstatic const mbedtls_cipher_info_t des_ede_ecb_info = {\n    MBEDTLS_CIPHER_DES_EDE_ECB,\n    MBEDTLS_MODE_ECB,\n    MBEDTLS_KEY_LENGTH_DES_EDE,\n    \"DES-EDE-ECB\",\n    8,\n    0,\n    8,\n    &des_ede_info\n};\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\nstatic const mbedtls_cipher_info_t des_ede_cbc_info = {\n    MBEDTLS_CIPHER_DES_EDE_CBC,\n    MBEDTLS_MODE_CBC,\n    MBEDTLS_KEY_LENGTH_DES_EDE,\n    \"DES-EDE-CBC\",\n    8,\n    0,\n    8,\n    &des_ede_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\nstatic const mbedtls_cipher_base_t des_ede3_info = {\n    MBEDTLS_CIPHER_ID_3DES,\n    des3_crypt_ecb_wrap,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    des3_crypt_cbc_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    NULL,\n#endif\n    des3_set3key_enc_wrap,\n    des3_set3key_dec_wrap,\n    des3_ctx_alloc,\n    des3_ctx_free\n};\n\nstatic const mbedtls_cipher_info_t des_ede3_ecb_info = {\n    MBEDTLS_CIPHER_DES_EDE3_ECB,\n    MBEDTLS_MODE_ECB,\n    MBEDTLS_KEY_LENGTH_DES_EDE3,\n    \"DES-EDE3-ECB\",\n    8,\n    0,\n    8,\n    &des_ede3_info\n};\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\nstatic const mbedtls_cipher_info_t des_ede3_cbc_info = {\n    MBEDTLS_CIPHER_DES_EDE3_CBC,\n    MBEDTLS_MODE_CBC,\n    MBEDTLS_KEY_LENGTH_DES_EDE3,\n    \"DES-EDE3-CBC\",\n    8,\n    0,\n    8,\n    &des_ede3_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_BLOWFISH_C)\n\nstatic int blowfish_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,\n        const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_blowfish_crypt_ecb( (mbedtls_blowfish_context *) ctx, operation, input,\n                               output );\n}\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\nstatic int blowfish_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation,\n        size_t length, unsigned char *iv, const unsigned char *input,\n        unsigned char *output )\n{\n    return mbedtls_blowfish_crypt_cbc( (mbedtls_blowfish_context *) ctx, operation, length, iv,\n                               input, output );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\nstatic int blowfish_crypt_cfb64_wrap( void *ctx, mbedtls_operation_t operation,\n        size_t length, size_t *iv_off, unsigned char *iv,\n        const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_blowfish_crypt_cfb64( (mbedtls_blowfish_context *) ctx, operation, length,\n                                 iv_off, iv, input, output );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\nstatic int blowfish_crypt_ctr_wrap( void *ctx, size_t length, size_t *nc_off,\n        unsigned char *nonce_counter, unsigned char *stream_block,\n        const unsigned char *input, unsigned char *output )\n{\n    return mbedtls_blowfish_crypt_ctr( (mbedtls_blowfish_context *) ctx, length, nc_off,\n                               nonce_counter, stream_block, input, output );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n\nstatic int blowfish_setkey_wrap( void *ctx, const unsigned char *key,\n                                 unsigned int key_bitlen )\n{\n    return mbedtls_blowfish_setkey( (mbedtls_blowfish_context *) ctx, key, key_bitlen );\n}\n\nstatic void * blowfish_ctx_alloc( void )\n{\n    mbedtls_blowfish_context *ctx;\n    ctx = mbedtls_calloc( 1, sizeof( mbedtls_blowfish_context ) );\n\n    if( ctx == NULL )\n        return( NULL );\n\n    mbedtls_blowfish_init( ctx );\n\n    return( ctx );\n}\n\nstatic void blowfish_ctx_free( void *ctx )\n{\n    mbedtls_blowfish_free( (mbedtls_blowfish_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic const mbedtls_cipher_base_t blowfish_info = {\n    MBEDTLS_CIPHER_ID_BLOWFISH,\n    blowfish_crypt_ecb_wrap,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    blowfish_crypt_cbc_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    blowfish_crypt_cfb64_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    blowfish_crypt_ctr_wrap,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    NULL,\n#endif\n    blowfish_setkey_wrap,\n    blowfish_setkey_wrap,\n    blowfish_ctx_alloc,\n    blowfish_ctx_free\n};\n\nstatic const mbedtls_cipher_info_t blowfish_ecb_info = {\n    MBEDTLS_CIPHER_BLOWFISH_ECB,\n    MBEDTLS_MODE_ECB,\n    128,\n    \"BLOWFISH-ECB\",\n    8,\n    MBEDTLS_CIPHER_VARIABLE_KEY_LEN,\n    8,\n    &blowfish_info\n};\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\nstatic const mbedtls_cipher_info_t blowfish_cbc_info = {\n    MBEDTLS_CIPHER_BLOWFISH_CBC,\n    MBEDTLS_MODE_CBC,\n    128,\n    \"BLOWFISH-CBC\",\n    8,\n    MBEDTLS_CIPHER_VARIABLE_KEY_LEN,\n    8,\n    &blowfish_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\nstatic const mbedtls_cipher_info_t blowfish_cfb64_info = {\n    MBEDTLS_CIPHER_BLOWFISH_CFB64,\n    MBEDTLS_MODE_CFB,\n    128,\n    \"BLOWFISH-CFB64\",\n    8,\n    MBEDTLS_CIPHER_VARIABLE_KEY_LEN,\n    8,\n    &blowfish_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\nstatic const mbedtls_cipher_info_t blowfish_ctr_info = {\n    MBEDTLS_CIPHER_BLOWFISH_CTR,\n    MBEDTLS_MODE_CTR,\n    128,\n    \"BLOWFISH-CTR\",\n    8,\n    MBEDTLS_CIPHER_VARIABLE_KEY_LEN,\n    8,\n    &blowfish_info\n};\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n#endif /* MBEDTLS_BLOWFISH_C */\n\n#if defined(MBEDTLS_ARC4_C)\nstatic int arc4_crypt_stream_wrap( void *ctx, size_t length,\n                                   const unsigned char *input,\n                                   unsigned char *output )\n{\n    return( mbedtls_arc4_crypt( (mbedtls_arc4_context *) ctx, length, input, output ) );\n}\n\nstatic int arc4_setkey_wrap( void *ctx, const unsigned char *key,\n                             unsigned int key_bitlen )\n{\n    /* we get key_bitlen in bits, arc4 expects it in bytes */\n    if( key_bitlen % 8 != 0 )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    mbedtls_arc4_setup( (mbedtls_arc4_context *) ctx, key, key_bitlen / 8 );\n    return( 0 );\n}\n\nstatic void * arc4_ctx_alloc( void )\n{\n    mbedtls_arc4_context *ctx;\n    ctx = mbedtls_calloc( 1, sizeof( mbedtls_arc4_context ) );\n\n    if( ctx == NULL )\n        return( NULL );\n\n    mbedtls_arc4_init( ctx );\n\n    return( ctx );\n}\n\nstatic void arc4_ctx_free( void *ctx )\n{\n    mbedtls_arc4_free( (mbedtls_arc4_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic const mbedtls_cipher_base_t arc4_base_info = {\n    MBEDTLS_CIPHER_ID_ARC4,\n    NULL,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    arc4_crypt_stream_wrap,\n#endif\n    arc4_setkey_wrap,\n    arc4_setkey_wrap,\n    arc4_ctx_alloc,\n    arc4_ctx_free\n};\n\nstatic const mbedtls_cipher_info_t arc4_128_info = {\n    MBEDTLS_CIPHER_ARC4_128,\n    MBEDTLS_MODE_STREAM,\n    128,\n    \"ARC4-128\",\n    0,\n    0,\n    1,\n    &arc4_base_info\n};\n#endif /* MBEDTLS_ARC4_C */\n\n#if defined(MBEDTLS_CHACHA20_C)\n\nstatic int chacha20_setkey_wrap( void *ctx, const unsigned char *key,\n                                 unsigned int key_bitlen )\n{\n    if( key_bitlen != 256U )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    if ( 0 != mbedtls_chacha20_setkey( (mbedtls_chacha20_context*)ctx, key ) )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    return( 0 );\n}\n\nstatic int chacha20_stream_wrap( void *ctx,  size_t length,\n                                 const unsigned char *input,\n                                 unsigned char *output )\n{\n    int ret;\n\n    ret = mbedtls_chacha20_update( ctx, length, input, output );\n    if( ret == MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    return( ret );\n}\n\nstatic void * chacha20_ctx_alloc( void )\n{\n    mbedtls_chacha20_context *ctx;\n    ctx = mbedtls_calloc( 1, sizeof( mbedtls_chacha20_context ) );\n\n    if( ctx == NULL )\n        return( NULL );\n\n    mbedtls_chacha20_init( ctx );\n\n    return( ctx );\n}\n\nstatic void chacha20_ctx_free( void *ctx )\n{\n    mbedtls_chacha20_free( (mbedtls_chacha20_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic const mbedtls_cipher_base_t chacha20_base_info = {\n    MBEDTLS_CIPHER_ID_CHACHA20,\n    NULL,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    chacha20_stream_wrap,\n#endif\n    chacha20_setkey_wrap,\n    chacha20_setkey_wrap,\n    chacha20_ctx_alloc,\n    chacha20_ctx_free\n};\nstatic const mbedtls_cipher_info_t chacha20_info = {\n    MBEDTLS_CIPHER_CHACHA20,\n    MBEDTLS_MODE_STREAM,\n    256,\n    \"CHACHA20\",\n    12,\n    0,\n    1,\n    &chacha20_base_info\n};\n#endif /* MBEDTLS_CHACHA20_C */\n\n#if defined(MBEDTLS_CHACHAPOLY_C)\n\nstatic int chachapoly_setkey_wrap( void *ctx,\n                                   const unsigned char *key,\n                                   unsigned int key_bitlen )\n{\n    if( key_bitlen != 256U )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    if ( 0 != mbedtls_chachapoly_setkey( (mbedtls_chachapoly_context*)ctx, key ) )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    return( 0 );\n}\n\nstatic void * chachapoly_ctx_alloc( void )\n{\n    mbedtls_chachapoly_context *ctx;\n    ctx = mbedtls_calloc( 1, sizeof( mbedtls_chachapoly_context ) );\n\n    if( ctx == NULL )\n        return( NULL );\n\n    mbedtls_chachapoly_init( ctx );\n\n    return( ctx );\n}\n\nstatic void chachapoly_ctx_free( void *ctx )\n{\n    mbedtls_chachapoly_free( (mbedtls_chachapoly_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic const mbedtls_cipher_base_t chachapoly_base_info = {\n    MBEDTLS_CIPHER_ID_CHACHA20,\n    NULL,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    NULL,\n#endif\n    chachapoly_setkey_wrap,\n    chachapoly_setkey_wrap,\n    chachapoly_ctx_alloc,\n    chachapoly_ctx_free\n};\nstatic const mbedtls_cipher_info_t chachapoly_info = {\n    MBEDTLS_CIPHER_CHACHA20_POLY1305,\n    MBEDTLS_MODE_CHACHAPOLY,\n    256,\n    \"CHACHA20-POLY1305\",\n    12,\n    0,\n    1,\n    &chachapoly_base_info\n};\n#endif /* MBEDTLS_CHACHAPOLY_C */\n\n#if defined(MBEDTLS_CIPHER_NULL_CIPHER)\nstatic int null_crypt_stream( void *ctx, size_t length,\n                              const unsigned char *input,\n                              unsigned char *output )\n{\n    ((void) ctx);\n    memmove( output, input, length );\n    return( 0 );\n}\n\nstatic int null_setkey( void *ctx, const unsigned char *key,\n                        unsigned int key_bitlen )\n{\n    ((void) ctx);\n    ((void) key);\n    ((void) key_bitlen);\n\n    return( 0 );\n}\n\nstatic void * null_ctx_alloc( void )\n{\n    return( (void *) 1 );\n}\n\nstatic void null_ctx_free( void *ctx )\n{\n    ((void) ctx);\n}\n\nstatic const mbedtls_cipher_base_t null_base_info = {\n    MBEDTLS_CIPHER_ID_NULL,\n    NULL,\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    NULL,\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_STREAM)\n    null_crypt_stream,\n#endif\n    null_setkey,\n    null_setkey,\n    null_ctx_alloc,\n    null_ctx_free\n};\n\nstatic const mbedtls_cipher_info_t null_cipher_info = {\n    MBEDTLS_CIPHER_NULL,\n    MBEDTLS_MODE_STREAM,\n    0,\n    \"NULL\",\n    0,\n    0,\n    1,\n    &null_base_info\n};\n#endif /* defined(MBEDTLS_CIPHER_NULL_CIPHER) */\n\nconst mbedtls_cipher_definition_t mbedtls_cipher_definitions[] =\n{\n#if defined(MBEDTLS_AES_C)\n    { MBEDTLS_CIPHER_AES_128_ECB,          &aes_128_ecb_info },\n    { MBEDTLS_CIPHER_AES_192_ECB,          &aes_192_ecb_info },\n    { MBEDTLS_CIPHER_AES_256_ECB,          &aes_256_ecb_info },\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_CIPHER_AES_128_CBC,          &aes_128_cbc_info },\n    { MBEDTLS_CIPHER_AES_192_CBC,          &aes_192_cbc_info },\n    { MBEDTLS_CIPHER_AES_256_CBC,          &aes_256_cbc_info },\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    { MBEDTLS_CIPHER_AES_128_CFB128,       &aes_128_cfb128_info },\n    { MBEDTLS_CIPHER_AES_192_CFB128,       &aes_192_cfb128_info },\n    { MBEDTLS_CIPHER_AES_256_CFB128,       &aes_256_cfb128_info },\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    { MBEDTLS_CIPHER_AES_128_OFB,          &aes_128_ofb_info },\n    { MBEDTLS_CIPHER_AES_192_OFB,          &aes_192_ofb_info },\n    { MBEDTLS_CIPHER_AES_256_OFB,          &aes_256_ofb_info },\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    { MBEDTLS_CIPHER_AES_128_CTR,          &aes_128_ctr_info },\n    { MBEDTLS_CIPHER_AES_192_CTR,          &aes_192_ctr_info },\n    { MBEDTLS_CIPHER_AES_256_CTR,          &aes_256_ctr_info },\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    { MBEDTLS_CIPHER_AES_128_XTS,          &aes_128_xts_info },\n    { MBEDTLS_CIPHER_AES_256_XTS,          &aes_256_xts_info },\n#endif\n#if defined(MBEDTLS_GCM_C)\n    { MBEDTLS_CIPHER_AES_128_GCM,          &aes_128_gcm_info },\n    { MBEDTLS_CIPHER_AES_192_GCM,          &aes_192_gcm_info },\n    { MBEDTLS_CIPHER_AES_256_GCM,          &aes_256_gcm_info },\n#endif\n#if defined(MBEDTLS_CCM_C)\n    { MBEDTLS_CIPHER_AES_128_CCM,          &aes_128_ccm_info },\n    { MBEDTLS_CIPHER_AES_192_CCM,          &aes_192_ccm_info },\n    { MBEDTLS_CIPHER_AES_256_CCM,          &aes_256_ccm_info },\n#endif\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_ARC4_C)\n    { MBEDTLS_CIPHER_ARC4_128,             &arc4_128_info },\n#endif\n\n#if defined(MBEDTLS_BLOWFISH_C)\n    { MBEDTLS_CIPHER_BLOWFISH_ECB,         &blowfish_ecb_info },\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_CIPHER_BLOWFISH_CBC,         &blowfish_cbc_info },\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    { MBEDTLS_CIPHER_BLOWFISH_CFB64,       &blowfish_cfb64_info },\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    { MBEDTLS_CIPHER_BLOWFISH_CTR,         &blowfish_ctr_info },\n#endif\n#endif /* MBEDTLS_BLOWFISH_C */\n\n#if defined(MBEDTLS_CAMELLIA_C)\n    { MBEDTLS_CIPHER_CAMELLIA_128_ECB,     &camellia_128_ecb_info },\n    { MBEDTLS_CIPHER_CAMELLIA_192_ECB,     &camellia_192_ecb_info },\n    { MBEDTLS_CIPHER_CAMELLIA_256_ECB,     &camellia_256_ecb_info },\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_CIPHER_CAMELLIA_128_CBC,     &camellia_128_cbc_info },\n    { MBEDTLS_CIPHER_CAMELLIA_192_CBC,     &camellia_192_cbc_info },\n    { MBEDTLS_CIPHER_CAMELLIA_256_CBC,     &camellia_256_cbc_info },\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    { MBEDTLS_CIPHER_CAMELLIA_128_CFB128,  &camellia_128_cfb128_info },\n    { MBEDTLS_CIPHER_CAMELLIA_192_CFB128,  &camellia_192_cfb128_info },\n    { MBEDTLS_CIPHER_CAMELLIA_256_CFB128,  &camellia_256_cfb128_info },\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    { MBEDTLS_CIPHER_CAMELLIA_128_CTR,     &camellia_128_ctr_info },\n    { MBEDTLS_CIPHER_CAMELLIA_192_CTR,     &camellia_192_ctr_info },\n    { MBEDTLS_CIPHER_CAMELLIA_256_CTR,     &camellia_256_ctr_info },\n#endif\n#if defined(MBEDTLS_GCM_C)\n    { MBEDTLS_CIPHER_CAMELLIA_128_GCM,     &camellia_128_gcm_info },\n    { MBEDTLS_CIPHER_CAMELLIA_192_GCM,     &camellia_192_gcm_info },\n    { MBEDTLS_CIPHER_CAMELLIA_256_GCM,     &camellia_256_gcm_info },\n#endif\n#if defined(MBEDTLS_CCM_C)\n    { MBEDTLS_CIPHER_CAMELLIA_128_CCM,     &camellia_128_ccm_info },\n    { MBEDTLS_CIPHER_CAMELLIA_192_CCM,     &camellia_192_ccm_info },\n    { MBEDTLS_CIPHER_CAMELLIA_256_CCM,     &camellia_256_ccm_info },\n#endif\n#endif /* MBEDTLS_CAMELLIA_C */\n\n#if defined(MBEDTLS_ARIA_C)\n    { MBEDTLS_CIPHER_ARIA_128_ECB,     &aria_128_ecb_info },\n    { MBEDTLS_CIPHER_ARIA_192_ECB,     &aria_192_ecb_info },\n    { MBEDTLS_CIPHER_ARIA_256_ECB,     &aria_256_ecb_info },\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_CIPHER_ARIA_128_CBC,     &aria_128_cbc_info },\n    { MBEDTLS_CIPHER_ARIA_192_CBC,     &aria_192_cbc_info },\n    { MBEDTLS_CIPHER_ARIA_256_CBC,     &aria_256_cbc_info },\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    { MBEDTLS_CIPHER_ARIA_128_CFB128,  &aria_128_cfb128_info },\n    { MBEDTLS_CIPHER_ARIA_192_CFB128,  &aria_192_cfb128_info },\n    { MBEDTLS_CIPHER_ARIA_256_CFB128,  &aria_256_cfb128_info },\n#endif\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    { MBEDTLS_CIPHER_ARIA_128_CTR,     &aria_128_ctr_info },\n    { MBEDTLS_CIPHER_ARIA_192_CTR,     &aria_192_ctr_info },\n    { MBEDTLS_CIPHER_ARIA_256_CTR,     &aria_256_ctr_info },\n#endif\n#if defined(MBEDTLS_GCM_C)\n    { MBEDTLS_CIPHER_ARIA_128_GCM,     &aria_128_gcm_info },\n    { MBEDTLS_CIPHER_ARIA_192_GCM,     &aria_192_gcm_info },\n    { MBEDTLS_CIPHER_ARIA_256_GCM,     &aria_256_gcm_info },\n#endif\n#if defined(MBEDTLS_CCM_C)\n    { MBEDTLS_CIPHER_ARIA_128_CCM,     &aria_128_ccm_info },\n    { MBEDTLS_CIPHER_ARIA_192_CCM,     &aria_192_ccm_info },\n    { MBEDTLS_CIPHER_ARIA_256_CCM,     &aria_256_ccm_info },\n#endif\n#endif /* MBEDTLS_ARIA_C */\n\n#if defined(MBEDTLS_DES_C)\n    { MBEDTLS_CIPHER_DES_ECB,              &des_ecb_info },\n    { MBEDTLS_CIPHER_DES_EDE_ECB,          &des_ede_ecb_info },\n    { MBEDTLS_CIPHER_DES_EDE3_ECB,         &des_ede3_ecb_info },\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_CIPHER_DES_CBC,              &des_cbc_info },\n    { MBEDTLS_CIPHER_DES_EDE_CBC,          &des_ede_cbc_info },\n    { MBEDTLS_CIPHER_DES_EDE3_CBC,         &des_ede3_cbc_info },\n#endif\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_CHACHA20_C)\n    { MBEDTLS_CIPHER_CHACHA20,             &chacha20_info },\n#endif\n\n#if defined(MBEDTLS_CHACHAPOLY_C)\n    { MBEDTLS_CIPHER_CHACHA20_POLY1305,    &chachapoly_info },\n#endif\n\n#if defined(MBEDTLS_CIPHER_NULL_CIPHER)\n    { MBEDTLS_CIPHER_NULL,                 &null_cipher_info },\n#endif /* MBEDTLS_CIPHER_NULL_CIPHER */\n\n    { MBEDTLS_CIPHER_NONE, NULL }\n};\n\n#define NUM_CIPHERS sizeof mbedtls_cipher_definitions / sizeof mbedtls_cipher_definitions[0]\nint mbedtls_cipher_supported[NUM_CIPHERS];\n\n#endif /* MBEDTLS_CIPHER_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/cmac.c",
    "content": "/**\n * \\file cmac.c\n *\n * \\brief NIST SP800-38B compliant CMAC implementation for AES and 3DES\n *\n *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n/*\n * References:\n *\n * - NIST SP 800-38B Recommendation for Block Cipher Modes of Operation: The\n *      CMAC Mode for Authentication\n *   http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38b.pdf\n *\n * - RFC 4493 - The AES-CMAC Algorithm\n *   https://tools.ietf.org/html/rfc4493\n *\n * - RFC 4615 - The Advanced Encryption Standard-Cipher-based Message\n *      Authentication Code-Pseudo-Random Function-128 (AES-CMAC-PRF-128)\n *      Algorithm for the Internet Key Exchange Protocol (IKE)\n *   https://tools.ietf.org/html/rfc4615\n *\n *   Additional test vectors: ISO/IEC 9797-1\n *\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_CMAC_C)\n\n#include \"mbedtls/cmac.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc     calloc\n#define mbedtls_free       free\n#if defined(MBEDTLS_SELF_TEST)\n#include <stdio.h>\n#define mbedtls_printf     printf\n#endif /* MBEDTLS_SELF_TEST */\n#endif /* MBEDTLS_PLATFORM_C */\n\n#if !defined(MBEDTLS_CMAC_ALT) || defined(MBEDTLS_SELF_TEST)\n\n/*\n * Multiplication by u in the Galois field of GF(2^n)\n *\n * As explained in NIST SP 800-38B, this can be computed:\n *\n *   If MSB(p) = 0, then p = (p << 1)\n *   If MSB(p) = 1, then p = (p << 1) ^ R_n\n *   with R_64 = 0x1B and  R_128 = 0x87\n *\n * Input and output MUST NOT point to the same buffer\n * Block size must be 8 bytes or 16 bytes - the block sizes for DES and AES.\n */\nstatic int cmac_multiply_by_u( unsigned char *output,\n                               const unsigned char *input,\n                               size_t blocksize )\n{\n    const unsigned char R_128 = 0x87;\n    const unsigned char R_64 = 0x1B;\n    unsigned char R_n, mask;\n    unsigned char overflow = 0x00;\n    int i;\n\n    if( blocksize == MBEDTLS_AES_BLOCK_SIZE )\n    {\n        R_n = R_128;\n    }\n    else if( blocksize == MBEDTLS_DES3_BLOCK_SIZE )\n    {\n        R_n = R_64;\n    }\n    else\n    {\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n    }\n\n    for( i = (int)blocksize - 1; i >= 0; i-- )\n    {\n        output[i] = input[i] << 1 | overflow;\n        overflow = input[i] >> 7;\n    }\n\n    /* mask = ( input[0] >> 7 ) ? 0xff : 0x00\n     * using bit operations to avoid branches */\n\n    /* MSVC has a warning about unary minus on unsigned, but this is\n     * well-defined and precisely what we want to do here */\n#if defined(_MSC_VER)\n#pragma warning( push )\n#pragma warning( disable : 4146 )\n#endif\n    mask = - ( input[0] >> 7 );\n#if defined(_MSC_VER)\n#pragma warning( pop )\n#endif\n\n    output[ blocksize - 1 ] ^= R_n & mask;\n\n    return( 0 );\n}\n\n/*\n * Generate subkeys\n *\n * - as specified by RFC 4493, section 2.3 Subkey Generation Algorithm\n */\nstatic int cmac_generate_subkeys( mbedtls_cipher_context_t *ctx,\n                                  unsigned char* K1, unsigned char* K2 )\n{\n    int ret;\n    unsigned char L[MBEDTLS_CIPHER_BLKSIZE_MAX];\n    size_t olen, block_size;\n\n    mbedtls_platform_zeroize( L, sizeof( L ) );\n\n    block_size = ctx->cipher_info->block_size;\n\n    /* Calculate Ek(0) */\n    if( ( ret = mbedtls_cipher_update( ctx, L, block_size, L, &olen ) ) != 0 )\n        goto exit;\n\n    /*\n     * Generate K1 and K2\n     */\n    if( ( ret = cmac_multiply_by_u( K1, L , block_size ) ) != 0 )\n        goto exit;\n\n    if( ( ret = cmac_multiply_by_u( K2, K1 , block_size ) ) != 0 )\n        goto exit;\n\nexit:\n    mbedtls_platform_zeroize( L, sizeof( L ) );\n\n    return( ret );\n}\n#endif /* !defined(MBEDTLS_CMAC_ALT) || defined(MBEDTLS_SELF_TEST) */\n\n#if !defined(MBEDTLS_CMAC_ALT)\nstatic void cmac_xor_block( unsigned char *output, const unsigned char *input1,\n                            const unsigned char *input2,\n                            const size_t block_size )\n{\n    size_t idx;\n\n    for( idx = 0; idx < block_size; idx++ )\n        output[ idx ] = input1[ idx ] ^ input2[ idx ];\n}\n\n/*\n * Create padded last block from (partial) last block.\n *\n * We can't use the padding option from the cipher layer, as it only works for\n * CBC and we use ECB mode, and anyway we need to XOR K1 or K2 in addition.\n */\nstatic void cmac_pad( unsigned char padded_block[MBEDTLS_CIPHER_BLKSIZE_MAX],\n                      size_t padded_block_len,\n                      const unsigned char *last_block,\n                      size_t last_block_len )\n{\n    size_t j;\n\n    for( j = 0; j < padded_block_len; j++ )\n    {\n        if( j < last_block_len )\n            padded_block[j] = last_block[j];\n        else if( j == last_block_len )\n            padded_block[j] = 0x80;\n        else\n            padded_block[j] = 0x00;\n    }\n}\n\nint mbedtls_cipher_cmac_starts( mbedtls_cipher_context_t *ctx,\n                                const unsigned char *key, size_t keybits )\n{\n    mbedtls_cipher_type_t type;\n    mbedtls_cmac_context_t *cmac_ctx;\n    int retval;\n\n    if( ctx == NULL || ctx->cipher_info == NULL || key == NULL )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    if( ( retval = mbedtls_cipher_setkey( ctx, key, (int)keybits,\n                                          MBEDTLS_ENCRYPT ) ) != 0 )\n        return( retval );\n\n    type = ctx->cipher_info->type;\n\n    switch( type )\n    {\n        case MBEDTLS_CIPHER_AES_128_ECB:\n        case MBEDTLS_CIPHER_AES_192_ECB:\n        case MBEDTLS_CIPHER_AES_256_ECB:\n        case MBEDTLS_CIPHER_DES_EDE3_ECB:\n            break;\n        default:\n            return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n    }\n\n    /* Allocated and initialise in the cipher context memory for the CMAC\n     * context */\n    cmac_ctx = mbedtls_calloc( 1, sizeof( mbedtls_cmac_context_t ) );\n    if( cmac_ctx == NULL )\n        return( MBEDTLS_ERR_CIPHER_ALLOC_FAILED );\n\n    ctx->cmac_ctx = cmac_ctx;\n\n    mbedtls_platform_zeroize( cmac_ctx->state, sizeof( cmac_ctx->state ) );\n\n    return 0;\n}\n\nint mbedtls_cipher_cmac_update( mbedtls_cipher_context_t *ctx,\n                                const unsigned char *input, size_t ilen )\n{\n    mbedtls_cmac_context_t* cmac_ctx;\n    unsigned char *state;\n    int ret = 0;\n    size_t n, j, olen, block_size;\n\n    if( ctx == NULL || ctx->cipher_info == NULL || input == NULL ||\n        ctx->cmac_ctx == NULL )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    cmac_ctx = ctx->cmac_ctx;\n    block_size = ctx->cipher_info->block_size;\n    state = ctx->cmac_ctx->state;\n\n    /* Is there data still to process from the last call, that's greater in\n     * size than a block? */\n    if( cmac_ctx->unprocessed_len > 0 &&\n        ilen > block_size - cmac_ctx->unprocessed_len )\n    {\n        memcpy( &cmac_ctx->unprocessed_block[cmac_ctx->unprocessed_len],\n                input,\n                block_size - cmac_ctx->unprocessed_len );\n\n        cmac_xor_block( state, cmac_ctx->unprocessed_block, state, block_size );\n\n        if( ( ret = mbedtls_cipher_update( ctx, state, block_size, state,\n                                           &olen ) ) != 0 )\n        {\n           goto exit;\n        }\n\n        input += block_size - cmac_ctx->unprocessed_len;\n        ilen -= block_size - cmac_ctx->unprocessed_len;\n        cmac_ctx->unprocessed_len = 0;\n    }\n\n    /* n is the number of blocks including any final partial block */\n    n = ( ilen + block_size - 1 ) / block_size;\n\n    /* Iterate across the input data in block sized chunks, excluding any\n     * final partial or complete block */\n    for( j = 1; j < n; j++ )\n    {\n        cmac_xor_block( state, input, state, block_size );\n\n        if( ( ret = mbedtls_cipher_update( ctx, state, block_size, state,\n                                           &olen ) ) != 0 )\n           goto exit;\n\n        ilen -= block_size;\n        input += block_size;\n    }\n\n    /* If there is data left over that wasn't aligned to a block */\n    if( ilen > 0 )\n    {\n        memcpy( &cmac_ctx->unprocessed_block[cmac_ctx->unprocessed_len],\n                input,\n                ilen );\n        cmac_ctx->unprocessed_len += ilen;\n    }\n\nexit:\n    return( ret );\n}\n\nint mbedtls_cipher_cmac_finish( mbedtls_cipher_context_t *ctx,\n                                unsigned char *output )\n{\n    mbedtls_cmac_context_t* cmac_ctx;\n    unsigned char *state, *last_block;\n    unsigned char K1[MBEDTLS_CIPHER_BLKSIZE_MAX];\n    unsigned char K2[MBEDTLS_CIPHER_BLKSIZE_MAX];\n    unsigned char M_last[MBEDTLS_CIPHER_BLKSIZE_MAX];\n    int ret;\n    size_t olen, block_size;\n\n    if( ctx == NULL || ctx->cipher_info == NULL || ctx->cmac_ctx == NULL ||\n        output == NULL )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    cmac_ctx = ctx->cmac_ctx;\n    block_size = ctx->cipher_info->block_size;\n    state = cmac_ctx->state;\n\n    mbedtls_platform_zeroize( K1, sizeof( K1 ) );\n    mbedtls_platform_zeroize( K2, sizeof( K2 ) );\n    cmac_generate_subkeys( ctx, K1, K2 );\n\n    last_block = cmac_ctx->unprocessed_block;\n\n    /* Calculate last block */\n    if( cmac_ctx->unprocessed_len < block_size )\n    {\n        cmac_pad( M_last, block_size, last_block, cmac_ctx->unprocessed_len );\n        cmac_xor_block( M_last, M_last, K2, block_size );\n    }\n    else\n    {\n        /* Last block is complete block */\n        cmac_xor_block( M_last, last_block, K1, block_size );\n    }\n\n\n    cmac_xor_block( state, M_last, state, block_size );\n    if( ( ret = mbedtls_cipher_update( ctx, state, block_size, state,\n                                       &olen ) ) != 0 )\n    {\n        goto exit;\n    }\n\n    memcpy( output, state, block_size );\n\nexit:\n    /* Wipe the generated keys on the stack, and any other transients to avoid\n     * side channel leakage */\n    mbedtls_platform_zeroize( K1, sizeof( K1 ) );\n    mbedtls_platform_zeroize( K2, sizeof( K2 ) );\n\n    cmac_ctx->unprocessed_len = 0;\n    mbedtls_platform_zeroize( cmac_ctx->unprocessed_block,\n                              sizeof( cmac_ctx->unprocessed_block ) );\n\n    mbedtls_platform_zeroize( state, MBEDTLS_CIPHER_BLKSIZE_MAX );\n    return( ret );\n}\n\nint mbedtls_cipher_cmac_reset( mbedtls_cipher_context_t *ctx )\n{\n    mbedtls_cmac_context_t* cmac_ctx;\n\n    if( ctx == NULL || ctx->cipher_info == NULL || ctx->cmac_ctx == NULL )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    cmac_ctx = ctx->cmac_ctx;\n\n    /* Reset the internal state */\n    cmac_ctx->unprocessed_len = 0;\n    mbedtls_platform_zeroize( cmac_ctx->unprocessed_block,\n                              sizeof( cmac_ctx->unprocessed_block ) );\n    mbedtls_platform_zeroize( cmac_ctx->state,\n                              sizeof( cmac_ctx->state ) );\n\n    return( 0 );\n}\n\nint mbedtls_cipher_cmac( const mbedtls_cipher_info_t *cipher_info,\n                         const unsigned char *key, size_t keylen,\n                         const unsigned char *input, size_t ilen,\n                         unsigned char *output )\n{\n    mbedtls_cipher_context_t ctx;\n    int ret;\n\n    if( cipher_info == NULL || key == NULL || input == NULL || output == NULL )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    mbedtls_cipher_init( &ctx );\n\n    if( ( ret = mbedtls_cipher_setup( &ctx, cipher_info ) ) != 0 )\n        goto exit;\n\n    ret = mbedtls_cipher_cmac_starts( &ctx, key, keylen );\n    if( ret != 0 )\n        goto exit;\n\n    ret = mbedtls_cipher_cmac_update( &ctx, input, ilen );\n    if( ret != 0 )\n        goto exit;\n\n    ret = mbedtls_cipher_cmac_finish( &ctx, output );\n\nexit:\n    mbedtls_cipher_free( &ctx );\n\n    return( ret );\n}\n\n#if defined(MBEDTLS_AES_C)\n/*\n * Implementation of AES-CMAC-PRF-128 defined in RFC 4615\n */\nint mbedtls_aes_cmac_prf_128( const unsigned char *key, size_t key_length,\n                              const unsigned char *input, size_t in_len,\n                              unsigned char *output )\n{\n    int ret;\n    const mbedtls_cipher_info_t *cipher_info;\n    unsigned char zero_key[MBEDTLS_AES_BLOCK_SIZE];\n    unsigned char int_key[MBEDTLS_AES_BLOCK_SIZE];\n\n    if( key == NULL || input == NULL || output == NULL )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    cipher_info = mbedtls_cipher_info_from_type( MBEDTLS_CIPHER_AES_128_ECB );\n    if( cipher_info == NULL )\n    {\n        /* Failing at this point must be due to a build issue */\n        ret = MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE;\n        goto exit;\n    }\n\n    if( key_length == MBEDTLS_AES_BLOCK_SIZE )\n    {\n        /* Use key as is */\n        memcpy( int_key, key, MBEDTLS_AES_BLOCK_SIZE );\n    }\n    else\n    {\n        memset( zero_key, 0, MBEDTLS_AES_BLOCK_SIZE );\n\n        ret = mbedtls_cipher_cmac( cipher_info, zero_key, 128, key,\n                                   key_length, int_key );\n        if( ret != 0 )\n            goto exit;\n    }\n\n    ret = mbedtls_cipher_cmac( cipher_info, int_key, 128, input, in_len,\n                               output );\n\nexit:\n    mbedtls_platform_zeroize( int_key, sizeof( int_key ) );\n\n    return( ret );\n}\n#endif /* MBEDTLS_AES_C */\n\n#endif /* !MBEDTLS_CMAC_ALT */\n\n#if defined(MBEDTLS_SELF_TEST)\n/*\n * CMAC test data for SP800-38B\n * http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/AES_CMAC.pdf\n * http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/TDES_CMAC.pdf\n *\n * AES-CMAC-PRF-128 test data from RFC 4615\n * https://tools.ietf.org/html/rfc4615#page-4\n */\n\n#define NB_CMAC_TESTS_PER_KEY 4\n#define NB_PRF_TESTS 3\n\n#if defined(MBEDTLS_AES_C) || defined(MBEDTLS_DES_C)\n/* All CMAC test inputs are truncated from the same 64 byte buffer. */\nstatic const unsigned char test_message[] = {\n    /* PT */\n    0x6b, 0xc1, 0xbe, 0xe2,     0x2e, 0x40, 0x9f, 0x96,\n    0xe9, 0x3d, 0x7e, 0x11,     0x73, 0x93, 0x17, 0x2a,\n    0xae, 0x2d, 0x8a, 0x57,     0x1e, 0x03, 0xac, 0x9c,\n    0x9e, 0xb7, 0x6f, 0xac,     0x45, 0xaf, 0x8e, 0x51,\n    0x30, 0xc8, 0x1c, 0x46,     0xa3, 0x5c, 0xe4, 0x11,\n    0xe5, 0xfb, 0xc1, 0x19,     0x1a, 0x0a, 0x52, 0xef,\n    0xf6, 0x9f, 0x24, 0x45,     0xdf, 0x4f, 0x9b, 0x17,\n    0xad, 0x2b, 0x41, 0x7b,     0xe6, 0x6c, 0x37, 0x10\n};\n#endif /* MBEDTLS_AES_C || MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_AES_C)\n/* Truncation point of message for AES CMAC tests  */\nstatic const  unsigned int  aes_message_lengths[NB_CMAC_TESTS_PER_KEY] = {\n    /* Mlen */\n    0,\n    16,\n    20,\n    64\n};\n\n/* CMAC-AES128 Test Data */\nstatic const unsigned char aes_128_key[16] = {\n    0x2b, 0x7e, 0x15, 0x16,     0x28, 0xae, 0xd2, 0xa6,\n    0xab, 0xf7, 0x15, 0x88,     0x09, 0xcf, 0x4f, 0x3c\n};\nstatic const unsigned char aes_128_subkeys[2][MBEDTLS_AES_BLOCK_SIZE] = {\n    {\n        /* K1 */\n        0xfb, 0xee, 0xd6, 0x18,     0x35, 0x71, 0x33, 0x66,\n        0x7c, 0x85, 0xe0, 0x8f,     0x72, 0x36, 0xa8, 0xde\n    },\n    {\n        /* K2 */\n        0xf7, 0xdd, 0xac, 0x30,     0x6a, 0xe2, 0x66, 0xcc,\n        0xf9, 0x0b, 0xc1, 0x1e,     0xe4, 0x6d, 0x51, 0x3b\n    }\n};\nstatic const unsigned char aes_128_expected_result[NB_CMAC_TESTS_PER_KEY][MBEDTLS_AES_BLOCK_SIZE] = {\n    {\n        /* Example #1 */\n        0xbb, 0x1d, 0x69, 0x29,     0xe9, 0x59, 0x37, 0x28,\n        0x7f, 0xa3, 0x7d, 0x12,     0x9b, 0x75, 0x67, 0x46\n    },\n    {\n        /* Example #2 */\n        0x07, 0x0a, 0x16, 0xb4,     0x6b, 0x4d, 0x41, 0x44,\n        0xf7, 0x9b, 0xdd, 0x9d,     0xd0, 0x4a, 0x28, 0x7c\n    },\n    {\n        /* Example #3 */\n        0x7d, 0x85, 0x44, 0x9e,     0xa6, 0xea, 0x19, 0xc8,\n        0x23, 0xa7, 0xbf, 0x78,     0x83, 0x7d, 0xfa, 0xde\n    },\n    {\n        /* Example #4 */\n        0x51, 0xf0, 0xbe, 0xbf,     0x7e, 0x3b, 0x9d, 0x92,\n        0xfc, 0x49, 0x74, 0x17,     0x79, 0x36, 0x3c, 0xfe\n    }\n};\n\n/* CMAC-AES192 Test Data */\nstatic const unsigned char aes_192_key[24] = {\n    0x8e, 0x73, 0xb0, 0xf7,     0xda, 0x0e, 0x64, 0x52,\n    0xc8, 0x10, 0xf3, 0x2b,     0x80, 0x90, 0x79, 0xe5,\n    0x62, 0xf8, 0xea, 0xd2,     0x52, 0x2c, 0x6b, 0x7b\n};\nstatic const unsigned char aes_192_subkeys[2][MBEDTLS_AES_BLOCK_SIZE] = {\n    {\n        /* K1 */\n        0x44, 0x8a, 0x5b, 0x1c,     0x93, 0x51, 0x4b, 0x27,\n        0x3e, 0xe6, 0x43, 0x9d,     0xd4, 0xda, 0xa2, 0x96\n    },\n    {\n        /* K2 */\n        0x89, 0x14, 0xb6, 0x39,     0x26, 0xa2, 0x96, 0x4e,\n        0x7d, 0xcc, 0x87, 0x3b,     0xa9, 0xb5, 0x45, 0x2c\n    }\n};\nstatic const unsigned char aes_192_expected_result[NB_CMAC_TESTS_PER_KEY][MBEDTLS_AES_BLOCK_SIZE] = {\n    {\n        /* Example #1 */\n        0xd1, 0x7d, 0xdf, 0x46,     0xad, 0xaa, 0xcd, 0xe5,\n        0x31, 0xca, 0xc4, 0x83,     0xde, 0x7a, 0x93, 0x67\n    },\n    {\n        /* Example #2 */\n        0x9e, 0x99, 0xa7, 0xbf,     0x31, 0xe7, 0x10, 0x90,\n        0x06, 0x62, 0xf6, 0x5e,     0x61, 0x7c, 0x51, 0x84\n    },\n    {\n        /* Example #3 */\n        0x3d, 0x75, 0xc1, 0x94,     0xed, 0x96, 0x07, 0x04,\n        0x44, 0xa9, 0xfa, 0x7e,     0xc7, 0x40, 0xec, 0xf8\n    },\n    {\n        /* Example #4 */\n        0xa1, 0xd5, 0xdf, 0x0e,     0xed, 0x79, 0x0f, 0x79,\n        0x4d, 0x77, 0x58, 0x96,     0x59, 0xf3, 0x9a, 0x11\n    }\n};\n\n/* CMAC-AES256 Test Data */\nstatic const unsigned char aes_256_key[32] = {\n    0x60, 0x3d, 0xeb, 0x10,     0x15, 0xca, 0x71, 0xbe,\n    0x2b, 0x73, 0xae, 0xf0,     0x85, 0x7d, 0x77, 0x81,\n    0x1f, 0x35, 0x2c, 0x07,     0x3b, 0x61, 0x08, 0xd7,\n    0x2d, 0x98, 0x10, 0xa3,     0x09, 0x14, 0xdf, 0xf4\n};\nstatic const unsigned char aes_256_subkeys[2][MBEDTLS_AES_BLOCK_SIZE] = {\n    {\n        /* K1 */\n        0xca, 0xd1, 0xed, 0x03,     0x29, 0x9e, 0xed, 0xac,\n        0x2e, 0x9a, 0x99, 0x80,     0x86, 0x21, 0x50, 0x2f\n    },\n    {\n        /* K2 */\n        0x95, 0xa3, 0xda, 0x06,     0x53, 0x3d, 0xdb, 0x58,\n        0x5d, 0x35, 0x33, 0x01,     0x0c, 0x42, 0xa0, 0xd9\n    }\n};\nstatic const unsigned char aes_256_expected_result[NB_CMAC_TESTS_PER_KEY][MBEDTLS_AES_BLOCK_SIZE] = {\n    {\n        /* Example #1 */\n        0x02, 0x89, 0x62, 0xf6,     0x1b, 0x7b, 0xf8, 0x9e,\n        0xfc, 0x6b, 0x55, 0x1f,     0x46, 0x67, 0xd9, 0x83\n    },\n    {\n        /* Example #2 */\n        0x28, 0xa7, 0x02, 0x3f,     0x45, 0x2e, 0x8f, 0x82,\n        0xbd, 0x4b, 0xf2, 0x8d,     0x8c, 0x37, 0xc3, 0x5c\n    },\n    {\n        /* Example #3 */\n        0x15, 0x67, 0x27, 0xdc,     0x08, 0x78, 0x94, 0x4a,\n        0x02, 0x3c, 0x1f, 0xe0,     0x3b, 0xad, 0x6d, 0x93\n    },\n    {\n        /* Example #4 */\n        0xe1, 0x99, 0x21, 0x90,     0x54, 0x9f, 0x6e, 0xd5,\n        0x69, 0x6a, 0x2c, 0x05,     0x6c, 0x31, 0x54, 0x10\n    }\n};\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_DES_C)\n/* Truncation point of message for 3DES CMAC tests  */\nstatic const unsigned int des3_message_lengths[NB_CMAC_TESTS_PER_KEY] = {\n    0,\n    16,\n    20,\n    32\n};\n\n/* CMAC-TDES (Generation) - 2 Key Test Data */\nstatic const unsigned char des3_2key_key[24] = {\n    /* Key1 */\n    0x01, 0x23, 0x45, 0x67,     0x89, 0xab, 0xcd, 0xef,\n    /* Key2 */\n    0x23, 0x45, 0x67, 0x89,     0xab, 0xcd, 0xEF, 0x01,\n    /* Key3 */\n    0x01, 0x23, 0x45, 0x67,     0x89, 0xab, 0xcd, 0xef\n};\nstatic const unsigned char des3_2key_subkeys[2][8] = {\n    {\n        /* K1 */\n        0x0d, 0xd2, 0xcb, 0x7a,     0x3d, 0x88, 0x88, 0xd9\n    },\n    {\n        /* K2 */\n        0x1b, 0xa5, 0x96, 0xf4,     0x7b, 0x11, 0x11, 0xb2\n    }\n};\nstatic const unsigned char des3_2key_expected_result[NB_CMAC_TESTS_PER_KEY][MBEDTLS_DES3_BLOCK_SIZE] = {\n    {\n        /* Sample #1 */\n        0x79, 0xce, 0x52, 0xa7,     0xf7, 0x86, 0xa9, 0x60\n    },\n    {\n        /* Sample #2 */\n        0xcc, 0x18, 0xa0, 0xb7,     0x9a, 0xf2, 0x41, 0x3b\n    },\n    {\n        /* Sample #3 */\n        0xc0, 0x6d, 0x37, 0x7e,     0xcd, 0x10, 0x19, 0x69\n    },\n    {\n        /* Sample #4 */\n        0x9c, 0xd3, 0x35, 0x80,     0xf9, 0xb6, 0x4d, 0xfb\n    }\n};\n\n/* CMAC-TDES (Generation) - 3 Key Test Data */\nstatic const unsigned char des3_3key_key[24] = {\n    /* Key1 */\n    0x01, 0x23, 0x45, 0x67,     0x89, 0xaa, 0xcd, 0xef,\n    /* Key2 */\n    0x23, 0x45, 0x67, 0x89,     0xab, 0xcd, 0xef, 0x01,\n    /* Key3 */\n    0x45, 0x67, 0x89, 0xab,     0xcd, 0xef, 0x01, 0x23\n};\nstatic const unsigned char des3_3key_subkeys[2][8] = {\n    {\n        /* K1 */\n        0x9d, 0x74, 0xe7, 0x39,     0x33, 0x17, 0x96, 0xc0\n    },\n    {\n        /* K2 */\n        0x3a, 0xe9, 0xce, 0x72,     0x66, 0x2f, 0x2d, 0x9b\n    }\n};\nstatic const unsigned char des3_3key_expected_result[NB_CMAC_TESTS_PER_KEY][MBEDTLS_DES3_BLOCK_SIZE] = {\n    {\n        /* Sample #1 */\n        0x7d, 0xb0, 0xd3, 0x7d,     0xf9, 0x36, 0xc5, 0x50\n    },\n    {\n        /* Sample #2 */\n        0x30, 0x23, 0x9c, 0xf1,     0xf5, 0x2e, 0x66, 0x09\n    },\n    {\n        /* Sample #3 */\n        0x6c, 0x9f, 0x3e, 0xe4,     0x92, 0x3f, 0x6b, 0xe2\n    },\n    {\n        /* Sample #4 */\n        0x99, 0x42, 0x9b, 0xd0,     0xbF, 0x79, 0x04, 0xe5\n    }\n};\n\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_AES_C)\n/* AES AES-CMAC-PRF-128 Test Data */\nstatic const unsigned char PRFK[] = {\n    /* Key */\n    0x00, 0x01, 0x02, 0x03,     0x04, 0x05, 0x06, 0x07,\n    0x08, 0x09, 0x0a, 0x0b,     0x0c, 0x0d, 0x0e, 0x0f,\n    0xed, 0xcb\n};\n\n/* Sizes in bytes */\nstatic const size_t PRFKlen[NB_PRF_TESTS] = {\n    18,\n    16,\n    10\n};\n\n/* Message */\nstatic const unsigned char PRFM[] = {\n    0x00, 0x01, 0x02, 0x03,     0x04, 0x05, 0x06, 0x07,\n    0x08, 0x09, 0x0a, 0x0b,     0x0c, 0x0d, 0x0e, 0x0f,\n    0x10, 0x11, 0x12, 0x13\n};\n\nstatic const unsigned char PRFT[NB_PRF_TESTS][16] = {\n    {\n        0x84, 0xa3, 0x48, 0xa4,     0xa4, 0x5d, 0x23, 0x5b,\n        0xab, 0xff, 0xfc, 0x0d,     0x2b, 0x4d, 0xa0, 0x9a\n    },\n    {\n        0x98, 0x0a, 0xe8, 0x7b,     0x5f, 0x4c, 0x9c, 0x52,\n        0x14, 0xf5, 0xb6, 0xa8,     0x45, 0x5e, 0x4c, 0x2d\n    },\n    {\n        0x29, 0x0d, 0x9e, 0x11,     0x2e, 0xdb, 0x09, 0xee,\n        0x14, 0x1f, 0xcf, 0x64,     0xc0, 0xb7, 0x2f, 0x3d\n    }\n};\n#endif /* MBEDTLS_AES_C */\n\nstatic int cmac_test_subkeys( int verbose,\n                              const char* testname,\n                              const unsigned char* key,\n                              int keybits,\n                              const unsigned char* subkeys,\n                              mbedtls_cipher_type_t cipher_type,\n                              int block_size,\n                              int num_tests )\n{\n    int i, ret = 0;\n    mbedtls_cipher_context_t ctx;\n    const mbedtls_cipher_info_t *cipher_info;\n    unsigned char K1[MBEDTLS_CIPHER_BLKSIZE_MAX];\n    unsigned char K2[MBEDTLS_CIPHER_BLKSIZE_MAX];\n\n    cipher_info = mbedtls_cipher_info_from_type( cipher_type );\n    if( cipher_info == NULL )\n    {\n        /* Failing at this point must be due to a build issue */\n        return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );\n    }\n\n    for( i = 0; i < num_tests; i++ )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"  %s CMAC subkey #%u: \", testname, i + 1 );\n\n        mbedtls_cipher_init( &ctx );\n\n        if( ( ret = mbedtls_cipher_setup( &ctx, cipher_info ) ) != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"test execution failed\\n\" );\n\n            goto cleanup;\n        }\n\n        if( ( ret = mbedtls_cipher_setkey( &ctx, key, keybits,\n                                       MBEDTLS_ENCRYPT ) ) != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"test execution failed\\n\" );\n\n            goto cleanup;\n        }\n\n        ret = cmac_generate_subkeys( &ctx, K1, K2 );\n        if( ret != 0 )\n        {\n           if( verbose != 0 )\n                mbedtls_printf( \"failed\\n\" );\n\n            goto cleanup;\n        }\n\n        if( ( ret = memcmp( K1, subkeys, block_size ) ) != 0  ||\n            ( ret = memcmp( K2, &subkeys[block_size], block_size ) ) != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed\\n\" );\n\n            goto cleanup;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n\n        mbedtls_cipher_free( &ctx );\n    }\n\n    ret = 0;\n    goto exit;\n\ncleanup:\n    mbedtls_cipher_free( &ctx );\n\nexit:\n    return( ret );\n}\n\nstatic int cmac_test_wth_cipher( int verbose,\n                                 const char* testname,\n                                 const unsigned char* key,\n                                 int keybits,\n                                 const unsigned char* messages,\n                                 const unsigned int message_lengths[4],\n                                 const unsigned char* expected_result,\n                                 mbedtls_cipher_type_t cipher_type,\n                                 int block_size,\n                                 int num_tests )\n{\n    const mbedtls_cipher_info_t *cipher_info;\n    int i, ret = 0;\n    unsigned char output[MBEDTLS_CIPHER_BLKSIZE_MAX];\n\n    cipher_info = mbedtls_cipher_info_from_type( cipher_type );\n    if( cipher_info == NULL )\n    {\n        /* Failing at this point must be due to a build issue */\n        ret = MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE;\n        goto exit;\n    }\n\n    for( i = 0; i < num_tests; i++ )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"  %s CMAC #%u: \", testname, i + 1 );\n\n        if( ( ret = mbedtls_cipher_cmac( cipher_info, key, keybits, messages,\n                                         message_lengths[i], output ) ) != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed\\n\" );\n            goto exit;\n        }\n\n        if( ( ret = memcmp( output, &expected_result[i * block_size], block_size ) ) != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed\\n\" );\n            goto exit;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n    ret = 0;\n\nexit:\n    return( ret );\n}\n\n#if defined(MBEDTLS_AES_C)\nstatic int test_aes128_cmac_prf( int verbose )\n{\n    int i;\n    int ret;\n    unsigned char output[MBEDTLS_AES_BLOCK_SIZE];\n\n    for( i = 0; i < NB_PRF_TESTS; i++ )\n    {\n        mbedtls_printf( \"  AES CMAC 128 PRF #%u: \", i );\n        ret = mbedtls_aes_cmac_prf_128( PRFK, PRFKlen[i], PRFM, 20, output );\n        if( ret != 0 ||\n            memcmp( output, PRFT[i], MBEDTLS_AES_BLOCK_SIZE ) != 0 )\n        {\n\n            if( verbose != 0 )\n                mbedtls_printf( \"failed\\n\" );\n\n            return( ret );\n        }\n        else if( verbose != 0 )\n        {\n            mbedtls_printf( \"passed\\n\" );\n        }\n    }\n    return( ret );\n}\n#endif /* MBEDTLS_AES_C */\n\nint mbedtls_cmac_self_test( int verbose )\n{\n    int ret;\n\n#if defined(MBEDTLS_AES_C)\n    /* AES-128 */\n    if( ( ret = cmac_test_subkeys( verbose,\n                                   \"AES 128\",\n                                   aes_128_key,\n                                   128,\n                                   (const unsigned char*)aes_128_subkeys,\n                                   MBEDTLS_CIPHER_AES_128_ECB,\n                                   MBEDTLS_AES_BLOCK_SIZE,\n                                   NB_CMAC_TESTS_PER_KEY ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    if( ( ret = cmac_test_wth_cipher( verbose,\n                                      \"AES 128\",\n                                      aes_128_key,\n                                      128,\n                                      test_message,\n                                      aes_message_lengths,\n                                      (const unsigned char*)aes_128_expected_result,\n                                      MBEDTLS_CIPHER_AES_128_ECB,\n                                      MBEDTLS_AES_BLOCK_SIZE,\n                                      NB_CMAC_TESTS_PER_KEY ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    /* AES-192 */\n    if( ( ret = cmac_test_subkeys( verbose,\n                                   \"AES 192\",\n                                   aes_192_key,\n                                   192,\n                                   (const unsigned char*)aes_192_subkeys,\n                                   MBEDTLS_CIPHER_AES_192_ECB,\n                                   MBEDTLS_AES_BLOCK_SIZE,\n                                   NB_CMAC_TESTS_PER_KEY ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    if( ( ret = cmac_test_wth_cipher( verbose,\n                                      \"AES 192\",\n                                      aes_192_key,\n                                      192,\n                                      test_message,\n                                      aes_message_lengths,\n                                      (const unsigned char*)aes_192_expected_result,\n                                      MBEDTLS_CIPHER_AES_192_ECB,\n                                      MBEDTLS_AES_BLOCK_SIZE,\n                                      NB_CMAC_TESTS_PER_KEY ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    /* AES-256 */\n    if( ( ret = cmac_test_subkeys( verbose,\n                                   \"AES 256\",\n                                   aes_256_key,\n                                   256,\n                                   (const unsigned char*)aes_256_subkeys,\n                                   MBEDTLS_CIPHER_AES_256_ECB,\n                                   MBEDTLS_AES_BLOCK_SIZE,\n                                   NB_CMAC_TESTS_PER_KEY ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    if( ( ret = cmac_test_wth_cipher ( verbose,\n                                       \"AES 256\",\n                                       aes_256_key,\n                                       256,\n                                       test_message,\n                                       aes_message_lengths,\n                                       (const unsigned char*)aes_256_expected_result,\n                                       MBEDTLS_CIPHER_AES_256_ECB,\n                                       MBEDTLS_AES_BLOCK_SIZE,\n                                       NB_CMAC_TESTS_PER_KEY ) ) != 0 )\n    {\n        return( ret );\n    }\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_DES_C)\n    /* 3DES 2 key */\n    if( ( ret = cmac_test_subkeys( verbose,\n                                   \"3DES 2 key\",\n                                   des3_2key_key,\n                                   192,\n                                   (const unsigned char*)des3_2key_subkeys,\n                                   MBEDTLS_CIPHER_DES_EDE3_ECB,\n                                   MBEDTLS_DES3_BLOCK_SIZE,\n                                   NB_CMAC_TESTS_PER_KEY ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    if( ( ret = cmac_test_wth_cipher( verbose,\n                                      \"3DES 2 key\",\n                                      des3_2key_key,\n                                      192,\n                                      test_message,\n                                      des3_message_lengths,\n                                      (const unsigned char*)des3_2key_expected_result,\n                                      MBEDTLS_CIPHER_DES_EDE3_ECB,\n                                      MBEDTLS_DES3_BLOCK_SIZE,\n                                      NB_CMAC_TESTS_PER_KEY ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    /* 3DES 3 key */\n    if( ( ret = cmac_test_subkeys( verbose,\n                                   \"3DES 3 key\",\n                                   des3_3key_key,\n                                   192,\n                                   (const unsigned char*)des3_3key_subkeys,\n                                   MBEDTLS_CIPHER_DES_EDE3_ECB,\n                                   MBEDTLS_DES3_BLOCK_SIZE,\n                                   NB_CMAC_TESTS_PER_KEY ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    if( ( ret = cmac_test_wth_cipher( verbose,\n                                      \"3DES 3 key\",\n                                      des3_3key_key,\n                                      192,\n                                      test_message,\n                                      des3_message_lengths,\n                                      (const unsigned char*)des3_3key_expected_result,\n                                      MBEDTLS_CIPHER_DES_EDE3_ECB,\n                                      MBEDTLS_DES3_BLOCK_SIZE,\n                                      NB_CMAC_TESTS_PER_KEY ) ) != 0 )\n    {\n        return( ret );\n    }\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_AES_C)\n    if( ( ret = test_aes128_cmac_prf( verbose ) ) != 0 )\n        return( ret );\n#endif /* MBEDTLS_AES_C */\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    return( 0 );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_CMAC_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/ctr_drbg.c",
    "content": "/*\n *  CTR_DRBG implementation based on AES-256 (NIST SP 800-90)\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The NIST SP 800-90 DRBGs are described in the following publication.\n *\n *  http://csrc.nist.gov/publications/nistpubs/800-90/SP800-90revised_March2007.pdf\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_CTR_DRBG_C)\n\n#include \"mbedtls/ctr_drbg.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_FS_IO)\n#include <stdio.h>\n#endif\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n/*\n * CTR_DRBG context initialization\n */\nvoid mbedtls_ctr_drbg_init( mbedtls_ctr_drbg_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_ctr_drbg_context ) );\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_mutex_init( &ctx->mutex );\n#endif\n}\n\n/*\n * Non-public function wrapped by mbedtls_ctr_drbg_seed(). Necessary to allow\n * NIST tests to succeed (which require known length fixed entropy)\n */\nint mbedtls_ctr_drbg_seed_entropy_len(\n                   mbedtls_ctr_drbg_context *ctx,\n                   int (*f_entropy)(void *, unsigned char *, size_t),\n                   void *p_entropy,\n                   const unsigned char *custom,\n                   size_t len,\n                   size_t entropy_len )\n{\n    int ret;\n    unsigned char key[MBEDTLS_CTR_DRBG_KEYSIZE];\n\n    memset( key, 0, MBEDTLS_CTR_DRBG_KEYSIZE );\n\n    mbedtls_aes_init( &ctx->aes_ctx );\n\n    ctx->f_entropy = f_entropy;\n    ctx->p_entropy = p_entropy;\n\n    ctx->entropy_len = entropy_len;\n    ctx->reseed_interval = MBEDTLS_CTR_DRBG_RESEED_INTERVAL;\n\n    /*\n     * Initialize with an empty key\n     */\n    if( ( ret = mbedtls_aes_setkey_enc( &ctx->aes_ctx, key, MBEDTLS_CTR_DRBG_KEYBITS ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    if( ( ret = mbedtls_ctr_drbg_reseed( ctx, custom, len ) ) != 0 )\n    {\n        return( ret );\n    }\n    return( 0 );\n}\n\nint mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx,\n                   int (*f_entropy)(void *, unsigned char *, size_t),\n                   void *p_entropy,\n                   const unsigned char *custom,\n                   size_t len )\n{\n    return( mbedtls_ctr_drbg_seed_entropy_len( ctx, f_entropy, p_entropy, custom, len,\n                                       MBEDTLS_CTR_DRBG_ENTROPY_LEN ) );\n}\n\nvoid mbedtls_ctr_drbg_free( mbedtls_ctr_drbg_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_mutex_free( &ctx->mutex );\n#endif\n    mbedtls_aes_free( &ctx->aes_ctx );\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ctr_drbg_context ) );\n}\n\nvoid mbedtls_ctr_drbg_set_prediction_resistance( mbedtls_ctr_drbg_context *ctx, int resistance )\n{\n    ctx->prediction_resistance = resistance;\n}\n\nvoid mbedtls_ctr_drbg_set_entropy_len( mbedtls_ctr_drbg_context *ctx, size_t len )\n{\n    ctx->entropy_len = len;\n}\n\nvoid mbedtls_ctr_drbg_set_reseed_interval( mbedtls_ctr_drbg_context *ctx, int interval )\n{\n    ctx->reseed_interval = interval;\n}\n\nstatic int block_cipher_df( unsigned char *output,\n                            const unsigned char *data, size_t data_len )\n{\n    unsigned char buf[MBEDTLS_CTR_DRBG_MAX_SEED_INPUT + MBEDTLS_CTR_DRBG_BLOCKSIZE + 16];\n    unsigned char tmp[MBEDTLS_CTR_DRBG_SEEDLEN];\n    unsigned char key[MBEDTLS_CTR_DRBG_KEYSIZE];\n    unsigned char chain[MBEDTLS_CTR_DRBG_BLOCKSIZE];\n    unsigned char *p, *iv;\n    mbedtls_aes_context aes_ctx;\n    int ret = 0;\n\n    int i, j;\n    size_t buf_len, use_len;\n\n    if( data_len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT )\n        return( MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG );\n\n    memset( buf, 0, MBEDTLS_CTR_DRBG_MAX_SEED_INPUT + MBEDTLS_CTR_DRBG_BLOCKSIZE + 16 );\n    mbedtls_aes_init( &aes_ctx );\n\n    /*\n     * Construct IV (16 bytes) and S in buffer\n     * IV = Counter (in 32-bits) padded to 16 with zeroes\n     * S = Length input string (in 32-bits) || Length of output (in 32-bits) ||\n     *     data || 0x80\n     *     (Total is padded to a multiple of 16-bytes with zeroes)\n     */\n    p = buf + MBEDTLS_CTR_DRBG_BLOCKSIZE;\n    *p++ = ( data_len >> 24 ) & 0xff;\n    *p++ = ( data_len >> 16 ) & 0xff;\n    *p++ = ( data_len >> 8  ) & 0xff;\n    *p++ = ( data_len       ) & 0xff;\n    p += 3;\n    *p++ = MBEDTLS_CTR_DRBG_SEEDLEN;\n    memcpy( p, data, data_len );\n    p[data_len] = 0x80;\n\n    buf_len = MBEDTLS_CTR_DRBG_BLOCKSIZE + 8 + data_len + 1;\n\n    for( i = 0; i < MBEDTLS_CTR_DRBG_KEYSIZE; i++ )\n        key[i] = i;\n\n    if( ( ret = mbedtls_aes_setkey_enc( &aes_ctx, key, MBEDTLS_CTR_DRBG_KEYBITS ) ) != 0 )\n    {\n        goto exit;\n    }\n\n    /*\n     * Reduce data to MBEDTLS_CTR_DRBG_SEEDLEN bytes of data\n     */\n    for( j = 0; j < MBEDTLS_CTR_DRBG_SEEDLEN; j += MBEDTLS_CTR_DRBG_BLOCKSIZE )\n    {\n        p = buf;\n        memset( chain, 0, MBEDTLS_CTR_DRBG_BLOCKSIZE );\n        use_len = buf_len;\n\n        while( use_len > 0 )\n        {\n            for( i = 0; i < MBEDTLS_CTR_DRBG_BLOCKSIZE; i++ )\n                chain[i] ^= p[i];\n            p += MBEDTLS_CTR_DRBG_BLOCKSIZE;\n            use_len -= ( use_len >= MBEDTLS_CTR_DRBG_BLOCKSIZE ) ?\n                       MBEDTLS_CTR_DRBG_BLOCKSIZE : use_len;\n\n            if( ( ret = mbedtls_aes_crypt_ecb( &aes_ctx, MBEDTLS_AES_ENCRYPT, chain, chain ) ) != 0 )\n            {\n                goto exit;\n            }\n        }\n\n        memcpy( tmp + j, chain, MBEDTLS_CTR_DRBG_BLOCKSIZE );\n\n        /*\n         * Update IV\n         */\n        buf[3]++;\n    }\n\n    /*\n     * Do final encryption with reduced data\n     */\n    if( ( ret = mbedtls_aes_setkey_enc( &aes_ctx, tmp, MBEDTLS_CTR_DRBG_KEYBITS ) ) != 0 )\n    {\n        goto exit;\n    }\n    iv = tmp + MBEDTLS_CTR_DRBG_KEYSIZE;\n    p = output;\n\n    for( j = 0; j < MBEDTLS_CTR_DRBG_SEEDLEN; j += MBEDTLS_CTR_DRBG_BLOCKSIZE )\n    {\n        if( ( ret = mbedtls_aes_crypt_ecb( &aes_ctx, MBEDTLS_AES_ENCRYPT, iv, iv ) ) != 0 )\n        {\n            goto exit;\n        }\n        memcpy( p, iv, MBEDTLS_CTR_DRBG_BLOCKSIZE );\n        p += MBEDTLS_CTR_DRBG_BLOCKSIZE;\n    }\nexit:\n    mbedtls_aes_free( &aes_ctx );\n    /*\n    * tidy up the stack\n    */\n    mbedtls_platform_zeroize( buf, sizeof( buf ) );\n    mbedtls_platform_zeroize( tmp, sizeof( tmp ) );\n    mbedtls_platform_zeroize( key, sizeof( key ) );\n    mbedtls_platform_zeroize( chain, sizeof( chain ) );\n    if( 0 != ret )\n    {\n        /*\n        * wipe partial seed from memory\n        */\n        mbedtls_platform_zeroize( output, MBEDTLS_CTR_DRBG_SEEDLEN );\n    }\n\n    return( ret );\n}\n\nstatic int ctr_drbg_update_internal( mbedtls_ctr_drbg_context *ctx,\n                              const unsigned char data[MBEDTLS_CTR_DRBG_SEEDLEN] )\n{\n    unsigned char tmp[MBEDTLS_CTR_DRBG_SEEDLEN];\n    unsigned char *p = tmp;\n    int i, j;\n    int ret = 0;\n\n    memset( tmp, 0, MBEDTLS_CTR_DRBG_SEEDLEN );\n\n    for( j = 0; j < MBEDTLS_CTR_DRBG_SEEDLEN; j += MBEDTLS_CTR_DRBG_BLOCKSIZE )\n    {\n        /*\n         * Increase counter\n         */\n        for( i = MBEDTLS_CTR_DRBG_BLOCKSIZE; i > 0; i-- )\n            if( ++ctx->counter[i - 1] != 0 )\n                break;\n\n        /*\n         * Crypt counter block\n         */\n        if( ( ret = mbedtls_aes_crypt_ecb( &ctx->aes_ctx, MBEDTLS_AES_ENCRYPT, ctx->counter, p ) ) != 0 )\n        {\n            return( ret );\n        }\n\n        p += MBEDTLS_CTR_DRBG_BLOCKSIZE;\n    }\n\n    for( i = 0; i < MBEDTLS_CTR_DRBG_SEEDLEN; i++ )\n        tmp[i] ^= data[i];\n\n    /*\n     * Update key and counter\n     */\n    if( ( ret = mbedtls_aes_setkey_enc( &ctx->aes_ctx, tmp, MBEDTLS_CTR_DRBG_KEYBITS ) ) != 0 )\n    {\n        return( ret );\n    }\n    memcpy( ctx->counter, tmp + MBEDTLS_CTR_DRBG_KEYSIZE, MBEDTLS_CTR_DRBG_BLOCKSIZE );\n\n    return( 0 );\n}\n\nvoid mbedtls_ctr_drbg_update( mbedtls_ctr_drbg_context *ctx,\n                      const unsigned char *additional, size_t add_len )\n{\n    unsigned char add_input[MBEDTLS_CTR_DRBG_SEEDLEN];\n\n    if( add_len > 0 )\n    {\n        /* MAX_INPUT would be more logical here, but we have to match\n         * block_cipher_df()'s limits since we can't propagate errors */\n        if( add_len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT )\n            add_len = MBEDTLS_CTR_DRBG_MAX_SEED_INPUT;\n\n        block_cipher_df( add_input, additional, add_len );\n        ctr_drbg_update_internal( ctx, add_input );\n    }\n}\n\nint mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,\n                     const unsigned char *additional, size_t len )\n{\n    unsigned char seed[MBEDTLS_CTR_DRBG_MAX_SEED_INPUT];\n    size_t seedlen = 0;\n    int ret;\n\n    if( ctx->entropy_len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT ||\n        len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT - ctx->entropy_len )\n        return( MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG );\n\n    memset( seed, 0, MBEDTLS_CTR_DRBG_MAX_SEED_INPUT );\n\n    /*\n     * Gather entropy_len bytes of entropy to seed state\n     */\n    if( 0 != ctx->f_entropy( ctx->p_entropy, seed,\n                             ctx->entropy_len ) )\n    {\n        return( MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED );\n    }\n\n    seedlen += ctx->entropy_len;\n\n    /*\n     * Add additional data\n     */\n    if( additional && len )\n    {\n        memcpy( seed + seedlen, additional, len );\n        seedlen += len;\n    }\n\n    /*\n     * Reduce to 384 bits\n     */\n    if( ( ret = block_cipher_df( seed, seed, seedlen ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    /*\n     * Update state\n     */\n    if( ( ret = ctr_drbg_update_internal( ctx, seed ) ) != 0 )\n    {\n        return( ret );\n    }\n    ctx->reseed_counter = 1;\n\n    return( 0 );\n}\n\nint mbedtls_ctr_drbg_random_with_add( void *p_rng,\n                              unsigned char *output, size_t output_len,\n                              const unsigned char *additional, size_t add_len )\n{\n    int ret = 0;\n    mbedtls_ctr_drbg_context *ctx = (mbedtls_ctr_drbg_context *) p_rng;\n    unsigned char add_input[MBEDTLS_CTR_DRBG_SEEDLEN];\n    unsigned char *p = output;\n    unsigned char tmp[MBEDTLS_CTR_DRBG_BLOCKSIZE];\n    int i;\n    size_t use_len;\n\n    if( output_len > MBEDTLS_CTR_DRBG_MAX_REQUEST )\n        return( MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG );\n\n    if( add_len > MBEDTLS_CTR_DRBG_MAX_INPUT )\n        return( MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG );\n\n    memset( add_input, 0, MBEDTLS_CTR_DRBG_SEEDLEN );\n\n    if( ctx->reseed_counter > ctx->reseed_interval ||\n        ctx->prediction_resistance )\n    {\n        if( ( ret = mbedtls_ctr_drbg_reseed( ctx, additional, add_len ) ) != 0 )\n        {\n            return( ret );\n        }\n        add_len = 0;\n    }\n\n    if( add_len > 0 )\n    {\n        if( ( ret = block_cipher_df( add_input, additional, add_len ) ) != 0 )\n        {\n            return( ret );\n        }\n        if( ( ret = ctr_drbg_update_internal( ctx, add_input ) ) != 0 )\n        {\n            return( ret );\n        }\n    }\n\n    while( output_len > 0 )\n    {\n        /*\n         * Increase counter\n         */\n        for( i = MBEDTLS_CTR_DRBG_BLOCKSIZE; i > 0; i-- )\n            if( ++ctx->counter[i - 1] != 0 )\n                break;\n\n        /*\n         * Crypt counter block\n         */\n        if( ( ret = mbedtls_aes_crypt_ecb( &ctx->aes_ctx, MBEDTLS_AES_ENCRYPT, ctx->counter, tmp ) ) != 0 )\n        {\n            return( ret );\n        }\n\n        use_len = ( output_len > MBEDTLS_CTR_DRBG_BLOCKSIZE ) ? MBEDTLS_CTR_DRBG_BLOCKSIZE :\n                                                       output_len;\n        /*\n         * Copy random block to destination\n         */\n        memcpy( p, tmp, use_len );\n        p += use_len;\n        output_len -= use_len;\n    }\n\n    if( ( ret = ctr_drbg_update_internal( ctx, add_input ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    ctx->reseed_counter++;\n\n    return( 0 );\n}\n\nint mbedtls_ctr_drbg_random( void *p_rng, unsigned char *output, size_t output_len )\n{\n    int ret;\n    mbedtls_ctr_drbg_context *ctx = (mbedtls_ctr_drbg_context *) p_rng;\n\n#if defined(MBEDTLS_THREADING_C)\n    if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )\n        return( ret );\n#endif\n\n    ret = mbedtls_ctr_drbg_random_with_add( ctx, output, output_len, NULL, 0 );\n\n#if defined(MBEDTLS_THREADING_C)\n    if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )\n        return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );\n#endif\n\n    return( ret );\n}\n\n#if defined(MBEDTLS_FS_IO)\nint mbedtls_ctr_drbg_write_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path )\n{\n    int ret = MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR;\n    FILE *f;\n    unsigned char buf[ MBEDTLS_CTR_DRBG_MAX_INPUT ];\n\n    if( ( f = fopen( path, \"wb\" ) ) == NULL )\n        return( MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR );\n\n    if( ( ret = mbedtls_ctr_drbg_random( ctx, buf, MBEDTLS_CTR_DRBG_MAX_INPUT ) ) != 0 )\n        goto exit;\n\n    if( fwrite( buf, 1, MBEDTLS_CTR_DRBG_MAX_INPUT, f ) != MBEDTLS_CTR_DRBG_MAX_INPUT )\n        ret = MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR;\n    else\n        ret = 0;\n\nexit:\n    mbedtls_platform_zeroize( buf, sizeof( buf ) );\n\n    fclose( f );\n    return( ret );\n}\n\nint mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path )\n{\n    int ret = 0;\n    FILE *f;\n    size_t n;\n    unsigned char buf[ MBEDTLS_CTR_DRBG_MAX_INPUT ];\n\n    if( ( f = fopen( path, \"rb\" ) ) == NULL )\n        return( MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR );\n\n    fseek( f, 0, SEEK_END );\n    n = (size_t) ftell( f );\n    fseek( f, 0, SEEK_SET );\n\n    if( n > MBEDTLS_CTR_DRBG_MAX_INPUT )\n    {\n        fclose( f );\n        return( MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG );\n    }\n\n    if( fread( buf, 1, n, f ) != n )\n        ret = MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR;\n    else\n        mbedtls_ctr_drbg_update( ctx, buf, n );\n\n    fclose( f );\n\n    mbedtls_platform_zeroize( buf, sizeof( buf ) );\n\n    if( ret != 0 )\n        return( ret );\n\n    return( mbedtls_ctr_drbg_write_seed_file( ctx, path ) );\n}\n#endif /* MBEDTLS_FS_IO */\n\n#if defined(MBEDTLS_SELF_TEST)\n\nstatic const unsigned char entropy_source_pr[96] =\n    { 0xc1, 0x80, 0x81, 0xa6, 0x5d, 0x44, 0x02, 0x16,\n      0x19, 0xb3, 0xf1, 0x80, 0xb1, 0xc9, 0x20, 0x02,\n      0x6a, 0x54, 0x6f, 0x0c, 0x70, 0x81, 0x49, 0x8b,\n      0x6e, 0xa6, 0x62, 0x52, 0x6d, 0x51, 0xb1, 0xcb,\n      0x58, 0x3b, 0xfa, 0xd5, 0x37, 0x5f, 0xfb, 0xc9,\n      0xff, 0x46, 0xd2, 0x19, 0xc7, 0x22, 0x3e, 0x95,\n      0x45, 0x9d, 0x82, 0xe1, 0xe7, 0x22, 0x9f, 0x63,\n      0x31, 0x69, 0xd2, 0x6b, 0x57, 0x47, 0x4f, 0xa3,\n      0x37, 0xc9, 0x98, 0x1c, 0x0b, 0xfb, 0x91, 0x31,\n      0x4d, 0x55, 0xb9, 0xe9, 0x1c, 0x5a, 0x5e, 0xe4,\n      0x93, 0x92, 0xcf, 0xc5, 0x23, 0x12, 0xd5, 0x56,\n      0x2c, 0x4a, 0x6e, 0xff, 0xdc, 0x10, 0xd0, 0x68 };\n\nstatic const unsigned char entropy_source_nopr[64] =\n    { 0x5a, 0x19, 0x4d, 0x5e, 0x2b, 0x31, 0x58, 0x14,\n      0x54, 0xde, 0xf6, 0x75, 0xfb, 0x79, 0x58, 0xfe,\n      0xc7, 0xdb, 0x87, 0x3e, 0x56, 0x89, 0xfc, 0x9d,\n      0x03, 0x21, 0x7c, 0x68, 0xd8, 0x03, 0x38, 0x20,\n      0xf9, 0xe6, 0x5e, 0x04, 0xd8, 0x56, 0xf3, 0xa9,\n      0xc4, 0x4a, 0x4c, 0xbd, 0xc1, 0xd0, 0x08, 0x46,\n      0xf5, 0x98, 0x3d, 0x77, 0x1c, 0x1b, 0x13, 0x7e,\n      0x4e, 0x0f, 0x9d, 0x8e, 0xf4, 0x09, 0xf9, 0x2e };\n\nstatic const unsigned char nonce_pers_pr[16] =\n    { 0xd2, 0x54, 0xfc, 0xff, 0x02, 0x1e, 0x69, 0xd2,\n      0x29, 0xc9, 0xcf, 0xad, 0x85, 0xfa, 0x48, 0x6c };\n\nstatic const unsigned char nonce_pers_nopr[16] =\n    { 0x1b, 0x54, 0xb8, 0xff, 0x06, 0x42, 0xbf, 0xf5,\n      0x21, 0xf1, 0x5c, 0x1c, 0x0b, 0x66, 0x5f, 0x3f };\n\nstatic const unsigned char result_pr[16] =\n    { 0x34, 0x01, 0x16, 0x56, 0xb4, 0x29, 0x00, 0x8f,\n      0x35, 0x63, 0xec, 0xb5, 0xf2, 0x59, 0x07, 0x23 };\n\nstatic const unsigned char result_nopr[16] =\n    { 0xa0, 0x54, 0x30, 0x3d, 0x8a, 0x7e, 0xa9, 0x88,\n      0x9d, 0x90, 0x3e, 0x07, 0x7c, 0x6f, 0x21, 0x8f };\n\nstatic size_t test_offset;\nstatic int ctr_drbg_self_test_entropy( void *data, unsigned char *buf,\n                                       size_t len )\n{\n    const unsigned char *p = data;\n    memcpy( buf, p + test_offset, len );\n    test_offset += len;\n    return( 0 );\n}\n\n#define CHK( c )    if( (c) != 0 )                          \\\n                    {                                       \\\n                        if( verbose != 0 )                  \\\n                            mbedtls_printf( \"failed\\n\" );  \\\n                        return( 1 );                        \\\n                    }\n\n/*\n * Checkup routine\n */\nint mbedtls_ctr_drbg_self_test( int verbose )\n{\n    mbedtls_ctr_drbg_context ctx;\n    unsigned char buf[16];\n\n    mbedtls_ctr_drbg_init( &ctx );\n\n    /*\n     * Based on a NIST CTR_DRBG test vector (PR = True)\n     */\n    if( verbose != 0 )\n        mbedtls_printf( \"  CTR_DRBG (PR = TRUE) : \" );\n\n    test_offset = 0;\n    CHK( mbedtls_ctr_drbg_seed_entropy_len( &ctx, ctr_drbg_self_test_entropy,\n                                (void *) entropy_source_pr, nonce_pers_pr, 16, 32 ) );\n    mbedtls_ctr_drbg_set_prediction_resistance( &ctx, MBEDTLS_CTR_DRBG_PR_ON );\n    CHK( mbedtls_ctr_drbg_random( &ctx, buf, MBEDTLS_CTR_DRBG_BLOCKSIZE ) );\n    CHK( mbedtls_ctr_drbg_random( &ctx, buf, MBEDTLS_CTR_DRBG_BLOCKSIZE ) );\n    CHK( memcmp( buf, result_pr, MBEDTLS_CTR_DRBG_BLOCKSIZE ) );\n\n    mbedtls_ctr_drbg_free( &ctx );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\n    /*\n     * Based on a NIST CTR_DRBG test vector (PR = FALSE)\n     */\n    if( verbose != 0 )\n        mbedtls_printf( \"  CTR_DRBG (PR = FALSE): \" );\n\n    mbedtls_ctr_drbg_init( &ctx );\n\n    test_offset = 0;\n    CHK( mbedtls_ctr_drbg_seed_entropy_len( &ctx, ctr_drbg_self_test_entropy,\n                            (void *) entropy_source_nopr, nonce_pers_nopr, 16, 32 ) );\n    CHK( mbedtls_ctr_drbg_random( &ctx, buf, 16 ) );\n    CHK( mbedtls_ctr_drbg_reseed( &ctx, NULL, 0 ) );\n    CHK( mbedtls_ctr_drbg_random( &ctx, buf, 16 ) );\n    CHK( memcmp( buf, result_nopr, 16 ) );\n\n    mbedtls_ctr_drbg_free( &ctx );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\n    if( verbose != 0 )\n            mbedtls_printf( \"\\n\" );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_CTR_DRBG_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/debug.c",
    "content": "/*\n *  Debugging routines\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_DEBUG_C)\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc      calloc\n#define mbedtls_free        free\n#define mbedtls_time_t      time_t\n#define mbedtls_snprintf    snprintf\n#endif\n\n#include \"mbedtls/debug.h\"\n\n#include <stdarg.h>\n#include <stdio.h>\n#include <string.h>\n\n#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \\\n    !defined(inline) && !defined(__cplusplus)\n#define inline __inline\n#endif\n\n#define DEBUG_BUF_SIZE      512\n\nstatic int debug_threshold = 0;\n\nvoid mbedtls_debug_set_threshold( int threshold )\n{\n    debug_threshold = threshold;\n}\n\n/*\n * All calls to f_dbg must be made via this function\n */\nstatic inline void debug_send_line( const mbedtls_ssl_context *ssl, int level,\n                                    const char *file, int line,\n                                    const char *str )\n{\n    /*\n     * If in a threaded environment, we need a thread identifier.\n     * Since there is no portable way to get one, use the address of the ssl\n     * context instead, as it shouldn't be shared between threads.\n     */\n#if defined(MBEDTLS_THREADING_C)\n    char idstr[20 + DEBUG_BUF_SIZE]; /* 0x + 16 nibbles + ': ' */\n    mbedtls_snprintf( idstr, sizeof( idstr ), \"%p: %s\", (void*)ssl, str );\n    ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, idstr );\n#else\n    ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, str );\n#endif\n}\n\nvoid mbedtls_debug_print_msg( const mbedtls_ssl_context *ssl, int level,\n                              const char *file, int line,\n                              const char *format, ... )\n{\n    va_list argp;\n    char str[DEBUG_BUF_SIZE];\n    int ret;\n\n    if( NULL == ssl || NULL == ssl->conf || NULL == ssl->conf->f_dbg || level > debug_threshold )\n        return;\n\n    va_start( argp, format );\n#if defined(_WIN32)\n#if defined(_TRUNCATE) && !defined(__MINGW32__)\n    ret = _vsnprintf_s( str, DEBUG_BUF_SIZE, _TRUNCATE, format, argp );\n#else\n    ret = _vsnprintf( str, DEBUG_BUF_SIZE, format, argp );\n    if( ret < 0 || (size_t) ret == DEBUG_BUF_SIZE )\n    {\n        str[DEBUG_BUF_SIZE-1] = '\\0';\n        ret = -1;\n    }\n#endif\n#else\n    ret = vsnprintf( str, DEBUG_BUF_SIZE, format, argp );\n#endif\n    va_end( argp );\n\n    if( ret >= 0 && ret < DEBUG_BUF_SIZE - 1 )\n    {\n        str[ret]     = '\\n';\n        str[ret + 1] = '\\0';\n    }\n\n    debug_send_line( ssl, level, file, line, str );\n}\n\nvoid mbedtls_debug_print_ret( const mbedtls_ssl_context *ssl, int level,\n                      const char *file, int line,\n                      const char *text, int ret )\n{\n    char str[DEBUG_BUF_SIZE];\n\n    if( ssl->conf == NULL || ssl->conf->f_dbg == NULL || level > debug_threshold )\n        return;\n\n    /*\n     * With non-blocking I/O and examples that just retry immediately,\n     * the logs would be quickly flooded with WANT_READ, so ignore that.\n     * Don't ignore WANT_WRITE however, since is is usually rare.\n     */\n    if( ret == MBEDTLS_ERR_SSL_WANT_READ )\n        return;\n\n    mbedtls_snprintf( str, sizeof( str ), \"%s() returned %d (-0x%04x)\\n\",\n              text, ret, -ret );\n\n    debug_send_line( ssl, level, file, line, str );\n}\n\nvoid mbedtls_debug_print_buf( const mbedtls_ssl_context *ssl, int level,\n                      const char *file, int line, const char *text,\n                      const unsigned char *buf, size_t len )\n{\n    char str[DEBUG_BUF_SIZE];\n    char txt[17];\n    size_t i, idx = 0;\n\n    if( ssl->conf == NULL || ssl->conf->f_dbg == NULL || level > debug_threshold )\n        return;\n\n    mbedtls_snprintf( str + idx, sizeof( str ) - idx, \"dumping '%s' (%u bytes)\\n\",\n              text, (unsigned int) len );\n\n    debug_send_line( ssl, level, file, line, str );\n\n    idx = 0;\n    memset( txt, 0, sizeof( txt ) );\n    for( i = 0; i < len; i++ )\n    {\n        if( i >= 4096 )\n            break;\n\n        if( i % 16 == 0 )\n        {\n            if( i > 0 )\n            {\n                mbedtls_snprintf( str + idx, sizeof( str ) - idx, \"  %s\\n\", txt );\n                debug_send_line( ssl, level, file, line, str );\n\n                idx = 0;\n                memset( txt, 0, sizeof( txt ) );\n            }\n\n            idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, \"%04x: \",\n                             (unsigned int) i );\n\n        }\n\n        idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, \" %02x\",\n                         (unsigned int) buf[i] );\n        txt[i % 16] = ( buf[i] > 31 && buf[i] < 127 ) ? buf[i] : '.' ;\n    }\n\n    if( len > 0 )\n    {\n        for( /* i = i */; i % 16 != 0; i++ )\n            idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, \"   \" );\n\n        mbedtls_snprintf( str + idx, sizeof( str ) - idx, \"  %s\\n\", txt );\n        debug_send_line( ssl, level, file, line, str );\n    }\n}\n\n#if defined(MBEDTLS_ECP_C)\nvoid mbedtls_debug_print_ecp( const mbedtls_ssl_context *ssl, int level,\n                      const char *file, int line,\n                      const char *text, const mbedtls_ecp_point *X )\n{\n    char str[DEBUG_BUF_SIZE];\n\n    if( ssl->conf == NULL || ssl->conf->f_dbg == NULL || level > debug_threshold )\n        return;\n\n    mbedtls_snprintf( str, sizeof( str ), \"%s(X)\", text );\n    mbedtls_debug_print_mpi( ssl, level, file, line, str, &X->X );\n\n    mbedtls_snprintf( str, sizeof( str ), \"%s(Y)\", text );\n    mbedtls_debug_print_mpi( ssl, level, file, line, str, &X->Y );\n}\n#endif /* MBEDTLS_ECP_C */\n\n#if defined(MBEDTLS_BIGNUM_C)\nvoid mbedtls_debug_print_mpi( const mbedtls_ssl_context *ssl, int level,\n                      const char *file, int line,\n                      const char *text, const mbedtls_mpi *X )\n{\n    char str[DEBUG_BUF_SIZE];\n    int j, k, zeros = 1;\n    size_t i, n, idx = 0;\n\n    if( ssl->conf == NULL || ssl->conf->f_dbg == NULL || X == NULL || level > debug_threshold )\n        return;\n\n    for( n = X->n - 1; n > 0; n-- )\n        if( X->p[n] != 0 )\n            break;\n\n    for( j = ( sizeof(mbedtls_mpi_uint) << 3 ) - 1; j >= 0; j-- )\n        if( ( ( X->p[n] >> j ) & 1 ) != 0 )\n            break;\n\n    mbedtls_snprintf( str + idx, sizeof( str ) - idx, \"value of '%s' (%d bits) is:\\n\",\n              text, (int) ( ( n * ( sizeof(mbedtls_mpi_uint) << 3 ) ) + j + 1 ) );\n\n    debug_send_line( ssl, level, file, line, str );\n\n    idx = 0;\n    for( i = n + 1, j = 0; i > 0; i-- )\n    {\n        if( zeros && X->p[i - 1] == 0 )\n            continue;\n\n        for( k = sizeof( mbedtls_mpi_uint ) - 1; k >= 0; k-- )\n        {\n            if( zeros && ( ( X->p[i - 1] >> ( k << 3 ) ) & 0xFF ) == 0 )\n                continue;\n            else\n                zeros = 0;\n\n            if( j % 16 == 0 )\n            {\n                if( j > 0 )\n                {\n                    mbedtls_snprintf( str + idx, sizeof( str ) - idx, \"\\n\" );\n                    debug_send_line( ssl, level, file, line, str );\n                    idx = 0;\n                }\n            }\n\n            idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, \" %02x\", (unsigned int)\n                             ( X->p[i - 1] >> ( k << 3 ) ) & 0xFF );\n\n            j++;\n        }\n\n    }\n\n    if( zeros == 1 )\n        idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, \" 00\" );\n\n    mbedtls_snprintf( str + idx, sizeof( str ) - idx, \"\\n\" );\n    debug_send_line( ssl, level, file, line, str );\n}\n#endif /* MBEDTLS_BIGNUM_C */\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\nstatic void debug_print_pk( const mbedtls_ssl_context *ssl, int level,\n                            const char *file, int line,\n                            const char *text, const mbedtls_pk_context *pk )\n{\n    size_t i;\n    mbedtls_pk_debug_item items[MBEDTLS_PK_DEBUG_MAX_ITEMS];\n    char name[16];\n\n    memset( items, 0, sizeof( items ) );\n\n    if( mbedtls_pk_debug( pk, items ) != 0 )\n    {\n        debug_send_line( ssl, level, file, line,\n                          \"invalid PK context\\n\" );\n        return;\n    }\n\n    for( i = 0; i < MBEDTLS_PK_DEBUG_MAX_ITEMS; i++ )\n    {\n        if( items[i].type == MBEDTLS_PK_DEBUG_NONE )\n            return;\n\n        mbedtls_snprintf( name, sizeof( name ), \"%s%s\", text, items[i].name );\n        name[sizeof( name ) - 1] = '\\0';\n\n        if( items[i].type == MBEDTLS_PK_DEBUG_MPI )\n            mbedtls_debug_print_mpi( ssl, level, file, line, name, items[i].value );\n        else\n#if defined(MBEDTLS_ECP_C)\n        if( items[i].type == MBEDTLS_PK_DEBUG_ECP )\n            mbedtls_debug_print_ecp( ssl, level, file, line, name, items[i].value );\n        else\n#endif\n            debug_send_line( ssl, level, file, line,\n                              \"should not happen\\n\" );\n    }\n}\n\nstatic void debug_print_line_by_line( const mbedtls_ssl_context *ssl, int level,\n                                      const char *file, int line, const char *text )\n{\n    char str[DEBUG_BUF_SIZE];\n    const char *start, *cur;\n\n    start = text;\n    for( cur = text; *cur != '\\0'; cur++ )\n    {\n        if( *cur == '\\n' )\n        {\n            size_t len = cur - start + 1;\n            if( len > DEBUG_BUF_SIZE - 1 )\n                len = DEBUG_BUF_SIZE - 1;\n\n            memcpy( str, start, len );\n            str[len] = '\\0';\n\n            debug_send_line( ssl, level, file, line, str );\n\n            start = cur + 1;\n        }\n    }\n}\n\nvoid mbedtls_debug_print_crt( const mbedtls_ssl_context *ssl, int level,\n                      const char *file, int line,\n                      const char *text, const mbedtls_x509_crt *crt )\n{\n    char str[DEBUG_BUF_SIZE];\n    int i = 0;\n\n    if( ssl->conf == NULL || ssl->conf->f_dbg == NULL || crt == NULL || level > debug_threshold )\n        return;\n\n    while( crt != NULL )\n    {\n        char buf[1024];\n\n        mbedtls_snprintf( str, sizeof( str ), \"%s #%d:\\n\", text, ++i );\n        debug_send_line( ssl, level, file, line, str );\n\n        mbedtls_x509_crt_info( buf, sizeof( buf ) - 1, \"\", crt );\n        debug_print_line_by_line( ssl, level, file, line, buf );\n\n        debug_print_pk( ssl, level, file, line, \"crt->\", &crt->pk );\n\n        crt = crt->next;\n    }\n}\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n#endif /* MBEDTLS_DEBUG_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/des.c",
    "content": "/*\n *  FIPS-46-3 compliant Triple-DES implementation\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  DES, on which TDES is based, was originally designed by Horst Feistel\n *  at IBM in 1974, and was adopted as a standard by NIST (formerly NBS).\n *\n *  http://csrc.nist.gov/publications/fips/fips46-3/fips46-3.pdf\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_DES_C)\n\n#include \"mbedtls/des.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if !defined(MBEDTLS_DES_ALT)\n\n/*\n * 32-bit integer manipulation macros (big endian)\n */\n#ifndef GET_UINT32_BE\n#define GET_UINT32_BE(n,b,i)                            \\\n{                                                       \\\n    (n) = ( (uint32_t) (b)[(i)    ] << 24 )             \\\n        | ( (uint32_t) (b)[(i) + 1] << 16 )             \\\n        | ( (uint32_t) (b)[(i) + 2] <<  8 )             \\\n        | ( (uint32_t) (b)[(i) + 3]       );            \\\n}\n#endif\n\n#ifndef PUT_UINT32_BE\n#define PUT_UINT32_BE(n,b,i)                            \\\n{                                                       \\\n    (b)[(i)    ] = (unsigned char) ( (n) >> 24 );       \\\n    (b)[(i) + 1] = (unsigned char) ( (n) >> 16 );       \\\n    (b)[(i) + 2] = (unsigned char) ( (n) >>  8 );       \\\n    (b)[(i) + 3] = (unsigned char) ( (n)       );       \\\n}\n#endif\n\n/*\n * Expanded DES S-boxes\n */\nstatic const uint32_t SB1[64] =\n{\n    0x01010400, 0x00000000, 0x00010000, 0x01010404,\n    0x01010004, 0x00010404, 0x00000004, 0x00010000,\n    0x00000400, 0x01010400, 0x01010404, 0x00000400,\n    0x01000404, 0x01010004, 0x01000000, 0x00000004,\n    0x00000404, 0x01000400, 0x01000400, 0x00010400,\n    0x00010400, 0x01010000, 0x01010000, 0x01000404,\n    0x00010004, 0x01000004, 0x01000004, 0x00010004,\n    0x00000000, 0x00000404, 0x00010404, 0x01000000,\n    0x00010000, 0x01010404, 0x00000004, 0x01010000,\n    0x01010400, 0x01000000, 0x01000000, 0x00000400,\n    0x01010004, 0x00010000, 0x00010400, 0x01000004,\n    0x00000400, 0x00000004, 0x01000404, 0x00010404,\n    0x01010404, 0x00010004, 0x01010000, 0x01000404,\n    0x01000004, 0x00000404, 0x00010404, 0x01010400,\n    0x00000404, 0x01000400, 0x01000400, 0x00000000,\n    0x00010004, 0x00010400, 0x00000000, 0x01010004\n};\n\nstatic const uint32_t SB2[64] =\n{\n    0x80108020, 0x80008000, 0x00008000, 0x00108020,\n    0x00100000, 0x00000020, 0x80100020, 0x80008020,\n    0x80000020, 0x80108020, 0x80108000, 0x80000000,\n    0x80008000, 0x00100000, 0x00000020, 0x80100020,\n    0x00108000, 0x00100020, 0x80008020, 0x00000000,\n    0x80000000, 0x00008000, 0x00108020, 0x80100000,\n    0x00100020, 0x80000020, 0x00000000, 0x00108000,\n    0x00008020, 0x80108000, 0x80100000, 0x00008020,\n    0x00000000, 0x00108020, 0x80100020, 0x00100000,\n    0x80008020, 0x80100000, 0x80108000, 0x00008000,\n    0x80100000, 0x80008000, 0x00000020, 0x80108020,\n    0x00108020, 0x00000020, 0x00008000, 0x80000000,\n    0x00008020, 0x80108000, 0x00100000, 0x80000020,\n    0x00100020, 0x80008020, 0x80000020, 0x00100020,\n    0x00108000, 0x00000000, 0x80008000, 0x00008020,\n    0x80000000, 0x80100020, 0x80108020, 0x00108000\n};\n\nstatic const uint32_t SB3[64] =\n{\n    0x00000208, 0x08020200, 0x00000000, 0x08020008,\n    0x08000200, 0x00000000, 0x00020208, 0x08000200,\n    0x00020008, 0x08000008, 0x08000008, 0x00020000,\n    0x08020208, 0x00020008, 0x08020000, 0x00000208,\n    0x08000000, 0x00000008, 0x08020200, 0x00000200,\n    0x00020200, 0x08020000, 0x08020008, 0x00020208,\n    0x08000208, 0x00020200, 0x00020000, 0x08000208,\n    0x00000008, 0x08020208, 0x00000200, 0x08000000,\n    0x08020200, 0x08000000, 0x00020008, 0x00000208,\n    0x00020000, 0x08020200, 0x08000200, 0x00000000,\n    0x00000200, 0x00020008, 0x08020208, 0x08000200,\n    0x08000008, 0x00000200, 0x00000000, 0x08020008,\n    0x08000208, 0x00020000, 0x08000000, 0x08020208,\n    0x00000008, 0x00020208, 0x00020200, 0x08000008,\n    0x08020000, 0x08000208, 0x00000208, 0x08020000,\n    0x00020208, 0x00000008, 0x08020008, 0x00020200\n};\n\nstatic const uint32_t SB4[64] =\n{\n    0x00802001, 0x00002081, 0x00002081, 0x00000080,\n    0x00802080, 0x00800081, 0x00800001, 0x00002001,\n    0x00000000, 0x00802000, 0x00802000, 0x00802081,\n    0x00000081, 0x00000000, 0x00800080, 0x00800001,\n    0x00000001, 0x00002000, 0x00800000, 0x00802001,\n    0x00000080, 0x00800000, 0x00002001, 0x00002080,\n    0x00800081, 0x00000001, 0x00002080, 0x00800080,\n    0x00002000, 0x00802080, 0x00802081, 0x00000081,\n    0x00800080, 0x00800001, 0x00802000, 0x00802081,\n    0x00000081, 0x00000000, 0x00000000, 0x00802000,\n    0x00002080, 0x00800080, 0x00800081, 0x00000001,\n    0x00802001, 0x00002081, 0x00002081, 0x00000080,\n    0x00802081, 0x00000081, 0x00000001, 0x00002000,\n    0x00800001, 0x00002001, 0x00802080, 0x00800081,\n    0x00002001, 0x00002080, 0x00800000, 0x00802001,\n    0x00000080, 0x00800000, 0x00002000, 0x00802080\n};\n\nstatic const uint32_t SB5[64] =\n{\n    0x00000100, 0x02080100, 0x02080000, 0x42000100,\n    0x00080000, 0x00000100, 0x40000000, 0x02080000,\n    0x40080100, 0x00080000, 0x02000100, 0x40080100,\n    0x42000100, 0x42080000, 0x00080100, 0x40000000,\n    0x02000000, 0x40080000, 0x40080000, 0x00000000,\n    0x40000100, 0x42080100, 0x42080100, 0x02000100,\n    0x42080000, 0x40000100, 0x00000000, 0x42000000,\n    0x02080100, 0x02000000, 0x42000000, 0x00080100,\n    0x00080000, 0x42000100, 0x00000100, 0x02000000,\n    0x40000000, 0x02080000, 0x42000100, 0x40080100,\n    0x02000100, 0x40000000, 0x42080000, 0x02080100,\n    0x40080100, 0x00000100, 0x02000000, 0x42080000,\n    0x42080100, 0x00080100, 0x42000000, 0x42080100,\n    0x02080000, 0x00000000, 0x40080000, 0x42000000,\n    0x00080100, 0x02000100, 0x40000100, 0x00080000,\n    0x00000000, 0x40080000, 0x02080100, 0x40000100\n};\n\nstatic const uint32_t SB6[64] =\n{\n    0x20000010, 0x20400000, 0x00004000, 0x20404010,\n    0x20400000, 0x00000010, 0x20404010, 0x00400000,\n    0x20004000, 0x00404010, 0x00400000, 0x20000010,\n    0x00400010, 0x20004000, 0x20000000, 0x00004010,\n    0x00000000, 0x00400010, 0x20004010, 0x00004000,\n    0x00404000, 0x20004010, 0x00000010, 0x20400010,\n    0x20400010, 0x00000000, 0x00404010, 0x20404000,\n    0x00004010, 0x00404000, 0x20404000, 0x20000000,\n    0x20004000, 0x00000010, 0x20400010, 0x00404000,\n    0x20404010, 0x00400000, 0x00004010, 0x20000010,\n    0x00400000, 0x20004000, 0x20000000, 0x00004010,\n    0x20000010, 0x20404010, 0x00404000, 0x20400000,\n    0x00404010, 0x20404000, 0x00000000, 0x20400010,\n    0x00000010, 0x00004000, 0x20400000, 0x00404010,\n    0x00004000, 0x00400010, 0x20004010, 0x00000000,\n    0x20404000, 0x20000000, 0x00400010, 0x20004010\n};\n\nstatic const uint32_t SB7[64] =\n{\n    0x00200000, 0x04200002, 0x04000802, 0x00000000,\n    0x00000800, 0x04000802, 0x00200802, 0x04200800,\n    0x04200802, 0x00200000, 0x00000000, 0x04000002,\n    0x00000002, 0x04000000, 0x04200002, 0x00000802,\n    0x04000800, 0x00200802, 0x00200002, 0x04000800,\n    0x04000002, 0x04200000, 0x04200800, 0x00200002,\n    0x04200000, 0x00000800, 0x00000802, 0x04200802,\n    0x00200800, 0x00000002, 0x04000000, 0x00200800,\n    0x04000000, 0x00200800, 0x00200000, 0x04000802,\n    0x04000802, 0x04200002, 0x04200002, 0x00000002,\n    0x00200002, 0x04000000, 0x04000800, 0x00200000,\n    0x04200800, 0x00000802, 0x00200802, 0x04200800,\n    0x00000802, 0x04000002, 0x04200802, 0x04200000,\n    0x00200800, 0x00000000, 0x00000002, 0x04200802,\n    0x00000000, 0x00200802, 0x04200000, 0x00000800,\n    0x04000002, 0x04000800, 0x00000800, 0x00200002\n};\n\nstatic const uint32_t SB8[64] =\n{\n    0x10001040, 0x00001000, 0x00040000, 0x10041040,\n    0x10000000, 0x10001040, 0x00000040, 0x10000000,\n    0x00040040, 0x10040000, 0x10041040, 0x00041000,\n    0x10041000, 0x00041040, 0x00001000, 0x00000040,\n    0x10040000, 0x10000040, 0x10001000, 0x00001040,\n    0x00041000, 0x00040040, 0x10040040, 0x10041000,\n    0x00001040, 0x00000000, 0x00000000, 0x10040040,\n    0x10000040, 0x10001000, 0x00041040, 0x00040000,\n    0x00041040, 0x00040000, 0x10041000, 0x00001000,\n    0x00000040, 0x10040040, 0x00001000, 0x00041040,\n    0x10001000, 0x00000040, 0x10000040, 0x10040000,\n    0x10040040, 0x10000000, 0x00040000, 0x10001040,\n    0x00000000, 0x10041040, 0x00040040, 0x10000040,\n    0x10040000, 0x10001000, 0x10001040, 0x00000000,\n    0x10041040, 0x00041000, 0x00041000, 0x00001040,\n    0x00001040, 0x00040040, 0x10000000, 0x10041000\n};\n\n/*\n * PC1: left and right halves bit-swap\n */\nstatic const uint32_t LHs[16] =\n{\n    0x00000000, 0x00000001, 0x00000100, 0x00000101,\n    0x00010000, 0x00010001, 0x00010100, 0x00010101,\n    0x01000000, 0x01000001, 0x01000100, 0x01000101,\n    0x01010000, 0x01010001, 0x01010100, 0x01010101\n};\n\nstatic const uint32_t RHs[16] =\n{\n    0x00000000, 0x01000000, 0x00010000, 0x01010000,\n    0x00000100, 0x01000100, 0x00010100, 0x01010100,\n    0x00000001, 0x01000001, 0x00010001, 0x01010001,\n    0x00000101, 0x01000101, 0x00010101, 0x01010101,\n};\n\n/*\n * Initial Permutation macro\n */\n#define DES_IP(X,Y)                                             \\\n{                                                               \\\n    T = ((X >>  4) ^ Y) & 0x0F0F0F0F; Y ^= T; X ^= (T <<  4);   \\\n    T = ((X >> 16) ^ Y) & 0x0000FFFF; Y ^= T; X ^= (T << 16);   \\\n    T = ((Y >>  2) ^ X) & 0x33333333; X ^= T; Y ^= (T <<  2);   \\\n    T = ((Y >>  8) ^ X) & 0x00FF00FF; X ^= T; Y ^= (T <<  8);   \\\n    Y = ((Y << 1) | (Y >> 31)) & 0xFFFFFFFF;                    \\\n    T = (X ^ Y) & 0xAAAAAAAA; Y ^= T; X ^= T;                   \\\n    X = ((X << 1) | (X >> 31)) & 0xFFFFFFFF;                    \\\n}\n\n/*\n * Final Permutation macro\n */\n#define DES_FP(X,Y)                                             \\\n{                                                               \\\n    X = ((X << 31) | (X >> 1)) & 0xFFFFFFFF;                    \\\n    T = (X ^ Y) & 0xAAAAAAAA; X ^= T; Y ^= T;                   \\\n    Y = ((Y << 31) | (Y >> 1)) & 0xFFFFFFFF;                    \\\n    T = ((Y >>  8) ^ X) & 0x00FF00FF; X ^= T; Y ^= (T <<  8);   \\\n    T = ((Y >>  2) ^ X) & 0x33333333; X ^= T; Y ^= (T <<  2);   \\\n    T = ((X >> 16) ^ Y) & 0x0000FFFF; Y ^= T; X ^= (T << 16);   \\\n    T = ((X >>  4) ^ Y) & 0x0F0F0F0F; Y ^= T; X ^= (T <<  4);   \\\n}\n\n/*\n * DES round macro\n */\n#define DES_ROUND(X,Y)                          \\\n{                                               \\\n    T = *SK++ ^ X;                              \\\n    Y ^= SB8[ (T      ) & 0x3F ] ^              \\\n         SB6[ (T >>  8) & 0x3F ] ^              \\\n         SB4[ (T >> 16) & 0x3F ] ^              \\\n         SB2[ (T >> 24) & 0x3F ];               \\\n                                                \\\n    T = *SK++ ^ ((X << 28) | (X >> 4));         \\\n    Y ^= SB7[ (T      ) & 0x3F ] ^              \\\n         SB5[ (T >>  8) & 0x3F ] ^              \\\n         SB3[ (T >> 16) & 0x3F ] ^              \\\n         SB1[ (T >> 24) & 0x3F ];               \\\n}\n\n#define SWAP(a,b) { uint32_t t = a; a = b; b = t; t = 0; }\n\nvoid mbedtls_des_init( mbedtls_des_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_des_context ) );\n}\n\nvoid mbedtls_des_free( mbedtls_des_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_des_context ) );\n}\n\nvoid mbedtls_des3_init( mbedtls_des3_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_des3_context ) );\n}\n\nvoid mbedtls_des3_free( mbedtls_des3_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_des3_context ) );\n}\n\nstatic const unsigned char odd_parity_table[128] = { 1,  2,  4,  7,  8,\n        11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, 32, 35, 37, 38, 41, 42, 44,\n        47, 49, 50, 52, 55, 56, 59, 61, 62, 64, 67, 69, 70, 73, 74, 76, 79, 81,\n        82, 84, 87, 88, 91, 93, 94, 97, 98, 100, 103, 104, 107, 109, 110, 112,\n        115, 117, 118, 121, 122, 124, 127, 128, 131, 133, 134, 137, 138, 140,\n        143, 145, 146, 148, 151, 152, 155, 157, 158, 161, 162, 164, 167, 168,\n        171, 173, 174, 176, 179, 181, 182, 185, 186, 188, 191, 193, 194, 196,\n        199, 200, 203, 205, 206, 208, 211, 213, 214, 217, 218, 220, 223, 224,\n        227, 229, 230, 233, 234, 236, 239, 241, 242, 244, 247, 248, 251, 253,\n        254 };\n\nvoid mbedtls_des_key_set_parity( unsigned char key[MBEDTLS_DES_KEY_SIZE] )\n{\n    int i;\n\n    for( i = 0; i < MBEDTLS_DES_KEY_SIZE; i++ )\n        key[i] = odd_parity_table[key[i] / 2];\n}\n\n/*\n * Check the given key's parity, returns 1 on failure, 0 on SUCCESS\n */\nint mbedtls_des_key_check_key_parity( const unsigned char key[MBEDTLS_DES_KEY_SIZE] )\n{\n    int i;\n\n    for( i = 0; i < MBEDTLS_DES_KEY_SIZE; i++ )\n        if( key[i] != odd_parity_table[key[i] / 2] )\n            return( 1 );\n\n    return( 0 );\n}\n\n/*\n * Table of weak and semi-weak keys\n *\n * Source: http://en.wikipedia.org/wiki/Weak_key\n *\n * Weak:\n * Alternating ones + zeros (0x0101010101010101)\n * Alternating 'F' + 'E' (0xFEFEFEFEFEFEFEFE)\n * '0xE0E0E0E0F1F1F1F1'\n * '0x1F1F1F1F0E0E0E0E'\n *\n * Semi-weak:\n * 0x011F011F010E010E and 0x1F011F010E010E01\n * 0x01E001E001F101F1 and 0xE001E001F101F101\n * 0x01FE01FE01FE01FE and 0xFE01FE01FE01FE01\n * 0x1FE01FE00EF10EF1 and 0xE01FE01FF10EF10E\n * 0x1FFE1FFE0EFE0EFE and 0xFE1FFE1FFE0EFE0E\n * 0xE0FEE0FEF1FEF1FE and 0xFEE0FEE0FEF1FEF1\n *\n */\n\n#define WEAK_KEY_COUNT 16\n\nstatic const unsigned char weak_key_table[WEAK_KEY_COUNT][MBEDTLS_DES_KEY_SIZE] =\n{\n    { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },\n    { 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE },\n    { 0x1F, 0x1F, 0x1F, 0x1F, 0x0E, 0x0E, 0x0E, 0x0E },\n    { 0xE0, 0xE0, 0xE0, 0xE0, 0xF1, 0xF1, 0xF1, 0xF1 },\n\n    { 0x01, 0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E },\n    { 0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E, 0x01 },\n    { 0x01, 0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1 },\n    { 0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1, 0x01 },\n    { 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE },\n    { 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01 },\n    { 0x1F, 0xE0, 0x1F, 0xE0, 0x0E, 0xF1, 0x0E, 0xF1 },\n    { 0xE0, 0x1F, 0xE0, 0x1F, 0xF1, 0x0E, 0xF1, 0x0E },\n    { 0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E, 0xFE },\n    { 0xFE, 0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E },\n    { 0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1, 0xFE },\n    { 0xFE, 0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1 }\n};\n\nint mbedtls_des_key_check_weak( const unsigned char key[MBEDTLS_DES_KEY_SIZE] )\n{\n    int i;\n\n    for( i = 0; i < WEAK_KEY_COUNT; i++ )\n        if( memcmp( weak_key_table[i], key, MBEDTLS_DES_KEY_SIZE) == 0 )\n            return( 1 );\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DES_SETKEY_ALT)\nvoid mbedtls_des_setkey( uint32_t SK[32], const unsigned char key[MBEDTLS_DES_KEY_SIZE] )\n{\n    int i;\n    uint32_t X, Y, T;\n\n    GET_UINT32_BE( X, key, 0 );\n    GET_UINT32_BE( Y, key, 4 );\n\n    /*\n     * Permuted Choice 1\n     */\n    T =  ((Y >>  4) ^ X) & 0x0F0F0F0F;  X ^= T; Y ^= (T <<  4);\n    T =  ((Y      ) ^ X) & 0x10101010;  X ^= T; Y ^= (T      );\n\n    X =   (LHs[ (X      ) & 0xF] << 3) | (LHs[ (X >>  8) & 0xF ] << 2)\n        | (LHs[ (X >> 16) & 0xF] << 1) | (LHs[ (X >> 24) & 0xF ]     )\n        | (LHs[ (X >>  5) & 0xF] << 7) | (LHs[ (X >> 13) & 0xF ] << 6)\n        | (LHs[ (X >> 21) & 0xF] << 5) | (LHs[ (X >> 29) & 0xF ] << 4);\n\n    Y =   (RHs[ (Y >>  1) & 0xF] << 3) | (RHs[ (Y >>  9) & 0xF ] << 2)\n        | (RHs[ (Y >> 17) & 0xF] << 1) | (RHs[ (Y >> 25) & 0xF ]     )\n        | (RHs[ (Y >>  4) & 0xF] << 7) | (RHs[ (Y >> 12) & 0xF ] << 6)\n        | (RHs[ (Y >> 20) & 0xF] << 5) | (RHs[ (Y >> 28) & 0xF ] << 4);\n\n    X &= 0x0FFFFFFF;\n    Y &= 0x0FFFFFFF;\n\n    /*\n     * calculate subkeys\n     */\n    for( i = 0; i < 16; i++ )\n    {\n        if( i < 2 || i == 8 || i == 15 )\n        {\n            X = ((X <<  1) | (X >> 27)) & 0x0FFFFFFF;\n            Y = ((Y <<  1) | (Y >> 27)) & 0x0FFFFFFF;\n        }\n        else\n        {\n            X = ((X <<  2) | (X >> 26)) & 0x0FFFFFFF;\n            Y = ((Y <<  2) | (Y >> 26)) & 0x0FFFFFFF;\n        }\n\n        *SK++ =   ((X <<  4) & 0x24000000) | ((X << 28) & 0x10000000)\n                | ((X << 14) & 0x08000000) | ((X << 18) & 0x02080000)\n                | ((X <<  6) & 0x01000000) | ((X <<  9) & 0x00200000)\n                | ((X >>  1) & 0x00100000) | ((X << 10) & 0x00040000)\n                | ((X <<  2) & 0x00020000) | ((X >> 10) & 0x00010000)\n                | ((Y >> 13) & 0x00002000) | ((Y >>  4) & 0x00001000)\n                | ((Y <<  6) & 0x00000800) | ((Y >>  1) & 0x00000400)\n                | ((Y >> 14) & 0x00000200) | ((Y      ) & 0x00000100)\n                | ((Y >>  5) & 0x00000020) | ((Y >> 10) & 0x00000010)\n                | ((Y >>  3) & 0x00000008) | ((Y >> 18) & 0x00000004)\n                | ((Y >> 26) & 0x00000002) | ((Y >> 24) & 0x00000001);\n\n        *SK++ =   ((X << 15) & 0x20000000) | ((X << 17) & 0x10000000)\n                | ((X << 10) & 0x08000000) | ((X << 22) & 0x04000000)\n                | ((X >>  2) & 0x02000000) | ((X <<  1) & 0x01000000)\n                | ((X << 16) & 0x00200000) | ((X << 11) & 0x00100000)\n                | ((X <<  3) & 0x00080000) | ((X >>  6) & 0x00040000)\n                | ((X << 15) & 0x00020000) | ((X >>  4) & 0x00010000)\n                | ((Y >>  2) & 0x00002000) | ((Y <<  8) & 0x00001000)\n                | ((Y >> 14) & 0x00000808) | ((Y >>  9) & 0x00000400)\n                | ((Y      ) & 0x00000200) | ((Y <<  7) & 0x00000100)\n                | ((Y >>  7) & 0x00000020) | ((Y >>  3) & 0x00000011)\n                | ((Y <<  2) & 0x00000004) | ((Y >> 21) & 0x00000002);\n    }\n}\n#endif /* !MBEDTLS_DES_SETKEY_ALT */\n\n/*\n * DES key schedule (56-bit, encryption)\n */\nint mbedtls_des_setkey_enc( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] )\n{\n    mbedtls_des_setkey( ctx->sk, key );\n\n    return( 0 );\n}\n\n/*\n * DES key schedule (56-bit, decryption)\n */\nint mbedtls_des_setkey_dec( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] )\n{\n    int i;\n\n    mbedtls_des_setkey( ctx->sk, key );\n\n    for( i = 0; i < 16; i += 2 )\n    {\n        SWAP( ctx->sk[i    ], ctx->sk[30 - i] );\n        SWAP( ctx->sk[i + 1], ctx->sk[31 - i] );\n    }\n\n    return( 0 );\n}\n\nstatic void des3_set2key( uint32_t esk[96],\n                          uint32_t dsk[96],\n                          const unsigned char key[MBEDTLS_DES_KEY_SIZE*2] )\n{\n    int i;\n\n    mbedtls_des_setkey( esk, key );\n    mbedtls_des_setkey( dsk + 32, key + 8 );\n\n    for( i = 0; i < 32; i += 2 )\n    {\n        dsk[i     ] = esk[30 - i];\n        dsk[i +  1] = esk[31 - i];\n\n        esk[i + 32] = dsk[62 - i];\n        esk[i + 33] = dsk[63 - i];\n\n        esk[i + 64] = esk[i    ];\n        esk[i + 65] = esk[i + 1];\n\n        dsk[i + 64] = dsk[i    ];\n        dsk[i + 65] = dsk[i + 1];\n    }\n}\n\n/*\n * Triple-DES key schedule (112-bit, encryption)\n */\nint mbedtls_des3_set2key_enc( mbedtls_des3_context *ctx,\n                      const unsigned char key[MBEDTLS_DES_KEY_SIZE * 2] )\n{\n    uint32_t sk[96];\n\n    des3_set2key( ctx->sk, sk, key );\n    mbedtls_platform_zeroize( sk,  sizeof( sk ) );\n\n    return( 0 );\n}\n\n/*\n * Triple-DES key schedule (112-bit, decryption)\n */\nint mbedtls_des3_set2key_dec( mbedtls_des3_context *ctx,\n                      const unsigned char key[MBEDTLS_DES_KEY_SIZE * 2] )\n{\n    uint32_t sk[96];\n\n    des3_set2key( sk, ctx->sk, key );\n    mbedtls_platform_zeroize( sk,  sizeof( sk ) );\n\n    return( 0 );\n}\n\nstatic void des3_set3key( uint32_t esk[96],\n                          uint32_t dsk[96],\n                          const unsigned char key[24] )\n{\n    int i;\n\n    mbedtls_des_setkey( esk, key );\n    mbedtls_des_setkey( dsk + 32, key +  8 );\n    mbedtls_des_setkey( esk + 64, key + 16 );\n\n    for( i = 0; i < 32; i += 2 )\n    {\n        dsk[i     ] = esk[94 - i];\n        dsk[i +  1] = esk[95 - i];\n\n        esk[i + 32] = dsk[62 - i];\n        esk[i + 33] = dsk[63 - i];\n\n        dsk[i + 64] = esk[30 - i];\n        dsk[i + 65] = esk[31 - i];\n    }\n}\n\n/*\n * Triple-DES key schedule (168-bit, encryption)\n */\nint mbedtls_des3_set3key_enc( mbedtls_des3_context *ctx,\n                      const unsigned char key[MBEDTLS_DES_KEY_SIZE * 3] )\n{\n    uint32_t sk[96];\n\n    des3_set3key( ctx->sk, sk, key );\n    mbedtls_platform_zeroize( sk,  sizeof( sk ) );\n\n    return( 0 );\n}\n\n/*\n * Triple-DES key schedule (168-bit, decryption)\n */\nint mbedtls_des3_set3key_dec( mbedtls_des3_context *ctx,\n                      const unsigned char key[MBEDTLS_DES_KEY_SIZE * 3] )\n{\n    uint32_t sk[96];\n\n    des3_set3key( sk, ctx->sk, key );\n    mbedtls_platform_zeroize( sk,  sizeof( sk ) );\n\n    return( 0 );\n}\n\n/*\n * DES-ECB block encryption/decryption\n */\n#if !defined(MBEDTLS_DES_CRYPT_ECB_ALT)\nint mbedtls_des_crypt_ecb( mbedtls_des_context *ctx,\n                    const unsigned char input[8],\n                    unsigned char output[8] )\n{\n    int i;\n    uint32_t X, Y, T, *SK;\n\n    SK = ctx->sk;\n\n    GET_UINT32_BE( X, input, 0 );\n    GET_UINT32_BE( Y, input, 4 );\n\n    DES_IP( X, Y );\n\n    for( i = 0; i < 8; i++ )\n    {\n        DES_ROUND( Y, X );\n        DES_ROUND( X, Y );\n    }\n\n    DES_FP( Y, X );\n\n    PUT_UINT32_BE( Y, output, 0 );\n    PUT_UINT32_BE( X, output, 4 );\n\n    return( 0 );\n}\n#endif /* !MBEDTLS_DES_CRYPT_ECB_ALT */\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n/*\n * DES-CBC buffer encryption/decryption\n */\nint mbedtls_des_crypt_cbc( mbedtls_des_context *ctx,\n                    int mode,\n                    size_t length,\n                    unsigned char iv[8],\n                    const unsigned char *input,\n                    unsigned char *output )\n{\n    int i;\n    unsigned char temp[8];\n\n    if( length % 8 )\n        return( MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH );\n\n    if( mode == MBEDTLS_DES_ENCRYPT )\n    {\n        while( length > 0 )\n        {\n            for( i = 0; i < 8; i++ )\n                output[i] = (unsigned char)( input[i] ^ iv[i] );\n\n            mbedtls_des_crypt_ecb( ctx, output, output );\n            memcpy( iv, output, 8 );\n\n            input  += 8;\n            output += 8;\n            length -= 8;\n        }\n    }\n    else /* MBEDTLS_DES_DECRYPT */\n    {\n        while( length > 0 )\n        {\n            memcpy( temp, input, 8 );\n            mbedtls_des_crypt_ecb( ctx, input, output );\n\n            for( i = 0; i < 8; i++ )\n                output[i] = (unsigned char)( output[i] ^ iv[i] );\n\n            memcpy( iv, temp, 8 );\n\n            input  += 8;\n            output += 8;\n            length -= 8;\n        }\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n/*\n * 3DES-ECB block encryption/decryption\n */\n#if !defined(MBEDTLS_DES3_CRYPT_ECB_ALT)\nint mbedtls_des3_crypt_ecb( mbedtls_des3_context *ctx,\n                     const unsigned char input[8],\n                     unsigned char output[8] )\n{\n    int i;\n    uint32_t X, Y, T, *SK;\n\n    SK = ctx->sk;\n\n    GET_UINT32_BE( X, input, 0 );\n    GET_UINT32_BE( Y, input, 4 );\n\n    DES_IP( X, Y );\n\n    for( i = 0; i < 8; i++ )\n    {\n        DES_ROUND( Y, X );\n        DES_ROUND( X, Y );\n    }\n\n    for( i = 0; i < 8; i++ )\n    {\n        DES_ROUND( X, Y );\n        DES_ROUND( Y, X );\n    }\n\n    for( i = 0; i < 8; i++ )\n    {\n        DES_ROUND( Y, X );\n        DES_ROUND( X, Y );\n    }\n\n    DES_FP( Y, X );\n\n    PUT_UINT32_BE( Y, output, 0 );\n    PUT_UINT32_BE( X, output, 4 );\n\n    return( 0 );\n}\n#endif /* !MBEDTLS_DES3_CRYPT_ECB_ALT */\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n/*\n * 3DES-CBC buffer encryption/decryption\n */\nint mbedtls_des3_crypt_cbc( mbedtls_des3_context *ctx,\n                     int mode,\n                     size_t length,\n                     unsigned char iv[8],\n                     const unsigned char *input,\n                     unsigned char *output )\n{\n    int i;\n    unsigned char temp[8];\n\n    if( length % 8 )\n        return( MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH );\n\n    if( mode == MBEDTLS_DES_ENCRYPT )\n    {\n        while( length > 0 )\n        {\n            for( i = 0; i < 8; i++ )\n                output[i] = (unsigned char)( input[i] ^ iv[i] );\n\n            mbedtls_des3_crypt_ecb( ctx, output, output );\n            memcpy( iv, output, 8 );\n\n            input  += 8;\n            output += 8;\n            length -= 8;\n        }\n    }\n    else /* MBEDTLS_DES_DECRYPT */\n    {\n        while( length > 0 )\n        {\n            memcpy( temp, input, 8 );\n            mbedtls_des3_crypt_ecb( ctx, input, output );\n\n            for( i = 0; i < 8; i++ )\n                output[i] = (unsigned char)( output[i] ^ iv[i] );\n\n            memcpy( iv, temp, 8 );\n\n            input  += 8;\n            output += 8;\n            length -= 8;\n        }\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#endif /* !MBEDTLS_DES_ALT */\n\n#if defined(MBEDTLS_SELF_TEST)\n/*\n * DES and 3DES test vectors from:\n *\n * http://csrc.nist.gov/groups/STM/cavp/documents/des/tripledes-vectors.zip\n */\nstatic const unsigned char des3_test_keys[24] =\n{\n    0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF,\n    0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01,\n    0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23\n};\n\nstatic const unsigned char des3_test_buf[8] =\n{\n    0x4E, 0x6F, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74\n};\n\nstatic const unsigned char des3_test_ecb_dec[3][8] =\n{\n    { 0xCD, 0xD6, 0x4F, 0x2F, 0x94, 0x27, 0xC1, 0x5D },\n    { 0x69, 0x96, 0xC8, 0xFA, 0x47, 0xA2, 0xAB, 0xEB },\n    { 0x83, 0x25, 0x39, 0x76, 0x44, 0x09, 0x1A, 0x0A }\n};\n\nstatic const unsigned char des3_test_ecb_enc[3][8] =\n{\n    { 0x6A, 0x2A, 0x19, 0xF4, 0x1E, 0xCA, 0x85, 0x4B },\n    { 0x03, 0xE6, 0x9F, 0x5B, 0xFA, 0x58, 0xEB, 0x42 },\n    { 0xDD, 0x17, 0xE8, 0xB8, 0xB4, 0x37, 0xD2, 0x32 }\n};\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\nstatic const unsigned char des3_test_iv[8] =\n{\n    0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF,\n};\n\nstatic const unsigned char des3_test_cbc_dec[3][8] =\n{\n    { 0x12, 0x9F, 0x40, 0xB9, 0xD2, 0x00, 0x56, 0xB3 },\n    { 0x47, 0x0E, 0xFC, 0x9A, 0x6B, 0x8E, 0xE3, 0x93 },\n    { 0xC5, 0xCE, 0xCF, 0x63, 0xEC, 0xEC, 0x51, 0x4C }\n};\n\nstatic const unsigned char des3_test_cbc_enc[3][8] =\n{\n    { 0x54, 0xF1, 0x5A, 0xF6, 0xEB, 0xE3, 0xA4, 0xB4 },\n    { 0x35, 0x76, 0x11, 0x56, 0x5F, 0xA1, 0x8E, 0x4D },\n    { 0xCB, 0x19, 0x1F, 0x85, 0xD1, 0xED, 0x84, 0x39 }\n};\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n/*\n * Checkup routine\n */\nint mbedtls_des_self_test( int verbose )\n{\n    int i, j, u, v, ret = 0;\n    mbedtls_des_context ctx;\n    mbedtls_des3_context ctx3;\n    unsigned char buf[8];\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    unsigned char prv[8];\n    unsigned char iv[8];\n#endif\n\n    mbedtls_des_init( &ctx );\n    mbedtls_des3_init( &ctx3 );\n    /*\n     * ECB mode\n     */\n    for( i = 0; i < 6; i++ )\n    {\n        u = i >> 1;\n        v = i  & 1;\n\n        if( verbose != 0 )\n            mbedtls_printf( \"  DES%c-ECB-%3d (%s): \",\n                             ( u == 0 ) ? ' ' : '3', 56 + u * 56,\n                             ( v == MBEDTLS_DES_DECRYPT ) ? \"dec\" : \"enc\" );\n\n        memcpy( buf, des3_test_buf, 8 );\n\n        switch( i )\n        {\n        case 0:\n            mbedtls_des_setkey_dec( &ctx, des3_test_keys );\n            break;\n\n        case 1:\n            mbedtls_des_setkey_enc( &ctx, des3_test_keys );\n            break;\n\n        case 2:\n            mbedtls_des3_set2key_dec( &ctx3, des3_test_keys );\n            break;\n\n        case 3:\n            mbedtls_des3_set2key_enc( &ctx3, des3_test_keys );\n            break;\n\n        case 4:\n            mbedtls_des3_set3key_dec( &ctx3, des3_test_keys );\n            break;\n\n        case 5:\n            mbedtls_des3_set3key_enc( &ctx3, des3_test_keys );\n            break;\n\n        default:\n            return( 1 );\n        }\n\n        for( j = 0; j < 10000; j++ )\n        {\n            if( u == 0 )\n                mbedtls_des_crypt_ecb( &ctx, buf, buf );\n            else\n                mbedtls_des3_crypt_ecb( &ctx3, buf, buf );\n        }\n\n        if( ( v == MBEDTLS_DES_DECRYPT &&\n                memcmp( buf, des3_test_ecb_dec[u], 8 ) != 0 ) ||\n            ( v != MBEDTLS_DES_DECRYPT &&\n                memcmp( buf, des3_test_ecb_enc[u], 8 ) != 0 ) )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed\\n\" );\n\n            ret = 1;\n            goto exit;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    /*\n     * CBC mode\n     */\n    for( i = 0; i < 6; i++ )\n    {\n        u = i >> 1;\n        v = i  & 1;\n\n        if( verbose != 0 )\n            mbedtls_printf( \"  DES%c-CBC-%3d (%s): \",\n                             ( u == 0 ) ? ' ' : '3', 56 + u * 56,\n                             ( v == MBEDTLS_DES_DECRYPT ) ? \"dec\" : \"enc\" );\n\n        memcpy( iv,  des3_test_iv,  8 );\n        memcpy( prv, des3_test_iv,  8 );\n        memcpy( buf, des3_test_buf, 8 );\n\n        switch( i )\n        {\n        case 0:\n            mbedtls_des_setkey_dec( &ctx, des3_test_keys );\n            break;\n\n        case 1:\n            mbedtls_des_setkey_enc( &ctx, des3_test_keys );\n            break;\n\n        case 2:\n            mbedtls_des3_set2key_dec( &ctx3, des3_test_keys );\n            break;\n\n        case 3:\n            mbedtls_des3_set2key_enc( &ctx3, des3_test_keys );\n            break;\n\n        case 4:\n            mbedtls_des3_set3key_dec( &ctx3, des3_test_keys );\n            break;\n\n        case 5:\n            mbedtls_des3_set3key_enc( &ctx3, des3_test_keys );\n            break;\n\n        default:\n            return( 1 );\n        }\n\n        if( v == MBEDTLS_DES_DECRYPT )\n        {\n            for( j = 0; j < 10000; j++ )\n            {\n                if( u == 0 )\n                    mbedtls_des_crypt_cbc( &ctx, v, 8, iv, buf, buf );\n                else\n                    mbedtls_des3_crypt_cbc( &ctx3, v, 8, iv, buf, buf );\n            }\n        }\n        else\n        {\n            for( j = 0; j < 10000; j++ )\n            {\n                unsigned char tmp[8];\n\n                if( u == 0 )\n                    mbedtls_des_crypt_cbc( &ctx, v, 8, iv, buf, buf );\n                else\n                    mbedtls_des3_crypt_cbc( &ctx3, v, 8, iv, buf, buf );\n\n                memcpy( tmp, prv, 8 );\n                memcpy( prv, buf, 8 );\n                memcpy( buf, tmp, 8 );\n            }\n\n            memcpy( buf, prv, 8 );\n        }\n\n        if( ( v == MBEDTLS_DES_DECRYPT &&\n                memcmp( buf, des3_test_cbc_dec[u], 8 ) != 0 ) ||\n            ( v != MBEDTLS_DES_DECRYPT &&\n                memcmp( buf, des3_test_cbc_enc[u], 8 ) != 0 ) )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed\\n\" );\n\n            ret = 1;\n            goto exit;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\nexit:\n    mbedtls_des_free( &ctx );\n    mbedtls_des3_free( &ctx3 );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_DES_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/dhm.c",
    "content": "/*\n *  Diffie-Hellman-Merkle key exchange\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The following sources were referenced in the design of this implementation\n *  of the Diffie-Hellman-Merkle algorithm:\n *\n *  [1] Handbook of Applied Cryptography - 1997, Chapter 12\n *      Menezes, van Oorschot and Vanstone\n *\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_DHM_C)\n\n#include \"mbedtls/dhm.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_PEM_PARSE_C)\n#include \"mbedtls/pem.h\"\n#endif\n\n#if defined(MBEDTLS_ASN1_PARSE_C)\n#include \"mbedtls/asn1.h\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#include <stdio.h>\n#define mbedtls_printf     printf\n#define mbedtls_calloc    calloc\n#define mbedtls_free       free\n#endif\n\n#if !defined(MBEDTLS_DHM_ALT)\n\n/*\n * helper to validate the mbedtls_mpi size and import it\n */\nstatic int dhm_read_bignum( mbedtls_mpi *X,\n                            unsigned char **p,\n                            const unsigned char *end )\n{\n    int ret, n;\n\n    if( end - *p < 2 )\n        return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );\n\n    n = ( (*p)[0] << 8 ) | (*p)[1];\n    (*p) += 2;\n\n    if( (int)( end - *p ) < n )\n        return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );\n\n    if( ( ret = mbedtls_mpi_read_binary( X, *p, n ) ) != 0 )\n        return( MBEDTLS_ERR_DHM_READ_PARAMS_FAILED + ret );\n\n    (*p) += n;\n\n    return( 0 );\n}\n\n/*\n * Verify sanity of parameter with regards to P\n *\n * Parameter should be: 2 <= public_param <= P - 2\n *\n * This means that we need to return an error if\n *              public_param < 2 or public_param > P-2\n *\n * For more information on the attack, see:\n *  http://www.cl.cam.ac.uk/~rja14/Papers/psandqs.pdf\n *  http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-2643\n */\nstatic int dhm_check_range( const mbedtls_mpi *param, const mbedtls_mpi *P )\n{\n    mbedtls_mpi L, U;\n    int ret = 0;\n\n    mbedtls_mpi_init( &L ); mbedtls_mpi_init( &U );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &L, 2 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &U, P, 2 ) );\n\n    if( mbedtls_mpi_cmp_mpi( param, &L ) < 0 ||\n        mbedtls_mpi_cmp_mpi( param, &U ) > 0 )\n    {\n        ret = MBEDTLS_ERR_DHM_BAD_INPUT_DATA;\n    }\n\ncleanup:\n    mbedtls_mpi_free( &L ); mbedtls_mpi_free( &U );\n    return( ret );\n}\n\nvoid mbedtls_dhm_init( mbedtls_dhm_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_dhm_context ) );\n}\n\n/*\n * Parse the ServerKeyExchange parameters\n */\nint mbedtls_dhm_read_params( mbedtls_dhm_context *ctx,\n                     unsigned char **p,\n                     const unsigned char *end )\n{\n    int ret;\n\n    if( ( ret = dhm_read_bignum( &ctx->P,  p, end ) ) != 0 ||\n        ( ret = dhm_read_bignum( &ctx->G,  p, end ) ) != 0 ||\n        ( ret = dhm_read_bignum( &ctx->GY, p, end ) ) != 0 )\n        return( ret );\n\n    if( ( ret = dhm_check_range( &ctx->GY, &ctx->P ) ) != 0 )\n        return( ret );\n\n    ctx->len = mbedtls_mpi_size( &ctx->P );\n\n    return( 0 );\n}\n\n/*\n * Setup and write the ServerKeyExchange parameters\n */\nint mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size,\n                     unsigned char *output, size_t *olen,\n                     int (*f_rng)(void *, unsigned char *, size_t),\n                     void *p_rng )\n{\n    int ret, count = 0;\n    size_t n1, n2, n3;\n    unsigned char *p;\n\n    if( mbedtls_mpi_cmp_int( &ctx->P, 0 ) == 0 )\n        return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );\n\n    /*\n     * Generate X as large as possible ( < P )\n     */\n    do\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->X, x_size, f_rng, p_rng ) );\n\n        while( mbedtls_mpi_cmp_mpi( &ctx->X, &ctx->P ) >= 0 )\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &ctx->X, 1 ) );\n\n        if( count++ > 10 )\n            return( MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED );\n    }\n    while( dhm_check_range( &ctx->X, &ctx->P ) != 0 );\n\n    /*\n     * Calculate GX = G^X mod P\n     */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->GX, &ctx->G, &ctx->X,\n                          &ctx->P , &ctx->RP ) );\n\n    if( ( ret = dhm_check_range( &ctx->GX, &ctx->P ) ) != 0 )\n        return( ret );\n\n    /*\n     * export P, G, GX\n     */\n#define DHM_MPI_EXPORT( X, n )                                          \\\n    do {                                                                \\\n        MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( ( X ),               \\\n                                                   p + 2,               \\\n                                                   ( n ) ) );           \\\n        *p++ = (unsigned char)( ( n ) >> 8 );                           \\\n        *p++ = (unsigned char)( ( n )      );                           \\\n        p += ( n );                                                     \\\n    } while( 0 )\n\n    n1 = mbedtls_mpi_size( &ctx->P  );\n    n2 = mbedtls_mpi_size( &ctx->G  );\n    n3 = mbedtls_mpi_size( &ctx->GX );\n\n    p = output;\n    DHM_MPI_EXPORT( &ctx->P , n1 );\n    DHM_MPI_EXPORT( &ctx->G , n2 );\n    DHM_MPI_EXPORT( &ctx->GX, n3 );\n\n    *olen = p - output;\n\n    ctx->len = n1;\n\ncleanup:\n\n    if( ret != 0 )\n        return( MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED + ret );\n\n    return( 0 );\n}\n\n/*\n * Set prime modulus and generator\n */\nint mbedtls_dhm_set_group( mbedtls_dhm_context *ctx,\n                           const mbedtls_mpi *P,\n                           const mbedtls_mpi *G )\n{\n    int ret;\n\n    if( ctx == NULL || P == NULL || G == NULL )\n        return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );\n\n    if( ( ret = mbedtls_mpi_copy( &ctx->P, P ) ) != 0 ||\n        ( ret = mbedtls_mpi_copy( &ctx->G, G ) ) != 0 )\n    {\n        return( MBEDTLS_ERR_DHM_SET_GROUP_FAILED + ret );\n    }\n\n    ctx->len = mbedtls_mpi_size( &ctx->P );\n    return( 0 );\n}\n\n/*\n * Import the peer's public value G^Y\n */\nint mbedtls_dhm_read_public( mbedtls_dhm_context *ctx,\n                     const unsigned char *input, size_t ilen )\n{\n    int ret;\n\n    if( ctx == NULL || ilen < 1 || ilen > ctx->len )\n        return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );\n\n    if( ( ret = mbedtls_mpi_read_binary( &ctx->GY, input, ilen ) ) != 0 )\n        return( MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED + ret );\n\n    return( 0 );\n}\n\n/*\n * Create own private value X and export G^X\n */\nint mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size,\n                     unsigned char *output, size_t olen,\n                     int (*f_rng)(void *, unsigned char *, size_t),\n                     void *p_rng )\n{\n    int ret, count = 0;\n\n    if( ctx == NULL || olen < 1 || olen > ctx->len )\n        return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );\n\n    if( mbedtls_mpi_cmp_int( &ctx->P, 0 ) == 0 )\n        return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );\n\n    /*\n     * generate X and calculate GX = G^X mod P\n     */\n    do\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->X, x_size, f_rng, p_rng ) );\n\n        while( mbedtls_mpi_cmp_mpi( &ctx->X, &ctx->P ) >= 0 )\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &ctx->X, 1 ) );\n\n        if( count++ > 10 )\n            return( MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED );\n    }\n    while( dhm_check_range( &ctx->X, &ctx->P ) != 0 );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->GX, &ctx->G, &ctx->X,\n                          &ctx->P , &ctx->RP ) );\n\n    if( ( ret = dhm_check_range( &ctx->GX, &ctx->P ) ) != 0 )\n        return( ret );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->GX, output, olen ) );\n\ncleanup:\n\n    if( ret != 0 )\n        return( MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED + ret );\n\n    return( 0 );\n}\n\n/*\n * Use the blinding method and optimisation suggested in section 10 of:\n *  KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA,\n *  DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer\n *  Berlin Heidelberg, 1996. p. 104-113.\n */\nstatic int dhm_update_blinding( mbedtls_dhm_context *ctx,\n                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    int ret, count;\n\n    /*\n     * Don't use any blinding the first time a particular X is used,\n     * but remember it to use blinding next time.\n     */\n    if( mbedtls_mpi_cmp_mpi( &ctx->X, &ctx->pX ) != 0 )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &ctx->pX, &ctx->X ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &ctx->Vi, 1 ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &ctx->Vf, 1 ) );\n\n        return( 0 );\n    }\n\n    /*\n     * Ok, we need blinding. Can we re-use existing values?\n     * If yes, just update them by squaring them.\n     */\n    if( mbedtls_mpi_cmp_int( &ctx->Vi, 1 ) != 0 )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vi, &ctx->Vi ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->P ) );\n\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vf, &ctx->Vf, &ctx->Vf ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vf, &ctx->Vf, &ctx->P ) );\n\n        return( 0 );\n    }\n\n    /*\n     * We need to generate blinding values from scratch\n     */\n\n    /* Vi = random( 2, P-1 ) */\n    count = 0;\n    do\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->Vi, mbedtls_mpi_size( &ctx->P ), f_rng, p_rng ) );\n\n        while( mbedtls_mpi_cmp_mpi( &ctx->Vi, &ctx->P ) >= 0 )\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &ctx->Vi, 1 ) );\n\n        if( count++ > 10 )\n            return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );\n    }\n    while( mbedtls_mpi_cmp_int( &ctx->Vi, 1 ) <= 0 );\n\n    /* Vf = Vi^-X mod P */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->Vf, &ctx->Vi, &ctx->P ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->Vf, &ctx->Vf, &ctx->X, &ctx->P, &ctx->RP ) );\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Derive and export the shared secret (G^Y)^X mod P\n */\nint mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx,\n                     unsigned char *output, size_t output_size, size_t *olen,\n                     int (*f_rng)(void *, unsigned char *, size_t),\n                     void *p_rng )\n{\n    int ret;\n    mbedtls_mpi GYb;\n\n    if( ctx == NULL || output_size < ctx->len )\n        return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );\n\n    if( ( ret = dhm_check_range( &ctx->GY, &ctx->P ) ) != 0 )\n        return( ret );\n\n    mbedtls_mpi_init( &GYb );\n\n    /* Blind peer's value */\n    if( f_rng != NULL )\n    {\n        MBEDTLS_MPI_CHK( dhm_update_blinding( ctx, f_rng, p_rng ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &GYb, &ctx->GY, &ctx->Vi ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &GYb, &GYb, &ctx->P ) );\n    }\n    else\n        MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &GYb, &ctx->GY ) );\n\n    /* Do modular exponentiation */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->K, &GYb, &ctx->X,\n                          &ctx->P, &ctx->RP ) );\n\n    /* Unblind secret value */\n    if( f_rng != NULL )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->K, &ctx->K, &ctx->Vf ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->K, &ctx->K, &ctx->P ) );\n    }\n\n    *olen = mbedtls_mpi_size( &ctx->K );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->K, output, *olen ) );\n\ncleanup:\n    mbedtls_mpi_free( &GYb );\n\n    if( ret != 0 )\n        return( MBEDTLS_ERR_DHM_CALC_SECRET_FAILED + ret );\n\n    return( 0 );\n}\n\n/*\n * Free the components of a DHM key\n */\nvoid mbedtls_dhm_free( mbedtls_dhm_context *ctx )\n{\n    mbedtls_mpi_free( &ctx->pX ); mbedtls_mpi_free( &ctx->Vf );\n    mbedtls_mpi_free( &ctx->Vi ); mbedtls_mpi_free( &ctx->RP );\n    mbedtls_mpi_free( &ctx->K  ); mbedtls_mpi_free( &ctx->GY );\n    mbedtls_mpi_free( &ctx->GX ); mbedtls_mpi_free( &ctx->X  );\n    mbedtls_mpi_free( &ctx->G  ); mbedtls_mpi_free( &ctx->P  );\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_dhm_context ) );\n}\n\n#if defined(MBEDTLS_ASN1_PARSE_C)\n/*\n * Parse DHM parameters\n */\nint mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin,\n                   size_t dhminlen )\n{\n    int ret;\n    size_t len;\n    unsigned char *p, *end;\n#if defined(MBEDTLS_PEM_PARSE_C)\n    mbedtls_pem_context pem;\n\n    mbedtls_pem_init( &pem );\n\n    /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */\n    if( dhminlen == 0 || dhmin[dhminlen - 1] != '\\0' )\n        ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;\n    else\n        ret = mbedtls_pem_read_buffer( &pem,\n                               \"-----BEGIN DH PARAMETERS-----\",\n                               \"-----END DH PARAMETERS-----\",\n                               dhmin, NULL, 0, &dhminlen );\n\n    if( ret == 0 )\n    {\n        /*\n         * Was PEM encoded\n         */\n        dhminlen = pem.buflen;\n    }\n    else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )\n        goto exit;\n\n    p = ( ret == 0 ) ? pem.buf : (unsigned char *) dhmin;\n#else\n    p = (unsigned char *) dhmin;\n#endif /* MBEDTLS_PEM_PARSE_C */\n    end = p + dhminlen;\n\n    /*\n     *  DHParams ::= SEQUENCE {\n     *      prime              INTEGER,  -- P\n     *      generator          INTEGER,  -- g\n     *      privateValueLength INTEGER OPTIONAL\n     *  }\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        ret = MBEDTLS_ERR_DHM_INVALID_FORMAT + ret;\n        goto exit;\n    }\n\n    end = p + len;\n\n    if( ( ret = mbedtls_asn1_get_mpi( &p, end, &dhm->P  ) ) != 0 ||\n        ( ret = mbedtls_asn1_get_mpi( &p, end, &dhm->G ) ) != 0 )\n    {\n        ret = MBEDTLS_ERR_DHM_INVALID_FORMAT + ret;\n        goto exit;\n    }\n\n    if( p != end )\n    {\n        /* This might be the optional privateValueLength.\n         * If so, we can cleanly discard it */\n        mbedtls_mpi rec;\n        mbedtls_mpi_init( &rec );\n        ret = mbedtls_asn1_get_mpi( &p, end, &rec );\n        mbedtls_mpi_free( &rec );\n        if ( ret != 0 )\n        {\n            ret = MBEDTLS_ERR_DHM_INVALID_FORMAT + ret;\n            goto exit;\n        }\n        if ( p != end )\n        {\n            ret = MBEDTLS_ERR_DHM_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;\n            goto exit;\n        }\n    }\n\n    ret = 0;\n\n    dhm->len = mbedtls_mpi_size( &dhm->P );\n\nexit:\n#if defined(MBEDTLS_PEM_PARSE_C)\n    mbedtls_pem_free( &pem );\n#endif\n    if( ret != 0 )\n        mbedtls_dhm_free( dhm );\n\n    return( ret );\n}\n\n#if defined(MBEDTLS_FS_IO)\n/*\n * Load all data from a file into a given buffer.\n *\n * The file is expected to contain either PEM or DER encoded data.\n * A terminating null byte is always appended. It is included in the announced\n * length only if the data looks like it is PEM encoded.\n */\nstatic int load_file( const char *path, unsigned char **buf, size_t *n )\n{\n    FILE *f;\n    long size;\n\n    if( ( f = fopen( path, \"rb\" ) ) == NULL )\n        return( MBEDTLS_ERR_DHM_FILE_IO_ERROR );\n\n    fseek( f, 0, SEEK_END );\n    if( ( size = ftell( f ) ) == -1 )\n    {\n        fclose( f );\n        return( MBEDTLS_ERR_DHM_FILE_IO_ERROR );\n    }\n    fseek( f, 0, SEEK_SET );\n\n    *n = (size_t) size;\n\n    if( *n + 1 == 0 ||\n        ( *buf = mbedtls_calloc( 1, *n + 1 ) ) == NULL )\n    {\n        fclose( f );\n        return( MBEDTLS_ERR_DHM_ALLOC_FAILED );\n    }\n\n    if( fread( *buf, 1, *n, f ) != *n )\n    {\n        fclose( f );\n\n        mbedtls_platform_zeroize( *buf, *n + 1 );\n        mbedtls_free( *buf );\n\n        return( MBEDTLS_ERR_DHM_FILE_IO_ERROR );\n    }\n\n    fclose( f );\n\n    (*buf)[*n] = '\\0';\n\n    if( strstr( (const char *) *buf, \"-----BEGIN \" ) != NULL )\n        ++*n;\n\n    return( 0 );\n}\n\n/*\n * Load and parse DHM parameters\n */\nint mbedtls_dhm_parse_dhmfile( mbedtls_dhm_context *dhm, const char *path )\n{\n    int ret;\n    size_t n;\n    unsigned char *buf;\n\n    if( ( ret = load_file( path, &buf, &n ) ) != 0 )\n        return( ret );\n\n    ret = mbedtls_dhm_parse_dhm( dhm, buf, n );\n\n    mbedtls_platform_zeroize( buf, n );\n    mbedtls_free( buf );\n\n    return( ret );\n}\n#endif /* MBEDTLS_FS_IO */\n#endif /* MBEDTLS_ASN1_PARSE_C */\n#endif /* MBEDTLS_DHM_ALT */\n\n#if defined(MBEDTLS_SELF_TEST)\n\nstatic const char mbedtls_test_dhm_params[] =\n\"-----BEGIN DH PARAMETERS-----\\r\\n\"\n\"MIGHAoGBAJ419DBEOgmQTzo5qXl5fQcN9TN455wkOL7052HzxxRVMyhYmwQcgJvh\\r\\n\"\n\"1sa18fyfR9OiVEMYglOpkqVoGLN7qd5aQNNi5W7/C+VBdHTBJcGZJyyP5B3qcz32\\r\\n\"\n\"9mLJKudlVudV0Qxk5qUJaPZ/xupz0NyoVpviuiBOI1gNi8ovSXWzAgEC\\r\\n\"\n\"-----END DH PARAMETERS-----\\r\\n\";\n\nstatic const size_t mbedtls_test_dhm_params_len = sizeof( mbedtls_test_dhm_params );\n\n/*\n * Checkup routine\n */\nint mbedtls_dhm_self_test( int verbose )\n{\n    int ret;\n    mbedtls_dhm_context dhm;\n\n    mbedtls_dhm_init( &dhm );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  DHM parameter load: \" );\n\n    if( ( ret = mbedtls_dhm_parse_dhm( &dhm,\n                    (const unsigned char *) mbedtls_test_dhm_params,\n                    mbedtls_test_dhm_params_len ) ) != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        ret = 1;\n        goto exit;\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\\n\" );\n\nexit:\n    mbedtls_dhm_free( &dhm );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_DHM_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/ecdh.c",
    "content": "/*\n *  Elliptic curve Diffie-Hellman\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n/*\n * References:\n *\n * SEC1 http://www.secg.org/index.php?action=secg,docs_secg\n * RFC 4492\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_ECDH_C)\n\n#include \"mbedtls/ecdh.h\"\n\n#include <string.h>\n\n#if !defined(MBEDTLS_ECDH_GEN_PUBLIC_ALT)\n/*\n * Generate public key: simple wrapper around mbedtls_ecp_gen_keypair\n */\nint mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q,\n                     int (*f_rng)(void *, unsigned char *, size_t),\n                     void *p_rng )\n{\n    return mbedtls_ecp_gen_keypair( grp, d, Q, f_rng, p_rng );\n}\n#endif /* MBEDTLS_ECDH_GEN_PUBLIC_ALT */\n\n#if !defined(MBEDTLS_ECDH_COMPUTE_SHARED_ALT)\n/*\n * Compute shared secret (SEC1 3.3.1)\n */\nint mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z,\n                         const mbedtls_ecp_point *Q, const mbedtls_mpi *d,\n                         int (*f_rng)(void *, unsigned char *, size_t),\n                         void *p_rng )\n{\n    int ret;\n    mbedtls_ecp_point P;\n\n    mbedtls_ecp_point_init( &P );\n\n    /*\n     * Make sure Q is a valid pubkey before using it\n     */\n    MBEDTLS_MPI_CHK( mbedtls_ecp_check_pubkey( grp, Q ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, &P, d, Q, f_rng, p_rng ) );\n\n    if( mbedtls_ecp_is_zero( &P ) )\n    {\n        ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;\n        goto cleanup;\n    }\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( z, &P.X ) );\n\ncleanup:\n    mbedtls_ecp_point_free( &P );\n\n    return( ret );\n}\n#endif /* MBEDTLS_ECDH_COMPUTE_SHARED_ALT */\n\n/*\n * Initialize context\n */\nvoid mbedtls_ecdh_init( mbedtls_ecdh_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_ecdh_context ) );\n}\n\n/*\n * Free context\n */\nvoid mbedtls_ecdh_free( mbedtls_ecdh_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    mbedtls_ecp_group_free( &ctx->grp );\n    mbedtls_ecp_point_free( &ctx->Q   );\n    mbedtls_ecp_point_free( &ctx->Qp  );\n    mbedtls_ecp_point_free( &ctx->Vi  );\n    mbedtls_ecp_point_free( &ctx->Vf  );\n    mbedtls_mpi_free( &ctx->d  );\n    mbedtls_mpi_free( &ctx->z  );\n    mbedtls_mpi_free( &ctx->_d );\n}\n\n/*\n * Setup and write the ServerKeyExhange parameters (RFC 4492)\n *      struct {\n *          ECParameters    curve_params;\n *          ECPoint         public;\n *      } ServerECDHParams;\n */\nint mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen,\n                      unsigned char *buf, size_t blen,\n                      int (*f_rng)(void *, unsigned char *, size_t),\n                      void *p_rng )\n{\n    int ret;\n    size_t grp_len, pt_len;\n\n    if( ctx == NULL || ctx->grp.pbits == 0 )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    if( ( ret = mbedtls_ecdh_gen_public( &ctx->grp, &ctx->d, &ctx->Q, f_rng, p_rng ) )\n                != 0 )\n        return( ret );\n\n    if( ( ret = mbedtls_ecp_tls_write_group( &ctx->grp, &grp_len, buf, blen ) )\n                != 0 )\n        return( ret );\n\n    buf += grp_len;\n    blen -= grp_len;\n\n    if( ( ret = mbedtls_ecp_tls_write_point( &ctx->grp, &ctx->Q, ctx->point_format,\n                                     &pt_len, buf, blen ) ) != 0 )\n        return( ret );\n\n    *olen = grp_len + pt_len;\n    return( 0 );\n}\n\n/*\n * Read the ServerKeyExhange parameters (RFC 4492)\n *      struct {\n *          ECParameters    curve_params;\n *          ECPoint         public;\n *      } ServerECDHParams;\n */\nint mbedtls_ecdh_read_params( mbedtls_ecdh_context *ctx,\n                      const unsigned char **buf, const unsigned char *end )\n{\n    int ret;\n\n    if( ( ret = mbedtls_ecp_tls_read_group( &ctx->grp, buf, end - *buf ) ) != 0 )\n        return( ret );\n\n    if( ( ret = mbedtls_ecp_tls_read_point( &ctx->grp, &ctx->Qp, buf, end - *buf ) )\n                != 0 )\n        return( ret );\n\n    return( 0 );\n}\n\n/*\n * Get parameters from a keypair\n */\nint mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx, const mbedtls_ecp_keypair *key,\n                     mbedtls_ecdh_side side )\n{\n    int ret;\n\n    if( ( ret = mbedtls_ecp_group_copy( &ctx->grp, &key->grp ) ) != 0 )\n        return( ret );\n\n    /* If it's not our key, just import the public part as Qp */\n    if( side == MBEDTLS_ECDH_THEIRS )\n        return( mbedtls_ecp_copy( &ctx->Qp, &key->Q ) );\n\n    /* Our key: import public (as Q) and private parts */\n    if( side != MBEDTLS_ECDH_OURS )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    if( ( ret = mbedtls_ecp_copy( &ctx->Q, &key->Q ) ) != 0 ||\n        ( ret = mbedtls_mpi_copy( &ctx->d, &key->d ) ) != 0 )\n        return( ret );\n\n    return( 0 );\n}\n\n/*\n * Setup and export the client public value\n */\nint mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen,\n                      unsigned char *buf, size_t blen,\n                      int (*f_rng)(void *, unsigned char *, size_t),\n                      void *p_rng )\n{\n    int ret;\n\n    if( ctx == NULL || ctx->grp.pbits == 0 )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    if( ( ret = mbedtls_ecdh_gen_public( &ctx->grp, &ctx->d, &ctx->Q, f_rng, p_rng ) )\n                != 0 )\n        return( ret );\n\n    return mbedtls_ecp_tls_write_point( &ctx->grp, &ctx->Q, ctx->point_format,\n                                olen, buf, blen );\n}\n\n/*\n * Parse and import the client's public value\n */\nint mbedtls_ecdh_read_public( mbedtls_ecdh_context *ctx,\n                      const unsigned char *buf, size_t blen )\n{\n    int ret;\n    const unsigned char *p = buf;\n\n    if( ctx == NULL )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    if( ( ret = mbedtls_ecp_tls_read_point( &ctx->grp, &ctx->Qp, &p, blen ) ) != 0 )\n        return( ret );\n\n    if( (size_t)( p - buf ) != blen )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    return( 0 );\n}\n\n/*\n * Derive and export the shared secret\n */\nint mbedtls_ecdh_calc_secret( mbedtls_ecdh_context *ctx, size_t *olen,\n                      unsigned char *buf, size_t blen,\n                      int (*f_rng)(void *, unsigned char *, size_t),\n                      void *p_rng )\n{\n    int ret;\n\n    if( ctx == NULL )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    if( ( ret = mbedtls_ecdh_compute_shared( &ctx->grp, &ctx->z, &ctx->Qp, &ctx->d,\n                                     f_rng, p_rng ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    if( mbedtls_mpi_size( &ctx->z ) > blen )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    *olen = ctx->grp.pbits / 8 + ( ( ctx->grp.pbits % 8 ) != 0 );\n    return mbedtls_mpi_write_binary( &ctx->z, buf, *olen );\n}\n\n#endif /* MBEDTLS_ECDH_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/ecdsa.c",
    "content": "/*\n *  Elliptic curve DSA\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n/*\n * References:\n *\n * SEC1 http://www.secg.org/index.php?action=secg,docs_secg\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_ECDSA_C)\n\n#include \"mbedtls/ecdsa.h\"\n#include \"mbedtls/asn1write.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_ECDSA_DETERMINISTIC)\n#include \"mbedtls/hmac_drbg.h\"\n#endif\n\n/*\n * Derive a suitable integer for group grp from a buffer of length len\n * SEC1 4.1.3 step 5 aka SEC1 4.1.4 step 3\n */\nstatic int derive_mpi( const mbedtls_ecp_group *grp, mbedtls_mpi *x,\n                       const unsigned char *buf, size_t blen )\n{\n    int ret;\n    size_t n_size = ( grp->nbits + 7 ) / 8;\n    size_t use_size = blen > n_size ? n_size : blen;\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( x, buf, use_size ) );\n    if( use_size * 8 > grp->nbits )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( x, use_size * 8 - grp->nbits ) );\n\n    /* While at it, reduce modulo N */\n    if( mbedtls_mpi_cmp_mpi( x, &grp->N ) >= 0 )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( x, x, &grp->N ) );\n\ncleanup:\n    return( ret );\n}\n\n#if !defined(MBEDTLS_ECDSA_SIGN_ALT)\n/*\n * Compute ECDSA signature of a hashed message (SEC1 4.1.3)\n * Obviously, compared to SEC1 4.1.3, we skip step 4 (hash message)\n */\nint mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,\n                const mbedtls_mpi *d, const unsigned char *buf, size_t blen,\n                int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    int ret, key_tries, sign_tries, blind_tries;\n    mbedtls_ecp_point R;\n    mbedtls_mpi k, e, t;\n\n    /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */\n    if( grp->N.p == NULL )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    /* Make sure d is in range 1..n-1 */\n    if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )\n        return( MBEDTLS_ERR_ECP_INVALID_KEY );\n\n    mbedtls_ecp_point_init( &R );\n    mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t );\n\n    sign_tries = 0;\n    do\n    {\n        /*\n         * Steps 1-3: generate a suitable ephemeral keypair\n         * and set r = xR mod n\n         */\n        key_tries = 0;\n        do\n        {\n            MBEDTLS_MPI_CHK( mbedtls_ecp_gen_keypair( grp, &k, &R, f_rng, p_rng ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( r, &R.X, &grp->N ) );\n\n            if( key_tries++ > 10 )\n            {\n                ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;\n                goto cleanup;\n            }\n        }\n        while( mbedtls_mpi_cmp_int( r, 0 ) == 0 );\n\n        /*\n         * Step 5: derive MPI from hashed message\n         */\n        MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) );\n\n        /*\n         * Generate a random value to blind inv_mod in next step,\n         * avoiding a potential timing leak.\n         */\n        blind_tries = 0;\n        do\n        {\n            size_t n_size = ( grp->nbits + 7 ) / 8;\n            MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &t, n_size, f_rng, p_rng ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &t, 8 * n_size - grp->nbits ) );\n\n            /* See mbedtls_ecp_gen_keypair() */\n            if( ++blind_tries > 30 )\n                return( MBEDTLS_ERR_ECP_RANDOM_FAILED );\n        }\n        while( mbedtls_mpi_cmp_int( &t, 1 ) < 0 ||\n               mbedtls_mpi_cmp_mpi( &t, &grp->N ) >= 0 );\n\n        /*\n         * Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n\n         */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, r, d ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &k, &k, &t ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, &k, &grp->N ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) );\n\n        if( sign_tries++ > 10 )\n        {\n            ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;\n            goto cleanup;\n        }\n    }\n    while( mbedtls_mpi_cmp_int( s, 0 ) == 0 );\n\ncleanup:\n    mbedtls_ecp_point_free( &R );\n    mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t );\n\n    return( ret );\n}\n#endif /* MBEDTLS_ECDSA_SIGN_ALT */\n\n#if defined(MBEDTLS_ECDSA_DETERMINISTIC)\n/*\n * Deterministic signature wrapper\n */\nint mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,\n                    const mbedtls_mpi *d, const unsigned char *buf, size_t blen,\n                    mbedtls_md_type_t md_alg )\n{\n    int ret;\n    mbedtls_hmac_drbg_context rng_ctx;\n    unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES];\n    size_t grp_len = ( grp->nbits + 7 ) / 8;\n    const mbedtls_md_info_t *md_info;\n    mbedtls_mpi h;\n\n    if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    mbedtls_mpi_init( &h );\n    mbedtls_hmac_drbg_init( &rng_ctx );\n\n    /* Use private key and message hash (reduced) to initialize HMAC_DRBG */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) );\n    MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) );\n    mbedtls_hmac_drbg_seed_buf( &rng_ctx, md_info, data, 2 * grp_len );\n\n    ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen,\n                      mbedtls_hmac_drbg_random, &rng_ctx );\n\ncleanup:\n    mbedtls_hmac_drbg_free( &rng_ctx );\n    mbedtls_mpi_free( &h );\n\n    return( ret );\n}\n#endif /* MBEDTLS_ECDSA_DETERMINISTIC */\n\n#if !defined(MBEDTLS_ECDSA_VERIFY_ALT)\n/*\n * Verify ECDSA signature of hashed message (SEC1 4.1.4)\n * Obviously, compared to SEC1 4.1.3, we skip step 2 (hash message)\n */\nint mbedtls_ecdsa_verify( mbedtls_ecp_group *grp,\n                  const unsigned char *buf, size_t blen,\n                  const mbedtls_ecp_point *Q, const mbedtls_mpi *r, const mbedtls_mpi *s)\n{\n    int ret;\n    mbedtls_mpi e, s_inv, u1, u2;\n    mbedtls_ecp_point R;\n\n    mbedtls_ecp_point_init( &R );\n    mbedtls_mpi_init( &e ); mbedtls_mpi_init( &s_inv ); mbedtls_mpi_init( &u1 ); mbedtls_mpi_init( &u2 );\n\n    /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */\n    if( grp->N.p == NULL )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    /*\n     * Step 1: make sure r and s are in range 1..n-1\n     */\n    if( mbedtls_mpi_cmp_int( r, 1 ) < 0 || mbedtls_mpi_cmp_mpi( r, &grp->N ) >= 0 ||\n        mbedtls_mpi_cmp_int( s, 1 ) < 0 || mbedtls_mpi_cmp_mpi( s, &grp->N ) >= 0 )\n    {\n        ret = MBEDTLS_ERR_ECP_VERIFY_FAILED;\n        goto cleanup;\n    }\n\n    /*\n     * Additional precaution: make sure Q is valid\n     */\n    MBEDTLS_MPI_CHK( mbedtls_ecp_check_pubkey( grp, Q ) );\n\n    /*\n     * Step 3: derive MPI from hashed message\n     */\n    MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) );\n\n    /*\n     * Step 4: u1 = e / s mod n, u2 = r / s mod n\n     */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &s_inv, s, &grp->N ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &u1, &e, &s_inv ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &u1, &u1, &grp->N ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &u2, r, &s_inv ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &u2, &u2, &grp->N ) );\n\n    /*\n     * Step 5: R = u1 G + u2 Q\n     *\n     * Since we're not using any secret data, no need to pass a RNG to\n     * mbedtls_ecp_mul() for countermesures.\n     */\n    MBEDTLS_MPI_CHK( mbedtls_ecp_muladd( grp, &R, &u1, &grp->G, &u2, Q ) );\n\n    if( mbedtls_ecp_is_zero( &R ) )\n    {\n        ret = MBEDTLS_ERR_ECP_VERIFY_FAILED;\n        goto cleanup;\n    }\n\n    /*\n     * Step 6: convert xR to an integer (no-op)\n     * Step 7: reduce xR mod n (gives v)\n     */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &R.X, &R.X, &grp->N ) );\n\n    /*\n     * Step 8: check if v (that is, R.X) is equal to r\n     */\n    if( mbedtls_mpi_cmp_mpi( &R.X, r ) != 0 )\n    {\n        ret = MBEDTLS_ERR_ECP_VERIFY_FAILED;\n        goto cleanup;\n    }\n\ncleanup:\n    mbedtls_ecp_point_free( &R );\n    mbedtls_mpi_free( &e ); mbedtls_mpi_free( &s_inv ); mbedtls_mpi_free( &u1 ); mbedtls_mpi_free( &u2 );\n\n    return( ret );\n}\n#endif /* MBEDTLS_ECDSA_VERIFY_ALT */\n\n/*\n * Convert a signature (given by context) to ASN.1\n */\nstatic int ecdsa_signature_to_asn1( const mbedtls_mpi *r, const mbedtls_mpi *s,\n                                    unsigned char *sig, size_t *slen )\n{\n    int ret;\n    unsigned char buf[MBEDTLS_ECDSA_MAX_LEN];\n    unsigned char *p = buf + sizeof( buf );\n    size_t len = 0;\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &p, buf, s ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &p, buf, r ) );\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &p, buf, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &p, buf,\n                                       MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) );\n\n    memcpy( sig, p, len );\n    *slen = len;\n\n    return( 0 );\n}\n\n/*\n * Compute and write signature\n */\nint mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg,\n                           const unsigned char *hash, size_t hlen,\n                           unsigned char *sig, size_t *slen,\n                           int (*f_rng)(void *, unsigned char *, size_t),\n                           void *p_rng )\n{\n    int ret;\n    mbedtls_mpi r, s;\n\n    mbedtls_mpi_init( &r );\n    mbedtls_mpi_init( &s );\n\n#if defined(MBEDTLS_ECDSA_DETERMINISTIC)\n    (void) f_rng;\n    (void) p_rng;\n\n    MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign_det( &ctx->grp, &r, &s, &ctx->d,\n                             hash, hlen, md_alg ) );\n#else\n    (void) md_alg;\n\n    MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d,\n                         hash, hlen, f_rng, p_rng ) );\n#endif\n\n    MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) );\n\ncleanup:\n    mbedtls_mpi_free( &r );\n    mbedtls_mpi_free( &s );\n\n    return( ret );\n}\n\n#if ! defined(MBEDTLS_DEPRECATED_REMOVED) && \\\n    defined(MBEDTLS_ECDSA_DETERMINISTIC)\nint mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx,\n                               const unsigned char *hash, size_t hlen,\n                               unsigned char *sig, size_t *slen,\n                               mbedtls_md_type_t md_alg )\n{\n    return( mbedtls_ecdsa_write_signature( ctx, md_alg, hash, hlen, sig, slen,\n                                   NULL, NULL ) );\n}\n#endif\n\n/*\n * Read and check signature\n */\nint mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx,\n                          const unsigned char *hash, size_t hlen,\n                          const unsigned char *sig, size_t slen )\n{\n    int ret;\n    unsigned char *p = (unsigned char *) sig;\n    const unsigned char *end = sig + slen;\n    size_t len;\n    mbedtls_mpi r, s;\n\n    mbedtls_mpi_init( &r );\n    mbedtls_mpi_init( &s );\n\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n                    MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        ret += MBEDTLS_ERR_ECP_BAD_INPUT_DATA;\n        goto cleanup;\n    }\n\n    if( p + len != end )\n    {\n        ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA +\n              MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;\n        goto cleanup;\n    }\n\n    if( ( ret = mbedtls_asn1_get_mpi( &p, end, &r ) ) != 0 ||\n        ( ret = mbedtls_asn1_get_mpi( &p, end, &s ) ) != 0 )\n    {\n        ret += MBEDTLS_ERR_ECP_BAD_INPUT_DATA;\n        goto cleanup;\n    }\n\n    if( ( ret = mbedtls_ecdsa_verify( &ctx->grp, hash, hlen,\n                              &ctx->Q, &r, &s ) ) != 0 )\n        goto cleanup;\n\n    /* At this point we know that the buffer starts with a valid signature.\n     * Return 0 if the buffer just contains the signature, and a specific\n     * error code if the valid signature is followed by more data. */\n    if( p != end )\n        ret = MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH;\n\ncleanup:\n    mbedtls_mpi_free( &r );\n    mbedtls_mpi_free( &s );\n\n    return( ret );\n}\n\n#if !defined(MBEDTLS_ECDSA_GENKEY_ALT)\n/*\n * Generate key pair\n */\nint mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid,\n                  int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    return( mbedtls_ecp_group_load( &ctx->grp, gid ) ||\n            mbedtls_ecp_gen_keypair( &ctx->grp, &ctx->d, &ctx->Q, f_rng, p_rng ) );\n}\n#endif /* MBEDTLS_ECDSA_GENKEY_ALT */\n\n/*\n * Set context from an mbedtls_ecp_keypair\n */\nint mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key )\n{\n    int ret;\n\n    if( ( ret = mbedtls_ecp_group_copy( &ctx->grp, &key->grp ) ) != 0 ||\n        ( ret = mbedtls_mpi_copy( &ctx->d, &key->d ) ) != 0 ||\n        ( ret = mbedtls_ecp_copy( &ctx->Q, &key->Q ) ) != 0 )\n    {\n        mbedtls_ecdsa_free( ctx );\n    }\n\n    return( ret );\n}\n\n/*\n * Initialize context\n */\nvoid mbedtls_ecdsa_init( mbedtls_ecdsa_context *ctx )\n{\n    mbedtls_ecp_keypair_init( ctx );\n}\n\n/*\n * Free context\n */\nvoid mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx )\n{\n    mbedtls_ecp_keypair_free( ctx );\n}\n\n#endif /* MBEDTLS_ECDSA_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/ecjpake.c",
    "content": "/*\n *  Elliptic curve J-PAKE\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n/*\n * References in the code are to the Thread v1.0 Specification,\n * available to members of the Thread Group http://threadgroup.org/\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_ECJPAKE_C)\n\n#include \"mbedtls/ecjpake.h\"\n\n#include <string.h>\n\n#if !defined(MBEDTLS_ECJPAKE_ALT)\n\n/*\n * Convert a mbedtls_ecjpake_role to identifier string\n */\nstatic const char * const ecjpake_id[] = {\n    \"client\",\n    \"server\"\n};\n\n#define ID_MINE     ( ecjpake_id[ ctx->role ] )\n#define ID_PEER     ( ecjpake_id[ 1 - ctx->role ] )\n\n/*\n * Initialize context\n */\nvoid mbedtls_ecjpake_init( mbedtls_ecjpake_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    ctx->md_info = NULL;\n    mbedtls_ecp_group_init( &ctx->grp );\n    ctx->point_format = MBEDTLS_ECP_PF_UNCOMPRESSED;\n\n    mbedtls_ecp_point_init( &ctx->Xm1 );\n    mbedtls_ecp_point_init( &ctx->Xm2 );\n    mbedtls_ecp_point_init( &ctx->Xp1 );\n    mbedtls_ecp_point_init( &ctx->Xp2 );\n    mbedtls_ecp_point_init( &ctx->Xp  );\n\n    mbedtls_mpi_init( &ctx->xm1 );\n    mbedtls_mpi_init( &ctx->xm2 );\n    mbedtls_mpi_init( &ctx->s   );\n}\n\n/*\n * Free context\n */\nvoid mbedtls_ecjpake_free( mbedtls_ecjpake_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    ctx->md_info = NULL;\n    mbedtls_ecp_group_free( &ctx->grp );\n\n    mbedtls_ecp_point_free( &ctx->Xm1 );\n    mbedtls_ecp_point_free( &ctx->Xm2 );\n    mbedtls_ecp_point_free( &ctx->Xp1 );\n    mbedtls_ecp_point_free( &ctx->Xp2 );\n    mbedtls_ecp_point_free( &ctx->Xp  );\n\n    mbedtls_mpi_free( &ctx->xm1 );\n    mbedtls_mpi_free( &ctx->xm2 );\n    mbedtls_mpi_free( &ctx->s   );\n}\n\n/*\n * Setup context\n */\nint mbedtls_ecjpake_setup( mbedtls_ecjpake_context *ctx,\n                           mbedtls_ecjpake_role role,\n                           mbedtls_md_type_t hash,\n                           mbedtls_ecp_group_id curve,\n                           const unsigned char *secret,\n                           size_t len )\n{\n    int ret;\n\n    ctx->role = role;\n\n    if( ( ctx->md_info = mbedtls_md_info_from_type( hash ) ) == NULL )\n        return( MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE );\n\n    MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &ctx->grp, curve ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->s, secret, len ) );\n\ncleanup:\n    if( ret != 0 )\n        mbedtls_ecjpake_free( ctx );\n\n    return( ret );\n}\n\n/*\n * Check if context is ready for use\n */\nint mbedtls_ecjpake_check( const mbedtls_ecjpake_context *ctx )\n{\n    if( ctx->md_info == NULL ||\n        ctx->grp.id == MBEDTLS_ECP_DP_NONE ||\n        ctx->s.p == NULL )\n    {\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n    }\n\n    return( 0 );\n}\n\n/*\n * Write a point plus its length to a buffer\n */\nstatic int ecjpake_write_len_point( unsigned char **p,\n                                    const unsigned char *end,\n                                    const mbedtls_ecp_group *grp,\n                                    const int pf,\n                                    const mbedtls_ecp_point *P )\n{\n    int ret;\n    size_t len;\n\n    /* Need at least 4 for length plus 1 for point */\n    if( end < *p || end - *p < 5 )\n        return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );\n\n    ret = mbedtls_ecp_point_write_binary( grp, P, pf,\n                                          &len, *p + 4, end - ( *p + 4 ) );\n    if( ret != 0 )\n        return( ret );\n\n    (*p)[0] = (unsigned char)( ( len >> 24 ) & 0xFF );\n    (*p)[1] = (unsigned char)( ( len >> 16 ) & 0xFF );\n    (*p)[2] = (unsigned char)( ( len >>  8 ) & 0xFF );\n    (*p)[3] = (unsigned char)( ( len       ) & 0xFF );\n\n    *p += 4 + len;\n\n    return( 0 );\n}\n\n/*\n * Size of the temporary buffer for ecjpake_hash:\n * 3 EC points plus their length, plus ID and its length (4 + 6 bytes)\n */\n#define ECJPAKE_HASH_BUF_LEN    ( 3 * ( 4 + MBEDTLS_ECP_MAX_PT_LEN ) + 4 + 6 )\n\n/*\n * Compute hash for ZKP (7.4.2.2.2.1)\n */\nstatic int ecjpake_hash( const mbedtls_md_info_t *md_info,\n                         const mbedtls_ecp_group *grp,\n                         const int pf,\n                         const mbedtls_ecp_point *G,\n                         const mbedtls_ecp_point *V,\n                         const mbedtls_ecp_point *X,\n                         const char *id,\n                         mbedtls_mpi *h )\n{\n    int ret;\n    unsigned char buf[ECJPAKE_HASH_BUF_LEN];\n    unsigned char *p = buf;\n    const unsigned char *end = buf + sizeof( buf );\n    const size_t id_len = strlen( id );\n    unsigned char hash[MBEDTLS_MD_MAX_SIZE];\n\n    /* Write things to temporary buffer */\n    MBEDTLS_MPI_CHK( ecjpake_write_len_point( &p, end, grp, pf, G ) );\n    MBEDTLS_MPI_CHK( ecjpake_write_len_point( &p, end, grp, pf, V ) );\n    MBEDTLS_MPI_CHK( ecjpake_write_len_point( &p, end, grp, pf, X ) );\n\n    if( end - p < 4 )\n        return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );\n\n    *p++ = (unsigned char)( ( id_len >> 24 ) & 0xFF );\n    *p++ = (unsigned char)( ( id_len >> 16 ) & 0xFF );\n    *p++ = (unsigned char)( ( id_len >>  8 ) & 0xFF );\n    *p++ = (unsigned char)( ( id_len       ) & 0xFF );\n\n    if( end < p || (size_t)( end - p ) < id_len )\n        return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );\n\n    memcpy( p, id, id_len );\n    p += id_len;\n\n    /* Compute hash */\n    mbedtls_md( md_info, buf, p - buf, hash );\n\n    /* Turn it into an integer mod n */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( h, hash,\n                                        mbedtls_md_get_size( md_info ) ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( h, h, &grp->N ) );\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Parse a ECShnorrZKP (7.4.2.2.2) and verify it (7.4.2.3.3)\n */\nstatic int ecjpake_zkp_read( const mbedtls_md_info_t *md_info,\n                             const mbedtls_ecp_group *grp,\n                             const int pf,\n                             const mbedtls_ecp_point *G,\n                             const mbedtls_ecp_point *X,\n                             const char *id,\n                             const unsigned char **p,\n                             const unsigned char *end )\n{\n    int ret;\n    mbedtls_ecp_point V, VV;\n    mbedtls_mpi r, h;\n    size_t r_len;\n\n    mbedtls_ecp_point_init( &V );\n    mbedtls_ecp_point_init( &VV );\n    mbedtls_mpi_init( &r );\n    mbedtls_mpi_init( &h );\n\n    /*\n     * struct {\n     *     ECPoint V;\n     *     opaque r<1..2^8-1>;\n     * } ECSchnorrZKP;\n     */\n    if( end < *p )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    MBEDTLS_MPI_CHK( mbedtls_ecp_tls_read_point( grp, &V, p, end - *p ) );\n\n    if( end < *p || (size_t)( end - *p ) < 1 )\n    {\n        ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;\n        goto cleanup;\n    }\n\n    r_len = *(*p)++;\n\n    if( end < *p || (size_t)( end - *p ) < r_len )\n    {\n        ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;\n        goto cleanup;\n    }\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &r, *p, r_len ) );\n    *p += r_len;\n\n    /*\n     * Verification\n     */\n    MBEDTLS_MPI_CHK( ecjpake_hash( md_info, grp, pf, G, &V, X, id, &h ) );\n    MBEDTLS_MPI_CHK( mbedtls_ecp_muladd( (mbedtls_ecp_group *) grp,\n                     &VV, &h, X, &r, G ) );\n\n    if( mbedtls_ecp_point_cmp( &VV, &V ) != 0 )\n    {\n        ret = MBEDTLS_ERR_ECP_VERIFY_FAILED;\n        goto cleanup;\n    }\n\ncleanup:\n    mbedtls_ecp_point_free( &V );\n    mbedtls_ecp_point_free( &VV );\n    mbedtls_mpi_free( &r );\n    mbedtls_mpi_free( &h );\n\n    return( ret );\n}\n\n/*\n * Generate ZKP (7.4.2.3.2) and write it as ECSchnorrZKP (7.4.2.2.2)\n */\nstatic int ecjpake_zkp_write( const mbedtls_md_info_t *md_info,\n                              const mbedtls_ecp_group *grp,\n                              const int pf,\n                              const mbedtls_ecp_point *G,\n                              const mbedtls_mpi *x,\n                              const mbedtls_ecp_point *X,\n                              const char *id,\n                              unsigned char **p,\n                              const unsigned char *end,\n                              int (*f_rng)(void *, unsigned char *, size_t),\n                              void *p_rng )\n{\n    int ret;\n    mbedtls_ecp_point V;\n    mbedtls_mpi v;\n    mbedtls_mpi h; /* later recycled to hold r */\n    size_t len;\n\n    if( end < *p )\n        return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );\n\n    mbedtls_ecp_point_init( &V );\n    mbedtls_mpi_init( &v );\n    mbedtls_mpi_init( &h );\n\n    /* Compute signature */\n    MBEDTLS_MPI_CHK( mbedtls_ecp_gen_keypair_base( (mbedtls_ecp_group *) grp,\n                                                   G, &v, &V, f_rng, p_rng ) );\n    MBEDTLS_MPI_CHK( ecjpake_hash( md_info, grp, pf, G, &V, X, id, &h ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &h, &h, x ) ); /* x*h */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &h, &v, &h ) ); /* v - x*h */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &h, &h, &grp->N ) ); /* r */\n\n    /* Write it out */\n    MBEDTLS_MPI_CHK( mbedtls_ecp_tls_write_point( grp, &V,\n                pf, &len, *p, end - *p ) );\n    *p += len;\n\n    len = mbedtls_mpi_size( &h ); /* actually r */\n    if( end < *p || (size_t)( end - *p ) < 1 + len || len > 255 )\n    {\n        ret = MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;\n        goto cleanup;\n    }\n\n    *(*p)++ = (unsigned char)( len & 0xFF );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, *p, len ) ); /* r */\n    *p += len;\n\ncleanup:\n    mbedtls_ecp_point_free( &V );\n    mbedtls_mpi_free( &v );\n    mbedtls_mpi_free( &h );\n\n    return( ret );\n}\n\n/*\n * Parse a ECJPAKEKeyKP (7.4.2.2.1) and check proof\n * Output: verified public key X\n */\nstatic int ecjpake_kkp_read( const mbedtls_md_info_t *md_info,\n                             const mbedtls_ecp_group *grp,\n                             const int pf,\n                             const mbedtls_ecp_point *G,\n                             mbedtls_ecp_point *X,\n                             const char *id,\n                             const unsigned char **p,\n                             const unsigned char *end )\n{\n    int ret;\n\n    if( end < *p )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    /*\n     * struct {\n     *     ECPoint X;\n     *     ECSchnorrZKP zkp;\n     * } ECJPAKEKeyKP;\n     */\n    MBEDTLS_MPI_CHK( mbedtls_ecp_tls_read_point( grp, X, p, end - *p ) );\n    if( mbedtls_ecp_is_zero( X ) )\n    {\n        ret = MBEDTLS_ERR_ECP_INVALID_KEY;\n        goto cleanup;\n    }\n\n    MBEDTLS_MPI_CHK( ecjpake_zkp_read( md_info, grp, pf, G, X, id, p, end ) );\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Generate an ECJPAKEKeyKP\n * Output: the serialized structure, plus private/public key pair\n */\nstatic int ecjpake_kkp_write( const mbedtls_md_info_t *md_info,\n                              const mbedtls_ecp_group *grp,\n                              const int pf,\n                              const mbedtls_ecp_point *G,\n                              mbedtls_mpi *x,\n                              mbedtls_ecp_point *X,\n                              const char *id,\n                              unsigned char **p,\n                              const unsigned char *end,\n                              int (*f_rng)(void *, unsigned char *, size_t),\n                              void *p_rng )\n{\n    int ret;\n    size_t len;\n\n    if( end < *p )\n        return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );\n\n    /* Generate key (7.4.2.3.1) and write it out */\n    MBEDTLS_MPI_CHK( mbedtls_ecp_gen_keypair_base( (mbedtls_ecp_group *) grp, G, x, X,\n                                                   f_rng, p_rng ) );\n    MBEDTLS_MPI_CHK( mbedtls_ecp_tls_write_point( grp, X,\n                pf, &len, *p, end - *p ) );\n    *p += len;\n\n    /* Generate and write proof */\n    MBEDTLS_MPI_CHK( ecjpake_zkp_write( md_info, grp, pf, G, x, X, id,\n                                        p, end, f_rng, p_rng ) );\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Read a ECJPAKEKeyKPPairList (7.4.2.3) and check proofs\n * Ouputs: verified peer public keys Xa, Xb\n */\nstatic int ecjpake_kkpp_read( const mbedtls_md_info_t *md_info,\n                              const mbedtls_ecp_group *grp,\n                              const int pf,\n                              const mbedtls_ecp_point *G,\n                              mbedtls_ecp_point *Xa,\n                              mbedtls_ecp_point *Xb,\n                              const char *id,\n                              const unsigned char *buf,\n                              size_t len )\n{\n    int ret;\n    const unsigned char *p = buf;\n    const unsigned char *end = buf + len;\n\n    /*\n     * struct {\n     *     ECJPAKEKeyKP ecjpake_key_kp_pair_list[2];\n     * } ECJPAKEKeyKPPairList;\n     */\n    MBEDTLS_MPI_CHK( ecjpake_kkp_read( md_info, grp, pf, G, Xa, id, &p, end ) );\n    MBEDTLS_MPI_CHK( ecjpake_kkp_read( md_info, grp, pf, G, Xb, id, &p, end ) );\n\n    if( p != end )\n        ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Generate a ECJPAKEKeyKPPairList\n * Outputs: the serialized structure, plus two private/public key pairs\n */\nstatic int ecjpake_kkpp_write( const mbedtls_md_info_t *md_info,\n                               const mbedtls_ecp_group *grp,\n                               const int pf,\n                               const mbedtls_ecp_point *G,\n                               mbedtls_mpi *xm1,\n                               mbedtls_ecp_point *Xa,\n                               mbedtls_mpi *xm2,\n                               mbedtls_ecp_point *Xb,\n                               const char *id,\n                               unsigned char *buf,\n                               size_t len,\n                               size_t *olen,\n                               int (*f_rng)(void *, unsigned char *, size_t),\n                               void *p_rng )\n{\n    int ret;\n    unsigned char *p = buf;\n    const unsigned char *end = buf + len;\n\n    MBEDTLS_MPI_CHK( ecjpake_kkp_write( md_info, grp, pf, G, xm1, Xa, id,\n                &p, end, f_rng, p_rng ) );\n    MBEDTLS_MPI_CHK( ecjpake_kkp_write( md_info, grp, pf, G, xm2, Xb, id,\n                &p, end, f_rng, p_rng ) );\n\n    *olen = p - buf;\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Read and process the first round message\n */\nint mbedtls_ecjpake_read_round_one( mbedtls_ecjpake_context *ctx,\n                                    const unsigned char *buf,\n                                    size_t len )\n{\n    return( ecjpake_kkpp_read( ctx->md_info, &ctx->grp, ctx->point_format,\n                               &ctx->grp.G,\n                               &ctx->Xp1, &ctx->Xp2, ID_PEER,\n                               buf, len ) );\n}\n\n/*\n * Generate and write the first round message\n */\nint mbedtls_ecjpake_write_round_one( mbedtls_ecjpake_context *ctx,\n                            unsigned char *buf, size_t len, size_t *olen,\n                            int (*f_rng)(void *, unsigned char *, size_t),\n                            void *p_rng )\n{\n    return( ecjpake_kkpp_write( ctx->md_info, &ctx->grp, ctx->point_format,\n                                &ctx->grp.G,\n                                &ctx->xm1, &ctx->Xm1, &ctx->xm2, &ctx->Xm2,\n                                ID_MINE, buf, len, olen, f_rng, p_rng ) );\n}\n\n/*\n * Compute the sum of three points R = A + B + C\n */\nstatic int ecjpake_ecp_add3( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,\n                             const mbedtls_ecp_point *A,\n                             const mbedtls_ecp_point *B,\n                             const mbedtls_ecp_point *C )\n{\n    int ret;\n    mbedtls_mpi one;\n\n    mbedtls_mpi_init( &one );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &one, 1 ) );\n    MBEDTLS_MPI_CHK( mbedtls_ecp_muladd( grp, R, &one, A, &one, B ) );\n    MBEDTLS_MPI_CHK( mbedtls_ecp_muladd( grp, R, &one, R, &one, C ) );\n\ncleanup:\n    mbedtls_mpi_free( &one );\n\n    return( ret );\n}\n\n/*\n * Read and process second round message (C: 7.4.2.5, S: 7.4.2.6)\n */\nint mbedtls_ecjpake_read_round_two( mbedtls_ecjpake_context *ctx,\n                                            const unsigned char *buf,\n                                            size_t len )\n{\n    int ret;\n    const unsigned char *p = buf;\n    const unsigned char *end = buf + len;\n    mbedtls_ecp_group grp;\n    mbedtls_ecp_point G;    /* C: GB, S: GA */\n\n    mbedtls_ecp_group_init( &grp );\n    mbedtls_ecp_point_init( &G );\n\n    /*\n     * Server: GA = X3  + X4  + X1      (7.4.2.6.1)\n     * Client: GB = X1  + X2  + X3      (7.4.2.5.1)\n     * Unified: G = Xm1 + Xm2 + Xp1\n     * We need that before parsing in order to check Xp as we read it\n     */\n    MBEDTLS_MPI_CHK( ecjpake_ecp_add3( &ctx->grp, &G,\n                                       &ctx->Xm1, &ctx->Xm2, &ctx->Xp1 ) );\n\n    /*\n     * struct {\n     *     ECParameters curve_params;   // only client reading server msg\n     *     ECJPAKEKeyKP ecjpake_key_kp;\n     * } Client/ServerECJPAKEParams;\n     */\n    if( ctx->role == MBEDTLS_ECJPAKE_CLIENT )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_ecp_tls_read_group( &grp, &p, len ) );\n        if( grp.id != ctx->grp.id )\n        {\n            ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;\n            goto cleanup;\n        }\n    }\n\n    MBEDTLS_MPI_CHK( ecjpake_kkp_read( ctx->md_info, &ctx->grp,\n                            ctx->point_format,\n                            &G, &ctx->Xp, ID_PEER, &p, end ) );\n\n    if( p != end )\n    {\n        ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;\n        goto cleanup;\n    }\n\ncleanup:\n    mbedtls_ecp_group_free( &grp );\n    mbedtls_ecp_point_free( &G );\n\n    return( ret );\n}\n\n/*\n * Compute R = +/- X * S mod N, taking care not to leak S\n */\nstatic int ecjpake_mul_secret( mbedtls_mpi *R, int sign,\n                               const mbedtls_mpi *X,\n                               const mbedtls_mpi *S,\n                               const mbedtls_mpi *N,\n                               int (*f_rng)(void *, unsigned char *, size_t),\n                               void *p_rng )\n{\n    int ret;\n    mbedtls_mpi b; /* Blinding value, then s + N * blinding */\n\n    mbedtls_mpi_init( &b );\n\n    /* b = s + rnd-128-bit * N */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &b, 16, f_rng, p_rng ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &b, &b, N ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &b, &b, S ) );\n\n    /* R = sign * X * b mod N */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( R, X, &b ) );\n    R->s *= sign;\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( R, R, N ) );\n\ncleanup:\n    mbedtls_mpi_free( &b );\n\n    return( ret );\n}\n\n/*\n * Generate and write the second round message (S: 7.4.2.5, C: 7.4.2.6)\n */\nint mbedtls_ecjpake_write_round_two( mbedtls_ecjpake_context *ctx,\n                            unsigned char *buf, size_t len, size_t *olen,\n                            int (*f_rng)(void *, unsigned char *, size_t),\n                            void *p_rng )\n{\n    int ret;\n    mbedtls_ecp_point G;    /* C: GA, S: GB */\n    mbedtls_ecp_point Xm;   /* C: Xc, S: Xs */\n    mbedtls_mpi xm;         /* C: xc, S: xs */\n    unsigned char *p = buf;\n    const unsigned char *end = buf + len;\n    size_t ec_len;\n\n    mbedtls_ecp_point_init( &G );\n    mbedtls_ecp_point_init( &Xm );\n    mbedtls_mpi_init( &xm );\n\n    /*\n     * First generate private/public key pair (S: 7.4.2.5.1, C: 7.4.2.6.1)\n     *\n     * Client:  GA = X1  + X3  + X4  | xs = x2  * s | Xc = xc * GA\n     * Server:  GB = X3  + X1  + X2  | xs = x4  * s | Xs = xs * GB\n     * Unified: G  = Xm1 + Xp1 + Xp2 | xm = xm2 * s | Xm = xm * G\n     */\n    MBEDTLS_MPI_CHK( ecjpake_ecp_add3( &ctx->grp, &G,\n                                       &ctx->Xp1, &ctx->Xp2, &ctx->Xm1 ) );\n    MBEDTLS_MPI_CHK( ecjpake_mul_secret( &xm, 1, &ctx->xm2, &ctx->s,\n                                         &ctx->grp.N, f_rng, p_rng ) );\n    MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &ctx->grp, &Xm, &xm, &G, f_rng, p_rng ) );\n\n    /*\n     * Now write things out\n     *\n     * struct {\n     *     ECParameters curve_params;   // only server writing its message\n     *     ECJPAKEKeyKP ecjpake_key_kp;\n     * } Client/ServerECJPAKEParams;\n     */\n    if( ctx->role == MBEDTLS_ECJPAKE_SERVER )\n    {\n        if( end < p )\n        {\n            ret = MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;\n            goto cleanup;\n        }\n        MBEDTLS_MPI_CHK( mbedtls_ecp_tls_write_group( &ctx->grp, &ec_len,\n                                                      p, end - p ) );\n        p += ec_len;\n    }\n\n    if( end < p )\n    {\n        ret = MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;\n        goto cleanup;\n    }\n    MBEDTLS_MPI_CHK( mbedtls_ecp_tls_write_point( &ctx->grp, &Xm,\n                     ctx->point_format, &ec_len, p, end - p ) );\n    p += ec_len;\n\n    MBEDTLS_MPI_CHK( ecjpake_zkp_write( ctx->md_info, &ctx->grp,\n                                        ctx->point_format,\n                                        &G, &xm, &Xm, ID_MINE,\n                                        &p, end, f_rng, p_rng ) );\n\n    *olen = p - buf;\n\ncleanup:\n    mbedtls_ecp_point_free( &G );\n    mbedtls_ecp_point_free( &Xm );\n    mbedtls_mpi_free( &xm );\n\n    return( ret );\n}\n\n/*\n * Derive PMS (7.4.2.7 / 7.4.2.8)\n */\nint mbedtls_ecjpake_derive_secret( mbedtls_ecjpake_context *ctx,\n                            unsigned char *buf, size_t len, size_t *olen,\n                            int (*f_rng)(void *, unsigned char *, size_t),\n                            void *p_rng )\n{\n    int ret;\n    mbedtls_ecp_point K;\n    mbedtls_mpi m_xm2_s, one;\n    unsigned char kx[MBEDTLS_ECP_MAX_BYTES];\n    size_t x_bytes;\n\n    *olen = mbedtls_md_get_size( ctx->md_info );\n    if( len < *olen )\n        return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );\n\n    mbedtls_ecp_point_init( &K );\n    mbedtls_mpi_init( &m_xm2_s );\n    mbedtls_mpi_init( &one );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &one, 1 ) );\n\n    /*\n     * Client:  K = ( Xs - X4  * x2  * s ) * x2\n     * Server:  K = ( Xc - X2  * x4  * s ) * x4\n     * Unified: K = ( Xp - Xp2 * xm2 * s ) * xm2\n     */\n    MBEDTLS_MPI_CHK( ecjpake_mul_secret( &m_xm2_s, -1, &ctx->xm2, &ctx->s,\n                                         &ctx->grp.N, f_rng, p_rng ) );\n    MBEDTLS_MPI_CHK( mbedtls_ecp_muladd( &ctx->grp, &K,\n                                         &one, &ctx->Xp,\n                                         &m_xm2_s, &ctx->Xp2 ) );\n    MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &ctx->grp, &K, &ctx->xm2, &K,\n                                      f_rng, p_rng ) );\n\n    /* PMS = SHA-256( K.X ) */\n    x_bytes = ( ctx->grp.pbits + 7 ) / 8;\n    MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &K.X, kx, x_bytes ) );\n    MBEDTLS_MPI_CHK( mbedtls_md( ctx->md_info, kx, x_bytes, buf ) );\n\ncleanup:\n    mbedtls_ecp_point_free( &K );\n    mbedtls_mpi_free( &m_xm2_s );\n    mbedtls_mpi_free( &one );\n\n    return( ret );\n}\n\n#undef ID_MINE\n#undef ID_PEER\n\n#endif /* ! MBEDTLS_ECJPAKE_ALT */\n\n#if defined(MBEDTLS_SELF_TEST)\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf     printf\n#endif\n\n#if !defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \\\n    !defined(MBEDTLS_SHA256_C)\nint mbedtls_ecjpake_self_test( int verbose )\n{\n    (void) verbose;\n    return( 0 );\n}\n#else\n\nstatic const unsigned char ecjpake_test_password[] = {\n    0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x6a, 0x70, 0x61, 0x6b, 0x65, 0x74,\n    0x65, 0x73, 0x74\n};\n\nstatic const unsigned char ecjpake_test_x1[] = {\n    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,\n    0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,\n    0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x21\n};\n\nstatic const unsigned char ecjpake_test_x2[] = {\n    0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c,\n    0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,\n    0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x81\n};\n\nstatic const unsigned char ecjpake_test_x3[] = {\n    0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c,\n    0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,\n    0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x81\n};\n\nstatic const unsigned char ecjpake_test_x4[] = {\n    0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc,\n    0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8,\n    0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe1\n};\n\nstatic const unsigned char ecjpake_test_cli_one[] = {\n    0x41, 0x04, 0xac, 0xcf, 0x01, 0x06, 0xef, 0x85, 0x8f, 0xa2, 0xd9, 0x19,\n    0x33, 0x13, 0x46, 0x80, 0x5a, 0x78, 0xb5, 0x8b, 0xba, 0xd0, 0xb8, 0x44,\n    0xe5, 0xc7, 0x89, 0x28, 0x79, 0x14, 0x61, 0x87, 0xdd, 0x26, 0x66, 0xad,\n    0xa7, 0x81, 0xbb, 0x7f, 0x11, 0x13, 0x72, 0x25, 0x1a, 0x89, 0x10, 0x62,\n    0x1f, 0x63, 0x4d, 0xf1, 0x28, 0xac, 0x48, 0xe3, 0x81, 0xfd, 0x6e, 0xf9,\n    0x06, 0x07, 0x31, 0xf6, 0x94, 0xa4, 0x41, 0x04, 0x1d, 0xd0, 0xbd, 0x5d,\n    0x45, 0x66, 0xc9, 0xbe, 0xd9, 0xce, 0x7d, 0xe7, 0x01, 0xb5, 0xe8, 0x2e,\n    0x08, 0xe8, 0x4b, 0x73, 0x04, 0x66, 0x01, 0x8a, 0xb9, 0x03, 0xc7, 0x9e,\n    0xb9, 0x82, 0x17, 0x22, 0x36, 0xc0, 0xc1, 0x72, 0x8a, 0xe4, 0xbf, 0x73,\n    0x61, 0x0d, 0x34, 0xde, 0x44, 0x24, 0x6e, 0xf3, 0xd9, 0xc0, 0x5a, 0x22,\n    0x36, 0xfb, 0x66, 0xa6, 0x58, 0x3d, 0x74, 0x49, 0x30, 0x8b, 0xab, 0xce,\n    0x20, 0x72, 0xfe, 0x16, 0x66, 0x29, 0x92, 0xe9, 0x23, 0x5c, 0x25, 0x00,\n    0x2f, 0x11, 0xb1, 0x50, 0x87, 0xb8, 0x27, 0x38, 0xe0, 0x3c, 0x94, 0x5b,\n    0xf7, 0xa2, 0x99, 0x5d, 0xda, 0x1e, 0x98, 0x34, 0x58, 0x41, 0x04, 0x7e,\n    0xa6, 0xe3, 0xa4, 0x48, 0x70, 0x37, 0xa9, 0xe0, 0xdb, 0xd7, 0x92, 0x62,\n    0xb2, 0xcc, 0x27, 0x3e, 0x77, 0x99, 0x30, 0xfc, 0x18, 0x40, 0x9a, 0xc5,\n    0x36, 0x1c, 0x5f, 0xe6, 0x69, 0xd7, 0x02, 0xe1, 0x47, 0x79, 0x0a, 0xeb,\n    0x4c, 0xe7, 0xfd, 0x65, 0x75, 0xab, 0x0f, 0x6c, 0x7f, 0xd1, 0xc3, 0x35,\n    0x93, 0x9a, 0xa8, 0x63, 0xba, 0x37, 0xec, 0x91, 0xb7, 0xe3, 0x2b, 0xb0,\n    0x13, 0xbb, 0x2b, 0x41, 0x04, 0xa4, 0x95, 0x58, 0xd3, 0x2e, 0xd1, 0xeb,\n    0xfc, 0x18, 0x16, 0xaf, 0x4f, 0xf0, 0x9b, 0x55, 0xfc, 0xb4, 0xca, 0x47,\n    0xb2, 0xa0, 0x2d, 0x1e, 0x7c, 0xaf, 0x11, 0x79, 0xea, 0x3f, 0xe1, 0x39,\n    0x5b, 0x22, 0xb8, 0x61, 0x96, 0x40, 0x16, 0xfa, 0xba, 0xf7, 0x2c, 0x97,\n    0x56, 0x95, 0xd9, 0x3d, 0x4d, 0xf0, 0xe5, 0x19, 0x7f, 0xe9, 0xf0, 0x40,\n    0x63, 0x4e, 0xd5, 0x97, 0x64, 0x93, 0x77, 0x87, 0xbe, 0x20, 0xbc, 0x4d,\n    0xee, 0xbb, 0xf9, 0xb8, 0xd6, 0x0a, 0x33, 0x5f, 0x04, 0x6c, 0xa3, 0xaa,\n    0x94, 0x1e, 0x45, 0x86, 0x4c, 0x7c, 0xad, 0xef, 0x9c, 0xf7, 0x5b, 0x3d,\n    0x8b, 0x01, 0x0e, 0x44, 0x3e, 0xf0\n};\n\nstatic const unsigned char ecjpake_test_srv_one[] = {\n    0x41, 0x04, 0x7e, 0xa6, 0xe3, 0xa4, 0x48, 0x70, 0x37, 0xa9, 0xe0, 0xdb,\n    0xd7, 0x92, 0x62, 0xb2, 0xcc, 0x27, 0x3e, 0x77, 0x99, 0x30, 0xfc, 0x18,\n    0x40, 0x9a, 0xc5, 0x36, 0x1c, 0x5f, 0xe6, 0x69, 0xd7, 0x02, 0xe1, 0x47,\n    0x79, 0x0a, 0xeb, 0x4c, 0xe7, 0xfd, 0x65, 0x75, 0xab, 0x0f, 0x6c, 0x7f,\n    0xd1, 0xc3, 0x35, 0x93, 0x9a, 0xa8, 0x63, 0xba, 0x37, 0xec, 0x91, 0xb7,\n    0xe3, 0x2b, 0xb0, 0x13, 0xbb, 0x2b, 0x41, 0x04, 0x09, 0xf8, 0x5b, 0x3d,\n    0x20, 0xeb, 0xd7, 0x88, 0x5c, 0xe4, 0x64, 0xc0, 0x8d, 0x05, 0x6d, 0x64,\n    0x28, 0xfe, 0x4d, 0xd9, 0x28, 0x7a, 0xa3, 0x65, 0xf1, 0x31, 0xf4, 0x36,\n    0x0f, 0xf3, 0x86, 0xd8, 0x46, 0x89, 0x8b, 0xc4, 0xb4, 0x15, 0x83, 0xc2,\n    0xa5, 0x19, 0x7f, 0x65, 0xd7, 0x87, 0x42, 0x74, 0x6c, 0x12, 0xa5, 0xec,\n    0x0a, 0x4f, 0xfe, 0x2f, 0x27, 0x0a, 0x75, 0x0a, 0x1d, 0x8f, 0xb5, 0x16,\n    0x20, 0x93, 0x4d, 0x74, 0xeb, 0x43, 0xe5, 0x4d, 0xf4, 0x24, 0xfd, 0x96,\n    0x30, 0x6c, 0x01, 0x17, 0xbf, 0x13, 0x1a, 0xfa, 0xbf, 0x90, 0xa9, 0xd3,\n    0x3d, 0x11, 0x98, 0xd9, 0x05, 0x19, 0x37, 0x35, 0x14, 0x41, 0x04, 0x19,\n    0x0a, 0x07, 0x70, 0x0f, 0xfa, 0x4b, 0xe6, 0xae, 0x1d, 0x79, 0xee, 0x0f,\n    0x06, 0xae, 0xb5, 0x44, 0xcd, 0x5a, 0xdd, 0xaa, 0xbe, 0xdf, 0x70, 0xf8,\n    0x62, 0x33, 0x21, 0x33, 0x2c, 0x54, 0xf3, 0x55, 0xf0, 0xfb, 0xfe, 0xc7,\n    0x83, 0xed, 0x35, 0x9e, 0x5d, 0x0b, 0xf7, 0x37, 0x7a, 0x0f, 0xc4, 0xea,\n    0x7a, 0xce, 0x47, 0x3c, 0x9c, 0x11, 0x2b, 0x41, 0xcc, 0xd4, 0x1a, 0xc5,\n    0x6a, 0x56, 0x12, 0x41, 0x04, 0x36, 0x0a, 0x1c, 0xea, 0x33, 0xfc, 0xe6,\n    0x41, 0x15, 0x64, 0x58, 0xe0, 0xa4, 0xea, 0xc2, 0x19, 0xe9, 0x68, 0x31,\n    0xe6, 0xae, 0xbc, 0x88, 0xb3, 0xf3, 0x75, 0x2f, 0x93, 0xa0, 0x28, 0x1d,\n    0x1b, 0xf1, 0xfb, 0x10, 0x60, 0x51, 0xdb, 0x96, 0x94, 0xa8, 0xd6, 0xe8,\n    0x62, 0xa5, 0xef, 0x13, 0x24, 0xa3, 0xd9, 0xe2, 0x78, 0x94, 0xf1, 0xee,\n    0x4f, 0x7c, 0x59, 0x19, 0x99, 0x65, 0xa8, 0xdd, 0x4a, 0x20, 0x91, 0x84,\n    0x7d, 0x2d, 0x22, 0xdf, 0x3e, 0xe5, 0x5f, 0xaa, 0x2a, 0x3f, 0xb3, 0x3f,\n    0xd2, 0xd1, 0xe0, 0x55, 0xa0, 0x7a, 0x7c, 0x61, 0xec, 0xfb, 0x8d, 0x80,\n    0xec, 0x00, 0xc2, 0xc9, 0xeb, 0x12\n};\n\nstatic const unsigned char ecjpake_test_srv_two[] = {\n    0x03, 0x00, 0x17, 0x41, 0x04, 0x0f, 0xb2, 0x2b, 0x1d, 0x5d, 0x11, 0x23,\n    0xe0, 0xef, 0x9f, 0xeb, 0x9d, 0x8a, 0x2e, 0x59, 0x0a, 0x1f, 0x4d, 0x7c,\n    0xed, 0x2c, 0x2b, 0x06, 0x58, 0x6e, 0x8f, 0x2a, 0x16, 0xd4, 0xeb, 0x2f,\n    0xda, 0x43, 0x28, 0xa2, 0x0b, 0x07, 0xd8, 0xfd, 0x66, 0x76, 0x54, 0xca,\n    0x18, 0xc5, 0x4e, 0x32, 0xa3, 0x33, 0xa0, 0x84, 0x54, 0x51, 0xe9, 0x26,\n    0xee, 0x88, 0x04, 0xfd, 0x7a, 0xf0, 0xaa, 0xa7, 0xa6, 0x41, 0x04, 0x55,\n    0x16, 0xea, 0x3e, 0x54, 0xa0, 0xd5, 0xd8, 0xb2, 0xce, 0x78, 0x6b, 0x38,\n    0xd3, 0x83, 0x37, 0x00, 0x29, 0xa5, 0xdb, 0xe4, 0x45, 0x9c, 0x9d, 0xd6,\n    0x01, 0xb4, 0x08, 0xa2, 0x4a, 0xe6, 0x46, 0x5c, 0x8a, 0xc9, 0x05, 0xb9,\n    0xeb, 0x03, 0xb5, 0xd3, 0x69, 0x1c, 0x13, 0x9e, 0xf8, 0x3f, 0x1c, 0xd4,\n    0x20, 0x0f, 0x6c, 0x9c, 0xd4, 0xec, 0x39, 0x22, 0x18, 0xa5, 0x9e, 0xd2,\n    0x43, 0xd3, 0xc8, 0x20, 0xff, 0x72, 0x4a, 0x9a, 0x70, 0xb8, 0x8c, 0xb8,\n    0x6f, 0x20, 0xb4, 0x34, 0xc6, 0x86, 0x5a, 0xa1, 0xcd, 0x79, 0x06, 0xdd,\n    0x7c, 0x9b, 0xce, 0x35, 0x25, 0xf5, 0x08, 0x27, 0x6f, 0x26, 0x83, 0x6c\n};\n\nstatic const unsigned char ecjpake_test_cli_two[] = {\n    0x41, 0x04, 0x69, 0xd5, 0x4e, 0xe8, 0x5e, 0x90, 0xce, 0x3f, 0x12, 0x46,\n    0x74, 0x2d, 0xe5, 0x07, 0xe9, 0x39, 0xe8, 0x1d, 0x1d, 0xc1, 0xc5, 0xcb,\n    0x98, 0x8b, 0x58, 0xc3, 0x10, 0xc9, 0xfd, 0xd9, 0x52, 0x4d, 0x93, 0x72,\n    0x0b, 0x45, 0x54, 0x1c, 0x83, 0xee, 0x88, 0x41, 0x19, 0x1d, 0xa7, 0xce,\n    0xd8, 0x6e, 0x33, 0x12, 0xd4, 0x36, 0x23, 0xc1, 0xd6, 0x3e, 0x74, 0x98,\n    0x9a, 0xba, 0x4a, 0xff, 0xd1, 0xee, 0x41, 0x04, 0x07, 0x7e, 0x8c, 0x31,\n    0xe2, 0x0e, 0x6b, 0xed, 0xb7, 0x60, 0xc1, 0x35, 0x93, 0xe6, 0x9f, 0x15,\n    0xbe, 0x85, 0xc2, 0x7d, 0x68, 0xcd, 0x09, 0xcc, 0xb8, 0xc4, 0x18, 0x36,\n    0x08, 0x91, 0x7c, 0x5c, 0x3d, 0x40, 0x9f, 0xac, 0x39, 0xfe, 0xfe, 0xe8,\n    0x2f, 0x72, 0x92, 0xd3, 0x6f, 0x0d, 0x23, 0xe0, 0x55, 0x91, 0x3f, 0x45,\n    0xa5, 0x2b, 0x85, 0xdd, 0x8a, 0x20, 0x52, 0xe9, 0xe1, 0x29, 0xbb, 0x4d,\n    0x20, 0x0f, 0x01, 0x1f, 0x19, 0x48, 0x35, 0x35, 0xa6, 0xe8, 0x9a, 0x58,\n    0x0c, 0x9b, 0x00, 0x03, 0xba, 0xf2, 0x14, 0x62, 0xec, 0xe9, 0x1a, 0x82,\n    0xcc, 0x38, 0xdb, 0xdc, 0xae, 0x60, 0xd9, 0xc5, 0x4c\n};\n\nstatic const unsigned char ecjpake_test_pms[] = {\n    0xf3, 0xd4, 0x7f, 0x59, 0x98, 0x44, 0xdb, 0x92, 0xa5, 0x69, 0xbb, 0xe7,\n    0x98, 0x1e, 0x39, 0xd9, 0x31, 0xfd, 0x74, 0x3b, 0xf2, 0x2e, 0x98, 0xf9,\n    0xb4, 0x38, 0xf7, 0x19, 0xd3, 0xc4, 0xf3, 0x51\n};\n\n/* Load my private keys and generate the correponding public keys */\nstatic int ecjpake_test_load( mbedtls_ecjpake_context *ctx,\n                              const unsigned char *xm1, size_t len1,\n                              const unsigned char *xm2, size_t len2 )\n{\n    int ret;\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->xm1, xm1, len1 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->xm2, xm2, len2 ) );\n    MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &ctx->grp, &ctx->Xm1, &ctx->xm1,\n                                      &ctx->grp.G, NULL, NULL ) );\n    MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &ctx->grp, &ctx->Xm2, &ctx->xm2,\n                                      &ctx->grp.G, NULL, NULL ) );\n\ncleanup:\n    return( ret );\n}\n\n/* For tests we don't need a secure RNG;\n * use the LGC from Numerical Recipes for simplicity */\nstatic int ecjpake_lgc( void *p, unsigned char *out, size_t len )\n{\n    static uint32_t x = 42;\n    (void) p;\n\n    while( len > 0 )\n    {\n        size_t use_len = len > 4 ? 4 : len;\n        x = 1664525 * x + 1013904223;\n        memcpy( out, &x, use_len );\n        out += use_len;\n        len -= use_len;\n    }\n\n    return( 0 );\n}\n\n#define TEST_ASSERT( x )    \\\n    do {                    \\\n        if( x )             \\\n            ret = 0;        \\\n        else                \\\n        {                   \\\n            ret = 1;        \\\n            goto cleanup;   \\\n        }                   \\\n    } while( 0 )\n\n/*\n * Checkup routine\n */\nint mbedtls_ecjpake_self_test( int verbose )\n{\n    int ret;\n    mbedtls_ecjpake_context cli;\n    mbedtls_ecjpake_context srv;\n    unsigned char buf[512], pms[32];\n    size_t len, pmslen;\n\n    mbedtls_ecjpake_init( &cli );\n    mbedtls_ecjpake_init( &srv );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  ECJPAKE test #0 (setup): \" );\n\n    TEST_ASSERT( mbedtls_ecjpake_setup( &cli, MBEDTLS_ECJPAKE_CLIENT,\n                    MBEDTLS_MD_SHA256, MBEDTLS_ECP_DP_SECP256R1,\n                    ecjpake_test_password,\n            sizeof( ecjpake_test_password ) ) == 0 );\n\n    TEST_ASSERT( mbedtls_ecjpake_setup( &srv, MBEDTLS_ECJPAKE_SERVER,\n                    MBEDTLS_MD_SHA256, MBEDTLS_ECP_DP_SECP256R1,\n                    ecjpake_test_password,\n            sizeof( ecjpake_test_password ) ) == 0 );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  ECJPAKE test #1 (random handshake): \" );\n\n    TEST_ASSERT( mbedtls_ecjpake_write_round_one( &cli,\n                 buf, sizeof( buf ), &len, ecjpake_lgc, NULL ) == 0 );\n\n    TEST_ASSERT( mbedtls_ecjpake_read_round_one( &srv, buf, len ) == 0 );\n\n    TEST_ASSERT( mbedtls_ecjpake_write_round_one( &srv,\n                 buf, sizeof( buf ), &len, ecjpake_lgc, NULL ) == 0 );\n\n    TEST_ASSERT( mbedtls_ecjpake_read_round_one( &cli, buf, len ) == 0 );\n\n    TEST_ASSERT( mbedtls_ecjpake_write_round_two( &srv,\n                 buf, sizeof( buf ), &len, ecjpake_lgc, NULL ) == 0 );\n\n    TEST_ASSERT( mbedtls_ecjpake_read_round_two( &cli, buf, len ) == 0 );\n\n    TEST_ASSERT( mbedtls_ecjpake_derive_secret( &cli,\n                 pms, sizeof( pms ), &pmslen, ecjpake_lgc, NULL ) == 0 );\n\n    TEST_ASSERT( mbedtls_ecjpake_write_round_two( &cli,\n                 buf, sizeof( buf ), &len, ecjpake_lgc, NULL ) == 0 );\n\n    TEST_ASSERT( mbedtls_ecjpake_read_round_two( &srv, buf, len ) == 0 );\n\n    TEST_ASSERT( mbedtls_ecjpake_derive_secret( &srv,\n                 buf, sizeof( buf ), &len, ecjpake_lgc, NULL ) == 0 );\n\n    TEST_ASSERT( len == pmslen );\n    TEST_ASSERT( memcmp( buf, pms, len ) == 0 );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  ECJPAKE test #2 (reference handshake): \" );\n\n    /* Simulate generation of round one */\n    MBEDTLS_MPI_CHK( ecjpake_test_load( &cli,\n                ecjpake_test_x1, sizeof( ecjpake_test_x1 ),\n                ecjpake_test_x2, sizeof( ecjpake_test_x2 ) ) );\n\n    MBEDTLS_MPI_CHK( ecjpake_test_load( &srv,\n                ecjpake_test_x3, sizeof( ecjpake_test_x3 ),\n                ecjpake_test_x4, sizeof( ecjpake_test_x4 ) ) );\n\n    /* Read round one */\n    TEST_ASSERT( mbedtls_ecjpake_read_round_one( &srv,\n                                    ecjpake_test_cli_one,\n                            sizeof( ecjpake_test_cli_one ) ) == 0 );\n\n    TEST_ASSERT( mbedtls_ecjpake_read_round_one( &cli,\n                                    ecjpake_test_srv_one,\n                            sizeof( ecjpake_test_srv_one ) ) == 0 );\n\n    /* Skip generation of round two, read round two */\n    TEST_ASSERT( mbedtls_ecjpake_read_round_two( &cli,\n                                    ecjpake_test_srv_two,\n                            sizeof( ecjpake_test_srv_two ) ) == 0 );\n\n    TEST_ASSERT( mbedtls_ecjpake_read_round_two( &srv,\n                                    ecjpake_test_cli_two,\n                            sizeof( ecjpake_test_cli_two ) ) == 0 );\n\n    /* Server derives PMS */\n    TEST_ASSERT( mbedtls_ecjpake_derive_secret( &srv,\n                 buf, sizeof( buf ), &len, ecjpake_lgc, NULL ) == 0 );\n\n    TEST_ASSERT( len == sizeof( ecjpake_test_pms ) );\n    TEST_ASSERT( memcmp( buf, ecjpake_test_pms, len ) == 0 );\n\n    memset( buf, 0, len ); /* Avoid interferences with next step */\n\n    /* Client derives PMS */\n    TEST_ASSERT( mbedtls_ecjpake_derive_secret( &cli,\n                 buf, sizeof( buf ), &len, ecjpake_lgc, NULL ) == 0 );\n\n    TEST_ASSERT( len == sizeof( ecjpake_test_pms ) );\n    TEST_ASSERT( memcmp( buf, ecjpake_test_pms, len ) == 0 );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\ncleanup:\n    mbedtls_ecjpake_free( &cli );\n    mbedtls_ecjpake_free( &srv );\n\n    if( ret != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        ret = 1;\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    return( ret );\n}\n\n#undef TEST_ASSERT\n\n#endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED && MBEDTLS_SHA256_C */\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_ECJPAKE_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/ecp.c",
    "content": "/*\n *  Elliptic curves over GF(p): generic functions\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n/*\n * References:\n *\n * SEC1 http://www.secg.org/index.php?action=secg,docs_secg\n * GECC = Guide to Elliptic Curve Cryptography - Hankerson, Menezes, Vanstone\n * FIPS 186-3 http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf\n * RFC 4492 for the related TLS structures and constants\n * RFC 7748 for the Curve448 and Curve25519 curve definitions\n *\n * [Curve25519] http://cr.yp.to/ecdh/curve25519-20060209.pdf\n *\n * [2] CORON, Jean-S'ebastien. Resistance against differential power analysis\n *     for elliptic curve cryptosystems. In : Cryptographic Hardware and\n *     Embedded Systems. Springer Berlin Heidelberg, 1999. p. 292-302.\n *     <http://link.springer.com/chapter/10.1007/3-540-48059-5_25>\n *\n * [3] HEDABOU, Mustapha, PINEL, Pierre, et B'EN'ETEAU, Lucien. A comb method to\n *     render ECC resistant against Side Channel Attacks. IACR Cryptology\n *     ePrint Archive, 2004, vol. 2004, p. 342.\n *     <http://eprint.iacr.org/2004/342.pdf>\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_ECP_C)\n\n#include \"mbedtls/ecp.h\"\n#include \"mbedtls/threading.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if !defined(MBEDTLS_ECP_ALT)\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#include <stdio.h>\n#define mbedtls_printf     printf\n#define mbedtls_calloc    calloc\n#define mbedtls_free       free\n#endif\n\n#include \"mbedtls/ecp_internal.h\"\n\n#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \\\n    !defined(inline) && !defined(__cplusplus)\n#define inline __inline\n#endif\n\n#if defined(MBEDTLS_SELF_TEST)\n/*\n * Counts of point addition and doubling, and field multiplications.\n * Used to test resistance of point multiplication to simple timing attacks.\n */\nstatic unsigned long add_count, dbl_count, mul_count;\n#endif\n\n#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) ||   \\\n    defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) ||   \\\n    defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) ||   \\\n    defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) ||   \\\n    defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) ||   \\\n    defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)   ||   \\\n    defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)   ||   \\\n    defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)   ||   \\\n    defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) ||   \\\n    defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) ||   \\\n    defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)\n#define ECP_SHORTWEIERSTRASS\n#endif\n\n#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) || \\\n    defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)\n#define ECP_MONTGOMERY\n#endif\n\n/*\n * Curve types: internal for now, might be exposed later\n */\ntypedef enum\n{\n    ECP_TYPE_NONE = 0,\n    ECP_TYPE_SHORT_WEIERSTRASS,    /* y^2 = x^3 + a x + b      */\n    ECP_TYPE_MONTGOMERY,           /* y^2 = x^3 + a x^2 + x    */\n} ecp_curve_type;\n\n/*\n * List of supported curves:\n *  - internal ID\n *  - TLS NamedCurve ID (RFC 4492 sec. 5.1.1, RFC 7071 sec. 2)\n *  - size in bits\n *  - readable name\n *\n * Curves are listed in order: largest curves first, and for a given size,\n * fastest curves first. This provides the default order for the SSL module.\n *\n * Reminder: update profiles in x509_crt.c when adding a new curves!\n */\nstatic const mbedtls_ecp_curve_info ecp_supported_curves[] =\n{\n#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)\n    { MBEDTLS_ECP_DP_SECP521R1,    25,     521,    \"secp521r1\"         },\n#endif\n#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)\n    { MBEDTLS_ECP_DP_BP512R1,      28,     512,    \"brainpoolP512r1\"   },\n#endif\n#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)\n    { MBEDTLS_ECP_DP_SECP384R1,    24,     384,    \"secp384r1\"         },\n#endif\n#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)\n    { MBEDTLS_ECP_DP_BP384R1,      27,     384,    \"brainpoolP384r1\"   },\n#endif\n#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)\n    { MBEDTLS_ECP_DP_SECP256R1,    23,     256,    \"secp256r1\"         },\n#endif\n#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)\n    { MBEDTLS_ECP_DP_SECP256K1,    22,     256,    \"secp256k1\"         },\n#endif\n#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)\n    { MBEDTLS_ECP_DP_BP256R1,      26,     256,    \"brainpoolP256r1\"   },\n#endif\n#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)\n    { MBEDTLS_ECP_DP_SECP224R1,    21,     224,    \"secp224r1\"         },\n#endif\n#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)\n    { MBEDTLS_ECP_DP_SECP224K1,    20,     224,    \"secp224k1\"         },\n#endif\n#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)\n    { MBEDTLS_ECP_DP_SECP192R1,    19,     192,    \"secp192r1\"         },\n#endif\n#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)\n    { MBEDTLS_ECP_DP_SECP192K1,    18,     192,    \"secp192k1\"         },\n#endif\n    { MBEDTLS_ECP_DP_NONE,          0,     0,      NULL                },\n};\n\n#define ECP_NB_CURVES   sizeof( ecp_supported_curves ) /    \\\n                        sizeof( ecp_supported_curves[0] )\n\nstatic mbedtls_ecp_group_id ecp_supported_grp_id[ECP_NB_CURVES];\n\n/*\n * List of supported curves and associated info\n */\nconst mbedtls_ecp_curve_info *mbedtls_ecp_curve_list( void )\n{\n    return( ecp_supported_curves );\n}\n\n/*\n * List of supported curves, group ID only\n */\nconst mbedtls_ecp_group_id *mbedtls_ecp_grp_id_list( void )\n{\n    static int init_done = 0;\n\n    if( ! init_done )\n    {\n        size_t i = 0;\n        const mbedtls_ecp_curve_info *curve_info;\n\n        for( curve_info = mbedtls_ecp_curve_list();\n             curve_info->grp_id != MBEDTLS_ECP_DP_NONE;\n             curve_info++ )\n        {\n            ecp_supported_grp_id[i++] = curve_info->grp_id;\n        }\n        ecp_supported_grp_id[i] = MBEDTLS_ECP_DP_NONE;\n\n        init_done = 1;\n    }\n\n    return( ecp_supported_grp_id );\n}\n\n/*\n * Get the curve info for the internal identifier\n */\nconst mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_grp_id( mbedtls_ecp_group_id grp_id )\n{\n    const mbedtls_ecp_curve_info *curve_info;\n\n    for( curve_info = mbedtls_ecp_curve_list();\n         curve_info->grp_id != MBEDTLS_ECP_DP_NONE;\n         curve_info++ )\n    {\n        if( curve_info->grp_id == grp_id )\n            return( curve_info );\n    }\n\n    return( NULL );\n}\n\n/*\n * Get the curve info from the TLS identifier\n */\nconst mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_tls_id( uint16_t tls_id )\n{\n    const mbedtls_ecp_curve_info *curve_info;\n\n    for( curve_info = mbedtls_ecp_curve_list();\n         curve_info->grp_id != MBEDTLS_ECP_DP_NONE;\n         curve_info++ )\n    {\n        if( curve_info->tls_id == tls_id )\n            return( curve_info );\n    }\n\n    return( NULL );\n}\n\n/*\n * Get the curve info from the name\n */\nconst mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_name( const char *name )\n{\n    const mbedtls_ecp_curve_info *curve_info;\n\n    for( curve_info = mbedtls_ecp_curve_list();\n         curve_info->grp_id != MBEDTLS_ECP_DP_NONE;\n         curve_info++ )\n    {\n        if( strcmp( curve_info->name, name ) == 0 )\n            return( curve_info );\n    }\n\n    return( NULL );\n}\n\n/*\n * Get the type of a curve\n */\nstatic inline ecp_curve_type ecp_get_type( const mbedtls_ecp_group *grp )\n{\n    if( grp->G.X.p == NULL )\n        return( ECP_TYPE_NONE );\n\n    if( grp->G.Y.p == NULL )\n        return( ECP_TYPE_MONTGOMERY );\n    else\n        return( ECP_TYPE_SHORT_WEIERSTRASS );\n}\n\n/*\n * Initialize (the components of) a point\n */\nvoid mbedtls_ecp_point_init( mbedtls_ecp_point *pt )\n{\n    if( pt == NULL )\n        return;\n\n    mbedtls_mpi_init( &pt->X );\n    mbedtls_mpi_init( &pt->Y );\n    mbedtls_mpi_init( &pt->Z );\n}\n\n/*\n * Initialize (the components of) a group\n */\nvoid mbedtls_ecp_group_init( mbedtls_ecp_group *grp )\n{\n    if( grp == NULL )\n        return;\n\n    memset( grp, 0, sizeof( mbedtls_ecp_group ) );\n}\n\n/*\n * Initialize (the components of) a key pair\n */\nvoid mbedtls_ecp_keypair_init( mbedtls_ecp_keypair *key )\n{\n    if( key == NULL )\n        return;\n\n    mbedtls_ecp_group_init( &key->grp );\n    mbedtls_mpi_init( &key->d );\n    mbedtls_ecp_point_init( &key->Q );\n}\n\n/*\n * Unallocate (the components of) a point\n */\nvoid mbedtls_ecp_point_free( mbedtls_ecp_point *pt )\n{\n    if( pt == NULL )\n        return;\n\n    mbedtls_mpi_free( &( pt->X ) );\n    mbedtls_mpi_free( &( pt->Y ) );\n    mbedtls_mpi_free( &( pt->Z ) );\n}\n\n/*\n * Unallocate (the components of) a group\n */\nvoid mbedtls_ecp_group_free( mbedtls_ecp_group *grp )\n{\n    size_t i;\n\n    if( grp == NULL )\n        return;\n\n    if( grp->h != 1 )\n    {\n        mbedtls_mpi_free( &grp->P );\n        mbedtls_mpi_free( &grp->A );\n        mbedtls_mpi_free( &grp->B );\n        mbedtls_ecp_point_free( &grp->G );\n        mbedtls_mpi_free( &grp->N );\n    }\n\n    if( grp->T != NULL )\n    {\n        for( i = 0; i < grp->T_size; i++ )\n            mbedtls_ecp_point_free( &grp->T[i] );\n        mbedtls_free( grp->T );\n    }\n\n    mbedtls_platform_zeroize( grp, sizeof( mbedtls_ecp_group ) );\n}\n\n/*\n * Unallocate (the components of) a key pair\n */\nvoid mbedtls_ecp_keypair_free( mbedtls_ecp_keypair *key )\n{\n    if( key == NULL )\n        return;\n\n    mbedtls_ecp_group_free( &key->grp );\n    mbedtls_mpi_free( &key->d );\n    mbedtls_ecp_point_free( &key->Q );\n}\n\n/*\n * Copy the contents of a point\n */\nint mbedtls_ecp_copy( mbedtls_ecp_point *P, const mbedtls_ecp_point *Q )\n{\n    int ret;\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &P->X, &Q->X ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &P->Y, &Q->Y ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &P->Z, &Q->Z ) );\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Copy the contents of a group object\n */\nint mbedtls_ecp_group_copy( mbedtls_ecp_group *dst, const mbedtls_ecp_group *src )\n{\n    return mbedtls_ecp_group_load( dst, src->id );\n}\n\n/*\n * Set point to zero\n */\nint mbedtls_ecp_set_zero( mbedtls_ecp_point *pt )\n{\n    int ret;\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->X , 1 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Y , 1 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Z , 0 ) );\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Tell if a point is zero\n */\nint mbedtls_ecp_is_zero( mbedtls_ecp_point *pt )\n{\n    return( mbedtls_mpi_cmp_int( &pt->Z, 0 ) == 0 );\n}\n\n/*\n * Compare two points lazyly\n */\nint mbedtls_ecp_point_cmp( const mbedtls_ecp_point *P,\n                           const mbedtls_ecp_point *Q )\n{\n    if( mbedtls_mpi_cmp_mpi( &P->X, &Q->X ) == 0 &&\n        mbedtls_mpi_cmp_mpi( &P->Y, &Q->Y ) == 0 &&\n        mbedtls_mpi_cmp_mpi( &P->Z, &Q->Z ) == 0 )\n    {\n        return( 0 );\n    }\n\n    return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n}\n\n/*\n * Import a non-zero point from ASCII strings\n */\nint mbedtls_ecp_point_read_string( mbedtls_ecp_point *P, int radix,\n                           const char *x, const char *y )\n{\n    int ret;\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &P->X, radix, x ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &P->Y, radix, y ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &P->Z, 1 ) );\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Export a point into unsigned binary data (SEC1 2.3.3)\n */\nint mbedtls_ecp_point_write_binary( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *P,\n                            int format, size_t *olen,\n                            unsigned char *buf, size_t buflen )\n{\n    int ret = 0;\n    size_t plen;\n\n    if( format != MBEDTLS_ECP_PF_UNCOMPRESSED &&\n        format != MBEDTLS_ECP_PF_COMPRESSED )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    /*\n     * Common case: P == 0\n     */\n    if( mbedtls_mpi_cmp_int( &P->Z, 0 ) == 0 )\n    {\n        if( buflen < 1 )\n            return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );\n\n        buf[0] = 0x00;\n        *olen = 1;\n\n        return( 0 );\n    }\n\n    plen = mbedtls_mpi_size( &grp->P );\n\n    if( format == MBEDTLS_ECP_PF_UNCOMPRESSED )\n    {\n        *olen = 2 * plen + 1;\n\n        if( buflen < *olen )\n            return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );\n\n        buf[0] = 0x04;\n        MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &P->X, buf + 1, plen ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &P->Y, buf + 1 + plen, plen ) );\n    }\n    else if( format == MBEDTLS_ECP_PF_COMPRESSED )\n    {\n        *olen = plen + 1;\n\n        if( buflen < *olen )\n            return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );\n\n        buf[0] = 0x02 + mbedtls_mpi_get_bit( &P->Y, 0 );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &P->X, buf + 1, plen ) );\n    }\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Import a point from unsigned binary data (SEC1 2.3.4)\n */\nint mbedtls_ecp_point_read_binary( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt,\n                           const unsigned char *buf, size_t ilen )\n{\n    int ret;\n    size_t plen;\n\n    if( ilen < 1 )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    if( buf[0] == 0x00 )\n    {\n        if( ilen == 1 )\n            return( mbedtls_ecp_set_zero( pt ) );\n        else\n            return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n    }\n\n    plen = mbedtls_mpi_size( &grp->P );\n\n    if( buf[0] != 0x04 )\n        return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );\n\n    if( ilen != 2 * plen + 1 )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &pt->X, buf + 1, plen ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &pt->Y, buf + 1 + plen, plen ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Z, 1 ) );\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Import a point from a TLS ECPoint record (RFC 4492)\n *      struct {\n *          opaque point <1..2^8-1>;\n *      } ECPoint;\n */\nint mbedtls_ecp_tls_read_point( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt,\n                        const unsigned char **buf, size_t buf_len )\n{\n    unsigned char data_len;\n    const unsigned char *buf_start;\n\n    /*\n     * We must have at least two bytes (1 for length, at least one for data)\n     */\n    if( buf_len < 2 )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    data_len = *(*buf)++;\n    if( data_len < 1 || data_len > buf_len - 1 )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    /*\n     * Save buffer start for read_binary and update buf\n     */\n    buf_start = *buf;\n    *buf += data_len;\n\n    return mbedtls_ecp_point_read_binary( grp, pt, buf_start, data_len );\n}\n\n/*\n * Export a point as a TLS ECPoint record (RFC 4492)\n *      struct {\n *          opaque point <1..2^8-1>;\n *      } ECPoint;\n */\nint mbedtls_ecp_tls_write_point( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt,\n                         int format, size_t *olen,\n                         unsigned char *buf, size_t blen )\n{\n    int ret;\n\n    /*\n     * buffer length must be at least one, for our length byte\n     */\n    if( blen < 1 )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    if( ( ret = mbedtls_ecp_point_write_binary( grp, pt, format,\n                    olen, buf + 1, blen - 1) ) != 0 )\n        return( ret );\n\n    /*\n     * write length to the first byte and update total length\n     */\n    buf[0] = (unsigned char) *olen;\n    ++*olen;\n\n    return( 0 );\n}\n\n/*\n * Set a group from an ECParameters record (RFC 4492)\n */\nint mbedtls_ecp_tls_read_group( mbedtls_ecp_group *grp, const unsigned char **buf, size_t len )\n{\n    uint16_t tls_id;\n    const mbedtls_ecp_curve_info *curve_info;\n\n    /*\n     * We expect at least three bytes (see below)\n     */\n    if( len < 3 )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    /*\n     * First byte is curve_type; only named_curve is handled\n     */\n    if( *(*buf)++ != MBEDTLS_ECP_TLS_NAMED_CURVE )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    /*\n     * Next two bytes are the namedcurve value\n     */\n    tls_id = *(*buf)++;\n    tls_id <<= 8;\n    tls_id |= *(*buf)++;\n\n    if( ( curve_info = mbedtls_ecp_curve_info_from_tls_id( tls_id ) ) == NULL )\n        return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );\n\n    return mbedtls_ecp_group_load( grp, curve_info->grp_id );\n}\n\n/*\n * Write the ECParameters record corresponding to a group (RFC 4492)\n */\nint mbedtls_ecp_tls_write_group( const mbedtls_ecp_group *grp, size_t *olen,\n                         unsigned char *buf, size_t blen )\n{\n    const mbedtls_ecp_curve_info *curve_info;\n\n    if( ( curve_info = mbedtls_ecp_curve_info_from_grp_id( grp->id ) ) == NULL )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    /*\n     * We are going to write 3 bytes (see below)\n     */\n    *olen = 3;\n    if( blen < *olen )\n        return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );\n\n    /*\n     * First byte is curve_type, always named_curve\n     */\n    *buf++ = MBEDTLS_ECP_TLS_NAMED_CURVE;\n\n    /*\n     * Next two bytes are the namedcurve value\n     */\n    buf[0] = curve_info->tls_id >> 8;\n    buf[1] = curve_info->tls_id & 0xFF;\n\n    return( 0 );\n}\n\n/*\n * Wrapper around fast quasi-modp functions, with fall-back to mbedtls_mpi_mod_mpi.\n * See the documentation of struct mbedtls_ecp_group.\n *\n * This function is in the critial loop for mbedtls_ecp_mul, so pay attention to perf.\n */\nstatic int ecp_modp( mbedtls_mpi *N, const mbedtls_ecp_group *grp )\n{\n    int ret;\n\n    if( grp->modp == NULL )\n        return( mbedtls_mpi_mod_mpi( N, N, &grp->P ) );\n\n    /* N->s < 0 is a much faster test, which fails only if N is 0 */\n    if( ( N->s < 0 && mbedtls_mpi_cmp_int( N, 0 ) != 0 ) ||\n        mbedtls_mpi_bitlen( N ) > 2 * grp->pbits )\n    {\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n    }\n\n    MBEDTLS_MPI_CHK( grp->modp( N ) );\n\n    /* N->s < 0 is a much faster test, which fails only if N is 0 */\n    while( N->s < 0 && mbedtls_mpi_cmp_int( N, 0 ) != 0 )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( N, N, &grp->P ) );\n\n    while( mbedtls_mpi_cmp_mpi( N, &grp->P ) >= 0 )\n        /* we known P, N and the result are positive */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( N, N, &grp->P ) );\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Fast mod-p functions expect their argument to be in the 0..p^2 range.\n *\n * In order to guarantee that, we need to ensure that operands of\n * mbedtls_mpi_mul_mpi are in the 0..p range. So, after each operation we will\n * bring the result back to this range.\n *\n * The following macros are shortcuts for doing that.\n */\n\n/*\n * Reduce a mbedtls_mpi mod p in-place, general case, to use after mbedtls_mpi_mul_mpi\n */\n#if defined(MBEDTLS_SELF_TEST)\n#define INC_MUL_COUNT   mul_count++;\n#else\n#define INC_MUL_COUNT\n#endif\n\n#define MOD_MUL( N )    do { MBEDTLS_MPI_CHK( ecp_modp( &N, grp ) ); INC_MUL_COUNT } \\\n                        while( 0 )\n\n/*\n * Reduce a mbedtls_mpi mod p in-place, to use after mbedtls_mpi_sub_mpi\n * N->s < 0 is a very fast test, which fails only if N is 0\n */\n#define MOD_SUB( N )                                \\\n    while( N.s < 0 && mbedtls_mpi_cmp_int( &N, 0 ) != 0 )   \\\n        MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &N, &N, &grp->P ) )\n\n/*\n * Reduce a mbedtls_mpi mod p in-place, to use after mbedtls_mpi_add_mpi and mbedtls_mpi_mul_int.\n * We known P, N and the result are positive, so sub_abs is correct, and\n * a bit faster.\n */\n#define MOD_ADD( N )                                \\\n    while( mbedtls_mpi_cmp_mpi( &N, &grp->P ) >= 0 )        \\\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( &N, &N, &grp->P ) )\n\n#if defined(ECP_SHORTWEIERSTRASS)\n/*\n * For curves in short Weierstrass form, we do all the internal operations in\n * Jacobian coordinates.\n *\n * For multiplication, we'll use a comb method with coutermeasueres against\n * SPA, hence timing attacks.\n */\n\n/*\n * Normalize jacobian coordinates so that Z == 0 || Z == 1  (GECC 3.2.1)\n * Cost: 1N := 1I + 3M + 1S\n */\nstatic int ecp_normalize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt )\n{\n    int ret;\n    mbedtls_mpi Zi, ZZi;\n\n    if( mbedtls_mpi_cmp_int( &pt->Z, 0 ) == 0 )\n        return( 0 );\n\n#if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT)\n    if ( mbedtls_internal_ecp_grp_capable( grp ) )\n    {\n        return mbedtls_internal_ecp_normalize_jac( grp, pt );\n    }\n#endif /* MBEDTLS_ECP_NORMALIZE_JAC_ALT */\n    mbedtls_mpi_init( &Zi ); mbedtls_mpi_init( &ZZi );\n\n    /*\n     * X = X / Z^2  mod p\n     */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &Zi,      &pt->Z,     &grp->P ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ZZi,     &Zi,        &Zi     ) ); MOD_MUL( ZZi );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &pt->X,   &pt->X,     &ZZi    ) ); MOD_MUL( pt->X );\n\n    /*\n     * Y = Y / Z^3  mod p\n     */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &pt->Y,   &pt->Y,     &ZZi    ) ); MOD_MUL( pt->Y );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &pt->Y,   &pt->Y,     &Zi     ) ); MOD_MUL( pt->Y );\n\n    /*\n     * Z = 1\n     */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Z, 1 ) );\n\ncleanup:\n\n    mbedtls_mpi_free( &Zi ); mbedtls_mpi_free( &ZZi );\n\n    return( ret );\n}\n\n/*\n * Normalize jacobian coordinates of an array of (pointers to) points,\n * using Montgomery's trick to perform only one inversion mod P.\n * (See for example Cohen's \"A Course in Computational Algebraic Number\n * Theory\", Algorithm 10.3.4.)\n *\n * Warning: fails (returning an error) if one of the points is zero!\n * This should never happen, see choice of w in ecp_mul_comb().\n *\n * Cost: 1N(t) := 1I + (6t - 3)M + 1S\n */\nstatic int ecp_normalize_jac_many( const mbedtls_ecp_group *grp,\n                                   mbedtls_ecp_point *T[], size_t t_len )\n{\n    int ret;\n    size_t i;\n    mbedtls_mpi *c, u, Zi, ZZi;\n\n    if( t_len < 2 )\n        return( ecp_normalize_jac( grp, *T ) );\n\n#if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT)\n    if ( mbedtls_internal_ecp_grp_capable( grp ) )\n    {\n        return mbedtls_internal_ecp_normalize_jac_many(grp, T, t_len);\n    }\n#endif\n\n    if( ( c = mbedtls_calloc( t_len, sizeof( mbedtls_mpi ) ) ) == NULL )\n        return( MBEDTLS_ERR_ECP_ALLOC_FAILED );\n\n    mbedtls_mpi_init( &u ); mbedtls_mpi_init( &Zi ); mbedtls_mpi_init( &ZZi );\n\n    /*\n     * c[i] = Z_0 * ... * Z_i\n     */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &c[0], &T[0]->Z ) );\n    for( i = 1; i < t_len; i++ )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &c[i], &c[i-1], &T[i]->Z ) );\n        MOD_MUL( c[i] );\n    }\n\n    /*\n     * u = 1 / (Z_0 * ... * Z_n) mod P\n     */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &u, &c[t_len-1], &grp->P ) );\n\n    for( i = t_len - 1; ; i-- )\n    {\n        /*\n         * Zi = 1 / Z_i mod p\n         * u = 1 / (Z_0 * ... * Z_i) mod P\n         */\n        if( i == 0 ) {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Zi, &u ) );\n        }\n        else\n        {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &Zi, &u, &c[i-1]  ) ); MOD_MUL( Zi );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &u,  &u, &T[i]->Z ) ); MOD_MUL( u );\n        }\n\n        /*\n         * proceed as in normalize()\n         */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ZZi,     &Zi,      &Zi  ) ); MOD_MUL( ZZi );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T[i]->X, &T[i]->X, &ZZi ) ); MOD_MUL( T[i]->X );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T[i]->Y, &T[i]->Y, &ZZi ) ); MOD_MUL( T[i]->Y );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T[i]->Y, &T[i]->Y, &Zi  ) ); MOD_MUL( T[i]->Y );\n\n        /*\n         * Post-precessing: reclaim some memory by shrinking coordinates\n         * - not storing Z (always 1)\n         * - shrinking other coordinates, but still keeping the same number of\n         *   limbs as P, as otherwise it will too likely be regrown too fast.\n         */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_shrink( &T[i]->X, grp->P.n ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_shrink( &T[i]->Y, grp->P.n ) );\n        mbedtls_mpi_free( &T[i]->Z );\n\n        if( i == 0 )\n            break;\n    }\n\ncleanup:\n\n    mbedtls_mpi_free( &u ); mbedtls_mpi_free( &Zi ); mbedtls_mpi_free( &ZZi );\n    for( i = 0; i < t_len; i++ )\n        mbedtls_mpi_free( &c[i] );\n    mbedtls_free( c );\n\n    return( ret );\n}\n\n/*\n * Conditional point inversion: Q -> -Q = (Q.X, -Q.Y, Q.Z) without leak.\n * \"inv\" must be 0 (don't invert) or 1 (invert) or the result will be invalid\n */\nstatic int ecp_safe_invert_jac( const mbedtls_ecp_group *grp,\n                            mbedtls_ecp_point *Q,\n                            unsigned char inv )\n{\n    int ret;\n    unsigned char nonzero;\n    mbedtls_mpi mQY;\n\n    mbedtls_mpi_init( &mQY );\n\n    /* Use the fact that -Q.Y mod P = P - Q.Y unless Q.Y == 0 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &mQY, &grp->P, &Q->Y ) );\n    nonzero = mbedtls_mpi_cmp_int( &Q->Y, 0 ) != 0;\n    MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &Q->Y, &mQY, inv & nonzero ) );\n\ncleanup:\n    mbedtls_mpi_free( &mQY );\n\n    return( ret );\n}\n\n/*\n * Point doubling R = 2 P, Jacobian coordinates\n *\n * Based on http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-1998-cmo-2 .\n *\n * We follow the variable naming fairly closely. The formula variations that trade a MUL for a SQR\n * (plus a few ADDs) aren't useful as our bignum implementation doesn't distinguish squaring.\n *\n * Standard optimizations are applied when curve parameter A is one of { 0, -3 }.\n *\n * Cost: 1D := 3M + 4S          (A ==  0)\n *             4M + 4S          (A == -3)\n *             3M + 6S + 1a     otherwise\n */\nstatic int ecp_double_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,\n                           const mbedtls_ecp_point *P )\n{\n    int ret;\n    mbedtls_mpi M, S, T, U;\n\n#if defined(MBEDTLS_SELF_TEST)\n    dbl_count++;\n#endif\n\n#if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT)\n    if ( mbedtls_internal_ecp_grp_capable( grp ) )\n    {\n        return mbedtls_internal_ecp_double_jac( grp, R, P );\n    }\n#endif /* MBEDTLS_ECP_DOUBLE_JAC_ALT */\n\n    mbedtls_mpi_init( &M ); mbedtls_mpi_init( &S ); mbedtls_mpi_init( &T ); mbedtls_mpi_init( &U );\n\n    /* Special case for A = -3 */\n    if( grp->A.p == NULL )\n    {\n        /* M = 3(X + Z^2)(X - Z^2) */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S,  &P->Z,  &P->Z   ) ); MOD_MUL( S );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &T,  &P->X,  &S      ) ); MOD_ADD( T );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U,  &P->X,  &S      ) ); MOD_SUB( U );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S,  &T,     &U      ) ); MOD_MUL( S );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &M,  &S,     3       ) ); MOD_ADD( M );\n    }\n    else\n    {\n        /* M = 3.X^2 */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S,  &P->X,  &P->X   ) ); MOD_MUL( S );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &M,  &S,     3       ) ); MOD_ADD( M );\n\n        /* Optimize away for \"koblitz\" curves with A = 0 */\n        if( mbedtls_mpi_cmp_int( &grp->A, 0 ) != 0 )\n        {\n            /* M += A.Z^4 */\n            MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S,  &P->Z,  &P->Z   ) ); MOD_MUL( S );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T,  &S,     &S      ) ); MOD_MUL( T );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S,  &T,     &grp->A ) ); MOD_MUL( S );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &M,  &M,     &S      ) ); MOD_ADD( M );\n        }\n    }\n\n    /* S = 4.X.Y^2 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T,  &P->Y,  &P->Y   ) ); MOD_MUL( T );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &T,  1               ) ); MOD_ADD( T );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S,  &P->X,  &T      ) ); MOD_MUL( S );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &S,  1               ) ); MOD_ADD( S );\n\n    /* U = 8.Y^4 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &U,  &T,     &T      ) ); MOD_MUL( U );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &U,  1               ) ); MOD_ADD( U );\n\n    /* T = M^2 - 2.S */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T,  &M,     &M      ) ); MOD_MUL( T );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T,  &T,     &S      ) ); MOD_SUB( T );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T,  &T,     &S      ) ); MOD_SUB( T );\n\n    /* S = M(S - T) - U */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &S,  &S,     &T      ) ); MOD_SUB( S );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S,  &S,     &M      ) ); MOD_MUL( S );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &S,  &S,     &U      ) ); MOD_SUB( S );\n\n    /* U = 2.Y.Z */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &U,  &P->Y,  &P->Z   ) ); MOD_MUL( U );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &U,  1               ) ); MOD_ADD( U );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->X, &T ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->Y, &S ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->Z, &U ) );\n\ncleanup:\n    mbedtls_mpi_free( &M ); mbedtls_mpi_free( &S ); mbedtls_mpi_free( &T ); mbedtls_mpi_free( &U );\n\n    return( ret );\n}\n\n/*\n * Addition: R = P + Q, mixed affine-Jacobian coordinates (GECC 3.22)\n *\n * The coordinates of Q must be normalized (= affine),\n * but those of P don't need to. R is not normalized.\n *\n * Special cases: (1) P or Q is zero, (2) R is zero, (3) P == Q.\n * None of these cases can happen as intermediate step in ecp_mul_comb():\n * - at each step, P, Q and R are multiples of the base point, the factor\n *   being less than its order, so none of them is zero;\n * - Q is an odd multiple of the base point, P an even multiple,\n *   due to the choice of precomputed points in the modified comb method.\n * So branches for these cases do not leak secret information.\n *\n * We accept Q->Z being unset (saving memory in tables) as meaning 1.\n *\n * Cost: 1A := 8M + 3S\n */\nstatic int ecp_add_mixed( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,\n                          const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q )\n{\n    int ret;\n    mbedtls_mpi T1, T2, T3, T4, X, Y, Z;\n\n#if defined(MBEDTLS_SELF_TEST)\n    add_count++;\n#endif\n\n#if defined(MBEDTLS_ECP_ADD_MIXED_ALT)\n    if ( mbedtls_internal_ecp_grp_capable( grp ) )\n    {\n        return mbedtls_internal_ecp_add_mixed( grp, R, P, Q );\n    }\n#endif /* MBEDTLS_ECP_ADD_MIXED_ALT */\n\n    /*\n     * Trivial cases: P == 0 or Q == 0 (case 1)\n     */\n    if( mbedtls_mpi_cmp_int( &P->Z, 0 ) == 0 )\n        return( mbedtls_ecp_copy( R, Q ) );\n\n    if( Q->Z.p != NULL && mbedtls_mpi_cmp_int( &Q->Z, 0 ) == 0 )\n        return( mbedtls_ecp_copy( R, P ) );\n\n    /*\n     * Make sure Q coordinates are normalized\n     */\n    if( Q->Z.p != NULL && mbedtls_mpi_cmp_int( &Q->Z, 1 ) != 0 )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    mbedtls_mpi_init( &T1 ); mbedtls_mpi_init( &T2 ); mbedtls_mpi_init( &T3 ); mbedtls_mpi_init( &T4 );\n    mbedtls_mpi_init( &X ); mbedtls_mpi_init( &Y ); mbedtls_mpi_init( &Z );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T1,  &P->Z,  &P->Z ) );  MOD_MUL( T1 );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T2,  &T1,    &P->Z ) );  MOD_MUL( T2 );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T1,  &T1,    &Q->X ) );  MOD_MUL( T1 );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T2,  &T2,    &Q->Y ) );  MOD_MUL( T2 );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T1,  &T1,    &P->X ) );  MOD_SUB( T1 );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T2,  &T2,    &P->Y ) );  MOD_SUB( T2 );\n\n    /* Special cases (2) and (3) */\n    if( mbedtls_mpi_cmp_int( &T1, 0 ) == 0 )\n    {\n        if( mbedtls_mpi_cmp_int( &T2, 0 ) == 0 )\n        {\n            ret = ecp_double_jac( grp, R, P );\n            goto cleanup;\n        }\n        else\n        {\n            ret = mbedtls_ecp_set_zero( R );\n            goto cleanup;\n        }\n    }\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &Z,   &P->Z,  &T1   ) );  MOD_MUL( Z  );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T3,  &T1,    &T1   ) );  MOD_MUL( T3 );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T4,  &T3,    &T1   ) );  MOD_MUL( T4 );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T3,  &T3,    &P->X ) );  MOD_MUL( T3 );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &T1,  &T3,    2     ) );  MOD_ADD( T1 );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &X,   &T2,    &T2   ) );  MOD_MUL( X  );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &X,   &X,     &T1   ) );  MOD_SUB( X  );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &X,   &X,     &T4   ) );  MOD_SUB( X  );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T3,  &T3,    &X    ) );  MOD_SUB( T3 );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T3,  &T3,    &T2   ) );  MOD_MUL( T3 );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T4,  &T4,    &P->Y ) );  MOD_MUL( T4 );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &Y,   &T3,    &T4   ) );  MOD_SUB( Y  );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->X, &X ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->Y, &Y ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->Z, &Z ) );\n\ncleanup:\n\n    mbedtls_mpi_free( &T1 ); mbedtls_mpi_free( &T2 ); mbedtls_mpi_free( &T3 ); mbedtls_mpi_free( &T4 );\n    mbedtls_mpi_free( &X ); mbedtls_mpi_free( &Y ); mbedtls_mpi_free( &Z );\n\n    return( ret );\n}\n\n/*\n * Randomize jacobian coordinates:\n * (X, Y, Z) -> (l^2 X, l^3 Y, l Z) for random l\n * This is sort of the reverse operation of ecp_normalize_jac().\n *\n * This countermeasure was first suggested in [2].\n */\nstatic int ecp_randomize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt,\n                int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    int ret;\n    mbedtls_mpi l, ll;\n    size_t p_size;\n    int count = 0;\n\n#if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT)\n    if ( mbedtls_internal_ecp_grp_capable( grp ) )\n    {\n        return mbedtls_internal_ecp_randomize_jac( grp, pt, f_rng, p_rng );\n    }\n#endif /* MBEDTLS_ECP_RANDOMIZE_JAC_ALT */\n\n    p_size = ( grp->pbits + 7 ) / 8;\n    mbedtls_mpi_init( &l ); mbedtls_mpi_init( &ll );\n\n    /* Generate l such that 1 < l < p */\n    do\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &l, p_size, f_rng, p_rng ) );\n\n        while( mbedtls_mpi_cmp_mpi( &l, &grp->P ) >= 0 )\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &l, 1 ) );\n\n        if( count++ > 10 )\n            return( MBEDTLS_ERR_ECP_RANDOM_FAILED );\n    }\n    while( mbedtls_mpi_cmp_int( &l, 1 ) <= 0 );\n\n    /* Z = l * Z */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &pt->Z,   &pt->Z,     &l  ) ); MOD_MUL( pt->Z );\n\n    /* X = l^2 * X */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ll,      &l,         &l  ) ); MOD_MUL( ll );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &pt->X,   &pt->X,     &ll ) ); MOD_MUL( pt->X );\n\n    /* Y = l^3 * Y */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ll,      &ll,        &l  ) ); MOD_MUL( ll );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &pt->Y,   &pt->Y,     &ll ) ); MOD_MUL( pt->Y );\n\ncleanup:\n    mbedtls_mpi_free( &l ); mbedtls_mpi_free( &ll );\n\n    return( ret );\n}\n\n/*\n * Check and define parameters used by the comb method (see below for details)\n */\n#if MBEDTLS_ECP_WINDOW_SIZE < 2 || MBEDTLS_ECP_WINDOW_SIZE > 7\n#error \"MBEDTLS_ECP_WINDOW_SIZE out of bounds\"\n#endif\n\n/* d = ceil( n / w ) */\n#define COMB_MAX_D      ( MBEDTLS_ECP_MAX_BITS + 1 ) / 2\n\n/* number of precomputed points */\n#define COMB_MAX_PRE    ( 1 << ( MBEDTLS_ECP_WINDOW_SIZE - 1 ) )\n\n/*\n * Compute the representation of m that will be used with our comb method.\n *\n * The basic comb method is described in GECC 3.44 for example. We use a\n * modified version that provides resistance to SPA by avoiding zero\n * digits in the representation as in [3]. We modify the method further by\n * requiring that all K_i be odd, which has the small cost that our\n * representation uses one more K_i, due to carries.\n *\n * Also, for the sake of compactness, only the seven low-order bits of x[i]\n * are used to represent K_i, and the msb of x[i] encodes the the sign (s_i in\n * the paper): it is set if and only if if s_i == -1;\n *\n * Calling conventions:\n * - x is an array of size d + 1\n * - w is the size, ie number of teeth, of the comb, and must be between\n *   2 and 7 (in practice, between 2 and MBEDTLS_ECP_WINDOW_SIZE)\n * - m is the MPI, expected to be odd and such that bitlength(m) <= w * d\n *   (the result will be incorrect if these assumptions are not satisfied)\n */\nstatic void ecp_comb_fixed( unsigned char x[], size_t d,\n                            unsigned char w, const mbedtls_mpi *m )\n{\n    size_t i, j;\n    unsigned char c, cc, adjust;\n\n    memset( x, 0, d+1 );\n\n    /* First get the classical comb values (except for x_d = 0) */\n    for( i = 0; i < d; i++ )\n        for( j = 0; j < w; j++ )\n            x[i] |= mbedtls_mpi_get_bit( m, i + d * j ) << j;\n\n    /* Now make sure x_1 .. x_d are odd */\n    c = 0;\n    for( i = 1; i <= d; i++ )\n    {\n        /* Add carry and update it */\n        cc   = x[i] & c;\n        x[i] = x[i] ^ c;\n        c = cc;\n\n        /* Adjust if needed, avoiding branches */\n        adjust = 1 - ( x[i] & 0x01 );\n        c   |= x[i] & ( x[i-1] * adjust );\n        x[i] = x[i] ^ ( x[i-1] * adjust );\n        x[i-1] |= adjust << 7;\n    }\n}\n\n/*\n * Precompute points for the comb method\n *\n * If i = i_{w-1} ... i_1 is the binary representation of i, then\n * T[i] = i_{w-1} 2^{(w-1)d} P + ... + i_1 2^d P + P\n *\n * T must be able to hold 2^{w - 1} elements\n *\n * Cost: d(w-1) D + (2^{w-1} - 1) A + 1 N(w-1) + 1 N(2^{w-1} - 1)\n */\nstatic int ecp_precompute_comb( const mbedtls_ecp_group *grp,\n                                mbedtls_ecp_point T[], const mbedtls_ecp_point *P,\n                                unsigned char w, size_t d )\n{\n    int ret;\n    unsigned char i, k;\n    size_t j;\n    mbedtls_ecp_point *cur, *TT[COMB_MAX_PRE - 1];\n\n    /*\n     * Set T[0] = P and\n     * T[2^{l-1}] = 2^{dl} P for l = 1 .. w-1 (this is not the final value)\n     */\n    MBEDTLS_MPI_CHK( mbedtls_ecp_copy( &T[0], P ) );\n\n    k = 0;\n    for( i = 1; i < ( 1U << ( w - 1 ) ); i <<= 1 )\n    {\n        cur = T + i;\n        MBEDTLS_MPI_CHK( mbedtls_ecp_copy( cur, T + ( i >> 1 ) ) );\n        for( j = 0; j < d; j++ )\n            MBEDTLS_MPI_CHK( ecp_double_jac( grp, cur, cur ) );\n\n        TT[k++] = cur;\n    }\n\n    MBEDTLS_MPI_CHK( ecp_normalize_jac_many( grp, TT, k ) );\n\n    /*\n     * Compute the remaining ones using the minimal number of additions\n     * Be careful to update T[2^l] only after using it!\n     */\n    k = 0;\n    for( i = 1; i < ( 1U << ( w - 1 ) ); i <<= 1 )\n    {\n        j = i;\n        while( j-- )\n        {\n            MBEDTLS_MPI_CHK( ecp_add_mixed( grp, &T[i + j], &T[j], &T[i] ) );\n            TT[k++] = &T[i + j];\n        }\n    }\n\n    MBEDTLS_MPI_CHK( ecp_normalize_jac_many( grp, TT, k ) );\n\ncleanup:\n\n    return( ret );\n}\n\n/*\n * Select precomputed point: R = sign(i) * T[ abs(i) / 2 ]\n */\nstatic int ecp_select_comb( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,\n                            const mbedtls_ecp_point T[], unsigned char t_len,\n                            unsigned char i )\n{\n    int ret;\n    unsigned char ii, j;\n\n    /* Ignore the \"sign\" bit and scale down */\n    ii =  ( i & 0x7Fu ) >> 1;\n\n    /* Read the whole table to thwart cache-based timing attacks */\n    for( j = 0; j < t_len; j++ )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &R->X, &T[j].X, j == ii ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &R->Y, &T[j].Y, j == ii ) );\n    }\n\n    /* Safely invert result if i is \"negative\" */\n    MBEDTLS_MPI_CHK( ecp_safe_invert_jac( grp, R, i >> 7 ) );\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Core multiplication algorithm for the (modified) comb method.\n * This part is actually common with the basic comb method (GECC 3.44)\n *\n * Cost: d A + d D + 1 R\n */\nstatic int ecp_mul_comb_core( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,\n                              const mbedtls_ecp_point T[], unsigned char t_len,\n                              const unsigned char x[], size_t d,\n                              int (*f_rng)(void *, unsigned char *, size_t),\n                              void *p_rng )\n{\n    int ret;\n    mbedtls_ecp_point Txi;\n    size_t i;\n\n    mbedtls_ecp_point_init( &Txi );\n\n    /* Start with a non-zero point and randomize its coordinates */\n    i = d;\n    MBEDTLS_MPI_CHK( ecp_select_comb( grp, R, T, t_len, x[i] ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &R->Z, 1 ) );\n    if( f_rng != 0 )\n        MBEDTLS_MPI_CHK( ecp_randomize_jac( grp, R, f_rng, p_rng ) );\n\n    while( i-- != 0 )\n    {\n        MBEDTLS_MPI_CHK( ecp_double_jac( grp, R, R ) );\n        MBEDTLS_MPI_CHK( ecp_select_comb( grp, &Txi, T, t_len, x[i] ) );\n        MBEDTLS_MPI_CHK( ecp_add_mixed( grp, R, R, &Txi ) );\n    }\n\ncleanup:\n\n    mbedtls_ecp_point_free( &Txi );\n\n    return( ret );\n}\n\n/*\n * Multiplication using the comb method,\n * for curves in short Weierstrass form\n */\nstatic int ecp_mul_comb( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,\n                         const mbedtls_mpi *m, const mbedtls_ecp_point *P,\n                         int (*f_rng)(void *, unsigned char *, size_t),\n                         void *p_rng )\n{\n    int ret;\n    unsigned char w, m_is_odd, p_eq_g, pre_len, i;\n    size_t d;\n    unsigned char k[COMB_MAX_D + 1];\n    mbedtls_ecp_point *T;\n    mbedtls_mpi M, mm;\n\n    mbedtls_mpi_init( &M );\n    mbedtls_mpi_init( &mm );\n\n    /* we need N to be odd to trnaform m in an odd number, check now */\n    if( mbedtls_mpi_get_bit( &grp->N, 0 ) != 1 )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    /*\n     * Minimize the number of multiplications, that is minimize\n     * 10 * d * w + 18 * 2^(w-1) + 11 * d + 7 * w, with d = ceil( nbits / w )\n     * (see costs of the various parts, with 1S = 1M)\n     */\n    w = grp->nbits >= 384 ? 5 : 4;\n\n    /*\n     * If P == G, pre-compute a bit more, since this may be re-used later.\n     * Just adding one avoids upping the cost of the first mul too much,\n     * and the memory cost too.\n     */\n#if MBEDTLS_ECP_FIXED_POINT_OPTIM == 1\n    p_eq_g = ( mbedtls_mpi_cmp_mpi( &P->Y, &grp->G.Y ) == 0 &&\n               mbedtls_mpi_cmp_mpi( &P->X, &grp->G.X ) == 0 );\n    if( p_eq_g )\n        w++;\n#else\n    p_eq_g = 0;\n#endif\n\n    /*\n     * Make sure w is within bounds.\n     * (The last test is useful only for very small curves in the test suite.)\n     */\n    if( w > MBEDTLS_ECP_WINDOW_SIZE )\n        w = MBEDTLS_ECP_WINDOW_SIZE;\n    if( w >= grp->nbits )\n        w = 2;\n\n    /* Other sizes that depend on w */\n    pre_len = 1U << ( w - 1 );\n    d = ( grp->nbits + w - 1 ) / w;\n\n    /*\n     * Prepare precomputed points: if P == G we want to\n     * use grp->T if already initialized, or initialize it.\n     */\n    T = p_eq_g ? grp->T : NULL;\n\n    if( T == NULL )\n    {\n        T = mbedtls_calloc( pre_len, sizeof( mbedtls_ecp_point ) );\n        if( T == NULL )\n        {\n            ret = MBEDTLS_ERR_ECP_ALLOC_FAILED;\n            goto cleanup;\n        }\n\n        MBEDTLS_MPI_CHK( ecp_precompute_comb( grp, T, P, w, d ) );\n\n        if( p_eq_g )\n        {\n            grp->T = T;\n            grp->T_size = pre_len;\n        }\n    }\n\n    /*\n     * Make sure M is odd (M = m or M = N - m, since N is odd)\n     * using the fact that m * P = - (N - m) * P\n     */\n    m_is_odd = ( mbedtls_mpi_get_bit( m, 0 ) == 1 );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &M, m ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &mm, &grp->N, m ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &M, &mm, ! m_is_odd ) );\n\n    /*\n     * Go for comb multiplication, R = M * P\n     */\n    ecp_comb_fixed( k, d, w, &M );\n    MBEDTLS_MPI_CHK( ecp_mul_comb_core( grp, R, T, pre_len, k, d, f_rng, p_rng ) );\n\n    /*\n     * Now get m * P from M * P and normalize it\n     */\n    MBEDTLS_MPI_CHK( ecp_safe_invert_jac( grp, R, ! m_is_odd ) );\n    MBEDTLS_MPI_CHK( ecp_normalize_jac( grp, R ) );\n\ncleanup:\n\n    if( T != NULL && ! p_eq_g )\n    {\n        for( i = 0; i < pre_len; i++ )\n            mbedtls_ecp_point_free( &T[i] );\n        mbedtls_free( T );\n    }\n\n    mbedtls_mpi_free( &M );\n    mbedtls_mpi_free( &mm );\n\n    if( ret != 0 )\n        mbedtls_ecp_point_free( R );\n\n    return( ret );\n}\n\n#endif /* ECP_SHORTWEIERSTRASS */\n\n#if defined(ECP_MONTGOMERY)\n/*\n * For Montgomery curves, we do all the internal arithmetic in projective\n * coordinates. Import/export of points uses only the x coordinates, which is\n * internaly represented as X / Z.\n *\n * For scalar multiplication, we'll use a Montgomery ladder.\n */\n\n/*\n * Normalize Montgomery x/z coordinates: X = X/Z, Z = 1\n * Cost: 1M + 1I\n */\nstatic int ecp_normalize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P )\n{\n    int ret;\n\n#if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)\n    if ( mbedtls_internal_ecp_grp_capable( grp ) )\n    {\n        return mbedtls_internal_ecp_normalize_mxz( grp, P );\n    }\n#endif /* MBEDTLS_ECP_NORMALIZE_MXZ_ALT */\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &P->Z, &P->Z, &grp->P ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &P->X, &P->X, &P->Z ) ); MOD_MUL( P->X );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &P->Z, 1 ) );\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Randomize projective x/z coordinates:\n * (X, Z) -> (l X, l Z) for random l\n * This is sort of the reverse operation of ecp_normalize_mxz().\n *\n * This countermeasure was first suggested in [2].\n * Cost: 2M\n */\nstatic int ecp_randomize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P,\n                int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    int ret;\n    mbedtls_mpi l;\n    size_t p_size;\n    int count = 0;\n\n#if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT)\n    if ( mbedtls_internal_ecp_grp_capable( grp ) )\n    {\n        return mbedtls_internal_ecp_randomize_mxz( grp, P, f_rng, p_rng );\n    }\n#endif /* MBEDTLS_ECP_RANDOMIZE_MXZ_ALT */\n\n    p_size = ( grp->pbits + 7 ) / 8;\n    mbedtls_mpi_init( &l );\n\n    /* Generate l such that 1 < l < p */\n    do\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &l, p_size, f_rng, p_rng ) );\n\n        while( mbedtls_mpi_cmp_mpi( &l, &grp->P ) >= 0 )\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &l, 1 ) );\n\n        if( count++ > 10 )\n            return( MBEDTLS_ERR_ECP_RANDOM_FAILED );\n    }\n    while( mbedtls_mpi_cmp_int( &l, 1 ) <= 0 );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &P->X, &P->X, &l ) ); MOD_MUL( P->X );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &P->Z, &P->Z, &l ) ); MOD_MUL( P->Z );\n\ncleanup:\n    mbedtls_mpi_free( &l );\n\n    return( ret );\n}\n\n/*\n * Double-and-add: R = 2P, S = P + Q, with d = X(P - Q),\n * for Montgomery curves in x/z coordinates.\n *\n * http://www.hyperelliptic.org/EFD/g1p/auto-code/montgom/xz/ladder/mladd-1987-m.op3\n * with\n * d =  X1\n * P = (X2, Z2)\n * Q = (X3, Z3)\n * R = (X4, Z4)\n * S = (X5, Z5)\n * and eliminating temporary variables tO, ..., t4.\n *\n * Cost: 5M + 4S\n */\nstatic int ecp_double_add_mxz( const mbedtls_ecp_group *grp,\n                               mbedtls_ecp_point *R, mbedtls_ecp_point *S,\n                               const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q,\n                               const mbedtls_mpi *d )\n{\n    int ret;\n    mbedtls_mpi A, AA, B, BB, E, C, D, DA, CB;\n\n#if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT)\n    if ( mbedtls_internal_ecp_grp_capable( grp ) )\n    {\n        return mbedtls_internal_ecp_double_add_mxz( grp, R, S, P, Q, d );\n    }\n#endif /* MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT */\n\n    mbedtls_mpi_init( &A ); mbedtls_mpi_init( &AA ); mbedtls_mpi_init( &B );\n    mbedtls_mpi_init( &BB ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &C );\n    mbedtls_mpi_init( &D ); mbedtls_mpi_init( &DA ); mbedtls_mpi_init( &CB );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &A,    &P->X,   &P->Z ) ); MOD_ADD( A    );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &AA,   &A,      &A    ) ); MOD_MUL( AA   );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &B,    &P->X,   &P->Z ) ); MOD_SUB( B    );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &BB,   &B,      &B    ) ); MOD_MUL( BB   );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &E,    &AA,     &BB   ) ); MOD_SUB( E    );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &C,    &Q->X,   &Q->Z ) ); MOD_ADD( C    );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &D,    &Q->X,   &Q->Z ) ); MOD_SUB( D    );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DA,   &D,      &A    ) ); MOD_MUL( DA   );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &CB,   &C,      &B    ) ); MOD_MUL( CB   );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &S->X, &DA,     &CB   ) ); MOD_MUL( S->X );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S->X, &S->X,   &S->X ) ); MOD_MUL( S->X );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &S->Z, &DA,     &CB   ) ); MOD_SUB( S->Z );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S->Z, &S->Z,   &S->Z ) ); MOD_MUL( S->Z );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S->Z, d,       &S->Z ) ); MOD_MUL( S->Z );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &R->X, &AA,     &BB   ) ); MOD_MUL( R->X );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &R->Z, &grp->A, &E    ) ); MOD_MUL( R->Z );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &R->Z, &BB,     &R->Z ) ); MOD_ADD( R->Z );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &R->Z, &E,      &R->Z ) ); MOD_MUL( R->Z );\n\ncleanup:\n    mbedtls_mpi_free( &A ); mbedtls_mpi_free( &AA ); mbedtls_mpi_free( &B );\n    mbedtls_mpi_free( &BB ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &C );\n    mbedtls_mpi_free( &D ); mbedtls_mpi_free( &DA ); mbedtls_mpi_free( &CB );\n\n    return( ret );\n}\n\n/*\n * Multiplication with Montgomery ladder in x/z coordinates,\n * for curves in Montgomery form\n */\nstatic int ecp_mul_mxz( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,\n                        const mbedtls_mpi *m, const mbedtls_ecp_point *P,\n                        int (*f_rng)(void *, unsigned char *, size_t),\n                        void *p_rng )\n{\n    int ret;\n    size_t i;\n    unsigned char b;\n    mbedtls_ecp_point RP;\n    mbedtls_mpi PX;\n\n    mbedtls_ecp_point_init( &RP ); mbedtls_mpi_init( &PX );\n\n    /* Save PX and read from P before writing to R, in case P == R */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &PX, &P->X ) );\n    MBEDTLS_MPI_CHK( mbedtls_ecp_copy( &RP, P ) );\n\n    /* Set R to zero in modified x/z coordinates */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &R->X, 1 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &R->Z, 0 ) );\n    mbedtls_mpi_free( &R->Y );\n\n    /* RP.X might be sligtly larger than P, so reduce it */\n    MOD_ADD( RP.X );\n\n    /* Randomize coordinates of the starting point */\n    if( f_rng != NULL )\n        MBEDTLS_MPI_CHK( ecp_randomize_mxz( grp, &RP, f_rng, p_rng ) );\n\n    /* Loop invariant: R = result so far, RP = R + P */\n    i = mbedtls_mpi_bitlen( m ); /* one past the (zero-based) most significant bit */\n    while( i-- > 0 )\n    {\n        b = mbedtls_mpi_get_bit( m, i );\n        /*\n         *  if (b) R = 2R + P else R = 2R,\n         * which is:\n         *  if (b) double_add( RP, R, RP, R )\n         *  else   double_add( R, RP, R, RP )\n         * but using safe conditional swaps to avoid leaks\n         */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->X, &RP.X, b ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->Z, &RP.Z, b ) );\n        MBEDTLS_MPI_CHK( ecp_double_add_mxz( grp, R, &RP, R, &RP, &PX ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->X, &RP.X, b ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->Z, &RP.Z, b ) );\n    }\n\n    MBEDTLS_MPI_CHK( ecp_normalize_mxz( grp, R ) );\n\ncleanup:\n    mbedtls_ecp_point_free( &RP ); mbedtls_mpi_free( &PX );\n\n    return( ret );\n}\n\n#endif /* ECP_MONTGOMERY */\n\n/*\n * Multiplication R = m * P\n */\nint mbedtls_ecp_mul( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,\n             const mbedtls_mpi *m, const mbedtls_ecp_point *P,\n             int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;\n#if defined(MBEDTLS_ECP_INTERNAL_ALT)\n    char is_grp_capable = 0;\n#endif\n\n    /* Common sanity checks */\n    if( mbedtls_mpi_cmp_int( &P->Z, 1 ) != 0 )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\n    if( ( ret = mbedtls_ecp_check_privkey( grp, m ) ) != 0 ||\n        ( ret = mbedtls_ecp_check_pubkey( grp, P ) ) != 0 )\n        return( ret );\n\n#if defined(MBEDTLS_ECP_INTERNAL_ALT)\n    if ( is_grp_capable = mbedtls_internal_ecp_grp_capable( grp )  )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_internal_ecp_init( grp ) );\n    }\n\n#endif /* MBEDTLS_ECP_INTERNAL_ALT */\n#if defined(ECP_MONTGOMERY)\n    if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY )\n        ret = ecp_mul_mxz( grp, R, m, P, f_rng, p_rng );\n\n#endif\n#if defined(ECP_SHORTWEIERSTRASS)\n    if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS )\n        ret = ecp_mul_comb( grp, R, m, P, f_rng, p_rng );\n\n#endif\n#if defined(MBEDTLS_ECP_INTERNAL_ALT)\ncleanup:\n\n    if ( is_grp_capable )\n    {\n        mbedtls_internal_ecp_free( grp );\n    }\n\n#endif /* MBEDTLS_ECP_INTERNAL_ALT */\n    return( ret );\n}\n\n#if defined(ECP_SHORTWEIERSTRASS)\n/*\n * Check that an affine point is valid as a public key,\n * short weierstrass curves (SEC1 3.2.3.1)\n */\nstatic int ecp_check_pubkey_sw( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt )\n{\n    int ret;\n    mbedtls_mpi YY, RHS;\n\n    /* pt coordinates must be normalized for our checks */\n    if( mbedtls_mpi_cmp_int( &pt->X, 0 ) < 0 ||\n        mbedtls_mpi_cmp_int( &pt->Y, 0 ) < 0 ||\n        mbedtls_mpi_cmp_mpi( &pt->X, &grp->P ) >= 0 ||\n        mbedtls_mpi_cmp_mpi( &pt->Y, &grp->P ) >= 0 )\n        return( MBEDTLS_ERR_ECP_INVALID_KEY );\n\n    mbedtls_mpi_init( &YY ); mbedtls_mpi_init( &RHS );\n\n    /*\n     * YY = Y^2\n     * RHS = X (X^2 + A) + B = X^3 + A X + B\n     */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &YY,  &pt->Y,   &pt->Y  ) );  MOD_MUL( YY  );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &RHS, &pt->X,   &pt->X  ) );  MOD_MUL( RHS );\n\n    /* Special case for A = -3 */\n    if( grp->A.p == NULL )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &RHS, &RHS, 3       ) );  MOD_SUB( RHS );\n    }\n    else\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &RHS, &RHS, &grp->A ) );  MOD_ADD( RHS );\n    }\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &RHS, &RHS,     &pt->X  ) );  MOD_MUL( RHS );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &RHS, &RHS,     &grp->B ) );  MOD_ADD( RHS );\n\n    if( mbedtls_mpi_cmp_mpi( &YY, &RHS ) != 0 )\n        ret = MBEDTLS_ERR_ECP_INVALID_KEY;\n\ncleanup:\n\n    mbedtls_mpi_free( &YY ); mbedtls_mpi_free( &RHS );\n\n    return( ret );\n}\n#endif /* ECP_SHORTWEIERSTRASS */\n\n/*\n * R = m * P with shortcuts for m == 1 and m == -1\n * NOT constant-time - ONLY for short Weierstrass!\n */\nstatic int mbedtls_ecp_mul_shortcuts( mbedtls_ecp_group *grp,\n                                      mbedtls_ecp_point *R,\n                                      const mbedtls_mpi *m,\n                                      const mbedtls_ecp_point *P )\n{\n    int ret;\n\n    if( mbedtls_mpi_cmp_int( m, 1 ) == 0 )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, P ) );\n    }\n    else if( mbedtls_mpi_cmp_int( m, -1 ) == 0 )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, P ) );\n        if( mbedtls_mpi_cmp_int( &R->Y, 0 ) != 0 )\n            MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &R->Y, &grp->P, &R->Y ) );\n    }\n    else\n    {\n        MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, R, m, P, NULL, NULL ) );\n    }\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Linear combination\n * NOT constant-time\n */\nint mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,\n             const mbedtls_mpi *m, const mbedtls_ecp_point *P,\n             const mbedtls_mpi *n, const mbedtls_ecp_point *Q )\n{\n    int ret;\n    mbedtls_ecp_point mP;\n#if defined(MBEDTLS_ECP_INTERNAL_ALT)\n    char is_grp_capable = 0;\n#endif\n\n    if( ecp_get_type( grp ) != ECP_TYPE_SHORT_WEIERSTRASS )\n        return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );\n\n    mbedtls_ecp_point_init( &mP );\n\n    MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, &mP, m, P ) );\n    MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, R,   n, Q ) );\n\n#if defined(MBEDTLS_ECP_INTERNAL_ALT)\n    if (  is_grp_capable = mbedtls_internal_ecp_grp_capable( grp )  )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_internal_ecp_init( grp ) );\n    }\n\n#endif /* MBEDTLS_ECP_INTERNAL_ALT */\n    MBEDTLS_MPI_CHK( ecp_add_mixed( grp, R, &mP, R ) );\n    MBEDTLS_MPI_CHK( ecp_normalize_jac( grp, R ) );\n\ncleanup:\n\n#if defined(MBEDTLS_ECP_INTERNAL_ALT)\n    if ( is_grp_capable )\n    {\n        mbedtls_internal_ecp_free( grp );\n    }\n\n#endif /* MBEDTLS_ECP_INTERNAL_ALT */\n    mbedtls_ecp_point_free( &mP );\n\n    return( ret );\n}\n\n\n#if defined(ECP_MONTGOMERY)\n/*\n * Check validity of a public key for Montgomery curves with x-only schemes\n */\nstatic int ecp_check_pubkey_mx( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt )\n{\n    /* [Curve25519 p. 5] Just check X is the correct number of bytes */\n    /* Allow any public value, if it's too big then we'll just reduce it mod p\n     * (RFC 7748 sec. 5 para. 3). */\n    if( mbedtls_mpi_size( &pt->X ) > ( grp->nbits + 7 ) / 8 )\n        return( MBEDTLS_ERR_ECP_INVALID_KEY );\n\n    return( 0 );\n}\n#endif /* ECP_MONTGOMERY */\n\n/*\n * Check that a point is valid as a public key\n */\nint mbedtls_ecp_check_pubkey( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt )\n{\n    /* Must use affine coordinates */\n    if( mbedtls_mpi_cmp_int( &pt->Z, 1 ) != 0 )\n        return( MBEDTLS_ERR_ECP_INVALID_KEY );\n\n#if defined(ECP_MONTGOMERY)\n    if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY )\n        return( ecp_check_pubkey_mx( grp, pt ) );\n#endif\n#if defined(ECP_SHORTWEIERSTRASS)\n    if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS )\n        return( ecp_check_pubkey_sw( grp, pt ) );\n#endif\n    return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n}\n\n/*\n * Check that an mbedtls_mpi is valid as a private key\n */\nint mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp, const mbedtls_mpi *d )\n{\n#if defined(ECP_MONTGOMERY)\n    if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY )\n    {\n        /* see RFC 7748 sec. 5 para. 5 */\n        if( mbedtls_mpi_get_bit( d, 0 ) != 0 ||\n            mbedtls_mpi_get_bit( d, 1 ) != 0 ||\n            mbedtls_mpi_bitlen( d ) - 1 != grp->nbits ) /* mbedtls_mpi_bitlen is one-based! */\n            return( MBEDTLS_ERR_ECP_INVALID_KEY );\n        else\n\n        /* see [Curve25519] page 5 */\n        if( grp->nbits == 254 && mbedtls_mpi_get_bit( d, 2 ) != 0 )\n            return( MBEDTLS_ERR_ECP_INVALID_KEY );\n\n        return( 0 );\n    }\n#endif /* ECP_MONTGOMERY */\n#if defined(ECP_SHORTWEIERSTRASS)\n    if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS )\n    {\n        /* see SEC1 3.2 */\n        if( mbedtls_mpi_cmp_int( d, 1 ) < 0 ||\n            mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )\n            return( MBEDTLS_ERR_ECP_INVALID_KEY );\n        else\n            return( 0 );\n    }\n#endif /* ECP_SHORTWEIERSTRASS */\n\n    return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n}\n\n/*\n * Generate a keypair with configurable base point\n */\nint mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp,\n                     const mbedtls_ecp_point *G,\n                     mbedtls_mpi *d, mbedtls_ecp_point *Q,\n                     int (*f_rng)(void *, unsigned char *, size_t),\n                     void *p_rng )\n{\n    int ret;\n    size_t n_size = ( grp->nbits + 7 ) / 8;\n\n#if defined(ECP_MONTGOMERY)\n    if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY )\n    {\n        /* [M225] page 5 */\n        size_t b;\n\n        do {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );\n        } while( mbedtls_mpi_bitlen( d ) == 0);\n\n        /* Make sure the most significant bit is nbits */\n        b = mbedtls_mpi_bitlen( d ) - 1; /* mbedtls_mpi_bitlen is one-based */\n        if( b > grp->nbits )\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, b - grp->nbits ) );\n        else\n            MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, grp->nbits, 1 ) );\n\n        /* Make sure the last two bits are unset for Curve448, three bits for\n           Curve25519 */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 0, 0 ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 1, 0 ) );\n        if( grp->nbits == 254 )\n        {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) );\n        }\n    }\n    else\n#endif /* ECP_MONTGOMERY */\n#if defined(ECP_SHORTWEIERSTRASS)\n    if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS )\n    {\n        /* SEC1 3.2.1: Generate d such that 1 <= n < N */\n        int count = 0;\n\n        /*\n         * Match the procedure given in RFC 6979 (deterministic ECDSA):\n         * - use the same byte ordering;\n         * - keep the leftmost nbits bits of the generated octet string;\n         * - try until result is in the desired range.\n         * This also avoids any biais, which is especially important for ECDSA.\n         */\n        do\n        {\n            MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_size - grp->nbits ) );\n\n            /*\n             * Each try has at worst a probability 1/2 of failing (the msb has\n             * a probability 1/2 of being 0, and then the result will be < N),\n             * so after 30 tries failure probability is a most 2**(-30).\n             *\n             * For most curves, 1 try is enough with overwhelming probability,\n             * since N starts with a lot of 1s in binary, but some curves\n             * such as secp224k1 are actually very close to the worst case.\n             */\n            if( ++count > 30 )\n                return( MBEDTLS_ERR_ECP_RANDOM_FAILED );\n        }\n        while( mbedtls_mpi_cmp_int( d, 1 ) < 0 ||\n               mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 );\n    }\n    else\n#endif /* ECP_SHORTWEIERSTRASS */\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n\ncleanup:\n    if( ret != 0 )\n        return( ret );\n\n    return( mbedtls_ecp_mul( grp, Q, d, G, f_rng, p_rng ) );\n}\n\n/*\n * Generate key pair, wrapper for conventional base point\n */\nint mbedtls_ecp_gen_keypair( mbedtls_ecp_group *grp,\n                             mbedtls_mpi *d, mbedtls_ecp_point *Q,\n                             int (*f_rng)(void *, unsigned char *, size_t),\n                             void *p_rng )\n{\n    return( mbedtls_ecp_gen_keypair_base( grp, &grp->G, d, Q, f_rng, p_rng ) );\n}\n\n/*\n * Generate a keypair, prettier wrapper\n */\nint mbedtls_ecp_gen_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key,\n                int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    int ret;\n\n    if( ( ret = mbedtls_ecp_group_load( &key->grp, grp_id ) ) != 0 )\n        return( ret );\n\n    return( mbedtls_ecp_gen_keypair( &key->grp, &key->d, &key->Q, f_rng, p_rng ) );\n}\n\n/*\n * Check a public-private key pair\n */\nint mbedtls_ecp_check_pub_priv( const mbedtls_ecp_keypair *pub, const mbedtls_ecp_keypair *prv )\n{\n    int ret;\n    mbedtls_ecp_point Q;\n    mbedtls_ecp_group grp;\n\n    if( pub->grp.id == MBEDTLS_ECP_DP_NONE ||\n        pub->grp.id != prv->grp.id ||\n        mbedtls_mpi_cmp_mpi( &pub->Q.X, &prv->Q.X ) ||\n        mbedtls_mpi_cmp_mpi( &pub->Q.Y, &prv->Q.Y ) ||\n        mbedtls_mpi_cmp_mpi( &pub->Q.Z, &prv->Q.Z ) )\n    {\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n    }\n\n    mbedtls_ecp_point_init( &Q );\n    mbedtls_ecp_group_init( &grp );\n\n    /* mbedtls_ecp_mul() needs a non-const group... */\n    mbedtls_ecp_group_copy( &grp, &prv->grp );\n\n    /* Also checks d is valid */\n    MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &Q, &prv->d, &prv->grp.G, NULL, NULL ) );\n\n    if( mbedtls_mpi_cmp_mpi( &Q.X, &prv->Q.X ) ||\n        mbedtls_mpi_cmp_mpi( &Q.Y, &prv->Q.Y ) ||\n        mbedtls_mpi_cmp_mpi( &Q.Z, &prv->Q.Z ) )\n    {\n        ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;\n        goto cleanup;\n    }\n\ncleanup:\n    mbedtls_ecp_point_free( &Q );\n    mbedtls_ecp_group_free( &grp );\n\n    return( ret );\n}\n\n#if defined(MBEDTLS_SELF_TEST)\n\n/*\n * Checkup routine\n */\nint mbedtls_ecp_self_test( int verbose )\n{\n    int ret;\n    size_t i;\n    mbedtls_ecp_group grp;\n    mbedtls_ecp_point R, P;\n    mbedtls_mpi m;\n    unsigned long add_c_prev, dbl_c_prev, mul_c_prev;\n    /* exponents especially adapted for secp192r1 */\n    const char *exponents[] =\n    {\n        \"000000000000000000000000000000000000000000000001\", /* one */\n        \"FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22830\", /* N - 1 */\n        \"5EA6F389A38B8BC81E767753B15AA5569E1782E30ABE7D25\", /* random */\n        \"400000000000000000000000000000000000000000000000\", /* one and zeros */\n        \"7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\", /* all ones */\n        \"555555555555555555555555555555555555555555555555\", /* 101010... */\n    };\n\n    mbedtls_ecp_group_init( &grp );\n    mbedtls_ecp_point_init( &R );\n    mbedtls_ecp_point_init( &P );\n    mbedtls_mpi_init( &m );\n\n    /* Use secp192r1 if available, or any available curve */\n#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)\n    MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, MBEDTLS_ECP_DP_SECP192R1 ) );\n#else\n    MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, mbedtls_ecp_curve_list()->grp_id ) );\n#endif\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  ECP test #1 (constant op_count, base point G): \" );\n\n    /* Do a dummy multiplication first to trigger precomputation */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &m, 2 ) );\n    MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &P, &m, &grp.G, NULL, NULL ) );\n\n    add_count = 0;\n    dbl_count = 0;\n    mul_count = 0;\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &m, 16, exponents[0] ) );\n    MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &R, &m, &grp.G, NULL, NULL ) );\n\n    for( i = 1; i < sizeof( exponents ) / sizeof( exponents[0] ); i++ )\n    {\n        add_c_prev = add_count;\n        dbl_c_prev = dbl_count;\n        mul_c_prev = mul_count;\n        add_count = 0;\n        dbl_count = 0;\n        mul_count = 0;\n\n        MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &m, 16, exponents[i] ) );\n        MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &R, &m, &grp.G, NULL, NULL ) );\n\n        if( add_count != add_c_prev ||\n            dbl_count != dbl_c_prev ||\n            mul_count != mul_c_prev )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed (%u)\\n\", (unsigned int) i );\n\n            ret = 1;\n            goto cleanup;\n        }\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  ECP test #2 (constant op_count, other point): \" );\n    /* We computed P = 2G last time, use it */\n\n    add_count = 0;\n    dbl_count = 0;\n    mul_count = 0;\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &m, 16, exponents[0] ) );\n    MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &R, &m, &P, NULL, NULL ) );\n\n    for( i = 1; i < sizeof( exponents ) / sizeof( exponents[0] ); i++ )\n    {\n        add_c_prev = add_count;\n        dbl_c_prev = dbl_count;\n        mul_c_prev = mul_count;\n        add_count = 0;\n        dbl_count = 0;\n        mul_count = 0;\n\n        MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &m, 16, exponents[i] ) );\n        MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &R, &m, &P, NULL, NULL ) );\n\n        if( add_count != add_c_prev ||\n            dbl_count != dbl_c_prev ||\n            mul_count != mul_c_prev )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed (%u)\\n\", (unsigned int) i );\n\n            ret = 1;\n            goto cleanup;\n        }\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\ncleanup:\n\n    if( ret < 0 && verbose != 0 )\n        mbedtls_printf( \"Unexpected error, return code = %08X\\n\", ret );\n\n    mbedtls_ecp_group_free( &grp );\n    mbedtls_ecp_point_free( &R );\n    mbedtls_ecp_point_free( &P );\n    mbedtls_mpi_free( &m );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* !MBEDTLS_ECP_ALT */\n\n#endif /* MBEDTLS_ECP_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/ecp_curves.c",
    "content": "/*\n *  Elliptic curves over GF(p): curve-specific data and functions\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_ECP_C)\n\n#include \"mbedtls/ecp.h\"\n\n#include <string.h>\n\n#if !defined(MBEDTLS_ECP_ALT)\n\n#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \\\n    !defined(inline) && !defined(__cplusplus)\n#define inline __inline\n#endif\n\n/*\n * Conversion macros for embedded constants:\n * build lists of mbedtls_mpi_uint's from lists of unsigned char's grouped by 8, 4 or 2\n */\n#if defined(MBEDTLS_HAVE_INT32)\n\n#define BYTES_TO_T_UINT_4( a, b, c, d )             \\\n    ( (mbedtls_mpi_uint) a <<  0 ) |                          \\\n    ( (mbedtls_mpi_uint) b <<  8 ) |                          \\\n    ( (mbedtls_mpi_uint) c << 16 ) |                          \\\n    ( (mbedtls_mpi_uint) d << 24 )\n\n#define BYTES_TO_T_UINT_2( a, b )                   \\\n    BYTES_TO_T_UINT_4( a, b, 0, 0 )\n\n#define BYTES_TO_T_UINT_8( a, b, c, d, e, f, g, h ) \\\n    BYTES_TO_T_UINT_4( a, b, c, d ),                \\\n    BYTES_TO_T_UINT_4( e, f, g, h )\n\n#else /* 64-bits */\n\n#define BYTES_TO_T_UINT_8( a, b, c, d, e, f, g, h ) \\\n    ( (mbedtls_mpi_uint) a <<  0 ) |                          \\\n    ( (mbedtls_mpi_uint) b <<  8 ) |                          \\\n    ( (mbedtls_mpi_uint) c << 16 ) |                          \\\n    ( (mbedtls_mpi_uint) d << 24 ) |                          \\\n    ( (mbedtls_mpi_uint) e << 32 ) |                          \\\n    ( (mbedtls_mpi_uint) f << 40 ) |                          \\\n    ( (mbedtls_mpi_uint) g << 48 ) |                          \\\n    ( (mbedtls_mpi_uint) h << 56 )\n\n#define BYTES_TO_T_UINT_4( a, b, c, d )             \\\n    BYTES_TO_T_UINT_8( a, b, c, d, 0, 0, 0, 0 )\n\n#define BYTES_TO_T_UINT_2( a, b )                   \\\n    BYTES_TO_T_UINT_8( a, b, 0, 0, 0, 0, 0, 0 )\n\n#endif /* bits in mbedtls_mpi_uint */\n\n/*\n * Note: the constants are in little-endian order\n * to be directly usable in MPIs\n */\n\n/*\n * Domain parameters for secp192r1\n */\n#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)\nstatic const mbedtls_mpi_uint secp192r1_p[] = {\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n};\nstatic const mbedtls_mpi_uint secp192r1_b[] = {\n    BYTES_TO_T_UINT_8( 0xB1, 0xB9, 0x46, 0xC1, 0xEC, 0xDE, 0xB8, 0xFE ),\n    BYTES_TO_T_UINT_8( 0x49, 0x30, 0x24, 0x72, 0xAB, 0xE9, 0xA7, 0x0F ),\n    BYTES_TO_T_UINT_8( 0xE7, 0x80, 0x9C, 0xE5, 0x19, 0x05, 0x21, 0x64 ),\n};\nstatic const mbedtls_mpi_uint secp192r1_gx[] = {\n    BYTES_TO_T_UINT_8( 0x12, 0x10, 0xFF, 0x82, 0xFD, 0x0A, 0xFF, 0xF4 ),\n    BYTES_TO_T_UINT_8( 0x00, 0x88, 0xA1, 0x43, 0xEB, 0x20, 0xBF, 0x7C ),\n    BYTES_TO_T_UINT_8( 0xF6, 0x90, 0x30, 0xB0, 0x0E, 0xA8, 0x8D, 0x18 ),\n};\nstatic const mbedtls_mpi_uint secp192r1_gy[] = {\n    BYTES_TO_T_UINT_8( 0x11, 0x48, 0x79, 0x1E, 0xA1, 0x77, 0xF9, 0x73 ),\n    BYTES_TO_T_UINT_8( 0xD5, 0xCD, 0x24, 0x6B, 0xED, 0x11, 0x10, 0x63 ),\n    BYTES_TO_T_UINT_8( 0x78, 0xDA, 0xC8, 0xFF, 0x95, 0x2B, 0x19, 0x07 ),\n};\nstatic const mbedtls_mpi_uint secp192r1_n[] = {\n    BYTES_TO_T_UINT_8( 0x31, 0x28, 0xD2, 0xB4, 0xB1, 0xC9, 0x6B, 0x14 ),\n    BYTES_TO_T_UINT_8( 0x36, 0xF8, 0xDE, 0x99, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n};\n#endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */\n\n/*\n * Domain parameters for secp224r1\n */\n#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)\nstatic const mbedtls_mpi_uint secp224r1_p[] = {\n    BYTES_TO_T_UINT_8( 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ),\n    BYTES_TO_T_UINT_8( 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00 ),\n};\nstatic const mbedtls_mpi_uint secp224r1_b[] = {\n    BYTES_TO_T_UINT_8( 0xB4, 0xFF, 0x55, 0x23, 0x43, 0x39, 0x0B, 0x27 ),\n    BYTES_TO_T_UINT_8( 0xBA, 0xD8, 0xBF, 0xD7, 0xB7, 0xB0, 0x44, 0x50 ),\n    BYTES_TO_T_UINT_8( 0x56, 0x32, 0x41, 0xF5, 0xAB, 0xB3, 0x04, 0x0C ),\n    BYTES_TO_T_UINT_4( 0x85, 0x0A, 0x05, 0xB4 ),\n};\nstatic const mbedtls_mpi_uint secp224r1_gx[] = {\n    BYTES_TO_T_UINT_8( 0x21, 0x1D, 0x5C, 0x11, 0xD6, 0x80, 0x32, 0x34 ),\n    BYTES_TO_T_UINT_8( 0x22, 0x11, 0xC2, 0x56, 0xD3, 0xC1, 0x03, 0x4A ),\n    BYTES_TO_T_UINT_8( 0xB9, 0x90, 0x13, 0x32, 0x7F, 0xBF, 0xB4, 0x6B ),\n    BYTES_TO_T_UINT_4( 0xBD, 0x0C, 0x0E, 0xB7 ),\n};\nstatic const mbedtls_mpi_uint secp224r1_gy[] = {\n    BYTES_TO_T_UINT_8( 0x34, 0x7E, 0x00, 0x85, 0x99, 0x81, 0xD5, 0x44 ),\n    BYTES_TO_T_UINT_8( 0x64, 0x47, 0x07, 0x5A, 0xA0, 0x75, 0x43, 0xCD ),\n    BYTES_TO_T_UINT_8( 0xE6, 0xDF, 0x22, 0x4C, 0xFB, 0x23, 0xF7, 0xB5 ),\n    BYTES_TO_T_UINT_4( 0x88, 0x63, 0x37, 0xBD ),\n};\nstatic const mbedtls_mpi_uint secp224r1_n[] = {\n    BYTES_TO_T_UINT_8( 0x3D, 0x2A, 0x5C, 0x5C, 0x45, 0x29, 0xDD, 0x13 ),\n    BYTES_TO_T_UINT_8( 0x3E, 0xF0, 0xB8, 0xE0, 0xA2, 0x16, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_4( 0xFF, 0xFF, 0xFF, 0xFF ),\n};\n#endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */\n\n/*\n * Domain parameters for secp256r1\n */\n#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)\nstatic const mbedtls_mpi_uint secp256r1_p[] = {\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00 ),\n    BYTES_TO_T_UINT_8( 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ),\n    BYTES_TO_T_UINT_8( 0x01, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF ),\n};\nstatic const mbedtls_mpi_uint secp256r1_b[] = {\n    BYTES_TO_T_UINT_8( 0x4B, 0x60, 0xD2, 0x27, 0x3E, 0x3C, 0xCE, 0x3B ),\n    BYTES_TO_T_UINT_8( 0xF6, 0xB0, 0x53, 0xCC, 0xB0, 0x06, 0x1D, 0x65 ),\n    BYTES_TO_T_UINT_8( 0xBC, 0x86, 0x98, 0x76, 0x55, 0xBD, 0xEB, 0xB3 ),\n    BYTES_TO_T_UINT_8( 0xE7, 0x93, 0x3A, 0xAA, 0xD8, 0x35, 0xC6, 0x5A ),\n};\nstatic const mbedtls_mpi_uint secp256r1_gx[] = {\n    BYTES_TO_T_UINT_8( 0x96, 0xC2, 0x98, 0xD8, 0x45, 0x39, 0xA1, 0xF4 ),\n    BYTES_TO_T_UINT_8( 0xA0, 0x33, 0xEB, 0x2D, 0x81, 0x7D, 0x03, 0x77 ),\n    BYTES_TO_T_UINT_8( 0xF2, 0x40, 0xA4, 0x63, 0xE5, 0xE6, 0xBC, 0xF8 ),\n    BYTES_TO_T_UINT_8( 0x47, 0x42, 0x2C, 0xE1, 0xF2, 0xD1, 0x17, 0x6B ),\n};\nstatic const mbedtls_mpi_uint secp256r1_gy[] = {\n    BYTES_TO_T_UINT_8( 0xF5, 0x51, 0xBF, 0x37, 0x68, 0x40, 0xB6, 0xCB ),\n    BYTES_TO_T_UINT_8( 0xCE, 0x5E, 0x31, 0x6B, 0x57, 0x33, 0xCE, 0x2B ),\n    BYTES_TO_T_UINT_8( 0x16, 0x9E, 0x0F, 0x7C, 0x4A, 0xEB, 0xE7, 0x8E ),\n    BYTES_TO_T_UINT_8( 0x9B, 0x7F, 0x1A, 0xFE, 0xE2, 0x42, 0xE3, 0x4F ),\n};\nstatic const mbedtls_mpi_uint secp256r1_n[] = {\n    BYTES_TO_T_UINT_8( 0x51, 0x25, 0x63, 0xFC, 0xC2, 0xCA, 0xB9, 0xF3 ),\n    BYTES_TO_T_UINT_8( 0x84, 0x9E, 0x17, 0xA7, 0xAD, 0xFA, 0xE6, 0xBC ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF ),\n};\n#endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */\n\n/*\n * Domain parameters for secp384r1\n */\n#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)\nstatic const mbedtls_mpi_uint secp384r1_p[] = {\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00 ),\n    BYTES_TO_T_UINT_8( 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n};\nstatic const mbedtls_mpi_uint secp384r1_b[] = {\n    BYTES_TO_T_UINT_8( 0xEF, 0x2A, 0xEC, 0xD3, 0xED, 0xC8, 0x85, 0x2A ),\n    BYTES_TO_T_UINT_8( 0x9D, 0xD1, 0x2E, 0x8A, 0x8D, 0x39, 0x56, 0xC6 ),\n    BYTES_TO_T_UINT_8( 0x5A, 0x87, 0x13, 0x50, 0x8F, 0x08, 0x14, 0x03 ),\n    BYTES_TO_T_UINT_8( 0x12, 0x41, 0x81, 0xFE, 0x6E, 0x9C, 0x1D, 0x18 ),\n    BYTES_TO_T_UINT_8( 0x19, 0x2D, 0xF8, 0xE3, 0x6B, 0x05, 0x8E, 0x98 ),\n    BYTES_TO_T_UINT_8( 0xE4, 0xE7, 0x3E, 0xE2, 0xA7, 0x2F, 0x31, 0xB3 ),\n};\nstatic const mbedtls_mpi_uint secp384r1_gx[] = {\n    BYTES_TO_T_UINT_8( 0xB7, 0x0A, 0x76, 0x72, 0x38, 0x5E, 0x54, 0x3A ),\n    BYTES_TO_T_UINT_8( 0x6C, 0x29, 0x55, 0xBF, 0x5D, 0xF2, 0x02, 0x55 ),\n    BYTES_TO_T_UINT_8( 0x38, 0x2A, 0x54, 0x82, 0xE0, 0x41, 0xF7, 0x59 ),\n    BYTES_TO_T_UINT_8( 0x98, 0x9B, 0xA7, 0x8B, 0x62, 0x3B, 0x1D, 0x6E ),\n    BYTES_TO_T_UINT_8( 0x74, 0xAD, 0x20, 0xF3, 0x1E, 0xC7, 0xB1, 0x8E ),\n    BYTES_TO_T_UINT_8( 0x37, 0x05, 0x8B, 0xBE, 0x22, 0xCA, 0x87, 0xAA ),\n};\nstatic const mbedtls_mpi_uint secp384r1_gy[] = {\n    BYTES_TO_T_UINT_8( 0x5F, 0x0E, 0xEA, 0x90, 0x7C, 0x1D, 0x43, 0x7A ),\n    BYTES_TO_T_UINT_8( 0x9D, 0x81, 0x7E, 0x1D, 0xCE, 0xB1, 0x60, 0x0A ),\n    BYTES_TO_T_UINT_8( 0xC0, 0xB8, 0xF0, 0xB5, 0x13, 0x31, 0xDA, 0xE9 ),\n    BYTES_TO_T_UINT_8( 0x7C, 0x14, 0x9A, 0x28, 0xBD, 0x1D, 0xF4, 0xF8 ),\n    BYTES_TO_T_UINT_8( 0x29, 0xDC, 0x92, 0x92, 0xBF, 0x98, 0x9E, 0x5D ),\n    BYTES_TO_T_UINT_8( 0x6F, 0x2C, 0x26, 0x96, 0x4A, 0xDE, 0x17, 0x36 ),\n};\nstatic const mbedtls_mpi_uint secp384r1_n[] = {\n    BYTES_TO_T_UINT_8( 0x73, 0x29, 0xC5, 0xCC, 0x6A, 0x19, 0xEC, 0xEC ),\n    BYTES_TO_T_UINT_8( 0x7A, 0xA7, 0xB0, 0x48, 0xB2, 0x0D, 0x1A, 0x58 ),\n    BYTES_TO_T_UINT_8( 0xDF, 0x2D, 0x37, 0xF4, 0x81, 0x4D, 0x63, 0xC7 ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n};\n#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */\n\n/*\n * Domain parameters for secp521r1\n */\n#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)\nstatic const mbedtls_mpi_uint secp521r1_p[] = {\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_2( 0xFF, 0x01 ),\n};\nstatic const mbedtls_mpi_uint secp521r1_b[] = {\n    BYTES_TO_T_UINT_8( 0x00, 0x3F, 0x50, 0x6B, 0xD4, 0x1F, 0x45, 0xEF ),\n    BYTES_TO_T_UINT_8( 0xF1, 0x34, 0x2C, 0x3D, 0x88, 0xDF, 0x73, 0x35 ),\n    BYTES_TO_T_UINT_8( 0x07, 0xBF, 0xB1, 0x3B, 0xBD, 0xC0, 0x52, 0x16 ),\n    BYTES_TO_T_UINT_8( 0x7B, 0x93, 0x7E, 0xEC, 0x51, 0x39, 0x19, 0x56 ),\n    BYTES_TO_T_UINT_8( 0xE1, 0x09, 0xF1, 0x8E, 0x91, 0x89, 0xB4, 0xB8 ),\n    BYTES_TO_T_UINT_8( 0xF3, 0x15, 0xB3, 0x99, 0x5B, 0x72, 0xDA, 0xA2 ),\n    BYTES_TO_T_UINT_8( 0xEE, 0x40, 0x85, 0xB6, 0xA0, 0x21, 0x9A, 0x92 ),\n    BYTES_TO_T_UINT_8( 0x1F, 0x9A, 0x1C, 0x8E, 0x61, 0xB9, 0x3E, 0x95 ),\n    BYTES_TO_T_UINT_2( 0x51, 0x00 ),\n};\nstatic const mbedtls_mpi_uint secp521r1_gx[] = {\n    BYTES_TO_T_UINT_8( 0x66, 0xBD, 0xE5, 0xC2, 0x31, 0x7E, 0x7E, 0xF9 ),\n    BYTES_TO_T_UINT_8( 0x9B, 0x42, 0x6A, 0x85, 0xC1, 0xB3, 0x48, 0x33 ),\n    BYTES_TO_T_UINT_8( 0xDE, 0xA8, 0xFF, 0xA2, 0x27, 0xC1, 0x1D, 0xFE ),\n    BYTES_TO_T_UINT_8( 0x28, 0x59, 0xE7, 0xEF, 0x77, 0x5E, 0x4B, 0xA1 ),\n    BYTES_TO_T_UINT_8( 0xBA, 0x3D, 0x4D, 0x6B, 0x60, 0xAF, 0x28, 0xF8 ),\n    BYTES_TO_T_UINT_8( 0x21, 0xB5, 0x3F, 0x05, 0x39, 0x81, 0x64, 0x9C ),\n    BYTES_TO_T_UINT_8( 0x42, 0xB4, 0x95, 0x23, 0x66, 0xCB, 0x3E, 0x9E ),\n    BYTES_TO_T_UINT_8( 0xCD, 0xE9, 0x04, 0x04, 0xB7, 0x06, 0x8E, 0x85 ),\n    BYTES_TO_T_UINT_2( 0xC6, 0x00 ),\n};\nstatic const mbedtls_mpi_uint secp521r1_gy[] = {\n    BYTES_TO_T_UINT_8( 0x50, 0x66, 0xD1, 0x9F, 0x76, 0x94, 0xBE, 0x88 ),\n    BYTES_TO_T_UINT_8( 0x40, 0xC2, 0x72, 0xA2, 0x86, 0x70, 0x3C, 0x35 ),\n    BYTES_TO_T_UINT_8( 0x61, 0x07, 0xAD, 0x3F, 0x01, 0xB9, 0x50, 0xC5 ),\n    BYTES_TO_T_UINT_8( 0x40, 0x26, 0xF4, 0x5E, 0x99, 0x72, 0xEE, 0x97 ),\n    BYTES_TO_T_UINT_8( 0x2C, 0x66, 0x3E, 0x27, 0x17, 0xBD, 0xAF, 0x17 ),\n    BYTES_TO_T_UINT_8( 0x68, 0x44, 0x9B, 0x57, 0x49, 0x44, 0xF5, 0x98 ),\n    BYTES_TO_T_UINT_8( 0xD9, 0x1B, 0x7D, 0x2C, 0xB4, 0x5F, 0x8A, 0x5C ),\n    BYTES_TO_T_UINT_8( 0x04, 0xC0, 0x3B, 0x9A, 0x78, 0x6A, 0x29, 0x39 ),\n    BYTES_TO_T_UINT_2( 0x18, 0x01 ),\n};\nstatic const mbedtls_mpi_uint secp521r1_n[] = {\n    BYTES_TO_T_UINT_8( 0x09, 0x64, 0x38, 0x91, 0x1E, 0xB7, 0x6F, 0xBB ),\n    BYTES_TO_T_UINT_8( 0xAE, 0x47, 0x9C, 0x89, 0xB8, 0xC9, 0xB5, 0x3B ),\n    BYTES_TO_T_UINT_8( 0xD0, 0xA5, 0x09, 0xF7, 0x48, 0x01, 0xCC, 0x7F ),\n    BYTES_TO_T_UINT_8( 0x6B, 0x96, 0x2F, 0xBF, 0x83, 0x87, 0x86, 0x51 ),\n    BYTES_TO_T_UINT_8( 0xFA, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_2( 0xFF, 0x01 ),\n};\n#endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)\nstatic const mbedtls_mpi_uint secp192k1_p[] = {\n    BYTES_TO_T_UINT_8( 0x37, 0xEE, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n};\nstatic const mbedtls_mpi_uint secp192k1_a[] = {\n    BYTES_TO_T_UINT_2( 0x00, 0x00 ),\n};\nstatic const mbedtls_mpi_uint secp192k1_b[] = {\n    BYTES_TO_T_UINT_2( 0x03, 0x00 ),\n};\nstatic const mbedtls_mpi_uint secp192k1_gx[] = {\n    BYTES_TO_T_UINT_8( 0x7D, 0x6C, 0xE0, 0xEA, 0xB1, 0xD1, 0xA5, 0x1D ),\n    BYTES_TO_T_UINT_8( 0x34, 0xF4, 0xB7, 0x80, 0x02, 0x7D, 0xB0, 0x26 ),\n    BYTES_TO_T_UINT_8( 0xAE, 0xE9, 0x57, 0xC0, 0x0E, 0xF1, 0x4F, 0xDB ),\n};\nstatic const mbedtls_mpi_uint secp192k1_gy[] = {\n    BYTES_TO_T_UINT_8( 0x9D, 0x2F, 0x5E, 0xD9, 0x88, 0xAA, 0x82, 0x40 ),\n    BYTES_TO_T_UINT_8( 0x34, 0x86, 0xBE, 0x15, 0xD0, 0x63, 0x41, 0x84 ),\n    BYTES_TO_T_UINT_8( 0xA7, 0x28, 0x56, 0x9C, 0x6D, 0x2F, 0x2F, 0x9B ),\n};\nstatic const mbedtls_mpi_uint secp192k1_n[] = {\n    BYTES_TO_T_UINT_8( 0x8D, 0xFD, 0xDE, 0x74, 0x6A, 0x46, 0x69, 0x0F ),\n    BYTES_TO_T_UINT_8( 0x17, 0xFC, 0xF2, 0x26, 0xFE, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n};\n#endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)\nstatic const mbedtls_mpi_uint secp224k1_p[] = {\n    BYTES_TO_T_UINT_8( 0x6D, 0xE5, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_4( 0xFF, 0xFF, 0xFF, 0xFF ),\n};\nstatic const mbedtls_mpi_uint secp224k1_a[] = {\n    BYTES_TO_T_UINT_2( 0x00, 0x00 ),\n};\nstatic const mbedtls_mpi_uint secp224k1_b[] = {\n    BYTES_TO_T_UINT_2( 0x05, 0x00 ),\n};\nstatic const mbedtls_mpi_uint secp224k1_gx[] = {\n    BYTES_TO_T_UINT_8( 0x5C, 0xA4, 0xB7, 0xB6, 0x0E, 0x65, 0x7E, 0x0F ),\n    BYTES_TO_T_UINT_8( 0xA9, 0x75, 0x70, 0xE4, 0xE9, 0x67, 0xA4, 0x69 ),\n    BYTES_TO_T_UINT_8( 0xA1, 0x28, 0xFC, 0x30, 0xDF, 0x99, 0xF0, 0x4D ),\n    BYTES_TO_T_UINT_4( 0x33, 0x5B, 0x45, 0xA1 ),\n};\nstatic const mbedtls_mpi_uint secp224k1_gy[] = {\n    BYTES_TO_T_UINT_8( 0xA5, 0x61, 0x6D, 0x55, 0xDB, 0x4B, 0xCA, 0xE2 ),\n    BYTES_TO_T_UINT_8( 0x59, 0xBD, 0xB0, 0xC0, 0xF7, 0x19, 0xE3, 0xF7 ),\n    BYTES_TO_T_UINT_8( 0xD6, 0xFB, 0xCA, 0x82, 0x42, 0x34, 0xBA, 0x7F ),\n    BYTES_TO_T_UINT_4( 0xED, 0x9F, 0x08, 0x7E ),\n};\nstatic const mbedtls_mpi_uint secp224k1_n[] = {\n    BYTES_TO_T_UINT_8( 0xF7, 0xB1, 0x9F, 0x76, 0x71, 0xA9, 0xF0, 0xCA ),\n    BYTES_TO_T_UINT_8( 0x84, 0x61, 0xEC, 0xD2, 0xE8, 0xDC, 0x01, 0x00 ),\n    BYTES_TO_T_UINT_8( 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ),\n    BYTES_TO_T_UINT_8( 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 ),\n};\n#endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)\nstatic const mbedtls_mpi_uint secp256k1_p[] = {\n    BYTES_TO_T_UINT_8( 0x2F, 0xFC, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n};\nstatic const mbedtls_mpi_uint secp256k1_a[] = {\n    BYTES_TO_T_UINT_2( 0x00, 0x00 ),\n};\nstatic const mbedtls_mpi_uint secp256k1_b[] = {\n    BYTES_TO_T_UINT_2( 0x07, 0x00 ),\n};\nstatic const mbedtls_mpi_uint secp256k1_gx[] = {\n    BYTES_TO_T_UINT_8( 0x98, 0x17, 0xF8, 0x16, 0x5B, 0x81, 0xF2, 0x59 ),\n    BYTES_TO_T_UINT_8( 0xD9, 0x28, 0xCE, 0x2D, 0xDB, 0xFC, 0x9B, 0x02 ),\n    BYTES_TO_T_UINT_8( 0x07, 0x0B, 0x87, 0xCE, 0x95, 0x62, 0xA0, 0x55 ),\n    BYTES_TO_T_UINT_8( 0xAC, 0xBB, 0xDC, 0xF9, 0x7E, 0x66, 0xBE, 0x79 ),\n};\nstatic const mbedtls_mpi_uint secp256k1_gy[] = {\n    BYTES_TO_T_UINT_8( 0xB8, 0xD4, 0x10, 0xFB, 0x8F, 0xD0, 0x47, 0x9C ),\n    BYTES_TO_T_UINT_8( 0x19, 0x54, 0x85, 0xA6, 0x48, 0xB4, 0x17, 0xFD ),\n    BYTES_TO_T_UINT_8( 0xA8, 0x08, 0x11, 0x0E, 0xFC, 0xFB, 0xA4, 0x5D ),\n    BYTES_TO_T_UINT_8( 0x65, 0xC4, 0xA3, 0x26, 0x77, 0xDA, 0x3A, 0x48 ),\n};\nstatic const mbedtls_mpi_uint secp256k1_n[] = {\n    BYTES_TO_T_UINT_8( 0x41, 0x41, 0x36, 0xD0, 0x8C, 0x5E, 0xD2, 0xBF ),\n    BYTES_TO_T_UINT_8( 0x3B, 0xA0, 0x48, 0xAF, 0xE6, 0xDC, 0xAE, 0xBA ),\n    BYTES_TO_T_UINT_8( 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n    BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ),\n};\n#endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */\n\n/*\n * Domain parameters for brainpoolP256r1 (RFC 5639 3.4)\n */\n#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)\nstatic const mbedtls_mpi_uint brainpoolP256r1_p[] = {\n    BYTES_TO_T_UINT_8( 0x77, 0x53, 0x6E, 0x1F, 0x1D, 0x48, 0x13, 0x20 ),\n    BYTES_TO_T_UINT_8( 0x28, 0x20, 0x26, 0xD5, 0x23, 0xF6, 0x3B, 0x6E ),\n    BYTES_TO_T_UINT_8( 0x72, 0x8D, 0x83, 0x9D, 0x90, 0x0A, 0x66, 0x3E ),\n    BYTES_TO_T_UINT_8( 0xBC, 0xA9, 0xEE, 0xA1, 0xDB, 0x57, 0xFB, 0xA9 ),\n};\nstatic const mbedtls_mpi_uint brainpoolP256r1_a[] = {\n    BYTES_TO_T_UINT_8( 0xD9, 0xB5, 0x30, 0xF3, 0x44, 0x4B, 0x4A, 0xE9 ),\n    BYTES_TO_T_UINT_8( 0x6C, 0x5C, 0xDC, 0x26, 0xC1, 0x55, 0x80, 0xFB ),\n    BYTES_TO_T_UINT_8( 0xE7, 0xFF, 0x7A, 0x41, 0x30, 0x75, 0xF6, 0xEE ),\n    BYTES_TO_T_UINT_8( 0x57, 0x30, 0x2C, 0xFC, 0x75, 0x09, 0x5A, 0x7D ),\n};\nstatic const mbedtls_mpi_uint brainpoolP256r1_b[] = {\n    BYTES_TO_T_UINT_8( 0xB6, 0x07, 0x8C, 0xFF, 0x18, 0xDC, 0xCC, 0x6B ),\n    BYTES_TO_T_UINT_8( 0xCE, 0xE1, 0xF7, 0x5C, 0x29, 0x16, 0x84, 0x95 ),\n    BYTES_TO_T_UINT_8( 0xBF, 0x7C, 0xD7, 0xBB, 0xD9, 0xB5, 0x30, 0xF3 ),\n    BYTES_TO_T_UINT_8( 0x44, 0x4B, 0x4A, 0xE9, 0x6C, 0x5C, 0xDC, 0x26 ),\n};\nstatic const mbedtls_mpi_uint brainpoolP256r1_gx[] = {\n    BYTES_TO_T_UINT_8( 0x62, 0x32, 0xCE, 0x9A, 0xBD, 0x53, 0x44, 0x3A ),\n    BYTES_TO_T_UINT_8( 0xC2, 0x23, 0xBD, 0xE3, 0xE1, 0x27, 0xDE, 0xB9 ),\n    BYTES_TO_T_UINT_8( 0xAF, 0xB7, 0x81, 0xFC, 0x2F, 0x48, 0x4B, 0x2C ),\n    BYTES_TO_T_UINT_8( 0xCB, 0x57, 0x7E, 0xCB, 0xB9, 0xAE, 0xD2, 0x8B ),\n};\nstatic const mbedtls_mpi_uint brainpoolP256r1_gy[] = {\n    BYTES_TO_T_UINT_8( 0x97, 0x69, 0x04, 0x2F, 0xC7, 0x54, 0x1D, 0x5C ),\n    BYTES_TO_T_UINT_8( 0x54, 0x8E, 0xED, 0x2D, 0x13, 0x45, 0x77, 0xC2 ),\n    BYTES_TO_T_UINT_8( 0xC9, 0x1D, 0x61, 0x14, 0x1A, 0x46, 0xF8, 0x97 ),\n    BYTES_TO_T_UINT_8( 0xFD, 0xC4, 0xDA, 0xC3, 0x35, 0xF8, 0x7E, 0x54 ),\n};\nstatic const mbedtls_mpi_uint brainpoolP256r1_n[] = {\n    BYTES_TO_T_UINT_8( 0xA7, 0x56, 0x48, 0x97, 0x82, 0x0E, 0x1E, 0x90 ),\n    BYTES_TO_T_UINT_8( 0xF7, 0xA6, 0x61, 0xB5, 0xA3, 0x7A, 0x39, 0x8C ),\n    BYTES_TO_T_UINT_8( 0x71, 0x8D, 0x83, 0x9D, 0x90, 0x0A, 0x66, 0x3E ),\n    BYTES_TO_T_UINT_8( 0xBC, 0xA9, 0xEE, 0xA1, 0xDB, 0x57, 0xFB, 0xA9 ),\n};\n#endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */\n\n/*\n * Domain parameters for brainpoolP384r1 (RFC 5639 3.6)\n */\n#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)\nstatic const mbedtls_mpi_uint brainpoolP384r1_p[] = {\n    BYTES_TO_T_UINT_8( 0x53, 0xEC, 0x07, 0x31, 0x13, 0x00, 0x47, 0x87 ),\n    BYTES_TO_T_UINT_8( 0x71, 0x1A, 0x1D, 0x90, 0x29, 0xA7, 0xD3, 0xAC ),\n    BYTES_TO_T_UINT_8( 0x23, 0x11, 0xB7, 0x7F, 0x19, 0xDA, 0xB1, 0x12 ),\n    BYTES_TO_T_UINT_8( 0xB4, 0x56, 0x54, 0xED, 0x09, 0x71, 0x2F, 0x15 ),\n    BYTES_TO_T_UINT_8( 0xDF, 0x41, 0xE6, 0x50, 0x7E, 0x6F, 0x5D, 0x0F ),\n    BYTES_TO_T_UINT_8( 0x28, 0x6D, 0x38, 0xA3, 0x82, 0x1E, 0xB9, 0x8C ),\n};\nstatic const mbedtls_mpi_uint brainpoolP384r1_a[] = {\n    BYTES_TO_T_UINT_8( 0x26, 0x28, 0xCE, 0x22, 0xDD, 0xC7, 0xA8, 0x04 ),\n    BYTES_TO_T_UINT_8( 0xEB, 0xD4, 0x3A, 0x50, 0x4A, 0x81, 0xA5, 0x8A ),\n    BYTES_TO_T_UINT_8( 0x0F, 0xF9, 0x91, 0xBA, 0xEF, 0x65, 0x91, 0x13 ),\n    BYTES_TO_T_UINT_8( 0x87, 0x27, 0xB2, 0x4F, 0x8E, 0xA2, 0xBE, 0xC2 ),\n    BYTES_TO_T_UINT_8( 0xA0, 0xAF, 0x05, 0xCE, 0x0A, 0x08, 0x72, 0x3C ),\n    BYTES_TO_T_UINT_8( 0x0C, 0x15, 0x8C, 0x3D, 0xC6, 0x82, 0xC3, 0x7B ),\n};\nstatic const mbedtls_mpi_uint brainpoolP384r1_b[] = {\n    BYTES_TO_T_UINT_8( 0x11, 0x4C, 0x50, 0xFA, 0x96, 0x86, 0xB7, 0x3A ),\n    BYTES_TO_T_UINT_8( 0x94, 0xC9, 0xDB, 0x95, 0x02, 0x39, 0xB4, 0x7C ),\n    BYTES_TO_T_UINT_8( 0xD5, 0x62, 0xEB, 0x3E, 0xA5, 0x0E, 0x88, 0x2E ),\n    BYTES_TO_T_UINT_8( 0xA6, 0xD2, 0xDC, 0x07, 0xE1, 0x7D, 0xB7, 0x2F ),\n    BYTES_TO_T_UINT_8( 0x7C, 0x44, 0xF0, 0x16, 0x54, 0xB5, 0x39, 0x8B ),\n    BYTES_TO_T_UINT_8( 0x26, 0x28, 0xCE, 0x22, 0xDD, 0xC7, 0xA8, 0x04 ),\n};\nstatic const mbedtls_mpi_uint brainpoolP384r1_gx[] = {\n    BYTES_TO_T_UINT_8( 0x1E, 0xAF, 0xD4, 0x47, 0xE2, 0xB2, 0x87, 0xEF ),\n    BYTES_TO_T_UINT_8( 0xAA, 0x46, 0xD6, 0x36, 0x34, 0xE0, 0x26, 0xE8 ),\n    BYTES_TO_T_UINT_8( 0xE8, 0x10, 0xBD, 0x0C, 0xFE, 0xCA, 0x7F, 0xDB ),\n    BYTES_TO_T_UINT_8( 0xE3, 0x4F, 0xF1, 0x7E, 0xE7, 0xA3, 0x47, 0x88 ),\n    BYTES_TO_T_UINT_8( 0x6B, 0x3F, 0xC1, 0xB7, 0x81, 0x3A, 0xA6, 0xA2 ),\n    BYTES_TO_T_UINT_8( 0xFF, 0x45, 0xCF, 0x68, 0xF0, 0x64, 0x1C, 0x1D ),\n};\nstatic const mbedtls_mpi_uint brainpoolP384r1_gy[] = {\n    BYTES_TO_T_UINT_8( 0x15, 0x53, 0x3C, 0x26, 0x41, 0x03, 0x82, 0x42 ),\n    BYTES_TO_T_UINT_8( 0x11, 0x81, 0x91, 0x77, 0x21, 0x46, 0x46, 0x0E ),\n    BYTES_TO_T_UINT_8( 0x28, 0x29, 0x91, 0xF9, 0x4F, 0x05, 0x9C, 0xE1 ),\n    BYTES_TO_T_UINT_8( 0x64, 0x58, 0xEC, 0xFE, 0x29, 0x0B, 0xB7, 0x62 ),\n    BYTES_TO_T_UINT_8( 0x52, 0xD5, 0xCF, 0x95, 0x8E, 0xEB, 0xB1, 0x5C ),\n    BYTES_TO_T_UINT_8( 0xA4, 0xC2, 0xF9, 0x20, 0x75, 0x1D, 0xBE, 0x8A ),\n};\nstatic const mbedtls_mpi_uint brainpoolP384r1_n[] = {\n    BYTES_TO_T_UINT_8( 0x65, 0x65, 0x04, 0xE9, 0x02, 0x32, 0x88, 0x3B ),\n    BYTES_TO_T_UINT_8( 0x10, 0xC3, 0x7F, 0x6B, 0xAF, 0xB6, 0x3A, 0xCF ),\n    BYTES_TO_T_UINT_8( 0xA7, 0x25, 0x04, 0xAC, 0x6C, 0x6E, 0x16, 0x1F ),\n    BYTES_TO_T_UINT_8( 0xB3, 0x56, 0x54, 0xED, 0x09, 0x71, 0x2F, 0x15 ),\n    BYTES_TO_T_UINT_8( 0xDF, 0x41, 0xE6, 0x50, 0x7E, 0x6F, 0x5D, 0x0F ),\n    BYTES_TO_T_UINT_8( 0x28, 0x6D, 0x38, 0xA3, 0x82, 0x1E, 0xB9, 0x8C ),\n};\n#endif /* MBEDTLS_ECP_DP_BP384R1_ENABLED */\n\n/*\n * Domain parameters for brainpoolP512r1 (RFC 5639 3.7)\n */\n#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)\nstatic const mbedtls_mpi_uint brainpoolP512r1_p[] = {\n    BYTES_TO_T_UINT_8( 0xF3, 0x48, 0x3A, 0x58, 0x56, 0x60, 0xAA, 0x28 ),\n    BYTES_TO_T_UINT_8( 0x85, 0xC6, 0x82, 0x2D, 0x2F, 0xFF, 0x81, 0x28 ),\n    BYTES_TO_T_UINT_8( 0xE6, 0x80, 0xA3, 0xE6, 0x2A, 0xA1, 0xCD, 0xAE ),\n    BYTES_TO_T_UINT_8( 0x42, 0x68, 0xC6, 0x9B, 0x00, 0x9B, 0x4D, 0x7D ),\n    BYTES_TO_T_UINT_8( 0x71, 0x08, 0x33, 0x70, 0xCA, 0x9C, 0x63, 0xD6 ),\n    BYTES_TO_T_UINT_8( 0x0E, 0xD2, 0xC9, 0xB3, 0xB3, 0x8D, 0x30, 0xCB ),\n    BYTES_TO_T_UINT_8( 0x07, 0xFC, 0xC9, 0x33, 0xAE, 0xE6, 0xD4, 0x3F ),\n    BYTES_TO_T_UINT_8( 0x8B, 0xC4, 0xE9, 0xDB, 0xB8, 0x9D, 0xDD, 0xAA ),\n};\nstatic const mbedtls_mpi_uint brainpoolP512r1_a[] = {\n    BYTES_TO_T_UINT_8( 0xCA, 0x94, 0xFC, 0x77, 0x4D, 0xAC, 0xC1, 0xE7 ),\n    BYTES_TO_T_UINT_8( 0xB9, 0xC7, 0xF2, 0x2B, 0xA7, 0x17, 0x11, 0x7F ),\n    BYTES_TO_T_UINT_8( 0xB5, 0xC8, 0x9A, 0x8B, 0xC9, 0xF1, 0x2E, 0x0A ),\n    BYTES_TO_T_UINT_8( 0xA1, 0x3A, 0x25, 0xA8, 0x5A, 0x5D, 0xED, 0x2D ),\n    BYTES_TO_T_UINT_8( 0xBC, 0x63, 0x98, 0xEA, 0xCA, 0x41, 0x34, 0xA8 ),\n    BYTES_TO_T_UINT_8( 0x10, 0x16, 0xF9, 0x3D, 0x8D, 0xDD, 0xCB, 0x94 ),\n    BYTES_TO_T_UINT_8( 0xC5, 0x4C, 0x23, 0xAC, 0x45, 0x71, 0x32, 0xE2 ),\n    BYTES_TO_T_UINT_8( 0x89, 0x3B, 0x60, 0x8B, 0x31, 0xA3, 0x30, 0x78 ),\n};\nstatic const mbedtls_mpi_uint brainpoolP512r1_b[] = {\n    BYTES_TO_T_UINT_8( 0x23, 0xF7, 0x16, 0x80, 0x63, 0xBD, 0x09, 0x28 ),\n    BYTES_TO_T_UINT_8( 0xDD, 0xE5, 0xBA, 0x5E, 0xB7, 0x50, 0x40, 0x98 ),\n    BYTES_TO_T_UINT_8( 0x67, 0x3E, 0x08, 0xDC, 0xCA, 0x94, 0xFC, 0x77 ),\n    BYTES_TO_T_UINT_8( 0x4D, 0xAC, 0xC1, 0xE7, 0xB9, 0xC7, 0xF2, 0x2B ),\n    BYTES_TO_T_UINT_8( 0xA7, 0x17, 0x11, 0x7F, 0xB5, 0xC8, 0x9A, 0x8B ),\n    BYTES_TO_T_UINT_8( 0xC9, 0xF1, 0x2E, 0x0A, 0xA1, 0x3A, 0x25, 0xA8 ),\n    BYTES_TO_T_UINT_8( 0x5A, 0x5D, 0xED, 0x2D, 0xBC, 0x63, 0x98, 0xEA ),\n    BYTES_TO_T_UINT_8( 0xCA, 0x41, 0x34, 0xA8, 0x10, 0x16, 0xF9, 0x3D ),\n};\nstatic const mbedtls_mpi_uint brainpoolP512r1_gx[] = {\n    BYTES_TO_T_UINT_8( 0x22, 0xF8, 0xB9, 0xBC, 0x09, 0x22, 0x35, 0x8B ),\n    BYTES_TO_T_UINT_8( 0x68, 0x5E, 0x6A, 0x40, 0x47, 0x50, 0x6D, 0x7C ),\n    BYTES_TO_T_UINT_8( 0x5F, 0x7D, 0xB9, 0x93, 0x7B, 0x68, 0xD1, 0x50 ),\n    BYTES_TO_T_UINT_8( 0x8D, 0xD4, 0xD0, 0xE2, 0x78, 0x1F, 0x3B, 0xFF ),\n    BYTES_TO_T_UINT_8( 0x8E, 0x09, 0xD0, 0xF4, 0xEE, 0x62, 0x3B, 0xB4 ),\n    BYTES_TO_T_UINT_8( 0xC1, 0x16, 0xD9, 0xB5, 0x70, 0x9F, 0xED, 0x85 ),\n    BYTES_TO_T_UINT_8( 0x93, 0x6A, 0x4C, 0x9C, 0x2E, 0x32, 0x21, 0x5A ),\n    BYTES_TO_T_UINT_8( 0x64, 0xD9, 0x2E, 0xD8, 0xBD, 0xE4, 0xAE, 0x81 ),\n};\nstatic const mbedtls_mpi_uint brainpoolP512r1_gy[] = {\n    BYTES_TO_T_UINT_8( 0x92, 0x08, 0xD8, 0x3A, 0x0F, 0x1E, 0xCD, 0x78 ),\n    BYTES_TO_T_UINT_8( 0x06, 0x54, 0xF0, 0xA8, 0x2F, 0x2B, 0xCA, 0xD1 ),\n    BYTES_TO_T_UINT_8( 0xAE, 0x63, 0x27, 0x8A, 0xD8, 0x4B, 0xCA, 0x5B ),\n    BYTES_TO_T_UINT_8( 0x5E, 0x48, 0x5F, 0x4A, 0x49, 0xDE, 0xDC, 0xB2 ),\n    BYTES_TO_T_UINT_8( 0x11, 0x81, 0x1F, 0x88, 0x5B, 0xC5, 0x00, 0xA0 ),\n    BYTES_TO_T_UINT_8( 0x1A, 0x7B, 0xA5, 0x24, 0x00, 0xF7, 0x09, 0xF2 ),\n    BYTES_TO_T_UINT_8( 0xFD, 0x22, 0x78, 0xCF, 0xA9, 0xBF, 0xEA, 0xC0 ),\n    BYTES_TO_T_UINT_8( 0xEC, 0x32, 0x63, 0x56, 0x5D, 0x38, 0xDE, 0x7D ),\n};\nstatic const mbedtls_mpi_uint brainpoolP512r1_n[] = {\n    BYTES_TO_T_UINT_8( 0x69, 0x00, 0xA9, 0x9C, 0x82, 0x96, 0x87, 0xB5 ),\n    BYTES_TO_T_UINT_8( 0xDD, 0xDA, 0x5D, 0x08, 0x81, 0xD3, 0xB1, 0x1D ),\n    BYTES_TO_T_UINT_8( 0x47, 0x10, 0xAC, 0x7F, 0x19, 0x61, 0x86, 0x41 ),\n    BYTES_TO_T_UINT_8( 0x19, 0x26, 0xA9, 0x4C, 0x41, 0x5C, 0x3E, 0x55 ),\n    BYTES_TO_T_UINT_8( 0x70, 0x08, 0x33, 0x70, 0xCA, 0x9C, 0x63, 0xD6 ),\n    BYTES_TO_T_UINT_8( 0x0E, 0xD2, 0xC9, 0xB3, 0xB3, 0x8D, 0x30, 0xCB ),\n    BYTES_TO_T_UINT_8( 0x07, 0xFC, 0xC9, 0x33, 0xAE, 0xE6, 0xD4, 0x3F ),\n    BYTES_TO_T_UINT_8( 0x8B, 0xC4, 0xE9, 0xDB, 0xB8, 0x9D, 0xDD, 0xAA ),\n};\n#endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */\n\n/*\n * Create an MPI from embedded constants\n * (assumes len is an exact multiple of sizeof mbedtls_mpi_uint)\n */\nstatic inline void ecp_mpi_load( mbedtls_mpi *X, const mbedtls_mpi_uint *p, size_t len )\n{\n    X->s = 1;\n    X->n = len / sizeof( mbedtls_mpi_uint );\n    X->p = (mbedtls_mpi_uint *) p;\n}\n\n/*\n * Set an MPI to static value 1\n */\nstatic inline void ecp_mpi_set1( mbedtls_mpi *X )\n{\n    static mbedtls_mpi_uint one[] = { 1 };\n    X->s = 1;\n    X->n = 1;\n    X->p = one;\n}\n\n/*\n * Make group available from embedded constants\n */\nstatic int ecp_group_load( mbedtls_ecp_group *grp,\n                           const mbedtls_mpi_uint *p,  size_t plen,\n                           const mbedtls_mpi_uint *a,  size_t alen,\n                           const mbedtls_mpi_uint *b,  size_t blen,\n                           const mbedtls_mpi_uint *gx, size_t gxlen,\n                           const mbedtls_mpi_uint *gy, size_t gylen,\n                           const mbedtls_mpi_uint *n,  size_t nlen)\n{\n    ecp_mpi_load( &grp->P, p, plen );\n    if( a != NULL )\n        ecp_mpi_load( &grp->A, a, alen );\n    ecp_mpi_load( &grp->B, b, blen );\n    ecp_mpi_load( &grp->N, n, nlen );\n\n    ecp_mpi_load( &grp->G.X, gx, gxlen );\n    ecp_mpi_load( &grp->G.Y, gy, gylen );\n    ecp_mpi_set1( &grp->G.Z );\n\n    grp->pbits = mbedtls_mpi_bitlen( &grp->P );\n    grp->nbits = mbedtls_mpi_bitlen( &grp->N );\n\n    grp->h = 1;\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_ECP_NIST_OPTIM)\n/* Forward declarations */\n#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)\nstatic int ecp_mod_p192( mbedtls_mpi * );\n#endif\n#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)\nstatic int ecp_mod_p224( mbedtls_mpi * );\n#endif\n#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)\nstatic int ecp_mod_p256( mbedtls_mpi * );\n#endif\n#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)\nstatic int ecp_mod_p384( mbedtls_mpi * );\n#endif\n#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)\nstatic int ecp_mod_p521( mbedtls_mpi * );\n#endif\n\n#define NIST_MODP( P )      grp->modp = ecp_mod_ ## P;\n#else\n#define NIST_MODP( P )\n#endif /* MBEDTLS_ECP_NIST_OPTIM */\n\n/* Additional forward declarations */\n#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)\nstatic int ecp_mod_p255( mbedtls_mpi * );\n#endif\n#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)\nstatic int ecp_mod_p448( mbedtls_mpi * );\n#endif\n#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)\nstatic int ecp_mod_p192k1( mbedtls_mpi * );\n#endif\n#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)\nstatic int ecp_mod_p224k1( mbedtls_mpi * );\n#endif\n#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)\nstatic int ecp_mod_p256k1( mbedtls_mpi * );\n#endif\n\n#define LOAD_GROUP_A( G )   ecp_group_load( grp,            \\\n                            G ## _p,  sizeof( G ## _p  ),   \\\n                            G ## _a,  sizeof( G ## _a  ),   \\\n                            G ## _b,  sizeof( G ## _b  ),   \\\n                            G ## _gx, sizeof( G ## _gx ),   \\\n                            G ## _gy, sizeof( G ## _gy ),   \\\n                            G ## _n,  sizeof( G ## _n  ) )\n\n#define LOAD_GROUP( G )     ecp_group_load( grp,            \\\n                            G ## _p,  sizeof( G ## _p  ),   \\\n                            NULL,     0,                    \\\n                            G ## _b,  sizeof( G ## _b  ),   \\\n                            G ## _gx, sizeof( G ## _gx ),   \\\n                            G ## _gy, sizeof( G ## _gy ),   \\\n                            G ## _n,  sizeof( G ## _n  ) )\n\n#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)\n/*\n * Specialized function for creating the Curve25519 group\n */\nstatic int ecp_use_curve25519( mbedtls_ecp_group *grp )\n{\n    int ret;\n\n    /* Actually ( A + 2 ) / 4 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &grp->A, 16, \"01DB42\" ) );\n\n    /* P = 2^255 - 19 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->P, 1 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &grp->P, 255 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &grp->P, &grp->P, 19 ) );\n    grp->pbits = mbedtls_mpi_bitlen( &grp->P );\n\n    /* N = 2^252 + 27742317777372353535851937790883648493 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &grp->N, 16,\n                                              \"14DEF9DEA2F79CD65812631A5CF5D3ED\" ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &grp->N, 252, 1 ) );\n\n    /* Y intentionally not set, since we use x/z coordinates.\n     * This is used as a marker to identify Montgomery curves! */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->G.X, 9 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->G.Z, 1 ) );\n    mbedtls_mpi_free( &grp->G.Y );\n\n    /* Actually, the required msb for private keys */\n    grp->nbits = 254;\n\ncleanup:\n    if( ret != 0 )\n        mbedtls_ecp_group_free( grp );\n\n    return( ret );\n}\n#endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)\n/*\n * Specialized function for creating the Curve448 group\n */\nstatic int ecp_use_curve448( mbedtls_ecp_group *grp )\n{\n    mbedtls_mpi Ns;\n    int ret;\n\n    mbedtls_mpi_init( &Ns );\n\n    /* Actually ( A + 2 ) / 4 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &grp->A, 16, \"98AA\" ) );\n\n    /* P = 2^448 - 2^224 - 1 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->P, 1 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &grp->P, 224 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &grp->P, &grp->P, 1 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &grp->P, 224 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &grp->P, &grp->P, 1 ) );\n    grp->pbits = mbedtls_mpi_bitlen( &grp->P );\n\n    /* Y intentionally not set, since we use x/z coordinates.\n     * This is used as a marker to identify Montgomery curves! */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->G.X, 5 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->G.Z, 1 ) );\n    mbedtls_mpi_free( &grp->G.Y );\n\n    /* N = 2^446 - 13818066809895115352007386748515426880336692474882178609894547503885 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &grp->N, 446, 1 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &Ns, 16,\n                                              \"8335DC163BB124B65129C96FDE933D8D723A70AADC873D6D54A7BB0D\" ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &grp->N, &grp->N, &Ns ) );\n\n    /* Actually, the required msb for private keys */\n    grp->nbits = 447;\n\ncleanup:\n    mbedtls_mpi_free( &Ns );\n    if( ret != 0 )\n        mbedtls_ecp_group_free( grp );\n\n    return( ret );\n}\n#endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */\n\n/*\n * Set a group using well-known domain parameters\n */\nint mbedtls_ecp_group_load( mbedtls_ecp_group *grp, mbedtls_ecp_group_id id )\n{\n    mbedtls_ecp_group_free( grp );\n\n    grp->id = id;\n\n    switch( id )\n    {\n#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)\n        case MBEDTLS_ECP_DP_SECP192R1:\n            NIST_MODP( p192 );\n            return( LOAD_GROUP( secp192r1 ) );\n#endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)\n        case MBEDTLS_ECP_DP_SECP224R1:\n            NIST_MODP( p224 );\n            return( LOAD_GROUP( secp224r1 ) );\n#endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)\n        case MBEDTLS_ECP_DP_SECP256R1:\n            NIST_MODP( p256 );\n            return( LOAD_GROUP( secp256r1 ) );\n#endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)\n        case MBEDTLS_ECP_DP_SECP384R1:\n            NIST_MODP( p384 );\n            return( LOAD_GROUP( secp384r1 ) );\n#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)\n        case MBEDTLS_ECP_DP_SECP521R1:\n            NIST_MODP( p521 );\n            return( LOAD_GROUP( secp521r1 ) );\n#endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)\n        case MBEDTLS_ECP_DP_SECP192K1:\n            grp->modp = ecp_mod_p192k1;\n            return( LOAD_GROUP_A( secp192k1 ) );\n#endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)\n        case MBEDTLS_ECP_DP_SECP224K1:\n            grp->modp = ecp_mod_p224k1;\n            return( LOAD_GROUP_A( secp224k1 ) );\n#endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)\n        case MBEDTLS_ECP_DP_SECP256K1:\n            grp->modp = ecp_mod_p256k1;\n            return( LOAD_GROUP_A( secp256k1 ) );\n#endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)\n        case MBEDTLS_ECP_DP_BP256R1:\n            return( LOAD_GROUP_A( brainpoolP256r1 ) );\n#endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)\n        case MBEDTLS_ECP_DP_BP384R1:\n            return( LOAD_GROUP_A( brainpoolP384r1 ) );\n#endif /* MBEDTLS_ECP_DP_BP384R1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)\n        case MBEDTLS_ECP_DP_BP512R1:\n            return( LOAD_GROUP_A( brainpoolP512r1 ) );\n#endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)\n        case MBEDTLS_ECP_DP_CURVE25519:\n            grp->modp = ecp_mod_p255;\n            return( ecp_use_curve25519( grp ) );\n#endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)\n        case MBEDTLS_ECP_DP_CURVE448:\n            grp->modp = ecp_mod_p448;\n            return( ecp_use_curve448( grp ) );\n#endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */\n\n        default:\n            mbedtls_ecp_group_free( grp );\n            return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );\n    }\n}\n\n#if defined(MBEDTLS_ECP_NIST_OPTIM)\n/*\n * Fast reduction modulo the primes used by the NIST curves.\n *\n * These functions are critical for speed, but not needed for correct\n * operations. So, we make the choice to heavily rely on the internals of our\n * bignum library, which creates a tight coupling between these functions and\n * our MPI implementation.  However, the coupling between the ECP module and\n * MPI remains loose, since these functions can be deactivated at will.\n */\n\n#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)\n/*\n * Compared to the way things are presented in FIPS 186-3 D.2,\n * we proceed in columns, from right (least significant chunk) to left,\n * adding chunks to N in place, and keeping a carry for the next chunk.\n * This avoids moving things around in memory, and uselessly adding zeros,\n * compared to the more straightforward, line-oriented approach.\n *\n * For this prime we need to handle data in chunks of 64 bits.\n * Since this is always a multiple of our basic mbedtls_mpi_uint, we can\n * use a mbedtls_mpi_uint * to designate such a chunk, and small loops to handle it.\n */\n\n/* Add 64-bit chunks (dst += src) and update carry */\nstatic inline void add64( mbedtls_mpi_uint *dst, mbedtls_mpi_uint *src, mbedtls_mpi_uint *carry )\n{\n    unsigned char i;\n    mbedtls_mpi_uint c = 0;\n    for( i = 0; i < 8 / sizeof( mbedtls_mpi_uint ); i++, dst++, src++ )\n    {\n        *dst += c;      c  = ( *dst < c );\n        *dst += *src;   c += ( *dst < *src );\n    }\n    *carry += c;\n}\n\n/* Add carry to a 64-bit chunk and update carry */\nstatic inline void carry64( mbedtls_mpi_uint *dst, mbedtls_mpi_uint *carry )\n{\n    unsigned char i;\n    for( i = 0; i < 8 / sizeof( mbedtls_mpi_uint ); i++, dst++ )\n    {\n        *dst += *carry;\n        *carry  = ( *dst < *carry );\n    }\n}\n\n#define WIDTH       8 / sizeof( mbedtls_mpi_uint )\n#define A( i )      N->p + i * WIDTH\n#define ADD( i )    add64( p, A( i ), &c )\n#define NEXT        p += WIDTH; carry64( p, &c )\n#define LAST        p += WIDTH; *p = c; while( ++p < end ) *p = 0\n\n/*\n * Fast quasi-reduction modulo p192 (FIPS 186-3 D.2.1)\n */\nstatic int ecp_mod_p192( mbedtls_mpi *N )\n{\n    int ret;\n    mbedtls_mpi_uint c = 0;\n    mbedtls_mpi_uint *p, *end;\n\n    /* Make sure we have enough blocks so that A(5) is legal */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_grow( N, 6 * WIDTH ) );\n\n    p = N->p;\n    end = p + N->n;\n\n    ADD( 3 ); ADD( 5 );             NEXT; // A0 += A3 + A5\n    ADD( 3 ); ADD( 4 ); ADD( 5 );   NEXT; // A1 += A3 + A4 + A5\n    ADD( 4 ); ADD( 5 );             LAST; // A2 += A4 + A5\n\ncleanup:\n    return( ret );\n}\n\n#undef WIDTH\n#undef A\n#undef ADD\n#undef NEXT\n#undef LAST\n#endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) ||   \\\n    defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) ||   \\\n    defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)\n/*\n * The reader is advised to first understand ecp_mod_p192() since the same\n * general structure is used here, but with additional complications:\n * (1) chunks of 32 bits, and (2) subtractions.\n */\n\n/*\n * For these primes, we need to handle data in chunks of 32 bits.\n * This makes it more complicated if we use 64 bits limbs in MPI,\n * which prevents us from using a uniform access method as for p192.\n *\n * So, we define a mini abstraction layer to access 32 bit chunks,\n * load them in 'cur' for work, and store them back from 'cur' when done.\n *\n * While at it, also define the size of N in terms of 32-bit chunks.\n */\n#define LOAD32      cur = A( i );\n\n#if defined(MBEDTLS_HAVE_INT32)  /* 32 bit */\n\n#define MAX32       N->n\n#define A( j )      N->p[j]\n#define STORE32     N->p[i] = cur;\n\n#else                               /* 64-bit */\n\n#define MAX32       N->n * 2\n#define A( j ) j % 2 ? (uint32_t)( N->p[j/2] >> 32 ) : (uint32_t)( N->p[j/2] )\n#define STORE32                                   \\\n    if( i % 2 ) {                                 \\\n        N->p[i/2] &= 0x00000000FFFFFFFF;          \\\n        N->p[i/2] |= ((mbedtls_mpi_uint) cur) << 32;        \\\n    } else {                                      \\\n        N->p[i/2] &= 0xFFFFFFFF00000000;          \\\n        N->p[i/2] |= (mbedtls_mpi_uint) cur;                \\\n    }\n\n#endif /* sizeof( mbedtls_mpi_uint ) */\n\n/*\n * Helpers for addition and subtraction of chunks, with signed carry.\n */\nstatic inline void add32( uint32_t *dst, uint32_t src, signed char *carry )\n{\n    *dst += src;\n    *carry += ( *dst < src );\n}\n\nstatic inline void sub32( uint32_t *dst, uint32_t src, signed char *carry )\n{\n    *carry -= ( *dst < src );\n    *dst -= src;\n}\n\n#define ADD( j )    add32( &cur, A( j ), &c );\n#define SUB( j )    sub32( &cur, A( j ), &c );\n\n/*\n * Helpers for the main 'loop'\n * (see fix_negative for the motivation of C)\n */\n#define INIT( b )                                           \\\n    int ret;                                                \\\n    signed char c = 0, cc;                                  \\\n    uint32_t cur;                                           \\\n    size_t i = 0, bits = b;                                 \\\n    mbedtls_mpi C;                                                  \\\n    mbedtls_mpi_uint Cp[ b / 8 / sizeof( mbedtls_mpi_uint) + 1 ];               \\\n                                                            \\\n    C.s = 1;                                                \\\n    C.n = b / 8 / sizeof( mbedtls_mpi_uint) + 1;                      \\\n    C.p = Cp;                                               \\\n    memset( Cp, 0, C.n * sizeof( mbedtls_mpi_uint ) );                \\\n                                                            \\\n    MBEDTLS_MPI_CHK( mbedtls_mpi_grow( N, b * 2 / 8 / sizeof( mbedtls_mpi_uint ) ) ); \\\n    LOAD32;\n\n#define NEXT                    \\\n    STORE32; i++; LOAD32;       \\\n    cc = c; c = 0;              \\\n    if( cc < 0 )                \\\n        sub32( &cur, -cc, &c ); \\\n    else                        \\\n        add32( &cur, cc, &c );  \\\n\n#define LAST                                    \\\n    STORE32; i++;                               \\\n    cur = c > 0 ? c : 0; STORE32;               \\\n    cur = 0; while( ++i < MAX32 ) { STORE32; }  \\\n    if( c < 0 ) fix_negative( N, c, &C, bits );\n\n/*\n * If the result is negative, we get it in the form\n * c * 2^(bits + 32) + N, with c negative and N positive shorter than 'bits'\n */\nstatic inline int fix_negative( mbedtls_mpi *N, signed char c, mbedtls_mpi *C, size_t bits )\n{\n    int ret;\n\n    /* C = - c * 2^(bits + 32) */\n#if !defined(MBEDTLS_HAVE_INT64)\n    ((void) bits);\n#else\n    if( bits == 224 )\n        C->p[ C->n - 1 ] = ((mbedtls_mpi_uint) -c) << 32;\n    else\n#endif\n        C->p[ C->n - 1 ] = (mbedtls_mpi_uint) -c;\n\n    /* N = - ( C - N ) */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( N, C, N ) );\n    N->s = -1;\n\ncleanup:\n\n    return( ret );\n}\n\n#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)\n/*\n * Fast quasi-reduction modulo p224 (FIPS 186-3 D.2.2)\n */\nstatic int ecp_mod_p224( mbedtls_mpi *N )\n{\n    INIT( 224 );\n\n    SUB(  7 ); SUB( 11 );               NEXT; // A0 += -A7 - A11\n    SUB(  8 ); SUB( 12 );               NEXT; // A1 += -A8 - A12\n    SUB(  9 ); SUB( 13 );               NEXT; // A2 += -A9 - A13\n    SUB( 10 ); ADD(  7 ); ADD( 11 );    NEXT; // A3 += -A10 + A7 + A11\n    SUB( 11 ); ADD(  8 ); ADD( 12 );    NEXT; // A4 += -A11 + A8 + A12\n    SUB( 12 ); ADD(  9 ); ADD( 13 );    NEXT; // A5 += -A12 + A9 + A13\n    SUB( 13 ); ADD( 10 );               LAST; // A6 += -A13 + A10\n\ncleanup:\n    return( ret );\n}\n#endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)\n/*\n * Fast quasi-reduction modulo p256 (FIPS 186-3 D.2.3)\n */\nstatic int ecp_mod_p256( mbedtls_mpi *N )\n{\n    INIT( 256 );\n\n    ADD(  8 ); ADD(  9 );\n    SUB( 11 ); SUB( 12 ); SUB( 13 ); SUB( 14 );             NEXT; // A0\n\n    ADD(  9 ); ADD( 10 );\n    SUB( 12 ); SUB( 13 ); SUB( 14 ); SUB( 15 );             NEXT; // A1\n\n    ADD( 10 ); ADD( 11 );\n    SUB( 13 ); SUB( 14 ); SUB( 15 );                        NEXT; // A2\n\n    ADD( 11 ); ADD( 11 ); ADD( 12 ); ADD( 12 ); ADD( 13 );\n    SUB( 15 ); SUB(  8 ); SUB(  9 );                        NEXT; // A3\n\n    ADD( 12 ); ADD( 12 ); ADD( 13 ); ADD( 13 ); ADD( 14 );\n    SUB(  9 ); SUB( 10 );                                   NEXT; // A4\n\n    ADD( 13 ); ADD( 13 ); ADD( 14 ); ADD( 14 ); ADD( 15 );\n    SUB( 10 ); SUB( 11 );                                   NEXT; // A5\n\n    ADD( 14 ); ADD( 14 ); ADD( 15 ); ADD( 15 ); ADD( 14 ); ADD( 13 );\n    SUB(  8 ); SUB(  9 );                                   NEXT; // A6\n\n    ADD( 15 ); ADD( 15 ); ADD( 15 ); ADD( 8 );\n    SUB( 10 ); SUB( 11 ); SUB( 12 ); SUB( 13 );             LAST; // A7\n\ncleanup:\n    return( ret );\n}\n#endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)\n/*\n * Fast quasi-reduction modulo p384 (FIPS 186-3 D.2.4)\n */\nstatic int ecp_mod_p384( mbedtls_mpi *N )\n{\n    INIT( 384 );\n\n    ADD( 12 ); ADD( 21 ); ADD( 20 );\n    SUB( 23 );                                              NEXT; // A0\n\n    ADD( 13 ); ADD( 22 ); ADD( 23 );\n    SUB( 12 ); SUB( 20 );                                   NEXT; // A2\n\n    ADD( 14 ); ADD( 23 );\n    SUB( 13 ); SUB( 21 );                                   NEXT; // A2\n\n    ADD( 15 ); ADD( 12 ); ADD( 20 ); ADD( 21 );\n    SUB( 14 ); SUB( 22 ); SUB( 23 );                        NEXT; // A3\n\n    ADD( 21 ); ADD( 21 ); ADD( 16 ); ADD( 13 ); ADD( 12 ); ADD( 20 ); ADD( 22 );\n    SUB( 15 ); SUB( 23 ); SUB( 23 );                        NEXT; // A4\n\n    ADD( 22 ); ADD( 22 ); ADD( 17 ); ADD( 14 ); ADD( 13 ); ADD( 21 ); ADD( 23 );\n    SUB( 16 );                                              NEXT; // A5\n\n    ADD( 23 ); ADD( 23 ); ADD( 18 ); ADD( 15 ); ADD( 14 ); ADD( 22 );\n    SUB( 17 );                                              NEXT; // A6\n\n    ADD( 19 ); ADD( 16 ); ADD( 15 ); ADD( 23 );\n    SUB( 18 );                                              NEXT; // A7\n\n    ADD( 20 ); ADD( 17 ); ADD( 16 );\n    SUB( 19 );                                              NEXT; // A8\n\n    ADD( 21 ); ADD( 18 ); ADD( 17 );\n    SUB( 20 );                                              NEXT; // A9\n\n    ADD( 22 ); ADD( 19 ); ADD( 18 );\n    SUB( 21 );                                              NEXT; // A10\n\n    ADD( 23 ); ADD( 20 ); ADD( 19 );\n    SUB( 22 );                                              LAST; // A11\n\ncleanup:\n    return( ret );\n}\n#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */\n\n#undef A\n#undef LOAD32\n#undef STORE32\n#undef MAX32\n#undef INIT\n#undef NEXT\n#undef LAST\n\n#endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED ||\n          MBEDTLS_ECP_DP_SECP256R1_ENABLED ||\n          MBEDTLS_ECP_DP_SECP384R1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)\n/*\n * Here we have an actual Mersenne prime, so things are more straightforward.\n * However, chunks are aligned on a 'weird' boundary (521 bits).\n */\n\n/* Size of p521 in terms of mbedtls_mpi_uint */\n#define P521_WIDTH      ( 521 / 8 / sizeof( mbedtls_mpi_uint ) + 1 )\n\n/* Bits to keep in the most significant mbedtls_mpi_uint */\n#define P521_MASK       0x01FF\n\n/*\n * Fast quasi-reduction modulo p521 (FIPS 186-3 D.2.5)\n * Write N as A1 + 2^521 A0, return A0 + A1\n */\nstatic int ecp_mod_p521( mbedtls_mpi *N )\n{\n    int ret;\n    size_t i;\n    mbedtls_mpi M;\n    mbedtls_mpi_uint Mp[P521_WIDTH + 1];\n    /* Worst case for the size of M is when mbedtls_mpi_uint is 16 bits:\n     * we need to hold bits 513 to 1056, which is 34 limbs, that is\n     * P521_WIDTH + 1. Otherwise P521_WIDTH is enough. */\n\n    if( N->n < P521_WIDTH )\n        return( 0 );\n\n    /* M = A1 */\n    M.s = 1;\n    M.n = N->n - ( P521_WIDTH - 1 );\n    if( M.n > P521_WIDTH + 1 )\n        M.n = P521_WIDTH + 1;\n    M.p = Mp;\n    memcpy( Mp, N->p + P521_WIDTH - 1, M.n * sizeof( mbedtls_mpi_uint ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &M, 521 % ( 8 * sizeof( mbedtls_mpi_uint ) ) ) );\n\n    /* N = A0 */\n    N->p[P521_WIDTH - 1] &= P521_MASK;\n    for( i = P521_WIDTH; i < N->n; i++ )\n        N->p[i] = 0;\n\n    /* N = A0 + A1 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( N, N, &M ) );\n\ncleanup:\n    return( ret );\n}\n\n#undef P521_WIDTH\n#undef P521_MASK\n#endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */\n\n#endif /* MBEDTLS_ECP_NIST_OPTIM */\n\n#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)\n\n/* Size of p255 in terms of mbedtls_mpi_uint */\n#define P255_WIDTH      ( 255 / 8 / sizeof( mbedtls_mpi_uint ) + 1 )\n\n/*\n * Fast quasi-reduction modulo p255 = 2^255 - 19\n * Write N as A0 + 2^255 A1, return A0 + 19 * A1\n */\nstatic int ecp_mod_p255( mbedtls_mpi *N )\n{\n    int ret;\n    size_t i;\n    mbedtls_mpi M;\n    mbedtls_mpi_uint Mp[P255_WIDTH + 2];\n\n    if( N->n < P255_WIDTH )\n        return( 0 );\n\n    /* M = A1 */\n    M.s = 1;\n    M.n = N->n - ( P255_WIDTH - 1 );\n    if( M.n > P255_WIDTH + 1 )\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n    M.p = Mp;\n    memset( Mp, 0, sizeof Mp );\n    memcpy( Mp, N->p + P255_WIDTH - 1, M.n * sizeof( mbedtls_mpi_uint ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &M, 255 % ( 8 * sizeof( mbedtls_mpi_uint ) ) ) );\n    M.n++; /* Make room for multiplication by 19 */\n\n    /* N = A0 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( N, 255, 0 ) );\n    for( i = P255_WIDTH; i < N->n; i++ )\n        N->p[i] = 0;\n\n    /* N = A0 + 19 * A1 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &M, &M, 19 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( N, N, &M ) );\n\ncleanup:\n    return( ret );\n}\n#endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)\n\n/* Size of p448 in terms of mbedtls_mpi_uint */\n#define P448_WIDTH      ( 448 / 8 / sizeof( mbedtls_mpi_uint ) )\n\n/* Number of limbs fully occupied by 2^224 (max), and limbs used by it (min) */\n#define DIV_ROUND_UP( X, Y ) ( ( ( X ) + ( Y ) - 1 ) / ( Y ) )\n#define P224_WIDTH_MIN   ( 28 / sizeof( mbedtls_mpi_uint ) )\n#define P224_WIDTH_MAX   DIV_ROUND_UP( 28, sizeof( mbedtls_mpi_uint ) )\n#define P224_UNUSED_BITS ( ( P224_WIDTH_MAX * sizeof( mbedtls_mpi_uint ) * 8 ) - 224 )\n\n/*\n * Fast quasi-reduction modulo p448 = 2^448 - 2^224 - 1\n * Write N as A0 + 2^448 A1 and A1 as B0 + 2^224 B1, and return\n * A0 + A1 + B1 + (B0 + B1) * 2^224.  This is different to the reference\n * implementation of Curve448, which uses its own special 56-bit limbs rather\n * than a generic bignum library.  We could squeeze some extra speed out on\n * 32-bit machines by splitting N up into 32-bit limbs and doing the\n * arithmetic using the limbs directly as we do for the NIST primes above,\n * but for 64-bit targets it should use half the number of operations if we do\n * the reduction with 224-bit limbs, since mpi_add_mpi will then use 64-bit adds.\n */\nstatic int ecp_mod_p448( mbedtls_mpi *N )\n{\n    int ret;\n    size_t i;\n    mbedtls_mpi M, Q;\n    mbedtls_mpi_uint Mp[P448_WIDTH + 1], Qp[P448_WIDTH];\n\n    if( N->n <= P448_WIDTH )\n        return( 0 );\n\n    /* M = A1 */\n    M.s = 1;\n    M.n = N->n - ( P448_WIDTH );\n    if( M.n > P448_WIDTH )\n        /* Shouldn't be called with N larger than 2^896! */\n        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );\n    M.p = Mp;\n    memset( Mp, 0, sizeof( Mp ) );\n    memcpy( Mp, N->p + P448_WIDTH, M.n * sizeof( mbedtls_mpi_uint ) );\n\n    /* N = A0 */\n    for( i = P448_WIDTH; i < N->n; i++ )\n        N->p[i] = 0;\n\n    /* N += A1 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( N, N, &M ) );\n\n    /* Q = B1, N += B1 */\n    Q = M;\n    Q.p = Qp;\n    memcpy( Qp, Mp, sizeof( Qp ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &Q, 224 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( N, N, &Q ) );\n\n    /* M = (B0 + B1) * 2^224, N += M */\n    if( sizeof( mbedtls_mpi_uint ) > 4 )\n        Mp[P224_WIDTH_MIN] &= ( (mbedtls_mpi_uint)-1 ) >> ( P224_UNUSED_BITS );\n    for( i = P224_WIDTH_MAX; i < M.n; ++i )\n        Mp[i] = 0;\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &M, &M, &Q ) );\n    M.n = P448_WIDTH + 1; /* Make room for shifted carry bit from the addition */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &M, 224 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( N, N, &M ) );\n\ncleanup:\n    return( ret );\n}\n#endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) ||   \\\n    defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) ||   \\\n    defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)\n/*\n * Fast quasi-reduction modulo P = 2^s - R,\n * with R about 33 bits, used by the Koblitz curves.\n *\n * Write N as A0 + 2^224 A1, return A0 + R * A1.\n * Actually do two passes, since R is big.\n */\n#define P_KOBLITZ_MAX   ( 256 / 8 / sizeof( mbedtls_mpi_uint ) )  // Max limbs in P\n#define P_KOBLITZ_R     ( 8 / sizeof( mbedtls_mpi_uint ) )        // Limbs in R\nstatic inline int ecp_mod_koblitz( mbedtls_mpi *N, mbedtls_mpi_uint *Rp, size_t p_limbs,\n                                   size_t adjust, size_t shift, mbedtls_mpi_uint mask )\n{\n    int ret;\n    size_t i;\n    mbedtls_mpi M, R;\n    mbedtls_mpi_uint Mp[P_KOBLITZ_MAX + P_KOBLITZ_R + 1];\n\n    if( N->n < p_limbs )\n        return( 0 );\n\n    /* Init R */\n    R.s = 1;\n    R.p = Rp;\n    R.n = P_KOBLITZ_R;\n\n    /* Common setup for M */\n    M.s = 1;\n    M.p = Mp;\n\n    /* M = A1 */\n    M.n = N->n - ( p_limbs - adjust );\n    if( M.n > p_limbs + adjust )\n        M.n = p_limbs + adjust;\n    memset( Mp, 0, sizeof Mp );\n    memcpy( Mp, N->p + p_limbs - adjust, M.n * sizeof( mbedtls_mpi_uint ) );\n    if( shift != 0 )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &M, shift ) );\n    M.n += R.n; /* Make room for multiplication by R */\n\n    /* N = A0 */\n    if( mask != 0 )\n        N->p[p_limbs - 1] &= mask;\n    for( i = p_limbs; i < N->n; i++ )\n        N->p[i] = 0;\n\n    /* N = A0 + R * A1 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &M, &M, &R ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( N, N, &M ) );\n\n    /* Second pass */\n\n    /* M = A1 */\n    M.n = N->n - ( p_limbs - adjust );\n    if( M.n > p_limbs + adjust )\n        M.n = p_limbs + adjust;\n    memset( Mp, 0, sizeof Mp );\n    memcpy( Mp, N->p + p_limbs - adjust, M.n * sizeof( mbedtls_mpi_uint ) );\n    if( shift != 0 )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &M, shift ) );\n    M.n += R.n; /* Make room for multiplication by R */\n\n    /* N = A0 */\n    if( mask != 0 )\n        N->p[p_limbs - 1] &= mask;\n    for( i = p_limbs; i < N->n; i++ )\n        N->p[i] = 0;\n\n    /* N = A0 + R * A1 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &M, &M, &R ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( N, N, &M ) );\n\ncleanup:\n    return( ret );\n}\n#endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED) ||\n          MBEDTLS_ECP_DP_SECP224K1_ENABLED) ||\n          MBEDTLS_ECP_DP_SECP256K1_ENABLED) */\n\n#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)\n/*\n * Fast quasi-reduction modulo p192k1 = 2^192 - R,\n * with R = 2^32 + 2^12 + 2^8 + 2^7 + 2^6 + 2^3 + 1 = 0x0100001119\n */\nstatic int ecp_mod_p192k1( mbedtls_mpi *N )\n{\n    static mbedtls_mpi_uint Rp[] = {\n        BYTES_TO_T_UINT_8( 0xC9, 0x11, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 ) };\n\n    return( ecp_mod_koblitz( N, Rp, 192 / 8 / sizeof( mbedtls_mpi_uint ), 0, 0, 0 ) );\n}\n#endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)\n/*\n * Fast quasi-reduction modulo p224k1 = 2^224 - R,\n * with R = 2^32 + 2^12 + 2^11 + 2^9 + 2^7 + 2^4 + 2 + 1 = 0x0100001A93\n */\nstatic int ecp_mod_p224k1( mbedtls_mpi *N )\n{\n    static mbedtls_mpi_uint Rp[] = {\n        BYTES_TO_T_UINT_8( 0x93, 0x1A, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 ) };\n\n#if defined(MBEDTLS_HAVE_INT64)\n    return( ecp_mod_koblitz( N, Rp, 4, 1, 32, 0xFFFFFFFF ) );\n#else\n    return( ecp_mod_koblitz( N, Rp, 224 / 8 / sizeof( mbedtls_mpi_uint ), 0, 0, 0 ) );\n#endif\n}\n\n#endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */\n\n#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)\n/*\n * Fast quasi-reduction modulo p256k1 = 2^256 - R,\n * with R = 2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1 = 0x01000003D1\n */\nstatic int ecp_mod_p256k1( mbedtls_mpi *N )\n{\n    static mbedtls_mpi_uint Rp[] = {\n        BYTES_TO_T_UINT_8( 0xD1, 0x03, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 ) };\n    return( ecp_mod_koblitz( N, Rp, 256 / 8 / sizeof( mbedtls_mpi_uint ), 0, 0, 0 ) );\n}\n#endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */\n\n#endif /* !MBEDTLS_ECP_ALT */\n\n#endif /* MBEDTLS_ECP_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/entropy.c",
    "content": "/*\n *  Entropy accumulator implementation\n *\n *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_ENTROPY_C)\n\n#if defined(MBEDTLS_TEST_NULL_ENTROPY)\n#warning \"**** WARNING!  MBEDTLS_TEST_NULL_ENTROPY defined! \"\n#warning \"**** THIS BUILD HAS NO DEFINED ENTROPY SOURCES \"\n#warning \"**** THIS BUILD IS *NOT* SUITABLE FOR PRODUCTION USE \"\n#endif\n\n#include \"mbedtls/entropy.h\"\n#include \"mbedtls/entropy_poll.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_FS_IO)\n#include <stdio.h>\n#endif\n\n#if defined(MBEDTLS_ENTROPY_NV_SEED)\n#include \"mbedtls/platform.h\"\n#endif\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf     printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if defined(MBEDTLS_HAVEGE_C)\n#include \"mbedtls/havege.h\"\n#endif\n\n#define ENTROPY_MAX_LOOP    256     /**< Maximum amount to loop before error */\n\nvoid mbedtls_entropy_init( mbedtls_entropy_context *ctx )\n{\n    ctx->source_count = 0;\n    memset( ctx->source, 0, sizeof( ctx->source ) );\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_mutex_init( &ctx->mutex );\n#endif\n\n    ctx->accumulator_started = 0;\n#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)\n    mbedtls_sha512_init( &ctx->accumulator );\n#else\n    mbedtls_sha256_init( &ctx->accumulator );\n#endif\n#if defined(MBEDTLS_HAVEGE_C)\n    mbedtls_havege_init( &ctx->havege_data );\n#endif\n\n    /* Reminder: Update ENTROPY_HAVE_STRONG in the test files\n     *           when adding more strong entropy sources here. */\n\n#if defined(MBEDTLS_TEST_NULL_ENTROPY)\n    mbedtls_entropy_add_source( ctx, mbedtls_null_entropy_poll, NULL,\n                                1, MBEDTLS_ENTROPY_SOURCE_STRONG );\n#endif\n\n#if !defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES)\n#if !defined(MBEDTLS_NO_PLATFORM_ENTROPY)\n    mbedtls_entropy_add_source( ctx, mbedtls_platform_entropy_poll, NULL,\n                                MBEDTLS_ENTROPY_MIN_PLATFORM,\n                                MBEDTLS_ENTROPY_SOURCE_STRONG );\n#endif\n#if defined(MBEDTLS_TIMING_C)\n    mbedtls_entropy_add_source( ctx, mbedtls_hardclock_poll, NULL,\n                                MBEDTLS_ENTROPY_MIN_HARDCLOCK,\n                                MBEDTLS_ENTROPY_SOURCE_WEAK );\n#endif\n#if defined(MBEDTLS_HAVEGE_C)\n    mbedtls_entropy_add_source( ctx, mbedtls_havege_poll, &ctx->havege_data,\n                                MBEDTLS_ENTROPY_MIN_HAVEGE,\n                                MBEDTLS_ENTROPY_SOURCE_STRONG );\n#endif\n#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)\n    mbedtls_entropy_add_source( ctx, mbedtls_hardware_poll, NULL,\n                                MBEDTLS_ENTROPY_MIN_HARDWARE,\n                                MBEDTLS_ENTROPY_SOURCE_STRONG );\n#endif\n#if defined(MBEDTLS_ENTROPY_NV_SEED)\n    mbedtls_entropy_add_source( ctx, mbedtls_nv_seed_poll, NULL,\n                                MBEDTLS_ENTROPY_BLOCK_SIZE,\n                                MBEDTLS_ENTROPY_SOURCE_STRONG );\n    ctx->initial_entropy_run = 0;\n#endif\n#endif /* MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES */\n}\n\nvoid mbedtls_entropy_free( mbedtls_entropy_context *ctx )\n{\n#if defined(MBEDTLS_HAVEGE_C)\n    mbedtls_havege_free( &ctx->havege_data );\n#endif\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_mutex_free( &ctx->mutex );\n#endif\n#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)\n    mbedtls_sha512_free( &ctx->accumulator );\n#else\n    mbedtls_sha256_free( &ctx->accumulator );\n#endif\n#if defined(MBEDTLS_ENTROPY_NV_SEED)\n    ctx->initial_entropy_run = 0;\n#endif\n    ctx->source_count = 0;\n    mbedtls_platform_zeroize( ctx->source, sizeof( ctx->source ) );\n    ctx->accumulator_started = 0;\n}\n\nint mbedtls_entropy_add_source( mbedtls_entropy_context *ctx,\n                        mbedtls_entropy_f_source_ptr f_source, void *p_source,\n                        size_t threshold, int strong )\n{\n    int idx, ret = 0;\n\n#if defined(MBEDTLS_THREADING_C)\n    if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )\n        return( ret );\n#endif\n\n    idx = ctx->source_count;\n    if( idx >= MBEDTLS_ENTROPY_MAX_SOURCES )\n    {\n        ret = MBEDTLS_ERR_ENTROPY_MAX_SOURCES;\n        goto exit;\n    }\n\n    ctx->source[idx].f_source  = f_source;\n    ctx->source[idx].p_source  = p_source;\n    ctx->source[idx].threshold = threshold;\n    ctx->source[idx].strong    = strong;\n\n    ctx->source_count++;\n\nexit:\n#if defined(MBEDTLS_THREADING_C)\n    if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )\n        return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );\n#endif\n\n    return( ret );\n}\n\n/*\n * Entropy accumulator update\n */\nstatic int entropy_update( mbedtls_entropy_context *ctx, unsigned char source_id,\n                           const unsigned char *data, size_t len )\n{\n    unsigned char header[2];\n    unsigned char tmp[MBEDTLS_ENTROPY_BLOCK_SIZE];\n    size_t use_len = len;\n    const unsigned char *p = data;\n    int ret = 0;\n\n    if( use_len > MBEDTLS_ENTROPY_BLOCK_SIZE )\n    {\n#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)\n        if( ( ret = mbedtls_sha512_ret( data, len, tmp, 0 ) ) != 0 )\n            goto cleanup;\n#else\n        if( ( ret = mbedtls_sha256_ret( data, len, tmp, 0 ) ) != 0 )\n            goto cleanup;\n#endif\n        p = tmp;\n        use_len = MBEDTLS_ENTROPY_BLOCK_SIZE;\n    }\n\n    header[0] = source_id;\n    header[1] = use_len & 0xFF;\n\n    /*\n     * Start the accumulator if this has not already happened. Note that\n     * it is sufficient to start the accumulator here only because all calls to\n     * gather entropy eventually execute this code.\n     */\n#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)\n    if( ctx->accumulator_started == 0 &&\n        ( ret = mbedtls_sha512_starts_ret( &ctx->accumulator, 0 ) ) != 0 )\n        goto cleanup;\n    else\n        ctx->accumulator_started = 1;\n    if( ( ret = mbedtls_sha512_update_ret( &ctx->accumulator, header, 2 ) ) != 0 )\n        goto cleanup;\n    ret = mbedtls_sha512_update_ret( &ctx->accumulator, p, use_len );\n#else\n    if( ctx->accumulator_started == 0 &&\n        ( ret = mbedtls_sha256_starts_ret( &ctx->accumulator, 0 ) ) != 0 )\n        goto cleanup;\n    else\n        ctx->accumulator_started = 1;\n    if( ( ret = mbedtls_sha256_update_ret( &ctx->accumulator, header, 2 ) ) != 0 )\n        goto cleanup;\n    ret = mbedtls_sha256_update_ret( &ctx->accumulator, p, use_len );\n#endif\n\ncleanup:\n    mbedtls_platform_zeroize( tmp, sizeof( tmp ) );\n\n    return( ret );\n}\n\nint mbedtls_entropy_update_manual( mbedtls_entropy_context *ctx,\n                           const unsigned char *data, size_t len )\n{\n    int ret;\n\n#if defined(MBEDTLS_THREADING_C)\n    if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )\n        return( ret );\n#endif\n\n    ret = entropy_update( ctx, MBEDTLS_ENTROPY_SOURCE_MANUAL, data, len );\n\n#if defined(MBEDTLS_THREADING_C)\n    if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )\n        return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );\n#endif\n\n    return( ret );\n}\n\n/*\n * Run through the different sources to add entropy to our accumulator\n */\nstatic int entropy_gather_internal( mbedtls_entropy_context *ctx )\n{\n    int ret, i, have_one_strong = 0;\n    unsigned char buf[MBEDTLS_ENTROPY_MAX_GATHER];\n    size_t olen;\n\n    if( ctx->source_count == 0 )\n        return( MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED );\n\n    /*\n     * Run through our entropy sources\n     */\n    for( i = 0; i < ctx->source_count; i++ )\n    {\n        if( ctx->source[i].strong == MBEDTLS_ENTROPY_SOURCE_STRONG )\n            have_one_strong = 1;\n\n        olen = 0;\n        if( ( ret = ctx->source[i].f_source( ctx->source[i].p_source,\n                        buf, MBEDTLS_ENTROPY_MAX_GATHER, &olen ) ) != 0 )\n        {\n            goto cleanup;\n        }\n\n        /*\n         * Add if we actually gathered something\n         */\n        if( olen > 0 )\n        {\n            if( ( ret = entropy_update( ctx, (unsigned char) i,\n                                        buf, olen ) ) != 0 )\n                return( ret );\n            ctx->source[i].size += olen;\n        }\n    }\n\n    if( have_one_strong == 0 )\n        ret = MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE;\n\ncleanup:\n    mbedtls_platform_zeroize( buf, sizeof( buf ) );\n\n    return( ret );\n}\n\n/*\n * Thread-safe wrapper for entropy_gather_internal()\n */\nint mbedtls_entropy_gather( mbedtls_entropy_context *ctx )\n{\n    int ret;\n\n#if defined(MBEDTLS_THREADING_C)\n    if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )\n        return( ret );\n#endif\n\n    ret = entropy_gather_internal( ctx );\n\n#if defined(MBEDTLS_THREADING_C)\n    if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )\n        return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );\n#endif\n\n    return( ret );\n}\n\nint mbedtls_entropy_func( void *data, unsigned char *output, size_t len )\n{\n    int ret, count = 0, i, done;\n    mbedtls_entropy_context *ctx = (mbedtls_entropy_context *) data;\n    unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];\n\n    if( len > MBEDTLS_ENTROPY_BLOCK_SIZE )\n        return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n\n#if defined(MBEDTLS_ENTROPY_NV_SEED)\n    /* Update the NV entropy seed before generating any entropy for outside\n     * use.\n     */\n    if( ctx->initial_entropy_run == 0 )\n    {\n        ctx->initial_entropy_run = 1;\n        if( ( ret = mbedtls_entropy_update_nv_seed( ctx ) ) != 0 )\n            return( ret );\n    }\n#endif\n\n#if defined(MBEDTLS_THREADING_C)\n    if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )\n        return( ret );\n#endif\n\n    /*\n     * Always gather extra entropy before a call\n     */\n    do\n    {\n        if( count++ > ENTROPY_MAX_LOOP )\n        {\n            ret = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;\n            goto exit;\n        }\n\n        if( ( ret = entropy_gather_internal( ctx ) ) != 0 )\n            goto exit;\n\n        done = 1;\n        for( i = 0; i < ctx->source_count; i++ )\n            if( ctx->source[i].size < ctx->source[i].threshold )\n                done = 0;\n    }\n    while( ! done );\n\n    memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );\n\n#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)\n    /*\n     * Note that at this stage it is assumed that the accumulator was started\n     * in a previous call to entropy_update(). If this is not guaranteed, the\n     * code below will fail.\n     */\n    if( ( ret = mbedtls_sha512_finish_ret( &ctx->accumulator, buf ) ) != 0 )\n        goto exit;\n\n    /*\n     * Reset accumulator and counters and recycle existing entropy\n     */\n    mbedtls_sha512_free( &ctx->accumulator );\n    mbedtls_sha512_init( &ctx->accumulator );\n    if( ( ret = mbedtls_sha512_starts_ret( &ctx->accumulator, 0 ) ) != 0 )\n        goto exit;\n    if( ( ret = mbedtls_sha512_update_ret( &ctx->accumulator, buf,\n                                           MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )\n        goto exit;\n\n    /*\n     * Perform second SHA-512 on entropy\n     */\n    if( ( ret = mbedtls_sha512_ret( buf, MBEDTLS_ENTROPY_BLOCK_SIZE,\n                                    buf, 0 ) ) != 0 )\n        goto exit;\n#else /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */\n    if( ( ret = mbedtls_sha256_finish_ret( &ctx->accumulator, buf ) ) != 0 )\n        goto exit;\n\n    /*\n     * Reset accumulator and counters and recycle existing entropy\n     */\n    mbedtls_sha256_free( &ctx->accumulator );\n    mbedtls_sha256_init( &ctx->accumulator );\n    if( ( ret = mbedtls_sha256_starts_ret( &ctx->accumulator, 0 ) ) != 0 )\n        goto exit;\n    if( ( ret = mbedtls_sha256_update_ret( &ctx->accumulator, buf,\n                                           MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )\n        goto exit;\n\n    /*\n     * Perform second SHA-256 on entropy\n     */\n    if( ( ret = mbedtls_sha256_ret( buf, MBEDTLS_ENTROPY_BLOCK_SIZE,\n                                    buf, 0 ) ) != 0 )\n        goto exit;\n#endif /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */\n\n    for( i = 0; i < ctx->source_count; i++ )\n        ctx->source[i].size = 0;\n\n    memcpy( output, buf, len );\n\n    ret = 0;\n\nexit:\n    mbedtls_platform_zeroize( buf, sizeof( buf ) );\n\n#if defined(MBEDTLS_THREADING_C)\n    if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )\n        return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );\n#endif\n\n    return( ret );\n}\n\n#if defined(MBEDTLS_ENTROPY_NV_SEED)\nint mbedtls_entropy_update_nv_seed( mbedtls_entropy_context *ctx )\n{\n    int ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;\n    unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];\n\n    /* Read new seed  and write it to NV */\n    if( ( ret = mbedtls_entropy_func( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )\n        return( ret );\n\n    if( mbedtls_nv_seed_write( buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) < 0 )\n        return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR );\n\n    /* Manually update the remaining stream with a separator value to diverge */\n    memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );\n    ret = mbedtls_entropy_update_manual( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE );\n\n    return( ret );\n}\n#endif /* MBEDTLS_ENTROPY_NV_SEED */\n\n#if defined(MBEDTLS_FS_IO)\nint mbedtls_entropy_write_seed_file( mbedtls_entropy_context *ctx, const char *path )\n{\n    int ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;\n    FILE *f;\n    unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];\n\n    if( ( f = fopen( path, \"wb\" ) ) == NULL )\n        return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR );\n\n    if( ( ret = mbedtls_entropy_func( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )\n        goto exit;\n\n    if( fwrite( buf, 1, MBEDTLS_ENTROPY_BLOCK_SIZE, f ) != MBEDTLS_ENTROPY_BLOCK_SIZE )\n    {\n        ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;\n        goto exit;\n    }\n\n    ret = 0;\n\nexit:\n    mbedtls_platform_zeroize( buf, sizeof( buf ) );\n\n    fclose( f );\n    return( ret );\n}\n\nint mbedtls_entropy_update_seed_file( mbedtls_entropy_context *ctx, const char *path )\n{\n    int ret = 0;\n    FILE *f;\n    size_t n;\n    unsigned char buf[ MBEDTLS_ENTROPY_MAX_SEED_SIZE ];\n\n    if( ( f = fopen( path, \"rb\" ) ) == NULL )\n        return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR );\n\n    fseek( f, 0, SEEK_END );\n    n = (size_t) ftell( f );\n    fseek( f, 0, SEEK_SET );\n\n    if( n > MBEDTLS_ENTROPY_MAX_SEED_SIZE )\n        n = MBEDTLS_ENTROPY_MAX_SEED_SIZE;\n\n    if( fread( buf, 1, n, f ) != n )\n        ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;\n    else\n        ret = mbedtls_entropy_update_manual( ctx, buf, n );\n\n    fclose( f );\n\n    mbedtls_platform_zeroize( buf, sizeof( buf ) );\n\n    if( ret != 0 )\n        return( ret );\n\n    return( mbedtls_entropy_write_seed_file( ctx, path ) );\n}\n#endif /* MBEDTLS_FS_IO */\n\n#if defined(MBEDTLS_SELF_TEST)\n#if !defined(MBEDTLS_TEST_NULL_ENTROPY)\n/*\n * Dummy source function\n */\nstatic int entropy_dummy_source( void *data, unsigned char *output,\n                                 size_t len, size_t *olen )\n{\n    ((void) data);\n\n    memset( output, 0x2a, len );\n    *olen = len;\n\n    return( 0 );\n}\n#endif /* !MBEDTLS_TEST_NULL_ENTROPY */\n\n#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)\n\nstatic int mbedtls_entropy_source_self_test_gather( unsigned char *buf, size_t buf_len )\n{\n    int ret = 0;\n    size_t entropy_len = 0;\n    size_t olen = 0;\n    size_t attempts = buf_len;\n\n    while( attempts > 0 && entropy_len < buf_len )\n    {\n        if( ( ret = mbedtls_hardware_poll( NULL, buf + entropy_len,\n            buf_len - entropy_len, &olen ) ) != 0 )\n            return( ret );\n\n        entropy_len += olen;\n        attempts--;\n    }\n\n    if( entropy_len < buf_len )\n    {\n        ret = 1;\n    }\n\n    return( ret );\n}\n\n\nstatic int mbedtls_entropy_source_self_test_check_bits( const unsigned char *buf,\n                                                        size_t buf_len )\n{\n    unsigned char set= 0xFF;\n    unsigned char unset = 0x00;\n    size_t i;\n\n    for( i = 0; i < buf_len; i++ )\n    {\n        set &= buf[i];\n        unset |= buf[i];\n    }\n\n    return( set == 0xFF || unset == 0x00 );\n}\n\n/*\n * A test to ensure hat the entropy sources are functioning correctly\n * and there is no obvious failure. The test performs the following checks:\n *  - The entropy source is not providing only 0s (all bits unset) or 1s (all\n *    bits set).\n *  - The entropy source is not providing values in a pattern. Because the\n *    hardware could be providing data in an arbitrary length, this check polls\n *    the hardware entropy source twice and compares the result to ensure they\n *    are not equal.\n *  - The error code returned by the entropy source is not an error.\n */\nint mbedtls_entropy_source_self_test( int verbose )\n{\n    int ret = 0;\n    unsigned char buf0[2 * sizeof( unsigned long long int )];\n    unsigned char buf1[2 * sizeof( unsigned long long int )];\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  ENTROPY_BIAS test: \" );\n\n    memset( buf0, 0x00, sizeof( buf0 ) );\n    memset( buf1, 0x00, sizeof( buf1 ) );\n\n    if( ( ret = mbedtls_entropy_source_self_test_gather( buf0, sizeof( buf0 ) ) ) != 0 )\n        goto cleanup;\n    if( ( ret = mbedtls_entropy_source_self_test_gather( buf1, sizeof( buf1 ) ) ) != 0 )\n        goto cleanup;\n\n    /* Make sure that the returned values are not all 0 or 1 */\n    if( ( ret = mbedtls_entropy_source_self_test_check_bits( buf0, sizeof( buf0 ) ) ) != 0 )\n        goto cleanup;\n    if( ( ret = mbedtls_entropy_source_self_test_check_bits( buf1, sizeof( buf1 ) ) ) != 0 )\n        goto cleanup;\n\n    /* Make sure that the entropy source is not returning values in a\n     * pattern */\n    ret = memcmp( buf0, buf1, sizeof( buf0 ) ) == 0;\n\ncleanup:\n    if( verbose != 0 )\n    {\n        if( ret != 0 )\n            mbedtls_printf( \"failed\\n\" );\n        else\n            mbedtls_printf( \"passed\\n\" );\n\n        mbedtls_printf( \"\\n\" );\n    }\n\n    return( ret != 0 );\n}\n\n#endif /* MBEDTLS_ENTROPY_HARDWARE_ALT */\n\n/*\n * The actual entropy quality is hard to test, but we can at least\n * test that the functions don't cause errors and write the correct\n * amount of data to buffers.\n */\nint mbedtls_entropy_self_test( int verbose )\n{\n    int ret = 1;\n#if !defined(MBEDTLS_TEST_NULL_ENTROPY)\n    mbedtls_entropy_context ctx;\n    unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 };\n    unsigned char acc[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 };\n    size_t i, j;\n#endif /* !MBEDTLS_TEST_NULL_ENTROPY */\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  ENTROPY test: \" );\n\n#if !defined(MBEDTLS_TEST_NULL_ENTROPY)\n    mbedtls_entropy_init( &ctx );\n\n    /* First do a gather to make sure we have default sources */\n    if( ( ret = mbedtls_entropy_gather( &ctx ) ) != 0 )\n        goto cleanup;\n\n    ret = mbedtls_entropy_add_source( &ctx, entropy_dummy_source, NULL, 16,\n                                      MBEDTLS_ENTROPY_SOURCE_WEAK );\n    if( ret != 0 )\n        goto cleanup;\n\n    if( ( ret = mbedtls_entropy_update_manual( &ctx, buf, sizeof buf ) ) != 0 )\n        goto cleanup;\n\n    /*\n     * To test that mbedtls_entropy_func writes correct number of bytes:\n     * - use the whole buffer and rely on ASan to detect overruns\n     * - collect entropy 8 times and OR the result in an accumulator:\n     *   any byte should then be 0 with probably 2^(-64), so requiring\n     *   each of the 32 or 64 bytes to be non-zero has a false failure rate\n     *   of at most 2^(-58) which is acceptable.\n     */\n    for( i = 0; i < 8; i++ )\n    {\n        if( ( ret = mbedtls_entropy_func( &ctx, buf, sizeof( buf ) ) ) != 0 )\n            goto cleanup;\n\n        for( j = 0; j < sizeof( buf ); j++ )\n            acc[j] |= buf[j];\n    }\n\n    for( j = 0; j < sizeof( buf ); j++ )\n    {\n        if( acc[j] == 0 )\n        {\n            ret = 1;\n            goto cleanup;\n        }\n    }\n\n#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)\n    if( ( ret = mbedtls_entropy_source_self_test( 0 ) ) != 0 )\n        goto cleanup;\n#endif\n\ncleanup:\n    mbedtls_entropy_free( &ctx );\n#endif /* !MBEDTLS_TEST_NULL_ENTROPY */\n\n    if( verbose != 0 )\n    {\n        if( ret != 0 )\n            mbedtls_printf( \"failed\\n\" );\n        else\n            mbedtls_printf( \"passed\\n\" );\n\n        mbedtls_printf( \"\\n\" );\n    }\n\n    return( ret != 0 );\n}\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_ENTROPY_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/entropy_poll.c",
    "content": "/*\n *  Platform-specific and custom entropy polling functions\n *\n *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if defined(__linux__)\n/* Ensure that syscall() is available even when compiling with -std=c99 */\n#define _GNU_SOURCE\n#endif\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <string.h>\n\n#if defined(MBEDTLS_ENTROPY_C)\n\n#include \"mbedtls/entropy.h\"\n#include \"mbedtls/entropy_poll.h\"\n\n#if defined(MBEDTLS_TIMING_C)\n#include \"mbedtls/timing.h\"\n#endif\n#if defined(MBEDTLS_HAVEGE_C)\n#include \"mbedtls/havege.h\"\n#endif\n#if defined(MBEDTLS_ENTROPY_NV_SEED)\n#include \"mbedtls/platform.h\"\n#endif\n\n#if !defined(MBEDTLS_NO_PLATFORM_ENTROPY)\n\n#if !defined(unix) && !defined(__unix__) && !defined(__unix) && \\\n    !defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) && \\\n    !defined(__HAIKU__)\n#error \"Platform entropy sources only work on Unix and Windows, see MBEDTLS_NO_PLATFORM_ENTROPY in config.h\"\n#endif\n\n#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)\n\n#if !defined(_WIN32_WINNT)\n#define _WIN32_WINNT 0x0400\n#endif\n#include <windows.h>\n#include <bcrypt.h>\n#if defined(_MSC_VER) && _MSC_VER <= 1600\n/* Visual Studio 2010 and earlier issue a warning when both <stdint.h> and\n * <intsafe.h> are included, as they redefine a number of <TYPE>_MAX constants.\n * These constants are guaranteed to be the same, though, so we suppress the\n * warning when including intsafe.h.\n */\n#pragma warning( push )\n#pragma warning( disable : 4005 )\n#endif\n#include <intsafe.h>\n#if defined(_MSC_VER) && _MSC_VER <= 1600\n#pragma warning( pop )\n#endif\n\nint mbedtls_platform_entropy_poll( void *data, unsigned char *output, size_t len,\n                           size_t *olen )\n{\n    ULONG len_as_ulong = 0;\n    ((void) data);\n    *olen = 0;\n\n    /*\n     * BCryptGenRandom takes ULONG for size, which is smaller than size_t on\n     * 64-bit Windows platforms. Ensure len's value can be safely converted into\n     * a ULONG.\n     */\n    if ( FAILED( SizeTToULong( len, &len_as_ulong ) ) )\n    {\n        return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n    }\n\n    if ( !BCRYPT_SUCCESS( BCryptGenRandom( NULL, output, len_as_ulong, BCRYPT_USE_SYSTEM_PREFERRED_RNG ) ) )\n    {\n        return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n    }\n\n    *olen = len;\n\n    return( 0 );\n}\n#else /* _WIN32 && !EFIX64 && !EFI32 */\n\n/*\n * Test for Linux getrandom() support.\n * Since there is no wrapper in the libc yet, use the generic syscall wrapper\n * available in GNU libc and compatible libc's (eg uClibc).\n */\n#if defined(__linux__) && defined(__GLIBC__)\n#include <unistd.h>\n#include <sys/syscall.h>\n#if defined(SYS_getrandom)\n#define HAVE_GETRANDOM\n\nstatic int getrandom_wrapper( void *buf, size_t buflen, unsigned int flags )\n{\n    /* MemSan cannot understand that the syscall writes to the buffer */\n#if defined(__has_feature)\n#if __has_feature(memory_sanitizer)\n    memset( buf, 0, buflen );\n#endif\n#endif\n\n    return( syscall( SYS_getrandom, buf, buflen, flags ) );\n}\n\n#include <sys/utsname.h>\n/* Check if version is at least 3.17.0 */\nstatic int check_version_3_17_plus( void )\n{\n    int minor;\n    struct utsname un;\n    const char *ver;\n\n    /* Get version information */\n    uname(&un);\n    ver = un.release;\n\n    /* Check major version; assume a single digit */\n    if( ver[0] < '3' || ver[0] > '9' || ver [1] != '.' )\n        return( -1 );\n\n    if( ver[0] - '0' > 3 )\n        return( 0 );\n\n    /* Ok, so now we know major == 3, check minor.\n     * Assume 1 or 2 digits. */\n    if( ver[2] < '0' || ver[2] > '9' )\n        return( -1 );\n\n    minor = ver[2] - '0';\n\n    if( ver[3] >= '0' && ver[3] <= '9' )\n        minor = 10 * minor + ver[3] - '0';\n    else if( ver [3] != '.' )\n        return( -1 );\n\n    if( minor < 17 )\n        return( -1 );\n\n    return( 0 );\n}\nstatic int has_getrandom = -1;\n#endif /* SYS_getrandom */\n#endif /* __linux__ */\n\n#include <stdio.h>\n\nint mbedtls_platform_entropy_poll( void *data,\n                           unsigned char *output, size_t len, size_t *olen )\n{\n    FILE *file;\n    size_t read_len;\n    ((void) data);\n\n#if defined(HAVE_GETRANDOM)\n    if( has_getrandom == -1 )\n        has_getrandom = ( check_version_3_17_plus() == 0 );\n\n    if( has_getrandom )\n    {\n        int ret;\n\n        if( ( ret = getrandom_wrapper( output, len, 0 ) ) < 0 )\n            return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n\n        *olen = ret;\n        return( 0 );\n    }\n#endif /* HAVE_GETRANDOM */\n\n    *olen = 0;\n\n    file = fopen( \"/dev/urandom\", \"rb\" );\n    if( file == NULL )\n        return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n\n    read_len = fread( output, 1, len, file );\n    if( read_len != len )\n    {\n        fclose( file );\n        return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n    }\n\n    fclose( file );\n    *olen = len;\n\n    return( 0 );\n}\n#endif /* _WIN32 && !EFIX64 && !EFI32 */\n#endif /* !MBEDTLS_NO_PLATFORM_ENTROPY */\n\n#if defined(MBEDTLS_TEST_NULL_ENTROPY)\nint mbedtls_null_entropy_poll( void *data,\n                    unsigned char *output, size_t len, size_t *olen )\n{\n    ((void) data);\n    ((void) output);\n    *olen = 0;\n\n    if( len < sizeof(unsigned char) )\n        return( 0 );\n\n    *olen = sizeof(unsigned char);\n\n    return( 0 );\n}\n#endif\n\n#if defined(MBEDTLS_TIMING_C)\nint mbedtls_hardclock_poll( void *data,\n                    unsigned char *output, size_t len, size_t *olen )\n{\n    unsigned long timer = mbedtls_timing_hardclock();\n    ((void) data);\n    *olen = 0;\n\n    if( len < sizeof(unsigned long) )\n        return( 0 );\n\n    memcpy( output, &timer, sizeof(unsigned long) );\n    *olen = sizeof(unsigned long);\n\n    return( 0 );\n}\n#endif /* MBEDTLS_TIMING_C */\n\n#if defined(MBEDTLS_HAVEGE_C)\nint mbedtls_havege_poll( void *data,\n                 unsigned char *output, size_t len, size_t *olen )\n{\n    mbedtls_havege_state *hs = (mbedtls_havege_state *) data;\n    *olen = 0;\n\n    if( mbedtls_havege_random( hs, output, len ) != 0 )\n        return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n\n    *olen = len;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_HAVEGE_C */\n\n#if defined(MBEDTLS_ENTROPY_NV_SEED)\nint mbedtls_nv_seed_poll( void *data,\n                          unsigned char *output, size_t len, size_t *olen )\n{\n    unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];\n    size_t use_len = MBEDTLS_ENTROPY_BLOCK_SIZE;\n    ((void) data);\n\n    memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );\n\n    if( mbedtls_nv_seed_read( buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) < 0 )\n      return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n\n    if( len < use_len )\n      use_len = len;\n\n    memcpy( output, buf, use_len );\n    *olen = use_len;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_ENTROPY_NV_SEED */\n\n#endif /* MBEDTLS_ENTROPY_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/entropy_poll.c.orig",
    "content": "/*\n *  Platform-specific and custom entropy polling functions\n *\n *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if defined(__linux__)\n/* Ensure that syscall() is available even when compiling with -std=c99 */\n#define _GNU_SOURCE\n#endif\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include <string.h>\n\n#if defined(MBEDTLS_ENTROPY_C)\n\n#include \"mbedtls/entropy.h\"\n#include \"mbedtls/entropy_poll.h\"\n\n#if defined(MBEDTLS_TIMING_C)\n#include \"mbedtls/timing.h\"\n#endif\n#if defined(MBEDTLS_HAVEGE_C)\n#include \"mbedtls/havege.h\"\n#endif\n#if defined(MBEDTLS_ENTROPY_NV_SEED)\n#include \"mbedtls/platform.h\"\n#endif\n\n#if !defined(MBEDTLS_NO_PLATFORM_ENTROPY)\n\n#if !defined(unix) && !defined(__unix__) && !defined(__unix) && \\\n    !defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) && \\\n    !defined(__HAIKU__)\n#error \"Platform entropy sources only work on Unix and Windows, see MBEDTLS_NO_PLATFORM_ENTROPY in config.h\"\n#endif\n\n#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)\n\n#if !defined(_WIN32_WINNT)\n#define _WIN32_WINNT 0x0400\n#endif\n#include <windows.h>\n#include <wincrypt.h>\n\nint mbedtls_platform_entropy_poll( void *data, unsigned char *output, size_t len,\n                           size_t *olen )\n{\n    HCRYPTPROV provider;\n    ((void) data);\n    *olen = 0;\n\n    if( CryptAcquireContext( &provider, NULL, NULL,\n                              PROV_RSA_FULL, CRYPT_VERIFYCONTEXT ) == FALSE )\n    {\n        return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n    }\n\n    if( CryptGenRandom( provider, (DWORD) len, output ) == FALSE )\n    {\n        CryptReleaseContext( provider, 0 );\n        return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n    }\n\n    CryptReleaseContext( provider, 0 );\n    *olen = len;\n\n    return( 0 );\n}\n#else /* _WIN32 && !EFIX64 && !EFI32 */\n\n/*\n * Test for Linux getrandom() support.\n * Since there is no wrapper in the libc yet, use the generic syscall wrapper\n * available in GNU libc and compatible libc's (eg uClibc).\n */\n#if defined(__linux__) && defined(__GLIBC__)\n#include <unistd.h>\n#include <sys/syscall.h>\n#if defined(SYS_getrandom)\n#define HAVE_GETRANDOM\n\nstatic int getrandom_wrapper( void *buf, size_t buflen, unsigned int flags )\n{\n    /* MemSan cannot understand that the syscall writes to the buffer */\n#if defined(__has_feature)\n#if __has_feature(memory_sanitizer)\n    memset( buf, 0, buflen );\n#endif\n#endif\n\n    return( syscall( SYS_getrandom, buf, buflen, flags ) );\n}\n\n#include <sys/utsname.h>\n/* Check if version is at least 3.17.0 */\nstatic int check_version_3_17_plus( void )\n{\n    int minor;\n    struct utsname un;\n    const char *ver;\n\n    /* Get version information */\n    uname(&un);\n    ver = un.release;\n\n    /* Check major version; assume a single digit */\n    if( ver[0] < '3' || ver[0] > '9' || ver [1] != '.' )\n        return( -1 );\n\n    if( ver[0] - '0' > 3 )\n        return( 0 );\n\n    /* Ok, so now we know major == 3, check minor.\n     * Assume 1 or 2 digits. */\n    if( ver[2] < '0' || ver[2] > '9' )\n        return( -1 );\n\n    minor = ver[2] - '0';\n\n    if( ver[3] >= '0' && ver[3] <= '9' )\n        minor = 10 * minor + ver[3] - '0';\n    else if( ver [3] != '.' )\n        return( -1 );\n\n    if( minor < 17 )\n        return( -1 );\n\n    return( 0 );\n}\nstatic int has_getrandom = -1;\n#endif /* SYS_getrandom */\n#endif /* __linux__ */\n\n#include <stdio.h>\n\nint mbedtls_platform_entropy_poll( void *data,\n                           unsigned char *output, size_t len, size_t *olen )\n{\n    FILE *file;\n    size_t read_len;\n    ((void) data);\n\n#if defined(HAVE_GETRANDOM)\n    if( has_getrandom == -1 )\n        has_getrandom = ( check_version_3_17_plus() == 0 );\n\n    if( has_getrandom )\n    {\n        int ret;\n\n        if( ( ret = getrandom_wrapper( output, len, 0 ) ) < 0 )\n            return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n\n        *olen = ret;\n        return( 0 );\n    }\n#endif /* HAVE_GETRANDOM */\n\n    *olen = 0;\n\n    file = fopen( \"/dev/urandom\", \"rb\" );\n    if( file == NULL )\n        return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n\n    read_len = fread( output, 1, len, file );\n    if( read_len != len )\n    {\n        fclose( file );\n        return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n    }\n\n    fclose( file );\n    *olen = len;\n\n    return( 0 );\n}\n#endif /* _WIN32 && !EFIX64 && !EFI32 */\n#endif /* !MBEDTLS_NO_PLATFORM_ENTROPY */\n\n#if defined(MBEDTLS_TEST_NULL_ENTROPY)\nint mbedtls_null_entropy_poll( void *data,\n                    unsigned char *output, size_t len, size_t *olen )\n{\n    ((void) data);\n    ((void) output);\n    *olen = 0;\n\n    if( len < sizeof(unsigned char) )\n        return( 0 );\n\n    *olen = sizeof(unsigned char);\n\n    return( 0 );\n}\n#endif\n\n#if defined(MBEDTLS_TIMING_C)\nint mbedtls_hardclock_poll( void *data,\n                    unsigned char *output, size_t len, size_t *olen )\n{\n    unsigned long timer = mbedtls_timing_hardclock();\n    ((void) data);\n    *olen = 0;\n\n    if( len < sizeof(unsigned long) )\n        return( 0 );\n\n    memcpy( output, &timer, sizeof(unsigned long) );\n    *olen = sizeof(unsigned long);\n\n    return( 0 );\n}\n#endif /* MBEDTLS_TIMING_C */\n\n#if defined(MBEDTLS_HAVEGE_C)\nint mbedtls_havege_poll( void *data,\n                 unsigned char *output, size_t len, size_t *olen )\n{\n    mbedtls_havege_state *hs = (mbedtls_havege_state *) data;\n    *olen = 0;\n\n    if( mbedtls_havege_random( hs, output, len ) != 0 )\n        return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n\n    *olen = len;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_HAVEGE_C */\n\n#if defined(MBEDTLS_ENTROPY_NV_SEED)\nint mbedtls_nv_seed_poll( void *data,\n                          unsigned char *output, size_t len, size_t *olen )\n{\n    unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];\n    size_t use_len = MBEDTLS_ENTROPY_BLOCK_SIZE;\n    ((void) data);\n\n    memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );\n\n    if( mbedtls_nv_seed_read( buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) < 0 )\n      return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );\n\n    if( len < use_len )\n      use_len = len;\n\n    memcpy( output, buf, use_len );\n    *olen = use_len;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_ENTROPY_NV_SEED */\n\n#endif /* MBEDTLS_ENTROPY_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/error.c",
    "content": "/*\n *  Error message information\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_ERROR_C) || defined(MBEDTLS_ERROR_STRERROR_DUMMY)\n#include \"mbedtls/error.h\"\n#include <string.h>\n#endif\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#define mbedtls_snprintf snprintf\n#define mbedtls_time_t   time_t\n#endif\n\n#if defined(MBEDTLS_ERROR_C)\n\n#include <stdio.h>\n\n#if defined(MBEDTLS_AES_C)\n#include \"mbedtls/aes.h\"\n#endif\n\n#if defined(MBEDTLS_ARC4_C)\n#include \"mbedtls/arc4.h\"\n#endif\n\n#if defined(MBEDTLS_ARIA_C)\n#include \"mbedtls/aria.h\"\n#endif\n\n#if defined(MBEDTLS_BASE64_C)\n#include \"mbedtls/base64.h\"\n#endif\n\n#if defined(MBEDTLS_BIGNUM_C)\n#include \"mbedtls/bignum.h\"\n#endif\n\n#if defined(MBEDTLS_BLOWFISH_C)\n#include \"mbedtls/blowfish.h\"\n#endif\n\n#if defined(MBEDTLS_CAMELLIA_C)\n#include \"mbedtls/camellia.h\"\n#endif\n\n#if defined(MBEDTLS_CCM_C)\n#include \"mbedtls/ccm.h\"\n#endif\n\n#if defined(MBEDTLS_CHACHA20_C)\n#include \"mbedtls/chacha20.h\"\n#endif\n\n#if defined(MBEDTLS_CHACHAPOLY_C)\n#include \"mbedtls/chachapoly.h\"\n#endif\n\n#if defined(MBEDTLS_CIPHER_C)\n#include \"mbedtls/cipher.h\"\n#endif\n\n#if defined(MBEDTLS_CMAC_C)\n#include \"mbedtls/cmac.h\"\n#endif\n\n#if defined(MBEDTLS_CTR_DRBG_C)\n#include \"mbedtls/ctr_drbg.h\"\n#endif\n\n#if defined(MBEDTLS_DES_C)\n#include \"mbedtls/des.h\"\n#endif\n\n#if defined(MBEDTLS_DHM_C)\n#include \"mbedtls/dhm.h\"\n#endif\n\n#if defined(MBEDTLS_ECP_C)\n#include \"mbedtls/ecp.h\"\n#endif\n\n#if defined(MBEDTLS_ENTROPY_C)\n#include \"mbedtls/entropy.h\"\n#endif\n\n#if defined(MBEDTLS_GCM_C)\n#include \"mbedtls/gcm.h\"\n#endif\n\n#if defined(MBEDTLS_HKDF_C)\n#include \"mbedtls/hkdf.h\"\n#endif\n\n#if defined(MBEDTLS_HMAC_DRBG_C)\n#include \"mbedtls/hmac_drbg.h\"\n#endif\n\n#if defined(MBEDTLS_MD_C)\n#include \"mbedtls/md.h\"\n#endif\n\n#if defined(MBEDTLS_MD2_C)\n#include \"mbedtls/md2.h\"\n#endif\n\n#if defined(MBEDTLS_MD4_C)\n#include \"mbedtls/md4.h\"\n#endif\n\n#if defined(MBEDTLS_MD5_C)\n#include \"mbedtls/md5.h\"\n#endif\n\n#if defined(MBEDTLS_NET_C)\n#include \"mbedtls/net_sockets.h\"\n#endif\n\n#if defined(MBEDTLS_OID_C)\n#include \"mbedtls/oid.h\"\n#endif\n\n#if defined(MBEDTLS_PADLOCK_C)\n#include \"mbedtls/padlock.h\"\n#endif\n\n#if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C)\n#include \"mbedtls/pem.h\"\n#endif\n\n#if defined(MBEDTLS_PK_C)\n#include \"mbedtls/pk.h\"\n#endif\n\n#if defined(MBEDTLS_PKCS12_C)\n#include \"mbedtls/pkcs12.h\"\n#endif\n\n#if defined(MBEDTLS_PKCS5_C)\n#include \"mbedtls/pkcs5.h\"\n#endif\n\n#if defined(MBEDTLS_POLY1305_C)\n#include \"mbedtls/poly1305.h\"\n#endif\n\n#if defined(MBEDTLS_RIPEMD160_C)\n#include \"mbedtls/ripemd160.h\"\n#endif\n\n#if defined(MBEDTLS_RSA_C)\n#include \"mbedtls/rsa.h\"\n#endif\n\n#if defined(MBEDTLS_SHA1_C)\n#include \"mbedtls/sha1.h\"\n#endif\n\n#if defined(MBEDTLS_SHA256_C)\n#include \"mbedtls/sha256.h\"\n#endif\n\n#if defined(MBEDTLS_SHA512_C)\n#include \"mbedtls/sha512.h\"\n#endif\n\n#if defined(MBEDTLS_SSL_TLS_C)\n#include \"mbedtls/ssl.h\"\n#endif\n\n#if defined(MBEDTLS_THREADING_C)\n#include \"mbedtls/threading.h\"\n#endif\n\n#if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C)\n#include \"mbedtls/x509.h\"\n#endif\n\n#if defined(MBEDTLS_XTEA_C)\n#include \"mbedtls/xtea.h\"\n#endif\n\n\nvoid mbedtls_strerror( int ret, char *buf, size_t buflen )\n{\n    size_t len;\n    int use_ret;\n\n    if( buflen == 0 )\n        return;\n\n    memset( buf, 0x00, buflen );\n\n    if( ret < 0 )\n        ret = -ret;\n\n    if( ret & 0xFF80 )\n    {\n        use_ret = ret & 0xFF80;\n\n        // High level error codes\n        //\n        // BEGIN generated code\n#if defined(MBEDTLS_CIPHER_C)\n        if( use_ret == -(MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"CIPHER - The selected feature is not available\" );\n        if( use_ret == -(MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"CIPHER - Bad input parameters\" );\n        if( use_ret == -(MBEDTLS_ERR_CIPHER_ALLOC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"CIPHER - Failed to allocate memory\" );\n        if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_PADDING) )\n            mbedtls_snprintf( buf, buflen, \"CIPHER - Input data contains invalid padding and is rejected\" );\n        if( use_ret == -(MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED) )\n            mbedtls_snprintf( buf, buflen, \"CIPHER - Decryption of block requires a full block\" );\n        if( use_ret == -(MBEDTLS_ERR_CIPHER_AUTH_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"CIPHER - Authentication failed (for AEAD modes)\" );\n        if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_CONTEXT) )\n            mbedtls_snprintf( buf, buflen, \"CIPHER - The context is invalid. For example, because it was freed\" );\n        if( use_ret == -(MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"CIPHER - Cipher hardware accelerator failed\" );\n#endif /* MBEDTLS_CIPHER_C */\n\n#if defined(MBEDTLS_DHM_C)\n        if( use_ret == -(MBEDTLS_ERR_DHM_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Bad input parameters\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_READ_PARAMS_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Reading of the DHM parameters failed\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Making of the DHM parameters failed\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Reading of the public values failed\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Making of the public value failed\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_CALC_SECRET_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Calculation of the DHM secret failed\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_INVALID_FORMAT) )\n            mbedtls_snprintf( buf, buflen, \"DHM - The ASN.1 data is not formatted correctly\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_ALLOC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Allocation of memory failed\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_FILE_IO_ERROR) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Read or write of file failed\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_HW_ACCEL_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"DHM - DHM hardware accelerator failed\" );\n        if( use_ret == -(MBEDTLS_ERR_DHM_SET_GROUP_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"DHM - Setting the modulus and generator failed\" );\n#endif /* MBEDTLS_DHM_C */\n\n#if defined(MBEDTLS_ECP_C)\n        if( use_ret == -(MBEDTLS_ERR_ECP_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"ECP - Bad input parameters to function\" );\n        if( use_ret == -(MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL) )\n            mbedtls_snprintf( buf, buflen, \"ECP - The buffer is too small to write to\" );\n        if( use_ret == -(MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"ECP - The requested feature is not available, for example, the requested curve is not supported\" );\n        if( use_ret == -(MBEDTLS_ERR_ECP_VERIFY_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"ECP - The signature is not valid\" );\n        if( use_ret == -(MBEDTLS_ERR_ECP_ALLOC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"ECP - Memory allocation failed\" );\n        if( use_ret == -(MBEDTLS_ERR_ECP_RANDOM_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"ECP - Generation of random value, such as ephemeral key, failed\" );\n        if( use_ret == -(MBEDTLS_ERR_ECP_INVALID_KEY) )\n            mbedtls_snprintf( buf, buflen, \"ECP - Invalid private or public key\" );\n        if( use_ret == -(MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"ECP - The buffer contains a valid signature followed by more data\" );\n        if( use_ret == -(MBEDTLS_ERR_ECP_HW_ACCEL_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"ECP - The ECP hardware accelerator failed\" );\n#endif /* MBEDTLS_ECP_C */\n\n#if defined(MBEDTLS_MD_C)\n        if( use_ret == -(MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"MD - The selected feature is not available\" );\n        if( use_ret == -(MBEDTLS_ERR_MD_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"MD - Bad input parameters to function\" );\n        if( use_ret == -(MBEDTLS_ERR_MD_ALLOC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"MD - Failed to allocate memory\" );\n        if( use_ret == -(MBEDTLS_ERR_MD_FILE_IO_ERROR) )\n            mbedtls_snprintf( buf, buflen, \"MD - Opening or reading of file failed\" );\n        if( use_ret == -(MBEDTLS_ERR_MD_HW_ACCEL_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"MD - MD hardware accelerator failed\" );\n#endif /* MBEDTLS_MD_C */\n\n#if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C)\n        if( use_ret == -(MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) )\n            mbedtls_snprintf( buf, buflen, \"PEM - No PEM header or footer found\" );\n        if( use_ret == -(MBEDTLS_ERR_PEM_INVALID_DATA) )\n            mbedtls_snprintf( buf, buflen, \"PEM - PEM string is not as expected\" );\n        if( use_ret == -(MBEDTLS_ERR_PEM_ALLOC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"PEM - Failed to allocate memory\" );\n        if( use_ret == -(MBEDTLS_ERR_PEM_INVALID_ENC_IV) )\n            mbedtls_snprintf( buf, buflen, \"PEM - RSA IV is not in hex-format\" );\n        if( use_ret == -(MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG) )\n            mbedtls_snprintf( buf, buflen, \"PEM - Unsupported key encryption algorithm\" );\n        if( use_ret == -(MBEDTLS_ERR_PEM_PASSWORD_REQUIRED) )\n            mbedtls_snprintf( buf, buflen, \"PEM - Private key password can't be empty\" );\n        if( use_ret == -(MBEDTLS_ERR_PEM_PASSWORD_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"PEM - Given private key password does not allow for correct decryption\" );\n        if( use_ret == -(MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"PEM - Unavailable feature, e.g. hashing/encryption combination\" );\n        if( use_ret == -(MBEDTLS_ERR_PEM_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"PEM - Bad input parameters to function\" );\n#endif /* MBEDTLS_PEM_PARSE_C || MBEDTLS_PEM_WRITE_C */\n\n#if defined(MBEDTLS_PK_C)\n        if( use_ret == -(MBEDTLS_ERR_PK_ALLOC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"PK - Memory allocation failed\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_TYPE_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"PK - Type mismatch, eg attempt to encrypt with an ECDSA key\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"PK - Bad input parameters to function\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_FILE_IO_ERROR) )\n            mbedtls_snprintf( buf, buflen, \"PK - Read/write of file failed\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_KEY_INVALID_VERSION) )\n            mbedtls_snprintf( buf, buflen, \"PK - Unsupported key version\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT) )\n            mbedtls_snprintf( buf, buflen, \"PK - Invalid key tag or value\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_UNKNOWN_PK_ALG) )\n            mbedtls_snprintf( buf, buflen, \"PK - Key algorithm is unsupported (only RSA and EC are supported)\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_PASSWORD_REQUIRED) )\n            mbedtls_snprintf( buf, buflen, \"PK - Private key password can't be empty\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_PASSWORD_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"PK - Given private key password does not allow for correct decryption\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_INVALID_PUBKEY) )\n            mbedtls_snprintf( buf, buflen, \"PK - The pubkey tag or value is invalid (only RSA and EC are supported)\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_INVALID_ALG) )\n            mbedtls_snprintf( buf, buflen, \"PK - The algorithm tag or value is invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE) )\n            mbedtls_snprintf( buf, buflen, \"PK - Elliptic curve is unsupported (only NIST curves are supported)\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"PK - Unavailable feature, e.g. RSA disabled for RSA key\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_SIG_LEN_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"PK - The buffer contains a valid signature followed by more data\" );\n        if( use_ret == -(MBEDTLS_ERR_PK_HW_ACCEL_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"PK - PK hardware accelerator failed\" );\n#endif /* MBEDTLS_PK_C */\n\n#if defined(MBEDTLS_PKCS12_C)\n        if( use_ret == -(MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"PKCS12 - Bad input parameters to function\" );\n        if( use_ret == -(MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"PKCS12 - Feature not available, e.g. unsupported encryption scheme\" );\n        if( use_ret == -(MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT) )\n            mbedtls_snprintf( buf, buflen, \"PKCS12 - PBE ASN.1 data not as expected\" );\n        if( use_ret == -(MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"PKCS12 - Given private key password does not allow for correct decryption\" );\n#endif /* MBEDTLS_PKCS12_C */\n\n#if defined(MBEDTLS_PKCS5_C)\n        if( use_ret == -(MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"PKCS5 - Bad input parameters to function\" );\n        if( use_ret == -(MBEDTLS_ERR_PKCS5_INVALID_FORMAT) )\n            mbedtls_snprintf( buf, buflen, \"PKCS5 - Unexpected ASN.1 data\" );\n        if( use_ret == -(MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"PKCS5 - Requested encryption or digest alg not available\" );\n        if( use_ret == -(MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"PKCS5 - Given private key password does not allow for correct decryption\" );\n#endif /* MBEDTLS_PKCS5_C */\n\n#if defined(MBEDTLS_RSA_C)\n        if( use_ret == -(MBEDTLS_ERR_RSA_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"RSA - Bad input parameters to function\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_INVALID_PADDING) )\n            mbedtls_snprintf( buf, buflen, \"RSA - Input data contains invalid padding and is rejected\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_KEY_GEN_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"RSA - Something failed during generation of a key\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_KEY_CHECK_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"RSA - Key failed to pass the validity check of the library\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_PUBLIC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"RSA - The public key operation failed\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_PRIVATE_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"RSA - The private key operation failed\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_VERIFY_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"RSA - The PKCS#1 verification failed\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE) )\n            mbedtls_snprintf( buf, buflen, \"RSA - The output buffer for decryption is not large enough\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_RNG_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"RSA - The random generator failed to generate non-zeros\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION) )\n            mbedtls_snprintf( buf, buflen, \"RSA - The implementation does not offer the requested operation, for example, because of security violations or lack of functionality\" );\n        if( use_ret == -(MBEDTLS_ERR_RSA_HW_ACCEL_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"RSA - RSA hardware accelerator failed\" );\n#endif /* MBEDTLS_RSA_C */\n\n#if defined(MBEDTLS_SSL_TLS_C)\n        if( use_ret == -(MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The requested feature is not available\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Bad input parameters to function\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_MAC) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Verification of the message MAC failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_RECORD) )\n            mbedtls_snprintf( buf, buflen, \"SSL - An invalid SSL record was received\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_CONN_EOF) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The connection indicated an EOF\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_UNKNOWN_CIPHER) )\n            mbedtls_snprintf( buf, buflen, \"SSL - An unknown cipher was received\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The server has no ciphersuites in common with the client\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_NO_RNG) )\n            mbedtls_snprintf( buf, buflen, \"SSL - No RNG was provided to the SSL module\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - No client certification received from the client, but required by the authentication mode\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Our own certificate(s) is/are too large to send in an SSL message\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The own certificate is not set, but needed by the server\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The own private key or pre-shared key is not set, but needed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - No CA Chain is set, but required to operate\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - An unexpected message was received from our peer\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE) )\n        {\n            mbedtls_snprintf( buf, buflen, \"SSL - A fatal alert message was received from our peer\" );\n            return;\n        }\n        if( use_ret == -(MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Verification of our peer failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The peer notified us that the connection is going to be closed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the ClientHello handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the ServerHello handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the Certificate handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the CertificateRequest handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the ServerKeyExchange handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the ServerHelloDone handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the ClientKeyExchange handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Read Public\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Calculate Secret\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the CertificateVerify handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the ChangeCipherSpec handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_FINISHED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the Finished handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_ALLOC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Memory allocation failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_HW_ACCEL_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Hardware acceleration function returned with error\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Hardware acceleration function skipped / left alone data\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_COMPRESSION_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the compression / decompression failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Handshake protocol not within min/max boundaries\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Processing of the NewSessionTicket handshake message failed\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Session ticket has expired\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Public key type mismatch (eg, asked for RSA key exchange and presented EC key)\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Unknown identity received (eg, PSK identity)\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_INTERNAL_ERROR) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Internal error (eg, unexpected failure in lower-level module)\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_COUNTER_WRAPPING) )\n            mbedtls_snprintf( buf, buflen, \"SSL - A counter would wrap (eg, too many messages exchanged)\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Unexpected message at ServerHello in renegotiation\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) )\n            mbedtls_snprintf( buf, buflen, \"SSL - DTLS client must retry for hello verification\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL) )\n            mbedtls_snprintf( buf, buflen, \"SSL - A buffer is too small to receive or write a message\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages)\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_WANT_READ) )\n            mbedtls_snprintf( buf, buflen, \"SSL - No data of requested type currently available on underlying transport\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_WANT_WRITE) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Connection requires a write call\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_TIMEOUT) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The operation timed out\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_CLIENT_RECONNECT) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The client initiated a reconnect from the same port\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_RECORD) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Record header looks valid but is not expected\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_NON_FATAL) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The alert message received indicates a non-fatal error\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Couldn't set the hash for verifying CertificateVerify\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_CONTINUE_PROCESSING) )\n            mbedtls_snprintf( buf, buflen, \"SSL - Internal-only message signaling that further message-processing should be done\" );\n        if( use_ret == -(MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) )\n            mbedtls_snprintf( buf, buflen, \"SSL - The asynchronous operation is not completed yet\" );\n#endif /* MBEDTLS_SSL_TLS_C */\n\n#if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C)\n        if( use_ret == -(MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Unavailable feature, e.g. RSA hashing/encryption combination\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_OID) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Requested OID is unknown\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_INVALID_FORMAT) )\n            mbedtls_snprintf( buf, buflen, \"X509 - The CRT/CRL/CSR format is invalid, e.g. different type expected\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_INVALID_VERSION) )\n            mbedtls_snprintf( buf, buflen, \"X509 - The CRT/CRL/CSR version element is invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_INVALID_SERIAL) )\n            mbedtls_snprintf( buf, buflen, \"X509 - The serial tag or value is invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_INVALID_ALG) )\n            mbedtls_snprintf( buf, buflen, \"X509 - The algorithm tag or value is invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_INVALID_NAME) )\n            mbedtls_snprintf( buf, buflen, \"X509 - The name tag or value is invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_INVALID_DATE) )\n            mbedtls_snprintf( buf, buflen, \"X509 - The date tag or value is invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_INVALID_SIGNATURE) )\n            mbedtls_snprintf( buf, buflen, \"X509 - The signature tag or value invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_INVALID_EXTENSIONS) )\n            mbedtls_snprintf( buf, buflen, \"X509 - The extension tag or value is invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_VERSION) )\n            mbedtls_snprintf( buf, buflen, \"X509 - CRT/CRL/CSR has an unsupported version number\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Signature algorithm (oid) is unsupported\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_SIG_MISMATCH) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Signature algorithms do not match. (see \\\\c ::mbedtls_x509_crt sig_oid)\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Certificate verification failed, e.g. CRL, CA or signature check failed\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Format not recognized as DER or PEM\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_BAD_INPUT_DATA) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Input invalid\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_ALLOC_FAILED) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Allocation of memory failed\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_FILE_IO_ERROR) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Read/write of file failed\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_BUFFER_TOO_SMALL) )\n            mbedtls_snprintf( buf, buflen, \"X509 - Destination buffer is too small\" );\n        if( use_ret == -(MBEDTLS_ERR_X509_FATAL_ERROR) )\n            mbedtls_snprintf( buf, buflen, \"X509 - A fatal error occured, eg the chain is too long or the vrfy callback failed\" );\n#endif /* MBEDTLS_X509_USE_C || MBEDTLS_X509_CREATE_C */\n        // END generated code\n\n        if( strlen( buf ) == 0 )\n            mbedtls_snprintf( buf, buflen, \"UNKNOWN ERROR CODE (%04X)\", use_ret );\n    }\n\n    use_ret = ret & ~0xFF80;\n\n    if( use_ret == 0 )\n        return;\n\n    // If high level code is present, make a concatenation between both\n    // error strings.\n    //\n    len = strlen( buf );\n\n    if( len > 0 )\n    {\n        if( buflen - len < 5 )\n            return;\n\n        mbedtls_snprintf( buf + len, buflen - len, \" : \" );\n\n        buf += len + 3;\n        buflen -= len + 3;\n    }\n\n    // Low level error codes\n    //\n    // BEGIN generated code\n#if defined(MBEDTLS_AES_C)\n    if( use_ret == -(MBEDTLS_ERR_AES_INVALID_KEY_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"AES - Invalid key length\" );\n    if( use_ret == -(MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"AES - Invalid data input length\" );\n    if( use_ret == -(MBEDTLS_ERR_AES_BAD_INPUT_DATA) )\n        mbedtls_snprintf( buf, buflen, \"AES - Invalid input data\" );\n    if( use_ret == -(MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE) )\n        mbedtls_snprintf( buf, buflen, \"AES - Feature not available. For example, an unsupported AES key size\" );\n    if( use_ret == -(MBEDTLS_ERR_AES_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"AES - AES hardware accelerator failed\" );\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_ARC4_C)\n    if( use_ret == -(MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"ARC4 - ARC4 hardware accelerator failed\" );\n#endif /* MBEDTLS_ARC4_C */\n\n#if defined(MBEDTLS_ARIA_C)\n    if( use_ret == -(MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"ARIA - Invalid key length\" );\n    if( use_ret == -(MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"ARIA - Invalid data input length\" );\n    if( use_ret == -(MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE) )\n        mbedtls_snprintf( buf, buflen, \"ARIA - Feature not available. For example, an unsupported ARIA key size\" );\n    if( use_ret == -(MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"ARIA - ARIA hardware accelerator failed\" );\n#endif /* MBEDTLS_ARIA_C */\n\n#if defined(MBEDTLS_ASN1_PARSE_C)\n    if( use_ret == -(MBEDTLS_ERR_ASN1_OUT_OF_DATA) )\n        mbedtls_snprintf( buf, buflen, \"ASN1 - Out of data when parsing an ASN1 data structure\" );\n    if( use_ret == -(MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) )\n        mbedtls_snprintf( buf, buflen, \"ASN1 - ASN1 tag was of an unexpected value\" );\n    if( use_ret == -(MBEDTLS_ERR_ASN1_INVALID_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"ASN1 - Error when trying to determine the length or invalid length\" );\n    if( use_ret == -(MBEDTLS_ERR_ASN1_LENGTH_MISMATCH) )\n        mbedtls_snprintf( buf, buflen, \"ASN1 - Actual length differs from expected length\" );\n    if( use_ret == -(MBEDTLS_ERR_ASN1_INVALID_DATA) )\n        mbedtls_snprintf( buf, buflen, \"ASN1 - Data is invalid. (not used)\" );\n    if( use_ret == -(MBEDTLS_ERR_ASN1_ALLOC_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"ASN1 - Memory allocation failed\" );\n    if( use_ret == -(MBEDTLS_ERR_ASN1_BUF_TOO_SMALL) )\n        mbedtls_snprintf( buf, buflen, \"ASN1 - Buffer too small when writing ASN.1 data structure\" );\n#endif /* MBEDTLS_ASN1_PARSE_C */\n\n#if defined(MBEDTLS_BASE64_C)\n    if( use_ret == -(MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL) )\n        mbedtls_snprintf( buf, buflen, \"BASE64 - Output buffer too small\" );\n    if( use_ret == -(MBEDTLS_ERR_BASE64_INVALID_CHARACTER) )\n        mbedtls_snprintf( buf, buflen, \"BASE64 - Invalid character in input\" );\n#endif /* MBEDTLS_BASE64_C */\n\n#if defined(MBEDTLS_BIGNUM_C)\n    if( use_ret == -(MBEDTLS_ERR_MPI_FILE_IO_ERROR) )\n        mbedtls_snprintf( buf, buflen, \"BIGNUM - An error occurred while reading from or writing to a file\" );\n    if( use_ret == -(MBEDTLS_ERR_MPI_BAD_INPUT_DATA) )\n        mbedtls_snprintf( buf, buflen, \"BIGNUM - Bad input parameters to function\" );\n    if( use_ret == -(MBEDTLS_ERR_MPI_INVALID_CHARACTER) )\n        mbedtls_snprintf( buf, buflen, \"BIGNUM - There is an invalid character in the digit string\" );\n    if( use_ret == -(MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL) )\n        mbedtls_snprintf( buf, buflen, \"BIGNUM - The buffer is too small to write to\" );\n    if( use_ret == -(MBEDTLS_ERR_MPI_NEGATIVE_VALUE) )\n        mbedtls_snprintf( buf, buflen, \"BIGNUM - The input arguments are negative or result in illegal output\" );\n    if( use_ret == -(MBEDTLS_ERR_MPI_DIVISION_BY_ZERO) )\n        mbedtls_snprintf( buf, buflen, \"BIGNUM - The input argument for division is zero, which is not allowed\" );\n    if( use_ret == -(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) )\n        mbedtls_snprintf( buf, buflen, \"BIGNUM - The input arguments are not acceptable\" );\n    if( use_ret == -(MBEDTLS_ERR_MPI_ALLOC_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"BIGNUM - Memory allocation failed\" );\n#endif /* MBEDTLS_BIGNUM_C */\n\n#if defined(MBEDTLS_BLOWFISH_C)\n    if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"BLOWFISH - Invalid key length\" );\n    if( use_ret == -(MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"BLOWFISH - Blowfish hardware accelerator failed\" );\n    if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"BLOWFISH - Invalid data input length\" );\n#endif /* MBEDTLS_BLOWFISH_C */\n\n#if defined(MBEDTLS_CAMELLIA_C)\n    if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"CAMELLIA - Invalid key length\" );\n    if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"CAMELLIA - Invalid data input length\" );\n    if( use_ret == -(MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"CAMELLIA - Camellia hardware accelerator failed\" );\n#endif /* MBEDTLS_CAMELLIA_C */\n\n#if defined(MBEDTLS_CCM_C)\n    if( use_ret == -(MBEDTLS_ERR_CCM_BAD_INPUT) )\n        mbedtls_snprintf( buf, buflen, \"CCM - Bad input parameters to the function\" );\n    if( use_ret == -(MBEDTLS_ERR_CCM_AUTH_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"CCM - Authenticated decryption failed\" );\n    if( use_ret == -(MBEDTLS_ERR_CCM_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"CCM - CCM hardware accelerator failed\" );\n#endif /* MBEDTLS_CCM_C */\n\n#if defined(MBEDTLS_CHACHA20_C)\n    if( use_ret == -(MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA) )\n        mbedtls_snprintf( buf, buflen, \"CHACHA20 - Invalid input parameter(s)\" );\n    if( use_ret == -(MBEDTLS_ERR_CHACHA20_FEATURE_UNAVAILABLE) )\n        mbedtls_snprintf( buf, buflen, \"CHACHA20 - Feature not available. For example, s part of the API is not implemented\" );\n    if( use_ret == -(MBEDTLS_ERR_CHACHA20_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"CHACHA20 - Chacha20 hardware accelerator failed\" );\n#endif /* MBEDTLS_CHACHA20_C */\n\n#if defined(MBEDTLS_CHACHAPOLY_C)\n    if( use_ret == -(MBEDTLS_ERR_CHACHAPOLY_BAD_STATE) )\n        mbedtls_snprintf( buf, buflen, \"CHACHAPOLY - The requested operation is not permitted in the current state\" );\n    if( use_ret == -(MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"CHACHAPOLY - Authenticated decryption failed: data was not authentic\" );\n#endif /* MBEDTLS_CHACHAPOLY_C */\n\n#if defined(MBEDTLS_CMAC_C)\n    if( use_ret == -(MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"CMAC - CMAC hardware accelerator failed\" );\n#endif /* MBEDTLS_CMAC_C */\n\n#if defined(MBEDTLS_CTR_DRBG_C)\n    if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"CTR_DRBG - The entropy source failed\" );\n    if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG) )\n        mbedtls_snprintf( buf, buflen, \"CTR_DRBG - The requested random buffer length is too big\" );\n    if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG) )\n        mbedtls_snprintf( buf, buflen, \"CTR_DRBG - The input (entropy + additional data) is too large\" );\n    if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR) )\n        mbedtls_snprintf( buf, buflen, \"CTR_DRBG - Read or write error in file\" );\n#endif /* MBEDTLS_CTR_DRBG_C */\n\n#if defined(MBEDTLS_DES_C)\n    if( use_ret == -(MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"DES - The data input has an invalid length\" );\n    if( use_ret == -(MBEDTLS_ERR_DES_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"DES - DES hardware accelerator failed\" );\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_ENTROPY_C)\n    if( use_ret == -(MBEDTLS_ERR_ENTROPY_SOURCE_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"ENTROPY - Critical entropy source failure\" );\n    if( use_ret == -(MBEDTLS_ERR_ENTROPY_MAX_SOURCES) )\n        mbedtls_snprintf( buf, buflen, \"ENTROPY - No more sources can be added\" );\n    if( use_ret == -(MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED) )\n        mbedtls_snprintf( buf, buflen, \"ENTROPY - No sources have been added to poll\" );\n    if( use_ret == -(MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE) )\n        mbedtls_snprintf( buf, buflen, \"ENTROPY - No strong sources have been added to poll\" );\n    if( use_ret == -(MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR) )\n        mbedtls_snprintf( buf, buflen, \"ENTROPY - Read/write error in file\" );\n#endif /* MBEDTLS_ENTROPY_C */\n\n#if defined(MBEDTLS_GCM_C)\n    if( use_ret == -(MBEDTLS_ERR_GCM_AUTH_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"GCM - Authenticated decryption failed\" );\n    if( use_ret == -(MBEDTLS_ERR_GCM_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"GCM - GCM hardware accelerator failed\" );\n    if( use_ret == -(MBEDTLS_ERR_GCM_BAD_INPUT) )\n        mbedtls_snprintf( buf, buflen, \"GCM - Bad input parameters to function\" );\n#endif /* MBEDTLS_GCM_C */\n\n#if defined(MBEDTLS_HKDF_C)\n    if( use_ret == -(MBEDTLS_ERR_HKDF_BAD_INPUT_DATA) )\n        mbedtls_snprintf( buf, buflen, \"HKDF - Bad input parameters to function\" );\n#endif /* MBEDTLS_HKDF_C */\n\n#if defined(MBEDTLS_HMAC_DRBG_C)\n    if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG) )\n        mbedtls_snprintf( buf, buflen, \"HMAC_DRBG - Too many random requested in single call\" );\n    if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG) )\n        mbedtls_snprintf( buf, buflen, \"HMAC_DRBG - Input too large (Entropy + additional)\" );\n    if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR) )\n        mbedtls_snprintf( buf, buflen, \"HMAC_DRBG - Read/write error in file\" );\n    if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"HMAC_DRBG - The entropy source failed\" );\n#endif /* MBEDTLS_HMAC_DRBG_C */\n\n#if defined(MBEDTLS_MD2_C)\n    if( use_ret == -(MBEDTLS_ERR_MD2_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"MD2 - MD2 hardware accelerator failed\" );\n#endif /* MBEDTLS_MD2_C */\n\n#if defined(MBEDTLS_MD4_C)\n    if( use_ret == -(MBEDTLS_ERR_MD4_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"MD4 - MD4 hardware accelerator failed\" );\n#endif /* MBEDTLS_MD4_C */\n\n#if defined(MBEDTLS_MD5_C)\n    if( use_ret == -(MBEDTLS_ERR_MD5_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"MD5 - MD5 hardware accelerator failed\" );\n#endif /* MBEDTLS_MD5_C */\n\n#if defined(MBEDTLS_NET_C)\n    if( use_ret == -(MBEDTLS_ERR_NET_SOCKET_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"NET - Failed to open a socket\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_CONNECT_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"NET - The connection to the given server / port failed\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_BIND_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"NET - Binding of the socket failed\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_LISTEN_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"NET - Could not listen on the socket\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_ACCEPT_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"NET - Could not accept the incoming connection\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_RECV_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"NET - Reading information from the socket failed\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_SEND_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"NET - Sending information through the socket failed\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_CONN_RESET) )\n        mbedtls_snprintf( buf, buflen, \"NET - Connection was reset by peer\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_UNKNOWN_HOST) )\n        mbedtls_snprintf( buf, buflen, \"NET - Failed to get an IP address for the given hostname\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_BUFFER_TOO_SMALL) )\n        mbedtls_snprintf( buf, buflen, \"NET - Buffer is too small to hold the data\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_INVALID_CONTEXT) )\n        mbedtls_snprintf( buf, buflen, \"NET - The context is invalid, eg because it was free()ed\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_POLL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"NET - Polling the net context failed\" );\n    if( use_ret == -(MBEDTLS_ERR_NET_BAD_INPUT_DATA) )\n        mbedtls_snprintf( buf, buflen, \"NET - Input invalid\" );\n#endif /* MBEDTLS_NET_C */\n\n#if defined(MBEDTLS_OID_C)\n    if( use_ret == -(MBEDTLS_ERR_OID_NOT_FOUND) )\n        mbedtls_snprintf( buf, buflen, \"OID - OID is not found\" );\n    if( use_ret == -(MBEDTLS_ERR_OID_BUF_TOO_SMALL) )\n        mbedtls_snprintf( buf, buflen, \"OID - output buffer is too small\" );\n#endif /* MBEDTLS_OID_C */\n\n#if defined(MBEDTLS_PADLOCK_C)\n    if( use_ret == -(MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED) )\n        mbedtls_snprintf( buf, buflen, \"PADLOCK - Input data should be aligned\" );\n#endif /* MBEDTLS_PADLOCK_C */\n\n#if defined(MBEDTLS_POLY1305_C)\n    if( use_ret == -(MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA) )\n        mbedtls_snprintf( buf, buflen, \"POLY1305 - Invalid input parameter(s)\" );\n    if( use_ret == -(MBEDTLS_ERR_POLY1305_FEATURE_UNAVAILABLE) )\n        mbedtls_snprintf( buf, buflen, \"POLY1305 - Feature not available. For example, s part of the API is not implemented\" );\n    if( use_ret == -(MBEDTLS_ERR_POLY1305_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"POLY1305 - Poly1305 hardware accelerator failed\" );\n#endif /* MBEDTLS_POLY1305_C */\n\n#if defined(MBEDTLS_RIPEMD160_C)\n    if( use_ret == -(MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"RIPEMD160 - RIPEMD160 hardware accelerator failed\" );\n#endif /* MBEDTLS_RIPEMD160_C */\n\n#if defined(MBEDTLS_SHA1_C)\n    if( use_ret == -(MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"SHA1 - SHA-1 hardware accelerator failed\" );\n#endif /* MBEDTLS_SHA1_C */\n\n#if defined(MBEDTLS_SHA256_C)\n    if( use_ret == -(MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"SHA256 - SHA-256 hardware accelerator failed\" );\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n    if( use_ret == -(MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"SHA512 - SHA-512 hardware accelerator failed\" );\n#endif /* MBEDTLS_SHA512_C */\n\n#if defined(MBEDTLS_THREADING_C)\n    if( use_ret == -(MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE) )\n        mbedtls_snprintf( buf, buflen, \"THREADING - The selected feature is not available\" );\n    if( use_ret == -(MBEDTLS_ERR_THREADING_BAD_INPUT_DATA) )\n        mbedtls_snprintf( buf, buflen, \"THREADING - Bad input parameters to function\" );\n    if( use_ret == -(MBEDTLS_ERR_THREADING_MUTEX_ERROR) )\n        mbedtls_snprintf( buf, buflen, \"THREADING - Locking / unlocking / free failed with error code\" );\n#endif /* MBEDTLS_THREADING_C */\n\n#if defined(MBEDTLS_XTEA_C)\n    if( use_ret == -(MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH) )\n        mbedtls_snprintf( buf, buflen, \"XTEA - The data input has an invalid length\" );\n    if( use_ret == -(MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED) )\n        mbedtls_snprintf( buf, buflen, \"XTEA - XTEA hardware accelerator failed\" );\n#endif /* MBEDTLS_XTEA_C */\n    // END generated code\n\n    if( strlen( buf ) != 0 )\n        return;\n\n    mbedtls_snprintf( buf, buflen, \"UNKNOWN ERROR CODE (%04X)\", use_ret );\n}\n\n#else /* MBEDTLS_ERROR_C */\n\n#if defined(MBEDTLS_ERROR_STRERROR_DUMMY)\n\n/*\n * Provide an non-function in case MBEDTLS_ERROR_C is not defined\n */\nvoid mbedtls_strerror( int ret, char *buf, size_t buflen )\n{\n    ((void) ret);\n\n    if( buflen > 0 )\n        buf[0] = '\\0';\n}\n\n#endif /* MBEDTLS_ERROR_STRERROR_DUMMY */\n\n#endif /* MBEDTLS_ERROR_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/gcm.c",
    "content": "/*\n *  NIST SP800-38D compliant GCM implementation\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n/*\n * http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf\n *\n * See also:\n * [MGV] http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf\n *\n * We use the algorithm described as Shoup's method with 4-bit tables in\n * [MGV] 4.1, pp. 12-13, to enhance speed without using too much memory.\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_GCM_C)\n\n#include \"mbedtls/gcm.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_AESNI_C)\n#include \"mbedtls/aesni.h\"\n#endif\n\n#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)\n#include \"mbedtls/aes.h\"\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */\n\n#if !defined(MBEDTLS_GCM_ALT)\n\n/*\n * 32-bit integer manipulation macros (big endian)\n */\n#ifndef GET_UINT32_BE\n#define GET_UINT32_BE(n,b,i)                            \\\n{                                                       \\\n    (n) = ( (uint32_t) (b)[(i)    ] << 24 )             \\\n        | ( (uint32_t) (b)[(i) + 1] << 16 )             \\\n        | ( (uint32_t) (b)[(i) + 2] <<  8 )             \\\n        | ( (uint32_t) (b)[(i) + 3]       );            \\\n}\n#endif\n\n#ifndef PUT_UINT32_BE\n#define PUT_UINT32_BE(n,b,i)                            \\\n{                                                       \\\n    (b)[(i)    ] = (unsigned char) ( (n) >> 24 );       \\\n    (b)[(i) + 1] = (unsigned char) ( (n) >> 16 );       \\\n    (b)[(i) + 2] = (unsigned char) ( (n) >>  8 );       \\\n    (b)[(i) + 3] = (unsigned char) ( (n)       );       \\\n}\n#endif\n\n/*\n * Initialize a context\n */\nvoid mbedtls_gcm_init( mbedtls_gcm_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_gcm_context ) );\n}\n\n/*\n * Precompute small multiples of H, that is set\n *      HH[i] || HL[i] = H times i,\n * where i is seen as a field element as in [MGV], ie high-order bits\n * correspond to low powers of P. The result is stored in the same way, that\n * is the high-order bit of HH corresponds to P^0 and the low-order bit of HL\n * corresponds to P^127.\n */\nstatic int gcm_gen_table( mbedtls_gcm_context *ctx )\n{\n    int ret, i, j;\n    uint64_t hi, lo;\n    uint64_t vl, vh;\n    unsigned char h[16];\n    size_t olen = 0;\n\n    memset( h, 0, 16 );\n    if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, h, 16, h, &olen ) ) != 0 )\n        return( ret );\n\n    /* pack h as two 64-bits ints, big-endian */\n    GET_UINT32_BE( hi, h,  0  );\n    GET_UINT32_BE( lo, h,  4  );\n    vh = (uint64_t) hi << 32 | lo;\n\n    GET_UINT32_BE( hi, h,  8  );\n    GET_UINT32_BE( lo, h,  12 );\n    vl = (uint64_t) hi << 32 | lo;\n\n    /* 8 = 1000 corresponds to 1 in GF(2^128) */\n    ctx->HL[8] = vl;\n    ctx->HH[8] = vh;\n\n#if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64)\n    /* With CLMUL support, we need only h, not the rest of the table */\n    if( mbedtls_aesni_has_support( MBEDTLS_AESNI_CLMUL ) )\n        return( 0 );\n#endif\n\n    /* 0 corresponds to 0 in GF(2^128) */\n    ctx->HH[0] = 0;\n    ctx->HL[0] = 0;\n\n    for( i = 4; i > 0; i >>= 1 )\n    {\n        uint32_t T = ( vl & 1 ) * 0xe1000000U;\n        vl  = ( vh << 63 ) | ( vl >> 1 );\n        vh  = ( vh >> 1 ) ^ ( (uint64_t) T << 32);\n\n        ctx->HL[i] = vl;\n        ctx->HH[i] = vh;\n    }\n\n    for( i = 2; i <= 8; i *= 2 )\n    {\n        uint64_t *HiL = ctx->HL + i, *HiH = ctx->HH + i;\n        vh = *HiH;\n        vl = *HiL;\n        for( j = 1; j < i; j++ )\n        {\n            HiH[j] = vh ^ ctx->HH[j];\n            HiL[j] = vl ^ ctx->HL[j];\n        }\n    }\n\n    return( 0 );\n}\n\nint mbedtls_gcm_setkey( mbedtls_gcm_context *ctx,\n                        mbedtls_cipher_id_t cipher,\n                        const unsigned char *key,\n                        unsigned int keybits )\n{\n    int ret;\n    const mbedtls_cipher_info_t *cipher_info;\n\n    cipher_info = mbedtls_cipher_info_from_values( cipher, keybits, MBEDTLS_MODE_ECB );\n    if( cipher_info == NULL )\n        return( MBEDTLS_ERR_GCM_BAD_INPUT );\n\n    if( cipher_info->block_size != 16 )\n        return( MBEDTLS_ERR_GCM_BAD_INPUT );\n\n    mbedtls_cipher_free( &ctx->cipher_ctx );\n\n    if( ( ret = mbedtls_cipher_setup( &ctx->cipher_ctx, cipher_info ) ) != 0 )\n        return( ret );\n\n    if( ( ret = mbedtls_cipher_setkey( &ctx->cipher_ctx, key, keybits,\n                               MBEDTLS_ENCRYPT ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    if( ( ret = gcm_gen_table( ctx ) ) != 0 )\n        return( ret );\n\n    return( 0 );\n}\n\n/*\n * Shoup's method for multiplication use this table with\n *      last4[x] = x times P^128\n * where x and last4[x] are seen as elements of GF(2^128) as in [MGV]\n */\nstatic const uint64_t last4[16] =\n{\n    0x0000, 0x1c20, 0x3840, 0x2460,\n    0x7080, 0x6ca0, 0x48c0, 0x54e0,\n    0xe100, 0xfd20, 0xd940, 0xc560,\n    0x9180, 0x8da0, 0xa9c0, 0xb5e0\n};\n\n/*\n * Sets output to x times H using the precomputed tables.\n * x and output are seen as elements of GF(2^128) as in [MGV].\n */\nstatic void gcm_mult( mbedtls_gcm_context *ctx, const unsigned char x[16],\n                      unsigned char output[16] )\n{\n    int i = 0;\n    unsigned char lo, hi, rem;\n    uint64_t zh, zl;\n\n#if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64)\n    if( mbedtls_aesni_has_support( MBEDTLS_AESNI_CLMUL ) ) {\n        unsigned char h[16];\n\n        PUT_UINT32_BE( ctx->HH[8] >> 32, h,  0 );\n        PUT_UINT32_BE( ctx->HH[8],       h,  4 );\n        PUT_UINT32_BE( ctx->HL[8] >> 32, h,  8 );\n        PUT_UINT32_BE( ctx->HL[8],       h, 12 );\n\n        mbedtls_aesni_gcm_mult( output, x, h );\n        return;\n    }\n#endif /* MBEDTLS_AESNI_C && MBEDTLS_HAVE_X86_64 */\n\n    lo = x[15] & 0xf;\n\n    zh = ctx->HH[lo];\n    zl = ctx->HL[lo];\n\n    for( i = 15; i >= 0; i-- )\n    {\n        lo = x[i] & 0xf;\n        hi = x[i] >> 4;\n\n        if( i != 15 )\n        {\n            rem = (unsigned char) zl & 0xf;\n            zl = ( zh << 60 ) | ( zl >> 4 );\n            zh = ( zh >> 4 );\n            zh ^= (uint64_t) last4[rem] << 48;\n            zh ^= ctx->HH[lo];\n            zl ^= ctx->HL[lo];\n\n        }\n\n        rem = (unsigned char) zl & 0xf;\n        zl = ( zh << 60 ) | ( zl >> 4 );\n        zh = ( zh >> 4 );\n        zh ^= (uint64_t) last4[rem] << 48;\n        zh ^= ctx->HH[hi];\n        zl ^= ctx->HL[hi];\n    }\n\n    PUT_UINT32_BE( zh >> 32, output, 0 );\n    PUT_UINT32_BE( zh, output, 4 );\n    PUT_UINT32_BE( zl >> 32, output, 8 );\n    PUT_UINT32_BE( zl, output, 12 );\n}\n\nint mbedtls_gcm_starts( mbedtls_gcm_context *ctx,\n                int mode,\n                const unsigned char *iv,\n                size_t iv_len,\n                const unsigned char *add,\n                size_t add_len )\n{\n    int ret;\n    unsigned char work_buf[16];\n    size_t i;\n    const unsigned char *p;\n    size_t use_len, olen = 0;\n\n    /* IV and AD are limited to 2^64 bits, so 2^61 bytes */\n    /* IV is not allowed to be zero length */\n    if( iv_len == 0 ||\n      ( (uint64_t) iv_len  ) >> 61 != 0 ||\n      ( (uint64_t) add_len ) >> 61 != 0 )\n    {\n        return( MBEDTLS_ERR_GCM_BAD_INPUT );\n    }\n\n    memset( ctx->y, 0x00, sizeof(ctx->y) );\n    memset( ctx->buf, 0x00, sizeof(ctx->buf) );\n\n    ctx->mode = mode;\n    ctx->len = 0;\n    ctx->add_len = 0;\n\n    if( iv_len == 12 )\n    {\n        memcpy( ctx->y, iv, iv_len );\n        ctx->y[15] = 1;\n    }\n    else\n    {\n        memset( work_buf, 0x00, 16 );\n        PUT_UINT32_BE( iv_len * 8, work_buf, 12 );\n\n        p = iv;\n        while( iv_len > 0 )\n        {\n            use_len = ( iv_len < 16 ) ? iv_len : 16;\n\n            for( i = 0; i < use_len; i++ )\n                ctx->y[i] ^= p[i];\n\n            gcm_mult( ctx, ctx->y, ctx->y );\n\n            iv_len -= use_len;\n            p += use_len;\n        }\n\n        for( i = 0; i < 16; i++ )\n            ctx->y[i] ^= work_buf[i];\n\n        gcm_mult( ctx, ctx->y, ctx->y );\n    }\n\n    if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, ctx->y, 16, ctx->base_ectr,\n                             &olen ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    ctx->add_len = add_len;\n    p = add;\n    while( add_len > 0 )\n    {\n        use_len = ( add_len < 16 ) ? add_len : 16;\n\n        for( i = 0; i < use_len; i++ )\n            ctx->buf[i] ^= p[i];\n\n        gcm_mult( ctx, ctx->buf, ctx->buf );\n\n        add_len -= use_len;\n        p += use_len;\n    }\n\n    return( 0 );\n}\n\nint mbedtls_gcm_update( mbedtls_gcm_context *ctx,\n                size_t length,\n                const unsigned char *input,\n                unsigned char *output )\n{\n    int ret;\n    unsigned char ectr[16];\n    size_t i;\n    const unsigned char *p;\n    unsigned char *out_p = output;\n    size_t use_len, olen = 0;\n\n    if( output > input && (size_t) ( output - input ) < length )\n        return( MBEDTLS_ERR_GCM_BAD_INPUT );\n\n    /* Total length is restricted to 2^39 - 256 bits, ie 2^36 - 2^5 bytes\n     * Also check for possible overflow */\n    if( ctx->len + length < ctx->len ||\n        (uint64_t) ctx->len + length > 0xFFFFFFFE0ull )\n    {\n        return( MBEDTLS_ERR_GCM_BAD_INPUT );\n    }\n\n    ctx->len += length;\n\n    p = input;\n    while( length > 0 )\n    {\n        use_len = ( length < 16 ) ? length : 16;\n\n        for( i = 16; i > 12; i-- )\n            if( ++ctx->y[i - 1] != 0 )\n                break;\n\n        if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, ctx->y, 16, ectr,\n                                   &olen ) ) != 0 )\n        {\n            return( ret );\n        }\n\n        for( i = 0; i < use_len; i++ )\n        {\n            if( ctx->mode == MBEDTLS_GCM_DECRYPT )\n                ctx->buf[i] ^= p[i];\n            out_p[i] = ectr[i] ^ p[i];\n            if( ctx->mode == MBEDTLS_GCM_ENCRYPT )\n                ctx->buf[i] ^= out_p[i];\n        }\n\n        gcm_mult( ctx, ctx->buf, ctx->buf );\n\n        length -= use_len;\n        p += use_len;\n        out_p += use_len;\n    }\n\n    return( 0 );\n}\n\nint mbedtls_gcm_finish( mbedtls_gcm_context *ctx,\n                unsigned char *tag,\n                size_t tag_len )\n{\n    unsigned char work_buf[16];\n    size_t i;\n    uint64_t orig_len = ctx->len * 8;\n    uint64_t orig_add_len = ctx->add_len * 8;\n\n    if( tag_len > 16 || tag_len < 4 )\n        return( MBEDTLS_ERR_GCM_BAD_INPUT );\n\n    memcpy( tag, ctx->base_ectr, tag_len );\n\n    if( orig_len || orig_add_len )\n    {\n        memset( work_buf, 0x00, 16 );\n\n        PUT_UINT32_BE( ( orig_add_len >> 32 ), work_buf, 0  );\n        PUT_UINT32_BE( ( orig_add_len       ), work_buf, 4  );\n        PUT_UINT32_BE( ( orig_len     >> 32 ), work_buf, 8  );\n        PUT_UINT32_BE( ( orig_len           ), work_buf, 12 );\n\n        for( i = 0; i < 16; i++ )\n            ctx->buf[i] ^= work_buf[i];\n\n        gcm_mult( ctx, ctx->buf, ctx->buf );\n\n        for( i = 0; i < tag_len; i++ )\n            tag[i] ^= ctx->buf[i];\n    }\n\n    return( 0 );\n}\n\nint mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx,\n                       int mode,\n                       size_t length,\n                       const unsigned char *iv,\n                       size_t iv_len,\n                       const unsigned char *add,\n                       size_t add_len,\n                       const unsigned char *input,\n                       unsigned char *output,\n                       size_t tag_len,\n                       unsigned char *tag )\n{\n    int ret;\n\n    if( ( ret = mbedtls_gcm_starts( ctx, mode, iv, iv_len, add, add_len ) ) != 0 )\n        return( ret );\n\n    if( ( ret = mbedtls_gcm_update( ctx, length, input, output ) ) != 0 )\n        return( ret );\n\n    if( ( ret = mbedtls_gcm_finish( ctx, tag, tag_len ) ) != 0 )\n        return( ret );\n\n    return( 0 );\n}\n\nint mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx,\n                      size_t length,\n                      const unsigned char *iv,\n                      size_t iv_len,\n                      const unsigned char *add,\n                      size_t add_len,\n                      const unsigned char *tag,\n                      size_t tag_len,\n                      const unsigned char *input,\n                      unsigned char *output )\n{\n    int ret;\n    unsigned char check_tag[16];\n    size_t i;\n    int diff;\n\n    if( ( ret = mbedtls_gcm_crypt_and_tag( ctx, MBEDTLS_GCM_DECRYPT, length,\n                                   iv, iv_len, add, add_len,\n                                   input, output, tag_len, check_tag ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    /* Check tag in \"constant-time\" */\n    for( diff = 0, i = 0; i < tag_len; i++ )\n        diff |= tag[i] ^ check_tag[i];\n\n    if( diff != 0 )\n    {\n        mbedtls_platform_zeroize( output, length );\n        return( MBEDTLS_ERR_GCM_AUTH_FAILED );\n    }\n\n    return( 0 );\n}\n\nvoid mbedtls_gcm_free( mbedtls_gcm_context *ctx )\n{\n    mbedtls_cipher_free( &ctx->cipher_ctx );\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_gcm_context ) );\n}\n\n#endif /* !MBEDTLS_GCM_ALT */\n\n#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)\n/*\n * AES-GCM test vectors from:\n *\n * http://csrc.nist.gov/groups/STM/cavp/documents/mac/gcmtestvectors.zip\n */\n#define MAX_TESTS   6\n\nstatic const int key_index[MAX_TESTS] =\n    { 0, 0, 1, 1, 1, 1 };\n\nstatic const unsigned char key[MAX_TESTS][32] =\n{\n    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },\n    { 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c,\n      0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08,\n      0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c,\n      0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08 },\n};\n\nstatic const size_t iv_len[MAX_TESTS] =\n    { 12, 12, 12, 12, 8, 60 };\n\nstatic const int iv_index[MAX_TESTS] =\n    { 0, 0, 1, 1, 1, 2 };\n\nstatic const unsigned char iv[MAX_TESTS][64] =\n{\n    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00 },\n    { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad,\n      0xde, 0xca, 0xf8, 0x88 },\n    { 0x93, 0x13, 0x22, 0x5d, 0xf8, 0x84, 0x06, 0xe5,\n      0x55, 0x90, 0x9c, 0x5a, 0xff, 0x52, 0x69, 0xaa,\n      0x6a, 0x7a, 0x95, 0x38, 0x53, 0x4f, 0x7d, 0xa1,\n      0xe4, 0xc3, 0x03, 0xd2, 0xa3, 0x18, 0xa7, 0x28,\n      0xc3, 0xc0, 0xc9, 0x51, 0x56, 0x80, 0x95, 0x39,\n      0xfc, 0xf0, 0xe2, 0x42, 0x9a, 0x6b, 0x52, 0x54,\n      0x16, 0xae, 0xdb, 0xf5, 0xa0, 0xde, 0x6a, 0x57,\n      0xa6, 0x37, 0xb3, 0x9b },\n};\n\nstatic const size_t add_len[MAX_TESTS] =\n    { 0, 0, 0, 20, 20, 20 };\n\nstatic const int add_index[MAX_TESTS] =\n    { 0, 0, 0, 1, 1, 1 };\n\nstatic const unsigned char additional[MAX_TESTS][64] =\n{\n    { 0x00 },\n    { 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef,\n      0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef,\n      0xab, 0xad, 0xda, 0xd2 },\n};\n\nstatic const size_t pt_len[MAX_TESTS] =\n    { 0, 16, 64, 60, 60, 60 };\n\nstatic const int pt_index[MAX_TESTS] =\n    { 0, 0, 1, 1, 1, 1 };\n\nstatic const unsigned char pt[MAX_TESTS][64] =\n{\n    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },\n    { 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5,\n      0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a,\n      0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda,\n      0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72,\n      0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53,\n      0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25,\n      0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57,\n      0xba, 0x63, 0x7b, 0x39, 0x1a, 0xaf, 0xd2, 0x55 },\n};\n\nstatic const unsigned char ct[MAX_TESTS * 3][64] =\n{\n    { 0x00 },\n    { 0x03, 0x88, 0xda, 0xce, 0x60, 0xb6, 0xa3, 0x92,\n      0xf3, 0x28, 0xc2, 0xb9, 0x71, 0xb2, 0xfe, 0x78 },\n    { 0x42, 0x83, 0x1e, 0xc2, 0x21, 0x77, 0x74, 0x24,\n      0x4b, 0x72, 0x21, 0xb7, 0x84, 0xd0, 0xd4, 0x9c,\n      0xe3, 0xaa, 0x21, 0x2f, 0x2c, 0x02, 0xa4, 0xe0,\n      0x35, 0xc1, 0x7e, 0x23, 0x29, 0xac, 0xa1, 0x2e,\n      0x21, 0xd5, 0x14, 0xb2, 0x54, 0x66, 0x93, 0x1c,\n      0x7d, 0x8f, 0x6a, 0x5a, 0xac, 0x84, 0xaa, 0x05,\n      0x1b, 0xa3, 0x0b, 0x39, 0x6a, 0x0a, 0xac, 0x97,\n      0x3d, 0x58, 0xe0, 0x91, 0x47, 0x3f, 0x59, 0x85 },\n    { 0x42, 0x83, 0x1e, 0xc2, 0x21, 0x77, 0x74, 0x24,\n      0x4b, 0x72, 0x21, 0xb7, 0x84, 0xd0, 0xd4, 0x9c,\n      0xe3, 0xaa, 0x21, 0x2f, 0x2c, 0x02, 0xa4, 0xe0,\n      0x35, 0xc1, 0x7e, 0x23, 0x29, 0xac, 0xa1, 0x2e,\n      0x21, 0xd5, 0x14, 0xb2, 0x54, 0x66, 0x93, 0x1c,\n      0x7d, 0x8f, 0x6a, 0x5a, 0xac, 0x84, 0xaa, 0x05,\n      0x1b, 0xa3, 0x0b, 0x39, 0x6a, 0x0a, 0xac, 0x97,\n      0x3d, 0x58, 0xe0, 0x91 },\n    { 0x61, 0x35, 0x3b, 0x4c, 0x28, 0x06, 0x93, 0x4a,\n      0x77, 0x7f, 0xf5, 0x1f, 0xa2, 0x2a, 0x47, 0x55,\n      0x69, 0x9b, 0x2a, 0x71, 0x4f, 0xcd, 0xc6, 0xf8,\n      0x37, 0x66, 0xe5, 0xf9, 0x7b, 0x6c, 0x74, 0x23,\n      0x73, 0x80, 0x69, 0x00, 0xe4, 0x9f, 0x24, 0xb2,\n      0x2b, 0x09, 0x75, 0x44, 0xd4, 0x89, 0x6b, 0x42,\n      0x49, 0x89, 0xb5, 0xe1, 0xeb, 0xac, 0x0f, 0x07,\n      0xc2, 0x3f, 0x45, 0x98 },\n    { 0x8c, 0xe2, 0x49, 0x98, 0x62, 0x56, 0x15, 0xb6,\n      0x03, 0xa0, 0x33, 0xac, 0xa1, 0x3f, 0xb8, 0x94,\n      0xbe, 0x91, 0x12, 0xa5, 0xc3, 0xa2, 0x11, 0xa8,\n      0xba, 0x26, 0x2a, 0x3c, 0xca, 0x7e, 0x2c, 0xa7,\n      0x01, 0xe4, 0xa9, 0xa4, 0xfb, 0xa4, 0x3c, 0x90,\n      0xcc, 0xdc, 0xb2, 0x81, 0xd4, 0x8c, 0x7c, 0x6f,\n      0xd6, 0x28, 0x75, 0xd2, 0xac, 0xa4, 0x17, 0x03,\n      0x4c, 0x34, 0xae, 0xe5 },\n    { 0x00 },\n    { 0x98, 0xe7, 0x24, 0x7c, 0x07, 0xf0, 0xfe, 0x41,\n      0x1c, 0x26, 0x7e, 0x43, 0x84, 0xb0, 0xf6, 0x00 },\n    { 0x39, 0x80, 0xca, 0x0b, 0x3c, 0x00, 0xe8, 0x41,\n      0xeb, 0x06, 0xfa, 0xc4, 0x87, 0x2a, 0x27, 0x57,\n      0x85, 0x9e, 0x1c, 0xea, 0xa6, 0xef, 0xd9, 0x84,\n      0x62, 0x85, 0x93, 0xb4, 0x0c, 0xa1, 0xe1, 0x9c,\n      0x7d, 0x77, 0x3d, 0x00, 0xc1, 0x44, 0xc5, 0x25,\n      0xac, 0x61, 0x9d, 0x18, 0xc8, 0x4a, 0x3f, 0x47,\n      0x18, 0xe2, 0x44, 0x8b, 0x2f, 0xe3, 0x24, 0xd9,\n      0xcc, 0xda, 0x27, 0x10, 0xac, 0xad, 0xe2, 0x56 },\n    { 0x39, 0x80, 0xca, 0x0b, 0x3c, 0x00, 0xe8, 0x41,\n      0xeb, 0x06, 0xfa, 0xc4, 0x87, 0x2a, 0x27, 0x57,\n      0x85, 0x9e, 0x1c, 0xea, 0xa6, 0xef, 0xd9, 0x84,\n      0x62, 0x85, 0x93, 0xb4, 0x0c, 0xa1, 0xe1, 0x9c,\n      0x7d, 0x77, 0x3d, 0x00, 0xc1, 0x44, 0xc5, 0x25,\n      0xac, 0x61, 0x9d, 0x18, 0xc8, 0x4a, 0x3f, 0x47,\n      0x18, 0xe2, 0x44, 0x8b, 0x2f, 0xe3, 0x24, 0xd9,\n      0xcc, 0xda, 0x27, 0x10 },\n    { 0x0f, 0x10, 0xf5, 0x99, 0xae, 0x14, 0xa1, 0x54,\n      0xed, 0x24, 0xb3, 0x6e, 0x25, 0x32, 0x4d, 0xb8,\n      0xc5, 0x66, 0x63, 0x2e, 0xf2, 0xbb, 0xb3, 0x4f,\n      0x83, 0x47, 0x28, 0x0f, 0xc4, 0x50, 0x70, 0x57,\n      0xfd, 0xdc, 0x29, 0xdf, 0x9a, 0x47, 0x1f, 0x75,\n      0xc6, 0x65, 0x41, 0xd4, 0xd4, 0xda, 0xd1, 0xc9,\n      0xe9, 0x3a, 0x19, 0xa5, 0x8e, 0x8b, 0x47, 0x3f,\n      0xa0, 0xf0, 0x62, 0xf7 },\n    { 0xd2, 0x7e, 0x88, 0x68, 0x1c, 0xe3, 0x24, 0x3c,\n      0x48, 0x30, 0x16, 0x5a, 0x8f, 0xdc, 0xf9, 0xff,\n      0x1d, 0xe9, 0xa1, 0xd8, 0xe6, 0xb4, 0x47, 0xef,\n      0x6e, 0xf7, 0xb7, 0x98, 0x28, 0x66, 0x6e, 0x45,\n      0x81, 0xe7, 0x90, 0x12, 0xaf, 0x34, 0xdd, 0xd9,\n      0xe2, 0xf0, 0x37, 0x58, 0x9b, 0x29, 0x2d, 0xb3,\n      0xe6, 0x7c, 0x03, 0x67, 0x45, 0xfa, 0x22, 0xe7,\n      0xe9, 0xb7, 0x37, 0x3b },\n    { 0x00 },\n    { 0xce, 0xa7, 0x40, 0x3d, 0x4d, 0x60, 0x6b, 0x6e,\n      0x07, 0x4e, 0xc5, 0xd3, 0xba, 0xf3, 0x9d, 0x18 },\n    { 0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07,\n      0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, 0x42, 0x7d,\n      0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9,\n      0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa,\n      0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d,\n      0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38,\n      0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a,\n      0xbc, 0xc9, 0xf6, 0x62, 0x89, 0x80, 0x15, 0xad },\n    { 0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07,\n      0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, 0x42, 0x7d,\n      0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9,\n      0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa,\n      0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d,\n      0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38,\n      0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a,\n      0xbc, 0xc9, 0xf6, 0x62 },\n    { 0xc3, 0x76, 0x2d, 0xf1, 0xca, 0x78, 0x7d, 0x32,\n      0xae, 0x47, 0xc1, 0x3b, 0xf1, 0x98, 0x44, 0xcb,\n      0xaf, 0x1a, 0xe1, 0x4d, 0x0b, 0x97, 0x6a, 0xfa,\n      0xc5, 0x2f, 0xf7, 0xd7, 0x9b, 0xba, 0x9d, 0xe0,\n      0xfe, 0xb5, 0x82, 0xd3, 0x39, 0x34, 0xa4, 0xf0,\n      0x95, 0x4c, 0xc2, 0x36, 0x3b, 0xc7, 0x3f, 0x78,\n      0x62, 0xac, 0x43, 0x0e, 0x64, 0xab, 0xe4, 0x99,\n      0xf4, 0x7c, 0x9b, 0x1f },\n    { 0x5a, 0x8d, 0xef, 0x2f, 0x0c, 0x9e, 0x53, 0xf1,\n      0xf7, 0x5d, 0x78, 0x53, 0x65, 0x9e, 0x2a, 0x20,\n      0xee, 0xb2, 0xb2, 0x2a, 0xaf, 0xde, 0x64, 0x19,\n      0xa0, 0x58, 0xab, 0x4f, 0x6f, 0x74, 0x6b, 0xf4,\n      0x0f, 0xc0, 0xc3, 0xb7, 0x80, 0xf2, 0x44, 0x45,\n      0x2d, 0xa3, 0xeb, 0xf1, 0xc5, 0xd8, 0x2c, 0xde,\n      0xa2, 0x41, 0x89, 0x97, 0x20, 0x0e, 0xf8, 0x2e,\n      0x44, 0xae, 0x7e, 0x3f },\n};\n\nstatic const unsigned char tag[MAX_TESTS * 3][16] =\n{\n    { 0x58, 0xe2, 0xfc, 0xce, 0xfa, 0x7e, 0x30, 0x61,\n      0x36, 0x7f, 0x1d, 0x57, 0xa4, 0xe7, 0x45, 0x5a },\n    { 0xab, 0x6e, 0x47, 0xd4, 0x2c, 0xec, 0x13, 0xbd,\n      0xf5, 0x3a, 0x67, 0xb2, 0x12, 0x57, 0xbd, 0xdf },\n    { 0x4d, 0x5c, 0x2a, 0xf3, 0x27, 0xcd, 0x64, 0xa6,\n      0x2c, 0xf3, 0x5a, 0xbd, 0x2b, 0xa6, 0xfa, 0xb4 },\n    { 0x5b, 0xc9, 0x4f, 0xbc, 0x32, 0x21, 0xa5, 0xdb,\n      0x94, 0xfa, 0xe9, 0x5a, 0xe7, 0x12, 0x1a, 0x47 },\n    { 0x36, 0x12, 0xd2, 0xe7, 0x9e, 0x3b, 0x07, 0x85,\n      0x56, 0x1b, 0xe1, 0x4a, 0xac, 0xa2, 0xfc, 0xcb },\n    { 0x61, 0x9c, 0xc5, 0xae, 0xff, 0xfe, 0x0b, 0xfa,\n      0x46, 0x2a, 0xf4, 0x3c, 0x16, 0x99, 0xd0, 0x50 },\n    { 0xcd, 0x33, 0xb2, 0x8a, 0xc7, 0x73, 0xf7, 0x4b,\n      0xa0, 0x0e, 0xd1, 0xf3, 0x12, 0x57, 0x24, 0x35 },\n    { 0x2f, 0xf5, 0x8d, 0x80, 0x03, 0x39, 0x27, 0xab,\n      0x8e, 0xf4, 0xd4, 0x58, 0x75, 0x14, 0xf0, 0xfb },\n    { 0x99, 0x24, 0xa7, 0xc8, 0x58, 0x73, 0x36, 0xbf,\n      0xb1, 0x18, 0x02, 0x4d, 0xb8, 0x67, 0x4a, 0x14 },\n    { 0x25, 0x19, 0x49, 0x8e, 0x80, 0xf1, 0x47, 0x8f,\n      0x37, 0xba, 0x55, 0xbd, 0x6d, 0x27, 0x61, 0x8c },\n    { 0x65, 0xdc, 0xc5, 0x7f, 0xcf, 0x62, 0x3a, 0x24,\n      0x09, 0x4f, 0xcc, 0xa4, 0x0d, 0x35, 0x33, 0xf8 },\n    { 0xdc, 0xf5, 0x66, 0xff, 0x29, 0x1c, 0x25, 0xbb,\n      0xb8, 0x56, 0x8f, 0xc3, 0xd3, 0x76, 0xa6, 0xd9 },\n    { 0x53, 0x0f, 0x8a, 0xfb, 0xc7, 0x45, 0x36, 0xb9,\n      0xa9, 0x63, 0xb4, 0xf1, 0xc4, 0xcb, 0x73, 0x8b },\n    { 0xd0, 0xd1, 0xc8, 0xa7, 0x99, 0x99, 0x6b, 0xf0,\n      0x26, 0x5b, 0x98, 0xb5, 0xd4, 0x8a, 0xb9, 0x19 },\n    { 0xb0, 0x94, 0xda, 0xc5, 0xd9, 0x34, 0x71, 0xbd,\n      0xec, 0x1a, 0x50, 0x22, 0x70, 0xe3, 0xcc, 0x6c },\n    { 0x76, 0xfc, 0x6e, 0xce, 0x0f, 0x4e, 0x17, 0x68,\n      0xcd, 0xdf, 0x88, 0x53, 0xbb, 0x2d, 0x55, 0x1b },\n    { 0x3a, 0x33, 0x7d, 0xbf, 0x46, 0xa7, 0x92, 0xc4,\n      0x5e, 0x45, 0x49, 0x13, 0xfe, 0x2e, 0xa8, 0xf2 },\n    { 0xa4, 0x4a, 0x82, 0x66, 0xee, 0x1c, 0x8e, 0xb0,\n      0xc8, 0xb5, 0xd4, 0xcf, 0x5a, 0xe9, 0xf1, 0x9a },\n};\n\nint mbedtls_gcm_self_test( int verbose )\n{\n    mbedtls_gcm_context ctx;\n    unsigned char buf[64];\n    unsigned char tag_buf[16];\n    int i, j, ret;\n    mbedtls_cipher_id_t cipher = MBEDTLS_CIPHER_ID_AES;\n\n    for( j = 0; j < 3; j++ )\n    {\n        int key_len = 128 + 64 * j;\n\n        for( i = 0; i < MAX_TESTS; i++ )\n        {\n            mbedtls_gcm_init( &ctx );\n\n            if( verbose != 0 )\n                mbedtls_printf( \"  AES-GCM-%3d #%d (%s): \",\n                                key_len, i, \"enc\" );\n\n            ret = mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]],\n                                      key_len );\n            /*\n             * AES-192 is an optional feature that may be unavailable when\n             * there is an alternative underlying implementation i.e. when\n             * MBEDTLS_AES_ALT is defined.\n             */\n            if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && key_len == 192 )\n            {\n                mbedtls_printf( \"skipped\\n\" );\n                break;\n            }\n            else if( ret != 0 )\n            {\n                goto exit;\n            }\n\n            ret = mbedtls_gcm_crypt_and_tag( &ctx, MBEDTLS_GCM_ENCRYPT,\n                                        pt_len[i],\n                                        iv[iv_index[i]], iv_len[i],\n                                        additional[add_index[i]], add_len[i],\n                                        pt[pt_index[i]], buf, 16, tag_buf );\n            if( ret != 0 )\n                goto exit;\n\n            if ( memcmp( buf, ct[j * 6 + i], pt_len[i] ) != 0 ||\n                 memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )\n            {\n                ret = 1;\n                goto exit;\n            }\n\n            mbedtls_gcm_free( &ctx );\n\n            if( verbose != 0 )\n                mbedtls_printf( \"passed\\n\" );\n\n            mbedtls_gcm_init( &ctx );\n\n            if( verbose != 0 )\n                mbedtls_printf( \"  AES-GCM-%3d #%d (%s): \",\n                                key_len, i, \"dec\" );\n\n            ret = mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]],\n                                      key_len );\n            if( ret != 0 )\n                goto exit;\n\n            ret = mbedtls_gcm_crypt_and_tag( &ctx, MBEDTLS_GCM_DECRYPT,\n                                        pt_len[i],\n                                        iv[iv_index[i]], iv_len[i],\n                                        additional[add_index[i]], add_len[i],\n                                        ct[j * 6 + i], buf, 16, tag_buf );\n\n            if( ret != 0 )\n                goto exit;\n\n            if( memcmp( buf, pt[pt_index[i]], pt_len[i] ) != 0 ||\n                memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )\n            {\n                ret = 1;\n                goto exit;\n            }\n\n            mbedtls_gcm_free( &ctx );\n\n            if( verbose != 0 )\n                mbedtls_printf( \"passed\\n\" );\n\n            mbedtls_gcm_init( &ctx );\n\n            if( verbose != 0 )\n                mbedtls_printf( \"  AES-GCM-%3d #%d split (%s): \",\n                                key_len, i, \"enc\" );\n\n            ret = mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]],\n                                      key_len );\n            if( ret != 0 )\n                goto exit;\n\n            ret = mbedtls_gcm_starts( &ctx, MBEDTLS_GCM_ENCRYPT,\n                                      iv[iv_index[i]], iv_len[i],\n                                      additional[add_index[i]], add_len[i] );\n            if( ret != 0 )\n                goto exit;\n\n            if( pt_len[i] > 32 )\n            {\n                size_t rest_len = pt_len[i] - 32;\n                ret = mbedtls_gcm_update( &ctx, 32, pt[pt_index[i]], buf );\n                if( ret != 0 )\n                    goto exit;\n\n                ret = mbedtls_gcm_update( &ctx, rest_len, pt[pt_index[i]] + 32,\n                                  buf + 32 );\n                if( ret != 0 )\n                    goto exit;\n            }\n            else\n            {\n                ret = mbedtls_gcm_update( &ctx, pt_len[i], pt[pt_index[i]], buf );\n                if( ret != 0 )\n                    goto exit;\n            }\n\n            ret = mbedtls_gcm_finish( &ctx, tag_buf, 16 );\n            if( ret != 0 )\n                goto exit;\n\n            if( memcmp( buf, ct[j * 6 + i], pt_len[i] ) != 0 ||\n                memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )\n            {\n                ret = 1;\n                goto exit;\n            }\n\n            mbedtls_gcm_free( &ctx );\n\n            if( verbose != 0 )\n                mbedtls_printf( \"passed\\n\" );\n\n            mbedtls_gcm_init( &ctx );\n\n            if( verbose != 0 )\n                mbedtls_printf( \"  AES-GCM-%3d #%d split (%s): \",\n                                key_len, i, \"dec\" );\n\n            ret = mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]],\n                                      key_len );\n            if( ret != 0 )\n                goto exit;\n\n            ret = mbedtls_gcm_starts( &ctx, MBEDTLS_GCM_DECRYPT,\n                              iv[iv_index[i]], iv_len[i],\n                              additional[add_index[i]], add_len[i] );\n            if( ret != 0 )\n                goto exit;\n\n            if( pt_len[i] > 32 )\n            {\n                size_t rest_len = pt_len[i] - 32;\n                ret = mbedtls_gcm_update( &ctx, 32, ct[j * 6 + i], buf );\n                if( ret != 0 )\n                    goto exit;\n\n                ret = mbedtls_gcm_update( &ctx, rest_len, ct[j * 6 + i] + 32,\n                                          buf + 32 );\n                if( ret != 0 )\n                    goto exit;\n            }\n            else\n            {\n                ret = mbedtls_gcm_update( &ctx, pt_len[i], ct[j * 6 + i],\n                                          buf );\n                if( ret != 0 )\n                    goto exit;\n            }\n\n            ret = mbedtls_gcm_finish( &ctx, tag_buf, 16 );\n            if( ret != 0 )\n                goto exit;\n\n            if( memcmp( buf, pt[pt_index[i]], pt_len[i] ) != 0 ||\n                memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )\n            {\n                ret = 1;\n                goto exit;\n            }\n\n            mbedtls_gcm_free( &ctx );\n\n            if( verbose != 0 )\n                mbedtls_printf( \"passed\\n\" );\n        }\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    ret = 0;\n\nexit:\n    if( ret != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n        mbedtls_gcm_free( &ctx );\n    }\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */\n\n#endif /* MBEDTLS_GCM_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/havege.c",
    "content": "/**\n *  \\brief HAVEGE: HArdware Volatile Entropy Gathering and Expansion\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The HAVEGE RNG was designed by Andre Seznec in 2002.\n *\n *  http://www.irisa.fr/caps/projects/hipsor/publi.php\n *\n *  Contact: seznec(at)irisa_dot_fr - orocheco(at)irisa_dot_fr\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_HAVEGE_C)\n\n#include \"mbedtls/havege.h\"\n#include \"mbedtls/timing.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n/* ------------------------------------------------------------------------\n * On average, one iteration accesses two 8-word blocks in the havege WALK\n * table, and generates 16 words in the RES array.\n *\n * The data read in the WALK table is updated and permuted after each use.\n * The result of the hardware clock counter read is used  for this update.\n *\n * 25 conditional tests are present.  The conditional tests are grouped in\n * two nested  groups of 12 conditional tests and 1 test that controls the\n * permutation; on average, there should be 6 tests executed and 3 of them\n * should be mispredicted.\n * ------------------------------------------------------------------------\n */\n\n#define SWAP(X,Y) { int *T = X; X = Y; Y = T; }\n\n#define TST1_ENTER if( PTEST & 1 ) { PTEST ^= 3; PTEST >>= 1;\n#define TST2_ENTER if( PTEST & 1 ) { PTEST ^= 3; PTEST >>= 1;\n\n#define TST1_LEAVE U1++; }\n#define TST2_LEAVE U2++; }\n\n#define ONE_ITERATION                                   \\\n                                                        \\\n    PTEST = PT1 >> 20;                                  \\\n                                                        \\\n    TST1_ENTER  TST1_ENTER  TST1_ENTER  TST1_ENTER      \\\n    TST1_ENTER  TST1_ENTER  TST1_ENTER  TST1_ENTER      \\\n    TST1_ENTER  TST1_ENTER  TST1_ENTER  TST1_ENTER      \\\n                                                        \\\n    TST1_LEAVE  TST1_LEAVE  TST1_LEAVE  TST1_LEAVE      \\\n    TST1_LEAVE  TST1_LEAVE  TST1_LEAVE  TST1_LEAVE      \\\n    TST1_LEAVE  TST1_LEAVE  TST1_LEAVE  TST1_LEAVE      \\\n                                                        \\\n    PTX = (PT1 >> 18) & 7;                              \\\n    PT1 &= 0x1FFF;                                      \\\n    PT2 &= 0x1FFF;                                      \\\n    CLK = (int) mbedtls_timing_hardclock();                            \\\n                                                        \\\n    i = 0;                                              \\\n    A = &WALK[PT1    ]; RES[i++] ^= *A;                 \\\n    B = &WALK[PT2    ]; RES[i++] ^= *B;                 \\\n    C = &WALK[PT1 ^ 1]; RES[i++] ^= *C;                 \\\n    D = &WALK[PT2 ^ 4]; RES[i++] ^= *D;                 \\\n                                                        \\\n    IN = (*A >> (1)) ^ (*A << (31)) ^ CLK;              \\\n    *A = (*B >> (2)) ^ (*B << (30)) ^ CLK;              \\\n    *B = IN ^ U1;                                       \\\n    *C = (*C >> (3)) ^ (*C << (29)) ^ CLK;              \\\n    *D = (*D >> (4)) ^ (*D << (28)) ^ CLK;              \\\n                                                        \\\n    A = &WALK[PT1 ^ 2]; RES[i++] ^= *A;                 \\\n    B = &WALK[PT2 ^ 2]; RES[i++] ^= *B;                 \\\n    C = &WALK[PT1 ^ 3]; RES[i++] ^= *C;                 \\\n    D = &WALK[PT2 ^ 6]; RES[i++] ^= *D;                 \\\n                                                        \\\n    if( PTEST & 1 ) SWAP( A, C );                       \\\n                                                        \\\n    IN = (*A >> (5)) ^ (*A << (27)) ^ CLK;              \\\n    *A = (*B >> (6)) ^ (*B << (26)) ^ CLK;              \\\n    *B = IN; CLK = (int) mbedtls_timing_hardclock();                   \\\n    *C = (*C >> (7)) ^ (*C << (25)) ^ CLK;              \\\n    *D = (*D >> (8)) ^ (*D << (24)) ^ CLK;              \\\n                                                        \\\n    A = &WALK[PT1 ^ 4];                                 \\\n    B = &WALK[PT2 ^ 1];                                 \\\n                                                        \\\n    PTEST = PT2 >> 1;                                   \\\n                                                        \\\n    PT2 = (RES[(i - 8) ^ PTY] ^ WALK[PT2 ^ PTY ^ 7]);   \\\n    PT2 = ((PT2 & 0x1FFF) & (~8)) ^ ((PT1 ^ 8) & 0x8);  \\\n    PTY = (PT2 >> 10) & 7;                              \\\n                                                        \\\n    TST2_ENTER  TST2_ENTER  TST2_ENTER  TST2_ENTER      \\\n    TST2_ENTER  TST2_ENTER  TST2_ENTER  TST2_ENTER      \\\n    TST2_ENTER  TST2_ENTER  TST2_ENTER  TST2_ENTER      \\\n                                                        \\\n    TST2_LEAVE  TST2_LEAVE  TST2_LEAVE  TST2_LEAVE      \\\n    TST2_LEAVE  TST2_LEAVE  TST2_LEAVE  TST2_LEAVE      \\\n    TST2_LEAVE  TST2_LEAVE  TST2_LEAVE  TST2_LEAVE      \\\n                                                        \\\n    C = &WALK[PT1 ^ 5];                                 \\\n    D = &WALK[PT2 ^ 5];                                 \\\n                                                        \\\n    RES[i++] ^= *A;                                     \\\n    RES[i++] ^= *B;                                     \\\n    RES[i++] ^= *C;                                     \\\n    RES[i++] ^= *D;                                     \\\n                                                        \\\n    IN = (*A >> ( 9)) ^ (*A << (23)) ^ CLK;             \\\n    *A = (*B >> (10)) ^ (*B << (22)) ^ CLK;             \\\n    *B = IN ^ U2;                                       \\\n    *C = (*C >> (11)) ^ (*C << (21)) ^ CLK;             \\\n    *D = (*D >> (12)) ^ (*D << (20)) ^ CLK;             \\\n                                                        \\\n    A = &WALK[PT1 ^ 6]; RES[i++] ^= *A;                 \\\n    B = &WALK[PT2 ^ 3]; RES[i++] ^= *B;                 \\\n    C = &WALK[PT1 ^ 7]; RES[i++] ^= *C;                 \\\n    D = &WALK[PT2 ^ 7]; RES[i++] ^= *D;                 \\\n                                                        \\\n    IN = (*A >> (13)) ^ (*A << (19)) ^ CLK;             \\\n    *A = (*B >> (14)) ^ (*B << (18)) ^ CLK;             \\\n    *B = IN;                                            \\\n    *C = (*C >> (15)) ^ (*C << (17)) ^ CLK;             \\\n    *D = (*D >> (16)) ^ (*D << (16)) ^ CLK;             \\\n                                                        \\\n    PT1 = ( RES[( i - 8 ) ^ PTX] ^                      \\\n            WALK[PT1 ^ PTX ^ 7] ) & (~1);               \\\n    PT1 ^= (PT2 ^ 0x10) & 0x10;                         \\\n                                                        \\\n    for( n++, i = 0; i < 16; i++ )                      \\\n        hs->pool[n % MBEDTLS_HAVEGE_COLLECT_SIZE] ^= RES[i];\n\n/*\n * Entropy gathering function\n */\nstatic void havege_fill( mbedtls_havege_state *hs )\n{\n    int i, n = 0;\n    int  U1,  U2, *A, *B, *C, *D;\n    int PT1, PT2, *WALK, RES[16];\n    int PTX, PTY, CLK, PTEST, IN;\n\n    WALK = hs->WALK;\n    PT1  = hs->PT1;\n    PT2  = hs->PT2;\n\n    PTX  = U1 = 0;\n    PTY  = U2 = 0;\n\n    (void)PTX;\n\n    memset( RES, 0, sizeof( RES ) );\n\n    while( n < MBEDTLS_HAVEGE_COLLECT_SIZE * 4 )\n    {\n        ONE_ITERATION\n        ONE_ITERATION\n        ONE_ITERATION\n        ONE_ITERATION\n    }\n\n    hs->PT1 = PT1;\n    hs->PT2 = PT2;\n\n    hs->offset[0] = 0;\n    hs->offset[1] = MBEDTLS_HAVEGE_COLLECT_SIZE / 2;\n}\n\n/*\n * HAVEGE initialization\n */\nvoid mbedtls_havege_init( mbedtls_havege_state *hs )\n{\n    memset( hs, 0, sizeof( mbedtls_havege_state ) );\n\n    havege_fill( hs );\n}\n\nvoid mbedtls_havege_free( mbedtls_havege_state *hs )\n{\n    if( hs == NULL )\n        return;\n\n    mbedtls_platform_zeroize( hs, sizeof( mbedtls_havege_state ) );\n}\n\n/*\n * HAVEGE rand function\n */\nint mbedtls_havege_random( void *p_rng, unsigned char *buf, size_t len )\n{\n    int val;\n    size_t use_len;\n    mbedtls_havege_state *hs = (mbedtls_havege_state *) p_rng;\n    unsigned char *p = buf;\n\n    while( len > 0 )\n    {\n        use_len = len;\n        if( use_len > sizeof(int) )\n            use_len = sizeof(int);\n\n        if( hs->offset[1] >= MBEDTLS_HAVEGE_COLLECT_SIZE )\n            havege_fill( hs );\n\n        val  = hs->pool[hs->offset[0]++];\n        val ^= hs->pool[hs->offset[1]++];\n\n        memcpy( p, &val, use_len );\n\n        len -= use_len;\n        p += use_len;\n    }\n\n    return( 0 );\n}\n\n#endif /* MBEDTLS_HAVEGE_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/hkdf.c",
    "content": "/*\n *  HKDF implementation -- RFC 5869\n *\n *  Copyright (C) 2016-2018, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_HKDF_C)\n\n#include <string.h>\n#include \"mbedtls/hkdf.h\"\n#include \"mbedtls/platform_util.h\"\n\nint mbedtls_hkdf( const mbedtls_md_info_t *md, const unsigned char *salt,\n                  size_t salt_len, const unsigned char *ikm, size_t ikm_len,\n                  const unsigned char *info, size_t info_len,\n                  unsigned char *okm, size_t okm_len )\n{\n    int ret;\n    unsigned char prk[MBEDTLS_MD_MAX_SIZE];\n\n    ret = mbedtls_hkdf_extract( md, salt, salt_len, ikm, ikm_len, prk );\n\n    if( ret == 0 )\n    {\n        ret = mbedtls_hkdf_expand( md, prk, mbedtls_md_get_size( md ),\n                                   info, info_len, okm, okm_len );\n    }\n\n    mbedtls_platform_zeroize( prk, sizeof( prk ) );\n\n    return( ret );\n}\n\nint mbedtls_hkdf_extract( const mbedtls_md_info_t *md,\n                          const unsigned char *salt, size_t salt_len,\n                          const unsigned char *ikm, size_t ikm_len,\n                          unsigned char *prk )\n{\n    unsigned char null_salt[MBEDTLS_MD_MAX_SIZE] = { '\\0' };\n\n    if( salt == NULL )\n    {\n        size_t hash_len;\n\n        if( salt_len != 0 )\n        {\n            return MBEDTLS_ERR_HKDF_BAD_INPUT_DATA;\n        }\n\n        hash_len = mbedtls_md_get_size( md );\n\n        if( hash_len == 0 )\n        {\n            return MBEDTLS_ERR_HKDF_BAD_INPUT_DATA;\n        }\n\n        salt = null_salt;\n        salt_len = hash_len;\n    }\n\n    return( mbedtls_md_hmac( md, salt, salt_len, ikm, ikm_len, prk ) );\n}\n\nint mbedtls_hkdf_expand( const mbedtls_md_info_t *md, const unsigned char *prk,\n                         size_t prk_len, const unsigned char *info,\n                         size_t info_len, unsigned char *okm, size_t okm_len )\n{\n    size_t hash_len;\n    size_t where = 0;\n    size_t n;\n    size_t t_len = 0;\n    size_t i;\n    int ret = 0;\n    mbedtls_md_context_t ctx;\n    unsigned char t[MBEDTLS_MD_MAX_SIZE];\n\n    if( okm == NULL )\n    {\n        return( MBEDTLS_ERR_HKDF_BAD_INPUT_DATA );\n    }\n\n    hash_len = mbedtls_md_get_size( md );\n\n    if( prk_len < hash_len || hash_len == 0 )\n    {\n        return( MBEDTLS_ERR_HKDF_BAD_INPUT_DATA );\n    }\n\n    if( info == NULL )\n    {\n        info = (const unsigned char *) \"\";\n        info_len = 0;\n    }\n\n    n = okm_len / hash_len;\n\n    if( (okm_len % hash_len) != 0 )\n    {\n        n++;\n    }\n\n    /*\n     * Per RFC 5869 Section 2.3, okm_len must not exceed\n     * 255 times the hash length\n     */\n    if( n > 255 )\n    {\n        return( MBEDTLS_ERR_HKDF_BAD_INPUT_DATA );\n    }\n\n    mbedtls_md_init( &ctx );\n\n    if( (ret = mbedtls_md_setup( &ctx, md, 1) ) != 0 )\n    {\n        goto exit;\n    }\n\n    /*\n     * Compute T = T(1) | T(2) | T(3) | ... | T(N)\n     * Where T(N) is defined in RFC 5869 Section 2.3\n     */\n    for( i = 1; i <= n; i++ )\n    {\n        size_t num_to_copy;\n        unsigned char c = i & 0xff;\n\n        ret = mbedtls_md_hmac_starts( &ctx, prk, prk_len );\n        if( ret != 0 )\n        {\n            goto exit;\n        }\n\n        ret = mbedtls_md_hmac_update( &ctx, t, t_len );\n        if( ret != 0 )\n        {\n            goto exit;\n        }\n\n        ret = mbedtls_md_hmac_update( &ctx, info, info_len );\n        if( ret != 0 )\n        {\n            goto exit;\n        }\n\n        /* The constant concatenated to the end of each T(n) is a single octet.\n         * */\n        ret = mbedtls_md_hmac_update( &ctx, &c, 1 );\n        if( ret != 0 )\n        {\n            goto exit;\n        }\n\n        ret = mbedtls_md_hmac_finish( &ctx, t );\n        if( ret != 0 )\n        {\n            goto exit;\n        }\n\n        num_to_copy = i != n ? hash_len : okm_len - where;\n        memcpy( okm + where, t, num_to_copy );\n        where += hash_len;\n        t_len = hash_len;\n    }\n\nexit:\n    mbedtls_md_free( &ctx );\n    mbedtls_platform_zeroize( t, sizeof( t ) );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_HKDF_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/hmac_drbg.c",
    "content": "/*\n *  HMAC_DRBG implementation (NIST SP 800-90)\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n/*\n *  The NIST SP 800-90A DRBGs are described in the following publication.\n *  http://csrc.nist.gov/publications/nistpubs/800-90A/SP800-90A.pdf\n *  References below are based on rev. 1 (January 2012).\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_HMAC_DRBG_C)\n\n#include \"mbedtls/hmac_drbg.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_FS_IO)\n#include <stdio.h>\n#endif\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_SELF_TEST */\n#endif /* MBEDTLS_PLATFORM_C */\n\n/*\n * HMAC_DRBG context initialization\n */\nvoid mbedtls_hmac_drbg_init( mbedtls_hmac_drbg_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_hmac_drbg_context ) );\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_mutex_init( &ctx->mutex );\n#endif\n}\n\n/*\n * HMAC_DRBG update, using optional additional data (10.1.2.2)\n */\nvoid mbedtls_hmac_drbg_update( mbedtls_hmac_drbg_context *ctx,\n                       const unsigned char *additional, size_t add_len )\n{\n    size_t md_len = mbedtls_md_get_size( ctx->md_ctx.md_info );\n    unsigned char rounds = ( additional != NULL && add_len != 0 ) ? 2 : 1;\n    unsigned char sep[1];\n    unsigned char K[MBEDTLS_MD_MAX_SIZE];\n\n    for( sep[0] = 0; sep[0] < rounds; sep[0]++ )\n    {\n        /* Step 1 or 4 */\n        mbedtls_md_hmac_reset( &ctx->md_ctx );\n        mbedtls_md_hmac_update( &ctx->md_ctx, ctx->V, md_len );\n        mbedtls_md_hmac_update( &ctx->md_ctx, sep, 1 );\n        if( rounds == 2 )\n            mbedtls_md_hmac_update( &ctx->md_ctx, additional, add_len );\n        mbedtls_md_hmac_finish( &ctx->md_ctx, K );\n\n        /* Step 2 or 5 */\n        mbedtls_md_hmac_starts( &ctx->md_ctx, K, md_len );\n        mbedtls_md_hmac_update( &ctx->md_ctx, ctx->V, md_len );\n        mbedtls_md_hmac_finish( &ctx->md_ctx, ctx->V );\n    }\n}\n\n/*\n * Simplified HMAC_DRBG initialisation (for use with deterministic ECDSA)\n */\nint mbedtls_hmac_drbg_seed_buf( mbedtls_hmac_drbg_context *ctx,\n                        const mbedtls_md_info_t * md_info,\n                        const unsigned char *data, size_t data_len )\n{\n    int ret;\n\n    if( ( ret = mbedtls_md_setup( &ctx->md_ctx, md_info, 1 ) ) != 0 )\n        return( ret );\n\n    /*\n     * Set initial working state.\n     * Use the V memory location, which is currently all 0, to initialize the\n     * MD context with an all-zero key. Then set V to its initial value.\n     */\n    mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, mbedtls_md_get_size( md_info ) );\n    memset( ctx->V, 0x01, mbedtls_md_get_size( md_info ) );\n\n    mbedtls_hmac_drbg_update( ctx, data, data_len );\n\n    return( 0 );\n}\n\n/*\n * HMAC_DRBG reseeding: 10.1.2.4 (arabic) + 9.2 (Roman)\n */\nint mbedtls_hmac_drbg_reseed( mbedtls_hmac_drbg_context *ctx,\n                      const unsigned char *additional, size_t len )\n{\n    unsigned char seed[MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT];\n    size_t seedlen;\n\n    /* III. Check input length */\n    if( len > MBEDTLS_HMAC_DRBG_MAX_INPUT ||\n        ctx->entropy_len + len > MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT )\n    {\n        return( MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG );\n    }\n\n    memset( seed, 0, MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT );\n\n    /* IV. Gather entropy_len bytes of entropy for the seed */\n    if( ctx->f_entropy( ctx->p_entropy, seed, ctx->entropy_len ) != 0 )\n        return( MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED );\n\n    seedlen = ctx->entropy_len;\n\n    /* 1. Concatenate entropy and additional data if any */\n    if( additional != NULL && len != 0 )\n    {\n        memcpy( seed + seedlen, additional, len );\n        seedlen += len;\n    }\n\n    /* 2. Update state */\n    mbedtls_hmac_drbg_update( ctx, seed, seedlen );\n\n    /* 3. Reset reseed_counter */\n    ctx->reseed_counter = 1;\n\n    /* 4. Done */\n    return( 0 );\n}\n\n/*\n * HMAC_DRBG initialisation (10.1.2.3 + 9.1)\n */\nint mbedtls_hmac_drbg_seed( mbedtls_hmac_drbg_context *ctx,\n                    const mbedtls_md_info_t * md_info,\n                    int (*f_entropy)(void *, unsigned char *, size_t),\n                    void *p_entropy,\n                    const unsigned char *custom,\n                    size_t len )\n{\n    int ret;\n    size_t entropy_len, md_size;\n\n    if( ( ret = mbedtls_md_setup( &ctx->md_ctx, md_info, 1 ) ) != 0 )\n        return( ret );\n\n    md_size = mbedtls_md_get_size( md_info );\n\n    /*\n     * Set initial working state.\n     * Use the V memory location, which is currently all 0, to initialize the\n     * MD context with an all-zero key. Then set V to its initial value.\n     */\n    mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, md_size );\n    memset( ctx->V, 0x01, md_size );\n\n    ctx->f_entropy = f_entropy;\n    ctx->p_entropy = p_entropy;\n\n    ctx->reseed_interval = MBEDTLS_HMAC_DRBG_RESEED_INTERVAL;\n\n    /*\n     * See SP800-57 5.6.1 (p. 65-66) for the security strength provided by\n     * each hash function, then according to SP800-90A rev1 10.1 table 2,\n     * min_entropy_len (in bits) is security_strength.\n     *\n     * (This also matches the sizes used in the NIST test vectors.)\n     */\n    entropy_len = md_size <= 20 ? 16 : /* 160-bits hash -> 128 bits */\n                  md_size <= 28 ? 24 : /* 224-bits hash -> 192 bits */\n                                  32;  /* better (256+) -> 256 bits */\n\n    /*\n     * For initialisation, use more entropy to emulate a nonce\n     * (Again, matches test vectors.)\n     */\n    ctx->entropy_len = entropy_len * 3 / 2;\n\n    if( ( ret = mbedtls_hmac_drbg_reseed( ctx, custom, len ) ) != 0 )\n        return( ret );\n\n    ctx->entropy_len = entropy_len;\n\n    return( 0 );\n}\n\n/*\n * Set prediction resistance\n */\nvoid mbedtls_hmac_drbg_set_prediction_resistance( mbedtls_hmac_drbg_context *ctx,\n                                          int resistance )\n{\n    ctx->prediction_resistance = resistance;\n}\n\n/*\n * Set entropy length grabbed for reseeds\n */\nvoid mbedtls_hmac_drbg_set_entropy_len( mbedtls_hmac_drbg_context *ctx, size_t len )\n{\n    ctx->entropy_len = len;\n}\n\n/*\n * Set reseed interval\n */\nvoid mbedtls_hmac_drbg_set_reseed_interval( mbedtls_hmac_drbg_context *ctx, int interval )\n{\n    ctx->reseed_interval = interval;\n}\n\n/*\n * HMAC_DRBG random function with optional additional data:\n * 10.1.2.5 (arabic) + 9.3 (Roman)\n */\nint mbedtls_hmac_drbg_random_with_add( void *p_rng,\n                               unsigned char *output, size_t out_len,\n                               const unsigned char *additional, size_t add_len )\n{\n    int ret;\n    mbedtls_hmac_drbg_context *ctx = (mbedtls_hmac_drbg_context *) p_rng;\n    size_t md_len = mbedtls_md_get_size( ctx->md_ctx.md_info );\n    size_t left = out_len;\n    unsigned char *out = output;\n\n    /* II. Check request length */\n    if( out_len > MBEDTLS_HMAC_DRBG_MAX_REQUEST )\n        return( MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG );\n\n    /* III. Check input length */\n    if( add_len > MBEDTLS_HMAC_DRBG_MAX_INPUT )\n        return( MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG );\n\n    /* 1. (aka VII and IX) Check reseed counter and PR */\n    if( ctx->f_entropy != NULL && /* For no-reseeding instances */\n        ( ctx->prediction_resistance == MBEDTLS_HMAC_DRBG_PR_ON ||\n          ctx->reseed_counter > ctx->reseed_interval ) )\n    {\n        if( ( ret = mbedtls_hmac_drbg_reseed( ctx, additional, add_len ) ) != 0 )\n            return( ret );\n\n        add_len = 0; /* VII.4 */\n    }\n\n    /* 2. Use additional data if any */\n    if( additional != NULL && add_len != 0 )\n        mbedtls_hmac_drbg_update( ctx, additional, add_len );\n\n    /* 3, 4, 5. Generate bytes */\n    while( left != 0 )\n    {\n        size_t use_len = left > md_len ? md_len : left;\n\n        mbedtls_md_hmac_reset( &ctx->md_ctx );\n        mbedtls_md_hmac_update( &ctx->md_ctx, ctx->V, md_len );\n        mbedtls_md_hmac_finish( &ctx->md_ctx, ctx->V );\n\n        memcpy( out, ctx->V, use_len );\n        out += use_len;\n        left -= use_len;\n    }\n\n    /* 6. Update */\n    mbedtls_hmac_drbg_update( ctx, additional, add_len );\n\n    /* 7. Update reseed counter */\n    ctx->reseed_counter++;\n\n    /* 8. Done */\n    return( 0 );\n}\n\n/*\n * HMAC_DRBG random function\n */\nint mbedtls_hmac_drbg_random( void *p_rng, unsigned char *output, size_t out_len )\n{\n    int ret;\n    mbedtls_hmac_drbg_context *ctx = (mbedtls_hmac_drbg_context *) p_rng;\n\n#if defined(MBEDTLS_THREADING_C)\n    if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )\n        return( ret );\n#endif\n\n    ret = mbedtls_hmac_drbg_random_with_add( ctx, output, out_len, NULL, 0 );\n\n#if defined(MBEDTLS_THREADING_C)\n    if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )\n        return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );\n#endif\n\n    return( ret );\n}\n\n/*\n * Free an HMAC_DRBG context\n */\nvoid mbedtls_hmac_drbg_free( mbedtls_hmac_drbg_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_mutex_free( &ctx->mutex );\n#endif\n    mbedtls_md_free( &ctx->md_ctx );\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_hmac_drbg_context ) );\n}\n\n#if defined(MBEDTLS_FS_IO)\nint mbedtls_hmac_drbg_write_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path )\n{\n    int ret;\n    FILE *f;\n    unsigned char buf[ MBEDTLS_HMAC_DRBG_MAX_INPUT ];\n\n    if( ( f = fopen( path, \"wb\" ) ) == NULL )\n        return( MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR );\n\n    if( ( ret = mbedtls_hmac_drbg_random( ctx, buf, sizeof( buf ) ) ) != 0 )\n        goto exit;\n\n    if( fwrite( buf, 1, sizeof( buf ), f ) != sizeof( buf ) )\n    {\n        ret = MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR;\n        goto exit;\n    }\n\n    ret = 0;\n\nexit:\n    fclose( f );\n    mbedtls_platform_zeroize( buf, sizeof( buf ) );\n\n    return( ret );\n}\n\nint mbedtls_hmac_drbg_update_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path )\n{\n    int ret = 0;\n    FILE *f;\n    size_t n;\n    unsigned char buf[ MBEDTLS_HMAC_DRBG_MAX_INPUT ];\n\n    if( ( f = fopen( path, \"rb\" ) ) == NULL )\n        return( MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR );\n\n    fseek( f, 0, SEEK_END );\n    n = (size_t) ftell( f );\n    fseek( f, 0, SEEK_SET );\n\n    if( n > MBEDTLS_HMAC_DRBG_MAX_INPUT )\n    {\n        fclose( f );\n        return( MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG );\n    }\n\n    if( fread( buf, 1, n, f ) != n )\n        ret = MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR;\n    else\n        mbedtls_hmac_drbg_update( ctx, buf, n );\n\n    fclose( f );\n\n    mbedtls_platform_zeroize( buf, sizeof( buf ) );\n\n    if( ret != 0 )\n        return( ret );\n\n    return( mbedtls_hmac_drbg_write_seed_file( ctx, path ) );\n}\n#endif /* MBEDTLS_FS_IO */\n\n\n#if defined(MBEDTLS_SELF_TEST)\n\n#if !defined(MBEDTLS_SHA1_C)\n/* Dummy checkup routine */\nint mbedtls_hmac_drbg_self_test( int verbose )\n{\n    (void) verbose;\n    return( 0 );\n}\n#else\n\n#define OUTPUT_LEN  80\n\n/* From a NIST PR=true test vector */\nstatic const unsigned char entropy_pr[] = {\n    0xa0, 0xc9, 0xab, 0x58, 0xf1, 0xe2, 0xe5, 0xa4, 0xde, 0x3e, 0xbd, 0x4f,\n    0xf7, 0x3e, 0x9c, 0x5b, 0x64, 0xef, 0xd8, 0xca, 0x02, 0x8c, 0xf8, 0x11,\n    0x48, 0xa5, 0x84, 0xfe, 0x69, 0xab, 0x5a, 0xee, 0x42, 0xaa, 0x4d, 0x42,\n    0x17, 0x60, 0x99, 0xd4, 0x5e, 0x13, 0x97, 0xdc, 0x40, 0x4d, 0x86, 0xa3,\n    0x7b, 0xf5, 0x59, 0x54, 0x75, 0x69, 0x51, 0xe4 };\nstatic const unsigned char result_pr[OUTPUT_LEN] = {\n    0x9a, 0x00, 0xa2, 0xd0, 0x0e, 0xd5, 0x9b, 0xfe, 0x31, 0xec, 0xb1, 0x39,\n    0x9b, 0x60, 0x81, 0x48, 0xd1, 0x96, 0x9d, 0x25, 0x0d, 0x3c, 0x1e, 0x94,\n    0x10, 0x10, 0x98, 0x12, 0x93, 0x25, 0xca, 0xb8, 0xfc, 0xcc, 0x2d, 0x54,\n    0x73, 0x19, 0x70, 0xc0, 0x10, 0x7a, 0xa4, 0x89, 0x25, 0x19, 0x95, 0x5e,\n    0x4b, 0xc6, 0x00, 0x1d, 0x7f, 0x4e, 0x6a, 0x2b, 0xf8, 0xa3, 0x01, 0xab,\n    0x46, 0x05, 0x5c, 0x09, 0xa6, 0x71, 0x88, 0xf1, 0xa7, 0x40, 0xee, 0xf3,\n    0xe1, 0x5c, 0x02, 0x9b, 0x44, 0xaf, 0x03, 0x44 };\n\n/* From a NIST PR=false test vector */\nstatic const unsigned char entropy_nopr[] = {\n    0x79, 0x34, 0x9b, 0xbf, 0x7c, 0xdd, 0xa5, 0x79, 0x95, 0x57, 0x86, 0x66,\n    0x21, 0xc9, 0x13, 0x83, 0x11, 0x46, 0x73, 0x3a, 0xbf, 0x8c, 0x35, 0xc8,\n    0xc7, 0x21, 0x5b, 0x5b, 0x96, 0xc4, 0x8e, 0x9b, 0x33, 0x8c, 0x74, 0xe3,\n    0xe9, 0x9d, 0xfe, 0xdf };\nstatic const unsigned char result_nopr[OUTPUT_LEN] = {\n    0xc6, 0xa1, 0x6a, 0xb8, 0xd4, 0x20, 0x70, 0x6f, 0x0f, 0x34, 0xab, 0x7f,\n    0xec, 0x5a, 0xdc, 0xa9, 0xd8, 0xca, 0x3a, 0x13, 0x3e, 0x15, 0x9c, 0xa6,\n    0xac, 0x43, 0xc6, 0xf8, 0xa2, 0xbe, 0x22, 0x83, 0x4a, 0x4c, 0x0a, 0x0a,\n    0xff, 0xb1, 0x0d, 0x71, 0x94, 0xf1, 0xc1, 0xa5, 0xcf, 0x73, 0x22, 0xec,\n    0x1a, 0xe0, 0x96, 0x4e, 0xd4, 0xbf, 0x12, 0x27, 0x46, 0xe0, 0x87, 0xfd,\n    0xb5, 0xb3, 0xe9, 0x1b, 0x34, 0x93, 0xd5, 0xbb, 0x98, 0xfa, 0xed, 0x49,\n    0xe8, 0x5f, 0x13, 0x0f, 0xc8, 0xa4, 0x59, 0xb7 };\n\n/* \"Entropy\" from buffer */\nstatic size_t test_offset;\nstatic int hmac_drbg_self_test_entropy( void *data,\n                                        unsigned char *buf, size_t len )\n{\n    const unsigned char *p = data;\n    memcpy( buf, p + test_offset, len );\n    test_offset += len;\n    return( 0 );\n}\n\n#define CHK( c )    if( (c) != 0 )                          \\\n                    {                                       \\\n                        if( verbose != 0 )                  \\\n                            mbedtls_printf( \"failed\\n\" );  \\\n                        return( 1 );                        \\\n                    }\n\n/*\n * Checkup routine for HMAC_DRBG with SHA-1\n */\nint mbedtls_hmac_drbg_self_test( int verbose )\n{\n    mbedtls_hmac_drbg_context ctx;\n    unsigned char buf[OUTPUT_LEN];\n    const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 );\n\n    mbedtls_hmac_drbg_init( &ctx );\n\n    /*\n     * PR = True\n     */\n    if( verbose != 0 )\n        mbedtls_printf( \"  HMAC_DRBG (PR = True) : \" );\n\n    test_offset = 0;\n    CHK( mbedtls_hmac_drbg_seed( &ctx, md_info,\n                         hmac_drbg_self_test_entropy, (void *) entropy_pr,\n                         NULL, 0 ) );\n    mbedtls_hmac_drbg_set_prediction_resistance( &ctx, MBEDTLS_HMAC_DRBG_PR_ON );\n    CHK( mbedtls_hmac_drbg_random( &ctx, buf, OUTPUT_LEN ) );\n    CHK( mbedtls_hmac_drbg_random( &ctx, buf, OUTPUT_LEN ) );\n    CHK( memcmp( buf, result_pr, OUTPUT_LEN ) );\n    mbedtls_hmac_drbg_free( &ctx );\n\n    mbedtls_hmac_drbg_free( &ctx );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\n    /*\n     * PR = False\n     */\n    if( verbose != 0 )\n        mbedtls_printf( \"  HMAC_DRBG (PR = False) : \" );\n\n    mbedtls_hmac_drbg_init( &ctx );\n\n    test_offset = 0;\n    CHK( mbedtls_hmac_drbg_seed( &ctx, md_info,\n                         hmac_drbg_self_test_entropy, (void *) entropy_nopr,\n                         NULL, 0 ) );\n    CHK( mbedtls_hmac_drbg_reseed( &ctx, NULL, 0 ) );\n    CHK( mbedtls_hmac_drbg_random( &ctx, buf, OUTPUT_LEN ) );\n    CHK( mbedtls_hmac_drbg_random( &ctx, buf, OUTPUT_LEN ) );\n    CHK( memcmp( buf, result_nopr, OUTPUT_LEN ) );\n    mbedtls_hmac_drbg_free( &ctx );\n\n    mbedtls_hmac_drbg_free( &ctx );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_HMAC_DRBG_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/md.c",
    "content": "/**\n * \\file mbedtls_md.c\n *\n * \\brief Generic message digest wrapper for mbed TLS\n *\n * \\author Adriaan de Jong <dejong@fox-it.com>\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_MD_C)\n\n#include \"mbedtls/md.h\"\n#include \"mbedtls/md_internal.h\"\n#include \"mbedtls/platform_util.h\"\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc    calloc\n#define mbedtls_free       free\n#endif\n\n#include <string.h>\n\n#if defined(MBEDTLS_FS_IO)\n#include <stdio.h>\n#endif\n\n/*\n * Reminder: update profiles in x509_crt.c when adding a new hash!\n */\nstatic const int supported_digests[] = {\n\n#if defined(MBEDTLS_SHA512_C)\n        MBEDTLS_MD_SHA512,\n        MBEDTLS_MD_SHA384,\n#endif\n\n#if defined(MBEDTLS_SHA256_C)\n        MBEDTLS_MD_SHA256,\n        MBEDTLS_MD_SHA224,\n#endif\n\n#if defined(MBEDTLS_SHA1_C)\n        MBEDTLS_MD_SHA1,\n#endif\n\n#if defined(MBEDTLS_RIPEMD160_C)\n        MBEDTLS_MD_RIPEMD160,\n#endif\n\n#if defined(MBEDTLS_MD5_C)\n        MBEDTLS_MD_MD5,\n#endif\n\n#if defined(MBEDTLS_MD4_C)\n        MBEDTLS_MD_MD4,\n#endif\n\n#if defined(MBEDTLS_MD2_C)\n        MBEDTLS_MD_MD2,\n#endif\n\n        MBEDTLS_MD_NONE\n};\n\nconst int *mbedtls_md_list( void )\n{\n    return( supported_digests );\n}\n\nconst mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name )\n{\n    if( NULL == md_name )\n        return( NULL );\n\n    /* Get the appropriate digest information */\n#if defined(MBEDTLS_MD2_C)\n    if( !strcmp( \"MD2\", md_name ) )\n        return mbedtls_md_info_from_type( MBEDTLS_MD_MD2 );\n#endif\n#if defined(MBEDTLS_MD4_C)\n    if( !strcmp( \"MD4\", md_name ) )\n        return mbedtls_md_info_from_type( MBEDTLS_MD_MD4 );\n#endif\n#if defined(MBEDTLS_MD5_C)\n    if( !strcmp( \"MD5\", md_name ) )\n        return mbedtls_md_info_from_type( MBEDTLS_MD_MD5 );\n#endif\n#if defined(MBEDTLS_RIPEMD160_C)\n    if( !strcmp( \"RIPEMD160\", md_name ) )\n        return mbedtls_md_info_from_type( MBEDTLS_MD_RIPEMD160 );\n#endif\n#if defined(MBEDTLS_SHA1_C)\n    if( !strcmp( \"SHA1\", md_name ) || !strcmp( \"SHA\", md_name ) )\n        return mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 );\n#endif\n#if defined(MBEDTLS_SHA256_C)\n    if( !strcmp( \"SHA224\", md_name ) )\n        return mbedtls_md_info_from_type( MBEDTLS_MD_SHA224 );\n    if( !strcmp( \"SHA256\", md_name ) )\n        return mbedtls_md_info_from_type( MBEDTLS_MD_SHA256 );\n#endif\n#if defined(MBEDTLS_SHA512_C)\n    if( !strcmp( \"SHA384\", md_name ) )\n        return mbedtls_md_info_from_type( MBEDTLS_MD_SHA384 );\n    if( !strcmp( \"SHA512\", md_name ) )\n        return mbedtls_md_info_from_type( MBEDTLS_MD_SHA512 );\n#endif\n    return( NULL );\n}\n\nconst mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type )\n{\n    switch( md_type )\n    {\n#if defined(MBEDTLS_MD2_C)\n        case MBEDTLS_MD_MD2:\n            return( &mbedtls_md2_info );\n#endif\n#if defined(MBEDTLS_MD4_C)\n        case MBEDTLS_MD_MD4:\n            return( &mbedtls_md4_info );\n#endif\n#if defined(MBEDTLS_MD5_C)\n        case MBEDTLS_MD_MD5:\n            return( &mbedtls_md5_info );\n#endif\n#if defined(MBEDTLS_RIPEMD160_C)\n        case MBEDTLS_MD_RIPEMD160:\n            return( &mbedtls_ripemd160_info );\n#endif\n#if defined(MBEDTLS_SHA1_C)\n        case MBEDTLS_MD_SHA1:\n            return( &mbedtls_sha1_info );\n#endif\n#if defined(MBEDTLS_SHA256_C)\n        case MBEDTLS_MD_SHA224:\n            return( &mbedtls_sha224_info );\n        case MBEDTLS_MD_SHA256:\n            return( &mbedtls_sha256_info );\n#endif\n#if defined(MBEDTLS_SHA512_C)\n        case MBEDTLS_MD_SHA384:\n            return( &mbedtls_sha384_info );\n        case MBEDTLS_MD_SHA512:\n            return( &mbedtls_sha512_info );\n#endif\n        default:\n            return( NULL );\n    }\n}\n\nvoid mbedtls_md_init( mbedtls_md_context_t *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_md_context_t ) );\n}\n\nvoid mbedtls_md_free( mbedtls_md_context_t *ctx )\n{\n    if( ctx == NULL || ctx->md_info == NULL )\n        return;\n\n    if( ctx->md_ctx != NULL )\n        ctx->md_info->ctx_free_func( ctx->md_ctx );\n\n    if( ctx->hmac_ctx != NULL )\n    {\n        mbedtls_platform_zeroize( ctx->hmac_ctx,\n                                  2 * ctx->md_info->block_size );\n        mbedtls_free( ctx->hmac_ctx );\n    }\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md_context_t ) );\n}\n\nint mbedtls_md_clone( mbedtls_md_context_t *dst,\n                      const mbedtls_md_context_t *src )\n{\n    if( dst == NULL || dst->md_info == NULL ||\n        src == NULL || src->md_info == NULL ||\n        dst->md_info != src->md_info )\n    {\n        return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );\n    }\n\n    dst->md_info->clone_func( dst->md_ctx, src->md_ctx );\n\n    return( 0 );\n}\n\n#if ! defined(MBEDTLS_DEPRECATED_REMOVED)\nint mbedtls_md_init_ctx( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info )\n{\n    return mbedtls_md_setup( ctx, md_info, 1 );\n}\n#endif\n\nint mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info, int hmac )\n{\n    if( md_info == NULL || ctx == NULL )\n        return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );\n\n    if( ( ctx->md_ctx = md_info->ctx_alloc_func() ) == NULL )\n        return( MBEDTLS_ERR_MD_ALLOC_FAILED );\n\n    if( hmac != 0 )\n    {\n        ctx->hmac_ctx = mbedtls_calloc( 2, md_info->block_size );\n        if( ctx->hmac_ctx == NULL )\n        {\n            md_info->ctx_free_func( ctx->md_ctx );\n            return( MBEDTLS_ERR_MD_ALLOC_FAILED );\n        }\n    }\n\n    ctx->md_info = md_info;\n\n    return( 0 );\n}\n\nint mbedtls_md_starts( mbedtls_md_context_t *ctx )\n{\n    if( ctx == NULL || ctx->md_info == NULL )\n        return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );\n\n    return( ctx->md_info->starts_func( ctx->md_ctx ) );\n}\n\nint mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen )\n{\n    if( ctx == NULL || ctx->md_info == NULL )\n        return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );\n\n    return( ctx->md_info->update_func( ctx->md_ctx, input, ilen ) );\n}\n\nint mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output )\n{\n    if( ctx == NULL || ctx->md_info == NULL )\n        return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );\n\n    return( ctx->md_info->finish_func( ctx->md_ctx, output ) );\n}\n\nint mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen,\n            unsigned char *output )\n{\n    if( md_info == NULL )\n        return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );\n\n    return( md_info->digest_func( input, ilen, output ) );\n}\n\n#if defined(MBEDTLS_FS_IO)\nint mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path, unsigned char *output )\n{\n    int ret;\n    FILE *f;\n    size_t n;\n    mbedtls_md_context_t ctx;\n    unsigned char buf[1024];\n\n    if( md_info == NULL )\n        return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );\n\n    if( ( f = fopen( path, \"rb\" ) ) == NULL )\n        return( MBEDTLS_ERR_MD_FILE_IO_ERROR );\n\n    mbedtls_md_init( &ctx );\n\n    if( ( ret = mbedtls_md_setup( &ctx, md_info, 0 ) ) != 0 )\n        goto cleanup;\n\n    if( ( ret = md_info->starts_func( ctx.md_ctx ) ) != 0 )\n        goto cleanup;\n\n    while( ( n = fread( buf, 1, sizeof( buf ), f ) ) > 0 )\n        if( ( ret = md_info->update_func( ctx.md_ctx, buf, n ) ) != 0 )\n            goto cleanup;\n\n    if( ferror( f ) != 0 )\n        ret = MBEDTLS_ERR_MD_FILE_IO_ERROR;\n    else\n        ret = md_info->finish_func( ctx.md_ctx, output );\n\ncleanup:\n    mbedtls_platform_zeroize( buf, sizeof( buf ) );\n    fclose( f );\n    mbedtls_md_free( &ctx );\n\n    return( ret );\n}\n#endif /* MBEDTLS_FS_IO */\n\nint mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key, size_t keylen )\n{\n    int ret;\n    unsigned char sum[MBEDTLS_MD_MAX_SIZE];\n    unsigned char *ipad, *opad;\n    size_t i;\n\n    if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )\n        return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );\n\n    if( keylen > (size_t) ctx->md_info->block_size )\n    {\n        if( ( ret = ctx->md_info->starts_func( ctx->md_ctx ) ) != 0 )\n            goto cleanup;\n        if( ( ret = ctx->md_info->update_func( ctx->md_ctx, key, keylen ) ) != 0 )\n            goto cleanup;\n        if( ( ret = ctx->md_info->finish_func( ctx->md_ctx, sum ) ) != 0 )\n            goto cleanup;\n\n        keylen = ctx->md_info->size;\n        key = sum;\n    }\n\n    ipad = (unsigned char *) ctx->hmac_ctx;\n    opad = (unsigned char *) ctx->hmac_ctx + ctx->md_info->block_size;\n\n    memset( ipad, 0x36, ctx->md_info->block_size );\n    memset( opad, 0x5C, ctx->md_info->block_size );\n\n    for( i = 0; i < keylen; i++ )\n    {\n        ipad[i] = (unsigned char)( ipad[i] ^ key[i] );\n        opad[i] = (unsigned char)( opad[i] ^ key[i] );\n    }\n\n    if( ( ret = ctx->md_info->starts_func( ctx->md_ctx ) ) != 0 )\n        goto cleanup;\n    if( ( ret = ctx->md_info->update_func( ctx->md_ctx, ipad,\n                                           ctx->md_info->block_size ) ) != 0 )\n        goto cleanup;\n\ncleanup:\n    mbedtls_platform_zeroize( sum, sizeof( sum ) );\n\n    return( ret );\n}\n\nint mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen )\n{\n    if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )\n        return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );\n\n    return( ctx->md_info->update_func( ctx->md_ctx, input, ilen ) );\n}\n\nint mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output )\n{\n    int ret;\n    unsigned char tmp[MBEDTLS_MD_MAX_SIZE];\n    unsigned char *opad;\n\n    if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )\n        return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );\n\n    opad = (unsigned char *) ctx->hmac_ctx + ctx->md_info->block_size;\n\n    if( ( ret = ctx->md_info->finish_func( ctx->md_ctx, tmp ) ) != 0 )\n        return( ret );\n    if( ( ret = ctx->md_info->starts_func( ctx->md_ctx ) ) != 0 )\n        return( ret );\n    if( ( ret = ctx->md_info->update_func( ctx->md_ctx, opad,\n                                           ctx->md_info->block_size ) ) != 0 )\n        return( ret );\n    if( ( ret = ctx->md_info->update_func( ctx->md_ctx, tmp,\n                                           ctx->md_info->size ) ) != 0 )\n        return( ret );\n    return( ctx->md_info->finish_func( ctx->md_ctx, output ) );\n}\n\nint mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx )\n{\n    int ret;\n    unsigned char *ipad;\n\n    if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )\n        return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );\n\n    ipad = (unsigned char *) ctx->hmac_ctx;\n\n    if( ( ret = ctx->md_info->starts_func( ctx->md_ctx ) ) != 0 )\n        return( ret );\n    return( ctx->md_info->update_func( ctx->md_ctx, ipad,\n                                       ctx->md_info->block_size ) );\n}\n\nint mbedtls_md_hmac( const mbedtls_md_info_t *md_info,\n                     const unsigned char *key, size_t keylen,\n                     const unsigned char *input, size_t ilen,\n                     unsigned char *output )\n{\n    mbedtls_md_context_t ctx;\n    int ret;\n\n    if( md_info == NULL )\n        return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );\n\n    mbedtls_md_init( &ctx );\n\n    if( ( ret = mbedtls_md_setup( &ctx, md_info, 1 ) ) != 0 )\n        goto cleanup;\n\n    if( ( ret = mbedtls_md_hmac_starts( &ctx, key, keylen ) ) != 0 )\n        goto cleanup;\n    if( ( ret = mbedtls_md_hmac_update( &ctx, input, ilen ) ) != 0 )\n        goto cleanup;\n    if( ( ret = mbedtls_md_hmac_finish( &ctx, output ) ) != 0 )\n        goto cleanup;\n\ncleanup:\n    mbedtls_md_free( &ctx );\n\n    return( ret );\n}\n\nint mbedtls_md_process( mbedtls_md_context_t *ctx, const unsigned char *data )\n{\n    if( ctx == NULL || ctx->md_info == NULL )\n        return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );\n\n    return( ctx->md_info->process_func( ctx->md_ctx, data ) );\n}\n\nunsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info )\n{\n    if( md_info == NULL )\n        return( 0 );\n\n    return md_info->size;\n}\n\nmbedtls_md_type_t mbedtls_md_get_type( const mbedtls_md_info_t *md_info )\n{\n    if( md_info == NULL )\n        return( MBEDTLS_MD_NONE );\n\n    return md_info->type;\n}\n\nconst char *mbedtls_md_get_name( const mbedtls_md_info_t *md_info )\n{\n    if( md_info == NULL )\n        return( NULL );\n\n    return md_info->name;\n}\n\n#endif /* MBEDTLS_MD_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/md2.c",
    "content": "/*\n *  RFC 1115/1319 compliant MD2 implementation\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The MD2 algorithm was designed by Ron Rivest in 1989.\n *\n *  http://www.ietf.org/rfc/rfc1115.txt\n *  http://www.ietf.org/rfc/rfc1319.txt\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_MD2_C)\n\n#include \"mbedtls/md2.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if !defined(MBEDTLS_MD2_ALT)\n\nstatic const unsigned char PI_SUBST[256] =\n{\n    0x29, 0x2E, 0x43, 0xC9, 0xA2, 0xD8, 0x7C, 0x01, 0x3D, 0x36,\n    0x54, 0xA1, 0xEC, 0xF0, 0x06, 0x13, 0x62, 0xA7, 0x05, 0xF3,\n    0xC0, 0xC7, 0x73, 0x8C, 0x98, 0x93, 0x2B, 0xD9, 0xBC, 0x4C,\n    0x82, 0xCA, 0x1E, 0x9B, 0x57, 0x3C, 0xFD, 0xD4, 0xE0, 0x16,\n    0x67, 0x42, 0x6F, 0x18, 0x8A, 0x17, 0xE5, 0x12, 0xBE, 0x4E,\n    0xC4, 0xD6, 0xDA, 0x9E, 0xDE, 0x49, 0xA0, 0xFB, 0xF5, 0x8E,\n    0xBB, 0x2F, 0xEE, 0x7A, 0xA9, 0x68, 0x79, 0x91, 0x15, 0xB2,\n    0x07, 0x3F, 0x94, 0xC2, 0x10, 0x89, 0x0B, 0x22, 0x5F, 0x21,\n    0x80, 0x7F, 0x5D, 0x9A, 0x5A, 0x90, 0x32, 0x27, 0x35, 0x3E,\n    0xCC, 0xE7, 0xBF, 0xF7, 0x97, 0x03, 0xFF, 0x19, 0x30, 0xB3,\n    0x48, 0xA5, 0xB5, 0xD1, 0xD7, 0x5E, 0x92, 0x2A, 0xAC, 0x56,\n    0xAA, 0xC6, 0x4F, 0xB8, 0x38, 0xD2, 0x96, 0xA4, 0x7D, 0xB6,\n    0x76, 0xFC, 0x6B, 0xE2, 0x9C, 0x74, 0x04, 0xF1, 0x45, 0x9D,\n    0x70, 0x59, 0x64, 0x71, 0x87, 0x20, 0x86, 0x5B, 0xCF, 0x65,\n    0xE6, 0x2D, 0xA8, 0x02, 0x1B, 0x60, 0x25, 0xAD, 0xAE, 0xB0,\n    0xB9, 0xF6, 0x1C, 0x46, 0x61, 0x69, 0x34, 0x40, 0x7E, 0x0F,\n    0x55, 0x47, 0xA3, 0x23, 0xDD, 0x51, 0xAF, 0x3A, 0xC3, 0x5C,\n    0xF9, 0xCE, 0xBA, 0xC5, 0xEA, 0x26, 0x2C, 0x53, 0x0D, 0x6E,\n    0x85, 0x28, 0x84, 0x09, 0xD3, 0xDF, 0xCD, 0xF4, 0x41, 0x81,\n    0x4D, 0x52, 0x6A, 0xDC, 0x37, 0xC8, 0x6C, 0xC1, 0xAB, 0xFA,\n    0x24, 0xE1, 0x7B, 0x08, 0x0C, 0xBD, 0xB1, 0x4A, 0x78, 0x88,\n    0x95, 0x8B, 0xE3, 0x63, 0xE8, 0x6D, 0xE9, 0xCB, 0xD5, 0xFE,\n    0x3B, 0x00, 0x1D, 0x39, 0xF2, 0xEF, 0xB7, 0x0E, 0x66, 0x58,\n    0xD0, 0xE4, 0xA6, 0x77, 0x72, 0xF8, 0xEB, 0x75, 0x4B, 0x0A,\n    0x31, 0x44, 0x50, 0xB4, 0x8F, 0xED, 0x1F, 0x1A, 0xDB, 0x99,\n    0x8D, 0x33, 0x9F, 0x11, 0x83, 0x14\n};\n\nvoid mbedtls_md2_init( mbedtls_md2_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_md2_context ) );\n}\n\nvoid mbedtls_md2_free( mbedtls_md2_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md2_context ) );\n}\n\nvoid mbedtls_md2_clone( mbedtls_md2_context *dst,\n                        const mbedtls_md2_context *src )\n{\n    *dst = *src;\n}\n\n/*\n * MD2 context setup\n */\nint mbedtls_md2_starts_ret( mbedtls_md2_context *ctx )\n{\n    memset( ctx->cksum, 0, 16 );\n    memset( ctx->state, 0, 46 );\n    memset( ctx->buffer, 0, 16 );\n    ctx->left = 0;\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_md2_starts( mbedtls_md2_context *ctx )\n{\n    mbedtls_md2_starts_ret( ctx );\n}\n#endif\n\n#if !defined(MBEDTLS_MD2_PROCESS_ALT)\nint mbedtls_internal_md2_process( mbedtls_md2_context *ctx )\n{\n    int i, j;\n    unsigned char t = 0;\n\n    for( i = 0; i < 16; i++ )\n    {\n        ctx->state[i + 16] = ctx->buffer[i];\n        ctx->state[i + 32] =\n            (unsigned char)( ctx->buffer[i] ^ ctx->state[i]);\n    }\n\n    for( i = 0; i < 18; i++ )\n    {\n        for( j = 0; j < 48; j++ )\n        {\n            ctx->state[j] = (unsigned char)\n               ( ctx->state[j] ^ PI_SUBST[t] );\n            t  = ctx->state[j];\n        }\n\n        t = (unsigned char)( t + i );\n    }\n\n    t = ctx->cksum[15];\n\n    for( i = 0; i < 16; i++ )\n    {\n        ctx->cksum[i] = (unsigned char)\n           ( ctx->cksum[i] ^ PI_SUBST[ctx->buffer[i] ^ t] );\n        t  = ctx->cksum[i];\n    }\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_md2_process( mbedtls_md2_context *ctx )\n{\n    mbedtls_internal_md2_process( ctx );\n}\n#endif\n#endif /* !MBEDTLS_MD2_PROCESS_ALT */\n\n/*\n * MD2 process buffer\n */\nint mbedtls_md2_update_ret( mbedtls_md2_context *ctx,\n                            const unsigned char *input,\n                            size_t ilen )\n{\n    int ret;\n    size_t fill;\n\n    while( ilen > 0 )\n    {\n        if( ilen > 16 - ctx->left )\n            fill = 16 - ctx->left;\n        else\n            fill = ilen;\n\n        memcpy( ctx->buffer + ctx->left, input, fill );\n\n        ctx->left += fill;\n        input += fill;\n        ilen  -= fill;\n\n        if( ctx->left == 16 )\n        {\n            ctx->left = 0;\n            if( ( ret = mbedtls_internal_md2_process( ctx ) ) != 0 )\n                return( ret );\n        }\n    }\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_md2_update( mbedtls_md2_context *ctx,\n                         const unsigned char *input,\n                         size_t ilen )\n{\n    mbedtls_md2_update_ret( ctx, input, ilen );\n}\n#endif\n\n/*\n * MD2 final digest\n */\nint mbedtls_md2_finish_ret( mbedtls_md2_context *ctx,\n                            unsigned char output[16] )\n{\n    int ret;\n    size_t i;\n    unsigned char x;\n\n    x = (unsigned char)( 16 - ctx->left );\n\n    for( i = ctx->left; i < 16; i++ )\n        ctx->buffer[i] = x;\n\n    if( ( ret = mbedtls_internal_md2_process( ctx ) ) != 0 )\n        return( ret );\n\n    memcpy( ctx->buffer, ctx->cksum, 16 );\n    if( ( ret = mbedtls_internal_md2_process( ctx ) ) != 0 )\n        return( ret );\n\n    memcpy( output, ctx->state, 16 );\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_md2_finish( mbedtls_md2_context *ctx,\n                         unsigned char output[16] )\n{\n    mbedtls_md2_finish_ret( ctx, output );\n}\n#endif\n\n#endif /* !MBEDTLS_MD2_ALT */\n\n/*\n * output = MD2( input buffer )\n */\nint mbedtls_md2_ret( const unsigned char *input,\n                     size_t ilen,\n                     unsigned char output[16] )\n{\n    int ret;\n    mbedtls_md2_context ctx;\n\n    mbedtls_md2_init( &ctx );\n\n    if( ( ret = mbedtls_md2_starts_ret( &ctx ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_md2_update_ret( &ctx, input, ilen ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_md2_finish_ret( &ctx, output ) ) != 0 )\n        goto exit;\n\nexit:\n    mbedtls_md2_free( &ctx );\n\n    return( ret );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_md2( const unsigned char *input,\n                  size_t ilen,\n                  unsigned char output[16] )\n{\n    mbedtls_md2_ret( input, ilen, output );\n}\n#endif\n\n#if defined(MBEDTLS_SELF_TEST)\n\n/*\n * RFC 1319 test vectors\n */\nstatic const unsigned char md2_test_str[7][81] =\n{\n    { \"\" },\n    { \"a\" },\n    { \"abc\" },\n    { \"message digest\" },\n    { \"abcdefghijklmnopqrstuvwxyz\" },\n    { \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\" },\n    { \"12345678901234567890123456789012345678901234567890123456789012\"\n      \"345678901234567890\" }\n};\n\nstatic const size_t md2_test_strlen[7] =\n{\n    0, 1, 3, 14, 26, 62, 80\n};\n\nstatic const unsigned char md2_test_sum[7][16] =\n{\n    { 0x83, 0x50, 0xE5, 0xA3, 0xE2, 0x4C, 0x15, 0x3D,\n      0xF2, 0x27, 0x5C, 0x9F, 0x80, 0x69, 0x27, 0x73 },\n    { 0x32, 0xEC, 0x01, 0xEC, 0x4A, 0x6D, 0xAC, 0x72,\n      0xC0, 0xAB, 0x96, 0xFB, 0x34, 0xC0, 0xB5, 0xD1 },\n    { 0xDA, 0x85, 0x3B, 0x0D, 0x3F, 0x88, 0xD9, 0x9B,\n      0x30, 0x28, 0x3A, 0x69, 0xE6, 0xDE, 0xD6, 0xBB },\n    { 0xAB, 0x4F, 0x49, 0x6B, 0xFB, 0x2A, 0x53, 0x0B,\n      0x21, 0x9F, 0xF3, 0x30, 0x31, 0xFE, 0x06, 0xB0 },\n    { 0x4E, 0x8D, 0xDF, 0xF3, 0x65, 0x02, 0x92, 0xAB,\n      0x5A, 0x41, 0x08, 0xC3, 0xAA, 0x47, 0x94, 0x0B },\n    { 0xDA, 0x33, 0xDE, 0xF2, 0xA4, 0x2D, 0xF1, 0x39,\n      0x75, 0x35, 0x28, 0x46, 0xC3, 0x03, 0x38, 0xCD },\n    { 0xD5, 0x97, 0x6F, 0x79, 0xD8, 0x3D, 0x3A, 0x0D,\n      0xC9, 0x80, 0x6C, 0x3C, 0x66, 0xF3, 0xEF, 0xD8 }\n};\n\n/*\n * Checkup routine\n */\nint mbedtls_md2_self_test( int verbose )\n{\n    int i, ret = 0;\n    unsigned char md2sum[16];\n\n    for( i = 0; i < 7; i++ )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"  MD2 test #%d: \", i + 1 );\n\n        ret = mbedtls_md2_ret( md2_test_str[i], md2_test_strlen[i], md2sum );\n        if( ret != 0 )\n            goto fail;\n\n        if( memcmp( md2sum, md2_test_sum[i], 16 ) != 0 )\n        {\n            ret = 1;\n            goto fail;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    return( 0 );\n\nfail:\n    if( verbose != 0 )\n        mbedtls_printf( \"failed\\n\" );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_MD2_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/md4.c",
    "content": "/*\n *  RFC 1186/1320 compliant MD4 implementation\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The MD4 algorithm was designed by Ron Rivest in 1990.\n *\n *  http://www.ietf.org/rfc/rfc1186.txt\n *  http://www.ietf.org/rfc/rfc1320.txt\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_MD4_C)\n\n#include \"mbedtls/md4.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if !defined(MBEDTLS_MD4_ALT)\n\n/*\n * 32-bit integer manipulation macros (little endian)\n */\n#ifndef GET_UINT32_LE\n#define GET_UINT32_LE(n,b,i)                            \\\n{                                                       \\\n    (n) = ( (uint32_t) (b)[(i)    ]       )             \\\n        | ( (uint32_t) (b)[(i) + 1] <<  8 )             \\\n        | ( (uint32_t) (b)[(i) + 2] << 16 )             \\\n        | ( (uint32_t) (b)[(i) + 3] << 24 );            \\\n}\n#endif\n\n#ifndef PUT_UINT32_LE\n#define PUT_UINT32_LE(n,b,i)                                    \\\n{                                                               \\\n    (b)[(i)    ] = (unsigned char) ( ( (n)       ) & 0xFF );    \\\n    (b)[(i) + 1] = (unsigned char) ( ( (n) >>  8 ) & 0xFF );    \\\n    (b)[(i) + 2] = (unsigned char) ( ( (n) >> 16 ) & 0xFF );    \\\n    (b)[(i) + 3] = (unsigned char) ( ( (n) >> 24 ) & 0xFF );    \\\n}\n#endif\n\nvoid mbedtls_md4_init( mbedtls_md4_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_md4_context ) );\n}\n\nvoid mbedtls_md4_free( mbedtls_md4_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md4_context ) );\n}\n\nvoid mbedtls_md4_clone( mbedtls_md4_context *dst,\n                        const mbedtls_md4_context *src )\n{\n    *dst = *src;\n}\n\n/*\n * MD4 context setup\n */\nint mbedtls_md4_starts_ret( mbedtls_md4_context *ctx )\n{\n    ctx->total[0] = 0;\n    ctx->total[1] = 0;\n\n    ctx->state[0] = 0x67452301;\n    ctx->state[1] = 0xEFCDAB89;\n    ctx->state[2] = 0x98BADCFE;\n    ctx->state[3] = 0x10325476;\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_md4_starts( mbedtls_md4_context *ctx )\n{\n    mbedtls_md4_starts_ret( ctx );\n}\n#endif\n\n#if !defined(MBEDTLS_MD4_PROCESS_ALT)\nint mbedtls_internal_md4_process( mbedtls_md4_context *ctx,\n                                  const unsigned char data[64] )\n{\n    uint32_t X[16], A, B, C, D;\n\n    GET_UINT32_LE( X[ 0], data,  0 );\n    GET_UINT32_LE( X[ 1], data,  4 );\n    GET_UINT32_LE( X[ 2], data,  8 );\n    GET_UINT32_LE( X[ 3], data, 12 );\n    GET_UINT32_LE( X[ 4], data, 16 );\n    GET_UINT32_LE( X[ 5], data, 20 );\n    GET_UINT32_LE( X[ 6], data, 24 );\n    GET_UINT32_LE( X[ 7], data, 28 );\n    GET_UINT32_LE( X[ 8], data, 32 );\n    GET_UINT32_LE( X[ 9], data, 36 );\n    GET_UINT32_LE( X[10], data, 40 );\n    GET_UINT32_LE( X[11], data, 44 );\n    GET_UINT32_LE( X[12], data, 48 );\n    GET_UINT32_LE( X[13], data, 52 );\n    GET_UINT32_LE( X[14], data, 56 );\n    GET_UINT32_LE( X[15], data, 60 );\n\n#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n)))\n\n    A = ctx->state[0];\n    B = ctx->state[1];\n    C = ctx->state[2];\n    D = ctx->state[3];\n\n#define F(x, y, z) ((x & y) | ((~x) & z))\n#define P(a,b,c,d,x,s) { a += F(b,c,d) + x; a = S(a,s); }\n\n    P( A, B, C, D, X[ 0],  3 );\n    P( D, A, B, C, X[ 1],  7 );\n    P( C, D, A, B, X[ 2], 11 );\n    P( B, C, D, A, X[ 3], 19 );\n    P( A, B, C, D, X[ 4],  3 );\n    P( D, A, B, C, X[ 5],  7 );\n    P( C, D, A, B, X[ 6], 11 );\n    P( B, C, D, A, X[ 7], 19 );\n    P( A, B, C, D, X[ 8],  3 );\n    P( D, A, B, C, X[ 9],  7 );\n    P( C, D, A, B, X[10], 11 );\n    P( B, C, D, A, X[11], 19 );\n    P( A, B, C, D, X[12],  3 );\n    P( D, A, B, C, X[13],  7 );\n    P( C, D, A, B, X[14], 11 );\n    P( B, C, D, A, X[15], 19 );\n\n#undef P\n#undef F\n\n#define F(x,y,z) ((x & y) | (x & z) | (y & z))\n#define P(a,b,c,d,x,s) { a += F(b,c,d) + x + 0x5A827999; a = S(a,s); }\n\n    P( A, B, C, D, X[ 0],  3 );\n    P( D, A, B, C, X[ 4],  5 );\n    P( C, D, A, B, X[ 8],  9 );\n    P( B, C, D, A, X[12], 13 );\n    P( A, B, C, D, X[ 1],  3 );\n    P( D, A, B, C, X[ 5],  5 );\n    P( C, D, A, B, X[ 9],  9 );\n    P( B, C, D, A, X[13], 13 );\n    P( A, B, C, D, X[ 2],  3 );\n    P( D, A, B, C, X[ 6],  5 );\n    P( C, D, A, B, X[10],  9 );\n    P( B, C, D, A, X[14], 13 );\n    P( A, B, C, D, X[ 3],  3 );\n    P( D, A, B, C, X[ 7],  5 );\n    P( C, D, A, B, X[11],  9 );\n    P( B, C, D, A, X[15], 13 );\n\n#undef P\n#undef F\n\n#define F(x,y,z) (x ^ y ^ z)\n#define P(a,b,c,d,x,s) { a += F(b,c,d) + x + 0x6ED9EBA1; a = S(a,s); }\n\n    P( A, B, C, D, X[ 0],  3 );\n    P( D, A, B, C, X[ 8],  9 );\n    P( C, D, A, B, X[ 4], 11 );\n    P( B, C, D, A, X[12], 15 );\n    P( A, B, C, D, X[ 2],  3 );\n    P( D, A, B, C, X[10],  9 );\n    P( C, D, A, B, X[ 6], 11 );\n    P( B, C, D, A, X[14], 15 );\n    P( A, B, C, D, X[ 1],  3 );\n    P( D, A, B, C, X[ 9],  9 );\n    P( C, D, A, B, X[ 5], 11 );\n    P( B, C, D, A, X[13], 15 );\n    P( A, B, C, D, X[ 3],  3 );\n    P( D, A, B, C, X[11],  9 );\n    P( C, D, A, B, X[ 7], 11 );\n    P( B, C, D, A, X[15], 15 );\n\n#undef F\n#undef P\n\n    ctx->state[0] += A;\n    ctx->state[1] += B;\n    ctx->state[2] += C;\n    ctx->state[3] += D;\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_md4_process( mbedtls_md4_context *ctx,\n                          const unsigned char data[64] )\n{\n    mbedtls_internal_md4_process( ctx, data );\n}\n#endif\n#endif /* !MBEDTLS_MD4_PROCESS_ALT */\n\n/*\n * MD4 process buffer\n */\nint mbedtls_md4_update_ret( mbedtls_md4_context *ctx,\n                            const unsigned char *input,\n                            size_t ilen )\n{\n    int ret;\n    size_t fill;\n    uint32_t left;\n\n    if( ilen == 0 )\n        return( 0 );\n\n    left = ctx->total[0] & 0x3F;\n    fill = 64 - left;\n\n    ctx->total[0] += (uint32_t) ilen;\n    ctx->total[0] &= 0xFFFFFFFF;\n\n    if( ctx->total[0] < (uint32_t) ilen )\n        ctx->total[1]++;\n\n    if( left && ilen >= fill )\n    {\n        memcpy( (void *) (ctx->buffer + left),\n                (void *) input, fill );\n\n        if( ( ret = mbedtls_internal_md4_process( ctx, ctx->buffer ) ) != 0 )\n            return( ret );\n\n        input += fill;\n        ilen  -= fill;\n        left = 0;\n    }\n\n    while( ilen >= 64 )\n    {\n        if( ( ret = mbedtls_internal_md4_process( ctx, input ) ) != 0 )\n            return( ret );\n\n        input += 64;\n        ilen  -= 64;\n    }\n\n    if( ilen > 0 )\n    {\n        memcpy( (void *) (ctx->buffer + left),\n                (void *) input, ilen );\n    }\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_md4_update( mbedtls_md4_context *ctx,\n                         const unsigned char *input,\n                         size_t ilen )\n{\n    mbedtls_md4_update_ret( ctx, input, ilen );\n}\n#endif\n\nstatic const unsigned char md4_padding[64] =\n{\n 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n};\n\n/*\n * MD4 final digest\n */\nint mbedtls_md4_finish_ret( mbedtls_md4_context *ctx,\n                            unsigned char output[16] )\n{\n    int ret;\n    uint32_t last, padn;\n    uint32_t high, low;\n    unsigned char msglen[8];\n\n    high = ( ctx->total[0] >> 29 )\n         | ( ctx->total[1] <<  3 );\n    low  = ( ctx->total[0] <<  3 );\n\n    PUT_UINT32_LE( low,  msglen, 0 );\n    PUT_UINT32_LE( high, msglen, 4 );\n\n    last = ctx->total[0] & 0x3F;\n    padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );\n\n    ret = mbedtls_md4_update_ret( ctx, (unsigned char *)md4_padding, padn );\n    if( ret != 0 )\n        return( ret );\n\n    if( ( ret = mbedtls_md4_update_ret( ctx, msglen, 8 ) ) != 0 )\n        return( ret );\n\n\n    PUT_UINT32_LE( ctx->state[0], output,  0 );\n    PUT_UINT32_LE( ctx->state[1], output,  4 );\n    PUT_UINT32_LE( ctx->state[2], output,  8 );\n    PUT_UINT32_LE( ctx->state[3], output, 12 );\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_md4_finish( mbedtls_md4_context *ctx,\n                         unsigned char output[16] )\n{\n    mbedtls_md4_finish_ret( ctx, output );\n}\n#endif\n\n#endif /* !MBEDTLS_MD4_ALT */\n\n/*\n * output = MD4( input buffer )\n */\nint mbedtls_md4_ret( const unsigned char *input,\n                     size_t ilen,\n                     unsigned char output[16] )\n{\n    int ret;\n    mbedtls_md4_context ctx;\n\n    mbedtls_md4_init( &ctx );\n\n    if( ( ret = mbedtls_md4_starts_ret( &ctx ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_md4_update_ret( &ctx, input, ilen ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_md4_finish_ret( &ctx, output ) ) != 0 )\n        goto exit;\n\nexit:\n    mbedtls_md4_free( &ctx );\n\n    return( ret );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_md4( const unsigned char *input,\n                  size_t ilen,\n                  unsigned char output[16] )\n{\n    mbedtls_md4_ret( input, ilen, output );\n}\n#endif\n\n#if defined(MBEDTLS_SELF_TEST)\n\n/*\n * RFC 1320 test vectors\n */\nstatic const unsigned char md4_test_str[7][81] =\n{\n    { \"\" },\n    { \"a\" },\n    { \"abc\" },\n    { \"message digest\" },\n    { \"abcdefghijklmnopqrstuvwxyz\" },\n    { \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\" },\n    { \"12345678901234567890123456789012345678901234567890123456789012\"\n      \"345678901234567890\" }\n};\n\nstatic const size_t md4_test_strlen[7] =\n{\n    0, 1, 3, 14, 26, 62, 80\n};\n\nstatic const unsigned char md4_test_sum[7][16] =\n{\n    { 0x31, 0xD6, 0xCF, 0xE0, 0xD1, 0x6A, 0xE9, 0x31,\n      0xB7, 0x3C, 0x59, 0xD7, 0xE0, 0xC0, 0x89, 0xC0 },\n    { 0xBD, 0xE5, 0x2C, 0xB3, 0x1D, 0xE3, 0x3E, 0x46,\n      0x24, 0x5E, 0x05, 0xFB, 0xDB, 0xD6, 0xFB, 0x24 },\n    { 0xA4, 0x48, 0x01, 0x7A, 0xAF, 0x21, 0xD8, 0x52,\n      0x5F, 0xC1, 0x0A, 0xE8, 0x7A, 0xA6, 0x72, 0x9D },\n    { 0xD9, 0x13, 0x0A, 0x81, 0x64, 0x54, 0x9F, 0xE8,\n      0x18, 0x87, 0x48, 0x06, 0xE1, 0xC7, 0x01, 0x4B },\n    { 0xD7, 0x9E, 0x1C, 0x30, 0x8A, 0xA5, 0xBB, 0xCD,\n      0xEE, 0xA8, 0xED, 0x63, 0xDF, 0x41, 0x2D, 0xA9 },\n    { 0x04, 0x3F, 0x85, 0x82, 0xF2, 0x41, 0xDB, 0x35,\n      0x1C, 0xE6, 0x27, 0xE1, 0x53, 0xE7, 0xF0, 0xE4 },\n    { 0xE3, 0x3B, 0x4D, 0xDC, 0x9C, 0x38, 0xF2, 0x19,\n      0x9C, 0x3E, 0x7B, 0x16, 0x4F, 0xCC, 0x05, 0x36 }\n};\n\n/*\n * Checkup routine\n */\nint mbedtls_md4_self_test( int verbose )\n{\n    int i, ret = 0;\n    unsigned char md4sum[16];\n\n    for( i = 0; i < 7; i++ )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"  MD4 test #%d: \", i + 1 );\n\n        ret = mbedtls_md4_ret( md4_test_str[i], md4_test_strlen[i], md4sum );\n        if( ret != 0 )\n            goto fail;\n\n        if( memcmp( md4sum, md4_test_sum[i], 16 ) != 0 )\n        {\n            ret = 1;\n            goto fail;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    return( 0 );\n\nfail:\n    if( verbose != 0 )\n        mbedtls_printf( \"failed\\n\" );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_MD4_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/md5.c",
    "content": "/*\n *  RFC 1321 compliant MD5 implementation\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The MD5 algorithm was designed by Ron Rivest in 1991.\n *\n *  http://www.ietf.org/rfc/rfc1321.txt\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_MD5_C)\n\n#include \"mbedtls/md5.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if !defined(MBEDTLS_MD5_ALT)\n\n/*\n * 32-bit integer manipulation macros (little endian)\n */\n#ifndef GET_UINT32_LE\n#define GET_UINT32_LE(n,b,i)                            \\\n{                                                       \\\n    (n) = ( (uint32_t) (b)[(i)    ]       )             \\\n        | ( (uint32_t) (b)[(i) + 1] <<  8 )             \\\n        | ( (uint32_t) (b)[(i) + 2] << 16 )             \\\n        | ( (uint32_t) (b)[(i) + 3] << 24 );            \\\n}\n#endif\n\n#ifndef PUT_UINT32_LE\n#define PUT_UINT32_LE(n,b,i)                                    \\\n{                                                               \\\n    (b)[(i)    ] = (unsigned char) ( ( (n)       ) & 0xFF );    \\\n    (b)[(i) + 1] = (unsigned char) ( ( (n) >>  8 ) & 0xFF );    \\\n    (b)[(i) + 2] = (unsigned char) ( ( (n) >> 16 ) & 0xFF );    \\\n    (b)[(i) + 3] = (unsigned char) ( ( (n) >> 24 ) & 0xFF );    \\\n}\n#endif\n\nvoid mbedtls_md5_init( mbedtls_md5_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_md5_context ) );\n}\n\nvoid mbedtls_md5_free( mbedtls_md5_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md5_context ) );\n}\n\nvoid mbedtls_md5_clone( mbedtls_md5_context *dst,\n                        const mbedtls_md5_context *src )\n{\n    *dst = *src;\n}\n\n/*\n * MD5 context setup\n */\nint mbedtls_md5_starts_ret( mbedtls_md5_context *ctx )\n{\n    ctx->total[0] = 0;\n    ctx->total[1] = 0;\n\n    ctx->state[0] = 0x67452301;\n    ctx->state[1] = 0xEFCDAB89;\n    ctx->state[2] = 0x98BADCFE;\n    ctx->state[3] = 0x10325476;\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_md5_starts( mbedtls_md5_context *ctx )\n{\n    mbedtls_md5_starts_ret( ctx );\n}\n#endif\n\n#if !defined(MBEDTLS_MD5_PROCESS_ALT)\nint mbedtls_internal_md5_process( mbedtls_md5_context *ctx,\n                                  const unsigned char data[64] )\n{\n    uint32_t X[16], A, B, C, D;\n\n    GET_UINT32_LE( X[ 0], data,  0 );\n    GET_UINT32_LE( X[ 1], data,  4 );\n    GET_UINT32_LE( X[ 2], data,  8 );\n    GET_UINT32_LE( X[ 3], data, 12 );\n    GET_UINT32_LE( X[ 4], data, 16 );\n    GET_UINT32_LE( X[ 5], data, 20 );\n    GET_UINT32_LE( X[ 6], data, 24 );\n    GET_UINT32_LE( X[ 7], data, 28 );\n    GET_UINT32_LE( X[ 8], data, 32 );\n    GET_UINT32_LE( X[ 9], data, 36 );\n    GET_UINT32_LE( X[10], data, 40 );\n    GET_UINT32_LE( X[11], data, 44 );\n    GET_UINT32_LE( X[12], data, 48 );\n    GET_UINT32_LE( X[13], data, 52 );\n    GET_UINT32_LE( X[14], data, 56 );\n    GET_UINT32_LE( X[15], data, 60 );\n\n#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n)))\n\n#define P(a,b,c,d,k,s,t)                                \\\n{                                                       \\\n    a += F(b,c,d) + X[k] + t; a = S(a,s) + b;           \\\n}\n\n    A = ctx->state[0];\n    B = ctx->state[1];\n    C = ctx->state[2];\n    D = ctx->state[3];\n\n#define F(x,y,z) (z ^ (x & (y ^ z)))\n\n    P( A, B, C, D,  0,  7, 0xD76AA478 );\n    P( D, A, B, C,  1, 12, 0xE8C7B756 );\n    P( C, D, A, B,  2, 17, 0x242070DB );\n    P( B, C, D, A,  3, 22, 0xC1BDCEEE );\n    P( A, B, C, D,  4,  7, 0xF57C0FAF );\n    P( D, A, B, C,  5, 12, 0x4787C62A );\n    P( C, D, A, B,  6, 17, 0xA8304613 );\n    P( B, C, D, A,  7, 22, 0xFD469501 );\n    P( A, B, C, D,  8,  7, 0x698098D8 );\n    P( D, A, B, C,  9, 12, 0x8B44F7AF );\n    P( C, D, A, B, 10, 17, 0xFFFF5BB1 );\n    P( B, C, D, A, 11, 22, 0x895CD7BE );\n    P( A, B, C, D, 12,  7, 0x6B901122 );\n    P( D, A, B, C, 13, 12, 0xFD987193 );\n    P( C, D, A, B, 14, 17, 0xA679438E );\n    P( B, C, D, A, 15, 22, 0x49B40821 );\n\n#undef F\n\n#define F(x,y,z) (y ^ (z & (x ^ y)))\n\n    P( A, B, C, D,  1,  5, 0xF61E2562 );\n    P( D, A, B, C,  6,  9, 0xC040B340 );\n    P( C, D, A, B, 11, 14, 0x265E5A51 );\n    P( B, C, D, A,  0, 20, 0xE9B6C7AA );\n    P( A, B, C, D,  5,  5, 0xD62F105D );\n    P( D, A, B, C, 10,  9, 0x02441453 );\n    P( C, D, A, B, 15, 14, 0xD8A1E681 );\n    P( B, C, D, A,  4, 20, 0xE7D3FBC8 );\n    P( A, B, C, D,  9,  5, 0x21E1CDE6 );\n    P( D, A, B, C, 14,  9, 0xC33707D6 );\n    P( C, D, A, B,  3, 14, 0xF4D50D87 );\n    P( B, C, D, A,  8, 20, 0x455A14ED );\n    P( A, B, C, D, 13,  5, 0xA9E3E905 );\n    P( D, A, B, C,  2,  9, 0xFCEFA3F8 );\n    P( C, D, A, B,  7, 14, 0x676F02D9 );\n    P( B, C, D, A, 12, 20, 0x8D2A4C8A );\n\n#undef F\n\n#define F(x,y,z) (x ^ y ^ z)\n\n    P( A, B, C, D,  5,  4, 0xFFFA3942 );\n    P( D, A, B, C,  8, 11, 0x8771F681 );\n    P( C, D, A, B, 11, 16, 0x6D9D6122 );\n    P( B, C, D, A, 14, 23, 0xFDE5380C );\n    P( A, B, C, D,  1,  4, 0xA4BEEA44 );\n    P( D, A, B, C,  4, 11, 0x4BDECFA9 );\n    P( C, D, A, B,  7, 16, 0xF6BB4B60 );\n    P( B, C, D, A, 10, 23, 0xBEBFBC70 );\n    P( A, B, C, D, 13,  4, 0x289B7EC6 );\n    P( D, A, B, C,  0, 11, 0xEAA127FA );\n    P( C, D, A, B,  3, 16, 0xD4EF3085 );\n    P( B, C, D, A,  6, 23, 0x04881D05 );\n    P( A, B, C, D,  9,  4, 0xD9D4D039 );\n    P( D, A, B, C, 12, 11, 0xE6DB99E5 );\n    P( C, D, A, B, 15, 16, 0x1FA27CF8 );\n    P( B, C, D, A,  2, 23, 0xC4AC5665 );\n\n#undef F\n\n#define F(x,y,z) (y ^ (x | ~z))\n\n    P( A, B, C, D,  0,  6, 0xF4292244 );\n    P( D, A, B, C,  7, 10, 0x432AFF97 );\n    P( C, D, A, B, 14, 15, 0xAB9423A7 );\n    P( B, C, D, A,  5, 21, 0xFC93A039 );\n    P( A, B, C, D, 12,  6, 0x655B59C3 );\n    P( D, A, B, C,  3, 10, 0x8F0CCC92 );\n    P( C, D, A, B, 10, 15, 0xFFEFF47D );\n    P( B, C, D, A,  1, 21, 0x85845DD1 );\n    P( A, B, C, D,  8,  6, 0x6FA87E4F );\n    P( D, A, B, C, 15, 10, 0xFE2CE6E0 );\n    P( C, D, A, B,  6, 15, 0xA3014314 );\n    P( B, C, D, A, 13, 21, 0x4E0811A1 );\n    P( A, B, C, D,  4,  6, 0xF7537E82 );\n    P( D, A, B, C, 11, 10, 0xBD3AF235 );\n    P( C, D, A, B,  2, 15, 0x2AD7D2BB );\n    P( B, C, D, A,  9, 21, 0xEB86D391 );\n\n#undef F\n\n    ctx->state[0] += A;\n    ctx->state[1] += B;\n    ctx->state[2] += C;\n    ctx->state[3] += D;\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_md5_process( mbedtls_md5_context *ctx,\n                          const unsigned char data[64] )\n{\n    mbedtls_internal_md5_process( ctx, data );\n}\n#endif\n#endif /* !MBEDTLS_MD5_PROCESS_ALT */\n\n/*\n * MD5 process buffer\n */\nint mbedtls_md5_update_ret( mbedtls_md5_context *ctx,\n                            const unsigned char *input,\n                            size_t ilen )\n{\n    int ret;\n    size_t fill;\n    uint32_t left;\n\n    if( ilen == 0 )\n        return( 0 );\n\n    left = ctx->total[0] & 0x3F;\n    fill = 64 - left;\n\n    ctx->total[0] += (uint32_t) ilen;\n    ctx->total[0] &= 0xFFFFFFFF;\n\n    if( ctx->total[0] < (uint32_t) ilen )\n        ctx->total[1]++;\n\n    if( left && ilen >= fill )\n    {\n        memcpy( (void *) (ctx->buffer + left), input, fill );\n        if( ( ret = mbedtls_internal_md5_process( ctx, ctx->buffer ) ) != 0 )\n            return( ret );\n\n        input += fill;\n        ilen  -= fill;\n        left = 0;\n    }\n\n    while( ilen >= 64 )\n    {\n        if( ( ret = mbedtls_internal_md5_process( ctx, input ) ) != 0 )\n            return( ret );\n\n        input += 64;\n        ilen  -= 64;\n    }\n\n    if( ilen > 0 )\n    {\n        memcpy( (void *) (ctx->buffer + left), input, ilen );\n    }\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_md5_update( mbedtls_md5_context *ctx,\n                         const unsigned char *input,\n                         size_t ilen )\n{\n    mbedtls_md5_update_ret( ctx, input, ilen );\n}\n#endif\n\n/*\n * MD5 final digest\n */\nint mbedtls_md5_finish_ret( mbedtls_md5_context *ctx,\n                            unsigned char output[16] )\n{\n    int ret;\n    uint32_t used;\n    uint32_t high, low;\n\n    /*\n     * Add padding: 0x80 then 0x00 until 8 bytes remain for the length\n     */\n    used = ctx->total[0] & 0x3F;\n\n    ctx->buffer[used++] = 0x80;\n\n    if( used <= 56 )\n    {\n        /* Enough room for padding + length in current block */\n        memset( ctx->buffer + used, 0, 56 - used );\n    }\n    else\n    {\n        /* We'll need an extra block */\n        memset( ctx->buffer + used, 0, 64 - used );\n\n        if( ( ret = mbedtls_internal_md5_process( ctx, ctx->buffer ) ) != 0 )\n            return( ret );\n\n        memset( ctx->buffer, 0, 56 );\n    }\n\n    /*\n     * Add message length\n     */\n    high = ( ctx->total[0] >> 29 )\n         | ( ctx->total[1] <<  3 );\n    low  = ( ctx->total[0] <<  3 );\n\n    PUT_UINT32_LE( low,  ctx->buffer, 56 );\n    PUT_UINT32_LE( high, ctx->buffer, 60 );\n\n    if( ( ret = mbedtls_internal_md5_process( ctx, ctx->buffer ) ) != 0 )\n        return( ret );\n\n    /*\n     * Output final state\n     */\n    PUT_UINT32_LE( ctx->state[0], output,  0 );\n    PUT_UINT32_LE( ctx->state[1], output,  4 );\n    PUT_UINT32_LE( ctx->state[2], output,  8 );\n    PUT_UINT32_LE( ctx->state[3], output, 12 );\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_md5_finish( mbedtls_md5_context *ctx,\n                         unsigned char output[16] )\n{\n    mbedtls_md5_finish_ret( ctx, output );\n}\n#endif\n\n#endif /* !MBEDTLS_MD5_ALT */\n\n/*\n * output = MD5( input buffer )\n */\nint mbedtls_md5_ret( const unsigned char *input,\n                     size_t ilen,\n                     unsigned char output[16] )\n{\n    int ret;\n    mbedtls_md5_context ctx;\n\n    mbedtls_md5_init( &ctx );\n\n    if( ( ret = mbedtls_md5_starts_ret( &ctx ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_md5_update_ret( &ctx, input, ilen ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_md5_finish_ret( &ctx, output ) ) != 0 )\n        goto exit;\n\nexit:\n    mbedtls_md5_free( &ctx );\n\n    return( ret );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_md5( const unsigned char *input,\n                  size_t ilen,\n                  unsigned char output[16] )\n{\n    mbedtls_md5_ret( input, ilen, output );\n}\n#endif\n\n#if defined(MBEDTLS_SELF_TEST)\n/*\n * RFC 1321 test vectors\n */\nstatic const unsigned char md5_test_buf[7][81] =\n{\n    { \"\" },\n    { \"a\" },\n    { \"abc\" },\n    { \"message digest\" },\n    { \"abcdefghijklmnopqrstuvwxyz\" },\n    { \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\" },\n    { \"12345678901234567890123456789012345678901234567890123456789012\"\n      \"345678901234567890\" }\n};\n\nstatic const size_t md5_test_buflen[7] =\n{\n    0, 1, 3, 14, 26, 62, 80\n};\n\nstatic const unsigned char md5_test_sum[7][16] =\n{\n    { 0xD4, 0x1D, 0x8C, 0xD9, 0x8F, 0x00, 0xB2, 0x04,\n      0xE9, 0x80, 0x09, 0x98, 0xEC, 0xF8, 0x42, 0x7E },\n    { 0x0C, 0xC1, 0x75, 0xB9, 0xC0, 0xF1, 0xB6, 0xA8,\n      0x31, 0xC3, 0x99, 0xE2, 0x69, 0x77, 0x26, 0x61 },\n    { 0x90, 0x01, 0x50, 0x98, 0x3C, 0xD2, 0x4F, 0xB0,\n      0xD6, 0x96, 0x3F, 0x7D, 0x28, 0xE1, 0x7F, 0x72 },\n    { 0xF9, 0x6B, 0x69, 0x7D, 0x7C, 0xB7, 0x93, 0x8D,\n      0x52, 0x5A, 0x2F, 0x31, 0xAA, 0xF1, 0x61, 0xD0 },\n    { 0xC3, 0xFC, 0xD3, 0xD7, 0x61, 0x92, 0xE4, 0x00,\n      0x7D, 0xFB, 0x49, 0x6C, 0xCA, 0x67, 0xE1, 0x3B },\n    { 0xD1, 0x74, 0xAB, 0x98, 0xD2, 0x77, 0xD9, 0xF5,\n      0xA5, 0x61, 0x1C, 0x2C, 0x9F, 0x41, 0x9D, 0x9F },\n    { 0x57, 0xED, 0xF4, 0xA2, 0x2B, 0xE3, 0xC9, 0x55,\n      0xAC, 0x49, 0xDA, 0x2E, 0x21, 0x07, 0xB6, 0x7A }\n};\n\n/*\n * Checkup routine\n */\nint mbedtls_md5_self_test( int verbose )\n{\n    int i, ret = 0;\n    unsigned char md5sum[16];\n\n    for( i = 0; i < 7; i++ )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"  MD5 test #%d: \", i + 1 );\n\n        ret = mbedtls_md5_ret( md5_test_buf[i], md5_test_buflen[i], md5sum );\n        if( ret != 0 )\n            goto fail;\n\n        if( memcmp( md5sum, md5_test_sum[i], 16 ) != 0 )\n        {\n            ret = 1;\n            goto fail;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    return( 0 );\n\nfail:\n    if( verbose != 0 )\n        mbedtls_printf( \"failed\\n\" );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_MD5_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/md_wrap.c",
    "content": "/**\n * \\file md_wrap.c\n *\n * \\brief Generic message digest wrapper for mbed TLS\n *\n * \\author Adriaan de Jong <dejong@fox-it.com>\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_MD_C)\n\n#include \"mbedtls/md_internal.h\"\n\n#if defined(MBEDTLS_MD2_C)\n#include \"mbedtls/md2.h\"\n#endif\n\n#if defined(MBEDTLS_MD4_C)\n#include \"mbedtls/md4.h\"\n#endif\n\n#if defined(MBEDTLS_MD5_C)\n#include \"mbedtls/md5.h\"\n#endif\n\n#if defined(MBEDTLS_RIPEMD160_C)\n#include \"mbedtls/ripemd160.h\"\n#endif\n\n#if defined(MBEDTLS_SHA1_C)\n#include \"mbedtls/sha1.h\"\n#endif\n\n#if defined(MBEDTLS_SHA256_C)\n#include \"mbedtls/sha256.h\"\n#endif\n\n#if defined(MBEDTLS_SHA512_C)\n#include \"mbedtls/sha512.h\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc    calloc\n#define mbedtls_free       free\n#endif\n\n#if defined(MBEDTLS_MD2_C)\n\nstatic int md2_starts_wrap( void *ctx )\n{\n    return( mbedtls_md2_starts_ret( (mbedtls_md2_context *) ctx ) );\n}\n\nstatic int md2_update_wrap( void *ctx, const unsigned char *input,\n                             size_t ilen )\n{\n    return( mbedtls_md2_update_ret( (mbedtls_md2_context *) ctx, input, ilen ) );\n}\n\nstatic int md2_finish_wrap( void *ctx, unsigned char *output )\n{\n    return( mbedtls_md2_finish_ret( (mbedtls_md2_context *) ctx, output ) );\n}\n\nstatic void *md2_ctx_alloc( void )\n{\n    void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_md2_context ) );\n\n    if( ctx != NULL )\n        mbedtls_md2_init( (mbedtls_md2_context *) ctx );\n\n    return( ctx );\n}\n\nstatic void md2_ctx_free( void *ctx )\n{\n    mbedtls_md2_free( (mbedtls_md2_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic void md2_clone_wrap( void *dst, const void *src )\n{\n    mbedtls_md2_clone( (mbedtls_md2_context *) dst,\n                 (const mbedtls_md2_context *) src );\n}\n\nstatic int md2_process_wrap( void *ctx, const unsigned char *data )\n{\n    ((void) data);\n\n    return( mbedtls_internal_md2_process( (mbedtls_md2_context *) ctx ) );\n}\n\nconst mbedtls_md_info_t mbedtls_md2_info = {\n    MBEDTLS_MD_MD2,\n    \"MD2\",\n    16,\n    16,\n    md2_starts_wrap,\n    md2_update_wrap,\n    md2_finish_wrap,\n    mbedtls_md2_ret,\n    md2_ctx_alloc,\n    md2_ctx_free,\n    md2_clone_wrap,\n    md2_process_wrap,\n};\n\n#endif /* MBEDTLS_MD2_C */\n\n#if defined(MBEDTLS_MD4_C)\n\nstatic int md4_starts_wrap( void *ctx )\n{\n    return( mbedtls_md4_starts_ret( (mbedtls_md4_context *) ctx ) );\n}\n\nstatic int md4_update_wrap( void *ctx, const unsigned char *input,\n                             size_t ilen )\n{\n    return( mbedtls_md4_update_ret( (mbedtls_md4_context *) ctx, input, ilen ) );\n}\n\nstatic int md4_finish_wrap( void *ctx, unsigned char *output )\n{\n    return( mbedtls_md4_finish_ret( (mbedtls_md4_context *) ctx, output ) );\n}\n\nstatic void *md4_ctx_alloc( void )\n{\n    void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_md4_context ) );\n\n    if( ctx != NULL )\n        mbedtls_md4_init( (mbedtls_md4_context *) ctx );\n\n    return( ctx );\n}\n\nstatic void md4_ctx_free( void *ctx )\n{\n    mbedtls_md4_free( (mbedtls_md4_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic void md4_clone_wrap( void *dst, const void *src )\n{\n    mbedtls_md4_clone( (mbedtls_md4_context *) dst,\n                       (const mbedtls_md4_context *) src );\n}\n\nstatic int md4_process_wrap( void *ctx, const unsigned char *data )\n{\n    return( mbedtls_internal_md4_process( (mbedtls_md4_context *) ctx, data ) );\n}\n\nconst mbedtls_md_info_t mbedtls_md4_info = {\n    MBEDTLS_MD_MD4,\n    \"MD4\",\n    16,\n    64,\n    md4_starts_wrap,\n    md4_update_wrap,\n    md4_finish_wrap,\n    mbedtls_md4_ret,\n    md4_ctx_alloc,\n    md4_ctx_free,\n    md4_clone_wrap,\n    md4_process_wrap,\n};\n\n#endif /* MBEDTLS_MD4_C */\n\n#if defined(MBEDTLS_MD5_C)\n\nstatic int md5_starts_wrap( void *ctx )\n{\n    return( mbedtls_md5_starts_ret( (mbedtls_md5_context *) ctx ) );\n}\n\nstatic int md5_update_wrap( void *ctx, const unsigned char *input,\n                             size_t ilen )\n{\n    return( mbedtls_md5_update_ret( (mbedtls_md5_context *) ctx, input, ilen ) );\n}\n\nstatic int md5_finish_wrap( void *ctx, unsigned char *output )\n{\n    return( mbedtls_md5_finish_ret( (mbedtls_md5_context *) ctx, output ) );\n}\n\nstatic void *md5_ctx_alloc( void )\n{\n    void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_md5_context ) );\n\n    if( ctx != NULL )\n        mbedtls_md5_init( (mbedtls_md5_context *) ctx );\n\n    return( ctx );\n}\n\nstatic void md5_ctx_free( void *ctx )\n{\n    mbedtls_md5_free( (mbedtls_md5_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic void md5_clone_wrap( void *dst, const void *src )\n{\n    mbedtls_md5_clone( (mbedtls_md5_context *) dst,\n                       (const mbedtls_md5_context *) src );\n}\n\nstatic int md5_process_wrap( void *ctx, const unsigned char *data )\n{\n    return( mbedtls_internal_md5_process( (mbedtls_md5_context *) ctx, data ) );\n}\n\nconst mbedtls_md_info_t mbedtls_md5_info = {\n    MBEDTLS_MD_MD5,\n    \"MD5\",\n    16,\n    64,\n    md5_starts_wrap,\n    md5_update_wrap,\n    md5_finish_wrap,\n    mbedtls_md5_ret,\n    md5_ctx_alloc,\n    md5_ctx_free,\n    md5_clone_wrap,\n    md5_process_wrap,\n};\n\n#endif /* MBEDTLS_MD5_C */\n\n#if defined(MBEDTLS_RIPEMD160_C)\n\nstatic int ripemd160_starts_wrap( void *ctx )\n{\n    return( mbedtls_ripemd160_starts_ret( (mbedtls_ripemd160_context *) ctx ) );\n}\n\nstatic int ripemd160_update_wrap( void *ctx, const unsigned char *input,\n                                   size_t ilen )\n{\n    return( mbedtls_ripemd160_update_ret( (mbedtls_ripemd160_context *) ctx,\n                                          input, ilen ) );\n}\n\nstatic int ripemd160_finish_wrap( void *ctx, unsigned char *output )\n{\n    return( mbedtls_ripemd160_finish_ret( (mbedtls_ripemd160_context *) ctx,\n                                          output ) );\n}\n\nstatic void *ripemd160_ctx_alloc( void )\n{\n    void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ripemd160_context ) );\n\n    if( ctx != NULL )\n        mbedtls_ripemd160_init( (mbedtls_ripemd160_context *) ctx );\n\n    return( ctx );\n}\n\nstatic void ripemd160_ctx_free( void *ctx )\n{\n    mbedtls_ripemd160_free( (mbedtls_ripemd160_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic void ripemd160_clone_wrap( void *dst, const void *src )\n{\n    mbedtls_ripemd160_clone( (mbedtls_ripemd160_context *) dst,\n                       (const mbedtls_ripemd160_context *) src );\n}\n\nstatic int ripemd160_process_wrap( void *ctx, const unsigned char *data )\n{\n    return( mbedtls_internal_ripemd160_process(\n                                (mbedtls_ripemd160_context *) ctx, data ) );\n}\n\nconst mbedtls_md_info_t mbedtls_ripemd160_info = {\n    MBEDTLS_MD_RIPEMD160,\n    \"RIPEMD160\",\n    20,\n    64,\n    ripemd160_starts_wrap,\n    ripemd160_update_wrap,\n    ripemd160_finish_wrap,\n    mbedtls_ripemd160_ret,\n    ripemd160_ctx_alloc,\n    ripemd160_ctx_free,\n    ripemd160_clone_wrap,\n    ripemd160_process_wrap,\n};\n\n#endif /* MBEDTLS_RIPEMD160_C */\n\n#if defined(MBEDTLS_SHA1_C)\n\nstatic int sha1_starts_wrap( void *ctx )\n{\n    return( mbedtls_sha1_starts_ret( (mbedtls_sha1_context *) ctx ) );\n}\n\nstatic int sha1_update_wrap( void *ctx, const unsigned char *input,\n                              size_t ilen )\n{\n    return( mbedtls_sha1_update_ret( (mbedtls_sha1_context *) ctx,\n                                     input, ilen ) );\n}\n\nstatic int sha1_finish_wrap( void *ctx, unsigned char *output )\n{\n    return( mbedtls_sha1_finish_ret( (mbedtls_sha1_context *) ctx, output ) );\n}\n\nstatic void *sha1_ctx_alloc( void )\n{\n    void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_sha1_context ) );\n\n    if( ctx != NULL )\n        mbedtls_sha1_init( (mbedtls_sha1_context *) ctx );\n\n    return( ctx );\n}\n\nstatic void sha1_clone_wrap( void *dst, const void *src )\n{\n    mbedtls_sha1_clone( (mbedtls_sha1_context *) dst,\n                  (const mbedtls_sha1_context *) src );\n}\n\nstatic void sha1_ctx_free( void *ctx )\n{\n    mbedtls_sha1_free( (mbedtls_sha1_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic int sha1_process_wrap( void *ctx, const unsigned char *data )\n{\n    return( mbedtls_internal_sha1_process( (mbedtls_sha1_context *) ctx,\n                                           data ) );\n}\n\nconst mbedtls_md_info_t mbedtls_sha1_info = {\n    MBEDTLS_MD_SHA1,\n    \"SHA1\",\n    20,\n    64,\n    sha1_starts_wrap,\n    sha1_update_wrap,\n    sha1_finish_wrap,\n    mbedtls_sha1_ret,\n    sha1_ctx_alloc,\n    sha1_ctx_free,\n    sha1_clone_wrap,\n    sha1_process_wrap,\n};\n\n#endif /* MBEDTLS_SHA1_C */\n\n/*\n * Wrappers for generic message digests\n */\n#if defined(MBEDTLS_SHA256_C)\n\nstatic int sha224_starts_wrap( void *ctx )\n{\n    return( mbedtls_sha256_starts_ret( (mbedtls_sha256_context *) ctx, 1 ) );\n}\n\nstatic int sha224_update_wrap( void *ctx, const unsigned char *input,\n                                size_t ilen )\n{\n    return( mbedtls_sha256_update_ret( (mbedtls_sha256_context *) ctx,\n                                       input, ilen ) );\n}\n\nstatic int sha224_finish_wrap( void *ctx, unsigned char *output )\n{\n    return( mbedtls_sha256_finish_ret( (mbedtls_sha256_context *) ctx,\n                                       output ) );\n}\n\nstatic int sha224_wrap( const unsigned char *input, size_t ilen,\n                        unsigned char *output )\n{\n    return( mbedtls_sha256_ret( input, ilen, output, 1 ) );\n}\n\nstatic void *sha224_ctx_alloc( void )\n{\n    void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_sha256_context ) );\n\n    if( ctx != NULL )\n        mbedtls_sha256_init( (mbedtls_sha256_context *) ctx );\n\n    return( ctx );\n}\n\nstatic void sha224_ctx_free( void *ctx )\n{\n    mbedtls_sha256_free( (mbedtls_sha256_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic void sha224_clone_wrap( void *dst, const void *src )\n{\n    mbedtls_sha256_clone( (mbedtls_sha256_context *) dst,\n                    (const mbedtls_sha256_context *) src );\n}\n\nstatic int sha224_process_wrap( void *ctx, const unsigned char *data )\n{\n    return( mbedtls_internal_sha256_process( (mbedtls_sha256_context *) ctx,\n                                             data ) );\n}\n\nconst mbedtls_md_info_t mbedtls_sha224_info = {\n    MBEDTLS_MD_SHA224,\n    \"SHA224\",\n    28,\n    64,\n    sha224_starts_wrap,\n    sha224_update_wrap,\n    sha224_finish_wrap,\n    sha224_wrap,\n    sha224_ctx_alloc,\n    sha224_ctx_free,\n    sha224_clone_wrap,\n    sha224_process_wrap,\n};\n\nstatic int sha256_starts_wrap( void *ctx )\n{\n    return( mbedtls_sha256_starts_ret( (mbedtls_sha256_context *) ctx, 0 ) );\n}\n\nstatic int sha256_wrap( const unsigned char *input, size_t ilen,\n                        unsigned char *output )\n{\n    return( mbedtls_sha256_ret( input, ilen, output, 0 ) );\n}\n\nconst mbedtls_md_info_t mbedtls_sha256_info = {\n    MBEDTLS_MD_SHA256,\n    \"SHA256\",\n    32,\n    64,\n    sha256_starts_wrap,\n    sha224_update_wrap,\n    sha224_finish_wrap,\n    sha256_wrap,\n    sha224_ctx_alloc,\n    sha224_ctx_free,\n    sha224_clone_wrap,\n    sha224_process_wrap,\n};\n\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n\nstatic int sha384_starts_wrap( void *ctx )\n{\n    return( mbedtls_sha512_starts_ret( (mbedtls_sha512_context *) ctx, 1 ) );\n}\n\nstatic int sha384_update_wrap( void *ctx, const unsigned char *input,\n                               size_t ilen )\n{\n    return( mbedtls_sha512_update_ret( (mbedtls_sha512_context *) ctx,\n                                       input, ilen ) );\n}\n\nstatic int sha384_finish_wrap( void *ctx, unsigned char *output )\n{\n    return( mbedtls_sha512_finish_ret( (mbedtls_sha512_context *) ctx,\n                                       output ) );\n}\n\nstatic int sha384_wrap( const unsigned char *input, size_t ilen,\n                        unsigned char *output )\n{\n    return( mbedtls_sha512_ret( input, ilen, output, 1 ) );\n}\n\nstatic void *sha384_ctx_alloc( void )\n{\n    void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_sha512_context ) );\n\n    if( ctx != NULL )\n        mbedtls_sha512_init( (mbedtls_sha512_context *) ctx );\n\n    return( ctx );\n}\n\nstatic void sha384_ctx_free( void *ctx )\n{\n    mbedtls_sha512_free( (mbedtls_sha512_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic void sha384_clone_wrap( void *dst, const void *src )\n{\n    mbedtls_sha512_clone( (mbedtls_sha512_context *) dst,\n                    (const mbedtls_sha512_context *) src );\n}\n\nstatic int sha384_process_wrap( void *ctx, const unsigned char *data )\n{\n    return( mbedtls_internal_sha512_process( (mbedtls_sha512_context *) ctx,\n                                             data ) );\n}\n\nconst mbedtls_md_info_t mbedtls_sha384_info = {\n    MBEDTLS_MD_SHA384,\n    \"SHA384\",\n    48,\n    128,\n    sha384_starts_wrap,\n    sha384_update_wrap,\n    sha384_finish_wrap,\n    sha384_wrap,\n    sha384_ctx_alloc,\n    sha384_ctx_free,\n    sha384_clone_wrap,\n    sha384_process_wrap,\n};\n\nstatic int sha512_starts_wrap( void *ctx )\n{\n    return( mbedtls_sha512_starts_ret( (mbedtls_sha512_context *) ctx, 0 ) );\n}\n\nstatic int sha512_wrap( const unsigned char *input, size_t ilen,\n                        unsigned char *output )\n{\n    return( mbedtls_sha512_ret( input, ilen, output, 0 ) );\n}\n\nconst mbedtls_md_info_t mbedtls_sha512_info = {\n    MBEDTLS_MD_SHA512,\n    \"SHA512\",\n    64,\n    128,\n    sha512_starts_wrap,\n    sha384_update_wrap,\n    sha384_finish_wrap,\n    sha512_wrap,\n    sha384_ctx_alloc,\n    sha384_ctx_free,\n    sha384_clone_wrap,\n    sha384_process_wrap,\n};\n\n#endif /* MBEDTLS_SHA512_C */\n\n#endif /* MBEDTLS_MD_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/memory_buffer_alloc.c",
    "content": "/*\n *  Buffer-based memory allocator\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)\n#include \"mbedtls/memory_buffer_alloc.h\"\n\n/* No need for the header guard as MBEDTLS_MEMORY_BUFFER_ALLOC_C\n   is dependent upon MBEDTLS_PLATFORM_C */\n#include \"mbedtls/platform.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_MEMORY_BACKTRACE)\n#include <execinfo.h>\n#endif\n\n#if defined(MBEDTLS_THREADING_C)\n#include \"mbedtls/threading.h\"\n#endif\n\n#define MAGIC1       0xFF00AA55\n#define MAGIC2       0xEE119966\n#define MAX_BT 20\n\ntypedef struct _memory_header memory_header;\nstruct _memory_header\n{\n    size_t          magic1;\n    size_t          size;\n    size_t          alloc;\n    memory_header   *prev;\n    memory_header   *next;\n    memory_header   *prev_free;\n    memory_header   *next_free;\n#if defined(MBEDTLS_MEMORY_BACKTRACE)\n    char            **trace;\n    size_t          trace_count;\n#endif\n    size_t          magic2;\n};\n\ntypedef struct\n{\n    unsigned char   *buf;\n    size_t          len;\n    memory_header   *first;\n    memory_header   *first_free;\n    int             verify;\n#if defined(MBEDTLS_MEMORY_DEBUG)\n    size_t          alloc_count;\n    size_t          free_count;\n    size_t          total_used;\n    size_t          maximum_used;\n    size_t          header_count;\n    size_t          maximum_header_count;\n#endif\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_threading_mutex_t   mutex;\n#endif\n}\nbuffer_alloc_ctx;\n\nstatic buffer_alloc_ctx heap;\n\n#if defined(MBEDTLS_MEMORY_DEBUG)\nstatic void debug_header( memory_header *hdr )\n{\n#if defined(MBEDTLS_MEMORY_BACKTRACE)\n    size_t i;\n#endif\n\n    mbedtls_fprintf( stderr, \"HDR:  PTR(%10zu), PREV(%10zu), NEXT(%10zu), \"\n                              \"ALLOC(%zu), SIZE(%10zu)\\n\",\n                      (size_t) hdr, (size_t) hdr->prev, (size_t) hdr->next,\n                      hdr->alloc, hdr->size );\n    mbedtls_fprintf( stderr, \"      FPREV(%10zu), FNEXT(%10zu)\\n\",\n                      (size_t) hdr->prev_free, (size_t) hdr->next_free );\n\n#if defined(MBEDTLS_MEMORY_BACKTRACE)\n    mbedtls_fprintf( stderr, \"TRACE: \\n\" );\n    for( i = 0; i < hdr->trace_count; i++ )\n        mbedtls_fprintf( stderr, \"%s\\n\", hdr->trace[i] );\n    mbedtls_fprintf( stderr, \"\\n\" );\n#endif\n}\n\nstatic void debug_chain( void )\n{\n    memory_header *cur = heap.first;\n\n    mbedtls_fprintf( stderr, \"\\nBlock list\\n\" );\n    while( cur != NULL )\n    {\n        debug_header( cur );\n        cur = cur->next;\n    }\n\n    mbedtls_fprintf( stderr, \"Free list\\n\" );\n    cur = heap.first_free;\n\n    while( cur != NULL )\n    {\n        debug_header( cur );\n        cur = cur->next_free;\n    }\n}\n#endif /* MBEDTLS_MEMORY_DEBUG */\n\nstatic int verify_header( memory_header *hdr )\n{\n    if( hdr->magic1 != MAGIC1 )\n    {\n#if defined(MBEDTLS_MEMORY_DEBUG)\n        mbedtls_fprintf( stderr, \"FATAL: MAGIC1 mismatch\\n\" );\n#endif\n        return( 1 );\n    }\n\n    if( hdr->magic2 != MAGIC2 )\n    {\n#if defined(MBEDTLS_MEMORY_DEBUG)\n        mbedtls_fprintf( stderr, \"FATAL: MAGIC2 mismatch\\n\" );\n#endif\n        return( 1 );\n    }\n\n    if( hdr->alloc > 1 )\n    {\n#if defined(MBEDTLS_MEMORY_DEBUG)\n        mbedtls_fprintf( stderr, \"FATAL: alloc has illegal value\\n\" );\n#endif\n        return( 1 );\n    }\n\n    if( hdr->prev != NULL && hdr->prev == hdr->next )\n    {\n#if defined(MBEDTLS_MEMORY_DEBUG)\n        mbedtls_fprintf( stderr, \"FATAL: prev == next\\n\" );\n#endif\n        return( 1 );\n    }\n\n    if( hdr->prev_free != NULL && hdr->prev_free == hdr->next_free )\n    {\n#if defined(MBEDTLS_MEMORY_DEBUG)\n        mbedtls_fprintf( stderr, \"FATAL: prev_free == next_free\\n\" );\n#endif\n        return( 1 );\n    }\n\n    return( 0 );\n}\n\nstatic int verify_chain( void )\n{\n    memory_header *prv = heap.first, *cur;\n\n    if( prv == NULL || verify_header( prv ) != 0 )\n    {\n#if defined(MBEDTLS_MEMORY_DEBUG)\n        mbedtls_fprintf( stderr, \"FATAL: verification of first header \"\n                                  \"failed\\n\" );\n#endif\n        return( 1 );\n    }\n\n    if( heap.first->prev != NULL )\n    {\n#if defined(MBEDTLS_MEMORY_DEBUG)\n        mbedtls_fprintf( stderr, \"FATAL: verification failed: \"\n                                  \"first->prev != NULL\\n\" );\n#endif\n        return( 1 );\n    }\n\n    cur = heap.first->next;\n\n    while( cur != NULL )\n    {\n        if( verify_header( cur ) != 0 )\n        {\n#if defined(MBEDTLS_MEMORY_DEBUG)\n            mbedtls_fprintf( stderr, \"FATAL: verification of header \"\n                                      \"failed\\n\" );\n#endif\n            return( 1 );\n        }\n\n        if( cur->prev != prv )\n        {\n#if defined(MBEDTLS_MEMORY_DEBUG)\n            mbedtls_fprintf( stderr, \"FATAL: verification failed: \"\n                                      \"cur->prev != prv\\n\" );\n#endif\n            return( 1 );\n        }\n\n        prv = cur;\n        cur = cur->next;\n    }\n\n    return( 0 );\n}\n\nstatic void *buffer_alloc_calloc( size_t n, size_t size )\n{\n    memory_header *new, *cur = heap.first_free;\n    unsigned char *p;\n    void *ret;\n    size_t original_len, len;\n#if defined(MBEDTLS_MEMORY_BACKTRACE)\n    void *trace_buffer[MAX_BT];\n    size_t trace_cnt;\n#endif\n\n    if( heap.buf == NULL || heap.first == NULL )\n        return( NULL );\n\n    original_len = len = n * size;\n\n    if( n == 0 || size == 0 || len / n != size )\n        return( NULL );\n    else if( len > (size_t)-MBEDTLS_MEMORY_ALIGN_MULTIPLE )\n        return( NULL );\n\n    if( len % MBEDTLS_MEMORY_ALIGN_MULTIPLE )\n    {\n        len -= len % MBEDTLS_MEMORY_ALIGN_MULTIPLE;\n        len += MBEDTLS_MEMORY_ALIGN_MULTIPLE;\n    }\n\n    // Find block that fits\n    //\n    while( cur != NULL )\n    {\n        if( cur->size >= len )\n            break;\n\n        cur = cur->next_free;\n    }\n\n    if( cur == NULL )\n        return( NULL );\n\n    if( cur->alloc != 0 )\n    {\n#if defined(MBEDTLS_MEMORY_DEBUG)\n        mbedtls_fprintf( stderr, \"FATAL: block in free_list but allocated \"\n                                  \"data\\n\" );\n#endif\n        mbedtls_exit( 1 );\n    }\n\n#if defined(MBEDTLS_MEMORY_DEBUG)\n    heap.alloc_count++;\n#endif\n\n    // Found location, split block if > memory_header + 4 room left\n    //\n    if( cur->size - len < sizeof(memory_header) +\n                          MBEDTLS_MEMORY_ALIGN_MULTIPLE )\n    {\n        cur->alloc = 1;\n\n        // Remove from free_list\n        //\n        if( cur->prev_free != NULL )\n            cur->prev_free->next_free = cur->next_free;\n        else\n            heap.first_free = cur->next_free;\n\n        if( cur->next_free != NULL )\n            cur->next_free->prev_free = cur->prev_free;\n\n        cur->prev_free = NULL;\n        cur->next_free = NULL;\n\n#if defined(MBEDTLS_MEMORY_DEBUG)\n        heap.total_used += cur->size;\n        if( heap.total_used > heap.maximum_used )\n            heap.maximum_used = heap.total_used;\n#endif\n#if defined(MBEDTLS_MEMORY_BACKTRACE)\n        trace_cnt = backtrace( trace_buffer, MAX_BT );\n        cur->trace = backtrace_symbols( trace_buffer, trace_cnt );\n        cur->trace_count = trace_cnt;\n#endif\n\n        if( ( heap.verify & MBEDTLS_MEMORY_VERIFY_ALLOC ) && verify_chain() != 0 )\n            mbedtls_exit( 1 );\n\n        ret = (unsigned char *) cur + sizeof( memory_header );\n        memset( ret, 0, original_len );\n\n        return( ret );\n    }\n\n    p = ( (unsigned char *) cur ) + sizeof(memory_header) + len;\n    new = (memory_header *) p;\n\n    new->size = cur->size - len - sizeof(memory_header);\n    new->alloc = 0;\n    new->prev = cur;\n    new->next = cur->next;\n#if defined(MBEDTLS_MEMORY_BACKTRACE)\n    new->trace = NULL;\n    new->trace_count = 0;\n#endif\n    new->magic1 = MAGIC1;\n    new->magic2 = MAGIC2;\n\n    if( new->next != NULL )\n        new->next->prev = new;\n\n    // Replace cur with new in free_list\n    //\n    new->prev_free = cur->prev_free;\n    new->next_free = cur->next_free;\n    if( new->prev_free != NULL )\n        new->prev_free->next_free = new;\n    else\n        heap.first_free = new;\n\n    if( new->next_free != NULL )\n        new->next_free->prev_free = new;\n\n    cur->alloc = 1;\n    cur->size = len;\n    cur->next = new;\n    cur->prev_free = NULL;\n    cur->next_free = NULL;\n\n#if defined(MBEDTLS_MEMORY_DEBUG)\n    heap.header_count++;\n    if( heap.header_count > heap.maximum_header_count )\n        heap.maximum_header_count = heap.header_count;\n    heap.total_used += cur->size;\n    if( heap.total_used > heap.maximum_used )\n        heap.maximum_used = heap.total_used;\n#endif\n#if defined(MBEDTLS_MEMORY_BACKTRACE)\n    trace_cnt = backtrace( trace_buffer, MAX_BT );\n    cur->trace = backtrace_symbols( trace_buffer, trace_cnt );\n    cur->trace_count = trace_cnt;\n#endif\n\n    if( ( heap.verify & MBEDTLS_MEMORY_VERIFY_ALLOC ) && verify_chain() != 0 )\n        mbedtls_exit( 1 );\n\n    ret = (unsigned char *) cur + sizeof( memory_header );\n    memset( ret, 0, original_len );\n\n    return( ret );\n}\n\nstatic void buffer_alloc_free( void *ptr )\n{\n    memory_header *hdr, *old = NULL;\n    unsigned char *p = (unsigned char *) ptr;\n\n    if( ptr == NULL || heap.buf == NULL || heap.first == NULL )\n        return;\n\n    if( p < heap.buf || p >= heap.buf + heap.len )\n    {\n#if defined(MBEDTLS_MEMORY_DEBUG)\n        mbedtls_fprintf( stderr, \"FATAL: mbedtls_free() outside of managed \"\n                                  \"space\\n\" );\n#endif\n        mbedtls_exit( 1 );\n    }\n\n    p -= sizeof(memory_header);\n    hdr = (memory_header *) p;\n\n    if( verify_header( hdr ) != 0 )\n        mbedtls_exit( 1 );\n\n    if( hdr->alloc != 1 )\n    {\n#if defined(MBEDTLS_MEMORY_DEBUG)\n        mbedtls_fprintf( stderr, \"FATAL: mbedtls_free() on unallocated \"\n                                  \"data\\n\" );\n#endif\n        mbedtls_exit( 1 );\n    }\n\n    hdr->alloc = 0;\n\n#if defined(MBEDTLS_MEMORY_DEBUG)\n    heap.free_count++;\n    heap.total_used -= hdr->size;\n#endif\n\n#if defined(MBEDTLS_MEMORY_BACKTRACE)\n    free( hdr->trace );\n    hdr->trace = NULL;\n    hdr->trace_count = 0;\n#endif\n\n    // Regroup with block before\n    //\n    if( hdr->prev != NULL && hdr->prev->alloc == 0 )\n    {\n#if defined(MBEDTLS_MEMORY_DEBUG)\n        heap.header_count--;\n#endif\n        hdr->prev->size += sizeof(memory_header) + hdr->size;\n        hdr->prev->next = hdr->next;\n        old = hdr;\n        hdr = hdr->prev;\n\n        if( hdr->next != NULL )\n            hdr->next->prev = hdr;\n\n        memset( old, 0, sizeof(memory_header) );\n    }\n\n    // Regroup with block after\n    //\n    if( hdr->next != NULL && hdr->next->alloc == 0 )\n    {\n#if defined(MBEDTLS_MEMORY_DEBUG)\n        heap.header_count--;\n#endif\n        hdr->size += sizeof(memory_header) + hdr->next->size;\n        old = hdr->next;\n        hdr->next = hdr->next->next;\n\n        if( hdr->prev_free != NULL || hdr->next_free != NULL )\n        {\n            if( hdr->prev_free != NULL )\n                hdr->prev_free->next_free = hdr->next_free;\n            else\n                heap.first_free = hdr->next_free;\n\n            if( hdr->next_free != NULL )\n                hdr->next_free->prev_free = hdr->prev_free;\n        }\n\n        hdr->prev_free = old->prev_free;\n        hdr->next_free = old->next_free;\n\n        if( hdr->prev_free != NULL )\n            hdr->prev_free->next_free = hdr;\n        else\n            heap.first_free = hdr;\n\n        if( hdr->next_free != NULL )\n            hdr->next_free->prev_free = hdr;\n\n        if( hdr->next != NULL )\n            hdr->next->prev = hdr;\n\n        memset( old, 0, sizeof(memory_header) );\n    }\n\n    // Prepend to free_list if we have not merged\n    // (Does not have to stay in same order as prev / next list)\n    //\n    if( old == NULL )\n    {\n        hdr->next_free = heap.first_free;\n        if( heap.first_free != NULL )\n            heap.first_free->prev_free = hdr;\n        heap.first_free = hdr;\n    }\n\n    if( ( heap.verify & MBEDTLS_MEMORY_VERIFY_FREE ) && verify_chain() != 0 )\n        mbedtls_exit( 1 );\n}\n\nvoid mbedtls_memory_buffer_set_verify( int verify )\n{\n    heap.verify = verify;\n}\n\nint mbedtls_memory_buffer_alloc_verify( void )\n{\n    return verify_chain();\n}\n\n#if defined(MBEDTLS_MEMORY_DEBUG)\nvoid mbedtls_memory_buffer_alloc_status( void )\n{\n    mbedtls_fprintf( stderr,\n                      \"Current use: %zu blocks / %zu bytes, max: %zu blocks / \"\n                      \"%zu bytes (total %zu bytes), alloc / free: %zu / %zu\\n\",\n                      heap.header_count, heap.total_used,\n                      heap.maximum_header_count, heap.maximum_used,\n                      heap.maximum_header_count * sizeof( memory_header )\n                      + heap.maximum_used,\n                      heap.alloc_count, heap.free_count );\n\n    if( heap.first->next == NULL )\n    {\n        mbedtls_fprintf( stderr, \"All memory de-allocated in stack buffer\\n\" );\n    }\n    else\n    {\n        mbedtls_fprintf( stderr, \"Memory currently allocated:\\n\" );\n        debug_chain();\n    }\n}\n\nvoid mbedtls_memory_buffer_alloc_max_get( size_t *max_used, size_t *max_blocks )\n{\n    *max_used   = heap.maximum_used;\n    *max_blocks = heap.maximum_header_count;\n}\n\nvoid mbedtls_memory_buffer_alloc_max_reset( void )\n{\n    heap.maximum_used = 0;\n    heap.maximum_header_count = 0;\n}\n\nvoid mbedtls_memory_buffer_alloc_cur_get( size_t *cur_used, size_t *cur_blocks )\n{\n    *cur_used   = heap.total_used;\n    *cur_blocks = heap.header_count;\n}\n#endif /* MBEDTLS_MEMORY_DEBUG */\n\n#if defined(MBEDTLS_THREADING_C)\nstatic void *buffer_alloc_calloc_mutexed( size_t n, size_t size )\n{\n    void *buf;\n    if( mbedtls_mutex_lock( &heap.mutex ) != 0 )\n        return( NULL );\n    buf = buffer_alloc_calloc( n, size );\n    if( mbedtls_mutex_unlock( &heap.mutex ) )\n        return( NULL );\n    return( buf );\n}\n\nstatic void buffer_alloc_free_mutexed( void *ptr )\n{\n    /* We have to good option here, but corrupting the heap seems\n     * worse than loosing memory. */\n    if( mbedtls_mutex_lock( &heap.mutex ) )\n        return;\n    buffer_alloc_free( ptr );\n    (void) mbedtls_mutex_unlock( &heap.mutex );\n}\n#endif /* MBEDTLS_THREADING_C */\n\nvoid mbedtls_memory_buffer_alloc_init( unsigned char *buf, size_t len )\n{\n    memset( &heap, 0, sizeof( buffer_alloc_ctx ) );\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_mutex_init( &heap.mutex );\n    mbedtls_platform_set_calloc_free( buffer_alloc_calloc_mutexed,\n                              buffer_alloc_free_mutexed );\n#else\n    mbedtls_platform_set_calloc_free( buffer_alloc_calloc, buffer_alloc_free );\n#endif\n\n    if( len < sizeof( memory_header ) + MBEDTLS_MEMORY_ALIGN_MULTIPLE )\n        return;\n    else if( (size_t)buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE )\n    {\n        /* Adjust len first since buf is used in the computation */\n        len -= MBEDTLS_MEMORY_ALIGN_MULTIPLE\n             - (size_t)buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE;\n        buf += MBEDTLS_MEMORY_ALIGN_MULTIPLE\n             - (size_t)buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE;\n    }\n\n    memset( buf, 0, len );\n\n    heap.buf = buf;\n    heap.len = len;\n\n    heap.first = (memory_header *)buf;\n    heap.first->size = len - sizeof( memory_header );\n    heap.first->magic1 = MAGIC1;\n    heap.first->magic2 = MAGIC2;\n    heap.first_free = heap.first;\n}\n\nvoid mbedtls_memory_buffer_alloc_free( void )\n{\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_mutex_free( &heap.mutex );\n#endif\n    mbedtls_platform_zeroize( &heap, sizeof(buffer_alloc_ctx) );\n}\n\n#if defined(MBEDTLS_SELF_TEST)\nstatic int check_pointer( void *p )\n{\n    if( p == NULL )\n        return( -1 );\n\n    if( (size_t) p % MBEDTLS_MEMORY_ALIGN_MULTIPLE != 0 )\n        return( -1 );\n\n    return( 0 );\n}\n\nstatic int check_all_free( void )\n{\n    if(\n#if defined(MBEDTLS_MEMORY_DEBUG)\n        heap.total_used != 0 ||\n#endif\n        heap.first != heap.first_free ||\n        (void *) heap.first != (void *) heap.buf )\n    {\n        return( -1 );\n    }\n\n    return( 0 );\n}\n\n#define TEST_ASSERT( condition )            \\\n    if( ! (condition) )                     \\\n    {                                       \\\n        if( verbose != 0 )                  \\\n            mbedtls_printf( \"failed\\n\" );  \\\n                                            \\\n        ret = 1;                            \\\n        goto cleanup;                       \\\n    }\n\nint mbedtls_memory_buffer_alloc_self_test( int verbose )\n{\n    unsigned char buf[1024];\n    unsigned char *p, *q, *r, *end;\n    int ret = 0;\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  MBA test #1 (basic alloc-free cycle): \" );\n\n    mbedtls_memory_buffer_alloc_init( buf, sizeof( buf ) );\n\n    p = mbedtls_calloc( 1, 1 );\n    q = mbedtls_calloc( 1, 128 );\n    r = mbedtls_calloc( 1, 16 );\n\n    TEST_ASSERT( check_pointer( p ) == 0 &&\n                 check_pointer( q ) == 0 &&\n                 check_pointer( r ) == 0 );\n\n    mbedtls_free( r );\n    mbedtls_free( q );\n    mbedtls_free( p );\n\n    TEST_ASSERT( check_all_free( ) == 0 );\n\n    /* Memorize end to compare with the next test */\n    end = heap.buf + heap.len;\n\n    mbedtls_memory_buffer_alloc_free( );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  MBA test #2 (buf not aligned): \" );\n\n    mbedtls_memory_buffer_alloc_init( buf + 1, sizeof( buf ) - 1 );\n\n    TEST_ASSERT( heap.buf + heap.len == end );\n\n    p = mbedtls_calloc( 1, 1 );\n    q = mbedtls_calloc( 1, 128 );\n    r = mbedtls_calloc( 1, 16 );\n\n    TEST_ASSERT( check_pointer( p ) == 0 &&\n                 check_pointer( q ) == 0 &&\n                 check_pointer( r ) == 0 );\n\n    mbedtls_free( r );\n    mbedtls_free( q );\n    mbedtls_free( p );\n\n    TEST_ASSERT( check_all_free( ) == 0 );\n\n    mbedtls_memory_buffer_alloc_free( );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  MBA test #3 (full): \" );\n\n    mbedtls_memory_buffer_alloc_init( buf, sizeof( buf ) );\n\n    p = mbedtls_calloc( 1, sizeof( buf ) - sizeof( memory_header ) );\n\n    TEST_ASSERT( check_pointer( p ) == 0 );\n    TEST_ASSERT( mbedtls_calloc( 1, 1 ) == NULL );\n\n    mbedtls_free( p );\n\n    p = mbedtls_calloc( 1, sizeof( buf ) - 2 * sizeof( memory_header ) - 16 );\n    q = mbedtls_calloc( 1, 16 );\n\n    TEST_ASSERT( check_pointer( p ) == 0 && check_pointer( q ) == 0 );\n    TEST_ASSERT( mbedtls_calloc( 1, 1 ) == NULL );\n\n    mbedtls_free( q );\n\n    TEST_ASSERT( mbedtls_calloc( 1, 17 ) == NULL );\n\n    mbedtls_free( p );\n\n    TEST_ASSERT( check_all_free( ) == 0 );\n\n    mbedtls_memory_buffer_alloc_free( );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\ncleanup:\n    mbedtls_memory_buffer_alloc_free( );\n\n    return( ret );\n}\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_MEMORY_BUFFER_ALLOC_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/net_sockets.c",
    "content": "/*\n *  TCP/IP or UDP/IP networking functions\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n/* Enable definition of getaddrinfo() even when compiling with -std=c99. Must\n * be set before config.h, which pulls in glibc's features.h indirectly.\n * Harmless on other platforms. */\n#define _POSIX_C_SOURCE 200112L\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_NET_C)\n\n#if !defined(unix) && !defined(__unix__) && !defined(__unix) && \\\n    !defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) && \\\n    !defined(__HAIKU__)\n#error \"This module only works on Unix and Windows, see MBEDTLS_NET_C in config.h\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#endif\n\n#include \"mbedtls/net_sockets.h\"\n\n#include <string.h>\n\n#if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \\\n    !defined(EFI32)\n\n#define IS_EINTR( ret ) ( ( ret ) == WSAEINTR )\n\n#if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0501)\n#undef _WIN32_WINNT\n/* Enables getaddrinfo() & Co */\n#define _WIN32_WINNT 0x0501\n#endif\n\n#include <ws2tcpip.h>\n\n#include <winsock2.h>\n#include <windows.h>\n\n#if defined(_MSC_VER)\n#if defined(_WIN32_WCE)\n#pragma comment( lib, \"ws2.lib\" )\n#else\n#pragma comment( lib, \"ws2_32.lib\" )\n#endif\n#endif /* _MSC_VER */\n\n#define read(fd,buf,len)        recv( fd, (char*)( buf ), (int)( len ), 0 )\n#define write(fd,buf,len)       send( fd, (char*)( buf ), (int)( len ), 0 )\n#define close(fd)               closesocket(fd)\n\nstatic int wsa_init_done = 0;\n\n#else /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */\n\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <sys/time.h>\n#include <unistd.h>\n#include <signal.h>\n#include <fcntl.h>\n#include <netdb.h>\n#include <errno.h>\n\n#define IS_EINTR( ret ) ( ( ret ) == EINTR )\n\n#endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */\n\n/* Some MS functions want int and MSVC warns if we pass size_t,\n * but the standard functions use socklen_t, so cast only for MSVC */\n#if defined(_MSC_VER)\n#define MSVC_INT_CAST   (int)\n#else\n#define MSVC_INT_CAST\n#endif\n\n#include <stdio.h>\n\n#include <time.h>\n\n#include <stdint.h>\n\n/*\n * Prepare for using the sockets interface\n */\nstatic int net_prepare( void )\n{\n#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \\\n    !defined(EFI32)\n    WSADATA wsaData;\n\n    if( wsa_init_done == 0 )\n    {\n        if( WSAStartup( MAKEWORD(2,0), &wsaData ) != 0 )\n            return( MBEDTLS_ERR_NET_SOCKET_FAILED );\n\n        wsa_init_done = 1;\n    }\n#else\n#if !defined(EFIX64) && !defined(EFI32)\n    signal( SIGPIPE, SIG_IGN );\n#endif\n#endif\n    return( 0 );\n}\n\n/*\n * Initialize a context\n */\nvoid mbedtls_net_init( mbedtls_net_context *ctx )\n{\n    ctx->fd = -1;\n}\n\n/*\n * Initiate a TCP connection with host:port and the given protocol\n */\nint mbedtls_net_connect( mbedtls_net_context *ctx, const char *host,\n                         const char *port, int proto )\n{\n    int ret;\n    struct addrinfo hints, *addr_list, *cur;\n\n    if( ( ret = net_prepare() ) != 0 )\n        return( ret );\n\n    /* Do name resolution with both IPv6 and IPv4 */\n    memset( &hints, 0, sizeof( hints ) );\n    hints.ai_family = AF_UNSPEC;\n    hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;\n    hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;\n\n    if( getaddrinfo( host, port, &hints, &addr_list ) != 0 )\n        return( MBEDTLS_ERR_NET_UNKNOWN_HOST );\n\n    /* Try the sockaddrs until a connection succeeds */\n    ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;\n    for( cur = addr_list; cur != NULL; cur = cur->ai_next )\n    {\n        ctx->fd = (int) socket( cur->ai_family, cur->ai_socktype,\n                            cur->ai_protocol );\n        if( ctx->fd < 0 )\n        {\n            ret = MBEDTLS_ERR_NET_SOCKET_FAILED;\n            continue;\n        }\n\n        if( connect( ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen ) == 0 )\n        {\n            ret = 0;\n            break;\n        }\n\n        close( ctx->fd );\n        ret = MBEDTLS_ERR_NET_CONNECT_FAILED;\n    }\n\n    freeaddrinfo( addr_list );\n\n    return( ret );\n}\n\n/*\n * Create a listening socket on bind_ip:port\n */\nint mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto )\n{\n    int n, ret;\n    struct addrinfo hints, *addr_list, *cur;\n\n    if( ( ret = net_prepare() ) != 0 )\n        return( ret );\n\n    /* Bind to IPv6 and/or IPv4, but only in the desired protocol */\n    memset( &hints, 0, sizeof( hints ) );\n    hints.ai_family = AF_UNSPEC;\n    hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;\n    hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;\n    if( bind_ip == NULL )\n        hints.ai_flags = AI_PASSIVE;\n\n    if( getaddrinfo( bind_ip, port, &hints, &addr_list ) != 0 )\n        return( MBEDTLS_ERR_NET_UNKNOWN_HOST );\n\n    /* Try the sockaddrs until a binding succeeds */\n    ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;\n    for( cur = addr_list; cur != NULL; cur = cur->ai_next )\n    {\n        ctx->fd = (int) socket( cur->ai_family, cur->ai_socktype,\n                            cur->ai_protocol );\n        if( ctx->fd < 0 )\n        {\n            ret = MBEDTLS_ERR_NET_SOCKET_FAILED;\n            continue;\n        }\n\n        n = 1;\n        if( setsockopt( ctx->fd, SOL_SOCKET, SO_REUSEADDR,\n                        (const char *) &n, sizeof( n ) ) != 0 )\n        {\n            close( ctx->fd );\n            ret = MBEDTLS_ERR_NET_SOCKET_FAILED;\n            continue;\n        }\n\n        if( bind( ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen ) != 0 )\n        {\n            close( ctx->fd );\n            ret = MBEDTLS_ERR_NET_BIND_FAILED;\n            continue;\n        }\n\n        /* Listen only makes sense for TCP */\n        if( proto == MBEDTLS_NET_PROTO_TCP )\n        {\n            if( listen( ctx->fd, MBEDTLS_NET_LISTEN_BACKLOG ) != 0 )\n            {\n                close( ctx->fd );\n                ret = MBEDTLS_ERR_NET_LISTEN_FAILED;\n                continue;\n            }\n        }\n\n        /* Bind was successful */\n        ret = 0;\n        break;\n    }\n\n    freeaddrinfo( addr_list );\n\n    return( ret );\n\n}\n\n#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \\\n    !defined(EFI32)\n/*\n * Check if the requested operation would be blocking on a non-blocking socket\n * and thus 'failed' with a negative return value.\n */\nstatic int net_would_block( const mbedtls_net_context *ctx )\n{\n    ((void) ctx);\n    return( WSAGetLastError() == WSAEWOULDBLOCK );\n}\n#else\n/*\n * Check if the requested operation would be blocking on a non-blocking socket\n * and thus 'failed' with a negative return value.\n *\n * Note: on a blocking socket this function always returns 0!\n */\nstatic int net_would_block( const mbedtls_net_context *ctx )\n{\n    int err = errno;\n\n    /*\n     * Never return 'WOULD BLOCK' on a non-blocking socket\n     */\n    if( ( fcntl( ctx->fd, F_GETFL ) & O_NONBLOCK ) != O_NONBLOCK )\n    {\n        errno = err;\n        return( 0 );\n    }\n\n    switch( errno = err )\n    {\n#if defined EAGAIN\n        case EAGAIN:\n#endif\n#if defined EWOULDBLOCK && EWOULDBLOCK != EAGAIN\n        case EWOULDBLOCK:\n#endif\n            return( 1 );\n    }\n    return( 0 );\n}\n#endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */\n\n/*\n * Accept a connection from a remote client\n */\nint mbedtls_net_accept( mbedtls_net_context *bind_ctx,\n                        mbedtls_net_context *client_ctx,\n                        void *client_ip, size_t buf_size, size_t *ip_len )\n{\n    int ret;\n    int type;\n\n    struct sockaddr_storage client_addr;\n\n#if defined(__socklen_t_defined) || defined(_SOCKLEN_T) ||  \\\n    defined(_SOCKLEN_T_DECLARED) || defined(__DEFINED_socklen_t)\n    socklen_t n = (socklen_t) sizeof( client_addr );\n    socklen_t type_len = (socklen_t) sizeof( type );\n#else\n    int n = (int) sizeof( client_addr );\n    int type_len = (int) sizeof( type );\n#endif\n\n    /* Is this a TCP or UDP socket? */\n    if( getsockopt( bind_ctx->fd, SOL_SOCKET, SO_TYPE,\n                    (void *) &type, &type_len ) != 0 ||\n        ( type != SOCK_STREAM && type != SOCK_DGRAM ) )\n    {\n        return( MBEDTLS_ERR_NET_ACCEPT_FAILED );\n    }\n\n    if( type == SOCK_STREAM )\n    {\n        /* TCP: actual accept() */\n        ret = client_ctx->fd = (int) accept( bind_ctx->fd,\n                                             (struct sockaddr *) &client_addr, &n );\n    }\n    else\n    {\n        /* UDP: wait for a message, but keep it in the queue */\n        char buf[1] = { 0 };\n\n        ret = (int) recvfrom( bind_ctx->fd, buf, sizeof( buf ), MSG_PEEK,\n                        (struct sockaddr *) &client_addr, &n );\n\n#if defined(_WIN32)\n        if( ret == SOCKET_ERROR &&\n            WSAGetLastError() == WSAEMSGSIZE )\n        {\n            /* We know buf is too small, thanks, just peeking here */\n            ret = 0;\n        }\n#endif\n    }\n\n    if( ret < 0 )\n    {\n        if( net_would_block( bind_ctx ) != 0 )\n            return( MBEDTLS_ERR_SSL_WANT_READ );\n\n        return( MBEDTLS_ERR_NET_ACCEPT_FAILED );\n    }\n\n    /* UDP: hijack the listening socket to communicate with the client,\n     * then bind a new socket to accept new connections */\n    if( type != SOCK_STREAM )\n    {\n        struct sockaddr_storage local_addr;\n        int one = 1;\n\n        if( connect( bind_ctx->fd, (struct sockaddr *) &client_addr, n ) != 0 )\n            return( MBEDTLS_ERR_NET_ACCEPT_FAILED );\n\n        client_ctx->fd = bind_ctx->fd;\n        bind_ctx->fd   = -1; /* In case we exit early */\n\n        n = sizeof( struct sockaddr_storage );\n        if( getsockname( client_ctx->fd,\n                         (struct sockaddr *) &local_addr, &n ) != 0 ||\n            ( bind_ctx->fd = (int) socket( local_addr.ss_family,\n                                           SOCK_DGRAM, IPPROTO_UDP ) ) < 0 ||\n            setsockopt( bind_ctx->fd, SOL_SOCKET, SO_REUSEADDR,\n                        (const char *) &one, sizeof( one ) ) != 0 )\n        {\n            return( MBEDTLS_ERR_NET_SOCKET_FAILED );\n        }\n\n        if( bind( bind_ctx->fd, (struct sockaddr *) &local_addr, n ) != 0 )\n        {\n            return( MBEDTLS_ERR_NET_BIND_FAILED );\n        }\n    }\n\n    if( client_ip != NULL )\n    {\n        if( client_addr.ss_family == AF_INET )\n        {\n            struct sockaddr_in *addr4 = (struct sockaddr_in *) &client_addr;\n            *ip_len = sizeof( addr4->sin_addr.s_addr );\n\n            if( buf_size < *ip_len )\n                return( MBEDTLS_ERR_NET_BUFFER_TOO_SMALL );\n\n            memcpy( client_ip, &addr4->sin_addr.s_addr, *ip_len );\n        }\n        else\n        {\n            struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) &client_addr;\n            *ip_len = sizeof( addr6->sin6_addr.s6_addr );\n\n            if( buf_size < *ip_len )\n                return( MBEDTLS_ERR_NET_BUFFER_TOO_SMALL );\n\n            memcpy( client_ip, &addr6->sin6_addr.s6_addr, *ip_len);\n        }\n    }\n\n    return( 0 );\n}\n\n/*\n * Set the socket blocking or non-blocking\n */\nint mbedtls_net_set_block( mbedtls_net_context *ctx )\n{\n#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \\\n    !defined(EFI32)\n    u_long n = 0;\n    return( ioctlsocket( ctx->fd, FIONBIO, &n ) );\n#else\n    return( fcntl( ctx->fd, F_SETFL, fcntl( ctx->fd, F_GETFL ) & ~O_NONBLOCK ) );\n#endif\n}\n\nint mbedtls_net_set_nonblock( mbedtls_net_context *ctx )\n{\n#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \\\n    !defined(EFI32)\n    u_long n = 1;\n    return( ioctlsocket( ctx->fd, FIONBIO, &n ) );\n#else\n    return( fcntl( ctx->fd, F_SETFL, fcntl( ctx->fd, F_GETFL ) | O_NONBLOCK ) );\n#endif\n}\n\n/*\n * Check if data is available on the socket\n */\n\nint mbedtls_net_poll( mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout )\n{\n    int ret;\n    struct timeval tv;\n\n    fd_set read_fds;\n    fd_set write_fds;\n\n    int fd = ctx->fd;\n\n    if( fd < 0 )\n        return( MBEDTLS_ERR_NET_INVALID_CONTEXT );\n\n#if defined(__has_feature)\n#if __has_feature(memory_sanitizer)\n    /* Ensure that memory sanitizers consider read_fds and write_fds as\n     * initialized even on platforms such as Glibc/x86_64 where FD_ZERO\n     * is implemented in assembly. */\n    memset( &read_fds, 0, sizeof( read_fds ) );\n    memset( &write_fds, 0, sizeof( write_fds ) );\n#endif\n#endif\n\n    FD_ZERO( &read_fds );\n    if( rw & MBEDTLS_NET_POLL_READ )\n    {\n        rw &= ~MBEDTLS_NET_POLL_READ;\n        FD_SET( fd, &read_fds );\n    }\n\n    FD_ZERO( &write_fds );\n    if( rw & MBEDTLS_NET_POLL_WRITE )\n    {\n        rw &= ~MBEDTLS_NET_POLL_WRITE;\n        FD_SET( fd, &write_fds );\n    }\n\n    if( rw != 0 )\n        return( MBEDTLS_ERR_NET_BAD_INPUT_DATA );\n\n    tv.tv_sec  = timeout / 1000;\n    tv.tv_usec = ( timeout % 1000 ) * 1000;\n\n    do\n    {\n        ret = select( fd + 1, &read_fds, &write_fds, NULL,\n                      timeout == (uint32_t) -1 ? NULL : &tv );\n    }\n    while( IS_EINTR( ret ) );\n\n    if( ret < 0 )\n        return( MBEDTLS_ERR_NET_POLL_FAILED );\n\n    ret = 0;\n    if( FD_ISSET( fd, &read_fds ) )\n        ret |= MBEDTLS_NET_POLL_READ;\n    if( FD_ISSET( fd, &write_fds ) )\n        ret |= MBEDTLS_NET_POLL_WRITE;\n\n    return( ret );\n}\n\n/*\n * Portable usleep helper\n */\nvoid mbedtls_net_usleep( unsigned long usec )\n{\n#if defined(_WIN32)\n    Sleep( ( usec + 999 ) / 1000 );\n#else\n    struct timeval tv;\n    tv.tv_sec  = usec / 1000000;\n#if defined(__unix__) || defined(__unix) || \\\n    ( defined(__APPLE__) && defined(__MACH__) )\n    tv.tv_usec = (suseconds_t) usec % 1000000;\n#else\n    tv.tv_usec = usec % 1000000;\n#endif\n    select( 0, NULL, NULL, NULL, &tv );\n#endif\n}\n\n/*\n * Read at most 'len' characters\n */\nint mbedtls_net_recv( void *ctx, unsigned char *buf, size_t len )\n{\n    int ret;\n    int fd = ((mbedtls_net_context *) ctx)->fd;\n\n    if( fd < 0 )\n        return( MBEDTLS_ERR_NET_INVALID_CONTEXT );\n\n    ret = (int) read( fd, buf, len );\n\n    if( ret < 0 )\n    {\n        if( net_would_block( ctx ) != 0 )\n            return( MBEDTLS_ERR_SSL_WANT_READ );\n\n#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \\\n    !defined(EFI32)\n        if( WSAGetLastError() == WSAECONNRESET )\n            return( MBEDTLS_ERR_NET_CONN_RESET );\n#else\n        if( errno == EPIPE || errno == ECONNRESET )\n            return( MBEDTLS_ERR_NET_CONN_RESET );\n\n        if( errno == EINTR )\n            return( MBEDTLS_ERR_SSL_WANT_READ );\n#endif\n\n        return( MBEDTLS_ERR_NET_RECV_FAILED );\n    }\n\n    return( ret );\n}\n\n/*\n * Read at most 'len' characters, blocking for at most 'timeout' ms\n */\nint mbedtls_net_recv_timeout( void *ctx, unsigned char *buf,\n                              size_t len, uint32_t timeout )\n{\n    int ret;\n    struct timeval tv;\n    fd_set read_fds;\n    int fd = ((mbedtls_net_context *) ctx)->fd;\n\n    if( fd < 0 )\n        return( MBEDTLS_ERR_NET_INVALID_CONTEXT );\n\n    FD_ZERO( &read_fds );\n    FD_SET( fd, &read_fds );\n\n    tv.tv_sec  = timeout / 1000;\n    tv.tv_usec = ( timeout % 1000 ) * 1000;\n\n    ret = select( fd + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv );\n\n    /* Zero fds ready means we timed out */\n    if( ret == 0 )\n        return( MBEDTLS_ERR_SSL_TIMEOUT );\n\n    if( ret < 0 )\n    {\n#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \\\n    !defined(EFI32)\n        if( WSAGetLastError() == WSAEINTR )\n            return( MBEDTLS_ERR_SSL_WANT_READ );\n#else\n        if( errno == EINTR )\n            return( MBEDTLS_ERR_SSL_WANT_READ );\n#endif\n\n        return( MBEDTLS_ERR_NET_RECV_FAILED );\n    }\n\n    /* This call will not block */\n    return( mbedtls_net_recv( ctx, buf, len ) );\n}\n\n/*\n * Write at most 'len' characters\n */\nint mbedtls_net_send( void *ctx, const unsigned char *buf, size_t len )\n{\n    int ret;\n    int fd = ((mbedtls_net_context *) ctx)->fd;\n\n    if( fd < 0 )\n        return( MBEDTLS_ERR_NET_INVALID_CONTEXT );\n\n    ret = (int) write( fd, buf, len );\n\n    if( ret < 0 )\n    {\n        if( net_would_block( ctx ) != 0 )\n            return( MBEDTLS_ERR_SSL_WANT_WRITE );\n\n#if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \\\n    !defined(EFI32)\n        if( WSAGetLastError() == WSAECONNRESET )\n            return( MBEDTLS_ERR_NET_CONN_RESET );\n#else\n        if( errno == EPIPE || errno == ECONNRESET )\n            return( MBEDTLS_ERR_NET_CONN_RESET );\n\n        if( errno == EINTR )\n            return( MBEDTLS_ERR_SSL_WANT_WRITE );\n#endif\n\n        return( MBEDTLS_ERR_NET_SEND_FAILED );\n    }\n\n    return( ret );\n}\n\n/*\n * Gracefully close the connection\n */\nvoid mbedtls_net_free( mbedtls_net_context *ctx )\n{\n    if( ctx->fd == -1 )\n        return;\n\n    shutdown( ctx->fd, 2 );\n    close( ctx->fd );\n\n    ctx->fd = -1;\n}\n\n#endif /* MBEDTLS_NET_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/nist_kw.c",
    "content": "/*\n *  Implementation of NIST SP 800-38F key wrapping, supporting KW and KWP modes\n *  only\n *\n *  Copyright (C) 2018, Arm Limited (or its affiliates), All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n/*\n * Definition of Key Wrapping:\n * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf\n * RFC 3394 \"Advanced Encryption Standard (AES) Key Wrap Algorithm\"\n * RFC 5649 \"Advanced Encryption Standard (AES) Key Wrap with Padding Algorithm\"\n *\n * Note: RFC 3394 defines different methodology for intermediate operations for\n * the wrapping and unwrapping operation than the definition in NIST SP 800-38F.\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_NIST_KW_C)\n\n#include \"mbedtls/nist_kw.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <stdint.h>\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */\n\n#if !defined(MBEDTLS_NIST_KW_ALT)\n\n#define KW_SEMIBLOCK_LENGTH    8\n#define MIN_SEMIBLOCKS_COUNT   3\n\n/* constant-time buffer comparison */\nstatic inline unsigned char mbedtls_nist_kw_safer_memcmp( const void *a, const void *b, size_t n )\n{\n    size_t i;\n    volatile const unsigned char *A = (volatile const unsigned char *) a;\n    volatile const unsigned char *B = (volatile const unsigned char *) b;\n    volatile unsigned char diff = 0;\n\n    for( i = 0; i < n; i++ )\n    {\n        /* Read volatile data in order before computing diff.\n         * This avoids IAR compiler warning:\n         * 'the order of volatile accesses is undefined ..' */\n        unsigned char x = A[i], y = B[i];\n        diff |= x ^ y;\n    }\n\n    return( diff );\n}\n\n/*! The 64-bit default integrity check value (ICV) for KW mode. */\nstatic const unsigned char NIST_KW_ICV1[] = {0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6};\n/*! The 32-bit default integrity check value (ICV) for KWP mode. */\nstatic const  unsigned char NIST_KW_ICV2[] = {0xA6, 0x59, 0x59, 0xA6};\n\n#ifndef GET_UINT32_BE\n#define GET_UINT32_BE(n,b,i)                            \\\ndo {                                                    \\\n    (n) = ( (uint32_t) (b)[(i)    ] << 24 )             \\\n        | ( (uint32_t) (b)[(i) + 1] << 16 )             \\\n        | ( (uint32_t) (b)[(i) + 2] <<  8 )             \\\n        | ( (uint32_t) (b)[(i) + 3]       );            \\\n} while( 0 )\n#endif\n\n#ifndef PUT_UINT32_BE\n#define PUT_UINT32_BE(n,b,i)                            \\\ndo {                                                    \\\n    (b)[(i)    ] = (unsigned char) ( (n) >> 24 );       \\\n    (b)[(i) + 1] = (unsigned char) ( (n) >> 16 );       \\\n    (b)[(i) + 2] = (unsigned char) ( (n) >>  8 );       \\\n    (b)[(i) + 3] = (unsigned char) ( (n)       );       \\\n} while( 0 )\n#endif\n\n/*\n * Initialize context\n */\nvoid mbedtls_nist_kw_init( mbedtls_nist_kw_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_nist_kw_context ) );\n}\n\nint mbedtls_nist_kw_setkey( mbedtls_nist_kw_context *ctx,\n                            mbedtls_cipher_id_t cipher,\n                            const unsigned char *key,\n                            unsigned int keybits,\n                            const int is_wrap )\n{\n    int ret;\n    const mbedtls_cipher_info_t *cipher_info;\n\n    cipher_info = mbedtls_cipher_info_from_values( cipher,\n                                                   keybits,\n                                                   MBEDTLS_MODE_ECB );\n    if( cipher_info == NULL )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    if( cipher_info->block_size != 16 )\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n\n    /*\n     * SP 800-38F currently defines AES cipher as the only block cipher allowed:\n     * \"For KW and KWP, the underlying block cipher shall be approved, and the\n     *  block size shall be 128 bits. Currently, the AES block cipher, with key\n     *  lengths of 128, 192, or 256 bits, is the only block cipher that fits\n     *  this profile.\"\n     *  Currently we don't support other 128 bit block ciphers for key wrapping,\n     *  such as Camellia and Aria.\n     */\n    if( cipher != MBEDTLS_CIPHER_ID_AES )\n        return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );\n\n    mbedtls_cipher_free( &ctx->cipher_ctx );\n\n    if( ( ret = mbedtls_cipher_setup( &ctx->cipher_ctx, cipher_info ) ) != 0 )\n        return( ret );\n\n    if( ( ret = mbedtls_cipher_setkey( &ctx->cipher_ctx, key, keybits,\n                                       is_wrap ? MBEDTLS_ENCRYPT :\n                                                 MBEDTLS_DECRYPT )\n                                                                   ) != 0 )\n    {\n        return( ret );\n    }\n\n    return( 0 );\n}\n\n/*\n * Free context\n */\nvoid mbedtls_nist_kw_free( mbedtls_nist_kw_context *ctx )\n{\n    mbedtls_cipher_free( &ctx->cipher_ctx );\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_nist_kw_context ) );\n}\n\n/*\n * Helper function for Xoring the uint64_t \"t\" with the encrypted A.\n * Defined in NIST SP 800-38F section 6.1\n */\nstatic void calc_a_xor_t( unsigned char A[KW_SEMIBLOCK_LENGTH], uint64_t t )\n{\n    size_t i = 0;\n    for( i = 0; i < sizeof( t ); i++ )\n    {\n        A[i] ^= ( t >> ( ( sizeof( t ) - 1 - i ) * 8 ) ) & 0xff;\n    }\n}\n\n/*\n * KW-AE as defined in SP 800-38F section 6.2\n * KWP-AE as defined in SP 800-38F section 6.3\n */\nint mbedtls_nist_kw_wrap( mbedtls_nist_kw_context *ctx,\n                          mbedtls_nist_kw_mode_t mode,\n                          const unsigned char *input, size_t in_len,\n                          unsigned char *output, size_t *out_len, size_t out_size )\n{\n    int ret = 0;\n    size_t semiblocks = 0;\n    size_t s;\n    size_t olen, padlen = 0;\n    uint64_t t = 0;\n    unsigned char outbuff[KW_SEMIBLOCK_LENGTH * 2];\n    unsigned char inbuff[KW_SEMIBLOCK_LENGTH * 2];\n    unsigned char *R2 = output + KW_SEMIBLOCK_LENGTH;\n    unsigned char *A = output;\n\n    *out_len = 0;\n    /*\n     * Generate the String to work on\n     */\n    if( mode == MBEDTLS_KW_MODE_KW )\n    {\n        if( out_size < in_len + KW_SEMIBLOCK_LENGTH )\n        {\n            return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n        }\n\n        /*\n         * According to SP 800-38F Table 1, the plaintext length for KW\n         * must be between 2 to 2^54-1 semiblocks inclusive.\n         */\n        if( in_len < 16 ||\n#if SIZE_MAX > 0x1FFFFFFFFFFFFF8\n            in_len > 0x1FFFFFFFFFFFFF8 ||\n#endif\n            in_len % KW_SEMIBLOCK_LENGTH != 0 )\n        {\n            return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n        }\n\n        memcpy( output, NIST_KW_ICV1, KW_SEMIBLOCK_LENGTH );\n        memmove( output + KW_SEMIBLOCK_LENGTH, input, in_len );\n    }\n    else\n    {\n        if( in_len % 8 != 0 )\n        {\n            padlen = ( 8 - ( in_len % 8 ) );\n        }\n\n        if( out_size < in_len + KW_SEMIBLOCK_LENGTH + padlen )\n        {\n            return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n        }\n\n        /*\n         * According to SP 800-38F Table 1, the plaintext length for KWP\n         * must be between 1 and 2^32-1 octets inclusive.\n         */\n        if( in_len < 1\n#if SIZE_MAX > 0xFFFFFFFF\n            || in_len > 0xFFFFFFFF\n#endif\n          )\n        {\n            return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n        }\n\n        memcpy( output, NIST_KW_ICV2, KW_SEMIBLOCK_LENGTH / 2 );\n        PUT_UINT32_BE( ( in_len & 0xffffffff ), output,\n                       KW_SEMIBLOCK_LENGTH / 2 );\n\n        memcpy( output + KW_SEMIBLOCK_LENGTH, input, in_len );\n        memset( output + KW_SEMIBLOCK_LENGTH + in_len, 0, padlen );\n    }\n    semiblocks = ( ( in_len + padlen ) / KW_SEMIBLOCK_LENGTH ) + 1;\n\n    s = 6 * ( semiblocks - 1 );\n\n    if( mode == MBEDTLS_KW_MODE_KWP\n        && in_len <= KW_SEMIBLOCK_LENGTH )\n    {\n        memcpy( inbuff, output, 16 );\n        ret = mbedtls_cipher_update( &ctx->cipher_ctx,\n                                     inbuff, 16, output, &olen );\n        if( ret != 0 )\n            goto cleanup;\n    }\n    else\n    {\n        /*\n         * Do the wrapping function W, as defined in RFC 3394 section 2.2.1\n         */\n        if( semiblocks < MIN_SEMIBLOCKS_COUNT )\n        {\n            ret = MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;\n            goto cleanup;\n        }\n\n        /* Calculate intermediate values */\n        for( t = 1; t <= s; t++ )\n        {\n            memcpy( inbuff, A, KW_SEMIBLOCK_LENGTH );\n            memcpy( inbuff + KW_SEMIBLOCK_LENGTH, R2, KW_SEMIBLOCK_LENGTH );\n\n            ret = mbedtls_cipher_update( &ctx->cipher_ctx,\n                                         inbuff, 16, outbuff, &olen );\n            if( ret != 0 )\n                goto cleanup;\n\n            memcpy( A, outbuff, KW_SEMIBLOCK_LENGTH );\n            calc_a_xor_t( A, t );\n\n            memcpy( R2, outbuff + KW_SEMIBLOCK_LENGTH, KW_SEMIBLOCK_LENGTH );\n            R2 += KW_SEMIBLOCK_LENGTH;\n            if( R2 >= output + ( semiblocks * KW_SEMIBLOCK_LENGTH ) )\n                R2 = output + KW_SEMIBLOCK_LENGTH;\n        }\n    }\n\n    *out_len = semiblocks * KW_SEMIBLOCK_LENGTH;\n\ncleanup:\n\n    if( ret != 0)\n    {\n        memset( output, 0, semiblocks * KW_SEMIBLOCK_LENGTH );\n    }\n    mbedtls_platform_zeroize( inbuff, KW_SEMIBLOCK_LENGTH * 2 );\n    mbedtls_platform_zeroize( outbuff, KW_SEMIBLOCK_LENGTH * 2 );\n    mbedtls_cipher_finish( &ctx->cipher_ctx, NULL, &olen );\n    return( ret );\n}\n\n/*\n * W-1 function as defined in RFC 3394 section 2.2.2\n * This function assumes the following:\n * 1. Output buffer is at least of size ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH.\n * 2. The input buffer is of size semiblocks * KW_SEMIBLOCK_LENGTH.\n * 3. Minimal number of semiblocks is 3.\n * 4. A is a buffer to hold the first semiblock of the input buffer.\n */\nstatic int unwrap( mbedtls_nist_kw_context *ctx,\n                   const unsigned char *input, size_t semiblocks,\n                   unsigned char A[KW_SEMIBLOCK_LENGTH],\n                   unsigned char *output, size_t* out_len )\n{\n    int ret = 0;\n    const size_t s = 6 * ( semiblocks - 1 );\n    size_t olen;\n    uint64_t t = 0;\n    unsigned char outbuff[KW_SEMIBLOCK_LENGTH * 2];\n    unsigned char inbuff[KW_SEMIBLOCK_LENGTH * 2];\n    unsigned char *R = output + ( semiblocks - 2 ) * KW_SEMIBLOCK_LENGTH;\n    *out_len = 0;\n\n    if( semiblocks < MIN_SEMIBLOCKS_COUNT )\n    {\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n    }\n\n    memcpy( A, input, KW_SEMIBLOCK_LENGTH );\n    memmove( output, input + KW_SEMIBLOCK_LENGTH, ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH );\n\n    /* Calculate intermediate values */\n    for( t = s; t >= 1; t-- )\n    {\n        calc_a_xor_t( A, t );\n\n        memcpy( inbuff, A, KW_SEMIBLOCK_LENGTH );\n        memcpy( inbuff + KW_SEMIBLOCK_LENGTH, R, KW_SEMIBLOCK_LENGTH );\n\n        ret = mbedtls_cipher_update( &ctx->cipher_ctx,\n                                     inbuff, 16, outbuff, &olen );\n        if( ret != 0 )\n            goto cleanup;\n\n        memcpy( A, outbuff, KW_SEMIBLOCK_LENGTH );\n\n        /* Set R as LSB64 of outbuff */\n        memcpy( R, outbuff + KW_SEMIBLOCK_LENGTH, KW_SEMIBLOCK_LENGTH );\n\n        if( R == output )\n            R = output + ( semiblocks - 2 ) * KW_SEMIBLOCK_LENGTH;\n        else\n            R -= KW_SEMIBLOCK_LENGTH;\n    }\n\n    *out_len = ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH;\n\ncleanup:\n    if( ret != 0)\n        memset( output, 0, ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH );\n    mbedtls_platform_zeroize( inbuff, sizeof( inbuff )  );\n    mbedtls_platform_zeroize( outbuff, sizeof( outbuff ) );\n\n    return( ret );\n}\n\n/*\n * KW-AD as defined in SP 800-38F section 6.2\n * KWP-AD as defined in SP 800-38F section 6.3\n */\nint mbedtls_nist_kw_unwrap( mbedtls_nist_kw_context *ctx,\n                            mbedtls_nist_kw_mode_t mode,\n                            const unsigned char *input, size_t in_len,\n                            unsigned char *output, size_t *out_len, size_t out_size )\n{\n    int ret = 0;\n    size_t i, olen;\n    unsigned char A[KW_SEMIBLOCK_LENGTH];\n    unsigned char diff, bad_padding = 0;\n\n    *out_len = 0;\n    if( out_size < in_len - KW_SEMIBLOCK_LENGTH )\n    {\n        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n    }\n\n    if( mode == MBEDTLS_KW_MODE_KW )\n    {\n        /*\n         * According to SP 800-38F Table 1, the ciphertext length for KW\n         * must be between 3 to 2^54 semiblocks inclusive.\n         */\n        if( in_len < 24 ||\n#if SIZE_MAX > 0x200000000000000\n            in_len > 0x200000000000000 ||\n#endif\n            in_len % KW_SEMIBLOCK_LENGTH != 0 )\n        {\n            return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n        }\n\n        ret = unwrap( ctx, input, in_len / KW_SEMIBLOCK_LENGTH,\n                      A, output, out_len );\n        if( ret != 0 )\n            goto cleanup;\n\n        /* Check ICV in \"constant-time\" */\n        diff = mbedtls_nist_kw_safer_memcmp( NIST_KW_ICV1, A, KW_SEMIBLOCK_LENGTH );\n\n        if( diff != 0 )\n        {\n            ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;\n            goto cleanup;\n        }\n\n    }\n    else if( mode == MBEDTLS_KW_MODE_KWP )\n    {\n        size_t padlen = 0;\n        uint32_t Plen;\n        /*\n         * According to SP 800-38F Table 1, the ciphertext length for KWP\n         * must be between 2 to 2^29 semiblocks inclusive.\n         */\n        if( in_len < KW_SEMIBLOCK_LENGTH * 2 ||\n#if SIZE_MAX > 0x100000000\n            in_len > 0x100000000 ||\n#endif\n            in_len % KW_SEMIBLOCK_LENGTH != 0 )\n        {\n            return(  MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );\n        }\n\n        if( in_len == KW_SEMIBLOCK_LENGTH * 2 )\n        {\n            unsigned char outbuff[KW_SEMIBLOCK_LENGTH * 2];\n            ret = mbedtls_cipher_update( &ctx->cipher_ctx,\n                                         input, 16, outbuff, &olen );\n            if( ret != 0 )\n                goto cleanup;\n\n            memcpy( A, outbuff, KW_SEMIBLOCK_LENGTH );\n            memcpy( output, outbuff + KW_SEMIBLOCK_LENGTH, KW_SEMIBLOCK_LENGTH );\n            mbedtls_platform_zeroize( outbuff, sizeof( outbuff ) );\n            *out_len = KW_SEMIBLOCK_LENGTH;\n        }\n        else\n        {\n            /* in_len >=  KW_SEMIBLOCK_LENGTH * 3 */\n            ret = unwrap( ctx, input, in_len / KW_SEMIBLOCK_LENGTH,\n                          A, output, out_len );\n            if( ret != 0 )\n                goto cleanup;\n        }\n\n        /* Check ICV in \"constant-time\" */\n        diff = mbedtls_nist_kw_safer_memcmp( NIST_KW_ICV2, A, KW_SEMIBLOCK_LENGTH / 2 );\n\n        if( diff != 0 )\n        {\n            ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;\n        }\n\n        GET_UINT32_BE( Plen, A, KW_SEMIBLOCK_LENGTH / 2 );\n\n        /*\n         * Plen is the length of the plaintext, when the input is valid.\n         * If Plen is larger than the plaintext and padding, padlen will be\n         * larger than 8, because of the type wrap around.\n         */\n        padlen = in_len - KW_SEMIBLOCK_LENGTH - Plen;\n        if ( padlen > 7 )\n        {\n            padlen &= 7;\n            ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;\n        }\n\n        /* Check padding in \"constant-time\" */\n        for( diff = 0, i = 0; i < KW_SEMIBLOCK_LENGTH; i++ )\n        {\n             if( i >= KW_SEMIBLOCK_LENGTH - padlen )\n                 diff |= output[*out_len - KW_SEMIBLOCK_LENGTH + i];\n             else\n                 bad_padding |= output[*out_len - KW_SEMIBLOCK_LENGTH + i];\n        }\n\n        if( diff != 0 )\n        {\n            ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;\n        }\n\n        if( ret != 0 )\n        {\n            goto cleanup;\n        }\n        memset( output + Plen, 0, padlen );\n        *out_len = Plen;\n    }\n    else\n    {\n        ret = MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE;\n        goto cleanup;\n    }\n\ncleanup:\n    if( ret != 0 )\n    {\n        memset( output, 0, *out_len );\n        *out_len = 0;\n    }\n\n    mbedtls_platform_zeroize( &bad_padding, sizeof( bad_padding) );\n    mbedtls_platform_zeroize( &diff, sizeof( diff ) );\n    mbedtls_platform_zeroize( A, sizeof( A ) );\n    mbedtls_cipher_finish( &ctx->cipher_ctx, NULL, &olen );\n    return( ret );\n}\n\n#endif /* !MBEDTLS_NIST_KW_ALT */\n\n#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)\n\n#define KW_TESTS 3\n\n/*\n * Test vectors taken from NIST\n * https://csrc.nist.gov/Projects/Cryptographic-Algorithm-Validation-Program/CAVP-TESTING-BLOCK-CIPHER-MODES#KW\n */\nstatic const unsigned int key_len[KW_TESTS] = { 16, 24, 32 };\n\nstatic const unsigned char kw_key[KW_TESTS][32] = {\n    { 0x75, 0x75, 0xda, 0x3a, 0x93, 0x60, 0x7c, 0xc2,\n      0xbf, 0xd8, 0xce, 0xc7, 0xaa, 0xdf, 0xd9, 0xa6 },\n    { 0x2d, 0x85, 0x26, 0x08, 0x1d, 0x02, 0xfb, 0x5b,\n      0x85, 0xf6, 0x9a, 0xc2, 0x86, 0xec, 0xd5, 0x7d,\n      0x40, 0xdf, 0x5d, 0xf3, 0x49, 0x47, 0x44, 0xd3 },\n    { 0x11, 0x2a, 0xd4, 0x1b, 0x48, 0x56, 0xc7, 0x25,\n      0x4a, 0x98, 0x48, 0xd3, 0x0f, 0xdd, 0x78, 0x33,\n      0x5b, 0x03, 0x9a, 0x48, 0xa8, 0x96, 0x2c, 0x4d,\n      0x1c, 0xb7, 0x8e, 0xab, 0xd5, 0xda, 0xd7, 0x88 }\n};\n\nstatic const unsigned char kw_msg[KW_TESTS][40] = {\n    { 0x42, 0x13, 0x6d, 0x3c, 0x38, 0x4a, 0x3e, 0xea,\n      0xc9, 0x5a, 0x06, 0x6f, 0xd2, 0x8f, 0xed, 0x3f },\n    { 0x95, 0xc1, 0x1b, 0xf5, 0x35, 0x3a, 0xfe, 0xdb,\n      0x98, 0xfd, 0xd6, 0xc8, 0xca, 0x6f, 0xdb, 0x6d,\n      0xa5, 0x4b, 0x74, 0xb4, 0x99, 0x0f, 0xdc, 0x45,\n      0xc0, 0x9d, 0x15, 0x8f, 0x51, 0xce, 0x62, 0x9d,\n      0xe2, 0xaf, 0x26, 0xe3, 0x25, 0x0e, 0x6b, 0x4c },\n    { 0x1b, 0x20, 0xbf, 0x19, 0x90, 0xb0, 0x65, 0xd7,\n      0x98, 0xe1, 0xb3, 0x22, 0x64, 0xad, 0x50, 0xa8,\n      0x74, 0x74, 0x92, 0xba, 0x09, 0xa0, 0x4d, 0xd1 }\n};\n\nstatic const size_t kw_msg_len[KW_TESTS] = { 16, 40, 24 };\nstatic const size_t kw_out_len[KW_TESTS] = { 24, 48, 32 };\nstatic const unsigned char kw_res[KW_TESTS][48] = {\n    { 0x03, 0x1f, 0x6b, 0xd7, 0xe6, 0x1e, 0x64, 0x3d,\n      0xf6, 0x85, 0x94, 0x81, 0x6f, 0x64, 0xca, 0xa3,\n      0xf5, 0x6f, 0xab, 0xea, 0x25, 0x48, 0xf5, 0xfb },\n    { 0x44, 0x3c, 0x6f, 0x15, 0x09, 0x83, 0x71, 0x91,\n      0x3e, 0x5c, 0x81, 0x4c, 0xa1, 0xa0, 0x42, 0xec,\n      0x68, 0x2f, 0x7b, 0x13, 0x6d, 0x24, 0x3a, 0x4d,\n      0x6c, 0x42, 0x6f, 0xc6, 0x97, 0x15, 0x63, 0xe8,\n      0xa1, 0x4a, 0x55, 0x8e, 0x09, 0x64, 0x16, 0x19,\n      0xbf, 0x03, 0xfc, 0xaf, 0x90, 0xb1, 0xfc, 0x2d },\n    { 0xba, 0x8a, 0x25, 0x9a, 0x47, 0x1b, 0x78, 0x7d,\n      0xd5, 0xd5, 0x40, 0xec, 0x25, 0xd4, 0x3d, 0x87,\n      0x20, 0x0f, 0xda, 0xdc, 0x6d, 0x1f, 0x05, 0xd9,\n      0x16, 0x58, 0x4f, 0xa9, 0xf6, 0xcb, 0xf5, 0x12 }\n};\n\nstatic const unsigned char kwp_key[KW_TESTS][32] = {\n    { 0x78, 0x65, 0xe2, 0x0f, 0x3c, 0x21, 0x65, 0x9a,\n      0xb4, 0x69, 0x0b, 0x62, 0x9c, 0xdf, 0x3c, 0xc4 },\n    { 0xf5, 0xf8, 0x96, 0xa3, 0xbd, 0x2f, 0x4a, 0x98,\n      0x23, 0xef, 0x16, 0x2b, 0x00, 0xb8, 0x05, 0xd7,\n      0xde, 0x1e, 0xa4, 0x66, 0x26, 0x96, 0xa2, 0x58 },\n    { 0x95, 0xda, 0x27, 0x00, 0xca, 0x6f, 0xd9, 0xa5,\n      0x25, 0x54, 0xee, 0x2a, 0x8d, 0xf1, 0x38, 0x6f,\n      0x5b, 0x94, 0xa1, 0xa6, 0x0e, 0xd8, 0xa4, 0xae,\n      0xf6, 0x0a, 0x8d, 0x61, 0xab, 0x5f, 0x22, 0x5a }\n};\n\nstatic const unsigned char kwp_msg[KW_TESTS][31] = {\n    { 0xbd, 0x68, 0x43, 0xd4, 0x20, 0x37, 0x8d, 0xc8,\n      0x96 },\n    { 0x6c, 0xcd, 0xd5, 0x85, 0x18, 0x40, 0x97, 0xeb,\n      0xd5, 0xc3, 0xaf, 0x3e, 0x47, 0xd0, 0x2c, 0x19,\n      0x14, 0x7b, 0x4d, 0x99, 0x5f, 0x96, 0x43, 0x66,\n      0x91, 0x56, 0x75, 0x8c, 0x13, 0x16, 0x8f },\n    { 0xd1 }\n};\nstatic const size_t kwp_msg_len[KW_TESTS] = { 9, 31, 1 };\n\nstatic const unsigned char kwp_res[KW_TESTS][48] = {\n    { 0x41, 0xec, 0xa9, 0x56, 0xd4, 0xaa, 0x04, 0x7e,\n      0xb5, 0xcf, 0x4e, 0xfe, 0x65, 0x96, 0x61, 0xe7,\n      0x4d, 0xb6, 0xf8, 0xc5, 0x64, 0xe2, 0x35, 0x00 },\n    { 0x4e, 0x9b, 0xc2, 0xbc, 0xbc, 0x6c, 0x1e, 0x13,\n      0xd3, 0x35, 0xbc, 0xc0, 0xf7, 0x73, 0x6a, 0x88,\n      0xfa, 0x87, 0x53, 0x66, 0x15, 0xbb, 0x8e, 0x63,\n      0x8b, 0xcc, 0x81, 0x66, 0x84, 0x68, 0x17, 0x90,\n      0x67, 0xcf, 0xa9, 0x8a, 0x9d, 0x0e, 0x33, 0x26 },\n    { 0x06, 0xba, 0x7a, 0xe6, 0xf3, 0x24, 0x8c, 0xfd,\n      0xcf, 0x26, 0x75, 0x07, 0xfa, 0x00, 0x1b, 0xc4  }\n};\nstatic const size_t kwp_out_len[KW_TESTS] = { 24, 40, 16 };\n\nint mbedtls_nist_kw_self_test( int verbose )\n{\n    mbedtls_nist_kw_context ctx;\n    unsigned char out[48];\n    size_t olen;\n    int i;\n    int ret = 0;\n    mbedtls_nist_kw_init( &ctx );\n\n    for( i = 0; i < KW_TESTS; i++ )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"  KW-AES-%u \", (unsigned int) key_len[i] * 8 );\n\n        ret = mbedtls_nist_kw_setkey( &ctx, MBEDTLS_CIPHER_ID_AES,\n                                      kw_key[i], key_len[i] * 8, 1 );\n        if( ret != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"  KW: setup failed \" );\n\n            goto end;\n        }\n\n        ret = mbedtls_nist_kw_wrap( &ctx, MBEDTLS_KW_MODE_KW, kw_msg[i],\n                                    kw_msg_len[i], out, &olen, sizeof( out ) );\n        if( ret != 0 || kw_out_len[i] != olen ||\n            memcmp( out, kw_res[i], kw_out_len[i] ) != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed. \");\n\n            ret = 1;\n            goto end;\n        }\n\n        if( ( ret = mbedtls_nist_kw_setkey( &ctx, MBEDTLS_CIPHER_ID_AES,\n                                            kw_key[i], key_len[i] * 8, 0 ) )\n              != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"  KW: setup failed \");\n\n            goto end;\n        }\n\n        ret = mbedtls_nist_kw_unwrap( &ctx, MBEDTLS_KW_MODE_KW,\n                                      out, olen, out, &olen, sizeof( out ) );\n\n        if( ret != 0 || olen != kw_msg_len[i] ||\n            memcmp( out, kw_msg[i], kw_msg_len[i] ) != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed\\n\" );\n\n            ret = 1;\n            goto end;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \" passed\\n\" );\n    }\n\n    for( i = 0; i < KW_TESTS; i++ )\n    {\n        olen = sizeof( out );\n        if( verbose != 0 )\n            mbedtls_printf( \"  KWP-AES-%u \", (unsigned int) key_len[i] * 8 );\n\n        ret = mbedtls_nist_kw_setkey( &ctx, MBEDTLS_CIPHER_ID_AES, kwp_key[i],\n                                      key_len[i] * 8, 1 );\n        if( ret  != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"  KWP: setup failed \" );\n\n            goto end;\n        }\n        ret = mbedtls_nist_kw_wrap( &ctx, MBEDTLS_KW_MODE_KWP, kwp_msg[i],\n                                    kwp_msg_len[i], out, &olen, sizeof( out ) );\n\n        if( ret != 0 || kwp_out_len[i] != olen ||\n            memcmp( out, kwp_res[i], kwp_out_len[i] ) != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed. \");\n\n            ret = 1;\n            goto end;\n        }\n\n        if( ( ret = mbedtls_nist_kw_setkey( &ctx, MBEDTLS_CIPHER_ID_AES,\n                                            kwp_key[i], key_len[i] * 8, 0 ) )\n              != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"  KWP: setup failed \");\n\n            goto end;\n        }\n\n        ret = mbedtls_nist_kw_unwrap(  &ctx, MBEDTLS_KW_MODE_KWP, out,\n                                       olen, out, &olen, sizeof( out ) );\n\n        if( ret != 0 || olen != kwp_msg_len[i] ||\n            memcmp( out, kwp_msg[i], kwp_msg_len[i] ) != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed. \");\n\n            ret = 1;\n            goto end;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \" passed\\n\" );\n    }\nend:\n    mbedtls_nist_kw_free( &ctx );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */\n\n#endif /* MBEDTLS_NIST_KW_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/oid.c",
    "content": "/**\n * \\file oid.c\n *\n * \\brief Object Identifier (OID) database\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_OID_C)\n\n#include \"mbedtls/oid.h\"\n#include \"mbedtls/rsa.h\"\n\n#include <stdio.h>\n#include <string.h>\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#define mbedtls_snprintf snprintf\n#endif\n\n#if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C)\n#include \"mbedtls/x509.h\"\n#endif\n\n/*\n * Macro to automatically add the size of #define'd OIDs\n */\n#define ADD_LEN(s)      s, MBEDTLS_OID_SIZE(s)\n\n/*\n * Macro to generate an internal function for oid_XXX_from_asn1() (used by\n * the other functions)\n */\n#define FN_OID_TYPED_FROM_ASN1( TYPE_T, NAME, LIST )                        \\\nstatic const TYPE_T * oid_ ## NAME ## _from_asn1( const mbedtls_asn1_buf *oid )     \\\n{                                                                           \\\n    const TYPE_T *p = LIST;                                                 \\\n    const mbedtls_oid_descriptor_t *cur = (const mbedtls_oid_descriptor_t *) p;             \\\n    if( p == NULL || oid == NULL ) return( NULL );                          \\\n    while( cur->asn1 != NULL ) {                                            \\\n        if( cur->asn1_len == oid->len &&                                    \\\n            memcmp( cur->asn1, oid->p, oid->len ) == 0 ) {                  \\\n            return( p );                                                    \\\n        }                                                                   \\\n        p++;                                                                \\\n        cur = (const mbedtls_oid_descriptor_t *) p;                                 \\\n    }                                                                       \\\n    return( NULL );                                                         \\\n}\n\n/*\n * Macro to generate a function for retrieving a single attribute from the\n * descriptor of an mbedtls_oid_descriptor_t wrapper.\n */\n#define FN_OID_GET_DESCRIPTOR_ATTR1(FN_NAME, TYPE_T, TYPE_NAME, ATTR1_TYPE, ATTR1) \\\nint FN_NAME( const mbedtls_asn1_buf *oid, ATTR1_TYPE * ATTR1 )                  \\\n{                                                                       \\\n    const TYPE_T *data = oid_ ## TYPE_NAME ## _from_asn1( oid );        \\\n    if( data == NULL ) return( MBEDTLS_ERR_OID_NOT_FOUND );            \\\n    *ATTR1 = data->descriptor.ATTR1;                                    \\\n    return( 0 );                                                        \\\n}\n\n/*\n * Macro to generate a function for retrieving a single attribute from an\n * mbedtls_oid_descriptor_t wrapper.\n */\n#define FN_OID_GET_ATTR1(FN_NAME, TYPE_T, TYPE_NAME, ATTR1_TYPE, ATTR1) \\\nint FN_NAME( const mbedtls_asn1_buf *oid, ATTR1_TYPE * ATTR1 )                  \\\n{                                                                       \\\n    const TYPE_T *data = oid_ ## TYPE_NAME ## _from_asn1( oid );        \\\n    if( data == NULL ) return( MBEDTLS_ERR_OID_NOT_FOUND );            \\\n    *ATTR1 = data->ATTR1;                                               \\\n    return( 0 );                                                        \\\n}\n\n/*\n * Macro to generate a function for retrieving two attributes from an\n * mbedtls_oid_descriptor_t wrapper.\n */\n#define FN_OID_GET_ATTR2(FN_NAME, TYPE_T, TYPE_NAME, ATTR1_TYPE, ATTR1,     \\\n                         ATTR2_TYPE, ATTR2)                                 \\\nint FN_NAME( const mbedtls_asn1_buf *oid, ATTR1_TYPE * ATTR1, ATTR2_TYPE * ATTR2 )  \\\n{                                                                           \\\n    const TYPE_T *data = oid_ ## TYPE_NAME ## _from_asn1( oid );            \\\n    if( data == NULL ) return( MBEDTLS_ERR_OID_NOT_FOUND );                \\\n    *ATTR1 = data->ATTR1;                                                   \\\n    *ATTR2 = data->ATTR2;                                                   \\\n    return( 0 );                                                            \\\n}\n\n/*\n * Macro to generate a function for retrieving the OID based on a single\n * attribute from a mbedtls_oid_descriptor_t wrapper.\n */\n#define FN_OID_GET_OID_BY_ATTR1(FN_NAME, TYPE_T, LIST, ATTR1_TYPE, ATTR1)   \\\nint FN_NAME( ATTR1_TYPE ATTR1, const char **oid, size_t *olen )             \\\n{                                                                           \\\n    const TYPE_T *cur = LIST;                                               \\\n    while( cur->descriptor.asn1 != NULL ) {                                 \\\n        if( cur->ATTR1 == ATTR1 ) {                                         \\\n            *oid = cur->descriptor.asn1;                                    \\\n            *olen = cur->descriptor.asn1_len;                               \\\n            return( 0 );                                                    \\\n        }                                                                   \\\n        cur++;                                                              \\\n    }                                                                       \\\n    return( MBEDTLS_ERR_OID_NOT_FOUND );                                   \\\n}\n\n/*\n * Macro to generate a function for retrieving the OID based on two\n * attributes from a mbedtls_oid_descriptor_t wrapper.\n */\n#define FN_OID_GET_OID_BY_ATTR2(FN_NAME, TYPE_T, LIST, ATTR1_TYPE, ATTR1,   \\\n                                ATTR2_TYPE, ATTR2)                          \\\nint FN_NAME( ATTR1_TYPE ATTR1, ATTR2_TYPE ATTR2, const char **oid ,         \\\n             size_t *olen )                                                 \\\n{                                                                           \\\n    const TYPE_T *cur = LIST;                                               \\\n    while( cur->descriptor.asn1 != NULL ) {                                 \\\n        if( cur->ATTR1 == ATTR1 && cur->ATTR2 == ATTR2 ) {                  \\\n            *oid = cur->descriptor.asn1;                                    \\\n            *olen = cur->descriptor.asn1_len;                               \\\n            return( 0 );                                                    \\\n        }                                                                   \\\n        cur++;                                                              \\\n    }                                                                       \\\n    return( MBEDTLS_ERR_OID_NOT_FOUND );                                   \\\n}\n\n#if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C)\n/*\n * For X520 attribute types\n */\ntypedef struct {\n    mbedtls_oid_descriptor_t    descriptor;\n    const char          *short_name;\n} oid_x520_attr_t;\n\nstatic const oid_x520_attr_t oid_x520_attr_type[] =\n{\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_CN ),          \"id-at-commonName\",               \"Common Name\" },\n        \"CN\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_COUNTRY ),     \"id-at-countryName\",              \"Country\" },\n        \"C\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_LOCALITY ),    \"id-at-locality\",                 \"Locality\" },\n        \"L\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_STATE ),       \"id-at-state\",                    \"State\" },\n        \"ST\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_ORGANIZATION ),\"id-at-organizationName\",         \"Organization\" },\n        \"O\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_ORG_UNIT ),    \"id-at-organizationalUnitName\",   \"Org Unit\" },\n        \"OU\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_PKCS9_EMAIL ),    \"emailAddress\",                   \"E-mail address\" },\n        \"emailAddress\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_SERIAL_NUMBER ),\"id-at-serialNumber\",            \"Serial number\" },\n        \"serialNumber\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_POSTAL_ADDRESS ),\"id-at-postalAddress\",          \"Postal address\" },\n        \"postalAddress\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_POSTAL_CODE ), \"id-at-postalCode\",               \"Postal code\" },\n        \"postalCode\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_SUR_NAME ),    \"id-at-surName\",                  \"Surname\" },\n        \"SN\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_GIVEN_NAME ),  \"id-at-givenName\",                \"Given name\" },\n        \"GN\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_INITIALS ),    \"id-at-initials\",                 \"Initials\" },\n        \"initials\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_GENERATION_QUALIFIER ), \"id-at-generationQualifier\", \"Generation qualifier\" },\n        \"generationQualifier\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_TITLE ),       \"id-at-title\",                    \"Title\" },\n        \"title\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_DN_QUALIFIER ),\"id-at-dnQualifier\",              \"Distinguished Name qualifier\" },\n        \"dnQualifier\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_PSEUDONYM ),   \"id-at-pseudonym\",                \"Pseudonym\" },\n        \"pseudonym\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_DOMAIN_COMPONENT ), \"id-domainComponent\",           \"Domain component\" },\n        \"DC\",\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_AT_UNIQUE_IDENTIFIER ), \"id-at-uniqueIdentifier\",    \"Unique Identifier\" },\n        \"uniqueIdentifier\",\n    },\n    {\n        { NULL, 0, NULL, NULL },\n        NULL,\n    }\n};\n\nFN_OID_TYPED_FROM_ASN1(oid_x520_attr_t, x520_attr, oid_x520_attr_type)\nFN_OID_GET_ATTR1(mbedtls_oid_get_attr_short_name, oid_x520_attr_t, x520_attr, const char *, short_name)\n\n/*\n * For X509 extensions\n */\ntypedef struct {\n    mbedtls_oid_descriptor_t    descriptor;\n    int                 ext_type;\n} oid_x509_ext_t;\n\nstatic const oid_x509_ext_t oid_x509_ext[] =\n{\n    {\n        { ADD_LEN( MBEDTLS_OID_BASIC_CONSTRAINTS ),    \"id-ce-basicConstraints\",   \"Basic Constraints\" },\n        MBEDTLS_X509_EXT_BASIC_CONSTRAINTS,\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_KEY_USAGE ),            \"id-ce-keyUsage\",           \"Key Usage\" },\n        MBEDTLS_X509_EXT_KEY_USAGE,\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_EXTENDED_KEY_USAGE ),   \"id-ce-extKeyUsage\",        \"Extended Key Usage\" },\n        MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE,\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_SUBJECT_ALT_NAME ),     \"id-ce-subjectAltName\",     \"Subject Alt Name\" },\n        MBEDTLS_X509_EXT_SUBJECT_ALT_NAME,\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_NS_CERT_TYPE ),         \"id-netscape-certtype\",     \"Netscape Certificate Type\" },\n        MBEDTLS_X509_EXT_NS_CERT_TYPE,\n    },\n    {\n        { NULL, 0, NULL, NULL },\n        0,\n    },\n};\n\nFN_OID_TYPED_FROM_ASN1(oid_x509_ext_t, x509_ext, oid_x509_ext)\nFN_OID_GET_ATTR1(mbedtls_oid_get_x509_ext_type, oid_x509_ext_t, x509_ext, int, ext_type)\n\nstatic const mbedtls_oid_descriptor_t oid_ext_key_usage[] =\n{\n    { ADD_LEN( MBEDTLS_OID_SERVER_AUTH ),      \"id-kp-serverAuth\",      \"TLS Web Server Authentication\" },\n    { ADD_LEN( MBEDTLS_OID_CLIENT_AUTH ),      \"id-kp-clientAuth\",      \"TLS Web Client Authentication\" },\n    { ADD_LEN( MBEDTLS_OID_CODE_SIGNING ),     \"id-kp-codeSigning\",     \"Code Signing\" },\n    { ADD_LEN( MBEDTLS_OID_EMAIL_PROTECTION ), \"id-kp-emailProtection\", \"E-mail Protection\" },\n    { ADD_LEN( MBEDTLS_OID_TIME_STAMPING ),    \"id-kp-timeStamping\",    \"Time Stamping\" },\n    { ADD_LEN( MBEDTLS_OID_OCSP_SIGNING ),     \"id-kp-OCSPSigning\",     \"OCSP Signing\" },\n    { NULL, 0, NULL, NULL },\n};\n\nFN_OID_TYPED_FROM_ASN1(mbedtls_oid_descriptor_t, ext_key_usage, oid_ext_key_usage)\nFN_OID_GET_ATTR1(mbedtls_oid_get_extended_key_usage, mbedtls_oid_descriptor_t, ext_key_usage, const char *, description)\n#endif /* MBEDTLS_X509_USE_C || MBEDTLS_X509_CREATE_C */\n\n#if defined(MBEDTLS_MD_C)\n/*\n * For SignatureAlgorithmIdentifier\n */\ntypedef struct {\n    mbedtls_oid_descriptor_t    descriptor;\n    mbedtls_md_type_t           md_alg;\n    mbedtls_pk_type_t           pk_alg;\n} oid_sig_alg_t;\n\nstatic const oid_sig_alg_t oid_sig_alg[] =\n{\n#if defined(MBEDTLS_RSA_C)\n#if defined(MBEDTLS_MD2_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_PKCS1_MD2 ),        \"md2WithRSAEncryption\",     \"RSA with MD2\" },\n        MBEDTLS_MD_MD2,      MBEDTLS_PK_RSA,\n    },\n#endif /* MBEDTLS_MD2_C */\n#if defined(MBEDTLS_MD4_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_PKCS1_MD4 ),        \"md4WithRSAEncryption\",     \"RSA with MD4\" },\n        MBEDTLS_MD_MD4,      MBEDTLS_PK_RSA,\n    },\n#endif /* MBEDTLS_MD4_C */\n#if defined(MBEDTLS_MD5_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_PKCS1_MD5 ),        \"md5WithRSAEncryption\",     \"RSA with MD5\" },\n        MBEDTLS_MD_MD5,      MBEDTLS_PK_RSA,\n    },\n#endif /* MBEDTLS_MD5_C */\n#if defined(MBEDTLS_SHA1_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_PKCS1_SHA1 ),       \"sha-1WithRSAEncryption\",   \"RSA with SHA1\" },\n        MBEDTLS_MD_SHA1,     MBEDTLS_PK_RSA,\n    },\n#endif /* MBEDTLS_SHA1_C */\n#if defined(MBEDTLS_SHA256_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_PKCS1_SHA224 ),     \"sha224WithRSAEncryption\",  \"RSA with SHA-224\" },\n        MBEDTLS_MD_SHA224,   MBEDTLS_PK_RSA,\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_PKCS1_SHA256 ),     \"sha256WithRSAEncryption\",  \"RSA with SHA-256\" },\n        MBEDTLS_MD_SHA256,   MBEDTLS_PK_RSA,\n    },\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_PKCS1_SHA384 ),     \"sha384WithRSAEncryption\",  \"RSA with SHA-384\" },\n        MBEDTLS_MD_SHA384,   MBEDTLS_PK_RSA,\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_PKCS1_SHA512 ),     \"sha512WithRSAEncryption\",  \"RSA with SHA-512\" },\n        MBEDTLS_MD_SHA512,   MBEDTLS_PK_RSA,\n    },\n#endif /* MBEDTLS_SHA512_C */\n#if defined(MBEDTLS_SHA1_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_RSA_SHA_OBS ),      \"sha-1WithRSAEncryption\",   \"RSA with SHA1\" },\n        MBEDTLS_MD_SHA1,     MBEDTLS_PK_RSA,\n    },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_RSA_C */\n#if defined(MBEDTLS_ECDSA_C)\n#if defined(MBEDTLS_SHA1_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_ECDSA_SHA1 ),       \"ecdsa-with-SHA1\",      \"ECDSA with SHA1\" },\n        MBEDTLS_MD_SHA1,     MBEDTLS_PK_ECDSA,\n    },\n#endif /* MBEDTLS_SHA1_C */\n#if defined(MBEDTLS_SHA256_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_ECDSA_SHA224 ),     \"ecdsa-with-SHA224\",    \"ECDSA with SHA224\" },\n        MBEDTLS_MD_SHA224,   MBEDTLS_PK_ECDSA,\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_ECDSA_SHA256 ),     \"ecdsa-with-SHA256\",    \"ECDSA with SHA256\" },\n        MBEDTLS_MD_SHA256,   MBEDTLS_PK_ECDSA,\n    },\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_ECDSA_SHA384 ),     \"ecdsa-with-SHA384\",    \"ECDSA with SHA384\" },\n        MBEDTLS_MD_SHA384,   MBEDTLS_PK_ECDSA,\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_ECDSA_SHA512 ),     \"ecdsa-with-SHA512\",    \"ECDSA with SHA512\" },\n        MBEDTLS_MD_SHA512,   MBEDTLS_PK_ECDSA,\n    },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_ECDSA_C */\n#if defined(MBEDTLS_RSA_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_RSASSA_PSS ),        \"RSASSA-PSS\",           \"RSASSA-PSS\" },\n        MBEDTLS_MD_NONE,     MBEDTLS_PK_RSASSA_PSS,\n    },\n#endif /* MBEDTLS_RSA_C */\n    {\n        { NULL, 0, NULL, NULL },\n        MBEDTLS_MD_NONE, MBEDTLS_PK_NONE,\n    },\n};\n\nFN_OID_TYPED_FROM_ASN1(oid_sig_alg_t, sig_alg, oid_sig_alg)\nFN_OID_GET_DESCRIPTOR_ATTR1(mbedtls_oid_get_sig_alg_desc, oid_sig_alg_t, sig_alg, const char *, description)\nFN_OID_GET_ATTR2(mbedtls_oid_get_sig_alg, oid_sig_alg_t, sig_alg, mbedtls_md_type_t, md_alg, mbedtls_pk_type_t, pk_alg)\nFN_OID_GET_OID_BY_ATTR2(mbedtls_oid_get_oid_by_sig_alg, oid_sig_alg_t, oid_sig_alg, mbedtls_pk_type_t, pk_alg, mbedtls_md_type_t, md_alg)\n#endif /* MBEDTLS_MD_C */\n\n/*\n * For PublicKeyInfo (PKCS1, RFC 5480)\n */\ntypedef struct {\n    mbedtls_oid_descriptor_t    descriptor;\n    mbedtls_pk_type_t           pk_alg;\n} oid_pk_alg_t;\n\nstatic const oid_pk_alg_t oid_pk_alg[] =\n{\n    {\n        { ADD_LEN( MBEDTLS_OID_PKCS1_RSA ),      \"rsaEncryption\",   \"RSA\" },\n        MBEDTLS_PK_RSA,\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_EC_ALG_UNRESTRICTED ),  \"id-ecPublicKey\",   \"Generic EC key\" },\n        MBEDTLS_PK_ECKEY,\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_EC_ALG_ECDH ),          \"id-ecDH\",          \"EC key for ECDH\" },\n        MBEDTLS_PK_ECKEY_DH,\n    },\n    {\n        { NULL, 0, NULL, NULL },\n        MBEDTLS_PK_NONE,\n    },\n};\n\nFN_OID_TYPED_FROM_ASN1(oid_pk_alg_t, pk_alg, oid_pk_alg)\nFN_OID_GET_ATTR1(mbedtls_oid_get_pk_alg, oid_pk_alg_t, pk_alg, mbedtls_pk_type_t, pk_alg)\nFN_OID_GET_OID_BY_ATTR1(mbedtls_oid_get_oid_by_pk_alg, oid_pk_alg_t, oid_pk_alg, mbedtls_pk_type_t, pk_alg)\n\n#if defined(MBEDTLS_ECP_C)\n/*\n * For namedCurve (RFC 5480)\n */\ntypedef struct {\n    mbedtls_oid_descriptor_t    descriptor;\n    mbedtls_ecp_group_id        grp_id;\n} oid_ecp_grp_t;\n\nstatic const oid_ecp_grp_t oid_ecp_grp[] =\n{\n#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)\n    {\n        { ADD_LEN( MBEDTLS_OID_EC_GRP_SECP192R1 ), \"secp192r1\",    \"secp192r1\" },\n        MBEDTLS_ECP_DP_SECP192R1,\n    },\n#endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)\n    {\n        { ADD_LEN( MBEDTLS_OID_EC_GRP_SECP224R1 ), \"secp224r1\",    \"secp224r1\" },\n        MBEDTLS_ECP_DP_SECP224R1,\n    },\n#endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)\n    {\n        { ADD_LEN( MBEDTLS_OID_EC_GRP_SECP256R1 ), \"secp256r1\",    \"secp256r1\" },\n        MBEDTLS_ECP_DP_SECP256R1,\n    },\n#endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)\n    {\n        { ADD_LEN( MBEDTLS_OID_EC_GRP_SECP384R1 ), \"secp384r1\",    \"secp384r1\" },\n        MBEDTLS_ECP_DP_SECP384R1,\n    },\n#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)\n    {\n        { ADD_LEN( MBEDTLS_OID_EC_GRP_SECP521R1 ), \"secp521r1\",    \"secp521r1\" },\n        MBEDTLS_ECP_DP_SECP521R1,\n    },\n#endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)\n    {\n        { ADD_LEN( MBEDTLS_OID_EC_GRP_SECP192K1 ), \"secp192k1\",    \"secp192k1\" },\n        MBEDTLS_ECP_DP_SECP192K1,\n    },\n#endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)\n    {\n        { ADD_LEN( MBEDTLS_OID_EC_GRP_SECP224K1 ), \"secp224k1\",    \"secp224k1\" },\n        MBEDTLS_ECP_DP_SECP224K1,\n    },\n#endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)\n    {\n        { ADD_LEN( MBEDTLS_OID_EC_GRP_SECP256K1 ), \"secp256k1\",    \"secp256k1\" },\n        MBEDTLS_ECP_DP_SECP256K1,\n    },\n#endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)\n    {\n        { ADD_LEN( MBEDTLS_OID_EC_GRP_BP256R1 ),   \"brainpoolP256r1\",\"brainpool256r1\" },\n        MBEDTLS_ECP_DP_BP256R1,\n    },\n#endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)\n    {\n        { ADD_LEN( MBEDTLS_OID_EC_GRP_BP384R1 ),   \"brainpoolP384r1\",\"brainpool384r1\" },\n        MBEDTLS_ECP_DP_BP384R1,\n    },\n#endif /* MBEDTLS_ECP_DP_BP384R1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)\n    {\n        { ADD_LEN( MBEDTLS_OID_EC_GRP_BP512R1 ),   \"brainpoolP512r1\",\"brainpool512r1\" },\n        MBEDTLS_ECP_DP_BP512R1,\n    },\n#endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */\n    {\n        { NULL, 0, NULL, NULL },\n        MBEDTLS_ECP_DP_NONE,\n    },\n};\n\nFN_OID_TYPED_FROM_ASN1(oid_ecp_grp_t, grp_id, oid_ecp_grp)\nFN_OID_GET_ATTR1(mbedtls_oid_get_ec_grp, oid_ecp_grp_t, grp_id, mbedtls_ecp_group_id, grp_id)\nFN_OID_GET_OID_BY_ATTR1(mbedtls_oid_get_oid_by_ec_grp, oid_ecp_grp_t, oid_ecp_grp, mbedtls_ecp_group_id, grp_id)\n#endif /* MBEDTLS_ECP_C */\n\n#if defined(MBEDTLS_CIPHER_C)\n/*\n * For PKCS#5 PBES2 encryption algorithm\n */\ntypedef struct {\n    mbedtls_oid_descriptor_t    descriptor;\n    mbedtls_cipher_type_t       cipher_alg;\n} oid_cipher_alg_t;\n\nstatic const oid_cipher_alg_t oid_cipher_alg[] =\n{\n    {\n        { ADD_LEN( MBEDTLS_OID_DES_CBC ),              \"desCBC\",       \"DES-CBC\" },\n        MBEDTLS_CIPHER_DES_CBC,\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_DES_EDE3_CBC ),         \"des-ede3-cbc\", \"DES-EDE3-CBC\" },\n        MBEDTLS_CIPHER_DES_EDE3_CBC,\n    },\n    {\n        { NULL, 0, NULL, NULL },\n        MBEDTLS_CIPHER_NONE,\n    },\n};\n\nFN_OID_TYPED_FROM_ASN1(oid_cipher_alg_t, cipher_alg, oid_cipher_alg)\nFN_OID_GET_ATTR1(mbedtls_oid_get_cipher_alg, oid_cipher_alg_t, cipher_alg, mbedtls_cipher_type_t, cipher_alg)\n#endif /* MBEDTLS_CIPHER_C */\n\n#if defined(MBEDTLS_MD_C)\n/*\n * For digestAlgorithm\n */\ntypedef struct {\n    mbedtls_oid_descriptor_t    descriptor;\n    mbedtls_md_type_t           md_alg;\n} oid_md_alg_t;\n\nstatic const oid_md_alg_t oid_md_alg[] =\n{\n#if defined(MBEDTLS_MD2_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_DIGEST_ALG_MD2 ),       \"id-md2\",       \"MD2\" },\n        MBEDTLS_MD_MD2,\n    },\n#endif /* MBEDTLS_MD2_C */\n#if defined(MBEDTLS_MD4_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_DIGEST_ALG_MD4 ),       \"id-md4\",       \"MD4\" },\n        MBEDTLS_MD_MD4,\n    },\n#endif /* MBEDTLS_MD4_C */\n#if defined(MBEDTLS_MD5_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_DIGEST_ALG_MD5 ),       \"id-md5\",       \"MD5\" },\n        MBEDTLS_MD_MD5,\n    },\n#endif /* MBEDTLS_MD5_C */\n#if defined(MBEDTLS_SHA1_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_DIGEST_ALG_SHA1 ),      \"id-sha1\",      \"SHA-1\" },\n        MBEDTLS_MD_SHA1,\n    },\n#endif /* MBEDTLS_SHA1_C */\n#if defined(MBEDTLS_SHA256_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_DIGEST_ALG_SHA224 ),    \"id-sha224\",    \"SHA-224\" },\n        MBEDTLS_MD_SHA224,\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_DIGEST_ALG_SHA256 ),    \"id-sha256\",    \"SHA-256\" },\n        MBEDTLS_MD_SHA256,\n    },\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_DIGEST_ALG_SHA384 ),    \"id-sha384\",    \"SHA-384\" },\n        MBEDTLS_MD_SHA384,\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_DIGEST_ALG_SHA512 ),    \"id-sha512\",    \"SHA-512\" },\n        MBEDTLS_MD_SHA512,\n    },\n#endif /* MBEDTLS_SHA512_C */\n    {\n        { NULL, 0, NULL, NULL },\n        MBEDTLS_MD_NONE,\n    },\n};\n\nFN_OID_TYPED_FROM_ASN1(oid_md_alg_t, md_alg, oid_md_alg)\nFN_OID_GET_ATTR1(mbedtls_oid_get_md_alg, oid_md_alg_t, md_alg, mbedtls_md_type_t, md_alg)\nFN_OID_GET_OID_BY_ATTR1(mbedtls_oid_get_oid_by_md, oid_md_alg_t, oid_md_alg, mbedtls_md_type_t, md_alg)\n\n/*\n * For HMAC digestAlgorithm\n */\ntypedef struct {\n    mbedtls_oid_descriptor_t    descriptor;\n    mbedtls_md_type_t           md_hmac;\n} oid_md_hmac_t;\n\nstatic const oid_md_hmac_t oid_md_hmac[] =\n{\n#if defined(MBEDTLS_SHA1_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_HMAC_SHA1 ),      \"hmacSHA1\",      \"HMAC-SHA-1\" },\n        MBEDTLS_MD_SHA1,\n    },\n#endif /* MBEDTLS_SHA1_C */\n#if defined(MBEDTLS_SHA256_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_HMAC_SHA224 ),    \"hmacSHA224\",    \"HMAC-SHA-224\" },\n        MBEDTLS_MD_SHA224,\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_HMAC_SHA256 ),    \"hmacSHA256\",    \"HMAC-SHA-256\" },\n        MBEDTLS_MD_SHA256,\n    },\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n    {\n        { ADD_LEN( MBEDTLS_OID_HMAC_SHA384 ),    \"hmacSHA384\",    \"HMAC-SHA-384\" },\n        MBEDTLS_MD_SHA384,\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_HMAC_SHA512 ),    \"hmacSHA512\",    \"HMAC-SHA-512\" },\n        MBEDTLS_MD_SHA512,\n    },\n#endif /* MBEDTLS_SHA512_C */\n    {\n        { NULL, 0, NULL, NULL },\n        MBEDTLS_MD_NONE,\n    },\n};\n\nFN_OID_TYPED_FROM_ASN1(oid_md_hmac_t, md_hmac, oid_md_hmac)\nFN_OID_GET_ATTR1(mbedtls_oid_get_md_hmac, oid_md_hmac_t, md_hmac, mbedtls_md_type_t, md_hmac)\n#endif /* MBEDTLS_MD_C */\n\n#if defined(MBEDTLS_PKCS12_C)\n/*\n * For PKCS#12 PBEs\n */\ntypedef struct {\n    mbedtls_oid_descriptor_t    descriptor;\n    mbedtls_md_type_t           md_alg;\n    mbedtls_cipher_type_t       cipher_alg;\n} oid_pkcs12_pbe_alg_t;\n\nstatic const oid_pkcs12_pbe_alg_t oid_pkcs12_pbe_alg[] =\n{\n    {\n        { ADD_LEN( MBEDTLS_OID_PKCS12_PBE_SHA1_DES3_EDE_CBC ), \"pbeWithSHAAnd3-KeyTripleDES-CBC\", \"PBE with SHA1 and 3-Key 3DES\" },\n        MBEDTLS_MD_SHA1,      MBEDTLS_CIPHER_DES_EDE3_CBC,\n    },\n    {\n        { ADD_LEN( MBEDTLS_OID_PKCS12_PBE_SHA1_DES2_EDE_CBC ), \"pbeWithSHAAnd2-KeyTripleDES-CBC\", \"PBE with SHA1 and 2-Key 3DES\" },\n        MBEDTLS_MD_SHA1,      MBEDTLS_CIPHER_DES_EDE_CBC,\n    },\n    {\n        { NULL, 0, NULL, NULL },\n        MBEDTLS_MD_NONE, MBEDTLS_CIPHER_NONE,\n    },\n};\n\nFN_OID_TYPED_FROM_ASN1(oid_pkcs12_pbe_alg_t, pkcs12_pbe_alg, oid_pkcs12_pbe_alg)\nFN_OID_GET_ATTR2(mbedtls_oid_get_pkcs12_pbe_alg, oid_pkcs12_pbe_alg_t, pkcs12_pbe_alg, mbedtls_md_type_t, md_alg, mbedtls_cipher_type_t, cipher_alg)\n#endif /* MBEDTLS_PKCS12_C */\n\n#define OID_SAFE_SNPRINTF                               \\\n    do {                                                \\\n        if( ret < 0 || (size_t) ret >= n )              \\\n            return( MBEDTLS_ERR_OID_BUF_TOO_SMALL );    \\\n                                                        \\\n        n -= (size_t) ret;                              \\\n        p += (size_t) ret;                              \\\n    } while( 0 )\n\n/* Return the x.y.z.... style numeric string for the given OID */\nint mbedtls_oid_get_numeric_string( char *buf, size_t size,\n                            const mbedtls_asn1_buf *oid )\n{\n    int ret;\n    size_t i, n;\n    unsigned int value;\n    char *p;\n\n    p = buf;\n    n = size;\n\n    /* First byte contains first two dots */\n    if( oid->len > 0 )\n    {\n        ret = mbedtls_snprintf( p, n, \"%d.%d\", oid->p[0] / 40, oid->p[0] % 40 );\n        OID_SAFE_SNPRINTF;\n    }\n\n    value = 0;\n    for( i = 1; i < oid->len; i++ )\n    {\n        /* Prevent overflow in value. */\n        if( ( ( value << 7 ) >> 7 ) != value )\n            return( MBEDTLS_ERR_OID_BUF_TOO_SMALL );\n\n        value <<= 7;\n        value += oid->p[i] & 0x7F;\n\n        if( !( oid->p[i] & 0x80 ) )\n        {\n            /* Last byte */\n            ret = mbedtls_snprintf( p, n, \".%d\", value );\n            OID_SAFE_SNPRINTF;\n            value = 0;\n        }\n    }\n\n    return( (int) ( size - n ) );\n}\n\n#endif /* MBEDTLS_OID_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/padlock.c",
    "content": "/*\n *  VIA PadLock support functions\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  This implementation is based on the VIA PadLock Programming Guide:\n *\n *  http://www.via.com.tw/en/downloads/whitepapers/initiatives/padlock/\n *  programming_guide.pdf\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_PADLOCK_C)\n\n#include \"mbedtls/padlock.h\"\n\n#include <string.h>\n\n#ifndef asm\n#define asm __asm\n#endif\n\n#if defined(MBEDTLS_HAVE_X86)\n\n/*\n * PadLock detection routine\n */\nint mbedtls_padlock_has_support( int feature )\n{\n    static int flags = -1;\n    int ebx = 0, edx = 0;\n\n    if( flags == -1 )\n    {\n        asm( \"movl  %%ebx, %0           \\n\\t\"\n             \"movl  $0xC0000000, %%eax  \\n\\t\"\n             \"cpuid                     \\n\\t\"\n             \"cmpl  $0xC0000001, %%eax  \\n\\t\"\n             \"movl  $0, %%edx           \\n\\t\"\n             \"jb    unsupported         \\n\\t\"\n             \"movl  $0xC0000001, %%eax  \\n\\t\"\n             \"cpuid                     \\n\\t\"\n             \"unsupported:              \\n\\t\"\n             \"movl  %%edx, %1           \\n\\t\"\n             \"movl  %2, %%ebx           \\n\\t\"\n             : \"=m\" (ebx), \"=m\" (edx)\n             :  \"m\" (ebx)\n             : \"eax\", \"ecx\", \"edx\" );\n\n        flags = edx;\n    }\n\n    return( flags & feature );\n}\n\n/*\n * PadLock AES-ECB block en(de)cryption\n */\nint mbedtls_padlock_xcryptecb( mbedtls_aes_context *ctx,\n                       int mode,\n                       const unsigned char input[16],\n                       unsigned char output[16] )\n{\n    int ebx = 0;\n    uint32_t *rk;\n    uint32_t *blk;\n    uint32_t *ctrl;\n    unsigned char buf[256];\n\n    rk  = ctx->rk;\n    blk = MBEDTLS_PADLOCK_ALIGN16( buf );\n    memcpy( blk, input, 16 );\n\n     ctrl = blk + 4;\n    *ctrl = 0x80 | ctx->nr | ( ( ctx->nr + ( mode^1 ) - 10 ) << 9 );\n\n    asm( \"pushfl                        \\n\\t\"\n         \"popfl                         \\n\\t\"\n         \"movl    %%ebx, %0             \\n\\t\"\n         \"movl    $1, %%ecx             \\n\\t\"\n         \"movl    %2, %%edx             \\n\\t\"\n         \"movl    %3, %%ebx             \\n\\t\"\n         \"movl    %4, %%esi             \\n\\t\"\n         \"movl    %4, %%edi             \\n\\t\"\n         \".byte  0xf3,0x0f,0xa7,0xc8    \\n\\t\"\n         \"movl    %1, %%ebx             \\n\\t\"\n         : \"=m\" (ebx)\n         :  \"m\" (ebx), \"m\" (ctrl), \"m\" (rk), \"m\" (blk)\n         : \"memory\", \"ecx\", \"edx\", \"esi\", \"edi\" );\n\n    memcpy( output, blk, 16 );\n\n    return( 0 );\n}\n\n/*\n * PadLock AES-CBC buffer en(de)cryption\n */\nint mbedtls_padlock_xcryptcbc( mbedtls_aes_context *ctx,\n                       int mode,\n                       size_t length,\n                       unsigned char iv[16],\n                       const unsigned char *input,\n                       unsigned char *output )\n{\n    int ebx = 0;\n    size_t count;\n    uint32_t *rk;\n    uint32_t *iw;\n    uint32_t *ctrl;\n    unsigned char buf[256];\n\n    if( ( (long) input  & 15 ) != 0 ||\n        ( (long) output & 15 ) != 0 )\n        return( MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED );\n\n    rk = ctx->rk;\n    iw = MBEDTLS_PADLOCK_ALIGN16( buf );\n    memcpy( iw, iv, 16 );\n\n     ctrl = iw + 4;\n    *ctrl = 0x80 | ctx->nr | ( ( ctx->nr + ( mode ^ 1 ) - 10 ) << 9 );\n\n    count = ( length + 15 ) >> 4;\n\n    asm( \"pushfl                        \\n\\t\"\n         \"popfl                         \\n\\t\"\n         \"movl    %%ebx, %0             \\n\\t\"\n         \"movl    %2, %%ecx             \\n\\t\"\n         \"movl    %3, %%edx             \\n\\t\"\n         \"movl    %4, %%ebx             \\n\\t\"\n         \"movl    %5, %%esi             \\n\\t\"\n         \"movl    %6, %%edi             \\n\\t\"\n         \"movl    %7, %%eax             \\n\\t\"\n         \".byte  0xf3,0x0f,0xa7,0xd0    \\n\\t\"\n         \"movl    %1, %%ebx             \\n\\t\"\n         : \"=m\" (ebx)\n         :  \"m\" (ebx), \"m\" (count), \"m\" (ctrl),\n            \"m\"  (rk), \"m\" (input), \"m\" (output), \"m\" (iw)\n         : \"memory\", \"eax\", \"ecx\", \"edx\", \"esi\", \"edi\" );\n\n    memcpy( iv, iw, 16 );\n\n    return( 0 );\n}\n\n#endif /* MBEDTLS_HAVE_X86 */\n\n#endif /* MBEDTLS_PADLOCK_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/pem.c",
    "content": "/*\n *  Privacy Enhanced Mail (PEM) decoding\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C)\n\n#include \"mbedtls/pem.h\"\n#include \"mbedtls/base64.h\"\n#include \"mbedtls/des.h\"\n#include \"mbedtls/aes.h\"\n#include \"mbedtls/md5.h\"\n#include \"mbedtls/cipher.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc    calloc\n#define mbedtls_free       free\n#endif\n\n#if defined(MBEDTLS_PEM_PARSE_C)\nvoid mbedtls_pem_init( mbedtls_pem_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_pem_context ) );\n}\n\n#if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) &&         \\\n    ( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) )\n/*\n * Read a 16-byte hex string and convert it to binary\n */\nstatic int pem_get_iv( const unsigned char *s, unsigned char *iv,\n                       size_t iv_len )\n{\n    size_t i, j, k;\n\n    memset( iv, 0, iv_len );\n\n    for( i = 0; i < iv_len * 2; i++, s++ )\n    {\n        if( *s >= '0' && *s <= '9' ) j = *s - '0'; else\n        if( *s >= 'A' && *s <= 'F' ) j = *s - '7'; else\n        if( *s >= 'a' && *s <= 'f' ) j = *s - 'W'; else\n            return( MBEDTLS_ERR_PEM_INVALID_ENC_IV );\n\n        k = ( ( i & 1 ) != 0 ) ? j : j << 4;\n\n        iv[i >> 1] = (unsigned char)( iv[i >> 1] | k );\n    }\n\n    return( 0 );\n}\n\nstatic int pem_pbkdf1( unsigned char *key, size_t keylen,\n                       unsigned char *iv,\n                       const unsigned char *pwd, size_t pwdlen )\n{\n    mbedtls_md5_context md5_ctx;\n    unsigned char md5sum[16];\n    size_t use_len;\n    int ret;\n\n    mbedtls_md5_init( &md5_ctx );\n\n    /*\n     * key[ 0..15] = MD5(pwd || IV)\n     */\n    if( ( ret = mbedtls_md5_starts_ret( &md5_ctx ) ) != 0 )\n        goto exit;\n    if( ( ret = mbedtls_md5_update_ret( &md5_ctx, pwd, pwdlen ) ) != 0 )\n        goto exit;\n    if( ( ret = mbedtls_md5_update_ret( &md5_ctx, iv,  8 ) ) != 0 )\n        goto exit;\n    if( ( ret = mbedtls_md5_finish_ret( &md5_ctx, md5sum ) ) != 0 )\n        goto exit;\n\n    if( keylen <= 16 )\n    {\n        memcpy( key, md5sum, keylen );\n        goto exit;\n    }\n\n    memcpy( key, md5sum, 16 );\n\n    /*\n     * key[16..23] = MD5(key[ 0..15] || pwd || IV])\n     */\n    if( ( ret = mbedtls_md5_starts_ret( &md5_ctx ) ) != 0 )\n        goto exit;\n    if( ( ret = mbedtls_md5_update_ret( &md5_ctx, md5sum, 16 ) ) != 0 )\n        goto exit;\n    if( ( ret = mbedtls_md5_update_ret( &md5_ctx, pwd, pwdlen ) ) != 0 )\n        goto exit;\n    if( ( ret = mbedtls_md5_update_ret( &md5_ctx, iv, 8 ) ) != 0 )\n        goto exit;\n    if( ( ret = mbedtls_md5_finish_ret( &md5_ctx, md5sum ) ) != 0 )\n        goto exit;\n\n    use_len = 16;\n    if( keylen < 32 )\n        use_len = keylen - 16;\n\n    memcpy( key + 16, md5sum, use_len );\n\nexit:\n    mbedtls_md5_free( &md5_ctx );\n    mbedtls_platform_zeroize( md5sum, 16 );\n\n    return( ret );\n}\n\n#if defined(MBEDTLS_DES_C)\n/*\n * Decrypt with DES-CBC, using PBKDF1 for key derivation\n */\nstatic int pem_des_decrypt( unsigned char des_iv[8],\n                            unsigned char *buf, size_t buflen,\n                            const unsigned char *pwd, size_t pwdlen )\n{\n    mbedtls_des_context des_ctx;\n    unsigned char des_key[8];\n    int ret;\n\n    mbedtls_des_init( &des_ctx );\n\n    if( ( ret = pem_pbkdf1( des_key, 8, des_iv, pwd, pwdlen ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_des_setkey_dec( &des_ctx, des_key ) ) != 0 )\n        goto exit;\n    ret = mbedtls_des_crypt_cbc( &des_ctx, MBEDTLS_DES_DECRYPT, buflen,\n                     des_iv, buf, buf );\n\nexit:\n    mbedtls_des_free( &des_ctx );\n    mbedtls_platform_zeroize( des_key, 8 );\n\n    return( ret );\n}\n\n/*\n * Decrypt with 3DES-CBC, using PBKDF1 for key derivation\n */\nstatic int pem_des3_decrypt( unsigned char des3_iv[8],\n                             unsigned char *buf, size_t buflen,\n                             const unsigned char *pwd, size_t pwdlen )\n{\n    mbedtls_des3_context des3_ctx;\n    unsigned char des3_key[24];\n    int ret;\n\n    mbedtls_des3_init( &des3_ctx );\n\n    if( ( ret = pem_pbkdf1( des3_key, 24, des3_iv, pwd, pwdlen ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_des3_set3key_dec( &des3_ctx, des3_key ) ) != 0 )\n        goto exit;\n    ret = mbedtls_des3_crypt_cbc( &des3_ctx, MBEDTLS_DES_DECRYPT, buflen,\n                     des3_iv, buf, buf );\n\nexit:\n    mbedtls_des3_free( &des3_ctx );\n    mbedtls_platform_zeroize( des3_key, 24 );\n\n    return( ret );\n}\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_AES_C)\n/*\n * Decrypt with AES-XXX-CBC, using PBKDF1 for key derivation\n */\nstatic int pem_aes_decrypt( unsigned char aes_iv[16], unsigned int keylen,\n                            unsigned char *buf, size_t buflen,\n                            const unsigned char *pwd, size_t pwdlen )\n{\n    mbedtls_aes_context aes_ctx;\n    unsigned char aes_key[32];\n    int ret;\n\n    mbedtls_aes_init( &aes_ctx );\n\n    if( ( ret = pem_pbkdf1( aes_key, keylen, aes_iv, pwd, pwdlen ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_aes_setkey_dec( &aes_ctx, aes_key, keylen * 8 ) ) != 0 )\n        goto exit;\n    ret = mbedtls_aes_crypt_cbc( &aes_ctx, MBEDTLS_AES_DECRYPT, buflen,\n                     aes_iv, buf, buf );\n\nexit:\n    mbedtls_aes_free( &aes_ctx );\n    mbedtls_platform_zeroize( aes_key, keylen );\n\n    return( ret );\n}\n#endif /* MBEDTLS_AES_C */\n\n#endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC &&\n          ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */\n\nint mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const char *footer,\n                     const unsigned char *data, const unsigned char *pwd,\n                     size_t pwdlen, size_t *use_len )\n{\n    int ret, enc;\n    size_t len;\n    unsigned char *buf;\n    const unsigned char *s1, *s2, *end;\n#if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) &&         \\\n    ( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) )\n    unsigned char pem_iv[16];\n    mbedtls_cipher_type_t enc_alg = MBEDTLS_CIPHER_NONE;\n#else\n    ((void) pwd);\n    ((void) pwdlen);\n#endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC &&\n          ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */\n\n    if( ctx == NULL )\n        return( MBEDTLS_ERR_PEM_BAD_INPUT_DATA );\n\n    s1 = (unsigned char *) strstr( (const char *) data, header );\n\n    if( s1 == NULL )\n        return( MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT );\n\n    s2 = (unsigned char *) strstr( (const char *) data, footer );\n\n    if( s2 == NULL || s2 <= s1 )\n        return( MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT );\n\n    s1 += strlen( header );\n    if( *s1 == ' '  ) s1++;\n    if( *s1 == '\\r' ) s1++;\n    if( *s1 == '\\n' ) s1++;\n    else return( MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT );\n\n    end = s2;\n    end += strlen( footer );\n    if( *end == ' '  ) end++;\n    if( *end == '\\r' ) end++;\n    if( *end == '\\n' ) end++;\n    *use_len = end - data;\n\n    enc = 0;\n\n    if( s2 - s1 >= 22 && memcmp( s1, \"Proc-Type: 4,ENCRYPTED\", 22 ) == 0 )\n    {\n#if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) &&         \\\n    ( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) )\n        enc++;\n\n        s1 += 22;\n        if( *s1 == '\\r' ) s1++;\n        if( *s1 == '\\n' ) s1++;\n        else return( MBEDTLS_ERR_PEM_INVALID_DATA );\n\n\n#if defined(MBEDTLS_DES_C)\n        if( s2 - s1 >= 23 && memcmp( s1, \"DEK-Info: DES-EDE3-CBC,\", 23 ) == 0 )\n        {\n            enc_alg = MBEDTLS_CIPHER_DES_EDE3_CBC;\n\n            s1 += 23;\n            if( s2 - s1 < 16 || pem_get_iv( s1, pem_iv, 8 ) != 0 )\n                return( MBEDTLS_ERR_PEM_INVALID_ENC_IV );\n\n            s1 += 16;\n        }\n        else if( s2 - s1 >= 18 && memcmp( s1, \"DEK-Info: DES-CBC,\", 18 ) == 0 )\n        {\n            enc_alg = MBEDTLS_CIPHER_DES_CBC;\n\n            s1 += 18;\n            if( s2 - s1 < 16 || pem_get_iv( s1, pem_iv, 8) != 0 )\n                return( MBEDTLS_ERR_PEM_INVALID_ENC_IV );\n\n            s1 += 16;\n        }\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_AES_C)\n        if( s2 - s1 >= 14 && memcmp( s1, \"DEK-Info: AES-\", 14 ) == 0 )\n        {\n            if( s2 - s1 < 22 )\n                return( MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG );\n            else if( memcmp( s1, \"DEK-Info: AES-128-CBC,\", 22 ) == 0 )\n                enc_alg = MBEDTLS_CIPHER_AES_128_CBC;\n            else if( memcmp( s1, \"DEK-Info: AES-192-CBC,\", 22 ) == 0 )\n                enc_alg = MBEDTLS_CIPHER_AES_192_CBC;\n            else if( memcmp( s1, \"DEK-Info: AES-256-CBC,\", 22 ) == 0 )\n                enc_alg = MBEDTLS_CIPHER_AES_256_CBC;\n            else\n                return( MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG );\n\n            s1 += 22;\n            if( s2 - s1 < 32 || pem_get_iv( s1, pem_iv, 16 ) != 0 )\n                return( MBEDTLS_ERR_PEM_INVALID_ENC_IV );\n\n            s1 += 32;\n        }\n#endif /* MBEDTLS_AES_C */\n\n        if( enc_alg == MBEDTLS_CIPHER_NONE )\n            return( MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG );\n\n        if( *s1 == '\\r' ) s1++;\n        if( *s1 == '\\n' ) s1++;\n        else return( MBEDTLS_ERR_PEM_INVALID_DATA );\n#else\n        return( MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE );\n#endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC &&\n          ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */\n    }\n\n    if( s1 >= s2 )\n        return( MBEDTLS_ERR_PEM_INVALID_DATA );\n\n    ret = mbedtls_base64_decode( NULL, 0, &len, s1, s2 - s1 );\n\n    if( ret == MBEDTLS_ERR_BASE64_INVALID_CHARACTER )\n        return( MBEDTLS_ERR_PEM_INVALID_DATA + ret );\n\n    if( ( buf = mbedtls_calloc( 1, len ) ) == NULL )\n        return( MBEDTLS_ERR_PEM_ALLOC_FAILED );\n\n    if( ( ret = mbedtls_base64_decode( buf, len, &len, s1, s2 - s1 ) ) != 0 )\n    {\n        mbedtls_platform_zeroize( buf, len );\n        mbedtls_free( buf );\n        return( MBEDTLS_ERR_PEM_INVALID_DATA + ret );\n    }\n\n    if( enc != 0 )\n    {\n#if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) &&         \\\n    ( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) )\n        if( pwd == NULL )\n        {\n            mbedtls_platform_zeroize( buf, len );\n            mbedtls_free( buf );\n            return( MBEDTLS_ERR_PEM_PASSWORD_REQUIRED );\n        }\n\n        ret = 0;\n\n#if defined(MBEDTLS_DES_C)\n        if( enc_alg == MBEDTLS_CIPHER_DES_EDE3_CBC )\n            ret = pem_des3_decrypt( pem_iv, buf, len, pwd, pwdlen );\n        else if( enc_alg == MBEDTLS_CIPHER_DES_CBC )\n            ret = pem_des_decrypt( pem_iv, buf, len, pwd, pwdlen );\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_AES_C)\n        if( enc_alg == MBEDTLS_CIPHER_AES_128_CBC )\n            ret = pem_aes_decrypt( pem_iv, 16, buf, len, pwd, pwdlen );\n        else if( enc_alg == MBEDTLS_CIPHER_AES_192_CBC )\n            ret = pem_aes_decrypt( pem_iv, 24, buf, len, pwd, pwdlen );\n        else if( enc_alg == MBEDTLS_CIPHER_AES_256_CBC )\n            ret = pem_aes_decrypt( pem_iv, 32, buf, len, pwd, pwdlen );\n#endif /* MBEDTLS_AES_C */\n\n        if( ret != 0 )\n        {\n            mbedtls_free( buf );\n            return( ret );\n        }\n\n        /*\n         * The result will be ASN.1 starting with a SEQUENCE tag, with 1 to 3\n         * length bytes (allow 4 to be sure) in all known use cases.\n         *\n         * Use that as a heuristic to try to detect password mismatches.\n         */\n        if( len <= 2 || buf[0] != 0x30 || buf[1] > 0x83 )\n        {\n            mbedtls_platform_zeroize( buf, len );\n            mbedtls_free( buf );\n            return( MBEDTLS_ERR_PEM_PASSWORD_MISMATCH );\n        }\n#else\n        mbedtls_platform_zeroize( buf, len );\n        mbedtls_free( buf );\n        return( MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE );\n#endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC &&\n          ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */\n    }\n\n    ctx->buf = buf;\n    ctx->buflen = len;\n\n    return( 0 );\n}\n\nvoid mbedtls_pem_free( mbedtls_pem_context *ctx )\n{\n    if( ctx->buf != NULL )\n        mbedtls_platform_zeroize( ctx->buf, ctx->buflen );\n    mbedtls_free( ctx->buf );\n    mbedtls_free( ctx->info );\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_pem_context ) );\n}\n#endif /* MBEDTLS_PEM_PARSE_C */\n\n#if defined(MBEDTLS_PEM_WRITE_C)\nint mbedtls_pem_write_buffer( const char *header, const char *footer,\n                      const unsigned char *der_data, size_t der_len,\n                      unsigned char *buf, size_t buf_len, size_t *olen )\n{\n    int ret;\n    unsigned char *encode_buf = NULL, *c, *p = buf;\n    size_t len = 0, use_len, add_len = 0;\n\n    mbedtls_base64_encode( NULL, 0, &use_len, der_data, der_len );\n    add_len = strlen( header ) + strlen( footer ) + ( use_len / 64 ) + 1;\n\n    if( use_len + add_len > buf_len )\n    {\n        *olen = use_len + add_len;\n        return( MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL );\n    }\n\n    if( use_len != 0 &&\n        ( ( encode_buf = mbedtls_calloc( 1, use_len ) ) == NULL ) )\n        return( MBEDTLS_ERR_PEM_ALLOC_FAILED );\n\n    if( ( ret = mbedtls_base64_encode( encode_buf, use_len, &use_len, der_data,\n                               der_len ) ) != 0 )\n    {\n        mbedtls_free( encode_buf );\n        return( ret );\n    }\n\n    memcpy( p, header, strlen( header ) );\n    p += strlen( header );\n    c = encode_buf;\n\n    while( use_len )\n    {\n        len = ( use_len > 64 ) ? 64 : use_len;\n        memcpy( p, c, len );\n        use_len -= len;\n        p += len;\n        c += len;\n        *p++ = '\\n';\n    }\n\n    memcpy( p, footer, strlen( footer ) );\n    p += strlen( footer );\n\n    *p++ = '\\0';\n    *olen = p - buf;\n\n    mbedtls_free( encode_buf );\n    return( 0 );\n}\n#endif /* MBEDTLS_PEM_WRITE_C */\n#endif /* MBEDTLS_PEM_PARSE_C || MBEDTLS_PEM_WRITE_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/pk.c",
    "content": "/*\n *  Public Key abstraction layer\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_PK_C)\n#include \"mbedtls/pk.h\"\n#include \"mbedtls/pk_internal.h\"\n\n#include \"mbedtls/platform_util.h\"\n\n#if defined(MBEDTLS_RSA_C)\n#include \"mbedtls/rsa.h\"\n#endif\n#if defined(MBEDTLS_ECP_C)\n#include \"mbedtls/ecp.h\"\n#endif\n#if defined(MBEDTLS_ECDSA_C)\n#include \"mbedtls/ecdsa.h\"\n#endif\n\n#include <limits.h>\n#include <stdint.h>\n\n/*\n * Initialise a mbedtls_pk_context\n */\nvoid mbedtls_pk_init( mbedtls_pk_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    ctx->pk_info = NULL;\n    ctx->pk_ctx = NULL;\n}\n\n/*\n * Free (the components of) a mbedtls_pk_context\n */\nvoid mbedtls_pk_free( mbedtls_pk_context *ctx )\n{\n    if( ctx == NULL || ctx->pk_info == NULL )\n        return;\n\n    ctx->pk_info->ctx_free_func( ctx->pk_ctx );\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_pk_context ) );\n}\n\n/*\n * Get pk_info structure from type\n */\nconst mbedtls_pk_info_t * mbedtls_pk_info_from_type( mbedtls_pk_type_t pk_type )\n{\n    switch( pk_type ) {\n#if defined(MBEDTLS_RSA_C)\n        case MBEDTLS_PK_RSA:\n            return( &mbedtls_rsa_info );\n#endif\n#if defined(MBEDTLS_ECP_C)\n        case MBEDTLS_PK_ECKEY:\n            return( &mbedtls_eckey_info );\n        case MBEDTLS_PK_ECKEY_DH:\n            return( &mbedtls_eckeydh_info );\n#endif\n#if defined(MBEDTLS_ECDSA_C)\n        case MBEDTLS_PK_ECDSA:\n            return( &mbedtls_ecdsa_info );\n#endif\n        /* MBEDTLS_PK_RSA_ALT omitted on purpose */\n        default:\n            return( NULL );\n    }\n}\n\n/*\n * Initialise context\n */\nint mbedtls_pk_setup( mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info )\n{\n    if( ctx == NULL || info == NULL || ctx->pk_info != NULL )\n        return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );\n\n    if( ( ctx->pk_ctx = info->ctx_alloc_func() ) == NULL )\n        return( MBEDTLS_ERR_PK_ALLOC_FAILED );\n\n    ctx->pk_info = info;\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)\n/*\n * Initialize an RSA-alt context\n */\nint mbedtls_pk_setup_rsa_alt( mbedtls_pk_context *ctx, void * key,\n                         mbedtls_pk_rsa_alt_decrypt_func decrypt_func,\n                         mbedtls_pk_rsa_alt_sign_func sign_func,\n                         mbedtls_pk_rsa_alt_key_len_func key_len_func )\n{\n    mbedtls_rsa_alt_context *rsa_alt;\n    const mbedtls_pk_info_t *info = &mbedtls_rsa_alt_info;\n\n    if( ctx == NULL || ctx->pk_info != NULL )\n        return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );\n\n    if( ( ctx->pk_ctx = info->ctx_alloc_func() ) == NULL )\n        return( MBEDTLS_ERR_PK_ALLOC_FAILED );\n\n    ctx->pk_info = info;\n\n    rsa_alt = (mbedtls_rsa_alt_context *) ctx->pk_ctx;\n\n    rsa_alt->key = key;\n    rsa_alt->decrypt_func = decrypt_func;\n    rsa_alt->sign_func = sign_func;\n    rsa_alt->key_len_func = key_len_func;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */\n\n/*\n * Tell if a PK can do the operations of the given type\n */\nint mbedtls_pk_can_do( const mbedtls_pk_context *ctx, mbedtls_pk_type_t type )\n{\n    /* null or NONE context can't do anything */\n    if( ctx == NULL || ctx->pk_info == NULL )\n        return( 0 );\n\n    return( ctx->pk_info->can_do( type ) );\n}\n\n/*\n * Helper for mbedtls_pk_sign and mbedtls_pk_verify\n */\nstatic inline int pk_hashlen_helper( mbedtls_md_type_t md_alg, size_t *hash_len )\n{\n    const mbedtls_md_info_t *md_info;\n\n    if( *hash_len != 0 )\n        return( 0 );\n\n    if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL )\n        return( -1 );\n\n    *hash_len = mbedtls_md_get_size( md_info );\n    return( 0 );\n}\n\n/*\n * Verify a signature\n */\nint mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,\n               const unsigned char *hash, size_t hash_len,\n               const unsigned char *sig, size_t sig_len )\n{\n    if( ctx == NULL || ctx->pk_info == NULL ||\n        pk_hashlen_helper( md_alg, &hash_len ) != 0 )\n        return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );\n\n    if( ctx->pk_info->verify_func == NULL )\n        return( MBEDTLS_ERR_PK_TYPE_MISMATCH );\n\n    return( ctx->pk_info->verify_func( ctx->pk_ctx, md_alg, hash, hash_len,\n                                       sig, sig_len ) );\n}\n\n/*\n * Verify a signature with options\n */\nint mbedtls_pk_verify_ext( mbedtls_pk_type_t type, const void *options,\n                   mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,\n                   const unsigned char *hash, size_t hash_len,\n                   const unsigned char *sig, size_t sig_len )\n{\n    if( ctx == NULL || ctx->pk_info == NULL )\n        return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );\n\n    if( ! mbedtls_pk_can_do( ctx, type ) )\n        return( MBEDTLS_ERR_PK_TYPE_MISMATCH );\n\n    if( type == MBEDTLS_PK_RSASSA_PSS )\n    {\n#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PKCS1_V21)\n        int ret;\n        const mbedtls_pk_rsassa_pss_options *pss_opts;\n\n#if SIZE_MAX > UINT_MAX\n        if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len )\n            return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );\n#endif /* SIZE_MAX > UINT_MAX */\n\n        if( options == NULL )\n            return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );\n\n        pss_opts = (const mbedtls_pk_rsassa_pss_options *) options;\n\n        if( sig_len < mbedtls_pk_get_len( ctx ) )\n            return( MBEDTLS_ERR_RSA_VERIFY_FAILED );\n\n        ret = mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_pk_rsa( *ctx ),\n                NULL, NULL, MBEDTLS_RSA_PUBLIC,\n                md_alg, (unsigned int) hash_len, hash,\n                pss_opts->mgf1_hash_id,\n                pss_opts->expected_salt_len,\n                sig );\n        if( ret != 0 )\n            return( ret );\n\n        if( sig_len > mbedtls_pk_get_len( ctx ) )\n            return( MBEDTLS_ERR_PK_SIG_LEN_MISMATCH );\n\n        return( 0 );\n#else\n        return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );\n#endif /* MBEDTLS_RSA_C && MBEDTLS_PKCS1_V21 */\n    }\n\n    /* General case: no options */\n    if( options != NULL )\n        return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );\n\n    return( mbedtls_pk_verify( ctx, md_alg, hash, hash_len, sig, sig_len ) );\n}\n\n/*\n * Make a signature\n */\nint mbedtls_pk_sign( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,\n             const unsigned char *hash, size_t hash_len,\n             unsigned char *sig, size_t *sig_len,\n             int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    if( ctx == NULL || ctx->pk_info == NULL ||\n        pk_hashlen_helper( md_alg, &hash_len ) != 0 )\n        return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );\n\n    if( ctx->pk_info->sign_func == NULL )\n        return( MBEDTLS_ERR_PK_TYPE_MISMATCH );\n\n    return( ctx->pk_info->sign_func( ctx->pk_ctx, md_alg, hash, hash_len,\n                                     sig, sig_len, f_rng, p_rng ) );\n}\n\n/*\n * Decrypt message\n */\nint mbedtls_pk_decrypt( mbedtls_pk_context *ctx,\n                const unsigned char *input, size_t ilen,\n                unsigned char *output, size_t *olen, size_t osize,\n                int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    if( ctx == NULL || ctx->pk_info == NULL )\n        return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );\n\n    if( ctx->pk_info->decrypt_func == NULL )\n        return( MBEDTLS_ERR_PK_TYPE_MISMATCH );\n\n    return( ctx->pk_info->decrypt_func( ctx->pk_ctx, input, ilen,\n                output, olen, osize, f_rng, p_rng ) );\n}\n\n/*\n * Encrypt message\n */\nint mbedtls_pk_encrypt( mbedtls_pk_context *ctx,\n                const unsigned char *input, size_t ilen,\n                unsigned char *output, size_t *olen, size_t osize,\n                int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    if( ctx == NULL || ctx->pk_info == NULL )\n        return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );\n\n    if( ctx->pk_info->encrypt_func == NULL )\n        return( MBEDTLS_ERR_PK_TYPE_MISMATCH );\n\n    return( ctx->pk_info->encrypt_func( ctx->pk_ctx, input, ilen,\n                output, olen, osize, f_rng, p_rng ) );\n}\n\n/*\n * Check public-private key pair\n */\nint mbedtls_pk_check_pair( const mbedtls_pk_context *pub, const mbedtls_pk_context *prv )\n{\n    if( pub == NULL || pub->pk_info == NULL ||\n        prv == NULL || prv->pk_info == NULL ||\n        prv->pk_info->check_pair_func == NULL )\n    {\n        return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );\n    }\n\n    if( prv->pk_info->type == MBEDTLS_PK_RSA_ALT )\n    {\n        if( pub->pk_info->type != MBEDTLS_PK_RSA )\n            return( MBEDTLS_ERR_PK_TYPE_MISMATCH );\n    }\n    else\n    {\n        if( pub->pk_info != prv->pk_info )\n            return( MBEDTLS_ERR_PK_TYPE_MISMATCH );\n    }\n\n    return( prv->pk_info->check_pair_func( pub->pk_ctx, prv->pk_ctx ) );\n}\n\n/*\n * Get key size in bits\n */\nsize_t mbedtls_pk_get_bitlen( const mbedtls_pk_context *ctx )\n{\n    if( ctx == NULL || ctx->pk_info == NULL )\n        return( 0 );\n\n    return( ctx->pk_info->get_bitlen( ctx->pk_ctx ) );\n}\n\n/*\n * Export debug information\n */\nint mbedtls_pk_debug( const mbedtls_pk_context *ctx, mbedtls_pk_debug_item *items )\n{\n    if( ctx == NULL || ctx->pk_info == NULL )\n        return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );\n\n    if( ctx->pk_info->debug_func == NULL )\n        return( MBEDTLS_ERR_PK_TYPE_MISMATCH );\n\n    ctx->pk_info->debug_func( ctx->pk_ctx, items );\n    return( 0 );\n}\n\n/*\n * Access the PK type name\n */\nconst char *mbedtls_pk_get_name( const mbedtls_pk_context *ctx )\n{\n    if( ctx == NULL || ctx->pk_info == NULL )\n        return( \"invalid PK\" );\n\n    return( ctx->pk_info->name );\n}\n\n/*\n * Access the PK type\n */\nmbedtls_pk_type_t mbedtls_pk_get_type( const mbedtls_pk_context *ctx )\n{\n    if( ctx == NULL || ctx->pk_info == NULL )\n        return( MBEDTLS_PK_NONE );\n\n    return( ctx->pk_info->type );\n}\n\n#endif /* MBEDTLS_PK_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/pk_wrap.c",
    "content": "/*\n *  Public Key abstraction layer: wrapper functions\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_PK_C)\n#include \"mbedtls/pk_internal.h\"\n\n/* Even if RSA not activated, for the sake of RSA-alt */\n#include \"mbedtls/rsa.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_ECP_C)\n#include \"mbedtls/ecp.h\"\n#endif\n\n#if defined(MBEDTLS_ECDSA_C)\n#include \"mbedtls/ecdsa.h\"\n#endif\n\n#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)\n#include \"mbedtls/platform_util.h\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc    calloc\n#define mbedtls_free       free\n#endif\n\n#include <limits.h>\n#include <stdint.h>\n\n#if defined(MBEDTLS_RSA_C)\nstatic int rsa_can_do( mbedtls_pk_type_t type )\n{\n    return( type == MBEDTLS_PK_RSA ||\n            type == MBEDTLS_PK_RSASSA_PSS );\n}\n\nstatic size_t rsa_get_bitlen( const void *ctx )\n{\n    const mbedtls_rsa_context * rsa = (const mbedtls_rsa_context *) ctx;\n    return( 8 * mbedtls_rsa_get_len( rsa ) );\n}\n\nstatic int rsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg,\n                   const unsigned char *hash, size_t hash_len,\n                   const unsigned char *sig, size_t sig_len )\n{\n    int ret;\n    mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx;\n    size_t rsa_len = mbedtls_rsa_get_len( rsa );\n\n#if SIZE_MAX > UINT_MAX\n    if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len )\n        return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );\n#endif /* SIZE_MAX > UINT_MAX */\n\n    if( sig_len < rsa_len )\n        return( MBEDTLS_ERR_RSA_VERIFY_FAILED );\n\n    if( ( ret = mbedtls_rsa_pkcs1_verify( rsa, NULL, NULL,\n                                  MBEDTLS_RSA_PUBLIC, md_alg,\n                                  (unsigned int) hash_len, hash, sig ) ) != 0 )\n        return( ret );\n\n    /* The buffer contains a valid signature followed by extra data.\n     * We have a special error code for that so that so that callers can\n     * use mbedtls_pk_verify() to check \"Does the buffer start with a\n     * valid signature?\" and not just \"Does the buffer contain a valid\n     * signature?\". */\n    if( sig_len > rsa_len )\n        return( MBEDTLS_ERR_PK_SIG_LEN_MISMATCH );\n\n    return( 0 );\n}\n\nstatic int rsa_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,\n                   const unsigned char *hash, size_t hash_len,\n                   unsigned char *sig, size_t *sig_len,\n                   int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx;\n\n#if SIZE_MAX > UINT_MAX\n    if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len )\n        return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );\n#endif /* SIZE_MAX > UINT_MAX */\n\n    *sig_len = mbedtls_rsa_get_len( rsa );\n\n    return( mbedtls_rsa_pkcs1_sign( rsa, f_rng, p_rng, MBEDTLS_RSA_PRIVATE,\n                md_alg, (unsigned int) hash_len, hash, sig ) );\n}\n\nstatic int rsa_decrypt_wrap( void *ctx,\n                    const unsigned char *input, size_t ilen,\n                    unsigned char *output, size_t *olen, size_t osize,\n                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx;\n\n    if( ilen != mbedtls_rsa_get_len( rsa ) )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    return( mbedtls_rsa_pkcs1_decrypt( rsa, f_rng, p_rng,\n                MBEDTLS_RSA_PRIVATE, olen, input, output, osize ) );\n}\n\nstatic int rsa_encrypt_wrap( void *ctx,\n                    const unsigned char *input, size_t ilen,\n                    unsigned char *output, size_t *olen, size_t osize,\n                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx;\n    *olen = mbedtls_rsa_get_len( rsa );\n\n    if( *olen > osize )\n        return( MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE );\n\n    return( mbedtls_rsa_pkcs1_encrypt( rsa, f_rng, p_rng, MBEDTLS_RSA_PUBLIC,\n                                       ilen, input, output ) );\n}\n\nstatic int rsa_check_pair_wrap( const void *pub, const void *prv )\n{\n    return( mbedtls_rsa_check_pub_priv( (const mbedtls_rsa_context *) pub,\n                                (const mbedtls_rsa_context *) prv ) );\n}\n\nstatic void *rsa_alloc_wrap( void )\n{\n    void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_rsa_context ) );\n\n    if( ctx != NULL )\n        mbedtls_rsa_init( (mbedtls_rsa_context *) ctx, 0, 0 );\n\n    return( ctx );\n}\n\nstatic void rsa_free_wrap( void *ctx )\n{\n    mbedtls_rsa_free( (mbedtls_rsa_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic void rsa_debug( const void *ctx, mbedtls_pk_debug_item *items )\n{\n    items->type = MBEDTLS_PK_DEBUG_MPI;\n    items->name = \"rsa.N\";\n    items->value = &( ((mbedtls_rsa_context *) ctx)->N );\n\n    items++;\n\n    items->type = MBEDTLS_PK_DEBUG_MPI;\n    items->name = \"rsa.E\";\n    items->value = &( ((mbedtls_rsa_context *) ctx)->E );\n}\n\nconst mbedtls_pk_info_t mbedtls_rsa_info = {\n    MBEDTLS_PK_RSA,\n    \"RSA\",\n    rsa_get_bitlen,\n    rsa_can_do,\n    rsa_verify_wrap,\n    rsa_sign_wrap,\n    rsa_decrypt_wrap,\n    rsa_encrypt_wrap,\n    rsa_check_pair_wrap,\n    rsa_alloc_wrap,\n    rsa_free_wrap,\n    rsa_debug,\n};\n#endif /* MBEDTLS_RSA_C */\n\n#if defined(MBEDTLS_ECP_C)\n/*\n * Generic EC key\n */\nstatic int eckey_can_do( mbedtls_pk_type_t type )\n{\n    return( type == MBEDTLS_PK_ECKEY ||\n            type == MBEDTLS_PK_ECKEY_DH ||\n            type == MBEDTLS_PK_ECDSA );\n}\n\nstatic size_t eckey_get_bitlen( const void *ctx )\n{\n    return( ((mbedtls_ecp_keypair *) ctx)->grp.pbits );\n}\n\n#if defined(MBEDTLS_ECDSA_C)\n/* Forward declarations */\nstatic int ecdsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg,\n                       const unsigned char *hash, size_t hash_len,\n                       const unsigned char *sig, size_t sig_len );\n\nstatic int ecdsa_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,\n                   const unsigned char *hash, size_t hash_len,\n                   unsigned char *sig, size_t *sig_len,\n                   int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );\n\nstatic int eckey_verify_wrap( void *ctx, mbedtls_md_type_t md_alg,\n                       const unsigned char *hash, size_t hash_len,\n                       const unsigned char *sig, size_t sig_len )\n{\n    int ret;\n    mbedtls_ecdsa_context ecdsa;\n\n    mbedtls_ecdsa_init( &ecdsa );\n\n    if( ( ret = mbedtls_ecdsa_from_keypair( &ecdsa, ctx ) ) == 0 )\n        ret = ecdsa_verify_wrap( &ecdsa, md_alg, hash, hash_len, sig, sig_len );\n\n    mbedtls_ecdsa_free( &ecdsa );\n\n    return( ret );\n}\n\nstatic int eckey_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,\n                   const unsigned char *hash, size_t hash_len,\n                   unsigned char *sig, size_t *sig_len,\n                   int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    int ret;\n    mbedtls_ecdsa_context ecdsa;\n\n    mbedtls_ecdsa_init( &ecdsa );\n\n    if( ( ret = mbedtls_ecdsa_from_keypair( &ecdsa, ctx ) ) == 0 )\n        ret = ecdsa_sign_wrap( &ecdsa, md_alg, hash, hash_len, sig, sig_len,\n                               f_rng, p_rng );\n\n    mbedtls_ecdsa_free( &ecdsa );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_ECDSA_C */\n\nstatic int eckey_check_pair( const void *pub, const void *prv )\n{\n    return( mbedtls_ecp_check_pub_priv( (const mbedtls_ecp_keypair *) pub,\n                                (const mbedtls_ecp_keypair *) prv ) );\n}\n\nstatic void *eckey_alloc_wrap( void )\n{\n    void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ecp_keypair ) );\n\n    if( ctx != NULL )\n        mbedtls_ecp_keypair_init( ctx );\n\n    return( ctx );\n}\n\nstatic void eckey_free_wrap( void *ctx )\n{\n    mbedtls_ecp_keypair_free( (mbedtls_ecp_keypair *) ctx );\n    mbedtls_free( ctx );\n}\n\nstatic void eckey_debug( const void *ctx, mbedtls_pk_debug_item *items )\n{\n    items->type = MBEDTLS_PK_DEBUG_ECP;\n    items->name = \"eckey.Q\";\n    items->value = &( ((mbedtls_ecp_keypair *) ctx)->Q );\n}\n\nconst mbedtls_pk_info_t mbedtls_eckey_info = {\n    MBEDTLS_PK_ECKEY,\n    \"EC\",\n    eckey_get_bitlen,\n    eckey_can_do,\n#if defined(MBEDTLS_ECDSA_C)\n    eckey_verify_wrap,\n    eckey_sign_wrap,\n#else\n    NULL,\n    NULL,\n#endif\n    NULL,\n    NULL,\n    eckey_check_pair,\n    eckey_alloc_wrap,\n    eckey_free_wrap,\n    eckey_debug,\n};\n\n/*\n * EC key restricted to ECDH\n */\nstatic int eckeydh_can_do( mbedtls_pk_type_t type )\n{\n    return( type == MBEDTLS_PK_ECKEY ||\n            type == MBEDTLS_PK_ECKEY_DH );\n}\n\nconst mbedtls_pk_info_t mbedtls_eckeydh_info = {\n    MBEDTLS_PK_ECKEY_DH,\n    \"EC_DH\",\n    eckey_get_bitlen,         /* Same underlying key structure */\n    eckeydh_can_do,\n    NULL,\n    NULL,\n    NULL,\n    NULL,\n    eckey_check_pair,\n    eckey_alloc_wrap,       /* Same underlying key structure */\n    eckey_free_wrap,        /* Same underlying key structure */\n    eckey_debug,            /* Same underlying key structure */\n};\n#endif /* MBEDTLS_ECP_C */\n\n#if defined(MBEDTLS_ECDSA_C)\nstatic int ecdsa_can_do( mbedtls_pk_type_t type )\n{\n    return( type == MBEDTLS_PK_ECDSA );\n}\n\nstatic int ecdsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg,\n                       const unsigned char *hash, size_t hash_len,\n                       const unsigned char *sig, size_t sig_len )\n{\n    int ret;\n    ((void) md_alg);\n\n    ret = mbedtls_ecdsa_read_signature( (mbedtls_ecdsa_context *) ctx,\n                                hash, hash_len, sig, sig_len );\n\n    if( ret == MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH )\n        return( MBEDTLS_ERR_PK_SIG_LEN_MISMATCH );\n\n    return( ret );\n}\n\nstatic int ecdsa_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,\n                   const unsigned char *hash, size_t hash_len,\n                   unsigned char *sig, size_t *sig_len,\n                   int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    return( mbedtls_ecdsa_write_signature( (mbedtls_ecdsa_context *) ctx,\n                md_alg, hash, hash_len, sig, sig_len, f_rng, p_rng ) );\n}\n\nstatic void *ecdsa_alloc_wrap( void )\n{\n    void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ecdsa_context ) );\n\n    if( ctx != NULL )\n        mbedtls_ecdsa_init( (mbedtls_ecdsa_context *) ctx );\n\n    return( ctx );\n}\n\nstatic void ecdsa_free_wrap( void *ctx )\n{\n    mbedtls_ecdsa_free( (mbedtls_ecdsa_context *) ctx );\n    mbedtls_free( ctx );\n}\n\nconst mbedtls_pk_info_t mbedtls_ecdsa_info = {\n    MBEDTLS_PK_ECDSA,\n    \"ECDSA\",\n    eckey_get_bitlen,     /* Compatible key structures */\n    ecdsa_can_do,\n    ecdsa_verify_wrap,\n    ecdsa_sign_wrap,\n    NULL,\n    NULL,\n    eckey_check_pair,   /* Compatible key structures */\n    ecdsa_alloc_wrap,\n    ecdsa_free_wrap,\n    eckey_debug,        /* Compatible key structures */\n};\n#endif /* MBEDTLS_ECDSA_C */\n\n#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)\n/*\n * Support for alternative RSA-private implementations\n */\n\nstatic int rsa_alt_can_do( mbedtls_pk_type_t type )\n{\n    return( type == MBEDTLS_PK_RSA );\n}\n\nstatic size_t rsa_alt_get_bitlen( const void *ctx )\n{\n    const mbedtls_rsa_alt_context *rsa_alt = (const mbedtls_rsa_alt_context *) ctx;\n\n    return( 8 * rsa_alt->key_len_func( rsa_alt->key ) );\n}\n\nstatic int rsa_alt_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,\n                   const unsigned char *hash, size_t hash_len,\n                   unsigned char *sig, size_t *sig_len,\n                   int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    mbedtls_rsa_alt_context *rsa_alt = (mbedtls_rsa_alt_context *) ctx;\n\n#if SIZE_MAX > UINT_MAX\n    if( UINT_MAX < hash_len )\n        return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );\n#endif /* SIZE_MAX > UINT_MAX */\n\n    *sig_len = rsa_alt->key_len_func( rsa_alt->key );\n\n    return( rsa_alt->sign_func( rsa_alt->key, f_rng, p_rng, MBEDTLS_RSA_PRIVATE,\n                md_alg, (unsigned int) hash_len, hash, sig ) );\n}\n\nstatic int rsa_alt_decrypt_wrap( void *ctx,\n                    const unsigned char *input, size_t ilen,\n                    unsigned char *output, size_t *olen, size_t osize,\n                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    mbedtls_rsa_alt_context *rsa_alt = (mbedtls_rsa_alt_context *) ctx;\n\n    ((void) f_rng);\n    ((void) p_rng);\n\n    if( ilen != rsa_alt->key_len_func( rsa_alt->key ) )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    return( rsa_alt->decrypt_func( rsa_alt->key,\n                MBEDTLS_RSA_PRIVATE, olen, input, output, osize ) );\n}\n\n#if defined(MBEDTLS_RSA_C)\nstatic int rsa_alt_check_pair( const void *pub, const void *prv )\n{\n    unsigned char sig[MBEDTLS_MPI_MAX_SIZE];\n    unsigned char hash[32];\n    size_t sig_len = 0;\n    int ret;\n\n    if( rsa_alt_get_bitlen( prv ) != rsa_get_bitlen( pub ) )\n        return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );\n\n    memset( hash, 0x2a, sizeof( hash ) );\n\n    if( ( ret = rsa_alt_sign_wrap( (void *) prv, MBEDTLS_MD_NONE,\n                                   hash, sizeof( hash ),\n                                   sig, &sig_len, NULL, NULL ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    if( rsa_verify_wrap( (void *) pub, MBEDTLS_MD_NONE,\n                         hash, sizeof( hash ), sig, sig_len ) != 0 )\n    {\n        return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_RSA_C */\n\nstatic void *rsa_alt_alloc_wrap( void )\n{\n    void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_rsa_alt_context ) );\n\n    if( ctx != NULL )\n        memset( ctx, 0, sizeof( mbedtls_rsa_alt_context ) );\n\n    return( ctx );\n}\n\nstatic void rsa_alt_free_wrap( void *ctx )\n{\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_rsa_alt_context ) );\n    mbedtls_free( ctx );\n}\n\nconst mbedtls_pk_info_t mbedtls_rsa_alt_info = {\n    MBEDTLS_PK_RSA_ALT,\n    \"RSA-alt\",\n    rsa_alt_get_bitlen,\n    rsa_alt_can_do,\n    NULL,\n    rsa_alt_sign_wrap,\n    rsa_alt_decrypt_wrap,\n    NULL,\n#if defined(MBEDTLS_RSA_C)\n    rsa_alt_check_pair,\n#else\n    NULL,\n#endif\n    rsa_alt_alloc_wrap,\n    rsa_alt_free_wrap,\n    NULL,\n};\n\n#endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */\n\n#endif /* MBEDTLS_PK_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/pkcs11.c",
    "content": "/**\n * \\file pkcs11.c\n *\n * \\brief Wrapper for PKCS#11 library libpkcs11-helper\n *\n * \\author Adriaan de Jong <dejong@fox-it.com>\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#include \"mbedtls/pkcs11.h\"\n\n#if defined(MBEDTLS_PKCS11_C)\n\n#include \"mbedtls/md.h\"\n#include \"mbedtls/oid.h\"\n#include \"mbedtls/x509_crt.h\"\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc    calloc\n#define mbedtls_free       free\n#endif\n\n#include <string.h>\n\nvoid mbedtls_pkcs11_init( mbedtls_pkcs11_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_pkcs11_context ) );\n}\n\nint mbedtls_pkcs11_x509_cert_bind( mbedtls_x509_crt *cert, pkcs11h_certificate_t pkcs11_cert )\n{\n    int ret = 1;\n    unsigned char *cert_blob = NULL;\n    size_t cert_blob_size = 0;\n\n    if( cert == NULL )\n    {\n        ret = 2;\n        goto cleanup;\n    }\n\n    if( pkcs11h_certificate_getCertificateBlob( pkcs11_cert, NULL,\n                                                &cert_blob_size ) != CKR_OK )\n    {\n        ret = 3;\n        goto cleanup;\n    }\n\n    cert_blob = mbedtls_calloc( 1, cert_blob_size );\n    if( NULL == cert_blob )\n    {\n        ret = 4;\n        goto cleanup;\n    }\n\n    if( pkcs11h_certificate_getCertificateBlob( pkcs11_cert, cert_blob,\n                                                &cert_blob_size ) != CKR_OK )\n    {\n        ret = 5;\n        goto cleanup;\n    }\n\n    if( 0 != mbedtls_x509_crt_parse( cert, cert_blob, cert_blob_size ) )\n    {\n        ret = 6;\n        goto cleanup;\n    }\n\n    ret = 0;\n\ncleanup:\n    if( NULL != cert_blob )\n        mbedtls_free( cert_blob );\n\n    return( ret );\n}\n\n\nint mbedtls_pkcs11_priv_key_bind( mbedtls_pkcs11_context *priv_key,\n        pkcs11h_certificate_t pkcs11_cert )\n{\n    int ret = 1;\n    mbedtls_x509_crt cert;\n\n    mbedtls_x509_crt_init( &cert );\n\n    if( priv_key == NULL )\n        goto cleanup;\n\n    if( 0 != mbedtls_pkcs11_x509_cert_bind( &cert, pkcs11_cert ) )\n        goto cleanup;\n\n    priv_key->len = mbedtls_pk_get_len( &cert.pk );\n    priv_key->pkcs11h_cert = pkcs11_cert;\n\n    ret = 0;\n\ncleanup:\n    mbedtls_x509_crt_free( &cert );\n\n    return( ret );\n}\n\nvoid mbedtls_pkcs11_priv_key_free( mbedtls_pkcs11_context *priv_key )\n{\n    if( NULL != priv_key )\n        pkcs11h_certificate_freeCertificate( priv_key->pkcs11h_cert );\n}\n\nint mbedtls_pkcs11_decrypt( mbedtls_pkcs11_context *ctx,\n                       int mode, size_t *olen,\n                       const unsigned char *input,\n                       unsigned char *output,\n                       size_t output_max_len )\n{\n    size_t input_len, output_len;\n\n    if( NULL == ctx )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    if( MBEDTLS_RSA_PRIVATE != mode )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    output_len = input_len = ctx->len;\n\n    if( input_len < 16 || input_len > output_max_len )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    /* Determine size of output buffer */\n    if( pkcs11h_certificate_decryptAny( ctx->pkcs11h_cert, CKM_RSA_PKCS, input,\n            input_len, NULL, &output_len ) != CKR_OK )\n    {\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n    }\n\n    if( output_len > output_max_len )\n        return( MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE );\n\n    if( pkcs11h_certificate_decryptAny( ctx->pkcs11h_cert, CKM_RSA_PKCS, input,\n            input_len, output, &output_len ) != CKR_OK )\n    {\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n    }\n    *olen = output_len;\n    return( 0 );\n}\n\nint mbedtls_pkcs11_sign( mbedtls_pkcs11_context *ctx,\n                    int mode,\n                    mbedtls_md_type_t md_alg,\n                    unsigned int hashlen,\n                    const unsigned char *hash,\n                    unsigned char *sig )\n{\n    size_t sig_len = 0, asn_len = 0, oid_size = 0;\n    unsigned char *p = sig;\n    const char *oid;\n\n    if( NULL == ctx )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    if( MBEDTLS_RSA_PRIVATE != mode )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    if( md_alg != MBEDTLS_MD_NONE )\n    {\n        const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );\n        if( md_info == NULL )\n            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n        if( mbedtls_oid_get_oid_by_md( md_alg, &oid, &oid_size ) != 0 )\n            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n        hashlen = mbedtls_md_get_size( md_info );\n        asn_len = 10 + oid_size;\n    }\n\n    sig_len = ctx->len;\n    if( hashlen > sig_len || asn_len > sig_len ||\n        hashlen + asn_len > sig_len )\n    {\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n    }\n\n    if( md_alg != MBEDTLS_MD_NONE )\n    {\n        /*\n         * DigestInfo ::= SEQUENCE {\n         *   digestAlgorithm DigestAlgorithmIdentifier,\n         *   digest Digest }\n         *\n         * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n         *\n         * Digest ::= OCTET STRING\n         */\n        *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;\n        *p++ = (unsigned char) ( 0x08 + oid_size + hashlen );\n        *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;\n        *p++ = (unsigned char) ( 0x04 + oid_size );\n        *p++ = MBEDTLS_ASN1_OID;\n        *p++ = oid_size & 0xFF;\n        memcpy( p, oid, oid_size );\n        p += oid_size;\n        *p++ = MBEDTLS_ASN1_NULL;\n        *p++ = 0x00;\n        *p++ = MBEDTLS_ASN1_OCTET_STRING;\n        *p++ = hashlen;\n    }\n\n    memcpy( p, hash, hashlen );\n\n    if( pkcs11h_certificate_signAny( ctx->pkcs11h_cert, CKM_RSA_PKCS, sig,\n            asn_len + hashlen, sig, &sig_len ) != CKR_OK )\n    {\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n    }\n\n    return( 0 );\n}\n\n#endif /* defined(MBEDTLS_PKCS11_C) */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/pkcs12.c",
    "content": "/*\n *  PKCS#12 Personal Information Exchange Syntax\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The PKCS #12 Personal Information Exchange Syntax Standard v1.1\n *\n *  http://www.rsa.com/rsalabs/pkcs/files/h11301-wp-pkcs-12v1-1-personal-information-exchange-syntax.pdf\n *  ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1-1.asn\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_PKCS12_C)\n\n#include \"mbedtls/pkcs12.h\"\n#include \"mbedtls/asn1.h\"\n#include \"mbedtls/cipher.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_ARC4_C)\n#include \"mbedtls/arc4.h\"\n#endif\n\n#if defined(MBEDTLS_DES_C)\n#include \"mbedtls/des.h\"\n#endif\n\nstatic int pkcs12_parse_pbe_params( mbedtls_asn1_buf *params,\n                                    mbedtls_asn1_buf *salt, int *iterations )\n{\n    int ret;\n    unsigned char **p = &params->p;\n    const unsigned char *end = params->p + params->len;\n\n    /*\n     *  pkcs-12PbeParams ::= SEQUENCE {\n     *    salt          OCTET STRING,\n     *    iterations    INTEGER\n     *  }\n     *\n     */\n    if( params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )\n        return( MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &salt->len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )\n        return( MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT + ret );\n\n    salt->p = *p;\n    *p += salt->len;\n\n    if( ( ret = mbedtls_asn1_get_int( p, end, iterations ) ) != 0 )\n        return( MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT + ret );\n\n    if( *p != end )\n        return( MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    return( 0 );\n}\n\n#define PKCS12_MAX_PWDLEN 128\n\nstatic int pkcs12_pbe_derive_key_iv( mbedtls_asn1_buf *pbe_params, mbedtls_md_type_t md_type,\n                                     const unsigned char *pwd,  size_t pwdlen,\n                                     unsigned char *key, size_t keylen,\n                                     unsigned char *iv,  size_t ivlen )\n{\n    int ret, iterations = 0;\n    mbedtls_asn1_buf salt;\n    size_t i;\n    unsigned char unipwd[PKCS12_MAX_PWDLEN * 2 + 2];\n\n    if( pwdlen > PKCS12_MAX_PWDLEN )\n        return( MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA );\n\n    memset( &salt, 0, sizeof(mbedtls_asn1_buf) );\n    memset( &unipwd, 0, sizeof(unipwd) );\n\n    if( ( ret = pkcs12_parse_pbe_params( pbe_params, &salt,\n                                         &iterations ) ) != 0 )\n        return( ret );\n\n    for( i = 0; i < pwdlen; i++ )\n        unipwd[i * 2 + 1] = pwd[i];\n\n    if( ( ret = mbedtls_pkcs12_derivation( key, keylen, unipwd, pwdlen * 2 + 2,\n                                   salt.p, salt.len, md_type,\n                                   MBEDTLS_PKCS12_DERIVE_KEY, iterations ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    if( iv == NULL || ivlen == 0 )\n        return( 0 );\n\n    if( ( ret = mbedtls_pkcs12_derivation( iv, ivlen, unipwd, pwdlen * 2 + 2,\n                                   salt.p, salt.len, md_type,\n                                   MBEDTLS_PKCS12_DERIVE_IV, iterations ) ) != 0 )\n    {\n        return( ret );\n    }\n    return( 0 );\n}\n\n#undef PKCS12_MAX_PWDLEN\n\nint mbedtls_pkcs12_pbe_sha1_rc4_128( mbedtls_asn1_buf *pbe_params, int mode,\n                             const unsigned char *pwd,  size_t pwdlen,\n                             const unsigned char *data, size_t len,\n                             unsigned char *output )\n{\n#if !defined(MBEDTLS_ARC4_C)\n    ((void) pbe_params);\n    ((void) mode);\n    ((void) pwd);\n    ((void) pwdlen);\n    ((void) data);\n    ((void) len);\n    ((void) output);\n    return( MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE );\n#else\n    int ret;\n    unsigned char key[16];\n    mbedtls_arc4_context ctx;\n    ((void) mode);\n\n    mbedtls_arc4_init( &ctx );\n\n    if( ( ret = pkcs12_pbe_derive_key_iv( pbe_params, MBEDTLS_MD_SHA1,\n                                          pwd, pwdlen,\n                                          key, 16, NULL, 0 ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    mbedtls_arc4_setup( &ctx, key, 16 );\n    if( ( ret = mbedtls_arc4_crypt( &ctx, len, data, output ) ) != 0 )\n        goto exit;\n\nexit:\n    mbedtls_platform_zeroize( key, sizeof( key ) );\n    mbedtls_arc4_free( &ctx );\n\n    return( ret );\n#endif /* MBEDTLS_ARC4_C */\n}\n\nint mbedtls_pkcs12_pbe( mbedtls_asn1_buf *pbe_params, int mode,\n                mbedtls_cipher_type_t cipher_type, mbedtls_md_type_t md_type,\n                const unsigned char *pwd,  size_t pwdlen,\n                const unsigned char *data, size_t len,\n                unsigned char *output )\n{\n    int ret, keylen = 0;\n    unsigned char key[32];\n    unsigned char iv[16];\n    const mbedtls_cipher_info_t *cipher_info;\n    mbedtls_cipher_context_t cipher_ctx;\n    size_t olen = 0;\n\n    cipher_info = mbedtls_cipher_info_from_type( cipher_type );\n    if( cipher_info == NULL )\n        return( MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE );\n\n    keylen = cipher_info->key_bitlen / 8;\n\n    if( ( ret = pkcs12_pbe_derive_key_iv( pbe_params, md_type, pwd, pwdlen,\n                                          key, keylen,\n                                          iv, cipher_info->iv_size ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    mbedtls_cipher_init( &cipher_ctx );\n\n    if( ( ret = mbedtls_cipher_setup( &cipher_ctx, cipher_info ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_cipher_setkey( &cipher_ctx, key, 8 * keylen, (mbedtls_operation_t) mode ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_cipher_set_iv( &cipher_ctx, iv, cipher_info->iv_size ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_cipher_reset( &cipher_ctx ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_cipher_update( &cipher_ctx, data, len,\n                                output, &olen ) ) != 0 )\n    {\n        goto exit;\n    }\n\n    if( ( ret = mbedtls_cipher_finish( &cipher_ctx, output + olen, &olen ) ) != 0 )\n        ret = MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH;\n\nexit:\n    mbedtls_platform_zeroize( key, sizeof( key ) );\n    mbedtls_platform_zeroize( iv,  sizeof( iv  ) );\n    mbedtls_cipher_free( &cipher_ctx );\n\n    return( ret );\n}\n\nstatic void pkcs12_fill_buffer( unsigned char *data, size_t data_len,\n                                const unsigned char *filler, size_t fill_len )\n{\n    unsigned char *p = data;\n    size_t use_len;\n\n    while( data_len > 0 )\n    {\n        use_len = ( data_len > fill_len ) ? fill_len : data_len;\n        memcpy( p, filler, use_len );\n        p += use_len;\n        data_len -= use_len;\n    }\n}\n\nint mbedtls_pkcs12_derivation( unsigned char *data, size_t datalen,\n                       const unsigned char *pwd, size_t pwdlen,\n                       const unsigned char *salt, size_t saltlen,\n                       mbedtls_md_type_t md_type, int id, int iterations )\n{\n    int ret;\n    unsigned int j;\n\n    unsigned char diversifier[128];\n    unsigned char salt_block[128], pwd_block[128], hash_block[128];\n    unsigned char hash_output[MBEDTLS_MD_MAX_SIZE];\n    unsigned char *p;\n    unsigned char c;\n\n    size_t hlen, use_len, v, i;\n\n    const mbedtls_md_info_t *md_info;\n    mbedtls_md_context_t md_ctx;\n\n    // This version only allows max of 64 bytes of password or salt\n    if( datalen > 128 || pwdlen > 64 || saltlen > 64 )\n        return( MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA );\n\n    md_info = mbedtls_md_info_from_type( md_type );\n    if( md_info == NULL )\n        return( MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE );\n\n    mbedtls_md_init( &md_ctx );\n\n    if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )\n        return( ret );\n    hlen = mbedtls_md_get_size( md_info );\n\n    if( hlen <= 32 )\n        v = 64;\n    else\n        v = 128;\n\n    memset( diversifier, (unsigned char) id, v );\n\n    pkcs12_fill_buffer( salt_block, v, salt, saltlen );\n    pkcs12_fill_buffer( pwd_block,  v, pwd,  pwdlen  );\n\n    p = data;\n    while( datalen > 0 )\n    {\n        // Calculate hash( diversifier || salt_block || pwd_block )\n        if( ( ret = mbedtls_md_starts( &md_ctx ) ) != 0 )\n            goto exit;\n\n        if( ( ret = mbedtls_md_update( &md_ctx, diversifier, v ) ) != 0 )\n            goto exit;\n\n        if( ( ret = mbedtls_md_update( &md_ctx, salt_block, v ) ) != 0 )\n            goto exit;\n\n        if( ( ret = mbedtls_md_update( &md_ctx, pwd_block, v ) ) != 0 )\n            goto exit;\n\n        if( ( ret = mbedtls_md_finish( &md_ctx, hash_output ) ) != 0 )\n            goto exit;\n\n        // Perform remaining ( iterations - 1 ) recursive hash calculations\n        for( i = 1; i < (size_t) iterations; i++ )\n        {\n            if( ( ret = mbedtls_md( md_info, hash_output, hlen, hash_output ) ) != 0 )\n                goto exit;\n        }\n\n        use_len = ( datalen > hlen ) ? hlen : datalen;\n        memcpy( p, hash_output, use_len );\n        datalen -= use_len;\n        p += use_len;\n\n        if( datalen == 0 )\n            break;\n\n        // Concatenating copies of hash_output into hash_block (B)\n        pkcs12_fill_buffer( hash_block, v, hash_output, hlen );\n\n        // B += 1\n        for( i = v; i > 0; i-- )\n            if( ++hash_block[i - 1] != 0 )\n                break;\n\n        // salt_block += B\n        c = 0;\n        for( i = v; i > 0; i-- )\n        {\n            j = salt_block[i - 1] + hash_block[i - 1] + c;\n            c = (unsigned char) (j >> 8);\n            salt_block[i - 1] = j & 0xFF;\n        }\n\n        // pwd_block  += B\n        c = 0;\n        for( i = v; i > 0; i-- )\n        {\n            j = pwd_block[i - 1] + hash_block[i - 1] + c;\n            c = (unsigned char) (j >> 8);\n            pwd_block[i - 1] = j & 0xFF;\n        }\n    }\n\n    ret = 0;\n\nexit:\n    mbedtls_platform_zeroize( salt_block, sizeof( salt_block ) );\n    mbedtls_platform_zeroize( pwd_block, sizeof( pwd_block ) );\n    mbedtls_platform_zeroize( hash_block, sizeof( hash_block ) );\n    mbedtls_platform_zeroize( hash_output, sizeof( hash_output ) );\n\n    mbedtls_md_free( &md_ctx );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_PKCS12_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/pkcs5.c",
    "content": "/**\n * \\file pkcs5.c\n *\n * \\brief PKCS#5 functions\n *\n * \\author Mathias Olsson <mathias@kompetensum.com>\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n * PKCS#5 includes PBKDF2 and more\n *\n * http://tools.ietf.org/html/rfc2898 (Specification)\n * http://tools.ietf.org/html/rfc6070 (Test vectors)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_PKCS5_C)\n\n#include \"mbedtls/pkcs5.h\"\n\n#if defined(MBEDTLS_ASN1_PARSE_C)\n#include \"mbedtls/asn1.h\"\n#include \"mbedtls/cipher.h\"\n#include \"mbedtls/oid.h\"\n#endif /* MBEDTLS_ASN1_PARSE_C */\n\n#include <string.h>\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif\n\n#if !defined(MBEDTLS_ASN1_PARSE_C)\nint mbedtls_pkcs5_pbes2( const mbedtls_asn1_buf *pbe_params, int mode,\n                 const unsigned char *pwd,  size_t pwdlen,\n                 const unsigned char *data, size_t datalen,\n                 unsigned char *output )\n{\n    ((void) pbe_params);\n    ((void) mode);\n    ((void) pwd);\n    ((void) pwdlen);\n    ((void) data);\n    ((void) datalen);\n    ((void) output);\n    return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );\n}\n#else\nstatic int pkcs5_parse_pbkdf2_params( const mbedtls_asn1_buf *params,\n                                      mbedtls_asn1_buf *salt, int *iterations,\n                                      int *keylen, mbedtls_md_type_t *md_type )\n{\n    int ret;\n    mbedtls_asn1_buf prf_alg_oid;\n    unsigned char *p = params->p;\n    const unsigned char *end = params->p + params->len;\n\n    if( params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )\n        return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );\n    /*\n     *  PBKDF2-params ::= SEQUENCE {\n     *    salt              OCTET STRING,\n     *    iterationCount    INTEGER,\n     *    keyLength         INTEGER OPTIONAL\n     *    prf               AlgorithmIdentifier DEFAULT algid-hmacWithSHA1\n     *  }\n     *\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &salt->len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )\n        return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret );\n\n    salt->p = p;\n    p += salt->len;\n\n    if( ( ret = mbedtls_asn1_get_int( &p, end, iterations ) ) != 0 )\n        return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret );\n\n    if( p == end )\n        return( 0 );\n\n    if( ( ret = mbedtls_asn1_get_int( &p, end, keylen ) ) != 0 )\n    {\n        if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )\n            return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret );\n    }\n\n    if( p == end )\n        return( 0 );\n\n    if( ( ret = mbedtls_asn1_get_alg_null( &p, end, &prf_alg_oid ) ) != 0 )\n        return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret );\n\n    if( mbedtls_oid_get_md_hmac( &prf_alg_oid, md_type ) != 0 )\n        return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );\n\n    if( p != end )\n        return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    return( 0 );\n}\n\nint mbedtls_pkcs5_pbes2( const mbedtls_asn1_buf *pbe_params, int mode,\n                 const unsigned char *pwd,  size_t pwdlen,\n                 const unsigned char *data, size_t datalen,\n                 unsigned char *output )\n{\n    int ret, iterations = 0, keylen = 0;\n    unsigned char *p, *end;\n    mbedtls_asn1_buf kdf_alg_oid, enc_scheme_oid, kdf_alg_params, enc_scheme_params;\n    mbedtls_asn1_buf salt;\n    mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1;\n    unsigned char key[32], iv[32];\n    size_t olen = 0;\n    const mbedtls_md_info_t *md_info;\n    const mbedtls_cipher_info_t *cipher_info;\n    mbedtls_md_context_t md_ctx;\n    mbedtls_cipher_type_t cipher_alg;\n    mbedtls_cipher_context_t cipher_ctx;\n\n    p = pbe_params->p;\n    end = p + pbe_params->len;\n\n    /*\n     *  PBES2-params ::= SEQUENCE {\n     *    keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},\n     *    encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}\n     *  }\n     */\n    if( pbe_params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )\n        return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );\n\n    if( ( ret = mbedtls_asn1_get_alg( &p, end, &kdf_alg_oid, &kdf_alg_params ) ) != 0 )\n        return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret );\n\n    // Only PBKDF2 supported at the moment\n    //\n    if( MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS5_PBKDF2, &kdf_alg_oid ) != 0 )\n        return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );\n\n    if( ( ret = pkcs5_parse_pbkdf2_params( &kdf_alg_params,\n                                           &salt, &iterations, &keylen,\n                                           &md_type ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    md_info = mbedtls_md_info_from_type( md_type );\n    if( md_info == NULL )\n        return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );\n\n    if( ( ret = mbedtls_asn1_get_alg( &p, end, &enc_scheme_oid,\n                              &enc_scheme_params ) ) != 0 )\n    {\n        return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret );\n    }\n\n    if( mbedtls_oid_get_cipher_alg( &enc_scheme_oid, &cipher_alg ) != 0 )\n        return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );\n\n    cipher_info = mbedtls_cipher_info_from_type( cipher_alg );\n    if( cipher_info == NULL )\n        return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );\n\n    /*\n     * The value of keylen from pkcs5_parse_pbkdf2_params() is ignored\n     * since it is optional and we don't know if it was set or not\n     */\n    keylen = cipher_info->key_bitlen / 8;\n\n    if( enc_scheme_params.tag != MBEDTLS_ASN1_OCTET_STRING ||\n        enc_scheme_params.len != cipher_info->iv_size )\n    {\n        return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT );\n    }\n\n    mbedtls_md_init( &md_ctx );\n    mbedtls_cipher_init( &cipher_ctx );\n\n    memcpy( iv, enc_scheme_params.p, enc_scheme_params.len );\n\n    if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_pkcs5_pbkdf2_hmac( &md_ctx, pwd, pwdlen, salt.p, salt.len,\n                                   iterations, keylen, key ) ) != 0 )\n    {\n        goto exit;\n    }\n\n    if( ( ret = mbedtls_cipher_setup( &cipher_ctx, cipher_info ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_cipher_setkey( &cipher_ctx, key, 8 * keylen, (mbedtls_operation_t) mode ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_cipher_crypt( &cipher_ctx, iv, enc_scheme_params.len,\n                              data, datalen, output, &olen ) ) != 0 )\n        ret = MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH;\n\nexit:\n    mbedtls_md_free( &md_ctx );\n    mbedtls_cipher_free( &cipher_ctx );\n\n    return( ret );\n}\n#endif /* MBEDTLS_ASN1_PARSE_C */\n\nint mbedtls_pkcs5_pbkdf2_hmac( mbedtls_md_context_t *ctx, const unsigned char *password,\n                       size_t plen, const unsigned char *salt, size_t slen,\n                       unsigned int iteration_count,\n                       uint32_t key_length, unsigned char *output )\n{\n    int ret, j;\n    unsigned int i;\n    unsigned char md1[MBEDTLS_MD_MAX_SIZE];\n    unsigned char work[MBEDTLS_MD_MAX_SIZE];\n    unsigned char md_size = mbedtls_md_get_size( ctx->md_info );\n    size_t use_len;\n    unsigned char *out_p = output;\n    unsigned char counter[4];\n\n    memset( counter, 0, 4 );\n    counter[3] = 1;\n\n#if UINT_MAX > 0xFFFFFFFF\n    if( iteration_count > 0xFFFFFFFF )\n        return( MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA );\n#endif\n\n    while( key_length )\n    {\n        // U1 ends up in work\n        //\n        if( ( ret = mbedtls_md_hmac_starts( ctx, password, plen ) ) != 0 )\n            return( ret );\n\n        if( ( ret = mbedtls_md_hmac_update( ctx, salt, slen ) ) != 0 )\n            return( ret );\n\n        if( ( ret = mbedtls_md_hmac_update( ctx, counter, 4 ) ) != 0 )\n            return( ret );\n\n        if( ( ret = mbedtls_md_hmac_finish( ctx, work ) ) != 0 )\n            return( ret );\n\n        memcpy( md1, work, md_size );\n\n        for( i = 1; i < iteration_count; i++ )\n        {\n            // U2 ends up in md1\n            //\n            if( ( ret = mbedtls_md_hmac_starts( ctx, password, plen ) ) != 0 )\n                return( ret );\n\n            if( ( ret = mbedtls_md_hmac_update( ctx, md1, md_size ) ) != 0 )\n                return( ret );\n\n            if( ( ret = mbedtls_md_hmac_finish( ctx, md1 ) ) != 0 )\n                return( ret );\n\n            // U1 xor U2\n            //\n            for( j = 0; j < md_size; j++ )\n                work[j] ^= md1[j];\n        }\n\n        use_len = ( key_length < md_size ) ? key_length : md_size;\n        memcpy( out_p, work, use_len );\n\n        key_length -= (uint32_t) use_len;\n        out_p += use_len;\n\n        for( i = 4; i > 0; i-- )\n            if( ++counter[i - 1] != 0 )\n                break;\n    }\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_SELF_TEST)\n\n#if !defined(MBEDTLS_SHA1_C)\nint mbedtls_pkcs5_self_test( int verbose )\n{\n    if( verbose != 0 )\n        mbedtls_printf( \"  PBKDF2 (SHA1): skipped\\n\\n\" );\n\n    return( 0 );\n}\n#else\n\n#define MAX_TESTS   6\n\nstatic const size_t plen[MAX_TESTS] =\n    { 8, 8, 8, 24, 9 };\n\nstatic const unsigned char password[MAX_TESTS][32] =\n{\n    \"password\",\n    \"password\",\n    \"password\",\n    \"passwordPASSWORDpassword\",\n    \"pass\\0word\",\n};\n\nstatic const size_t slen[MAX_TESTS] =\n    { 4, 4, 4, 36, 5 };\n\nstatic const unsigned char salt[MAX_TESTS][40] =\n{\n    \"salt\",\n    \"salt\",\n    \"salt\",\n    \"saltSALTsaltSALTsaltSALTsaltSALTsalt\",\n    \"sa\\0lt\",\n};\n\nstatic const uint32_t it_cnt[MAX_TESTS] =\n    { 1, 2, 4096, 4096, 4096 };\n\nstatic const uint32_t key_len[MAX_TESTS] =\n    { 20, 20, 20, 25, 16 };\n\nstatic const unsigned char result_key[MAX_TESTS][32] =\n{\n    { 0x0c, 0x60, 0xc8, 0x0f, 0x96, 0x1f, 0x0e, 0x71,\n      0xf3, 0xa9, 0xb5, 0x24, 0xaf, 0x60, 0x12, 0x06,\n      0x2f, 0xe0, 0x37, 0xa6 },\n    { 0xea, 0x6c, 0x01, 0x4d, 0xc7, 0x2d, 0x6f, 0x8c,\n      0xcd, 0x1e, 0xd9, 0x2a, 0xce, 0x1d, 0x41, 0xf0,\n      0xd8, 0xde, 0x89, 0x57 },\n    { 0x4b, 0x00, 0x79, 0x01, 0xb7, 0x65, 0x48, 0x9a,\n      0xbe, 0xad, 0x49, 0xd9, 0x26, 0xf7, 0x21, 0xd0,\n      0x65, 0xa4, 0x29, 0xc1 },\n    { 0x3d, 0x2e, 0xec, 0x4f, 0xe4, 0x1c, 0x84, 0x9b,\n      0x80, 0xc8, 0xd8, 0x36, 0x62, 0xc0, 0xe4, 0x4a,\n      0x8b, 0x29, 0x1a, 0x96, 0x4c, 0xf2, 0xf0, 0x70,\n      0x38 },\n    { 0x56, 0xfa, 0x6a, 0xa7, 0x55, 0x48, 0x09, 0x9d,\n      0xcc, 0x37, 0xd7, 0xf0, 0x34, 0x25, 0xe0, 0xc3 },\n};\n\nint mbedtls_pkcs5_self_test( int verbose )\n{\n    mbedtls_md_context_t sha1_ctx;\n    const mbedtls_md_info_t *info_sha1;\n    int ret, i;\n    unsigned char key[64];\n\n    mbedtls_md_init( &sha1_ctx );\n\n    info_sha1 = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 );\n    if( info_sha1 == NULL )\n    {\n        ret = 1;\n        goto exit;\n    }\n\n    if( ( ret = mbedtls_md_setup( &sha1_ctx, info_sha1, 1 ) ) != 0 )\n    {\n        ret = 1;\n        goto exit;\n    }\n\n    for( i = 0; i < MAX_TESTS; i++ )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"  PBKDF2 (SHA1) #%d: \", i );\n\n        ret = mbedtls_pkcs5_pbkdf2_hmac( &sha1_ctx, password[i], plen[i], salt[i],\n                                  slen[i], it_cnt[i], key_len[i], key );\n        if( ret != 0 ||\n            memcmp( result_key[i], key, key_len[i] ) != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed\\n\" );\n\n            ret = 1;\n            goto exit;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\nexit:\n    mbedtls_md_free( &sha1_ctx );\n\n    return( ret );\n}\n#endif /* MBEDTLS_SHA1_C */\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_PKCS5_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/pkparse.c",
    "content": "/*\n *  Public Key layer for parsing key files and structures\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_PK_PARSE_C)\n\n#include \"mbedtls/pk.h\"\n#include \"mbedtls/asn1.h\"\n#include \"mbedtls/oid.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_RSA_C)\n#include \"mbedtls/rsa.h\"\n#endif\n#if defined(MBEDTLS_ECP_C)\n#include \"mbedtls/ecp.h\"\n#endif\n#if defined(MBEDTLS_ECDSA_C)\n#include \"mbedtls/ecdsa.h\"\n#endif\n#if defined(MBEDTLS_PEM_PARSE_C)\n#include \"mbedtls/pem.h\"\n#endif\n#if defined(MBEDTLS_PKCS5_C)\n#include \"mbedtls/pkcs5.h\"\n#endif\n#if defined(MBEDTLS_PKCS12_C)\n#include \"mbedtls/pkcs12.h\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc    calloc\n#define mbedtls_free       free\n#endif\n\n#if defined(MBEDTLS_FS_IO)\n/*\n * Load all data from a file into a given buffer.\n *\n * The file is expected to contain either PEM or DER encoded data.\n * A terminating null byte is always appended. It is included in the announced\n * length only if the data looks like it is PEM encoded.\n */\nint mbedtls_pk_load_file( const char *path, unsigned char **buf, size_t *n )\n{\n    FILE *f;\n    long size;\n\n    if( ( f = fopen( path, \"rb\" ) ) == NULL )\n        return( MBEDTLS_ERR_PK_FILE_IO_ERROR );\n\n    fseek( f, 0, SEEK_END );\n    if( ( size = ftell( f ) ) == -1 )\n    {\n        fclose( f );\n        return( MBEDTLS_ERR_PK_FILE_IO_ERROR );\n    }\n    fseek( f, 0, SEEK_SET );\n\n    *n = (size_t) size;\n\n    if( *n + 1 == 0 ||\n        ( *buf = mbedtls_calloc( 1, *n + 1 ) ) == NULL )\n    {\n        fclose( f );\n        return( MBEDTLS_ERR_PK_ALLOC_FAILED );\n    }\n\n    if( fread( *buf, 1, *n, f ) != *n )\n    {\n        fclose( f );\n\n        mbedtls_platform_zeroize( *buf, *n );\n        mbedtls_free( *buf );\n\n        return( MBEDTLS_ERR_PK_FILE_IO_ERROR );\n    }\n\n    fclose( f );\n\n    (*buf)[*n] = '\\0';\n\n    if( strstr( (const char *) *buf, \"-----BEGIN \" ) != NULL )\n        ++*n;\n\n    return( 0 );\n}\n\n/*\n * Load and parse a private key\n */\nint mbedtls_pk_parse_keyfile( mbedtls_pk_context *ctx,\n                      const char *path, const char *pwd )\n{\n    int ret;\n    size_t n;\n    unsigned char *buf;\n\n    if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )\n        return( ret );\n\n    if( pwd == NULL )\n        ret = mbedtls_pk_parse_key( ctx, buf, n, NULL, 0 );\n    else\n        ret = mbedtls_pk_parse_key( ctx, buf, n,\n                (const unsigned char *) pwd, strlen( pwd ) );\n\n    mbedtls_platform_zeroize( buf, n );\n    mbedtls_free( buf );\n\n    return( ret );\n}\n\n/*\n * Load and parse a public key\n */\nint mbedtls_pk_parse_public_keyfile( mbedtls_pk_context *ctx, const char *path )\n{\n    int ret;\n    size_t n;\n    unsigned char *buf;\n\n    if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )\n        return( ret );\n\n    ret = mbedtls_pk_parse_public_key( ctx, buf, n );\n\n    mbedtls_platform_zeroize( buf, n );\n    mbedtls_free( buf );\n\n    return( ret );\n}\n#endif /* MBEDTLS_FS_IO */\n\n#if defined(MBEDTLS_ECP_C)\n/* Minimally parse an ECParameters buffer to and mbedtls_asn1_buf\n *\n * ECParameters ::= CHOICE {\n *   namedCurve         OBJECT IDENTIFIER\n *   specifiedCurve     SpecifiedECDomain -- = SEQUENCE { ... }\n *   -- implicitCurve   NULL\n * }\n */\nstatic int pk_get_ecparams( unsigned char **p, const unsigned char *end,\n                            mbedtls_asn1_buf *params )\n{\n    int ret;\n\n    if ( end - *p < 1 )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n    /* Tag may be either OID or SEQUENCE */\n    params->tag = **p;\n    if( params->tag != MBEDTLS_ASN1_OID\n#if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)\n            && params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE )\n#endif\n            )\n    {\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );\n    }\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &params->len, params->tag ) ) != 0 )\n    {\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n    }\n\n    params->p = *p;\n    *p += params->len;\n\n    if( *p != end )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)\n/*\n * Parse a SpecifiedECDomain (SEC 1 C.2) and (mostly) fill the group with it.\n * WARNING: the resulting group should only be used with\n * pk_group_id_from_specified(), since its base point may not be set correctly\n * if it was encoded compressed.\n *\n *  SpecifiedECDomain ::= SEQUENCE {\n *      version SpecifiedECDomainVersion(ecdpVer1 | ecdpVer2 | ecdpVer3, ...),\n *      fieldID FieldID {{FieldTypes}},\n *      curve Curve,\n *      base ECPoint,\n *      order INTEGER,\n *      cofactor INTEGER OPTIONAL,\n *      hash HashAlgorithm OPTIONAL,\n *      ...\n *  }\n *\n * We only support prime-field as field type, and ignore hash and cofactor.\n */\nstatic int pk_group_from_specified( const mbedtls_asn1_buf *params, mbedtls_ecp_group *grp )\n{\n    int ret;\n    unsigned char *p = params->p;\n    const unsigned char * const end = params->p + params->len;\n    const unsigned char *end_field, *end_curve;\n    size_t len;\n    int ver;\n\n    /* SpecifiedECDomainVersion ::= INTEGER { 1, 2, 3 } */\n    if( ( ret = mbedtls_asn1_get_int( &p, end, &ver ) ) != 0 )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n\n    if( ver < 1 || ver > 3 )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );\n\n    /*\n     * FieldID { FIELD-ID:IOSet } ::= SEQUENCE { -- Finite field\n     *       fieldType FIELD-ID.&id({IOSet}),\n     *       parameters FIELD-ID.&Type({IOSet}{@fieldType})\n     * }\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n        return( ret );\n\n    end_field = p + len;\n\n    /*\n     * FIELD-ID ::= TYPE-IDENTIFIER\n     * FieldTypes FIELD-ID ::= {\n     *       { Prime-p IDENTIFIED BY prime-field } |\n     *       { Characteristic-two IDENTIFIED BY characteristic-two-field }\n     * }\n     * prime-field OBJECT IDENTIFIER ::= { id-fieldType 1 }\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end_field, &len, MBEDTLS_ASN1_OID ) ) != 0 )\n        return( ret );\n\n    if( len != MBEDTLS_OID_SIZE( MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD ) ||\n        memcmp( p, MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD, len ) != 0 )\n    {\n        return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );\n    }\n\n    p += len;\n\n    /* Prime-p ::= INTEGER -- Field of size p. */\n    if( ( ret = mbedtls_asn1_get_mpi( &p, end_field, &grp->P ) ) != 0 )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n\n    grp->pbits = mbedtls_mpi_bitlen( &grp->P );\n\n    if( p != end_field )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    /*\n     * Curve ::= SEQUENCE {\n     *       a FieldElement,\n     *       b FieldElement,\n     *       seed BIT STRING OPTIONAL\n     *       -- Shall be present if used in SpecifiedECDomain\n     *       -- with version equal to ecdpVer2 or ecdpVer3\n     * }\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n        return( ret );\n\n    end_curve = p + len;\n\n    /*\n     * FieldElement ::= OCTET STRING\n     * containing an integer in the case of a prime field\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end_curve, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ||\n        ( ret = mbedtls_mpi_read_binary( &grp->A, p, len ) ) != 0 )\n    {\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n    }\n\n    p += len;\n\n    if( ( ret = mbedtls_asn1_get_tag( &p, end_curve, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ||\n        ( ret = mbedtls_mpi_read_binary( &grp->B, p, len ) ) != 0 )\n    {\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n    }\n\n    p += len;\n\n    /* Ignore seed BIT STRING OPTIONAL */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end_curve, &len, MBEDTLS_ASN1_BIT_STRING ) ) == 0 )\n        p += len;\n\n    if( p != end_curve )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    /*\n     * ECPoint ::= OCTET STRING\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n\n    if( ( ret = mbedtls_ecp_point_read_binary( grp, &grp->G,\n                                      ( const unsigned char *) p, len ) ) != 0 )\n    {\n        /*\n         * If we can't read the point because it's compressed, cheat by\n         * reading only the X coordinate and the parity bit of Y.\n         */\n        if( ret != MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ||\n            ( p[0] != 0x02 && p[0] != 0x03 ) ||\n            len != mbedtls_mpi_size( &grp->P ) + 1 ||\n            mbedtls_mpi_read_binary( &grp->G.X, p + 1, len - 1 ) != 0 ||\n            mbedtls_mpi_lset( &grp->G.Y, p[0] - 2 ) != 0 ||\n            mbedtls_mpi_lset( &grp->G.Z, 1 ) != 0 )\n        {\n            return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );\n        }\n    }\n\n    p += len;\n\n    /*\n     * order INTEGER\n     */\n    if( ( ret = mbedtls_asn1_get_mpi( &p, end, &grp->N ) ) != 0 )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n\n    grp->nbits = mbedtls_mpi_bitlen( &grp->N );\n\n    /*\n     * Allow optional elements by purposefully not enforcing p == end here.\n     */\n\n    return( 0 );\n}\n\n/*\n * Find the group id associated with an (almost filled) group as generated by\n * pk_group_from_specified(), or return an error if unknown.\n */\nstatic int pk_group_id_from_group( const mbedtls_ecp_group *grp, mbedtls_ecp_group_id *grp_id )\n{\n    int ret = 0;\n    mbedtls_ecp_group ref;\n    const mbedtls_ecp_group_id *id;\n\n    mbedtls_ecp_group_init( &ref );\n\n    for( id = mbedtls_ecp_grp_id_list(); *id != MBEDTLS_ECP_DP_NONE; id++ )\n    {\n        /* Load the group associated to that id */\n        mbedtls_ecp_group_free( &ref );\n        MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &ref, *id ) );\n\n        /* Compare to the group we were given, starting with easy tests */\n        if( grp->pbits == ref.pbits && grp->nbits == ref.nbits &&\n            mbedtls_mpi_cmp_mpi( &grp->P, &ref.P ) == 0 &&\n            mbedtls_mpi_cmp_mpi( &grp->A, &ref.A ) == 0 &&\n            mbedtls_mpi_cmp_mpi( &grp->B, &ref.B ) == 0 &&\n            mbedtls_mpi_cmp_mpi( &grp->N, &ref.N ) == 0 &&\n            mbedtls_mpi_cmp_mpi( &grp->G.X, &ref.G.X ) == 0 &&\n            mbedtls_mpi_cmp_mpi( &grp->G.Z, &ref.G.Z ) == 0 &&\n            /* For Y we may only know the parity bit, so compare only that */\n            mbedtls_mpi_get_bit( &grp->G.Y, 0 ) == mbedtls_mpi_get_bit( &ref.G.Y, 0 ) )\n        {\n            break;\n        }\n\n    }\n\ncleanup:\n    mbedtls_ecp_group_free( &ref );\n\n    *grp_id = *id;\n\n    if( ret == 0 && *id == MBEDTLS_ECP_DP_NONE )\n        ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;\n\n    return( ret );\n}\n\n/*\n * Parse a SpecifiedECDomain (SEC 1 C.2) and find the associated group ID\n */\nstatic int pk_group_id_from_specified( const mbedtls_asn1_buf *params,\n                                       mbedtls_ecp_group_id *grp_id )\n{\n    int ret;\n    mbedtls_ecp_group grp;\n\n    mbedtls_ecp_group_init( &grp );\n\n    if( ( ret = pk_group_from_specified( params, &grp ) ) != 0 )\n        goto cleanup;\n\n    ret = pk_group_id_from_group( &grp, grp_id );\n\ncleanup:\n    mbedtls_ecp_group_free( &grp );\n\n    return( ret );\n}\n#endif /* MBEDTLS_PK_PARSE_EC_EXTENDED */\n\n/*\n * Use EC parameters to initialise an EC group\n *\n * ECParameters ::= CHOICE {\n *   namedCurve         OBJECT IDENTIFIER\n *   specifiedCurve     SpecifiedECDomain -- = SEQUENCE { ... }\n *   -- implicitCurve   NULL\n */\nstatic int pk_use_ecparams( const mbedtls_asn1_buf *params, mbedtls_ecp_group *grp )\n{\n    int ret;\n    mbedtls_ecp_group_id grp_id;\n\n    if( params->tag == MBEDTLS_ASN1_OID )\n    {\n        if( mbedtls_oid_get_ec_grp( params, &grp_id ) != 0 )\n            return( MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE );\n    }\n    else\n    {\n#if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)\n        if( ( ret = pk_group_id_from_specified( params, &grp_id ) ) != 0 )\n            return( ret );\n#else\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );\n#endif\n    }\n\n    /*\n     * grp may already be initilialized; if so, make sure IDs match\n     */\n    if( grp->id != MBEDTLS_ECP_DP_NONE && grp->id != grp_id )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );\n\n    if( ( ret = mbedtls_ecp_group_load( grp, grp_id ) ) != 0 )\n        return( ret );\n\n    return( 0 );\n}\n\n/*\n * EC public key is an EC point\n *\n * The caller is responsible for clearing the structure upon failure if\n * desired. Take care to pass along the possible ECP_FEATURE_UNAVAILABLE\n * return code of mbedtls_ecp_point_read_binary() and leave p in a usable state.\n */\nstatic int pk_get_ecpubkey( unsigned char **p, const unsigned char *end,\n                            mbedtls_ecp_keypair *key )\n{\n    int ret;\n\n    if( ( ret = mbedtls_ecp_point_read_binary( &key->grp, &key->Q,\n                    (const unsigned char *) *p, end - *p ) ) == 0 )\n    {\n        ret = mbedtls_ecp_check_pubkey( &key->grp, &key->Q );\n    }\n\n    /*\n     * We know mbedtls_ecp_point_read_binary consumed all bytes or failed\n     */\n    *p = (unsigned char *) end;\n\n    return( ret );\n}\n#endif /* MBEDTLS_ECP_C */\n\n#if defined(MBEDTLS_RSA_C)\n/*\n *  RSAPublicKey ::= SEQUENCE {\n *      modulus           INTEGER,  -- n\n *      publicExponent    INTEGER   -- e\n *  }\n */\nstatic int pk_get_rsapubkey( unsigned char **p,\n                             const unsigned char *end,\n                             mbedtls_rsa_context *rsa )\n{\n    int ret;\n    size_t len;\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n        return( MBEDTLS_ERR_PK_INVALID_PUBKEY + ret );\n\n    if( *p + len != end )\n        return( MBEDTLS_ERR_PK_INVALID_PUBKEY +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    /* Import N */\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ) ) != 0 )\n        return( MBEDTLS_ERR_PK_INVALID_PUBKEY + ret );\n\n    if( ( ret = mbedtls_rsa_import_raw( rsa, *p, len, NULL, 0, NULL, 0,\n                                        NULL, 0, NULL, 0 ) ) != 0 )\n        return( MBEDTLS_ERR_PK_INVALID_PUBKEY );\n\n    *p += len;\n\n    /* Import E */\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ) ) != 0 )\n        return( MBEDTLS_ERR_PK_INVALID_PUBKEY + ret );\n\n    if( ( ret = mbedtls_rsa_import_raw( rsa, NULL, 0, NULL, 0, NULL, 0,\n                                        NULL, 0, *p, len ) ) != 0 )\n        return( MBEDTLS_ERR_PK_INVALID_PUBKEY );\n\n    *p += len;\n\n    if( mbedtls_rsa_complete( rsa ) != 0 ||\n        mbedtls_rsa_check_pubkey( rsa ) != 0 )\n    {\n        return( MBEDTLS_ERR_PK_INVALID_PUBKEY );\n    }\n\n    if( *p != end )\n        return( MBEDTLS_ERR_PK_INVALID_PUBKEY +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_RSA_C */\n\n/* Get a PK algorithm identifier\n *\n *  AlgorithmIdentifier  ::=  SEQUENCE  {\n *       algorithm               OBJECT IDENTIFIER,\n *       parameters              ANY DEFINED BY algorithm OPTIONAL  }\n */\nstatic int pk_get_pk_alg( unsigned char **p,\n                          const unsigned char *end,\n                          mbedtls_pk_type_t *pk_alg, mbedtls_asn1_buf *params )\n{\n    int ret;\n    mbedtls_asn1_buf alg_oid;\n\n    memset( params, 0, sizeof(mbedtls_asn1_buf) );\n\n    if( ( ret = mbedtls_asn1_get_alg( p, end, &alg_oid, params ) ) != 0 )\n        return( MBEDTLS_ERR_PK_INVALID_ALG + ret );\n\n    if( mbedtls_oid_get_pk_alg( &alg_oid, pk_alg ) != 0 )\n        return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );\n\n    /*\n     * No parameters with RSA (only for EC)\n     */\n    if( *pk_alg == MBEDTLS_PK_RSA &&\n            ( ( params->tag != MBEDTLS_ASN1_NULL && params->tag != 0 ) ||\n                params->len != 0 ) )\n    {\n        return( MBEDTLS_ERR_PK_INVALID_ALG );\n    }\n\n    return( 0 );\n}\n\n/*\n *  SubjectPublicKeyInfo  ::=  SEQUENCE  {\n *       algorithm            AlgorithmIdentifier,\n *       subjectPublicKey     BIT STRING }\n */\nint mbedtls_pk_parse_subpubkey( unsigned char **p, const unsigned char *end,\n                        mbedtls_pk_context *pk )\n{\n    int ret;\n    size_t len;\n    mbedtls_asn1_buf alg_params;\n    mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;\n    const mbedtls_pk_info_t *pk_info;\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &len,\n                    MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n    }\n\n    end = *p + len;\n\n    if( ( ret = pk_get_pk_alg( p, end, &pk_alg, &alg_params ) ) != 0 )\n        return( ret );\n\n    if( ( ret = mbedtls_asn1_get_bitstring_null( p, end, &len ) ) != 0 )\n        return( MBEDTLS_ERR_PK_INVALID_PUBKEY + ret );\n\n    if( *p + len != end )\n        return( MBEDTLS_ERR_PK_INVALID_PUBKEY +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    if( ( pk_info = mbedtls_pk_info_from_type( pk_alg ) ) == NULL )\n        return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );\n\n    if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 )\n        return( ret );\n\n#if defined(MBEDTLS_RSA_C)\n    if( pk_alg == MBEDTLS_PK_RSA )\n    {\n        ret = pk_get_rsapubkey( p, end, mbedtls_pk_rsa( *pk ) );\n    } else\n#endif /* MBEDTLS_RSA_C */\n#if defined(MBEDTLS_ECP_C)\n    if( pk_alg == MBEDTLS_PK_ECKEY_DH || pk_alg == MBEDTLS_PK_ECKEY )\n    {\n        ret = pk_use_ecparams( &alg_params, &mbedtls_pk_ec( *pk )->grp );\n        if( ret == 0 )\n            ret = pk_get_ecpubkey( p, end, mbedtls_pk_ec( *pk ) );\n    } else\n#endif /* MBEDTLS_ECP_C */\n        ret = MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;\n\n    if( ret == 0 && *p != end )\n        ret = MBEDTLS_ERR_PK_INVALID_PUBKEY\n              MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;\n\n    if( ret != 0 )\n        mbedtls_pk_free( pk );\n\n    return( ret );\n}\n\n#if defined(MBEDTLS_RSA_C)\n/*\n * Parse a PKCS#1 encoded private RSA key\n */\nstatic int pk_parse_key_pkcs1_der( mbedtls_rsa_context *rsa,\n                                   const unsigned char *key,\n                                   size_t keylen )\n{\n    int ret, version;\n    size_t len;\n    unsigned char *p, *end;\n\n    mbedtls_mpi T;\n    mbedtls_mpi_init( &T );\n\n    p = (unsigned char *) key;\n    end = p + keylen;\n\n    /*\n     * This function parses the RSAPrivateKey (PKCS#1)\n     *\n     *  RSAPrivateKey ::= SEQUENCE {\n     *      version           Version,\n     *      modulus           INTEGER,  -- n\n     *      publicExponent    INTEGER,  -- e\n     *      privateExponent   INTEGER,  -- d\n     *      prime1            INTEGER,  -- p\n     *      prime2            INTEGER,  -- q\n     *      exponent1         INTEGER,  -- d mod (p-1)\n     *      exponent2         INTEGER,  -- d mod (q-1)\n     *      coefficient       INTEGER,  -- (inverse of q) mod p\n     *      otherPrimeInfos   OtherPrimeInfos OPTIONAL\n     *  }\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n    }\n\n    end = p + len;\n\n    if( ( ret = mbedtls_asn1_get_int( &p, end, &version ) ) != 0 )\n    {\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n    }\n\n    if( version != 0 )\n    {\n        return( MBEDTLS_ERR_PK_KEY_INVALID_VERSION );\n    }\n\n    /* Import N */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n                                      MBEDTLS_ASN1_INTEGER ) ) != 0 ||\n        ( ret = mbedtls_rsa_import_raw( rsa, p, len, NULL, 0, NULL, 0,\n                                        NULL, 0, NULL, 0 ) ) != 0 )\n        goto cleanup;\n    p += len;\n\n    /* Import E */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n                                      MBEDTLS_ASN1_INTEGER ) ) != 0 ||\n        ( ret = mbedtls_rsa_import_raw( rsa, NULL, 0, NULL, 0, NULL, 0,\n                                        NULL, 0, p, len ) ) != 0 )\n        goto cleanup;\n    p += len;\n\n    /* Import D */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n                                      MBEDTLS_ASN1_INTEGER ) ) != 0 ||\n        ( ret = mbedtls_rsa_import_raw( rsa, NULL, 0, NULL, 0, NULL, 0,\n                                        p, len, NULL, 0 ) ) != 0 )\n        goto cleanup;\n    p += len;\n\n    /* Import P */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n                                      MBEDTLS_ASN1_INTEGER ) ) != 0 ||\n        ( ret = mbedtls_rsa_import_raw( rsa, NULL, 0, p, len, NULL, 0,\n                                        NULL, 0, NULL, 0 ) ) != 0 )\n        goto cleanup;\n    p += len;\n\n    /* Import Q */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n                                      MBEDTLS_ASN1_INTEGER ) ) != 0 ||\n        ( ret = mbedtls_rsa_import_raw( rsa, NULL, 0, NULL, 0, p, len,\n                                        NULL, 0, NULL, 0 ) ) != 0 )\n        goto cleanup;\n    p += len;\n\n    /* Complete the RSA private key */\n    if( ( ret = mbedtls_rsa_complete( rsa ) ) != 0 )\n        goto cleanup;\n\n    /* Check optional parameters */\n    if( ( ret = mbedtls_asn1_get_mpi( &p, end, &T ) ) != 0 ||\n        ( ret = mbedtls_asn1_get_mpi( &p, end, &T ) ) != 0 ||\n        ( ret = mbedtls_asn1_get_mpi( &p, end, &T ) ) != 0 )\n        goto cleanup;\n\n    if( p != end )\n    {\n        ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +\n              MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ;\n    }\n\ncleanup:\n\n    mbedtls_mpi_free( &T );\n\n    if( ret != 0 )\n    {\n        /* Wrap error code if it's coming from a lower level */\n        if( ( ret & 0xff80 ) == 0 )\n            ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret;\n        else\n            ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;\n\n        mbedtls_rsa_free( rsa );\n    }\n\n    return( ret );\n}\n#endif /* MBEDTLS_RSA_C */\n\n#if defined(MBEDTLS_ECP_C)\n/*\n * Parse a SEC1 encoded private EC key\n */\nstatic int pk_parse_key_sec1_der( mbedtls_ecp_keypair *eck,\n                                  const unsigned char *key,\n                                  size_t keylen )\n{\n    int ret;\n    int version, pubkey_done;\n    size_t len;\n    mbedtls_asn1_buf params;\n    unsigned char *p = (unsigned char *) key;\n    unsigned char *end = p + keylen;\n    unsigned char *end2;\n\n    /*\n     * RFC 5915, or SEC1 Appendix C.4\n     *\n     * ECPrivateKey ::= SEQUENCE {\n     *      version        INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),\n     *      privateKey     OCTET STRING,\n     *      parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,\n     *      publicKey  [1] BIT STRING OPTIONAL\n     *    }\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n    }\n\n    end = p + len;\n\n    if( ( ret = mbedtls_asn1_get_int( &p, end, &version ) ) != 0 )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n\n    if( version != 1 )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_VERSION );\n\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n\n    if( ( ret = mbedtls_mpi_read_binary( &eck->d, p, len ) ) != 0 )\n    {\n        mbedtls_ecp_keypair_free( eck );\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n    }\n\n    p += len;\n\n    pubkey_done = 0;\n    if( p != end )\n    {\n        /*\n         * Is 'parameters' present?\n         */\n        if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n                        MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) == 0 )\n        {\n            if( ( ret = pk_get_ecparams( &p, p + len, &params) ) != 0 ||\n                ( ret = pk_use_ecparams( &params, &eck->grp )  ) != 0 )\n            {\n                mbedtls_ecp_keypair_free( eck );\n                return( ret );\n            }\n        }\n        else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )\n        {\n            mbedtls_ecp_keypair_free( eck );\n            return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n        }\n    }\n\n    if( p != end )\n    {\n        /*\n         * Is 'publickey' present? If not, or if we can't read it (eg because it\n         * is compressed), create it from the private key.\n         */\n        if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n                        MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 1 ) ) == 0 )\n        {\n            end2 = p + len;\n\n            if( ( ret = mbedtls_asn1_get_bitstring_null( &p, end2, &len ) ) != 0 )\n                return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n\n            if( p + len != end2 )\n                return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +\n                        MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n            if( ( ret = pk_get_ecpubkey( &p, end2, eck ) ) == 0 )\n                pubkey_done = 1;\n            else\n            {\n                /*\n                 * The only acceptable failure mode of pk_get_ecpubkey() above\n                 * is if the point format is not recognized.\n                 */\n                if( ret != MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE )\n                    return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );\n            }\n        }\n        else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )\n        {\n            mbedtls_ecp_keypair_free( eck );\n            return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n        }\n    }\n\n    if( ! pubkey_done &&\n        ( ret = mbedtls_ecp_mul( &eck->grp, &eck->Q, &eck->d, &eck->grp.G,\n                                                      NULL, NULL ) ) != 0 )\n    {\n        mbedtls_ecp_keypair_free( eck );\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n    }\n\n    if( ( ret = mbedtls_ecp_check_privkey( &eck->grp, &eck->d ) ) != 0 )\n    {\n        mbedtls_ecp_keypair_free( eck );\n        return( ret );\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_ECP_C */\n\n/*\n * Parse an unencrypted PKCS#8 encoded private key\n *\n * Notes:\n *\n * - This function does not own the key buffer. It is the\n *   responsibility of the caller to take care of zeroizing\n *   and freeing it after use.\n *\n * - The function is responsible for freeing the provided\n *   PK context on failure.\n *\n */\nstatic int pk_parse_key_pkcs8_unencrypted_der(\n                                    mbedtls_pk_context *pk,\n                                    const unsigned char* key,\n                                    size_t keylen )\n{\n    int ret, version;\n    size_t len;\n    mbedtls_asn1_buf params;\n    unsigned char *p = (unsigned char *) key;\n    unsigned char *end = p + keylen;\n    mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;\n    const mbedtls_pk_info_t *pk_info;\n\n    /*\n     * This function parses the PrivateKeyInfo object (PKCS#8 v1.2 = RFC 5208)\n     *\n     *    PrivateKeyInfo ::= SEQUENCE {\n     *      version                   Version,\n     *      privateKeyAlgorithm       PrivateKeyAlgorithmIdentifier,\n     *      privateKey                PrivateKey,\n     *      attributes           [0]  IMPLICIT Attributes OPTIONAL }\n     *\n     *    Version ::= INTEGER\n     *    PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier\n     *    PrivateKey ::= OCTET STRING\n     *\n     *  The PrivateKey OCTET STRING is a SEC1 ECPrivateKey\n     */\n\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n    }\n\n    end = p + len;\n\n    if( ( ret = mbedtls_asn1_get_int( &p, end, &version ) ) != 0 )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n\n    if( version != 0 )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_VERSION + ret );\n\n    if( ( ret = pk_get_pk_alg( &p, end, &pk_alg, &params ) ) != 0 )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n\n    if( len < 1 )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n    if( ( pk_info = mbedtls_pk_info_from_type( pk_alg ) ) == NULL )\n        return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );\n\n    if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 )\n        return( ret );\n\n#if defined(MBEDTLS_RSA_C)\n    if( pk_alg == MBEDTLS_PK_RSA )\n    {\n        if( ( ret = pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ), p, len ) ) != 0 )\n        {\n            mbedtls_pk_free( pk );\n            return( ret );\n        }\n    } else\n#endif /* MBEDTLS_RSA_C */\n#if defined(MBEDTLS_ECP_C)\n    if( pk_alg == MBEDTLS_PK_ECKEY || pk_alg == MBEDTLS_PK_ECKEY_DH )\n    {\n        if( ( ret = pk_use_ecparams( &params, &mbedtls_pk_ec( *pk )->grp ) ) != 0 ||\n            ( ret = pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ), p, len )  ) != 0 )\n        {\n            mbedtls_pk_free( pk );\n            return( ret );\n        }\n    } else\n#endif /* MBEDTLS_ECP_C */\n        return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );\n\n    return( 0 );\n}\n\n/*\n * Parse an encrypted PKCS#8 encoded private key\n *\n * To save space, the decryption happens in-place on the given key buffer.\n * Also, while this function may modify the keybuffer, it doesn't own it,\n * and instead it is the responsibility of the caller to zeroize and properly\n * free it after use.\n *\n */\n#if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)\nstatic int pk_parse_key_pkcs8_encrypted_der(\n                                    mbedtls_pk_context *pk,\n                                    unsigned char *key, size_t keylen,\n                                    const unsigned char *pwd, size_t pwdlen )\n{\n    int ret, decrypted = 0;\n    size_t len;\n    unsigned char *buf;\n    unsigned char *p, *end;\n    mbedtls_asn1_buf pbe_alg_oid, pbe_params;\n#if defined(MBEDTLS_PKCS12_C)\n    mbedtls_cipher_type_t cipher_alg;\n    mbedtls_md_type_t md_alg;\n#endif\n\n    p = key;\n    end = p + keylen;\n\n    if( pwdlen == 0 )\n        return( MBEDTLS_ERR_PK_PASSWORD_REQUIRED );\n\n    /*\n     * This function parses the EncryptedPrivateKeyInfo object (PKCS#8)\n     *\n     *  EncryptedPrivateKeyInfo ::= SEQUENCE {\n     *    encryptionAlgorithm  EncryptionAlgorithmIdentifier,\n     *    encryptedData        EncryptedData\n     *  }\n     *\n     *  EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n     *\n     *  EncryptedData ::= OCTET STRING\n     *\n     *  The EncryptedData OCTET STRING is a PKCS#8 PrivateKeyInfo\n     *\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n    }\n\n    end = p + len;\n\n    if( ( ret = mbedtls_asn1_get_alg( &p, end, &pbe_alg_oid, &pbe_params ) ) != 0 )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )\n        return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );\n\n    buf = p;\n\n    /*\n     * Decrypt EncryptedData with appropriate PBE\n     */\n#if defined(MBEDTLS_PKCS12_C)\n    if( mbedtls_oid_get_pkcs12_pbe_alg( &pbe_alg_oid, &md_alg, &cipher_alg ) == 0 )\n    {\n        if( ( ret = mbedtls_pkcs12_pbe( &pbe_params, MBEDTLS_PKCS12_PBE_DECRYPT,\n                                cipher_alg, md_alg,\n                                pwd, pwdlen, p, len, buf ) ) != 0 )\n        {\n            if( ret == MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH )\n                return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH );\n\n            return( ret );\n        }\n\n        decrypted = 1;\n    }\n    else if( MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_128, &pbe_alg_oid ) == 0 )\n    {\n        if( ( ret = mbedtls_pkcs12_pbe_sha1_rc4_128( &pbe_params,\n                                             MBEDTLS_PKCS12_PBE_DECRYPT,\n                                             pwd, pwdlen,\n                                             p, len, buf ) ) != 0 )\n        {\n            return( ret );\n        }\n\n        // Best guess for password mismatch when using RC4. If first tag is\n        // not MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE\n        //\n        if( *buf != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )\n            return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH );\n\n        decrypted = 1;\n    }\n    else\n#endif /* MBEDTLS_PKCS12_C */\n#if defined(MBEDTLS_PKCS5_C)\n    if( MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS5_PBES2, &pbe_alg_oid ) == 0 )\n    {\n        if( ( ret = mbedtls_pkcs5_pbes2( &pbe_params, MBEDTLS_PKCS5_DECRYPT, pwd, pwdlen,\n                                  p, len, buf ) ) != 0 )\n        {\n            if( ret == MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH )\n                return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH );\n\n            return( ret );\n        }\n\n        decrypted = 1;\n    }\n    else\n#endif /* MBEDTLS_PKCS5_C */\n    {\n        ((void) pwd);\n    }\n\n    if( decrypted == 0 )\n        return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );\n\n    return( pk_parse_key_pkcs8_unencrypted_der( pk, buf, len ) );\n}\n#endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */\n\n/*\n * Parse a private key\n */\nint mbedtls_pk_parse_key( mbedtls_pk_context *pk,\n                  const unsigned char *key, size_t keylen,\n                  const unsigned char *pwd, size_t pwdlen )\n{\n    int ret;\n    const mbedtls_pk_info_t *pk_info;\n\n#if defined(MBEDTLS_PEM_PARSE_C)\n    size_t len;\n    mbedtls_pem_context pem;\n\n    mbedtls_pem_init( &pem );\n\n#if defined(MBEDTLS_RSA_C)\n    /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */\n    if( keylen == 0 || key[keylen - 1] != '\\0' )\n        ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;\n    else\n        ret = mbedtls_pem_read_buffer( &pem,\n                               \"-----BEGIN RSA PRIVATE KEY-----\",\n                               \"-----END RSA PRIVATE KEY-----\",\n                               key, pwd, pwdlen, &len );\n\n    if( ret == 0 )\n    {\n        pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA );\n        if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ||\n            ( ret = pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ),\n                                            pem.buf, pem.buflen ) ) != 0 )\n        {\n            mbedtls_pk_free( pk );\n        }\n\n        mbedtls_pem_free( &pem );\n        return( ret );\n    }\n    else if( ret == MBEDTLS_ERR_PEM_PASSWORD_MISMATCH )\n        return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH );\n    else if( ret == MBEDTLS_ERR_PEM_PASSWORD_REQUIRED )\n        return( MBEDTLS_ERR_PK_PASSWORD_REQUIRED );\n    else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )\n        return( ret );\n#endif /* MBEDTLS_RSA_C */\n\n#if defined(MBEDTLS_ECP_C)\n    /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */\n    if( keylen == 0 || key[keylen - 1] != '\\0' )\n        ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;\n    else\n        ret = mbedtls_pem_read_buffer( &pem,\n                               \"-----BEGIN EC PRIVATE KEY-----\",\n                               \"-----END EC PRIVATE KEY-----\",\n                               key, pwd, pwdlen, &len );\n    if( ret == 0 )\n    {\n        pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY );\n\n        if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ||\n            ( ret = pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ),\n                                           pem.buf, pem.buflen ) ) != 0 )\n        {\n            mbedtls_pk_free( pk );\n        }\n\n        mbedtls_pem_free( &pem );\n        return( ret );\n    }\n    else if( ret == MBEDTLS_ERR_PEM_PASSWORD_MISMATCH )\n        return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH );\n    else if( ret == MBEDTLS_ERR_PEM_PASSWORD_REQUIRED )\n        return( MBEDTLS_ERR_PK_PASSWORD_REQUIRED );\n    else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )\n        return( ret );\n#endif /* MBEDTLS_ECP_C */\n\n    /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */\n    if( keylen == 0 || key[keylen - 1] != '\\0' )\n        ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;\n    else\n        ret = mbedtls_pem_read_buffer( &pem,\n                               \"-----BEGIN PRIVATE KEY-----\",\n                               \"-----END PRIVATE KEY-----\",\n                               key, NULL, 0, &len );\n    if( ret == 0 )\n    {\n        if( ( ret = pk_parse_key_pkcs8_unencrypted_der( pk,\n                                                pem.buf, pem.buflen ) ) != 0 )\n        {\n            mbedtls_pk_free( pk );\n        }\n\n        mbedtls_pem_free( &pem );\n        return( ret );\n    }\n    else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )\n        return( ret );\n\n#if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)\n    /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */\n    if( keylen == 0 || key[keylen - 1] != '\\0' )\n        ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;\n    else\n        ret = mbedtls_pem_read_buffer( &pem,\n                               \"-----BEGIN ENCRYPTED PRIVATE KEY-----\",\n                               \"-----END ENCRYPTED PRIVATE KEY-----\",\n                               key, NULL, 0, &len );\n    if( ret == 0 )\n    {\n        if( ( ret = pk_parse_key_pkcs8_encrypted_der( pk,\n                                                      pem.buf, pem.buflen,\n                                                      pwd, pwdlen ) ) != 0 )\n        {\n            mbedtls_pk_free( pk );\n        }\n\n        mbedtls_pem_free( &pem );\n        return( ret );\n    }\n    else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )\n        return( ret );\n#endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */\n#else\n    ((void) pwd);\n    ((void) pwdlen);\n#endif /* MBEDTLS_PEM_PARSE_C */\n\n    /*\n     * At this point we only know it's not a PEM formatted key. Could be any\n     * of the known DER encoded private key formats\n     *\n     * We try the different DER format parsers to see if one passes without\n     * error\n     */\n#if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)\n    {\n        unsigned char *key_copy;\n\n        if( keylen == 0 )\n            return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );\n\n        if( ( key_copy = mbedtls_calloc( 1, keylen ) ) == NULL )\n            return( MBEDTLS_ERR_PK_ALLOC_FAILED );\n\n        memcpy( key_copy, key, keylen );\n\n        ret = pk_parse_key_pkcs8_encrypted_der( pk, key_copy, keylen,\n                                                pwd, pwdlen );\n\n        mbedtls_platform_zeroize( key_copy, keylen );\n        mbedtls_free( key_copy );\n    }\n\n    if( ret == 0 )\n        return( 0 );\n\n    mbedtls_pk_free( pk );\n\n    if( ret == MBEDTLS_ERR_PK_PASSWORD_MISMATCH )\n    {\n        return( ret );\n    }\n#endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */\n\n    if( ( ret = pk_parse_key_pkcs8_unencrypted_der( pk, key, keylen ) ) == 0 )\n        return( 0 );\n\n    mbedtls_pk_free( pk );\n\n#if defined(MBEDTLS_RSA_C)\n\n    pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA );\n    if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ||\n        ( ret = pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ),\n                                        key, keylen ) ) != 0 )\n    {\n        mbedtls_pk_free( pk );\n    }\n    else\n    {\n        return( 0 );\n    }\n\n#endif /* MBEDTLS_RSA_C */\n\n#if defined(MBEDTLS_ECP_C)\n\n    pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY );\n    if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ||\n        ( ret = pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ),\n                                       key, keylen ) ) != 0 )\n    {\n        mbedtls_pk_free( pk );\n    }\n    else\n    {\n        return( 0 );\n    }\n\n#endif /* MBEDTLS_ECP_C */\n\n    return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );\n}\n\n/*\n * Parse a public key\n */\nint mbedtls_pk_parse_public_key( mbedtls_pk_context *ctx,\n                         const unsigned char *key, size_t keylen )\n{\n    int ret;\n    unsigned char *p;\n#if defined(MBEDTLS_RSA_C)\n    const mbedtls_pk_info_t *pk_info;\n#endif\n#if defined(MBEDTLS_PEM_PARSE_C)\n    size_t len;\n    mbedtls_pem_context pem;\n\n    mbedtls_pem_init( &pem );\n#if defined(MBEDTLS_RSA_C)\n    /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */\n    if( keylen == 0 || key[keylen - 1] != '\\0' )\n        ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;\n    else\n        ret = mbedtls_pem_read_buffer( &pem,\n                               \"-----BEGIN RSA PUBLIC KEY-----\",\n                               \"-----END RSA PUBLIC KEY-----\",\n                               key, NULL, 0, &len );\n\n    if( ret == 0 )\n    {\n        p = pem.buf;\n        if( ( pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA ) ) == NULL )\n            return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );\n\n        if( ( ret = mbedtls_pk_setup( ctx, pk_info ) ) != 0 )\n            return( ret );\n\n        if ( ( ret = pk_get_rsapubkey( &p, p + pem.buflen, mbedtls_pk_rsa( *ctx ) ) ) != 0 )\n            mbedtls_pk_free( ctx );\n\n        mbedtls_pem_free( &pem );\n        return( ret );\n    }\n    else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )\n    {\n        mbedtls_pem_free( &pem );\n        return( ret );\n    }\n#endif /* MBEDTLS_RSA_C */\n\n    /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */\n    if( keylen == 0 || key[keylen - 1] != '\\0' )\n        ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;\n    else\n        ret = mbedtls_pem_read_buffer( &pem,\n                \"-----BEGIN PUBLIC KEY-----\",\n                \"-----END PUBLIC KEY-----\",\n                key, NULL, 0, &len );\n\n    if( ret == 0 )\n    {\n        /*\n         * Was PEM encoded\n         */\n        p = pem.buf;\n\n        ret = mbedtls_pk_parse_subpubkey( &p,  p + pem.buflen, ctx );\n        mbedtls_pem_free( &pem );\n        return( ret );\n    }\n    else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )\n    {\n        mbedtls_pem_free( &pem );\n        return( ret );\n    }\n    mbedtls_pem_free( &pem );\n#endif /* MBEDTLS_PEM_PARSE_C */\n\n#if defined(MBEDTLS_RSA_C)\n    if( ( pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA ) ) == NULL )\n        return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );\n\n    if( ( ret = mbedtls_pk_setup( ctx, pk_info ) ) != 0 )\n        return( ret );\n\n    p = (unsigned char *)key;\n    ret = pk_get_rsapubkey( &p, p + keylen, mbedtls_pk_rsa( *ctx ) );\n    if( ret == 0 )\n    {\n        return( ret );\n    }\n    mbedtls_pk_free( ctx );\n    if( ret != ( MBEDTLS_ERR_PK_INVALID_PUBKEY + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) )\n    {\n        return( ret );\n    }\n#endif /* MBEDTLS_RSA_C */\n    p = (unsigned char *) key;\n\n    ret = mbedtls_pk_parse_subpubkey( &p, p + keylen, ctx );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_PK_PARSE_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/pkwrite.c",
    "content": "/*\n *  Public Key layer for writing key files and structures\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_PK_WRITE_C)\n\n#include \"mbedtls/pk.h\"\n#include \"mbedtls/asn1write.h\"\n#include \"mbedtls/oid.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_RSA_C)\n#include \"mbedtls/rsa.h\"\n#endif\n#if defined(MBEDTLS_ECP_C)\n#include \"mbedtls/ecp.h\"\n#endif\n#if defined(MBEDTLS_ECDSA_C)\n#include \"mbedtls/ecdsa.h\"\n#endif\n#if defined(MBEDTLS_PEM_WRITE_C)\n#include \"mbedtls/pem.h\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc    calloc\n#define mbedtls_free       free\n#endif\n\n#if defined(MBEDTLS_RSA_C)\n/*\n *  RSAPublicKey ::= SEQUENCE {\n *      modulus           INTEGER,  -- n\n *      publicExponent    INTEGER   -- e\n *  }\n */\nstatic int pk_write_rsa_pubkey( unsigned char **p, unsigned char *start,\n                                mbedtls_rsa_context *rsa )\n{\n    int ret;\n    size_t len = 0;\n    mbedtls_mpi T;\n\n    mbedtls_mpi_init( &T );\n\n    /* Export E */\n    if ( ( ret = mbedtls_rsa_export( rsa, NULL, NULL, NULL, NULL, &T ) ) != 0 ||\n         ( ret = mbedtls_asn1_write_mpi( p, start, &T ) ) < 0 )\n        goto end_of_export;\n    len += ret;\n\n    /* Export N */\n    if ( ( ret = mbedtls_rsa_export( rsa, &T, NULL, NULL, NULL, NULL ) ) != 0 ||\n         ( ret = mbedtls_asn1_write_mpi( p, start, &T ) ) < 0 )\n        goto end_of_export;\n    len += ret;\n\nend_of_export:\n\n    mbedtls_mpi_free( &T );\n    if( ret < 0 )\n        return( ret );\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED |\n                                                 MBEDTLS_ASN1_SEQUENCE ) );\n\n    return( (int) len );\n}\n#endif /* MBEDTLS_RSA_C */\n\n#if defined(MBEDTLS_ECP_C)\n/*\n * EC public key is an EC point\n */\nstatic int pk_write_ec_pubkey( unsigned char **p, unsigned char *start,\n                               mbedtls_ecp_keypair *ec )\n{\n    int ret;\n    size_t len = 0;\n    unsigned char buf[MBEDTLS_ECP_MAX_PT_LEN];\n\n    if( ( ret = mbedtls_ecp_point_write_binary( &ec->grp, &ec->Q,\n                                        MBEDTLS_ECP_PF_UNCOMPRESSED,\n                                        &len, buf, sizeof( buf ) ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    if( *p < start || (size_t)( *p - start ) < len )\n        return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n    *p -= len;\n    memcpy( *p, buf, len );\n\n    return( (int) len );\n}\n\n/*\n * ECParameters ::= CHOICE {\n *   namedCurve         OBJECT IDENTIFIER\n * }\n */\nstatic int pk_write_ec_param( unsigned char **p, unsigned char *start,\n                              mbedtls_ecp_keypair *ec )\n{\n    int ret;\n    size_t len = 0;\n    const char *oid;\n    size_t oid_len;\n\n    if( ( ret = mbedtls_oid_get_oid_by_ec_grp( ec->grp.id, &oid, &oid_len ) ) != 0 )\n        return( ret );\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_oid( p, start, oid, oid_len ) );\n\n    return( (int) len );\n}\n#endif /* MBEDTLS_ECP_C */\n\nint mbedtls_pk_write_pubkey( unsigned char **p, unsigned char *start,\n                             const mbedtls_pk_context *key )\n{\n    int ret;\n    size_t len = 0;\n\n#if defined(MBEDTLS_RSA_C)\n    if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_RSA )\n        MBEDTLS_ASN1_CHK_ADD( len, pk_write_rsa_pubkey( p, start, mbedtls_pk_rsa( *key ) ) );\n    else\n#endif\n#if defined(MBEDTLS_ECP_C)\n    if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_ECKEY )\n        MBEDTLS_ASN1_CHK_ADD( len, pk_write_ec_pubkey( p, start, mbedtls_pk_ec( *key ) ) );\n    else\n#endif\n        return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );\n\n    return( (int) len );\n}\n\nint mbedtls_pk_write_pubkey_der( mbedtls_pk_context *key, unsigned char *buf, size_t size )\n{\n    int ret;\n    unsigned char *c;\n    size_t len = 0, par_len = 0, oid_len;\n    const char *oid;\n\n    c = buf + size;\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_pk_write_pubkey( &c, buf, key ) );\n\n    if( c - buf < 1 )\n        return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n    /*\n     *  SubjectPublicKeyInfo  ::=  SEQUENCE  {\n     *       algorithm            AlgorithmIdentifier,\n     *       subjectPublicKey     BIT STRING }\n     */\n    *--c = 0;\n    len += 1;\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_BIT_STRING ) );\n\n    if( ( ret = mbedtls_oid_get_oid_by_pk_alg( mbedtls_pk_get_type( key ),\n                                       &oid, &oid_len ) ) != 0 )\n    {\n        return( ret );\n    }\n\n#if defined(MBEDTLS_ECP_C)\n    if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_ECKEY )\n    {\n        MBEDTLS_ASN1_CHK_ADD( par_len, pk_write_ec_param( &c, buf, mbedtls_pk_ec( *key ) ) );\n    }\n#endif\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_algorithm_identifier( &c, buf, oid, oid_len,\n                                                        par_len ) );\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED |\n                                                MBEDTLS_ASN1_SEQUENCE ) );\n\n    return( (int) len );\n}\n\nint mbedtls_pk_write_key_der( mbedtls_pk_context *key, unsigned char *buf, size_t size )\n{\n    int ret;\n    unsigned char *c = buf + size;\n    size_t len = 0;\n\n#if defined(MBEDTLS_RSA_C)\n    if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_RSA )\n    {\n        mbedtls_mpi T; /* Temporary holding the exported parameters */\n        mbedtls_rsa_context *rsa = mbedtls_pk_rsa( *key );\n\n        /*\n         * Export the parameters one after another to avoid simultaneous copies.\n         */\n\n        mbedtls_mpi_init( &T );\n\n        /* Export QP */\n        if( ( ret = mbedtls_rsa_export_crt( rsa, NULL, NULL, &T ) ) != 0 ||\n            ( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )\n            goto end_of_export;\n        len += ret;\n\n        /* Export DQ */\n        if( ( ret = mbedtls_rsa_export_crt( rsa, NULL, &T, NULL ) ) != 0 ||\n            ( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )\n            goto end_of_export;\n        len += ret;\n\n        /* Export DP */\n        if( ( ret = mbedtls_rsa_export_crt( rsa, &T, NULL, NULL ) ) != 0 ||\n            ( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )\n            goto end_of_export;\n        len += ret;\n\n        /* Export Q */\n        if ( ( ret = mbedtls_rsa_export( rsa, NULL, NULL,\n                                         &T, NULL, NULL ) ) != 0 ||\n             ( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )\n            goto end_of_export;\n        len += ret;\n\n        /* Export P */\n        if ( ( ret = mbedtls_rsa_export( rsa, NULL, &T,\n                                         NULL, NULL, NULL ) ) != 0 ||\n             ( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )\n            goto end_of_export;\n        len += ret;\n\n        /* Export D */\n        if ( ( ret = mbedtls_rsa_export( rsa, NULL, NULL,\n                                         NULL, &T, NULL ) ) != 0 ||\n             ( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )\n            goto end_of_export;\n        len += ret;\n\n        /* Export E */\n        if ( ( ret = mbedtls_rsa_export( rsa, NULL, NULL,\n                                         NULL, NULL, &T ) ) != 0 ||\n             ( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )\n            goto end_of_export;\n        len += ret;\n\n        /* Export N */\n        if ( ( ret = mbedtls_rsa_export( rsa, &T, NULL,\n                                         NULL, NULL, NULL ) ) != 0 ||\n             ( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )\n            goto end_of_export;\n        len += ret;\n\n    end_of_export:\n\n        mbedtls_mpi_free( &T );\n        if( ret < 0 )\n            return( ret );\n\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_int( &c, buf, 0 ) );\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c,\n                                               buf, MBEDTLS_ASN1_CONSTRUCTED |\n                                               MBEDTLS_ASN1_SEQUENCE ) );\n    }\n    else\n#endif /* MBEDTLS_RSA_C */\n#if defined(MBEDTLS_ECP_C)\n    if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_ECKEY )\n    {\n        mbedtls_ecp_keypair *ec = mbedtls_pk_ec( *key );\n        size_t pub_len = 0, par_len = 0;\n\n        /*\n         * RFC 5915, or SEC1 Appendix C.4\n         *\n         * ECPrivateKey ::= SEQUENCE {\n         *      version        INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),\n         *      privateKey     OCTET STRING,\n         *      parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,\n         *      publicKey  [1] BIT STRING OPTIONAL\n         *    }\n         */\n\n        /* publicKey */\n        MBEDTLS_ASN1_CHK_ADD( pub_len, pk_write_ec_pubkey( &c, buf, ec ) );\n\n        if( c - buf < 1 )\n            return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n        *--c = 0;\n        pub_len += 1;\n\n        MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_asn1_write_len( &c, buf, pub_len ) );\n        MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_BIT_STRING ) );\n\n        MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_asn1_write_len( &c, buf, pub_len ) );\n        MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_asn1_write_tag( &c, buf,\n                            MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 1 ) );\n        len += pub_len;\n\n        /* parameters */\n        MBEDTLS_ASN1_CHK_ADD( par_len, pk_write_ec_param( &c, buf, ec ) );\n\n        MBEDTLS_ASN1_CHK_ADD( par_len, mbedtls_asn1_write_len( &c, buf, par_len ) );\n        MBEDTLS_ASN1_CHK_ADD( par_len, mbedtls_asn1_write_tag( &c, buf,\n                            MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) );\n        len += par_len;\n\n        /* privateKey: write as MPI then fix tag */\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &c, buf, &ec->d ) );\n        *c = MBEDTLS_ASN1_OCTET_STRING;\n\n        /* version */\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_int( &c, buf, 1 ) );\n\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED |\n                                                    MBEDTLS_ASN1_SEQUENCE ) );\n    }\n    else\n#endif /* MBEDTLS_ECP_C */\n        return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );\n\n    return( (int) len );\n}\n\n#if defined(MBEDTLS_PEM_WRITE_C)\n\n#define PEM_BEGIN_PUBLIC_KEY    \"-----BEGIN PUBLIC KEY-----\\n\"\n#define PEM_END_PUBLIC_KEY      \"-----END PUBLIC KEY-----\\n\"\n\n#define PEM_BEGIN_PRIVATE_KEY_RSA   \"-----BEGIN RSA PRIVATE KEY-----\\n\"\n#define PEM_END_PRIVATE_KEY_RSA     \"-----END RSA PRIVATE KEY-----\\n\"\n#define PEM_BEGIN_PRIVATE_KEY_EC    \"-----BEGIN EC PRIVATE KEY-----\\n\"\n#define PEM_END_PRIVATE_KEY_EC      \"-----END EC PRIVATE KEY-----\\n\"\n\n/*\n * Max sizes of key per types. Shown as tag + len (+ content).\n */\n\n#if defined(MBEDTLS_RSA_C)\n/*\n * RSA public keys:\n *  SubjectPublicKeyInfo  ::=  SEQUENCE  {          1 + 3\n *       algorithm            AlgorithmIdentifier,  1 + 1 (sequence)\n *                                                + 1 + 1 + 9 (rsa oid)\n *                                                + 1 + 1 (params null)\n *       subjectPublicKey     BIT STRING }          1 + 3 + (1 + below)\n *  RSAPublicKey ::= SEQUENCE {                     1 + 3\n *      modulus           INTEGER,  -- n            1 + 3 + MPI_MAX + 1\n *      publicExponent    INTEGER   -- e            1 + 3 + MPI_MAX + 1\n *  }\n */\n#define RSA_PUB_DER_MAX_BYTES   38 + 2 * MBEDTLS_MPI_MAX_SIZE\n\n/*\n * RSA private keys:\n *  RSAPrivateKey ::= SEQUENCE {                    1 + 3\n *      version           Version,                  1 + 1 + 1\n *      modulus           INTEGER,                  1 + 3 + MPI_MAX + 1\n *      publicExponent    INTEGER,                  1 + 3 + MPI_MAX + 1\n *      privateExponent   INTEGER,                  1 + 3 + MPI_MAX + 1\n *      prime1            INTEGER,                  1 + 3 + MPI_MAX / 2 + 1\n *      prime2            INTEGER,                  1 + 3 + MPI_MAX / 2 + 1\n *      exponent1         INTEGER,                  1 + 3 + MPI_MAX / 2 + 1\n *      exponent2         INTEGER,                  1 + 3 + MPI_MAX / 2 + 1\n *      coefficient       INTEGER,                  1 + 3 + MPI_MAX / 2 + 1\n *      otherPrimeInfos   OtherPrimeInfos OPTIONAL  0 (not supported)\n *  }\n */\n#define MPI_MAX_SIZE_2          MBEDTLS_MPI_MAX_SIZE / 2 + \\\n                                MBEDTLS_MPI_MAX_SIZE % 2\n#define RSA_PRV_DER_MAX_BYTES   47 + 3 * MBEDTLS_MPI_MAX_SIZE \\\n                                   + 5 * MPI_MAX_SIZE_2\n\n#else /* MBEDTLS_RSA_C */\n\n#define RSA_PUB_DER_MAX_BYTES   0\n#define RSA_PRV_DER_MAX_BYTES   0\n\n#endif /* MBEDTLS_RSA_C */\n\n#if defined(MBEDTLS_ECP_C)\n/*\n * EC public keys:\n *  SubjectPublicKeyInfo  ::=  SEQUENCE  {      1 + 2\n *    algorithm         AlgorithmIdentifier,    1 + 1 (sequence)\n *                                            + 1 + 1 + 7 (ec oid)\n *                                            + 1 + 1 + 9 (namedCurve oid)\n *    subjectPublicKey  BIT STRING              1 + 2 + 1               [1]\n *                                            + 1 (point format)        [1]\n *                                            + 2 * ECP_MAX (coords)    [1]\n *  }\n */\n#define ECP_PUB_DER_MAX_BYTES   30 + 2 * MBEDTLS_ECP_MAX_BYTES\n\n/*\n * EC private keys:\n * ECPrivateKey ::= SEQUENCE {                  1 + 2\n *      version        INTEGER ,                1 + 1 + 1\n *      privateKey     OCTET STRING,            1 + 1 + ECP_MAX\n *      parameters [0] ECParameters OPTIONAL,   1 + 1 + (1 + 1 + 9)\n *      publicKey  [1] BIT STRING OPTIONAL      1 + 2 + [1] above\n *    }\n */\n#define ECP_PRV_DER_MAX_BYTES   29 + 3 * MBEDTLS_ECP_MAX_BYTES\n\n#else /* MBEDTLS_ECP_C */\n\n#define ECP_PUB_DER_MAX_BYTES   0\n#define ECP_PRV_DER_MAX_BYTES   0\n\n#endif /* MBEDTLS_ECP_C */\n\n#define PUB_DER_MAX_BYTES   RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \\\n                            RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES\n#define PRV_DER_MAX_BYTES   RSA_PRV_DER_MAX_BYTES > ECP_PRV_DER_MAX_BYTES ? \\\n                            RSA_PRV_DER_MAX_BYTES : ECP_PRV_DER_MAX_BYTES\n\nint mbedtls_pk_write_pubkey_pem( mbedtls_pk_context *key, unsigned char *buf, size_t size )\n{\n    int ret;\n    unsigned char output_buf[PUB_DER_MAX_BYTES];\n    size_t olen = 0;\n\n    if( ( ret = mbedtls_pk_write_pubkey_der( key, output_buf,\n                                     sizeof(output_buf) ) ) < 0 )\n    {\n        return( ret );\n    }\n\n    if( ( ret = mbedtls_pem_write_buffer( PEM_BEGIN_PUBLIC_KEY, PEM_END_PUBLIC_KEY,\n                                  output_buf + sizeof(output_buf) - ret,\n                                  ret, buf, size, &olen ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    return( 0 );\n}\n\nint mbedtls_pk_write_key_pem( mbedtls_pk_context *key, unsigned char *buf, size_t size )\n{\n    int ret;\n    unsigned char output_buf[PRV_DER_MAX_BYTES];\n    const char *begin, *end;\n    size_t olen = 0;\n\n    if( ( ret = mbedtls_pk_write_key_der( key, output_buf, sizeof(output_buf) ) ) < 0 )\n        return( ret );\n\n#if defined(MBEDTLS_RSA_C)\n    if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_RSA )\n    {\n        begin = PEM_BEGIN_PRIVATE_KEY_RSA;\n        end = PEM_END_PRIVATE_KEY_RSA;\n    }\n    else\n#endif\n#if defined(MBEDTLS_ECP_C)\n    if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_ECKEY )\n    {\n        begin = PEM_BEGIN_PRIVATE_KEY_EC;\n        end = PEM_END_PRIVATE_KEY_EC;\n    }\n    else\n#endif\n        return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );\n\n    if( ( ret = mbedtls_pem_write_buffer( begin, end,\n                                  output_buf + sizeof(output_buf) - ret,\n                                  ret, buf, size, &olen ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_PEM_WRITE_C */\n\n#endif /* MBEDTLS_PK_WRITE_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/platform.c",
    "content": "/*\n *  Platform abstraction layer\n *\n *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_PLATFORM_C)\n\n#include \"mbedtls/platform.h\"\n#include \"mbedtls/platform_util.h\"\n\n#if defined(MBEDTLS_PLATFORM_MEMORY)\n#if !defined(MBEDTLS_PLATFORM_STD_CALLOC)\nstatic void *platform_calloc_uninit( size_t n, size_t size )\n{\n    ((void) n);\n    ((void) size);\n    return( NULL );\n}\n\n#define MBEDTLS_PLATFORM_STD_CALLOC   platform_calloc_uninit\n#endif /* !MBEDTLS_PLATFORM_STD_CALLOC */\n\n#if !defined(MBEDTLS_PLATFORM_STD_FREE)\nstatic void platform_free_uninit( void *ptr )\n{\n    ((void) ptr);\n}\n\n#define MBEDTLS_PLATFORM_STD_FREE     platform_free_uninit\n#endif /* !MBEDTLS_PLATFORM_STD_FREE */\n\nstatic void * (*mbedtls_calloc_func)( size_t, size_t ) = MBEDTLS_PLATFORM_STD_CALLOC;\nstatic void (*mbedtls_free_func)( void * ) = MBEDTLS_PLATFORM_STD_FREE;\n\nvoid * mbedtls_calloc( size_t nmemb, size_t size )\n{\n    return (*mbedtls_calloc_func)( nmemb, size );\n}\n\nvoid mbedtls_free( void * ptr )\n{\n    (*mbedtls_free_func)( ptr );\n}\n\nint mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ),\n                              void (*free_func)( void * ) )\n{\n    mbedtls_calloc_func = calloc_func;\n    mbedtls_free_func = free_func;\n    return( 0 );\n}\n#endif /* MBEDTLS_PLATFORM_MEMORY */\n\n#if defined(_WIN32)\n#include <stdarg.h>\nint mbedtls_platform_win32_snprintf( char *s, size_t n, const char *fmt, ... )\n{\n    int ret;\n    va_list argp;\n\n    /* Avoid calling the invalid parameter handler by checking ourselves */\n    if( s == NULL || n == 0 || fmt == NULL )\n        return( -1 );\n\n    va_start( argp, fmt );\n#if defined(_TRUNCATE) && !defined(__MINGW32__)\n    ret = _vsnprintf_s( s, n, _TRUNCATE, fmt, argp );\n#else\n    ret = _vsnprintf( s, n, fmt, argp );\n    if( ret < 0 || (size_t) ret == n )\n    {\n        s[n-1] = '\\0';\n        ret = -1;\n    }\n#endif\n    va_end( argp );\n\n    return( ret );\n}\n#endif\n\n#if defined(MBEDTLS_PLATFORM_SNPRINTF_ALT)\n#if !defined(MBEDTLS_PLATFORM_STD_SNPRINTF)\n/*\n * Make dummy function to prevent NULL pointer dereferences\n */\nstatic int platform_snprintf_uninit( char * s, size_t n,\n                                     const char * format, ... )\n{\n    ((void) s);\n    ((void) n);\n    ((void) format);\n    return( 0 );\n}\n\n#define MBEDTLS_PLATFORM_STD_SNPRINTF    platform_snprintf_uninit\n#endif /* !MBEDTLS_PLATFORM_STD_SNPRINTF */\n\nint (*mbedtls_snprintf)( char * s, size_t n,\n                          const char * format,\n                          ... ) = MBEDTLS_PLATFORM_STD_SNPRINTF;\n\nint mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n,\n                                                 const char * format,\n                                                 ... ) )\n{\n    mbedtls_snprintf = snprintf_func;\n    return( 0 );\n}\n#endif /* MBEDTLS_PLATFORM_SNPRINTF_ALT */\n\n#if defined(MBEDTLS_PLATFORM_PRINTF_ALT)\n#if !defined(MBEDTLS_PLATFORM_STD_PRINTF)\n/*\n * Make dummy function to prevent NULL pointer dereferences\n */\nstatic int platform_printf_uninit( const char *format, ... )\n{\n    ((void) format);\n    return( 0 );\n}\n\n#define MBEDTLS_PLATFORM_STD_PRINTF    platform_printf_uninit\n#endif /* !MBEDTLS_PLATFORM_STD_PRINTF */\n\nint (*mbedtls_printf)( const char *, ... ) = MBEDTLS_PLATFORM_STD_PRINTF;\n\nint mbedtls_platform_set_printf( int (*printf_func)( const char *, ... ) )\n{\n    mbedtls_printf = printf_func;\n    return( 0 );\n}\n#endif /* MBEDTLS_PLATFORM_PRINTF_ALT */\n\n#if defined(MBEDTLS_PLATFORM_FPRINTF_ALT)\n#if !defined(MBEDTLS_PLATFORM_STD_FPRINTF)\n/*\n * Make dummy function to prevent NULL pointer dereferences\n */\nstatic int platform_fprintf_uninit( FILE *stream, const char *format, ... )\n{\n    ((void) stream);\n    ((void) format);\n    return( 0 );\n}\n\n#define MBEDTLS_PLATFORM_STD_FPRINTF   platform_fprintf_uninit\n#endif /* !MBEDTLS_PLATFORM_STD_FPRINTF */\n\nint (*mbedtls_fprintf)( FILE *, const char *, ... ) =\n                                        MBEDTLS_PLATFORM_STD_FPRINTF;\n\nint mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *, const char *, ... ) )\n{\n    mbedtls_fprintf = fprintf_func;\n    return( 0 );\n}\n#endif /* MBEDTLS_PLATFORM_FPRINTF_ALT */\n\n#if defined(MBEDTLS_PLATFORM_EXIT_ALT)\n#if !defined(MBEDTLS_PLATFORM_STD_EXIT)\n/*\n * Make dummy function to prevent NULL pointer dereferences\n */\nstatic void platform_exit_uninit( int status )\n{\n    ((void) status);\n}\n\n#define MBEDTLS_PLATFORM_STD_EXIT   platform_exit_uninit\n#endif /* !MBEDTLS_PLATFORM_STD_EXIT */\n\nvoid (*mbedtls_exit)( int status ) = MBEDTLS_PLATFORM_STD_EXIT;\n\nint mbedtls_platform_set_exit( void (*exit_func)( int status ) )\n{\n    mbedtls_exit = exit_func;\n    return( 0 );\n}\n#endif /* MBEDTLS_PLATFORM_EXIT_ALT */\n\n#if defined(MBEDTLS_HAVE_TIME)\n\n#if defined(MBEDTLS_PLATFORM_TIME_ALT)\n#if !defined(MBEDTLS_PLATFORM_STD_TIME)\n/*\n * Make dummy function to prevent NULL pointer dereferences\n */\nstatic mbedtls_time_t platform_time_uninit( mbedtls_time_t* timer )\n{\n    ((void) timer);\n    return( 0 );\n}\n\n#define MBEDTLS_PLATFORM_STD_TIME   platform_time_uninit\n#endif /* !MBEDTLS_PLATFORM_STD_TIME */\n\nmbedtls_time_t (*mbedtls_time)( mbedtls_time_t* timer ) = MBEDTLS_PLATFORM_STD_TIME;\n\nint mbedtls_platform_set_time( mbedtls_time_t (*time_func)( mbedtls_time_t* timer ) )\n{\n    mbedtls_time = time_func;\n    return( 0 );\n}\n#endif /* MBEDTLS_PLATFORM_TIME_ALT */\n\n#endif /* MBEDTLS_HAVE_TIME */\n\n#if defined(MBEDTLS_ENTROPY_NV_SEED)\n#if !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS) && defined(MBEDTLS_FS_IO)\n/* Default implementations for the platform independent seed functions use\n * standard libc file functions to read from and write to a pre-defined filename\n */\nint mbedtls_platform_std_nv_seed_read( unsigned char *buf, size_t buf_len )\n{\n    FILE *file;\n    size_t n;\n\n    if( ( file = fopen( MBEDTLS_PLATFORM_STD_NV_SEED_FILE, \"rb\" ) ) == NULL )\n        return( -1 );\n\n    if( ( n = fread( buf, 1, buf_len, file ) ) != buf_len )\n    {\n        fclose( file );\n        mbedtls_platform_zeroize( buf, buf_len );\n        return( -1 );\n    }\n\n    fclose( file );\n    return( (int)n );\n}\n\nint mbedtls_platform_std_nv_seed_write( unsigned char *buf, size_t buf_len )\n{\n    FILE *file;\n    size_t n;\n\n    if( ( file = fopen( MBEDTLS_PLATFORM_STD_NV_SEED_FILE, \"w\" ) ) == NULL )\n        return -1;\n\n    if( ( n = fwrite( buf, 1, buf_len, file ) ) != buf_len )\n    {\n        fclose( file );\n        return -1;\n    }\n\n    fclose( file );\n    return( (int)n );\n}\n#endif /* MBEDTLS_PLATFORM_NO_STD_FUNCTIONS */\n\n#if defined(MBEDTLS_PLATFORM_NV_SEED_ALT)\n#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ)\n/*\n * Make dummy function to prevent NULL pointer dereferences\n */\nstatic int platform_nv_seed_read_uninit( unsigned char *buf, size_t buf_len )\n{\n    ((void) buf);\n    ((void) buf_len);\n    return( -1 );\n}\n\n#define MBEDTLS_PLATFORM_STD_NV_SEED_READ   platform_nv_seed_read_uninit\n#endif /* !MBEDTLS_PLATFORM_STD_NV_SEED_READ */\n\n#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE)\n/*\n * Make dummy function to prevent NULL pointer dereferences\n */\nstatic int platform_nv_seed_write_uninit( unsigned char *buf, size_t buf_len )\n{\n    ((void) buf);\n    ((void) buf_len);\n    return( -1 );\n}\n\n#define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE   platform_nv_seed_write_uninit\n#endif /* !MBEDTLS_PLATFORM_STD_NV_SEED_WRITE */\n\nint (*mbedtls_nv_seed_read)( unsigned char *buf, size_t buf_len ) =\n            MBEDTLS_PLATFORM_STD_NV_SEED_READ;\nint (*mbedtls_nv_seed_write)( unsigned char *buf, size_t buf_len ) =\n            MBEDTLS_PLATFORM_STD_NV_SEED_WRITE;\n\nint mbedtls_platform_set_nv_seed(\n        int (*nv_seed_read_func)( unsigned char *buf, size_t buf_len ),\n        int (*nv_seed_write_func)( unsigned char *buf, size_t buf_len ) )\n{\n    mbedtls_nv_seed_read = nv_seed_read_func;\n    mbedtls_nv_seed_write = nv_seed_write_func;\n    return( 0 );\n}\n#endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */\n#endif /* MBEDTLS_ENTROPY_NV_SEED */\n\n#if !defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT)\n/*\n * Placeholder platform setup that does nothing by default\n */\nint mbedtls_platform_setup( mbedtls_platform_context *ctx )\n{\n    (void)ctx;\n\n    return( 0 );\n}\n\n/*\n * Placeholder platform teardown that does nothing by default\n */\nvoid mbedtls_platform_teardown( mbedtls_platform_context *ctx )\n{\n    (void)ctx;\n}\n#endif /* MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */\n\n#endif /* MBEDTLS_PLATFORM_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/platform_util.c",
    "content": "/*\n * Common and shared functions used by multiple modules in the Mbed TLS\n * library.\n *\n *  Copyright (C) 2018, Arm Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of Mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#include \"mbedtls/platform_util.h\"\n\n#include <stddef.h>\n#include <string.h>\n\n#if !defined(MBEDTLS_PLATFORM_ZEROIZE_ALT)\n/*\n * This implementation should never be optimized out by the compiler\n *\n * This implementation for mbedtls_platform_zeroize() was inspired from Colin\n * Percival's blog article at:\n *\n * http://www.daemonology.net/blog/2014-09-04-how-to-zero-a-buffer.html\n *\n * It uses a volatile function pointer to the standard memset(). Because the\n * pointer is volatile the compiler expects it to change at\n * any time and will not optimize out the call that could potentially perform\n * other operations on the input buffer instead of just setting it to 0.\n * Nevertheless, as pointed out by davidtgoldblatt on Hacker News\n * (refer to http://www.daemonology.net/blog/2014-09-05-erratum.html for\n * details), optimizations of the following form are still possible:\n *\n * if( memset_func != memset )\n *     memset_func( buf, 0, len );\n *\n * Note that it is extremely difficult to guarantee that\n * mbedtls_platform_zeroize() will not be optimized out by aggressive compilers\n * in a portable way. For this reason, Mbed TLS also provides the configuration\n * option MBEDTLS_PLATFORM_ZEROIZE_ALT, which allows users to configure\n * mbedtls_platform_zeroize() to use a suitable implementation for their\n * platform and needs.\n */\nstatic void * (* const volatile memset_func)( void *, int, size_t ) = memset;\n\nvoid mbedtls_platform_zeroize( void *buf, size_t len )\n{\n    memset_func( buf, 0, len );\n}\n#endif /* MBEDTLS_PLATFORM_ZEROIZE_ALT */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/poly1305.c",
    "content": "/**\n * \\file poly1305.c\n *\n * \\brief Poly1305 authentication algorithm.\n *\n *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_POLY1305_C)\n\n#include \"mbedtls/poly1305.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if !defined(MBEDTLS_POLY1305_ALT)\n\n#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \\\n    !defined(inline) && !defined(__cplusplus)\n#define inline __inline\n#endif\n\n#define POLY1305_BLOCK_SIZE_BYTES ( 16U )\n\n#define BYTES_TO_U32_LE( data, offset )                           \\\n    ( (uint32_t) data[offset]                                     \\\n          | (uint32_t) ( (uint32_t) data[( offset ) + 1] << 8 )   \\\n          | (uint32_t) ( (uint32_t) data[( offset ) + 2] << 16 )  \\\n          | (uint32_t) ( (uint32_t) data[( offset ) + 3] << 24 )  \\\n    )\n\n/*\n * Our implementation is tuned for 32-bit platforms with a 64-bit multiplier.\n * However we provided an alternative for platforms without such a multiplier.\n */\n#if defined(MBEDTLS_NO_64BIT_MULTIPLICATION)\nstatic uint64_t mul64( uint32_t a, uint32_t b )\n{\n    /* a = al + 2**16 ah, b = bl + 2**16 bh */\n    const uint16_t al = (uint16_t) a;\n    const uint16_t bl = (uint16_t) b;\n    const uint16_t ah = a >> 16;\n    const uint16_t bh = b >> 16;\n\n    /* ab = al*bl + 2**16 (ah*bl + bl*bh) + 2**32 ah*bh */\n    const uint32_t lo = (uint32_t) al * bl;\n    const uint64_t me = (uint64_t)( (uint32_t) ah * bl ) + (uint32_t) al * bh;\n    const uint32_t hi = (uint32_t) ah * bh;\n\n    return( lo + ( me << 16 ) + ( (uint64_t) hi << 32 ) );\n}\n#else\nstatic inline uint64_t mul64( uint32_t a, uint32_t b )\n{\n    return( (uint64_t) a * b );\n}\n#endif\n\n\n/**\n * \\brief                   Process blocks with Poly1305.\n *\n * \\param ctx               The Poly1305 context.\n * \\param nblocks           Number of blocks to process. Note that this\n *                          function only processes full blocks.\n * \\param input             Buffer containing the input block(s).\n * \\param needs_padding     Set to 0 if the padding bit has already been\n *                          applied to the input data before calling this\n *                          function.  Otherwise, set this parameter to 1.\n */\nstatic void poly1305_process( mbedtls_poly1305_context *ctx,\n                              size_t nblocks,\n                              const unsigned char *input,\n                              uint32_t needs_padding )\n{\n    uint64_t d0, d1, d2, d3;\n    uint32_t acc0, acc1, acc2, acc3, acc4;\n    uint32_t r0, r1, r2, r3;\n    uint32_t rs1, rs2, rs3;\n    size_t offset  = 0U;\n    size_t i;\n\n    r0 = ctx->r[0];\n    r1 = ctx->r[1];\n    r2 = ctx->r[2];\n    r3 = ctx->r[3];\n\n    rs1 = r1 + ( r1 >> 2U );\n    rs2 = r2 + ( r2 >> 2U );\n    rs3 = r3 + ( r3 >> 2U );\n\n    acc0 = ctx->acc[0];\n    acc1 = ctx->acc[1];\n    acc2 = ctx->acc[2];\n    acc3 = ctx->acc[3];\n    acc4 = ctx->acc[4];\n\n    /* Process full blocks */\n    for( i = 0U; i < nblocks; i++ )\n    {\n        /* The input block is treated as a 128-bit little-endian integer */\n        d0   = BYTES_TO_U32_LE( input, offset + 0  );\n        d1   = BYTES_TO_U32_LE( input, offset + 4  );\n        d2   = BYTES_TO_U32_LE( input, offset + 8  );\n        d3   = BYTES_TO_U32_LE( input, offset + 12 );\n\n        /* Compute: acc += (padded) block as a 130-bit integer */\n        d0  += (uint64_t) acc0;\n        d1  += (uint64_t) acc1 + ( d0 >> 32U );\n        d2  += (uint64_t) acc2 + ( d1 >> 32U );\n        d3  += (uint64_t) acc3 + ( d2 >> 32U );\n        acc0 = (uint32_t) d0;\n        acc1 = (uint32_t) d1;\n        acc2 = (uint32_t) d2;\n        acc3 = (uint32_t) d3;\n        acc4 += (uint32_t) ( d3 >> 32U ) + needs_padding;\n\n        /* Compute: acc *= r */\n        d0 = mul64( acc0, r0  ) +\n             mul64( acc1, rs3 ) +\n             mul64( acc2, rs2 ) +\n             mul64( acc3, rs1 );\n        d1 = mul64( acc0, r1  ) +\n             mul64( acc1, r0  ) +\n             mul64( acc2, rs3 ) +\n             mul64( acc3, rs2 ) +\n             mul64( acc4, rs1 );\n        d2 = mul64( acc0, r2  ) +\n             mul64( acc1, r1  ) +\n             mul64( acc2, r0  ) +\n             mul64( acc3, rs3 ) +\n             mul64( acc4, rs2 );\n        d3 = mul64( acc0, r3  ) +\n             mul64( acc1, r2  ) +\n             mul64( acc2, r1  ) +\n             mul64( acc3, r0  ) +\n             mul64( acc4, rs3 );\n        acc4 *= r0;\n\n        /* Compute: acc %= (2^130 - 5) (partial remainder) */\n        d1 += ( d0 >> 32 );\n        d2 += ( d1 >> 32 );\n        d3 += ( d2 >> 32 );\n        acc0 = (uint32_t) d0;\n        acc1 = (uint32_t) d1;\n        acc2 = (uint32_t) d2;\n        acc3 = (uint32_t) d3;\n        acc4 = (uint32_t) ( d3 >> 32 ) + acc4;\n\n        d0 = (uint64_t) acc0 + ( acc4 >> 2 ) + ( acc4 & 0xFFFFFFFCU );\n        acc4 &= 3U;\n        acc0 = (uint32_t) d0;\n        d0 = (uint64_t) acc1 + ( d0 >> 32U );\n        acc1 = (uint32_t) d0;\n        d0 = (uint64_t) acc2 + ( d0 >> 32U );\n        acc2 = (uint32_t) d0;\n        d0 = (uint64_t) acc3 + ( d0 >> 32U );\n        acc3 = (uint32_t) d0;\n        d0 = (uint64_t) acc4 + ( d0 >> 32U );\n        acc4 = (uint32_t) d0;\n\n        offset    += POLY1305_BLOCK_SIZE_BYTES;\n    }\n\n    ctx->acc[0] = acc0;\n    ctx->acc[1] = acc1;\n    ctx->acc[2] = acc2;\n    ctx->acc[3] = acc3;\n    ctx->acc[4] = acc4;\n}\n\n/**\n * \\brief                   Compute the Poly1305 MAC\n *\n * \\param ctx               The Poly1305 context.\n * \\param mac               The buffer to where the MAC is written. Must be\n *                          big enough to contain the 16-byte MAC.\n */\nstatic void poly1305_compute_mac( const mbedtls_poly1305_context *ctx,\n                                  unsigned char mac[16] )\n{\n    uint64_t d;\n    uint32_t g0, g1, g2, g3, g4;\n    uint32_t acc0, acc1, acc2, acc3, acc4;\n    uint32_t mask;\n    uint32_t mask_inv;\n\n    acc0 = ctx->acc[0];\n    acc1 = ctx->acc[1];\n    acc2 = ctx->acc[2];\n    acc3 = ctx->acc[3];\n    acc4 = ctx->acc[4];\n\n    /* Before adding 's' we ensure that the accumulator is mod 2^130 - 5.\n     * We do this by calculating acc - (2^130 - 5), then checking if\n     * the 131st bit is set. If it is, then reduce: acc -= (2^130 - 5)\n     */\n\n    /* Calculate acc + -(2^130 - 5) */\n    d  = ( (uint64_t) acc0 + 5U );\n    g0 = (uint32_t) d;\n    d  = ( (uint64_t) acc1 + ( d >> 32 ) );\n    g1 = (uint32_t) d;\n    d  = ( (uint64_t) acc2 + ( d >> 32 ) );\n    g2 = (uint32_t) d;\n    d  = ( (uint64_t) acc3 + ( d >> 32 ) );\n    g3 = (uint32_t) d;\n    g4 = acc4 + (uint32_t) ( d >> 32U );\n\n    /* mask == 0xFFFFFFFF if 131st bit is set, otherwise mask == 0 */\n    mask = (uint32_t) 0U - ( g4 >> 2U );\n    mask_inv = ~mask;\n\n    /* If 131st bit is set then acc=g, otherwise, acc is unmodified */\n    acc0 = ( acc0 & mask_inv ) | ( g0 & mask );\n    acc1 = ( acc1 & mask_inv ) | ( g1 & mask );\n    acc2 = ( acc2 & mask_inv ) | ( g2 & mask );\n    acc3 = ( acc3 & mask_inv ) | ( g3 & mask );\n\n    /* Add 's' */\n    d = (uint64_t) acc0 + ctx->s[0];\n    acc0 = (uint32_t) d;\n    d = (uint64_t) acc1 + ctx->s[1] + ( d >> 32U );\n    acc1 = (uint32_t) d;\n    d = (uint64_t) acc2 + ctx->s[2] + ( d >> 32U );\n    acc2 = (uint32_t) d;\n    acc3 += ctx->s[3] + (uint32_t) ( d >> 32U );\n\n    /* Compute MAC (128 least significant bits of the accumulator) */\n    mac[ 0] = (unsigned char)( acc0       );\n    mac[ 1] = (unsigned char)( acc0 >>  8 );\n    mac[ 2] = (unsigned char)( acc0 >> 16 );\n    mac[ 3] = (unsigned char)( acc0 >> 24 );\n    mac[ 4] = (unsigned char)( acc1       );\n    mac[ 5] = (unsigned char)( acc1 >>  8 );\n    mac[ 6] = (unsigned char)( acc1 >> 16 );\n    mac[ 7] = (unsigned char)( acc1 >> 24 );\n    mac[ 8] = (unsigned char)( acc2       );\n    mac[ 9] = (unsigned char)( acc2 >>  8 );\n    mac[10] = (unsigned char)( acc2 >> 16 );\n    mac[11] = (unsigned char)( acc2 >> 24 );\n    mac[12] = (unsigned char)( acc3       );\n    mac[13] = (unsigned char)( acc3 >>  8 );\n    mac[14] = (unsigned char)( acc3 >> 16 );\n    mac[15] = (unsigned char)( acc3 >> 24 );\n}\n\nvoid mbedtls_poly1305_init( mbedtls_poly1305_context *ctx )\n{\n    if( ctx != NULL )\n    {\n        mbedtls_platform_zeroize( ctx, sizeof( mbedtls_poly1305_context ) );\n    }\n}\n\nvoid mbedtls_poly1305_free( mbedtls_poly1305_context *ctx )\n{\n    if( ctx != NULL )\n    {\n        mbedtls_platform_zeroize( ctx, sizeof( mbedtls_poly1305_context ) );\n    }\n}\n\nint mbedtls_poly1305_starts( mbedtls_poly1305_context *ctx,\n                             const unsigned char key[32] )\n{\n    if( ctx == NULL || key == NULL )\n    {\n        return( MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA );\n    }\n\n    /* r &= 0x0ffffffc0ffffffc0ffffffc0fffffff */\n    ctx->r[0] = BYTES_TO_U32_LE( key, 0 )  & 0x0FFFFFFFU;\n    ctx->r[1] = BYTES_TO_U32_LE( key, 4 )  & 0x0FFFFFFCU;\n    ctx->r[2] = BYTES_TO_U32_LE( key, 8 )  & 0x0FFFFFFCU;\n    ctx->r[3] = BYTES_TO_U32_LE( key, 12 ) & 0x0FFFFFFCU;\n\n    ctx->s[0] = BYTES_TO_U32_LE( key, 16 );\n    ctx->s[1] = BYTES_TO_U32_LE( key, 20 );\n    ctx->s[2] = BYTES_TO_U32_LE( key, 24 );\n    ctx->s[3] = BYTES_TO_U32_LE( key, 28 );\n\n    /* Initial accumulator state */\n    ctx->acc[0] = 0U;\n    ctx->acc[1] = 0U;\n    ctx->acc[2] = 0U;\n    ctx->acc[3] = 0U;\n    ctx->acc[4] = 0U;\n\n    /* Queue initially empty */\n    mbedtls_platform_zeroize( ctx->queue, sizeof( ctx->queue ) );\n    ctx->queue_len = 0U;\n\n    return( 0 );\n}\n\nint mbedtls_poly1305_update( mbedtls_poly1305_context *ctx,\n                             const unsigned char *input,\n                             size_t ilen )\n{\n    size_t offset    = 0U;\n    size_t remaining = ilen;\n    size_t queue_free_len;\n    size_t nblocks;\n\n    if( ctx == NULL )\n    {\n        return( MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA );\n    }\n    else if( ( ilen > 0U ) && ( input == NULL ) )\n    {\n        /* input pointer is allowed to be NULL only if ilen == 0 */\n        return( MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA );\n    }\n\n    if( ( remaining > 0U ) && ( ctx->queue_len > 0U ) )\n    {\n        queue_free_len = ( POLY1305_BLOCK_SIZE_BYTES - ctx->queue_len );\n\n        if( ilen < queue_free_len )\n        {\n            /* Not enough data to complete the block.\n             * Store this data with the other leftovers.\n             */\n            memcpy( &ctx->queue[ctx->queue_len],\n                    input,\n                    ilen );\n\n            ctx->queue_len += ilen;\n\n            remaining = 0U;\n        }\n        else\n        {\n            /* Enough data to produce a complete block */\n            memcpy( &ctx->queue[ctx->queue_len],\n                    input,\n                    queue_free_len );\n\n            ctx->queue_len = 0U;\n\n            poly1305_process( ctx, 1U, ctx->queue, 1U ); /* add padding bit */\n\n            offset    += queue_free_len;\n            remaining -= queue_free_len;\n        }\n    }\n\n    if( remaining >= POLY1305_BLOCK_SIZE_BYTES )\n    {\n        nblocks = remaining / POLY1305_BLOCK_SIZE_BYTES;\n\n        poly1305_process( ctx, nblocks, &input[offset], 1U );\n\n        offset += nblocks * POLY1305_BLOCK_SIZE_BYTES;\n        remaining %= POLY1305_BLOCK_SIZE_BYTES;\n    }\n\n    if( remaining > 0U )\n    {\n        /* Store partial block */\n        ctx->queue_len = remaining;\n        memcpy( ctx->queue, &input[offset], remaining );\n    }\n\n    return( 0 );\n}\n\nint mbedtls_poly1305_finish( mbedtls_poly1305_context *ctx,\n                             unsigned char mac[16] )\n{\n    if( ( ctx == NULL ) || ( mac == NULL ) )\n    {\n        return( MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA );\n    }\n\n    /* Process any leftover data */\n    if( ctx->queue_len > 0U )\n    {\n        /* Add padding bit */\n        ctx->queue[ctx->queue_len] = 1U;\n        ctx->queue_len++;\n\n        /* Pad with zeroes */\n        memset( &ctx->queue[ctx->queue_len],\n                0,\n                POLY1305_BLOCK_SIZE_BYTES - ctx->queue_len );\n\n        poly1305_process( ctx, 1U,          /* Process 1 block */\n                          ctx->queue, 0U ); /* Already padded above */\n    }\n\n    poly1305_compute_mac( ctx, mac );\n\n    return( 0 );\n}\n\nint mbedtls_poly1305_mac( const unsigned char key[32],\n                          const unsigned char *input,\n                          size_t ilen,\n                          unsigned char mac[16] )\n{\n    mbedtls_poly1305_context ctx;\n    int ret;\n\n    mbedtls_poly1305_init( &ctx );\n\n    ret = mbedtls_poly1305_starts( &ctx, key );\n    if( ret != 0 )\n        goto cleanup;\n\n    ret = mbedtls_poly1305_update( &ctx, input, ilen );\n    if( ret != 0 )\n        goto cleanup;\n\n    ret = mbedtls_poly1305_finish( &ctx, mac );\n\ncleanup:\n    mbedtls_poly1305_free( &ctx );\n    return( ret );\n}\n\n#endif /* MBEDTLS_POLY1305_ALT */\n\n#if defined(MBEDTLS_SELF_TEST)\n\nstatic const unsigned char test_keys[2][32] =\n{\n    {\n        0x85, 0xd6, 0xbe, 0x78, 0x57, 0x55, 0x6d, 0x33,\n        0x7f, 0x44, 0x52, 0xfe, 0x42, 0xd5, 0x06, 0xa8,\n        0x01, 0x03, 0x80, 0x8a, 0xfb, 0x0d, 0xb2, 0xfd,\n        0x4a, 0xbf, 0xf6, 0xaf, 0x41, 0x49, 0xf5, 0x1b\n    },\n    {\n        0x1c, 0x92, 0x40, 0xa5, 0xeb, 0x55, 0xd3, 0x8a,\n        0xf3, 0x33, 0x88, 0x86, 0x04, 0xf6, 0xb5, 0xf0,\n        0x47, 0x39, 0x17, 0xc1, 0x40, 0x2b, 0x80, 0x09,\n        0x9d, 0xca, 0x5c, 0xbc, 0x20, 0x70, 0x75, 0xc0\n    }\n};\n\nstatic const unsigned char test_data[2][127] =\n{\n    {\n        0x43, 0x72, 0x79, 0x70, 0x74, 0x6f, 0x67, 0x72,\n        0x61, 0x70, 0x68, 0x69, 0x63, 0x20, 0x46, 0x6f,\n        0x72, 0x75, 0x6d, 0x20, 0x52, 0x65, 0x73, 0x65,\n        0x61, 0x72, 0x63, 0x68, 0x20, 0x47, 0x72, 0x6f,\n        0x75, 0x70\n    },\n    {\n        0x27, 0x54, 0x77, 0x61, 0x73, 0x20, 0x62, 0x72,\n        0x69, 0x6c, 0x6c, 0x69, 0x67, 0x2c, 0x20, 0x61,\n        0x6e, 0x64, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73,\n        0x6c, 0x69, 0x74, 0x68, 0x79, 0x20, 0x74, 0x6f,\n        0x76, 0x65, 0x73, 0x0a, 0x44, 0x69, 0x64, 0x20,\n        0x67, 0x79, 0x72, 0x65, 0x20, 0x61, 0x6e, 0x64,\n        0x20, 0x67, 0x69, 0x6d, 0x62, 0x6c, 0x65, 0x20,\n        0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x77,\n        0x61, 0x62, 0x65, 0x3a, 0x0a, 0x41, 0x6c, 0x6c,\n        0x20, 0x6d, 0x69, 0x6d, 0x73, 0x79, 0x20, 0x77,\n        0x65, 0x72, 0x65, 0x20, 0x74, 0x68, 0x65, 0x20,\n        0x62, 0x6f, 0x72, 0x6f, 0x67, 0x6f, 0x76, 0x65,\n        0x73, 0x2c, 0x0a, 0x41, 0x6e, 0x64, 0x20, 0x74,\n        0x68, 0x65, 0x20, 0x6d, 0x6f, 0x6d, 0x65, 0x20,\n        0x72, 0x61, 0x74, 0x68, 0x73, 0x20, 0x6f, 0x75,\n        0x74, 0x67, 0x72, 0x61, 0x62, 0x65, 0x2e\n    }\n};\n\nstatic const size_t test_data_len[2] =\n{\n    34U,\n    127U\n};\n\nstatic const unsigned char test_mac[2][16] =\n{\n    {\n        0xa8, 0x06, 0x1d, 0xc1, 0x30, 0x51, 0x36, 0xc6,\n        0xc2, 0x2b, 0x8b, 0xaf, 0x0c, 0x01, 0x27, 0xa9\n    },\n    {\n        0x45, 0x41, 0x66, 0x9a, 0x7e, 0xaa, 0xee, 0x61,\n        0xe7, 0x08, 0xdc, 0x7c, 0xbc, 0xc5, 0xeb, 0x62\n    }\n};\n\n#define ASSERT( cond, args )            \\\n    do                                  \\\n    {                                   \\\n        if( ! ( cond ) )                \\\n        {                               \\\n            if( verbose != 0 )          \\\n                mbedtls_printf args;    \\\n                                        \\\n            return( -1 );               \\\n        }                               \\\n    }                                   \\\n    while( 0 )\n\nint mbedtls_poly1305_self_test( int verbose )\n{\n    unsigned char mac[16];\n    unsigned i;\n    int ret;\n\n    for( i = 0U; i < 2U; i++ )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"  Poly1305 test %u \", i );\n\n        ret = mbedtls_poly1305_mac( test_keys[i],\n                                    test_data[i],\n                                    test_data_len[i],\n                                    mac );\n        ASSERT( 0 == ret, ( \"error code: %i\\n\", ret ) );\n\n        ASSERT( 0 == memcmp( mac, test_mac[i], 16U ), ( \"failed (mac)\\n\" ) );\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    return( 0 );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_POLY1305_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/ripemd160.c",
    "content": "/*\n *  RIPE MD-160 implementation\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n/*\n *  The RIPEMD-160 algorithm was designed by RIPE in 1996\n *  http://homes.esat.kuleuven.be/~bosselae/mbedtls_ripemd160.html\n *  http://ehash.iaik.tugraz.at/wiki/RIPEMD-160\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_RIPEMD160_C)\n\n#include \"mbedtls/ripemd160.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if !defined(MBEDTLS_RIPEMD160_ALT)\n\n/*\n * 32-bit integer manipulation macros (little endian)\n */\n#ifndef GET_UINT32_LE\n#define GET_UINT32_LE(n,b,i)                            \\\n{                                                       \\\n    (n) = ( (uint32_t) (b)[(i)    ]       )             \\\n        | ( (uint32_t) (b)[(i) + 1] <<  8 )             \\\n        | ( (uint32_t) (b)[(i) + 2] << 16 )             \\\n        | ( (uint32_t) (b)[(i) + 3] << 24 );            \\\n}\n#endif\n\n#ifndef PUT_UINT32_LE\n#define PUT_UINT32_LE(n,b,i)                                    \\\n{                                                               \\\n    (b)[(i)    ] = (unsigned char) ( ( (n)       ) & 0xFF );    \\\n    (b)[(i) + 1] = (unsigned char) ( ( (n) >>  8 ) & 0xFF );    \\\n    (b)[(i) + 2] = (unsigned char) ( ( (n) >> 16 ) & 0xFF );    \\\n    (b)[(i) + 3] = (unsigned char) ( ( (n) >> 24 ) & 0xFF );    \\\n}\n#endif\n\nvoid mbedtls_ripemd160_init( mbedtls_ripemd160_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_ripemd160_context ) );\n}\n\nvoid mbedtls_ripemd160_free( mbedtls_ripemd160_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ripemd160_context ) );\n}\n\nvoid mbedtls_ripemd160_clone( mbedtls_ripemd160_context *dst,\n                        const mbedtls_ripemd160_context *src )\n{\n    *dst = *src;\n}\n\n/*\n * RIPEMD-160 context setup\n */\nint mbedtls_ripemd160_starts_ret( mbedtls_ripemd160_context *ctx )\n{\n    ctx->total[0] = 0;\n    ctx->total[1] = 0;\n\n    ctx->state[0] = 0x67452301;\n    ctx->state[1] = 0xEFCDAB89;\n    ctx->state[2] = 0x98BADCFE;\n    ctx->state[3] = 0x10325476;\n    ctx->state[4] = 0xC3D2E1F0;\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_ripemd160_starts( mbedtls_ripemd160_context *ctx )\n{\n    mbedtls_ripemd160_starts_ret( ctx );\n}\n#endif\n\n#if !defined(MBEDTLS_RIPEMD160_PROCESS_ALT)\n/*\n * Process one block\n */\nint mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx,\n                                        const unsigned char data[64] )\n{\n    uint32_t A, B, C, D, E, Ap, Bp, Cp, Dp, Ep, X[16];\n\n    GET_UINT32_LE( X[ 0], data,  0 );\n    GET_UINT32_LE( X[ 1], data,  4 );\n    GET_UINT32_LE( X[ 2], data,  8 );\n    GET_UINT32_LE( X[ 3], data, 12 );\n    GET_UINT32_LE( X[ 4], data, 16 );\n    GET_UINT32_LE( X[ 5], data, 20 );\n    GET_UINT32_LE( X[ 6], data, 24 );\n    GET_UINT32_LE( X[ 7], data, 28 );\n    GET_UINT32_LE( X[ 8], data, 32 );\n    GET_UINT32_LE( X[ 9], data, 36 );\n    GET_UINT32_LE( X[10], data, 40 );\n    GET_UINT32_LE( X[11], data, 44 );\n    GET_UINT32_LE( X[12], data, 48 );\n    GET_UINT32_LE( X[13], data, 52 );\n    GET_UINT32_LE( X[14], data, 56 );\n    GET_UINT32_LE( X[15], data, 60 );\n\n    A = Ap = ctx->state[0];\n    B = Bp = ctx->state[1];\n    C = Cp = ctx->state[2];\n    D = Dp = ctx->state[3];\n    E = Ep = ctx->state[4];\n\n#define F1( x, y, z )   ( x ^ y ^ z )\n#define F2( x, y, z )   ( ( x & y ) | ( ~x & z ) )\n#define F3( x, y, z )   ( ( x | ~y ) ^ z )\n#define F4( x, y, z )   ( ( x & z ) | ( y & ~z ) )\n#define F5( x, y, z )   ( x ^ ( y | ~z ) )\n\n#define S( x, n ) ( ( x << n ) | ( x >> (32 - n) ) )\n\n#define P( a, b, c, d, e, r, s, f, k )      \\\n    a += f( b, c, d ) + X[r] + k;           \\\n    a = S( a, s ) + e;                      \\\n    c = S( c, 10 );\n\n#define P2( a, b, c, d, e, r, s, rp, sp )   \\\n    P( a, b, c, d, e, r, s, F, K );         \\\n    P( a ## p, b ## p, c ## p, d ## p, e ## p, rp, sp, Fp, Kp );\n\n#define F   F1\n#define K   0x00000000\n#define Fp  F5\n#define Kp  0x50A28BE6\n    P2( A, B, C, D, E,  0, 11,  5,  8 );\n    P2( E, A, B, C, D,  1, 14, 14,  9 );\n    P2( D, E, A, B, C,  2, 15,  7,  9 );\n    P2( C, D, E, A, B,  3, 12,  0, 11 );\n    P2( B, C, D, E, A,  4,  5,  9, 13 );\n    P2( A, B, C, D, E,  5,  8,  2, 15 );\n    P2( E, A, B, C, D,  6,  7, 11, 15 );\n    P2( D, E, A, B, C,  7,  9,  4,  5 );\n    P2( C, D, E, A, B,  8, 11, 13,  7 );\n    P2( B, C, D, E, A,  9, 13,  6,  7 );\n    P2( A, B, C, D, E, 10, 14, 15,  8 );\n    P2( E, A, B, C, D, 11, 15,  8, 11 );\n    P2( D, E, A, B, C, 12,  6,  1, 14 );\n    P2( C, D, E, A, B, 13,  7, 10, 14 );\n    P2( B, C, D, E, A, 14,  9,  3, 12 );\n    P2( A, B, C, D, E, 15,  8, 12,  6 );\n#undef F\n#undef K\n#undef Fp\n#undef Kp\n\n#define F   F2\n#define K   0x5A827999\n#define Fp  F4\n#define Kp  0x5C4DD124\n    P2( E, A, B, C, D,  7,  7,  6,  9 );\n    P2( D, E, A, B, C,  4,  6, 11, 13 );\n    P2( C, D, E, A, B, 13,  8,  3, 15 );\n    P2( B, C, D, E, A,  1, 13,  7,  7 );\n    P2( A, B, C, D, E, 10, 11,  0, 12 );\n    P2( E, A, B, C, D,  6,  9, 13,  8 );\n    P2( D, E, A, B, C, 15,  7,  5,  9 );\n    P2( C, D, E, A, B,  3, 15, 10, 11 );\n    P2( B, C, D, E, A, 12,  7, 14,  7 );\n    P2( A, B, C, D, E,  0, 12, 15,  7 );\n    P2( E, A, B, C, D,  9, 15,  8, 12 );\n    P2( D, E, A, B, C,  5,  9, 12,  7 );\n    P2( C, D, E, A, B,  2, 11,  4,  6 );\n    P2( B, C, D, E, A, 14,  7,  9, 15 );\n    P2( A, B, C, D, E, 11, 13,  1, 13 );\n    P2( E, A, B, C, D,  8, 12,  2, 11 );\n#undef F\n#undef K\n#undef Fp\n#undef Kp\n\n#define F   F3\n#define K   0x6ED9EBA1\n#define Fp  F3\n#define Kp  0x6D703EF3\n    P2( D, E, A, B, C,  3, 11, 15,  9 );\n    P2( C, D, E, A, B, 10, 13,  5,  7 );\n    P2( B, C, D, E, A, 14,  6,  1, 15 );\n    P2( A, B, C, D, E,  4,  7,  3, 11 );\n    P2( E, A, B, C, D,  9, 14,  7,  8 );\n    P2( D, E, A, B, C, 15,  9, 14,  6 );\n    P2( C, D, E, A, B,  8, 13,  6,  6 );\n    P2( B, C, D, E, A,  1, 15,  9, 14 );\n    P2( A, B, C, D, E,  2, 14, 11, 12 );\n    P2( E, A, B, C, D,  7,  8,  8, 13 );\n    P2( D, E, A, B, C,  0, 13, 12,  5 );\n    P2( C, D, E, A, B,  6,  6,  2, 14 );\n    P2( B, C, D, E, A, 13,  5, 10, 13 );\n    P2( A, B, C, D, E, 11, 12,  0, 13 );\n    P2( E, A, B, C, D,  5,  7,  4,  7 );\n    P2( D, E, A, B, C, 12,  5, 13,  5 );\n#undef F\n#undef K\n#undef Fp\n#undef Kp\n\n#define F   F4\n#define K   0x8F1BBCDC\n#define Fp  F2\n#define Kp  0x7A6D76E9\n    P2( C, D, E, A, B,  1, 11,  8, 15 );\n    P2( B, C, D, E, A,  9, 12,  6,  5 );\n    P2( A, B, C, D, E, 11, 14,  4,  8 );\n    P2( E, A, B, C, D, 10, 15,  1, 11 );\n    P2( D, E, A, B, C,  0, 14,  3, 14 );\n    P2( C, D, E, A, B,  8, 15, 11, 14 );\n    P2( B, C, D, E, A, 12,  9, 15,  6 );\n    P2( A, B, C, D, E,  4,  8,  0, 14 );\n    P2( E, A, B, C, D, 13,  9,  5,  6 );\n    P2( D, E, A, B, C,  3, 14, 12,  9 );\n    P2( C, D, E, A, B,  7,  5,  2, 12 );\n    P2( B, C, D, E, A, 15,  6, 13,  9 );\n    P2( A, B, C, D, E, 14,  8,  9, 12 );\n    P2( E, A, B, C, D,  5,  6,  7,  5 );\n    P2( D, E, A, B, C,  6,  5, 10, 15 );\n    P2( C, D, E, A, B,  2, 12, 14,  8 );\n#undef F\n#undef K\n#undef Fp\n#undef Kp\n\n#define F   F5\n#define K   0xA953FD4E\n#define Fp  F1\n#define Kp  0x00000000\n    P2( B, C, D, E, A,  4,  9, 12,  8 );\n    P2( A, B, C, D, E,  0, 15, 15,  5 );\n    P2( E, A, B, C, D,  5,  5, 10, 12 );\n    P2( D, E, A, B, C,  9, 11,  4,  9 );\n    P2( C, D, E, A, B,  7,  6,  1, 12 );\n    P2( B, C, D, E, A, 12,  8,  5,  5 );\n    P2( A, B, C, D, E,  2, 13,  8, 14 );\n    P2( E, A, B, C, D, 10, 12,  7,  6 );\n    P2( D, E, A, B, C, 14,  5,  6,  8 );\n    P2( C, D, E, A, B,  1, 12,  2, 13 );\n    P2( B, C, D, E, A,  3, 13, 13,  6 );\n    P2( A, B, C, D, E,  8, 14, 14,  5 );\n    P2( E, A, B, C, D, 11, 11,  0, 15 );\n    P2( D, E, A, B, C,  6,  8,  3, 13 );\n    P2( C, D, E, A, B, 15,  5,  9, 11 );\n    P2( B, C, D, E, A, 13,  6, 11, 11 );\n#undef F\n#undef K\n#undef Fp\n#undef Kp\n\n    C             = ctx->state[1] + C + Dp;\n    ctx->state[1] = ctx->state[2] + D + Ep;\n    ctx->state[2] = ctx->state[3] + E + Ap;\n    ctx->state[3] = ctx->state[4] + A + Bp;\n    ctx->state[4] = ctx->state[0] + B + Cp;\n    ctx->state[0] = C;\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_ripemd160_process( mbedtls_ripemd160_context *ctx,\n                                const unsigned char data[64] )\n{\n    mbedtls_internal_ripemd160_process( ctx, data );\n}\n#endif\n#endif /* !MBEDTLS_RIPEMD160_PROCESS_ALT */\n\n/*\n * RIPEMD-160 process buffer\n */\nint mbedtls_ripemd160_update_ret( mbedtls_ripemd160_context *ctx,\n                                  const unsigned char *input,\n                                  size_t ilen )\n{\n    int ret;\n    size_t fill;\n    uint32_t left;\n\n    if( ilen == 0 )\n        return( 0 );\n\n    left = ctx->total[0] & 0x3F;\n    fill = 64 - left;\n\n    ctx->total[0] += (uint32_t) ilen;\n    ctx->total[0] &= 0xFFFFFFFF;\n\n    if( ctx->total[0] < (uint32_t) ilen )\n        ctx->total[1]++;\n\n    if( left && ilen >= fill )\n    {\n        memcpy( (void *) (ctx->buffer + left), input, fill );\n\n        if( ( ret = mbedtls_internal_ripemd160_process( ctx, ctx->buffer ) ) != 0 )\n            return( ret );\n\n        input += fill;\n        ilen  -= fill;\n        left = 0;\n    }\n\n    while( ilen >= 64 )\n    {\n        if( ( ret = mbedtls_internal_ripemd160_process( ctx, input ) ) != 0 )\n            return( ret );\n\n        input += 64;\n        ilen  -= 64;\n    }\n\n    if( ilen > 0 )\n    {\n        memcpy( (void *) (ctx->buffer + left), input, ilen );\n    }\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_ripemd160_update( mbedtls_ripemd160_context *ctx,\n                               const unsigned char *input,\n                               size_t ilen )\n{\n    mbedtls_ripemd160_update_ret( ctx, input, ilen );\n}\n#endif\n\nstatic const unsigned char ripemd160_padding[64] =\n{\n 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n};\n\n/*\n * RIPEMD-160 final digest\n */\nint mbedtls_ripemd160_finish_ret( mbedtls_ripemd160_context *ctx,\n                                  unsigned char output[20] )\n{\n    int ret;\n    uint32_t last, padn;\n    uint32_t high, low;\n    unsigned char msglen[8];\n\n    high = ( ctx->total[0] >> 29 )\n         | ( ctx->total[1] <<  3 );\n    low  = ( ctx->total[0] <<  3 );\n\n    PUT_UINT32_LE( low,  msglen, 0 );\n    PUT_UINT32_LE( high, msglen, 4 );\n\n    last = ctx->total[0] & 0x3F;\n    padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );\n\n    ret = mbedtls_ripemd160_update_ret( ctx, ripemd160_padding, padn );\n    if( ret != 0 )\n        return( ret );\n\n    ret = mbedtls_ripemd160_update_ret( ctx, msglen, 8 );\n    if( ret != 0 )\n        return( ret );\n\n    PUT_UINT32_LE( ctx->state[0], output,  0 );\n    PUT_UINT32_LE( ctx->state[1], output,  4 );\n    PUT_UINT32_LE( ctx->state[2], output,  8 );\n    PUT_UINT32_LE( ctx->state[3], output, 12 );\n    PUT_UINT32_LE( ctx->state[4], output, 16 );\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_ripemd160_finish( mbedtls_ripemd160_context *ctx,\n                               unsigned char output[20] )\n{\n    mbedtls_ripemd160_finish_ret( ctx, output );\n}\n#endif\n\n#endif /* ! MBEDTLS_RIPEMD160_ALT */\n\n/*\n * output = RIPEMD-160( input buffer )\n */\nint mbedtls_ripemd160_ret( const unsigned char *input,\n                           size_t ilen,\n                           unsigned char output[20] )\n{\n    int ret;\n    mbedtls_ripemd160_context ctx;\n\n    mbedtls_ripemd160_init( &ctx );\n\n    if( ( ret = mbedtls_ripemd160_starts_ret( &ctx ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_ripemd160_update_ret( &ctx, input, ilen ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_ripemd160_finish_ret( &ctx, output ) ) != 0 )\n        goto exit;\n\nexit:\n    mbedtls_ripemd160_free( &ctx );\n\n    return( ret );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_ripemd160( const unsigned char *input,\n                        size_t ilen,\n                        unsigned char output[20] )\n{\n    mbedtls_ripemd160_ret( input, ilen, output );\n}\n#endif\n\n#if defined(MBEDTLS_SELF_TEST)\n/*\n * Test vectors from the RIPEMD-160 paper and\n * http://homes.esat.kuleuven.be/~bosselae/mbedtls_ripemd160.html#HMAC\n */\n#define TESTS   8\nstatic const unsigned char ripemd160_test_str[TESTS][81] =\n{\n    { \"\" },\n    { \"a\" },\n    { \"abc\" },\n    { \"message digest\" },\n    { \"abcdefghijklmnopqrstuvwxyz\" },\n    { \"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq\" },\n    { \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\" },\n    { \"12345678901234567890123456789012345678901234567890123456789012\"\n      \"345678901234567890\" },\n};\n\nstatic const size_t ripemd160_test_strlen[TESTS] =\n{\n    0, 1, 3, 14, 26, 56, 62, 80\n};\n\nstatic const unsigned char ripemd160_test_md[TESTS][20] =\n{\n    { 0x9c, 0x11, 0x85, 0xa5, 0xc5, 0xe9, 0xfc, 0x54, 0x61, 0x28,\n      0x08, 0x97, 0x7e, 0xe8, 0xf5, 0x48, 0xb2, 0x25, 0x8d, 0x31 },\n    { 0x0b, 0xdc, 0x9d, 0x2d, 0x25, 0x6b, 0x3e, 0xe9, 0xda, 0xae,\n      0x34, 0x7b, 0xe6, 0xf4, 0xdc, 0x83, 0x5a, 0x46, 0x7f, 0xfe },\n    { 0x8e, 0xb2, 0x08, 0xf7, 0xe0, 0x5d, 0x98, 0x7a, 0x9b, 0x04,\n      0x4a, 0x8e, 0x98, 0xc6, 0xb0, 0x87, 0xf1, 0x5a, 0x0b, 0xfc },\n    { 0x5d, 0x06, 0x89, 0xef, 0x49, 0xd2, 0xfa, 0xe5, 0x72, 0xb8,\n      0x81, 0xb1, 0x23, 0xa8, 0x5f, 0xfa, 0x21, 0x59, 0x5f, 0x36 },\n    { 0xf7, 0x1c, 0x27, 0x10, 0x9c, 0x69, 0x2c, 0x1b, 0x56, 0xbb,\n      0xdc, 0xeb, 0x5b, 0x9d, 0x28, 0x65, 0xb3, 0x70, 0x8d, 0xbc },\n    { 0x12, 0xa0, 0x53, 0x38, 0x4a, 0x9c, 0x0c, 0x88, 0xe4, 0x05,\n      0xa0, 0x6c, 0x27, 0xdc, 0xf4, 0x9a, 0xda, 0x62, 0xeb, 0x2b },\n    { 0xb0, 0xe2, 0x0b, 0x6e, 0x31, 0x16, 0x64, 0x02, 0x86, 0xed,\n      0x3a, 0x87, 0xa5, 0x71, 0x30, 0x79, 0xb2, 0x1f, 0x51, 0x89 },\n    { 0x9b, 0x75, 0x2e, 0x45, 0x57, 0x3d, 0x4b, 0x39, 0xf4, 0xdb,\n      0xd3, 0x32, 0x3c, 0xab, 0x82, 0xbf, 0x63, 0x32, 0x6b, 0xfb },\n};\n\n/*\n * Checkup routine\n */\nint mbedtls_ripemd160_self_test( int verbose )\n{\n    int i, ret = 0;\n    unsigned char output[20];\n\n    memset( output, 0, sizeof output );\n\n    for( i = 0; i < TESTS; i++ )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"  RIPEMD-160 test #%d: \", i + 1 );\n\n        ret = mbedtls_ripemd160_ret( ripemd160_test_str[i],\n                                     ripemd160_test_strlen[i], output );\n        if( ret != 0 )\n            goto fail;\n\n        if( memcmp( output, ripemd160_test_md[i], 20 ) != 0 )\n        {\n            ret = 1;\n            goto fail;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    return( 0 );\n\nfail:\n    if( verbose != 0 )\n        mbedtls_printf( \"failed\\n\" );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_RIPEMD160_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/rsa.c",
    "content": "/*\n *  The RSA public-key cryptosystem\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n/*\n *  The following sources were referenced in the design of this implementation\n *  of the RSA algorithm:\n *\n *  [1] A method for obtaining digital signatures and public-key cryptosystems\n *      R Rivest, A Shamir, and L Adleman\n *      http://people.csail.mit.edu/rivest/pubs.html#RSA78\n *\n *  [2] Handbook of Applied Cryptography - 1997, Chapter 8\n *      Menezes, van Oorschot and Vanstone\n *\n *  [3] Malware Guard Extension: Using SGX to Conceal Cache Attacks\n *      Michael Schwarz, Samuel Weiser, Daniel Gruss, Clémentine Maurice and\n *      Stefan Mangard\n *      https://arxiv.org/abs/1702.08719v2\n *\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_RSA_C)\n\n#include \"mbedtls/rsa.h\"\n#include \"mbedtls/rsa_internal.h\"\n#include \"mbedtls/oid.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_PKCS1_V21)\n#include \"mbedtls/md.h\"\n#endif\n\n#if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__)\n#include <stdlib.h>\n#endif\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#define mbedtls_calloc calloc\n#define mbedtls_free   free\n#endif\n\n#if !defined(MBEDTLS_RSA_ALT)\n\n#if defined(MBEDTLS_PKCS1_V15)\n/* constant-time buffer comparison */\nstatic inline int mbedtls_safer_memcmp( const void *a, const void *b, size_t n )\n{\n    size_t i;\n    const unsigned char *A = (const unsigned char *) a;\n    const unsigned char *B = (const unsigned char *) b;\n    unsigned char diff = 0;\n\n    for( i = 0; i < n; i++ )\n        diff |= A[i] ^ B[i];\n\n    return( diff );\n}\n#endif /* MBEDTLS_PKCS1_V15 */\n\nint mbedtls_rsa_import( mbedtls_rsa_context *ctx,\n                        const mbedtls_mpi *N,\n                        const mbedtls_mpi *P, const mbedtls_mpi *Q,\n                        const mbedtls_mpi *D, const mbedtls_mpi *E )\n{\n    int ret;\n\n    if( ( N != NULL && ( ret = mbedtls_mpi_copy( &ctx->N, N ) ) != 0 ) ||\n        ( P != NULL && ( ret = mbedtls_mpi_copy( &ctx->P, P ) ) != 0 ) ||\n        ( Q != NULL && ( ret = mbedtls_mpi_copy( &ctx->Q, Q ) ) != 0 ) ||\n        ( D != NULL && ( ret = mbedtls_mpi_copy( &ctx->D, D ) ) != 0 ) ||\n        ( E != NULL && ( ret = mbedtls_mpi_copy( &ctx->E, E ) ) != 0 ) )\n    {\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );\n    }\n\n    if( N != NULL )\n        ctx->len = mbedtls_mpi_size( &ctx->N );\n\n    return( 0 );\n}\n\nint mbedtls_rsa_import_raw( mbedtls_rsa_context *ctx,\n                            unsigned char const *N, size_t N_len,\n                            unsigned char const *P, size_t P_len,\n                            unsigned char const *Q, size_t Q_len,\n                            unsigned char const *D, size_t D_len,\n                            unsigned char const *E, size_t E_len )\n{\n    int ret = 0;\n\n    if( N != NULL )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->N, N, N_len ) );\n        ctx->len = mbedtls_mpi_size( &ctx->N );\n    }\n\n    if( P != NULL )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->P, P, P_len ) );\n\n    if( Q != NULL )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->Q, Q, Q_len ) );\n\n    if( D != NULL )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->D, D, D_len ) );\n\n    if( E != NULL )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->E, E, E_len ) );\n\ncleanup:\n\n    if( ret != 0 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );\n\n    return( 0 );\n}\n\n/*\n * Checks whether the context fields are set in such a way\n * that the RSA primitives will be able to execute without error.\n * It does *not* make guarantees for consistency of the parameters.\n */\nstatic int rsa_check_context( mbedtls_rsa_context const *ctx, int is_priv,\n                              int blinding_needed )\n{\n#if !defined(MBEDTLS_RSA_NO_CRT)\n    /* blinding_needed is only used for NO_CRT to decide whether\n     * P,Q need to be present or not. */\n    ((void) blinding_needed);\n#endif\n\n    if( ctx->len != mbedtls_mpi_size( &ctx->N ) ||\n        ctx->len > MBEDTLS_MPI_MAX_SIZE )\n    {\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n    }\n\n    /*\n     * 1. Modular exponentiation needs positive, odd moduli.\n     */\n\n    /* Modular exponentiation wrt. N is always used for\n     * RSA public key operations. */\n    if( mbedtls_mpi_cmp_int( &ctx->N, 0 ) <= 0 ||\n        mbedtls_mpi_get_bit( &ctx->N, 0 ) == 0  )\n    {\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n    }\n\n#if !defined(MBEDTLS_RSA_NO_CRT)\n    /* Modular exponentiation for P and Q is only\n     * used for private key operations and if CRT\n     * is used. */\n    if( is_priv &&\n        ( mbedtls_mpi_cmp_int( &ctx->P, 0 ) <= 0 ||\n          mbedtls_mpi_get_bit( &ctx->P, 0 ) == 0 ||\n          mbedtls_mpi_cmp_int( &ctx->Q, 0 ) <= 0 ||\n          mbedtls_mpi_get_bit( &ctx->Q, 0 ) == 0  ) )\n    {\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n    }\n#endif /* !MBEDTLS_RSA_NO_CRT */\n\n    /*\n     * 2. Exponents must be positive\n     */\n\n    /* Always need E for public key operations */\n    if( mbedtls_mpi_cmp_int( &ctx->E, 0 ) <= 0 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n#if defined(MBEDTLS_RSA_NO_CRT)\n    /* For private key operations, use D or DP & DQ\n     * as (unblinded) exponents. */\n    if( is_priv && mbedtls_mpi_cmp_int( &ctx->D, 0 ) <= 0 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n#else\n    if( is_priv &&\n        ( mbedtls_mpi_cmp_int( &ctx->DP, 0 ) <= 0 ||\n          mbedtls_mpi_cmp_int( &ctx->DQ, 0 ) <= 0  ) )\n    {\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n    }\n#endif /* MBEDTLS_RSA_NO_CRT */\n\n    /* Blinding shouldn't make exponents negative either,\n     * so check that P, Q >= 1 if that hasn't yet been\n     * done as part of 1. */\n#if defined(MBEDTLS_RSA_NO_CRT)\n    if( is_priv && blinding_needed &&\n        ( mbedtls_mpi_cmp_int( &ctx->P, 0 ) <= 0 ||\n          mbedtls_mpi_cmp_int( &ctx->Q, 0 ) <= 0 ) )\n    {\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n    }\n#endif\n\n    /* It wouldn't lead to an error if it wasn't satisfied,\n     * but check for QP >= 1 nonetheless. */\n#if !defined(MBEDTLS_RSA_NO_CRT)\n    if( is_priv &&\n        mbedtls_mpi_cmp_int( &ctx->QP, 0 ) <= 0 )\n    {\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n    }\n#endif\n\n    return( 0 );\n}\n\nint mbedtls_rsa_complete( mbedtls_rsa_context *ctx )\n{\n    int ret = 0;\n\n    const int have_N = ( mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 );\n    const int have_P = ( mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 );\n    const int have_Q = ( mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 );\n    const int have_D = ( mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 );\n    const int have_E = ( mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0 );\n\n    /*\n     * Check whether provided parameters are enough\n     * to deduce all others. The following incomplete\n     * parameter sets for private keys are supported:\n     *\n     * (1) P, Q missing.\n     * (2) D and potentially N missing.\n     *\n     */\n\n    const int n_missing  =              have_P &&  have_Q &&  have_D && have_E;\n    const int pq_missing =   have_N && !have_P && !have_Q &&  have_D && have_E;\n    const int d_missing  =              have_P &&  have_Q && !have_D && have_E;\n    const int is_pub     =   have_N && !have_P && !have_Q && !have_D && have_E;\n\n    /* These three alternatives are mutually exclusive */\n    const int is_priv = n_missing || pq_missing || d_missing;\n\n    if( !is_priv && !is_pub )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    /*\n     * Step 1: Deduce N if P, Q are provided.\n     */\n\n    if( !have_N && have_P && have_Q )\n    {\n        if( ( ret = mbedtls_mpi_mul_mpi( &ctx->N, &ctx->P,\n                                         &ctx->Q ) ) != 0 )\n        {\n            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );\n        }\n\n        ctx->len = mbedtls_mpi_size( &ctx->N );\n    }\n\n    /*\n     * Step 2: Deduce and verify all remaining core parameters.\n     */\n\n    if( pq_missing )\n    {\n        ret = mbedtls_rsa_deduce_primes( &ctx->N, &ctx->E, &ctx->D,\n                                         &ctx->P, &ctx->Q );\n        if( ret != 0 )\n            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );\n\n    }\n    else if( d_missing )\n    {\n        if( ( ret = mbedtls_rsa_deduce_private_exponent( &ctx->P,\n                                                         &ctx->Q,\n                                                         &ctx->E,\n                                                         &ctx->D ) ) != 0 )\n        {\n            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );\n        }\n    }\n\n    /*\n     * Step 3: Deduce all additional parameters specific\n     *         to our current RSA implementation.\n     */\n\n#if !defined(MBEDTLS_RSA_NO_CRT)\n    if( is_priv )\n    {\n        ret = mbedtls_rsa_deduce_crt( &ctx->P,  &ctx->Q,  &ctx->D,\n                                      &ctx->DP, &ctx->DQ, &ctx->QP );\n        if( ret != 0 )\n            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );\n    }\n#endif /* MBEDTLS_RSA_NO_CRT */\n\n    /*\n     * Step 3: Basic sanity checks\n     */\n\n    return( rsa_check_context( ctx, is_priv, 1 ) );\n}\n\nint mbedtls_rsa_export_raw( const mbedtls_rsa_context *ctx,\n                            unsigned char *N, size_t N_len,\n                            unsigned char *P, size_t P_len,\n                            unsigned char *Q, size_t Q_len,\n                            unsigned char *D, size_t D_len,\n                            unsigned char *E, size_t E_len )\n{\n    int ret = 0;\n\n    /* Check if key is private or public */\n    const int is_priv =\n        mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 &&\n        mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 &&\n        mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 &&\n        mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 &&\n        mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0;\n\n    if( !is_priv )\n    {\n        /* If we're trying to export private parameters for a public key,\n         * something must be wrong. */\n        if( P != NULL || Q != NULL || D != NULL )\n            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    }\n\n    if( N != NULL )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->N, N, N_len ) );\n\n    if( P != NULL )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->P, P, P_len ) );\n\n    if( Q != NULL )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->Q, Q, Q_len ) );\n\n    if( D != NULL )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->D, D, D_len ) );\n\n    if( E != NULL )\n        MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->E, E, E_len ) );\n\ncleanup:\n\n    return( ret );\n}\n\nint mbedtls_rsa_export( const mbedtls_rsa_context *ctx,\n                        mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q,\n                        mbedtls_mpi *D, mbedtls_mpi *E )\n{\n    int ret;\n\n    /* Check if key is private or public */\n    int is_priv =\n        mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 &&\n        mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 &&\n        mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 &&\n        mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 &&\n        mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0;\n\n    if( !is_priv )\n    {\n        /* If we're trying to export private parameters for a public key,\n         * something must be wrong. */\n        if( P != NULL || Q != NULL || D != NULL )\n            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    }\n\n    /* Export all requested core parameters. */\n\n    if( ( N != NULL && ( ret = mbedtls_mpi_copy( N, &ctx->N ) ) != 0 ) ||\n        ( P != NULL && ( ret = mbedtls_mpi_copy( P, &ctx->P ) ) != 0 ) ||\n        ( Q != NULL && ( ret = mbedtls_mpi_copy( Q, &ctx->Q ) ) != 0 ) ||\n        ( D != NULL && ( ret = mbedtls_mpi_copy( D, &ctx->D ) ) != 0 ) ||\n        ( E != NULL && ( ret = mbedtls_mpi_copy( E, &ctx->E ) ) != 0 ) )\n    {\n        return( ret );\n    }\n\n    return( 0 );\n}\n\n/*\n * Export CRT parameters\n * This must also be implemented if CRT is not used, for being able to\n * write DER encoded RSA keys. The helper function mbedtls_rsa_deduce_crt\n * can be used in this case.\n */\nint mbedtls_rsa_export_crt( const mbedtls_rsa_context *ctx,\n                            mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP )\n{\n    int ret;\n\n    /* Check if key is private or public */\n    int is_priv =\n        mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 &&\n        mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 &&\n        mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 &&\n        mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 &&\n        mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0;\n\n    if( !is_priv )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n#if !defined(MBEDTLS_RSA_NO_CRT)\n    /* Export all requested blinding parameters. */\n    if( ( DP != NULL && ( ret = mbedtls_mpi_copy( DP, &ctx->DP ) ) != 0 ) ||\n        ( DQ != NULL && ( ret = mbedtls_mpi_copy( DQ, &ctx->DQ ) ) != 0 ) ||\n        ( QP != NULL && ( ret = mbedtls_mpi_copy( QP, &ctx->QP ) ) != 0 ) )\n    {\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );\n    }\n#else\n    if( ( ret = mbedtls_rsa_deduce_crt( &ctx->P, &ctx->Q, &ctx->D,\n                                        DP, DQ, QP ) ) != 0 )\n    {\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );\n    }\n#endif\n\n    return( 0 );\n}\n\n/*\n * Initialize an RSA context\n */\nvoid mbedtls_rsa_init( mbedtls_rsa_context *ctx,\n               int padding,\n               int hash_id )\n{\n    memset( ctx, 0, sizeof( mbedtls_rsa_context ) );\n\n    mbedtls_rsa_set_padding( ctx, padding, hash_id );\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_mutex_init( &ctx->mutex );\n#endif\n}\n\n/*\n * Set padding for an existing RSA context\n */\nvoid mbedtls_rsa_set_padding( mbedtls_rsa_context *ctx, int padding, int hash_id )\n{\n    ctx->padding = padding;\n    ctx->hash_id = hash_id;\n}\n\n/*\n * Get length in bytes of RSA modulus\n */\n\nsize_t mbedtls_rsa_get_len( const mbedtls_rsa_context *ctx )\n{\n    return( ctx->len );\n}\n\n\n#if defined(MBEDTLS_GENPRIME)\n\n/*\n * Generate an RSA keypair\n *\n * This generation method follows the RSA key pair generation procedure of\n * FIPS 186-4 if 2^16 < exponent < 2^256 and nbits = 2048 or nbits = 3072.\n */\nint mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx,\n                 int (*f_rng)(void *, unsigned char *, size_t),\n                 void *p_rng,\n                 unsigned int nbits, int exponent )\n{\n    int ret;\n    mbedtls_mpi H, G, L;\n\n    if( f_rng == NULL || nbits < 128 || exponent < 3 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    if( nbits % 2 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    mbedtls_mpi_init( &H );\n    mbedtls_mpi_init( &G );\n    mbedtls_mpi_init( &L );\n\n    /*\n     * find primes P and Q with Q < P so that:\n     * 1.  |P-Q| > 2^( nbits / 2 - 100 )\n     * 2.  GCD( E, (P-1)*(Q-1) ) == 1\n     * 3.  E^-1 mod LCM(P-1, Q-1) > 2^( nbits / 2 )\n     */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &ctx->E, exponent ) );\n\n    do\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->P, nbits >> 1, 0,\n                                                f_rng, p_rng ) );\n\n        MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, nbits >> 1, 0,\n                                                f_rng, p_rng ) );\n\n        /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &H, &ctx->P, &ctx->Q ) );\n        if( mbedtls_mpi_bitlen( &H ) <= ( ( nbits >= 200 ) ? ( ( nbits >> 1 ) - 99 ) : 0 ) )\n            continue;\n\n        /* not required by any standards, but some users rely on the fact that P > Q */\n        if( H.s < 0 )\n            mbedtls_mpi_swap( &ctx->P, &ctx->Q );\n\n        /* Temporarily replace P,Q by P-1, Q-1 */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &ctx->P, &ctx->P, 1 ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &ctx->Q, &ctx->Q, 1 ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &H, &ctx->P, &ctx->Q ) );\n\n        /* check GCD( E, (P-1)*(Q-1) ) == 1 (FIPS 186-4 §B.3.1 criterion 2(a)) */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->E, &H  ) );\n        if( mbedtls_mpi_cmp_int( &G, 1 ) != 0 )\n            continue;\n\n        /* compute smallest possible D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b)) */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->P, &ctx->Q ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &L, NULL, &H, &G ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->D, &ctx->E, &L ) );\n\n        if( mbedtls_mpi_bitlen( &ctx->D ) <= ( ( nbits + 1 ) / 2 ) ) // (FIPS 186-4 §B.3.1 criterion 3(a))\n            continue;\n\n        break;\n    }\n    while( 1 );\n\n    /* Restore P,Q */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &ctx->P,  &ctx->P, 1 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &ctx->Q,  &ctx->Q, 1 ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->N, &ctx->P, &ctx->Q ) );\n\n    ctx->len = mbedtls_mpi_size( &ctx->N );\n\n#if !defined(MBEDTLS_RSA_NO_CRT)\n    /*\n     * DP = D mod (P - 1)\n     * DQ = D mod (Q - 1)\n     * QP = Q^-1 mod P\n     */\n    MBEDTLS_MPI_CHK( mbedtls_rsa_deduce_crt( &ctx->P, &ctx->Q, &ctx->D,\n                                             &ctx->DP, &ctx->DQ, &ctx->QP ) );\n#endif /* MBEDTLS_RSA_NO_CRT */\n\n    /* Double-check */\n    MBEDTLS_MPI_CHK( mbedtls_rsa_check_privkey( ctx ) );\n\ncleanup:\n\n    mbedtls_mpi_free( &H );\n    mbedtls_mpi_free( &G );\n    mbedtls_mpi_free( &L );\n\n    if( ret != 0 )\n    {\n        mbedtls_rsa_free( ctx );\n        return( MBEDTLS_ERR_RSA_KEY_GEN_FAILED + ret );\n    }\n\n    return( 0 );\n}\n\n#endif /* MBEDTLS_GENPRIME */\n\n/*\n * Check a public RSA key\n */\nint mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx )\n{\n    if( rsa_check_context( ctx, 0 /* public */, 0 /* no blinding */ ) != 0 )\n        return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );\n\n    if( mbedtls_mpi_bitlen( &ctx->N ) < 128 )\n    {\n        return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );\n    }\n\n    if( mbedtls_mpi_get_bit( &ctx->E, 0 ) == 0 ||\n        mbedtls_mpi_bitlen( &ctx->E )     < 2  ||\n        mbedtls_mpi_cmp_mpi( &ctx->E, &ctx->N ) >= 0 )\n    {\n        return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );\n    }\n\n    return( 0 );\n}\n\n/*\n * Check for the consistency of all fields in an RSA private key context\n */\nint mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx )\n{\n    if( mbedtls_rsa_check_pubkey( ctx ) != 0 ||\n        rsa_check_context( ctx, 1 /* private */, 1 /* blinding */ ) != 0 )\n    {\n        return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );\n    }\n\n    if( mbedtls_rsa_validate_params( &ctx->N, &ctx->P, &ctx->Q,\n                                     &ctx->D, &ctx->E, NULL, NULL ) != 0 )\n    {\n        return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );\n    }\n\n#if !defined(MBEDTLS_RSA_NO_CRT)\n    else if( mbedtls_rsa_validate_crt( &ctx->P, &ctx->Q, &ctx->D,\n                                       &ctx->DP, &ctx->DQ, &ctx->QP ) != 0 )\n    {\n        return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );\n    }\n#endif\n\n    return( 0 );\n}\n\n/*\n * Check if contexts holding a public and private key match\n */\nint mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub,\n                                const mbedtls_rsa_context *prv )\n{\n    if( mbedtls_rsa_check_pubkey( pub )  != 0 ||\n        mbedtls_rsa_check_privkey( prv ) != 0 )\n    {\n        return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );\n    }\n\n    if( mbedtls_mpi_cmp_mpi( &pub->N, &prv->N ) != 0 ||\n        mbedtls_mpi_cmp_mpi( &pub->E, &prv->E ) != 0 )\n    {\n        return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );\n    }\n\n    return( 0 );\n}\n\n/*\n * Do an RSA public key operation\n */\nint mbedtls_rsa_public( mbedtls_rsa_context *ctx,\n                const unsigned char *input,\n                unsigned char *output )\n{\n    int ret;\n    size_t olen;\n    mbedtls_mpi T;\n\n    if( rsa_check_context( ctx, 0 /* public */, 0 /* no blinding */ ) )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    mbedtls_mpi_init( &T );\n\n#if defined(MBEDTLS_THREADING_C)\n    if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )\n        return( ret );\n#endif\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T, input, ctx->len ) );\n\n    if( mbedtls_mpi_cmp_mpi( &T, &ctx->N ) >= 0 )\n    {\n        ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;\n        goto cleanup;\n    }\n\n    olen = ctx->len;\n    MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T, &T, &ctx->E, &ctx->N, &ctx->RN ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &T, output, olen ) );\n\ncleanup:\n#if defined(MBEDTLS_THREADING_C)\n    if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )\n        return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );\n#endif\n\n    mbedtls_mpi_free( &T );\n\n    if( ret != 0 )\n        return( MBEDTLS_ERR_RSA_PUBLIC_FAILED + ret );\n\n    return( 0 );\n}\n\n/*\n * Generate or update blinding values, see section 10 of:\n *  KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA,\n *  DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer\n *  Berlin Heidelberg, 1996. p. 104-113.\n */\nstatic int rsa_prepare_blinding( mbedtls_rsa_context *ctx,\n                 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n{\n    int ret, count = 0;\n\n    if( ctx->Vf.p != NULL )\n    {\n        /* We already have blinding values, just update them by squaring */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vi, &ctx->Vi ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vf, &ctx->Vf, &ctx->Vf ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vf, &ctx->Vf, &ctx->N ) );\n\n        goto cleanup;\n    }\n\n    /* Unblinding value: Vf = random number, invertible mod N */\n    do {\n        if( count++ > 10 )\n            return( MBEDTLS_ERR_RSA_RNG_FAILED );\n\n        MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->Vf, ctx->len - 1, f_rng, p_rng ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &ctx->Vi, &ctx->Vf, &ctx->N ) );\n    } while( mbedtls_mpi_cmp_int( &ctx->Vi, 1 ) != 0 );\n\n    /* Blinding value: Vi =  Vf^(-e) mod N */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->Vi, &ctx->Vf, &ctx->N ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN ) );\n\n\ncleanup:\n    return( ret );\n}\n\n/*\n * Exponent blinding supposed to prevent side-channel attacks using multiple\n * traces of measurements to recover the RSA key. The more collisions are there,\n * the more bits of the key can be recovered. See [3].\n *\n * Collecting n collisions with m bit long blinding value requires 2^(m-m/n)\n * observations on avarage.\n *\n * For example with 28 byte blinding to achieve 2 collisions the adversary has\n * to make 2^112 observations on avarage.\n *\n * (With the currently (as of 2017 April) known best algorithms breaking 2048\n * bit RSA requires approximately as much time as trying out 2^112 random keys.\n * Thus in this sense with 28 byte blinding the security is not reduced by\n * side-channel attacks like the one in [3])\n *\n * This countermeasure does not help if the key recovery is possible with a\n * single trace.\n */\n#define RSA_EXPONENT_BLINDING 28\n\n/*\n * Do an RSA private key operation\n */\nint mbedtls_rsa_private( mbedtls_rsa_context *ctx,\n                 int (*f_rng)(void *, unsigned char *, size_t),\n                 void *p_rng,\n                 const unsigned char *input,\n                 unsigned char *output )\n{\n    int ret;\n    size_t olen;\n\n    /* Temporary holding the result */\n    mbedtls_mpi T;\n\n    /* Temporaries holding P-1, Q-1 and the\n     * exponent blinding factor, respectively. */\n    mbedtls_mpi P1, Q1, R;\n\n#if !defined(MBEDTLS_RSA_NO_CRT)\n    /* Temporaries holding the results mod p resp. mod q. */\n    mbedtls_mpi TP, TQ;\n\n    /* Temporaries holding the blinded exponents for\n     * the mod p resp. mod q computation (if used). */\n    mbedtls_mpi DP_blind, DQ_blind;\n\n    /* Pointers to actual exponents to be used - either the unblinded\n     * or the blinded ones, depending on the presence of a PRNG. */\n    mbedtls_mpi *DP = &ctx->DP;\n    mbedtls_mpi *DQ = &ctx->DQ;\n#else\n    /* Temporary holding the blinded exponent (if used). */\n    mbedtls_mpi D_blind;\n\n    /* Pointer to actual exponent to be used - either the unblinded\n     * or the blinded one, depending on the presence of a PRNG. */\n    mbedtls_mpi *D = &ctx->D;\n#endif /* MBEDTLS_RSA_NO_CRT */\n\n    /* Temporaries holding the initial input and the double\n     * checked result; should be the same in the end. */\n    mbedtls_mpi I, C;\n\n    if( rsa_check_context( ctx, 1             /* private key checks */,\n                                f_rng != NULL /* blinding y/n       */ ) != 0 )\n    {\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n    }\n\n#if defined(MBEDTLS_THREADING_C)\n    if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )\n        return( ret );\n#endif\n\n    /* MPI Initialization */\n    mbedtls_mpi_init( &T );\n\n    mbedtls_mpi_init( &P1 );\n    mbedtls_mpi_init( &Q1 );\n    mbedtls_mpi_init( &R );\n\n    if( f_rng != NULL )\n    {\n#if defined(MBEDTLS_RSA_NO_CRT)\n        mbedtls_mpi_init( &D_blind );\n#else\n        mbedtls_mpi_init( &DP_blind );\n        mbedtls_mpi_init( &DQ_blind );\n#endif\n    }\n\n#if !defined(MBEDTLS_RSA_NO_CRT)\n    mbedtls_mpi_init( &TP ); mbedtls_mpi_init( &TQ );\n#endif\n\n    mbedtls_mpi_init( &I );\n    mbedtls_mpi_init( &C );\n\n    /* End of MPI initialization */\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T, input, ctx->len ) );\n    if( mbedtls_mpi_cmp_mpi( &T, &ctx->N ) >= 0 )\n    {\n        ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;\n        goto cleanup;\n    }\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &I, &T ) );\n\n    if( f_rng != NULL )\n    {\n        /*\n         * Blinding\n         * T = T * Vi mod N\n         */\n        MBEDTLS_MPI_CHK( rsa_prepare_blinding( ctx, f_rng, p_rng ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &T, &ctx->Vi ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T, &ctx->N ) );\n\n        /*\n         * Exponent blinding\n         */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &P1, &ctx->P, 1 ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &Q1, &ctx->Q, 1 ) );\n\n#if defined(MBEDTLS_RSA_NO_CRT)\n        /*\n         * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D\n         */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING,\n                         f_rng, p_rng ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &D_blind, &P1, &Q1 ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &D_blind, &D_blind, &R ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &D_blind, &D_blind, &ctx->D ) );\n\n        D = &D_blind;\n#else\n        /*\n         * DP_blind = ( P - 1 ) * R + DP\n         */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING,\n                         f_rng, p_rng ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DP_blind, &P1, &R ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DP_blind, &DP_blind,\n                    &ctx->DP ) );\n\n        DP = &DP_blind;\n\n        /*\n         * DQ_blind = ( Q - 1 ) * R + DQ\n         */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING,\n                         f_rng, p_rng ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DQ_blind, &Q1, &R ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DQ_blind, &DQ_blind,\n                    &ctx->DQ ) );\n\n        DQ = &DQ_blind;\n#endif /* MBEDTLS_RSA_NO_CRT */\n    }\n\n#if defined(MBEDTLS_RSA_NO_CRT)\n    MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T, &T, D, &ctx->N, &ctx->RN ) );\n#else\n    /*\n     * Faster decryption using the CRT\n     *\n     * TP = input ^ dP mod P\n     * TQ = input ^ dQ mod Q\n     */\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &TP, &T, DP, &ctx->P, &ctx->RP ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &TQ, &T, DQ, &ctx->Q, &ctx->RQ ) );\n\n    /*\n     * T = (TP - TQ) * (Q^-1 mod P) mod P\n     */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T, &TP, &TQ ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &TP, &T, &ctx->QP ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &TP, &ctx->P ) );\n\n    /*\n     * T = TQ + T * Q\n     */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &TP, &T, &ctx->Q ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &T, &TQ, &TP ) );\n#endif /* MBEDTLS_RSA_NO_CRT */\n\n    if( f_rng != NULL )\n    {\n        /*\n         * Unblind\n         * T = T * Vf mod N\n         */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &T, &ctx->Vf ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T, &ctx->N ) );\n    }\n\n    /* Verify the result to prevent glitching attacks. */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &C, &T, &ctx->E,\n                                          &ctx->N, &ctx->RN ) );\n    if( mbedtls_mpi_cmp_mpi( &C, &I ) != 0 )\n    {\n        ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;\n        goto cleanup;\n    }\n\n    olen = ctx->len;\n    MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &T, output, olen ) );\n\ncleanup:\n#if defined(MBEDTLS_THREADING_C)\n    if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )\n        return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );\n#endif\n\n    mbedtls_mpi_free( &P1 );\n    mbedtls_mpi_free( &Q1 );\n    mbedtls_mpi_free( &R );\n\n    if( f_rng != NULL )\n    {\n#if defined(MBEDTLS_RSA_NO_CRT)\n        mbedtls_mpi_free( &D_blind );\n#else\n        mbedtls_mpi_free( &DP_blind );\n        mbedtls_mpi_free( &DQ_blind );\n#endif\n    }\n\n    mbedtls_mpi_free( &T );\n\n#if !defined(MBEDTLS_RSA_NO_CRT)\n    mbedtls_mpi_free( &TP ); mbedtls_mpi_free( &TQ );\n#endif\n\n    mbedtls_mpi_free( &C );\n    mbedtls_mpi_free( &I );\n\n    if( ret != 0 )\n        return( MBEDTLS_ERR_RSA_PRIVATE_FAILED + ret );\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_PKCS1_V21)\n/**\n * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer.\n *\n * \\param dst       buffer to mask\n * \\param dlen      length of destination buffer\n * \\param src       source of the mask generation\n * \\param slen      length of the source buffer\n * \\param md_ctx    message digest context to use\n */\nstatic int mgf_mask( unsigned char *dst, size_t dlen, unsigned char *src,\n                      size_t slen, mbedtls_md_context_t *md_ctx )\n{\n    unsigned char mask[MBEDTLS_MD_MAX_SIZE];\n    unsigned char counter[4];\n    unsigned char *p;\n    unsigned int hlen;\n    size_t i, use_len;\n    int ret = 0;\n\n    memset( mask, 0, MBEDTLS_MD_MAX_SIZE );\n    memset( counter, 0, 4 );\n\n    hlen = mbedtls_md_get_size( md_ctx->md_info );\n\n    /* Generate and apply dbMask */\n    p = dst;\n\n    while( dlen > 0 )\n    {\n        use_len = hlen;\n        if( dlen < hlen )\n            use_len = dlen;\n\n        if( ( ret = mbedtls_md_starts( md_ctx ) ) != 0 )\n            goto exit;\n        if( ( ret = mbedtls_md_update( md_ctx, src, slen ) ) != 0 )\n            goto exit;\n        if( ( ret = mbedtls_md_update( md_ctx, counter, 4 ) ) != 0 )\n            goto exit;\n        if( ( ret = mbedtls_md_finish( md_ctx, mask ) ) != 0 )\n            goto exit;\n\n        for( i = 0; i < use_len; ++i )\n            *p++ ^= mask[i];\n\n        counter[3]++;\n\n        dlen -= use_len;\n    }\n\nexit:\n    mbedtls_platform_zeroize( mask, sizeof( mask ) );\n\n    return( ret );\n}\n#endif /* MBEDTLS_PKCS1_V21 */\n\n#if defined(MBEDTLS_PKCS1_V21)\n/*\n * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function\n */\nint mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx,\n                            int (*f_rng)(void *, unsigned char *, size_t),\n                            void *p_rng,\n                            int mode,\n                            const unsigned char *label, size_t label_len,\n                            size_t ilen,\n                            const unsigned char *input,\n                            unsigned char *output )\n{\n    size_t olen;\n    int ret;\n    unsigned char *p = output;\n    unsigned int hlen;\n    const mbedtls_md_info_t *md_info;\n    mbedtls_md_context_t md_ctx;\n\n    if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    if( f_rng == NULL )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id );\n    if( md_info == NULL )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    olen = ctx->len;\n    hlen = mbedtls_md_get_size( md_info );\n\n    /* first comparison checks for overflow */\n    if( ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    memset( output, 0, olen );\n\n    *p++ = 0;\n\n    /* Generate a random octet string seed */\n    if( ( ret = f_rng( p_rng, p, hlen ) ) != 0 )\n        return( MBEDTLS_ERR_RSA_RNG_FAILED + ret );\n\n    p += hlen;\n\n    /* Construct DB */\n    if( ( ret = mbedtls_md( md_info, label, label_len, p ) ) != 0 )\n        return( ret );\n    p += hlen;\n    p += olen - 2 * hlen - 2 - ilen;\n    *p++ = 1;\n    memcpy( p, input, ilen );\n\n    mbedtls_md_init( &md_ctx );\n    if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )\n        goto exit;\n\n    /* maskedDB: Apply dbMask to DB */\n    if( ( ret = mgf_mask( output + hlen + 1, olen - hlen - 1, output + 1, hlen,\n                          &md_ctx ) ) != 0 )\n        goto exit;\n\n    /* maskedSeed: Apply seedMask to seed */\n    if( ( ret = mgf_mask( output + 1, hlen, output + hlen + 1, olen - hlen - 1,\n                          &md_ctx ) ) != 0 )\n        goto exit;\n\nexit:\n    mbedtls_md_free( &md_ctx );\n\n    if( ret != 0 )\n        return( ret );\n\n    return( ( mode == MBEDTLS_RSA_PUBLIC )\n            ? mbedtls_rsa_public(  ctx, output, output )\n            : mbedtls_rsa_private( ctx, f_rng, p_rng, output, output ) );\n}\n#endif /* MBEDTLS_PKCS1_V21 */\n\n#if defined(MBEDTLS_PKCS1_V15)\n/*\n * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function\n */\nint mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx,\n                                 int (*f_rng)(void *, unsigned char *, size_t),\n                                 void *p_rng,\n                                 int mode, size_t ilen,\n                                 const unsigned char *input,\n                                 unsigned char *output )\n{\n    size_t nb_pad, olen;\n    int ret;\n    unsigned char *p = output;\n\n    if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    // We don't check p_rng because it won't be dereferenced here\n    if( f_rng == NULL || input == NULL || output == NULL )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    olen = ctx->len;\n\n    /* first comparison checks for overflow */\n    if( ilen + 11 < ilen || olen < ilen + 11 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    nb_pad = olen - 3 - ilen;\n\n    *p++ = 0;\n    if( mode == MBEDTLS_RSA_PUBLIC )\n    {\n        *p++ = MBEDTLS_RSA_CRYPT;\n\n        while( nb_pad-- > 0 )\n        {\n            int rng_dl = 100;\n\n            do {\n                ret = f_rng( p_rng, p, 1 );\n            } while( *p == 0 && --rng_dl && ret == 0 );\n\n            /* Check if RNG failed to generate data */\n            if( rng_dl == 0 || ret != 0 )\n                return( MBEDTLS_ERR_RSA_RNG_FAILED + ret );\n\n            p++;\n        }\n    }\n    else\n    {\n        *p++ = MBEDTLS_RSA_SIGN;\n\n        while( nb_pad-- > 0 )\n            *p++ = 0xFF;\n    }\n\n    *p++ = 0;\n    memcpy( p, input, ilen );\n\n    return( ( mode == MBEDTLS_RSA_PUBLIC )\n            ? mbedtls_rsa_public(  ctx, output, output )\n            : mbedtls_rsa_private( ctx, f_rng, p_rng, output, output ) );\n}\n#endif /* MBEDTLS_PKCS1_V15 */\n\n/*\n * Add the message padding, then do an RSA operation\n */\nint mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx,\n                       int (*f_rng)(void *, unsigned char *, size_t),\n                       void *p_rng,\n                       int mode, size_t ilen,\n                       const unsigned char *input,\n                       unsigned char *output )\n{\n    switch( ctx->padding )\n    {\n#if defined(MBEDTLS_PKCS1_V15)\n        case MBEDTLS_RSA_PKCS_V15:\n            return mbedtls_rsa_rsaes_pkcs1_v15_encrypt( ctx, f_rng, p_rng, mode, ilen,\n                                                input, output );\n#endif\n\n#if defined(MBEDTLS_PKCS1_V21)\n        case MBEDTLS_RSA_PKCS_V21:\n            return mbedtls_rsa_rsaes_oaep_encrypt( ctx, f_rng, p_rng, mode, NULL, 0,\n                                           ilen, input, output );\n#endif\n\n        default:\n            return( MBEDTLS_ERR_RSA_INVALID_PADDING );\n    }\n}\n\n#if defined(MBEDTLS_PKCS1_V21)\n/*\n * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function\n */\nint mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx,\n                            int (*f_rng)(void *, unsigned char *, size_t),\n                            void *p_rng,\n                            int mode,\n                            const unsigned char *label, size_t label_len,\n                            size_t *olen,\n                            const unsigned char *input,\n                            unsigned char *output,\n                            size_t output_max_len )\n{\n    int ret;\n    size_t ilen, i, pad_len;\n    unsigned char *p, bad, pad_done;\n    unsigned char buf[MBEDTLS_MPI_MAX_SIZE];\n    unsigned char lhash[MBEDTLS_MD_MAX_SIZE];\n    unsigned int hlen;\n    const mbedtls_md_info_t *md_info;\n    mbedtls_md_context_t md_ctx;\n\n    /*\n     * Parameters sanity checks\n     */\n    if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    ilen = ctx->len;\n\n    if( ilen < 16 || ilen > sizeof( buf ) )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id );\n    if( md_info == NULL )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    hlen = mbedtls_md_get_size( md_info );\n\n    // checking for integer underflow\n    if( 2 * hlen + 2 > ilen )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    /*\n     * RSA operation\n     */\n    ret = ( mode == MBEDTLS_RSA_PUBLIC )\n          ? mbedtls_rsa_public(  ctx, input, buf )\n          : mbedtls_rsa_private( ctx, f_rng, p_rng, input, buf );\n\n    if( ret != 0 )\n        goto cleanup;\n\n    /*\n     * Unmask data and generate lHash\n     */\n    mbedtls_md_init( &md_ctx );\n    if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )\n    {\n        mbedtls_md_free( &md_ctx );\n        goto cleanup;\n    }\n\n    /* seed: Apply seedMask to maskedSeed */\n    if( ( ret = mgf_mask( buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,\n                          &md_ctx ) ) != 0 ||\n    /* DB: Apply dbMask to maskedDB */\n        ( ret = mgf_mask( buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,\n                          &md_ctx ) ) != 0 )\n    {\n        mbedtls_md_free( &md_ctx );\n        goto cleanup;\n    }\n\n    mbedtls_md_free( &md_ctx );\n\n    /* Generate lHash */\n    if( ( ret = mbedtls_md( md_info, label, label_len, lhash ) ) != 0 )\n        goto cleanup;\n\n    /*\n     * Check contents, in \"constant-time\"\n     */\n    p = buf;\n    bad = 0;\n\n    bad |= *p++; /* First byte must be 0 */\n\n    p += hlen; /* Skip seed */\n\n    /* Check lHash */\n    for( i = 0; i < hlen; i++ )\n        bad |= lhash[i] ^ *p++;\n\n    /* Get zero-padding len, but always read till end of buffer\n     * (minus one, for the 01 byte) */\n    pad_len = 0;\n    pad_done = 0;\n    for( i = 0; i < ilen - 2 * hlen - 2; i++ )\n    {\n        pad_done |= p[i];\n        pad_len += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;\n    }\n\n    p += pad_len;\n    bad |= *p++ ^ 0x01;\n\n    /*\n     * The only information \"leaked\" is whether the padding was correct or not\n     * (eg, no data is copied if it was not correct). This meets the\n     * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between\n     * the different error conditions.\n     */\n    if( bad != 0 )\n    {\n        ret = MBEDTLS_ERR_RSA_INVALID_PADDING;\n        goto cleanup;\n    }\n\n    if( ilen - ( p - buf ) > output_max_len )\n    {\n        ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;\n        goto cleanup;\n    }\n\n    *olen = ilen - (p - buf);\n    memcpy( output, p, *olen );\n    ret = 0;\n\ncleanup:\n    mbedtls_platform_zeroize( buf, sizeof( buf ) );\n    mbedtls_platform_zeroize( lhash, sizeof( lhash ) );\n\n    return( ret );\n}\n#endif /* MBEDTLS_PKCS1_V21 */\n\n#if defined(MBEDTLS_PKCS1_V15)\n/*\n * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function\n */\nint mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx,\n                                 int (*f_rng)(void *, unsigned char *, size_t),\n                                 void *p_rng,\n                                 int mode, size_t *olen,\n                                 const unsigned char *input,\n                                 unsigned char *output,\n                                 size_t output_max_len)\n{\n    int ret;\n    size_t ilen, pad_count = 0, i;\n    unsigned char *p, bad, pad_done = 0;\n    unsigned char buf[MBEDTLS_MPI_MAX_SIZE];\n\n    if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    ilen = ctx->len;\n\n    if( ilen < 16 || ilen > sizeof( buf ) )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    ret = ( mode == MBEDTLS_RSA_PUBLIC )\n          ? mbedtls_rsa_public(  ctx, input, buf )\n          : mbedtls_rsa_private( ctx, f_rng, p_rng, input, buf );\n\n    if( ret != 0 )\n        goto cleanup;\n\n    p = buf;\n    bad = 0;\n\n    /*\n     * Check and get padding len in \"constant-time\"\n     */\n    bad |= *p++; /* First byte must be 0 */\n\n    /* This test does not depend on secret data */\n    if( mode == MBEDTLS_RSA_PRIVATE )\n    {\n        bad |= *p++ ^ MBEDTLS_RSA_CRYPT;\n\n        /* Get padding len, but always read till end of buffer\n         * (minus one, for the 00 byte) */\n        for( i = 0; i < ilen - 3; i++ )\n        {\n            pad_done  |= ((p[i] | (unsigned char)-p[i]) >> 7) ^ 1;\n            pad_count += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;\n        }\n\n        p += pad_count;\n        bad |= *p++; /* Must be zero */\n    }\n    else\n    {\n        bad |= *p++ ^ MBEDTLS_RSA_SIGN;\n\n        /* Get padding len, but always read till end of buffer\n         * (minus one, for the 00 byte) */\n        for( i = 0; i < ilen - 3; i++ )\n        {\n            pad_done |= ( p[i] != 0xFF );\n            pad_count += ( pad_done == 0 );\n        }\n\n        p += pad_count;\n        bad |= *p++; /* Must be zero */\n    }\n\n    bad |= ( pad_count < 8 );\n\n    if( bad )\n    {\n        ret = MBEDTLS_ERR_RSA_INVALID_PADDING;\n        goto cleanup;\n    }\n\n    if( ilen - ( p - buf ) > output_max_len )\n    {\n        ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;\n        goto cleanup;\n    }\n\n    *olen = ilen - (p - buf);\n    memcpy( output, p, *olen );\n    ret = 0;\n\ncleanup:\n    mbedtls_platform_zeroize( buf, sizeof( buf ) );\n\n    return( ret );\n}\n#endif /* MBEDTLS_PKCS1_V15 */\n\n/*\n * Do an RSA operation, then remove the message padding\n */\nint mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx,\n                       int (*f_rng)(void *, unsigned char *, size_t),\n                       void *p_rng,\n                       int mode, size_t *olen,\n                       const unsigned char *input,\n                       unsigned char *output,\n                       size_t output_max_len)\n{\n    switch( ctx->padding )\n    {\n#if defined(MBEDTLS_PKCS1_V15)\n        case MBEDTLS_RSA_PKCS_V15:\n            return mbedtls_rsa_rsaes_pkcs1_v15_decrypt( ctx, f_rng, p_rng, mode, olen,\n                                                input, output, output_max_len );\n#endif\n\n#if defined(MBEDTLS_PKCS1_V21)\n        case MBEDTLS_RSA_PKCS_V21:\n            return mbedtls_rsa_rsaes_oaep_decrypt( ctx, f_rng, p_rng, mode, NULL, 0,\n                                           olen, input, output,\n                                           output_max_len );\n#endif\n\n        default:\n            return( MBEDTLS_ERR_RSA_INVALID_PADDING );\n    }\n}\n\n#if defined(MBEDTLS_PKCS1_V21)\n/*\n * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function\n */\nint mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx,\n                         int (*f_rng)(void *, unsigned char *, size_t),\n                         void *p_rng,\n                         int mode,\n                         mbedtls_md_type_t md_alg,\n                         unsigned int hashlen,\n                         const unsigned char *hash,\n                         unsigned char *sig )\n{\n    size_t olen;\n    unsigned char *p = sig;\n    unsigned char salt[MBEDTLS_MD_MAX_SIZE];\n    unsigned int slen, hlen, offset = 0;\n    int ret;\n    size_t msb;\n    const mbedtls_md_info_t *md_info;\n    mbedtls_md_context_t md_ctx;\n\n    if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    if( f_rng == NULL )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    olen = ctx->len;\n\n    if( md_alg != MBEDTLS_MD_NONE )\n    {\n        /* Gather length of hash to sign */\n        md_info = mbedtls_md_info_from_type( md_alg );\n        if( md_info == NULL )\n            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n        hashlen = mbedtls_md_get_size( md_info );\n    }\n\n    md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id );\n    if( md_info == NULL )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    hlen = mbedtls_md_get_size( md_info );\n    slen = hlen;\n\n    if( olen < hlen + slen + 2 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    memset( sig, 0, olen );\n\n    /* Generate salt of length slen */\n    if( ( ret = f_rng( p_rng, salt, slen ) ) != 0 )\n        return( MBEDTLS_ERR_RSA_RNG_FAILED + ret );\n\n    /* Note: EMSA-PSS encoding is over the length of N - 1 bits */\n    msb = mbedtls_mpi_bitlen( &ctx->N ) - 1;\n    p += olen - hlen * 2 - 2;\n    *p++ = 0x01;\n    memcpy( p, salt, slen );\n    p += slen;\n\n    mbedtls_md_init( &md_ctx );\n    if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )\n        goto exit;\n\n    /* Generate H = Hash( M' ) */\n    if( ( ret = mbedtls_md_starts( &md_ctx ) ) != 0 )\n        goto exit;\n    if( ( ret = mbedtls_md_update( &md_ctx, p, 8 ) ) != 0 )\n        goto exit;\n    if( ( ret = mbedtls_md_update( &md_ctx, hash, hashlen ) ) != 0 )\n        goto exit;\n    if( ( ret = mbedtls_md_update( &md_ctx, salt, slen ) ) != 0 )\n        goto exit;\n    if( ( ret = mbedtls_md_finish( &md_ctx, p ) ) != 0 )\n        goto exit;\n\n    /* Compensate for boundary condition when applying mask */\n    if( msb % 8 == 0 )\n        offset = 1;\n\n    /* maskedDB: Apply dbMask to DB */\n    if( ( ret = mgf_mask( sig + offset, olen - hlen - 1 - offset, p, hlen,\n                          &md_ctx ) ) != 0 )\n        goto exit;\n\n    msb = mbedtls_mpi_bitlen( &ctx->N ) - 1;\n    sig[0] &= 0xFF >> ( olen * 8 - msb );\n\n    p += hlen;\n    *p++ = 0xBC;\n\n    mbedtls_platform_zeroize( salt, sizeof( salt ) );\n\nexit:\n    mbedtls_md_free( &md_ctx );\n\n    if( ret != 0 )\n        return( ret );\n\n    return( ( mode == MBEDTLS_RSA_PUBLIC )\n            ? mbedtls_rsa_public(  ctx, sig, sig )\n            : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, sig ) );\n}\n#endif /* MBEDTLS_PKCS1_V21 */\n\n#if defined(MBEDTLS_PKCS1_V15)\n/*\n * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function\n */\n\n/* Construct a PKCS v1.5 encoding of a hashed message\n *\n * This is used both for signature generation and verification.\n *\n * Parameters:\n * - md_alg:  Identifies the hash algorithm used to generate the given hash;\n *            MBEDTLS_MD_NONE if raw data is signed.\n * - hashlen: Length of hash in case hashlen is MBEDTLS_MD_NONE.\n * - hash:    Buffer containing the hashed message or the raw data.\n * - dst_len: Length of the encoded message.\n * - dst:     Buffer to hold the encoded message.\n *\n * Assumptions:\n * - hash has size hashlen if md_alg == MBEDTLS_MD_NONE.\n * - hash has size corresponding to md_alg if md_alg != MBEDTLS_MD_NONE.\n * - dst points to a buffer of size at least dst_len.\n *\n */\nstatic int rsa_rsassa_pkcs1_v15_encode( mbedtls_md_type_t md_alg,\n                                        unsigned int hashlen,\n                                        const unsigned char *hash,\n                                        size_t dst_len,\n                                        unsigned char *dst )\n{\n    size_t oid_size  = 0;\n    size_t nb_pad    = dst_len;\n    unsigned char *p = dst;\n    const char *oid  = NULL;\n\n    /* Are we signing hashed or raw data? */\n    if( md_alg != MBEDTLS_MD_NONE )\n    {\n        const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );\n        if( md_info == NULL )\n            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n        if( mbedtls_oid_get_oid_by_md( md_alg, &oid, &oid_size ) != 0 )\n            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n        hashlen = mbedtls_md_get_size( md_info );\n\n        /* Double-check that 8 + hashlen + oid_size can be used as a\n         * 1-byte ASN.1 length encoding and that there's no overflow. */\n        if( 8 + hashlen + oid_size  >= 0x80         ||\n            10 + hashlen            <  hashlen      ||\n            10 + hashlen + oid_size <  10 + hashlen )\n            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n        /*\n         * Static bounds check:\n         * - Need 10 bytes for five tag-length pairs.\n         *   (Insist on 1-byte length encodings to protect against variants of\n         *    Bleichenbacher's forgery attack against lax PKCS#1v1.5 verification)\n         * - Need hashlen bytes for hash\n         * - Need oid_size bytes for hash alg OID.\n         */\n        if( nb_pad < 10 + hashlen + oid_size )\n            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n        nb_pad -= 10 + hashlen + oid_size;\n    }\n    else\n    {\n        if( nb_pad < hashlen )\n            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n        nb_pad -= hashlen;\n    }\n\n    /* Need space for signature header and padding delimiter (3 bytes),\n     * and 8 bytes for the minimal padding */\n    if( nb_pad < 3 + 8 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n    nb_pad -= 3;\n\n    /* Now nb_pad is the amount of memory to be filled\n     * with padding, and at least 8 bytes long. */\n\n    /* Write signature header and padding */\n    *p++ = 0;\n    *p++ = MBEDTLS_RSA_SIGN;\n    memset( p, 0xFF, nb_pad );\n    p += nb_pad;\n    *p++ = 0;\n\n    /* Are we signing raw data? */\n    if( md_alg == MBEDTLS_MD_NONE )\n    {\n        memcpy( p, hash, hashlen );\n        return( 0 );\n    }\n\n    /* Signing hashed data, add corresponding ASN.1 structure\n     *\n     * DigestInfo ::= SEQUENCE {\n     *   digestAlgorithm DigestAlgorithmIdentifier,\n     *   digest Digest }\n     * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n     * Digest ::= OCTET STRING\n     *\n     * Schematic:\n     * TAG-SEQ + LEN [ TAG-SEQ + LEN [ TAG-OID  + LEN [ OID  ]\n     *                                 TAG-NULL + LEN [ NULL ] ]\n     *                 TAG-OCTET + LEN [ HASH ] ]\n     */\n    *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;\n    *p++ = (unsigned char)( 0x08 + oid_size + hashlen );\n    *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;\n    *p++ = (unsigned char)( 0x04 + oid_size );\n    *p++ = MBEDTLS_ASN1_OID;\n    *p++ = (unsigned char) oid_size;\n    memcpy( p, oid, oid_size );\n    p += oid_size;\n    *p++ = MBEDTLS_ASN1_NULL;\n    *p++ = 0x00;\n    *p++ = MBEDTLS_ASN1_OCTET_STRING;\n    *p++ = (unsigned char) hashlen;\n    memcpy( p, hash, hashlen );\n    p += hashlen;\n\n    /* Just a sanity-check, should be automatic\n     * after the initial bounds check. */\n    if( p != dst + dst_len )\n    {\n        mbedtls_platform_zeroize( dst, dst_len );\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n    }\n\n    return( 0 );\n}\n\n/*\n * Do an RSA operation to sign the message digest\n */\nint mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx,\n                               int (*f_rng)(void *, unsigned char *, size_t),\n                               void *p_rng,\n                               int mode,\n                               mbedtls_md_type_t md_alg,\n                               unsigned int hashlen,\n                               const unsigned char *hash,\n                               unsigned char *sig )\n{\n    int ret;\n    unsigned char *sig_try = NULL, *verif = NULL;\n\n    if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    /*\n     * Prepare PKCS1-v1.5 encoding (padding and hash identifier)\n     */\n\n    if( ( ret = rsa_rsassa_pkcs1_v15_encode( md_alg, hashlen, hash,\n                                             ctx->len, sig ) ) != 0 )\n        return( ret );\n\n    /*\n     * Call respective RSA primitive\n     */\n\n    if( mode == MBEDTLS_RSA_PUBLIC )\n    {\n        /* Skip verification on a public key operation */\n        return( mbedtls_rsa_public( ctx, sig, sig ) );\n    }\n\n    /* Private key operation\n     *\n     * In order to prevent Lenstra's attack, make the signature in a\n     * temporary buffer and check it before returning it.\n     */\n\n    sig_try = mbedtls_calloc( 1, ctx->len );\n    if( sig_try == NULL )\n        return( MBEDTLS_ERR_MPI_ALLOC_FAILED );\n\n    verif = mbedtls_calloc( 1, ctx->len );\n    if( verif == NULL )\n    {\n        mbedtls_free( sig_try );\n        return( MBEDTLS_ERR_MPI_ALLOC_FAILED );\n    }\n\n    MBEDTLS_MPI_CHK( mbedtls_rsa_private( ctx, f_rng, p_rng, sig, sig_try ) );\n    MBEDTLS_MPI_CHK( mbedtls_rsa_public( ctx, sig_try, verif ) );\n\n    if( mbedtls_safer_memcmp( verif, sig, ctx->len ) != 0 )\n    {\n        ret = MBEDTLS_ERR_RSA_PRIVATE_FAILED;\n        goto cleanup;\n    }\n\n    memcpy( sig, sig_try, ctx->len );\n\ncleanup:\n    mbedtls_free( sig_try );\n    mbedtls_free( verif );\n\n    return( ret );\n}\n#endif /* MBEDTLS_PKCS1_V15 */\n\n/*\n * Do an RSA operation to sign the message digest\n */\nint mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx,\n                    int (*f_rng)(void *, unsigned char *, size_t),\n                    void *p_rng,\n                    int mode,\n                    mbedtls_md_type_t md_alg,\n                    unsigned int hashlen,\n                    const unsigned char *hash,\n                    unsigned char *sig )\n{\n    switch( ctx->padding )\n    {\n#if defined(MBEDTLS_PKCS1_V15)\n        case MBEDTLS_RSA_PKCS_V15:\n            return mbedtls_rsa_rsassa_pkcs1_v15_sign( ctx, f_rng, p_rng, mode, md_alg,\n                                              hashlen, hash, sig );\n#endif\n\n#if defined(MBEDTLS_PKCS1_V21)\n        case MBEDTLS_RSA_PKCS_V21:\n            return mbedtls_rsa_rsassa_pss_sign( ctx, f_rng, p_rng, mode, md_alg,\n                                        hashlen, hash, sig );\n#endif\n\n        default:\n            return( MBEDTLS_ERR_RSA_INVALID_PADDING );\n    }\n}\n\n#if defined(MBEDTLS_PKCS1_V21)\n/*\n * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function\n */\nint mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx,\n                               int (*f_rng)(void *, unsigned char *, size_t),\n                               void *p_rng,\n                               int mode,\n                               mbedtls_md_type_t md_alg,\n                               unsigned int hashlen,\n                               const unsigned char *hash,\n                               mbedtls_md_type_t mgf1_hash_id,\n                               int expected_salt_len,\n                               const unsigned char *sig )\n{\n    int ret;\n    size_t siglen;\n    unsigned char *p;\n    unsigned char *hash_start;\n    unsigned char result[MBEDTLS_MD_MAX_SIZE];\n    unsigned char zeros[8];\n    unsigned int hlen;\n    size_t observed_salt_len, msb;\n    const mbedtls_md_info_t *md_info;\n    mbedtls_md_context_t md_ctx;\n    unsigned char buf[MBEDTLS_MPI_MAX_SIZE];\n\n    if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    siglen = ctx->len;\n\n    if( siglen < 16 || siglen > sizeof( buf ) )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    ret = ( mode == MBEDTLS_RSA_PUBLIC )\n          ? mbedtls_rsa_public(  ctx, sig, buf )\n          : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, buf );\n\n    if( ret != 0 )\n        return( ret );\n\n    p = buf;\n\n    if( buf[siglen - 1] != 0xBC )\n        return( MBEDTLS_ERR_RSA_INVALID_PADDING );\n\n    if( md_alg != MBEDTLS_MD_NONE )\n    {\n        /* Gather length of hash to sign */\n        md_info = mbedtls_md_info_from_type( md_alg );\n        if( md_info == NULL )\n            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n        hashlen = mbedtls_md_get_size( md_info );\n    }\n\n    md_info = mbedtls_md_info_from_type( mgf1_hash_id );\n    if( md_info == NULL )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    hlen = mbedtls_md_get_size( md_info );\n\n    memset( zeros, 0, 8 );\n\n    /*\n     * Note: EMSA-PSS verification is over the length of N - 1 bits\n     */\n    msb = mbedtls_mpi_bitlen( &ctx->N ) - 1;\n\n    if( buf[0] >> ( 8 - siglen * 8 + msb ) )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    /* Compensate for boundary condition when applying mask */\n    if( msb % 8 == 0 )\n    {\n        p++;\n        siglen -= 1;\n    }\n\n    if( siglen < hlen + 2 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n    hash_start = p + siglen - hlen - 1;\n\n    mbedtls_md_init( &md_ctx );\n    if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )\n        goto exit;\n\n    ret = mgf_mask( p, siglen - hlen - 1, hash_start, hlen, &md_ctx );\n    if( ret != 0 )\n        goto exit;\n\n    buf[0] &= 0xFF >> ( siglen * 8 - msb );\n\n    while( p < hash_start - 1 && *p == 0 )\n        p++;\n\n    if( *p++ != 0x01 )\n    {\n        ret = MBEDTLS_ERR_RSA_INVALID_PADDING;\n        goto exit;\n    }\n\n    observed_salt_len = hash_start - p;\n\n    if( expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY &&\n        observed_salt_len != (size_t) expected_salt_len )\n    {\n        ret = MBEDTLS_ERR_RSA_INVALID_PADDING;\n        goto exit;\n    }\n\n    /*\n     * Generate H = Hash( M' )\n     */\n    ret = mbedtls_md_starts( &md_ctx );\n    if ( ret != 0 )\n        goto exit;\n    ret = mbedtls_md_update( &md_ctx, zeros, 8 );\n    if ( ret != 0 )\n        goto exit;\n    ret = mbedtls_md_update( &md_ctx, hash, hashlen );\n    if ( ret != 0 )\n        goto exit;\n    ret = mbedtls_md_update( &md_ctx, p, observed_salt_len );\n    if ( ret != 0 )\n        goto exit;\n    ret = mbedtls_md_finish( &md_ctx, result );\n    if ( ret != 0 )\n        goto exit;\n\n    if( memcmp( hash_start, result, hlen ) != 0 )\n    {\n        ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;\n        goto exit;\n    }\n\nexit:\n    mbedtls_md_free( &md_ctx );\n\n    return( ret );\n}\n\n/*\n * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function\n */\nint mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx,\n                           int (*f_rng)(void *, unsigned char *, size_t),\n                           void *p_rng,\n                           int mode,\n                           mbedtls_md_type_t md_alg,\n                           unsigned int hashlen,\n                           const unsigned char *hash,\n                           const unsigned char *sig )\n{\n    mbedtls_md_type_t mgf1_hash_id = ( ctx->hash_id != MBEDTLS_MD_NONE )\n                             ? (mbedtls_md_type_t) ctx->hash_id\n                             : md_alg;\n\n    return( mbedtls_rsa_rsassa_pss_verify_ext( ctx, f_rng, p_rng, mode,\n                                       md_alg, hashlen, hash,\n                                       mgf1_hash_id, MBEDTLS_RSA_SALT_LEN_ANY,\n                                       sig ) );\n\n}\n#endif /* MBEDTLS_PKCS1_V21 */\n\n#if defined(MBEDTLS_PKCS1_V15)\n/*\n * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function\n */\nint mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx,\n                                 int (*f_rng)(void *, unsigned char *, size_t),\n                                 void *p_rng,\n                                 int mode,\n                                 mbedtls_md_type_t md_alg,\n                                 unsigned int hashlen,\n                                 const unsigned char *hash,\n                                 const unsigned char *sig )\n{\n    int ret = 0;\n    const size_t sig_len = ctx->len;\n    unsigned char *encoded = NULL, *encoded_expected = NULL;\n\n    if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )\n        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n    /*\n     * Prepare expected PKCS1 v1.5 encoding of hash.\n     */\n\n    if( ( encoded          = mbedtls_calloc( 1, sig_len ) ) == NULL ||\n        ( encoded_expected = mbedtls_calloc( 1, sig_len ) ) == NULL )\n    {\n        ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;\n        goto cleanup;\n    }\n\n    if( ( ret = rsa_rsassa_pkcs1_v15_encode( md_alg, hashlen, hash, sig_len,\n                                             encoded_expected ) ) != 0 )\n        goto cleanup;\n\n    /*\n     * Apply RSA primitive to get what should be PKCS1 encoded hash.\n     */\n\n    ret = ( mode == MBEDTLS_RSA_PUBLIC )\n          ? mbedtls_rsa_public(  ctx, sig, encoded )\n          : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, encoded );\n    if( ret != 0 )\n        goto cleanup;\n\n    /*\n     * Compare\n     */\n\n    if( ( ret = mbedtls_safer_memcmp( encoded, encoded_expected,\n                                      sig_len ) ) != 0 )\n    {\n        ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;\n        goto cleanup;\n    }\n\ncleanup:\n\n    if( encoded != NULL )\n    {\n        mbedtls_platform_zeroize( encoded, sig_len );\n        mbedtls_free( encoded );\n    }\n\n    if( encoded_expected != NULL )\n    {\n        mbedtls_platform_zeroize( encoded_expected, sig_len );\n        mbedtls_free( encoded_expected );\n    }\n\n    return( ret );\n}\n#endif /* MBEDTLS_PKCS1_V15 */\n\n/*\n * Do an RSA operation and check the message digest\n */\nint mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx,\n                      int (*f_rng)(void *, unsigned char *, size_t),\n                      void *p_rng,\n                      int mode,\n                      mbedtls_md_type_t md_alg,\n                      unsigned int hashlen,\n                      const unsigned char *hash,\n                      const unsigned char *sig )\n{\n    switch( ctx->padding )\n    {\n#if defined(MBEDTLS_PKCS1_V15)\n        case MBEDTLS_RSA_PKCS_V15:\n            return mbedtls_rsa_rsassa_pkcs1_v15_verify( ctx, f_rng, p_rng, mode, md_alg,\n                                                hashlen, hash, sig );\n#endif\n\n#if defined(MBEDTLS_PKCS1_V21)\n        case MBEDTLS_RSA_PKCS_V21:\n            return mbedtls_rsa_rsassa_pss_verify( ctx, f_rng, p_rng, mode, md_alg,\n                                          hashlen, hash, sig );\n#endif\n\n        default:\n            return( MBEDTLS_ERR_RSA_INVALID_PADDING );\n    }\n}\n\n/*\n * Copy the components of an RSA key\n */\nint mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src )\n{\n    int ret;\n\n    dst->ver = src->ver;\n    dst->len = src->len;\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->N, &src->N ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->E, &src->E ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->D, &src->D ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->P, &src->P ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Q, &src->Q ) );\n\n#if !defined(MBEDTLS_RSA_NO_CRT)\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->DP, &src->DP ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->DQ, &src->DQ ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->QP, &src->QP ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RP, &src->RP ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RQ, &src->RQ ) );\n#endif\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RN, &src->RN ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Vi, &src->Vi ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Vf, &src->Vf ) );\n\n    dst->padding = src->padding;\n    dst->hash_id = src->hash_id;\n\ncleanup:\n    if( ret != 0 )\n        mbedtls_rsa_free( dst );\n\n    return( ret );\n}\n\n/*\n * Free the components of an RSA key\n */\nvoid mbedtls_rsa_free( mbedtls_rsa_context *ctx )\n{\n    mbedtls_mpi_free( &ctx->Vi ); mbedtls_mpi_free( &ctx->Vf );\n    mbedtls_mpi_free( &ctx->RN ); mbedtls_mpi_free( &ctx->D  );\n    mbedtls_mpi_free( &ctx->Q  ); mbedtls_mpi_free( &ctx->P  );\n    mbedtls_mpi_free( &ctx->E  ); mbedtls_mpi_free( &ctx->N  );\n\n#if !defined(MBEDTLS_RSA_NO_CRT)\n    mbedtls_mpi_free( &ctx->RQ ); mbedtls_mpi_free( &ctx->RP );\n    mbedtls_mpi_free( &ctx->QP ); mbedtls_mpi_free( &ctx->DQ );\n    mbedtls_mpi_free( &ctx->DP );\n#endif /* MBEDTLS_RSA_NO_CRT */\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_mutex_free( &ctx->mutex );\n#endif\n}\n\n#endif /* !MBEDTLS_RSA_ALT */\n\n#if defined(MBEDTLS_SELF_TEST)\n\n#include \"mbedtls/sha1.h\"\n\n/*\n * Example RSA-1024 keypair, for test purposes\n */\n#define KEY_LEN 128\n\n#define RSA_N   \"9292758453063D803DD603D5E777D788\" \\\n                \"8ED1D5BF35786190FA2F23EBC0848AEA\" \\\n                \"DDA92CA6C3D80B32C4D109BE0F36D6AE\" \\\n                \"7130B9CED7ACDF54CFC7555AC14EEBAB\" \\\n                \"93A89813FBF3C4F8066D2D800F7C38A8\" \\\n                \"1AE31942917403FF4946B0A83D3D3E05\" \\\n                \"EE57C6F5F5606FB5D4BC6CD34EE0801A\" \\\n                \"5E94BB77B07507233A0BC7BAC8F90F79\"\n\n#define RSA_E   \"10001\"\n\n#define RSA_D   \"24BF6185468786FDD303083D25E64EFC\" \\\n                \"66CA472BC44D253102F8B4A9D3BFA750\" \\\n                \"91386C0077937FE33FA3252D28855837\" \\\n                \"AE1B484A8A9A45F7EE8C0C634F99E8CD\" \\\n                \"DF79C5CE07EE72C7F123142198164234\" \\\n                \"CABB724CF78B8173B9F880FC86322407\" \\\n                \"AF1FEDFDDE2BEB674CA15F3E81A1521E\" \\\n                \"071513A1E85B5DFA031F21ECAE91A34D\"\n\n#define RSA_P   \"C36D0EB7FCD285223CFB5AABA5BDA3D8\" \\\n                \"2C01CAD19EA484A87EA4377637E75500\" \\\n                \"FCB2005C5C7DD6EC4AC023CDA285D796\" \\\n                \"C3D9E75E1EFC42488BB4F1D13AC30A57\"\n\n#define RSA_Q   \"C000DF51A7C77AE8D7C7370C1FF55B69\" \\\n                \"E211C2B9E5DB1ED0BF61D0D9899620F4\" \\\n                \"910E4168387E3C30AA1E00C339A79508\" \\\n                \"8452DD96A9A5EA5D9DCA68DA636032AF\"\n\n#define PT_LEN  24\n#define RSA_PT  \"\\xAA\\xBB\\xCC\\x03\\x02\\x01\\x00\\xFF\\xFF\\xFF\\xFF\\xFF\" \\\n                \"\\x11\\x22\\x33\\x0A\\x0B\\x0C\\xCC\\xDD\\xDD\\xDD\\xDD\\xDD\"\n\n#if defined(MBEDTLS_PKCS1_V15)\nstatic int myrand( void *rng_state, unsigned char *output, size_t len )\n{\n#if !defined(__OpenBSD__)\n    size_t i;\n\n    if( rng_state != NULL )\n        rng_state  = NULL;\n\n    for( i = 0; i < len; ++i )\n        output[i] = rand();\n#else\n    if( rng_state != NULL )\n        rng_state = NULL;\n\n    arc4random_buf( output, len );\n#endif /* !OpenBSD */\n\n    return( 0 );\n}\n#endif /* MBEDTLS_PKCS1_V15 */\n\n/*\n * Checkup routine\n */\nint mbedtls_rsa_self_test( int verbose )\n{\n    int ret = 0;\n#if defined(MBEDTLS_PKCS1_V15)\n    size_t len;\n    mbedtls_rsa_context rsa;\n    unsigned char rsa_plaintext[PT_LEN];\n    unsigned char rsa_decrypted[PT_LEN];\n    unsigned char rsa_ciphertext[KEY_LEN];\n#if defined(MBEDTLS_SHA1_C)\n    unsigned char sha1sum[20];\n#endif\n\n    mbedtls_mpi K;\n\n    mbedtls_mpi_init( &K );\n    mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 );\n\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_N  ) );\n    MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, &K, NULL, NULL, NULL, NULL ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_P  ) );\n    MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, &K, NULL, NULL, NULL ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_Q  ) );\n    MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, &K, NULL, NULL ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_D  ) );\n    MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, NULL, &K, NULL ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_E  ) );\n    MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, NULL, NULL, &K ) );\n\n    MBEDTLS_MPI_CHK( mbedtls_rsa_complete( &rsa ) );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  RSA key validation: \" );\n\n    if( mbedtls_rsa_check_pubkey(  &rsa ) != 0 ||\n        mbedtls_rsa_check_privkey( &rsa ) != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        ret = 1;\n        goto cleanup;\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n  PKCS#1 encryption : \" );\n\n    memcpy( rsa_plaintext, RSA_PT, PT_LEN );\n\n    if( mbedtls_rsa_pkcs1_encrypt( &rsa, myrand, NULL, MBEDTLS_RSA_PUBLIC,\n                                   PT_LEN, rsa_plaintext,\n                                   rsa_ciphertext ) != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        ret = 1;\n        goto cleanup;\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n  PKCS#1 decryption : \" );\n\n    if( mbedtls_rsa_pkcs1_decrypt( &rsa, myrand, NULL, MBEDTLS_RSA_PRIVATE,\n                                   &len, rsa_ciphertext, rsa_decrypted,\n                                   sizeof(rsa_decrypted) ) != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        ret = 1;\n        goto cleanup;\n    }\n\n    if( memcmp( rsa_decrypted, rsa_plaintext, len ) != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        ret = 1;\n        goto cleanup;\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\n#if defined(MBEDTLS_SHA1_C)\n    if( verbose != 0 )\n        mbedtls_printf( \"  PKCS#1 data sign  : \" );\n\n    if( mbedtls_sha1_ret( rsa_plaintext, PT_LEN, sha1sum ) != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        return( 1 );\n    }\n\n    if( mbedtls_rsa_pkcs1_sign( &rsa, myrand, NULL,\n                                MBEDTLS_RSA_PRIVATE, MBEDTLS_MD_SHA1, 0,\n                                sha1sum, rsa_ciphertext ) != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        ret = 1;\n        goto cleanup;\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n  PKCS#1 sig. verify: \" );\n\n    if( mbedtls_rsa_pkcs1_verify( &rsa, NULL, NULL,\n                                  MBEDTLS_RSA_PUBLIC, MBEDTLS_MD_SHA1, 0,\n                                  sha1sum, rsa_ciphertext ) != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        ret = 1;\n        goto cleanup;\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n#endif /* MBEDTLS_SHA1_C */\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\ncleanup:\n    mbedtls_mpi_free( &K );\n    mbedtls_rsa_free( &rsa );\n#else /* MBEDTLS_PKCS1_V15 */\n    ((void) verbose);\n#endif /* MBEDTLS_PKCS1_V15 */\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_RSA_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/rsa_internal.c",
    "content": "/*\n *  Helper functions for the RSA module\n *\n *  Copyright (C) 2006-2017, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n *\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_RSA_C)\n\n#include \"mbedtls/rsa.h\"\n#include \"mbedtls/bignum.h\"\n#include \"mbedtls/rsa_internal.h\"\n\n/*\n * Compute RSA prime factors from public and private exponents\n *\n * Summary of algorithm:\n * Setting F := lcm(P-1,Q-1), the idea is as follows:\n *\n * (a) For any 1 <= X < N with gcd(X,N)=1, we have X^F = 1 modulo N, so X^(F/2)\n *     is a square root of 1 in Z/NZ. Since Z/NZ ~= Z/PZ x Z/QZ by CRT and the\n *     square roots of 1 in Z/PZ and Z/QZ are +1 and -1, this leaves the four\n *     possibilities X^(F/2) = (+-1, +-1). If it happens that X^(F/2) = (-1,+1)\n *     or (+1,-1), then gcd(X^(F/2) + 1, N) will be equal to one of the prime\n *     factors of N.\n *\n * (b) If we don't know F/2 but (F/2) * K for some odd (!) K, then the same\n *     construction still applies since (-)^K is the identity on the set of\n *     roots of 1 in Z/NZ.\n *\n * The public and private key primitives (-)^E and (-)^D are mutually inverse\n * bijections on Z/NZ if and only if (-)^(DE) is the identity on Z/NZ, i.e.\n * if and only if DE - 1 is a multiple of F, say DE - 1 = F * L.\n * Splitting L = 2^t * K with K odd, we have\n *\n *   DE - 1 = FL = (F/2) * (2^(t+1)) * K,\n *\n * so (F / 2) * K is among the numbers\n *\n *   (DE - 1) >> 1, (DE - 1) >> 2, ..., (DE - 1) >> ord\n *\n * where ord is the order of 2 in (DE - 1).\n * We can therefore iterate through these numbers apply the construction\n * of (a) and (b) above to attempt to factor N.\n *\n */\nint mbedtls_rsa_deduce_primes( mbedtls_mpi const *N,\n                     mbedtls_mpi const *E, mbedtls_mpi const *D,\n                     mbedtls_mpi *P, mbedtls_mpi *Q )\n{\n    int ret = 0;\n\n    uint16_t attempt;  /* Number of current attempt  */\n    uint16_t iter;     /* Number of squares computed in the current attempt */\n\n    uint16_t order;    /* Order of 2 in DE - 1 */\n\n    mbedtls_mpi T;  /* Holds largest odd divisor of DE - 1     */\n    mbedtls_mpi K;  /* Temporary holding the current candidate */\n\n    const unsigned char primes[] = { 2,\n           3,    5,    7,   11,   13,   17,   19,   23,\n          29,   31,   37,   41,   43,   47,   53,   59,\n          61,   67,   71,   73,   79,   83,   89,   97,\n         101,  103,  107,  109,  113,  127,  131,  137,\n         139,  149,  151,  157,  163,  167,  173,  179,\n         181,  191,  193,  197,  199,  211,  223,  227,\n         229,  233,  239,  241,  251\n    };\n\n    const size_t num_primes = sizeof( primes ) / sizeof( *primes );\n\n    if( P == NULL || Q == NULL || P->p != NULL || Q->p != NULL )\n        return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );\n\n    if( mbedtls_mpi_cmp_int( N, 0 ) <= 0 ||\n        mbedtls_mpi_cmp_int( D, 1 ) <= 0 ||\n        mbedtls_mpi_cmp_mpi( D, N ) >= 0 ||\n        mbedtls_mpi_cmp_int( E, 1 ) <= 0 ||\n        mbedtls_mpi_cmp_mpi( E, N ) >= 0 )\n    {\n        return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );\n    }\n\n    /*\n     * Initializations and temporary changes\n     */\n\n    mbedtls_mpi_init( &K );\n    mbedtls_mpi_init( &T );\n\n    /* T := DE - 1 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, D,  E ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &T, &T, 1 ) );\n\n    if( ( order = (uint16_t) mbedtls_mpi_lsb( &T ) ) == 0 )\n    {\n        ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;\n        goto cleanup;\n    }\n\n    /* After this operation, T holds the largest odd divisor of DE - 1. */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &T, order ) );\n\n    /*\n     * Actual work\n     */\n\n    /* Skip trying 2 if N == 1 mod 8 */\n    attempt = 0;\n    if( N->p[0] % 8 == 1 )\n        attempt = 1;\n\n    for( ; attempt < num_primes; ++attempt )\n    {\n        mbedtls_mpi_lset( &K, primes[attempt] );\n\n        /* Check if gcd(K,N) = 1 */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( P, &K, N ) );\n        if( mbedtls_mpi_cmp_int( P, 1 ) != 0 )\n            continue;\n\n        /* Go through K^T + 1, K^(2T) + 1, K^(4T) + 1, ...\n         * and check whether they have nontrivial GCD with N. */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &K, &K, &T, N,\n                             Q /* temporarily use Q for storing Montgomery\n                                * multiplication helper values */ ) );\n\n        for( iter = 1; iter <= order; ++iter )\n        {\n            /* If we reach 1 prematurely, there's no point\n             * in continuing to square K */\n            if( mbedtls_mpi_cmp_int( &K, 1 ) == 0 )\n                break;\n\n            MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &K, &K, 1 ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( P, &K, N ) );\n\n            if( mbedtls_mpi_cmp_int( P, 1 ) ==  1 &&\n                mbedtls_mpi_cmp_mpi( P, N ) == -1 )\n            {\n                /*\n                 * Have found a nontrivial divisor P of N.\n                 * Set Q := N / P.\n                 */\n\n                MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( Q, NULL, N, P ) );\n                goto cleanup;\n            }\n\n            MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, &K, &K ) );\n            MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, N ) );\n        }\n\n        /*\n         * If we get here, then either we prematurely aborted the loop because\n         * we reached 1, or K holds primes[attempt]^(DE - 1) mod N, which must\n         * be 1 if D,E,N were consistent.\n         * Check if that's the case and abort if not, to avoid very long,\n         * yet eventually failing, computations if N,D,E were not sane.\n         */\n        if( mbedtls_mpi_cmp_int( &K, 1 ) != 0 )\n        {\n            break;\n        }\n    }\n\n    ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;\n\ncleanup:\n\n    mbedtls_mpi_free( &K );\n    mbedtls_mpi_free( &T );\n    return( ret );\n}\n\n/*\n * Given P, Q and the public exponent E, deduce D.\n * This is essentially a modular inversion.\n */\nint mbedtls_rsa_deduce_private_exponent( mbedtls_mpi const *P,\n                                         mbedtls_mpi const *Q,\n                                         mbedtls_mpi const *E,\n                                         mbedtls_mpi *D )\n{\n    int ret = 0;\n    mbedtls_mpi K, L;\n\n    if( D == NULL || mbedtls_mpi_cmp_int( D, 0 ) != 0 )\n        return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );\n\n    if( mbedtls_mpi_cmp_int( P, 1 ) <= 0 ||\n        mbedtls_mpi_cmp_int( Q, 1 ) <= 0 ||\n        mbedtls_mpi_cmp_int( E, 0 ) == 0 )\n    {\n        return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );\n    }\n\n    mbedtls_mpi_init( &K );\n    mbedtls_mpi_init( &L );\n\n    /* Temporarily put K := P-1 and L := Q-1 */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, Q, 1 ) );\n\n    /* Temporarily put D := gcd(P-1, Q-1) */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( D, &K, &L ) );\n\n    /* K := LCM(P-1, Q-1) */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, &K, &L ) );\n    MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &K, NULL, &K, D ) );\n\n    /* Compute modular inverse of E in LCM(P-1, Q-1) */\n    MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( D, E, &K ) );\n\ncleanup:\n\n    mbedtls_mpi_free( &K );\n    mbedtls_mpi_free( &L );\n\n    return( ret );\n}\n\n/*\n * Check that RSA CRT parameters are in accordance with core parameters.\n */\nint mbedtls_rsa_validate_crt( const mbedtls_mpi *P,  const mbedtls_mpi *Q,\n                              const mbedtls_mpi *D,  const mbedtls_mpi *DP,\n                              const mbedtls_mpi *DQ, const mbedtls_mpi *QP )\n{\n    int ret = 0;\n\n    mbedtls_mpi K, L;\n    mbedtls_mpi_init( &K );\n    mbedtls_mpi_init( &L );\n\n    /* Check that DP - D == 0 mod P - 1 */\n    if( DP != NULL )\n    {\n        if( P == NULL )\n        {\n            ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;\n            goto cleanup;\n        }\n\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &L, DP, D ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &L, &L, &K ) );\n\n        if( mbedtls_mpi_cmp_int( &L, 0 ) != 0 )\n        {\n            ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;\n            goto cleanup;\n        }\n    }\n\n    /* Check that DQ - D == 0 mod Q - 1 */\n    if( DQ != NULL )\n    {\n        if( Q == NULL )\n        {\n            ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;\n            goto cleanup;\n        }\n\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, Q, 1 ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &L, DQ, D ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &L, &L, &K ) );\n\n        if( mbedtls_mpi_cmp_int( &L, 0 ) != 0 )\n        {\n            ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;\n            goto cleanup;\n        }\n    }\n\n    /* Check that QP * Q - 1 == 0 mod P */\n    if( QP != NULL )\n    {\n        if( P == NULL || Q == NULL )\n        {\n            ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;\n            goto cleanup;\n        }\n\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, QP, Q ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, P ) );\n        if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 )\n        {\n            ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;\n            goto cleanup;\n        }\n    }\n\ncleanup:\n\n    /* Wrap MPI error codes by RSA check failure error code */\n    if( ret != 0 &&\n        ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED &&\n        ret != MBEDTLS_ERR_RSA_BAD_INPUT_DATA )\n    {\n        ret += MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;\n    }\n\n    mbedtls_mpi_free( &K );\n    mbedtls_mpi_free( &L );\n\n    return( ret );\n}\n\n/*\n * Check that core RSA parameters are sane.\n */\nint mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P,\n                                 const mbedtls_mpi *Q, const mbedtls_mpi *D,\n                                 const mbedtls_mpi *E,\n                                 int (*f_rng)(void *, unsigned char *, size_t),\n                                 void *p_rng )\n{\n    int ret = 0;\n    mbedtls_mpi K, L;\n\n    mbedtls_mpi_init( &K );\n    mbedtls_mpi_init( &L );\n\n    /*\n     * Step 1: If PRNG provided, check that P and Q are prime\n     */\n\n#if defined(MBEDTLS_GENPRIME)\n    if( f_rng != NULL && P != NULL &&\n        ( ret = mbedtls_mpi_is_prime( P, f_rng, p_rng ) ) != 0 )\n    {\n        ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;\n        goto cleanup;\n    }\n\n    if( f_rng != NULL && Q != NULL &&\n        ( ret = mbedtls_mpi_is_prime( Q, f_rng, p_rng ) ) != 0 )\n    {\n        ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;\n        goto cleanup;\n    }\n#else\n    ((void) f_rng);\n    ((void) p_rng);\n#endif /* MBEDTLS_GENPRIME */\n\n    /*\n     * Step 2: Check that 1 < N = P * Q\n     */\n\n    if( P != NULL && Q != NULL && N != NULL )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, P, Q ) );\n        if( mbedtls_mpi_cmp_int( N, 1 )  <= 0 ||\n            mbedtls_mpi_cmp_mpi( &K, N ) != 0 )\n        {\n            ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;\n            goto cleanup;\n        }\n    }\n\n    /*\n     * Step 3: Check and 1 < D, E < N if present.\n     */\n\n    if( N != NULL && D != NULL && E != NULL )\n    {\n        if ( mbedtls_mpi_cmp_int( D, 1 ) <= 0 ||\n             mbedtls_mpi_cmp_int( E, 1 ) <= 0 ||\n             mbedtls_mpi_cmp_mpi( D, N ) >= 0 ||\n             mbedtls_mpi_cmp_mpi( E, N ) >= 0 )\n        {\n            ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;\n            goto cleanup;\n        }\n    }\n\n    /*\n     * Step 4: Check that D, E are inverse modulo P-1 and Q-1\n     */\n\n    if( P != NULL && Q != NULL && D != NULL && E != NULL )\n    {\n        if( mbedtls_mpi_cmp_int( P, 1 ) <= 0 ||\n            mbedtls_mpi_cmp_int( Q, 1 ) <= 0 )\n        {\n            ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;\n            goto cleanup;\n        }\n\n        /* Compute DE-1 mod P-1 */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, D, E ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, P, 1 ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, &L ) );\n        if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 )\n        {\n            ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;\n            goto cleanup;\n        }\n\n        /* Compute DE-1 mod Q-1 */\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, D, E ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, Q, 1 ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, &L ) );\n        if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 )\n        {\n            ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;\n            goto cleanup;\n        }\n    }\n\ncleanup:\n\n    mbedtls_mpi_free( &K );\n    mbedtls_mpi_free( &L );\n\n    /* Wrap MPI error codes by RSA check failure error code */\n    if( ret != 0 && ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED )\n    {\n        ret += MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;\n    }\n\n    return( ret );\n}\n\nint mbedtls_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,\n                            const mbedtls_mpi *D, mbedtls_mpi *DP,\n                            mbedtls_mpi *DQ, mbedtls_mpi *QP )\n{\n    int ret = 0;\n    mbedtls_mpi K;\n    mbedtls_mpi_init( &K );\n\n    /* DP = D mod P-1 */\n    if( DP != NULL )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1  ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( DP, D, &K ) );\n    }\n\n    /* DQ = D mod Q-1 */\n    if( DQ != NULL )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, Q, 1  ) );\n        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( DQ, D, &K ) );\n    }\n\n    /* QP = Q^{-1} mod P */\n    if( QP != NULL )\n    {\n        MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( QP, Q, P ) );\n    }\n\ncleanup:\n    mbedtls_mpi_free( &K );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_RSA_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/sha1.c",
    "content": "/*\n *  FIPS-180-1 compliant SHA-1 implementation\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The SHA-1 standard was published by NIST in 1993.\n *\n *  http://www.itl.nist.gov/fipspubs/fip180-1.htm\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_SHA1_C)\n\n#include \"mbedtls/sha1.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if !defined(MBEDTLS_SHA1_ALT)\n\n/*\n * 32-bit integer manipulation macros (big endian)\n */\n#ifndef GET_UINT32_BE\n#define GET_UINT32_BE(n,b,i)                            \\\n{                                                       \\\n    (n) = ( (uint32_t) (b)[(i)    ] << 24 )             \\\n        | ( (uint32_t) (b)[(i) + 1] << 16 )             \\\n        | ( (uint32_t) (b)[(i) + 2] <<  8 )             \\\n        | ( (uint32_t) (b)[(i) + 3]       );            \\\n}\n#endif\n\n#ifndef PUT_UINT32_BE\n#define PUT_UINT32_BE(n,b,i)                            \\\n{                                                       \\\n    (b)[(i)    ] = (unsigned char) ( (n) >> 24 );       \\\n    (b)[(i) + 1] = (unsigned char) ( (n) >> 16 );       \\\n    (b)[(i) + 2] = (unsigned char) ( (n) >>  8 );       \\\n    (b)[(i) + 3] = (unsigned char) ( (n)       );       \\\n}\n#endif\n\nvoid mbedtls_sha1_init( mbedtls_sha1_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_sha1_context ) );\n}\n\nvoid mbedtls_sha1_free( mbedtls_sha1_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha1_context ) );\n}\n\nvoid mbedtls_sha1_clone( mbedtls_sha1_context *dst,\n                         const mbedtls_sha1_context *src )\n{\n    *dst = *src;\n}\n\n/*\n * SHA-1 context setup\n */\nint mbedtls_sha1_starts_ret( mbedtls_sha1_context *ctx )\n{\n    ctx->total[0] = 0;\n    ctx->total[1] = 0;\n\n    ctx->state[0] = 0x67452301;\n    ctx->state[1] = 0xEFCDAB89;\n    ctx->state[2] = 0x98BADCFE;\n    ctx->state[3] = 0x10325476;\n    ctx->state[4] = 0xC3D2E1F0;\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_sha1_starts( mbedtls_sha1_context *ctx )\n{\n    mbedtls_sha1_starts_ret( ctx );\n}\n#endif\n\n#if !defined(MBEDTLS_SHA1_PROCESS_ALT)\nint mbedtls_internal_sha1_process( mbedtls_sha1_context *ctx,\n                                   const unsigned char data[64] )\n{\n    uint32_t temp, W[16], A, B, C, D, E;\n\n    GET_UINT32_BE( W[ 0], data,  0 );\n    GET_UINT32_BE( W[ 1], data,  4 );\n    GET_UINT32_BE( W[ 2], data,  8 );\n    GET_UINT32_BE( W[ 3], data, 12 );\n    GET_UINT32_BE( W[ 4], data, 16 );\n    GET_UINT32_BE( W[ 5], data, 20 );\n    GET_UINT32_BE( W[ 6], data, 24 );\n    GET_UINT32_BE( W[ 7], data, 28 );\n    GET_UINT32_BE( W[ 8], data, 32 );\n    GET_UINT32_BE( W[ 9], data, 36 );\n    GET_UINT32_BE( W[10], data, 40 );\n    GET_UINT32_BE( W[11], data, 44 );\n    GET_UINT32_BE( W[12], data, 48 );\n    GET_UINT32_BE( W[13], data, 52 );\n    GET_UINT32_BE( W[14], data, 56 );\n    GET_UINT32_BE( W[15], data, 60 );\n\n#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n)))\n\n#define R(t)                                            \\\n(                                                       \\\n    temp = W[( t -  3 ) & 0x0F] ^ W[( t - 8 ) & 0x0F] ^ \\\n           W[( t - 14 ) & 0x0F] ^ W[  t       & 0x0F],  \\\n    ( W[t & 0x0F] = S(temp,1) )                         \\\n)\n\n#define P(a,b,c,d,e,x)                                  \\\n{                                                       \\\n    e += S(a,5) + F(b,c,d) + K + x; b = S(b,30);        \\\n}\n\n    A = ctx->state[0];\n    B = ctx->state[1];\n    C = ctx->state[2];\n    D = ctx->state[3];\n    E = ctx->state[4];\n\n#define F(x,y,z) (z ^ (x & (y ^ z)))\n#define K 0x5A827999\n\n    P( A, B, C, D, E, W[0]  );\n    P( E, A, B, C, D, W[1]  );\n    P( D, E, A, B, C, W[2]  );\n    P( C, D, E, A, B, W[3]  );\n    P( B, C, D, E, A, W[4]  );\n    P( A, B, C, D, E, W[5]  );\n    P( E, A, B, C, D, W[6]  );\n    P( D, E, A, B, C, W[7]  );\n    P( C, D, E, A, B, W[8]  );\n    P( B, C, D, E, A, W[9]  );\n    P( A, B, C, D, E, W[10] );\n    P( E, A, B, C, D, W[11] );\n    P( D, E, A, B, C, W[12] );\n    P( C, D, E, A, B, W[13] );\n    P( B, C, D, E, A, W[14] );\n    P( A, B, C, D, E, W[15] );\n    P( E, A, B, C, D, R(16) );\n    P( D, E, A, B, C, R(17) );\n    P( C, D, E, A, B, R(18) );\n    P( B, C, D, E, A, R(19) );\n\n#undef K\n#undef F\n\n#define F(x,y,z) (x ^ y ^ z)\n#define K 0x6ED9EBA1\n\n    P( A, B, C, D, E, R(20) );\n    P( E, A, B, C, D, R(21) );\n    P( D, E, A, B, C, R(22) );\n    P( C, D, E, A, B, R(23) );\n    P( B, C, D, E, A, R(24) );\n    P( A, B, C, D, E, R(25) );\n    P( E, A, B, C, D, R(26) );\n    P( D, E, A, B, C, R(27) );\n    P( C, D, E, A, B, R(28) );\n    P( B, C, D, E, A, R(29) );\n    P( A, B, C, D, E, R(30) );\n    P( E, A, B, C, D, R(31) );\n    P( D, E, A, B, C, R(32) );\n    P( C, D, E, A, B, R(33) );\n    P( B, C, D, E, A, R(34) );\n    P( A, B, C, D, E, R(35) );\n    P( E, A, B, C, D, R(36) );\n    P( D, E, A, B, C, R(37) );\n    P( C, D, E, A, B, R(38) );\n    P( B, C, D, E, A, R(39) );\n\n#undef K\n#undef F\n\n#define F(x,y,z) ((x & y) | (z & (x | y)))\n#define K 0x8F1BBCDC\n\n    P( A, B, C, D, E, R(40) );\n    P( E, A, B, C, D, R(41) );\n    P( D, E, A, B, C, R(42) );\n    P( C, D, E, A, B, R(43) );\n    P( B, C, D, E, A, R(44) );\n    P( A, B, C, D, E, R(45) );\n    P( E, A, B, C, D, R(46) );\n    P( D, E, A, B, C, R(47) );\n    P( C, D, E, A, B, R(48) );\n    P( B, C, D, E, A, R(49) );\n    P( A, B, C, D, E, R(50) );\n    P( E, A, B, C, D, R(51) );\n    P( D, E, A, B, C, R(52) );\n    P( C, D, E, A, B, R(53) );\n    P( B, C, D, E, A, R(54) );\n    P( A, B, C, D, E, R(55) );\n    P( E, A, B, C, D, R(56) );\n    P( D, E, A, B, C, R(57) );\n    P( C, D, E, A, B, R(58) );\n    P( B, C, D, E, A, R(59) );\n\n#undef K\n#undef F\n\n#define F(x,y,z) (x ^ y ^ z)\n#define K 0xCA62C1D6\n\n    P( A, B, C, D, E, R(60) );\n    P( E, A, B, C, D, R(61) );\n    P( D, E, A, B, C, R(62) );\n    P( C, D, E, A, B, R(63) );\n    P( B, C, D, E, A, R(64) );\n    P( A, B, C, D, E, R(65) );\n    P( E, A, B, C, D, R(66) );\n    P( D, E, A, B, C, R(67) );\n    P( C, D, E, A, B, R(68) );\n    P( B, C, D, E, A, R(69) );\n    P( A, B, C, D, E, R(70) );\n    P( E, A, B, C, D, R(71) );\n    P( D, E, A, B, C, R(72) );\n    P( C, D, E, A, B, R(73) );\n    P( B, C, D, E, A, R(74) );\n    P( A, B, C, D, E, R(75) );\n    P( E, A, B, C, D, R(76) );\n    P( D, E, A, B, C, R(77) );\n    P( C, D, E, A, B, R(78) );\n    P( B, C, D, E, A, R(79) );\n\n#undef K\n#undef F\n\n    ctx->state[0] += A;\n    ctx->state[1] += B;\n    ctx->state[2] += C;\n    ctx->state[3] += D;\n    ctx->state[4] += E;\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_sha1_process( mbedtls_sha1_context *ctx,\n                           const unsigned char data[64] )\n{\n    mbedtls_internal_sha1_process( ctx, data );\n}\n#endif\n#endif /* !MBEDTLS_SHA1_PROCESS_ALT */\n\n/*\n * SHA-1 process buffer\n */\nint mbedtls_sha1_update_ret( mbedtls_sha1_context *ctx,\n                             const unsigned char *input,\n                             size_t ilen )\n{\n    int ret;\n    size_t fill;\n    uint32_t left;\n\n    if( ilen == 0 )\n        return( 0 );\n\n    left = ctx->total[0] & 0x3F;\n    fill = 64 - left;\n\n    ctx->total[0] += (uint32_t) ilen;\n    ctx->total[0] &= 0xFFFFFFFF;\n\n    if( ctx->total[0] < (uint32_t) ilen )\n        ctx->total[1]++;\n\n    if( left && ilen >= fill )\n    {\n        memcpy( (void *) (ctx->buffer + left), input, fill );\n\n        if( ( ret = mbedtls_internal_sha1_process( ctx, ctx->buffer ) ) != 0 )\n            return( ret );\n\n        input += fill;\n        ilen  -= fill;\n        left = 0;\n    }\n\n    while( ilen >= 64 )\n    {\n        if( ( ret = mbedtls_internal_sha1_process( ctx, input ) ) != 0 )\n            return( ret );\n\n        input += 64;\n        ilen  -= 64;\n    }\n\n    if( ilen > 0 )\n        memcpy( (void *) (ctx->buffer + left), input, ilen );\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_sha1_update( mbedtls_sha1_context *ctx,\n                          const unsigned char *input,\n                          size_t ilen )\n{\n    mbedtls_sha1_update_ret( ctx, input, ilen );\n}\n#endif\n\n/*\n * SHA-1 final digest\n */\nint mbedtls_sha1_finish_ret( mbedtls_sha1_context *ctx,\n                             unsigned char output[20] )\n{\n    int ret;\n    uint32_t used;\n    uint32_t high, low;\n\n    /*\n     * Add padding: 0x80 then 0x00 until 8 bytes remain for the length\n     */\n    used = ctx->total[0] & 0x3F;\n\n    ctx->buffer[used++] = 0x80;\n\n    if( used <= 56 )\n    {\n        /* Enough room for padding + length in current block */\n        memset( ctx->buffer + used, 0, 56 - used );\n    }\n    else\n    {\n        /* We'll need an extra block */\n        memset( ctx->buffer + used, 0, 64 - used );\n\n        if( ( ret = mbedtls_internal_sha1_process( ctx, ctx->buffer ) ) != 0 )\n            return( ret );\n\n        memset( ctx->buffer, 0, 56 );\n    }\n\n    /*\n     * Add message length\n     */\n    high = ( ctx->total[0] >> 29 )\n         | ( ctx->total[1] <<  3 );\n    low  = ( ctx->total[0] <<  3 );\n\n    PUT_UINT32_BE( high, ctx->buffer, 56 );\n    PUT_UINT32_BE( low,  ctx->buffer, 60 );\n\n    if( ( ret = mbedtls_internal_sha1_process( ctx, ctx->buffer ) ) != 0 )\n        return( ret );\n\n    /*\n     * Output final state\n     */\n    PUT_UINT32_BE( ctx->state[0], output,  0 );\n    PUT_UINT32_BE( ctx->state[1], output,  4 );\n    PUT_UINT32_BE( ctx->state[2], output,  8 );\n    PUT_UINT32_BE( ctx->state[3], output, 12 );\n    PUT_UINT32_BE( ctx->state[4], output, 16 );\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_sha1_finish( mbedtls_sha1_context *ctx,\n                          unsigned char output[20] )\n{\n    mbedtls_sha1_finish_ret( ctx, output );\n}\n#endif\n\n#endif /* !MBEDTLS_SHA1_ALT */\n\n/*\n * output = SHA-1( input buffer )\n */\nint mbedtls_sha1_ret( const unsigned char *input,\n                      size_t ilen,\n                      unsigned char output[20] )\n{\n    int ret;\n    mbedtls_sha1_context ctx;\n\n    mbedtls_sha1_init( &ctx );\n\n    if( ( ret = mbedtls_sha1_starts_ret( &ctx ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_sha1_update_ret( &ctx, input, ilen ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_sha1_finish_ret( &ctx, output ) ) != 0 )\n        goto exit;\n\nexit:\n    mbedtls_sha1_free( &ctx );\n\n    return( ret );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_sha1( const unsigned char *input,\n                   size_t ilen,\n                   unsigned char output[20] )\n{\n    mbedtls_sha1_ret( input, ilen, output );\n}\n#endif\n\n#if defined(MBEDTLS_SELF_TEST)\n/*\n * FIPS-180-1 test vectors\n */\nstatic const unsigned char sha1_test_buf[3][57] =\n{\n    { \"abc\" },\n    { \"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq\" },\n    { \"\" }\n};\n\nstatic const size_t sha1_test_buflen[3] =\n{\n    3, 56, 1000\n};\n\nstatic const unsigned char sha1_test_sum[3][20] =\n{\n    { 0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E,\n      0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D },\n    { 0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E, 0xBA, 0xAE,\n      0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5, 0xE5, 0x46, 0x70, 0xF1 },\n    { 0x34, 0xAA, 0x97, 0x3C, 0xD4, 0xC4, 0xDA, 0xA4, 0xF6, 0x1E,\n      0xEB, 0x2B, 0xDB, 0xAD, 0x27, 0x31, 0x65, 0x34, 0x01, 0x6F }\n};\n\n/*\n * Checkup routine\n */\nint mbedtls_sha1_self_test( int verbose )\n{\n    int i, j, buflen, ret = 0;\n    unsigned char buf[1024];\n    unsigned char sha1sum[20];\n    mbedtls_sha1_context ctx;\n\n    mbedtls_sha1_init( &ctx );\n\n    /*\n     * SHA-1\n     */\n    for( i = 0; i < 3; i++ )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"  SHA-1 test #%d: \", i + 1 );\n\n        if( ( ret = mbedtls_sha1_starts_ret( &ctx ) ) != 0 )\n            goto fail;\n\n        if( i == 2 )\n        {\n            memset( buf, 'a', buflen = 1000 );\n\n            for( j = 0; j < 1000; j++ )\n            {\n                ret = mbedtls_sha1_update_ret( &ctx, buf, buflen );\n                if( ret != 0 )\n                    goto fail;\n            }\n        }\n        else\n        {\n            ret = mbedtls_sha1_update_ret( &ctx, sha1_test_buf[i],\n                                           sha1_test_buflen[i] );\n            if( ret != 0 )\n                goto fail;\n        }\n\n        if( ( ret = mbedtls_sha1_finish_ret( &ctx, sha1sum ) ) != 0 )\n            goto fail;\n\n        if( memcmp( sha1sum, sha1_test_sum[i], 20 ) != 0 )\n        {\n            ret = 1;\n            goto fail;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    goto exit;\n\nfail:\n    if( verbose != 0 )\n        mbedtls_printf( \"failed\\n\" );\n\nexit:\n    mbedtls_sha1_free( &ctx );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_SHA1_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/sha256.c",
    "content": "/*\n *  FIPS-180-2 compliant SHA-256 implementation\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The SHA-256 Secure Hash Standard was published by NIST in 2002.\n *\n *  http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_SHA256_C)\n\n#include \"mbedtls/sha256.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#include <stdlib.h>\n#define mbedtls_printf printf\n#define mbedtls_calloc    calloc\n#define mbedtls_free       free\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if !defined(MBEDTLS_SHA256_ALT)\n\n/*\n * 32-bit integer manipulation macros (big endian)\n */\n#ifndef GET_UINT32_BE\n#define GET_UINT32_BE(n,b,i)                            \\\ndo {                                                    \\\n    (n) = ( (uint32_t) (b)[(i)    ] << 24 )             \\\n        | ( (uint32_t) (b)[(i) + 1] << 16 )             \\\n        | ( (uint32_t) (b)[(i) + 2] <<  8 )             \\\n        | ( (uint32_t) (b)[(i) + 3]       );            \\\n} while( 0 )\n#endif\n\n#ifndef PUT_UINT32_BE\n#define PUT_UINT32_BE(n,b,i)                            \\\ndo {                                                    \\\n    (b)[(i)    ] = (unsigned char) ( (n) >> 24 );       \\\n    (b)[(i) + 1] = (unsigned char) ( (n) >> 16 );       \\\n    (b)[(i) + 2] = (unsigned char) ( (n) >>  8 );       \\\n    (b)[(i) + 3] = (unsigned char) ( (n)       );       \\\n} while( 0 )\n#endif\n\nvoid mbedtls_sha256_init( mbedtls_sha256_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_sha256_context ) );\n}\n\nvoid mbedtls_sha256_free( mbedtls_sha256_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha256_context ) );\n}\n\nvoid mbedtls_sha256_clone( mbedtls_sha256_context *dst,\n                           const mbedtls_sha256_context *src )\n{\n    *dst = *src;\n}\n\n/*\n * SHA-256 context setup\n */\nint mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 )\n{\n    ctx->total[0] = 0;\n    ctx->total[1] = 0;\n\n    if( is224 == 0 )\n    {\n        /* SHA-256 */\n        ctx->state[0] = 0x6A09E667;\n        ctx->state[1] = 0xBB67AE85;\n        ctx->state[2] = 0x3C6EF372;\n        ctx->state[3] = 0xA54FF53A;\n        ctx->state[4] = 0x510E527F;\n        ctx->state[5] = 0x9B05688C;\n        ctx->state[6] = 0x1F83D9AB;\n        ctx->state[7] = 0x5BE0CD19;\n    }\n    else\n    {\n        /* SHA-224 */\n        ctx->state[0] = 0xC1059ED8;\n        ctx->state[1] = 0x367CD507;\n        ctx->state[2] = 0x3070DD17;\n        ctx->state[3] = 0xF70E5939;\n        ctx->state[4] = 0xFFC00B31;\n        ctx->state[5] = 0x68581511;\n        ctx->state[6] = 0x64F98FA7;\n        ctx->state[7] = 0xBEFA4FA4;\n    }\n\n    ctx->is224 = is224;\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_sha256_starts( mbedtls_sha256_context *ctx,\n                            int is224 )\n{\n    mbedtls_sha256_starts_ret( ctx, is224 );\n}\n#endif\n\n#if !defined(MBEDTLS_SHA256_PROCESS_ALT)\nstatic const uint32_t K[] =\n{\n    0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,\n    0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,\n    0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,\n    0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,\n    0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,\n    0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,\n    0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,\n    0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,\n    0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,\n    0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,\n    0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,\n    0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,\n    0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,\n    0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,\n    0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,\n    0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2,\n};\n\n#define  SHR(x,n) ((x & 0xFFFFFFFF) >> n)\n#define ROTR(x,n) (SHR(x,n) | (x << (32 - n)))\n\n#define S0(x) (ROTR(x, 7) ^ ROTR(x,18) ^  SHR(x, 3))\n#define S1(x) (ROTR(x,17) ^ ROTR(x,19) ^  SHR(x,10))\n\n#define S2(x) (ROTR(x, 2) ^ ROTR(x,13) ^ ROTR(x,22))\n#define S3(x) (ROTR(x, 6) ^ ROTR(x,11) ^ ROTR(x,25))\n\n#define F0(x,y,z) ((x & y) | (z & (x | y)))\n#define F1(x,y,z) (z ^ (x & (y ^ z)))\n\n#define R(t)                                    \\\n(                                               \\\n    W[t] = S1(W[t -  2]) + W[t -  7] +          \\\n           S0(W[t - 15]) + W[t - 16]            \\\n)\n\n#define P(a,b,c,d,e,f,g,h,x,K)                  \\\n{                                               \\\n    temp1 = h + S3(e) + F1(e,f,g) + K + x;      \\\n    temp2 = S2(a) + F0(a,b,c);                  \\\n    d += temp1; h = temp1 + temp2;              \\\n}\n\nint mbedtls_internal_sha256_process( mbedtls_sha256_context *ctx,\n                                const unsigned char data[64] )\n{\n    uint32_t temp1, temp2, W[64];\n    uint32_t A[8];\n    unsigned int i;\n\n    for( i = 0; i < 8; i++ )\n        A[i] = ctx->state[i];\n\n#if defined(MBEDTLS_SHA256_SMALLER)\n    for( i = 0; i < 64; i++ )\n    {\n        if( i < 16 )\n            GET_UINT32_BE( W[i], data, 4 * i );\n        else\n            R( i );\n\n        P( A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], W[i], K[i] );\n\n        temp1 = A[7]; A[7] = A[6]; A[6] = A[5]; A[5] = A[4]; A[4] = A[3];\n        A[3] = A[2]; A[2] = A[1]; A[1] = A[0]; A[0] = temp1;\n    }\n#else /* MBEDTLS_SHA256_SMALLER */\n    for( i = 0; i < 16; i++ )\n        GET_UINT32_BE( W[i], data, 4 * i );\n\n    for( i = 0; i < 16; i += 8 )\n    {\n        P( A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], W[i+0], K[i+0] );\n        P( A[7], A[0], A[1], A[2], A[3], A[4], A[5], A[6], W[i+1], K[i+1] );\n        P( A[6], A[7], A[0], A[1], A[2], A[3], A[4], A[5], W[i+2], K[i+2] );\n        P( A[5], A[6], A[7], A[0], A[1], A[2], A[3], A[4], W[i+3], K[i+3] );\n        P( A[4], A[5], A[6], A[7], A[0], A[1], A[2], A[3], W[i+4], K[i+4] );\n        P( A[3], A[4], A[5], A[6], A[7], A[0], A[1], A[2], W[i+5], K[i+5] );\n        P( A[2], A[3], A[4], A[5], A[6], A[7], A[0], A[1], W[i+6], K[i+6] );\n        P( A[1], A[2], A[3], A[4], A[5], A[6], A[7], A[0], W[i+7], K[i+7] );\n    }\n\n    for( i = 16; i < 64; i += 8 )\n    {\n        P( A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], R(i+0), K[i+0] );\n        P( A[7], A[0], A[1], A[2], A[3], A[4], A[5], A[6], R(i+1), K[i+1] );\n        P( A[6], A[7], A[0], A[1], A[2], A[3], A[4], A[5], R(i+2), K[i+2] );\n        P( A[5], A[6], A[7], A[0], A[1], A[2], A[3], A[4], R(i+3), K[i+3] );\n        P( A[4], A[5], A[6], A[7], A[0], A[1], A[2], A[3], R(i+4), K[i+4] );\n        P( A[3], A[4], A[5], A[6], A[7], A[0], A[1], A[2], R(i+5), K[i+5] );\n        P( A[2], A[3], A[4], A[5], A[6], A[7], A[0], A[1], R(i+6), K[i+6] );\n        P( A[1], A[2], A[3], A[4], A[5], A[6], A[7], A[0], R(i+7), K[i+7] );\n    }\n#endif /* MBEDTLS_SHA256_SMALLER */\n\n    for( i = 0; i < 8; i++ )\n        ctx->state[i] += A[i];\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_sha256_process( mbedtls_sha256_context *ctx,\n                             const unsigned char data[64] )\n{\n    mbedtls_internal_sha256_process( ctx, data );\n}\n#endif\n#endif /* !MBEDTLS_SHA256_PROCESS_ALT */\n\n/*\n * SHA-256 process buffer\n */\nint mbedtls_sha256_update_ret( mbedtls_sha256_context *ctx,\n                               const unsigned char *input,\n                               size_t ilen )\n{\n    int ret;\n    size_t fill;\n    uint32_t left;\n\n    if( ilen == 0 )\n        return( 0 );\n\n    left = ctx->total[0] & 0x3F;\n    fill = 64 - left;\n\n    ctx->total[0] += (uint32_t) ilen;\n    ctx->total[0] &= 0xFFFFFFFF;\n\n    if( ctx->total[0] < (uint32_t) ilen )\n        ctx->total[1]++;\n\n    if( left && ilen >= fill )\n    {\n        memcpy( (void *) (ctx->buffer + left), input, fill );\n\n        if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 )\n            return( ret );\n\n        input += fill;\n        ilen  -= fill;\n        left = 0;\n    }\n\n    while( ilen >= 64 )\n    {\n        if( ( ret = mbedtls_internal_sha256_process( ctx, input ) ) != 0 )\n            return( ret );\n\n        input += 64;\n        ilen  -= 64;\n    }\n\n    if( ilen > 0 )\n        memcpy( (void *) (ctx->buffer + left), input, ilen );\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_sha256_update( mbedtls_sha256_context *ctx,\n                            const unsigned char *input,\n                            size_t ilen )\n{\n    mbedtls_sha256_update_ret( ctx, input, ilen );\n}\n#endif\n\n/*\n * SHA-256 final digest\n */\nint mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx,\n                               unsigned char output[32] )\n{\n    int ret;\n    uint32_t used;\n    uint32_t high, low;\n\n    /*\n     * Add padding: 0x80 then 0x00 until 8 bytes remain for the length\n     */\n    used = ctx->total[0] & 0x3F;\n\n    ctx->buffer[used++] = 0x80;\n\n    if( used <= 56 )\n    {\n        /* Enough room for padding + length in current block */\n        memset( ctx->buffer + used, 0, 56 - used );\n    }\n    else\n    {\n        /* We'll need an extra block */\n        memset( ctx->buffer + used, 0, 64 - used );\n\n        if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 )\n            return( ret );\n\n        memset( ctx->buffer, 0, 56 );\n    }\n\n    /*\n     * Add message length\n     */\n    high = ( ctx->total[0] >> 29 )\n         | ( ctx->total[1] <<  3 );\n    low  = ( ctx->total[0] <<  3 );\n\n    PUT_UINT32_BE( high, ctx->buffer, 56 );\n    PUT_UINT32_BE( low,  ctx->buffer, 60 );\n\n    if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 )\n        return( ret );\n\n    /*\n     * Output final state\n     */\n    PUT_UINT32_BE( ctx->state[0], output,  0 );\n    PUT_UINT32_BE( ctx->state[1], output,  4 );\n    PUT_UINT32_BE( ctx->state[2], output,  8 );\n    PUT_UINT32_BE( ctx->state[3], output, 12 );\n    PUT_UINT32_BE( ctx->state[4], output, 16 );\n    PUT_UINT32_BE( ctx->state[5], output, 20 );\n    PUT_UINT32_BE( ctx->state[6], output, 24 );\n\n    if( ctx->is224 == 0 )\n        PUT_UINT32_BE( ctx->state[7], output, 28 );\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_sha256_finish( mbedtls_sha256_context *ctx,\n                            unsigned char output[32] )\n{\n    mbedtls_sha256_finish_ret( ctx, output );\n}\n#endif\n\n#endif /* !MBEDTLS_SHA256_ALT */\n\n/*\n * output = SHA-256( input buffer )\n */\nint mbedtls_sha256_ret( const unsigned char *input,\n                        size_t ilen,\n                        unsigned char output[32],\n                        int is224 )\n{\n    int ret;\n    mbedtls_sha256_context ctx;\n\n    mbedtls_sha256_init( &ctx );\n\n    if( ( ret = mbedtls_sha256_starts_ret( &ctx, is224 ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_sha256_update_ret( &ctx, input, ilen ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_sha256_finish_ret( &ctx, output ) ) != 0 )\n        goto exit;\n\nexit:\n    mbedtls_sha256_free( &ctx );\n\n    return( ret );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_sha256( const unsigned char *input,\n                     size_t ilen,\n                     unsigned char output[32],\n                     int is224 )\n{\n    mbedtls_sha256_ret( input, ilen, output, is224 );\n}\n#endif\n\n#if defined(MBEDTLS_SELF_TEST)\n/*\n * FIPS-180-2 test vectors\n */\nstatic const unsigned char sha256_test_buf[3][57] =\n{\n    { \"abc\" },\n    { \"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq\" },\n    { \"\" }\n};\n\nstatic const size_t sha256_test_buflen[3] =\n{\n    3, 56, 1000\n};\n\nstatic const unsigned char sha256_test_sum[6][32] =\n{\n    /*\n     * SHA-224 test vectors\n     */\n    { 0x23, 0x09, 0x7D, 0x22, 0x34, 0x05, 0xD8, 0x22,\n      0x86, 0x42, 0xA4, 0x77, 0xBD, 0xA2, 0x55, 0xB3,\n      0x2A, 0xAD, 0xBC, 0xE4, 0xBD, 0xA0, 0xB3, 0xF7,\n      0xE3, 0x6C, 0x9D, 0xA7 },\n    { 0x75, 0x38, 0x8B, 0x16, 0x51, 0x27, 0x76, 0xCC,\n      0x5D, 0xBA, 0x5D, 0xA1, 0xFD, 0x89, 0x01, 0x50,\n      0xB0, 0xC6, 0x45, 0x5C, 0xB4, 0xF5, 0x8B, 0x19,\n      0x52, 0x52, 0x25, 0x25 },\n    { 0x20, 0x79, 0x46, 0x55, 0x98, 0x0C, 0x91, 0xD8,\n      0xBB, 0xB4, 0xC1, 0xEA, 0x97, 0x61, 0x8A, 0x4B,\n      0xF0, 0x3F, 0x42, 0x58, 0x19, 0x48, 0xB2, 0xEE,\n      0x4E, 0xE7, 0xAD, 0x67 },\n\n    /*\n     * SHA-256 test vectors\n     */\n    { 0xBA, 0x78, 0x16, 0xBF, 0x8F, 0x01, 0xCF, 0xEA,\n      0x41, 0x41, 0x40, 0xDE, 0x5D, 0xAE, 0x22, 0x23,\n      0xB0, 0x03, 0x61, 0xA3, 0x96, 0x17, 0x7A, 0x9C,\n      0xB4, 0x10, 0xFF, 0x61, 0xF2, 0x00, 0x15, 0xAD },\n    { 0x24, 0x8D, 0x6A, 0x61, 0xD2, 0x06, 0x38, 0xB8,\n      0xE5, 0xC0, 0x26, 0x93, 0x0C, 0x3E, 0x60, 0x39,\n      0xA3, 0x3C, 0xE4, 0x59, 0x64, 0xFF, 0x21, 0x67,\n      0xF6, 0xEC, 0xED, 0xD4, 0x19, 0xDB, 0x06, 0xC1 },\n    { 0xCD, 0xC7, 0x6E, 0x5C, 0x99, 0x14, 0xFB, 0x92,\n      0x81, 0xA1, 0xC7, 0xE2, 0x84, 0xD7, 0x3E, 0x67,\n      0xF1, 0x80, 0x9A, 0x48, 0xA4, 0x97, 0x20, 0x0E,\n      0x04, 0x6D, 0x39, 0xCC, 0xC7, 0x11, 0x2C, 0xD0 }\n};\n\n/*\n * Checkup routine\n */\nint mbedtls_sha256_self_test( int verbose )\n{\n    int i, j, k, buflen, ret = 0;\n    unsigned char *buf;\n    unsigned char sha256sum[32];\n    mbedtls_sha256_context ctx;\n\n    buf = mbedtls_calloc( 1024, sizeof(unsigned char) );\n    if( NULL == buf )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"Buffer allocation failed\\n\" );\n\n        return( 1 );\n    }\n\n    mbedtls_sha256_init( &ctx );\n\n    for( i = 0; i < 6; i++ )\n    {\n        j = i % 3;\n        k = i < 3;\n\n        if( verbose != 0 )\n            mbedtls_printf( \"  SHA-%d test #%d: \", 256 - k * 32, j + 1 );\n\n        if( ( ret = mbedtls_sha256_starts_ret( &ctx, k ) ) != 0 )\n            goto fail;\n\n        if( j == 2 )\n        {\n            memset( buf, 'a', buflen = 1000 );\n\n            for( j = 0; j < 1000; j++ )\n            {\n                ret = mbedtls_sha256_update_ret( &ctx, buf, buflen );\n                if( ret != 0 )\n                    goto fail;\n            }\n\n        }\n        else\n        {\n            ret = mbedtls_sha256_update_ret( &ctx, sha256_test_buf[j],\n                                             sha256_test_buflen[j] );\n            if( ret != 0 )\n                 goto fail;\n        }\n\n        if( ( ret = mbedtls_sha256_finish_ret( &ctx, sha256sum ) ) != 0 )\n            goto fail;\n\n\n        if( memcmp( sha256sum, sha256_test_sum[i], 32 - k * 4 ) != 0 )\n        {\n            ret = 1;\n            goto fail;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    goto exit;\n\nfail:\n    if( verbose != 0 )\n        mbedtls_printf( \"failed\\n\" );\n\nexit:\n    mbedtls_sha256_free( &ctx );\n    mbedtls_free( buf );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_SHA256_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/sha512.c",
    "content": "/*\n *  FIPS-180-2 compliant SHA-384/512 implementation\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The SHA-512 Secure Hash Standard was published by NIST in 2002.\n *\n *  http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_SHA512_C)\n\n#include \"mbedtls/sha512.h\"\n#include \"mbedtls/platform_util.h\"\n\n#if defined(_MSC_VER) || defined(__WATCOMC__)\n  #define UL64(x) x##ui64\n#else\n  #define UL64(x) x##ULL\n#endif\n\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#include <stdlib.h>\n#define mbedtls_printf printf\n#define mbedtls_calloc    calloc\n#define mbedtls_free       free\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if !defined(MBEDTLS_SHA512_ALT)\n\n/*\n * 64-bit integer manipulation macros (big endian)\n */\n#ifndef GET_UINT64_BE\n#define GET_UINT64_BE(n,b,i)                            \\\n{                                                       \\\n    (n) = ( (uint64_t) (b)[(i)    ] << 56 )       \\\n        | ( (uint64_t) (b)[(i) + 1] << 48 )       \\\n        | ( (uint64_t) (b)[(i) + 2] << 40 )       \\\n        | ( (uint64_t) (b)[(i) + 3] << 32 )       \\\n        | ( (uint64_t) (b)[(i) + 4] << 24 )       \\\n        | ( (uint64_t) (b)[(i) + 5] << 16 )       \\\n        | ( (uint64_t) (b)[(i) + 6] <<  8 )       \\\n        | ( (uint64_t) (b)[(i) + 7]       );      \\\n}\n#endif /* GET_UINT64_BE */\n\n#ifndef PUT_UINT64_BE\n#define PUT_UINT64_BE(n,b,i)                            \\\n{                                                       \\\n    (b)[(i)    ] = (unsigned char) ( (n) >> 56 );       \\\n    (b)[(i) + 1] = (unsigned char) ( (n) >> 48 );       \\\n    (b)[(i) + 2] = (unsigned char) ( (n) >> 40 );       \\\n    (b)[(i) + 3] = (unsigned char) ( (n) >> 32 );       \\\n    (b)[(i) + 4] = (unsigned char) ( (n) >> 24 );       \\\n    (b)[(i) + 5] = (unsigned char) ( (n) >> 16 );       \\\n    (b)[(i) + 6] = (unsigned char) ( (n) >>  8 );       \\\n    (b)[(i) + 7] = (unsigned char) ( (n)       );       \\\n}\n#endif /* PUT_UINT64_BE */\n\nvoid mbedtls_sha512_init( mbedtls_sha512_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_sha512_context ) );\n}\n\nvoid mbedtls_sha512_free( mbedtls_sha512_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha512_context ) );\n}\n\nvoid mbedtls_sha512_clone( mbedtls_sha512_context *dst,\n                           const mbedtls_sha512_context *src )\n{\n    *dst = *src;\n}\n\n/*\n * SHA-512 context setup\n */\nint mbedtls_sha512_starts_ret( mbedtls_sha512_context *ctx, int is384 )\n{\n    ctx->total[0] = 0;\n    ctx->total[1] = 0;\n\n    if( is384 == 0 )\n    {\n        /* SHA-512 */\n        ctx->state[0] = UL64(0x6A09E667F3BCC908);\n        ctx->state[1] = UL64(0xBB67AE8584CAA73B);\n        ctx->state[2] = UL64(0x3C6EF372FE94F82B);\n        ctx->state[3] = UL64(0xA54FF53A5F1D36F1);\n        ctx->state[4] = UL64(0x510E527FADE682D1);\n        ctx->state[5] = UL64(0x9B05688C2B3E6C1F);\n        ctx->state[6] = UL64(0x1F83D9ABFB41BD6B);\n        ctx->state[7] = UL64(0x5BE0CD19137E2179);\n    }\n    else\n    {\n        /* SHA-384 */\n        ctx->state[0] = UL64(0xCBBB9D5DC1059ED8);\n        ctx->state[1] = UL64(0x629A292A367CD507);\n        ctx->state[2] = UL64(0x9159015A3070DD17);\n        ctx->state[3] = UL64(0x152FECD8F70E5939);\n        ctx->state[4] = UL64(0x67332667FFC00B31);\n        ctx->state[5] = UL64(0x8EB44A8768581511);\n        ctx->state[6] = UL64(0xDB0C2E0D64F98FA7);\n        ctx->state[7] = UL64(0x47B5481DBEFA4FA4);\n    }\n\n    ctx->is384 = is384;\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_sha512_starts( mbedtls_sha512_context *ctx,\n                            int is384 )\n{\n    mbedtls_sha512_starts_ret( ctx, is384 );\n}\n#endif\n\n#if !defined(MBEDTLS_SHA512_PROCESS_ALT)\n\n/*\n * Round constants\n */\nstatic const uint64_t K[80] =\n{\n    UL64(0x428A2F98D728AE22),  UL64(0x7137449123EF65CD),\n    UL64(0xB5C0FBCFEC4D3B2F),  UL64(0xE9B5DBA58189DBBC),\n    UL64(0x3956C25BF348B538),  UL64(0x59F111F1B605D019),\n    UL64(0x923F82A4AF194F9B),  UL64(0xAB1C5ED5DA6D8118),\n    UL64(0xD807AA98A3030242),  UL64(0x12835B0145706FBE),\n    UL64(0x243185BE4EE4B28C),  UL64(0x550C7DC3D5FFB4E2),\n    UL64(0x72BE5D74F27B896F),  UL64(0x80DEB1FE3B1696B1),\n    UL64(0x9BDC06A725C71235),  UL64(0xC19BF174CF692694),\n    UL64(0xE49B69C19EF14AD2),  UL64(0xEFBE4786384F25E3),\n    UL64(0x0FC19DC68B8CD5B5),  UL64(0x240CA1CC77AC9C65),\n    UL64(0x2DE92C6F592B0275),  UL64(0x4A7484AA6EA6E483),\n    UL64(0x5CB0A9DCBD41FBD4),  UL64(0x76F988DA831153B5),\n    UL64(0x983E5152EE66DFAB),  UL64(0xA831C66D2DB43210),\n    UL64(0xB00327C898FB213F),  UL64(0xBF597FC7BEEF0EE4),\n    UL64(0xC6E00BF33DA88FC2),  UL64(0xD5A79147930AA725),\n    UL64(0x06CA6351E003826F),  UL64(0x142929670A0E6E70),\n    UL64(0x27B70A8546D22FFC),  UL64(0x2E1B21385C26C926),\n    UL64(0x4D2C6DFC5AC42AED),  UL64(0x53380D139D95B3DF),\n    UL64(0x650A73548BAF63DE),  UL64(0x766A0ABB3C77B2A8),\n    UL64(0x81C2C92E47EDAEE6),  UL64(0x92722C851482353B),\n    UL64(0xA2BFE8A14CF10364),  UL64(0xA81A664BBC423001),\n    UL64(0xC24B8B70D0F89791),  UL64(0xC76C51A30654BE30),\n    UL64(0xD192E819D6EF5218),  UL64(0xD69906245565A910),\n    UL64(0xF40E35855771202A),  UL64(0x106AA07032BBD1B8),\n    UL64(0x19A4C116B8D2D0C8),  UL64(0x1E376C085141AB53),\n    UL64(0x2748774CDF8EEB99),  UL64(0x34B0BCB5E19B48A8),\n    UL64(0x391C0CB3C5C95A63),  UL64(0x4ED8AA4AE3418ACB),\n    UL64(0x5B9CCA4F7763E373),  UL64(0x682E6FF3D6B2B8A3),\n    UL64(0x748F82EE5DEFB2FC),  UL64(0x78A5636F43172F60),\n    UL64(0x84C87814A1F0AB72),  UL64(0x8CC702081A6439EC),\n    UL64(0x90BEFFFA23631E28),  UL64(0xA4506CEBDE82BDE9),\n    UL64(0xBEF9A3F7B2C67915),  UL64(0xC67178F2E372532B),\n    UL64(0xCA273ECEEA26619C),  UL64(0xD186B8C721C0C207),\n    UL64(0xEADA7DD6CDE0EB1E),  UL64(0xF57D4F7FEE6ED178),\n    UL64(0x06F067AA72176FBA),  UL64(0x0A637DC5A2C898A6),\n    UL64(0x113F9804BEF90DAE),  UL64(0x1B710B35131C471B),\n    UL64(0x28DB77F523047D84),  UL64(0x32CAAB7B40C72493),\n    UL64(0x3C9EBE0A15C9BEBC),  UL64(0x431D67C49C100D4C),\n    UL64(0x4CC5D4BECB3E42B6),  UL64(0x597F299CFC657E2A),\n    UL64(0x5FCB6FAB3AD6FAEC),  UL64(0x6C44198C4A475817)\n};\n\nint mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx,\n                                     const unsigned char data[128] )\n{\n    int i;\n    uint64_t temp1, temp2, W[80];\n    uint64_t A, B, C, D, E, F, G, H;\n\n#define  SHR(x,n) (x >> n)\n#define ROTR(x,n) (SHR(x,n) | (x << (64 - n)))\n\n#define S0(x) (ROTR(x, 1) ^ ROTR(x, 8) ^  SHR(x, 7))\n#define S1(x) (ROTR(x,19) ^ ROTR(x,61) ^  SHR(x, 6))\n\n#define S2(x) (ROTR(x,28) ^ ROTR(x,34) ^ ROTR(x,39))\n#define S3(x) (ROTR(x,14) ^ ROTR(x,18) ^ ROTR(x,41))\n\n#define F0(x,y,z) ((x & y) | (z & (x | y)))\n#define F1(x,y,z) (z ^ (x & (y ^ z)))\n\n#define P(a,b,c,d,e,f,g,h,x,K)                  \\\n{                                               \\\n    temp1 = h + S3(e) + F1(e,f,g) + K + x;      \\\n    temp2 = S2(a) + F0(a,b,c);                  \\\n    d += temp1; h = temp1 + temp2;              \\\n}\n\n    for( i = 0; i < 16; i++ )\n    {\n        GET_UINT64_BE( W[i], data, i << 3 );\n    }\n\n    for( ; i < 80; i++ )\n    {\n        W[i] = S1(W[i -  2]) + W[i -  7] +\n               S0(W[i - 15]) + W[i - 16];\n    }\n\n    A = ctx->state[0];\n    B = ctx->state[1];\n    C = ctx->state[2];\n    D = ctx->state[3];\n    E = ctx->state[4];\n    F = ctx->state[5];\n    G = ctx->state[6];\n    H = ctx->state[7];\n    i = 0;\n\n    do\n    {\n        P( A, B, C, D, E, F, G, H, W[i], K[i] ); i++;\n        P( H, A, B, C, D, E, F, G, W[i], K[i] ); i++;\n        P( G, H, A, B, C, D, E, F, W[i], K[i] ); i++;\n        P( F, G, H, A, B, C, D, E, W[i], K[i] ); i++;\n        P( E, F, G, H, A, B, C, D, W[i], K[i] ); i++;\n        P( D, E, F, G, H, A, B, C, W[i], K[i] ); i++;\n        P( C, D, E, F, G, H, A, B, W[i], K[i] ); i++;\n        P( B, C, D, E, F, G, H, A, W[i], K[i] ); i++;\n    }\n    while( i < 80 );\n\n    ctx->state[0] += A;\n    ctx->state[1] += B;\n    ctx->state[2] += C;\n    ctx->state[3] += D;\n    ctx->state[4] += E;\n    ctx->state[5] += F;\n    ctx->state[6] += G;\n    ctx->state[7] += H;\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_sha512_process( mbedtls_sha512_context *ctx,\n                             const unsigned char data[128] )\n{\n    mbedtls_internal_sha512_process( ctx, data );\n}\n#endif\n#endif /* !MBEDTLS_SHA512_PROCESS_ALT */\n\n/*\n * SHA-512 process buffer\n */\nint mbedtls_sha512_update_ret( mbedtls_sha512_context *ctx,\n                               const unsigned char *input,\n                               size_t ilen )\n{\n    int ret;\n    size_t fill;\n    unsigned int left;\n\n    if( ilen == 0 )\n        return( 0 );\n\n    left = (unsigned int) (ctx->total[0] & 0x7F);\n    fill = 128 - left;\n\n    ctx->total[0] += (uint64_t) ilen;\n\n    if( ctx->total[0] < (uint64_t) ilen )\n        ctx->total[1]++;\n\n    if( left && ilen >= fill )\n    {\n        memcpy( (void *) (ctx->buffer + left), input, fill );\n\n        if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 )\n            return( ret );\n\n        input += fill;\n        ilen  -= fill;\n        left = 0;\n    }\n\n    while( ilen >= 128 )\n    {\n        if( ( ret = mbedtls_internal_sha512_process( ctx, input ) ) != 0 )\n            return( ret );\n\n        input += 128;\n        ilen  -= 128;\n    }\n\n    if( ilen > 0 )\n        memcpy( (void *) (ctx->buffer + left), input, ilen );\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_sha512_update( mbedtls_sha512_context *ctx,\n                            const unsigned char *input,\n                            size_t ilen )\n{\n    mbedtls_sha512_update_ret( ctx, input, ilen );\n}\n#endif\n\n/*\n * SHA-512 final digest\n */\nint mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx,\n                               unsigned char output[64] )\n{\n    int ret;\n    unsigned used;\n    uint64_t high, low;\n\n    /*\n     * Add padding: 0x80 then 0x00 until 16 bytes remain for the length\n     */\n    used = ctx->total[0] & 0x7F;\n\n    ctx->buffer[used++] = 0x80;\n\n    if( used <= 112 )\n    {\n        /* Enough room for padding + length in current block */\n        memset( ctx->buffer + used, 0, 112 - used );\n    }\n    else\n    {\n        /* We'll need an extra block */\n        memset( ctx->buffer + used, 0, 128 - used );\n\n        if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 )\n            return( ret );\n\n        memset( ctx->buffer, 0, 112 );\n    }\n\n    /*\n     * Add message length\n     */\n    high = ( ctx->total[0] >> 61 )\n         | ( ctx->total[1] <<  3 );\n    low  = ( ctx->total[0] <<  3 );\n\n    PUT_UINT64_BE( high, ctx->buffer, 112 );\n    PUT_UINT64_BE( low,  ctx->buffer, 120 );\n\n    if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 )\n        return( ret );\n\n    /*\n     * Output final state\n     */\n    PUT_UINT64_BE( ctx->state[0], output,  0 );\n    PUT_UINT64_BE( ctx->state[1], output,  8 );\n    PUT_UINT64_BE( ctx->state[2], output, 16 );\n    PUT_UINT64_BE( ctx->state[3], output, 24 );\n    PUT_UINT64_BE( ctx->state[4], output, 32 );\n    PUT_UINT64_BE( ctx->state[5], output, 40 );\n\n    if( ctx->is384 == 0 )\n    {\n        PUT_UINT64_BE( ctx->state[6], output, 48 );\n        PUT_UINT64_BE( ctx->state[7], output, 56 );\n    }\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_sha512_finish( mbedtls_sha512_context *ctx,\n                            unsigned char output[64] )\n{\n    mbedtls_sha512_finish_ret( ctx, output );\n}\n#endif\n\n#endif /* !MBEDTLS_SHA512_ALT */\n\n/*\n * output = SHA-512( input buffer )\n */\nint mbedtls_sha512_ret( const unsigned char *input,\n                    size_t ilen,\n                    unsigned char output[64],\n                    int is384 )\n{\n    int ret;\n    mbedtls_sha512_context ctx;\n\n    mbedtls_sha512_init( &ctx );\n\n    if( ( ret = mbedtls_sha512_starts_ret( &ctx, is384 ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_sha512_update_ret( &ctx, input, ilen ) ) != 0 )\n        goto exit;\n\n    if( ( ret = mbedtls_sha512_finish_ret( &ctx, output ) ) != 0 )\n        goto exit;\n\nexit:\n    mbedtls_sha512_free( &ctx );\n\n    return( ret );\n}\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nvoid mbedtls_sha512( const unsigned char *input,\n                     size_t ilen,\n                     unsigned char output[64],\n                     int is384 )\n{\n    mbedtls_sha512_ret( input, ilen, output, is384 );\n}\n#endif\n\n#if defined(MBEDTLS_SELF_TEST)\n\n/*\n * FIPS-180-2 test vectors\n */\nstatic const unsigned char sha512_test_buf[3][113] =\n{\n    { \"abc\" },\n    { \"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn\"\n      \"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu\" },\n    { \"\" }\n};\n\nstatic const size_t sha512_test_buflen[3] =\n{\n    3, 112, 1000\n};\n\nstatic const unsigned char sha512_test_sum[6][64] =\n{\n    /*\n     * SHA-384 test vectors\n     */\n    { 0xCB, 0x00, 0x75, 0x3F, 0x45, 0xA3, 0x5E, 0x8B,\n      0xB5, 0xA0, 0x3D, 0x69, 0x9A, 0xC6, 0x50, 0x07,\n      0x27, 0x2C, 0x32, 0xAB, 0x0E, 0xDE, 0xD1, 0x63,\n      0x1A, 0x8B, 0x60, 0x5A, 0x43, 0xFF, 0x5B, 0xED,\n      0x80, 0x86, 0x07, 0x2B, 0xA1, 0xE7, 0xCC, 0x23,\n      0x58, 0xBA, 0xEC, 0xA1, 0x34, 0xC8, 0x25, 0xA7 },\n    { 0x09, 0x33, 0x0C, 0x33, 0xF7, 0x11, 0x47, 0xE8,\n      0x3D, 0x19, 0x2F, 0xC7, 0x82, 0xCD, 0x1B, 0x47,\n      0x53, 0x11, 0x1B, 0x17, 0x3B, 0x3B, 0x05, 0xD2,\n      0x2F, 0xA0, 0x80, 0x86, 0xE3, 0xB0, 0xF7, 0x12,\n      0xFC, 0xC7, 0xC7, 0x1A, 0x55, 0x7E, 0x2D, 0xB9,\n      0x66, 0xC3, 0xE9, 0xFA, 0x91, 0x74, 0x60, 0x39 },\n    { 0x9D, 0x0E, 0x18, 0x09, 0x71, 0x64, 0x74, 0xCB,\n      0x08, 0x6E, 0x83, 0x4E, 0x31, 0x0A, 0x4A, 0x1C,\n      0xED, 0x14, 0x9E, 0x9C, 0x00, 0xF2, 0x48, 0x52,\n      0x79, 0x72, 0xCE, 0xC5, 0x70, 0x4C, 0x2A, 0x5B,\n      0x07, 0xB8, 0xB3, 0xDC, 0x38, 0xEC, 0xC4, 0xEB,\n      0xAE, 0x97, 0xDD, 0xD8, 0x7F, 0x3D, 0x89, 0x85 },\n\n    /*\n     * SHA-512 test vectors\n     */\n    { 0xDD, 0xAF, 0x35, 0xA1, 0x93, 0x61, 0x7A, 0xBA,\n      0xCC, 0x41, 0x73, 0x49, 0xAE, 0x20, 0x41, 0x31,\n      0x12, 0xE6, 0xFA, 0x4E, 0x89, 0xA9, 0x7E, 0xA2,\n      0x0A, 0x9E, 0xEE, 0xE6, 0x4B, 0x55, 0xD3, 0x9A,\n      0x21, 0x92, 0x99, 0x2A, 0x27, 0x4F, 0xC1, 0xA8,\n      0x36, 0xBA, 0x3C, 0x23, 0xA3, 0xFE, 0xEB, 0xBD,\n      0x45, 0x4D, 0x44, 0x23, 0x64, 0x3C, 0xE8, 0x0E,\n      0x2A, 0x9A, 0xC9, 0x4F, 0xA5, 0x4C, 0xA4, 0x9F },\n    { 0x8E, 0x95, 0x9B, 0x75, 0xDA, 0xE3, 0x13, 0xDA,\n      0x8C, 0xF4, 0xF7, 0x28, 0x14, 0xFC, 0x14, 0x3F,\n      0x8F, 0x77, 0x79, 0xC6, 0xEB, 0x9F, 0x7F, 0xA1,\n      0x72, 0x99, 0xAE, 0xAD, 0xB6, 0x88, 0x90, 0x18,\n      0x50, 0x1D, 0x28, 0x9E, 0x49, 0x00, 0xF7, 0xE4,\n      0x33, 0x1B, 0x99, 0xDE, 0xC4, 0xB5, 0x43, 0x3A,\n      0xC7, 0xD3, 0x29, 0xEE, 0xB6, 0xDD, 0x26, 0x54,\n      0x5E, 0x96, 0xE5, 0x5B, 0x87, 0x4B, 0xE9, 0x09 },\n    { 0xE7, 0x18, 0x48, 0x3D, 0x0C, 0xE7, 0x69, 0x64,\n      0x4E, 0x2E, 0x42, 0xC7, 0xBC, 0x15, 0xB4, 0x63,\n      0x8E, 0x1F, 0x98, 0xB1, 0x3B, 0x20, 0x44, 0x28,\n      0x56, 0x32, 0xA8, 0x03, 0xAF, 0xA9, 0x73, 0xEB,\n      0xDE, 0x0F, 0xF2, 0x44, 0x87, 0x7E, 0xA6, 0x0A,\n      0x4C, 0xB0, 0x43, 0x2C, 0xE5, 0x77, 0xC3, 0x1B,\n      0xEB, 0x00, 0x9C, 0x5C, 0x2C, 0x49, 0xAA, 0x2E,\n      0x4E, 0xAD, 0xB2, 0x17, 0xAD, 0x8C, 0xC0, 0x9B }\n};\n\n/*\n * Checkup routine\n */\nint mbedtls_sha512_self_test( int verbose )\n{\n    int i, j, k, buflen, ret = 0;\n    unsigned char *buf;\n    unsigned char sha512sum[64];\n    mbedtls_sha512_context ctx;\n\n    buf = mbedtls_calloc( 1024, sizeof(unsigned char) );\n    if( NULL == buf )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"Buffer allocation failed\\n\" );\n\n        return( 1 );\n    }\n\n    mbedtls_sha512_init( &ctx );\n\n    for( i = 0; i < 6; i++ )\n    {\n        j = i % 3;\n        k = i < 3;\n\n        if( verbose != 0 )\n            mbedtls_printf( \"  SHA-%d test #%d: \", 512 - k * 128, j + 1 );\n\n        if( ( ret = mbedtls_sha512_starts_ret( &ctx, k ) ) != 0 )\n            goto fail;\n\n        if( j == 2 )\n        {\n            memset( buf, 'a', buflen = 1000 );\n\n            for( j = 0; j < 1000; j++ )\n            {\n                ret = mbedtls_sha512_update_ret( &ctx, buf, buflen );\n                if( ret != 0 )\n                    goto fail;\n            }\n        }\n        else\n        {\n            ret = mbedtls_sha512_update_ret( &ctx, sha512_test_buf[j],\n                                             sha512_test_buflen[j] );\n            if( ret != 0 )\n                goto fail;\n        }\n\n        if( ( ret = mbedtls_sha512_finish_ret( &ctx, sha512sum ) ) != 0 )\n            goto fail;\n\n        if( memcmp( sha512sum, sha512_test_sum[i], 64 - k * 16 ) != 0 )\n        {\n            ret = 1;\n            goto fail;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    goto exit;\n\nfail:\n    if( verbose != 0 )\n        mbedtls_printf( \"failed\\n\" );\n\nexit:\n    mbedtls_sha512_free( &ctx );\n    mbedtls_free( buf );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_SHA512_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/ssl_cache.c",
    "content": "/*\n *  SSL session cache implementation\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n * These session callbacks use a simple chained list\n * to store and retrieve the session information.\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_SSL_CACHE_C)\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc    calloc\n#define mbedtls_free      free\n#endif\n\n#include \"mbedtls/ssl_cache.h\"\n\n#include <string.h>\n\nvoid mbedtls_ssl_cache_init( mbedtls_ssl_cache_context *cache )\n{\n    memset( cache, 0, sizeof( mbedtls_ssl_cache_context ) );\n\n    cache->timeout = MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT;\n    cache->max_entries = MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES;\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_mutex_init( &cache->mutex );\n#endif\n}\n\nint mbedtls_ssl_cache_get( void *data, mbedtls_ssl_session *session )\n{\n    int ret = 1;\n#if defined(MBEDTLS_HAVE_TIME)\n    mbedtls_time_t t = mbedtls_time( NULL );\n#endif\n    mbedtls_ssl_cache_context *cache = (mbedtls_ssl_cache_context *) data;\n    mbedtls_ssl_cache_entry *cur, *entry;\n\n#if defined(MBEDTLS_THREADING_C)\n    if( mbedtls_mutex_lock( &cache->mutex ) != 0 )\n        return( 1 );\n#endif\n\n    cur = cache->chain;\n    entry = NULL;\n\n    while( cur != NULL )\n    {\n        entry = cur;\n        cur = cur->next;\n\n#if defined(MBEDTLS_HAVE_TIME)\n        if( cache->timeout != 0 &&\n            (int) ( t - entry->timestamp ) > cache->timeout )\n            continue;\n#endif\n\n        if( session->ciphersuite != entry->session.ciphersuite ||\n            session->compression != entry->session.compression ||\n            session->id_len != entry->session.id_len )\n            continue;\n\n        if( memcmp( session->id, entry->session.id,\n                    entry->session.id_len ) != 0 )\n            continue;\n\n        memcpy( session->master, entry->session.master, 48 );\n\n        session->verify_result = entry->session.verify_result;\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n        /*\n         * Restore peer certificate (without rest of the original chain)\n         */\n        if( entry->peer_cert.p != NULL )\n        {\n            if( ( session->peer_cert = mbedtls_calloc( 1,\n                                 sizeof(mbedtls_x509_crt) ) ) == NULL )\n            {\n                ret = 1;\n                goto exit;\n            }\n\n            mbedtls_x509_crt_init( session->peer_cert );\n            if( mbedtls_x509_crt_parse( session->peer_cert, entry->peer_cert.p,\n                                entry->peer_cert.len ) != 0 )\n            {\n                mbedtls_free( session->peer_cert );\n                session->peer_cert = NULL;\n                ret = 1;\n                goto exit;\n            }\n        }\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n        ret = 0;\n        goto exit;\n    }\n\nexit:\n#if defined(MBEDTLS_THREADING_C)\n    if( mbedtls_mutex_unlock( &cache->mutex ) != 0 )\n        ret = 1;\n#endif\n\n    return( ret );\n}\n\nint mbedtls_ssl_cache_set( void *data, const mbedtls_ssl_session *session )\n{\n    int ret = 1;\n#if defined(MBEDTLS_HAVE_TIME)\n    mbedtls_time_t t = mbedtls_time( NULL ), oldest = 0;\n    mbedtls_ssl_cache_entry *old = NULL;\n#endif\n    mbedtls_ssl_cache_context *cache = (mbedtls_ssl_cache_context *) data;\n    mbedtls_ssl_cache_entry *cur, *prv;\n    int count = 0;\n\n#if defined(MBEDTLS_THREADING_C)\n    if( ( ret = mbedtls_mutex_lock( &cache->mutex ) ) != 0 )\n        return( ret );\n#endif\n\n    cur = cache->chain;\n    prv = NULL;\n\n    while( cur != NULL )\n    {\n        count++;\n\n#if defined(MBEDTLS_HAVE_TIME)\n        if( cache->timeout != 0 &&\n            (int) ( t - cur->timestamp ) > cache->timeout )\n        {\n            cur->timestamp = t;\n            break; /* expired, reuse this slot, update timestamp */\n        }\n#endif\n\n        if( memcmp( session->id, cur->session.id, cur->session.id_len ) == 0 )\n            break; /* client reconnected, keep timestamp for session id */\n\n#if defined(MBEDTLS_HAVE_TIME)\n        if( oldest == 0 || cur->timestamp < oldest )\n        {\n            oldest = cur->timestamp;\n            old = cur;\n        }\n#endif\n\n        prv = cur;\n        cur = cur->next;\n    }\n\n    if( cur == NULL )\n    {\n#if defined(MBEDTLS_HAVE_TIME)\n        /*\n         * Reuse oldest entry if max_entries reached\n         */\n        if( count >= cache->max_entries )\n        {\n            if( old == NULL )\n            {\n                ret = 1;\n                goto exit;\n            }\n\n            cur = old;\n        }\n#else /* MBEDTLS_HAVE_TIME */\n        /*\n         * Reuse first entry in chain if max_entries reached,\n         * but move to last place\n         */\n        if( count >= cache->max_entries )\n        {\n            if( cache->chain == NULL )\n            {\n                ret = 1;\n                goto exit;\n            }\n\n            cur = cache->chain;\n            cache->chain = cur->next;\n            cur->next = NULL;\n            prv->next = cur;\n        }\n#endif /* MBEDTLS_HAVE_TIME */\n        else\n        {\n            /*\n             * max_entries not reached, create new entry\n             */\n            cur = mbedtls_calloc( 1, sizeof(mbedtls_ssl_cache_entry) );\n            if( cur == NULL )\n            {\n                ret = 1;\n                goto exit;\n            }\n\n            if( prv == NULL )\n                cache->chain = cur;\n            else\n                prv->next = cur;\n        }\n\n#if defined(MBEDTLS_HAVE_TIME)\n        cur->timestamp = t;\n#endif\n    }\n\n    memcpy( &cur->session, session, sizeof( mbedtls_ssl_session ) );\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    /*\n     * If we're reusing an entry, free its certificate first\n     */\n    if( cur->peer_cert.p != NULL )\n    {\n        mbedtls_free( cur->peer_cert.p );\n        memset( &cur->peer_cert, 0, sizeof(mbedtls_x509_buf) );\n    }\n\n    /*\n     * Store peer certificate\n     */\n    if( session->peer_cert != NULL )\n    {\n        cur->peer_cert.p = mbedtls_calloc( 1, session->peer_cert->raw.len );\n        if( cur->peer_cert.p == NULL )\n        {\n            ret = 1;\n            goto exit;\n        }\n\n        memcpy( cur->peer_cert.p, session->peer_cert->raw.p,\n                session->peer_cert->raw.len );\n        cur->peer_cert.len = session->peer_cert->raw.len;\n\n        cur->session.peer_cert = NULL;\n    }\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n    ret = 0;\n\nexit:\n#if defined(MBEDTLS_THREADING_C)\n    if( mbedtls_mutex_unlock( &cache->mutex ) != 0 )\n        ret = 1;\n#endif\n\n    return( ret );\n}\n\n#if defined(MBEDTLS_HAVE_TIME)\nvoid mbedtls_ssl_cache_set_timeout( mbedtls_ssl_cache_context *cache, int timeout )\n{\n    if( timeout < 0 ) timeout = 0;\n\n    cache->timeout = timeout;\n}\n#endif /* MBEDTLS_HAVE_TIME */\n\nvoid mbedtls_ssl_cache_set_max_entries( mbedtls_ssl_cache_context *cache, int max )\n{\n    if( max < 0 ) max = 0;\n\n    cache->max_entries = max;\n}\n\nvoid mbedtls_ssl_cache_free( mbedtls_ssl_cache_context *cache )\n{\n    mbedtls_ssl_cache_entry *cur, *prv;\n\n    cur = cache->chain;\n\n    while( cur != NULL )\n    {\n        prv = cur;\n        cur = cur->next;\n\n        mbedtls_ssl_session_free( &prv->session );\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n        mbedtls_free( prv->peer_cert.p );\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n        mbedtls_free( prv );\n    }\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_mutex_free( &cache->mutex );\n#endif\n    cache->chain = NULL;\n}\n\n#endif /* MBEDTLS_SSL_CACHE_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/ssl_ciphersuites.c",
    "content": "/**\n * \\file ssl_ciphersuites.c\n *\n * \\brief SSL ciphersuites for mbed TLS\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_SSL_TLS_C)\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#endif\n\n#include \"mbedtls/ssl_ciphersuites.h\"\n#include \"mbedtls/ssl.h\"\n\n#include <string.h>\n\n/*\n * Ordered from most preferred to least preferred in terms of security.\n *\n * Current rule (except rc4, weak and null which come last):\n * 1. By key exchange:\n *    Forward-secure non-PSK > forward-secure PSK > ECJPAKE > other non-PSK > other PSK\n * 2. By key length and cipher:\n *    ChaCha > AES-256 > Camellia-256 > ARIA-256 > AES-128 > Camellia-128 > ARIA-128 > 3DES\n * 3. By cipher mode when relevant GCM > CCM > CBC > CCM_8\n * 4. By hash function used when relevant\n * 5. By key exchange/auth again: EC > non-EC\n */\nstatic const int ciphersuite_preference[] =\n{\n#if defined(MBEDTLS_SSL_CIPHERSUITES)\n    MBEDTLS_SSL_CIPHERSUITES,\n#else\n    /* Chacha-Poly ephemeral suites */\n    MBEDTLS_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,\n    MBEDTLS_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,\n\n    /* All AES-256 ephemeral suites */\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n    MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM,\n    MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM,\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,\n    MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n    MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA,\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8,\n    MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM_8,\n\n    /* All CAMELLIA-256 ephemeral suites */\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384,\n    MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384,\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384,\n    MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256,\n    MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,\n\n    /* All ARIA-256 ephemeral suites */\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384,\n    MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384,\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384,\n    MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384,\n\n    /* All AES-128 ephemeral suites */\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n    MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM,\n    MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM,\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,\n    MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,\n    MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA,\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,\n    MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM_8,\n\n    /* All CAMELLIA-128 ephemeral suites */\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256,\n    MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256,\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,\n    MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,\n    MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,\n\n    /* All ARIA-128 ephemeral suites */\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256,\n    MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256,\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256,\n    MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256,\n\n    /* All remaining >= 128-bit ephemeral suites */\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,\n    MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,\n\n    /* The PSK ephemeral suites */\n    MBEDTLS_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,\n    MBEDTLS_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256,\n    MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384,\n    MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM,\n    MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384,\n    MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384,\n    MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA,\n    MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA,\n    MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384,\n    MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,\n    MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,\n    MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM_8,\n    MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384,\n    MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384,\n    MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384,\n\n    MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256,\n    MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM,\n    MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,\n    MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256,\n    MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA,\n    MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA,\n    MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256,\n    MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,\n    MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,\n    MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM_8,\n    MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256,\n    MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256,\n    MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256,\n\n    MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA,\n    MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA,\n\n    /* The ECJPAKE suite */\n    MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8,\n\n    /* All AES-256 suites */\n    MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384,\n    MBEDTLS_TLS_RSA_WITH_AES_256_CCM,\n    MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256,\n    MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA,\n    MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384,\n    MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384,\n    MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384,\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384,\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,\n    MBEDTLS_TLS_RSA_WITH_AES_256_CCM_8,\n\n    /* All CAMELLIA-256 suites */\n    MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384,\n    MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256,\n    MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,\n    MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384,\n    MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384,\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384,\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,\n\n    /* All ARIA-256 suites */\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384,\n    MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384,\n    MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384,\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384,\n    MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384,\n    MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384,\n\n    /* All AES-128 suites */\n    MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,\n    MBEDTLS_TLS_RSA_WITH_AES_128_CCM,\n    MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,\n    MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,\n    MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,\n    MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,\n    MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,\n    MBEDTLS_TLS_RSA_WITH_AES_128_CCM_8,\n\n    /* All CAMELLIA-128 suites */\n    MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256,\n    MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256,\n    MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,\n    MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256,\n    MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256,\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256,\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,\n\n    /* All ARIA-128 suites */\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256,\n    MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256,\n    MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256,\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256,\n    MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256,\n    MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256,\n\n    /* All remaining >= 128-bit suites */\n    MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA,\n    MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,\n\n    /* The RSA PSK suites */\n    MBEDTLS_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256,\n    MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384,\n    MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384,\n    MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA,\n    MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384,\n    MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384,\n    MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384,\n    MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384,\n\n    MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256,\n    MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256,\n    MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA,\n    MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256,\n    MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256,\n    MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256,\n    MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256,\n\n    MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA,\n\n    /* The PSK suites */\n    MBEDTLS_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256,\n    MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384,\n    MBEDTLS_TLS_PSK_WITH_AES_256_CCM,\n    MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384,\n    MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA,\n    MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384,\n    MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384,\n    MBEDTLS_TLS_PSK_WITH_AES_256_CCM_8,\n    MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384,\n    MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384,\n\n    MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256,\n    MBEDTLS_TLS_PSK_WITH_AES_128_CCM,\n    MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256,\n    MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA,\n    MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256,\n    MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256,\n    MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8,\n    MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256,\n    MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256,\n\n    MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA,\n\n    /* RC4 suites */\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA,\n    MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA,\n    MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA,\n    MBEDTLS_TLS_RSA_WITH_RC4_128_SHA,\n    MBEDTLS_TLS_RSA_WITH_RC4_128_MD5,\n    MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA,\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA,\n    MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA,\n    MBEDTLS_TLS_PSK_WITH_RC4_128_SHA,\n\n    /* Weak suites */\n    MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA,\n    MBEDTLS_TLS_RSA_WITH_DES_CBC_SHA,\n\n    /* NULL suites */\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA,\n    MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA,\n    MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384,\n    MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256,\n    MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA,\n    MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA384,\n    MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA256,\n    MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA,\n\n    MBEDTLS_TLS_RSA_WITH_NULL_SHA256,\n    MBEDTLS_TLS_RSA_WITH_NULL_SHA,\n    MBEDTLS_TLS_RSA_WITH_NULL_MD5,\n    MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA,\n    MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA,\n    MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA384,\n    MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA256,\n    MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA,\n    MBEDTLS_TLS_PSK_WITH_NULL_SHA384,\n    MBEDTLS_TLS_PSK_WITH_NULL_SHA256,\n    MBEDTLS_TLS_PSK_WITH_NULL_SHA,\n\n#endif /* MBEDTLS_SSL_CIPHERSUITES */\n    0\n};\n\nstatic const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =\n{\n#if defined(MBEDTLS_CHACHAPOLY_C) && \\\n    defined(MBEDTLS_SHA256_C) && \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,\n      \"TLS-ECDHE-RSA-WITH-CHACHA20-POLY1305-SHA256\",\n      MBEDTLS_CIPHER_CHACHA20_POLY1305, MBEDTLS_MD_SHA256,\n      MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,\n      \"TLS-ECDHE-ECDSA-WITH-CHACHA20-POLY1305-SHA256\",\n      MBEDTLS_CIPHER_CHACHA20_POLY1305, MBEDTLS_MD_SHA256,\n      MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)\n    { MBEDTLS_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,\n      \"TLS-DHE-RSA-WITH-CHACHA20-POLY1305-SHA256\",\n      MBEDTLS_CIPHER_CHACHA20_POLY1305, MBEDTLS_MD_SHA256,\n      MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)\n    { MBEDTLS_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256,\n      \"TLS-PSK-WITH-CHACHA20-POLY1305-SHA256\",\n      MBEDTLS_CIPHER_CHACHA20_POLY1305, MBEDTLS_MD_SHA256,\n      MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)\n    { MBEDTLS_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,\n      \"TLS-ECDHE-PSK-WITH-CHACHA20-POLY1305-SHA256\",\n      MBEDTLS_CIPHER_CHACHA20_POLY1305, MBEDTLS_MD_SHA256,\n      MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)\n    { MBEDTLS_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256,\n      \"TLS-DHE-PSK-WITH-CHACHA20-POLY1305-SHA256\",\n      MBEDTLS_CIPHER_CHACHA20_POLY1305, MBEDTLS_MD_SHA256,\n      MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)\n    { MBEDTLS_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256,\n      \"TLS-RSA-PSK-WITH-CHACHA20-POLY1305-SHA256\",\n      MBEDTLS_CIPHER_CHACHA20_POLY1305, MBEDTLS_MD_SHA256,\n      MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#endif /* MBEDTLS_CHACHAPOLY_C &&\n          MBEDTLS_SHA256_C &&\n          MBEDTLS_SSL_PROTO_TLS1_2 */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)\n#if defined(MBEDTLS_AES_C)\n#if defined(MBEDTLS_SHA1_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, \"TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, \"TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_SHA1_C */\n#if defined(MBEDTLS_SHA256_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, \"TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#if defined(MBEDTLS_GCM_C)\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, \"TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, \"TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#if defined(MBEDTLS_GCM_C)\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, \"TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_SHA512_C */\n#if defined(MBEDTLS_CCM_C)\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM, \"TLS-ECDHE-ECDSA-WITH-AES-256-CCM\",\n      MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8, \"TLS-ECDHE-ECDSA-WITH-AES-256-CCM-8\",\n      MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_SHORT_TAG },\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM, \"TLS-ECDHE-ECDSA-WITH-AES-128-CCM\",\n      MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, \"TLS-ECDHE-ECDSA-WITH-AES-128-CCM-8\",\n      MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_SHORT_TAG },\n#endif /* MBEDTLS_CCM_C */\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_CAMELLIA_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, \"TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, \"TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_GCM_C)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256, \"TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384, \"TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_CAMELLIA_C */\n\n#if defined(MBEDTLS_DES_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, \"TLS-ECDHE-ECDSA-WITH-3DES-EDE-CBC-SHA\",\n      MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_ARC4_C)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, \"TLS-ECDHE-ECDSA-WITH-RC4-128-SHA\",\n      MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_NODTLS },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_ARC4_C */\n\n#if defined(MBEDTLS_CIPHER_NULL_CIPHER)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA, \"TLS-ECDHE-ECDSA-WITH-NULL-SHA\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_NULL_CIPHER */\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)\n#if defined(MBEDTLS_AES_C)\n#if defined(MBEDTLS_SHA1_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, \"TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, \"TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_SHA1_C */\n#if defined(MBEDTLS_SHA256_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, \"TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#if defined(MBEDTLS_GCM_C)\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, \"TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, \"TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#if defined(MBEDTLS_GCM_C)\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, \"TLS-ECDHE-RSA-WITH-AES-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_CAMELLIA_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, \"TLS-ECDHE-RSA-WITH-CAMELLIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384, \"TLS-ECDHE-RSA-WITH-CAMELLIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_GCM_C)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256, \"TLS-ECDHE-RSA-WITH-CAMELLIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384, \"TLS-ECDHE-RSA-WITH-CAMELLIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_CAMELLIA_C */\n\n#if defined(MBEDTLS_DES_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, \"TLS-ECDHE-RSA-WITH-3DES-EDE-CBC-SHA\",\n      MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_ARC4_C)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA, \"TLS-ECDHE-RSA-WITH-RC4-128-SHA\",\n      MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_NODTLS },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_ARC4_C */\n\n#if defined(MBEDTLS_CIPHER_NULL_CIPHER)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA, \"TLS-ECDHE-RSA-WITH-NULL-SHA\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_NULL_CIPHER */\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)\n#if defined(MBEDTLS_AES_C)\n#if defined(MBEDTLS_SHA512_C) && defined(MBEDTLS_GCM_C)\n    { MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, \"TLS-DHE-RSA-WITH-AES-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C && MBEDTLS_GCM_C */\n\n#if defined(MBEDTLS_SHA256_C)\n#if defined(MBEDTLS_GCM_C)\n    { MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, \"TLS-DHE-RSA-WITH-AES-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_GCM_C */\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, \"TLS-DHE-RSA-WITH-AES-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n\n    { MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, \"TLS-DHE-RSA-WITH-AES-256-CBC-SHA256\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA, \"TLS-DHE-RSA-WITH-AES-128-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n\n    { MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA, \"TLS-DHE-RSA-WITH-AES-256-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#if defined(MBEDTLS_CCM_C)\n    { MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM, \"TLS-DHE-RSA-WITH-AES-256-CCM\",\n      MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n    { MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM_8, \"TLS-DHE-RSA-WITH-AES-256-CCM-8\",\n      MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_SHORT_TAG },\n    { MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM, \"TLS-DHE-RSA-WITH-AES-128-CCM\",\n      MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n    { MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM_8, \"TLS-DHE-RSA-WITH-AES-128-CCM-8\",\n      MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_SHORT_TAG },\n#endif /* MBEDTLS_CCM_C */\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_CAMELLIA_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, \"TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n\n    { MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256, \"TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, \"TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA\",\n      MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n\n    { MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, \"TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA\",\n      MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#if defined(MBEDTLS_GCM_C)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256, \"TLS-DHE-RSA-WITH-CAMELLIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384, \"TLS-DHE-RSA-WITH-CAMELLIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_CAMELLIA_C */\n\n#if defined(MBEDTLS_DES_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, \"TLS-DHE-RSA-WITH-3DES-EDE-CBC-SHA\",\n      MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_DES_C */\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)\n#if defined(MBEDTLS_AES_C)\n#if defined(MBEDTLS_SHA512_C) && defined(MBEDTLS_GCM_C)\n    { MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384, \"TLS-RSA-WITH-AES-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C && MBEDTLS_GCM_C */\n\n#if defined(MBEDTLS_SHA256_C)\n#if defined(MBEDTLS_GCM_C)\n    { MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, \"TLS-RSA-WITH-AES-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_GCM_C */\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256, \"TLS-RSA-WITH-AES-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n\n    { MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256, \"TLS-RSA-WITH-AES-256-CBC-SHA256\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA1_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA, \"TLS-RSA-WITH-AES-128-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n\n    { MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA, \"TLS-RSA-WITH-AES-256-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_SHA1_C */\n#if defined(MBEDTLS_CCM_C)\n    { MBEDTLS_TLS_RSA_WITH_AES_256_CCM, \"TLS-RSA-WITH-AES-256-CCM\",\n      MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n    { MBEDTLS_TLS_RSA_WITH_AES_256_CCM_8, \"TLS-RSA-WITH-AES-256-CCM-8\",\n      MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_SHORT_TAG },\n    { MBEDTLS_TLS_RSA_WITH_AES_128_CCM, \"TLS-RSA-WITH-AES-128-CCM\",\n      MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n    { MBEDTLS_TLS_RSA_WITH_AES_128_CCM_8, \"TLS-RSA-WITH-AES-128-CCM-8\",\n      MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_SHORT_TAG },\n#endif /* MBEDTLS_CCM_C */\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_CAMELLIA_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256, \"TLS-RSA-WITH-CAMELLIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n\n    { MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256, \"TLS-RSA-WITH-CAMELLIA-256-CBC-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, \"TLS-RSA-WITH-CAMELLIA-128-CBC-SHA\",\n      MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n\n    { MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, \"TLS-RSA-WITH-CAMELLIA-256-CBC-SHA\",\n      MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_GCM_C)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256, \"TLS-RSA-WITH-CAMELLIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384, \"TLS-RSA-WITH-CAMELLIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_CAMELLIA_C */\n\n#if defined(MBEDTLS_DES_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA, \"TLS-RSA-WITH-3DES-EDE-CBC-SHA\",\n      MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_ARC4_C)\n#if defined(MBEDTLS_MD5_C)\n    { MBEDTLS_TLS_RSA_WITH_RC4_128_MD5, \"TLS-RSA-WITH-RC4-128-MD5\",\n      MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_MD5, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_NODTLS },\n#endif\n\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_RSA_WITH_RC4_128_SHA, \"TLS-RSA-WITH-RC4-128-SHA\",\n      MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_NODTLS },\n#endif\n#endif /* MBEDTLS_ARC4_C */\n#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)\n#if defined(MBEDTLS_AES_C)\n#if defined(MBEDTLS_SHA1_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, \"TLS-ECDH-RSA-WITH-AES-128-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n    { MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, \"TLS-ECDH-RSA-WITH-AES-256-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_SHA1_C */\n#if defined(MBEDTLS_SHA256_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, \"TLS-ECDH-RSA-WITH-AES-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#if defined(MBEDTLS_GCM_C)\n    { MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, \"TLS-ECDH-RSA-WITH-AES-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, \"TLS-ECDH-RSA-WITH-AES-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#if defined(MBEDTLS_GCM_C)\n    { MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, \"TLS-ECDH-RSA-WITH-AES-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_CAMELLIA_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256, \"TLS-ECDH-RSA-WITH-CAMELLIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384, \"TLS-ECDH-RSA-WITH-CAMELLIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_GCM_C)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256, \"TLS-ECDH-RSA-WITH-CAMELLIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384, \"TLS-ECDH-RSA-WITH-CAMELLIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_CAMELLIA_C */\n\n#if defined(MBEDTLS_DES_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, \"TLS-ECDH-RSA-WITH-3DES-EDE-CBC-SHA\",\n      MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_ARC4_C)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA, \"TLS-ECDH-RSA-WITH-RC4-128-SHA\",\n      MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_NODTLS },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_ARC4_C */\n\n#if defined(MBEDTLS_CIPHER_NULL_CIPHER)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA, \"TLS-ECDH-RSA-WITH-NULL-SHA\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_NULL_CIPHER */\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)\n#if defined(MBEDTLS_AES_C)\n#if defined(MBEDTLS_SHA1_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, \"TLS-ECDH-ECDSA-WITH-AES-128-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, \"TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_SHA1_C */\n#if defined(MBEDTLS_SHA256_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, \"TLS-ECDH-ECDSA-WITH-AES-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#if defined(MBEDTLS_GCM_C)\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, \"TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, \"TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#if defined(MBEDTLS_GCM_C)\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, \"TLS-ECDH-ECDSA-WITH-AES-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_CAMELLIA_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, \"TLS-ECDH-ECDSA-WITH-CAMELLIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, \"TLS-ECDH-ECDSA-WITH-CAMELLIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_GCM_C)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256, \"TLS-ECDH-ECDSA-WITH-CAMELLIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384, \"TLS-ECDH-ECDSA-WITH-CAMELLIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_CAMELLIA_C */\n\n#if defined(MBEDTLS_DES_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, \"TLS-ECDH-ECDSA-WITH-3DES-EDE-CBC-SHA\",\n      MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_ARC4_C)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA, \"TLS-ECDH-ECDSA-WITH-RC4-128-SHA\",\n      MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_NODTLS },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_ARC4_C */\n\n#if defined(MBEDTLS_CIPHER_NULL_CIPHER)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA, \"TLS-ECDH-ECDSA-WITH-NULL-SHA\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_NULL_CIPHER */\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)\n#if defined(MBEDTLS_AES_C)\n#if defined(MBEDTLS_GCM_C)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256, \"TLS-PSK-WITH-AES-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384, \"TLS-PSK-WITH-AES-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_GCM_C */\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256, \"TLS-PSK-WITH-AES-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384, \"TLS-PSK-WITH-AES-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA, \"TLS-PSK-WITH-AES-128-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n\n    { MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA, \"TLS-PSK-WITH-AES-256-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#if defined(MBEDTLS_CCM_C)\n    { MBEDTLS_TLS_PSK_WITH_AES_256_CCM, \"TLS-PSK-WITH-AES-256-CCM\",\n      MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n    { MBEDTLS_TLS_PSK_WITH_AES_256_CCM_8, \"TLS-PSK-WITH-AES-256-CCM-8\",\n      MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_SHORT_TAG },\n    { MBEDTLS_TLS_PSK_WITH_AES_128_CCM, \"TLS-PSK-WITH-AES-128-CCM\",\n      MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n    { MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8, \"TLS-PSK-WITH-AES-128-CCM-8\",\n      MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_SHORT_TAG },\n#endif /* MBEDTLS_CCM_C */\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_CAMELLIA_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256, \"TLS-PSK-WITH-CAMELLIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384, \"TLS-PSK-WITH-CAMELLIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_GCM_C)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256, \"TLS-PSK-WITH-CAMELLIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384, \"TLS-PSK-WITH-CAMELLIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_CAMELLIA_C */\n\n#if defined(MBEDTLS_DES_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA, \"TLS-PSK-WITH-3DES-EDE-CBC-SHA\",\n      MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_ARC4_C)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_PSK_WITH_RC4_128_SHA, \"TLS-PSK-WITH-RC4-128-SHA\",\n      MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_NODTLS },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_ARC4_C */\n#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)\n#if defined(MBEDTLS_AES_C)\n#if defined(MBEDTLS_GCM_C)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256, \"TLS-DHE-PSK-WITH-AES-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384, \"TLS-DHE-PSK-WITH-AES-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_GCM_C */\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256, \"TLS-DHE-PSK-WITH-AES-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, \"TLS-DHE-PSK-WITH-AES-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA, \"TLS-DHE-PSK-WITH-AES-128-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n\n    { MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA, \"TLS-DHE-PSK-WITH-AES-256-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#if defined(MBEDTLS_CCM_C)\n    { MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM, \"TLS-DHE-PSK-WITH-AES-256-CCM\",\n      MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n    { MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM_8, \"TLS-DHE-PSK-WITH-AES-256-CCM-8\",\n      MBEDTLS_CIPHER_AES_256_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_SHORT_TAG },\n    { MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM, \"TLS-DHE-PSK-WITH-AES-128-CCM\",\n      MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n    { MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM_8, \"TLS-DHE-PSK-WITH-AES-128-CCM-8\",\n      MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_SHORT_TAG },\n#endif /* MBEDTLS_CCM_C */\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_CAMELLIA_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, \"TLS-DHE-PSK-WITH-CAMELLIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, \"TLS-DHE-PSK-WITH-CAMELLIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_GCM_C)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256, \"TLS-DHE-PSK-WITH-CAMELLIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384, \"TLS-DHE-PSK-WITH-CAMELLIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_CAMELLIA_C */\n\n#if defined(MBEDTLS_DES_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA, \"TLS-DHE-PSK-WITH-3DES-EDE-CBC-SHA\",\n      MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_ARC4_C)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA, \"TLS-DHE-PSK-WITH-RC4-128-SHA\",\n      MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_NODTLS },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_ARC4_C */\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)\n#if defined(MBEDTLS_AES_C)\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, \"TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384, \"TLS-ECDHE-PSK-WITH-AES-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA, \"TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n\n    { MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA, \"TLS-ECDHE-PSK-WITH-AES-256-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_CAMELLIA_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, \"TLS-ECDHE-PSK-WITH-CAMELLIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, \"TLS-ECDHE-PSK-WITH-CAMELLIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_CAMELLIA_C */\n\n#if defined(MBEDTLS_DES_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA, \"TLS-ECDHE-PSK-WITH-3DES-EDE-CBC-SHA\",\n      MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_ARC4_C)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA, \"TLS-ECDHE-PSK-WITH-RC4-128-SHA\",\n      MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_NODTLS },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_ARC4_C */\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)\n#if defined(MBEDTLS_AES_C)\n#if defined(MBEDTLS_GCM_C)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256, \"TLS-RSA-PSK-WITH-AES-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_AES_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384, \"TLS-RSA-PSK-WITH-AES-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_AES_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_GCM_C */\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, \"TLS-RSA-PSK-WITH-AES-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, \"TLS-RSA-PSK-WITH-AES-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA, \"TLS-RSA-PSK-WITH-AES-128-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_128_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n\n    { MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA, \"TLS-RSA-PSK-WITH-AES-256-CBC-SHA\",\n      MBEDTLS_CIPHER_AES_256_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_AES_C */\n\n#if defined(MBEDTLS_CAMELLIA_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256, \"TLS-RSA-PSK-WITH-CAMELLIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384, \"TLS-RSA-PSK-WITH-CAMELLIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n#if defined(MBEDTLS_GCM_C)\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256, \"TLS-RSA-PSK-WITH-CAMELLIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_CAMELLIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384, \"TLS-RSA-PSK-WITH-CAMELLIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_CAMELLIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_GCM_C */\n#endif /* MBEDTLS_CAMELLIA_C */\n\n#if defined(MBEDTLS_DES_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, \"TLS-RSA-PSK-WITH-3DES-EDE-CBC-SHA\",\n      MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_DES_C */\n\n#if defined(MBEDTLS_ARC4_C)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA, \"TLS-RSA-PSK-WITH-RC4-128-SHA\",\n      MBEDTLS_CIPHER_ARC4_128, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_NODTLS },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_ARC4_C */\n#endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n#if defined(MBEDTLS_AES_C)\n#if defined(MBEDTLS_CCM_C)\n    { MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8, \"TLS-ECJPAKE-WITH-AES-128-CCM-8\",\n      MBEDTLS_CIPHER_AES_128_CCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECJPAKE,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_SHORT_TAG },\n#endif /* MBEDTLS_CCM_C */\n#endif /* MBEDTLS_AES_C */\n#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n\n#if defined(MBEDTLS_ENABLE_WEAK_CIPHERSUITES)\n#if defined(MBEDTLS_CIPHER_NULL_CIPHER)\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)\n#if defined(MBEDTLS_MD5_C)\n    { MBEDTLS_TLS_RSA_WITH_NULL_MD5, \"TLS-RSA-WITH-NULL-MD5\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_MD5, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif\n\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_RSA_WITH_NULL_SHA, \"TLS-RSA-WITH-NULL-SHA\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif\n\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_RSA_WITH_NULL_SHA256, \"TLS-RSA-WITH-NULL-SHA256\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif\n#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_PSK_WITH_NULL_SHA, \"TLS-PSK-WITH-NULL-SHA\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif /* MBEDTLS_SHA1_C */\n\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_PSK_WITH_NULL_SHA256, \"TLS-PSK-WITH-NULL-SHA256\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_PSK_WITH_NULL_SHA384, \"TLS-PSK-WITH-NULL-SHA384\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif\n#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA, \"TLS-DHE-PSK-WITH-NULL-SHA\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif /* MBEDTLS_SHA1_C */\n\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA256, \"TLS-DHE-PSK-WITH-NULL-SHA256\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA384, \"TLS-DHE-PSK-WITH-NULL-SHA384\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA, \"TLS-ECDHE-PSK-WITH-NULL-SHA\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif /* MBEDTLS_SHA1_C */\n\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256, \"TLS-ECDHE-PSK-WITH-NULL-SHA256\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384, \"TLS-ECDHE-PSK-WITH-NULL-SHA384\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA, \"TLS-RSA-PSK-WITH-NULL-SHA\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif /* MBEDTLS_SHA1_C */\n\n#if defined(MBEDTLS_SHA256_C)\n    { MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA256, \"TLS-RSA-PSK-WITH-NULL-SHA256\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif\n\n#if defined(MBEDTLS_SHA512_C)\n    { MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA384, \"TLS-RSA-PSK-WITH-NULL-SHA384\",\n      MBEDTLS_CIPHER_NULL, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif\n#endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */\n#endif /* MBEDTLS_CIPHER_NULL_CIPHER */\n\n#if defined(MBEDTLS_DES_C)\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA, \"TLS-DHE-RSA-WITH-DES-CBC-SHA\",\n      MBEDTLS_CIPHER_DES_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)\n#if defined(MBEDTLS_SHA1_C)\n    { MBEDTLS_TLS_RSA_WITH_DES_CBC_SHA, \"TLS-RSA-WITH-DES-CBC-SHA\",\n      MBEDTLS_CIPHER_DES_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_CIPHERSUITE_WEAK },\n#endif /* MBEDTLS_SHA1_C */\n#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* MBEDTLS_DES_C */\n#endif /* MBEDTLS_ENABLE_WEAK_CIPHERSUITES */\n\n#if defined(MBEDTLS_ARIA_C)\n\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)\n\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384,\n             \"TLS-RSA-WITH-ARIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384,\n             \"TLS-RSA-WITH-ARIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256,\n             \"TLS-RSA-WITH-ARIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256,\n             \"TLS-RSA-WITH-ARIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n\n#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)\n\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384,\n             \"TLS-RSA-PSK-WITH-ARIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384,\n             \"TLS-RSA-PSK-WITH-ARIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256,\n             \"TLS-RSA-PSK-WITH-ARIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256,\n             \"TLS-RSA-PSK-WITH-ARIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_RSA_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n\n#endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)\n\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384,\n             \"TLS-PSK-WITH-ARIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384,MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384,\n             \"TLS-PSK-WITH-ARIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256,\n             \"TLS-PSK-WITH-ARIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256,\n             \"TLS-PSK-WITH-ARIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n\n#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)\n\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384,\n             \"TLS-ECDH-RSA-WITH-ARIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384,\n             \"TLS-ECDH-RSA-WITH-ARIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256,\n             \"TLS-ECDH-RSA-WITH-ARIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256,\n             \"TLS-ECDH-RSA-WITH-ARIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)\n\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384,\n             \"TLS-ECDHE-RSA-WITH-ARIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384,\n             \"TLS-ECDHE-RSA-WITH-ARIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256,\n             \"TLS-ECDHE-RSA-WITH-ARIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256,\n             \"TLS-ECDHE-RSA-WITH-ARIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)\n\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384,\n             \"TLS-ECDHE-PSK-WITH-ARIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256,\n             \"TLS-ECDHE-PSK-WITH-ARIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)\n\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384,\n             \"TLS-ECDHE-ECDSA-WITH-ARIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384,\n             \"TLS-ECDHE-ECDSA-WITH-ARIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256,\n             \"TLS-ECDHE-ECDSA-WITH-ARIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256,\n             \"TLS-ECDHE-ECDSA-WITH-ARIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)\n\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384,\n             \"TLS-ECDH-ECDSA-WITH-ARIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384,\n             \"TLS-ECDH-ECDSA-WITH-ARIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256,\n             \"TLS-ECDH-ECDSA-WITH-ARIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256,\n             \"TLS-ECDH-ECDSA-WITH-ARIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)\n\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384,\n             \"TLS-DHE-RSA-WITH-ARIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384,\n             \"TLS-DHE-RSA-WITH-ARIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256,\n             \"TLS-DHE-RSA-WITH-ARIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256,\n             \"TLS-DHE-RSA-WITH-ARIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_RSA,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)\n\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384,\n             \"TLS-DHE-PSK-WITH-ARIA-256-GCM-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_GCM, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA512_C))\n    { MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384,\n             \"TLS-DHE-PSK-WITH-ARIA-256-CBC-SHA384\",\n      MBEDTLS_CIPHER_ARIA_256_CBC, MBEDTLS_MD_SHA384, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_GCM_C) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256,\n             \"TLS-DHE-PSK-WITH-ARIA-128-GCM-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_GCM, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n#if (defined(MBEDTLS_CIPHER_MODE_CBC) && defined(MBEDTLS_SHA256_C))\n    { MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256,\n             \"TLS-DHE-PSK-WITH-ARIA-128-CBC-SHA256\",\n      MBEDTLS_CIPHER_ARIA_128_CBC, MBEDTLS_MD_SHA256, MBEDTLS_KEY_EXCHANGE_DHE_PSK,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,\n      0 },\n#endif\n\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */\n\n#endif /* MBEDTLS_ARIA_C */\n\n\n    { 0, \"\",\n      MBEDTLS_CIPHER_NONE, MBEDTLS_MD_NONE, MBEDTLS_KEY_EXCHANGE_NONE,\n      0, 0, 0, 0, 0 }\n};\n\n#if defined(MBEDTLS_SSL_CIPHERSUITES)\nconst int *mbedtls_ssl_list_ciphersuites( void )\n{\n    return( ciphersuite_preference );\n}\n#else\n#define MAX_CIPHERSUITES    sizeof( ciphersuite_definitions     ) /         \\\n                            sizeof( ciphersuite_definitions[0]  )\nstatic int supported_ciphersuites[MAX_CIPHERSUITES];\nstatic int supported_init = 0;\n\nconst int *mbedtls_ssl_list_ciphersuites( void )\n{\n    /*\n     * On initial call filter out all ciphersuites not supported by current\n     * build based on presence in the ciphersuite_definitions.\n     */\n    if( supported_init == 0 )\n    {\n        const int *p;\n        int *q;\n\n        for( p = ciphersuite_preference, q = supported_ciphersuites;\n             *p != 0 && q < supported_ciphersuites + MAX_CIPHERSUITES - 1;\n             p++ )\n        {\n#if defined(MBEDTLS_REMOVE_ARC4_CIPHERSUITES)\n            const mbedtls_ssl_ciphersuite_t *cs_info;\n            if( ( cs_info = mbedtls_ssl_ciphersuite_from_id( *p ) ) != NULL &&\n                cs_info->cipher != MBEDTLS_CIPHER_ARC4_128 )\n#else\n            if( mbedtls_ssl_ciphersuite_from_id( *p ) != NULL )\n#endif\n                *(q++) = *p;\n        }\n        *q = 0;\n\n        supported_init = 1;\n    }\n\n    return( supported_ciphersuites );\n}\n#endif /* MBEDTLS_SSL_CIPHERSUITES */\n\nconst mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_string(\n                                                const char *ciphersuite_name )\n{\n    const mbedtls_ssl_ciphersuite_t *cur = ciphersuite_definitions;\n\n    if( NULL == ciphersuite_name )\n        return( NULL );\n\n    while( cur->id != 0 )\n    {\n        if( 0 == strcmp( cur->name, ciphersuite_name ) )\n            return( cur );\n\n        cur++;\n    }\n\n    return( NULL );\n}\n\nconst mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_id( int ciphersuite )\n{\n    const mbedtls_ssl_ciphersuite_t *cur = ciphersuite_definitions;\n\n    while( cur->id != 0 )\n    {\n        if( cur->id == ciphersuite )\n            return( cur );\n\n        cur++;\n    }\n\n    return( NULL );\n}\n\nconst char *mbedtls_ssl_get_ciphersuite_name( const int ciphersuite_id )\n{\n    const mbedtls_ssl_ciphersuite_t *cur;\n\n    cur = mbedtls_ssl_ciphersuite_from_id( ciphersuite_id );\n\n    if( cur == NULL )\n        return( \"unknown\" );\n\n    return( cur->name );\n}\n\nint mbedtls_ssl_get_ciphersuite_id( const char *ciphersuite_name )\n{\n    const mbedtls_ssl_ciphersuite_t *cur;\n\n    cur = mbedtls_ssl_ciphersuite_from_string( ciphersuite_name );\n\n    if( cur == NULL )\n        return( 0 );\n\n    return( cur->id );\n}\n\n#if defined(MBEDTLS_PK_C)\nmbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_pk_alg( const mbedtls_ssl_ciphersuite_t *info )\n{\n    switch( info->key_exchange )\n    {\n        case MBEDTLS_KEY_EXCHANGE_RSA:\n        case MBEDTLS_KEY_EXCHANGE_DHE_RSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:\n        case MBEDTLS_KEY_EXCHANGE_RSA_PSK:\n            return( MBEDTLS_PK_RSA );\n\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:\n            return( MBEDTLS_PK_ECDSA );\n\n        case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:\n            return( MBEDTLS_PK_ECKEY );\n\n        default:\n            return( MBEDTLS_PK_NONE );\n    }\n}\n\nmbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg( const mbedtls_ssl_ciphersuite_t *info )\n{\n    switch( info->key_exchange )\n    {\n        case MBEDTLS_KEY_EXCHANGE_RSA:\n        case MBEDTLS_KEY_EXCHANGE_DHE_RSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:\n            return( MBEDTLS_PK_RSA );\n\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:\n            return( MBEDTLS_PK_ECDSA );\n\n        default:\n            return( MBEDTLS_PK_NONE );\n    }\n}\n\n#endif /* MBEDTLS_PK_C */\n\n#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)\nint mbedtls_ssl_ciphersuite_uses_ec( const mbedtls_ssl_ciphersuite_t *info )\n{\n    switch( info->key_exchange )\n    {\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:\n        case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:\n        case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:\n            return( 1 );\n\n        default:\n            return( 0 );\n    }\n}\n#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)\nint mbedtls_ssl_ciphersuite_uses_psk( const mbedtls_ssl_ciphersuite_t *info )\n{\n    switch( info->key_exchange )\n    {\n        case MBEDTLS_KEY_EXCHANGE_PSK:\n        case MBEDTLS_KEY_EXCHANGE_RSA_PSK:\n        case MBEDTLS_KEY_EXCHANGE_DHE_PSK:\n        case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:\n            return( 1 );\n\n        default:\n            return( 0 );\n    }\n}\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */\n\n#endif /* MBEDTLS_SSL_TLS_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/ssl_cli.c",
    "content": "/*\n *  SSLv3/TLSv1 client-side functions\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_SSL_CLI_C)\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc    calloc\n#define mbedtls_free      free\n#endif\n\n#include \"mbedtls/debug.h\"\n#include \"mbedtls/ssl.h\"\n#include \"mbedtls/ssl_internal.h\"\n\n#include <string.h>\n\n#include <stdint.h>\n\n#if defined(MBEDTLS_HAVE_TIME)\n#include \"mbedtls/platform_time.h\"\n#endif\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\n#include \"mbedtls/platform_util.h\"\n#endif\n\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\nstatic void ssl_write_hostname_ext( mbedtls_ssl_context *ssl,\n                                    unsigned char *buf,\n                                    size_t *olen )\n{\n    unsigned char *p = buf;\n    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;\n    size_t hostname_len;\n\n    *olen = 0;\n\n    if( ssl->hostname == NULL )\n        return;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, adding server name extension: %s\",\n                   ssl->hostname ) );\n\n    hostname_len = strlen( ssl->hostname );\n\n    if( end < p || (size_t)( end - p ) < hostname_len + 9 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"buffer too small\" ) );\n        return;\n    }\n\n    /*\n     * Sect. 3, RFC 6066 (TLS Extensions Definitions)\n     *\n     * In order to provide any of the server names, clients MAY include an\n     * extension of type \"server_name\" in the (extended) client hello. The\n     * \"extension_data\" field of this extension SHALL contain\n     * \"ServerNameList\" where:\n     *\n     * struct {\n     *     NameType name_type;\n     *     select (name_type) {\n     *         case host_name: HostName;\n     *     } name;\n     * } ServerName;\n     *\n     * enum {\n     *     host_name(0), (255)\n     * } NameType;\n     *\n     * opaque HostName<1..2^16-1>;\n     *\n     * struct {\n     *     ServerName server_name_list<1..2^16-1>\n     * } ServerNameList;\n     *\n     */\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME      ) & 0xFF );\n\n    *p++ = (unsigned char)( ( (hostname_len + 5) >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( (hostname_len + 5)      ) & 0xFF );\n\n    *p++ = (unsigned char)( ( (hostname_len + 3) >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( (hostname_len + 3)      ) & 0xFF );\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME ) & 0xFF );\n    *p++ = (unsigned char)( ( hostname_len >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( hostname_len      ) & 0xFF );\n\n    memcpy( p, ssl->hostname, hostname_len );\n\n    *olen = hostname_len + 9;\n}\n#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\nstatic void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl,\n                                         unsigned char *buf,\n                                         size_t *olen )\n{\n    unsigned char *p = buf;\n    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;\n\n    *olen = 0;\n\n    /* We're always including an TLS_EMPTY_RENEGOTIATION_INFO_SCSV in the\n     * initial ClientHello, in which case also adding the renegotiation\n     * info extension is NOT RECOMMENDED as per RFC 5746 Section 3.4. */\n    if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )\n        return;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, adding renegotiation extension\" ) );\n\n    if( end < p || (size_t)( end - p ) < 5 + ssl->verify_data_len )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"buffer too small\" ) );\n        return;\n    }\n\n    /*\n     * Secure renegotiation\n     */\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO      ) & 0xFF );\n\n    *p++ = 0x00;\n    *p++ = ( ssl->verify_data_len + 1 ) & 0xFF;\n    *p++ = ssl->verify_data_len & 0xFF;\n\n    memcpy( p, ssl->own_verify_data, ssl->verify_data_len );\n\n    *olen = 5 + ssl->verify_data_len;\n}\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n\n/*\n * Only if we handle at least one key exchange that needs signatures.\n */\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \\\n    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\nstatic void ssl_write_signature_algorithms_ext( mbedtls_ssl_context *ssl,\n                                                unsigned char *buf,\n                                                size_t *olen )\n{\n    unsigned char *p = buf;\n    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;\n    size_t sig_alg_len = 0;\n    const int *md;\n#if defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C)\n    unsigned char *sig_alg_list = buf + 6;\n#endif\n\n    *olen = 0;\n\n    if( ssl->conf->max_minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )\n        return;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, adding signature_algorithms extension\" ) );\n\n    for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )\n    {\n#if defined(MBEDTLS_ECDSA_C)\n        sig_alg_len += 2;\n#endif\n#if defined(MBEDTLS_RSA_C)\n        sig_alg_len += 2;\n#endif\n    }\n\n    if( end < p || (size_t)( end - p ) < sig_alg_len + 6 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"buffer too small\" ) );\n        return;\n    }\n\n    /*\n     * Prepare signature_algorithms extension (TLS 1.2)\n     */\n    sig_alg_len = 0;\n\n    for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )\n    {\n#if defined(MBEDTLS_ECDSA_C)\n        sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );\n        sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_ECDSA;\n#endif\n#if defined(MBEDTLS_RSA_C)\n        sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );\n        sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_RSA;\n#endif\n    }\n\n    /*\n     * enum {\n     *     none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5),\n     *     sha512(6), (255)\n     * } HashAlgorithm;\n     *\n     * enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }\n     *   SignatureAlgorithm;\n     *\n     * struct {\n     *     HashAlgorithm hash;\n     *     SignatureAlgorithm signature;\n     * } SignatureAndHashAlgorithm;\n     *\n     * SignatureAndHashAlgorithm\n     *   supported_signature_algorithms<2..2^16-2>;\n     */\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG      ) & 0xFF );\n\n    *p++ = (unsigned char)( ( ( sig_alg_len + 2 ) >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( ( sig_alg_len + 2 )      ) & 0xFF );\n\n    *p++ = (unsigned char)( ( sig_alg_len >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( sig_alg_len      ) & 0xFF );\n\n    *olen = 6 + sig_alg_len;\n}\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&\n          MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */\n\n#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\nstatic void ssl_write_supported_elliptic_curves_ext( mbedtls_ssl_context *ssl,\n                                                     unsigned char *buf,\n                                                     size_t *olen )\n{\n    unsigned char *p = buf;\n    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;\n    unsigned char *elliptic_curve_list = p + 6;\n    size_t elliptic_curve_len = 0;\n    const mbedtls_ecp_curve_info *info;\n#if defined(MBEDTLS_ECP_C)\n    const mbedtls_ecp_group_id *grp_id;\n#else\n    ((void) ssl);\n#endif\n\n    *olen = 0;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, adding supported_elliptic_curves extension\" ) );\n\n#if defined(MBEDTLS_ECP_C)\n    for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ )\n#else\n    for( info = mbedtls_ecp_curve_list(); info->grp_id != MBEDTLS_ECP_DP_NONE; info++ )\n#endif\n    {\n#if defined(MBEDTLS_ECP_C)\n        info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );\n#endif\n        if( info == NULL )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"invalid curve in ssl configuration\" ) );\n            return;\n        }\n\n        elliptic_curve_len += 2;\n    }\n\n    if( end < p || (size_t)( end - p ) < 6 + elliptic_curve_len )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"buffer too small\" ) );\n        return;\n    }\n\n    elliptic_curve_len = 0;\n\n#if defined(MBEDTLS_ECP_C)\n    for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ )\n#else\n    for( info = mbedtls_ecp_curve_list(); info->grp_id != MBEDTLS_ECP_DP_NONE; info++ )\n#endif\n    {\n#if defined(MBEDTLS_ECP_C)\n        info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );\n#endif\n        elliptic_curve_list[elliptic_curve_len++] = info->tls_id >> 8;\n        elliptic_curve_list[elliptic_curve_len++] = info->tls_id & 0xFF;\n    }\n\n    if( elliptic_curve_len == 0 )\n        return;\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES      ) & 0xFF );\n\n    *p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( ( elliptic_curve_len + 2 )      ) & 0xFF );\n\n    *p++ = (unsigned char)( ( ( elliptic_curve_len     ) >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( ( elliptic_curve_len     )      ) & 0xFF );\n\n    *olen = 6 + elliptic_curve_len;\n}\n\nstatic void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl,\n                                                   unsigned char *buf,\n                                                   size_t *olen )\n{\n    unsigned char *p = buf;\n    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;\n\n    *olen = 0;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, adding supported_point_formats extension\" ) );\n\n    if( end < p || (size_t)( end - p ) < 6 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"buffer too small\" ) );\n        return;\n    }\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS      ) & 0xFF );\n\n    *p++ = 0x00;\n    *p++ = 2;\n\n    *p++ = 1;\n    *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;\n\n    *olen = 6;\n}\n#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||\n          MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\nstatic void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl,\n                                        unsigned char *buf,\n                                        size_t *olen )\n{\n    int ret;\n    unsigned char *p = buf;\n    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;\n    size_t kkpp_len;\n\n    *olen = 0;\n\n    /* Skip costly extension if we can't use EC J-PAKE anyway */\n    if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )\n        return;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, adding ecjpake_kkpp extension\" ) );\n\n    if( end - p < 4 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"buffer too small\" ) );\n        return;\n    }\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP      ) & 0xFF );\n\n    /*\n     * We may need to send ClientHello multiple times for Hello verification.\n     * We don't want to compute fresh values every time (both for performance\n     * and consistency reasons), so cache the extension content.\n     */\n    if( ssl->handshake->ecjpake_cache == NULL ||\n        ssl->handshake->ecjpake_cache_len == 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"generating new ecjpake parameters\" ) );\n\n        ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx,\n                                        p + 2, end - p - 2, &kkpp_len,\n                                        ssl->conf->f_rng, ssl->conf->p_rng );\n        if( ret != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1 , \"mbedtls_ecjpake_write_round_one\", ret );\n            return;\n        }\n\n        ssl->handshake->ecjpake_cache = mbedtls_calloc( 1, kkpp_len );\n        if( ssl->handshake->ecjpake_cache == NULL )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"allocation failed\" ) );\n            return;\n        }\n\n        memcpy( ssl->handshake->ecjpake_cache, p + 2, kkpp_len );\n        ssl->handshake->ecjpake_cache_len = kkpp_len;\n    }\n    else\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"re-using cached ecjpake parameters\" ) );\n\n        kkpp_len = ssl->handshake->ecjpake_cache_len;\n\n        if( (size_t)( end - p - 2 ) < kkpp_len )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"buffer too small\" ) );\n            return;\n        }\n\n        memcpy( p + 2, ssl->handshake->ecjpake_cache, kkpp_len );\n    }\n\n    *p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( kkpp_len      ) & 0xFF );\n\n    *olen = kkpp_len + 4;\n}\n#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\nstatic void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl,\n                                               unsigned char *buf,\n                                               size_t *olen )\n{\n    unsigned char *p = buf;\n    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;\n\n    *olen = 0;\n\n    if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ) {\n        return;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, adding max_fragment_length extension\" ) );\n\n    if( end < p || (size_t)( end - p ) < 5 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"buffer too small\" ) );\n        return;\n    }\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH      ) & 0xFF );\n\n    *p++ = 0x00;\n    *p++ = 1;\n\n    *p++ = ssl->conf->mfl_code;\n\n    *olen = 5;\n}\n#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */\n\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)\nstatic void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl,\n                                          unsigned char *buf, size_t *olen )\n{\n    unsigned char *p = buf;\n    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;\n\n    *olen = 0;\n\n    if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED )\n    {\n        return;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, adding truncated_hmac extension\" ) );\n\n    if( end < p || (size_t)( end - p ) < 4 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"buffer too small\" ) );\n        return;\n    }\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC      ) & 0xFF );\n\n    *p++ = 0x00;\n    *p++ = 0x00;\n\n    *olen = 4;\n}\n#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */\n\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\nstatic void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,\n                                       unsigned char *buf, size_t *olen )\n{\n    unsigned char *p = buf;\n    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;\n\n    *olen = 0;\n\n    if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||\n        ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )\n    {\n        return;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, adding encrypt_then_mac \"\n                        \"extension\" ) );\n\n    if( end < p || (size_t)( end - p ) < 4 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"buffer too small\" ) );\n        return;\n    }\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC      ) & 0xFF );\n\n    *p++ = 0x00;\n    *p++ = 0x00;\n\n    *olen = 4;\n}\n#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */\n\n#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)\nstatic void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl,\n                                       unsigned char *buf, size_t *olen )\n{\n    unsigned char *p = buf;\n    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;\n\n    *olen = 0;\n\n    if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||\n        ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )\n    {\n        return;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, adding extended_master_secret \"\n                        \"extension\" ) );\n\n    if( end < p || (size_t)( end - p ) < 4 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"buffer too small\" ) );\n        return;\n    }\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET      ) & 0xFF );\n\n    *p++ = 0x00;\n    *p++ = 0x00;\n\n    *olen = 4;\n}\n#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\nstatic void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl,\n                                          unsigned char *buf, size_t *olen )\n{\n    unsigned char *p = buf;\n    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;\n    size_t tlen = ssl->session_negotiate->ticket_len;\n\n    *olen = 0;\n\n    if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED )\n    {\n        return;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, adding session ticket extension\" ) );\n\n    if( end < p || (size_t)( end - p ) < 4 + tlen )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"buffer too small\" ) );\n        return;\n    }\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET      ) & 0xFF );\n\n    *p++ = (unsigned char)( ( tlen >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( tlen      ) & 0xFF );\n\n    *olen = 4;\n\n    if( ssl->session_negotiate->ticket == NULL || tlen == 0 )\n    {\n        return;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"sending session ticket of length %d\", tlen ) );\n\n    memcpy( p, ssl->session_negotiate->ticket, tlen );\n\n    *olen += tlen;\n}\n#endif /* MBEDTLS_SSL_SESSION_TICKETS */\n\n#if defined(MBEDTLS_SSL_ALPN)\nstatic void ssl_write_alpn_ext( mbedtls_ssl_context *ssl,\n                                unsigned char *buf, size_t *olen )\n{\n    unsigned char *p = buf;\n    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;\n    size_t alpnlen = 0;\n    const char **cur;\n\n    *olen = 0;\n\n    if( ssl->conf->alpn_list == NULL )\n    {\n        return;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, adding alpn extension\" ) );\n\n    for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )\n        alpnlen += (unsigned char)( strlen( *cur ) & 0xFF ) + 1;\n\n    if( end < p || (size_t)( end - p ) < 6 + alpnlen )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"buffer too small\" ) );\n        return;\n    }\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN      ) & 0xFF );\n\n    /*\n     * opaque ProtocolName<1..2^8-1>;\n     *\n     * struct {\n     *     ProtocolName protocol_name_list<2..2^16-1>\n     * } ProtocolNameList;\n     */\n\n    /* Skip writing extension and list length for now */\n    p += 4;\n\n    for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )\n    {\n        *p = (unsigned char)( strlen( *cur ) & 0xFF );\n        memcpy( p + 1, *cur, *p );\n        p += 1 + *p;\n    }\n\n    *olen = p - buf;\n\n    /* List length = olen - 2 (ext_type) - 2 (ext_len) - 2 (list_len) */\n    buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF );\n    buf[5] = (unsigned char)( ( ( *olen - 6 )      ) & 0xFF );\n\n    /* Extension length = olen - 2 (ext_type) - 2 (ext_len) */\n    buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF );\n    buf[3] = (unsigned char)( ( ( *olen - 4 )      ) & 0xFF );\n}\n#endif /* MBEDTLS_SSL_ALPN */\n\n/*\n * Generate random bytes for ClientHello\n */\nstatic int ssl_generate_random( mbedtls_ssl_context *ssl )\n{\n    int ret;\n    unsigned char *p = ssl->handshake->randbytes;\n#if defined(MBEDTLS_HAVE_TIME)\n    mbedtls_time_t t;\n#endif\n\n    /*\n     * When responding to a verify request, MUST reuse random (RFC 6347 4.2.1)\n     */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&\n        ssl->handshake->verify_cookie != NULL )\n    {\n        return( 0 );\n    }\n#endif\n\n#if defined(MBEDTLS_HAVE_TIME)\n    t = mbedtls_time( NULL );\n    *p++ = (unsigned char)( t >> 24 );\n    *p++ = (unsigned char)( t >> 16 );\n    *p++ = (unsigned char)( t >>  8 );\n    *p++ = (unsigned char)( t       );\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, current time: %lu\", t ) );\n#else\n    if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 )\n        return( ret );\n\n    p += 4;\n#endif /* MBEDTLS_HAVE_TIME */\n\n    if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 )\n        return( ret );\n\n    return( 0 );\n}\n\n/**\n * \\brief           Validate cipher suite against config in SSL context.\n *\n * \\param suite_info    cipher suite to validate\n * \\param ssl           SSL context\n * \\param min_minor_ver Minimal minor version to accept a cipher suite\n * \\param max_minor_ver Maximal minor version to accept a cipher suite\n *\n * \\return          0 if valid, else 1\n */\nstatic int ssl_validate_ciphersuite( const mbedtls_ssl_ciphersuite_t * suite_info,\n                                     const mbedtls_ssl_context * ssl,\n                                     int min_minor_ver, int max_minor_ver )\n{\n    (void) ssl;\n    if( suite_info == NULL )\n        return( 1 );\n\n    if( suite_info->min_minor_ver > max_minor_ver ||\n            suite_info->max_minor_ver < min_minor_ver )\n        return( 1 );\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&\n            ( suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )\n        return( 1 );\n#endif\n\n#if defined(MBEDTLS_ARC4_C)\n    if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&\n            suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )\n        return( 1 );\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&\n            mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )\n        return( 1 );\n#endif\n\n    return( 0 );\n}\n\nstatic int ssl_write_client_hello( mbedtls_ssl_context *ssl )\n{\n    int ret;\n    size_t i, n, olen, ext_len = 0;\n    unsigned char *buf;\n    unsigned char *p, *q;\n    unsigned char offer_compress;\n    const int *ciphersuites;\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write client hello\" ) );\n\n    if( ssl->conf->f_rng == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"no RNG provided\") );\n        return( MBEDTLS_ERR_SSL_NO_RNG );\n    }\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )\n#endif\n    {\n        ssl->major_ver = ssl->conf->min_major_ver;\n        ssl->minor_ver = ssl->conf->min_minor_ver;\n    }\n\n    if( ssl->conf->max_major_ver == 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"configured max major version is invalid, \"\n                            \"consider using mbedtls_ssl_config_defaults()\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n    }\n\n    /*\n     *     0  .   0   handshake type\n     *     1  .   3   handshake length\n     *     4  .   5   highest version supported\n     *     6  .   9   current UNIX time\n     *    10  .  37   random bytes\n     */\n    buf = ssl->out_msg;\n    p = buf + 4;\n\n    mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,\n                       ssl->conf->transport, p );\n    p += 2;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, max version: [%d:%d]\",\n                   buf[4], buf[5] ) );\n\n    if( ( ret = ssl_generate_random( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"ssl_generate_random\", ret );\n        return( ret );\n    }\n\n    memcpy( p, ssl->handshake->randbytes, 32 );\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"client hello, random bytes\", p, 32 );\n    p += 32;\n\n    /*\n     *    38  .  38   session id length\n     *    39  . 39+n  session id\n     *   39+n . 39+n  DTLS only: cookie length (1 byte)\n     *   40+n .  ..   DTSL only: cookie\n     *   ..   . ..    ciphersuitelist length (2 bytes)\n     *   ..   . ..    ciphersuitelist\n     *   ..   . ..    compression methods length (1 byte)\n     *   ..   . ..    compression methods\n     *   ..   . ..    extensions length (2 bytes)\n     *   ..   . ..    extensions\n     */\n    n = ssl->session_negotiate->id_len;\n\n    if( n < 16 || n > 32 ||\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n        ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||\n#endif\n        ssl->handshake->resume == 0 )\n    {\n        n = 0;\n    }\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\n    /*\n     * RFC 5077 section 3.4: \"When presenting a ticket, the client MAY\n     * generate and include a Session ID in the TLS ClientHello.\"\n     */\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )\n#endif\n    {\n        if( ssl->session_negotiate->ticket != NULL &&\n                ssl->session_negotiate->ticket_len != 0 )\n        {\n            ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id, 32 );\n\n            if( ret != 0 )\n                return( ret );\n\n            ssl->session_negotiate->id_len = n = 32;\n        }\n    }\n#endif /* MBEDTLS_SSL_SESSION_TICKETS */\n\n    *p++ = (unsigned char) n;\n\n    for( i = 0; i < n; i++ )\n        *p++ = ssl->session_negotiate->id[i];\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, session id len.: %d\", n ) );\n    MBEDTLS_SSL_DEBUG_BUF( 3,   \"client hello, session id\", buf + 39, n );\n\n    /*\n     * DTLS cookie\n     */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        if( ssl->handshake->verify_cookie == NULL )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"no verify cookie to send\" ) );\n            *p++ = 0;\n        }\n        else\n        {\n            MBEDTLS_SSL_DEBUG_BUF( 3, \"client hello, cookie\",\n                              ssl->handshake->verify_cookie,\n                              ssl->handshake->verify_cookie_len );\n\n            *p++ = ssl->handshake->verify_cookie_len;\n            memcpy( p, ssl->handshake->verify_cookie,\n                       ssl->handshake->verify_cookie_len );\n            p += ssl->handshake->verify_cookie_len;\n        }\n    }\n#endif\n\n    /*\n     * Ciphersuite list\n     */\n    ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];\n\n    /* Skip writing ciphersuite length for now */\n    n = 0;\n    q = p;\n    p += 2;\n\n    for( i = 0; ciphersuites[i] != 0; i++ )\n    {\n        ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuites[i] );\n\n        if( ssl_validate_ciphersuite( ciphersuite_info, ssl,\n                                      ssl->conf->min_minor_ver,\n                                      ssl->conf->max_minor_ver ) != 0 )\n            continue;\n\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, add ciphersuite: %04x\",\n                                    ciphersuites[i] ) );\n\n        n++;\n        *p++ = (unsigned char)( ciphersuites[i] >> 8 );\n        *p++ = (unsigned char)( ciphersuites[i]      );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, got %d ciphersuites (excluding SCSVs)\", n ) );\n\n    /*\n     * Add TLS_EMPTY_RENEGOTIATION_INFO_SCSV\n     */\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )\n#endif\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"adding EMPTY_RENEGOTIATION_INFO_SCSV\" ) );\n        *p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO >> 8 );\n        *p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO      );\n        n++;\n    }\n\n    /* Some versions of OpenSSL don't handle it correctly if not at end */\n#if defined(MBEDTLS_SSL_FALLBACK_SCSV)\n    if( ssl->conf->fallback == MBEDTLS_SSL_IS_FALLBACK )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"adding FALLBACK_SCSV\" ) );\n        *p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 );\n        *p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE      );\n        n++;\n    }\n#endif\n\n    *q++ = (unsigned char)( n >> 7 );\n    *q++ = (unsigned char)( n << 1 );\n\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n    offer_compress = 1;\n#else\n    offer_compress = 0;\n#endif\n\n    /*\n     * We don't support compression with DTLS right now: if many records come\n     * in the same datagram, uncompressing one could overwrite the next one.\n     * We don't want to add complexity for handling that case unless there is\n     * an actual need for it.\n     */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n        offer_compress = 0;\n#endif\n\n    if( offer_compress )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, compress len.: %d\", 2 ) );\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, compress alg.: %d %d\",\n                            MBEDTLS_SSL_COMPRESS_DEFLATE, MBEDTLS_SSL_COMPRESS_NULL ) );\n\n        *p++ = 2;\n        *p++ = MBEDTLS_SSL_COMPRESS_DEFLATE;\n        *p++ = MBEDTLS_SSL_COMPRESS_NULL;\n    }\n    else\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, compress len.: %d\", 1 ) );\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, compress alg.: %d\",\n                            MBEDTLS_SSL_COMPRESS_NULL ) );\n\n        *p++ = 1;\n        *p++ = MBEDTLS_SSL_COMPRESS_NULL;\n    }\n\n    // First write extensions, then the total length\n    //\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\n    ssl_write_hostname_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n    /* Note that TLS_EMPTY_RENEGOTIATION_INFO_SCSV is always added\n     * even if MBEDTLS_SSL_RENEGOTIATION is not defined. */\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \\\n    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n    ssl_write_signature_algorithms_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    ssl_write_supported_elliptic_curves_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n\n    ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\n    ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)\n    ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\n    ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)\n    ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n#if defined(MBEDTLS_SSL_ALPN)\n    ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\n    ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n    /* olen unused if all extensions are disabled */\n    ((void) olen);\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello, total extension length: %d\",\n                   ext_len ) );\n\n    if( ext_len > 0 )\n    {\n        *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF );\n        *p++ = (unsigned char)( ( ext_len      ) & 0xFF );\n        p += ext_len;\n    }\n\n    ssl->out_msglen  = p - buf;\n    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;\n    ssl->out_msg[0]  = MBEDTLS_SSL_HS_CLIENT_HELLO;\n\n    ssl->state++;\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n        mbedtls_ssl_send_flight_completed( ssl );\n#endif\n\n    if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_write_record\", ret );\n        return( ret );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write client hello\" ) );\n\n    return( 0 );\n}\n\nstatic int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl,\n                                         const unsigned char *buf,\n                                         size_t len )\n{\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )\n    {\n        /* Check verify-data in constant-time. The length OTOH is no secret */\n        if( len    != 1 + ssl->verify_data_len * 2 ||\n            buf[0] !=     ssl->verify_data_len * 2 ||\n            mbedtls_ssl_safer_memcmp( buf + 1,\n                          ssl->own_verify_data, ssl->verify_data_len ) != 0 ||\n            mbedtls_ssl_safer_memcmp( buf + 1 + ssl->verify_data_len,\n                          ssl->peer_verify_data, ssl->verify_data_len ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"non-matching renegotiation info\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n            return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n        }\n    }\n    else\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n    {\n        if( len != 1 || buf[0] != 0x00 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"non-zero length renegotiation info\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n            return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n        }\n\n        ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;\n    }\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\nstatic int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl,\n                                              const unsigned char *buf,\n                                              size_t len )\n{\n    /*\n     * server should use the extension only if we did,\n     * and if so the server's value should match ours (and len is always 1)\n     */\n    if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ||\n        len != 1 ||\n        buf[0] != ssl->conf->mfl_code )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"non-matching max fragment length extension\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */\n\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)\nstatic int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl,\n                                         const unsigned char *buf,\n                                         size_t len )\n{\n    if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED ||\n        len != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"non-matching truncated HMAC extension\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n\n    ((void) buf);\n\n    ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */\n\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\nstatic int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,\n                                         const unsigned char *buf,\n                                         size_t len )\n{\n    if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||\n        ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||\n        len != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"non-matching encrypt-then-MAC extension\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n\n    ((void) buf);\n\n    ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */\n\n#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)\nstatic int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl,\n                                         const unsigned char *buf,\n                                         size_t len )\n{\n    if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||\n        ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||\n        len != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"non-matching extended master secret extension\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n\n    ((void) buf);\n\n    ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\nstatic int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl,\n                                         const unsigned char *buf,\n                                         size_t len )\n{\n    if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED ||\n        len != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"non-matching session ticket extension\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n\n    ((void) buf);\n\n    ssl->handshake->new_session_ticket = 1;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_SESSION_TICKETS */\n\n#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\nstatic int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl,\n                                                  const unsigned char *buf,\n                                                  size_t len )\n{\n    size_t list_size;\n    const unsigned char *p;\n\n    if( len == 0 || (size_t)( buf[0] + 1 ) != len )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n    list_size = buf[0];\n\n    p = buf + 1;\n    while( list_size > 0 )\n    {\n        if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||\n            p[0] == MBEDTLS_ECP_PF_COMPRESSED )\n        {\n#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)\n            ssl->handshake->ecdh_ctx.point_format = p[0];\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n            ssl->handshake->ecjpake_ctx.point_format = p[0];\n#endif\n            MBEDTLS_SSL_DEBUG_MSG( 4, ( \"point format selected: %d\", p[0] ) );\n            return( 0 );\n        }\n\n        list_size--;\n        p++;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 1, ( \"no point format in common\" ) );\n    mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                    MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n    return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n}\n#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||\n          MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\nstatic int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl,\n                                   const unsigned char *buf,\n                                   size_t len )\n{\n    int ret;\n\n    if( ssl->transform_negotiate->ciphersuite_info->key_exchange !=\n        MBEDTLS_KEY_EXCHANGE_ECJPAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"skip ecjpake kkpp extension\" ) );\n        return( 0 );\n    }\n\n    /* If we got here, we no longer need our cached extension */\n    mbedtls_free( ssl->handshake->ecjpake_cache );\n    ssl->handshake->ecjpake_cache = NULL;\n    ssl->handshake->ecjpake_cache_len = 0;\n\n    if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx,\n                                                buf, len ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecjpake_read_round_one\", ret );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n        return( ret );\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n\n#if defined(MBEDTLS_SSL_ALPN)\nstatic int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,\n                               const unsigned char *buf, size_t len )\n{\n    size_t list_len, name_len;\n    const char **p;\n\n    /* If we didn't send it, the server shouldn't send it */\n    if( ssl->conf->alpn_list == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"non-matching ALPN extension\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n\n    /*\n     * opaque ProtocolName<1..2^8-1>;\n     *\n     * struct {\n     *     ProtocolName protocol_name_list<2..2^16-1>\n     * } ProtocolNameList;\n     *\n     * the \"ProtocolNameList\" MUST contain exactly one \"ProtocolName\"\n     */\n\n    /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */\n    if( len < 4 )\n    {\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n\n    list_len = ( buf[0] << 8 ) | buf[1];\n    if( list_len != len - 2 )\n    {\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n\n    name_len = buf[2];\n    if( name_len != list_len - 1 )\n    {\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n\n    /* Check that the server chosen protocol was in our list and save it */\n    for( p = ssl->conf->alpn_list; *p != NULL; p++ )\n    {\n        if( name_len == strlen( *p ) &&\n            memcmp( buf + 3, *p, name_len ) == 0 )\n        {\n            ssl->alpn_chosen = *p;\n            return( 0 );\n        }\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 1, ( \"ALPN extension: no matching protocol\" ) );\n    mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                    MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n    return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n}\n#endif /* MBEDTLS_SSL_ALPN */\n\n/*\n * Parse HelloVerifyRequest.  Only called after verifying the HS type.\n */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\nstatic int ssl_parse_hello_verify_request( mbedtls_ssl_context *ssl )\n{\n    const unsigned char *p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );\n    int major_ver, minor_ver;\n    unsigned char cookie_len;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse hello verify request\" ) );\n\n    /*\n     * struct {\n     *   ProtocolVersion server_version;\n     *   opaque cookie<0..2^8-1>;\n     * } HelloVerifyRequest;\n     */\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"server version\", p, 2 );\n    mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, p );\n    p += 2;\n\n    /*\n     * Since the RFC is not clear on this point, accept DTLS 1.0 (TLS 1.1)\n     * even is lower than our min version.\n     */\n    if( major_ver < MBEDTLS_SSL_MAJOR_VERSION_3 ||\n        minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ||\n        major_ver > ssl->conf->max_major_ver  ||\n        minor_ver > ssl->conf->max_minor_ver  )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server version\" ) );\n\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                     MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );\n\n        return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );\n    }\n\n    cookie_len = *p++;\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"cookie\", p, cookie_len );\n\n    if( ( ssl->in_msg + ssl->in_msglen ) - p < cookie_len )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1,\n            ( \"cookie length does not match incoming message size\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                    MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n\n    mbedtls_free( ssl->handshake->verify_cookie );\n\n    ssl->handshake->verify_cookie = mbedtls_calloc( 1, cookie_len );\n    if( ssl->handshake->verify_cookie  == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"alloc failed (%d bytes)\", cookie_len ) );\n        return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n    }\n\n    memcpy( ssl->handshake->verify_cookie, p, cookie_len );\n    ssl->handshake->verify_cookie_len = cookie_len;\n\n    /* Start over at ClientHello */\n    ssl->state = MBEDTLS_SSL_CLIENT_HELLO;\n    mbedtls_ssl_reset_checksum( ssl );\n\n    mbedtls_ssl_recv_flight_completed( ssl );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= parse hello verify request\" ) );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n\nstatic int ssl_parse_server_hello( mbedtls_ssl_context *ssl )\n{\n    int ret, i;\n    size_t n;\n    size_t ext_len;\n    unsigned char *buf, *ext;\n    unsigned char comp;\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n    int accept_comp;\n#endif\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    int renegotiation_info_seen = 0;\n#endif\n    int handshake_failure = 0;\n    const mbedtls_ssl_ciphersuite_t *suite_info;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse server hello\" ) );\n\n    buf = ssl->in_msg;\n\n    if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )\n    {\n        /* No alert on a read error. */\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_read_record\", ret );\n        return( ret );\n    }\n\n    if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )\n    {\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n        if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )\n        {\n            ssl->renego_records_seen++;\n\n            if( ssl->conf->renego_max_records >= 0 &&\n                ssl->renego_records_seen > ssl->conf->renego_max_records )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"renegotiation requested, \"\n                                    \"but not honored by server\" ) );\n                return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n            }\n\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"non-handshake message during renego\" ) );\n\n            ssl->keep_current_message = 1;\n            return( MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO );\n        }\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );\n        return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n    }\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        if( buf[0] == MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"received hello verify request\" ) );\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= parse server hello\" ) );\n            return( ssl_parse_hello_verify_request( ssl ) );\n        }\n        else\n        {\n            /* We made it through the verification process */\n            mbedtls_free( ssl->handshake->verify_cookie );\n            ssl->handshake->verify_cookie = NULL;\n            ssl->handshake->verify_cookie_len = 0;\n        }\n    }\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n\n    if( ssl->in_hslen < 38 + mbedtls_ssl_hs_hdr_len( ssl ) ||\n        buf[0] != MBEDTLS_SSL_HS_SERVER_HELLO )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n\n    /*\n     *  0   .  1    server_version\n     *  2   . 33    random (maybe including 4 bytes of Unix time)\n     * 34   . 34    session_id length = n\n     * 35   . 34+n  session_id\n     * 35+n . 36+n  cipher_suite\n     * 37+n . 37+n  compression_method\n     *\n     * 38+n . 39+n  extensions length (optional)\n     * 40+n .  ..   extensions\n     */\n    buf += mbedtls_ssl_hs_hdr_len( ssl );\n\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"server hello, version\", buf + 0, 2 );\n    mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver,\n                      ssl->conf->transport, buf + 0 );\n\n    if( ssl->major_ver < ssl->conf->min_major_ver ||\n        ssl->minor_ver < ssl->conf->min_minor_ver ||\n        ssl->major_ver > ssl->conf->max_major_ver ||\n        ssl->minor_ver > ssl->conf->max_minor_ver )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"server version out of bounds - \"\n                            \" min: [%d:%d], server: [%d:%d], max: [%d:%d]\",\n                            ssl->conf->min_major_ver, ssl->conf->min_minor_ver,\n                            ssl->major_ver, ssl->minor_ver,\n                            ssl->conf->max_major_ver, ssl->conf->max_minor_ver ) );\n\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                     MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );\n\n        return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, current time: %lu\",\n                           ( (uint32_t) buf[2] << 24 ) |\n                           ( (uint32_t) buf[3] << 16 ) |\n                           ( (uint32_t) buf[4] <<  8 ) |\n                           ( (uint32_t) buf[5]       ) ) );\n\n    memcpy( ssl->handshake->randbytes + 32, buf + 2, 32 );\n\n    n = buf[34];\n\n    MBEDTLS_SSL_DEBUG_BUF( 3,   \"server hello, random bytes\", buf + 2, 32 );\n\n    if( n > 32 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n\n    if( ssl->in_hslen > mbedtls_ssl_hs_hdr_len( ssl ) + 39 + n )\n    {\n        ext_len = ( ( buf[38 + n] <<  8 )\n                  | ( buf[39 + n]       ) );\n\n        if( ( ext_len > 0 && ext_len < 4 ) ||\n            ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 40 + n + ext_len )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server hello message\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n            return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n        }\n    }\n    else if( ssl->in_hslen == mbedtls_ssl_hs_hdr_len( ssl ) + 38 + n )\n    {\n        ext_len = 0;\n    }\n    else\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n\n    /* ciphersuite (used later) */\n    i = ( buf[35 + n] << 8 ) | buf[36 + n];\n\n    /*\n     * Read and check compression\n     */\n    comp = buf[37 + n];\n\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n    /* See comments in ssl_write_client_hello() */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n        accept_comp = 0;\n    else\n#endif\n        accept_comp = 1;\n\n    if( comp != MBEDTLS_SSL_COMPRESS_NULL &&\n        ( comp != MBEDTLS_SSL_COMPRESS_DEFLATE || accept_comp == 0 ) )\n#else /* MBEDTLS_ZLIB_SUPPORT */\n    if( comp != MBEDTLS_SSL_COMPRESS_NULL )\n#endif/* MBEDTLS_ZLIB_SUPPORT */\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"server hello, bad compression: %d\", comp ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n        return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );\n    }\n\n    /*\n     * Initialize update checksum functions\n     */\n    ssl->transform_negotiate->ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( i );\n\n    if( ssl->transform_negotiate->ciphersuite_info == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"ciphersuite info for %04x not found\", i ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n    }\n\n    mbedtls_ssl_optimize_checksum( ssl, ssl->transform_negotiate->ciphersuite_info );\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, session id len.: %d\", n ) );\n    MBEDTLS_SSL_DEBUG_BUF( 3,   \"server hello, session id\", buf + 35, n );\n\n    /*\n     * Check if the session can be resumed\n     */\n    if( ssl->handshake->resume == 0 || n == 0 ||\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n        ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||\n#endif\n        ssl->session_negotiate->ciphersuite != i ||\n        ssl->session_negotiate->compression != comp ||\n        ssl->session_negotiate->id_len != n ||\n        memcmp( ssl->session_negotiate->id, buf + 35, n ) != 0 )\n    {\n        ssl->state++;\n        ssl->handshake->resume = 0;\n#if defined(MBEDTLS_HAVE_TIME)\n        ssl->session_negotiate->start = mbedtls_time( NULL );\n#endif\n        ssl->session_negotiate->ciphersuite = i;\n        ssl->session_negotiate->compression = comp;\n        ssl->session_negotiate->id_len = n;\n        memcpy( ssl->session_negotiate->id, buf + 35, n );\n    }\n    else\n    {\n        ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;\n\n        if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_derive_keys\", ret );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );\n            return( ret );\n        }\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"%s session has been resumed\",\n                   ssl->handshake->resume ? \"a\" : \"no\" ) );\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, chosen ciphersuite: %04x\", i ) );\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, compress alg.: %d\", buf[37 + n] ) );\n\n    /*\n     * Perform cipher suite validation in same way as in ssl_write_client_hello.\n     */\n    i = 0;\n    while( 1 )\n    {\n        if( ssl->conf->ciphersuite_list[ssl->minor_ver][i] == 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server hello message\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n            return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n        }\n\n        if( ssl->conf->ciphersuite_list[ssl->minor_ver][i++] ==\n            ssl->session_negotiate->ciphersuite )\n        {\n            break;\n        }\n    }\n\n    suite_info = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite );\n    if( ssl_validate_ciphersuite( suite_info, ssl, ssl->minor_ver, ssl->minor_ver ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, chosen ciphersuite: %s\", suite_info->name ) );\n\n    if( comp != MBEDTLS_SSL_COMPRESS_NULL\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n        && comp != MBEDTLS_SSL_COMPRESS_DEFLATE\n#endif\n      )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n    ssl->session_negotiate->compression = comp;\n\n    ext = buf + 40 + n;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"server hello, total extension length: %d\", ext_len ) );\n\n    while( ext_len )\n    {\n        unsigned int ext_id   = ( ( ext[0] <<  8 )\n                                | ( ext[1]       ) );\n        unsigned int ext_size = ( ( ext[2] <<  8 )\n                                | ( ext[3]       ) );\n\n        if( ext_size + 4 > ext_len )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server hello message\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n            return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n        }\n\n        switch( ext_id )\n        {\n        case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found renegotiation extension\" ) );\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n            renegotiation_info_seen = 1;\n#endif\n\n            if( ( ret = ssl_parse_renegotiation_info( ssl, ext + 4,\n                                                      ext_size ) ) != 0 )\n                return( ret );\n\n            break;\n\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\n        case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found max_fragment_length extension\" ) );\n\n            if( ( ret = ssl_parse_max_fragment_length_ext( ssl,\n                            ext + 4, ext_size ) ) != 0 )\n            {\n                return( ret );\n            }\n\n            break;\n#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */\n\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)\n        case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found truncated_hmac extension\" ) );\n\n            if( ( ret = ssl_parse_truncated_hmac_ext( ssl,\n                            ext + 4, ext_size ) ) != 0 )\n            {\n                return( ret );\n            }\n\n            break;\n#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */\n\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\n        case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found encrypt_then_mac extension\" ) );\n\n            if( ( ret = ssl_parse_encrypt_then_mac_ext( ssl,\n                            ext + 4, ext_size ) ) != 0 )\n            {\n                return( ret );\n            }\n\n            break;\n#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */\n\n#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)\n        case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found extended_master_secret extension\" ) );\n\n            if( ( ret = ssl_parse_extended_ms_ext( ssl,\n                            ext + 4, ext_size ) ) != 0 )\n            {\n                return( ret );\n            }\n\n            break;\n#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\n        case MBEDTLS_TLS_EXT_SESSION_TICKET:\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found session_ticket extension\" ) );\n\n            if( ( ret = ssl_parse_session_ticket_ext( ssl,\n                            ext + 4, ext_size ) ) != 0 )\n            {\n                return( ret );\n            }\n\n            break;\n#endif /* MBEDTLS_SSL_SESSION_TICKETS */\n\n#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n        case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found supported_point_formats extension\" ) );\n\n            if( ( ret = ssl_parse_supported_point_formats_ext( ssl,\n                            ext + 4, ext_size ) ) != 0 )\n            {\n                return( ret );\n            }\n\n            break;\n#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||\n          MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n        case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found ecjpake_kkpp extension\" ) );\n\n            if( ( ret = ssl_parse_ecjpake_kkpp( ssl,\n                            ext + 4, ext_size ) ) != 0 )\n            {\n                return( ret );\n            }\n\n            break;\n#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n\n#if defined(MBEDTLS_SSL_ALPN)\n        case MBEDTLS_TLS_EXT_ALPN:\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found alpn extension\" ) );\n\n            if( ( ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ) ) != 0 )\n                return( ret );\n\n            break;\n#endif /* MBEDTLS_SSL_ALPN */\n\n        default:\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"unknown extension found: %d (ignoring)\",\n                           ext_id ) );\n        }\n\n        ext_len -= 4 + ext_size;\n        ext += 4 + ext_size;\n\n        if( ext_len > 0 && ext_len < 4 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server hello message\" ) );\n            return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n        }\n    }\n\n    /*\n     * Renegotiation security checks\n     */\n    if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&\n        ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"legacy renegotiation, breaking off handshake\" ) );\n        handshake_failure = 1;\n    }\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&\n             ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&\n             renegotiation_info_seen == 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"renegotiation_info extension missing (secure)\" ) );\n        handshake_failure = 1;\n    }\n    else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&\n             ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&\n             ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"legacy renegotiation not allowed\" ) );\n        handshake_failure = 1;\n    }\n    else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&\n             ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&\n             renegotiation_info_seen == 1 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"renegotiation_info extension present (legacy)\" ) );\n        handshake_failure = 1;\n    }\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n\n    if( handshake_failure == 1 )\n    {\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= parse server hello\" ) );\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \\\n    defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)\nstatic int ssl_parse_server_dh_params( mbedtls_ssl_context *ssl, unsigned char **p,\n                                       unsigned char *end )\n{\n    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;\n\n    /*\n     * Ephemeral DH parameters:\n     *\n     * struct {\n     *     opaque dh_p<1..2^16-1>;\n     *     opaque dh_g<1..2^16-1>;\n     *     opaque dh_Ys<1..2^16-1>;\n     * } ServerDHParams;\n     */\n    if( ( ret = mbedtls_dhm_read_params( &ssl->handshake->dhm_ctx, p, end ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 2, ( \"mbedtls_dhm_read_params\" ), ret );\n        return( ret );\n    }\n\n    if( ssl->handshake->dhm_ctx.len * 8 < ssl->conf->dhm_min_bitlen )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"DHM prime too short: %d < %d\",\n                                    ssl->handshake->dhm_ctx.len * 8,\n                                    ssl->conf->dhm_min_bitlen ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n    }\n\n    MBEDTLS_SSL_DEBUG_MPI( 3, \"DHM: P \", &ssl->handshake->dhm_ctx.P  );\n    MBEDTLS_SSL_DEBUG_MPI( 3, \"DHM: G \", &ssl->handshake->dhm_ctx.G  );\n    MBEDTLS_SSL_DEBUG_MPI( 3, \"DHM: GY\", &ssl->handshake->dhm_ctx.GY );\n\n    return( ret );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) ||                     \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)\nstatic int ssl_check_server_ecdh_params( const mbedtls_ssl_context *ssl )\n{\n    const mbedtls_ecp_curve_info *curve_info;\n\n    curve_info = mbedtls_ecp_curve_info_from_grp_id( ssl->handshake->ecdh_ctx.grp.id );\n    if( curve_info == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"ECDH curve: %s\", curve_info->name ) );\n\n#if defined(MBEDTLS_ECP_C)\n    if( mbedtls_ssl_check_curve( ssl, ssl->handshake->ecdh_ctx.grp.id ) != 0 )\n#else\n    if( ssl->handshake->ecdh_ctx.grp.nbits < 163 ||\n        ssl->handshake->ecdh_ctx.grp.nbits > 521 )\n#endif\n        return( -1 );\n\n    MBEDTLS_SSL_DEBUG_ECP( 3, \"ECDH: Qp\", &ssl->handshake->ecdh_ctx.Qp );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)\nstatic int ssl_parse_server_ecdh_params( mbedtls_ssl_context *ssl,\n                                         unsigned char **p,\n                                         unsigned char *end )\n{\n    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;\n\n    /*\n     * Ephemeral ECDH parameters:\n     *\n     * struct {\n     *     ECParameters curve_params;\n     *     ECPoint      public;\n     * } ServerECDHParams;\n     */\n    if( ( ret = mbedtls_ecdh_read_params( &ssl->handshake->ecdh_ctx,\n                                  (const unsigned char **) p, end ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, ( \"mbedtls_ecdh_read_params\" ), ret );\n        return( ret );\n    }\n\n    if( ssl_check_server_ecdh_params( ssl ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message (ECDHE curve)\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n    }\n\n    return( ret );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)\nstatic int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,\n                                      unsigned char **p,\n                                      unsigned char *end )\n{\n    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;\n    size_t  len;\n    ((void) ssl);\n\n    /*\n     * PSK parameters:\n     *\n     * opaque psk_identity_hint<0..2^16-1>;\n     */\n    if( (*p) > end - 2 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message \"\n                                    \"(psk_identity_hint length)\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n    }\n    len = (*p)[0] << 8 | (*p)[1];\n    *p += 2;\n\n    if( (*p) > end - len )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message \"\n                                    \"(psk_identity_hint length)\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n    }\n\n    /*\n     * Note: we currently ignore the PKS identity hint, as we only allow one\n     * PSK to be provisionned on the client. This could be changed later if\n     * someone needs that feature.\n     */\n    *p += len;\n    ret = 0;\n\n    return( ret );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) ||                           \\\n    defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)\n/*\n * Generate a pre-master secret and encrypt it with the server's RSA key\n */\nstatic int ssl_write_encrypted_pms( mbedtls_ssl_context *ssl,\n                                    size_t offset, size_t *olen,\n                                    size_t pms_offset )\n{\n    int ret;\n    size_t len_bytes = ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ? 0 : 2;\n    unsigned char *p = ssl->handshake->premaster + pms_offset;\n\n    if( offset + len_bytes > MBEDTLS_SSL_OUT_CONTENT_LEN )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"buffer too small for encrypted pms\" ) );\n        return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );\n    }\n\n    /*\n     * Generate (part of) the pre-master as\n     *  struct {\n     *      ProtocolVersion client_version;\n     *      opaque random[46];\n     *  } PreMasterSecret;\n     */\n    mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,\n                       ssl->conf->transport, p );\n\n    if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p + 2, 46 ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"f_rng\", ret );\n        return( ret );\n    }\n\n    ssl->handshake->pmslen = 48;\n\n    if( ssl->session_negotiate->peer_cert == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"certificate required\" ) );\n        return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n    }\n\n    /*\n     * Now write it out, encrypted\n     */\n    if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,\n                MBEDTLS_PK_RSA ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"certificate key type mismatch\" ) );\n        return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );\n    }\n\n    if( ( ret = mbedtls_pk_encrypt( &ssl->session_negotiate->peer_cert->pk,\n                            p, ssl->handshake->pmslen,\n                            ssl->out_msg + offset + len_bytes, olen,\n                            MBEDTLS_SSL_OUT_CONTENT_LEN - offset - len_bytes,\n                            ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_rsa_pkcs1_encrypt\", ret );\n        return( ret );\n    }\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_2)\n    if( len_bytes == 2 )\n    {\n        ssl->out_msg[offset+0] = (unsigned char)( *olen >> 8 );\n        ssl->out_msg[offset+1] = (unsigned char)( *olen      );\n        *olen += 2;\n    }\n#endif\n\n    return( 0 );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)\nstatic int ssl_parse_signature_algorithm( mbedtls_ssl_context *ssl,\n                                          unsigned char **p,\n                                          unsigned char *end,\n                                          mbedtls_md_type_t *md_alg,\n                                          mbedtls_pk_type_t *pk_alg )\n{\n    ((void) ssl);\n    *md_alg = MBEDTLS_MD_NONE;\n    *pk_alg = MBEDTLS_PK_NONE;\n\n    /* Only in TLS 1.2 */\n    if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )\n    {\n        return( 0 );\n    }\n\n    if( (*p) + 2 > end )\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n\n    /*\n     * Get hash algorithm\n     */\n    if( ( *md_alg = mbedtls_ssl_md_alg_from_hash( (*p)[0] ) ) == MBEDTLS_MD_NONE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"Server used unsupported \"\n                            \"HashAlgorithm %d\", *(p)[0] ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n    }\n\n    /*\n     * Get signature algorithm\n     */\n    if( ( *pk_alg = mbedtls_ssl_pk_alg_from_sig( (*p)[1] ) ) == MBEDTLS_PK_NONE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"server used unsupported \"\n                            \"SignatureAlgorithm %d\", (*p)[1] ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n    }\n\n    /*\n     * Check if the hash is acceptable\n     */\n    if( mbedtls_ssl_check_sig_hash( ssl, *md_alg ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"server used HashAlgorithm %d that was not offered\",\n                                    *(p)[0] ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"Server used SignatureAlgorithm %d\", (*p)[1] ) );\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"Server used HashAlgorithm %d\", (*p)[0] ) );\n    *p += 2;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)\nstatic int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )\n{\n    int ret;\n    const mbedtls_ecp_keypair *peer_key;\n\n    if( ssl->session_negotiate->peer_cert == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"certificate required\" ) );\n        return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n    }\n\n    if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,\n                     MBEDTLS_PK_ECKEY ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"server key not ECDH capable\" ) );\n        return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );\n    }\n\n    peer_key = mbedtls_pk_ec( ssl->session_negotiate->peer_cert->pk );\n\n    if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx, peer_key,\n                                 MBEDTLS_ECDH_THEIRS ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, ( \"mbedtls_ecdh_get_params\" ), ret );\n        return( ret );\n    }\n\n    if( ssl_check_server_ecdh_params( ssl ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server certificate (ECDH curve)\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );\n    }\n\n    return( ret );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||\n          MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */\n\nstatic int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )\n{\n    int ret;\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =\n        ssl->transform_negotiate->ciphersuite_info;\n    unsigned char *p = NULL, *end = NULL;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse server key exchange\" ) );\n\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip parse server key exchange\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n    ((void) p);\n    ((void) end);\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )\n    {\n        if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"ssl_get_ecdh_params_from_cert\", ret );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n            return( ret );\n        }\n\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip parse server key exchange\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n    ((void) p);\n    ((void) end);\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */\n\n    if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_read_record\", ret );\n        return( ret );\n    }\n\n    if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );\n        return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n    }\n\n    /*\n     * ServerKeyExchange may be skipped with PSK and RSA-PSK when the server\n     * doesn't use a psk_identity_hint\n     */\n    if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )\n    {\n        if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||\n            ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )\n        {\n            /* Current message is probably either\n             * CertificateRequest or ServerHelloDone */\n            ssl->keep_current_message = 1;\n            goto exit;\n        }\n\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"server key exchange message must \"\n                                    \"not be skipped\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );\n\n        return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n    }\n\n    p   = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );\n    end = ssl->in_msg + ssl->in_hslen;\n    MBEDTLS_SSL_DEBUG_BUF( 3,   \"server key exchange\", p, end - p );\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )\n    {\n        if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n            return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n        }\n    } /* FALLTROUGH */\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) ||                       \\\n    defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )\n        ; /* nothing more to do */\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \\\n    defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )\n    {\n        if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n            return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n        }\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) ||                     \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )\n    {\n        if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n            return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n        }\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )\n    {\n        ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,\n                                              p, end - p );\n        if( ret != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecjpake_read_round_two\", ret );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n            return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n        }\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)\n    if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )\n    {\n        size_t sig_len, hashlen;\n        unsigned char hash[64];\n        mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;\n        mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;\n        unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );\n        size_t params_len = p - params;\n\n        /*\n         * Handle the digitally-signed structure\n         */\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n        if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )\n        {\n            if( ssl_parse_signature_algorithm( ssl, &p, end,\n                                               &md_alg, &pk_alg ) != 0 )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n                mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                                MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n                return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n            }\n\n            if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n                mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                                MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n                return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n            }\n        }\n        else\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1)\n        if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )\n        {\n            pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );\n\n            /* Default hash for ECDSA is SHA-1 */\n            if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE )\n                md_alg = MBEDTLS_MD_SHA1;\n        }\n        else\n#endif\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n        /*\n         * Read signature\n         */\n\n        if( p > end - 2 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n            return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n        }\n        sig_len = ( p[0] << 8 ) | p[1];\n        p += 2;\n\n        if( p != end - sig_len )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n            return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n        }\n\n        MBEDTLS_SSL_DEBUG_BUF( 3, \"signature\", p, sig_len );\n\n        /*\n         * Compute the hash that has been signed\n         */\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1)\n        if( md_alg == MBEDTLS_MD_NONE )\n        {\n            hashlen = 36;\n            ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params,\n                                                           params_len );\n            if( ret != 0 )\n                return( ret );\n        }\n        else\n#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \\\n          MBEDTLS_SSL_PROTO_TLS1_1 */\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_2)\n        if( md_alg != MBEDTLS_MD_NONE )\n        {\n            ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, &hashlen,\n                                                          params, params_len,\n                                                          md_alg );\n            if( ret != 0 )\n                return( ret );\n        }\n        else\n#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \\\n          MBEDTLS_SSL_PROTO_TLS1_2 */\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n        MBEDTLS_SSL_DEBUG_BUF( 3, \"parameters hash\", hash, hashlen );\n\n        if( ssl->session_negotiate->peer_cert == NULL )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"certificate required\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n            return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n        }\n\n        /*\n         * Verify signature\n         */\n        if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n            return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );\n        }\n\n        if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,\n                               md_alg, hash, hashlen, p, sig_len ) ) != 0 )\n        {\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_pk_verify\", ret );\n            return( ret );\n        }\n    }\n#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */\n\nexit:\n    ssl->state++;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= parse server key exchange\" ) );\n\n    return( 0 );\n}\n\n#if ! defined(MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED)\nstatic int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )\n{\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =\n        ssl->transform_negotiate->ciphersuite_info;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse certificate request\" ) );\n\n    if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip parse certificate request\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n    return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n}\n#else /* MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED */\nstatic int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )\n{\n    int ret;\n    unsigned char *buf;\n    size_t n = 0;\n    size_t cert_type_len = 0, dn_len = 0;\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =\n        ssl->transform_negotiate->ciphersuite_info;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse certificate request\" ) );\n\n    if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip parse certificate request\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n\n    if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_read_record\", ret );\n        return( ret );\n    }\n\n    if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate request message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );\n        return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n    }\n\n    ssl->state++;\n    ssl->client_auth = ( ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE_REQUEST );\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"got %s certificate request\",\n                        ssl->client_auth ? \"a\" : \"no\" ) );\n\n    if( ssl->client_auth == 0 )\n    {\n        /* Current message is probably the ServerHelloDone */\n        ssl->keep_current_message = 1;\n        goto exit;\n    }\n\n    /*\n     *  struct {\n     *      ClientCertificateType certificate_types<1..2^8-1>;\n     *      SignatureAndHashAlgorithm\n     *        supported_signature_algorithms<2^16-1>; -- TLS 1.2 only\n     *      DistinguishedName certificate_authorities<0..2^16-1>;\n     *  } CertificateRequest;\n     *\n     *  Since we only support a single certificate on clients, let's just\n     *  ignore all the information that's supposed to help us pick a\n     *  certificate.\n     *\n     *  We could check that our certificate matches the request, and bail out\n     *  if it doesn't, but it's simpler to just send the certificate anyway,\n     *  and give the server the opportunity to decide if it should terminate\n     *  the connection when it doesn't like our certificate.\n     *\n     *  Same goes for the hash in TLS 1.2's signature_algorithms: at this\n     *  point we only have one hash available (see comments in\n     *  write_certificate_verify), so let's just use what we have.\n     *\n     *  However, we still minimally parse the message to check it is at least\n     *  superficially sane.\n     */\n    buf = ssl->in_msg;\n\n    /* certificate_types */\n    if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate request message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );\n    }\n    cert_type_len = buf[mbedtls_ssl_hs_hdr_len( ssl )];\n    n = cert_type_len;\n\n    /*\n     * In the subsequent code there are two paths that read from buf:\n     *     * the length of the signature algorithms field (if minor version of\n     *       SSL is 3),\n     *     * distinguished name length otherwise.\n     * Both reach at most the index:\n     *    ...hdr_len + 2 + n,\n     * therefore the buffer length at this point must be greater than that\n     * regardless of the actual code path.\n     */\n    if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate request message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );\n    }\n\n    /* supported_signature_algorithms */\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )\n    {\n        size_t sig_alg_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] <<  8 )\n                             | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n]       ) );\n#if defined(MBEDTLS_DEBUG_C)\n        unsigned char* sig_alg;\n        size_t i;\n#endif\n\n        /*\n         * The furthest access in buf is in the loop few lines below:\n         *     sig_alg[i + 1],\n         * where:\n         *     sig_alg = buf + ...hdr_len + 3 + n,\n         *     max(i) = sig_alg_len - 1.\n         * Therefore the furthest access is:\n         *     buf[...hdr_len + 3 + n + sig_alg_len - 1 + 1],\n         * which reduces to:\n         *     buf[...hdr_len + 3 + n + sig_alg_len],\n         * which is one less than we need the buf to be.\n         */\n        if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n + sig_alg_len )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate request message\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );\n        }\n\n#if defined(MBEDTLS_DEBUG_C)\n        sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n;\n        for( i = 0; i < sig_alg_len; i += 2 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"Supported Signature Algorithm found: %d\"\n                                        \",%d\", sig_alg[i], sig_alg[i + 1]  ) );\n        }\n#endif\n\n        n += 2 + sig_alg_len;\n    }\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n\n    /* certificate_authorities */\n    dn_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] <<  8 )\n             | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n]       ) );\n\n    n += dn_len;\n    if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate request message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );\n    }\n\nexit:\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= parse certificate request\" ) );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED */\n\nstatic int ssl_parse_server_hello_done( mbedtls_ssl_context *ssl )\n{\n    int ret;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse server hello done\" ) );\n\n    if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_read_record\", ret );\n        return( ret );\n    }\n\n    if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server hello done message\" ) );\n        return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n    }\n\n    if( ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) ||\n        ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_HELLO_DONE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server hello done message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE );\n    }\n\n    ssl->state++;\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n        mbedtls_ssl_recv_flight_completed( ssl );\n#endif\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= parse server hello done\" ) );\n\n    return( 0 );\n}\n\nstatic int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl )\n{\n    int ret;\n    size_t i, n;\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =\n        ssl->transform_negotiate->ciphersuite_info;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write client key exchange\" ) );\n\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA )\n    {\n        /*\n         * DHM key exchange -- send G^X mod P\n         */\n        n = ssl->handshake->dhm_ctx.len;\n\n        ssl->out_msg[4] = (unsigned char)( n >> 8 );\n        ssl->out_msg[5] = (unsigned char)( n      );\n        i = 6;\n\n        ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,\n                                (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),\n                               &ssl->out_msg[i], n,\n                                ssl->conf->f_rng, ssl->conf->p_rng );\n        if( ret != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_dhm_make_public\", ret );\n            return( ret );\n        }\n\n        MBEDTLS_SSL_DEBUG_MPI( 3, \"DHM: X \", &ssl->handshake->dhm_ctx.X  );\n        MBEDTLS_SSL_DEBUG_MPI( 3, \"DHM: GX\", &ssl->handshake->dhm_ctx.GX );\n\n        if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,\n                                      ssl->handshake->premaster,\n                                      MBEDTLS_PREMASTER_SIZE,\n                                     &ssl->handshake->pmslen,\n                                      ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_dhm_calc_secret\", ret );\n            return( ret );\n        }\n\n        MBEDTLS_SSL_DEBUG_MPI( 3, \"DHM: K \", &ssl->handshake->dhm_ctx.K  );\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )\n    {\n        /*\n         * ECDH key exchange -- send client public value\n         */\n        i = 4;\n\n        ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx,\n                                &n,\n                                &ssl->out_msg[i], 1000,\n                                ssl->conf->f_rng, ssl->conf->p_rng );\n        if( ret != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecdh_make_public\", ret );\n            return( ret );\n        }\n\n        MBEDTLS_SSL_DEBUG_ECP( 3, \"ECDH: Q\", &ssl->handshake->ecdh_ctx.Q );\n\n        if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx,\n                                      &ssl->handshake->pmslen,\n                                       ssl->handshake->premaster,\n                                       MBEDTLS_MPI_MAX_SIZE,\n                                       ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecdh_calc_secret\", ret );\n            return( ret );\n        }\n\n        MBEDTLS_SSL_DEBUG_MPI( 3, \"ECDH: z\", &ssl->handshake->ecdh_ctx.z );\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)\n    if( mbedtls_ssl_ciphersuite_uses_psk( ciphersuite_info ) )\n    {\n        /*\n         * opaque psk_identity<0..2^16-1>;\n         */\n        if( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"got no private key for PSK\" ) );\n            return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );\n        }\n\n        i = 4;\n        n = ssl->conf->psk_identity_len;\n\n        if( i + 2 + n > MBEDTLS_SSL_OUT_CONTENT_LEN )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"psk identity too long or \"\n                                        \"SSL buffer too short\" ) );\n            return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );\n        }\n\n        ssl->out_msg[i++] = (unsigned char)( n >> 8 );\n        ssl->out_msg[i++] = (unsigned char)( n      );\n\n        memcpy( ssl->out_msg + i, ssl->conf->psk_identity, ssl->conf->psk_identity_len );\n        i += ssl->conf->psk_identity_len;\n\n#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)\n        if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK )\n        {\n            n = 0;\n        }\n        else\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)\n        if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )\n        {\n            if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 2 ) ) != 0 )\n                return( ret );\n        }\n        else\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)\n        if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )\n        {\n            /*\n             * ClientDiffieHellmanPublic public (DHM send G^X mod P)\n             */\n            n = ssl->handshake->dhm_ctx.len;\n\n            if( i + 2 + n > MBEDTLS_SSL_OUT_CONTENT_LEN )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"psk identity or DHM size too long\"\n                                            \" or SSL buffer too short\" ) );\n                return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );\n            }\n\n            ssl->out_msg[i++] = (unsigned char)( n >> 8 );\n            ssl->out_msg[i++] = (unsigned char)( n      );\n\n            ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,\n                    (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),\n                    &ssl->out_msg[i], n,\n                    ssl->conf->f_rng, ssl->conf->p_rng );\n            if( ret != 0 )\n            {\n                MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_dhm_make_public\", ret );\n                return( ret );\n            }\n        }\n        else\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)\n        if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )\n        {\n            /*\n             * ClientECDiffieHellmanPublic public;\n             */\n            ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx, &n,\n                    &ssl->out_msg[i], MBEDTLS_SSL_OUT_CONTENT_LEN - i,\n                    ssl->conf->f_rng, ssl->conf->p_rng );\n            if( ret != 0 )\n            {\n                MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecdh_make_public\", ret );\n                return( ret );\n            }\n\n            MBEDTLS_SSL_DEBUG_ECP( 3, \"ECDH: Q\", &ssl->handshake->ecdh_ctx.Q );\n        }\n        else\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n        if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,\n                        ciphersuite_info->key_exchange ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_psk_derive_premaster\", ret );\n            return( ret );\n        }\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )\n    {\n        i = 4;\n        if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 0 ) ) != 0 )\n            return( ret );\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )\n    {\n        i = 4;\n\n        ret = mbedtls_ecjpake_write_round_two( &ssl->handshake->ecjpake_ctx,\n                ssl->out_msg + i, MBEDTLS_SSL_OUT_CONTENT_LEN - i, &n,\n                ssl->conf->f_rng, ssl->conf->p_rng );\n        if( ret != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecjpake_write_round_two\", ret );\n            return( ret );\n        }\n\n        ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx,\n                ssl->handshake->premaster, 32, &ssl->handshake->pmslen,\n                ssl->conf->f_rng, ssl->conf->p_rng );\n        if( ret != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecjpake_derive_secret\", ret );\n            return( ret );\n        }\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */\n    {\n        ((void) ciphersuite_info);\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    ssl->out_msglen  = i + n;\n    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;\n    ssl->out_msg[0]  = MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE;\n\n    ssl->state++;\n\n    if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_write_record\", ret );\n        return( ret );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write client key exchange\" ) );\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)       && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)   && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)  && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)&& \\\n    !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)\nstatic int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )\n{\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =\n        ssl->transform_negotiate->ciphersuite_info;\n    int ret;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write certificate verify\" ) );\n\n    if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_derive_keys\", ret );\n        return( ret );\n    }\n\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip write certificate verify\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n    return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n}\n#else\nstatic int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )\n{\n    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =\n        ssl->transform_negotiate->ciphersuite_info;\n    size_t n = 0, offset = 0;\n    unsigned char hash[48];\n    unsigned char *hash_start = hash;\n    mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;\n    unsigned int hashlen;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write certificate verify\" ) );\n\n    if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_derive_keys\", ret );\n        return( ret );\n    }\n\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip write certificate verify\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n\n    if( ssl->client_auth == 0 || mbedtls_ssl_own_cert( ssl ) == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip write certificate verify\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n\n    if( mbedtls_ssl_own_key( ssl ) == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"got no private key for certificate\" ) );\n        return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );\n    }\n\n    /*\n     * Make an RSA signature of the handshake digests\n     */\n    ssl->handshake->calc_verify( ssl, hash );\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1)\n    if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )\n    {\n        /*\n         * digitally-signed struct {\n         *     opaque md5_hash[16];\n         *     opaque sha_hash[20];\n         * };\n         *\n         * md5_hash\n         *     MD5(handshake_messages);\n         *\n         * sha_hash\n         *     SHA(handshake_messages);\n         */\n        hashlen = 36;\n        md_alg = MBEDTLS_MD_NONE;\n\n        /*\n         * For ECDSA, default hash is SHA-1 only\n         */\n        if( mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECDSA ) )\n        {\n            hash_start += 16;\n            hashlen -= 16;\n            md_alg = MBEDTLS_MD_SHA1;\n        }\n    }\n    else\n#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \\\n          MBEDTLS_SSL_PROTO_TLS1_1 */\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )\n    {\n        /*\n         * digitally-signed struct {\n         *     opaque handshake_messages[handshake_messages_length];\n         * };\n         *\n         * Taking shortcut here. We assume that the server always allows the\n         * PRF Hash function and has sent it in the allowed signature\n         * algorithms list received in the Certificate Request message.\n         *\n         * Until we encounter a server that does not, we will take this\n         * shortcut.\n         *\n         * Reason: Otherwise we should have running hashes for SHA512 and SHA224\n         *         in order to satisfy 'weird' needs from the server side.\n         */\n        if( ssl->transform_negotiate->ciphersuite_info->mac ==\n            MBEDTLS_MD_SHA384 )\n        {\n            md_alg = MBEDTLS_MD_SHA384;\n            ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA384;\n        }\n        else\n        {\n            md_alg = MBEDTLS_MD_SHA256;\n            ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA256;\n        }\n        ssl->out_msg[5] = mbedtls_ssl_sig_from_pk( mbedtls_ssl_own_key( ssl ) );\n\n        /* Info from md_alg will be used instead */\n        hashlen = 0;\n        offset = 2;\n    }\n    else\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ), md_alg, hash_start, hashlen,\n                         ssl->out_msg + 6 + offset, &n,\n                         ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_pk_sign\", ret );\n        return( ret );\n    }\n\n    ssl->out_msg[4 + offset] = (unsigned char)( n >> 8 );\n    ssl->out_msg[5 + offset] = (unsigned char)( n      );\n\n    ssl->out_msglen  = 6 + n + offset;\n    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;\n    ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE_VERIFY;\n\n    ssl->state++;\n\n    if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_write_record\", ret );\n        return( ret );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write certificate verify\" ) );\n\n    return( ret );\n}\n#endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&\n          !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&\n          !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED &&\n          !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED &&\n          !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED &&\n          !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\nstatic int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl )\n{\n    int ret;\n    uint32_t lifetime;\n    size_t ticket_len;\n    unsigned char *ticket;\n    const unsigned char *msg;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse new session ticket\" ) );\n\n    if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_read_record\", ret );\n        return( ret );\n    }\n\n    if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad new session ticket message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );\n        return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n    }\n\n    /*\n     * struct {\n     *     uint32 ticket_lifetime_hint;\n     *     opaque ticket<0..2^16-1>;\n     * } NewSessionTicket;\n     *\n     * 0  .  3   ticket_lifetime_hint\n     * 4  .  5   ticket_len (n)\n     * 6  .  5+n ticket content\n     */\n    if( ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET ||\n        ssl->in_hslen < 6 + mbedtls_ssl_hs_hdr_len( ssl ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad new session ticket message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );\n    }\n\n    msg = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );\n\n    lifetime = ( msg[0] << 24 ) | ( msg[1] << 16 ) |\n               ( msg[2] <<  8 ) | ( msg[3]       );\n\n    ticket_len = ( msg[4] << 8 ) | ( msg[5] );\n\n    if( ticket_len + 6 + mbedtls_ssl_hs_hdr_len( ssl ) != ssl->in_hslen )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad new session ticket message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ticket length: %d\", ticket_len ) );\n\n    /* We're not waiting for a NewSessionTicket message any more */\n    ssl->handshake->new_session_ticket = 0;\n    ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;\n\n    /*\n     * Zero-length ticket means the server changed his mind and doesn't want\n     * to send a ticket after all, so just forget it\n     */\n    if( ticket_len == 0 )\n        return( 0 );\n\n    mbedtls_platform_zeroize( ssl->session_negotiate->ticket,\n                              ssl->session_negotiate->ticket_len );\n    mbedtls_free( ssl->session_negotiate->ticket );\n    ssl->session_negotiate->ticket = NULL;\n    ssl->session_negotiate->ticket_len = 0;\n\n    if( ( ticket = mbedtls_calloc( 1, ticket_len ) ) == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"ticket alloc failed\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );\n        return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n    }\n\n    memcpy( ticket, msg + 6, ticket_len );\n\n    ssl->session_negotiate->ticket = ticket;\n    ssl->session_negotiate->ticket_len = ticket_len;\n    ssl->session_negotiate->ticket_lifetime = lifetime;\n\n    /*\n     * RFC 5077 section 3.4:\n     * \"If the client receives a session ticket from the server, then it\n     * discards any Session ID that was sent in the ServerHello.\"\n     */\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ticket in use, discarding session id\" ) );\n    ssl->session_negotiate->id_len = 0;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= parse new session ticket\" ) );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_SESSION_TICKETS */\n\n/*\n * SSL handshake -- client side -- single step\n */\nint mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl )\n{\n    int ret = 0;\n\n    if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"client state: %d\", ssl->state ) );\n\n    if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )\n        return( ret );\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&\n        ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )\n    {\n        if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )\n            return( ret );\n    }\n#endif\n\n    /* Change state now, so that it is right in mbedtls_ssl_read_record(), used\n     * by DTLS for dropping out-of-sequence ChangeCipherSpec records */\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\n    if( ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC &&\n        ssl->handshake->new_session_ticket != 0 )\n    {\n        ssl->state = MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET;\n    }\n#endif\n\n    switch( ssl->state )\n    {\n        case MBEDTLS_SSL_HELLO_REQUEST:\n            ssl->state = MBEDTLS_SSL_CLIENT_HELLO;\n            break;\n\n       /*\n        *  ==>   ClientHello\n        */\n       case MBEDTLS_SSL_CLIENT_HELLO:\n           ret = ssl_write_client_hello( ssl );\n           break;\n\n       /*\n        *  <==   ServerHello\n        *        Certificate\n        *      ( ServerKeyExchange  )\n        *      ( CertificateRequest )\n        *        ServerHelloDone\n        */\n       case MBEDTLS_SSL_SERVER_HELLO:\n           ret = ssl_parse_server_hello( ssl );\n           break;\n\n       case MBEDTLS_SSL_SERVER_CERTIFICATE:\n           ret = mbedtls_ssl_parse_certificate( ssl );\n           break;\n\n       case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:\n           ret = ssl_parse_server_key_exchange( ssl );\n           break;\n\n       case MBEDTLS_SSL_CERTIFICATE_REQUEST:\n           ret = ssl_parse_certificate_request( ssl );\n           break;\n\n       case MBEDTLS_SSL_SERVER_HELLO_DONE:\n           ret = ssl_parse_server_hello_done( ssl );\n           break;\n\n       /*\n        *  ==> ( Certificate/Alert  )\n        *        ClientKeyExchange\n        *      ( CertificateVerify  )\n        *        ChangeCipherSpec\n        *        Finished\n        */\n       case MBEDTLS_SSL_CLIENT_CERTIFICATE:\n           ret = mbedtls_ssl_write_certificate( ssl );\n           break;\n\n       case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:\n           ret = ssl_write_client_key_exchange( ssl );\n           break;\n\n       case MBEDTLS_SSL_CERTIFICATE_VERIFY:\n           ret = ssl_write_certificate_verify( ssl );\n           break;\n\n       case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:\n           ret = mbedtls_ssl_write_change_cipher_spec( ssl );\n           break;\n\n       case MBEDTLS_SSL_CLIENT_FINISHED:\n           ret = mbedtls_ssl_write_finished( ssl );\n           break;\n\n       /*\n        *  <==   ( NewSessionTicket )\n        *        ChangeCipherSpec\n        *        Finished\n        */\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\n       case MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET:\n           ret = ssl_parse_new_session_ticket( ssl );\n           break;\n#endif\n\n       case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:\n           ret = mbedtls_ssl_parse_change_cipher_spec( ssl );\n           break;\n\n       case MBEDTLS_SSL_SERVER_FINISHED:\n           ret = mbedtls_ssl_parse_finished( ssl );\n           break;\n\n       case MBEDTLS_SSL_FLUSH_BUFFERS:\n           MBEDTLS_SSL_DEBUG_MSG( 2, ( \"handshake: done\" ) );\n           ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;\n           break;\n\n       case MBEDTLS_SSL_HANDSHAKE_WRAPUP:\n           mbedtls_ssl_handshake_wrapup( ssl );\n           break;\n\n       default:\n           MBEDTLS_SSL_DEBUG_MSG( 1, ( \"invalid state %d\", ssl->state ) );\n           return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n   }\n\n    return( ret );\n}\n#endif /* MBEDTLS_SSL_CLI_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/ssl_cookie.c",
    "content": "/*\n *  DTLS cookie callbacks implementation\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n * These session callbacks use a simple chained list\n * to store and retrieve the session information.\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_SSL_COOKIE_C)\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#define mbedtls_calloc    calloc\n#define mbedtls_free      free\n#endif\n\n#include \"mbedtls/ssl_cookie.h\"\n#include \"mbedtls/ssl_internal.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n/*\n * If DTLS is in use, then at least one of SHA-1, SHA-256, SHA-512 is\n * available. Try SHA-256 first, 512 wastes resources since we need to stay\n * with max 32 bytes of cookie for DTLS 1.0\n */\n#if defined(MBEDTLS_SHA256_C)\n#define COOKIE_MD           MBEDTLS_MD_SHA224\n#define COOKIE_MD_OUTLEN    32\n#define COOKIE_HMAC_LEN     28\n#elif defined(MBEDTLS_SHA512_C)\n#define COOKIE_MD           MBEDTLS_MD_SHA384\n#define COOKIE_MD_OUTLEN    48\n#define COOKIE_HMAC_LEN     28\n#elif defined(MBEDTLS_SHA1_C)\n#define COOKIE_MD           MBEDTLS_MD_SHA1\n#define COOKIE_MD_OUTLEN    20\n#define COOKIE_HMAC_LEN     20\n#else\n#error \"DTLS hello verify needs SHA-1 or SHA-2\"\n#endif\n\n/*\n * Cookies are formed of a 4-bytes timestamp (or serial number) and\n * an HMAC of timestemp and client ID.\n */\n#define COOKIE_LEN      ( 4 + COOKIE_HMAC_LEN )\n\nvoid mbedtls_ssl_cookie_init( mbedtls_ssl_cookie_ctx *ctx )\n{\n    mbedtls_md_init( &ctx->hmac_ctx );\n#if !defined(MBEDTLS_HAVE_TIME)\n    ctx->serial = 0;\n#endif\n    ctx->timeout = MBEDTLS_SSL_COOKIE_TIMEOUT;\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_mutex_init( &ctx->mutex );\n#endif\n}\n\nvoid mbedtls_ssl_cookie_set_timeout( mbedtls_ssl_cookie_ctx *ctx, unsigned long delay )\n{\n    ctx->timeout = delay;\n}\n\nvoid mbedtls_ssl_cookie_free( mbedtls_ssl_cookie_ctx *ctx )\n{\n    mbedtls_md_free( &ctx->hmac_ctx );\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_mutex_free( &ctx->mutex );\n#endif\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ssl_cookie_ctx ) );\n}\n\nint mbedtls_ssl_cookie_setup( mbedtls_ssl_cookie_ctx *ctx,\n                      int (*f_rng)(void *, unsigned char *, size_t),\n                      void *p_rng )\n{\n    int ret;\n    unsigned char key[COOKIE_MD_OUTLEN];\n\n    if( ( ret = f_rng( p_rng, key, sizeof( key ) ) ) != 0 )\n        return( ret );\n\n    ret = mbedtls_md_setup( &ctx->hmac_ctx, mbedtls_md_info_from_type( COOKIE_MD ), 1 );\n    if( ret != 0 )\n        return( ret );\n\n    ret = mbedtls_md_hmac_starts( &ctx->hmac_ctx, key, sizeof( key ) );\n    if( ret != 0 )\n        return( ret );\n\n    mbedtls_platform_zeroize( key, sizeof( key ) );\n\n    return( 0 );\n}\n\n/*\n * Generate the HMAC part of a cookie\n */\nstatic int ssl_cookie_hmac( mbedtls_md_context_t *hmac_ctx,\n                            const unsigned char time[4],\n                            unsigned char **p, unsigned char *end,\n                            const unsigned char *cli_id, size_t cli_id_len )\n{\n    unsigned char hmac_out[COOKIE_MD_OUTLEN];\n\n    if( (size_t)( end - *p ) < COOKIE_HMAC_LEN )\n        return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );\n\n    if( mbedtls_md_hmac_reset(  hmac_ctx ) != 0 ||\n        mbedtls_md_hmac_update( hmac_ctx, time, 4 ) != 0 ||\n        mbedtls_md_hmac_update( hmac_ctx, cli_id, cli_id_len ) != 0 ||\n        mbedtls_md_hmac_finish( hmac_ctx, hmac_out ) != 0 )\n    {\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    memcpy( *p, hmac_out, COOKIE_HMAC_LEN );\n    *p += COOKIE_HMAC_LEN;\n\n    return( 0 );\n}\n\n/*\n * Generate cookie for DTLS ClientHello verification\n */\nint mbedtls_ssl_cookie_write( void *p_ctx,\n                      unsigned char **p, unsigned char *end,\n                      const unsigned char *cli_id, size_t cli_id_len )\n{\n    int ret;\n    mbedtls_ssl_cookie_ctx *ctx = (mbedtls_ssl_cookie_ctx *) p_ctx;\n    unsigned long t;\n\n    if( ctx == NULL || cli_id == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    if( (size_t)( end - *p ) < COOKIE_LEN )\n        return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );\n\n#if defined(MBEDTLS_HAVE_TIME)\n    t = (unsigned long) mbedtls_time( NULL );\n#else\n    t = ctx->serial++;\n#endif\n\n    (*p)[0] = (unsigned char)( t >> 24 );\n    (*p)[1] = (unsigned char)( t >> 16 );\n    (*p)[2] = (unsigned char)( t >>  8 );\n    (*p)[3] = (unsigned char)( t       );\n    *p += 4;\n\n#if defined(MBEDTLS_THREADING_C)\n    if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR + ret );\n#endif\n\n    ret = ssl_cookie_hmac( &ctx->hmac_ctx, *p - 4,\n                           p, end, cli_id, cli_id_len );\n\n#if defined(MBEDTLS_THREADING_C)\n    if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR +\n                MBEDTLS_ERR_THREADING_MUTEX_ERROR );\n#endif\n\n    return( ret );\n}\n\n/*\n * Check a cookie\n */\nint mbedtls_ssl_cookie_check( void *p_ctx,\n                      const unsigned char *cookie, size_t cookie_len,\n                      const unsigned char *cli_id, size_t cli_id_len )\n{\n    unsigned char ref_hmac[COOKIE_HMAC_LEN];\n    int ret = 0;\n    unsigned char *p = ref_hmac;\n    mbedtls_ssl_cookie_ctx *ctx = (mbedtls_ssl_cookie_ctx *) p_ctx;\n    unsigned long cur_time, cookie_time;\n\n    if( ctx == NULL || cli_id == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    if( cookie_len != COOKIE_LEN )\n        return( -1 );\n\n#if defined(MBEDTLS_THREADING_C)\n    if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR + ret );\n#endif\n\n    if( ssl_cookie_hmac( &ctx->hmac_ctx, cookie,\n                         &p, p + sizeof( ref_hmac ),\n                         cli_id, cli_id_len ) != 0 )\n        ret = -1;\n\n#if defined(MBEDTLS_THREADING_C)\n    if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR +\n                MBEDTLS_ERR_THREADING_MUTEX_ERROR );\n#endif\n\n    if( ret != 0 )\n        return( ret );\n\n    if( mbedtls_ssl_safer_memcmp( cookie + 4, ref_hmac, sizeof( ref_hmac ) ) != 0 )\n        return( -1 );\n\n#if defined(MBEDTLS_HAVE_TIME)\n    cur_time = (unsigned long) mbedtls_time( NULL );\n#else\n    cur_time = ctx->serial;\n#endif\n\n    cookie_time = ( (unsigned long) cookie[0] << 24 ) |\n                  ( (unsigned long) cookie[1] << 16 ) |\n                  ( (unsigned long) cookie[2] <<  8 ) |\n                  ( (unsigned long) cookie[3]       );\n\n    if( ctx->timeout != 0 && cur_time - cookie_time > ctx->timeout )\n        return( -1 );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_COOKIE_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/ssl_srv.c",
    "content": "/*\n *  SSLv3/TLSv1 server-side functions\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_SSL_SRV_C)\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc    calloc\n#define mbedtls_free      free\n#endif\n\n#include \"mbedtls/debug.h\"\n#include \"mbedtls/ssl.h\"\n#include \"mbedtls/ssl_internal.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_ECP_C)\n#include \"mbedtls/ecp.h\"\n#endif\n\n#if defined(MBEDTLS_HAVE_TIME)\n#include \"mbedtls/platform_time.h\"\n#endif\n\n#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)\nint mbedtls_ssl_set_client_transport_id( mbedtls_ssl_context *ssl,\n                                 const unsigned char *info,\n                                 size_t ilen )\n{\n    if( ssl->conf->endpoint != MBEDTLS_SSL_IS_SERVER )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    mbedtls_free( ssl->cli_id );\n\n    if( ( ssl->cli_id = mbedtls_calloc( 1, ilen ) ) == NULL )\n        return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n\n    memcpy( ssl->cli_id, info, ilen );\n    ssl->cli_id_len = ilen;\n\n    return( 0 );\n}\n\nvoid mbedtls_ssl_conf_dtls_cookies( mbedtls_ssl_config *conf,\n                           mbedtls_ssl_cookie_write_t *f_cookie_write,\n                           mbedtls_ssl_cookie_check_t *f_cookie_check,\n                           void *p_cookie )\n{\n    conf->f_cookie_write = f_cookie_write;\n    conf->f_cookie_check = f_cookie_check;\n    conf->p_cookie       = p_cookie;\n}\n#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */\n\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\nstatic int ssl_parse_servername_ext( mbedtls_ssl_context *ssl,\n                                     const unsigned char *buf,\n                                     size_t len )\n{\n    int ret;\n    size_t servername_list_size, hostname_len;\n    const unsigned char *p;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"parse ServerName extension\" ) );\n\n    if( len < 2 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n    servername_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );\n    if( servername_list_size + 2 != len )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    p = buf + 2;\n    while( servername_list_size > 2 )\n    {\n        hostname_len = ( ( p[1] << 8 ) | p[2] );\n        if( hostname_len + 3 > servername_list_size )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n        }\n\n        if( p[0] == MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME )\n        {\n            ret = ssl->conf->f_sni( ssl->conf->p_sni,\n                                    ssl, p + 3, hostname_len );\n            if( ret != 0 )\n            {\n                MBEDTLS_SSL_DEBUG_RET( 1, \"ssl_sni_wrapper\", ret );\n                mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                        MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME );\n                return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n            }\n            return( 0 );\n        }\n\n        servername_list_size -= hostname_len + 3;\n        p += hostname_len + 3;\n    }\n\n    if( servername_list_size != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */\n\nstatic int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl,\n                                         const unsigned char *buf,\n                                         size_t len )\n{\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )\n    {\n        /* Check verify-data in constant-time. The length OTOH is no secret */\n        if( len    != 1 + ssl->verify_data_len ||\n            buf[0] !=     ssl->verify_data_len ||\n            mbedtls_ssl_safer_memcmp( buf + 1, ssl->peer_verify_data,\n                          ssl->verify_data_len ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"non-matching renegotiation info\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n        }\n    }\n    else\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n    {\n        if( len != 1 || buf[0] != 0x0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"non-zero length renegotiation info\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n        }\n\n        ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;\n    }\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \\\n    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n\n/*\n * Status of the implementation of signature-algorithms extension:\n *\n * Currently, we are only considering the signature-algorithm extension\n * to pick a ciphersuite which allows us to send the ServerKeyExchange\n * message with a signature-hash combination that the user allows.\n *\n * We do *not* check whether all certificates in our certificate\n * chain are signed with an allowed signature-hash pair.\n * This needs to be done at a later stage.\n *\n */\nstatic int ssl_parse_signature_algorithms_ext( mbedtls_ssl_context *ssl,\n                                               const unsigned char *buf,\n                                               size_t len )\n{\n    size_t sig_alg_list_size;\n\n    const unsigned char *p;\n    const unsigned char *end = buf + len;\n\n    mbedtls_md_type_t md_cur;\n    mbedtls_pk_type_t sig_cur;\n\n    if ( len < 2 ) {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n    sig_alg_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );\n    if( sig_alg_list_size + 2 != len ||\n        sig_alg_list_size % 2 != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    /* Currently we only guarantee signing the ServerKeyExchange message according\n     * to the constraints specified in this extension (see above), so it suffices\n     * to remember only one suitable hash for each possible signature algorithm.\n     *\n     * This will change when we also consider certificate signatures,\n     * in which case we will need to remember the whole signature-hash\n     * pair list from the extension.\n     */\n\n    for( p = buf + 2; p < end; p += 2 )\n    {\n        /* Silently ignore unknown signature or hash algorithms. */\n\n        if( ( sig_cur = mbedtls_ssl_pk_alg_from_sig( p[1] ) ) == MBEDTLS_PK_NONE )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello v3, signature_algorithm ext\"\n                                        \" unknown sig alg encoding %d\", p[1] ) );\n            continue;\n        }\n\n        /* Check if we support the hash the user proposes */\n        md_cur = mbedtls_ssl_md_alg_from_hash( p[0] );\n        if( md_cur == MBEDTLS_MD_NONE )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello v3, signature_algorithm ext:\"\n                                        \" unknown hash alg encoding %d\", p[0] ) );\n            continue;\n        }\n\n        if( mbedtls_ssl_check_sig_hash( ssl, md_cur ) == 0 )\n        {\n            mbedtls_ssl_sig_hash_set_add( &ssl->handshake->hash_algs, sig_cur, md_cur );\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello v3, signature_algorithm ext:\"\n                                        \" match sig %d and hash %d\",\n                                        sig_cur, md_cur ) );\n        }\n        else\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello v3, signature_algorithm ext: \"\n                                        \"hash alg %d not supported\", md_cur ) );\n        }\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&\n          MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */\n\n#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\nstatic int ssl_parse_supported_elliptic_curves( mbedtls_ssl_context *ssl,\n                                                const unsigned char *buf,\n                                                size_t len )\n{\n    size_t list_size, our_size;\n    const unsigned char *p;\n    const mbedtls_ecp_curve_info *curve_info, **curves;\n\n    if ( len < 2 ) {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n    list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );\n    if( list_size + 2 != len ||\n        list_size % 2 != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    /* Should never happen unless client duplicates the extension */\n    if( ssl->handshake->curves != NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    /* Don't allow our peer to make us allocate too much memory,\n     * and leave room for a final 0 */\n    our_size = list_size / 2 + 1;\n    if( our_size > MBEDTLS_ECP_DP_MAX )\n        our_size = MBEDTLS_ECP_DP_MAX;\n\n    if( ( curves = mbedtls_calloc( our_size, sizeof( *curves ) ) ) == NULL )\n    {\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );\n        return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n    }\n\n    ssl->handshake->curves = curves;\n\n    p = buf + 2;\n    while( list_size > 0 && our_size > 1 )\n    {\n        curve_info = mbedtls_ecp_curve_info_from_tls_id( ( p[0] << 8 ) | p[1] );\n\n        if( curve_info != NULL )\n        {\n            *curves++ = curve_info;\n            our_size--;\n        }\n\n        list_size -= 2;\n        p += 2;\n    }\n\n    return( 0 );\n}\n\nstatic int ssl_parse_supported_point_formats( mbedtls_ssl_context *ssl,\n                                              const unsigned char *buf,\n                                              size_t len )\n{\n    size_t list_size;\n    const unsigned char *p;\n\n    if( len == 0 || (size_t)( buf[0] + 1 ) != len )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n    list_size = buf[0];\n\n    p = buf + 1;\n    while( list_size > 0 )\n    {\n        if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||\n            p[0] == MBEDTLS_ECP_PF_COMPRESSED )\n        {\n#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)\n            ssl->handshake->ecdh_ctx.point_format = p[0];\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n            ssl->handshake->ecjpake_ctx.point_format = p[0];\n#endif\n            MBEDTLS_SSL_DEBUG_MSG( 4, ( \"point format selected: %d\", p[0] ) );\n            return( 0 );\n        }\n\n        list_size--;\n        p++;\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||\n          MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\nstatic int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl,\n                                   const unsigned char *buf,\n                                   size_t len )\n{\n    int ret;\n\n    if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"skip ecjpake kkpp extension\" ) );\n        return( 0 );\n    }\n\n    if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx,\n                                                buf, len ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecjpake_read_round_one\", ret );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n        return( ret );\n    }\n\n    /* Only mark the extension as OK when we're sure it is */\n    ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\nstatic int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl,\n                                              const unsigned char *buf,\n                                              size_t len )\n{\n    if( len != 1 || buf[0] >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    ssl->session_negotiate->mfl_code = buf[0];\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */\n\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)\nstatic int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl,\n                                         const unsigned char *buf,\n                                         size_t len )\n{\n    if( len != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    ((void) buf);\n\n    if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )\n        ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */\n\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\nstatic int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,\n                                      const unsigned char *buf,\n                                      size_t len )\n{\n    if( len != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    ((void) buf);\n\n    if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED &&\n        ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )\n    {\n        ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */\n\n#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)\nstatic int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl,\n                                      const unsigned char *buf,\n                                      size_t len )\n{\n    if( len != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    ((void) buf);\n\n    if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED &&\n        ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )\n    {\n        ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\nstatic int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl,\n                                         unsigned char *buf,\n                                         size_t len )\n{\n    int ret;\n    mbedtls_ssl_session session;\n\n    mbedtls_ssl_session_init( &session );\n\n    if( ssl->conf->f_ticket_parse == NULL ||\n        ssl->conf->f_ticket_write == NULL )\n    {\n        return( 0 );\n    }\n\n    /* Remember the client asked us to send a new ticket */\n    ssl->handshake->new_session_ticket = 1;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ticket length: %d\", len ) );\n\n    if( len == 0 )\n        return( 0 );\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ticket rejected: renegotiating\" ) );\n        return( 0 );\n    }\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n\n    /*\n     * Failures are ok: just ignore the ticket and proceed.\n     */\n    if( ( ret = ssl->conf->f_ticket_parse( ssl->conf->p_ticket, &session,\n                                           buf, len ) ) != 0 )\n    {\n        mbedtls_ssl_session_free( &session );\n\n        if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ticket is not authentic\" ) );\n        else if( ret == MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED )\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ticket is expired\" ) );\n        else\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_ticket_parse\", ret );\n\n        return( 0 );\n    }\n\n    /*\n     * Keep the session ID sent by the client, since we MUST send it back to\n     * inform them we're accepting the ticket  (RFC 5077 section 3.4)\n     */\n    session.id_len = ssl->session_negotiate->id_len;\n    memcpy( &session.id, ssl->session_negotiate->id, session.id_len );\n\n    mbedtls_ssl_session_free( ssl->session_negotiate );\n    memcpy( ssl->session_negotiate, &session, sizeof( mbedtls_ssl_session ) );\n\n    /* Zeroize instead of free as we copied the content */\n    mbedtls_platform_zeroize( &session, sizeof( mbedtls_ssl_session ) );\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"session successfully restored from ticket\" ) );\n\n    ssl->handshake->resume = 1;\n\n    /* Don't send a new ticket after all, this one is OK */\n    ssl->handshake->new_session_ticket = 0;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_SESSION_TICKETS */\n\n#if defined(MBEDTLS_SSL_ALPN)\nstatic int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,\n                               const unsigned char *buf, size_t len )\n{\n    size_t list_len, cur_len, ours_len;\n    const unsigned char *theirs, *start, *end;\n    const char **ours;\n\n    /* If ALPN not configured, just ignore the extension */\n    if( ssl->conf->alpn_list == NULL )\n        return( 0 );\n\n    /*\n     * opaque ProtocolName<1..2^8-1>;\n     *\n     * struct {\n     *     ProtocolName protocol_name_list<2..2^16-1>\n     * } ProtocolNameList;\n     */\n\n    /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */\n    if( len < 4 )\n    {\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    list_len = ( buf[0] << 8 ) | buf[1];\n    if( list_len != len - 2 )\n    {\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    /*\n     * Validate peer's list (lengths)\n     */\n    start = buf + 2;\n    end = buf + len;\n    for( theirs = start; theirs != end; theirs += cur_len )\n    {\n        cur_len = *theirs++;\n\n        /* Current identifier must fit in list */\n        if( cur_len > (size_t)( end - theirs ) )\n        {\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n        }\n\n        /* Empty strings MUST NOT be included */\n        if( cur_len == 0 )\n        {\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n        }\n    }\n\n    /*\n     * Use our order of preference\n     */\n    for( ours = ssl->conf->alpn_list; *ours != NULL; ours++ )\n    {\n        ours_len = strlen( *ours );\n        for( theirs = start; theirs != end; theirs += cur_len )\n        {\n            cur_len = *theirs++;\n\n            if( cur_len == ours_len &&\n                memcmp( theirs, *ours, cur_len ) == 0 )\n            {\n                ssl->alpn_chosen = *ours;\n                return( 0 );\n            }\n        }\n    }\n\n    /* If we get there, no match was found */\n    mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                            MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL );\n    return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n}\n#endif /* MBEDTLS_SSL_ALPN */\n\n/*\n * Auxiliary functions for ServerHello parsing and related actions\n */\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n/*\n * Return 0 if the given key uses one of the acceptable curves, -1 otherwise\n */\n#if defined(MBEDTLS_ECDSA_C)\nstatic int ssl_check_key_curve( mbedtls_pk_context *pk,\n                                const mbedtls_ecp_curve_info **curves )\n{\n    const mbedtls_ecp_curve_info **crv = curves;\n    mbedtls_ecp_group_id grp_id = mbedtls_pk_ec( *pk )->grp.id;\n\n    while( *crv != NULL )\n    {\n        if( (*crv)->grp_id == grp_id )\n            return( 0 );\n        crv++;\n    }\n\n    return( -1 );\n}\n#endif /* MBEDTLS_ECDSA_C */\n\n/*\n * Try picking a certificate for this ciphersuite,\n * return 0 on success and -1 on failure.\n */\nstatic int ssl_pick_cert( mbedtls_ssl_context *ssl,\n                          const mbedtls_ssl_ciphersuite_t * ciphersuite_info )\n{\n    mbedtls_ssl_key_cert *cur, *list, *fallback = NULL;\n    mbedtls_pk_type_t pk_alg =\n        mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );\n    uint32_t flags;\n\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\n    if( ssl->handshake->sni_key_cert != NULL )\n        list = ssl->handshake->sni_key_cert;\n    else\n#endif\n        list = ssl->conf->key_cert;\n\n    if( pk_alg == MBEDTLS_PK_NONE )\n        return( 0 );\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciphersuite requires certificate\" ) );\n\n    if( list == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server has no certificate\" ) );\n        return( -1 );\n    }\n\n    for( cur = list; cur != NULL; cur = cur->next )\n    {\n        MBEDTLS_SSL_DEBUG_CRT( 3, \"candidate certificate chain, certificate\",\n                          cur->cert );\n\n        if( ! mbedtls_pk_can_do( &cur->cert->pk, pk_alg ) )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"certificate mismatch: key type\" ) );\n            continue;\n        }\n\n        /*\n         * This avoids sending the client a cert it'll reject based on\n         * keyUsage or other extensions.\n         *\n         * It also allows the user to provision different certificates for\n         * different uses based on keyUsage, eg if they want to avoid signing\n         * and decrypting with the same RSA key.\n         */\n        if( mbedtls_ssl_check_cert_usage( cur->cert, ciphersuite_info,\n                                  MBEDTLS_SSL_IS_SERVER, &flags ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"certificate mismatch: \"\n                                \"(extended) key usage extension\" ) );\n            continue;\n        }\n\n#if defined(MBEDTLS_ECDSA_C)\n        if( pk_alg == MBEDTLS_PK_ECDSA &&\n            ssl_check_key_curve( &cur->cert->pk, ssl->handshake->curves ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"certificate mismatch: elliptic curve\" ) );\n            continue;\n        }\n#endif\n\n        /*\n         * Try to select a SHA-1 certificate for pre-1.2 clients, but still\n         * present them a SHA-higher cert rather than failing if it's the only\n         * one we got that satisfies the other conditions.\n         */\n        if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 &&\n            cur->cert->sig_md != MBEDTLS_MD_SHA1 )\n        {\n            if( fallback == NULL )\n                fallback = cur;\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 3, ( \"certificate not preferred: \"\n                                    \"sha-2 with pre-TLS 1.2 client\" ) );\n            continue;\n            }\n        }\n\n        /* If we get there, we got a winner */\n        break;\n    }\n\n    if( cur == NULL )\n        cur = fallback;\n\n    /* Do not update ssl->handshake->key_cert unless there is a match */\n    if( cur != NULL )\n    {\n        ssl->handshake->key_cert = cur;\n        MBEDTLS_SSL_DEBUG_CRT( 3, \"selected certificate chain, certificate\",\n                          ssl->handshake->key_cert->cert );\n        return( 0 );\n    }\n\n    return( -1 );\n}\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n/*\n * Check if a given ciphersuite is suitable for use with our config/keys/etc\n * Sets ciphersuite_info only if the suite matches.\n */\nstatic int ssl_ciphersuite_match( mbedtls_ssl_context *ssl, int suite_id,\n                                  const mbedtls_ssl_ciphersuite_t **ciphersuite_info )\n{\n    const mbedtls_ssl_ciphersuite_t *suite_info;\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \\\n    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n    mbedtls_pk_type_t sig_type;\n#endif\n\n    suite_info = mbedtls_ssl_ciphersuite_from_id( suite_id );\n    if( suite_info == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"trying ciphersuite: %s\", suite_info->name ) );\n\n    if( suite_info->min_minor_ver > ssl->minor_ver ||\n        suite_info->max_minor_ver < ssl->minor_ver )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciphersuite mismatch: version\" ) );\n        return( 0 );\n    }\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&\n        ( suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )\n        return( 0 );\n#endif\n\n#if defined(MBEDTLS_ARC4_C)\n    if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&\n            suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciphersuite mismatch: rc4\" ) );\n        return( 0 );\n    }\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&\n        ( ssl->handshake->cli_exts & MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK ) == 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciphersuite mismatch: ecjpake \"\n                                    \"not configured or ext missing\" ) );\n        return( 0 );\n    }\n#endif\n\n\n#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)\n    if( mbedtls_ssl_ciphersuite_uses_ec( suite_info ) &&\n        ( ssl->handshake->curves == NULL ||\n          ssl->handshake->curves[0] == NULL ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciphersuite mismatch: \"\n                            \"no common elliptic curve\" ) );\n        return( 0 );\n    }\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)\n    /* If the ciphersuite requires a pre-shared key and we don't\n     * have one, skip it now rather than failing later */\n    if( mbedtls_ssl_ciphersuite_uses_psk( suite_info ) &&\n        ssl->conf->f_psk == NULL &&\n        ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL ||\n          ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciphersuite mismatch: no pre-shared key\" ) );\n        return( 0 );\n    }\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \\\n    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n    /* If the ciphersuite requires signing, check whether\n     * a suitable hash algorithm is present. */\n    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )\n    {\n        sig_type = mbedtls_ssl_get_ciphersuite_sig_alg( suite_info );\n        if( sig_type != MBEDTLS_PK_NONE &&\n            mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, sig_type ) == MBEDTLS_MD_NONE )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciphersuite mismatch: no suitable hash algorithm \"\n                                        \"for signature algorithm %d\", sig_type ) );\n            return( 0 );\n        }\n    }\n\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&\n          MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    /*\n     * Final check: if ciphersuite requires us to have a\n     * certificate/key of a particular type:\n     * - select the appropriate certificate if we have one, or\n     * - try the next ciphersuite if we don't\n     * This must be done last since we modify the key_cert list.\n     */\n    if( ssl_pick_cert( ssl, suite_info ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciphersuite mismatch: \"\n                            \"no suitable certificate\" ) );\n        return( 0 );\n    }\n#endif\n\n    *ciphersuite_info = suite_info;\n    return( 0 );\n}\n\n#if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO)\nstatic int ssl_parse_client_hello_v2( mbedtls_ssl_context *ssl )\n{\n    int ret, got_common_suite;\n    unsigned int i, j;\n    size_t n;\n    unsigned int ciph_len, sess_len, chal_len;\n    unsigned char *buf, *p;\n    const int *ciphersuites;\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse client hello v2\" ) );\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"client hello v2 illegal for renegotiation\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n\n    buf = ssl->in_hdr;\n\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"record header\", buf, 5 );\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello v2, message type: %d\",\n                   buf[2] ) );\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello v2, message len.: %d\",\n                   ( ( buf[0] & 0x7F ) << 8 ) | buf[1] ) );\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello v2, max. version: [%d:%d]\",\n                   buf[3], buf[4] ) );\n\n    /*\n     * SSLv2 Client Hello\n     *\n     * Record layer:\n     *     0  .   1   message length\n     *\n     * SSL layer:\n     *     2  .   2   message type\n     *     3  .   4   protocol version\n     */\n    if( buf[2] != MBEDTLS_SSL_HS_CLIENT_HELLO ||\n        buf[3] != MBEDTLS_SSL_MAJOR_VERSION_3 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    n = ( ( buf[0] << 8 ) | buf[1] ) & 0x7FFF;\n\n    if( n < 17 || n > 512 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    ssl->major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;\n    ssl->minor_ver = ( buf[4] <= ssl->conf->max_minor_ver )\n                     ? buf[4]  : ssl->conf->max_minor_ver;\n\n    if( ssl->minor_ver < ssl->conf->min_minor_ver )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"client only supports ssl smaller than minimum\"\n                            \" [%d:%d] < [%d:%d]\",\n                            ssl->major_ver, ssl->minor_ver,\n                            ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) );\n\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                     MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );\n        return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );\n    }\n\n    ssl->handshake->max_major_ver = buf[3];\n    ssl->handshake->max_minor_ver = buf[4];\n\n    if( ( ret = mbedtls_ssl_fetch_input( ssl, 2 + n ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_fetch_input\", ret );\n        return( ret );\n    }\n\n    ssl->handshake->update_checksum( ssl, buf + 2, n );\n\n    buf = ssl->in_msg;\n    n = ssl->in_left - 5;\n\n    /*\n     *    0  .   1   ciphersuitelist length\n     *    2  .   3   session id length\n     *    4  .   5   challenge length\n     *    6  .  ..   ciphersuitelist\n     *   ..  .  ..   session id\n     *   ..  .  ..   challenge\n     */\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"record contents\", buf, n );\n\n    ciph_len = ( buf[0] << 8 ) | buf[1];\n    sess_len = ( buf[2] << 8 ) | buf[3];\n    chal_len = ( buf[4] << 8 ) | buf[5];\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciph_len: %d, sess_len: %d, chal_len: %d\",\n                   ciph_len, sess_len, chal_len ) );\n\n    /*\n     * Make sure each parameter length is valid\n     */\n    if( ciph_len < 3 || ( ciph_len % 3 ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    if( sess_len > 32 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    if( chal_len < 8 || chal_len > 32 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    if( n != 6 + ciph_len + sess_len + chal_len )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"client hello, ciphersuitelist\",\n                   buf + 6, ciph_len );\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"client hello, session id\",\n                   buf + 6 + ciph_len, sess_len );\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"client hello, challenge\",\n                   buf + 6 + ciph_len + sess_len, chal_len );\n\n    p = buf + 6 + ciph_len;\n    ssl->session_negotiate->id_len = sess_len;\n    memset( ssl->session_negotiate->id, 0,\n            sizeof( ssl->session_negotiate->id ) );\n    memcpy( ssl->session_negotiate->id, p, ssl->session_negotiate->id_len );\n\n    p += sess_len;\n    memset( ssl->handshake->randbytes, 0, 64 );\n    memcpy( ssl->handshake->randbytes + 32 - chal_len, p, chal_len );\n\n    /*\n     * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV\n     */\n    for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 )\n    {\n        if( p[0] == 0 && p[1] == 0 && p[2] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"received TLS_EMPTY_RENEGOTIATION_INFO \" ) );\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n            if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"received RENEGOTIATION SCSV \"\n                                    \"during renegotiation\" ) );\n\n                mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                                MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n                return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n            }\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n            ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;\n            break;\n        }\n    }\n\n#if defined(MBEDTLS_SSL_FALLBACK_SCSV)\n    for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 )\n    {\n        if( p[0] == 0 &&\n            p[1] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ) & 0xff ) &&\n            p[2] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE      ) & 0xff ) )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"received FALLBACK_SCSV\" ) );\n\n            if( ssl->minor_ver < ssl->conf->max_minor_ver )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"inapropriate fallback\" ) );\n\n                mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK );\n\n                return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n            }\n\n            break;\n        }\n    }\n#endif /* MBEDTLS_SSL_FALLBACK_SCSV */\n\n    got_common_suite = 0;\n    ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];\n    ciphersuite_info = NULL;\n#if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE)\n    for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 )\n        for( i = 0; ciphersuites[i] != 0; i++ )\n#else\n    for( i = 0; ciphersuites[i] != 0; i++ )\n        for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 )\n#endif\n        {\n            if( p[0] != 0 ||\n                p[1] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) ||\n                p[2] != ( ( ciphersuites[i]      ) & 0xFF ) )\n                continue;\n\n            got_common_suite = 1;\n\n            if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i],\n                                               &ciphersuite_info ) ) != 0 )\n                return( ret );\n\n            if( ciphersuite_info != NULL )\n                goto have_ciphersuite_v2;\n        }\n\n    if( got_common_suite )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"got ciphersuites in common, \"\n                            \"but none of them usable\" ) );\n        return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE );\n    }\n    else\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"got no ciphersuites in common\" ) );\n        return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN );\n    }\n\nhave_ciphersuite_v2:\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"selected ciphersuite: %s\", ciphersuite_info->name ) );\n\n    ssl->session_negotiate->ciphersuite = ciphersuites[i];\n    ssl->transform_negotiate->ciphersuite_info = ciphersuite_info;\n\n    /*\n     * SSLv2 Client Hello relevant renegotiation security checks\n     */\n    if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&\n        ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"legacy renegotiation, breaking off handshake\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    ssl->in_left = 0;\n    ssl->state++;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= parse client hello v2\" ) );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO */\n\n/* This function doesn't alert on errors that happen early during\n   ClientHello parsing because they might indicate that the client is\n   not talking SSL/TLS at all and would not understand our alert. */\nstatic int ssl_parse_client_hello( mbedtls_ssl_context *ssl )\n{\n    int ret, got_common_suite;\n    size_t i, j;\n    size_t ciph_offset, comp_offset, ext_offset;\n    size_t msg_len, ciph_len, sess_len, comp_len, ext_len;\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    size_t cookie_offset, cookie_len;\n#endif\n    unsigned char *buf, *p, *ext;\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    int renegotiation_info_seen = 0;\n#endif\n    int handshake_failure = 0;\n    const int *ciphersuites;\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info;\n    int major, minor;\n\n    /* If there is no signature-algorithm extension present,\n     * we need to fall back to the default values for allowed\n     * signature-hash pairs. */\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \\\n    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n    int sig_hash_alg_ext_present = 0;\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&\n          MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse client hello\" ) );\n\n#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)\nread_record_header:\n#endif\n    /*\n     * If renegotiating, then the input was read with mbedtls_ssl_read_record(),\n     * otherwise read it ourselves manually in order to support SSLv2\n     * ClientHello, which doesn't use the same record layer format.\n     */\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )\n#endif\n    {\n        if( ( ret = mbedtls_ssl_fetch_input( ssl, 5 ) ) != 0 )\n        {\n            /* No alert on a read error. */\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_fetch_input\", ret );\n            return( ret );\n        }\n    }\n\n    buf = ssl->in_hdr;\n\n#if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO)\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM )\n#endif\n        if( ( buf[0] & 0x80 ) != 0 )\n            return( ssl_parse_client_hello_v2( ssl ) );\n#endif\n\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"record header\", buf, mbedtls_ssl_hdr_len( ssl ) );\n\n    /*\n     * SSLv3/TLS Client Hello\n     *\n     * Record layer:\n     *     0  .   0   message type\n     *     1  .   2   protocol version\n     *     3  .   11  DTLS: epoch + record sequence number\n     *     3  .   4   message length\n     */\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello v3, message type: %d\",\n                   buf[0] ) );\n\n    if( buf[0] != MBEDTLS_SSL_MSG_HANDSHAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello v3, message len.: %d\",\n                   ( ssl->in_len[0] << 8 ) | ssl->in_len[1] ) );\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello v3, protocol version: [%d:%d]\",\n                   buf[1], buf[2] ) );\n\n    mbedtls_ssl_read_version( &major, &minor, ssl->conf->transport, buf + 1 );\n\n    /* According to RFC 5246 Appendix E.1, the version here is typically\n     * \"{03,00}, the lowest version number supported by the client, [or] the\n     * value of ClientHello.client_version\", so the only meaningful check here\n     * is the major version shouldn't be less than 3 */\n    if( major < MBEDTLS_SSL_MAJOR_VERSION_3 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    /* For DTLS if this is the initial handshake, remember the client sequence\n     * number to use it in our next message (RFC 6347 4.2.1) */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n        && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE\n#endif\n        )\n    {\n        /* Epoch should be 0 for initial handshakes */\n        if( ssl->in_ctr[0] != 0 || ssl->in_ctr[1] != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n        }\n\n        memcpy( ssl->out_ctr + 2, ssl->in_ctr + 2, 6 );\n\n#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)\n        if( mbedtls_ssl_dtls_replay_check( ssl ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"replayed record, discarding\" ) );\n            ssl->next_record_offset = 0;\n            ssl->in_left = 0;\n            goto read_record_header;\n        }\n\n        /* No MAC to check yet, so we can update right now */\n        mbedtls_ssl_dtls_replay_update( ssl );\n#endif\n    }\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n\n    msg_len = ( ssl->in_len[0] << 8 ) | ssl->in_len[1];\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )\n    {\n        /* Set by mbedtls_ssl_read_record() */\n        msg_len = ssl->in_hslen;\n    }\n    else\n#endif\n    {\n        if( msg_len > MBEDTLS_SSL_IN_CONTENT_LEN )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n        }\n\n        if( ( ret = mbedtls_ssl_fetch_input( ssl,\n                       mbedtls_ssl_hdr_len( ssl ) + msg_len ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_fetch_input\", ret );\n            return( ret );\n        }\n\n    /* Done reading this record, get ready for the next one */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n        if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n            ssl->next_record_offset = msg_len + mbedtls_ssl_hdr_len( ssl );\n        else\n#endif\n            ssl->in_left = 0;\n    }\n\n    buf = ssl->in_msg;\n\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"record contents\", buf, msg_len );\n\n    ssl->handshake->update_checksum( ssl, buf, msg_len );\n\n    /*\n     * Handshake layer:\n     *     0  .   0   handshake type\n     *     1  .   3   handshake length\n     *     4  .   5   DTLS only: message seqence number\n     *     6  .   8   DTLS only: fragment offset\n     *     9  .  11   DTLS only: fragment length\n     */\n    if( msg_len < mbedtls_ssl_hs_hdr_len( ssl ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello v3, handshake type: %d\", buf[0] ) );\n\n    if( buf[0] != MBEDTLS_SSL_HS_CLIENT_HELLO )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello v3, handshake len.: %d\",\n                   ( buf[1] << 16 ) | ( buf[2] << 8 ) | buf[3] ) );\n\n    /* We don't support fragmentation of ClientHello (yet?) */\n    if( buf[1] != 0 ||\n        msg_len != mbedtls_ssl_hs_hdr_len( ssl ) + ( ( buf[2] << 8 ) | buf[3] ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        /*\n         * Copy the client's handshake message_seq on initial handshakes,\n         * check sequence number on renego.\n         */\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n        if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )\n        {\n            /* This couldn't be done in ssl_prepare_handshake_record() */\n            unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) |\n                                         ssl->in_msg[5];\n\n            if( cli_msg_seq != ssl->handshake->in_msg_seq )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message_seq: \"\n                                    \"%d (expected %d)\", cli_msg_seq,\n                                    ssl->handshake->in_msg_seq ) );\n                return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n            }\n\n            ssl->handshake->in_msg_seq++;\n        }\n        else\n#endif\n        {\n            unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) |\n                                         ssl->in_msg[5];\n            ssl->handshake->out_msg_seq = cli_msg_seq;\n            ssl->handshake->in_msg_seq  = cli_msg_seq + 1;\n        }\n\n        /*\n         * For now we don't support fragmentation, so make sure\n         * fragment_offset == 0 and fragment_length == length\n         */\n        if( ssl->in_msg[6] != 0 || ssl->in_msg[7] != 0 || ssl->in_msg[8] != 0 ||\n            memcmp( ssl->in_msg + 1, ssl->in_msg + 9, 3 ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"ClientHello fragmentation not supported\" ) );\n            return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );\n        }\n    }\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n\n    buf += mbedtls_ssl_hs_hdr_len( ssl );\n    msg_len -= mbedtls_ssl_hs_hdr_len( ssl );\n\n    /*\n     * ClientHello layer:\n     *     0  .   1   protocol version\n     *     2  .  33   random bytes (starting with 4 bytes of Unix time)\n     *    34  .  35   session id length (1 byte)\n     *    35  . 34+x  session id\n     *   35+x . 35+x  DTLS only: cookie length (1 byte)\n     *   36+x .  ..   DTLS only: cookie\n     *    ..  .  ..   ciphersuite list length (2 bytes)\n     *    ..  .  ..   ciphersuite list\n     *    ..  .  ..   compression alg. list length (1 byte)\n     *    ..  .  ..   compression alg. list\n     *    ..  .  ..   extensions length (2 bytes, optional)\n     *    ..  .  ..   extensions (optional)\n     */\n\n    /*\n     * Minimal length (with everything empty and extensions ommitted) is\n     * 2 + 32 + 1 + 2 + 1 = 38 bytes. Check that first, so that we can\n     * read at least up to session id length without worrying.\n     */\n    if( msg_len < 38 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    /*\n     * Check and save the protocol version\n     */\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"client hello, version\", buf, 2 );\n\n    mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver,\n                      ssl->conf->transport, buf );\n\n    ssl->handshake->max_major_ver = ssl->major_ver;\n    ssl->handshake->max_minor_ver = ssl->minor_ver;\n\n    if( ssl->major_ver < ssl->conf->min_major_ver ||\n        ssl->minor_ver < ssl->conf->min_minor_ver )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"client only supports ssl smaller than minimum\"\n                            \" [%d:%d] < [%d:%d]\",\n                            ssl->major_ver, ssl->minor_ver,\n                            ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                     MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );\n        return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );\n    }\n\n    if( ssl->major_ver > ssl->conf->max_major_ver )\n    {\n        ssl->major_ver = ssl->conf->max_major_ver;\n        ssl->minor_ver = ssl->conf->max_minor_ver;\n    }\n    else if( ssl->minor_ver > ssl->conf->max_minor_ver )\n        ssl->minor_ver = ssl->conf->max_minor_ver;\n\n    /*\n     * Save client random (inc. Unix time)\n     */\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"client hello, random bytes\", buf + 2, 32 );\n\n    memcpy( ssl->handshake->randbytes, buf + 2, 32 );\n\n    /*\n     * Check the session ID length and save session ID\n     */\n    sess_len = buf[34];\n\n    if( sess_len > sizeof( ssl->session_negotiate->id ) ||\n        sess_len + 34 + 2 > msg_len ) /* 2 for cipherlist length field */\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"client hello, session id\", buf + 35, sess_len );\n\n    ssl->session_negotiate->id_len = sess_len;\n    memset( ssl->session_negotiate->id, 0,\n            sizeof( ssl->session_negotiate->id ) );\n    memcpy( ssl->session_negotiate->id, buf + 35,\n            ssl->session_negotiate->id_len );\n\n    /*\n     * Check the cookie length and content\n     */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        cookie_offset = 35 + sess_len;\n        cookie_len = buf[cookie_offset];\n\n        if( cookie_offset + 1 + cookie_len + 2 > msg_len )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n        }\n\n        MBEDTLS_SSL_DEBUG_BUF( 3, \"client hello, cookie\",\n                       buf + cookie_offset + 1, cookie_len );\n\n#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)\n        if( ssl->conf->f_cookie_check != NULL\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n            && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE\n#endif\n            )\n        {\n            if( ssl->conf->f_cookie_check( ssl->conf->p_cookie,\n                                     buf + cookie_offset + 1, cookie_len,\n                                     ssl->cli_id, ssl->cli_id_len ) != 0 )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 2, ( \"cookie verification failed\" ) );\n                ssl->handshake->verify_cookie_len = 1;\n            }\n            else\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 2, ( \"cookie verification passed\" ) );\n                ssl->handshake->verify_cookie_len = 0;\n            }\n        }\n        else\n#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */\n        {\n            /* We know we didn't send a cookie, so it should be empty */\n            if( cookie_len != 0 )\n            {\n                /* This may be an attacker's probe, so don't send an alert */\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n                return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n            }\n\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"cookie verification skipped\" ) );\n        }\n\n    /*\n     * Check the ciphersuitelist length (will be parsed later)\n     */\n        ciph_offset = cookie_offset + 1 + cookie_len;\n    }\n    else\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n        ciph_offset = 35 + sess_len;\n\n    ciph_len = ( buf[ciph_offset + 0] << 8 )\n             | ( buf[ciph_offset + 1]      );\n\n    if( ciph_len < 2 ||\n        ciph_len + 2 + ciph_offset + 1 > msg_len || /* 1 for comp. alg. len */\n        ( ciph_len % 2 ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"client hello, ciphersuitelist\",\n                   buf + ciph_offset + 2,  ciph_len );\n\n    /*\n     * Check the compression algorithms length and pick one\n     */\n    comp_offset = ciph_offset + 2 + ciph_len;\n\n    comp_len = buf[comp_offset];\n\n    if( comp_len < 1 ||\n        comp_len > 16 ||\n        comp_len + comp_offset + 1 > msg_len )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"client hello, compression\",\n                      buf + comp_offset + 1, comp_len );\n\n    ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL;\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n    for( i = 0; i < comp_len; ++i )\n    {\n        if( buf[comp_offset + 1 + i] == MBEDTLS_SSL_COMPRESS_DEFLATE )\n        {\n            ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_DEFLATE;\n            break;\n        }\n    }\n#endif\n\n    /* See comments in ssl_write_client_hello() */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n        ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL;\n#endif\n\n    /* Do not parse the extensions if the protocol is SSLv3 */\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n    if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) )\n    {\n#endif\n        /*\n         * Check the extension length\n         */\n        ext_offset = comp_offset + 1 + comp_len;\n        if( msg_len > ext_offset )\n        {\n            if( msg_len < ext_offset + 2 )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n                mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                                MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n                return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n            }\n\n            ext_len = ( buf[ext_offset + 0] << 8 )\n                    | ( buf[ext_offset + 1]      );\n\n            if( ( ext_len > 0 && ext_len < 4 ) ||\n                msg_len != ext_offset + 2 + ext_len )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n                mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                                MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n                return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n            }\n        }\n        else\n            ext_len = 0;\n\n        ext = buf + ext_offset + 2;\n        MBEDTLS_SSL_DEBUG_BUF( 3, \"client hello extensions\", ext, ext_len );\n\n        while( ext_len != 0 )\n        {\n            unsigned int ext_id;\n            unsigned int ext_size;\n            if ( ext_len < 4 ) {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n                mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                               MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n                return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n            }\n            ext_id   = ( ( ext[0] <<  8 ) | ( ext[1] ) );\n            ext_size = ( ( ext[2] <<  8 ) | ( ext[3] ) );\n\n            if( ext_size + 4 > ext_len )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n                mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                                MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n                return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n            }\n            switch( ext_id )\n            {\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\n            case MBEDTLS_TLS_EXT_SERVERNAME:\n                MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found ServerName extension\" ) );\n                if( ssl->conf->f_sni == NULL )\n                    break;\n\n                ret = ssl_parse_servername_ext( ssl, ext + 4, ext_size );\n                if( ret != 0 )\n                    return( ret );\n                break;\n#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */\n\n            case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:\n                MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found renegotiation extension\" ) );\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n                renegotiation_info_seen = 1;\n#endif\n\n                ret = ssl_parse_renegotiation_info( ssl, ext + 4, ext_size );\n                if( ret != 0 )\n                    return( ret );\n                break;\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \\\n    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n            case MBEDTLS_TLS_EXT_SIG_ALG:\n                MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found signature_algorithms extension\" ) );\n\n                ret = ssl_parse_signature_algorithms_ext( ssl, ext + 4, ext_size );\n                if( ret != 0 )\n                    return( ret );\n\n                sig_hash_alg_ext_present = 1;\n                break;\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&\n          MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */\n\n#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n            case MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES:\n                MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found supported elliptic curves extension\" ) );\n\n                ret = ssl_parse_supported_elliptic_curves( ssl, ext + 4, ext_size );\n                if( ret != 0 )\n                    return( ret );\n                break;\n\n            case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:\n                MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found supported point formats extension\" ) );\n                ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT;\n\n                ret = ssl_parse_supported_point_formats( ssl, ext + 4, ext_size );\n                if( ret != 0 )\n                    return( ret );\n                break;\n#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||\n          MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n            case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:\n                MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found ecjpake kkpp extension\" ) );\n\n                ret = ssl_parse_ecjpake_kkpp( ssl, ext + 4, ext_size );\n                if( ret != 0 )\n                    return( ret );\n                break;\n#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\n            case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:\n                MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found max fragment length extension\" ) );\n\n                ret = ssl_parse_max_fragment_length_ext( ssl, ext + 4, ext_size );\n                if( ret != 0 )\n                    return( ret );\n                break;\n#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */\n\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)\n            case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:\n                MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found truncated hmac extension\" ) );\n\n                ret = ssl_parse_truncated_hmac_ext( ssl, ext + 4, ext_size );\n                if( ret != 0 )\n                    return( ret );\n                break;\n#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */\n\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\n            case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:\n                MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found encrypt then mac extension\" ) );\n\n                ret = ssl_parse_encrypt_then_mac_ext( ssl, ext + 4, ext_size );\n                if( ret != 0 )\n                    return( ret );\n                break;\n#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */\n\n#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)\n            case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:\n                MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found extended master secret extension\" ) );\n\n                ret = ssl_parse_extended_ms_ext( ssl, ext + 4, ext_size );\n                if( ret != 0 )\n                    return( ret );\n                break;\n#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\n            case MBEDTLS_TLS_EXT_SESSION_TICKET:\n                MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found session ticket extension\" ) );\n\n                ret = ssl_parse_session_ticket_ext( ssl, ext + 4, ext_size );\n                if( ret != 0 )\n                    return( ret );\n                break;\n#endif /* MBEDTLS_SSL_SESSION_TICKETS */\n\n#if defined(MBEDTLS_SSL_ALPN)\n            case MBEDTLS_TLS_EXT_ALPN:\n                MBEDTLS_SSL_DEBUG_MSG( 3, ( \"found alpn extension\" ) );\n\n                ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size );\n                if( ret != 0 )\n                    return( ret );\n                break;\n#endif /* MBEDTLS_SSL_SESSION_TICKETS */\n\n            default:\n                MBEDTLS_SSL_DEBUG_MSG( 3, ( \"unknown extension found: %d (ignoring)\",\n                               ext_id ) );\n            }\n\n            ext_len -= 4 + ext_size;\n            ext += 4 + ext_size;\n\n            if( ext_len > 0 && ext_len < 4 )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client hello message\" ) );\n                mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                                MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n                return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n            }\n        }\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n    }\n#endif\n\n#if defined(MBEDTLS_SSL_FALLBACK_SCSV)\n    for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 )\n    {\n        if( p[0] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ) & 0xff ) &&\n            p[1] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE      ) & 0xff ) )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"received FALLBACK_SCSV\" ) );\n\n            if( ssl->minor_ver < ssl->conf->max_minor_ver )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"inapropriate fallback\" ) );\n\n                mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK );\n\n                return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n            }\n\n            break;\n        }\n    }\n#endif /* MBEDTLS_SSL_FALLBACK_SCSV */\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \\\n    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n\n    /*\n     * Try to fall back to default hash SHA1 if the client\n     * hasn't provided any preferred signature-hash combinations.\n     */\n    if( sig_hash_alg_ext_present == 0 )\n    {\n        mbedtls_md_type_t md_default = MBEDTLS_MD_SHA1;\n\n        if( mbedtls_ssl_check_sig_hash( ssl, md_default ) != 0 )\n            md_default = MBEDTLS_MD_NONE;\n\n        mbedtls_ssl_sig_hash_set_const_hash( &ssl->handshake->hash_algs, md_default );\n    }\n\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&\n          MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */\n\n    /*\n     * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV\n     */\n    for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 )\n    {\n        if( p[0] == 0 && p[1] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"received TLS_EMPTY_RENEGOTIATION_INFO \" ) );\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n            if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"received RENEGOTIATION SCSV \"\n                                            \"during renegotiation\" ) );\n                mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                                MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n                return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n            }\n#endif\n            ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;\n            break;\n        }\n    }\n\n    /*\n     * Renegotiation security checks\n     */\n    if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION &&\n        ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"legacy renegotiation, breaking off handshake\" ) );\n        handshake_failure = 1;\n    }\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&\n             ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&\n             renegotiation_info_seen == 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"renegotiation_info extension missing (secure)\" ) );\n        handshake_failure = 1;\n    }\n    else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&\n             ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&\n             ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"legacy renegotiation not allowed\" ) );\n        handshake_failure = 1;\n    }\n    else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&\n             ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&\n             renegotiation_info_seen == 1 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"renegotiation_info extension present (legacy)\" ) );\n        handshake_failure = 1;\n    }\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n\n    if( handshake_failure == 1 )\n    {\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    /*\n     * Search for a matching ciphersuite\n     * (At the end because we need information from the EC-based extensions\n     * and certificate from the SNI callback triggered by the SNI extension.)\n     */\n    got_common_suite = 0;\n    ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];\n    ciphersuite_info = NULL;\n#if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE)\n    for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 )\n        for( i = 0; ciphersuites[i] != 0; i++ )\n#else\n    for( i = 0; ciphersuites[i] != 0; i++ )\n        for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 )\n#endif\n        {\n            if( p[0] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) ||\n                p[1] != ( ( ciphersuites[i]      ) & 0xFF ) )\n                continue;\n\n            got_common_suite = 1;\n\n            if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i],\n                                               &ciphersuite_info ) ) != 0 )\n                return( ret );\n\n            if( ciphersuite_info != NULL )\n                goto have_ciphersuite;\n        }\n\n    if( got_common_suite )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"got ciphersuites in common, \"\n                            \"but none of them usable\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n        return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE );\n    }\n    else\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"got no ciphersuites in common\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );\n        return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN );\n    }\n\nhave_ciphersuite:\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"selected ciphersuite: %s\", ciphersuite_info->name ) );\n\n    ssl->session_negotiate->ciphersuite = ciphersuites[i];\n    ssl->transform_negotiate->ciphersuite_info = ciphersuite_info;\n\n    ssl->state++;\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n        mbedtls_ssl_recv_flight_completed( ssl );\n#endif\n\n    /* Debugging-only output for testsuite */\n#if defined(MBEDTLS_DEBUG_C)                         && \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_2)                && \\\n    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )\n    {\n        mbedtls_pk_type_t sig_alg = mbedtls_ssl_get_ciphersuite_sig_alg( ciphersuite_info );\n        if( sig_alg != MBEDTLS_PK_NONE )\n        {\n            mbedtls_md_type_t md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs,\n                                                                  sig_alg );\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"client hello v3, signature_algorithm ext: %d\",\n                                        mbedtls_ssl_hash_from_md_alg( md_alg ) ) );\n        }\n        else\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"no hash algorithm for signature algorithm \"\n                                        \"%d - should not happen\", sig_alg ) );\n        }\n    }\n#endif\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= parse client hello\" ) );\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)\nstatic void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl,\n                                          unsigned char *buf,\n                                          size_t *olen )\n{\n    unsigned char *p = buf;\n\n    if( ssl->session_negotiate->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED )\n    {\n        *olen = 0;\n        return;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, adding truncated hmac extension\" ) );\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC      ) & 0xFF );\n\n    *p++ = 0x00;\n    *p++ = 0x00;\n\n    *olen = 4;\n}\n#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */\n\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\nstatic void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,\n                                            unsigned char *buf,\n                                            size_t *olen )\n{\n    unsigned char *p = buf;\n    const mbedtls_ssl_ciphersuite_t *suite = NULL;\n    const mbedtls_cipher_info_t *cipher = NULL;\n\n    if( ssl->session_negotiate->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||\n        ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )\n    {\n        *olen = 0;\n        return;\n    }\n\n    /*\n     * RFC 7366: \"If a server receives an encrypt-then-MAC request extension\n     * from a client and then selects a stream or Authenticated Encryption\n     * with Associated Data (AEAD) ciphersuite, it MUST NOT send an\n     * encrypt-then-MAC response extension back to the client.\"\n     */\n    if( ( suite = mbedtls_ssl_ciphersuite_from_id(\n                    ssl->session_negotiate->ciphersuite ) ) == NULL ||\n        ( cipher = mbedtls_cipher_info_from_type( suite->cipher ) ) == NULL ||\n        cipher->mode != MBEDTLS_MODE_CBC )\n    {\n        *olen = 0;\n        return;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, adding encrypt then mac extension\" ) );\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC      ) & 0xFF );\n\n    *p++ = 0x00;\n    *p++ = 0x00;\n\n    *olen = 4;\n}\n#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */\n\n#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)\nstatic void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl,\n                                       unsigned char *buf,\n                                       size_t *olen )\n{\n    unsigned char *p = buf;\n\n    if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||\n        ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )\n    {\n        *olen = 0;\n        return;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, adding extended master secret \"\n                        \"extension\" ) );\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET      ) & 0xFF );\n\n    *p++ = 0x00;\n    *p++ = 0x00;\n\n    *olen = 4;\n}\n#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\nstatic void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl,\n                                          unsigned char *buf,\n                                          size_t *olen )\n{\n    unsigned char *p = buf;\n\n    if( ssl->handshake->new_session_ticket == 0 )\n    {\n        *olen = 0;\n        return;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, adding session ticket extension\" ) );\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET      ) & 0xFF );\n\n    *p++ = 0x00;\n    *p++ = 0x00;\n\n    *olen = 4;\n}\n#endif /* MBEDTLS_SSL_SESSION_TICKETS */\n\nstatic void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl,\n                                         unsigned char *buf,\n                                         size_t *olen )\n{\n    unsigned char *p = buf;\n\n    if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION )\n    {\n        *olen = 0;\n        return;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, secure renegotiation extension\" ) );\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO      ) & 0xFF );\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )\n    {\n        *p++ = 0x00;\n        *p++ = ( ssl->verify_data_len * 2 + 1 ) & 0xFF;\n        *p++ = ssl->verify_data_len * 2 & 0xFF;\n\n        memcpy( p, ssl->peer_verify_data, ssl->verify_data_len );\n        p += ssl->verify_data_len;\n        memcpy( p, ssl->own_verify_data, ssl->verify_data_len );\n        p += ssl->verify_data_len;\n    }\n    else\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n    {\n        *p++ = 0x00;\n        *p++ = 0x01;\n        *p++ = 0x00;\n    }\n\n    *olen = p - buf;\n}\n\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\nstatic void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl,\n                                               unsigned char *buf,\n                                               size_t *olen )\n{\n    unsigned char *p = buf;\n\n    if( ssl->session_negotiate->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE )\n    {\n        *olen = 0;\n        return;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, max_fragment_length extension\" ) );\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH      ) & 0xFF );\n\n    *p++ = 0x00;\n    *p++ = 1;\n\n    *p++ = ssl->session_negotiate->mfl_code;\n\n    *olen = 5;\n}\n#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */\n\n#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\nstatic void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl,\n                                                   unsigned char *buf,\n                                                   size_t *olen )\n{\n    unsigned char *p = buf;\n    ((void) ssl);\n\n    if( ( ssl->handshake->cli_exts &\n          MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT ) == 0 )\n    {\n        *olen = 0;\n        return;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, supported_point_formats extension\" ) );\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS      ) & 0xFF );\n\n    *p++ = 0x00;\n    *p++ = 2;\n\n    *p++ = 1;\n    *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;\n\n    *olen = 6;\n}\n#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\nstatic void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl,\n                                        unsigned char *buf,\n                                        size_t *olen )\n{\n    int ret;\n    unsigned char *p = buf;\n    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;\n    size_t kkpp_len;\n\n    *olen = 0;\n\n    /* Skip costly computation if not needed */\n    if( ssl->transform_negotiate->ciphersuite_info->key_exchange !=\n        MBEDTLS_KEY_EXCHANGE_ECJPAKE )\n        return;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, ecjpake kkpp extension\" ) );\n\n    if( end - p < 4 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"buffer too small\" ) );\n        return;\n    }\n\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP      ) & 0xFF );\n\n    ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx,\n                                        p + 2, end - p - 2, &kkpp_len,\n                                        ssl->conf->f_rng, ssl->conf->p_rng );\n    if( ret != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1 , \"mbedtls_ecjpake_write_round_one\", ret );\n        return;\n    }\n\n    *p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF );\n    *p++ = (unsigned char)( ( kkpp_len      ) & 0xFF );\n\n    *olen = kkpp_len + 4;\n}\n#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n\n#if defined(MBEDTLS_SSL_ALPN )\nstatic void ssl_write_alpn_ext( mbedtls_ssl_context *ssl,\n                                unsigned char *buf, size_t *olen )\n{\n    if( ssl->alpn_chosen == NULL )\n    {\n        *olen = 0;\n        return;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, adding alpn extension\" ) );\n\n    /*\n     * 0 . 1    ext identifier\n     * 2 . 3    ext length\n     * 4 . 5    protocol list length\n     * 6 . 6    protocol name length\n     * 7 . 7+n  protocol name\n     */\n    buf[0] = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF );\n    buf[1] = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN      ) & 0xFF );\n\n    *olen = 7 + strlen( ssl->alpn_chosen );\n\n    buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF );\n    buf[3] = (unsigned char)( ( ( *olen - 4 )      ) & 0xFF );\n\n    buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF );\n    buf[5] = (unsigned char)( ( ( *olen - 6 )      ) & 0xFF );\n\n    buf[6] = (unsigned char)( ( ( *olen - 7 )      ) & 0xFF );\n\n    memcpy( buf + 7, ssl->alpn_chosen, *olen - 7 );\n}\n#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */\n\n#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)\nstatic int ssl_write_hello_verify_request( mbedtls_ssl_context *ssl )\n{\n    int ret;\n    unsigned char *p = ssl->out_msg + 4;\n    unsigned char *cookie_len_byte;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write hello verify request\" ) );\n\n    /*\n     * struct {\n     *   ProtocolVersion server_version;\n     *   opaque cookie<0..2^8-1>;\n     * } HelloVerifyRequest;\n     */\n\n    /* The RFC is not clear on this point, but sending the actual negotiated\n     * version looks like the most interoperable thing to do. */\n    mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,\n                       ssl->conf->transport, p );\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"server version\", p, 2 );\n    p += 2;\n\n    /* If we get here, f_cookie_check is not null */\n    if( ssl->conf->f_cookie_write == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"inconsistent cookie callbacks\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    /* Skip length byte until we know the length */\n    cookie_len_byte = p++;\n\n    if( ( ret = ssl->conf->f_cookie_write( ssl->conf->p_cookie,\n                                     &p, ssl->out_buf + MBEDTLS_SSL_OUT_BUFFER_LEN,\n                                     ssl->cli_id, ssl->cli_id_len ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"f_cookie_write\", ret );\n        return( ret );\n    }\n\n    *cookie_len_byte = (unsigned char)( p - ( cookie_len_byte + 1 ) );\n\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"cookie sent\", cookie_len_byte + 1, *cookie_len_byte );\n\n    ssl->out_msglen  = p - ssl->out_msg;\n    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;\n    ssl->out_msg[0]  = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;\n\n    ssl->state = MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT;\n\n    if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_write_record\", ret );\n        return( ret );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write hello verify request\" ) );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */\n\nstatic int ssl_write_server_hello( mbedtls_ssl_context *ssl )\n{\n#if defined(MBEDTLS_HAVE_TIME)\n    mbedtls_time_t t;\n#endif\n    int ret;\n    size_t olen, ext_len = 0, n;\n    unsigned char *buf, *p;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write server hello\" ) );\n\n#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&\n        ssl->handshake->verify_cookie_len != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"client hello was not authenticated\" ) );\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write server hello\" ) );\n\n        return( ssl_write_hello_verify_request( ssl ) );\n    }\n#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */\n\n    if( ssl->conf->f_rng == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"no RNG provided\") );\n        return( MBEDTLS_ERR_SSL_NO_RNG );\n    }\n\n    /*\n     *     0  .   0   handshake type\n     *     1  .   3   handshake length\n     *     4  .   5   protocol version\n     *     6  .   9   UNIX time()\n     *    10  .  37   random bytes\n     */\n    buf = ssl->out_msg;\n    p = buf + 4;\n\n    mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,\n                       ssl->conf->transport, p );\n    p += 2;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, chosen version: [%d:%d]\",\n                        buf[4], buf[5] ) );\n\n#if defined(MBEDTLS_HAVE_TIME)\n    t = mbedtls_time( NULL );\n    *p++ = (unsigned char)( t >> 24 );\n    *p++ = (unsigned char)( t >> 16 );\n    *p++ = (unsigned char)( t >>  8 );\n    *p++ = (unsigned char)( t       );\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, current time: %lu\", t ) );\n#else\n    if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 )\n        return( ret );\n\n    p += 4;\n#endif /* MBEDTLS_HAVE_TIME */\n\n    if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 )\n        return( ret );\n\n    p += 28;\n\n    memcpy( ssl->handshake->randbytes + 32, buf + 6, 32 );\n\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"server hello, random bytes\", buf + 6, 32 );\n\n    /*\n     * Resume is 0  by default, see ssl_handshake_init().\n     * It may be already set to 1 by ssl_parse_session_ticket_ext().\n     * If not, try looking up session ID in our cache.\n     */\n    if( ssl->handshake->resume == 0 &&\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n        ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE &&\n#endif\n        ssl->session_negotiate->id_len != 0 &&\n        ssl->conf->f_get_cache != NULL &&\n        ssl->conf->f_get_cache( ssl->conf->p_cache, ssl->session_negotiate ) == 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"session successfully restored from cache\" ) );\n        ssl->handshake->resume = 1;\n    }\n\n    if( ssl->handshake->resume == 0 )\n    {\n        /*\n         * New session, create a new session id,\n         * unless we're about to issue a session ticket\n         */\n        ssl->state++;\n\n#if defined(MBEDTLS_HAVE_TIME)\n        ssl->session_negotiate->start = mbedtls_time( NULL );\n#endif\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\n        if( ssl->handshake->new_session_ticket != 0 )\n        {\n            ssl->session_negotiate->id_len = n = 0;\n            memset( ssl->session_negotiate->id, 0, 32 );\n        }\n        else\n#endif /* MBEDTLS_SSL_SESSION_TICKETS */\n        {\n            ssl->session_negotiate->id_len = n = 32;\n            if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id,\n                                    n ) ) != 0 )\n                return( ret );\n        }\n    }\n    else\n    {\n        /*\n         * Resuming a session\n         */\n        n = ssl->session_negotiate->id_len;\n        ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;\n\n        if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_derive_keys\", ret );\n            return( ret );\n        }\n    }\n\n    /*\n     *    38  .  38     session id length\n     *    39  . 38+n    session id\n     *   39+n . 40+n    chosen ciphersuite\n     *   41+n . 41+n    chosen compression alg.\n     *   42+n . 43+n    extensions length\n     *   44+n . 43+n+m  extensions\n     */\n    *p++ = (unsigned char) ssl->session_negotiate->id_len;\n    memcpy( p, ssl->session_negotiate->id, ssl->session_negotiate->id_len );\n    p += ssl->session_negotiate->id_len;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, session id len.: %d\", n ) );\n    MBEDTLS_SSL_DEBUG_BUF( 3,   \"server hello, session id\", buf + 39, n );\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"%s session has been resumed\",\n                   ssl->handshake->resume ? \"a\" : \"no\" ) );\n\n    *p++ = (unsigned char)( ssl->session_negotiate->ciphersuite >> 8 );\n    *p++ = (unsigned char)( ssl->session_negotiate->ciphersuite      );\n    *p++ = (unsigned char)( ssl->session_negotiate->compression      );\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, chosen ciphersuite: %s\",\n           mbedtls_ssl_get_ciphersuite_name( ssl->session_negotiate->ciphersuite ) ) );\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, compress alg.: 0x%02X\",\n                   ssl->session_negotiate->compression ) );\n\n    /* Do not write the extensions if the protocol is SSLv3 */\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n    if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) )\n    {\n#endif\n\n    /*\n     *  First write extensions, then the total length\n     */\n    ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\n    ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)\n    ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\n    ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)\n    ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\n    ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n#if defined(MBEDTLS_SSL_ALPN)\n    ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen );\n    ext_len += olen;\n#endif\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"server hello, total extension length: %d\", ext_len ) );\n\n    if( ext_len > 0 )\n    {\n        *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF );\n        *p++ = (unsigned char)( ( ext_len      ) & 0xFF );\n        p += ext_len;\n    }\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n    }\n#endif\n\n    ssl->out_msglen  = p - buf;\n    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;\n    ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_HELLO;\n\n    ret = mbedtls_ssl_write_record( ssl );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write server hello\" ) );\n\n    return( ret );\n}\n\n#if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)       && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)   && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)  && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)&& \\\n    !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)\nstatic int ssl_write_certificate_request( mbedtls_ssl_context *ssl )\n{\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =\n        ssl->transform_negotiate->ciphersuite_info;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write certificate request\" ) );\n\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip write certificate request\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n    return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n}\n#else\nstatic int ssl_write_certificate_request( mbedtls_ssl_context *ssl )\n{\n    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =\n        ssl->transform_negotiate->ciphersuite_info;\n    size_t dn_size, total_dn_size; /* excluding length bytes */\n    size_t ct_len, sa_len; /* including length bytes */\n    unsigned char *buf, *p;\n    const unsigned char * const end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;\n    const mbedtls_x509_crt *crt;\n    int authmode;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write certificate request\" ) );\n\n    ssl->state++;\n\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\n    if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET )\n        authmode = ssl->handshake->sni_authmode;\n    else\n#endif\n        authmode = ssl->conf->authmode;\n\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ||\n        authmode == MBEDTLS_SSL_VERIFY_NONE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip write certificate request\" ) );\n        return( 0 );\n    }\n\n    /*\n     *     0  .   0   handshake type\n     *     1  .   3   handshake length\n     *     4  .   4   cert type count\n     *     5  .. m-1  cert types\n     *     m  .. m+1  sig alg length (TLS 1.2 only)\n     *    m+1 .. n-1  SignatureAndHashAlgorithms (TLS 1.2 only)\n     *     n  .. n+1  length of all DNs\n     *    n+2 .. n+3  length of DN 1\n     *    n+4 .. ...  Distinguished Name #1\n     *    ... .. ...  length of DN 2, etc.\n     */\n    buf = ssl->out_msg;\n    p = buf + 4;\n\n    /*\n     * Supported certificate types\n     *\n     *     ClientCertificateType certificate_types<1..2^8-1>;\n     *     enum { (255) } ClientCertificateType;\n     */\n    ct_len = 0;\n\n#if defined(MBEDTLS_RSA_C)\n    p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_RSA_SIGN;\n#endif\n#if defined(MBEDTLS_ECDSA_C)\n    p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN;\n#endif\n\n    p[0] = (unsigned char) ct_len++;\n    p += ct_len;\n\n    sa_len = 0;\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n    /*\n     * Add signature_algorithms for verify (TLS 1.2)\n     *\n     *     SignatureAndHashAlgorithm supported_signature_algorithms<2..2^16-2>;\n     *\n     *     struct {\n     *           HashAlgorithm hash;\n     *           SignatureAlgorithm signature;\n     *     } SignatureAndHashAlgorithm;\n     *\n     *     enum { (255) } HashAlgorithm;\n     *     enum { (255) } SignatureAlgorithm;\n     */\n    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )\n    {\n        const int *cur;\n\n        /*\n         * Supported signature algorithms\n         */\n        for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ )\n        {\n            unsigned char hash = mbedtls_ssl_hash_from_md_alg( *cur );\n\n            if( MBEDTLS_SSL_HASH_NONE == hash || mbedtls_ssl_set_calc_verify_md( ssl, hash ) )\n                continue;\n\n#if defined(MBEDTLS_RSA_C)\n            p[2 + sa_len++] = hash;\n            p[2 + sa_len++] = MBEDTLS_SSL_SIG_RSA;\n#endif\n#if defined(MBEDTLS_ECDSA_C)\n            p[2 + sa_len++] = hash;\n            p[2 + sa_len++] = MBEDTLS_SSL_SIG_ECDSA;\n#endif\n        }\n\n        p[0] = (unsigned char)( sa_len >> 8 );\n        p[1] = (unsigned char)( sa_len      );\n        sa_len += 2;\n        p += sa_len;\n    }\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n\n    /*\n     * DistinguishedName certificate_authorities<0..2^16-1>;\n     * opaque DistinguishedName<1..2^16-1>;\n     */\n    p += 2;\n\n    total_dn_size = 0;\n\n    if( ssl->conf->cert_req_ca_list ==  MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED )\n    {\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\n        if( ssl->handshake->sni_ca_chain != NULL )\n            crt = ssl->handshake->sni_ca_chain;\n        else\n#endif\n            crt = ssl->conf->ca_chain;\n\n        while( crt != NULL && crt->version != 0 )\n        {\n            dn_size = crt->subject_raw.len;\n\n            if( end < p ||\n                (size_t)( end - p ) < dn_size ||\n                (size_t)( end - p ) < 2 + dn_size )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"skipping CAs: buffer too short\" ) );\n                break;\n            }\n\n            *p++ = (unsigned char)( dn_size >> 8 );\n            *p++ = (unsigned char)( dn_size      );\n            memcpy( p, crt->subject_raw.p, dn_size );\n            p += dn_size;\n\n            MBEDTLS_SSL_DEBUG_BUF( 3, \"requested DN\", p - dn_size, dn_size );\n\n            total_dn_size += 2 + dn_size;\n            crt = crt->next;\n        }\n    }\n\n    ssl->out_msglen  = p - buf;\n    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;\n    ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE_REQUEST;\n    ssl->out_msg[4 + ct_len + sa_len] = (unsigned char)( total_dn_size  >> 8 );\n    ssl->out_msg[5 + ct_len + sa_len] = (unsigned char)( total_dn_size       );\n\n    ret = mbedtls_ssl_write_record( ssl );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write certificate request\" ) );\n\n    return( ret );\n}\n#endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&\n          !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&\n          !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED &&\n          !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED &&\n          !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED &&\n          !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)\nstatic int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )\n{\n    int ret;\n\n    if( ! mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECKEY ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"server key not ECDH capable\" ) );\n        return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );\n    }\n\n    if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx,\n                                 mbedtls_pk_ec( *mbedtls_ssl_own_key( ssl ) ),\n                                 MBEDTLS_ECDH_OURS ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, ( \"mbedtls_ecdh_get_params\" ), ret );\n        return( ret );\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||\n          MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) && \\\n    defined(MBEDTLS_SSL_ASYNC_PRIVATE)\nstatic int ssl_resume_server_key_exchange( mbedtls_ssl_context *ssl,\n                                           size_t *signature_len )\n{\n    /* Append the signature to ssl->out_msg, leaving 2 bytes for the\n     * signature length which will be added in ssl_write_server_key_exchange\n     * after the call to ssl_prepare_server_key_exchange.\n     * ssl_write_server_key_exchange also takes care of incrementing\n     * ssl->out_msglen. */\n    unsigned char *sig_start = ssl->out_msg + ssl->out_msglen + 2;\n    size_t sig_max_len = ( ssl->out_buf + MBEDTLS_SSL_OUT_CONTENT_LEN\n                           - sig_start );\n    int ret = ssl->conf->f_async_resume( ssl,\n                                         sig_start, signature_len, sig_max_len );\n    if( ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )\n    {\n        ssl->handshake->async_in_progress = 0;\n        mbedtls_ssl_set_async_operation_data( ssl, NULL );\n    }\n    MBEDTLS_SSL_DEBUG_RET( 2, \"ssl_resume_server_key_exchange\", ret );\n    return( ret );\n}\n#endif /* defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) &&\n          defined(MBEDTLS_SSL_ASYNC_PRIVATE) */\n\n/* Prepare the ServerKeyExchange message, up to and including\n * calculating the signature if any, but excluding formatting the\n * signature and sending the message. */\nstatic int ssl_prepare_server_key_exchange( mbedtls_ssl_context *ssl,\n                                            size_t *signature_len )\n{\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =\n                            ssl->transform_negotiate->ciphersuite_info;\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED)\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)\n    unsigned char *dig_signed = NULL;\n#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED */\n\n    (void) ciphersuite_info; /* unused in some configurations */\n#if !defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)\n    (void) signature_len;\n#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */\n\n    ssl->out_msglen = 4; /* header (type:1, length:3) to be written later */\n\n    /*\n     *\n     * Part 1: Provide key exchange parameters for chosen ciphersuite.\n     *\n     */\n\n    /*\n     * - ECJPAKE key exchanges\n     */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )\n    {\n        int ret;\n        size_t len = 0;\n\n        ret = mbedtls_ecjpake_write_round_two(\n            &ssl->handshake->ecjpake_ctx,\n            ssl->out_msg + ssl->out_msglen,\n            MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen, &len,\n            ssl->conf->f_rng, ssl->conf->p_rng );\n        if( ret != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecjpake_write_round_two\", ret );\n            return( ret );\n        }\n\n        ssl->out_msglen += len;\n    }\n#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n\n    /*\n     * For (EC)DHE key exchanges with PSK, parameters are prefixed by support\n     * identity hint (RFC 4279, Sec. 3). Until someone needs this feature,\n     * we use empty support identity hints here.\n     **/\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)   || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )\n    {\n        ssl->out_msg[ssl->out_msglen++] = 0x00;\n        ssl->out_msg[ssl->out_msglen++] = 0x00;\n    }\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */\n\n    /*\n     * - DHE key exchanges\n     */\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED)\n    if( mbedtls_ssl_ciphersuite_uses_dhe( ciphersuite_info ) )\n    {\n        int ret;\n        size_t len = 0;\n\n        if( ssl->conf->dhm_P.p == NULL || ssl->conf->dhm_G.p == NULL )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"no DH parameters set\" ) );\n            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n        }\n\n        /*\n         * Ephemeral DH parameters:\n         *\n         * struct {\n         *     opaque dh_p<1..2^16-1>;\n         *     opaque dh_g<1..2^16-1>;\n         *     opaque dh_Ys<1..2^16-1>;\n         * } ServerDHParams;\n         */\n        if( ( ret = mbedtls_dhm_set_group( &ssl->handshake->dhm_ctx,\n                                           &ssl->conf->dhm_P,\n                                           &ssl->conf->dhm_G ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_dhm_set_group\", ret );\n            return( ret );\n        }\n\n        if( ( ret = mbedtls_dhm_make_params(\n                  &ssl->handshake->dhm_ctx,\n                  (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),\n                  ssl->out_msg + ssl->out_msglen, &len,\n                  ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_dhm_make_params\", ret );\n            return( ret );\n        }\n\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)\n        dig_signed = ssl->out_msg + ssl->out_msglen;\n#endif\n\n        ssl->out_msglen += len;\n\n        MBEDTLS_SSL_DEBUG_MPI( 3, \"DHM: X \", &ssl->handshake->dhm_ctx.X  );\n        MBEDTLS_SSL_DEBUG_MPI( 3, \"DHM: P \", &ssl->handshake->dhm_ctx.P  );\n        MBEDTLS_SSL_DEBUG_MPI( 3, \"DHM: G \", &ssl->handshake->dhm_ctx.G  );\n        MBEDTLS_SSL_DEBUG_MPI( 3, \"DHM: GX\", &ssl->handshake->dhm_ctx.GX );\n    }\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED */\n\n    /*\n     * - ECDHE key exchanges\n     */\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED)\n    if( mbedtls_ssl_ciphersuite_uses_ecdhe( ciphersuite_info ) )\n    {\n        /*\n         * Ephemeral ECDH parameters:\n         *\n         * struct {\n         *     ECParameters curve_params;\n         *     ECPoint      public;\n         * } ServerECDHParams;\n         */\n        const mbedtls_ecp_curve_info **curve = NULL;\n        const mbedtls_ecp_group_id *gid;\n        int ret;\n        size_t len = 0;\n\n        /* Match our preference list against the offered curves */\n        for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ )\n            for( curve = ssl->handshake->curves; *curve != NULL; curve++ )\n                if( (*curve)->grp_id == *gid )\n                    goto curve_matching_done;\n\ncurve_matching_done:\n        if( curve == NULL || *curve == NULL )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"no matching curve for ECDHE\" ) );\n            return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN );\n        }\n\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"ECDHE curve: %s\", (*curve)->name ) );\n\n        if( ( ret = mbedtls_ecp_group_load( &ssl->handshake->ecdh_ctx.grp,\n                                       (*curve)->grp_id ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecp_group_load\", ret );\n            return( ret );\n        }\n\n        if( ( ret = mbedtls_ecdh_make_params(\n                  &ssl->handshake->ecdh_ctx, &len,\n                  ssl->out_msg + ssl->out_msglen,\n                  MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen,\n                  ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecdh_make_params\", ret );\n            return( ret );\n        }\n\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)\n        dig_signed = ssl->out_msg + ssl->out_msglen;\n#endif\n\n        ssl->out_msglen += len;\n\n        MBEDTLS_SSL_DEBUG_ECP( 3, \"ECDH: Q \", &ssl->handshake->ecdh_ctx.Q );\n    }\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED */\n\n    /*\n     *\n     * Part 2: For key exchanges involving the server signing the\n     *         exchange parameters, compute and add the signature here.\n     *\n     */\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)\n    if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )\n    {\n        size_t dig_signed_len = ssl->out_msg + ssl->out_msglen - dig_signed;\n        size_t hashlen = 0;\n        unsigned char hash[MBEDTLS_MD_MAX_SIZE];\n        int ret;\n\n        /*\n         * 2.1: Choose hash algorithm:\n         * A: For TLS 1.2, obey signature-hash-algorithm extension\n         *    to choose appropriate hash.\n         * B: For SSL3, TLS1.0, TLS1.1 and ECDHE_ECDSA, use SHA1\n         *    (RFC 4492, Sec. 5.4)\n         * C: Otherwise, use MD5 + SHA1 (RFC 4346, Sec. 7.4.3)\n         */\n\n        mbedtls_md_type_t md_alg;\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n        mbedtls_pk_type_t sig_alg =\n            mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );\n        if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )\n        {\n            /* A: For TLS 1.2, obey signature-hash-algorithm extension\n             *    (RFC 5246, Sec. 7.4.1.4.1). */\n            if( sig_alg == MBEDTLS_PK_NONE ||\n                ( md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs,\n                                                          sig_alg ) ) == MBEDTLS_MD_NONE )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n                /* (... because we choose a cipher suite\n                 *      only if there is a matching hash.) */\n                return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n            }\n        }\n        else\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1)\n        if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )\n        {\n            /* B: Default hash SHA1 */\n            md_alg = MBEDTLS_MD_SHA1;\n        }\n        else\n#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \\\n          MBEDTLS_SSL_PROTO_TLS1_1 */\n        {\n            /* C: MD5 + SHA1 */\n            md_alg = MBEDTLS_MD_NONE;\n        }\n\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"pick hash algorithm %d for signing\", md_alg ) );\n\n        /*\n         * 2.2: Compute the hash to be signed\n         */\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1)\n        if( md_alg == MBEDTLS_MD_NONE )\n        {\n            hashlen = 36;\n            ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash,\n                                                           dig_signed,\n                                                           dig_signed_len );\n            if( ret != 0 )\n                return( ret );\n        }\n        else\n#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \\\n          MBEDTLS_SSL_PROTO_TLS1_1 */\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_2)\n        if( md_alg != MBEDTLS_MD_NONE )\n        {\n            ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, &hashlen,\n                                                          dig_signed,\n                                                          dig_signed_len,\n                                                          md_alg );\n            if( ret != 0 )\n                return( ret );\n        }\n        else\n#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \\\n          MBEDTLS_SSL_PROTO_TLS1_2 */\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n        MBEDTLS_SSL_DEBUG_BUF( 3, \"parameters hash\", hash, hashlen );\n\n        /*\n         * 2.3: Compute and add the signature\n         */\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n        if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )\n        {\n            /*\n             * For TLS 1.2, we need to specify signature and hash algorithm\n             * explicitly through a prefix to the signature.\n             *\n             * struct {\n             *    HashAlgorithm hash;\n             *    SignatureAlgorithm signature;\n             * } SignatureAndHashAlgorithm;\n             *\n             * struct {\n             *    SignatureAndHashAlgorithm algorithm;\n             *    opaque signature<0..2^16-1>;\n             * } DigitallySigned;\n             *\n             */\n\n            ssl->out_msg[ssl->out_msglen++] =\n                mbedtls_ssl_hash_from_md_alg( md_alg );\n            ssl->out_msg[ssl->out_msglen++] =\n                mbedtls_ssl_sig_from_pk_alg( sig_alg );\n        }\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n\n#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)\n        if( ssl->conf->f_async_sign_start != NULL )\n        {\n            ret = ssl->conf->f_async_sign_start( ssl,\n                                                 mbedtls_ssl_own_cert( ssl ),\n                                                 md_alg, hash, hashlen );\n            switch( ret )\n            {\n            case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH:\n                /* act as if f_async_sign was null */\n                break;\n            case 0:\n                ssl->handshake->async_in_progress = 1;\n                return( ssl_resume_server_key_exchange( ssl, signature_len ) );\n            case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:\n                ssl->handshake->async_in_progress = 1;\n                return( MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS );\n            default:\n                MBEDTLS_SSL_DEBUG_RET( 1, \"f_async_sign_start\", ret );\n                return( ret );\n            }\n        }\n#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */\n\n        if( mbedtls_ssl_own_key( ssl ) == NULL )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"got no private key\" ) );\n            return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );\n        }\n\n        /* Append the signature to ssl->out_msg, leaving 2 bytes for the\n         * signature length which will be added in ssl_write_server_key_exchange\n         * after the call to ssl_prepare_server_key_exchange.\n         * ssl_write_server_key_exchange also takes care of incrementing\n         * ssl->out_msglen. */\n        if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ),\n                                     md_alg, hash, hashlen,\n                                     ssl->out_msg + ssl->out_msglen + 2,\n                                     signature_len,\n                                     ssl->conf->f_rng,\n                                     ssl->conf->p_rng ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_pk_sign\", ret );\n            return( ret );\n        }\n    }\n#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */\n\n    return( 0 );\n}\n\n/* Prepare the ServerKeyExchange message and send it. For ciphersuites\n * that do not include a ServerKeyExchange message, do nothing. Either\n * way, if successful, move on to the next step in the SSL state\n * machine. */\nstatic int ssl_write_server_key_exchange( mbedtls_ssl_context *ssl )\n{\n    int ret;\n    size_t signature_len = 0;\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED)\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =\n                            ssl->transform_negotiate->ciphersuite_info;\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED */\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write server key exchange\" ) );\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED)\n    /* Extract static ECDH parameters and abort if ServerKeyExchange\n     * is not needed. */\n    if( mbedtls_ssl_ciphersuite_no_pfs( ciphersuite_info ) )\n    {\n        /* For suites involving ECDH, extract DH parameters\n         * from certificate at this point. */\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED)\n        if( mbedtls_ssl_ciphersuite_uses_ecdh( ciphersuite_info ) )\n        {\n            ssl_get_ecdh_params_from_cert( ssl );\n        }\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED */\n\n        /* Key exchanges not involving ephemeral keys don't use\n         * ServerKeyExchange, so end here. */\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip write server key exchange\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) && \\\n    defined(MBEDTLS_SSL_ASYNC_PRIVATE)\n    /* If we have already prepared the message and there is an ongoing\n     * signature operation, resume signing. */\n    if( ssl->handshake->async_in_progress != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"resuming signature operation\" ) );\n        ret = ssl_resume_server_key_exchange( ssl, &signature_len );\n    }\n    else\n#endif /* defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) &&\n          defined(MBEDTLS_SSL_ASYNC_PRIVATE) */\n    {\n        /* ServerKeyExchange is needed. Prepare the message. */\n        ret = ssl_prepare_server_key_exchange( ssl, &signature_len );\n    }\n\n    if( ret != 0 )\n    {\n        /* If we're starting to write a new message, set ssl->out_msglen\n         * to 0. But if we're resuming after an asynchronous message,\n         * out_msglen is the amount of data written so far and mst be\n         * preserved. */\n        if( ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write server key exchange (pending)\" ) );\n        else\n            ssl->out_msglen = 0;\n        return( ret );\n    }\n\n    /* If there is a signature, write its length.\n     * ssl_prepare_server_key_exchange already wrote the signature\n     * itself at its proper place in the output buffer. */\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)\n    if( signature_len != 0 )\n    {\n        ssl->out_msg[ssl->out_msglen++] = (unsigned char)( signature_len >> 8 );\n        ssl->out_msg[ssl->out_msglen++] = (unsigned char)( signature_len      );\n\n        MBEDTLS_SSL_DEBUG_BUF( 3, \"my signature\",\n                               ssl->out_msg + ssl->out_msglen,\n                               signature_len );\n\n        /* Skip over the already-written signature */\n        ssl->out_msglen += signature_len;\n    }\n#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */\n\n    /* Add header and send. */\n    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;\n    ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE;\n\n    ssl->state++;\n\n    if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_write_record\", ret );\n        return( ret );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write server key exchange\" ) );\n    return( 0 );\n}\n\nstatic int ssl_write_server_hello_done( mbedtls_ssl_context *ssl )\n{\n    int ret;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write server hello done\" ) );\n\n    ssl->out_msglen  = 4;\n    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;\n    ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_HELLO_DONE;\n\n    ssl->state++;\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n        mbedtls_ssl_send_flight_completed( ssl );\n#endif\n\n    if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_write_record\", ret );\n        return( ret );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write server hello done\" ) );\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \\\n    defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)\nstatic int ssl_parse_client_dh_public( mbedtls_ssl_context *ssl, unsigned char **p,\n                                       const unsigned char *end )\n{\n    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;\n    size_t n;\n\n    /*\n     * Receive G^Y mod P, premaster = (G^Y)^X mod P\n     */\n    if( *p + 2 > end )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n    }\n\n    n = ( (*p)[0] << 8 ) | (*p)[1];\n    *p += 2;\n\n    if( *p + n > end )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n    }\n\n    if( ( ret = mbedtls_dhm_read_public( &ssl->handshake->dhm_ctx, *p, n ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_dhm_read_public\", ret );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP );\n    }\n\n    *p += n;\n\n    MBEDTLS_SSL_DEBUG_MPI( 3, \"DHM: GY\", &ssl->handshake->dhm_ctx.GY );\n\n    return( ret );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) ||                           \\\n    defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)\n\n#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)\nstatic int ssl_resume_decrypt_pms( mbedtls_ssl_context *ssl,\n                                   unsigned char *peer_pms,\n                                   size_t *peer_pmslen,\n                                   size_t peer_pmssize )\n{\n    int ret = ssl->conf->f_async_resume( ssl,\n                                         peer_pms, peer_pmslen, peer_pmssize );\n    if( ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )\n    {\n        ssl->handshake->async_in_progress = 0;\n        mbedtls_ssl_set_async_operation_data( ssl, NULL );\n    }\n    MBEDTLS_SSL_DEBUG_RET( 2, \"ssl_decrypt_encrypted_pms\", ret );\n    return( ret );\n}\n#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */\n\nstatic int ssl_decrypt_encrypted_pms( mbedtls_ssl_context *ssl,\n                                      const unsigned char *p,\n                                      const unsigned char *end,\n                                      unsigned char *peer_pms,\n                                      size_t *peer_pmslen,\n                                      size_t peer_pmssize )\n{\n    int ret;\n    mbedtls_pk_context *private_key = mbedtls_ssl_own_key( ssl );\n    mbedtls_pk_context *public_key = &mbedtls_ssl_own_cert( ssl )->pk;\n    size_t len = mbedtls_pk_get_len( public_key );\n\n#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)\n    /* If we have already started decoding the message and there is an ongoing\n     * decryption operation, resume signing. */\n    if( ssl->handshake->async_in_progress != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"resuming decryption operation\" ) );\n        return( ssl_resume_decrypt_pms( ssl,\n                                        peer_pms, peer_pmslen, peer_pmssize ) );\n    }\n#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */\n\n    /*\n     * Prepare to decrypt the premaster using own private RSA key\n     */\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_2)\n    if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )\n    {\n        if ( p + 2 > end ) {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n        }\n        if( *p++ != ( ( len >> 8 ) & 0xFF ) ||\n            *p++ != ( ( len      ) & 0xFF ) )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n        }\n    }\n#endif\n\n    if( p + len != end )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n    }\n\n    /*\n     * Decrypt the premaster secret\n     */\n#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)\n    if( ssl->conf->f_async_decrypt_start != NULL )\n    {\n        ret = ssl->conf->f_async_decrypt_start( ssl,\n                                                mbedtls_ssl_own_cert( ssl ),\n                                                p, len );\n        switch( ret )\n        {\n        case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH:\n            /* act as if f_async_decrypt_start was null */\n            break;\n        case 0:\n            ssl->handshake->async_in_progress = 1;\n            return( ssl_resume_decrypt_pms( ssl,\n                                            peer_pms,\n                                            peer_pmslen,\n                                            peer_pmssize ) );\n        case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:\n            ssl->handshake->async_in_progress = 1;\n            return( MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS );\n        default:\n            MBEDTLS_SSL_DEBUG_RET( 1, \"f_async_decrypt_start\", ret );\n            return( ret );\n        }\n    }\n#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */\n\n    if( ! mbedtls_pk_can_do( private_key, MBEDTLS_PK_RSA ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"got no RSA private key\" ) );\n        return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );\n    }\n\n    ret = mbedtls_pk_decrypt( private_key, p, len,\n                              peer_pms, peer_pmslen, peer_pmssize,\n                              ssl->conf->f_rng, ssl->conf->p_rng );\n    return( ret );\n}\n\nstatic int ssl_parse_encrypted_pms( mbedtls_ssl_context *ssl,\n                                    const unsigned char *p,\n                                    const unsigned char *end,\n                                    size_t pms_offset )\n{\n    int ret;\n    unsigned char *pms = ssl->handshake->premaster + pms_offset;\n    unsigned char ver[2];\n    unsigned char fake_pms[48], peer_pms[48];\n    unsigned char mask;\n    size_t i, peer_pmslen;\n    unsigned int diff;\n\n    /* In case of a failure in decryption, the decryption may write less than\n     * 2 bytes of output, but we always read the first two bytes. It doesn't\n     * matter in the end because diff will be nonzero in that case due to\n     * peer_pmslen being less than 48, and we only care whether diff is 0.\n     * But do initialize peer_pms for robustness anyway. This also makes\n     * memory analyzers happy (don't access uninitialized memory, even\n     * if it's an unsigned char). */\n    peer_pms[0] = peer_pms[1] = ~0;\n\n    ret = ssl_decrypt_encrypted_pms( ssl, p, end,\n                                     peer_pms,\n                                     &peer_pmslen,\n                                     sizeof( peer_pms ) );\n\n#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)\n    if ( ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )\n        return( ret );\n#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */\n\n    mbedtls_ssl_write_version( ssl->handshake->max_major_ver,\n                               ssl->handshake->max_minor_ver,\n                               ssl->conf->transport, ver );\n\n    /* Avoid data-dependent branches while checking for invalid\n     * padding, to protect against timing-based Bleichenbacher-type\n     * attacks. */\n    diff  = (unsigned int) ret;\n    diff |= peer_pmslen ^ 48;\n    diff |= peer_pms[0] ^ ver[0];\n    diff |= peer_pms[1] ^ ver[1];\n\n    /* mask = diff ? 0xff : 0x00 using bit operations to avoid branches */\n    /* MSVC has a warning about unary minus on unsigned, but this is\n     * well-defined and precisely what we want to do here */\n#if defined(_MSC_VER)\n#pragma warning( push )\n#pragma warning( disable : 4146 )\n#endif\n    mask = - ( ( diff | - diff ) >> ( sizeof( unsigned int ) * 8 - 1 ) );\n#if defined(_MSC_VER)\n#pragma warning( pop )\n#endif\n\n    /*\n     * Protection against Bleichenbacher's attack: invalid PKCS#1 v1.5 padding\n     * must not cause the connection to end immediately; instead, send a\n     * bad_record_mac later in the handshake.\n     * To protect against timing-based variants of the attack, we must\n     * not have any branch that depends on whether the decryption was\n     * successful. In particular, always generate the fake premaster secret,\n     * regardless of whether it will ultimately influence the output or not.\n     */\n    ret = ssl->conf->f_rng( ssl->conf->p_rng, fake_pms, sizeof( fake_pms ) );\n    if( ret != 0 )\n    {\n        /* It's ok to abort on an RNG failure, since this does not reveal\n         * anything about the RSA decryption. */\n        return( ret );\n    }\n\n#if defined(MBEDTLS_SSL_DEBUG_ALL)\n    if( diff != 0 )\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n#endif\n\n    if( sizeof( ssl->handshake->premaster ) < pms_offset ||\n        sizeof( ssl->handshake->premaster ) - pms_offset < 48 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n    ssl->handshake->pmslen = 48;\n\n    /* Set pms to either the true or the fake PMS, without\n     * data-dependent branches. */\n    for( i = 0; i < ssl->handshake->pmslen; i++ )\n        pms[i] = ( mask & fake_pms[i] ) | ( (~mask) & peer_pms[i] );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)\nstatic int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p,\n                                          const unsigned char *end )\n{\n    int ret = 0;\n    size_t n;\n\n    if( ssl->conf->f_psk == NULL &&\n        ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL ||\n          ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"got no pre-shared key\" ) );\n        return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );\n    }\n\n    /*\n     * Receive client pre-shared key identity name\n     */\n    if( end - *p < 2 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n    }\n\n    n = ( (*p)[0] << 8 ) | (*p)[1];\n    *p += 2;\n\n    if( n < 1 || n > 65535 || n > (size_t) ( end - *p ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n    }\n\n    if( ssl->conf->f_psk != NULL )\n    {\n        if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 )\n            ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;\n    }\n    else\n    {\n        /* Identity is not a big secret since clients send it in the clear,\n         * but treat it carefully anyway, just in case */\n        if( n != ssl->conf->psk_identity_len ||\n            mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 )\n        {\n            ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;\n        }\n    }\n\n    if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY )\n    {\n        MBEDTLS_SSL_DEBUG_BUF( 3, \"Unknown PSK identity\", *p, n );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY );\n        return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY );\n    }\n\n    *p += n;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */\n\nstatic int ssl_parse_client_key_exchange( mbedtls_ssl_context *ssl )\n{\n    int ret;\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info;\n    unsigned char *p, *end;\n\n    ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse client key exchange\" ) );\n\n#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) && \\\n    ( defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \\\n      defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) )\n    if( ( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||\n          ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) &&\n        ( ssl->handshake->async_in_progress != 0 ) )\n    {\n        /* We've already read a record and there is an asynchronous\n         * operation in progress to decrypt it. So skip reading the\n         * record. */\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"will resume decryption of previously-read record\" ) );\n    }\n    else\n#endif\n    if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_read_record\", ret );\n        return( ret );\n    }\n\n    p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );\n    end = ssl->in_msg + ssl->in_hslen;\n\n    if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n    }\n\n    if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n    }\n\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA )\n    {\n        if( ( ret = ssl_parse_client_dh_public( ssl, &p, end ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, ( \"ssl_parse_client_dh_public\" ), ret );\n            return( ret );\n        }\n\n        if( p != end )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange\" ) );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n        }\n\n        if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,\n                                      ssl->handshake->premaster,\n                                      MBEDTLS_PREMASTER_SIZE,\n                                     &ssl->handshake->pmslen,\n                                      ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_dhm_calc_secret\", ret );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS );\n        }\n\n        MBEDTLS_SSL_DEBUG_MPI( 3, \"DHM: K \", &ssl->handshake->dhm_ctx.K  );\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )\n    {\n        if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx,\n                                      p, end - p) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecdh_read_public\", ret );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP );\n        }\n\n        MBEDTLS_SSL_DEBUG_ECP( 3, \"ECDH: Qp \", &ssl->handshake->ecdh_ctx.Qp );\n\n        if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx,\n                                      &ssl->handshake->pmslen,\n                                       ssl->handshake->premaster,\n                                       MBEDTLS_MPI_MAX_SIZE,\n                                       ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecdh_calc_secret\", ret );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS );\n        }\n\n        MBEDTLS_SSL_DEBUG_MPI( 3, \"ECDH: z  \", &ssl->handshake->ecdh_ctx.z );\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||\n          MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK )\n    {\n        if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, ( \"ssl_parse_client_psk_identity\" ), ret );\n            return( ret );\n        }\n\n        if( p != end )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange\" ) );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n        }\n\n        if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,\n                        ciphersuite_info->key_exchange ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_psk_derive_premaster\", ret );\n            return( ret );\n        }\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )\n    {\n#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)\n        if ( ssl->handshake->async_in_progress != 0 )\n        {\n            /* There is an asynchronous operation in progress to\n             * decrypt the encrypted premaster secret, so skip\n             * directly to resuming this operation. */\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"PSK identity already parsed\" ) );\n            /* Update p to skip the PSK identity. ssl_parse_encrypted_pms\n             * won't actually use it, but maintain p anyway for robustness. */\n            p += ssl->conf->psk_identity_len + 2;\n        }\n        else\n#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */\n        if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, ( \"ssl_parse_client_psk_identity\" ), ret );\n            return( ret );\n        }\n\n        if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 2 ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, ( \"ssl_parse_encrypted_pms\" ), ret );\n            return( ret );\n        }\n\n        if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,\n                        ciphersuite_info->key_exchange ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_psk_derive_premaster\", ret );\n            return( ret );\n        }\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )\n    {\n        if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, ( \"ssl_parse_client_psk_identity\" ), ret );\n            return( ret );\n        }\n        if( ( ret = ssl_parse_client_dh_public( ssl, &p, end ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, ( \"ssl_parse_client_dh_public\" ), ret );\n            return( ret );\n        }\n\n        if( p != end )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange\" ) );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n        }\n\n        if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,\n                        ciphersuite_info->key_exchange ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_psk_derive_premaster\", ret );\n            return( ret );\n        }\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )\n    {\n        if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, ( \"ssl_parse_client_psk_identity\" ), ret );\n            return( ret );\n        }\n\n        if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx,\n                                       p, end - p ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecdh_read_public\", ret );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP );\n        }\n\n        MBEDTLS_SSL_DEBUG_ECP( 3, \"ECDH: Qp \", &ssl->handshake->ecdh_ctx.Qp );\n\n        if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,\n                        ciphersuite_info->key_exchange ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_psk_derive_premaster\", ret );\n            return( ret );\n        }\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )\n    {\n        if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 0 ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, ( \"ssl_parse_parse_encrypted_pms_secret\" ), ret );\n            return( ret );\n        }\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )\n    {\n        ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,\n                                              p, end - p );\n        if( ret != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecjpake_read_round_two\", ret );\n            return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n        }\n\n        ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx,\n                ssl->handshake->premaster, 32, &ssl->handshake->pmslen,\n                ssl->conf->f_rng, ssl->conf->p_rng );\n        if( ret != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecjpake_derive_secret\", ret );\n            return( ret );\n        }\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_derive_keys\", ret );\n        return( ret );\n    }\n\n    ssl->state++;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= parse client key exchange\" ) );\n\n    return( 0 );\n}\n\n#if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)       && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)   && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)  && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)&& \\\n    !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)\nstatic int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl )\n{\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =\n        ssl->transform_negotiate->ciphersuite_info;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse certificate verify\" ) );\n\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip parse certificate verify\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n    return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n}\n#else\nstatic int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl )\n{\n    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;\n    size_t i, sig_len;\n    unsigned char hash[48];\n    unsigned char *hash_start = hash;\n    size_t hashlen;\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n    mbedtls_pk_type_t pk_alg;\n#endif\n    mbedtls_md_type_t md_alg;\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =\n        ssl->transform_negotiate->ciphersuite_info;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse certificate verify\" ) );\n\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ||\n        ssl->session_negotiate->peer_cert == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip parse certificate verify\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n\n    /* Read the message without adding it to the checksum */\n    do {\n\n        do ret = mbedtls_ssl_read_record_layer( ssl );\n        while( ret == MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );\n\n        if( ret != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, ( \"mbedtls_ssl_read_record_layer\" ), ret );\n            return( ret );\n        }\n\n        ret = mbedtls_ssl_handle_message_type( ssl );\n\n    } while( MBEDTLS_ERR_SSL_NON_FATAL           == ret ||\n             MBEDTLS_ERR_SSL_CONTINUE_PROCESSING == ret );\n\n    if( 0 != ret )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, ( \"mbedtls_ssl_handle_message_type\" ), ret );\n        return( ret );\n    }\n\n    ssl->state++;\n\n    /* Process the message contents */\n    if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ||\n        ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE_VERIFY )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate verify message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );\n    }\n\n    i = mbedtls_ssl_hs_hdr_len( ssl );\n\n    /*\n     *  struct {\n     *     SignatureAndHashAlgorithm algorithm; -- TLS 1.2 only\n     *     opaque signature<0..2^16-1>;\n     *  } DigitallySigned;\n     */\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1)\n    if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )\n    {\n        md_alg = MBEDTLS_MD_NONE;\n        hashlen = 36;\n\n        /* For ECDSA, use SHA-1, not MD-5 + SHA-1 */\n        if( mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,\n                        MBEDTLS_PK_ECDSA ) )\n        {\n            hash_start += 16;\n            hashlen -= 16;\n            md_alg = MBEDTLS_MD_SHA1;\n        }\n    }\n    else\n#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 ||\n          MBEDTLS_SSL_PROTO_TLS1_1 */\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )\n    {\n        if( i + 2 > ssl->in_hslen )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate verify message\" ) );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );\n        }\n\n        /*\n         * Hash\n         */\n        md_alg = mbedtls_ssl_md_alg_from_hash( ssl->in_msg[i] );\n\n        if( md_alg == MBEDTLS_MD_NONE || mbedtls_ssl_set_calc_verify_md( ssl, ssl->in_msg[i] ) )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"peer not adhering to requested sig_alg\"\n                                \" for verify message\" ) );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );\n        }\n\n#if !defined(MBEDTLS_MD_SHA1)\n        if( MBEDTLS_MD_SHA1 == md_alg )\n            hash_start += 16;\n#endif\n\n        /* Info from md_alg will be used instead */\n        hashlen = 0;\n\n        i++;\n\n        /*\n         * Signature\n         */\n        if( ( pk_alg = mbedtls_ssl_pk_alg_from_sig( ssl->in_msg[i] ) )\n                        == MBEDTLS_PK_NONE )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"peer not adhering to requested sig_alg\"\n                                \" for verify message\" ) );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );\n        }\n\n        /*\n         * Check the certificate's key type matches the signature alg\n         */\n        if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"sig_alg doesn't match cert key\" ) );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );\n        }\n\n        i++;\n    }\n    else\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    if( i + 2 > ssl->in_hslen )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate verify message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );\n    }\n\n    sig_len = ( ssl->in_msg[i] << 8 ) | ssl->in_msg[i+1];\n    i += 2;\n\n    if( i + sig_len != ssl->in_hslen )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate verify message\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );\n    }\n\n    /* Calculate hash and verify signature */\n    ssl->handshake->calc_verify( ssl, hash );\n\n    if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,\n                           md_alg, hash_start, hashlen,\n                           ssl->in_msg + i, sig_len ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_pk_verify\", ret );\n        return( ret );\n    }\n\n    mbedtls_ssl_update_handshake_status( ssl );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= parse certificate verify\" ) );\n\n    return( ret );\n}\n#endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&\n          !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&\n          !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED &&\n          !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED &&\n          !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED &&\n          !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\nstatic int ssl_write_new_session_ticket( mbedtls_ssl_context *ssl )\n{\n    int ret;\n    size_t tlen;\n    uint32_t lifetime;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write new session ticket\" ) );\n\n    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;\n    ssl->out_msg[0]  = MBEDTLS_SSL_HS_NEW_SESSION_TICKET;\n\n    /*\n     * struct {\n     *     uint32 ticket_lifetime_hint;\n     *     opaque ticket<0..2^16-1>;\n     * } NewSessionTicket;\n     *\n     * 4  .  7   ticket_lifetime_hint (0 = unspecified)\n     * 8  .  9   ticket_len (n)\n     * 10 .  9+n ticket content\n     */\n\n    if( ( ret = ssl->conf->f_ticket_write( ssl->conf->p_ticket,\n                                ssl->session_negotiate,\n                                ssl->out_msg + 10,\n                                ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN,\n                                &tlen, &lifetime ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_ticket_write\", ret );\n        tlen = 0;\n    }\n\n    ssl->out_msg[4] = ( lifetime >> 24 ) & 0xFF;\n    ssl->out_msg[5] = ( lifetime >> 16 ) & 0xFF;\n    ssl->out_msg[6] = ( lifetime >>  8 ) & 0xFF;\n    ssl->out_msg[7] = ( lifetime       ) & 0xFF;\n\n    ssl->out_msg[8] = (unsigned char)( ( tlen >> 8 ) & 0xFF );\n    ssl->out_msg[9] = (unsigned char)( ( tlen      ) & 0xFF );\n\n    ssl->out_msglen = 10 + tlen;\n\n    /*\n     * Morally equivalent to updating ssl->state, but NewSessionTicket and\n     * ChangeCipherSpec share the same state.\n     */\n    ssl->handshake->new_session_ticket = 0;\n\n    if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_write_record\", ret );\n        return( ret );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write new session ticket\" ) );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_SESSION_TICKETS */\n\n/*\n * SSL handshake -- server side -- single step\n */\nint mbedtls_ssl_handshake_server_step( mbedtls_ssl_context *ssl )\n{\n    int ret = 0;\n\n    if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"server state: %d\", ssl->state ) );\n\n    if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )\n        return( ret );\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&\n        ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )\n    {\n        if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )\n            return( ret );\n    }\n#endif\n\n    switch( ssl->state )\n    {\n        case MBEDTLS_SSL_HELLO_REQUEST:\n            ssl->state = MBEDTLS_SSL_CLIENT_HELLO;\n            break;\n\n        /*\n         *  <==   ClientHello\n         */\n        case MBEDTLS_SSL_CLIENT_HELLO:\n            ret = ssl_parse_client_hello( ssl );\n            break;\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n        case MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT:\n            return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );\n#endif\n\n        /*\n         *  ==>   ServerHello\n         *        Certificate\n         *      ( ServerKeyExchange  )\n         *      ( CertificateRequest )\n         *        ServerHelloDone\n         */\n        case MBEDTLS_SSL_SERVER_HELLO:\n            ret = ssl_write_server_hello( ssl );\n            break;\n\n        case MBEDTLS_SSL_SERVER_CERTIFICATE:\n            ret = mbedtls_ssl_write_certificate( ssl );\n            break;\n\n        case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:\n            ret = ssl_write_server_key_exchange( ssl );\n            break;\n\n        case MBEDTLS_SSL_CERTIFICATE_REQUEST:\n            ret = ssl_write_certificate_request( ssl );\n            break;\n\n        case MBEDTLS_SSL_SERVER_HELLO_DONE:\n            ret = ssl_write_server_hello_done( ssl );\n            break;\n\n        /*\n         *  <== ( Certificate/Alert  )\n         *        ClientKeyExchange\n         *      ( CertificateVerify  )\n         *        ChangeCipherSpec\n         *        Finished\n         */\n        case MBEDTLS_SSL_CLIENT_CERTIFICATE:\n            ret = mbedtls_ssl_parse_certificate( ssl );\n            break;\n\n        case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:\n            ret = ssl_parse_client_key_exchange( ssl );\n            break;\n\n        case MBEDTLS_SSL_CERTIFICATE_VERIFY:\n            ret = ssl_parse_certificate_verify( ssl );\n            break;\n\n        case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:\n            ret = mbedtls_ssl_parse_change_cipher_spec( ssl );\n            break;\n\n        case MBEDTLS_SSL_CLIENT_FINISHED:\n            ret = mbedtls_ssl_parse_finished( ssl );\n            break;\n\n        /*\n         *  ==> ( NewSessionTicket )\n         *        ChangeCipherSpec\n         *        Finished\n         */\n        case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\n            if( ssl->handshake->new_session_ticket != 0 )\n                ret = ssl_write_new_session_ticket( ssl );\n            else\n#endif\n                ret = mbedtls_ssl_write_change_cipher_spec( ssl );\n            break;\n\n        case MBEDTLS_SSL_SERVER_FINISHED:\n            ret = mbedtls_ssl_write_finished( ssl );\n            break;\n\n        case MBEDTLS_SSL_FLUSH_BUFFERS:\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"handshake: done\" ) );\n            ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;\n            break;\n\n        case MBEDTLS_SSL_HANDSHAKE_WRAPUP:\n            mbedtls_ssl_handshake_wrapup( ssl );\n            break;\n\n        default:\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"invalid state %d\", ssl->state ) );\n            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n    }\n\n    return( ret );\n}\n#endif /* MBEDTLS_SSL_SRV_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/ssl_ticket.c",
    "content": "/*\n *  TLS server tickets callbacks implementation\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_SSL_TICKET_C)\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc    calloc\n#define mbedtls_free      free\n#endif\n\n#include \"mbedtls/ssl_ticket.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n/*\n * Initialze context\n */\nvoid mbedtls_ssl_ticket_init( mbedtls_ssl_ticket_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_ssl_ticket_context ) );\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_mutex_init( &ctx->mutex );\n#endif\n}\n\n#define MAX_KEY_BYTES 32    /* 256 bits */\n\n/*\n * Generate/update a key\n */\nstatic int ssl_ticket_gen_key( mbedtls_ssl_ticket_context *ctx,\n                               unsigned char index )\n{\n    int ret;\n    unsigned char buf[MAX_KEY_BYTES];\n    mbedtls_ssl_ticket_key *key = ctx->keys + index;\n\n#if defined(MBEDTLS_HAVE_TIME)\n    key->generation_time = (uint32_t) mbedtls_time( NULL );\n#endif\n\n    if( ( ret = ctx->f_rng( ctx->p_rng, key->name, sizeof( key->name ) ) ) != 0 )\n        return( ret );\n\n    if( ( ret = ctx->f_rng( ctx->p_rng, buf, sizeof( buf ) ) ) != 0 )\n        return( ret );\n\n    /* With GCM and CCM, same context can encrypt & decrypt */\n    ret = mbedtls_cipher_setkey( &key->ctx, buf,\n                                 mbedtls_cipher_get_key_bitlen( &key->ctx ),\n                                 MBEDTLS_ENCRYPT );\n\n    mbedtls_platform_zeroize( buf, sizeof( buf ) );\n\n    return( ret );\n}\n\n/*\n * Rotate/generate keys if necessary\n */\nstatic int ssl_ticket_update_keys( mbedtls_ssl_ticket_context *ctx )\n{\n#if !defined(MBEDTLS_HAVE_TIME)\n    ((void) ctx);\n#else\n    if( ctx->ticket_lifetime != 0 )\n    {\n        uint32_t current_time = (uint32_t) mbedtls_time( NULL );\n        uint32_t key_time = ctx->keys[ctx->active].generation_time;\n\n        if( current_time > key_time &&\n            current_time - key_time < ctx->ticket_lifetime )\n        {\n            return( 0 );\n        }\n\n        ctx->active = 1 - ctx->active;\n\n        return( ssl_ticket_gen_key( ctx, ctx->active ) );\n    }\n    else\n#endif /* MBEDTLS_HAVE_TIME */\n        return( 0 );\n}\n\n/*\n * Setup context for actual use\n */\nint mbedtls_ssl_ticket_setup( mbedtls_ssl_ticket_context *ctx,\n    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,\n    mbedtls_cipher_type_t cipher,\n    uint32_t lifetime )\n{\n    int ret;\n    const mbedtls_cipher_info_t *cipher_info;\n\n    ctx->f_rng = f_rng;\n    ctx->p_rng = p_rng;\n\n    ctx->ticket_lifetime = lifetime;\n\n    cipher_info = mbedtls_cipher_info_from_type( cipher);\n    if( cipher_info == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    if( cipher_info->mode != MBEDTLS_MODE_GCM &&\n        cipher_info->mode != MBEDTLS_MODE_CCM )\n    {\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n    }\n\n    if( cipher_info->key_bitlen > 8 * MAX_KEY_BYTES )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    if( ( ret = mbedtls_cipher_setup( &ctx->keys[0].ctx, cipher_info ) ) != 0 ||\n        ( ret = mbedtls_cipher_setup( &ctx->keys[1].ctx, cipher_info ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    if( ( ret = ssl_ticket_gen_key( ctx, 0 ) ) != 0 ||\n        ( ret = ssl_ticket_gen_key( ctx, 1 ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    return( 0 );\n}\n\n/*\n * Serialize a session in the following format:\n *  0   .   n-1     session structure, n = sizeof(mbedtls_ssl_session)\n *  n   .   n+2     peer_cert length = m (0 if no certificate)\n *  n+3 .   n+2+m   peer cert ASN.1\n */\nstatic int ssl_save_session( const mbedtls_ssl_session *session,\n                             unsigned char *buf, size_t buf_len,\n                             size_t *olen )\n{\n    unsigned char *p = buf;\n    size_t left = buf_len;\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    size_t cert_len;\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n    if( left < sizeof( mbedtls_ssl_session ) )\n        return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );\n\n    memcpy( p, session, sizeof( mbedtls_ssl_session ) );\n    p += sizeof( mbedtls_ssl_session );\n    left -= sizeof( mbedtls_ssl_session );\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    if( session->peer_cert == NULL )\n        cert_len = 0;\n    else\n        cert_len = session->peer_cert->raw.len;\n\n    if( left < 3 + cert_len )\n        return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );\n\n    *p++ = (unsigned char)( cert_len >> 16 & 0xFF );\n    *p++ = (unsigned char)( cert_len >>  8 & 0xFF );\n    *p++ = (unsigned char)( cert_len       & 0xFF );\n\n    if( session->peer_cert != NULL )\n        memcpy( p, session->peer_cert->raw.p, cert_len );\n\n    p += cert_len;\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n    *olen = p - buf;\n\n    return( 0 );\n}\n\n/*\n * Unserialise session, see ssl_save_session()\n */\nstatic int ssl_load_session( mbedtls_ssl_session *session,\n                             const unsigned char *buf, size_t len )\n{\n    const unsigned char *p = buf;\n    const unsigned char * const end = buf + len;\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    size_t cert_len;\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n    if( p + sizeof( mbedtls_ssl_session ) > end )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    memcpy( session, p, sizeof( mbedtls_ssl_session ) );\n    p += sizeof( mbedtls_ssl_session );\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    if( p + 3 > end )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    cert_len = ( p[0] << 16 ) | ( p[1] << 8 ) | p[2];\n    p += 3;\n\n    if( cert_len == 0 )\n    {\n        session->peer_cert = NULL;\n    }\n    else\n    {\n        int ret;\n\n        if( p + cert_len > end )\n            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n        session->peer_cert = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );\n\n        if( session->peer_cert == NULL )\n            return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n\n        mbedtls_x509_crt_init( session->peer_cert );\n\n        if( ( ret = mbedtls_x509_crt_parse_der( session->peer_cert,\n                                        p, cert_len ) ) != 0 )\n        {\n            mbedtls_x509_crt_free( session->peer_cert );\n            mbedtls_free( session->peer_cert );\n            session->peer_cert = NULL;\n            return( ret );\n        }\n\n        p += cert_len;\n    }\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n    if( p != end )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    return( 0 );\n}\n\n/*\n * Create session ticket, with the following structure:\n *\n *    struct {\n *        opaque key_name[4];\n *        opaque iv[12];\n *        opaque encrypted_state<0..2^16-1>;\n *        opaque tag[16];\n *    } ticket;\n *\n * The key_name, iv, and length of encrypted_state are the additional\n * authenticated data.\n */\nint mbedtls_ssl_ticket_write( void *p_ticket,\n                              const mbedtls_ssl_session *session,\n                              unsigned char *start,\n                              const unsigned char *end,\n                              size_t *tlen,\n                              uint32_t *ticket_lifetime )\n{\n    int ret;\n    mbedtls_ssl_ticket_context *ctx = p_ticket;\n    mbedtls_ssl_ticket_key *key;\n    unsigned char *key_name = start;\n    unsigned char *iv = start + 4;\n    unsigned char *state_len_bytes = iv + 12;\n    unsigned char *state = state_len_bytes + 2;\n    unsigned char *tag;\n    size_t clear_len, ciph_len;\n\n    *tlen = 0;\n\n    if( ctx == NULL || ctx->f_rng == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    /* We need at least 4 bytes for key_name, 12 for IV, 2 for len 16 for tag,\n     * in addition to session itself, that will be checked when writing it. */\n    if( end - start < 4 + 12 + 2 + 16 )\n        return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );\n\n#if defined(MBEDTLS_THREADING_C)\n    if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )\n        return( ret );\n#endif\n\n    if( ( ret = ssl_ticket_update_keys( ctx ) ) != 0 )\n        goto cleanup;\n\n    key = &ctx->keys[ctx->active];\n\n    *ticket_lifetime = ctx->ticket_lifetime;\n\n    memcpy( key_name, key->name, 4 );\n\n    if( ( ret = ctx->f_rng( ctx->p_rng, iv, 12 ) ) != 0 )\n        goto cleanup;\n\n    /* Dump session state */\n    if( ( ret = ssl_save_session( session,\n                                  state, end - state, &clear_len ) ) != 0 ||\n        (unsigned long) clear_len > 65535 )\n    {\n         goto cleanup;\n    }\n    state_len_bytes[0] = ( clear_len >> 8 ) & 0xff;\n    state_len_bytes[1] = ( clear_len      ) & 0xff;\n\n    /* Encrypt and authenticate */\n    tag = state + clear_len;\n    if( ( ret = mbedtls_cipher_auth_encrypt( &key->ctx,\n                    iv, 12, key_name, 4 + 12 + 2,\n                    state, clear_len, state, &ciph_len, tag, 16 ) ) != 0 )\n    {\n        goto cleanup;\n    }\n    if( ciph_len != clear_len )\n    {\n        ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;\n        goto cleanup;\n    }\n\n    *tlen = 4 + 12 + 2 + 16 + ciph_len;\n\ncleanup:\n#if defined(MBEDTLS_THREADING_C)\n    if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )\n        return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );\n#endif\n\n    return( ret );\n}\n\n/*\n * Select key based on name\n */\nstatic mbedtls_ssl_ticket_key *ssl_ticket_select_key(\n        mbedtls_ssl_ticket_context *ctx,\n        const unsigned char name[4] )\n{\n    unsigned char i;\n\n    for( i = 0; i < sizeof( ctx->keys ) / sizeof( *ctx->keys ); i++ )\n        if( memcmp( name, ctx->keys[i].name, 4 ) == 0 )\n            return( &ctx->keys[i] );\n\n    return( NULL );\n}\n\n/*\n * Load session ticket (see mbedtls_ssl_ticket_write for structure)\n */\nint mbedtls_ssl_ticket_parse( void *p_ticket,\n                              mbedtls_ssl_session *session,\n                              unsigned char *buf,\n                              size_t len )\n{\n    int ret;\n    mbedtls_ssl_ticket_context *ctx = p_ticket;\n    mbedtls_ssl_ticket_key *key;\n    unsigned char *key_name = buf;\n    unsigned char *iv = buf + 4;\n    unsigned char *enc_len_p = iv + 12;\n    unsigned char *ticket = enc_len_p + 2;\n    unsigned char *tag;\n    size_t enc_len, clear_len;\n\n    if( ctx == NULL || ctx->f_rng == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    /* See mbedtls_ssl_ticket_write() */\n    if( len < 4 + 12 + 2 + 16 )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n#if defined(MBEDTLS_THREADING_C)\n    if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )\n        return( ret );\n#endif\n\n    if( ( ret = ssl_ticket_update_keys( ctx ) ) != 0 )\n        goto cleanup;\n\n    enc_len = ( enc_len_p[0] << 8 ) | enc_len_p[1];\n    tag = ticket + enc_len;\n\n    if( len != 4 + 12 + 2 + enc_len + 16 )\n    {\n        ret = MBEDTLS_ERR_SSL_BAD_INPUT_DATA;\n        goto cleanup;\n    }\n\n    /* Select key */\n    if( ( key = ssl_ticket_select_key( ctx, key_name ) ) == NULL )\n    {\n        /* We can't know for sure but this is a likely option unless we're\n         * under attack - this is only informative anyway */\n        ret = MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED;\n        goto cleanup;\n    }\n\n    /* Decrypt and authenticate */\n    if( ( ret = mbedtls_cipher_auth_decrypt( &key->ctx, iv, 12,\n                    key_name, 4 + 12 + 2, ticket, enc_len,\n                    ticket, &clear_len, tag, 16 ) ) != 0 )\n    {\n        if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED )\n            ret = MBEDTLS_ERR_SSL_INVALID_MAC;\n\n        goto cleanup;\n    }\n    if( clear_len != enc_len )\n    {\n        ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;\n        goto cleanup;\n    }\n\n    /* Actually load session */\n    if( ( ret = ssl_load_session( session, ticket, clear_len ) ) != 0 )\n        goto cleanup;\n\n#if defined(MBEDTLS_HAVE_TIME)\n    {\n        /* Check for expiration */\n        mbedtls_time_t current_time = mbedtls_time( NULL );\n\n        if( current_time < session->start ||\n            (uint32_t)( current_time - session->start ) > ctx->ticket_lifetime )\n        {\n            ret = MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED;\n            goto cleanup;\n        }\n    }\n#endif\n\ncleanup:\n#if defined(MBEDTLS_THREADING_C)\n    if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )\n        return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );\n#endif\n\n    return( ret );\n}\n\n/*\n * Free context\n */\nvoid mbedtls_ssl_ticket_free( mbedtls_ssl_ticket_context *ctx )\n{\n    mbedtls_cipher_free( &ctx->keys[0].ctx );\n    mbedtls_cipher_free( &ctx->keys[1].ctx );\n\n#if defined(MBEDTLS_THREADING_C)\n    mbedtls_mutex_free( &ctx->mutex );\n#endif\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ssl_ticket_context ) );\n}\n\n#endif /* MBEDTLS_SSL_TICKET_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/ssl_tls.c",
    "content": "/*\n *  SSLv3/TLSv1 shared functions\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The SSL 3.0 specification was drafted by Netscape in 1996,\n *  and became an IETF standard in 1999.\n *\n *  http://wp.netscape.com/eng/ssl3/\n *  http://www.ietf.org/rfc/rfc2246.txt\n *  http://www.ietf.org/rfc/rfc4346.txt\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_SSL_TLS_C)\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_calloc    calloc\n#define mbedtls_free      free\n#endif\n\n#include \"mbedtls/debug.h\"\n#include \"mbedtls/ssl.h\"\n#include \"mbedtls/ssl_internal.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n#include \"mbedtls/oid.h\"\n#endif\n\n/* Length of the \"epoch\" field in the record header */\nstatic inline size_t ssl_ep_len( const mbedtls_ssl_context *ssl )\n{\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n        return( 2 );\n#else\n    ((void) ssl);\n#endif\n    return( 0 );\n}\n\n/*\n * Start a timer.\n * Passing millisecs = 0 cancels a running timer.\n */\nstatic void ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs )\n{\n    if( ssl->f_set_timer == NULL )\n        return;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"set_timer to %d ms\", (int) millisecs ) );\n    ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs );\n}\n\n/*\n * Return -1 is timer is expired, 0 if it isn't.\n */\nstatic int ssl_check_timer( mbedtls_ssl_context *ssl )\n{\n    if( ssl->f_get_timer == NULL )\n        return( 0 );\n\n    if( ssl->f_get_timer( ssl->p_timer ) == 2 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"timer expired\" ) );\n        return( -1 );\n    }\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n/*\n * Double the retransmit timeout value, within the allowed range,\n * returning -1 if the maximum value has already been reached.\n */\nstatic int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl )\n{\n    uint32_t new_timeout;\n\n    if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max )\n        return( -1 );\n\n    new_timeout = 2 * ssl->handshake->retransmit_timeout;\n\n    /* Avoid arithmetic overflow and range overflow */\n    if( new_timeout < ssl->handshake->retransmit_timeout ||\n        new_timeout > ssl->conf->hs_timeout_max )\n    {\n        new_timeout = ssl->conf->hs_timeout_max;\n    }\n\n    ssl->handshake->retransmit_timeout = new_timeout;\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"update timeout value to %d millisecs\",\n                        ssl->handshake->retransmit_timeout ) );\n\n    return( 0 );\n}\n\nstatic void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl )\n{\n    ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min;\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"update timeout value to %d millisecs\",\n                        ssl->handshake->retransmit_timeout ) );\n}\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\n/*\n * Convert max_fragment_length codes to length.\n * RFC 6066 says:\n *    enum{\n *        2^9(1), 2^10(2), 2^11(3), 2^12(4), (255)\n *    } MaxFragmentLength;\n * and we add 0 -> extension unused\n */\nstatic unsigned int ssl_mfl_code_to_length( int mfl )\n{\n    switch( mfl )\n    {\n    case MBEDTLS_SSL_MAX_FRAG_LEN_NONE:\n        return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN );\n    case MBEDTLS_SSL_MAX_FRAG_LEN_512:\n        return 512;\n    case MBEDTLS_SSL_MAX_FRAG_LEN_1024:\n        return 1024;\n    case MBEDTLS_SSL_MAX_FRAG_LEN_2048:\n        return 2048;\n    case MBEDTLS_SSL_MAX_FRAG_LEN_4096:\n        return 4096;\n    default:\n        return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN );\n    }\n}\n#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */\n\n#if defined(MBEDTLS_SSL_CLI_C)\nstatic int ssl_session_copy( mbedtls_ssl_session *dst, const mbedtls_ssl_session *src )\n{\n    mbedtls_ssl_session_free( dst );\n    memcpy( dst, src, sizeof( mbedtls_ssl_session ) );\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    if( src->peer_cert != NULL )\n    {\n        int ret;\n\n        dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) );\n        if( dst->peer_cert == NULL )\n            return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n\n        mbedtls_x509_crt_init( dst->peer_cert );\n\n        if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p,\n                                        src->peer_cert->raw.len ) ) != 0 )\n        {\n            mbedtls_free( dst->peer_cert );\n            dst->peer_cert = NULL;\n            return( ret );\n        }\n    }\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)\n    if( src->ticket != NULL )\n    {\n        dst->ticket = mbedtls_calloc( 1, src->ticket_len );\n        if( dst->ticket == NULL )\n            return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n\n        memcpy( dst->ticket, src->ticket, src->ticket_len );\n    }\n#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_CLI_C */\n\n#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)\nint (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl,\n                     const unsigned char *key_enc, const unsigned char *key_dec,\n                     size_t keylen,\n                     const unsigned char *iv_enc,  const unsigned char *iv_dec,\n                     size_t ivlen,\n                     const unsigned char *mac_enc, const unsigned char *mac_dec,\n                     size_t maclen ) = NULL;\nint (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL;\nint (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL;\nint (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL;\nint (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL;\nint (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL;\n#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */\n\n/*\n * Key material generation\n */\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\nstatic int ssl3_prf( const unsigned char *secret, size_t slen,\n                     const char *label,\n                     const unsigned char *random, size_t rlen,\n                     unsigned char *dstbuf, size_t dlen )\n{\n    int ret = 0;\n    size_t i;\n    mbedtls_md5_context md5;\n    mbedtls_sha1_context sha1;\n    unsigned char padding[16];\n    unsigned char sha1sum[20];\n    ((void)label);\n\n    mbedtls_md5_init(  &md5  );\n    mbedtls_sha1_init( &sha1 );\n\n    /*\n     *  SSLv3:\n     *    block =\n     *      MD5( secret + SHA1( 'A'    + secret + random ) ) +\n     *      MD5( secret + SHA1( 'BB'   + secret + random ) ) +\n     *      MD5( secret + SHA1( 'CCC'  + secret + random ) ) +\n     *      ...\n     */\n    for( i = 0; i < dlen / 16; i++ )\n    {\n        memset( padding, (unsigned char) ('A' + i), 1 + i );\n\n        if( ( ret = mbedtls_sha1_starts_ret( &sha1 ) ) != 0 )\n            goto exit;\n        if( ( ret = mbedtls_sha1_update_ret( &sha1, padding, 1 + i ) ) != 0 )\n            goto exit;\n        if( ( ret = mbedtls_sha1_update_ret( &sha1, secret, slen ) ) != 0 )\n            goto exit;\n        if( ( ret = mbedtls_sha1_update_ret( &sha1, random, rlen ) ) != 0 )\n            goto exit;\n        if( ( ret = mbedtls_sha1_finish_ret( &sha1, sha1sum ) ) != 0 )\n            goto exit;\n\n        if( ( ret = mbedtls_md5_starts_ret( &md5 ) ) != 0 )\n            goto exit;\n        if( ( ret = mbedtls_md5_update_ret( &md5, secret, slen ) ) != 0 )\n            goto exit;\n        if( ( ret = mbedtls_md5_update_ret( &md5, sha1sum, 20 ) ) != 0 )\n            goto exit;\n        if( ( ret = mbedtls_md5_finish_ret( &md5, dstbuf + i * 16 ) ) != 0 )\n            goto exit;\n    }\n\nexit:\n    mbedtls_md5_free(  &md5  );\n    mbedtls_sha1_free( &sha1 );\n\n    mbedtls_platform_zeroize( padding, sizeof( padding ) );\n    mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) );\n\n    return( ret );\n}\n#endif /* MBEDTLS_SSL_PROTO_SSL3 */\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)\nstatic int tls1_prf( const unsigned char *secret, size_t slen,\n                     const char *label,\n                     const unsigned char *random, size_t rlen,\n                     unsigned char *dstbuf, size_t dlen )\n{\n    size_t nb, hs;\n    size_t i, j, k;\n    const unsigned char *S1, *S2;\n    unsigned char tmp[128];\n    unsigned char h_i[20];\n    const mbedtls_md_info_t *md_info;\n    mbedtls_md_context_t md_ctx;\n    int ret;\n\n    mbedtls_md_init( &md_ctx );\n\n    if( sizeof( tmp ) < 20 + strlen( label ) + rlen )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    hs = ( slen + 1 ) / 2;\n    S1 = secret;\n    S2 = secret + slen - hs;\n\n    nb = strlen( label );\n    memcpy( tmp + 20, label, nb );\n    memcpy( tmp + 20 + nb, random, rlen );\n    nb += rlen;\n\n    /*\n     * First compute P_md5(secret,label+random)[0..dlen]\n     */\n    if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ) ) == NULL )\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n\n    if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )\n        return( ret );\n\n    mbedtls_md_hmac_starts( &md_ctx, S1, hs );\n    mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );\n    mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );\n\n    for( i = 0; i < dlen; i += 16 )\n    {\n        mbedtls_md_hmac_reset ( &md_ctx );\n        mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 + nb );\n        mbedtls_md_hmac_finish( &md_ctx, h_i );\n\n        mbedtls_md_hmac_reset ( &md_ctx );\n        mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 );\n        mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );\n\n        k = ( i + 16 > dlen ) ? dlen % 16 : 16;\n\n        for( j = 0; j < k; j++ )\n            dstbuf[i + j]  = h_i[j];\n    }\n\n    mbedtls_md_free( &md_ctx );\n\n    /*\n     * XOR out with P_sha1(secret,label+random)[0..dlen]\n     */\n    if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ) ) == NULL )\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n\n    if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )\n        return( ret );\n\n    mbedtls_md_hmac_starts( &md_ctx, S2, hs );\n    mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );\n    mbedtls_md_hmac_finish( &md_ctx, tmp );\n\n    for( i = 0; i < dlen; i += 20 )\n    {\n        mbedtls_md_hmac_reset ( &md_ctx );\n        mbedtls_md_hmac_update( &md_ctx, tmp, 20 + nb );\n        mbedtls_md_hmac_finish( &md_ctx, h_i );\n\n        mbedtls_md_hmac_reset ( &md_ctx );\n        mbedtls_md_hmac_update( &md_ctx, tmp, 20 );\n        mbedtls_md_hmac_finish( &md_ctx, tmp );\n\n        k = ( i + 20 > dlen ) ? dlen % 20 : 20;\n\n        for( j = 0; j < k; j++ )\n            dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] );\n    }\n\n    mbedtls_md_free( &md_ctx );\n\n    mbedtls_platform_zeroize( tmp, sizeof( tmp ) );\n    mbedtls_platform_zeroize( h_i, sizeof( h_i ) );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\nstatic int tls_prf_generic( mbedtls_md_type_t md_type,\n                            const unsigned char *secret, size_t slen,\n                            const char *label,\n                            const unsigned char *random, size_t rlen,\n                            unsigned char *dstbuf, size_t dlen )\n{\n    size_t nb;\n    size_t i, j, k, md_len;\n    unsigned char tmp[128];\n    unsigned char h_i[MBEDTLS_MD_MAX_SIZE];\n    const mbedtls_md_info_t *md_info;\n    mbedtls_md_context_t md_ctx;\n    int ret;\n\n    mbedtls_md_init( &md_ctx );\n\n    if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL )\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n\n    md_len = mbedtls_md_get_size( md_info );\n\n    if( sizeof( tmp ) < md_len + strlen( label ) + rlen )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    nb = strlen( label );\n    memcpy( tmp + md_len, label, nb );\n    memcpy( tmp + md_len + nb, random, rlen );\n    nb += rlen;\n\n    /*\n     * Compute P_<hash>(secret, label + random)[0..dlen]\n     */\n    if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )\n        return( ret );\n\n    mbedtls_md_hmac_starts( &md_ctx, secret, slen );\n    mbedtls_md_hmac_update( &md_ctx, tmp + md_len, nb );\n    mbedtls_md_hmac_finish( &md_ctx, tmp );\n\n    for( i = 0; i < dlen; i += md_len )\n    {\n        mbedtls_md_hmac_reset ( &md_ctx );\n        mbedtls_md_hmac_update( &md_ctx, tmp, md_len + nb );\n        mbedtls_md_hmac_finish( &md_ctx, h_i );\n\n        mbedtls_md_hmac_reset ( &md_ctx );\n        mbedtls_md_hmac_update( &md_ctx, tmp, md_len );\n        mbedtls_md_hmac_finish( &md_ctx, tmp );\n\n        k = ( i + md_len > dlen ) ? dlen % md_len : md_len;\n\n        for( j = 0; j < k; j++ )\n            dstbuf[i + j]  = h_i[j];\n    }\n\n    mbedtls_md_free( &md_ctx );\n\n    mbedtls_platform_zeroize( tmp, sizeof( tmp ) );\n    mbedtls_platform_zeroize( h_i, sizeof( h_i ) );\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_SHA256_C)\nstatic int tls_prf_sha256( const unsigned char *secret, size_t slen,\n                           const char *label,\n                           const unsigned char *random, size_t rlen,\n                           unsigned char *dstbuf, size_t dlen )\n{\n    return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen,\n                             label, random, rlen, dstbuf, dlen ) );\n}\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\nstatic int tls_prf_sha384( const unsigned char *secret, size_t slen,\n                           const char *label,\n                           const unsigned char *random, size_t rlen,\n                           unsigned char *dstbuf, size_t dlen )\n{\n    return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen,\n                             label, random, rlen, dstbuf, dlen ) );\n}\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n\nstatic void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t );\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1)\nstatic void ssl_update_checksum_md5sha1( mbedtls_ssl_context *, const unsigned char *, size_t );\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\nstatic void ssl_calc_verify_ssl( mbedtls_ssl_context *, unsigned char * );\nstatic void ssl_calc_finished_ssl( mbedtls_ssl_context *, unsigned char *, int );\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)\nstatic void ssl_calc_verify_tls( mbedtls_ssl_context *, unsigned char * );\nstatic void ssl_calc_finished_tls( mbedtls_ssl_context *, unsigned char *, int );\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#if defined(MBEDTLS_SHA256_C)\nstatic void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t );\nstatic void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *,unsigned char * );\nstatic void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int );\n#endif\n\n#if defined(MBEDTLS_SHA512_C)\nstatic void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t );\nstatic void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *, unsigned char * );\nstatic void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int );\n#endif\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n\nint mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )\n{\n    int ret = 0;\n    unsigned char tmp[64];\n    unsigned char keyblk[256];\n    unsigned char *key1;\n    unsigned char *key2;\n    unsigned char *mac_enc;\n    unsigned char *mac_dec;\n    size_t mac_key_len;\n    size_t iv_copy_len;\n    const mbedtls_cipher_info_t *cipher_info;\n    const mbedtls_md_info_t *md_info;\n\n    mbedtls_ssl_session *session = ssl->session_negotiate;\n    mbedtls_ssl_transform *transform = ssl->transform_negotiate;\n    mbedtls_ssl_handshake_params *handshake = ssl->handshake;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> derive keys\" ) );\n\n    cipher_info = mbedtls_cipher_info_from_type( transform->ciphersuite_info->cipher );\n    if( cipher_info == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"cipher info for %d not found\",\n                            transform->ciphersuite_info->cipher ) );\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n    }\n\n    md_info = mbedtls_md_info_from_type( transform->ciphersuite_info->mac );\n    if( md_info == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"mbedtls_md info for %d not found\",\n                            transform->ciphersuite_info->mac ) );\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n    }\n\n    /*\n     * Set appropriate PRF function and other SSL / TLS / TLS1.2 functions\n     */\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )\n    {\n        handshake->tls_prf = ssl3_prf;\n        handshake->calc_verify = ssl_calc_verify_ssl;\n        handshake->calc_finished = ssl_calc_finished_ssl;\n    }\n    else\n#endif\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)\n    if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )\n    {\n        handshake->tls_prf = tls1_prf;\n        handshake->calc_verify = ssl_calc_verify_tls;\n        handshake->calc_finished = ssl_calc_finished_tls;\n    }\n    else\n#endif\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#if defined(MBEDTLS_SHA512_C)\n    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 &&\n        transform->ciphersuite_info->mac == MBEDTLS_MD_SHA384 )\n    {\n        handshake->tls_prf = tls_prf_sha384;\n        handshake->calc_verify = ssl_calc_verify_tls_sha384;\n        handshake->calc_finished = ssl_calc_finished_tls_sha384;\n    }\n    else\n#endif\n#if defined(MBEDTLS_SHA256_C)\n    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )\n    {\n        handshake->tls_prf = tls_prf_sha256;\n        handshake->calc_verify = ssl_calc_verify_tls_sha256;\n        handshake->calc_finished = ssl_calc_finished_tls_sha256;\n    }\n    else\n#endif\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    /*\n     * SSLv3:\n     *   master =\n     *     MD5( premaster + SHA1( 'A'   + premaster + randbytes ) ) +\n     *     MD5( premaster + SHA1( 'BB'  + premaster + randbytes ) ) +\n     *     MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) )\n     *\n     * TLSv1+:\n     *   master = PRF( premaster, \"master secret\", randbytes )[0..47]\n     */\n    if( handshake->resume == 0 )\n    {\n        MBEDTLS_SSL_DEBUG_BUF( 3, \"premaster secret\", handshake->premaster,\n                       handshake->pmslen );\n\n#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)\n        if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED )\n        {\n            unsigned char session_hash[48];\n            size_t hash_len;\n\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"using extended master secret\" ) );\n\n            ssl->handshake->calc_verify( ssl, session_hash );\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n            if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )\n            {\n#if defined(MBEDTLS_SHA512_C)\n                if( ssl->transform_negotiate->ciphersuite_info->mac ==\n                    MBEDTLS_MD_SHA384 )\n                {\n                    hash_len = 48;\n                }\n                else\n#endif\n                    hash_len = 32;\n            }\n            else\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n                hash_len = 36;\n\n            MBEDTLS_SSL_DEBUG_BUF( 3, \"session hash\", session_hash, hash_len );\n\n            ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,\n                                      \"extended master secret\",\n                                      session_hash, hash_len,\n                                      session->master, 48 );\n            if( ret != 0 )\n            {\n                MBEDTLS_SSL_DEBUG_RET( 1, \"prf\", ret );\n                return( ret );\n            }\n\n        }\n        else\n#endif\n        ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,\n                                  \"master secret\",\n                                  handshake->randbytes, 64,\n                                  session->master, 48 );\n        if( ret != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"prf\", ret );\n            return( ret );\n        }\n\n        mbedtls_platform_zeroize( handshake->premaster,\n                                  sizeof(handshake->premaster) );\n    }\n    else\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"no premaster (session resumed)\" ) );\n\n    /*\n     * Swap the client and server random values.\n     */\n    memcpy( tmp, handshake->randbytes, 64 );\n    memcpy( handshake->randbytes, tmp + 32, 32 );\n    memcpy( handshake->randbytes + 32, tmp, 32 );\n    mbedtls_platform_zeroize( tmp, sizeof( tmp ) );\n\n    /*\n     *  SSLv3:\n     *    key block =\n     *      MD5( master + SHA1( 'A'    + master + randbytes ) ) +\n     *      MD5( master + SHA1( 'BB'   + master + randbytes ) ) +\n     *      MD5( master + SHA1( 'CCC'  + master + randbytes ) ) +\n     *      MD5( master + SHA1( 'DDDD' + master + randbytes ) ) +\n     *      ...\n     *\n     *  TLSv1:\n     *    key block = PRF( master, \"key expansion\", randbytes )\n     */\n    ret = handshake->tls_prf( session->master, 48, \"key expansion\",\n                              handshake->randbytes, 64, keyblk, 256 );\n    if( ret != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"prf\", ret );\n        return( ret );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciphersuite = %s\",\n                   mbedtls_ssl_get_ciphersuite_name( session->ciphersuite ) ) );\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"master secret\", session->master, 48 );\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"random bytes\", handshake->randbytes, 64 );\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"key block\", keyblk, 256 );\n\n    mbedtls_platform_zeroize( handshake->randbytes,\n                              sizeof( handshake->randbytes ) );\n\n    /*\n     * Determine the appropriate key, IV and MAC length.\n     */\n\n    transform->keylen = cipher_info->key_bitlen / 8;\n\n    if( cipher_info->mode == MBEDTLS_MODE_GCM ||\n        cipher_info->mode == MBEDTLS_MODE_CCM ||\n        cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )\n    {\n        size_t taglen, explicit_ivlen;\n\n        transform->maclen = 0;\n        mac_key_len = 0;\n\n        /* All modes haves 96-bit IVs;\n         * GCM and CCM has 4 implicit and 8 explicit bytes\n         * ChachaPoly has all 12 bytes implicit\n         */\n        transform->ivlen = 12;\n        if( cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )\n            transform->fixed_ivlen = 12;\n        else\n            transform->fixed_ivlen = 4;\n\n        /* All modes have 128-bit tags, except CCM_8 (ciphersuite flag) */\n        taglen = transform->ciphersuite_info->flags &\n                  MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;\n\n\n        /* Minimum length of encrypted record */\n        explicit_ivlen = transform->ivlen - transform->fixed_ivlen;\n        transform->minlen = explicit_ivlen + taglen;\n    }\n    else\n    {\n        /* Initialize HMAC contexts */\n        if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 ||\n            ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_md_setup\", ret );\n            return( ret );\n        }\n\n        /* Get MAC length */\n        mac_key_len = mbedtls_md_get_size( md_info );\n        transform->maclen = mac_key_len;\n\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)\n        /*\n         * If HMAC is to be truncated, we shall keep the leftmost bytes,\n         * (rfc 6066 page 13 or rfc 2104 section 4),\n         * so we only need to adjust the length here.\n         */\n        if( session->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )\n        {\n            transform->maclen = MBEDTLS_SSL_TRUNCATED_HMAC_LEN;\n\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT)\n            /* Fall back to old, non-compliant version of the truncated\n             * HMAC implementation which also truncates the key\n             * (Mbed TLS versions from 1.3 to 2.6.0) */\n            mac_key_len = transform->maclen;\n#endif\n        }\n#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */\n\n        /* IV length */\n        transform->ivlen = cipher_info->iv_size;\n\n        /* Minimum length */\n        if( cipher_info->mode == MBEDTLS_MODE_STREAM )\n            transform->minlen = transform->maclen;\n        else\n        {\n            /*\n             * GenericBlockCipher:\n             * 1. if EtM is in use: one block plus MAC\n             *    otherwise: * first multiple of blocklen greater than maclen\n             * 2. IV except for SSL3 and TLS 1.0\n             */\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\n            if( session->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )\n            {\n                transform->minlen = transform->maclen\n                                  + cipher_info->block_size;\n            }\n            else\n#endif\n            {\n                transform->minlen = transform->maclen\n                                  + cipher_info->block_size\n                                  - transform->maclen % cipher_info->block_size;\n            }\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)\n            if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||\n                ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_1 )\n                ; /* No need to adjust minlen */\n            else\n#endif\n#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)\n            if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_2 ||\n                ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )\n            {\n                transform->minlen += transform->ivlen;\n            }\n            else\n#endif\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n                return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n            }\n        }\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"keylen: %d, minlen: %d, ivlen: %d, maclen: %d\",\n                   transform->keylen, transform->minlen, transform->ivlen,\n                   transform->maclen ) );\n\n    /*\n     * Finally setup the cipher contexts, IVs and MAC secrets.\n     */\n#if defined(MBEDTLS_SSL_CLI_C)\n    if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )\n    {\n        key1 = keyblk + mac_key_len * 2;\n        key2 = keyblk + mac_key_len * 2 + transform->keylen;\n\n        mac_enc = keyblk;\n        mac_dec = keyblk + mac_key_len;\n\n        /*\n         * This is not used in TLS v1.1.\n         */\n        iv_copy_len = ( transform->fixed_ivlen ) ?\n                            transform->fixed_ivlen : transform->ivlen;\n        memcpy( transform->iv_enc, key2 + transform->keylen,  iv_copy_len );\n        memcpy( transform->iv_dec, key2 + transform->keylen + iv_copy_len,\n                iv_copy_len );\n    }\n    else\n#endif /* MBEDTLS_SSL_CLI_C */\n#if defined(MBEDTLS_SSL_SRV_C)\n    if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )\n    {\n        key1 = keyblk + mac_key_len * 2 + transform->keylen;\n        key2 = keyblk + mac_key_len * 2;\n\n        mac_enc = keyblk + mac_key_len;\n        mac_dec = keyblk;\n\n        /*\n         * This is not used in TLS v1.1.\n         */\n        iv_copy_len = ( transform->fixed_ivlen ) ?\n                            transform->fixed_ivlen : transform->ivlen;\n        memcpy( transform->iv_dec, key1 + transform->keylen,  iv_copy_len );\n        memcpy( transform->iv_enc, key1 + transform->keylen + iv_copy_len,\n                iv_copy_len );\n    }\n    else\n#endif /* MBEDTLS_SSL_SRV_C */\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )\n    {\n        if( mac_key_len > sizeof transform->mac_enc )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n        memcpy( transform->mac_enc, mac_enc, mac_key_len );\n        memcpy( transform->mac_dec, mac_dec, mac_key_len );\n    }\n    else\n#endif /* MBEDTLS_SSL_PROTO_SSL3 */\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_2)\n    if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )\n    {\n        /* For HMAC-based ciphersuites, initialize the HMAC transforms.\n           For AEAD-based ciphersuites, there is nothing to do here. */\n        if( mac_key_len != 0 )\n        {\n            mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, mac_key_len );\n            mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, mac_key_len );\n        }\n    }\n    else\n#endif\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)\n    if( mbedtls_ssl_hw_record_init != NULL )\n    {\n        int ret = 0;\n\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"going for mbedtls_ssl_hw_record_init()\" ) );\n\n        if( ( ret = mbedtls_ssl_hw_record_init( ssl, key1, key2, transform->keylen,\n                                        transform->iv_enc, transform->iv_dec,\n                                        iv_copy_len,\n                                        mac_enc, mac_dec,\n                                        mac_key_len ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_hw_record_init\", ret );\n            return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );\n        }\n    }\n#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */\n\n#if defined(MBEDTLS_SSL_EXPORT_KEYS)\n    if( ssl->conf->f_export_keys != NULL )\n    {\n        ssl->conf->f_export_keys( ssl->conf->p_export_keys,\n                                  session->master, keyblk,\n                                  mac_key_len, transform->keylen,\n                                  iv_copy_len );\n    }\n#endif\n\n    if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc,\n                                 cipher_info ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_cipher_setup\", ret );\n        return( ret );\n    }\n\n    if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec,\n                                 cipher_info ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_cipher_setup\", ret );\n        return( ret );\n    }\n\n    if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1,\n                               cipher_info->key_bitlen,\n                               MBEDTLS_ENCRYPT ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_cipher_setkey\", ret );\n        return( ret );\n    }\n\n    if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2,\n                               cipher_info->key_bitlen,\n                               MBEDTLS_DECRYPT ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_cipher_setkey\", ret );\n        return( ret );\n    }\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    if( cipher_info->mode == MBEDTLS_MODE_CBC )\n    {\n        if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc,\n                                             MBEDTLS_PADDING_NONE ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_cipher_set_padding_mode\", ret );\n            return( ret );\n        }\n\n        if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec,\n                                             MBEDTLS_PADDING_NONE ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_cipher_set_padding_mode\", ret );\n            return( ret );\n        }\n    }\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n\n    mbedtls_platform_zeroize( keyblk, sizeof( keyblk ) );\n\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n    // Initialize compression\n    //\n    if( session->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )\n    {\n        if( ssl->compress_buf == NULL )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"Allocating compression buffer\" ) );\n            ssl->compress_buf = mbedtls_calloc( 1, MBEDTLS_SSL_COMPRESS_BUFFER_LEN );\n            if( ssl->compress_buf == NULL )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"alloc(%d bytes) failed\",\n                                    MBEDTLS_SSL_COMPRESS_BUFFER_LEN ) );\n                return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n            }\n        }\n\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"Initializing zlib states\" ) );\n\n        memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );\n        memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );\n\n        if( deflateInit( &transform->ctx_deflate,\n                         Z_DEFAULT_COMPRESSION )   != Z_OK ||\n            inflateInit( &transform->ctx_inflate ) != Z_OK )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"Failed to initialize compression\" ) );\n            return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );\n        }\n    }\n#endif /* MBEDTLS_ZLIB_SUPPORT */\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= derive keys\" ) );\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\nvoid ssl_calc_verify_ssl( mbedtls_ssl_context *ssl, unsigned char hash[36] )\n{\n    mbedtls_md5_context md5;\n    mbedtls_sha1_context sha1;\n    unsigned char pad_1[48];\n    unsigned char pad_2[48];\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> calc verify ssl\" ) );\n\n    mbedtls_md5_init( &md5 );\n    mbedtls_sha1_init( &sha1 );\n\n    mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );\n    mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );\n\n    memset( pad_1, 0x36, 48 );\n    memset( pad_2, 0x5C, 48 );\n\n    mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 );\n    mbedtls_md5_update_ret( &md5, pad_1, 48 );\n    mbedtls_md5_finish_ret( &md5, hash );\n\n    mbedtls_md5_starts_ret( &md5 );\n    mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 );\n    mbedtls_md5_update_ret( &md5, pad_2, 48 );\n    mbedtls_md5_update_ret( &md5, hash,  16 );\n    mbedtls_md5_finish_ret( &md5, hash );\n\n    mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 );\n    mbedtls_sha1_update_ret( &sha1, pad_1, 40 );\n    mbedtls_sha1_finish_ret( &sha1, hash + 16 );\n\n    mbedtls_sha1_starts_ret( &sha1 );\n    mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 );\n    mbedtls_sha1_update_ret( &sha1, pad_2, 40 );\n    mbedtls_sha1_update_ret( &sha1, hash + 16, 20 );\n    mbedtls_sha1_finish_ret( &sha1, hash + 16 );\n\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"calculated verify result\", hash, 36 );\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= calc verify\" ) );\n\n    mbedtls_md5_free(  &md5  );\n    mbedtls_sha1_free( &sha1 );\n\n    return;\n}\n#endif /* MBEDTLS_SSL_PROTO_SSL3 */\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)\nvoid ssl_calc_verify_tls( mbedtls_ssl_context *ssl, unsigned char hash[36] )\n{\n    mbedtls_md5_context md5;\n    mbedtls_sha1_context sha1;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> calc verify tls\" ) );\n\n    mbedtls_md5_init( &md5 );\n    mbedtls_sha1_init( &sha1 );\n\n    mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );\n    mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );\n\n     mbedtls_md5_finish_ret( &md5,  hash );\n    mbedtls_sha1_finish_ret( &sha1, hash + 16 );\n\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"calculated verify result\", hash, 36 );\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= calc verify\" ) );\n\n    mbedtls_md5_free(  &md5  );\n    mbedtls_sha1_free( &sha1 );\n\n    return;\n}\n#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#if defined(MBEDTLS_SHA256_C)\nvoid ssl_calc_verify_tls_sha256( mbedtls_ssl_context *ssl, unsigned char hash[32] )\n{\n    mbedtls_sha256_context sha256;\n\n    mbedtls_sha256_init( &sha256 );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> calc verify sha256\" ) );\n\n    mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );\n    mbedtls_sha256_finish_ret( &sha256, hash );\n\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"calculated verify result\", hash, 32 );\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= calc verify\" ) );\n\n    mbedtls_sha256_free( &sha256 );\n\n    return;\n}\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\nvoid ssl_calc_verify_tls_sha384( mbedtls_ssl_context *ssl, unsigned char hash[48] )\n{\n    mbedtls_sha512_context sha512;\n\n    mbedtls_sha512_init( &sha512 );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> calc verify sha384\" ) );\n\n    mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );\n    mbedtls_sha512_finish_ret( &sha512, hash );\n\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"calculated verify result\", hash, 48 );\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= calc verify\" ) );\n\n    mbedtls_sha512_free( &sha512 );\n\n    return;\n}\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)\nint mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex )\n{\n    unsigned char *p = ssl->handshake->premaster;\n    unsigned char *end = p + sizeof( ssl->handshake->premaster );\n    const unsigned char *psk = ssl->conf->psk;\n    size_t psk_len = ssl->conf->psk_len;\n\n    /* If the psk callback was called, use its result */\n    if( ssl->handshake->psk != NULL )\n    {\n        psk = ssl->handshake->psk;\n        psk_len = ssl->handshake->psk_len;\n    }\n\n    /*\n     * PMS = struct {\n     *     opaque other_secret<0..2^16-1>;\n     *     opaque psk<0..2^16-1>;\n     * };\n     * with \"other_secret\" depending on the particular key exchange\n     */\n#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)\n    if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK )\n    {\n        if( end - p < 2 )\n            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n        *(p++) = (unsigned char)( psk_len >> 8 );\n        *(p++) = (unsigned char)( psk_len      );\n\n        if( end < p || (size_t)( end - p ) < psk_len )\n            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n        memset( p, 0, psk_len );\n        p += psk_len;\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)\n    if( key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK )\n    {\n        /*\n         * other_secret already set by the ClientKeyExchange message,\n         * and is 48 bytes long\n         */\n        if( end - p < 2 )\n            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n        *p++ = 0;\n        *p++ = 48;\n        p += 48;\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)\n    if( key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK )\n    {\n        int ret;\n        size_t len;\n\n        /* Write length only when we know the actual value */\n        if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,\n                                      p + 2, end - ( p + 2 ), &len,\n                                      ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_dhm_calc_secret\", ret );\n            return( ret );\n        }\n        *(p++) = (unsigned char)( len >> 8 );\n        *(p++) = (unsigned char)( len );\n        p += len;\n\n        MBEDTLS_SSL_DEBUG_MPI( 3, \"DHM: K \", &ssl->handshake->dhm_ctx.K  );\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)\n    if( key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )\n    {\n        int ret;\n        size_t zlen;\n\n        if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen,\n                                       p + 2, end - ( p + 2 ),\n                                       ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ecdh_calc_secret\", ret );\n            return( ret );\n        }\n\n        *(p++) = (unsigned char)( zlen >> 8 );\n        *(p++) = (unsigned char)( zlen      );\n        p += zlen;\n\n        MBEDTLS_SSL_DEBUG_MPI( 3, \"ECDH: z\", &ssl->handshake->ecdh_ctx.z );\n    }\n    else\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    /* opaque psk<0..2^16-1>; */\n    if( end - p < 2 )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    *(p++) = (unsigned char)( psk_len >> 8 );\n    *(p++) = (unsigned char)( psk_len      );\n\n    if( end < p || (size_t)( end - p ) < psk_len )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    memcpy( p, psk, psk_len );\n    p += psk_len;\n\n    ssl->handshake->pmslen = p - ssl->handshake->premaster;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n/*\n * SSLv3.0 MAC functions\n */\n#define SSL_MAC_MAX_BYTES   20  /* MD-5 or SHA-1 */\nstatic void ssl_mac( mbedtls_md_context_t *md_ctx,\n                     const unsigned char *secret,\n                     const unsigned char *buf, size_t len,\n                     const unsigned char *ctr, int type,\n                     unsigned char out[SSL_MAC_MAX_BYTES] )\n{\n    unsigned char header[11];\n    unsigned char padding[48];\n    int padlen;\n    int md_size = mbedtls_md_get_size( md_ctx->md_info );\n    int md_type = mbedtls_md_get_type( md_ctx->md_info );\n\n    /* Only MD5 and SHA-1 supported */\n    if( md_type == MBEDTLS_MD_MD5 )\n        padlen = 48;\n    else\n        padlen = 40;\n\n    memcpy( header, ctr, 8 );\n    header[ 8] = (unsigned char)  type;\n    header[ 9] = (unsigned char)( len >> 8 );\n    header[10] = (unsigned char)( len      );\n\n    memset( padding, 0x36, padlen );\n    mbedtls_md_starts( md_ctx );\n    mbedtls_md_update( md_ctx, secret,  md_size );\n    mbedtls_md_update( md_ctx, padding, padlen  );\n    mbedtls_md_update( md_ctx, header,  11      );\n    mbedtls_md_update( md_ctx, buf,     len     );\n    mbedtls_md_finish( md_ctx, out              );\n\n    memset( padding, 0x5C, padlen );\n    mbedtls_md_starts( md_ctx );\n    mbedtls_md_update( md_ctx, secret,    md_size );\n    mbedtls_md_update( md_ctx, padding,   padlen  );\n    mbedtls_md_update( md_ctx, out,       md_size );\n    mbedtls_md_finish( md_ctx, out                );\n}\n#endif /* MBEDTLS_SSL_PROTO_SSL3 */\n\n#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) ||     \\\n    ( defined(MBEDTLS_CIPHER_MODE_CBC) &&                                  \\\n      ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C)) )\n#define SSL_SOME_MODES_USE_MAC\n#endif\n\n/* The function below is only used in the Lucky 13 counter-measure in\n * ssl_decrypt_buf(). These are the defines that guard the call site. */\n#if defined(SSL_SOME_MODES_USE_MAC) && \\\n    ( defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n      defined(MBEDTLS_SSL_PROTO_TLS1_1) || \\\n      defined(MBEDTLS_SSL_PROTO_TLS1_2) )\n/* This function makes sure every byte in the memory region is accessed\n * (in ascending addresses order) */\nstatic void ssl_read_memory( unsigned char *p, size_t len )\n{\n    unsigned char acc = 0;\n    volatile unsigned char force;\n\n    for( ; len != 0; p++, len-- )\n        acc ^= *p;\n\n    force = acc;\n    (void) force;\n}\n#endif /* SSL_SOME_MODES_USE_MAC && ( TLS1 || TLS1_1 || TLS1_2 ) */\n\n/*\n * Encryption/decryption functions\n */\nstatic int ssl_encrypt_buf( mbedtls_ssl_context *ssl )\n{\n    mbedtls_cipher_mode_t mode;\n    int auth_done = 0;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> encrypt buf\" ) );\n\n    if( ssl->session_out == NULL || ssl->transform_out == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc );\n\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"before encrypt: output payload\",\n                      ssl->out_msg, ssl->out_msglen );\n\n    if( ssl->out_msglen > MBEDTLS_SSL_OUT_CONTENT_LEN )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"Record content %u too large, maximum %d\",\n                                    (unsigned) ssl->out_msglen,\n                                    MBEDTLS_SSL_OUT_CONTENT_LEN ) );\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n    }\n\n    /*\n     * Add MAC before if needed\n     */\n#if defined(SSL_SOME_MODES_USE_MAC)\n    if( mode == MBEDTLS_MODE_STREAM ||\n        ( mode == MBEDTLS_MODE_CBC\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\n          && ssl->session_out->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED\n#endif\n        ) )\n    {\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n        if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )\n        {\n            unsigned char mac[SSL_MAC_MAX_BYTES];\n\n            ssl_mac( &ssl->transform_out->md_ctx_enc,\n                      ssl->transform_out->mac_enc,\n                      ssl->out_msg, ssl->out_msglen,\n                      ssl->out_ctr, ssl->out_msgtype,\n                      mac );\n\n            memcpy( ssl->out_msg + ssl->out_msglen, mac, ssl->transform_out->maclen );\n        }\n        else\n#endif\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \\\n        defined(MBEDTLS_SSL_PROTO_TLS1_2)\n        if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )\n        {\n            unsigned char mac[MBEDTLS_SSL_MAC_ADD];\n\n            mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_ctr, 8 );\n            mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_hdr, 3 );\n            mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_len, 2 );\n            mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,\n                             ssl->out_msg, ssl->out_msglen );\n            mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc, mac );\n            mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );\n\n            memcpy( ssl->out_msg + ssl->out_msglen, mac, ssl->transform_out->maclen );\n        }\n        else\n#endif\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n        MBEDTLS_SSL_DEBUG_BUF( 4, \"computed mac\",\n                       ssl->out_msg + ssl->out_msglen,\n                       ssl->transform_out->maclen );\n\n        ssl->out_msglen += ssl->transform_out->maclen;\n        auth_done++;\n    }\n#endif /* AEAD not the only option */\n\n    /*\n     * Encrypt\n     */\n#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)\n    if( mode == MBEDTLS_MODE_STREAM )\n    {\n        int ret;\n        size_t olen = 0;\n\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"before encrypt: msglen = %d, \"\n                            \"including %d bytes of padding\",\n                       ssl->out_msglen, 0 ) );\n\n        if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,\n                                   ssl->transform_out->iv_enc,\n                                   ssl->transform_out->ivlen,\n                                   ssl->out_msg, ssl->out_msglen,\n                                   ssl->out_msg, &olen ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_cipher_crypt\", ret );\n            return( ret );\n        }\n\n        if( ssl->out_msglen != olen )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n    }\n    else\n#endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */\n#if defined(MBEDTLS_GCM_C) || \\\n    defined(MBEDTLS_CCM_C) || \\\n    defined(MBEDTLS_CHACHAPOLY_C)\n    if( mode == MBEDTLS_MODE_GCM ||\n        mode == MBEDTLS_MODE_CCM ||\n        mode == MBEDTLS_MODE_CHACHAPOLY )\n    {\n        int ret;\n        size_t enc_msglen, olen;\n        unsigned char *enc_msg;\n        unsigned char add_data[13];\n        unsigned char iv[12];\n        mbedtls_ssl_transform *transform = ssl->transform_out;\n        unsigned char taglen = transform->ciphersuite_info->flags &\n                               MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;\n        size_t explicit_ivlen = transform->ivlen - transform->fixed_ivlen;\n\n        /*\n         * Prepare additional authenticated data\n         */\n        memcpy( add_data, ssl->out_ctr, 8 );\n        add_data[8]  = ssl->out_msgtype;\n        mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,\n                           ssl->conf->transport, add_data + 9 );\n        add_data[11] = ( ssl->out_msglen >> 8 ) & 0xFF;\n        add_data[12] = ssl->out_msglen & 0xFF;\n\n        MBEDTLS_SSL_DEBUG_BUF( 4, \"additional data for AEAD\", add_data, 13 );\n\n        /*\n         * Generate IV\n         */\n        if( transform->ivlen == 12 && transform->fixed_ivlen == 4 )\n        {\n            /* GCM and CCM: fixed || explicit (=seqnum) */\n            memcpy( iv, transform->iv_enc, transform->fixed_ivlen );\n            memcpy( iv + transform->fixed_ivlen, ssl->out_ctr, 8 );\n            memcpy( ssl->out_iv, ssl->out_ctr, 8 );\n\n        }\n        else if( transform->ivlen == 12 && transform->fixed_ivlen == 12 )\n        {\n            /* ChachaPoly: fixed XOR sequence number */\n            unsigned char i;\n\n            memcpy( iv, transform->iv_enc, transform->fixed_ivlen );\n\n            for( i = 0; i < 8; i++ )\n                iv[i+4] ^= ssl->out_ctr[i];\n        }\n        else\n        {\n            /* Reminder if we ever add an AEAD mode with a different size */\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n        MBEDTLS_SSL_DEBUG_BUF( 4, \"IV used (internal)\",\n                                  iv, transform->ivlen );\n        MBEDTLS_SSL_DEBUG_BUF( 4, \"IV used (transmitted)\",\n                                  ssl->out_iv, explicit_ivlen );\n\n        /*\n         * Fix message length with added IV\n         */\n        enc_msg = ssl->out_msg;\n        enc_msglen = ssl->out_msglen;\n        ssl->out_msglen += explicit_ivlen;\n\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"before encrypt: msglen = %d, \"\n                                    \"including 0 bytes of padding\",\n                                    ssl->out_msglen ) );\n\n        /*\n         * Encrypt and authenticate\n         */\n        if( ( ret = mbedtls_cipher_auth_encrypt( &transform->cipher_ctx_enc,\n                                         iv, transform->ivlen,\n                                         add_data, 13,\n                                         enc_msg, enc_msglen,\n                                         enc_msg, &olen,\n                                         enc_msg + enc_msglen, taglen ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_cipher_auth_encrypt\", ret );\n            return( ret );\n        }\n\n        if( olen != enc_msglen )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n        ssl->out_msglen += taglen;\n        auth_done++;\n\n        MBEDTLS_SSL_DEBUG_BUF( 4, \"after encrypt: tag\", enc_msg + enc_msglen, taglen );\n    }\n    else\n#endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */\n#if defined(MBEDTLS_CIPHER_MODE_CBC) &&                                    \\\n    ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C) )\n    if( mode == MBEDTLS_MODE_CBC )\n    {\n        int ret;\n        unsigned char *enc_msg;\n        size_t enc_msglen, padlen, olen = 0, i;\n\n        padlen = ssl->transform_out->ivlen - ( ssl->out_msglen + 1 ) %\n                 ssl->transform_out->ivlen;\n        if( padlen == ssl->transform_out->ivlen )\n            padlen = 0;\n\n        for( i = 0; i <= padlen; i++ )\n            ssl->out_msg[ssl->out_msglen + i] = (unsigned char) padlen;\n\n        ssl->out_msglen += padlen + 1;\n\n        enc_msglen = ssl->out_msglen;\n        enc_msg = ssl->out_msg;\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)\n        /*\n         * Prepend per-record IV for block cipher in TLS v1.1 and up as per\n         * Method 1 (6.2.3.2. in RFC4346 and RFC5246)\n         */\n        if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )\n        {\n            /*\n             * Generate IV\n             */\n            ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->transform_out->iv_enc,\n                                  ssl->transform_out->ivlen );\n            if( ret != 0 )\n                return( ret );\n\n            memcpy( ssl->out_iv, ssl->transform_out->iv_enc,\n                    ssl->transform_out->ivlen );\n\n            /*\n             * Fix pointer positions and message length with added IV\n             */\n            enc_msg = ssl->out_msg;\n            enc_msglen = ssl->out_msglen;\n            ssl->out_msglen += ssl->transform_out->ivlen;\n        }\n#endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */\n\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"before encrypt: msglen = %d, \"\n                            \"including %d bytes of IV and %d bytes of padding\",\n                            ssl->out_msglen, ssl->transform_out->ivlen,\n                            padlen + 1 ) );\n\n        if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,\n                                   ssl->transform_out->iv_enc,\n                                   ssl->transform_out->ivlen,\n                                   enc_msg, enc_msglen,\n                                   enc_msg, &olen ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_cipher_crypt\", ret );\n            return( ret );\n        }\n\n        if( enc_msglen != olen )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)\n        if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )\n        {\n            /*\n             * Save IV in SSL3 and TLS1\n             */\n            memcpy( ssl->transform_out->iv_enc,\n                    ssl->transform_out->cipher_ctx_enc.iv,\n                    ssl->transform_out->ivlen );\n        }\n#endif\n\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\n        if( auth_done == 0 )\n        {\n            /*\n             * MAC(MAC_write_key, seq_num +\n             *     TLSCipherText.type +\n             *     TLSCipherText.version +\n             *     length_of( (IV +) ENC(...) ) +\n             *     IV + // except for TLS 1.0\n             *     ENC(content + padding + padding_length));\n             */\n            unsigned char pseudo_hdr[13];\n\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"using encrypt then mac\" ) );\n\n            memcpy( pseudo_hdr +  0, ssl->out_ctr, 8 );\n            memcpy( pseudo_hdr +  8, ssl->out_hdr, 3 );\n            pseudo_hdr[11] = (unsigned char)( ( ssl->out_msglen >> 8 ) & 0xFF );\n            pseudo_hdr[12] = (unsigned char)( ( ssl->out_msglen      ) & 0xFF );\n\n            MBEDTLS_SSL_DEBUG_BUF( 4, \"MAC'd meta-data\", pseudo_hdr, 13 );\n\n            mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, pseudo_hdr, 13 );\n            mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,\n                             ssl->out_iv, ssl->out_msglen );\n            mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc,\n                             ssl->out_iv + ssl->out_msglen );\n            mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );\n\n            ssl->out_msglen += ssl->transform_out->maclen;\n            auth_done++;\n        }\n#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */\n    }\n    else\n#endif /* MBEDTLS_CIPHER_MODE_CBC &&\n          ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C || MBEDTLS_ARIA_C ) */\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    /* Make extra sure authentication was performed, exactly once */\n    if( auth_done != 1 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= encrypt buf\" ) );\n\n    return( 0 );\n}\n\nstatic int ssl_decrypt_buf( mbedtls_ssl_context *ssl )\n{\n    mbedtls_cipher_mode_t mode;\n    int auth_done = 0;\n#if defined(SSL_SOME_MODES_USE_MAC)\n    size_t padlen = 0, correct = 1;\n#endif\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> decrypt buf\" ) );\n\n    if( ssl->session_in == NULL || ssl->transform_in == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_in->cipher_ctx_dec );\n\n    if( ssl->in_msglen < ssl->transform_in->minlen )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"in_msglen (%d) < minlen (%d)\",\n                       ssl->in_msglen, ssl->transform_in->minlen ) );\n        return( MBEDTLS_ERR_SSL_INVALID_MAC );\n    }\n\n#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)\n    if( mode == MBEDTLS_MODE_STREAM )\n    {\n        int ret;\n        size_t olen = 0;\n\n        padlen = 0;\n\n        if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,\n                                   ssl->transform_in->iv_dec,\n                                   ssl->transform_in->ivlen,\n                                   ssl->in_msg, ssl->in_msglen,\n                                   ssl->in_msg, &olen ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_cipher_crypt\", ret );\n            return( ret );\n        }\n\n        if( ssl->in_msglen != olen )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n    }\n    else\n#endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */\n#if defined(MBEDTLS_GCM_C) || \\\n    defined(MBEDTLS_CCM_C) || \\\n    defined(MBEDTLS_CHACHAPOLY_C)\n    if( mode == MBEDTLS_MODE_GCM ||\n        mode == MBEDTLS_MODE_CCM ||\n        mode == MBEDTLS_MODE_CHACHAPOLY )\n    {\n        int ret;\n        size_t dec_msglen, olen;\n        unsigned char *dec_msg;\n        unsigned char *dec_msg_result;\n        unsigned char add_data[13];\n        unsigned char iv[12];\n        mbedtls_ssl_transform *transform = ssl->transform_in;\n        unsigned char taglen = transform->ciphersuite_info->flags &\n                               MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;\n        size_t explicit_iv_len = transform->ivlen - transform->fixed_ivlen;\n\n        /*\n         * Compute and update sizes\n         */\n        if( ssl->in_msglen < explicit_iv_len + taglen )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"msglen (%d) < explicit_iv_len (%d) \"\n                                \"+ taglen (%d)\", ssl->in_msglen,\n                                explicit_iv_len, taglen ) );\n            return( MBEDTLS_ERR_SSL_INVALID_MAC );\n        }\n        dec_msglen = ssl->in_msglen - explicit_iv_len - taglen;\n\n        dec_msg = ssl->in_msg;\n        dec_msg_result = ssl->in_msg;\n        ssl->in_msglen = dec_msglen;\n\n        /*\n         * Prepare additional authenticated data\n         */\n        memcpy( add_data, ssl->in_ctr, 8 );\n        add_data[8]  = ssl->in_msgtype;\n        mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,\n                           ssl->conf->transport, add_data + 9 );\n        add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF;\n        add_data[12] = ssl->in_msglen & 0xFF;\n\n        MBEDTLS_SSL_DEBUG_BUF( 4, \"additional data for AEAD\", add_data, 13 );\n\n        /*\n         * Prepare IV\n         */\n        if( transform->ivlen == 12 && transform->fixed_ivlen == 4 )\n        {\n            /* GCM and CCM: fixed || explicit (transmitted) */\n            memcpy( iv, transform->iv_dec, transform->fixed_ivlen );\n            memcpy( iv + transform->fixed_ivlen, ssl->in_iv, 8 );\n\n        }\n        else if( transform->ivlen == 12 && transform->fixed_ivlen == 12 )\n        {\n            /* ChachaPoly: fixed XOR sequence number */\n            unsigned char i;\n\n            memcpy( iv, transform->iv_dec, transform->fixed_ivlen );\n\n            for( i = 0; i < 8; i++ )\n                iv[i+4] ^= ssl->in_ctr[i];\n        }\n        else\n        {\n            /* Reminder if we ever add an AEAD mode with a different size */\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n        MBEDTLS_SSL_DEBUG_BUF( 4, \"IV used\", iv, transform->ivlen );\n        MBEDTLS_SSL_DEBUG_BUF( 4, \"TAG used\", dec_msg + dec_msglen, taglen );\n\n        /*\n         * Decrypt and authenticate\n         */\n        if( ( ret = mbedtls_cipher_auth_decrypt( &ssl->transform_in->cipher_ctx_dec,\n                                         iv, transform->ivlen,\n                                         add_data, 13,\n                                         dec_msg, dec_msglen,\n                                         dec_msg_result, &olen,\n                                         dec_msg + dec_msglen, taglen ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_cipher_auth_decrypt\", ret );\n\n            if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED )\n                return( MBEDTLS_ERR_SSL_INVALID_MAC );\n\n            return( ret );\n        }\n        auth_done++;\n\n        if( olen != dec_msglen )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n    }\n    else\n#endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */\n#if defined(MBEDTLS_CIPHER_MODE_CBC) &&                                    \\\n    ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C) )\n    if( mode == MBEDTLS_MODE_CBC )\n    {\n        /*\n         * Decrypt and check the padding\n         */\n        int ret;\n        unsigned char *dec_msg;\n        unsigned char *dec_msg_result;\n        size_t dec_msglen;\n        size_t minlen = 0;\n        size_t olen = 0;\n\n        /*\n         * Check immediate ciphertext sanity\n         */\n#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)\n        if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )\n            minlen += ssl->transform_in->ivlen;\n#endif\n\n        if( ssl->in_msglen < minlen + ssl->transform_in->ivlen ||\n            ssl->in_msglen < minlen + ssl->transform_in->maclen + 1 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"msglen (%d) < max( ivlen(%d), maclen (%d) \"\n                                \"+ 1 ) ( + expl IV )\", ssl->in_msglen,\n                                ssl->transform_in->ivlen,\n                                ssl->transform_in->maclen ) );\n            return( MBEDTLS_ERR_SSL_INVALID_MAC );\n        }\n\n        dec_msglen = ssl->in_msglen;\n        dec_msg = ssl->in_msg;\n        dec_msg_result = ssl->in_msg;\n\n        /*\n         * Authenticate before decrypt if enabled\n         */\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\n        if( ssl->session_in->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )\n        {\n            unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];\n            unsigned char pseudo_hdr[13];\n\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"using encrypt then mac\" ) );\n\n            dec_msglen -= ssl->transform_in->maclen;\n            ssl->in_msglen -= ssl->transform_in->maclen;\n\n            memcpy( pseudo_hdr +  0, ssl->in_ctr, 8 );\n            memcpy( pseudo_hdr +  8, ssl->in_hdr, 3 );\n            pseudo_hdr[11] = (unsigned char)( ( ssl->in_msglen >> 8 ) & 0xFF );\n            pseudo_hdr[12] = (unsigned char)( ( ssl->in_msglen      ) & 0xFF );\n\n            MBEDTLS_SSL_DEBUG_BUF( 4, \"MAC'd meta-data\", pseudo_hdr, 13 );\n\n            mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, pseudo_hdr, 13 );\n            mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec,\n                             ssl->in_iv, ssl->in_msglen );\n            mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, mac_expect );\n            mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );\n\n            MBEDTLS_SSL_DEBUG_BUF( 4, \"message  mac\", ssl->in_iv + ssl->in_msglen,\n                                              ssl->transform_in->maclen );\n            MBEDTLS_SSL_DEBUG_BUF( 4, \"expected mac\", mac_expect,\n                                              ssl->transform_in->maclen );\n\n            if( mbedtls_ssl_safer_memcmp( ssl->in_iv + ssl->in_msglen, mac_expect,\n                                          ssl->transform_in->maclen ) != 0 )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"message mac does not match\" ) );\n\n                return( MBEDTLS_ERR_SSL_INVALID_MAC );\n            }\n            auth_done++;\n        }\n#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */\n\n        /*\n         * Check length sanity\n         */\n        if( ssl->in_msglen % ssl->transform_in->ivlen != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"msglen (%d) %% ivlen (%d) != 0\",\n                           ssl->in_msglen, ssl->transform_in->ivlen ) );\n            return( MBEDTLS_ERR_SSL_INVALID_MAC );\n        }\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)\n        /*\n         * Initialize for prepended IV for block cipher in TLS v1.1 and up\n         */\n        if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )\n        {\n            unsigned char i;\n            dec_msglen -= ssl->transform_in->ivlen;\n            ssl->in_msglen -= ssl->transform_in->ivlen;\n\n            for( i = 0; i < ssl->transform_in->ivlen; i++ )\n                ssl->transform_in->iv_dec[i] = ssl->in_iv[i];\n        }\n#endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */\n\n        if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,\n                                   ssl->transform_in->iv_dec,\n                                   ssl->transform_in->ivlen,\n                                   dec_msg, dec_msglen,\n                                   dec_msg_result, &olen ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_cipher_crypt\", ret );\n            return( ret );\n        }\n\n        if( dec_msglen != olen )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)\n        if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )\n        {\n            /*\n             * Save IV in SSL3 and TLS1\n             */\n            memcpy( ssl->transform_in->iv_dec,\n                    ssl->transform_in->cipher_ctx_dec.iv,\n                    ssl->transform_in->ivlen );\n        }\n#endif\n\n        padlen = 1 + ssl->in_msg[ssl->in_msglen - 1];\n\n        if( ssl->in_msglen < ssl->transform_in->maclen + padlen &&\n            auth_done == 0 )\n        {\n#if defined(MBEDTLS_SSL_DEBUG_ALL)\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"msglen (%d) < maclen (%d) + padlen (%d)\",\n                        ssl->in_msglen, ssl->transform_in->maclen, padlen ) );\n#endif\n            padlen = 0;\n            correct = 0;\n        }\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n        if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )\n        {\n            if( padlen > ssl->transform_in->ivlen )\n            {\n#if defined(MBEDTLS_SSL_DEBUG_ALL)\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad padding length: is %d, \"\n                                    \"should be no more than %d\",\n                               padlen, ssl->transform_in->ivlen ) );\n#endif\n                correct = 0;\n            }\n        }\n        else\n#endif /* MBEDTLS_SSL_PROTO_SSL3 */\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_2)\n        if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )\n        {\n            /*\n             * TLSv1+: always check the padding up to the first failure\n             * and fake check up to 256 bytes of padding\n             */\n            size_t pad_count = 0, real_count = 1;\n            size_t padding_idx = ssl->in_msglen - padlen;\n            size_t i;\n\n            /*\n             * Padding is guaranteed to be incorrect if:\n             *   1. padlen > ssl->in_msglen\n             *\n             *   2. padding_idx > MBEDTLS_SSL_IN_CONTENT_LEN +\n             *                     ssl->transform_in->maclen\n             *\n             * In both cases we reset padding_idx to a safe value (0) to\n             * prevent out-of-buffer reads.\n             */\n            correct &= ( padlen <= ssl->in_msglen );\n            correct &= ( padding_idx <= MBEDTLS_SSL_IN_CONTENT_LEN +\n                                       ssl->transform_in->maclen );\n\n            padding_idx *= correct;\n\n            for( i = 0; i < 256; i++ )\n            {\n                real_count &= ( i < padlen );\n                pad_count += real_count *\n                             ( ssl->in_msg[padding_idx + i] == padlen - 1 );\n            }\n\n            correct &= ( pad_count == padlen ); /* Only 1 on correct padding */\n\n#if defined(MBEDTLS_SSL_DEBUG_ALL)\n            if( padlen > 0 && correct == 0 )\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad padding byte detected\" ) );\n#endif\n            padlen &= correct * 0x1FF;\n        }\n        else\n#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \\\n          MBEDTLS_SSL_PROTO_TLS1_2 */\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n        ssl->in_msglen -= padlen;\n    }\n    else\n#endif /* MBEDTLS_CIPHER_MODE_CBC &&\n          ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C || MBEDTLS_ARIA_C ) */\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n#if defined(MBEDTLS_SSL_DEBUG_ALL)\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"raw buffer after decryption\",\n                   ssl->in_msg, ssl->in_msglen );\n#endif\n\n    /*\n     * Authenticate if not done yet.\n     * Compute the MAC regardless of the padding result (RFC4346, CBCTIME).\n     */\n#if defined(SSL_SOME_MODES_USE_MAC)\n    if( auth_done == 0 )\n    {\n        unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];\n\n        ssl->in_msglen -= ssl->transform_in->maclen;\n\n        ssl->in_len[0] = (unsigned char)( ssl->in_msglen >> 8 );\n        ssl->in_len[1] = (unsigned char)( ssl->in_msglen      );\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n        if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )\n        {\n            ssl_mac( &ssl->transform_in->md_ctx_dec,\n                      ssl->transform_in->mac_dec,\n                      ssl->in_msg, ssl->in_msglen,\n                      ssl->in_ctr, ssl->in_msgtype,\n                      mac_expect );\n        }\n        else\n#endif /* MBEDTLS_SSL_PROTO_SSL3 */\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \\\n        defined(MBEDTLS_SSL_PROTO_TLS1_2)\n        if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )\n        {\n            /*\n             * Process MAC and always update for padlen afterwards to make\n             * total time independent of padlen.\n             *\n             * Known timing attacks:\n             *  - Lucky Thirteen (http://www.isg.rhul.ac.uk/tls/TLStiming.pdf)\n             *\n             * To compensate for different timings for the MAC calculation\n             * depending on how much padding was removed (which is determined\n             * by padlen), process extra_run more blocks through the hash\n             * function.\n             *\n             * The formula in the paper is\n             *   extra_run = ceil( (L1-55) / 64 ) - ceil( (L2-55) / 64 )\n             * where L1 is the size of the header plus the decrypted message\n             * plus CBC padding and L2 is the size of the header plus the\n             * decrypted message. This is for an underlying hash function\n             * with 64-byte blocks.\n             * We use ( (Lx+8) / 64 ) to handle 'negative Lx' values\n             * correctly. We round down instead of up, so -56 is the correct\n             * value for our calculations instead of -55.\n             *\n             * Repeat the formula rather than defining a block_size variable.\n             * This avoids requiring division by a variable at runtime\n             * (which would be marginally less efficient and would require\n             * linking an extra division function in some builds).\n             */\n            size_t j, extra_run = 0;\n\n            /*\n             * The next two sizes are the minimum and maximum values of\n             * in_msglen over all padlen values.\n             *\n             * They're independent of padlen, since we previously did\n             * in_msglen -= padlen.\n             *\n             * Note that max_len + maclen is never more than the buffer\n             * length, as we previously did in_msglen -= maclen too.\n             */\n            const size_t max_len = ssl->in_msglen + padlen;\n            const size_t min_len = ( max_len > 256 ) ? max_len - 256 : 0;\n\n            switch( ssl->transform_in->ciphersuite_info->mac )\n            {\n#if defined(MBEDTLS_MD5_C) || defined(MBEDTLS_SHA1_C) || \\\n    defined(MBEDTLS_SHA256_C)\n                case MBEDTLS_MD_MD5:\n                case MBEDTLS_MD_SHA1:\n                case MBEDTLS_MD_SHA256:\n                    /* 8 bytes of message size, 64-byte compression blocks */\n                    extra_run = ( 13 + ssl->in_msglen + padlen + 8 ) / 64 -\n                                ( 13 + ssl->in_msglen          + 8 ) / 64;\n                    break;\n#endif\n#if defined(MBEDTLS_SHA512_C)\n                case MBEDTLS_MD_SHA384:\n                    /* 16 bytes of message size, 128-byte compression blocks */\n                    extra_run = ( 13 + ssl->in_msglen + padlen + 16 ) / 128 -\n                                ( 13 + ssl->in_msglen          + 16 ) / 128;\n                    break;\n#endif\n                default:\n                    MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n                    return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n            }\n\n            extra_run &= correct * 0xFF;\n\n            mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_ctr, 8 );\n            mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_hdr, 3 );\n            mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_len, 2 );\n            mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_msg,\n                             ssl->in_msglen );\n            /* Make sure we access everything even when padlen > 0. This\n             * makes the synchronisation requirements for just-in-time\n             * Prime+Probe attacks much tighter and hopefully impractical. */\n            ssl_read_memory( ssl->in_msg + ssl->in_msglen, padlen );\n            mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, mac_expect );\n\n            /* Call mbedtls_md_process at least once due to cache attacks\n             * that observe whether md_process() was called of not */\n            for( j = 0; j < extra_run + 1; j++ )\n                mbedtls_md_process( &ssl->transform_in->md_ctx_dec, ssl->in_msg );\n\n            mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );\n\n            /* Make sure we access all the memory that could contain the MAC,\n             * before we check it in the next code block. This makes the\n             * synchronisation requirements for just-in-time Prime+Probe\n             * attacks much tighter and hopefully impractical. */\n            ssl_read_memory( ssl->in_msg + min_len,\n                                 max_len - min_len + ssl->transform_in->maclen );\n        }\n        else\n#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \\\n              MBEDTLS_SSL_PROTO_TLS1_2 */\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n#if defined(MBEDTLS_SSL_DEBUG_ALL)\n        MBEDTLS_SSL_DEBUG_BUF( 4, \"expected mac\", mac_expect, ssl->transform_in->maclen );\n        MBEDTLS_SSL_DEBUG_BUF( 4, \"message  mac\", ssl->in_msg + ssl->in_msglen,\n                               ssl->transform_in->maclen );\n#endif\n\n        if( mbedtls_ssl_safer_memcmp( ssl->in_msg + ssl->in_msglen, mac_expect,\n                                      ssl->transform_in->maclen ) != 0 )\n        {\n#if defined(MBEDTLS_SSL_DEBUG_ALL)\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"message mac does not match\" ) );\n#endif\n            correct = 0;\n        }\n        auth_done++;\n\n        /*\n         * Finally check the correct flag\n         */\n        if( correct == 0 )\n            return( MBEDTLS_ERR_SSL_INVALID_MAC );\n    }\n#endif /* SSL_SOME_MODES_USE_MAC */\n\n    /* Make extra sure authentication was performed, exactly once */\n    if( auth_done != 1 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    if( ssl->in_msglen == 0 )\n    {\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n        if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3\n            && ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )\n        {\n            /* TLS v1.2 explicitly disallows zero-length messages which are not application data */\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"invalid zero-length message type: %d\", ssl->in_msgtype ) );\n            return( MBEDTLS_ERR_SSL_INVALID_RECORD );\n        }\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n\n        ssl->nb_zero++;\n\n        /*\n         * Three or more empty messages may be a DoS attack\n         * (excessive CPU consumption).\n         */\n        if( ssl->nb_zero > 3 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"received four consecutive empty \"\n                                \"messages, possible DoS attack\" ) );\n            return( MBEDTLS_ERR_SSL_INVALID_MAC );\n        }\n    }\n    else\n        ssl->nb_zero = 0;\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        ; /* in_ctr read from peer, not maintained internally */\n    }\n    else\n#endif\n    {\n        unsigned char i;\n        for( i = 8; i > ssl_ep_len( ssl ); i-- )\n            if( ++ssl->in_ctr[i - 1] != 0 )\n                break;\n\n        /* The loop goes to its end iff the counter is wrapping */\n        if( i == ssl_ep_len( ssl ) )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"incoming message counter would wrap\" ) );\n            return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );\n        }\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= decrypt buf\" ) );\n\n    return( 0 );\n}\n\n#undef MAC_NONE\n#undef MAC_PLAINTEXT\n#undef MAC_CIPHERTEXT\n\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n/*\n * Compression/decompression functions\n */\nstatic int ssl_compress_buf( mbedtls_ssl_context *ssl )\n{\n    int ret;\n    unsigned char *msg_post = ssl->out_msg;\n    ptrdiff_t bytes_written = ssl->out_msg - ssl->out_buf;\n    size_t len_pre = ssl->out_msglen;\n    unsigned char *msg_pre = ssl->compress_buf;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> compress buf\" ) );\n\n    if( len_pre == 0 )\n        return( 0 );\n\n    memcpy( msg_pre, ssl->out_msg, len_pre );\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"before compression: msglen = %d, \",\n                   ssl->out_msglen ) );\n\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"before compression: output payload\",\n                   ssl->out_msg, ssl->out_msglen );\n\n    ssl->transform_out->ctx_deflate.next_in = msg_pre;\n    ssl->transform_out->ctx_deflate.avail_in = len_pre;\n    ssl->transform_out->ctx_deflate.next_out = msg_post;\n    ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_OUT_BUFFER_LEN - bytes_written;\n\n    ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH );\n    if( ret != Z_OK )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"failed to perform compression (%d)\", ret ) );\n        return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );\n    }\n\n    ssl->out_msglen = MBEDTLS_SSL_OUT_BUFFER_LEN -\n                      ssl->transform_out->ctx_deflate.avail_out - bytes_written;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"after compression: msglen = %d, \",\n                   ssl->out_msglen ) );\n\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"after compression: output payload\",\n                   ssl->out_msg, ssl->out_msglen );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= compress buf\" ) );\n\n    return( 0 );\n}\n\nstatic int ssl_decompress_buf( mbedtls_ssl_context *ssl )\n{\n    int ret;\n    unsigned char *msg_post = ssl->in_msg;\n    ptrdiff_t header_bytes = ssl->in_msg - ssl->in_buf;\n    size_t len_pre = ssl->in_msglen;\n    unsigned char *msg_pre = ssl->compress_buf;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> decompress buf\" ) );\n\n    if( len_pre == 0 )\n        return( 0 );\n\n    memcpy( msg_pre, ssl->in_msg, len_pre );\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"before decompression: msglen = %d, \",\n                   ssl->in_msglen ) );\n\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"before decompression: input payload\",\n                   ssl->in_msg, ssl->in_msglen );\n\n    ssl->transform_in->ctx_inflate.next_in = msg_pre;\n    ssl->transform_in->ctx_inflate.avail_in = len_pre;\n    ssl->transform_in->ctx_inflate.next_out = msg_post;\n    ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_IN_BUFFER_LEN -\n                                               header_bytes;\n\n    ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH );\n    if( ret != Z_OK )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"failed to perform decompression (%d)\", ret ) );\n        return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );\n    }\n\n    ssl->in_msglen = MBEDTLS_SSL_IN_BUFFER_LEN -\n                     ssl->transform_in->ctx_inflate.avail_out - header_bytes;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"after decompression: msglen = %d, \",\n                   ssl->in_msglen ) );\n\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"after decompression: input payload\",\n                   ssl->in_msg, ssl->in_msglen );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= decompress buf\" ) );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_ZLIB_SUPPORT */\n\n#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)\nstatic int ssl_write_hello_request( mbedtls_ssl_context *ssl );\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\nstatic int ssl_resend_hello_request( mbedtls_ssl_context *ssl )\n{\n    /* If renegotiation is not enforced, retransmit until we would reach max\n     * timeout if we were using the usual handshake doubling scheme */\n    if( ssl->conf->renego_max_records < 0 )\n    {\n        uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1;\n        unsigned char doublings = 1;\n\n        while( ratio != 0 )\n        {\n            ++doublings;\n            ratio >>= 1;\n        }\n\n        if( ++ssl->renego_records_seen > doublings )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"no longer retransmitting hello request\" ) );\n            return( 0 );\n        }\n    }\n\n    return( ssl_write_hello_request( ssl ) );\n}\n#endif\n#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */\n\n/*\n * Fill the input message buffer by appending data to it.\n * The amount of data already fetched is in ssl->in_left.\n *\n * If we return 0, is it guaranteed that (at least) nb_want bytes are\n * available (from this read and/or a previous one). Otherwise, an error code\n * is returned (possibly EOF or WANT_READ).\n *\n * With stream transport (TLS) on success ssl->in_left == nb_want, but\n * with datagram transport (DTLS) on success ssl->in_left >= nb_want,\n * since we always read a whole datagram at once.\n *\n * For DTLS, it is up to the caller to set ssl->next_record_offset when\n * they're done reading a record.\n */\nint mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want )\n{\n    int ret;\n    size_t len;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> fetch input\" ) );\n\n    if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"Bad usage of mbedtls_ssl_set_bio() \"\n                            \"or mbedtls_ssl_set_bio()\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n    }\n\n    if( nb_want > MBEDTLS_SSL_IN_BUFFER_LEN - (size_t)( ssl->in_hdr - ssl->in_buf ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"requesting more data than fits\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n    }\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        uint32_t timeout;\n\n        /* Just to be sure */\n        if( ssl->f_set_timer == NULL || ssl->f_get_timer == NULL )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"You must use \"\n                        \"mbedtls_ssl_set_timer_cb() for DTLS\" ) );\n            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n        }\n\n        /*\n         * The point is, we need to always read a full datagram at once, so we\n         * sometimes read more then requested, and handle the additional data.\n         * It could be the rest of the current record (while fetching the\n         * header) and/or some other records in the same datagram.\n         */\n\n        /*\n         * Move to the next record in the already read datagram if applicable\n         */\n        if( ssl->next_record_offset != 0 )\n        {\n            if( ssl->in_left < ssl->next_record_offset )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n                return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n            }\n\n            ssl->in_left -= ssl->next_record_offset;\n\n            if( ssl->in_left != 0 )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 2, ( \"next record in same datagram, offset: %d\",\n                                    ssl->next_record_offset ) );\n                memmove( ssl->in_hdr,\n                         ssl->in_hdr + ssl->next_record_offset,\n                         ssl->in_left );\n            }\n\n            ssl->next_record_offset = 0;\n        }\n\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"in_left: %d, nb_want: %d\",\n                       ssl->in_left, nb_want ) );\n\n        /*\n         * Done if we already have enough data.\n         */\n        if( nb_want <= ssl->in_left)\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= fetch input\" ) );\n            return( 0 );\n        }\n\n        /*\n         * A record can't be split accross datagrams. If we need to read but\n         * are not at the beginning of a new record, the caller did something\n         * wrong.\n         */\n        if( ssl->in_left != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n        /*\n         * Don't even try to read if time's out already.\n         * This avoids by-passing the timer when repeatedly receiving messages\n         * that will end up being dropped.\n         */\n        if( ssl_check_timer( ssl ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"timer has expired\" ) );\n            ret = MBEDTLS_ERR_SSL_TIMEOUT;\n        }\n        else\n        {\n            len = MBEDTLS_SSL_IN_BUFFER_LEN - ( ssl->in_hdr - ssl->in_buf );\n\n            if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )\n                timeout = ssl->handshake->retransmit_timeout;\n            else\n                timeout = ssl->conf->read_timeout;\n\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"f_recv_timeout: %u ms\", timeout ) );\n\n            if( ssl->f_recv_timeout != NULL )\n                ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len,\n                                                                    timeout );\n            else\n                ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len );\n\n            MBEDTLS_SSL_DEBUG_RET( 2, \"ssl->f_recv(_timeout)\", ret );\n\n            if( ret == 0 )\n                return( MBEDTLS_ERR_SSL_CONN_EOF );\n        }\n\n        if( ret == MBEDTLS_ERR_SSL_TIMEOUT )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"timeout\" ) );\n            ssl_set_timer( ssl, 0 );\n\n            if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )\n            {\n                if( ssl_double_retransmit_timeout( ssl ) != 0 )\n                {\n                    MBEDTLS_SSL_DEBUG_MSG( 1, ( \"handshake timeout\" ) );\n                    return( MBEDTLS_ERR_SSL_TIMEOUT );\n                }\n\n                if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )\n                {\n                    MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_resend\", ret );\n                    return( ret );\n                }\n\n                return( MBEDTLS_ERR_SSL_WANT_READ );\n            }\n#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)\n            else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&\n                     ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )\n            {\n                if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )\n                {\n                    MBEDTLS_SSL_DEBUG_RET( 1, \"ssl_resend_hello_request\", ret );\n                    return( ret );\n                }\n\n                return( MBEDTLS_ERR_SSL_WANT_READ );\n            }\n#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */\n        }\n\n        if( ret < 0 )\n            return( ret );\n\n        ssl->in_left = ret;\n    }\n    else\n#endif\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"in_left: %d, nb_want: %d\",\n                       ssl->in_left, nb_want ) );\n\n        while( ssl->in_left < nb_want )\n        {\n            len = nb_want - ssl->in_left;\n\n            if( ssl_check_timer( ssl ) != 0 )\n                ret = MBEDTLS_ERR_SSL_TIMEOUT;\n            else\n            {\n                if( ssl->f_recv_timeout != NULL )\n                {\n                    ret = ssl->f_recv_timeout( ssl->p_bio,\n                                               ssl->in_hdr + ssl->in_left, len,\n                                               ssl->conf->read_timeout );\n                }\n                else\n                {\n                    ret = ssl->f_recv( ssl->p_bio,\n                                       ssl->in_hdr + ssl->in_left, len );\n                }\n            }\n\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"in_left: %d, nb_want: %d\",\n                                        ssl->in_left, nb_want ) );\n            MBEDTLS_SSL_DEBUG_RET( 2, \"ssl->f_recv(_timeout)\", ret );\n\n            if( ret == 0 )\n                return( MBEDTLS_ERR_SSL_CONN_EOF );\n\n            if( ret < 0 )\n                return( ret );\n\n            if ( (size_t)ret > len || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1,\n                    ( \"f_recv returned %d bytes but only %lu were requested\",\n                    ret, (unsigned long)len ) );\n                return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n            }\n\n            ssl->in_left += ret;\n        }\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= fetch input\" ) );\n\n    return( 0 );\n}\n\n/*\n * Flush any data not yet written\n */\nint mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl )\n{\n    int ret;\n    unsigned char *buf, i;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> flush output\" ) );\n\n    if( ssl->f_send == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"Bad usage of mbedtls_ssl_set_bio() \"\n                            \"or mbedtls_ssl_set_bio()\" ) );\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n    }\n\n    /* Avoid incrementing counter if data is flushed */\n    if( ssl->out_left == 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= flush output\" ) );\n        return( 0 );\n    }\n\n    while( ssl->out_left > 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"message length: %d, out_left: %d\",\n                       mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) );\n\n        buf = ssl->out_hdr + mbedtls_ssl_hdr_len( ssl ) +\n              ssl->out_msglen - ssl->out_left;\n        ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left );\n\n        MBEDTLS_SSL_DEBUG_RET( 2, \"ssl->f_send\", ret );\n\n        if( ret <= 0 )\n            return( ret );\n\n        if( (size_t)ret > ssl->out_left || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1,\n                ( \"f_send returned %d bytes but only %lu bytes were sent\",\n                ret, (unsigned long)ssl->out_left ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n        ssl->out_left -= ret;\n    }\n\n    for( i = 8; i > ssl_ep_len( ssl ); i-- )\n        if( ++ssl->out_ctr[i - 1] != 0 )\n            break;\n\n    /* The loop goes to its end iff the counter is wrapping */\n    if( i == ssl_ep_len( ssl ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"outgoing message counter would wrap\" ) );\n        return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= flush output\" ) );\n\n    return( 0 );\n}\n\n/*\n * Functions to handle the DTLS retransmission state machine\n */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n/*\n * Append current handshake message to current outgoing flight\n */\nstatic int ssl_flight_append( mbedtls_ssl_context *ssl )\n{\n    mbedtls_ssl_flight_item *msg;\n\n    /* Allocate space for current message */\n    if( ( msg = mbedtls_calloc( 1, sizeof(  mbedtls_ssl_flight_item ) ) ) == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"alloc %d bytes failed\",\n                            sizeof( mbedtls_ssl_flight_item ) ) );\n        return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n    }\n\n    if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"alloc %d bytes failed\", ssl->out_msglen ) );\n        mbedtls_free( msg );\n        return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n    }\n\n    /* Copy current handshake message with headers */\n    memcpy( msg->p, ssl->out_msg, ssl->out_msglen );\n    msg->len = ssl->out_msglen;\n    msg->type = ssl->out_msgtype;\n    msg->next = NULL;\n\n    /* Append to the current flight */\n    if( ssl->handshake->flight == NULL )\n        ssl->handshake->flight = msg;\n    else\n    {\n        mbedtls_ssl_flight_item *cur = ssl->handshake->flight;\n        while( cur->next != NULL )\n            cur = cur->next;\n        cur->next = msg;\n    }\n\n    return( 0 );\n}\n\n/*\n * Free the current flight of handshake messages\n */\nstatic void ssl_flight_free( mbedtls_ssl_flight_item *flight )\n{\n    mbedtls_ssl_flight_item *cur = flight;\n    mbedtls_ssl_flight_item *next;\n\n    while( cur != NULL )\n    {\n        next = cur->next;\n\n        mbedtls_free( cur->p );\n        mbedtls_free( cur );\n\n        cur = next;\n    }\n}\n\n#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)\nstatic void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl );\n#endif\n\n/*\n * Swap transform_out and out_ctr with the alternative ones\n */\nstatic void ssl_swap_epochs( mbedtls_ssl_context *ssl )\n{\n    mbedtls_ssl_transform *tmp_transform;\n    unsigned char tmp_out_ctr[8];\n\n    if( ssl->transform_out == ssl->handshake->alt_transform_out )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"skip swap epochs\" ) );\n        return;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"swap epochs\" ) );\n\n    /* Swap transforms */\n    tmp_transform                     = ssl->transform_out;\n    ssl->transform_out                = ssl->handshake->alt_transform_out;\n    ssl->handshake->alt_transform_out = tmp_transform;\n\n    /* Swap epoch + sequence_number */\n    memcpy( tmp_out_ctr,                 ssl->out_ctr,                8 );\n    memcpy( ssl->out_ctr,                ssl->handshake->alt_out_ctr, 8 );\n    memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr,                 8 );\n\n    /* Adjust to the newly activated transform */\n    if( ssl->transform_out != NULL &&\n        ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )\n    {\n        ssl->out_msg = ssl->out_iv + ssl->transform_out->ivlen -\n                                     ssl->transform_out->fixed_ivlen;\n    }\n    else\n        ssl->out_msg = ssl->out_iv;\n\n#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)\n    if( mbedtls_ssl_hw_record_activate != NULL )\n    {\n        if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_hw_record_activate\", ret );\n            return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );\n        }\n    }\n#endif\n}\n\n/*\n * Retransmit the current flight of messages.\n *\n * Need to remember the current message in case flush_output returns\n * WANT_WRITE, causing us to exit this function and come back later.\n * This function must be called until state is no longer SENDING.\n */\nint mbedtls_ssl_resend( mbedtls_ssl_context *ssl )\n{\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> mbedtls_ssl_resend\" ) );\n\n    if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"initialise resending\" ) );\n\n        ssl->handshake->cur_msg = ssl->handshake->flight;\n        ssl_swap_epochs( ssl );\n\n        ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING;\n    }\n\n    while( ssl->handshake->cur_msg != NULL )\n    {\n        int ret;\n        mbedtls_ssl_flight_item *cur = ssl->handshake->cur_msg;\n\n        /* Swap epochs before sending Finished: we can't do it after\n         * sending ChangeCipherSpec, in case write returns WANT_READ.\n         * Must be done before copying, may change out_msg pointer */\n        if( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE &&\n            cur->p[0] == MBEDTLS_SSL_HS_FINISHED )\n        {\n            ssl_swap_epochs( ssl );\n        }\n\n        memcpy( ssl->out_msg, cur->p, cur->len );\n        ssl->out_msglen = cur->len;\n        ssl->out_msgtype = cur->type;\n\n        ssl->handshake->cur_msg = cur->next;\n\n        MBEDTLS_SSL_DEBUG_BUF( 3, \"resent handshake message header\", ssl->out_msg, 12 );\n\n        if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_write_record\", ret );\n            return( ret );\n        }\n    }\n\n    if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )\n        ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;\n    else\n    {\n        ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;\n        ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= mbedtls_ssl_resend\" ) );\n\n    return( 0 );\n}\n\n/*\n * To be called when the last message of an incoming flight is received.\n */\nvoid mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl )\n{\n    /* We won't need to resend that one any more */\n    ssl_flight_free( ssl->handshake->flight );\n    ssl->handshake->flight = NULL;\n    ssl->handshake->cur_msg = NULL;\n\n    /* The next incoming flight will start with this msg_seq */\n    ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq;\n\n    /* Cancel timer */\n    ssl_set_timer( ssl, 0 );\n\n    if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&\n        ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )\n    {\n        ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;\n    }\n    else\n        ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;\n}\n\n/*\n * To be called when the last message of an outgoing flight is send.\n */\nvoid mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl )\n{\n    ssl_reset_retransmit_timeout( ssl );\n    ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );\n\n    if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&\n        ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )\n    {\n        ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;\n    }\n    else\n        ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;\n}\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n\n/*\n * Record layer functions\n */\n\n/*\n * Write current record.\n * Uses ssl->out_msgtype, ssl->out_msglen and bytes at ssl->out_msg.\n */\nint mbedtls_ssl_write_record( mbedtls_ssl_context *ssl )\n{\n    int ret, done = 0, out_msg_type;\n    size_t len = ssl->out_msglen;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write record\" ) );\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&\n        ssl->handshake != NULL &&\n        ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )\n    {\n        ; /* Skip special handshake treatment when resending */\n    }\n    else\n#endif\n    if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )\n    {\n        out_msg_type = ssl->out_msg[0];\n\n        if( out_msg_type != MBEDTLS_SSL_HS_HELLO_REQUEST &&\n            ssl->handshake == NULL )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n        ssl->out_msg[1] = (unsigned char)( ( len - 4 ) >> 16 );\n        ssl->out_msg[2] = (unsigned char)( ( len - 4 ) >>  8 );\n        ssl->out_msg[3] = (unsigned char)( ( len - 4 )       );\n\n        /*\n         * DTLS has additional fields in the Handshake layer,\n         * between the length field and the actual payload:\n         *      uint16 message_seq;\n         *      uint24 fragment_offset;\n         *      uint24 fragment_length;\n         */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n        if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n        {\n            /* Make room for the additional DTLS fields */\n            if( MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen < 8 )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"DTLS handshake message too large: \"\n                              \"size %u, maximum %u\",\n                               (unsigned) ( ssl->in_hslen - 4 ),\n                               (unsigned) ( MBEDTLS_SSL_OUT_CONTENT_LEN - 12 ) ) );\n                return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n            }\n\n            memmove( ssl->out_msg + 12, ssl->out_msg + 4, len - 4 );\n            ssl->out_msglen += 8;\n            len += 8;\n\n            /* Write message_seq and update it, except for HelloRequest */\n            if( out_msg_type != MBEDTLS_SSL_HS_HELLO_REQUEST )\n            {\n                ssl->out_msg[4] = ( ssl->handshake->out_msg_seq >> 8 ) & 0xFF;\n                ssl->out_msg[5] = ( ssl->handshake->out_msg_seq      ) & 0xFF;\n                ++( ssl->handshake->out_msg_seq );\n            }\n            else\n            {\n                ssl->out_msg[4] = 0;\n                ssl->out_msg[5] = 0;\n            }\n\n            /* We don't fragment, so frag_offset = 0 and frag_len = len */\n            memset( ssl->out_msg + 6, 0x00, 3 );\n            memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 );\n        }\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n\n        if( out_msg_type != MBEDTLS_SSL_HS_HELLO_REQUEST )\n            ssl->handshake->update_checksum( ssl, ssl->out_msg, len );\n    }\n\n    /* Save handshake and CCS messages for resending */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&\n        ssl->handshake != NULL &&\n        ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING &&\n        ( ssl->out_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ||\n          ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) )\n    {\n        if( ( ret = ssl_flight_append( ssl ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"ssl_flight_append\", ret );\n            return( ret );\n        }\n    }\n#endif\n\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n    if( ssl->transform_out != NULL &&\n        ssl->session_out->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )\n    {\n        if( ( ret = ssl_compress_buf( ssl ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"ssl_compress_buf\", ret );\n            return( ret );\n        }\n\n        len = ssl->out_msglen;\n    }\n#endif /*MBEDTLS_ZLIB_SUPPORT */\n\n#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)\n    if( mbedtls_ssl_hw_record_write != NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"going for mbedtls_ssl_hw_record_write()\" ) );\n\n        ret = mbedtls_ssl_hw_record_write( ssl );\n        if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_hw_record_write\", ret );\n            return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );\n        }\n\n        if( ret == 0 )\n            done = 1;\n    }\n#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */\n    if( !done )\n    {\n        ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;\n        mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,\n                           ssl->conf->transport, ssl->out_hdr + 1 );\n\n        ssl->out_len[0] = (unsigned char)( len >> 8 );\n        ssl->out_len[1] = (unsigned char)( len      );\n\n        if( ssl->transform_out != NULL )\n        {\n            if( ( ret = ssl_encrypt_buf( ssl ) ) != 0 )\n            {\n                MBEDTLS_SSL_DEBUG_RET( 1, \"ssl_encrypt_buf\", ret );\n                return( ret );\n            }\n\n            len = ssl->out_msglen;\n            ssl->out_len[0] = (unsigned char)( len >> 8 );\n            ssl->out_len[1] = (unsigned char)( len      );\n        }\n\n        ssl->out_left = mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen;\n\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"output record: msgtype = %d, \"\n                            \"version = [%d:%d], msglen = %d\",\n                       ssl->out_hdr[0], ssl->out_hdr[1], ssl->out_hdr[2],\n                     ( ssl->out_len[0] << 8 ) | ssl->out_len[1] ) );\n\n        MBEDTLS_SSL_DEBUG_BUF( 4, \"output record sent to network\",\n                       ssl->out_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen );\n    }\n\n    if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_flush_output\", ret );\n        return( ret );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write record\" ) );\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n/*\n * Mark bits in bitmask (used for DTLS HS reassembly)\n */\nstatic void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len )\n{\n    unsigned int start_bits, end_bits;\n\n    start_bits = 8 - ( offset % 8 );\n    if( start_bits != 8 )\n    {\n        size_t first_byte_idx = offset / 8;\n\n        /* Special case */\n        if( len <= start_bits )\n        {\n            for( ; len != 0; len-- )\n                mask[first_byte_idx] |= 1 << ( start_bits - len );\n\n            /* Avoid potential issues with offset or len becoming invalid */\n            return;\n        }\n\n        offset += start_bits; /* Now offset % 8 == 0 */\n        len -= start_bits;\n\n        for( ; start_bits != 0; start_bits-- )\n            mask[first_byte_idx] |= 1 << ( start_bits - 1 );\n    }\n\n    end_bits = len % 8;\n    if( end_bits != 0 )\n    {\n        size_t last_byte_idx = ( offset + len ) / 8;\n\n        len -= end_bits; /* Now len % 8 == 0 */\n\n        for( ; end_bits != 0; end_bits-- )\n            mask[last_byte_idx] |= 1 << ( 8 - end_bits );\n    }\n\n    memset( mask + offset / 8, 0xFF, len / 8 );\n}\n\n/*\n * Check that bitmask is full\n */\nstatic int ssl_bitmask_check( unsigned char *mask, size_t len )\n{\n    size_t i;\n\n    for( i = 0; i < len / 8; i++ )\n        if( mask[i] != 0xFF )\n            return( -1 );\n\n    for( i = 0; i < len % 8; i++ )\n        if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 )\n            return( -1 );\n\n    return( 0 );\n}\n\n/*\n * Reassemble fragmented DTLS handshake messages.\n *\n * Use a temporary buffer for reassembly, divided in two parts:\n * - the first holds the reassembled message (including handshake header),\n * - the second holds a bitmask indicating which parts of the message\n *   (excluding headers) have been received so far.\n */\nstatic int ssl_reassemble_dtls_handshake( mbedtls_ssl_context *ssl )\n{\n    unsigned char *msg, *bitmask;\n    size_t frag_len, frag_off;\n    size_t msg_len = ssl->in_hslen - 12; /* Without headers */\n\n    if( ssl->handshake == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"not supported outside handshake (for now)\" ) );\n        return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );\n    }\n\n    /*\n     * For first fragment, check size and allocate buffer\n     */\n    if( ssl->handshake->hs_msg == NULL )\n    {\n        size_t alloc_len;\n\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"initialize reassembly, total length = %d\",\n                            msg_len ) );\n\n        if( ssl->in_hslen > MBEDTLS_SSL_IN_CONTENT_LEN )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"handshake message too large\" ) );\n            return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );\n        }\n\n        /* The bitmask needs one bit per byte of message excluding header */\n        alloc_len = 12 + msg_len + msg_len / 8 + ( msg_len % 8 != 0 );\n\n        ssl->handshake->hs_msg = mbedtls_calloc( 1, alloc_len );\n        if( ssl->handshake->hs_msg == NULL )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"alloc failed (%d bytes)\", alloc_len ) );\n            return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n        }\n\n        /* Prepare final header: copy msg_type, length and message_seq,\n         * then add standardised fragment_offset and fragment_length */\n        memcpy( ssl->handshake->hs_msg, ssl->in_msg, 6 );\n        memset( ssl->handshake->hs_msg + 6, 0, 3 );\n        memcpy( ssl->handshake->hs_msg + 9,\n                ssl->handshake->hs_msg + 1, 3 );\n    }\n    else\n    {\n        /* Make sure msg_type and length are consistent */\n        if( memcmp( ssl->handshake->hs_msg, ssl->in_msg, 4 ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"fragment header mismatch\" ) );\n            return( MBEDTLS_ERR_SSL_INVALID_RECORD );\n        }\n    }\n\n    msg = ssl->handshake->hs_msg + 12;\n    bitmask = msg + msg_len;\n\n    /*\n     * Check and copy current fragment\n     */\n    frag_off = ( ssl->in_msg[6]  << 16 ) |\n               ( ssl->in_msg[7]  << 8  ) |\n                 ssl->in_msg[8];\n    frag_len = ( ssl->in_msg[9]  << 16 ) |\n               ( ssl->in_msg[10] << 8  ) |\n                 ssl->in_msg[11];\n\n    if( frag_off + frag_len > msg_len )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"invalid fragment offset/len: %d + %d > %d\",\n                          frag_off, frag_len, msg_len ) );\n        return( MBEDTLS_ERR_SSL_INVALID_RECORD );\n    }\n\n    if( frag_len + 12 > ssl->in_msglen )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"invalid fragment length: %d + 12 > %d\",\n                          frag_len, ssl->in_msglen ) );\n        return( MBEDTLS_ERR_SSL_INVALID_RECORD );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"adding fragment, offset = %d, length = %d\",\n                        frag_off, frag_len ) );\n\n    memcpy( msg + frag_off, ssl->in_msg + 12, frag_len );\n    ssl_bitmask_set( bitmask, frag_off, frag_len );\n\n    /*\n     * Do we have the complete message by now?\n     * If yes, finalize it, else ask to read the next record.\n     */\n    if( ssl_bitmask_check( bitmask, msg_len ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"message is not complete yet\" ) );\n        return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"handshake message completed\" ) );\n\n    if( frag_len + 12 < ssl->in_msglen )\n    {\n        /*\n         * We'got more handshake messages in the same record.\n         * This case is not handled now because no know implementation does\n         * that and it's hard to test, so we prefer to fail cleanly for now.\n         */\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"last fragment not alone in its record\" ) );\n        return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );\n    }\n\n    if( ssl->in_left > ssl->next_record_offset )\n    {\n        /*\n         * We've got more data in the buffer after the current record,\n         * that we don't want to overwrite. Move it before writing the\n         * reassembled message, and adjust in_left and next_record_offset.\n         */\n        unsigned char *cur_remain = ssl->in_hdr + ssl->next_record_offset;\n        unsigned char *new_remain = ssl->in_msg + ssl->in_hslen;\n        size_t remain_len = ssl->in_left - ssl->next_record_offset;\n\n        /* First compute and check new lengths */\n        ssl->next_record_offset = new_remain - ssl->in_hdr;\n        ssl->in_left = ssl->next_record_offset + remain_len;\n\n        if( ssl->in_left > MBEDTLS_SSL_IN_BUFFER_LEN -\n                           (size_t)( ssl->in_hdr - ssl->in_buf ) )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"reassembled message too large for buffer\" ) );\n            return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );\n        }\n\n        memmove( new_remain, cur_remain, remain_len );\n    }\n\n    memcpy( ssl->in_msg, ssl->handshake->hs_msg, ssl->in_hslen );\n\n    mbedtls_free( ssl->handshake->hs_msg );\n    ssl->handshake->hs_msg = NULL;\n\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"reassembled handshake message\",\n                   ssl->in_msg, ssl->in_hslen );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n\nint mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl )\n{\n    if( ssl->in_msglen < mbedtls_ssl_hs_hdr_len( ssl ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"handshake message too short: %d\",\n                            ssl->in_msglen ) );\n        return( MBEDTLS_ERR_SSL_INVALID_RECORD );\n    }\n\n    ssl->in_hslen = mbedtls_ssl_hs_hdr_len( ssl ) + (\n                    ( ssl->in_msg[1] << 16 ) |\n                    ( ssl->in_msg[2] << 8  ) |\n                      ssl->in_msg[3] );\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"handshake message: msglen =\"\n                        \" %d, type = %d, hslen = %d\",\n                        ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) );\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        int ret;\n        unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];\n\n        if( ssl->handshake != NULL &&\n            ( ( ssl->state   != MBEDTLS_SSL_HANDSHAKE_OVER &&\n                recv_msg_seq != ssl->handshake->in_msg_seq ) ||\n              ( ssl->state  == MBEDTLS_SSL_HANDSHAKE_OVER &&\n                ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) ) )\n        {\n            /* Retransmit only on last message from previous flight, to avoid\n             * too many retransmissions.\n             * Besides, No sane server ever retransmits HelloVerifyRequest */\n            if( recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 &&\n                ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 2, ( \"received message from last flight, \"\n                                    \"message_seq = %d, start_of_flight = %d\",\n                                    recv_msg_seq,\n                                    ssl->handshake->in_flight_start_seq ) );\n\n                if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )\n                {\n                    MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_resend\", ret );\n                    return( ret );\n                }\n            }\n            else\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 2, ( \"dropping out-of-sequence message: \"\n                                    \"message_seq = %d, expected = %d\",\n                                    recv_msg_seq,\n                                    ssl->handshake->in_msg_seq ) );\n            }\n\n            return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );\n        }\n        /* Wait until message completion to increment in_msg_seq */\n\n        /* Reassemble if current message is fragmented or reassembly is\n         * already in progress */\n        if( ssl->in_msglen < ssl->in_hslen ||\n            memcmp( ssl->in_msg + 6, \"\\0\\0\\0\",        3 ) != 0 ||\n            memcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 ||\n            ( ssl->handshake != NULL && ssl->handshake->hs_msg != NULL ) )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"found fragmented DTLS handshake message\" ) );\n\n            if( ( ret = ssl_reassemble_dtls_handshake( ssl ) ) != 0 )\n            {\n                MBEDTLS_SSL_DEBUG_RET( 1, \"ssl_reassemble_dtls_handshake\", ret );\n                return( ret );\n            }\n        }\n    }\n    else\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n    /* With TLS we don't handle fragmentation (for now) */\n    if( ssl->in_msglen < ssl->in_hslen )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"TLS handshake fragmentation not supported\" ) );\n        return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );\n    }\n\n    return( 0 );\n}\n\nvoid mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl )\n{\n\n    if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER &&\n        ssl->handshake != NULL )\n    {\n        ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen );\n    }\n\n    /* Handshake message is complete, increment counter */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&\n        ssl->handshake != NULL )\n    {\n        ssl->handshake->in_msg_seq++;\n    }\n#endif\n}\n\n/*\n * DTLS anti-replay: RFC 6347 4.1.2.6\n *\n * in_window is a field of bits numbered from 0 (lsb) to 63 (msb).\n * Bit n is set iff record number in_window_top - n has been seen.\n *\n * Usually, in_window_top is the last record number seen and the lsb of\n * in_window is set. The only exception is the initial state (record number 0\n * not seen yet).\n */\n#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)\nstatic void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl )\n{\n    ssl->in_window_top = 0;\n    ssl->in_window = 0;\n}\n\nstatic inline uint64_t ssl_load_six_bytes( unsigned char *buf )\n{\n    return( ( (uint64_t) buf[0] << 40 ) |\n            ( (uint64_t) buf[1] << 32 ) |\n            ( (uint64_t) buf[2] << 24 ) |\n            ( (uint64_t) buf[3] << 16 ) |\n            ( (uint64_t) buf[4] <<  8 ) |\n            ( (uint64_t) buf[5]       ) );\n}\n\n/*\n * Return 0 if sequence number is acceptable, -1 otherwise\n */\nint mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context *ssl )\n{\n    uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );\n    uint64_t bit;\n\n    if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )\n        return( 0 );\n\n    if( rec_seqnum > ssl->in_window_top )\n        return( 0 );\n\n    bit = ssl->in_window_top - rec_seqnum;\n\n    if( bit >= 64 )\n        return( -1 );\n\n    if( ( ssl->in_window & ( (uint64_t) 1 << bit ) ) != 0 )\n        return( -1 );\n\n    return( 0 );\n}\n\n/*\n * Update replay window on new validated record\n */\nvoid mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl )\n{\n    uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );\n\n    if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )\n        return;\n\n    if( rec_seqnum > ssl->in_window_top )\n    {\n        /* Update window_top and the contents of the window */\n        uint64_t shift = rec_seqnum - ssl->in_window_top;\n\n        if( shift >= 64 )\n            ssl->in_window = 1;\n        else\n        {\n            ssl->in_window <<= shift;\n            ssl->in_window |= 1;\n        }\n\n        ssl->in_window_top = rec_seqnum;\n    }\n    else\n    {\n        /* Mark that number as seen in the current window */\n        uint64_t bit = ssl->in_window_top - rec_seqnum;\n\n        if( bit < 64 ) /* Always true, but be extra sure */\n            ssl->in_window |= (uint64_t) 1 << bit;\n    }\n}\n#endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */\n\n#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)\n/* Forward declaration */\nstatic int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial );\n\n/*\n * Without any SSL context, check if a datagram looks like a ClientHello with\n * a valid cookie, and if it doesn't, generate a HelloVerifyRequest message.\n * Both input and output include full DTLS headers.\n *\n * - if cookie is valid, return 0\n * - if ClientHello looks superficially valid but cookie is not,\n *   fill obuf and set olen, then\n *   return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED\n * - otherwise return a specific error code\n */\nstatic int ssl_check_dtls_clihlo_cookie(\n                           mbedtls_ssl_cookie_write_t *f_cookie_write,\n                           mbedtls_ssl_cookie_check_t *f_cookie_check,\n                           void *p_cookie,\n                           const unsigned char *cli_id, size_t cli_id_len,\n                           const unsigned char *in, size_t in_len,\n                           unsigned char *obuf, size_t buf_len, size_t *olen )\n{\n    size_t sid_len, cookie_len;\n    unsigned char *p;\n\n    if( f_cookie_write == NULL || f_cookie_check == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    /*\n     * Structure of ClientHello with record and handshake headers,\n     * and expected values. We don't need to check a lot, more checks will be\n     * done when actually parsing the ClientHello - skipping those checks\n     * avoids code duplication and does not make cookie forging any easier.\n     *\n     *  0-0  ContentType type;                  copied, must be handshake\n     *  1-2  ProtocolVersion version;           copied\n     *  3-4  uint16 epoch;                      copied, must be 0\n     *  5-10 uint48 sequence_number;            copied\n     * 11-12 uint16 length;                     (ignored)\n     *\n     * 13-13 HandshakeType msg_type;            (ignored)\n     * 14-16 uint24 length;                     (ignored)\n     * 17-18 uint16 message_seq;                copied\n     * 19-21 uint24 fragment_offset;            copied, must be 0\n     * 22-24 uint24 fragment_length;            (ignored)\n     *\n     * 25-26 ProtocolVersion client_version;    (ignored)\n     * 27-58 Random random;                     (ignored)\n     * 59-xx SessionID session_id;              1 byte len + sid_len content\n     * 60+   opaque cookie<0..2^8-1>;           1 byte len + content\n     *       ...\n     *\n     * Minimum length is 61 bytes.\n     */\n    if( in_len < 61 ||\n        in[0] != MBEDTLS_SSL_MSG_HANDSHAKE ||\n        in[3] != 0 || in[4] != 0 ||\n        in[19] != 0 || in[20] != 0 || in[21] != 0 )\n    {\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n    }\n\n    sid_len = in[59];\n    if( sid_len > in_len - 61 )\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n\n    cookie_len = in[60 + sid_len];\n    if( cookie_len > in_len - 60 )\n        return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );\n\n    if( f_cookie_check( p_cookie, in + sid_len + 61, cookie_len,\n                        cli_id, cli_id_len ) == 0 )\n    {\n        /* Valid cookie */\n        return( 0 );\n    }\n\n    /*\n     * If we get here, we've got an invalid cookie, let's prepare HVR.\n     *\n     *  0-0  ContentType type;                  copied\n     *  1-2  ProtocolVersion version;           copied\n     *  3-4  uint16 epoch;                      copied\n     *  5-10 uint48 sequence_number;            copied\n     * 11-12 uint16 length;                     olen - 13\n     *\n     * 13-13 HandshakeType msg_type;            hello_verify_request\n     * 14-16 uint24 length;                     olen - 25\n     * 17-18 uint16 message_seq;                copied\n     * 19-21 uint24 fragment_offset;            copied\n     * 22-24 uint24 fragment_length;            olen - 25\n     *\n     * 25-26 ProtocolVersion server_version;    0xfe 0xff\n     * 27-27 opaque cookie<0..2^8-1>;           cookie_len = olen - 27, cookie\n     *\n     * Minimum length is 28.\n     */\n    if( buf_len < 28 )\n        return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );\n\n    /* Copy most fields and adapt others */\n    memcpy( obuf, in, 25 );\n    obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;\n    obuf[25] = 0xfe;\n    obuf[26] = 0xff;\n\n    /* Generate and write actual cookie */\n    p = obuf + 28;\n    if( f_cookie_write( p_cookie,\n                        &p, obuf + buf_len, cli_id, cli_id_len ) != 0 )\n    {\n        return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    *olen = p - obuf;\n\n    /* Go back and fill length fields */\n    obuf[27] = (unsigned char)( *olen - 28 );\n\n    obuf[14] = obuf[22] = (unsigned char)( ( *olen - 25 ) >> 16 );\n    obuf[15] = obuf[23] = (unsigned char)( ( *olen - 25 ) >>  8 );\n    obuf[16] = obuf[24] = (unsigned char)( ( *olen - 25 )       );\n\n    obuf[11] = (unsigned char)( ( *olen - 13 ) >>  8 );\n    obuf[12] = (unsigned char)( ( *olen - 13 )       );\n\n    return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );\n}\n\n/*\n * Handle possible client reconnect with the same UDP quadruplet\n * (RFC 6347 Section 4.2.8).\n *\n * Called by ssl_parse_record_header() in case we receive an epoch 0 record\n * that looks like a ClientHello.\n *\n * - if the input looks like a ClientHello without cookies,\n *   send back HelloVerifyRequest, then\n *   return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED\n * - if the input looks like a ClientHello with a valid cookie,\n *   reset the session of the current context, and\n *   return MBEDTLS_ERR_SSL_CLIENT_RECONNECT\n * - if anything goes wrong, return a specific error code\n *\n * mbedtls_ssl_read_record() will ignore the record if anything else than\n * MBEDTLS_ERR_SSL_CLIENT_RECONNECT or 0 is returned, although this function\n * cannot not return 0.\n */\nstatic int ssl_handle_possible_reconnect( mbedtls_ssl_context *ssl )\n{\n    int ret;\n    size_t len;\n\n    ret = ssl_check_dtls_clihlo_cookie(\n            ssl->conf->f_cookie_write,\n            ssl->conf->f_cookie_check,\n            ssl->conf->p_cookie,\n            ssl->cli_id, ssl->cli_id_len,\n            ssl->in_buf, ssl->in_left,\n            ssl->out_buf, MBEDTLS_SSL_OUT_CONTENT_LEN, &len );\n\n    MBEDTLS_SSL_DEBUG_RET( 2, \"ssl_check_dtls_clihlo_cookie\", ret );\n\n    if( ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED )\n    {\n        /* Don't check write errors as we can't do anything here.\n         * If the error is permanent we'll catch it later,\n         * if it's not, then hopefully it'll work next time. */\n        (void) ssl->f_send( ssl->p_bio, ssl->out_buf, len );\n\n        return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );\n    }\n\n    if( ret == 0 )\n    {\n        /* Got a valid cookie, partially reset context */\n        if( ( ret = ssl_session_reset_int( ssl, 1 ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"reset\", ret );\n            return( ret );\n        }\n\n        return( MBEDTLS_ERR_SSL_CLIENT_RECONNECT );\n    }\n\n    return( ret );\n}\n#endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */\n\n/*\n * ContentType type;\n * ProtocolVersion version;\n * uint16 epoch;            // DTLS only\n * uint48 sequence_number;  // DTLS only\n * uint16 length;\n *\n * Return 0 if header looks sane (and, for DTLS, the record is expected)\n * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad,\n * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected.\n *\n * With DTLS, mbedtls_ssl_read_record() will:\n * 1. proceed with the record if this function returns 0\n * 2. drop only the current record if this function returns UNEXPECTED_RECORD\n * 3. return CLIENT_RECONNECT if this function return that value\n * 4. drop the whole datagram if this function returns anything else.\n * Point 2 is needed when the peer is resending, and we have already received\n * the first record from a datagram but are still waiting for the others.\n */\nstatic int ssl_parse_record_header( mbedtls_ssl_context *ssl )\n{\n    int major_ver, minor_ver;\n\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"input record header\", ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) );\n\n    ssl->in_msgtype =  ssl->in_hdr[0];\n    ssl->in_msglen = ( ssl->in_len[0] << 8 ) | ssl->in_len[1];\n    mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, ssl->in_hdr + 1 );\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"input record: msgtype = %d, \"\n                        \"version = [%d:%d], msglen = %d\",\n                        ssl->in_msgtype,\n                        major_ver, minor_ver, ssl->in_msglen ) );\n\n    /* Check record type */\n    if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE &&\n        ssl->in_msgtype != MBEDTLS_SSL_MSG_ALERT &&\n        ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&\n        ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"unknown record type\" ) );\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n        /* Silently ignore invalid DTLS records as recommended by RFC 6347\n         * Section 4.1.2.7 */\n        if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                    MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );\n\n        return( MBEDTLS_ERR_SSL_INVALID_RECORD );\n    }\n\n    /* Check version */\n    if( major_ver != ssl->major_ver )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"major version mismatch\" ) );\n        return( MBEDTLS_ERR_SSL_INVALID_RECORD );\n    }\n\n    if( minor_ver > ssl->conf->max_minor_ver )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"minor version mismatch\" ) );\n        return( MBEDTLS_ERR_SSL_INVALID_RECORD );\n    }\n\n    /* Check length against the size of our buffer */\n    if( ssl->in_msglen > MBEDTLS_SSL_IN_BUFFER_LEN\n                         - (size_t)( ssl->in_msg - ssl->in_buf ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad message length\" ) );\n        return( MBEDTLS_ERR_SSL_INVALID_RECORD );\n    }\n\n    /*\n     * DTLS-related tests.\n     * Check epoch before checking length constraint because\n     * the latter varies with the epoch. E.g., if a ChangeCipherSpec\n     * message gets duplicated before the corresponding Finished message,\n     * the second ChangeCipherSpec should be discarded because it belongs\n     * to an old epoch, but not because its length is shorter than\n     * the minimum record length for packets using the new record transform.\n     * Note that these two kinds of failures are handled differently,\n     * as an unexpected record is silently skipped but an invalid\n     * record leads to the entire datagram being dropped.\n     */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1];\n\n        /* Check epoch (and sequence number) with DTLS */\n        if( rec_epoch != ssl->in_epoch )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"record from another epoch: \"\n                                        \"expected %d, received %d\",\n                                        ssl->in_epoch, rec_epoch ) );\n\n#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)\n            /*\n             * Check for an epoch 0 ClientHello. We can't use in_msg here to\n             * access the first byte of record content (handshake type), as we\n             * have an active transform (possibly iv_len != 0), so use the\n             * fact that the record header len is 13 instead.\n             */\n            if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&\n                ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER &&\n                rec_epoch == 0 &&\n                ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&\n                ssl->in_left > 13 &&\n                ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"possible client reconnect \"\n                                            \"from the same port\" ) );\n                return( ssl_handle_possible_reconnect( ssl ) );\n            }\n            else\n#endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */\n                return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );\n        }\n\n#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)\n        /* Replay detection only works for the current epoch */\n        if( rec_epoch == ssl->in_epoch &&\n            mbedtls_ssl_dtls_replay_check( ssl ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"replayed record\" ) );\n            return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );\n        }\n#endif\n\n        /* Drop unexpected ChangeCipherSpec messages */\n        if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&\n            ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC &&\n            ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"dropping unexpected ChangeCipherSpec\" ) );\n            return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );\n        }\n\n        /* Drop unexpected ApplicationData records,\n         * except at the beginning of renegotiations */\n        if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA &&\n            ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n            && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&\n                   ssl->state == MBEDTLS_SSL_SERVER_HELLO )\n#endif\n            )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"dropping unexpected ApplicationData\" ) );\n            return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );\n        }\n    }\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n\n\n    /* Check length against bounds of the current transform and version */\n    if( ssl->transform_in == NULL )\n    {\n        if( ssl->in_msglen < 1 ||\n            ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad message length\" ) );\n            return( MBEDTLS_ERR_SSL_INVALID_RECORD );\n        }\n    }\n    else\n    {\n        if( ssl->in_msglen < ssl->transform_in->minlen )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad message length\" ) );\n            return( MBEDTLS_ERR_SSL_INVALID_RECORD );\n        }\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n        if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&\n            ssl->in_msglen > ssl->transform_in->minlen + MBEDTLS_SSL_IN_CONTENT_LEN )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad message length\" ) );\n            return( MBEDTLS_ERR_SSL_INVALID_RECORD );\n        }\n#endif\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_2)\n        /*\n         * TLS encrypted messages can have up to 256 bytes of padding\n         */\n        if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 &&\n            ssl->in_msglen > ssl->transform_in->minlen +\n                             MBEDTLS_SSL_IN_CONTENT_LEN + 256 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad message length\" ) );\n            return( MBEDTLS_ERR_SSL_INVALID_RECORD );\n        }\n#endif\n    }\n\n    return( 0 );\n}\n\n/*\n * If applicable, decrypt (and decompress) record content\n */\nstatic int ssl_prepare_record_content( mbedtls_ssl_context *ssl )\n{\n    int ret, done = 0;\n\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"input record from network\",\n                   ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen );\n\n#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)\n    if( mbedtls_ssl_hw_record_read != NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"going for mbedtls_ssl_hw_record_read()\" ) );\n\n        ret = mbedtls_ssl_hw_record_read( ssl );\n        if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_hw_record_read\", ret );\n            return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );\n        }\n\n        if( ret == 0 )\n            done = 1;\n    }\n#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */\n    if( !done && ssl->transform_in != NULL )\n    {\n        if( ( ret = ssl_decrypt_buf( ssl ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"ssl_decrypt_buf\", ret );\n            return( ret );\n        }\n\n        MBEDTLS_SSL_DEBUG_BUF( 4, \"input payload after decrypt\",\n                       ssl->in_msg, ssl->in_msglen );\n\n        if( ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad message length\" ) );\n            return( MBEDTLS_ERR_SSL_INVALID_RECORD );\n        }\n    }\n\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n    if( ssl->transform_in != NULL &&\n        ssl->session_in->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )\n    {\n        if( ( ret = ssl_decompress_buf( ssl ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"ssl_decompress_buf\", ret );\n            return( ret );\n        }\n    }\n#endif /* MBEDTLS_ZLIB_SUPPORT */\n\n#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        mbedtls_ssl_dtls_replay_update( ssl );\n    }\n#endif\n\n    return( 0 );\n}\n\nstatic void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl );\n\n/*\n * Read a record.\n *\n * Silently ignore non-fatal alert (and for DTLS, invalid records as well,\n * RFC 6347 4.1.2.7) and continue reading until a valid record is found.\n *\n */\nint mbedtls_ssl_read_record( mbedtls_ssl_context *ssl )\n{\n    int ret;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> read record\" ) );\n\n    if( ssl->keep_current_message == 0 )\n    {\n        do {\n\n            do ret = mbedtls_ssl_read_record_layer( ssl );\n            while( ret == MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );\n\n            if( ret != 0 )\n            {\n                MBEDTLS_SSL_DEBUG_RET( 1, ( \"mbedtls_ssl_read_record_layer\" ), ret );\n                return( ret );\n            }\n\n            ret = mbedtls_ssl_handle_message_type( ssl );\n\n        } while( MBEDTLS_ERR_SSL_NON_FATAL           == ret  ||\n                 MBEDTLS_ERR_SSL_CONTINUE_PROCESSING == ret );\n\n        if( 0 != ret )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, ( \"mbedtls_ssl_handle_message_type\" ), ret );\n            return( ret );\n        }\n\n        if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )\n        {\n            mbedtls_ssl_update_handshake_status( ssl );\n        }\n    }\n    else\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= reuse previously read message\" ) );\n        ssl->keep_current_message = 0;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= read record\" ) );\n\n    return( 0 );\n}\n\nint mbedtls_ssl_read_record_layer( mbedtls_ssl_context *ssl )\n{\n    int ret;\n\n    /*\n     * Step A\n     *\n     * Consume last content-layer message and potentially\n     * update in_msglen which keeps track of the contents'\n     * consumption state.\n     *\n     * (1) Handshake messages:\n     *     Remove last handshake message, move content\n     *     and adapt in_msglen.\n     *\n     * (2) Alert messages:\n     *     Consume whole record content, in_msglen = 0.\n     *\n     * (3) Change cipher spec:\n     *     Consume whole record content, in_msglen = 0.\n     *\n     * (4) Application data:\n     *     Don't do anything - the record layer provides\n     *     the application data as a stream transport\n     *     and consumes through mbedtls_ssl_read only.\n     *\n     */\n\n    /* Case (1): Handshake messages */\n    if( ssl->in_hslen != 0 )\n    {\n        /* Hard assertion to be sure that no application data\n         * is in flight, as corrupting ssl->in_msglen during\n         * ssl->in_offt != NULL is fatal. */\n        if( ssl->in_offt != NULL )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n        }\n\n        /*\n         * Get next Handshake message in the current record\n         */\n\n        /* Notes:\n         * (1) in_hslen is not necessarily the size of the\n         *     current handshake content: If DTLS handshake\n         *     fragmentation is used, that's the fragment\n         *     size instead. Using the total handshake message\n         *     size here is faulty and should be changed at\n         *     some point.\n         * (2) While it doesn't seem to cause problems, one\n         *     has to be very careful not to assume that in_hslen\n         *     is always <= in_msglen in a sensible communication.\n         *     Again, it's wrong for DTLS handshake fragmentation.\n         *     The following check is therefore mandatory, and\n         *     should not be treated as a silently corrected assertion.\n         *     Additionally, ssl->in_hslen might be arbitrarily out of\n         *     bounds after handling a DTLS message with an unexpected\n         *     sequence number, see mbedtls_ssl_prepare_handshake_record.\n         */\n        if( ssl->in_hslen < ssl->in_msglen )\n        {\n            ssl->in_msglen -= ssl->in_hslen;\n            memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen,\n                     ssl->in_msglen );\n\n            MBEDTLS_SSL_DEBUG_BUF( 4, \"remaining content in record\",\n                                   ssl->in_msg, ssl->in_msglen );\n        }\n        else\n        {\n            ssl->in_msglen = 0;\n        }\n\n        ssl->in_hslen   = 0;\n    }\n    /* Case (4): Application data */\n    else if( ssl->in_offt != NULL )\n    {\n        return( 0 );\n    }\n    /* Everything else (CCS & Alerts) */\n    else\n    {\n        ssl->in_msglen = 0;\n    }\n\n    /*\n     * Step B\n     *\n     * Fetch and decode new record if current one is fully consumed.\n     *\n     */\n\n    if( ssl->in_msglen > 0 )\n    {\n        /* There's something left to be processed in the current record. */\n        return( 0 );\n    }\n\n    /* Current record either fully processed or to be discarded. */\n\n    if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_hdr_len( ssl ) ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_fetch_input\", ret );\n        return( ret );\n    }\n\n    if( ( ret = ssl_parse_record_header( ssl ) ) != 0 )\n    {\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n        if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&\n            ret != MBEDTLS_ERR_SSL_CLIENT_RECONNECT )\n        {\n            if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD )\n            {\n                /* Skip unexpected record (but not whole datagram) */\n                ssl->next_record_offset = ssl->in_msglen\n                                        + mbedtls_ssl_hdr_len( ssl );\n\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"discarding unexpected record \"\n                                            \"(header)\" ) );\n            }\n            else\n            {\n                /* Skip invalid record and the rest of the datagram */\n                ssl->next_record_offset = 0;\n                ssl->in_left = 0;\n\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"discarding invalid record \"\n                                            \"(header)\" ) );\n            }\n\n            /* Get next record */\n            return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );\n        }\n#endif\n        return( ret );\n    }\n\n    /*\n     * Read and optionally decrypt the message contents\n     */\n    if( ( ret = mbedtls_ssl_fetch_input( ssl,\n                                 mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_fetch_input\", ret );\n        return( ret );\n    }\n\n    /* Done reading this record, get ready for the next one */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        ssl->next_record_offset = ssl->in_msglen + mbedtls_ssl_hdr_len( ssl );\n        if( ssl->next_record_offset < ssl->in_left )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"more than one record within datagram\" ) );\n        }\n    }\n    else\n#endif\n        ssl->in_left = 0;\n\n    if( ( ret = ssl_prepare_record_content( ssl ) ) != 0 )\n    {\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n        if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n        {\n            /* Silently discard invalid records */\n            if( ret == MBEDTLS_ERR_SSL_INVALID_RECORD ||\n                ret == MBEDTLS_ERR_SSL_INVALID_MAC )\n            {\n                /* Except when waiting for Finished as a bad mac here\n                 * probably means something went wrong in the handshake\n                 * (eg wrong psk used, mitm downgrade attempt, etc.) */\n                if( ssl->state == MBEDTLS_SSL_CLIENT_FINISHED ||\n                    ssl->state == MBEDTLS_SSL_SERVER_FINISHED )\n                {\n#if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)\n                    if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )\n                    {\n                        mbedtls_ssl_send_alert_message( ssl,\n                                MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );\n                    }\n#endif\n                    return( ret );\n                }\n\n#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)\n                if( ssl->conf->badmac_limit != 0 &&\n                    ++ssl->badmac_seen >= ssl->conf->badmac_limit )\n                {\n                    MBEDTLS_SSL_DEBUG_MSG( 1, ( \"too many records with bad MAC\" ) );\n                    return( MBEDTLS_ERR_SSL_INVALID_MAC );\n                }\n#endif\n\n                /* As above, invalid records cause\n                 * dismissal of the whole datagram. */\n\n                ssl->next_record_offset = 0;\n                ssl->in_left = 0;\n\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"discarding invalid record (mac)\" ) );\n                return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );\n            }\n\n            return( ret );\n        }\n        else\n#endif\n        {\n            /* Error out (and send alert) on invalid records */\n#if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)\n            if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )\n            {\n                mbedtls_ssl_send_alert_message( ssl,\n                        MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                        MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );\n            }\n#endif\n            return( ret );\n        }\n    }\n\n    return( 0 );\n}\n\nint mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl )\n{\n    int ret;\n\n    /*\n     * Handle particular types of records\n     */\n    if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )\n    {\n        if( ( ret = mbedtls_ssl_prepare_handshake_record( ssl ) ) != 0 )\n        {\n            return( ret );\n        }\n    }\n\n    if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )\n    {\n        if( ssl->in_msglen != 2 )\n        {\n            /* Note: Standard allows for more than one 2 byte alert\n               to be packed in a single message, but Mbed TLS doesn't\n               currently support this. */\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"invalid alert message, len: %d\",\n                           ssl->in_msglen ) );\n            return( MBEDTLS_ERR_SSL_INVALID_RECORD );\n        }\n\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"got an alert message, type: [%d:%d]\",\n                       ssl->in_msg[0], ssl->in_msg[1] ) );\n\n        /*\n         * Ignore non-fatal alerts, except close_notify and no_renegotiation\n         */\n        if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"is a fatal alert message (msg %d)\",\n                           ssl->in_msg[1] ) );\n            return( MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE );\n        }\n\n        if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&\n            ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"is a close notify message\" ) );\n            return( MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY );\n        }\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED)\n        if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&\n            ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"is a SSLv3 no renegotiation alert\" ) );\n            /* Will be handled when trying to parse ServerHello */\n            return( 0 );\n        }\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_SRV_C)\n        if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&\n            ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&\n            ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&\n            ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"is a SSLv3 no_cert\" ) );\n            /* Will be handled in mbedtls_ssl_parse_certificate() */\n            return( 0 );\n        }\n#endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */\n\n        /* Silently ignore: fetch new message */\n        return MBEDTLS_ERR_SSL_NON_FATAL;\n    }\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&\n        ssl->handshake != NULL &&\n        ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER  )\n    {\n        ssl_handshake_wrapup_free_hs_transform( ssl );\n    }\n#endif\n\n    return( 0 );\n}\n\nint mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl )\n{\n    int ret;\n\n    if( ( ret = mbedtls_ssl_send_alert_message( ssl,\n                    MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                    MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    return( 0 );\n}\n\nint mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl,\n                            unsigned char level,\n                            unsigned char message )\n{\n    int ret;\n\n    if( ssl == NULL || ssl->conf == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> send alert message\" ) );\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"send alert level=%u message=%u\", level, message ));\n\n    ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;\n    ssl->out_msglen = 2;\n    ssl->out_msg[0] = level;\n    ssl->out_msg[1] = message;\n\n    if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_write_record\", ret );\n        return( ret );\n    }\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= send alert message\" ) );\n\n    return( 0 );\n}\n\n/*\n * Handshake functions\n */\n#if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)         && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)     && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)     && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)   && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)    && \\\n    !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)\n/* No certificate support -> dummy functions */\nint mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )\n{\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write certificate\" ) );\n\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip write certificate\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n    return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n}\n\nint mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )\n{\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse certificate\" ) );\n\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip parse certificate\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n    return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n}\n\n#else\n/* Some certificate support -> implement write and parse */\n\nint mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )\n{\n    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;\n    size_t i, n;\n    const mbedtls_x509_crt *crt;\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write certificate\" ) );\n\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip write certificate\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n\n#if defined(MBEDTLS_SSL_CLI_C)\n    if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )\n    {\n        if( ssl->client_auth == 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip write certificate\" ) );\n            ssl->state++;\n            return( 0 );\n        }\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n        /*\n         * If using SSLv3 and got no cert, send an Alert message\n         * (otherwise an empty Certificate message will be sent).\n         */\n        if( mbedtls_ssl_own_cert( ssl )  == NULL &&\n            ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )\n        {\n            ssl->out_msglen  = 2;\n            ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;\n            ssl->out_msg[0]  = MBEDTLS_SSL_ALERT_LEVEL_WARNING;\n            ssl->out_msg[1]  = MBEDTLS_SSL_ALERT_MSG_NO_CERT;\n\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"got no certificate to send\" ) );\n            goto write_msg;\n        }\n#endif /* MBEDTLS_SSL_PROTO_SSL3 */\n    }\n#endif /* MBEDTLS_SSL_CLI_C */\n#if defined(MBEDTLS_SSL_SRV_C)\n    if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )\n    {\n        if( mbedtls_ssl_own_cert( ssl ) == NULL )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"got no certificate to send\" ) );\n            return( MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED );\n        }\n    }\n#endif\n\n    MBEDTLS_SSL_DEBUG_CRT( 3, \"own certificate\", mbedtls_ssl_own_cert( ssl ) );\n\n    /*\n     *     0  .  0    handshake type\n     *     1  .  3    handshake length\n     *     4  .  6    length of all certs\n     *     7  .  9    length of cert. 1\n     *    10  . n-1   peer certificate\n     *     n  . n+2   length of cert. 2\n     *    n+3 . ...   upper level cert, etc.\n     */\n    i = 7;\n    crt = mbedtls_ssl_own_cert( ssl );\n\n    while( crt != NULL )\n    {\n        n = crt->raw.len;\n        if( n > MBEDTLS_SSL_OUT_CONTENT_LEN - 3 - i )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"certificate too large, %d > %d\",\n                           i + 3 + n, MBEDTLS_SSL_OUT_CONTENT_LEN ) );\n            return( MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE );\n        }\n\n        ssl->out_msg[i    ] = (unsigned char)( n >> 16 );\n        ssl->out_msg[i + 1] = (unsigned char)( n >>  8 );\n        ssl->out_msg[i + 2] = (unsigned char)( n       );\n\n        i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n );\n        i += n; crt = crt->next;\n    }\n\n    ssl->out_msg[4]  = (unsigned char)( ( i - 7 ) >> 16 );\n    ssl->out_msg[5]  = (unsigned char)( ( i - 7 ) >>  8 );\n    ssl->out_msg[6]  = (unsigned char)( ( i - 7 )       );\n\n    ssl->out_msglen  = i;\n    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;\n    ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE;\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)\nwrite_msg:\n#endif\n\n    ssl->state++;\n\n    if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_write_record\", ret );\n        return( ret );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write certificate\" ) );\n\n    return( ret );\n}\n\nint mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )\n{\n    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;\n    size_t i, n;\n    const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;\n    int authmode = ssl->conf->authmode;\n    uint8_t alert;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse certificate\" ) );\n\n    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip parse certificate\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n\n#if defined(MBEDTLS_SSL_SRV_C)\n    if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&\n        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip parse certificate\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\n    if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET )\n        authmode = ssl->handshake->sni_authmode;\n#endif\n\n    if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&\n        authmode == MBEDTLS_SSL_VERIFY_NONE )\n    {\n        ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY;\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= skip parse certificate\" ) );\n        ssl->state++;\n        return( 0 );\n    }\n#endif\n\n    if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )\n    {\n        /* mbedtls_ssl_read_record may have sent an alert already. We\n           let it decide whether to alert. */\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_read_record\", ret );\n        return( ret );\n    }\n\n    ssl->state++;\n\n#if defined(MBEDTLS_SSL_SRV_C)\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n    /*\n     * Check if the client sent an empty certificate\n     */\n    if( ssl->conf->endpoint  == MBEDTLS_SSL_IS_SERVER &&\n        ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )\n    {\n        if( ssl->in_msglen  == 2                        &&\n            ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT            &&\n            ssl->in_msg[0]  == MBEDTLS_SSL_ALERT_LEVEL_WARNING  &&\n            ssl->in_msg[1]  == MBEDTLS_SSL_ALERT_MSG_NO_CERT )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"SSLv3 client has no certificate\" ) );\n\n            /* The client was asked for a certificate but didn't send\n               one. The client should know what's going on, so we\n               don't send an alert. */\n            ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;\n            if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )\n                return( 0 );\n            else\n                return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );\n        }\n    }\n#endif /* MBEDTLS_SSL_PROTO_SSL3 */\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_2)\n    if( ssl->conf->endpoint  == MBEDTLS_SSL_IS_SERVER &&\n        ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )\n    {\n        if( ssl->in_hslen   == 3 + mbedtls_ssl_hs_hdr_len( ssl ) &&\n            ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE    &&\n            ssl->in_msg[0]  == MBEDTLS_SSL_HS_CERTIFICATE   &&\n            memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), \"\\0\\0\\0\", 3 ) == 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"TLSv1 client has no certificate\" ) );\n\n            /* The client was asked for a certificate but didn't send\n               one. The client should know what's going on, so we\n               don't send an alert. */\n            ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;\n            if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )\n                return( 0 );\n            else\n                return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );\n        }\n    }\n#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \\\n          MBEDTLS_SSL_PROTO_TLS1_2 */\n#endif /* MBEDTLS_SSL_SRV_C */\n\n    if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );\n        return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n    }\n\n    if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE ||\n        ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 3 + 3 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );\n    }\n\n    i = mbedtls_ssl_hs_hdr_len( ssl );\n\n    /*\n     * Same message structure as in mbedtls_ssl_write_certificate()\n     */\n    n = ( ssl->in_msg[i+1] << 8 ) | ssl->in_msg[i+2];\n\n    if( ssl->in_msg[i] != 0 ||\n        ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len( ssl ) )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );\n    }\n\n    /* In case we tried to reuse a session but it failed */\n    if( ssl->session_negotiate->peer_cert != NULL )\n    {\n        mbedtls_x509_crt_free( ssl->session_negotiate->peer_cert );\n        mbedtls_free( ssl->session_negotiate->peer_cert );\n    }\n\n    if( ( ssl->session_negotiate->peer_cert = mbedtls_calloc( 1,\n                    sizeof( mbedtls_x509_crt ) ) ) == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"alloc(%d bytes) failed\",\n                       sizeof( mbedtls_x509_crt ) ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );\n        return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n    }\n\n    mbedtls_x509_crt_init( ssl->session_negotiate->peer_cert );\n\n    i += 3;\n\n    while( i < ssl->in_hslen )\n    {\n        if ( i + 3 > ssl->in_hslen ) {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate message\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );\n        }\n        if( ssl->in_msg[i] != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate message\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );\n        }\n\n        n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )\n            | (unsigned int) ssl->in_msg[i + 2];\n        i += 3;\n\n        if( n < 128 || i + n > ssl->in_hslen )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate message\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );\n        }\n\n        ret = mbedtls_x509_crt_parse_der( ssl->session_negotiate->peer_cert,\n                                  ssl->in_msg + i, n );\n        switch( ret )\n        {\n        case 0: /*ok*/\n        case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND:\n            /* Ignore certificate with an unknown algorithm: maybe a\n               prior certificate was already trusted. */\n            break;\n\n        case MBEDTLS_ERR_X509_ALLOC_FAILED:\n            alert = MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR;\n            goto crt_parse_der_failed;\n\n        case MBEDTLS_ERR_X509_UNKNOWN_VERSION:\n            alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;\n            goto crt_parse_der_failed;\n\n        default:\n            alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;\n        crt_parse_der_failed:\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, alert );\n            MBEDTLS_SSL_DEBUG_RET( 1, \" mbedtls_x509_crt_parse_der\", ret );\n            return( ret );\n        }\n\n        i += n;\n    }\n\n    MBEDTLS_SSL_DEBUG_CRT( 3, \"peer certificate\", ssl->session_negotiate->peer_cert );\n\n    /*\n     * On client, make sure the server cert doesn't change during renego to\n     * avoid \"triple handshake\" attack: https://secure-resumption.com/\n     */\n#if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)\n    if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&\n        ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )\n    {\n        if( ssl->session->peer_cert == NULL )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"new server cert during renegotiation\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );\n        }\n\n        if( ssl->session->peer_cert->raw.len !=\n            ssl->session_negotiate->peer_cert->raw.len ||\n            memcmp( ssl->session->peer_cert->raw.p,\n                    ssl->session_negotiate->peer_cert->raw.p,\n                    ssl->session->peer_cert->raw.len ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"server cert changed during renegotiation\" ) );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );\n            return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );\n        }\n    }\n#endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */\n\n    if( authmode != MBEDTLS_SSL_VERIFY_NONE )\n    {\n        mbedtls_x509_crt *ca_chain;\n        mbedtls_x509_crl *ca_crl;\n\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\n        if( ssl->handshake->sni_ca_chain != NULL )\n        {\n            ca_chain = ssl->handshake->sni_ca_chain;\n            ca_crl   = ssl->handshake->sni_ca_crl;\n        }\n        else\n#endif\n        {\n            ca_chain = ssl->conf->ca_chain;\n            ca_crl   = ssl->conf->ca_crl;\n        }\n\n        /*\n         * Main check: verify certificate\n         */\n        ret = mbedtls_x509_crt_verify_with_profile(\n                                ssl->session_negotiate->peer_cert,\n                                ca_chain, ca_crl,\n                                ssl->conf->cert_profile,\n                                ssl->hostname,\n                               &ssl->session_negotiate->verify_result,\n                                ssl->conf->f_vrfy, ssl->conf->p_vrfy );\n\n        if( ret != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"x509_verify_cert\", ret );\n        }\n\n        /*\n         * Secondary checks: always done, but change 'ret' only if it was 0\n         */\n\n#if defined(MBEDTLS_ECP_C)\n        {\n            const mbedtls_pk_context *pk = &ssl->session_negotiate->peer_cert->pk;\n\n            /* If certificate uses an EC key, make sure the curve is OK */\n            if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) &&\n                mbedtls_ssl_check_curve( ssl, mbedtls_pk_ec( *pk )->grp.id ) != 0 )\n            {\n                ssl->session_negotiate->verify_result |= MBEDTLS_X509_BADCERT_BAD_KEY;\n\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate (EC key curve)\" ) );\n                if( ret == 0 )\n                    ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;\n            }\n        }\n#endif /* MBEDTLS_ECP_C */\n\n        if( mbedtls_ssl_check_cert_usage( ssl->session_negotiate->peer_cert,\n                                 ciphersuite_info,\n                                 ! ssl->conf->endpoint,\n                                 &ssl->session_negotiate->verify_result ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad certificate (usage extensions)\" ) );\n            if( ret == 0 )\n                ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;\n        }\n\n        /* mbedtls_x509_crt_verify_with_profile is supposed to report a\n         * verification failure through MBEDTLS_ERR_X509_CERT_VERIFY_FAILED,\n         * with details encoded in the verification flags. All other kinds\n         * of error codes, including those from the user provided f_vrfy\n         * functions, are treated as fatal and lead to a failure of\n         * ssl_parse_certificate even if verification was optional. */\n        if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL &&\n            ( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ||\n              ret == MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ) )\n        {\n            ret = 0;\n        }\n\n        if( ca_chain == NULL && authmode == MBEDTLS_SSL_VERIFY_REQUIRED )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"got no CA chain\" ) );\n            ret = MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED;\n        }\n\n        if( ret != 0 )\n        {\n            /* The certificate may have been rejected for several reasons.\n               Pick one and send the corresponding alert. Which alert to send\n               may be a subject of debate in some cases. */\n            if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_OTHER )\n                alert = MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED;\n            else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_CN_MISMATCH )\n                alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;\n            else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_KEY_USAGE )\n                alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;\n            else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXT_KEY_USAGE )\n                alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;\n            else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NS_CERT_TYPE )\n                alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;\n            else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_PK )\n                alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;\n            else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_KEY )\n                alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;\n            else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXPIRED )\n                alert = MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED;\n            else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_REVOKED )\n                alert = MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED;\n            else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NOT_TRUSTED )\n                alert = MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA;\n            else\n                alert = MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN;\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            alert );\n        }\n\n#if defined(MBEDTLS_DEBUG_C)\n        if( ssl->session_negotiate->verify_result != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"! Certificate verification flags %x\",\n                                        ssl->session_negotiate->verify_result ) );\n        }\n        else\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 3, ( \"Certificate verification flags clear\" ) );\n        }\n#endif /* MBEDTLS_DEBUG_C */\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= parse certificate\" ) );\n\n    return( ret );\n}\n#endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED\n          !MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED\n          !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED\n          !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED\n          !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED\n          !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED\n          !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */\n\nint mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl )\n{\n    int ret;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write change cipher spec\" ) );\n\n    ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;\n    ssl->out_msglen  = 1;\n    ssl->out_msg[0]  = 1;\n\n    ssl->state++;\n\n    if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_write_record\", ret );\n        return( ret );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write change cipher spec\" ) );\n\n    return( 0 );\n}\n\nint mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl )\n{\n    int ret;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse change cipher spec\" ) );\n\n    if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_read_record\", ret );\n        return( ret );\n    }\n\n    if( ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad change cipher spec message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );\n        return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n    }\n\n    if( ssl->in_msglen != 1 || ssl->in_msg[0] != 1 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad change cipher spec message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC );\n    }\n\n    /*\n     * Switch to our negotiated transform and session parameters for inbound\n     * data.\n     */\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"switching to new transform spec for inbound data\" ) );\n    ssl->transform_in = ssl->transform_negotiate;\n    ssl->session_in = ssl->session_negotiate;\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)\n        ssl_dtls_replay_reset( ssl );\n#endif\n\n        /* Increment epoch */\n        if( ++ssl->in_epoch == 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"DTLS epoch would wrap\" ) );\n            /* This is highly unlikely to happen for legitimate reasons, so\n               treat it as an attack and don't send an alert. */\n            return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );\n        }\n    }\n    else\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n    memset( ssl->in_ctr, 0, 8 );\n\n    /*\n     * Set the in_msg pointer to the correct location based on IV length\n     */\n    if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )\n    {\n        ssl->in_msg = ssl->in_iv + ssl->transform_negotiate->ivlen -\n                      ssl->transform_negotiate->fixed_ivlen;\n    }\n    else\n        ssl->in_msg = ssl->in_iv;\n\n#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)\n    if( mbedtls_ssl_hw_record_activate != NULL )\n    {\n        if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_INBOUND ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_hw_record_activate\", ret );\n            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                            MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );\n            return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );\n        }\n    }\n#endif\n\n    ssl->state++;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= parse change cipher spec\" ) );\n\n    return( 0 );\n}\n\nvoid mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl,\n                            const mbedtls_ssl_ciphersuite_t *ciphersuite_info )\n{\n    ((void) ciphersuite_info);\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1)\n    if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )\n        ssl->handshake->update_checksum = ssl_update_checksum_md5sha1;\n    else\n#endif\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#if defined(MBEDTLS_SHA512_C)\n    if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 )\n        ssl->handshake->update_checksum = ssl_update_checksum_sha384;\n    else\n#endif\n#if defined(MBEDTLS_SHA256_C)\n    if( ciphersuite_info->mac != MBEDTLS_MD_SHA384 )\n        ssl->handshake->update_checksum = ssl_update_checksum_sha256;\n    else\n#endif\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n        return;\n    }\n}\n\nvoid mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl )\n{\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1)\n     mbedtls_md5_starts_ret( &ssl->handshake->fin_md5  );\n    mbedtls_sha1_starts_ret( &ssl->handshake->fin_sha1 );\n#endif\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#if defined(MBEDTLS_SHA256_C)\n    mbedtls_sha256_starts_ret( &ssl->handshake->fin_sha256, 0 );\n#endif\n#if defined(MBEDTLS_SHA512_C)\n    mbedtls_sha512_starts_ret( &ssl->handshake->fin_sha512, 1 );\n#endif\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n}\n\nstatic void ssl_update_checksum_start( mbedtls_ssl_context *ssl,\n                                       const unsigned char *buf, size_t len )\n{\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1)\n     mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len );\n    mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len );\n#endif\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#if defined(MBEDTLS_SHA256_C)\n    mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len );\n#endif\n#if defined(MBEDTLS_SHA512_C)\n    mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len );\n#endif\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n}\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1)\nstatic void ssl_update_checksum_md5sha1( mbedtls_ssl_context *ssl,\n                                         const unsigned char *buf, size_t len )\n{\n     mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len );\n    mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len );\n}\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#if defined(MBEDTLS_SHA256_C)\nstatic void ssl_update_checksum_sha256( mbedtls_ssl_context *ssl,\n                                        const unsigned char *buf, size_t len )\n{\n    mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len );\n}\n#endif\n\n#if defined(MBEDTLS_SHA512_C)\nstatic void ssl_update_checksum_sha384( mbedtls_ssl_context *ssl,\n                                        const unsigned char *buf, size_t len )\n{\n    mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len );\n}\n#endif\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\nstatic void ssl_calc_finished_ssl(\n                mbedtls_ssl_context *ssl, unsigned char *buf, int from )\n{\n    const char *sender;\n    mbedtls_md5_context  md5;\n    mbedtls_sha1_context sha1;\n\n    unsigned char padbuf[48];\n    unsigned char md5sum[16];\n    unsigned char sha1sum[20];\n\n    mbedtls_ssl_session *session = ssl->session_negotiate;\n    if( !session )\n        session = ssl->session;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> calc  finished ssl\" ) );\n\n    mbedtls_md5_init( &md5 );\n    mbedtls_sha1_init( &sha1 );\n\n    mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );\n    mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );\n\n    /*\n     * SSLv3:\n     *   hash =\n     *      MD5( master + pad2 +\n     *          MD5( handshake + sender + master + pad1 ) )\n     *   + SHA1( master + pad2 +\n     *         SHA1( handshake + sender + master + pad1 ) )\n     */\n\n#if !defined(MBEDTLS_MD5_ALT)\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"finished  md5 state\", (unsigned char *)\n                    md5.state, sizeof(  md5.state ) );\n#endif\n\n#if !defined(MBEDTLS_SHA1_ALT)\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"finished sha1 state\", (unsigned char *)\n                   sha1.state, sizeof( sha1.state ) );\n#endif\n\n    sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? \"CLNT\"\n                                       : \"SRVR\";\n\n    memset( padbuf, 0x36, 48 );\n\n    mbedtls_md5_update_ret( &md5, (const unsigned char *) sender, 4 );\n    mbedtls_md5_update_ret( &md5, session->master, 48 );\n    mbedtls_md5_update_ret( &md5, padbuf, 48 );\n    mbedtls_md5_finish_ret( &md5, md5sum );\n\n    mbedtls_sha1_update_ret( &sha1, (const unsigned char *) sender, 4 );\n    mbedtls_sha1_update_ret( &sha1, session->master, 48 );\n    mbedtls_sha1_update_ret( &sha1, padbuf, 40 );\n    mbedtls_sha1_finish_ret( &sha1, sha1sum );\n\n    memset( padbuf, 0x5C, 48 );\n\n    mbedtls_md5_starts_ret( &md5 );\n    mbedtls_md5_update_ret( &md5, session->master, 48 );\n    mbedtls_md5_update_ret( &md5, padbuf, 48 );\n    mbedtls_md5_update_ret( &md5, md5sum, 16 );\n    mbedtls_md5_finish_ret( &md5, buf );\n\n    mbedtls_sha1_starts_ret( &sha1 );\n    mbedtls_sha1_update_ret( &sha1, session->master, 48 );\n    mbedtls_sha1_update_ret( &sha1, padbuf , 40 );\n    mbedtls_sha1_update_ret( &sha1, sha1sum, 20 );\n    mbedtls_sha1_finish_ret( &sha1, buf + 16 );\n\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"calc finished result\", buf, 36 );\n\n    mbedtls_md5_free(  &md5  );\n    mbedtls_sha1_free( &sha1 );\n\n    mbedtls_platform_zeroize(  padbuf, sizeof(  padbuf ) );\n    mbedtls_platform_zeroize(  md5sum, sizeof(  md5sum ) );\n    mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= calc  finished\" ) );\n}\n#endif /* MBEDTLS_SSL_PROTO_SSL3 */\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)\nstatic void ssl_calc_finished_tls(\n                mbedtls_ssl_context *ssl, unsigned char *buf, int from )\n{\n    int len = 12;\n    const char *sender;\n    mbedtls_md5_context  md5;\n    mbedtls_sha1_context sha1;\n    unsigned char padbuf[36];\n\n    mbedtls_ssl_session *session = ssl->session_negotiate;\n    if( !session )\n        session = ssl->session;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> calc  finished tls\" ) );\n\n    mbedtls_md5_init( &md5 );\n    mbedtls_sha1_init( &sha1 );\n\n    mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );\n    mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );\n\n    /*\n     * TLSv1:\n     *   hash = PRF( master, finished_label,\n     *               MD5( handshake ) + SHA1( handshake ) )[0..11]\n     */\n\n#if !defined(MBEDTLS_MD5_ALT)\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"finished  md5 state\", (unsigned char *)\n                    md5.state, sizeof(  md5.state ) );\n#endif\n\n#if !defined(MBEDTLS_SHA1_ALT)\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"finished sha1 state\", (unsigned char *)\n                   sha1.state, sizeof( sha1.state ) );\n#endif\n\n    sender = ( from == MBEDTLS_SSL_IS_CLIENT )\n             ? \"client finished\"\n             : \"server finished\";\n\n    mbedtls_md5_finish_ret(  &md5, padbuf );\n    mbedtls_sha1_finish_ret( &sha1, padbuf + 16 );\n\n    ssl->handshake->tls_prf( session->master, 48, sender,\n                             padbuf, 36, buf, len );\n\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"calc finished result\", buf, len );\n\n    mbedtls_md5_free(  &md5  );\n    mbedtls_sha1_free( &sha1 );\n\n    mbedtls_platform_zeroize(  padbuf, sizeof(  padbuf ) );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= calc  finished\" ) );\n}\n#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#if defined(MBEDTLS_SHA256_C)\nstatic void ssl_calc_finished_tls_sha256(\n                mbedtls_ssl_context *ssl, unsigned char *buf, int from )\n{\n    int len = 12;\n    const char *sender;\n    mbedtls_sha256_context sha256;\n    unsigned char padbuf[32];\n\n    mbedtls_ssl_session *session = ssl->session_negotiate;\n    if( !session )\n        session = ssl->session;\n\n    mbedtls_sha256_init( &sha256 );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> calc  finished tls sha256\" ) );\n\n    mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );\n\n    /*\n     * TLSv1.2:\n     *   hash = PRF( master, finished_label,\n     *               Hash( handshake ) )[0.11]\n     */\n\n#if !defined(MBEDTLS_SHA256_ALT)\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"finished sha2 state\", (unsigned char *)\n                   sha256.state, sizeof( sha256.state ) );\n#endif\n\n    sender = ( from == MBEDTLS_SSL_IS_CLIENT )\n             ? \"client finished\"\n             : \"server finished\";\n\n    mbedtls_sha256_finish_ret( &sha256, padbuf );\n\n    ssl->handshake->tls_prf( session->master, 48, sender,\n                             padbuf, 32, buf, len );\n\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"calc finished result\", buf, len );\n\n    mbedtls_sha256_free( &sha256 );\n\n    mbedtls_platform_zeroize(  padbuf, sizeof(  padbuf ) );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= calc  finished\" ) );\n}\n#endif /* MBEDTLS_SHA256_C */\n\n#if defined(MBEDTLS_SHA512_C)\nstatic void ssl_calc_finished_tls_sha384(\n                mbedtls_ssl_context *ssl, unsigned char *buf, int from )\n{\n    int len = 12;\n    const char *sender;\n    mbedtls_sha512_context sha512;\n    unsigned char padbuf[48];\n\n    mbedtls_ssl_session *session = ssl->session_negotiate;\n    if( !session )\n        session = ssl->session;\n\n    mbedtls_sha512_init( &sha512 );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> calc  finished tls sha384\" ) );\n\n    mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );\n\n    /*\n     * TLSv1.2:\n     *   hash = PRF( master, finished_label,\n     *               Hash( handshake ) )[0.11]\n     */\n\n#if !defined(MBEDTLS_SHA512_ALT)\n    MBEDTLS_SSL_DEBUG_BUF( 4, \"finished sha512 state\", (unsigned char *)\n                   sha512.state, sizeof( sha512.state ) );\n#endif\n\n    sender = ( from == MBEDTLS_SSL_IS_CLIENT )\n             ? \"client finished\"\n             : \"server finished\";\n\n    mbedtls_sha512_finish_ret( &sha512, padbuf );\n\n    ssl->handshake->tls_prf( session->master, 48, sender,\n                             padbuf, 48, buf, len );\n\n    MBEDTLS_SSL_DEBUG_BUF( 3, \"calc finished result\", buf, len );\n\n    mbedtls_sha512_free( &sha512 );\n\n    mbedtls_platform_zeroize(  padbuf, sizeof( padbuf ) );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= calc  finished\" ) );\n}\n#endif /* MBEDTLS_SHA512_C */\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n\nstatic void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl )\n{\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"=> handshake wrapup: final free\" ) );\n\n    /*\n     * Free our handshake params\n     */\n    mbedtls_ssl_handshake_free( ssl );\n    mbedtls_free( ssl->handshake );\n    ssl->handshake = NULL;\n\n    /*\n     * Free the previous transform and swith in the current one\n     */\n    if( ssl->transform )\n    {\n        mbedtls_ssl_transform_free( ssl->transform );\n        mbedtls_free( ssl->transform );\n    }\n    ssl->transform = ssl->transform_negotiate;\n    ssl->transform_negotiate = NULL;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"<= handshake wrapup: final free\" ) );\n}\n\nvoid mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl )\n{\n    int resume = ssl->handshake->resume;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"=> handshake wrapup\" ) );\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )\n    {\n        ssl->renego_status =  MBEDTLS_SSL_RENEGOTIATION_DONE;\n        ssl->renego_records_seen = 0;\n    }\n#endif\n\n    /*\n     * Free the previous session and switch in the current one\n     */\n    if( ssl->session )\n    {\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\n        /* RFC 7366 3.1: keep the EtM state */\n        ssl->session_negotiate->encrypt_then_mac =\n                  ssl->session->encrypt_then_mac;\n#endif\n\n        mbedtls_ssl_session_free( ssl->session );\n        mbedtls_free( ssl->session );\n    }\n    ssl->session = ssl->session_negotiate;\n    ssl->session_negotiate = NULL;\n\n    /*\n     * Add cache entry\n     */\n    if( ssl->conf->f_set_cache != NULL &&\n        ssl->session->id_len != 0 &&\n        resume == 0 )\n    {\n        if( ssl->conf->f_set_cache( ssl->conf->p_cache, ssl->session ) != 0 )\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"cache did not store session\" ) );\n    }\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&\n        ssl->handshake->flight != NULL )\n    {\n        /* Cancel handshake timer */\n        ssl_set_timer( ssl, 0 );\n\n        /* Keep last flight around in case we need to resend it:\n         * we need the handshake and transform structures for that */\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"skip freeing handshake and transform\" ) );\n    }\n    else\n#endif\n        ssl_handshake_wrapup_free_hs_transform( ssl );\n\n    ssl->state++;\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"<= handshake wrapup\" ) );\n}\n\nint mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl )\n{\n    int ret, hash_len;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write finished\" ) );\n\n    /*\n     * Set the out_msg pointer to the correct location based on IV length\n     */\n    if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )\n    {\n        ssl->out_msg = ssl->out_iv + ssl->transform_negotiate->ivlen -\n                       ssl->transform_negotiate->fixed_ivlen;\n    }\n    else\n        ssl->out_msg = ssl->out_iv;\n\n    ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->conf->endpoint );\n\n    /*\n     * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites\n     * may define some other value. Currently (early 2016), no defined\n     * ciphersuite does this (and this is unlikely to change as activity has\n     * moved to TLS 1.3 now) so we can keep the hardcoded 12 here.\n     */\n    hash_len = ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) ? 36 : 12;\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    ssl->verify_data_len = hash_len;\n    memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len );\n#endif\n\n    ssl->out_msglen  = 4 + hash_len;\n    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;\n    ssl->out_msg[0]  = MBEDTLS_SSL_HS_FINISHED;\n\n    /*\n     * In case of session resuming, invert the client and server\n     * ChangeCipherSpec messages order.\n     */\n    if( ssl->handshake->resume != 0 )\n    {\n#if defined(MBEDTLS_SSL_CLI_C)\n        if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )\n            ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;\n#endif\n#if defined(MBEDTLS_SSL_SRV_C)\n        if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )\n            ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;\n#endif\n    }\n    else\n        ssl->state++;\n\n    /*\n     * Switch to our negotiated transform and session parameters for outbound\n     * data.\n     */\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"switching to new transform spec for outbound data\" ) );\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        unsigned char i;\n\n        /* Remember current epoch settings for resending */\n        ssl->handshake->alt_transform_out = ssl->transform_out;\n        memcpy( ssl->handshake->alt_out_ctr, ssl->out_ctr, 8 );\n\n        /* Set sequence_number to zero */\n        memset( ssl->out_ctr + 2, 0, 6 );\n\n        /* Increment epoch */\n        for( i = 2; i > 0; i-- )\n            if( ++ssl->out_ctr[i - 1] != 0 )\n                break;\n\n        /* The loop goes to its end iff the counter is wrapping */\n        if( i == 0 )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"DTLS epoch would wrap\" ) );\n            return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );\n        }\n    }\n    else\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n    memset( ssl->out_ctr, 0, 8 );\n\n    ssl->transform_out = ssl->transform_negotiate;\n    ssl->session_out = ssl->session_negotiate;\n\n#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)\n    if( mbedtls_ssl_hw_record_activate != NULL )\n    {\n        if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_hw_record_activate\", ret );\n            return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );\n        }\n    }\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n        mbedtls_ssl_send_flight_completed( ssl );\n#endif\n\n    if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_write_record\", ret );\n        return( ret );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write finished\" ) );\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n#define SSL_MAX_HASH_LEN 36\n#else\n#define SSL_MAX_HASH_LEN 12\n#endif\n\nint mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl )\n{\n    int ret;\n    unsigned int hash_len;\n    unsigned char buf[SSL_MAX_HASH_LEN];\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> parse finished\" ) );\n\n    ssl->handshake->calc_finished( ssl, buf, ssl->conf->endpoint ^ 1 );\n\n    if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_read_record\", ret );\n        return( ret );\n    }\n\n    if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad finished message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );\n        return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n    }\n\n    /* There is currently no ciphersuite using another length with TLS 1.2 */\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )\n        hash_len = 36;\n    else\n#endif\n        hash_len = 12;\n\n    if( ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED ||\n        ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) + hash_len )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad finished message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );\n    }\n\n    if( mbedtls_ssl_safer_memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ),\n                      buf, hash_len ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad finished message\" ) );\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );\n        return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );\n    }\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    ssl->verify_data_len = hash_len;\n    memcpy( ssl->peer_verify_data, buf, hash_len );\n#endif\n\n    if( ssl->handshake->resume != 0 )\n    {\n#if defined(MBEDTLS_SSL_CLI_C)\n        if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )\n            ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;\n#endif\n#if defined(MBEDTLS_SSL_SRV_C)\n        if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )\n            ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;\n#endif\n    }\n    else\n        ssl->state++;\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n        mbedtls_ssl_recv_flight_completed( ssl );\n#endif\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= parse finished\" ) );\n\n    return( 0 );\n}\n\nstatic void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake )\n{\n    memset( handshake, 0, sizeof( mbedtls_ssl_handshake_params ) );\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1)\n     mbedtls_md5_init(   &handshake->fin_md5  );\n    mbedtls_sha1_init(   &handshake->fin_sha1 );\n     mbedtls_md5_starts_ret( &handshake->fin_md5  );\n    mbedtls_sha1_starts_ret( &handshake->fin_sha1 );\n#endif\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#if defined(MBEDTLS_SHA256_C)\n    mbedtls_sha256_init(   &handshake->fin_sha256    );\n    mbedtls_sha256_starts_ret( &handshake->fin_sha256, 0 );\n#endif\n#if defined(MBEDTLS_SHA512_C)\n    mbedtls_sha512_init(   &handshake->fin_sha512    );\n    mbedtls_sha512_starts_ret( &handshake->fin_sha512, 1 );\n#endif\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n\n    handshake->update_checksum = ssl_update_checksum_start;\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \\\n    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n    mbedtls_ssl_sig_hash_set_init( &handshake->hash_algs );\n#endif\n\n#if defined(MBEDTLS_DHM_C)\n    mbedtls_dhm_init( &handshake->dhm_ctx );\n#endif\n#if defined(MBEDTLS_ECDH_C)\n    mbedtls_ecdh_init( &handshake->ecdh_ctx );\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    mbedtls_ecjpake_init( &handshake->ecjpake_ctx );\n#if defined(MBEDTLS_SSL_CLI_C)\n    handshake->ecjpake_cache = NULL;\n    handshake->ecjpake_cache_len = 0;\n#endif\n#endif\n\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\n    handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET;\n#endif\n}\n\nstatic void ssl_transform_init( mbedtls_ssl_transform *transform )\n{\n    memset( transform, 0, sizeof(mbedtls_ssl_transform) );\n\n    mbedtls_cipher_init( &transform->cipher_ctx_enc );\n    mbedtls_cipher_init( &transform->cipher_ctx_dec );\n\n    mbedtls_md_init( &transform->md_ctx_enc );\n    mbedtls_md_init( &transform->md_ctx_dec );\n}\n\nvoid mbedtls_ssl_session_init( mbedtls_ssl_session *session )\n{\n    memset( session, 0, sizeof(mbedtls_ssl_session) );\n}\n\nstatic int ssl_handshake_init( mbedtls_ssl_context *ssl )\n{\n    /* Clear old handshake information if present */\n    if( ssl->transform_negotiate )\n        mbedtls_ssl_transform_free( ssl->transform_negotiate );\n    if( ssl->session_negotiate )\n        mbedtls_ssl_session_free( ssl->session_negotiate );\n    if( ssl->handshake )\n        mbedtls_ssl_handshake_free( ssl );\n\n    /*\n     * Either the pointers are now NULL or cleared properly and can be freed.\n     * Now allocate missing structures.\n     */\n    if( ssl->transform_negotiate == NULL )\n    {\n        ssl->transform_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_transform) );\n    }\n\n    if( ssl->session_negotiate == NULL )\n    {\n        ssl->session_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_session) );\n    }\n\n    if( ssl->handshake == NULL )\n    {\n        ssl->handshake = mbedtls_calloc( 1, sizeof(mbedtls_ssl_handshake_params) );\n    }\n\n    /* All pointers should exist and can be directly freed without issue */\n    if( ssl->handshake == NULL ||\n        ssl->transform_negotiate == NULL ||\n        ssl->session_negotiate == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"alloc() of ssl sub-contexts failed\" ) );\n\n        mbedtls_free( ssl->handshake );\n        mbedtls_free( ssl->transform_negotiate );\n        mbedtls_free( ssl->session_negotiate );\n\n        ssl->handshake = NULL;\n        ssl->transform_negotiate = NULL;\n        ssl->session_negotiate = NULL;\n\n        return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n    }\n\n    /* Initialize structures */\n    mbedtls_ssl_session_init( ssl->session_negotiate );\n    ssl_transform_init( ssl->transform_negotiate );\n    ssl_handshake_params_init( ssl->handshake );\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        ssl->handshake->alt_transform_out = ssl->transform_out;\n\n        if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )\n            ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;\n        else\n            ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;\n\n        ssl_set_timer( ssl, 0 );\n    }\n#endif\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)\n/* Dummy cookie callbacks for defaults */\nstatic int ssl_cookie_write_dummy( void *ctx,\n                      unsigned char **p, unsigned char *end,\n                      const unsigned char *cli_id, size_t cli_id_len )\n{\n    ((void) ctx);\n    ((void) p);\n    ((void) end);\n    ((void) cli_id);\n    ((void) cli_id_len);\n\n    return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );\n}\n\nstatic int ssl_cookie_check_dummy( void *ctx,\n                      const unsigned char *cookie, size_t cookie_len,\n                      const unsigned char *cli_id, size_t cli_id_len )\n{\n    ((void) ctx);\n    ((void) cookie);\n    ((void) cookie_len);\n    ((void) cli_id);\n    ((void) cli_id_len);\n\n    return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );\n}\n#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */\n\n/*\n * Initialize an SSL context\n */\nvoid mbedtls_ssl_init( mbedtls_ssl_context *ssl )\n{\n    memset( ssl, 0, sizeof( mbedtls_ssl_context ) );\n}\n\n/*\n * Setup an SSL context\n */\nint mbedtls_ssl_setup( mbedtls_ssl_context *ssl,\n                       const mbedtls_ssl_config *conf )\n{\n    int ret;\n\n    ssl->conf = conf;\n\n    /*\n     * Prepare base structures\n     */\n    ssl->in_buf = mbedtls_calloc( 1, MBEDTLS_SSL_IN_BUFFER_LEN );\n    if( ssl->in_buf == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"alloc(%d bytes) failed\", MBEDTLS_SSL_IN_BUFFER_LEN) );\n        return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n    }\n\n    ssl->out_buf = mbedtls_calloc( 1, MBEDTLS_SSL_OUT_BUFFER_LEN );\n    if( ssl->out_buf == NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 1, ( \"alloc(%d bytes) failed\", MBEDTLS_SSL_OUT_BUFFER_LEN) );\n        mbedtls_free( ssl->in_buf );\n        ssl->in_buf = NULL;\n        return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n    }\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        ssl->out_hdr = ssl->out_buf;\n        ssl->out_ctr = ssl->out_buf +  3;\n        ssl->out_len = ssl->out_buf + 11;\n        ssl->out_iv  = ssl->out_buf + 13;\n        ssl->out_msg = ssl->out_buf + 13;\n\n        ssl->in_hdr = ssl->in_buf;\n        ssl->in_ctr = ssl->in_buf +  3;\n        ssl->in_len = ssl->in_buf + 11;\n        ssl->in_iv  = ssl->in_buf + 13;\n        ssl->in_msg = ssl->in_buf + 13;\n    }\n    else\n#endif\n    {\n        ssl->out_ctr = ssl->out_buf;\n        ssl->out_hdr = ssl->out_buf +  8;\n        ssl->out_len = ssl->out_buf + 11;\n        ssl->out_iv  = ssl->out_buf + 13;\n        ssl->out_msg = ssl->out_buf + 13;\n\n        ssl->in_ctr = ssl->in_buf;\n        ssl->in_hdr = ssl->in_buf +  8;\n        ssl->in_len = ssl->in_buf + 11;\n        ssl->in_iv  = ssl->in_buf + 13;\n        ssl->in_msg = ssl->in_buf + 13;\n    }\n\n    if( ( ret = ssl_handshake_init( ssl ) ) != 0 )\n        return( ret );\n\n    return( 0 );\n}\n\n/*\n * Reset an initialized and used SSL context for re-use while retaining\n * all application-set variables, function pointers and data.\n *\n * If partial is non-zero, keep data in the input buffer and client ID.\n * (Use when a DTLS client reconnects from the same port.)\n */\nstatic int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial )\n{\n    int ret;\n\n    ssl->state = MBEDTLS_SSL_HELLO_REQUEST;\n\n    /* Cancel any possibly running timer */\n    ssl_set_timer( ssl, 0 );\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE;\n    ssl->renego_records_seen = 0;\n\n    ssl->verify_data_len = 0;\n    memset( ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );\n    memset( ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );\n#endif\n    ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION;\n\n    ssl->in_offt = NULL;\n\n    ssl->in_msg = ssl->in_buf + 13;\n    ssl->in_msgtype = 0;\n    ssl->in_msglen = 0;\n    if( partial == 0 )\n        ssl->in_left = 0;\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    ssl->next_record_offset = 0;\n    ssl->in_epoch = 0;\n#endif\n#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)\n    ssl_dtls_replay_reset( ssl );\n#endif\n\n    ssl->in_hslen = 0;\n    ssl->nb_zero = 0;\n\n    ssl->keep_current_message = 0;\n\n    ssl->out_msg = ssl->out_buf + 13;\n    ssl->out_msgtype = 0;\n    ssl->out_msglen = 0;\n    ssl->out_left = 0;\n#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)\n    if( ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED )\n        ssl->split_done = 0;\n#endif\n\n    ssl->transform_in = NULL;\n    ssl->transform_out = NULL;\n\n    memset( ssl->out_buf, 0, MBEDTLS_SSL_OUT_BUFFER_LEN );\n    if( partial == 0 )\n        memset( ssl->in_buf, 0, MBEDTLS_SSL_IN_BUFFER_LEN );\n\n#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)\n    if( mbedtls_ssl_hw_record_reset != NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"going for mbedtls_ssl_hw_record_reset()\" ) );\n        if( ( ret = mbedtls_ssl_hw_record_reset( ssl ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_hw_record_reset\", ret );\n            return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );\n        }\n    }\n#endif\n\n    if( ssl->transform )\n    {\n        mbedtls_ssl_transform_free( ssl->transform );\n        mbedtls_free( ssl->transform );\n        ssl->transform = NULL;\n    }\n\n    if( ssl->session )\n    {\n        mbedtls_ssl_session_free( ssl->session );\n        mbedtls_free( ssl->session );\n        ssl->session = NULL;\n    }\n\n#if defined(MBEDTLS_SSL_ALPN)\n    ssl->alpn_chosen = NULL;\n#endif\n\n#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)\n    if( partial == 0 )\n    {\n        mbedtls_free( ssl->cli_id );\n        ssl->cli_id = NULL;\n        ssl->cli_id_len = 0;\n    }\n#endif\n\n    if( ( ret = ssl_handshake_init( ssl ) ) != 0 )\n        return( ret );\n\n    return( 0 );\n}\n\n/*\n * Reset an initialized and used SSL context for re-use while retaining\n * all application-set variables, function pointers and data.\n */\nint mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl )\n{\n    return( ssl_session_reset_int( ssl, 0 ) );\n}\n\n/*\n * SSL set accessors\n */\nvoid mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint )\n{\n    conf->endpoint   = endpoint;\n}\n\nvoid mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport )\n{\n    conf->transport = transport;\n}\n\n#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)\nvoid mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode )\n{\n    conf->anti_replay = mode;\n}\n#endif\n\n#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)\nvoid mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit )\n{\n    conf->badmac_limit = limit;\n}\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\nvoid mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf, uint32_t min, uint32_t max )\n{\n    conf->hs_timeout_min = min;\n    conf->hs_timeout_max = max;\n}\n#endif\n\nvoid mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode )\n{\n    conf->authmode   = authmode;\n}\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\nvoid mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf,\n                     int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),\n                     void *p_vrfy )\n{\n    conf->f_vrfy      = f_vrfy;\n    conf->p_vrfy      = p_vrfy;\n}\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\nvoid mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf,\n                  int (*f_rng)(void *, unsigned char *, size_t),\n                  void *p_rng )\n{\n    conf->f_rng      = f_rng;\n    conf->p_rng      = p_rng;\n}\n\nvoid mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf,\n                  void (*f_dbg)(void *, int, const char *, int, const char *),\n                  void  *p_dbg )\n{\n    conf->f_dbg      = f_dbg;\n    conf->p_dbg      = p_dbg;\n}\n\nvoid mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl,\n        void *p_bio,\n        mbedtls_ssl_send_t *f_send,\n        mbedtls_ssl_recv_t *f_recv,\n        mbedtls_ssl_recv_timeout_t *f_recv_timeout )\n{\n    ssl->p_bio          = p_bio;\n    ssl->f_send         = f_send;\n    ssl->f_recv         = f_recv;\n    ssl->f_recv_timeout = f_recv_timeout;\n}\n\nvoid mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout )\n{\n    conf->read_timeout   = timeout;\n}\n\nvoid mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl,\n                               void *p_timer,\n                               mbedtls_ssl_set_timer_t *f_set_timer,\n                               mbedtls_ssl_get_timer_t *f_get_timer )\n{\n    ssl->p_timer        = p_timer;\n    ssl->f_set_timer    = f_set_timer;\n    ssl->f_get_timer    = f_get_timer;\n\n    /* Make sure we start with no timer running */\n    ssl_set_timer( ssl, 0 );\n}\n\n#if defined(MBEDTLS_SSL_SRV_C)\nvoid mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf,\n        void *p_cache,\n        int (*f_get_cache)(void *, mbedtls_ssl_session *),\n        int (*f_set_cache)(void *, const mbedtls_ssl_session *) )\n{\n    conf->p_cache = p_cache;\n    conf->f_get_cache = f_get_cache;\n    conf->f_set_cache = f_set_cache;\n}\n#endif /* MBEDTLS_SSL_SRV_C */\n\n#if defined(MBEDTLS_SSL_CLI_C)\nint mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session )\n{\n    int ret;\n\n    if( ssl == NULL ||\n        session == NULL ||\n        ssl->session_negotiate == NULL ||\n        ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )\n    {\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n    }\n\n    if( ( ret = ssl_session_copy( ssl->session_negotiate, session ) ) != 0 )\n        return( ret );\n\n    ssl->handshake->resume = 1;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_CLI_C */\n\nvoid mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf,\n                                   const int *ciphersuites )\n{\n    conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites;\n    conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites;\n    conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites;\n    conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites;\n}\n\nvoid mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf,\n                                       const int *ciphersuites,\n                                       int major, int minor )\n{\n    if( major != MBEDTLS_SSL_MAJOR_VERSION_3 )\n        return;\n\n    if( minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3 )\n        return;\n\n    conf->ciphersuite_list[minor] = ciphersuites;\n}\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\nvoid mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf,\n                                    const mbedtls_x509_crt_profile *profile )\n{\n    conf->cert_profile = profile;\n}\n\n/* Append a new keycert entry to a (possibly empty) list */\nstatic int ssl_append_key_cert( mbedtls_ssl_key_cert **head,\n                                mbedtls_x509_crt *cert,\n                                mbedtls_pk_context *key )\n{\n    mbedtls_ssl_key_cert *new_cert;\n\n    new_cert = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) );\n    if( new_cert == NULL )\n        return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n\n    new_cert->cert = cert;\n    new_cert->key  = key;\n    new_cert->next = NULL;\n\n    /* Update head is the list was null, else add to the end */\n    if( *head == NULL )\n    {\n        *head = new_cert;\n    }\n    else\n    {\n        mbedtls_ssl_key_cert *cur = *head;\n        while( cur->next != NULL )\n            cur = cur->next;\n        cur->next = new_cert;\n    }\n\n    return( 0 );\n}\n\nint mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,\n                              mbedtls_x509_crt *own_cert,\n                              mbedtls_pk_context *pk_key )\n{\n    return( ssl_append_key_cert( &conf->key_cert, own_cert, pk_key ) );\n}\n\nvoid mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf,\n                               mbedtls_x509_crt *ca_chain,\n                               mbedtls_x509_crl *ca_crl )\n{\n    conf->ca_chain   = ca_chain;\n    conf->ca_crl     = ca_crl;\n}\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\nint mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl,\n                                 mbedtls_x509_crt *own_cert,\n                                 mbedtls_pk_context *pk_key )\n{\n    return( ssl_append_key_cert( &ssl->handshake->sni_key_cert,\n                                 own_cert, pk_key ) );\n}\n\nvoid mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl,\n                                  mbedtls_x509_crt *ca_chain,\n                                  mbedtls_x509_crl *ca_crl )\n{\n    ssl->handshake->sni_ca_chain   = ca_chain;\n    ssl->handshake->sni_ca_crl     = ca_crl;\n}\n\nvoid mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl,\n                                  int authmode )\n{\n    ssl->handshake->sni_authmode = authmode;\n}\n#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n/*\n * Set EC J-PAKE password for current handshake\n */\nint mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,\n                                         const unsigned char *pw,\n                                         size_t pw_len )\n{\n    mbedtls_ecjpake_role role;\n\n    if( ssl->handshake == NULL || ssl->conf == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )\n        role = MBEDTLS_ECJPAKE_SERVER;\n    else\n        role = MBEDTLS_ECJPAKE_CLIENT;\n\n    return( mbedtls_ecjpake_setup( &ssl->handshake->ecjpake_ctx,\n                                   role,\n                                   MBEDTLS_MD_SHA256,\n                                   MBEDTLS_ECP_DP_SECP256R1,\n                                   pw, pw_len ) );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)\nint mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,\n                const unsigned char *psk, size_t psk_len,\n                const unsigned char *psk_identity, size_t psk_identity_len )\n{\n    if( psk == NULL || psk_identity == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    if( psk_len > MBEDTLS_PSK_MAX_LEN )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    /* Identity len will be encoded on two bytes */\n    if( ( psk_identity_len >> 16 ) != 0 ||\n        psk_identity_len > MBEDTLS_SSL_OUT_CONTENT_LEN )\n    {\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n    }\n\n    if( conf->psk != NULL )\n    {\n        mbedtls_platform_zeroize( conf->psk, conf->psk_len );\n\n        mbedtls_free( conf->psk );\n        conf->psk = NULL;\n        conf->psk_len = 0;\n    }\n    if( conf->psk_identity != NULL )\n    {\n        mbedtls_free( conf->psk_identity );\n        conf->psk_identity = NULL;\n        conf->psk_identity_len = 0;\n    }\n\n    if( ( conf->psk = mbedtls_calloc( 1, psk_len ) ) == NULL ||\n        ( conf->psk_identity = mbedtls_calloc( 1, psk_identity_len ) ) == NULL )\n    {\n        mbedtls_free( conf->psk );\n        mbedtls_free( conf->psk_identity );\n        conf->psk = NULL;\n        conf->psk_identity = NULL;\n        return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n    }\n\n    conf->psk_len = psk_len;\n    conf->psk_identity_len = psk_identity_len;\n\n    memcpy( conf->psk, psk, conf->psk_len );\n    memcpy( conf->psk_identity, psk_identity, conf->psk_identity_len );\n\n    return( 0 );\n}\n\nint mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl,\n                            const unsigned char *psk, size_t psk_len )\n{\n    if( psk == NULL || ssl->handshake == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    if( psk_len > MBEDTLS_PSK_MAX_LEN )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    if( ssl->handshake->psk != NULL )\n    {\n        mbedtls_platform_zeroize( ssl->handshake->psk,\n                                  ssl->handshake->psk_len );\n        mbedtls_free( ssl->handshake->psk );\n        ssl->handshake->psk_len = 0;\n    }\n\n    if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL )\n        return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n\n    ssl->handshake->psk_len = psk_len;\n    memcpy( ssl->handshake->psk, psk, ssl->handshake->psk_len );\n\n    return( 0 );\n}\n\nvoid mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf,\n                     int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,\n                     size_t),\n                     void *p_psk )\n{\n    conf->f_psk = f_psk;\n    conf->p_psk = p_psk;\n}\n#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */\n\n#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)\n\n#if !defined(MBEDTLS_DEPRECATED_REMOVED)\nint mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G )\n{\n    int ret;\n\n    if( ( ret = mbedtls_mpi_read_string( &conf->dhm_P, 16, dhm_P ) ) != 0 ||\n        ( ret = mbedtls_mpi_read_string( &conf->dhm_G, 16, dhm_G ) ) != 0 )\n    {\n        mbedtls_mpi_free( &conf->dhm_P );\n        mbedtls_mpi_free( &conf->dhm_G );\n        return( ret );\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_DEPRECATED_REMOVED */\n\nint mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf,\n                                   const unsigned char *dhm_P, size_t P_len,\n                                   const unsigned char *dhm_G, size_t G_len )\n{\n    int ret;\n\n    if( ( ret = mbedtls_mpi_read_binary( &conf->dhm_P, dhm_P, P_len ) ) != 0 ||\n        ( ret = mbedtls_mpi_read_binary( &conf->dhm_G, dhm_G, G_len ) ) != 0 )\n    {\n        mbedtls_mpi_free( &conf->dhm_P );\n        mbedtls_mpi_free( &conf->dhm_G );\n        return( ret );\n    }\n\n    return( 0 );\n}\n\nint mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx )\n{\n    int ret;\n\n    if( ( ret = mbedtls_mpi_copy( &conf->dhm_P, &dhm_ctx->P ) ) != 0 ||\n        ( ret = mbedtls_mpi_copy( &conf->dhm_G, &dhm_ctx->G ) ) != 0 )\n    {\n        mbedtls_mpi_free( &conf->dhm_P );\n        mbedtls_mpi_free( &conf->dhm_G );\n        return( ret );\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */\n\n#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)\n/*\n * Set the minimum length for Diffie-Hellman parameters\n */\nvoid mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf,\n                                      unsigned int bitlen )\n{\n    conf->dhm_min_bitlen = bitlen;\n}\n#endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */\n\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n/*\n * Set allowed/preferred hashes for handshake signatures\n */\nvoid mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,\n                                  const int *hashes )\n{\n    conf->sig_hashes = hashes;\n}\n#endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */\n\n#if defined(MBEDTLS_ECP_C)\n/*\n * Set the allowed elliptic curves\n */\nvoid mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf,\n                             const mbedtls_ecp_group_id *curve_list )\n{\n    conf->curve_list = curve_list;\n}\n#endif /* MBEDTLS_ECP_C */\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\nint mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname )\n{\n    /* Initialize to suppress unnecessary compiler warning */\n    size_t hostname_len = 0;\n\n    /* Check if new hostname is valid before\n     * making any change to current one */\n    if( hostname != NULL )\n    {\n        hostname_len = strlen( hostname );\n\n        if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN )\n            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n    }\n\n    /* Now it's clear that we will overwrite the old hostname,\n     * so we can free it safely */\n\n    if( ssl->hostname != NULL )\n    {\n        mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) );\n        mbedtls_free( ssl->hostname );\n    }\n\n    /* Passing NULL as hostname shall clear the old one */\n\n    if( hostname == NULL )\n    {\n        ssl->hostname = NULL;\n    }\n    else\n    {\n        ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 );\n        if( ssl->hostname == NULL )\n            return( MBEDTLS_ERR_SSL_ALLOC_FAILED );\n\n        memcpy( ssl->hostname, hostname, hostname_len );\n\n        ssl->hostname[hostname_len] = '\\0';\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\nvoid mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf,\n                  int (*f_sni)(void *, mbedtls_ssl_context *,\n                                const unsigned char *, size_t),\n                  void *p_sni )\n{\n    conf->f_sni = f_sni;\n    conf->p_sni = p_sni;\n}\n#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */\n\n#if defined(MBEDTLS_SSL_ALPN)\nint mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos )\n{\n    size_t cur_len, tot_len;\n    const char **p;\n\n    /*\n     * RFC 7301 3.1: \"Empty strings MUST NOT be included and byte strings\n     * MUST NOT be truncated.\"\n     * We check lengths now rather than later.\n     */\n    tot_len = 0;\n    for( p = protos; *p != NULL; p++ )\n    {\n        cur_len = strlen( *p );\n        tot_len += cur_len;\n\n        if( cur_len == 0 || cur_len > 255 || tot_len > 65535 )\n            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n    }\n\n    conf->alpn_list = protos;\n\n    return( 0 );\n}\n\nconst char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl )\n{\n    return( ssl->alpn_chosen );\n}\n#endif /* MBEDTLS_SSL_ALPN */\n\nvoid mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor )\n{\n    conf->max_major_ver = major;\n    conf->max_minor_ver = minor;\n}\n\nvoid mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor )\n{\n    conf->min_major_ver = major;\n    conf->min_minor_ver = minor;\n}\n\n#if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)\nvoid mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback )\n{\n    conf->fallback = fallback;\n}\n#endif\n\n#if defined(MBEDTLS_SSL_SRV_C)\nvoid mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf,\n                                          char cert_req_ca_list )\n{\n    conf->cert_req_ca_list = cert_req_ca_list;\n}\n#endif\n\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\nvoid mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm )\n{\n    conf->encrypt_then_mac = etm;\n}\n#endif\n\n#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)\nvoid mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems )\n{\n    conf->extended_ms = ems;\n}\n#endif\n\n#if defined(MBEDTLS_ARC4_C)\nvoid mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 )\n{\n    conf->arc4_disabled = arc4;\n}\n#endif\n\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\nint mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code )\n{\n    if( mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ||\n        ssl_mfl_code_to_length( mfl_code ) > MBEDTLS_TLS_EXT_ADV_CONTENT_LEN )\n    {\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n    }\n\n    conf->mfl_code = mfl_code;\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */\n\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)\nvoid mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate )\n{\n    conf->trunc_hmac = truncate;\n}\n#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */\n\n#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)\nvoid mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split )\n{\n    conf->cbc_record_splitting = split;\n}\n#endif\n\nvoid mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy )\n{\n    conf->allow_legacy_renegotiation = allow_legacy;\n}\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\nvoid mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation )\n{\n    conf->disable_renegotiation = renegotiation;\n}\n\nvoid mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records )\n{\n    conf->renego_max_records = max_records;\n}\n\nvoid mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf,\n                                   const unsigned char period[8] )\n{\n    memcpy( conf->renego_period, period, 8 );\n}\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\n#if defined(MBEDTLS_SSL_CLI_C)\nvoid mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets )\n{\n    conf->session_tickets = use_tickets;\n}\n#endif\n\n#if defined(MBEDTLS_SSL_SRV_C)\nvoid mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf,\n        mbedtls_ssl_ticket_write_t *f_ticket_write,\n        mbedtls_ssl_ticket_parse_t *f_ticket_parse,\n        void *p_ticket )\n{\n    conf->f_ticket_write = f_ticket_write;\n    conf->f_ticket_parse = f_ticket_parse;\n    conf->p_ticket       = p_ticket;\n}\n#endif\n#endif /* MBEDTLS_SSL_SESSION_TICKETS */\n\n#if defined(MBEDTLS_SSL_EXPORT_KEYS)\nvoid mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf,\n        mbedtls_ssl_export_keys_t *f_export_keys,\n        void *p_export_keys )\n{\n    conf->f_export_keys = f_export_keys;\n    conf->p_export_keys = p_export_keys;\n}\n#endif\n\n#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)\nvoid mbedtls_ssl_conf_async_private_cb(\n    mbedtls_ssl_config *conf,\n    mbedtls_ssl_async_sign_t *f_async_sign,\n    mbedtls_ssl_async_decrypt_t *f_async_decrypt,\n    mbedtls_ssl_async_resume_t *f_async_resume,\n    mbedtls_ssl_async_cancel_t *f_async_cancel,\n    void *async_config_data )\n{\n    conf->f_async_sign_start = f_async_sign;\n    conf->f_async_decrypt_start = f_async_decrypt;\n    conf->f_async_resume = f_async_resume;\n    conf->f_async_cancel = f_async_cancel;\n    conf->p_async_config_data = async_config_data;\n}\n\nvoid *mbedtls_ssl_conf_get_async_config_data( const mbedtls_ssl_config *conf )\n{\n    return( conf->p_async_config_data );\n}\n\nvoid *mbedtls_ssl_get_async_operation_data( const mbedtls_ssl_context *ssl )\n{\n    if( ssl->handshake == NULL )\n        return( NULL );\n    else\n        return( ssl->handshake->user_async_ctx );\n}\n\nvoid mbedtls_ssl_set_async_operation_data( mbedtls_ssl_context *ssl,\n                                 void *ctx )\n{\n    if( ssl->handshake != NULL )\n        ssl->handshake->user_async_ctx = ctx;\n}\n#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */\n\n/*\n * SSL get accessors\n */\nsize_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl )\n{\n    return( ssl->in_offt == NULL ? 0 : ssl->in_msglen );\n}\n\nint mbedtls_ssl_check_pending( const mbedtls_ssl_context *ssl )\n{\n    /*\n     * Case A: We're currently holding back\n     * a message for further processing.\n     */\n\n    if( ssl->keep_current_message == 1 )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ssl_check_pending: record held back for processing\" ) );\n        return( 1 );\n    }\n\n    /*\n     * Case B: Further records are pending in the current datagram.\n     */\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&\n        ssl->in_left > ssl->next_record_offset )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ssl_check_pending: more records within current datagram\" ) );\n        return( 1 );\n    }\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n\n    /*\n     * Case C: A handshake message is being processed.\n     */\n\n    if( ssl->in_hslen > 0 && ssl->in_hslen < ssl->in_msglen )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ssl_check_pending: more handshake messages within current record\" ) );\n        return( 1 );\n    }\n\n    /*\n     * Case D: An application data message is being processed\n     */\n    if( ssl->in_offt != NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ssl_check_pending: application data record is being processed\" ) );\n        return( 1 );\n    }\n\n    /*\n     * In all other cases, the rest of the message can be dropped.\n     * As in ssl_read_record_layer, this needs to be adapted if\n     * we implement support for multiple alerts in single records.\n     */\n\n    MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ssl_check_pending: nothing pending\" ) );\n    return( 0 );\n}\n\nuint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl )\n{\n    if( ssl->session != NULL )\n        return( ssl->session->verify_result );\n\n    if( ssl->session_negotiate != NULL )\n        return( ssl->session_negotiate->verify_result );\n\n    return( 0xFFFFFFFF );\n}\n\nconst char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl )\n{\n    if( ssl == NULL || ssl->session == NULL )\n        return( NULL );\n\n    return mbedtls_ssl_get_ciphersuite_name( ssl->session->ciphersuite );\n}\n\nconst char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl )\n{\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        switch( ssl->minor_ver )\n        {\n            case MBEDTLS_SSL_MINOR_VERSION_2:\n                return( \"DTLSv1.0\" );\n\n            case MBEDTLS_SSL_MINOR_VERSION_3:\n                return( \"DTLSv1.2\" );\n\n            default:\n                return( \"unknown (DTLS)\" );\n        }\n    }\n#endif\n\n    switch( ssl->minor_ver )\n    {\n        case MBEDTLS_SSL_MINOR_VERSION_0:\n            return( \"SSLv3.0\" );\n\n        case MBEDTLS_SSL_MINOR_VERSION_1:\n            return( \"TLSv1.0\" );\n\n        case MBEDTLS_SSL_MINOR_VERSION_2:\n            return( \"TLSv1.1\" );\n\n        case MBEDTLS_SSL_MINOR_VERSION_3:\n            return( \"TLSv1.2\" );\n\n        default:\n            return( \"unknown\" );\n    }\n}\n\nint mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl )\n{\n    size_t transform_expansion;\n    const mbedtls_ssl_transform *transform = ssl->transform_out;\n\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n    if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL )\n        return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );\n#endif\n\n    if( transform == NULL )\n        return( (int) mbedtls_ssl_hdr_len( ssl ) );\n\n    switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) )\n    {\n        case MBEDTLS_MODE_GCM:\n        case MBEDTLS_MODE_CCM:\n        case MBEDTLS_MODE_STREAM:\n            transform_expansion = transform->minlen;\n            break;\n\n        case MBEDTLS_MODE_CBC:\n            transform_expansion = transform->maclen\n                      + mbedtls_cipher_get_block_size( &transform->cipher_ctx_enc );\n            break;\n\n        default:\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n    }\n\n    return( (int)( mbedtls_ssl_hdr_len( ssl ) + transform_expansion ) );\n}\n\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\nsize_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl )\n{\n    size_t max_len;\n\n    /*\n     * Assume mfl_code is correct since it was checked when set\n     */\n    max_len = ssl_mfl_code_to_length( ssl->conf->mfl_code );\n\n    /*\n     * Check if a smaller max length was negotiated\n     */\n    if( ssl->session_out != NULL &&\n        ssl_mfl_code_to_length( ssl->session_out->mfl_code ) < max_len )\n    {\n        max_len = ssl_mfl_code_to_length( ssl->session_out->mfl_code );\n    }\n\n    return max_len;\n}\n#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\nconst mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl )\n{\n    if( ssl == NULL || ssl->session == NULL )\n        return( NULL );\n\n    return( ssl->session->peer_cert );\n}\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n#if defined(MBEDTLS_SSL_CLI_C)\nint mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session *dst )\n{\n    if( ssl == NULL ||\n        dst == NULL ||\n        ssl->session == NULL ||\n        ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )\n    {\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n    }\n\n    return( ssl_session_copy( dst, ssl->session ) );\n}\n#endif /* MBEDTLS_SSL_CLI_C */\n\n/*\n * Perform a single step of the SSL handshake\n */\nint mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl )\n{\n    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;\n\n    if( ssl == NULL || ssl->conf == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n#if defined(MBEDTLS_SSL_CLI_C)\n    if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )\n        ret = mbedtls_ssl_handshake_client_step( ssl );\n#endif\n#if defined(MBEDTLS_SSL_SRV_C)\n    if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )\n        ret = mbedtls_ssl_handshake_server_step( ssl );\n#endif\n\n    return( ret );\n}\n\n/*\n * Perform the SSL handshake\n */\nint mbedtls_ssl_handshake( mbedtls_ssl_context *ssl )\n{\n    int ret = 0;\n\n    if( ssl == NULL || ssl->conf == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> handshake\" ) );\n\n    while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )\n    {\n        ret = mbedtls_ssl_handshake_step( ssl );\n\n        if( ret != 0 )\n            break;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= handshake\" ) );\n\n    return( ret );\n}\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n#if defined(MBEDTLS_SSL_SRV_C)\n/*\n * Write HelloRequest to request renegotiation on server\n */\nstatic int ssl_write_hello_request( mbedtls_ssl_context *ssl )\n{\n    int ret;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write hello request\" ) );\n\n    ssl->out_msglen  = 4;\n    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;\n    ssl->out_msg[0]  = MBEDTLS_SSL_HS_HELLO_REQUEST;\n\n    if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_write_record\", ret );\n        return( ret );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write hello request\" ) );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_SSL_SRV_C */\n\n/*\n * Actually renegotiate current connection, triggered by either:\n * - any side: calling mbedtls_ssl_renegotiate(),\n * - client: receiving a HelloRequest during mbedtls_ssl_read(),\n * - server: receiving any handshake message on server during mbedtls_ssl_read() after\n *   the initial handshake is completed.\n * If the handshake doesn't complete due to waiting for I/O, it will continue\n * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively.\n */\nstatic int ssl_start_renegotiation( mbedtls_ssl_context *ssl )\n{\n    int ret;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> renegotiate\" ) );\n\n    if( ( ret = ssl_handshake_init( ssl ) ) != 0 )\n        return( ret );\n\n    /* RFC 6347 4.2.2: \"[...] the HelloRequest will have message_seq = 0 and\n     * the ServerHello will have message_seq = 1\" */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&\n        ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )\n    {\n        if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )\n            ssl->handshake->out_msg_seq = 1;\n        else\n            ssl->handshake->in_msg_seq = 1;\n    }\n#endif\n\n    ssl->state = MBEDTLS_SSL_HELLO_REQUEST;\n    ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS;\n\n    if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_handshake\", ret );\n        return( ret );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= renegotiate\" ) );\n\n    return( 0 );\n}\n\n/*\n * Renegotiate current connection on client,\n * or request renegotiation on server\n */\nint mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl )\n{\n    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;\n\n    if( ssl == NULL || ssl->conf == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n#if defined(MBEDTLS_SSL_SRV_C)\n    /* On server, just send the request */\n    if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )\n    {\n        if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )\n            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n        ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;\n\n        /* Did we already try/start sending HelloRequest? */\n        if( ssl->out_left != 0 )\n            return( mbedtls_ssl_flush_output( ssl ) );\n\n        return( ssl_write_hello_request( ssl ) );\n    }\n#endif /* MBEDTLS_SSL_SRV_C */\n\n#if defined(MBEDTLS_SSL_CLI_C)\n    /*\n     * On client, either start the renegotiation process or,\n     * if already in progress, continue the handshake\n     */\n    if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )\n    {\n        if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )\n            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n        if( ( ret = ssl_start_renegotiation( ssl ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"ssl_start_renegotiation\", ret );\n            return( ret );\n        }\n    }\n    else\n    {\n        if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_handshake\", ret );\n            return( ret );\n        }\n    }\n#endif /* MBEDTLS_SSL_CLI_C */\n\n    return( ret );\n}\n\n/*\n * Check record counters and renegotiate if they're above the limit.\n */\nstatic int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl )\n{\n    size_t ep_len = ssl_ep_len( ssl );\n    int in_ctr_cmp;\n    int out_ctr_cmp;\n\n    if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ||\n        ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ||\n        ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED )\n    {\n        return( 0 );\n    }\n\n    in_ctr_cmp = memcmp( ssl->in_ctr + ep_len,\n                        ssl->conf->renego_period + ep_len, 8 - ep_len );\n    out_ctr_cmp = memcmp( ssl->out_ctr + ep_len,\n                          ssl->conf->renego_period + ep_len, 8 - ep_len );\n\n    if( in_ctr_cmp <= 0 && out_ctr_cmp <= 0 )\n    {\n        return( 0 );\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 1, ( \"record counter limit reached: renegotiate\" ) );\n    return( mbedtls_ssl_renegotiate( ssl ) );\n}\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n\n/*\n * Receive application data decrypted from the SSL layer\n */\nint mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )\n{\n    int ret;\n    size_t n;\n\n    if( ssl == NULL || ssl->conf == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> read\" ) );\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )\n            return( ret );\n\n        if( ssl->handshake != NULL &&\n            ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )\n        {\n            if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )\n                return( ret );\n        }\n    }\n#endif\n\n    /*\n     * Check if renegotiation is necessary and/or handshake is\n     * in process. If yes, perform/continue, and fall through\n     * if an unexpected packet is received while the client\n     * is waiting for the ServerHello.\n     *\n     * (There is no equivalent to the last condition on\n     *  the server-side as it is not treated as within\n     *  a handshake while waiting for the ClientHello\n     *  after a renegotiation request.)\n     */\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    ret = ssl_check_ctr_renegotiate( ssl );\n    if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&\n        ret != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"ssl_check_ctr_renegotiate\", ret );\n        return( ret );\n    }\n#endif\n\n    if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )\n    {\n        ret = mbedtls_ssl_handshake( ssl );\n        if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&\n            ret != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_handshake\", ret );\n            return( ret );\n        }\n    }\n\n    /* Loop as long as no application data record is available */\n    while( ssl->in_offt == NULL )\n    {\n        /* Start timer if not already running */\n        if( ssl->f_get_timer != NULL &&\n            ssl->f_get_timer( ssl->p_timer ) == -1 )\n        {\n            ssl_set_timer( ssl, ssl->conf->read_timeout );\n        }\n\n        if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )\n        {\n            if( ret == MBEDTLS_ERR_SSL_CONN_EOF )\n                return( 0 );\n\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_read_record\", ret );\n            return( ret );\n        }\n\n        if( ssl->in_msglen  == 0 &&\n            ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA )\n        {\n            /*\n             * OpenSSL sends empty messages to randomize the IV\n             */\n            if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )\n            {\n                if( ret == MBEDTLS_ERR_SSL_CONN_EOF )\n                    return( 0 );\n\n                MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_read_record\", ret );\n                return( ret );\n            }\n        }\n\n        if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"received handshake message\" ) );\n\n            /*\n             * - For client-side, expect SERVER_HELLO_REQUEST.\n             * - For server-side, expect CLIENT_HELLO.\n             * - Fail (TLS) or silently drop record (DTLS) in other cases.\n             */\n\n#if defined(MBEDTLS_SSL_CLI_C)\n            if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&\n                ( ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST ||\n                  ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) ) )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"handshake received (not HelloRequest)\" ) );\n\n                /* With DTLS, drop the packet (probably from last handshake) */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n                if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n                {\n                    continue;\n                }\n#endif\n                return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n            }\n#endif /* MBEDTLS_SSL_CLI_C */\n\n#if defined(MBEDTLS_SSL_SRV_C)\n            if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&\n                ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO )\n            {\n                MBEDTLS_SSL_DEBUG_MSG( 1, ( \"handshake received (not ClientHello)\" ) );\n\n                /* With DTLS, drop the packet (probably from last handshake) */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n                if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n                {\n                    continue;\n                }\n#endif\n                return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n            }\n#endif /* MBEDTLS_SSL_SRV_C */\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n            /* Determine whether renegotiation attempt should be accepted */\n            if( ! ( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ||\n                    ( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&\n                      ssl->conf->allow_legacy_renegotiation ==\n                                                   MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) ) )\n            {\n                /*\n                 * Accept renegotiation request\n                 */\n\n                /* DTLS clients need to know renego is server-initiated */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n                if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&\n                    ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )\n                {\n                    ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;\n                }\n#endif\n                ret = ssl_start_renegotiation( ssl );\n                if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&\n                    ret != 0 )\n                {\n                    MBEDTLS_SSL_DEBUG_RET( 1, \"ssl_start_renegotiation\", ret );\n                    return( ret );\n                }\n            }\n            else\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n            {\n                /*\n                 * Refuse renegotiation\n                 */\n\n                MBEDTLS_SSL_DEBUG_MSG( 3, ( \"refusing renegotiation, sending alert\" ) );\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n                if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )\n                {\n                    /* SSLv3 does not have a \"no_renegotiation\" warning, so\n                       we send a fatal alert and abort the connection. */\n                    mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                                    MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );\n                    return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n                }\n                else\n#endif /* MBEDTLS_SSL_PROTO_SSL3 */\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_2)\n                if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )\n                {\n                    if( ( ret = mbedtls_ssl_send_alert_message( ssl,\n                                    MBEDTLS_SSL_ALERT_LEVEL_WARNING,\n                                    MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 )\n                    {\n                        return( ret );\n                    }\n                }\n                else\n#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 ||\n          MBEDTLS_SSL_PROTO_TLS1_2 */\n                {\n                    MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n                    return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n                }\n            }\n\n            /* At this point, we don't know whether the renegotiation has been\n             * completed or not. The cases to consider are the following:\n             * 1) The renegotiation is complete. In this case, no new record\n             *    has been read yet.\n             * 2) The renegotiation is incomplete because the client received\n             *    an application data record while awaiting the ServerHello.\n             * 3) The renegotiation is incomplete because the client received\n             *    a non-handshake, non-application data message while awaiting\n             *    the ServerHello.\n             * In each of these case, looping will be the proper action:\n             * - For 1), the next iteration will read a new record and check\n             *   if it's application data.\n             * - For 2), the loop condition isn't satisfied as application data\n             *   is present, hence continue is the same as break\n             * - For 3), the loop condition is satisfied and read_record\n             *   will re-deliver the message that was held back by the client\n             *   when expecting the ServerHello.\n             */\n            continue;\n        }\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n        else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )\n        {\n            if( ssl->conf->renego_max_records >= 0 )\n            {\n                if( ++ssl->renego_records_seen > ssl->conf->renego_max_records )\n                {\n                    MBEDTLS_SSL_DEBUG_MSG( 1, ( \"renegotiation requested, \"\n                                        \"but not honored by client\" ) );\n                    return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n                }\n            }\n        }\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n\n        /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */\n        if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 2, ( \"ignoring non-fatal non-closure alert\" ) );\n            return( MBEDTLS_ERR_SSL_WANT_READ );\n        }\n\n        if( ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad application data message\" ) );\n            return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );\n        }\n\n        ssl->in_offt = ssl->in_msg;\n\n        /* We're going to return something now, cancel timer,\n         * except if handshake (renegotiation) is in progress */\n        if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )\n            ssl_set_timer( ssl, 0 );\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n        /* If we requested renego but received AppData, resend HelloRequest.\n         * Do it now, after setting in_offt, to avoid taking this branch\n         * again if ssl_write_hello_request() returns WANT_WRITE */\n#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)\n        if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&\n            ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )\n        {\n            if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )\n            {\n                MBEDTLS_SSL_DEBUG_RET( 1, \"ssl_resend_hello_request\", ret );\n                return( ret );\n            }\n        }\n#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n    }\n\n    n = ( len < ssl->in_msglen )\n        ? len : ssl->in_msglen;\n\n    memcpy( buf, ssl->in_offt, n );\n    ssl->in_msglen -= n;\n\n    if( ssl->in_msglen == 0 )\n    {\n        /* all bytes consumed */\n        ssl->in_offt = NULL;\n        ssl->keep_current_message = 0;\n    }\n    else\n    {\n        /* more data available */\n        ssl->in_offt += n;\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= read\" ) );\n\n    return( (int) n );\n}\n\n/*\n * Send application data to be encrypted by the SSL layer, taking care of max\n * fragment length and buffer size.\n *\n * According to RFC 5246 Section 6.2.1:\n *\n *      Zero-length fragments of Application data MAY be sent as they are\n *      potentially useful as a traffic analysis countermeasure.\n *\n * Therefore, it is possible that the input message length is 0 and the\n * corresponding return code is 0 on success.\n */\nstatic int ssl_write_real( mbedtls_ssl_context *ssl,\n                           const unsigned char *buf, size_t len )\n{\n    int ret;\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\n    size_t max_len = mbedtls_ssl_get_max_frag_len( ssl );\n#else\n    size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;\n#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */\n    if( len > max_len )\n    {\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n        if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n        {\n            MBEDTLS_SSL_DEBUG_MSG( 1, ( \"fragment larger than the (negotiated) \"\n                                \"maximum fragment length: %d > %d\",\n                                len, max_len ) );\n            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n        }\n        else\n#endif\n            len = max_len;\n    }\n\n    if( ssl->out_left != 0 )\n    {\n        /*\n         * The user has previously tried to send the data and\n         * MBEDTLS_ERR_SSL_WANT_WRITE or the message was only partially\n         * written. In this case, we expect the high-level write function\n         * (e.g. mbedtls_ssl_write()) to be called with the same parameters\n         */\n        if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_flush_output\", ret );\n            return( ret );\n        }\n    }\n    else\n    {\n        /*\n         * The user is trying to send a message the first time, so we need to\n         * copy the data into the internal buffers and setup the data structure\n         * to keep track of partial writes\n         */\n        ssl->out_msglen  = len;\n        ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA;\n        memcpy( ssl->out_msg, buf, len );\n\n        if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_write_record\", ret );\n            return( ret );\n        }\n    }\n\n    return( (int) len );\n}\n\n/*\n * Write application data, doing 1/n-1 splitting if necessary.\n *\n * With non-blocking I/O, ssl_write_real() may return WANT_WRITE,\n * then the caller will call us again with the same arguments, so\n * remember whether we already did the split or not.\n */\n#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)\nstatic int ssl_write_split( mbedtls_ssl_context *ssl,\n                            const unsigned char *buf, size_t len )\n{\n    int ret;\n\n    if( ssl->conf->cbc_record_splitting ==\n            MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED ||\n        len <= 1 ||\n        ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_1 ||\n        mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc )\n                                != MBEDTLS_MODE_CBC )\n    {\n        return( ssl_write_real( ssl, buf, len ) );\n    }\n\n    if( ssl->split_done == 0 )\n    {\n        if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 )\n            return( ret );\n        ssl->split_done = 1;\n    }\n\n    if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 )\n        return( ret );\n    ssl->split_done = 0;\n\n    return( ret + 1 );\n}\n#endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */\n\n/*\n * Write application data (public-facing wrapper)\n */\nint mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len )\n{\n    int ret;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write\" ) );\n\n    if( ssl == NULL || ssl->conf == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"ssl_check_ctr_renegotiate\", ret );\n        return( ret );\n    }\n#endif\n\n    if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )\n    {\n        if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_handshake\", ret );\n            return( ret );\n        }\n    }\n\n#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)\n    ret = ssl_write_split( ssl, buf, len );\n#else\n    ret = ssl_write_real( ssl, buf, len );\n#endif\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write\" ) );\n\n    return( ret );\n}\n\n/*\n * Notify the peer that the connection is being closed\n */\nint mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl )\n{\n    int ret;\n\n    if( ssl == NULL || ssl->conf == NULL )\n        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> write close notify\" ) );\n\n    if( ssl->out_left != 0 )\n        return( mbedtls_ssl_flush_output( ssl ) );\n\n    if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )\n    {\n        if( ( ret = mbedtls_ssl_send_alert_message( ssl,\n                        MBEDTLS_SSL_ALERT_LEVEL_WARNING,\n                        MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 )\n        {\n            MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_ssl_send_alert_message\", ret );\n            return( ret );\n        }\n    }\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= write close notify\" ) );\n\n    return( 0 );\n}\n\nvoid mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform )\n{\n    if( transform == NULL )\n        return;\n\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n    deflateEnd( &transform->ctx_deflate );\n    inflateEnd( &transform->ctx_inflate );\n#endif\n\n    mbedtls_cipher_free( &transform->cipher_ctx_enc );\n    mbedtls_cipher_free( &transform->cipher_ctx_dec );\n\n    mbedtls_md_free( &transform->md_ctx_enc );\n    mbedtls_md_free( &transform->md_ctx_dec );\n\n    mbedtls_platform_zeroize( transform, sizeof( mbedtls_ssl_transform ) );\n}\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\nstatic void ssl_key_cert_free( mbedtls_ssl_key_cert *key_cert )\n{\n    mbedtls_ssl_key_cert *cur = key_cert, *next;\n\n    while( cur != NULL )\n    {\n        next = cur->next;\n        mbedtls_free( cur );\n        cur = next;\n    }\n}\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\nvoid mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl )\n{\n    mbedtls_ssl_handshake_params *handshake = ssl->handshake;\n\n    if( handshake == NULL )\n        return;\n\n#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)\n    if( ssl->conf->f_async_cancel != NULL && handshake->async_in_progress != 0 )\n    {\n        ssl->conf->f_async_cancel( ssl );\n        handshake->async_in_progress = 0;\n    }\n#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1)\n    mbedtls_md5_free(    &handshake->fin_md5  );\n    mbedtls_sha1_free(   &handshake->fin_sha1 );\n#endif\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n#if defined(MBEDTLS_SHA256_C)\n    mbedtls_sha256_free(   &handshake->fin_sha256    );\n#endif\n#if defined(MBEDTLS_SHA512_C)\n    mbedtls_sha512_free(   &handshake->fin_sha512    );\n#endif\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n\n#if defined(MBEDTLS_DHM_C)\n    mbedtls_dhm_free( &handshake->dhm_ctx );\n#endif\n#if defined(MBEDTLS_ECDH_C)\n    mbedtls_ecdh_free( &handshake->ecdh_ctx );\n#endif\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    mbedtls_ecjpake_free( &handshake->ecjpake_ctx );\n#if defined(MBEDTLS_SSL_CLI_C)\n    mbedtls_free( handshake->ecjpake_cache );\n    handshake->ecjpake_cache = NULL;\n    handshake->ecjpake_cache_len = 0;\n#endif\n#endif\n\n#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \\\n    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    /* explicit void pointer cast for buggy MS compiler */\n    mbedtls_free( (void *) handshake->curves );\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)\n    if( handshake->psk != NULL )\n    {\n        mbedtls_platform_zeroize( handshake->psk, handshake->psk_len );\n        mbedtls_free( handshake->psk );\n    }\n#endif\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C) && \\\n    defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\n    /*\n     * Free only the linked list wrapper, not the keys themselves\n     * since the belong to the SNI callback\n     */\n    if( handshake->sni_key_cert != NULL )\n    {\n        mbedtls_ssl_key_cert *cur = handshake->sni_key_cert, *next;\n\n        while( cur != NULL )\n        {\n            next = cur->next;\n            mbedtls_free( cur );\n            cur = next;\n        }\n    }\n#endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    mbedtls_free( handshake->verify_cookie );\n    mbedtls_free( handshake->hs_msg );\n    ssl_flight_free( handshake->flight );\n#endif\n\n    mbedtls_platform_zeroize( handshake,\n                              sizeof( mbedtls_ssl_handshake_params ) );\n}\n\nvoid mbedtls_ssl_session_free( mbedtls_ssl_session *session )\n{\n    if( session == NULL )\n        return;\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    if( session->peer_cert != NULL )\n    {\n        mbedtls_x509_crt_free( session->peer_cert );\n        mbedtls_free( session->peer_cert );\n    }\n#endif\n\n#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)\n    mbedtls_free( session->ticket );\n#endif\n\n    mbedtls_platform_zeroize( session, sizeof( mbedtls_ssl_session ) );\n}\n\n/*\n * Free an SSL context\n */\nvoid mbedtls_ssl_free( mbedtls_ssl_context *ssl )\n{\n    if( ssl == NULL )\n        return;\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"=> free\" ) );\n\n    if( ssl->out_buf != NULL )\n    {\n        mbedtls_platform_zeroize( ssl->out_buf, MBEDTLS_SSL_OUT_BUFFER_LEN );\n        mbedtls_free( ssl->out_buf );\n    }\n\n    if( ssl->in_buf != NULL )\n    {\n        mbedtls_platform_zeroize( ssl->in_buf, MBEDTLS_SSL_IN_BUFFER_LEN );\n        mbedtls_free( ssl->in_buf );\n    }\n\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n    if( ssl->compress_buf != NULL )\n    {\n        mbedtls_platform_zeroize( ssl->compress_buf, MBEDTLS_SSL_COMPRESS_BUFFER_LEN );\n        mbedtls_free( ssl->compress_buf );\n    }\n#endif\n\n    if( ssl->transform )\n    {\n        mbedtls_ssl_transform_free( ssl->transform );\n        mbedtls_free( ssl->transform );\n    }\n\n    if( ssl->handshake )\n    {\n        mbedtls_ssl_handshake_free( ssl );\n        mbedtls_ssl_transform_free( ssl->transform_negotiate );\n        mbedtls_ssl_session_free( ssl->session_negotiate );\n\n        mbedtls_free( ssl->handshake );\n        mbedtls_free( ssl->transform_negotiate );\n        mbedtls_free( ssl->session_negotiate );\n    }\n\n    if( ssl->session )\n    {\n        mbedtls_ssl_session_free( ssl->session );\n        mbedtls_free( ssl->session );\n    }\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    if( ssl->hostname != NULL )\n    {\n        mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) );\n        mbedtls_free( ssl->hostname );\n    }\n#endif\n\n#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)\n    if( mbedtls_ssl_hw_record_finish != NULL )\n    {\n        MBEDTLS_SSL_DEBUG_MSG( 2, ( \"going for mbedtls_ssl_hw_record_finish()\" ) );\n        mbedtls_ssl_hw_record_finish( ssl );\n    }\n#endif\n\n#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)\n    mbedtls_free( ssl->cli_id );\n#endif\n\n    MBEDTLS_SSL_DEBUG_MSG( 2, ( \"<= free\" ) );\n\n    /* Actually clear after last debug message */\n    mbedtls_platform_zeroize( ssl, sizeof( mbedtls_ssl_context ) );\n}\n\n/*\n * Initialze mbedtls_ssl_config\n */\nvoid mbedtls_ssl_config_init( mbedtls_ssl_config *conf )\n{\n    memset( conf, 0, sizeof( mbedtls_ssl_config ) );\n}\n\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\nstatic int ssl_preset_default_hashes[] = {\n#if defined(MBEDTLS_SHA512_C)\n    MBEDTLS_MD_SHA512,\n    MBEDTLS_MD_SHA384,\n#endif\n#if defined(MBEDTLS_SHA256_C)\n    MBEDTLS_MD_SHA256,\n    MBEDTLS_MD_SHA224,\n#endif\n#if defined(MBEDTLS_SHA1_C) && defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE)\n    MBEDTLS_MD_SHA1,\n#endif\n    MBEDTLS_MD_NONE\n};\n#endif\n\nstatic int ssl_preset_suiteb_ciphersuites[] = {\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n    0\n};\n\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\nstatic int ssl_preset_suiteb_hashes[] = {\n    MBEDTLS_MD_SHA256,\n    MBEDTLS_MD_SHA384,\n    MBEDTLS_MD_NONE\n};\n#endif\n\n#if defined(MBEDTLS_ECP_C)\nstatic mbedtls_ecp_group_id ssl_preset_suiteb_curves[] = {\n    MBEDTLS_ECP_DP_SECP256R1,\n    MBEDTLS_ECP_DP_SECP384R1,\n    MBEDTLS_ECP_DP_NONE\n};\n#endif\n\n/*\n * Load default in mbedtls_ssl_config\n */\nint mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,\n                                 int endpoint, int transport, int preset )\n{\n#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)\n    int ret;\n#endif\n\n    /* Use the functions here so that they are covered in tests,\n     * but otherwise access member directly for efficiency */\n    mbedtls_ssl_conf_endpoint( conf, endpoint );\n    mbedtls_ssl_conf_transport( conf, transport );\n\n    /*\n     * Things that are common to all presets\n     */\n#if defined(MBEDTLS_SSL_CLI_C)\n    if( endpoint == MBEDTLS_SSL_IS_CLIENT )\n    {\n        conf->authmode = MBEDTLS_SSL_VERIFY_REQUIRED;\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\n        conf->session_tickets = MBEDTLS_SSL_SESSION_TICKETS_ENABLED;\n#endif\n    }\n#endif\n\n#if defined(MBEDTLS_ARC4_C)\n    conf->arc4_disabled = MBEDTLS_SSL_ARC4_DISABLED;\n#endif\n\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\n    conf->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;\n#endif\n\n#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)\n    conf->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;\n#endif\n\n#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)\n    conf->cbc_record_splitting = MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED;\n#endif\n\n#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)\n    conf->f_cookie_write = ssl_cookie_write_dummy;\n    conf->f_cookie_check = ssl_cookie_check_dummy;\n#endif\n\n#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)\n    conf->anti_replay = MBEDTLS_SSL_ANTI_REPLAY_ENABLED;\n#endif\n\n#if defined(MBEDTLS_SSL_SRV_C)\n    conf->cert_req_ca_list = MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED;\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    conf->hs_timeout_min = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN;\n    conf->hs_timeout_max = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX;\n#endif\n\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    conf->renego_max_records = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT;\n    memset( conf->renego_period,     0x00, 2 );\n    memset( conf->renego_period + 2, 0xFF, 6 );\n#endif\n\n#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)\n            if( endpoint == MBEDTLS_SSL_IS_SERVER )\n            {\n                const unsigned char dhm_p[] =\n                    MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN;\n                const unsigned char dhm_g[] =\n                    MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN;\n\n                if ( ( ret = mbedtls_ssl_conf_dh_param_bin( conf,\n                                               dhm_p, sizeof( dhm_p ),\n                                               dhm_g, sizeof( dhm_g ) ) ) != 0 )\n                {\n                    return( ret );\n                }\n            }\n#endif\n\n    /*\n     * Preset-specific defaults\n     */\n    switch( preset )\n    {\n        /*\n         * NSA Suite B\n         */\n        case MBEDTLS_SSL_PRESET_SUITEB:\n            conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;\n            conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */\n            conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;\n            conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;\n\n            conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =\n            conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =\n            conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =\n            conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =\n                                   ssl_preset_suiteb_ciphersuites;\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n            conf->cert_profile = &mbedtls_x509_crt_profile_suiteb;\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n            conf->sig_hashes = ssl_preset_suiteb_hashes;\n#endif\n\n#if defined(MBEDTLS_ECP_C)\n            conf->curve_list = ssl_preset_suiteb_curves;\n#endif\n            break;\n\n        /*\n         * Default\n         */\n        default:\n            conf->min_major_ver = ( MBEDTLS_SSL_MIN_MAJOR_VERSION >\n                                    MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION ) ?\n                                    MBEDTLS_SSL_MIN_MAJOR_VERSION :\n                                    MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION;\n            conf->min_minor_ver = ( MBEDTLS_SSL_MIN_MINOR_VERSION >\n                                    MBEDTLS_SSL_MIN_VALID_MINOR_VERSION ) ?\n                                    MBEDTLS_SSL_MIN_MINOR_VERSION :\n                                    MBEDTLS_SSL_MIN_VALID_MINOR_VERSION;\n            conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;\n            conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n            if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n                conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_2;\n#endif\n\n            conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =\n            conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =\n            conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =\n            conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =\n                                   mbedtls_ssl_list_ciphersuites();\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n            conf->cert_profile = &mbedtls_x509_crt_profile_default;\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n            conf->sig_hashes = ssl_preset_default_hashes;\n#endif\n\n#if defined(MBEDTLS_ECP_C)\n            conf->curve_list = mbedtls_ecp_grp_id_list();\n#endif\n\n#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)\n            conf->dhm_min_bitlen = 1024;\n#endif\n    }\n\n    return( 0 );\n}\n\n/*\n * Free mbedtls_ssl_config\n */\nvoid mbedtls_ssl_config_free( mbedtls_ssl_config *conf )\n{\n#if defined(MBEDTLS_DHM_C)\n    mbedtls_mpi_free( &conf->dhm_P );\n    mbedtls_mpi_free( &conf->dhm_G );\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)\n    if( conf->psk != NULL )\n    {\n        mbedtls_platform_zeroize( conf->psk, conf->psk_len );\n        mbedtls_free( conf->psk );\n        conf->psk = NULL;\n        conf->psk_len = 0;\n    }\n\n    if( conf->psk_identity != NULL )\n    {\n        mbedtls_platform_zeroize( conf->psk_identity, conf->psk_identity_len );\n        mbedtls_free( conf->psk_identity );\n        conf->psk_identity = NULL;\n        conf->psk_identity_len = 0;\n    }\n#endif\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    ssl_key_cert_free( conf->key_cert );\n#endif\n\n    mbedtls_platform_zeroize( conf, sizeof( mbedtls_ssl_config ) );\n}\n\n#if defined(MBEDTLS_PK_C) && \\\n    ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) )\n/*\n * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX\n */\nunsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk )\n{\n#if defined(MBEDTLS_RSA_C)\n    if( mbedtls_pk_can_do( pk, MBEDTLS_PK_RSA ) )\n        return( MBEDTLS_SSL_SIG_RSA );\n#endif\n#if defined(MBEDTLS_ECDSA_C)\n    if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECDSA ) )\n        return( MBEDTLS_SSL_SIG_ECDSA );\n#endif\n    return( MBEDTLS_SSL_SIG_ANON );\n}\n\nunsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type )\n{\n    switch( type ) {\n        case MBEDTLS_PK_RSA:\n            return( MBEDTLS_SSL_SIG_RSA );\n        case MBEDTLS_PK_ECDSA:\n        case MBEDTLS_PK_ECKEY:\n            return( MBEDTLS_SSL_SIG_ECDSA );\n        default:\n            return( MBEDTLS_SSL_SIG_ANON );\n    }\n}\n\nmbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig )\n{\n    switch( sig )\n    {\n#if defined(MBEDTLS_RSA_C)\n        case MBEDTLS_SSL_SIG_RSA:\n            return( MBEDTLS_PK_RSA );\n#endif\n#if defined(MBEDTLS_ECDSA_C)\n        case MBEDTLS_SSL_SIG_ECDSA:\n            return( MBEDTLS_PK_ECDSA );\n#endif\n        default:\n            return( MBEDTLS_PK_NONE );\n    }\n}\n#endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \\\n    defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n\n/* Find an entry in a signature-hash set matching a given hash algorithm. */\nmbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set,\n                                                 mbedtls_pk_type_t sig_alg )\n{\n    switch( sig_alg )\n    {\n        case MBEDTLS_PK_RSA:\n            return( set->rsa );\n        case MBEDTLS_PK_ECDSA:\n            return( set->ecdsa );\n        default:\n            return( MBEDTLS_MD_NONE );\n    }\n}\n\n/* Add a signature-hash-pair to a signature-hash set */\nvoid mbedtls_ssl_sig_hash_set_add( mbedtls_ssl_sig_hash_set_t *set,\n                                   mbedtls_pk_type_t sig_alg,\n                                   mbedtls_md_type_t md_alg )\n{\n    switch( sig_alg )\n    {\n        case MBEDTLS_PK_RSA:\n            if( set->rsa == MBEDTLS_MD_NONE )\n                set->rsa = md_alg;\n            break;\n\n        case MBEDTLS_PK_ECDSA:\n            if( set->ecdsa == MBEDTLS_MD_NONE )\n                set->ecdsa = md_alg;\n            break;\n\n        default:\n            break;\n    }\n}\n\n/* Allow exactly one hash algorithm for each signature. */\nvoid mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set,\n                                          mbedtls_md_type_t md_alg )\n{\n    set->rsa   = md_alg;\n    set->ecdsa = md_alg;\n}\n\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2) &&\n          MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */\n\n/*\n * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX\n */\nmbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash )\n{\n    switch( hash )\n    {\n#if defined(MBEDTLS_MD5_C)\n        case MBEDTLS_SSL_HASH_MD5:\n            return( MBEDTLS_MD_MD5 );\n#endif\n#if defined(MBEDTLS_SHA1_C)\n        case MBEDTLS_SSL_HASH_SHA1:\n            return( MBEDTLS_MD_SHA1 );\n#endif\n#if defined(MBEDTLS_SHA256_C)\n        case MBEDTLS_SSL_HASH_SHA224:\n            return( MBEDTLS_MD_SHA224 );\n        case MBEDTLS_SSL_HASH_SHA256:\n            return( MBEDTLS_MD_SHA256 );\n#endif\n#if defined(MBEDTLS_SHA512_C)\n        case MBEDTLS_SSL_HASH_SHA384:\n            return( MBEDTLS_MD_SHA384 );\n        case MBEDTLS_SSL_HASH_SHA512:\n            return( MBEDTLS_MD_SHA512 );\n#endif\n        default:\n            return( MBEDTLS_MD_NONE );\n    }\n}\n\n/*\n * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX\n */\nunsigned char mbedtls_ssl_hash_from_md_alg( int md )\n{\n    switch( md )\n    {\n#if defined(MBEDTLS_MD5_C)\n        case MBEDTLS_MD_MD5:\n            return( MBEDTLS_SSL_HASH_MD5 );\n#endif\n#if defined(MBEDTLS_SHA1_C)\n        case MBEDTLS_MD_SHA1:\n            return( MBEDTLS_SSL_HASH_SHA1 );\n#endif\n#if defined(MBEDTLS_SHA256_C)\n        case MBEDTLS_MD_SHA224:\n            return( MBEDTLS_SSL_HASH_SHA224 );\n        case MBEDTLS_MD_SHA256:\n            return( MBEDTLS_SSL_HASH_SHA256 );\n#endif\n#if defined(MBEDTLS_SHA512_C)\n        case MBEDTLS_MD_SHA384:\n            return( MBEDTLS_SSL_HASH_SHA384 );\n        case MBEDTLS_MD_SHA512:\n            return( MBEDTLS_SSL_HASH_SHA512 );\n#endif\n        default:\n            return( MBEDTLS_SSL_HASH_NONE );\n    }\n}\n\n#if defined(MBEDTLS_ECP_C)\n/*\n * Check if a curve proposed by the peer is in our list.\n * Return 0 if we're willing to use it, -1 otherwise.\n */\nint mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id )\n{\n    const mbedtls_ecp_group_id *gid;\n\n    if( ssl->conf->curve_list == NULL )\n        return( -1 );\n\n    for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ )\n        if( *gid == grp_id )\n            return( 0 );\n\n    return( -1 );\n}\n#endif /* MBEDTLS_ECP_C */\n\n#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)\n/*\n * Check if a hash proposed by the peer is in our list.\n * Return 0 if we're willing to use it, -1 otherwise.\n */\nint mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl,\n                                mbedtls_md_type_t md )\n{\n    const int *cur;\n\n    if( ssl->conf->sig_hashes == NULL )\n        return( -1 );\n\n    for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ )\n        if( *cur == (int) md )\n            return( 0 );\n\n    return( -1 );\n}\n#endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\nint mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert,\n                          const mbedtls_ssl_ciphersuite_t *ciphersuite,\n                          int cert_endpoint,\n                          uint32_t *flags )\n{\n    int ret = 0;\n#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)\n    int usage = 0;\n#endif\n#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)\n    const char *ext_oid;\n    size_t ext_len;\n#endif\n\n#if !defined(MBEDTLS_X509_CHECK_KEY_USAGE) &&          \\\n    !defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)\n    ((void) cert);\n    ((void) cert_endpoint);\n    ((void) flags);\n#endif\n\n#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)\n    if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )\n    {\n        /* Server part of the key exchange */\n        switch( ciphersuite->key_exchange )\n        {\n            case MBEDTLS_KEY_EXCHANGE_RSA:\n            case MBEDTLS_KEY_EXCHANGE_RSA_PSK:\n                usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT;\n                break;\n\n            case MBEDTLS_KEY_EXCHANGE_DHE_RSA:\n            case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:\n            case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:\n                usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;\n                break;\n\n            case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:\n            case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:\n                usage = MBEDTLS_X509_KU_KEY_AGREEMENT;\n                break;\n\n            /* Don't use default: we want warnings when adding new values */\n            case MBEDTLS_KEY_EXCHANGE_NONE:\n            case MBEDTLS_KEY_EXCHANGE_PSK:\n            case MBEDTLS_KEY_EXCHANGE_DHE_PSK:\n            case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:\n            case MBEDTLS_KEY_EXCHANGE_ECJPAKE:\n                usage = 0;\n        }\n    }\n    else\n    {\n        /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */\n        usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;\n    }\n\n    if( mbedtls_x509_crt_check_key_usage( cert, usage ) != 0 )\n    {\n        *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE;\n        ret = -1;\n    }\n#else\n    ((void) ciphersuite);\n#endif /* MBEDTLS_X509_CHECK_KEY_USAGE */\n\n#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)\n    if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )\n    {\n        ext_oid = MBEDTLS_OID_SERVER_AUTH;\n        ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH );\n    }\n    else\n    {\n        ext_oid = MBEDTLS_OID_CLIENT_AUTH;\n        ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_CLIENT_AUTH );\n    }\n\n    if( mbedtls_x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 )\n    {\n        *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE;\n        ret = -1;\n    }\n#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */\n\n    return( ret );\n}\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n\n/*\n * Convert version numbers to/from wire format\n * and, for DTLS, to/from TLS equivalent.\n *\n * For TLS this is the identity.\n * For DTLS, use 1's complement (v -> 255 - v, and then map as follows:\n * 1.0 <-> 3.2      (DTLS 1.0 is based on TLS 1.1)\n * 1.x <-> 3.x+1    for x != 0 (DTLS 1.2 based on TLS 1.2)\n */\nvoid mbedtls_ssl_write_version( int major, int minor, int transport,\n                        unsigned char ver[2] )\n{\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        if( minor == MBEDTLS_SSL_MINOR_VERSION_2 )\n            --minor; /* DTLS 1.0 stored as TLS 1.1 internally */\n\n        ver[0] = (unsigned char)( 255 - ( major - 2 ) );\n        ver[1] = (unsigned char)( 255 - ( minor - 1 ) );\n    }\n    else\n#else\n    ((void) transport);\n#endif\n    {\n        ver[0] = (unsigned char) major;\n        ver[1] = (unsigned char) minor;\n    }\n}\n\nvoid mbedtls_ssl_read_version( int *major, int *minor, int transport,\n                       const unsigned char ver[2] )\n{\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )\n    {\n        *major = 255 - ver[0] + 2;\n        *minor = 255 - ver[1] + 1;\n\n        if( *minor == MBEDTLS_SSL_MINOR_VERSION_1 )\n            ++*minor; /* DTLS 1.0 stored as TLS 1.1 internally */\n    }\n    else\n#else\n    ((void) transport);\n#endif\n    {\n        *major = ver[0];\n        *minor = ver[1];\n    }\n}\n\nint mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md )\n{\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n    if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )\n        return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;\n\n    switch( md )\n    {\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)\n#if defined(MBEDTLS_MD5_C)\n        case MBEDTLS_SSL_HASH_MD5:\n            return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;\n#endif\n#if defined(MBEDTLS_SHA1_C)\n        case MBEDTLS_SSL_HASH_SHA1:\n            ssl->handshake->calc_verify = ssl_calc_verify_tls;\n            break;\n#endif\n#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */\n#if defined(MBEDTLS_SHA512_C)\n        case MBEDTLS_SSL_HASH_SHA384:\n            ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384;\n            break;\n#endif\n#if defined(MBEDTLS_SHA256_C)\n        case MBEDTLS_SSL_HASH_SHA256:\n            ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256;\n            break;\n#endif\n        default:\n            return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;\n    }\n\n    return 0;\n#else /* !MBEDTLS_SSL_PROTO_TLS1_2 */\n    (void) ssl;\n    (void) md;\n\n    return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n}\n\n#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_1)\nint mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl,\n                                        unsigned char *output,\n                                        unsigned char *data, size_t data_len )\n{\n    int ret = 0;\n    mbedtls_md5_context mbedtls_md5;\n    mbedtls_sha1_context mbedtls_sha1;\n\n    mbedtls_md5_init( &mbedtls_md5 );\n    mbedtls_sha1_init( &mbedtls_sha1 );\n\n    /*\n     * digitally-signed struct {\n     *     opaque md5_hash[16];\n     *     opaque sha_hash[20];\n     * };\n     *\n     * md5_hash\n     *     MD5(ClientHello.random + ServerHello.random\n     *                            + ServerParams);\n     * sha_hash\n     *     SHA(ClientHello.random + ServerHello.random\n     *                            + ServerParams);\n     */\n    if( ( ret = mbedtls_md5_starts_ret( &mbedtls_md5 ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_md5_starts_ret\", ret );\n        goto exit;\n    }\n    if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5,\n                                        ssl->handshake->randbytes, 64 ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_md5_update_ret\", ret );\n        goto exit;\n    }\n    if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5, data, data_len ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_md5_update_ret\", ret );\n        goto exit;\n    }\n    if( ( ret = mbedtls_md5_finish_ret( &mbedtls_md5, output ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_md5_finish_ret\", ret );\n        goto exit;\n    }\n\n    if( ( ret = mbedtls_sha1_starts_ret( &mbedtls_sha1 ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_sha1_starts_ret\", ret );\n        goto exit;\n    }\n    if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1,\n                                         ssl->handshake->randbytes, 64 ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_sha1_update_ret\", ret );\n        goto exit;\n    }\n    if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1, data,\n                                         data_len ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_sha1_update_ret\", ret );\n        goto exit;\n    }\n    if( ( ret = mbedtls_sha1_finish_ret( &mbedtls_sha1,\n                                         output + 16 ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_sha1_finish_ret\", ret );\n        goto exit;\n    }\n\nexit:\n    mbedtls_md5_free( &mbedtls_md5 );\n    mbedtls_sha1_free( &mbedtls_sha1 );\n\n    if( ret != 0 )\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );\n\n    return( ret );\n\n}\n#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \\\n          MBEDTLS_SSL_PROTO_TLS1_1 */\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \\\n    defined(MBEDTLS_SSL_PROTO_TLS1_2)\nint mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,\n                                            unsigned char *hash, size_t *hashlen,\n                                            unsigned char *data, size_t data_len,\n                                            mbedtls_md_type_t md_alg )\n{\n    int ret = 0;\n    mbedtls_md_context_t ctx;\n    const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );\n    *hashlen = mbedtls_md_get_size( md_info );\n\n    mbedtls_md_init( &ctx );\n\n    /*\n     * digitally-signed struct {\n     *     opaque client_random[32];\n     *     opaque server_random[32];\n     *     ServerDHParams params;\n     * };\n     */\n    if( ( ret = mbedtls_md_setup( &ctx, md_info, 0 ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_md_setup\", ret );\n        goto exit;\n    }\n    if( ( ret = mbedtls_md_starts( &ctx ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_md_starts\", ret );\n        goto exit;\n    }\n    if( ( ret = mbedtls_md_update( &ctx, ssl->handshake->randbytes, 64 ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_md_update\", ret );\n        goto exit;\n    }\n    if( ( ret = mbedtls_md_update( &ctx, data, data_len ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_md_update\", ret );\n        goto exit;\n    }\n    if( ( ret = mbedtls_md_finish( &ctx, hash ) ) != 0 )\n    {\n        MBEDTLS_SSL_DEBUG_RET( 1, \"mbedtls_md_finish\", ret );\n        goto exit;\n    }\n\nexit:\n    mbedtls_md_free( &ctx );\n\n    if( ret != 0 )\n        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n                                        MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );\n\n    return( ret );\n}\n#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \\\n          MBEDTLS_SSL_PROTO_TLS1_2 */\n\n#endif /* MBEDTLS_SSL_TLS_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/threading.c",
    "content": "/*\n *  Threading abstraction layer\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_THREADING_C)\n\n#include \"mbedtls/threading.h\"\n\n#if defined(MBEDTLS_THREADING_PTHREAD)\nstatic void threading_mutex_init_pthread( mbedtls_threading_mutex_t *mutex )\n{\n    if( mutex == NULL )\n        return;\n\n    mutex->is_valid = pthread_mutex_init( &mutex->mutex, NULL ) == 0;\n}\n\nstatic void threading_mutex_free_pthread( mbedtls_threading_mutex_t *mutex )\n{\n    if( mutex == NULL || !mutex->is_valid )\n        return;\n\n    (void) pthread_mutex_destroy( &mutex->mutex );\n    mutex->is_valid = 0;\n}\n\nstatic int threading_mutex_lock_pthread( mbedtls_threading_mutex_t *mutex )\n{\n    if( mutex == NULL || ! mutex->is_valid )\n        return( MBEDTLS_ERR_THREADING_BAD_INPUT_DATA );\n\n    if( pthread_mutex_lock( &mutex->mutex ) != 0 )\n        return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );\n\n    return( 0 );\n}\n\nstatic int threading_mutex_unlock_pthread( mbedtls_threading_mutex_t *mutex )\n{\n    if( mutex == NULL || ! mutex->is_valid )\n        return( MBEDTLS_ERR_THREADING_BAD_INPUT_DATA );\n\n    if( pthread_mutex_unlock( &mutex->mutex ) != 0 )\n        return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );\n\n    return( 0 );\n}\n\nvoid (*mbedtls_mutex_init)( mbedtls_threading_mutex_t * ) = threading_mutex_init_pthread;\nvoid (*mbedtls_mutex_free)( mbedtls_threading_mutex_t * ) = threading_mutex_free_pthread;\nint (*mbedtls_mutex_lock)( mbedtls_threading_mutex_t * ) = threading_mutex_lock_pthread;\nint (*mbedtls_mutex_unlock)( mbedtls_threading_mutex_t * ) = threading_mutex_unlock_pthread;\n\n/*\n * With phtreads we can statically initialize mutexes\n */\n#define MUTEX_INIT  = { PTHREAD_MUTEX_INITIALIZER, 1 }\n\n#endif /* MBEDTLS_THREADING_PTHREAD */\n\n#if defined(MBEDTLS_THREADING_ALT)\nstatic int threading_mutex_fail( mbedtls_threading_mutex_t *mutex )\n{\n    ((void) mutex );\n    return( MBEDTLS_ERR_THREADING_BAD_INPUT_DATA );\n}\nstatic void threading_mutex_dummy( mbedtls_threading_mutex_t *mutex )\n{\n    ((void) mutex );\n    return;\n}\n\nvoid (*mbedtls_mutex_init)( mbedtls_threading_mutex_t * ) = threading_mutex_dummy;\nvoid (*mbedtls_mutex_free)( mbedtls_threading_mutex_t * ) = threading_mutex_dummy;\nint (*mbedtls_mutex_lock)( mbedtls_threading_mutex_t * ) = threading_mutex_fail;\nint (*mbedtls_mutex_unlock)( mbedtls_threading_mutex_t * ) = threading_mutex_fail;\n\n/*\n * Set functions pointers and initialize global mutexes\n */\nvoid mbedtls_threading_set_alt( void (*mutex_init)( mbedtls_threading_mutex_t * ),\n                       void (*mutex_free)( mbedtls_threading_mutex_t * ),\n                       int (*mutex_lock)( mbedtls_threading_mutex_t * ),\n                       int (*mutex_unlock)( mbedtls_threading_mutex_t * ) )\n{\n    mbedtls_mutex_init = mutex_init;\n    mbedtls_mutex_free = mutex_free;\n    mbedtls_mutex_lock = mutex_lock;\n    mbedtls_mutex_unlock = mutex_unlock;\n\n#if defined(MBEDTLS_FS_IO)\n    mbedtls_mutex_init( &mbedtls_threading_readdir_mutex );\n#endif\n}\n\n/*\n * Free global mutexes\n */\nvoid mbedtls_threading_free_alt( void )\n{\n#if defined(MBEDTLS_FS_IO)\n    mbedtls_mutex_free( &mbedtls_threading_readdir_mutex );\n#endif\n}\n#endif /* MBEDTLS_THREADING_ALT */\n\n/*\n * Define global mutexes\n */\n#ifndef MUTEX_INIT\n#define MUTEX_INIT\n#endif\n#if defined(MBEDTLS_FS_IO)\nmbedtls_threading_mutex_t mbedtls_threading_readdir_mutex MUTEX_INIT;\n#endif\n\n#endif /* MBEDTLS_THREADING_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/timing.c",
    "content": "/*\n *  Portable interface to the CPU cycle counter\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf     printf\n#endif\n\n#if defined(MBEDTLS_TIMING_C)\n\n#include \"mbedtls/timing.h\"\n\n#if !defined(MBEDTLS_TIMING_ALT)\n\n#if !defined(unix) && !defined(__unix__) && !defined(__unix) && \\\n    !defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) && \\\n    !defined(__HAIKU__)\n#error \"This module only works on Unix and Windows, see MBEDTLS_TIMING_C in config.h\"\n#endif\n\n#ifndef asm\n#define asm __asm\n#endif\n\n#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)\n\n#include <windows.h>\n#include <winbase.h>\n\nstruct _hr_time\n{\n    LARGE_INTEGER start;\n};\n\n#else\n\n#include <unistd.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <signal.h>\n#include <time.h>\n\nstruct _hr_time\n{\n    struct timeval start;\n};\n\n#endif /* _WIN32 && !EFIX64 && !EFI32 */\n\n#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) &&  \\\n    ( defined(_MSC_VER) && defined(_M_IX86) ) || defined(__WATCOMC__)\n\n#define HAVE_HARDCLOCK\n\nunsigned long mbedtls_timing_hardclock( void )\n{\n    unsigned long tsc;\n    __asm   rdtsc\n    __asm   mov  [tsc], eax\n    return( tsc );\n}\n#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&\n          ( _MSC_VER && _M_IX86 ) || __WATCOMC__ */\n\n/* some versions of mingw-64 have 32-bit longs even on x84_64 */\n#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) &&  \\\n    defined(__GNUC__) && ( defined(__i386__) || (                       \\\n    ( defined(__amd64__) || defined( __x86_64__) ) && __SIZEOF_LONG__ == 4 ) )\n\n#define HAVE_HARDCLOCK\n\nunsigned long mbedtls_timing_hardclock( void )\n{\n    unsigned long lo, hi;\n    asm volatile( \"rdtsc\" : \"=a\" (lo), \"=d\" (hi) );\n    return( lo );\n}\n#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&\n          __GNUC__ && __i386__ */\n\n#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) &&  \\\n    defined(__GNUC__) && ( defined(__amd64__) || defined(__x86_64__) )\n\n#define HAVE_HARDCLOCK\n\nunsigned long mbedtls_timing_hardclock( void )\n{\n    unsigned long lo, hi;\n    asm volatile( \"rdtsc\" : \"=a\" (lo), \"=d\" (hi) );\n    return( lo | ( hi << 32 ) );\n}\n#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&\n          __GNUC__ && ( __amd64__ || __x86_64__ ) */\n\n#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) &&  \\\n    defined(__GNUC__) && ( defined(__powerpc__) || defined(__ppc__) )\n\n#define HAVE_HARDCLOCK\n\nunsigned long mbedtls_timing_hardclock( void )\n{\n    unsigned long tbl, tbu0, tbu1;\n\n    do\n    {\n        asm volatile( \"mftbu %0\" : \"=r\" (tbu0) );\n        asm volatile( \"mftb  %0\" : \"=r\" (tbl ) );\n        asm volatile( \"mftbu %0\" : \"=r\" (tbu1) );\n    }\n    while( tbu0 != tbu1 );\n\n    return( tbl );\n}\n#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&\n          __GNUC__ && ( __powerpc__ || __ppc__ ) */\n\n#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) &&  \\\n    defined(__GNUC__) && defined(__sparc64__)\n\n#if defined(__OpenBSD__)\n#warning OpenBSD does not allow access to tick register using software version instead\n#else\n#define HAVE_HARDCLOCK\n\nunsigned long mbedtls_timing_hardclock( void )\n{\n    unsigned long tick;\n    asm volatile( \"rdpr %%tick, %0;\" : \"=&r\" (tick) );\n    return( tick );\n}\n#endif /* __OpenBSD__ */\n#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&\n          __GNUC__ && __sparc64__ */\n\n#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) &&  \\\n    defined(__GNUC__) && defined(__sparc__) && !defined(__sparc64__)\n\n#define HAVE_HARDCLOCK\n\nunsigned long mbedtls_timing_hardclock( void )\n{\n    unsigned long tick;\n    asm volatile( \".byte 0x83, 0x41, 0x00, 0x00\" );\n    asm volatile( \"mov   %%g1, %0\" : \"=r\" (tick) );\n    return( tick );\n}\n#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&\n          __GNUC__ && __sparc__ && !__sparc64__ */\n\n#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) &&      \\\n    defined(__GNUC__) && defined(__alpha__)\n\n#define HAVE_HARDCLOCK\n\nunsigned long mbedtls_timing_hardclock( void )\n{\n    unsigned long cc;\n    asm volatile( \"rpcc %0\" : \"=r\" (cc) );\n    return( cc & 0xFFFFFFFF );\n}\n#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&\n          __GNUC__ && __alpha__ */\n\n#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) &&      \\\n    defined(__GNUC__) && defined(__ia64__)\n\n#define HAVE_HARDCLOCK\n\nunsigned long mbedtls_timing_hardclock( void )\n{\n    unsigned long itc;\n    asm volatile( \"mov %0 = ar.itc\" : \"=r\" (itc) );\n    return( itc );\n}\n#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&\n          __GNUC__ && __ia64__ */\n\n#if !defined(HAVE_HARDCLOCK) && defined(_MSC_VER) && \\\n    !defined(EFIX64) && !defined(EFI32)\n\n#define HAVE_HARDCLOCK\n\nunsigned long mbedtls_timing_hardclock( void )\n{\n    LARGE_INTEGER offset;\n\n    QueryPerformanceCounter( &offset );\n\n    return( (unsigned long)( offset.QuadPart ) );\n}\n#endif /* !HAVE_HARDCLOCK && _MSC_VER && !EFIX64 && !EFI32 */\n\n#if !defined(HAVE_HARDCLOCK)\n\n#define HAVE_HARDCLOCK\n\nstatic int hardclock_init = 0;\nstatic struct timeval tv_init;\n\nunsigned long mbedtls_timing_hardclock( void )\n{\n    struct timeval tv_cur;\n\n    if( hardclock_init == 0 )\n    {\n        gettimeofday( &tv_init, NULL );\n        hardclock_init = 1;\n    }\n\n    gettimeofday( &tv_cur, NULL );\n    return( ( tv_cur.tv_sec  - tv_init.tv_sec  ) * 1000000\n          + ( tv_cur.tv_usec - tv_init.tv_usec ) );\n}\n#endif /* !HAVE_HARDCLOCK */\n\nvolatile int mbedtls_timing_alarmed = 0;\n\n#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)\n\nunsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset )\n{\n    struct _hr_time *t = (struct _hr_time *) val;\n\n    if( reset )\n    {\n        QueryPerformanceCounter( &t->start );\n        return( 0 );\n    }\n    else\n    {\n        unsigned long delta;\n        LARGE_INTEGER now, hfreq;\n        QueryPerformanceCounter(  &now );\n        QueryPerformanceFrequency( &hfreq );\n        delta = (unsigned long)( ( now.QuadPart - t->start.QuadPart ) * 1000ul\n                                 / hfreq.QuadPart );\n        return( delta );\n    }\n}\n\n/* It's OK to use a global because alarm() is supposed to be global anyway */\nstatic DWORD alarmMs;\n\nstatic DWORD WINAPI TimerProc( LPVOID TimerContext )\n{\n    ((void) TimerContext);\n    Sleep( alarmMs );\n    mbedtls_timing_alarmed = 1;\n    return( TRUE );\n}\n\nvoid mbedtls_set_alarm( int seconds )\n{\n    DWORD ThreadId;\n\n    if( seconds == 0 )\n    {\n        /* No need to create a thread for this simple case.\n         * Also, this shorcut is more reliable at least on MinGW32 */\n        mbedtls_timing_alarmed = 1;\n        return;\n    }\n\n    mbedtls_timing_alarmed = 0;\n    alarmMs = seconds * 1000;\n    CloseHandle( CreateThread( NULL, 0, TimerProc, NULL, 0, &ThreadId ) );\n}\n\n#else /* _WIN32 && !EFIX64 && !EFI32 */\n\nunsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset )\n{\n    struct _hr_time *t = (struct _hr_time *) val;\n\n    if( reset )\n    {\n        gettimeofday( &t->start, NULL );\n        return( 0 );\n    }\n    else\n    {\n        unsigned long delta;\n        struct timeval now;\n        gettimeofday( &now, NULL );\n        delta = ( now.tv_sec  - t->start.tv_sec  ) * 1000ul\n              + ( now.tv_usec - t->start.tv_usec ) / 1000;\n        return( delta );\n    }\n}\n\nstatic void sighandler( int signum )\n{\n    mbedtls_timing_alarmed = 1;\n    signal( signum, sighandler );\n}\n\nvoid mbedtls_set_alarm( int seconds )\n{\n    mbedtls_timing_alarmed = 0;\n    signal( SIGALRM, sighandler );\n    alarm( seconds );\n    if( seconds == 0 )\n    {\n        /* alarm(0) cancelled any previous pending alarm, but the\n           handler won't fire, so raise the flag straight away. */\n        mbedtls_timing_alarmed = 1;\n    }\n}\n\n#endif /* _WIN32 && !EFIX64 && !EFI32 */\n\n/*\n * Set delays to watch\n */\nvoid mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms )\n{\n    mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data;\n\n    ctx->int_ms = int_ms;\n    ctx->fin_ms = fin_ms;\n\n    if( fin_ms != 0 )\n        (void) mbedtls_timing_get_timer( &ctx->timer, 1 );\n}\n\n/*\n * Get number of delays expired\n */\nint mbedtls_timing_get_delay( void *data )\n{\n    mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data;\n    unsigned long elapsed_ms;\n\n    if( ctx->fin_ms == 0 )\n        return( -1 );\n\n    elapsed_ms = mbedtls_timing_get_timer( &ctx->timer, 0 );\n\n    if( elapsed_ms >= ctx->fin_ms )\n        return( 2 );\n\n    if( elapsed_ms >= ctx->int_ms )\n        return( 1 );\n\n    return( 0 );\n}\n\n#endif /* !MBEDTLS_TIMING_ALT */\n\n#if defined(MBEDTLS_SELF_TEST)\n\n/*\n * Busy-waits for the given number of milliseconds.\n * Used for testing mbedtls_timing_hardclock.\n */\nstatic void busy_msleep( unsigned long msec )\n{\n    struct mbedtls_timing_hr_time hires;\n    unsigned long i = 0; /* for busy-waiting */\n    volatile unsigned long j; /* to prevent optimisation */\n\n    (void) mbedtls_timing_get_timer( &hires, 1 );\n\n    while( mbedtls_timing_get_timer( &hires, 0 ) < msec )\n        i++;\n\n    j = i;\n    (void) j;\n}\n\n#define FAIL    do                                                      \\\n    {                                                                   \\\n        if( verbose != 0 )                                              \\\n        {                                                               \\\n            mbedtls_printf( \"failed at line %d\\n\", __LINE__ );          \\\n            mbedtls_printf( \" cycles=%lu ratio=%lu millisecs=%lu secs=%lu hardfail=%d a=%lu b=%lu\\n\", \\\n                            cycles, ratio, millisecs, secs, hardfail,   \\\n                            (unsigned long) a, (unsigned long) b );     \\\n            mbedtls_printf( \" elapsed(hires)=%lu elapsed(ctx)=%lu status(ctx)=%d\\n\", \\\n                            mbedtls_timing_get_timer( &hires, 0 ),      \\\n                            mbedtls_timing_get_timer( &ctx.timer, 0 ),  \\\n                            mbedtls_timing_get_delay( &ctx ) );         \\\n        }                                                               \\\n        return( 1 );                                                    \\\n    } while( 0 )\n\n/*\n * Checkup routine\n *\n * Warning: this is work in progress, some tests may not be reliable enough\n * yet! False positives may happen.\n */\nint mbedtls_timing_self_test( int verbose )\n{\n    unsigned long cycles = 0, ratio = 0;\n    unsigned long millisecs = 0, secs = 0;\n    int hardfail = 0;\n    struct mbedtls_timing_hr_time hires;\n    uint32_t a = 0, b = 0;\n    mbedtls_timing_delay_context ctx;\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  TIMING tests note: will take some time!\\n\" );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  TIMING test #1 (set_alarm / get_timer): \" );\n\n    {\n        secs = 1;\n\n        (void) mbedtls_timing_get_timer( &hires, 1 );\n\n        mbedtls_set_alarm( (int) secs );\n        while( !mbedtls_timing_alarmed )\n            ;\n\n        millisecs = mbedtls_timing_get_timer( &hires, 0 );\n\n        /* For some reason on Windows it looks like alarm has an extra delay\n         * (maybe related to creating a new thread). Allow some room here. */\n        if( millisecs < 800 * secs || millisecs > 1200 * secs + 300 )\n            FAIL;\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  TIMING test #2 (set/get_delay        ): \" );\n\n    {\n        a = 800;\n        b = 400;\n        mbedtls_timing_set_delay( &ctx, a, a + b );          /* T = 0 */\n\n        busy_msleep( a - a / 4 );                      /* T = a - a/4 */\n        if( mbedtls_timing_get_delay( &ctx ) != 0 )\n            FAIL;\n\n        busy_msleep( a / 4 + b / 4 );                  /* T = a + b/4 */\n        if( mbedtls_timing_get_delay( &ctx ) != 1 )\n            FAIL;\n\n        busy_msleep( b );                          /* T = a + b + b/4 */\n        if( mbedtls_timing_get_delay( &ctx ) != 2 )\n            FAIL;\n    }\n\n    mbedtls_timing_set_delay( &ctx, 0, 0 );\n    busy_msleep( 200 );\n    if( mbedtls_timing_get_delay( &ctx ) != -1 )\n        FAIL;\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  TIMING test #3 (hardclock / get_timer): \" );\n\n    /*\n     * Allow one failure for possible counter wrapping.\n     * On a 4Ghz 32-bit machine the cycle counter wraps about once per second;\n     * since the whole test is about 10ms, it shouldn't happen twice in a row.\n     */\n\nhard_test:\n    if( hardfail > 1 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed (ignored)\\n\" );\n\n        goto hard_test_done;\n    }\n\n    /* Get a reference ratio cycles/ms */\n    millisecs = 1;\n    cycles = mbedtls_timing_hardclock();\n    busy_msleep( millisecs );\n    cycles = mbedtls_timing_hardclock() - cycles;\n    ratio = cycles / millisecs;\n\n    /* Check that the ratio is mostly constant */\n    for( millisecs = 2; millisecs <= 4; millisecs++ )\n    {\n        cycles = mbedtls_timing_hardclock();\n        busy_msleep( millisecs );\n        cycles = mbedtls_timing_hardclock() - cycles;\n\n        /* Allow variation up to 20% */\n        if( cycles / millisecs < ratio - ratio / 5 ||\n            cycles / millisecs > ratio + ratio / 5 )\n        {\n            hardfail++;\n            goto hard_test;\n        }\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\" );\n\nhard_test_done:\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\n    return( 0 );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_TIMING_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/version.c",
    "content": "/*\n *  Version information\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_VERSION_C)\n\n#include \"mbedtls/version.h\"\n#include <string.h>\n\nunsigned int mbedtls_version_get_number( void )\n{\n    return( MBEDTLS_VERSION_NUMBER );\n}\n\nvoid mbedtls_version_get_string( char *string )\n{\n    memcpy( string, MBEDTLS_VERSION_STRING,\n            sizeof( MBEDTLS_VERSION_STRING ) );\n}\n\nvoid mbedtls_version_get_string_full( char *string )\n{\n    memcpy( string, MBEDTLS_VERSION_STRING_FULL,\n            sizeof( MBEDTLS_VERSION_STRING_FULL ) );\n}\n\n#endif /* MBEDTLS_VERSION_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/version_features.c",
    "content": "/*\n *  Version feature information\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_VERSION_C)\n\n#include \"mbedtls/version.h\"\n\n#include <string.h>\n\nstatic const char *features[] = {\n#if defined(MBEDTLS_VERSION_FEATURES)\n#if defined(MBEDTLS_HAVE_ASM)\n    \"MBEDTLS_HAVE_ASM\",\n#endif /* MBEDTLS_HAVE_ASM */\n#if defined(MBEDTLS_NO_UDBL_DIVISION)\n    \"MBEDTLS_NO_UDBL_DIVISION\",\n#endif /* MBEDTLS_NO_UDBL_DIVISION */\n#if defined(MBEDTLS_NO_64BIT_MULTIPLICATION)\n    \"MBEDTLS_NO_64BIT_MULTIPLICATION\",\n#endif /* MBEDTLS_NO_64BIT_MULTIPLICATION */\n#if defined(MBEDTLS_HAVE_SSE2)\n    \"MBEDTLS_HAVE_SSE2\",\n#endif /* MBEDTLS_HAVE_SSE2 */\n#if defined(MBEDTLS_HAVE_TIME)\n    \"MBEDTLS_HAVE_TIME\",\n#endif /* MBEDTLS_HAVE_TIME */\n#if defined(MBEDTLS_HAVE_TIME_DATE)\n    \"MBEDTLS_HAVE_TIME_DATE\",\n#endif /* MBEDTLS_HAVE_TIME_DATE */\n#if defined(MBEDTLS_PLATFORM_MEMORY)\n    \"MBEDTLS_PLATFORM_MEMORY\",\n#endif /* MBEDTLS_PLATFORM_MEMORY */\n#if defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS)\n    \"MBEDTLS_PLATFORM_NO_STD_FUNCTIONS\",\n#endif /* MBEDTLS_PLATFORM_NO_STD_FUNCTIONS */\n#if defined(MBEDTLS_PLATFORM_EXIT_ALT)\n    \"MBEDTLS_PLATFORM_EXIT_ALT\",\n#endif /* MBEDTLS_PLATFORM_EXIT_ALT */\n#if defined(MBEDTLS_PLATFORM_TIME_ALT)\n    \"MBEDTLS_PLATFORM_TIME_ALT\",\n#endif /* MBEDTLS_PLATFORM_TIME_ALT */\n#if defined(MBEDTLS_PLATFORM_FPRINTF_ALT)\n    \"MBEDTLS_PLATFORM_FPRINTF_ALT\",\n#endif /* MBEDTLS_PLATFORM_FPRINTF_ALT */\n#if defined(MBEDTLS_PLATFORM_PRINTF_ALT)\n    \"MBEDTLS_PLATFORM_PRINTF_ALT\",\n#endif /* MBEDTLS_PLATFORM_PRINTF_ALT */\n#if defined(MBEDTLS_PLATFORM_SNPRINTF_ALT)\n    \"MBEDTLS_PLATFORM_SNPRINTF_ALT\",\n#endif /* MBEDTLS_PLATFORM_SNPRINTF_ALT */\n#if defined(MBEDTLS_PLATFORM_NV_SEED_ALT)\n    \"MBEDTLS_PLATFORM_NV_SEED_ALT\",\n#endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */\n#if defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT)\n    \"MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT\",\n#endif /* MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */\n#if defined(MBEDTLS_DEPRECATED_WARNING)\n    \"MBEDTLS_DEPRECATED_WARNING\",\n#endif /* MBEDTLS_DEPRECATED_WARNING */\n#if defined(MBEDTLS_DEPRECATED_REMOVED)\n    \"MBEDTLS_DEPRECATED_REMOVED\",\n#endif /* MBEDTLS_DEPRECATED_REMOVED */\n#if defined(MBEDTLS_TIMING_ALT)\n    \"MBEDTLS_TIMING_ALT\",\n#endif /* MBEDTLS_TIMING_ALT */\n#if defined(MBEDTLS_AES_ALT)\n    \"MBEDTLS_AES_ALT\",\n#endif /* MBEDTLS_AES_ALT */\n#if defined(MBEDTLS_ARC4_ALT)\n    \"MBEDTLS_ARC4_ALT\",\n#endif /* MBEDTLS_ARC4_ALT */\n#if defined(MBEDTLS_ARIA_ALT)\n    \"MBEDTLS_ARIA_ALT\",\n#endif /* MBEDTLS_ARIA_ALT */\n#if defined(MBEDTLS_BLOWFISH_ALT)\n    \"MBEDTLS_BLOWFISH_ALT\",\n#endif /* MBEDTLS_BLOWFISH_ALT */\n#if defined(MBEDTLS_CAMELLIA_ALT)\n    \"MBEDTLS_CAMELLIA_ALT\",\n#endif /* MBEDTLS_CAMELLIA_ALT */\n#if defined(MBEDTLS_CCM_ALT)\n    \"MBEDTLS_CCM_ALT\",\n#endif /* MBEDTLS_CCM_ALT */\n#if defined(MBEDTLS_CHACHA20_ALT)\n    \"MBEDTLS_CHACHA20_ALT\",\n#endif /* MBEDTLS_CHACHA20_ALT */\n#if defined(MBEDTLS_CHACHAPOLY_ALT)\n    \"MBEDTLS_CHACHAPOLY_ALT\",\n#endif /* MBEDTLS_CHACHAPOLY_ALT */\n#if defined(MBEDTLS_CMAC_ALT)\n    \"MBEDTLS_CMAC_ALT\",\n#endif /* MBEDTLS_CMAC_ALT */\n#if defined(MBEDTLS_DES_ALT)\n    \"MBEDTLS_DES_ALT\",\n#endif /* MBEDTLS_DES_ALT */\n#if defined(MBEDTLS_DHM_ALT)\n    \"MBEDTLS_DHM_ALT\",\n#endif /* MBEDTLS_DHM_ALT */\n#if defined(MBEDTLS_ECJPAKE_ALT)\n    \"MBEDTLS_ECJPAKE_ALT\",\n#endif /* MBEDTLS_ECJPAKE_ALT */\n#if defined(MBEDTLS_GCM_ALT)\n    \"MBEDTLS_GCM_ALT\",\n#endif /* MBEDTLS_GCM_ALT */\n#if defined(MBEDTLS_NIST_KW_ALT)\n    \"MBEDTLS_NIST_KW_ALT\",\n#endif /* MBEDTLS_NIST_KW_ALT */\n#if defined(MBEDTLS_MD2_ALT)\n    \"MBEDTLS_MD2_ALT\",\n#endif /* MBEDTLS_MD2_ALT */\n#if defined(MBEDTLS_MD4_ALT)\n    \"MBEDTLS_MD4_ALT\",\n#endif /* MBEDTLS_MD4_ALT */\n#if defined(MBEDTLS_MD5_ALT)\n    \"MBEDTLS_MD5_ALT\",\n#endif /* MBEDTLS_MD5_ALT */\n#if defined(MBEDTLS_POLY1305_ALT)\n    \"MBEDTLS_POLY1305_ALT\",\n#endif /* MBEDTLS_POLY1305_ALT */\n#if defined(MBEDTLS_RIPEMD160_ALT)\n    \"MBEDTLS_RIPEMD160_ALT\",\n#endif /* MBEDTLS_RIPEMD160_ALT */\n#if defined(MBEDTLS_RSA_ALT)\n    \"MBEDTLS_RSA_ALT\",\n#endif /* MBEDTLS_RSA_ALT */\n#if defined(MBEDTLS_SHA1_ALT)\n    \"MBEDTLS_SHA1_ALT\",\n#endif /* MBEDTLS_SHA1_ALT */\n#if defined(MBEDTLS_SHA256_ALT)\n    \"MBEDTLS_SHA256_ALT\",\n#endif /* MBEDTLS_SHA256_ALT */\n#if defined(MBEDTLS_SHA512_ALT)\n    \"MBEDTLS_SHA512_ALT\",\n#endif /* MBEDTLS_SHA512_ALT */\n#if defined(MBEDTLS_XTEA_ALT)\n    \"MBEDTLS_XTEA_ALT\",\n#endif /* MBEDTLS_XTEA_ALT */\n#if defined(MBEDTLS_ECP_ALT)\n    \"MBEDTLS_ECP_ALT\",\n#endif /* MBEDTLS_ECP_ALT */\n#if defined(MBEDTLS_MD2_PROCESS_ALT)\n    \"MBEDTLS_MD2_PROCESS_ALT\",\n#endif /* MBEDTLS_MD2_PROCESS_ALT */\n#if defined(MBEDTLS_MD4_PROCESS_ALT)\n    \"MBEDTLS_MD4_PROCESS_ALT\",\n#endif /* MBEDTLS_MD4_PROCESS_ALT */\n#if defined(MBEDTLS_MD5_PROCESS_ALT)\n    \"MBEDTLS_MD5_PROCESS_ALT\",\n#endif /* MBEDTLS_MD5_PROCESS_ALT */\n#if defined(MBEDTLS_RIPEMD160_PROCESS_ALT)\n    \"MBEDTLS_RIPEMD160_PROCESS_ALT\",\n#endif /* MBEDTLS_RIPEMD160_PROCESS_ALT */\n#if defined(MBEDTLS_SHA1_PROCESS_ALT)\n    \"MBEDTLS_SHA1_PROCESS_ALT\",\n#endif /* MBEDTLS_SHA1_PROCESS_ALT */\n#if defined(MBEDTLS_SHA256_PROCESS_ALT)\n    \"MBEDTLS_SHA256_PROCESS_ALT\",\n#endif /* MBEDTLS_SHA256_PROCESS_ALT */\n#if defined(MBEDTLS_SHA512_PROCESS_ALT)\n    \"MBEDTLS_SHA512_PROCESS_ALT\",\n#endif /* MBEDTLS_SHA512_PROCESS_ALT */\n#if defined(MBEDTLS_DES_SETKEY_ALT)\n    \"MBEDTLS_DES_SETKEY_ALT\",\n#endif /* MBEDTLS_DES_SETKEY_ALT */\n#if defined(MBEDTLS_DES_CRYPT_ECB_ALT)\n    \"MBEDTLS_DES_CRYPT_ECB_ALT\",\n#endif /* MBEDTLS_DES_CRYPT_ECB_ALT */\n#if defined(MBEDTLS_DES3_CRYPT_ECB_ALT)\n    \"MBEDTLS_DES3_CRYPT_ECB_ALT\",\n#endif /* MBEDTLS_DES3_CRYPT_ECB_ALT */\n#if defined(MBEDTLS_AES_SETKEY_ENC_ALT)\n    \"MBEDTLS_AES_SETKEY_ENC_ALT\",\n#endif /* MBEDTLS_AES_SETKEY_ENC_ALT */\n#if defined(MBEDTLS_AES_SETKEY_DEC_ALT)\n    \"MBEDTLS_AES_SETKEY_DEC_ALT\",\n#endif /* MBEDTLS_AES_SETKEY_DEC_ALT */\n#if defined(MBEDTLS_AES_ENCRYPT_ALT)\n    \"MBEDTLS_AES_ENCRYPT_ALT\",\n#endif /* MBEDTLS_AES_ENCRYPT_ALT */\n#if defined(MBEDTLS_AES_DECRYPT_ALT)\n    \"MBEDTLS_AES_DECRYPT_ALT\",\n#endif /* MBEDTLS_AES_DECRYPT_ALT */\n#if defined(MBEDTLS_ECDH_GEN_PUBLIC_ALT)\n    \"MBEDTLS_ECDH_GEN_PUBLIC_ALT\",\n#endif /* MBEDTLS_ECDH_GEN_PUBLIC_ALT */\n#if defined(MBEDTLS_ECDH_COMPUTE_SHARED_ALT)\n    \"MBEDTLS_ECDH_COMPUTE_SHARED_ALT\",\n#endif /* MBEDTLS_ECDH_COMPUTE_SHARED_ALT */\n#if defined(MBEDTLS_ECDSA_VERIFY_ALT)\n    \"MBEDTLS_ECDSA_VERIFY_ALT\",\n#endif /* MBEDTLS_ECDSA_VERIFY_ALT */\n#if defined(MBEDTLS_ECDSA_SIGN_ALT)\n    \"MBEDTLS_ECDSA_SIGN_ALT\",\n#endif /* MBEDTLS_ECDSA_SIGN_ALT */\n#if defined(MBEDTLS_ECDSA_GENKEY_ALT)\n    \"MBEDTLS_ECDSA_GENKEY_ALT\",\n#endif /* MBEDTLS_ECDSA_GENKEY_ALT */\n#if defined(MBEDTLS_ECP_INTERNAL_ALT)\n    \"MBEDTLS_ECP_INTERNAL_ALT\",\n#endif /* MBEDTLS_ECP_INTERNAL_ALT */\n#if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT)\n    \"MBEDTLS_ECP_RANDOMIZE_JAC_ALT\",\n#endif /* MBEDTLS_ECP_RANDOMIZE_JAC_ALT */\n#if defined(MBEDTLS_ECP_ADD_MIXED_ALT)\n    \"MBEDTLS_ECP_ADD_MIXED_ALT\",\n#endif /* MBEDTLS_ECP_ADD_MIXED_ALT */\n#if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT)\n    \"MBEDTLS_ECP_DOUBLE_JAC_ALT\",\n#endif /* MBEDTLS_ECP_DOUBLE_JAC_ALT */\n#if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT)\n    \"MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT\",\n#endif /* MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT */\n#if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT)\n    \"MBEDTLS_ECP_NORMALIZE_JAC_ALT\",\n#endif /* MBEDTLS_ECP_NORMALIZE_JAC_ALT */\n#if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT)\n    \"MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT\",\n#endif /* MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT */\n#if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT)\n    \"MBEDTLS_ECP_RANDOMIZE_MXZ_ALT\",\n#endif /* MBEDTLS_ECP_RANDOMIZE_MXZ_ALT */\n#if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)\n    \"MBEDTLS_ECP_NORMALIZE_MXZ_ALT\",\n#endif /* MBEDTLS_ECP_NORMALIZE_MXZ_ALT */\n#if defined(MBEDTLS_TEST_NULL_ENTROPY)\n    \"MBEDTLS_TEST_NULL_ENTROPY\",\n#endif /* MBEDTLS_TEST_NULL_ENTROPY */\n#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)\n    \"MBEDTLS_ENTROPY_HARDWARE_ALT\",\n#endif /* MBEDTLS_ENTROPY_HARDWARE_ALT */\n#if defined(MBEDTLS_AES_ROM_TABLES)\n    \"MBEDTLS_AES_ROM_TABLES\",\n#endif /* MBEDTLS_AES_ROM_TABLES */\n#if defined(MBEDTLS_AES_FEWER_TABLES)\n    \"MBEDTLS_AES_FEWER_TABLES\",\n#endif /* MBEDTLS_AES_FEWER_TABLES */\n#if defined(MBEDTLS_CAMELLIA_SMALL_MEMORY)\n    \"MBEDTLS_CAMELLIA_SMALL_MEMORY\",\n#endif /* MBEDTLS_CAMELLIA_SMALL_MEMORY */\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n    \"MBEDTLS_CIPHER_MODE_CBC\",\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#if defined(MBEDTLS_CIPHER_MODE_CFB)\n    \"MBEDTLS_CIPHER_MODE_CFB\",\n#endif /* MBEDTLS_CIPHER_MODE_CFB */\n#if defined(MBEDTLS_CIPHER_MODE_CTR)\n    \"MBEDTLS_CIPHER_MODE_CTR\",\n#endif /* MBEDTLS_CIPHER_MODE_CTR */\n#if defined(MBEDTLS_CIPHER_MODE_OFB)\n    \"MBEDTLS_CIPHER_MODE_OFB\",\n#endif /* MBEDTLS_CIPHER_MODE_OFB */\n#if defined(MBEDTLS_CIPHER_MODE_XTS)\n    \"MBEDTLS_CIPHER_MODE_XTS\",\n#endif /* MBEDTLS_CIPHER_MODE_XTS */\n#if defined(MBEDTLS_CIPHER_NULL_CIPHER)\n    \"MBEDTLS_CIPHER_NULL_CIPHER\",\n#endif /* MBEDTLS_CIPHER_NULL_CIPHER */\n#if defined(MBEDTLS_CIPHER_PADDING_PKCS7)\n    \"MBEDTLS_CIPHER_PADDING_PKCS7\",\n#endif /* MBEDTLS_CIPHER_PADDING_PKCS7 */\n#if defined(MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS)\n    \"MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS\",\n#endif /* MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS */\n#if defined(MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN)\n    \"MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN\",\n#endif /* MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN */\n#if defined(MBEDTLS_CIPHER_PADDING_ZEROS)\n    \"MBEDTLS_CIPHER_PADDING_ZEROS\",\n#endif /* MBEDTLS_CIPHER_PADDING_ZEROS */\n#if defined(MBEDTLS_ENABLE_WEAK_CIPHERSUITES)\n    \"MBEDTLS_ENABLE_WEAK_CIPHERSUITES\",\n#endif /* MBEDTLS_ENABLE_WEAK_CIPHERSUITES */\n#if defined(MBEDTLS_REMOVE_ARC4_CIPHERSUITES)\n    \"MBEDTLS_REMOVE_ARC4_CIPHERSUITES\",\n#endif /* MBEDTLS_REMOVE_ARC4_CIPHERSUITES */\n#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)\n    \"MBEDTLS_ECP_DP_SECP192R1_ENABLED\",\n#endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)\n    \"MBEDTLS_ECP_DP_SECP224R1_ENABLED\",\n#endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)\n    \"MBEDTLS_ECP_DP_SECP256R1_ENABLED\",\n#endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)\n    \"MBEDTLS_ECP_DP_SECP384R1_ENABLED\",\n#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)\n    \"MBEDTLS_ECP_DP_SECP521R1_ENABLED\",\n#endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)\n    \"MBEDTLS_ECP_DP_SECP192K1_ENABLED\",\n#endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)\n    \"MBEDTLS_ECP_DP_SECP224K1_ENABLED\",\n#endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)\n    \"MBEDTLS_ECP_DP_SECP256K1_ENABLED\",\n#endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)\n    \"MBEDTLS_ECP_DP_BP256R1_ENABLED\",\n#endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)\n    \"MBEDTLS_ECP_DP_BP384R1_ENABLED\",\n#endif /* MBEDTLS_ECP_DP_BP384R1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)\n    \"MBEDTLS_ECP_DP_BP512R1_ENABLED\",\n#endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */\n#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)\n    \"MBEDTLS_ECP_DP_CURVE25519_ENABLED\",\n#endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */\n#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)\n    \"MBEDTLS_ECP_DP_CURVE448_ENABLED\",\n#endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */\n#if defined(MBEDTLS_ECP_NIST_OPTIM)\n    \"MBEDTLS_ECP_NIST_OPTIM\",\n#endif /* MBEDTLS_ECP_NIST_OPTIM */\n#if defined(MBEDTLS_ECDSA_DETERMINISTIC)\n    \"MBEDTLS_ECDSA_DETERMINISTIC\",\n#endif /* MBEDTLS_ECDSA_DETERMINISTIC */\n#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)\n    \"MBEDTLS_KEY_EXCHANGE_PSK_ENABLED\",\n#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)\n    \"MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED\",\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)\n    \"MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED\",\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)\n    \"MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED\",\n#endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)\n    \"MBEDTLS_KEY_EXCHANGE_RSA_ENABLED\",\n#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)\n    \"MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED\",\n#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)\n    \"MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED\",\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)\n    \"MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED\",\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)\n    \"MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED\",\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)\n    \"MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED\",\n#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED */\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n    \"MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED\",\n#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */\n#if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)\n    \"MBEDTLS_PK_PARSE_EC_EXTENDED\",\n#endif /* MBEDTLS_PK_PARSE_EC_EXTENDED */\n#if defined(MBEDTLS_ERROR_STRERROR_DUMMY)\n    \"MBEDTLS_ERROR_STRERROR_DUMMY\",\n#endif /* MBEDTLS_ERROR_STRERROR_DUMMY */\n#if defined(MBEDTLS_GENPRIME)\n    \"MBEDTLS_GENPRIME\",\n#endif /* MBEDTLS_GENPRIME */\n#if defined(MBEDTLS_FS_IO)\n    \"MBEDTLS_FS_IO\",\n#endif /* MBEDTLS_FS_IO */\n#if defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES)\n    \"MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES\",\n#endif /* MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES */\n#if defined(MBEDTLS_NO_PLATFORM_ENTROPY)\n    \"MBEDTLS_NO_PLATFORM_ENTROPY\",\n#endif /* MBEDTLS_NO_PLATFORM_ENTROPY */\n#if defined(MBEDTLS_ENTROPY_FORCE_SHA256)\n    \"MBEDTLS_ENTROPY_FORCE_SHA256\",\n#endif /* MBEDTLS_ENTROPY_FORCE_SHA256 */\n#if defined(MBEDTLS_ENTROPY_NV_SEED)\n    \"MBEDTLS_ENTROPY_NV_SEED\",\n#endif /* MBEDTLS_ENTROPY_NV_SEED */\n#if defined(MBEDTLS_MEMORY_DEBUG)\n    \"MBEDTLS_MEMORY_DEBUG\",\n#endif /* MBEDTLS_MEMORY_DEBUG */\n#if defined(MBEDTLS_MEMORY_BACKTRACE)\n    \"MBEDTLS_MEMORY_BACKTRACE\",\n#endif /* MBEDTLS_MEMORY_BACKTRACE */\n#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)\n    \"MBEDTLS_PK_RSA_ALT_SUPPORT\",\n#endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */\n#if defined(MBEDTLS_PKCS1_V15)\n    \"MBEDTLS_PKCS1_V15\",\n#endif /* MBEDTLS_PKCS1_V15 */\n#if defined(MBEDTLS_PKCS1_V21)\n    \"MBEDTLS_PKCS1_V21\",\n#endif /* MBEDTLS_PKCS1_V21 */\n#if defined(MBEDTLS_RSA_NO_CRT)\n    \"MBEDTLS_RSA_NO_CRT\",\n#endif /* MBEDTLS_RSA_NO_CRT */\n#if defined(MBEDTLS_SELF_TEST)\n    \"MBEDTLS_SELF_TEST\",\n#endif /* MBEDTLS_SELF_TEST */\n#if defined(MBEDTLS_SHA256_SMALLER)\n    \"MBEDTLS_SHA256_SMALLER\",\n#endif /* MBEDTLS_SHA256_SMALLER */\n#if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)\n    \"MBEDTLS_SSL_ALL_ALERT_MESSAGES\",\n#endif /* MBEDTLS_SSL_ALL_ALERT_MESSAGES */\n#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)\n    \"MBEDTLS_SSL_ASYNC_PRIVATE\",\n#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */\n#if defined(MBEDTLS_SSL_DEBUG_ALL)\n    \"MBEDTLS_SSL_DEBUG_ALL\",\n#endif /* MBEDTLS_SSL_DEBUG_ALL */\n#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)\n    \"MBEDTLS_SSL_ENCRYPT_THEN_MAC\",\n#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */\n#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)\n    \"MBEDTLS_SSL_EXTENDED_MASTER_SECRET\",\n#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */\n#if defined(MBEDTLS_SSL_FALLBACK_SCSV)\n    \"MBEDTLS_SSL_FALLBACK_SCSV\",\n#endif /* MBEDTLS_SSL_FALLBACK_SCSV */\n#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)\n    \"MBEDTLS_SSL_HW_RECORD_ACCEL\",\n#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */\n#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)\n    \"MBEDTLS_SSL_CBC_RECORD_SPLITTING\",\n#endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */\n#if defined(MBEDTLS_SSL_RENEGOTIATION)\n    \"MBEDTLS_SSL_RENEGOTIATION\",\n#endif /* MBEDTLS_SSL_RENEGOTIATION */\n#if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO)\n    \"MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO\",\n#endif /* MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO */\n#if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE)\n    \"MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE\",\n#endif /* MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE */\n#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)\n    \"MBEDTLS_SSL_MAX_FRAGMENT_LENGTH\",\n#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */\n#if defined(MBEDTLS_SSL_PROTO_SSL3)\n    \"MBEDTLS_SSL_PROTO_SSL3\",\n#endif /* MBEDTLS_SSL_PROTO_SSL3 */\n#if defined(MBEDTLS_SSL_PROTO_TLS1)\n    \"MBEDTLS_SSL_PROTO_TLS1\",\n#endif /* MBEDTLS_SSL_PROTO_TLS1 */\n#if defined(MBEDTLS_SSL_PROTO_TLS1_1)\n    \"MBEDTLS_SSL_PROTO_TLS1_1\",\n#endif /* MBEDTLS_SSL_PROTO_TLS1_1 */\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2)\n    \"MBEDTLS_SSL_PROTO_TLS1_2\",\n#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n    \"MBEDTLS_SSL_PROTO_DTLS\",\n#endif /* MBEDTLS_SSL_PROTO_DTLS */\n#if defined(MBEDTLS_SSL_ALPN)\n    \"MBEDTLS_SSL_ALPN\",\n#endif /* MBEDTLS_SSL_ALPN */\n#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)\n    \"MBEDTLS_SSL_DTLS_ANTI_REPLAY\",\n#endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */\n#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)\n    \"MBEDTLS_SSL_DTLS_HELLO_VERIFY\",\n#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */\n#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE)\n    \"MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE\",\n#endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE */\n#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)\n    \"MBEDTLS_SSL_DTLS_BADMAC_LIMIT\",\n#endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */\n#if defined(MBEDTLS_SSL_SESSION_TICKETS)\n    \"MBEDTLS_SSL_SESSION_TICKETS\",\n#endif /* MBEDTLS_SSL_SESSION_TICKETS */\n#if defined(MBEDTLS_SSL_EXPORT_KEYS)\n    \"MBEDTLS_SSL_EXPORT_KEYS\",\n#endif /* MBEDTLS_SSL_EXPORT_KEYS */\n#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)\n    \"MBEDTLS_SSL_SERVER_NAME_INDICATION\",\n#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)\n    \"MBEDTLS_SSL_TRUNCATED_HMAC\",\n#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */\n#if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT)\n    \"MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT\",\n#endif /* MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT */\n#if defined(MBEDTLS_THREADING_ALT)\n    \"MBEDTLS_THREADING_ALT\",\n#endif /* MBEDTLS_THREADING_ALT */\n#if defined(MBEDTLS_THREADING_PTHREAD)\n    \"MBEDTLS_THREADING_PTHREAD\",\n#endif /* MBEDTLS_THREADING_PTHREAD */\n#if defined(MBEDTLS_VERSION_FEATURES)\n    \"MBEDTLS_VERSION_FEATURES\",\n#endif /* MBEDTLS_VERSION_FEATURES */\n#if defined(MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3)\n    \"MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3\",\n#endif /* MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3 */\n#if defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION)\n    \"MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION\",\n#endif /* MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION */\n#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)\n    \"MBEDTLS_X509_CHECK_KEY_USAGE\",\n#endif /* MBEDTLS_X509_CHECK_KEY_USAGE */\n#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)\n    \"MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE\",\n#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */\n#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)\n    \"MBEDTLS_X509_RSASSA_PSS_SUPPORT\",\n#endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */\n#if defined(MBEDTLS_ZLIB_SUPPORT)\n    \"MBEDTLS_ZLIB_SUPPORT\",\n#endif /* MBEDTLS_ZLIB_SUPPORT */\n#if defined(MBEDTLS_AESNI_C)\n    \"MBEDTLS_AESNI_C\",\n#endif /* MBEDTLS_AESNI_C */\n#if defined(MBEDTLS_AES_C)\n    \"MBEDTLS_AES_C\",\n#endif /* MBEDTLS_AES_C */\n#if defined(MBEDTLS_ARC4_C)\n    \"MBEDTLS_ARC4_C\",\n#endif /* MBEDTLS_ARC4_C */\n#if defined(MBEDTLS_ASN1_PARSE_C)\n    \"MBEDTLS_ASN1_PARSE_C\",\n#endif /* MBEDTLS_ASN1_PARSE_C */\n#if defined(MBEDTLS_ASN1_WRITE_C)\n    \"MBEDTLS_ASN1_WRITE_C\",\n#endif /* MBEDTLS_ASN1_WRITE_C */\n#if defined(MBEDTLS_BASE64_C)\n    \"MBEDTLS_BASE64_C\",\n#endif /* MBEDTLS_BASE64_C */\n#if defined(MBEDTLS_BIGNUM_C)\n    \"MBEDTLS_BIGNUM_C\",\n#endif /* MBEDTLS_BIGNUM_C */\n#if defined(MBEDTLS_BLOWFISH_C)\n    \"MBEDTLS_BLOWFISH_C\",\n#endif /* MBEDTLS_BLOWFISH_C */\n#if defined(MBEDTLS_CAMELLIA_C)\n    \"MBEDTLS_CAMELLIA_C\",\n#endif /* MBEDTLS_CAMELLIA_C */\n#if defined(MBEDTLS_ARIA_C)\n    \"MBEDTLS_ARIA_C\",\n#endif /* MBEDTLS_ARIA_C */\n#if defined(MBEDTLS_CCM_C)\n    \"MBEDTLS_CCM_C\",\n#endif /* MBEDTLS_CCM_C */\n#if defined(MBEDTLS_CERTS_C)\n    \"MBEDTLS_CERTS_C\",\n#endif /* MBEDTLS_CERTS_C */\n#if defined(MBEDTLS_CHACHA20_C)\n    \"MBEDTLS_CHACHA20_C\",\n#endif /* MBEDTLS_CHACHA20_C */\n#if defined(MBEDTLS_CHACHAPOLY_C)\n    \"MBEDTLS_CHACHAPOLY_C\",\n#endif /* MBEDTLS_CHACHAPOLY_C */\n#if defined(MBEDTLS_CIPHER_C)\n    \"MBEDTLS_CIPHER_C\",\n#endif /* MBEDTLS_CIPHER_C */\n#if defined(MBEDTLS_CMAC_C)\n    \"MBEDTLS_CMAC_C\",\n#endif /* MBEDTLS_CMAC_C */\n#if defined(MBEDTLS_CTR_DRBG_C)\n    \"MBEDTLS_CTR_DRBG_C\",\n#endif /* MBEDTLS_CTR_DRBG_C */\n#if defined(MBEDTLS_DEBUG_C)\n    \"MBEDTLS_DEBUG_C\",\n#endif /* MBEDTLS_DEBUG_C */\n#if defined(MBEDTLS_DES_C)\n    \"MBEDTLS_DES_C\",\n#endif /* MBEDTLS_DES_C */\n#if defined(MBEDTLS_DHM_C)\n    \"MBEDTLS_DHM_C\",\n#endif /* MBEDTLS_DHM_C */\n#if defined(MBEDTLS_ECDH_C)\n    \"MBEDTLS_ECDH_C\",\n#endif /* MBEDTLS_ECDH_C */\n#if defined(MBEDTLS_ECDSA_C)\n    \"MBEDTLS_ECDSA_C\",\n#endif /* MBEDTLS_ECDSA_C */\n#if defined(MBEDTLS_ECJPAKE_C)\n    \"MBEDTLS_ECJPAKE_C\",\n#endif /* MBEDTLS_ECJPAKE_C */\n#if defined(MBEDTLS_ECP_C)\n    \"MBEDTLS_ECP_C\",\n#endif /* MBEDTLS_ECP_C */\n#if defined(MBEDTLS_ENTROPY_C)\n    \"MBEDTLS_ENTROPY_C\",\n#endif /* MBEDTLS_ENTROPY_C */\n#if defined(MBEDTLS_ERROR_C)\n    \"MBEDTLS_ERROR_C\",\n#endif /* MBEDTLS_ERROR_C */\n#if defined(MBEDTLS_GCM_C)\n    \"MBEDTLS_GCM_C\",\n#endif /* MBEDTLS_GCM_C */\n#if defined(MBEDTLS_HAVEGE_C)\n    \"MBEDTLS_HAVEGE_C\",\n#endif /* MBEDTLS_HAVEGE_C */\n#if defined(MBEDTLS_HKDF_C)\n    \"MBEDTLS_HKDF_C\",\n#endif /* MBEDTLS_HKDF_C */\n#if defined(MBEDTLS_HMAC_DRBG_C)\n    \"MBEDTLS_HMAC_DRBG_C\",\n#endif /* MBEDTLS_HMAC_DRBG_C */\n#if defined(MBEDTLS_NIST_KW_C)\n    \"MBEDTLS_NIST_KW_C\",\n#endif /* MBEDTLS_NIST_KW_C */\n#if defined(MBEDTLS_MD_C)\n    \"MBEDTLS_MD_C\",\n#endif /* MBEDTLS_MD_C */\n#if defined(MBEDTLS_MD2_C)\n    \"MBEDTLS_MD2_C\",\n#endif /* MBEDTLS_MD2_C */\n#if defined(MBEDTLS_MD4_C)\n    \"MBEDTLS_MD4_C\",\n#endif /* MBEDTLS_MD4_C */\n#if defined(MBEDTLS_MD5_C)\n    \"MBEDTLS_MD5_C\",\n#endif /* MBEDTLS_MD5_C */\n#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)\n    \"MBEDTLS_MEMORY_BUFFER_ALLOC_C\",\n#endif /* MBEDTLS_MEMORY_BUFFER_ALLOC_C */\n#if defined(MBEDTLS_NET_C)\n    \"MBEDTLS_NET_C\",\n#endif /* MBEDTLS_NET_C */\n#if defined(MBEDTLS_OID_C)\n    \"MBEDTLS_OID_C\",\n#endif /* MBEDTLS_OID_C */\n#if defined(MBEDTLS_PADLOCK_C)\n    \"MBEDTLS_PADLOCK_C\",\n#endif /* MBEDTLS_PADLOCK_C */\n#if defined(MBEDTLS_PEM_PARSE_C)\n    \"MBEDTLS_PEM_PARSE_C\",\n#endif /* MBEDTLS_PEM_PARSE_C */\n#if defined(MBEDTLS_PEM_WRITE_C)\n    \"MBEDTLS_PEM_WRITE_C\",\n#endif /* MBEDTLS_PEM_WRITE_C */\n#if defined(MBEDTLS_PK_C)\n    \"MBEDTLS_PK_C\",\n#endif /* MBEDTLS_PK_C */\n#if defined(MBEDTLS_PK_PARSE_C)\n    \"MBEDTLS_PK_PARSE_C\",\n#endif /* MBEDTLS_PK_PARSE_C */\n#if defined(MBEDTLS_PK_WRITE_C)\n    \"MBEDTLS_PK_WRITE_C\",\n#endif /* MBEDTLS_PK_WRITE_C */\n#if defined(MBEDTLS_PKCS5_C)\n    \"MBEDTLS_PKCS5_C\",\n#endif /* MBEDTLS_PKCS5_C */\n#if defined(MBEDTLS_PKCS11_C)\n    \"MBEDTLS_PKCS11_C\",\n#endif /* MBEDTLS_PKCS11_C */\n#if defined(MBEDTLS_PKCS12_C)\n    \"MBEDTLS_PKCS12_C\",\n#endif /* MBEDTLS_PKCS12_C */\n#if defined(MBEDTLS_PLATFORM_C)\n    \"MBEDTLS_PLATFORM_C\",\n#endif /* MBEDTLS_PLATFORM_C */\n#if defined(MBEDTLS_POLY1305_C)\n    \"MBEDTLS_POLY1305_C\",\n#endif /* MBEDTLS_POLY1305_C */\n#if defined(MBEDTLS_RIPEMD160_C)\n    \"MBEDTLS_RIPEMD160_C\",\n#endif /* MBEDTLS_RIPEMD160_C */\n#if defined(MBEDTLS_RSA_C)\n    \"MBEDTLS_RSA_C\",\n#endif /* MBEDTLS_RSA_C */\n#if defined(MBEDTLS_SHA1_C)\n    \"MBEDTLS_SHA1_C\",\n#endif /* MBEDTLS_SHA1_C */\n#if defined(MBEDTLS_SHA256_C)\n    \"MBEDTLS_SHA256_C\",\n#endif /* MBEDTLS_SHA256_C */\n#if defined(MBEDTLS_SHA512_C)\n    \"MBEDTLS_SHA512_C\",\n#endif /* MBEDTLS_SHA512_C */\n#if defined(MBEDTLS_SSL_CACHE_C)\n    \"MBEDTLS_SSL_CACHE_C\",\n#endif /* MBEDTLS_SSL_CACHE_C */\n#if defined(MBEDTLS_SSL_COOKIE_C)\n    \"MBEDTLS_SSL_COOKIE_C\",\n#endif /* MBEDTLS_SSL_COOKIE_C */\n#if defined(MBEDTLS_SSL_TICKET_C)\n    \"MBEDTLS_SSL_TICKET_C\",\n#endif /* MBEDTLS_SSL_TICKET_C */\n#if defined(MBEDTLS_SSL_CLI_C)\n    \"MBEDTLS_SSL_CLI_C\",\n#endif /* MBEDTLS_SSL_CLI_C */\n#if defined(MBEDTLS_SSL_SRV_C)\n    \"MBEDTLS_SSL_SRV_C\",\n#endif /* MBEDTLS_SSL_SRV_C */\n#if defined(MBEDTLS_SSL_TLS_C)\n    \"MBEDTLS_SSL_TLS_C\",\n#endif /* MBEDTLS_SSL_TLS_C */\n#if defined(MBEDTLS_THREADING_C)\n    \"MBEDTLS_THREADING_C\",\n#endif /* MBEDTLS_THREADING_C */\n#if defined(MBEDTLS_TIMING_C)\n    \"MBEDTLS_TIMING_C\",\n#endif /* MBEDTLS_TIMING_C */\n#if defined(MBEDTLS_VERSION_C)\n    \"MBEDTLS_VERSION_C\",\n#endif /* MBEDTLS_VERSION_C */\n#if defined(MBEDTLS_X509_USE_C)\n    \"MBEDTLS_X509_USE_C\",\n#endif /* MBEDTLS_X509_USE_C */\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n    \"MBEDTLS_X509_CRT_PARSE_C\",\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n#if defined(MBEDTLS_X509_CRL_PARSE_C)\n    \"MBEDTLS_X509_CRL_PARSE_C\",\n#endif /* MBEDTLS_X509_CRL_PARSE_C */\n#if defined(MBEDTLS_X509_CSR_PARSE_C)\n    \"MBEDTLS_X509_CSR_PARSE_C\",\n#endif /* MBEDTLS_X509_CSR_PARSE_C */\n#if defined(MBEDTLS_X509_CREATE_C)\n    \"MBEDTLS_X509_CREATE_C\",\n#endif /* MBEDTLS_X509_CREATE_C */\n#if defined(MBEDTLS_X509_CRT_WRITE_C)\n    \"MBEDTLS_X509_CRT_WRITE_C\",\n#endif /* MBEDTLS_X509_CRT_WRITE_C */\n#if defined(MBEDTLS_X509_CSR_WRITE_C)\n    \"MBEDTLS_X509_CSR_WRITE_C\",\n#endif /* MBEDTLS_X509_CSR_WRITE_C */\n#if defined(MBEDTLS_XTEA_C)\n    \"MBEDTLS_XTEA_C\",\n#endif /* MBEDTLS_XTEA_C */\n#endif /* MBEDTLS_VERSION_FEATURES */\n    NULL\n};\n\nint mbedtls_version_check_feature( const char *feature )\n{\n    const char **idx = features;\n\n    if( *idx == NULL )\n        return( -2 );\n\n    if( feature == NULL )\n        return( -1 );\n\n    while( *idx != NULL )\n    {\n        if( !strcmp( *idx, feature ) )\n            return( 0 );\n        idx++;\n    }\n    return( -1 );\n}\n\n#endif /* MBEDTLS_VERSION_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/x509.c",
    "content": "/*\n *  X.509 common functions for parsing and verification\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The ITU-T X.509 standard defines a certificate format for PKI.\n *\n *  http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs)\n *  http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs)\n *  http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10)\n *\n *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf\n *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf\n */\n\n/* Ensure gmtime_r is available even with -std=c99; must be included before\n * config.h, which pulls in glibc's features.h. Harmless on other platforms. */\n#define _POSIX_C_SOURCE 200112L\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_X509_USE_C)\n\n#include \"mbedtls/x509.h\"\n#include \"mbedtls/asn1.h\"\n#include \"mbedtls/oid.h\"\n\n#include <stdio.h>\n#include <string.h>\n\n#if defined(MBEDTLS_PEM_PARSE_C)\n#include \"mbedtls/pem.h\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#include <stdlib.h>\n#define mbedtls_free      free\n#define mbedtls_calloc    calloc\n#define mbedtls_printf    printf\n#define mbedtls_snprintf  snprintf\n#endif\n\n#if defined(MBEDTLS_HAVE_TIME)\n#include \"mbedtls/platform_time.h\"\n#endif\n#if defined(MBEDTLS_HAVE_TIME_DATE)\n#include <time.h>\n#endif\n\n#define CHECK(code) if( ( ret = code ) != 0 ){ return( ret ); }\n#define CHECK_RANGE(min, max, val) if( val < min || val > max ){ return( ret ); }\n\n/*\n *  CertificateSerialNumber  ::=  INTEGER\n */\nint mbedtls_x509_get_serial( unsigned char **p, const unsigned char *end,\n                     mbedtls_x509_buf *serial )\n{\n    int ret;\n\n    if( ( end - *p ) < 1 )\n        return( MBEDTLS_ERR_X509_INVALID_SERIAL +\n                MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n    if( **p != ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_PRIMITIVE | 2 ) &&\n        **p !=   MBEDTLS_ASN1_INTEGER )\n        return( MBEDTLS_ERR_X509_INVALID_SERIAL +\n                MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );\n\n    serial->tag = *(*p)++;\n\n    if( ( ret = mbedtls_asn1_get_len( p, end, &serial->len ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_SERIAL + ret );\n\n    serial->p = *p;\n    *p += serial->len;\n\n    return( 0 );\n}\n\n/* Get an algorithm identifier without parameters (eg for signatures)\n *\n *  AlgorithmIdentifier  ::=  SEQUENCE  {\n *       algorithm               OBJECT IDENTIFIER,\n *       parameters              ANY DEFINED BY algorithm OPTIONAL  }\n */\nint mbedtls_x509_get_alg_null( unsigned char **p, const unsigned char *end,\n                       mbedtls_x509_buf *alg )\n{\n    int ret;\n\n    if( ( ret = mbedtls_asn1_get_alg_null( p, end, alg ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_ALG + ret );\n\n    return( 0 );\n}\n\n/*\n * Parse an algorithm identifier with (optional) paramaters\n */\nint mbedtls_x509_get_alg( unsigned char **p, const unsigned char *end,\n                  mbedtls_x509_buf *alg, mbedtls_x509_buf *params )\n{\n    int ret;\n\n    if( ( ret = mbedtls_asn1_get_alg( p, end, alg, params ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_ALG + ret );\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)\n/*\n * HashAlgorithm ::= AlgorithmIdentifier\n *\n * AlgorithmIdentifier  ::=  SEQUENCE  {\n *      algorithm               OBJECT IDENTIFIER,\n *      parameters              ANY DEFINED BY algorithm OPTIONAL  }\n *\n * For HashAlgorithm, parameters MUST be NULL or absent.\n */\nstatic int x509_get_hash_alg( const mbedtls_x509_buf *alg, mbedtls_md_type_t *md_alg )\n{\n    int ret;\n    unsigned char *p;\n    const unsigned char *end;\n    mbedtls_x509_buf md_oid;\n    size_t len;\n\n    /* Make sure we got a SEQUENCE and setup bounds */\n    if( alg->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )\n        return( MBEDTLS_ERR_X509_INVALID_ALG +\n                MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );\n\n    p = (unsigned char *) alg->p;\n    end = p + alg->len;\n\n    if( p >= end )\n        return( MBEDTLS_ERR_X509_INVALID_ALG +\n                MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n    /* Parse md_oid */\n    md_oid.tag = *p;\n\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &md_oid.len, MBEDTLS_ASN1_OID ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_ALG + ret );\n\n    md_oid.p = p;\n    p += md_oid.len;\n\n    /* Get md_alg from md_oid */\n    if( ( ret = mbedtls_oid_get_md_alg( &md_oid, md_alg ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_ALG + ret );\n\n    /* Make sure params is absent of NULL */\n    if( p == end )\n        return( 0 );\n\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_NULL ) ) != 0 || len != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_ALG + ret );\n\n    if( p != end )\n        return( MBEDTLS_ERR_X509_INVALID_ALG +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    return( 0 );\n}\n\n/*\n *    RSASSA-PSS-params  ::=  SEQUENCE  {\n *       hashAlgorithm     [0] HashAlgorithm DEFAULT sha1Identifier,\n *       maskGenAlgorithm  [1] MaskGenAlgorithm DEFAULT mgf1SHA1Identifier,\n *       saltLength        [2] INTEGER DEFAULT 20,\n *       trailerField      [3] INTEGER DEFAULT 1  }\n *    -- Note that the tags in this Sequence are explicit.\n *\n * RFC 4055 (which defines use of RSASSA-PSS in PKIX) states that the value\n * of trailerField MUST be 1, and PKCS#1 v2.2 doesn't even define any other\n * option. Enfore this at parsing time.\n */\nint mbedtls_x509_get_rsassa_pss_params( const mbedtls_x509_buf *params,\n                                mbedtls_md_type_t *md_alg, mbedtls_md_type_t *mgf_md,\n                                int *salt_len )\n{\n    int ret;\n    unsigned char *p;\n    const unsigned char *end, *end2;\n    size_t len;\n    mbedtls_x509_buf alg_id, alg_params;\n\n    /* First set everything to defaults */\n    *md_alg = MBEDTLS_MD_SHA1;\n    *mgf_md = MBEDTLS_MD_SHA1;\n    *salt_len = 20;\n\n    /* Make sure params is a SEQUENCE and setup bounds */\n    if( params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )\n        return( MBEDTLS_ERR_X509_INVALID_ALG +\n                MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );\n\n    p = (unsigned char *) params->p;\n    end = p + params->len;\n\n    if( p == end )\n        return( 0 );\n\n    /*\n     * HashAlgorithm\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n                    MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) == 0 )\n    {\n        end2 = p + len;\n\n        /* HashAlgorithm ::= AlgorithmIdentifier (without parameters) */\n        if( ( ret = mbedtls_x509_get_alg_null( &p, end2, &alg_id ) ) != 0 )\n            return( ret );\n\n        if( ( ret = mbedtls_oid_get_md_alg( &alg_id, md_alg ) ) != 0 )\n            return( MBEDTLS_ERR_X509_INVALID_ALG + ret );\n\n        if( p != end2 )\n            return( MBEDTLS_ERR_X509_INVALID_ALG +\n                    MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n    }\n    else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )\n        return( MBEDTLS_ERR_X509_INVALID_ALG + ret );\n\n    if( p == end )\n        return( 0 );\n\n    /*\n     * MaskGenAlgorithm\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n                    MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 1 ) ) == 0 )\n    {\n        end2 = p + len;\n\n        /* MaskGenAlgorithm ::= AlgorithmIdentifier (params = HashAlgorithm) */\n        if( ( ret = mbedtls_x509_get_alg( &p, end2, &alg_id, &alg_params ) ) != 0 )\n            return( ret );\n\n        /* Only MFG1 is recognised for now */\n        if( MBEDTLS_OID_CMP( MBEDTLS_OID_MGF1, &alg_id ) != 0 )\n            return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE +\n                    MBEDTLS_ERR_OID_NOT_FOUND );\n\n        /* Parse HashAlgorithm */\n        if( ( ret = x509_get_hash_alg( &alg_params, mgf_md ) ) != 0 )\n            return( ret );\n\n        if( p != end2 )\n            return( MBEDTLS_ERR_X509_INVALID_ALG +\n                    MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n    }\n    else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )\n        return( MBEDTLS_ERR_X509_INVALID_ALG + ret );\n\n    if( p == end )\n        return( 0 );\n\n    /*\n     * salt_len\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n                    MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 2 ) ) == 0 )\n    {\n        end2 = p + len;\n\n        if( ( ret = mbedtls_asn1_get_int( &p, end2, salt_len ) ) != 0 )\n            return( MBEDTLS_ERR_X509_INVALID_ALG + ret );\n\n        if( p != end2 )\n            return( MBEDTLS_ERR_X509_INVALID_ALG +\n                    MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n    }\n    else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )\n        return( MBEDTLS_ERR_X509_INVALID_ALG + ret );\n\n    if( p == end )\n        return( 0 );\n\n    /*\n     * trailer_field (if present, must be 1)\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n                    MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 3 ) ) == 0 )\n    {\n        int trailer_field;\n\n        end2 = p + len;\n\n        if( ( ret = mbedtls_asn1_get_int( &p, end2, &trailer_field ) ) != 0 )\n            return( MBEDTLS_ERR_X509_INVALID_ALG + ret );\n\n        if( p != end2 )\n            return( MBEDTLS_ERR_X509_INVALID_ALG +\n                    MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n        if( trailer_field != 1 )\n            return( MBEDTLS_ERR_X509_INVALID_ALG );\n    }\n    else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )\n        return( MBEDTLS_ERR_X509_INVALID_ALG + ret );\n\n    if( p != end )\n        return( MBEDTLS_ERR_X509_INVALID_ALG +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    return( 0 );\n}\n#endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */\n\n/*\n *  AttributeTypeAndValue ::= SEQUENCE {\n *    type     AttributeType,\n *    value    AttributeValue }\n *\n *  AttributeType ::= OBJECT IDENTIFIER\n *\n *  AttributeValue ::= ANY DEFINED BY AttributeType\n */\nstatic int x509_get_attr_type_value( unsigned char **p,\n                                     const unsigned char *end,\n                                     mbedtls_x509_name *cur )\n{\n    int ret;\n    size_t len;\n    mbedtls_x509_buf *oid;\n    mbedtls_x509_buf *val;\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_NAME + ret );\n\n    if( ( end - *p ) < 1 )\n        return( MBEDTLS_ERR_X509_INVALID_NAME +\n                MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n    oid = &cur->oid;\n    oid->tag = **p;\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &oid->len, MBEDTLS_ASN1_OID ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_NAME + ret );\n\n    oid->p = *p;\n    *p += oid->len;\n\n    if( ( end - *p ) < 1 )\n        return( MBEDTLS_ERR_X509_INVALID_NAME +\n                MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n    if( **p != MBEDTLS_ASN1_BMP_STRING && **p != MBEDTLS_ASN1_UTF8_STRING      &&\n        **p != MBEDTLS_ASN1_T61_STRING && **p != MBEDTLS_ASN1_PRINTABLE_STRING &&\n        **p != MBEDTLS_ASN1_IA5_STRING && **p != MBEDTLS_ASN1_UNIVERSAL_STRING &&\n        **p != MBEDTLS_ASN1_BIT_STRING )\n        return( MBEDTLS_ERR_X509_INVALID_NAME +\n                MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );\n\n    val = &cur->val;\n    val->tag = *(*p)++;\n\n    if( ( ret = mbedtls_asn1_get_len( p, end, &val->len ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_NAME + ret );\n\n    val->p = *p;\n    *p += val->len;\n\n    cur->next = NULL;\n\n    return( 0 );\n}\n\n/*\n *  Name ::= CHOICE { -- only one possibility for now --\n *       rdnSequence  RDNSequence }\n *\n *  RDNSequence ::= SEQUENCE OF RelativeDistinguishedName\n *\n *  RelativeDistinguishedName ::=\n *    SET OF AttributeTypeAndValue\n *\n *  AttributeTypeAndValue ::= SEQUENCE {\n *    type     AttributeType,\n *    value    AttributeValue }\n *\n *  AttributeType ::= OBJECT IDENTIFIER\n *\n *  AttributeValue ::= ANY DEFINED BY AttributeType\n *\n * The data structure is optimized for the common case where each RDN has only\n * one element, which is represented as a list of AttributeTypeAndValue.\n * For the general case we still use a flat list, but we mark elements of the\n * same set so that they are \"merged\" together in the functions that consume\n * this list, eg mbedtls_x509_dn_gets().\n */\nint mbedtls_x509_get_name( unsigned char **p, const unsigned char *end,\n                   mbedtls_x509_name *cur )\n{\n    int ret;\n    size_t set_len;\n    const unsigned char *end_set;\n\n    /* don't use recursion, we'd risk stack overflow if not optimized */\n    while( 1 )\n    {\n        /*\n         * parse SET\n         */\n        if( ( ret = mbedtls_asn1_get_tag( p, end, &set_len,\n                MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET ) ) != 0 )\n            return( MBEDTLS_ERR_X509_INVALID_NAME + ret );\n\n        end_set  = *p + set_len;\n\n        while( 1 )\n        {\n            if( ( ret = x509_get_attr_type_value( p, end_set, cur ) ) != 0 )\n                return( ret );\n\n            if( *p == end_set )\n                break;\n\n            /* Mark this item as being no the only one in a set */\n            cur->next_merged = 1;\n\n            cur->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_name ) );\n\n            if( cur->next == NULL )\n                return( MBEDTLS_ERR_X509_ALLOC_FAILED );\n\n            cur = cur->next;\n        }\n\n        /*\n         * continue until end of SEQUENCE is reached\n         */\n        if( *p == end )\n            return( 0 );\n\n        cur->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_name ) );\n\n        if( cur->next == NULL )\n            return( MBEDTLS_ERR_X509_ALLOC_FAILED );\n\n        cur = cur->next;\n    }\n}\n\nstatic int x509_parse_int( unsigned char **p, size_t n, int *res )\n{\n    *res = 0;\n\n    for( ; n > 0; --n )\n    {\n        if( ( **p < '0') || ( **p > '9' ) )\n            return ( MBEDTLS_ERR_X509_INVALID_DATE );\n\n        *res *= 10;\n        *res += ( *(*p)++ - '0' );\n    }\n\n    return( 0 );\n}\n\nstatic int x509_date_is_valid(const mbedtls_x509_time *t )\n{\n    int ret = MBEDTLS_ERR_X509_INVALID_DATE;\n    int month_len;\n\n    CHECK_RANGE( 0, 9999, t->year );\n    CHECK_RANGE( 0, 23,   t->hour );\n    CHECK_RANGE( 0, 59,   t->min  );\n    CHECK_RANGE( 0, 59,   t->sec  );\n\n    switch( t->mon )\n    {\n        case 1: case 3: case 5: case 7: case 8: case 10: case 12:\n            month_len = 31;\n            break;\n        case 4: case 6: case 9: case 11:\n            month_len = 30;\n            break;\n        case 2:\n            if( ( !( t->year % 4 ) && t->year % 100 ) ||\n                !( t->year % 400 ) )\n                month_len = 29;\n            else\n                month_len = 28;\n            break;\n        default:\n            return( ret );\n    }\n    CHECK_RANGE( 1, month_len, t->day );\n\n    return( 0 );\n}\n\n/*\n * Parse an ASN1_UTC_TIME (yearlen=2) or ASN1_GENERALIZED_TIME (yearlen=4)\n * field.\n */\nstatic int x509_parse_time( unsigned char **p, size_t len, size_t yearlen,\n                            mbedtls_x509_time *tm )\n{\n    int ret;\n\n    /*\n     * Minimum length is 10 or 12 depending on yearlen\n     */\n    if ( len < yearlen + 8 )\n        return ( MBEDTLS_ERR_X509_INVALID_DATE );\n    len -= yearlen + 8;\n\n    /*\n     * Parse year, month, day, hour, minute\n     */\n    CHECK( x509_parse_int( p, yearlen, &tm->year ) );\n    if ( 2 == yearlen )\n    {\n        if ( tm->year < 50 )\n            tm->year += 100;\n\n        tm->year += 1900;\n    }\n\n    CHECK( x509_parse_int( p, 2, &tm->mon ) );\n    CHECK( x509_parse_int( p, 2, &tm->day ) );\n    CHECK( x509_parse_int( p, 2, &tm->hour ) );\n    CHECK( x509_parse_int( p, 2, &tm->min ) );\n\n    /*\n     * Parse seconds if present\n     */\n    if ( len >= 2 )\n    {\n        CHECK( x509_parse_int( p, 2, &tm->sec ) );\n        len -= 2;\n    }\n    else\n        return ( MBEDTLS_ERR_X509_INVALID_DATE );\n\n    /*\n     * Parse trailing 'Z' if present\n     */\n    if ( 1 == len && 'Z' == **p )\n    {\n        (*p)++;\n        len--;\n    }\n\n    /*\n     * We should have parsed all characters at this point\n     */\n    if ( 0 != len )\n        return ( MBEDTLS_ERR_X509_INVALID_DATE );\n\n    CHECK( x509_date_is_valid( tm ) );\n\n    return ( 0 );\n}\n\n/*\n *  Time ::= CHOICE {\n *       utcTime        UTCTime,\n *       generalTime    GeneralizedTime }\n */\nint mbedtls_x509_get_time( unsigned char **p, const unsigned char *end,\n                           mbedtls_x509_time *tm )\n{\n    int ret;\n    size_t len, year_len;\n    unsigned char tag;\n\n    if( ( end - *p ) < 1 )\n        return( MBEDTLS_ERR_X509_INVALID_DATE +\n                MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n    tag = **p;\n\n    if( tag == MBEDTLS_ASN1_UTC_TIME )\n        year_len = 2;\n    else if( tag == MBEDTLS_ASN1_GENERALIZED_TIME )\n        year_len = 4;\n    else\n        return( MBEDTLS_ERR_X509_INVALID_DATE +\n                MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );\n\n    (*p)++;\n    ret = mbedtls_asn1_get_len( p, end, &len );\n\n    if( ret != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_DATE + ret );\n\n    return x509_parse_time( p, len, year_len, tm );\n}\n\nint mbedtls_x509_get_sig( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *sig )\n{\n    int ret;\n    size_t len;\n    int tag_type;\n\n    if( ( end - *p ) < 1 )\n        return( MBEDTLS_ERR_X509_INVALID_SIGNATURE +\n                MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n    tag_type = **p;\n\n    if( ( ret = mbedtls_asn1_get_bitstring_null( p, end, &len ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_SIGNATURE + ret );\n\n    sig->tag = tag_type;\n    sig->len = len;\n    sig->p = *p;\n\n    *p += len;\n\n    return( 0 );\n}\n\n/*\n * Get signature algorithm from alg OID and optional parameters\n */\nint mbedtls_x509_get_sig_alg( const mbedtls_x509_buf *sig_oid, const mbedtls_x509_buf *sig_params,\n                      mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg,\n                      void **sig_opts )\n{\n    int ret;\n\n    if( *sig_opts != NULL )\n        return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n\n    if( ( ret = mbedtls_oid_get_sig_alg( sig_oid, md_alg, pk_alg ) ) != 0 )\n        return( MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + ret );\n\n#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)\n    if( *pk_alg == MBEDTLS_PK_RSASSA_PSS )\n    {\n        mbedtls_pk_rsassa_pss_options *pss_opts;\n\n        pss_opts = mbedtls_calloc( 1, sizeof( mbedtls_pk_rsassa_pss_options ) );\n        if( pss_opts == NULL )\n            return( MBEDTLS_ERR_X509_ALLOC_FAILED );\n\n        ret = mbedtls_x509_get_rsassa_pss_params( sig_params,\n                                          md_alg,\n                                          &pss_opts->mgf1_hash_id,\n                                          &pss_opts->expected_salt_len );\n        if( ret != 0 )\n        {\n            mbedtls_free( pss_opts );\n            return( ret );\n        }\n\n        *sig_opts = (void *) pss_opts;\n    }\n    else\n#endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */\n    {\n        /* Make sure parameters are absent or NULL */\n        if( ( sig_params->tag != MBEDTLS_ASN1_NULL && sig_params->tag != 0 ) ||\n              sig_params->len != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_ALG );\n    }\n\n    return( 0 );\n}\n\n/*\n * X.509 Extensions (No parsing of extensions, pointer should\n * be either manually updated or extensions should be parsed!)\n */\nint mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end,\n                  mbedtls_x509_buf *ext, int tag )\n{\n    int ret;\n    size_t len;\n\n    if( *p == end )\n        return( 0 );\n\n    ext->tag = **p;\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &ext->len,\n            MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | tag ) ) != 0 )\n        return( ret );\n\n    ext->p = *p;\n    end = *p + ext->len;\n\n    /*\n     * Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension\n     *\n     * Extension  ::=  SEQUENCE  {\n     *      extnID      OBJECT IDENTIFIER,\n     *      critical    BOOLEAN DEFAULT FALSE,\n     *      extnValue   OCTET STRING  }\n     */\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n\n    if( end != *p + len )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    return( 0 );\n}\n\n/*\n * Store the name in printable form into buf; no more\n * than size characters will be written\n */\nint mbedtls_x509_dn_gets( char *buf, size_t size, const mbedtls_x509_name *dn )\n{\n    int ret;\n    size_t i, n;\n    unsigned char c, merge = 0;\n    const mbedtls_x509_name *name;\n    const char *short_name = NULL;\n    char s[MBEDTLS_X509_MAX_DN_NAME_SIZE], *p;\n\n    memset( s, 0, sizeof( s ) );\n\n    name = dn;\n    p = buf;\n    n = size;\n\n    while( name != NULL )\n    {\n        if( !name->oid.p )\n        {\n            name = name->next;\n            continue;\n        }\n\n        if( name != dn )\n        {\n            ret = mbedtls_snprintf( p, n, merge ? \" + \" : \", \" );\n            MBEDTLS_X509_SAFE_SNPRINTF;\n        }\n\n        ret = mbedtls_oid_get_attr_short_name( &name->oid, &short_name );\n\n        if( ret == 0 )\n            ret = mbedtls_snprintf( p, n, \"%s=\", short_name );\n        else\n            ret = mbedtls_snprintf( p, n, \"\\?\\?=\" );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n\n        for( i = 0; i < name->val.len; i++ )\n        {\n            if( i >= sizeof( s ) - 1 )\n                break;\n\n            c = name->val.p[i];\n            if( c < 32 || c == 127 || ( c > 128 && c < 160 ) )\n                 s[i] = '?';\n            else s[i] = c;\n        }\n        s[i] = '\\0';\n        ret = mbedtls_snprintf( p, n, \"%s\", s );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n\n        merge = name->next_merged;\n        name = name->next;\n    }\n\n    return( (int) ( size - n ) );\n}\n\n/*\n * Store the serial in printable form into buf; no more\n * than size characters will be written\n */\nint mbedtls_x509_serial_gets( char *buf, size_t size, const mbedtls_x509_buf *serial )\n{\n    int ret;\n    size_t i, n, nr;\n    char *p;\n\n    p = buf;\n    n = size;\n\n    nr = ( serial->len <= 32 )\n        ? serial->len  : 28;\n\n    for( i = 0; i < nr; i++ )\n    {\n        if( i == 0 && nr > 1 && serial->p[i] == 0x0 )\n            continue;\n\n        ret = mbedtls_snprintf( p, n, \"%02X%s\",\n                serial->p[i], ( i < nr - 1 ) ? \":\" : \"\" );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n    }\n\n    if( nr != serial->len )\n    {\n        ret = mbedtls_snprintf( p, n, \"....\" );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n    }\n\n    return( (int) ( size - n ) );\n}\n\n/*\n * Helper for writing signature algorithms\n */\nint mbedtls_x509_sig_alg_gets( char *buf, size_t size, const mbedtls_x509_buf *sig_oid,\n                       mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg,\n                       const void *sig_opts )\n{\n    int ret;\n    char *p = buf;\n    size_t n = size;\n    const char *desc = NULL;\n\n    ret = mbedtls_oid_get_sig_alg_desc( sig_oid, &desc );\n    if( ret != 0 )\n        ret = mbedtls_snprintf( p, n, \"???\"  );\n    else\n        ret = mbedtls_snprintf( p, n, \"%s\", desc );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)\n    if( pk_alg == MBEDTLS_PK_RSASSA_PSS )\n    {\n        const mbedtls_pk_rsassa_pss_options *pss_opts;\n        const mbedtls_md_info_t *md_info, *mgf_md_info;\n\n        pss_opts = (const mbedtls_pk_rsassa_pss_options *) sig_opts;\n\n        md_info = mbedtls_md_info_from_type( md_alg );\n        mgf_md_info = mbedtls_md_info_from_type( pss_opts->mgf1_hash_id );\n\n        ret = mbedtls_snprintf( p, n, \" (%s, MGF1-%s, 0x%02X)\",\n                              md_info ? mbedtls_md_get_name( md_info ) : \"???\",\n                              mgf_md_info ? mbedtls_md_get_name( mgf_md_info ) : \"???\",\n                              pss_opts->expected_salt_len );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n    }\n#else\n    ((void) pk_alg);\n    ((void) md_alg);\n    ((void) sig_opts);\n#endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */\n\n    return( (int)( size - n ) );\n}\n\n/*\n * Helper for writing \"RSA key size\", \"EC key size\", etc\n */\nint mbedtls_x509_key_size_helper( char *buf, size_t buf_size, const char *name )\n{\n    char *p = buf;\n    size_t n = buf_size;\n    int ret;\n\n    ret = mbedtls_snprintf( p, n, \"%s key size\", name );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_HAVE_TIME_DATE)\n/*\n * Set the time structure to the current time.\n * Return 0 on success, non-zero on failure.\n */\nstatic int x509_get_current_time( mbedtls_x509_time *now )\n{\n    struct tm *lt, tm_buf;\n    mbedtls_time_t tt;\n    int ret = 0;\n\n    tt = mbedtls_time( NULL );\n#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)\n    lt = gmtime_s( &tm_buf, &tt ) == 0 ? &tm_buf : NULL;\n#else\n    lt = gmtime_r( &tt, &tm_buf );\n#endif\n\n    if( lt == NULL )\n        ret = -1;\n    else\n    {\n        now->year = lt->tm_year + 1900;\n        now->mon  = lt->tm_mon  + 1;\n        now->day  = lt->tm_mday;\n        now->hour = lt->tm_hour;\n        now->min  = lt->tm_min;\n        now->sec  = lt->tm_sec;\n    }\n\n    return( ret );\n}\n\n/*\n * Return 0 if before <= after, 1 otherwise\n */\nstatic int x509_check_time( const mbedtls_x509_time *before, const mbedtls_x509_time *after )\n{\n    if( before->year  > after->year )\n        return( 1 );\n\n    if( before->year == after->year &&\n        before->mon   > after->mon )\n        return( 1 );\n\n    if( before->year == after->year &&\n        before->mon  == after->mon  &&\n        before->day   > after->day )\n        return( 1 );\n\n    if( before->year == after->year &&\n        before->mon  == after->mon  &&\n        before->day  == after->day  &&\n        before->hour  > after->hour )\n        return( 1 );\n\n    if( before->year == after->year &&\n        before->mon  == after->mon  &&\n        before->day  == after->day  &&\n        before->hour == after->hour &&\n        before->min   > after->min  )\n        return( 1 );\n\n    if( before->year == after->year &&\n        before->mon  == after->mon  &&\n        before->day  == after->day  &&\n        before->hour == after->hour &&\n        before->min  == after->min  &&\n        before->sec   > after->sec  )\n        return( 1 );\n\n    return( 0 );\n}\n\nint mbedtls_x509_time_is_past( const mbedtls_x509_time *to )\n{\n    mbedtls_x509_time now;\n\n    if( x509_get_current_time( &now ) != 0 )\n        return( 1 );\n\n    return( x509_check_time( &now, to ) );\n}\n\nint mbedtls_x509_time_is_future( const mbedtls_x509_time *from )\n{\n    mbedtls_x509_time now;\n\n    if( x509_get_current_time( &now ) != 0 )\n        return( 1 );\n\n    return( x509_check_time( from, &now ) );\n}\n\n#else  /* MBEDTLS_HAVE_TIME_DATE */\n\nint mbedtls_x509_time_is_past( const mbedtls_x509_time *to )\n{\n    ((void) to);\n    return( 0 );\n}\n\nint mbedtls_x509_time_is_future( const mbedtls_x509_time *from )\n{\n    ((void) from);\n    return( 0 );\n}\n#endif /* MBEDTLS_HAVE_TIME_DATE */\n\n#if defined(MBEDTLS_SELF_TEST)\n\n#include \"mbedtls/x509_crt.h\"\n#include \"mbedtls/certs.h\"\n\n/*\n * Checkup routine\n */\nint mbedtls_x509_self_test( int verbose )\n{\n#if defined(MBEDTLS_CERTS_C) && defined(MBEDTLS_SHA256_C)\n    int ret;\n    uint32_t flags;\n    mbedtls_x509_crt cacert;\n    mbedtls_x509_crt clicert;\n\n    if( verbose != 0 )\n        mbedtls_printf( \"  X.509 certificate load: \" );\n\n    mbedtls_x509_crt_init( &clicert );\n\n    ret = mbedtls_x509_crt_parse( &clicert, (const unsigned char *) mbedtls_test_cli_crt,\n                           mbedtls_test_cli_crt_len );\n    if( ret != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        return( ret );\n    }\n\n    mbedtls_x509_crt_init( &cacert );\n\n    ret = mbedtls_x509_crt_parse( &cacert, (const unsigned char *) mbedtls_test_ca_crt,\n                          mbedtls_test_ca_crt_len );\n    if( ret != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        return( ret );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n  X.509 signature verify: \");\n\n    ret = mbedtls_x509_crt_verify( &clicert, &cacert, NULL, NULL, &flags, NULL, NULL );\n    if( ret != 0 )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"failed\\n\" );\n\n        return( ret );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"passed\\n\\n\");\n\n    mbedtls_x509_crt_free( &cacert  );\n    mbedtls_x509_crt_free( &clicert );\n\n    return( 0 );\n#else\n    ((void) verbose);\n    return( 0 );\n#endif /* MBEDTLS_CERTS_C && MBEDTLS_SHA1_C */\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_X509_USE_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/x509_create.c",
    "content": "/*\n *  X.509 base functions for creating certificates / CSRs\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_X509_CREATE_C)\n\n#include \"mbedtls/x509.h\"\n#include \"mbedtls/asn1write.h\"\n#include \"mbedtls/oid.h\"\n\n#include <string.h>\n\ntypedef struct {\n    const char *name;\n    size_t name_len;\n    const char*oid;\n} x509_attr_descriptor_t;\n\n#define ADD_STRLEN( s )     s, sizeof( s ) - 1\n\nstatic const x509_attr_descriptor_t x509_attrs[] =\n{\n    { ADD_STRLEN( \"CN\" ),                       MBEDTLS_OID_AT_CN },\n    { ADD_STRLEN( \"commonName\" ),               MBEDTLS_OID_AT_CN },\n    { ADD_STRLEN( \"C\" ),                        MBEDTLS_OID_AT_COUNTRY },\n    { ADD_STRLEN( \"countryName\" ),              MBEDTLS_OID_AT_COUNTRY },\n    { ADD_STRLEN( \"O\" ),                        MBEDTLS_OID_AT_ORGANIZATION },\n    { ADD_STRLEN( \"organizationName\" ),         MBEDTLS_OID_AT_ORGANIZATION },\n    { ADD_STRLEN( \"L\" ),                        MBEDTLS_OID_AT_LOCALITY },\n    { ADD_STRLEN( \"locality\" ),                 MBEDTLS_OID_AT_LOCALITY },\n    { ADD_STRLEN( \"R\" ),                        MBEDTLS_OID_PKCS9_EMAIL },\n    { ADD_STRLEN( \"OU\" ),                       MBEDTLS_OID_AT_ORG_UNIT },\n    { ADD_STRLEN( \"organizationalUnitName\" ),   MBEDTLS_OID_AT_ORG_UNIT },\n    { ADD_STRLEN( \"ST\" ),                       MBEDTLS_OID_AT_STATE },\n    { ADD_STRLEN( \"stateOrProvinceName\" ),      MBEDTLS_OID_AT_STATE },\n    { ADD_STRLEN( \"emailAddress\" ),             MBEDTLS_OID_PKCS9_EMAIL },\n    { ADD_STRLEN( \"serialNumber\" ),             MBEDTLS_OID_AT_SERIAL_NUMBER },\n    { ADD_STRLEN( \"postalAddress\" ),            MBEDTLS_OID_AT_POSTAL_ADDRESS },\n    { ADD_STRLEN( \"postalCode\" ),               MBEDTLS_OID_AT_POSTAL_CODE },\n    { ADD_STRLEN( \"dnQualifier\" ),              MBEDTLS_OID_AT_DN_QUALIFIER },\n    { ADD_STRLEN( \"title\" ),                    MBEDTLS_OID_AT_TITLE },\n    { ADD_STRLEN( \"surName\" ),                  MBEDTLS_OID_AT_SUR_NAME },\n    { ADD_STRLEN( \"SN\" ),                       MBEDTLS_OID_AT_SUR_NAME },\n    { ADD_STRLEN( \"givenName\" ),                MBEDTLS_OID_AT_GIVEN_NAME },\n    { ADD_STRLEN( \"GN\" ),                       MBEDTLS_OID_AT_GIVEN_NAME },\n    { ADD_STRLEN( \"initials\" ),                 MBEDTLS_OID_AT_INITIALS },\n    { ADD_STRLEN( \"pseudonym\" ),                MBEDTLS_OID_AT_PSEUDONYM },\n    { ADD_STRLEN( \"generationQualifier\" ),      MBEDTLS_OID_AT_GENERATION_QUALIFIER },\n    { ADD_STRLEN( \"domainComponent\" ),          MBEDTLS_OID_DOMAIN_COMPONENT },\n    { ADD_STRLEN( \"DC\" ),                       MBEDTLS_OID_DOMAIN_COMPONENT },\n    { NULL, 0, NULL }\n};\n\nstatic const char *x509_at_oid_from_name( const char *name, size_t name_len )\n{\n    const x509_attr_descriptor_t *cur;\n\n    for( cur = x509_attrs; cur->name != NULL; cur++ )\n        if( cur->name_len == name_len &&\n            strncmp( cur->name, name, name_len ) == 0 )\n            break;\n\n    return( cur->oid );\n}\n\nint mbedtls_x509_string_to_names( mbedtls_asn1_named_data **head, const char *name )\n{\n    int ret = 0;\n    const char *s = name, *c = s;\n    const char *end = s + strlen( s );\n    const char *oid = NULL;\n    int in_tag = 1;\n    char data[MBEDTLS_X509_MAX_DN_NAME_SIZE];\n    char *d = data;\n\n    /* Clear existing chain if present */\n    mbedtls_asn1_free_named_data_list( head );\n\n    while( c <= end )\n    {\n        if( in_tag && *c == '=' )\n        {\n            if( ( oid = x509_at_oid_from_name( s, c - s ) ) == NULL )\n            {\n                ret = MBEDTLS_ERR_X509_UNKNOWN_OID;\n                goto exit;\n            }\n\n            s = c + 1;\n            in_tag = 0;\n            d = data;\n        }\n\n        if( !in_tag && *c == '\\\\' && c != end )\n        {\n            c++;\n\n            /* Check for valid escaped characters */\n            if( c == end || *c != ',' )\n            {\n                ret = MBEDTLS_ERR_X509_INVALID_NAME;\n                goto exit;\n            }\n        }\n        else if( !in_tag && ( *c == ',' || c == end ) )\n        {\n            if( mbedtls_asn1_store_named_data( head, oid, strlen( oid ),\n                                       (unsigned char *) data,\n                                       d - data ) == NULL )\n            {\n                return( MBEDTLS_ERR_X509_ALLOC_FAILED );\n            }\n\n            while( c < end && *(c + 1) == ' ' )\n                c++;\n\n            s = c + 1;\n            in_tag = 1;\n        }\n\n        if( !in_tag && s != c + 1 )\n        {\n            *(d++) = *c;\n\n            if( d - data == MBEDTLS_X509_MAX_DN_NAME_SIZE )\n            {\n                ret = MBEDTLS_ERR_X509_INVALID_NAME;\n                goto exit;\n            }\n        }\n\n        c++;\n    }\n\nexit:\n\n    return( ret );\n}\n\n/* The first byte of the value in the mbedtls_asn1_named_data structure is reserved\n * to store the critical boolean for us\n */\nint mbedtls_x509_set_extension( mbedtls_asn1_named_data **head, const char *oid, size_t oid_len,\n                        int critical, const unsigned char *val, size_t val_len )\n{\n    mbedtls_asn1_named_data *cur;\n\n    if( ( cur = mbedtls_asn1_store_named_data( head, oid, oid_len,\n                                       NULL, val_len + 1 ) ) == NULL )\n    {\n        return( MBEDTLS_ERR_X509_ALLOC_FAILED );\n    }\n\n    cur->val.p[0] = critical;\n    memcpy( cur->val.p + 1, val, val_len );\n\n    return( 0 );\n}\n\n/*\n *  RelativeDistinguishedName ::=\n *    SET OF AttributeTypeAndValue\n *\n *  AttributeTypeAndValue ::= SEQUENCE {\n *    type     AttributeType,\n *    value    AttributeValue }\n *\n *  AttributeType ::= OBJECT IDENTIFIER\n *\n *  AttributeValue ::= ANY DEFINED BY AttributeType\n */\nstatic int x509_write_name( unsigned char **p, unsigned char *start,\n                            const char *oid, size_t oid_len,\n                            const unsigned char *name, size_t name_len )\n{\n    int ret;\n    size_t len = 0;\n\n    // Write PrintableString for all except MBEDTLS_OID_PKCS9_EMAIL\n    //\n    if( MBEDTLS_OID_SIZE( MBEDTLS_OID_PKCS9_EMAIL ) == oid_len &&\n        memcmp( oid, MBEDTLS_OID_PKCS9_EMAIL, oid_len ) == 0 )\n    {\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_ia5_string( p, start,\n                                                  (const char *) name,\n                                                  name_len ) );\n    }\n    else\n    {\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_printable_string( p, start,\n                                                        (const char *) name,\n                                                        name_len ) );\n    }\n\n    // Write OID\n    //\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_oid( p, start, oid, oid_len ) );\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED |\n                                                 MBEDTLS_ASN1_SEQUENCE ) );\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED |\n                                                 MBEDTLS_ASN1_SET ) );\n\n    return( (int) len );\n}\n\nint mbedtls_x509_write_names( unsigned char **p, unsigned char *start,\n                      mbedtls_asn1_named_data *first )\n{\n    int ret;\n    size_t len = 0;\n    mbedtls_asn1_named_data *cur = first;\n\n    while( cur != NULL )\n    {\n        MBEDTLS_ASN1_CHK_ADD( len, x509_write_name( p, start, (char *) cur->oid.p,\n                                            cur->oid.len,\n                                            cur->val.p, cur->val.len ) );\n        cur = cur->next;\n    }\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED |\n                                                 MBEDTLS_ASN1_SEQUENCE ) );\n\n    return( (int) len );\n}\n\nint mbedtls_x509_write_sig( unsigned char **p, unsigned char *start,\n                    const char *oid, size_t oid_len,\n                    unsigned char *sig, size_t size )\n{\n    int ret;\n    size_t len = 0;\n\n    if( *p < start || (size_t)( *p - start ) < size )\n        return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n    len = size;\n    (*p) -= len;\n    memcpy( *p, sig, len );\n\n    if( *p - start < 1 )\n        return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n    *--(*p) = 0;\n    len += 1;\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_BIT_STRING ) );\n\n    // Write OID\n    //\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_algorithm_identifier( p, start, oid,\n                                                        oid_len, 0 ) );\n\n    return( (int) len );\n}\n\nstatic int x509_write_extension( unsigned char **p, unsigned char *start,\n                                 mbedtls_asn1_named_data *ext )\n{\n    int ret;\n    size_t len = 0;\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, ext->val.p + 1,\n                                              ext->val.len - 1 ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, ext->val.len - 1 ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_OCTET_STRING ) );\n\n    if( ext->val.p[0] != 0 )\n    {\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_bool( p, start, 1 ) );\n    }\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, ext->oid.p,\n                                              ext->oid.len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, ext->oid.len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_OID ) );\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED |\n                                                 MBEDTLS_ASN1_SEQUENCE ) );\n\n    return( (int) len );\n}\n\n/*\n * Extension  ::=  SEQUENCE  {\n *     extnID      OBJECT IDENTIFIER,\n *     critical    BOOLEAN DEFAULT FALSE,\n *     extnValue   OCTET STRING\n *                 -- contains the DER encoding of an ASN.1 value\n *                 -- corresponding to the extension type identified\n *                 -- by extnID\n *     }\n */\nint mbedtls_x509_write_extensions( unsigned char **p, unsigned char *start,\n                           mbedtls_asn1_named_data *first )\n{\n    int ret;\n    size_t len = 0;\n    mbedtls_asn1_named_data *cur_ext = first;\n\n    while( cur_ext != NULL )\n    {\n        MBEDTLS_ASN1_CHK_ADD( len, x509_write_extension( p, start, cur_ext ) );\n        cur_ext = cur_ext->next;\n    }\n\n    return( (int) len );\n}\n\n#endif /* MBEDTLS_X509_CREATE_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/x509_crl.c",
    "content": "/*\n *  X.509 Certidicate Revocation List (CRL) parsing\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The ITU-T X.509 standard defines a certificate format for PKI.\n *\n *  http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs)\n *  http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs)\n *  http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10)\n *\n *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf\n *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_X509_CRL_PARSE_C)\n\n#include \"mbedtls/x509_crl.h\"\n#include \"mbedtls/oid.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_PEM_PARSE_C)\n#include \"mbedtls/pem.h\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#include <stdio.h>\n#define mbedtls_free       free\n#define mbedtls_calloc    calloc\n#define mbedtls_snprintf   snprintf\n#endif\n\n#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)\n#include <windows.h>\n#else\n#include <time.h>\n#endif\n\n#if defined(MBEDTLS_FS_IO) || defined(EFIX64) || defined(EFI32)\n#include <stdio.h>\n#endif\n\n/*\n *  Version  ::=  INTEGER  {  v1(0), v2(1)  }\n */\nstatic int x509_crl_get_version( unsigned char **p,\n                             const unsigned char *end,\n                             int *ver )\n{\n    int ret;\n\n    if( ( ret = mbedtls_asn1_get_int( p, end, ver ) ) != 0 )\n    {\n        if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )\n        {\n            *ver = 0;\n            return( 0 );\n        }\n\n        return( MBEDTLS_ERR_X509_INVALID_VERSION + ret );\n    }\n\n    return( 0 );\n}\n\n/*\n * X.509 CRL v2 extensions\n *\n * We currently don't parse any extension's content, but we do check that the\n * list of extensions is well-formed and abort on critical extensions (that\n * are unsupported as we don't support any extension so far)\n */\nstatic int x509_get_crl_ext( unsigned char **p,\n                             const unsigned char *end,\n                             mbedtls_x509_buf *ext )\n{\n    int ret;\n\n    /*\n     * crlExtensions           [0]  EXPLICIT Extensions OPTIONAL\n     *                              -- if present, version MUST be v2\n     */\n    if( ( ret = mbedtls_x509_get_ext( p, end, ext, 0 ) ) != 0 )\n    {\n        if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )\n            return( 0 );\n\n        return( ret );\n    }\n\n    while( *p < end )\n    {\n        /*\n         * Extension  ::=  SEQUENCE  {\n         *      extnID      OBJECT IDENTIFIER,\n         *      critical    BOOLEAN DEFAULT FALSE,\n         *      extnValue   OCTET STRING  }\n         */\n        int is_critical = 0;\n        const unsigned char *end_ext_data;\n        size_t len;\n\n        /* Get enclosing sequence tag */\n        if( ( ret = mbedtls_asn1_get_tag( p, end, &len,\n                MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n\n        end_ext_data = *p + len;\n\n        /* Get OID (currently ignored) */\n        if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len,\n                                          MBEDTLS_ASN1_OID ) ) != 0 )\n        {\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n        }\n        *p += len;\n\n        /* Get optional critical */\n        if( ( ret = mbedtls_asn1_get_bool( p, end_ext_data,\n                                           &is_critical ) ) != 0 &&\n            ( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) )\n        {\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n        }\n\n        /* Data should be octet string type */\n        if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len,\n                MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n\n        /* Ignore data so far and just check its length */\n        *p += len;\n        if( *p != end_ext_data )\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                    MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n        /* Abort on (unsupported) critical extensions */\n        if( is_critical )\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                    MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );\n    }\n\n    if( *p != end )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    return( 0 );\n}\n\n/*\n * X.509 CRL v2 entry extensions (no extensions parsed yet.)\n */\nstatic int x509_get_crl_entry_ext( unsigned char **p,\n                             const unsigned char *end,\n                             mbedtls_x509_buf *ext )\n{\n    int ret;\n    size_t len = 0;\n\n    /* OPTIONAL */\n    if( end <= *p )\n        return( 0 );\n\n    ext->tag = **p;\n    ext->p = *p;\n\n    /*\n     * Get CRL-entry extension sequence header\n     * crlEntryExtensions      Extensions OPTIONAL  -- if present, MUST be v2\n     */\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &ext->len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )\n        {\n            ext->p = NULL;\n            return( 0 );\n        }\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n    }\n\n    end = *p + ext->len;\n\n    if( end != *p + ext->len )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    while( *p < end )\n    {\n        if( ( ret = mbedtls_asn1_get_tag( p, end, &len,\n                MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n\n        *p += len;\n    }\n\n    if( *p != end )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    return( 0 );\n}\n\n/*\n * X.509 CRL Entries\n */\nstatic int x509_get_entries( unsigned char **p,\n                             const unsigned char *end,\n                             mbedtls_x509_crl_entry *entry )\n{\n    int ret;\n    size_t entry_len;\n    mbedtls_x509_crl_entry *cur_entry = entry;\n\n    if( *p == end )\n        return( 0 );\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &entry_len,\n            MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED ) ) != 0 )\n    {\n        if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )\n            return( 0 );\n\n        return( ret );\n    }\n\n    end = *p + entry_len;\n\n    while( *p < end )\n    {\n        size_t len2;\n        const unsigned char *end2;\n\n        if( ( ret = mbedtls_asn1_get_tag( p, end, &len2,\n                MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED ) ) != 0 )\n        {\n            return( ret );\n        }\n\n        cur_entry->raw.tag = **p;\n        cur_entry->raw.p = *p;\n        cur_entry->raw.len = len2;\n        end2 = *p + len2;\n\n        if( ( ret = mbedtls_x509_get_serial( p, end2, &cur_entry->serial ) ) != 0 )\n            return( ret );\n\n        if( ( ret = mbedtls_x509_get_time( p, end2,\n                                   &cur_entry->revocation_date ) ) != 0 )\n            return( ret );\n\n        if( ( ret = x509_get_crl_entry_ext( p, end2,\n                                            &cur_entry->entry_ext ) ) != 0 )\n            return( ret );\n\n        if( *p < end )\n        {\n            cur_entry->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_crl_entry ) );\n\n            if( cur_entry->next == NULL )\n                return( MBEDTLS_ERR_X509_ALLOC_FAILED );\n\n            cur_entry = cur_entry->next;\n        }\n    }\n\n    return( 0 );\n}\n\n/*\n * Parse one  CRLs in DER format and append it to the chained list\n */\nint mbedtls_x509_crl_parse_der( mbedtls_x509_crl *chain,\n                        const unsigned char *buf, size_t buflen )\n{\n    int ret;\n    size_t len;\n    unsigned char *p = NULL, *end = NULL;\n    mbedtls_x509_buf sig_params1, sig_params2, sig_oid2;\n    mbedtls_x509_crl *crl = chain;\n\n    /*\n     * Check for valid input\n     */\n    if( crl == NULL || buf == NULL )\n        return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n\n    memset( &sig_params1, 0, sizeof( mbedtls_x509_buf ) );\n    memset( &sig_params2, 0, sizeof( mbedtls_x509_buf ) );\n    memset( &sig_oid2, 0, sizeof( mbedtls_x509_buf ) );\n\n    /*\n     * Add new CRL on the end of the chain if needed.\n     */\n    while( crl->version != 0 && crl->next != NULL )\n        crl = crl->next;\n\n    if( crl->version != 0 && crl->next == NULL )\n    {\n        crl->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_crl ) );\n\n        if( crl->next == NULL )\n        {\n            mbedtls_x509_crl_free( crl );\n            return( MBEDTLS_ERR_X509_ALLOC_FAILED );\n        }\n\n        mbedtls_x509_crl_init( crl->next );\n        crl = crl->next;\n    }\n\n    /*\n     * Copy raw DER-encoded CRL\n     */\n    if( buflen == 0 )\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT );\n\n    p = mbedtls_calloc( 1, buflen );\n    if( p == NULL )\n        return( MBEDTLS_ERR_X509_ALLOC_FAILED );\n\n    memcpy( p, buf, buflen );\n\n    crl->raw.p = p;\n    crl->raw.len = buflen;\n\n    end = p + buflen;\n\n    /*\n     * CertificateList  ::=  SEQUENCE  {\n     *      tbsCertList          TBSCertList,\n     *      signatureAlgorithm   AlgorithmIdentifier,\n     *      signatureValue       BIT STRING  }\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        mbedtls_x509_crl_free( crl );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT );\n    }\n\n    if( len != (size_t) ( end - p ) )\n    {\n        mbedtls_x509_crl_free( crl );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n    }\n\n    /*\n     * TBSCertList  ::=  SEQUENCE  {\n     */\n    crl->tbs.p = p;\n\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        mbedtls_x509_crl_free( crl );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );\n    }\n\n    end = p + len;\n    crl->tbs.len = end - crl->tbs.p;\n\n    /*\n     * Version  ::=  INTEGER  OPTIONAL {  v1(0), v2(1)  }\n     *               -- if present, MUST be v2\n     *\n     * signature            AlgorithmIdentifier\n     */\n    if( ( ret = x509_crl_get_version( &p, end, &crl->version ) ) != 0 ||\n        ( ret = mbedtls_x509_get_alg( &p, end, &crl->sig_oid, &sig_params1 ) ) != 0 )\n    {\n        mbedtls_x509_crl_free( crl );\n        return( ret );\n    }\n\n    if( crl->version < 0 || crl->version > 1 )\n    {\n        mbedtls_x509_crl_free( crl );\n        return( MBEDTLS_ERR_X509_UNKNOWN_VERSION );\n    }\n\n    crl->version++;\n\n    if( ( ret = mbedtls_x509_get_sig_alg( &crl->sig_oid, &sig_params1,\n                                  &crl->sig_md, &crl->sig_pk,\n                                  &crl->sig_opts ) ) != 0 )\n    {\n        mbedtls_x509_crl_free( crl );\n        return( MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG );\n    }\n\n    /*\n     * issuer               Name\n     */\n    crl->issuer_raw.p = p;\n\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        mbedtls_x509_crl_free( crl );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );\n    }\n\n    if( ( ret = mbedtls_x509_get_name( &p, p + len, &crl->issuer ) ) != 0 )\n    {\n        mbedtls_x509_crl_free( crl );\n        return( ret );\n    }\n\n    crl->issuer_raw.len = p - crl->issuer_raw.p;\n\n    /*\n     * thisUpdate          Time\n     * nextUpdate          Time OPTIONAL\n     */\n    if( ( ret = mbedtls_x509_get_time( &p, end, &crl->this_update ) ) != 0 )\n    {\n        mbedtls_x509_crl_free( crl );\n        return( ret );\n    }\n\n    if( ( ret = mbedtls_x509_get_time( &p, end, &crl->next_update ) ) != 0 )\n    {\n        if( ret != ( MBEDTLS_ERR_X509_INVALID_DATE +\n                        MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) &&\n            ret != ( MBEDTLS_ERR_X509_INVALID_DATE +\n                        MBEDTLS_ERR_ASN1_OUT_OF_DATA ) )\n        {\n            mbedtls_x509_crl_free( crl );\n            return( ret );\n        }\n    }\n\n    /*\n     * revokedCertificates    SEQUENCE OF SEQUENCE   {\n     *      userCertificate        CertificateSerialNumber,\n     *      revocationDate         Time,\n     *      crlEntryExtensions     Extensions OPTIONAL\n     *                                   -- if present, MUST be v2\n     *                        } OPTIONAL\n     */\n    if( ( ret = x509_get_entries( &p, end, &crl->entry ) ) != 0 )\n    {\n        mbedtls_x509_crl_free( crl );\n        return( ret );\n    }\n\n    /*\n     * crlExtensions          EXPLICIT Extensions OPTIONAL\n     *                              -- if present, MUST be v2\n     */\n    if( crl->version == 2 )\n    {\n        ret = x509_get_crl_ext( &p, end, &crl->crl_ext );\n\n        if( ret != 0 )\n        {\n            mbedtls_x509_crl_free( crl );\n            return( ret );\n        }\n    }\n\n    if( p != end )\n    {\n        mbedtls_x509_crl_free( crl );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n    }\n\n    end = crl->raw.p + crl->raw.len;\n\n    /*\n     *  signatureAlgorithm   AlgorithmIdentifier,\n     *  signatureValue       BIT STRING\n     */\n    if( ( ret = mbedtls_x509_get_alg( &p, end, &sig_oid2, &sig_params2 ) ) != 0 )\n    {\n        mbedtls_x509_crl_free( crl );\n        return( ret );\n    }\n\n    if( crl->sig_oid.len != sig_oid2.len ||\n        memcmp( crl->sig_oid.p, sig_oid2.p, crl->sig_oid.len ) != 0 ||\n        sig_params1.len != sig_params2.len ||\n        ( sig_params1.len != 0 &&\n          memcmp( sig_params1.p, sig_params2.p, sig_params1.len ) != 0 ) )\n    {\n        mbedtls_x509_crl_free( crl );\n        return( MBEDTLS_ERR_X509_SIG_MISMATCH );\n    }\n\n    if( ( ret = mbedtls_x509_get_sig( &p, end, &crl->sig ) ) != 0 )\n    {\n        mbedtls_x509_crl_free( crl );\n        return( ret );\n    }\n\n    if( p != end )\n    {\n        mbedtls_x509_crl_free( crl );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n    }\n\n    return( 0 );\n}\n\n/*\n * Parse one or more CRLs and add them to the chained list\n */\nint mbedtls_x509_crl_parse( mbedtls_x509_crl *chain, const unsigned char *buf, size_t buflen )\n{\n#if defined(MBEDTLS_PEM_PARSE_C)\n    int ret;\n    size_t use_len;\n    mbedtls_pem_context pem;\n    int is_pem = 0;\n\n    if( chain == NULL || buf == NULL )\n        return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n\n    do\n    {\n        mbedtls_pem_init( &pem );\n\n        // Avoid calling mbedtls_pem_read_buffer() on non-null-terminated\n        // string\n        if( buflen == 0 || buf[buflen - 1] != '\\0' )\n            ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;\n        else\n            ret = mbedtls_pem_read_buffer( &pem,\n                                           \"-----BEGIN X509 CRL-----\",\n                                           \"-----END X509 CRL-----\",\n                                            buf, NULL, 0, &use_len );\n\n        if( ret == 0 )\n        {\n            /*\n             * Was PEM encoded\n             */\n            is_pem = 1;\n\n            buflen -= use_len;\n            buf += use_len;\n\n            if( ( ret = mbedtls_x509_crl_parse_der( chain,\n                                            pem.buf, pem.buflen ) ) != 0 )\n            {\n                mbedtls_pem_free( &pem );\n                return( ret );\n            }\n        }\n        else if( is_pem )\n        {\n            mbedtls_pem_free( &pem );\n            return( ret );\n        }\n\n        mbedtls_pem_free( &pem );\n    }\n    /* In the PEM case, buflen is 1 at the end, for the terminated NULL byte.\n     * And a valid CRL cannot be less than 1 byte anyway. */\n    while( is_pem && buflen > 1 );\n\n    if( is_pem )\n        return( 0 );\n    else\n#endif /* MBEDTLS_PEM_PARSE_C */\n        return( mbedtls_x509_crl_parse_der( chain, buf, buflen ) );\n}\n\n#if defined(MBEDTLS_FS_IO)\n/*\n * Load one or more CRLs and add them to the chained list\n */\nint mbedtls_x509_crl_parse_file( mbedtls_x509_crl *chain, const char *path )\n{\n    int ret;\n    size_t n;\n    unsigned char *buf;\n\n    if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )\n        return( ret );\n\n    ret = mbedtls_x509_crl_parse( chain, buf, n );\n\n    mbedtls_platform_zeroize( buf, n );\n    mbedtls_free( buf );\n\n    return( ret );\n}\n#endif /* MBEDTLS_FS_IO */\n\n/*\n * Return an informational string about the certificate.\n */\n#define BEFORE_COLON    14\n#define BC              \"14\"\n/*\n * Return an informational string about the CRL.\n */\nint mbedtls_x509_crl_info( char *buf, size_t size, const char *prefix,\n                   const mbedtls_x509_crl *crl )\n{\n    int ret;\n    size_t n;\n    char *p;\n    const mbedtls_x509_crl_entry *entry;\n\n    p = buf;\n    n = size;\n\n    ret = mbedtls_snprintf( p, n, \"%sCRL version   : %d\",\n                               prefix, crl->version );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    ret = mbedtls_snprintf( p, n, \"\\n%sissuer name   : \", prefix );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n    ret = mbedtls_x509_dn_gets( p, n, &crl->issuer );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    ret = mbedtls_snprintf( p, n, \"\\n%sthis update   : \" \\\n                   \"%04d-%02d-%02d %02d:%02d:%02d\", prefix,\n                   crl->this_update.year, crl->this_update.mon,\n                   crl->this_update.day,  crl->this_update.hour,\n                   crl->this_update.min,  crl->this_update.sec );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    ret = mbedtls_snprintf( p, n, \"\\n%snext update   : \" \\\n                   \"%04d-%02d-%02d %02d:%02d:%02d\", prefix,\n                   crl->next_update.year, crl->next_update.mon,\n                   crl->next_update.day,  crl->next_update.hour,\n                   crl->next_update.min,  crl->next_update.sec );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    entry = &crl->entry;\n\n    ret = mbedtls_snprintf( p, n, \"\\n%sRevoked certificates:\",\n                               prefix );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    while( entry != NULL && entry->raw.len != 0 )\n    {\n        ret = mbedtls_snprintf( p, n, \"\\n%sserial number: \",\n                               prefix );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n\n        ret = mbedtls_x509_serial_gets( p, n, &entry->serial );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n\n        ret = mbedtls_snprintf( p, n, \" revocation date: \" \\\n                   \"%04d-%02d-%02d %02d:%02d:%02d\",\n                   entry->revocation_date.year, entry->revocation_date.mon,\n                   entry->revocation_date.day,  entry->revocation_date.hour,\n                   entry->revocation_date.min,  entry->revocation_date.sec );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n\n        entry = entry->next;\n    }\n\n    ret = mbedtls_snprintf( p, n, \"\\n%ssigned using  : \", prefix );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    ret = mbedtls_x509_sig_alg_gets( p, n, &crl->sig_oid, crl->sig_pk, crl->sig_md,\n                             crl->sig_opts );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    ret = mbedtls_snprintf( p, n, \"\\n\" );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    return( (int) ( size - n ) );\n}\n\n/*\n * Initialize a CRL chain\n */\nvoid mbedtls_x509_crl_init( mbedtls_x509_crl *crl )\n{\n    memset( crl, 0, sizeof(mbedtls_x509_crl) );\n}\n\n/*\n * Unallocate all CRL data\n */\nvoid mbedtls_x509_crl_free( mbedtls_x509_crl *crl )\n{\n    mbedtls_x509_crl *crl_cur = crl;\n    mbedtls_x509_crl *crl_prv;\n    mbedtls_x509_name *name_cur;\n    mbedtls_x509_name *name_prv;\n    mbedtls_x509_crl_entry *entry_cur;\n    mbedtls_x509_crl_entry *entry_prv;\n\n    if( crl == NULL )\n        return;\n\n    do\n    {\n#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)\n        mbedtls_free( crl_cur->sig_opts );\n#endif\n\n        name_cur = crl_cur->issuer.next;\n        while( name_cur != NULL )\n        {\n            name_prv = name_cur;\n            name_cur = name_cur->next;\n            mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) );\n            mbedtls_free( name_prv );\n        }\n\n        entry_cur = crl_cur->entry.next;\n        while( entry_cur != NULL )\n        {\n            entry_prv = entry_cur;\n            entry_cur = entry_cur->next;\n            mbedtls_platform_zeroize( entry_prv,\n                                      sizeof( mbedtls_x509_crl_entry ) );\n            mbedtls_free( entry_prv );\n        }\n\n        if( crl_cur->raw.p != NULL )\n        {\n            mbedtls_platform_zeroize( crl_cur->raw.p, crl_cur->raw.len );\n            mbedtls_free( crl_cur->raw.p );\n        }\n\n        crl_cur = crl_cur->next;\n    }\n    while( crl_cur != NULL );\n\n    crl_cur = crl;\n    do\n    {\n        crl_prv = crl_cur;\n        crl_cur = crl_cur->next;\n\n        mbedtls_platform_zeroize( crl_prv, sizeof( mbedtls_x509_crl ) );\n        if( crl_prv != crl )\n            mbedtls_free( crl_prv );\n    }\n    while( crl_cur != NULL );\n}\n\n#endif /* MBEDTLS_X509_CRL_PARSE_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/x509_crt.c",
    "content": "/*\n *  X.509 certificate parsing and verification\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The ITU-T X.509 standard defines a certificate format for PKI.\n *\n *  http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs)\n *  http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs)\n *  http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10)\n *\n *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf\n *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf\n *\n *  [SIRO] https://cabforum.org/wp-content/uploads/Chunghwatelecom201503cabforumV4.pdf\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n\n#include \"mbedtls/x509_crt.h\"\n#include \"mbedtls/oid.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <stdio.h>\n#include <string.h>\n\n#if defined(MBEDTLS_PEM_PARSE_C)\n#include \"mbedtls/pem.h\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#define mbedtls_free       free\n#define mbedtls_calloc    calloc\n#define mbedtls_snprintf   snprintf\n#endif\n\n#if defined(MBEDTLS_THREADING_C)\n#include \"mbedtls/threading.h\"\n#endif\n\n#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)\n#include <windows.h>\n#if defined(_MSC_VER) && _MSC_VER <= 1600\n/* Visual Studio 2010 and earlier issue a warning when both <stdint.h> and\n * <intsafe.h> are included, as they redefine a number of <TYPE>_MAX constants.\n * These constants are guaranteed to be the same, though, so we suppress the\n * warning when including intsafe.h.\n */\n#pragma warning( push )\n#pragma warning( disable : 4005 )\n#endif\n#include <intsafe.h>\n#if defined(_MSC_VER) && _MSC_VER <= 1600\n#pragma warning( pop )\n#endif\n#else\n#include <time.h>\n#endif\n\n#if defined(MBEDTLS_FS_IO)\n#include <stdio.h>\n#if !defined(_WIN32) || defined(EFIX64) || defined(EFI32)\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <dirent.h>\n#endif /* !_WIN32 || EFIX64 || EFI32 */\n#endif\n\n/*\n * Item in a verification chain: cert and flags for it\n */\ntypedef struct {\n    mbedtls_x509_crt *crt;\n    uint32_t flags;\n} x509_crt_verify_chain_item;\n\n/*\n * Max size of verification chain: end-entity + intermediates + trusted root\n */\n#define X509_MAX_VERIFY_CHAIN_SIZE    ( MBEDTLS_X509_MAX_INTERMEDIATE_CA + 2 )\n\n/*\n * Default profile\n */\nconst mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default =\n{\n#if defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES)\n    /* Allow SHA-1 (weak, but still safe in controlled environments) */\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA1 ) |\n#endif\n    /* Only SHA-2 hashes */\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 ) |\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),\n    0xFFFFFFF, /* Any PK alg    */\n    0xFFFFFFF, /* Any curve     */\n    2048,\n};\n\n/*\n * Next-default profile\n */\nconst mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next =\n{\n    /* Hashes from SHA-256 and above */\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),\n    0xFFFFFFF, /* Any PK alg    */\n#if defined(MBEDTLS_ECP_C)\n    /* Curves at or above 128-bit security level */\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ) |\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP521R1 ) |\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP256R1 ) |\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP384R1 ) |\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP512R1 ) |\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256K1 ),\n#else\n    0,\n#endif\n    2048,\n};\n\n/*\n * NSA Suite B Profile\n */\nconst mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb =\n{\n    /* Only SHA-256 and 384 */\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ),\n    /* Only ECDSA */\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECDSA ) |\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECKEY ),\n#if defined(MBEDTLS_ECP_C)\n    /* Only NIST P-256 and P-384 */\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |\n    MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ),\n#else\n    0,\n#endif\n    0,\n};\n\n/*\n * Check md_alg against profile\n * Return 0 if md_alg is acceptable for this profile, -1 otherwise\n */\nstatic int x509_profile_check_md_alg( const mbedtls_x509_crt_profile *profile,\n                                      mbedtls_md_type_t md_alg )\n{\n    if( ( profile->allowed_mds & MBEDTLS_X509_ID_FLAG( md_alg ) ) != 0 )\n        return( 0 );\n\n    return( -1 );\n}\n\n/*\n * Check pk_alg against profile\n * Return 0 if pk_alg is acceptable for this profile, -1 otherwise\n */\nstatic int x509_profile_check_pk_alg( const mbedtls_x509_crt_profile *profile,\n                                      mbedtls_pk_type_t pk_alg )\n{\n    if( ( profile->allowed_pks & MBEDTLS_X509_ID_FLAG( pk_alg ) ) != 0 )\n        return( 0 );\n\n    return( -1 );\n}\n\n/*\n * Check key against profile\n * Return 0 if pk is acceptable for this profile, -1 otherwise\n */\nstatic int x509_profile_check_key( const mbedtls_x509_crt_profile *profile,\n                                   const mbedtls_pk_context *pk )\n{\n    const mbedtls_pk_type_t pk_alg = mbedtls_pk_get_type( pk );\n\n#if defined(MBEDTLS_RSA_C)\n    if( pk_alg == MBEDTLS_PK_RSA || pk_alg == MBEDTLS_PK_RSASSA_PSS )\n    {\n        if( mbedtls_pk_get_bitlen( pk ) >= profile->rsa_min_bitlen )\n            return( 0 );\n\n        return( -1 );\n    }\n#endif\n\n#if defined(MBEDTLS_ECP_C)\n    if( pk_alg == MBEDTLS_PK_ECDSA ||\n        pk_alg == MBEDTLS_PK_ECKEY ||\n        pk_alg == MBEDTLS_PK_ECKEY_DH )\n    {\n        const mbedtls_ecp_group_id gid = mbedtls_pk_ec( *pk )->grp.id;\n\n        if( ( profile->allowed_curves & MBEDTLS_X509_ID_FLAG( gid ) ) != 0 )\n            return( 0 );\n\n        return( -1 );\n    }\n#endif\n\n    return( -1 );\n}\n\n/*\n *  Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }\n */\nstatic int x509_get_version( unsigned char **p,\n                             const unsigned char *end,\n                             int *ver )\n{\n    int ret;\n    size_t len;\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &len,\n            MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) != 0 )\n    {\n        if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )\n        {\n            *ver = 0;\n            return( 0 );\n        }\n\n        return( ret );\n    }\n\n    end = *p + len;\n\n    if( ( ret = mbedtls_asn1_get_int( p, end, ver ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_VERSION + ret );\n\n    if( *p != end )\n        return( MBEDTLS_ERR_X509_INVALID_VERSION +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    return( 0 );\n}\n\n/*\n *  Validity ::= SEQUENCE {\n *       notBefore      Time,\n *       notAfter       Time }\n */\nstatic int x509_get_dates( unsigned char **p,\n                           const unsigned char *end,\n                           mbedtls_x509_time *from,\n                           mbedtls_x509_time *to )\n{\n    int ret;\n    size_t len;\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_DATE + ret );\n\n    end = *p + len;\n\n    if( ( ret = mbedtls_x509_get_time( p, end, from ) ) != 0 )\n        return( ret );\n\n    if( ( ret = mbedtls_x509_get_time( p, end, to ) ) != 0 )\n        return( ret );\n\n    if( *p != end )\n        return( MBEDTLS_ERR_X509_INVALID_DATE +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    return( 0 );\n}\n\n/*\n * X.509 v2/v3 unique identifier (not parsed)\n */\nstatic int x509_get_uid( unsigned char **p,\n                         const unsigned char *end,\n                         mbedtls_x509_buf *uid, int n )\n{\n    int ret;\n\n    if( *p == end )\n        return( 0 );\n\n    uid->tag = **p;\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &uid->len,\n            MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | n ) ) != 0 )\n    {\n        if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )\n            return( 0 );\n\n        return( ret );\n    }\n\n    uid->p = *p;\n    *p += uid->len;\n\n    return( 0 );\n}\n\nstatic int x509_get_basic_constraints( unsigned char **p,\n                                       const unsigned char *end,\n                                       int *ca_istrue,\n                                       int *max_pathlen )\n{\n    int ret;\n    size_t len;\n\n    /*\n     * BasicConstraints ::= SEQUENCE {\n     *      cA                      BOOLEAN DEFAULT FALSE,\n     *      pathLenConstraint       INTEGER (0..MAX) OPTIONAL }\n     */\n    *ca_istrue = 0; /* DEFAULT FALSE */\n    *max_pathlen = 0; /* endless */\n\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n\n    if( *p == end )\n        return( 0 );\n\n    if( ( ret = mbedtls_asn1_get_bool( p, end, ca_istrue ) ) != 0 )\n    {\n        if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )\n            ret = mbedtls_asn1_get_int( p, end, ca_istrue );\n\n        if( ret != 0 )\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n\n        if( *ca_istrue != 0 )\n            *ca_istrue = 1;\n    }\n\n    if( *p == end )\n        return( 0 );\n\n    if( ( ret = mbedtls_asn1_get_int( p, end, max_pathlen ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n\n    if( *p != end )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    (*max_pathlen)++;\n\n    return( 0 );\n}\n\nstatic int x509_get_ns_cert_type( unsigned char **p,\n                                       const unsigned char *end,\n                                       unsigned char *ns_cert_type)\n{\n    int ret;\n    mbedtls_x509_bitstring bs = { 0, 0, NULL };\n\n    if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n\n    if( bs.len != 1 )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                MBEDTLS_ERR_ASN1_INVALID_LENGTH );\n\n    /* Get actual bitstring */\n    *ns_cert_type = *bs.p;\n    return( 0 );\n}\n\nstatic int x509_get_key_usage( unsigned char **p,\n                               const unsigned char *end,\n                               unsigned int *key_usage)\n{\n    int ret;\n    size_t i;\n    mbedtls_x509_bitstring bs = { 0, 0, NULL };\n\n    if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n\n    if( bs.len < 1 )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                MBEDTLS_ERR_ASN1_INVALID_LENGTH );\n\n    /* Get actual bitstring */\n    *key_usage = 0;\n    for( i = 0; i < bs.len && i < sizeof( unsigned int ); i++ )\n    {\n        *key_usage |= (unsigned int) bs.p[i] << (8*i);\n    }\n\n    return( 0 );\n}\n\n/*\n * ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId\n *\n * KeyPurposeId ::= OBJECT IDENTIFIER\n */\nstatic int x509_get_ext_key_usage( unsigned char **p,\n                               const unsigned char *end,\n                               mbedtls_x509_sequence *ext_key_usage)\n{\n    int ret;\n\n    if( ( ret = mbedtls_asn1_get_sequence_of( p, end, ext_key_usage, MBEDTLS_ASN1_OID ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n\n    /* Sequence length must be >= 1 */\n    if( ext_key_usage->buf.p == NULL )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                MBEDTLS_ERR_ASN1_INVALID_LENGTH );\n\n    return( 0 );\n}\n\n/*\n * SubjectAltName ::= GeneralNames\n *\n * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName\n *\n * GeneralName ::= CHOICE {\n *      otherName                       [0]     OtherName,\n *      rfc822Name                      [1]     IA5String,\n *      dNSName                         [2]     IA5String,\n *      x400Address                     [3]     ORAddress,\n *      directoryName                   [4]     Name,\n *      ediPartyName                    [5]     EDIPartyName,\n *      uniformResourceIdentifier       [6]     IA5String,\n *      iPAddress                       [7]     OCTET STRING,\n *      registeredID                    [8]     OBJECT IDENTIFIER }\n *\n * OtherName ::= SEQUENCE {\n *      type-id    OBJECT IDENTIFIER,\n *      value      [0] EXPLICIT ANY DEFINED BY type-id }\n *\n * EDIPartyName ::= SEQUENCE {\n *      nameAssigner            [0]     DirectoryString OPTIONAL,\n *      partyName               [1]     DirectoryString }\n *\n * NOTE: we only parse and use dNSName at this point.\n */\nstatic int x509_get_subject_alt_name( unsigned char **p,\n                                      const unsigned char *end,\n                                      mbedtls_x509_sequence *subject_alt_name )\n{\n    int ret;\n    size_t len, tag_len;\n    mbedtls_asn1_buf *buf;\n    unsigned char tag;\n    mbedtls_asn1_sequence *cur = subject_alt_name;\n\n    /* Get main sequence tag */\n    if( ( ret = mbedtls_asn1_get_tag( p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n\n    if( *p + len != end )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    while( *p < end )\n    {\n        if( ( end - *p ) < 1 )\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                    MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n        tag = **p;\n        (*p)++;\n        if( ( ret = mbedtls_asn1_get_len( p, end, &tag_len ) ) != 0 )\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n\n        if( ( tag & MBEDTLS_ASN1_TAG_CLASS_MASK ) !=\n                MBEDTLS_ASN1_CONTEXT_SPECIFIC )\n        {\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                    MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );\n        }\n\n        /* Skip everything but DNS name */\n        if( tag != ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2 ) )\n        {\n            *p += tag_len;\n            continue;\n        }\n\n        /* Allocate and assign next pointer */\n        if( cur->buf.p != NULL )\n        {\n            if( cur->next != NULL )\n                return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );\n\n            cur->next = mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) );\n\n            if( cur->next == NULL )\n                return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                        MBEDTLS_ERR_ASN1_ALLOC_FAILED );\n\n            cur = cur->next;\n        }\n\n        buf = &(cur->buf);\n        buf->tag = tag;\n        buf->p = *p;\n        buf->len = tag_len;\n        *p += buf->len;\n    }\n\n    /* Set final sequence entry's next pointer to NULL */\n    cur->next = NULL;\n\n    if( *p != end )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    return( 0 );\n}\n\n/*\n * X.509 v3 extensions\n *\n */\nstatic int x509_get_crt_ext( unsigned char **p,\n                             const unsigned char *end,\n                             mbedtls_x509_crt *crt )\n{\n    int ret;\n    size_t len;\n    unsigned char *end_ext_data, *end_ext_octet;\n\n    if( ( ret = mbedtls_x509_get_ext( p, end, &crt->v3_ext, 3 ) ) != 0 )\n    {\n        if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )\n            return( 0 );\n\n        return( ret );\n    }\n\n    while( *p < end )\n    {\n        /*\n         * Extension  ::=  SEQUENCE  {\n         *      extnID      OBJECT IDENTIFIER,\n         *      critical    BOOLEAN DEFAULT FALSE,\n         *      extnValue   OCTET STRING  }\n         */\n        mbedtls_x509_buf extn_oid = {0, 0, NULL};\n        int is_critical = 0; /* DEFAULT FALSE */\n        int ext_type = 0;\n\n        if( ( ret = mbedtls_asn1_get_tag( p, end, &len,\n                MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n\n        end_ext_data = *p + len;\n\n        /* Get extension ID */\n        extn_oid.tag = **p;\n\n        if( ( ret = mbedtls_asn1_get_tag( p, end, &extn_oid.len, MBEDTLS_ASN1_OID ) ) != 0 )\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n\n        extn_oid.p = *p;\n        *p += extn_oid.len;\n\n        if( ( end - *p ) < 1 )\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                    MBEDTLS_ERR_ASN1_OUT_OF_DATA );\n\n        /* Get optional critical */\n        if( ( ret = mbedtls_asn1_get_bool( p, end_ext_data, &is_critical ) ) != 0 &&\n            ( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) )\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n\n        /* Data should be octet string type */\n        if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len,\n                MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );\n\n        end_ext_octet = *p + len;\n\n        if( end_ext_octet != end_ext_data )\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                    MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n        /*\n         * Detect supported extensions\n         */\n        ret = mbedtls_oid_get_x509_ext_type( &extn_oid, &ext_type );\n\n        if( ret != 0 )\n        {\n            /* No parser found, skip extension */\n            *p = end_ext_octet;\n\n#if !defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION)\n            if( is_critical )\n            {\n                /* Data is marked as critical: fail */\n                return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                        MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );\n            }\n#endif\n            continue;\n        }\n\n        /* Forbid repeated extensions */\n        if( ( crt->ext_types & ext_type ) != 0 )\n            return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );\n\n        crt->ext_types |= ext_type;\n\n        switch( ext_type )\n        {\n        case MBEDTLS_X509_EXT_BASIC_CONSTRAINTS:\n            /* Parse basic constraints */\n            if( ( ret = x509_get_basic_constraints( p, end_ext_octet,\n                    &crt->ca_istrue, &crt->max_pathlen ) ) != 0 )\n                return( ret );\n            break;\n\n        case MBEDTLS_X509_EXT_KEY_USAGE:\n            /* Parse key usage */\n            if( ( ret = x509_get_key_usage( p, end_ext_octet,\n                    &crt->key_usage ) ) != 0 )\n                return( ret );\n            break;\n\n        case MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE:\n            /* Parse extended key usage */\n            if( ( ret = x509_get_ext_key_usage( p, end_ext_octet,\n                    &crt->ext_key_usage ) ) != 0 )\n                return( ret );\n            break;\n\n        case MBEDTLS_X509_EXT_SUBJECT_ALT_NAME:\n            /* Parse subject alt name */\n            if( ( ret = x509_get_subject_alt_name( p, end_ext_octet,\n                    &crt->subject_alt_names ) ) != 0 )\n                return( ret );\n            break;\n\n        case MBEDTLS_X509_EXT_NS_CERT_TYPE:\n            /* Parse netscape certificate type */\n            if( ( ret = x509_get_ns_cert_type( p, end_ext_octet,\n                    &crt->ns_cert_type ) ) != 0 )\n                return( ret );\n            break;\n\n        default:\n            return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE );\n        }\n    }\n\n    if( *p != end )\n        return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n\n    return( 0 );\n}\n\n/*\n * Parse and fill a single X.509 certificate in DER format\n */\nstatic int x509_crt_parse_der_core( mbedtls_x509_crt *crt, const unsigned char *buf,\n                                    size_t buflen )\n{\n    int ret;\n    size_t len;\n    unsigned char *p, *end, *crt_end;\n    mbedtls_x509_buf sig_params1, sig_params2, sig_oid2;\n\n    memset( &sig_params1, 0, sizeof( mbedtls_x509_buf ) );\n    memset( &sig_params2, 0, sizeof( mbedtls_x509_buf ) );\n    memset( &sig_oid2, 0, sizeof( mbedtls_x509_buf ) );\n\n    /*\n     * Check for valid input\n     */\n    if( crt == NULL || buf == NULL )\n        return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n\n    // Use the original buffer until we figure out actual length\n    p = (unsigned char*) buf;\n    len = buflen;\n    end = p + len;\n\n    /*\n     * Certificate  ::=  SEQUENCE  {\n     *      tbsCertificate       TBSCertificate,\n     *      signatureAlgorithm   AlgorithmIdentifier,\n     *      signatureValue       BIT STRING  }\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT );\n    }\n\n    if( len > (size_t) ( end - p ) )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n    }\n    crt_end = p + len;\n\n    // Create and populate a new buffer for the raw field\n    crt->raw.len = crt_end - buf;\n    crt->raw.p = p = mbedtls_calloc( 1, crt->raw.len );\n    if( p == NULL )\n        return( MBEDTLS_ERR_X509_ALLOC_FAILED );\n\n    memcpy( p, buf, crt->raw.len );\n\n    // Direct pointers to the new buffer\n    p += crt->raw.len - len;\n    end = crt_end = p + len;\n\n    /*\n     * TBSCertificate  ::=  SEQUENCE  {\n     */\n    crt->tbs.p = p;\n\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );\n    }\n\n    end = p + len;\n    crt->tbs.len = end - crt->tbs.p;\n\n    /*\n     * Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }\n     *\n     * CertificateSerialNumber  ::=  INTEGER\n     *\n     * signature            AlgorithmIdentifier\n     */\n    if( ( ret = x509_get_version(  &p, end, &crt->version  ) ) != 0 ||\n        ( ret = mbedtls_x509_get_serial(   &p, end, &crt->serial   ) ) != 0 ||\n        ( ret = mbedtls_x509_get_alg(      &p, end, &crt->sig_oid,\n                                            &sig_params1 ) ) != 0 )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( ret );\n    }\n\n    if( crt->version < 0 || crt->version > 2 )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( MBEDTLS_ERR_X509_UNKNOWN_VERSION );\n    }\n\n    crt->version++;\n\n    if( ( ret = mbedtls_x509_get_sig_alg( &crt->sig_oid, &sig_params1,\n                                  &crt->sig_md, &crt->sig_pk,\n                                  &crt->sig_opts ) ) != 0 )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( ret );\n    }\n\n    /*\n     * issuer               Name\n     */\n    crt->issuer_raw.p = p;\n\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );\n    }\n\n    if( ( ret = mbedtls_x509_get_name( &p, p + len, &crt->issuer ) ) != 0 )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( ret );\n    }\n\n    crt->issuer_raw.len = p - crt->issuer_raw.p;\n\n    /*\n     * Validity ::= SEQUENCE {\n     *      notBefore      Time,\n     *      notAfter       Time }\n     *\n     */\n    if( ( ret = x509_get_dates( &p, end, &crt->valid_from,\n                                         &crt->valid_to ) ) != 0 )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( ret );\n    }\n\n    /*\n     * subject              Name\n     */\n    crt->subject_raw.p = p;\n\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );\n    }\n\n    if( len && ( ret = mbedtls_x509_get_name( &p, p + len, &crt->subject ) ) != 0 )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( ret );\n    }\n\n    crt->subject_raw.len = p - crt->subject_raw.p;\n\n    /*\n     * SubjectPublicKeyInfo\n     */\n    if( ( ret = mbedtls_pk_parse_subpubkey( &p, end, &crt->pk ) ) != 0 )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( ret );\n    }\n\n    /*\n     *  issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL,\n     *                       -- If present, version shall be v2 or v3\n     *  subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL,\n     *                       -- If present, version shall be v2 or v3\n     *  extensions      [3]  EXPLICIT Extensions OPTIONAL\n     *                       -- If present, version shall be v3\n     */\n    if( crt->version == 2 || crt->version == 3 )\n    {\n        ret = x509_get_uid( &p, end, &crt->issuer_id,  1 );\n        if( ret != 0 )\n        {\n            mbedtls_x509_crt_free( crt );\n            return( ret );\n        }\n    }\n\n    if( crt->version == 2 || crt->version == 3 )\n    {\n        ret = x509_get_uid( &p, end, &crt->subject_id,  2 );\n        if( ret != 0 )\n        {\n            mbedtls_x509_crt_free( crt );\n            return( ret );\n        }\n    }\n\n#if !defined(MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3)\n    if( crt->version == 3 )\n#endif\n    {\n        ret = x509_get_crt_ext( &p, end, crt );\n        if( ret != 0 )\n        {\n            mbedtls_x509_crt_free( crt );\n            return( ret );\n        }\n    }\n\n    if( p != end )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n    }\n\n    end = crt_end;\n\n    /*\n     *  }\n     *  -- end of TBSCertificate\n     *\n     *  signatureAlgorithm   AlgorithmIdentifier,\n     *  signatureValue       BIT STRING\n     */\n    if( ( ret = mbedtls_x509_get_alg( &p, end, &sig_oid2, &sig_params2 ) ) != 0 )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( ret );\n    }\n\n    if( crt->sig_oid.len != sig_oid2.len ||\n        memcmp( crt->sig_oid.p, sig_oid2.p, crt->sig_oid.len ) != 0 ||\n        sig_params1.len != sig_params2.len ||\n        ( sig_params1.len != 0 &&\n          memcmp( sig_params1.p, sig_params2.p, sig_params1.len ) != 0 ) )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( MBEDTLS_ERR_X509_SIG_MISMATCH );\n    }\n\n    if( ( ret = mbedtls_x509_get_sig( &p, end, &crt->sig ) ) != 0 )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( ret );\n    }\n\n    if( p != end )\n    {\n        mbedtls_x509_crt_free( crt );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n    }\n\n    return( 0 );\n}\n\n/*\n * Parse one X.509 certificate in DER format from a buffer and add them to a\n * chained list\n */\nint mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf,\n                        size_t buflen )\n{\n    int ret;\n    mbedtls_x509_crt *crt = chain, *prev = NULL;\n\n    /*\n     * Check for valid input\n     */\n    if( crt == NULL || buf == NULL )\n        return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n\n    while( crt->version != 0 && crt->next != NULL )\n    {\n        prev = crt;\n        crt = crt->next;\n    }\n\n    /*\n     * Add new certificate on the end of the chain if needed.\n     */\n    if( crt->version != 0 && crt->next == NULL )\n    {\n        crt->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );\n\n        if( crt->next == NULL )\n            return( MBEDTLS_ERR_X509_ALLOC_FAILED );\n\n        prev = crt;\n        mbedtls_x509_crt_init( crt->next );\n        crt = crt->next;\n    }\n\n    if( ( ret = x509_crt_parse_der_core( crt, buf, buflen ) ) != 0 )\n    {\n        if( prev )\n            prev->next = NULL;\n\n        if( crt != chain )\n            mbedtls_free( crt );\n\n        return( ret );\n    }\n\n    return( 0 );\n}\n\n/*\n * Parse one or more PEM certificates from a buffer and add them to the chained\n * list\n */\nint mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen )\n{\n#if defined(MBEDTLS_PEM_PARSE_C)\n    int success = 0, first_error = 0, total_failed = 0;\n    int buf_format = MBEDTLS_X509_FORMAT_DER;\n#endif\n\n    /*\n     * Check for valid input\n     */\n    if( chain == NULL || buf == NULL )\n        return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n\n    /*\n     * Determine buffer content. Buffer contains either one DER certificate or\n     * one or more PEM certificates.\n     */\n#if defined(MBEDTLS_PEM_PARSE_C)\n    if( buflen != 0 && buf[buflen - 1] == '\\0' &&\n        strstr( (const char *) buf, \"-----BEGIN CERTIFICATE-----\" ) != NULL )\n    {\n        buf_format = MBEDTLS_X509_FORMAT_PEM;\n    }\n\n    if( buf_format == MBEDTLS_X509_FORMAT_DER )\n        return mbedtls_x509_crt_parse_der( chain, buf, buflen );\n#else\n    return mbedtls_x509_crt_parse_der( chain, buf, buflen );\n#endif\n\n#if defined(MBEDTLS_PEM_PARSE_C)\n    if( buf_format == MBEDTLS_X509_FORMAT_PEM )\n    {\n        int ret;\n        mbedtls_pem_context pem;\n\n        /* 1 rather than 0 since the terminating NULL byte is counted in */\n        while( buflen > 1 )\n        {\n            size_t use_len;\n            mbedtls_pem_init( &pem );\n\n            /* If we get there, we know the string is null-terminated */\n            ret = mbedtls_pem_read_buffer( &pem,\n                           \"-----BEGIN CERTIFICATE-----\",\n                           \"-----END CERTIFICATE-----\",\n                           buf, NULL, 0, &use_len );\n\n            if( ret == 0 )\n            {\n                /*\n                 * Was PEM encoded\n                 */\n                buflen -= use_len;\n                buf += use_len;\n            }\n            else if( ret == MBEDTLS_ERR_PEM_BAD_INPUT_DATA )\n            {\n                return( ret );\n            }\n            else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )\n            {\n                mbedtls_pem_free( &pem );\n\n                /*\n                 * PEM header and footer were found\n                 */\n                buflen -= use_len;\n                buf += use_len;\n\n                if( first_error == 0 )\n                    first_error = ret;\n\n                total_failed++;\n                continue;\n            }\n            else\n                break;\n\n            ret = mbedtls_x509_crt_parse_der( chain, pem.buf, pem.buflen );\n\n            mbedtls_pem_free( &pem );\n\n            if( ret != 0 )\n            {\n                /*\n                 * Quit parsing on a memory error\n                 */\n                if( ret == MBEDTLS_ERR_X509_ALLOC_FAILED )\n                    return( ret );\n\n                if( first_error == 0 )\n                    first_error = ret;\n\n                total_failed++;\n                continue;\n            }\n\n            success = 1;\n        }\n    }\n\n    if( success )\n        return( total_failed );\n    else if( first_error )\n        return( first_error );\n    else\n        return( MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT );\n#endif /* MBEDTLS_PEM_PARSE_C */\n}\n\n#if defined(MBEDTLS_FS_IO)\n/*\n * Load one or more certificates and add them to the chained list\n */\nint mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path )\n{\n    int ret;\n    size_t n;\n    unsigned char *buf;\n\n    if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )\n        return( ret );\n\n    ret = mbedtls_x509_crt_parse( chain, buf, n );\n\n    mbedtls_platform_zeroize( buf, n );\n    mbedtls_free( buf );\n\n    return( ret );\n}\n\nint mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path )\n{\n    int ret = 0;\n#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)\n    int w_ret;\n    WCHAR szDir[MAX_PATH];\n    char filename[MAX_PATH];\n    char *p;\n    size_t len = strlen( path );\n    int length_as_int = 0;\n\n    WIN32_FIND_DATAW file_data;\n    HANDLE hFind;\n\n    if( len > MAX_PATH - 3 )\n        return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n\n    memset( szDir, 0, sizeof(szDir) );\n    memset( filename, 0, MAX_PATH );\n    memcpy( filename, path, len );\n    filename[len++] = '\\\\';\n    p = filename + len;\n    filename[len++] = '*';\n\n    if ( FAILED ( SizeTToInt( len, &length_as_int ) ) )\n        return( MBEDTLS_ERR_X509_FILE_IO_ERROR );\n\n    /*\n     * Note this function uses the code page CP_ACP, and assumes the incoming\n     * string is encoded in ANSI, before translating it into Unicode. If the\n     * incoming string were changed to be UTF-8, then the length check needs to\n     * change to check the number of characters, not the number of bytes, in the\n     * incoming string are less than MAX_PATH to avoid a buffer overrun with\n     * MultiByteToWideChar().\n     */\n    w_ret = MultiByteToWideChar( CP_ACP, 0, filename, length_as_int, szDir,\n                                 MAX_PATH - 3 );\n    if( w_ret == 0 )\n        return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n\n    hFind = FindFirstFileW( szDir, &file_data );\n    if( hFind == INVALID_HANDLE_VALUE )\n        return( MBEDTLS_ERR_X509_FILE_IO_ERROR );\n\n    len = MAX_PATH - len;\n    do\n    {\n        memset( p, 0, len );\n\n        if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )\n            continue;\n\n        if ( FAILED( SizeTToInt( wcslen( file_data.cFileName ), &length_as_int ) ) )\n            return( MBEDTLS_ERR_X509_FILE_IO_ERROR );\n\n        w_ret = WideCharToMultiByte( CP_ACP, 0, file_data.cFileName,\n                                     length_as_int,\n                                     p, (int) len - 1,\n                                     NULL, NULL );\n        if( w_ret == 0 )\n        {\n            ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;\n            goto cleanup;\n        }\n\n        w_ret = mbedtls_x509_crt_parse_file( chain, filename );\n        if( w_ret < 0 )\n            ret++;\n        else\n            ret += w_ret;\n    }\n    while( FindNextFileW( hFind, &file_data ) != 0 );\n\n    if( GetLastError() != ERROR_NO_MORE_FILES )\n        ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;\n\ncleanup:\n    FindClose( hFind );\n#else /* _WIN32 */\n    int t_ret;\n    int snp_ret;\n    struct stat sb;\n    struct dirent *entry;\n    char entry_name[MBEDTLS_X509_MAX_FILE_PATH_LEN];\n    DIR *dir = opendir( path );\n\n    if( dir == NULL )\n        return( MBEDTLS_ERR_X509_FILE_IO_ERROR );\n\n#if defined(MBEDTLS_THREADING_C)\n    if( ( ret = mbedtls_mutex_lock( &mbedtls_threading_readdir_mutex ) ) != 0 )\n    {\n        closedir( dir );\n        return( ret );\n    }\n#endif /* MBEDTLS_THREADING_C */\n\n    while( ( entry = readdir( dir ) ) != NULL )\n    {\n        snp_ret = mbedtls_snprintf( entry_name, sizeof entry_name,\n                                    \"%s/%s\", path, entry->d_name );\n\n        if( snp_ret < 0 || (size_t)snp_ret >= sizeof entry_name )\n        {\n            ret = MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;\n            goto cleanup;\n        }\n        else if( stat( entry_name, &sb ) == -1 )\n        {\n            ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;\n            goto cleanup;\n        }\n\n        if( !S_ISREG( sb.st_mode ) )\n            continue;\n\n        // Ignore parse errors\n        //\n        t_ret = mbedtls_x509_crt_parse_file( chain, entry_name );\n        if( t_ret < 0 )\n            ret++;\n        else\n            ret += t_ret;\n    }\n\ncleanup:\n    closedir( dir );\n\n#if defined(MBEDTLS_THREADING_C)\n    if( mbedtls_mutex_unlock( &mbedtls_threading_readdir_mutex ) != 0 )\n        ret = MBEDTLS_ERR_THREADING_MUTEX_ERROR;\n#endif /* MBEDTLS_THREADING_C */\n\n#endif /* _WIN32 */\n\n    return( ret );\n}\n#endif /* MBEDTLS_FS_IO */\n\nstatic int x509_info_subject_alt_name( char **buf, size_t *size,\n                                       const mbedtls_x509_sequence *subject_alt_name )\n{\n    size_t i;\n    size_t n = *size;\n    char *p = *buf;\n    const mbedtls_x509_sequence *cur = subject_alt_name;\n    const char *sep = \"\";\n    size_t sep_len = 0;\n\n    while( cur != NULL )\n    {\n        if( cur->buf.len + sep_len >= n )\n        {\n            *p = '\\0';\n            return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL );\n        }\n\n        n -= cur->buf.len + sep_len;\n        for( i = 0; i < sep_len; i++ )\n            *p++ = sep[i];\n        for( i = 0; i < cur->buf.len; i++ )\n            *p++ = cur->buf.p[i];\n\n        sep = \", \";\n        sep_len = 2;\n\n        cur = cur->next;\n    }\n\n    *p = '\\0';\n\n    *size = n;\n    *buf = p;\n\n    return( 0 );\n}\n\n#define PRINT_ITEM(i)                           \\\n    {                                           \\\n        ret = mbedtls_snprintf( p, n, \"%s\" i, sep );    \\\n        MBEDTLS_X509_SAFE_SNPRINTF;                        \\\n        sep = \", \";                             \\\n    }\n\n#define CERT_TYPE(type,name)                    \\\n    if( ns_cert_type & type )                   \\\n        PRINT_ITEM( name );\n\nstatic int x509_info_cert_type( char **buf, size_t *size,\n                                unsigned char ns_cert_type )\n{\n    int ret;\n    size_t n = *size;\n    char *p = *buf;\n    const char *sep = \"\";\n\n    CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT,         \"SSL Client\" );\n    CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER,         \"SSL Server\" );\n    CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL,              \"Email\" );\n    CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING,     \"Object Signing\" );\n    CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_RESERVED,           \"Reserved\" );\n    CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CA,             \"SSL CA\" );\n    CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA,           \"Email CA\" );\n    CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA,  \"Object Signing CA\" );\n\n    *size = n;\n    *buf = p;\n\n    return( 0 );\n}\n\n#define KEY_USAGE(code,name)    \\\n    if( key_usage & code )      \\\n        PRINT_ITEM( name );\n\nstatic int x509_info_key_usage( char **buf, size_t *size,\n                                unsigned int key_usage )\n{\n    int ret;\n    size_t n = *size;\n    char *p = *buf;\n    const char *sep = \"\";\n\n    KEY_USAGE( MBEDTLS_X509_KU_DIGITAL_SIGNATURE,    \"Digital Signature\" );\n    KEY_USAGE( MBEDTLS_X509_KU_NON_REPUDIATION,      \"Non Repudiation\" );\n    KEY_USAGE( MBEDTLS_X509_KU_KEY_ENCIPHERMENT,     \"Key Encipherment\" );\n    KEY_USAGE( MBEDTLS_X509_KU_DATA_ENCIPHERMENT,    \"Data Encipherment\" );\n    KEY_USAGE( MBEDTLS_X509_KU_KEY_AGREEMENT,        \"Key Agreement\" );\n    KEY_USAGE( MBEDTLS_X509_KU_KEY_CERT_SIGN,        \"Key Cert Sign\" );\n    KEY_USAGE( MBEDTLS_X509_KU_CRL_SIGN,             \"CRL Sign\" );\n    KEY_USAGE( MBEDTLS_X509_KU_ENCIPHER_ONLY,        \"Encipher Only\" );\n    KEY_USAGE( MBEDTLS_X509_KU_DECIPHER_ONLY,        \"Decipher Only\" );\n\n    *size = n;\n    *buf = p;\n\n    return( 0 );\n}\n\nstatic int x509_info_ext_key_usage( char **buf, size_t *size,\n                                    const mbedtls_x509_sequence *extended_key_usage )\n{\n    int ret;\n    const char *desc;\n    size_t n = *size;\n    char *p = *buf;\n    const mbedtls_x509_sequence *cur = extended_key_usage;\n    const char *sep = \"\";\n\n    while( cur != NULL )\n    {\n        if( mbedtls_oid_get_extended_key_usage( &cur->buf, &desc ) != 0 )\n            desc = \"???\";\n\n        ret = mbedtls_snprintf( p, n, \"%s%s\", sep, desc );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n\n        sep = \", \";\n\n        cur = cur->next;\n    }\n\n    *size = n;\n    *buf = p;\n\n    return( 0 );\n}\n\n/*\n * Return an informational string about the certificate.\n */\n#define BEFORE_COLON    18\n#define BC              \"18\"\nint mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix,\n                   const mbedtls_x509_crt *crt )\n{\n    int ret;\n    size_t n;\n    char *p;\n    char key_size_str[BEFORE_COLON];\n\n    p = buf;\n    n = size;\n\n    if( NULL == crt )\n    {\n        ret = mbedtls_snprintf( p, n, \"\\nCertificate is uninitialised!\\n\" );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n\n        return( (int) ( size - n ) );\n    }\n\n    ret = mbedtls_snprintf( p, n, \"%scert. version     : %d\\n\",\n                               prefix, crt->version );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n    ret = mbedtls_snprintf( p, n, \"%sserial number     : \",\n                               prefix );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    ret = mbedtls_x509_serial_gets( p, n, &crt->serial );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    ret = mbedtls_snprintf( p, n, \"\\n%sissuer name       : \", prefix );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n    ret = mbedtls_x509_dn_gets( p, n, &crt->issuer  );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    ret = mbedtls_snprintf( p, n, \"\\n%ssubject name      : \", prefix );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n    ret = mbedtls_x509_dn_gets( p, n, &crt->subject );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    ret = mbedtls_snprintf( p, n, \"\\n%sissued  on        : \" \\\n                   \"%04d-%02d-%02d %02d:%02d:%02d\", prefix,\n                   crt->valid_from.year, crt->valid_from.mon,\n                   crt->valid_from.day,  crt->valid_from.hour,\n                   crt->valid_from.min,  crt->valid_from.sec );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    ret = mbedtls_snprintf( p, n, \"\\n%sexpires on        : \" \\\n                   \"%04d-%02d-%02d %02d:%02d:%02d\", prefix,\n                   crt->valid_to.year, crt->valid_to.mon,\n                   crt->valid_to.day,  crt->valid_to.hour,\n                   crt->valid_to.min,  crt->valid_to.sec );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    ret = mbedtls_snprintf( p, n, \"\\n%ssigned using      : \", prefix );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    ret = mbedtls_x509_sig_alg_gets( p, n, &crt->sig_oid, crt->sig_pk,\n                             crt->sig_md, crt->sig_opts );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    /* Key size */\n    if( ( ret = mbedtls_x509_key_size_helper( key_size_str, BEFORE_COLON,\n                                      mbedtls_pk_get_name( &crt->pk ) ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    ret = mbedtls_snprintf( p, n, \"\\n%s%-\" BC \"s: %d bits\", prefix, key_size_str,\n                          (int) mbedtls_pk_get_bitlen( &crt->pk ) );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    /*\n     * Optional extensions\n     */\n\n    if( crt->ext_types & MBEDTLS_X509_EXT_BASIC_CONSTRAINTS )\n    {\n        ret = mbedtls_snprintf( p, n, \"\\n%sbasic constraints : CA=%s\", prefix,\n                        crt->ca_istrue ? \"true\" : \"false\" );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n\n        if( crt->max_pathlen > 0 )\n        {\n            ret = mbedtls_snprintf( p, n, \", max_pathlen=%d\", crt->max_pathlen - 1 );\n            MBEDTLS_X509_SAFE_SNPRINTF;\n        }\n    }\n\n    if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )\n    {\n        ret = mbedtls_snprintf( p, n, \"\\n%ssubject alt name  : \", prefix );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n\n        if( ( ret = x509_info_subject_alt_name( &p, &n,\n                                            &crt->subject_alt_names ) ) != 0 )\n            return( ret );\n    }\n\n    if( crt->ext_types & MBEDTLS_X509_EXT_NS_CERT_TYPE )\n    {\n        ret = mbedtls_snprintf( p, n, \"\\n%scert. type        : \", prefix );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n\n        if( ( ret = x509_info_cert_type( &p, &n, crt->ns_cert_type ) ) != 0 )\n            return( ret );\n    }\n\n    if( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE )\n    {\n        ret = mbedtls_snprintf( p, n, \"\\n%skey usage         : \", prefix );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n\n        if( ( ret = x509_info_key_usage( &p, &n, crt->key_usage ) ) != 0 )\n            return( ret );\n    }\n\n    if( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE )\n    {\n        ret = mbedtls_snprintf( p, n, \"\\n%sext key usage     : \", prefix );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n\n        if( ( ret = x509_info_ext_key_usage( &p, &n,\n                                             &crt->ext_key_usage ) ) != 0 )\n            return( ret );\n    }\n\n    ret = mbedtls_snprintf( p, n, \"\\n\" );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    return( (int) ( size - n ) );\n}\n\nstruct x509_crt_verify_string {\n    int code;\n    const char *string;\n};\n\nstatic const struct x509_crt_verify_string x509_crt_verify_strings[] = {\n    { MBEDTLS_X509_BADCERT_EXPIRED,       \"The certificate validity has expired\" },\n    { MBEDTLS_X509_BADCERT_REVOKED,       \"The certificate has been revoked (is on a CRL)\" },\n    { MBEDTLS_X509_BADCERT_CN_MISMATCH,   \"The certificate Common Name (CN) does not match with the expected CN\" },\n    { MBEDTLS_X509_BADCERT_NOT_TRUSTED,   \"The certificate is not correctly signed by the trusted CA\" },\n    { MBEDTLS_X509_BADCRL_NOT_TRUSTED,    \"The CRL is not correctly signed by the trusted CA\" },\n    { MBEDTLS_X509_BADCRL_EXPIRED,        \"The CRL is expired\" },\n    { MBEDTLS_X509_BADCERT_MISSING,       \"Certificate was missing\" },\n    { MBEDTLS_X509_BADCERT_SKIP_VERIFY,   \"Certificate verification was skipped\" },\n    { MBEDTLS_X509_BADCERT_OTHER,         \"Other reason (can be used by verify callback)\" },\n    { MBEDTLS_X509_BADCERT_FUTURE,        \"The certificate validity starts in the future\" },\n    { MBEDTLS_X509_BADCRL_FUTURE,         \"The CRL is from the future\" },\n    { MBEDTLS_X509_BADCERT_KEY_USAGE,     \"Usage does not match the keyUsage extension\" },\n    { MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, \"Usage does not match the extendedKeyUsage extension\" },\n    { MBEDTLS_X509_BADCERT_NS_CERT_TYPE,  \"Usage does not match the nsCertType extension\" },\n    { MBEDTLS_X509_BADCERT_BAD_MD,        \"The certificate is signed with an unacceptable hash.\" },\n    { MBEDTLS_X509_BADCERT_BAD_PK,        \"The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA).\" },\n    { MBEDTLS_X509_BADCERT_BAD_KEY,       \"The certificate is signed with an unacceptable key (eg bad curve, RSA too short).\" },\n    { MBEDTLS_X509_BADCRL_BAD_MD,         \"The CRL is signed with an unacceptable hash.\" },\n    { MBEDTLS_X509_BADCRL_BAD_PK,         \"The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA).\" },\n    { MBEDTLS_X509_BADCRL_BAD_KEY,        \"The CRL is signed with an unacceptable key (eg bad curve, RSA too short).\" },\n    { 0, NULL }\n};\n\nint mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,\n                          uint32_t flags )\n{\n    int ret;\n    const struct x509_crt_verify_string *cur;\n    char *p = buf;\n    size_t n = size;\n\n    for( cur = x509_crt_verify_strings; cur->string != NULL ; cur++ )\n    {\n        if( ( flags & cur->code ) == 0 )\n            continue;\n\n        ret = mbedtls_snprintf( p, n, \"%s%s\\n\", prefix, cur->string );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n        flags ^= cur->code;\n    }\n\n    if( flags != 0 )\n    {\n        ret = mbedtls_snprintf( p, n, \"%sUnknown reason \"\n                                       \"(this should not happen)\\n\", prefix );\n        MBEDTLS_X509_SAFE_SNPRINTF;\n    }\n\n    return( (int) ( size - n ) );\n}\n\n#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)\nint mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,\n                                      unsigned int usage )\n{\n    unsigned int usage_must, usage_may;\n    unsigned int may_mask = MBEDTLS_X509_KU_ENCIPHER_ONLY\n                          | MBEDTLS_X509_KU_DECIPHER_ONLY;\n\n    if( ( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE ) == 0 )\n        return( 0 );\n\n    usage_must = usage & ~may_mask;\n\n    if( ( ( crt->key_usage & ~may_mask ) & usage_must ) != usage_must )\n        return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n\n    usage_may = usage & may_mask;\n\n    if( ( ( crt->key_usage & may_mask ) | usage_may ) != usage_may )\n        return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n\n    return( 0 );\n}\n#endif\n\n#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)\nint mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,\n                                       const char *usage_oid,\n                                       size_t usage_len )\n{\n    const mbedtls_x509_sequence *cur;\n\n    /* Extension is not mandatory, absent means no restriction */\n    if( ( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE ) == 0 )\n        return( 0 );\n\n    /*\n     * Look for the requested usage (or wildcard ANY) in our list\n     */\n    for( cur = &crt->ext_key_usage; cur != NULL; cur = cur->next )\n    {\n        const mbedtls_x509_buf *cur_oid = &cur->buf;\n\n        if( cur_oid->len == usage_len &&\n            memcmp( cur_oid->p, usage_oid, usage_len ) == 0 )\n        {\n            return( 0 );\n        }\n\n        if( MBEDTLS_OID_CMP( MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE, cur_oid ) == 0 )\n            return( 0 );\n    }\n\n    return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n}\n#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */\n\n#if defined(MBEDTLS_X509_CRL_PARSE_C)\n/*\n * Return 1 if the certificate is revoked, or 0 otherwise.\n */\nint mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl )\n{\n    const mbedtls_x509_crl_entry *cur = &crl->entry;\n\n    while( cur != NULL && cur->serial.len != 0 )\n    {\n        if( crt->serial.len == cur->serial.len &&\n            memcmp( crt->serial.p, cur->serial.p, crt->serial.len ) == 0 )\n        {\n            if( mbedtls_x509_time_is_past( &cur->revocation_date ) )\n                return( 1 );\n        }\n\n        cur = cur->next;\n    }\n\n    return( 0 );\n}\n\n/*\n * Check that the given certificate is not revoked according to the CRL.\n * Skip validation if no CRL for the given CA is present.\n */\nstatic int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca,\n                               mbedtls_x509_crl *crl_list,\n                               const mbedtls_x509_crt_profile *profile )\n{\n    int flags = 0;\n    unsigned char hash[MBEDTLS_MD_MAX_SIZE];\n    const mbedtls_md_info_t *md_info;\n\n    if( ca == NULL )\n        return( flags );\n\n    while( crl_list != NULL )\n    {\n        if( crl_list->version == 0 ||\n            crl_list->issuer_raw.len != ca->subject_raw.len ||\n            memcmp( crl_list->issuer_raw.p, ca->subject_raw.p,\n                    crl_list->issuer_raw.len ) != 0 )\n        {\n            crl_list = crl_list->next;\n            continue;\n        }\n\n        /*\n         * Check if the CA is configured to sign CRLs\n         */\n#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)\n        if( mbedtls_x509_crt_check_key_usage( ca, MBEDTLS_X509_KU_CRL_SIGN ) != 0 )\n        {\n            flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;\n            break;\n        }\n#endif\n\n        /*\n         * Check if CRL is correctly signed by the trusted CA\n         */\n        if( x509_profile_check_md_alg( profile, crl_list->sig_md ) != 0 )\n            flags |= MBEDTLS_X509_BADCRL_BAD_MD;\n\n        if( x509_profile_check_pk_alg( profile, crl_list->sig_pk ) != 0 )\n            flags |= MBEDTLS_X509_BADCRL_BAD_PK;\n\n        md_info = mbedtls_md_info_from_type( crl_list->sig_md );\n        if( mbedtls_md( md_info, crl_list->tbs.p, crl_list->tbs.len, hash ) != 0 )\n        {\n            /* Note: this can't happen except after an internal error */\n            flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;\n            break;\n        }\n\n        if( x509_profile_check_key( profile, &ca->pk ) != 0 )\n            flags |= MBEDTLS_X509_BADCERT_BAD_KEY;\n\n        if( mbedtls_pk_verify_ext( crl_list->sig_pk, crl_list->sig_opts, &ca->pk,\n                           crl_list->sig_md, hash, mbedtls_md_get_size( md_info ),\n                           crl_list->sig.p, crl_list->sig.len ) != 0 )\n        {\n            flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;\n            break;\n        }\n\n        /*\n         * Check for validity of CRL (Do not drop out)\n         */\n        if( mbedtls_x509_time_is_past( &crl_list->next_update ) )\n            flags |= MBEDTLS_X509_BADCRL_EXPIRED;\n\n        if( mbedtls_x509_time_is_future( &crl_list->this_update ) )\n            flags |= MBEDTLS_X509_BADCRL_FUTURE;\n\n        /*\n         * Check if certificate is revoked\n         */\n        if( mbedtls_x509_crt_is_revoked( crt, crl_list ) )\n        {\n            flags |= MBEDTLS_X509_BADCERT_REVOKED;\n            break;\n        }\n\n        crl_list = crl_list->next;\n    }\n\n    return( flags );\n}\n#endif /* MBEDTLS_X509_CRL_PARSE_C */\n\n/*\n * Like memcmp, but case-insensitive and always returns -1 if different\n */\nstatic int x509_memcasecmp( const void *s1, const void *s2, size_t len )\n{\n    size_t i;\n    unsigned char diff;\n    const unsigned char *n1 = s1, *n2 = s2;\n\n    for( i = 0; i < len; i++ )\n    {\n        diff = n1[i] ^ n2[i];\n\n        if( diff == 0 )\n            continue;\n\n        if( diff == 32 &&\n            ( ( n1[i] >= 'a' && n1[i] <= 'z' ) ||\n              ( n1[i] >= 'A' && n1[i] <= 'Z' ) ) )\n        {\n            continue;\n        }\n\n        return( -1 );\n    }\n\n    return( 0 );\n}\n\n/*\n * Return 0 if name matches wildcard, -1 otherwise\n */\nstatic int x509_check_wildcard( const char *cn, const mbedtls_x509_buf *name )\n{\n    size_t i;\n    size_t cn_idx = 0, cn_len = strlen( cn );\n\n    /* We can't have a match if there is no wildcard to match */\n    if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' )\n        return( -1 );\n\n    for( i = 0; i < cn_len; ++i )\n    {\n        if( cn[i] == '.' )\n        {\n            cn_idx = i;\n            break;\n        }\n    }\n\n    if( cn_idx == 0 )\n        return( -1 );\n\n    if( cn_len - cn_idx == name->len - 1 &&\n        x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )\n    {\n        return( 0 );\n    }\n\n    return( -1 );\n}\n\n/*\n * Compare two X.509 strings, case-insensitive, and allowing for some encoding\n * variations (but not all).\n *\n * Return 0 if equal, -1 otherwise.\n */\nstatic int x509_string_cmp( const mbedtls_x509_buf *a, const mbedtls_x509_buf *b )\n{\n    if( a->tag == b->tag &&\n        a->len == b->len &&\n        memcmp( a->p, b->p, b->len ) == 0 )\n    {\n        return( 0 );\n    }\n\n    if( ( a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&\n        ( b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&\n        a->len == b->len &&\n        x509_memcasecmp( a->p, b->p, b->len ) == 0 )\n    {\n        return( 0 );\n    }\n\n    return( -1 );\n}\n\n/*\n * Compare two X.509 Names (aka rdnSequence).\n *\n * See RFC 5280 section 7.1, though we don't implement the whole algorithm:\n * we sometimes return unequal when the full algorithm would return equal,\n * but never the other way. (In particular, we don't do Unicode normalisation\n * or space folding.)\n *\n * Return 0 if equal, -1 otherwise.\n */\nstatic int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b )\n{\n    /* Avoid recursion, it might not be optimised by the compiler */\n    while( a != NULL || b != NULL )\n    {\n        if( a == NULL || b == NULL )\n            return( -1 );\n\n        /* type */\n        if( a->oid.tag != b->oid.tag ||\n            a->oid.len != b->oid.len ||\n            memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 )\n        {\n            return( -1 );\n        }\n\n        /* value */\n        if( x509_string_cmp( &a->val, &b->val ) != 0 )\n            return( -1 );\n\n        /* structure of the list of sets */\n        if( a->next_merged != b->next_merged )\n            return( -1 );\n\n        a = a->next;\n        b = b->next;\n    }\n\n    /* a == NULL == b */\n    return( 0 );\n}\n\n/*\n * Check the signature of a certificate by its parent\n */\nstatic int x509_crt_check_signature( const mbedtls_x509_crt *child,\n                                     mbedtls_x509_crt *parent )\n{\n    const mbedtls_md_info_t *md_info;\n    unsigned char hash[MBEDTLS_MD_MAX_SIZE];\n\n    md_info = mbedtls_md_info_from_type( child->sig_md );\n    if( mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ) != 0 )\n    {\n        /* Note: this can't happen except after an internal error */\n        return( -1 );\n    }\n\n    if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk,\n                child->sig_md, hash, mbedtls_md_get_size( md_info ),\n                child->sig.p, child->sig.len ) != 0 )\n    {\n        return( -1 );\n    }\n\n    return( 0 );\n}\n\n/*\n * Check if 'parent' is a suitable parent (signing CA) for 'child'.\n * Return 0 if yes, -1 if not.\n *\n * top means parent is a locally-trusted certificate\n */\nstatic int x509_crt_check_parent( const mbedtls_x509_crt *child,\n                                  const mbedtls_x509_crt *parent,\n                                  int top )\n{\n    int need_ca_bit;\n\n    /* Parent must be the issuer */\n    if( x509_name_cmp( &child->issuer, &parent->subject ) != 0 )\n        return( -1 );\n\n    /* Parent must have the basicConstraints CA bit set as a general rule */\n    need_ca_bit = 1;\n\n    /* Exception: v1/v2 certificates that are locally trusted. */\n    if( top && parent->version < 3 )\n        need_ca_bit = 0;\n\n    if( need_ca_bit && ! parent->ca_istrue )\n        return( -1 );\n\n#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)\n    if( need_ca_bit &&\n        mbedtls_x509_crt_check_key_usage( parent, MBEDTLS_X509_KU_KEY_CERT_SIGN ) != 0 )\n    {\n        return( -1 );\n    }\n#endif\n\n    return( 0 );\n}\n\n/*\n * Find a suitable parent for child in candidates, or return NULL.\n *\n * Here suitable is defined as:\n *  1. subject name matches child's issuer\n *  2. if necessary, the CA bit is set and key usage allows signing certs\n *  3. for trusted roots, the signature is correct\n *  4. pathlen constraints are satisfied\n *\n * If there's a suitable candidate which is also time-valid, return the first\n * such. Otherwise, return the first suitable candidate (or NULL if there is\n * none).\n *\n * The rationale for this rule is that someone could have a list of trusted\n * roots with two versions on the same root with different validity periods.\n * (At least one user reported having such a list and wanted it to just work.)\n * The reason we don't just require time-validity is that generally there is\n * only one version, and if it's expired we want the flags to state that\n * rather than NOT_TRUSTED, as would be the case if we required it here.\n *\n * The rationale for rule 3 (signature for trusted roots) is that users might\n * have two versions of the same CA with different keys in their list, and the\n * way we select the correct one is by checking the signature (as we don't\n * rely on key identifier extensions). (This is one way users might choose to\n * handle key rollover, another relies on self-issued certs, see [SIRO].)\n *\n * Arguments:\n *  - [in] child: certificate for which we're looking for a parent\n *  - [in] candidates: chained list of potential parents\n *  - [in] top: 1 if candidates consists of trusted roots, ie we're at the top\n *         of the chain, 0 otherwise\n *  - [in] path_cnt: number of intermediates seen so far\n *  - [in] self_cnt: number of self-signed intermediates seen so far\n *         (will never be greater than path_cnt)\n *\n * Return value:\n *  - the first suitable parent found (see above regarding time-validity)\n *  - NULL if no suitable parent was found\n */\nstatic mbedtls_x509_crt *x509_crt_find_parent_in( mbedtls_x509_crt *child,\n                                                  mbedtls_x509_crt *candidates,\n                                                  int top,\n                                                  size_t path_cnt,\n                                                  size_t self_cnt )\n{\n    mbedtls_x509_crt *parent, *badtime_parent = NULL;\n\n    for( parent = candidates; parent != NULL; parent = parent->next )\n    {\n        /* basic parenting skills (name, CA bit, key usage) */\n        if( x509_crt_check_parent( child, parent, top ) != 0 )\n            continue;\n\n        /* +1 because stored max_pathlen is 1 higher that the actual value */\n        if( parent->max_pathlen > 0 &&\n            (size_t) parent->max_pathlen < 1 + path_cnt - self_cnt )\n        {\n            continue;\n        }\n\n        /* Signature */\n        if( top && x509_crt_check_signature( child, parent ) != 0 )\n        {\n            continue;\n        }\n\n        /* optional time check */\n        if( mbedtls_x509_time_is_past( &parent->valid_to ) ||\n            mbedtls_x509_time_is_future( &parent->valid_from ) )\n        {\n            if( badtime_parent == NULL )\n                badtime_parent = parent;\n\n            continue;\n        }\n\n        break;\n    }\n\n    if( parent == NULL )\n        parent = badtime_parent;\n\n    return( parent );\n}\n\n/*\n * Find a parent in trusted CAs or the provided chain, or return NULL.\n *\n * Searches in trusted CAs first, and return the first suitable parent found\n * (see find_parent_in() for definition of suitable).\n *\n * Arguments:\n *  - [in] child: certificate for which we're looking for a parent, followed\n *         by a chain of possible intermediates\n *  - [in] trust_ca: locally trusted CAs\n *  - [out] 1 if parent was found in trust_ca, 0 if found in provided chain\n *  - [in] path_cnt: number of intermediates seen so far\n *  - [in] self_cnt: number of self-signed intermediates seen so far\n *         (will always be no greater than path_cnt)\n *\n * Return value:\n *  - the first suitable parent found (see find_parent_in() for \"suitable\")\n *  - NULL if no suitable parent was found\n */\nstatic mbedtls_x509_crt *x509_crt_find_parent( mbedtls_x509_crt *child,\n                                               mbedtls_x509_crt *trust_ca,\n                                               int *parent_is_trusted,\n                                               size_t path_cnt,\n                                               size_t self_cnt )\n{\n    mbedtls_x509_crt *parent;\n\n    /* Look for a parent in trusted CAs */\n    *parent_is_trusted = 1;\n    parent = x509_crt_find_parent_in( child, trust_ca, 1, path_cnt, self_cnt );\n\n    if( parent != NULL )\n        return( parent );\n\n    /* Look for a parent upwards the chain */\n    *parent_is_trusted = 0;\n    return( x509_crt_find_parent_in( child, child->next, 0, path_cnt, self_cnt ) );\n}\n\n/*\n * Check if an end-entity certificate is locally trusted\n *\n * Currently we require such certificates to be self-signed (actually only\n * check for self-issued as self-signatures are not checked)\n */\nstatic int x509_crt_check_ee_locally_trusted(\n                    mbedtls_x509_crt *crt,\n                    mbedtls_x509_crt *trust_ca )\n{\n    mbedtls_x509_crt *cur;\n\n    /* must be self-issued */\n    if( x509_name_cmp( &crt->issuer, &crt->subject ) != 0 )\n        return( -1 );\n\n    /* look for an exact match with trusted cert */\n    for( cur = trust_ca; cur != NULL; cur = cur->next )\n    {\n        if( crt->raw.len == cur->raw.len &&\n            memcmp( crt->raw.p, cur->raw.p, crt->raw.len ) == 0 )\n        {\n            return( 0 );\n        }\n    }\n\n    /* too bad */\n    return( -1 );\n}\n\n/*\n * Build and verify a certificate chain\n *\n * Given a peer-provided list of certificates EE, C1, ..., Cn and\n * a list of trusted certs R1, ... Rp, try to build and verify a chain\n *      EE, Ci1, ... Ciq [, Rj]\n * such that every cert in the chain is a child of the next one,\n * jumping to a trusted root as early as possible.\n *\n * Verify that chain and return it with flags for all issues found.\n *\n * Special cases:\n * - EE == Rj -> return a one-element list containing it\n * - EE, Ci1, ..., Ciq cannot be continued with a trusted root\n *   -> return that chain with NOT_TRUSTED set on Ciq\n *\n * Arguments:\n *  - [in] crt: the cert list EE, C1, ..., Cn\n *  - [in] trust_ca: the trusted list R1, ..., Rp\n *  - [in] ca_crl, profile: as in verify_with_profile()\n *  - [out] ver_chain, chain_len: the built and verified chain\n *\n * Return value:\n *  - non-zero if the chain could not be fully built and examined\n *  - 0 is the chain was successfully built and examined,\n *      even if it was found to be invalid\n */\nstatic int x509_crt_verify_chain(\n                mbedtls_x509_crt *crt,\n                mbedtls_x509_crt *trust_ca,\n                mbedtls_x509_crl *ca_crl,\n                const mbedtls_x509_crt_profile *profile,\n                x509_crt_verify_chain_item ver_chain[X509_MAX_VERIFY_CHAIN_SIZE],\n                size_t *chain_len )\n{\n    uint32_t *flags;\n    mbedtls_x509_crt *child;\n    mbedtls_x509_crt *parent;\n    int parent_is_trusted = 0;\n    int child_is_trusted = 0;\n    size_t self_cnt = 0;\n\n    child = crt;\n    *chain_len = 0;\n\n    while( 1 ) {\n        /* Add certificate to the verification chain */\n        ver_chain[*chain_len].crt = child;\n        flags = &ver_chain[*chain_len].flags;\n        ++*chain_len;\n\n        /* Check time-validity (all certificates) */\n        if( mbedtls_x509_time_is_past( &child->valid_to ) )\n            *flags |= MBEDTLS_X509_BADCERT_EXPIRED;\n\n        if( mbedtls_x509_time_is_future( &child->valid_from ) )\n            *flags |= MBEDTLS_X509_BADCERT_FUTURE;\n\n        /* Stop here for trusted roots (but not for trusted EE certs) */\n        if( child_is_trusted )\n            return( 0 );\n\n        /* Check signature algorithm: MD & PK algs */\n        if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 )\n            *flags |= MBEDTLS_X509_BADCERT_BAD_MD;\n\n        if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 )\n            *flags |= MBEDTLS_X509_BADCERT_BAD_PK;\n\n        /* Special case: EE certs that are locally trusted */\n        if( *chain_len == 1 &&\n            x509_crt_check_ee_locally_trusted( child, trust_ca ) == 0 )\n        {\n            return( 0 );\n        }\n\n        /* Look for a parent in trusted CAs or up the chain */\n        parent = x509_crt_find_parent( child, trust_ca, &parent_is_trusted,\n                                       *chain_len - 1, self_cnt );\n\n        /* No parent? We're done here */\n        if( parent == NULL )\n        {\n            *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;\n            return( 0 );\n        }\n\n        /* Count intermediate self-issued (not necessarily self-signed) certs.\n         * These can occur with some strategies for key rollover, see [SIRO],\n         * and should be excluded from max_pathlen checks. */\n        if( *chain_len != 1 &&\n            x509_name_cmp( &child->issuer, &child->subject ) == 0 )\n        {\n            self_cnt++;\n        }\n\n        /* path_cnt is 0 for the first intermediate CA,\n         * and if parent is trusted it's not an intermediate CA */\n        if( ! parent_is_trusted &&\n            *chain_len > MBEDTLS_X509_MAX_INTERMEDIATE_CA )\n        {\n            /* return immediately to avoid overflow the chain array */\n            return( MBEDTLS_ERR_X509_FATAL_ERROR );\n        }\n\n        /* if parent is trusted, the signature was checked by find_parent() */\n        if( ! parent_is_trusted && x509_crt_check_signature( child, parent ) != 0 )\n            *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;\n\n        /* check size of signing key */\n        if( x509_profile_check_key( profile, &parent->pk ) != 0 )\n            *flags |= MBEDTLS_X509_BADCERT_BAD_KEY;\n\n#if defined(MBEDTLS_X509_CRL_PARSE_C)\n        /* Check trusted CA's CRL for the given crt */\n        *flags |= x509_crt_verifycrl( child, parent, ca_crl, profile );\n#else\n        (void) ca_crl;\n#endif\n\n        /* prepare for next iteration */\n        child = parent;\n        parent = NULL;\n        child_is_trusted = parent_is_trusted;\n    }\n}\n\n/*\n * Check for CN match\n */\nstatic int x509_crt_check_cn( const mbedtls_x509_buf *name,\n                              const char *cn, size_t cn_len )\n{\n    /* try exact match */\n    if( name->len == cn_len &&\n        x509_memcasecmp( cn, name->p, cn_len ) == 0 )\n    {\n        return( 0 );\n    }\n\n    /* try wildcard match */\n    if( x509_check_wildcard( cn, name ) == 0 )\n    {\n        return( 0 );\n    }\n\n    return( -1 );\n}\n\n/*\n * Verify the requested CN - only call this if cn is not NULL!\n */\nstatic void x509_crt_verify_name( const mbedtls_x509_crt *crt,\n                                  const char *cn,\n                                  uint32_t *flags )\n{\n    const mbedtls_x509_name *name;\n    const mbedtls_x509_sequence *cur;\n    size_t cn_len = strlen( cn );\n\n    if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )\n    {\n        for( cur = &crt->subject_alt_names; cur != NULL; cur = cur->next )\n        {\n            if( x509_crt_check_cn( &cur->buf, cn, cn_len ) == 0 )\n                break;\n        }\n\n        if( cur == NULL )\n            *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;\n    }\n    else\n    {\n        for( name = &crt->subject; name != NULL; name = name->next )\n        {\n            if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 &&\n                x509_crt_check_cn( &name->val, cn, cn_len ) == 0 )\n            {\n                break;\n            }\n        }\n\n        if( name == NULL )\n            *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;\n    }\n}\n\n/*\n * Merge the flags for all certs in the chain, after calling callback\n */\nstatic int x509_crt_merge_flags_with_cb(\n           uint32_t *flags,\n           x509_crt_verify_chain_item ver_chain[X509_MAX_VERIFY_CHAIN_SIZE],\n           size_t chain_len,\n           int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),\n           void *p_vrfy )\n{\n    int ret;\n    size_t i;\n    uint32_t cur_flags;\n\n    for( i = chain_len; i != 0; --i )\n    {\n        cur_flags = ver_chain[i-1].flags;\n\n        if( NULL != f_vrfy )\n            if( ( ret = f_vrfy( p_vrfy, ver_chain[i-1].crt, (int) i-1, &cur_flags ) ) != 0 )\n                return( ret );\n\n        *flags |= cur_flags;\n    }\n\n    return( 0 );\n}\n\n/*\n * Verify the certificate validity\n */\nint mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,\n                     mbedtls_x509_crt *trust_ca,\n                     mbedtls_x509_crl *ca_crl,\n                     const char *cn, uint32_t *flags,\n                     int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),\n                     void *p_vrfy )\n{\n    return( mbedtls_x509_crt_verify_with_profile( crt, trust_ca, ca_crl,\n                &mbedtls_x509_crt_profile_default, cn, flags, f_vrfy, p_vrfy ) );\n}\n\n/*\n * Verify the certificate validity, with profile\n *\n * This function:\n *  - checks the requested CN (if any)\n *  - checks the type and size of the EE cert's key,\n *    as that isn't done as part of chain building/verification currently\n *  - builds and verifies the chain\n *  - then calls the callback and merges the flags\n */\nint mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,\n                     mbedtls_x509_crt *trust_ca,\n                     mbedtls_x509_crl *ca_crl,\n                     const mbedtls_x509_crt_profile *profile,\n                     const char *cn, uint32_t *flags,\n                     int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),\n                     void *p_vrfy )\n{\n    int ret;\n    mbedtls_pk_type_t pk_type;\n    x509_crt_verify_chain_item ver_chain[X509_MAX_VERIFY_CHAIN_SIZE];\n    size_t chain_len;\n    uint32_t *ee_flags = &ver_chain[0].flags;\n\n    *flags = 0;\n    memset( ver_chain, 0, sizeof( ver_chain ) );\n    chain_len = 0;\n\n    if( profile == NULL )\n    {\n        ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA;\n        goto exit;\n    }\n\n    /* check name if requested */\n    if( cn != NULL )\n        x509_crt_verify_name( crt, cn, ee_flags );\n\n    /* Check the type and size of the key */\n    pk_type = mbedtls_pk_get_type( &crt->pk );\n\n    if( x509_profile_check_pk_alg( profile, pk_type ) != 0 )\n        *ee_flags |= MBEDTLS_X509_BADCERT_BAD_PK;\n\n    if( x509_profile_check_key( profile, &crt->pk ) != 0 )\n        *ee_flags |= MBEDTLS_X509_BADCERT_BAD_KEY;\n\n    /* Check the chain */\n    ret = x509_crt_verify_chain( crt, trust_ca, ca_crl, profile,\n                                 ver_chain, &chain_len );\n    if( ret != 0 )\n        goto exit;\n\n    /* Build final flags, calling callback on the way if any */\n    ret = x509_crt_merge_flags_with_cb( flags,\n                                        ver_chain, chain_len, f_vrfy, p_vrfy );\n\nexit:\n    /* prevent misuse of the vrfy callback - VERIFY_FAILED would be ignored by\n     * the SSL module for authmode optional, but non-zero return from the\n     * callback means a fatal error so it shouldn't be ignored */\n    if( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED )\n        ret = MBEDTLS_ERR_X509_FATAL_ERROR;\n\n    if( ret != 0 )\n    {\n        *flags = (uint32_t) -1;\n        return( ret );\n    }\n\n    if( *flags != 0 )\n        return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );\n\n    return( 0 );\n}\n\n/*\n * Initialize a certificate chain\n */\nvoid mbedtls_x509_crt_init( mbedtls_x509_crt *crt )\n{\n    memset( crt, 0, sizeof(mbedtls_x509_crt) );\n}\n\n/*\n * Unallocate all certificate data\n */\nvoid mbedtls_x509_crt_free( mbedtls_x509_crt *crt )\n{\n    mbedtls_x509_crt *cert_cur = crt;\n    mbedtls_x509_crt *cert_prv;\n    mbedtls_x509_name *name_cur;\n    mbedtls_x509_name *name_prv;\n    mbedtls_x509_sequence *seq_cur;\n    mbedtls_x509_sequence *seq_prv;\n\n    if( crt == NULL )\n        return;\n\n    do\n    {\n        mbedtls_pk_free( &cert_cur->pk );\n\n#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)\n        mbedtls_free( cert_cur->sig_opts );\n#endif\n\n        name_cur = cert_cur->issuer.next;\n        while( name_cur != NULL )\n        {\n            name_prv = name_cur;\n            name_cur = name_cur->next;\n            mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) );\n            mbedtls_free( name_prv );\n        }\n\n        name_cur = cert_cur->subject.next;\n        while( name_cur != NULL )\n        {\n            name_prv = name_cur;\n            name_cur = name_cur->next;\n            mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) );\n            mbedtls_free( name_prv );\n        }\n\n        seq_cur = cert_cur->ext_key_usage.next;\n        while( seq_cur != NULL )\n        {\n            seq_prv = seq_cur;\n            seq_cur = seq_cur->next;\n            mbedtls_platform_zeroize( seq_prv,\n                                      sizeof( mbedtls_x509_sequence ) );\n            mbedtls_free( seq_prv );\n        }\n\n        seq_cur = cert_cur->subject_alt_names.next;\n        while( seq_cur != NULL )\n        {\n            seq_prv = seq_cur;\n            seq_cur = seq_cur->next;\n            mbedtls_platform_zeroize( seq_prv,\n                                      sizeof( mbedtls_x509_sequence ) );\n            mbedtls_free( seq_prv );\n        }\n\n        if( cert_cur->raw.p != NULL )\n        {\n            mbedtls_platform_zeroize( cert_cur->raw.p, cert_cur->raw.len );\n            mbedtls_free( cert_cur->raw.p );\n        }\n\n        cert_cur = cert_cur->next;\n    }\n    while( cert_cur != NULL );\n\n    cert_cur = crt;\n    do\n    {\n        cert_prv = cert_cur;\n        cert_cur = cert_cur->next;\n\n        mbedtls_platform_zeroize( cert_prv, sizeof( mbedtls_x509_crt ) );\n        if( cert_prv != crt )\n            mbedtls_free( cert_prv );\n    }\n    while( cert_cur != NULL );\n}\n\n#endif /* MBEDTLS_X509_CRT_PARSE_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/x509_csr.c",
    "content": "/*\n *  X.509 Certificate Signing Request (CSR) parsing\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n *  The ITU-T X.509 standard defines a certificate format for PKI.\n *\n *  http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs)\n *  http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs)\n *  http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10)\n *\n *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf\n *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_X509_CSR_PARSE_C)\n\n#include \"mbedtls/x509_csr.h\"\n#include \"mbedtls/oid.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_PEM_PARSE_C)\n#include \"mbedtls/pem.h\"\n#endif\n\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdlib.h>\n#include <stdio.h>\n#define mbedtls_free       free\n#define mbedtls_calloc    calloc\n#define mbedtls_snprintf   snprintf\n#endif\n\n#if defined(MBEDTLS_FS_IO) || defined(EFIX64) || defined(EFI32)\n#include <stdio.h>\n#endif\n\n/*\n *  Version  ::=  INTEGER  {  v1(0)  }\n */\nstatic int x509_csr_get_version( unsigned char **p,\n                             const unsigned char *end,\n                             int *ver )\n{\n    int ret;\n\n    if( ( ret = mbedtls_asn1_get_int( p, end, ver ) ) != 0 )\n    {\n        if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )\n        {\n            *ver = 0;\n            return( 0 );\n        }\n\n        return( MBEDTLS_ERR_X509_INVALID_VERSION + ret );\n    }\n\n    return( 0 );\n}\n\n/*\n * Parse a CSR in DER format\n */\nint mbedtls_x509_csr_parse_der( mbedtls_x509_csr *csr,\n                        const unsigned char *buf, size_t buflen )\n{\n    int ret;\n    size_t len;\n    unsigned char *p, *end;\n    mbedtls_x509_buf sig_params;\n\n    memset( &sig_params, 0, sizeof( mbedtls_x509_buf ) );\n\n    /*\n     * Check for valid input\n     */\n    if( csr == NULL || buf == NULL || buflen == 0 )\n        return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n\n    mbedtls_x509_csr_init( csr );\n\n    /*\n     * first copy the raw DER data\n     */\n    p = mbedtls_calloc( 1, len = buflen );\n\n    if( p == NULL )\n        return( MBEDTLS_ERR_X509_ALLOC_FAILED );\n\n    memcpy( p, buf, buflen );\n\n    csr->raw.p = p;\n    csr->raw.len = len;\n    end = p + len;\n\n    /*\n     *  CertificationRequest ::= SEQUENCE {\n     *       certificationRequestInfo CertificationRequestInfo,\n     *       signatureAlgorithm AlgorithmIdentifier,\n     *       signature          BIT STRING\n     *  }\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        mbedtls_x509_csr_free( csr );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT );\n    }\n\n    if( len != (size_t) ( end - p ) )\n    {\n        mbedtls_x509_csr_free( csr );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n    }\n\n    /*\n     *  CertificationRequestInfo ::= SEQUENCE {\n     */\n    csr->cri.p = p;\n\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        mbedtls_x509_csr_free( csr );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );\n    }\n\n    end = p + len;\n    csr->cri.len = end - csr->cri.p;\n\n    /*\n     *  Version  ::=  INTEGER {  v1(0) }\n     */\n    if( ( ret = x509_csr_get_version( &p, end, &csr->version ) ) != 0 )\n    {\n        mbedtls_x509_csr_free( csr );\n        return( ret );\n    }\n\n    if( csr->version != 0 )\n    {\n        mbedtls_x509_csr_free( csr );\n        return( MBEDTLS_ERR_X509_UNKNOWN_VERSION );\n    }\n\n    csr->version++;\n\n    /*\n     *  subject               Name\n     */\n    csr->subject_raw.p = p;\n\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )\n    {\n        mbedtls_x509_csr_free( csr );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );\n    }\n\n    if( ( ret = mbedtls_x509_get_name( &p, p + len, &csr->subject ) ) != 0 )\n    {\n        mbedtls_x509_csr_free( csr );\n        return( ret );\n    }\n\n    csr->subject_raw.len = p - csr->subject_raw.p;\n\n    /*\n     *  subjectPKInfo SubjectPublicKeyInfo\n     */\n    if( ( ret = mbedtls_pk_parse_subpubkey( &p, end, &csr->pk ) ) != 0 )\n    {\n        mbedtls_x509_csr_free( csr );\n        return( ret );\n    }\n\n    /*\n     *  attributes    [0] Attributes\n     *\n     *  The list of possible attributes is open-ended, though RFC 2985\n     *  (PKCS#9) defines a few in section 5.4. We currently don't support any,\n     *  so we just ignore them. This is a safe thing to do as the worst thing\n     *  that could happen is that we issue a certificate that does not match\n     *  the requester's expectations - this cannot cause a violation of our\n     *  signature policies.\n     */\n    if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,\n            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC ) ) != 0 )\n    {\n        mbedtls_x509_csr_free( csr );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );\n    }\n\n    p += len;\n\n    end = csr->raw.p + csr->raw.len;\n\n    /*\n     *  signatureAlgorithm   AlgorithmIdentifier,\n     *  signature            BIT STRING\n     */\n    if( ( ret = mbedtls_x509_get_alg( &p, end, &csr->sig_oid, &sig_params ) ) != 0 )\n    {\n        mbedtls_x509_csr_free( csr );\n        return( ret );\n    }\n\n    if( ( ret = mbedtls_x509_get_sig_alg( &csr->sig_oid, &sig_params,\n                                  &csr->sig_md, &csr->sig_pk,\n                                  &csr->sig_opts ) ) != 0 )\n    {\n        mbedtls_x509_csr_free( csr );\n        return( MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG );\n    }\n\n    if( ( ret = mbedtls_x509_get_sig( &p, end, &csr->sig ) ) != 0 )\n    {\n        mbedtls_x509_csr_free( csr );\n        return( ret );\n    }\n\n    if( p != end )\n    {\n        mbedtls_x509_csr_free( csr );\n        return( MBEDTLS_ERR_X509_INVALID_FORMAT +\n                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );\n    }\n\n    return( 0 );\n}\n\n/*\n * Parse a CSR, allowing for PEM or raw DER encoding\n */\nint mbedtls_x509_csr_parse( mbedtls_x509_csr *csr, const unsigned char *buf, size_t buflen )\n{\n#if defined(MBEDTLS_PEM_PARSE_C)\n    int ret;\n    size_t use_len;\n    mbedtls_pem_context pem;\n#endif\n\n    /*\n     * Check for valid input\n     */\n    if( csr == NULL || buf == NULL || buflen == 0 )\n        return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n\n#if defined(MBEDTLS_PEM_PARSE_C)\n    /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */\n    if( buf[buflen - 1] == '\\0' )\n    {\n        mbedtls_pem_init( &pem );\n        ret = mbedtls_pem_read_buffer( &pem,\n                               \"-----BEGIN CERTIFICATE REQUEST-----\",\n                               \"-----END CERTIFICATE REQUEST-----\",\n                               buf, NULL, 0, &use_len );\n\n        if( ret == 0 )\n            /*\n             * Was PEM encoded, parse the result\n             */\n            ret = mbedtls_x509_csr_parse_der( csr, pem.buf, pem.buflen );\n\n        mbedtls_pem_free( &pem );\n        if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )\n            return( ret );\n    }\n#endif /* MBEDTLS_PEM_PARSE_C */\n    return( mbedtls_x509_csr_parse_der( csr, buf, buflen ) );\n}\n\n#if defined(MBEDTLS_FS_IO)\n/*\n * Load a CSR into the structure\n */\nint mbedtls_x509_csr_parse_file( mbedtls_x509_csr *csr, const char *path )\n{\n    int ret;\n    size_t n;\n    unsigned char *buf;\n\n    if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )\n        return( ret );\n\n    ret = mbedtls_x509_csr_parse( csr, buf, n );\n\n    mbedtls_platform_zeroize( buf, n );\n    mbedtls_free( buf );\n\n    return( ret );\n}\n#endif /* MBEDTLS_FS_IO */\n\n#define BEFORE_COLON    14\n#define BC              \"14\"\n/*\n * Return an informational string about the CSR.\n */\nint mbedtls_x509_csr_info( char *buf, size_t size, const char *prefix,\n                   const mbedtls_x509_csr *csr )\n{\n    int ret;\n    size_t n;\n    char *p;\n    char key_size_str[BEFORE_COLON];\n\n    p = buf;\n    n = size;\n\n    ret = mbedtls_snprintf( p, n, \"%sCSR version   : %d\",\n                               prefix, csr->version );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    ret = mbedtls_snprintf( p, n, \"\\n%ssubject name  : \", prefix );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n    ret = mbedtls_x509_dn_gets( p, n, &csr->subject );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    ret = mbedtls_snprintf( p, n, \"\\n%ssigned using  : \", prefix );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    ret = mbedtls_x509_sig_alg_gets( p, n, &csr->sig_oid, csr->sig_pk, csr->sig_md,\n                             csr->sig_opts );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    if( ( ret = mbedtls_x509_key_size_helper( key_size_str, BEFORE_COLON,\n                                      mbedtls_pk_get_name( &csr->pk ) ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    ret = mbedtls_snprintf( p, n, \"\\n%s%-\" BC \"s: %d bits\\n\", prefix, key_size_str,\n                          (int) mbedtls_pk_get_bitlen( &csr->pk ) );\n    MBEDTLS_X509_SAFE_SNPRINTF;\n\n    return( (int) ( size - n ) );\n}\n\n/*\n * Initialize a CSR\n */\nvoid mbedtls_x509_csr_init( mbedtls_x509_csr *csr )\n{\n    memset( csr, 0, sizeof(mbedtls_x509_csr) );\n}\n\n/*\n * Unallocate all CSR data\n */\nvoid mbedtls_x509_csr_free( mbedtls_x509_csr *csr )\n{\n    mbedtls_x509_name *name_cur;\n    mbedtls_x509_name *name_prv;\n\n    if( csr == NULL )\n        return;\n\n    mbedtls_pk_free( &csr->pk );\n\n#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)\n    mbedtls_free( csr->sig_opts );\n#endif\n\n    name_cur = csr->subject.next;\n    while( name_cur != NULL )\n    {\n        name_prv = name_cur;\n        name_cur = name_cur->next;\n        mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) );\n        mbedtls_free( name_prv );\n    }\n\n    if( csr->raw.p != NULL )\n    {\n        mbedtls_platform_zeroize( csr->raw.p, csr->raw.len );\n        mbedtls_free( csr->raw.p );\n    }\n\n    mbedtls_platform_zeroize( csr, sizeof( mbedtls_x509_csr ) );\n}\n\n#endif /* MBEDTLS_X509_CSR_PARSE_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/x509write_crt.c",
    "content": "/*\n *  X.509 certificate writing\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n * References:\n * - certificates: RFC 5280, updated by RFC 6818\n * - CSRs: PKCS#10 v1.7 aka RFC 2986\n * - attributes: PKCS#9 v2.0 aka RFC 2985\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_X509_CRT_WRITE_C)\n\n#include \"mbedtls/x509_crt.h\"\n#include \"mbedtls/oid.h\"\n#include \"mbedtls/asn1write.h\"\n#include \"mbedtls/sha1.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_PEM_WRITE_C)\n#include \"mbedtls/pem.h\"\n#endif /* MBEDTLS_PEM_WRITE_C */\n\nvoid mbedtls_x509write_crt_init( mbedtls_x509write_cert *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_x509write_cert ) );\n\n    mbedtls_mpi_init( &ctx->serial );\n    ctx->version = MBEDTLS_X509_CRT_VERSION_3;\n}\n\nvoid mbedtls_x509write_crt_free( mbedtls_x509write_cert *ctx )\n{\n    mbedtls_mpi_free( &ctx->serial );\n\n    mbedtls_asn1_free_named_data_list( &ctx->subject );\n    mbedtls_asn1_free_named_data_list( &ctx->issuer );\n    mbedtls_asn1_free_named_data_list( &ctx->extensions );\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_x509write_cert ) );\n}\n\nvoid mbedtls_x509write_crt_set_version( mbedtls_x509write_cert *ctx, int version )\n{\n    ctx->version = version;\n}\n\nvoid mbedtls_x509write_crt_set_md_alg( mbedtls_x509write_cert *ctx, mbedtls_md_type_t md_alg )\n{\n    ctx->md_alg = md_alg;\n}\n\nvoid mbedtls_x509write_crt_set_subject_key( mbedtls_x509write_cert *ctx, mbedtls_pk_context *key )\n{\n    ctx->subject_key = key;\n}\n\nvoid mbedtls_x509write_crt_set_issuer_key( mbedtls_x509write_cert *ctx, mbedtls_pk_context *key )\n{\n    ctx->issuer_key = key;\n}\n\nint mbedtls_x509write_crt_set_subject_name( mbedtls_x509write_cert *ctx,\n                                    const char *subject_name )\n{\n    return mbedtls_x509_string_to_names( &ctx->subject, subject_name );\n}\n\nint mbedtls_x509write_crt_set_issuer_name( mbedtls_x509write_cert *ctx,\n                                   const char *issuer_name )\n{\n    return mbedtls_x509_string_to_names( &ctx->issuer, issuer_name );\n}\n\nint mbedtls_x509write_crt_set_serial( mbedtls_x509write_cert *ctx, const mbedtls_mpi *serial )\n{\n    int ret;\n\n    if( ( ret = mbedtls_mpi_copy( &ctx->serial, serial ) ) != 0 )\n        return( ret );\n\n    return( 0 );\n}\n\nint mbedtls_x509write_crt_set_validity( mbedtls_x509write_cert *ctx, const char *not_before,\n                                const char *not_after )\n{\n    if( strlen( not_before ) != MBEDTLS_X509_RFC5280_UTC_TIME_LEN - 1 ||\n        strlen( not_after )  != MBEDTLS_X509_RFC5280_UTC_TIME_LEN - 1 )\n    {\n        return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n    }\n    strncpy( ctx->not_before, not_before, MBEDTLS_X509_RFC5280_UTC_TIME_LEN );\n    strncpy( ctx->not_after , not_after , MBEDTLS_X509_RFC5280_UTC_TIME_LEN );\n    ctx->not_before[MBEDTLS_X509_RFC5280_UTC_TIME_LEN - 1] = 'Z';\n    ctx->not_after[MBEDTLS_X509_RFC5280_UTC_TIME_LEN - 1] = 'Z';\n\n    return( 0 );\n}\n\nint mbedtls_x509write_crt_set_extension( mbedtls_x509write_cert *ctx,\n                                 const char *oid, size_t oid_len,\n                                 int critical,\n                                 const unsigned char *val, size_t val_len )\n{\n    return mbedtls_x509_set_extension( &ctx->extensions, oid, oid_len,\n                               critical, val, val_len );\n}\n\nint mbedtls_x509write_crt_set_basic_constraints( mbedtls_x509write_cert *ctx,\n                                         int is_ca, int max_pathlen )\n{\n    int ret;\n    unsigned char buf[9];\n    unsigned char *c = buf + sizeof(buf);\n    size_t len = 0;\n\n    memset( buf, 0, sizeof(buf) );\n\n    if( is_ca && max_pathlen > 127 )\n        return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );\n\n    if( is_ca )\n    {\n        if( max_pathlen >= 0 )\n        {\n            MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_int( &c, buf, max_pathlen ) );\n        }\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_bool( &c, buf, 1 ) );\n    }\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED |\n                                                MBEDTLS_ASN1_SEQUENCE ) );\n\n    return mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_BASIC_CONSTRAINTS,\n                                        MBEDTLS_OID_SIZE( MBEDTLS_OID_BASIC_CONSTRAINTS ),\n                                        0, buf + sizeof(buf) - len, len );\n}\n\n#if defined(MBEDTLS_SHA1_C)\nint mbedtls_x509write_crt_set_subject_key_identifier( mbedtls_x509write_cert *ctx )\n{\n    int ret;\n    unsigned char buf[MBEDTLS_MPI_MAX_SIZE * 2 + 20]; /* tag, length + 2xMPI */\n    unsigned char *c = buf + sizeof(buf);\n    size_t len = 0;\n\n    memset( buf, 0, sizeof(buf) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_pk_write_pubkey( &c, buf, ctx->subject_key ) );\n\n    ret = mbedtls_sha1_ret( buf + sizeof( buf ) - len, len,\n                            buf + sizeof( buf ) - 20 );\n    if( ret != 0 )\n        return( ret );\n    c = buf + sizeof( buf ) - 20;\n    len = 20;\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_OCTET_STRING ) );\n\n    return mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_SUBJECT_KEY_IDENTIFIER,\n                                        MBEDTLS_OID_SIZE( MBEDTLS_OID_SUBJECT_KEY_IDENTIFIER ),\n                                        0, buf + sizeof(buf) - len, len );\n}\n\nint mbedtls_x509write_crt_set_authority_key_identifier( mbedtls_x509write_cert *ctx )\n{\n    int ret;\n    unsigned char buf[MBEDTLS_MPI_MAX_SIZE * 2 + 20]; /* tag, length + 2xMPI */\n    unsigned char *c = buf + sizeof( buf );\n    size_t len = 0;\n\n    memset( buf, 0, sizeof(buf) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_pk_write_pubkey( &c, buf, ctx->issuer_key ) );\n\n    ret = mbedtls_sha1_ret( buf + sizeof( buf ) - len, len,\n                            buf + sizeof( buf ) - 20 );\n    if( ret != 0 )\n        return( ret );\n    c = buf + sizeof( buf ) - 20;\n    len = 20;\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | 0 ) );\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED |\n                                                MBEDTLS_ASN1_SEQUENCE ) );\n\n    return mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER,\n                                   MBEDTLS_OID_SIZE( MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER ),\n                                   0, buf + sizeof( buf ) - len, len );\n}\n#endif /* MBEDTLS_SHA1_C */\n\nint mbedtls_x509write_crt_set_key_usage( mbedtls_x509write_cert *ctx,\n                                         unsigned int key_usage )\n{\n    unsigned char buf[4], ku;\n    unsigned char *c;\n    int ret;\n\n    /* We currently only support 7 bits, from 0x80 to 0x02 */\n    if( ( key_usage & ~0xfe ) != 0 )\n        return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE );\n\n    c = buf + 4;\n    ku = (unsigned char) key_usage;\n\n    if( ( ret = mbedtls_asn1_write_bitstring( &c, buf, &ku, 7 ) ) != 4 )\n        return( ret );\n\n    ret = mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_KEY_USAGE,\n                                       MBEDTLS_OID_SIZE( MBEDTLS_OID_KEY_USAGE ),\n                                       1, buf, 4 );\n    if( ret != 0 )\n        return( ret );\n\n    return( 0 );\n}\n\nint mbedtls_x509write_crt_set_ns_cert_type( mbedtls_x509write_cert *ctx,\n                                    unsigned char ns_cert_type )\n{\n    unsigned char buf[4];\n    unsigned char *c;\n    int ret;\n\n    c = buf + 4;\n\n    if( ( ret = mbedtls_asn1_write_bitstring( &c, buf, &ns_cert_type, 8 ) ) != 4 )\n        return( ret );\n\n    ret = mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_NS_CERT_TYPE,\n                                       MBEDTLS_OID_SIZE( MBEDTLS_OID_NS_CERT_TYPE ),\n                                       0, buf, 4 );\n    if( ret != 0 )\n        return( ret );\n\n    return( 0 );\n}\n\nstatic int x509_write_time( unsigned char **p, unsigned char *start,\n                            const char *t, size_t size )\n{\n    int ret;\n    size_t len = 0;\n\n    /*\n     * write MBEDTLS_ASN1_UTC_TIME if year < 2050 (2 bytes shorter)\n     */\n    if( t[0] == '2' && t[1] == '0' && t[2] < '5' )\n    {\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start,\n                                             (const unsigned char *) t + 2,\n                                             size - 2 ) );\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_UTC_TIME ) );\n    }\n    else\n    {\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start,\n                                                  (const unsigned char *) t,\n                                                  size ) );\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_GENERALIZED_TIME ) );\n    }\n\n    return( (int) len );\n}\n\nint mbedtls_x509write_crt_der( mbedtls_x509write_cert *ctx, unsigned char *buf, size_t size,\n                       int (*f_rng)(void *, unsigned char *, size_t),\n                       void *p_rng )\n{\n    int ret;\n    const char *sig_oid;\n    size_t sig_oid_len = 0;\n    unsigned char *c, *c2;\n    unsigned char hash[64];\n    unsigned char sig[MBEDTLS_MPI_MAX_SIZE];\n    unsigned char tmp_buf[2048];\n    size_t sub_len = 0, pub_len = 0, sig_and_oid_len = 0, sig_len;\n    size_t len = 0;\n    mbedtls_pk_type_t pk_alg;\n\n    /*\n     * Prepare data to be signed in tmp_buf\n     */\n    c = tmp_buf + sizeof( tmp_buf );\n\n    /* Signature algorithm needed in TBS, and later for actual signature */\n\n    /* There's no direct way of extracting a signature algorithm\n     * (represented as an element of mbedtls_pk_type_t) from a PK instance. */\n    if( mbedtls_pk_can_do( ctx->issuer_key, MBEDTLS_PK_RSA ) )\n        pk_alg = MBEDTLS_PK_RSA;\n    else if( mbedtls_pk_can_do( ctx->issuer_key, MBEDTLS_PK_ECDSA ) )\n        pk_alg = MBEDTLS_PK_ECDSA;\n    else\n        return( MBEDTLS_ERR_X509_INVALID_ALG );\n\n    if( ( ret = mbedtls_oid_get_oid_by_sig_alg( pk_alg, ctx->md_alg,\n                                          &sig_oid, &sig_oid_len ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    /*\n     *  Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension\n     */\n\n    /* Only for v3 */\n    if( ctx->version == MBEDTLS_X509_CRT_VERSION_3 )\n    {\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_extensions( &c, tmp_buf, ctx->extensions ) );\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) );\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED |\n                                                           MBEDTLS_ASN1_SEQUENCE ) );\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) );\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC |\n                                                           MBEDTLS_ASN1_CONSTRUCTED | 3 ) );\n    }\n\n    /*\n     *  SubjectPublicKeyInfo\n     */\n    MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_pk_write_pubkey_der( ctx->subject_key,\n                                                tmp_buf, c - tmp_buf ) );\n    c -= pub_len;\n    len += pub_len;\n\n    /*\n     *  Subject  ::=  Name\n     */\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_names( &c, tmp_buf, ctx->subject ) );\n\n    /*\n     *  Validity ::= SEQUENCE {\n     *       notBefore      Time,\n     *       notAfter       Time }\n     */\n    sub_len = 0;\n\n    MBEDTLS_ASN1_CHK_ADD( sub_len, x509_write_time( &c, tmp_buf, ctx->not_after,\n                                            MBEDTLS_X509_RFC5280_UTC_TIME_LEN ) );\n\n    MBEDTLS_ASN1_CHK_ADD( sub_len, x509_write_time( &c, tmp_buf, ctx->not_before,\n                                            MBEDTLS_X509_RFC5280_UTC_TIME_LEN ) );\n\n    len += sub_len;\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, sub_len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED |\n                                                    MBEDTLS_ASN1_SEQUENCE ) );\n\n    /*\n     *  Issuer  ::=  Name\n     */\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_names( &c, tmp_buf, ctx->issuer ) );\n\n    /*\n     *  Signature   ::=  AlgorithmIdentifier\n     */\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_algorithm_identifier( &c, tmp_buf,\n                       sig_oid, strlen( sig_oid ), 0 ) );\n\n    /*\n     *  Serial   ::=  INTEGER\n     */\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &c, tmp_buf, &ctx->serial ) );\n\n    /*\n     *  Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }\n     */\n\n    /* Can be omitted for v1 */\n    if( ctx->version != MBEDTLS_X509_CRT_VERSION_1 )\n    {\n        sub_len = 0;\n        MBEDTLS_ASN1_CHK_ADD( sub_len, mbedtls_asn1_write_int( &c, tmp_buf, ctx->version ) );\n        len += sub_len;\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, sub_len ) );\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC |\n                                                           MBEDTLS_ASN1_CONSTRUCTED | 0 ) );\n    }\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED |\n                                                       MBEDTLS_ASN1_SEQUENCE ) );\n\n    /*\n     * Make signature\n     */\n    if( ( ret = mbedtls_md( mbedtls_md_info_from_type( ctx->md_alg ), c,\n                            len, hash ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    if( ( ret = mbedtls_pk_sign( ctx->issuer_key, ctx->md_alg, hash, 0, sig, &sig_len,\n                         f_rng, p_rng ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    /*\n     * Write data to output buffer\n     */\n    c2 = buf + size;\n    MBEDTLS_ASN1_CHK_ADD( sig_and_oid_len, mbedtls_x509_write_sig( &c2, buf,\n                                        sig_oid, sig_oid_len, sig, sig_len ) );\n\n    if( len > (size_t)( c2 - buf ) )\n        return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n    c2 -= len;\n    memcpy( c2, c, len );\n\n    len += sig_and_oid_len;\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c2, buf, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c2, buf, MBEDTLS_ASN1_CONSTRUCTED |\n                                                 MBEDTLS_ASN1_SEQUENCE ) );\n\n    return( (int) len );\n}\n\n#define PEM_BEGIN_CRT           \"-----BEGIN CERTIFICATE-----\\n\"\n#define PEM_END_CRT             \"-----END CERTIFICATE-----\\n\"\n\n#if defined(MBEDTLS_PEM_WRITE_C)\nint mbedtls_x509write_crt_pem( mbedtls_x509write_cert *crt, unsigned char *buf, size_t size,\n                       int (*f_rng)(void *, unsigned char *, size_t),\n                       void *p_rng )\n{\n    int ret;\n    unsigned char output_buf[4096];\n    size_t olen = 0;\n\n    if( ( ret = mbedtls_x509write_crt_der( crt, output_buf, sizeof(output_buf),\n                                   f_rng, p_rng ) ) < 0 )\n    {\n        return( ret );\n    }\n\n    if( ( ret = mbedtls_pem_write_buffer( PEM_BEGIN_CRT, PEM_END_CRT,\n                                  output_buf + sizeof(output_buf) - ret,\n                                  ret, buf, size, &olen ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_PEM_WRITE_C */\n\n#endif /* MBEDTLS_X509_CRT_WRITE_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/x509write_csr.c",
    "content": "/*\n *  X.509 Certificate Signing Request writing\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n/*\n * References:\n * - CSRs: PKCS#10 v1.7 aka RFC 2986\n * - attributes: PKCS#9 v2.0 aka RFC 2985\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_X509_CSR_WRITE_C)\n\n#include \"mbedtls/x509_csr.h\"\n#include \"mbedtls/oid.h\"\n#include \"mbedtls/asn1write.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n#include <stdlib.h>\n\n#if defined(MBEDTLS_PEM_WRITE_C)\n#include \"mbedtls/pem.h\"\n#endif\n\nvoid mbedtls_x509write_csr_init( mbedtls_x509write_csr *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_x509write_csr ) );\n}\n\nvoid mbedtls_x509write_csr_free( mbedtls_x509write_csr *ctx )\n{\n    mbedtls_asn1_free_named_data_list( &ctx->subject );\n    mbedtls_asn1_free_named_data_list( &ctx->extensions );\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_x509write_csr ) );\n}\n\nvoid mbedtls_x509write_csr_set_md_alg( mbedtls_x509write_csr *ctx, mbedtls_md_type_t md_alg )\n{\n    ctx->md_alg = md_alg;\n}\n\nvoid mbedtls_x509write_csr_set_key( mbedtls_x509write_csr *ctx, mbedtls_pk_context *key )\n{\n    ctx->key = key;\n}\n\nint mbedtls_x509write_csr_set_subject_name( mbedtls_x509write_csr *ctx,\n                                    const char *subject_name )\n{\n    return mbedtls_x509_string_to_names( &ctx->subject, subject_name );\n}\n\nint mbedtls_x509write_csr_set_extension( mbedtls_x509write_csr *ctx,\n                                 const char *oid, size_t oid_len,\n                                 const unsigned char *val, size_t val_len )\n{\n    return mbedtls_x509_set_extension( &ctx->extensions, oid, oid_len,\n                               0, val, val_len );\n}\n\nint mbedtls_x509write_csr_set_key_usage( mbedtls_x509write_csr *ctx, unsigned char key_usage )\n{\n    unsigned char buf[4];\n    unsigned char *c;\n    int ret;\n\n    c = buf + 4;\n\n    if( ( ret = mbedtls_asn1_write_bitstring( &c, buf, &key_usage, 7 ) ) != 4 )\n        return( ret );\n\n    ret = mbedtls_x509write_csr_set_extension( ctx, MBEDTLS_OID_KEY_USAGE,\n                                       MBEDTLS_OID_SIZE( MBEDTLS_OID_KEY_USAGE ),\n                                       buf, 4 );\n    if( ret != 0 )\n        return( ret );\n\n    return( 0 );\n}\n\nint mbedtls_x509write_csr_set_ns_cert_type( mbedtls_x509write_csr *ctx,\n                                    unsigned char ns_cert_type )\n{\n    unsigned char buf[4];\n    unsigned char *c;\n    int ret;\n\n    c = buf + 4;\n\n    if( ( ret = mbedtls_asn1_write_bitstring( &c, buf, &ns_cert_type, 8 ) ) != 4 )\n        return( ret );\n\n    ret = mbedtls_x509write_csr_set_extension( ctx, MBEDTLS_OID_NS_CERT_TYPE,\n                                       MBEDTLS_OID_SIZE( MBEDTLS_OID_NS_CERT_TYPE ),\n                                       buf, 4 );\n    if( ret != 0 )\n        return( ret );\n\n    return( 0 );\n}\n\nint mbedtls_x509write_csr_der( mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size,\n                       int (*f_rng)(void *, unsigned char *, size_t),\n                       void *p_rng )\n{\n    int ret;\n    const char *sig_oid;\n    size_t sig_oid_len = 0;\n    unsigned char *c, *c2;\n    unsigned char hash[64];\n    unsigned char sig[MBEDTLS_MPI_MAX_SIZE];\n    unsigned char tmp_buf[2048];\n    size_t pub_len = 0, sig_and_oid_len = 0, sig_len;\n    size_t len = 0;\n    mbedtls_pk_type_t pk_alg;\n\n    /*\n     * Prepare data to be signed in tmp_buf\n     */\n    c = tmp_buf + sizeof( tmp_buf );\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_extensions( &c, tmp_buf, ctx->extensions ) );\n\n    if( len )\n    {\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) );\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED |\n                                                        MBEDTLS_ASN1_SEQUENCE ) );\n\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) );\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED |\n                                                        MBEDTLS_ASN1_SET ) );\n\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_oid( &c, tmp_buf, MBEDTLS_OID_PKCS9_CSR_EXT_REQ,\n                                          MBEDTLS_OID_SIZE( MBEDTLS_OID_PKCS9_CSR_EXT_REQ ) ) );\n\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) );\n        MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED |\n                                                        MBEDTLS_ASN1_SEQUENCE ) );\n    }\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED |\n                                                    MBEDTLS_ASN1_CONTEXT_SPECIFIC ) );\n\n    MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_pk_write_pubkey_der( ctx->key,\n                                                tmp_buf, c - tmp_buf ) );\n    c -= pub_len;\n    len += pub_len;\n\n    /*\n     *  Subject  ::=  Name\n     */\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_names( &c, tmp_buf, ctx->subject ) );\n\n    /*\n     *  Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }\n     */\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_int( &c, tmp_buf, 0 ) );\n\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED |\n                                                    MBEDTLS_ASN1_SEQUENCE ) );\n\n    /*\n     * Prepare signature\n     */\n    mbedtls_md( mbedtls_md_info_from_type( ctx->md_alg ), c, len, hash );\n\n    if( ( ret = mbedtls_pk_sign( ctx->key, ctx->md_alg, hash, 0, sig, &sig_len,\n                                 f_rng, p_rng ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    if( mbedtls_pk_can_do( ctx->key, MBEDTLS_PK_RSA ) )\n        pk_alg = MBEDTLS_PK_RSA;\n    else if( mbedtls_pk_can_do( ctx->key, MBEDTLS_PK_ECDSA ) )\n        pk_alg = MBEDTLS_PK_ECDSA;\n    else\n        return( MBEDTLS_ERR_X509_INVALID_ALG );\n\n    if( ( ret = mbedtls_oid_get_oid_by_sig_alg( pk_alg, ctx->md_alg,\n                                                &sig_oid, &sig_oid_len ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    /*\n     * Write data to output buffer\n     */\n    c2 = buf + size;\n    MBEDTLS_ASN1_CHK_ADD( sig_and_oid_len, mbedtls_x509_write_sig( &c2, buf,\n                                        sig_oid, sig_oid_len, sig, sig_len ) );\n\n    if( len > (size_t)( c2 - buf ) )\n        return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );\n\n    c2 -= len;\n    memcpy( c2, c, len );\n\n    len += sig_and_oid_len;\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c2, buf, len ) );\n    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c2, buf, MBEDTLS_ASN1_CONSTRUCTED |\n                                                 MBEDTLS_ASN1_SEQUENCE ) );\n\n    return( (int) len );\n}\n\n#define PEM_BEGIN_CSR           \"-----BEGIN CERTIFICATE REQUEST-----\\n\"\n#define PEM_END_CSR             \"-----END CERTIFICATE REQUEST-----\\n\"\n\n#if defined(MBEDTLS_PEM_WRITE_C)\nint mbedtls_x509write_csr_pem( mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size,\n                       int (*f_rng)(void *, unsigned char *, size_t),\n                       void *p_rng )\n{\n    int ret;\n    unsigned char output_buf[4096];\n    size_t olen = 0;\n\n    if( ( ret = mbedtls_x509write_csr_der( ctx, output_buf, sizeof(output_buf),\n                                   f_rng, p_rng ) ) < 0 )\n    {\n        return( ret );\n    }\n\n    if( ( ret = mbedtls_pem_write_buffer( PEM_BEGIN_CSR, PEM_END_CSR,\n                                  output_buf + sizeof(output_buf) - ret,\n                                  ret, buf, size, &olen ) ) != 0 )\n    {\n        return( ret );\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_PEM_WRITE_C */\n\n#endif /* MBEDTLS_X509_CSR_WRITE_C */\n"
  },
  {
    "path": "jsb_build/websockets/mbedtls/library/xtea.c",
    "content": "/*\n *  An 32-bit implementation of the XTEA algorithm\n *\n *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved\n *  SPDX-License-Identifier: Apache-2.0\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n *  not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  This file is part of mbed TLS (https://tls.mbed.org)\n */\n\n#if !defined(MBEDTLS_CONFIG_FILE)\n#include \"mbedtls/config.h\"\n#else\n#include MBEDTLS_CONFIG_FILE\n#endif\n\n#if defined(MBEDTLS_XTEA_C)\n\n#include \"mbedtls/xtea.h\"\n#include \"mbedtls/platform_util.h\"\n\n#include <string.h>\n\n#if defined(MBEDTLS_SELF_TEST)\n#if defined(MBEDTLS_PLATFORM_C)\n#include \"mbedtls/platform.h\"\n#else\n#include <stdio.h>\n#define mbedtls_printf printf\n#endif /* MBEDTLS_PLATFORM_C */\n#endif /* MBEDTLS_SELF_TEST */\n\n#if !defined(MBEDTLS_XTEA_ALT)\n\n/*\n * 32-bit integer manipulation macros (big endian)\n */\n#ifndef GET_UINT32_BE\n#define GET_UINT32_BE(n,b,i)                            \\\n{                                                       \\\n    (n) = ( (uint32_t) (b)[(i)    ] << 24 )             \\\n        | ( (uint32_t) (b)[(i) + 1] << 16 )             \\\n        | ( (uint32_t) (b)[(i) + 2] <<  8 )             \\\n        | ( (uint32_t) (b)[(i) + 3]       );            \\\n}\n#endif\n\n#ifndef PUT_UINT32_BE\n#define PUT_UINT32_BE(n,b,i)                            \\\n{                                                       \\\n    (b)[(i)    ] = (unsigned char) ( (n) >> 24 );       \\\n    (b)[(i) + 1] = (unsigned char) ( (n) >> 16 );       \\\n    (b)[(i) + 2] = (unsigned char) ( (n) >>  8 );       \\\n    (b)[(i) + 3] = (unsigned char) ( (n)       );       \\\n}\n#endif\n\nvoid mbedtls_xtea_init( mbedtls_xtea_context *ctx )\n{\n    memset( ctx, 0, sizeof( mbedtls_xtea_context ) );\n}\n\nvoid mbedtls_xtea_free( mbedtls_xtea_context *ctx )\n{\n    if( ctx == NULL )\n        return;\n\n    mbedtls_platform_zeroize( ctx, sizeof( mbedtls_xtea_context ) );\n}\n\n/*\n * XTEA key schedule\n */\nvoid mbedtls_xtea_setup( mbedtls_xtea_context *ctx, const unsigned char key[16] )\n{\n    int i;\n\n    memset( ctx, 0, sizeof(mbedtls_xtea_context) );\n\n    for( i = 0; i < 4; i++ )\n    {\n        GET_UINT32_BE( ctx->k[i], key, i << 2 );\n    }\n}\n\n/*\n * XTEA encrypt function\n */\nint mbedtls_xtea_crypt_ecb( mbedtls_xtea_context *ctx, int mode,\n                    const unsigned char input[8], unsigned char output[8])\n{\n    uint32_t *k, v0, v1, i;\n\n    k = ctx->k;\n\n    GET_UINT32_BE( v0, input, 0 );\n    GET_UINT32_BE( v1, input, 4 );\n\n    if( mode == MBEDTLS_XTEA_ENCRYPT )\n    {\n        uint32_t sum = 0, delta = 0x9E3779B9;\n\n        for( i = 0; i < 32; i++ )\n        {\n            v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);\n            sum += delta;\n            v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]);\n        }\n    }\n    else /* MBEDTLS_XTEA_DECRYPT */\n    {\n        uint32_t delta = 0x9E3779B9, sum = delta * 32;\n\n        for( i = 0; i < 32; i++ )\n        {\n            v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]);\n            sum -= delta;\n            v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);\n        }\n    }\n\n    PUT_UINT32_BE( v0, output, 0 );\n    PUT_UINT32_BE( v1, output, 4 );\n\n    return( 0 );\n}\n\n#if defined(MBEDTLS_CIPHER_MODE_CBC)\n/*\n * XTEA-CBC buffer encryption/decryption\n */\nint mbedtls_xtea_crypt_cbc( mbedtls_xtea_context *ctx, int mode, size_t length,\n                    unsigned char iv[8], const unsigned char *input,\n                    unsigned char *output)\n{\n    int i;\n    unsigned char temp[8];\n\n    if( length % 8 )\n        return( MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH );\n\n    if( mode == MBEDTLS_XTEA_DECRYPT )\n    {\n        while( length > 0 )\n        {\n            memcpy( temp, input, 8 );\n            mbedtls_xtea_crypt_ecb( ctx, mode, input, output );\n\n            for( i = 0; i < 8; i++ )\n                output[i] = (unsigned char)( output[i] ^ iv[i] );\n\n            memcpy( iv, temp, 8 );\n\n            input  += 8;\n            output += 8;\n            length -= 8;\n        }\n    }\n    else\n    {\n        while( length > 0 )\n        {\n            for( i = 0; i < 8; i++ )\n                output[i] = (unsigned char)( input[i] ^ iv[i] );\n\n            mbedtls_xtea_crypt_ecb( ctx, mode, output, output );\n            memcpy( iv, output, 8 );\n\n            input  += 8;\n            output += 8;\n            length -= 8;\n        }\n    }\n\n    return( 0 );\n}\n#endif /* MBEDTLS_CIPHER_MODE_CBC */\n#endif /* !MBEDTLS_XTEA_ALT */\n\n#if defined(MBEDTLS_SELF_TEST)\n\n/*\n * XTEA tests vectors (non-official)\n */\n\nstatic const unsigned char xtea_test_key[6][16] =\n{\n   { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,\n     0x0c, 0x0d, 0x0e, 0x0f },\n   { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,\n     0x0c, 0x0d, 0x0e, 0x0f },\n   { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,\n     0x0c, 0x0d, 0x0e, 0x0f },\n   { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n     0x00, 0x00, 0x00, 0x00 },\n   { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n     0x00, 0x00, 0x00, 0x00 },\n   { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n     0x00, 0x00, 0x00, 0x00 }\n};\n\nstatic const unsigned char xtea_test_pt[6][8] =\n{\n    { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48 },\n    { 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41 },\n    { 0x5a, 0x5b, 0x6e, 0x27, 0x89, 0x48, 0xd7, 0x7f },\n    { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48 },\n    { 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41 },\n    { 0x70, 0xe1, 0x22, 0x5d, 0x6e, 0x4e, 0x76, 0x55 }\n};\n\nstatic const unsigned char xtea_test_ct[6][8] =\n{\n    { 0x49, 0x7d, 0xf3, 0xd0, 0x72, 0x61, 0x2c, 0xb5 },\n    { 0xe7, 0x8f, 0x2d, 0x13, 0x74, 0x43, 0x41, 0xd8 },\n    { 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41 },\n    { 0xa0, 0x39, 0x05, 0x89, 0xf8, 0xb8, 0xef, 0xa5 },\n    { 0xed, 0x23, 0x37, 0x5a, 0x82, 0x1a, 0x8c, 0x2d },\n    { 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41 }\n};\n\n/*\n * Checkup routine\n */\nint mbedtls_xtea_self_test( int verbose )\n{\n    int i, ret = 0;\n    unsigned char buf[8];\n    mbedtls_xtea_context ctx;\n\n    mbedtls_xtea_init( &ctx );\n    for( i = 0; i < 6; i++ )\n    {\n        if( verbose != 0 )\n            mbedtls_printf( \"  XTEA test #%d: \", i + 1 );\n\n        memcpy( buf, xtea_test_pt[i], 8 );\n\n        mbedtls_xtea_setup( &ctx, xtea_test_key[i] );\n        mbedtls_xtea_crypt_ecb( &ctx, MBEDTLS_XTEA_ENCRYPT, buf, buf );\n\n        if( memcmp( buf, xtea_test_ct[i], 8 ) != 0 )\n        {\n            if( verbose != 0 )\n                mbedtls_printf( \"failed\\n\" );\n\n            ret = 1;\n            goto exit;\n        }\n\n        if( verbose != 0 )\n            mbedtls_printf( \"passed\\n\" );\n    }\n\n    if( verbose != 0 )\n        mbedtls_printf( \"\\n\" );\n\nexit:\n    mbedtls_xtea_free( &ctx );\n\n    return( ret );\n}\n\n#endif /* MBEDTLS_SELF_TEST */\n\n#endif /* MBEDTLS_XTEA_C */\n"
  },
  {
    "path": "jsb_build/websockets/test_server/src/main.go",
    "content": "package main\r\n\r\nimport (\r\n\t\"fmt\"\r\n\t\"net/http\"\r\n\t\"time\"\r\n\r\n\t\"github.com/gorilla/websocket\"\r\n)\r\n\r\nfunc homepageHandler(w http.ResponseWriter, r *http.Request) {\r\n\thttp.Error(w, \"does not exist\", 404)\r\n}\r\n\r\nfunc accept(conn *websocket.Conn) {\r\n\tfor {\r\n\t\ttp, msg, err := conn.ReadMessage()\r\n\t\tif err != nil {\r\n\t\t\tfmt.Printf(\"failed to read %v\", err)\r\n\t\t\tbreak\r\n\t\t}\r\n\t\terr = conn.WriteMessage(tp, msg)\r\n\t\tif err != nil {\r\n\t\t\tfmt.Printf(\"failed to write %v\", err)\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfunc main() {\r\n\toriginChecker := func(r *http.Request) bool {\r\n\t\treturn true\r\n\t}\r\n\tupgrader := websocket.Upgrader{\r\n\t\tCheckOrigin:      originChecker,\r\n\t\tHandshakeTimeout: time.Minute,\r\n\t}\r\n\thttp.HandleFunc(\"/websocket\", func(w http.ResponseWriter, r *http.Request) {\r\n\t\tconn, err := upgrader.Upgrade(w, r, nil)\r\n\t\tif err != nil {\r\n\t\t\tfmt.Printf(\"failed to upgrade %v\", r.RemoteAddr)\r\n\t\t\treturn\r\n\t\t}\r\n\t\tfmt.Printf(\"open %v\", r.RemoteAddr)\r\n\t\tgo accept(conn)\r\n\t})\r\n\thttp.HandleFunc(\"/\", homepageHandler)\r\n\tfmt.Printf(\"listening...\")\r\n\thttp.ListenAndServe(\":8080\", nil)\r\n}\r\n"
  },
  {
    "path": "jsb_build/websockets/unity_ws.c",
    "content": "\r\n#include \"unity_ws.h\"\r\n#include \"core/private.h\"\r\n\r\n#define ULWS_DEFAULT 0\r\n#define ULWS_USE_SSL 1\r\n#define ULWS_USE_SSL_ALLOW_SELFSIGNED 2\r\n\r\nULWS_EXTERNAL struct lws_context *ulws_create(const char *name, size_t len, lws_callback_function callback, size_t rx_buffer_size, size_t tx_packet_size)\r\n{\r\n\t// struct lws_protocols protocols[2];\r\n\t// memset(protocols, 0, sizeof(struct lws_protocols) * 2);\r\n\tstruct lws_protocols *protocols = lws_zalloc(sizeof(struct lws_protocols) * 2, \"lws_protocols\");\r\n\r\n\tchar *copyname = (char *)malloc(len + 1);\r\n\tmemcpy(copyname, name, len);\r\n\tcopyname[len] = '\\0';\r\n\r\n\tprotocols[0].name = copyname;\r\n\tprotocols[0].callback = callback;\r\n\tprotocols[0].per_session_data_size = 0;\r\n\tprotocols[0].rx_buffer_size = rx_buffer_size;\r\n\tprotocols[0].tx_packet_size = tx_packet_size;\r\n\r\n\tstruct lws_context_creation_info info;\r\n\tmemset(&info, 0, sizeof(struct lws_context_creation_info));\r\n\r\n\tinfo.port = CONTEXT_PORT_NO_LISTEN;\r\n\tinfo.protocols = protocols;\r\n\tinfo.gid = -1;\r\n\tinfo.uid = -1;\r\n\t// info.ws_ping_pong_interval = 5;\r\n\tinfo.user = protocols;\r\n\tstruct lws_context *context = lws_create_context(&info);\r\n\treturn context;\r\n}\r\n\r\nULWS_EXTERNAL int ulws_pre()\r\n{\r\n\treturn LWS_PRE;\r\n}\r\n\r\nULWS_EXTERNAL struct lws *ulws_connect(struct lws_context *context,\r\n\t\t\t\t\t\t\t\t\t   const char *protocol_names,\r\n\t\t\t\t\t\t\t\t\t   ulws_ssl_type ssl_type,\r\n\t\t\t\t\t\t\t\t\t   const char *host, const char *address, const char *path, int port)\r\n{\r\n\tstruct lws_client_connect_info i;\r\n\r\n\tmemset(&i, 0, sizeof(struct lws_client_connect_info));\r\n\r\n\ti.context = context;\r\n\ti.protocol = protocol_names;\r\n\tif (ssl_type == ULWS_DEFAULT)\r\n\t{\r\n\t\ti.ssl_connection = 0;\r\n\t}\r\n\telse\r\n\t{\r\n\t\ti.ssl_connection = LCCSCF_USE_SSL;\r\n\t\tif (ssl_type & ULWS_USE_SSL_ALLOW_SELFSIGNED)\r\n\t\t{\r\n\t\t\ti.ssl_connection |= LCCSCF_ALLOW_SELFSIGNED;\r\n\t\t}\r\n\t}\r\n\ti.address = address;\r\n\ti.host = host;\r\n\ti.path = path;\r\n\ti.port = port;\r\n\r\n\treturn lws_client_connect_via_info(&i);\r\n}\r\n\r\nULWS_EXTERNAL void ulws_destroy(struct lws_context *context)\r\n{\r\n\tstruct lws_protocols *protocols = (struct lws_protocols *)lws_context_user(context);\r\n\tlws_context_destroy(context);\r\n\tif (protocols) {\r\n\t\tlws_free(protocols[0].name);\r\n\t\tlws_free(protocols);\r\n\t}\r\n}\r\n"
  },
  {
    "path": "jsb_build/websockets/unity_ws.h",
    "content": "\r\n#include \"libwebsockets.h\"\r\n\r\n#if defined(WIN32) || defined(_WIN32)\r\n    #define ULWS_EXTERNAL_DECL extern __declspec(dllexport)\r\n    #define ULWS_EXTERNAL __declspec(dllexport)\r\n#else\r\n    #define ULWS_EXTERNAL_DECL extern\r\n    #define ULWS_EXTERNAL\r\n#endif\r\n\r\ntypedef int ulws_ssl_type;\r\n\r\nULWS_EXTERNAL_DECL int ulws_pre();\r\n\r\nULWS_EXTERNAL_DECL struct lws_context * ulws_create(const char *name, size_t len, lws_callback_function callback, size_t rx_buffer_size, size_t tx_packet_size);\r\n\r\nULWS_EXTERNAL_DECL void ulws_destroy(struct lws_context *context);\r\n\r\nULWS_EXTERNAL_DECL struct lws *ulws_connect(struct lws_context *context, \r\n                                    const char *protocol_names, \r\n                                    ulws_ssl_type ssl_type, \r\n                                    const char *host, const char *address, const char *path, int port);\r\n"
  },
  {
    "path": "jsb_build/websockets/zlib/adler32.c",
    "content": "/* adler32.c -- compute the Adler-32 checksum of a data stream\n * Copyright (C) 1995-2011, 2016 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* @(#) $Id$ */\n\n#include \"zutil.h\"\n\nlocal uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2));\n\n#define BASE 65521U     /* largest prime smaller than 65536 */\n#define NMAX 5552\n/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */\n\n#define DO1(buf,i)  {adler += (buf)[i]; sum2 += adler;}\n#define DO2(buf,i)  DO1(buf,i); DO1(buf,i+1);\n#define DO4(buf,i)  DO2(buf,i); DO2(buf,i+2);\n#define DO8(buf,i)  DO4(buf,i); DO4(buf,i+4);\n#define DO16(buf)   DO8(buf,0); DO8(buf,8);\n\n/* use NO_DIVIDE if your processor does not do division in hardware --\n   try it both ways to see which is faster */\n#ifdef NO_DIVIDE\n/* note that this assumes BASE is 65521, where 65536 % 65521 == 15\n   (thank you to John Reiser for pointing this out) */\n#  define CHOP(a) \\\n    do { \\\n        unsigned long tmp = a >> 16; \\\n        a &= 0xffffUL; \\\n        a += (tmp << 4) - tmp; \\\n    } while (0)\n#  define MOD28(a) \\\n    do { \\\n        CHOP(a); \\\n        if (a >= BASE) a -= BASE; \\\n    } while (0)\n#  define MOD(a) \\\n    do { \\\n        CHOP(a); \\\n        MOD28(a); \\\n    } while (0)\n#  define MOD63(a) \\\n    do { /* this assumes a is not negative */ \\\n        z_off64_t tmp = a >> 32; \\\n        a &= 0xffffffffL; \\\n        a += (tmp << 8) - (tmp << 5) + tmp; \\\n        tmp = a >> 16; \\\n        a &= 0xffffL; \\\n        a += (tmp << 4) - tmp; \\\n        tmp = a >> 16; \\\n        a &= 0xffffL; \\\n        a += (tmp << 4) - tmp; \\\n        if (a >= BASE) a -= BASE; \\\n    } while (0)\n#else\n#  define MOD(a) a %= BASE\n#  define MOD28(a) a %= BASE\n#  define MOD63(a) a %= BASE\n#endif\n\n/* ========================================================================= */\nuLong ZEXPORT adler32_z(adler, buf, len)\n    uLong adler;\n    const Bytef *buf;\n    z_size_t len;\n{\n    unsigned long sum2;\n    unsigned n;\n\n    /* split Adler-32 into component sums */\n    sum2 = (adler >> 16) & 0xffff;\n    adler &= 0xffff;\n\n    /* in case user likes doing a byte at a time, keep it fast */\n    if (len == 1) {\n        adler += buf[0];\n        if (adler >= BASE)\n            adler -= BASE;\n        sum2 += adler;\n        if (sum2 >= BASE)\n            sum2 -= BASE;\n        return adler | (sum2 << 16);\n    }\n\n    /* initial Adler-32 value (deferred check for len == 1 speed) */\n    if (buf == Z_NULL)\n        return 1L;\n\n    /* in case short lengths are provided, keep it somewhat fast */\n    if (len < 16) {\n        while (len--) {\n            adler += *buf++;\n            sum2 += adler;\n        }\n        if (adler >= BASE)\n            adler -= BASE;\n        MOD28(sum2);            /* only added so many BASE's */\n        return adler | (sum2 << 16);\n    }\n\n    /* do length NMAX blocks -- requires just one modulo operation */\n    while (len >= NMAX) {\n        len -= NMAX;\n        n = NMAX / 16;          /* NMAX is divisible by 16 */\n        do {\n            DO16(buf);          /* 16 sums unrolled */\n            buf += 16;\n        } while (--n);\n        MOD(adler);\n        MOD(sum2);\n    }\n\n    /* do remaining bytes (less than NMAX, still just one modulo) */\n    if (len) {                  /* avoid modulos if none remaining */\n        while (len >= 16) {\n            len -= 16;\n            DO16(buf);\n            buf += 16;\n        }\n        while (len--) {\n            adler += *buf++;\n            sum2 += adler;\n        }\n        MOD(adler);\n        MOD(sum2);\n    }\n\n    /* return recombined sums */\n    return adler | (sum2 << 16);\n}\n\n/* ========================================================================= */\nuLong ZEXPORT adler32(adler, buf, len)\n    uLong adler;\n    const Bytef *buf;\n    uInt len;\n{\n    return adler32_z(adler, buf, len);\n}\n\n/* ========================================================================= */\nlocal uLong adler32_combine_(adler1, adler2, len2)\n    uLong adler1;\n    uLong adler2;\n    z_off64_t len2;\n{\n    unsigned long sum1;\n    unsigned long sum2;\n    unsigned rem;\n\n    /* for negative len, return invalid adler32 as a clue for debugging */\n    if (len2 < 0)\n        return 0xffffffffUL;\n\n    /* the derivation of this formula is left as an exercise for the reader */\n    MOD63(len2);                /* assumes len2 >= 0 */\n    rem = (unsigned)len2;\n    sum1 = adler1 & 0xffff;\n    sum2 = rem * sum1;\n    MOD(sum2);\n    sum1 += (adler2 & 0xffff) + BASE - 1;\n    sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;\n    if (sum1 >= BASE) sum1 -= BASE;\n    if (sum1 >= BASE) sum1 -= BASE;\n    if (sum2 >= ((unsigned long)BASE << 1)) sum2 -= ((unsigned long)BASE << 1);\n    if (sum2 >= BASE) sum2 -= BASE;\n    return sum1 | (sum2 << 16);\n}\n\n/* ========================================================================= */\nuLong ZEXPORT adler32_combine(adler1, adler2, len2)\n    uLong adler1;\n    uLong adler2;\n    z_off_t len2;\n{\n    return adler32_combine_(adler1, adler2, len2);\n}\n\nuLong ZEXPORT adler32_combine64(adler1, adler2, len2)\n    uLong adler1;\n    uLong adler2;\n    z_off64_t len2;\n{\n    return adler32_combine_(adler1, adler2, len2);\n}\n"
  },
  {
    "path": "jsb_build/websockets/zlib/compress.c",
    "content": "/* compress.c -- compress a memory buffer\n * Copyright (C) 1995-2005, 2014, 2016 Jean-loup Gailly, Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* @(#) $Id$ */\n\n#define ZLIB_INTERNAL\n#include \"zlib.h\"\n\n/* ===========================================================================\n     Compresses the source buffer into the destination buffer. The level\n   parameter has the same meaning as in deflateInit.  sourceLen is the byte\n   length of the source buffer. Upon entry, destLen is the total size of the\n   destination buffer, which must be at least 0.1% larger than sourceLen plus\n   12 bytes. Upon exit, destLen is the actual size of the compressed buffer.\n\n     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_BUF_ERROR if there was not enough room in the output buffer,\n   Z_STREAM_ERROR if the level parameter is invalid.\n*/\nint ZEXPORT compress2 (dest, destLen, source, sourceLen, level)\n    Bytef *dest;\n    uLongf *destLen;\n    const Bytef *source;\n    uLong sourceLen;\n    int level;\n{\n    z_stream stream;\n    int err;\n    const uInt max = (uInt)-1;\n    uLong left;\n\n    left = *destLen;\n    *destLen = 0;\n\n    stream.zalloc = (alloc_func)0;\n    stream.zfree = (free_func)0;\n    stream.opaque = (voidpf)0;\n\n    err = deflateInit(&stream, level);\n    if (err != Z_OK) return err;\n\n    stream.next_out = dest;\n    stream.avail_out = 0;\n    stream.next_in = (z_const Bytef *)source;\n    stream.avail_in = 0;\n\n    do {\n        if (stream.avail_out == 0) {\n            stream.avail_out = left > (uLong)max ? max : (uInt)left;\n            left -= stream.avail_out;\n        }\n        if (stream.avail_in == 0) {\n            stream.avail_in = sourceLen > (uLong)max ? max : (uInt)sourceLen;\n            sourceLen -= stream.avail_in;\n        }\n        err = deflate(&stream, sourceLen ? Z_NO_FLUSH : Z_FINISH);\n    } while (err == Z_OK);\n\n    *destLen = stream.total_out;\n    deflateEnd(&stream);\n    return err == Z_STREAM_END ? Z_OK : err;\n}\n\n/* ===========================================================================\n */\nint ZEXPORT compress (dest, destLen, source, sourceLen)\n    Bytef *dest;\n    uLongf *destLen;\n    const Bytef *source;\n    uLong sourceLen;\n{\n    return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);\n}\n\n/* ===========================================================================\n     If the default memLevel or windowBits for deflateInit() is changed, then\n   this function needs to be updated.\n */\nuLong ZEXPORT compressBound (sourceLen)\n    uLong sourceLen;\n{\n    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +\n           (sourceLen >> 25) + 13;\n}\n"
  },
  {
    "path": "jsb_build/websockets/zlib/crc32.c",
    "content": "/* crc32.c -- compute the CRC-32 of a data stream\n * Copyright (C) 1995-2006, 2010, 2011, 2012, 2016 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n *\n * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster\n * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing\n * tables for updating the shift register in one step with three exclusive-ors\n * instead of four steps with four exclusive-ors.  This results in about a\n * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.\n */\n\n/* @(#) $Id$ */\n\n/*\n  Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore\n  protection on the static variables used to control the first-use generation\n  of the crc tables.  Therefore, if you #define DYNAMIC_CRC_TABLE, you should\n  first call get_crc_table() to initialize the tables before allowing more than\n  one thread to use crc32().\n\n  DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h.\n */\n\n#ifdef MAKECRCH\n#  include <stdio.h>\n#  ifndef DYNAMIC_CRC_TABLE\n#    define DYNAMIC_CRC_TABLE\n#  endif /* !DYNAMIC_CRC_TABLE */\n#endif /* MAKECRCH */\n\n#include \"zutil.h\"      /* for STDC and FAR definitions */\n\n/* Definitions for doing the crc four data bytes at a time. */\n#if !defined(NOBYFOUR) && defined(Z_U4)\n#  define BYFOUR\n#endif\n#ifdef BYFOUR\n   local unsigned long crc32_little OF((unsigned long,\n                        const unsigned char FAR *, z_size_t));\n   local unsigned long crc32_big OF((unsigned long,\n                        const unsigned char FAR *, z_size_t));\n#  define TBLS 8\n#else\n#  define TBLS 1\n#endif /* BYFOUR */\n\n/* Local functions for crc concatenation */\nlocal unsigned long gf2_matrix_times OF((unsigned long *mat,\n                                         unsigned long vec));\nlocal void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));\nlocal uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2));\n\n\n#ifdef DYNAMIC_CRC_TABLE\n\nlocal volatile int crc_table_empty = 1;\nlocal z_crc_t FAR crc_table[TBLS][256];\nlocal void make_crc_table OF((void));\n#ifdef MAKECRCH\n   local void write_table OF((FILE *, const z_crc_t FAR *));\n#endif /* MAKECRCH */\n/*\n  Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:\n  x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.\n\n  Polynomials over GF(2) are represented in binary, one bit per coefficient,\n  with the lowest powers in the most significant bit.  Then adding polynomials\n  is just exclusive-or, and multiplying a polynomial by x is a right shift by\n  one.  If we call the above polynomial p, and represent a byte as the\n  polynomial q, also with the lowest power in the most significant bit (so the\n  byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,\n  where a mod b means the remainder after dividing a by b.\n\n  This calculation is done using the shift-register method of multiplying and\n  taking the remainder.  The register is initialized to zero, and for each\n  incoming bit, x^32 is added mod p to the register if the bit is a one (where\n  x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by\n  x (which is shifting right by one and adding x^32 mod p if the bit shifted\n  out is a one).  We start with the highest power (least significant bit) of\n  q and repeat for all eight bits of q.\n\n  The first table is simply the CRC of all possible eight bit values.  This is\n  all the information needed to generate CRCs on data a byte at a time for all\n  combinations of CRC register values and incoming bytes.  The remaining tables\n  allow for word-at-a-time CRC calculation for both big-endian and little-\n  endian machines, where a word is four bytes.\n*/\nlocal void make_crc_table()\n{\n    z_crc_t c;\n    int n, k;\n    z_crc_t poly;                       /* polynomial exclusive-or pattern */\n    /* terms of polynomial defining this crc (except x^32): */\n    static volatile int first = 1;      /* flag to limit concurrent making */\n    static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};\n\n    /* See if another task is already doing this (not thread-safe, but better\n       than nothing -- significantly reduces duration of vulnerability in\n       case the advice about DYNAMIC_CRC_TABLE is ignored) */\n    if (first) {\n        first = 0;\n\n        /* make exclusive-or pattern from polynomial (0xedb88320UL) */\n        poly = 0;\n        for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++)\n            poly |= (z_crc_t)1 << (31 - p[n]);\n\n        /* generate a crc for every 8-bit value */\n        for (n = 0; n < 256; n++) {\n            c = (z_crc_t)n;\n            for (k = 0; k < 8; k++)\n                c = c & 1 ? poly ^ (c >> 1) : c >> 1;\n            crc_table[0][n] = c;\n        }\n\n#ifdef BYFOUR\n        /* generate crc for each value followed by one, two, and three zeros,\n           and then the byte reversal of those as well as the first table */\n        for (n = 0; n < 256; n++) {\n            c = crc_table[0][n];\n            crc_table[4][n] = ZSWAP32(c);\n            for (k = 1; k < 4; k++) {\n                c = crc_table[0][c & 0xff] ^ (c >> 8);\n                crc_table[k][n] = c;\n                crc_table[k + 4][n] = ZSWAP32(c);\n            }\n        }\n#endif /* BYFOUR */\n\n        crc_table_empty = 0;\n    }\n    else {      /* not first */\n        /* wait for the other guy to finish (not efficient, but rare) */\n        while (crc_table_empty)\n            ;\n    }\n\n#ifdef MAKECRCH\n    /* write out CRC tables to crc32.h */\n    {\n        FILE *out;\n\n        out = fopen(\"crc32.h\", \"w\");\n        if (out == NULL) return;\n        fprintf(out, \"/* crc32.h -- tables for rapid CRC calculation\\n\");\n        fprintf(out, \" * Generated automatically by crc32.c\\n */\\n\\n\");\n        fprintf(out, \"local const z_crc_t FAR \");\n        fprintf(out, \"crc_table[TBLS][256] =\\n{\\n  {\\n\");\n        write_table(out, crc_table[0]);\n#  ifdef BYFOUR\n        fprintf(out, \"#ifdef BYFOUR\\n\");\n        for (k = 1; k < 8; k++) {\n            fprintf(out, \"  },\\n  {\\n\");\n            write_table(out, crc_table[k]);\n        }\n        fprintf(out, \"#endif\\n\");\n#  endif /* BYFOUR */\n        fprintf(out, \"  }\\n};\\n\");\n        fclose(out);\n    }\n#endif /* MAKECRCH */\n}\n\n#ifdef MAKECRCH\nlocal void write_table(out, table)\n    FILE *out;\n    const z_crc_t FAR *table;\n{\n    int n;\n\n    for (n = 0; n < 256; n++)\n        fprintf(out, \"%s0x%08lxUL%s\", n % 5 ? \"\" : \"    \",\n                (unsigned long)(table[n]),\n                n == 255 ? \"\\n\" : (n % 5 == 4 ? \",\\n\" : \", \"));\n}\n#endif /* MAKECRCH */\n\n#else /* !DYNAMIC_CRC_TABLE */\n/* ========================================================================\n * Tables of CRC-32s of all single-byte values, made by make_crc_table().\n */\n#include \"crc32.h\"\n#endif /* DYNAMIC_CRC_TABLE */\n\n/* =========================================================================\n * This function can be used by asm versions of crc32()\n */\nconst z_crc_t FAR * ZEXPORT get_crc_table()\n{\n#ifdef DYNAMIC_CRC_TABLE\n    if (crc_table_empty)\n        make_crc_table();\n#endif /* DYNAMIC_CRC_TABLE */\n    return (const z_crc_t FAR *)crc_table;\n}\n\n/* ========================================================================= */\n#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)\n#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1\n\n/* ========================================================================= */\nunsigned long ZEXPORT crc32_z(crc, buf, len)\n    unsigned long crc;\n    const unsigned char FAR *buf;\n    z_size_t len;\n{\n    if (buf == Z_NULL) return 0UL;\n\n#ifdef DYNAMIC_CRC_TABLE\n    if (crc_table_empty)\n        make_crc_table();\n#endif /* DYNAMIC_CRC_TABLE */\n\n#ifdef BYFOUR\n    if (sizeof(void *) == sizeof(ptrdiff_t)) {\n        z_crc_t endian;\n\n        endian = 1;\n        if (*((unsigned char *)(&endian)))\n            return crc32_little(crc, buf, len);\n        else\n            return crc32_big(crc, buf, len);\n    }\n#endif /* BYFOUR */\n    crc = crc ^ 0xffffffffUL;\n    while (len >= 8) {\n        DO8;\n        len -= 8;\n    }\n    if (len) do {\n        DO1;\n    } while (--len);\n    return crc ^ 0xffffffffUL;\n}\n\n/* ========================================================================= */\nunsigned long ZEXPORT crc32(crc, buf, len)\n    unsigned long crc;\n    const unsigned char FAR *buf;\n    uInt len;\n{\n    return crc32_z(crc, buf, len);\n}\n\n#ifdef BYFOUR\n\n/*\n   This BYFOUR code accesses the passed unsigned char * buffer with a 32-bit\n   integer pointer type. This violates the strict aliasing rule, where a\n   compiler can assume, for optimization purposes, that two pointers to\n   fundamentally different types won't ever point to the same memory. This can\n   manifest as a problem only if one of the pointers is written to. This code\n   only reads from those pointers. So long as this code remains isolated in\n   this compilation unit, there won't be a problem. For this reason, this code\n   should not be copied and pasted into a compilation unit in which other code\n   writes to the buffer that is passed to these routines.\n */\n\n/* ========================================================================= */\n#define DOLIT4 c ^= *buf4++; \\\n        c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \\\n            crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]\n#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4\n\n/* ========================================================================= */\nlocal unsigned long crc32_little(crc, buf, len)\n    unsigned long crc;\n    const unsigned char FAR *buf;\n    z_size_t len;\n{\n    register z_crc_t c;\n    register const z_crc_t FAR *buf4;\n\n    c = (z_crc_t)crc;\n    c = ~c;\n    while (len && ((ptrdiff_t)buf & 3)) {\n        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);\n        len--;\n    }\n\n    buf4 = (const z_crc_t FAR *)(const void FAR *)buf;\n    while (len >= 32) {\n        DOLIT32;\n        len -= 32;\n    }\n    while (len >= 4) {\n        DOLIT4;\n        len -= 4;\n    }\n    buf = (const unsigned char FAR *)buf4;\n\n    if (len) do {\n        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);\n    } while (--len);\n    c = ~c;\n    return (unsigned long)c;\n}\n\n/* ========================================================================= */\n#define DOBIG4 c ^= *buf4++; \\\n        c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \\\n            crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]\n#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4\n\n/* ========================================================================= */\nlocal unsigned long crc32_big(crc, buf, len)\n    unsigned long crc;\n    const unsigned char FAR *buf;\n    z_size_t len;\n{\n    register z_crc_t c;\n    register const z_crc_t FAR *buf4;\n\n    c = ZSWAP32((z_crc_t)crc);\n    c = ~c;\n    while (len && ((ptrdiff_t)buf & 3)) {\n        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);\n        len--;\n    }\n\n    buf4 = (const z_crc_t FAR *)(const void FAR *)buf;\n    while (len >= 32) {\n        DOBIG32;\n        len -= 32;\n    }\n    while (len >= 4) {\n        DOBIG4;\n        len -= 4;\n    }\n    buf = (const unsigned char FAR *)buf4;\n\n    if (len) do {\n        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);\n    } while (--len);\n    c = ~c;\n    return (unsigned long)(ZSWAP32(c));\n}\n\n#endif /* BYFOUR */\n\n#define GF2_DIM 32      /* dimension of GF(2) vectors (length of CRC) */\n\n/* ========================================================================= */\nlocal unsigned long gf2_matrix_times(mat, vec)\n    unsigned long *mat;\n    unsigned long vec;\n{\n    unsigned long sum;\n\n    sum = 0;\n    while (vec) {\n        if (vec & 1)\n            sum ^= *mat;\n        vec >>= 1;\n        mat++;\n    }\n    return sum;\n}\n\n/* ========================================================================= */\nlocal void gf2_matrix_square(square, mat)\n    unsigned long *square;\n    unsigned long *mat;\n{\n    int n;\n\n    for (n = 0; n < GF2_DIM; n++)\n        square[n] = gf2_matrix_times(mat, mat[n]);\n}\n\n/* ========================================================================= */\nlocal uLong crc32_combine_(crc1, crc2, len2)\n    uLong crc1;\n    uLong crc2;\n    z_off64_t len2;\n{\n    int n;\n    unsigned long row;\n    unsigned long even[GF2_DIM];    /* even-power-of-two zeros operator */\n    unsigned long odd[GF2_DIM];     /* odd-power-of-two zeros operator */\n\n    /* degenerate case (also disallow negative lengths) */\n    if (len2 <= 0)\n        return crc1;\n\n    /* put operator for one zero bit in odd */\n    odd[0] = 0xedb88320UL;          /* CRC-32 polynomial */\n    row = 1;\n    for (n = 1; n < GF2_DIM; n++) {\n        odd[n] = row;\n        row <<= 1;\n    }\n\n    /* put operator for two zero bits in even */\n    gf2_matrix_square(even, odd);\n\n    /* put operator for four zero bits in odd */\n    gf2_matrix_square(odd, even);\n\n    /* apply len2 zeros to crc1 (first square will put the operator for one\n       zero byte, eight zero bits, in even) */\n    do {\n        /* apply zeros operator for this bit of len2 */\n        gf2_matrix_square(even, odd);\n        if (len2 & 1)\n            crc1 = gf2_matrix_times(even, crc1);\n        len2 >>= 1;\n\n        /* if no more bits set, then done */\n        if (len2 == 0)\n            break;\n\n        /* another iteration of the loop with odd and even swapped */\n        gf2_matrix_square(odd, even);\n        if (len2 & 1)\n            crc1 = gf2_matrix_times(odd, crc1);\n        len2 >>= 1;\n\n        /* if no more bits set, then done */\n    } while (len2 != 0);\n\n    /* return combined crc */\n    crc1 ^= crc2;\n    return crc1;\n}\n\n/* ========================================================================= */\nuLong ZEXPORT crc32_combine(crc1, crc2, len2)\n    uLong crc1;\n    uLong crc2;\n    z_off_t len2;\n{\n    return crc32_combine_(crc1, crc2, len2);\n}\n\nuLong ZEXPORT crc32_combine64(crc1, crc2, len2)\n    uLong crc1;\n    uLong crc2;\n    z_off64_t len2;\n{\n    return crc32_combine_(crc1, crc2, len2);\n}\n"
  },
  {
    "path": "jsb_build/websockets/zlib/crc32.h",
    "content": "/* crc32.h -- tables for rapid CRC calculation\n * Generated automatically by crc32.c\n */\n\nlocal const z_crc_t FAR crc_table[TBLS][256] =\n{\n  {\n    0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,\n    0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,\n    0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,\n    0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,\n    0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,\n    0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,\n    0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,\n    0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,\n    0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,\n    0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,\n    0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,\n    0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,\n    0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,\n    0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,\n    0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,\n    0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,\n    0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,\n    0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,\n    0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,\n    0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,\n    0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,\n    0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,\n    0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,\n    0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,\n    0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,\n    0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,\n    0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,\n    0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,\n    0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,\n    0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,\n    0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,\n    0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,\n    0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,\n    0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,\n    0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,\n    0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,\n    0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,\n    0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,\n    0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,\n    0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,\n    0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,\n    0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,\n    0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,\n    0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,\n    0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,\n    0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,\n    0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,\n    0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,\n    0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,\n    0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,\n    0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,\n    0x2d02ef8dUL\n#ifdef BYFOUR\n  },\n  {\n    0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,\n    0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,\n    0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,\n    0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,\n    0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,\n    0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,\n    0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,\n    0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,\n    0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,\n    0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,\n    0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,\n    0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,\n    0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,\n    0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,\n    0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,\n    0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,\n    0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,\n    0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,\n    0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,\n    0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,\n    0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,\n    0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,\n    0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,\n    0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,\n    0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,\n    0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,\n    0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,\n    0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,\n    0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,\n    0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,\n    0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,\n    0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,\n    0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,\n    0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,\n    0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,\n    0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,\n    0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,\n    0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,\n    0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,\n    0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,\n    0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,\n    0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,\n    0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,\n    0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,\n    0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,\n    0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,\n    0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,\n    0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,\n    0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,\n    0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,\n    0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,\n    0x9324fd72UL\n  },\n  {\n    0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,\n    0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,\n    0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,\n    0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,\n    0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,\n    0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,\n    0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,\n    0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,\n    0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,\n    0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,\n    0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,\n    0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,\n    0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,\n    0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,\n    0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,\n    0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,\n    0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,\n    0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,\n    0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,\n    0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,\n    0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,\n    0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,\n    0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,\n    0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,\n    0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,\n    0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,\n    0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,\n    0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,\n    0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,\n    0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,\n    0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,\n    0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,\n    0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,\n    0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,\n    0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,\n    0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,\n    0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,\n    0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,\n    0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,\n    0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,\n    0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,\n    0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,\n    0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,\n    0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,\n    0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,\n    0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,\n    0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,\n    0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,\n    0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,\n    0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,\n    0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,\n    0xbe9834edUL\n  },\n  {\n    0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,\n    0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,\n    0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,\n    0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,\n    0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,\n    0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,\n    0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,\n    0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,\n    0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,\n    0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,\n    0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,\n    0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,\n    0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,\n    0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,\n    0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,\n    0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,\n    0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,\n    0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,\n    0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,\n    0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,\n    0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,\n    0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,\n    0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,\n    0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,\n    0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,\n    0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,\n    0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,\n    0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,\n    0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,\n    0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,\n    0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,\n    0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,\n    0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,\n    0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,\n    0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,\n    0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,\n    0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,\n    0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,\n    0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,\n    0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,\n    0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,\n    0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,\n    0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,\n    0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,\n    0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,\n    0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,\n    0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,\n    0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,\n    0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,\n    0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,\n    0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,\n    0xde0506f1UL\n  },\n  {\n    0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,\n    0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,\n    0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,\n    0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,\n    0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,\n    0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,\n    0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,\n    0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,\n    0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,\n    0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,\n    0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,\n    0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,\n    0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,\n    0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,\n    0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,\n    0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,\n    0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,\n    0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,\n    0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,\n    0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,\n    0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,\n    0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,\n    0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,\n    0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,\n    0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,\n    0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,\n    0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,\n    0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,\n    0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,\n    0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,\n    0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,\n    0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,\n    0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,\n    0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,\n    0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,\n    0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,\n    0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,\n    0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,\n    0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,\n    0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,\n    0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,\n    0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,\n    0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,\n    0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,\n    0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,\n    0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,\n    0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,\n    0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,\n    0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,\n    0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,\n    0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,\n    0x8def022dUL\n  },\n  {\n    0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,\n    0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,\n    0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,\n    0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,\n    0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,\n    0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,\n    0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,\n    0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,\n    0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,\n    0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,\n    0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,\n    0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,\n    0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,\n    0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,\n    0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,\n    0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,\n    0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,\n    0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,\n    0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,\n    0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,\n    0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,\n    0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,\n    0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,\n    0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,\n    0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,\n    0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,\n    0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,\n    0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,\n    0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,\n    0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,\n    0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,\n    0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,\n    0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,\n    0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,\n    0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,\n    0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,\n    0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,\n    0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,\n    0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,\n    0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,\n    0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,\n    0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,\n    0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,\n    0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,\n    0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,\n    0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,\n    0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,\n    0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,\n    0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,\n    0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,\n    0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,\n    0x72fd2493UL\n  },\n  {\n    0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,\n    0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,\n    0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,\n    0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,\n    0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,\n    0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,\n    0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,\n    0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,\n    0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,\n    0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,\n    0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,\n    0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,\n    0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,\n    0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,\n    0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,\n    0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,\n    0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,\n    0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,\n    0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,\n    0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,\n    0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,\n    0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,\n    0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,\n    0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,\n    0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,\n    0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,\n    0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,\n    0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,\n    0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,\n    0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,\n    0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,\n    0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,\n    0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,\n    0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,\n    0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,\n    0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,\n    0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,\n    0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,\n    0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,\n    0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,\n    0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,\n    0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,\n    0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,\n    0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,\n    0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,\n    0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,\n    0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,\n    0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,\n    0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,\n    0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,\n    0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,\n    0xed3498beUL\n  },\n  {\n    0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,\n    0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,\n    0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,\n    0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,\n    0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,\n    0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,\n    0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,\n    0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,\n    0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,\n    0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,\n    0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,\n    0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,\n    0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,\n    0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,\n    0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,\n    0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,\n    0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,\n    0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,\n    0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,\n    0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,\n    0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,\n    0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,\n    0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,\n    0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,\n    0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,\n    0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,\n    0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,\n    0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,\n    0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,\n    0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,\n    0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,\n    0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,\n    0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,\n    0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,\n    0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,\n    0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,\n    0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,\n    0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,\n    0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,\n    0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,\n    0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,\n    0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,\n    0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,\n    0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,\n    0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,\n    0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,\n    0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,\n    0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,\n    0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,\n    0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,\n    0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,\n    0xf10605deUL\n#endif\n  }\n};\n"
  },
  {
    "path": "jsb_build/websockets/zlib/deflate.c",
    "content": "/* deflate.c -- compress data using the deflation algorithm\n * Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/*\n *  ALGORITHM\n *\n *      The \"deflation\" process depends on being able to identify portions\n *      of the input text which are identical to earlier input (within a\n *      sliding window trailing behind the input currently being processed).\n *\n *      The most straightforward technique turns out to be the fastest for\n *      most input files: try all possible matches and select the longest.\n *      The key feature of this algorithm is that insertions into the string\n *      dictionary are very simple and thus fast, and deletions are avoided\n *      completely. Insertions are performed at each input character, whereas\n *      string matches are performed only when the previous match ends. So it\n *      is preferable to spend more time in matches to allow very fast string\n *      insertions and avoid deletions. The matching algorithm for small\n *      strings is inspired from that of Rabin & Karp. A brute force approach\n *      is used to find longer strings when a small match has been found.\n *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze\n *      (by Leonid Broukhis).\n *         A previous version of this file used a more sophisticated algorithm\n *      (by Fiala and Greene) which is guaranteed to run in linear amortized\n *      time, but has a larger average cost, uses more memory and is patented.\n *      However the F&G algorithm may be faster for some highly redundant\n *      files if the parameter max_chain_length (described below) is too large.\n *\n *  ACKNOWLEDGEMENTS\n *\n *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and\n *      I found it in 'freeze' written by Leonid Broukhis.\n *      Thanks to many people for bug reports and testing.\n *\n *  REFERENCES\n *\n *      Deutsch, L.P.,\"DEFLATE Compressed Data Format Specification\".\n *      Available in http://tools.ietf.org/html/rfc1951\n *\n *      A description of the Rabin and Karp algorithm is given in the book\n *         \"Algorithms\" by R. Sedgewick, Addison-Wesley, p252.\n *\n *      Fiala,E.R., and Greene,D.H.\n *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595\n *\n */\n\n/* @(#) $Id$ */\n\n#include \"deflate.h\"\n\nconst char deflate_copyright[] =\n   \" deflate 1.2.11 Copyright 1995-2017 Jean-loup Gailly and Mark Adler \";\n/*\n  If you use the zlib library in a product, an acknowledgment is welcome\n  in the documentation of your product. If for some reason you cannot\n  include such an acknowledgment, I would appreciate that you keep this\n  copyright string in the executable of your product.\n */\n\n/* ===========================================================================\n *  Function prototypes.\n */\ntypedef enum {\n    need_more,      /* block not completed, need more input or more output */\n    block_done,     /* block flush performed */\n    finish_started, /* finish started, need only more output at next deflate */\n    finish_done     /* finish done, accept no more input or output */\n} block_state;\n\ntypedef block_state (*compress_func) OF((deflate_state *s, int flush));\n/* Compression function. Returns the block state after the call. */\n\nlocal int deflateStateCheck      OF((z_streamp strm));\nlocal void slide_hash     OF((deflate_state *s));\nlocal void fill_window    OF((deflate_state *s));\nlocal block_state deflate_stored OF((deflate_state *s, int flush));\nlocal block_state deflate_fast   OF((deflate_state *s, int flush));\n#ifndef FASTEST\nlocal block_state deflate_slow   OF((deflate_state *s, int flush));\n#endif\nlocal block_state deflate_rle    OF((deflate_state *s, int flush));\nlocal block_state deflate_huff   OF((deflate_state *s, int flush));\nlocal void lm_init        OF((deflate_state *s));\nlocal void putShortMSB    OF((deflate_state *s, uInt b));\nlocal void flush_pending  OF((z_streamp strm));\nlocal unsigned read_buf   OF((z_streamp strm, Bytef *buf, unsigned size));\n#ifdef ASMV\n#  pragma message(\"Assembler code may have bugs -- use at your own risk\")\n      void match_init OF((void)); /* asm code initialization */\n      uInt longest_match  OF((deflate_state *s, IPos cur_match));\n#else\nlocal uInt longest_match  OF((deflate_state *s, IPos cur_match));\n#endif\n\n#ifdef ZLIB_DEBUG\nlocal  void check_match OF((deflate_state *s, IPos start, IPos match,\n                            int length));\n#endif\n\n/* ===========================================================================\n * Local data\n */\n\n#define NIL 0\n/* Tail of hash chains */\n\n#ifndef TOO_FAR\n#  define TOO_FAR 4096\n#endif\n/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\ntypedef struct config_s {\n   ush good_length; /* reduce lazy search above this match length */\n   ush max_lazy;    /* do not perform lazy search above this match length */\n   ush nice_length; /* quit search above this match length */\n   ush max_chain;\n   compress_func func;\n} config;\n\n#ifdef FASTEST\nlocal const config configuration_table[2] = {\n/*      good lazy nice chain */\n/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */\n/* 1 */ {4,    4,  8,    4, deflate_fast}}; /* max speed, no lazy matches */\n#else\nlocal const config configuration_table[10] = {\n/*      good lazy nice chain */\n/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */\n/* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */\n/* 2 */ {4,    5, 16,    8, deflate_fast},\n/* 3 */ {4,    6, 32,   32, deflate_fast},\n\n/* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */\n/* 5 */ {8,   16, 32,   32, deflate_slow},\n/* 6 */ {8,   16, 128, 128, deflate_slow},\n/* 7 */ {8,   32, 128, 256, deflate_slow},\n/* 8 */ {32, 128, 258, 1024, deflate_slow},\n/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */\n#endif\n\n/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4\n * For deflate_fast() (levels <= 3) good is ignored and lazy has a different\n * meaning.\n */\n\n/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */\n#define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))\n\n/* ===========================================================================\n * Update a hash value with the given input byte\n * IN  assertion: all calls to UPDATE_HASH are made with consecutive input\n *    characters, so that a running hash key can be computed from the previous\n *    key instead of complete recalculation each time.\n */\n#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)\n\n\n/* ===========================================================================\n * Insert string str in the dictionary and set match_head to the previous head\n * of the hash chain (the most recent string with same hash key). Return\n * the previous length of the hash chain.\n * If this file is compiled with -DFASTEST, the compression level is forced\n * to 1, and no hash chains are maintained.\n * IN  assertion: all calls to INSERT_STRING are made with consecutive input\n *    characters and the first MIN_MATCH bytes of str are valid (except for\n *    the last MIN_MATCH-1 bytes of the input file).\n */\n#ifdef FASTEST\n#define INSERT_STRING(s, str, match_head) \\\n   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \\\n    match_head = s->head[s->ins_h], \\\n    s->head[s->ins_h] = (Pos)(str))\n#else\n#define INSERT_STRING(s, str, match_head) \\\n   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \\\n    match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \\\n    s->head[s->ins_h] = (Pos)(str))\n#endif\n\n/* ===========================================================================\n * Initialize the hash table (avoiding 64K overflow for 16 bit systems).\n * prev[] will be initialized on the fly.\n */\n#define CLEAR_HASH(s) \\\n    s->head[s->hash_size-1] = NIL; \\\n    zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));\n\n/* ===========================================================================\n * Slide the hash table when sliding the window down (could be avoided with 32\n * bit values at the expense of memory usage). We slide even when level == 0 to\n * keep the hash table consistent if we switch back to level > 0 later.\n */\nlocal void slide_hash(s)\n    deflate_state *s;\n{\n    unsigned n, m;\n    Posf *p;\n    uInt wsize = s->w_size;\n\n    n = s->hash_size;\n    p = &s->head[n];\n    do {\n        m = *--p;\n        *p = (Pos)(m >= wsize ? m - wsize : NIL);\n    } while (--n);\n    n = wsize;\n#ifndef FASTEST\n    p = &s->prev[n];\n    do {\n        m = *--p;\n        *p = (Pos)(m >= wsize ? m - wsize : NIL);\n        /* If n is not on any hash chain, prev[n] is garbage but\n         * its value will never be used.\n         */\n    } while (--n);\n#endif\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateInit_(strm, level, version, stream_size)\n    z_streamp strm;\n    int level;\n    const char *version;\n    int stream_size;\n{\n    return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,\n                         Z_DEFAULT_STRATEGY, version, stream_size);\n    /* To do: ignore strm->next_in if we use it as window */\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,\n                  version, stream_size)\n    z_streamp strm;\n    int  level;\n    int  method;\n    int  windowBits;\n    int  memLevel;\n    int  strategy;\n    const char *version;\n    int stream_size;\n{\n    deflate_state *s;\n    int wrap = 1;\n    static const char my_version[] = ZLIB_VERSION;\n\n    ushf *overlay;\n    /* We overlay pending_buf and d_buf+l_buf. This works since the average\n     * output size for (length,distance) codes is <= 24 bits.\n     */\n\n    if (version == Z_NULL || version[0] != my_version[0] ||\n        stream_size != sizeof(z_stream)) {\n        return Z_VERSION_ERROR;\n    }\n    if (strm == Z_NULL) return Z_STREAM_ERROR;\n\n    strm->msg = Z_NULL;\n    if (strm->zalloc == (alloc_func)0) {\n#ifdef Z_SOLO\n        return Z_STREAM_ERROR;\n#else\n        strm->zalloc = zcalloc;\n        strm->opaque = (voidpf)0;\n#endif\n    }\n    if (strm->zfree == (free_func)0)\n#ifdef Z_SOLO\n        return Z_STREAM_ERROR;\n#else\n        strm->zfree = zcfree;\n#endif\n\n#ifdef FASTEST\n    if (level != 0) level = 1;\n#else\n    if (level == Z_DEFAULT_COMPRESSION) level = 6;\n#endif\n\n    if (windowBits < 0) { /* suppress zlib wrapper */\n        wrap = 0;\n        windowBits = -windowBits;\n    }\n#ifdef GZIP\n    else if (windowBits > 15) {\n        wrap = 2;       /* write gzip wrapper instead */\n        windowBits -= 16;\n    }\n#endif\n    if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||\n        windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n        strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) {\n        return Z_STREAM_ERROR;\n    }\n    if (windowBits == 8) windowBits = 9;  /* until 256-byte window bug fixed */\n    s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));\n    if (s == Z_NULL) return Z_MEM_ERROR;\n    strm->state = (struct internal_state FAR *)s;\n    s->strm = strm;\n    s->status = INIT_STATE;     /* to pass state test in deflateReset() */\n\n    s->wrap = wrap;\n    s->gzhead = Z_NULL;\n    s->w_bits = (uInt)windowBits;\n    s->w_size = 1 << s->w_bits;\n    s->w_mask = s->w_size - 1;\n\n    s->hash_bits = (uInt)memLevel + 7;\n    s->hash_size = 1 << s->hash_bits;\n    s->hash_mask = s->hash_size - 1;\n    s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);\n\n    s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));\n    s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));\n    s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));\n\n    s->high_water = 0;      /* nothing written to s->window yet */\n\n    s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n    overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n    s->pending_buf = (uchf *) overlay;\n    s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);\n\n    if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||\n        s->pending_buf == Z_NULL) {\n        s->status = FINISH_STATE;\n        strm->msg = ERR_MSG(Z_MEM_ERROR);\n        deflateEnd (strm);\n        return Z_MEM_ERROR;\n    }\n    s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n    s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n\n    s->level = level;\n    s->strategy = strategy;\n    s->method = (Byte)method;\n\n    return deflateReset(strm);\n}\n\n/* =========================================================================\n * Check for a valid deflate stream state. Return 0 if ok, 1 if not.\n */\nlocal int deflateStateCheck (strm)\n    z_streamp strm;\n{\n    deflate_state *s;\n    if (strm == Z_NULL ||\n        strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)\n        return 1;\n    s = strm->state;\n    if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE &&\n#ifdef GZIP\n                                           s->status != GZIP_STATE &&\n#endif\n                                           s->status != EXTRA_STATE &&\n                                           s->status != NAME_STATE &&\n                                           s->status != COMMENT_STATE &&\n                                           s->status != HCRC_STATE &&\n                                           s->status != BUSY_STATE &&\n                                           s->status != FINISH_STATE))\n        return 1;\n    return 0;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)\n    z_streamp strm;\n    const Bytef *dictionary;\n    uInt  dictLength;\n{\n    deflate_state *s;\n    uInt str, n;\n    int wrap;\n    unsigned avail;\n    z_const unsigned char *next;\n\n    if (deflateStateCheck(strm) || dictionary == Z_NULL)\n        return Z_STREAM_ERROR;\n    s = strm->state;\n    wrap = s->wrap;\n    if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)\n        return Z_STREAM_ERROR;\n\n    /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n    if (wrap == 1)\n        strm->adler = adler32(strm->adler, dictionary, dictLength);\n    s->wrap = 0;                    /* avoid computing Adler-32 in read_buf */\n\n    /* if dictionary would fill window, just replace the history */\n    if (dictLength >= s->w_size) {\n        if (wrap == 0) {            /* already empty otherwise */\n            CLEAR_HASH(s);\n            s->strstart = 0;\n            s->block_start = 0L;\n            s->insert = 0;\n        }\n        dictionary += dictLength - s->w_size;  /* use the tail */\n        dictLength = s->w_size;\n    }\n\n    /* insert dictionary into window and hash */\n    avail = strm->avail_in;\n    next = strm->next_in;\n    strm->avail_in = dictLength;\n    strm->next_in = (z_const Bytef *)dictionary;\n    fill_window(s);\n    while (s->lookahead >= MIN_MATCH) {\n        str = s->strstart;\n        n = s->lookahead - (MIN_MATCH-1);\n        do {\n            UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);\n#ifndef FASTEST\n            s->prev[str & s->w_mask] = s->head[s->ins_h];\n#endif\n            s->head[s->ins_h] = (Pos)str;\n            str++;\n        } while (--n);\n        s->strstart = str;\n        s->lookahead = MIN_MATCH-1;\n        fill_window(s);\n    }\n    s->strstart += s->lookahead;\n    s->block_start = (long)s->strstart;\n    s->insert = s->lookahead;\n    s->lookahead = 0;\n    s->match_length = s->prev_length = MIN_MATCH-1;\n    s->match_available = 0;\n    strm->next_in = next;\n    strm->avail_in = avail;\n    s->wrap = wrap;\n    return Z_OK;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateGetDictionary (strm, dictionary, dictLength)\n    z_streamp strm;\n    Bytef *dictionary;\n    uInt  *dictLength;\n{\n    deflate_state *s;\n    uInt len;\n\n    if (deflateStateCheck(strm))\n        return Z_STREAM_ERROR;\n    s = strm->state;\n    len = s->strstart + s->lookahead;\n    if (len > s->w_size)\n        len = s->w_size;\n    if (dictionary != Z_NULL && len)\n        zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);\n    if (dictLength != Z_NULL)\n        *dictLength = len;\n    return Z_OK;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateResetKeep (strm)\n    z_streamp strm;\n{\n    deflate_state *s;\n\n    if (deflateStateCheck(strm)) {\n        return Z_STREAM_ERROR;\n    }\n\n    strm->total_in = strm->total_out = 0;\n    strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */\n    strm->data_type = Z_UNKNOWN;\n\n    s = (deflate_state *)strm->state;\n    s->pending = 0;\n    s->pending_out = s->pending_buf;\n\n    if (s->wrap < 0) {\n        s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */\n    }\n    s->status =\n#ifdef GZIP\n        s->wrap == 2 ? GZIP_STATE :\n#endif\n        s->wrap ? INIT_STATE : BUSY_STATE;\n    strm->adler =\n#ifdef GZIP\n        s->wrap == 2 ? crc32(0L, Z_NULL, 0) :\n#endif\n        adler32(0L, Z_NULL, 0);\n    s->last_flush = Z_NO_FLUSH;\n\n    _tr_init(s);\n\n    return Z_OK;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateReset (strm)\n    z_streamp strm;\n{\n    int ret;\n\n    ret = deflateResetKeep(strm);\n    if (ret == Z_OK)\n        lm_init(strm->state);\n    return ret;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateSetHeader (strm, head)\n    z_streamp strm;\n    gz_headerp head;\n{\n    if (deflateStateCheck(strm) || strm->state->wrap != 2)\n        return Z_STREAM_ERROR;\n    strm->state->gzhead = head;\n    return Z_OK;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflatePending (strm, pending, bits)\n    unsigned *pending;\n    int *bits;\n    z_streamp strm;\n{\n    if (deflateStateCheck(strm)) return Z_STREAM_ERROR;\n    if (pending != Z_NULL)\n        *pending = strm->state->pending;\n    if (bits != Z_NULL)\n        *bits = strm->state->bi_valid;\n    return Z_OK;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflatePrime (strm, bits, value)\n    z_streamp strm;\n    int bits;\n    int value;\n{\n    deflate_state *s;\n    int put;\n\n    if (deflateStateCheck(strm)) return Z_STREAM_ERROR;\n    s = strm->state;\n    if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3))\n        return Z_BUF_ERROR;\n    do {\n        put = Buf_size - s->bi_valid;\n        if (put > bits)\n            put = bits;\n        s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);\n        s->bi_valid += put;\n        _tr_flush_bits(s);\n        value >>= put;\n        bits -= put;\n    } while (bits);\n    return Z_OK;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateParams(strm, level, strategy)\n    z_streamp strm;\n    int level;\n    int strategy;\n{\n    deflate_state *s;\n    compress_func func;\n\n    if (deflateStateCheck(strm)) return Z_STREAM_ERROR;\n    s = strm->state;\n\n#ifdef FASTEST\n    if (level != 0) level = 1;\n#else\n    if (level == Z_DEFAULT_COMPRESSION) level = 6;\n#endif\n    if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {\n        return Z_STREAM_ERROR;\n    }\n    func = configuration_table[s->level].func;\n\n    if ((strategy != s->strategy || func != configuration_table[level].func) &&\n        s->high_water) {\n        /* Flush the last buffer: */\n        int err = deflate(strm, Z_BLOCK);\n        if (err == Z_STREAM_ERROR)\n            return err;\n        if (strm->avail_out == 0)\n            return Z_BUF_ERROR;\n    }\n    if (s->level != level) {\n        if (s->level == 0 && s->matches != 0) {\n            if (s->matches == 1)\n                slide_hash(s);\n            else\n                CLEAR_HASH(s);\n            s->matches = 0;\n        }\n        s->level = level;\n        s->max_lazy_match   = configuration_table[level].max_lazy;\n        s->good_match       = configuration_table[level].good_length;\n        s->nice_match       = configuration_table[level].nice_length;\n        s->max_chain_length = configuration_table[level].max_chain;\n    }\n    s->strategy = strategy;\n    return Z_OK;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)\n    z_streamp strm;\n    int good_length;\n    int max_lazy;\n    int nice_length;\n    int max_chain;\n{\n    deflate_state *s;\n\n    if (deflateStateCheck(strm)) return Z_STREAM_ERROR;\n    s = strm->state;\n    s->good_match = (uInt)good_length;\n    s->max_lazy_match = (uInt)max_lazy;\n    s->nice_match = nice_length;\n    s->max_chain_length = (uInt)max_chain;\n    return Z_OK;\n}\n\n/* =========================================================================\n * For the default windowBits of 15 and memLevel of 8, this function returns\n * a close to exact, as well as small, upper bound on the compressed size.\n * They are coded as constants here for a reason--if the #define's are\n * changed, then this function needs to be changed as well.  The return\n * value for 15 and 8 only works for those exact settings.\n *\n * For any setting other than those defaults for windowBits and memLevel,\n * the value returned is a conservative worst case for the maximum expansion\n * resulting from using fixed blocks instead of stored blocks, which deflate\n * can emit on compressed data for some combinations of the parameters.\n *\n * This function could be more sophisticated to provide closer upper bounds for\n * every combination of windowBits and memLevel.  But even the conservative\n * upper bound of about 14% expansion does not seem onerous for output buffer\n * allocation.\n */\nuLong ZEXPORT deflateBound(strm, sourceLen)\n    z_streamp strm;\n    uLong sourceLen;\n{\n    deflate_state *s;\n    uLong complen, wraplen;\n\n    /* conservative upper bound for compressed data */\n    complen = sourceLen +\n              ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;\n\n    /* if can't get parameters, return conservative bound plus zlib wrapper */\n    if (deflateStateCheck(strm))\n        return complen + 6;\n\n    /* compute wrapper length */\n    s = strm->state;\n    switch (s->wrap) {\n    case 0:                                 /* raw deflate */\n        wraplen = 0;\n        break;\n    case 1:                                 /* zlib wrapper */\n        wraplen = 6 + (s->strstart ? 4 : 0);\n        break;\n#ifdef GZIP\n    case 2:                                 /* gzip wrapper */\n        wraplen = 18;\n        if (s->gzhead != Z_NULL) {          /* user-supplied gzip header */\n            Bytef *str;\n            if (s->gzhead->extra != Z_NULL)\n                wraplen += 2 + s->gzhead->extra_len;\n            str = s->gzhead->name;\n            if (str != Z_NULL)\n                do {\n                    wraplen++;\n                } while (*str++);\n            str = s->gzhead->comment;\n            if (str != Z_NULL)\n                do {\n                    wraplen++;\n                } while (*str++);\n            if (s->gzhead->hcrc)\n                wraplen += 2;\n        }\n        break;\n#endif\n    default:                                /* for compiler happiness */\n        wraplen = 6;\n    }\n\n    /* if not default parameters, return conservative bound */\n    if (s->w_bits != 15 || s->hash_bits != 8 + 7)\n        return complen + wraplen;\n\n    /* default settings: return tight bound for that case */\n    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +\n           (sourceLen >> 25) + 13 - 6 + wraplen;\n}\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nlocal void putShortMSB (s, b)\n    deflate_state *s;\n    uInt b;\n{\n    put_byte(s, (Byte)(b >> 8));\n    put_byte(s, (Byte)(b & 0xff));\n}\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output, except for\n * some deflate_stored() output, goes through this function so some\n * applications may wish to modify it to avoid allocating a large\n * strm->next_out buffer and copying into it. (See also read_buf()).\n */\nlocal void flush_pending(strm)\n    z_streamp strm;\n{\n    unsigned len;\n    deflate_state *s = strm->state;\n\n    _tr_flush_bits(s);\n    len = s->pending;\n    if (len > strm->avail_out) len = strm->avail_out;\n    if (len == 0) return;\n\n    zmemcpy(strm->next_out, s->pending_out, len);\n    strm->next_out  += len;\n    s->pending_out  += len;\n    strm->total_out += len;\n    strm->avail_out -= len;\n    s->pending      -= len;\n    if (s->pending == 0) {\n        s->pending_out = s->pending_buf;\n    }\n}\n\n/* ===========================================================================\n * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].\n */\n#define HCRC_UPDATE(beg) \\\n    do { \\\n        if (s->gzhead->hcrc && s->pending > (beg)) \\\n            strm->adler = crc32(strm->adler, s->pending_buf + (beg), \\\n                                s->pending - (beg)); \\\n    } while (0)\n\n/* ========================================================================= */\nint ZEXPORT deflate (strm, flush)\n    z_streamp strm;\n    int flush;\n{\n    int old_flush; /* value of flush param for previous deflate call */\n    deflate_state *s;\n\n    if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {\n        return Z_STREAM_ERROR;\n    }\n    s = strm->state;\n\n    if (strm->next_out == Z_NULL ||\n        (strm->avail_in != 0 && strm->next_in == Z_NULL) ||\n        (s->status == FINISH_STATE && flush != Z_FINISH)) {\n        ERR_RETURN(strm, Z_STREAM_ERROR);\n    }\n    if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);\n\n    old_flush = s->last_flush;\n    s->last_flush = flush;\n\n    /* Flush as much pending output as possible */\n    if (s->pending != 0) {\n        flush_pending(strm);\n        if (strm->avail_out == 0) {\n            /* Since avail_out is 0, deflate will be called again with\n             * more output space, but possibly with both pending and\n             * avail_in equal to zero. There won't be anything to do,\n             * but this is not an error situation so make sure we\n             * return OK instead of BUF_ERROR at next call of deflate:\n             */\n            s->last_flush = -1;\n            return Z_OK;\n        }\n\n    /* Make sure there is something to do and avoid duplicate consecutive\n     * flushes. For repeated and useless calls with Z_FINISH, we keep\n     * returning Z_STREAM_END instead of Z_BUF_ERROR.\n     */\n    } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&\n               flush != Z_FINISH) {\n        ERR_RETURN(strm, Z_BUF_ERROR);\n    }\n\n    /* User must not provide more input after the first FINISH: */\n    if (s->status == FINISH_STATE && strm->avail_in != 0) {\n        ERR_RETURN(strm, Z_BUF_ERROR);\n    }\n\n    /* Write the header */\n    if (s->status == INIT_STATE) {\n        /* zlib header */\n        uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;\n        uInt level_flags;\n\n        if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)\n            level_flags = 0;\n        else if (s->level < 6)\n            level_flags = 1;\n        else if (s->level == 6)\n            level_flags = 2;\n        else\n            level_flags = 3;\n        header |= (level_flags << 6);\n        if (s->strstart != 0) header |= PRESET_DICT;\n        header += 31 - (header % 31);\n\n        putShortMSB(s, header);\n\n        /* Save the adler32 of the preset dictionary: */\n        if (s->strstart != 0) {\n            putShortMSB(s, (uInt)(strm->adler >> 16));\n            putShortMSB(s, (uInt)(strm->adler & 0xffff));\n        }\n        strm->adler = adler32(0L, Z_NULL, 0);\n        s->status = BUSY_STATE;\n\n        /* Compression must start with an empty pending buffer */\n        flush_pending(strm);\n        if (s->pending != 0) {\n            s->last_flush = -1;\n            return Z_OK;\n        }\n    }\n#ifdef GZIP\n    if (s->status == GZIP_STATE) {\n        /* gzip header */\n        strm->adler = crc32(0L, Z_NULL, 0);\n        put_byte(s, 31);\n        put_byte(s, 139);\n        put_byte(s, 8);\n        if (s->gzhead == Z_NULL) {\n            put_byte(s, 0);\n            put_byte(s, 0);\n            put_byte(s, 0);\n            put_byte(s, 0);\n            put_byte(s, 0);\n            put_byte(s, s->level == 9 ? 2 :\n                     (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?\n                      4 : 0));\n            put_byte(s, OS_CODE);\n            s->status = BUSY_STATE;\n\n            /* Compression must start with an empty pending buffer */\n            flush_pending(strm);\n            if (s->pending != 0) {\n                s->last_flush = -1;\n                return Z_OK;\n            }\n        }\n        else {\n            put_byte(s, (s->gzhead->text ? 1 : 0) +\n                     (s->gzhead->hcrc ? 2 : 0) +\n                     (s->gzhead->extra == Z_NULL ? 0 : 4) +\n                     (s->gzhead->name == Z_NULL ? 0 : 8) +\n                     (s->gzhead->comment == Z_NULL ? 0 : 16)\n                     );\n            put_byte(s, (Byte)(s->gzhead->time & 0xff));\n            put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));\n            put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));\n            put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));\n            put_byte(s, s->level == 9 ? 2 :\n                     (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?\n                      4 : 0));\n            put_byte(s, s->gzhead->os & 0xff);\n            if (s->gzhead->extra != Z_NULL) {\n                put_byte(s, s->gzhead->extra_len & 0xff);\n                put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);\n            }\n            if (s->gzhead->hcrc)\n                strm->adler = crc32(strm->adler, s->pending_buf,\n                                    s->pending);\n            s->gzindex = 0;\n            s->status = EXTRA_STATE;\n        }\n    }\n    if (s->status == EXTRA_STATE) {\n        if (s->gzhead->extra != Z_NULL) {\n            ulg beg = s->pending;   /* start of bytes to update crc */\n            uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex;\n            while (s->pending + left > s->pending_buf_size) {\n                uInt copy = s->pending_buf_size - s->pending;\n                zmemcpy(s->pending_buf + s->pending,\n                        s->gzhead->extra + s->gzindex, copy);\n                s->pending = s->pending_buf_size;\n                HCRC_UPDATE(beg);\n                s->gzindex += copy;\n                flush_pending(strm);\n                if (s->pending != 0) {\n                    s->last_flush = -1;\n                    return Z_OK;\n                }\n                beg = 0;\n                left -= copy;\n            }\n            zmemcpy(s->pending_buf + s->pending,\n                    s->gzhead->extra + s->gzindex, left);\n            s->pending += left;\n            HCRC_UPDATE(beg);\n            s->gzindex = 0;\n        }\n        s->status = NAME_STATE;\n    }\n    if (s->status == NAME_STATE) {\n        if (s->gzhead->name != Z_NULL) {\n            ulg beg = s->pending;   /* start of bytes to update crc */\n            int val;\n            do {\n                if (s->pending == s->pending_buf_size) {\n                    HCRC_UPDATE(beg);\n                    flush_pending(strm);\n                    if (s->pending != 0) {\n                        s->last_flush = -1;\n                        return Z_OK;\n                    }\n                    beg = 0;\n                }\n                val = s->gzhead->name[s->gzindex++];\n                put_byte(s, val);\n            } while (val != 0);\n            HCRC_UPDATE(beg);\n            s->gzindex = 0;\n        }\n        s->status = COMMENT_STATE;\n    }\n    if (s->status == COMMENT_STATE) {\n        if (s->gzhead->comment != Z_NULL) {\n            ulg beg = s->pending;   /* start of bytes to update crc */\n            int val;\n            do {\n                if (s->pending == s->pending_buf_size) {\n                    HCRC_UPDATE(beg);\n                    flush_pending(strm);\n                    if (s->pending != 0) {\n                        s->last_flush = -1;\n                        return Z_OK;\n                    }\n                    beg = 0;\n                }\n                val = s->gzhead->comment[s->gzindex++];\n                put_byte(s, val);\n            } while (val != 0);\n            HCRC_UPDATE(beg);\n        }\n        s->status = HCRC_STATE;\n    }\n    if (s->status == HCRC_STATE) {\n        if (s->gzhead->hcrc) {\n            if (s->pending + 2 > s->pending_buf_size) {\n                flush_pending(strm);\n                if (s->pending != 0) {\n                    s->last_flush = -1;\n                    return Z_OK;\n                }\n            }\n            put_byte(s, (Byte)(strm->adler & 0xff));\n            put_byte(s, (Byte)((strm->adler >> 8) & 0xff));\n            strm->adler = crc32(0L, Z_NULL, 0);\n        }\n        s->status = BUSY_STATE;\n\n        /* Compression must start with an empty pending buffer */\n        flush_pending(strm);\n        if (s->pending != 0) {\n            s->last_flush = -1;\n            return Z_OK;\n        }\n    }\n#endif\n\n    /* Start a new block or continue the current one.\n     */\n    if (strm->avail_in != 0 || s->lookahead != 0 ||\n        (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {\n        block_state bstate;\n\n        bstate = s->level == 0 ? deflate_stored(s, flush) :\n                 s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :\n                 s->strategy == Z_RLE ? deflate_rle(s, flush) :\n                 (*(configuration_table[s->level].func))(s, flush);\n\n        if (bstate == finish_started || bstate == finish_done) {\n            s->status = FINISH_STATE;\n        }\n        if (bstate == need_more || bstate == finish_started) {\n            if (strm->avail_out == 0) {\n                s->last_flush = -1; /* avoid BUF_ERROR next call, see above */\n            }\n            return Z_OK;\n            /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n             * of deflate should use the same flush parameter to make sure\n             * that the flush is complete. So we don't have to output an\n             * empty block here, this will be done at next call. This also\n             * ensures that for a very small output buffer, we emit at most\n             * one empty block.\n             */\n        }\n        if (bstate == block_done) {\n            if (flush == Z_PARTIAL_FLUSH) {\n                _tr_align(s);\n            } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */\n                _tr_stored_block(s, (char*)0, 0L, 0);\n                /* For a full flush, this empty block will be recognized\n                 * as a special marker by inflate_sync().\n                 */\n                if (flush == Z_FULL_FLUSH) {\n                    CLEAR_HASH(s);             /* forget history */\n                    if (s->lookahead == 0) {\n                        s->strstart = 0;\n                        s->block_start = 0L;\n                        s->insert = 0;\n                    }\n                }\n            }\n            flush_pending(strm);\n            if (strm->avail_out == 0) {\n              s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n              return Z_OK;\n            }\n        }\n    }\n\n    if (flush != Z_FINISH) return Z_OK;\n    if (s->wrap <= 0) return Z_STREAM_END;\n\n    /* Write the trailer */\n#ifdef GZIP\n    if (s->wrap == 2) {\n        put_byte(s, (Byte)(strm->adler & 0xff));\n        put_byte(s, (Byte)((strm->adler >> 8) & 0xff));\n        put_byte(s, (Byte)((strm->adler >> 16) & 0xff));\n        put_byte(s, (Byte)((strm->adler >> 24) & 0xff));\n        put_byte(s, (Byte)(strm->total_in & 0xff));\n        put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));\n        put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));\n        put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));\n    }\n    else\n#endif\n    {\n        putShortMSB(s, (uInt)(strm->adler >> 16));\n        putShortMSB(s, (uInt)(strm->adler & 0xffff));\n    }\n    flush_pending(strm);\n    /* If avail_out is zero, the application will call deflate again\n     * to flush the rest.\n     */\n    if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */\n    return s->pending != 0 ? Z_OK : Z_STREAM_END;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateEnd (strm)\n    z_streamp strm;\n{\n    int status;\n\n    if (deflateStateCheck(strm)) return Z_STREAM_ERROR;\n\n    status = strm->state->status;\n\n    /* Deallocate in reverse order of allocations: */\n    TRY_FREE(strm, strm->state->pending_buf);\n    TRY_FREE(strm, strm->state->head);\n    TRY_FREE(strm, strm->state->prev);\n    TRY_FREE(strm, strm->state->window);\n\n    ZFREE(strm, strm->state);\n    strm->state = Z_NULL;\n\n    return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;\n}\n\n/* =========================================================================\n * Copy the source state to the destination state.\n * To simplify the source, this is not supported for 16-bit MSDOS (which\n * doesn't have enough memory anyway to duplicate compression states).\n */\nint ZEXPORT deflateCopy (dest, source)\n    z_streamp dest;\n    z_streamp source;\n{\n#ifdef MAXSEG_64K\n    return Z_STREAM_ERROR;\n#else\n    deflate_state *ds;\n    deflate_state *ss;\n    ushf *overlay;\n\n\n    if (deflateStateCheck(source) || dest == Z_NULL) {\n        return Z_STREAM_ERROR;\n    }\n\n    ss = source->state;\n\n    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));\n\n    ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));\n    if (ds == Z_NULL) return Z_MEM_ERROR;\n    dest->state = (struct internal_state FAR *) ds;\n    zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));\n    ds->strm = dest;\n\n    ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));\n    ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));\n    ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));\n    overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);\n    ds->pending_buf = (uchf *) overlay;\n\n    if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||\n        ds->pending_buf == Z_NULL) {\n        deflateEnd (dest);\n        return Z_MEM_ERROR;\n    }\n    /* following zmemcpy do not work for 16-bit MSDOS */\n    zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));\n    zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));\n    zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));\n    zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);\n\n    ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);\n    ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);\n    ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;\n\n    ds->l_desc.dyn_tree = ds->dyn_ltree;\n    ds->d_desc.dyn_tree = ds->dyn_dtree;\n    ds->bl_desc.dyn_tree = ds->bl_tree;\n\n    return Z_OK;\n#endif /* MAXSEG_64K */\n}\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read.  All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->next_in buffer and copying from it.\n * (See also flush_pending()).\n */\nlocal unsigned read_buf(strm, buf, size)\n    z_streamp strm;\n    Bytef *buf;\n    unsigned size;\n{\n    unsigned len = strm->avail_in;\n\n    if (len > size) len = size;\n    if (len == 0) return 0;\n\n    strm->avail_in  -= len;\n\n    zmemcpy(buf, strm->next_in, len);\n    if (strm->state->wrap == 1) {\n        strm->adler = adler32(strm->adler, buf, len);\n    }\n#ifdef GZIP\n    else if (strm->state->wrap == 2) {\n        strm->adler = crc32(strm->adler, buf, len);\n    }\n#endif\n    strm->next_in  += len;\n    strm->total_in += len;\n\n    return len;\n}\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nlocal void lm_init (s)\n    deflate_state *s;\n{\n    s->window_size = (ulg)2L*s->w_size;\n\n    CLEAR_HASH(s);\n\n    /* Set the default configuration parameters:\n     */\n    s->max_lazy_match   = configuration_table[s->level].max_lazy;\n    s->good_match       = configuration_table[s->level].good_length;\n    s->nice_match       = configuration_table[s->level].nice_length;\n    s->max_chain_length = configuration_table[s->level].max_chain;\n\n    s->strstart = 0;\n    s->block_start = 0L;\n    s->lookahead = 0;\n    s->insert = 0;\n    s->match_length = s->prev_length = MIN_MATCH-1;\n    s->match_available = 0;\n    s->ins_h = 0;\n#ifndef FASTEST\n#ifdef ASMV\n    match_init(); /* initialize the asm code */\n#endif\n#endif\n}\n\n#ifndef FASTEST\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\n#ifndef ASMV\n/* For 80x86 and 680x0, an optimized version will be provided in match.asm or\n * match.S. The code will be functionally equivalent.\n */\nlocal uInt longest_match(s, cur_match)\n    deflate_state *s;\n    IPos cur_match;                             /* current match */\n{\n    unsigned chain_length = s->max_chain_length;/* max hash chain length */\n    register Bytef *scan = s->window + s->strstart; /* current string */\n    register Bytef *match;                      /* matched string */\n    register int len;                           /* length of current match */\n    int best_len = (int)s->prev_length;         /* best match length so far */\n    int nice_match = s->nice_match;             /* stop if match long enough */\n    IPos limit = s->strstart > (IPos)MAX_DIST(s) ?\n        s->strstart - (IPos)MAX_DIST(s) : NIL;\n    /* Stop when cur_match becomes <= limit. To simplify the code,\n     * we prevent matches with the string of window index 0.\n     */\n    Posf *prev = s->prev;\n    uInt wmask = s->w_mask;\n\n#ifdef UNALIGNED_OK\n    /* Compare two bytes at a time. Note: this is not always beneficial.\n     * Try with and without -DUNALIGNED_OK to check.\n     */\n    register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;\n    register ush scan_start = *(ushf*)scan;\n    register ush scan_end   = *(ushf*)(scan+best_len-1);\n#else\n    register Bytef *strend = s->window + s->strstart + MAX_MATCH;\n    register Byte scan_end1  = scan[best_len-1];\n    register Byte scan_end   = scan[best_len];\n#endif\n\n    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n     * It is easy to get rid of this optimization if necessary.\n     */\n    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n    /* Do not waste too much time if we already have a good match: */\n    if (s->prev_length >= s->good_match) {\n        chain_length >>= 2;\n    }\n    /* Do not look for matches beyond the end of the input. This is necessary\n     * to make deflate deterministic.\n     */\n    if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead;\n\n    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n    do {\n        Assert(cur_match < s->strstart, \"no future\");\n        match = s->window + cur_match;\n\n        /* Skip to next match if the match length cannot increase\n         * or if the match length is less than 2.  Note that the checks below\n         * for insufficient lookahead only occur occasionally for performance\n         * reasons.  Therefore uninitialized memory will be accessed, and\n         * conditional jumps will be made that depend on those values.\n         * However the length of the match is limited to the lookahead, so\n         * the output of deflate is not affected by the uninitialized values.\n         */\n#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)\n        /* This code assumes sizeof(unsigned short) == 2. Do not use\n         * UNALIGNED_OK if your compiler uses a different size.\n         */\n        if (*(ushf*)(match+best_len-1) != scan_end ||\n            *(ushf*)match != scan_start) continue;\n\n        /* It is not necessary to compare scan[2] and match[2] since they are\n         * always equal when the other bytes match, given that the hash keys\n         * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at\n         * strstart+3, +5, ... up to strstart+257. We check for insufficient\n         * lookahead only every 4th comparison; the 128th check will be made\n         * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is\n         * necessary to put more guard bytes at the end of the window, or\n         * to check more often for insufficient lookahead.\n         */\n        Assert(scan[2] == match[2], \"scan[2]?\");\n        scan++, match++;\n        do {\n        } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&\n                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&\n                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&\n                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&\n                 scan < strend);\n        /* The funny \"do {}\" generates better code on most compilers */\n\n        /* Here, scan <= window+strstart+257 */\n        Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n        if (*scan == *match) scan++;\n\n        len = (MAX_MATCH - 1) - (int)(strend-scan);\n        scan = strend - (MAX_MATCH-1);\n\n#else /* UNALIGNED_OK */\n\n        if (match[best_len]   != scan_end  ||\n            match[best_len-1] != scan_end1 ||\n            *match            != *scan     ||\n            *++match          != scan[1])      continue;\n\n        /* The check at best_len-1 can be removed because it will be made\n         * again later. (This heuristic is not always a win.)\n         * It is not necessary to compare scan[2] and match[2] since they\n         * are always equal when the other bytes match, given that\n         * the hash keys are equal and that HASH_BITS >= 8.\n         */\n        scan += 2, match++;\n        Assert(*scan == *match, \"match[2]?\");\n\n        /* We check for insufficient lookahead only every 8th comparison;\n         * the 256th check will be made at strstart+258.\n         */\n        do {\n        } while (*++scan == *++match && *++scan == *++match &&\n                 *++scan == *++match && *++scan == *++match &&\n                 *++scan == *++match && *++scan == *++match &&\n                 *++scan == *++match && *++scan == *++match &&\n                 scan < strend);\n\n        Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n        len = MAX_MATCH - (int)(strend - scan);\n        scan = strend - MAX_MATCH;\n\n#endif /* UNALIGNED_OK */\n\n        if (len > best_len) {\n            s->match_start = cur_match;\n            best_len = len;\n            if (len >= nice_match) break;\n#ifdef UNALIGNED_OK\n            scan_end = *(ushf*)(scan+best_len-1);\n#else\n            scan_end1  = scan[best_len-1];\n            scan_end   = scan[best_len];\n#endif\n        }\n    } while ((cur_match = prev[cur_match & wmask]) > limit\n             && --chain_length != 0);\n\n    if ((uInt)best_len <= s->lookahead) return (uInt)best_len;\n    return s->lookahead;\n}\n#endif /* ASMV */\n\n#else /* FASTEST */\n\n/* ---------------------------------------------------------------------------\n * Optimized version for FASTEST only\n */\nlocal uInt longest_match(s, cur_match)\n    deflate_state *s;\n    IPos cur_match;                             /* current match */\n{\n    register Bytef *scan = s->window + s->strstart; /* current string */\n    register Bytef *match;                       /* matched string */\n    register int len;                           /* length of current match */\n    register Bytef *strend = s->window + s->strstart + MAX_MATCH;\n\n    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n     * It is easy to get rid of this optimization if necessary.\n     */\n    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n    Assert(cur_match < s->strstart, \"no future\");\n\n    match = s->window + cur_match;\n\n    /* Return failure if the match length is less than 2:\n     */\n    if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;\n\n    /* The check at best_len-1 can be removed because it will be made\n     * again later. (This heuristic is not always a win.)\n     * It is not necessary to compare scan[2] and match[2] since they\n     * are always equal when the other bytes match, given that\n     * the hash keys are equal and that HASH_BITS >= 8.\n     */\n    scan += 2, match += 2;\n    Assert(*scan == *match, \"match[2]?\");\n\n    /* We check for insufficient lookahead only every 8th comparison;\n     * the 256th check will be made at strstart+258.\n     */\n    do {\n    } while (*++scan == *++match && *++scan == *++match &&\n             *++scan == *++match && *++scan == *++match &&\n             *++scan == *++match && *++scan == *++match &&\n             *++scan == *++match && *++scan == *++match &&\n             scan < strend);\n\n    Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n    len = MAX_MATCH - (int)(strend - scan);\n\n    if (len < MIN_MATCH) return MIN_MATCH - 1;\n\n    s->match_start = cur_match;\n    return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;\n}\n\n#endif /* FASTEST */\n\n#ifdef ZLIB_DEBUG\n\n#define EQUAL 0\n/* result of memcmp for equal strings */\n\n/* ===========================================================================\n * Check that the match at match_start is indeed a match.\n */\nlocal void check_match(s, start, match, length)\n    deflate_state *s;\n    IPos start, match;\n    int length;\n{\n    /* check that the match is indeed a match */\n    if (zmemcmp(s->window + match,\n                s->window + start, length) != EQUAL) {\n        fprintf(stderr, \" start %u, match %u, length %d\\n\",\n                start, match, length);\n        do {\n            fprintf(stderr, \"%c%c\", s->window[match++], s->window[start++]);\n        } while (--length != 0);\n        z_error(\"invalid match\");\n    }\n    if (z_verbose > 1) {\n        fprintf(stderr,\"\\\\[%d,%d]\", start-match, length);\n        do { putc(s->window[start++], stderr); } while (--length != 0);\n    }\n}\n#else\n#  define check_match(s, start, match, length)\n#endif /* ZLIB_DEBUG */\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n *    At least one byte has been read, or avail_in == 0; reads are\n *    performed for at least two bytes (required for the zip translate_eol\n *    option -- not supported here).\n */\nlocal void fill_window(s)\n    deflate_state *s;\n{\n    unsigned n;\n    unsigned more;    /* Amount of free space at the end of the window. */\n    uInt wsize = s->w_size;\n\n    Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n    do {\n        more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);\n\n        /* Deal with !@#$% 64K limit: */\n        if (sizeof(int) <= 2) {\n            if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n                more = wsize;\n\n            } else if (more == (unsigned)(-1)) {\n                /* Very unlikely, but possible on 16 bit machine if\n                 * strstart == 0 && lookahead == 1 (input done a byte at time)\n                 */\n                more--;\n            }\n        }\n\n        /* If the window is almost full and there is insufficient lookahead,\n         * move the upper half to the lower one to make room in the upper half.\n         */\n        if (s->strstart >= wsize+MAX_DIST(s)) {\n\n            zmemcpy(s->window, s->window+wsize, (unsigned)wsize - more);\n            s->match_start -= wsize;\n            s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */\n            s->block_start -= (long) wsize;\n            slide_hash(s);\n            more += wsize;\n        }\n        if (s->strm->avail_in == 0) break;\n\n        /* If there was no sliding:\n         *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n         *    more == window_size - lookahead - strstart\n         * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n         * => more >= window_size - 2*WSIZE + 2\n         * In the BIG_MEM or MMAP case (not yet supported),\n         *   window_size == input_size + MIN_LOOKAHEAD  &&\n         *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n         * Otherwise, window_size == 2*WSIZE so more >= 2.\n         * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n         */\n        Assert(more >= 2, \"more < 2\");\n\n        n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);\n        s->lookahead += n;\n\n        /* Initialize the hash value now that we have some input: */\n        if (s->lookahead + s->insert >= MIN_MATCH) {\n            uInt str = s->strstart - s->insert;\n            s->ins_h = s->window[str];\n            UPDATE_HASH(s, s->ins_h, s->window[str + 1]);\n#if MIN_MATCH != 3\n            Call UPDATE_HASH() MIN_MATCH-3 more times\n#endif\n            while (s->insert) {\n                UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);\n#ifndef FASTEST\n                s->prev[str & s->w_mask] = s->head[s->ins_h];\n#endif\n                s->head[s->ins_h] = (Pos)str;\n                str++;\n                s->insert--;\n                if (s->lookahead + s->insert < MIN_MATCH)\n                    break;\n            }\n        }\n        /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n         * but this is not important since only literal bytes will be emitted.\n         */\n\n    } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);\n\n    /* If the WIN_INIT bytes after the end of the current data have never been\n     * written, then zero those bytes in order to avoid memory check reports of\n     * the use of uninitialized (or uninitialised as Julian writes) bytes by\n     * the longest match routines.  Update the high water mark for the next\n     * time through here.  WIN_INIT is set to MAX_MATCH since the longest match\n     * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n     */\n    if (s->high_water < s->window_size) {\n        ulg curr = s->strstart + (ulg)(s->lookahead);\n        ulg init;\n\n        if (s->high_water < curr) {\n            /* Previous high water mark below current data -- zero WIN_INIT\n             * bytes or up to end of window, whichever is less.\n             */\n            init = s->window_size - curr;\n            if (init > WIN_INIT)\n                init = WIN_INIT;\n            zmemzero(s->window + curr, (unsigned)init);\n            s->high_water = curr + init;\n        }\n        else if (s->high_water < (ulg)curr + WIN_INIT) {\n            /* High water mark at or above current data, but below current data\n             * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n             * to end of window, whichever is less.\n             */\n            init = (ulg)curr + WIN_INIT - s->high_water;\n            if (init > s->window_size - s->high_water)\n                init = s->window_size - s->high_water;\n            zmemzero(s->window + s->high_water, (unsigned)init);\n            s->high_water += init;\n        }\n    }\n\n    Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n           \"not enough room for search\");\n}\n\n/* ===========================================================================\n * Flush the current block, with given end-of-file flag.\n * IN assertion: strstart is set to the end of the current match.\n */\n#define FLUSH_BLOCK_ONLY(s, last) { \\\n   _tr_flush_block(s, (s->block_start >= 0L ? \\\n                   (charf *)&s->window[(unsigned)s->block_start] : \\\n                   (charf *)Z_NULL), \\\n                (ulg)((long)s->strstart - s->block_start), \\\n                (last)); \\\n   s->block_start = s->strstart; \\\n   flush_pending(s->strm); \\\n   Tracev((stderr,\"[FLUSH]\")); \\\n}\n\n/* Same but force premature exit if necessary. */\n#define FLUSH_BLOCK(s, last) { \\\n   FLUSH_BLOCK_ONLY(s, last); \\\n   if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \\\n}\n\n/* Maximum stored block length in deflate format (not including header). */\n#define MAX_STORED 65535\n\n/* Minimum of a and b. */\n#define MIN(a, b) ((a) > (b) ? (b) : (a))\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n *\n * In case deflateParams() is used to later switch to a non-zero compression\n * level, s->matches (otherwise unused when storing) keeps track of the number\n * of hash table slides to perform. If s->matches is 1, then one hash table\n * slide will be done when switching. If s->matches is 2, the maximum value\n * allowed here, then the hash table will be cleared, since two or more slides\n * is the same as a clear.\n *\n * deflate_stored() is written to minimize the number of times an input byte is\n * copied. It is most efficient with large input and output buffers, which\n * maximizes the opportunites to have a single copy from next_in to next_out.\n */\nlocal block_state deflate_stored(s, flush)\n    deflate_state *s;\n    int flush;\n{\n    /* Smallest worthy block size when not flushing or finishing. By default\n     * this is 32K. This can be as small as 507 bytes for memLevel == 1. For\n     * large input and output buffers, the stored block size will be larger.\n     */\n    unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);\n\n    /* Copy as many min_block or larger stored blocks directly to next_out as\n     * possible. If flushing, copy the remaining available input to next_out as\n     * stored blocks, if there is enough space.\n     */\n    unsigned len, left, have, last = 0;\n    unsigned used = s->strm->avail_in;\n    do {\n        /* Set len to the maximum size block that we can copy directly with the\n         * available input data and output space. Set left to how much of that\n         * would be copied from what's left in the window.\n         */\n        len = MAX_STORED;       /* maximum deflate stored block length */\n        have = (s->bi_valid + 42) >> 3;         /* number of header bytes */\n        if (s->strm->avail_out < have)          /* need room for header */\n            break;\n            /* maximum stored block length that will fit in avail_out: */\n        have = s->strm->avail_out - have;\n        left = s->strstart - s->block_start;    /* bytes left in window */\n        if (len > (ulg)left + s->strm->avail_in)\n            len = left + s->strm->avail_in;     /* limit len to the input */\n        if (len > have)\n            len = have;                         /* limit len to the output */\n\n        /* If the stored block would be less than min_block in length, or if\n         * unable to copy all of the available input when flushing, then try\n         * copying to the window and the pending buffer instead. Also don't\n         * write an empty block when flushing -- deflate() does that.\n         */\n        if (len < min_block && ((len == 0 && flush != Z_FINISH) ||\n                                flush == Z_NO_FLUSH ||\n                                len != left + s->strm->avail_in))\n            break;\n\n        /* Make a dummy stored block in pending to get the header bytes,\n         * including any pending bits. This also updates the debugging counts.\n         */\n        last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;\n        _tr_stored_block(s, (char *)0, 0L, last);\n\n        /* Replace the lengths in the dummy stored block with len. */\n        s->pending_buf[s->pending - 4] = len;\n        s->pending_buf[s->pending - 3] = len >> 8;\n        s->pending_buf[s->pending - 2] = ~len;\n        s->pending_buf[s->pending - 1] = ~len >> 8;\n\n        /* Write the stored block header bytes. */\n        flush_pending(s->strm);\n\n#ifdef ZLIB_DEBUG\n        /* Update debugging counts for the data about to be copied. */\n        s->compressed_len += len << 3;\n        s->bits_sent += len << 3;\n#endif\n\n        /* Copy uncompressed bytes from the window to next_out. */\n        if (left) {\n            if (left > len)\n                left = len;\n            zmemcpy(s->strm->next_out, s->window + s->block_start, left);\n            s->strm->next_out += left;\n            s->strm->avail_out -= left;\n            s->strm->total_out += left;\n            s->block_start += left;\n            len -= left;\n        }\n\n        /* Copy uncompressed bytes directly from next_in to next_out, updating\n         * the check value.\n         */\n        if (len) {\n            read_buf(s->strm, s->strm->next_out, len);\n            s->strm->next_out += len;\n            s->strm->avail_out -= len;\n            s->strm->total_out += len;\n        }\n    } while (last == 0);\n\n    /* Update the sliding window with the last s->w_size bytes of the copied\n     * data, or append all of the copied data to the existing window if less\n     * than s->w_size bytes were copied. Also update the number of bytes to\n     * insert in the hash tables, in the event that deflateParams() switches to\n     * a non-zero compression level.\n     */\n    used -= s->strm->avail_in;      /* number of input bytes directly copied */\n    if (used) {\n        /* If any input was used, then no unused input remains in the window,\n         * therefore s->block_start == s->strstart.\n         */\n        if (used >= s->w_size) {    /* supplant the previous history */\n            s->matches = 2;         /* clear hash */\n            zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);\n            s->strstart = s->w_size;\n        }\n        else {\n            if (s->window_size - s->strstart <= used) {\n                /* Slide the window down. */\n                s->strstart -= s->w_size;\n                zmemcpy(s->window, s->window + s->w_size, s->strstart);\n                if (s->matches < 2)\n                    s->matches++;   /* add a pending slide_hash() */\n            }\n            zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);\n            s->strstart += used;\n        }\n        s->block_start = s->strstart;\n        s->insert += MIN(used, s->w_size - s->insert);\n    }\n    if (s->high_water < s->strstart)\n        s->high_water = s->strstart;\n\n    /* If the last block was written to next_out, then done. */\n    if (last)\n        return finish_done;\n\n    /* If flushing and all input has been consumed, then done. */\n    if (flush != Z_NO_FLUSH && flush != Z_FINISH &&\n        s->strm->avail_in == 0 && (long)s->strstart == s->block_start)\n        return block_done;\n\n    /* Fill the window with any remaining input. */\n    have = s->window_size - s->strstart - 1;\n    if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) {\n        /* Slide the window down. */\n        s->block_start -= s->w_size;\n        s->strstart -= s->w_size;\n        zmemcpy(s->window, s->window + s->w_size, s->strstart);\n        if (s->matches < 2)\n            s->matches++;           /* add a pending slide_hash() */\n        have += s->w_size;          /* more space now */\n    }\n    if (have > s->strm->avail_in)\n        have = s->strm->avail_in;\n    if (have) {\n        read_buf(s->strm, s->window + s->strstart, have);\n        s->strstart += have;\n    }\n    if (s->high_water < s->strstart)\n        s->high_water = s->strstart;\n\n    /* There was not enough avail_out to write a complete worthy or flushed\n     * stored block to next_out. Write a stored block to pending instead, if we\n     * have enough input for a worthy block, or if flushing and there is enough\n     * room for the remaining input as a stored block in the pending buffer.\n     */\n    have = (s->bi_valid + 42) >> 3;         /* number of header bytes */\n        /* maximum stored block length that will fit in pending: */\n    have = MIN(s->pending_buf_size - have, MAX_STORED);\n    min_block = MIN(have, s->w_size);\n    left = s->strstart - s->block_start;\n    if (left >= min_block ||\n        ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH &&\n         s->strm->avail_in == 0 && left <= have)) {\n        len = MIN(left, have);\n        last = flush == Z_FINISH && s->strm->avail_in == 0 &&\n               len == left ? 1 : 0;\n        _tr_stored_block(s, (charf *)s->window + s->block_start, len, last);\n        s->block_start += len;\n        flush_pending(s->strm);\n    }\n\n    /* We've done all we can with the available input and output. */\n    return last ? finish_started : need_more;\n}\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nlocal block_state deflate_fast(s, flush)\n    deflate_state *s;\n    int flush;\n{\n    IPos hash_head;       /* head of the hash chain */\n    int bflush;           /* set if current block must be flushed */\n\n    for (;;) {\n        /* Make sure that we always have enough lookahead, except\n         * at the end of the input file. We need MAX_MATCH bytes\n         * for the next match, plus MIN_MATCH bytes to insert the\n         * string following the next match.\n         */\n        if (s->lookahead < MIN_LOOKAHEAD) {\n            fill_window(s);\n            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {\n                return need_more;\n            }\n            if (s->lookahead == 0) break; /* flush the current block */\n        }\n\n        /* Insert the string window[strstart .. strstart+2] in the\n         * dictionary, and set hash_head to the head of the hash chain:\n         */\n        hash_head = NIL;\n        if (s->lookahead >= MIN_MATCH) {\n            INSERT_STRING(s, s->strstart, hash_head);\n        }\n\n        /* Find the longest match, discarding those <= prev_length.\n         * At this point we have always match_length < MIN_MATCH\n         */\n        if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {\n            /* To simplify the code, we prevent matches with the string\n             * of window index 0 (in particular we have to avoid a match\n             * of the string with itself at the start of the input file).\n             */\n            s->match_length = longest_match (s, hash_head);\n            /* longest_match() sets match_start */\n        }\n        if (s->match_length >= MIN_MATCH) {\n            check_match(s, s->strstart, s->match_start, s->match_length);\n\n            _tr_tally_dist(s, s->strstart - s->match_start,\n                           s->match_length - MIN_MATCH, bflush);\n\n            s->lookahead -= s->match_length;\n\n            /* Insert new strings in the hash table only if the match length\n             * is not too large. This saves time but degrades compression.\n             */\n#ifndef FASTEST\n            if (s->match_length <= s->max_insert_length &&\n                s->lookahead >= MIN_MATCH) {\n                s->match_length--; /* string at strstart already in table */\n                do {\n                    s->strstart++;\n                    INSERT_STRING(s, s->strstart, hash_head);\n                    /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n                     * always MIN_MATCH bytes ahead.\n                     */\n                } while (--s->match_length != 0);\n                s->strstart++;\n            } else\n#endif\n            {\n                s->strstart += s->match_length;\n                s->match_length = 0;\n                s->ins_h = s->window[s->strstart];\n                UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);\n#if MIN_MATCH != 3\n                Call UPDATE_HASH() MIN_MATCH-3 more times\n#endif\n                /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n                 * matter since it will be recomputed at next deflate call.\n                 */\n            }\n        } else {\n            /* No match, output a literal byte */\n            Tracevv((stderr,\"%c\", s->window[s->strstart]));\n            _tr_tally_lit (s, s->window[s->strstart], bflush);\n            s->lookahead--;\n            s->strstart++;\n        }\n        if (bflush) FLUSH_BLOCK(s, 0);\n    }\n    s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;\n    if (flush == Z_FINISH) {\n        FLUSH_BLOCK(s, 1);\n        return finish_done;\n    }\n    if (s->last_lit)\n        FLUSH_BLOCK(s, 0);\n    return block_done;\n}\n\n#ifndef FASTEST\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nlocal block_state deflate_slow(s, flush)\n    deflate_state *s;\n    int flush;\n{\n    IPos hash_head;          /* head of hash chain */\n    int bflush;              /* set if current block must be flushed */\n\n    /* Process the input block. */\n    for (;;) {\n        /* Make sure that we always have enough lookahead, except\n         * at the end of the input file. We need MAX_MATCH bytes\n         * for the next match, plus MIN_MATCH bytes to insert the\n         * string following the next match.\n         */\n        if (s->lookahead < MIN_LOOKAHEAD) {\n            fill_window(s);\n            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {\n                return need_more;\n            }\n            if (s->lookahead == 0) break; /* flush the current block */\n        }\n\n        /* Insert the string window[strstart .. strstart+2] in the\n         * dictionary, and set hash_head to the head of the hash chain:\n         */\n        hash_head = NIL;\n        if (s->lookahead >= MIN_MATCH) {\n            INSERT_STRING(s, s->strstart, hash_head);\n        }\n\n        /* Find the longest match, discarding those <= prev_length.\n         */\n        s->prev_length = s->match_length, s->prev_match = s->match_start;\n        s->match_length = MIN_MATCH-1;\n\n        if (hash_head != NIL && s->prev_length < s->max_lazy_match &&\n            s->strstart - hash_head <= MAX_DIST(s)) {\n            /* To simplify the code, we prevent matches with the string\n             * of window index 0 (in particular we have to avoid a match\n             * of the string with itself at the start of the input file).\n             */\n            s->match_length = longest_match (s, hash_head);\n            /* longest_match() sets match_start */\n\n            if (s->match_length <= 5 && (s->strategy == Z_FILTERED\n#if TOO_FAR <= 32767\n                || (s->match_length == MIN_MATCH &&\n                    s->strstart - s->match_start > TOO_FAR)\n#endif\n                )) {\n\n                /* If prev_match is also MIN_MATCH, match_start is garbage\n                 * but we will ignore the current match anyway.\n                 */\n                s->match_length = MIN_MATCH-1;\n            }\n        }\n        /* If there was a match at the previous step and the current\n         * match is not better, output the previous match:\n         */\n        if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {\n            uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;\n            /* Do not insert strings in hash table beyond this. */\n\n            check_match(s, s->strstart-1, s->prev_match, s->prev_length);\n\n            _tr_tally_dist(s, s->strstart -1 - s->prev_match,\n                           s->prev_length - MIN_MATCH, bflush);\n\n            /* Insert in hash table all strings up to the end of the match.\n             * strstart-1 and strstart are already inserted. If there is not\n             * enough lookahead, the last two strings are not inserted in\n             * the hash table.\n             */\n            s->lookahead -= s->prev_length-1;\n            s->prev_length -= 2;\n            do {\n                if (++s->strstart <= max_insert) {\n                    INSERT_STRING(s, s->strstart, hash_head);\n                }\n            } while (--s->prev_length != 0);\n            s->match_available = 0;\n            s->match_length = MIN_MATCH-1;\n            s->strstart++;\n\n            if (bflush) FLUSH_BLOCK(s, 0);\n\n        } else if (s->match_available) {\n            /* If there was no match at the previous position, output a\n             * single literal. If there was a match but the current match\n             * is longer, truncate the previous match to a single literal.\n             */\n            Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n            _tr_tally_lit(s, s->window[s->strstart-1], bflush);\n            if (bflush) {\n                FLUSH_BLOCK_ONLY(s, 0);\n            }\n            s->strstart++;\n            s->lookahead--;\n            if (s->strm->avail_out == 0) return need_more;\n        } else {\n            /* There is no previous match to compare with, wait for\n             * the next step to decide.\n             */\n            s->match_available = 1;\n            s->strstart++;\n            s->lookahead--;\n        }\n    }\n    Assert (flush != Z_NO_FLUSH, \"no flush?\");\n    if (s->match_available) {\n        Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n        _tr_tally_lit(s, s->window[s->strstart-1], bflush);\n        s->match_available = 0;\n    }\n    s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;\n    if (flush == Z_FINISH) {\n        FLUSH_BLOCK(s, 1);\n        return finish_done;\n    }\n    if (s->last_lit)\n        FLUSH_BLOCK(s, 0);\n    return block_done;\n}\n#endif /* FASTEST */\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one.  Do not maintain a hash table.  (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nlocal block_state deflate_rle(s, flush)\n    deflate_state *s;\n    int flush;\n{\n    int bflush;             /* set if current block must be flushed */\n    uInt prev;              /* byte at distance one to match */\n    Bytef *scan, *strend;   /* scan goes up to strend for length of run */\n\n    for (;;) {\n        /* Make sure that we always have enough lookahead, except\n         * at the end of the input file. We need MAX_MATCH bytes\n         * for the longest run, plus one for the unrolled loop.\n         */\n        if (s->lookahead <= MAX_MATCH) {\n            fill_window(s);\n            if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {\n                return need_more;\n            }\n            if (s->lookahead == 0) break; /* flush the current block */\n        }\n\n        /* See how many times the previous byte repeats */\n        s->match_length = 0;\n        if (s->lookahead >= MIN_MATCH && s->strstart > 0) {\n            scan = s->window + s->strstart - 1;\n            prev = *scan;\n            if (prev == *++scan && prev == *++scan && prev == *++scan) {\n                strend = s->window + s->strstart + MAX_MATCH;\n                do {\n                } while (prev == *++scan && prev == *++scan &&\n                         prev == *++scan && prev == *++scan &&\n                         prev == *++scan && prev == *++scan &&\n                         prev == *++scan && prev == *++scan &&\n                         scan < strend);\n                s->match_length = MAX_MATCH - (uInt)(strend - scan);\n                if (s->match_length > s->lookahead)\n                    s->match_length = s->lookahead;\n            }\n            Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n        }\n\n        /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n        if (s->match_length >= MIN_MATCH) {\n            check_match(s, s->strstart, s->strstart - 1, s->match_length);\n\n            _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);\n\n            s->lookahead -= s->match_length;\n            s->strstart += s->match_length;\n            s->match_length = 0;\n        } else {\n            /* No match, output a literal byte */\n            Tracevv((stderr,\"%c\", s->window[s->strstart]));\n            _tr_tally_lit (s, s->window[s->strstart], bflush);\n            s->lookahead--;\n            s->strstart++;\n        }\n        if (bflush) FLUSH_BLOCK(s, 0);\n    }\n    s->insert = 0;\n    if (flush == Z_FINISH) {\n        FLUSH_BLOCK(s, 1);\n        return finish_done;\n    }\n    if (s->last_lit)\n        FLUSH_BLOCK(s, 0);\n    return block_done;\n}\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nlocal block_state deflate_huff(s, flush)\n    deflate_state *s;\n    int flush;\n{\n    int bflush;             /* set if current block must be flushed */\n\n    for (;;) {\n        /* Make sure that we have a literal to write. */\n        if (s->lookahead == 0) {\n            fill_window(s);\n            if (s->lookahead == 0) {\n                if (flush == Z_NO_FLUSH)\n                    return need_more;\n                break;      /* flush the current block */\n            }\n        }\n\n        /* Output a literal byte */\n        s->match_length = 0;\n        Tracevv((stderr,\"%c\", s->window[s->strstart]));\n        _tr_tally_lit (s, s->window[s->strstart], bflush);\n        s->lookahead--;\n        s->strstart++;\n        if (bflush) FLUSH_BLOCK(s, 0);\n    }\n    s->insert = 0;\n    if (flush == Z_FINISH) {\n        FLUSH_BLOCK(s, 1);\n        return finish_done;\n    }\n    if (s->last_lit)\n        FLUSH_BLOCK(s, 0);\n    return block_done;\n}\n"
  },
  {
    "path": "jsb_build/websockets/zlib/deflate.h",
    "content": "/* deflate.h -- internal compression state\n * Copyright (C) 1995-2016 Jean-loup Gailly\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* WARNING: this file should *not* be used by applications. It is\n   part of the implementation of the compression library and is\n   subject to change. Applications should only use zlib.h.\n */\n\n/* @(#) $Id$ */\n\n#ifndef DEFLATE_H\n#define DEFLATE_H\n\n#include \"zutil.h\"\n\n/* define NO_GZIP when compiling if you want to disable gzip header and\n   trailer creation by deflate().  NO_GZIP would be used to avoid linking in\n   the crc code when it is not needed.  For shared libraries, gzip encoding\n   should be left enabled. */\n#ifndef NO_GZIP\n#  define GZIP\n#endif\n\n/* ===========================================================================\n * Internal compression state.\n */\n\n#define LENGTH_CODES 29\n/* number of length codes, not counting the special END_BLOCK code */\n\n#define LITERALS  256\n/* number of literal bytes 0..255 */\n\n#define L_CODES (LITERALS+1+LENGTH_CODES)\n/* number of Literal or Length codes, including the END_BLOCK code */\n\n#define D_CODES   30\n/* number of distance codes */\n\n#define BL_CODES  19\n/* number of codes used to transfer the bit lengths */\n\n#define HEAP_SIZE (2*L_CODES+1)\n/* maximum heap size */\n\n#define MAX_BITS 15\n/* All codes must not exceed MAX_BITS bits */\n\n#define Buf_size 16\n/* size of bit buffer in bi_buf */\n\n#define INIT_STATE    42    /* zlib header -> BUSY_STATE */\n#ifdef GZIP\n#  define GZIP_STATE  57    /* gzip header -> BUSY_STATE | EXTRA_STATE */\n#endif\n#define EXTRA_STATE   69    /* gzip extra block -> NAME_STATE */\n#define NAME_STATE    73    /* gzip file name -> COMMENT_STATE */\n#define COMMENT_STATE 91    /* gzip comment -> HCRC_STATE */\n#define HCRC_STATE   103    /* gzip header CRC -> BUSY_STATE */\n#define BUSY_STATE   113    /* deflate -> FINISH_STATE */\n#define FINISH_STATE 666    /* stream complete */\n/* Stream status */\n\n\n/* Data structure describing a single value and its code string. */\ntypedef struct ct_data_s {\n    union {\n        ush  freq;       /* frequency count */\n        ush  code;       /* bit string */\n    } fc;\n    union {\n        ush  dad;        /* father node in Huffman tree */\n        ush  len;        /* length of bit string */\n    } dl;\n} FAR ct_data;\n\n#define Freq fc.freq\n#define Code fc.code\n#define Dad  dl.dad\n#define Len  dl.len\n\ntypedef struct static_tree_desc_s  static_tree_desc;\n\ntypedef struct tree_desc_s {\n    ct_data *dyn_tree;           /* the dynamic tree */\n    int     max_code;            /* largest code with non zero frequency */\n    const static_tree_desc *stat_desc;  /* the corresponding static tree */\n} FAR tree_desc;\n\ntypedef ush Pos;\ntypedef Pos FAR Posf;\ntypedef unsigned IPos;\n\n/* A Pos is an index in the character window. We use short instead of int to\n * save space in the various tables. IPos is used only for parameter passing.\n */\n\ntypedef struct internal_state {\n    z_streamp strm;      /* pointer back to this zlib stream */\n    int   status;        /* as the name implies */\n    Bytef *pending_buf;  /* output still pending */\n    ulg   pending_buf_size; /* size of pending_buf */\n    Bytef *pending_out;  /* next pending byte to output to the stream */\n    ulg   pending;       /* nb of bytes in the pending buffer */\n    int   wrap;          /* bit 0 true for zlib, bit 1 true for gzip */\n    gz_headerp  gzhead;  /* gzip header information to write */\n    ulg   gzindex;       /* where in extra, name, or comment */\n    Byte  method;        /* can only be DEFLATED */\n    int   last_flush;    /* value of flush param for previous deflate call */\n\n                /* used by deflate.c: */\n\n    uInt  w_size;        /* LZ77 window size (32K by default) */\n    uInt  w_bits;        /* log2(w_size)  (8..16) */\n    uInt  w_mask;        /* w_size - 1 */\n\n    Bytef *window;\n    /* Sliding window. Input bytes are read into the second half of the window,\n     * and move to the first half later to keep a dictionary of at least wSize\n     * bytes. With this organization, matches are limited to a distance of\n     * wSize-MAX_MATCH bytes, but this ensures that IO is always\n     * performed with a length multiple of the block size. Also, it limits\n     * the window size to 64K, which is quite useful on MSDOS.\n     * To do: use the user input buffer as sliding window.\n     */\n\n    ulg window_size;\n    /* Actual size of window: 2*wSize, except when the user input buffer\n     * is directly used as sliding window.\n     */\n\n    Posf *prev;\n    /* Link to older string with same hash index. To limit the size of this\n     * array to 64K, this link is maintained only for the last 32K strings.\n     * An index in this array is thus a window index modulo 32K.\n     */\n\n    Posf *head; /* Heads of the hash chains or NIL. */\n\n    uInt  ins_h;          /* hash index of string to be inserted */\n    uInt  hash_size;      /* number of elements in hash table */\n    uInt  hash_bits;      /* log2(hash_size) */\n    uInt  hash_mask;      /* hash_size-1 */\n\n    uInt  hash_shift;\n    /* Number of bits by which ins_h must be shifted at each input\n     * step. It must be such that after MIN_MATCH steps, the oldest\n     * byte no longer takes part in the hash key, that is:\n     *   hash_shift * MIN_MATCH >= hash_bits\n     */\n\n    long block_start;\n    /* Window position at the beginning of the current output block. Gets\n     * negative when the window is moved backwards.\n     */\n\n    uInt match_length;           /* length of best match */\n    IPos prev_match;             /* previous match */\n    int match_available;         /* set if previous match exists */\n    uInt strstart;               /* start of string to insert */\n    uInt match_start;            /* start of matching string */\n    uInt lookahead;              /* number of valid bytes ahead in window */\n\n    uInt prev_length;\n    /* Length of the best match at previous step. Matches not greater than this\n     * are discarded. This is used in the lazy match evaluation.\n     */\n\n    uInt max_chain_length;\n    /* To speed up deflation, hash chains are never searched beyond this\n     * length.  A higher limit improves compression ratio but degrades the\n     * speed.\n     */\n\n    uInt max_lazy_match;\n    /* Attempt to find a better match only when the current match is strictly\n     * smaller than this value. This mechanism is used only for compression\n     * levels >= 4.\n     */\n#   define max_insert_length  max_lazy_match\n    /* Insert new strings in the hash table only if the match length is not\n     * greater than this length. This saves time but degrades compression.\n     * max_insert_length is used only for compression levels <= 3.\n     */\n\n    int level;    /* compression level (1..9) */\n    int strategy; /* favor or force Huffman coding*/\n\n    uInt good_match;\n    /* Use a faster search when the previous match is longer than this */\n\n    int nice_match; /* Stop searching when current match exceeds this */\n\n                /* used by trees.c: */\n    /* Didn't use ct_data typedef below to suppress compiler warning */\n    struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */\n    struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n    struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */\n\n    struct tree_desc_s l_desc;               /* desc. for literal tree */\n    struct tree_desc_s d_desc;               /* desc. for distance tree */\n    struct tree_desc_s bl_desc;              /* desc. for bit length tree */\n\n    ush bl_count[MAX_BITS+1];\n    /* number of codes at each bit length for an optimal tree */\n\n    int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */\n    int heap_len;               /* number of elements in the heap */\n    int heap_max;               /* element of largest frequency */\n    /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n     * The same heap array is used to build all trees.\n     */\n\n    uch depth[2*L_CODES+1];\n    /* Depth of each subtree used as tie breaker for trees of equal frequency\n     */\n\n    uchf *l_buf;          /* buffer for literals or lengths */\n\n    uInt  lit_bufsize;\n    /* Size of match buffer for literals/lengths.  There are 4 reasons for\n     * limiting lit_bufsize to 64K:\n     *   - frequencies can be kept in 16 bit counters\n     *   - if compression is not successful for the first block, all input\n     *     data is still in the window so we can still emit a stored block even\n     *     when input comes from standard input.  (This can also be done for\n     *     all blocks if lit_bufsize is not greater than 32K.)\n     *   - if compression is not successful for a file smaller than 64K, we can\n     *     even emit a stored file instead of a stored block (saving 5 bytes).\n     *     This is applicable only for zip (not gzip or zlib).\n     *   - creating new Huffman trees less frequently may not provide fast\n     *     adaptation to changes in the input data statistics. (Take for\n     *     example a binary file with poorly compressible code followed by\n     *     a highly compressible string table.) Smaller buffer sizes give\n     *     fast adaptation but have of course the overhead of transmitting\n     *     trees more frequently.\n     *   - I can't count above 4\n     */\n\n    uInt last_lit;      /* running index in l_buf */\n\n    ushf *d_buf;\n    /* Buffer for distances. To simplify the code, d_buf and l_buf have\n     * the same number of elements. To use different lengths, an extra flag\n     * array would be necessary.\n     */\n\n    ulg opt_len;        /* bit length of current block with optimal trees */\n    ulg static_len;     /* bit length of current block with static trees */\n    uInt matches;       /* number of string matches in current block */\n    uInt insert;        /* bytes at end of window left to insert */\n\n#ifdef ZLIB_DEBUG\n    ulg compressed_len; /* total bit length of compressed file mod 2^32 */\n    ulg bits_sent;      /* bit length of compressed data sent mod 2^32 */\n#endif\n\n    ush bi_buf;\n    /* Output buffer. bits are inserted starting at the bottom (least\n     * significant bits).\n     */\n    int bi_valid;\n    /* Number of valid bits in bi_buf.  All bits above the last valid bit\n     * are always zero.\n     */\n\n    ulg high_water;\n    /* High water mark offset in window for initialized bytes -- bytes above\n     * this are set to zero in order to avoid memory check warnings when\n     * longest match routines access bytes past the input.  This is then\n     * updated to the new high water mark.\n     */\n\n} FAR deflate_state;\n\n/* Output a byte on the stream.\n * IN assertion: there is enough room in pending_buf.\n */\n#define put_byte(s, c) {s->pending_buf[s->pending++] = (Bytef)(c);}\n\n\n#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)\n/* Minimum amount of lookahead, except at the end of the input file.\n * See deflate.c for comments about the MIN_MATCH+1.\n */\n\n#define MAX_DIST(s)  ((s)->w_size-MIN_LOOKAHEAD)\n/* In order to simplify the code, particularly on 16 bit machines, match\n * distances are limited to MAX_DIST instead of WSIZE.\n */\n\n#define WIN_INIT MAX_MATCH\n/* Number of bytes after end of data in window to initialize in order to avoid\n   memory checker errors from longest match routines */\n\n        /* in trees.c */\nvoid ZLIB_INTERNAL _tr_init OF((deflate_state *s));\nint ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));\nvoid ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf,\n                        ulg stored_len, int last));\nvoid ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s));\nvoid ZLIB_INTERNAL _tr_align OF((deflate_state *s));\nvoid ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf,\n                        ulg stored_len, int last));\n\n#define d_code(dist) \\\n   ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])\n/* Mapping from a distance to a distance code. dist is the distance - 1 and\n * must not have side effects. _dist_code[256] and _dist_code[257] are never\n * used.\n */\n\n#ifndef ZLIB_DEBUG\n/* Inline versions of _tr_tally for speed: */\n\n#if defined(GEN_TREES_H) || !defined(STDC)\n  extern uch ZLIB_INTERNAL _length_code[];\n  extern uch ZLIB_INTERNAL _dist_code[];\n#else\n  extern const uch ZLIB_INTERNAL _length_code[];\n  extern const uch ZLIB_INTERNAL _dist_code[];\n#endif\n\n# define _tr_tally_lit(s, c, flush) \\\n  { uch cc = (c); \\\n    s->d_buf[s->last_lit] = 0; \\\n    s->l_buf[s->last_lit++] = cc; \\\n    s->dyn_ltree[cc].Freq++; \\\n    flush = (s->last_lit == s->lit_bufsize-1); \\\n   }\n# define _tr_tally_dist(s, distance, length, flush) \\\n  { uch len = (uch)(length); \\\n    ush dist = (ush)(distance); \\\n    s->d_buf[s->last_lit] = dist; \\\n    s->l_buf[s->last_lit++] = len; \\\n    dist--; \\\n    s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \\\n    s->dyn_dtree[d_code(dist)].Freq++; \\\n    flush = (s->last_lit == s->lit_bufsize-1); \\\n  }\n#else\n# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)\n# define _tr_tally_dist(s, distance, length, flush) \\\n              flush = _tr_tally(s, distance, length)\n#endif\n\n#endif /* DEFLATE_H */\n"
  },
  {
    "path": "jsb_build/websockets/zlib/gzclose.c",
    "content": "/* gzclose.c -- zlib gzclose() function\n * Copyright (C) 2004, 2010 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n#include \"gzguts.h\"\n\n/* gzclose() is in a separate file so that it is linked in only if it is used.\n   That way the other gzclose functions can be used instead to avoid linking in\n   unneeded compression or decompression routines. */\nint ZEXPORT gzclose(file)\n    gzFile file;\n{\n#ifndef NO_GZCOMPRESS\n    gz_statep state;\n\n    if (file == NULL)\n        return Z_STREAM_ERROR;\n    state = (gz_statep)file;\n\n    return state->mode == GZ_READ ? gzclose_r(file) : gzclose_w(file);\n#else\n    return gzclose_r(file);\n#endif\n}\n"
  },
  {
    "path": "jsb_build/websockets/zlib/gzguts.h",
    "content": "/* gzguts.h -- zlib internal header definitions for gz* operations\n * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013, 2016 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n#ifdef _LARGEFILE64_SOURCE\n#  ifndef _LARGEFILE_SOURCE\n#    define _LARGEFILE_SOURCE 1\n#  endif\n#  ifdef _FILE_OFFSET_BITS\n#    undef _FILE_OFFSET_BITS\n#  endif\n#endif\n\n#ifdef HAVE_HIDDEN\n#  define ZLIB_INTERNAL __attribute__((visibility (\"hidden\")))\n#else\n#  define ZLIB_INTERNAL\n#endif\n\n#include <stdio.h>\n#include \"zlib.h\"\n#ifdef STDC\n#  include <string.h>\n#  include <stdlib.h>\n#  include <limits.h>\n#endif\n\n#ifndef _POSIX_SOURCE\n#  define _POSIX_SOURCE\n#endif\n#include <fcntl.h>\n\n#ifdef _WIN32\n#  include <stddef.h>\n#endif\n\n#if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32)\n#  include <io.h>\n#endif\n\n#if defined(_WIN32) || defined(__CYGWIN__)\n#  define WIDECHAR\n#endif\n\n#ifdef WINAPI_FAMILY\n#  define open _open\n#  define read _read\n#  define write _write\n#  define close _close\n#endif\n\n#ifdef NO_DEFLATE       /* for compatibility with old definition */\n#  define NO_GZCOMPRESS\n#endif\n\n#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)\n#  ifndef HAVE_VSNPRINTF\n#    define HAVE_VSNPRINTF\n#  endif\n#endif\n\n#if defined(__CYGWIN__)\n#  ifndef HAVE_VSNPRINTF\n#    define HAVE_VSNPRINTF\n#  endif\n#endif\n\n#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410)\n#  ifndef HAVE_VSNPRINTF\n#    define HAVE_VSNPRINTF\n#  endif\n#endif\n\n#ifndef HAVE_VSNPRINTF\n#  ifdef MSDOS\n/* vsnprintf may exist on some MS-DOS compilers (DJGPP?),\n   but for now we just assume it doesn't. */\n#    define NO_vsnprintf\n#  endif\n#  ifdef __TURBOC__\n#    define NO_vsnprintf\n#  endif\n#  ifdef WIN32\n/* In Win32, vsnprintf is available as the \"non-ANSI\" _vsnprintf. */\n#    if !defined(vsnprintf) && !defined(NO_vsnprintf)\n#      if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 )\n#         define vsnprintf _vsnprintf\n#      endif\n#    endif\n#  endif\n#  ifdef __SASC\n#    define NO_vsnprintf\n#  endif\n#  ifdef VMS\n#    define NO_vsnprintf\n#  endif\n#  ifdef __OS400__\n#    define NO_vsnprintf\n#  endif\n#  ifdef __MVS__\n#    define NO_vsnprintf\n#  endif\n#endif\n\n/* unlike snprintf (which is required in C99), _snprintf does not guarantee\n   null termination of the result -- however this is only used in gzlib.c where\n   the result is assured to fit in the space provided */\n#if defined(_MSC_VER) && _MSC_VER < 1900\n#  define snprintf _snprintf\n#endif\n\n#ifndef local\n#  define local static\n#endif\n/* since \"static\" is used to mean two completely different things in C, we\n   define \"local\" for the non-static meaning of \"static\", for readability\n   (compile with -Dlocal if your debugger can't find static symbols) */\n\n/* gz* functions always use library allocation functions */\n#ifndef STDC\n  extern voidp  malloc OF((uInt size));\n  extern void   free   OF((voidpf ptr));\n#endif\n\n/* get errno and strerror definition */\n#if defined UNDER_CE\n#  include <windows.h>\n#  define zstrerror() gz_strwinerror((DWORD)GetLastError())\n#else\n#  ifndef NO_STRERROR\n#    include <errno.h>\n#    define zstrerror() strerror(errno)\n#  else\n#    define zstrerror() \"stdio error (consult errno)\"\n#  endif\n#endif\n\n/* provide prototypes for these when building zlib without LFS */\n#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0\n    ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));\n    ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\n    ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));\n    ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));\n#endif\n\n/* default memLevel */\n#if MAX_MEM_LEVEL >= 8\n#  define DEF_MEM_LEVEL 8\n#else\n#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL\n#endif\n\n/* default i/o buffer size -- double this for output when reading (this and\n   twice this must be able to fit in an unsigned type) */\n#define GZBUFSIZE 8192\n\n/* gzip modes, also provide a little integrity check on the passed structure */\n#define GZ_NONE 0\n#define GZ_READ 7247\n#define GZ_WRITE 31153\n#define GZ_APPEND 1     /* mode set to GZ_WRITE after the file is opened */\n\n/* values for gz_state how */\n#define LOOK 0      /* look for a gzip header */\n#define COPY 1      /* copy input directly */\n#define GZIP 2      /* decompress a gzip stream */\n\n/* internal gzip file state data structure */\ntypedef struct {\n        /* exposed contents for gzgetc() macro */\n    struct gzFile_s x;      /* \"x\" for exposed */\n                            /* x.have: number of bytes available at x.next */\n                            /* x.next: next output data to deliver or write */\n                            /* x.pos: current position in uncompressed data */\n        /* used for both reading and writing */\n    int mode;               /* see gzip modes above */\n    int fd;                 /* file descriptor */\n    char *path;             /* path or fd for error messages */\n    unsigned size;          /* buffer size, zero if not allocated yet */\n    unsigned want;          /* requested buffer size, default is GZBUFSIZE */\n    unsigned char *in;      /* input buffer (double-sized when writing) */\n    unsigned char *out;     /* output buffer (double-sized when reading) */\n    int direct;             /* 0 if processing gzip, 1 if transparent */\n        /* just for reading */\n    int how;                /* 0: get header, 1: copy, 2: decompress */\n    z_off64_t start;        /* where the gzip data started, for rewinding */\n    int eof;                /* true if end of input file reached */\n    int past;               /* true if read requested past end */\n        /* just for writing */\n    int level;              /* compression level */\n    int strategy;           /* compression strategy */\n        /* seek request */\n    z_off64_t skip;         /* amount to skip (already rewound if backwards) */\n    int seek;               /* true if seek request pending */\n        /* error information */\n    int err;                /* error code */\n    char *msg;              /* error message */\n        /* zlib inflate or deflate stream */\n    z_stream strm;          /* stream structure in-place (not a pointer) */\n} gz_state;\ntypedef gz_state FAR *gz_statep;\n\n/* shared functions */\nvoid ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *));\n#if defined UNDER_CE\nchar ZLIB_INTERNAL *gz_strwinerror OF((DWORD error));\n#endif\n\n/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t\n   value -- needed when comparing unsigned to z_off64_t, which is signed\n   (possible z_off64_t types off_t, off64_t, and long are all signed) */\n#ifdef INT_MAX\n#  define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX)\n#else\nunsigned ZLIB_INTERNAL gz_intmax OF((void));\n#  define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax())\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/zlib/gzlib.c",
    "content": "/* gzlib.c -- zlib functions common to reading and writing gzip files\n * Copyright (C) 2004-2017 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n#include \"gzguts.h\"\n\n#if defined(_WIN32) && !defined(__BORLANDC__) && !defined(__MINGW32__)\n#  define LSEEK _lseeki64\n#else\n#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0\n#  define LSEEK lseek64\n#else\n#  define LSEEK lseek\n#endif\n#endif\n\n/* Local functions */\nlocal void gz_reset OF((gz_statep));\nlocal gzFile gz_open OF((const void *, int, const char *));\n\n#if defined UNDER_CE\n\n/* Map the Windows error number in ERROR to a locale-dependent error message\n   string and return a pointer to it.  Typically, the values for ERROR come\n   from GetLastError.\n\n   The string pointed to shall not be modified by the application, but may be\n   overwritten by a subsequent call to gz_strwinerror\n\n   The gz_strwinerror function does not change the current setting of\n   GetLastError. */\nchar ZLIB_INTERNAL *gz_strwinerror (error)\n     DWORD error;\n{\n    static char buf[1024];\n\n    wchar_t *msgbuf;\n    DWORD lasterr = GetLastError();\n    DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM\n        | FORMAT_MESSAGE_ALLOCATE_BUFFER,\n        NULL,\n        error,\n        0, /* Default language */\n        (LPVOID)&msgbuf,\n        0,\n        NULL);\n    if (chars != 0) {\n        /* If there is an \\r\\n appended, zap it.  */\n        if (chars >= 2\n            && msgbuf[chars - 2] == '\\r' && msgbuf[chars - 1] == '\\n') {\n            chars -= 2;\n            msgbuf[chars] = 0;\n        }\n\n        if (chars > sizeof (buf) - 1) {\n            chars = sizeof (buf) - 1;\n            msgbuf[chars] = 0;\n        }\n\n        wcstombs(buf, msgbuf, chars + 1);\n        LocalFree(msgbuf);\n    }\n    else {\n        sprintf(buf, \"unknown win32 error (%ld)\", error);\n    }\n\n    SetLastError(lasterr);\n    return buf;\n}\n\n#endif /* UNDER_CE */\n\n/* Reset gzip file state */\nlocal void gz_reset(state)\n    gz_statep state;\n{\n    state->x.have = 0;              /* no output data available */\n    if (state->mode == GZ_READ) {   /* for reading ... */\n        state->eof = 0;             /* not at end of file */\n        state->past = 0;            /* have not read past end yet */\n        state->how = LOOK;          /* look for gzip header */\n    }\n    state->seek = 0;                /* no seek request pending */\n    gz_error(state, Z_OK, NULL);    /* clear error */\n    state->x.pos = 0;               /* no uncompressed data yet */\n    state->strm.avail_in = 0;       /* no input data yet */\n}\n\n/* Open a gzip file either by name or file descriptor. */\nlocal gzFile gz_open(path, fd, mode)\n    const void *path;\n    int fd;\n    const char *mode;\n{\n    gz_statep state;\n    z_size_t len;\n    int oflag;\n#ifdef O_CLOEXEC\n    int cloexec = 0;\n#endif\n#ifdef O_EXCL\n    int exclusive = 0;\n#endif\n\n    /* check input */\n    if (path == NULL)\n        return NULL;\n\n    /* allocate gzFile structure to return */\n    state = (gz_statep)malloc(sizeof(gz_state));\n    if (state == NULL)\n        return NULL;\n    state->size = 0;            /* no buffers allocated yet */\n    state->want = GZBUFSIZE;    /* requested buffer size */\n    state->msg = NULL;          /* no error message yet */\n\n    /* interpret mode */\n    state->mode = GZ_NONE;\n    state->level = Z_DEFAULT_COMPRESSION;\n    state->strategy = Z_DEFAULT_STRATEGY;\n    state->direct = 0;\n    while (*mode) {\n        if (*mode >= '0' && *mode <= '9')\n            state->level = *mode - '0';\n        else\n            switch (*mode) {\n            case 'r':\n                state->mode = GZ_READ;\n                break;\n#ifndef NO_GZCOMPRESS\n            case 'w':\n                state->mode = GZ_WRITE;\n                break;\n            case 'a':\n                state->mode = GZ_APPEND;\n                break;\n#endif\n            case '+':       /* can't read and write at the same time */\n                free(state);\n                return NULL;\n            case 'b':       /* ignore -- will request binary anyway */\n                break;\n#ifdef O_CLOEXEC\n            case 'e':\n                cloexec = 1;\n                break;\n#endif\n#ifdef O_EXCL\n            case 'x':\n                exclusive = 1;\n                break;\n#endif\n            case 'f':\n                state->strategy = Z_FILTERED;\n                break;\n            case 'h':\n                state->strategy = Z_HUFFMAN_ONLY;\n                break;\n            case 'R':\n                state->strategy = Z_RLE;\n                break;\n            case 'F':\n                state->strategy = Z_FIXED;\n                break;\n            case 'T':\n                state->direct = 1;\n                break;\n            default:        /* could consider as an error, but just ignore */\n                ;\n            }\n        mode++;\n    }\n\n    /* must provide an \"r\", \"w\", or \"a\" */\n    if (state->mode == GZ_NONE) {\n        free(state);\n        return NULL;\n    }\n\n    /* can't force transparent read */\n    if (state->mode == GZ_READ) {\n        if (state->direct) {\n            free(state);\n            return NULL;\n        }\n        state->direct = 1;      /* for empty file */\n    }\n\n    /* save the path name for error messages */\n#ifdef WIDECHAR\n    if (fd == -2) {\n        len = wcstombs(NULL, path, 0);\n        if (len == (z_size_t)-1)\n            len = 0;\n    }\n    else\n#endif\n        len = strlen((const char *)path);\n    state->path = (char *)malloc(len + 1);\n    if (state->path == NULL) {\n        free(state);\n        return NULL;\n    }\n#ifdef WIDECHAR\n    if (fd == -2)\n        if (len)\n            wcstombs(state->path, path, len + 1);\n        else\n            *(state->path) = 0;\n    else\n#endif\n#if !defined(NO_snprintf) && !defined(NO_vsnprintf)\n        (void)snprintf(state->path, len + 1, \"%s\", (const char *)path);\n#else\n        strcpy(state->path, path);\n#endif\n\n    /* compute the flags for open() */\n    oflag =\n#ifdef O_LARGEFILE\n        O_LARGEFILE |\n#endif\n#ifdef O_BINARY\n        O_BINARY |\n#endif\n#ifdef O_CLOEXEC\n        (cloexec ? O_CLOEXEC : 0) |\n#endif\n        (state->mode == GZ_READ ?\n         O_RDONLY :\n         (O_WRONLY | O_CREAT |\n#ifdef O_EXCL\n          (exclusive ? O_EXCL : 0) |\n#endif\n          (state->mode == GZ_WRITE ?\n           O_TRUNC :\n           O_APPEND)));\n\n    /* open the file with the appropriate flags (or just use fd) */\n    state->fd = fd > -1 ? fd : (\n#ifdef WIDECHAR\n        fd == -2 ? _wopen(path, oflag, 0666) :\n#endif\n        open((const char *)path, oflag, 0666));\n    if (state->fd == -1) {\n        free(state->path);\n        free(state);\n        return NULL;\n    }\n    if (state->mode == GZ_APPEND) {\n        LSEEK(state->fd, 0, SEEK_END);  /* so gzoffset() is correct */\n        state->mode = GZ_WRITE;         /* simplify later checks */\n    }\n\n    /* save the current position for rewinding (only if reading) */\n    if (state->mode == GZ_READ) {\n        state->start = LSEEK(state->fd, 0, SEEK_CUR);\n        if (state->start == -1) state->start = 0;\n    }\n\n    /* initialize stream */\n    gz_reset(state);\n\n    /* return stream */\n    return (gzFile)state;\n}\n\n/* -- see zlib.h -- */\ngzFile ZEXPORT gzopen(path, mode)\n    const char *path;\n    const char *mode;\n{\n    return gz_open(path, -1, mode);\n}\n\n/* -- see zlib.h -- */\ngzFile ZEXPORT gzopen64(path, mode)\n    const char *path;\n    const char *mode;\n{\n    return gz_open(path, -1, mode);\n}\n\n/* -- see zlib.h -- */\ngzFile ZEXPORT gzdopen(fd, mode)\n    int fd;\n    const char *mode;\n{\n    char *path;         /* identifier for error messages */\n    gzFile gz;\n\n    if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL)\n        return NULL;\n#if !defined(NO_snprintf) && !defined(NO_vsnprintf)\n    (void)snprintf(path, 7 + 3 * sizeof(int), \"<fd:%d>\", fd);\n#else\n    sprintf(path, \"<fd:%d>\", fd);   /* for debugging */\n#endif\n    gz = gz_open(path, fd, mode);\n    free(path);\n    return gz;\n}\n\n/* -- see zlib.h -- */\n#ifdef WIDECHAR\ngzFile ZEXPORT gzopen_w(path, mode)\n    const wchar_t *path;\n    const char *mode;\n{\n    return gz_open(path, -2, mode);\n}\n#endif\n\n/* -- see zlib.h -- */\nint ZEXPORT gzbuffer(file, size)\n    gzFile file;\n    unsigned size;\n{\n    gz_statep state;\n\n    /* get internal structure and check integrity */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n    if (state->mode != GZ_READ && state->mode != GZ_WRITE)\n        return -1;\n\n    /* make sure we haven't already allocated memory */\n    if (state->size != 0)\n        return -1;\n\n    /* check and set requested size */\n    if ((size << 1) < size)\n        return -1;              /* need to be able to double it */\n    if (size < 2)\n        size = 2;               /* need two bytes to check magic header */\n    state->want = size;\n    return 0;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzrewind(file)\n    gzFile file;\n{\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n\n    /* check that we're reading and that there's no error */\n    if (state->mode != GZ_READ ||\n            (state->err != Z_OK && state->err != Z_BUF_ERROR))\n        return -1;\n\n    /* back up and start over */\n    if (LSEEK(state->fd, state->start, SEEK_SET) == -1)\n        return -1;\n    gz_reset(state);\n    return 0;\n}\n\n/* -- see zlib.h -- */\nz_off64_t ZEXPORT gzseek64(file, offset, whence)\n    gzFile file;\n    z_off64_t offset;\n    int whence;\n{\n    unsigned n;\n    z_off64_t ret;\n    gz_statep state;\n\n    /* get internal structure and check integrity */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n    if (state->mode != GZ_READ && state->mode != GZ_WRITE)\n        return -1;\n\n    /* check that there's no error */\n    if (state->err != Z_OK && state->err != Z_BUF_ERROR)\n        return -1;\n\n    /* can only seek from start or relative to current position */\n    if (whence != SEEK_SET && whence != SEEK_CUR)\n        return -1;\n\n    /* normalize offset to a SEEK_CUR specification */\n    if (whence == SEEK_SET)\n        offset -= state->x.pos;\n    else if (state->seek)\n        offset += state->skip;\n    state->seek = 0;\n\n    /* if within raw area while reading, just go there */\n    if (state->mode == GZ_READ && state->how == COPY &&\n            state->x.pos + offset >= 0) {\n        ret = LSEEK(state->fd, offset - state->x.have, SEEK_CUR);\n        if (ret == -1)\n            return -1;\n        state->x.have = 0;\n        state->eof = 0;\n        state->past = 0;\n        state->seek = 0;\n        gz_error(state, Z_OK, NULL);\n        state->strm.avail_in = 0;\n        state->x.pos += offset;\n        return state->x.pos;\n    }\n\n    /* calculate skip amount, rewinding if needed for back seek when reading */\n    if (offset < 0) {\n        if (state->mode != GZ_READ)         /* writing -- can't go backwards */\n            return -1;\n        offset += state->x.pos;\n        if (offset < 0)                     /* before start of file! */\n            return -1;\n        if (gzrewind(file) == -1)           /* rewind, then skip to offset */\n            return -1;\n    }\n\n    /* if reading, skip what's in output buffer (one less gzgetc() check) */\n    if (state->mode == GZ_READ) {\n        n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ?\n            (unsigned)offset : state->x.have;\n        state->x.have -= n;\n        state->x.next += n;\n        state->x.pos += n;\n        offset -= n;\n    }\n\n    /* request skip (if not zero) */\n    if (offset) {\n        state->seek = 1;\n        state->skip = offset;\n    }\n    return state->x.pos + offset;\n}\n\n/* -- see zlib.h -- */\nz_off_t ZEXPORT gzseek(file, offset, whence)\n    gzFile file;\n    z_off_t offset;\n    int whence;\n{\n    z_off64_t ret;\n\n    ret = gzseek64(file, (z_off64_t)offset, whence);\n    return ret == (z_off_t)ret ? (z_off_t)ret : -1;\n}\n\n/* -- see zlib.h -- */\nz_off64_t ZEXPORT gztell64(file)\n    gzFile file;\n{\n    gz_statep state;\n\n    /* get internal structure and check integrity */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n    if (state->mode != GZ_READ && state->mode != GZ_WRITE)\n        return -1;\n\n    /* return position */\n    return state->x.pos + (state->seek ? state->skip : 0);\n}\n\n/* -- see zlib.h -- */\nz_off_t ZEXPORT gztell(file)\n    gzFile file;\n{\n    z_off64_t ret;\n\n    ret = gztell64(file);\n    return ret == (z_off_t)ret ? (z_off_t)ret : -1;\n}\n\n/* -- see zlib.h -- */\nz_off64_t ZEXPORT gzoffset64(file)\n    gzFile file;\n{\n    z_off64_t offset;\n    gz_statep state;\n\n    /* get internal structure and check integrity */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n    if (state->mode != GZ_READ && state->mode != GZ_WRITE)\n        return -1;\n\n    /* compute and return effective offset in file */\n    offset = LSEEK(state->fd, 0, SEEK_CUR);\n    if (offset == -1)\n        return -1;\n    if (state->mode == GZ_READ)             /* reading */\n        offset -= state->strm.avail_in;     /* don't count buffered input */\n    return offset;\n}\n\n/* -- see zlib.h -- */\nz_off_t ZEXPORT gzoffset(file)\n    gzFile file;\n{\n    z_off64_t ret;\n\n    ret = gzoffset64(file);\n    return ret == (z_off_t)ret ? (z_off_t)ret : -1;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzeof(file)\n    gzFile file;\n{\n    gz_statep state;\n\n    /* get internal structure and check integrity */\n    if (file == NULL)\n        return 0;\n    state = (gz_statep)file;\n    if (state->mode != GZ_READ && state->mode != GZ_WRITE)\n        return 0;\n\n    /* return end-of-file state */\n    return state->mode == GZ_READ ? state->past : 0;\n}\n\n/* -- see zlib.h -- */\nconst char * ZEXPORT gzerror(file, errnum)\n    gzFile file;\n    int *errnum;\n{\n    gz_statep state;\n\n    /* get internal structure and check integrity */\n    if (file == NULL)\n        return NULL;\n    state = (gz_statep)file;\n    if (state->mode != GZ_READ && state->mode != GZ_WRITE)\n        return NULL;\n\n    /* return error information */\n    if (errnum != NULL)\n        *errnum = state->err;\n    return state->err == Z_MEM_ERROR ? \"out of memory\" :\n                                       (state->msg == NULL ? \"\" : state->msg);\n}\n\n/* -- see zlib.h -- */\nvoid ZEXPORT gzclearerr(file)\n    gzFile file;\n{\n    gz_statep state;\n\n    /* get internal structure and check integrity */\n    if (file == NULL)\n        return;\n    state = (gz_statep)file;\n    if (state->mode != GZ_READ && state->mode != GZ_WRITE)\n        return;\n\n    /* clear error and end-of-file */\n    if (state->mode == GZ_READ) {\n        state->eof = 0;\n        state->past = 0;\n    }\n    gz_error(state, Z_OK, NULL);\n}\n\n/* Create an error message in allocated memory and set state->err and\n   state->msg accordingly.  Free any previous error message already there.  Do\n   not try to free or allocate space if the error is Z_MEM_ERROR (out of\n   memory).  Simply save the error message as a static string.  If there is an\n   allocation failure constructing the error message, then convert the error to\n   out of memory. */\nvoid ZLIB_INTERNAL gz_error(state, err, msg)\n    gz_statep state;\n    int err;\n    const char *msg;\n{\n    /* free previously allocated message and clear */\n    if (state->msg != NULL) {\n        if (state->err != Z_MEM_ERROR)\n            free(state->msg);\n        state->msg = NULL;\n    }\n\n    /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */\n    if (err != Z_OK && err != Z_BUF_ERROR)\n        state->x.have = 0;\n\n    /* set error code, and if no message, then done */\n    state->err = err;\n    if (msg == NULL)\n        return;\n\n    /* for an out of memory error, return literal string when requested */\n    if (err == Z_MEM_ERROR)\n        return;\n\n    /* construct error message with path */\n    if ((state->msg = (char *)malloc(strlen(state->path) + strlen(msg) + 3)) ==\n            NULL) {\n        state->err = Z_MEM_ERROR;\n        return;\n    }\n#if !defined(NO_snprintf) && !defined(NO_vsnprintf)\n    (void)snprintf(state->msg, strlen(state->path) + strlen(msg) + 3,\n                   \"%s%s%s\", state->path, \": \", msg);\n#else\n    strcpy(state->msg, state->path);\n    strcat(state->msg, \": \");\n    strcat(state->msg, msg);\n#endif\n}\n\n#ifndef INT_MAX\n/* portably return maximum value for an int (when limits.h presumed not\n   available) -- we need to do this to cover cases where 2's complement not\n   used, since C standard permits 1's complement and sign-bit representations,\n   otherwise we could just use ((unsigned)-1) >> 1 */\nunsigned ZLIB_INTERNAL gz_intmax()\n{\n    unsigned p, q;\n\n    p = 1;\n    do {\n        q = p;\n        p <<= 1;\n        p++;\n    } while (p > q);\n    return q >> 1;\n}\n#endif\n"
  },
  {
    "path": "jsb_build/websockets/zlib/gzread.c",
    "content": "/* gzread.c -- zlib functions for reading gzip files\n * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013, 2016 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n#include \"gzguts.h\"\n\n/* Local functions */\nlocal int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *));\nlocal int gz_avail OF((gz_statep));\nlocal int gz_look OF((gz_statep));\nlocal int gz_decomp OF((gz_statep));\nlocal int gz_fetch OF((gz_statep));\nlocal int gz_skip OF((gz_statep, z_off64_t));\nlocal z_size_t gz_read OF((gz_statep, voidp, z_size_t));\n\n/* Use read() to load a buffer -- return -1 on error, otherwise 0.  Read from\n   state->fd, and update state->eof, state->err, and state->msg as appropriate.\n   This function needs to loop on read(), since read() is not guaranteed to\n   read the number of bytes requested, depending on the type of descriptor. */\nlocal int gz_load(state, buf, len, have)\n    gz_statep state;\n    unsigned char *buf;\n    unsigned len;\n    unsigned *have;\n{\n    int ret;\n    unsigned get, max = ((unsigned)-1 >> 2) + 1;\n\n    *have = 0;\n    do {\n        get = len - *have;\n        if (get > max)\n            get = max;\n        ret = read(state->fd, buf + *have, get);\n        if (ret <= 0)\n            break;\n        *have += (unsigned)ret;\n    } while (*have < len);\n    if (ret < 0) {\n        gz_error(state, Z_ERRNO, zstrerror());\n        return -1;\n    }\n    if (ret == 0)\n        state->eof = 1;\n    return 0;\n}\n\n/* Load up input buffer and set eof flag if last data loaded -- return -1 on\n   error, 0 otherwise.  Note that the eof flag is set when the end of the input\n   file is reached, even though there may be unused data in the buffer.  Once\n   that data has been used, no more attempts will be made to read the file.\n   If strm->avail_in != 0, then the current data is moved to the beginning of\n   the input buffer, and then the remainder of the buffer is loaded with the\n   available data from the input file. */\nlocal int gz_avail(state)\n    gz_statep state;\n{\n    unsigned got;\n    z_streamp strm = &(state->strm);\n\n    if (state->err != Z_OK && state->err != Z_BUF_ERROR)\n        return -1;\n    if (state->eof == 0) {\n        if (strm->avail_in) {       /* copy what's there to the start */\n            unsigned char *p = state->in;\n            unsigned const char *q = strm->next_in;\n            unsigned n = strm->avail_in;\n            do {\n                *p++ = *q++;\n            } while (--n);\n        }\n        if (gz_load(state, state->in + strm->avail_in,\n                    state->size - strm->avail_in, &got) == -1)\n            return -1;\n        strm->avail_in += got;\n        strm->next_in = state->in;\n    }\n    return 0;\n}\n\n/* Look for gzip header, set up for inflate or copy.  state->x.have must be 0.\n   If this is the first time in, allocate required memory.  state->how will be\n   left unchanged if there is no more input data available, will be set to COPY\n   if there is no gzip header and direct copying will be performed, or it will\n   be set to GZIP for decompression.  If direct copying, then leftover input\n   data from the input buffer will be copied to the output buffer.  In that\n   case, all further file reads will be directly to either the output buffer or\n   a user buffer.  If decompressing, the inflate state will be initialized.\n   gz_look() will return 0 on success or -1 on failure. */\nlocal int gz_look(state)\n    gz_statep state;\n{\n    z_streamp strm = &(state->strm);\n\n    /* allocate read buffers and inflate memory */\n    if (state->size == 0) {\n        /* allocate buffers */\n        state->in = (unsigned char *)malloc(state->want);\n        state->out = (unsigned char *)malloc(state->want << 1);\n        if (state->in == NULL || state->out == NULL) {\n            free(state->out);\n            free(state->in);\n            gz_error(state, Z_MEM_ERROR, \"out of memory\");\n            return -1;\n        }\n        state->size = state->want;\n\n        /* allocate inflate memory */\n        state->strm.zalloc = Z_NULL;\n        state->strm.zfree = Z_NULL;\n        state->strm.opaque = Z_NULL;\n        state->strm.avail_in = 0;\n        state->strm.next_in = Z_NULL;\n        if (inflateInit2(&(state->strm), 15 + 16) != Z_OK) {    /* gunzip */\n            free(state->out);\n            free(state->in);\n            state->size = 0;\n            gz_error(state, Z_MEM_ERROR, \"out of memory\");\n            return -1;\n        }\n    }\n\n    /* get at least the magic bytes in the input buffer */\n    if (strm->avail_in < 2) {\n        if (gz_avail(state) == -1)\n            return -1;\n        if (strm->avail_in == 0)\n            return 0;\n    }\n\n    /* look for gzip magic bytes -- if there, do gzip decoding (note: there is\n       a logical dilemma here when considering the case of a partially written\n       gzip file, to wit, if a single 31 byte is written, then we cannot tell\n       whether this is a single-byte file, or just a partially written gzip\n       file -- for here we assume that if a gzip file is being written, then\n       the header will be written in a single operation, so that reading a\n       single byte is sufficient indication that it is not a gzip file) */\n    if (strm->avail_in > 1 &&\n            strm->next_in[0] == 31 && strm->next_in[1] == 139) {\n        inflateReset(strm);\n        state->how = GZIP;\n        state->direct = 0;\n        return 0;\n    }\n\n    /* no gzip header -- if we were decoding gzip before, then this is trailing\n       garbage.  Ignore the trailing garbage and finish. */\n    if (state->direct == 0) {\n        strm->avail_in = 0;\n        state->eof = 1;\n        state->x.have = 0;\n        return 0;\n    }\n\n    /* doing raw i/o, copy any leftover input to output -- this assumes that\n       the output buffer is larger than the input buffer, which also assures\n       space for gzungetc() */\n    state->x.next = state->out;\n    if (strm->avail_in) {\n        memcpy(state->x.next, strm->next_in, strm->avail_in);\n        state->x.have = strm->avail_in;\n        strm->avail_in = 0;\n    }\n    state->how = COPY;\n    state->direct = 1;\n    return 0;\n}\n\n/* Decompress from input to the provided next_out and avail_out in the state.\n   On return, state->x.have and state->x.next point to the just decompressed\n   data.  If the gzip stream completes, state->how is reset to LOOK to look for\n   the next gzip stream or raw data, once state->x.have is depleted.  Returns 0\n   on success, -1 on failure. */\nlocal int gz_decomp(state)\n    gz_statep state;\n{\n    int ret = Z_OK;\n    unsigned had;\n    z_streamp strm = &(state->strm);\n\n    /* fill output buffer up to end of deflate stream */\n    had = strm->avail_out;\n    do {\n        /* get more input for inflate() */\n        if (strm->avail_in == 0 && gz_avail(state) == -1)\n            return -1;\n        if (strm->avail_in == 0) {\n            gz_error(state, Z_BUF_ERROR, \"unexpected end of file\");\n            break;\n        }\n\n        /* decompress and handle errors */\n        ret = inflate(strm, Z_NO_FLUSH);\n        if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {\n            gz_error(state, Z_STREAM_ERROR,\n                     \"internal error: inflate stream corrupt\");\n            return -1;\n        }\n        if (ret == Z_MEM_ERROR) {\n            gz_error(state, Z_MEM_ERROR, \"out of memory\");\n            return -1;\n        }\n        if (ret == Z_DATA_ERROR) {              /* deflate stream invalid */\n            gz_error(state, Z_DATA_ERROR,\n                     strm->msg == NULL ? \"compressed data error\" : strm->msg);\n            return -1;\n        }\n    } while (strm->avail_out && ret != Z_STREAM_END);\n\n    /* update available output */\n    state->x.have = had - strm->avail_out;\n    state->x.next = strm->next_out - state->x.have;\n\n    /* if the gzip stream completed successfully, look for another */\n    if (ret == Z_STREAM_END)\n        state->how = LOOK;\n\n    /* good decompression */\n    return 0;\n}\n\n/* Fetch data and put it in the output buffer.  Assumes state->x.have is 0.\n   Data is either copied from the input file or decompressed from the input\n   file depending on state->how.  If state->how is LOOK, then a gzip header is\n   looked for to determine whether to copy or decompress.  Returns -1 on error,\n   otherwise 0.  gz_fetch() will leave state->how as COPY or GZIP unless the\n   end of the input file has been reached and all data has been processed.  */\nlocal int gz_fetch(state)\n    gz_statep state;\n{\n    z_streamp strm = &(state->strm);\n\n    do {\n        switch(state->how) {\n        case LOOK:      /* -> LOOK, COPY (only if never GZIP), or GZIP */\n            if (gz_look(state) == -1)\n                return -1;\n            if (state->how == LOOK)\n                return 0;\n            break;\n        case COPY:      /* -> COPY */\n            if (gz_load(state, state->out, state->size << 1, &(state->x.have))\n                    == -1)\n                return -1;\n            state->x.next = state->out;\n            return 0;\n        case GZIP:      /* -> GZIP or LOOK (if end of gzip stream) */\n            strm->avail_out = state->size << 1;\n            strm->next_out = state->out;\n            if (gz_decomp(state) == -1)\n                return -1;\n        }\n    } while (state->x.have == 0 && (!state->eof || strm->avail_in));\n    return 0;\n}\n\n/* Skip len uncompressed bytes of output.  Return -1 on error, 0 on success. */\nlocal int gz_skip(state, len)\n    gz_statep state;\n    z_off64_t len;\n{\n    unsigned n;\n\n    /* skip over len bytes or reach end-of-file, whichever comes first */\n    while (len)\n        /* skip over whatever is in output buffer */\n        if (state->x.have) {\n            n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ?\n                (unsigned)len : state->x.have;\n            state->x.have -= n;\n            state->x.next += n;\n            state->x.pos += n;\n            len -= n;\n        }\n\n        /* output buffer empty -- return if we're at the end of the input */\n        else if (state->eof && state->strm.avail_in == 0)\n            break;\n\n        /* need more data to skip -- load up output buffer */\n        else {\n            /* get more output, looking for header if required */\n            if (gz_fetch(state) == -1)\n                return -1;\n        }\n    return 0;\n}\n\n/* Read len bytes into buf from file, or less than len up to the end of the\n   input.  Return the number of bytes read.  If zero is returned, either the\n   end of file was reached, or there was an error.  state->err must be\n   consulted in that case to determine which. */\nlocal z_size_t gz_read(state, buf, len)\n    gz_statep state;\n    voidp buf;\n    z_size_t len;\n{\n    z_size_t got;\n    unsigned n;\n\n    /* if len is zero, avoid unnecessary operations */\n    if (len == 0)\n        return 0;\n\n    /* process a skip request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_skip(state, state->skip) == -1)\n            return 0;\n    }\n\n    /* get len bytes to buf, or less than len if at the end */\n    got = 0;\n    do {\n        /* set n to the maximum amount of len that fits in an unsigned int */\n        n = -1;\n        if (n > len)\n            n = len;\n\n        /* first just try copying data from the output buffer */\n        if (state->x.have) {\n            if (state->x.have < n)\n                n = state->x.have;\n            memcpy(buf, state->x.next, n);\n            state->x.next += n;\n            state->x.have -= n;\n        }\n\n        /* output buffer empty -- return if we're at the end of the input */\n        else if (state->eof && state->strm.avail_in == 0) {\n            state->past = 1;        /* tried to read past end */\n            break;\n        }\n\n        /* need output data -- for small len or new stream load up our output\n           buffer */\n        else if (state->how == LOOK || n < (state->size << 1)) {\n            /* get more output, looking for header if required */\n            if (gz_fetch(state) == -1)\n                return 0;\n            continue;       /* no progress yet -- go back to copy above */\n            /* the copy above assures that we will leave with space in the\n               output buffer, allowing at least one gzungetc() to succeed */\n        }\n\n        /* large len -- read directly into user buffer */\n        else if (state->how == COPY) {      /* read directly */\n            if (gz_load(state, (unsigned char *)buf, n, &n) == -1)\n                return 0;\n        }\n\n        /* large len -- decompress directly into user buffer */\n        else {  /* state->how == GZIP */\n            state->strm.avail_out = n;\n            state->strm.next_out = (unsigned char *)buf;\n            if (gz_decomp(state) == -1)\n                return 0;\n            n = state->x.have;\n            state->x.have = 0;\n        }\n\n        /* update progress */\n        len -= n;\n        buf = (char *)buf + n;\n        got += n;\n        state->x.pos += n;\n    } while (len);\n\n    /* return number of bytes read into user buffer */\n    return got;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzread(file, buf, len)\n    gzFile file;\n    voidp buf;\n    unsigned len;\n{\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n\n    /* check that we're reading and that there's no (serious) error */\n    if (state->mode != GZ_READ ||\n            (state->err != Z_OK && state->err != Z_BUF_ERROR))\n        return -1;\n\n    /* since an int is returned, make sure len fits in one, otherwise return\n       with an error (this avoids a flaw in the interface) */\n    if ((int)len < 0) {\n        gz_error(state, Z_STREAM_ERROR, \"request does not fit in an int\");\n        return -1;\n    }\n\n    /* read len or fewer bytes to buf */\n    len = gz_read(state, buf, len);\n\n    /* check for an error */\n    if (len == 0 && state->err != Z_OK && state->err != Z_BUF_ERROR)\n        return -1;\n\n    /* return the number of bytes read (this is assured to fit in an int) */\n    return (int)len;\n}\n\n/* -- see zlib.h -- */\nz_size_t ZEXPORT gzfread(buf, size, nitems, file)\n    voidp buf;\n    z_size_t size;\n    z_size_t nitems;\n    gzFile file;\n{\n    z_size_t len;\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return 0;\n    state = (gz_statep)file;\n\n    /* check that we're reading and that there's no (serious) error */\n    if (state->mode != GZ_READ ||\n            (state->err != Z_OK && state->err != Z_BUF_ERROR))\n        return 0;\n\n    /* compute bytes to read -- error on overflow */\n    len = nitems * size;\n    if (size && len / size != nitems) {\n        gz_error(state, Z_STREAM_ERROR, \"request does not fit in a size_t\");\n        return 0;\n    }\n\n    /* read len or fewer bytes to buf, return the number of full items read */\n    return len ? gz_read(state, buf, len) / size : 0;\n}\n\n/* -- see zlib.h -- */\n#ifdef Z_PREFIX_SET\n#  undef z_gzgetc\n#else\n#  undef gzgetc\n#endif\nint ZEXPORT gzgetc(file)\n    gzFile file;\n{\n    int ret;\n    unsigned char buf[1];\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n\n    /* check that we're reading and that there's no (serious) error */\n    if (state->mode != GZ_READ ||\n        (state->err != Z_OK && state->err != Z_BUF_ERROR))\n        return -1;\n\n    /* try output buffer (no need to check for skip request) */\n    if (state->x.have) {\n        state->x.have--;\n        state->x.pos++;\n        return *(state->x.next)++;\n    }\n\n    /* nothing there -- try gz_read() */\n    ret = gz_read(state, buf, 1);\n    return ret < 1 ? -1 : buf[0];\n}\n\nint ZEXPORT gzgetc_(file)\ngzFile file;\n{\n    return gzgetc(file);\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzungetc(c, file)\n    int c;\n    gzFile file;\n{\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n\n    /* check that we're reading and that there's no (serious) error */\n    if (state->mode != GZ_READ ||\n        (state->err != Z_OK && state->err != Z_BUF_ERROR))\n        return -1;\n\n    /* process a skip request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_skip(state, state->skip) == -1)\n            return -1;\n    }\n\n    /* can't push EOF */\n    if (c < 0)\n        return -1;\n\n    /* if output buffer empty, put byte at end (allows more pushing) */\n    if (state->x.have == 0) {\n        state->x.have = 1;\n        state->x.next = state->out + (state->size << 1) - 1;\n        state->x.next[0] = (unsigned char)c;\n        state->x.pos--;\n        state->past = 0;\n        return c;\n    }\n\n    /* if no room, give up (must have already done a gzungetc()) */\n    if (state->x.have == (state->size << 1)) {\n        gz_error(state, Z_DATA_ERROR, \"out of room to push characters\");\n        return -1;\n    }\n\n    /* slide output data if needed and insert byte before existing data */\n    if (state->x.next == state->out) {\n        unsigned char *src = state->out + state->x.have;\n        unsigned char *dest = state->out + (state->size << 1);\n        while (src > state->out)\n            *--dest = *--src;\n        state->x.next = dest;\n    }\n    state->x.have++;\n    state->x.next--;\n    state->x.next[0] = (unsigned char)c;\n    state->x.pos--;\n    state->past = 0;\n    return c;\n}\n\n/* -- see zlib.h -- */\nchar * ZEXPORT gzgets(file, buf, len)\n    gzFile file;\n    char *buf;\n    int len;\n{\n    unsigned left, n;\n    char *str;\n    unsigned char *eol;\n    gz_statep state;\n\n    /* check parameters and get internal structure */\n    if (file == NULL || buf == NULL || len < 1)\n        return NULL;\n    state = (gz_statep)file;\n\n    /* check that we're reading and that there's no (serious) error */\n    if (state->mode != GZ_READ ||\n        (state->err != Z_OK && state->err != Z_BUF_ERROR))\n        return NULL;\n\n    /* process a skip request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_skip(state, state->skip) == -1)\n            return NULL;\n    }\n\n    /* copy output bytes up to new line or len - 1, whichever comes first --\n       append a terminating zero to the string (we don't check for a zero in\n       the contents, let the user worry about that) */\n    str = buf;\n    left = (unsigned)len - 1;\n    if (left) do {\n        /* assure that something is in the output buffer */\n        if (state->x.have == 0 && gz_fetch(state) == -1)\n            return NULL;                /* error */\n        if (state->x.have == 0) {       /* end of file */\n            state->past = 1;            /* read past end */\n            break;                      /* return what we have */\n        }\n\n        /* look for end-of-line in current output buffer */\n        n = state->x.have > left ? left : state->x.have;\n        eol = (unsigned char *)memchr(state->x.next, '\\n', n);\n        if (eol != NULL)\n            n = (unsigned)(eol - state->x.next) + 1;\n\n        /* copy through end-of-line, or remainder if not found */\n        memcpy(buf, state->x.next, n);\n        state->x.have -= n;\n        state->x.next += n;\n        state->x.pos += n;\n        left -= n;\n        buf += n;\n    } while (left && eol == NULL);\n\n    /* return terminated string, or if nothing, end of file */\n    if (buf == str)\n        return NULL;\n    buf[0] = 0;\n    return str;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzdirect(file)\n    gzFile file;\n{\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return 0;\n    state = (gz_statep)file;\n\n    /* if the state is not known, but we can find out, then do so (this is\n       mainly for right after a gzopen() or gzdopen()) */\n    if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0)\n        (void)gz_look(state);\n\n    /* return 1 if transparent, 0 if processing a gzip stream */\n    return state->direct;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzclose_r(file)\n    gzFile file;\n{\n    int ret, err;\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return Z_STREAM_ERROR;\n    state = (gz_statep)file;\n\n    /* check that we're reading */\n    if (state->mode != GZ_READ)\n        return Z_STREAM_ERROR;\n\n    /* free memory and close file */\n    if (state->size) {\n        inflateEnd(&(state->strm));\n        free(state->out);\n        free(state->in);\n    }\n    err = state->err == Z_BUF_ERROR ? Z_BUF_ERROR : Z_OK;\n    gz_error(state, Z_OK, NULL);\n    free(state->path);\n    ret = close(state->fd);\n    free(state);\n    return ret ? Z_ERRNO : err;\n}\n"
  },
  {
    "path": "jsb_build/websockets/zlib/gzwrite.c",
    "content": "/* gzwrite.c -- zlib functions for writing gzip files\n * Copyright (C) 2004-2017 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n#include \"gzguts.h\"\n\n/* Local functions */\nlocal int gz_init OF((gz_statep));\nlocal int gz_comp OF((gz_statep, int));\nlocal int gz_zero OF((gz_statep, z_off64_t));\nlocal z_size_t gz_write OF((gz_statep, voidpc, z_size_t));\n\n/* Initialize state for writing a gzip file.  Mark initialization by setting\n   state->size to non-zero.  Return -1 on a memory allocation failure, or 0 on\n   success. */\nlocal int gz_init(state)\n    gz_statep state;\n{\n    int ret;\n    z_streamp strm = &(state->strm);\n\n    /* allocate input buffer (double size for gzprintf) */\n    state->in = (unsigned char *)malloc(state->want << 1);\n    if (state->in == NULL) {\n        gz_error(state, Z_MEM_ERROR, \"out of memory\");\n        return -1;\n    }\n\n    /* only need output buffer and deflate state if compressing */\n    if (!state->direct) {\n        /* allocate output buffer */\n        state->out = (unsigned char *)malloc(state->want);\n        if (state->out == NULL) {\n            free(state->in);\n            gz_error(state, Z_MEM_ERROR, \"out of memory\");\n            return -1;\n        }\n\n        /* allocate deflate memory, set up for gzip compression */\n        strm->zalloc = Z_NULL;\n        strm->zfree = Z_NULL;\n        strm->opaque = Z_NULL;\n        ret = deflateInit2(strm, state->level, Z_DEFLATED,\n                           MAX_WBITS + 16, DEF_MEM_LEVEL, state->strategy);\n        if (ret != Z_OK) {\n            free(state->out);\n            free(state->in);\n            gz_error(state, Z_MEM_ERROR, \"out of memory\");\n            return -1;\n        }\n        strm->next_in = NULL;\n    }\n\n    /* mark state as initialized */\n    state->size = state->want;\n\n    /* initialize write buffer if compressing */\n    if (!state->direct) {\n        strm->avail_out = state->size;\n        strm->next_out = state->out;\n        state->x.next = strm->next_out;\n    }\n    return 0;\n}\n\n/* Compress whatever is at avail_in and next_in and write to the output file.\n   Return -1 if there is an error writing to the output file or if gz_init()\n   fails to allocate memory, otherwise 0.  flush is assumed to be a valid\n   deflate() flush value.  If flush is Z_FINISH, then the deflate() state is\n   reset to start a new gzip stream.  If gz->direct is true, then simply write\n   to the output file without compressing, and ignore flush. */\nlocal int gz_comp(state, flush)\n    gz_statep state;\n    int flush;\n{\n    int ret, writ;\n    unsigned have, put, max = ((unsigned)-1 >> 2) + 1;\n    z_streamp strm = &(state->strm);\n\n    /* allocate memory if this is the first time through */\n    if (state->size == 0 && gz_init(state) == -1)\n        return -1;\n\n    /* write directly if requested */\n    if (state->direct) {\n        while (strm->avail_in) {\n            put = strm->avail_in > max ? max : strm->avail_in;\n            writ = write(state->fd, strm->next_in, put);\n            if (writ < 0) {\n                gz_error(state, Z_ERRNO, zstrerror());\n                return -1;\n            }\n            strm->avail_in -= (unsigned)writ;\n            strm->next_in += writ;\n        }\n        return 0;\n    }\n\n    /* run deflate() on provided input until it produces no more output */\n    ret = Z_OK;\n    do {\n        /* write out current buffer contents if full, or if flushing, but if\n           doing Z_FINISH then don't write until we get to Z_STREAM_END */\n        if (strm->avail_out == 0 || (flush != Z_NO_FLUSH &&\n            (flush != Z_FINISH || ret == Z_STREAM_END))) {\n            while (strm->next_out > state->x.next) {\n                put = strm->next_out - state->x.next > (int)max ? max :\n                      (unsigned)(strm->next_out - state->x.next);\n                writ = write(state->fd, state->x.next, put);\n                if (writ < 0) {\n                    gz_error(state, Z_ERRNO, zstrerror());\n                    return -1;\n                }\n                state->x.next += writ;\n            }\n            if (strm->avail_out == 0) {\n                strm->avail_out = state->size;\n                strm->next_out = state->out;\n                state->x.next = state->out;\n            }\n        }\n\n        /* compress */\n        have = strm->avail_out;\n        ret = deflate(strm, flush);\n        if (ret == Z_STREAM_ERROR) {\n            gz_error(state, Z_STREAM_ERROR,\n                      \"internal error: deflate stream corrupt\");\n            return -1;\n        }\n        have -= strm->avail_out;\n    } while (have);\n\n    /* if that completed a deflate stream, allow another to start */\n    if (flush == Z_FINISH)\n        deflateReset(strm);\n\n    /* all done, no errors */\n    return 0;\n}\n\n/* Compress len zeros to output.  Return -1 on a write error or memory\n   allocation failure by gz_comp(), or 0 on success. */\nlocal int gz_zero(state, len)\n    gz_statep state;\n    z_off64_t len;\n{\n    int first;\n    unsigned n;\n    z_streamp strm = &(state->strm);\n\n    /* consume whatever's left in the input buffer */\n    if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)\n        return -1;\n\n    /* compress len zeros (len guaranteed > 0) */\n    first = 1;\n    while (len) {\n        n = GT_OFF(state->size) || (z_off64_t)state->size > len ?\n            (unsigned)len : state->size;\n        if (first) {\n            memset(state->in, 0, n);\n            first = 0;\n        }\n        strm->avail_in = n;\n        strm->next_in = state->in;\n        state->x.pos += n;\n        if (gz_comp(state, Z_NO_FLUSH) == -1)\n            return -1;\n        len -= n;\n    }\n    return 0;\n}\n\n/* Write len bytes from buf to file.  Return the number of bytes written.  If\n   the returned value is less than len, then there was an error. */\nlocal z_size_t gz_write(state, buf, len)\n    gz_statep state;\n    voidpc buf;\n    z_size_t len;\n{\n    z_size_t put = len;\n\n    /* if len is zero, avoid unnecessary operations */\n    if (len == 0)\n        return 0;\n\n    /* allocate memory if this is the first time through */\n    if (state->size == 0 && gz_init(state) == -1)\n        return 0;\n\n    /* check for seek request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_zero(state, state->skip) == -1)\n            return 0;\n    }\n\n    /* for small len, copy to input buffer, otherwise compress directly */\n    if (len < state->size) {\n        /* copy to input buffer, compress when full */\n        do {\n            unsigned have, copy;\n\n            if (state->strm.avail_in == 0)\n                state->strm.next_in = state->in;\n            have = (unsigned)((state->strm.next_in + state->strm.avail_in) -\n                              state->in);\n            copy = state->size - have;\n            if (copy > len)\n                copy = len;\n            memcpy(state->in + have, buf, copy);\n            state->strm.avail_in += copy;\n            state->x.pos += copy;\n            buf = (const char *)buf + copy;\n            len -= copy;\n            if (len && gz_comp(state, Z_NO_FLUSH) == -1)\n                return 0;\n        } while (len);\n    }\n    else {\n        /* consume whatever's left in the input buffer */\n        if (state->strm.avail_in && gz_comp(state, Z_NO_FLUSH) == -1)\n            return 0;\n\n        /* directly compress user buffer to file */\n        state->strm.next_in = (z_const Bytef *)buf;\n        do {\n            unsigned n = (unsigned)-1;\n            if (n > len)\n                n = len;\n            state->strm.avail_in = n;\n            state->x.pos += n;\n            if (gz_comp(state, Z_NO_FLUSH) == -1)\n                return 0;\n            len -= n;\n        } while (len);\n    }\n\n    /* input was all buffered or compressed */\n    return put;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzwrite(file, buf, len)\n    gzFile file;\n    voidpc buf;\n    unsigned len;\n{\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return 0;\n    state = (gz_statep)file;\n\n    /* check that we're writing and that there's no error */\n    if (state->mode != GZ_WRITE || state->err != Z_OK)\n        return 0;\n\n    /* since an int is returned, make sure len fits in one, otherwise return\n       with an error (this avoids a flaw in the interface) */\n    if ((int)len < 0) {\n        gz_error(state, Z_DATA_ERROR, \"requested length does not fit in int\");\n        return 0;\n    }\n\n    /* write len bytes from buf (the return value will fit in an int) */\n    return (int)gz_write(state, buf, len);\n}\n\n/* -- see zlib.h -- */\nz_size_t ZEXPORT gzfwrite(buf, size, nitems, file)\n    voidpc buf;\n    z_size_t size;\n    z_size_t nitems;\n    gzFile file;\n{\n    z_size_t len;\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return 0;\n    state = (gz_statep)file;\n\n    /* check that we're writing and that there's no error */\n    if (state->mode != GZ_WRITE || state->err != Z_OK)\n        return 0;\n\n    /* compute bytes to read -- error on overflow */\n    len = nitems * size;\n    if (size && len / size != nitems) {\n        gz_error(state, Z_STREAM_ERROR, \"request does not fit in a size_t\");\n        return 0;\n    }\n\n    /* write len bytes to buf, return the number of full items written */\n    return len ? gz_write(state, buf, len) / size : 0;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzputc(file, c)\n    gzFile file;\n    int c;\n{\n    unsigned have;\n    unsigned char buf[1];\n    gz_statep state;\n    z_streamp strm;\n\n    /* get internal structure */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n    strm = &(state->strm);\n\n    /* check that we're writing and that there's no error */\n    if (state->mode != GZ_WRITE || state->err != Z_OK)\n        return -1;\n\n    /* check for seek request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_zero(state, state->skip) == -1)\n            return -1;\n    }\n\n    /* try writing to input buffer for speed (state->size == 0 if buffer not\n       initialized) */\n    if (state->size) {\n        if (strm->avail_in == 0)\n            strm->next_in = state->in;\n        have = (unsigned)((strm->next_in + strm->avail_in) - state->in);\n        if (have < state->size) {\n            state->in[have] = (unsigned char)c;\n            strm->avail_in++;\n            state->x.pos++;\n            return c & 0xff;\n        }\n    }\n\n    /* no room in buffer or not initialized, use gz_write() */\n    buf[0] = (unsigned char)c;\n    if (gz_write(state, buf, 1) != 1)\n        return -1;\n    return c & 0xff;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzputs(file, str)\n    gzFile file;\n    const char *str;\n{\n    int ret;\n    z_size_t len;\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n\n    /* check that we're writing and that there's no error */\n    if (state->mode != GZ_WRITE || state->err != Z_OK)\n        return -1;\n\n    /* write string */\n    len = strlen(str);\n    ret = gz_write(state, str, len);\n    return ret == 0 && len != 0 ? -1 : ret;\n}\n\n#if defined(STDC) || defined(Z_HAVE_STDARG_H)\n#include <stdarg.h>\n\n/* -- see zlib.h -- */\nint ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va)\n{\n    int len;\n    unsigned left;\n    char *next;\n    gz_statep state;\n    z_streamp strm;\n\n    /* get internal structure */\n    if (file == NULL)\n        return Z_STREAM_ERROR;\n    state = (gz_statep)file;\n    strm = &(state->strm);\n\n    /* check that we're writing and that there's no error */\n    if (state->mode != GZ_WRITE || state->err != Z_OK)\n        return Z_STREAM_ERROR;\n\n    /* make sure we have some buffer space */\n    if (state->size == 0 && gz_init(state) == -1)\n        return state->err;\n\n    /* check for seek request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_zero(state, state->skip) == -1)\n            return state->err;\n    }\n\n    /* do the printf() into the input buffer, put length in len -- the input\n       buffer is double-sized just for this function, so there is guaranteed to\n       be state->size bytes available after the current contents */\n    if (strm->avail_in == 0)\n        strm->next_in = state->in;\n    next = (char *)(state->in + (strm->next_in - state->in) + strm->avail_in);\n    next[state->size - 1] = 0;\n#ifdef NO_vsnprintf\n#  ifdef HAS_vsprintf_void\n    (void)vsprintf(next, format, va);\n    for (len = 0; len < state->size; len++)\n        if (next[len] == 0) break;\n#  else\n    len = vsprintf(next, format, va);\n#  endif\n#else\n#  ifdef HAS_vsnprintf_void\n    (void)vsnprintf(next, state->size, format, va);\n    len = strlen(next);\n#  else\n    len = vsnprintf(next, state->size, format, va);\n#  endif\n#endif\n\n    /* check that printf() results fit in buffer */\n    if (len == 0 || (unsigned)len >= state->size || next[state->size - 1] != 0)\n        return 0;\n\n    /* update buffer and position, compress first half if past that */\n    strm->avail_in += (unsigned)len;\n    state->x.pos += len;\n    if (strm->avail_in >= state->size) {\n        left = strm->avail_in - state->size;\n        strm->avail_in = state->size;\n        if (gz_comp(state, Z_NO_FLUSH) == -1)\n            return state->err;\n        memcpy(state->in, state->in + state->size, left);\n        strm->next_in = state->in;\n        strm->avail_in = left;\n    }\n    return len;\n}\n\nint ZEXPORTVA gzprintf(gzFile file, const char *format, ...)\n{\n    va_list va;\n    int ret;\n\n    va_start(va, format);\n    ret = gzvprintf(file, format, va);\n    va_end(va);\n    return ret;\n}\n\n#else /* !STDC && !Z_HAVE_STDARG_H */\n\n/* -- see zlib.h -- */\nint ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,\n                       a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)\n    gzFile file;\n    const char *format;\n    int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,\n        a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;\n{\n    unsigned len, left;\n    char *next;\n    gz_statep state;\n    z_streamp strm;\n\n    /* get internal structure */\n    if (file == NULL)\n        return Z_STREAM_ERROR;\n    state = (gz_statep)file;\n    strm = &(state->strm);\n\n    /* check that can really pass pointer in ints */\n    if (sizeof(int) != sizeof(void *))\n        return Z_STREAM_ERROR;\n\n    /* check that we're writing and that there's no error */\n    if (state->mode != GZ_WRITE || state->err != Z_OK)\n        return Z_STREAM_ERROR;\n\n    /* make sure we have some buffer space */\n    if (state->size == 0 && gz_init(state) == -1)\n        return state->error;\n\n    /* check for seek request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_zero(state, state->skip) == -1)\n            return state->error;\n    }\n\n    /* do the printf() into the input buffer, put length in len -- the input\n       buffer is double-sized just for this function, so there is guaranteed to\n       be state->size bytes available after the current contents */\n    if (strm->avail_in == 0)\n        strm->next_in = state->in;\n    next = (char *)(strm->next_in + strm->avail_in);\n    next[state->size - 1] = 0;\n#ifdef NO_snprintf\n#  ifdef HAS_sprintf_void\n    sprintf(next, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12,\n            a13, a14, a15, a16, a17, a18, a19, a20);\n    for (len = 0; len < size; len++)\n        if (next[len] == 0)\n            break;\n#  else\n    len = sprintf(next, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11,\n                  a12, a13, a14, a15, a16, a17, a18, a19, a20);\n#  endif\n#else\n#  ifdef HAS_snprintf_void\n    snprintf(next, state->size, format, a1, a2, a3, a4, a5, a6, a7, a8, a9,\n             a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);\n    len = strlen(next);\n#  else\n    len = snprintf(next, state->size, format, a1, a2, a3, a4, a5, a6, a7, a8,\n                   a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);\n#  endif\n#endif\n\n    /* check that printf() results fit in buffer */\n    if (len == 0 || len >= state->size || next[state->size - 1] != 0)\n        return 0;\n\n    /* update buffer and position, compress first half if past that */\n    strm->avail_in += len;\n    state->x.pos += len;\n    if (strm->avail_in >= state->size) {\n        left = strm->avail_in - state->size;\n        strm->avail_in = state->size;\n        if (gz_comp(state, Z_NO_FLUSH) == -1)\n            return state->err;\n        memcpy(state->in, state->in + state->size, left);\n        strm->next_in = state->in;\n        strm->avail_in = left;\n    }\n    return (int)len;\n}\n\n#endif\n\n/* -- see zlib.h -- */\nint ZEXPORT gzflush(file, flush)\n    gzFile file;\n    int flush;\n{\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return Z_STREAM_ERROR;\n    state = (gz_statep)file;\n\n    /* check that we're writing and that there's no error */\n    if (state->mode != GZ_WRITE || state->err != Z_OK)\n        return Z_STREAM_ERROR;\n\n    /* check flush parameter */\n    if (flush < 0 || flush > Z_FINISH)\n        return Z_STREAM_ERROR;\n\n    /* check for seek request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_zero(state, state->skip) == -1)\n            return state->err;\n    }\n\n    /* compress remaining data with requested flush */\n    (void)gz_comp(state, flush);\n    return state->err;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzsetparams(file, level, strategy)\n    gzFile file;\n    int level;\n    int strategy;\n{\n    gz_statep state;\n    z_streamp strm;\n\n    /* get internal structure */\n    if (file == NULL)\n        return Z_STREAM_ERROR;\n    state = (gz_statep)file;\n    strm = &(state->strm);\n\n    /* check that we're writing and that there's no error */\n    if (state->mode != GZ_WRITE || state->err != Z_OK)\n        return Z_STREAM_ERROR;\n\n    /* if no change is requested, then do nothing */\n    if (level == state->level && strategy == state->strategy)\n        return Z_OK;\n\n    /* check for seek request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_zero(state, state->skip) == -1)\n            return state->err;\n    }\n\n    /* change compression parameters for subsequent input */\n    if (state->size) {\n        /* flush previous input with previous parameters before changing */\n        if (strm->avail_in && gz_comp(state, Z_BLOCK) == -1)\n            return state->err;\n        deflateParams(strm, level, strategy);\n    }\n    state->level = level;\n    state->strategy = strategy;\n    return Z_OK;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzclose_w(file)\n    gzFile file;\n{\n    int ret = Z_OK;\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return Z_STREAM_ERROR;\n    state = (gz_statep)file;\n\n    /* check that we're writing */\n    if (state->mode != GZ_WRITE)\n        return Z_STREAM_ERROR;\n\n    /* check for seek request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_zero(state, state->skip) == -1)\n            ret = state->err;\n    }\n\n    /* flush, free memory, and close file */\n    if (gz_comp(state, Z_FINISH) == -1)\n        ret = state->err;\n    if (state->size) {\n        if (!state->direct) {\n            (void)deflateEnd(&(state->strm));\n            free(state->out);\n        }\n        free(state->in);\n    }\n    gz_error(state, Z_OK, NULL);\n    free(state->path);\n    if (close(state->fd) == -1)\n        ret = Z_ERRNO;\n    free(state);\n    return ret;\n}\n"
  },
  {
    "path": "jsb_build/websockets/zlib/infback.c",
    "content": "/* infback.c -- inflate using a call-back interface\n * Copyright (C) 1995-2016 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/*\n   This code is largely copied from inflate.c.  Normally either infback.o or\n   inflate.o would be linked into an application--not both.  The interface\n   with inffast.c is retained so that optimized assembler-coded versions of\n   inflate_fast() can be used with either inflate.c or infback.c.\n */\n\n#include \"zutil.h\"\n#include \"inftrees.h\"\n#include \"inflate.h\"\n#include \"inffast.h\"\n\n/* function prototypes */\nlocal void fixedtables OF((struct inflate_state FAR *state));\n\n/*\n   strm provides memory allocation functions in zalloc and zfree, or\n   Z_NULL to use the library memory allocation functions.\n\n   windowBits is in the range 8..15, and window is a user-supplied\n   window and output buffer that is 2**windowBits bytes.\n */\nint ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size)\nz_streamp strm;\nint windowBits;\nunsigned char FAR *window;\nconst char *version;\nint stream_size;\n{\n    struct inflate_state FAR *state;\n\n    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||\n        stream_size != (int)(sizeof(z_stream)))\n        return Z_VERSION_ERROR;\n    if (strm == Z_NULL || window == Z_NULL ||\n        windowBits < 8 || windowBits > 15)\n        return Z_STREAM_ERROR;\n    strm->msg = Z_NULL;                 /* in case we return an error */\n    if (strm->zalloc == (alloc_func)0) {\n#ifdef Z_SOLO\n        return Z_STREAM_ERROR;\n#else\n        strm->zalloc = zcalloc;\n        strm->opaque = (voidpf)0;\n#endif\n    }\n    if (strm->zfree == (free_func)0)\n#ifdef Z_SOLO\n        return Z_STREAM_ERROR;\n#else\n    strm->zfree = zcfree;\n#endif\n    state = (struct inflate_state FAR *)ZALLOC(strm, 1,\n                                               sizeof(struct inflate_state));\n    if (state == Z_NULL) return Z_MEM_ERROR;\n    Tracev((stderr, \"inflate: allocated\\n\"));\n    strm->state = (struct internal_state FAR *)state;\n    state->dmax = 32768U;\n    state->wbits = (uInt)windowBits;\n    state->wsize = 1U << windowBits;\n    state->window = window;\n    state->wnext = 0;\n    state->whave = 0;\n    return Z_OK;\n}\n\n/*\n   Return state with length and distance decoding tables and index sizes set to\n   fixed code decoding.  Normally this returns fixed tables from inffixed.h.\n   If BUILDFIXED is defined, then instead this routine builds the tables the\n   first time it's called, and returns those tables the first time and\n   thereafter.  This reduces the size of the code by about 2K bytes, in\n   exchange for a little execution time.  However, BUILDFIXED should not be\n   used for threaded applications, since the rewriting of the tables and virgin\n   may not be thread-safe.\n */\nlocal void fixedtables(state)\nstruct inflate_state FAR *state;\n{\n#ifdef BUILDFIXED\n    static int virgin = 1;\n    static code *lenfix, *distfix;\n    static code fixed[544];\n\n    /* build fixed huffman tables if first call (may not be thread safe) */\n    if (virgin) {\n        unsigned sym, bits;\n        static code *next;\n\n        /* literal/length table */\n        sym = 0;\n        while (sym < 144) state->lens[sym++] = 8;\n        while (sym < 256) state->lens[sym++] = 9;\n        while (sym < 280) state->lens[sym++] = 7;\n        while (sym < 288) state->lens[sym++] = 8;\n        next = fixed;\n        lenfix = next;\n        bits = 9;\n        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);\n\n        /* distance table */\n        sym = 0;\n        while (sym < 32) state->lens[sym++] = 5;\n        distfix = next;\n        bits = 5;\n        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);\n\n        /* do this just once */\n        virgin = 0;\n    }\n#else /* !BUILDFIXED */\n#   include \"inffixed.h\"\n#endif /* BUILDFIXED */\n    state->lencode = lenfix;\n    state->lenbits = 9;\n    state->distcode = distfix;\n    state->distbits = 5;\n}\n\n/* Macros for inflateBack(): */\n\n/* Load returned state from inflate_fast() */\n#define LOAD() \\\n    do { \\\n        put = strm->next_out; \\\n        left = strm->avail_out; \\\n        next = strm->next_in; \\\n        have = strm->avail_in; \\\n        hold = state->hold; \\\n        bits = state->bits; \\\n    } while (0)\n\n/* Set state from registers for inflate_fast() */\n#define RESTORE() \\\n    do { \\\n        strm->next_out = put; \\\n        strm->avail_out = left; \\\n        strm->next_in = next; \\\n        strm->avail_in = have; \\\n        state->hold = hold; \\\n        state->bits = bits; \\\n    } while (0)\n\n/* Clear the input bit accumulator */\n#define INITBITS() \\\n    do { \\\n        hold = 0; \\\n        bits = 0; \\\n    } while (0)\n\n/* Assure that some input is available.  If input is requested, but denied,\n   then return a Z_BUF_ERROR from inflateBack(). */\n#define PULL() \\\n    do { \\\n        if (have == 0) { \\\n            have = in(in_desc, &next); \\\n            if (have == 0) { \\\n                next = Z_NULL; \\\n                ret = Z_BUF_ERROR; \\\n                goto inf_leave; \\\n            } \\\n        } \\\n    } while (0)\n\n/* Get a byte of input into the bit accumulator, or return from inflateBack()\n   with an error if there is no input available. */\n#define PULLBYTE() \\\n    do { \\\n        PULL(); \\\n        have--; \\\n        hold += (unsigned long)(*next++) << bits; \\\n        bits += 8; \\\n    } while (0)\n\n/* Assure that there are at least n bits in the bit accumulator.  If there is\n   not enough available input to do that, then return from inflateBack() with\n   an error. */\n#define NEEDBITS(n) \\\n    do { \\\n        while (bits < (unsigned)(n)) \\\n            PULLBYTE(); \\\n    } while (0)\n\n/* Return the low n bits of the bit accumulator (n < 16) */\n#define BITS(n) \\\n    ((unsigned)hold & ((1U << (n)) - 1))\n\n/* Remove n bits from the bit accumulator */\n#define DROPBITS(n) \\\n    do { \\\n        hold >>= (n); \\\n        bits -= (unsigned)(n); \\\n    } while (0)\n\n/* Remove zero to seven bits as needed to go to a byte boundary */\n#define BYTEBITS() \\\n    do { \\\n        hold >>= bits & 7; \\\n        bits -= bits & 7; \\\n    } while (0)\n\n/* Assure that some output space is available, by writing out the window\n   if it's full.  If the write fails, return from inflateBack() with a\n   Z_BUF_ERROR. */\n#define ROOM() \\\n    do { \\\n        if (left == 0) { \\\n            put = state->window; \\\n            left = state->wsize; \\\n            state->whave = left; \\\n            if (out(out_desc, put, left)) { \\\n                ret = Z_BUF_ERROR; \\\n                goto inf_leave; \\\n            } \\\n        } \\\n    } while (0)\n\n/*\n   strm provides the memory allocation functions and window buffer on input,\n   and provides information on the unused input on return.  For Z_DATA_ERROR\n   returns, strm will also provide an error message.\n\n   in() and out() are the call-back input and output functions.  When\n   inflateBack() needs more input, it calls in().  When inflateBack() has\n   filled the window with output, or when it completes with data in the\n   window, it calls out() to write out the data.  The application must not\n   change the provided input until in() is called again or inflateBack()\n   returns.  The application must not change the window/output buffer until\n   inflateBack() returns.\n\n   in() and out() are called with a descriptor parameter provided in the\n   inflateBack() call.  This parameter can be a structure that provides the\n   information required to do the read or write, as well as accumulated\n   information on the input and output such as totals and check values.\n\n   in() should return zero on failure.  out() should return non-zero on\n   failure.  If either in() or out() fails, than inflateBack() returns a\n   Z_BUF_ERROR.  strm->next_in can be checked for Z_NULL to see whether it\n   was in() or out() that caused in the error.  Otherwise,  inflateBack()\n   returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format\n   error, or Z_MEM_ERROR if it could not allocate memory for the state.\n   inflateBack() can also return Z_STREAM_ERROR if the input parameters\n   are not correct, i.e. strm is Z_NULL or the state was not initialized.\n */\nint ZEXPORT inflateBack(strm, in, in_desc, out, out_desc)\nz_streamp strm;\nin_func in;\nvoid FAR *in_desc;\nout_func out;\nvoid FAR *out_desc;\n{\n    struct inflate_state FAR *state;\n    z_const unsigned char FAR *next;    /* next input */\n    unsigned char FAR *put;     /* next output */\n    unsigned have, left;        /* available input and output */\n    unsigned long hold;         /* bit buffer */\n    unsigned bits;              /* bits in bit buffer */\n    unsigned copy;              /* number of stored or match bytes to copy */\n    unsigned char FAR *from;    /* where to copy match bytes from */\n    code here;                  /* current decoding table entry */\n    code last;                  /* parent table entry */\n    unsigned len;               /* length to copy for repeats, bits to drop */\n    int ret;                    /* return code */\n    static const unsigned short order[19] = /* permutation of code lengths */\n        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};\n\n    /* Check that the strm exists and that the state was initialized */\n    if (strm == Z_NULL || strm->state == Z_NULL)\n        return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n\n    /* Reset the state */\n    strm->msg = Z_NULL;\n    state->mode = TYPE;\n    state->last = 0;\n    state->whave = 0;\n    next = strm->next_in;\n    have = next != Z_NULL ? strm->avail_in : 0;\n    hold = 0;\n    bits = 0;\n    put = state->window;\n    left = state->wsize;\n\n    /* Inflate until end of block marked as last */\n    for (;;)\n        switch (state->mode) {\n        case TYPE:\n            /* determine and dispatch block type */\n            if (state->last) {\n                BYTEBITS();\n                state->mode = DONE;\n                break;\n            }\n            NEEDBITS(3);\n            state->last = BITS(1);\n            DROPBITS(1);\n            switch (BITS(2)) {\n            case 0:                             /* stored block */\n                Tracev((stderr, \"inflate:     stored block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = STORED;\n                break;\n            case 1:                             /* fixed block */\n                fixedtables(state);\n                Tracev((stderr, \"inflate:     fixed codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = LEN;              /* decode codes */\n                break;\n            case 2:                             /* dynamic block */\n                Tracev((stderr, \"inflate:     dynamic codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = TABLE;\n                break;\n            case 3:\n                strm->msg = (char *)\"invalid block type\";\n                state->mode = BAD;\n            }\n            DROPBITS(2);\n            break;\n\n        case STORED:\n            /* get and verify stored block length */\n            BYTEBITS();                         /* go to byte boundary */\n            NEEDBITS(32);\n            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {\n                strm->msg = (char *)\"invalid stored block lengths\";\n                state->mode = BAD;\n                break;\n            }\n            state->length = (unsigned)hold & 0xffff;\n            Tracev((stderr, \"inflate:       stored length %u\\n\",\n                    state->length));\n            INITBITS();\n\n            /* copy stored block from input to output */\n            while (state->length != 0) {\n                copy = state->length;\n                PULL();\n                ROOM();\n                if (copy > have) copy = have;\n                if (copy > left) copy = left;\n                zmemcpy(put, next, copy);\n                have -= copy;\n                next += copy;\n                left -= copy;\n                put += copy;\n                state->length -= copy;\n            }\n            Tracev((stderr, \"inflate:       stored end\\n\"));\n            state->mode = TYPE;\n            break;\n\n        case TABLE:\n            /* get dynamic table entries descriptor */\n            NEEDBITS(14);\n            state->nlen = BITS(5) + 257;\n            DROPBITS(5);\n            state->ndist = BITS(5) + 1;\n            DROPBITS(5);\n            state->ncode = BITS(4) + 4;\n            DROPBITS(4);\n#ifndef PKZIP_BUG_WORKAROUND\n            if (state->nlen > 286 || state->ndist > 30) {\n                strm->msg = (char *)\"too many length or distance symbols\";\n                state->mode = BAD;\n                break;\n            }\n#endif\n            Tracev((stderr, \"inflate:       table sizes ok\\n\"));\n\n            /* get code length code lengths (not a typo) */\n            state->have = 0;\n            while (state->have < state->ncode) {\n                NEEDBITS(3);\n                state->lens[order[state->have++]] = (unsigned short)BITS(3);\n                DROPBITS(3);\n            }\n            while (state->have < 19)\n                state->lens[order[state->have++]] = 0;\n            state->next = state->codes;\n            state->lencode = (code const FAR *)(state->next);\n            state->lenbits = 7;\n            ret = inflate_table(CODES, state->lens, 19, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid code lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       code lengths ok\\n\"));\n\n            /* get length and distance code code lengths */\n            state->have = 0;\n            while (state->have < state->nlen + state->ndist) {\n                for (;;) {\n                    here = state->lencode[BITS(state->lenbits)];\n                    if ((unsigned)(here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                if (here.val < 16) {\n                    DROPBITS(here.bits);\n                    state->lens[state->have++] = here.val;\n                }\n                else {\n                    if (here.val == 16) {\n                        NEEDBITS(here.bits + 2);\n                        DROPBITS(here.bits);\n                        if (state->have == 0) {\n                            strm->msg = (char *)\"invalid bit length repeat\";\n                            state->mode = BAD;\n                            break;\n                        }\n                        len = (unsigned)(state->lens[state->have - 1]);\n                        copy = 3 + BITS(2);\n                        DROPBITS(2);\n                    }\n                    else if (here.val == 17) {\n                        NEEDBITS(here.bits + 3);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 3 + BITS(3);\n                        DROPBITS(3);\n                    }\n                    else {\n                        NEEDBITS(here.bits + 7);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 11 + BITS(7);\n                        DROPBITS(7);\n                    }\n                    if (state->have + copy > state->nlen + state->ndist) {\n                        strm->msg = (char *)\"invalid bit length repeat\";\n                        state->mode = BAD;\n                        break;\n                    }\n                    while (copy--)\n                        state->lens[state->have++] = (unsigned short)len;\n                }\n            }\n\n            /* handle error breaks in while */\n            if (state->mode == BAD) break;\n\n            /* check for end-of-block code (better have one) */\n            if (state->lens[256] == 0) {\n                strm->msg = (char *)\"invalid code -- missing end-of-block\";\n                state->mode = BAD;\n                break;\n            }\n\n            /* build code tables -- note: do not change the lenbits or distbits\n               values here (9 and 6) without reading the comments in inftrees.h\n               concerning the ENOUGH constants, which depend on those values */\n            state->next = state->codes;\n            state->lencode = (code const FAR *)(state->next);\n            state->lenbits = 9;\n            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid literal/lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            state->distcode = (code const FAR *)(state->next);\n            state->distbits = 6;\n            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,\n                            &(state->next), &(state->distbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid distances set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       codes ok\\n\"));\n            state->mode = LEN;\n\n        case LEN:\n            /* use inflate_fast() if we have enough input and output */\n            if (have >= 6 && left >= 258) {\n                RESTORE();\n                if (state->whave < state->wsize)\n                    state->whave = state->wsize - left;\n                inflate_fast(strm, state->wsize);\n                LOAD();\n                break;\n            }\n\n            /* get a literal, length, or end-of-block code */\n            for (;;) {\n                here = state->lencode[BITS(state->lenbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if (here.op && (here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->lencode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n            }\n            DROPBITS(here.bits);\n            state->length = (unsigned)here.val;\n\n            /* process literal */\n            if (here.op == 0) {\n                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n                        \"inflate:         literal '%c'\\n\" :\n                        \"inflate:         literal 0x%02x\\n\", here.val));\n                ROOM();\n                *put++ = (unsigned char)(state->length);\n                left--;\n                state->mode = LEN;\n                break;\n            }\n\n            /* process end of block */\n            if (here.op & 32) {\n                Tracevv((stderr, \"inflate:         end of block\\n\"));\n                state->mode = TYPE;\n                break;\n            }\n\n            /* invalid code */\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid literal/length code\";\n                state->mode = BAD;\n                break;\n            }\n\n            /* length code -- get extra bits, if any */\n            state->extra = (unsigned)(here.op) & 15;\n            if (state->extra != 0) {\n                NEEDBITS(state->extra);\n                state->length += BITS(state->extra);\n                DROPBITS(state->extra);\n            }\n            Tracevv((stderr, \"inflate:         length %u\\n\", state->length));\n\n            /* get distance code */\n            for (;;) {\n                here = state->distcode[BITS(state->distbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if ((here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->distcode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n            }\n            DROPBITS(here.bits);\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid distance code\";\n                state->mode = BAD;\n                break;\n            }\n            state->offset = (unsigned)here.val;\n\n            /* get distance extra bits, if any */\n            state->extra = (unsigned)(here.op) & 15;\n            if (state->extra != 0) {\n                NEEDBITS(state->extra);\n                state->offset += BITS(state->extra);\n                DROPBITS(state->extra);\n            }\n            if (state->offset > state->wsize - (state->whave < state->wsize ?\n                                                left : 0)) {\n                strm->msg = (char *)\"invalid distance too far back\";\n                state->mode = BAD;\n                break;\n            }\n            Tracevv((stderr, \"inflate:         distance %u\\n\", state->offset));\n\n            /* copy match from window to output */\n            do {\n                ROOM();\n                copy = state->wsize - state->offset;\n                if (copy < left) {\n                    from = put + copy;\n                    copy = left - copy;\n                }\n                else {\n                    from = put - state->offset;\n                    copy = left;\n                }\n                if (copy > state->length) copy = state->length;\n                state->length -= copy;\n                left -= copy;\n                do {\n                    *put++ = *from++;\n                } while (--copy);\n            } while (state->length != 0);\n            break;\n\n        case DONE:\n            /* inflate stream terminated properly -- write leftover output */\n            ret = Z_STREAM_END;\n            if (left < state->wsize) {\n                if (out(out_desc, state->window, state->wsize - left))\n                    ret = Z_BUF_ERROR;\n            }\n            goto inf_leave;\n\n        case BAD:\n            ret = Z_DATA_ERROR;\n            goto inf_leave;\n\n        default:                /* can't happen, but makes compilers happy */\n            ret = Z_STREAM_ERROR;\n            goto inf_leave;\n        }\n\n    /* Return unused input */\n  inf_leave:\n    strm->next_in = next;\n    strm->avail_in = have;\n    return ret;\n}\n\nint ZEXPORT inflateBackEnd(strm)\nz_streamp strm;\n{\n    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)\n        return Z_STREAM_ERROR;\n    ZFREE(strm, strm->state);\n    strm->state = Z_NULL;\n    Tracev((stderr, \"inflate: end\\n\"));\n    return Z_OK;\n}\n"
  },
  {
    "path": "jsb_build/websockets/zlib/inffast.c",
    "content": "/* inffast.c -- fast decoding\n * Copyright (C) 1995-2017 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n#include \"zutil.h\"\n#include \"inftrees.h\"\n#include \"inflate.h\"\n#include \"inffast.h\"\n\n#ifdef ASMINF\n#  pragma message(\"Assembler code may have bugs -- use at your own risk\")\n#else\n\n/*\n   Decode literal, length, and distance codes and write out the resulting\n   literal and match bytes until either not enough input or output is\n   available, an end-of-block is encountered, or a data error is encountered.\n   When large enough input and output buffers are supplied to inflate(), for\n   example, a 16K input buffer and a 64K output buffer, more than 95% of the\n   inflate execution time is spent in this routine.\n\n   Entry assumptions:\n\n        state->mode == LEN\n        strm->avail_in >= 6\n        strm->avail_out >= 258\n        start >= strm->avail_out\n        state->bits < 8\n\n   On return, state->mode is one of:\n\n        LEN -- ran out of enough output space or enough available input\n        TYPE -- reached end of block code, inflate() to interpret next block\n        BAD -- error in block data\n\n   Notes:\n\n    - The maximum input bits used by a length/distance pair is 15 bits for the\n      length code, 5 bits for the length extra, 15 bits for the distance code,\n      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.\n      Therefore if strm->avail_in >= 6, then there is enough input to avoid\n      checking for available input while decoding.\n\n    - The maximum bytes that a single length/distance pair can output is 258\n      bytes, which is the maximum length that can be coded.  inflate_fast()\n      requires strm->avail_out >= 258 for each loop to avoid checking for\n      output space.\n */\nvoid ZLIB_INTERNAL inflate_fast(strm, start)\nz_streamp strm;\nunsigned start;         /* inflate()'s starting value for strm->avail_out */\n{\n    struct inflate_state FAR *state;\n    z_const unsigned char FAR *in;      /* local strm->next_in */\n    z_const unsigned char FAR *last;    /* have enough input while in < last */\n    unsigned char FAR *out;     /* local strm->next_out */\n    unsigned char FAR *beg;     /* inflate()'s initial strm->next_out */\n    unsigned char FAR *end;     /* while out < end, enough space available */\n#ifdef INFLATE_STRICT\n    unsigned dmax;              /* maximum distance from zlib header */\n#endif\n    unsigned wsize;             /* window size or zero if not using window */\n    unsigned whave;             /* valid bytes in the window */\n    unsigned wnext;             /* window write index */\n    unsigned char FAR *window;  /* allocated sliding window, if wsize != 0 */\n    unsigned long hold;         /* local strm->hold */\n    unsigned bits;              /* local strm->bits */\n    code const FAR *lcode;      /* local strm->lencode */\n    code const FAR *dcode;      /* local strm->distcode */\n    unsigned lmask;             /* mask for first level of length codes */\n    unsigned dmask;             /* mask for first level of distance codes */\n    code here;                  /* retrieved table entry */\n    unsigned op;                /* code bits, operation, extra bits, or */\n                                /*  window position, window bytes to copy */\n    unsigned len;               /* match length, unused bytes */\n    unsigned dist;              /* match distance */\n    unsigned char FAR *from;    /* where to copy match from */\n\n    /* copy state to local variables */\n    state = (struct inflate_state FAR *)strm->state;\n    in = strm->next_in;\n    last = in + (strm->avail_in - 5);\n    out = strm->next_out;\n    beg = out - (start - strm->avail_out);\n    end = out + (strm->avail_out - 257);\n#ifdef INFLATE_STRICT\n    dmax = state->dmax;\n#endif\n    wsize = state->wsize;\n    whave = state->whave;\n    wnext = state->wnext;\n    window = state->window;\n    hold = state->hold;\n    bits = state->bits;\n    lcode = state->lencode;\n    dcode = state->distcode;\n    lmask = (1U << state->lenbits) - 1;\n    dmask = (1U << state->distbits) - 1;\n\n    /* decode literals and length/distances until end-of-block or not enough\n       input data or output space */\n    do {\n        if (bits < 15) {\n            hold += (unsigned long)(*in++) << bits;\n            bits += 8;\n            hold += (unsigned long)(*in++) << bits;\n            bits += 8;\n        }\n        here = lcode[hold & lmask];\n      dolen:\n        op = (unsigned)(here.bits);\n        hold >>= op;\n        bits -= op;\n        op = (unsigned)(here.op);\n        if (op == 0) {                          /* literal */\n            Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n                    \"inflate:         literal '%c'\\n\" :\n                    \"inflate:         literal 0x%02x\\n\", here.val));\n            *out++ = (unsigned char)(here.val);\n        }\n        else if (op & 16) {                     /* length base */\n            len = (unsigned)(here.val);\n            op &= 15;                           /* number of extra bits */\n            if (op) {\n                if (bits < op) {\n                    hold += (unsigned long)(*in++) << bits;\n                    bits += 8;\n                }\n                len += (unsigned)hold & ((1U << op) - 1);\n                hold >>= op;\n                bits -= op;\n            }\n            Tracevv((stderr, \"inflate:         length %u\\n\", len));\n            if (bits < 15) {\n                hold += (unsigned long)(*in++) << bits;\n                bits += 8;\n                hold += (unsigned long)(*in++) << bits;\n                bits += 8;\n            }\n            here = dcode[hold & dmask];\n          dodist:\n            op = (unsigned)(here.bits);\n            hold >>= op;\n            bits -= op;\n            op = (unsigned)(here.op);\n            if (op & 16) {                      /* distance base */\n                dist = (unsigned)(here.val);\n                op &= 15;                       /* number of extra bits */\n                if (bits < op) {\n                    hold += (unsigned long)(*in++) << bits;\n                    bits += 8;\n                    if (bits < op) {\n                        hold += (unsigned long)(*in++) << bits;\n                        bits += 8;\n                    }\n                }\n                dist += (unsigned)hold & ((1U << op) - 1);\n#ifdef INFLATE_STRICT\n                if (dist > dmax) {\n                    strm->msg = (char *)\"invalid distance too far back\";\n                    state->mode = BAD;\n                    break;\n                }\n#endif\n                hold >>= op;\n                bits -= op;\n                Tracevv((stderr, \"inflate:         distance %u\\n\", dist));\n                op = (unsigned)(out - beg);     /* max distance in output */\n                if (dist > op) {                /* see if copy from window */\n                    op = dist - op;             /* distance back in window */\n                    if (op > whave) {\n                        if (state->sane) {\n                            strm->msg =\n                                (char *)\"invalid distance too far back\";\n                            state->mode = BAD;\n                            break;\n                        }\n#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n                        if (len <= op - whave) {\n                            do {\n                                *out++ = 0;\n                            } while (--len);\n                            continue;\n                        }\n                        len -= op - whave;\n                        do {\n                            *out++ = 0;\n                        } while (--op > whave);\n                        if (op == 0) {\n                            from = out - dist;\n                            do {\n                                *out++ = *from++;\n                            } while (--len);\n                            continue;\n                        }\n#endif\n                    }\n                    from = window;\n                    if (wnext == 0) {           /* very common case */\n                        from += wsize - op;\n                        if (op < len) {         /* some from window */\n                            len -= op;\n                            do {\n                                *out++ = *from++;\n                            } while (--op);\n                            from = out - dist;  /* rest from output */\n                        }\n                    }\n                    else if (wnext < op) {      /* wrap around window */\n                        from += wsize + wnext - op;\n                        op -= wnext;\n                        if (op < len) {         /* some from end of window */\n                            len -= op;\n                            do {\n                                *out++ = *from++;\n                            } while (--op);\n                            from = window;\n                            if (wnext < len) {  /* some from start of window */\n                                op = wnext;\n                                len -= op;\n                                do {\n                                    *out++ = *from++;\n                                } while (--op);\n                                from = out - dist;      /* rest from output */\n                            }\n                        }\n                    }\n                    else {                      /* contiguous in window */\n                        from += wnext - op;\n                        if (op < len) {         /* some from window */\n                            len -= op;\n                            do {\n                                *out++ = *from++;\n                            } while (--op);\n                            from = out - dist;  /* rest from output */\n                        }\n                    }\n                    while (len > 2) {\n                        *out++ = *from++;\n                        *out++ = *from++;\n                        *out++ = *from++;\n                        len -= 3;\n                    }\n                    if (len) {\n                        *out++ = *from++;\n                        if (len > 1)\n                            *out++ = *from++;\n                    }\n                }\n                else {\n                    from = out - dist;          /* copy direct from output */\n                    do {                        /* minimum length is three */\n                        *out++ = *from++;\n                        *out++ = *from++;\n                        *out++ = *from++;\n                        len -= 3;\n                    } while (len > 2);\n                    if (len) {\n                        *out++ = *from++;\n                        if (len > 1)\n                            *out++ = *from++;\n                    }\n                }\n            }\n            else if ((op & 64) == 0) {          /* 2nd level distance code */\n                here = dcode[here.val + (hold & ((1U << op) - 1))];\n                goto dodist;\n            }\n            else {\n                strm->msg = (char *)\"invalid distance code\";\n                state->mode = BAD;\n                break;\n            }\n        }\n        else if ((op & 64) == 0) {              /* 2nd level length code */\n            here = lcode[here.val + (hold & ((1U << op) - 1))];\n            goto dolen;\n        }\n        else if (op & 32) {                     /* end-of-block */\n            Tracevv((stderr, \"inflate:         end of block\\n\"));\n            state->mode = TYPE;\n            break;\n        }\n        else {\n            strm->msg = (char *)\"invalid literal/length code\";\n            state->mode = BAD;\n            break;\n        }\n    } while (in < last && out < end);\n\n    /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n    len = bits >> 3;\n    in -= len;\n    bits -= len << 3;\n    hold &= (1U << bits) - 1;\n\n    /* update state and return */\n    strm->next_in = in;\n    strm->next_out = out;\n    strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));\n    strm->avail_out = (unsigned)(out < end ?\n                                 257 + (end - out) : 257 - (out - end));\n    state->hold = hold;\n    state->bits = bits;\n    return;\n}\n\n/*\n   inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):\n   - Using bit fields for code structure\n   - Different op definition to avoid & for extra bits (do & for table bits)\n   - Three separate decoding do-loops for direct, window, and wnext == 0\n   - Special case for distance > 1 copies to do overlapped load and store copy\n   - Explicit branch predictions (based on measured branch probabilities)\n   - Deferring match copy and interspersed it with decoding subsequent codes\n   - Swapping literal/length else\n   - Swapping window/direct else\n   - Larger unrolled copy loops (three is about right)\n   - Moving len -= 3 statement into middle of loop\n */\n\n#endif /* !ASMINF */\n"
  },
  {
    "path": "jsb_build/websockets/zlib/inffast.h",
    "content": "/* inffast.h -- header to use inffast.c\n * Copyright (C) 1995-2003, 2010 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* WARNING: this file should *not* be used by applications. It is\n   part of the implementation of the compression library and is\n   subject to change. Applications should only use zlib.h.\n */\n\nvoid ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start));\n"
  },
  {
    "path": "jsb_build/websockets/zlib/inffixed.h",
    "content": "    /* inffixed.h -- table for decoding fixed codes\n     * Generated automatically by makefixed().\n     */\n\n    /* WARNING: this file should *not* be used by applications.\n       It is part of the implementation of this library and is\n       subject to change. Applications should only use zlib.h.\n     */\n\n    static const code lenfix[512] = {\n        {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},\n        {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},\n        {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},\n        {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},\n        {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},\n        {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},\n        {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},\n        {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},\n        {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},\n        {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},\n        {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},\n        {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},\n        {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},\n        {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},\n        {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},\n        {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},\n        {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},\n        {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},\n        {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},\n        {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},\n        {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},\n        {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},\n        {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},\n        {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},\n        {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},\n        {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},\n        {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},\n        {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},\n        {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},\n        {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},\n        {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},\n        {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},\n        {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},\n        {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},\n        {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},\n        {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},\n        {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},\n        {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},\n        {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},\n        {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},\n        {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},\n        {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},\n        {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},\n        {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},\n        {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},\n        {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},\n        {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},\n        {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},\n        {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},\n        {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},\n        {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},\n        {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},\n        {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},\n        {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},\n        {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},\n        {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},\n        {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},\n        {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},\n        {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},\n        {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},\n        {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},\n        {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},\n        {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},\n        {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},\n        {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},\n        {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},\n        {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},\n        {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},\n        {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},\n        {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},\n        {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},\n        {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},\n        {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},\n        {0,9,255}\n    };\n\n    static const code distfix[32] = {\n        {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},\n        {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},\n        {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},\n        {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},\n        {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},\n        {22,5,193},{64,5,0}\n    };\n"
  },
  {
    "path": "jsb_build/websockets/zlib/inflate.c",
    "content": "/* inflate.c -- zlib decompression\n * Copyright (C) 1995-2016 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/*\n * Change history:\n *\n * 1.2.beta0    24 Nov 2002\n * - First version -- complete rewrite of inflate to simplify code, avoid\n *   creation of window when not needed, minimize use of window when it is\n *   needed, make inffast.c even faster, implement gzip decoding, and to\n *   improve code readability and style over the previous zlib inflate code\n *\n * 1.2.beta1    25 Nov 2002\n * - Use pointers for available input and output checking in inffast.c\n * - Remove input and output counters in inffast.c\n * - Change inffast.c entry and loop from avail_in >= 7 to >= 6\n * - Remove unnecessary second byte pull from length extra in inffast.c\n * - Unroll direct copy to three copies per loop in inffast.c\n *\n * 1.2.beta2    4 Dec 2002\n * - Change external routine names to reduce potential conflicts\n * - Correct filename to inffixed.h for fixed tables in inflate.c\n * - Make hbuf[] unsigned char to match parameter type in inflate.c\n * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)\n *   to avoid negation problem on Alphas (64 bit) in inflate.c\n *\n * 1.2.beta3    22 Dec 2002\n * - Add comments on state->bits assertion in inffast.c\n * - Add comments on op field in inftrees.h\n * - Fix bug in reuse of allocated window after inflateReset()\n * - Remove bit fields--back to byte structure for speed\n * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths\n * - Change post-increments to pre-increments in inflate_fast(), PPC biased?\n * - Add compile time option, POSTINC, to use post-increments instead (Intel?)\n * - Make MATCH copy in inflate() much faster for when inflate_fast() not used\n * - Use local copies of stream next and avail values, as well as local bit\n *   buffer and bit count in inflate()--for speed when inflate_fast() not used\n *\n * 1.2.beta4    1 Jan 2003\n * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings\n * - Move a comment on output buffer sizes from inffast.c to inflate.c\n * - Add comments in inffast.c to introduce the inflate_fast() routine\n * - Rearrange window copies in inflate_fast() for speed and simplification\n * - Unroll last copy for window match in inflate_fast()\n * - Use local copies of window variables in inflate_fast() for speed\n * - Pull out common wnext == 0 case for speed in inflate_fast()\n * - Make op and len in inflate_fast() unsigned for consistency\n * - Add FAR to lcode and dcode declarations in inflate_fast()\n * - Simplified bad distance check in inflate_fast()\n * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new\n *   source file infback.c to provide a call-back interface to inflate for\n *   programs like gzip and unzip -- uses window as output buffer to avoid\n *   window copying\n *\n * 1.2.beta5    1 Jan 2003\n * - Improved inflateBack() interface to allow the caller to provide initial\n *   input in strm.\n * - Fixed stored blocks bug in inflateBack()\n *\n * 1.2.beta6    4 Jan 2003\n * - Added comments in inffast.c on effectiveness of POSTINC\n * - Typecasting all around to reduce compiler warnings\n * - Changed loops from while (1) or do {} while (1) to for (;;), again to\n *   make compilers happy\n * - Changed type of window in inflateBackInit() to unsigned char *\n *\n * 1.2.beta7    27 Jan 2003\n * - Changed many types to unsigned or unsigned short to avoid warnings\n * - Added inflateCopy() function\n *\n * 1.2.0        9 Mar 2003\n * - Changed inflateBack() interface to provide separate opaque descriptors\n *   for the in() and out() functions\n * - Changed inflateBack() argument and in_func typedef to swap the length\n *   and buffer address return values for the input function\n * - Check next_in and next_out for Z_NULL on entry to inflate()\n *\n * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.\n */\n\n#include \"zutil.h\"\n#include \"inftrees.h\"\n#include \"inflate.h\"\n#include \"inffast.h\"\n\n#ifdef MAKEFIXED\n#  ifndef BUILDFIXED\n#    define BUILDFIXED\n#  endif\n#endif\n\n/* function prototypes */\nlocal int inflateStateCheck OF((z_streamp strm));\nlocal void fixedtables OF((struct inflate_state FAR *state));\nlocal int updatewindow OF((z_streamp strm, const unsigned char FAR *end,\n                           unsigned copy));\n#ifdef BUILDFIXED\n   void makefixed OF((void));\n#endif\nlocal unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf,\n                              unsigned len));\n\nlocal int inflateStateCheck(strm)\nz_streamp strm;\n{\n    struct inflate_state FAR *state;\n    if (strm == Z_NULL ||\n        strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)\n        return 1;\n    state = (struct inflate_state FAR *)strm->state;\n    if (state == Z_NULL || state->strm != strm ||\n        state->mode < HEAD || state->mode > SYNC)\n        return 1;\n    return 0;\n}\n\nint ZEXPORT inflateResetKeep(strm)\nz_streamp strm;\n{\n    struct inflate_state FAR *state;\n\n    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    strm->total_in = strm->total_out = state->total = 0;\n    strm->msg = Z_NULL;\n    if (state->wrap)        /* to support ill-conceived Java test suite */\n        strm->adler = state->wrap & 1;\n    state->mode = HEAD;\n    state->last = 0;\n    state->havedict = 0;\n    state->dmax = 32768U;\n    state->head = Z_NULL;\n    state->hold = 0;\n    state->bits = 0;\n    state->lencode = state->distcode = state->next = state->codes;\n    state->sane = 1;\n    state->back = -1;\n    Tracev((stderr, \"inflate: reset\\n\"));\n    return Z_OK;\n}\n\nint ZEXPORT inflateReset(strm)\nz_streamp strm;\n{\n    struct inflate_state FAR *state;\n\n    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    state->wsize = 0;\n    state->whave = 0;\n    state->wnext = 0;\n    return inflateResetKeep(strm);\n}\n\nint ZEXPORT inflateReset2(strm, windowBits)\nz_streamp strm;\nint windowBits;\n{\n    int wrap;\n    struct inflate_state FAR *state;\n\n    /* get the state */\n    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n\n    /* extract wrap request from windowBits parameter */\n    if (windowBits < 0) {\n        wrap = 0;\n        windowBits = -windowBits;\n    }\n    else {\n        wrap = (windowBits >> 4) + 5;\n#ifdef GUNZIP\n        if (windowBits < 48)\n            windowBits &= 15;\n#endif\n    }\n\n    /* set number of window bits, free window if different */\n    if (windowBits && (windowBits < 8 || windowBits > 15))\n        return Z_STREAM_ERROR;\n    if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {\n        ZFREE(strm, state->window);\n        state->window = Z_NULL;\n    }\n\n    /* update state and reset the rest of it */\n    state->wrap = wrap;\n    state->wbits = (unsigned)windowBits;\n    return inflateReset(strm);\n}\n\nint ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)\nz_streamp strm;\nint windowBits;\nconst char *version;\nint stream_size;\n{\n    int ret;\n    struct inflate_state FAR *state;\n\n    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||\n        stream_size != (int)(sizeof(z_stream)))\n        return Z_VERSION_ERROR;\n    if (strm == Z_NULL) return Z_STREAM_ERROR;\n    strm->msg = Z_NULL;                 /* in case we return an error */\n    if (strm->zalloc == (alloc_func)0) {\n#ifdef Z_SOLO\n        return Z_STREAM_ERROR;\n#else\n        strm->zalloc = zcalloc;\n        strm->opaque = (voidpf)0;\n#endif\n    }\n    if (strm->zfree == (free_func)0)\n#ifdef Z_SOLO\n        return Z_STREAM_ERROR;\n#else\n        strm->zfree = zcfree;\n#endif\n    state = (struct inflate_state FAR *)\n            ZALLOC(strm, 1, sizeof(struct inflate_state));\n    if (state == Z_NULL) return Z_MEM_ERROR;\n    Tracev((stderr, \"inflate: allocated\\n\"));\n    strm->state = (struct internal_state FAR *)state;\n    state->strm = strm;\n    state->window = Z_NULL;\n    state->mode = HEAD;     /* to pass state test in inflateReset2() */\n    ret = inflateReset2(strm, windowBits);\n    if (ret != Z_OK) {\n        ZFREE(strm, state);\n        strm->state = Z_NULL;\n    }\n    return ret;\n}\n\nint ZEXPORT inflateInit_(strm, version, stream_size)\nz_streamp strm;\nconst char *version;\nint stream_size;\n{\n    return inflateInit2_(strm, DEF_WBITS, version, stream_size);\n}\n\nint ZEXPORT inflatePrime(strm, bits, value)\nz_streamp strm;\nint bits;\nint value;\n{\n    struct inflate_state FAR *state;\n\n    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    if (bits < 0) {\n        state->hold = 0;\n        state->bits = 0;\n        return Z_OK;\n    }\n    if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR;\n    value &= (1L << bits) - 1;\n    state->hold += (unsigned)value << state->bits;\n    state->bits += (uInt)bits;\n    return Z_OK;\n}\n\n/*\n   Return state with length and distance decoding tables and index sizes set to\n   fixed code decoding.  Normally this returns fixed tables from inffixed.h.\n   If BUILDFIXED is defined, then instead this routine builds the tables the\n   first time it's called, and returns those tables the first time and\n   thereafter.  This reduces the size of the code by about 2K bytes, in\n   exchange for a little execution time.  However, BUILDFIXED should not be\n   used for threaded applications, since the rewriting of the tables and virgin\n   may not be thread-safe.\n */\nlocal void fixedtables(state)\nstruct inflate_state FAR *state;\n{\n#ifdef BUILDFIXED\n    static int virgin = 1;\n    static code *lenfix, *distfix;\n    static code fixed[544];\n\n    /* build fixed huffman tables if first call (may not be thread safe) */\n    if (virgin) {\n        unsigned sym, bits;\n        static code *next;\n\n        /* literal/length table */\n        sym = 0;\n        while (sym < 144) state->lens[sym++] = 8;\n        while (sym < 256) state->lens[sym++] = 9;\n        while (sym < 280) state->lens[sym++] = 7;\n        while (sym < 288) state->lens[sym++] = 8;\n        next = fixed;\n        lenfix = next;\n        bits = 9;\n        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);\n\n        /* distance table */\n        sym = 0;\n        while (sym < 32) state->lens[sym++] = 5;\n        distfix = next;\n        bits = 5;\n        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);\n\n        /* do this just once */\n        virgin = 0;\n    }\n#else /* !BUILDFIXED */\n#   include \"inffixed.h\"\n#endif /* BUILDFIXED */\n    state->lencode = lenfix;\n    state->lenbits = 9;\n    state->distcode = distfix;\n    state->distbits = 5;\n}\n\n#ifdef MAKEFIXED\n#include <stdio.h>\n\n/*\n   Write out the inffixed.h that is #include'd above.  Defining MAKEFIXED also\n   defines BUILDFIXED, so the tables are built on the fly.  makefixed() writes\n   those tables to stdout, which would be piped to inffixed.h.  A small program\n   can simply call makefixed to do this:\n\n    void makefixed(void);\n\n    int main(void)\n    {\n        makefixed();\n        return 0;\n    }\n\n   Then that can be linked with zlib built with MAKEFIXED defined and run:\n\n    a.out > inffixed.h\n */\nvoid makefixed()\n{\n    unsigned low, size;\n    struct inflate_state state;\n\n    fixedtables(&state);\n    puts(\"    /* inffixed.h -- table for decoding fixed codes\");\n    puts(\"     * Generated automatically by makefixed().\");\n    puts(\"     */\");\n    puts(\"\");\n    puts(\"    /* WARNING: this file should *not* be used by applications.\");\n    puts(\"       It is part of the implementation of this library and is\");\n    puts(\"       subject to change. Applications should only use zlib.h.\");\n    puts(\"     */\");\n    puts(\"\");\n    size = 1U << 9;\n    printf(\"    static const code lenfix[%u] = {\", size);\n    low = 0;\n    for (;;) {\n        if ((low % 7) == 0) printf(\"\\n        \");\n        printf(\"{%u,%u,%d}\", (low & 127) == 99 ? 64 : state.lencode[low].op,\n               state.lencode[low].bits, state.lencode[low].val);\n        if (++low == size) break;\n        putchar(',');\n    }\n    puts(\"\\n    };\");\n    size = 1U << 5;\n    printf(\"\\n    static const code distfix[%u] = {\", size);\n    low = 0;\n    for (;;) {\n        if ((low % 6) == 0) printf(\"\\n        \");\n        printf(\"{%u,%u,%d}\", state.distcode[low].op, state.distcode[low].bits,\n               state.distcode[low].val);\n        if (++low == size) break;\n        putchar(',');\n    }\n    puts(\"\\n    };\");\n}\n#endif /* MAKEFIXED */\n\n/*\n   Update the window with the last wsize (normally 32K) bytes written before\n   returning.  If window does not exist yet, create it.  This is only called\n   when a window is already in use, or when output has been written during this\n   inflate call, but the end of the deflate stream has not been reached yet.\n   It is also called to create a window for dictionary data when a dictionary\n   is loaded.\n\n   Providing output buffers larger than 32K to inflate() should provide a speed\n   advantage, since only the last 32K of output is copied to the sliding window\n   upon return from inflate(), and since all distances after the first 32K of\n   output will fall in the output data, making match copies simpler and faster.\n   The advantage may be dependent on the size of the processor's data caches.\n */\nlocal int updatewindow(strm, end, copy)\nz_streamp strm;\nconst Bytef *end;\nunsigned copy;\n{\n    struct inflate_state FAR *state;\n    unsigned dist;\n\n    state = (struct inflate_state FAR *)strm->state;\n\n    /* if it hasn't been done already, allocate space for the window */\n    if (state->window == Z_NULL) {\n        state->window = (unsigned char FAR *)\n                        ZALLOC(strm, 1U << state->wbits,\n                               sizeof(unsigned char));\n        if (state->window == Z_NULL) return 1;\n    }\n\n    /* if window not in use yet, initialize */\n    if (state->wsize == 0) {\n        state->wsize = 1U << state->wbits;\n        state->wnext = 0;\n        state->whave = 0;\n    }\n\n    /* copy state->wsize or less output bytes into the circular window */\n    if (copy >= state->wsize) {\n        zmemcpy(state->window, end - state->wsize, state->wsize);\n        state->wnext = 0;\n        state->whave = state->wsize;\n    }\n    else {\n        dist = state->wsize - state->wnext;\n        if (dist > copy) dist = copy;\n        zmemcpy(state->window + state->wnext, end - copy, dist);\n        copy -= dist;\n        if (copy) {\n            zmemcpy(state->window, end - copy, copy);\n            state->wnext = copy;\n            state->whave = state->wsize;\n        }\n        else {\n            state->wnext += dist;\n            if (state->wnext == state->wsize) state->wnext = 0;\n            if (state->whave < state->wsize) state->whave += dist;\n        }\n    }\n    return 0;\n}\n\n/* Macros for inflate(): */\n\n/* check function to use adler32() for zlib or crc32() for gzip */\n#ifdef GUNZIP\n#  define UPDATE(check, buf, len) \\\n    (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))\n#else\n#  define UPDATE(check, buf, len) adler32(check, buf, len)\n#endif\n\n/* check macros for header crc */\n#ifdef GUNZIP\n#  define CRC2(check, word) \\\n    do { \\\n        hbuf[0] = (unsigned char)(word); \\\n        hbuf[1] = (unsigned char)((word) >> 8); \\\n        check = crc32(check, hbuf, 2); \\\n    } while (0)\n\n#  define CRC4(check, word) \\\n    do { \\\n        hbuf[0] = (unsigned char)(word); \\\n        hbuf[1] = (unsigned char)((word) >> 8); \\\n        hbuf[2] = (unsigned char)((word) >> 16); \\\n        hbuf[3] = (unsigned char)((word) >> 24); \\\n        check = crc32(check, hbuf, 4); \\\n    } while (0)\n#endif\n\n/* Load registers with state in inflate() for speed */\n#define LOAD() \\\n    do { \\\n        put = strm->next_out; \\\n        left = strm->avail_out; \\\n        next = strm->next_in; \\\n        have = strm->avail_in; \\\n        hold = state->hold; \\\n        bits = state->bits; \\\n    } while (0)\n\n/* Restore state from registers in inflate() */\n#define RESTORE() \\\n    do { \\\n        strm->next_out = put; \\\n        strm->avail_out = left; \\\n        strm->next_in = next; \\\n        strm->avail_in = have; \\\n        state->hold = hold; \\\n        state->bits = bits; \\\n    } while (0)\n\n/* Clear the input bit accumulator */\n#define INITBITS() \\\n    do { \\\n        hold = 0; \\\n        bits = 0; \\\n    } while (0)\n\n/* Get a byte of input into the bit accumulator, or return from inflate()\n   if there is no input available. */\n#define PULLBYTE() \\\n    do { \\\n        if (have == 0) goto inf_leave; \\\n        have--; \\\n        hold += (unsigned long)(*next++) << bits; \\\n        bits += 8; \\\n    } while (0)\n\n/* Assure that there are at least n bits in the bit accumulator.  If there is\n   not enough available input to do that, then return from inflate(). */\n#define NEEDBITS(n) \\\n    do { \\\n        while (bits < (unsigned)(n)) \\\n            PULLBYTE(); \\\n    } while (0)\n\n/* Return the low n bits of the bit accumulator (n < 16) */\n#define BITS(n) \\\n    ((unsigned)hold & ((1U << (n)) - 1))\n\n/* Remove n bits from the bit accumulator */\n#define DROPBITS(n) \\\n    do { \\\n        hold >>= (n); \\\n        bits -= (unsigned)(n); \\\n    } while (0)\n\n/* Remove zero to seven bits as needed to go to a byte boundary */\n#define BYTEBITS() \\\n    do { \\\n        hold >>= bits & 7; \\\n        bits -= bits & 7; \\\n    } while (0)\n\n/*\n   inflate() uses a state machine to process as much input data and generate as\n   much output data as possible before returning.  The state machine is\n   structured roughly as follows:\n\n    for (;;) switch (state) {\n    ...\n    case STATEn:\n        if (not enough input data or output space to make progress)\n            return;\n        ... make progress ...\n        state = STATEm;\n        break;\n    ...\n    }\n\n   so when inflate() is called again, the same case is attempted again, and\n   if the appropriate resources are provided, the machine proceeds to the\n   next state.  The NEEDBITS() macro is usually the way the state evaluates\n   whether it can proceed or should return.  NEEDBITS() does the return if\n   the requested bits are not available.  The typical use of the BITS macros\n   is:\n\n        NEEDBITS(n);\n        ... do something with BITS(n) ...\n        DROPBITS(n);\n\n   where NEEDBITS(n) either returns from inflate() if there isn't enough\n   input left to load n bits into the accumulator, or it continues.  BITS(n)\n   gives the low n bits in the accumulator.  When done, DROPBITS(n) drops\n   the low n bits off the accumulator.  INITBITS() clears the accumulator\n   and sets the number of available bits to zero.  BYTEBITS() discards just\n   enough bits to put the accumulator on a byte boundary.  After BYTEBITS()\n   and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.\n\n   NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return\n   if there is no input available.  The decoding of variable length codes uses\n   PULLBYTE() directly in order to pull just enough bytes to decode the next\n   code, and no more.\n\n   Some states loop until they get enough input, making sure that enough\n   state information is maintained to continue the loop where it left off\n   if NEEDBITS() returns in the loop.  For example, want, need, and keep\n   would all have to actually be part of the saved state in case NEEDBITS()\n   returns:\n\n    case STATEw:\n        while (want < need) {\n            NEEDBITS(n);\n            keep[want++] = BITS(n);\n            DROPBITS(n);\n        }\n        state = STATEx;\n    case STATEx:\n\n   As shown above, if the next state is also the next case, then the break\n   is omitted.\n\n   A state may also return if there is not enough output space available to\n   complete that state.  Those states are copying stored data, writing a\n   literal byte, and copying a matching string.\n\n   When returning, a \"goto inf_leave\" is used to update the total counters,\n   update the check value, and determine whether any progress has been made\n   during that inflate() call in order to return the proper return code.\n   Progress is defined as a change in either strm->avail_in or strm->avail_out.\n   When there is a window, goto inf_leave will update the window with the last\n   output written.  If a goto inf_leave occurs in the middle of decompression\n   and there is no window currently, goto inf_leave will create one and copy\n   output to the window for the next call of inflate().\n\n   In this implementation, the flush parameter of inflate() only affects the\n   return code (per zlib.h).  inflate() always writes as much as possible to\n   strm->next_out, given the space available and the provided input--the effect\n   documented in zlib.h of Z_SYNC_FLUSH.  Furthermore, inflate() always defers\n   the allocation of and copying into a sliding window until necessary, which\n   provides the effect documented in zlib.h for Z_FINISH when the entire input\n   stream available.  So the only thing the flush parameter actually does is:\n   when flush is set to Z_FINISH, inflate() cannot return Z_OK.  Instead it\n   will return Z_BUF_ERROR if it has not reached the end of the stream.\n */\n\nint ZEXPORT inflate(strm, flush)\nz_streamp strm;\nint flush;\n{\n    struct inflate_state FAR *state;\n    z_const unsigned char FAR *next;    /* next input */\n    unsigned char FAR *put;     /* next output */\n    unsigned have, left;        /* available input and output */\n    unsigned long hold;         /* bit buffer */\n    unsigned bits;              /* bits in bit buffer */\n    unsigned in, out;           /* save starting available input and output */\n    unsigned copy;              /* number of stored or match bytes to copy */\n    unsigned char FAR *from;    /* where to copy match bytes from */\n    code here;                  /* current decoding table entry */\n    code last;                  /* parent table entry */\n    unsigned len;               /* length to copy for repeats, bits to drop */\n    int ret;                    /* return code */\n#ifdef GUNZIP\n    unsigned char hbuf[4];      /* buffer for gzip header crc calculation */\n#endif\n    static const unsigned short order[19] = /* permutation of code lengths */\n        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};\n\n    if (inflateStateCheck(strm) || strm->next_out == Z_NULL ||\n        (strm->next_in == Z_NULL && strm->avail_in != 0))\n        return Z_STREAM_ERROR;\n\n    state = (struct inflate_state FAR *)strm->state;\n    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */\n    LOAD();\n    in = have;\n    out = left;\n    ret = Z_OK;\n    for (;;)\n        switch (state->mode) {\n        case HEAD:\n            if (state->wrap == 0) {\n                state->mode = TYPEDO;\n                break;\n            }\n            NEEDBITS(16);\n#ifdef GUNZIP\n            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */\n                if (state->wbits == 0)\n                    state->wbits = 15;\n                state->check = crc32(0L, Z_NULL, 0);\n                CRC2(state->check, hold);\n                INITBITS();\n                state->mode = FLAGS;\n                break;\n            }\n            state->flags = 0;           /* expect zlib header */\n            if (state->head != Z_NULL)\n                state->head->done = -1;\n            if (!(state->wrap & 1) ||   /* check if zlib header allowed */\n#else\n            if (\n#endif\n                ((BITS(8) << 8) + (hold >> 8)) % 31) {\n                strm->msg = (char *)\"incorrect header check\";\n                state->mode = BAD;\n                break;\n            }\n            if (BITS(4) != Z_DEFLATED) {\n                strm->msg = (char *)\"unknown compression method\";\n                state->mode = BAD;\n                break;\n            }\n            DROPBITS(4);\n            len = BITS(4) + 8;\n            if (state->wbits == 0)\n                state->wbits = len;\n            if (len > 15 || len > state->wbits) {\n                strm->msg = (char *)\"invalid window size\";\n                state->mode = BAD;\n                break;\n            }\n            state->dmax = 1U << len;\n            Tracev((stderr, \"inflate:   zlib header ok\\n\"));\n            strm->adler = state->check = adler32(0L, Z_NULL, 0);\n            state->mode = hold & 0x200 ? DICTID : TYPE;\n            INITBITS();\n            break;\n#ifdef GUNZIP\n        case FLAGS:\n            NEEDBITS(16);\n            state->flags = (int)(hold);\n            if ((state->flags & 0xff) != Z_DEFLATED) {\n                strm->msg = (char *)\"unknown compression method\";\n                state->mode = BAD;\n                break;\n            }\n            if (state->flags & 0xe000) {\n                strm->msg = (char *)\"unknown header flags set\";\n                state->mode = BAD;\n                break;\n            }\n            if (state->head != Z_NULL)\n                state->head->text = (int)((hold >> 8) & 1);\n            if ((state->flags & 0x0200) && (state->wrap & 4))\n                CRC2(state->check, hold);\n            INITBITS();\n            state->mode = TIME;\n        case TIME:\n            NEEDBITS(32);\n            if (state->head != Z_NULL)\n                state->head->time = hold;\n            if ((state->flags & 0x0200) && (state->wrap & 4))\n                CRC4(state->check, hold);\n            INITBITS();\n            state->mode = OS;\n        case OS:\n            NEEDBITS(16);\n            if (state->head != Z_NULL) {\n                state->head->xflags = (int)(hold & 0xff);\n                state->head->os = (int)(hold >> 8);\n            }\n            if ((state->flags & 0x0200) && (state->wrap & 4))\n                CRC2(state->check, hold);\n            INITBITS();\n            state->mode = EXLEN;\n        case EXLEN:\n            if (state->flags & 0x0400) {\n                NEEDBITS(16);\n                state->length = (unsigned)(hold);\n                if (state->head != Z_NULL)\n                    state->head->extra_len = (unsigned)hold;\n                if ((state->flags & 0x0200) && (state->wrap & 4))\n                    CRC2(state->check, hold);\n                INITBITS();\n            }\n            else if (state->head != Z_NULL)\n                state->head->extra = Z_NULL;\n            state->mode = EXTRA;\n        case EXTRA:\n            if (state->flags & 0x0400) {\n                copy = state->length;\n                if (copy > have) copy = have;\n                if (copy) {\n                    if (state->head != Z_NULL &&\n                        state->head->extra != Z_NULL) {\n                        len = state->head->extra_len - state->length;\n                        zmemcpy(state->head->extra + len, next,\n                                len + copy > state->head->extra_max ?\n                                state->head->extra_max - len : copy);\n                    }\n                    if ((state->flags & 0x0200) && (state->wrap & 4))\n                        state->check = crc32(state->check, next, copy);\n                    have -= copy;\n                    next += copy;\n                    state->length -= copy;\n                }\n                if (state->length) goto inf_leave;\n            }\n            state->length = 0;\n            state->mode = NAME;\n        case NAME:\n            if (state->flags & 0x0800) {\n                if (have == 0) goto inf_leave;\n                copy = 0;\n                do {\n                    len = (unsigned)(next[copy++]);\n                    if (state->head != Z_NULL &&\n                            state->head->name != Z_NULL &&\n                            state->length < state->head->name_max)\n                        state->head->name[state->length++] = (Bytef)len;\n                } while (len && copy < have);\n                if ((state->flags & 0x0200) && (state->wrap & 4))\n                    state->check = crc32(state->check, next, copy);\n                have -= copy;\n                next += copy;\n                if (len) goto inf_leave;\n            }\n            else if (state->head != Z_NULL)\n                state->head->name = Z_NULL;\n            state->length = 0;\n            state->mode = COMMENT;\n        case COMMENT:\n            if (state->flags & 0x1000) {\n                if (have == 0) goto inf_leave;\n                copy = 0;\n                do {\n                    len = (unsigned)(next[copy++]);\n                    if (state->head != Z_NULL &&\n                            state->head->comment != Z_NULL &&\n                            state->length < state->head->comm_max)\n                        state->head->comment[state->length++] = (Bytef)len;\n                } while (len && copy < have);\n                if ((state->flags & 0x0200) && (state->wrap & 4))\n                    state->check = crc32(state->check, next, copy);\n                have -= copy;\n                next += copy;\n                if (len) goto inf_leave;\n            }\n            else if (state->head != Z_NULL)\n                state->head->comment = Z_NULL;\n            state->mode = HCRC;\n        case HCRC:\n            if (state->flags & 0x0200) {\n                NEEDBITS(16);\n                if ((state->wrap & 4) && hold != (state->check & 0xffff)) {\n                    strm->msg = (char *)\"header crc mismatch\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n            }\n            if (state->head != Z_NULL) {\n                state->head->hcrc = (int)((state->flags >> 9) & 1);\n                state->head->done = 1;\n            }\n            strm->adler = state->check = crc32(0L, Z_NULL, 0);\n            state->mode = TYPE;\n            break;\n#endif\n        case DICTID:\n            NEEDBITS(32);\n            strm->adler = state->check = ZSWAP32(hold);\n            INITBITS();\n            state->mode = DICT;\n        case DICT:\n            if (state->havedict == 0) {\n                RESTORE();\n                return Z_NEED_DICT;\n            }\n            strm->adler = state->check = adler32(0L, Z_NULL, 0);\n            state->mode = TYPE;\n        case TYPE:\n            if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;\n        case TYPEDO:\n            if (state->last) {\n                BYTEBITS();\n                state->mode = CHECK;\n                break;\n            }\n            NEEDBITS(3);\n            state->last = BITS(1);\n            DROPBITS(1);\n            switch (BITS(2)) {\n            case 0:                             /* stored block */\n                Tracev((stderr, \"inflate:     stored block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = STORED;\n                break;\n            case 1:                             /* fixed block */\n                fixedtables(state);\n                Tracev((stderr, \"inflate:     fixed codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = LEN_;             /* decode codes */\n                if (flush == Z_TREES) {\n                    DROPBITS(2);\n                    goto inf_leave;\n                }\n                break;\n            case 2:                             /* dynamic block */\n                Tracev((stderr, \"inflate:     dynamic codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = TABLE;\n                break;\n            case 3:\n                strm->msg = (char *)\"invalid block type\";\n                state->mode = BAD;\n            }\n            DROPBITS(2);\n            break;\n        case STORED:\n            BYTEBITS();                         /* go to byte boundary */\n            NEEDBITS(32);\n            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {\n                strm->msg = (char *)\"invalid stored block lengths\";\n                state->mode = BAD;\n                break;\n            }\n            state->length = (unsigned)hold & 0xffff;\n            Tracev((stderr, \"inflate:       stored length %u\\n\",\n                    state->length));\n            INITBITS();\n            state->mode = COPY_;\n            if (flush == Z_TREES) goto inf_leave;\n        case COPY_:\n            state->mode = COPY;\n        case COPY:\n            copy = state->length;\n            if (copy) {\n                if (copy > have) copy = have;\n                if (copy > left) copy = left;\n                if (copy == 0) goto inf_leave;\n                zmemcpy(put, next, copy);\n                have -= copy;\n                next += copy;\n                left -= copy;\n                put += copy;\n                state->length -= copy;\n                break;\n            }\n            Tracev((stderr, \"inflate:       stored end\\n\"));\n            state->mode = TYPE;\n            break;\n        case TABLE:\n            NEEDBITS(14);\n            state->nlen = BITS(5) + 257;\n            DROPBITS(5);\n            state->ndist = BITS(5) + 1;\n            DROPBITS(5);\n            state->ncode = BITS(4) + 4;\n            DROPBITS(4);\n#ifndef PKZIP_BUG_WORKAROUND\n            if (state->nlen > 286 || state->ndist > 30) {\n                strm->msg = (char *)\"too many length or distance symbols\";\n                state->mode = BAD;\n                break;\n            }\n#endif\n            Tracev((stderr, \"inflate:       table sizes ok\\n\"));\n            state->have = 0;\n            state->mode = LENLENS;\n        case LENLENS:\n            while (state->have < state->ncode) {\n                NEEDBITS(3);\n                state->lens[order[state->have++]] = (unsigned short)BITS(3);\n                DROPBITS(3);\n            }\n            while (state->have < 19)\n                state->lens[order[state->have++]] = 0;\n            state->next = state->codes;\n            state->lencode = (const code FAR *)(state->next);\n            state->lenbits = 7;\n            ret = inflate_table(CODES, state->lens, 19, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid code lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       code lengths ok\\n\"));\n            state->have = 0;\n            state->mode = CODELENS;\n        case CODELENS:\n            while (state->have < state->nlen + state->ndist) {\n                for (;;) {\n                    here = state->lencode[BITS(state->lenbits)];\n                    if ((unsigned)(here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                if (here.val < 16) {\n                    DROPBITS(here.bits);\n                    state->lens[state->have++] = here.val;\n                }\n                else {\n                    if (here.val == 16) {\n                        NEEDBITS(here.bits + 2);\n                        DROPBITS(here.bits);\n                        if (state->have == 0) {\n                            strm->msg = (char *)\"invalid bit length repeat\";\n                            state->mode = BAD;\n                            break;\n                        }\n                        len = state->lens[state->have - 1];\n                        copy = 3 + BITS(2);\n                        DROPBITS(2);\n                    }\n                    else if (here.val == 17) {\n                        NEEDBITS(here.bits + 3);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 3 + BITS(3);\n                        DROPBITS(3);\n                    }\n                    else {\n                        NEEDBITS(here.bits + 7);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 11 + BITS(7);\n                        DROPBITS(7);\n                    }\n                    if (state->have + copy > state->nlen + state->ndist) {\n                        strm->msg = (char *)\"invalid bit length repeat\";\n                        state->mode = BAD;\n                        break;\n                    }\n                    while (copy--)\n                        state->lens[state->have++] = (unsigned short)len;\n                }\n            }\n\n            /* handle error breaks in while */\n            if (state->mode == BAD) break;\n\n            /* check for end-of-block code (better have one) */\n            if (state->lens[256] == 0) {\n                strm->msg = (char *)\"invalid code -- missing end-of-block\";\n                state->mode = BAD;\n                break;\n            }\n\n            /* build code tables -- note: do not change the lenbits or distbits\n               values here (9 and 6) without reading the comments in inftrees.h\n               concerning the ENOUGH constants, which depend on those values */\n            state->next = state->codes;\n            state->lencode = (const code FAR *)(state->next);\n            state->lenbits = 9;\n            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid literal/lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            state->distcode = (const code FAR *)(state->next);\n            state->distbits = 6;\n            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,\n                            &(state->next), &(state->distbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid distances set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       codes ok\\n\"));\n            state->mode = LEN_;\n            if (flush == Z_TREES) goto inf_leave;\n        case LEN_:\n            state->mode = LEN;\n        case LEN:\n            if (have >= 6 && left >= 258) {\n                RESTORE();\n                inflate_fast(strm, out);\n                LOAD();\n                if (state->mode == TYPE)\n                    state->back = -1;\n                break;\n            }\n            state->back = 0;\n            for (;;) {\n                here = state->lencode[BITS(state->lenbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if (here.op && (here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->lencode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n                state->back += last.bits;\n            }\n            DROPBITS(here.bits);\n            state->back += here.bits;\n            state->length = (unsigned)here.val;\n            if ((int)(here.op) == 0) {\n                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n                        \"inflate:         literal '%c'\\n\" :\n                        \"inflate:         literal 0x%02x\\n\", here.val));\n                state->mode = LIT;\n                break;\n            }\n            if (here.op & 32) {\n                Tracevv((stderr, \"inflate:         end of block\\n\"));\n                state->back = -1;\n                state->mode = TYPE;\n                break;\n            }\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid literal/length code\";\n                state->mode = BAD;\n                break;\n            }\n            state->extra = (unsigned)(here.op) & 15;\n            state->mode = LENEXT;\n        case LENEXT:\n            if (state->extra) {\n                NEEDBITS(state->extra);\n                state->length += BITS(state->extra);\n                DROPBITS(state->extra);\n                state->back += state->extra;\n            }\n            Tracevv((stderr, \"inflate:         length %u\\n\", state->length));\n            state->was = state->length;\n            state->mode = DIST;\n        case DIST:\n            for (;;) {\n                here = state->distcode[BITS(state->distbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if ((here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->distcode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n                state->back += last.bits;\n            }\n            DROPBITS(here.bits);\n            state->back += here.bits;\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid distance code\";\n                state->mode = BAD;\n                break;\n            }\n            state->offset = (unsigned)here.val;\n            state->extra = (unsigned)(here.op) & 15;\n            state->mode = DISTEXT;\n        case DISTEXT:\n            if (state->extra) {\n                NEEDBITS(state->extra);\n                state->offset += BITS(state->extra);\n                DROPBITS(state->extra);\n                state->back += state->extra;\n            }\n#ifdef INFLATE_STRICT\n            if (state->offset > state->dmax) {\n                strm->msg = (char *)\"invalid distance too far back\";\n                state->mode = BAD;\n                break;\n            }\n#endif\n            Tracevv((stderr, \"inflate:         distance %u\\n\", state->offset));\n            state->mode = MATCH;\n        case MATCH:\n            if (left == 0) goto inf_leave;\n            copy = out - left;\n            if (state->offset > copy) {         /* copy from window */\n                copy = state->offset - copy;\n                if (copy > state->whave) {\n                    if (state->sane) {\n                        strm->msg = (char *)\"invalid distance too far back\";\n                        state->mode = BAD;\n                        break;\n                    }\n#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n                    Trace((stderr, \"inflate.c too far\\n\"));\n                    copy -= state->whave;\n                    if (copy > state->length) copy = state->length;\n                    if (copy > left) copy = left;\n                    left -= copy;\n                    state->length -= copy;\n                    do {\n                        *put++ = 0;\n                    } while (--copy);\n                    if (state->length == 0) state->mode = LEN;\n                    break;\n#endif\n                }\n                if (copy > state->wnext) {\n                    copy -= state->wnext;\n                    from = state->window + (state->wsize - copy);\n                }\n                else\n                    from = state->window + (state->wnext - copy);\n                if (copy > state->length) copy = state->length;\n            }\n            else {                              /* copy from output */\n                from = put - state->offset;\n                copy = state->length;\n            }\n            if (copy > left) copy = left;\n            left -= copy;\n            state->length -= copy;\n            do {\n                *put++ = *from++;\n            } while (--copy);\n            if (state->length == 0) state->mode = LEN;\n            break;\n        case LIT:\n            if (left == 0) goto inf_leave;\n            *put++ = (unsigned char)(state->length);\n            left--;\n            state->mode = LEN;\n            break;\n        case CHECK:\n            if (state->wrap) {\n                NEEDBITS(32);\n                out -= left;\n                strm->total_out += out;\n                state->total += out;\n                if ((state->wrap & 4) && out)\n                    strm->adler = state->check =\n                        UPDATE(state->check, put - out, out);\n                out = left;\n                if ((state->wrap & 4) && (\n#ifdef GUNZIP\n                     state->flags ? hold :\n#endif\n                     ZSWAP32(hold)) != state->check) {\n                    strm->msg = (char *)\"incorrect data check\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n                Tracev((stderr, \"inflate:   check matches trailer\\n\"));\n            }\n#ifdef GUNZIP\n            state->mode = LENGTH;\n        case LENGTH:\n            if (state->wrap && state->flags) {\n                NEEDBITS(32);\n                if (hold != (state->total & 0xffffffffUL)) {\n                    strm->msg = (char *)\"incorrect length check\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n                Tracev((stderr, \"inflate:   length matches trailer\\n\"));\n            }\n#endif\n            state->mode = DONE;\n        case DONE:\n            ret = Z_STREAM_END;\n            goto inf_leave;\n        case BAD:\n            ret = Z_DATA_ERROR;\n            goto inf_leave;\n        case MEM:\n            return Z_MEM_ERROR;\n        case SYNC:\n        default:\n            return Z_STREAM_ERROR;\n        }\n\n    /*\n       Return from inflate(), updating the total counts and the check value.\n       If there was no progress during the inflate() call, return a buffer\n       error.  Call updatewindow() to create and/or update the window state.\n       Note: a memory error from inflate() is non-recoverable.\n     */\n  inf_leave:\n    RESTORE();\n    if (state->wsize || (out != strm->avail_out && state->mode < BAD &&\n            (state->mode < CHECK || flush != Z_FINISH)))\n        if (updatewindow(strm, strm->next_out, out - strm->avail_out)) {\n            state->mode = MEM;\n            return Z_MEM_ERROR;\n        }\n    in -= strm->avail_in;\n    out -= strm->avail_out;\n    strm->total_in += in;\n    strm->total_out += out;\n    state->total += out;\n    if ((state->wrap & 4) && out)\n        strm->adler = state->check =\n            UPDATE(state->check, strm->next_out - out, out);\n    strm->data_type = (int)state->bits + (state->last ? 64 : 0) +\n                      (state->mode == TYPE ? 128 : 0) +\n                      (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);\n    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)\n        ret = Z_BUF_ERROR;\n    return ret;\n}\n\nint ZEXPORT inflateEnd(strm)\nz_streamp strm;\n{\n    struct inflate_state FAR *state;\n    if (inflateStateCheck(strm))\n        return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    if (state->window != Z_NULL) ZFREE(strm, state->window);\n    ZFREE(strm, strm->state);\n    strm->state = Z_NULL;\n    Tracev((stderr, \"inflate: end\\n\"));\n    return Z_OK;\n}\n\nint ZEXPORT inflateGetDictionary(strm, dictionary, dictLength)\nz_streamp strm;\nBytef *dictionary;\nuInt *dictLength;\n{\n    struct inflate_state FAR *state;\n\n    /* check state */\n    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n\n    /* copy dictionary */\n    if (state->whave && dictionary != Z_NULL) {\n        zmemcpy(dictionary, state->window + state->wnext,\n                state->whave - state->wnext);\n        zmemcpy(dictionary + state->whave - state->wnext,\n                state->window, state->wnext);\n    }\n    if (dictLength != Z_NULL)\n        *dictLength = state->whave;\n    return Z_OK;\n}\n\nint ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)\nz_streamp strm;\nconst Bytef *dictionary;\nuInt dictLength;\n{\n    struct inflate_state FAR *state;\n    unsigned long dictid;\n    int ret;\n\n    /* check state */\n    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    if (state->wrap != 0 && state->mode != DICT)\n        return Z_STREAM_ERROR;\n\n    /* check for correct dictionary identifier */\n    if (state->mode == DICT) {\n        dictid = adler32(0L, Z_NULL, 0);\n        dictid = adler32(dictid, dictionary, dictLength);\n        if (dictid != state->check)\n            return Z_DATA_ERROR;\n    }\n\n    /* copy dictionary to window using updatewindow(), which will amend the\n       existing dictionary if appropriate */\n    ret = updatewindow(strm, dictionary + dictLength, dictLength);\n    if (ret) {\n        state->mode = MEM;\n        return Z_MEM_ERROR;\n    }\n    state->havedict = 1;\n    Tracev((stderr, \"inflate:   dictionary set\\n\"));\n    return Z_OK;\n}\n\nint ZEXPORT inflateGetHeader(strm, head)\nz_streamp strm;\ngz_headerp head;\n{\n    struct inflate_state FAR *state;\n\n    /* check state */\n    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;\n\n    /* save header structure */\n    state->head = head;\n    head->done = 0;\n    return Z_OK;\n}\n\n/*\n   Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff.  Return when found\n   or when out of input.  When called, *have is the number of pattern bytes\n   found in order so far, in 0..3.  On return *have is updated to the new\n   state.  If on return *have equals four, then the pattern was found and the\n   return value is how many bytes were read including the last byte of the\n   pattern.  If *have is less than four, then the pattern has not been found\n   yet and the return value is len.  In the latter case, syncsearch() can be\n   called again with more data and the *have state.  *have is initialized to\n   zero for the first call.\n */\nlocal unsigned syncsearch(have, buf, len)\nunsigned FAR *have;\nconst unsigned char FAR *buf;\nunsigned len;\n{\n    unsigned got;\n    unsigned next;\n\n    got = *have;\n    next = 0;\n    while (next < len && got < 4) {\n        if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))\n            got++;\n        else if (buf[next])\n            got = 0;\n        else\n            got = 4 - got;\n        next++;\n    }\n    *have = got;\n    return next;\n}\n\nint ZEXPORT inflateSync(strm)\nz_streamp strm;\n{\n    unsigned len;               /* number of bytes to look at or looked at */\n    unsigned long in, out;      /* temporary to save total_in and total_out */\n    unsigned char buf[4];       /* to restore bit buffer to byte string */\n    struct inflate_state FAR *state;\n\n    /* check parameters */\n    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;\n\n    /* if first time, start search in bit buffer */\n    if (state->mode != SYNC) {\n        state->mode = SYNC;\n        state->hold <<= state->bits & 7;\n        state->bits -= state->bits & 7;\n        len = 0;\n        while (state->bits >= 8) {\n            buf[len++] = (unsigned char)(state->hold);\n            state->hold >>= 8;\n            state->bits -= 8;\n        }\n        state->have = 0;\n        syncsearch(&(state->have), buf, len);\n    }\n\n    /* search available input */\n    len = syncsearch(&(state->have), strm->next_in, strm->avail_in);\n    strm->avail_in -= len;\n    strm->next_in += len;\n    strm->total_in += len;\n\n    /* return no joy or set up to restart inflate() on a new block */\n    if (state->have != 4) return Z_DATA_ERROR;\n    in = strm->total_in;  out = strm->total_out;\n    inflateReset(strm);\n    strm->total_in = in;  strm->total_out = out;\n    state->mode = TYPE;\n    return Z_OK;\n}\n\n/*\n   Returns true if inflate is currently at the end of a block generated by\n   Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP\n   implementation to provide an additional safety check. PPP uses\n   Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored\n   block. When decompressing, PPP checks that at the end of input packet,\n   inflate is waiting for these length bytes.\n */\nint ZEXPORT inflateSyncPoint(strm)\nz_streamp strm;\n{\n    struct inflate_state FAR *state;\n\n    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    return state->mode == STORED && state->bits == 0;\n}\n\nint ZEXPORT inflateCopy(dest, source)\nz_streamp dest;\nz_streamp source;\n{\n    struct inflate_state FAR *state;\n    struct inflate_state FAR *copy;\n    unsigned char FAR *window;\n    unsigned wsize;\n\n    /* check input */\n    if (inflateStateCheck(source) || dest == Z_NULL)\n        return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)source->state;\n\n    /* allocate space */\n    copy = (struct inflate_state FAR *)\n           ZALLOC(source, 1, sizeof(struct inflate_state));\n    if (copy == Z_NULL) return Z_MEM_ERROR;\n    window = Z_NULL;\n    if (state->window != Z_NULL) {\n        window = (unsigned char FAR *)\n                 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));\n        if (window == Z_NULL) {\n            ZFREE(source, copy);\n            return Z_MEM_ERROR;\n        }\n    }\n\n    /* copy state */\n    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));\n    zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state));\n    copy->strm = dest;\n    if (state->lencode >= state->codes &&\n        state->lencode <= state->codes + ENOUGH - 1) {\n        copy->lencode = copy->codes + (state->lencode - state->codes);\n        copy->distcode = copy->codes + (state->distcode - state->codes);\n    }\n    copy->next = copy->codes + (state->next - state->codes);\n    if (window != Z_NULL) {\n        wsize = 1U << state->wbits;\n        zmemcpy(window, state->window, wsize);\n    }\n    copy->window = window;\n    dest->state = (struct internal_state FAR *)copy;\n    return Z_OK;\n}\n\nint ZEXPORT inflateUndermine(strm, subvert)\nz_streamp strm;\nint subvert;\n{\n    struct inflate_state FAR *state;\n\n    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n    state->sane = !subvert;\n    return Z_OK;\n#else\n    (void)subvert;\n    state->sane = 1;\n    return Z_DATA_ERROR;\n#endif\n}\n\nint ZEXPORT inflateValidate(strm, check)\nz_streamp strm;\nint check;\n{\n    struct inflate_state FAR *state;\n\n    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    if (check)\n        state->wrap |= 4;\n    else\n        state->wrap &= ~4;\n    return Z_OK;\n}\n\nlong ZEXPORT inflateMark(strm)\nz_streamp strm;\n{\n    struct inflate_state FAR *state;\n\n    if (inflateStateCheck(strm))\n        return -(1L << 16);\n    state = (struct inflate_state FAR *)strm->state;\n    return (long)(((unsigned long)((long)state->back)) << 16) +\n        (state->mode == COPY ? state->length :\n            (state->mode == MATCH ? state->was - state->length : 0));\n}\n\nunsigned long ZEXPORT inflateCodesUsed(strm)\nz_streamp strm;\n{\n    struct inflate_state FAR *state;\n    if (inflateStateCheck(strm)) return (unsigned long)-1;\n    state = (struct inflate_state FAR *)strm->state;\n    return (unsigned long)(state->next - state->codes);\n}\n"
  },
  {
    "path": "jsb_build/websockets/zlib/inflate.h",
    "content": "/* inflate.h -- internal inflate state definition\n * Copyright (C) 1995-2016 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* WARNING: this file should *not* be used by applications. It is\n   part of the implementation of the compression library and is\n   subject to change. Applications should only use zlib.h.\n */\n\n/* define NO_GZIP when compiling if you want to disable gzip header and\n   trailer decoding by inflate().  NO_GZIP would be used to avoid linking in\n   the crc code when it is not needed.  For shared libraries, gzip decoding\n   should be left enabled. */\n#ifndef NO_GZIP\n#  define GUNZIP\n#endif\n\n/* Possible inflate modes between inflate() calls */\ntypedef enum {\n    HEAD = 16180,   /* i: waiting for magic header */\n    FLAGS,      /* i: waiting for method and flags (gzip) */\n    TIME,       /* i: waiting for modification time (gzip) */\n    OS,         /* i: waiting for extra flags and operating system (gzip) */\n    EXLEN,      /* i: waiting for extra length (gzip) */\n    EXTRA,      /* i: waiting for extra bytes (gzip) */\n    NAME,       /* i: waiting for end of file name (gzip) */\n    COMMENT,    /* i: waiting for end of comment (gzip) */\n    HCRC,       /* i: waiting for header crc (gzip) */\n    DICTID,     /* i: waiting for dictionary check value */\n    DICT,       /* waiting for inflateSetDictionary() call */\n        TYPE,       /* i: waiting for type bits, including last-flag bit */\n        TYPEDO,     /* i: same, but skip check to exit inflate on new block */\n        STORED,     /* i: waiting for stored size (length and complement) */\n        COPY_,      /* i/o: same as COPY below, but only first time in */\n        COPY,       /* i/o: waiting for input or output to copy stored block */\n        TABLE,      /* i: waiting for dynamic block table lengths */\n        LENLENS,    /* i: waiting for code length code lengths */\n        CODELENS,   /* i: waiting for length/lit and distance code lengths */\n            LEN_,       /* i: same as LEN below, but only first time in */\n            LEN,        /* i: waiting for length/lit/eob code */\n            LENEXT,     /* i: waiting for length extra bits */\n            DIST,       /* i: waiting for distance code */\n            DISTEXT,    /* i: waiting for distance extra bits */\n            MATCH,      /* o: waiting for output space to copy string */\n            LIT,        /* o: waiting for output space to write literal */\n    CHECK,      /* i: waiting for 32-bit check value */\n    LENGTH,     /* i: waiting for 32-bit length (gzip) */\n    DONE,       /* finished check, done -- remain here until reset */\n    BAD,        /* got a data error -- remain here until reset */\n    MEM,        /* got an inflate() memory error -- remain here until reset */\n    SYNC        /* looking for synchronization bytes to restart inflate() */\n} inflate_mode;\n\n/*\n    State transitions between above modes -\n\n    (most modes can go to BAD or MEM on error -- not shown for clarity)\n\n    Process header:\n        HEAD -> (gzip) or (zlib) or (raw)\n        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT ->\n                  HCRC -> TYPE\n        (zlib) -> DICTID or TYPE\n        DICTID -> DICT -> TYPE\n        (raw) -> TYPEDO\n    Read deflate blocks:\n            TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK\n            STORED -> COPY_ -> COPY -> TYPE\n            TABLE -> LENLENS -> CODELENS -> LEN_\n            LEN_ -> LEN\n    Read deflate codes in fixed or dynamic block:\n                LEN -> LENEXT or LIT or TYPE\n                LENEXT -> DIST -> DISTEXT -> MATCH -> LEN\n                LIT -> LEN\n    Process trailer:\n        CHECK -> LENGTH -> DONE\n */\n\n/* State maintained between inflate() calls -- approximately 7K bytes, not\n   including the allocated sliding window, which is up to 32K bytes. */\nstruct inflate_state {\n    z_streamp strm;             /* pointer back to this zlib stream */\n    inflate_mode mode;          /* current inflate mode */\n    int last;                   /* true if processing last block */\n    int wrap;                   /* bit 0 true for zlib, bit 1 true for gzip,\n                                   bit 2 true to validate check value */\n    int havedict;               /* true if dictionary provided */\n    int flags;                  /* gzip header method and flags (0 if zlib) */\n    unsigned dmax;              /* zlib header max distance (INFLATE_STRICT) */\n    unsigned long check;        /* protected copy of check value */\n    unsigned long total;        /* protected copy of output count */\n    gz_headerp head;            /* where to save gzip header information */\n        /* sliding window */\n    unsigned wbits;             /* log base 2 of requested window size */\n    unsigned wsize;             /* window size or zero if not using window */\n    unsigned whave;             /* valid bytes in the window */\n    unsigned wnext;             /* window write index */\n    unsigned char FAR *window;  /* allocated sliding window, if needed */\n        /* bit accumulator */\n    unsigned long hold;         /* input bit accumulator */\n    unsigned bits;              /* number of bits in \"in\" */\n        /* for string and stored block copying */\n    unsigned length;            /* literal or length of data to copy */\n    unsigned offset;            /* distance back to copy string from */\n        /* for table and code decoding */\n    unsigned extra;             /* extra bits needed */\n        /* fixed and dynamic code tables */\n    code const FAR *lencode;    /* starting table for length/literal codes */\n    code const FAR *distcode;   /* starting table for distance codes */\n    unsigned lenbits;           /* index bits for lencode */\n    unsigned distbits;          /* index bits for distcode */\n        /* dynamic table building */\n    unsigned ncode;             /* number of code length code lengths */\n    unsigned nlen;              /* number of length code lengths */\n    unsigned ndist;             /* number of distance code lengths */\n    unsigned have;              /* number of code lengths in lens[] */\n    code FAR *next;             /* next available space in codes[] */\n    unsigned short lens[320];   /* temporary storage for code lengths */\n    unsigned short work[288];   /* work area for code table building */\n    code codes[ENOUGH];         /* space for code tables */\n    int sane;                   /* if false, allow invalid distance too far */\n    int back;                   /* bits back of last unprocessed length/lit */\n    unsigned was;               /* initial length of match */\n};\n"
  },
  {
    "path": "jsb_build/websockets/zlib/inftrees.c",
    "content": "/* inftrees.c -- generate Huffman trees for efficient decoding\n * Copyright (C) 1995-2017 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n#include \"zutil.h\"\n#include \"inftrees.h\"\n\n#define MAXBITS 15\n\nconst char inflate_copyright[] =\n   \" inflate 1.2.11 Copyright 1995-2017 Mark Adler \";\n/*\n  If you use the zlib library in a product, an acknowledgment is welcome\n  in the documentation of your product. If for some reason you cannot\n  include such an acknowledgment, I would appreciate that you keep this\n  copyright string in the executable of your product.\n */\n\n/*\n   Build a set of tables to decode the provided canonical Huffman code.\n   The code lengths are lens[0..codes-1].  The result starts at *table,\n   whose indices are 0..2^bits-1.  work is a writable array of at least\n   lens shorts, which is used as a work area.  type is the type of code\n   to be generated, CODES, LENS, or DISTS.  On return, zero is success,\n   -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table\n   on return points to the next available entry's address.  bits is the\n   requested root table index bits, and on return it is the actual root\n   table index bits.  It will differ if the request is greater than the\n   longest code or if it is less than the shortest code.\n */\nint ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work)\ncodetype type;\nunsigned short FAR *lens;\nunsigned codes;\ncode FAR * FAR *table;\nunsigned FAR *bits;\nunsigned short FAR *work;\n{\n    unsigned len;               /* a code's length in bits */\n    unsigned sym;               /* index of code symbols */\n    unsigned min, max;          /* minimum and maximum code lengths */\n    unsigned root;              /* number of index bits for root table */\n    unsigned curr;              /* number of index bits for current table */\n    unsigned drop;              /* code bits to drop for sub-table */\n    int left;                   /* number of prefix codes available */\n    unsigned used;              /* code entries in table used */\n    unsigned huff;              /* Huffman code */\n    unsigned incr;              /* for incrementing code, index */\n    unsigned fill;              /* index for replicating entries */\n    unsigned low;               /* low bits for current root entry */\n    unsigned mask;              /* mask for low root bits */\n    code here;                  /* table entry for duplication */\n    code FAR *next;             /* next available space in table */\n    const unsigned short FAR *base;     /* base value table to use */\n    const unsigned short FAR *extra;    /* extra bits table to use */\n    unsigned match;             /* use base and extra for symbol >= match */\n    unsigned short count[MAXBITS+1];    /* number of codes of each length */\n    unsigned short offs[MAXBITS+1];     /* offsets in table for each length */\n    static const unsigned short lbase[31] = { /* Length codes 257..285 base */\n        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};\n    static const unsigned short lext[31] = { /* Length codes 257..285 extra */\n        16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 77, 202};\n    static const unsigned short dbase[32] = { /* Distance codes 0..29 base */\n        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n        8193, 12289, 16385, 24577, 0, 0};\n    static const unsigned short dext[32] = { /* Distance codes 0..29 extra */\n        16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n        23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n        28, 28, 29, 29, 64, 64};\n\n    /*\n       Process a set of code lengths to create a canonical Huffman code.  The\n       code lengths are lens[0..codes-1].  Each length corresponds to the\n       symbols 0..codes-1.  The Huffman code is generated by first sorting the\n       symbols by length from short to long, and retaining the symbol order\n       for codes with equal lengths.  Then the code starts with all zero bits\n       for the first code of the shortest length, and the codes are integer\n       increments for the same length, and zeros are appended as the length\n       increases.  For the deflate format, these bits are stored backwards\n       from their more natural integer increment ordering, and so when the\n       decoding tables are built in the large loop below, the integer codes\n       are incremented backwards.\n\n       This routine assumes, but does not check, that all of the entries in\n       lens[] are in the range 0..MAXBITS.  The caller must assure this.\n       1..MAXBITS is interpreted as that code length.  zero means that that\n       symbol does not occur in this code.\n\n       The codes are sorted by computing a count of codes for each length,\n       creating from that a table of starting indices for each length in the\n       sorted table, and then entering the symbols in order in the sorted\n       table.  The sorted table is work[], with that space being provided by\n       the caller.\n\n       The length counts are used for other purposes as well, i.e. finding\n       the minimum and maximum length codes, determining if there are any\n       codes at all, checking for a valid set of lengths, and looking ahead\n       at length counts to determine sub-table sizes when building the\n       decoding tables.\n     */\n\n    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n    for (len = 0; len <= MAXBITS; len++)\n        count[len] = 0;\n    for (sym = 0; sym < codes; sym++)\n        count[lens[sym]]++;\n\n    /* bound code lengths, force root to be within code lengths */\n    root = *bits;\n    for (max = MAXBITS; max >= 1; max--)\n        if (count[max] != 0) break;\n    if (root > max) root = max;\n    if (max == 0) {                     /* no symbols to code at all */\n        here.op = (unsigned char)64;    /* invalid code marker */\n        here.bits = (unsigned char)1;\n        here.val = (unsigned short)0;\n        *(*table)++ = here;             /* make a table to force an error */\n        *(*table)++ = here;\n        *bits = 1;\n        return 0;     /* no symbols, but wait for decoding to report error */\n    }\n    for (min = 1; min < max; min++)\n        if (count[min] != 0) break;\n    if (root < min) root = min;\n\n    /* check for an over-subscribed or incomplete set of lengths */\n    left = 1;\n    for (len = 1; len <= MAXBITS; len++) {\n        left <<= 1;\n        left -= count[len];\n        if (left < 0) return -1;        /* over-subscribed */\n    }\n    if (left > 0 && (type == CODES || max != 1))\n        return -1;                      /* incomplete set */\n\n    /* generate offsets into symbol table for each length for sorting */\n    offs[1] = 0;\n    for (len = 1; len < MAXBITS; len++)\n        offs[len + 1] = offs[len] + count[len];\n\n    /* sort symbols by length, by symbol order within each length */\n    for (sym = 0; sym < codes; sym++)\n        if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;\n\n    /*\n       Create and fill in decoding tables.  In this loop, the table being\n       filled is at next and has curr index bits.  The code being used is huff\n       with length len.  That code is converted to an index by dropping drop\n       bits off of the bottom.  For codes where len is less than drop + curr,\n       those top drop + curr - len bits are incremented through all values to\n       fill the table with replicated entries.\n\n       root is the number of index bits for the root table.  When len exceeds\n       root, sub-tables are created pointed to by the root entry with an index\n       of the low root bits of huff.  This is saved in low to check for when a\n       new sub-table should be started.  drop is zero when the root table is\n       being filled, and drop is root when sub-tables are being filled.\n\n       When a new sub-table is needed, it is necessary to look ahead in the\n       code lengths to determine what size sub-table is needed.  The length\n       counts are used for this, and so count[] is decremented as codes are\n       entered in the tables.\n\n       used keeps track of how many table entries have been allocated from the\n       provided *table space.  It is checked for LENS and DIST tables against\n       the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n       the initial root table size constants.  See the comments in inftrees.h\n       for more information.\n\n       sym increments through all symbols, and the loop terminates when\n       all codes of length max, i.e. all codes, have been processed.  This\n       routine permits incomplete codes, so another loop after this one fills\n       in the rest of the decoding tables with invalid code markers.\n     */\n\n    /* set up for code type */\n    switch (type) {\n    case CODES:\n        base = extra = work;    /* dummy value--not used */\n        match = 20;\n        break;\n    case LENS:\n        base = lbase;\n        extra = lext;\n        match = 257;\n        break;\n    default:    /* DISTS */\n        base = dbase;\n        extra = dext;\n        match = 0;\n    }\n\n    /* initialize state for loop */\n    huff = 0;                   /* starting code */\n    sym = 0;                    /* starting code symbol */\n    len = min;                  /* starting code length */\n    next = *table;              /* current table to fill in */\n    curr = root;                /* current table index bits */\n    drop = 0;                   /* current bits to drop from code for index */\n    low = (unsigned)(-1);       /* trigger new sub-table when len > root */\n    used = 1U << root;          /* use root table entries */\n    mask = used - 1;            /* mask for comparing low */\n\n    /* check available table space */\n    if ((type == LENS && used > ENOUGH_LENS) ||\n        (type == DISTS && used > ENOUGH_DISTS))\n        return 1;\n\n    /* process all codes and make table entries */\n    for (;;) {\n        /* create table entry */\n        here.bits = (unsigned char)(len - drop);\n        if (work[sym] + 1U < match) {\n            here.op = (unsigned char)0;\n            here.val = work[sym];\n        }\n        else if (work[sym] >= match) {\n            here.op = (unsigned char)(extra[work[sym] - match]);\n            here.val = base[work[sym] - match];\n        }\n        else {\n            here.op = (unsigned char)(32 + 64);         /* end of block */\n            here.val = 0;\n        }\n\n        /* replicate for those indices with low len bits equal to huff */\n        incr = 1U << (len - drop);\n        fill = 1U << curr;\n        min = fill;                 /* save offset to next table */\n        do {\n            fill -= incr;\n            next[(huff >> drop) + fill] = here;\n        } while (fill != 0);\n\n        /* backwards increment the len-bit code huff */\n        incr = 1U << (len - 1);\n        while (huff & incr)\n            incr >>= 1;\n        if (incr != 0) {\n            huff &= incr - 1;\n            huff += incr;\n        }\n        else\n            huff = 0;\n\n        /* go to next symbol, update count, len */\n        sym++;\n        if (--(count[len]) == 0) {\n            if (len == max) break;\n            len = lens[work[sym]];\n        }\n\n        /* create new sub-table if needed */\n        if (len > root && (huff & mask) != low) {\n            /* if first time, transition to sub-tables */\n            if (drop == 0)\n                drop = root;\n\n            /* increment past last table */\n            next += min;            /* here min is 1 << curr */\n\n            /* determine length of next table */\n            curr = len - drop;\n            left = (int)(1 << curr);\n            while (curr + drop < max) {\n                left -= count[curr + drop];\n                if (left <= 0) break;\n                curr++;\n                left <<= 1;\n            }\n\n            /* check for enough space */\n            used += 1U << curr;\n            if ((type == LENS && used > ENOUGH_LENS) ||\n                (type == DISTS && used > ENOUGH_DISTS))\n                return 1;\n\n            /* point entry in root table to sub-table */\n            low = huff & mask;\n            (*table)[low].op = (unsigned char)curr;\n            (*table)[low].bits = (unsigned char)root;\n            (*table)[low].val = (unsigned short)(next - *table);\n        }\n    }\n\n    /* fill in remaining table entry if code is incomplete (guaranteed to have\n       at most one remaining entry, since if the code is incomplete, the\n       maximum code length that was allowed to get this far is one bit) */\n    if (huff != 0) {\n        here.op = (unsigned char)64;            /* invalid code marker */\n        here.bits = (unsigned char)(len - drop);\n        here.val = (unsigned short)0;\n        next[huff] = here;\n    }\n\n    /* set return parameters */\n    *table += used;\n    *bits = root;\n    return 0;\n}\n"
  },
  {
    "path": "jsb_build/websockets/zlib/inftrees.h",
    "content": "/* inftrees.h -- header to use inftrees.c\n * Copyright (C) 1995-2005, 2010 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* WARNING: this file should *not* be used by applications. It is\n   part of the implementation of the compression library and is\n   subject to change. Applications should only use zlib.h.\n */\n\n/* Structure for decoding tables.  Each entry provides either the\n   information needed to do the operation requested by the code that\n   indexed that table entry, or it provides a pointer to another\n   table that indexes more bits of the code.  op indicates whether\n   the entry is a pointer to another table, a literal, a length or\n   distance, an end-of-block, or an invalid code.  For a table\n   pointer, the low four bits of op is the number of index bits of\n   that table.  For a length or distance, the low four bits of op\n   is the number of extra bits to get after the code.  bits is\n   the number of bits in this code or part of the code to drop off\n   of the bit buffer.  val is the actual byte to output in the case\n   of a literal, the base length or distance, or the offset from\n   the current table to the next table.  Each entry is four bytes. */\ntypedef struct {\n    unsigned char op;           /* operation, extra bits, table bits */\n    unsigned char bits;         /* bits in this part of the code */\n    unsigned short val;         /* offset in table or code value */\n} code;\n\n/* op values as set by inflate_table():\n    00000000 - literal\n    0000tttt - table link, tttt != 0 is the number of table index bits\n    0001eeee - length or distance, eeee is the number of extra bits\n    01100000 - end of block\n    01000000 - invalid code\n */\n\n/* Maximum size of the dynamic table.  The maximum number of code structures is\n   1444, which is the sum of 852 for literal/length codes and 592 for distance\n   codes.  These values were found by exhaustive searches using the program\n   examples/enough.c found in the zlib distribtution.  The arguments to that\n   program are the number of symbols, the initial root table size, and the\n   maximum bit length of a code.  \"enough 286 9 15\" for literal/length codes\n   returns returns 852, and \"enough 30 6 15\" for distance codes returns 592.\n   The initial root table size (9 or 6) is found in the fifth argument of the\n   inflate_table() calls in inflate.c and infback.c.  If the root table size is\n   changed, then these maximum sizes would be need to be recalculated and\n   updated. */\n#define ENOUGH_LENS 852\n#define ENOUGH_DISTS 592\n#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)\n\n/* Type of code to build for inflate_table() */\ntypedef enum {\n    CODES,\n    LENS,\n    DISTS\n} codetype;\n\nint ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens,\n                             unsigned codes, code FAR * FAR *table,\n                             unsigned FAR *bits, unsigned short FAR *work));\n"
  },
  {
    "path": "jsb_build/websockets/zlib/trees.c",
    "content": "/* trees.c -- output deflated data using Huffman coding\n * Copyright (C) 1995-2017 Jean-loup Gailly\n * detect_data_type() function provided freely by Cosmin Truta, 2006\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/*\n *  ALGORITHM\n *\n *      The \"deflation\" process uses several Huffman trees. The more\n *      common source values are represented by shorter bit sequences.\n *\n *      Each code tree is stored in a compressed form which is itself\n * a Huffman encoding of the lengths of all the code strings (in\n * ascending order by source values).  The actual code strings are\n * reconstructed from the lengths in the inflate process, as described\n * in the deflate specification.\n *\n *  REFERENCES\n *\n *      Deutsch, L.P.,\"'Deflate' Compressed Data Format Specification\".\n *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc\n *\n *      Storer, James A.\n *          Data Compression:  Methods and Theory, pp. 49-50.\n *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.\n *\n *      Sedgewick, R.\n *          Algorithms, p290.\n *          Addison-Wesley, 1983. ISBN 0-201-06672-6.\n */\n\n/* @(#) $Id$ */\n\n/* #define GEN_TREES_H */\n\n#include \"deflate.h\"\n\n#ifdef ZLIB_DEBUG\n#  include <ctype.h>\n#endif\n\n/* ===========================================================================\n * Constants\n */\n\n#define MAX_BL_BITS 7\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\n#define END_BLOCK 256\n/* end of block literal code */\n\n#define REP_3_6      16\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\n#define REPZ_3_10    17\n/* repeat a zero length 3-10 times  (3 bits of repeat count) */\n\n#define REPZ_11_138  18\n/* repeat a zero length 11-138 times  (7 bits of repeat count) */\n\nlocal const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */\n   = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};\n\nlocal const int extra_dbits[D_CODES] /* extra bits for each distance code */\n   = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};\n\nlocal const int extra_blbits[BL_CODES]/* extra bits for each bit length code */\n   = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};\n\nlocal const uch bl_order[BL_CODES]\n   = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n#define DIST_CODE_LEN  512 /* see definition of array dist_code below */\n\n#if defined(GEN_TREES_H) || !defined(STDC)\n/* non ANSI compilers may not accept trees.h */\n\nlocal ct_data static_ltree[L_CODES+2];\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nlocal ct_data static_dtree[D_CODES];\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nuch _dist_code[DIST_CODE_LEN];\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nuch _length_code[MAX_MATCH-MIN_MATCH+1];\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nlocal int base_length[LENGTH_CODES];\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nlocal int base_dist[D_CODES];\n/* First normalized distance for each code (0 = distance of 1) */\n\n#else\n#  include \"trees.h\"\n#endif /* GEN_TREES_H */\n\nstruct static_tree_desc_s {\n    const ct_data *static_tree;  /* static tree or NULL */\n    const intf *extra_bits;      /* extra bits for each code or NULL */\n    int     extra_base;          /* base index for extra_bits */\n    int     elems;               /* max number of elements in the tree */\n    int     max_length;          /* max bit length for the codes */\n};\n\nlocal const static_tree_desc  static_l_desc =\n{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};\n\nlocal const static_tree_desc  static_d_desc =\n{static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};\n\nlocal const static_tree_desc  static_bl_desc =\n{(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};\n\n/* ===========================================================================\n * Local (static) routines in this file.\n */\n\nlocal void tr_static_init OF((void));\nlocal void init_block     OF((deflate_state *s));\nlocal void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));\nlocal void gen_bitlen     OF((deflate_state *s, tree_desc *desc));\nlocal void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));\nlocal void build_tree     OF((deflate_state *s, tree_desc *desc));\nlocal void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));\nlocal void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));\nlocal int  build_bl_tree  OF((deflate_state *s));\nlocal void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,\n                              int blcodes));\nlocal void compress_block OF((deflate_state *s, const ct_data *ltree,\n                              const ct_data *dtree));\nlocal int  detect_data_type OF((deflate_state *s));\nlocal unsigned bi_reverse OF((unsigned value, int length));\nlocal void bi_windup      OF((deflate_state *s));\nlocal void bi_flush       OF((deflate_state *s));\n\n#ifdef GEN_TREES_H\nlocal void gen_trees_header OF((void));\n#endif\n\n#ifndef ZLIB_DEBUG\n#  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)\n   /* Send a code of the given tree. c and tree must not have side effects */\n\n#else /* !ZLIB_DEBUG */\n#  define send_code(s, c, tree) \\\n     { if (z_verbose>2) fprintf(stderr,\"\\ncd %3d \",(c)); \\\n       send_bits(s, tree[c].Code, tree[c].Len); }\n#endif\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\n#define put_short(s, w) { \\\n    put_byte(s, (uch)((w) & 0xff)); \\\n    put_byte(s, (uch)((ush)(w) >> 8)); \\\n}\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\n#ifdef ZLIB_DEBUG\nlocal void send_bits      OF((deflate_state *s, int value, int length));\n\nlocal void send_bits(s, value, length)\n    deflate_state *s;\n    int value;  /* value to send */\n    int length; /* number of bits */\n{\n    Tracevv((stderr,\" l %2d v %4x \", length, value));\n    Assert(length > 0 && length <= 15, \"invalid length\");\n    s->bits_sent += (ulg)length;\n\n    /* If not enough room in bi_buf, use (valid) bits from bi_buf and\n     * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))\n     * unused bits in value.\n     */\n    if (s->bi_valid > (int)Buf_size - length) {\n        s->bi_buf |= (ush)value << s->bi_valid;\n        put_short(s, s->bi_buf);\n        s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);\n        s->bi_valid += length - Buf_size;\n    } else {\n        s->bi_buf |= (ush)value << s->bi_valid;\n        s->bi_valid += length;\n    }\n}\n#else /* !ZLIB_DEBUG */\n\n#define send_bits(s, value, length) \\\n{ int len = length;\\\n  if (s->bi_valid > (int)Buf_size - len) {\\\n    int val = (int)value;\\\n    s->bi_buf |= (ush)val << s->bi_valid;\\\n    put_short(s, s->bi_buf);\\\n    s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\\\n    s->bi_valid += len - Buf_size;\\\n  } else {\\\n    s->bi_buf |= (ush)(value) << s->bi_valid;\\\n    s->bi_valid += len;\\\n  }\\\n}\n#endif /* ZLIB_DEBUG */\n\n\n/* the arguments must not have side effects */\n\n/* ===========================================================================\n * Initialize the various 'constant' tables.\n */\nlocal void tr_static_init()\n{\n#if defined(GEN_TREES_H) || !defined(STDC)\n    static int static_init_done = 0;\n    int n;        /* iterates over tree elements */\n    int bits;     /* bit counter */\n    int length;   /* length value */\n    int code;     /* code value */\n    int dist;     /* distance index */\n    ush bl_count[MAX_BITS+1];\n    /* number of codes at each bit length for an optimal tree */\n\n    if (static_init_done) return;\n\n    /* For some embedded targets, global variables are not initialized: */\n#ifdef NO_INIT_GLOBAL_POINTERS\n    static_l_desc.static_tree = static_ltree;\n    static_l_desc.extra_bits = extra_lbits;\n    static_d_desc.static_tree = static_dtree;\n    static_d_desc.extra_bits = extra_dbits;\n    static_bl_desc.extra_bits = extra_blbits;\n#endif\n\n    /* Initialize the mapping length (0..255) -> length code (0..28) */\n    length = 0;\n    for (code = 0; code < LENGTH_CODES-1; code++) {\n        base_length[code] = length;\n        for (n = 0; n < (1<<extra_lbits[code]); n++) {\n            _length_code[length++] = (uch)code;\n        }\n    }\n    Assert (length == 256, \"tr_static_init: length != 256\");\n    /* Note that the length 255 (match length 258) can be represented\n     * in two different ways: code 284 + 5 bits or code 285, so we\n     * overwrite length_code[255] to use the best encoding:\n     */\n    _length_code[length-1] = (uch)code;\n\n    /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n    dist = 0;\n    for (code = 0 ; code < 16; code++) {\n        base_dist[code] = dist;\n        for (n = 0; n < (1<<extra_dbits[code]); n++) {\n            _dist_code[dist++] = (uch)code;\n        }\n    }\n    Assert (dist == 256, \"tr_static_init: dist != 256\");\n    dist >>= 7; /* from now on, all distances are divided by 128 */\n    for ( ; code < D_CODES; code++) {\n        base_dist[code] = dist << 7;\n        for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {\n            _dist_code[256 + dist++] = (uch)code;\n        }\n    }\n    Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n    /* Construct the codes of the static literal tree */\n    for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;\n    n = 0;\n    while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;\n    while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;\n    while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;\n    while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;\n    /* Codes 286 and 287 do not exist, but we must include them in the\n     * tree construction to get a canonical Huffman tree (longest code\n     * all ones)\n     */\n    gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);\n\n    /* The static distance tree is trivial: */\n    for (n = 0; n < D_CODES; n++) {\n        static_dtree[n].Len = 5;\n        static_dtree[n].Code = bi_reverse((unsigned)n, 5);\n    }\n    static_init_done = 1;\n\n#  ifdef GEN_TREES_H\n    gen_trees_header();\n#  endif\n#endif /* defined(GEN_TREES_H) || !defined(STDC) */\n}\n\n/* ===========================================================================\n * Genererate the file trees.h describing the static trees.\n */\n#ifdef GEN_TREES_H\n#  ifndef ZLIB_DEBUG\n#    include <stdio.h>\n#  endif\n\n#  define SEPARATOR(i, last, width) \\\n      ((i) == (last)? \"\\n};\\n\\n\" :    \\\n       ((i) % (width) == (width)-1 ? \",\\n\" : \", \"))\n\nvoid gen_trees_header()\n{\n    FILE *header = fopen(\"trees.h\", \"w\");\n    int i;\n\n    Assert (header != NULL, \"Can't open trees.h\");\n    fprintf(header,\n            \"/* header created automatically with -DGEN_TREES_H */\\n\\n\");\n\n    fprintf(header, \"local const ct_data static_ltree[L_CODES+2] = {\\n\");\n    for (i = 0; i < L_CODES+2; i++) {\n        fprintf(header, \"{{%3u},{%3u}}%s\", static_ltree[i].Code,\n                static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));\n    }\n\n    fprintf(header, \"local const ct_data static_dtree[D_CODES] = {\\n\");\n    for (i = 0; i < D_CODES; i++) {\n        fprintf(header, \"{{%2u},{%2u}}%s\", static_dtree[i].Code,\n                static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));\n    }\n\n    fprintf(header, \"const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\\n\");\n    for (i = 0; i < DIST_CODE_LEN; i++) {\n        fprintf(header, \"%2u%s\", _dist_code[i],\n                SEPARATOR(i, DIST_CODE_LEN-1, 20));\n    }\n\n    fprintf(header,\n        \"const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\\n\");\n    for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {\n        fprintf(header, \"%2u%s\", _length_code[i],\n                SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));\n    }\n\n    fprintf(header, \"local const int base_length[LENGTH_CODES] = {\\n\");\n    for (i = 0; i < LENGTH_CODES; i++) {\n        fprintf(header, \"%1u%s\", base_length[i],\n                SEPARATOR(i, LENGTH_CODES-1, 20));\n    }\n\n    fprintf(header, \"local const int base_dist[D_CODES] = {\\n\");\n    for (i = 0; i < D_CODES; i++) {\n        fprintf(header, \"%5u%s\", base_dist[i],\n                SEPARATOR(i, D_CODES-1, 10));\n    }\n\n    fclose(header);\n}\n#endif /* GEN_TREES_H */\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nvoid ZLIB_INTERNAL _tr_init(s)\n    deflate_state *s;\n{\n    tr_static_init();\n\n    s->l_desc.dyn_tree = s->dyn_ltree;\n    s->l_desc.stat_desc = &static_l_desc;\n\n    s->d_desc.dyn_tree = s->dyn_dtree;\n    s->d_desc.stat_desc = &static_d_desc;\n\n    s->bl_desc.dyn_tree = s->bl_tree;\n    s->bl_desc.stat_desc = &static_bl_desc;\n\n    s->bi_buf = 0;\n    s->bi_valid = 0;\n#ifdef ZLIB_DEBUG\n    s->compressed_len = 0L;\n    s->bits_sent = 0L;\n#endif\n\n    /* Initialize the first block of the first file: */\n    init_block(s);\n}\n\n/* ===========================================================================\n * Initialize a new block.\n */\nlocal void init_block(s)\n    deflate_state *s;\n{\n    int n; /* iterates over tree elements */\n\n    /* Initialize the trees. */\n    for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;\n    for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;\n    for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;\n\n    s->dyn_ltree[END_BLOCK].Freq = 1;\n    s->opt_len = s->static_len = 0L;\n    s->last_lit = s->matches = 0;\n}\n\n#define SMALLEST 1\n/* Index within the heap array of least frequent node in the Huffman tree */\n\n\n/* ===========================================================================\n * Remove the smallest element from the heap and recreate the heap with\n * one less element. Updates heap and heap_len.\n */\n#define pqremove(s, tree, top) \\\n{\\\n    top = s->heap[SMALLEST]; \\\n    s->heap[SMALLEST] = s->heap[s->heap_len--]; \\\n    pqdownheap(s, tree, SMALLEST); \\\n}\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\n#define smaller(tree, n, m, depth) \\\n   (tree[n].Freq < tree[m].Freq || \\\n   (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nlocal void pqdownheap(s, tree, k)\n    deflate_state *s;\n    ct_data *tree;  /* the tree to restore */\n    int k;               /* node to move down */\n{\n    int v = s->heap[k];\n    int j = k << 1;  /* left son of k */\n    while (j <= s->heap_len) {\n        /* Set j to the smallest of the two sons: */\n        if (j < s->heap_len &&\n            smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {\n            j++;\n        }\n        /* Exit if v is smaller than both sons */\n        if (smaller(tree, v, s->heap[j], s->depth)) break;\n\n        /* Exchange v with the smallest son */\n        s->heap[k] = s->heap[j];  k = j;\n\n        /* And continue down the tree, setting j to the left son of k */\n        j <<= 1;\n    }\n    s->heap[k] = v;\n}\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n *    above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n *     array bl_count contains the frequencies for each bit length.\n *     The length opt_len is updated; static_len is also updated if stree is\n *     not null.\n */\nlocal void gen_bitlen(s, desc)\n    deflate_state *s;\n    tree_desc *desc;    /* the tree descriptor */\n{\n    ct_data *tree        = desc->dyn_tree;\n    int max_code         = desc->max_code;\n    const ct_data *stree = desc->stat_desc->static_tree;\n    const intf *extra    = desc->stat_desc->extra_bits;\n    int base             = desc->stat_desc->extra_base;\n    int max_length       = desc->stat_desc->max_length;\n    int h;              /* heap index */\n    int n, m;           /* iterate over the tree elements */\n    int bits;           /* bit length */\n    int xbits;          /* extra bits */\n    ush f;              /* frequency */\n    int overflow = 0;   /* number of elements with bit length too large */\n\n    for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;\n\n    /* In a first pass, compute the optimal bit lengths (which may\n     * overflow in the case of the bit length tree).\n     */\n    tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */\n\n    for (h = s->heap_max+1; h < HEAP_SIZE; h++) {\n        n = s->heap[h];\n        bits = tree[tree[n].Dad].Len + 1;\n        if (bits > max_length) bits = max_length, overflow++;\n        tree[n].Len = (ush)bits;\n        /* We overwrite tree[n].Dad which is no longer needed */\n\n        if (n > max_code) continue; /* not a leaf node */\n\n        s->bl_count[bits]++;\n        xbits = 0;\n        if (n >= base) xbits = extra[n-base];\n        f = tree[n].Freq;\n        s->opt_len += (ulg)f * (unsigned)(bits + xbits);\n        if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits);\n    }\n    if (overflow == 0) return;\n\n    Tracev((stderr,\"\\nbit length overflow\\n\"));\n    /* This happens for example on obj2 and pic of the Calgary corpus */\n\n    /* Find the first bit length which could increase: */\n    do {\n        bits = max_length-1;\n        while (s->bl_count[bits] == 0) bits--;\n        s->bl_count[bits]--;      /* move one leaf down the tree */\n        s->bl_count[bits+1] += 2; /* move one overflow item as its brother */\n        s->bl_count[max_length]--;\n        /* The brother of the overflow item also moves one step up,\n         * but this does not affect bl_count[max_length]\n         */\n        overflow -= 2;\n    } while (overflow > 0);\n\n    /* Now recompute all bit lengths, scanning in increasing frequency.\n     * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n     * lengths instead of fixing only the wrong ones. This idea is taken\n     * from 'ar' written by Haruhiko Okumura.)\n     */\n    for (bits = max_length; bits != 0; bits--) {\n        n = s->bl_count[bits];\n        while (n != 0) {\n            m = s->heap[--h];\n            if (m > max_code) continue;\n            if ((unsigned) tree[m].Len != (unsigned) bits) {\n                Tracev((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n                s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq;\n                tree[m].Len = (ush)bits;\n            }\n            n--;\n        }\n    }\n}\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n *     zero code length.\n */\nlocal void gen_codes (tree, max_code, bl_count)\n    ct_data *tree;             /* the tree to decorate */\n    int max_code;              /* largest code with non zero frequency */\n    ushf *bl_count;            /* number of codes at each bit length */\n{\n    ush next_code[MAX_BITS+1]; /* next code value for each bit length */\n    unsigned code = 0;         /* running code value */\n    int bits;                  /* bit index */\n    int n;                     /* code index */\n\n    /* The distribution counts are first used to generate the code values\n     * without bit reversal.\n     */\n    for (bits = 1; bits <= MAX_BITS; bits++) {\n        code = (code + bl_count[bits-1]) << 1;\n        next_code[bits] = (ush)code;\n    }\n    /* Check that the bit counts in bl_count are consistent. The last code\n     * must be all ones.\n     */\n    Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,\n            \"inconsistent bit counts\");\n    Tracev((stderr,\"\\ngen_codes: max_code %d \", max_code));\n\n    for (n = 0;  n <= max_code; n++) {\n        int len = tree[n].Len;\n        if (len == 0) continue;\n        /* Now reverse the bits */\n        tree[n].Code = (ush)bi_reverse(next_code[len]++, len);\n\n        Tracecv(tree != static_ltree, (stderr,\"\\nn %3d %c l %2d c %4x (%x) \",\n             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));\n    }\n}\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n *     and corresponding code. The length opt_len is updated; static_len is\n *     also updated if stree is not null. The field max_code is set.\n */\nlocal void build_tree(s, desc)\n    deflate_state *s;\n    tree_desc *desc; /* the tree descriptor */\n{\n    ct_data *tree         = desc->dyn_tree;\n    const ct_data *stree  = desc->stat_desc->static_tree;\n    int elems             = desc->stat_desc->elems;\n    int n, m;          /* iterate over heap elements */\n    int max_code = -1; /* largest code with non zero frequency */\n    int node;          /* new node being created */\n\n    /* Construct the initial heap, with least frequent element in\n     * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n     * heap[0] is not used.\n     */\n    s->heap_len = 0, s->heap_max = HEAP_SIZE;\n\n    for (n = 0; n < elems; n++) {\n        if (tree[n].Freq != 0) {\n            s->heap[++(s->heap_len)] = max_code = n;\n            s->depth[n] = 0;\n        } else {\n            tree[n].Len = 0;\n        }\n    }\n\n    /* The pkzip format requires that at least one distance code exists,\n     * and that at least one bit should be sent even if there is only one\n     * possible code. So to avoid special checks later on we force at least\n     * two codes of non zero frequency.\n     */\n    while (s->heap_len < 2) {\n        node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);\n        tree[node].Freq = 1;\n        s->depth[node] = 0;\n        s->opt_len--; if (stree) s->static_len -= stree[node].Len;\n        /* node is 0 or 1 so it does not have extra bits */\n    }\n    desc->max_code = max_code;\n\n    /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n     * establish sub-heaps of increasing lengths:\n     */\n    for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);\n\n    /* Construct the Huffman tree by repeatedly combining the least two\n     * frequent nodes.\n     */\n    node = elems;              /* next internal node of the tree */\n    do {\n        pqremove(s, tree, n);  /* n = node of least frequency */\n        m = s->heap[SMALLEST]; /* m = node of next least frequency */\n\n        s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */\n        s->heap[--(s->heap_max)] = m;\n\n        /* Create a new node father of n and m */\n        tree[node].Freq = tree[n].Freq + tree[m].Freq;\n        s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?\n                                s->depth[n] : s->depth[m]) + 1);\n        tree[n].Dad = tree[m].Dad = (ush)node;\n#ifdef DUMP_BL_TREE\n        if (tree == s->bl_tree) {\n            fprintf(stderr,\"\\nnode %d(%d), sons %d(%d) %d(%d)\",\n                    node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);\n        }\n#endif\n        /* and insert the new node in the heap */\n        s->heap[SMALLEST] = node++;\n        pqdownheap(s, tree, SMALLEST);\n\n    } while (s->heap_len >= 2);\n\n    s->heap[--(s->heap_max)] = s->heap[SMALLEST];\n\n    /* At this point, the fields freq and dad are set. We can now\n     * generate the bit lengths.\n     */\n    gen_bitlen(s, (tree_desc *)desc);\n\n    /* The field len is now set, we can generate the bit codes */\n    gen_codes ((ct_data *)tree, max_code, s->bl_count);\n}\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nlocal void scan_tree (s, tree, max_code)\n    deflate_state *s;\n    ct_data *tree;   /* the tree to be scanned */\n    int max_code;    /* and its largest code of non zero frequency */\n{\n    int n;                     /* iterates over all tree elements */\n    int prevlen = -1;          /* last emitted length */\n    int curlen;                /* length of current code */\n    int nextlen = tree[0].Len; /* length of next code */\n    int count = 0;             /* repeat count of the current code */\n    int max_count = 7;         /* max repeat count */\n    int min_count = 4;         /* min repeat count */\n\n    if (nextlen == 0) max_count = 138, min_count = 3;\n    tree[max_code+1].Len = (ush)0xffff; /* guard */\n\n    for (n = 0; n <= max_code; n++) {\n        curlen = nextlen; nextlen = tree[n+1].Len;\n        if (++count < max_count && curlen == nextlen) {\n            continue;\n        } else if (count < min_count) {\n            s->bl_tree[curlen].Freq += count;\n        } else if (curlen != 0) {\n            if (curlen != prevlen) s->bl_tree[curlen].Freq++;\n            s->bl_tree[REP_3_6].Freq++;\n        } else if (count <= 10) {\n            s->bl_tree[REPZ_3_10].Freq++;\n        } else {\n            s->bl_tree[REPZ_11_138].Freq++;\n        }\n        count = 0; prevlen = curlen;\n        if (nextlen == 0) {\n            max_count = 138, min_count = 3;\n        } else if (curlen == nextlen) {\n            max_count = 6, min_count = 3;\n        } else {\n            max_count = 7, min_count = 4;\n        }\n    }\n}\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nlocal void send_tree (s, tree, max_code)\n    deflate_state *s;\n    ct_data *tree; /* the tree to be scanned */\n    int max_code;       /* and its largest code of non zero frequency */\n{\n    int n;                     /* iterates over all tree elements */\n    int prevlen = -1;          /* last emitted length */\n    int curlen;                /* length of current code */\n    int nextlen = tree[0].Len; /* length of next code */\n    int count = 0;             /* repeat count of the current code */\n    int max_count = 7;         /* max repeat count */\n    int min_count = 4;         /* min repeat count */\n\n    /* tree[max_code+1].Len = -1; */  /* guard already set */\n    if (nextlen == 0) max_count = 138, min_count = 3;\n\n    for (n = 0; n <= max_code; n++) {\n        curlen = nextlen; nextlen = tree[n+1].Len;\n        if (++count < max_count && curlen == nextlen) {\n            continue;\n        } else if (count < min_count) {\n            do { send_code(s, curlen, s->bl_tree); } while (--count != 0);\n\n        } else if (curlen != 0) {\n            if (curlen != prevlen) {\n                send_code(s, curlen, s->bl_tree); count--;\n            }\n            Assert(count >= 3 && count <= 6, \" 3_6?\");\n            send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);\n\n        } else if (count <= 10) {\n            send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);\n\n        } else {\n            send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);\n        }\n        count = 0; prevlen = curlen;\n        if (nextlen == 0) {\n            max_count = 138, min_count = 3;\n        } else if (curlen == nextlen) {\n            max_count = 6, min_count = 3;\n        } else {\n            max_count = 7, min_count = 4;\n        }\n    }\n}\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nlocal int build_bl_tree(s)\n    deflate_state *s;\n{\n    int max_blindex;  /* index of last bit length code of non zero freq */\n\n    /* Determine the bit length frequencies for literal and distance trees */\n    scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);\n    scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);\n\n    /* Build the bit length tree: */\n    build_tree(s, (tree_desc *)(&(s->bl_desc)));\n    /* opt_len now includes the length of the tree representations, except\n     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n     */\n\n    /* Determine the number of bit length codes to send. The pkzip format\n     * requires that at least 4 bit length codes be sent. (appnote.txt says\n     * 3 but the actual value used is 4.)\n     */\n    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {\n        if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;\n    }\n    /* Update opt_len to include the bit length tree and counts */\n    s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4;\n    Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n            s->opt_len, s->static_len));\n\n    return max_blindex;\n}\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nlocal void send_all_trees(s, lcodes, dcodes, blcodes)\n    deflate_state *s;\n    int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n    int rank;                    /* index in bl_order */\n\n    Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n    Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n            \"too many codes\");\n    Tracev((stderr, \"\\nbl counts: \"));\n    send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */\n    send_bits(s, dcodes-1,   5);\n    send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */\n    for (rank = 0; rank < blcodes; rank++) {\n        Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n        send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);\n    }\n    Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n    send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */\n    Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n    send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */\n    Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n}\n\n/* ===========================================================================\n * Send a stored block\n */\nvoid ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)\n    deflate_state *s;\n    charf *buf;       /* input block */\n    ulg stored_len;   /* length of input block */\n    int last;         /* one if this is the last block for a file */\n{\n    send_bits(s, (STORED_BLOCK<<1)+last, 3);    /* send block type */\n    bi_windup(s);        /* align on byte boundary */\n    put_short(s, (ush)stored_len);\n    put_short(s, (ush)~stored_len);\n    zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len);\n    s->pending += stored_len;\n#ifdef ZLIB_DEBUG\n    s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;\n    s->compressed_len += (stored_len + 4) << 3;\n    s->bits_sent += 2*16;\n    s->bits_sent += stored_len<<3;\n#endif\n}\n\n/* ===========================================================================\n * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)\n */\nvoid ZLIB_INTERNAL _tr_flush_bits(s)\n    deflate_state *s;\n{\n    bi_flush(s);\n}\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nvoid ZLIB_INTERNAL _tr_align(s)\n    deflate_state *s;\n{\n    send_bits(s, STATIC_TREES<<1, 3);\n    send_code(s, END_BLOCK, static_ltree);\n#ifdef ZLIB_DEBUG\n    s->compressed_len += 10L; /* 3 for block type, 7 for EOB */\n#endif\n    bi_flush(s);\n}\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and write out the encoded block.\n */\nvoid ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)\n    deflate_state *s;\n    charf *buf;       /* input block, or NULL if too old */\n    ulg stored_len;   /* length of input block */\n    int last;         /* one if this is the last block for a file */\n{\n    ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n    int max_blindex = 0;  /* index of last bit length code of non zero freq */\n\n    /* Build the Huffman trees unless a stored block is forced */\n    if (s->level > 0) {\n\n        /* Check if the file is binary or text */\n        if (s->strm->data_type == Z_UNKNOWN)\n            s->strm->data_type = detect_data_type(s);\n\n        /* Construct the literal and distance trees */\n        build_tree(s, (tree_desc *)(&(s->l_desc)));\n        Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n                s->static_len));\n\n        build_tree(s, (tree_desc *)(&(s->d_desc)));\n        Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n                s->static_len));\n        /* At this point, opt_len and static_len are the total bit lengths of\n         * the compressed block data, excluding the tree representations.\n         */\n\n        /* Build the bit length tree for the above two trees, and get the index\n         * in bl_order of the last bit length code to send.\n         */\n        max_blindex = build_bl_tree(s);\n\n        /* Determine the best encoding. Compute the block lengths in bytes. */\n        opt_lenb = (s->opt_len+3+7)>>3;\n        static_lenb = (s->static_len+3+7)>>3;\n\n        Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n                opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n                s->last_lit));\n\n        if (static_lenb <= opt_lenb) opt_lenb = static_lenb;\n\n    } else {\n        Assert(buf != (char*)0, \"lost buf\");\n        opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n    }\n\n#ifdef FORCE_STORED\n    if (buf != (char*)0) { /* force stored block */\n#else\n    if (stored_len+4 <= opt_lenb && buf != (char*)0) {\n                       /* 4: two words for the lengths */\n#endif\n        /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n         * Otherwise we can't have processed more than WSIZE input bytes since\n         * the last block flush, because compression would have been\n         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n         * transform a block into a stored block.\n         */\n        _tr_stored_block(s, buf, stored_len, last);\n\n#ifdef FORCE_STATIC\n    } else if (static_lenb >= 0) { /* force static trees */\n#else\n    } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {\n#endif\n        send_bits(s, (STATIC_TREES<<1)+last, 3);\n        compress_block(s, (const ct_data *)static_ltree,\n                       (const ct_data *)static_dtree);\n#ifdef ZLIB_DEBUG\n        s->compressed_len += 3 + s->static_len;\n#endif\n    } else {\n        send_bits(s, (DYN_TREES<<1)+last, 3);\n        send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,\n                       max_blindex+1);\n        compress_block(s, (const ct_data *)s->dyn_ltree,\n                       (const ct_data *)s->dyn_dtree);\n#ifdef ZLIB_DEBUG\n        s->compressed_len += 3 + s->opt_len;\n#endif\n    }\n    Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n    /* The above check is made mod 2^32, for files larger than 512 MB\n     * and uLong implemented on 32 bits.\n     */\n    init_block(s);\n\n    if (last) {\n        bi_windup(s);\n#ifdef ZLIB_DEBUG\n        s->compressed_len += 7;  /* align on byte boundary */\n#endif\n    }\n    Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n           s->compressed_len-7*last));\n}\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nint ZLIB_INTERNAL _tr_tally (s, dist, lc)\n    deflate_state *s;\n    unsigned dist;  /* distance of matched string */\n    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */\n{\n    s->d_buf[s->last_lit] = (ush)dist;\n    s->l_buf[s->last_lit++] = (uch)lc;\n    if (dist == 0) {\n        /* lc is the unmatched char */\n        s->dyn_ltree[lc].Freq++;\n    } else {\n        s->matches++;\n        /* Here, lc is the match length - MIN_MATCH */\n        dist--;             /* dist = match distance - 1 */\n        Assert((ush)dist < (ush)MAX_DIST(s) &&\n               (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n               (ush)d_code(dist) < (ush)D_CODES,  \"_tr_tally: bad match\");\n\n        s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;\n        s->dyn_dtree[d_code(dist)].Freq++;\n    }\n\n#ifdef TRUNCATE_BLOCK\n    /* Try to guess if it is profitable to stop the current block here */\n    if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {\n        /* Compute an upper bound for the compressed length */\n        ulg out_length = (ulg)s->last_lit*8L;\n        ulg in_length = (ulg)((long)s->strstart - s->block_start);\n        int dcode;\n        for (dcode = 0; dcode < D_CODES; dcode++) {\n            out_length += (ulg)s->dyn_dtree[dcode].Freq *\n                (5L+extra_dbits[dcode]);\n        }\n        out_length >>= 3;\n        Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n               s->last_lit, in_length, out_length,\n               100L - out_length*100L/in_length));\n        if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;\n    }\n#endif\n    return (s->last_lit == s->lit_bufsize-1);\n    /* We avoid equality with lit_bufsize because of wraparound at 64K\n     * on 16 bit machines and because stored blocks are restricted to\n     * 64K-1 bytes.\n     */\n}\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nlocal void compress_block(s, ltree, dtree)\n    deflate_state *s;\n    const ct_data *ltree; /* literal tree */\n    const ct_data *dtree; /* distance tree */\n{\n    unsigned dist;      /* distance of matched string */\n    int lc;             /* match length or unmatched char (if dist == 0) */\n    unsigned lx = 0;    /* running index in l_buf */\n    unsigned code;      /* the code to send */\n    int extra;          /* number of extra bits to send */\n\n    if (s->last_lit != 0) do {\n        dist = s->d_buf[lx];\n        lc = s->l_buf[lx++];\n        if (dist == 0) {\n            send_code(s, lc, ltree); /* send a literal byte */\n            Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n        } else {\n            /* Here, lc is the match length - MIN_MATCH */\n            code = _length_code[lc];\n            send_code(s, code+LITERALS+1, ltree); /* send the length code */\n            extra = extra_lbits[code];\n            if (extra != 0) {\n                lc -= base_length[code];\n                send_bits(s, lc, extra);       /* send the extra length bits */\n            }\n            dist--; /* dist is now the match distance - 1 */\n            code = d_code(dist);\n            Assert (code < D_CODES, \"bad d_code\");\n\n            send_code(s, code, dtree);       /* send the distance code */\n            extra = extra_dbits[code];\n            if (extra != 0) {\n                dist -= (unsigned)base_dist[code];\n                send_bits(s, dist, extra);   /* send the extra distance bits */\n            }\n        } /* literal or match pair ? */\n\n        /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n        Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n               \"pendingBuf overflow\");\n\n    } while (lx < s->last_lit);\n\n    send_code(s, END_BLOCK, ltree);\n}\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n *    a) There are no non-portable control characters belonging to the\n *       \"black list\" (0..6, 14..25, 28..31).\n *    b) There is at least one printable character belonging to the\n *       \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n *   \"gray list\" that is ignored in this detection algorithm:\n *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nlocal int detect_data_type(s)\n    deflate_state *s;\n{\n    /* black_mask is the bit mask of black-listed bytes\n     * set bits 0..6, 14..25, and 28..31\n     * 0xf3ffc07f = binary 11110011111111111100000001111111\n     */\n    unsigned long black_mask = 0xf3ffc07fUL;\n    int n;\n\n    /* Check for non-textual (\"black-listed\") bytes. */\n    for (n = 0; n <= 31; n++, black_mask >>= 1)\n        if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))\n            return Z_BINARY;\n\n    /* Check for textual (\"white-listed\") bytes. */\n    if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0\n            || s->dyn_ltree[13].Freq != 0)\n        return Z_TEXT;\n    for (n = 32; n < LITERALS; n++)\n        if (s->dyn_ltree[n].Freq != 0)\n            return Z_TEXT;\n\n    /* There are no \"black-listed\" or \"white-listed\" bytes:\n     * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n     */\n    return Z_BINARY;\n}\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nlocal unsigned bi_reverse(code, len)\n    unsigned code; /* the value to invert */\n    int len;       /* its bit length */\n{\n    register unsigned res = 0;\n    do {\n        res |= code & 1;\n        code >>= 1, res <<= 1;\n    } while (--len > 0);\n    return res >> 1;\n}\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nlocal void bi_flush(s)\n    deflate_state *s;\n{\n    if (s->bi_valid == 16) {\n        put_short(s, s->bi_buf);\n        s->bi_buf = 0;\n        s->bi_valid = 0;\n    } else if (s->bi_valid >= 8) {\n        put_byte(s, (Byte)s->bi_buf);\n        s->bi_buf >>= 8;\n        s->bi_valid -= 8;\n    }\n}\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nlocal void bi_windup(s)\n    deflate_state *s;\n{\n    if (s->bi_valid > 8) {\n        put_short(s, s->bi_buf);\n    } else if (s->bi_valid > 0) {\n        put_byte(s, (Byte)s->bi_buf);\n    }\n    s->bi_buf = 0;\n    s->bi_valid = 0;\n#ifdef ZLIB_DEBUG\n    s->bits_sent = (s->bits_sent+7) & ~7;\n#endif\n}\n"
  },
  {
    "path": "jsb_build/websockets/zlib/trees.h",
    "content": "/* header created automatically with -DGEN_TREES_H */\n\nlocal const ct_data static_ltree[L_CODES+2] = {\n{{ 12},{  8}}, {{140},{  8}}, {{ 76},{  8}}, {{204},{  8}}, {{ 44},{  8}},\n{{172},{  8}}, {{108},{  8}}, {{236},{  8}}, {{ 28},{  8}}, {{156},{  8}},\n{{ 92},{  8}}, {{220},{  8}}, {{ 60},{  8}}, {{188},{  8}}, {{124},{  8}},\n{{252},{  8}}, {{  2},{  8}}, {{130},{  8}}, {{ 66},{  8}}, {{194},{  8}},\n{{ 34},{  8}}, {{162},{  8}}, {{ 98},{  8}}, {{226},{  8}}, {{ 18},{  8}},\n{{146},{  8}}, {{ 82},{  8}}, {{210},{  8}}, {{ 50},{  8}}, {{178},{  8}},\n{{114},{  8}}, {{242},{  8}}, {{ 10},{  8}}, {{138},{  8}}, {{ 74},{  8}},\n{{202},{  8}}, {{ 42},{  8}}, {{170},{  8}}, {{106},{  8}}, {{234},{  8}},\n{{ 26},{  8}}, {{154},{  8}}, {{ 90},{  8}}, {{218},{  8}}, {{ 58},{  8}},\n{{186},{  8}}, {{122},{  8}}, {{250},{  8}}, {{  6},{  8}}, {{134},{  8}},\n{{ 70},{  8}}, {{198},{  8}}, {{ 38},{  8}}, {{166},{  8}}, {{102},{  8}},\n{{230},{  8}}, {{ 22},{  8}}, {{150},{  8}}, {{ 86},{  8}}, {{214},{  8}},\n{{ 54},{  8}}, {{182},{  8}}, {{118},{  8}}, {{246},{  8}}, {{ 14},{  8}},\n{{142},{  8}}, {{ 78},{  8}}, {{206},{  8}}, {{ 46},{  8}}, {{174},{  8}},\n{{110},{  8}}, {{238},{  8}}, {{ 30},{  8}}, {{158},{  8}}, {{ 94},{  8}},\n{{222},{  8}}, {{ 62},{  8}}, {{190},{  8}}, {{126},{  8}}, {{254},{  8}},\n{{  1},{  8}}, {{129},{  8}}, {{ 65},{  8}}, {{193},{  8}}, {{ 33},{  8}},\n{{161},{  8}}, {{ 97},{  8}}, {{225},{  8}}, {{ 17},{  8}}, {{145},{  8}},\n{{ 81},{  8}}, {{209},{  8}}, {{ 49},{  8}}, {{177},{  8}}, {{113},{  8}},\n{{241},{  8}}, {{  9},{  8}}, {{137},{  8}}, {{ 73},{  8}}, {{201},{  8}},\n{{ 41},{  8}}, {{169},{  8}}, {{105},{  8}}, {{233},{  8}}, {{ 25},{  8}},\n{{153},{  8}}, {{ 89},{  8}}, {{217},{  8}}, {{ 57},{  8}}, {{185},{  8}},\n{{121},{  8}}, {{249},{  8}}, {{  5},{  8}}, {{133},{  8}}, {{ 69},{  8}},\n{{197},{  8}}, {{ 37},{  8}}, {{165},{  8}}, {{101},{  8}}, {{229},{  8}},\n{{ 21},{  8}}, {{149},{  8}}, {{ 85},{  8}}, {{213},{  8}}, {{ 53},{  8}},\n{{181},{  8}}, {{117},{  8}}, {{245},{  8}}, {{ 13},{  8}}, {{141},{  8}},\n{{ 77},{  8}}, {{205},{  8}}, {{ 45},{  8}}, {{173},{  8}}, {{109},{  8}},\n{{237},{  8}}, {{ 29},{  8}}, {{157},{  8}}, {{ 93},{  8}}, {{221},{  8}},\n{{ 61},{  8}}, {{189},{  8}}, {{125},{  8}}, {{253},{  8}}, {{ 19},{  9}},\n{{275},{  9}}, {{147},{  9}}, {{403},{  9}}, {{ 83},{  9}}, {{339},{  9}},\n{{211},{  9}}, {{467},{  9}}, {{ 51},{  9}}, {{307},{  9}}, {{179},{  9}},\n{{435},{  9}}, {{115},{  9}}, {{371},{  9}}, {{243},{  9}}, {{499},{  9}},\n{{ 11},{  9}}, {{267},{  9}}, {{139},{  9}}, {{395},{  9}}, {{ 75},{  9}},\n{{331},{  9}}, {{203},{  9}}, {{459},{  9}}, {{ 43},{  9}}, {{299},{  9}},\n{{171},{  9}}, {{427},{  9}}, {{107},{  9}}, {{363},{  9}}, {{235},{  9}},\n{{491},{  9}}, {{ 27},{  9}}, {{283},{  9}}, {{155},{  9}}, {{411},{  9}},\n{{ 91},{  9}}, {{347},{  9}}, {{219},{  9}}, {{475},{  9}}, {{ 59},{  9}},\n{{315},{  9}}, {{187},{  9}}, {{443},{  9}}, {{123},{  9}}, {{379},{  9}},\n{{251},{  9}}, {{507},{  9}}, {{  7},{  9}}, {{263},{  9}}, {{135},{  9}},\n{{391},{  9}}, {{ 71},{  9}}, {{327},{  9}}, {{199},{  9}}, {{455},{  9}},\n{{ 39},{  9}}, {{295},{  9}}, {{167},{  9}}, {{423},{  9}}, {{103},{  9}},\n{{359},{  9}}, {{231},{  9}}, {{487},{  9}}, {{ 23},{  9}}, {{279},{  9}},\n{{151},{  9}}, {{407},{  9}}, {{ 87},{  9}}, {{343},{  9}}, {{215},{  9}},\n{{471},{  9}}, {{ 55},{  9}}, {{311},{  9}}, {{183},{  9}}, {{439},{  9}},\n{{119},{  9}}, {{375},{  9}}, {{247},{  9}}, {{503},{  9}}, {{ 15},{  9}},\n{{271},{  9}}, {{143},{  9}}, {{399},{  9}}, {{ 79},{  9}}, {{335},{  9}},\n{{207},{  9}}, {{463},{  9}}, {{ 47},{  9}}, {{303},{  9}}, {{175},{  9}},\n{{431},{  9}}, {{111},{  9}}, {{367},{  9}}, {{239},{  9}}, {{495},{  9}},\n{{ 31},{  9}}, {{287},{  9}}, {{159},{  9}}, {{415},{  9}}, {{ 95},{  9}},\n{{351},{  9}}, {{223},{  9}}, {{479},{  9}}, {{ 63},{  9}}, {{319},{  9}},\n{{191},{  9}}, {{447},{  9}}, {{127},{  9}}, {{383},{  9}}, {{255},{  9}},\n{{511},{  9}}, {{  0},{  7}}, {{ 64},{  7}}, {{ 32},{  7}}, {{ 96},{  7}},\n{{ 16},{  7}}, {{ 80},{  7}}, {{ 48},{  7}}, {{112},{  7}}, {{  8},{  7}},\n{{ 72},{  7}}, {{ 40},{  7}}, {{104},{  7}}, {{ 24},{  7}}, {{ 88},{  7}},\n{{ 56},{  7}}, {{120},{  7}}, {{  4},{  7}}, {{ 68},{  7}}, {{ 36},{  7}},\n{{100},{  7}}, {{ 20},{  7}}, {{ 84},{  7}}, {{ 52},{  7}}, {{116},{  7}},\n{{  3},{  8}}, {{131},{  8}}, {{ 67},{  8}}, {{195},{  8}}, {{ 35},{  8}},\n{{163},{  8}}, {{ 99},{  8}}, {{227},{  8}}\n};\n\nlocal const ct_data static_dtree[D_CODES] = {\n{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},\n{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},\n{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},\n{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},\n{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},\n{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}\n};\n\nconst uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n 0,  1,  2,  3,  4,  4,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  8,\n 8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 10, 10, 10,\n10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,\n11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,\n12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,\n13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,\n13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,\n14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,\n14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,\n14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,\n15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,\n15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,\n15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,  0,  0, 16, 17,\n18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,\n23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,\n26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,\n27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,\n27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,\n28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,\n28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,\n28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,\n29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,\n29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,\n29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29\n};\n\nconst uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n 0,  1,  2,  3,  4,  5,  6,  7,  8,  8,  9,  9, 10, 10, 11, 11, 12, 12, 12, 12,\n13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,\n17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,\n19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,\n22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,\n23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,\n26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,\n26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,\n27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28\n};\n\nlocal const int base_length[LENGTH_CODES] = {\n0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,\n64, 80, 96, 112, 128, 160, 192, 224, 0\n};\n\nlocal const int base_dist[D_CODES] = {\n    0,     1,     2,     3,     4,     6,     8,    12,    16,    24,\n   32,    48,    64,    96,   128,   192,   256,   384,   512,   768,\n 1024,  1536,  2048,  3072,  4096,  6144,  8192, 12288, 16384, 24576\n};\n\n"
  },
  {
    "path": "jsb_build/websockets/zlib/uncompr.c",
    "content": "/* uncompr.c -- decompress a memory buffer\n * Copyright (C) 1995-2003, 2010, 2014, 2016 Jean-loup Gailly, Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* @(#) $Id$ */\n\n#define ZLIB_INTERNAL\n#include \"zlib.h\"\n\n/* ===========================================================================\n     Decompresses the source buffer into the destination buffer.  *sourceLen is\n   the byte length of the source buffer. Upon entry, *destLen is the total size\n   of the destination buffer, which must be large enough to hold the entire\n   uncompressed data. (The size of the uncompressed data must have been saved\n   previously by the compressor and transmitted to the decompressor by some\n   mechanism outside the scope of this compression library.) Upon exit,\n   *destLen is the size of the decompressed data and *sourceLen is the number\n   of source bytes consumed. Upon return, source + *sourceLen points to the\n   first unused input byte.\n\n     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_BUF_ERROR if there was not enough room in the output buffer, or\n   Z_DATA_ERROR if the input data was corrupted, including if the input data is\n   an incomplete zlib stream.\n*/\nint ZEXPORT uncompress2 (dest, destLen, source, sourceLen)\n    Bytef *dest;\n    uLongf *destLen;\n    const Bytef *source;\n    uLong *sourceLen;\n{\n    z_stream stream;\n    int err;\n    const uInt max = (uInt)-1;\n    uLong len, left;\n    Byte buf[1];    /* for detection of incomplete stream when *destLen == 0 */\n\n    len = *sourceLen;\n    if (*destLen) {\n        left = *destLen;\n        *destLen = 0;\n    }\n    else {\n        left = 1;\n        dest = buf;\n    }\n\n    stream.next_in = (z_const Bytef *)source;\n    stream.avail_in = 0;\n    stream.zalloc = (alloc_func)0;\n    stream.zfree = (free_func)0;\n    stream.opaque = (voidpf)0;\n\n    err = inflateInit(&stream);\n    if (err != Z_OK) return err;\n\n    stream.next_out = dest;\n    stream.avail_out = 0;\n\n    do {\n        if (stream.avail_out == 0) {\n            stream.avail_out = left > (uLong)max ? max : (uInt)left;\n            left -= stream.avail_out;\n        }\n        if (stream.avail_in == 0) {\n            stream.avail_in = len > (uLong)max ? max : (uInt)len;\n            len -= stream.avail_in;\n        }\n        err = inflate(&stream, Z_NO_FLUSH);\n    } while (err == Z_OK);\n\n    *sourceLen -= len + stream.avail_in;\n    if (dest != buf)\n        *destLen = stream.total_out;\n    else if (stream.total_out && err == Z_BUF_ERROR)\n        left = 1;\n\n    inflateEnd(&stream);\n    return err == Z_STREAM_END ? Z_OK :\n           err == Z_NEED_DICT ? Z_DATA_ERROR  :\n           err == Z_BUF_ERROR && left + stream.avail_out ? Z_DATA_ERROR :\n           err;\n}\n\nint ZEXPORT uncompress (dest, destLen, source, sourceLen)\n    Bytef *dest;\n    uLongf *destLen;\n    const Bytef *source;\n    uLong sourceLen;\n{\n    return uncompress2(dest, destLen, source, &sourceLen);\n}\n"
  },
  {
    "path": "jsb_build/websockets/zlib/zconf.h",
    "content": "/* zconf.h -- configuration of the zlib compression library\n * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* @(#) $Id$ */\n\n#ifndef ZCONF_H\n#define ZCONF_H\n\n/*\n * If you *really* need a unique prefix for all types and library functions,\n * compile with -DZ_PREFIX. The \"standard\" zlib should be compiled without it.\n * Even better than compiling with -DZ_PREFIX would be to use configure to set\n * this permanently in zconf.h using \"./configure --zprefix\".\n */\n#ifdef Z_PREFIX     /* may be set to #if 1 by ./configure */\n#  define Z_PREFIX_SET\n\n/* all linked symbols and init macros */\n#  define _dist_code            z__dist_code\n#  define _length_code          z__length_code\n#  define _tr_align             z__tr_align\n#  define _tr_flush_bits        z__tr_flush_bits\n#  define _tr_flush_block       z__tr_flush_block\n#  define _tr_init              z__tr_init\n#  define _tr_stored_block      z__tr_stored_block\n#  define _tr_tally             z__tr_tally\n#  define adler32               z_adler32\n#  define adler32_combine       z_adler32_combine\n#  define adler32_combine64     z_adler32_combine64\n#  define adler32_z             z_adler32_z\n#  ifndef Z_SOLO\n#    define compress              z_compress\n#    define compress2             z_compress2\n#    define compressBound         z_compressBound\n#  endif\n#  define crc32                 z_crc32\n#  define crc32_combine         z_crc32_combine\n#  define crc32_combine64       z_crc32_combine64\n#  define crc32_z               z_crc32_z\n#  define deflate               z_deflate\n#  define deflateBound          z_deflateBound\n#  define deflateCopy           z_deflateCopy\n#  define deflateEnd            z_deflateEnd\n#  define deflateGetDictionary  z_deflateGetDictionary\n#  define deflateInit           z_deflateInit\n#  define deflateInit2          z_deflateInit2\n#  define deflateInit2_         z_deflateInit2_\n#  define deflateInit_          z_deflateInit_\n#  define deflateParams         z_deflateParams\n#  define deflatePending        z_deflatePending\n#  define deflatePrime          z_deflatePrime\n#  define deflateReset          z_deflateReset\n#  define deflateResetKeep      z_deflateResetKeep\n#  define deflateSetDictionary  z_deflateSetDictionary\n#  define deflateSetHeader      z_deflateSetHeader\n#  define deflateTune           z_deflateTune\n#  define deflate_copyright     z_deflate_copyright\n#  define get_crc_table         z_get_crc_table\n#  ifndef Z_SOLO\n#    define gz_error              z_gz_error\n#    define gz_intmax             z_gz_intmax\n#    define gz_strwinerror        z_gz_strwinerror\n#    define gzbuffer              z_gzbuffer\n#    define gzclearerr            z_gzclearerr\n#    define gzclose               z_gzclose\n#    define gzclose_r             z_gzclose_r\n#    define gzclose_w             z_gzclose_w\n#    define gzdirect              z_gzdirect\n#    define gzdopen               z_gzdopen\n#    define gzeof                 z_gzeof\n#    define gzerror               z_gzerror\n#    define gzflush               z_gzflush\n#    define gzfread               z_gzfread\n#    define gzfwrite              z_gzfwrite\n#    define gzgetc                z_gzgetc\n#    define gzgetc_               z_gzgetc_\n#    define gzgets                z_gzgets\n#    define gzoffset              z_gzoffset\n#    define gzoffset64            z_gzoffset64\n#    define gzopen                z_gzopen\n#    define gzopen64              z_gzopen64\n#    ifdef _WIN32\n#      define gzopen_w              z_gzopen_w\n#    endif\n#    define gzprintf              z_gzprintf\n#    define gzputc                z_gzputc\n#    define gzputs                z_gzputs\n#    define gzread                z_gzread\n#    define gzrewind              z_gzrewind\n#    define gzseek                z_gzseek\n#    define gzseek64              z_gzseek64\n#    define gzsetparams           z_gzsetparams\n#    define gztell                z_gztell\n#    define gztell64              z_gztell64\n#    define gzungetc              z_gzungetc\n#    define gzvprintf             z_gzvprintf\n#    define gzwrite               z_gzwrite\n#  endif\n#  define inflate               z_inflate\n#  define inflateBack           z_inflateBack\n#  define inflateBackEnd        z_inflateBackEnd\n#  define inflateBackInit       z_inflateBackInit\n#  define inflateBackInit_      z_inflateBackInit_\n#  define inflateCodesUsed      z_inflateCodesUsed\n#  define inflateCopy           z_inflateCopy\n#  define inflateEnd            z_inflateEnd\n#  define inflateGetDictionary  z_inflateGetDictionary\n#  define inflateGetHeader      z_inflateGetHeader\n#  define inflateInit           z_inflateInit\n#  define inflateInit2          z_inflateInit2\n#  define inflateInit2_         z_inflateInit2_\n#  define inflateInit_          z_inflateInit_\n#  define inflateMark           z_inflateMark\n#  define inflatePrime          z_inflatePrime\n#  define inflateReset          z_inflateReset\n#  define inflateReset2         z_inflateReset2\n#  define inflateResetKeep      z_inflateResetKeep\n#  define inflateSetDictionary  z_inflateSetDictionary\n#  define inflateSync           z_inflateSync\n#  define inflateSyncPoint      z_inflateSyncPoint\n#  define inflateUndermine      z_inflateUndermine\n#  define inflateValidate       z_inflateValidate\n#  define inflate_copyright     z_inflate_copyright\n#  define inflate_fast          z_inflate_fast\n#  define inflate_table         z_inflate_table\n#  ifndef Z_SOLO\n#    define uncompress            z_uncompress\n#    define uncompress2           z_uncompress2\n#  endif\n#  define zError                z_zError\n#  ifndef Z_SOLO\n#    define zcalloc               z_zcalloc\n#    define zcfree                z_zcfree\n#  endif\n#  define zlibCompileFlags      z_zlibCompileFlags\n#  define zlibVersion           z_zlibVersion\n\n/* all zlib typedefs in zlib.h and zconf.h */\n#  define Byte                  z_Byte\n#  define Bytef                 z_Bytef\n#  define alloc_func            z_alloc_func\n#  define charf                 z_charf\n#  define free_func             z_free_func\n#  ifndef Z_SOLO\n#    define gzFile                z_gzFile\n#  endif\n#  define gz_header             z_gz_header\n#  define gz_headerp            z_gz_headerp\n#  define in_func               z_in_func\n#  define intf                  z_intf\n#  define out_func              z_out_func\n#  define uInt                  z_uInt\n#  define uIntf                 z_uIntf\n#  define uLong                 z_uLong\n#  define uLongf                z_uLongf\n#  define voidp                 z_voidp\n#  define voidpc                z_voidpc\n#  define voidpf                z_voidpf\n\n/* all zlib structs in zlib.h and zconf.h */\n#  define gz_header_s           z_gz_header_s\n#  define internal_state        z_internal_state\n\n#endif\n\n#if defined(__MSDOS__) && !defined(MSDOS)\n#  define MSDOS\n#endif\n#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)\n#  define OS2\n#endif\n#if defined(_WINDOWS) && !defined(WINDOWS)\n#  define WINDOWS\n#endif\n#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)\n#  ifndef WIN32\n#    define WIN32\n#  endif\n#endif\n#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)\n#  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)\n#    ifndef SYS16BIT\n#      define SYS16BIT\n#    endif\n#  endif\n#endif\n\n/*\n * Compile with -DMAXSEG_64K if the alloc function cannot allocate more\n * than 64k bytes at a time (needed on systems with 16-bit int).\n */\n#ifdef SYS16BIT\n#  define MAXSEG_64K\n#endif\n#ifdef MSDOS\n#  define UNALIGNED_OK\n#endif\n\n#ifdef __STDC_VERSION__\n#  ifndef STDC\n#    define STDC\n#  endif\n#  if __STDC_VERSION__ >= 199901L\n#    ifndef STDC99\n#      define STDC99\n#    endif\n#  endif\n#endif\n#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))\n#  define STDC\n#endif\n#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))\n#  define STDC\n#endif\n#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))\n#  define STDC\n#endif\n#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))\n#  define STDC\n#endif\n\n#if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */\n#  define STDC\n#endif\n\n#ifndef STDC\n#  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */\n#    define const       /* note: need a more gentle solution here */\n#  endif\n#endif\n\n#if defined(ZLIB_CONST) && !defined(z_const)\n#  define z_const const\n#else\n#  define z_const\n#endif\n\n#ifdef Z_SOLO\n   typedef unsigned long z_size_t;\n#else\n#  define z_longlong long long\n#  if defined(NO_SIZE_T)\n     typedef unsigned NO_SIZE_T z_size_t;\n#  elif defined(STDC)\n#    include <stddef.h>\n     typedef size_t z_size_t;\n#  else\n     typedef unsigned long z_size_t;\n#  endif\n#  undef z_longlong\n#endif\n\n/* Maximum value for memLevel in deflateInit2 */\n#ifndef MAX_MEM_LEVEL\n#  ifdef MAXSEG_64K\n#    define MAX_MEM_LEVEL 8\n#  else\n#    define MAX_MEM_LEVEL 9\n#  endif\n#endif\n\n/* Maximum value for windowBits in deflateInit2 and inflateInit2.\n * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files\n * created by gzip. (Files created by minigzip can still be extracted by\n * gzip.)\n */\n#ifndef MAX_WBITS\n#  define MAX_WBITS   15 /* 32K LZ77 window */\n#endif\n\n/* The memory requirements for deflate are (in bytes):\n            (1 << (windowBits+2)) +  (1 << (memLevel+9))\n that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)\n plus a few kilobytes for small objects. For example, if you want to reduce\n the default memory requirements from 256K to 128K, compile with\n     make CFLAGS=\"-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7\"\n Of course this will generally degrade compression (there's no free lunch).\n\n   The memory requirements for inflate are (in bytes) 1 << windowBits\n that is, 32K for windowBits=15 (default value) plus about 7 kilobytes\n for small objects.\n*/\n\n                        /* Type declarations */\n\n#ifndef OF /* function prototypes */\n#  ifdef STDC\n#    define OF(args)  args\n#  else\n#    define OF(args)  ()\n#  endif\n#endif\n\n#ifndef Z_ARG /* function prototypes for stdarg */\n#  if defined(STDC) || defined(Z_HAVE_STDARG_H)\n#    define Z_ARG(args)  args\n#  else\n#    define Z_ARG(args)  ()\n#  endif\n#endif\n\n/* The following definitions for FAR are needed only for MSDOS mixed\n * model programming (small or medium model with some far allocations).\n * This was tested only with MSC; for other MSDOS compilers you may have\n * to define NO_MEMCPY in zutil.h.  If you don't need the mixed model,\n * just define FAR to be empty.\n */\n#ifdef SYS16BIT\n#  if defined(M_I86SM) || defined(M_I86MM)\n     /* MSC small or medium model */\n#    define SMALL_MEDIUM\n#    ifdef _MSC_VER\n#      define FAR _far\n#    else\n#      define FAR far\n#    endif\n#  endif\n#  if (defined(__SMALL__) || defined(__MEDIUM__))\n     /* Turbo C small or medium model */\n#    define SMALL_MEDIUM\n#    ifdef __BORLANDC__\n#      define FAR _far\n#    else\n#      define FAR far\n#    endif\n#  endif\n#endif\n\n#if defined(WINDOWS) || defined(WIN32)\n   /* If building or using zlib as a DLL, define ZLIB_DLL.\n    * This is not mandatory, but it offers a little performance increase.\n    */\n#  ifdef ZLIB_DLL\n#    if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))\n#      ifdef ZLIB_INTERNAL\n#        define ZEXTERN extern __declspec(dllexport)\n#      else\n#        define ZEXTERN extern __declspec(dllimport)\n#      endif\n#    endif\n#  endif  /* ZLIB_DLL */\n   /* If building or using zlib with the WINAPI/WINAPIV calling convention,\n    * define ZLIB_WINAPI.\n    * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.\n    */\n#  ifdef ZLIB_WINAPI\n#    ifdef FAR\n#      undef FAR\n#    endif\n#    include <windows.h>\n     /* No need for _export, use ZLIB.DEF instead. */\n     /* For complete Windows compatibility, use WINAPI, not __stdcall. */\n#    define ZEXPORT WINAPI\n#    ifdef WIN32\n#      define ZEXPORTVA WINAPIV\n#    else\n#      define ZEXPORTVA FAR CDECL\n#    endif\n#  endif\n#endif\n\n#if defined (__BEOS__)\n#  ifdef ZLIB_DLL\n#    ifdef ZLIB_INTERNAL\n#      define ZEXPORT   __declspec(dllexport)\n#      define ZEXPORTVA __declspec(dllexport)\n#    else\n#      define ZEXPORT   __declspec(dllimport)\n#      define ZEXPORTVA __declspec(dllimport)\n#    endif\n#  endif\n#endif\n\n#ifndef ZEXTERN\n#  define ZEXTERN extern\n#endif\n#ifndef ZEXPORT\n#  define ZEXPORT\n#endif\n#ifndef ZEXPORTVA\n#  define ZEXPORTVA\n#endif\n\n#ifndef FAR\n#  define FAR\n#endif\n\n#if !defined(__MACTYPES__)\ntypedef unsigned char  Byte;  /* 8 bits */\n#endif\ntypedef unsigned int   uInt;  /* 16 bits or more */\ntypedef unsigned long  uLong; /* 32 bits or more */\n\n#ifdef SMALL_MEDIUM\n   /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */\n#  define Bytef Byte FAR\n#else\n   typedef Byte  FAR Bytef;\n#endif\ntypedef char  FAR charf;\ntypedef int   FAR intf;\ntypedef uInt  FAR uIntf;\ntypedef uLong FAR uLongf;\n\n#ifdef STDC\n   typedef void const *voidpc;\n   typedef void FAR   *voidpf;\n   typedef void       *voidp;\n#else\n   typedef Byte const *voidpc;\n   typedef Byte FAR   *voidpf;\n   typedef Byte       *voidp;\n#endif\n\n#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC)\n#  include <limits.h>\n#  if (UINT_MAX == 0xffffffffUL)\n#    define Z_U4 unsigned\n#  elif (ULONG_MAX == 0xffffffffUL)\n#    define Z_U4 unsigned long\n#  elif (USHRT_MAX == 0xffffffffUL)\n#    define Z_U4 unsigned short\n#  endif\n#endif\n\n#ifdef Z_U4\n   typedef Z_U4 z_crc_t;\n#else\n   typedef unsigned long z_crc_t;\n#endif\n\n#ifdef HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */\n#  define Z_HAVE_UNISTD_H\n#endif\n\n#ifdef HAVE_STDARG_H    /* may be set to #if 1 by ./configure */\n#  define Z_HAVE_STDARG_H\n#endif\n\n#ifdef STDC\n#  ifndef Z_SOLO\n#    include <sys/types.h>      /* for off_t */\n#  endif\n#endif\n\n#if defined(STDC) || defined(Z_HAVE_STDARG_H)\n#  ifndef Z_SOLO\n#    include <stdarg.h>         /* for va_list */\n#  endif\n#endif\n\n#ifdef _WIN32\n#  ifndef Z_SOLO\n#    include <stddef.h>         /* for wchar_t */\n#  endif\n#endif\n\n/* a little trick to accommodate both \"#define _LARGEFILE64_SOURCE\" and\n * \"#define _LARGEFILE64_SOURCE 1\" as requesting 64-bit operations, (even\n * though the former does not conform to the LFS document), but considering\n * both \"#undef _LARGEFILE64_SOURCE\" and \"#define _LARGEFILE64_SOURCE 0\" as\n * equivalently requesting no 64-bit operations\n */\n#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1\n#  undef _LARGEFILE64_SOURCE\n#endif\n\n#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H)\n#  define Z_HAVE_UNISTD_H\n#endif\n#ifndef Z_SOLO\n#  if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE)\n#    include <unistd.h>         /* for SEEK_*, off_t, and _LFS64_LARGEFILE */\n#    ifdef VMS\n#      include <unixio.h>       /* for off_t */\n#    endif\n#    ifndef z_off_t\n#      define z_off_t off_t\n#    endif\n#  endif\n#endif\n\n#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0\n#  define Z_LFS64\n#endif\n\n#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)\n#  define Z_LARGE64\n#endif\n\n#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64)\n#  define Z_WANT64\n#endif\n\n#if !defined(SEEK_SET) && !defined(Z_SOLO)\n#  define SEEK_SET        0       /* Seek from beginning of file.  */\n#  define SEEK_CUR        1       /* Seek from current position.  */\n#  define SEEK_END        2       /* Set file pointer to EOF plus \"offset\" */\n#endif\n\n#ifndef z_off_t\n#  define z_off_t long\n#endif\n\n#if !defined(_WIN32) && defined(Z_LARGE64)\n#  define z_off64_t off64_t\n#else\n#  if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO)\n#    define z_off64_t __int64\n#  else\n#    define z_off64_t z_off_t\n#  endif\n#endif\n\n/* MVS linker does not support external names larger than 8 bytes */\n#if defined(__MVS__)\n  #pragma map(deflateInit_,\"DEIN\")\n  #pragma map(deflateInit2_,\"DEIN2\")\n  #pragma map(deflateEnd,\"DEEND\")\n  #pragma map(deflateBound,\"DEBND\")\n  #pragma map(inflateInit_,\"ININ\")\n  #pragma map(inflateInit2_,\"ININ2\")\n  #pragma map(inflateEnd,\"INEND\")\n  #pragma map(inflateSync,\"INSY\")\n  #pragma map(inflateSetDictionary,\"INSEDI\")\n  #pragma map(compressBound,\"CMBND\")\n  #pragma map(inflate_table,\"INTABL\")\n  #pragma map(inflate_fast,\"INFA\")\n  #pragma map(inflate_copyright,\"INCOPY\")\n#endif\n\n#endif /* ZCONF_H */\n"
  },
  {
    "path": "jsb_build/websockets/zlib/zlib.h",
    "content": "/* zlib.h -- interface of the 'zlib' general purpose compression library\n  version 1.2.11, January 15th, 2017\n\n  Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler\n\n  This software is provided 'as-is', without any express or implied\n  warranty.  In no event will the authors be held liable for any damages\n  arising from the use of this software.\n\n  Permission is granted to anyone to use this software for any purpose,\n  including commercial applications, and to alter it and redistribute it\n  freely, subject to the following restrictions:\n\n  1. The origin of this software must not be misrepresented; you must not\n     claim that you wrote the original software. If you use this software\n     in a product, an acknowledgment in the product documentation would be\n     appreciated but is not required.\n  2. Altered source versions must be plainly marked as such, and must not be\n     misrepresented as being the original software.\n  3. This notice may not be removed or altered from any source distribution.\n\n  Jean-loup Gailly        Mark Adler\n  jloup@gzip.org          madler@alumni.caltech.edu\n\n\n  The data format used by the zlib library is described by RFCs (Request for\n  Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950\n  (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).\n*/\n\n#ifndef ZLIB_H\n#define ZLIB_H\n\n#include \"zconf.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#define ZLIB_VERSION \"1.2.11\"\n#define ZLIB_VERNUM 0x12b0\n#define ZLIB_VER_MAJOR 1\n#define ZLIB_VER_MINOR 2\n#define ZLIB_VER_REVISION 11\n#define ZLIB_VER_SUBREVISION 0\n\n/*\n    The 'zlib' compression library provides in-memory compression and\n  decompression functions, including integrity checks of the uncompressed data.\n  This version of the library supports only one compression method (deflation)\n  but other algorithms will be added later and will have the same stream\n  interface.\n\n    Compression can be done in a single step if the buffers are large enough,\n  or can be done by repeated calls of the compression function.  In the latter\n  case, the application must provide more input and/or consume the output\n  (providing more output space) before each call.\n\n    The compressed data format used by default by the in-memory functions is\n  the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped\n  around a deflate stream, which is itself documented in RFC 1951.\n\n    The library also supports reading and writing files in gzip (.gz) format\n  with an interface similar to that of stdio using the functions that start\n  with \"gz\".  The gzip format is different from the zlib format.  gzip is a\n  gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.\n\n    This library can optionally read and write gzip and raw deflate streams in\n  memory as well.\n\n    The zlib format was designed to be compact and fast for use in memory\n  and on communications channels.  The gzip format was designed for single-\n  file compression on file systems, has a larger header than zlib to maintain\n  directory information, and uses a different, slower check method than zlib.\n\n    The library does not install any signal handler.  The decoder checks\n  the consistency of the compressed data, so the library should never crash\n  even in the case of corrupted input.\n*/\n\ntypedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));\ntypedef void   (*free_func)  OF((voidpf opaque, voidpf address));\n\nstruct internal_state;\n\ntypedef struct z_stream_s {\n    z_const Bytef *next_in;     /* next input byte */\n    uInt     avail_in;  /* number of bytes available at next_in */\n    uLong    total_in;  /* total number of input bytes read so far */\n\n    Bytef    *next_out; /* next output byte will go here */\n    uInt     avail_out; /* remaining free space at next_out */\n    uLong    total_out; /* total number of bytes output so far */\n\n    z_const char *msg;  /* last error message, NULL if no error */\n    struct internal_state FAR *state; /* not visible by applications */\n\n    alloc_func zalloc;  /* used to allocate the internal state */\n    free_func  zfree;   /* used to free the internal state */\n    voidpf     opaque;  /* private data object passed to zalloc and zfree */\n\n    int     data_type;  /* best guess about the data type: binary or text\n                           for deflate, or the decoding state for inflate */\n    uLong   adler;      /* Adler-32 or CRC-32 value of the uncompressed data */\n    uLong   reserved;   /* reserved for future use */\n} z_stream;\n\ntypedef z_stream FAR *z_streamp;\n\n/*\n     gzip header information passed to and from zlib routines.  See RFC 1952\n  for more details on the meanings of these fields.\n*/\ntypedef struct gz_header_s {\n    int     text;       /* true if compressed data believed to be text */\n    uLong   time;       /* modification time */\n    int     xflags;     /* extra flags (not used when writing a gzip file) */\n    int     os;         /* operating system */\n    Bytef   *extra;     /* pointer to extra field or Z_NULL if none */\n    uInt    extra_len;  /* extra field length (valid if extra != Z_NULL) */\n    uInt    extra_max;  /* space at extra (only when reading header) */\n    Bytef   *name;      /* pointer to zero-terminated file name or Z_NULL */\n    uInt    name_max;   /* space at name (only when reading header) */\n    Bytef   *comment;   /* pointer to zero-terminated comment or Z_NULL */\n    uInt    comm_max;   /* space at comment (only when reading header) */\n    int     hcrc;       /* true if there was or will be a header crc */\n    int     done;       /* true when done reading gzip header (not used\n                           when writing a gzip file) */\n} gz_header;\n\ntypedef gz_header FAR *gz_headerp;\n\n/*\n     The application must update next_in and avail_in when avail_in has dropped\n   to zero.  It must update next_out and avail_out when avail_out has dropped\n   to zero.  The application must initialize zalloc, zfree and opaque before\n   calling the init function.  All other fields are set by the compression\n   library and must not be updated by the application.\n\n     The opaque value provided by the application will be passed as the first\n   parameter for calls of zalloc and zfree.  This can be useful for custom\n   memory management.  The compression library attaches no meaning to the\n   opaque value.\n\n     zalloc must return Z_NULL if there is not enough memory for the object.\n   If zlib is used in a multi-threaded application, zalloc and zfree must be\n   thread safe.  In that case, zlib is thread-safe.  When zalloc and zfree are\n   Z_NULL on entry to the initialization function, they are set to internal\n   routines that use the standard library functions malloc() and free().\n\n     On 16-bit systems, the functions zalloc and zfree must be able to allocate\n   exactly 65536 bytes, but will not be required to allocate more than this if\n   the symbol MAXSEG_64K is defined (see zconf.h).  WARNING: On MSDOS, pointers\n   returned by zalloc for objects of exactly 65536 bytes *must* have their\n   offset normalized to zero.  The default allocation function provided by this\n   library ensures this (see zutil.c).  To reduce memory requirements and avoid\n   any allocation of 64K objects, at the expense of compression ratio, compile\n   the library with -DMAX_WBITS=14 (see zconf.h).\n\n     The fields total_in and total_out can be used for statistics or progress\n   reports.  After compression, total_in holds the total size of the\n   uncompressed data and may be saved for use by the decompressor (particularly\n   if the decompressor wants to decompress everything in a single step).\n*/\n\n                        /* constants */\n\n#define Z_NO_FLUSH      0\n#define Z_PARTIAL_FLUSH 1\n#define Z_SYNC_FLUSH    2\n#define Z_FULL_FLUSH    3\n#define Z_FINISH        4\n#define Z_BLOCK         5\n#define Z_TREES         6\n/* Allowed flush values; see deflate() and inflate() below for details */\n\n#define Z_OK            0\n#define Z_STREAM_END    1\n#define Z_NEED_DICT     2\n#define Z_ERRNO        (-1)\n#define Z_STREAM_ERROR (-2)\n#define Z_DATA_ERROR   (-3)\n#define Z_MEM_ERROR    (-4)\n#define Z_BUF_ERROR    (-5)\n#define Z_VERSION_ERROR (-6)\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n\n#define Z_NO_COMPRESSION         0\n#define Z_BEST_SPEED             1\n#define Z_BEST_COMPRESSION       9\n#define Z_DEFAULT_COMPRESSION  (-1)\n/* compression levels */\n\n#define Z_FILTERED            1\n#define Z_HUFFMAN_ONLY        2\n#define Z_RLE                 3\n#define Z_FIXED               4\n#define Z_DEFAULT_STRATEGY    0\n/* compression strategy; see deflateInit2() below for details */\n\n#define Z_BINARY   0\n#define Z_TEXT     1\n#define Z_ASCII    Z_TEXT   /* for compatibility with 1.2.2 and earlier */\n#define Z_UNKNOWN  2\n/* Possible values of the data_type field for deflate() */\n\n#define Z_DEFLATED   8\n/* The deflate compression method (the only one supported in this version) */\n\n#define Z_NULL  0  /* for initializing zalloc, zfree, opaque */\n\n#define zlib_version zlibVersion()\n/* for compatibility with versions < 1.0.2 */\n\n\n                        /* basic functions */\n\nZEXTERN const char * ZEXPORT zlibVersion OF((void));\n/* The application can compare zlibVersion and ZLIB_VERSION for consistency.\n   If the first character differs, the library code actually used is not\n   compatible with the zlib.h header file used by the application.  This check\n   is automatically made by deflateInit and inflateInit.\n */\n\n/*\nZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));\n\n     Initializes the internal stream state for compression.  The fields\n   zalloc, zfree and opaque must be initialized before by the caller.  If\n   zalloc and zfree are set to Z_NULL, deflateInit updates them to use default\n   allocation functions.\n\n     The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:\n   1 gives best speed, 9 gives best compression, 0 gives no compression at all\n   (the input data is simply copied a block at a time).  Z_DEFAULT_COMPRESSION\n   requests a default compromise between speed and compression (currently\n   equivalent to level 6).\n\n     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_STREAM_ERROR if level is not a valid compression level, or\n   Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible\n   with the version assumed by the caller (ZLIB_VERSION).  msg is set to null\n   if there is no error message.  deflateInit does not perform any compression:\n   this will be done by deflate().\n*/\n\n\nZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));\n/*\n    deflate compresses as much data as possible, and stops when the input\n  buffer becomes empty or the output buffer becomes full.  It may introduce\n  some output latency (reading input without producing any output) except when\n  forced to flush.\n\n    The detailed semantics are as follows.  deflate performs one or both of the\n  following actions:\n\n  - Compress more input starting at next_in and update next_in and avail_in\n    accordingly.  If not all input can be processed (because there is not\n    enough room in the output buffer), next_in and avail_in are updated and\n    processing will resume at this point for the next call of deflate().\n\n  - Generate more output starting at next_out and update next_out and avail_out\n    accordingly.  This action is forced if the parameter flush is non zero.\n    Forcing flush frequently degrades the compression ratio, so this parameter\n    should be set only when necessary.  Some output may be provided even if\n    flush is zero.\n\n    Before the call of deflate(), the application should ensure that at least\n  one of the actions is possible, by providing more input and/or consuming more\n  output, and updating avail_in or avail_out accordingly; avail_out should\n  never be zero before the call.  The application can consume the compressed\n  output when it wants, for example when the output buffer is full (avail_out\n  == 0), or after each call of deflate().  If deflate returns Z_OK and with\n  zero avail_out, it must be called again after making room in the output\n  buffer because there might be more output pending. See deflatePending(),\n  which can be used if desired to determine whether or not there is more ouput\n  in that case.\n\n    Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to\n  decide how much data to accumulate before producing output, in order to\n  maximize compression.\n\n    If the parameter flush is set to Z_SYNC_FLUSH, all pending output is\n  flushed to the output buffer and the output is aligned on a byte boundary, so\n  that the decompressor can get all input data available so far.  (In\n  particular avail_in is zero after the call if enough output space has been\n  provided before the call.) Flushing may degrade compression for some\n  compression algorithms and so it should be used only when necessary.  This\n  completes the current deflate block and follows it with an empty stored block\n  that is three bits plus filler bits to the next byte, followed by four bytes\n  (00 00 ff ff).\n\n    If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the\n  output buffer, but the output is not aligned to a byte boundary.  All of the\n  input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.\n  This completes the current deflate block and follows it with an empty fixed\n  codes block that is 10 bits long.  This assures that enough bytes are output\n  in order for the decompressor to finish the block before the empty fixed\n  codes block.\n\n    If flush is set to Z_BLOCK, a deflate block is completed and emitted, as\n  for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to\n  seven bits of the current block are held to be written as the next byte after\n  the next deflate block is completed.  In this case, the decompressor may not\n  be provided enough bits at this point in order to complete decompression of\n  the data provided so far to the compressor.  It may need to wait for the next\n  block to be emitted.  This is for advanced applications that need to control\n  the emission of deflate blocks.\n\n    If flush is set to Z_FULL_FLUSH, all output is flushed as with\n  Z_SYNC_FLUSH, and the compression state is reset so that decompression can\n  restart from this point if previous compressed data has been damaged or if\n  random access is desired.  Using Z_FULL_FLUSH too often can seriously degrade\n  compression.\n\n    If deflate returns with avail_out == 0, this function must be called again\n  with the same value of the flush parameter and more output space (updated\n  avail_out), until the flush is complete (deflate returns with non-zero\n  avail_out).  In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that\n  avail_out is greater than six to avoid repeated flush markers due to\n  avail_out == 0 on return.\n\n    If the parameter flush is set to Z_FINISH, pending input is processed,\n  pending output is flushed and deflate returns with Z_STREAM_END if there was\n  enough output space.  If deflate returns with Z_OK or Z_BUF_ERROR, this\n  function must be called again with Z_FINISH and more output space (updated\n  avail_out) but no more input data, until it returns with Z_STREAM_END or an\n  error.  After deflate has returned Z_STREAM_END, the only possible operations\n  on the stream are deflateReset or deflateEnd.\n\n    Z_FINISH can be used in the first deflate call after deflateInit if all the\n  compression is to be done in a single step.  In order to complete in one\n  call, avail_out must be at least the value returned by deflateBound (see\n  below).  Then deflate is guaranteed to return Z_STREAM_END.  If not enough\n  output space is provided, deflate will not return Z_STREAM_END, and it must\n  be called again as described above.\n\n    deflate() sets strm->adler to the Adler-32 checksum of all input read\n  so far (that is, total_in bytes).  If a gzip stream is being generated, then\n  strm->adler will be the CRC-32 checksum of the input read so far.  (See\n  deflateInit2 below.)\n\n    deflate() may update strm->data_type if it can make a good guess about\n  the input data type (Z_BINARY or Z_TEXT).  If in doubt, the data is\n  considered binary.  This field is only for information purposes and does not\n  affect the compression algorithm in any manner.\n\n    deflate() returns Z_OK if some progress has been made (more input\n  processed or more output produced), Z_STREAM_END if all input has been\n  consumed and all output has been produced (only when flush is set to\n  Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example\n  if next_in or next_out was Z_NULL or the state was inadvertently written over\n  by the application), or Z_BUF_ERROR if no progress is possible (for example\n  avail_in or avail_out was zero).  Note that Z_BUF_ERROR is not fatal, and\n  deflate() can be called again with more input and more output space to\n  continue compressing.\n*/\n\n\nZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));\n/*\n     All dynamically allocated data structures for this stream are freed.\n   This function discards any unprocessed input and does not flush any pending\n   output.\n\n     deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the\n   stream state was inconsistent, Z_DATA_ERROR if the stream was freed\n   prematurely (some input or output was discarded).  In the error case, msg\n   may be set but then points to a static string (which must not be\n   deallocated).\n*/\n\n\n/*\nZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));\n\n     Initializes the internal stream state for decompression.  The fields\n   next_in, avail_in, zalloc, zfree and opaque must be initialized before by\n   the caller.  In the current version of inflate, the provided input is not\n   read or consumed.  The allocation of a sliding window will be deferred to\n   the first call of inflate (if the decompression does not complete on the\n   first call).  If zalloc and zfree are set to Z_NULL, inflateInit updates\n   them to use default allocation functions.\n\n     inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the\n   version assumed by the caller, or Z_STREAM_ERROR if the parameters are\n   invalid, such as a null pointer to the structure.  msg is set to null if\n   there is no error message.  inflateInit does not perform any decompression.\n   Actual decompression will be done by inflate().  So next_in, and avail_in,\n   next_out, and avail_out are unused and unchanged.  The current\n   implementation of inflateInit() does not process any header information --\n   that is deferred until inflate() is called.\n*/\n\n\nZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));\n/*\n    inflate decompresses as much data as possible, and stops when the input\n  buffer becomes empty or the output buffer becomes full.  It may introduce\n  some output latency (reading input without producing any output) except when\n  forced to flush.\n\n  The detailed semantics are as follows.  inflate performs one or both of the\n  following actions:\n\n  - Decompress more input starting at next_in and update next_in and avail_in\n    accordingly.  If not all input can be processed (because there is not\n    enough room in the output buffer), then next_in and avail_in are updated\n    accordingly, and processing will resume at this point for the next call of\n    inflate().\n\n  - Generate more output starting at next_out and update next_out and avail_out\n    accordingly.  inflate() provides as much output as possible, until there is\n    no more input data or no more space in the output buffer (see below about\n    the flush parameter).\n\n    Before the call of inflate(), the application should ensure that at least\n  one of the actions is possible, by providing more input and/or consuming more\n  output, and updating the next_* and avail_* values accordingly.  If the\n  caller of inflate() does not provide both available input and available\n  output space, it is possible that there will be no progress made.  The\n  application can consume the uncompressed output when it wants, for example\n  when the output buffer is full (avail_out == 0), or after each call of\n  inflate().  If inflate returns Z_OK and with zero avail_out, it must be\n  called again after making room in the output buffer because there might be\n  more output pending.\n\n    The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH,\n  Z_BLOCK, or Z_TREES.  Z_SYNC_FLUSH requests that inflate() flush as much\n  output as possible to the output buffer.  Z_BLOCK requests that inflate()\n  stop if and when it gets to the next deflate block boundary.  When decoding\n  the zlib or gzip format, this will cause inflate() to return immediately\n  after the header and before the first block.  When doing a raw inflate,\n  inflate() will go ahead and process the first block, and will return when it\n  gets to the end of that block, or when it runs out of data.\n\n    The Z_BLOCK option assists in appending to or combining deflate streams.\n  To assist in this, on return inflate() always sets strm->data_type to the\n  number of unused bits in the last byte taken from strm->next_in, plus 64 if\n  inflate() is currently decoding the last block in the deflate stream, plus\n  128 if inflate() returned immediately after decoding an end-of-block code or\n  decoding the complete header up to just before the first byte of the deflate\n  stream.  The end-of-block will not be indicated until all of the uncompressed\n  data from that block has been written to strm->next_out.  The number of\n  unused bits may in general be greater than seven, except when bit 7 of\n  data_type is set, in which case the number of unused bits will be less than\n  eight.  data_type is set as noted here every time inflate() returns for all\n  flush options, and so can be used to determine the amount of currently\n  consumed input in bits.\n\n    The Z_TREES option behaves as Z_BLOCK does, but it also returns when the\n  end of each deflate block header is reached, before any actual data in that\n  block is decoded.  This allows the caller to determine the length of the\n  deflate block header for later use in random access within a deflate block.\n  256 is added to the value of strm->data_type when inflate() returns\n  immediately after reaching the end of the deflate block header.\n\n    inflate() should normally be called until it returns Z_STREAM_END or an\n  error.  However if all decompression is to be performed in a single step (a\n  single call of inflate), the parameter flush should be set to Z_FINISH.  In\n  this case all pending input is processed and all pending output is flushed;\n  avail_out must be large enough to hold all of the uncompressed data for the\n  operation to complete.  (The size of the uncompressed data may have been\n  saved by the compressor for this purpose.)  The use of Z_FINISH is not\n  required to perform an inflation in one step.  However it may be used to\n  inform inflate that a faster approach can be used for the single inflate()\n  call.  Z_FINISH also informs inflate to not maintain a sliding window if the\n  stream completes, which reduces inflate's memory footprint.  If the stream\n  does not complete, either because not all of the stream is provided or not\n  enough output space is provided, then a sliding window will be allocated and\n  inflate() can be called again to continue the operation as if Z_NO_FLUSH had\n  been used.\n\n     In this implementation, inflate() always flushes as much output as\n  possible to the output buffer, and always uses the faster approach on the\n  first call.  So the effects of the flush parameter in this implementation are\n  on the return value of inflate() as noted below, when inflate() returns early\n  when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of\n  memory for a sliding window when Z_FINISH is used.\n\n     If a preset dictionary is needed after this call (see inflateSetDictionary\n  below), inflate sets strm->adler to the Adler-32 checksum of the dictionary\n  chosen by the compressor and returns Z_NEED_DICT; otherwise it sets\n  strm->adler to the Adler-32 checksum of all output produced so far (that is,\n  total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described\n  below.  At the end of the stream, inflate() checks that its computed Adler-32\n  checksum is equal to that saved by the compressor and returns Z_STREAM_END\n  only if the checksum is correct.\n\n    inflate() can decompress and check either zlib-wrapped or gzip-wrapped\n  deflate data.  The header type is detected automatically, if requested when\n  initializing with inflateInit2().  Any information contained in the gzip\n  header is not retained unless inflateGetHeader() is used.  When processing\n  gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output\n  produced so far.  The CRC-32 is checked against the gzip trailer, as is the\n  uncompressed length, modulo 2^32.\n\n    inflate() returns Z_OK if some progress has been made (more input processed\n  or more output produced), Z_STREAM_END if the end of the compressed data has\n  been reached and all uncompressed output has been produced, Z_NEED_DICT if a\n  preset dictionary is needed at this point, Z_DATA_ERROR if the input data was\n  corrupted (input stream not conforming to the zlib format or incorrect check\n  value, in which case strm->msg points to a string with a more specific\n  error), Z_STREAM_ERROR if the stream structure was inconsistent (for example\n  next_in or next_out was Z_NULL, or the state was inadvertently written over\n  by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR\n  if no progress was possible or if there was not enough room in the output\n  buffer when Z_FINISH is used.  Note that Z_BUF_ERROR is not fatal, and\n  inflate() can be called again with more input and more output space to\n  continue decompressing.  If Z_DATA_ERROR is returned, the application may\n  then call inflateSync() to look for a good compression block if a partial\n  recovery of the data is to be attempted.\n*/\n\n\nZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));\n/*\n     All dynamically allocated data structures for this stream are freed.\n   This function discards any unprocessed input and does not flush any pending\n   output.\n\n     inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state\n   was inconsistent.\n*/\n\n\n                        /* Advanced functions */\n\n/*\n    The following functions are needed only in some special applications.\n*/\n\n/*\nZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,\n                                     int  level,\n                                     int  method,\n                                     int  windowBits,\n                                     int  memLevel,\n                                     int  strategy));\n\n     This is another version of deflateInit with more compression options.  The\n   fields next_in, zalloc, zfree and opaque must be initialized before by the\n   caller.\n\n     The method parameter is the compression method.  It must be Z_DEFLATED in\n   this version of the library.\n\n     The windowBits parameter is the base two logarithm of the window size\n   (the size of the history buffer).  It should be in the range 8..15 for this\n   version of the library.  Larger values of this parameter result in better\n   compression at the expense of memory usage.  The default value is 15 if\n   deflateInit is used instead.\n\n     For the current implementation of deflate(), a windowBits value of 8 (a\n   window size of 256 bytes) is not supported.  As a result, a request for 8\n   will result in 9 (a 512-byte window).  In that case, providing 8 to\n   inflateInit2() will result in an error when the zlib header with 9 is\n   checked against the initialization of inflate().  The remedy is to not use 8\n   with deflateInit2() with this initialization, or at least in that case use 9\n   with inflateInit2().\n\n     windowBits can also be -8..-15 for raw deflate.  In this case, -windowBits\n   determines the window size.  deflate() will then generate raw deflate data\n   with no zlib header or trailer, and will not compute a check value.\n\n     windowBits can also be greater than 15 for optional gzip encoding.  Add\n   16 to windowBits to write a simple gzip header and trailer around the\n   compressed data instead of a zlib wrapper.  The gzip header will have no\n   file name, no extra data, no comment, no modification time (set to zero), no\n   header crc, and the operating system will be set to the appropriate value,\n   if the operating system was determined at compile time.  If a gzip stream is\n   being written, strm->adler is a CRC-32 instead of an Adler-32.\n\n     For raw deflate or gzip encoding, a request for a 256-byte window is\n   rejected as invalid, since only the zlib header provides a means of\n   transmitting the window size to the decompressor.\n\n     The memLevel parameter specifies how much memory should be allocated\n   for the internal compression state.  memLevel=1 uses minimum memory but is\n   slow and reduces compression ratio; memLevel=9 uses maximum memory for\n   optimal speed.  The default value is 8.  See zconf.h for total memory usage\n   as a function of windowBits and memLevel.\n\n     The strategy parameter is used to tune the compression algorithm.  Use the\n   value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a\n   filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no\n   string match), or Z_RLE to limit match distances to one (run-length\n   encoding).  Filtered data consists mostly of small values with a somewhat\n   random distribution.  In this case, the compression algorithm is tuned to\n   compress them better.  The effect of Z_FILTERED is to force more Huffman\n   coding and less string matching; it is somewhat intermediate between\n   Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY.  Z_RLE is designed to be almost as\n   fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data.  The\n   strategy parameter only affects the compression ratio but not the\n   correctness of the compressed output even if it is not set appropriately.\n   Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler\n   decoder for special applications.\n\n     deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid\n   method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is\n   incompatible with the version assumed by the caller (ZLIB_VERSION).  msg is\n   set to null if there is no error message.  deflateInit2 does not perform any\n   compression: this will be done by deflate().\n*/\n\nZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,\n                                             const Bytef *dictionary,\n                                             uInt  dictLength));\n/*\n     Initializes the compression dictionary from the given byte sequence\n   without producing any compressed output.  When using the zlib format, this\n   function must be called immediately after deflateInit, deflateInit2 or\n   deflateReset, and before any call of deflate.  When doing raw deflate, this\n   function must be called either before any call of deflate, or immediately\n   after the completion of a deflate block, i.e. after all input has been\n   consumed and all output has been delivered when using any of the flush\n   options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH.  The\n   compressor and decompressor must use exactly the same dictionary (see\n   inflateSetDictionary).\n\n     The dictionary should consist of strings (byte sequences) that are likely\n   to be encountered later in the data to be compressed, with the most commonly\n   used strings preferably put towards the end of the dictionary.  Using a\n   dictionary is most useful when the data to be compressed is short and can be\n   predicted with good accuracy; the data can then be compressed better than\n   with the default empty dictionary.\n\n     Depending on the size of the compression data structures selected by\n   deflateInit or deflateInit2, a part of the dictionary may in effect be\n   discarded, for example if the dictionary is larger than the window size\n   provided in deflateInit or deflateInit2.  Thus the strings most likely to be\n   useful should be put at the end of the dictionary, not at the front.  In\n   addition, the current implementation of deflate will use at most the window\n   size minus 262 bytes of the provided dictionary.\n\n     Upon return of this function, strm->adler is set to the Adler-32 value\n   of the dictionary; the decompressor may later use this value to determine\n   which dictionary has been used by the compressor.  (The Adler-32 value\n   applies to the whole dictionary even if only a subset of the dictionary is\n   actually used by the compressor.) If a raw deflate was requested, then the\n   Adler-32 value is not computed and strm->adler is not set.\n\n     deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a\n   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is\n   inconsistent (for example if deflate has already been called for this stream\n   or if not at a block boundary for raw deflate).  deflateSetDictionary does\n   not perform any compression: this will be done by deflate().\n*/\n\nZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm,\n                                             Bytef *dictionary,\n                                             uInt  *dictLength));\n/*\n     Returns the sliding dictionary being maintained by deflate.  dictLength is\n   set to the number of bytes in the dictionary, and that many bytes are copied\n   to dictionary.  dictionary must have enough space, where 32768 bytes is\n   always enough.  If deflateGetDictionary() is called with dictionary equal to\n   Z_NULL, then only the dictionary length is returned, and nothing is copied.\n   Similary, if dictLength is Z_NULL, then it is not set.\n\n     deflateGetDictionary() may return a length less than the window size, even\n   when more than the window size in input has been provided. It may return up\n   to 258 bytes less in that case, due to how zlib's implementation of deflate\n   manages the sliding window and lookahead for matches, where matches can be\n   up to 258 bytes long. If the application needs the last window-size bytes of\n   input, then that would need to be saved by the application outside of zlib.\n\n     deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the\n   stream state is inconsistent.\n*/\n\nZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,\n                                    z_streamp source));\n/*\n     Sets the destination stream as a complete copy of the source stream.\n\n     This function can be useful when several compression strategies will be\n   tried, for example when there are several ways of pre-processing the input\n   data with a filter.  The streams that will be discarded should then be freed\n   by calling deflateEnd.  Note that deflateCopy duplicates the internal\n   compression state which can be quite large, so this strategy is slow and can\n   consume lots of memory.\n\n     deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not\n   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent\n   (such as zalloc being Z_NULL).  msg is left unchanged in both source and\n   destination.\n*/\n\nZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));\n/*\n     This function is equivalent to deflateEnd followed by deflateInit, but\n   does not free and reallocate the internal compression state.  The stream\n   will leave the compression level and any other attributes that may have been\n   set unchanged.\n\n     deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent (such as zalloc or state being Z_NULL).\n*/\n\nZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,\n                                      int level,\n                                      int strategy));\n/*\n     Dynamically update the compression level and compression strategy.  The\n   interpretation of level and strategy is as in deflateInit2().  This can be\n   used to switch between compression and straight copy of the input data, or\n   to switch to a different kind of input data requiring a different strategy.\n   If the compression approach (which is a function of the level) or the\n   strategy is changed, and if any input has been consumed in a previous\n   deflate() call, then the input available so far is compressed with the old\n   level and strategy using deflate(strm, Z_BLOCK).  There are three approaches\n   for the compression levels 0, 1..3, and 4..9 respectively.  The new level\n   and strategy will take effect at the next call of deflate().\n\n     If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does\n   not have enough output space to complete, then the parameter change will not\n   take effect.  In this case, deflateParams() can be called again with the\n   same parameters and more output space to try again.\n\n     In order to assure a change in the parameters on the first try, the\n   deflate stream should be flushed using deflate() with Z_BLOCK or other flush\n   request until strm.avail_out is not zero, before calling deflateParams().\n   Then no more input data should be provided before the deflateParams() call.\n   If this is done, the old level and strategy will be applied to the data\n   compressed before deflateParams(), and the new level and strategy will be\n   applied to the the data compressed after deflateParams().\n\n     deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream\n   state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if\n   there was not enough output space to complete the compression of the\n   available input data before a change in the strategy or approach.  Note that\n   in the case of a Z_BUF_ERROR, the parameters are not changed.  A return\n   value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be\n   retried with more output space.\n*/\n\nZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,\n                                    int good_length,\n                                    int max_lazy,\n                                    int nice_length,\n                                    int max_chain));\n/*\n     Fine tune deflate's internal compression parameters.  This should only be\n   used by someone who understands the algorithm used by zlib's deflate for\n   searching for the best matching string, and even then only by the most\n   fanatic optimizer trying to squeeze out the last compressed bit for their\n   specific input data.  Read the deflate.c source code for the meaning of the\n   max_lazy, good_length, nice_length, and max_chain parameters.\n\n     deflateTune() can be called after deflateInit() or deflateInit2(), and\n   returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.\n */\n\nZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,\n                                       uLong sourceLen));\n/*\n     deflateBound() returns an upper bound on the compressed size after\n   deflation of sourceLen bytes.  It must be called after deflateInit() or\n   deflateInit2(), and after deflateSetHeader(), if used.  This would be used\n   to allocate an output buffer for deflation in a single pass, and so would be\n   called before deflate().  If that first deflate() call is provided the\n   sourceLen input bytes, an output buffer allocated to the size returned by\n   deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed\n   to return Z_STREAM_END.  Note that it is possible for the compressed size to\n   be larger than the value returned by deflateBound() if flush options other\n   than Z_FINISH or Z_NO_FLUSH are used.\n*/\n\nZEXTERN int ZEXPORT deflatePending OF((z_streamp strm,\n                                       unsigned *pending,\n                                       int *bits));\n/*\n     deflatePending() returns the number of bytes and bits of output that have\n   been generated, but not yet provided in the available output.  The bytes not\n   provided would be due to the available output space having being consumed.\n   The number of bits of output not provided are between 0 and 7, where they\n   await more bits to join them in order to fill out a full byte.  If pending\n   or bits are Z_NULL, then those values are not set.\n\n     deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent.\n */\n\nZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,\n                                     int bits,\n                                     int value));\n/*\n     deflatePrime() inserts bits in the deflate output stream.  The intent\n   is that this function is used to start off the deflate output with the bits\n   leftover from a previous deflate stream when appending to it.  As such, this\n   function can only be used for raw deflate, and must be used before the first\n   deflate() call after a deflateInit2() or deflateReset().  bits must be less\n   than or equal to 16, and that many of the least significant bits of value\n   will be inserted in the output.\n\n     deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough\n   room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the\n   source stream state was inconsistent.\n*/\n\nZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,\n                                         gz_headerp head));\n/*\n     deflateSetHeader() provides gzip header information for when a gzip\n   stream is requested by deflateInit2().  deflateSetHeader() may be called\n   after deflateInit2() or deflateReset() and before the first call of\n   deflate().  The text, time, os, extra field, name, and comment information\n   in the provided gz_header structure are written to the gzip header (xflag is\n   ignored -- the extra flags are set according to the compression level).  The\n   caller must assure that, if not Z_NULL, name and comment are terminated with\n   a zero byte, and that if extra is not Z_NULL, that extra_len bytes are\n   available there.  If hcrc is true, a gzip header crc is included.  Note that\n   the current versions of the command-line version of gzip (up through version\n   1.3.x) do not support header crc's, and will report that it is a \"multi-part\n   gzip file\" and give up.\n\n     If deflateSetHeader is not used, the default gzip header has text false,\n   the time set to zero, and os set to 255, with no extra, name, or comment\n   fields.  The gzip header is returned to the default state by deflateReset().\n\n     deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent.\n*/\n\n/*\nZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,\n                                     int  windowBits));\n\n     This is another version of inflateInit with an extra parameter.  The\n   fields next_in, avail_in, zalloc, zfree and opaque must be initialized\n   before by the caller.\n\n     The windowBits parameter is the base two logarithm of the maximum window\n   size (the size of the history buffer).  It should be in the range 8..15 for\n   this version of the library.  The default value is 15 if inflateInit is used\n   instead.  windowBits must be greater than or equal to the windowBits value\n   provided to deflateInit2() while compressing, or it must be equal to 15 if\n   deflateInit2() was not used.  If a compressed stream with a larger window\n   size is given as input, inflate() will return with the error code\n   Z_DATA_ERROR instead of trying to allocate a larger window.\n\n     windowBits can also be zero to request that inflate use the window size in\n   the zlib header of the compressed stream.\n\n     windowBits can also be -8..-15 for raw inflate.  In this case, -windowBits\n   determines the window size.  inflate() will then process raw deflate data,\n   not looking for a zlib or gzip header, not generating a check value, and not\n   looking for any check values for comparison at the end of the stream.  This\n   is for use with other formats that use the deflate compressed data format\n   such as zip.  Those formats provide their own check values.  If a custom\n   format is developed using the raw deflate format for compressed data, it is\n   recommended that a check value such as an Adler-32 or a CRC-32 be applied to\n   the uncompressed data as is done in the zlib, gzip, and zip formats.  For\n   most applications, the zlib format should be used as is.  Note that comments\n   above on the use in deflateInit2() applies to the magnitude of windowBits.\n\n     windowBits can also be greater than 15 for optional gzip decoding.  Add\n   32 to windowBits to enable zlib and gzip decoding with automatic header\n   detection, or add 16 to decode only the gzip format (the zlib format will\n   return a Z_DATA_ERROR).  If a gzip stream is being decoded, strm->adler is a\n   CRC-32 instead of an Adler-32.  Unlike the gunzip utility and gzread() (see\n   below), inflate() will not automatically decode concatenated gzip streams.\n   inflate() will return Z_STREAM_END at the end of the gzip stream.  The state\n   would need to be reset to continue decoding a subsequent gzip stream.\n\n     inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the\n   version assumed by the caller, or Z_STREAM_ERROR if the parameters are\n   invalid, such as a null pointer to the structure.  msg is set to null if\n   there is no error message.  inflateInit2 does not perform any decompression\n   apart from possibly reading the zlib header if present: actual decompression\n   will be done by inflate().  (So next_in and avail_in may be modified, but\n   next_out and avail_out are unused and unchanged.) The current implementation\n   of inflateInit2() does not process any header information -- that is\n   deferred until inflate() is called.\n*/\n\nZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,\n                                             const Bytef *dictionary,\n                                             uInt  dictLength));\n/*\n     Initializes the decompression dictionary from the given uncompressed byte\n   sequence.  This function must be called immediately after a call of inflate,\n   if that call returned Z_NEED_DICT.  The dictionary chosen by the compressor\n   can be determined from the Adler-32 value returned by that call of inflate.\n   The compressor and decompressor must use exactly the same dictionary (see\n   deflateSetDictionary).  For raw inflate, this function can be called at any\n   time to set the dictionary.  If the provided dictionary is smaller than the\n   window and there is already data in the window, then the provided dictionary\n   will amend what's there.  The application must insure that the dictionary\n   that was used for compression is provided.\n\n     inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a\n   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is\n   inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the\n   expected one (incorrect Adler-32 value).  inflateSetDictionary does not\n   perform any decompression: this will be done by subsequent calls of\n   inflate().\n*/\n\nZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm,\n                                             Bytef *dictionary,\n                                             uInt  *dictLength));\n/*\n     Returns the sliding dictionary being maintained by inflate.  dictLength is\n   set to the number of bytes in the dictionary, and that many bytes are copied\n   to dictionary.  dictionary must have enough space, where 32768 bytes is\n   always enough.  If inflateGetDictionary() is called with dictionary equal to\n   Z_NULL, then only the dictionary length is returned, and nothing is copied.\n   Similary, if dictLength is Z_NULL, then it is not set.\n\n     inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the\n   stream state is inconsistent.\n*/\n\nZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));\n/*\n     Skips invalid compressed data until a possible full flush point (see above\n   for the description of deflate with Z_FULL_FLUSH) can be found, or until all\n   available input is skipped.  No output is provided.\n\n     inflateSync searches for a 00 00 FF FF pattern in the compressed data.\n   All full flush points have this pattern, but not all occurrences of this\n   pattern are full flush points.\n\n     inflateSync returns Z_OK if a possible full flush point has been found,\n   Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point\n   has been found, or Z_STREAM_ERROR if the stream structure was inconsistent.\n   In the success case, the application may save the current current value of\n   total_in which indicates where valid compressed data was found.  In the\n   error case, the application may repeatedly call inflateSync, providing more\n   input each time, until success or end of the input data.\n*/\n\nZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,\n                                    z_streamp source));\n/*\n     Sets the destination stream as a complete copy of the source stream.\n\n     This function can be useful when randomly accessing a large stream.  The\n   first pass through the stream can periodically record the inflate state,\n   allowing restarting inflate at those points when randomly accessing the\n   stream.\n\n     inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not\n   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent\n   (such as zalloc being Z_NULL).  msg is left unchanged in both source and\n   destination.\n*/\n\nZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));\n/*\n     This function is equivalent to inflateEnd followed by inflateInit,\n   but does not free and reallocate the internal decompression state.  The\n   stream will keep attributes that may have been set by inflateInit2.\n\n     inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent (such as zalloc or state being Z_NULL).\n*/\n\nZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm,\n                                      int windowBits));\n/*\n     This function is the same as inflateReset, but it also permits changing\n   the wrap and window size requests.  The windowBits parameter is interpreted\n   the same as it is for inflateInit2.  If the window size is changed, then the\n   memory allocated for the window is freed, and the window will be reallocated\n   by inflate() if needed.\n\n     inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent (such as zalloc or state being Z_NULL), or if\n   the windowBits parameter is invalid.\n*/\n\nZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,\n                                     int bits,\n                                     int value));\n/*\n     This function inserts bits in the inflate input stream.  The intent is\n   that this function is used to start inflating at a bit position in the\n   middle of a byte.  The provided bits will be used before any bytes are used\n   from next_in.  This function should only be used with raw inflate, and\n   should be used before the first inflate() call after inflateInit2() or\n   inflateReset().  bits must be less than or equal to 16, and that many of the\n   least significant bits of value will be inserted in the input.\n\n     If bits is negative, then the input stream bit buffer is emptied.  Then\n   inflatePrime() can be called again to put bits in the buffer.  This is used\n   to clear out bits leftover after feeding inflate a block description prior\n   to feeding inflate codes.\n\n     inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent.\n*/\n\nZEXTERN long ZEXPORT inflateMark OF((z_streamp strm));\n/*\n     This function returns two values, one in the lower 16 bits of the return\n   value, and the other in the remaining upper bits, obtained by shifting the\n   return value down 16 bits.  If the upper value is -1 and the lower value is\n   zero, then inflate() is currently decoding information outside of a block.\n   If the upper value is -1 and the lower value is non-zero, then inflate is in\n   the middle of a stored block, with the lower value equaling the number of\n   bytes from the input remaining to copy.  If the upper value is not -1, then\n   it is the number of bits back from the current bit position in the input of\n   the code (literal or length/distance pair) currently being processed.  In\n   that case the lower value is the number of bytes already emitted for that\n   code.\n\n     A code is being processed if inflate is waiting for more input to complete\n   decoding of the code, or if it has completed decoding but is waiting for\n   more output space to write the literal or match data.\n\n     inflateMark() is used to mark locations in the input data for random\n   access, which may be at bit positions, and to note those cases where the\n   output of a code may span boundaries of random access blocks.  The current\n   location in the input stream can be determined from avail_in and data_type\n   as noted in the description for the Z_BLOCK flush parameter for inflate.\n\n     inflateMark returns the value noted above, or -65536 if the provided\n   source stream state was inconsistent.\n*/\n\nZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,\n                                         gz_headerp head));\n/*\n     inflateGetHeader() requests that gzip header information be stored in the\n   provided gz_header structure.  inflateGetHeader() may be called after\n   inflateInit2() or inflateReset(), and before the first call of inflate().\n   As inflate() processes the gzip stream, head->done is zero until the header\n   is completed, at which time head->done is set to one.  If a zlib stream is\n   being decoded, then head->done is set to -1 to indicate that there will be\n   no gzip header information forthcoming.  Note that Z_BLOCK or Z_TREES can be\n   used to force inflate() to return immediately after header processing is\n   complete and before any actual data is decompressed.\n\n     The text, time, xflags, and os fields are filled in with the gzip header\n   contents.  hcrc is set to true if there is a header CRC.  (The header CRC\n   was valid if done is set to one.) If extra is not Z_NULL, then extra_max\n   contains the maximum number of bytes to write to extra.  Once done is true,\n   extra_len contains the actual extra field length, and extra contains the\n   extra field, or that field truncated if extra_max is less than extra_len.\n   If name is not Z_NULL, then up to name_max characters are written there,\n   terminated with a zero unless the length is greater than name_max.  If\n   comment is not Z_NULL, then up to comm_max characters are written there,\n   terminated with a zero unless the length is greater than comm_max.  When any\n   of extra, name, or comment are not Z_NULL and the respective field is not\n   present in the header, then that field is set to Z_NULL to signal its\n   absence.  This allows the use of deflateSetHeader() with the returned\n   structure to duplicate the header.  However if those fields are set to\n   allocated memory, then the application will need to save those pointers\n   elsewhere so that they can be eventually freed.\n\n     If inflateGetHeader is not used, then the header information is simply\n   discarded.  The header is always checked for validity, including the header\n   CRC if present.  inflateReset() will reset the process to discard the header\n   information.  The application would need to call inflateGetHeader() again to\n   retrieve the header from the next gzip stream.\n\n     inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent.\n*/\n\n/*\nZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,\n                                        unsigned char FAR *window));\n\n     Initialize the internal stream state for decompression using inflateBack()\n   calls.  The fields zalloc, zfree and opaque in strm must be initialized\n   before the call.  If zalloc and zfree are Z_NULL, then the default library-\n   derived memory allocation routines are used.  windowBits is the base two\n   logarithm of the window size, in the range 8..15.  window is a caller\n   supplied buffer of that size.  Except for special applications where it is\n   assured that deflate was used with small window sizes, windowBits must be 15\n   and a 32K byte window must be supplied to be able to decompress general\n   deflate streams.\n\n     See inflateBack() for the usage of these routines.\n\n     inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of\n   the parameters are invalid, Z_MEM_ERROR if the internal state could not be\n   allocated, or Z_VERSION_ERROR if the version of the library does not match\n   the version of the header file.\n*/\n\ntypedef unsigned (*in_func) OF((void FAR *,\n                                z_const unsigned char FAR * FAR *));\ntypedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));\n\nZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,\n                                    in_func in, void FAR *in_desc,\n                                    out_func out, void FAR *out_desc));\n/*\n     inflateBack() does a raw inflate with a single call using a call-back\n   interface for input and output.  This is potentially more efficient than\n   inflate() for file i/o applications, in that it avoids copying between the\n   output and the sliding window by simply making the window itself the output\n   buffer.  inflate() can be faster on modern CPUs when used with large\n   buffers.  inflateBack() trusts the application to not change the output\n   buffer passed by the output function, at least until inflateBack() returns.\n\n     inflateBackInit() must be called first to allocate the internal state\n   and to initialize the state with the user-provided window buffer.\n   inflateBack() may then be used multiple times to inflate a complete, raw\n   deflate stream with each call.  inflateBackEnd() is then called to free the\n   allocated state.\n\n     A raw deflate stream is one with no zlib or gzip header or trailer.\n   This routine would normally be used in a utility that reads zip or gzip\n   files and writes out uncompressed files.  The utility would decode the\n   header and process the trailer on its own, hence this routine expects only\n   the raw deflate stream to decompress.  This is different from the default\n   behavior of inflate(), which expects a zlib header and trailer around the\n   deflate stream.\n\n     inflateBack() uses two subroutines supplied by the caller that are then\n   called by inflateBack() for input and output.  inflateBack() calls those\n   routines until it reads a complete deflate stream and writes out all of the\n   uncompressed data, or until it encounters an error.  The function's\n   parameters and return types are defined above in the in_func and out_func\n   typedefs.  inflateBack() will call in(in_desc, &buf) which should return the\n   number of bytes of provided input, and a pointer to that input in buf.  If\n   there is no input available, in() must return zero -- buf is ignored in that\n   case -- and inflateBack() will return a buffer error.  inflateBack() will\n   call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1].\n   out() should return zero on success, or non-zero on failure.  If out()\n   returns non-zero, inflateBack() will return with an error.  Neither in() nor\n   out() are permitted to change the contents of the window provided to\n   inflateBackInit(), which is also the buffer that out() uses to write from.\n   The length written by out() will be at most the window size.  Any non-zero\n   amount of input may be provided by in().\n\n     For convenience, inflateBack() can be provided input on the first call by\n   setting strm->next_in and strm->avail_in.  If that input is exhausted, then\n   in() will be called.  Therefore strm->next_in must be initialized before\n   calling inflateBack().  If strm->next_in is Z_NULL, then in() will be called\n   immediately for input.  If strm->next_in is not Z_NULL, then strm->avail_in\n   must also be initialized, and then if strm->avail_in is not zero, input will\n   initially be taken from strm->next_in[0 ..  strm->avail_in - 1].\n\n     The in_desc and out_desc parameters of inflateBack() is passed as the\n   first parameter of in() and out() respectively when they are called.  These\n   descriptors can be optionally used to pass any information that the caller-\n   supplied in() and out() functions need to do their job.\n\n     On return, inflateBack() will set strm->next_in and strm->avail_in to\n   pass back any unused input that was provided by the last in() call.  The\n   return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR\n   if in() or out() returned an error, Z_DATA_ERROR if there was a format error\n   in the deflate stream (in which case strm->msg is set to indicate the nature\n   of the error), or Z_STREAM_ERROR if the stream was not properly initialized.\n   In the case of Z_BUF_ERROR, an input or output error can be distinguished\n   using strm->next_in which will be Z_NULL only if in() returned an error.  If\n   strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning\n   non-zero.  (in() will always be called before out(), so strm->next_in is\n   assured to be defined if out() returns non-zero.)  Note that inflateBack()\n   cannot return Z_OK.\n*/\n\nZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));\n/*\n     All memory allocated by inflateBackInit() is freed.\n\n     inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream\n   state was inconsistent.\n*/\n\nZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));\n/* Return flags indicating compile-time options.\n\n    Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:\n     1.0: size of uInt\n     3.2: size of uLong\n     5.4: size of voidpf (pointer)\n     7.6: size of z_off_t\n\n    Compiler, assembler, and debug options:\n     8: ZLIB_DEBUG\n     9: ASMV or ASMINF -- use ASM code\n     10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention\n     11: 0 (reserved)\n\n    One-time table building (smaller code, but not thread-safe if true):\n     12: BUILDFIXED -- build static block decoding tables when needed\n     13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed\n     14,15: 0 (reserved)\n\n    Library content (indicates missing functionality):\n     16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking\n                          deflate code when not needed)\n     17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect\n                    and decode gzip streams (to avoid linking crc code)\n     18-19: 0 (reserved)\n\n    Operation variations (changes in library functionality):\n     20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate\n     21: FASTEST -- deflate algorithm with only one, lowest compression level\n     22,23: 0 (reserved)\n\n    The sprintf variant used by gzprintf (zero is best):\n     24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format\n     25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!\n     26: 0 = returns value, 1 = void -- 1 means inferred string length returned\n\n    Remainder:\n     27-31: 0 (reserved)\n */\n\n#ifndef Z_SOLO\n\n                        /* utility functions */\n\n/*\n     The following utility functions are implemented on top of the basic\n   stream-oriented functions.  To simplify the interface, some default options\n   are assumed (compression level and memory usage, standard memory allocation\n   functions).  The source code of these utility functions can be modified if\n   you need special options.\n*/\n\nZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,\n                                 const Bytef *source, uLong sourceLen));\n/*\n     Compresses the source buffer into the destination buffer.  sourceLen is\n   the byte length of the source buffer.  Upon entry, destLen is the total size\n   of the destination buffer, which must be at least the value returned by\n   compressBound(sourceLen).  Upon exit, destLen is the actual size of the\n   compressed data.  compress() is equivalent to compress2() with a level\n   parameter of Z_DEFAULT_COMPRESSION.\n\n     compress returns Z_OK if success, Z_MEM_ERROR if there was not\n   enough memory, Z_BUF_ERROR if there was not enough room in the output\n   buffer.\n*/\n\nZEXTERN int ZEXPORT compress2 OF((Bytef *dest,   uLongf *destLen,\n                                  const Bytef *source, uLong sourceLen,\n                                  int level));\n/*\n     Compresses the source buffer into the destination buffer.  The level\n   parameter has the same meaning as in deflateInit.  sourceLen is the byte\n   length of the source buffer.  Upon entry, destLen is the total size of the\n   destination buffer, which must be at least the value returned by\n   compressBound(sourceLen).  Upon exit, destLen is the actual size of the\n   compressed data.\n\n     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_BUF_ERROR if there was not enough room in the output buffer,\n   Z_STREAM_ERROR if the level parameter is invalid.\n*/\n\nZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));\n/*\n     compressBound() returns an upper bound on the compressed size after\n   compress() or compress2() on sourceLen bytes.  It would be used before a\n   compress() or compress2() call to allocate the destination buffer.\n*/\n\nZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,\n                                   const Bytef *source, uLong sourceLen));\n/*\n     Decompresses the source buffer into the destination buffer.  sourceLen is\n   the byte length of the source buffer.  Upon entry, destLen is the total size\n   of the destination buffer, which must be large enough to hold the entire\n   uncompressed data.  (The size of the uncompressed data must have been saved\n   previously by the compressor and transmitted to the decompressor by some\n   mechanism outside the scope of this compression library.) Upon exit, destLen\n   is the actual size of the uncompressed data.\n\n     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not\n   enough memory, Z_BUF_ERROR if there was not enough room in the output\n   buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.  In\n   the case where there is not enough room, uncompress() will fill the output\n   buffer with the uncompressed data up to that point.\n*/\n\nZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest,   uLongf *destLen,\n                                    const Bytef *source, uLong *sourceLen));\n/*\n     Same as uncompress, except that sourceLen is a pointer, where the\n   length of the source is *sourceLen.  On return, *sourceLen is the number of\n   source bytes consumed.\n*/\n\n                        /* gzip file access functions */\n\n/*\n     This library supports reading and writing files in gzip (.gz) format with\n   an interface similar to that of stdio, using the functions that start with\n   \"gz\".  The gzip format is different from the zlib format.  gzip is a gzip\n   wrapper, documented in RFC 1952, wrapped around a deflate stream.\n*/\n\ntypedef struct gzFile_s *gzFile;    /* semi-opaque gzip file descriptor */\n\n/*\nZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));\n\n     Opens a gzip (.gz) file for reading or writing.  The mode parameter is as\n   in fopen (\"rb\" or \"wb\") but can also include a compression level (\"wb9\") or\n   a strategy: 'f' for filtered data as in \"wb6f\", 'h' for Huffman-only\n   compression as in \"wb1h\", 'R' for run-length encoding as in \"wb1R\", or 'F'\n   for fixed code compression as in \"wb9F\".  (See the description of\n   deflateInit2 for more information about the strategy parameter.)  'T' will\n   request transparent writing or appending with no compression and not using\n   the gzip format.\n\n     \"a\" can be used instead of \"w\" to request that the gzip stream that will\n   be written be appended to the file.  \"+\" will result in an error, since\n   reading and writing to the same gzip file is not supported.  The addition of\n   \"x\" when writing will create the file exclusively, which fails if the file\n   already exists.  On systems that support it, the addition of \"e\" when\n   reading or writing will set the flag to close the file on an execve() call.\n\n     These functions, as well as gzip, will read and decode a sequence of gzip\n   streams in a file.  The append function of gzopen() can be used to create\n   such a file.  (Also see gzflush() for another way to do this.)  When\n   appending, gzopen does not test whether the file begins with a gzip stream,\n   nor does it look for the end of the gzip streams to begin appending.  gzopen\n   will simply append a gzip stream to the existing file.\n\n     gzopen can be used to read a file which is not in gzip format; in this\n   case gzread will directly read from the file without decompression.  When\n   reading, this will be detected automatically by looking for the magic two-\n   byte gzip header.\n\n     gzopen returns NULL if the file could not be opened, if there was\n   insufficient memory to allocate the gzFile state, or if an invalid mode was\n   specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).\n   errno can be checked to determine if the reason gzopen failed was that the\n   file could not be opened.\n*/\n\nZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));\n/*\n     gzdopen associates a gzFile with the file descriptor fd.  File descriptors\n   are obtained from calls like open, dup, creat, pipe or fileno (if the file\n   has been previously opened with fopen).  The mode parameter is as in gzopen.\n\n     The next call of gzclose on the returned gzFile will also close the file\n   descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor\n   fd.  If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd,\n   mode);.  The duplicated descriptor should be saved to avoid a leak, since\n   gzdopen does not close fd if it fails.  If you are using fileno() to get the\n   file descriptor from a FILE *, then you will have to use dup() to avoid\n   double-close()ing the file descriptor.  Both gzclose() and fclose() will\n   close the associated file descriptor, so they need to have different file\n   descriptors.\n\n     gzdopen returns NULL if there was insufficient memory to allocate the\n   gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not\n   provided, or '+' was provided), or if fd is -1.  The file descriptor is not\n   used until the next gz* read, write, seek, or close operation, so gzdopen\n   will not detect if fd is invalid (unless fd is -1).\n*/\n\nZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size));\n/*\n     Set the internal buffer size used by this library's functions.  The\n   default buffer size is 8192 bytes.  This function must be called after\n   gzopen() or gzdopen(), and before any other calls that read or write the\n   file.  The buffer memory allocation is always deferred to the first read or\n   write.  Three times that size in buffer space is allocated.  A larger buffer\n   size of, for example, 64K or 128K bytes will noticeably increase the speed\n   of decompression (reading).\n\n     The new buffer size also affects the maximum length for gzprintf().\n\n     gzbuffer() returns 0 on success, or -1 on failure, such as being called\n   too late.\n*/\n\nZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));\n/*\n     Dynamically update the compression level or strategy.  See the description\n   of deflateInit2 for the meaning of these parameters.  Previously provided\n   data is flushed before the parameter change.\n\n     gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not\n   opened for writing, Z_ERRNO if there is an error writing the flushed data,\n   or Z_MEM_ERROR if there is a memory allocation error.\n*/\n\nZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));\n/*\n     Reads the given number of uncompressed bytes from the compressed file.  If\n   the input file is not in gzip format, gzread copies the given number of\n   bytes into the buffer directly from the file.\n\n     After reaching the end of a gzip stream in the input, gzread will continue\n   to read, looking for another gzip stream.  Any number of gzip streams may be\n   concatenated in the input file, and will all be decompressed by gzread().\n   If something other than a gzip stream is encountered after a gzip stream,\n   that remaining trailing garbage is ignored (and no error is returned).\n\n     gzread can be used to read a gzip file that is being concurrently written.\n   Upon reaching the end of the input, gzread will return with the available\n   data.  If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then\n   gzclearerr can be used to clear the end of file indicator in order to permit\n   gzread to be tried again.  Z_OK indicates that a gzip stream was completed\n   on the last gzread.  Z_BUF_ERROR indicates that the input file ended in the\n   middle of a gzip stream.  Note that gzread does not return -1 in the event\n   of an incomplete gzip stream.  This error is deferred until gzclose(), which\n   will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip\n   stream.  Alternatively, gzerror can be used before gzclose to detect this\n   case.\n\n     gzread returns the number of uncompressed bytes actually read, less than\n   len for end of file, or -1 for error.  If len is too large to fit in an int,\n   then nothing is read, -1 is returned, and the error state is set to\n   Z_STREAM_ERROR.\n*/\n\nZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems,\n                                     gzFile file));\n/*\n     Read up to nitems items of size size from file to buf, otherwise operating\n   as gzread() does.  This duplicates the interface of stdio's fread(), with\n   size_t request and return types.  If the library defines size_t, then\n   z_size_t is identical to size_t.  If not, then z_size_t is an unsigned\n   integer type that can contain a pointer.\n\n     gzfread() returns the number of full items read of size size, or zero if\n   the end of the file was reached and a full item could not be read, or if\n   there was an error.  gzerror() must be consulted if zero is returned in\n   order to determine if there was an error.  If the multiplication of size and\n   nitems overflows, i.e. the product does not fit in a z_size_t, then nothing\n   is read, zero is returned, and the error state is set to Z_STREAM_ERROR.\n\n     In the event that the end of file is reached and only a partial item is\n   available at the end, i.e. the remaining uncompressed data length is not a\n   multiple of size, then the final partial item is nevetheless read into buf\n   and the end-of-file flag is set.  The length of the partial item read is not\n   provided, but could be inferred from the result of gztell().  This behavior\n   is the same as the behavior of fread() implementations in common libraries,\n   but it prevents the direct use of gzfread() to read a concurrently written\n   file, reseting and retrying on end-of-file, when size is not 1.\n*/\n\nZEXTERN int ZEXPORT gzwrite OF((gzFile file,\n                                voidpc buf, unsigned len));\n/*\n     Writes the given number of uncompressed bytes into the compressed file.\n   gzwrite returns the number of uncompressed bytes written or 0 in case of\n   error.\n*/\n\nZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size,\n                                      z_size_t nitems, gzFile file));\n/*\n     gzfwrite() writes nitems items of size size from buf to file, duplicating\n   the interface of stdio's fwrite(), with size_t request and return types.  If\n   the library defines size_t, then z_size_t is identical to size_t.  If not,\n   then z_size_t is an unsigned integer type that can contain a pointer.\n\n     gzfwrite() returns the number of full items written of size size, or zero\n   if there was an error.  If the multiplication of size and nitems overflows,\n   i.e. the product does not fit in a z_size_t, then nothing is written, zero\n   is returned, and the error state is set to Z_STREAM_ERROR.\n*/\n\nZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...));\n/*\n     Converts, formats, and writes the arguments to the compressed file under\n   control of the format string, as in fprintf.  gzprintf returns the number of\n   uncompressed bytes actually written, or a negative zlib error code in case\n   of error.  The number of uncompressed bytes written is limited to 8191, or\n   one less than the buffer size given to gzbuffer().  The caller should assure\n   that this limit is not exceeded.  If it is exceeded, then gzprintf() will\n   return an error (0) with nothing written.  In this case, there may also be a\n   buffer overflow with unpredictable consequences, which is possible only if\n   zlib was compiled with the insecure functions sprintf() or vsprintf()\n   because the secure snprintf() or vsnprintf() functions were not available.\n   This can be determined using zlibCompileFlags().\n*/\n\nZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));\n/*\n     Writes the given null-terminated string to the compressed file, excluding\n   the terminating null character.\n\n     gzputs returns the number of characters written, or -1 in case of error.\n*/\n\nZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));\n/*\n     Reads bytes from the compressed file until len-1 characters are read, or a\n   newline character is read and transferred to buf, or an end-of-file\n   condition is encountered.  If any characters are read or if len == 1, the\n   string is terminated with a null character.  If no characters are read due\n   to an end-of-file or len < 1, then the buffer is left untouched.\n\n     gzgets returns buf which is a null-terminated string, or it returns NULL\n   for end-of-file or in case of error.  If there was an error, the contents at\n   buf are indeterminate.\n*/\n\nZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));\n/*\n     Writes c, converted to an unsigned char, into the compressed file.  gzputc\n   returns the value that was written, or -1 in case of error.\n*/\n\nZEXTERN int ZEXPORT gzgetc OF((gzFile file));\n/*\n     Reads one byte from the compressed file.  gzgetc returns this byte or -1\n   in case of end of file or error.  This is implemented as a macro for speed.\n   As such, it does not do all of the checking the other functions do.  I.e.\n   it does not check to see if file is NULL, nor whether the structure file\n   points to has been clobbered or not.\n*/\n\nZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));\n/*\n     Push one character back onto the stream to be read as the first character\n   on the next read.  At least one character of push-back is allowed.\n   gzungetc() returns the character pushed, or -1 on failure.  gzungetc() will\n   fail if c is -1, and may fail if a character has been pushed but not read\n   yet.  If gzungetc is used immediately after gzopen or gzdopen, at least the\n   output buffer size of pushed characters is allowed.  (See gzbuffer above.)\n   The pushed character will be discarded if the stream is repositioned with\n   gzseek() or gzrewind().\n*/\n\nZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));\n/*\n     Flushes all pending output into the compressed file.  The parameter flush\n   is as in the deflate() function.  The return value is the zlib error number\n   (see function gzerror below).  gzflush is only permitted when writing.\n\n     If the flush parameter is Z_FINISH, the remaining data is written and the\n   gzip stream is completed in the output.  If gzwrite() is called again, a new\n   gzip stream will be started in the output.  gzread() is able to read such\n   concatenated gzip streams.\n\n     gzflush should be called only when strictly necessary because it will\n   degrade compression if called too often.\n*/\n\n/*\nZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,\n                                   z_off_t offset, int whence));\n\n     Sets the starting position for the next gzread or gzwrite on the given\n   compressed file.  The offset represents a number of bytes in the\n   uncompressed data stream.  The whence parameter is defined as in lseek(2);\n   the value SEEK_END is not supported.\n\n     If the file is opened for reading, this function is emulated but can be\n   extremely slow.  If the file is opened for writing, only forward seeks are\n   supported; gzseek then compresses a sequence of zeroes up to the new\n   starting position.\n\n     gzseek returns the resulting offset location as measured in bytes from\n   the beginning of the uncompressed stream, or -1 in case of error, in\n   particular if the file is opened for writing and the new starting position\n   would be before the current position.\n*/\n\nZEXTERN int ZEXPORT    gzrewind OF((gzFile file));\n/*\n     Rewinds the given file. This function is supported only for reading.\n\n     gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)\n*/\n\n/*\nZEXTERN z_off_t ZEXPORT    gztell OF((gzFile file));\n\n     Returns the starting position for the next gzread or gzwrite on the given\n   compressed file.  This position represents a number of bytes in the\n   uncompressed data stream, and is zero when starting, even if appending or\n   reading a gzip stream from the middle of a file using gzdopen().\n\n     gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)\n*/\n\n/*\nZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file));\n\n     Returns the current offset in the file being read or written.  This offset\n   includes the count of bytes that precede the gzip stream, for example when\n   appending or when using gzdopen() for reading.  When reading, the offset\n   does not include as yet unused buffered input.  This information can be used\n   for a progress indicator.  On error, gzoffset() returns -1.\n*/\n\nZEXTERN int ZEXPORT gzeof OF((gzFile file));\n/*\n     Returns true (1) if the end-of-file indicator has been set while reading,\n   false (0) otherwise.  Note that the end-of-file indicator is set only if the\n   read tried to go past the end of the input, but came up short.  Therefore,\n   just like feof(), gzeof() may return false even if there is no more data to\n   read, in the event that the last read request was for the exact number of\n   bytes remaining in the input file.  This will happen if the input file size\n   is an exact multiple of the buffer size.\n\n     If gzeof() returns true, then the read functions will return no more data,\n   unless the end-of-file indicator is reset by gzclearerr() and the input file\n   has grown since the previous end of file was detected.\n*/\n\nZEXTERN int ZEXPORT gzdirect OF((gzFile file));\n/*\n     Returns true (1) if file is being copied directly while reading, or false\n   (0) if file is a gzip stream being decompressed.\n\n     If the input file is empty, gzdirect() will return true, since the input\n   does not contain a gzip stream.\n\n     If gzdirect() is used immediately after gzopen() or gzdopen() it will\n   cause buffers to be allocated to allow reading the file to determine if it\n   is a gzip file.  Therefore if gzbuffer() is used, it should be called before\n   gzdirect().\n\n     When writing, gzdirect() returns true (1) if transparent writing was\n   requested (\"wT\" for the gzopen() mode), or false (0) otherwise.  (Note:\n   gzdirect() is not needed when writing.  Transparent writing must be\n   explicitly requested, so the application already knows the answer.  When\n   linking statically, using gzdirect() will include all of the zlib code for\n   gzip file reading and decompression, which may not be desired.)\n*/\n\nZEXTERN int ZEXPORT    gzclose OF((gzFile file));\n/*\n     Flushes all pending output if necessary, closes the compressed file and\n   deallocates the (de)compression state.  Note that once file is closed, you\n   cannot call gzerror with file, since its structures have been deallocated.\n   gzclose must not be called more than once on the same file, just as free\n   must not be called more than once on the same allocation.\n\n     gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a\n   file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the\n   last read ended in the middle of a gzip stream, or Z_OK on success.\n*/\n\nZEXTERN int ZEXPORT gzclose_r OF((gzFile file));\nZEXTERN int ZEXPORT gzclose_w OF((gzFile file));\n/*\n     Same as gzclose(), but gzclose_r() is only for use when reading, and\n   gzclose_w() is only for use when writing or appending.  The advantage to\n   using these instead of gzclose() is that they avoid linking in zlib\n   compression or decompression code that is not used when only reading or only\n   writing respectively.  If gzclose() is used, then both compression and\n   decompression code will be included the application when linking to a static\n   zlib library.\n*/\n\nZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));\n/*\n     Returns the error message for the last error which occurred on the given\n   compressed file.  errnum is set to zlib error number.  If an error occurred\n   in the file system and not in the compression library, errnum is set to\n   Z_ERRNO and the application may consult errno to get the exact error code.\n\n     The application must not modify the returned string.  Future calls to\n   this function may invalidate the previously returned string.  If file is\n   closed, then the string previously returned by gzerror will no longer be\n   available.\n\n     gzerror() should be used to distinguish errors from end-of-file for those\n   functions above that do not distinguish those cases in their return values.\n*/\n\nZEXTERN void ZEXPORT gzclearerr OF((gzFile file));\n/*\n     Clears the error and end-of-file flags for file.  This is analogous to the\n   clearerr() function in stdio.  This is useful for continuing to read a gzip\n   file that is being written concurrently.\n*/\n\n#endif /* !Z_SOLO */\n\n                        /* checksum functions */\n\n/*\n     These functions are not related to compression but are exported\n   anyway because they might be useful in applications using the compression\n   library.\n*/\n\nZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));\n/*\n     Update a running Adler-32 checksum with the bytes buf[0..len-1] and\n   return the updated checksum.  If buf is Z_NULL, this function returns the\n   required initial value for the checksum.\n\n     An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed\n   much faster.\n\n   Usage example:\n\n     uLong adler = adler32(0L, Z_NULL, 0);\n\n     while (read_buffer(buffer, length) != EOF) {\n       adler = adler32(adler, buffer, length);\n     }\n     if (adler != original_adler) error();\n*/\n\nZEXTERN uLong ZEXPORT adler32_z OF((uLong adler, const Bytef *buf,\n                                    z_size_t len));\n/*\n     Same as adler32(), but with a size_t length.\n*/\n\n/*\nZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,\n                                          z_off_t len2));\n\n     Combine two Adler-32 checksums into one.  For two sequences of bytes, seq1\n   and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for\n   each, adler1 and adler2.  adler32_combine() returns the Adler-32 checksum of\n   seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.  Note\n   that the z_off_t type (like off_t) is a signed integer.  If len2 is\n   negative, the result has no meaning or utility.\n*/\n\nZEXTERN uLong ZEXPORT crc32   OF((uLong crc, const Bytef *buf, uInt len));\n/*\n     Update a running CRC-32 with the bytes buf[0..len-1] and return the\n   updated CRC-32.  If buf is Z_NULL, this function returns the required\n   initial value for the crc.  Pre- and post-conditioning (one's complement) is\n   performed within this function so it shouldn't be done by the application.\n\n   Usage example:\n\n     uLong crc = crc32(0L, Z_NULL, 0);\n\n     while (read_buffer(buffer, length) != EOF) {\n       crc = crc32(crc, buffer, length);\n     }\n     if (crc != original_crc) error();\n*/\n\nZEXTERN uLong ZEXPORT crc32_z OF((uLong adler, const Bytef *buf,\n                                  z_size_t len));\n/*\n     Same as crc32(), but with a size_t length.\n*/\n\n/*\nZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));\n\n     Combine two CRC-32 check values into one.  For two sequences of bytes,\n   seq1 and seq2 with lengths len1 and len2, CRC-32 check values were\n   calculated for each, crc1 and crc2.  crc32_combine() returns the CRC-32\n   check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and\n   len2.\n*/\n\n\n                        /* various hacks, don't look :) */\n\n/* deflateInit and inflateInit are macros to allow checking the zlib version\n * and the compiler's view of z_stream:\n */\nZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,\n                                     const char *version, int stream_size));\nZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,\n                                     const char *version, int stream_size));\nZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int  level, int  method,\n                                      int windowBits, int memLevel,\n                                      int strategy, const char *version,\n                                      int stream_size));\nZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int  windowBits,\n                                      const char *version, int stream_size));\nZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,\n                                         unsigned char FAR *window,\n                                         const char *version,\n                                         int stream_size));\n#ifdef Z_PREFIX_SET\n#  define z_deflateInit(strm, level) \\\n          deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream))\n#  define z_inflateInit(strm) \\\n          inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream))\n#  define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \\\n          deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\\\n                        (strategy), ZLIB_VERSION, (int)sizeof(z_stream))\n#  define z_inflateInit2(strm, windowBits) \\\n          inflateInit2_((strm), (windowBits), ZLIB_VERSION, \\\n                        (int)sizeof(z_stream))\n#  define z_inflateBackInit(strm, windowBits, window) \\\n          inflateBackInit_((strm), (windowBits), (window), \\\n                           ZLIB_VERSION, (int)sizeof(z_stream))\n#else\n#  define deflateInit(strm, level) \\\n          deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream))\n#  define inflateInit(strm) \\\n          inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream))\n#  define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \\\n          deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\\\n                        (strategy), ZLIB_VERSION, (int)sizeof(z_stream))\n#  define inflateInit2(strm, windowBits) \\\n          inflateInit2_((strm), (windowBits), ZLIB_VERSION, \\\n                        (int)sizeof(z_stream))\n#  define inflateBackInit(strm, windowBits, window) \\\n          inflateBackInit_((strm), (windowBits), (window), \\\n                           ZLIB_VERSION, (int)sizeof(z_stream))\n#endif\n\n#ifndef Z_SOLO\n\n/* gzgetc() macro and its supporting function and exposed data structure.  Note\n * that the real internal state is much larger than the exposed structure.\n * This abbreviated structure exposes just enough for the gzgetc() macro.  The\n * user should not mess with these exposed elements, since their names or\n * behavior could change in the future, perhaps even capriciously.  They can\n * only be used by the gzgetc() macro.  You have been warned.\n */\nstruct gzFile_s {\n    unsigned have;\n    unsigned char *next;\n    z_off64_t pos;\n};\nZEXTERN int ZEXPORT gzgetc_ OF((gzFile file));  /* backward compatibility */\n#ifdef Z_PREFIX_SET\n#  undef z_gzgetc\n#  define z_gzgetc(g) \\\n          ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g))\n#else\n#  define gzgetc(g) \\\n          ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g))\n#endif\n\n/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or\n * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if\n * both are true, the application gets the *64 functions, and the regular\n * functions are changed to 64 bits) -- in case these are set on systems\n * without large file support, _LFS64_LARGEFILE must also be true\n */\n#ifdef Z_LARGE64\n   ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));\n   ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\n   ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));\n   ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));\n   ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t));\n   ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t));\n#endif\n\n#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64)\n#  ifdef Z_PREFIX_SET\n#    define z_gzopen z_gzopen64\n#    define z_gzseek z_gzseek64\n#    define z_gztell z_gztell64\n#    define z_gzoffset z_gzoffset64\n#    define z_adler32_combine z_adler32_combine64\n#    define z_crc32_combine z_crc32_combine64\n#  else\n#    define gzopen gzopen64\n#    define gzseek gzseek64\n#    define gztell gztell64\n#    define gzoffset gzoffset64\n#    define adler32_combine adler32_combine64\n#    define crc32_combine crc32_combine64\n#  endif\n#  ifndef Z_LARGE64\n     ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));\n     ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int));\n     ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile));\n     ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile));\n     ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));\n     ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));\n#  endif\n#else\n   ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *));\n   ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int));\n   ZEXTERN z_off_t ZEXPORT gztell OF((gzFile));\n   ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile));\n   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));\n   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));\n#endif\n\n#else /* Z_SOLO */\n\n   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));\n   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));\n\n#endif /* !Z_SOLO */\n\n/* undocumented functions */\nZEXTERN const char   * ZEXPORT zError           OF((int));\nZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp));\nZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table    OF((void));\nZEXTERN int            ZEXPORT inflateUndermine OF((z_streamp, int));\nZEXTERN int            ZEXPORT inflateValidate OF((z_streamp, int));\nZEXTERN unsigned long  ZEXPORT inflateCodesUsed OF ((z_streamp));\nZEXTERN int            ZEXPORT inflateResetKeep OF((z_streamp));\nZEXTERN int            ZEXPORT deflateResetKeep OF((z_streamp));\n#if (defined(_WIN32) || defined(__CYGWIN__)) && !defined(Z_SOLO)\nZEXTERN gzFile         ZEXPORT gzopen_w OF((const wchar_t *path,\n                                            const char *mode));\n#endif\n#if defined(STDC) || defined(Z_HAVE_STDARG_H)\n#  ifndef Z_SOLO\nZEXTERN int            ZEXPORTVA gzvprintf Z_ARG((gzFile file,\n                                                  const char *format,\n                                                  va_list va));\n#  endif\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* ZLIB_H */\n"
  },
  {
    "path": "jsb_build/websockets/zlib/zutil.c",
    "content": "/* zutil.c -- target dependent utility functions for the compression library\n * Copyright (C) 1995-2017 Jean-loup Gailly\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* @(#) $Id$ */\n\n#include \"zutil.h\"\n#ifndef Z_SOLO\n#  include \"gzguts.h\"\n#endif\n\nz_const char * const z_errmsg[10] = {\n    (z_const char *)\"need dictionary\",     /* Z_NEED_DICT       2  */\n    (z_const char *)\"stream end\",          /* Z_STREAM_END      1  */\n    (z_const char *)\"\",                    /* Z_OK              0  */\n    (z_const char *)\"file error\",          /* Z_ERRNO         (-1) */\n    (z_const char *)\"stream error\",        /* Z_STREAM_ERROR  (-2) */\n    (z_const char *)\"data error\",          /* Z_DATA_ERROR    (-3) */\n    (z_const char *)\"insufficient memory\", /* Z_MEM_ERROR     (-4) */\n    (z_const char *)\"buffer error\",        /* Z_BUF_ERROR     (-5) */\n    (z_const char *)\"incompatible version\",/* Z_VERSION_ERROR (-6) */\n    (z_const char *)\"\"\n};\n\n\nconst char * ZEXPORT zlibVersion()\n{\n    return ZLIB_VERSION;\n}\n\nuLong ZEXPORT zlibCompileFlags()\n{\n    uLong flags;\n\n    flags = 0;\n    switch ((int)(sizeof(uInt))) {\n    case 2:     break;\n    case 4:     flags += 1;     break;\n    case 8:     flags += 2;     break;\n    default:    flags += 3;\n    }\n    switch ((int)(sizeof(uLong))) {\n    case 2:     break;\n    case 4:     flags += 1 << 2;        break;\n    case 8:     flags += 2 << 2;        break;\n    default:    flags += 3 << 2;\n    }\n    switch ((int)(sizeof(voidpf))) {\n    case 2:     break;\n    case 4:     flags += 1 << 4;        break;\n    case 8:     flags += 2 << 4;        break;\n    default:    flags += 3 << 4;\n    }\n    switch ((int)(sizeof(z_off_t))) {\n    case 2:     break;\n    case 4:     flags += 1 << 6;        break;\n    case 8:     flags += 2 << 6;        break;\n    default:    flags += 3 << 6;\n    }\n#ifdef ZLIB_DEBUG\n    flags += 1 << 8;\n#endif\n#if defined(ASMV) || defined(ASMINF)\n    flags += 1 << 9;\n#endif\n#ifdef ZLIB_WINAPI\n    flags += 1 << 10;\n#endif\n#ifdef BUILDFIXED\n    flags += 1 << 12;\n#endif\n#ifdef DYNAMIC_CRC_TABLE\n    flags += 1 << 13;\n#endif\n#ifdef NO_GZCOMPRESS\n    flags += 1L << 16;\n#endif\n#ifdef NO_GZIP\n    flags += 1L << 17;\n#endif\n#ifdef PKZIP_BUG_WORKAROUND\n    flags += 1L << 20;\n#endif\n#ifdef FASTEST\n    flags += 1L << 21;\n#endif\n#if defined(STDC) || defined(Z_HAVE_STDARG_H)\n#  ifdef NO_vsnprintf\n    flags += 1L << 25;\n#    ifdef HAS_vsprintf_void\n    flags += 1L << 26;\n#    endif\n#  else\n#    ifdef HAS_vsnprintf_void\n    flags += 1L << 26;\n#    endif\n#  endif\n#else\n    flags += 1L << 24;\n#  ifdef NO_snprintf\n    flags += 1L << 25;\n#    ifdef HAS_sprintf_void\n    flags += 1L << 26;\n#    endif\n#  else\n#    ifdef HAS_snprintf_void\n    flags += 1L << 26;\n#    endif\n#  endif\n#endif\n    return flags;\n}\n\n#ifdef ZLIB_DEBUG\n#include <stdlib.h>\n#  ifndef verbose\n#    define verbose 0\n#  endif\nint ZLIB_INTERNAL z_verbose = verbose;\n\nvoid ZLIB_INTERNAL z_error (m)\n    char *m;\n{\n    fprintf(stderr, \"%s\\n\", m);\n    exit(1);\n}\n#endif\n\n/* exported to allow conversion of error code to string for compress() and\n * uncompress()\n */\nconst char * ZEXPORT zError(err)\n    int err;\n{\n    return ERR_MSG(err);\n}\n\n#if defined(_WIN32_WCE)\n    /* The Microsoft C Run-Time Library for Windows CE doesn't have\n     * errno.  We define it as a global variable to simplify porting.\n     * Its value is always 0 and should not be used.\n     */\n    int errno = 0;\n#endif\n\n#ifndef HAVE_MEMCPY\n\nvoid ZLIB_INTERNAL zmemcpy(dest, source, len)\n    Bytef* dest;\n    const Bytef* source;\n    uInt  len;\n{\n    if (len == 0) return;\n    do {\n        *dest++ = *source++; /* ??? to be unrolled */\n    } while (--len != 0);\n}\n\nint ZLIB_INTERNAL zmemcmp(s1, s2, len)\n    const Bytef* s1;\n    const Bytef* s2;\n    uInt  len;\n{\n    uInt j;\n\n    for (j = 0; j < len; j++) {\n        if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;\n    }\n    return 0;\n}\n\nvoid ZLIB_INTERNAL zmemzero(dest, len)\n    Bytef* dest;\n    uInt  len;\n{\n    if (len == 0) return;\n    do {\n        *dest++ = 0;  /* ??? to be unrolled */\n    } while (--len != 0);\n}\n#endif\n\n#ifndef Z_SOLO\n\n#ifdef SYS16BIT\n\n#ifdef __TURBOC__\n/* Turbo C in 16-bit mode */\n\n#  define MY_ZCALLOC\n\n/* Turbo C malloc() does not allow dynamic allocation of 64K bytes\n * and farmalloc(64K) returns a pointer with an offset of 8, so we\n * must fix the pointer. Warning: the pointer must be put back to its\n * original form in order to free it, use zcfree().\n */\n\n#define MAX_PTR 10\n/* 10*64K = 640K */\n\nlocal int next_ptr = 0;\n\ntypedef struct ptr_table_s {\n    voidpf org_ptr;\n    voidpf new_ptr;\n} ptr_table;\n\nlocal ptr_table table[MAX_PTR];\n/* This table is used to remember the original form of pointers\n * to large buffers (64K). Such pointers are normalized with a zero offset.\n * Since MSDOS is not a preemptive multitasking OS, this table is not\n * protected from concurrent access. This hack doesn't work anyway on\n * a protected system like OS/2. Use Microsoft C instead.\n */\n\nvoidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size)\n{\n    voidpf buf;\n    ulg bsize = (ulg)items*size;\n\n    (void)opaque;\n\n    /* If we allocate less than 65520 bytes, we assume that farmalloc\n     * will return a usable pointer which doesn't have to be normalized.\n     */\n    if (bsize < 65520L) {\n        buf = farmalloc(bsize);\n        if (*(ush*)&buf != 0) return buf;\n    } else {\n        buf = farmalloc(bsize + 16L);\n    }\n    if (buf == NULL || next_ptr >= MAX_PTR) return NULL;\n    table[next_ptr].org_ptr = buf;\n\n    /* Normalize the pointer to seg:0 */\n    *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;\n    *(ush*)&buf = 0;\n    table[next_ptr++].new_ptr = buf;\n    return buf;\n}\n\nvoid ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)\n{\n    int n;\n\n    (void)opaque;\n\n    if (*(ush*)&ptr != 0) { /* object < 64K */\n        farfree(ptr);\n        return;\n    }\n    /* Find the original pointer */\n    for (n = 0; n < next_ptr; n++) {\n        if (ptr != table[n].new_ptr) continue;\n\n        farfree(table[n].org_ptr);\n        while (++n < next_ptr) {\n            table[n-1] = table[n];\n        }\n        next_ptr--;\n        return;\n    }\n    Assert(0, \"zcfree: ptr not found\");\n}\n\n#endif /* __TURBOC__ */\n\n\n#ifdef M_I86\n/* Microsoft C in 16-bit mode */\n\n#  define MY_ZCALLOC\n\n#if (!defined(_MSC_VER) || (_MSC_VER <= 600))\n#  define _halloc  halloc\n#  define _hfree   hfree\n#endif\n\nvoidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size)\n{\n    (void)opaque;\n    return _halloc((long)items, size);\n}\n\nvoid ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)\n{\n    (void)opaque;\n    _hfree(ptr);\n}\n\n#endif /* M_I86 */\n\n#endif /* SYS16BIT */\n\n\n#ifndef MY_ZCALLOC /* Any system without a special alloc function */\n\n#ifndef STDC\nextern voidp  malloc OF((uInt size));\nextern voidp  calloc OF((uInt items, uInt size));\nextern void   free   OF((voidpf ptr));\n#endif\n\nvoidpf ZLIB_INTERNAL zcalloc (opaque, items, size)\n    voidpf opaque;\n    unsigned items;\n    unsigned size;\n{\n    (void)opaque;\n    return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :\n                              (voidpf)calloc(items, size);\n}\n\nvoid ZLIB_INTERNAL zcfree (opaque, ptr)\n    voidpf opaque;\n    voidpf ptr;\n{\n    (void)opaque;\n    free(ptr);\n}\n\n#endif /* MY_ZCALLOC */\n\n#endif /* !Z_SOLO */\n"
  },
  {
    "path": "jsb_build/websockets/zlib/zutil.h",
    "content": "/* zutil.h -- internal interface and configuration of the compression library\n * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* WARNING: this file should *not* be used by applications. It is\n   part of the implementation of the compression library and is\n   subject to change. Applications should only use zlib.h.\n */\n\n/* @(#) $Id$ */\n\n#ifndef ZUTIL_H\n#define ZUTIL_H\n\n#ifdef HAVE_HIDDEN\n#  define ZLIB_INTERNAL __attribute__((visibility (\"hidden\")))\n#else\n#  define ZLIB_INTERNAL\n#endif\n\n#include \"zlib.h\"\n\n#if defined(STDC) && !defined(Z_SOLO)\n#  if !(defined(_WIN32_WCE) && defined(_MSC_VER))\n#    include <stddef.h>\n#  endif\n#  include <string.h>\n#  include <stdlib.h>\n#endif\n\n#ifdef Z_SOLO\n   typedef long ptrdiff_t;  /* guess -- will be caught if guess is wrong */\n#endif\n\n#ifndef local\n#  define local static\n#endif\n/* since \"static\" is used to mean two completely different things in C, we\n   define \"local\" for the non-static meaning of \"static\", for readability\n   (compile with -Dlocal if your debugger can't find static symbols) */\n\ntypedef unsigned char  uch;\ntypedef uch FAR uchf;\ntypedef unsigned short ush;\ntypedef ush FAR ushf;\ntypedef unsigned long  ulg;\n\nextern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */\n/* (size given to avoid silly warnings with Visual C++) */\n\n#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]\n\n#define ERR_RETURN(strm,err) \\\n  return (strm->msg = ERR_MSG(err), (err))\n/* To be used only when the state is known to be valid */\n\n        /* common constants */\n\n#ifndef DEF_WBITS\n#  define DEF_WBITS MAX_WBITS\n#endif\n/* default windowBits for decompression. MAX_WBITS is for compression only */\n\n#if MAX_MEM_LEVEL >= 8\n#  define DEF_MEM_LEVEL 8\n#else\n#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL\n#endif\n/* default memLevel */\n\n#define STORED_BLOCK 0\n#define STATIC_TREES 1\n#define DYN_TREES    2\n/* The three kinds of block type */\n\n#define MIN_MATCH  3\n#define MAX_MATCH  258\n/* The minimum and maximum match lengths */\n\n#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */\n\n        /* target dependencies */\n\n#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))\n#  define OS_CODE  0x00\n#  ifndef Z_SOLO\n#    if defined(__TURBOC__) || defined(__BORLANDC__)\n#      if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))\n         /* Allow compilation with ANSI keywords only enabled */\n         void _Cdecl farfree( void *block );\n         void *_Cdecl farmalloc( unsigned long nbytes );\n#      else\n#        include <alloc.h>\n#      endif\n#    else /* MSC or DJGPP */\n#      include <malloc.h>\n#    endif\n#  endif\n#endif\n\n#ifdef AMIGA\n#  define OS_CODE  1\n#endif\n\n#if defined(VAXC) || defined(VMS)\n#  define OS_CODE  2\n#  define F_OPEN(name, mode) \\\n     fopen((name), (mode), \"mbc=60\", \"ctx=stm\", \"rfm=fix\", \"mrs=512\")\n#endif\n\n#ifdef __370__\n#  if __TARGET_LIB__ < 0x20000000\n#    define OS_CODE 4\n#  elif __TARGET_LIB__ < 0x40000000\n#    define OS_CODE 11\n#  else\n#    define OS_CODE 8\n#  endif\n#endif\n\n#if defined(ATARI) || defined(atarist)\n#  define OS_CODE  5\n#endif\n\n#ifdef OS2\n#  define OS_CODE  6\n#  if defined(M_I86) && !defined(Z_SOLO)\n#    include <malloc.h>\n#  endif\n#endif\n\n#if defined(MACOS) || defined(TARGET_OS_MAC)\n#  define OS_CODE  7\n#  ifndef Z_SOLO\n#    if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os\n#      include <unix.h> /* for fdopen */\n#    else\n#      ifndef fdopen\n#        define fdopen(fd,mode) NULL /* No fdopen() */\n#      endif\n#    endif\n#  endif\n#endif\n\n#ifdef __acorn\n#  define OS_CODE 13\n#endif\n\n#if defined(WIN32) && !defined(__CYGWIN__)\n#  define OS_CODE  10\n#endif\n\n#ifdef _BEOS_\n#  define OS_CODE  16\n#endif\n\n#ifdef __TOS_OS400__\n#  define OS_CODE 18\n#endif\n\n#ifdef __APPLE__\n#  define OS_CODE 19\n#endif\n\n#if defined(_BEOS_) || defined(RISCOS)\n#  define fdopen(fd,mode) NULL /* No fdopen() */\n#endif\n\n#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX\n#  if defined(_WIN32_WCE)\n#    define fdopen(fd,mode) NULL /* No fdopen() */\n#    ifndef _PTRDIFF_T_DEFINED\n       typedef int ptrdiff_t;\n#      define _PTRDIFF_T_DEFINED\n#    endif\n#  else\n#    define fdopen(fd,type)  _fdopen(fd,type)\n#  endif\n#endif\n\n#if defined(__BORLANDC__) && !defined(MSDOS)\n  #pragma warn -8004\n  #pragma warn -8008\n  #pragma warn -8066\n#endif\n\n/* provide prototypes for these when building zlib without LFS */\n#if !defined(_WIN32) && \\\n    (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0)\n    ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));\n    ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));\n#endif\n\n        /* common defaults */\n\n#ifndef OS_CODE\n#  define OS_CODE  3     /* assume Unix */\n#endif\n\n#ifndef F_OPEN\n#  define F_OPEN(name, mode) fopen((name), (mode))\n#endif\n\n         /* functions */\n\n#if defined(pyr) || defined(Z_SOLO)\n#  define NO_MEMCPY\n#endif\n#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)\n /* Use our own functions for small and medium model with MSC <= 5.0.\n  * You may have to use the same strategy for Borland C (untested).\n  * The __SC__ check is for Symantec.\n  */\n#  define NO_MEMCPY\n#endif\n#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)\n#  define HAVE_MEMCPY\n#endif\n#ifdef HAVE_MEMCPY\n#  ifdef SMALL_MEDIUM /* MSDOS small or medium model */\n#    define zmemcpy _fmemcpy\n#    define zmemcmp _fmemcmp\n#    define zmemzero(dest, len) _fmemset(dest, 0, len)\n#  else\n#    define zmemcpy memcpy\n#    define zmemcmp memcmp\n#    define zmemzero(dest, len) memset(dest, 0, len)\n#  endif\n#else\n   void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));\n   int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));\n   void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len));\n#endif\n\n/* Diagnostic functions */\n#ifdef ZLIB_DEBUG\n#  include <stdio.h>\n   extern int ZLIB_INTERNAL z_verbose;\n   extern void ZLIB_INTERNAL z_error OF((char *m));\n#  define Assert(cond,msg) {if(!(cond)) z_error(msg);}\n#  define Trace(x) {if (z_verbose>=0) fprintf x ;}\n#  define Tracev(x) {if (z_verbose>0) fprintf x ;}\n#  define Tracevv(x) {if (z_verbose>1) fprintf x ;}\n#  define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}\n#  define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}\n#else\n#  define Assert(cond,msg)\n#  define Trace(x)\n#  define Tracev(x)\n#  define Tracevv(x)\n#  define Tracec(c,x)\n#  define Tracecv(c,x)\n#endif\n\n#ifndef Z_SOLO\n   voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items,\n                                    unsigned size));\n   void ZLIB_INTERNAL zcfree  OF((voidpf opaque, voidpf ptr));\n#endif\n\n#define ZALLOC(strm, items, size) \\\n           (*((strm)->zalloc))((strm)->opaque, (items), (size))\n#define ZFREE(strm, addr)  (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))\n#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}\n\n/* Reverse the bytes in a 32-bit value */\n#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \\\n                    (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))\n\n#endif /* ZUTIL_H */\n"
  },
  {
    "path": "package.json",
    "content": "{\r\n    \"dependencies\": {\r\n        \"@types/matter-js\": \"^0.17.7\",\r\n        \"matter-js\": \"^0.18.0\",\r\n        \"protobufjs\": \"^6.11.3\"\r\n    },\r\n    \"devDependencies\": {\r\n        \"@babel/plugin-proposal-optional-chaining\": \"^7.10.4\",\r\n        \"@types/node\": \"^10.17.27\",\r\n        \"@types/protobufjs\": \"^6.0.0\",\r\n        \"awesome-typescript-loader\": \"^5.2.1\",\r\n        \"babel-core\": \"^6.26.3\",\r\n        \"babel-preset-env\": \"^1.7.0\",\r\n        \"clean-webpack-plugin\": \"^3.0.0\",\r\n        \"copy-webpack-plugin\": \"^6.0.3\",\r\n        \"gulp\": \"^4.0.2\",\r\n        \"gulp-babel\": \"^7.0.1\",\r\n        \"gulp-clean\": \"^0.4.0\",\r\n        \"gulp-cli\": \"^2.3.0\",\r\n        \"gulp-concat\": \"^2.6.1\",\r\n        \"gulp-rename\": \"^2.0.0\",\r\n        \"gulp-uglify\": \"^3.0.0\",\r\n        \"html-webpack-plugin\": \"^4.3.0\",\r\n        \"run-sequence\": \"^2.2.1\",\r\n        \"ts-loader\": \"^8.0.0\",\r\n        \"typescript\": \"^3.9.6\",\r\n        \"uglify-es\": \"^3.3.9\",\r\n        \"webpack\": \"^4.43.0\",\r\n        \"webpack-cli\": \"^3.3.12\",\r\n        \"webpack-dev-server\": \"^4.13.1\",\r\n        \"xlsx\": \"^0.17.0\"\r\n    },\r\n    \"scripts\": {\r\n        \"pack-res\": \"gulp\",\r\n        \"watch\": \"webpack --watch\",\r\n        \"dev\": \"webpack-dev-server --open\",\r\n        \"publish\": \"webpack\",\r\n        \"build\": \"webpack\"\r\n    }\r\n}\r\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\r\n    \"compilerOptions\": {\r\n        \"newLine\": \"CRLF\",\r\n        // \"module\": \"ESNext\",\r\n        \"module\": \"commonjs\",\r\n        \"target\": \"ES2018\",\r\n        \"sourceRoot\": \"\",\r\n        \"outDir\": \"Scripts/out\",\r\n        // \"outFile\": \"Scripts/out/code.js\",\r\n        \"typeRoots\": [\r\n            \"Packages/cc.starlessnight.unity-jsb/Typings\",\r\n            \"Assets/Generated/Typings\",\r\n            \"Scripts/types\"\r\n        ],\r\n        \"moduleResolution\": \"node\",\r\n        \"types\": [\r\n            \"node\"\r\n        ],\r\n        // \"listEmittedFiles\": true,\r\n        \"experimentalDecorators\": true,\r\n        \"noImplicitAny\": false,\r\n        // use 'skipLibCheck' if compilation reports error TS2300 on Promise/Proxy type definition\r\n        // or just ignore the errors (the typescript source will still be compiled into js)\r\n        // \"skipLibCheck\": true,\r\n        // \"strictNullChecks\": true,\r\n        \"allowJs\": true,\r\n        \"jsx\": \"react\",\r\n        \"jsxFactory\": \"JSX.createElement\",\r\n        // \"jsxFragmentFactory\": \"React.Fragment\",\r\n        // \"jsxImportSource\": \"react-jsb\",\r\n        \"inlineSourceMap\": false,\r\n        \"sourceMap\": true\r\n    },\r\n    \"compileOnSave\": true,\r\n    \"include\": [\r\n        \"Packages/cc.starlessnight.unity-jsb/Typings/**/*.ts\",\r\n        \"Assets/Generated/**/*.ts\",\r\n        \"Scripts/types/**/*.ts\",\r\n        \"Scripts/src/**/*.ts\",\r\n        \"Scripts/src/**/*.tsx\"\r\n    ],\r\n    \"exclude\": [\r\n        \"Assets/Examples/Scripts/out/**/*\"\r\n    ]\r\n}"
  },
  {
    "path": "webpack.config.js",
    "content": "\r\nconst path = require('path');\r\nconst { CleanWebpackPlugin } = require('clean-webpack-plugin');\r\nconst CopyWebpackPlugin = require('copy-webpack-plugin');\r\nconst webpack = require('webpack');\r\nconst HtmlWebpackPlugin = require('html-webpack-plugin');\r\nconst fs = require('fs');\r\n\r\nconst jsbm = JSON.parse(fs.readFileSync('jsb-modules.json'));\r\nlet external_modules = {};\r\nfor (let m of jsbm.modules) {\r\n    external_modules[m] = `commonjs2 ${m}`;\r\n}\r\nexternal_modules['jsb'] = 'commonjs2 jsb';\r\n\r\nmodule.exports = {\r\n    entry: {\r\n        example_main: './Scripts/src/example_main.ts'\r\n    },\r\n    output: {\r\n        // filename: 'main.js',\r\n        filename: '[name].js',\r\n        path: path.resolve(__dirname, './Scripts/dist')\r\n    },\r\n    externals: external_modules,\r\n    module: {\r\n        rules: [{\r\n            test: /\\.tsx?$/,\r\n            parser: { amd: false, system: false },\r\n            use: 'ts-loader',\r\n            // use: 'awesome-typescript-loader', \r\n            exclude: /node_modules/\r\n        }]\r\n    },\r\n    resolve: {\r\n        extensions: ['.tsx', '.ts', '.js']\r\n    },\r\n    devtool: 'inline-source-map',\r\n    devServer: {\r\n        contentBase: './Scripts/dist',\r\n        port: 8183,\r\n        hot: true\r\n    },\r\n    mode: 'development',\r\n    plugins: [\r\n        new CleanWebpackPlugin(),\r\n        new CopyWebpackPlugin({\r\n            patterns: [\r\n                {\r\n                    from: path.resolve(__dirname, './Scripts/dist'),\r\n                    to: path.resolve(__dirname, './Assets/Examples/Resources/dist'),\r\n                    transformPath: (targetPath, absolutePath) => {\r\n                        return targetPath + \".txt\";\r\n                    },\r\n                    toType: \"dir\"\r\n                },\r\n                {\r\n                    from: path.resolve(__dirname, './Scripts/protogen'),\r\n                    to: path.resolve(__dirname, './Assets/Examples/Resources/protogen'),\r\n                    transformPath: (targetPath, absolutePath) => {\r\n                        return targetPath + \".txt\";\r\n                    },\r\n                    toType: \"dir\"\r\n                },\r\n                {\r\n                    from: path.resolve(__dirname, './Scripts/config'),\r\n                    to: path.resolve(__dirname, './Assets/Examples/Resources/config'),\r\n                    transformPath: (targetPath, absolutePath) => {\r\n                        return targetPath + \".txt\";\r\n                    },\r\n                    toType: \"dir\"\r\n                }\r\n            ]\r\n        }),\r\n        // new webpack.HotModuleReplacementPlugin()\r\n        new HtmlWebpackPlugin({ template: './Scripts/src/index.html' })\r\n    ]\r\n}\r\n"
  },
  {
    "path": "xmldoc.bat",
    "content": "@ECHO OFF\r\nSETLOCAL\r\n\r\nSET vswherePath=%ProgramFiles(x86)%\\Microsoft Visual Studio\\Installer\\vswhere.exe\r\nIF NOT EXIST \"%vswherePath%\" GOTO :ERROR\r\n\r\nFOR /F \"tokens=*\" %%i IN (\t'\r\n\t  \"%vswherePath%\" -latest -prerelease -products * ^\r\n        -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 ^\r\n        -property installationPath'\r\n      ) DO SET vsBase=%%i\r\n\r\nIF \"%vsBase%\"==\"\" GOTO :ERROR\r\n\r\nCALL \"%vsBase%\\vc\\Auxiliary\\Build\\vcvars64.bat\" > NUL\r\n\r\nfor /f \"delims=\" %%i in (\"%cd%\") do set folder=%%~ni\r\nmsbuild %folder%.sln /p:Configuration=Debug /p:Platform=\"Any CPU\" /p:GenerateDocumentationFile=true\r\n\r\nEXIT /B 0\r\n\r\nENDLOCAL\r\n\r\n:ERROR\r\n    EXIT /B 1\r\n"
  }
]